summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRémi Verschelde <rverschelde@gmail.com>2017-03-05 16:44:50 +0100
committerRémi Verschelde <rverschelde@gmail.com>2017-03-05 16:44:50 +0100
commit5dbf1809c6e3e905b94b8764e99491e608122261 (patch)
tree5e5a5360db15d86d59ec8c6e4f7eb511388c5a9a
parent45438e9918d421b244bfd7776a30e67dc7f2d3e3 (diff)
A Whole New World (clang-format edition)
I can show you the code Pretty, with proper whitespace Tell me, coder, now when did You last write readable code? I can open your eyes Make you see your bad indent Force you to respect the style The core devs agreed upon A whole new world A new fantastic code format A de facto standard With some sugar Enforced with clang-format A whole new world A dazzling style we all dreamed of And when we read it through It's crystal clear That now we're in a whole new world of code
-rw-r--r--core/allocators.h144
-rw-r--r--core/array.cpp119
-rw-r--r--core/array.h40
-rw-r--r--core/bind/core_bind.cpp1513
-rw-r--r--core/bind/core_bind.h305
-rw-r--r--core/class_db.cpp820
-rw-r--r--core/class_db.h282
-rw-r--r--core/color.cpp291
-rw-r--r--core/color.h87
-rw-r--r--core/command_queue_mt.cpp36
-rw-r--r--core/command_queue_mt.h914
-rw-r--r--core/compressed_translation.cpp564
-rw-r--r--core/compressed_translation.h23
-rw-r--r--core/core_string_names.cpp26
-rw-r--r--core/core_string_names.h16
-rw-r--r--core/dictionary.cpp132
-rw-r--r--core/dictionary.h36
-rw-r--r--core/dvector.cpp38
-rw-r--r--core/dvector.h367
-rw-r--r--core/engine.cpp44
-rw-r--r--core/engine.h8
-rw-r--r--core/error_list.h23
-rw-r--r--core/error_macros.cpp40
-rw-r--r--core/error_macros.h209
-rw-r--r--core/event_queue.cpp147
-rw-r--r--core/event_queue.h11
-rw-r--r--core/func_ref.cpp37
-rw-r--r--core/func_ref.h11
-rw-r--r--core/global_config.cpp610
-rw-r--r--core/global_config.h88
-rw-r--r--core/global_constants.cpp990
-rw-r--r--core/global_constants.h2
-rw-r--r--core/hash_map.h342
-rw-r--r--core/hashfuncs.h61
-rw-r--r--core/helper/math_fieldwise.cpp15
-rw-r--r--core/helper/math_fieldwise.h2
-rw-r--r--core/helper/value_evaluator.h3
-rw-r--r--core/image.cpp2032
-rw-r--r--core/image.h85
-rw-r--r--core/input_map.cpp225
-rw-r--r--core/input_map.h35
-rw-r--r--core/int_types.h30
-rw-r--r--core/io/compression.cpp90
-rw-r--r--core/io/compression.h13
-rw-r--r--core/io/config_file.cpp128
-rw-r--r--core/io/config_file.h27
-rw-r--r--core/io/file_access_buffered.cpp10
-rw-r--r--core/io/file_access_buffered.h10
-rw-r--r--core/io/file_access_buffered_fa.h26
-rw-r--r--core/io/file_access_compressed.cpp320
-rw-r--r--core/io/file_access_compressed.h19
-rw-r--r--core/io/file_access_encrypted.cpp204
-rw-r--r--core/io/file_access_encrypted.h23
-rw-r--r--core/io/file_access_memory.cpp28
-rw-r--r--core/io/file_access_memory.h19
-rw-r--r--core/io/file_access_network.cpp324
-rw-r--r--core/io/file_access_network.h34
-rw-r--r--core/io/file_access_pack.cpp237
-rw-r--r--core/io/file_access_pack.h83
-rw-r--r--core/io/file_access_zip.cpp94
-rw-r--r--core/io/file_access_zip.h36
-rw-r--r--core/io/http_client.cpp637
-rw-r--r--core/io/http_client.h26
-rw-r--r--core/io/image_loader.cpp44
-rw-r--r--core/io/image_loader.h29
-rw-r--r--core/io/ip.cpp154
-rw-r--r--core/io/ip.h38
-rw-r--r--core/io/ip_address.cpp74
-rw-r--r--core/io/ip_address.h23
-rw-r--r--core/io/json.cpp299
-rw-r--r--core/io/json.h17
-rw-r--r--core/io/marshalls.cpp1117
-rw-r--r--core/io/marshalls.h80
-rw-r--r--core/io/networked_multiplayer_peer.cpp46
-rw-r--r--core/io/networked_multiplayer_peer.h32
-rw-r--r--core/io/packet_peer.cpp141
-rw-r--r--core/io/packet_peer.h37
-rw-r--r--core/io/packet_peer_udp.cpp32
-rw-r--r--core/io/packet_peer_udp.h26
-rw-r--r--core/io/pck_packer.cpp26
-rw-r--r--core/io/pck_packer.h7
-rw-r--r--core/io/resource_format_binary.cpp1256
-rw-r--r--core/io/resource_format_binary.h76
-rw-r--r--core/io/resource_import.cpp153
-rw-r--r--core/io/resource_import.h59
-rw-r--r--core/io/resource_loader.cpp198
-rw-r--r--core/io/resource_loader.h96
-rw-r--r--core/io/resource_saver.cpp71
-rw-r--r--core/io/resource_saver.h45
-rw-r--r--core/io/stream_peer.cpp406
-rw-r--r--core/io/stream_peer.h44
-rw-r--r--core/io/stream_peer_ssl.cpp37
-rw-r--r--core/io/stream_peer_ssl.h26
-rw-r--r--core/io/stream_peer_tcp.cpp39
-rw-r--r--core/io/stream_peer_tcp.h29
-rw-r--r--core/io/tcp_server.cpp18
-rw-r--r--core/io/tcp_server.h20
-rw-r--r--core/io/translation_loader_po.cpp125
-rw-r--r--core/io/translation_loader_po.h10
-rw-r--r--core/io/xml_parser.cpp333
-rw-r--r--core/io/xml_parser.h27
-rw-r--r--core/io/zip_io.h72
-rw-r--r--core/list.h407
-rw-r--r--core/map.h507
-rw-r--r--core/math/a_star.cpp308
-rw-r--r--core/math/a_star.h41
-rw-r--r--core/math/audio_frame.cpp1
-rw-r--r--core/math/audio_frame.h77
-rw-r--r--core/math/bsp_tree.cpp418
-rw-r--r--core/math/bsp_tree.h105
-rw-r--r--core/math/camera_matrix.cpp593
-rw-r--r--core/math/camera_matrix.h40
-rw-r--r--core/math/face3.cpp426
-rw-r--r--core/math/face3.h247
-rw-r--r--core/math/geometry.cpp836
-rw-r--r--core/math/geometry.h758
-rw-r--r--core/math/math_2d.cpp364
-rw-r--r--core/math/math_2d.h706
-rw-r--r--core/math/math_defs.h8
-rw-r--r--core/math/math_funcs.cpp76
-rw-r--r--core/math/math_funcs.h249
-rw-r--r--core/math/matrix3.cpp379
-rw-r--r--core/math/matrix3.h217
-rw-r--r--core/math/octree.h987
-rw-r--r--core/math/plane.cpp81
-rw-r--r--core/math/plane.h84
-rw-r--r--core/math/quat.cpp102
-rw-r--r--core/math/quat.h167
-rw-r--r--core/math/quick_hull.cpp299
-rw-r--r--core/math/quick_hull.h42
-rw-r--r--core/math/rect3.cpp355
-rw-r--r--core/math/rect3.h333
-rw-r--r--core/math/transform.cpp96
-rw-r--r--core/math/transform.h239
-rw-r--r--core/math/triangle_mesh.cpp416
-rw-r--r--core/math/triangle_mesh.h22
-rw-r--r--core/math/triangulate.cpp194
-rw-r--r--core/math/triangulate.h21
-rw-r--r--core/math/vector3.cpp79
-rw-r--r--core/math/vector3.h274
-rw-r--r--core/message_queue.cpp261
-rw-r--r--core/message_queue.h20
-rw-r--r--core/method_bind.cpp73
-rw-r--r--core/method_bind.h241
-rw-r--r--core/method_ptrcall.h484
-rw-r--r--core/object.cpp1175
-rw-r--r--core/object.h658
-rw-r--r--core/os/copymem.h2
-rw-r--r--core/os/dir_access.cpp151
-rw-r--r--core/os/dir_access.h70
-rw-r--r--core/os/file_access.cpp284
-rw-r--r--core/os/file_access.h111
-rw-r--r--core/os/input.cpp90
-rw-r--r--core/os/input.h100
-rw-r--r--core/os/input_event.cpp181
-rw-r--r--core/os/input_event.h136
-rw-r--r--core/os/keyboard.cpp297
-rw-r--r--core/os/keyboard.h514
-rw-r--r--core/os/main_loop.cpp64
-rw-r--r--core/os/main_loop.h14
-rw-r--r--core/os/memory.cpp112
-rw-r--r--core/os/memory.h102
-rw-r--r--core/os/mutex.cpp12
-rw-r--r--core/os/mutex.h25
-rw-r--r--core/os/os.cpp202
-rw-r--r--core/os/os.h165
-rw-r--r--core/os/power.h15
-rw-r--r--core/os/rw_lock.cpp9
-rw-r--r--core/os/rw_lock.h42
-rw-r--r--core/os/semaphore.cpp6
-rw-r--r--core/os/semaphore.h12
-rw-r--r--core/os/shell.cpp13
-rw-r--r--core/os/shell.h8
-rw-r--r--core/os/thread.cpp25
-rw-r--r--core/os/thread.h26
-rw-r--r--core/os/thread_dummy.cpp10
-rw-r--r--core/os/thread_dummy.h14
-rw-r--r--core/os/thread_safe.cpp2
-rw-r--r--core/os/thread_safe.h22
-rw-r--r--core/packed_data_container.cpp301
-rw-r--r--core/packed_data_container.h54
-rw-r--r--core/pair.h12
-rw-r--r--core/path_db.cpp238
-rw-r--r--core/path_db.h25
-rw-r--r--core/path_remap.cpp1
-rw-r--r--core/pool_allocator.cpp370
-rw-r--r--core/pool_allocator.h53
-rw-r--r--core/print_string.cpp34
-rw-r--r--core/print_string.h13
-rw-r--r--core/ref_ptr.cpp37
-rw-r--r--core/ref_ptr.h11
-rw-r--r--core/reference.cpp31
-rw-r--r--core/reference.h197
-rw-r--r--core/register_core_types.cpp148
-rw-r--r--core/resource.cpp221
-rw-r--r--core/resource.h69
-rw-r--r--core/rid.cpp4
-rw-r--r--core/rid.h109
-rw-r--r--core/ring_buffer.h52
-rw-r--r--core/safe_refcount.cpp56
-rw-r--r--core/safe_refcount.h29
-rw-r--r--core/script_debugger_local.cpp206
-rw-r--r--core/script_debugger_local.h13
-rw-r--r--core/script_debugger_remote.cpp687
-rw-r--r--core/script_debugger_remote.h42
-rw-r--r--core/script_language.cpp196
-rw-r--r--core/script_language.h297
-rw-r--r--core/self_list.h53
-rw-r--r--core/set.h478
-rw-r--r--core/simple_type.h86
-rw-r--r--core/sort.h197
-rw-r--r--core/string_db.cpp239
-rw-r--r--core/string_db.h63
-rw-r--r--core/translation.cpp1697
-rw-r--r--core/translation.h39
-rw-r--r--core/typedefs.h67
-rw-r--r--core/ucaps.h2697
-rw-r--r--core/undo_redo.cpp358
-rw-r--r--core/undo_redo.h48
-rw-r--r--core/ustring.cpp2786
-rw-r--r--core/ustring.h175
-rw-r--r--core/variant.cpp1833
-rw-r--r--core/variant.h280
-rw-r--r--core/variant_call.cpp2259
-rw-r--r--core/variant_construct_string.cpp286
-rw-r--r--core/variant_op.cpp3781
-rw-r--r--core/variant_parser.cpp1654
-rw-r--r--core/variant_parser.h66
-rw-r--r--core/vector.h279
-rw-r--r--core/vmap.h102
-rw-r--r--core/vset.h63
-rw-r--r--drivers/alsa/audio_driver_alsa.cpp100
-rw-r--r--drivers/alsa/audio_driver_alsa.h17
-rw-r--r--drivers/convex_decomp/b2d_decompose.cpp195
-rw-r--r--drivers/convex_decomp/b2d_decompose.h2
-rw-r--r--drivers/gl_context/context_gl.cpp19
-rw-r--r--drivers/gl_context/context_gl.h24
-rw-r--r--drivers/gles2/rasterizer_gles2.cpp8039
-rw-r--r--drivers/gles2/rasterizer_gles2.h894
-rw-r--r--drivers/gles2/rasterizer_instance_gles2.cpp3
-rw-r--r--drivers/gles2/rasterizer_instance_gles2.h1
-rw-r--r--drivers/gles2/shader_compiler_gles2.cpp1032
-rw-r--r--drivers/gles2/shader_compiler_gles2.h20
-rw-r--r--drivers/gles2/shader_gles2.cpp621
-rw-r--r--drivers/gles2/shader_gles2.h306
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.cpp1084
-rw-r--r--drivers/gles3/rasterizer_canvas_gles3.h28
-rw-r--r--drivers/gles3/rasterizer_gles3.cpp249
-rw-r--r--drivers/gles3/rasterizer_gles3.h11
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.cpp3797
-rw-r--r--drivers/gles3/rasterizer_scene_gles3.h338
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.cpp4914
-rw-r--r--drivers/gles3/rasterizer_storage_gles3.h557
-rw-r--r--drivers/gles3/shader_compiler_gles3.cpp623
-rw-r--r--drivers/gles3/shader_compiler_gles3.h29
-rw-r--r--drivers/gles3/shader_gles3.cpp628
-rw-r--r--drivers/gles3/shader_gles3.h317
-rw-r--r--drivers/png/image_loader_png.cpp212
-rw-r--r--drivers/png/image_loader_png.h14
-rw-r--r--drivers/png/resource_saver_png.cpp106
-rw-r--r--drivers/png/resource_saver_png.h10
-rw-r--r--drivers/pulseaudio/audio_driver_pulseaudio.cpp41
-rw-r--r--drivers/pulseaudio/audio_driver_pulseaudio.h28
-rw-r--r--drivers/register_driver_types.cpp18
-rw-r--r--drivers/rtaudio/audio_driver_rtaudio.cpp95
-rw-r--r--drivers/rtaudio/audio_driver_rtaudio.h13
-rw-r--r--drivers/unix/dir_access_unix.cpp144
-rw-r--r--drivers/unix/dir_access_unix.h34
-rw-r--r--drivers/unix/file_access_unix.cpp144
-rw-r--r--drivers/unix/file_access_unix.h39
-rw-r--r--drivers/unix/ip_unix.cpp113
-rw-r--r--drivers/unix/ip_unix.h6
-rw-r--r--drivers/unix/mutex_posix.cpp15
-rw-r--r--drivers/unix/mutex_posix.h17
-rw-r--r--drivers/unix/os_unix.cpp251
-rw-r--r--drivers/unix/os_unix.h53
-rw-r--r--drivers/unix/packet_peer_udp_posix.cpp118
-rw-r--r--drivers/unix/packet_peer_udp_posix.h14
-rw-r--r--drivers/unix/rw_lock_posix.cpp25
-rw-r--r--drivers/unix/rw_lock_posix.h6
-rw-r--r--drivers/unix/semaphore_posix.cpp22
-rw-r--r--drivers/unix/semaphore_posix.h8
-rw-r--r--drivers/unix/socket_helpers.h48
-rw-r--r--drivers/unix/stream_peer_tcp_posix.cpp61
-rw-r--r--drivers/unix/stream_peer_tcp_posix.h18
-rw-r--r--drivers/unix/tcp_server_posix.cpp34
-rw-r--r--drivers/unix/tcp_server_posix.h6
-rw-r--r--drivers/unix/thread_posix.cpp67
-rw-r--r--drivers/unix/thread_posix.h29
-rw-r--r--drivers/windows/dir_access_windows.cpp160
-rw-r--r--drivers/windows/dir_access_windows.h9
-rw-r--r--drivers/windows/file_access_windows.cpp132
-rw-r--r--drivers/windows/file_access_windows.h10
-rw-r--r--drivers/windows/mutex_windows.cpp46
-rw-r--r--drivers/windows/mutex_windows.h19
-rw-r--r--drivers/windows/rw_lock_windows.cpp18
-rw-r--r--drivers/windows/rw_lock_windows.h6
-rw-r--r--drivers/windows/semaphore_windows.cpp37
-rw-r--r--drivers/windows/semaphore_windows.h10
-rw-r--r--drivers/windows/shell_windows.cpp9
-rw-r--r--drivers/windows/shell_windows.h4
-rw-r--r--drivers/windows/thread_windows.cpp61
-rw-r--r--drivers/windows/thread_windows.h29
-rw-r--r--drivers/xaudio2/audio_driver_xaudio2.cpp29
-rw-r--r--drivers/xaudio2/audio_driver_xaudio2.h41
-rw-r--r--editor/animation_editor.cpp3270
-rw-r--r--editor/animation_editor.h64
-rw-r--r--editor/array_property_edit.cpp220
-rw-r--r--editor/array_property_edit.h16
-rw-r--r--editor/asset_library_editor_plugin.cpp994
-rw-r--r--editor/asset_library_editor_plugin.h111
-rw-r--r--editor/call_dialog.cpp2
-rw-r--r--editor/call_dialog.h6
-rw-r--r--editor/code_editor.cpp602
-rw-r--r--editor/code_editor.h63
-rw-r--r--editor/collada/collada.cpp1935
-rw-r--r--editor/collada/collada.h375
-rw-r--r--editor/connections_dialog.cpp484
-rw-r--r--editor/connections_dialog.h34
-rw-r--r--editor/create_dialog.cpp507
-rw-r--r--editor/create_dialog.h47
-rw-r--r--editor/dependency_editor.cpp456
-rw-r--r--editor/dependency_editor.h52
-rw-r--r--editor/doc/doc_data.cpp886
-rw-r--r--editor/doc/doc_data.h36
-rw-r--r--editor/doc/doc_dump.cpp269
-rw-r--r--editor/doc/doc_dump.h4
-rw-r--r--editor/doc_code_font.h8
-rw-r--r--editor/doc_font.h8
-rw-r--r--editor/doc_title_font.h8
-rw-r--r--editor/editor_asset_installer.cpp236
-rw-r--r--editor/editor_asset_installer.h13
-rw-r--r--editor/editor_audio_buses.cpp830
-rw-r--r--editor/editor_audio_buses.h80
-rw-r--r--editor/editor_autoload_settings.cpp77
-rw-r--r--editor/editor_autoload_settings.h18
-rw-r--r--editor/editor_data.cpp499
-rw-r--r--editor/editor_data.h87
-rw-r--r--editor/editor_dir_dialog.cpp150
-rw-r--r--editor/editor_dir_dialog.h13
-rw-r--r--editor/editor_export.cpp560
-rw-r--r--editor/editor_export.h150
-rw-r--r--editor/editor_file_dialog.cpp1018
-rw-r--r--editor/editor_file_dialog.h51
-rw-r--r--editor/editor_file_system.cpp1038
-rw-r--r--editor/editor_file_system.h73
-rw-r--r--editor/editor_fonts.cpp106
-rw-r--r--editor/editor_help.cpp1002
-rw-r--r--editor/editor_help.h97
-rw-r--r--editor/editor_initialize_ssl.cpp13
-rw-r--r--editor/editor_log.cpp103
-rw-r--r--editor/editor_log.h17
-rw-r--r--editor/editor_name_dialog.cpp21
-rw-r--r--editor/editor_name_dialog.h8
-rw-r--r--editor/editor_node.cpp3353
-rw-r--r--editor/editor_node.h312
-rw-r--r--editor/editor_path.cpp119
-rw-r--r--editor/editor_path.h12
-rw-r--r--editor/editor_plugin.cpp232
-rw-r--r--editor/editor_plugin.h89
-rw-r--r--editor/editor_plugin_settings.cpp152
-rw-r--r--editor/editor_plugin_settings.h14
-rw-r--r--editor/editor_profiler.cpp563
-rw-r--r--editor/editor_profiler.h36
-rw-r--r--editor/editor_resource_preview.cpp227
-rw-r--r--editor/editor_resource_preview.h42
-rw-r--r--editor/editor_run.cpp104
-rw-r--r--editor/editor_run.h10
-rw-r--r--editor/editor_run_native.cpp34
-rw-r--r--editor/editor_run_native.h9
-rw-r--r--editor/editor_run_script.cpp32
-rw-r--r--editor/editor_run_script.h7
-rw-r--r--editor/editor_scale.cpp2
-rw-r--r--editor/editor_settings.cpp651
-rw-r--r--editor/editor_settings.h74
-rw-r--r--editor/editor_sub_scene.cpp122
-rw-r--r--editor/editor_sub_scene.h19
-rw-r--r--editor/editor_themes.cpp40
-rw-r--r--editor/file_type_cache.cpp37
-rw-r--r--editor/file_type_cache.h17
-rw-r--r--editor/fileserver/editor_file_server.cpp266
-rw-r--r--editor/fileserver/editor_file_server.h20
-rw-r--r--editor/filesystem_dock.cpp1026
-rw-r--r--editor/filesystem_dock.h72
-rw-r--r--editor/groups_editor.cpp90
-rw-r--r--editor/groups_editor.h16
-rw-r--r--editor/import/editor_import_collada.cpp1450
-rw-r--r--editor/import/editor_import_collada.h12
-rw-r--r--editor/import/resource_importer_csv_translation.cpp60
-rw-r--r--editor/import/resource_importer_csv_translation.h9
-rw-r--r--editor/import/resource_importer_obj.cpp162
-rw-r--r--editor/import/resource_importer_obj.h10
-rw-r--r--editor/import/resource_importer_scene.cpp764
-rw-r--r--editor/import/resource_importer_scene.h69
-rw-r--r--editor/import/resource_importer_texture.cpp232
-rw-r--r--editor/import/resource_importer_texture.h30
-rw-r--r--editor/import/resource_importer_wav.cpp434
-rw-r--r--editor/import/resource_importer_wav.h12
-rw-r--r--editor/import_dock.cpp177
-rw-r--r--editor/import_dock.h15
-rw-r--r--editor/inspector_dock.h3
-rw-r--r--editor/io_plugins/editor_atlas.cpp92
-rw-r--r--editor/io_plugins/editor_atlas.h5
-rw-r--r--editor/io_plugins/editor_bitmask_import_plugin.cpp8
-rw-r--r--editor/io_plugins/editor_export_scene.cpp4
-rw-r--r--editor/io_plugins/editor_font_import_plugin.cpp6
-rw-r--r--editor/io_plugins/editor_mesh_import_plugin.cpp4
-rw-r--r--editor/io_plugins/editor_sample_import_plugin.cpp6
-rw-r--r--editor/io_plugins/editor_scene_import_plugin.cpp25
-rw-r--r--editor/io_plugins/editor_scene_import_plugin.h16
-rw-r--r--editor/io_plugins/editor_scene_importer_fbxconv.cpp2
-rw-r--r--editor/io_plugins/editor_texture_import_plugin.cpp12
-rw-r--r--editor/io_plugins/editor_texture_import_plugin.h15
-rw-r--r--editor/io_plugins/editor_translation_import_plugin.cpp6
-rw-r--r--editor/multi_node_edit.cpp90
-rw-r--r--editor/multi_node_edit.h19
-rw-r--r--editor/node_dock.cpp40
-rw-r--r--editor/node_dock.h8
-rw-r--r--editor/output_strings.cpp139
-rw-r--r--editor/output_strings.h20
-rw-r--r--editor/pane_drag.cpp34
-rw-r--r--editor/pane_drag.h7
-rw-r--r--editor/plugins/animation_player_editor_plugin.cpp790
-rw-r--r--editor/plugins/animation_player_editor_plugin.h50
-rw-r--r--editor/plugins/animation_tree_editor_plugin.cpp1166
-rw-r--r--editor/plugins/animation_tree_editor_plugin.h49
-rw-r--r--editor/plugins/baked_light_baker.cpp6
-rw-r--r--editor/plugins/baked_light_baker.h2
-rw-r--r--editor/plugins/baked_light_baker_cmpxchg.cpp58
-rw-r--r--editor/plugins/baked_light_editor_plugin.cpp7
-rw-r--r--editor/plugins/baked_light_editor_plugin.h5
-rw-r--r--editor/plugins/camera_editor_plugin.cpp50
-rw-r--r--editor/plugins/camera_editor_plugin.h13
-rw-r--r--editor/plugins/canvas_item_editor_plugin.cpp2381
-rw-r--r--editor/plugins/canvas_item_editor_plugin.h138
-rw-r--r--editor/plugins/collision_polygon_2d_editor_plugin.cpp301
-rw-r--r--editor/plugins/collision_polygon_2d_editor_plugin.h18
-rw-r--r--editor/plugins/collision_polygon_editor_plugin.cpp6
-rw-r--r--editor/plugins/collision_polygon_editor_plugin.h4
-rw-r--r--editor/plugins/collision_shape_2d_editor_plugin.cpp222
-rw-r--r--editor/plugins/collision_shape_2d_editor_plugin.h32
-rw-r--r--editor/plugins/color_ramp_editor_plugin.cpp44
-rw-r--r--editor/plugins/color_ramp_editor_plugin.h7
-rw-r--r--editor/plugins/cube_grid_theme_editor_plugin.cpp8
-rw-r--r--editor/plugins/cube_grid_theme_editor_plugin.h3
-rw-r--r--editor/plugins/editor_preview_plugins.cpp38
-rw-r--r--editor/plugins/gi_probe_editor_plugin.cpp22
-rw-r--r--editor/plugins/gi_probe_editor_plugin.h13
-rw-r--r--editor/plugins/item_list_editor_plugin.cpp189
-rw-r--r--editor/plugins/item_list_editor_plugin.h96
-rw-r--r--editor/plugins/light_occluder_2d_editor_plugin.cpp334
-rw-r--r--editor/plugins/light_occluder_2d_editor_plugin.h20
-rw-r--r--editor/plugins/line_2d_editor_plugin.cpp88
-rw-r--r--editor/plugins/line_2d_editor_plugin.h20
-rw-r--r--editor/plugins/material_editor_plugin.cpp52
-rw-r--r--editor/plugins/material_editor_plugin.h6
-rw-r--r--editor/plugins/mesh_editor_plugin.h6
-rw-r--r--editor/plugins/mesh_instance_editor_plugin.cpp141
-rw-r--r--editor/plugins/mesh_instance_editor_plugin.h15
-rw-r--r--editor/plugins/multimesh_editor_plugin.cpp208
-rw-r--r--editor/plugins/multimesh_editor_plugin.h16
-rw-r--r--editor/plugins/navigation_polygon_editor_plugin.cpp396
-rw-r--r--editor/plugins/navigation_polygon_editor_plugin.h20
-rw-r--r--editor/plugins/particles_2d_editor_plugin.cpp110
-rw-r--r--editor/plugins/particles_2d_editor_plugin.h13
-rw-r--r--editor/plugins/particles_editor_plugin.cpp3
-rw-r--r--editor/plugins/particles_editor_plugin.h2
-rw-r--r--editor/plugins/path_2d_editor_plugin.cpp306
-rw-r--r--editor/plugins/path_2d_editor_plugin.h20
-rw-r--r--editor/plugins/path_editor_plugin.cpp4
-rw-r--r--editor/plugins/path_editor_plugin.h3
-rw-r--r--editor/plugins/polygon_2d_editor_plugin.cpp741
-rw-r--r--editor/plugins/polygon_2d_editor_plugin.h19
-rw-r--r--editor/plugins/resource_preloader_editor_plugin.cpp296
-rw-r--r--editor/plugins/resource_preloader_editor_plugin.h31
-rw-r--r--editor/plugins/rich_text_editor_plugin.cpp62
-rw-r--r--editor/plugins/rich_text_editor_plugin.h18
-rw-r--r--editor/plugins/sample_editor_plugin.cpp4
-rw-r--r--editor/plugins/sample_editor_plugin.h2
-rw-r--r--editor/plugins/sample_library_editor_plugin.cpp6
-rw-r--r--editor/plugins/sample_library_editor_plugin.h9
-rw-r--r--editor/plugins/sample_player_editor_plugin.cpp2
-rw-r--r--editor/plugins/sample_player_editor_plugin.h4
-rw-r--r--editor/plugins/script_editor_plugin.cpp1171
-rw-r--r--editor/plugins/script_editor_plugin.h145
-rw-r--r--editor/plugins/script_text_editor.cpp644
-rw-r--r--editor/plugins/script_text_editor.h50
-rw-r--r--editor/plugins/shader_editor_plugin.cpp250
-rw-r--r--editor/plugins/shader_editor_plugin.h32
-rw-r--r--editor/plugins/shader_graph_editor_plugin.cpp6
-rw-r--r--editor/plugins/shader_graph_editor_plugin.h9
-rw-r--r--editor/plugins/spatial_editor_plugin.cpp2678
-rw-r--r--editor/plugins/spatial_editor_plugin.h166
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.cpp611
-rw-r--r--editor/plugins/sprite_frames_editor_plugin.h35
-rw-r--r--editor/plugins/stream_editor_plugin.h2
-rw-r--r--editor/plugins/style_box_editor_plugin.cpp44
-rw-r--r--editor/plugins/style_box_editor_plugin.h22
-rw-r--r--editor/plugins/texture_editor_plugin.cpp84
-rw-r--r--editor/plugins/texture_editor_plugin.h13
-rw-r--r--editor/plugins/texture_region_editor_plugin.cpp755
-rw-r--r--editor/plugins/texture_region_editor_plugin.h23
-rw-r--r--editor/plugins/theme_editor_plugin.cpp610
-rw-r--r--editor/plugins/theme_editor_plugin.h34
-rw-r--r--editor/plugins/tile_map_editor_plugin.cpp781
-rw-r--r--editor/plugins/tile_map_editor_plugin.h54
-rw-r--r--editor/plugins/tile_set_editor_plugin.cpp156
-rw-r--r--editor/plugins/tile_set_editor_plugin.h27
-rw-r--r--editor/progress_dialog.cpp133
-rw-r--r--editor/progress_dialog.h43
-rw-r--r--editor/project_export.cpp453
-rw-r--r--editor/project_export.h53
-rw-r--r--editor/project_manager.cpp776
-rw-r--r--editor/project_manager.h32
-rw-r--r--editor/project_settings.cpp1070
-rw-r--r--editor/project_settings.h48
-rw-r--r--editor/property_editor.cpp3137
-rw-r--r--editor/property_editor.h164
-rw-r--r--editor/property_selector.cpp528
-rw-r--r--editor/property_selector.h32
-rw-r--r--editor/pvrtc_compress.cpp63
-rw-r--r--editor/pvrtc_compress.h1
-rw-r--r--editor/quick_open.cpp82
-rw-r--r--editor/quick_open.h19
-rw-r--r--editor/register_exporters.h1
-rw-r--r--editor/reparent_dialog.cpp45
-rw-r--r--editor/reparent_dialog.h16
-rw-r--r--editor/resources_dock.cpp216
-rw-r--r--editor/resources_dock.h39
-rw-r--r--editor/run_settings_dialog.cpp25
-rw-r--r--editor/run_settings_dialog.h15
-rw-r--r--editor/scene_tree_dock.cpp1172
-rw-r--r--editor/scene_tree_dock.h80
-rw-r--r--editor/scene_tree_editor.cpp786
-rw-r--r--editor/scene_tree_editor.h83
-rw-r--r--editor/script_create_dialog.cpp235
-rw-r--r--editor/script_create_dialog.h25
-rw-r--r--editor/script_editor_debugger.cpp1189
-rw-r--r--editor/script_editor_debugger.h70
-rw-r--r--editor/settings_config_dialog.cpp229
-rw-r--r--editor/settings_config_dialog.h19
-rw-r--r--editor/spatial_editor_gizmos.cpp2418
-rw-r--r--editor/spatial_editor_gizmos.h327
-rw-r--r--main/input_default.cpp347
-rw-r--r--main/input_default.h62
-rw-r--r--main/main.cpp1115
-rw-r--r--main/main.h7
-rw-r--r--main/performance.cpp95
-rw-r--r--main/performance.h10
-rw-r--r--main/splash.h2
-rw-r--r--main/tests/test_containers.cpp16
-rw-r--r--main/tests/test_containers.h3
-rw-r--r--main/tests/test_gdscript.cpp1022
-rw-r--r--main/tests/test_gdscript.h3
-rw-r--r--main/tests/test_gui.cpp207
-rw-r--r--main/tests/test_gui.h4
-rw-r--r--main/tests/test_image.cpp25
-rw-r--r--main/tests/test_image.h3
-rw-r--r--main/tests/test_io.cpp53
-rw-r--r--main/tests/test_io.h3
-rw-r--r--main/tests/test_main.cpp58
-rw-r--r--main/tests/test_main.h9
-rw-r--r--main/tests/test_math.cpp463
-rw-r--r--main/tests/test_math.h3
-rw-r--r--main/tests/test_physics.cpp377
-rw-r--r--main/tests/test_physics.h3
-rw-r--r--main/tests/test_physics_2d.cpp293
-rw-r--r--main/tests/test_physics_2d.h4
-rw-r--r--main/tests/test_render.cpp134
-rw-r--r--main/tests/test_render.h3
-rw-r--r--main/tests/test_shader_lang.cpp228
-rw-r--r--main/tests/test_shader_lang.h3
-rw-r--r--main/tests/test_sound.cpp6
-rw-r--r--main/tests/test_sound.h3
-rw-r--r--main/tests/test_string.cpp260
-rw-r--r--main/tests/test_string.h8
-rw-r--r--modules/cscript/godot_c.cpp1
-rw-r--r--modules/cscript/godot_c.h309
-rw-r--r--modules/cscript/register_types.cpp3
-rw-r--r--modules/dds/register_types.cpp2
-rw-r--r--modules/dds/texture_loader_dds.cpp345
-rw-r--r--modules/dds/texture_loader_dds.h9
-rw-r--r--modules/enet/networked_multiplayer_enet.cpp446
-rw-r--r--modules/enet/networked_multiplayer_enet.h31
-rw-r--r--modules/enet/register_types.cpp7
-rw-r--r--modules/etc1/image_etc.cpp153
-rw-r--r--modules/etc1/image_etc.h1
-rw-r--r--modules/etc1/register_types.cpp2
-rw-r--r--modules/etc1/texture_loader_pkm.cpp46
-rw-r--r--modules/etc1/texture_loader_pkm.h9
-rw-r--r--modules/gdscript/gd_compiler.cpp1303
-rw-r--r--modules/gdscript/gd_compiler.h144
-rw-r--r--modules/gdscript/gd_editor.cpp2016
-rw-r--r--modules/gdscript/gd_function.cpp991
-rw-r--r--modules/gdscript/gd_function.h84
-rw-r--r--modules/gdscript/gd_functions.cpp1044
-rw-r--r--modules/gdscript/gd_functions.h4
-rw-r--r--modules/gdscript/gd_parser.cpp2682
-rw-r--r--modules/gdscript/gd_parser.h164
-rw-r--r--modules/gdscript/gd_script.cpp1069
-rw-r--r--modules/gdscript/gd_script.h270
-rw-r--r--modules/gdscript/gd_tokenizer.cpp1163
-rw-r--r--modules/gdscript/gd_tokenizer.h122
-rw-r--r--modules/gdscript/register_types.cpp28
-rw-r--r--modules/gridmap/grid_map.cpp974
-rw-r--r--modules/gridmap/grid_map.h88
-rw-r--r--modules/gridmap/grid_map_editor_plugin.cpp958
-rw-r--r--modules/gridmap/grid_map_editor_plugin.h36
-rw-r--r--modules/gridmap/register_types.cpp4
-rw-r--r--modules/jpg/image_loader_jpegd.cpp54
-rw-r--r--modules/jpg/image_loader_jpegd.h8
-rw-r--r--modules/jpg/register_types.cpp4
-rw-r--r--modules/openssl/stream_peer_openssl.cpp360
-rw-r--r--modules/openssl/stream_peer_openssl.h50
-rw-r--r--modules/opus/audio_stream_opus.cpp222
-rw-r--r--modules/opus/audio_stream_opus.h36
-rw-r--r--modules/opus/register_types.cpp4
-rw-r--r--modules/pbm/bitmap_loader_pbm.cpp154
-rw-r--r--modules/pbm/bitmap_loader_pbm.h8
-rw-r--r--modules/pbm/register_types.cpp6
-rw-r--r--modules/pvr/register_types.cpp2
-rw-r--r--modules/pvr/texture_loader_pvr.cpp447
-rw-r--r--modules/pvr/texture_loader_pvr.h12
-rw-r--r--modules/regex/regex.cpp461
-rw-r--r--modules/regex/regex.h29
-rw-r--r--modules/regex/register_types.cpp2
-rw-r--r--modules/squish/image_compress_squish.cpp53
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.cpp134
-rw-r--r--modules/stb_vorbis/audio_stream_ogg_vorbis.h31
-rw-r--r--modules/stb_vorbis/register_types.cpp1
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.cpp31
-rw-r--r--modules/stb_vorbis/resource_importer_ogg_vorbis.h11
-rw-r--r--modules/theora/register_types.cpp6
-rw-r--r--modules/theora/video_stream_theora.cpp458
-rw-r--r--modules/theora/video_stream_theora.h56
-rw-r--r--modules/visual_script/register_types.cpp26
-rw-r--r--modules/visual_script/visual_script.cpp1841
-rw-r--r--modules/visual_script/visual_script.h435
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.cpp713
-rw-r--r--modules/visual_script/visual_script_builtin_funcs.h20
-rw-r--r--modules/visual_script/visual_script_editor.cpp2441
-rw-r--r--modules/visual_script/visual_script_editor.h91
-rw-r--r--modules/visual_script/visual_script_expression.cpp1158
-rw-r--r--modules/visual_script/visual_script_expression.h107
-rw-r--r--modules/visual_script/visual_script_flow_control.cpp1235
-rw-r--r--modules/visual_script/visual_script_flow_control.h138
-rw-r--r--modules/visual_script/visual_script_func_nodes.cpp1611
-rw-r--r--modules/visual_script/visual_script_func_nodes.h113
-rw-r--r--modules/visual_script/visual_script_nodes.cpp2142
-rw-r--r--modules/visual_script/visual_script_nodes.h387
-rw-r--r--modules/visual_script/visual_script_yield_nodes.cpp355
-rw-r--r--modules/visual_script/visual_script_yield_nodes.h39
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.cpp269
-rw-r--r--modules/vorbis/audio_stream_ogg_vorbis.h35
-rw-r--r--modules/vorbis/register_types.cpp4
-rw-r--r--modules/webm/video_stream_webm.cpp55
-rw-r--r--modules/webm/video_stream_webm.h2
-rw-r--r--modules/webp/image_loader_webp.cpp103
-rw-r--r--modules/webp/image_loader_webp.h8
-rw-r--r--modules/webp/register_types.cpp4
-rw-r--r--platform/android/audio_driver_jandroid.cpp127
-rw-r--r--platform/android/audio_driver_jandroid.h15
-rw-r--r--platform/android/audio_driver_opensl.cpp163
-rw-r--r--platform/android/audio_driver_opensl.h25
-rw-r--r--platform/android/dir_access_android.cpp87
-rw-r--r--platform/android/dir_access_android.h11
-rw-r--r--platform/android/dir_access_jandroid.cpp153
-rw-r--r--platform/android/dir_access_jandroid.h9
-rw-r--r--platform/android/export/export.cpp15
-rw-r--r--platform/android/file_access_android.cpp100
-rw-r--r--platform/android/file_access_android.h17
-rw-r--r--platform/android/file_access_jandroid.cpp139
-rw-r--r--platform/android/file_access_jandroid.h16
-rw-r--r--platform/android/globals/global_defaults.cpp3
-rw-r--r--platform/android/godot_android.cpp1022
-rw-r--r--platform/android/java_class_wrapper.cpp755
-rw-r--r--platform/android/java_class_wrapper.h172
-rw-r--r--platform/android/java_glue.cpp1194
-rw-r--r--platform/android/java_glue.h48
-rw-r--r--platform/android/os_android.cpp419
-rw-r--r--platform/android/os_android.h77
-rw-r--r--platform/android/power_android.cpp103
-rw-r--r--platform/android/power_android.h14
-rw-r--r--platform/android/thread_jandroid.cpp58
-rw-r--r--platform/android/thread_jandroid.h27
-rw-r--r--platform/bb10/audio_driver_bb10.cpp37
-rw-r--r--platform/bb10/audio_driver_bb10.h20
-rw-r--r--platform/bb10/export/export.cpp12
-rw-r--r--platform/bb10/godot_bb10.cpp7
-rw-r--r--platform/bb10/os_bb10.cpp305
-rw-r--r--platform/bb10/os_bb10.h47
-rw-r--r--platform/bb10/payment_service.cpp36
-rw-r--r--platform/bb10/payment_service.h8
-rw-r--r--platform/bb10/power_bb10.cpp15
-rw-r--r--platform/bb10/power_bb10.h1
-rw-r--r--platform/haiku/audio_driver_media_kit.cpp20
-rw-r--r--platform/haiku/audio_driver_media_kit.h15
-rw-r--r--platform/haiku/context_gl_haiku.cpp4
-rw-r--r--platform/haiku/context_gl_haiku.h10
-rw-r--r--platform/haiku/godot_haiku.cpp4
-rw-r--r--platform/haiku/haiku_application.cpp4
-rw-r--r--platform/haiku/haiku_application.h7
-rw-r--r--platform/haiku/haiku_direct_window.cpp44
-rw-r--r--platform/haiku/haiku_direct_window.h41
-rw-r--r--platform/haiku/haiku_gl_view.cpp5
-rw-r--r--platform/haiku/haiku_gl_view.h5
-rw-r--r--platform/haiku/key_mapping_haiku.cpp60
-rw-r--r--platform/haiku/key_mapping_haiku.h5
-rw-r--r--platform/haiku/os_haiku.cpp31
-rw-r--r--platform/haiku/os_haiku.h59
-rw-r--r--platform/haiku/power_haiku.cpp13
-rw-r--r--platform/haiku/power_haiku.h1
-rw-r--r--platform/iphone/app_delegate.h8
-rw-r--r--platform/iphone/audio_driver_iphone.cpp37
-rw-r--r--platform/iphone/audio_driver_iphone.h17
-rw-r--r--platform/iphone/game_center.h6
-rw-r--r--[-rwxr-xr-x]platform/iphone/gl_view.h25
-rw-r--r--[-rwxr-xr-x]platform/iphone/globals/global_defaults.cpp1
-rw-r--r--platform/iphone/godot_iphone.cpp37
-rw-r--r--platform/iphone/icloud.h7
-rw-r--r--platform/iphone/in_app_store.h9
-rw-r--r--platform/iphone/ios.h2
-rw-r--r--platform/iphone/os_iphone.cpp103
-rw-r--r--platform/iphone/os_iphone.h62
-rw-r--r--platform/iphone/platform_refcount.h8
-rw-r--r--platform/iphone/power_iphone.cpp14
-rw-r--r--platform/iphone/rasterizer_iphone.cpp1652
-rw-r--r--platform/iphone/rasterizer_iphone.h420
-rw-r--r--platform/iphone/sem_iphone.cpp33
-rw-r--r--platform/iphone/sem_iphone.h3
-rw-r--r--platform/iphone/view_controller.h3
-rw-r--r--platform/javascript/audio_driver_javascript.cpp25
-rw-r--r--platform/javascript/audio_driver_javascript.h7
-rw-r--r--platform/javascript/audio_server_javascript.cpp2
-rw-r--r--platform/javascript/dom_keys.h26
-rw-r--r--platform/javascript/export/export.cpp14
-rw-r--r--platform/javascript/javascript_eval.cpp28
-rw-r--r--platform/javascript/javascript_eval.h5
-rw-r--r--platform/javascript/javascript_main.cpp125
-rw-r--r--platform/javascript/os_javascript.cpp404
-rw-r--r--platform/javascript/os_javascript.h64
-rw-r--r--platform/javascript/power_javascript.cpp18
-rw-r--r--platform/javascript/power_javascript.h1
-rw-r--r--platform/osx/audio_driver_osx.cpp36
-rw-r--r--platform/osx/audio_driver_osx.h16
-rw-r--r--platform/osx/context_gl_osx.cpp42
-rw-r--r--platform/osx/context_gl_osx.h4
-rw-r--r--platform/osx/dir_access_osx.h13
-rw-r--r--platform/osx/export/export.cpp11
-rw-r--r--platform/osx/joypad_osx.cpp296
-rw-r--r--platform/osx/joypad_osx.h4
-rw-r--r--platform/osx/os_osx.h71
-rw-r--r--platform/osx/power_osx.cpp66
-rw-r--r--platform/osx/power_osx.h2
-rw-r--r--platform/osx/sem_osx.cpp25
-rw-r--r--platform/osx/sem_osx.h3
-rw-r--r--platform/server/godot_server.cpp6
-rw-r--r--platform/server/os_server.cpp75
-rw-r--r--platform/server/os_server.h34
-rw-r--r--platform/uwp/app.cpp281
-rw-r--r--platform/uwp/export/export.cpp31
-rw-r--r--platform/uwp/gl_context_egl.cpp84
-rw-r--r--platform/uwp/gl_context_egl.h11
-rw-r--r--platform/uwp/joypad_uwp.cpp36
-rw-r--r--platform/uwp/joypad_uwp.h11
-rw-r--r--platform/uwp/os_uwp.cpp313
-rw-r--r--platform/uwp/os_uwp.h116
-rw-r--r--platform/uwp/thread_uwp.cpp15
-rw-r--r--platform/uwp/thread_uwp.h11
-rw-r--r--platform/windows/context_gl_win.cpp126
-rw-r--r--platform/windows/context_gl_win.h12
-rw-r--r--platform/windows/ctxgl_procaddr.cpp14
-rw-r--r--platform/windows/ctxgl_procaddr.h3
-rw-r--r--platform/windows/export/export.cpp3
-rw-r--r--platform/windows/godot_win.cpp202
-rw-r--r--platform/windows/joypad.cpp95
-rw-r--r--platform/windows/joypad.h38
-rw-r--r--platform/windows/key_mapping_win.cpp373
-rw-r--r--platform/windows/key_mapping_win.h9
-rw-r--r--platform/windows/lang_table.h296
-rw-r--r--platform/windows/os_windows.cpp1455
-rw-r--r--platform/windows/os_windows.h105
-rw-r--r--platform/windows/packet_peer_udp_winsock.cpp124
-rw-r--r--platform/windows/packet_peer_udp_winsock.h14
-rw-r--r--platform/windows/power_windows.cpp83
-rw-r--r--platform/windows/stream_peer_winsock.cpp48
-rw-r--r--platform/windows/stream_peer_winsock.h19
-rw-r--r--platform/windows/tcp_server_winsock.cpp21
-rw-r--r--platform/windows/tcp_server_winsock.h5
-rw-r--r--platform/x11/context_gl_x11.cpp117
-rw-r--r--platform/x11/context_gl_x11.h13
-rw-r--r--platform/x11/export/export.cpp9
-rw-r--r--platform/x11/godot_x11.cpp10
-rw-r--r--platform/x11/joypad_linux.cpp156
-rw-r--r--platform/x11/joypad_linux.h11
-rw-r--r--platform/x11/key_mapping_x11.cpp336
-rw-r--r--platform/x11/key_mapping_x11.h7
-rw-r--r--platform/x11/os_x11.cpp1378
-rw-r--r--platform/x11/os_x11.h93
-rw-r--r--platform/x11/power_x11.cpp177
-rw-r--r--platform/x11/power_x11.h11
-rw-r--r--scene/2d/animated_sprite.cpp408
-rw-r--r--scene/2d/animated_sprite.h86
-rw-r--r--scene/2d/area_2d.cpp489
-rw-r--r--scene/2d/area_2d.h45
-rw-r--r--scene/2d/back_buffer_copy.cpp50
-rw-r--r--scene/2d/back_buffer_copy.h9
-rw-r--r--scene/2d/camera_2d.cpp452
-rw-r--r--scene/2d/camera_2d.h19
-rw-r--r--scene/2d/canvas_item.cpp651
-rw-r--r--scene/2d/canvas_item.h112
-rw-r--r--scene/2d/canvas_modulate.cpp56
-rw-r--r--scene/2d/canvas_modulate.h7
-rw-r--r--scene/2d/collision_object_2d.cpp228
-rw-r--r--scene/2d/collision_object_2d.h30
-rw-r--r--scene/2d/collision_polygon_2d.cpp203
-rw-r--r--scene/2d/collision_polygon_2d.h19
-rw-r--r--scene/2d/collision_shape_2d.cpp107
-rw-r--r--scene/2d/collision_shape_2d.h7
-rw-r--r--scene/2d/joints_2d.cpp265
-rw-r--r--scene/2d/joints_2d.h31
-rw-r--r--scene/2d/light_2d.cpp363
-rw-r--r--scene/2d/light_2d.h51
-rw-r--r--scene/2d/light_occluder_2d.cpp132
-rw-r--r--scene/2d/light_occluder_2d.h19
-rw-r--r--scene/2d/line_2d.cpp105
-rw-r--r--scene/2d/line_2d.h10
-rw-r--r--scene/2d/line_builder.cpp214
-rw-r--r--scene/2d/line_builder.h6
-rw-r--r--scene/2d/navigation2d.cpp556
-rw-r--r--scene/2d/navigation2d.h79
-rw-r--r--scene/2d/navigation_polygon.cpp291
-rw-r--r--scene/2d/navigation_polygon.h34
-rw-r--r--scene/2d/node_2d.cpp289
-rw-r--r--scene/2d/node_2d.h38
-rw-r--r--scene/2d/parallax_background.cpp128
-rw-r--r--scene/2d/parallax_background.h22
-rw-r--r--scene/2d/parallax_layer.cpp89
-rw-r--r--scene/2d/parallax_layer.h12
-rw-r--r--scene/2d/particles_2d.cpp814
-rw-r--r--scene/2d/particles_2d.h54
-rw-r--r--scene/2d/path_2d.cpp230
-rw-r--r--scene/2d/path_2d.h29
-rw-r--r--scene/2d/path_texture.cpp40
-rw-r--r--scene/2d/path_texture.h10
-rw-r--r--scene/2d/physics_body_2d.cpp1030
-rw-r--r--scene/2d/physics_body_2d.h86
-rw-r--r--scene/2d/polygon_2d.cpp300
-rw-r--r--scene/2d/polygon_2d.h23
-rw-r--r--scene/2d/position_2d.cpp13
-rw-r--r--scene/2d/position_2d.h7
-rw-r--r--scene/2d/ray_cast_2d.cpp178
-rw-r--r--scene/2d/ray_cast_2d.h18
-rw-r--r--scene/2d/remote_transform_2d.cpp32
-rw-r--r--scene/2d/remote_transform_2d.h7
-rw-r--r--scene/2d/screen_button.cpp240
-rw-r--r--scene/2d/screen_button.h25
-rw-r--r--scene/2d/sprite.cpp190
-rw-r--r--scene/2d/sprite.h17
-rw-r--r--scene/2d/tile_map.cpp923
-rw-r--r--scene/2d/tile_map.h114
-rw-r--r--scene/2d/visibility_notifier_2d.cpp218
-rw-r--r--scene/2d/visibility_notifier_2d.h34
-rw-r--r--scene/2d/y_sort.cpp19
-rw-r--r--scene/2d/y_sort.h4
-rw-r--r--scene/3d/area.cpp488
-rw-r--r--scene/3d/area.h46
-rw-r--r--scene/3d/baked_light_instance.cpp1437
-rw-r--r--scene/3d/baked_light_instance.h70
-rw-r--r--scene/3d/body_shape.cpp166
-rw-r--r--scene/3d/body_shape.h10
-rw-r--r--scene/3d/bone_attachment.cpp65
-rw-r--r--scene/3d/bone_attachment.h13
-rw-r--r--scene/3d/camera.cpp448
-rw-r--r--scene/3d/camera.h46
-rw-r--r--scene/3d/character_camera.cpp1
-rw-r--r--scene/3d/character_camera.h1
-rw-r--r--scene/3d/collision_object.cpp232
-rw-r--r--scene/3d/collision_object.h36
-rw-r--r--scene/3d/collision_polygon.cpp134
-rw-r--r--scene/3d/collision_polygon.h18
-rw-r--r--scene/3d/gi_probe.cpp1317
-rw-r--r--scene/3d/gi_probe.h72
-rw-r--r--scene/3d/immediate_geometry.cpp120
-rw-r--r--scene/3d/immediate_geometry.h27
-rw-r--r--scene/3d/interpolated_camera.cpp66
-rw-r--r--scene/3d/interpolated_camera.h8
-rw-r--r--scene/3d/light.cpp366
-rw-r--r--scene/3d/light.h45
-rw-r--r--scene/3d/listener.cpp62
-rw-r--r--scene/3d/listener.h15
-rw-r--r--scene/3d/mesh_instance.cpp166
-rw-r--r--scene/3d/mesh_instance.h28
-rw-r--r--scene/3d/multimesh_instance.cpp22
-rw-r--r--scene/3d/multimesh_instance.h10
-rw-r--r--scene/3d/navigation.cpp577
-rw-r--r--scene/3d/navigation.h94
-rw-r--r--scene/3d/navigation_mesh.cpp240
-rw-r--r--scene/3d/navigation_mesh.h28
-rw-r--r--scene/3d/particles.cpp2
-rw-r--r--scene/3d/particles.h4
-rw-r--r--scene/3d/path.cpp242
-rw-r--r--scene/3d/path.h25
-rw-r--r--scene/3d/physics_body.cpp942
-rw-r--r--scene/3d/physics_body.h89
-rw-r--r--scene/3d/physics_joint.cpp1080
-rw-r--r--scene/3d/physics_joint.h210
-rw-r--r--scene/3d/portal.cpp158
-rw-r--r--scene/3d/portal.h17
-rw-r--r--scene/3d/position_3d.cpp4
-rw-r--r--scene/3d/position_3d.h6
-rw-r--r--scene/3d/proximity_group.cpp45
-rw-r--r--scene/3d/proximity_group.h8
-rw-r--r--scene/3d/quad.cpp153
-rw-r--r--scene/3d/quad.h13
-rw-r--r--scene/3d/ray_cast.cpp139
-rw-r--r--scene/3d/ray_cast.h16
-rw-r--r--scene/3d/reflection_probe.cpp226
-rw-r--r--scene/3d/reflection_probe.h20
-rw-r--r--scene/3d/remote_transform.cpp30
-rw-r--r--scene/3d/remote_transform.h19
-rw-r--r--scene/3d/room_instance.cpp92
-rw-r--r--scene/3d/room_instance.h25
-rw-r--r--scene/3d/scenario_fx.cpp46
-rw-r--r--scene/3d/scenario_fx.h9
-rw-r--r--scene/3d/skeleton.cpp393
-rw-r--r--scene/3d/skeleton.h50
-rw-r--r--scene/3d/spatial.cpp407
-rw-r--r--scene/3d/spatial.h81
-rw-r--r--scene/3d/spatial_indexer.cpp2
-rw-r--r--scene/3d/sprite_3d.cpp721
-rw-r--r--scene/3d/sprite_3d.h67
-rw-r--r--scene/3d/test_cube.cpp8
-rw-r--r--scene/3d/test_cube.h9
-rw-r--r--scene/3d/vehicle_body.cpp743
-rw-r--r--scene/3d/vehicle_body.h98
-rw-r--r--scene/3d/visibility_notifier.cpp176
-rw-r--r--scene/3d/visibility_notifier.h33
-rw-r--r--scene/3d/visual_instance.cpp232
-rw-r--r--scene/3d/visual_instance.h62
-rw-r--r--scene/animation/animation_cache.cpp206
-rw-r--r--scene/animation/animation_cache.h29
-rw-r--r--scene/animation/animation_player.cpp911
-rw-r--r--scene/animation/animation_player.h162
-rw-r--r--scene/animation/animation_tree_player.cpp1485
-rw-r--r--scene/animation/animation_tree_player.h286
-rw-r--r--scene/animation/tween.cpp1038
-rw-r--r--scene/animation/tween.h167
-rw-r--r--scene/animation/tween_interpolaters.cpp450
-rw-r--r--scene/audio/audio_player.cpp184
-rw-r--r--scene/audio/audio_player.h16
-rw-r--r--scene/gui/base_button.cpp299
-rw-r--r--scene/gui/base_button.h39
-rw-r--r--scene/gui/box_container.cpp181
-rw-r--r--scene/gui/box_container.h27
-rw-r--r--scene/gui/button.cpp167
-rw-r--r--scene/gui/button.h23
-rw-r--r--scene/gui/button_array.cpp472
-rw-r--r--scene/gui/button_array.h46
-rw-r--r--scene/gui/center_container.cpp33
-rw-r--r--scene/gui/center_container.h7
-rw-r--r--scene/gui/check_box.cpp45
-rw-r--r--scene/gui/check_box.h15
-rw-r--r--scene/gui/check_button.cpp27
-rw-r--r--scene/gui/check_button.h6
-rw-r--r--scene/gui/color_picker.cpp406
-rw-r--r--scene/gui/color_picker.h45
-rw-r--r--scene/gui/color_ramp_edit.cpp292
-rw-r--r--scene/gui/color_ramp_edit.h15
-rw-r--r--scene/gui/color_rect.cpp19
-rw-r--r--scene/gui/color_rect.h10
-rw-r--r--scene/gui/container.cpp65
-rw-r--r--scene/gui/container.h9
-rw-r--r--scene/gui/control.cpp1831
-rw-r--r--scene/gui/control.h204
-rw-r--r--scene/gui/dialogs.cpp216
-rw-r--r--scene/gui/dialogs.h56
-rw-r--r--scene/gui/file_dialog.cpp593
-rw-r--r--scene/gui/file_dialog.h46
-rw-r--r--scene/gui/graph_edit.cpp862
-rw-r--r--scene/gui/graph_edit.h68
-rw-r--r--scene/gui/graph_node.cpp556
-rw-r--r--scene/gui/graph_node.h47
-rw-r--r--scene/gui/grid_container.cpp149
-rw-r--r--scene/gui/grid_container.h6
-rw-r--r--scene/gui/input_action.cpp70
-rw-r--r--scene/gui/input_action.h10
-rw-r--r--scene/gui/item_list.cpp1094
-rw-r--r--scene/gui/item_list.h51
-rw-r--r--scene/gui/label.cpp565
-rw-r--r--scene/gui/label.h28
-rw-r--r--scene/gui/line_edit.cpp648
-rw-r--r--scene/gui/line_edit.h15
-rw-r--r--scene/gui/link_button.cpp73
-rw-r--r--scene/gui/link_button.h12
-rw-r--r--scene/gui/margin_container.cpp18
-rw-r--r--scene/gui/margin_container.h4
-rw-r--r--scene/gui/menu_button.cpp39
-rw-r--r--scene/gui/menu_button.h11
-rw-r--r--scene/gui/option_button.cpp212
-rw-r--r--scene/gui/option_button.h26
-rw-r--r--scene/gui/panel.cpp10
-rw-r--r--scene/gui/panel.h10
-rw-r--r--scene/gui/panel_container.cpp46
-rw-r--r--scene/gui/panel_container.h5
-rw-r--r--scene/gui/patch_9_rect.cpp88
-rw-r--r--scene/gui/patch_9_rect.h12
-rw-r--r--scene/gui/popup.cpp160
-rw-r--r--scene/gui/popup.h26
-rw-r--r--scene/gui/popup_menu.cpp812
-rw-r--r--scene/gui/popup_menu.h83
-rw-r--r--scene/gui/progress_bar.cpp38
-rw-r--r--scene/gui/progress_bar.h6
-rw-r--r--scene/gui/range.cpp162
-rw-r--r--scene/gui/range.h17
-rw-r--r--scene/gui/reference_rect.cpp7
-rw-r--r--scene/gui/reference_rect.h4
-rw-r--r--scene/gui/rich_text_label.cpp1704
-rw-r--r--scene/gui/rich_text_label.h127
-rw-r--r--scene/gui/scroll_bar.cpp519
-rw-r--r--scene/gui/scroll_bar.h32
-rw-r--r--scene/gui/scroll_container.cpp310
-rw-r--r--scene/gui/scroll_container.h9
-rw-r--r--scene/gui/separator.cpp29
-rw-r--r--scene/gui/separator.h15
-rw-r--r--scene/gui/slider.cpp155
-rw-r--r--scene/gui/slider.h23
-rw-r--r--scene/gui/spin_box.cpp169
-rw-r--r--scene/gui/spin_box.h20
-rw-r--r--scene/gui/split_container.cpp290
-rw-r--r--scene/gui/split_container.h32
-rw-r--r--scene/gui/tab_container.cpp75
-rw-r--r--scene/gui/tab_container.h28
-rw-r--r--scene/gui/tabs.cpp491
-rw-r--r--scene/gui/tabs.h25
-rw-r--r--scene/gui/text_edit.cpp2903
-rw-r--r--scene/gui/text_edit.h154
-rw-r--r--scene/gui/texture_button.cpp141
-rw-r--r--scene/gui/texture_button.h21
-rw-r--r--scene/gui/texture_progress.cpp319
-rw-r--r--scene/gui/texture_progress.h14
-rw-r--r--scene/gui/texture_rect.cpp104
-rw-r--r--scene/gui/texture_rect.h13
-rw-r--r--scene/gui/tool_button.h3
-rw-r--r--scene/gui/tree.cpp2713
-rw-r--r--scene/gui/tree.h223
-rw-r--r--scene/gui/video_player.cpp168
-rw-r--r--scene/gui/video_player.h21
-rw-r--r--scene/gui/viewport_container.cpp41
-rw-r--r--scene/gui/viewport_container.h6
-rw-r--r--scene/io/resource_format_image.cpp4
-rw-r--r--scene/main/canvas_layer.cpp167
-rw-r--r--scene/main/canvas_layer.h15
-rw-r--r--scene/main/http_request.cpp377
-rw-r--r--scene/main/http_request.h21
-rw-r--r--scene/main/instance_placeholder.cpp51
-rw-r--r--scene/main/instance_placeholder.h13
-rw-r--r--scene/main/node.cpp1848
-rw-r--r--scene/main/node.h209
-rw-r--r--scene/main/resource_preloader.cpp101
-rw-r--r--scene/main/resource_preloader.h21
-rw-r--r--scene/main/scene_main_loop.cpp1417
-rw-r--r--scene/main/scene_main_loop.h246
-rw-r--r--scene/main/timer.cpp82
-rw-r--r--scene/main/timer.h7
-rw-r--r--scene/main/viewport.cpp1515
-rw-r--r--scene/main/viewport.h157
-rw-r--r--scene/register_scene_types.cpp271
-rw-r--r--scene/resources/animation.cpp1562
-rw-r--r--scene/resources/animation.h149
-rw-r--r--scene/resources/audio_stream_resampled.cpp1
-rw-r--r--scene/resources/audio_stream_sample.cpp435
-rw-r--r--scene/resources/audio_stream_sample.h36
-rw-r--r--scene/resources/baked_light.cpp1
-rw-r--r--scene/resources/baked_light.h2
-rw-r--r--scene/resources/bit_mask.cpp145
-rw-r--r--scene/resources/bit_mask.h21
-rw-r--r--scene/resources/bounds.cpp16
-rw-r--r--scene/resources/bounds.h8
-rw-r--r--scene/resources/box_shape.cpp32
-rw-r--r--scene/resources/box_shape.h6
-rw-r--r--scene/resources/canvas.cpp4
-rw-r--r--scene/resources/canvas.h4
-rw-r--r--scene/resources/capsule_shape.cpp70
-rw-r--r--scene/resources/capsule_shape.h6
-rw-r--r--scene/resources/capsule_shape_2d.cpp50
-rw-r--r--scene/resources/capsule_shape_2d.h10
-rw-r--r--scene/resources/circle_shape_2d.cpp31
-rw-r--r--scene/resources/circle_shape_2d.h9
-rw-r--r--scene/resources/color_ramp.cpp86
-rw-r--r--scene/resources/color_ramp.h59
-rw-r--r--scene/resources/concave_polygon_shape.cpp62
-rw-r--r--scene/resources/concave_polygon_shape.h33
-rw-r--r--scene/resources/concave_polygon_shape_2d.cpp42
-rw-r--r--scene/resources/concave_polygon_shape_2d.h12
-rw-r--r--scene/resources/convex_polygon_shape.cpp37
-rw-r--r--scene/resources/convex_polygon_shape.h7
-rw-r--r--scene/resources/convex_polygon_shape_2d.cpp53
-rw-r--r--scene/resources/convex_polygon_shape_2d.h14
-rw-r--r--scene/resources/curve.cpp824
-rw-r--r--scene/resources/curve.h57
-rw-r--r--scene/resources/default_theme/default_theme.cpp1166
-rw-r--r--scene/resources/default_theme/default_theme.h2
-rw-r--r--scene/resources/dynamic_font.cpp702
-rw-r--r--scene/resources/dynamic_font.h103
-rw-r--r--scene/resources/dynamic_font_stb.cpp334
-rw-r--r--scene/resources/dynamic_font_stb.h70
-rw-r--r--scene/resources/environment.cpp966
-rw-r--r--scene/resources/environment.h33
-rw-r--r--scene/resources/font.cpp407
-rw-r--r--scene/resources/font.h73
-rw-r--r--scene/resources/material.cpp1110
-rw-r--r--scene/resources/material.h106
-rw-r--r--scene/resources/mesh.cpp716
-rw-r--r--scene/resources/mesh.h133
-rw-r--r--scene/resources/mesh_data_tool.cpp485
-rw-r--r--scene/resources/mesh_data_tool.h42
-rw-r--r--scene/resources/mesh_library.cpp175
-rw-r--r--scene/resources/mesh_library.h32
-rw-r--r--scene/resources/multimesh.cpp183
-rw-r--r--scene/resources/multimesh.h24
-rw-r--r--scene/resources/packed_scene.cpp1128
-rw-r--r--scene/resources/packed_scene.h81
-rw-r--r--scene/resources/plane_shape.cpp31
-rw-r--r--scene/resources/plane_shape.h5
-rw-r--r--scene/resources/polygon_path_finder.cpp487
-rw-r--r--scene/resources/polygon_path_finder.h38
-rw-r--r--scene/resources/ray_shape.cpp17
-rw-r--r--scene/resources/ray_shape.h5
-rw-r--r--scene/resources/rectangle_shape_2d.cpp31
-rw-r--r--scene/resources/rectangle_shape_2d.h12
-rw-r--r--scene/resources/room.cpp22
-rw-r--r--scene/resources/room.h13
-rw-r--r--scene/resources/scene_format_text.cpp873
-rw-r--r--scene/resources/scene_format_text.h71
-rw-r--r--scene/resources/segment_shape_2d.cpp101
-rw-r--r--scene/resources/segment_shape_2d.h23
-rw-r--r--scene/resources/shader.cpp77
-rw-r--r--scene/resources/shader.h56
-rw-r--r--scene/resources/shader_graph.cpp47
-rw-r--r--scene/resources/shader_graph.h1
-rw-r--r--scene/resources/shape.cpp39
-rw-r--r--scene/resources/shape.h10
-rw-r--r--scene/resources/shape_2d.cpp82
-rw-r--r--scene/resources/shape_2d.h21
-rw-r--r--scene/resources/shape_line_2d.cpp52
-rw-r--r--scene/resources/shape_line_2d.h10
-rw-r--r--scene/resources/sky_box.cpp134
-rw-r--r--scene/resources/sky_box.h19
-rw-r--r--scene/resources/space_2d.cpp18
-rw-r--r--scene/resources/space_2d.h10
-rw-r--r--scene/resources/sphere_shape.cpp40
-rw-r--r--scene/resources/sphere_shape.h6
-rw-r--r--scene/resources/style_box.cpp290
-rw-r--r--scene/resources/style_box.h55
-rw-r--r--scene/resources/surface_tool.cpp737
-rw-r--r--scene/resources/surface_tool.h87
-rw-r--r--scene/resources/texture.cpp1111
-rw-r--r--scene/resources/texture.h237
-rw-r--r--scene/resources/theme.cpp690
-rw-r--r--scene/resources/theme.h171
-rw-r--r--scene/resources/tile_set.cpp373
-rw-r--r--scene/resources/tile_set.h51
-rw-r--r--scene/resources/video_stream.cpp6
-rw-r--r--scene/resources/video_stream.h50
-rw-r--r--scene/resources/world.cpp190
-rw-r--r--scene/resources/world.h29
-rw-r--r--scene/resources/world_2d.cpp234
-rw-r--r--scene/resources/world_2d.h28
-rw-r--r--scene/scene_string_names.cpp186
-rw-r--r--scene/scene_string_names.h22
-rw-r--r--servers/audio/audio_driver_dummy.cpp37
-rw-r--r--servers/audio/audio_driver_dummy.h14
-rw-r--r--servers/audio/audio_effect.cpp4
-rw-r--r--servers/audio/audio_effect.h13
-rw-r--r--servers/audio/audio_filter_sw.cpp244
-rw-r--r--servers/audio/audio_filter_sw.h43
-rw-r--r--servers/audio/audio_rb_resampler.cpp325
-rw-r--r--servers/audio/audio_rb_resampler.h92
-rw-r--r--servers/audio/audio_stream.cpp52
-rw-r--r--servers/audio/audio_stream.h59
-rw-r--r--servers/audio/effects/audio_effect_amplify.cpp31
-rw-r--r--servers/audio/effects/audio_effect_amplify.h18
-rw-r--r--servers/audio/effects/audio_effect_chorus.cpp370
-rw-r--r--servers/audio/effects/audio_effect_chorus.h64
-rw-r--r--servers/audio/effects/audio_effect_compressor.cpp152
-rw-r--r--servers/audio/effects/audio_effect_compressor.h28
-rw-r--r--servers/audio/effects/audio_effect_delay.cpp313
-rw-r--r--servers/audio/effects/audio_effect_delay.h25
-rw-r--r--servers/audio/effects/audio_effect_distortion.cpp148
-rw-r--r--servers/audio/effects/audio_effect_distortion.h23
-rw-r--r--servers/audio/effects/audio_effect_eq.cpp78
-rw-r--r--servers/audio/effects/audio_effect_eq.h48
-rw-r--r--servers/audio/effects/audio_effect_filter.cpp115
-rw-r--r--servers/audio/effects/audio_effect_filter.h77
-rw-r--r--servers/audio/effects/audio_effect_limiter.cpp77
-rw-r--r--servers/audio/effects/audio_effect_limiter.h21
-rw-r--r--servers/audio/effects/audio_effect_panner.cpp28
-rw-r--r--servers/audio/effects/audio_effect_panner.h18
-rw-r--r--servers/audio/effects/audio_effect_phaser.cpp128
-rw-r--r--servers/audio/effects/audio_effect_phaser.h35
-rw-r--r--servers/audio/effects/audio_effect_pitch_shift.cpp30
-rw-r--r--servers/audio/effects/audio_effect_pitch_shift.h52
-rw-r--r--servers/audio/effects/audio_effect_reverb.cpp161
-rw-r--r--servers/audio/effects/audio_effect_reverb.h19
-rw-r--r--servers/audio/effects/audio_effect_stereo_enhance.cpp119
-rw-r--r--servers/audio/effects/audio_effect_stereo_enhance.h20
-rw-r--r--servers/audio/effects/eq.cpp145
-rw-r--r--servers/audio/effects/eq.h43
-rw-r--r--servers/audio/effects/reverb.cpp279
-rw-r--r--servers/audio/effects/reverb.h39
-rw-r--r--servers/audio/reverb_sw.cpp520
-rw-r--r--servers/audio/reverb_sw.h16
-rw-r--r--servers/audio/voice_rb_sw.h36
-rw-r--r--servers/audio_server.cpp827
-rw-r--r--servers/audio_server.h157
-rw-r--r--servers/physics/area_pair_sw.cpp81
-rw-r--r--servers/physics/area_pair_sw.h15
-rw-r--r--servers/physics/area_sw.cpp172
-rw-r--r--servers/physics/area_sw.h93
-rw-r--r--servers/physics/body_pair_sw.cpp331
-rw-r--r--servers/physics/body_pair_sw.h22
-rw-r--r--servers/physics/body_sw.cpp394
-rw-r--r--servers/physics/body_sw.h262
-rw-r--r--servers/physics/broad_phase_basic.cpp135
-rw-r--r--servers/physics/broad_phase_basic.h34
-rw-r--r--servers/physics/broad_phase_octree.cpp76
-rw-r--r--servers/physics/broad_phase_octree.h21
-rw-r--r--servers/physics/broad_phase_sw.cpp5
-rw-r--r--servers/physics/broad_phase_sw.h33
-rw-r--r--servers/physics/collision_object_sw.cpp135
-rw-r--r--servers/physics/collision_object_sw.h66
-rw-r--r--servers/physics/collision_solver_sat.cpp1271
-rw-r--r--servers/physics/collision_solver_sat.h3
-rw-r--r--servers/physics/collision_solver_sw.cpp294
-rw-r--r--servers/physics/collision_solver_sw.h22
-rw-r--r--servers/physics/constraint_sw.h30
-rw-r--r--servers/physics/gjk_epa.cpp19
-rw-r--r--servers/physics/gjk_epa.h4
-rw-r--r--servers/physics/joints/cone_twist_joint_sw.cpp234
-rw-r--r--servers/physics/joints/cone_twist_joint_sw.h74
-rw-r--r--servers/physics/joints/generic_6dof_joint_sw.cpp563
-rw-r--r--servers/physics/joints/generic_6dof_joint_sw.h507
-rw-r--r--servers/physics/joints/hinge_joint_sw.cpp299
-rw-r--r--servers/physics/joints/hinge_joint_sw.h46
-rw-r--r--servers/physics/joints/jacobian_entry_sw.h123
-rw-r--r--servers/physics/joints/pin_joint_sw.cpp89
-rw-r--r--servers/physics/joints/pin_joint_sw.h29
-rw-r--r--servers/physics/joints/slider_joint_sw.cpp303
-rw-r--r--servers/physics/joints/slider_joint_sw.h87
-rw-r--r--servers/physics/joints_sw.h11
-rw-r--r--servers/physics/physics_server_sw.cpp747
-rw-r--r--servers/physics/physics_server_sw.h135
-rw-r--r--servers/physics/shape_sw.cpp1195
-rw-r--r--servers/physics/shape_sw.h233
-rw-r--r--servers/physics/space_sw.cpp561
-rw-r--r--servers/physics/space_sw.h84
-rw-r--r--servers/physics/step_sw.cpp201
-rw-r--r--servers/physics/step_sw.h12
-rw-r--r--servers/physics_2d/area_2d_sw.cpp176
-rw-r--r--servers/physics_2d/area_2d_sw.h91
-rw-r--r--servers/physics_2d/area_pair_2d_sw.cpp83
-rw-r--r--servers/physics_2d/area_pair_2d_sw.h15
-rw-r--r--servers/physics_2d/body_2d_sw.cpp394
-rw-r--r--servers/physics_2d/body_2d_sw.h241
-rw-r--r--servers/physics_2d/body_pair_2d_sw.cpp331
-rw-r--r--servers/physics_2d/body_pair_2d_sw.h22
-rw-r--r--servers/physics_2d/broad_phase_2d_basic.cpp120
-rw-r--r--servers/physics_2d/broad_phase_2d_basic.h36
-rw-r--r--servers/physics_2d/broad_phase_2d_hash_grid.cpp479
-rw-r--r--servers/physics_2d/broad_phase_2d_hash_grid.h80
-rw-r--r--servers/physics_2d/broad_phase_2d_sw.cpp5
-rw-r--r--servers/physics_2d/broad_phase_2d_sw.h35
-rw-r--r--servers/physics_2d/collision_object_2d_sw.cpp144
-rw-r--r--servers/physics_2d/collision_object_2d_sw.h68
-rw-r--r--servers/physics_2d/collision_solver_2d_sat.cpp1171
-rw-r--r--servers/physics_2d/collision_solver_2d_sat.h3
-rw-r--r--servers/physics_2d/collision_solver_2d_sw.cpp186
-rw-r--r--servers/physics_2d/collision_solver_2d_sw.h16
-rw-r--r--servers/physics_2d/constraint_2d_sw.h27
-rw-r--r--servers/physics_2d/joints_2d_sw.cpp260
-rw-r--r--servers/physics_2d/joints_2d_sw.h44
-rw-r--r--servers/physics_2d/physics_2d_server_sw.cpp613
-rw-r--r--servers/physics_2d/physics_2d_server_sw.h117
-rw-r--r--servers/physics_2d/physics_2d_server_wrap_mt.cpp78
-rw-r--r--servers/physics_2d/physics_2d_server_wrap_mt.h273
-rw-r--r--servers/physics_2d/shape_2d_sw.cpp878
-rw-r--r--servers/physics_2d/shape_2d_sw.h414
-rw-r--r--servers/physics_2d/space_2d_sw.cpp926
-rw-r--r--servers/physics_2d/space_2d_sw.h94
-rw-r--r--servers/physics_2d/step_2d_sw.cpp204
-rw-r--r--servers/physics_2d/step_2d_sw.h12
-rw-r--r--servers/physics_2d_server.cpp704
-rw-r--r--servers/physics_2d_server.h405
-rw-r--r--servers/physics_server.cpp767
-rw-r--r--servers/physics_server.h446
-rw-r--r--servers/register_server_types.cpp66
-rw-r--r--servers/server_wrap_mt_common.h1397
-rw-r--r--servers/visual/rasterizer.cpp11
-rw-r--r--servers/visual/rasterizer.h861
-rw-r--r--servers/visual/shader_language.cpp3466
-rw-r--r--servers/visual/shader_language.h172
-rw-r--r--servers/visual/shader_types.cpp242
-rw-r--r--servers/visual/shader_types.h14
-rw-r--r--servers/visual/visual_server_canvas.cpp902
-rw-r--r--servers/visual/visual_server_canvas.h156
-rw-r--r--servers/visual/visual_server_global.cpp14
-rw-r--r--servers/visual/visual_server_global.h4
-rw-r--r--servers/visual/visual_server_light_baker.cpp4
-rw-r--r--servers/visual/visual_server_light_baker.h7
-rw-r--r--servers/visual/visual_server_raster.cpp85
-rw-r--r--servers/visual/visual_server_raster.h770
-rw-r--r--servers/visual/visual_server_scene.cpp2230
-rw-r--r--servers/visual/visual_server_scene.h284
-rw-r--r--servers/visual/visual_server_viewport.cpp378
-rw-r--r--servers/visual/visual_server_viewport.h102
-rw-r--r--servers/visual_server.cpp1161
-rw-r--r--servers/visual_server.h859
1318 files changed, 140937 insertions, 166890 deletions
diff --git a/core/allocators.h b/core/allocators.h
index 14deeb8739..de92d02226 100644
--- a/core/allocators.h
+++ b/core/allocators.h
@@ -30,13 +30,13 @@
#define ALLOCATORS_H
#include "os/memory.h"
-template<int PREALLOC_COUNT=64, int MAX_HANDS=8>
+template <int PREALLOC_COUNT = 64, int MAX_HANDS = 8>
class BalloonAllocator {
enum {
- USED_FLAG=(1<<30),
- USED_MASK=USED_FLAG-1
+ USED_FLAG = (1 << 30),
+ USED_MASK = USED_FLAG - 1
};
struct Balloon {
@@ -46,7 +46,6 @@ class BalloonAllocator {
uint32_t hand;
};
-
struct Hand {
int used;
@@ -55,136 +54,132 @@ class BalloonAllocator {
Balloon *last;
};
-
Hand hands[MAX_HANDS];
-
-
public:
+ void *alloc(size_t p_size) {
- void* alloc(size_t p_size) {
+ size_t max = (1 << MAX_HANDS);
+ ERR_FAIL_COND_V(p_size > max, NULL);
- size_t max=(1<<MAX_HANDS);
- ERR_FAIL_COND_V( p_size>max, NULL );
+ unsigned int hand = 0;
- unsigned int hand=0;
+ while (p_size > (size_t)(1 << hand))
+ ++hand;
- while(p_size>(size_t)(1<<hand)) ++hand;
+ Hand &h = hands[hand];
- Hand &h=hands[hand];
+ if (h.used == h.allocated) {
- if (h.used==h.allocated) {
+ for (int i = 0; i < PREALLOC_COUNT; i++) {
- for(int i=0;i<PREALLOC_COUNT;i++) {
-
- Balloon *b = (Balloon*)memalloc(sizeof(Balloon)+(1<<hand));
- b->hand=hand;
+ Balloon *b = (Balloon *)memalloc(sizeof(Balloon) + (1 << hand));
+ b->hand = hand;
if (h.last) {
- b->prev=h.last;
- h.last->next=b;
- h.last=b;
+ b->prev = h.last;
+ h.last->next = b;
+ h.last = b;
} else {
- b->prev=NULL;
- h.last=b;
- h.first=b;
+ b->prev = NULL;
+ h.last = b;
+ h.first = b;
}
}
- h.last->next=NULL;
- h.allocated+=PREALLOC_COUNT;
+ h.last->next = NULL;
+ h.allocated += PREALLOC_COUNT;
}
- Balloon *pick=h.last;
+ Balloon *pick = h.last;
- ERR_FAIL_COND_V( (pick->hand&USED_FLAG), NULL );
+ ERR_FAIL_COND_V((pick->hand & USED_FLAG), NULL);
// remove last
- h.last=h.last->prev;
- h.last->next=NULL;
+ h.last = h.last->prev;
+ h.last->next = NULL;
- pick->next=h.first;
- h.first->prev=pick;
- pick->prev=NULL;
- h.first=pick;
+ pick->next = h.first;
+ h.first->prev = pick;
+ pick->prev = NULL;
+ h.first = pick;
h.used++;
- pick->hand|=USED_FLAG;
+ pick->hand |= USED_FLAG;
- return (void*)(pick+1);
+ return (void *)(pick + 1);
}
- void free(void* p_ptr) {
+ void free(void *p_ptr) {
- Balloon *b=(Balloon*)p_ptr;
- b-=1;
+ Balloon *b = (Balloon *)p_ptr;
+ b -= 1;
- ERR_FAIL_COND(!(b->hand&USED_FLAG) );
+ ERR_FAIL_COND(!(b->hand & USED_FLAG));
- b->hand=b->hand&USED_MASK; // not used
- int hand=b->hand;
+ b->hand = b->hand & USED_MASK; // not used
+ int hand = b->hand;
- Hand &h=hands[hand];
+ Hand &h = hands[hand];
- if (b==h.first)
- h.first=b->next;
+ if (b == h.first)
+ h.first = b->next;
if (b->prev)
- b->prev->next=b->next;
+ b->prev->next = b->next;
if (b->next)
- b->next->prev=b->prev;
+ b->next->prev = b->prev;
- if (h.last!=b) {
- h.last->next=b;
- b->prev=h.last;
- b->next=NULL;
- h.last=b;
+ if (h.last != b) {
+ h.last->next = b;
+ b->prev = h.last;
+ b->next = NULL;
+ h.last = b;
}
h.used--;
- if (h.used<=(h.allocated-(PREALLOC_COUNT*2))) { // this is done to ensure no alloc/free is done constantly
+ if (h.used <= (h.allocated - (PREALLOC_COUNT * 2))) { // this is done to ensure no alloc/free is done constantly
- for(int i=0;i<PREALLOC_COUNT;i++) {
- ERR_CONTINUE( h.last->hand& USED_FLAG );
+ for (int i = 0; i < PREALLOC_COUNT; i++) {
+ ERR_CONTINUE(h.last->hand & USED_FLAG);
- Balloon *new_last=h.last->prev;
+ Balloon *new_last = h.last->prev;
if (new_last)
- new_last->next=NULL;
- memfree( h.last );
- h.last=new_last;
+ new_last->next = NULL;
+ memfree(h.last);
+ h.last = new_last;
}
- h.allocated-=PREALLOC_COUNT;
+ h.allocated -= PREALLOC_COUNT;
}
}
BalloonAllocator() {
- for(int i=0;i<MAX_HANDS;i++) {
+ for (int i = 0; i < MAX_HANDS; i++) {
- hands[i].allocated=0;
- hands[i].used=0;
- hands[i].first=NULL;
- hands[i].last=NULL;
+ hands[i].allocated = 0;
+ hands[i].used = 0;
+ hands[i].first = NULL;
+ hands[i].last = NULL;
}
-
}
void clear() {
- for(int i=0;i<MAX_HANDS;i++) {
+ for (int i = 0; i < MAX_HANDS; i++) {
- while(hands[i].first) {
+ while (hands[i].first) {
- Balloon *b=hands[i].first;
- hands[i].first=b->next;
+ Balloon *b = hands[i].first;
+ hands[i].first = b->next;
memfree(b);
}
- hands[i].allocated=0;
- hands[i].used=0;
- hands[i].first=NULL;
- hands[i].last=NULL;
+ hands[i].allocated = 0;
+ hands[i].used = 0;
+ hands[i].first = NULL;
+ hands[i].last = NULL;
}
}
@@ -194,5 +189,4 @@ public:
}
};
-
#endif // ALLOCATORS_H
diff --git a/core/array.cpp b/core/array.cpp
index 16598a044d..80aca6f850 100644
--- a/core/array.cpp
+++ b/core/array.cpp
@@ -28,10 +28,10 @@
/*************************************************************************/
#include "array.h"
-#include "vector.h"
#include "hashfuncs.h"
-#include "variant.h"
#include "object.h"
+#include "variant.h"
+#include "vector.h"
struct ArrayPrivate {
@@ -39,7 +39,7 @@ struct ArrayPrivate {
Vector<Variant> array;
};
-void Array::_ref(const Array& p_from) const {
+void Array::_ref(const Array &p_from) const {
ArrayPrivate *_fp = p_from._p;
@@ -55,8 +55,6 @@ void Array::_ref(const Array& p_from) const {
_unref();
_p = p_from._p;
-
-
}
void Array::_unref() const {
@@ -67,19 +65,17 @@ void Array::_unref() const {
if (_p->refcount.unref()) {
memdelete(_p);
}
- _p=NULL;
+ _p = NULL;
}
-
-Variant& Array::operator[](int p_idx) {
+Variant &Array::operator[](int p_idx) {
return _p->array[p_idx];
}
-const Variant& Array::operator[](int p_idx) const {
+const Variant &Array::operator[](int p_idx) const {
return _p->array[p_idx];
-
}
int Array::size() const {
@@ -95,27 +91,26 @@ void Array::clear() {
_p->array.clear();
}
+bool Array::operator==(const Array &p_array) const {
-bool Array::operator==(const Array& p_array) const {
-
- return _p==p_array._p;
+ return _p == p_array._p;
}
uint32_t Array::hash() const {
- uint32_t h=hash_djb2_one_32(0);
+ uint32_t h = hash_djb2_one_32(0);
- for (int i=0;i<_p->array.size();i++) {
+ for (int i = 0; i < _p->array.size(); i++) {
- h = hash_djb2_one_32( _p->array[i].hash(), h);
+ h = hash_djb2_one_32(_p->array[i].hash(), h);
}
return h;
}
-void Array::operator=(const Array& p_array) {
+void Array::operator=(const Array &p_array) {
_ref(p_array);
}
-void Array::push_back(const Variant& p_value) {
+void Array::push_back(const Variant &p_value) {
_p->array.push_back(p_value);
}
@@ -125,12 +120,12 @@ Error Array::resize(int p_new_size) {
return _p->array.resize(p_new_size);
}
-void Array::insert(int p_pos, const Variant& p_value) {
+void Array::insert(int p_pos, const Variant &p_value) {
- _p->array.insert(p_pos,p_value);
+ _p->array.insert(p_pos, p_value);
}
-void Array::erase(const Variant& p_value) {
+void Array::erase(const Variant &p_value) {
_p->array.erase(p_value);
}
@@ -145,12 +140,12 @@ Variant Array::back() const {
return operator[](_p->array.size() - 1);
}
-int Array::find(const Variant& p_value, int p_from) const {
+int Array::find(const Variant &p_value, int p_from) const {
return _p->array.find(p_value, p_from);
}
-int Array::rfind(const Variant& p_value, int p_from) const {
+int Array::rfind(const Variant &p_value, int p_from) const {
if (_p->array.size() == 0)
return -1;
@@ -164,9 +159,9 @@ int Array::rfind(const Variant& p_value, int p_from) const {
p_from = _p->array.size() - 1;
}
- for (int i=p_from; i>=0; i--) {
+ for (int i = p_from; i >= 0; i--) {
- if(_p->array[i] == p_value){
+ if (_p->array[i] == p_value) {
return i;
};
};
@@ -174,20 +169,20 @@ int Array::rfind(const Variant& p_value, int p_from) const {
return -1;
}
-int Array::find_last(const Variant& p_value) const {
+int Array::find_last(const Variant &p_value) const {
return rfind(p_value);
}
-int Array::count(const Variant& p_value) const {
+int Array::count(const Variant &p_value) const {
- if(_p->array.size() == 0)
+ if (_p->array.size() == 0)
return 0;
- int amount=0;
- for (int i=0; i<_p->array.size(); i++) {
+ int amount = 0;
+ for (int i = 0; i < _p->array.size(); i++) {
- if(_p->array[i] == p_value){
+ if (_p->array[i] == p_value) {
amount++;
};
};
@@ -195,7 +190,7 @@ int Array::count(const Variant& p_value) const {
return amount;
}
-bool Array::has(const Variant& p_value) const {
+bool Array::has(const Variant &p_value) const {
return _p->array.find(p_value, 0) != -1;
}
@@ -204,25 +199,24 @@ void Array::remove(int p_pos) {
_p->array.remove(p_pos);
}
+void Array::set(int p_idx, const Variant &p_value) {
-void Array::set(int p_idx,const Variant& p_value) {
-
- operator[](p_idx)=p_value;
+ operator[](p_idx) = p_value;
}
-const Variant& Array::get(int p_idx) const {
+const Variant &Array::get(int p_idx) const {
return operator[](p_idx);
}
struct _ArrayVariantSort {
- _FORCE_INLINE_ bool operator()(const Variant& p_l, const Variant& p_r) const {
- bool valid=false;
+ _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
+ bool valid = false;
Variant res;
- Variant::evaluate(Variant::OP_LESS,p_l,p_r,res,valid);
+ Variant::evaluate(Variant::OP_LESS, p_l, p_r, res, valid);
if (!valid)
- res=false;
+ res = false;
return res;
}
};
@@ -230,7 +224,6 @@ struct _ArrayVariantSort {
void Array::sort() {
_p->array.sort_custom<_ArrayVariantSort>();
-
}
struct _ArrayVariantSortCustom {
@@ -238,40 +231,37 @@ struct _ArrayVariantSortCustom {
Object *obj;
StringName func;
- _FORCE_INLINE_ bool operator()(const Variant& p_l, const Variant& p_r) const {
+ _FORCE_INLINE_ bool operator()(const Variant &p_l, const Variant &p_r) const {
- const Variant*args[2]={&p_l,&p_r};
+ const Variant *args[2] = { &p_l, &p_r };
Variant::CallError err;
- bool res = obj->call(func,args,2,err);
- if (err.error!=Variant::CallError::CALL_OK)
- res=false;
+ bool res = obj->call(func, args, 2, err);
+ if (err.error != Variant::CallError::CALL_OK)
+ res = false;
return res;
-
}
};
-void Array::sort_custom(Object *p_obj,const StringName& p_function){
+void Array::sort_custom(Object *p_obj, const StringName &p_function) {
ERR_FAIL_NULL(p_obj);
- SortArray<Variant,_ArrayVariantSortCustom> avs;
- avs.compare.obj=p_obj;
- avs.compare.func=p_function;
- avs.sort(_p->array.ptr(),_p->array.size());
-
+ SortArray<Variant, _ArrayVariantSortCustom> avs;
+ avs.compare.obj = p_obj;
+ avs.compare.func = p_function;
+ avs.sort(_p->array.ptr(), _p->array.size());
}
-void Array::invert(){
+void Array::invert() {
_p->array.invert();
}
+void Array::push_front(const Variant &p_value) {
-void Array::push_front(const Variant& p_value) {
-
- _p->array.insert(0,p_value);
+ _p->array.insert(0, p_value);
}
-Variant Array::pop_back(){
+Variant Array::pop_back() {
if (!_p->array.empty()) {
int n = _p->array.size() - 1;
@@ -280,10 +270,9 @@ Variant Array::pop_back(){
return ret;
}
return Variant();
-
}
-Variant Array::pop_front(){
+Variant Array::pop_front() {
if (!_p->array.empty()) {
Variant ret = _p->array.get(0);
@@ -291,21 +280,17 @@ Variant Array::pop_front(){
return ret;
}
return Variant();
-
}
+Array::Array(const Array &p_from) {
-Array::Array(const Array& p_from) {
-
- _p=NULL;
+ _p = NULL;
_ref(p_from);
-
}
Array::Array() {
- _p = memnew( ArrayPrivate );
+ _p = memnew(ArrayPrivate);
_p->refcount.init();
-
}
Array::~Array() {
diff --git a/core/array.h b/core/array.h
index 16ab16002c..f9ba9f7706 100644
--- a/core/array.h
+++ b/core/array.h
@@ -38,56 +38,54 @@ class StringName;
class Array {
mutable ArrayPrivate *_p;
- void _ref(const Array& p_from) const;
+ void _ref(const Array &p_from) const;
void _unref() const;
public:
+ Variant &operator[](int p_idx);
+ const Variant &operator[](int p_idx) const;
- Variant& operator[](int p_idx);
- const Variant& operator[](int p_idx) const;
-
- void set(int p_idx,const Variant& p_value);
- const Variant& get(int p_idx) const;
+ void set(int p_idx, const Variant &p_value);
+ const Variant &get(int p_idx) const;
int size() const;
bool empty() const;
void clear();
- bool operator==(const Array& p_array) const;
+ bool operator==(const Array &p_array) const;
uint32_t hash() const;
- void operator=(const Array& p_array);
+ void operator=(const Array &p_array);
- void push_back(const Variant& p_value);
- _FORCE_INLINE_ void append(const Variant& p_value) { push_back(p_value); } //for python compatibility
+ void push_back(const Variant &p_value);
+ _FORCE_INLINE_ void append(const Variant &p_value) { push_back(p_value); } //for python compatibility
Error resize(int p_new_size);
- void insert(int p_pos, const Variant& p_value);
+ void insert(int p_pos, const Variant &p_value);
void remove(int p_pos);
Variant front() const;
Variant back() const;
void sort();
- void sort_custom(Object *p_obj,const StringName& p_function);
+ void sort_custom(Object *p_obj, const StringName &p_function);
void invert();
- int find(const Variant& p_value, int p_from=0) const;
- int rfind(const Variant& p_value, int p_from=-1) const;
- int find_last(const Variant& p_value) const;
- int count(const Variant& p_value) const;
- bool has(const Variant& p_value) const;
+ int find(const Variant &p_value, int p_from = 0) const;
+ int rfind(const Variant &p_value, int p_from = -1) const;
+ int find_last(const Variant &p_value) const;
+ int count(const Variant &p_value) const;
+ bool has(const Variant &p_value) const;
- void erase(const Variant& p_value);
+ void erase(const Variant &p_value);
- void push_front(const Variant& p_value);
+ void push_front(const Variant &p_value);
Variant pop_back();
Variant pop_front();
- Array(const Array& p_from);
+ Array(const Array &p_from);
Array();
~Array();
-
};
#endif // ARRAY_H
diff --git a/core/bind/core_bind.cpp b/core/bind/core_bind.cpp
index 08e1a311fa..ce3d65b448 100644
--- a/core/bind/core_bind.cpp
+++ b/core/bind/core_bind.cpp
@@ -27,21 +27,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "core_bind.h"
-#include "os/os.h"
+#include "core/global_config.h"
#include "geometry.h"
-#include "io/marshalls.h"
#include "io/base64.h"
-#include "core/global_config.h"
#include "io/file_access_encrypted.h"
+#include "io/marshalls.h"
#include "os/keyboard.h"
+#include "os/os.h"
/**
* Time constants borrowed from loc_time.h
*/
-#define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */
-#define SECS_DAY (24L * 60L * 60L)
-#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
-#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
+#define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */
+#define SECS_DAY (24L * 60L * 60L)
+#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
+#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
#define SECOND_KEY "second"
#define MINUTE_KEY "minute"
#define HOUR_KEY "hour"
@@ -57,24 +57,24 @@ static const unsigned int MONTH_DAYS_TABLE[2][12] = {
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};
-_ResourceLoader *_ResourceLoader::singleton=NULL;
+_ResourceLoader *_ResourceLoader::singleton = NULL;
-Ref<ResourceInteractiveLoader> _ResourceLoader::load_interactive(const String& p_path,const String& p_type_hint) {
- return ResourceLoader::load_interactive(p_path,p_type_hint);
+Ref<ResourceInteractiveLoader> _ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint) {
+ return ResourceLoader::load_interactive(p_path, p_type_hint);
}
-RES _ResourceLoader::load(const String &p_path,const String& p_type_hint, bool p_no_cache) {
+RES _ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache) {
- RES ret = ResourceLoader::load(p_path,p_type_hint, p_no_cache);
+ RES ret = ResourceLoader::load(p_path, p_type_hint, p_no_cache);
return ret;
}
-PoolVector<String> _ResourceLoader::get_recognized_extensions_for_type(const String& p_type) {
+PoolVector<String> _ResourceLoader::get_recognized_extensions_for_type(const String &p_type) {
List<String> exts;
- ResourceLoader::get_recognized_extensions_for_type(p_type,&exts);
+ ResourceLoader::get_recognized_extensions_for_type(p_type, &exts);
PoolVector<String> ret;
- for(List<String>::Element *E=exts.front();E;E=E->next()) {
+ for (List<String>::Element *E = exts.front(); E; E = E->next()) {
ret.push_back(E->get());
}
@@ -87,13 +87,13 @@ void _ResourceLoader::set_abort_on_missing_resources(bool p_abort) {
ResourceLoader::set_abort_on_missing_resources(p_abort);
}
-PoolStringArray _ResourceLoader::get_dependencies(const String& p_path) {
+PoolStringArray _ResourceLoader::get_dependencies(const String &p_path) {
List<String> deps;
ResourceLoader::get_dependencies(p_path, &deps);
PoolStringArray ret;
- for(List<String>::Element *E=deps.front();E;E=E->next()) {
+ for (List<String>::Element *E = deps.front(); E; E = E->next()) {
ret.push_back(E->get());
}
@@ -106,50 +106,46 @@ bool _ResourceLoader::has(const String &p_path) {
return ResourceCache::has(local_path);
};
-
void _ResourceLoader::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("load_interactive:ResourceInteractiveLoader","path","type_hint"),&_ResourceLoader::load_interactive,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("load:Resource","path","type_hint", "p_no_cache"),&_ResourceLoader::load,DEFVAL(""), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type","type"),&_ResourceLoader::get_recognized_extensions_for_type);
- ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources","abort"),&_ResourceLoader::set_abort_on_missing_resources);
- ClassDB::bind_method(D_METHOD("get_dependencies","path"),&_ResourceLoader::get_dependencies);
- ClassDB::bind_method(D_METHOD("has","path"),&_ResourceLoader::has);
+ ClassDB::bind_method(D_METHOD("load_interactive:ResourceInteractiveLoader", "path", "type_hint"), &_ResourceLoader::load_interactive, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("load:Resource", "path", "type_hint", "p_no_cache"), &_ResourceLoader::load, DEFVAL(""), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_recognized_extensions_for_type", "type"), &_ResourceLoader::get_recognized_extensions_for_type);
+ ClassDB::bind_method(D_METHOD("set_abort_on_missing_resources", "abort"), &_ResourceLoader::set_abort_on_missing_resources);
+ ClassDB::bind_method(D_METHOD("get_dependencies", "path"), &_ResourceLoader::get_dependencies);
+ ClassDB::bind_method(D_METHOD("has", "path"), &_ResourceLoader::has);
}
_ResourceLoader::_ResourceLoader() {
- singleton=this;
+ singleton = this;
}
+Error _ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
-Error _ResourceSaver::save(const String &p_path,const RES& p_resource, uint32_t p_flags) {
-
- ERR_FAIL_COND_V(p_resource.is_null(),ERR_INVALID_PARAMETER);
- return ResourceSaver::save(p_path,p_resource, p_flags);
+ ERR_FAIL_COND_V(p_resource.is_null(), ERR_INVALID_PARAMETER);
+ return ResourceSaver::save(p_path, p_resource, p_flags);
}
-PoolVector<String> _ResourceSaver::get_recognized_extensions(const RES& p_resource) {
+PoolVector<String> _ResourceSaver::get_recognized_extensions(const RES &p_resource) {
- ERR_FAIL_COND_V(p_resource.is_null(),PoolVector<String>());
+ ERR_FAIL_COND_V(p_resource.is_null(), PoolVector<String>());
List<String> exts;
- ResourceSaver::get_recognized_extensions(p_resource,&exts);
+ ResourceSaver::get_recognized_extensions(p_resource, &exts);
PoolVector<String> ret;
- for(List<String>::Element *E=exts.front();E;E=E->next()) {
+ for (List<String>::Element *E = exts.front(); E; E = E->next()) {
ret.push_back(E->get());
}
return ret;
}
-_ResourceSaver *_ResourceSaver::singleton=NULL;
-
+_ResourceSaver *_ResourceSaver::singleton = NULL;
void _ResourceSaver::_bind_methods() {
- ClassDB::bind_method(D_METHOD("save","path","resource:Resource","flags"),&_ResourceSaver::save,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_recognized_extensions","type"),&_ResourceSaver::get_recognized_extensions);
+ ClassDB::bind_method(D_METHOD("save", "path", "resource:Resource", "flags"), &_ResourceSaver::save, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_recognized_extensions", "type"), &_ResourceSaver::get_recognized_extensions);
BIND_CONSTANT(FLAG_RELATIVE_PATHS);
BIND_CONSTANT(FLAG_BUNDLE_RESOURCES);
@@ -161,21 +157,18 @@ void _ResourceSaver::_bind_methods() {
_ResourceSaver::_ResourceSaver() {
- singleton=this;
+ singleton = this;
}
-
/////////////////OS
-
Point2 _OS::get_mouse_pos() const {
return OS::get_singleton()->get_mouse_pos();
}
-void _OS::set_window_title(const String& p_title) {
+void _OS::set_window_title(const String &p_title) {
OS::get_singleton()->set_window_title(p_title);
-
}
int _OS::get_mouse_button_state() const {
@@ -191,44 +184,37 @@ bool _OS::has_touchscreen_ui_hint() const {
return OS::get_singleton()->has_touchscreen_ui_hint();
}
-void _OS::set_clipboard(const String& p_text) {
-
+void _OS::set_clipboard(const String &p_text) {
OS::get_singleton()->set_clipboard(p_text);
}
String _OS::get_clipboard() const {
return OS::get_singleton()->get_clipboard();
-
}
-void _OS::set_video_mode(const Size2& p_size, bool p_fullscreen,bool p_resizeable,int p_screen) {
+void _OS::set_video_mode(const Size2 &p_size, bool p_fullscreen, bool p_resizeable, int p_screen) {
OS::VideoMode vm;
- vm.width=p_size.width;
- vm.height=p_size.height;
- vm.fullscreen=p_fullscreen;
- vm.resizable=p_resizeable;
- OS::get_singleton()->set_video_mode( vm,p_screen);
-
-
+ vm.width = p_size.width;
+ vm.height = p_size.height;
+ vm.fullscreen = p_fullscreen;
+ vm.resizable = p_resizeable;
+ OS::get_singleton()->set_video_mode(vm, p_screen);
}
Size2 _OS::get_video_mode(int p_screen) const {
OS::VideoMode vm;
vm = OS::get_singleton()->get_video_mode(p_screen);
- return Size2(vm.width,vm.height);
-
+ return Size2(vm.width, vm.height);
}
bool _OS::is_video_mode_fullscreen(int p_screen) const {
OS::VideoMode vm;
vm = OS::get_singleton()->get_video_mode(p_screen);
return vm.fullscreen;
-
}
-
int _OS::get_screen_count() const {
return OS::get_singleton()->get_screen_count();
}
@@ -251,14 +237,14 @@ Size2 _OS::get_screen_size(int p_screen) const {
int _OS::get_screen_dpi(int p_screen) const {
- return OS::get_singleton()->get_screen_dpi(p_screen);
+ return OS::get_singleton()->get_screen_dpi(p_screen);
}
Point2 _OS::get_window_position() const {
return OS::get_singleton()->get_window_position();
}
-void _OS::set_window_position(const Point2& p_position) {
+void _OS::set_window_position(const Point2 &p_position) {
OS::get_singleton()->set_window_position(p_position);
}
@@ -266,7 +252,7 @@ Size2 _OS::get_window_size() const {
return OS::get_singleton()->get_window_size();
}
-void _OS::set_window_size(const Size2& p_size) {
+void _OS::set_window_size(const Size2 &p_size) {
OS::get_singleton()->set_window_size(p_size);
}
@@ -325,11 +311,11 @@ bool _OS::is_video_mode_resizable(int p_screen) const {
Array _OS::get_fullscreen_mode_list(int p_screen) const {
List<OS::VideoMode> vmlist;
- OS::get_singleton()->get_fullscreen_mode_list(&vmlist,p_screen);
+ OS::get_singleton()->get_fullscreen_mode_list(&vmlist, p_screen);
Array vmarr;
- for(List<OS::VideoMode>::Element *E=vmlist.front();E;E=E->next() ){
+ for (List<OS::VideoMode>::Element *E = vmlist.front(); E; E = E->next()) {
- vmarr.push_back(Size2(E->get().width,E->get().height));
+ vmarr.push_back(Size2(E->get().width, E->get().height));
}
return vmarr;
@@ -354,22 +340,20 @@ Error _OS::shell_open(String p_uri) {
return OS::get_singleton()->shell_open(p_uri);
};
-
-int _OS::execute(const String& p_path, const Vector<String> & p_arguments, bool p_blocking, Array p_output) {
+int _OS::execute(const String &p_path, const Vector<String> &p_arguments, bool p_blocking, Array p_output) {
OS::ProcessID pid;
List<String> args;
- for(int i=0;i<p_arguments.size();i++)
+ for (int i = 0; i < p_arguments.size(); i++)
args.push_back(p_arguments[i]);
String pipe;
- Error err = OS::get_singleton()->execute(p_path,args,p_blocking,&pid, &pipe);
+ Error err = OS::get_singleton()->execute(p_path, args, p_blocking, &pid, &pipe);
p_output.clear();
p_output.push_back(pipe);
if (err != OK)
return -1;
else
return pid;
-
}
Error _OS::kill(int p_pid) {
@@ -381,12 +365,11 @@ int _OS::get_process_ID() const {
return OS::get_singleton()->get_process_ID();
};
-
-bool _OS::has_environment(const String& p_var) const {
+bool _OS::has_environment(const String &p_var) const {
return OS::get_singleton()->has_environment(p_var);
}
-String _OS::get_environment(const String& p_var) const {
+String _OS::get_environment(const String &p_var) const {
return OS::get_singleton()->get_environment(p_var);
}
@@ -399,7 +382,7 @@ Vector<String> _OS::get_cmdline_args() {
List<String> cmdline = OS::get_singleton()->get_cmdline_args();
Vector<String> cmdlinev;
- for(List<String>::Element *E=cmdline.front();E;E=E->next()) {
+ for (List<String>::Element *E = cmdline.front(); E; E = E->next()) {
cmdlinev.push_back(E->get());
}
@@ -413,13 +396,13 @@ String _OS::get_locale() const {
}
String _OS::get_latin_keyboard_variant() const {
- switch( OS::get_singleton()->get_latin_keyboard_variant() ) {
+ switch (OS::get_singleton()->get_latin_keyboard_variant()) {
case OS::LATIN_KEYBOARD_QWERTY: return "QWERTY";
case OS::LATIN_KEYBOARD_QWERTZ: return "QWERTZ";
case OS::LATIN_KEYBOARD_AZERTY: return "AZERTY";
case OS::LATIN_KEYBOARD_QZERTY: return "QZERTY";
case OS::LATIN_KEYBOARD_DVORAK: return "DVORAK";
- case OS::LATIN_KEYBOARD_NEO : return "NEO";
+ case OS::LATIN_KEYBOARD_NEO: return "NEO";
default: return "ERROR";
}
}
@@ -429,14 +412,12 @@ String _OS::get_model_name() const {
return OS::get_singleton()->get_model_name();
}
-
-
bool _OS::is_ok_left_and_cancel_right() const {
return OS::get_singleton()->get_swap_ok_cancel();
}
-Error _OS::set_thread_name(const String& p_name) {
+Error _OS::set_thread_name(const String &p_name) {
return Thread::set_name(p_name);
};
@@ -509,22 +490,19 @@ struct Time {
int _OS::get_static_memory_usage() const {
return OS::get_singleton()->get_static_memory_usage();
-
}
int _OS::get_static_memory_peak_usage() const {
return OS::get_singleton()->get_static_memory_peak_usage();
-
}
-int _OS::get_dynamic_memory_usage() const{
+int _OS::get_dynamic_memory_usage() const {
return OS::get_singleton()->get_dynamic_memory_usage();
}
-
-void _OS::set_icon(const Image& p_icon) {
+void _OS::set_icon(const Image &p_icon) {
OS::get_singleton()->set_icon(p_icon);
}
@@ -551,7 +529,7 @@ Dictionary _OS::get_datetime(bool utc) const {
List<Variant> keys;
timed.get_key_list(&keys);
- for(int i = 0; i < keys.size(); i++) {
+ for (int i = 0; i < keys.size(); i++) {
dated[keys[i]] = timed[keys[i]];
}
@@ -562,11 +540,11 @@ Dictionary _OS::get_date(bool utc) const {
OS::Date date = OS::get_singleton()->get_date(utc);
Dictionary dated;
- dated[YEAR_KEY]=date.year;
- dated[MONTH_KEY]=date.month;
- dated[DAY_KEY]=date.day;
- dated[WEEKDAY_KEY]=date.weekday;
- dated[DST_KEY]=date.dst;
+ dated[YEAR_KEY] = date.year;
+ dated[MONTH_KEY] = date.month;
+ dated[DAY_KEY] = date.day;
+ dated[WEEKDAY_KEY] = date.weekday;
+ dated[DST_KEY] = date.dst;
return dated;
}
@@ -574,9 +552,9 @@ Dictionary _OS::get_time(bool utc) const {
OS::Time time = OS::get_singleton()->get_time(utc);
Dictionary timed;
- timed[HOUR_KEY]=time.hour;
- timed[MINUTE_KEY]=time.min;
- timed[SECOND_KEY]=time.sec;
+ timed[HOUR_KEY] = time.hour;
+ timed[MINUTE_KEY] = time.min;
+ timed[SECOND_KEY] = time.sec;
return timed;
}
@@ -603,12 +581,12 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
// Get all time values from the dictionary, set to zero if it doesn't exist.
// Risk incorrect calculation over throwing errors
- unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]): 0);
- unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]): 0);
- unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]): 0);
- unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]): 0);
- unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) -1: 0);
- unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]):0);
+ unsigned int second = ((datetime.has(SECOND_KEY)) ? static_cast<unsigned int>(datetime[SECOND_KEY]) : 0);
+ unsigned int minute = ((datetime.has(MINUTE_KEY)) ? static_cast<unsigned int>(datetime[MINUTE_KEY]) : 0);
+ unsigned int hour = ((datetime.has(HOUR_KEY)) ? static_cast<unsigned int>(datetime[HOUR_KEY]) : 0);
+ unsigned int day = ((datetime.has(DAY_KEY)) ? static_cast<unsigned int>(datetime[DAY_KEY]) : 0);
+ unsigned int month = ((datetime.has(MONTH_KEY)) ? static_cast<unsigned int>(datetime[MONTH_KEY]) - 1 : 0);
+ unsigned int year = ((datetime.has(YEAR_KEY)) ? static_cast<unsigned int>(datetime[YEAR_KEY]) : 0);
/// How many days come before each month (0-12)
static const unsigned short int DAYS_PAST_THIS_YEAR_TABLE[2][13] = {
@@ -619,41 +597,40 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
};
ERR_EXPLAIN("Invalid second value of: " + itos(second));
- ERR_FAIL_COND_V( second > 59, 0);
+ ERR_FAIL_COND_V(second > 59, 0);
ERR_EXPLAIN("Invalid minute value of: " + itos(minute));
- ERR_FAIL_COND_V( minute > 59, 0);
+ ERR_FAIL_COND_V(minute > 59, 0);
ERR_EXPLAIN("Invalid hour value of: " + itos(hour));
- ERR_FAIL_COND_V( hour > 23, 0);
+ ERR_FAIL_COND_V(hour > 23, 0);
- ERR_EXPLAIN("Invalid month value of: " + itos(month+1));
- ERR_FAIL_COND_V( month+1 > 12, 0);
+ ERR_EXPLAIN("Invalid month value of: " + itos(month + 1));
+ ERR_FAIL_COND_V(month + 1 > 12, 0);
// Do this check after month is tested as valid
- ERR_EXPLAIN("Invalid day value of: " + itos(day) + " which is larger than "+ itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month]));
- ERR_FAIL_COND_V( day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month], 0);
+ ERR_EXPLAIN("Invalid day value of: " + itos(day) + " which is larger than " + itos(MONTH_DAYS_TABLE[LEAPYEAR(year)][month]));
+ ERR_FAIL_COND_V(day > MONTH_DAYS_TABLE[LEAPYEAR(year)][month], 0);
// Calculate all the seconds from months past in this year
uint64_t SECONDS_FROM_MONTHS_PAST_THIS_YEAR = DAYS_PAST_THIS_YEAR_TABLE[LEAPYEAR(year)][month] * SECONDS_PER_DAY;
uint64_t SECONDS_FROM_YEARS_PAST = 0;
- for(unsigned int iyear = EPOCH_YR; iyear < year; iyear++) {
+ for (unsigned int iyear = EPOCH_YR; iyear < year; iyear++) {
SECONDS_FROM_YEARS_PAST += YEARSIZE(iyear) * SECONDS_PER_DAY;
}
uint64_t epoch =
- second +
- minute * SECONDS_PER_MINUTE +
- hour * SECONDS_PER_HOUR +
- // Subtract 1 from day, since the current day isn't over yet
- // and we cannot count all 24 hours.
- (day-1) * SECONDS_PER_DAY +
- SECONDS_FROM_MONTHS_PAST_THIS_YEAR +
- SECONDS_FROM_YEARS_PAST;
+ second +
+ minute * SECONDS_PER_MINUTE +
+ hour * SECONDS_PER_HOUR +
+ // Subtract 1 from day, since the current day isn't over yet
+ // and we cannot count all 24 hours.
+ (day - 1) * SECONDS_PER_DAY +
+ SECONDS_FROM_MONTHS_PAST_THIS_YEAR +
+ SECONDS_FROM_YEARS_PAST;
return epoch;
-
}
/**
@@ -667,12 +644,12 @@ uint64_t _OS::get_unix_time_from_datetime(Dictionary datetime) const {
*
* @return dictionary of date and time values
*/
-Dictionary _OS::get_datetime_from_unix_time( uint64_t unix_time_val) const {
+Dictionary _OS::get_datetime_from_unix_time(uint64_t unix_time_val) const {
// Just fail if unix time is negative (when interpreted as an int).
// This means the user passed in a negative value by accident
- ERR_EXPLAIN("unix_time_val was really huge!"+ itos(unix_time_val) + " You probably passed in a negative value!");
- ERR_FAIL_COND_V( (int64_t)unix_time_val < 0, Dictionary());
+ ERR_EXPLAIN("unix_time_val was really huge!" + itos(unix_time_val) + " You probably passed in a negative value!");
+ ERR_FAIL_COND_V((int64_t)unix_time_val < 0, Dictionary());
OS::Date date;
OS::Time time;
@@ -705,18 +682,18 @@ Dictionary _OS::get_datetime_from_unix_time( uint64_t unix_time_val) const {
}
/// Add 1 to month to make sure months are indexed starting at 1
- date.month = static_cast<OS::Month>(imonth+1);
+ date.month = static_cast<OS::Month>(imonth + 1);
date.day = dayno + 1;
Dictionary timed;
- timed[HOUR_KEY]=time.hour;
- timed[MINUTE_KEY]=time.min;
- timed[SECOND_KEY]=time.sec;
- timed[YEAR_KEY]=date.year;
- timed[MONTH_KEY]=date.month;
- timed[DAY_KEY]=date.day;
- timed[WEEKDAY_KEY]=date.weekday;
+ timed[HOUR_KEY] = time.hour;
+ timed[MINUTE_KEY] = time.min;
+ timed[SECOND_KEY] = time.sec;
+ timed[YEAR_KEY] = date.year;
+ timed[MONTH_KEY] = date.month;
+ timed[DAY_KEY] = date.day;
+ timed[WEEKDAY_KEY] = date.weekday;
return timed;
}
@@ -745,7 +722,7 @@ void _OS::delay_usec(uint32_t p_usec) const {
void _OS::delay_msec(uint32_t p_msec) const {
- OS::get_singleton()->delay_usec(int64_t(p_msec)*1000);
+ OS::get_singleton()->delay_usec(int64_t(p_msec) * 1000);
}
uint32_t _OS::get_ticks_msec() const {
@@ -768,7 +745,6 @@ bool _OS::can_draw() const {
return OS::get_singleton()->can_draw();
}
-
int _OS::get_processor_count() const {
return OS::get_singleton()->get_processor_count();
@@ -777,10 +753,9 @@ int _OS::get_processor_count() const {
bool _OS::is_stdout_verbose() const {
return OS::get_singleton()->is_stdout_verbose();
-
}
-void _OS::dump_memory_to_file(const String& p_file) {
+void _OS::dump_memory_to_file(const String &p_file) {
OS::get_singleton()->dump_memory_to_file(p_file.utf8().get_data());
}
@@ -792,19 +767,18 @@ struct _OSCoreBindImg {
int fmt;
ObjectID id;
int vram;
- bool operator<(const _OSCoreBindImg& p_img) const { return vram==p_img.vram ? id<p_img.id : vram > p_img.vram; }
+ bool operator<(const _OSCoreBindImg &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; }
};
void _OS::print_all_textures_by_size() {
-
List<_OSCoreBindImg> imgs;
- int total=0;
+ int total = 0;
{
List<Ref<Resource> > rsrc;
ResourceCache::get_cached_resources(&rsrc);
- for (List<Ref<Resource> >::Element *E=rsrc.front();E;E=E->next()) {
+ for (List<Ref<Resource> >::Element *E = rsrc.front(); E; E = E->next()) {
if (!E->get()->is_class("ImageTexture"))
continue;
@@ -813,27 +787,27 @@ void _OS::print_all_textures_by_size() {
int fmt = E->get()->call("get_format");
_OSCoreBindImg img;
- img.size=size;
- img.fmt=fmt;
- img.path=E->get()->get_path();
- img.vram=Image::get_image_data_size(img.size.width,img.size.height,Image::Format(img.fmt));
- img.id=E->get()->get_instance_ID();
- total+=img.vram;
+ img.size = size;
+ img.fmt = fmt;
+ img.path = E->get()->get_path();
+ img.vram = Image::get_image_data_size(img.size.width, img.size.height, Image::Format(img.fmt));
+ img.id = E->get()->get_instance_ID();
+ total += img.vram;
imgs.push_back(img);
}
}
imgs.sort();
- for(List<_OSCoreBindImg>::Element *E=imgs.front();E;E=E->next()) {
+ for (List<_OSCoreBindImg>::Element *E = imgs.front(); E; E = E->next()) {
- total-=E->get().vram;
+ total -= E->get().vram;
}
}
-void _OS::print_resources_by_type(const Vector<String>& p_types) {
+void _OS::print_resources_by_type(const Vector<String> &p_types) {
- Map<String,int> type_count;
+ Map<String, int> type_count;
List<Ref<Resource> > resources;
ResourceCache::get_cached_resources(&resources);
@@ -841,13 +815,13 @@ void _OS::print_resources_by_type(const Vector<String>& p_types) {
List<Ref<Resource> > rsrc;
ResourceCache::get_cached_resources(&rsrc);
- for (List<Ref<Resource> >::Element *E=rsrc.front();E;E=E->next()) {
+ for (List<Ref<Resource> >::Element *E = rsrc.front(); E; E = E->next()) {
Ref<Resource> r = E->get();
bool found = false;
- for (int i=0; i<p_types.size(); i++) {
+ for (int i = 0; i < p_types.size(); i++) {
if (r->is_class(p_types[i]))
found = true;
}
@@ -855,20 +829,18 @@ void _OS::print_resources_by_type(const Vector<String>& p_types) {
continue;
if (!type_count.has(r->get_class())) {
- type_count[r->get_class()]=0;
+ type_count[r->get_class()] = 0;
}
-
type_count[r->get_class()]++;
}
-
};
bool _OS::has_virtual_keyboard() const {
return OS::get_singleton()->has_virtual_keyboard();
}
-void _OS::show_virtual_keyboard(const String& p_existing_text) {
+void _OS::show_virtual_keyboard(const String &p_existing_text) {
OS::get_singleton()->show_virtual_keyboard(p_existing_text, Rect2());
}
@@ -876,7 +848,7 @@ void _OS::hide_virtual_keyboard() {
OS::get_singleton()->hide_virtual_keyboard();
}
-void _OS::print_all_resources(const String& p_to_file ) {
+void _OS::print_all_resources(const String &p_to_file) {
OS::get_singleton()->print_all_resources(p_to_file);
}
@@ -886,7 +858,7 @@ void _OS::print_resources_in_use(bool p_short) {
OS::get_singleton()->print_resources_in_use(p_short);
}
-void _OS::dump_resources_to_file(const String& p_file) {
+void _OS::dump_resources_to_file(const String &p_file) {
OS::get_singleton()->dump_resources_to_file(p_file.utf8().get_data());
}
@@ -932,7 +904,6 @@ bool _OS::is_debug_build() const {
#else
return false;
#endif
-
}
void _OS::set_screen_orientation(ScreenOrientation p_orientation) {
@@ -960,8 +931,6 @@ String _OS::get_system_dir(SystemDir p_dir) const {
return OS::get_singleton()->get_system_dir(OS::SystemDir(p_dir));
}
-
-
String _OS::get_scancode_string(uint32_t p_code) const {
return keycode_get_string(p_code);
@@ -970,25 +939,25 @@ bool _OS::is_scancode_unicode(uint32_t p_unicode) const {
return keycode_has_unicode(p_unicode);
}
-int _OS::find_scancode_from_string(const String& p_code) const {
+int _OS::find_scancode_from_string(const String &p_code) const {
return find_keycode(p_code);
}
-void _OS::alert(const String& p_alert,const String& p_title) {
+void _OS::alert(const String &p_alert, const String &p_title) {
- OS::get_singleton()->alert(p_alert,p_title);
+ OS::get_singleton()->alert(p_alert, p_title);
}
-_OS *_OS::singleton=NULL;
+_OS *_OS::singleton = NULL;
void _OS::_bind_methods() {
//ClassDB::bind_method(D_METHOD("get_mouse_pos"),&_OS::get_mouse_pos);
//ClassDB::bind_method(D_METHOD("is_mouse_grab_enabled"),&_OS::is_mouse_grab_enabled);
- ClassDB::bind_method(D_METHOD("set_clipboard","clipboard"),&_OS::set_clipboard);
- ClassDB::bind_method(D_METHOD("get_clipboard"),&_OS::get_clipboard);
+ ClassDB::bind_method(D_METHOD("set_clipboard", "clipboard"), &_OS::set_clipboard);
+ ClassDB::bind_method(D_METHOD("get_clipboard"), &_OS::get_clipboard);
//will not delete for now, just unexpose
//ClassDB::bind_method(D_METHOD("set_video_mode","size","fullscreen","resizable","screen"),&_OS::set_video_mode,DEFVAL(0));
@@ -997,219 +966,212 @@ void _OS::_bind_methods() {
//ClassDB::bind_method(D_METHOD("is_video_mode_resizable","screen"),&_OS::is_video_mode_resizable,DEFVAL(0));
//ClassDB::bind_method(D_METHOD("get_fullscreen_mode_list","screen"),&_OS::get_fullscreen_mode_list,DEFVAL(0));
-
- ClassDB::bind_method(D_METHOD("get_screen_count"),&_OS::get_screen_count);
- ClassDB::bind_method(D_METHOD("get_current_screen"),&_OS::get_current_screen);
- ClassDB::bind_method(D_METHOD("set_current_screen","screen"),&_OS::set_current_screen);
- ClassDB::bind_method(D_METHOD("get_screen_position","screen"),&_OS::get_screen_position,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_screen_size","screen"),&_OS::get_screen_size,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_screen_dpi","screen"),&_OS::get_screen_dpi,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_window_position"),&_OS::get_window_position);
- ClassDB::bind_method(D_METHOD("set_window_position","position"),&_OS::set_window_position);
- ClassDB::bind_method(D_METHOD("get_window_size"),&_OS::get_window_size);
- ClassDB::bind_method(D_METHOD("set_window_size","size"),&_OS::set_window_size);
- ClassDB::bind_method(D_METHOD("set_window_fullscreen","enabled"),&_OS::set_window_fullscreen);
- ClassDB::bind_method(D_METHOD("is_window_fullscreen"),&_OS::is_window_fullscreen);
- ClassDB::bind_method(D_METHOD("set_window_resizable","enabled"),&_OS::set_window_resizable);
- ClassDB::bind_method(D_METHOD("is_window_resizable"),&_OS::is_window_resizable);
- ClassDB::bind_method(D_METHOD("set_window_minimized", "enabled"),&_OS::set_window_minimized);
- ClassDB::bind_method(D_METHOD("is_window_minimized"),&_OS::is_window_minimized);
- ClassDB::bind_method(D_METHOD("set_window_maximized", "enabled"),&_OS::set_window_maximized);
- ClassDB::bind_method(D_METHOD("is_window_maximized"),&_OS::is_window_maximized);
+ ClassDB::bind_method(D_METHOD("get_screen_count"), &_OS::get_screen_count);
+ ClassDB::bind_method(D_METHOD("get_current_screen"), &_OS::get_current_screen);
+ ClassDB::bind_method(D_METHOD("set_current_screen", "screen"), &_OS::set_current_screen);
+ ClassDB::bind_method(D_METHOD("get_screen_position", "screen"), &_OS::get_screen_position, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_screen_size", "screen"), &_OS::get_screen_size, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_screen_dpi", "screen"), &_OS::get_screen_dpi, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_window_position"), &_OS::get_window_position);
+ ClassDB::bind_method(D_METHOD("set_window_position", "position"), &_OS::set_window_position);
+ ClassDB::bind_method(D_METHOD("get_window_size"), &_OS::get_window_size);
+ ClassDB::bind_method(D_METHOD("set_window_size", "size"), &_OS::set_window_size);
+ ClassDB::bind_method(D_METHOD("set_window_fullscreen", "enabled"), &_OS::set_window_fullscreen);
+ ClassDB::bind_method(D_METHOD("is_window_fullscreen"), &_OS::is_window_fullscreen);
+ ClassDB::bind_method(D_METHOD("set_window_resizable", "enabled"), &_OS::set_window_resizable);
+ ClassDB::bind_method(D_METHOD("is_window_resizable"), &_OS::is_window_resizable);
+ ClassDB::bind_method(D_METHOD("set_window_minimized", "enabled"), &_OS::set_window_minimized);
+ ClassDB::bind_method(D_METHOD("is_window_minimized"), &_OS::is_window_minimized);
+ ClassDB::bind_method(D_METHOD("set_window_maximized", "enabled"), &_OS::set_window_maximized);
+ ClassDB::bind_method(D_METHOD("is_window_maximized"), &_OS::is_window_maximized);
ClassDB::bind_method(D_METHOD("request_attention"), &_OS::request_attention);
ClassDB::bind_method(D_METHOD("set_borderless_window", "borderless"), &_OS::set_borderless_window);
ClassDB::bind_method(D_METHOD("get_borderless_window"), &_OS::get_borderless_window);
- ClassDB::bind_method(D_METHOD("set_screen_orientation","orientation"),&_OS::set_screen_orientation);
- ClassDB::bind_method(D_METHOD("get_screen_orientation"),&_OS::get_screen_orientation);
+ ClassDB::bind_method(D_METHOD("set_screen_orientation", "orientation"), &_OS::set_screen_orientation);
+ ClassDB::bind_method(D_METHOD("get_screen_orientation"), &_OS::get_screen_orientation);
- ClassDB::bind_method(D_METHOD("set_keep_screen_on","enabled"),&_OS::set_keep_screen_on);
- ClassDB::bind_method(D_METHOD("is_keep_screen_on"),&_OS::is_keep_screen_on);
+ ClassDB::bind_method(D_METHOD("set_keep_screen_on", "enabled"), &_OS::set_keep_screen_on);
+ ClassDB::bind_method(D_METHOD("is_keep_screen_on"), &_OS::is_keep_screen_on);
+ ClassDB::bind_method(D_METHOD("has_touchscreen_ui_hint"), &_OS::has_touchscreen_ui_hint);
- ClassDB::bind_method(D_METHOD("has_touchscreen_ui_hint"),&_OS::has_touchscreen_ui_hint);
+ ClassDB::bind_method(D_METHOD("set_window_title", "title"), &_OS::set_window_title);
- ClassDB::bind_method(D_METHOD("set_window_title","title"),&_OS::set_window_title);
+ ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode", "enable"), &_OS::set_low_processor_usage_mode);
+ ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"), &_OS::is_in_low_processor_usage_mode);
- ClassDB::bind_method(D_METHOD("set_low_processor_usage_mode","enable"),&_OS::set_low_processor_usage_mode);
- ClassDB::bind_method(D_METHOD("is_in_low_processor_usage_mode"),&_OS::is_in_low_processor_usage_mode);
+ ClassDB::bind_method(D_METHOD("get_processor_count"), &_OS::get_processor_count);
- ClassDB::bind_method(D_METHOD("get_processor_count"),&_OS::get_processor_count);
+ ClassDB::bind_method(D_METHOD("get_executable_path"), &_OS::get_executable_path);
+ ClassDB::bind_method(D_METHOD("execute", "path", "arguments", "blocking", "output"), &_OS::execute, DEFVAL(Array()));
+ ClassDB::bind_method(D_METHOD("kill", "pid"), &_OS::kill);
+ ClassDB::bind_method(D_METHOD("shell_open", "uri"), &_OS::shell_open);
+ ClassDB::bind_method(D_METHOD("get_process_ID"), &_OS::get_process_ID);
- ClassDB::bind_method(D_METHOD("get_executable_path"),&_OS::get_executable_path);
- ClassDB::bind_method(D_METHOD("execute","path","arguments","blocking","output"),&_OS::execute,DEFVAL(Array()));
- ClassDB::bind_method(D_METHOD("kill","pid"),&_OS::kill);
- ClassDB::bind_method(D_METHOD("shell_open","uri"),&_OS::shell_open);
- ClassDB::bind_method(D_METHOD("get_process_ID"),&_OS::get_process_ID);
+ ClassDB::bind_method(D_METHOD("get_environment", "environment"), &_OS::get_environment);
+ ClassDB::bind_method(D_METHOD("has_environment", "environment"), &_OS::has_environment);
- ClassDB::bind_method(D_METHOD("get_environment","environment"),&_OS::get_environment);
- ClassDB::bind_method(D_METHOD("has_environment","environment"),&_OS::has_environment);
+ ClassDB::bind_method(D_METHOD("get_name"), &_OS::get_name);
+ ClassDB::bind_method(D_METHOD("get_cmdline_args"), &_OS::get_cmdline_args);
- ClassDB::bind_method(D_METHOD("get_name"),&_OS::get_name);
- ClassDB::bind_method(D_METHOD("get_cmdline_args"),&_OS::get_cmdline_args);
-
- ClassDB::bind_method(D_METHOD("get_datetime","utc"),&_OS::get_datetime,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_date","utc"),&_OS::get_date,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_time","utc"),&_OS::get_time,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_time_zone_info"),&_OS::get_time_zone_info);
- ClassDB::bind_method(D_METHOD("get_unix_time"),&_OS::get_unix_time);
+ ClassDB::bind_method(D_METHOD("get_datetime", "utc"), &_OS::get_datetime, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_date", "utc"), &_OS::get_date, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_time", "utc"), &_OS::get_time, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_time_zone_info"), &_OS::get_time_zone_info);
+ ClassDB::bind_method(D_METHOD("get_unix_time"), &_OS::get_unix_time);
ClassDB::bind_method(D_METHOD("get_datetime_from_unix_time", "unix_time_val"),
&_OS::get_datetime_from_unix_time);
ClassDB::bind_method(D_METHOD("get_unix_time_from_datetime", "datetime"),
&_OS::get_unix_time_from_datetime);
ClassDB::bind_method(D_METHOD("get_system_time_secs"), &_OS::get_system_time_secs);
- ClassDB::bind_method(D_METHOD("set_icon","icon"),&_OS::set_icon);
-
- ClassDB::bind_method(D_METHOD("get_exit_code"),&_OS::get_exit_code);
- ClassDB::bind_method(D_METHOD("set_exit_code","code"),&_OS::set_exit_code);
+ ClassDB::bind_method(D_METHOD("set_icon", "icon"), &_OS::set_icon);
- ClassDB::bind_method(D_METHOD("delay_usec","usec"),&_OS::delay_usec);
- ClassDB::bind_method(D_METHOD("delay_msec","msec"),&_OS::delay_msec);
- ClassDB::bind_method(D_METHOD("get_ticks_msec"),&_OS::get_ticks_msec);
- ClassDB::bind_method(D_METHOD("get_splash_tick_msec"),&_OS::get_splash_tick_msec);
- ClassDB::bind_method(D_METHOD("get_locale"),&_OS::get_locale);
- ClassDB::bind_method(D_METHOD("get_latin_keyboard_variant"),&_OS::get_latin_keyboard_variant);
- ClassDB::bind_method(D_METHOD("get_model_name"),&_OS::get_model_name);
+ ClassDB::bind_method(D_METHOD("get_exit_code"), &_OS::get_exit_code);
+ ClassDB::bind_method(D_METHOD("set_exit_code", "code"), &_OS::set_exit_code);
+ ClassDB::bind_method(D_METHOD("delay_usec", "usec"), &_OS::delay_usec);
+ ClassDB::bind_method(D_METHOD("delay_msec", "msec"), &_OS::delay_msec);
+ ClassDB::bind_method(D_METHOD("get_ticks_msec"), &_OS::get_ticks_msec);
+ ClassDB::bind_method(D_METHOD("get_splash_tick_msec"), &_OS::get_splash_tick_msec);
+ ClassDB::bind_method(D_METHOD("get_locale"), &_OS::get_locale);
+ ClassDB::bind_method(D_METHOD("get_latin_keyboard_variant"), &_OS::get_latin_keyboard_variant);
+ ClassDB::bind_method(D_METHOD("get_model_name"), &_OS::get_model_name);
- ClassDB::bind_method(D_METHOD("can_draw"),&_OS::can_draw);
- ClassDB::bind_method(D_METHOD("is_stdout_verbose"),&_OS::is_stdout_verbose);
+ ClassDB::bind_method(D_METHOD("can_draw"), &_OS::can_draw);
+ ClassDB::bind_method(D_METHOD("is_stdout_verbose"), &_OS::is_stdout_verbose);
- ClassDB::bind_method(D_METHOD("can_use_threads"),&_OS::can_use_threads);
+ ClassDB::bind_method(D_METHOD("can_use_threads"), &_OS::can_use_threads);
- ClassDB::bind_method(D_METHOD("is_debug_build"),&_OS::is_debug_build);
+ ClassDB::bind_method(D_METHOD("is_debug_build"), &_OS::is_debug_build);
//ClassDB::bind_method(D_METHOD("get_mouse_button_state"),&_OS::get_mouse_button_state);
- ClassDB::bind_method(D_METHOD("dump_memory_to_file","file"),&_OS::dump_memory_to_file);
- ClassDB::bind_method(D_METHOD("dump_resources_to_file","file"),&_OS::dump_resources_to_file);
- ClassDB::bind_method(D_METHOD("has_virtual_keyboard"),&_OS::has_virtual_keyboard);
- ClassDB::bind_method(D_METHOD("show_virtual_keyboard", "existing_text"),&_OS::show_virtual_keyboard,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("hide_virtual_keyboard"),&_OS::hide_virtual_keyboard);
- ClassDB::bind_method(D_METHOD("print_resources_in_use","short"),&_OS::print_resources_in_use,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("print_all_resources","tofile"),&_OS::print_all_resources,DEFVAL(""));
-
- ClassDB::bind_method(D_METHOD("get_static_memory_usage"),&_OS::get_static_memory_usage);
- ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"),&_OS::get_static_memory_peak_usage);
- ClassDB::bind_method(D_METHOD("get_dynamic_memory_usage"),&_OS::get_dynamic_memory_usage);
-
- ClassDB::bind_method(D_METHOD("get_data_dir"),&_OS::get_data_dir);
- ClassDB::bind_method(D_METHOD("get_system_dir","dir"),&_OS::get_system_dir);
- ClassDB::bind_method(D_METHOD("get_unique_ID"),&_OS::get_unique_ID);
-
- ClassDB::bind_method(D_METHOD("is_ok_left_and_cancel_right"),&_OS::is_ok_left_and_cancel_right);
-
-
- ClassDB::bind_method(D_METHOD("print_all_textures_by_size"),&_OS::print_all_textures_by_size);
- ClassDB::bind_method(D_METHOD("print_resources_by_type","types"),&_OS::print_resources_by_type);
-
- ClassDB::bind_method(D_METHOD("native_video_play","path","volume","audio_track","subtitle_track"),&_OS::native_video_play);
- ClassDB::bind_method(D_METHOD("native_video_is_playing"),&_OS::native_video_is_playing);
- ClassDB::bind_method(D_METHOD("native_video_stop"),&_OS::native_video_stop);
- ClassDB::bind_method(D_METHOD("native_video_pause"),&_OS::native_video_pause);
- ClassDB::bind_method(D_METHOD("native_video_unpause"),&_OS::native_video_unpause);
-
- ClassDB::bind_method(D_METHOD("get_scancode_string","code"),&_OS::get_scancode_string);
- ClassDB::bind_method(D_METHOD("is_scancode_unicode","code"),&_OS::is_scancode_unicode);
- ClassDB::bind_method(D_METHOD("find_scancode_from_string","string"),&_OS::find_scancode_from_string);
-
- ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap","enabled"),&_OS::set_use_file_access_save_and_swap);
-
- ClassDB::bind_method(D_METHOD("alert","text","title"),&_OS::alert,DEFVAL("Alert!"));
-
- ClassDB::bind_method(D_METHOD("set_thread_name","name"),&_OS::set_thread_name);
-
- ClassDB::bind_method(D_METHOD("set_use_vsync","enable"),&_OS::set_use_vsync);
- ClassDB::bind_method(D_METHOD("is_vsync_enabled"),&_OS::is_vsync_enabled);
-
- ClassDB::bind_method(D_METHOD("get_power_state"),&_OS::get_power_state);
- ClassDB::bind_method(D_METHOD("get_power_seconds_left"),&_OS::get_power_seconds_left);
- ClassDB::bind_method(D_METHOD("get_power_percent_left"),&_OS::get_power_percent_left);
-
- BIND_CONSTANT( DAY_SUNDAY );
- BIND_CONSTANT( DAY_MONDAY );
- BIND_CONSTANT( DAY_TUESDAY );
- BIND_CONSTANT( DAY_WEDNESDAY );
- BIND_CONSTANT( DAY_THURSDAY );
- BIND_CONSTANT( DAY_FRIDAY );
- BIND_CONSTANT( DAY_SATURDAY );
-
- BIND_CONSTANT( MONTH_JANUARY );
- BIND_CONSTANT( MONTH_FEBRUARY );
- BIND_CONSTANT( MONTH_MARCH );
- BIND_CONSTANT( MONTH_APRIL );
- BIND_CONSTANT( MONTH_MAY );
- BIND_CONSTANT( MONTH_JUNE );
- BIND_CONSTANT( MONTH_JULY );
- BIND_CONSTANT( MONTH_AUGUST );
- BIND_CONSTANT( MONTH_SEPTEMBER );
- BIND_CONSTANT( MONTH_OCTOBER );
- BIND_CONSTANT( MONTH_NOVEMBER );
- BIND_CONSTANT( MONTH_DECEMBER );
-
- BIND_CONSTANT( SCREEN_ORIENTATION_LANDSCAPE );
- BIND_CONSTANT( SCREEN_ORIENTATION_PORTRAIT );
- BIND_CONSTANT( SCREEN_ORIENTATION_REVERSE_LANDSCAPE );
- BIND_CONSTANT( SCREEN_ORIENTATION_REVERSE_PORTRAIT );
- BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR_LANDSCAPE );
- BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR_PORTRAIT );
- BIND_CONSTANT( SCREEN_ORIENTATION_SENSOR );
-
- BIND_CONSTANT( SYSTEM_DIR_DESKTOP);
- BIND_CONSTANT( SYSTEM_DIR_DCIM );
- BIND_CONSTANT( SYSTEM_DIR_DOCUMENTS );
- BIND_CONSTANT( SYSTEM_DIR_DOWNLOADS );
- BIND_CONSTANT( SYSTEM_DIR_MOVIES );
- BIND_CONSTANT( SYSTEM_DIR_MUSIC );
- BIND_CONSTANT( SYSTEM_DIR_PICTURES );
- BIND_CONSTANT( SYSTEM_DIR_RINGTONES );
-
- BIND_CONSTANT( POWERSTATE_UNKNOWN );
- BIND_CONSTANT( POWERSTATE_ON_BATTERY );
- BIND_CONSTANT( POWERSTATE_NO_BATTERY );
- BIND_CONSTANT( POWERSTATE_CHARGING );
- BIND_CONSTANT( POWERSTATE_CHARGED );
-
+ ClassDB::bind_method(D_METHOD("dump_memory_to_file", "file"), &_OS::dump_memory_to_file);
+ ClassDB::bind_method(D_METHOD("dump_resources_to_file", "file"), &_OS::dump_resources_to_file);
+ ClassDB::bind_method(D_METHOD("has_virtual_keyboard"), &_OS::has_virtual_keyboard);
+ ClassDB::bind_method(D_METHOD("show_virtual_keyboard", "existing_text"), &_OS::show_virtual_keyboard, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("hide_virtual_keyboard"), &_OS::hide_virtual_keyboard);
+ ClassDB::bind_method(D_METHOD("print_resources_in_use", "short"), &_OS::print_resources_in_use, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("print_all_resources", "tofile"), &_OS::print_all_resources, DEFVAL(""));
+
+ ClassDB::bind_method(D_METHOD("get_static_memory_usage"), &_OS::get_static_memory_usage);
+ ClassDB::bind_method(D_METHOD("get_static_memory_peak_usage"), &_OS::get_static_memory_peak_usage);
+ ClassDB::bind_method(D_METHOD("get_dynamic_memory_usage"), &_OS::get_dynamic_memory_usage);
+
+ ClassDB::bind_method(D_METHOD("get_data_dir"), &_OS::get_data_dir);
+ ClassDB::bind_method(D_METHOD("get_system_dir", "dir"), &_OS::get_system_dir);
+ ClassDB::bind_method(D_METHOD("get_unique_ID"), &_OS::get_unique_ID);
+
+ ClassDB::bind_method(D_METHOD("is_ok_left_and_cancel_right"), &_OS::is_ok_left_and_cancel_right);
+
+ ClassDB::bind_method(D_METHOD("print_all_textures_by_size"), &_OS::print_all_textures_by_size);
+ ClassDB::bind_method(D_METHOD("print_resources_by_type", "types"), &_OS::print_resources_by_type);
+
+ ClassDB::bind_method(D_METHOD("native_video_play", "path", "volume", "audio_track", "subtitle_track"), &_OS::native_video_play);
+ ClassDB::bind_method(D_METHOD("native_video_is_playing"), &_OS::native_video_is_playing);
+ ClassDB::bind_method(D_METHOD("native_video_stop"), &_OS::native_video_stop);
+ ClassDB::bind_method(D_METHOD("native_video_pause"), &_OS::native_video_pause);
+ ClassDB::bind_method(D_METHOD("native_video_unpause"), &_OS::native_video_unpause);
+
+ ClassDB::bind_method(D_METHOD("get_scancode_string", "code"), &_OS::get_scancode_string);
+ ClassDB::bind_method(D_METHOD("is_scancode_unicode", "code"), &_OS::is_scancode_unicode);
+ ClassDB::bind_method(D_METHOD("find_scancode_from_string", "string"), &_OS::find_scancode_from_string);
+
+ ClassDB::bind_method(D_METHOD("set_use_file_access_save_and_swap", "enabled"), &_OS::set_use_file_access_save_and_swap);
+
+ ClassDB::bind_method(D_METHOD("alert", "text", "title"), &_OS::alert, DEFVAL("Alert!"));
+
+ ClassDB::bind_method(D_METHOD("set_thread_name", "name"), &_OS::set_thread_name);
+
+ ClassDB::bind_method(D_METHOD("set_use_vsync", "enable"), &_OS::set_use_vsync);
+ ClassDB::bind_method(D_METHOD("is_vsync_enabled"), &_OS::is_vsync_enabled);
+
+ ClassDB::bind_method(D_METHOD("get_power_state"), &_OS::get_power_state);
+ ClassDB::bind_method(D_METHOD("get_power_seconds_left"), &_OS::get_power_seconds_left);
+ ClassDB::bind_method(D_METHOD("get_power_percent_left"), &_OS::get_power_percent_left);
+
+ BIND_CONSTANT(DAY_SUNDAY);
+ BIND_CONSTANT(DAY_MONDAY);
+ BIND_CONSTANT(DAY_TUESDAY);
+ BIND_CONSTANT(DAY_WEDNESDAY);
+ BIND_CONSTANT(DAY_THURSDAY);
+ BIND_CONSTANT(DAY_FRIDAY);
+ BIND_CONSTANT(DAY_SATURDAY);
+
+ BIND_CONSTANT(MONTH_JANUARY);
+ BIND_CONSTANT(MONTH_FEBRUARY);
+ BIND_CONSTANT(MONTH_MARCH);
+ BIND_CONSTANT(MONTH_APRIL);
+ BIND_CONSTANT(MONTH_MAY);
+ BIND_CONSTANT(MONTH_JUNE);
+ BIND_CONSTANT(MONTH_JULY);
+ BIND_CONSTANT(MONTH_AUGUST);
+ BIND_CONSTANT(MONTH_SEPTEMBER);
+ BIND_CONSTANT(MONTH_OCTOBER);
+ BIND_CONSTANT(MONTH_NOVEMBER);
+ BIND_CONSTANT(MONTH_DECEMBER);
+
+ BIND_CONSTANT(SCREEN_ORIENTATION_LANDSCAPE);
+ BIND_CONSTANT(SCREEN_ORIENTATION_PORTRAIT);
+ BIND_CONSTANT(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
+ BIND_CONSTANT(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
+ BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
+ BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR_PORTRAIT);
+ BIND_CONSTANT(SCREEN_ORIENTATION_SENSOR);
+
+ BIND_CONSTANT(SYSTEM_DIR_DESKTOP);
+ BIND_CONSTANT(SYSTEM_DIR_DCIM);
+ BIND_CONSTANT(SYSTEM_DIR_DOCUMENTS);
+ BIND_CONSTANT(SYSTEM_DIR_DOWNLOADS);
+ BIND_CONSTANT(SYSTEM_DIR_MOVIES);
+ BIND_CONSTANT(SYSTEM_DIR_MUSIC);
+ BIND_CONSTANT(SYSTEM_DIR_PICTURES);
+ BIND_CONSTANT(SYSTEM_DIR_RINGTONES);
+
+ BIND_CONSTANT(POWERSTATE_UNKNOWN);
+ BIND_CONSTANT(POWERSTATE_ON_BATTERY);
+ BIND_CONSTANT(POWERSTATE_NO_BATTERY);
+ BIND_CONSTANT(POWERSTATE_CHARGING);
+ BIND_CONSTANT(POWERSTATE_CHARGED);
}
_OS::_OS() {
- singleton=this;
+ singleton = this;
}
-
///////////////////// GEOMETRY
-
-_Geometry *_Geometry::singleton=NULL;
+_Geometry *_Geometry::singleton = NULL;
_Geometry *_Geometry::get_singleton() {
return singleton;
}
-PoolVector<Plane> _Geometry::build_box_planes(const Vector3& p_extents) {
+PoolVector<Plane> _Geometry::build_box_planes(const Vector3 &p_extents) {
return Geometry::build_box_planes(p_extents);
}
PoolVector<Plane> _Geometry::build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis) {
- return Geometry::build_cylinder_planes(p_radius,p_height,p_sides,p_axis);
+ return Geometry::build_cylinder_planes(p_radius, p_height, p_sides, p_axis);
}
PoolVector<Plane> _Geometry::build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
- return Geometry::build_capsule_planes(p_radius,p_height,p_sides,p_lats,p_axis);
+ return Geometry::build_capsule_planes(p_radius, p_height, p_sides, p_lats, p_axis);
}
-real_t _Geometry::segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius) {
+real_t _Geometry::segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
- return Geometry::segment_intersects_circle(p_from,p_to,p_circle_pos,p_circle_radius);
+ return Geometry::segment_intersects_circle(p_from, p_to, p_circle_pos, p_circle_radius);
}
-Variant _Geometry::segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b) {
+Variant _Geometry::segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b) {
Vector2 result;
if (Geometry::segment_intersects_segment_2d(p_from_a, p_to_a, p_from_b, p_to_b, &result)) {
@@ -1220,122 +1182,117 @@ Variant _Geometry::segment_intersects_segment_2d(const Vector2& p_from_a,const V
};
};
-PoolVector<Vector2> _Geometry::get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2) {
+PoolVector<Vector2> _Geometry::get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2) {
Vector2 r1, r2;
- Geometry::get_closest_points_between_segments(p1,q1,p2,q2,r1,r2);
+ Geometry::get_closest_points_between_segments(p1, q1, p2, q2, r1, r2);
PoolVector<Vector2> r;
r.resize(2);
- r.set(0,r1);
- r.set(1,r2);
+ r.set(0, r1);
+ r.set(1, r2);
return r;
}
-PoolVector<Vector3> _Geometry::get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2) {
+PoolVector<Vector3> _Geometry::get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2) {
Vector3 r1, r2;
- Geometry::get_closest_points_between_segments(p1,p2,q1,q2,r1,r2);
+ Geometry::get_closest_points_between_segments(p1, p2, q1, q2, r1, r2);
PoolVector<Vector3> r;
r.resize(2);
- r.set(0,r1);
- r.set(1,r2);
+ r.set(0, r1);
+ r.set(1, r2);
return r;
-
}
-Vector2 _Geometry::get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b) {
+Vector2 _Geometry::get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
- Vector2 s[2]={p_a,p_b};
- return Geometry::get_closest_point_to_segment_2d(p_point,s);
+ Vector2 s[2] = { p_a, p_b };
+ return Geometry::get_closest_point_to_segment_2d(p_point, s);
}
-Vector3 _Geometry::get_closest_point_to_segment(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b) {
+Vector3 _Geometry::get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
- Vector3 s[2]={p_a,p_b};
- return Geometry::get_closest_point_to_segment(p_point,s);
+ Vector3 s[2] = { p_a, p_b };
+ return Geometry::get_closest_point_to_segment(p_point, s);
}
-Vector2 _Geometry::get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b) {
+Vector2 _Geometry::get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b) {
- Vector2 s[2]={p_a,p_b};
- return Geometry::get_closest_point_to_segment_uncapped_2d(p_point,s);
+ Vector2 s[2] = { p_a, p_b };
+ return Geometry::get_closest_point_to_segment_uncapped_2d(p_point, s);
}
-Vector3 _Geometry::get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b) {
+Vector3 _Geometry::get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b) {
- Vector3 s[2]={p_a,p_b};
- return Geometry::get_closest_point_to_segment_uncapped(p_point,s);
+ Vector3 s[2] = { p_a, p_b };
+ return Geometry::get_closest_point_to_segment_uncapped(p_point, s);
}
-Variant _Geometry::ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2) {
+Variant _Geometry::ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
Vector3 res;
- if (Geometry::ray_intersects_triangle(p_from,p_dir,p_v0,p_v1,p_v2,&res))
+ if (Geometry::ray_intersects_triangle(p_from, p_dir, p_v0, p_v1, p_v2, &res))
return res;
else
return Variant();
-
-
}
-Variant _Geometry::segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2) {
+Variant _Geometry::segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2) {
Vector3 res;
- if (Geometry::segment_intersects_triangle(p_from,p_to,p_v0,p_v1,p_v2,&res))
+ if (Geometry::segment_intersects_triangle(p_from, p_to, p_v0, p_v1, p_v2, &res))
return res;
else
return Variant();
-
}
-bool _Geometry::point_is_inside_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c) const {
+bool _Geometry::point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const {
- return Geometry::is_point_in_triangle(s,a,b,c);
+ return Geometry::is_point_in_triangle(s, a, b, c);
}
-PoolVector<Vector3> _Geometry::segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius) {
+PoolVector<Vector3> _Geometry::segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius) {
PoolVector<Vector3> r;
- Vector3 res,norm;
- if (!Geometry::segment_intersects_sphere(p_from,p_to,p_sphere_pos,p_sphere_radius,&res,&norm))
+ Vector3 res, norm;
+ if (!Geometry::segment_intersects_sphere(p_from, p_to, p_sphere_pos, p_sphere_radius, &res, &norm))
return r;
r.resize(2);
- r.set(0,res);
- r.set(1,norm);
+ r.set(0, res);
+ r.set(1, norm);
return r;
}
-PoolVector<Vector3> _Geometry::segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius) {
+PoolVector<Vector3> _Geometry::segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius) {
PoolVector<Vector3> r;
- Vector3 res,norm;
- if (!Geometry::segment_intersects_cylinder(p_from,p_to,p_height,p_radius,&res,&norm))
+ Vector3 res, norm;
+ if (!Geometry::segment_intersects_cylinder(p_from, p_to, p_height, p_radius, &res, &norm))
return r;
r.resize(2);
- r.set(0,res);
- r.set(1,norm);
+ r.set(0, res);
+ r.set(1, norm);
return r;
-
}
-PoolVector<Vector3> _Geometry::segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector<Plane>& p_planes) {
+PoolVector<Vector3> _Geometry::segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &p_planes) {
PoolVector<Vector3> r;
- Vector3 res,norm;
- if (!Geometry::segment_intersects_convex(p_from,p_to,p_planes.ptr(),p_planes.size(),&res,&norm))
+ Vector3 res, norm;
+ if (!Geometry::segment_intersects_convex(p_from, p_to, p_planes.ptr(), p_planes.size(), &res, &norm))
return r;
r.resize(2);
- r.set(0,res);
- r.set(1,norm);
+ r.set(0, res);
+ r.set(1, norm);
return r;
}
-Vector<int> _Geometry::triangulate_polygon(const Vector<Vector2>& p_polygon) {
+Vector<int> _Geometry::triangulate_polygon(const Vector<Vector2> &p_polygon) {
return Geometry::triangulate_polygon(p_polygon);
}
-Dictionary _Geometry::make_atlas(const Vector<Size2>& p_rects) {
+Dictionary _Geometry::make_atlas(const Vector<Size2> &p_rects) {
Dictionary ret;
Vector<Size2i> rects;
- for (int i=0; i<p_rects.size(); i++) {
+ for (int i = 0; i < p_rects.size(); i++) {
rects.push_back(p_rects[i]);
};
@@ -1347,215 +1304,193 @@ Dictionary _Geometry::make_atlas(const Vector<Size2>& p_rects) {
Size2 r_size = size;
Vector<Point2> r_result;
- for (int i=0; i<result.size(); i++) {
+ for (int i = 0; i < result.size(); i++) {
r_result.push_back(result[i]);
};
-
ret["points"] = r_result;
ret["size"] = r_size;
return ret;
};
-
-int _Geometry::get_uv84_normal_bit(const Vector3& p_vector) {
+int _Geometry::get_uv84_normal_bit(const Vector3 &p_vector) {
return Geometry::get_uv84_normal_bit(p_vector);
}
-
void _Geometry::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("build_box_planes", "extents"), &_Geometry::build_box_planes);
+ ClassDB::bind_method(D_METHOD("build_cylinder_planes", "radius", "height", "sides", "axis"), &_Geometry::build_cylinder_planes, DEFVAL(Vector3::AXIS_Z));
+ ClassDB::bind_method(D_METHOD("build_capsule_planes", "radius", "height", "sides", "lats", "axis"), &_Geometry::build_capsule_planes, DEFVAL(Vector3::AXIS_Z));
+ ClassDB::bind_method(D_METHOD("segment_intersects_circle", "segment_from", "segment_to", "circle_pos", "circle_radius"), &_Geometry::segment_intersects_circle);
+ ClassDB::bind_method(D_METHOD("segment_intersects_segment_2d", "from_a", "to_a", "from_b", "to_b"), &_Geometry::segment_intersects_segment_2d);
- ClassDB::bind_method(D_METHOD("build_box_planes","extents"),&_Geometry::build_box_planes);
- ClassDB::bind_method(D_METHOD("build_cylinder_planes","radius","height","sides","axis"),&_Geometry::build_cylinder_planes,DEFVAL(Vector3::AXIS_Z));
- ClassDB::bind_method(D_METHOD("build_capsule_planes","radius","height","sides","lats","axis"),&_Geometry::build_capsule_planes,DEFVAL(Vector3::AXIS_Z));
- ClassDB::bind_method(D_METHOD("segment_intersects_circle","segment_from","segment_to","circle_pos","circle_radius"),&_Geometry::segment_intersects_circle);
- ClassDB::bind_method(D_METHOD("segment_intersects_segment_2d","from_a","to_a","from_b","to_b"),&_Geometry::segment_intersects_segment_2d);
-
- ClassDB::bind_method(D_METHOD("get_closest_points_between_segments_2d","p1","q1","p2","q2"),&_Geometry::get_closest_points_between_segments_2d);
- ClassDB::bind_method(D_METHOD("get_closest_points_between_segments","p1","p2","q1","q2"),&_Geometry::get_closest_points_between_segments);
+ ClassDB::bind_method(D_METHOD("get_closest_points_between_segments_2d", "p1", "q1", "p2", "q2"), &_Geometry::get_closest_points_between_segments_2d);
+ ClassDB::bind_method(D_METHOD("get_closest_points_between_segments", "p1", "p2", "q1", "q2"), &_Geometry::get_closest_points_between_segments);
- ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_2d","point","s1","s2"),&_Geometry::get_closest_point_to_segment_2d);
- ClassDB::bind_method(D_METHOD("get_closest_point_to_segment","point","s1","s2"),&_Geometry::get_closest_point_to_segment);
+ ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_2d);
+ ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment);
- ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped_2d","point","s1","s2"),&_Geometry::get_closest_point_to_segment_uncapped_2d);
- ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped","point","s1","s2"),&_Geometry::get_closest_point_to_segment_uncapped);
+ ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped_2d", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped_2d);
+ ClassDB::bind_method(D_METHOD("get_closest_point_to_segment_uncapped", "point", "s1", "s2"), &_Geometry::get_closest_point_to_segment_uncapped);
- ClassDB::bind_method(D_METHOD("get_uv84_normal_bit","normal"),&_Geometry::get_uv84_normal_bit);
+ ClassDB::bind_method(D_METHOD("get_uv84_normal_bit", "normal"), &_Geometry::get_uv84_normal_bit);
- ClassDB::bind_method(D_METHOD("ray_intersects_triangle","from","dir","a","b","c"),&_Geometry::ray_intersects_triangle);
- ClassDB::bind_method(D_METHOD("segment_intersects_triangle","from","to","a","b","c"),&_Geometry::segment_intersects_triangle);
- ClassDB::bind_method(D_METHOD("segment_intersects_sphere","from","to","spos","sradius"),&_Geometry::segment_intersects_sphere);
- ClassDB::bind_method(D_METHOD("segment_intersects_cylinder","from","to","height","radius"),&_Geometry::segment_intersects_cylinder);
- ClassDB::bind_method(D_METHOD("segment_intersects_convex","from","to","planes"),&_Geometry::segment_intersects_convex);
- ClassDB::bind_method(D_METHOD("point_is_inside_triangle","point","a","b","c"),&_Geometry::point_is_inside_triangle);
+ ClassDB::bind_method(D_METHOD("ray_intersects_triangle", "from", "dir", "a", "b", "c"), &_Geometry::ray_intersects_triangle);
+ ClassDB::bind_method(D_METHOD("segment_intersects_triangle", "from", "to", "a", "b", "c"), &_Geometry::segment_intersects_triangle);
+ ClassDB::bind_method(D_METHOD("segment_intersects_sphere", "from", "to", "spos", "sradius"), &_Geometry::segment_intersects_sphere);
+ ClassDB::bind_method(D_METHOD("segment_intersects_cylinder", "from", "to", "height", "radius"), &_Geometry::segment_intersects_cylinder);
+ ClassDB::bind_method(D_METHOD("segment_intersects_convex", "from", "to", "planes"), &_Geometry::segment_intersects_convex);
+ ClassDB::bind_method(D_METHOD("point_is_inside_triangle", "point", "a", "b", "c"), &_Geometry::point_is_inside_triangle);
- ClassDB::bind_method(D_METHOD("triangulate_polygon","polygon"),&_Geometry::triangulate_polygon);
+ ClassDB::bind_method(D_METHOD("triangulate_polygon", "polygon"), &_Geometry::triangulate_polygon);
- ClassDB::bind_method(D_METHOD("make_atlas","sizes"),&_Geometry::make_atlas);
+ ClassDB::bind_method(D_METHOD("make_atlas", "sizes"), &_Geometry::make_atlas);
}
-
_Geometry::_Geometry() {
- singleton=this;
+ singleton = this;
}
-
///////////////////////// FILE
+Error _File::open_encrypted(const String &p_path, int p_mode_flags, const Vector<uint8_t> &p_key) {
-
-Error _File::open_encrypted(const String& p_path, int p_mode_flags,const Vector<uint8_t>& p_key) {
-
- Error err = open(p_path,p_mode_flags);
+ Error err = open(p_path, p_mode_flags);
if (err)
return err;
- FileAccessEncrypted *fae = memnew( FileAccessEncrypted );
- err = fae->open_and_parse(f,p_key,(p_mode_flags==WRITE)?FileAccessEncrypted::MODE_WRITE_AES256:FileAccessEncrypted::MODE_READ);
+ FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
+ err = fae->open_and_parse(f, p_key, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
if (err) {
memdelete(fae);
close();
return err;
}
- f=fae;
+ f = fae;
return OK;
}
-Error _File::open_encrypted_pass(const String& p_path, int p_mode_flags,const String& p_pass) {
+Error _File::open_encrypted_pass(const String &p_path, int p_mode_flags, const String &p_pass) {
- Error err = open(p_path,p_mode_flags);
+ Error err = open(p_path, p_mode_flags);
if (err)
return err;
- FileAccessEncrypted *fae = memnew( FileAccessEncrypted );
- err = fae->open_and_parse_password(f,p_pass,(p_mode_flags==WRITE)?FileAccessEncrypted::MODE_WRITE_AES256:FileAccessEncrypted::MODE_READ);
+ FileAccessEncrypted *fae = memnew(FileAccessEncrypted);
+ err = fae->open_and_parse_password(f, p_pass, (p_mode_flags == WRITE) ? FileAccessEncrypted::MODE_WRITE_AES256 : FileAccessEncrypted::MODE_READ);
if (err) {
memdelete(fae);
close();
return err;
}
- f=fae;
+ f = fae;
return OK;
-
}
-
-Error _File::open(const String& p_path, int p_mode_flags) {
+Error _File::open(const String &p_path, int p_mode_flags) {
close();
Error err;
- f = FileAccess::open(p_path,p_mode_flags,&err);
+ f = FileAccess::open(p_path, p_mode_flags, &err);
if (f)
f->set_endian_swap(eswap);
return err;
-
}
-void _File::close(){
+void _File::close() {
if (f)
memdelete(f);
- f=NULL;
+ f = NULL;
}
-bool _File::is_open() const{
-
+bool _File::is_open() const {
- return f!=NULL;
+ return f != NULL;
}
-void _File::seek(int64_t p_position){
+void _File::seek(int64_t p_position) {
ERR_FAIL_COND(!f);
f->seek(p_position);
-
}
-void _File::seek_end(int64_t p_position){
-
+void _File::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
f->seek_end(p_position);
}
-int64_t _File::get_pos() const{
+int64_t _File::get_pos() const {
-
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_pos();
}
-int64_t _File::get_len() const{
+int64_t _File::get_len() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_len();
}
-bool _File::eof_reached() const{
+bool _File::eof_reached() const {
- ERR_FAIL_COND_V(!f,false);
+ ERR_FAIL_COND_V(!f, false);
return f->eof_reached();
}
-uint8_t _File::get_8() const{
+uint8_t _File::get_8() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_8();
-
}
-uint16_t _File::get_16() const{
+uint16_t _File::get_16() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_16();
-
}
-uint32_t _File::get_32() const{
+uint32_t _File::get_32() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_32();
-
}
-uint64_t _File::get_64() const{
+uint64_t _File::get_64() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_64();
-
}
-float _File::get_float() const{
+float _File::get_float() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_float();
-
}
-double _File::get_double() const{
+double _File::get_double() const {
-
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_double();
}
-real_t _File::get_real() const{
-
+real_t _File::get_real() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
return f->get_real();
}
-PoolVector<uint8_t> _File::get_buffer(int p_length) const{
+PoolVector<uint8_t> _File::get_buffer(int p_length) const {
PoolVector<uint8_t> data;
- ERR_FAIL_COND_V(!f,data);
+ ERR_FAIL_COND_V(!f, data);
- ERR_FAIL_COND_V(p_length<0,data);
- if (p_length==0)
+ ERR_FAIL_COND_V(p_length < 0, data);
+ if (p_length == 0)
return data;
Error err = data.resize(p_length);
- ERR_FAIL_COND_V(err!=OK,data);
+ ERR_FAIL_COND_V(err != OK, data);
PoolVector<uint8_t>::Write w = data.write();
- int len = f->get_buffer(&w[0],p_length);
- ERR_FAIL_COND_V( len < 0 , PoolVector<uint8_t>());
+ int len = f->get_buffer(&w[0], p_length);
+ ERR_FAIL_COND_V(len < 0, PoolVector<uint8_t>());
w = PoolVector<uint8_t>::Write();
@@ -1563,10 +1498,8 @@ PoolVector<uint8_t> _File::get_buffer(int p_length) const{
data.resize(p_length);
return data;
-
}
-
String _File::get_as_text() const {
ERR_FAIL_COND_V(!f, String());
@@ -1576,42 +1509,35 @@ String _File::get_as_text() const {
f->seek(0);
String l = get_line();
- while(!eof_reached()) {
- text+=l+"\n";
+ while (!eof_reached()) {
+ text += l + "\n";
l = get_line();
}
- text+=l;
+ text += l;
f->seek(original_pos);
return text;
-
-
}
-
-String _File::get_md5(const String& p_path) const {
+String _File::get_md5(const String &p_path) const {
return FileAccess::get_md5(p_path);
-
}
-String _File::get_sha256(const String& p_path) const {
+String _File::get_sha256(const String &p_path) const {
return FileAccess::get_sha256(p_path);
-
}
+String _File::get_line() const {
-String _File::get_line() const{
-
- ERR_FAIL_COND_V(!f,String());
+ ERR_FAIL_COND_V(!f, String());
return f->get_line();
-
}
Vector<String> _File::get_csv_line(String delim) const {
- ERR_FAIL_COND_V(!f,Vector<String>());
+ ERR_FAIL_COND_V(!f, Vector<String>());
return f->get_csv_line(delim);
}
@@ -1620,79 +1546,76 @@ Vector<String> _File::get_csv_line(String delim) const {
* this flags get reset to false (little endian) on each open
*/
-void _File::set_endian_swap(bool p_swap){
+void _File::set_endian_swap(bool p_swap) {
-
- eswap=p_swap;
+ eswap = p_swap;
if (f)
f->set_endian_swap(p_swap);
-
}
-bool _File::get_endian_swap(){
-
+bool _File::get_endian_swap() {
return eswap;
}
-Error _File::get_error() const{
+Error _File::get_error() const {
if (!f)
return ERR_UNCONFIGURED;
return f->get_error();
}
-void _File::store_8(uint8_t p_dest){
+void _File::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
f->store_8(p_dest);
}
-void _File::store_16(uint16_t p_dest){
+void _File::store_16(uint16_t p_dest) {
ERR_FAIL_COND(!f);
f->store_16(p_dest);
}
-void _File::store_32(uint32_t p_dest){
+void _File::store_32(uint32_t p_dest) {
ERR_FAIL_COND(!f);
f->store_32(p_dest);
}
-void _File::store_64(uint64_t p_dest){
+void _File::store_64(uint64_t p_dest) {
ERR_FAIL_COND(!f);
f->store_64(p_dest);
}
-void _File::store_float(float p_dest){
+void _File::store_float(float p_dest) {
ERR_FAIL_COND(!f);
f->store_float(p_dest);
}
-void _File::store_double(double p_dest){
+void _File::store_double(double p_dest) {
ERR_FAIL_COND(!f);
f->store_double(p_dest);
}
-void _File::store_real(real_t p_real){
+void _File::store_real(real_t p_real) {
ERR_FAIL_COND(!f);
f->store_real(p_real);
}
-void _File::store_string(const String& p_string){
+void _File::store_string(const String &p_string) {
ERR_FAIL_COND(!f);
f->store_string(p_string);
}
-void _File::store_pascal_string(const String& p_string) {
+void _File::store_pascal_string(const String &p_string) {
ERR_FAIL_COND(!f);
@@ -1706,46 +1629,44 @@ String _File::get_pascal_string() {
return f->get_pascal_string();
};
-void _File::store_line(const String& p_string){
+void _File::store_line(const String &p_string) {
ERR_FAIL_COND(!f);
f->store_line(p_string);
}
-void _File::store_buffer(const PoolVector<uint8_t>& p_buffer){
+void _File::store_buffer(const PoolVector<uint8_t> &p_buffer) {
ERR_FAIL_COND(!f);
int len = p_buffer.size();
- if (len==0)
+ if (len == 0)
return;
PoolVector<uint8_t>::Read r = p_buffer.read();
- f->store_buffer(&r[0],len);
+ f->store_buffer(&r[0], len);
}
-bool _File::file_exists(const String& p_name) const{
+bool _File::file_exists(const String &p_name) const {
return FileAccess::exists(p_name);
-
-
}
-void _File::store_var(const Variant& p_var) {
+void _File::store_var(const Variant &p_var) {
ERR_FAIL_COND(!f);
int len;
- Error err = encode_variant(p_var,NULL,len);
- ERR_FAIL_COND( err != OK );
+ Error err = encode_variant(p_var, NULL, len);
+ ERR_FAIL_COND(err != OK);
PoolVector<uint8_t> buff;
buff.resize(len);
PoolVector<uint8_t>::Write w = buff.write();
- err = encode_variant(p_var,&w[0],len);
- ERR_FAIL_COND( err != OK );
- w=PoolVector<uint8_t>::Write();
+ err = encode_variant(p_var, &w[0], len);
+ ERR_FAIL_COND(err != OK);
+ w = PoolVector<uint8_t>::Write();
store_32(len);
store_buffer(buff);
@@ -1753,7 +1674,7 @@ void _File::store_var(const Variant& p_var) {
Variant _File::get_var() const {
- ERR_FAIL_COND_V(!f,Variant());
+ ERR_FAIL_COND_V(!f, Variant());
uint32_t len = get_32();
PoolVector<uint8_t> buff = get_buffer(len);
ERR_FAIL_COND_V(buff.size() != len, Variant());
@@ -1761,8 +1682,8 @@ Variant _File::get_var() const {
PoolVector<uint8_t>::Read r = buff.read();
Variant v;
- Error err = decode_variant(v,&r[0],len);
- ERR_FAIL_COND_V( err!=OK, Variant() );
+ Error err = decode_variant(v, &r[0], len);
+ ERR_FAIL_COND_V(err != OK, Variant());
return v;
}
@@ -1774,95 +1695,89 @@ uint64_t _File::get_modified_time(const String &p_file) const {
void _File::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("open_encrypted","path","mode_flags","key"),&_File::open_encrypted);
- ClassDB::bind_method(D_METHOD("open_encrypted_with_pass","path","mode_flags","pass"),&_File::open_encrypted_pass);
-
- ClassDB::bind_method(D_METHOD("open","path","flags"),&_File::open);
- ClassDB::bind_method(D_METHOD("close"),&_File::close);
- ClassDB::bind_method(D_METHOD("is_open"),&_File::is_open);
- ClassDB::bind_method(D_METHOD("seek","pos"),&_File::seek);
- ClassDB::bind_method(D_METHOD("seek_end","pos"),&_File::seek_end,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_pos"),&_File::get_pos);
- ClassDB::bind_method(D_METHOD("get_len"),&_File::get_len);
- ClassDB::bind_method(D_METHOD("eof_reached"),&_File::eof_reached);
- ClassDB::bind_method(D_METHOD("get_8"),&_File::get_8);
- ClassDB::bind_method(D_METHOD("get_16"),&_File::get_16);
- ClassDB::bind_method(D_METHOD("get_32"),&_File::get_32);
- ClassDB::bind_method(D_METHOD("get_64"),&_File::get_64);
- ClassDB::bind_method(D_METHOD("get_float"),&_File::get_float);
- ClassDB::bind_method(D_METHOD("get_double"),&_File::get_double);
- ClassDB::bind_method(D_METHOD("get_real"),&_File::get_real);
- ClassDB::bind_method(D_METHOD("get_buffer","len"),&_File::get_buffer);
- ClassDB::bind_method(D_METHOD("get_line"),&_File::get_line);
- ClassDB::bind_method(D_METHOD("get_as_text"),&_File::get_as_text);
- ClassDB::bind_method(D_METHOD("get_md5","path"),&_File::get_md5);
- ClassDB::bind_method(D_METHOD("get_sha256","path"),&_File::get_sha256);
- ClassDB::bind_method(D_METHOD("get_endian_swap"),&_File::get_endian_swap);
- ClassDB::bind_method(D_METHOD("set_endian_swap","enable"),&_File::set_endian_swap);
- ClassDB::bind_method(D_METHOD("get_error:Error"),&_File::get_error);
- ClassDB::bind_method(D_METHOD("get_var"),&_File::get_var);
- ClassDB::bind_method(D_METHOD("get_csv_line","delim"),&_File::get_csv_line,DEFVAL(","));
-
- ClassDB::bind_method(D_METHOD("store_8","value"),&_File::store_8);
- ClassDB::bind_method(D_METHOD("store_16","value"),&_File::store_16);
- ClassDB::bind_method(D_METHOD("store_32","value"),&_File::store_32);
- ClassDB::bind_method(D_METHOD("store_64","value"),&_File::store_64);
- ClassDB::bind_method(D_METHOD("store_float","value"),&_File::store_float);
- ClassDB::bind_method(D_METHOD("store_double","value"),&_File::store_double);
- ClassDB::bind_method(D_METHOD("store_real","value"),&_File::store_real);
- ClassDB::bind_method(D_METHOD("store_buffer","buffer"),&_File::store_buffer);
- ClassDB::bind_method(D_METHOD("store_line","line"),&_File::store_line);
- ClassDB::bind_method(D_METHOD("store_string","string"),&_File::store_string);
- ClassDB::bind_method(D_METHOD("store_var","value"),&_File::store_var);
-
- ClassDB::bind_method(D_METHOD("store_pascal_string","string"),&_File::store_pascal_string);
- ClassDB::bind_method(D_METHOD("get_pascal_string"),&_File::get_pascal_string);
-
- ClassDB::bind_method(D_METHOD("file_exists","path"),&_File::file_exists);
- ClassDB::bind_method(D_METHOD("get_modified_time", "file"),&_File::get_modified_time);
-
- BIND_CONSTANT( READ );
- BIND_CONSTANT( WRITE );
- BIND_CONSTANT( READ_WRITE );
- BIND_CONSTANT( WRITE_READ );
-}
-
-_File::_File(){
+ ClassDB::bind_method(D_METHOD("open_encrypted", "path", "mode_flags", "key"), &_File::open_encrypted);
+ ClassDB::bind_method(D_METHOD("open_encrypted_with_pass", "path", "mode_flags", "pass"), &_File::open_encrypted_pass);
+
+ ClassDB::bind_method(D_METHOD("open", "path", "flags"), &_File::open);
+ ClassDB::bind_method(D_METHOD("close"), &_File::close);
+ ClassDB::bind_method(D_METHOD("is_open"), &_File::is_open);
+ ClassDB::bind_method(D_METHOD("seek", "pos"), &_File::seek);
+ ClassDB::bind_method(D_METHOD("seek_end", "pos"), &_File::seek_end, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_pos"), &_File::get_pos);
+ ClassDB::bind_method(D_METHOD("get_len"), &_File::get_len);
+ ClassDB::bind_method(D_METHOD("eof_reached"), &_File::eof_reached);
+ ClassDB::bind_method(D_METHOD("get_8"), &_File::get_8);
+ ClassDB::bind_method(D_METHOD("get_16"), &_File::get_16);
+ ClassDB::bind_method(D_METHOD("get_32"), &_File::get_32);
+ ClassDB::bind_method(D_METHOD("get_64"), &_File::get_64);
+ ClassDB::bind_method(D_METHOD("get_float"), &_File::get_float);
+ ClassDB::bind_method(D_METHOD("get_double"), &_File::get_double);
+ ClassDB::bind_method(D_METHOD("get_real"), &_File::get_real);
+ ClassDB::bind_method(D_METHOD("get_buffer", "len"), &_File::get_buffer);
+ ClassDB::bind_method(D_METHOD("get_line"), &_File::get_line);
+ ClassDB::bind_method(D_METHOD("get_as_text"), &_File::get_as_text);
+ ClassDB::bind_method(D_METHOD("get_md5", "path"), &_File::get_md5);
+ ClassDB::bind_method(D_METHOD("get_sha256", "path"), &_File::get_sha256);
+ ClassDB::bind_method(D_METHOD("get_endian_swap"), &_File::get_endian_swap);
+ ClassDB::bind_method(D_METHOD("set_endian_swap", "enable"), &_File::set_endian_swap);
+ ClassDB::bind_method(D_METHOD("get_error:Error"), &_File::get_error);
+ ClassDB::bind_method(D_METHOD("get_var"), &_File::get_var);
+ ClassDB::bind_method(D_METHOD("get_csv_line", "delim"), &_File::get_csv_line, DEFVAL(","));
+
+ ClassDB::bind_method(D_METHOD("store_8", "value"), &_File::store_8);
+ ClassDB::bind_method(D_METHOD("store_16", "value"), &_File::store_16);
+ ClassDB::bind_method(D_METHOD("store_32", "value"), &_File::store_32);
+ ClassDB::bind_method(D_METHOD("store_64", "value"), &_File::store_64);
+ ClassDB::bind_method(D_METHOD("store_float", "value"), &_File::store_float);
+ ClassDB::bind_method(D_METHOD("store_double", "value"), &_File::store_double);
+ ClassDB::bind_method(D_METHOD("store_real", "value"), &_File::store_real);
+ ClassDB::bind_method(D_METHOD("store_buffer", "buffer"), &_File::store_buffer);
+ ClassDB::bind_method(D_METHOD("store_line", "line"), &_File::store_line);
+ ClassDB::bind_method(D_METHOD("store_string", "string"), &_File::store_string);
+ ClassDB::bind_method(D_METHOD("store_var", "value"), &_File::store_var);
+
+ ClassDB::bind_method(D_METHOD("store_pascal_string", "string"), &_File::store_pascal_string);
+ ClassDB::bind_method(D_METHOD("get_pascal_string"), &_File::get_pascal_string);
+
+ ClassDB::bind_method(D_METHOD("file_exists", "path"), &_File::file_exists);
+ ClassDB::bind_method(D_METHOD("get_modified_time", "file"), &_File::get_modified_time);
+
+ BIND_CONSTANT(READ);
+ BIND_CONSTANT(WRITE);
+ BIND_CONSTANT(READ_WRITE);
+ BIND_CONSTANT(WRITE_READ);
+}
+
+_File::_File() {
f = NULL;
- eswap=false;
-
+ eswap = false;
}
-_File::~_File(){
+_File::~_File() {
if (f)
memdelete(f);
-
}
///////////////////////////////////////////////////////
-
-
-
-Error _Directory::open(const String& p_path) {
+Error _Directory::open(const String &p_path) {
Error err;
- DirAccess *alt=DirAccess::open(p_path,&err);
+ DirAccess *alt = DirAccess::open(p_path, &err);
if (!alt)
return err;
if (d)
memdelete(d);
- d=alt;
+ d = alt;
return OK;
}
Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
_list_skip_navigational = p_skip_navigational;
_list_skip_hidden = p_skip_hidden;
@@ -1870,84 +1785,80 @@ Error _Directory::list_dir_begin(bool p_skip_navigational, bool p_skip_hidden) {
return d->list_dir_begin();
}
-String _Directory::get_next(){
+String _Directory::get_next() {
- ERR_FAIL_COND_V(!d,"");
+ ERR_FAIL_COND_V(!d, "");
String next = d->get_next();
- while (next != ""
- && ((_list_skip_navigational && (next == "." || next == ".."))
- || (_list_skip_hidden && d->current_is_hidden()))) {
+ while (next != "" && ((_list_skip_navigational && (next == "." || next == "..")) || (_list_skip_hidden && d->current_is_hidden()))) {
next = d->get_next();
}
return next;
}
-bool _Directory::current_is_dir() const{
+bool _Directory::current_is_dir() const {
- ERR_FAIL_COND_V(!d,false);
+ ERR_FAIL_COND_V(!d, false);
return d->current_is_dir();
}
-void _Directory::list_dir_end(){
+void _Directory::list_dir_end() {
ERR_FAIL_COND(!d);
return d->list_dir_end();
}
-int _Directory::get_drive_count(){
+int _Directory::get_drive_count() {
- ERR_FAIL_COND_V(!d,0);
+ ERR_FAIL_COND_V(!d, 0);
return d->get_drive_count();
}
-String _Directory::get_drive(int p_drive){
+String _Directory::get_drive(int p_drive) {
- ERR_FAIL_COND_V(!d,"");
+ ERR_FAIL_COND_V(!d, "");
return d->get_drive(p_drive);
}
int _Directory::get_current_drive() {
- ERR_FAIL_COND_V(!d,0);
+ ERR_FAIL_COND_V(!d, 0);
return d->get_current_drive();
}
-Error _Directory::change_dir(String p_dir){
+Error _Directory::change_dir(String p_dir) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
return d->change_dir(p_dir);
}
String _Directory::get_current_dir() {
- ERR_FAIL_COND_V(!d,"");
+ ERR_FAIL_COND_V(!d, "");
return d->get_current_dir();
}
-Error _Directory::make_dir(String p_dir){
+Error _Directory::make_dir(String p_dir) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
if (!p_dir.is_rel_path()) {
DirAccess *d = DirAccess::create_for_path(p_dir);
Error err = d->make_dir(p_dir);
memdelete(d);
return err;
-
}
return d->make_dir(p_dir);
}
-Error _Directory::make_dir_recursive(String p_dir){
+Error _Directory::make_dir_recursive(String p_dir) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
if (!p_dir.is_rel_path()) {
DirAccess *d = DirAccess::create_for_path(p_dir);
Error err = d->make_dir_recursive(p_dir);
memdelete(d);
return err;
-
}
return d->make_dir_recursive(p_dir);
}
-bool _Directory::file_exists(String p_file){
+bool _Directory::file_exists(String p_file) {
- ERR_FAIL_COND_V(!d,false);
+ ERR_FAIL_COND_V(!d, false);
if (!p_file.is_rel_path()) {
return FileAccess::exists(p_file);
@@ -1957,7 +1868,7 @@ bool _Directory::file_exists(String p_file){
}
bool _Directory::dir_exists(String p_dir) {
- ERR_FAIL_COND_V(!d,false);
+ ERR_FAIL_COND_V(!d, false);
if (!p_dir.is_rel_path()) {
DirAccess *d = DirAccess::create_for_path(p_dir);
@@ -1970,33 +1881,32 @@ bool _Directory::dir_exists(String p_dir) {
}
}
-int _Directory::get_space_left(){
+int _Directory::get_space_left() {
- ERR_FAIL_COND_V(!d,0);
- return d->get_space_left()/1024*1024; //return value in megabytes, given binding is int
+ ERR_FAIL_COND_V(!d, 0);
+ return d->get_space_left() / 1024 * 1024; //return value in megabytes, given binding is int
}
-Error _Directory::copy(String p_from,String p_to){
+Error _Directory::copy(String p_from, String p_to) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
- return d->copy(p_from,p_to);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
+ return d->copy(p_from, p_to);
}
-Error _Directory::rename(String p_from, String p_to){
+Error _Directory::rename(String p_from, String p_to) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
if (!p_from.is_rel_path()) {
DirAccess *d = DirAccess::create_for_path(p_from);
- Error err = d->rename(p_from,p_to);
+ Error err = d->rename(p_from, p_to);
memdelete(d);
return err;
}
- return d->rename(p_from,p_to);
-
+ return d->rename(p_from, p_to);
}
-Error _Directory::remove(String p_name){
+Error _Directory::remove(String p_name) {
- ERR_FAIL_COND_V(!d,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!d, ERR_UNCONFIGURED);
if (!p_name.is_rel_path()) {
DirAccess *d = DirAccess::create_for_path(p_name);
Error err = d->remove(p_name);
@@ -2009,27 +1919,25 @@ Error _Directory::remove(String p_name){
void _Directory::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("open:Error","path"),&_Directory::open);
+ ClassDB::bind_method(D_METHOD("open:Error", "path"), &_Directory::open);
ClassDB::bind_method(D_METHOD("list_dir_begin", "skip_navigational", "skip_hidden"), &_Directory::list_dir_begin, DEFVAL(false), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_next"),&_Directory::get_next);
- ClassDB::bind_method(D_METHOD("current_is_dir"),&_Directory::current_is_dir);
- ClassDB::bind_method(D_METHOD("list_dir_end"),&_Directory::list_dir_end);
- ClassDB::bind_method(D_METHOD("get_drive_count"),&_Directory::get_drive_count);
- ClassDB::bind_method(D_METHOD("get_drive","idx"),&_Directory::get_drive);
- ClassDB::bind_method(D_METHOD("get_current_drive"),&_Directory::get_current_drive);
- ClassDB::bind_method(D_METHOD("change_dir:Error","todir"),&_Directory::change_dir);
- ClassDB::bind_method(D_METHOD("get_current_dir"),&_Directory::get_current_dir);
- ClassDB::bind_method(D_METHOD("make_dir:Error","path"),&_Directory::make_dir);
- ClassDB::bind_method(D_METHOD("make_dir_recursive:Error","path"),&_Directory::make_dir_recursive);
- ClassDB::bind_method(D_METHOD("file_exists","path"),&_Directory::file_exists);
- ClassDB::bind_method(D_METHOD("dir_exists","path"),&_Directory::dir_exists);
+ ClassDB::bind_method(D_METHOD("get_next"), &_Directory::get_next);
+ ClassDB::bind_method(D_METHOD("current_is_dir"), &_Directory::current_is_dir);
+ ClassDB::bind_method(D_METHOD("list_dir_end"), &_Directory::list_dir_end);
+ ClassDB::bind_method(D_METHOD("get_drive_count"), &_Directory::get_drive_count);
+ ClassDB::bind_method(D_METHOD("get_drive", "idx"), &_Directory::get_drive);
+ ClassDB::bind_method(D_METHOD("get_current_drive"), &_Directory::get_current_drive);
+ ClassDB::bind_method(D_METHOD("change_dir:Error", "todir"), &_Directory::change_dir);
+ ClassDB::bind_method(D_METHOD("get_current_dir"), &_Directory::get_current_dir);
+ ClassDB::bind_method(D_METHOD("make_dir:Error", "path"), &_Directory::make_dir);
+ ClassDB::bind_method(D_METHOD("make_dir_recursive:Error", "path"), &_Directory::make_dir_recursive);
+ ClassDB::bind_method(D_METHOD("file_exists", "path"), &_Directory::file_exists);
+ ClassDB::bind_method(D_METHOD("dir_exists", "path"), &_Directory::dir_exists);
//ClassDB::bind_method(D_METHOD("get_modified_time","file"),&_Directory::get_modified_time);
- ClassDB::bind_method(D_METHOD("get_space_left"),&_Directory::get_space_left);
- ClassDB::bind_method(D_METHOD("copy:Error","from","to"),&_Directory::copy);
- ClassDB::bind_method(D_METHOD("rename:Error","from","to"),&_Directory::rename);
- ClassDB::bind_method(D_METHOD("remove:Error","path"),&_Directory::remove);
-
+ ClassDB::bind_method(D_METHOD("get_space_left"), &_Directory::get_space_left);
+ ClassDB::bind_method(D_METHOD("copy:Error", "from", "to"), &_Directory::copy);
+ ClassDB::bind_method(D_METHOD("rename:Error", "from", "to"), &_Directory::rename);
+ ClassDB::bind_method(D_METHOD("remove:Error", "path"), &_Directory::remove);
}
_Directory::_Directory() {
@@ -2043,40 +1951,39 @@ _Directory::~_Directory() {
memdelete(d);
}
-_Marshalls* _Marshalls::singleton=NULL;
+_Marshalls *_Marshalls::singleton = NULL;
-_Marshalls *_Marshalls::get_singleton()
-{
+_Marshalls *_Marshalls::get_singleton() {
return singleton;
}
-String _Marshalls::variant_to_base64(const Variant& p_var) {
+String _Marshalls::variant_to_base64(const Variant &p_var) {
int len;
- Error err = encode_variant(p_var,NULL,len);
- ERR_FAIL_COND_V( err != OK, "" );
+ Error err = encode_variant(p_var, NULL, len);
+ ERR_FAIL_COND_V(err != OK, "");
PoolVector<uint8_t> buff;
buff.resize(len);
PoolVector<uint8_t>::Write w = buff.write();
- err = encode_variant(p_var,&w[0],len);
- ERR_FAIL_COND_V( err != OK, "" );
+ err = encode_variant(p_var, &w[0], len);
+ ERR_FAIL_COND_V(err != OK, "");
int b64len = len / 3 * 4 + 4 + 1;
PoolVector<uint8_t> b64buff;
b64buff.resize(b64len);
PoolVector<uint8_t>::Write w64 = b64buff.write();
- int strlen = base64_encode((char*)(&w64[0]), (char*)(&w[0]), len);
+ int strlen = base64_encode((char *)(&w64[0]), (char *)(&w[0]), len);
//OS::get_singleton()->print("len is %i, vector size is %i\n", b64len, strlen);
w64[strlen] = 0;
- String ret = (char*)&w64[0];
+ String ret = (char *)&w64[0];
return ret;
};
-Variant _Marshalls::base64_to_variant(const String& p_str) {
+Variant _Marshalls::base64_to_variant(const String &p_str) {
int strlen = p_str.length();
CharString cstr = p_str.ascii();
@@ -2085,11 +1992,11 @@ Variant _Marshalls::base64_to_variant(const String& p_str) {
buf.resize(strlen / 4 * 3 + 1);
PoolVector<uint8_t>::Write w = buf.write();
- int len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen);
+ int len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen);
Variant v;
Error err = decode_variant(v, &w[0], len);
- ERR_FAIL_COND_V( err!=OK, Variant() );
+ ERR_FAIL_COND_V(err != OK, Variant());
return v;
};
@@ -2104,9 +2011,9 @@ String _Marshalls::raw_to_base64(const PoolVector<uint8_t> &p_arr) {
b64buff.resize(b64len);
PoolVector<uint8_t>::Write w64 = b64buff.write();
- int strlen = base64_encode((char*)(&w64[0]), (char*)(&r[0]), len);
+ int strlen = base64_encode((char *)(&w64[0]), (char *)(&r[0]), len);
w64[strlen] = 0;
- String ret = (char*)&w64[0];
+ String ret = (char *)&w64[0];
return ret;
};
@@ -2122,7 +2029,7 @@ PoolVector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
buf.resize(strlen / 4 * 3 + 1);
PoolVector<uint8_t>::Write w = buf.write();
- arr_len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen);
+ arr_len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen);
};
buf.resize(arr_len);
@@ -2130,7 +2037,7 @@ PoolVector<uint8_t> _Marshalls::base64_to_raw(const String &p_str) {
return buf;
};
-String _Marshalls::utf8_to_base64(const String& p_str) {
+String _Marshalls::utf8_to_base64(const String &p_str) {
CharString cstr = p_str.utf8();
int len = cstr.length();
@@ -2140,15 +2047,15 @@ String _Marshalls::utf8_to_base64(const String& p_str) {
b64buff.resize(b64len);
PoolVector<uint8_t>::Write w64 = b64buff.write();
- int strlen = base64_encode((char*)(&w64[0]), (char*)cstr.get_data(), len);
+ int strlen = base64_encode((char *)(&w64[0]), (char *)cstr.get_data(), len);
w64[strlen] = 0;
- String ret = (char*)&w64[0];
+ String ret = (char *)&w64[0];
return ret;
};
-String _Marshalls::base64_to_utf8(const String& p_str) {
+String _Marshalls::base64_to_utf8(const String &p_str) {
int strlen = p_str.length();
CharString cstr = p_str.ascii();
@@ -2157,35 +2064,28 @@ String _Marshalls::base64_to_utf8(const String& p_str) {
buf.resize(strlen / 4 * 3 + 1 + 1);
PoolVector<uint8_t>::Write w = buf.write();
- int len = base64_decode((char*)(&w[0]), (char*)cstr.get_data(), strlen);
+ int len = base64_decode((char *)(&w[0]), (char *)cstr.get_data(), strlen);
w[len] = 0;
- String ret = String::utf8((char*)&w[0]);
+ String ret = String::utf8((char *)&w[0]);
return ret;
};
-
void _Marshalls::_bind_methods() {
- ClassDB::bind_method(D_METHOD("variant_to_base64:String","variant"),&_Marshalls::variant_to_base64);
- ClassDB::bind_method(D_METHOD("base64_to_variant:Variant","base64_str"),&_Marshalls::base64_to_variant);
-
- ClassDB::bind_method(D_METHOD("raw_to_base64:String","array"),&_Marshalls::raw_to_base64);
- ClassDB::bind_method(D_METHOD("base64_to_raw:RawArray","base64_str"),&_Marshalls::base64_to_raw);
+ ClassDB::bind_method(D_METHOD("variant_to_base64:String", "variant"), &_Marshalls::variant_to_base64);
+ ClassDB::bind_method(D_METHOD("base64_to_variant:Variant", "base64_str"), &_Marshalls::base64_to_variant);
- ClassDB::bind_method(D_METHOD("utf8_to_base64:String","utf8_str"),&_Marshalls::utf8_to_base64);
- ClassDB::bind_method(D_METHOD("base64_to_utf8:String","base64_str"),&_Marshalls::base64_to_utf8);
+ ClassDB::bind_method(D_METHOD("raw_to_base64:String", "array"), &_Marshalls::raw_to_base64);
+ ClassDB::bind_method(D_METHOD("base64_to_raw:RawArray", "base64_str"), &_Marshalls::base64_to_raw);
+ ClassDB::bind_method(D_METHOD("utf8_to_base64:String", "utf8_str"), &_Marshalls::utf8_to_base64);
+ ClassDB::bind_method(D_METHOD("base64_to_utf8:String", "base64_str"), &_Marshalls::base64_to_utf8);
};
-
-
////////////////
-
-
-
Error _Semaphore::wait() {
return semaphore->wait();
@@ -2196,133 +2096,120 @@ Error _Semaphore::post() {
return semaphore->post();
}
-
void _Semaphore::_bind_methods() {
- ClassDB::bind_method(D_METHOD("wait:Error"),&_Semaphore::wait);
- ClassDB::bind_method(D_METHOD("post:Error"),&_Semaphore::post);
-
+ ClassDB::bind_method(D_METHOD("wait:Error"), &_Semaphore::wait);
+ ClassDB::bind_method(D_METHOD("post:Error"), &_Semaphore::post);
}
-
_Semaphore::_Semaphore() {
- semaphore =Semaphore::create();
+ semaphore = Semaphore::create();
}
-_Semaphore::~_Semaphore(){
+_Semaphore::~_Semaphore() {
memdelete(semaphore);
}
-
///////////////
-
void _Mutex::lock() {
mutex->lock();
}
-Error _Mutex::try_lock(){
+Error _Mutex::try_lock() {
return mutex->try_lock();
}
-void _Mutex::unlock(){
+void _Mutex::unlock() {
mutex->unlock();
}
void _Mutex::_bind_methods() {
- ClassDB::bind_method(D_METHOD("lock"),&_Mutex::lock);
- ClassDB::bind_method(D_METHOD("try_lock:Error"),&_Mutex::try_lock);
- ClassDB::bind_method(D_METHOD("unlock"),&_Mutex::unlock);
-
+ ClassDB::bind_method(D_METHOD("lock"), &_Mutex::lock);
+ ClassDB::bind_method(D_METHOD("try_lock:Error"), &_Mutex::try_lock);
+ ClassDB::bind_method(D_METHOD("unlock"), &_Mutex::unlock);
}
-
_Mutex::_Mutex() {
- mutex =Mutex::create();
+ mutex = Mutex::create();
}
-_Mutex::~_Mutex(){
+_Mutex::~_Mutex() {
memdelete(mutex);
}
-
///////////////
-
-
void _Thread::_start_func(void *ud) {
- Ref<_Thread>* tud=(Ref<_Thread>*)ud;
- Ref<_Thread> t=*tud;
+ Ref<_Thread> *tud = (Ref<_Thread> *)ud;
+ Ref<_Thread> t = *tud;
memdelete(tud);
Variant::CallError ce;
- const Variant* arg[1]={&t->userdata};
+ const Variant *arg[1] = { &t->userdata };
Thread::set_name(t->target_method);
- t->ret=t->target_instance->call(t->target_method,arg,1,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
+ t->ret = t->target_instance->call(t->target_method, arg, 1, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
String reason;
- switch(ce.error) {
+ switch (ce.error) {
case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: {
- reason="Invalid Argument #"+itos(ce.argument);
+ reason = "Invalid Argument #" + itos(ce.argument);
} break;
case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
- reason="Too Many Arguments";
+ reason = "Too Many Arguments";
} break;
case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
- reason="Too Many Arguments";
+ reason = "Too Many Arguments";
} break;
case Variant::CallError::CALL_ERROR_INVALID_METHOD: {
- reason="Method Not Found";
+ reason = "Method Not Found";
} break;
default: {}
}
-
- ERR_EXPLAIN("Could not call function '"+t->target_method.operator String()+"'' starting thread ID: "+t->get_id()+" Reason: "+reason);
+ ERR_EXPLAIN("Could not call function '" + t->target_method.operator String() + "'' starting thread ID: " + t->get_id() + " Reason: " + reason);
ERR_FAIL();
}
-
}
-Error _Thread::start(Object *p_instance,const StringName& p_method,const Variant& p_userdata,int p_priority) {
+Error _Thread::start(Object *p_instance, const StringName &p_method, const Variant &p_userdata, int p_priority) {
- ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);
- ERR_FAIL_COND_V(!p_instance,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(p_method==StringName(),ERR_INVALID_PARAMETER);
- ERR_FAIL_INDEX_V(p_priority,3,ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(!p_instance, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_method == StringName(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_priority, 3, ERR_INVALID_PARAMETER);
+ ret = Variant();
+ target_method = p_method;
+ target_instance = p_instance;
+ userdata = p_userdata;
+ active = true;
- ret=Variant();
- target_method=p_method;
- target_instance=p_instance;
- userdata=p_userdata;
- active=true;
-
- Ref<_Thread> *ud = memnew( Ref<_Thread>(this) );
+ Ref<_Thread> *ud = memnew(Ref<_Thread>(this));
Thread::Settings s;
- s.priority=(Thread::Priority)p_priority;
- thread = Thread::create(_start_func,ud,s);
+ s.priority = (Thread::Priority)p_priority;
+ thread = Thread::create(_start_func, ud, s);
if (!thread) {
- active=false;
- target_method=StringName();
- target_instance=NULL;
- userdata=Variant();
+ active = false;
+ target_method = StringName();
+ target_instance = NULL;
+ userdata = Variant();
return ERR_CANT_CREATE;
}
@@ -2343,36 +2230,35 @@ bool _Thread::is_active() const {
}
Variant _Thread::wait_to_finish() {
- ERR_FAIL_COND_V(!thread,Variant());
- ERR_FAIL_COND_V(!active,Variant());
+ ERR_FAIL_COND_V(!thread, Variant());
+ ERR_FAIL_COND_V(!active, Variant());
Thread::wait_to_finish(thread);
Variant r = ret;
- active=false;
- target_method=StringName();
- target_instance=NULL;
- userdata=Variant();
- thread=NULL;
+ active = false;
+ target_method = StringName();
+ target_instance = NULL;
+ userdata = Variant();
+ thread = NULL;
return r;
}
void _Thread::_bind_methods() {
- ClassDB::bind_method(D_METHOD("start:Error","instance","method","userdata","priority"),&_Thread::start,DEFVAL(Variant()),DEFVAL(PRIORITY_NORMAL));
- ClassDB::bind_method(D_METHOD("get_id"),&_Thread::get_id);
- ClassDB::bind_method(D_METHOD("is_active"),&_Thread::is_active);
- ClassDB::bind_method(D_METHOD("wait_to_finish:Variant"),&_Thread::wait_to_finish);
-
- BIND_CONSTANT( PRIORITY_LOW );
- BIND_CONSTANT( PRIORITY_NORMAL );
- BIND_CONSTANT( PRIORITY_HIGH );
+ ClassDB::bind_method(D_METHOD("start:Error", "instance", "method", "userdata", "priority"), &_Thread::start, DEFVAL(Variant()), DEFVAL(PRIORITY_NORMAL));
+ ClassDB::bind_method(D_METHOD("get_id"), &_Thread::get_id);
+ ClassDB::bind_method(D_METHOD("is_active"), &_Thread::is_active);
+ ClassDB::bind_method(D_METHOD("wait_to_finish:Variant"), &_Thread::wait_to_finish);
+ BIND_CONSTANT(PRIORITY_LOW);
+ BIND_CONSTANT(PRIORITY_NORMAL);
+ BIND_CONSTANT(PRIORITY_HIGH);
}
_Thread::_Thread() {
- active=false;
- thread=NULL;
- target_instance=NULL;
+ active = false;
+ thread = NULL;
+ target_instance = NULL;
}
_Thread::~_Thread() {
@@ -2380,11 +2266,10 @@ _Thread::~_Thread() {
if (active) {
ERR_EXPLAIN("Reference to a Thread object object was lost while the thread is still running..");
}
- ERR_FAIL_COND(active==true);
+ ERR_FAIL_COND(active == true);
}
/////////////////////////////////////
-
PoolStringArray _ClassDB::get_class_list() const {
List<StringName> classes;
@@ -2392,29 +2277,28 @@ PoolStringArray _ClassDB::get_class_list() const {
PoolStringArray ret;
ret.resize(classes.size());
- int idx=0;
- for (List<StringName>::Element *E=classes.front();E;E=E->next()) {
- ret.set(idx++,E->get());
+ int idx = 0;
+ for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
+ ret.set(idx++, E->get());
}
return ret;
-
}
-PoolStringArray _ClassDB::get_inheriters_from_class( const StringName& p_class) const {
+PoolStringArray _ClassDB::get_inheriters_from_class(const StringName &p_class) const {
List<StringName> classes;
- ClassDB::get_inheriters_from_class(p_class,&classes);
+ ClassDB::get_inheriters_from_class(p_class, &classes);
PoolStringArray ret;
ret.resize(classes.size());
- int idx=0;
- for (List<StringName>::Element *E=classes.front();E;E=E->next()) {
- ret.set(idx++,E->get());
+ int idx = 0;
+ for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
+ ret.set(idx++, E->get());
}
return ret;
}
-StringName _ClassDB::get_parent_class(const StringName& p_class) const {
+StringName _ClassDB::get_parent_class(const StringName &p_class) const {
return ClassDB::get_parent_class(p_class);
}
@@ -2422,9 +2306,9 @@ bool _ClassDB::class_exists(const StringName &p_class) const {
return ClassDB::class_exists(p_class);
}
-bool _ClassDB::is_parent_class(const StringName &p_class,const StringName& p_inherits) const {
+bool _ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) const {
- return ClassDB::is_parent_class(p_class,p_inherits);
+ return ClassDB::is_parent_class(p_class, p_inherits);
}
bool _ClassDB::can_instance(const StringName &p_class) const {
@@ -2444,27 +2328,26 @@ Variant _ClassDB::instance(const StringName &p_class) const {
}
}
-bool _ClassDB::has_signal(StringName p_class,StringName p_signal) const {
+bool _ClassDB::has_signal(StringName p_class, StringName p_signal) const {
- return ClassDB::has_signal(p_class,p_signal);
+ return ClassDB::has_signal(p_class, p_signal);
}
-Dictionary _ClassDB::get_signal(StringName p_class,StringName p_signal) const {
+Dictionary _ClassDB::get_signal(StringName p_class, StringName p_signal) const {
MethodInfo signal;
- if (ClassDB::get_signal(p_class,p_signal,&signal)) {
+ if (ClassDB::get_signal(p_class, p_signal, &signal)) {
return signal.operator Dictionary();
} else {
return Dictionary();
}
-
}
-Array _ClassDB::get_signal_list(StringName p_class,bool p_no_inheritance) const {
+Array _ClassDB::get_signal_list(StringName p_class, bool p_no_inheritance) const {
List<MethodInfo> signals;
- ClassDB::get_signal_list(p_class,&signals,p_no_inheritance);
+ ClassDB::get_signal_list(p_class, &signals, p_no_inheritance);
Array ret;
- for (List<MethodInfo>::Element *E=signals.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = signals.front(); E; E = E->next()) {
ret.push_back(E->get().operator Dictionary());
}
@@ -2474,67 +2357,63 @@ Array _ClassDB::get_signal_list(StringName p_class,bool p_no_inheritance) const
Array _ClassDB::get_property_list(StringName p_class, bool p_no_inheritance) const {
List<PropertyInfo> plist;
- ClassDB::get_property_list(p_class,&plist,p_no_inheritance);
+ ClassDB::get_property_list(p_class, &plist, p_no_inheritance);
Array ret;
- for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
ret.push_back(E->get().operator Dictionary());
}
return ret;
-
-
}
-bool _ClassDB::has_method(StringName p_class,StringName p_method,bool p_no_inheritance) const {
+bool _ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) const {
- return ClassDB::has_method(p_class,p_method,p_no_inheritance);
+ return ClassDB::has_method(p_class, p_method, p_no_inheritance);
}
-
-Array _ClassDB::get_method_list(StringName p_class,bool p_no_inheritance) const {
+Array _ClassDB::get_method_list(StringName p_class, bool p_no_inheritance) const {
List<MethodInfo> methods;
- ClassDB::get_method_list(p_class,&methods,p_no_inheritance);
+ ClassDB::get_method_list(p_class, &methods, p_no_inheritance);
Array ret;
- for (List<MethodInfo>::Element *E=methods.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
ret.push_back(E->get().operator Dictionary());
}
return ret;
}
-PoolStringArray _ClassDB::get_integer_constant_list(const StringName& p_class, bool p_no_inheritance) const {
+PoolStringArray _ClassDB::get_integer_constant_list(const StringName &p_class, bool p_no_inheritance) const {
List<String> constants;
- ClassDB::get_integer_constant_list(p_class,&constants,p_no_inheritance);
+ ClassDB::get_integer_constant_list(p_class, &constants, p_no_inheritance);
PoolStringArray ret;
ret.resize(constants.size());
- int idx=0;
- for (List<String>::Element *E=constants.front();E;E=E->next()) {
- ret.set(idx++,E->get());
+ int idx = 0;
+ for (List<String>::Element *E = constants.front(); E; E = E->next()) {
+ ret.set(idx++, E->get());
}
return ret;
}
-bool _ClassDB::has_integer_constant(const StringName& p_class, const StringName &p_name) const {
+bool _ClassDB::has_integer_constant(const StringName &p_class, const StringName &p_name) const {
bool success;
- ClassDB::get_integer_constant(p_class,p_name,&success);
+ ClassDB::get_integer_constant(p_class, p_name, &success);
return success;
}
-int _ClassDB::get_integer_constant(const StringName& p_class, const StringName &p_name) const {
+int _ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name) const {
bool found;
- int c = ClassDB::get_integer_constant(p_class,p_name,&found);
- ERR_FAIL_COND_V(!found,0);
+ int c = ClassDB::get_integer_constant(p_class, p_name, &found);
+ ERR_FAIL_COND_V(!found, 0);
return c;
-
}
-StringName _ClassDB::get_category(const StringName& p_node) const {
+StringName _ClassDB::get_category(const StringName &p_node) const {
return ClassDB::get_category(p_node);
}
@@ -2546,46 +2425,39 @@ bool _ClassDB::is_class_enabled(StringName p_class) const {
void _ClassDB::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_class_list"),&_ClassDB::get_class_list);
- ClassDB::bind_method(D_METHOD("get_inheriters_from_class","class"),&_ClassDB::get_inheriters_from_class);
- ClassDB::bind_method(D_METHOD("get_parent_class","class"),&_ClassDB::get_parent_class);
- ClassDB::bind_method(D_METHOD("class_exists","class"),&_ClassDB::class_exists);
- ClassDB::bind_method(D_METHOD("is_parent_class","class","inherits"),&_ClassDB::is_parent_class);
- ClassDB::bind_method(D_METHOD("can_instance","class"),&_ClassDB::can_instance);
- ClassDB::bind_method(D_METHOD("instance:Variant","class"),&_ClassDB::instance);
+ ClassDB::bind_method(D_METHOD("get_class_list"), &_ClassDB::get_class_list);
+ ClassDB::bind_method(D_METHOD("get_inheriters_from_class", "class"), &_ClassDB::get_inheriters_from_class);
+ ClassDB::bind_method(D_METHOD("get_parent_class", "class"), &_ClassDB::get_parent_class);
+ ClassDB::bind_method(D_METHOD("class_exists", "class"), &_ClassDB::class_exists);
+ ClassDB::bind_method(D_METHOD("is_parent_class", "class", "inherits"), &_ClassDB::is_parent_class);
+ ClassDB::bind_method(D_METHOD("can_instance", "class"), &_ClassDB::can_instance);
+ ClassDB::bind_method(D_METHOD("instance:Variant", "class"), &_ClassDB::instance);
- ClassDB::bind_method(D_METHOD("class_has_signal","class","signal"),&_ClassDB::has_signal);
- ClassDB::bind_method(D_METHOD("class_get_signal","class","signal"),&_ClassDB::get_signal);
- ClassDB::bind_method(D_METHOD("class_get_signal_list","class","no_inheritance"),&_ClassDB::get_signal_list,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("class_has_signal", "class", "signal"), &_ClassDB::has_signal);
+ ClassDB::bind_method(D_METHOD("class_get_signal", "class", "signal"), &_ClassDB::get_signal);
+ ClassDB::bind_method(D_METHOD("class_get_signal_list", "class", "no_inheritance"), &_ClassDB::get_signal_list, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("class_get_property_list","class","no_inheritance"),&_ClassDB::get_property_list,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("class_get_property_list", "class", "no_inheritance"), &_ClassDB::get_property_list, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("class_has_method","class","method","no_inheritance"),&_ClassDB::has_method,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("class_has_method", "class", "method", "no_inheritance"), &_ClassDB::has_method, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("class_get_method_list","class","no_inheritance"),&_ClassDB::get_method_list,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("class_get_method_list", "class", "no_inheritance"), &_ClassDB::get_method_list, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("class_get_integer_constant_list","class","no_inheritance"),&_ClassDB::get_integer_constant_list,DEFVAL(false));
-
- ClassDB::bind_method(D_METHOD("class_has_integer_constant","class","name"),&_ClassDB::has_integer_constant);
- ClassDB::bind_method(D_METHOD("class_get_integer_constant","class","name"),&_ClassDB::get_integer_constant);
-
- ClassDB::bind_method(D_METHOD("class_get_category","class"),&_ClassDB::get_category);
- ClassDB::bind_method(D_METHOD("is_class_enabled","class"),&_ClassDB::is_class_enabled);
+ ClassDB::bind_method(D_METHOD("class_get_integer_constant_list", "class", "no_inheritance"), &_ClassDB::get_integer_constant_list, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("class_has_integer_constant", "class", "name"), &_ClassDB::has_integer_constant);
+ ClassDB::bind_method(D_METHOD("class_get_integer_constant", "class", "name"), &_ClassDB::get_integer_constant);
+ ClassDB::bind_method(D_METHOD("class_get_category", "class"), &_ClassDB::get_category);
+ ClassDB::bind_method(D_METHOD("is_class_enabled", "class"), &_ClassDB::is_class_enabled);
}
-_ClassDB::_ClassDB(){
-
-
+_ClassDB::_ClassDB() {
}
-_ClassDB::~_ClassDB(){
-
-
+_ClassDB::~_ClassDB() {
}
///////////////////////////////
-
void _Engine::set_iterations_per_second(int p_ips) {
Engine::get_singleton()->set_iterations_per_second(p_ips);
@@ -2593,7 +2465,6 @@ void _Engine::set_iterations_per_second(int p_ips) {
int _Engine::get_iterations_per_second() const {
return Engine::get_singleton()->get_iterations_per_second();
-
}
void _Engine::set_target_fps(int p_fps) {
@@ -2604,8 +2475,6 @@ float _Engine::get_target_fps() const {
return Engine::get_singleton()->get_target_fps();
}
-
-
float _Engine::get_frames_per_second() const {
return Engine::get_singleton()->get_frames_per_second();
@@ -2625,7 +2494,7 @@ float _Engine::get_time_scale() {
return Engine::get_singleton()->get_time_scale();
}
-int _Engine::get_frames_drawn() {
+int _Engine::get_frames_drawn() {
return Engine::get_singleton()->get_frames_drawn();
}
@@ -2641,30 +2510,28 @@ Dictionary _Engine::get_version_info() const {
return Engine::get_singleton()->get_version_info();
}
-
void _Engine::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_iterations_per_second","iterations_per_second"),&_Engine::set_iterations_per_second);
- ClassDB::bind_method(D_METHOD("get_iterations_per_second"),&_Engine::get_iterations_per_second);
- ClassDB::bind_method(D_METHOD("set_target_fps","target_fps"),&_Engine::set_target_fps);
- ClassDB::bind_method(D_METHOD("get_target_fps"),&_Engine::get_target_fps);
-
- ClassDB::bind_method(D_METHOD("set_time_scale","time_scale"),&_Engine::set_time_scale);
- ClassDB::bind_method(D_METHOD("get_time_scale"),&_Engine::get_time_scale);
+ ClassDB::bind_method(D_METHOD("set_iterations_per_second", "iterations_per_second"), &_Engine::set_iterations_per_second);
+ ClassDB::bind_method(D_METHOD("get_iterations_per_second"), &_Engine::get_iterations_per_second);
+ ClassDB::bind_method(D_METHOD("set_target_fps", "target_fps"), &_Engine::set_target_fps);
+ ClassDB::bind_method(D_METHOD("get_target_fps"), &_Engine::get_target_fps);
- ClassDB::bind_method(D_METHOD("get_custom_level"),&_Engine::get_custom_level);
+ ClassDB::bind_method(D_METHOD("set_time_scale", "time_scale"), &_Engine::set_time_scale);
+ ClassDB::bind_method(D_METHOD("get_time_scale"), &_Engine::get_time_scale);
- ClassDB::bind_method(D_METHOD("get_frames_drawn"),&_Engine::get_frames_drawn);
- ClassDB::bind_method(D_METHOD("get_frames_per_second"),&_Engine::get_frames_per_second);
+ ClassDB::bind_method(D_METHOD("get_custom_level"), &_Engine::get_custom_level);
- ClassDB::bind_method(D_METHOD("get_main_loop:MainLoop"),&_Engine::get_main_loop);
+ ClassDB::bind_method(D_METHOD("get_frames_drawn"), &_Engine::get_frames_drawn);
+ ClassDB::bind_method(D_METHOD("get_frames_per_second"), &_Engine::get_frames_per_second);
- ClassDB::bind_method(D_METHOD("get_version_info"),&_Engine::get_version_info);
+ ClassDB::bind_method(D_METHOD("get_main_loop:MainLoop"), &_Engine::get_main_loop);
+ ClassDB::bind_method(D_METHOD("get_version_info"), &_Engine::get_version_info);
}
_Engine *_Engine::singleton = NULL;
_Engine::_Engine() {
- singleton=this;
+ singleton = this;
}
diff --git a/core/bind/core_bind.h b/core/bind/core_bind.h
index 6b9ae198ef..1d231ff033 100644
--- a/core/bind/core_bind.h
+++ b/core/bind/core_bind.h
@@ -31,73 +31,67 @@
#include "io/resource_loader.h"
#include "io/resource_saver.h"
-#include "os/file_access.h"
#include "os/dir_access.h"
-#include "os/thread.h"
-#include "os/semaphore.h"
+#include "os/file_access.h"
#include "os/power.h"
+#include "os/semaphore.h"
+#include "os/thread.h"
-
-class _ResourceLoader : public Object {
- GDCLASS(_ResourceLoader,Object);
+class _ResourceLoader : public Object {
+ GDCLASS(_ResourceLoader, Object);
protected:
-
static void _bind_methods();
static _ResourceLoader *singleton;
-public:
-
+public:
static _ResourceLoader *get_singleton() { return singleton; }
- Ref<ResourceInteractiveLoader> load_interactive(const String& p_path,const String& p_type_hint="");
- RES load(const String &p_path,const String& p_type_hint="", bool p_no_cache = false);
- PoolVector<String> get_recognized_extensions_for_type(const String& p_type);
+ Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "");
+ RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false);
+ PoolVector<String> get_recognized_extensions_for_type(const String &p_type);
void set_abort_on_missing_resources(bool p_abort);
- PoolStringArray get_dependencies(const String& p_path);
- bool has(const String& p_path);
+ PoolStringArray get_dependencies(const String &p_path);
+ bool has(const String &p_path);
_ResourceLoader();
};
-class _ResourceSaver : public Object {
- GDCLASS(_ResourceSaver,Object);
+class _ResourceSaver : public Object {
+ GDCLASS(_ResourceSaver, Object);
protected:
-
static void _bind_methods();
static _ResourceSaver *singleton;
-public:
+public:
enum SaverFlags {
- FLAG_RELATIVE_PATHS=1,
- FLAG_BUNDLE_RESOURCES=2,
- FLAG_CHANGE_PATH=4,
- FLAG_OMIT_EDITOR_PROPERTIES=8,
- FLAG_SAVE_BIG_ENDIAN=16,
- FLAG_COMPRESS=32,
+ FLAG_RELATIVE_PATHS = 1,
+ FLAG_BUNDLE_RESOURCES = 2,
+ FLAG_CHANGE_PATH = 4,
+ FLAG_OMIT_EDITOR_PROPERTIES = 8,
+ FLAG_SAVE_BIG_ENDIAN = 16,
+ FLAG_COMPRESS = 32,
};
static _ResourceSaver *get_singleton() { return singleton; }
- Error save(const String &p_path,const RES& p_resource, uint32_t p_flags);
- PoolVector<String> get_recognized_extensions(const RES& p_resource);
-
+ Error save(const String &p_path, const RES &p_resource, uint32_t p_flags);
+ PoolVector<String> get_recognized_extensions(const RES &p_resource);
_ResourceSaver();
};
class MainLoop;
-class _OS : public Object {
- GDCLASS(_OS,Object);
+class _OS : public Object {
+ GDCLASS(_OS, Object);
protected:
-
static void _bind_methods();
static _OS *singleton;
-public:
+public:
enum Weekday {
DAY_SUNDAY,
DAY_MONDAY,
@@ -126,30 +120,28 @@ public:
};
Point2 get_mouse_pos() const;
- void set_window_title(const String& p_title);
+ void set_window_title(const String &p_title);
int get_mouse_button_state() const;
-
- void set_clipboard(const String& p_text);
+ void set_clipboard(const String &p_text);
String get_clipboard() const;
- void set_video_mode(const Size2& p_size, bool p_fullscreen,bool p_resizeable,int p_screen=0);
- Size2 get_video_mode(int p_screen=0) const;
- bool is_video_mode_fullscreen(int p_screen=0) const;
- bool is_video_mode_resizable(int p_screen=0) const;
- Array get_fullscreen_mode_list(int p_screen=0) const;
-
+ void set_video_mode(const Size2 &p_size, bool p_fullscreen, bool p_resizeable, int p_screen = 0);
+ Size2 get_video_mode(int p_screen = 0) const;
+ bool is_video_mode_fullscreen(int p_screen = 0) const;
+ bool is_video_mode_resizable(int p_screen = 0) const;
+ Array get_fullscreen_mode_list(int p_screen = 0) const;
virtual int get_screen_count() const;
virtual int get_current_screen() const;
virtual void set_current_screen(int p_screen);
- virtual Point2 get_screen_position(int p_screen=0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
- virtual int get_screen_dpi(int p_screen=0) const;
+ virtual Point2 get_screen_position(int p_screen = 0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
+ virtual int get_screen_dpi(int p_screen = 0) const;
virtual Point2 get_window_position() const;
- virtual void set_window_position(const Point2& p_position);
+ virtual void set_window_position(const Point2 &p_position);
virtual Size2 get_window_size() const;
- virtual void set_window_size(const Size2& p_size);
+ virtual void set_window_size(const Size2 &p_size);
virtual void set_window_fullscreen(bool p_enabled);
virtual bool is_window_fullscreen() const;
virtual void set_window_resizable(bool p_enabled);
@@ -173,15 +165,15 @@ public:
bool is_in_low_processor_usage_mode() const;
String get_executable_path() const;
- int execute(const String& p_path, const Vector<String> & p_arguments,bool p_blocking,Array p_output=Array());
+ int execute(const String &p_path, const Vector<String> &p_arguments, bool p_blocking, Array p_output = Array());
Error kill(int p_pid);
Error shell_open(String p_uri);
int get_process_ID() const;
- bool has_environment(const String& p_var) const;
- String get_environment(const String& p_var) const;
+ bool has_environment(const String &p_var) const;
+ String get_environment(const String &p_var) const;
String get_name() const;
Vector<String> get_cmdline_args();
@@ -191,18 +183,17 @@ public:
String get_model_name() const;
-
- void dump_memory_to_file(const String& p_file);
- void dump_resources_to_file(const String& p_file);
+ void dump_memory_to_file(const String &p_file);
+ void dump_resources_to_file(const String &p_file);
bool has_virtual_keyboard() const;
- void show_virtual_keyboard(const String& p_existing_text="");
+ void show_virtual_keyboard(const String &p_existing_text = "");
void hide_virtual_keyboard();
- void print_resources_in_use(bool p_short=false);
- void print_all_resources(const String& p_to_file);
+ void print_resources_in_use(bool p_short = false);
+ void print_all_resources(const String &p_to_file);
void print_all_textures_by_size();
- void print_resources_by_type(const Vector<String>& p_types);
+ void print_resources_by_type(const Vector<String> &p_types);
bool has_touchscreen_ui_hint() const;
@@ -212,8 +203,7 @@ public:
String get_scancode_string(uint32_t p_code) const;
bool is_scancode_unicode(uint32_t p_unicode) const;
- int find_scancode_from_string(const String& p_code) const;
-
+ int find_scancode_from_string(const String &p_code) const;
/*
struct Date {
@@ -235,7 +225,7 @@ public:
void set_use_file_access_save_and_swap(bool p_enable);
- void set_icon(const Image& p_icon);
+ void set_icon(const Image &p_icon);
int get_exit_code() const;
void set_exit_code(int p_code);
@@ -289,11 +279,9 @@ public:
String get_system_dir(SystemDir p_dir) const;
-
String get_data_dir() const;
- void alert(const String& p_alert,const String& p_title="ALERT!");
-
+ void alert(const String &p_alert, const String &p_title = "ALERT!");
void set_screen_orientation(ScreenOrientation p_orientation);
ScreenOrientation get_screen_orientation() const;
@@ -301,10 +289,9 @@ public:
void set_keep_screen_on(bool p_enabled);
bool is_keep_screen_on() const;
-
bool is_ok_left_and_cancel_right() const;
- Error set_thread_name(const String& p_name);
+ Error set_thread_name(const String &p_name);
void set_use_vsync(bool p_enable);
bool is_vsync_enabled() const;
@@ -321,76 +308,71 @@ public:
VARIANT_ENUM_CAST(_OS::SystemDir);
VARIANT_ENUM_CAST(_OS::ScreenOrientation);
-
class _Geometry : public Object {
GDCLASS(_Geometry, Object);
static _Geometry *singleton;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
static _Geometry *get_singleton();
- PoolVector<Plane> build_box_planes(const Vector3& p_extents);
- PoolVector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z);
- PoolVector<Plane> build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis=Vector3::AXIS_Z);
- Variant segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b);
- PoolVector<Vector2> get_closest_points_between_segments_2d( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2);
- PoolVector<Vector3> get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2);
- Vector2 get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b);
- Vector3 get_closest_point_to_segment(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b);
- Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2& p_a,const Vector2& p_b);
- Vector3 get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3& p_a,const Vector3& p_b);
- Variant ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2);
- Variant segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2);
- bool point_is_inside_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c) const;
-
- PoolVector<Vector3> segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius);
- PoolVector<Vector3> segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, float p_height,float p_radius);
- PoolVector<Vector3> segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Vector<Plane>& p_planes);
- real_t segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius);
- int get_uv84_normal_bit(const Vector3& p_vector);
-
- Vector<int> triangulate_polygon(const Vector<Vector2>& p_polygon);
-
- Dictionary make_atlas(const Vector<Size2>& p_rects);
+ PoolVector<Plane> build_box_planes(const Vector3 &p_extents);
+ PoolVector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ PoolVector<Plane> build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ Variant segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b);
+ PoolVector<Vector2> get_closest_points_between_segments_2d(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2);
+ PoolVector<Vector3> get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2);
+ Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b);
+ Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b);
+ Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 &p_a, const Vector2 &p_b);
+ Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 &p_a, const Vector3 &p_b);
+ Variant ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2);
+ Variant segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2);
+ bool point_is_inside_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) const;
+
+ PoolVector<Vector3> segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius);
+ PoolVector<Vector3> segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius);
+ PoolVector<Vector3> segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Vector<Plane> &p_planes);
+ real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius);
+ int get_uv84_normal_bit(const Vector3 &p_vector);
+
+ Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon);
+
+ Dictionary make_atlas(const Vector<Size2> &p_rects);
_Geometry();
};
-
-
-
class _File : public Reference {
- GDCLASS(_File,Reference);
+ GDCLASS(_File, Reference);
FileAccess *f;
bool eswap;
-protected:
+protected:
static void _bind_methods();
-public:
- enum ModeFlags {
+public:
+ enum ModeFlags {
- READ=1,
- WRITE=2,
- READ_WRITE=3,
- WRITE_READ=7,
+ READ = 1,
+ WRITE = 2,
+ READ_WRITE = 3,
+ WRITE_READ = 7,
};
- Error open_encrypted(const String& p_path, int p_mode_flags,const Vector<uint8_t>& p_key);
- Error open_encrypted_pass(const String& p_path, int p_mode_flags,const String& p_pass);
-
+ Error open_encrypted(const String &p_path, int p_mode_flags, const Vector<uint8_t> &p_key);
+ Error open_encrypted_pass(const String &p_path, int p_mode_flags, const String &p_pass);
- Error open(const String& p_path, int p_mode_flags); ///< open a file
+ Error open(const String &p_path, int p_mode_flags); ///< open a file
void close(); ///< close a file
bool is_open() const; ///< true when file is open
void seek(int64_t p_position); ///< seek to a given position
- void seek_end(int64_t p_position=0); ///< seek from the end of file
+ void seek_end(int64_t p_position = 0); ///< seek from the end of file
int64_t get_pos() const; ///< get position in the file
int64_t get_len() const; ///< get size of the file
@@ -410,8 +392,8 @@ public:
PoolVector<uint8_t> get_buffer(int p_length) const; ///< get an array of bytes
String get_line() const;
String get_as_text() const;
- String get_md5(const String& p_path) const;
- String get_sha256(const String& p_path) const;
+ String get_md5(const String &p_path) const;
+ String get_sha256(const String &p_path) const;
/**< use this for files WRITTEN in _big_ endian machines (ie, amiga/mac)
* It's not about the current CPU type but file formats.
@@ -432,38 +414,36 @@ public:
void store_double(double p_dest);
void store_real(real_t p_real);
- void store_string(const String& p_string);
- void store_line(const String& p_string);
+ void store_string(const String &p_string);
+ void store_line(const String &p_string);
- virtual void store_pascal_string(const String& p_string);
+ virtual void store_pascal_string(const String &p_string);
virtual String get_pascal_string();
- Vector<String> get_csv_line(String delim=",") const;
+ Vector<String> get_csv_line(String delim = ",") const;
+ void store_buffer(const PoolVector<uint8_t> &p_buffer); ///< store an array of bytes
- void store_buffer(const PoolVector<uint8_t>& p_buffer); ///< store an array of bytes
+ void store_var(const Variant &p_var);
- void store_var(const Variant& p_var);
+ bool file_exists(const String &p_name) const; ///< return true if a file exists
- bool file_exists(const String& p_name) const; ///< return true if a file exists
-
- uint64_t get_modified_time(const String& p_file) const;
+ uint64_t get_modified_time(const String &p_file) const;
_File();
virtual ~_File();
-
};
class _Directory : public Reference {
- GDCLASS(_Directory,Reference);
+ GDCLASS(_Directory, Reference);
DirAccess *d;
-protected:
+protected:
static void _bind_methods();
-public:
- Error open(const String& p_path);
+public:
+ Error open(const String &p_path);
Error list_dir_begin(bool p_skip_internal = false, bool p_skip_hidden = false); ///< This starts dir listing
String get_next();
@@ -486,11 +466,10 @@ public:
int get_space_left();
- Error copy(String p_from,String p_to);
+ Error copy(String p_from, String p_to);
Error rename(String p_from, String p_to);
Error remove(String p_name);
-
_Directory();
virtual ~_Directory();
@@ -501,41 +480,37 @@ private:
class _Marshalls : public Reference {
- GDCLASS(_Marshalls,Reference);
+ GDCLASS(_Marshalls, Reference);
- static _Marshalls* singleton;
+ static _Marshalls *singleton;
protected:
-
static void _bind_methods();
-
public:
+ static _Marshalls *get_singleton();
- static _Marshalls* get_singleton();
-
- String variant_to_base64(const Variant& p_var);
- Variant base64_to_variant(const String& p_str);
+ String variant_to_base64(const Variant &p_var);
+ Variant base64_to_variant(const String &p_str);
- String raw_to_base64(const PoolVector<uint8_t>& p_arr);
- PoolVector<uint8_t> base64_to_raw(const String& p_str);
+ String raw_to_base64(const PoolVector<uint8_t> &p_arr);
+ PoolVector<uint8_t> base64_to_raw(const String &p_str);
- String utf8_to_base64(const String& p_str);
- String base64_to_utf8(const String& p_str);
+ String utf8_to_base64(const String &p_str);
+ String base64_to_utf8(const String &p_str);
_Marshalls() { singleton = this; }
~_Marshalls() { singleton = NULL; }
};
-
class _Mutex : public Reference {
- GDCLASS(_Mutex,Reference);
+ GDCLASS(_Mutex, Reference);
Mutex *mutex;
static void _bind_methods();
-public:
+public:
void lock();
Error try_lock();
void unlock();
@@ -546,12 +521,12 @@ public:
class _Semaphore : public Reference {
- GDCLASS(_Semaphore,Reference);
+ GDCLASS(_Semaphore, Reference);
Semaphore *semaphore;
static void _bind_methods();
-public:
+public:
Error wait();
Error post();
@@ -561,10 +536,9 @@ public:
class _Thread : public Reference {
- GDCLASS(_Thread,Reference);
+ GDCLASS(_Thread, Reference);
protected:
-
Variant ret;
Variant userdata;
volatile bool active;
@@ -573,8 +547,8 @@ protected:
Thread *thread;
static void _bind_methods();
static void _start_func(void *ud);
-public:
+public:
enum Priority {
PRIORITY_LOW,
@@ -582,7 +556,7 @@ public:
PRIORITY_HIGH
};
- Error start(Object *p_instance,const StringName& p_method,const Variant& p_userdata=Variant(),int p_priority=PRIORITY_NORMAL);
+ Error start(Object *p_instance, const StringName &p_method, const Variant &p_userdata = Variant(), int p_priority = PRIORITY_NORMAL);
String get_id() const;
bool is_active() const;
Variant wait_to_finish();
@@ -593,35 +567,34 @@ public:
class _ClassDB : public Object {
- GDCLASS(_ClassDB,Object)
+ GDCLASS(_ClassDB, Object)
protected:
static void _bind_methods();
-public:
+public:
PoolStringArray get_class_list() const;
- PoolStringArray get_inheriters_from_class( const StringName& p_class) const;
- StringName get_parent_class(const StringName& p_class) const;
+ PoolStringArray get_inheriters_from_class(const StringName &p_class) const;
+ StringName get_parent_class(const StringName &p_class) const;
bool class_exists(const StringName &p_class) const;
- bool is_parent_class(const StringName &p_class,const StringName& p_inherits) const;
+ bool is_parent_class(const StringName &p_class, const StringName &p_inherits) const;
bool can_instance(const StringName &p_class) const;
Variant instance(const StringName &p_class) const;
- bool has_signal(StringName p_class,StringName p_signal) const;
- Dictionary get_signal(StringName p_class,StringName p_signal) const;
- Array get_signal_list(StringName p_class,bool p_no_inheritance=false) const;
+ bool has_signal(StringName p_class, StringName p_signal) const;
+ Dictionary get_signal(StringName p_class, StringName p_signal) const;
+ Array get_signal_list(StringName p_class, bool p_no_inheritance = false) const;
- Array get_property_list(StringName p_class, bool p_no_inheritance=false) const;
+ Array get_property_list(StringName p_class, bool p_no_inheritance = false) const;
- bool has_method(StringName p_class,StringName p_method,bool p_no_inheritance=false) const;
+ bool has_method(StringName p_class, StringName p_method, bool p_no_inheritance = false) const;
+ Array get_method_list(StringName p_class, bool p_no_inheritance = false) const;
- Array get_method_list(StringName p_class,bool p_no_inheritance=false) const;
-
- PoolStringArray get_integer_constant_list(const StringName& p_class, bool p_no_inheritance=false) const;
- bool has_integer_constant(const StringName& p_class, const StringName &p_name) const;
- int get_integer_constant(const StringName& p_class, const StringName &p_name) const;
- StringName get_category(const StringName& p_node) const;
+ PoolStringArray get_integer_constant_list(const StringName &p_class, bool p_no_inheritance = false) const;
+ bool has_integer_constant(const StringName &p_class, const StringName &p_name) const;
+ int get_integer_constant(const StringName &p_class, const StringName &p_name) const;
+ StringName get_category(const StringName &p_node) const;
bool is_class_enabled(StringName p_class) const;
@@ -629,18 +602,15 @@ public:
~_ClassDB();
};
-
-class _Engine : public Object {
- GDCLASS(_Engine,Object);
+class _Engine : public Object {
+ GDCLASS(_Engine, Object);
protected:
-
static void _bind_methods();
static _Engine *singleton;
public:
-
- static _Engine* get_singleton() { return singleton; }
+ static _Engine *get_singleton() { return singleton; }
void set_iterations_per_second(int p_ips);
int get_iterations_per_second() const;
@@ -649,7 +619,7 @@ public:
float get_frames_per_second() const;
- int get_frames_drawn();
+ int get_frames_drawn();
void set_time_scale(float p_scale);
float get_time_scale();
@@ -663,5 +633,4 @@ public:
_Engine();
};
-
#endif // CORE_BIND_H
diff --git a/core/class_db.cpp b/core/class_db.cpp
index 4bdae45fb9..3c376f7451 100644
--- a/core/class_db.cpp
+++ b/core/class_db.cpp
@@ -44,200 +44,196 @@
#ifdef DEBUG_METHODS_ENABLED
-ParamDef::ParamDef(const Variant& p_variant) { used=true; val=p_variant; }
-
+ParamDef::ParamDef(const Variant &p_variant) {
+ used = true;
+ val = p_variant;
+}
-MethodDefinition D_METHOD(const char* p_name) {
+MethodDefinition D_METHOD(const char *p_name) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.push_back(StaticCString::create(p_arg1));
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(2);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(3);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(4);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(5);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
return md;
}
-
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(6);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
- md.args[5]=StaticCString::create(p_arg6);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
+ md.args[5] = StaticCString::create(p_arg6);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(7);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
- md.args[5]=StaticCString::create(p_arg6);
- md.args[6]=StaticCString::create(p_arg7);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
+ md.args[5] = StaticCString::create(p_arg6);
+ md.args[6] = StaticCString::create(p_arg7);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(8);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
- md.args[5]=StaticCString::create(p_arg6);
- md.args[6]=StaticCString::create(p_arg7);
- md.args[7]=StaticCString::create(p_arg8);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
+ md.args[5] = StaticCString::create(p_arg6);
+ md.args[6] = StaticCString::create(p_arg7);
+ md.args[7] = StaticCString::create(p_arg8);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(9);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
- md.args[5]=StaticCString::create(p_arg6);
- md.args[6]=StaticCString::create(p_arg7);
- md.args[7]=StaticCString::create(p_arg8);
- md.args[8]=StaticCString::create(p_arg9);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
+ md.args[5] = StaticCString::create(p_arg6);
+ md.args[6] = StaticCString::create(p_arg7);
+ md.args[7] = StaticCString::create(p_arg8);
+ md.args[8] = StaticCString::create(p_arg9);
return md;
}
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9,const char *p_arg10) {
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10) {
MethodDefinition md;
- md.name=StaticCString::create(p_name);
+ md.name = StaticCString::create(p_name);
md.args.resize(10);
- md.args[0]=StaticCString::create(p_arg1);
- md.args[1]=StaticCString::create(p_arg2);
- md.args[2]=StaticCString::create(p_arg3);
- md.args[3]=StaticCString::create(p_arg4);
- md.args[4]=StaticCString::create(p_arg5);
- md.args[5]=StaticCString::create(p_arg6);
- md.args[6]=StaticCString::create(p_arg7);
- md.args[7]=StaticCString::create(p_arg8);
- md.args[8]=StaticCString::create(p_arg9);
- md.args[9]=StaticCString::create(p_arg10);
+ md.args[0] = StaticCString::create(p_arg1);
+ md.args[1] = StaticCString::create(p_arg2);
+ md.args[2] = StaticCString::create(p_arg3);
+ md.args[3] = StaticCString::create(p_arg4);
+ md.args[4] = StaticCString::create(p_arg5);
+ md.args[5] = StaticCString::create(p_arg6);
+ md.args[6] = StaticCString::create(p_arg7);
+ md.args[7] = StaticCString::create(p_arg8);
+ md.args[8] = StaticCString::create(p_arg9);
+ md.args[9] = StaticCString::create(p_arg10);
return md;
}
-
#endif
-
-ClassDB::APIType ClassDB::current_api=API_CORE;
+ClassDB::APIType ClassDB::current_api = API_CORE;
void ClassDB::set_current_api(APIType p_api) {
- current_api=p_api;
+ current_api = p_api;
}
-HashMap<StringName,ClassDB::ClassInfo,StringNameHasher> ClassDB::classes;
-HashMap<StringName,StringName,StringNameHasher> ClassDB::resource_base_extensions;
-HashMap<StringName,StringName,StringNameHasher> ClassDB::compat_classes;
+HashMap<StringName, ClassDB::ClassInfo, StringNameHasher> ClassDB::classes;
+HashMap<StringName, StringName, StringNameHasher> ClassDB::resource_base_extensions;
+HashMap<StringName, StringName, StringNameHasher> ClassDB::compat_classes;
ClassDB::ClassInfo::ClassInfo() {
- creation_func=NULL;
- inherits_ptr=NULL;
- disabled=false;
+ creation_func = NULL;
+ inherits_ptr = NULL;
+ disabled = false;
}
ClassDB::ClassInfo::~ClassInfo() {
-
-
}
-
-bool ClassDB::is_parent_class(const StringName &p_class,const StringName& p_inherits) {
+bool ClassDB::is_parent_class(const StringName &p_class, const StringName &p_inherits) {
OBJTYPE_RLOCK;
- StringName inherits=p_class;
+ StringName inherits = p_class;
while (inherits.operator String().length()) {
- if (inherits==p_inherits)
+ if (inherits == p_inherits)
return true;
- inherits=get_parent_class(inherits);
+ inherits = get_parent_class(inherits);
}
return false;
}
-void ClassDB::get_class_list( List<StringName> *p_classes) {
+void ClassDB::get_class_list(List<StringName> *p_classes) {
OBJTYPE_RLOCK;
- const StringName *k=NULL;
+ const StringName *k = NULL;
- while((k=classes.next(k))) {
+ while ((k = classes.next(k))) {
p_classes->push_back(*k);
}
@@ -245,22 +241,20 @@ void ClassDB::get_class_list( List<StringName> *p_classes) {
p_classes->sort();
}
-
-void ClassDB::get_inheriters_from_class( const StringName& p_class,List<StringName> *p_classes) {
+void ClassDB::get_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes) {
OBJTYPE_RLOCK;
- const StringName *k=NULL;
+ const StringName *k = NULL;
- while((k=classes.next(k))) {
+ while ((k = classes.next(k))) {
- if (*k!=p_class && is_parent_class(*k,p_class))
+ if (*k != p_class && is_parent_class(*k, p_class))
p_classes->push_back(*k);
}
-
}
-StringName ClassDB::get_parent_class_nocheck(const StringName& p_class) {
+StringName ClassDB::get_parent_class_nocheck(const StringName &p_class) {
OBJTYPE_RLOCK;
@@ -268,15 +262,14 @@ StringName ClassDB::get_parent_class_nocheck(const StringName& p_class) {
if (!ti)
return StringName();
return ti->inherits;
-
}
-StringName ClassDB::get_parent_class(const StringName& p_class) {
+StringName ClassDB::get_parent_class(const StringName &p_class) {
OBJTYPE_RLOCK;
ClassInfo *ti = classes.getptr(p_class);
- ERR_FAIL_COND_V(!ti,StringName());
+ ERR_FAIL_COND_V(!ti, StringName());
return ti->inherits;
}
@@ -286,7 +279,7 @@ ClassDB::APIType ClassDB::get_api_type(const StringName &p_class) {
ClassInfo *ti = classes.getptr(p_class);
- ERR_FAIL_COND_V(!ti,API_NONE);
+ ERR_FAIL_COND_V(!ti, API_NONE);
return ti->api;
}
@@ -299,105 +292,102 @@ uint64_t ClassDB::get_api_hash(APIType p_api) {
List<StringName> names;
- const StringName *k=NULL;
+ const StringName *k = NULL;
- while((k=classes.next(k))) {
+ while ((k = 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()) {
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
ClassInfo *t = classes.getptr(E->get());
- ERR_FAIL_COND_V(!t,0);
- if (t->api!=p_api)
+ ERR_FAIL_COND_V(!t, 0);
+ if (t->api != p_api)
continue;
- hash = hash_djb2_one_64(t->name.hash(),hash);
- hash = hash_djb2_one_64(t->inherits.hash(),hash);
+ hash = hash_djb2_one_64(t->name.hash(), hash);
+ hash = hash_djb2_one_64(t->inherits.hash(), hash);
{ //methods
List<StringName> snames;
- k=NULL;
+ k = NULL;
- while((k=t->method_map.next(k))) {
+ while ((k = t->method_map.next(k))) {
snames.push_back(*k);
}
snames.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *F=snames.front();F;F=F->next()) {
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
MethodBind *mb = t->method_map[F->get()];
- hash = hash_djb2_one_64( mb->get_name().hash(), hash);
- hash = hash_djb2_one_64( mb->get_argument_count(), hash);
- hash = hash_djb2_one_64( mb->get_argument_type(-1), hash); //return
-
- for(int i=0;i<mb->get_argument_count();i++) {
- hash = hash_djb2_one_64( mb->get_argument_info(i).type, hash );
- hash = hash_djb2_one_64( mb->get_argument_info(i).name.hash(), hash );
- hash = hash_djb2_one_64( mb->get_argument_info(i).hint, hash );
- hash = hash_djb2_one_64( mb->get_argument_info(i).hint_string.hash(), hash );
+ hash = hash_djb2_one_64(mb->get_name().hash(), hash);
+ hash = hash_djb2_one_64(mb->get_argument_count(), hash);
+ hash = hash_djb2_one_64(mb->get_argument_type(-1), hash); //return
+
+ for (int i = 0; i < mb->get_argument_count(); i++) {
+ hash = hash_djb2_one_64(mb->get_argument_info(i).type, hash);
+ hash = hash_djb2_one_64(mb->get_argument_info(i).name.hash(), hash);
+ hash = hash_djb2_one_64(mb->get_argument_info(i).hint, hash);
+ hash = hash_djb2_one_64(mb->get_argument_info(i).hint_string.hash(), hash);
}
- hash = hash_djb2_one_64( mb->get_default_argument_count(), hash);
+ hash = hash_djb2_one_64(mb->get_default_argument_count(), hash);
- for(int i=0;i<mb->get_default_argument_count();i++) {
+ for (int i = 0; i < mb->get_default_argument_count(); i++) {
//hash should not change, i hope for tis
Variant da = mb->get_default_argument(i);
- hash = hash_djb2_one_64( da.hash(), hash );
+ hash = hash_djb2_one_64(da.hash(), hash);
}
- hash = hash_djb2_one_64( mb->get_hint_flags(), hash);
-
+ hash = hash_djb2_one_64(mb->get_hint_flags(), hash);
}
}
-
{ //constants
List<StringName> snames;
- k=NULL;
+ k = NULL;
- while((k=t->constant_map.next(k))) {
+ while ((k = t->constant_map.next(k))) {
snames.push_back(*k);
}
snames.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *F=snames.front();F;F=F->next()) {
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
hash = hash_djb2_one_64(F->get().hash(), hash);
- hash = hash_djb2_one_64( t->constant_map[F->get()], hash);
+ hash = hash_djb2_one_64(t->constant_map[F->get()], hash);
}
}
-
{ //signals
List<StringName> snames;
- k=NULL;
+ k = NULL;
- while((k=t->signal_map.next(k))) {
+ while ((k = t->signal_map.next(k))) {
snames.push_back(*k);
}
snames.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *F=snames.front();F;F=F->next()) {
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
MethodInfo &mi = t->signal_map[F->get()];
- hash = hash_djb2_one_64( F->get().hash(), hash);
- for(int i=0;i<mi.arguments.size();i++) {
- hash = hash_djb2_one_64( mi.arguments[i].type, hash);
+ hash = hash_djb2_one_64(F->get().hash(), hash);
+ for (int i = 0; i < mi.arguments.size(); i++) {
+ hash = hash_djb2_one_64(mi.arguments[i].type, hash);
}
}
}
@@ -406,45 +396,40 @@ uint64_t ClassDB::get_api_hash(APIType p_api) {
List<StringName> snames;
- k=NULL;
+ k = NULL;
- while((k=t->property_setget.next(k))) {
+ while ((k = t->property_setget.next(k))) {
snames.push_back(*k);
}
snames.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *F=snames.front();F;F=F->next()) {
+ for (List<StringName>::Element *F = snames.front(); F; F = F->next()) {
- PropertySetGet *psg=t->property_setget.getptr(F->get());
-
- hash = hash_djb2_one_64( F->get().hash(), hash);
- hash = hash_djb2_one_64( psg->setter.hash(), hash);
- hash = hash_djb2_one_64( psg->getter.hash(), hash);
+ PropertySetGet *psg = t->property_setget.getptr(F->get());
+ hash = hash_djb2_one_64(F->get().hash(), hash);
+ hash = hash_djb2_one_64(psg->setter.hash(), hash);
+ hash = hash_djb2_one_64(psg->getter.hash(), hash);
}
}
//property list
- for (List<PropertyInfo>::Element *F=t->property_list.front();F;F=F->next()) {
+ for (List<PropertyInfo>::Element *F = t->property_list.front(); F; F = F->next()) {
- hash = hash_djb2_one_64( F->get().name.hash(), hash);
- hash = hash_djb2_one_64( F->get().type, hash);
- hash = hash_djb2_one_64( F->get().hint, hash);
- hash = hash_djb2_one_64( F->get().hint_string.hash(), hash);
- hash = hash_djb2_one_64( F->get().usage, hash);
+ hash = hash_djb2_one_64(F->get().name.hash(), hash);
+ hash = hash_djb2_one_64(F->get().type, hash);
+ hash = hash_djb2_one_64(F->get().hint, hash);
+ hash = hash_djb2_one_64(F->get().hint_string.hash(), hash);
+ hash = hash_djb2_one_64(F->get().usage, hash);
}
-
-
}
-
return hash;
#else
return 0;
#endif
-
}
bool ClassDB::class_exists(const StringName &p_class) {
@@ -453,10 +438,10 @@ bool ClassDB::class_exists(const StringName &p_class) {
return classes.has(p_class);
}
-void ClassDB::add_compatibility_class(const StringName& p_class,const StringName& p_fallback) {
+void ClassDB::add_compatibility_class(const StringName &p_class, const StringName &p_fallback) {
OBJTYPE_WLOCK;
- compat_classes[p_class]=p_fallback;
+ compat_classes[p_class] = p_fallback;
}
Object *ClassDB::instance(const StringName &p_class) {
@@ -464,15 +449,15 @@ Object *ClassDB::instance(const StringName &p_class) {
ClassInfo *ti;
{
OBJTYPE_RLOCK;
- ti=classes.getptr(p_class);
+ ti = classes.getptr(p_class);
if (!ti || ti->disabled || !ti->creation_func) {
if (compat_classes.has(p_class)) {
- ti=classes.getptr(compat_classes[p_class]);
+ ti = classes.getptr(compat_classes[p_class]);
}
}
- ERR_FAIL_COND_V(!ti,NULL);
- ERR_FAIL_COND_V(ti->disabled,NULL);
- ERR_FAIL_COND_V(!ti->creation_func,NULL);
+ ERR_FAIL_COND_V(!ti, NULL);
+ ERR_FAIL_COND_V(ti->disabled, NULL);
+ ERR_FAIL_COND_V(!ti->creation_func, NULL);
}
return ti->creation_func();
@@ -482,12 +467,11 @@ bool ClassDB::can_instance(const StringName &p_class) {
OBJTYPE_RLOCK;
ClassInfo *ti = classes.getptr(p_class);
- ERR_FAIL_COND_V(!ti,false);
- return (!ti->disabled && ti->creation_func!=NULL);
+ ERR_FAIL_COND_V(!ti, false);
+ return (!ti->disabled && ti->creation_func != NULL);
}
-
-void ClassDB::_add_class2(const StringName& p_class, const StringName& p_inherits) {
+void ClassDB::_add_class2(const StringName &p_class, const StringName &p_inherits) {
OBJTYPE_WLOCK;
@@ -495,120 +479,110 @@ void ClassDB::_add_class2(const StringName& p_class, const StringName& p_inherit
ERR_FAIL_COND(classes.has(name));
- classes[name]=ClassInfo();
- ClassInfo &ti=classes[name];
- ti.name=name;
- ti.inherits=p_inherits;
- ti.api=current_api;
+ classes[name] = ClassInfo();
+ ClassInfo &ti = classes[name];
+ ti.name = name;
+ ti.inherits = p_inherits;
+ ti.api = current_api;
if (ti.inherits) {
- ERR_FAIL_COND( !classes.has(ti.inherits) ); //it MUST be registered.
+ ERR_FAIL_COND(!classes.has(ti.inherits)); //it MUST be registered.
ti.inherits_ptr = &classes[ti.inherits];
} else {
- ti.inherits_ptr=NULL;
+ ti.inherits_ptr = NULL;
}
-
-
}
-void ClassDB::get_method_list(StringName p_class,List<MethodInfo> *p_methods,bool p_no_inheritance) {
-
+void ClassDB::get_method_list(StringName p_class, List<MethodInfo> *p_methods, bool p_no_inheritance) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
- while(type) {
+ while (type) {
if (type->disabled) {
if (p_no_inheritance)
break;
- type=type->inherits_ptr;
+ type = type->inherits_ptr;
continue;
}
#ifdef DEBUG_METHODS_ENABLED
- for( List<MethodInfo>::Element *E=type->virtual_methods.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = type->virtual_methods.front(); E; E = E->next()) {
p_methods->push_back(E->get());
}
- for( List<StringName>::Element *E=type->method_order.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = type->method_order.front(); E; E = E->next()) {
- MethodBind *method=type->method_map.get(E->get());
+ MethodBind *method = type->method_map.get(E->get());
MethodInfo minfo;
- minfo.name=E->get();
- minfo.id=method->get_method_id();
+ minfo.name = E->get();
+ minfo.id = method->get_method_id();
- for (int i=0;i<method->get_argument_count();i++) {
+ for (int i = 0; i < method->get_argument_count(); i++) {
//Variant::Type t=method->get_argument_type(i);
minfo.arguments.push_back(method->get_argument_info(i));
}
-
- if (method->get_argument_type(-1)!=Variant::NIL) {
- minfo.return_val=method->get_argument_info(-1);
+ if (method->get_argument_type(-1) != Variant::NIL) {
+ minfo.return_val = method->get_argument_info(-1);
}
- minfo.flags=method->get_hint_flags();
+ minfo.flags = method->get_hint_flags();
p_methods->push_back(minfo);
}
-
-
#else
- const StringName *K=NULL;
+ const StringName *K = NULL;
- while((K=type->method_map.next(K))) {
+ while ((K = type->method_map.next(K))) {
- MethodBind*m = type->method_map[*K];
+ MethodBind *m = type->method_map[*K];
MethodInfo mi;
- mi.name=m->get_name();
+ mi.name = m->get_name();
p_methods->push_back(mi);
}
-
#endif
if (p_no_inheritance)
break;
- type=type->inherits_ptr;
+ type = type->inherits_ptr;
}
-
}
-
MethodBind *ClassDB::get_method(StringName p_class, StringName p_name) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
- while(type) {
+ while (type) {
- MethodBind **method=type->method_map.getptr(p_name);
+ MethodBind **method = type->method_map.getptr(p_name);
if (method && *method)
return *method;
- type=type->inherits_ptr;
+ type = type->inherits_ptr;
}
return NULL;
}
-
-void ClassDB::bind_integer_constant(const StringName& p_class, const StringName &p_name, int p_constant) {
+void ClassDB::bind_integer_constant(const StringName &p_class, const StringName &p_name, int p_constant) {
OBJTYPE_WLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
if (!type) {
ERR_FAIL_COND(!type);
@@ -619,28 +593,27 @@ void ClassDB::bind_integer_constant(const StringName& p_class, const StringName
ERR_FAIL();
}
- type->constant_map[p_name]=p_constant;
+ type->constant_map[p_name] = p_constant;
#ifdef DEBUG_METHODS_ENABLED
type->constant_order.push_back(p_name);
#endif
-
}
-void ClassDB::get_integer_constant_list(const StringName& p_class, List<String> *p_constants, bool p_no_inheritance) {
+void ClassDB::get_integer_constant_list(const StringName &p_class, List<String> *p_constants, bool p_no_inheritance) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
- while(type) {
+ while (type) {
#ifdef DEBUG_METHODS_ENABLED
- for(List<StringName>::Element *E=type->constant_order.front();E;E=E->next())
+ for (List<StringName>::Element *E = type->constant_order.front(); E; E = E->next())
p_constants->push_back(E->get());
#else
- const StringName *K=NULL;
+ const StringName *K = NULL;
- while((K=type->constant_map.next(K))) {
+ while ((K = type->constant_map.next(K))) {
p_constants->push_back(*K);
}
@@ -648,76 +621,71 @@ void ClassDB::get_integer_constant_list(const StringName& p_class, List<String>
if (p_no_inheritance)
break;
- type=type->inherits_ptr;
+ type = type->inherits_ptr;
}
-
}
-
-int ClassDB::get_integer_constant(const StringName& p_class, const StringName &p_name, bool *p_success) {
+int ClassDB::get_integer_constant(const StringName &p_class, const StringName &p_name, bool *p_success) {
OBJTYPE_RLOCK;
+ ClassInfo *type = classes.getptr(p_class);
- ClassInfo *type=classes.getptr(p_class);
-
- while(type) {
+ while (type) {
-
- int *constant=type->constant_map.getptr(p_name);
+ int *constant = type->constant_map.getptr(p_name);
if (constant) {
if (p_success)
- *p_success=true;
+ *p_success = true;
return *constant;
}
- type=type->inherits_ptr;
+ type = type->inherits_ptr;
}
if (p_success)
- *p_success=false;
+ *p_success = false;
return 0;
}
-void ClassDB::add_signal(StringName p_class,const MethodInfo& p_signal) {
+void ClassDB::add_signal(StringName p_class, const MethodInfo &p_signal) {
OBJTYPE_WLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
ERR_FAIL_COND(!type);
- ClassInfo *check=type;
+ ClassInfo *check = type;
StringName sname = p_signal.name;
#ifdef DEBUG_METHODS_ENABLED
- while(check) {
+ while (check) {
if (check->signal_map.has(sname)) {
- ERR_EXPLAIN("Type "+String(p_class)+" already has signal: "+String(sname));
+ ERR_EXPLAIN("Type " + String(p_class) + " already has signal: " + String(sname));
ERR_FAIL();
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
#endif
- type->signal_map[sname]=p_signal;
-
+ type->signal_map[sname] = p_signal;
}
-void ClassDB::get_signal_list(StringName p_class,List<MethodInfo> *p_signals,bool p_no_inheritance) {
+void ClassDB::get_signal_list(StringName p_class, List<MethodInfo> *p_signals, bool p_no_inheritance) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
ERR_FAIL_COND(!type);
- ClassInfo *check=type;
+ ClassInfo *check = type;
- while(check) {
+ while (check) {
- const StringName *S=NULL;
- while((S=check->signal_map.next(S))) {
+ const StringName *S = NULL;
+ while ((S = check->signal_map.next(S))) {
p_signals->push_back(check->signal_map[*S]);
}
@@ -725,63 +693,58 @@ void ClassDB::get_signal_list(StringName p_class,List<MethodInfo> *p_signals,boo
if (p_no_inheritance)
return;
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
-
-
}
-bool ClassDB::has_signal(StringName p_class,StringName p_signal) {
+bool ClassDB::has_signal(StringName p_class, StringName p_signal) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
if (check->signal_map.has(p_signal))
return true;
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
}
-bool ClassDB::get_signal(StringName p_class,StringName p_signal,MethodInfo *r_signal) {
+bool ClassDB::get_signal(StringName p_class, StringName p_signal, MethodInfo *r_signal) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
if (check->signal_map.has(p_signal)) {
if (r_signal) {
- *r_signal=check->signal_map[p_signal];
+ *r_signal = check->signal_map[p_signal];
}
return true;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
}
-
-void ClassDB::add_property_group(StringName p_class,const String& p_name,const String& p_prefix) {
+void ClassDB::add_property_group(StringName p_class, const String &p_name, const String &p_prefix) {
OBJTYPE_WLOCK;
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
ERR_FAIL_COND(!type);
- type->property_list.push_back(PropertyInfo(Variant::NIL,p_name,PROPERTY_HINT_NONE,p_prefix,PROPERTY_USAGE_GROUP));
+ type->property_list.push_back(PropertyInfo(Variant::NIL, p_name, PROPERTY_HINT_NONE, p_prefix, PROPERTY_USAGE_GROUP));
}
-void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const StringName& p_setter, const StringName& p_getter, int p_index) {
-
-
+void ClassDB::add_property(StringName p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index) {
#ifndef NO_THREADS
lock->read_lock();
#endif
- ClassInfo *type=classes.getptr(p_class);
+ ClassInfo *type = classes.getptr(p_class);
#ifndef NO_THREADS
lock->read_unlock();
@@ -789,52 +752,47 @@ void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const
ERR_FAIL_COND(!type);
- MethodBind *mb_set=NULL;
+ MethodBind *mb_set = NULL;
if (p_setter) {
- mb_set = get_method(p_class,p_setter);
+ mb_set = get_method(p_class, p_setter);
#ifdef DEBUG_METHODS_ENABLED
if (!mb_set) {
- ERR_EXPLAIN("Invalid Setter: "+p_class+"::"+p_setter+" for property: "+p_pinfo.name);
+ ERR_EXPLAIN("Invalid Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name);
ERR_FAIL_COND(!mb_set);
} else {
- int exp_args=1+(p_index>=0?1:0);
- if (mb_set->get_argument_count()!=exp_args) {
- ERR_EXPLAIN("Invalid Function for Setter: "+p_class+"::"+p_setter+" for property: "+p_pinfo.name);
+ int exp_args = 1 + (p_index >= 0 ? 1 : 0);
+ if (mb_set->get_argument_count() != exp_args) {
+ ERR_EXPLAIN("Invalid Function for Setter: " + p_class + "::" + p_setter + " for property: " + p_pinfo.name);
ERR_FAIL();
-
}
}
#endif
}
- MethodBind *mb_get=NULL;
+ MethodBind *mb_get = NULL;
if (p_getter) {
- MethodBind *mb_get = get_method(p_class,p_getter);
+ MethodBind *mb_get = get_method(p_class, p_getter);
#ifdef DEBUG_METHODS_ENABLED
if (!mb_get) {
- ERR_EXPLAIN("Invalid Getter: "+p_class+"::"+p_getter+" for property: "+p_pinfo.name);
+ ERR_EXPLAIN("Invalid Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name);
ERR_FAIL_COND(!mb_get);
} else {
- int exp_args=0+(p_index>=0?1:0);
- if (mb_get->get_argument_count()!=exp_args) {
- ERR_EXPLAIN("Invalid Function for Getter: "+p_class+"::"+p_getter+" for property: "+p_pinfo.name);
+ int exp_args = 0 + (p_index >= 0 ? 1 : 0);
+ if (mb_get->get_argument_count() != exp_args) {
+ ERR_EXPLAIN("Invalid Function for Getter: " + p_class + "::" + p_getter + " for property: " + p_pinfo.name);
ERR_FAIL();
-
}
-
}
#endif
}
-
-
#ifdef DEBUG_METHODS_ENABLED
if (type->property_setget.has(p_pinfo.name)) {
- ERR_EXPLAIN("Object already has property: "+p_class);
+ ERR_EXPLAIN("Object already has property: " + p_class);
ERR_FAIL();
}
#endif
@@ -844,28 +802,25 @@ void ClassDB::add_property(StringName p_class,const PropertyInfo& p_pinfo, const
type->property_list.push_back(p_pinfo);
PropertySetGet psg;
- psg.setter=p_setter;
- psg.getter=p_getter;
- psg._setptr=mb_set;
- psg._getptr=mb_get;
- psg.index=p_index;
- psg.type=p_pinfo.type;
-
- type->property_setget[p_pinfo.name]=psg;
-
+ psg.setter = p_setter;
+ psg.getter = p_getter;
+ psg._setptr = mb_set;
+ psg._getptr = mb_get;
+ psg.index = p_index;
+ psg.type = p_pinfo.type;
+
+ type->property_setget[p_pinfo.name] = psg;
}
-
-void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance,const Object *p_validator) {
+void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator) {
OBJTYPE_RLOCK;
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
-
- for(List<PropertyInfo>::Element *E=check->property_list.front();E;E=E->next()) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
+ for (List<PropertyInfo>::Element *E = check->property_list.front(); E; E = E->next()) {
if (p_validator) {
PropertyInfo pi = E->get();
@@ -877,266 +832,253 @@ void ClassDB::get_property_list(StringName p_class, List<PropertyInfo> *p_list,
}
if (p_no_inheritance)
- return ;
- check=check->inherits_ptr;
+ return;
+ check = check->inherits_ptr;
}
-
}
-bool ClassDB::set_property(Object* p_object,const StringName& p_property, const Variant& p_value,bool *r_valid) {
-
+bool ClassDB::set_property(Object *p_object, const StringName &p_property, const Variant &p_value, bool *r_valid) {
-
- ClassInfo *type=classes.getptr(p_object->get_class_name());
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_object->get_class_name());
+ ClassInfo *check = type;
+ while (check) {
const PropertySetGet *psg = check->property_setget.getptr(p_property);
if (psg) {
if (!psg->setter) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return true; //return true but do nothing
}
Variant::CallError ce;
- if (psg->index>=0) {
- Variant index=psg->index;
- const Variant* arg[2]={&index,&p_value};
+ if (psg->index >= 0) {
+ Variant index = psg->index;
+ const Variant *arg[2] = { &index, &p_value };
//p_object->call(psg->setter,arg,2,ce);
if (psg->_setptr) {
- psg->_setptr->call(p_object,arg,2,ce);
+ psg->_setptr->call(p_object, arg, 2, ce);
} else {
- p_object->call(psg->setter,arg,2,ce);
+ p_object->call(psg->setter, arg, 2, ce);
}
-
} else {
- const Variant* arg[1]={&p_value};
+ const Variant *arg[1] = { &p_value };
if (psg->_setptr) {
- psg->_setptr->call(p_object,arg,1,ce);
+ psg->_setptr->call(p_object, arg, 1, ce);
} else {
- p_object->call(psg->setter,arg,1,ce);
+ p_object->call(psg->setter, arg, 1, ce);
}
}
if (r_valid)
- *r_valid=ce.error==Variant::CallError::CALL_OK;
+ *r_valid = ce.error == Variant::CallError::CALL_OK;
return true;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
}
-bool ClassDB::get_property(Object* p_object,const StringName& p_property, Variant& r_value) {
+bool ClassDB::get_property(Object *p_object, const StringName &p_property, Variant &r_value) {
- ClassInfo *type=classes.getptr(p_object->get_class_name());
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_object->get_class_name());
+ ClassInfo *check = type;
+ while (check) {
const PropertySetGet *psg = check->property_setget.getptr(p_property);
if (psg) {
if (!psg->getter)
return true; //return true but do nothing
- if (psg->index>=0) {
- Variant index=psg->index;
- const Variant* arg[1]={&index};
+ if (psg->index >= 0) {
+ Variant index = psg->index;
+ const Variant *arg[1] = { &index };
Variant::CallError ce;
- r_value = p_object->call(psg->getter,arg,1,ce);
+ r_value = p_object->call(psg->getter, arg, 1, ce);
} else {
Variant::CallError ce;
if (psg->_getptr) {
- r_value = psg->_getptr->call(p_object,NULL,0,ce);
+ r_value = psg->_getptr->call(p_object, NULL, 0, ce);
} else {
- r_value = p_object->call(psg->getter,NULL,0,ce);
+ r_value = p_object->call(psg->getter, NULL, 0, ce);
}
}
return true;
}
- const int *c =check->constant_map.getptr(p_property);
+ const int *c = check->constant_map.getptr(p_property);
if (c) {
- r_value=*c;
+ r_value = *c;
return true;
}
//if (check->constant_map.fin)
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
}
-Variant::Type ClassDB::get_property_type(const StringName& p_class, const StringName& p_property,bool *r_is_valid) {
+Variant::Type ClassDB::get_property_type(const StringName &p_class, const StringName &p_property, bool *r_is_valid) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
const PropertySetGet *psg = check->property_setget.getptr(p_property);
if (psg) {
if (r_is_valid)
- *r_is_valid=true;
+ *r_is_valid = true;
return psg->type;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
if (r_is_valid)
- *r_is_valid=false;
+ *r_is_valid = false;
return Variant::NIL;
-
}
-StringName ClassDB::get_property_setter(StringName p_class,const StringName p_property) {
+StringName ClassDB::get_property_setter(StringName p_class, const StringName p_property) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
const PropertySetGet *psg = check->property_setget.getptr(p_property);
if (psg) {
return psg->setter;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return StringName();
}
-StringName ClassDB::get_property_getter(StringName p_class,const StringName p_property) {
+StringName ClassDB::get_property_getter(StringName p_class, const StringName p_property) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
const PropertySetGet *psg = check->property_setget.getptr(p_property);
if (psg) {
return psg->getter;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return StringName();
}
-bool ClassDB::has_property(const StringName& p_class, const StringName& p_property, bool p_no_inheritance) {
-
+bool ClassDB::has_property(const StringName &p_class, const StringName &p_property, bool p_no_inheritance) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
if (check->property_setget.has(p_property))
return true;
if (p_no_inheritance)
break;
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
}
-void ClassDB::set_method_flags(StringName p_class,StringName p_method,int p_flags) {
+void ClassDB::set_method_flags(StringName p_class, StringName p_method, int p_flags) {
OBJTYPE_WLOCK;
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
ERR_FAIL_COND(!check);
ERR_FAIL_COND(!check->method_map.has(p_method));
check->method_map[p_method]->set_hint_flags(p_flags);
-
-
}
-bool ClassDB::has_method(StringName p_class,StringName p_method,bool p_no_inheritance) {
+bool ClassDB::has_method(StringName p_class, StringName p_method, bool p_no_inheritance) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
if (check->method_map.has(p_method))
return true;
if (p_no_inheritance)
return false;
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
-
}
-bool ClassDB::get_setter_and_type_for_property(const StringName& p_class, const StringName& p_prop, StringName& r_class, StringName& r_setter) {
+bool ClassDB::get_setter_and_type_for_property(const StringName &p_class, const StringName &p_prop, StringName &r_class, StringName &r_setter) {
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
if (check->property_setget.has(p_prop)) {
- r_class=check->name;
- r_setter=check->property_setget[p_prop].setter;
+ r_class = check->name;
+ r_setter = check->property_setget[p_prop].setter;
return true;
}
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
return false;
-
}
#ifdef DEBUG_METHODS_ENABLED
-MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) {
- StringName mdname=method_name.name;
+MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount) {
+ StringName mdname = method_name.name;
#else
-MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const char *method_name, const Variant **p_defs, int p_defcount) {
- StringName mdname=StaticCString::create(method_name);
+MethodBind *ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount) {
+ StringName mdname = StaticCString::create(method_name);
#endif
-
StringName rettype;
- if (mdname.operator String().find(":")!=-1) {
- rettype = mdname.operator String().get_slice(":",1);
- mdname = mdname.operator String().get_slice(":",0);
+ if (mdname.operator String().find(":") != -1) {
+ rettype = mdname.operator String().get_slice(":", 1);
+ mdname = mdname.operator String().get_slice(":", 0);
}
-
OBJTYPE_WLOCK;
- ERR_FAIL_COND_V(!p_bind,NULL);
+ ERR_FAIL_COND_V(!p_bind, NULL);
p_bind->set_name(mdname);
- String instance_type=p_bind->get_instance_class();
+ String instance_type = p_bind->get_instance_class();
#ifdef DEBUG_ENABLED
- if (has_method(instance_type,mdname)) {
- ERR_EXPLAIN("Class "+String(instance_type)+" already has a method "+String(mdname));
+ if (has_method(instance_type, mdname)) {
+ ERR_EXPLAIN("Class " + String(instance_type) + " already has a method " + String(mdname));
ERR_FAIL_V(NULL);
}
#endif
-
- ClassInfo *type=classes.getptr(instance_type);
+ ClassInfo *type = classes.getptr(instance_type);
if (!type) {
- ERR_PRINTS("Couldn't bind method '"+mdname+"' for instance: "+instance_type);
+ ERR_PRINTS("Couldn't bind method '" + mdname + "' for instance: " + instance_type);
memdelete(p_bind);
- ERR_FAIL_COND_V(!type,NULL);
+ ERR_FAIL_COND_V(!type, NULL);
}
if (type->method_map.has(mdname)) {
memdelete(p_bind);
// overloading not supported
- ERR_EXPLAIN("Method already bound: "+instance_type+"::"+mdname);
+ ERR_EXPLAIN("Method already bound: " + instance_type + "::" + mdname);
ERR_FAIL_V(NULL);
}
#ifdef DEBUG_METHODS_ENABLED
@@ -1144,87 +1086,83 @@ MethodBind* ClassDB::bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const
p_bind->set_return_type(rettype);
type->method_order.push_back(mdname);
#endif
- type->method_map[mdname]=p_bind;
-
+ type->method_map[mdname] = p_bind;
Vector<Variant> defvals;
defvals.resize(p_defcount);
- for(int i=0;i<p_defcount;i++) {
+ for (int i = 0; i < p_defcount; i++) {
- defvals[i]=*p_defs[p_defcount-i-1];
+ defvals[i] = *p_defs[p_defcount - i - 1];
}
p_bind->set_default_arguments(defvals);
p_bind->set_hint_flags(p_flags);
return p_bind;
-
}
-void ClassDB::add_virtual_method(const StringName& p_class, const MethodInfo& p_method , bool p_virtual) {
+void ClassDB::add_virtual_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual) {
ERR_FAIL_COND(!classes.has(p_class));
OBJTYPE_WLOCK;
#ifdef DEBUG_METHODS_ENABLED
- MethodInfo mi=p_method;
+ MethodInfo mi = p_method;
if (p_virtual)
- mi.flags|=METHOD_FLAG_VIRTUAL;
+ mi.flags |= METHOD_FLAG_VIRTUAL;
classes[p_class].virtual_methods.push_back(mi);
#endif
-
}
-void ClassDB::get_virtual_methods(const StringName& p_class, List<MethodInfo> * p_methods , bool p_no_inheritance) {
+void ClassDB::get_virtual_methods(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance) {
ERR_FAIL_COND(!classes.has(p_class));
#ifdef DEBUG_METHODS_ENABLED
- ClassInfo *type=classes.getptr(p_class);
- ClassInfo *check=type;
- while(check) {
+ ClassInfo *type = classes.getptr(p_class);
+ ClassInfo *check = type;
+ while (check) {
- for(List<MethodInfo>::Element *E=check->virtual_methods.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = check->virtual_methods.front(); E; E = E->next()) {
p_methods->push_back(E->get());
}
if (p_no_inheritance)
return;
- check=check->inherits_ptr;
+ check = check->inherits_ptr;
}
#endif
-
}
-void ClassDB::set_class_enabled(StringName p_class,bool p_enable) {
+void ClassDB::set_class_enabled(StringName p_class, bool p_enable) {
OBJTYPE_WLOCK;
ERR_FAIL_COND(!classes.has(p_class));
- classes[p_class].disabled=!p_enable;
+ classes[p_class].disabled = !p_enable;
}
bool ClassDB::is_class_enabled(StringName p_class) {
OBJTYPE_RLOCK;
- ClassInfo *ti=classes.getptr(p_class);
+ ClassInfo *ti = classes.getptr(p_class);
if (!ti || !ti->creation_func) {
if (compat_classes.has(p_class)) {
- ti=classes.getptr(compat_classes[p_class]);
+ ti = classes.getptr(compat_classes[p_class]);
}
}
- ERR_FAIL_COND_V(!ti,false);
+ ERR_FAIL_COND_V(!ti, false);
return !ti->disabled;
}
-StringName ClassDB::get_category(const StringName& p_node) {
+StringName ClassDB::get_category(const StringName &p_node) {
- ERR_FAIL_COND_V(!classes.has(p_node),StringName());
+ ERR_FAIL_COND_V(!classes.has(p_node), StringName());
#ifdef DEBUG_ENABLED
return classes[p_node].category;
#else
@@ -1232,37 +1170,36 @@ StringName ClassDB::get_category(const StringName& p_node) {
#endif
}
-void ClassDB::add_resource_base_extension(const StringName& p_extension,const StringName& p_class) {
+void ClassDB::add_resource_base_extension(const StringName &p_extension, const StringName &p_class) {
if (resource_base_extensions.has(p_extension))
return;
- resource_base_extensions[p_extension]=p_class;
+ resource_base_extensions[p_extension] = p_class;
}
void ClassDB::get_resource_base_extensions(List<String> *p_extensions) {
- const StringName *K=NULL;
+ const StringName *K = NULL;
- while((K=resource_base_extensions.next(K))) {
+ while ((K = resource_base_extensions.next(K))) {
p_extensions->push_back(*K);
}
}
-void ClassDB::get_extensions_for_type(const StringName& p_class,List<String> *p_extensions) {
+void ClassDB::get_extensions_for_type(const StringName &p_class, List<String> *p_extensions) {
- const StringName *K=NULL;
+ const StringName *K = NULL;
- while((K=resource_base_extensions.next(K))) {
+ while ((K = resource_base_extensions.next(K))) {
StringName cmp = resource_base_extensions[*K];
- if (is_parent_class(p_class,cmp))
+ if (is_parent_class(p_class, cmp))
p_extensions->push_back(*K);
}
}
-
-RWLock *ClassDB::lock=NULL;
+RWLock *ClassDB::lock = NULL;
void ClassDB::init() {
@@ -1274,20 +1211,18 @@ void ClassDB::init() {
void ClassDB::cleanup() {
-
-
//OBJTYPE_LOCK; hah not here
- const StringName *k=NULL;
+ const StringName *k = NULL;
- while((k=classes.next(k))) {
+ while ((k = classes.next(k))) {
- ClassInfo &ti=classes[*k];
+ ClassInfo &ti = classes[*k];
- const StringName *m=NULL;
- while((m=ti.method_map.next(m))) {
+ const StringName *m = NULL;
+ while ((m = ti.method_map.next(m))) {
- memdelete( ti.method_map[*m] );
+ memdelete(ti.method_map[*m]);
}
}
classes.clear();
@@ -1298,7 +1233,6 @@ void ClassDB::cleanup() {
memdelete(lock);
#endif
-
}
//
diff --git a/core/class_db.h b/core/class_db.h
index 6e02d0bf46..6966183cfa 100644
--- a/core/class_db.h
+++ b/core/class_db.h
@@ -29,8 +29,8 @@
#ifndef CLASS_DB_H
#define CLASS_DB_H
-#include "object.h"
#include "method_bind.h"
+#include "object.h"
#include "print_string.h"
/**
@@ -44,26 +44,24 @@ struct ParamHint {
String hint_text;
Variant default_val;
- ParamHint(const String& p_name="", PropertyHint p_hint=PROPERTY_HINT_NONE, const String& p_hint_text="",Variant p_default_val=Variant()) {
+ ParamHint(const String &p_name = "", PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_text = "", Variant p_default_val = Variant()) {
- name=p_name;
- hint=p_hint;
- hint_text=p_hint_text;
- default_val=p_default_val;
+ name = p_name;
+ hint = p_hint;
+ hint_text = p_hint_text;
+ default_val = p_default_val;
}
-
};
struct ParamDef {
bool used;
Variant val;
- _FORCE_INLINE_ ParamDef() { used=false; }
- ParamDef(const Variant& p_variant);
+ _FORCE_INLINE_ ParamDef() { used = false; }
+ ParamDef(const Variant &p_variant);
};
//#define DEFVAL( m_defval ) ParamDef(m_defval)
-#define DEFVAL( m_defval ) (m_defval)
-
+#define DEFVAL(m_defval) (m_defval)
//#define SIMPLE_METHODDEF
@@ -71,27 +69,24 @@ struct ParamDef {
struct MethodDefinition {
-
StringName name;
Vector<StringName> args;
MethodDefinition() {}
- MethodDefinition(const char *p_name) { name=p_name; }
- MethodDefinition(const StringName& p_name) { name=p_name; }
+ MethodDefinition(const char *p_name) { name = p_name; }
+ MethodDefinition(const StringName &p_name) { name = p_name; }
};
-
-
-MethodDefinition D_METHOD(const char* p_name);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9);
-MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_arg2,const char *p_arg3,const char *p_arg4,const char *p_arg5,const char *p_arg6,const char *p_arg7,const char *p_arg8,const char *p_arg9,const char *p_arg10);
+MethodDefinition D_METHOD(const char *p_name);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9);
+MethodDefinition D_METHOD(const char *p_name, const char *p_arg1, const char *p_arg2, const char *p_arg3, const char *p_arg4, const char *p_arg5, const char *p_arg6, const char *p_arg7, const char *p_arg8, const char *p_arg9, const char *p_arg10);
#else
@@ -99,7 +94,9 @@ MethodDefinition D_METHOD(const char* p_name,const char *p_arg1,const char *p_ar
#ifdef NO_VARIADIC_MACROS
-static _FORCE_INLINE_ const char* D_METHOD(const char* m_name, ...) { return m_name; }
+static _FORCE_INLINE_ const char *D_METHOD(const char *m_name, ...) {
+ return m_name;
+}
#else
@@ -118,6 +115,7 @@ public:
API_EDITOR,
API_NONE
};
+
public:
struct PropertySetGet {
@@ -133,9 +131,9 @@ public:
APIType api;
ClassInfo *inherits_ptr;
- HashMap<StringName,MethodBind*,StringNameHasher> method_map;
- HashMap<StringName,int,StringNameHasher> constant_map;
- HashMap<StringName,MethodInfo,StringNameHasher> signal_map;
+ HashMap<StringName, MethodBind *, StringNameHasher> method_map;
+ HashMap<StringName, int, StringNameHasher> constant_map;
+ HashMap<StringName, MethodInfo, StringNameHasher> signal_map;
List<PropertyInfo> property_list;
#ifdef DEBUG_METHODS_ENABLED
List<StringName> constant_order;
@@ -143,44 +141,42 @@ public:
List<MethodInfo> virtual_methods;
StringName category;
#endif
- HashMap<StringName,PropertySetGet,StringNameHasher> property_setget;
-
+ HashMap<StringName, PropertySetGet, StringNameHasher> property_setget;
StringName inherits;
StringName name;
bool disabled;
- Object* (*creation_func)();
+ Object *(*creation_func)();
ClassInfo();
~ClassInfo();
};
- template<class T>
+ template <class T>
static Object *creator() {
- return memnew( T );
+ return memnew(T);
}
static RWLock *lock;
- static HashMap<StringName,ClassInfo,StringNameHasher> classes;
- static HashMap<StringName,StringName,StringNameHasher> resource_base_extensions;
- static HashMap<StringName,StringName,StringNameHasher> compat_classes;
+ static HashMap<StringName, ClassInfo, StringNameHasher> classes;
+ static HashMap<StringName, StringName, StringNameHasher> resource_base_extensions;
+ static HashMap<StringName, StringName, StringNameHasher> compat_classes;
#ifdef DEBUG_METHODS_ENABLED
- static MethodBind* bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const MethodDefinition &method_name, const Variant **p_defs, int p_defcount);
+ static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const Variant **p_defs, int p_defcount);
#else
- static MethodBind* bind_methodfi(uint32_t p_flags, MethodBind *p_bind , const char *method_name, const Variant **p_defs, int p_defcount);
+ static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const char *method_name, const Variant **p_defs, int p_defcount);
#endif
-
static APIType current_api;
- static void _add_class2(const StringName& p_class, const StringName& p_inherits);
-public:
+ static void _add_class2(const StringName &p_class, const StringName &p_inherits);
+public:
// DO NOT USE THIS!!!!!! NEEDS TO BE PUBLIC BUT DO NOT USE NO MATTER WHAT!!!
- template<class T>
+ template <class T>
static void _add_class() {
- _add_class2(T::get_class_static(),T::get_parent_class_static());
+ _add_class2(T::get_class_static(), T::get_parent_class_static());
#if 0
GLOBAL_LOCK_FUNCTION;
@@ -204,18 +200,18 @@ public:
#endif
}
- template<class T>
+ template <class T>
static void register_class() {
GLOBAL_LOCK_FUNCTION;
T::initialize_class();
- ClassInfo *t=classes.getptr(T::get_class_static());
+ ClassInfo *t = classes.getptr(T::get_class_static());
ERR_FAIL_COND(!t);
- t->creation_func=&creator<T>;
+ t->creation_func = &creator<T>;
T::register_custom_data_to_otdb();
}
- template<class T>
+ template <class T>
static void register_virtual_class() {
GLOBAL_LOCK_FUNCTION;
@@ -223,29 +219,29 @@ public:
//nothing
}
- template<class T>
- static Object* _create_ptr_func() {
+ template <class T>
+ static Object *_create_ptr_func() {
return T::create();
}
- template<class T>
+ template <class T>
static void register_custom_instance_class() {
GLOBAL_LOCK_FUNCTION;
T::initialize_class();
- ClassInfo *t=classes.getptr(T::get_class_static());
+ ClassInfo *t = classes.getptr(T::get_class_static());
ERR_FAIL_COND(!t);
- t->creation_func=&_create_ptr_func<T>;
+ t->creation_func = &_create_ptr_func<T>;
T::register_custom_data_to_otdb();
}
- static void get_class_list( List<StringName> *p_classes);
- static void get_inheriters_from_class( const StringName& p_class,List<StringName> *p_classes);
- static StringName get_parent_class_nocheck(const StringName& p_class);
- static StringName get_parent_class(const StringName& p_class);
+ static void get_class_list(List<StringName> *p_classes);
+ static void get_inheriters_from_class(const StringName &p_class, List<StringName> *p_classes);
+ static StringName get_parent_class_nocheck(const StringName &p_class);
+ static StringName get_parent_class(const StringName &p_class);
static bool class_exists(const StringName &p_class);
- static bool is_parent_class(const StringName &p_class,const StringName& p_inherits);
+ static bool is_parent_class(const StringName &p_class, const StringName &p_inherits);
static bool can_instance(const StringName &p_class);
static Object *instance(const StringName &p_class);
static APIType get_api_type(const StringName &p_class);
@@ -307,9 +303,11 @@ public:
Vector<Variant> defvals;
-#define PARSE_DEFVAL(m_defval)\
- if (d##m_defval.used) defvals.insert(0,d##m_defval.val);\
- else goto set_defvals;
+#define PARSE_DEFVAL(m_defval) \
+ if (d##m_defval.used) \
+ defvals.insert(0, d##m_defval.val); \
+ else \
+ goto set_defvals;
PARSE_DEFVAL(1);
@@ -346,67 +344,66 @@ public:
}
#endif
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method) {
MethodBind *bind = create_method_bind(p_method);
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,NULL,0); //use static function, much smaller binary usage
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, NULL, 0); //use static function, much smaller binary usage
}
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[1]={&p_def1};
+ const Variant *ptr[1] = { &p_def1 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,1);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 1);
}
-
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[2]={&p_def1,&p_def2};
+ const Variant *ptr[2] = { &p_def1, &p_def2 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,2);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 2);
}
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[3]={&p_def1,&p_def2,&p_def3};
+ const Variant *ptr[3] = { &p_def1, &p_def2, &p_def3 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,3);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 3);
}
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[4]={&p_def1,&p_def2,&p_def3,&p_def4};
+ const Variant *ptr[4] = { &p_def1, &p_def2, &p_def3, &p_def4 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,4);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 4);
}
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4,const Variant& p_def5) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4, const Variant &p_def5) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[5]={&p_def1,&p_def2,&p_def3,&p_def4,&p_def5};
+ const Variant *ptr[5] = { &p_def1, &p_def2, &p_def3, &p_def4, &p_def5 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,5);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 5);
}
- template<class N, class M>
- static MethodBind* bind_method(N p_method_name, M p_method,const Variant& p_def1,const Variant& p_def2,const Variant& p_def3,const Variant& p_def4,const Variant& p_def5,const Variant& p_def6) {
+ template <class N, class M>
+ static MethodBind *bind_method(N p_method_name, M p_method, const Variant &p_def1, const Variant &p_def2, const Variant &p_def3, const Variant &p_def4, const Variant &p_def5, const Variant &p_def6) {
MethodBind *bind = create_method_bind(p_method);
- const Variant* ptr[6]={&p_def1,&p_def2,&p_def3,&p_def4,&p_def5,&p_def6};
+ const Variant *ptr[6] = { &p_def1, &p_def2, &p_def3, &p_def4, &p_def5, &p_def6 };
- return bind_methodfi(METHOD_FLAGS_DEFAULT,bind,p_method_name,ptr,6);
+ return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, ptr, 6);
}
#if 0
@@ -429,108 +426,99 @@ public:
#endif
#endif
- template<class M>
- static MethodBind* bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method,const MethodInfo& p_info=MethodInfo(),const Vector<Variant>& p_default_args=Vector<Variant>()) {
+ template <class M>
+ static MethodBind *bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method, const MethodInfo &p_info = MethodInfo(), const Vector<Variant> &p_default_args = Vector<Variant>()) {
GLOBAL_LOCK_FUNCTION;
-
-
- MethodBind *bind = create_vararg_method_bind(p_method,p_info);
- ERR_FAIL_COND_V(!bind,NULL);
+ MethodBind *bind = create_vararg_method_bind(p_method, p_info);
+ ERR_FAIL_COND_V(!bind, NULL);
String rettype;
- if (p_name.operator String().find(":")!=-1) {
- rettype = p_name.operator String().get_slice(":",1);
- p_name = p_name.operator String().get_slice(":",0);
+ if (p_name.operator String().find(":") != -1) {
+ rettype = p_name.operator String().get_slice(":", 1);
+ p_name = p_name.operator String().get_slice(":", 0);
}
bind->set_name(p_name);
bind->set_default_arguments(p_default_args);
- String instance_type=bind->get_instance_class();
+ String instance_type = bind->get_instance_class();
- ClassInfo *type=classes.getptr(instance_type);
+ ClassInfo *type = classes.getptr(instance_type);
if (!type) {
memdelete(bind);
- ERR_FAIL_COND_V(!type,NULL);
+ ERR_FAIL_COND_V(!type, NULL);
}
if (type->method_map.has(p_name)) {
memdelete(bind);
// overloading not supported
- ERR_EXPLAIN("Method already bound: "+instance_type+"::"+p_name);
+ ERR_EXPLAIN("Method already bound: " + instance_type + "::" + p_name);
ERR_FAIL_V(NULL);
}
- type->method_map[p_name]=bind;
+ type->method_map[p_name] = bind;
#ifdef DEBUG_METHODS_ENABLED
if (!rettype.empty())
bind->set_return_type(rettype);
type->method_order.push_back(p_name);
#endif
-
return bind;
-
}
-
- static void add_signal(StringName p_class,const MethodInfo& p_signal);
- static bool has_signal(StringName p_class,StringName p_signal);
- static bool get_signal(StringName p_class,StringName p_signal,MethodInfo *r_signal);
- static void get_signal_list(StringName p_class,List<MethodInfo> *p_signals,bool p_no_inheritance=false);
-
- static void add_property_group(StringName p_class,const String& p_name,const String& p_prefix="");
- static void add_property(StringName p_class,const PropertyInfo& p_pinfo, const StringName& p_setter, const StringName& p_getter, int p_index=-1);
- static void get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance=false, const Object *p_validator=NULL);
- static bool set_property(Object* p_object, const StringName& p_property, const Variant& p_value, bool *r_valid=NULL);
- static bool get_property(Object* p_object,const StringName& p_property, Variant& r_value);
- static bool has_property(const StringName& p_class,const StringName& p_property,bool p_no_inheritance=false);
- static Variant::Type get_property_type(const StringName& p_class, const StringName& p_property,bool *r_is_valid=NULL);
- static StringName get_property_setter(StringName p_class,const StringName p_property);
- static StringName get_property_getter(StringName p_class,const StringName p_property);
-
-
-
- static bool has_method(StringName p_class,StringName p_method,bool p_no_inheritance=false);
- static void set_method_flags(StringName p_class,StringName p_method,int p_flags);
-
-
- static void get_method_list(StringName p_class,List<MethodInfo> *p_methods,bool p_no_inheritance=false);
+ static void add_signal(StringName p_class, const MethodInfo &p_signal);
+ static bool has_signal(StringName p_class, StringName p_signal);
+ static bool get_signal(StringName p_class, StringName p_signal, MethodInfo *r_signal);
+ static void get_signal_list(StringName p_class, List<MethodInfo> *p_signals, bool p_no_inheritance = false);
+
+ static void add_property_group(StringName p_class, const String &p_name, const String &p_prefix = "");
+ static void add_property(StringName p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index = -1);
+ static void get_property_list(StringName p_class, List<PropertyInfo> *p_list, bool p_no_inheritance = false, const Object *p_validator = NULL);
+ static bool set_property(Object *p_object, const StringName &p_property, const Variant &p_value, bool *r_valid = NULL);
+ static bool get_property(Object *p_object, const StringName &p_property, Variant &r_value);
+ static bool has_property(const StringName &p_class, const StringName &p_property, bool p_no_inheritance = false);
+ static Variant::Type get_property_type(const StringName &p_class, const StringName &p_property, bool *r_is_valid = NULL);
+ static StringName get_property_setter(StringName p_class, const StringName p_property);
+ static StringName get_property_getter(StringName p_class, const StringName p_property);
+
+ static bool has_method(StringName p_class, StringName p_method, bool p_no_inheritance = false);
+ static void set_method_flags(StringName p_class, StringName p_method, int p_flags);
+
+ static void get_method_list(StringName p_class, List<MethodInfo> *p_methods, bool p_no_inheritance = false);
static MethodBind *get_method(StringName p_class, StringName p_name);
- static void add_virtual_method(const StringName& p_class,const MethodInfo& p_method,bool p_virtual=true );
- static void get_virtual_methods(const StringName& p_class,List<MethodInfo> * p_methods,bool p_no_inheritance=false );
+ static void add_virtual_method(const StringName &p_class, const MethodInfo &p_method, bool p_virtual = true);
+ static void get_virtual_methods(const StringName &p_class, List<MethodInfo> *p_methods, bool p_no_inheritance = false);
- static void bind_integer_constant(const StringName& p_class, const StringName &p_name, int p_constant);
- static void get_integer_constant_list(const StringName& p_class, List<String> *p_constants, bool p_no_inheritance=false);
- static int get_integer_constant(const StringName& p_class, const StringName &p_name, bool *p_success=NULL);
- static StringName get_category(const StringName& p_node);
+ static void bind_integer_constant(const StringName &p_class, const StringName &p_name, int p_constant);
+ static void get_integer_constant_list(const StringName &p_class, List<String> *p_constants, bool p_no_inheritance = false);
+ static int get_integer_constant(const StringName &p_class, const StringName &p_name, bool *p_success = NULL);
+ static StringName get_category(const StringName &p_node);
- static bool get_setter_and_type_for_property(const StringName& p_class, const StringName& p_prop, StringName& r_class, StringName& r_setter);
+ static bool get_setter_and_type_for_property(const StringName &p_class, const StringName &p_prop, StringName &r_class, StringName &r_setter);
- static void set_class_enabled(StringName p_class,bool p_enable);
+ static void set_class_enabled(StringName p_class, bool p_enable);
static bool is_class_enabled(StringName p_class);
- static void add_resource_base_extension(const StringName& p_extension,const StringName& p_class);
+ static void add_resource_base_extension(const StringName &p_extension, const StringName &p_class);
static void get_resource_base_extensions(List<String> *p_extensions);
- static void get_extensions_for_type(const StringName& p_class,List<String> *p_extensions);
+ static void get_extensions_for_type(const StringName &p_class, List<String> *p_extensions);
- static void add_compatibility_class(const StringName& p_class,const StringName& p_fallback);
+ static void add_compatibility_class(const StringName &p_class, const StringName &p_fallback);
static void init();
static void set_current_api(APIType p_api);
static void cleanup();
};
-
-#define BIND_CONSTANT(m_constant)\
- ClassDB::bind_integer_constant( get_class_static() , #m_constant, m_constant);
+#define BIND_CONSTANT(m_constant) \
+ ClassDB::bind_integer_constant(get_class_static(), #m_constant, m_constant);
#ifdef TOOLS_ENABLED
-#define BIND_VMETHOD(m_method)\
- ClassDB::add_virtual_method( get_class_static() , m_method );
+#define BIND_VMETHOD(m_method) \
+ ClassDB::add_virtual_method(get_class_static(), m_method);
#else
@@ -538,6 +526,4 @@ public:
#endif
-
-
#endif // CLASS_DB_H
diff --git a/core/color.cpp b/core/color.cpp
index 80a98da252..f052ddea8a 100644
--- a/core/color.cpp
+++ b/core/color.cpp
@@ -28,82 +28,80 @@
/*************************************************************************/
#include "color.h"
+#include "color_names.inc"
+#include "map.h"
#include "math_funcs.h"
#include "print_string.h"
-#include "map.h"
-#include "color_names.inc"
uint32_t Color::to_ARGB32() const {
- uint32_t c=(uint8_t)(a*255);
- c<<=8;
- c|=(uint8_t)(r*255);
- c<<=8;
- c|=(uint8_t)(g*255);
- c<<=8;
- c|=(uint8_t)(b*255);
+ uint32_t c = (uint8_t)(a * 255);
+ c <<= 8;
+ c |= (uint8_t)(r * 255);
+ c <<= 8;
+ c |= (uint8_t)(g * 255);
+ c <<= 8;
+ c |= (uint8_t)(b * 255);
return c;
}
uint32_t Color::to_32() const {
- uint32_t c=(uint8_t)(a*255);
- c<<=8;
- c|=(uint8_t)(r*255);
- c<<=8;
- c|=(uint8_t)(g*255);
- c<<=8;
- c|=(uint8_t)(b*255);
+ uint32_t c = (uint8_t)(a * 255);
+ c <<= 8;
+ c |= (uint8_t)(r * 255);
+ c <<= 8;
+ c |= (uint8_t)(g * 255);
+ c <<= 8;
+ c |= (uint8_t)(b * 255);
return c;
}
float Color::get_h() const {
- float min = MIN( r, g );
- min = MIN( min, b );
- float max = MAX( r, g );
- max = MAX( max, b );
+ float min = MIN(r, g);
+ min = MIN(min, b);
+ float max = MAX(r, g);
+ max = MAX(max, b);
float delta = max - min;
- if( delta == 0 )
+ 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
+ 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 = 4 + (r - g) / delta; // between magenta & cyan
- h/=6.0;
- if (h<0)
- h+=1.0;
+ h /= 6.0;
+ if (h < 0)
+ h += 1.0;
return h;
}
float Color::get_s() const {
-
- float min = MIN( r, g );
- min = MIN( min, b );
- float max = MAX( r, g );
- max = MAX( max, b );
+ float min = MIN(r, g);
+ min = MIN(min, b);
+ float max = MAX(r, g);
+ max = MAX(max, b);
float delta = max - min;
- return (max!=0) ? (delta / max) : 0;
-
+ return (max != 0) ? (delta / max) : 0;
}
float Color::get_v() const {
- float max = MAX( r, g );
- max = MAX( max, b );
+ float max = MAX(r, g);
+ max = MAX(max, b);
return max;
}
@@ -111,24 +109,24 @@ void Color::set_hsv(float p_h, float p_s, float p_v, float p_alpha) {
int i;
float f, p, q, t;
- a=p_alpha;
+ a = p_alpha;
- if( p_s == 0 ) {
+ if (p_s == 0) {
// acp_hromatic (grey)
r = g = b = p_v;
return;
}
- p_h *=6.0;
- p_h = Math::fmod(p_h,6);
- i = Math::floor( p_h );
+ p_h *= 6.0;
+ p_h = Math::fmod(p_h, 6);
+ i = Math::floor(p_h);
f = p_h - i;
- p = p_v * ( 1 - p_s );
- q = p_v * ( 1 - p_s * f );
- t = p_v * ( 1 - p_s * ( 1 - f ) );
+ p = p_v * (1 - p_s);
+ q = p_v * (1 - p_s * f);
+ t = p_v * (1 - p_s * (1 - f));
- switch( i ) {
+ switch (i) {
case 0: // Red is the dominant color
r = p_v;
g = t;
@@ -164,170 +162,166 @@ void Color::set_hsv(float p_h, float p_s, float p_v, float p_alpha) {
void Color::invert() {
- r=1.0-r;
- g=1.0-g;
- b=1.0-b;
+ r = 1.0 - r;
+ g = 1.0 - g;
+ b = 1.0 - b;
}
void Color::contrast() {
- r=Math::fmod(r+0.5,1.0);
- g=Math::fmod(g+0.5,1.0);
- b=Math::fmod(b+0.5,1.0);
+ r = Math::fmod(r + 0.5, 1.0);
+ g = Math::fmod(g + 0.5, 1.0);
+ b = Math::fmod(b + 0.5, 1.0);
}
Color Color::hex(uint32_t p_hex) {
- float a = (p_hex&0xFF)/255.0;
- p_hex>>=8;
- float b = (p_hex&0xFF)/255.0;
- p_hex>>=8;
- float g = (p_hex&0xFF)/255.0;
- p_hex>>=8;
- float r = (p_hex&0xFF)/255.0;
+ float a = (p_hex & 0xFF) / 255.0;
+ p_hex >>= 8;
+ float b = (p_hex & 0xFF) / 255.0;
+ p_hex >>= 8;
+ float g = (p_hex & 0xFF) / 255.0;
+ p_hex >>= 8;
+ float r = (p_hex & 0xFF) / 255.0;
- return Color(r,g,b,a);
+ return Color(r, g, b, a);
}
-static float _parse_col(const String& p_str, int p_ofs) {
+static float _parse_col(const String &p_str, int p_ofs) {
- int ig=0;
+ int ig = 0;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- int c=p_str[i+p_ofs];
- int v=0;
+ int c = p_str[i + p_ofs];
+ int 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;
+ 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 {
return -1;
}
- if (i==0)
- ig+=v*16;
+ if (i == 0)
+ ig += v * 16;
else
- ig+=v;
-
+ ig += v;
}
return ig;
-
}
Color Color::inverted() const {
- Color c=*this;
+ Color c = *this;
c.invert();
return c;
}
Color Color::contrasted() const {
- Color c=*this;
+ Color c = *this;
c.contrast();
return c;
}
-
-Color Color::html(const String& p_color) {
+Color Color::html(const String &p_color) {
String color = p_color;
- if (color.length()==0)
+ if (color.length() == 0)
return Color();
- if (color[0]=='#')
- color=color.substr(1,color.length()-1);
+ if (color[0] == '#')
+ color = color.substr(1, color.length() - 1);
- bool alpha=false;
+ bool alpha = false;
- if (color.length()==8) {
- alpha=true;
- } else if (color.length()==6) {
- alpha=false;
+ if (color.length() == 8) {
+ alpha = true;
+ } else if (color.length() == 6) {
+ alpha = false;
} else {
- ERR_EXPLAIN("Invalid Color Code: "+p_color);
+ ERR_EXPLAIN("Invalid Color Code: " + p_color);
ERR_FAIL_V(Color());
}
- int a=255;
+ int a = 255;
if (alpha) {
- a=_parse_col(color,0);
- if (a<0) {
- ERR_EXPLAIN("Invalid Color Code: "+p_color);
+ a = _parse_col(color, 0);
+ if (a < 0) {
+ ERR_EXPLAIN("Invalid Color Code: " + p_color);
ERR_FAIL_V(Color());
}
}
- int from=alpha?2:0;
+ int from = alpha ? 2 : 0;
- int r=_parse_col(color,from+0);
- if (r<0) {
- ERR_EXPLAIN("Invalid Color Code: "+p_color);
+ int r = _parse_col(color, from + 0);
+ if (r < 0) {
+ ERR_EXPLAIN("Invalid Color Code: " + p_color);
ERR_FAIL_V(Color());
}
- int g=_parse_col(color,from+2);
- if (g<0) {
- ERR_EXPLAIN("Invalid Color Code: "+p_color);
+ int g = _parse_col(color, from + 2);
+ if (g < 0) {
+ ERR_EXPLAIN("Invalid Color Code: " + p_color);
ERR_FAIL_V(Color());
}
- int b=_parse_col(color,from+4);
- if (b<0) {
- ERR_EXPLAIN("Invalid Color Code: "+p_color);
+ int b = _parse_col(color, from + 4);
+ if (b < 0) {
+ ERR_EXPLAIN("Invalid Color Code: " + p_color);
ERR_FAIL_V(Color());
}
- return Color(r/255.0,g/255.0,b/255.0,a/255.0);
+ return Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
}
-bool Color::html_is_valid(const String& p_color) {
+bool Color::html_is_valid(const String &p_color) {
String color = p_color;
- if (color.length()==0)
+ if (color.length() == 0)
return false;
- if (color[0]=='#')
- color=color.substr(1,color.length()-1);
+ if (color[0] == '#')
+ color = color.substr(1, color.length() - 1);
- bool alpha=false;
+ bool alpha = false;
- if (color.length()==8) {
- alpha=true;
- } else if (color.length()==6) {
- alpha=false;
+ if (color.length() == 8) {
+ alpha = true;
+ } else if (color.length() == 6) {
+ alpha = false;
} else {
return false;
}
- int a=255;
+ int a = 255;
if (alpha) {
- a=_parse_col(color,0);
- if (a<0) {
+ a = _parse_col(color, 0);
+ if (a < 0) {
return false;
}
}
- int from=alpha?2:0;
+ int from = alpha ? 2 : 0;
- int r=_parse_col(color,from+0);
- if (r<0) {
+ int r = _parse_col(color, from + 0);
+ if (r < 0) {
return false;
}
- int g=_parse_col(color,from+2);
- if (g<0) {
+ int g = _parse_col(color, from + 2);
+ if (g < 0) {
return false;
}
- int b=_parse_col(color,from+4);
- if (b<0) {
+ int b = _parse_col(color, from + 4);
+ if (b < 0) {
return false;
}
return true;
-
}
Color Color::named(const String &p_name) {
@@ -340,12 +334,12 @@ Color Color::named(const String &p_name) {
name = name.replace("'", "");
name = name.replace(".", "");
name = name.to_lower();
-
- const Map<String, Color>::Element* color = _named_colors.find(name);
- if(color) {
+
+ const Map<String, Color>::Element *color = _named_colors.find(name);
+ if (color) {
return color->value();
} else {
- ERR_EXPLAIN("Invalid Color Name: "+p_name);
+ ERR_EXPLAIN("Invalid Color Name: " + p_name);
ERR_FAIL_V(Color());
}
}
@@ -353,48 +347,43 @@ Color Color::named(const String &p_name) {
String _to_hex(float p_val) {
int v = p_val * 255;
- v = CLAMP(v,0,255);
+ v = CLAMP(v, 0, 255);
String ret;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- CharType c[2]={0,0};
- int lv = v&0xF;
- if (lv<10)
- c[0]='0'+lv;
+ CharType c[2] = { 0, 0 };
+ int lv = v & 0xF;
+ if (lv < 10)
+ c[0] = '0' + lv;
else
- c[0]='a'+lv-10;
+ c[0] = 'a' + lv - 10;
- v>>=4;
- String cs=(const CharType*)c;
+ v >>= 4;
+ String cs = (const CharType *)c;
ret = cs + ret;
}
return ret;
-
}
String Color::to_html(bool p_alpha) const {
String txt;
- txt+=_to_hex(r);
- txt+=_to_hex(g);
- txt+=_to_hex(b);
+ txt += _to_hex(r);
+ txt += _to_hex(g);
+ txt += _to_hex(b);
if (p_alpha)
- txt=_to_hex(a)+txt;
+ txt = _to_hex(a) + txt;
return txt;
-
}
-
float Color::gray() const {
- return (r+g+b)/3.0;
+ return (r + g + b) / 3.0;
}
Color::operator String() const {
- return rtos(r)+", "+rtos(g)+", "+rtos(b)+", "+rtos(a);
+ return rtos(r) + ", " + rtos(g) + ", " + rtos(b) + ", " + rtos(a);
}
-
-
diff --git a/core/color.h b/core/color.h
index 50a6761340..2339cd6cd7 100644
--- a/core/color.h
+++ b/core/color.h
@@ -29,8 +29,8 @@
#ifndef COLOR_H
#define COLOR_H
-#include "ustring.h"
#include "math_funcs.h"
+#include "ustring.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -47,8 +47,8 @@ struct Color {
float components[4];
};
- bool operator==(const Color &p_color) const { return (r==p_color.r && g==p_color.g && b==p_color.b && a==p_color.a ); }
- bool operator!=(const Color &p_color) const { return (r!=p_color.r || g!=p_color.g || b!=p_color.b || a!=p_color.a ); }
+ bool operator==(const Color &p_color) const { return (r == p_color.r && g == p_color.g && b == p_color.b && a == p_color.a); }
+ bool operator!=(const Color &p_color) const { return (r != p_color.r || g != p_color.g || b != p_color.b || a != p_color.a); }
uint32_t to_32() const;
uint32_t to_ARGB32() const;
@@ -56,12 +56,12 @@ struct Color {
float get_h() const;
float get_s() const;
float get_v() const;
- void set_hsv(float p_h, float p_s, float p_v, float p_alpha=1.0);
+ void set_hsv(float p_h, float p_s, float p_v, float p_alpha = 1.0);
- _FORCE_INLINE_ float& operator[](int idx) {
+ _FORCE_INLINE_ float &operator[](int idx) {
return components[idx];
}
- _FORCE_INLINE_ const float& operator[](int idx) const {
+ _FORCE_INLINE_ const float &operator[](int idx) const {
return components[idx];
}
@@ -70,30 +70,29 @@ struct Color {
Color inverted() const;
Color contrasted() const;
- _FORCE_INLINE_ Color linear_interpolate(const Color& p_b, float p_t) const {
+ _FORCE_INLINE_ Color linear_interpolate(const Color &p_b, float p_t) const {
- Color res=*this;
+ Color res = *this;
- res.r+= (p_t * (p_b.r-r));
- res.g+= (p_t * (p_b.g-g));
- res.b+= (p_t * (p_b.b-b));
- res.a+= (p_t * (p_b.a-a));
+ res.r += (p_t * (p_b.r - r));
+ res.g += (p_t * (p_b.g - g));
+ res.b += (p_t * (p_b.b - b));
+ res.a += (p_t * (p_b.a - a));
return res;
}
- _FORCE_INLINE_ Color blend(const Color& p_over) const {
-
+ _FORCE_INLINE_ Color blend(const Color &p_over) const {
Color res;
float sa = 1.0 - p_over.a;
- res.a = a*sa+p_over.a;
- if (res.a==0) {
- return Color(0,0,0,0);
+ res.a = a * sa + p_over.a;
+ if (res.a == 0) {
+ return Color(0, 0, 0, 0);
} else {
- res.r = (r*a*sa + p_over.r * p_over.a)/res.a;
- res.g = (g*a*sa + p_over.g * p_over.a)/res.a;
- res.b = (b*a*sa + p_over.b * p_over.a)/res.a;
+ res.r = (r * a * sa + p_over.r * p_over.a) / res.a;
+ res.g = (g * a * sa + p_over.g * p_over.a) / res.a;
+ res.b = (b * a * sa + p_over.b * p_over.a) / res.a;
}
return res;
}
@@ -101,48 +100,54 @@ struct Color {
_FORCE_INLINE_ Color to_linear() const {
return Color(
- r<0.04045 ? r * (1.0 / 12.92) : Math::pow((r + 0.055) * (1.0 / (1 + 0.055)), 2.4),
- g<0.04045 ? g * (1.0 / 12.92) : Math::pow((g + 0.055) * (1.0 / (1 + 0.055)), 2.4),
- b<0.04045 ? b * (1.0 / 12.92) : Math::pow((b + 0.055) * (1.0 / (1 + 0.055)), 2.4),
- a
- );
+ r < 0.04045 ? r * (1.0 / 12.92) : Math::pow((r + 0.055) * (1.0 / (1 + 0.055)), 2.4),
+ g < 0.04045 ? g * (1.0 / 12.92) : Math::pow((g + 0.055) * (1.0 / (1 + 0.055)), 2.4),
+ b < 0.04045 ? b * (1.0 / 12.92) : Math::pow((b + 0.055) * (1.0 / (1 + 0.055)), 2.4),
+ a);
}
static Color hex(uint32_t p_hex);
- static Color html(const String& p_color);
- static bool html_is_valid(const String& p_color);
- static Color named(const String& p_name);
- String to_html(bool p_alpha=true) const;
+ static Color html(const String &p_color);
+ static bool html_is_valid(const String &p_color);
+ static Color named(const String &p_name);
+ String to_html(bool p_alpha = true) const;
- _FORCE_INLINE_ bool operator<(const Color& p_color) const; //used in set keys
+ _FORCE_INLINE_ bool operator<(const Color &p_color) const; //used in set keys
operator String() const;
/**
* No construct parameters, r=0, g=0, b=0. a=255
*/
_FORCE_INLINE_ Color() {
- r=0; g=0; b=0; a=1.0;
+ r = 0;
+ g = 0;
+ b = 0;
+ a = 1.0;
}
/**
* RGB / RGBA construct parameters. Alpha is optional, but defaults to 1.0
*/
- _FORCE_INLINE_ Color(float p_r,float p_g,float p_b,float p_a=1.0) { r=p_r; g=p_g; b=p_b; a=p_a; }
+ _FORCE_INLINE_ Color(float p_r, float p_g, float p_b, float p_a = 1.0) {
+ r = p_r;
+ g = p_g;
+ b = p_b;
+ a = p_a;
+ }
};
-bool Color::operator<(const Color& p_color) const {
+bool Color::operator<(const Color &p_color) const {
- if (r==p_color.r) {
- if (g==p_color.g) {
- if(b==p_color.b) {
- return (a<p_color.a);
+ if (r == p_color.r) {
+ if (g == p_color.g) {
+ if (b == p_color.b) {
+ return (a < p_color.a);
} else
- return (b<p_color.b);
+ return (b < p_color.b);
} else
- return g<p_color.g;
+ return g < p_color.g;
} else
- return r<p_color.r;
-
+ return r < p_color.r;
}
#endif
diff --git a/core/command_queue_mt.cpp b/core/command_queue_mt.cpp
index 6d50ed8d9a..c66177261b 100644
--- a/core/command_queue_mt.cpp
+++ b/core/command_queue_mt.cpp
@@ -48,22 +48,22 @@ void CommandQueueMT::wait_for_flush() {
OS::get_singleton()->delay_usec(1000);
}
-CommandQueueMT::SyncSemaphore* CommandQueueMT::_alloc_sync_sem() {
+CommandQueueMT::SyncSemaphore *CommandQueueMT::_alloc_sync_sem() {
- int idx=-1;
+ int idx = -1;
- while(true) {
+ while (true) {
- for(int i=0;i<SYNC_SEMAPHORES;i++) {
+ for (int i = 0; i < SYNC_SEMAPHORES; i++) {
if (!sync_sems[i].in_use) {
- sync_sems[i].in_use=true;
- idx=i;
+ sync_sems[i].in_use = true;
+ idx = i;
break;
}
}
- if (idx==-1) {
+ if (idx == -1) {
wait_for_flush();
} else {
break;
@@ -73,36 +73,30 @@ CommandQueueMT::SyncSemaphore* CommandQueueMT::_alloc_sync_sem() {
return &sync_sems[idx];
}
+CommandQueueMT::CommandQueueMT(bool p_sync) {
-CommandQueueMT::CommandQueueMT(bool p_sync){
-
- read_ptr=0;
- write_ptr=0;
+ read_ptr = 0;
+ write_ptr = 0;
mutex = Mutex::create();
- for(int i=0;i<SYNC_SEMAPHORES;i++) {
-
- sync_sems[i].sem=Semaphore::create();
- sync_sems[i].in_use=false;
-
+ for (int i = 0; i < SYNC_SEMAPHORES; i++) {
+ sync_sems[i].sem = Semaphore::create();
+ sync_sems[i].in_use = false;
}
if (p_sync)
sync = Semaphore::create();
else
- sync=NULL;
+ sync = NULL;
}
-
CommandQueueMT::~CommandQueueMT() {
if (sync)
memdelete(sync);
memdelete(mutex);
- for(int i=0;i<SYNC_SEMAPHORES;i++) {
+ for (int i = 0; i < SYNC_SEMAPHORES; i++) {
memdelete(sync_sems[i].sem);
}
}
-
-
diff --git a/core/command_queue_mt.h b/core/command_queue_mt.h
index 3975df7658..3a859c809c 100644
--- a/core/command_queue_mt.h
+++ b/core/command_queue_mt.h
@@ -29,11 +29,11 @@
#ifndef COMMAND_QUEUE_MT_H
#define COMMAND_QUEUE_MT_H
-#include "typedefs.h"
-#include "os/semaphore.h"
-#include "os/mutex.h"
#include "os/memory.h"
+#include "os/mutex.h"
+#include "os/semaphore.h"
#include "simple_type.h"
+#include "typedefs.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -48,69 +48,69 @@ class CommandQueueMT {
struct CommandBase {
- virtual void call()=0;
- virtual ~CommandBase() {};
+ virtual void call() = 0;
+ virtual ~CommandBase(){};
};
- template<class T,class M>
+ template <class T, class M>
struct Command0 : public CommandBase {
- T*instance;
+ T *instance;
M method;
virtual void call() { (instance->*method)(); }
};
- template<class T,class M,class P1>
+ template <class T, class M, class P1>
struct Command1 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
virtual void call() { (instance->*method)(p1); }
};
- template<class T,class M,class P1,class P2>
+ template <class T, class M, class P1, class P2>
struct Command2 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
- virtual void call() { (instance->*method)(p1,p2); }
+ virtual void call() { (instance->*method)(p1, p2); }
};
- template<class T,class M,class P1,class P2,class P3>
+ template <class T, class M, class P1, class P2, class P3>
struct Command3 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
typename GetSimpleTypeT<P3>::type_t p3;
- virtual void call() { (instance->*method)(p1,p2,p3); }
+ virtual void call() { (instance->*method)(p1, p2, p3); }
};
- template<class T,class M,class P1,class P2,class P3,class P4>
+ template <class T, class M, class P1, class P2, class P3, class P4>
struct Command4 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
typename GetSimpleTypeT<P3>::type_t p3;
typename GetSimpleTypeT<P4>::type_t p4;
- virtual void call() { (instance->*method)(p1,p2,p3,p4); }
+ virtual void call() { (instance->*method)(p1, p2, p3, p4); }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5>
struct Command5 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -118,13 +118,13 @@ class CommandQueueMT {
typename GetSimpleTypeT<P4>::type_t p4;
typename GetSimpleTypeT<P5>::type_t p5;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); }
+ virtual void call() { (instance->*method)(p1, p2, p3, p4, p5); }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
struct Command6 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -133,13 +133,13 @@ class CommandQueueMT {
typename GetSimpleTypeT<P5>::type_t p5;
typename GetSimpleTypeT<P6>::type_t p6;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6); }
+ virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6); }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
struct Command7 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -149,13 +149,13 @@ class CommandQueueMT {
typename GetSimpleTypeT<P6>::type_t p6;
typename GetSimpleTypeT<P7>::type_t p7;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7); }
+ virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6, p7); }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
struct Command8 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -166,96 +166,120 @@ class CommandQueueMT {
typename GetSimpleTypeT<P7>::type_t p7;
typename GetSimpleTypeT<P8>::type_t p8;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); }
+ virtual void call() { (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8); }
};
/* comands that return */
- template<class T,class M,class R>
+ template <class T, class M, class R>
struct CommandRet0 : public CommandBase {
- T*instance;
+ T *instance;
M method;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)();
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class R>
+ template <class T, class M, class P1, class R>
struct CommandRet1 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class R>
+ template <class T, class M, class P1, class P2, class R>
struct CommandRet2 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class R>
+ template <class T, class M, class P1, class P2, class P3, class R>
struct CommandRet3 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
typename GetSimpleTypeT<P3>::type_t p3;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class R>
+ template <class T, class M, class P1, class P2, class P3, class P4, class R>
struct CommandRet4 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
typename GetSimpleTypeT<P3>::type_t p3;
typename GetSimpleTypeT<P4>::type_t p4;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3, p4);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class R>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class R>
struct CommandRet5 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
typename GetSimpleTypeT<P3>::type_t p3;
typename GetSimpleTypeT<P4>::type_t p4;
typename GetSimpleTypeT<P5>::type_t p5;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3, p4, p5);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class R>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class R>
struct CommandRet6 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -263,16 +287,20 @@ class CommandQueueMT {
typename GetSimpleTypeT<P4>::type_t p4;
typename GetSimpleTypeT<P5>::type_t p5;
typename GetSimpleTypeT<P6>::type_t p6;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3, p4, p5, p6);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class R>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class R>
struct CommandRet7 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -281,16 +309,20 @@ class CommandQueueMT {
typename GetSimpleTypeT<P5>::type_t p5;
typename GetSimpleTypeT<P6>::type_t p6;
typename GetSimpleTypeT<P7>::type_t p7;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6,p7); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3, p4, p5, p6, p7);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8,class R>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class R>
struct CommandRet8 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -300,56 +332,72 @@ class CommandQueueMT {
typename GetSimpleTypeT<P6>::type_t p6;
typename GetSimpleTypeT<P7>::type_t p7;
typename GetSimpleTypeT<P8>::type_t p8;
- R* ret;
+ R *ret;
SyncSemaphore *sync;
- virtual void call() { *ret = (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ *ret = (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
/** commands that don't return but sync */
/* comands that return */
- template<class T,class M>
+ template <class T, class M>
struct CommandSync0 : public CommandBase {
- T*instance;
+ T *instance;
M method;
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)();
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1>
+ template <class T, class M, class P1>
struct CommandSync1 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2>
+ template <class T, class M, class P1, class P2>
struct CommandSync2 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3>
+ template <class T, class M, class P1, class P2, class P3>
struct CommandSync3 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -357,13 +405,17 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4>
+ template <class T, class M, class P1, class P2, class P3, class P4>
struct CommandSync4 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -372,13 +424,17 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3,p4); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3, p4);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5>
struct CommandSync5 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -388,13 +444,17 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3, p4, p5);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
struct CommandSync6 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -405,13 +465,17 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3, p4, p5, p6);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
struct CommandSync7 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -423,13 +487,17 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3, p4, p5, p6, p7);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
- template<class T,class M,class P1,class P2,class P3,class P4,class P5,class P6,class P7,class P8>
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
struct CommandSync8 : public CommandBase {
- T*instance;
+ T *instance;
M method;
typename GetSimpleTypeT<P1>::type_t p1;
typename GetSimpleTypeT<P2>::type_t p2;
@@ -442,18 +510,21 @@ class CommandQueueMT {
SyncSemaphore *sync;
- virtual void call() { (instance->*method)(p1,p2,p3,p4,p5,p6,p7,p8); sync->sem->post(); sync->in_use=false; }
+ virtual void call() {
+ (instance->*method)(p1, p2, p3, p4, p5, p6, p7, p8);
+ sync->sem->post();
+ sync->in_use = false;
+ }
};
/***** BASE *******/
enum {
- COMMAND_MEM_SIZE_KB=256,
- COMMAND_MEM_SIZE=COMMAND_MEM_SIZE_KB*1024,
- SYNC_SEMAPHORES=8
+ COMMAND_MEM_SIZE_KB = 256,
+ COMMAND_MEM_SIZE = COMMAND_MEM_SIZE_KB * 1024,
+ SYNC_SEMAPHORES = 8
};
-
uint8_t command_mem[COMMAND_MEM_SIZE];
uint32_t read_ptr;
uint32_t write_ptr;
@@ -461,255 +532,247 @@ class CommandQueueMT {
Mutex *mutex;
Semaphore *sync;
-
- template<class T>
- T* allocate() {
+ template <class T>
+ T *allocate() {
// alloc size is size+T+safeguard
- uint32_t alloc_size=sizeof(T)+sizeof(uint32_t);
+ uint32_t alloc_size = sizeof(T) + sizeof(uint32_t);
- tryagain:
+ tryagain:
if (write_ptr < read_ptr) {
// behind read_ptr, check that there is room
- if ( (read_ptr-write_ptr) <= alloc_size )
+ if ((read_ptr - write_ptr) <= alloc_size)
return NULL;
} else if (write_ptr >= read_ptr) {
// ahead of read_ptr, check that there is room
-
- if ( (COMMAND_MEM_SIZE-write_ptr) < alloc_size+4 ) {
+ if ((COMMAND_MEM_SIZE - write_ptr) < alloc_size + 4) {
// no room at the end, wrap down;
- if (read_ptr==0) // dont want write_ptr to become read_ptr
+ if (read_ptr == 0) // dont want write_ptr to become read_ptr
return NULL;
// if this happens, it's a bug
- ERR_FAIL_COND_V( (COMMAND_MEM_SIZE-write_ptr) < sizeof(uint32_t), NULL );
+ ERR_FAIL_COND_V((COMMAND_MEM_SIZE - write_ptr) < sizeof(uint32_t), NULL);
// zero means, wrap to begining
- uint32_t * p = (uint32_t*)&command_mem[write_ptr];
- *p=0;
- write_ptr=0;
+ uint32_t *p = (uint32_t *)&command_mem[write_ptr];
+ *p = 0;
+ write_ptr = 0;
goto tryagain;
}
}
// allocate the size
- uint32_t * p = (uint32_t*)&command_mem[write_ptr];
- *p=sizeof(T);
- write_ptr+=sizeof(uint32_t);
+ uint32_t *p = (uint32_t *)&command_mem[write_ptr];
+ *p = sizeof(T);
+ write_ptr += sizeof(uint32_t);
// allocate the command
- T* cmd = memnew_placement( &command_mem[write_ptr], T );
- write_ptr+=sizeof(T);
+ T *cmd = memnew_placement(&command_mem[write_ptr], T);
+ write_ptr += sizeof(T);
return cmd;
-
}
- template<class T>
- T* allocate_and_lock() {
+ template <class T>
+ T *allocate_and_lock() {
lock();
- T* ret;
+ T *ret;
- while ( (ret=allocate<T>())==NULL ) {
+ while ((ret = allocate<T>()) == NULL) {
unlock();
// sleep a little until fetch happened and some room is made
wait_for_flush();
lock();
-
}
return ret;
}
-
bool flush_one() {
- tryagain:
+ tryagain:
// tried to read an empty queue
- if (read_ptr == write_ptr )
+ if (read_ptr == write_ptr)
return false;
- uint32_t size = *(uint32_t*)( &command_mem[read_ptr] );
+ uint32_t size = *(uint32_t *)(&command_mem[read_ptr]);
- if (size==0) {
+ if (size == 0) {
//end of ringbuffer, wrap
- read_ptr=0;
+ read_ptr = 0;
goto tryagain;
}
- read_ptr+=sizeof(uint32_t);
+ read_ptr += sizeof(uint32_t);
- CommandBase *cmd = reinterpret_cast<CommandBase*>( &command_mem[read_ptr] );
+ CommandBase *cmd = reinterpret_cast<CommandBase *>(&command_mem[read_ptr]);
cmd->call();
cmd->~CommandBase();
- read_ptr+=size;
+ read_ptr += size;
return true;
}
-
void lock();
void unlock();
void wait_for_flush();
- SyncSemaphore* _alloc_sync_sem();
-
+ SyncSemaphore *_alloc_sync_sem();
public:
-
/* NORMAL PUSH COMMANDS */
- template<class T, class M>
- void push( T * p_instance, M p_method ) {
+ template <class T, class M>
+ void push(T *p_instance, M p_method) {
- Command0<T,M> * cmd = allocate_and_lock< Command0<T,M> >();
+ Command0<T, M> *cmd = allocate_and_lock<Command0<T, M> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1>
- void push( T * p_instance, M p_method, P1 p1 ) {
+ template <class T, class M, class P1>
+ void push(T *p_instance, M p_method, P1 p1) {
- Command1<T,M,P1> * cmd = allocate_and_lock< Command1<T,M,P1> >();
+ Command1<T, M, P1> *cmd = allocate_and_lock<Command1<T, M, P1> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2>
- void push( T * p_instance, M p_method, P1 p1, P2 p2 ) {
+ template <class T, class M, class P1, class P2>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2) {
- Command2<T,M,P1,P2> * cmd = allocate_and_lock< Command2<T,M,P1,P2> >();
+ Command2<T, M, P1, P2> *cmd = allocate_and_lock<Command2<T, M, P1, P2> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) {
+ template <class T, class M, class P1, class P2, class P3>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) {
- Command3<T,M,P1,P2,P3> * cmd = allocate_and_lock< Command3<T,M,P1,P2,P3> >();
+ Command3<T, M, P1, P2, P3> *cmd = allocate_and_lock<Command3<T, M, P1, P2, P3> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3, class P4>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) {
- Command4<T,M,P1,P2,P3,P4> * cmd = allocate_and_lock< Command4<T,M,P1,P2,P3,P4> >();
+ Command4<T, M, P1, P2, P3, P4> *cmd = allocate_and_lock<Command4<T, M, P1, P2, P3, P4> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
- Command5<T,M,P1,P2,P3,P4,P5> * cmd = allocate_and_lock< Command5<T,M,P1,P2,P3,P4,P5> >();
+ Command5<T, M, P1, P2, P3, P4, P5> *cmd = allocate_and_lock<Command5<T, M, P1, P2, P3, P4, P5> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
- Command6<T,M,P1,P2,P3,P4,P5,P6> * cmd = allocate_and_lock< Command6<T,M,P1,P2,P3,P4,P5,P6> >();
+ Command6<T, M, P1, P2, P3, P4, P5, P6> *cmd = allocate_and_lock<Command6<T, M, P1, P2, P3, P4, P5, P6> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
- Command7<T,M,P1,P2,P3,P4,P5,P6,P7> * cmd = allocate_and_lock< Command7<T,M,P1,P2,P3,P4,P5,P6,P7> >();
+ Command7<T, M, P1, P2, P3, P4, P5, P6, P7> *cmd = allocate_and_lock<Command7<T, M, P1, P2, P3, P4, P5, P6, P7> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
unlock();
if (sync) sync->post();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7,class P8>
- void push( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
+ void push(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
- Command8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> * cmd = allocate_and_lock< Command8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> >();
+ Command8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> *cmd = allocate_and_lock<Command8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
- cmd->p8=p8;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
+ cmd->p8 = p8;
unlock();
@@ -717,17 +780,16 @@ public:
}
/*** PUSH AND RET COMMANDS ***/
+ template <class T, class M, class R>
+ void push_and_ret(T *p_instance, M p_method, R *r_ret) {
- template<class T, class M,class R>
- void push_and_ret( T * p_instance, M p_method, R* r_ret) {
-
- CommandRet0<T,M,R> * cmd = allocate_and_lock< CommandRet0<T,M,R> >();
+ CommandRet0<T, M, R> *cmd = allocate_and_lock<CommandRet0<T, M, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -735,17 +797,17 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, R* r_ret) {
+ template <class T, class M, class P1, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, R *r_ret) {
- CommandRet1<T,M,P1,R> * cmd = allocate_and_lock< CommandRet1<T,M,P1,R> >();
+ CommandRet1<T, M, P1, R> *cmd = allocate_and_lock<CommandRet1<T, M, P1, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -753,18 +815,18 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, R* r_ret) {
+ template <class T, class M, class P1, class P2, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, R *r_ret) {
- CommandRet2<T,M,P1,P2,R> * cmd = allocate_and_lock< CommandRet2<T,M,P1,P2,R> >();
+ CommandRet2<T, M, P1, P2, R> *cmd = allocate_and_lock<CommandRet2<T, M, P1, P2, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -772,19 +834,19 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, R* r_ret ) {
+ template <class T, class M, class P1, class P2, class P3, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, R *r_ret) {
- CommandRet3<T,M,P1,P2,P3,R> * cmd = allocate_and_lock< CommandRet3<T,M,P1,P2,P3,R> >();
+ CommandRet3<T, M, P1, P2, P3, R> *cmd = allocate_and_lock<CommandRet3<T, M, P1, P2, P3, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -792,20 +854,20 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R* r_ret ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, R *r_ret) {
- CommandRet4<T,M,P1,P2,P3,P4,R> * cmd = allocate_and_lock< CommandRet4<T,M,P1,P2,P3,P4,R> >();
+ CommandRet4<T, M, P1, P2, P3, P4, R> *cmd = allocate_and_lock<CommandRet4<T, M, P1, P2, P3, P4, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -813,21 +875,21 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R* r_ret ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, R *r_ret) {
- CommandRet5<T,M,P1,P2,P3,P4,P5,R> * cmd = allocate_and_lock< CommandRet5<T,M,P1,P2,P3,P4,P5,R> >();
+ CommandRet5<T, M, P1, P2, P3, P4, P5, R> *cmd = allocate_and_lock<CommandRet5<T, M, P1, P2, P3, P4, P5, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -835,22 +897,22 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, R* r_ret ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, R *r_ret) {
- CommandRet6<T,M,P1,P2,P3,P4,P5,P6,R> * cmd = allocate_and_lock< CommandRet6<T,M,P1,P2,P3,P4,P5,P6,R> >();
+ CommandRet6<T, M, P1, P2, P3, P4, P5, P6, R> *cmd = allocate_and_lock<CommandRet6<T, M, P1, P2, P3, P4, P5, P6, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -858,23 +920,23 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7, R* r_ret ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, R *r_ret) {
- CommandRet7<T,M,P1,P2,P3,P4,P5,P6,P7,R> * cmd = allocate_and_lock< CommandRet7<T,M,P1,P2,P3,P4,P5,P6,P7,R> >();
+ CommandRet7<T, M, P1, P2, P3, P4, P5, P6, P7, R> *cmd = allocate_and_lock<CommandRet7<T, M, P1, P2, P3, P4, P5, P6, P7, R> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -882,24 +944,24 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class P8,class R>
- void push_and_ret( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7,P8 p8, R* r_ret ) {
-
- CommandRet8<T,M,P1,P2,P3,P4,P5,P6,P7,P8,R> * cmd = allocate_and_lock< CommandRet8<T,M,P1,P2,P3,P4,P5,P6,P7,P8,R> >();
-
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
- cmd->p8=p8;
- cmd->ret=r_ret;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8, class R>
+ void push_and_ret(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, R *r_ret) {
+
+ CommandRet8<T, M, P1, P2, P3, P4, P5, P6, P7, P8, R> *cmd = allocate_and_lock<CommandRet8<T, M, P1, P2, P3, P4, P5, P6, P7, P8, R> >();
+
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
+ cmd->p8 = p8;
+ cmd->ret = r_ret;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -907,17 +969,16 @@ public:
ss->sem->wait();
}
+ template <class T, class M>
+ void push_and_sync(T *p_instance, M p_method) {
- template<class T, class M>
- void push_and_sync( T * p_instance, M p_method) {
+ CommandSync0<T, M> *cmd = allocate_and_lock<CommandSync0<T, M> >();
- CommandSync0<T,M> * cmd = allocate_and_lock< CommandSync0<T,M> >();
+ cmd->instance = p_instance;
+ cmd->method = p_method;
- cmd->instance=p_instance;
- cmd->method=p_method;
-
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -925,17 +986,17 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1>
- void push_and_sync( T * p_instance, M p_method, P1 p1) {
+ template <class T, class M, class P1>
+ void push_and_sync(T *p_instance, M p_method, P1 p1) {
- CommandSync1<T,M,P1> * cmd = allocate_and_lock< CommandSync1<T,M,P1> >();
+ CommandSync1<T, M, P1> *cmd = allocate_and_lock<CommandSync1<T, M, P1> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -943,18 +1004,18 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2) {
+ template <class T, class M, class P1, class P2>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2) {
- CommandSync2<T,M,P1,P2> * cmd = allocate_and_lock< CommandSync2<T,M,P1,P2> >();
+ CommandSync2<T, M, P1, P2> *cmd = allocate_and_lock<CommandSync2<T, M, P1, P2> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -962,19 +1023,19 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3 ) {
+ template <class T, class M, class P1, class P2, class P3>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3) {
- CommandSync3<T,M,P1,P2,P3> * cmd = allocate_and_lock< CommandSync3<T,M,P1,P2,P3> >();
+ CommandSync3<T, M, P1, P2, P3> *cmd = allocate_and_lock<CommandSync3<T, M, P1, P2, P3> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -982,20 +1043,20 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4) {
- CommandSync4<T,M,P1,P2,P3,P4> * cmd = allocate_and_lock< CommandSync4<T,M,P1,P2,P3,P4> >();
+ CommandSync4<T, M, P1, P2, P3, P4> *cmd = allocate_and_lock<CommandSync4<T, M, P1, P2, P3, P4> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -1003,21 +1064,21 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) {
- CommandSync5<T,M,P1,P2,P3,P4,P5> * cmd = allocate_and_lock< CommandSync5<T,M,P1,P2,P3,P4,P5> >();
+ CommandSync5<T, M, P1, P2, P3, P4, P5> *cmd = allocate_and_lock<CommandSync5<T, M, P1, P2, P3, P4, P5> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -1025,22 +1086,22 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) {
- CommandSync6<T,M,P1,P2,P3,P4,P5,P6> * cmd = allocate_and_lock< CommandSync6<T,M,P1,P2,P3,P4,P5,P6> >();
+ CommandSync6<T, M, P1, P2, P3, P4, P5, P6> *cmd = allocate_and_lock<CommandSync6<T, M, P1, P2, P3, P4, P5, P6> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -1048,23 +1109,23 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7 ) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) {
- CommandSync7<T,M,P1,P2,P3,P4,P5,P6,P7> * cmd = allocate_and_lock< CommandSync7<T,M,P1,P2,P3,P4,P5,P6,P7> >();
+ CommandSync7<T, M, P1, P2, P3, P4, P5, P6, P7> *cmd = allocate_and_lock<CommandSync7<T, M, P1, P2, P3, P4, P5, P6, P7> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -1072,24 +1133,24 @@ public:
ss->sem->wait();
}
- template<class T, class M, class P1, class P2, class P3, class P4, class P5, class P6,class P7,class P8>
- void push_and_sync( T * p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6,P7 p7,P8 p8) {
+ template <class T, class M, class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
+ void push_and_sync(T *p_instance, M p_method, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) {
- CommandSync8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> * cmd = allocate_and_lock< CommandSync8<T,M,P1,P2,P3,P4,P5,P6,P7,P8> >();
+ CommandSync8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> *cmd = allocate_and_lock<CommandSync8<T, M, P1, P2, P3, P4, P5, P6, P7, P8> >();
- cmd->instance=p_instance;
- cmd->method=p_method;
- cmd->p1=p1;
- cmd->p2=p2;
- cmd->p3=p3;
- cmd->p4=p4;
- cmd->p5=p5;
- cmd->p6=p6;
- cmd->p7=p7;
- cmd->p8=p8;
+ cmd->instance = p_instance;
+ cmd->method = p_method;
+ cmd->p1 = p1;
+ cmd->p2 = p2;
+ cmd->p3 = p3;
+ cmd->p4 = p4;
+ cmd->p5 = p5;
+ cmd->p6 = p6;
+ cmd->p7 = p7;
+ cmd->p8 = p8;
- SyncSemaphore *ss=_alloc_sync_sem();
- cmd->sync=ss;
+ SyncSemaphore *ss = _alloc_sync_sem();
+ cmd->sync = ss;
unlock();
@@ -1119,7 +1180,6 @@ public:
CommandQueueMT(bool p_sync);
~CommandQueueMT();
-
};
#endif
diff --git a/core/compressed_translation.cpp b/core/compressed_translation.cpp
index 570cf114f7..75c24a5aba 100644
--- a/core/compressed_translation.cpp
+++ b/core/compressed_translation.cpp
@@ -46,201 +46,199 @@ Redistribution and use in source and binary forms, with or without modification,
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.
*/
-
/* Our compression codebook, used for compression */
static const char *Smaz_cb[241] = {
-"\002s,\266", "\003had\232\002leW", "\003on \216", "", "\001yS",
-"\002ma\255\002li\227", "\003or \260", "", "\002ll\230\003s t\277",
-"\004fromg\002mel", "", "\003its\332", "\001z\333", "\003ingF", "\001>\336",
-"\001 \000\003 (\002nc\344", "\002nd=\003 on\312",
-"\002ne\213\003hat\276\003re q", "", "\002ngT\003herz\004have\306\003s o\225",
-"", "\003ionk\003s a\254\002ly\352", "\003hisL\003 inN\003 be\252", "",
-"\003 fo\325\003 of \003 ha\311", "", "\002of\005",
-"\003 co\241\002no\267\003 ma\370", "", "", "\003 cl\356\003enta\003 an7",
-"\002ns\300\001\"e", "\003n t\217\002ntP\003s, \205",
-"\002pe\320\003 we\351\002om\223", "\002on\037", "", "\002y G", "\003 wa\271",
-"\003 re\321\002or*", "", "\002=\"\251\002ot\337", "\003forD\002ou[",
-"\003 toR", "\003 th\r", "\003 it\366",
-"\003but\261\002ra\202\003 wi\363\002</\361", "\003 wh\237", "\002 4",
-"\003nd ?", "\002re!", "", "\003ng c", "",
-"\003ly \307\003ass\323\001a\004\002rir", "", "", "", "\002se_", "\003of \"",
-"\003div\364\002ros\003ere\240", "", "\002ta\310\001bZ\002si\324", "",
-"\003and\a\002rs\335", "\002rt\362", "\002teE", "\003ati\316", "\002so\263",
-"\002th\021", "\002tiJ\001c\034\003allp", "\003ate\345", "\002ss\246",
-"\002stM", "", "\002><\346", "\002to\024", "\003arew", "\001d\030",
-"\002tr\303", "", "\001\n1\003 a \222", "\003f tv\002veo", "\002un\340", "",
-"\003e o\242", "\002a \243\002wa\326\001e\002", "\002ur\226\003e a\274",
-"\002us\244\003\n\r\n\247", "\002ut\304\003e c\373", "\002we\221", "", "",
-"\002wh\302", "\001f,", "", "", "", "\003d t\206", "", "", "\003th \343",
-"\001g;", "", "", "\001\r9\003e s\265", "\003e t\234", "", "\003to Y",
-"\003e\r\n\236", "\002d \036\001h\022", "", "\001,Q", "\002 a\031", "\002 b^",
-"\002\r\n\025\002 cI", "\002 d\245", "\002 e\253", "\002 fh\001i\b\002e \v",
-"", "\002 hU\001-\314", "\002 i8", "", "", "\002 l\315", "\002 m{",
-"\002f :\002 n\354", "\002 o\035", "\002 p}\001.n\003\r\n\r\250", "",
-"\002 r\275", "\002 s>", "\002 t\016", "", "\002g \235\005which+\003whi\367",
-"\002 w5", "\001/\305", "\003as \214", "\003at \207", "", "\003who\331", "",
-"\001l\026\002h \212", "", "\002, $", "", "\004withV", "", "", "", "\001m-", "",
-"", "\002ac\357", "\002ad\350", "\003TheH", "", "", "\004this\233\001n\t",
-"", "\002. y", "", "\002alX\003e, \365", "\003tio\215\002be\\",
-"\002an\032\003ver\347", "", "\004that0\003tha\313\001o\006", "\003was2",
-"\002arO", "\002as.", "\002at'\003the\001\004they\200\005there\322\005theird",
-"\002ce\210", "\004were]", "", "\002ch\231\002l \264\001p<", "", "",
-"\003one\256", "", "\003he \023\002dej", "\003ter\270", "\002cou", "",
-"\002by\177\002di\201\002eax", "", "\002ec\327", "\002edB", "\002ee\353", "",
-"", "\001r\f\002n )", "", "", "", "\002el\262", "", "\003in i\002en3", "",
-"\002o `\001s\n", "", "\002er\033", "\003is t\002es6", "", "\002ge\371",
-"\004.com\375", "\002fo\334\003our\330", "\003ch \301\001t\003", "\002hab", "",
-"\003men\374", "", "\002he\020", "", "", "\001u&", "\002hif", "",
-"\003not\204\002ic\203", "\003ed @\002id\355", "", "", "\002ho\273",
-"\002r K\001vm", "", "", "", "\003t t\257\002il\360", "\002im\342",
-"\003en \317\002in\017", "\002io\220", "\002s \027\001wA", "", "\003er |",
-"\003es ~\002is%", "\002it/", "", "\002iv\272", "",
-"\002t #\ahttp://C\001x\372", "\002la\211", "\001<\341", "\003, a\224"
+ "\002s,\266", "\003had\232\002leW", "\003on \216", "", "\001yS",
+ "\002ma\255\002li\227", "\003or \260", "", "\002ll\230\003s t\277",
+ "\004fromg\002mel", "", "\003its\332", "\001z\333", "\003ingF", "\001>\336",
+ "\001 \000\003 (\002nc\344", "\002nd=\003 on\312",
+ "\002ne\213\003hat\276\003re q", "", "\002ngT\003herz\004have\306\003s o\225",
+ "", "\003ionk\003s a\254\002ly\352", "\003hisL\003 inN\003 be\252", "",
+ "\003 fo\325\003 of \003 ha\311", "", "\002of\005",
+ "\003 co\241\002no\267\003 ma\370", "", "", "\003 cl\356\003enta\003 an7",
+ "\002ns\300\001\"e", "\003n t\217\002ntP\003s, \205",
+ "\002pe\320\003 we\351\002om\223", "\002on\037", "", "\002y G", "\003 wa\271",
+ "\003 re\321\002or*", "", "\002=\"\251\002ot\337", "\003forD\002ou[",
+ "\003 toR", "\003 th\r", "\003 it\366",
+ "\003but\261\002ra\202\003 wi\363\002</\361", "\003 wh\237", "\002 4",
+ "\003nd ?", "\002re!", "", "\003ng c", "",
+ "\003ly \307\003ass\323\001a\004\002rir", "", "", "", "\002se_", "\003of \"",
+ "\003div\364\002ros\003ere\240", "", "\002ta\310\001bZ\002si\324", "",
+ "\003and\a\002rs\335", "\002rt\362", "\002teE", "\003ati\316", "\002so\263",
+ "\002th\021", "\002tiJ\001c\034\003allp", "\003ate\345", "\002ss\246",
+ "\002stM", "", "\002><\346", "\002to\024", "\003arew", "\001d\030",
+ "\002tr\303", "", "\001\n1\003 a \222", "\003f tv\002veo", "\002un\340", "",
+ "\003e o\242", "\002a \243\002wa\326\001e\002", "\002ur\226\003e a\274",
+ "\002us\244\003\n\r\n\247", "\002ut\304\003e c\373", "\002we\221", "", "",
+ "\002wh\302", "\001f,", "", "", "", "\003d t\206", "", "", "\003th \343",
+ "\001g;", "", "", "\001\r9\003e s\265", "\003e t\234", "", "\003to Y",
+ "\003e\r\n\236", "\002d \036\001h\022", "", "\001,Q", "\002 a\031", "\002 b^",
+ "\002\r\n\025\002 cI", "\002 d\245", "\002 e\253", "\002 fh\001i\b\002e \v",
+ "", "\002 hU\001-\314", "\002 i8", "", "", "\002 l\315", "\002 m{",
+ "\002f :\002 n\354", "\002 o\035", "\002 p}\001.n\003\r\n\r\250", "",
+ "\002 r\275", "\002 s>", "\002 t\016", "", "\002g \235\005which+\003whi\367",
+ "\002 w5", "\001/\305", "\003as \214", "\003at \207", "", "\003who\331", "",
+ "\001l\026\002h \212", "", "\002, $", "", "\004withV", "", "", "", "\001m-", "",
+ "", "\002ac\357", "\002ad\350", "\003TheH", "", "", "\004this\233\001n\t",
+ "", "\002. y", "", "\002alX\003e, \365", "\003tio\215\002be\\",
+ "\002an\032\003ver\347", "", "\004that0\003tha\313\001o\006", "\003was2",
+ "\002arO", "\002as.", "\002at'\003the\001\004they\200\005there\322\005theird",
+ "\002ce\210", "\004were]", "", "\002ch\231\002l \264\001p<", "", "",
+ "\003one\256", "", "\003he \023\002dej", "\003ter\270", "\002cou", "",
+ "\002by\177\002di\201\002eax", "", "\002ec\327", "\002edB", "\002ee\353", "",
+ "", "\001r\f\002n )", "", "", "", "\002el\262", "", "\003in i\002en3", "",
+ "\002o `\001s\n", "", "\002er\033", "\003is t\002es6", "", "\002ge\371",
+ "\004.com\375", "\002fo\334\003our\330", "\003ch \301\001t\003", "\002hab", "",
+ "\003men\374", "", "\002he\020", "", "", "\001u&", "\002hif", "",
+ "\003not\204\002ic\203", "\003ed @\002id\355", "", "", "\002ho\273",
+ "\002r K\001vm", "", "", "", "\003t t\257\002il\360", "\002im\342",
+ "\003en \317\002in\017", "\002io\220", "\002s \027\001wA", "", "\003er |",
+ "\003es ~\002is%", "\002it/", "", "\002iv\272", "",
+ "\002t #\ahttp://C\001x\372", "\002la\211", "\001<\341", "\003, a\224"
};
/* Reverse compression codebook, used for decompression */
static const char *Smaz_rcb[254] = {
-" ", "the", "e", "t", "a", "of", "o", "and", "i", "n", "s", "e ", "r", " th",
-" t", "in", "he", "th", "h", "he ", "to", "\r\n", "l", "s ", "d", " a", "an",
-"er", "c", " o", "d ", "on", " of", "re", "of ", "t ", ", ", "is", "u", "at",
-" ", "n ", "or", "which", "f", "m", "as", "it", "that", "\n", "was", "en",
-" ", " w", "es", " an", " i", "\r", "f ", "g", "p", "nd", " s", "nd ", "ed ",
-"w", "ed", "http://", "for", "te", "ing", "y ", "The", " c", "ti", "r ", "his",
-"st", " in", "ar", "nt", ",", " to", "y", "ng", " h", "with", "le", "al", "to ",
-"b", "ou", "be", "were", " b", "se", "o ", "ent", "ha", "ng ", "their", "\"",
-"hi", "from", " f", "in ", "de", "ion", "me", "v", ".", "ve", "all", "re ",
-"ri", "ro", "is ", "co", "f t", "are", "ea", ". ", "her", " m", "er ", " p",
-"es ", "by", "they", "di", "ra", "ic", "not", "s, ", "d t", "at ", "ce", "la",
-"h ", "ne", "as ", "tio", "on ", "n t", "io", "we", " a ", "om", ", a", "s o",
-"ur", "li", "ll", "ch", "had", "this", "e t", "g ", "e\r\n", " wh", "ere",
-" co", "e o", "a ", "us", " d", "ss", "\n\r\n", "\r\n\r", "=\"", " be", " e",
-"s a", "ma", "one", "t t", "or ", "but", "el", "so", "l ", "e s", "s,", "no",
-"ter", " wa", "iv", "ho", "e a", " r", "hat", "s t", "ns", "ch ", "wh", "tr",
-"ut", "/", "have", "ly ", "ta", " ha", " on", "tha", "-", " l", "ati", "en ",
-"pe", " re", "there", "ass", "si", " fo", "wa", "ec", "our", "who", "its", "z",
-"fo", "rs", ">", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad",
-" we", "ly", "ee", " n", "id", " cl", "ac", "il", "</", "rt", " wi", "div",
-"e, ", " it", "whi", " ma", "ge", "x", "e c", "men", ".com"
+ " ", "the", "e", "t", "a", "of", "o", "and", "i", "n", "s", "e ", "r", " th",
+ " t", "in", "he", "th", "h", "he ", "to", "\r\n", "l", "s ", "d", " a", "an",
+ "er", "c", " o", "d ", "on", " of", "re", "of ", "t ", ", ", "is", "u", "at",
+ " ", "n ", "or", "which", "f", "m", "as", "it", "that", "\n", "was", "en",
+ " ", " w", "es", " an", " i", "\r", "f ", "g", "p", "nd", " s", "nd ", "ed ",
+ "w", "ed", "http://", "for", "te", "ing", "y ", "The", " c", "ti", "r ", "his",
+ "st", " in", "ar", "nt", ",", " to", "y", "ng", " h", "with", "le", "al", "to ",
+ "b", "ou", "be", "were", " b", "se", "o ", "ent", "ha", "ng ", "their", "\"",
+ "hi", "from", " f", "in ", "de", "ion", "me", "v", ".", "ve", "all", "re ",
+ "ri", "ro", "is ", "co", "f t", "are", "ea", ". ", "her", " m", "er ", " p",
+ "es ", "by", "they", "di", "ra", "ic", "not", "s, ", "d t", "at ", "ce", "la",
+ "h ", "ne", "as ", "tio", "on ", "n t", "io", "we", " a ", "om", ", a", "s o",
+ "ur", "li", "ll", "ch", "had", "this", "e t", "g ", "e\r\n", " wh", "ere",
+ " co", "e o", "a ", "us", " d", "ss", "\n\r\n", "\r\n\r", "=\"", " be", " e",
+ "s a", "ma", "one", "t t", "or ", "but", "el", "so", "l ", "e s", "s,", "no",
+ "ter", " wa", "iv", "ho", "e a", " r", "hat", "s t", "ns", "ch ", "wh", "tr",
+ "ut", "/", "have", "ly ", "ta", " ha", " on", "tha", "-", " l", "ati", "en ",
+ "pe", " re", "there", "ass", "si", " fo", "wa", "ec", "our", "who", "its", "z",
+ "fo", "rs", ">", "ot", "un", "<", "im", "th ", "nc", "ate", "><", "ver", "ad",
+ " we", "ly", "ee", " n", "id", " cl", "ac", "il", "</", "rt", " wi", "div",
+ "e, ", " it", "whi", " ma", "ge", "x", "e c", "men", ".com"
};
static int smaz_compress(const char *in, int inlen, char *out, int outlen) {
- unsigned int h1,h2,h3=0;
- int verblen = 0, _outlen = outlen;
- char verb[256], *_out = out;
+ unsigned int h1, h2, h3 = 0;
+ int verblen = 0, _outlen = outlen;
+ char verb[256], *_out = out;
- while(inlen) {
- int j = 7, needed;
- char *flush = NULL;
- const char *slot;
+ while (inlen) {
+ int j = 7, needed;
+ char *flush = NULL;
+ const char *slot;
- h1 = h2 = in[0]<<3;
- if (inlen > 1) h2 += in[1];
- if (inlen > 2) h3 = h2^in[2];
- if (j > inlen) j = inlen;
+ h1 = h2 = in[0] << 3;
+ if (inlen > 1) h2 += in[1];
+ if (inlen > 2) h3 = h2 ^ in[2];
+ if (j > inlen) j = inlen;
- /* Try to lookup substrings into the hash table, starting from the
+ /* Try to lookup substrings into the hash table, starting from the
* longer to the shorter substrings */
- for (; j > 0; j--) {
- switch(j) {
- case 1: slot = Smaz_cb[h1%241]; break;
- case 2: slot = Smaz_cb[h2%241]; break;
- default: slot = Smaz_cb[h3%241]; break;
- }
- while(slot[0]) {
- if (slot[0] == j && memcmp(slot+1,in,j) == 0) {
- /* Match found in the hash table,
+ for (; j > 0; j--) {
+ switch (j) {
+ case 1: slot = Smaz_cb[h1 % 241]; break;
+ case 2: slot = Smaz_cb[h2 % 241]; break;
+ default: slot = Smaz_cb[h3 % 241]; break;
+ }
+ while (slot[0]) {
+ if (slot[0] == j && memcmp(slot + 1, in, j) == 0) {
+ /* Match found in the hash table,
* prepare a verbatim bytes flush if needed */
- if (verblen) {
- needed = (verblen == 1) ? 2 : 2+verblen;
+ if (verblen) {
+ needed = (verblen == 1) ? 2 : 2 + verblen;
+ flush = out;
+ out += needed;
+ outlen -= needed;
+ }
+ /* Emit the byte */
+ if (outlen <= 0) return _outlen + 1;
+ out[0] = slot[slot[0] + 1];
+ out++;
+ outlen--;
+ inlen -= j;
+ in += j;
+ goto out;
+ } else {
+ slot += slot[0] + 2;
+ }
+ }
+ }
+ /* Match not found - add the byte to the verbatim buffer */
+ verb[verblen] = in[0];
+ verblen++;
+ inlen--;
+ in++;
+ out:
+ /* Prepare a flush if we reached the flush length limit, and there
+* is not already a pending flush operation. */
+ if (!flush && (verblen == 256 || (verblen > 0 && inlen == 0))) {
+ needed = (verblen == 1) ? 2 : 2 + verblen;
flush = out;
out += needed;
outlen -= needed;
- }
- /* Emit the byte */
- if (outlen <= 0) return _outlen+1;
- out[0] = slot[slot[0]+1];
- out++;
- outlen--;
- inlen -= j;
- in += j;
- goto out;
- } else {
- slot += slot[0]+2;
+ if (outlen < 0) return _outlen + 1;
+ }
+ /* Perform a verbatim flush if needed */
+ if (flush) {
+ if (verblen == 1) {
+ flush[0] = (signed char)254;
+ flush[1] = verb[0];
+ } else {
+ flush[0] = (signed char)255;
+ flush[1] = (signed char)(verblen - 1);
+ memcpy(flush + 2, verb, verblen);
+ }
+ flush = NULL;
+ verblen = 0;
}
- }
- }
- /* Match not found - add the byte to the verbatim buffer */
- verb[verblen] = in[0];
- verblen++;
- inlen--;
- in++;
-out:
- /* Prepare a flush if we reached the flush length limit, and there
-* is not already a pending flush operation. */
- if (!flush && (verblen == 256 || (verblen > 0 && inlen == 0))) {
- needed = (verblen == 1) ? 2 : 2+verblen;
- flush = out;
- out += needed;
- outlen -= needed;
- if (outlen < 0) return _outlen+1;
- }
- /* Perform a verbatim flush if needed */
- if (flush) {
- if (verblen == 1) {
- flush[0] = (signed char)254;
- flush[1] = verb[0];
- } else {
- flush[0] = (signed char)255;
- flush[1] = (signed char)(verblen-1);
- memcpy(flush+2,verb,verblen);
- }
- flush = NULL;
- verblen = 0;
}
- }
- return out-_out;
+ return out - _out;
}
static int smaz_decompress(const char *in, int inlen, char *out, int outlen) {
- unsigned char *c = (unsigned char*) in;
- char *_out = out;
- int _outlen = outlen;
-
- while(inlen) {
- if (*c == 254) {
- /* Verbatim byte */
- if (outlen < 1) return _outlen+1;
- *out = *(c+1);
- out++;
- outlen--;
- c += 2;
- inlen -= 2;
- } else if (*c == 255) {
- /* Verbatim string */
- int len = (*(c+1))+1;
- if (outlen < len) return _outlen+1;
- memcpy(out,c+2,len);
- out += len;
- outlen -= len;
- c += 2+len;
- inlen -= 2+len;
- } else {
- /* Codebook entry */
- const char *s = Smaz_rcb[*c];
- int len = strlen(s);
-
- if (outlen < len) return _outlen+1;
- memcpy(out,s,len);
- out += len;
- outlen -= len;
- c++;
- inlen--;
+ unsigned char *c = (unsigned char *)in;
+ char *_out = out;
+ int _outlen = outlen;
+
+ while (inlen) {
+ if (*c == 254) {
+ /* Verbatim byte */
+ if (outlen < 1) return _outlen + 1;
+ *out = *(c + 1);
+ out++;
+ outlen--;
+ c += 2;
+ inlen -= 2;
+ } else if (*c == 255) {
+ /* Verbatim string */
+ int len = (*(c + 1)) + 1;
+ if (outlen < len) return _outlen + 1;
+ memcpy(out, c + 2, len);
+ out += len;
+ outlen -= len;
+ c += 2 + len;
+ inlen -= 2 + len;
+ } else {
+ /* Codebook entry */
+ const char *s = Smaz_rcb[*c];
+ int len = strlen(s);
+
+ if (outlen < len) return _outlen + 1;
+ memcpy(out, s, len);
+ out += len;
+ outlen -= len;
+ c++;
+ inlen--;
+ }
}
- }
- return out-_out;
+ return out - _out;
}
-
/////////// END OF SMAZ /////////////
struct _PHashTranslationCmp {
@@ -255,104 +253,100 @@ void PHashTranslation::generate(const Ref<Translation> &p_from) {
List<StringName> keys;
p_from->get_message_list(&keys);
- int size=Math::larger_prime(keys.size());
-
+ int size = Math::larger_prime(keys.size());
- print_line("compressing keys: "+itos(keys.size()));
- Vector< Vector< Pair<int,CharString> > > buckets;
- Vector< Map< uint32_t, int > > table;
- Vector< uint32_t > hfunc_table;
- Vector< _PHashTranslationCmp > compressed;
+ print_line("compressing keys: " + itos(keys.size()));
+ Vector<Vector<Pair<int, CharString> > > buckets;
+ Vector<Map<uint32_t, int> > table;
+ Vector<uint32_t> hfunc_table;
+ Vector<_PHashTranslationCmp> compressed;
table.resize(size);
hfunc_table.resize(size);
buckets.resize(size);
compressed.resize(keys.size());
- int idx=0;
- int total_compression_size=0;
- int total_string_size=0;
+ int idx = 0;
+ int total_compression_size = 0;
+ int total_string_size = 0;
- for(List<StringName>::Element *E=keys.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = keys.front(); E; E = E->next()) {
//hash string
CharString cs = E->get().operator String().utf8();
- uint32_t h = hash(0,cs.get_data());
- Pair<int,CharString> p;
- p.first=idx;
- p.second=cs;
+ uint32_t h = hash(0, cs.get_data());
+ Pair<int, CharString> p;
+ p.first = idx;
+ p.second = cs;
buckets[h % size].push_back(p);
//compress string
CharString src_s = p_from->get_message(E->get()).operator String().utf8();
_PHashTranslationCmp ps;
- ps.orig_len=src_s.size();
- ps.offset=total_compression_size;
+ ps.orig_len = src_s.size();
+ ps.offset = total_compression_size;
- if (ps.orig_len!=0) {
+ if (ps.orig_len != 0) {
CharString dst_s;
dst_s.resize(src_s.size());
- int ret = smaz_compress(src_s.get_data(),src_s.size(),&dst_s[0],src_s.size());
- if (ret>=src_s.size()) {
+ int ret = smaz_compress(src_s.get_data(), src_s.size(), &dst_s[0], src_s.size());
+ if (ret >= src_s.size()) {
//if compressed is larger than original, just use original
- ps.orig_len=src_s.size();
- ps.compressed=src_s;
+ ps.orig_len = src_s.size();
+ ps.compressed = src_s;
} else {
dst_s.resize(ret);
//ps.orig_len=;
- ps.compressed=dst_s;
+ ps.compressed = dst_s;
}
} else {
- ps.orig_len=1;
+ ps.orig_len = 1;
ps.compressed.resize(1);
- ps.compressed[0]=0;
+ ps.compressed[0] = 0;
}
-
- compressed[idx]=ps;
- total_compression_size+=ps.compressed.size();
- total_string_size+=src_s.size();
+ compressed[idx] = ps;
+ total_compression_size += ps.compressed.size();
+ total_string_size += src_s.size();
idx++;
}
- int bucket_table_size=0;
- print_line("total compressed string size: "+itos(total_compression_size)+" ("+itos(total_string_size)+" uncompressed).");
+ int bucket_table_size = 0;
+ print_line("total compressed string size: " + itos(total_compression_size) + " (" + itos(total_string_size) + " uncompressed).");
- for(int i=0;i<size;i++) {
+ for (int i = 0; i < size; i++) {
- Vector< Pair<int,CharString> > &b = buckets[i];
- Map< uint32_t, int > &t=table[i];
+ Vector<Pair<int, CharString> > &b = buckets[i];
+ Map<uint32_t, int> &t = table[i];
- if (b.size()==0)
+ if (b.size() == 0)
continue;
//print_line("bucket: "+itos(i)+" - elements: "+itos(b.size()));
int d = 1;
- int item =0;
+ int item = 0;
- while(item < b.size()) {
+ while (item < b.size()) {
- uint32_t slot = hash(d,b[item].second.get_data());
+ uint32_t slot = hash(d, b[item].second.get_data());
if (t.has(slot)) {
- item=0;
+ item = 0;
d++;
t.clear();
} else {
- t[slot]=b[item].first;
+ t[slot] = b[item].first;
item++;
}
}
- hfunc_table[i]=d;
- bucket_table_size+=2+b.size()*4;
-
+ hfunc_table[i] = d;
+ bucket_table_size += 2 + b.size() * 4;
}
-
- print_line("bucket table size: "+itos(bucket_table_size*4));
- print_line("hash table size: "+itos(size*4));
+ print_line("bucket table size: " + itos(bucket_table_size * 4));
+ print_line("hash table size: " + itos(size * 4));
hash_table.resize(size);
bucket_table.resize(bucket_table_size);
@@ -360,136 +354,130 @@ void PHashTranslation::generate(const Ref<Translation> &p_from) {
PoolVector<int>::Write htwb = hash_table.write();
PoolVector<int>::Write btwb = bucket_table.write();
- uint32_t *htw = (uint32_t*)&htwb[0];
- uint32_t *btw = (uint32_t*)&btwb[0];
+ uint32_t *htw = (uint32_t *)&htwb[0];
+ uint32_t *btw = (uint32_t *)&btwb[0];
- int btindex=0;
- int collisions=0;
+ int btindex = 0;
+ int collisions = 0;
- for(int i=0;i<size;i++) {
+ for (int i = 0; i < size; i++) {
- Map< uint32_t, int > &t=table[i];
- if (t.size()==0) {
- htw[i]=0xFFFFFFFF; //nothing
+ Map<uint32_t, int> &t = table[i];
+ if (t.size() == 0) {
+ htw[i] = 0xFFFFFFFF; //nothing
continue;
- } else if (t.size()>1) {
- collisions+=t.size()-1;
+ } else if (t.size() > 1) {
+ collisions += t.size() - 1;
}
- htw[i]=btindex;
- btw[btindex++]=t.size();
- btw[btindex++]=hfunc_table[i];
+ htw[i] = btindex;
+ btw[btindex++] = t.size();
+ btw[btindex++] = hfunc_table[i];
- for( Map< uint32_t, int >::Element *E=t.front();E;E=E->next()) {
+ for (Map<uint32_t, int>::Element *E = t.front(); E; E = E->next()) {
- btw[btindex++]=E->key();
- btw[btindex++]=compressed[E->get()].offset;
- btw[btindex++]=compressed[E->get()].compressed.size();
- btw[btindex++]=compressed[E->get()].orig_len;
+ btw[btindex++] = E->key();
+ btw[btindex++] = compressed[E->get()].offset;
+ btw[btindex++] = compressed[E->get()].compressed.size();
+ btw[btindex++] = compressed[E->get()].orig_len;
}
-
}
- print_line("total collisions: "+itos(collisions));
+ print_line("total collisions: " + itos(collisions));
strings.resize(total_compression_size);
PoolVector<uint8_t>::Write cw = strings.write();
- for(int i=0;i<compressed.size();i++) {
- memcpy(&cw[compressed[i].offset],compressed[i].compressed.get_data(),compressed[i].compressed.size());
+ for (int i = 0; i < compressed.size(); i++) {
+ memcpy(&cw[compressed[i].offset], compressed[i].compressed.get_data(), compressed[i].compressed.size());
}
-
- ERR_FAIL_COND(btindex!=bucket_table_size);
+ ERR_FAIL_COND(btindex != bucket_table_size);
set_locale(p_from->get_locale());
#endif
}
-bool PHashTranslation::_set(const StringName& p_name, const Variant& p_value) {
+bool PHashTranslation::_set(const StringName &p_name, const Variant &p_value) {
String name = p_name.operator String();
- if (name=="hash_table") {
- hash_table=p_value;
+ if (name == "hash_table") {
+ hash_table = p_value;
//print_line("translation: loaded hash table of size: "+itos(hash_table.size()));
- } else if (name=="bucket_table") {
- bucket_table=p_value;
+ } else if (name == "bucket_table") {
+ bucket_table = p_value;
//print_line("translation: loaded bucket table of size: "+itos(bucket_table.size()));
- } else if (name=="strings") {
- strings=p_value;
+ } else if (name == "strings") {
+ strings = p_value;
//print_line("translation: loaded string table of size: "+itos(strings.size()));
- } else if (name=="load_from") {
+ } else if (name == "load_from") {
//print_line("generating");
generate(p_value);
} else
return false;
return true;
-
}
-bool PHashTranslation::_get(const StringName& p_name,Variant &r_ret) const{
+bool PHashTranslation::_get(const StringName &p_name, Variant &r_ret) const {
String name = p_name.operator String();
- if (name=="hash_table")
- r_ret=hash_table;
- else if (name=="bucket_table")
- r_ret=bucket_table;
- else if (name=="strings")
- r_ret=strings;
+ if (name == "hash_table")
+ r_ret = hash_table;
+ else if (name == "bucket_table")
+ r_ret = bucket_table;
+ else if (name == "strings")
+ r_ret = strings;
else
return false;
return true;
-
}
-StringName PHashTranslation::get_message(const StringName& p_src_text) const {
+StringName PHashTranslation::get_message(const StringName &p_src_text) const {
int htsize = hash_table.size();
- if (htsize==0)
+ if (htsize == 0)
return StringName();
CharString str = p_src_text.operator String().utf8();
- uint32_t h = hash(0,str.get_data());
+ uint32_t h = hash(0, str.get_data());
-
- PoolVector<int>::Read htr = hash_table.read();
- const uint32_t *htptr = (const uint32_t*)&htr[0];
- PoolVector<int>::Read btr = bucket_table.read();
- const uint32_t *btptr = (const uint32_t*)&btr[0];
+ PoolVector<int>::Read htr = hash_table.read();
+ const uint32_t *htptr = (const uint32_t *)&htr[0];
+ PoolVector<int>::Read btr = bucket_table.read();
+ const uint32_t *btptr = (const uint32_t *)&btr[0];
PoolVector<uint8_t>::Read sr = strings.read();
- const char *sptr= (const char*)&sr[0];
+ const char *sptr = (const char *)&sr[0];
- uint32_t p = htptr[ h % htsize];
+ uint32_t p = htptr[h % htsize];
//print_line("String: "+p_src_text.operator String());
//print_line("Hash: "+itos(p));
- if (p==0xFFFFFFFF) {
+ if (p == 0xFFFFFFFF) {
//print_line("GETMSG: Nothing!");
return StringName(); //nothing
}
- const Bucket &bucket = *(const Bucket*)&btptr[p];
+ const Bucket &bucket = *(const Bucket *)&btptr[p];
- h = hash(bucket.func,str.get_data());
+ h = hash(bucket.func, str.get_data());
- int idx=-1;
+ int idx = -1;
- for(int i=0;i<bucket.size;i++) {
+ for (int i = 0; i < bucket.size; i++) {
- if (bucket.elem[i].key==h) {
+ if (bucket.elem[i].key == h) {
- idx=i;
+ idx = i;
break;
}
-
}
//print_line("bucket pos: "+itos(idx));
- if (idx==-1) {
+ if (idx == -1) {
//print_line("GETMSG: Not in Bucket!");
return StringName();
}
@@ -497,7 +485,7 @@ StringName PHashTranslation::get_message(const StringName& p_src_text) const {
if (bucket.elem[idx].comp_size == bucket.elem[idx].uncomp_size) {
String rstr;
- rstr.parse_utf8(&sptr[ bucket.elem[idx].str_offset ], bucket.elem[idx].uncomp_size );
+ rstr.parse_utf8(&sptr[bucket.elem[idx].str_offset], bucket.elem[idx].uncomp_size);
//print_line("Uncompressed, size: "+itos(bucket.elem[idx].comp_size));
//print_line("Return: "+rstr);
@@ -505,31 +493,27 @@ StringName PHashTranslation::get_message(const StringName& p_src_text) const {
} else {
CharString uncomp;
- uncomp.resize( bucket.elem[idx].uncomp_size+1 );
- smaz_decompress(&sptr[ bucket.elem[idx].str_offset ], bucket.elem[idx].comp_size,uncomp.ptr(),bucket.elem[idx].uncomp_size );
+ uncomp.resize(bucket.elem[idx].uncomp_size + 1);
+ smaz_decompress(&sptr[bucket.elem[idx].str_offset], bucket.elem[idx].comp_size, uncomp.ptr(), bucket.elem[idx].uncomp_size);
String rstr;
rstr.parse_utf8(uncomp.get_data());
//print_line("Compressed, size: "+itos(bucket.elem[idx].comp_size));
//print_line("Return: "+rstr);
return rstr;
}
-
}
+void PHashTranslation::_get_property_list(List<PropertyInfo> *p_list) const {
-void PHashTranslation::_get_property_list( List<PropertyInfo> *p_list) const{
-
- p_list->push_back( PropertyInfo(Variant::POOL_INT_ARRAY, "hash_table"));
- p_list->push_back( PropertyInfo(Variant::POOL_INT_ARRAY, "bucket_table"));
- p_list->push_back( PropertyInfo(Variant::POOL_BYTE_ARRAY, "strings"));
- p_list->push_back( PropertyInfo(Variant::OBJECT, "load_from",PROPERTY_HINT_RESOURCE_TYPE,"Translation",PROPERTY_USAGE_EDITOR));
-
+ p_list->push_back(PropertyInfo(Variant::POOL_INT_ARRAY, "hash_table"));
+ p_list->push_back(PropertyInfo(Variant::POOL_INT_ARRAY, "bucket_table"));
+ p_list->push_back(PropertyInfo(Variant::POOL_BYTE_ARRAY, "strings"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "load_from", PROPERTY_HINT_RESOURCE_TYPE, "Translation", PROPERTY_USAGE_EDITOR));
}
void PHashTranslation::_bind_methods() {
- ClassDB::bind_method(D_METHOD("generate","from:Translation"),&PHashTranslation::generate);
+ ClassDB::bind_method(D_METHOD("generate", "from:Translation"), &PHashTranslation::generate);
}
-PHashTranslation::PHashTranslation()
-{
+PHashTranslation::PHashTranslation() {
}
diff --git a/core/compressed_translation.h b/core/compressed_translation.h
index cb1e084051..abaa4ebe2c 100644
--- a/core/compressed_translation.h
+++ b/core/compressed_translation.h
@@ -33,8 +33,7 @@
class PHashTranslation : public Translation {
- GDCLASS(PHashTranslation,Translation);
-
+ GDCLASS(PHashTranslation, Translation);
//this translation uses a sort of modified perfect hash algorithm
//it requieres hashing strings twice and then does a binary search,
@@ -46,7 +45,6 @@ class PHashTranslation : public Translation {
PoolVector<int> bucket_table;
PoolVector<uint8_t> strings;
-
struct Bucket {
int size;
@@ -63,11 +61,11 @@ class PHashTranslation : public Translation {
Elem elem[1];
};
- _FORCE_INLINE_ uint32_t hash( uint32_t d, const char *p_str ) const {
+ _FORCE_INLINE_ uint32_t hash(uint32_t d, const char *p_str) const {
- if (d==0)
- d=0x1000193;
- while(*p_str) {
+ if (d == 0)
+ d = 0x1000193;
+ while (*p_str) {
d = (d * 0x1000193) ^ uint32_t(*p_str);
p_str++;
@@ -75,16 +73,15 @@ class PHashTranslation : public Translation {
return d;
}
-protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
- virtual StringName get_message(const StringName& p_src_text) const; //overridable for other implementations
+ virtual StringName get_message(const StringName &p_src_text) const; //overridable for other implementations
void generate(const Ref<Translation> &p_from);
PHashTranslation();
diff --git a/core/core_string_names.cpp b/core/core_string_names.cpp
index f8c6f47797..cbb3060f13 100644
--- a/core/core_string_names.cpp
+++ b/core/core_string_names.cpp
@@ -28,21 +28,19 @@
/*************************************************************************/
#include "core_string_names.h"
-CoreStringNames* CoreStringNames::singleton=NULL;
+CoreStringNames *CoreStringNames::singleton = NULL;
CoreStringNames::CoreStringNames() {
- _free=StaticCString::create("free");
- changed=StaticCString::create("changed");
- _meta=StaticCString::create("__meta__");
- _script=StaticCString::create("script");
- script_changed=StaticCString::create("script_changed");
- ___pdcdata=StaticCString::create("___pdcdata");
- __getvar=StaticCString::create("__getvar");
- _iter_init=StaticCString::create("_iter_init");
- _iter_next=StaticCString::create("_iter_next");
- _iter_get=StaticCString::create("_iter_get");
- get_rid=StaticCString::create("get_rid");
-
-
+ _free = StaticCString::create("free");
+ changed = StaticCString::create("changed");
+ _meta = StaticCString::create("__meta__");
+ _script = StaticCString::create("script");
+ script_changed = StaticCString::create("script_changed");
+ ___pdcdata = StaticCString::create("___pdcdata");
+ __getvar = StaticCString::create("__getvar");
+ _iter_init = StaticCString::create("_iter_init");
+ _iter_next = StaticCString::create("_iter_next");
+ _iter_get = StaticCString::create("_iter_get");
+ get_rid = StaticCString::create("get_rid");
}
diff --git a/core/core_string_names.h b/core/core_string_names.h
index 7d3754786c..f6542be290 100644
--- a/core/core_string_names.h
+++ b/core/core_string_names.h
@@ -33,18 +33,21 @@
class CoreStringNames {
-friend void register_core_types();
-friend void unregister_core_types();
+ friend void register_core_types();
+ friend void unregister_core_types();
- static CoreStringNames* singleton;
+ static CoreStringNames *singleton;
static void create() { singleton = memnew(CoreStringNames); }
- static void free() { memdelete( singleton); singleton=NULL; }
+ static void free() {
+ memdelete(singleton);
+ singleton = NULL;
+ }
CoreStringNames();
-public:
- _FORCE_INLINE_ static CoreStringNames* get_singleton() { return singleton; }
+public:
+ _FORCE_INLINE_ static CoreStringNames *get_singleton() { return singleton; }
StringName _free;
StringName changed;
@@ -57,7 +60,6 @@ public:
StringName _iter_next;
StringName _iter_get;
StringName get_rid;
-
};
#endif // SCENE_STRING_NAMES_H
diff --git a/core/dictionary.cpp b/core/dictionary.cpp
index 1176b9be3b..3663bb1a4f 100644
--- a/core/dictionary.cpp
+++ b/core/dictionary.cpp
@@ -33,13 +33,9 @@
struct _DictionaryVariantHash {
- static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); }
+ static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); }
};
-
-
-
-
struct DictionaryPrivate {
struct Data {
@@ -48,171 +44,156 @@ struct DictionaryPrivate {
};
SafeRefCount refcount;
- HashMap<Variant,Data,_DictionaryVariantHash> variant_map;
+ HashMap<Variant, Data, _DictionaryVariantHash> variant_map;
int counter;
-
};
struct DictionaryPrivateSort {
- bool operator()(const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *A,const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *B) const {
+ bool operator()(const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *A, const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *B) const {
return A->data.order < B->data.order;
}
};
-void Dictionary::get_key_list( List<Variant> *p_keys) const {
+void Dictionary::get_key_list(List<Variant> *p_keys) const {
if (_p->variant_map.empty())
return;
int count = _p->variant_map.size();
- const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair**)alloca( count * sizeof(HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *) );
+ const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **)alloca(count * sizeof(HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *));
_p->variant_map.get_key_value_ptr_array(pairs);
- SortArray<const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair*,DictionaryPrivateSort> sort;
- sort.sort(pairs,count);
+ SortArray<const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *, DictionaryPrivateSort> sort;
+ sort.sort(pairs, count);
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
p_keys->push_back(pairs[i]->key);
}
-
}
-Variant& Dictionary::operator[](const Variant& p_key) {
-
+Variant &Dictionary::operator[](const Variant &p_key) {
- DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key);
+ DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key);
if (!v) {
DictionaryPrivate::Data d;
- d.order=_p->counter++;
- _p->variant_map[p_key]=d;
- v =_p->variant_map.getptr(p_key);
-
+ d.order = _p->counter++;
+ _p->variant_map[p_key] = d;
+ v = _p->variant_map.getptr(p_key);
}
return v->variant;
}
-const Variant& Dictionary::operator[](const Variant& p_key) const {
+const Variant &Dictionary::operator[](const Variant &p_key) const {
return _p->variant_map[p_key].variant;
-
}
-const Variant* Dictionary::getptr(const Variant& p_key) const {
+const Variant *Dictionary::getptr(const Variant &p_key) const {
- const DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key);
+ const DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key);
if (!v)
return NULL;
else
return &v->variant;
}
-Variant* Dictionary::getptr(const Variant& p_key) {
+Variant *Dictionary::getptr(const Variant &p_key) {
- DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key);
+ DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key);
if (!v)
return NULL;
else
return &v->variant;
-
-
}
-Variant Dictionary::get_valid(const Variant& p_key) const {
+Variant Dictionary::get_valid(const Variant &p_key) const {
- DictionaryPrivate::Data *v =_p->variant_map.getptr(p_key);
+ DictionaryPrivate::Data *v = _p->variant_map.getptr(p_key);
if (!v)
return Variant();
else
return v->variant;
}
-
int Dictionary::size() const {
return _p->variant_map.size();
-
}
bool Dictionary::empty() const {
return !_p->variant_map.size();
}
-bool Dictionary::has(const Variant& p_key) const {
+bool Dictionary::has(const Variant &p_key) const {
return _p->variant_map.has(p_key);
}
-bool Dictionary::has_all(const Array& p_keys) const {
- for (int i=0;i<p_keys.size();i++) {
- if( !has(p_keys[i]) ) {
+bool Dictionary::has_all(const Array &p_keys) const {
+ for (int i = 0; i < p_keys.size(); i++) {
+ if (!has(p_keys[i])) {
return false;
}
}
return true;
}
-void Dictionary::erase(const Variant& p_key) {
-
+void Dictionary::erase(const Variant &p_key) {
_p->variant_map.erase(p_key);
}
-bool Dictionary::operator==(const Dictionary& p_dictionary) const {
+bool Dictionary::operator==(const Dictionary &p_dictionary) const {
- return _p==p_dictionary._p;
+ return _p == p_dictionary._p;
}
-void Dictionary::_ref(const Dictionary& p_from) const {
+void Dictionary::_ref(const Dictionary &p_from) const {
//make a copy first (thread safe)
if (!p_from._p->refcount.ref())
return; // couldn't copy
//if this is the same, unreference the other one
- if (p_from._p==_p) {
+ if (p_from._p == _p) {
_p->refcount.unref();
return;
}
if (_p)
_unref();
- _p=p_from._p;
-
+ _p = p_from._p;
}
void Dictionary::clear() {
_p->variant_map.clear();
- _p->counter=0;
+ _p->counter = 0;
}
-
void Dictionary::_unref() const {
ERR_FAIL_COND(!_p);
if (_p->refcount.unref()) {
memdelete(_p);
}
- _p=NULL;
-
+ _p = NULL;
}
uint32_t Dictionary::hash() const {
- uint32_t h=hash_djb2_one_32(Variant::DICTIONARY);
+ uint32_t h = hash_djb2_one_32(Variant::DICTIONARY);
List<Variant> keys;
get_key_list(&keys);
- for (List<Variant>::Element *E=keys.front();E;E=E->next()) {
-
- h = hash_djb2_one_32( E->get().hash(), h);
- h = hash_djb2_one_32( operator[](E->get()).hash(), h);
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
+ h = hash_djb2_one_32(E->get().hash(), h);
+ h = hash_djb2_one_32(operator[](E->get()).hash(), h);
}
-
return h;
}
@@ -220,13 +201,12 @@ Array Dictionary::keys() const {
Array karr;
karr.resize(size());
- const Variant *K=NULL;
- int idx=0;
- while((K=next(K))) {
- karr[idx++]=(*K);
+ const Variant *K = NULL;
+ int idx = 0;
+ while ((K = next(K))) {
+ karr[idx++] = (*K);
}
return karr;
-
}
Array Dictionary::values() const {
@@ -237,20 +217,20 @@ Array Dictionary::values() const {
return varr;
int count = _p->variant_map.size();
- const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair**)alloca( count * sizeof(HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair *) );
+ const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **pairs = (const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair **)alloca(count * sizeof(HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *));
_p->variant_map.get_key_value_ptr_array(pairs);
- SortArray<const HashMap<Variant,DictionaryPrivate::Data,_DictionaryVariantHash>::Pair*,DictionaryPrivateSort> sort;
- sort.sort(pairs,count);
+ SortArray<const HashMap<Variant, DictionaryPrivate::Data, _DictionaryVariantHash>::Pair *, DictionaryPrivateSort> sort;
+ sort.sort(pairs, count);
- for(int i=0;i<count;i++) {
- varr[i]=pairs[i]->data.variant;
+ for (int i = 0; i < count; i++) {
+ varr[i] = pairs[i]->data.variant;
}
return varr;
}
-const Variant* Dictionary::next(const Variant* p_key) const {
+const Variant *Dictionary::next(const Variant *p_key) const {
return _p->variant_map.next(p_key);
}
@@ -262,34 +242,28 @@ Dictionary Dictionary::copy() const {
List<Variant> keys;
get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
- n[E->get()]=operator[](E->get());
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
+ n[E->get()] = operator[](E->get());
}
return n;
}
-
-void Dictionary::operator=(const Dictionary& p_dictionary) {
+void Dictionary::operator=(const Dictionary &p_dictionary) {
_ref(p_dictionary);
}
-
-
-Dictionary::Dictionary(const Dictionary& p_from) {
- _p=NULL;
+Dictionary::Dictionary(const Dictionary &p_from) {
+ _p = NULL;
_ref(p_from);
}
-
Dictionary::Dictionary() {
- _p=memnew( DictionaryPrivate );
+ _p = memnew(DictionaryPrivate);
_p->refcount.init();
- _p->counter=0;
-
-
+ _p->counter = 0;
}
Dictionary::~Dictionary() {
diff --git a/core/dictionary.h b/core/dictionary.h
index a1bf291d6b..588e33a95f 100644
--- a/core/dictionary.h
+++ b/core/dictionary.h
@@ -29,57 +29,53 @@
#ifndef DICTIONARY_H
#define DICTIONARY_H
-
-#include "list.h"
#include "array.h"
+#include "list.h"
#include "ustring.h"
class Variant;
-
struct DictionaryPrivate;
-
class Dictionary {
mutable DictionaryPrivate *_p;
-
- void _ref(const Dictionary& p_from) const;
+ void _ref(const Dictionary &p_from) const;
void _unref() const;
-public:
- void get_key_list( List<Variant> *p_keys) const;
+public:
+ void get_key_list(List<Variant> *p_keys) const;
- Variant& operator[](const Variant& p_key);
- const Variant& operator[](const Variant& p_key) const;
+ Variant &operator[](const Variant &p_key);
+ const Variant &operator[](const Variant &p_key) const;
- const Variant* getptr(const Variant& p_key) const;
- Variant* getptr(const Variant& p_key);
+ const Variant *getptr(const Variant &p_key) const;
+ Variant *getptr(const Variant &p_key);
- Variant get_valid(const Variant& p_key) const;
+ Variant get_valid(const Variant &p_key) const;
int size() const;
bool empty() const;
void clear();
- bool has(const Variant& p_key) const;
- bool has_all(const Array& p_keys) const;
+ bool has(const Variant &p_key) const;
+ bool has_all(const Array &p_keys) const;
- void erase(const Variant& p_key);
+ void erase(const Variant &p_key);
- bool operator==(const Dictionary& p_dictionary) const;
+ bool operator==(const Dictionary &p_dictionary) const;
uint32_t hash() const;
- void operator=(const Dictionary& p_dictionary);
+ void operator=(const Dictionary &p_dictionary);
- const Variant* next(const Variant* p_key=NULL) const;
+ const Variant *next(const Variant *p_key = NULL) const;
Array keys() const;
Array values() const;
Dictionary copy() const;
- Dictionary(const Dictionary& p_from);
+ Dictionary(const Dictionary &p_from);
Dictionary();
~Dictionary();
};
diff --git a/core/dvector.cpp b/core/dvector.cpp
index f6b5a5fcbf..5930a1220b 100644
--- a/core/dvector.cpp
+++ b/core/dvector.cpp
@@ -28,38 +28,35 @@
/*************************************************************************/
#include "dvector.h"
-Mutex* dvector_lock=NULL;
+Mutex *dvector_lock = NULL;
-PoolAllocator *MemoryPool::memory_pool=NULL;
-uint8_t *MemoryPool::pool_memory=NULL;
-size_t *MemoryPool::pool_size=NULL;
+PoolAllocator *MemoryPool::memory_pool = NULL;
+uint8_t *MemoryPool::pool_memory = NULL;
+size_t *MemoryPool::pool_size = NULL;
+MemoryPool::Alloc *MemoryPool::allocs = NULL;
+MemoryPool::Alloc *MemoryPool::free_list = NULL;
+uint32_t MemoryPool::alloc_count = 0;
+uint32_t MemoryPool::allocs_used = 0;
+Mutex *MemoryPool::alloc_mutex = NULL;
-MemoryPool::Alloc *MemoryPool::allocs=NULL;
-MemoryPool::Alloc *MemoryPool::free_list=NULL;
-uint32_t MemoryPool::alloc_count=0;
-uint32_t MemoryPool::allocs_used=0;
-Mutex *MemoryPool::alloc_mutex=NULL;
-
-size_t MemoryPool::total_memory=0;
-size_t MemoryPool::max_memory=0;
-
+size_t MemoryPool::total_memory = 0;
+size_t MemoryPool::max_memory = 0;
void MemoryPool::setup(uint32_t p_max_allocs) {
- allocs = memnew_arr( Alloc, p_max_allocs);
+ allocs = memnew_arr(Alloc, p_max_allocs);
alloc_count = p_max_allocs;
- allocs_used=0;
+ allocs_used = 0;
- for(uint32_t i=0;i<alloc_count-1;i++) {
+ for (uint32_t i = 0; i < alloc_count - 1; i++) {
- allocs[i].free_list=&allocs[i+1];
+ allocs[i].free_list = &allocs[i + 1];
}
- free_list=&allocs[0];
+ free_list = &allocs[0];
alloc_mutex = Mutex::create();
-
}
void MemoryPool::cleanup() {
@@ -68,6 +65,5 @@ void MemoryPool::cleanup() {
memdelete(alloc_mutex);
ERR_EXPLAINC("There are still MemoryPool allocs in use at exit!");
- ERR_FAIL_COND(allocs_used>0);
-
+ ERR_FAIL_COND(allocs_used > 0);
}
diff --git a/core/dvector.h b/core/dvector.h
index 456be41289..3f4318216d 100644
--- a/core/dvector.h
+++ b/core/dvector.h
@@ -29,11 +29,11 @@
#ifndef DVECTOR_H
#define DVECTOR_H
-#include "os/memory.h"
#include "os/copymem.h"
+#include "os/memory.h"
+#include "os/rw_lock.h"
#include "pool_allocator.h"
#include "safe_refcount.h"
-#include "os/rw_lock.h"
#include "ustring.h"
struct MemoryPool {
@@ -44,7 +44,6 @@ struct MemoryPool {
static uint8_t *pool_memory;
static size_t *pool_size;
-
struct Alloc {
SafeRefCount refcount;
@@ -55,10 +54,15 @@ struct MemoryPool {
Alloc *free_list;
- Alloc() { mem=NULL; lock=0; pool_id=POOL_ALLOCATOR_INVALID_ID; size=0; free_list=NULL; }
+ Alloc() {
+ mem = NULL;
+ lock = 0;
+ pool_id = POOL_ALLOCATOR_INVALID_ID;
+ size = 0;
+ free_list = NULL;
+ }
};
-
static Alloc *allocs;
static Alloc *free_list;
static uint32_t alloc_count;
@@ -67,39 +71,33 @@ struct MemoryPool {
static size_t total_memory;
static size_t max_memory;
-
- static void setup(uint32_t p_max_allocs=(1<<16));
+ static void setup(uint32_t p_max_allocs = (1 << 16));
static void cleanup();
};
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-template<class T>
+template <class T>
class PoolVector {
MemoryPool::Alloc *alloc;
-
void _copy_on_write() {
-
if (!alloc)
return;
-// ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all
+ // ERR_FAIL_COND(alloc->lock>0); should not be illegal to lock this for copy on write, as it's a copy on write after all
- if (alloc->refcount.get()==1)
+ if (alloc->refcount.get() == 1)
return; //nothing to do
-
//must allocate something
MemoryPool::alloc_mutex->lock();
- if (MemoryPool::allocs_used==MemoryPool::alloc_count) {
+ if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex->unlock();
ERR_EXPLAINC("All memory pool allocations are in use, can't COW.");
ERR_FAIL();
@@ -114,26 +112,24 @@ class PoolVector {
MemoryPool::allocs_used++;
//copy the alloc data
- alloc->size=old_alloc->size;
+ alloc->size = old_alloc->size;
alloc->refcount.init();
- alloc->pool_id=POOL_ALLOCATOR_INVALID_ID;
- alloc->lock=0;
+ alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
+ alloc->lock = 0;
#ifdef DEBUG_ENABLED
- MemoryPool::total_memory+=alloc->size;
- if (MemoryPool::total_memory>MemoryPool::max_memory) {
- MemoryPool::max_memory=MemoryPool::total_memory;
+ MemoryPool::total_memory += alloc->size;
+ if (MemoryPool::total_memory > MemoryPool::max_memory) {
+ MemoryPool::max_memory = MemoryPool::total_memory;
}
#endif
MemoryPool::alloc_mutex->unlock();
-
if (MemoryPool::memory_pool) {
-
} else {
- alloc->mem = memalloc( alloc->size );
+ alloc->mem = memalloc(alloc->size);
}
{
@@ -142,21 +138,20 @@ class PoolVector {
Read r;
r._ref(old_alloc);
- int cur_elements = alloc->size/sizeof(T);
- T*dst = (T*)w.ptr();
- const T*src = (const T*)r.ptr();
- for(int i=0;i<cur_elements;i++) {
- memnew_placement(&dst[i],T(src[i]));
+ int cur_elements = alloc->size / sizeof(T);
+ T *dst = (T *)w.ptr();
+ const T *src = (const T *)r.ptr();
+ for (int i = 0; i < cur_elements; i++) {
+ memnew_placement(&dst[i], T(src[i]));
}
}
-
- if (old_alloc->refcount.unref()==true) {
- //this should never happen but..
+ if (old_alloc->refcount.unref() == true) {
+//this should never happen but..
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex->lock();
- MemoryPool::total_memory-=old_alloc->size;
+ MemoryPool::total_memory -= old_alloc->size;
MemoryPool::alloc_mutex->unlock();
#endif
@@ -164,12 +159,11 @@ class PoolVector {
Write w;
w._ref(old_alloc);
- int cur_elements = old_alloc->size/sizeof(T);
- T*elems = (T*)w.ptr();
- for(int i=0;i<cur_elements;i++) {
+ int cur_elements = old_alloc->size / sizeof(T);
+ T *elems = (T *)w.ptr();
+ for (int i = 0; i < cur_elements; i++) {
elems[i].~T();
}
-
}
if (MemoryPool::memory_pool) {
@@ -178,26 +172,22 @@ class PoolVector {
//if some resize
} else {
-
- memfree( old_alloc->mem );
- old_alloc->mem=NULL;
- old_alloc->size=0;
-
+ memfree(old_alloc->mem);
+ old_alloc->mem = NULL;
+ old_alloc->size = 0;
MemoryPool::alloc_mutex->lock();
- old_alloc->free_list=MemoryPool::free_list;
- MemoryPool::free_list=old_alloc;
+ old_alloc->free_list = MemoryPool::free_list;
+ MemoryPool::free_list = old_alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex->unlock();
}
-
}
-
}
- void _reference( const PoolVector& p_dvector ) {
+ void _reference(const PoolVector &p_dvector) {
- if (alloc==p_dvector.alloc)
+ if (alloc == p_dvector.alloc)
return;
_unreference();
@@ -207,108 +197,98 @@ class PoolVector {
}
if (p_dvector.alloc->refcount.ref()) {
- alloc=p_dvector.alloc;
+ alloc = p_dvector.alloc;
}
-
}
-
void _unreference() {
if (!alloc)
return;
- if (alloc->refcount.unref()==false) {
- alloc=NULL;
+ if (alloc->refcount.unref() == false) {
+ alloc = NULL;
return;
}
//must be disposed!
{
- int cur_elements = alloc->size/sizeof(T);
+ int cur_elements = alloc->size / sizeof(T);
Write w = write();
- for (int i=0;i<cur_elements;i++) {
+ for (int i = 0; i < cur_elements; i++) {
w[i].~T();
}
-
}
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex->lock();
- MemoryPool::total_memory-=alloc->size;
+ MemoryPool::total_memory -= alloc->size;
MemoryPool::alloc_mutex->unlock();
#endif
-
if (MemoryPool::memory_pool) {
//resize memory pool
//if none, create
//if some resize
} else {
- memfree( alloc->mem );
- alloc->mem=NULL;
- alloc->size=0;
-
+ memfree(alloc->mem);
+ alloc->mem = NULL;
+ alloc->size = 0;
MemoryPool::alloc_mutex->lock();
- alloc->free_list=MemoryPool::free_list;
- MemoryPool::free_list=alloc;
+ alloc->free_list = MemoryPool::free_list;
+ MemoryPool::free_list = alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex->unlock();
-
}
- alloc=NULL;
+ alloc = NULL;
}
public:
-
class Access {
- friend class PoolVector;
+ friend class PoolVector;
+
protected:
MemoryPool::Alloc *alloc;
- T * mem;
+ T *mem;
_FORCE_INLINE_ void _ref(MemoryPool::Alloc *p_alloc) {
- alloc=p_alloc;
+ alloc = p_alloc;
if (alloc) {
- if (atomic_increment(&alloc->lock)==1) {
+ if (atomic_increment(&alloc->lock) == 1) {
if (MemoryPool::memory_pool) {
//lock it and get mem
}
}
- mem = (T*)alloc->mem;
+ mem = (T *)alloc->mem;
}
}
_FORCE_INLINE_ void _unref() {
-
if (alloc) {
- if (atomic_decrement(&alloc->lock)==0) {
+ if (atomic_decrement(&alloc->lock) == 0) {
if (MemoryPool::memory_pool) {
//put mem back
}
}
mem = NULL;
- alloc=NULL;
+ alloc = NULL;
}
-
-
}
Access() {
- alloc=NULL;
- mem=NULL;
+ alloc = NULL;
+ mem = NULL;
}
-
public:
virtual ~Access() {
_unref();
@@ -317,48 +297,42 @@ public:
class Read : public Access {
public:
-
- _FORCE_INLINE_ const T& operator[](int p_index) const { return this->mem[p_index]; }
+ _FORCE_INLINE_ const T &operator[](int p_index) const { return this->mem[p_index]; }
_FORCE_INLINE_ const T *ptr() const { return this->mem; }
- void operator=(const Read& p_read) {
- if (this->alloc==p_read.alloc)
+ void operator=(const Read &p_read) {
+ if (this->alloc == p_read.alloc)
return;
this->_unref();
this->_ref(p_read.alloc);
}
- Read(const Read& p_read) {
+ Read(const Read &p_read) {
this->_ref(p_read.alloc);
}
Read() {}
-
-
};
class Write : public Access {
public:
-
- _FORCE_INLINE_ T& operator[](int p_index) const { return this->mem[p_index]; }
+ _FORCE_INLINE_ T &operator[](int p_index) const { return this->mem[p_index]; }
_FORCE_INLINE_ T *ptr() const { return this->mem; }
- void operator=(const Write& p_read) {
- if (this->alloc==p_read.alloc)
+ void operator=(const Write &p_read) {
+ if (this->alloc == p_read.alloc)
return;
this->_unref();
this->_ref(p_read.alloc);
}
- Write(const Write& p_read) {
+ Write(const Write &p_read) {
this->_ref(p_read.alloc);
}
Write() {}
-
};
-
Read read() const {
Read r;
@@ -366,7 +340,6 @@ public:
r._ref(alloc);
}
return r;
-
}
Write write() {
@@ -378,90 +351,88 @@ public:
return w;
}
- template<class MC>
- void fill_with(const MC& p_mc) {
-
+ template <class MC>
+ void fill_with(const MC &p_mc) {
- int c=p_mc.size();
+ int c = p_mc.size();
resize(c);
- Write w=write();
- int idx=0;
- for(const typename MC::Element *E=p_mc.front();E;E=E->next()) {
+ Write w = write();
+ int idx = 0;
+ for (const typename MC::Element *E = p_mc.front(); E; E = E->next()) {
- w[idx++]=E->get();
+ w[idx++] = E->get();
}
}
-
void remove(int p_index) {
int s = size();
ERR_FAIL_INDEX(p_index, s);
Write w = write();
- for (int i=p_index; i<s-1; i++) {
+ for (int i = p_index; i < s - 1; i++) {
- w[i]=w[i+1];
+ w[i] = w[i + 1];
};
w = Write();
- resize(s-1);
+ resize(s - 1);
}
inline int size() const;
T get(int p_index) const;
- void set(int p_index, const T& p_val);
- void push_back(const T& p_val);
- void append(const T& p_val) { push_back(p_val); }
- void append_array(const PoolVector<T>& p_arr) {
+ void set(int p_index, const T &p_val);
+ void push_back(const T &p_val);
+ void append(const T &p_val) { push_back(p_val); }
+ void append_array(const PoolVector<T> &p_arr) {
int ds = p_arr.size();
- if (ds==0)
+ if (ds == 0)
return;
int bs = size();
- resize( bs + ds);
+ resize(bs + ds);
Write w = write();
Read r = p_arr.read();
- for(int i=0;i<ds;i++)
- w[bs+i]=r[i];
+ for (int i = 0; i < ds; i++)
+ w[bs + i] = r[i];
}
PoolVector<T> subarray(int p_from, int p_to) {
- if (p_from<0) {
- p_from=size()+p_from;
+ if (p_from < 0) {
+ p_from = size() + p_from;
}
- if (p_to<0) {
- p_to=size()+p_to;
+ if (p_to < 0) {
+ p_to = size() + p_to;
}
- if (p_from<0 || p_from>=size()) {
- PoolVector<T>& aux=*((PoolVector<T>*)0); // nullreturn
- ERR_FAIL_COND_V(p_from<0 || p_from>=size(),aux)
+ if (p_from < 0 || p_from >= size()) {
+ PoolVector<T> &aux = *((PoolVector<T> *)0); // nullreturn
+ ERR_FAIL_COND_V(p_from < 0 || p_from >= size(), aux)
}
- if (p_to<0 || p_to>=size()) {
- PoolVector<T>& aux=*((PoolVector<T>*)0); // nullreturn
- ERR_FAIL_COND_V(p_to<0 || p_to>=size(),aux)
+ if (p_to < 0 || p_to >= size()) {
+ PoolVector<T> &aux = *((PoolVector<T> *)0); // nullreturn
+ ERR_FAIL_COND_V(p_to < 0 || p_to >= size(), aux)
}
PoolVector<T> slice;
- int span=1 + p_to - p_from;
+ int span = 1 + p_to - p_from;
slice.resize(span);
Read r = read();
Write w = slice.write();
- for (int i=0; i<span; ++i) {
- w[i] = r[p_from+i];
+ for (int i = 0; i < span; ++i) {
+ w[i] = r[p_from + i];
}
return slice;
}
- Error insert(int p_pos,const T& p_val) {
+ Error insert(int p_pos, const T &p_val) {
- int s=size();
- ERR_FAIL_INDEX_V(p_pos,s+1,ERR_INVALID_PARAMETER);
- resize(s+1);
+ int s = size();
+ ERR_FAIL_INDEX_V(p_pos, s + 1, ERR_INVALID_PARAMETER);
+ resize(s + 1);
{
Write w = write();
- for (int i=s;i>p_pos;i--)
- w[i]=w[i-1];
- w[p_pos]=p_val;
+ for (int i = s; i > p_pos; i--)
+ w[i] = w[i - 1];
+ w[p_pos] = p_val;
}
return OK;
@@ -471,14 +442,14 @@ public:
String rs = "";
int s = size();
Read r = read();
- for(int i=0;i<s;i++) {
+ for (int i = 0; i < s; i++) {
rs += r[i] + delimiter;
}
- rs.erase( rs.length()-delimiter.length(), delimiter.length());
+ rs.erase(rs.length() - delimiter.length(), delimiter.length());
return rs;
}
- bool is_locked() const { return alloc && alloc->lock>0; }
+ bool is_locked() const { return alloc && alloc->lock > 0; }
inline const T operator[](int p_index) const;
@@ -486,49 +457,51 @@ public:
void invert();
- void operator=(const PoolVector& p_dvector) { _reference(p_dvector); }
- PoolVector() { alloc=NULL; }
- PoolVector(const PoolVector& p_dvector) { alloc=NULL; _reference(p_dvector); }
+ void operator=(const PoolVector &p_dvector) { _reference(p_dvector); }
+ PoolVector() { alloc = NULL; }
+ PoolVector(const PoolVector &p_dvector) {
+ alloc = NULL;
+ _reference(p_dvector);
+ }
~PoolVector() { _unreference(); }
-
};
-template<class T>
+template <class T>
int PoolVector<T>::size() const {
- return alloc ? alloc->size/sizeof(T) : 0;
+ return alloc ? alloc->size / sizeof(T) : 0;
}
-template<class T>
+template <class T>
T PoolVector<T>::get(int p_index) const {
return operator[](p_index);
}
-template<class T>
-void PoolVector<T>::set(int p_index, const T& p_val) {
+template <class T>
+void PoolVector<T>::set(int p_index, const T &p_val) {
- if (p_index<0 || p_index>=size()) {
- ERR_FAIL_COND(p_index<0 || p_index>=size());
+ if (p_index < 0 || p_index >= size()) {
+ ERR_FAIL_COND(p_index < 0 || p_index >= size());
}
Write w = write();
- w[p_index]=p_val;
+ w[p_index] = p_val;
}
-template<class T>
-void PoolVector<T>::push_back(const T& p_val) {
+template <class T>
+void PoolVector<T>::push_back(const T &p_val) {
- resize( size() + 1 );
- set( size() -1, p_val );
+ resize(size() + 1);
+ set(size() - 1, p_val);
}
-template<class T>
+template <class T>
const T PoolVector<T>::operator[](int p_index) const {
- if (p_index<0 || p_index>=size()) {
- T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux);
+ if (p_index < 0 || p_index >= size()) {
+ T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux);
}
Read r = read();
@@ -536,19 +509,17 @@ const T PoolVector<T>::operator[](int p_index) const {
return r[p_index];
}
-
-template<class T>
+template <class T>
Error PoolVector<T>::resize(int p_size) {
+ if (alloc == NULL) {
- if (alloc==NULL) {
-
- if (p_size==0)
+ if (p_size == 0)
return OK; //nothing to do here
//must allocate something
MemoryPool::alloc_mutex->lock();
- if (MemoryPool::allocs_used==MemoryPool::alloc_count) {
+ if (MemoryPool::allocs_used == MemoryPool::alloc_count) {
MemoryPool::alloc_mutex->unlock();
ERR_EXPLAINC("All memory pool allocations are in use.");
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
@@ -561,22 +532,22 @@ Error PoolVector<T>::resize(int p_size) {
MemoryPool::allocs_used++;
//cleanup the alloc
- alloc->size=0;
+ alloc->size = 0;
alloc->refcount.init();
- alloc->pool_id=POOL_ALLOCATOR_INVALID_ID;
+ alloc->pool_id = POOL_ALLOCATOR_INVALID_ID;
MemoryPool::alloc_mutex->unlock();
} else {
- ERR_FAIL_COND_V( alloc->lock>0, ERR_LOCKED ); //can't resize if locked!
+ ERR_FAIL_COND_V(alloc->lock > 0, ERR_LOCKED); //can't resize if locked!
}
- size_t new_size = sizeof(T)*p_size;
+ size_t new_size = sizeof(T) * p_size;
- if (alloc->size==new_size)
+ if (alloc->size == new_size)
return OK; //nothing to do
- if (p_size == 0 ) {
+ if (p_size == 0) {
_unreference();
return OK;
}
@@ -585,18 +556,17 @@ Error PoolVector<T>::resize(int p_size) {
#ifdef DEBUG_ENABLED
MemoryPool::alloc_mutex->lock();
- MemoryPool::total_memory-=alloc->size;
- MemoryPool::total_memory+=new_size;
- if (MemoryPool::total_memory>MemoryPool::max_memory) {
- MemoryPool::max_memory=MemoryPool::total_memory;
+ MemoryPool::total_memory -= alloc->size;
+ MemoryPool::total_memory += new_size;
+ if (MemoryPool::total_memory > MemoryPool::max_memory) {
+ MemoryPool::max_memory = MemoryPool::total_memory;
}
MemoryPool::alloc_mutex->unlock();
#endif
-
int cur_elements = alloc->size / sizeof(T);
- if (p_size > cur_elements ) {
+ if (p_size > cur_elements) {
if (MemoryPool::memory_pool) {
//resize memory pool
@@ -604,32 +574,30 @@ Error PoolVector<T>::resize(int p_size) {
//if some resize
} else {
- if (alloc->size==0) {
- alloc->mem = memalloc( new_size );
+ if (alloc->size == 0) {
+ alloc->mem = memalloc(new_size);
} else {
- alloc->mem = memrealloc( alloc->mem, new_size );
+ alloc->mem = memrealloc(alloc->mem, new_size);
}
}
- alloc->size=new_size;
+ alloc->size = new_size;
Write w = write();
- for (int i=cur_elements;i<p_size;i++) {
+ for (int i = cur_elements; i < p_size; i++) {
- memnew_placement(&w[i], T );
+ memnew_placement(&w[i], T);
}
-
} else {
{
Write w = write();
- for (int i=p_size;i<cur_elements;i++) {
+ for (int i = p_size; i < cur_elements; i++) {
w[i].~T();
}
-
}
if (MemoryPool::memory_pool) {
@@ -638,39 +606,38 @@ Error PoolVector<T>::resize(int p_size) {
//if some resize
} else {
- if (new_size==0) {
- memfree( alloc->mem );
- alloc->mem=NULL;
- alloc->size=0;
+ if (new_size == 0) {
+ memfree(alloc->mem);
+ alloc->mem = NULL;
+ alloc->size = 0;
MemoryPool::alloc_mutex->lock();
- alloc->free_list=MemoryPool::free_list;
- MemoryPool::free_list=alloc;
+ alloc->free_list = MemoryPool::free_list;
+ MemoryPool::free_list = alloc;
MemoryPool::allocs_used--;
MemoryPool::alloc_mutex->unlock();
} else {
- alloc->mem = memrealloc( alloc->mem, new_size );
- alloc->size=new_size;
+ alloc->mem = memrealloc(alloc->mem, new_size);
+ alloc->size = new_size;
}
}
-
}
return OK;
}
-template<class T>
+template <class T>
void PoolVector<T>::invert() {
T temp;
Write w = write();
int s = size();
- int half_s = s/2;
+ int half_s = s / 2;
- for(int i=0;i<half_s;i++) {
+ for (int i = 0; i < half_s; i++) {
temp = w[i];
- w[i] = w[s-i-1];
- w[s-i-1] = temp;
+ w[i] = w[s - i - 1];
+ w[s - i - 1] = temp;
}
}
diff --git a/core/engine.cpp b/core/engine.cpp
index b017e77275..1e46117bd6 100644
--- a/core/engine.cpp
+++ b/core/engine.cpp
@@ -32,7 +32,7 @@
void Engine::set_iterations_per_second(int p_ips) {
- ips=p_ips;
+ ips = p_ips;
}
int Engine::get_iterations_per_second() const {
@@ -40,7 +40,7 @@ int Engine::get_iterations_per_second() const {
}
void Engine::set_target_fps(int p_fps) {
- _target_fps=p_fps>0? p_fps : 0;
+ _target_fps = p_fps > 0 ? p_fps : 0;
}
float Engine::get_target_fps() const {
@@ -54,7 +54,7 @@ uint64_t Engine::get_frames_drawn() {
void Engine::set_frame_delay(uint32_t p_msec) {
- _frame_delay=p_msec;
+ _frame_delay = p_msec;
}
uint32_t Engine::get_frame_delay() const {
@@ -64,7 +64,7 @@ uint32_t Engine::get_frame_delay() const {
void Engine::set_time_scale(float p_scale) {
- _time_scale=p_scale;
+ _time_scale = p_scale;
}
float Engine::get_time_scale() const {
@@ -77,11 +77,11 @@ Dictionary Engine::get_version_info() const {
Dictionary dict;
dict["major"] = VERSION_MAJOR;
dict["minor"] = VERSION_MINOR;
- #ifdef VERSION_PATCH
+#ifdef VERSION_PATCH
dict["patch"] = VERSION_PATCH;
- #else
+#else
dict["patch"] = 0;
- #endif
+#endif
dict["status"] = _MKSTR(VERSION_STATUS);
dict["revision"] = _MKSTR(VERSION_REVISION);
dict["year"] = VERSION_YEAR;
@@ -95,25 +95,23 @@ Dictionary Engine::get_version_info() const {
return dict;
}
-
-Engine *Engine::singleton=NULL;
+Engine *Engine::singleton = NULL;
Engine *Engine::get_singleton() {
return singleton;
}
-Engine::Engine()
-{
-
- singleton=this;
- frames_drawn=0;
- ips=60;
- _frame_delay=0;
- _fps=1;
- _target_fps=0;
- _time_scale=1.0;
- _pixel_snap=false;
- _fixed_frames=0;
- _idle_frames=0;
- _in_fixed=false;
+Engine::Engine() {
+
+ singleton = this;
+ frames_drawn = 0;
+ ips = 60;
+ _frame_delay = 0;
+ _fps = 1;
+ _target_fps = 0;
+ _time_scale = 1.0;
+ _pixel_snap = false;
+ _fixed_frames = 0;
+ _idle_frames = 0;
+ _in_fixed = false;
}
diff --git a/core/engine.h b/core/engine.h
index 9af4219a68..346e9538d6 100644
--- a/core/engine.h
+++ b/core/engine.h
@@ -29,14 +29,14 @@
#ifndef ENGINE_H
#define ENGINE_H
-#include "ustring.h"
#include "list.h"
-#include "vector.h"
#include "os/main_loop.h"
+#include "ustring.h"
+#include "vector.h"
class Engine {
-friend class Main;
+ friend class Main;
String _custom_level;
uint64_t frames_drawn;
@@ -52,8 +52,8 @@ friend class Main;
bool _in_fixed;
static Engine *singleton;
-public:
+public:
static Engine *get_singleton();
virtual void set_iterations_per_second(int p_ips);
diff --git a/core/error_list.h b/core/error_list.h
index f4063a9285..72b8425444 100644
--- a/core/error_list.h
+++ b/core/error_list.h
@@ -47,7 +47,7 @@ enum Error {
ERR_FILE_NOT_FOUND,
ERR_FILE_BAD_DRIVE,
ERR_FILE_BAD_PATH,
- ERR_FILE_NO_PERMISSION, // (10)
+ ERR_FILE_NO_PERMISSION, // (10)
ERR_FILE_ALREADY_IN_USE,
ERR_FILE_CANT_OPEN,
ERR_FILE_CANT_WRITE,
@@ -57,15 +57,15 @@ enum Error {
ERR_FILE_MISSING_DEPENDENCIES,
ERR_FILE_EOF,
ERR_CANT_OPEN, ///< Can't open a resource/socket/file
- ERR_CANT_CREATE, // (20)
+ ERR_CANT_CREATE, // (20)
ERR_QUERY_FAILED,
ERR_ALREADY_IN_USE,
- ERR_LOCKED, ///< resource is locked
- ERR_TIMEOUT,
- ERR_CANT_CONNECT, // (25)
+ ERR_LOCKED, ///< resource is locked
+ ERR_TIMEOUT,
+ ERR_CANT_CONNECT, // (25)
ERR_CANT_RESOLVE,
ERR_CONNECTION_ERROR,
- ERR_CANT_AQUIRE_RESOURCE,
+ ERR_CANT_AQUIRE_RESOURCE,
ERR_CANT_FORK,
ERR_INVALID_DATA, ///< Data passed is invalid (30)
ERR_INVALID_PARAMETER, ///< Parameter passed is invalid
@@ -74,15 +74,15 @@ enum Error {
ERR_DATABASE_CANT_READ, ///< database is full
ERR_DATABASE_CANT_WRITE, ///< database is full (35)
ERR_COMPILATION_FAILED,
- ERR_METHOD_NOT_FOUND,
- ERR_LINK_FAILED,
+ ERR_METHOD_NOT_FOUND,
+ ERR_LINK_FAILED,
ERR_SCRIPT_FAILED,
- ERR_CYCLIC_LINK, // (40)
+ ERR_CYCLIC_LINK, // (40)
ERR_INVALID_DECLARATION,
ERR_DUPLICATE_SYMBOL,
ERR_PARSE_ERROR,
ERR_BUSY,
- ERR_SKIP, // (45)
+ ERR_SKIP, // (45)
ERR_HELP, ///< user requested help!!
ERR_BUG, ///< a bug in the software certainly happened, due to a double check failing or unexpected behavior.
ERR_PRINTER_ON_FIRE, /// the parallel port printer is engulfed in flames
@@ -90,7 +90,4 @@ enum Error {
ERR_WTF = ERR_OMFG_THIS_IS_VERY_VERY_BAD ///< short version of the above
};
-
-
#endif
-
diff --git a/core/error_macros.cpp b/core/error_macros.cpp
index e963f6122b..530e209dd8 100644
--- a/core/error_macros.cpp
+++ b/core/error_macros.cpp
@@ -30,12 +30,11 @@
#include "os/os.h"
+bool _err_error_exists = false;
-bool _err_error_exists=false;
+static ErrorHandlerList *error_handler_list = NULL;
-static ErrorHandlerList *error_handler_list=NULL;
-
-void _err_set_last_error(const char* p_err) {
+void _err_set_last_error(const char *p_err) {
OS::get_singleton()->set_last_error(p_err);
}
@@ -48,8 +47,8 @@ void _err_clear_last_error() {
void add_error_handler(ErrorHandlerList *p_handler) {
_global_lock();
- p_handler->next=error_handler_list;
- error_handler_list=p_handler;
+ p_handler->next = error_handler_list;
+ error_handler_list = p_handler;
_global_unlock();
}
@@ -60,44 +59,39 @@ void remove_error_handler(ErrorHandlerList *p_handler) {
ErrorHandlerList *prev = NULL;
ErrorHandlerList *l = error_handler_list;
- while(l) {
+ while (l) {
- if (l==p_handler) {
+ if (l == p_handler) {
if (prev)
- prev->next=l->next;
+ prev->next = l->next;
else
- error_handler_list=l->next;
+ error_handler_list = l->next;
break;
}
- prev=l;
- l=l->next;
-
+ prev = l;
+ l = l->next;
}
_global_unlock();
-
}
-void _err_print_error(const char* p_function, const char* p_file,int p_line,const char *p_error,ErrorHandlerType p_type) {
+void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, ErrorHandlerType p_type) {
-
-
- OS::get_singleton()->print_error(p_function,p_file,p_line,p_error,_err_error_exists?OS::get_singleton()->get_last_error():"",(OS::ErrorType)p_type);
+ OS::get_singleton()->print_error(p_function, p_file, p_line, p_error, _err_error_exists ? OS::get_singleton()->get_last_error() : "", (OS::ErrorType)p_type);
_global_lock();
ErrorHandlerList *l = error_handler_list;
- while(l) {
+ while (l) {
- l->errfunc(l->userdata,p_function,p_file,p_line,p_error,_err_error_exists?OS::get_singleton()->get_last_error():"",p_type);
- l=l->next;
+ l->errfunc(l->userdata, p_function, p_file, p_line, p_error, _err_error_exists ? OS::get_singleton()->get_last_error() : "", p_type);
+ l = l->next;
}
_global_unlock();
if (_err_error_exists) {
OS::get_singleton()->clear_last_error();
- _err_error_exists=false;
+ _err_error_exists = false;
}
-
}
diff --git a/core/error_macros.h b/core/error_macros.h
index ac86ef432b..02a15de067 100644
--- a/core/error_macros.h
+++ b/core/error_macros.h
@@ -29,7 +29,6 @@
#ifndef ERROR_MACROS_H
#define ERROR_MACROS_H
-
/**
* Error macros. Unlike exceptions and asserts, these macros try to mantain consistency and stability
* inside the code. It is recommended to always return processable data, so in case of an error, the
@@ -53,8 +52,8 @@ enum ErrorHandlerType {
ERR_HANDLER_SHADER,
};
-typedef void (*ErrorHandlerFunc)(void*,const char*,const char*,int p_line,const char *, const char *,ErrorHandlerType p_type);
-void _err_set_last_error(const char* p_err);
+typedef void (*ErrorHandlerFunc)(void *, const char *, const char *, int p_line, const char *, const char *, ErrorHandlerType p_type);
+void _err_set_last_error(const char *p_err);
void _err_clear_last_error();
struct ErrorHandlerList {
@@ -62,22 +61,26 @@ struct ErrorHandlerList {
ErrorHandlerFunc errfunc;
void *userdata;
- ErrorHandlerList*next;
+ ErrorHandlerList *next;
- ErrorHandlerList() { errfunc=0; next=0; userdata=0; }
+ ErrorHandlerList() {
+ errfunc = 0;
+ next = 0;
+ userdata = 0;
+ }
};
void add_error_handler(ErrorHandlerList *p_handler);
void remove_error_handler(ErrorHandlerList *p_handler);
-void _err_print_error(const char* p_function,const char* p_file,int p_line,const char *p_error,ErrorHandlerType p_type=ERR_HANDLER_ERROR);
+void _err_print_error(const char *p_function, const char *p_file, int p_line, const char *p_error, ErrorHandlerType p_type = ERR_HANDLER_ERROR);
#ifndef _STR
#define _STR(m_x) #m_x
#define _MKSTR(m_x) _STR(m_x)
#endif
-#define _FNL __FILE__":"
+#define _FNL __FILE__ ":"
/** An index has failed if m_index<0 or m_index >=m_size, the function exists */
@@ -86,13 +89,21 @@ extern bool _err_error_exists;
#ifdef DEBUG_ENABLED
/** Print a warning string.
*/
-#define ERR_EXPLAINC(m_reason) {_err_set_last_error(m_reason); _err_error_exists=true;}
-#define ERR_EXPLAIN(m_string) {_err_set_last_error(String(m_string).utf8().get_data()); _err_error_exists=true;}
+#define ERR_EXPLAINC(m_reason) \
+ { \
+ _err_set_last_error(m_reason); \
+ _err_error_exists = true; \
+ }
+#define ERR_EXPLAIN(m_string) \
+ { \
+ _err_set_last_error(String(m_string).utf8().get_data()); \
+ _err_error_exists = true; \
+ }
#else
-#define ERR_EXPLAIN( m_text )
-#define ERR_EXPLAINC( m_text )
+#define ERR_EXPLAIN(m_text)
+#define ERR_EXPLAINC(m_text)
#endif
@@ -103,49 +114,63 @@ extern bool _err_error_exists;
#define FUNCTION_STR __FUNCTION__
#endif
-#define ERR_FAIL_INDEX(m_index,m_size) \
- do {if ((m_index)<0 || (m_index)>=(m_size)) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Index " _STR(m_index)" out of size (" _STR(m_size)")."); \
- return; \
- } else _err_error_exists=false; } while(0); \
+#define ERR_FAIL_INDEX(m_index, m_size) \
+ do { \
+ if ((m_index) < 0 || (m_index) >= (m_size)) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Index " _STR(m_index) " out of size (" _STR(m_size) ")."); \
+ return; \
+ } else \
+ _err_error_exists = false; \
+ } while (0);
/** An index has failed if m_index<0 or m_index >=m_size, the function exists.
* This function returns an error value, if returning Error, please select the most
* appropriate error condition from error_macros.h
*/
-#define ERR_FAIL_INDEX_V(m_index,m_size,m_retval) \
- do {if ((m_index)<0 || (m_index)>=(m_size)) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Index " _STR(m_index)" out of size (" _STR(m_size)")."); \
- return m_retval; \
- } else _err_error_exists=false;} while (0);
+#define ERR_FAIL_INDEX_V(m_index, m_size, m_retval) \
+ do { \
+ if ((m_index) < 0 || (m_index) >= (m_size)) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Index " _STR(m_index) " out of size (" _STR(m_size) ")."); \
+ return m_retval; \
+ } else \
+ _err_error_exists = false; \
+ } while (0);
- /** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
+/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
* the function will exit.
*/
- #define ERR_FAIL_NULL(m_param) \
- { if ( !m_param ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Parameter ' " _STR(m_param)" ' is null."); \
- return; \
- }else _err_error_exists=false; } \
-
-
-#define ERR_FAIL_NULL_V(m_param,m_retval) \
- { if ( !m_param ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Parameter ' " _STR(m_param)" ' is null."); \
- return m_retval; \
- }else _err_error_exists=false; } \
+#define ERR_FAIL_NULL(m_param) \
+ { \
+ if (!m_param) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter ' " _STR(m_param) " ' is null."); \
+ return; \
+ } else \
+ _err_error_exists = false; \
+ }
+
+#define ERR_FAIL_NULL_V(m_param, m_retval) \
+ { \
+ if (!m_param) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Parameter ' " _STR(m_param) " ' is null."); \
+ return m_retval; \
+ } else \
+ _err_error_exists = false; \
+ }
/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
* the function will exit.
*/
-#define ERR_FAIL_COND(m_cond) \
- { if ( m_cond ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true."); \
- return; \
- }else _err_error_exists=false; } \
+#define ERR_FAIL_COND(m_cond) \
+ { \
+ if (m_cond) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true."); \
+ return; \
+ } else \
+ _err_error_exists = false; \
+ }
/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
* the function will exit.
@@ -153,81 +178,89 @@ extern bool _err_error_exists;
* appropriate error condition from error_macros.h
*/
-#define ERR_FAIL_COND_V(m_cond,m_retval) \
- { if ( m_cond ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. returned: " _STR(m_retval)); \
- return m_retval; \
- }else _err_error_exists=false; } \
+#define ERR_FAIL_COND_V(m_cond, m_retval) \
+ { \
+ if (m_cond) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. returned: " _STR(m_retval)); \
+ return m_retval; \
+ } else \
+ _err_error_exists = false; \
+ }
/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
* the loop will skip to the next iteration.
*/
-#define ERR_CONTINUE(m_cond) \
- { if ( m_cond ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. Continuing..:"); \
- continue;\
- } else _err_error_exists=false;} \
+#define ERR_CONTINUE(m_cond) \
+ { \
+ if (m_cond) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Continuing..:"); \
+ continue; \
+ } else \
+ _err_error_exists = false; \
+ }
/** An error condition happened (m_cond tested true) (WARNING this is the opposite as assert().
* the loop will break
*/
-#define ERR_BREAK(m_cond) \
- { if ( m_cond ) { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Condition ' " _STR(m_cond)" ' is true. Breaking..:"); \
- break;\
- } else _err_error_exists=false;} \
+#define ERR_BREAK(m_cond) \
+ { \
+ if (m_cond) { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Condition ' " _STR(m_cond) " ' is true. Breaking..:"); \
+ break; \
+ } else \
+ _err_error_exists = false; \
+ }
/** Print an error string and return
*/
-#define ERR_FAIL() \
-{ \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Method/Function Failed."); \
- _err_error_exists=false;\
- return;\
-} \
+#define ERR_FAIL() \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/Function Failed."); \
+ _err_error_exists = false; \
+ return; \
+ }
/** Print an error string and return with value
*/
-#define ERR_FAIL_V(m_value) \
-{ \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,"Method/Function Failed, returning: " __STR(m_value)); \
- _err_error_exists=false; \
- return m_value;\
-} \
+#define ERR_FAIL_V(m_value) \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, "Method/Function Failed, returning: " __STR(m_value)); \
+ _err_error_exists = false; \
+ return m_value; \
+ }
/** Print an error string.
*/
-#define ERR_PRINT(m_string) \
- { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,m_string); \
- _err_error_exists=false;\
- } \
+#define ERR_PRINT(m_string) \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, m_string); \
+ _err_error_exists = false; \
+ }
-#define ERR_PRINTS(m_string) \
- { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,String(m_string).utf8().get_data()); \
- _err_error_exists=false;\
- } \
+#define ERR_PRINTS(m_string) \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, String(m_string).utf8().get_data()); \
+ _err_error_exists = false; \
+ }
/** Print a warning string.
*/
-#define WARN_PRINT(m_string) \
- { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,m_string,ERR_HANDLER_WARNING); \
- _err_error_exists=false;\
- } \
-
-
-#define WARN_PRINTS(m_string) \
- { \
- _err_print_error(FUNCTION_STR,__FILE__,__LINE__,String(m_string).utf8().get_data(),ERR_HANDLER_WARNING); \
- _err_error_exists=false;\
- } \
+#define WARN_PRINT(m_string) \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, m_string, ERR_HANDLER_WARNING); \
+ _err_error_exists = false; \
+ }
+
+#define WARN_PRINTS(m_string) \
+ { \
+ _err_print_error(FUNCTION_STR, __FILE__, __LINE__, String(m_string).utf8().get_data(), ERR_HANDLER_WARNING); \
+ _err_error_exists = false; \
+ }
#endif
diff --git a/core/event_queue.cpp b/core/event_queue.cpp
index 587283cc79..f9ebc82e40 100644
--- a/core/event_queue.cpp
+++ b/core/event_queue.cpp
@@ -28,134 +28,129 @@
/*************************************************************************/
#include "event_queue.h"
-
-Error EventQueue::push_call(uint32_t p_instance_ID, const StringName& p_method, VARIANT_ARG_DECLARE) {
-
- uint8_t room_needed=sizeof(Event);
- int args=0;
- if (p_arg5.get_type()!=Variant::NIL)
- args=5;
- else if (p_arg4.get_type()!=Variant::NIL)
- args=4;
- else if (p_arg3.get_type()!=Variant::NIL)
- args=3;
- else if (p_arg2.get_type()!=Variant::NIL)
- args=2;
- else if (p_arg1.get_type()!=Variant::NIL)
- args=1;
+Error EventQueue::push_call(uint32_t p_instance_ID, const StringName &p_method, VARIANT_ARG_DECLARE) {
+
+ uint8_t room_needed = sizeof(Event);
+ int args = 0;
+ if (p_arg5.get_type() != Variant::NIL)
+ args = 5;
+ else if (p_arg4.get_type() != Variant::NIL)
+ args = 4;
+ else if (p_arg3.get_type() != Variant::NIL)
+ args = 3;
+ else if (p_arg2.get_type() != Variant::NIL)
+ args = 2;
+ else if (p_arg1.get_type() != Variant::NIL)
+ args = 1;
else
- args=0;
+ args = 0;
- room_needed+=sizeof(Variant)*args;
+ room_needed += sizeof(Variant) * args;
- ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY );
- Event * ev = memnew_placement( &event_buffer[ buffer_end ], Event );
- ev->args=args;
- ev->instance_ID=p_instance_ID;
- ev->method=p_method;
+ ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
+ Event *ev = memnew_placement(&event_buffer[buffer_end], Event);
+ ev->args = args;
+ ev->instance_ID = p_instance_ID;
+ ev->method = p_method;
- buffer_end+=sizeof(Event);
+ buffer_end += sizeof(Event);
- if (args>=1) {
+ if (args >= 1) {
- Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_arg1;
+ Variant *v = memnew_placement(&event_buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_arg1;
}
- if (args>=2) {
+ if (args >= 2) {
- Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_arg2;
+ Variant *v = memnew_placement(&event_buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_arg2;
}
- if (args>=3) {
-
- Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_arg3;
+ if (args >= 3) {
+ Variant *v = memnew_placement(&event_buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_arg3;
}
- if (args>=4) {
+ if (args >= 4) {
- Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_arg4;
+ Variant *v = memnew_placement(&event_buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_arg4;
}
- if (args>=5) {
+ if (args >= 5) {
- Variant * v = memnew_placement( &event_buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_arg5;
+ Variant *v = memnew_placement(&event_buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_arg5;
}
if (buffer_end > buffer_max_used)
- buffer_max_used=buffer_end;
+ buffer_max_used = buffer_end;
return OK;
}
void EventQueue::flush_events() {
- uint32_t read_pos=0;
+ uint32_t read_pos = 0;
- while (read_pos < buffer_end ) {
+ while (read_pos < buffer_end) {
- Event *event = (Event*)&event_buffer[ read_pos ];
- Variant *args= (Variant*)(event+1);
+ Event *event = (Event *)&event_buffer[read_pos];
+ Variant *args = (Variant *)(event + 1);
Object *obj = ObjectDB::get_instance(event->instance_ID);
if (obj) {
// events don't expect a return value
- obj->call( event->method,
- (event->args>=1) ? args[0] : Variant(),
- (event->args>=2) ? args[1] : Variant(),
- (event->args>=3) ? args[2] : Variant(),
- (event->args>=4) ? args[3] : Variant(),
- (event->args>=5) ? args[4] : Variant() );
+ obj->call(event->method,
+ (event->args >= 1) ? args[0] : Variant(),
+ (event->args >= 2) ? args[1] : Variant(),
+ (event->args >= 3) ? args[2] : Variant(),
+ (event->args >= 4) ? args[3] : Variant(),
+ (event->args >= 5) ? args[4] : Variant());
}
- if (event->args>=1) args[0].~Variant();
- if (event->args>=2) args[1].~Variant();
- if (event->args>=3) args[2].~Variant();
- if (event->args>=4) args[3].~Variant();
- if (event->args>=5) args[4].~Variant();
+ if (event->args >= 1) args[0].~Variant();
+ if (event->args >= 2) args[1].~Variant();
+ if (event->args >= 3) args[2].~Variant();
+ if (event->args >= 4) args[3].~Variant();
+ if (event->args >= 5) args[4].~Variant();
event->~Event();
- read_pos+=sizeof(Event)+sizeof(Variant)*event->args;
+ read_pos += sizeof(Event) + sizeof(Variant) * event->args;
}
- buffer_end=0; // reset buffer
+ buffer_end = 0; // reset buffer
}
EventQueue::EventQueue(uint32_t p_buffer_size) {
-
- buffer_end=0;
- buffer_max_used=0;
- buffer_size=p_buffer_size;
- event_buffer = memnew_arr( uint8_t, buffer_size );
-
+ buffer_end = 0;
+ buffer_max_used = 0;
+ buffer_size = p_buffer_size;
+ event_buffer = memnew_arr(uint8_t, buffer_size);
}
EventQueue::~EventQueue() {
- uint32_t read_pos=0;
+ uint32_t read_pos = 0;
- while (read_pos < buffer_end ) {
+ while (read_pos < buffer_end) {
- Event *event = (Event*)&event_buffer[ read_pos ];
- Variant *args= (Variant*)(event+1);
- for (int i=0;i<event->args;i++)
+ Event *event = (Event *)&event_buffer[read_pos];
+ Variant *args = (Variant *)(event + 1);
+ for (int i = 0; i < event->args; i++)
args[i].~Variant();
event->~Event();
- read_pos+=sizeof(Event)+sizeof(Variant)*event->args;
+ read_pos += sizeof(Event) + sizeof(Variant) * event->args;
}
memdelete_arr(event_buffer);
- event_buffer=NULL;
+ event_buffer = NULL;
}
-
diff --git a/core/event_queue.h b/core/event_queue.h
index d15ff81bc7..8e35445b68 100644
--- a/core/event_queue.h
+++ b/core/event_queue.h
@@ -37,7 +37,7 @@ class EventQueue {
enum {
- DEFAULT_EVENT_QUEUE_SIZE_KB=256
+ DEFAULT_EVENT_QUEUE_SIZE_KB = 256
};
struct Event {
@@ -47,20 +47,17 @@ class EventQueue {
int args;
};
-
uint8_t *event_buffer;
uint32_t buffer_end;
uint32_t buffer_max_used;
uint32_t buffer_size;
-public:
-
- Error push_call(uint32_t p_instance_ID, const StringName& p_method, VARIANT_ARG_LIST);
+public:
+ Error push_call(uint32_t p_instance_ID, const StringName &p_method, VARIANT_ARG_LIST);
void flush_events();
- EventQueue(uint32_t p_buffer_size=DEFAULT_EVENT_QUEUE_SIZE_KB*1024);
+ EventQueue(uint32_t p_buffer_size = DEFAULT_EVENT_QUEUE_SIZE_KB * 1024);
~EventQueue();
-
};
#endif
diff --git a/core/func_ref.cpp b/core/func_ref.cpp
index 2233615e25..1589be996e 100644
--- a/core/func_ref.cpp
+++ b/core/func_ref.cpp
@@ -28,51 +28,46 @@
/*************************************************************************/
#include "func_ref.h"
-Variant FuncRef::call_func(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
+Variant FuncRef::call_func(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- if (id==0) {
- r_error.error=Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ if (id == 0) {
+ r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
return Variant();
}
- Object* obj = ObjectDB::get_instance(id);
+ Object *obj = ObjectDB::get_instance(id);
if (!obj) {
- r_error.error=Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
return Variant();
}
- return obj->call(function,p_args,p_argcount,r_error);
-
+ return obj->call(function, p_args, p_argcount, r_error);
}
-void FuncRef::set_instance(Object *p_obj){
+void FuncRef::set_instance(Object *p_obj) {
ERR_FAIL_NULL(p_obj);
- id=p_obj->get_instance_ID();
+ id = p_obj->get_instance_ID();
}
-void FuncRef::set_function(const StringName& p_func){
+void FuncRef::set_function(const StringName &p_func) {
- function=p_func;
+ function = p_func;
}
void FuncRef::_bind_methods() {
{
MethodInfo mi;
- mi.name="call_func";
+ mi.name = "call_func";
Vector<Variant> defargs;
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_func:Variant",&FuncRef::call_func,mi,defargs);
-
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_func:Variant", &FuncRef::call_func, mi, defargs);
}
- ClassDB::bind_method(D_METHOD("set_instance","instance"),&FuncRef::set_instance);
- ClassDB::bind_method(D_METHOD("set_function","name"),&FuncRef::set_function);
-
+ ClassDB::bind_method(D_METHOD("set_instance", "instance"), &FuncRef::set_instance);
+ ClassDB::bind_method(D_METHOD("set_function", "name"), &FuncRef::set_function);
}
+FuncRef::FuncRef() {
-FuncRef::FuncRef(){
-
- id=0;
+ id = 0;
}
-
diff --git a/core/func_ref.h b/core/func_ref.h
index 0c9bca4680..1179c98e29 100644
--- a/core/func_ref.h
+++ b/core/func_ref.h
@@ -31,20 +31,19 @@
#include "reference.h"
-class FuncRef : public Reference{
+class FuncRef : public Reference {
- GDCLASS(FuncRef,Reference);
+ GDCLASS(FuncRef, Reference);
ObjectID id;
StringName function;
protected:
-
static void _bind_methods();
-public:
- Variant call_func(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+public:
+ Variant call_func(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
void set_instance(Object *p_obj);
- void set_function(const StringName& p_func);
+ void set_function(const StringName &p_func);
FuncRef();
};
diff --git a/core/global_config.cpp b/core/global_config.cpp
index b76991c04e..6aded6fbb7 100644
--- a/core/global_config.cpp
+++ b/core/global_config.cpp
@@ -28,19 +28,19 @@
/*************************************************************************/
#include "global_config.h"
+#include "bind/core_bind.h"
+#include "io/file_access_network.h"
+#include "io/file_access_pack.h"
+#include "io/marshalls.h"
#include "os/dir_access.h"
#include "os/file_access.h"
#include "os/keyboard.h"
-#include "io/marshalls.h"
-#include "bind/core_bind.h"
#include "os/os.h"
-#include "io/file_access_pack.h"
-#include "io/file_access_network.h"
#include "variant_parser.h"
#define FORMAT_VERSION 3
-GlobalConfig *GlobalConfig::singleton=NULL;
+GlobalConfig *GlobalConfig::singleton = NULL;
GlobalConfig *GlobalConfig::get_singleton() {
@@ -52,24 +52,23 @@ String GlobalConfig::get_resource_path() const {
return resource_path;
};
-String GlobalConfig::localize_path(const String& p_path) const {
+String GlobalConfig::localize_path(const String &p_path) const {
- if (resource_path=="")
+ if (resource_path == "")
return p_path; //not initialied yet
if (p_path.begins_with("res://") || p_path.begins_with("user://") ||
- (p_path.is_abs_path() && !p_path.begins_with(resource_path)))
+ (p_path.is_abs_path() && !p_path.begins_with(resource_path)))
return p_path.simplify_path();
-
DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- String path = p_path.replace("\\","/").simplify_path();
+ String path = p_path.replace("\\", "/").simplify_path();
- if (dir->change_dir(path)==OK) {
+ if (dir->change_dir(path) == OK) {
String cwd = dir->get_current_dir();
- cwd = cwd.replace("\\","/");
+ cwd = cwd.replace("\\", "/");
memdelete(dir);
@@ -84,10 +83,9 @@ String GlobalConfig::localize_path(const String& p_path) const {
int sep = path.find_last("/");
if (sep == -1) {
- return "res://"+path;
+ return "res://" + path;
};
-
String parent = path.substr(0, sep);
String plocal = localize_path(parent);
@@ -96,23 +94,21 @@ String GlobalConfig::localize_path(const String& p_path) const {
};
return plocal + path.substr(sep, path.size() - sep);
};
-
}
-void GlobalConfig::set_initial_value(const String& p_name, const Variant & p_value) {
+void GlobalConfig::set_initial_value(const String &p_name, const Variant &p_value) {
ERR_FAIL_COND(!props.has(p_name));
- props[p_name].initial=p_value;
+ props[p_name].initial = p_value;
}
-
-String GlobalConfig::globalize_path(const String& p_path) const {
+String GlobalConfig::globalize_path(const String &p_path) const {
if (p_path.begins_with("res://")) {
if (resource_path != "") {
- return p_path.replace("res:/",resource_path);
+ return p_path.replace("res:/", resource_path);
};
return p_path.replace("res://", "");
};
@@ -120,63 +116,59 @@ String GlobalConfig::globalize_path(const String& p_path) const {
return p_path;
}
-
-bool GlobalConfig::_set(const StringName& p_name, const Variant& p_value) {
+bool GlobalConfig::_set(const StringName &p_name, const Variant &p_value) {
_THREAD_SAFE_METHOD_
-
- if (p_value.get_type()==Variant::NIL)
+ if (p_value.get_type() == Variant::NIL)
props.erase(p_name);
else {
if (props.has(p_name)) {
if (!props[p_name].overrided)
- props[p_name].variant=p_value;
+ props[p_name].variant = p_value;
- if (props[p_name].order>=NO_ORDER_BASE && registering_order) {
- props[p_name].order=last_order++;
+ if (props[p_name].order >= NO_ORDER_BASE && registering_order) {
+ props[p_name].order = last_order++;
}
} else {
- props[p_name]=VariantContainer(p_value,last_order++ + (registering_order?0:NO_ORDER_BASE));
+ props[p_name] = VariantContainer(p_value, last_order++ + (registering_order ? 0 : NO_ORDER_BASE));
}
}
if (!disable_platform_override) {
- String s=String(p_name);
+ String s = String(p_name);
int sl = s.find("/");
int p = s.find(".");
- if (p!=-1 && sl!=-1 && p < sl) {
+ if (p != -1 && sl != -1 && p < sl) {
- Vector<String> ps = s.substr(0,sl).split(".");
- String prop=s.substr(sl,s.length()-sl);
- for(int i=1;i<ps.size();i++) {
+ Vector<String> ps = s.substr(0, sl).split(".");
+ String prop = s.substr(sl, s.length() - sl);
+ for (int i = 1; i < ps.size(); i++) {
- if (ps[i]==OS::get_singleton()->get_name()) {
+ if (ps[i] == OS::get_singleton()->get_name()) {
- String fullprop=ps[0]+prop;
+ String fullprop = ps[0] + prop;
- set(fullprop,p_value);
- props[fullprop].overrided=true;
+ set(fullprop, p_value);
+ props[fullprop].overrided = true;
}
}
}
-
}
return true;
}
-bool GlobalConfig::_get(const StringName& p_name,Variant &r_ret) const {
+bool GlobalConfig::_get(const StringName &p_name, Variant &r_ret) const {
_THREAD_SAFE_METHOD_
if (!props.has(p_name)) {
- print_line("WARNING: not found: "+String(p_name));
+ print_line("WARNING: not found: " + String(p_name));
return false;
}
- r_ret=props[p_name].variant;
+ r_ret = props[p_name].variant;
return true;
-
}
struct _VCSort {
@@ -186,7 +178,7 @@ struct _VCSort {
int order;
int flags;
- bool operator<(const _VCSort& p_vcs) const{ return order==p_vcs.order?name<p_vcs.name:order< p_vcs.order; }
+ bool operator<(const _VCSort &p_vcs) const { return order == p_vcs.order ? name < p_vcs.name : order < p_vcs.order; }
};
void GlobalConfig::_get_property_list(List<PropertyInfo> *p_list) const {
@@ -195,66 +187,63 @@ void GlobalConfig::_get_property_list(List<PropertyInfo> *p_list) const {
Set<_VCSort> vclist;
- for(Map<StringName,VariantContainer>::Element *E=props.front();E;E=E->next()) {
+ for (Map<StringName, VariantContainer>::Element *E = props.front(); E; E = E->next()) {
- const VariantContainer *v=&E->get();
+ const VariantContainer *v = &E->get();
if (v->hide_from_editor)
continue;
_VCSort vc;
- vc.name=E->key();
- vc.order=v->order;
- vc.type=v->variant.get_type();
+ vc.name = E->key();
+ vc.order = v->order;
+ vc.type = v->variant.get_type();
if (vc.name.begins_with("input/") || vc.name.begins_with("import/") || vc.name.begins_with("export/") || vc.name.begins_with("/remap") || vc.name.begins_with("/locale") || vc.name.begins_with("/autoload"))
- vc.flags=PROPERTY_USAGE_STORAGE;
+ vc.flags = PROPERTY_USAGE_STORAGE;
else
- vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE;
+ vc.flags = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE;
vclist.insert(vc);
}
- for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) {
+ for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) {
if (custom_prop_info.has(E->get().name)) {
- PropertyInfo pi=custom_prop_info[E->get().name];
- pi.name=E->get().name;
- pi.usage=E->get().flags;
- p_list->push_back( pi );
+ PropertyInfo pi = custom_prop_info[E->get().name];
+ pi.name = E->get().name;
+ pi.usage = E->get().flags;
+ p_list->push_back(pi);
} else
- p_list->push_back( PropertyInfo(E->get().type, E->get().name,PROPERTY_HINT_NONE,"",E->get().flags) );
+ p_list->push_back(PropertyInfo(E->get().type, E->get().name, PROPERTY_HINT_NONE, "", E->get().flags));
}
}
-
-
-bool GlobalConfig::_load_resource_pack(const String& p_pack) {
+bool GlobalConfig::_load_resource_pack(const String &p_pack) {
if (PackedData::get_singleton()->is_disabled())
return false;
- bool ok = PackedData::get_singleton()->add_pack(p_pack)==OK;
+ bool ok = PackedData::get_singleton()->add_pack(p_pack) == OK;
if (!ok)
return false;
//if data.pck is found, all directory access will be from here
DirAccess::make_default<DirAccessPack>(DirAccess::ACCESS_RESOURCES);
- using_datapack=true;
+ using_datapack = true;
return true;
}
-Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) {
+Error GlobalConfig::setup(const String &p_path, const String &p_main_pack) {
//If looking for files in network, just use network!
if (FileAccessNetworkClient::get_singleton()) {
- if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) {
+ if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) {
_load_settings("res://override.cfg");
-
}
return OK;
@@ -264,56 +253,47 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) {
//Attempt with a passed main pack first
- if (p_main_pack!="") {
+ if (p_main_pack != "") {
bool ok = _load_resource_pack(p_main_pack);
- ERR_FAIL_COND_V(!ok,ERR_CANT_OPEN);
+ ERR_FAIL_COND_V(!ok, ERR_CANT_OPEN);
- if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) {
+ if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) {
//load override from location of the main pack
_load_settings(p_main_pack.get_base_dir().plus_file("override.cfg"));
-
}
return OK;
-
}
//Attempt with execname.pck
- if (exec_path!="") {
-
+ if (exec_path != "") {
- if (_load_resource_pack(exec_path.get_basename()+".pck")) {
+ if (_load_resource_pack(exec_path.get_basename() + ".pck")) {
- if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) {
+ if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) {
//load override from location of executable
_load_settings(exec_path.get_base_dir().plus_file("override.cfg"));
-
}
-
-
return OK;
}
-
}
-
//Try to use the filesystem for files, according to OS. (only Android -when reading from pck- and iOS use this)
- if (OS::get_singleton()->get_resource_dir()!="") {
+ if (OS::get_singleton()->get_resource_dir() != "") {
//OS will call Globals->get_resource_path which will be empty if not overriden!
//if the OS would rather use somewhere else, then it will not be empty.
- resource_path=OS::get_singleton()->get_resource_dir().replace("\\","/");
- if (resource_path.length() && resource_path[ resource_path.length()-1]=='/')
- resource_path=resource_path.substr(0,resource_path.length()-1); // chop end
+ resource_path = OS::get_singleton()->get_resource_dir().replace("\\", "/");
+ if (resource_path.length() && resource_path[resource_path.length() - 1] == '/')
+ resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
// data.pck and data.zip are deprecated and no longer supported, apologies.
// make sure this is loaded from the resource path
- if (_load_settings("res://godot.cfg")==OK || _load_settings_binary("res://godot.cfb")==OK) {
+ if (_load_settings("res://godot.cfg") == OK || _load_settings_binary("res://godot.cfb") == OK) {
_load_settings("res://override.cfg");
-
}
return OK;
@@ -322,7 +302,7 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) {
//Nothing was found, try to find a godot.cfg somewhere!
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- ERR_FAIL_COND_V(!d,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!d, ERR_CANT_CREATE);
d->change_dir(p_path);
@@ -330,33 +310,32 @@ Error GlobalConfig::setup(const String& p_path,const String & p_main_pack) {
String current_dir = d->get_current_dir();
bool found = false;
- while(true) {
+ while (true) {
//try to load settings in ascending through dirs shape!
- if (_load_settings(current_dir+"/godot.cfg")==OK || _load_settings_binary(current_dir+"/godot.cfb")==OK) {
+ if (_load_settings(current_dir + "/godot.cfg") == OK || _load_settings_binary(current_dir + "/godot.cfb") == OK) {
- _load_settings(current_dir+"/override.cfg");
- candidate=current_dir;
- found=true;
+ _load_settings(current_dir + "/override.cfg");
+ candidate = current_dir;
+ found = true;
break;
}
d->change_dir("..");
- if (d->get_current_dir()==current_dir)
+ if (d->get_current_dir() == current_dir)
break; //not doing anything useful
- current_dir=d->get_current_dir();
+ current_dir = d->get_current_dir();
}
-
- resource_path=candidate;
- resource_path = resource_path.replace("\\","/"); // windows path to unix path just in case
+ resource_path = candidate;
+ resource_path = resource_path.replace("\\", "/"); // windows path to unix path just in case
memdelete(d);
if (!found)
return ERR_FILE_NOT_FOUND;
- if (resource_path.length() && resource_path[ resource_path.length()-1]=='/')
- resource_path=resource_path.substr(0,resource_path.length()-1); // chop end
+ if (resource_path.length() && resource_path[resource_path.length() - 1] == '/')
+ resource_path = resource_path.substr(0, resource_path.length() - 1); // chop end
return OK;
}
@@ -368,24 +347,22 @@ bool GlobalConfig::has(String p_var) const {
return props.has(p_var);
}
-
void GlobalConfig::set_registering_order(bool p_enable) {
- registering_order=p_enable;
+ registering_order = p_enable;
}
Error GlobalConfig::_load_settings_binary(const String p_path) {
Error err;
- FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err);
- if (err!=OK) {
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (err != OK) {
return err;
}
-
uint8_t hdr[4];
- f->get_buffer(hdr,4);
- if (hdr[0]!='E'|| hdr[1]!='C' || hdr[2]!='F' || hdr[3]!='G') {
+ f->get_buffer(hdr, 4);
+ if (hdr[0] != 'E' || hdr[1] != 'C' || hdr[2] != 'F' || hdr[3] != 'G') {
memdelete(f);
ERR_EXPLAIN("Corrupted header in binary godot.cfb (not ECFG)");
@@ -394,111 +371,101 @@ Error GlobalConfig::_load_settings_binary(const String p_path) {
set_registering_order(false);
- uint32_t count=f->get_32();
+ uint32_t count = f->get_32();
- for(uint32_t i=0;i<count;i++) {
+ for (uint32_t i = 0; i < count; i++) {
- uint32_t slen=f->get_32();
+ uint32_t slen = f->get_32();
CharString cs;
- cs.resize(slen+1);
- cs[slen]=0;
- f->get_buffer((uint8_t*)cs.ptr(),slen);
+ cs.resize(slen + 1);
+ cs[slen] = 0;
+ f->get_buffer((uint8_t *)cs.ptr(), slen);
String key;
key.parse_utf8(cs.ptr());
- uint32_t vlen=f->get_32();
+ uint32_t vlen = f->get_32();
Vector<uint8_t> d;
d.resize(vlen);
- f->get_buffer(d.ptr(),vlen);
+ f->get_buffer(d.ptr(), vlen);
Variant value;
- Error err = decode_variant(value,d.ptr(),d.size());
- ERR_EXPLAIN("Error decoding property: "+key);
- ERR_CONTINUE(err!=OK);
- set(key,value);
-
+ Error err = decode_variant(value, d.ptr(), d.size());
+ ERR_EXPLAIN("Error decoding property: " + key);
+ ERR_CONTINUE(err != OK);
+ set(key, value);
}
set_registering_order(true);
-
return OK;
}
Error GlobalConfig::_load_settings(const String p_path) {
-
-
Error err;
- FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
return ERR_CANT_OPEN;
VariantParser::StreamFile stream;
- stream.f=f;
+ stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
- int lines=0;
+ int lines = 0;
String error_text;
String section;
- while(true) {
+ while (true) {
- assign=Variant();
+ assign = Variant();
next_tag.fields.clear();
- next_tag.name=String();
+ next_tag.name = String();
- err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true);
- if (err==ERR_FILE_EOF) {
+ err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
+ if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
- }
- else if (err!=OK) {
- ERR_PRINTS("GlobalConfig::load - "+p_path+":"+itos(lines)+" error: "+error_text);
+ } else if (err != OK) {
+ ERR_PRINTS("GlobalConfig::load - " + p_path + ":" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
- if (assign!=String()) {
- if (section==String() && assign=="config_version") {
+ if (assign != String()) {
+ if (section == String() && assign == "config_version") {
int config_version = value;
if (config_version > FORMAT_VERSION) {
memdelete(f);
- ERR_FAIL_COND_V(config_version > FORMAT_VERSION,ERR_FILE_CANT_OPEN);
+ ERR_FAIL_COND_V(config_version > FORMAT_VERSION, ERR_FILE_CANT_OPEN);
}
-
}
- set(section+"/"+assign,value);
- } else if (next_tag.name!=String()) {
- section=next_tag.name;
+ set(section + "/" + assign, value);
+ } else if (next_tag.name != String()) {
+ section = next_tag.name;
}
}
memdelete(f);
return OK;
-
}
+int GlobalConfig::get_order(const String &p_name) const {
-
-int GlobalConfig::get_order(const String& p_name) const {
-
- ERR_FAIL_COND_V(!props.has(p_name),-1);
+ ERR_FAIL_COND_V(!props.has(p_name), -1);
return props[p_name].order;
}
-
-void GlobalConfig::set_order(const String& p_name, int p_order){
+void GlobalConfig::set_order(const String &p_name, int p_order) {
ERR_FAIL_COND(!props.has(p_name));
- props[p_name].order=p_order;
+ props[p_name].order = p_order;
}
-void GlobalConfig::clear(const String& p_name) {
+void GlobalConfig::clear(const String &p_name) {
ERR_FAIL_COND(!props.has(p_name));
props.erase(p_name);
@@ -506,28 +473,27 @@ void GlobalConfig::clear(const String& p_name) {
Error GlobalConfig::save() {
- return save_custom(get_resource_path()+"/godot.cfg");
+ return save_custom(get_resource_path() + "/godot.cfg");
}
-Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) {
-
+Error GlobalConfig::_save_settings_binary(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom) {
Error err;
- FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err);
- if (err!=OK) {
+ FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
+ if (err != OK) {
- ERR_EXPLAIN("Coudln't save godot.cfb at "+p_file);
- ERR_FAIL_COND_V(err,err)
+ ERR_EXPLAIN("Coudln't save godot.cfb at " + p_file);
+ ERR_FAIL_COND_V(err, err)
}
- uint8_t hdr[4]={'E','C','F','G'};
- file->store_buffer(hdr,4);
+ uint8_t hdr[4] = { 'E', 'C', 'F', 'G' };
+ file->store_buffer(hdr, 4);
- int count=0;
+ int count = 0;
- for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) {
+ for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
- for(List<String>::Element *F=E->get().front();F;F=F->next()) {
+ for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
count++;
}
@@ -535,17 +501,16 @@ Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String,
file->store_32(count); //store how many properties are saved
+ for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
- for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) {
-
- for(List<String>::Element *F=E->get().front();F;F=F->next()) {
+ for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
String key = F->get();
- if (E->key()!="")
- key=E->key()+"/"+key;
+ if (E->key() != "")
+ key = E->key() + "/" + key;
Variant value;
if (p_custom.has(key))
- value=p_custom[key];
+ value = p_custom[key];
else
value = get(key);
@@ -553,67 +518,62 @@ Error GlobalConfig::_save_settings_binary(const String& p_file,const Map<String,
file->store_string(key);
int len;
- Error err = encode_variant(value,NULL,len);
- if (err!=OK)
+ Error err = encode_variant(value, NULL, len);
+ if (err != OK)
memdelete(file);
- ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
Vector<uint8_t> buff;
buff.resize(len);
- err = encode_variant(value,&buff[0],len);
- if (err!=OK)
+ err = encode_variant(value, &buff[0], len);
+ if (err != OK)
memdelete(file);
- ERR_FAIL_COND_V( err != OK, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(err != OK, ERR_INVALID_DATA);
file->store_32(len);
- file->store_buffer(buff.ptr(),buff.size());
+ file->store_buffer(buff.ptr(), buff.size());
}
}
file->close();
memdelete(file);
-
return OK;
}
-
-Error GlobalConfig::_save_settings_text(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom) {
+Error GlobalConfig::_save_settings_text(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom) {
Error err;
- FileAccess *file = FileAccess::open(p_file,FileAccess::WRITE,&err);
+ FileAccess *file = FileAccess::open(p_file, FileAccess::WRITE, &err);
if (err) {
- ERR_EXPLAIN("Coudln't save godot.cfg - "+p_file);
- ERR_FAIL_COND_V(err,err)
+ ERR_EXPLAIN("Coudln't save godot.cfg - " + p_file);
+ ERR_FAIL_COND_V(err, err)
}
- file->store_string("config_version="+itos(FORMAT_VERSION)+"\n");
+ file->store_string("config_version=" + itos(FORMAT_VERSION) + "\n");
+ for (Map<String, List<String> >::Element *E = props.front(); E; E = E->next()) {
- for(Map<String,List<String> >::Element *E=props.front();E;E=E->next()) {
-
- if (E!=props.front())
+ if (E != props.front())
file->store_string("\n");
- if (E->key()!="")
- file->store_string("["+E->key()+"]\n\n");
- for(List<String>::Element *F=E->get().front();F;F=F->next()) {
+ if (E->key() != "")
+ file->store_string("[" + E->key() + "]\n\n");
+ for (List<String>::Element *F = E->get().front(); F; F = F->next()) {
String key = F->get();
- if (E->key()!="")
- key=E->key()+"/"+key;
+ if (E->key() != "")
+ key = E->key() + "/" + key;
Variant value;
if (p_custom.has(key))
- value=p_custom[key];
+ value = p_custom[key];
else
value = get(key);
-
String vstr;
- VariantWriter::write_to_string(value,vstr);
- file->store_string(F->get()+"="+vstr+"\n");
-
+ VariantWriter::write_to_string(value, vstr);
+ file->store_string(F->get() + "=" + vstr + "\n");
}
}
@@ -628,15 +588,15 @@ Error GlobalConfig::_save_custom_bnd(const String &p_file) { // add other params
return save_custom(p_file);
};
-Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,const Set<String>& p_ignore_masks) {
+Error GlobalConfig::save_custom(const String &p_path, const CustomMap &p_custom, const Set<String> &p_ignore_masks) {
- ERR_FAIL_COND_V(p_path=="",ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_path == "", ERR_INVALID_PARAMETER);
Set<_VCSort> vclist;
- for(Map<StringName,VariantContainer>::Element *G=props.front();G;G=G->next()) {
+ for (Map<StringName, VariantContainer>::Element *G = props.front(); G; G = G->next()) {
- const VariantContainer *v=&G->get();
+ const VariantContainer *v = &G->get();
if (v->hide_from_editor)
continue;
@@ -644,12 +604,12 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c
if (p_custom.has(G->key()))
continue;
- bool discard=false;
+ bool discard = false;
- for(const Set<String>::Element *E=p_ignore_masks.front();E;E=E->next()) {
+ for (const Set<String>::Element *E = p_ignore_masks.front(); E; E = E->next()) {
- if ( String(G->key()).match(E->get())) {
- discard=true;
+ if (String(G->key()).match(E->get())) {
+ discard = true;
break;
}
}
@@ -658,57 +618,53 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c
continue;
_VCSort vc;
- vc.name=G->key();//*k;
- vc.order=v->order;
- vc.type=v->variant.get_type();
- vc.flags=PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_STORAGE;
- if (v->variant==v->initial)
+ vc.name = G->key(); //*k;
+ vc.order = v->order;
+ vc.type = v->variant.get_type();
+ vc.flags = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_STORAGE;
+ if (v->variant == v->initial)
continue;
-
vclist.insert(vc);
}
- for(const Map<String,Variant>::Element *E=p_custom.front();E;E=E->next()) {
-
+ for (const Map<String, Variant>::Element *E = p_custom.front(); E; E = E->next()) {
_VCSort vc;
- vc.name=E->key();
- vc.order=0xFFFFFFF;
- vc.type=E->get().get_type();
- vc.flags=PROPERTY_USAGE_STORAGE;
+ vc.name = E->key();
+ vc.order = 0xFFFFFFF;
+ vc.type = E->get().get_type();
+ vc.flags = PROPERTY_USAGE_STORAGE;
vclist.insert(vc);
}
- Map<String,List<String> > props;
+ Map<String, List<String> > props;
- for(Set<_VCSort>::Element *E=vclist.front();E;E=E->next()) {
+ for (Set<_VCSort>::Element *E = vclist.front(); E; E = E->next()) {
String category = E->get().name;
String name = E->get().name;
int div = category.find("/");
- if (div<0)
- category="";
+ if (div < 0)
+ category = "";
else {
- category=category.substr(0,div);
- name=name.substr(div+1,name.size());
+ category = category.substr(0, div);
+ name = name.substr(div + 1, name.size());
}
props[category].push_back(name);
}
-
-
if (p_path.ends_with(".cfg"))
- return _save_settings_text(p_path,props,p_custom);
+ return _save_settings_text(p_path, props, p_custom);
else if (p_path.ends_with(".cfb"))
- return _save_settings_binary(p_path,props,p_custom);
+ return _save_settings_binary(p_path, props, p_custom);
else {
- ERR_EXPLAIN("Unknown config file format: "+p_path);
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ ERR_EXPLAIN("Unknown config file format: " + p_path);
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
}
return OK;
@@ -754,43 +710,40 @@ Error GlobalConfig::save_custom(const String& p_path,const CustomMap& p_custom,c
#endif
}
-Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default) {
+Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default) {
if (GlobalConfig::get_singleton()->has(p_var)) {
- GlobalConfig::get_singleton()->set_initial_value(p_var,p_default);
+ GlobalConfig::get_singleton()->set_initial_value(p_var, p_default);
return GlobalConfig::get_singleton()->get(p_var);
}
- GlobalConfig::get_singleton()->set(p_var,p_default);
- GlobalConfig::get_singleton()->set_initial_value(p_var,p_default);
+ GlobalConfig::get_singleton()->set(p_var, p_default);
+ GlobalConfig::get_singleton()->set_initial_value(p_var, p_default);
return p_default;
-
}
void GlobalConfig::add_singleton(const Singleton &p_singleton) {
singletons.push_back(p_singleton);
- singleton_ptrs[p_singleton.name]=p_singleton.ptr;
+ singleton_ptrs[p_singleton.name] = p_singleton.ptr;
}
-Object* GlobalConfig::get_singleton_object(const String& p_name) const {
+Object *GlobalConfig::get_singleton_object(const String &p_name) const {
-
- const Map<StringName,Object*>::Element *E=singleton_ptrs.find(p_name);
+ const Map<StringName, Object *>::Element *E = singleton_ptrs.find(p_name);
if (!E)
return NULL;
else
return E->get();
-
};
-bool GlobalConfig::has_singleton(const String& p_name) const {
+bool GlobalConfig::has_singleton(const String &p_name) const {
return get_singleton_object(p_name) != NULL;
};
void GlobalConfig::get_singletons(List<Singleton> *p_singletons) {
- for(List<Singleton>::Element *E=singletons.front();E;E=E->next())
+ for (List<Singleton>::Element *E = singletons.front(); E; E = E->next())
p_singletons->push_back(E->get());
}
@@ -800,20 +753,19 @@ Vector<String> GlobalConfig::get_optimizer_presets() const {
GlobalConfig::get_singleton()->get_property_list(&pi);
Vector<String> names;
- for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
if (!E->get().name.begins_with("optimizer_presets/"))
continue;
- names.push_back(E->get().name.get_slicec('/',1));
+ names.push_back(E->get().name.get_slicec('/', 1));
}
names.sort();
return names;
-
}
-void GlobalConfig::_add_property_info_bind(const Dictionary& p_info) {
+void GlobalConfig::_add_property_info_bind(const Dictionary &p_info) {
ERR_FAIL_COND(!p_info.has("name"));
ERR_FAIL_COND(!p_info.has("type"));
@@ -832,17 +784,16 @@ void GlobalConfig::_add_property_info_bind(const Dictionary& p_info) {
set_custom_property_info(pinfo.name, pinfo);
}
-void GlobalConfig::set_custom_property_info(const String& p_prop,const PropertyInfo& p_info) {
+void GlobalConfig::set_custom_property_info(const String &p_prop, const PropertyInfo &p_info) {
ERR_FAIL_COND(!props.has(p_prop));
- custom_prop_info[p_prop]=p_info;
- custom_prop_info[p_prop].name=p_prop;
-
+ custom_prop_info[p_prop] = p_info;
+ custom_prop_info[p_prop].name = p_prop;
}
void GlobalConfig::set_disable_platform_override(bool p_disable) {
- disable_platform_override=p_disable;
+ disable_platform_override = p_disable;
}
bool GlobalConfig::is_using_datapack() const {
@@ -850,16 +801,15 @@ bool GlobalConfig::is_using_datapack() const {
return using_datapack;
}
-bool GlobalConfig::property_can_revert(const String& p_name) {
+bool GlobalConfig::property_can_revert(const String &p_name) {
if (!props.has(p_name))
return false;
- return props[p_name].initial!=props[p_name].variant;
-
+ return props[p_name].initial != props[p_name].variant;
}
-Variant GlobalConfig::property_get_revert(const String& p_name) {
+Variant GlobalConfig::property_get_revert(const String &p_name) {
if (!props.has(p_name))
return Variant();
@@ -869,150 +819,140 @@ Variant GlobalConfig::property_get_revert(const String& p_name) {
void GlobalConfig::_bind_methods() {
- ClassDB::bind_method(D_METHOD("has","name"),&GlobalConfig::has);
- ClassDB::bind_method(D_METHOD("set_order","name","pos"),&GlobalConfig::set_order);
- ClassDB::bind_method(D_METHOD("get_order","name"),&GlobalConfig::get_order);
- ClassDB::bind_method(D_METHOD("set_initial_value","name","value"),&GlobalConfig::set_initial_value);
- ClassDB::bind_method(D_METHOD("add_property_info", "hint"),&GlobalConfig::_add_property_info_bind);
- ClassDB::bind_method(D_METHOD("clear","name"),&GlobalConfig::clear);
- ClassDB::bind_method(D_METHOD("localize_path","path"),&GlobalConfig::localize_path);
- ClassDB::bind_method(D_METHOD("globalize_path","path"),&GlobalConfig::globalize_path);
- ClassDB::bind_method(D_METHOD("save"),&GlobalConfig::save);
- ClassDB::bind_method(D_METHOD("has_singleton","name"),&GlobalConfig::has_singleton);
- ClassDB::bind_method(D_METHOD("get_singleton","name"),&GlobalConfig::get_singleton_object);
- ClassDB::bind_method(D_METHOD("load_resource_pack","pack"),&GlobalConfig::_load_resource_pack);
- ClassDB::bind_method(D_METHOD("property_can_revert","name"),&GlobalConfig::property_can_revert);
- ClassDB::bind_method(D_METHOD("property_get_revert","name"),&GlobalConfig::property_get_revert);
-
- ClassDB::bind_method(D_METHOD("save_custom","file"),&GlobalConfig::_save_custom_bnd);
+ ClassDB::bind_method(D_METHOD("has", "name"), &GlobalConfig::has);
+ ClassDB::bind_method(D_METHOD("set_order", "name", "pos"), &GlobalConfig::set_order);
+ ClassDB::bind_method(D_METHOD("get_order", "name"), &GlobalConfig::get_order);
+ ClassDB::bind_method(D_METHOD("set_initial_value", "name", "value"), &GlobalConfig::set_initial_value);
+ ClassDB::bind_method(D_METHOD("add_property_info", "hint"), &GlobalConfig::_add_property_info_bind);
+ ClassDB::bind_method(D_METHOD("clear", "name"), &GlobalConfig::clear);
+ ClassDB::bind_method(D_METHOD("localize_path", "path"), &GlobalConfig::localize_path);
+ ClassDB::bind_method(D_METHOD("globalize_path", "path"), &GlobalConfig::globalize_path);
+ ClassDB::bind_method(D_METHOD("save"), &GlobalConfig::save);
+ ClassDB::bind_method(D_METHOD("has_singleton", "name"), &GlobalConfig::has_singleton);
+ ClassDB::bind_method(D_METHOD("get_singleton", "name"), &GlobalConfig::get_singleton_object);
+ ClassDB::bind_method(D_METHOD("load_resource_pack", "pack"), &GlobalConfig::_load_resource_pack);
+ ClassDB::bind_method(D_METHOD("property_can_revert", "name"), &GlobalConfig::property_can_revert);
+ ClassDB::bind_method(D_METHOD("property_get_revert", "name"), &GlobalConfig::property_get_revert);
+ ClassDB::bind_method(D_METHOD("save_custom", "file"), &GlobalConfig::_save_custom_bnd);
}
GlobalConfig::GlobalConfig() {
-
- singleton=this;
- last_order=0;
- disable_platform_override=false;
- registering_order=true;
-
+ singleton = this;
+ last_order = 0;
+ disable_platform_override = false;
+ registering_order = true;
Array va;
InputEvent key;
- key.type=InputEvent::KEY;
+ key.type = InputEvent::KEY;
InputEvent joyb;
- joyb.type=InputEvent::JOYPAD_BUTTON;
-
-
- GLOBAL_DEF("application/name","" );
- GLOBAL_DEF("application/main_scene","");
- custom_prop_info["application/main_scene"]=PropertyInfo(Variant::STRING,"application/main_scene",PROPERTY_HINT_FILE,"tscn,scn,xscn,xml,res");
- GLOBAL_DEF("application/disable_stdout",false);
- GLOBAL_DEF("application/disable_stderr",false);
- GLOBAL_DEF("application/use_shared_user_dir",true);
+ joyb.type = InputEvent::JOYPAD_BUTTON;
+ GLOBAL_DEF("application/name", "");
+ GLOBAL_DEF("application/main_scene", "");
+ custom_prop_info["application/main_scene"] = PropertyInfo(Variant::STRING, "application/main_scene", PROPERTY_HINT_FILE, "tscn,scn,xscn,xml,res");
+ GLOBAL_DEF("application/disable_stdout", false);
+ GLOBAL_DEF("application/disable_stderr", false);
+ GLOBAL_DEF("application/use_shared_user_dir", true);
- key.key.scancode=KEY_RETURN;
+ key.key.scancode = KEY_RETURN;
va.push_back(key);
- key.key.scancode=KEY_ENTER;
+ key.key.scancode = KEY_ENTER;
va.push_back(key);
- key.key.scancode=KEY_SPACE;
+ key.key.scancode = KEY_SPACE;
va.push_back(key);
- joyb.joy_button.button_index=JOY_BUTTON_0;
+ joyb.joy_button.button_index = JOY_BUTTON_0;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_accept",va);
+ GLOBAL_DEF("input/ui_accept", va);
input_presets.push_back("input/ui_accept");
- va=Array();
- key.key.scancode=KEY_SPACE;
+ va = Array();
+ key.key.scancode = KEY_SPACE;
va.push_back(key);
- joyb.joy_button.button_index=JOY_BUTTON_3;
+ joyb.joy_button.button_index = JOY_BUTTON_3;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_select",va);
+ GLOBAL_DEF("input/ui_select", va);
input_presets.push_back("input/ui_select");
- va=Array();
- key.key.scancode=KEY_ESCAPE;
+ va = Array();
+ key.key.scancode = KEY_ESCAPE;
va.push_back(key);
- joyb.joy_button.button_index=JOY_BUTTON_1;
+ joyb.joy_button.button_index = JOY_BUTTON_1;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_cancel",va);
+ GLOBAL_DEF("input/ui_cancel", va);
input_presets.push_back("input/ui_cancel");
- va=Array();
- key.key.scancode=KEY_TAB;
+ va = Array();
+ key.key.scancode = KEY_TAB;
va.push_back(key);
- GLOBAL_DEF("input/ui_focus_next",va);
+ GLOBAL_DEF("input/ui_focus_next", va);
input_presets.push_back("input/ui_focus_next");
- va=Array();
- key.key.scancode=KEY_TAB;
- key.key.mod.shift=true;
+ va = Array();
+ key.key.scancode = KEY_TAB;
+ key.key.mod.shift = true;
va.push_back(key);
- GLOBAL_DEF("input/ui_focus_prev",va);
+ GLOBAL_DEF("input/ui_focus_prev", va);
input_presets.push_back("input/ui_focus_prev");
- key.key.mod.shift=false;
+ key.key.mod.shift = false;
- va=Array();
- key.key.scancode=KEY_LEFT;
+ va = Array();
+ key.key.scancode = KEY_LEFT;
va.push_back(key);
- joyb.joy_button.button_index=JOY_DPAD_LEFT;
+ joyb.joy_button.button_index = JOY_DPAD_LEFT;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_left",va);
+ GLOBAL_DEF("input/ui_left", va);
input_presets.push_back("input/ui_left");
- va=Array();
- key.key.scancode=KEY_RIGHT;
+ va = Array();
+ key.key.scancode = KEY_RIGHT;
va.push_back(key);
- joyb.joy_button.button_index=JOY_DPAD_RIGHT;
+ joyb.joy_button.button_index = JOY_DPAD_RIGHT;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_right",va);
+ GLOBAL_DEF("input/ui_right", va);
input_presets.push_back("input/ui_right");
- va=Array();
- key.key.scancode=KEY_UP;
+ va = Array();
+ key.key.scancode = KEY_UP;
va.push_back(key);
- joyb.joy_button.button_index=JOY_DPAD_UP;
+ joyb.joy_button.button_index = JOY_DPAD_UP;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_up",va);
+ GLOBAL_DEF("input/ui_up", va);
input_presets.push_back("input/ui_up");
- va=Array();
- key.key.scancode=KEY_DOWN;
+ va = Array();
+ key.key.scancode = KEY_DOWN;
va.push_back(key);
- joyb.joy_button.button_index=JOY_DPAD_DOWN;
+ joyb.joy_button.button_index = JOY_DPAD_DOWN;
va.push_back(joyb);
- GLOBAL_DEF("input/ui_down",va);
+ GLOBAL_DEF("input/ui_down", va);
input_presets.push_back("input/ui_down");
-
- va=Array();
- key.key.scancode=KEY_PAGEUP;
+ va = Array();
+ key.key.scancode = KEY_PAGEUP;
va.push_back(key);
- GLOBAL_DEF("input/ui_page_up",va);
+ GLOBAL_DEF("input/ui_page_up", va);
input_presets.push_back("input/ui_page_up");
- va=Array();
- key.key.scancode=KEY_PAGEDOWN;
+ va = Array();
+ key.key.scancode = KEY_PAGEDOWN;
va.push_back(key);
- GLOBAL_DEF("input/ui_page_down",va);
+ GLOBAL_DEF("input/ui_page_down", va);
input_presets.push_back("input/ui_page_down");
//GLOBAL_DEF("display/handheld/orientation", "landscape");
+ custom_prop_info["display/handheld/orientation"] = PropertyInfo(Variant::STRING, "display/handheld/orientation", PROPERTY_HINT_ENUM, "landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor");
+ custom_prop_info["rendering/threads/thread_model"] = PropertyInfo(Variant::INT, "rendering/threads/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded");
+ custom_prop_info["physics/2d/thread_model"] = PropertyInfo(Variant::INT, "physics/2d/thread_model", PROPERTY_HINT_ENUM, "Single-Unsafe,Single-Safe,Multi-Threaded");
- custom_prop_info["display/handheld/orientation"]=PropertyInfo(Variant::STRING,"display/handheld/orientation",PROPERTY_HINT_ENUM,"landscape,portrait,reverse_landscape,reverse_portrait,sensor_landscape,sensor_portrait,sensor");
- custom_prop_info["rendering/threads/thread_model"]=PropertyInfo(Variant::INT,"rendering/threads/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded");
- custom_prop_info["physics/2d/thread_model"]=PropertyInfo(Variant::INT,"physics/2d/thread_model",PROPERTY_HINT_ENUM,"Single-Unsafe,Single-Safe,Multi-Threaded");
-
- GLOBAL_DEF("debug/profiler/max_functions",16384);
- using_datapack=false;
+ GLOBAL_DEF("debug/profiler/max_functions", 16384);
+ using_datapack = false;
}
-
GlobalConfig::~GlobalConfig() {
- singleton=NULL;
+ singleton = NULL;
}
-
-
diff --git a/core/global_config.h b/core/global_config.h
index 471f1ff885..7bdf356129 100644
--- a/core/global_config.h
+++ b/core/global_config.h
@@ -30,32 +30,32 @@
#define GLOBAL_CONFIG_H
#include "object.h"
-#include "set.h"
#include "os/thread_safe.h"
+#include "set.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class GlobalConfig : public Object {
- GDCLASS( GlobalConfig, Object );
+ GDCLASS(GlobalConfig, Object);
_THREAD_SAFE_CLASS_
public:
-
- typedef Map<String,Variant> CustomMap;
+ typedef Map<String, Variant> CustomMap;
struct Singleton {
StringName name;
Object *ptr;
- Singleton(const StringName& p_name=StringName(), Object *p_ptr=NULL) { name=p_name; ptr=p_ptr; }
+ Singleton(const StringName &p_name = StringName(), Object *p_ptr = NULL) {
+ name = p_name;
+ ptr = p_ptr;
+ }
};
protected:
-
enum {
- NO_ORDER_BASE=1<<18
+ NO_ORDER_BASE = 1 << 18
};
struct VariantContainer {
@@ -65,22 +65,32 @@ protected:
Variant initial;
bool hide_from_editor;
bool overrided;
- VariantContainer(){ order=0; hide_from_editor=false; persist=false; overrided=false; }
- VariantContainer(const Variant& p_variant, int p_order, bool p_persist=false) { variant=p_variant; order=p_order; hide_from_editor=false; persist=p_persist; overrided=false; }
+ VariantContainer() {
+ order = 0;
+ hide_from_editor = false;
+ persist = false;
+ overrided = false;
+ }
+ VariantContainer(const Variant &p_variant, int p_order, bool p_persist = false) {
+ variant = p_variant;
+ order = p_order;
+ hide_from_editor = false;
+ persist = p_persist;
+ overrided = false;
+ }
};
bool registering_order;
int last_order;
- Map<StringName,VariantContainer> props;
+ Map<StringName, VariantContainer> props;
String resource_path;
- Map<StringName,PropertyInfo> custom_prop_info;
+ Map<StringName, PropertyInfo> custom_prop_info;
bool disable_platform_override;
bool using_datapack;
List<String> input_presets;
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
static GlobalConfig *singleton;
@@ -88,58 +98,55 @@ protected:
Error _load_settings(const String p_path);
Error _load_settings_binary(const String p_path);
- Error _save_settings_text(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom=CustomMap());
- Error _save_settings_binary(const String& p_file,const Map<String,List<String> > &props,const CustomMap& p_custom=CustomMap());
+ Error _save_settings_text(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom = CustomMap());
+ Error _save_settings_binary(const String &p_file, const Map<String, List<String> > &props, const CustomMap &p_custom = CustomMap());
List<Singleton> singletons;
- Map<StringName,Object*> singleton_ptrs;
+ Map<StringName, Object *> singleton_ptrs;
- Error _save_custom_bnd(const String& p_file);
+ Error _save_custom_bnd(const String &p_file);
- bool _load_resource_pack(const String& p_pack);
+ bool _load_resource_pack(const String &p_pack);
- void _add_property_info_bind(const Dictionary& p_info);
+ void _add_property_info_bind(const Dictionary &p_info);
protected:
-
static void _bind_methods();
-public:
-
+public:
bool has(String p_var) const;
- String localize_path(const String& p_path) const;
- String globalize_path(const String& p_path) const;
-
+ String localize_path(const String &p_path) const;
+ String globalize_path(const String &p_path) const;
- void set_initial_value(const String& p_name, const Variant & p_value);
- bool property_can_revert(const String& p_name);
- Variant property_get_revert(const String& p_name);
+ void set_initial_value(const String &p_name, const Variant &p_value);
+ bool property_can_revert(const String &p_name);
+ Variant property_get_revert(const String &p_name);
String get_resource_path() const;
static GlobalConfig *get_singleton();
- void clear(const String& p_name);
- int get_order(const String& p_name) const;
- void set_order(const String& p_name, int p_order);
+ void clear(const String &p_name);
+ int get_order(const String &p_name) const;
+ void set_order(const String &p_name, int p_order);
- Error setup(const String& p_path, const String &p_main_pack);
+ Error setup(const String &p_path, const String &p_main_pack);
- Error save_custom(const String& p_path="",const CustomMap& p_custom=CustomMap(),const Set<String>& p_ignore_masks=Set<String>());
+ Error save_custom(const String &p_path = "", const CustomMap &p_custom = CustomMap(), const Set<String> &p_ignore_masks = Set<String>());
Error save();
- void set_custom_property_info(const String& p_prop,const PropertyInfo& p_info);
+ void set_custom_property_info(const String &p_prop, const PropertyInfo &p_info);
void add_singleton(const Singleton &p_singleton);
void get_singletons(List<Singleton> *p_singletons);
- bool has_singleton(const String& p_name) const;
+ bool has_singleton(const String &p_name) const;
Vector<String> get_optimizer_presets() const;
List<String> get_input_presets() const { return input_presets; }
void set_disable_platform_override(bool p_disable);
- Object* get_singleton_object(const String& p_name) const;
+ Object *get_singleton_object(const String &p_name) const;
void register_global_defaults();
@@ -149,12 +156,11 @@ public:
GlobalConfig();
~GlobalConfig();
-
};
//not a macro any longer
-Variant _GLOBAL_DEF( const String& p_var, const Variant& p_default);
-#define GLOBAL_DEF(m_var,m_value) _GLOBAL_DEF(m_var,m_value)
+Variant _GLOBAL_DEF(const String &p_var, const Variant &p_default);
+#define GLOBAL_DEF(m_var, m_value) _GLOBAL_DEF(m_var, m_value)
#define GLOBAL_GET(m_var) GlobalConfig::get_singleton()->get(m_var)
#endif
diff --git a/core/global_constants.cpp b/core/global_constants.cpp
index be811ccbd2..c7f353ac44 100644
--- a/core/global_constants.cpp
+++ b/core/global_constants.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "global_constants.h"
-#include "variant.h"
-#include "os/keyboard.h"
#include "object.h"
+#include "os/keyboard.h"
+#include "variant.h"
struct _GlobalConstant {
@@ -38,519 +38,515 @@ struct _GlobalConstant {
int value;
};
-#define BIND_GLOBAL_CONSTANT(m_constant) {#m_constant,m_constant}
-
+#define BIND_GLOBAL_CONSTANT(m_constant) \
+ { #m_constant, m_constant }
-static _GlobalConstant _global_constants[]={
+static _GlobalConstant _global_constants[] = {
-//{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace
+ //{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace
- BIND_GLOBAL_CONSTANT( MARGIN_LEFT ),
- BIND_GLOBAL_CONSTANT( MARGIN_TOP ),
- BIND_GLOBAL_CONSTANT( MARGIN_RIGHT ),
- BIND_GLOBAL_CONSTANT( MARGIN_BOTTOM ),
- BIND_GLOBAL_CONSTANT( VERTICAL ),
- BIND_GLOBAL_CONSTANT( HORIZONTAL ),
- BIND_GLOBAL_CONSTANT( HALIGN_LEFT ),
- BIND_GLOBAL_CONSTANT( HALIGN_CENTER ),
- BIND_GLOBAL_CONSTANT( HALIGN_RIGHT ),
- BIND_GLOBAL_CONSTANT( VALIGN_TOP ),
- BIND_GLOBAL_CONSTANT( VALIGN_CENTER ),
- BIND_GLOBAL_CONSTANT( VALIGN_BOTTOM ),
+ BIND_GLOBAL_CONSTANT(MARGIN_LEFT),
+ BIND_GLOBAL_CONSTANT(MARGIN_TOP),
+ BIND_GLOBAL_CONSTANT(MARGIN_RIGHT),
+ BIND_GLOBAL_CONSTANT(MARGIN_BOTTOM),
+ BIND_GLOBAL_CONSTANT(VERTICAL),
+ BIND_GLOBAL_CONSTANT(HORIZONTAL),
+ BIND_GLOBAL_CONSTANT(HALIGN_LEFT),
+ BIND_GLOBAL_CONSTANT(HALIGN_CENTER),
+ BIND_GLOBAL_CONSTANT(HALIGN_RIGHT),
+ BIND_GLOBAL_CONSTANT(VALIGN_TOP),
+ BIND_GLOBAL_CONSTANT(VALIGN_CENTER),
+ BIND_GLOBAL_CONSTANT(VALIGN_BOTTOM),
// hueg list of keys
- BIND_GLOBAL_CONSTANT( SPKEY ),
-
- BIND_GLOBAL_CONSTANT( KEY_ESCAPE ),
- BIND_GLOBAL_CONSTANT( KEY_TAB ),
- BIND_GLOBAL_CONSTANT( KEY_BACKTAB ),
- BIND_GLOBAL_CONSTANT( KEY_BACKSPACE ),
- BIND_GLOBAL_CONSTANT( KEY_RETURN ),
- BIND_GLOBAL_CONSTANT( KEY_ENTER ),
- BIND_GLOBAL_CONSTANT( KEY_INSERT ),
- BIND_GLOBAL_CONSTANT( KEY_DELETE ),
- BIND_GLOBAL_CONSTANT( KEY_PAUSE ),
- BIND_GLOBAL_CONSTANT( KEY_PRINT ),
- BIND_GLOBAL_CONSTANT( KEY_SYSREQ ),
- BIND_GLOBAL_CONSTANT( KEY_CLEAR ),
- BIND_GLOBAL_CONSTANT( KEY_HOME ),
- BIND_GLOBAL_CONSTANT( KEY_END ),
- BIND_GLOBAL_CONSTANT( KEY_LEFT ),
- BIND_GLOBAL_CONSTANT( KEY_UP ),
- BIND_GLOBAL_CONSTANT( KEY_RIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_DOWN ),
- BIND_GLOBAL_CONSTANT( KEY_PAGEUP ),
- BIND_GLOBAL_CONSTANT( KEY_PAGEDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_SHIFT ),
- BIND_GLOBAL_CONSTANT( KEY_CONTROL ),
- BIND_GLOBAL_CONSTANT( KEY_META ),
- BIND_GLOBAL_CONSTANT( KEY_ALT ),
- BIND_GLOBAL_CONSTANT( KEY_CAPSLOCK ),
- BIND_GLOBAL_CONSTANT( KEY_NUMLOCK ),
- BIND_GLOBAL_CONSTANT( KEY_SCROLLLOCK ),
- BIND_GLOBAL_CONSTANT( KEY_F1 ),
- BIND_GLOBAL_CONSTANT( KEY_F2 ),
- BIND_GLOBAL_CONSTANT( KEY_F3 ),
- BIND_GLOBAL_CONSTANT( KEY_F4 ),
- BIND_GLOBAL_CONSTANT( KEY_F5 ),
- BIND_GLOBAL_CONSTANT( KEY_F6 ),
- BIND_GLOBAL_CONSTANT( KEY_F7 ),
- BIND_GLOBAL_CONSTANT( KEY_F8 ),
- BIND_GLOBAL_CONSTANT( KEY_F9 ),
- BIND_GLOBAL_CONSTANT( KEY_F10 ),
- BIND_GLOBAL_CONSTANT( KEY_F11 ),
- BIND_GLOBAL_CONSTANT( KEY_F12 ),
- BIND_GLOBAL_CONSTANT( KEY_F13 ),
- BIND_GLOBAL_CONSTANT( KEY_F14 ),
- BIND_GLOBAL_CONSTANT( KEY_F15 ),
- BIND_GLOBAL_CONSTANT( KEY_F16 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_ENTER ),
- BIND_GLOBAL_CONSTANT( KEY_KP_MULTIPLY ),
- BIND_GLOBAL_CONSTANT( KEY_KP_DIVIDE ),
- BIND_GLOBAL_CONSTANT( KEY_KP_SUBTRACT ),
- BIND_GLOBAL_CONSTANT( KEY_KP_PERIOD ),
- BIND_GLOBAL_CONSTANT( KEY_KP_ADD ),
- BIND_GLOBAL_CONSTANT( KEY_KP_0 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_1 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_2 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_3 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_4 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_5 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_6 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_7 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_8 ),
- BIND_GLOBAL_CONSTANT( KEY_KP_9 ),
- BIND_GLOBAL_CONSTANT( KEY_SUPER_L ),
- BIND_GLOBAL_CONSTANT( KEY_SUPER_R ),
- BIND_GLOBAL_CONSTANT( KEY_MENU ),
- BIND_GLOBAL_CONSTANT( KEY_HYPER_L ),
- BIND_GLOBAL_CONSTANT( KEY_HYPER_R ),
- BIND_GLOBAL_CONSTANT( KEY_HELP ),
- BIND_GLOBAL_CONSTANT( KEY_DIRECTION_L ),
- BIND_GLOBAL_CONSTANT( KEY_DIRECTION_R ),
- BIND_GLOBAL_CONSTANT( KEY_BACK ),
- BIND_GLOBAL_CONSTANT( KEY_FORWARD ),
- BIND_GLOBAL_CONSTANT( KEY_STOP ),
- BIND_GLOBAL_CONSTANT( KEY_REFRESH ),
- BIND_GLOBAL_CONSTANT( KEY_VOLUMEDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_VOLUMEMUTE ),
- BIND_GLOBAL_CONSTANT( KEY_VOLUMEUP ),
- BIND_GLOBAL_CONSTANT( KEY_BASSBOOST ),
- BIND_GLOBAL_CONSTANT( KEY_BASSUP ),
- BIND_GLOBAL_CONSTANT( KEY_BASSDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_TREBLEUP ),
- BIND_GLOBAL_CONSTANT( KEY_TREBLEDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_MEDIAPLAY ),
- BIND_GLOBAL_CONSTANT( KEY_MEDIASTOP ),
- BIND_GLOBAL_CONSTANT( KEY_MEDIAPREVIOUS ),
- BIND_GLOBAL_CONSTANT( KEY_MEDIANEXT ),
- BIND_GLOBAL_CONSTANT( KEY_MEDIARECORD ),
- BIND_GLOBAL_CONSTANT( KEY_HOMEPAGE ),
- BIND_GLOBAL_CONSTANT( KEY_FAVORITES ),
- BIND_GLOBAL_CONSTANT( KEY_SEARCH ),
- BIND_GLOBAL_CONSTANT( KEY_STANDBY ),
- BIND_GLOBAL_CONSTANT( KEY_OPENURL ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHMAIL ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHMEDIA ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH0 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH1 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH2 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH3 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH4 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH5 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH6 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH7 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH8 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCH9 ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHA ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHB ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHC ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHD ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHE ),
- BIND_GLOBAL_CONSTANT( KEY_LAUNCHF ),
-
- BIND_GLOBAL_CONSTANT( KEY_UNKNOWN ),
- BIND_GLOBAL_CONSTANT( KEY_SPACE ),
- BIND_GLOBAL_CONSTANT( KEY_EXCLAM ),
- BIND_GLOBAL_CONSTANT( KEY_QUOTEDBL ),
- BIND_GLOBAL_CONSTANT( KEY_NUMBERSIGN ),
- BIND_GLOBAL_CONSTANT( KEY_DOLLAR ),
- BIND_GLOBAL_CONSTANT( KEY_PERCENT ),
- BIND_GLOBAL_CONSTANT( KEY_AMPERSAND ),
- BIND_GLOBAL_CONSTANT( KEY_APOSTROPHE ),
- BIND_GLOBAL_CONSTANT( KEY_PARENLEFT ),
- BIND_GLOBAL_CONSTANT( KEY_PARENRIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_ASTERISK ),
- BIND_GLOBAL_CONSTANT( KEY_PLUS ),
- BIND_GLOBAL_CONSTANT( KEY_COMMA ),
- BIND_GLOBAL_CONSTANT( KEY_MINUS ),
- BIND_GLOBAL_CONSTANT( KEY_PERIOD ),
- BIND_GLOBAL_CONSTANT( KEY_SLASH ),
- BIND_GLOBAL_CONSTANT( KEY_0 ),
- BIND_GLOBAL_CONSTANT( KEY_1 ),
- BIND_GLOBAL_CONSTANT( KEY_2 ),
- BIND_GLOBAL_CONSTANT( KEY_3 ),
- BIND_GLOBAL_CONSTANT( KEY_4 ),
- BIND_GLOBAL_CONSTANT( KEY_5 ),
- BIND_GLOBAL_CONSTANT( KEY_6 ),
- BIND_GLOBAL_CONSTANT( KEY_7 ),
- BIND_GLOBAL_CONSTANT( KEY_8 ),
- BIND_GLOBAL_CONSTANT( KEY_9 ),
- BIND_GLOBAL_CONSTANT( KEY_COLON ),
- BIND_GLOBAL_CONSTANT( KEY_SEMICOLON ),
- BIND_GLOBAL_CONSTANT( KEY_LESS ),
- BIND_GLOBAL_CONSTANT( KEY_EQUAL ),
- BIND_GLOBAL_CONSTANT( KEY_GREATER ),
- BIND_GLOBAL_CONSTANT( KEY_QUESTION ),
- BIND_GLOBAL_CONSTANT( KEY_AT ),
- BIND_GLOBAL_CONSTANT( KEY_A ),
- BIND_GLOBAL_CONSTANT( KEY_B ),
- BIND_GLOBAL_CONSTANT( KEY_C ),
- BIND_GLOBAL_CONSTANT( KEY_D ),
- BIND_GLOBAL_CONSTANT( KEY_E ),
- BIND_GLOBAL_CONSTANT( KEY_F ),
- BIND_GLOBAL_CONSTANT( KEY_G ),
- BIND_GLOBAL_CONSTANT( KEY_H ),
- BIND_GLOBAL_CONSTANT( KEY_I ),
- BIND_GLOBAL_CONSTANT( KEY_J ),
- BIND_GLOBAL_CONSTANT( KEY_K ),
- BIND_GLOBAL_CONSTANT( KEY_L ),
- BIND_GLOBAL_CONSTANT( KEY_M ),
- BIND_GLOBAL_CONSTANT( KEY_N ),
- BIND_GLOBAL_CONSTANT( KEY_O ),
- BIND_GLOBAL_CONSTANT( KEY_P ),
- BIND_GLOBAL_CONSTANT( KEY_Q ),
- BIND_GLOBAL_CONSTANT( KEY_R ),
- BIND_GLOBAL_CONSTANT( KEY_S ),
- BIND_GLOBAL_CONSTANT( KEY_T ),
- BIND_GLOBAL_CONSTANT( KEY_U ),
- BIND_GLOBAL_CONSTANT( KEY_V ),
- BIND_GLOBAL_CONSTANT( KEY_W ),
- BIND_GLOBAL_CONSTANT( KEY_X ),
- BIND_GLOBAL_CONSTANT( KEY_Y ),
- BIND_GLOBAL_CONSTANT( KEY_Z ),
- BIND_GLOBAL_CONSTANT( KEY_BRACKETLEFT ),
- BIND_GLOBAL_CONSTANT( KEY_BACKSLASH ),
- BIND_GLOBAL_CONSTANT( KEY_BRACKETRIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_ASCIICIRCUM ),
- BIND_GLOBAL_CONSTANT( KEY_UNDERSCORE ),
- BIND_GLOBAL_CONSTANT( KEY_QUOTELEFT ),
- BIND_GLOBAL_CONSTANT( KEY_BRACELEFT ),
- BIND_GLOBAL_CONSTANT( KEY_BAR ),
- BIND_GLOBAL_CONSTANT( KEY_BRACERIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_ASCIITILDE ),
- BIND_GLOBAL_CONSTANT( KEY_NOBREAKSPACE ),
- BIND_GLOBAL_CONSTANT( KEY_EXCLAMDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_CENT ),
- BIND_GLOBAL_CONSTANT( KEY_STERLING ),
- BIND_GLOBAL_CONSTANT( KEY_CURRENCY ),
- BIND_GLOBAL_CONSTANT( KEY_YEN ),
- BIND_GLOBAL_CONSTANT( KEY_BROKENBAR ),
- BIND_GLOBAL_CONSTANT( KEY_SECTION ),
- BIND_GLOBAL_CONSTANT( KEY_DIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_COPYRIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_ORDFEMININE ),
- BIND_GLOBAL_CONSTANT( KEY_GUILLEMOTLEFT ),
- BIND_GLOBAL_CONSTANT( KEY_NOTSIGN ),
- BIND_GLOBAL_CONSTANT( KEY_HYPHEN ),
- BIND_GLOBAL_CONSTANT( KEY_REGISTERED ),
- BIND_GLOBAL_CONSTANT( KEY_MACRON ),
- BIND_GLOBAL_CONSTANT( KEY_DEGREE ),
- BIND_GLOBAL_CONSTANT( KEY_PLUSMINUS ),
- BIND_GLOBAL_CONSTANT( KEY_TWOSUPERIOR ),
- BIND_GLOBAL_CONSTANT( KEY_THREESUPERIOR ),
- BIND_GLOBAL_CONSTANT( KEY_ACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_MU ),
- BIND_GLOBAL_CONSTANT( KEY_PARAGRAPH ),
- BIND_GLOBAL_CONSTANT( KEY_PERIODCENTERED ),
- BIND_GLOBAL_CONSTANT( KEY_CEDILLA ),
- BIND_GLOBAL_CONSTANT( KEY_ONESUPERIOR ),
- BIND_GLOBAL_CONSTANT( KEY_MASCULINE ),
- BIND_GLOBAL_CONSTANT( KEY_GUILLEMOTRIGHT ),
- BIND_GLOBAL_CONSTANT( KEY_ONEQUARTER ),
- BIND_GLOBAL_CONSTANT( KEY_ONEHALF ),
- BIND_GLOBAL_CONSTANT( KEY_THREEQUARTERS ),
- BIND_GLOBAL_CONSTANT( KEY_QUESTIONDOWN ),
- BIND_GLOBAL_CONSTANT( KEY_AGRAVE ),
- BIND_GLOBAL_CONSTANT( KEY_AACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_ACIRCUMFLEX ),
- BIND_GLOBAL_CONSTANT( KEY_ATILDE ),
- BIND_GLOBAL_CONSTANT( KEY_ADIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_ARING ),
- BIND_GLOBAL_CONSTANT( KEY_AE ),
- BIND_GLOBAL_CONSTANT( KEY_CCEDILLA ),
- BIND_GLOBAL_CONSTANT( KEY_EGRAVE ),
- BIND_GLOBAL_CONSTANT( KEY_EACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_ECIRCUMFLEX ),
- BIND_GLOBAL_CONSTANT( KEY_EDIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_IGRAVE ),
- BIND_GLOBAL_CONSTANT( KEY_IACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_ICIRCUMFLEX ),
- BIND_GLOBAL_CONSTANT( KEY_IDIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_ETH ),
- BIND_GLOBAL_CONSTANT( KEY_NTILDE ),
- BIND_GLOBAL_CONSTANT( KEY_OGRAVE ),
- BIND_GLOBAL_CONSTANT( KEY_OACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_OCIRCUMFLEX ),
- BIND_GLOBAL_CONSTANT( KEY_OTILDE ),
- BIND_GLOBAL_CONSTANT( KEY_ODIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_MULTIPLY ),
- BIND_GLOBAL_CONSTANT( KEY_OOBLIQUE ),
- BIND_GLOBAL_CONSTANT( KEY_UGRAVE ),
- BIND_GLOBAL_CONSTANT( KEY_UACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_UCIRCUMFLEX ),
- BIND_GLOBAL_CONSTANT( KEY_UDIAERESIS ),
- BIND_GLOBAL_CONSTANT( KEY_YACUTE ),
- BIND_GLOBAL_CONSTANT( KEY_THORN ),
- BIND_GLOBAL_CONSTANT( KEY_SSHARP ),
-
- BIND_GLOBAL_CONSTANT( KEY_DIVISION ),
- BIND_GLOBAL_CONSTANT( KEY_YDIAERESIS ),
-
- BIND_GLOBAL_CONSTANT( KEY_CODE_MASK ),
- BIND_GLOBAL_CONSTANT( KEY_MODIFIER_MASK ),
-
- BIND_GLOBAL_CONSTANT( KEY_MASK_SHIFT ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_ALT ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_META ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_CTRL ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_CMD ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_KPAD ),
- BIND_GLOBAL_CONSTANT( KEY_MASK_GROUP_SWITCH ),
+ BIND_GLOBAL_CONSTANT(SPKEY),
+
+ BIND_GLOBAL_CONSTANT(KEY_ESCAPE),
+ BIND_GLOBAL_CONSTANT(KEY_TAB),
+ BIND_GLOBAL_CONSTANT(KEY_BACKTAB),
+ BIND_GLOBAL_CONSTANT(KEY_BACKSPACE),
+ BIND_GLOBAL_CONSTANT(KEY_RETURN),
+ BIND_GLOBAL_CONSTANT(KEY_ENTER),
+ BIND_GLOBAL_CONSTANT(KEY_INSERT),
+ BIND_GLOBAL_CONSTANT(KEY_DELETE),
+ BIND_GLOBAL_CONSTANT(KEY_PAUSE),
+ BIND_GLOBAL_CONSTANT(KEY_PRINT),
+ BIND_GLOBAL_CONSTANT(KEY_SYSREQ),
+ BIND_GLOBAL_CONSTANT(KEY_CLEAR),
+ BIND_GLOBAL_CONSTANT(KEY_HOME),
+ BIND_GLOBAL_CONSTANT(KEY_END),
+ BIND_GLOBAL_CONSTANT(KEY_LEFT),
+ BIND_GLOBAL_CONSTANT(KEY_UP),
+ BIND_GLOBAL_CONSTANT(KEY_RIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_DOWN),
+ BIND_GLOBAL_CONSTANT(KEY_PAGEUP),
+ BIND_GLOBAL_CONSTANT(KEY_PAGEDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_SHIFT),
+ BIND_GLOBAL_CONSTANT(KEY_CONTROL),
+ BIND_GLOBAL_CONSTANT(KEY_META),
+ BIND_GLOBAL_CONSTANT(KEY_ALT),
+ BIND_GLOBAL_CONSTANT(KEY_CAPSLOCK),
+ BIND_GLOBAL_CONSTANT(KEY_NUMLOCK),
+ BIND_GLOBAL_CONSTANT(KEY_SCROLLLOCK),
+ BIND_GLOBAL_CONSTANT(KEY_F1),
+ BIND_GLOBAL_CONSTANT(KEY_F2),
+ BIND_GLOBAL_CONSTANT(KEY_F3),
+ BIND_GLOBAL_CONSTANT(KEY_F4),
+ BIND_GLOBAL_CONSTANT(KEY_F5),
+ BIND_GLOBAL_CONSTANT(KEY_F6),
+ BIND_GLOBAL_CONSTANT(KEY_F7),
+ BIND_GLOBAL_CONSTANT(KEY_F8),
+ BIND_GLOBAL_CONSTANT(KEY_F9),
+ BIND_GLOBAL_CONSTANT(KEY_F10),
+ BIND_GLOBAL_CONSTANT(KEY_F11),
+ BIND_GLOBAL_CONSTANT(KEY_F12),
+ BIND_GLOBAL_CONSTANT(KEY_F13),
+ BIND_GLOBAL_CONSTANT(KEY_F14),
+ BIND_GLOBAL_CONSTANT(KEY_F15),
+ BIND_GLOBAL_CONSTANT(KEY_F16),
+ BIND_GLOBAL_CONSTANT(KEY_KP_ENTER),
+ BIND_GLOBAL_CONSTANT(KEY_KP_MULTIPLY),
+ BIND_GLOBAL_CONSTANT(KEY_KP_DIVIDE),
+ BIND_GLOBAL_CONSTANT(KEY_KP_SUBTRACT),
+ BIND_GLOBAL_CONSTANT(KEY_KP_PERIOD),
+ BIND_GLOBAL_CONSTANT(KEY_KP_ADD),
+ BIND_GLOBAL_CONSTANT(KEY_KP_0),
+ BIND_GLOBAL_CONSTANT(KEY_KP_1),
+ BIND_GLOBAL_CONSTANT(KEY_KP_2),
+ BIND_GLOBAL_CONSTANT(KEY_KP_3),
+ BIND_GLOBAL_CONSTANT(KEY_KP_4),
+ BIND_GLOBAL_CONSTANT(KEY_KP_5),
+ BIND_GLOBAL_CONSTANT(KEY_KP_6),
+ BIND_GLOBAL_CONSTANT(KEY_KP_7),
+ BIND_GLOBAL_CONSTANT(KEY_KP_8),
+ BIND_GLOBAL_CONSTANT(KEY_KP_9),
+ BIND_GLOBAL_CONSTANT(KEY_SUPER_L),
+ BIND_GLOBAL_CONSTANT(KEY_SUPER_R),
+ BIND_GLOBAL_CONSTANT(KEY_MENU),
+ BIND_GLOBAL_CONSTANT(KEY_HYPER_L),
+ BIND_GLOBAL_CONSTANT(KEY_HYPER_R),
+ BIND_GLOBAL_CONSTANT(KEY_HELP),
+ BIND_GLOBAL_CONSTANT(KEY_DIRECTION_L),
+ BIND_GLOBAL_CONSTANT(KEY_DIRECTION_R),
+ BIND_GLOBAL_CONSTANT(KEY_BACK),
+ BIND_GLOBAL_CONSTANT(KEY_FORWARD),
+ BIND_GLOBAL_CONSTANT(KEY_STOP),
+ BIND_GLOBAL_CONSTANT(KEY_REFRESH),
+ BIND_GLOBAL_CONSTANT(KEY_VOLUMEDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_VOLUMEMUTE),
+ BIND_GLOBAL_CONSTANT(KEY_VOLUMEUP),
+ BIND_GLOBAL_CONSTANT(KEY_BASSBOOST),
+ BIND_GLOBAL_CONSTANT(KEY_BASSUP),
+ BIND_GLOBAL_CONSTANT(KEY_BASSDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_TREBLEUP),
+ BIND_GLOBAL_CONSTANT(KEY_TREBLEDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_MEDIAPLAY),
+ BIND_GLOBAL_CONSTANT(KEY_MEDIASTOP),
+ BIND_GLOBAL_CONSTANT(KEY_MEDIAPREVIOUS),
+ BIND_GLOBAL_CONSTANT(KEY_MEDIANEXT),
+ BIND_GLOBAL_CONSTANT(KEY_MEDIARECORD),
+ BIND_GLOBAL_CONSTANT(KEY_HOMEPAGE),
+ BIND_GLOBAL_CONSTANT(KEY_FAVORITES),
+ BIND_GLOBAL_CONSTANT(KEY_SEARCH),
+ BIND_GLOBAL_CONSTANT(KEY_STANDBY),
+ BIND_GLOBAL_CONSTANT(KEY_OPENURL),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHMAIL),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHMEDIA),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH0),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH1),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH2),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH3),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH4),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH5),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH6),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH7),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH8),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCH9),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHA),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHB),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHC),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHD),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHE),
+ BIND_GLOBAL_CONSTANT(KEY_LAUNCHF),
+
+ BIND_GLOBAL_CONSTANT(KEY_UNKNOWN),
+ BIND_GLOBAL_CONSTANT(KEY_SPACE),
+ BIND_GLOBAL_CONSTANT(KEY_EXCLAM),
+ BIND_GLOBAL_CONSTANT(KEY_QUOTEDBL),
+ BIND_GLOBAL_CONSTANT(KEY_NUMBERSIGN),
+ BIND_GLOBAL_CONSTANT(KEY_DOLLAR),
+ BIND_GLOBAL_CONSTANT(KEY_PERCENT),
+ BIND_GLOBAL_CONSTANT(KEY_AMPERSAND),
+ BIND_GLOBAL_CONSTANT(KEY_APOSTROPHE),
+ BIND_GLOBAL_CONSTANT(KEY_PARENLEFT),
+ BIND_GLOBAL_CONSTANT(KEY_PARENRIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_ASTERISK),
+ BIND_GLOBAL_CONSTANT(KEY_PLUS),
+ BIND_GLOBAL_CONSTANT(KEY_COMMA),
+ BIND_GLOBAL_CONSTANT(KEY_MINUS),
+ BIND_GLOBAL_CONSTANT(KEY_PERIOD),
+ BIND_GLOBAL_CONSTANT(KEY_SLASH),
+ BIND_GLOBAL_CONSTANT(KEY_0),
+ BIND_GLOBAL_CONSTANT(KEY_1),
+ BIND_GLOBAL_CONSTANT(KEY_2),
+ BIND_GLOBAL_CONSTANT(KEY_3),
+ BIND_GLOBAL_CONSTANT(KEY_4),
+ BIND_GLOBAL_CONSTANT(KEY_5),
+ BIND_GLOBAL_CONSTANT(KEY_6),
+ BIND_GLOBAL_CONSTANT(KEY_7),
+ BIND_GLOBAL_CONSTANT(KEY_8),
+ BIND_GLOBAL_CONSTANT(KEY_9),
+ BIND_GLOBAL_CONSTANT(KEY_COLON),
+ BIND_GLOBAL_CONSTANT(KEY_SEMICOLON),
+ BIND_GLOBAL_CONSTANT(KEY_LESS),
+ BIND_GLOBAL_CONSTANT(KEY_EQUAL),
+ BIND_GLOBAL_CONSTANT(KEY_GREATER),
+ BIND_GLOBAL_CONSTANT(KEY_QUESTION),
+ BIND_GLOBAL_CONSTANT(KEY_AT),
+ BIND_GLOBAL_CONSTANT(KEY_A),
+ BIND_GLOBAL_CONSTANT(KEY_B),
+ BIND_GLOBAL_CONSTANT(KEY_C),
+ BIND_GLOBAL_CONSTANT(KEY_D),
+ BIND_GLOBAL_CONSTANT(KEY_E),
+ BIND_GLOBAL_CONSTANT(KEY_F),
+ BIND_GLOBAL_CONSTANT(KEY_G),
+ BIND_GLOBAL_CONSTANT(KEY_H),
+ BIND_GLOBAL_CONSTANT(KEY_I),
+ BIND_GLOBAL_CONSTANT(KEY_J),
+ BIND_GLOBAL_CONSTANT(KEY_K),
+ BIND_GLOBAL_CONSTANT(KEY_L),
+ BIND_GLOBAL_CONSTANT(KEY_M),
+ BIND_GLOBAL_CONSTANT(KEY_N),
+ BIND_GLOBAL_CONSTANT(KEY_O),
+ BIND_GLOBAL_CONSTANT(KEY_P),
+ BIND_GLOBAL_CONSTANT(KEY_Q),
+ BIND_GLOBAL_CONSTANT(KEY_R),
+ BIND_GLOBAL_CONSTANT(KEY_S),
+ BIND_GLOBAL_CONSTANT(KEY_T),
+ BIND_GLOBAL_CONSTANT(KEY_U),
+ BIND_GLOBAL_CONSTANT(KEY_V),
+ BIND_GLOBAL_CONSTANT(KEY_W),
+ BIND_GLOBAL_CONSTANT(KEY_X),
+ BIND_GLOBAL_CONSTANT(KEY_Y),
+ BIND_GLOBAL_CONSTANT(KEY_Z),
+ BIND_GLOBAL_CONSTANT(KEY_BRACKETLEFT),
+ BIND_GLOBAL_CONSTANT(KEY_BACKSLASH),
+ BIND_GLOBAL_CONSTANT(KEY_BRACKETRIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_ASCIICIRCUM),
+ BIND_GLOBAL_CONSTANT(KEY_UNDERSCORE),
+ BIND_GLOBAL_CONSTANT(KEY_QUOTELEFT),
+ BIND_GLOBAL_CONSTANT(KEY_BRACELEFT),
+ BIND_GLOBAL_CONSTANT(KEY_BAR),
+ BIND_GLOBAL_CONSTANT(KEY_BRACERIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_ASCIITILDE),
+ BIND_GLOBAL_CONSTANT(KEY_NOBREAKSPACE),
+ BIND_GLOBAL_CONSTANT(KEY_EXCLAMDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_CENT),
+ BIND_GLOBAL_CONSTANT(KEY_STERLING),
+ BIND_GLOBAL_CONSTANT(KEY_CURRENCY),
+ BIND_GLOBAL_CONSTANT(KEY_YEN),
+ BIND_GLOBAL_CONSTANT(KEY_BROKENBAR),
+ BIND_GLOBAL_CONSTANT(KEY_SECTION),
+ BIND_GLOBAL_CONSTANT(KEY_DIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_COPYRIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_ORDFEMININE),
+ BIND_GLOBAL_CONSTANT(KEY_GUILLEMOTLEFT),
+ BIND_GLOBAL_CONSTANT(KEY_NOTSIGN),
+ BIND_GLOBAL_CONSTANT(KEY_HYPHEN),
+ BIND_GLOBAL_CONSTANT(KEY_REGISTERED),
+ BIND_GLOBAL_CONSTANT(KEY_MACRON),
+ BIND_GLOBAL_CONSTANT(KEY_DEGREE),
+ BIND_GLOBAL_CONSTANT(KEY_PLUSMINUS),
+ BIND_GLOBAL_CONSTANT(KEY_TWOSUPERIOR),
+ BIND_GLOBAL_CONSTANT(KEY_THREESUPERIOR),
+ BIND_GLOBAL_CONSTANT(KEY_ACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_MU),
+ BIND_GLOBAL_CONSTANT(KEY_PARAGRAPH),
+ BIND_GLOBAL_CONSTANT(KEY_PERIODCENTERED),
+ BIND_GLOBAL_CONSTANT(KEY_CEDILLA),
+ BIND_GLOBAL_CONSTANT(KEY_ONESUPERIOR),
+ BIND_GLOBAL_CONSTANT(KEY_MASCULINE),
+ BIND_GLOBAL_CONSTANT(KEY_GUILLEMOTRIGHT),
+ BIND_GLOBAL_CONSTANT(KEY_ONEQUARTER),
+ BIND_GLOBAL_CONSTANT(KEY_ONEHALF),
+ BIND_GLOBAL_CONSTANT(KEY_THREEQUARTERS),
+ BIND_GLOBAL_CONSTANT(KEY_QUESTIONDOWN),
+ BIND_GLOBAL_CONSTANT(KEY_AGRAVE),
+ BIND_GLOBAL_CONSTANT(KEY_AACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_ACIRCUMFLEX),
+ BIND_GLOBAL_CONSTANT(KEY_ATILDE),
+ BIND_GLOBAL_CONSTANT(KEY_ADIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_ARING),
+ BIND_GLOBAL_CONSTANT(KEY_AE),
+ BIND_GLOBAL_CONSTANT(KEY_CCEDILLA),
+ BIND_GLOBAL_CONSTANT(KEY_EGRAVE),
+ BIND_GLOBAL_CONSTANT(KEY_EACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_ECIRCUMFLEX),
+ BIND_GLOBAL_CONSTANT(KEY_EDIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_IGRAVE),
+ BIND_GLOBAL_CONSTANT(KEY_IACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_ICIRCUMFLEX),
+ BIND_GLOBAL_CONSTANT(KEY_IDIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_ETH),
+ BIND_GLOBAL_CONSTANT(KEY_NTILDE),
+ BIND_GLOBAL_CONSTANT(KEY_OGRAVE),
+ BIND_GLOBAL_CONSTANT(KEY_OACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_OCIRCUMFLEX),
+ BIND_GLOBAL_CONSTANT(KEY_OTILDE),
+ BIND_GLOBAL_CONSTANT(KEY_ODIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_MULTIPLY),
+ BIND_GLOBAL_CONSTANT(KEY_OOBLIQUE),
+ BIND_GLOBAL_CONSTANT(KEY_UGRAVE),
+ BIND_GLOBAL_CONSTANT(KEY_UACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_UCIRCUMFLEX),
+ BIND_GLOBAL_CONSTANT(KEY_UDIAERESIS),
+ BIND_GLOBAL_CONSTANT(KEY_YACUTE),
+ BIND_GLOBAL_CONSTANT(KEY_THORN),
+ BIND_GLOBAL_CONSTANT(KEY_SSHARP),
+
+ BIND_GLOBAL_CONSTANT(KEY_DIVISION),
+ BIND_GLOBAL_CONSTANT(KEY_YDIAERESIS),
+
+ BIND_GLOBAL_CONSTANT(KEY_CODE_MASK),
+ BIND_GLOBAL_CONSTANT(KEY_MODIFIER_MASK),
+
+ BIND_GLOBAL_CONSTANT(KEY_MASK_SHIFT),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_ALT),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_META),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_CTRL),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_CMD),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_KPAD),
+ BIND_GLOBAL_CONSTANT(KEY_MASK_GROUP_SWITCH),
// mouse
- BIND_GLOBAL_CONSTANT( BUTTON_LEFT ),
- BIND_GLOBAL_CONSTANT( BUTTON_RIGHT ),
- BIND_GLOBAL_CONSTANT( BUTTON_MIDDLE ),
- BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_UP ),
- BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_DOWN ),
- BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_LEFT ),
- BIND_GLOBAL_CONSTANT( BUTTON_WHEEL_RIGHT ),
- BIND_GLOBAL_CONSTANT( BUTTON_MASK_LEFT ),
- BIND_GLOBAL_CONSTANT( BUTTON_MASK_RIGHT ),
- BIND_GLOBAL_CONSTANT( BUTTON_MASK_MIDDLE ),
+ BIND_GLOBAL_CONSTANT(BUTTON_LEFT),
+ BIND_GLOBAL_CONSTANT(BUTTON_RIGHT),
+ BIND_GLOBAL_CONSTANT(BUTTON_MIDDLE),
+ BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_UP),
+ BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_DOWN),
+ BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_LEFT),
+ BIND_GLOBAL_CONSTANT(BUTTON_WHEEL_RIGHT),
+ BIND_GLOBAL_CONSTANT(BUTTON_MASK_LEFT),
+ BIND_GLOBAL_CONSTANT(BUTTON_MASK_RIGHT),
+ BIND_GLOBAL_CONSTANT(BUTTON_MASK_MIDDLE),
//joypads
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_0 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_1 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_2 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_3 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_4 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_5 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_6 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_7 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_8 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_9 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_10 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_11 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_12 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_13 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_14 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_15 ),
- BIND_GLOBAL_CONSTANT( JOY_BUTTON_MAX ),
-
- BIND_GLOBAL_CONSTANT( JOY_SNES_A ),
- BIND_GLOBAL_CONSTANT( JOY_SNES_B ),
- BIND_GLOBAL_CONSTANT( JOY_SNES_X ),
- BIND_GLOBAL_CONSTANT( JOY_SNES_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_SONY_CIRCLE ),
- BIND_GLOBAL_CONSTANT( JOY_SONY_X ),
- BIND_GLOBAL_CONSTANT( JOY_SONY_SQUARE ),
- BIND_GLOBAL_CONSTANT( JOY_SONY_TRIANGLE ),
-
- BIND_GLOBAL_CONSTANT( JOY_SEGA_B ),
- BIND_GLOBAL_CONSTANT( JOY_SEGA_A ),
- BIND_GLOBAL_CONSTANT( JOY_SEGA_X ),
- BIND_GLOBAL_CONSTANT( JOY_SEGA_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_XBOX_B ),
- BIND_GLOBAL_CONSTANT( JOY_XBOX_A ),
- BIND_GLOBAL_CONSTANT( JOY_XBOX_X ),
- BIND_GLOBAL_CONSTANT( JOY_XBOX_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_DS_A ),
- BIND_GLOBAL_CONSTANT( JOY_DS_B ),
- BIND_GLOBAL_CONSTANT( JOY_DS_X ),
- BIND_GLOBAL_CONSTANT( JOY_DS_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_SELECT ),
- BIND_GLOBAL_CONSTANT( JOY_START ),
- BIND_GLOBAL_CONSTANT( JOY_DPAD_UP ),
- BIND_GLOBAL_CONSTANT( JOY_DPAD_DOWN ),
- BIND_GLOBAL_CONSTANT( JOY_DPAD_LEFT ),
- BIND_GLOBAL_CONSTANT( JOY_DPAD_RIGHT ),
- BIND_GLOBAL_CONSTANT( JOY_L ),
- BIND_GLOBAL_CONSTANT( JOY_L2 ),
- BIND_GLOBAL_CONSTANT( JOY_L3 ),
- BIND_GLOBAL_CONSTANT( JOY_R ),
- BIND_GLOBAL_CONSTANT( JOY_R2 ),
- BIND_GLOBAL_CONSTANT( JOY_R3 ),
-
- BIND_GLOBAL_CONSTANT( JOY_AXIS_0 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_1 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_2 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_3 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_4 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_5 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_6 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_7 ),
- BIND_GLOBAL_CONSTANT( JOY_AXIS_MAX ),
-
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_0_X ),
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_0_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_1_X ),
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_1_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_2_X ),
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_2_Y ),
-
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_L2 ),
- BIND_GLOBAL_CONSTANT( JOY_ANALOG_R2 ),
-
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_0),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_1),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_2),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_3),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_4),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_5),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_6),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_7),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_8),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_9),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_10),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_11),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_12),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_13),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_14),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_15),
+ BIND_GLOBAL_CONSTANT(JOY_BUTTON_MAX),
+
+ BIND_GLOBAL_CONSTANT(JOY_SNES_A),
+ BIND_GLOBAL_CONSTANT(JOY_SNES_B),
+ BIND_GLOBAL_CONSTANT(JOY_SNES_X),
+ BIND_GLOBAL_CONSTANT(JOY_SNES_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_SONY_CIRCLE),
+ BIND_GLOBAL_CONSTANT(JOY_SONY_X),
+ BIND_GLOBAL_CONSTANT(JOY_SONY_SQUARE),
+ BIND_GLOBAL_CONSTANT(JOY_SONY_TRIANGLE),
+
+ BIND_GLOBAL_CONSTANT(JOY_SEGA_B),
+ BIND_GLOBAL_CONSTANT(JOY_SEGA_A),
+ BIND_GLOBAL_CONSTANT(JOY_SEGA_X),
+ BIND_GLOBAL_CONSTANT(JOY_SEGA_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_XBOX_B),
+ BIND_GLOBAL_CONSTANT(JOY_XBOX_A),
+ BIND_GLOBAL_CONSTANT(JOY_XBOX_X),
+ BIND_GLOBAL_CONSTANT(JOY_XBOX_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_DS_A),
+ BIND_GLOBAL_CONSTANT(JOY_DS_B),
+ BIND_GLOBAL_CONSTANT(JOY_DS_X),
+ BIND_GLOBAL_CONSTANT(JOY_DS_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_SELECT),
+ BIND_GLOBAL_CONSTANT(JOY_START),
+ BIND_GLOBAL_CONSTANT(JOY_DPAD_UP),
+ BIND_GLOBAL_CONSTANT(JOY_DPAD_DOWN),
+ BIND_GLOBAL_CONSTANT(JOY_DPAD_LEFT),
+ BIND_GLOBAL_CONSTANT(JOY_DPAD_RIGHT),
+ BIND_GLOBAL_CONSTANT(JOY_L),
+ BIND_GLOBAL_CONSTANT(JOY_L2),
+ BIND_GLOBAL_CONSTANT(JOY_L3),
+ BIND_GLOBAL_CONSTANT(JOY_R),
+ BIND_GLOBAL_CONSTANT(JOY_R2),
+ BIND_GLOBAL_CONSTANT(JOY_R3),
+
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_0),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_1),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_2),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_3),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_4),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_5),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_6),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_7),
+ BIND_GLOBAL_CONSTANT(JOY_AXIS_MAX),
+
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_0_X),
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_0_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_1_X),
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_1_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_2_X),
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_2_Y),
+
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_L2),
+ BIND_GLOBAL_CONSTANT(JOY_ANALOG_R2),
// error list
- BIND_GLOBAL_CONSTANT( OK ),
- BIND_GLOBAL_CONSTANT( FAILED ), ///< Generic fail error
- BIND_GLOBAL_CONSTANT( ERR_UNAVAILABLE ), ///< What is requested is unsupported/unavailable
- BIND_GLOBAL_CONSTANT( ERR_UNCONFIGURED ), ///< The object being used hasnt been properly set up yet
- BIND_GLOBAL_CONSTANT( ERR_UNAUTHORIZED ), ///< Missing credentials for requested resource
- BIND_GLOBAL_CONSTANT( ERR_PARAMETER_RANGE_ERROR ), ///< Parameter given out of range
- BIND_GLOBAL_CONSTANT( ERR_OUT_OF_MEMORY ), ///< Out of memory
- BIND_GLOBAL_CONSTANT( ERR_FILE_NOT_FOUND ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_BAD_DRIVE ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_BAD_PATH ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_NO_PERMISSION ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_ALREADY_IN_USE ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_OPEN ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_WRITE ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_CANT_READ ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_UNRECOGNIZED ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_CORRUPT ),
- BIND_GLOBAL_CONSTANT( ERR_FILE_MISSING_DEPENDENCIES),
- BIND_GLOBAL_CONSTANT( ERR_FILE_EOF ),
- BIND_GLOBAL_CONSTANT( ERR_CANT_OPEN ), ///< Can't open a resource/socket/file
- BIND_GLOBAL_CONSTANT( ERR_CANT_CREATE ),
- BIND_GLOBAL_CONSTANT( ERR_PARSE_ERROR ),
- BIND_GLOBAL_CONSTANT( ERR_QUERY_FAILED ),
- BIND_GLOBAL_CONSTANT( ERR_ALREADY_IN_USE ),
- BIND_GLOBAL_CONSTANT( ERR_LOCKED ), ///< resource is locked
- BIND_GLOBAL_CONSTANT( ERR_TIMEOUT ),
- BIND_GLOBAL_CONSTANT( ERR_CANT_AQUIRE_RESOURCE ),
- BIND_GLOBAL_CONSTANT( ERR_INVALID_DATA ), ///< Data passed is invalid
- BIND_GLOBAL_CONSTANT( ERR_INVALID_PARAMETER ), ///< Parameter passed is invalid
- BIND_GLOBAL_CONSTANT( ERR_ALREADY_EXISTS ), ///< When adding ), item already exists
- BIND_GLOBAL_CONSTANT( ERR_DOES_NOT_EXIST ), ///< When retrieving/erasing ), it item does not exist
- BIND_GLOBAL_CONSTANT( ERR_DATABASE_CANT_READ ), ///< database is full
- BIND_GLOBAL_CONSTANT( ERR_DATABASE_CANT_WRITE ), ///< database is full
- BIND_GLOBAL_CONSTANT( ERR_COMPILATION_FAILED ),
- BIND_GLOBAL_CONSTANT( ERR_METHOD_NOT_FOUND ),
- BIND_GLOBAL_CONSTANT( ERR_LINK_FAILED ),
- BIND_GLOBAL_CONSTANT( ERR_SCRIPT_FAILED ),
- BIND_GLOBAL_CONSTANT( ERR_CYCLIC_LINK ),
- BIND_GLOBAL_CONSTANT( ERR_BUSY ),
- BIND_GLOBAL_CONSTANT( ERR_HELP ), ///< user requested help!!
- BIND_GLOBAL_CONSTANT( ERR_BUG ), ///< a bug in the software certainly happened ), due to a double check failing or unexpected behavior.
- BIND_GLOBAL_CONSTANT( ERR_WTF ),
-
-
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_NONE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_RANGE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_EXP_RANGE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_ENUM ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_EXP_EASING ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LENGTH ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_KEY_ACCEL ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_FLAGS ),
-
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_2D_RENDER ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_2D_PHYSICS ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_3D_RENDER ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_LAYERS_3D_PHYSICS),
-
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_FILE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_DIR ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_GLOBAL_FILE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_GLOBAL_DIR ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_RESOURCE_TYPE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_MULTILINE_TEXT ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_COLOR_NO_ALPHA ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_IMAGE_COMPRESS_LOSSY ),
- BIND_GLOBAL_CONSTANT( PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS ),
-
-
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORAGE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_EDITOR ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NETWORK ),
-
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_EDITOR_HELPER ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CHECKABLE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CHECKED ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_INTERNATIONALIZED ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_GROUP ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_CATEGORY ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORE_IF_NONZERO ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_STORE_IF_NONONE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NO_INSTANCE_STATE ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_RESTART_IF_CHANGED ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_SCRIPT_VARIABLE ),
-
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_DEFAULT ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_DEFAULT_INTL ),
- BIND_GLOBAL_CONSTANT( PROPERTY_USAGE_NOEDITOR ),
-
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_NORMAL ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_EDITOR ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_NOSCRIPT ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_CONST ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_REVERSE ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_VIRTUAL ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAG_FROM_SCRIPT ),
- BIND_GLOBAL_CONSTANT( METHOD_FLAGS_DEFAULT ),
-
- {"TYPE_NIL",Variant::NIL},
- {"TYPE_BOOL",Variant::BOOL},
- {"TYPE_INT",Variant::INT},
- {"TYPE_REAL",Variant::REAL},
- {"TYPE_STRING",Variant::STRING},
- {"TYPE_VECTOR2",Variant::VECTOR2}, // 5
- {"TYPE_RECT2",Variant::RECT2},
- {"TYPE_VECTOR3",Variant::VECTOR3},
- {"TYPE_TRANSFORM2D",Variant::TRANSFORM2D},
- {"TYPE_PLANE",Variant::PLANE},
- {"TYPE_QUAT",Variant::QUAT}, // 10
- {"TYPE_RECT3",Variant::RECT3}, //sorry naming convention fail :( not like it's used often
- {"TYPE_BASIS",Variant::BASIS},
- {"TYPE_TRANSFORM",Variant::TRANSFORM},
- {"TYPE_COLOR",Variant::COLOR},
- {"TYPE_IMAGE",Variant::IMAGE}, // 15
- {"TYPE_NODE_PATH",Variant::NODE_PATH},
- {"TYPE_RID",Variant::_RID},
- {"TYPE_OBJECT",Variant::OBJECT},
- {"TYPE_INPUT_EVENT",Variant::INPUT_EVENT},
- {"TYPE_DICTIONARY",Variant::DICTIONARY}, // 20
- {"TYPE_ARRAY",Variant::ARRAY},
- {"TYPE_RAW_ARRAY",Variant::POOL_BYTE_ARRAY},
- {"TYPE_INT_ARRAY",Variant::POOL_INT_ARRAY},
- {"TYPE_REAL_ARRAY",Variant::POOL_REAL_ARRAY},
- {"TYPE_STRING_ARRAY",Variant::POOL_STRING_ARRAY}, // 25
- {"TYPE_VECTOR2_ARRAY",Variant::POOL_VECTOR2_ARRAY},
- {"TYPE_VECTOR3_ARRAY",Variant::POOL_VECTOR3_ARRAY},
- {"TYPE_COLOR_ARRAY",Variant::POOL_COLOR_ARRAY},
- {"TYPE_MAX",Variant::VARIANT_MAX},
- {NULL,0}
+ BIND_GLOBAL_CONSTANT(OK),
+ BIND_GLOBAL_CONSTANT(FAILED), ///< Generic fail error
+ BIND_GLOBAL_CONSTANT(ERR_UNAVAILABLE), ///< What is requested is unsupported/unavailable
+ BIND_GLOBAL_CONSTANT(ERR_UNCONFIGURED), ///< The object being used hasnt been properly set up yet
+ BIND_GLOBAL_CONSTANT(ERR_UNAUTHORIZED), ///< Missing credentials for requested resource
+ BIND_GLOBAL_CONSTANT(ERR_PARAMETER_RANGE_ERROR), ///< Parameter given out of range
+ BIND_GLOBAL_CONSTANT(ERR_OUT_OF_MEMORY), ///< Out of memory
+ BIND_GLOBAL_CONSTANT(ERR_FILE_NOT_FOUND),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_BAD_DRIVE),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_BAD_PATH),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_NO_PERMISSION),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_ALREADY_IN_USE),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_OPEN),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_WRITE),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_CANT_READ),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_UNRECOGNIZED),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_CORRUPT),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_MISSING_DEPENDENCIES),
+ BIND_GLOBAL_CONSTANT(ERR_FILE_EOF),
+ BIND_GLOBAL_CONSTANT(ERR_CANT_OPEN), ///< Can't open a resource/socket/file
+ BIND_GLOBAL_CONSTANT(ERR_CANT_CREATE),
+ BIND_GLOBAL_CONSTANT(ERR_PARSE_ERROR),
+ BIND_GLOBAL_CONSTANT(ERR_QUERY_FAILED),
+ BIND_GLOBAL_CONSTANT(ERR_ALREADY_IN_USE),
+ BIND_GLOBAL_CONSTANT(ERR_LOCKED), ///< resource is locked
+ BIND_GLOBAL_CONSTANT(ERR_TIMEOUT),
+ BIND_GLOBAL_CONSTANT(ERR_CANT_AQUIRE_RESOURCE),
+ BIND_GLOBAL_CONSTANT(ERR_INVALID_DATA), ///< Data passed is invalid
+ BIND_GLOBAL_CONSTANT(ERR_INVALID_PARAMETER), ///< Parameter passed is invalid
+ BIND_GLOBAL_CONSTANT(ERR_ALREADY_EXISTS), ///< When adding ), item already exists
+ BIND_GLOBAL_CONSTANT(ERR_DOES_NOT_EXIST), ///< When retrieving/erasing ), it item does not exist
+ BIND_GLOBAL_CONSTANT(ERR_DATABASE_CANT_READ), ///< database is full
+ BIND_GLOBAL_CONSTANT(ERR_DATABASE_CANT_WRITE), ///< database is full
+ BIND_GLOBAL_CONSTANT(ERR_COMPILATION_FAILED),
+ BIND_GLOBAL_CONSTANT(ERR_METHOD_NOT_FOUND),
+ BIND_GLOBAL_CONSTANT(ERR_LINK_FAILED),
+ BIND_GLOBAL_CONSTANT(ERR_SCRIPT_FAILED),
+ BIND_GLOBAL_CONSTANT(ERR_CYCLIC_LINK),
+ BIND_GLOBAL_CONSTANT(ERR_BUSY),
+ BIND_GLOBAL_CONSTANT(ERR_HELP), ///< user requested help!!
+ BIND_GLOBAL_CONSTANT(ERR_BUG), ///< a bug in the software certainly happened ), due to a double check failing or unexpected behavior.
+ BIND_GLOBAL_CONSTANT(ERR_WTF),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_NONE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_RANGE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_EXP_RANGE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_ENUM),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_EXP_EASING),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LENGTH),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_KEY_ACCEL),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_FLAGS),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_2D_RENDER),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_2D_PHYSICS),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_3D_RENDER),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_LAYERS_3D_PHYSICS),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_FILE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_DIR),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_GLOBAL_FILE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_GLOBAL_DIR),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_RESOURCE_TYPE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_MULTILINE_TEXT),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_COLOR_NO_ALPHA),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSY),
+ BIND_GLOBAL_CONSTANT(PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORAGE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_EDITOR),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NETWORK),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_EDITOR_HELPER),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CHECKABLE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CHECKED),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_INTERNATIONALIZED),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_GROUP),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_CATEGORY),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORE_IF_NONZERO),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_STORE_IF_NONONE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NO_INSTANCE_STATE),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_RESTART_IF_CHANGED),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_SCRIPT_VARIABLE),
+
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_DEFAULT),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_DEFAULT_INTL),
+ BIND_GLOBAL_CONSTANT(PROPERTY_USAGE_NOEDITOR),
+
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_NORMAL),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_EDITOR),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_NOSCRIPT),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_CONST),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_REVERSE),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_VIRTUAL),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAG_FROM_SCRIPT),
+ BIND_GLOBAL_CONSTANT(METHOD_FLAGS_DEFAULT),
+
+ { "TYPE_NIL", Variant::NIL },
+ { "TYPE_BOOL", Variant::BOOL },
+ { "TYPE_INT", Variant::INT },
+ { "TYPE_REAL", Variant::REAL },
+ { "TYPE_STRING", Variant::STRING },
+ { "TYPE_VECTOR2", Variant::VECTOR2 }, // 5
+ { "TYPE_RECT2", Variant::RECT2 },
+ { "TYPE_VECTOR3", Variant::VECTOR3 },
+ { "TYPE_TRANSFORM2D", Variant::TRANSFORM2D },
+ { "TYPE_PLANE", Variant::PLANE },
+ { "TYPE_QUAT", Variant::QUAT }, // 10
+ { "TYPE_RECT3", Variant::RECT3 }, //sorry naming convention fail :( not like it's used often
+ { "TYPE_BASIS", Variant::BASIS },
+ { "TYPE_TRANSFORM", Variant::TRANSFORM },
+ { "TYPE_COLOR", Variant::COLOR },
+ { "TYPE_IMAGE", Variant::IMAGE }, // 15
+ { "TYPE_NODE_PATH", Variant::NODE_PATH },
+ { "TYPE_RID", Variant::_RID },
+ { "TYPE_OBJECT", Variant::OBJECT },
+ { "TYPE_INPUT_EVENT", Variant::INPUT_EVENT },
+ { "TYPE_DICTIONARY", Variant::DICTIONARY }, // 20
+ { "TYPE_ARRAY", Variant::ARRAY },
+ { "TYPE_RAW_ARRAY", Variant::POOL_BYTE_ARRAY },
+ { "TYPE_INT_ARRAY", Variant::POOL_INT_ARRAY },
+ { "TYPE_REAL_ARRAY", Variant::POOL_REAL_ARRAY },
+ { "TYPE_STRING_ARRAY", Variant::POOL_STRING_ARRAY }, // 25
+ { "TYPE_VECTOR2_ARRAY", Variant::POOL_VECTOR2_ARRAY },
+ { "TYPE_VECTOR3_ARRAY", Variant::POOL_VECTOR3_ARRAY },
+ { "TYPE_COLOR_ARRAY", Variant::POOL_COLOR_ARRAY },
+ { "TYPE_MAX", Variant::VARIANT_MAX },
+ { NULL, 0 }
};
int GlobalConstants::get_global_constant_count() {
- int i=0;
- while(_global_constants[i].name)
+ int i = 0;
+ while (_global_constants[i].name)
i++;
return i;
-
}
const char *GlobalConstants::get_global_constant_name(int p_idx) {
@@ -562,5 +558,3 @@ int GlobalConstants::get_global_constant_value(int p_idx) {
return _global_constants[p_idx].value;
}
-
-
diff --git a/core/global_constants.h b/core/global_constants.h
index 3270dcd151..8823ebf3b0 100644
--- a/core/global_constants.h
+++ b/core/global_constants.h
@@ -29,10 +29,8 @@
#ifndef GLOBAL_CONSTANTS_H
#define GLOBAL_CONSTANTS_H
-
class GlobalConstants {
public:
-
static int get_global_constant_count();
static const char *get_global_constant_name(int p_idx);
static int get_global_constant_value(int p_idx);
diff --git a/core/hash_map.h b/core/hash_map.h
index 515fc6c4fe..645e34e923 100644
--- a/core/hash_map.h
+++ b/core/hash_map.h
@@ -29,42 +29,42 @@
#ifndef HASH_MAP_H
#define HASH_MAP_H
+#include "error_macros.h"
#include "hashfuncs.h"
+#include "list.h"
#include "math_funcs.h"
-#include "error_macros.h"
-#include "ustring.h"
#include "os/memory.h"
-#include "list.h"
+#include "ustring.h"
struct HashMapHasherDefault {
- static _FORCE_INLINE_ uint32_t hash(const String &p_string) { return p_string.hash(); }
- static _FORCE_INLINE_ uint32_t hash(const char *p_cstr) { return hash_djb2(p_cstr); }
- static _FORCE_INLINE_ uint32_t hash(const uint64_t p_int) { return hash_one_uint64(p_int); }
+ static _FORCE_INLINE_ uint32_t hash(const String &p_string) { return p_string.hash(); }
+ static _FORCE_INLINE_ uint32_t hash(const char *p_cstr) { return hash_djb2(p_cstr); }
+ static _FORCE_INLINE_ uint32_t hash(const uint64_t p_int) { return hash_one_uint64(p_int); }
- static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); }
- static _FORCE_INLINE_ uint32_t hash(const float p_float) { return hash_djb2_one_float(p_float); }
- static _FORCE_INLINE_ uint32_t hash(const double p_double){ return hash_djb2_one_float(p_double); }
+ static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); }
+ static _FORCE_INLINE_ uint32_t hash(const float p_float) { return hash_djb2_one_float(p_float); }
+ static _FORCE_INLINE_ uint32_t hash(const double p_double) { return hash_djb2_one_float(p_double); }
static _FORCE_INLINE_ uint32_t hash(const uint32_t p_int) { return p_int; }
- static _FORCE_INLINE_ uint32_t hash(const int32_t p_int) { return (uint32_t)p_int; }
+ static _FORCE_INLINE_ uint32_t hash(const int32_t p_int) { return (uint32_t)p_int; }
static _FORCE_INLINE_ uint32_t hash(const uint16_t p_int) { return p_int; }
- static _FORCE_INLINE_ uint32_t hash(const int16_t p_int) { return (uint32_t)p_int; }
- static _FORCE_INLINE_ uint32_t hash(const uint8_t p_int) { return p_int; }
- static _FORCE_INLINE_ uint32_t hash(const int8_t p_int) { return (uint32_t)p_int; }
- static _FORCE_INLINE_ uint32_t hash(const wchar_t p_wchar){ return (uint32_t)p_wchar; }
+ static _FORCE_INLINE_ uint32_t hash(const int16_t p_int) { return (uint32_t)p_int; }
+ static _FORCE_INLINE_ uint32_t hash(const uint8_t p_int) { return p_int; }
+ static _FORCE_INLINE_ uint32_t hash(const int8_t p_int) { return (uint32_t)p_int; }
+ static _FORCE_INLINE_ uint32_t hash(const wchar_t p_wchar) { return (uint32_t)p_wchar; }
//static _FORCE_INLINE_ uint32_t hash(const void* p_ptr) { return uint32_t(uint64_t(p_ptr))*(0x9e3779b1L); }
};
template <typename T>
struct HashMapComparatorDefault {
- static bool compare(const T& p_lhs, const T& p_rhs) {
+ static bool compare(const T &p_lhs, const T &p_rhs) {
return p_lhs == p_rhs;
}
- bool compare(const float& p_lhs, const float& p_rhs) {
+ bool compare(const float &p_lhs, const float &p_rhs) {
return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs));
}
- bool compare(const double& p_lhs, const double& p_rhs) {
+ bool compare(const double &p_lhs, const double &p_rhs) {
return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs));
}
};
@@ -86,20 +86,21 @@ struct HashMapComparatorDefault {
*
*/
-template<class TKey, class TData, class Hasher=HashMapHasherDefault, class Comparator=HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER=3,uint8_t RELATIONSHIP=8>
+template <class TKey, class TData, class Hasher = HashMapHasherDefault, class Comparator = HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER = 3, uint8_t RELATIONSHIP = 8>
class HashMap {
public:
-
struct Pair {
TKey key;
TData data;
Pair() {}
- Pair(const TKey& p_key, const TData& p_data) { key=p_key; data=p_data; }
+ Pair(const TKey &p_key, const TData &p_data) {
+ key = p_key;
+ data = p_data;
+ }
};
-
private:
struct Entry {
@@ -107,7 +108,7 @@ private:
Entry *next;
Pair pair;
- Entry() { next=0; }
+ Entry() { next = 0; }
};
Entry **hash_table;
@@ -116,204 +117,191 @@ private:
void make_hash_table() {
- ERR_FAIL_COND( hash_table );
-
+ ERR_FAIL_COND(hash_table);
- hash_table = memnew_arr( Entry*, (1<<MIN_HASH_TABLE_POWER) );
+ hash_table = memnew_arr(Entry *, (1 << MIN_HASH_TABLE_POWER));
hash_table_power = MIN_HASH_TABLE_POWER;
- elements=0;
- for (int i=0;i<(1<<MIN_HASH_TABLE_POWER);i++)
- hash_table[i]=0;
+ elements = 0;
+ for (int i = 0; i < (1 << MIN_HASH_TABLE_POWER); i++)
+ hash_table[i] = 0;
}
void erase_hash_table() {
ERR_FAIL_COND(elements);
- memdelete_arr( hash_table );
- hash_table=0;
- hash_table_power=0;
- elements=0;
+ memdelete_arr(hash_table);
+ hash_table = 0;
+ hash_table_power = 0;
+ elements = 0;
}
void check_hash_table() {
- int new_hash_table_power=-1;
+ int new_hash_table_power = -1;
- if ((int)elements > ( (1<<hash_table_power) * RELATIONSHIP ) ) {
+ if ((int)elements > ((1 << hash_table_power) * RELATIONSHIP)) {
/* rehash up */
- new_hash_table_power=hash_table_power+1;
+ new_hash_table_power = hash_table_power + 1;
- while( (int)elements > ( (1<<new_hash_table_power) * RELATIONSHIP ) ) {
+ while ((int)elements > ((1 << new_hash_table_power) * RELATIONSHIP)) {
new_hash_table_power++;
}
- } else if ( (hash_table_power>(int)MIN_HASH_TABLE_POWER) && ((int)elements < ( (1<<(hash_table_power-1)) * RELATIONSHIP ) ) ) {
+ } else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) {
/* rehash down */
- new_hash_table_power=hash_table_power-1;
+ new_hash_table_power = hash_table_power - 1;
- while( (int)elements < ( (1<<(new_hash_table_power-1)) * RELATIONSHIP ) ) {
+ while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) {
new_hash_table_power--;
}
- if (new_hash_table_power<(int)MIN_HASH_TABLE_POWER)
- new_hash_table_power=MIN_HASH_TABLE_POWER;
+ if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER)
+ new_hash_table_power = MIN_HASH_TABLE_POWER;
}
-
- if (new_hash_table_power==-1)
+ if (new_hash_table_power == -1)
return;
- Entry ** new_hash_table = memnew_arr( Entry*, (1<<new_hash_table_power) );
+ Entry **new_hash_table = memnew_arr(Entry *, (1 << new_hash_table_power));
if (!new_hash_table) {
ERR_PRINT("Out of Memory");
return;
}
- for (int i=0;i<(1<<new_hash_table_power);i++) {
+ for (int i = 0; i < (1 << new_hash_table_power); i++) {
- new_hash_table[i]=0;
+ new_hash_table[i] = 0;
}
- for (int i=0;i<(1<<hash_table_power);i++) {
+ for (int i = 0; i < (1 << hash_table_power); i++) {
- while( hash_table[i] ) {
+ while (hash_table[i]) {
- Entry *se=hash_table[i];
- hash_table[i]=se->next;
- int new_pos = se->hash & ((1<<new_hash_table_power)-1);
- se->next=new_hash_table[new_pos];
- new_hash_table[new_pos]=se;
+ Entry *se = hash_table[i];
+ hash_table[i] = se->next;
+ int new_pos = se->hash & ((1 << new_hash_table_power) - 1);
+ se->next = new_hash_table[new_pos];
+ new_hash_table[new_pos] = se;
}
-
}
if (hash_table)
- memdelete_arr( hash_table );
- hash_table=new_hash_table;
- hash_table_power=new_hash_table_power;
-
+ memdelete_arr(hash_table);
+ hash_table = new_hash_table;
+ hash_table_power = new_hash_table_power;
}
/* I want to have only one function.. */
- _FORCE_INLINE_ const Entry * get_entry( const TKey& p_key ) const {
+ _FORCE_INLINE_ const Entry *get_entry(const TKey &p_key) const {
- uint32_t hash = Hasher::hash( p_key );
- uint32_t index = hash&((1<<hash_table_power)-1);
+ uint32_t hash = Hasher::hash(p_key);
+ uint32_t index = hash & ((1 << hash_table_power) - 1);
Entry *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
- if (e->hash == hash && Comparator::compare(e->pair.key,p_key) ) {
+ if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
/* the pair exists in this hashtable, so just update data */
return e;
}
- e=e->next;
+ e = e->next;
}
return NULL;
}
- Entry * create_entry(const TKey& p_key) {
+ Entry *create_entry(const TKey &p_key) {
/* if entry doesn't exist, create it */
- Entry *e = memnew( Entry );
- ERR_FAIL_COND_V(!e,NULL); /* out of memory */
- uint32_t hash = Hasher::hash( p_key );
- uint32_t index = hash&((1<<hash_table_power)-1);
+ Entry *e = memnew(Entry);
+ ERR_FAIL_COND_V(!e, NULL); /* out of memory */
+ uint32_t hash = Hasher::hash(p_key);
+ uint32_t index = hash & ((1 << hash_table_power) - 1);
e->next = hash_table[index];
e->hash = hash;
- e->pair.key=p_key;
+ e->pair.key = p_key;
- hash_table[index]=e;
+ hash_table[index] = e;
elements++;
return e;
}
+ void copy_from(const HashMap &p_t) {
- void copy_from(const HashMap& p_t) {
-
- if (&p_t==this)
+ if (&p_t == this)
return; /* much less bother with that */
clear();
- if (!p_t.hash_table || p_t.hash_table_power==0)
+ if (!p_t.hash_table || p_t.hash_table_power == 0)
return; /* not copying from empty table */
- hash_table = memnew_arr(Entry*,1<<p_t.hash_table_power);
- hash_table_power=p_t.hash_table_power;
- elements=p_t.elements;
+ hash_table = memnew_arr(Entry *, 1 << p_t.hash_table_power);
+ hash_table_power = p_t.hash_table_power;
+ elements = p_t.elements;
- for (int i=0;i<( 1<<p_t.hash_table_power );i++) {
+ for (int i = 0; i < (1 << p_t.hash_table_power); i++) {
- hash_table[i]=NULL;
+ hash_table[i] = NULL;
const Entry *e = p_t.hash_table[i];
- while(e) {
+ while (e) {
- Entry *le = memnew( Entry ); /* local entry */
+ Entry *le = memnew(Entry); /* local entry */
- *le=*e; /* copy data */
+ *le = *e; /* copy data */
/* add to list and reassign pointers */
- le->next=hash_table[i];
- hash_table[i]=le;
+ le->next = hash_table[i];
+ hash_table[i] = le;
- e=e->next;
+ e = e->next;
}
-
-
}
-
-
}
-public:
+public:
+ void set(const TKey &p_key, const TData &p_data) {
- void set( const TKey& p_key, const TData& p_data ) {
-
- set( Pair( p_key, p_data ) );
-
+ set(Pair(p_key, p_data));
}
- void set( const Pair& p_pair ) {
+ void set(const Pair &p_pair) {
- Entry *e=NULL;
+ Entry *e = NULL;
if (!hash_table)
make_hash_table(); // if no table, make one
else
- e = const_cast<Entry*>( get_entry(p_pair.key) );
+ e = const_cast<Entry *>(get_entry(p_pair.key));
/* if we made it up to here, the pair doesn't exist, create and assign */
if (!e) {
- e=create_entry(p_pair.key);
+ e = create_entry(p_pair.key);
if (!e)
return;
check_hash_table(); // perform mantenience routine
}
e->pair.data = p_pair.data;
-
}
+ bool has(const TKey &p_key) const {
- bool has( const TKey& p_key ) const {
-
- return getptr(p_key)!=NULL;
+ return getptr(p_key) != NULL;
}
/**
@@ -322,17 +310,17 @@ public:
* first with has(key)
*/
- const TData& get( const TKey& p_key ) const {
+ const TData &get(const TKey &p_key) const {
- const TData* res = getptr(p_key);
- ERR_FAIL_COND_V(!res,*res);
+ const TData *res = getptr(p_key);
+ ERR_FAIL_COND_V(!res, *res);
return *res;
}
- TData& get( const TKey& p_key ) {
+ TData &get(const TKey &p_key) {
- TData* res = getptr(p_key);
- ERR_FAIL_COND_V(!res,*res);
+ TData *res = getptr(p_key);
+ ERR_FAIL_COND_V(!res, *res);
return *res;
}
@@ -341,33 +329,30 @@ public:
* This is mainly used for speed purposes.
*/
-
- _FORCE_INLINE_ TData* getptr( const TKey& p_key ) {
+ _FORCE_INLINE_ TData *getptr(const TKey &p_key) {
if (!hash_table)
return NULL;
- Entry *e=const_cast<Entry*>(get_entry(p_key ));
+ Entry *e = const_cast<Entry *>(get_entry(p_key));
if (e)
return &e->pair.data;
return NULL;
-
}
- _FORCE_INLINE_ const TData* getptr( const TKey& p_key ) const {
+ _FORCE_INLINE_ const TData *getptr(const TKey &p_key) const {
if (!hash_table)
return NULL;
- const Entry *e=const_cast<Entry*>(get_entry(p_key ));
+ const Entry *e = const_cast<Entry *>(get_entry(p_key));
if (e)
return &e->pair.data;
return NULL;
-
}
/**
@@ -375,129 +360,124 @@ public:
* This version is custom, will take a hash and a custom key (that should support operator==()
*/
- template<class C>
- _FORCE_INLINE_ TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) {
+ template <class C>
+ _FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) {
if (!hash_table)
return NULL;
uint32_t hash = p_custom_hash;
- uint32_t index = hash&((1<<hash_table_power)-1);
+ uint32_t index = hash & ((1 << hash_table_power) - 1);
Entry *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
- if (e->hash == hash && Comparator::compare(e->pair.key,p_custom_key) ) {
+ if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
/* the pair exists in this hashtable, so just update data */
return &e->pair.data;
}
- e=e->next;
+ e = e->next;
}
return NULL;
}
- template<class C>
- _FORCE_INLINE_ const TData* custom_getptr( C p_custom_key,uint32_t p_custom_hash ) const {
+ template <class C>
+ _FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const {
if (!hash_table)
return NULL;
uint32_t hash = p_custom_hash;
- uint32_t index = hash&((1<<hash_table_power)-1);
+ uint32_t index = hash & ((1 << hash_table_power) - 1);
const Entry *e = hash_table[index];
while (e) {
/* checking hash first avoids comparing key, which may take longer */
- if (e->hash == hash && Comparator::compare(e->pair.key,p_custom_key) ) {
+ if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
/* the pair exists in this hashtable, so just update data */
return &e->pair.data;
}
- e=e->next;
+ e = e->next;
}
return NULL;
}
-
/**
* Erase an item, return true if erasing was succesful
*/
- bool erase( const TKey& p_key ) {
+ bool erase(const TKey &p_key) {
if (!hash_table)
return false;
- uint32_t hash = Hasher::hash( p_key );
- uint32_t index = hash&((1<<hash_table_power)-1);
-
+ uint32_t hash = Hasher::hash(p_key);
+ uint32_t index = hash & ((1 << hash_table_power) - 1);
Entry *e = hash_table[index];
- Entry *p=NULL;
+ Entry *p = NULL;
while (e) {
/* checking hash first avoids comparing key, which may take longer */
- if (e->hash == hash && Comparator::compare(e->pair.key,p_key) ) {
+ if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
if (p) {
- p->next=e->next;
+ p->next = e->next;
} else {
//begin of list
- hash_table[index]=e->next;
+ hash_table[index] = e->next;
}
memdelete(e);
elements--;
- if (elements==0)
+ if (elements == 0)
erase_hash_table();
else
check_hash_table();
return true;
}
- p=e;
- e=e->next;
+ p = e;
+ e = e->next;
}
-
return false;
-
}
- inline const TData& operator[](const TKey& p_key) const { //constref
+ inline const TData &operator[](const TKey &p_key) const { //constref
return get(p_key);
}
- inline TData& operator[](const TKey& p_key ) { //assignment
+ inline TData &operator[](const TKey &p_key) { //assignment
- Entry *e=NULL;
+ Entry *e = NULL;
if (!hash_table)
make_hash_table(); // if no table, make one
else
- e = const_cast<Entry*>( get_entry(p_key) );
+ e = const_cast<Entry *>(get_entry(p_key));
/* if we made it up to here, the pair doesn't exist, create */
if (!e) {
- e=create_entry(p_key);
+ e = create_entry(p_key);
if (!e)
- return *(TData*)NULL; /* panic! */
+ return *(TData *)NULL; /* panic! */
check_hash_table(); // perform mantenience routine
}
return e->pair.data;
-
}
/**
@@ -515,13 +495,13 @@ public:
* }
*
*/
- const TKey* next(const TKey* p_key) const {
+ const TKey *next(const TKey *p_key) const {
if (!hash_table) return NULL;
if (!p_key) { /* get the first key */
- for (int i=0;i<(1<<hash_table_power);i++) {
+ for (int i = 0; i < (1 << hash_table_power); i++) {
if (hash_table[i]) {
return &hash_table[i]->pair.key;
@@ -530,17 +510,17 @@ public:
} else { /* get the next key */
- const Entry *e = get_entry( *p_key );
- ERR_FAIL_COND_V( !e, NULL ); /* invalid key supplied */
+ const Entry *e = get_entry(*p_key);
+ ERR_FAIL_COND_V(!e, NULL); /* invalid key supplied */
if (e->next) {
/* if there is a "next" in the list, return that */
return &e->next->pair.key;
} else {
/* go to next entries */
- uint32_t index = e->hash&((1<<hash_table_power)-1);
+ uint32_t index = e->hash & ((1 << hash_table_power) - 1);
index++;
- for (int i=index;i<(1<<hash_table_power);i++) {
+ for (int i = index; i < (1 << hash_table_power); i++) {
if (hash_table[i]) {
return &hash_table[i]->pair.key;
@@ -549,10 +529,8 @@ public:
}
/* nothing found, was at end */
-
}
-
return NULL; /* nothing found */
}
@@ -563,53 +541,52 @@ public:
inline bool empty() const {
- return elements==0;
+ return elements == 0;
}
void clear() {
/* clean up */
if (hash_table) {
- for (int i=0;i<(1<<hash_table_power);i++) {
+ for (int i = 0; i < (1 << hash_table_power); i++) {
while (hash_table[i]) {
- Entry *e=hash_table[i];
- hash_table[i]=e->next;
- memdelete( e );
+ Entry *e = hash_table[i];
+ hash_table[i] = e->next;
+ memdelete(e);
}
}
- memdelete_arr( hash_table );
+ memdelete_arr(hash_table);
}
- hash_table=0;
- hash_table_power=0;
- elements=0;
+ hash_table = 0;
+ hash_table_power = 0;
+ elements = 0;
}
-
- void operator=(const HashMap& p_table) {
+ void operator=(const HashMap &p_table) {
copy_from(p_table);
}
HashMap() {
- hash_table=NULL;
- elements=0;
- hash_table_power=0;
+ hash_table = NULL;
+ elements = 0;
+ hash_table_power = 0;
}
void get_key_value_ptr_array(const Pair **p_pairs) const {
if (!hash_table)
return;
- for(int i=0;i<(1<<hash_table_power);i++) {
+ for (int i = 0; i < (1 << hash_table_power); i++) {
- Entry *e=hash_table[i];
- while(e) {
- *p_pairs=&e->pair;
+ Entry *e = hash_table[i];
+ while (e) {
+ *p_pairs = &e->pair;
p_pairs++;
- e=e->next;
+ e = e->next;
}
}
}
@@ -617,24 +594,23 @@ public:
void get_key_list(List<TKey> *p_keys) const {
if (!hash_table)
return;
- for(int i=0;i<(1<<hash_table_power);i++) {
+ for (int i = 0; i < (1 << hash_table_power); i++) {
- Entry *e=hash_table[i];
- while(e) {
+ Entry *e = hash_table[i];
+ while (e) {
p_keys->push_back(e->pair.key);
- e=e->next;
+ e = e->next;
}
}
}
- HashMap(const HashMap& p_table) {
+ HashMap(const HashMap &p_table) {
- hash_table=NULL;
- elements=0;
- hash_table_power=0;
+ hash_table = NULL;
+ elements = 0;
+ hash_table_power = 0;
copy_from(p_table);
-
}
~HashMap() {
@@ -643,6 +619,4 @@ public:
}
};
-
-
#endif
diff --git a/core/hashfuncs.h b/core/hashfuncs.h
index 121d7e8c59..aff6772d68 100644
--- a/core/hashfuncs.h
+++ b/core/hashfuncs.h
@@ -29,15 +29,14 @@
#ifndef HASHFUNCS_H
#define HASHFUNCS_H
-#include "math_funcs.h"
#include "math_defs.h"
+#include "math_funcs.h"
#include "typedefs.h"
/**
* Hashing functions
*/
-
/**
* DJB2 Hash function
* @param C String
@@ -45,7 +44,7 @@
*/
static inline uint32_t hash_djb2(const char *p_cstr) {
- const unsigned char* chr=(const unsigned char*)p_cstr;
+ const unsigned char *chr = (const unsigned char *)p_cstr;
uint32_t hash = 5381;
uint32_t c;
@@ -55,99 +54,95 @@ static inline uint32_t hash_djb2(const char *p_cstr) {
return hash;
}
-static inline uint32_t hash_djb2_buffer(const uint8_t *p_buff, int p_len,uint32_t p_prev=5381) {
+static inline uint32_t hash_djb2_buffer(const uint8_t *p_buff, int p_len, uint32_t p_prev = 5381) {
uint32_t hash = p_prev;
- for(int i=0;i<p_len;i++)
+ for (int i = 0; i < p_len; i++)
hash = ((hash << 5) + hash) + p_buff[i]; /* hash * 33 + c */
return hash;
}
-static inline uint32_t hash_djb2_one_32(uint32_t p_in,uint32_t p_prev=5381) {
+static inline uint32_t hash_djb2_one_32(uint32_t p_in, uint32_t p_prev = 5381) {
- return ((p_prev<<5)+p_prev)+p_in;
+ return ((p_prev << 5) + p_prev) + p_in;
}
static inline uint32_t hash_one_uint64(const uint64_t p_int) {
- uint64_t v=p_int;
+ uint64_t v = p_int;
v = (~v) + (v << 18); // v = (v << 18) - v - 1;
v = v ^ (v >> 31);
v = v * 21; // v = (v + (v << 2)) + (v << 4);
v = v ^ (v >> 11);
v = v + (v << 6);
v = v ^ (v >> 22);
- return (int) v;
+ return (int)v;
}
-static inline uint32_t hash_djb2_one_float(float p_in,uint32_t p_prev=5381) {
+static inline uint32_t hash_djb2_one_float(float p_in, uint32_t p_prev = 5381) {
union {
float f;
uint32_t i;
} u;
// Normalize +/- 0.0 and NaN values so they hash the same.
- if (p_in==0.0f)
- u.f=0.0;
+ if (p_in == 0.0f)
+ u.f = 0.0;
else if (Math::is_nan(p_in))
- u.f=Math_NAN;
+ u.f = Math_NAN;
else
- u.f=p_in;
+ u.f = p_in;
- return ((p_prev<<5)+p_prev)+u.i;
+ return ((p_prev << 5) + p_prev) + u.i;
}
// Overload for real_t size changes
-static inline uint32_t hash_djb2_one_float(double p_in,uint32_t p_prev=5381) {
+static inline uint32_t hash_djb2_one_float(double p_in, uint32_t p_prev = 5381) {
union {
double d;
uint64_t i;
} u;
// Normalize +/- 0.0 and NaN values so they hash the same.
- if (p_in==0.0f)
- u.d=0.0;
+ if (p_in == 0.0f)
+ u.d = 0.0;
else if (Math::is_nan(p_in))
- u.d=Math_NAN;
+ u.d = Math_NAN;
else
- u.d=p_in;
+ u.d = p_in;
- return ((p_prev<<5)+p_prev) + hash_one_uint64(u.i);
+ return ((p_prev << 5) + p_prev) + hash_one_uint64(u.i);
}
-template<class T>
+template <class T>
static inline uint32_t make_uint32_t(T p_in) {
union {
T t;
uint32_t _u32;
} _u;
- _u._u32=0;
- _u.t=p_in;
+ _u._u32 = 0;
+ _u.t = p_in;
return _u._u32;
}
+static inline uint64_t hash_djb2_one_64(uint64_t p_in, uint64_t p_prev = 5381) {
-static inline uint64_t hash_djb2_one_64(uint64_t p_in,uint64_t p_prev=5381) {
-
- return ((p_prev<<5)+p_prev)+p_in;
+ return ((p_prev << 5) + p_prev) + p_in;
}
-
-template<class T>
+template <class T>
static inline uint64_t make_uint64_t(T p_in) {
union {
T t;
uint64_t _u64;
} _u;
- _u._u64=0; // in case p_in is smaller
+ _u._u64 = 0; // in case p_in is smaller
- _u.t=p_in;
+ _u.t = p_in;
return _u._u64;
}
-
-
#endif
diff --git a/core/helper/math_fieldwise.cpp b/core/helper/math_fieldwise.cpp
index 1ea754b70f..377a3f8234 100644
--- a/core/helper/math_fieldwise.cpp
+++ b/core/helper/math_fieldwise.cpp
@@ -31,12 +31,17 @@
#include "core/helper/math_fieldwise.h"
-#define SETUP_TYPE(m_type) m_type source=p_source; m_type target=p_target;
-#define TRY_TRANSFER_FIELD(m_name,m_member) if (p_field==m_name) { target.m_member=source.m_member; }
+#define SETUP_TYPE(m_type) \
+ m_type source = p_source; \
+ m_type target = p_target;
+#define TRY_TRANSFER_FIELD(m_name, m_member) \
+ if (p_field == m_name) { \
+ target.m_member = source.m_member; \
+ }
-Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const String& p_field) {
+Variant fieldwise_assign(const Variant &p_target, const Variant &p_source, const String &p_field) {
- ERR_FAIL_COND_V(p_target.get_type()!=p_source.get_type(),p_target);
+ ERR_FAIL_COND_V(p_target.get_type() != p_source.get_type(), p_target);
switch (p_source.get_type()) {
@@ -169,7 +174,7 @@ Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const
ERR_FAIL_V(p_target);
}
- /* clang-format on */
+ /* clang-format on */
}
}
diff --git a/core/helper/math_fieldwise.h b/core/helper/math_fieldwise.h
index 31f9af8d0b..e73227f148 100644
--- a/core/helper/math_fieldwise.h
+++ b/core/helper/math_fieldwise.h
@@ -33,7 +33,7 @@
#include "core/variant.h"
-Variant fieldwise_assign(const Variant& p_target, const Variant& p_source, const String& p_field);
+Variant fieldwise_assign(const Variant &p_target, const Variant &p_source, const String &p_field);
#endif // TOOLS_ENABLED
diff --git a/core/helper/value_evaluator.h b/core/helper/value_evaluator.h
index 9ea03db4c6..e001e1646a 100644
--- a/core/helper/value_evaluator.h
+++ b/core/helper/value_evaluator.h
@@ -34,8 +34,9 @@
class ValueEvaluator : public Object {
GDCLASS(ValueEvaluator, Object);
+
public:
- virtual double eval(const String& p_text) {
+ virtual double eval(const String &p_text) {
return p_text.to_double();
}
};
diff --git a/core/image.cpp b/core/image.cpp
index 037ff82452..649a51c174 100644
--- a/core/image.cpp
+++ b/core/image.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "image.h"
-#include "hash_map.h"
#include "core/io/image_loader.h"
#include "core/os/copymem.h"
+#include "hash_map.h"
#include "hq2x.h"
#include "print_string.h"
#include <stdio.h>
-
-const char* Image::format_names[Image::FORMAT_MAX]={
+const char *Image::format_names[Image::FORMAT_MAX] = {
"Lum8", //luminance
"LumAlpha8", //luminance-alpha
"Red8",
@@ -80,113 +79,124 @@ const char* Image::format_names[Image::FORMAT_MAX]={
SavePNGFunc Image::save_png_func = NULL;
+void Image::_put_pixelb(int p_x, int p_y, uint32_t p_pixelsize, uint8_t *p_dst, const uint8_t *p_src) {
-void Image::_put_pixelb(int p_x,int p_y, uint32_t p_pixelsize,uint8_t *p_dst,const uint8_t *p_src) {
+ uint32_t ofs = (p_y * width + p_x) * p_pixelsize;
-
- uint32_t ofs=(p_y*width+p_x)*p_pixelsize;
-
- for(uint32_t i=0;i<p_pixelsize;i++) {
- p_dst[ofs+i]=p_src[i];
+ for (uint32_t i = 0; i < p_pixelsize; i++) {
+ p_dst[ofs + i] = p_src[i];
}
}
-void Image::_get_pixelb(int p_x,int p_y, uint32_t p_pixelsize,const uint8_t *p_src,uint8_t *p_dst) {
+void Image::_get_pixelb(int p_x, int p_y, uint32_t p_pixelsize, const uint8_t *p_src, uint8_t *p_dst) {
- uint32_t ofs=(p_y*width+p_x)*p_pixelsize;
+ uint32_t ofs = (p_y * width + p_x) * p_pixelsize;
- for(uint32_t i=0;i<p_pixelsize;i++) {
- p_dst[ofs]=p_src[ofs+i];
+ for (uint32_t i = 0; i < p_pixelsize; i++) {
+ p_dst[ofs] = p_src[ofs + i];
}
-
}
-
int Image::get_format_pixel_size(Format p_format) {
- switch(p_format) {
- case FORMAT_L8: return 1; //luminance
- case FORMAT_LA8: return 2; //luminance-alpha
+ switch (p_format) {
+ case FORMAT_L8:
+ return 1; //luminance
+ case FORMAT_LA8:
+ return 2; //luminance-alpha
case FORMAT_R8: return 1;
case FORMAT_RG8: return 2;
case FORMAT_RGB8: return 3;
case FORMAT_RGBA8: return 4;
- case FORMAT_RGB565: return 2; //16 bit
+ case FORMAT_RGB565:
+ return 2; //16 bit
case FORMAT_RGBA4444: return 2;
case FORMAT_RGBA5551: return 2;
- case FORMAT_RF: return 4; //float
+ case FORMAT_RF:
+ return 4; //float
case FORMAT_RGF: return 8;
case FORMAT_RGBF: return 12;
case FORMAT_RGBAF: return 16;
- case FORMAT_RH: return 2; //half float
+ case FORMAT_RH:
+ return 2; //half float
case FORMAT_RGH: return 4;
case FORMAT_RGBH: return 8;
case FORMAT_RGBAH: return 12;
- case FORMAT_DXT1: return 1; //s3tc bc1
- case FORMAT_DXT3: return 1; //bc2
- case FORMAT_DXT5: return 1; //bc3
- case FORMAT_ATI1: return 1; //bc4
- case FORMAT_ATI2: return 1; //bc5
- case FORMAT_BPTC_RGBA: return 1; //btpc bc6h
- case FORMAT_BPTC_RGBF: return 1; //float /
- case FORMAT_BPTC_RGBFU: return 1; //unsigned float
- case FORMAT_PVRTC2: return 1; //pvrtc
+ case FORMAT_DXT1:
+ return 1; //s3tc bc1
+ case FORMAT_DXT3:
+ return 1; //bc2
+ case FORMAT_DXT5:
+ return 1; //bc3
+ case FORMAT_ATI1:
+ return 1; //bc4
+ case FORMAT_ATI2:
+ return 1; //bc5
+ case FORMAT_BPTC_RGBA:
+ return 1; //btpc bc6h
+ case FORMAT_BPTC_RGBF:
+ return 1; //float /
+ case FORMAT_BPTC_RGBFU:
+ return 1; //unsigned float
+ case FORMAT_PVRTC2:
+ return 1; //pvrtc
case FORMAT_PVRTC2A: return 1;
case FORMAT_PVRTC4: return 1;
case FORMAT_PVRTC4A: return 1;
- case FORMAT_ETC: return 1; //etc1
- case FORMAT_ETC2_R11: return 1; //etc2
- case FORMAT_ETC2_R11S: return 1; //signed: return 1; NOT srgb.
+ case FORMAT_ETC:
+ return 1; //etc1
+ case FORMAT_ETC2_R11:
+ return 1; //etc2
+ case FORMAT_ETC2_R11S:
+ return 1; //signed: return 1; NOT srgb.
case FORMAT_ETC2_RG11: return 1;
case FORMAT_ETC2_RG11S: return 1;
case FORMAT_ETC2_RGB8: return 1;
case FORMAT_ETC2_RGBA8: return 1;
case FORMAT_ETC2_RGB8A1: return 1;
- case FORMAT_MAX: {}
-
-
+ case FORMAT_MAX: {
+ }
}
return 0;
}
-void Image::get_format_min_pixel_size(Format p_format,int &r_w, int &r_h) {
-
+void Image::get_format_min_pixel_size(Format p_format, int &r_w, int &r_h) {
- switch(p_format) {
+ switch (p_format) {
case FORMAT_DXT1: //s3tc bc1
case FORMAT_DXT3: //bc2
case FORMAT_DXT5: //bc3
case FORMAT_ATI1: //bc4
case FORMAT_ATI2: { //bc5 case case FORMAT_DXT1:
- r_w=4;
- r_h=4;
+ r_w = 4;
+ r_h = 4;
} break;
case FORMAT_PVRTC2:
case FORMAT_PVRTC2A: {
- r_w=16;
- r_h=8;
+ r_w = 16;
+ r_h = 8;
} break;
case FORMAT_PVRTC4A:
case FORMAT_PVRTC4: {
- r_w=8;
- r_h=8;
+ r_w = 8;
+ r_h = 8;
} break;
case FORMAT_ETC: {
- r_w=4;
- r_h=4;
+ r_w = 4;
+ r_h = 4;
} break;
case FORMAT_BPTC_RGBA:
case FORMAT_BPTC_RGBF:
case FORMAT_BPTC_RGBFU: {
- r_w=4;
- r_h=4;
+ r_w = 4;
+ r_h = 4;
} break;
- case FORMAT_ETC2_R11: //etc2
+ case FORMAT_ETC2_R11: //etc2
case FORMAT_ETC2_R11S: //signed: NOT srgb.
case FORMAT_ETC2_RG11:
case FORMAT_ETC2_RG11S:
@@ -194,85 +204,79 @@ void Image::get_format_min_pixel_size(Format p_format,int &r_w, int &r_h) {
case FORMAT_ETC2_RGBA8:
case FORMAT_ETC2_RGB8A1: {
- r_w=4;
- r_h=4;
+ r_w = 4;
+ r_h = 4;
} break;
default: {
- r_w=1;
- r_h=1;
+ r_w = 1;
+ r_h = 1;
} break;
}
-
}
-
int Image::get_format_pixel_rshift(Format p_format) {
- if (p_format==FORMAT_DXT1 || p_format==FORMAT_ATI1 || p_format==FORMAT_PVRTC4 || p_format==FORMAT_PVRTC4A || p_format==FORMAT_ETC || p_format==FORMAT_ETC2_R11 || p_format==FORMAT_ETC2_R11S || p_format==FORMAT_ETC2_RGB8 || p_format==FORMAT_ETC2_RGB8A1)
+ if (p_format == FORMAT_DXT1 || p_format == FORMAT_ATI1 || p_format == FORMAT_PVRTC4 || p_format == FORMAT_PVRTC4A || p_format == FORMAT_ETC || p_format == FORMAT_ETC2_R11 || p_format == FORMAT_ETC2_R11S || p_format == FORMAT_ETC2_RGB8 || p_format == FORMAT_ETC2_RGB8A1)
return 1;
- else if (p_format==FORMAT_PVRTC2 || p_format==FORMAT_PVRTC2A)
+ else if (p_format == FORMAT_PVRTC2 || p_format == FORMAT_PVRTC2A)
return 2;
else
return 0;
}
+void Image::_get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const {
-void Image::_get_mipmap_offset_and_size(int p_mipmap,int &r_offset, int &r_width,int &r_height) const {
-
- int w=width;
- int h=height;
- int ofs=0;
+ int w = width;
+ int h = height;
+ int ofs = 0;
int pixel_size = get_format_pixel_size(format);
int pixel_rshift = get_format_pixel_rshift(format);
- int minw,minh;
- get_format_min_pixel_size(format,minw,minh);
-
- for(int i=0;i<p_mipmap;i++) {
- int s = w*h;
- s*=pixel_size;
- s>>=pixel_rshift;
- ofs+=s;
- w=MAX(minw,w>>1);
- h=MAX(minh,h>>1);
+ int minw, minh;
+ get_format_min_pixel_size(format, minw, minh);
+
+ for (int i = 0; i < p_mipmap; i++) {
+ int s = w * h;
+ s *= pixel_size;
+ s >>= pixel_rshift;
+ ofs += s;
+ w = MAX(minw, w >> 1);
+ h = MAX(minh, h >> 1);
}
- r_offset=ofs;
- r_width=w;
- r_height=h;
+ r_offset = ofs;
+ r_width = w;
+ r_height = h;
}
int Image::get_mipmap_offset(int p_mipmap) const {
- ERR_FAIL_INDEX_V(p_mipmap,get_mipmap_count()+1,-1);
+ ERR_FAIL_INDEX_V(p_mipmap, get_mipmap_count() + 1, -1);
- int ofs,w,h;
- _get_mipmap_offset_and_size(p_mipmap,ofs,w,h);
+ int ofs, w, h;
+ _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
return ofs;
}
-void Image::get_mipmap_offset_and_size(int p_mipmap,int &r_ofs, int &r_size) const {
+void Image::get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const {
- int ofs,w,h;
- _get_mipmap_offset_and_size(p_mipmap,ofs,w,h);
+ int ofs, w, h;
+ _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
int ofs2;
- _get_mipmap_offset_and_size(p_mipmap+1,ofs2,w,h);
- r_ofs=ofs;
- r_size=ofs2-ofs;
-
+ _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w, h);
+ r_ofs = ofs;
+ r_size = ofs2 - ofs;
}
-void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap,int &r_ofs, int &r_size,int &w, int& h) const {
-
+void Image::get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const {
int ofs;
- _get_mipmap_offset_and_size(p_mipmap,ofs,w,h);
- int ofs2,w2,h2;
- _get_mipmap_offset_and_size(p_mipmap+1,ofs2,w2,h2);
- r_ofs=ofs;
- r_size=ofs2-ofs;
-
+ _get_mipmap_offset_and_size(p_mipmap, ofs, w, h);
+ int ofs2, w2, h2;
+ _get_mipmap_offset_and_size(p_mipmap + 1, ofs2, w2, h2);
+ r_ofs = ofs;
+ r_size = ofs2 - ofs;
}
int Image::get_width() const {
@@ -280,7 +284,7 @@ int Image::get_width() const {
return width;
}
-int Image::get_height() const{
+int Image::get_height() const {
return height;
}
@@ -293,77 +297,70 @@ bool Image::has_mipmaps() const {
int Image::get_mipmap_count() const {
if (mipmaps)
- return get_image_required_mipmaps(width,height,format);
+ return get_image_required_mipmaps(width, height, format);
else
return 0;
}
-
//using template generates perfectly optimized code due to constant expression reduction and unused variable removal present in all compilers
-template<uint32_t read_bytes,bool read_alpha,uint32_t write_bytes,bool write_alpha,bool read_gray,bool write_gray>
-static void _convert( int p_width,int p_height,const uint8_t* p_src,uint8_t* p_dst ){
-
-
+template <uint32_t read_bytes, bool read_alpha, uint32_t write_bytes, bool write_alpha, bool read_gray, bool write_gray>
+static void _convert(int p_width, int p_height, const uint8_t *p_src, uint8_t *p_dst) {
- for(int y=0;y<p_height;y++) {
- for(int x=0;x<p_width;x++) {
+ for (int y = 0; y < p_height; y++) {
+ for (int x = 0; x < p_width; x++) {
- const uint8_t *rofs = &p_src[((y*p_width)+x)*(read_bytes+(read_alpha?1:0))];
- uint8_t *wofs = &p_dst[((y*p_width)+x)*(write_bytes+(write_alpha?1:0))];
+ const uint8_t *rofs = &p_src[((y * p_width) + x) * (read_bytes + (read_alpha ? 1 : 0))];
+ uint8_t *wofs = &p_dst[((y * p_width) + x) * (write_bytes + (write_alpha ? 1 : 0))];
uint8_t rgba[4];
if (read_gray) {
- rgba[0]=rofs[0];
- rgba[1]=rofs[0];
- rgba[2]=rofs[0];
+ rgba[0] = rofs[0];
+ rgba[1] = rofs[0];
+ rgba[2] = rofs[0];
} else {
- for(uint32_t i=0;i<MAX(read_bytes,write_bytes);i++) {
+ for (uint32_t i = 0; i < MAX(read_bytes, write_bytes); i++) {
- rgba[i]=(i<read_bytes)?rofs[i]:0;
+ rgba[i] = (i < read_bytes) ? rofs[i] : 0;
}
}
if (read_alpha || write_alpha) {
- rgba[3]=read_alpha?rofs[read_bytes]:255;
+ rgba[3] = read_alpha ? rofs[read_bytes] : 255;
}
if (write_gray) {
//TODO: not correct grayscale, should use fixed point version of actual weights
- wofs[0]=uint8_t((uint16_t(rofs[0])+uint16_t(rofs[1])+uint16_t(rofs[2]))/3);
+ wofs[0] = uint8_t((uint16_t(rofs[0]) + uint16_t(rofs[1]) + uint16_t(rofs[2])) / 3);
} else {
- for(uint32_t i=0;i<write_bytes;i++) {
+ for (uint32_t i = 0; i < write_bytes; i++) {
- wofs[i]=rgba[i];
+ wofs[i] = rgba[i];
}
}
if (write_alpha) {
- wofs[write_bytes]=rgba[3];
+ wofs[write_bytes] = rgba[3];
}
-
}
}
-
}
-void Image::convert( Format p_new_format ){
+void Image::convert(Format p_new_format) {
- if (data.size()==0)
+ if (data.size() == 0)
return;
- if (p_new_format==format)
+ if (p_new_format == format)
return;
-
- if (format>=FORMAT_RGB565 || p_new_format>=FORMAT_RGB565) {
+ if (format >= FORMAT_RGB565 || p_new_format >= FORMAT_RGB565) {
ERR_EXPLAIN("Cannot convert to <-> from non byte formats.");
ERR_FAIL();
}
-
- Image new_img(width,height,0,p_new_format);
+ Image new_img(width, height, 0, p_new_format);
//int len=data.size();
@@ -373,179 +370,168 @@ void Image::convert( Format p_new_format ){
const uint8_t *rptr = r.ptr();
uint8_t *wptr = w.ptr();
- int conversion_type = format | p_new_format<<8;
-
- switch(conversion_type) {
-
- case FORMAT_L8|(FORMAT_LA8<<8): _convert<1,false,1,true,true,true>( width, height,rptr, wptr ); break;
- case FORMAT_L8|(FORMAT_R8<<8): _convert<1,false,1,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_L8|(FORMAT_RG8<<8): _convert<1,false,2,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_L8|(FORMAT_RGB8<<8): _convert<1,false,3,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_L8|(FORMAT_RGBA8<<8): _convert<1,false,3,true,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_LA8|(FORMAT_L8<<8): _convert<1,true,1,false,true,true>( width, height,rptr, wptr ); break;
- case FORMAT_LA8|(FORMAT_R8<<8): _convert<1,true,1,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_LA8|(FORMAT_RG8<<8): _convert<1,true,2,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_LA8|(FORMAT_RGB8<<8): _convert<1,true,3,false,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_LA8|(FORMAT_RGBA8<<8): _convert<1,true,3,true,true,false>( width, height,rptr, wptr ); break;
- case FORMAT_R8|(FORMAT_L8<<8): _convert<1,false,1,false,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_R8|(FORMAT_LA8<<8): _convert<1,false,1,true,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_R8|(FORMAT_RG8<<8): _convert<1,false,2,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_R8|(FORMAT_RGB8<<8): _convert<1,false,3,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_R8|(FORMAT_RGBA8<<8): _convert<1,false,3,true,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RG8|(FORMAT_L8<<8): _convert<2,false,1,false,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RG8|(FORMAT_LA8<<8): _convert<2,false,1,true,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RG8|(FORMAT_R8<<8): _convert<2,false,1,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RG8|(FORMAT_RGB8<<8): _convert<2,false,3,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RG8|(FORMAT_RGBA8<<8): _convert<2,false,3,true,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGB8|(FORMAT_L8<<8): _convert<3,false,1,false,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RGB8|(FORMAT_LA8<<8): _convert<3,false,1,true,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RGB8|(FORMAT_R8<<8): _convert<3,false,1,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGB8|(FORMAT_RG8<<8): _convert<3,false,2,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGB8|(FORMAT_RGBA8<<8): _convert<3,false,3,true,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGBA8|(FORMAT_L8<<8): _convert<3,true,1,false,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RGBA8|(FORMAT_LA8<<8): _convert<3,true,1,true,false,true>( width, height,rptr, wptr ); break;
- case FORMAT_RGBA8|(FORMAT_R8<<8): _convert<3,true,1,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGBA8|(FORMAT_RG8<<8): _convert<3,true,2,false,false,false>( width, height,rptr, wptr ); break;
- case FORMAT_RGBA8|(FORMAT_RGB8<<8): _convert<3,true,3,false,false,false>( width, height,rptr, wptr ); break;
-
+ int conversion_type = format | p_new_format << 8;
+
+ switch (conversion_type) {
+
+ case FORMAT_L8 | (FORMAT_LA8 << 8): _convert<1, false, 1, true, true, true>(width, height, rptr, wptr); break;
+ case FORMAT_L8 | (FORMAT_R8 << 8): _convert<1, false, 1, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_L8 | (FORMAT_RG8 << 8): _convert<1, false, 2, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_L8 | (FORMAT_RGB8 << 8): _convert<1, false, 3, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_L8 | (FORMAT_RGBA8 << 8): _convert<1, false, 3, true, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_LA8 | (FORMAT_L8 << 8): _convert<1, true, 1, false, true, true>(width, height, rptr, wptr); break;
+ case FORMAT_LA8 | (FORMAT_R8 << 8): _convert<1, true, 1, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_LA8 | (FORMAT_RG8 << 8): _convert<1, true, 2, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_LA8 | (FORMAT_RGB8 << 8): _convert<1, true, 3, false, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_LA8 | (FORMAT_RGBA8 << 8): _convert<1, true, 3, true, true, false>(width, height, rptr, wptr); break;
+ case FORMAT_R8 | (FORMAT_L8 << 8): _convert<1, false, 1, false, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_R8 | (FORMAT_LA8 << 8): _convert<1, false, 1, true, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_R8 | (FORMAT_RG8 << 8): _convert<1, false, 2, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_R8 | (FORMAT_RGB8 << 8): _convert<1, false, 3, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_R8 | (FORMAT_RGBA8 << 8): _convert<1, false, 3, true, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RG8 | (FORMAT_L8 << 8): _convert<2, false, 1, false, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RG8 | (FORMAT_LA8 << 8): _convert<2, false, 1, true, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RG8 | (FORMAT_R8 << 8): _convert<2, false, 1, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RG8 | (FORMAT_RGB8 << 8): _convert<2, false, 3, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RG8 | (FORMAT_RGBA8 << 8): _convert<2, false, 3, true, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGB8 | (FORMAT_L8 << 8): _convert<3, false, 1, false, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RGB8 | (FORMAT_LA8 << 8): _convert<3, false, 1, true, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RGB8 | (FORMAT_R8 << 8): _convert<3, false, 1, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGB8 | (FORMAT_RG8 << 8): _convert<3, false, 2, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGB8 | (FORMAT_RGBA8 << 8): _convert<3, false, 3, true, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGBA8 | (FORMAT_L8 << 8): _convert<3, true, 1, false, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RGBA8 | (FORMAT_LA8 << 8): _convert<3, true, 1, true, false, true>(width, height, rptr, wptr); break;
+ case FORMAT_RGBA8 | (FORMAT_R8 << 8): _convert<3, true, 1, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGBA8 | (FORMAT_RG8 << 8): _convert<3, true, 2, false, false, false>(width, height, rptr, wptr); break;
+ case FORMAT_RGBA8 | (FORMAT_RGB8 << 8): _convert<3, true, 3, false, false, false>(width, height, rptr, wptr); break;
}
-
r = PoolVector<uint8_t>::Read();
w = PoolVector<uint8_t>::Write();
- bool gen_mipmaps=mipmaps;
+ bool gen_mipmaps = mipmaps;
//mipmaps=false;
- *this=new_img;
+ *this = new_img;
if (gen_mipmaps)
generate_mipmaps();
-
}
-Image::Format Image::get_format() const{
+Image::Format Image::get_format() const {
return format;
}
-static double _bicubic_interp_kernel( double x ) {
+static double _bicubic_interp_kernel(double x) {
x = ABS(x);
double bc = 0;
- if ( x <= 1 )
- bc = ( 1.5 * x - 2.5 ) * x * x + 1;
- else if ( x < 2 )
- bc = ( ( -0.5 * x + 2.5 ) * x - 4 ) * x + 2;
-
+ if (x <= 1)
+ bc = (1.5 * x - 2.5) * x * x + 1;
+ else if (x < 2)
+ bc = ((-0.5 * x + 2.5) * x - 4) * x + 2;
return bc;
}
-template<int CC>
-static void _scale_cubic(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
-
+template <int CC>
+static void _scale_cubic(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
// get source image size
- int width = p_src_width;
- int height = p_src_height;
- double xfac = (double) width / p_dst_width;
- double yfac = (double) height / p_dst_height;
+ int width = p_src_width;
+ int height = p_src_height;
+ double xfac = (double)width / p_dst_width;
+ double yfac = (double)height / p_dst_height;
// coordinates of source points and cooefficiens
- double ox, oy, dx, dy, k1, k2;
- int ox1, oy1, ox2, oy2;
+ double ox, oy, dx, dy, k1, k2;
+ int ox1, oy1, ox2, oy2;
// destination pixel values
// width and height decreased by 1
int ymax = height - 1;
int xmax = width - 1;
// temporary pointer
- for ( uint32_t y = 0; y < p_dst_height; y++ ) {
+ for (uint32_t y = 0; y < p_dst_height; y++) {
// Y coordinates
- oy = (double) y * yfac - 0.5f;
- oy1 = (int) oy;
- dy = oy - (double) oy1;
+ oy = (double)y * yfac - 0.5f;
+ oy1 = (int)oy;
+ dy = oy - (double)oy1;
- for ( uint32_t x = 0; x < p_dst_width; x++ ) {
+ for (uint32_t x = 0; x < p_dst_width; x++) {
// X coordinates
- ox = (double) x * xfac - 0.5f;
- ox1 = (int) ox;
- dx = ox - (double) ox1;
+ ox = (double)x * xfac - 0.5f;
+ ox1 = (int)ox;
+ dx = ox - (double)ox1;
// initial pixel value
- uint8_t *dst=p_dst + (y*p_dst_width+x)*CC;
+ uint8_t *dst = p_dst + (y * p_dst_width + x) * CC;
double color[CC];
- for(int i=0;i<CC;i++) {
- color[i]=0;
+ for (int i = 0; i < CC; i++) {
+ color[i] = 0;
}
-
-
- for ( int n = -1; n < 3; n++ ) {
+ for (int n = -1; n < 3; n++) {
// get Y cooefficient
- k1 = _bicubic_interp_kernel( dy - (double) n );
+ k1 = _bicubic_interp_kernel(dy - (double)n);
oy2 = oy1 + n;
- if ( oy2 < 0 )
+ if (oy2 < 0)
oy2 = 0;
- if ( oy2 > ymax )
+ if (oy2 > ymax)
oy2 = ymax;
- for ( int m = -1; m < 3; m++ ) {
+ for (int m = -1; m < 3; m++) {
// get X cooefficient
- k2 = k1 * _bicubic_interp_kernel( (double) m - dx );
+ k2 = k1 * _bicubic_interp_kernel((double)m - dx);
ox2 = ox1 + m;
- if ( ox2 < 0 )
+ if (ox2 < 0)
ox2 = 0;
- if ( ox2 > xmax )
+ if (ox2 > xmax)
ox2 = xmax;
// get pixel of original image
- const uint8_t *p = p_src + (oy2 * p_src_width + ox2)*CC;
+ const uint8_t *p = p_src + (oy2 * p_src_width + ox2) * CC;
- for(int i=0;i<CC;i++) {
+ for (int i = 0; i < CC; i++) {
- color[i]+=p[i]*k2;
+ color[i] += p[i] * k2;
}
}
}
- for(int i=0;i<CC;i++) {
- dst[i]=CLAMP(Math::fast_ftoi(color[i]),0,255);
+ for (int i = 0; i < CC; i++) {
+ dst[i] = CLAMP(Math::fast_ftoi(color[i]), 0, 255);
}
}
}
}
-
-
-
-template<int CC>
-static void _scale_bilinear(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
+template <int CC>
+static void _scale_bilinear(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
enum {
- FRAC_BITS=8,
- FRAC_LEN=(1<<FRAC_BITS),
- FRAC_MASK=FRAC_LEN-1
+ FRAC_BITS = 8,
+ FRAC_LEN = (1 << FRAC_BITS),
+ FRAC_MASK = FRAC_LEN - 1
};
- for(uint32_t i=0;i<p_dst_height;i++) {
+ for (uint32_t i = 0; i < p_dst_height; i++) {
- uint32_t src_yofs_up_fp = (i*p_src_height*FRAC_LEN/p_dst_height);
+ uint32_t src_yofs_up_fp = (i * p_src_height * FRAC_LEN / p_dst_height);
uint32_t src_yofs_frac = src_yofs_up_fp & FRAC_MASK;
uint32_t src_yofs_up = src_yofs_up_fp >> FRAC_BITS;
-
- uint32_t src_yofs_down = (i+1)*p_src_height/p_dst_height;
- if (src_yofs_down>=p_src_height)
- src_yofs_down=p_src_height-1;
+ uint32_t src_yofs_down = (i + 1) * p_src_height / p_dst_height;
+ if (src_yofs_down >= p_src_height)
+ src_yofs_down = p_src_height - 1;
//src_yofs_up*=CC;
//src_yofs_down*=CC;
@@ -553,60 +539,57 @@ static void _scale_bilinear(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src
uint32_t y_ofs_up = src_yofs_up * p_src_width * CC;
uint32_t y_ofs_down = src_yofs_down * p_src_width * CC;
- for(uint32_t j=0;j<p_dst_width;j++) {
+ for (uint32_t j = 0; j < p_dst_width; j++) {
- uint32_t src_xofs_left_fp = (j*p_src_width*FRAC_LEN/p_dst_width);
+ uint32_t src_xofs_left_fp = (j * p_src_width * FRAC_LEN / p_dst_width);
uint32_t src_xofs_frac = src_xofs_left_fp & FRAC_MASK;
uint32_t src_xofs_left = src_xofs_left_fp >> FRAC_BITS;
- uint32_t src_xofs_right = (j+1)*p_src_width/p_dst_width;
- if (src_xofs_right>=p_src_width)
- src_xofs_right=p_src_width-1;
+ uint32_t src_xofs_right = (j + 1) * p_src_width / p_dst_width;
+ if (src_xofs_right >= p_src_width)
+ src_xofs_right = p_src_width - 1;
- src_xofs_left*=CC;
- src_xofs_right*=CC;
+ src_xofs_left *= CC;
+ src_xofs_right *= CC;
- for(uint32_t l=0;l<CC;l++) {
+ for (uint32_t l = 0; l < CC; l++) {
- uint32_t p00=p_src[y_ofs_up+src_xofs_left+l]<<FRAC_BITS;
- uint32_t p10=p_src[y_ofs_up+src_xofs_right+l]<<FRAC_BITS;
- uint32_t p01=p_src[y_ofs_down+src_xofs_left+l]<<FRAC_BITS;
- uint32_t p11=p_src[y_ofs_down+src_xofs_right+l]<<FRAC_BITS;
+ uint32_t p00 = p_src[y_ofs_up + src_xofs_left + l] << FRAC_BITS;
+ uint32_t p10 = p_src[y_ofs_up + src_xofs_right + l] << FRAC_BITS;
+ uint32_t p01 = p_src[y_ofs_down + src_xofs_left + l] << FRAC_BITS;
+ uint32_t p11 = p_src[y_ofs_down + src_xofs_right + l] << FRAC_BITS;
- uint32_t interp_up = p00+(((p10-p00)*src_xofs_frac)>>FRAC_BITS);
- uint32_t interp_down = p01+(((p11-p01)*src_xofs_frac)>>FRAC_BITS);
- uint32_t interp = interp_up+(((interp_down-interp_up)*src_yofs_frac)>>FRAC_BITS);
- interp>>=FRAC_BITS;
- p_dst[i*p_dst_width*CC+j*CC+l]=interp;
+ uint32_t interp_up = p00 + (((p10 - p00) * src_xofs_frac) >> FRAC_BITS);
+ uint32_t interp_down = p01 + (((p11 - p01) * src_xofs_frac) >> FRAC_BITS);
+ uint32_t interp = interp_up + (((interp_down - interp_up) * src_yofs_frac) >> FRAC_BITS);
+ interp >>= FRAC_BITS;
+ p_dst[i * p_dst_width * CC + j * CC + l] = interp;
}
}
}
}
+template <int CC>
+static void _scale_nearest(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
-template<int CC>
-static void _scale_nearest(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_src_width, uint32_t p_src_height, uint32_t p_dst_width, uint32_t p_dst_height) {
+ for (uint32_t i = 0; i < p_dst_height; i++) {
-
- for(uint32_t i=0;i<p_dst_height;i++) {
-
- uint32_t src_yofs = i*p_src_height/p_dst_height;
+ uint32_t src_yofs = i * p_src_height / p_dst_height;
uint32_t y_ofs = src_yofs * p_src_width * CC;
- for(uint32_t j=0;j<p_dst_width;j++) {
+ for (uint32_t j = 0; j < p_dst_width; j++) {
- uint32_t src_xofs = j*p_src_width/p_dst_width;
- src_xofs*=CC;
+ uint32_t src_xofs = j * p_src_width / p_dst_width;
+ src_xofs *= CC;
- for(uint32_t l=0;l<CC;l++) {
+ for (uint32_t l = 0; l < CC; l++) {
- uint32_t p=p_src[y_ofs+src_xofs+l];
- p_dst[i*p_dst_width*CC+j*CC+l]=p;
+ uint32_t p = p_src[y_ofs + src_xofs + l];
+ p_dst[i * p_dst_width * CC + j * CC + l] = p;
}
}
}
}
-
void Image::resize_to_po2(bool p_square) {
if (!_can_modify(format)) {
@@ -617,16 +600,16 @@ void Image::resize_to_po2(bool p_square) {
int w = nearest_power_of_2(width);
int h = nearest_power_of_2(height);
- if (w==width && h==height) {
+ if (w == width && h == height) {
- if (!p_square || w==h)
+ if (!p_square || w == h)
return; //nothing to do
}
- resize(w,h);
+ resize(w, h);
}
-Image Image::resized( int p_width, int p_height, int p_interpolation ) {
+Image Image::resized(int p_width, int p_height, int p_interpolation) {
Image ret = *this;
ret.resize(p_width, p_height, (Interpolation)p_interpolation);
@@ -634,124 +617,116 @@ Image Image::resized( int p_width, int p_height, int p_interpolation ) {
return ret;
};
-
-void Image::resize( int p_width, int p_height, Interpolation p_interpolation ) {
+void Image::resize(int p_width, int p_height, Interpolation p_interpolation) {
if (!_can_modify(format)) {
ERR_EXPLAIN("Cannot resize in indexed, compressed or custom image formats.");
ERR_FAIL();
}
- ERR_FAIL_COND(p_width<=0);
- ERR_FAIL_COND(p_height<=0);
- ERR_FAIL_COND(p_width>MAX_WIDTH);
- ERR_FAIL_COND(p_height>MAX_HEIGHT);
-
+ ERR_FAIL_COND(p_width <= 0);
+ ERR_FAIL_COND(p_height <= 0);
+ ERR_FAIL_COND(p_width > MAX_WIDTH);
+ ERR_FAIL_COND(p_height > MAX_HEIGHT);
- if (p_width==width && p_height==height)
+ if (p_width == width && p_height == height)
return;
- Image dst( p_width, p_height, 0, format );
+ Image dst(p_width, p_height, 0, format);
PoolVector<uint8_t>::Read r = data.read();
- const unsigned char*r_ptr=r.ptr();
+ const unsigned char *r_ptr = r.ptr();
PoolVector<uint8_t>::Write w = dst.data.write();
- unsigned char*w_ptr=w.ptr();
-
+ unsigned char *w_ptr = w.ptr();
- switch(p_interpolation) {
+ switch (p_interpolation) {
case INTERPOLATE_NEAREST: {
- switch(get_format_pixel_size(format)) {
- case 1: _scale_nearest<1>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 2: _scale_nearest<2>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 3: _scale_nearest<3>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 4: _scale_nearest<4>(r_ptr,w_ptr,width,height,p_width,p_height); break;
+ switch (get_format_pixel_size(format)) {
+ case 1: _scale_nearest<1>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 2: _scale_nearest<2>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 3: _scale_nearest<3>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 4: _scale_nearest<4>(r_ptr, w_ptr, width, height, p_width, p_height); break;
}
} break;
case INTERPOLATE_BILINEAR: {
- switch(get_format_pixel_size(format)) {
- case 1: _scale_bilinear<1>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 2: _scale_bilinear<2>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 3: _scale_bilinear<3>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 4: _scale_bilinear<4>(r_ptr,w_ptr,width,height,p_width,p_height); break;
+ switch (get_format_pixel_size(format)) {
+ case 1: _scale_bilinear<1>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 2: _scale_bilinear<2>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 3: _scale_bilinear<3>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 4: _scale_bilinear<4>(r_ptr, w_ptr, width, height, p_width, p_height); break;
}
} break;
case INTERPOLATE_CUBIC: {
- switch(get_format_pixel_size(format)) {
- case 1: _scale_cubic<1>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 2: _scale_cubic<2>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 3: _scale_cubic<3>(r_ptr,w_ptr,width,height,p_width,p_height); break;
- case 4: _scale_cubic<4>(r_ptr,w_ptr,width,height,p_width,p_height); break;
+ switch (get_format_pixel_size(format)) {
+ case 1: _scale_cubic<1>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 2: _scale_cubic<2>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 3: _scale_cubic<3>(r_ptr, w_ptr, width, height, p_width, p_height); break;
+ case 4: _scale_cubic<4>(r_ptr, w_ptr, width, height, p_width, p_height); break;
}
} break;
-
-
}
r = PoolVector<uint8_t>::Read();
w = PoolVector<uint8_t>::Write();
- if (mipmaps>0)
+ if (mipmaps > 0)
dst.generate_mipmaps();
- *this=dst;
+ *this = dst;
}
-void Image::crop( int p_width, int p_height ) {
+void Image::crop(int p_width, int p_height) {
if (!_can_modify(format)) {
ERR_EXPLAIN("Cannot crop in indexed, compressed or custom image formats.");
ERR_FAIL();
}
- ERR_FAIL_COND(p_width<=0);
- ERR_FAIL_COND(p_height<=0);
- ERR_FAIL_COND(p_width>MAX_WIDTH);
- ERR_FAIL_COND(p_height>MAX_HEIGHT);
+ ERR_FAIL_COND(p_width <= 0);
+ ERR_FAIL_COND(p_height <= 0);
+ ERR_FAIL_COND(p_width > MAX_WIDTH);
+ ERR_FAIL_COND(p_height > MAX_HEIGHT);
/* to save memory, cropping should be done in-place, however, since this function
will most likely either not be used much, or in critical areas, for now it wont, because
it's a waste of time. */
- if (p_width==width && p_height==height)
+ if (p_width == width && p_height == height)
return;
uint8_t pdata[16]; //largest is 16
uint32_t pixel_size = get_format_pixel_size(format);
- Image dst( p_width, p_height,0, format );
+ Image dst(p_width, p_height, 0, format);
{
PoolVector<uint8_t>::Read r = data.read();
PoolVector<uint8_t>::Write w = dst.data.write();
- for (int y=0;y<p_height;y++) {
+ for (int y = 0; y < p_height; y++) {
- for (int x=0;x<p_width;x++) {
+ for (int x = 0; x < p_width; x++) {
- if ((x>=width || y>=height)) {
- for(uint32_t i=0;i<pixel_size;i++)
- pdata[i]=0;
+ if ((x >= width || y >= height)) {
+ for (uint32_t i = 0; i < pixel_size; i++)
+ pdata[i] = 0;
} else {
- _get_pixelb(x,y,pixel_size,r.ptr(),pdata);
+ _get_pixelb(x, y, pixel_size, r.ptr(), pdata);
}
-
- dst._put_pixelb(x,y,pixel_size,w.ptr(),pdata);
+ dst._put_pixelb(x, y, pixel_size, w.ptr(), pdata);
}
}
}
-
- if (mipmaps>0)
+ if (mipmaps > 0)
dst.generate_mipmaps();
- *this=dst;
-
+ *this = dst;
}
void Image::flip_y() {
@@ -761,38 +736,32 @@ void Image::flip_y() {
ERR_FAIL();
}
- bool gm=mipmaps;
+ bool gm = mipmaps;
if (gm)
clear_mipmaps();
-
-
{
PoolVector<uint8_t>::Write w = data.write();
uint8_t up[16];
uint8_t down[16];
uint32_t pixel_size = get_format_pixel_size(format);
- for (int y=0;y<height;y++) {
-
- for (int x=0;x<width;x++) {
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
- _get_pixelb(x,y,pixel_size,w.ptr(),up);
- _get_pixelb(x,height-y-1,pixel_size,w.ptr(),down);
-
- _put_pixelb(x,height-y-1,pixel_size,w.ptr(),up);
- _put_pixelb(x,y,pixel_size,w.ptr(),down);
+ _get_pixelb(x, y, pixel_size, w.ptr(), up);
+ _get_pixelb(x, height - y - 1, pixel_size, w.ptr(), down);
+ _put_pixelb(x, height - y - 1, pixel_size, w.ptr(), up);
+ _put_pixelb(x, y, pixel_size, w.ptr(), down);
}
}
}
-
if (gm)
generate_mipmaps();
-
}
void Image::flip_x() {
@@ -802,161 +771,149 @@ void Image::flip_x() {
ERR_FAIL();
}
- bool gm=mipmaps;
+ bool gm = mipmaps;
if (gm)
clear_mipmaps();
-
{
PoolVector<uint8_t>::Write w = data.write();
uint8_t up[16];
uint8_t down[16];
uint32_t pixel_size = get_format_pixel_size(format);
- for (int y=0;y<height;y++) {
-
- for (int x=0;x<width;x++) {
-
+ for (int y = 0; y < height; y++) {
- _get_pixelb(x,y,pixel_size,w.ptr(),up);
- _get_pixelb(width-x-1,y,pixel_size,w.ptr(),down);
+ for (int x = 0; x < width; x++) {
- _put_pixelb(width-x-1,y,pixel_size,w.ptr(),up);
- _put_pixelb(x,y,pixel_size,w.ptr(),down);
+ _get_pixelb(x, y, pixel_size, w.ptr(), up);
+ _get_pixelb(width - x - 1, y, pixel_size, w.ptr(), down);
+ _put_pixelb(width - x - 1, y, pixel_size, w.ptr(), up);
+ _put_pixelb(x, y, pixel_size, w.ptr(), down);
}
}
}
if (gm)
generate_mipmaps();
-
}
-int Image::_get_dst_image_size(int p_width, int p_height, Format p_format,int &r_mipmaps,int p_mipmaps) {
+int Image::_get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps) {
- int size=0;
- int w=p_width;
- int h=p_height;
- int mm=0;
+ int size = 0;
+ int w = p_width;
+ int h = p_height;
+ int mm = 0;
- int pixsize=get_format_pixel_size(p_format);
- int pixshift=get_format_pixel_rshift(p_format);
- int minw,minh;
- get_format_min_pixel_size(p_format,minw,minh);
+ int pixsize = get_format_pixel_size(p_format);
+ int pixshift = get_format_pixel_rshift(p_format);
+ int minw, minh;
+ get_format_min_pixel_size(p_format, minw, minh);
- while(true) {
+ while (true) {
- int s = w*h;
- s*=pixsize;
- s>>=pixshift;
+ int s = w * h;
+ s *= pixsize;
+ s >>= pixshift;
- size+=s;
+ size += s;
- if (p_mipmaps>=0 && mm==p_mipmaps)
+ if (p_mipmaps >= 0 && mm == p_mipmaps)
break;
- if (p_mipmaps>=0) {
+ if (p_mipmaps >= 0) {
- w=MAX(minw,w>>1);
- h=MAX(minh,h>>1);
+ w = MAX(minw, w >> 1);
+ h = MAX(minh, h >> 1);
} else {
- if (w==minw && h==minh)
+ if (w == minw && h == minh)
break;
- w=MAX(minw,w>>1);
- h=MAX(minh,h>>1);
+ w = MAX(minw, w >> 1);
+ h = MAX(minh, h >> 1);
}
mm++;
};
- r_mipmaps=mm;
+ r_mipmaps = mm;
return size;
}
bool Image::_can_modify(Format p_format) const {
- return p_format<FORMAT_RGB565;
+ return p_format < FORMAT_RGB565;
}
-template<int CC>
-static void _generate_po2_mipmap(const uint8_t* p_src, uint8_t* p_dst, uint32_t p_width, uint32_t p_height) {
+template <int CC>
+static void _generate_po2_mipmap(const uint8_t *p_src, uint8_t *p_dst, uint32_t p_width, uint32_t p_height) {
//fast power of 2 mipmap generation
uint32_t dst_w = p_width >> 1;
uint32_t dst_h = p_height >> 1;
- for(uint32_t i=0;i<dst_h;i++) {
+ for (uint32_t i = 0; i < dst_h; i++) {
- const uint8_t *rup_ptr = &p_src[i*2*p_width*CC];
+ const uint8_t *rup_ptr = &p_src[i * 2 * p_width * CC];
const uint8_t *rdown_ptr = rup_ptr + p_width * CC;
- uint8_t *dst_ptr = &p_dst[i*dst_w*CC];
- uint32_t count=dst_w;
-
-
- while(count--) {
+ uint8_t *dst_ptr = &p_dst[i * dst_w * CC];
+ uint32_t count = dst_w;
- for(int j=0;j<CC;j++) {
+ while (count--) {
- uint16_t val=0;
- val+=rup_ptr[j];
- val+=rup_ptr[j+CC];
- val+=rdown_ptr[j];
- val+=rdown_ptr[j+CC];
- dst_ptr[j]=val>>2;
+ for (int j = 0; j < CC; j++) {
+ uint16_t val = 0;
+ val += rup_ptr[j];
+ val += rup_ptr[j + CC];
+ val += rdown_ptr[j];
+ val += rdown_ptr[j + CC];
+ dst_ptr[j] = val >> 2;
}
- dst_ptr+=CC;
- rup_ptr+=CC*2;
- rdown_ptr+=CC*2;
+ dst_ptr += CC;
+ rup_ptr += CC * 2;
+ rdown_ptr += CC * 2;
}
}
}
-
void Image::expand_x2_hq2x() {
ERR_FAIL_COND(!_can_modify(format));
Format current = format;
- bool mm=has_mipmaps();
+ bool mm = has_mipmaps();
if (mm) {
clear_mipmaps();
}
- if (current!=FORMAT_RGBA8)
+ if (current != FORMAT_RGBA8)
convert(FORMAT_RGBA8);
PoolVector<uint8_t> dest;
- dest.resize(width*2*height*2*4);
+ dest.resize(width * 2 * height * 2 * 4);
{
PoolVector<uint8_t>::Read r = data.read();
PoolVector<uint8_t>::Write w = dest.write();
- hq2x_resize((const uint32_t*)r.ptr(),width,height,(uint32_t*)w.ptr());
-
+ hq2x_resize((const uint32_t *)r.ptr(), width, height, (uint32_t *)w.ptr());
}
- width*=2;
- height*=2;
- data=dest;
-
+ width *= 2;
+ height *= 2;
+ data = dest;
- if (current!=FORMAT_RGBA8)
+ if (current != FORMAT_RGBA8)
convert(current);
if (mipmaps) {
generate_mipmaps();
}
-
}
void Image::shrink_x2() {
- ERR_FAIL_COND( data.size()==0 );
-
-
+ ERR_FAIL_COND(data.size() == 0);
if (mipmaps) {
@@ -965,136 +922,126 @@ void Image::shrink_x2() {
int ofs = get_mipmap_offset(1);
- int new_size = data.size()-ofs;
+ int new_size = data.size() - ofs;
new_img.resize(new_size);
-
{
- PoolVector<uint8_t>::Write w=new_img.write();
- PoolVector<uint8_t>::Read r=data.read();
+ PoolVector<uint8_t>::Write w = new_img.write();
+ PoolVector<uint8_t>::Read r = data.read();
- copymem(w.ptr(),&r[ofs],new_size);
+ copymem(w.ptr(), &r[ofs], new_size);
}
- width/=2;
- height/=2;
- data=new_img;
+ width /= 2;
+ height /= 2;
+ data = new_img;
} else {
PoolVector<uint8_t> new_img;
- ERR_FAIL_COND( !_can_modify(format) );
+ ERR_FAIL_COND(!_can_modify(format));
int ps = get_format_pixel_size(format);
- new_img.resize((width/2)*(height/2)*ps);
+ new_img.resize((width / 2) * (height / 2) * ps);
{
- PoolVector<uint8_t>::Write w=new_img.write();
- PoolVector<uint8_t>::Read r=data.read();
+ PoolVector<uint8_t>::Write w = new_img.write();
+ PoolVector<uint8_t>::Read r = data.read();
- switch(format) {
+ switch (format) {
case FORMAT_L8:
- case FORMAT_R8: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width,height); break;
- case FORMAT_LA8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width,height); break;
- case FORMAT_RG8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width,height); break;
- case FORMAT_RGB8: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width,height); break;
- case FORMAT_RGBA8: _generate_po2_mipmap<4>(r.ptr(), w.ptr(), width,height); break;
+ case FORMAT_R8: _generate_po2_mipmap<1>(r.ptr(), w.ptr(), width, height); break;
+ case FORMAT_LA8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width, height); break;
+ case FORMAT_RG8: _generate_po2_mipmap<2>(r.ptr(), w.ptr(), width, height); break;
+ case FORMAT_RGB8: _generate_po2_mipmap<3>(r.ptr(), w.ptr(), width, height); break;
+ case FORMAT_RGBA8: _generate_po2_mipmap<4>(r.ptr(), w.ptr(), width, height); break;
default: {}
}
}
- width/=2;
- height/=2;
- data=new_img;
-
+ width /= 2;
+ height /= 2;
+ data = new_img;
}
}
-Error Image::generate_mipmaps() {
+Error Image::generate_mipmaps() {
if (!_can_modify(format)) {
ERR_EXPLAIN("Cannot generate mipmaps in indexed, compressed or custom image formats.");
ERR_FAIL_V(ERR_UNAVAILABLE);
-
}
- ERR_FAIL_COND_V(width==0 || height==0,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(width == 0 || height == 0, ERR_UNCONFIGURED);
int mmcount;
- int size = _get_dst_image_size(width,height,format,mmcount);
+ int size = _get_dst_image_size(width, height, format, mmcount);
data.resize(size);
- print_line("to gen mipmaps w "+itos(width)+" h "+itos(height) +" format "+get_format_name(format)+" mipmaps " +itos(mmcount)+" new size is: "+itos(size));
+ print_line("to gen mipmaps w " + itos(width) + " h " + itos(height) + " format " + get_format_name(format) + " mipmaps " + itos(mmcount) + " new size is: " + itos(size));
- PoolVector<uint8_t>::Write wp=data.write();
+ PoolVector<uint8_t>::Write wp = data.write();
- if (nearest_power_of_2(width)==uint32_t(width) && nearest_power_of_2(height)==uint32_t(height)) {
+ if (nearest_power_of_2(width) == uint32_t(width) && nearest_power_of_2(height) == uint32_t(height)) {
//use fast code for powers of 2
- int prev_ofs=0;
- int prev_h=height;
- int prev_w=width;
-
- for(int i=1;i<mmcount;i++) {
+ int prev_ofs = 0;
+ int prev_h = height;
+ int prev_w = width;
+ for (int i = 1; i < mmcount; i++) {
- int ofs,w,h;
- _get_mipmap_offset_and_size(i,ofs, w,h);
+ int ofs, w, h;
+ _get_mipmap_offset_and_size(i, ofs, w, h);
-
- switch(format) {
+ switch (format) {
case FORMAT_L8:
- case FORMAT_R8: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break;
+ case FORMAT_R8: _generate_po2_mipmap<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break;
case FORMAT_LA8:
- case FORMAT_RG8: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break;
- case FORMAT_RGB8: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break;
- case FORMAT_RGBA8: _generate_po2_mipmap<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h); break;
+ case FORMAT_RG8: _generate_po2_mipmap<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break;
+ case FORMAT_RGB8: _generate_po2_mipmap<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break;
+ case FORMAT_RGBA8: _generate_po2_mipmap<4>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h); break;
default: {}
}
- prev_ofs=ofs;
- prev_w=w;
- prev_h=h;
+ prev_ofs = ofs;
+ prev_w = w;
+ prev_h = h;
}
-
} else {
//use slow code..
//use bilinear filtered code for non powers of 2
- int prev_ofs=0;
- int prev_h=height;
- int prev_w=width;
-
- for(int i=1;i<mmcount;i++) {
+ int prev_ofs = 0;
+ int prev_h = height;
+ int prev_w = width;
+ for (int i = 1; i < mmcount; i++) {
- int ofs,w,h;
- _get_mipmap_offset_and_size(i,ofs, w,h);
+ int ofs, w, h;
+ _get_mipmap_offset_and_size(i, ofs, w, h);
- switch(format) {
+ switch (format) {
case FORMAT_L8:
- case FORMAT_R8: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break;
+ case FORMAT_R8: _scale_bilinear<1>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break;
case FORMAT_LA8:
- case FORMAT_RG8: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break;
- case FORMAT_RGB8:_scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break;
- case FORMAT_RGBA8: _scale_bilinear<4>(&wp[prev_ofs], &wp[ofs], prev_w,prev_h,w,h); break;
+ case FORMAT_RG8: _scale_bilinear<2>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break;
+ case FORMAT_RGB8: _scale_bilinear<3>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break;
+ case FORMAT_RGBA8: _scale_bilinear<4>(&wp[prev_ofs], &wp[ofs], prev_w, prev_h, w, h); break;
default: {}
}
- prev_ofs=ofs;
- prev_w=w;
- prev_h=h;
+ prev_ofs = ofs;
+ prev_w = w;
+ prev_h = h;
}
-
-
-
}
- mipmaps=true;
+ mipmaps = true;
return OK;
}
@@ -1107,18 +1054,16 @@ void Image::clear_mipmaps() {
if (empty())
return;
- int ofs,w,h;
- _get_mipmap_offset_and_size(1,ofs,w,h);
+ int ofs, w, h;
+ _get_mipmap_offset_and_size(1, ofs, w, h);
data.resize(ofs);
- mipmaps=false;
-
+ mipmaps = false;
}
-
bool Image::empty() const {
- return (data.size()==0);
+ return (data.size() == 0);
}
PoolVector<uint8_t> Image::get_data() const {
@@ -1126,53 +1071,48 @@ PoolVector<uint8_t> Image::get_data() const {
return data;
}
-void Image::create(int p_width, int p_height, bool p_use_mipmaps,Format p_format) {
-
+void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
- int mm=0;
- int size = _get_dst_image_size(p_width,p_height,p_format,mm,p_use_mipmaps?-1:0);
- data.resize( size );
+ int mm = 0;
+ int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
+ data.resize(size);
{
- PoolVector<uint8_t>::Write w= data.write();
- zeromem(w.ptr(),size);
+ PoolVector<uint8_t>::Write w = data.write();
+ zeromem(w.ptr(), size);
}
- width=p_width;
- height=p_height;
- mipmaps=p_use_mipmaps;
- format=p_format;
-
-
+ width = p_width;
+ height = p_height;
+ mipmaps = p_use_mipmaps;
+ format = p_format;
}
-void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data) {
+void Image::create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data) {
- ERR_FAIL_INDEX(p_width-1,MAX_WIDTH);
- ERR_FAIL_INDEX(p_height-1,MAX_HEIGHT);
+ ERR_FAIL_INDEX(p_width - 1, MAX_WIDTH);
+ ERR_FAIL_INDEX(p_height - 1, MAX_HEIGHT);
int mm;
- int size = _get_dst_image_size(p_width,p_height,p_format,mm,p_use_mipmaps?-1:0);
+ int size = _get_dst_image_size(p_width, p_height, p_format, mm, p_use_mipmaps ? -1 : 0);
- if (size!=p_data.size()) {
- ERR_EXPLAIN("Expected data size of "+itos(size)+" in Image::create()");
- ERR_FAIL_COND(p_data.size()!=size);
+ if (size != p_data.size()) {
+ ERR_EXPLAIN("Expected data size of " + itos(size) + " in Image::create()");
+ ERR_FAIL_COND(p_data.size() != size);
}
- height=p_height;
- width=p_width;
- format=p_format;
- data=p_data;
- mipmaps=p_use_mipmaps;
+ height = p_height;
+ width = p_width;
+ format = p_format;
+ data = p_data;
+ mipmaps = p_use_mipmaps;
}
+void Image::create(const char **p_xpm) {
-void Image::create( const char ** p_xpm ) {
-
-
- int size_width,size_height;
- int pixelchars=0;
- mipmaps=false;
- bool has_alpha=false;
+ int size_width, size_height;
+ int pixelchars = 0;
+ mipmaps = false;
+ bool has_alpha = false;
enum Status {
READING_HEADER,
@@ -1182,132 +1122,128 @@ void Image::create( const char ** p_xpm ) {
};
Status status = READING_HEADER;
- int line=0;
+ int line = 0;
- HashMap<String,Color> colormap;
+ HashMap<String, Color> colormap;
int colormap_size;
uint32_t pixel_size;
PoolVector<uint8_t>::Write w;
- while (status!=DONE) {
-
- const char * line_ptr = p_xpm[line];
+ while (status != DONE) {
+ const char *line_ptr = p_xpm[line];
switch (status) {
- case READING_HEADER: {
+ case READING_HEADER: {
- String line_str=line_ptr;
- line_str.replace("\t"," ");
+ String line_str = line_ptr;
+ line_str.replace("\t", " ");
- size_width=line_str.get_slicec(' ',0).to_int();
- size_height=line_str.get_slicec(' ',1).to_int();
- colormap_size=line_str.get_slicec(' ',2).to_int();
- pixelchars=line_str.get_slicec(' ',3).to_int();
- ERR_FAIL_COND(colormap_size > 32766);
- ERR_FAIL_COND(pixelchars > 5);
- ERR_FAIL_COND(size_width > 32767);
- ERR_FAIL_COND(size_height > 32767);
- status=READING_COLORS;
- } break;
- case READING_COLORS: {
+ size_width = line_str.get_slicec(' ', 0).to_int();
+ size_height = line_str.get_slicec(' ', 1).to_int();
+ colormap_size = line_str.get_slicec(' ', 2).to_int();
+ pixelchars = line_str.get_slicec(' ', 3).to_int();
+ ERR_FAIL_COND(colormap_size > 32766);
+ ERR_FAIL_COND(pixelchars > 5);
+ ERR_FAIL_COND(size_width > 32767);
+ ERR_FAIL_COND(size_height > 32767);
+ status = READING_COLORS;
+ } break;
+ case READING_COLORS: {
- String colorstring;
- for (int i=0;i<pixelchars;i++) {
+ String colorstring;
+ for (int i = 0; i < pixelchars; i++) {
- colorstring+=*line_ptr;
- line_ptr++;
- }
+ colorstring += *line_ptr;
+ line_ptr++;
+ }
//skip spaces
- while (*line_ptr==' ' || *line_ptr=='\t' || *line_ptr==0) {
- if (*line_ptr==0)
- break;
- line_ptr++;
- }
- if (*line_ptr=='c') {
-
- line_ptr++;
- while (*line_ptr==' ' || *line_ptr=='\t' || *line_ptr==0) {
- if (*line_ptr==0)
+ while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
+ if (*line_ptr == 0)
break;
line_ptr++;
}
+ if (*line_ptr == 'c') {
- if (*line_ptr=='#') {
line_ptr++;
- uint8_t col_r;
- uint8_t col_g;
- uint8_t col_b;
- //uint8_t col_a=255;
-
- for (int i=0;i<6;i++) {
-
- char v = line_ptr[i];
-
- if (v>='0' && v<='9')
- v-='0';
- else if (v>='A' && v<='F')
- v=(v-'A')+10;
- else if (v>='a' && v<='f')
- v=(v-'a')+10;
- else
+ while (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == 0) {
+ if (*line_ptr == 0)
break;
-
- switch(i) {
- case 0: col_r=v<<4; break;
- case 1: col_r|=v; break;
- case 2: col_g=v<<4; break;
- case 3: col_g|=v; break;
- case 4: col_b=v<<4; break;
- case 5: col_b|=v; break;
- };
-
+ line_ptr++;
}
- // magenta mask
- if (col_r==255 && col_g==0 && col_b==255) {
-
- colormap[colorstring]=Color(0,0,0,0);
- has_alpha=true;
- } else {
-
- colormap[colorstring]=Color(col_r/255.0,col_g/255.0,col_b/255.0,1.0);
+ if (*line_ptr == '#') {
+ line_ptr++;
+ uint8_t col_r;
+ uint8_t col_g;
+ uint8_t col_b;
+ //uint8_t col_a=255;
+
+ for (int i = 0; i < 6; i++) {
+
+ char v = line_ptr[i];
+
+ if (v >= '0' && v <= '9')
+ v -= '0';
+ else if (v >= 'A' && v <= 'F')
+ v = (v - 'A') + 10;
+ else if (v >= 'a' && v <= 'f')
+ v = (v - 'a') + 10;
+ else
+ break;
+
+ switch (i) {
+ case 0: col_r = v << 4; break;
+ case 1: col_r |= v; break;
+ case 2: col_g = v << 4; break;
+ case 3: col_g |= v; break;
+ case 4: col_b = v << 4; break;
+ case 5: col_b |= v; break;
+ };
+ }
+
+ // magenta mask
+ if (col_r == 255 && col_g == 0 && col_b == 255) {
+
+ colormap[colorstring] = Color(0, 0, 0, 0);
+ has_alpha = true;
+ } else {
+
+ colormap[colorstring] = Color(col_r / 255.0, col_g / 255.0, col_b / 255.0, 1.0);
+ }
}
-
}
- }
- if (line==colormap_size) {
+ if (line == colormap_size) {
- status=READING_PIXELS;
- create(size_width,size_height,0,has_alpha?FORMAT_RGBA8:FORMAT_RGB8);
- w=data.write();
- pixel_size=has_alpha?4:3;
- }
- } break;
- case READING_PIXELS: {
+ status = READING_PIXELS;
+ create(size_width, size_height, 0, has_alpha ? FORMAT_RGBA8 : FORMAT_RGB8);
+ w = data.write();
+ pixel_size = has_alpha ? 4 : 3;
+ }
+ } break;
+ case READING_PIXELS: {
- int y=line-colormap_size-1;
- for (int x=0;x<size_width;x++) {
+ int y = line - colormap_size - 1;
+ for (int x = 0; x < size_width; x++) {
- char pixelstr[6]={0,0,0,0,0,0};
- for (int i=0;i<pixelchars;i++)
- pixelstr[i]=line_ptr[x*pixelchars+i];
+ char pixelstr[6] = { 0, 0, 0, 0, 0, 0 };
+ for (int i = 0; i < pixelchars; i++)
+ pixelstr[i] = line_ptr[x * pixelchars + i];
- Color *colorptr = colormap.getptr(pixelstr);
- ERR_FAIL_COND(!colorptr);
- uint8_t pixel[4];
- for(uint32_t i=0;i<pixel_size;i++) {
- pixel[i]=CLAMP((*colorptr)[i]*255,0,255);
+ Color *colorptr = colormap.getptr(pixelstr);
+ ERR_FAIL_COND(!colorptr);
+ uint8_t pixel[4];
+ for (uint32_t i = 0; i < pixel_size; i++) {
+ pixel[i] = CLAMP((*colorptr)[i] * 255, 0, 255);
+ }
+ _put_pixelb(x, y, pixel_size, w.ptr(), pixel);
}
- _put_pixelb(x,y,pixel_size,w.ptr(),pixel);
- }
-
- if (y==(size_height-1))
- status=DONE;
- } break;
- default:{}
+ if (y == (size_height - 1))
+ status = DONE;
+ } break;
+ default: {}
}
line++;
@@ -1316,63 +1252,60 @@ void Image::create( const char ** p_xpm ) {
#define DETECT_ALPHA_MAX_TRESHOLD 254
#define DETECT_ALPHA_MIN_TRESHOLD 2
-#define DETECT_ALPHA( m_value )\
-{ \
- uint8_t value=m_value;\
- if (value<DETECT_ALPHA_MIN_TRESHOLD)\
- bit=true;\
- else if (value<DETECT_ALPHA_MAX_TRESHOLD) {\
- \
- detected=true;\
- break;\
- }\
-}
-
-#define DETECT_NON_ALPHA( m_value )\
-{ \
- uint8_t value=m_value;\
- if (value>0) {\
- \
- detected=true;\
- break;\
- }\
-}
+#define DETECT_ALPHA(m_value) \
+ { \
+ uint8_t value = m_value; \
+ if (value < DETECT_ALPHA_MIN_TRESHOLD) \
+ bit = true; \
+ else if (value < DETECT_ALPHA_MAX_TRESHOLD) { \
+ \
+ detected = true; \
+ break; \
+ } \
+ }
+#define DETECT_NON_ALPHA(m_value) \
+ { \
+ uint8_t value = m_value; \
+ if (value > 0) { \
+ \
+ detected = true; \
+ break; \
+ } \
+ }
bool Image::is_invisible() const {
- if (format==FORMAT_L8 ||
- format==FORMAT_RGB8 || format==FORMAT_RG8)
+ if (format == FORMAT_L8 ||
+ format == FORMAT_RGB8 || format == FORMAT_RG8)
return false;
int len = data.size();
- if (len==0)
+ if (len == 0)
return true;
-
- int w,h;
- _get_mipmap_offset_and_size(1,len,w,h);
+ int w, h;
+ _get_mipmap_offset_and_size(1, len, w, h);
PoolVector<uint8_t>::Read r = data.read();
- const unsigned char *data_ptr=r.ptr();
+ const unsigned char *data_ptr = r.ptr();
- bool detected=false;
+ bool detected = false;
- switch(format) {
+ switch (format) {
case FORMAT_LA8: {
-
- for(int i=0;i<(len>>1);i++) {
- DETECT_NON_ALPHA(data_ptr[(i<<1)+1]);
+ for (int i = 0; i < (len >> 1); i++) {
+ DETECT_NON_ALPHA(data_ptr[(i << 1) + 1]);
}
} break;
case FORMAT_RGBA8: {
- for(int i=0;i<(len>>2);i++) {
- DETECT_NON_ALPHA(data_ptr[(i<<2)+3])
+ for (int i = 0; i < (len >> 2); i++) {
+ DETECT_NON_ALPHA(data_ptr[(i << 2) + 3])
}
} break;
@@ -1381,7 +1314,7 @@ bool Image::is_invisible() const {
case FORMAT_PVRTC4A:
case FORMAT_DXT3:
case FORMAT_DXT5: {
- detected=true;
+ detected = true;
} break;
default: {}
}
@@ -1391,43 +1324,41 @@ bool Image::is_invisible() const {
Image::AlphaMode Image::detect_alpha() const {
-
int len = data.size();
- if (len==0)
+ if (len == 0)
return ALPHA_NONE;
- int w,h;
- _get_mipmap_offset_and_size(1,len,w,h);
+ int w, h;
+ _get_mipmap_offset_and_size(1, len, w, h);
PoolVector<uint8_t>::Read r = data.read();
- const unsigned char *data_ptr=r.ptr();
+ const unsigned char *data_ptr = r.ptr();
- bool bit=false;
- bool detected=false;
+ bool bit = false;
+ bool detected = false;
- switch(format) {
+ switch (format) {
case FORMAT_LA8: {
-
- for(int i=0;i<(len>>1);i++) {
- DETECT_ALPHA(data_ptr[(i<<1)+1]);
+ for (int i = 0; i < (len >> 1); i++) {
+ DETECT_ALPHA(data_ptr[(i << 1) + 1]);
}
} break;
case FORMAT_RGBA8: {
- for(int i=0;i<(len>>2);i++) {
- DETECT_ALPHA(data_ptr[(i<<2)+3])
+ for (int i = 0; i < (len >> 2); i++) {
+ DETECT_ALPHA(data_ptr[(i << 2) + 3])
}
- } break;
+ } break;
case FORMAT_PVRTC2A:
case FORMAT_PVRTC4A:
case FORMAT_DXT3:
case FORMAT_DXT5: {
- detected=true;
+ detected = true;
} break;
default: {}
}
@@ -1438,15 +1369,14 @@ Image::AlphaMode Image::detect_alpha() const {
return ALPHA_BIT;
else
return ALPHA_NONE;
-
}
-Error Image::load(const String& p_path) {
+Error Image::load(const String &p_path) {
return ImageLoader::load_image(p_path, this);
}
-Error Image::save_png(const String& p_path) {
+Error Image::save_png(const String &p_path) {
if (save_png_func == NULL)
return ERR_UNAVAILABLE;
@@ -1454,7 +1384,7 @@ Error Image::save_png(const String& p_path) {
return save_png_func(p_path, *this);
}
-bool Image::operator==(const Image& p_image) const {
+bool Image::operator==(const Image &p_image) const {
if (data.size() == 0 && p_image.data.size() == 0)
return true;
@@ -1464,42 +1394,31 @@ bool Image::operator==(const Image& p_image) const {
return r.ptr() == pr.ptr();
}
-
-
-
-int Image::get_image_data_size(int p_width, int p_height, Format p_format,int p_mipmaps) {
+int Image::get_image_data_size(int p_width, int p_height, Format p_format, int p_mipmaps) {
int mm;
- return _get_dst_image_size(p_width,p_height,p_format,mm,p_mipmaps);
-
+ return _get_dst_image_size(p_width, p_height, p_format, mm, p_mipmaps);
}
int Image::get_image_required_mipmaps(int p_width, int p_height, Format p_format) {
int mm;
- _get_dst_image_size(p_width,p_height,p_format,mm,-1);
+ _get_dst_image_size(p_width, p_height, p_format, mm, -1);
return mm;
-
}
-
-
-
-
Error Image::_decompress_bc() {
-
- int wd=width,ht=height;
- if (wd%4!=0) {
- wd+=4-(wd%4);
+ int wd = width, ht = height;
+ if (wd % 4 != 0) {
+ wd += 4 - (wd % 4);
}
- if (ht%4!=0) {
- ht+=4-(ht%4);
+ if (ht % 4 != 0) {
+ ht += 4 - (ht % 4);
}
-
int mm;
- int size = _get_dst_image_size(wd,ht,FORMAT_RGBA8,mm);
+ int size = _get_dst_image_size(wd, ht, FORMAT_RGBA8, mm);
PoolVector<uint8_t> newdata;
newdata.resize(size);
@@ -1507,358 +1426,339 @@ Error Image::_decompress_bc() {
PoolVector<uint8_t>::Write w = newdata.write();
PoolVector<uint8_t>::Read r = data.read();
- int rofs=0;
- int wofs=0;
+ int rofs = 0;
+ int wofs = 0;
//print_line("width: "+itos(wd)+" height: "+itos(ht));
- for(int i=0;i<=mm;i++) {
+ for (int i = 0; i <= mm; i++) {
- switch(format) {
+ switch (format) {
case FORMAT_DXT1: {
- int len = (wd*ht)/16;
- uint8_t* dst=&w[wofs];
+ int len = (wd * ht) / 16;
+ uint8_t *dst = &w[wofs];
uint32_t ofs_table[16];
- for(int x=0;x<4;x++) {
+ for (int x = 0; x < 4; x++) {
- for(int y=0;y<4;y++) {
+ for (int y = 0; y < 4; y++) {
- ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4;
+ ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4;
}
}
-
- for(int j=0;j<len;j++) {
-
- const uint8_t* src=&r[rofs+j*8];
- uint16_t col_a=src[1];
- col_a<<=8;
- col_a|=src[0];
- uint16_t col_b=src[3];
- col_b<<=8;
- col_b|=src[2];
-
- uint8_t table[4][4]={
- { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 },
- { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 },
- {0,0,0,255},
- {0,0,0,255}
+ for (int j = 0; j < len; j++) {
+
+ const uint8_t *src = &r[rofs + j * 8];
+ uint16_t col_a = src[1];
+ col_a <<= 8;
+ col_a |= src[0];
+ uint16_t col_b = src[3];
+ col_b <<= 8;
+ col_b |= src[2];
+
+ uint8_t table[4][4] = {
+ { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 },
+ { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((col_b)&0x1f) << 3), 255 },
+ { 0, 0, 0, 255 },
+ { 0, 0, 0, 255 }
};
- if (col_a<col_b) {
+ if (col_a < col_b) {
//punchrough
- table[2][0]=(int(table[0][0])+int(table[1][0]))>>1;
- table[2][1]=(int(table[0][1])+int(table[1][1]))>>1;
- table[2][2]=(int(table[0][2])+int(table[1][2]))>>1;
- table[3][3]=0; //premul alpha black
+ table[2][0] = (int(table[0][0]) + int(table[1][0])) >> 1;
+ table[2][1] = (int(table[0][1]) + int(table[1][1])) >> 1;
+ table[2][2] = (int(table[0][2]) + int(table[1][2])) >> 1;
+ table[3][3] = 0; //premul alpha black
} else {
//gradient
- table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3;
- table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3;
- table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3;
- table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3;
- table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3;
- table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3;
+ table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3;
+ table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3;
+ table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3;
+ table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3;
+ table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3;
+ table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3;
}
- uint32_t block=src[4];
- block<<=8;
- block|=src[5];
- block<<=8;
- block|=src[6];
- block<<=8;
- block|=src[7];
-
- int y = (j/(wd/4))*4;
- int x = (j%(wd/4))*4;
- int pixofs = (y*wd+x)*4;
-
- for(int k=0;k<16;k++) {
- int idx = pixofs+ofs_table[k];
- dst[idx+0]=table[block&0x3][0];
- dst[idx+1]=table[block&0x3][1];
- dst[idx+2]=table[block&0x3][2];
- dst[idx+3]=table[block&0x3][3];
- block>>=2;
+ uint32_t block = src[4];
+ block <<= 8;
+ block |= src[5];
+ block <<= 8;
+ block |= src[6];
+ block <<= 8;
+ block |= src[7];
+
+ int y = (j / (wd / 4)) * 4;
+ int x = (j % (wd / 4)) * 4;
+ int pixofs = (y * wd + x) * 4;
+
+ for (int k = 0; k < 16; k++) {
+ int idx = pixofs + ofs_table[k];
+ dst[idx + 0] = table[block & 0x3][0];
+ dst[idx + 1] = table[block & 0x3][1];
+ dst[idx + 2] = table[block & 0x3][2];
+ dst[idx + 3] = table[block & 0x3][3];
+ block >>= 2;
}
-
}
- rofs+=len*8;
- wofs+=wd*ht*4;
+ rofs += len * 8;
+ wofs += wd * ht * 4;
-
- wd/=2;
- ht/=2;
+ wd /= 2;
+ ht /= 2;
} break;
case FORMAT_DXT3: {
- int len = (wd*ht)/16;
- uint8_t* dst=&w[wofs];
+ int len = (wd * ht) / 16;
+ uint8_t *dst = &w[wofs];
uint32_t ofs_table[16];
- for(int x=0;x<4;x++) {
+ for (int x = 0; x < 4; x++) {
- for(int y=0;y<4;y++) {
+ for (int y = 0; y < 4; y++) {
- ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4;
+ ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4;
}
}
-
- for(int j=0;j<len;j++) {
-
- const uint8_t* src=&r[rofs+j*16];
-
- uint64_t ablock=src[1];
- ablock<<=8;
- ablock|=src[0];
- ablock<<=8;
- ablock|=src[3];
- ablock<<=8;
- ablock|=src[2];
- ablock<<=8;
- ablock|=src[5];
- ablock<<=8;
- ablock|=src[4];
- ablock<<=8;
- ablock|=src[7];
- ablock<<=8;
- ablock|=src[6];
-
-
- uint16_t col_a=src[8+1];
- col_a<<=8;
- col_a|=src[8+0];
- uint16_t col_b=src[8+3];
- col_b<<=8;
- col_b|=src[8+2];
-
- uint8_t table[4][4]={
- { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 },
- { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 },
-
- {0,0,0,255},
- {0,0,0,255}
+ for (int j = 0; j < len; j++) {
+
+ const uint8_t *src = &r[rofs + j * 16];
+
+ uint64_t ablock = src[1];
+ ablock <<= 8;
+ ablock |= src[0];
+ ablock <<= 8;
+ ablock |= src[3];
+ ablock <<= 8;
+ ablock |= src[2];
+ ablock <<= 8;
+ ablock |= src[5];
+ ablock <<= 8;
+ ablock |= src[4];
+ ablock <<= 8;
+ ablock |= src[7];
+ ablock <<= 8;
+ ablock |= src[6];
+
+ uint16_t col_a = src[8 + 1];
+ col_a <<= 8;
+ col_a |= src[8 + 0];
+ uint16_t col_b = src[8 + 3];
+ col_b <<= 8;
+ col_b |= src[8 + 2];
+
+ uint8_t table[4][4] = {
+ { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 },
+ { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((col_b)&0x1f) << 3), 255 },
+
+ { 0, 0, 0, 255 },
+ { 0, 0, 0, 255 }
};
//always gradient
- table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3;
- table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3;
- table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3;
- table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3;
- table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3;
- table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3;
-
- uint32_t block=src[4+8];
- block<<=8;
- block|=src[5+8];
- block<<=8;
- block|=src[6+8];
- block<<=8;
- block|=src[7+8];
-
- int y = (j/(wd/4))*4;
- int x = (j%(wd/4))*4;
- int pixofs = (y*wd+x)*4;
-
- for(int k=0;k<16;k++) {
- uint8_t alpha = ablock&0xf;
- alpha=int(alpha)*255/15; //right way for alpha
- int idx = pixofs+ofs_table[k];
- dst[idx+0]=table[block&0x3][0];
- dst[idx+1]=table[block&0x3][1];
- dst[idx+2]=table[block&0x3][2];
- dst[idx+3]=alpha;
- block>>=2;
- ablock>>=4;
+ table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3;
+ table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3;
+ table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3;
+ table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3;
+ table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3;
+ table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3;
+
+ uint32_t block = src[4 + 8];
+ block <<= 8;
+ block |= src[5 + 8];
+ block <<= 8;
+ block |= src[6 + 8];
+ block <<= 8;
+ block |= src[7 + 8];
+
+ int y = (j / (wd / 4)) * 4;
+ int x = (j % (wd / 4)) * 4;
+ int pixofs = (y * wd + x) * 4;
+
+ for (int k = 0; k < 16; k++) {
+ uint8_t alpha = ablock & 0xf;
+ alpha = int(alpha) * 255 / 15; //right way for alpha
+ int idx = pixofs + ofs_table[k];
+ dst[idx + 0] = table[block & 0x3][0];
+ dst[idx + 1] = table[block & 0x3][1];
+ dst[idx + 2] = table[block & 0x3][2];
+ dst[idx + 3] = alpha;
+ block >>= 2;
+ ablock >>= 4;
}
-
}
- rofs+=len*16;
- wofs+=wd*ht*4;
+ rofs += len * 16;
+ wofs += wd * ht * 4;
-
- wd/=2;
- ht/=2;
+ wd /= 2;
+ ht /= 2;
} break;
case FORMAT_DXT5: {
- int len = (wd*ht)/16;
- uint8_t* dst=&w[wofs];
+ int len = (wd * ht) / 16;
+ uint8_t *dst = &w[wofs];
uint32_t ofs_table[16];
- for(int x=0;x<4;x++) {
+ for (int x = 0; x < 4; x++) {
- for(int y=0;y<4;y++) {
+ for (int y = 0; y < 4; y++) {
- ofs_table[15-(y*4+(3-x))]=(x+y*wd)*4;
+ ofs_table[15 - (y * 4 + (3 - x))] = (x + y * wd) * 4;
}
}
+ for (int j = 0; j < len; j++) {
+ const uint8_t *src = &r[rofs + j * 16];
- for(int j=0;j<len;j++) {
-
- const uint8_t* src=&r[rofs+j*16];
-
- uint8_t a_start=src[1];
- uint8_t a_end=src[0];
+ uint8_t a_start = src[1];
+ uint8_t a_end = src[0];
- uint64_t ablock=src[3];
- ablock<<=8;
- ablock|=src[2];
- ablock<<=8;
- ablock|=src[5];
- ablock<<=8;
- ablock|=src[4];
- ablock<<=8;
- ablock|=src[7];
- ablock<<=8;
- ablock|=src[6];
+ uint64_t ablock = src[3];
+ ablock <<= 8;
+ ablock |= src[2];
+ ablock <<= 8;
+ ablock |= src[5];
+ ablock <<= 8;
+ ablock |= src[4];
+ ablock <<= 8;
+ ablock |= src[7];
+ ablock <<= 8;
+ ablock |= src[6];
uint8_t atable[8];
- if (a_start>a_end) {
+ if (a_start > a_end) {
- atable[0]=(int(a_start)*7+int(a_end)*0)/7;
- atable[1]=(int(a_start)*6+int(a_end)*1)/7;
- atable[2]=(int(a_start)*5+int(a_end)*2)/7;
- atable[3]=(int(a_start)*4+int(a_end)*3)/7;
- atable[4]=(int(a_start)*3+int(a_end)*4)/7;
- atable[5]=(int(a_start)*2+int(a_end)*5)/7;
- atable[6]=(int(a_start)*1+int(a_end)*6)/7;
- atable[7]=(int(a_start)*0+int(a_end)*7)/7;
+ atable[0] = (int(a_start) * 7 + int(a_end) * 0) / 7;
+ atable[1] = (int(a_start) * 6 + int(a_end) * 1) / 7;
+ atable[2] = (int(a_start) * 5 + int(a_end) * 2) / 7;
+ atable[3] = (int(a_start) * 4 + int(a_end) * 3) / 7;
+ atable[4] = (int(a_start) * 3 + int(a_end) * 4) / 7;
+ atable[5] = (int(a_start) * 2 + int(a_end) * 5) / 7;
+ atable[6] = (int(a_start) * 1 + int(a_end) * 6) / 7;
+ atable[7] = (int(a_start) * 0 + int(a_end) * 7) / 7;
} else {
- atable[0]=(int(a_start)*5+int(a_end)*0)/5;
- atable[1]=(int(a_start)*4+int(a_end)*1)/5;
- atable[2]=(int(a_start)*3+int(a_end)*2)/5;
- atable[3]=(int(a_start)*2+int(a_end)*3)/5;
- atable[4]=(int(a_start)*1+int(a_end)*4)/5;
- atable[5]=(int(a_start)*0+int(a_end)*5)/5;
- atable[6]=0;
- atable[7]=255;
-
+ atable[0] = (int(a_start) * 5 + int(a_end) * 0) / 5;
+ atable[1] = (int(a_start) * 4 + int(a_end) * 1) / 5;
+ atable[2] = (int(a_start) * 3 + int(a_end) * 2) / 5;
+ atable[3] = (int(a_start) * 2 + int(a_end) * 3) / 5;
+ atable[4] = (int(a_start) * 1 + int(a_end) * 4) / 5;
+ atable[5] = (int(a_start) * 0 + int(a_end) * 5) / 5;
+ atable[6] = 0;
+ atable[7] = 255;
}
+ uint16_t col_a = src[8 + 1];
+ col_a <<= 8;
+ col_a |= src[8 + 0];
+ uint16_t col_b = src[8 + 3];
+ col_b <<= 8;
+ col_b |= src[8 + 2];
- uint16_t col_a=src[8+1];
- col_a<<=8;
- col_a|=src[8+0];
- uint16_t col_b=src[8+3];
- col_b<<=8;
- col_b|=src[8+2];
-
- uint8_t table[4][4]={
- { uint8_t((col_a>>11)<<3), uint8_t(((col_a>>5)&0x3f)<<2),uint8_t(((col_a)&0x1f)<<3), 255 },
- { uint8_t((col_b>>11)<<3), uint8_t(((col_b>>5)&0x3f)<<2),uint8_t(((col_b)&0x1f)<<3), 255 },
+ uint8_t table[4][4] = {
+ { uint8_t((col_a >> 11) << 3), uint8_t(((col_a >> 5) & 0x3f) << 2), uint8_t(((col_a)&0x1f) << 3), 255 },
+ { uint8_t((col_b >> 11) << 3), uint8_t(((col_b >> 5) & 0x3f) << 2), uint8_t(((col_b)&0x1f) << 3), 255 },
- {0,0,0,255},
- {0,0,0,255}
+ { 0, 0, 0, 255 },
+ { 0, 0, 0, 255 }
};
//always gradient
- table[2][0]=(int(table[0][0])*2+int(table[1][0]))/3;
- table[2][1]=(int(table[0][1])*2+int(table[1][1]))/3;
- table[2][2]=(int(table[0][2])*2+int(table[1][2]))/3;
- table[3][0]=(int(table[0][0])+int(table[1][0])*2)/3;
- table[3][1]=(int(table[0][1])+int(table[1][1])*2)/3;
- table[3][2]=(int(table[0][2])+int(table[1][2])*2)/3;
-
-
- uint32_t block=src[4+8];
- block<<=8;
- block|=src[5+8];
- block<<=8;
- block|=src[6+8];
- block<<=8;
- block|=src[7+8];
-
- int y = (j/(wd/4))*4;
- int x = (j%(wd/4))*4;
- int pixofs = (y*wd+x)*4;
-
-
-
- for(int k=0;k<16;k++) {
- uint8_t alpha = ablock&0x7;
- int idx = pixofs+ofs_table[k];
- dst[idx+0]=table[block&0x3][0];
- dst[idx+1]=table[block&0x3][1];
- dst[idx+2]=table[block&0x3][2];
- dst[idx+3]=atable[alpha];
- block>>=2;
- ablock>>=3;
+ table[2][0] = (int(table[0][0]) * 2 + int(table[1][0])) / 3;
+ table[2][1] = (int(table[0][1]) * 2 + int(table[1][1])) / 3;
+ table[2][2] = (int(table[0][2]) * 2 + int(table[1][2])) / 3;
+ table[3][0] = (int(table[0][0]) + int(table[1][0]) * 2) / 3;
+ table[3][1] = (int(table[0][1]) + int(table[1][1]) * 2) / 3;
+ table[3][2] = (int(table[0][2]) + int(table[1][2]) * 2) / 3;
+
+ uint32_t block = src[4 + 8];
+ block <<= 8;
+ block |= src[5 + 8];
+ block <<= 8;
+ block |= src[6 + 8];
+ block <<= 8;
+ block |= src[7 + 8];
+
+ int y = (j / (wd / 4)) * 4;
+ int x = (j % (wd / 4)) * 4;
+ int pixofs = (y * wd + x) * 4;
+
+ for (int k = 0; k < 16; k++) {
+ uint8_t alpha = ablock & 0x7;
+ int idx = pixofs + ofs_table[k];
+ dst[idx + 0] = table[block & 0x3][0];
+ dst[idx + 1] = table[block & 0x3][1];
+ dst[idx + 2] = table[block & 0x3][2];
+ dst[idx + 3] = atable[alpha];
+ block >>= 2;
+ ablock >>= 3;
}
-
}
- rofs+=len*16;
- wofs+=wd*ht*4;
+ rofs += len * 16;
+ wofs += wd * ht * 4;
-
- wd/=2;
- ht/=2;
+ wd /= 2;
+ ht /= 2;
} break;
default: {}
}
-
}
- w=PoolVector<uint8_t>::Write();
- r=PoolVector<uint8_t>::Read();
+ w = PoolVector<uint8_t>::Write();
+ r = PoolVector<uint8_t>::Read();
- data=newdata;
- format=FORMAT_RGBA8;
- if (wd!=width || ht!=height) {
+ data = newdata;
+ format = FORMAT_RGBA8;
+ if (wd != width || ht != height) {
- SWAP(width,wd);
- SWAP(height,ht);
- crop(wd,ht);
+ SWAP(width, wd);
+ SWAP(height, ht);
+ crop(wd, ht);
}
return OK;
}
bool Image::is_compressed() const {
- return format>=FORMAT_RGB565;
+ return format >= FORMAT_RGB565;
}
-
Image Image::decompressed() const {
- Image img=*this;
+ Image img = *this;
img.decompress();
return img;
}
Error Image::decompress() {
- if (format>=FORMAT_DXT1 && format<=FORMAT_ATI2 )
- _decompress_bc();//_image_decompress_bc(this);
- else if (format>=FORMAT_PVRTC2 && format<=FORMAT_PVRTC4A&& _image_decompress_pvrtc)
+ if (format >= FORMAT_DXT1 && format <= FORMAT_ATI2)
+ _decompress_bc(); //_image_decompress_bc(this);
+ else if (format >= FORMAT_PVRTC2 && format <= FORMAT_PVRTC4A && _image_decompress_pvrtc)
_image_decompress_pvrtc(this);
- else if (format==FORMAT_ETC && _image_decompress_etc)
+ else if (format == FORMAT_ETC && _image_decompress_etc)
_image_decompress_etc(this);
- else if (format>=FORMAT_ETC2_R11 && format<=FORMAT_ETC2_RGB8A1 && _image_decompress_etc)
+ else if (format >= FORMAT_ETC2_R11 && format <= FORMAT_ETC2_RGB8A1 && _image_decompress_etc)
_image_decompress_etc2(this);
else
return ERR_UNAVAILABLE;
return OK;
}
-
Error Image::compress(CompressMode p_mode) {
- switch(p_mode) {
+ switch (p_mode) {
case COMPRESS_16BIT: {
@@ -1892,7 +1792,6 @@ Error Image::compress(CompressMode p_mode) {
} break;
}
-
return OK;
}
@@ -1906,82 +1805,75 @@ Image Image::compressed(int p_mode) {
Image::Image(const char **p_xpm) {
- width=0;
- height=0;
- mipmaps=false;
- format=FORMAT_L8;
+ width = 0;
+ height = 0;
+ mipmaps = false;
+ format = FORMAT_L8;
create(p_xpm);
}
+Image::Image(int p_width, int p_height, bool p_use_mipmaps, Format p_format) {
-Image::Image(int p_width, int p_height,bool p_use_mipmaps, Format p_format) {
-
- width=0;
- height=0;
- mipmaps=p_use_mipmaps;
- format=FORMAT_L8;
-
- create(p_width,p_height,p_use_mipmaps,p_format);
+ width = 0;
+ height = 0;
+ mipmaps = p_use_mipmaps;
+ format = FORMAT_L8;
+ create(p_width, p_height, p_use_mipmaps, p_format);
}
-Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data) {
-
- width=0;
- height=0;
- mipmaps=p_mipmaps;
- format=FORMAT_L8;
+Image::Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data) {
- create(p_width,p_height,p_mipmaps,p_format,p_data);
+ width = 0;
+ height = 0;
+ mipmaps = p_mipmaps;
+ format = FORMAT_L8;
+ create(p_width, p_height, p_mipmaps, p_format, p_data);
}
-
Rect2 Image::get_used_rect() const {
- if (format!=FORMAT_LA8 && format!=FORMAT_RGBA8)
- return Rect2(Point2(),Size2(width,height));
+ if (format != FORMAT_LA8 && format != FORMAT_RGBA8)
+ return Rect2(Point2(), Size2(width, height));
int len = data.size();
- if (len==0)
+ if (len == 0)
return Rect2();
//int data_size = len;
PoolVector<uint8_t>::Read r = data.read();
- const unsigned char *rptr=r.ptr();
+ const unsigned char *rptr = r.ptr();
- int ps = format==FORMAT_LA8?2:4;
- int minx=0xFFFFFF,miny=0xFFFFFFF;
- int maxx=-1,maxy=-1;
- for(int j=0;j<height;j++) {
- for(int i=0;i<width;i++) {
+ int ps = format == FORMAT_LA8 ? 2 : 4;
+ int minx = 0xFFFFFF, miny = 0xFFFFFFF;
+ int maxx = -1, maxy = -1;
+ for (int j = 0; j < height; j++) {
+ for (int i = 0; i < width; i++) {
-
- bool opaque = rptr[(j*width+i)*ps+(ps-1)]>2;
+ bool opaque = rptr[(j * width + i) * ps + (ps - 1)] > 2;
if (!opaque)
continue;
- if (i>maxx)
- maxx=i;
- if (j>maxy)
- maxy=j;
- if (i<minx)
- minx=i;
- if (j<miny)
- miny=j;
+ if (i > maxx)
+ maxx = i;
+ if (j > maxy)
+ maxy = j;
+ if (i < minx)
+ minx = i;
+ if (j < miny)
+ miny = j;
}
}
- if (maxx==-1)
+ if (maxx == -1)
return Rect2();
else
- return Rect2(minx,miny,maxx-minx+1,maxy-miny+1);
-
+ return Rect2(minx, miny, maxx - minx + 1, maxy - miny + 1);
}
-
-Image Image::get_rect(const Rect2& p_area) const {
+Image Image::get_rect(const Rect2 &p_area) const {
Image img(p_area.size.x, p_area.size.y, mipmaps, format);
img.blit_rect(*this, p_area, Point2(0, 0));
@@ -1989,91 +1881,85 @@ Image Image::get_rect(const Rect2& p_area) const {
return img;
}
-void Image::blit_rect(const Image& p_src, const Rect2& p_src_rect,const Point2& p_dest) {
+void Image::blit_rect(const Image &p_src, const Rect2 &p_src_rect, const Point2 &p_dest) {
- int dsize=data.size();
- int srcdsize=p_src.data.size();
- ERR_FAIL_COND( dsize==0 );
- ERR_FAIL_COND( srcdsize==0 );
- ERR_FAIL_COND( format!=p_src.format );
+ int dsize = data.size();
+ int srcdsize = p_src.data.size();
+ ERR_FAIL_COND(dsize == 0);
+ ERR_FAIL_COND(srcdsize == 0);
+ ERR_FAIL_COND(format != p_src.format);
+ Rect2i local_src_rect = Rect2i(0, 0, width, height).clip(Rect2i(p_dest + p_src_rect.pos, p_src_rect.size));
- Rect2i local_src_rect = Rect2i(0,0,width,height).clip( Rect2i(p_dest+p_src_rect.pos,p_src_rect.size) );
-
- if (local_src_rect.size.x<=0 || local_src_rect.size.y<=0)
+ if (local_src_rect.size.x <= 0 || local_src_rect.size.y <= 0)
return;
- Rect2i src_rect( p_src_rect.pos + ( local_src_rect.pos - p_dest), local_src_rect.size );
+ Rect2i src_rect(p_src_rect.pos + (local_src_rect.pos - p_dest), local_src_rect.size);
PoolVector<uint8_t>::Write wp = data.write();
- uint8_t *dst_data_ptr=wp.ptr();
+ uint8_t *dst_data_ptr = wp.ptr();
PoolVector<uint8_t>::Read rp = p_src.data.read();
- const uint8_t *src_data_ptr=rp.ptr();
-
- int pixel_size=get_format_pixel_size(format);
+ const uint8_t *src_data_ptr = rp.ptr();
- for(int i=0;i<src_rect.size.y;i++) {
+ int pixel_size = get_format_pixel_size(format);
+ for (int i = 0; i < src_rect.size.y; i++) {
- for(int j=0;j<src_rect.size.x;j++) {
+ for (int j = 0; j < src_rect.size.x; j++) {
- int src_x = src_rect.pos.x+j;
- int src_y = src_rect.pos.y+i;
+ int src_x = src_rect.pos.x + j;
+ int src_y = src_rect.pos.y + i;
- int dst_x = local_src_rect.pos.x+j;
- int dst_y = local_src_rect.pos.y+i;
+ int dst_x = local_src_rect.pos.x + j;
+ int dst_y = local_src_rect.pos.y + i;
- const uint8_t *src = &src_data_ptr[ (src_y*p_src.width+src_x)*pixel_size];
- uint8_t *dst = &dst_data_ptr[ (dst_y*width+dst_x)*pixel_size];
+ const uint8_t *src = &src_data_ptr[(src_y * p_src.width + src_x) * pixel_size];
+ uint8_t *dst = &dst_data_ptr[(dst_y * width + dst_x) * pixel_size];
- for(int k=0;k<pixel_size;k++) {
- dst[k]=src[k];
+ for (int k = 0; k < pixel_size; k++) {
+ dst[k] = src[k];
}
}
}
-
}
+Image (*Image::_png_mem_loader_func)(const uint8_t *, int) = NULL;
+Image (*Image::_jpg_mem_loader_func)(const uint8_t *, int) = NULL;
-Image (*Image::_png_mem_loader_func)(const uint8_t*,int)=NULL;
-Image (*Image::_jpg_mem_loader_func)(const uint8_t*,int)=NULL;
-
-void (*Image::_image_compress_bc_func)(Image *)=NULL;
-void (*Image::_image_compress_pvrtc2_func)(Image *)=NULL;
-void (*Image::_image_compress_pvrtc4_func)(Image *)=NULL;
-void (*Image::_image_compress_etc_func)(Image *)=NULL;
-void (*Image::_image_compress_etc2_func)(Image *)=NULL;
-void (*Image::_image_decompress_pvrtc)(Image *)=NULL;
-void (*Image::_image_decompress_bc)(Image *)=NULL;
-void (*Image::_image_decompress_etc)(Image *)=NULL;
-void (*Image::_image_decompress_etc2)(Image *)=NULL;
+void (*Image::_image_compress_bc_func)(Image *) = NULL;
+void (*Image::_image_compress_pvrtc2_func)(Image *) = NULL;
+void (*Image::_image_compress_pvrtc4_func)(Image *) = NULL;
+void (*Image::_image_compress_etc_func)(Image *) = NULL;
+void (*Image::_image_compress_etc2_func)(Image *) = NULL;
+void (*Image::_image_decompress_pvrtc)(Image *) = NULL;
+void (*Image::_image_decompress_bc)(Image *) = NULL;
+void (*Image::_image_decompress_etc)(Image *) = NULL;
+void (*Image::_image_decompress_etc2)(Image *) = NULL;
-PoolVector<uint8_t> (*Image::lossy_packer)(const Image& ,float )=NULL;
-Image (*Image::lossy_unpacker)(const PoolVector<uint8_t>& )=NULL;
-PoolVector<uint8_t> (*Image::lossless_packer)(const Image& )=NULL;
-Image (*Image::lossless_unpacker)(const PoolVector<uint8_t>& )=NULL;
+PoolVector<uint8_t> (*Image::lossy_packer)(const Image &, float) = NULL;
+Image (*Image::lossy_unpacker)(const PoolVector<uint8_t> &) = NULL;
+PoolVector<uint8_t> (*Image::lossless_packer)(const Image &) = NULL;
+Image (*Image::lossless_unpacker)(const PoolVector<uint8_t> &) = NULL;
void Image::set_compress_bc_func(void (*p_compress_func)(Image *)) {
- _image_compress_bc_func=p_compress_func;
+ _image_compress_bc_func = p_compress_func;
}
-
-
void Image::normalmap_to_xy() {
convert(Image::FORMAT_RGBA8);
{
- int len = data.size()/4;
+ int len = data.size() / 4;
PoolVector<uint8_t>::Write wp = data.write();
- unsigned char *data_ptr=wp.ptr();
+ unsigned char *data_ptr = wp.ptr();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- data_ptr[(i<<2)+3]=data_ptr[(i<<2)+0]; //x to w
- data_ptr[(i<<2)+0]=data_ptr[(i<<2)+1]; //y to xz
- data_ptr[(i<<2)+2]=data_ptr[(i<<2)+1];
+ data_ptr[(i << 2) + 3] = data_ptr[(i << 2) + 0]; //x to w
+ data_ptr[(i << 2) + 0] = data_ptr[(i << 2) + 1]; //y to xz
+ data_ptr[(i << 2) + 2] = data_ptr[(i << 2) + 1];
}
}
@@ -2082,171 +1968,159 @@ void Image::normalmap_to_xy() {
void Image::srgb_to_linear() {
- if (data.size()==0)
+ if (data.size() == 0)
return;
- static const uint8_t srgb2lin[256]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252};
-
+ static const uint8_t srgb2lin[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 22, 22, 23, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 31, 31, 32, 33, 33, 34, 35, 36, 36, 37, 38, 38, 39, 40, 41, 42, 42, 43, 44, 45, 46, 47, 47, 48, 49, 50, 51, 52, 53, 54, 55, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 80, 81, 82, 83, 84, 85, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 101, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 122, 123, 125, 126, 128, 129, 131, 132, 134, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 152, 153, 155, 157, 159, 160, 162, 164, 166, 167, 169, 171, 173, 175, 176, 178, 180, 182, 184, 186, 188, 190, 192, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 218, 220, 222, 224, 226, 228, 230, 232, 235, 237, 239, 241, 243, 245, 248, 250, 252 };
- ERR_FAIL_COND( format!=FORMAT_RGB8 && format!=FORMAT_RGBA8 );
+ ERR_FAIL_COND(format != FORMAT_RGB8 && format != FORMAT_RGBA8);
- if (format==FORMAT_RGBA8) {
+ if (format == FORMAT_RGBA8) {
- int len = data.size()/4;
+ int len = data.size() / 4;
PoolVector<uint8_t>::Write wp = data.write();
- unsigned char *data_ptr=wp.ptr();
+ unsigned char *data_ptr = wp.ptr();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- data_ptr[(i<<2)+0]=srgb2lin[ data_ptr[(i<<2)+0] ];
- data_ptr[(i<<2)+1]=srgb2lin[ data_ptr[(i<<2)+1] ];
- data_ptr[(i<<2)+2]=srgb2lin[ data_ptr[(i<<2)+2] ];
+ data_ptr[(i << 2) + 0] = srgb2lin[data_ptr[(i << 2) + 0]];
+ data_ptr[(i << 2) + 1] = srgb2lin[data_ptr[(i << 2) + 1]];
+ data_ptr[(i << 2) + 2] = srgb2lin[data_ptr[(i << 2) + 2]];
}
- } else if (format==FORMAT_RGB8) {
+ } else if (format == FORMAT_RGB8) {
- int len = data.size()/3;
+ int len = data.size() / 3;
PoolVector<uint8_t>::Write wp = data.write();
- unsigned char *data_ptr=wp.ptr();
+ unsigned char *data_ptr = wp.ptr();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- data_ptr[(i*3)+0]=srgb2lin[ data_ptr[(i*3)+0] ];
- data_ptr[(i*3)+1]=srgb2lin[ data_ptr[(i*3)+1] ];
- data_ptr[(i*3)+2]=srgb2lin[ data_ptr[(i*3)+2] ];
+ data_ptr[(i * 3) + 0] = srgb2lin[data_ptr[(i * 3) + 0]];
+ data_ptr[(i * 3) + 1] = srgb2lin[data_ptr[(i * 3) + 1]];
+ data_ptr[(i * 3) + 2] = srgb2lin[data_ptr[(i * 3) + 2]];
}
}
-
}
void Image::premultiply_alpha() {
- if (data.size()==0)
+ if (data.size() == 0)
return;
- if (format!=FORMAT_RGBA8)
+ if (format != FORMAT_RGBA8)
return; //not needed
PoolVector<uint8_t>::Write wp = data.write();
- unsigned char *data_ptr=wp.ptr();
+ unsigned char *data_ptr = wp.ptr();
+ for (int i = 0; i < height; i++) {
+ for (int j = 0; j < width; j++) {
- for(int i=0;i<height;i++) {
- for(int j=0;j<width;j++) {
+ uint8_t *ptr = &data_ptr[(i * width + j) * 4];
- uint8_t *ptr = &data_ptr[(i*width+j)*4];
-
- ptr[0]=(uint16_t(ptr[0])*uint16_t(ptr[3]))>>8;
- ptr[1]=(uint16_t(ptr[1])*uint16_t(ptr[3]))>>8;
- ptr[2]=(uint16_t(ptr[2])*uint16_t(ptr[3]))>>8;
+ ptr[0] = (uint16_t(ptr[0]) * uint16_t(ptr[3])) >> 8;
+ ptr[1] = (uint16_t(ptr[1]) * uint16_t(ptr[3])) >> 8;
+ ptr[2] = (uint16_t(ptr[2]) * uint16_t(ptr[3])) >> 8;
}
}
}
void Image::fix_alpha_edges() {
- if (data.size()==0)
+ if (data.size() == 0)
return;
- if (format!=FORMAT_RGBA8)
+ if (format != FORMAT_RGBA8)
return; //not needed
PoolVector<uint8_t> dcopy = data;
PoolVector<uint8_t>::Read rp = dcopy.read();
- const uint8_t *srcptr=rp.ptr();
+ const uint8_t *srcptr = rp.ptr();
PoolVector<uint8_t>::Write wp = data.write();
- unsigned char *data_ptr=wp.ptr();
+ unsigned char *data_ptr = wp.ptr();
- const int max_radius=4;
- const int alpha_treshold=20;
- const int max_dist=0x7FFFFFFF;
+ const int max_radius = 4;
+ const int alpha_treshold = 20;
+ const int max_dist = 0x7FFFFFFF;
- for(int i=0;i<height;i++) {
- for(int j=0;j<width;j++) {
+ for (int i = 0; i < height; i++) {
+ for (int j = 0; j < width; j++) {
- const uint8_t *rptr = &srcptr[(i*width+j)*4];
- uint8_t *wptr = &data_ptr[(i*width+j)*4];
+ const uint8_t *rptr = &srcptr[(i * width + j) * 4];
+ uint8_t *wptr = &data_ptr[(i * width + j) * 4];
- if (rptr[3]>=alpha_treshold)
+ if (rptr[3] >= alpha_treshold)
continue;
- int closest_dist=max_dist;
+ int closest_dist = max_dist;
uint8_t closest_color[3];
+ int from_x = MAX(0, j - max_radius);
+ int to_x = MIN(width - 1, j + max_radius);
+ int from_y = MAX(0, i - max_radius);
+ int to_y = MIN(height - 1, i + max_radius);
- int from_x = MAX(0,j-max_radius);
- int to_x = MIN(width-1,j+max_radius);
- int from_y = MAX(0,i-max_radius);
- int to_y = MIN(height-1,i+max_radius);
-
- for(int k=from_y;k<=to_y;k++) {
- for(int l=from_x;l<=to_x;l++) {
+ for (int k = from_y; k <= to_y; k++) {
+ for (int l = from_x; l <= to_x; l++) {
- int dy = i-k;
- int dx = j-l;
- int dist = dy*dy+dx*dx;
- if (dist>=closest_dist)
+ int dy = i - k;
+ int dx = j - l;
+ int dist = dy * dy + dx * dx;
+ if (dist >= closest_dist)
continue;
- const uint8_t * rp = &srcptr[(k*width+l)<<2];
+ const uint8_t *rp = &srcptr[(k * width + l) << 2];
- if (rp[3]<alpha_treshold)
+ if (rp[3] < alpha_treshold)
continue;
- closest_color[0]=rp[0];
- closest_color[1]=rp[1];
- closest_color[2]=rp[2];
-
+ closest_color[0] = rp[0];
+ closest_color[1] = rp[1];
+ closest_color[2] = rp[2];
}
}
+ if (closest_dist != max_dist) {
- if (closest_dist!=max_dist) {
-
- wptr[0]=closest_color[0];
- wptr[1]=closest_color[1];
- wptr[2]=closest_color[2];
+ wptr[0] = closest_color[0];
+ wptr[1] = closest_color[1];
+ wptr[2] = closest_color[2];
}
-
}
}
-
}
String Image::get_format_name(Format p_format) {
- ERR_FAIL_INDEX_V(p_format,FORMAT_MAX,String());
+ ERR_FAIL_INDEX_V(p_format, FORMAT_MAX, String());
return format_names[p_format];
}
-Image::Image(const uint8_t* p_mem_png_jpg, int p_len) {
+Image::Image(const uint8_t *p_mem_png_jpg, int p_len) {
- width=0;
- height=0;
- mipmaps=false;
- format=FORMAT_L8;
+ width = 0;
+ height = 0;
+ mipmaps = false;
+ format = FORMAT_L8;
if (_png_mem_loader_func) {
- *this = _png_mem_loader_func(p_mem_png_jpg,p_len);
+ *this = _png_mem_loader_func(p_mem_png_jpg, p_len);
}
if (empty() && _jpg_mem_loader_func) {
- *this = _jpg_mem_loader_func(p_mem_png_jpg,p_len);
+ *this = _jpg_mem_loader_func(p_mem_png_jpg, p_len);
}
-
}
Image::Image() {
- width=0;
- height=0;
- mipmaps=false;
+ width = 0;
+ height = 0;
+ mipmaps = false;
format = FORMAT_L8;
}
Image::~Image() {
-
}
-
-
diff --git a/core/image.h b/core/image.h
index 1a257f28a0..310351e547 100644
--- a/core/image.h
+++ b/core/image.h
@@ -29,8 +29,8 @@
#ifndef IMAGE_H
#define IMAGE_H
-#include "dvector.h"
#include "color.h"
+#include "dvector.h"
#include "math_2d.h"
/**
* @author Juan Linietsky <reduzio@gmail.com>
@@ -42,16 +42,16 @@
class Image;
-typedef Error (*SavePNGFunc)(const String &p_path, Image& p_img);
+typedef Error (*SavePNGFunc)(const String &p_path, Image &p_img);
class Image {
enum {
- MAX_WIDTH=16384, // force a limit somehow
- MAX_HEIGHT=16384// force a limit somehow
+ MAX_WIDTH = 16384, // force a limit somehow
+ MAX_HEIGHT = 16384 // force a limit somehow
};
-public:
+public:
static SavePNGFunc save_png_func;
enum Format {
@@ -96,7 +96,7 @@ public:
FORMAT_MAX
};
- static const char* format_names[FORMAT_MAX];
+ static const char *format_names[FORMAT_MAX];
enum Interpolation {
INTERPOLATE_NEAREST,
@@ -107,8 +107,8 @@ public:
//some functions provided by something else
- static Image (*_png_mem_loader_func)(const uint8_t* p_png,int p_size);
- static Image (*_jpg_mem_loader_func)(const uint8_t* p_png,int p_size);
+ static Image (*_png_mem_loader_func)(const uint8_t *p_png, int p_size);
+ static Image (*_jpg_mem_loader_func)(const uint8_t *p_png, int p_size);
static void (*_image_compress_bc_func)(Image *);
static void (*_image_compress_pvrtc2_func)(Image *);
@@ -123,30 +123,26 @@ public:
Error _decompress_bc();
- static PoolVector<uint8_t> (*lossy_packer)(const Image& p_image,float p_quality);
- static Image (*lossy_unpacker)(const PoolVector<uint8_t>& p_buffer);
- static PoolVector<uint8_t> (*lossless_packer)(const Image& p_image);
- static Image (*lossless_unpacker)(const PoolVector<uint8_t>& p_buffer);
-private:
+ static PoolVector<uint8_t> (*lossy_packer)(const Image &p_image, float p_quality);
+ static Image (*lossy_unpacker)(const PoolVector<uint8_t> &p_buffer);
+ static PoolVector<uint8_t> (*lossless_packer)(const Image &p_image);
+ static Image (*lossless_unpacker)(const PoolVector<uint8_t> &p_buffer);
+private:
Format format;
PoolVector<uint8_t> data;
- int width,height;
+ int width, height;
bool mipmaps;
- _FORCE_INLINE_ void _get_mipmap_offset_and_size(int p_mipmap,int &r_offset, int &r_width, int &r_height) const; //get where the mipmap begins in data
+ _FORCE_INLINE_ void _get_mipmap_offset_and_size(int p_mipmap, int &r_offset, int &r_width, int &r_height) const; //get where the mipmap begins in data
- static int _get_dst_image_size(int p_width, int p_height, Format p_format,int &r_mipmaps,int p_mipmaps=-1);
+ static int _get_dst_image_size(int p_width, int p_height, Format p_format, int &r_mipmaps, int p_mipmaps = -1);
bool _can_modify(Format p_format) const;
-
- _FORCE_INLINE_ void _put_pixelb(int p_x,int p_y, uint32_t p_pixelsize,uint8_t *p_dst,const uint8_t *p_src);
- _FORCE_INLINE_ void _get_pixelb(int p_x,int p_y, uint32_t p_pixelsize,const uint8_t *p_src,uint8_t *p_dst);
+ _FORCE_INLINE_ void _put_pixelb(int p_x, int p_y, uint32_t p_pixelsize, uint8_t *p_dst, const uint8_t *p_src);
+ _FORCE_INLINE_ void _get_pixelb(int p_x, int p_y, uint32_t p_pixelsize, const uint8_t *p_src, uint8_t *p_dst);
public:
-
-
-
int get_width() const; ///< Get image width
int get_height() const; ///< Get image height
bool has_mipmaps() const;
@@ -155,7 +151,7 @@ public:
/**
* Convert the image to another format, conversion only to raw byte format
*/
- void convert( Format p_new_format );
+ void convert(Format p_new_format);
Image converted(int p_new_format) {
ERR_FAIL_INDEX_V(p_new_format, FORMAT_MAX, Image());
@@ -171,24 +167,23 @@ public:
Format get_format() const;
int get_mipmap_offset(int p_mipmap) const; //get where the mipmap begins in data
- void get_mipmap_offset_and_size(int p_mipmap,int &r_ofs, int &r_size) const; //get where the mipmap begins in data
- void get_mipmap_offset_size_and_dimensions(int p_mipmap,int &r_ofs, int &r_size,int &w, int& h) const; //get where the mipmap begins in data
+ void get_mipmap_offset_and_size(int p_mipmap, int &r_ofs, int &r_size) const; //get where the mipmap begins in data
+ void get_mipmap_offset_size_and_dimensions(int p_mipmap, int &r_ofs, int &r_size, int &w, int &h) const; //get where the mipmap begins in data
/**
* Resize the image, using the prefered interpolation method.
* Indexed-Color images always use INTERPOLATE_NEAREST.
*/
- void resize_to_po2(bool p_square=false);
- void resize( int p_width, int p_height, Interpolation p_interpolation=INTERPOLATE_BILINEAR );
- Image resized( int p_width, int p_height, int p_interpolation=INTERPOLATE_BILINEAR );
+ void resize_to_po2(bool p_square = false);
+ void resize(int p_width, int p_height, Interpolation p_interpolation = INTERPOLATE_BILINEAR);
+ Image resized(int p_width, int p_height, int p_interpolation = INTERPOLATE_BILINEAR);
void shrink_x2();
void expand_x2_hq2x();
/**
* Crop the image to a specific size, if larger, then the image is filled by black
*/
- void crop( int p_width, int p_height );
-
+ void crop(int p_width, int p_height);
void flip_x();
void flip_y();
@@ -200,15 +195,13 @@ public:
void clear_mipmaps();
-
-
/**
* Create a new image of a given size and format. Current image will be lost
*/
void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format);
- void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data);
+ void create(int p_width, int p_height, bool p_use_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data);
- void create( const char ** p_xpm );
+ void create(const char **p_xpm);
/**
* returns true when the image is empty (0,0) in size
*/
@@ -216,8 +209,8 @@ public:
PoolVector<uint8_t> get_data() const;
- Error load(const String& p_path);
- Error save_png(const String& p_path);
+ Error load(const String &p_path);
+ Error save_png(const String &p_path);
/**
* create an empty image
@@ -230,7 +223,7 @@ public:
/**
* import an image of a specific size and format from a pointer
*/
- Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t>& p_data);
+ Image(int p_width, int p_height, bool p_mipmaps, Format p_format, const PoolVector<uint8_t> &p_data);
enum AlphaMode {
ALPHA_NONE,
@@ -241,16 +234,14 @@ public:
AlphaMode detect_alpha() const;
bool is_invisible() const;
-
static int get_format_pixel_size(Format p_format);
static int get_format_pixel_rshift(Format p_format);
- static void get_format_min_pixel_size(Format p_format,int &r_w, int &r_h);
+ static void get_format_min_pixel_size(Format p_format, int &r_w, int &r_h);
- static int get_image_data_size(int p_width, int p_height, Format p_format,int p_mipmaps=0);
+ static int get_image_data_size(int p_width, int p_height, Format p_format, int p_mipmaps = 0);
static int get_image_required_mipmaps(int p_width, int p_height, Format p_format);
-
- bool operator==(const Image& p_image) const;
+ bool operator==(const Image &p_image) const;
enum CompressMode {
COMPRESS_16BIT,
@@ -261,7 +252,7 @@ public:
COMPRESS_ETC2
};
- Error compress(CompressMode p_mode=COMPRESS_S3TC);
+ Error compress(CompressMode p_mode = COMPRESS_S3TC);
Image compressed(int p_mode); /* from the Image::CompressMode enum */
Error decompress();
Image decompressed() const;
@@ -272,19 +263,17 @@ public:
void srgb_to_linear();
void normalmap_to_xy();
- void blit_rect(const Image& p_src, const Rect2& p_src_rect,const Point2& p_dest);
+ void blit_rect(const Image &p_src, const Rect2 &p_src_rect, const Point2 &p_dest);
Rect2 get_used_rect() const;
- Image get_rect(const Rect2& p_area) const;
+ Image get_rect(const Rect2 &p_area) const;
static void set_compress_bc_func(void (*p_compress_func)(Image *));
static String get_format_name(Format p_format);
- Image(const uint8_t* p_mem_png_jpg, int p_len=-1);
+ Image(const uint8_t *p_mem_png_jpg, int p_len = -1);
Image(const char **p_xpm);
~Image();
-
};
-
#endif
diff --git a/core/input_map.cpp b/core/input_map.cpp
index 444c55cac6..b2b4246d6a 100644
--- a/core/input_map.cpp
+++ b/core/input_map.cpp
@@ -31,50 +31,45 @@
#include "global_config.h"
#include "os/keyboard.h"
-InputMap *InputMap::singleton=NULL;
+InputMap *InputMap::singleton = NULL;
void InputMap::_bind_methods() {
- ClassDB::bind_method(D_METHOD("has_action","action"),&InputMap::has_action);
- ClassDB::bind_method(D_METHOD("get_action_id","action"),&InputMap::get_action_id);
- ClassDB::bind_method(D_METHOD("get_action_from_id","id"),&InputMap::get_action_from_id);
- ClassDB::bind_method(D_METHOD("get_actions"),&InputMap::_get_actions);
- ClassDB::bind_method(D_METHOD("add_action","action"),&InputMap::add_action);
- ClassDB::bind_method(D_METHOD("erase_action","action"),&InputMap::erase_action);
-
- ClassDB::bind_method(D_METHOD("action_add_event","action","event"),&InputMap::action_add_event);
- ClassDB::bind_method(D_METHOD("action_has_event","action","event"),&InputMap::action_has_event);
- ClassDB::bind_method(D_METHOD("action_erase_event","action","event"),&InputMap::action_erase_event);
- ClassDB::bind_method(D_METHOD("get_action_list","action"),&InputMap::_get_action_list);
- ClassDB::bind_method(D_METHOD("event_is_action","event","action"),&InputMap::event_is_action);
- ClassDB::bind_method(D_METHOD("load_from_globals"),&InputMap::load_from_globals);
-
+ ClassDB::bind_method(D_METHOD("has_action", "action"), &InputMap::has_action);
+ ClassDB::bind_method(D_METHOD("get_action_id", "action"), &InputMap::get_action_id);
+ ClassDB::bind_method(D_METHOD("get_action_from_id", "id"), &InputMap::get_action_from_id);
+ ClassDB::bind_method(D_METHOD("get_actions"), &InputMap::_get_actions);
+ ClassDB::bind_method(D_METHOD("add_action", "action"), &InputMap::add_action);
+ ClassDB::bind_method(D_METHOD("erase_action", "action"), &InputMap::erase_action);
+
+ ClassDB::bind_method(D_METHOD("action_add_event", "action", "event"), &InputMap::action_add_event);
+ ClassDB::bind_method(D_METHOD("action_has_event", "action", "event"), &InputMap::action_has_event);
+ ClassDB::bind_method(D_METHOD("action_erase_event", "action", "event"), &InputMap::action_erase_event);
+ ClassDB::bind_method(D_METHOD("get_action_list", "action"), &InputMap::_get_action_list);
+ ClassDB::bind_method(D_METHOD("event_is_action", "event", "action"), &InputMap::event_is_action);
+ ClassDB::bind_method(D_METHOD("load_from_globals"), &InputMap::load_from_globals);
}
+void InputMap::add_action(const StringName &p_action) {
-void InputMap::add_action(const StringName& p_action) {
-
- ERR_FAIL_COND( input_map.has(p_action) );
- input_map[p_action]=Action();
- static int last_id=1;
- input_map[p_action].id=last_id;
- input_id_map[last_id]=p_action;
+ ERR_FAIL_COND(input_map.has(p_action));
+ input_map[p_action] = Action();
+ static int last_id = 1;
+ input_map[p_action].id = last_id;
+ input_id_map[last_id] = p_action;
last_id++;
-
-
}
-void InputMap::erase_action(const StringName& p_action) {
+void InputMap::erase_action(const StringName &p_action) {
- ERR_FAIL_COND( !input_map.has(p_action) );
+ ERR_FAIL_COND(!input_map.has(p_action));
input_id_map.erase(input_map[p_action].id);
input_map.erase(p_action);
-
}
StringName InputMap::get_action_from_id(int p_id) const {
- ERR_FAIL_COND_V(!input_id_map.has(p_id),StringName());
+ ERR_FAIL_COND_V(!input_id_map.has(p_id), StringName());
return input_id_map[p_id];
}
@@ -82,10 +77,10 @@ Array InputMap::_get_actions() {
Array ret;
List<StringName> actions = get_actions();
- if(actions.empty())
+ if (actions.empty())
return ret;
- for(const List<StringName>::Element *E=actions.front();E;E=E->next()) {
+ for (const List<StringName>::Element *E = actions.front(); E; E = E->next()) {
ret.push_back(E->get());
}
@@ -96,55 +91,55 @@ Array InputMap::_get_actions() {
List<StringName> InputMap::get_actions() const {
List<StringName> actions = List<StringName>();
- if(input_map.empty()){
+ if (input_map.empty()) {
return actions;
}
- for (Map<StringName, Action>::Element *E=input_map.front();E;E=E->next()) {
+ for (Map<StringName, Action>::Element *E = input_map.front(); E; E = E->next()) {
actions.push_back(E->key());
}
return actions;
}
-List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &p_list,const InputEvent& p_event, bool p_action_test) const {
+List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &p_list, const InputEvent &p_event, bool p_action_test) const {
- for (List<InputEvent>::Element *E=p_list.front();E;E=E->next()) {
+ for (List<InputEvent>::Element *E = p_list.front(); E; E = E->next()) {
- const InputEvent& e=E->get();
- if(e.type!=p_event.type)
+ const InputEvent &e = E->get();
+ if (e.type != p_event.type)
continue;
- if (e.type!=InputEvent::KEY && e.device!=p_event.device)
+ if (e.type != InputEvent::KEY && e.device != p_event.device)
continue;
- bool same=false;
+ bool same = false;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::KEY: {
- if(p_action_test) {
+ if (p_action_test) {
uint32_t code = e.key.get_scancode_with_modifiers();
uint32_t event_code = p_event.key.get_scancode_with_modifiers();
- same=(e.key.scancode==p_event.key.scancode && (!p_event.key.pressed || ((code & event_code) == code)));
+ same = (e.key.scancode == p_event.key.scancode && (!p_event.key.pressed || ((code & event_code) == code)));
} else {
- same=(e.key.scancode==p_event.key.scancode && e.key.mod == p_event.key.mod);
+ same = (e.key.scancode == p_event.key.scancode && e.key.mod == p_event.key.mod);
}
} break;
case InputEvent::JOYPAD_BUTTON: {
- same=(e.joy_button.button_index==p_event.joy_button.button_index);
+ same = (e.joy_button.button_index == p_event.joy_button.button_index);
} break;
case InputEvent::MOUSE_BUTTON: {
- same=(e.mouse_button.button_index==p_event.mouse_button.button_index);
+ same = (e.mouse_button.button_index == p_event.mouse_button.button_index);
} break;
case InputEvent::JOYPAD_MOTION: {
- same=(e.joy_motion.axis==p_event.joy_motion.axis && (e.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0));
+ same = (e.joy_motion.axis == p_event.joy_motion.axis && (e.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0));
} break;
}
@@ -153,93 +148,85 @@ List<InputEvent>::Element *InputMap::_find_event(List<InputEvent> &p_list,const
return E;
}
-
return NULL;
}
-
-bool InputMap::has_action(const StringName& p_action) const {
+bool InputMap::has_action(const StringName &p_action) const {
return input_map.has(p_action);
}
-void InputMap::action_add_event(const StringName& p_action,const InputEvent& p_event) {
+void InputMap::action_add_event(const StringName &p_action, const InputEvent &p_event) {
- ERR_FAIL_COND(p_event.type==InputEvent::ACTION);
- ERR_FAIL_COND( !input_map.has(p_action) );
- if (_find_event(input_map[p_action].inputs,p_event))
+ ERR_FAIL_COND(p_event.type == InputEvent::ACTION);
+ ERR_FAIL_COND(!input_map.has(p_action));
+ if (_find_event(input_map[p_action].inputs, p_event))
return; //already gots
input_map[p_action].inputs.push_back(p_event);
-
}
+int InputMap::get_action_id(const StringName &p_action) const {
-int InputMap::get_action_id(const StringName& p_action) const {
-
- ERR_FAIL_COND_V(!input_map.has(p_action),-1);
+ ERR_FAIL_COND_V(!input_map.has(p_action), -1);
return input_map[p_action].id;
}
-bool InputMap::action_has_event(const StringName& p_action,const InputEvent& p_event) {
-
- ERR_FAIL_COND_V( !input_map.has(p_action), false );
- return (_find_event(input_map[p_action].inputs,p_event)!=NULL);
+bool InputMap::action_has_event(const StringName &p_action, const InputEvent &p_event) {
+ ERR_FAIL_COND_V(!input_map.has(p_action), false);
+ return (_find_event(input_map[p_action].inputs, p_event) != NULL);
}
-void InputMap::action_erase_event(const StringName& p_action,const InputEvent& p_event) {
+void InputMap::action_erase_event(const StringName &p_action, const InputEvent &p_event) {
- ERR_FAIL_COND( !input_map.has(p_action) );
+ ERR_FAIL_COND(!input_map.has(p_action));
- List<InputEvent>::Element *E=_find_event(input_map[p_action].inputs,p_event);
+ List<InputEvent>::Element *E = _find_event(input_map[p_action].inputs, p_event);
if (E)
input_map[p_action].inputs.erase(E);
}
-
-Array InputMap::_get_action_list(const StringName& p_action) {
+Array InputMap::_get_action_list(const StringName &p_action) {
Array ret;
const List<InputEvent> *al = get_action_list(p_action);
if (al) {
- for(const List<InputEvent>::Element *E=al->front();E;E=E->next()) {
+ for (const List<InputEvent>::Element *E = al->front(); E; E = E->next()) {
ret.push_back(E->get());
}
}
return ret;
-
}
-const List<InputEvent> *InputMap::get_action_list(const StringName& p_action) {
+const List<InputEvent> *InputMap::get_action_list(const StringName &p_action) {
- const Map<StringName, Action>::Element *E=input_map.find(p_action);
+ const Map<StringName, Action>::Element *E = input_map.find(p_action);
if (!E)
return NULL;
return &E->get().inputs;
}
-bool InputMap::event_is_action(const InputEvent& p_event, const StringName& p_action) const {
+bool InputMap::event_is_action(const InputEvent &p_event, const StringName &p_action) const {
-
- Map<StringName,Action >::Element *E=input_map.find(p_action);
- if(!E) {
- ERR_EXPLAIN("Request for nonexistent InputMap action: "+String(p_action));
- ERR_FAIL_COND_V(!E,false);
+ Map<StringName, Action>::Element *E = input_map.find(p_action);
+ if (!E) {
+ ERR_EXPLAIN("Request for nonexistent InputMap action: " + String(p_action));
+ ERR_FAIL_COND_V(!E, false);
}
- if (p_event.type==InputEvent::ACTION) {
+ if (p_event.type == InputEvent::ACTION) {
- return p_event.action.action==E->get().id;
+ return p_event.action.action == E->get().id;
}
- return _find_event(E->get().inputs,p_event,true)!=NULL;
+ return _find_event(E->get().inputs, p_event, true) != NULL;
}
-const Map<StringName, InputMap::Action>& InputMap::get_action_map() const {
+const Map<StringName, InputMap::Action> &InputMap::get_action_map() const {
return input_map;
}
@@ -250,94 +237,88 @@ void InputMap::load_from_globals() {
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
add_action(name);
Array va = GlobalConfig::get_singleton()->get(pi.name);
- for(int i=0;i<va.size();i++) {
+ for (int i = 0; i < va.size(); i++) {
- InputEvent ie=va[i];
- if (ie.type==InputEvent::NONE)
+ InputEvent ie = va[i];
+ if (ie.type == InputEvent::NONE)
continue;
- action_add_event(name,ie);
-
+ action_add_event(name, ie);
}
-
}
-
}
void InputMap::load_default() {
InputEvent key;
- key.type=InputEvent::KEY;
+ key.type = InputEvent::KEY;
add_action("ui_accept");
- key.key.scancode=KEY_RETURN;
- action_add_event("ui_accept",key);
- key.key.scancode=KEY_ENTER;
- action_add_event("ui_accept",key);
- key.key.scancode=KEY_SPACE;
- action_add_event("ui_accept",key);
+ key.key.scancode = KEY_RETURN;
+ action_add_event("ui_accept", key);
+ key.key.scancode = KEY_ENTER;
+ action_add_event("ui_accept", key);
+ key.key.scancode = KEY_SPACE;
+ action_add_event("ui_accept", key);
add_action("ui_select");
- key.key.scancode=KEY_SPACE;
- action_add_event("ui_select",key);
+ key.key.scancode = KEY_SPACE;
+ action_add_event("ui_select", key);
add_action("ui_cancel");
- key.key.scancode=KEY_ESCAPE;
- action_add_event("ui_cancel",key);
+ key.key.scancode = KEY_ESCAPE;
+ action_add_event("ui_cancel", key);
add_action("ui_focus_next");
- key.key.scancode=KEY_TAB;
- action_add_event("ui_focus_next",key);
+ key.key.scancode = KEY_TAB;
+ action_add_event("ui_focus_next", key);
add_action("ui_focus_prev");
- key.key.scancode=KEY_TAB;
- key.key.mod.shift=true;
- action_add_event("ui_focus_prev",key);
- key.key.mod.shift=false;
+ key.key.scancode = KEY_TAB;
+ key.key.mod.shift = true;
+ action_add_event("ui_focus_prev", key);
+ key.key.mod.shift = false;
add_action("ui_left");
- key.key.scancode=KEY_LEFT;
- action_add_event("ui_left",key);
+ key.key.scancode = KEY_LEFT;
+ action_add_event("ui_left", key);
add_action("ui_right");
- key.key.scancode=KEY_RIGHT;
- action_add_event("ui_right",key);
+ key.key.scancode = KEY_RIGHT;
+ action_add_event("ui_right", key);
add_action("ui_up");
- key.key.scancode=KEY_UP;
- action_add_event("ui_up",key);
+ key.key.scancode = KEY_UP;
+ action_add_event("ui_up", key);
add_action("ui_down");
- key.key.scancode=KEY_DOWN;
- action_add_event("ui_down",key);
-
+ key.key.scancode = KEY_DOWN;
+ action_add_event("ui_down", key);
add_action("ui_page_up");
- key.key.scancode=KEY_PAGEUP;
- action_add_event("ui_page_up",key);
+ key.key.scancode = KEY_PAGEUP;
+ action_add_event("ui_page_up", key);
add_action("ui_page_down");
- key.key.scancode=KEY_PAGEDOWN;
- action_add_event("ui_page_down",key);
+ key.key.scancode = KEY_PAGEDOWN;
+ action_add_event("ui_page_down", key);
//set("display/handheld/orientation", "landscape");
-
-
}
InputMap::InputMap() {
ERR_FAIL_COND(singleton);
- singleton=this;
+ singleton = this;
}
diff --git a/core/input_map.h b/core/input_map.h
index 6ccd24f29c..25d0c3e1b9 100644
--- a/core/input_map.h
+++ b/core/input_map.h
@@ -29,51 +29,50 @@
#ifndef INPUT_MAP_H
#define INPUT_MAP_H
-
#include "object.h"
class InputMap : public Object {
- GDCLASS( InputMap, Object );
+ GDCLASS(InputMap, Object);
+
public:
struct Action {
int id;
List<InputEvent> inputs;
};
+
private:
static InputMap *singleton;
mutable Map<StringName, Action> input_map;
- mutable Map<int,StringName> input_id_map;
+ mutable Map<int, StringName> input_id_map;
- List<InputEvent>::Element *_find_event(List<InputEvent> &p_list,const InputEvent& p_event, bool p_action_test=false) const;
+ List<InputEvent>::Element *_find_event(List<InputEvent> &p_list, const InputEvent &p_event, bool p_action_test = false) const;
- Array _get_action_list(const StringName& p_action);
+ Array _get_action_list(const StringName &p_action);
Array _get_actions();
protected:
-
static void _bind_methods();
-public:
+public:
static _FORCE_INLINE_ InputMap *get_singleton() { return singleton; }
-
- bool has_action(const StringName& p_action) const;
- int get_action_id(const StringName& p_action) const;
+ bool has_action(const StringName &p_action) const;
+ int get_action_id(const StringName &p_action) const;
StringName get_action_from_id(int p_id) const;
List<StringName> get_actions() const;
- void add_action(const StringName& p_action);
- void erase_action(const StringName& p_action);
+ void add_action(const StringName &p_action);
+ void erase_action(const StringName &p_action);
- void action_add_event(const StringName& p_action,const InputEvent& p_event);
- bool action_has_event(const StringName& p_action,const InputEvent& p_event);
- void action_erase_event(const StringName& p_action,const InputEvent& p_event);
+ void action_add_event(const StringName &p_action, const InputEvent &p_event);
+ bool action_has_event(const StringName &p_action, const InputEvent &p_event);
+ void action_erase_event(const StringName &p_action, const InputEvent &p_event);
- const List<InputEvent> *get_action_list(const StringName& p_action);
- bool event_is_action(const InputEvent& p_event, const StringName& p_action) const;
+ const List<InputEvent> *get_action_list(const StringName &p_action);
+ bool event_is_action(const InputEvent &p_event, const StringName &p_action) const;
- const Map<StringName, Action>& get_action_map() const;
+ const Map<StringName, Action> &get_action_map() const;
void load_from_globals();
void load_default();
diff --git a/core/int_types.h b/core/int_types.h
index a7f04c680e..50ce38a3ba 100644
--- a/core/int_types.h
+++ b/core/int_types.h
@@ -29,25 +29,25 @@
#ifdef _MSC_VER
-typedef signed __int8 int8_t;
-typedef unsigned __int8 uint8_t;
-typedef signed __int16 int16_t;
-typedef unsigned __int16 uint16_t;
-typedef signed __int32 int32_t;
-typedef unsigned __int32 uint32_t;
-typedef signed __int64 int64_t;
-typedef unsigned __int64 uint64_t;
+typedef signed __int8 int8_t;
+typedef unsigned __int8 uint8_t;
+typedef signed __int16 int16_t;
+typedef unsigned __int16 uint16_t;
+typedef signed __int32 int32_t;
+typedef unsigned __int32 uint32_t;
+typedef signed __int64 int64_t;
+typedef unsigned __int64 uint64_t;
#else
#ifdef NO_STDINT_H
-typedef unsigned char uint8_t;
-typedef signed char int8_t;
-typedef unsigned short uint16_t;
-typedef signed short int16_t;
-typedef unsigned int uint32_t;
-typedef signed int int32_t;
-typedef long long int64_t;
+typedef unsigned char uint8_t;
+typedef signed char int8_t;
+typedef unsigned short uint16_t;
+typedef signed short int16_t;
+typedef unsigned int uint32_t;
+typedef signed int int32_t;
+typedef long long int64_t;
typedef unsigned long long uint64_t;
#else
#include <stdint.h>
diff --git a/core/io/compression.cpp b/core/io/compression.cpp
index 6fda7d52f3..25fd2ad2ee 100644
--- a/core/io/compression.cpp
+++ b/core/io/compression.cpp
@@ -26,25 +26,25 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "zlib.h"
-#include "os/copymem.h"
#include "compression.h"
+#include "os/copymem.h"
+#include "zlib.h"
#include "fastlz.h"
#include "zip_io.h"
-int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode) {
+int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode) {
- switch(p_mode) {
+ switch (p_mode) {
case MODE_FASTLZ: {
- if (p_src_size<16) {
+ if (p_src_size < 16) {
uint8_t src[16];
- zeromem(&src[p_src_size],16-p_src_size);
- copymem(src,p_src,p_src_size);
- return fastlz_compress(src,16,p_dst);
+ zeromem(&src[p_src_size], 16 - p_src_size);
+ copymem(src, p_src, p_src_size);
+ return fastlz_compress(src, 16, p_dst);
} else {
- return fastlz_compress(p_src,p_src_size,p_dst);
+ return fastlz_compress(p_src, p_src_size, p_dst);
}
} break;
@@ -54,20 +54,20 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M
strm.zalloc = zipio_alloc;
strm.zfree = zipio_free;
strm.opaque = Z_NULL;
- int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION);
- if (err!=Z_OK)
- return -1;
+ int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
+ if (err != Z_OK)
+ return -1;
- strm.avail_in=p_src_size;
- int aout = deflateBound(&strm,p_src_size);
+ strm.avail_in = p_src_size;
+ int aout = deflateBound(&strm, p_src_size);
/*if (aout>p_src_size) {
deflateEnd(&strm);
return -1;
}*/
- strm.avail_out=aout;
- strm.next_in=(Bytef*)p_src;
- strm.next_out=p_dst;
- deflate(&strm,Z_FINISH);
+ strm.avail_out = aout;
+ strm.next_in = (Bytef *)p_src;
+ strm.next_out = p_dst;
+ deflate(&strm, Z_FINISH);
aout = aout - strm.avail_out;
deflateEnd(&strm);
return aout;
@@ -78,15 +78,14 @@ int Compression::compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,M
ERR_FAIL_V(-1);
}
-int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){
+int Compression::get_max_compressed_buffer_size(int p_src_size, Mode p_mode) {
- switch(p_mode) {
+ switch (p_mode) {
case MODE_FASTLZ: {
-
- int ss = p_src_size+p_src_size*6/100;
- if (ss<66)
- ss=66;
+ int ss = p_src_size + p_src_size * 6 / 100;
+ if (ss < 66)
+ ss = 66;
return ss;
} break;
@@ -96,34 +95,31 @@ int Compression::get_max_compressed_buffer_size(int p_src_size,Mode p_mode){
strm.zalloc = zipio_alloc;
strm.zfree = zipio_free;
strm.opaque = Z_NULL;
- int err = deflateInit(&strm,Z_DEFAULT_COMPRESSION);
- if (err!=Z_OK)
- return -1;
- int aout = deflateBound(&strm,p_src_size);
+ int err = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
+ if (err != Z_OK)
+ return -1;
+ int aout = deflateBound(&strm, p_src_size);
deflateEnd(&strm);
return aout;
} break;
}
ERR_FAIL_V(-1);
-
}
+int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode) {
-
-int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode){
-
- switch(p_mode) {
+ switch (p_mode) {
case MODE_FASTLZ: {
- int ret_size=0;
+ int ret_size = 0;
- if (p_dst_max_size<16) {
+ if (p_dst_max_size < 16) {
uint8_t dst[16];
- ret_size = fastlz_decompress(p_src,p_src_size,dst,16);
- copymem(p_dst,dst,p_dst_max_size);
+ ret_size = fastlz_decompress(p_src, p_src_size, dst, 16);
+ copymem(p_dst, dst, p_dst_max_size);
} else {
- ret_size = fastlz_decompress(p_src,p_src_size,p_dst,p_dst_max_size);
+ ret_size = fastlz_decompress(p_src, p_src_size, p_dst, p_dst_max_size);
}
return ret_size;
} break;
@@ -133,20 +129,20 @@ int Compression::decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p
strm.zalloc = zipio_alloc;
strm.zfree = zipio_free;
strm.opaque = Z_NULL;
- strm.avail_in= 0;
- strm.next_in=Z_NULL;
+ strm.avail_in = 0;
+ strm.next_in = Z_NULL;
int err = inflateInit(&strm);
- ERR_FAIL_COND_V(err!=Z_OK,-1);
+ ERR_FAIL_COND_V(err != Z_OK, -1);
- strm.avail_in=p_src_size;
- strm.avail_out=p_dst_max_size;
- strm.next_in=(Bytef*)p_src;
- strm.next_out=p_dst;
+ strm.avail_in = p_src_size;
+ strm.avail_out = p_dst_max_size;
+ strm.next_in = (Bytef *)p_src;
+ strm.next_out = p_dst;
- err = inflate(&strm,Z_FINISH);
+ err = inflate(&strm, Z_FINISH);
int total = strm.total_out;
inflateEnd(&strm);
- ERR_FAIL_COND_V(err!=Z_STREAM_END,-1);
+ ERR_FAIL_COND_V(err != Z_STREAM_END, -1);
return total;
} break;
}
diff --git a/core/io/compression.h b/core/io/compression.h
index fc00d02dda..5156919867 100644
--- a/core/io/compression.h
+++ b/core/io/compression.h
@@ -31,23 +31,18 @@
#include "typedefs.h"
-class Compression
-{
+class Compression {
public:
-
enum Mode {
MODE_FASTLZ,
MODE_DEFLATE
};
-
- static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ);
- static int get_max_compressed_buffer_size(int p_src_size,Mode p_mode=MODE_FASTLZ);
- static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size,Mode p_mode=MODE_FASTLZ);
+ static int compress(uint8_t *p_dst, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ);
+ static int get_max_compressed_buffer_size(int p_src_size, Mode p_mode = MODE_FASTLZ);
+ static int decompress(uint8_t *p_dst, int p_dst_max_size, const uint8_t *p_src, int p_src_size, Mode p_mode = MODE_FASTLZ);
Compression();
};
-
-
#endif // COMPRESSION_H
diff --git a/core/io/config_file.cpp b/core/io/config_file.cpp
index fdfcc3ae3a..052a83168d 100644
--- a/core/io/config_file.cpp
+++ b/core/io/config_file.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "config_file.h"
-#include "os/keyboard.h"
#include "os/file_access.h"
+#include "os/keyboard.h"
#include "variant_parser.h"
PoolStringArray ConfigFile::_get_sections() const {
@@ -37,35 +37,33 @@ PoolStringArray ConfigFile::_get_sections() const {
get_sections(&s);
PoolStringArray arr;
arr.resize(s.size());
- int idx=0;
- for(const List<String>::Element *E=s.front();E;E=E->next()) {
+ int idx = 0;
+ for (const List<String>::Element *E = s.front(); E; E = E->next()) {
- arr.set(idx++,E->get());
+ arr.set(idx++, E->get());
}
return arr;
}
-PoolStringArray ConfigFile::_get_section_keys(const String& p_section) const{
+PoolStringArray ConfigFile::_get_section_keys(const String &p_section) const {
List<String> s;
- get_section_keys(p_section,&s);
+ get_section_keys(p_section, &s);
PoolStringArray arr;
arr.resize(s.size());
- int idx=0;
- for(const List<String>::Element *E=s.front();E;E=E->next()) {
+ int idx = 0;
+ for (const List<String>::Element *E = s.front(); E; E = E->next()) {
- arr.set(idx++,E->get());
+ arr.set(idx++, E->get());
}
return arr;
-
}
+void ConfigFile::set_value(const String &p_section, const String &p_key, const Variant &p_value) {
-void ConfigFile::set_value(const String& p_section, const String& p_key, const Variant& p_value){
-
- if (p_value.get_type()==Variant::NIL) {
+ if (p_value.get_type() == Variant::NIL) {
//erase
if (!values.has(p_section))
return; // ?
@@ -76,58 +74,54 @@ void ConfigFile::set_value(const String& p_section, const String& p_key, const V
} else {
if (!values.has(p_section)) {
- values[p_section]=Map<String, Variant>();
+ values[p_section] = Map<String, Variant>();
}
- values[p_section][p_key]=p_value;
-
+ values[p_section][p_key] = p_value;
}
-
}
-Variant ConfigFile::get_value(const String& p_section, const String& p_key, Variant p_default) const {
+Variant ConfigFile::get_value(const String &p_section, const String &p_key, Variant p_default) const {
- ERR_FAIL_COND_V(!values.has(p_section),p_default);
- ERR_FAIL_COND_V(!values[p_section].has(p_key),p_default);
+ ERR_FAIL_COND_V(!values.has(p_section), p_default);
+ ERR_FAIL_COND_V(!values[p_section].has(p_key), p_default);
return values[p_section][p_key];
-
}
-bool ConfigFile::has_section(const String& p_section) const {
+bool ConfigFile::has_section(const String &p_section) const {
return values.has(p_section);
}
-bool ConfigFile::has_section_key(const String& p_section,const String& p_key) const {
+bool ConfigFile::has_section_key(const String &p_section, const String &p_key) const {
if (!values.has(p_section))
return false;
return values[p_section].has(p_key);
}
-void ConfigFile::get_sections(List<String> *r_sections) const{
+void ConfigFile::get_sections(List<String> *r_sections) const {
- for(const Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) {
+ for (const Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) {
r_sections->push_back(E->key());
}
}
-void ConfigFile::get_section_keys(const String& p_section,List<String> *r_keys) const{
+void ConfigFile::get_section_keys(const String &p_section, List<String> *r_keys) const {
ERR_FAIL_COND(!values.has(p_section));
- for(const Map<String, Variant> ::Element *E=values[p_section].front();E;E=E->next()) {
+ for (const Map<String, Variant>::Element *E = values[p_section].front(); E; E = E->next()) {
r_keys->push_back(E->key());
}
-
}
-void ConfigFile::erase_section(const String& p_section) {
+void ConfigFile::erase_section(const String &p_section) {
values.erase(p_section);
}
-Error ConfigFile::save(const String& p_path){
+Error ConfigFile::save(const String &p_path) {
Error err;
- FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
+ FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
if (file)
@@ -135,18 +129,17 @@ Error ConfigFile::save(const String& p_path){
return err;
}
+ for (Map<String, Map<String, Variant> >::Element *E = values.front(); E; E = E->next()) {
- for(Map< String, Map<String, Variant> >::Element *E=values.front();E;E=E->next()) {
-
- if (E!=values.front())
+ if (E != values.front())
file->store_string("\n");
- file->store_string("["+E->key()+"]\n\n");
+ file->store_string("[" + E->key() + "]\n\n");
- for(Map<String, Variant>::Element *F=E->get().front();F;F=F->next()) {
+ for (Map<String, Variant>::Element *F = E->get().front(); F; F = F->next()) {
String vstr;
- VariantWriter::write_to_string(F->get(),vstr);
- file->store_string(F->key()+"="+vstr+"\n");
+ VariantWriter::write_to_string(F->get(), vstr);
+ file->store_string(F->key() + "=" + vstr + "\n");
}
}
@@ -155,48 +148,46 @@ Error ConfigFile::save(const String& p_path){
return OK;
}
-
-Error ConfigFile::load(const String& p_path) {
+Error ConfigFile::load(const String &p_path) {
Error err;
- FileAccess *f= FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
return ERR_CANT_OPEN;
VariantParser::StreamFile stream;
- stream.f=f;
+ stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
- int lines=0;
+ int lines = 0;
String error_text;
String section;
- while(true) {
+ while (true) {
- assign=Variant();
+ assign = Variant();
next_tag.fields.clear();
- next_tag.name=String();
+ next_tag.name = String();
- err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true);
- if (err==ERR_FILE_EOF) {
+ err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
+ if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
- }
- else if (err!=OK) {
- ERR_PRINTS("ConfgFile::load - "+p_path+":"+itos(lines)+" error: "+error_text);
+ } else if (err != OK) {
+ ERR_PRINTS("ConfgFile::load - " + p_path + ":" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
- if (assign!=String()) {
- set_value(section,assign,value);
- } else if (next_tag.name!=String()) {
- section=next_tag.name;
+ if (assign != String()) {
+ set_value(section, assign, value);
+ } else if (next_tag.name != String()) {
+ section = next_tag.name;
}
}
@@ -205,27 +196,22 @@ Error ConfigFile::load(const String& p_path) {
return OK;
}
+void ConfigFile::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_value", "section", "key", "value"), &ConfigFile::set_value);
+ ClassDB::bind_method(D_METHOD("get_value:Variant", "section", "key", "default"), &ConfigFile::get_value, DEFVAL(Variant()));
-void ConfigFile::_bind_methods(){
-
- ClassDB::bind_method(D_METHOD("set_value","section","key","value"),&ConfigFile::set_value);
- ClassDB::bind_method(D_METHOD("get_value:Variant","section","key","default"),&ConfigFile::get_value,DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("has_section", "section"), &ConfigFile::has_section);
+ ClassDB::bind_method(D_METHOD("has_section_key", "section", "key"), &ConfigFile::has_section_key);
- ClassDB::bind_method(D_METHOD("has_section","section"),&ConfigFile::has_section);
- ClassDB::bind_method(D_METHOD("has_section_key","section","key"),&ConfigFile::has_section_key);
+ ClassDB::bind_method(D_METHOD("get_sections"), &ConfigFile::_get_sections);
+ ClassDB::bind_method(D_METHOD("get_section_keys", "section"), &ConfigFile::_get_section_keys);
- ClassDB::bind_method(D_METHOD("get_sections"),&ConfigFile::_get_sections);
- ClassDB::bind_method(D_METHOD("get_section_keys","section"),&ConfigFile::_get_section_keys);
-
- ClassDB::bind_method(D_METHOD("erase_section","section"),&ConfigFile::erase_section);
-
- ClassDB::bind_method(D_METHOD("load:Error","path"),&ConfigFile::load);
- ClassDB::bind_method(D_METHOD("save:Error","path"),&ConfigFile::save);
+ ClassDB::bind_method(D_METHOD("erase_section", "section"), &ConfigFile::erase_section);
+ ClassDB::bind_method(D_METHOD("load:Error", "path"), &ConfigFile::load);
+ ClassDB::bind_method(D_METHOD("save:Error", "path"), &ConfigFile::save);
}
-
-ConfigFile::ConfigFile()
-{
+ConfigFile::ConfigFile() {
}
diff --git a/core/io/config_file.h b/core/io/config_file.h
index c9c4a9fbc0..4d179bd137 100644
--- a/core/io/config_file.h
+++ b/core/io/config_file.h
@@ -31,33 +31,32 @@
#include "reference.h"
-
class ConfigFile : public Reference {
- GDCLASS(ConfigFile,Reference);
+ GDCLASS(ConfigFile, Reference);
- Map< String, Map<String, Variant> > values;
+ Map<String, Map<String, Variant> > values;
PoolStringArray _get_sections() const;
- PoolStringArray _get_section_keys(const String& p_section) const;
-protected:
+ PoolStringArray _get_section_keys(const String &p_section) const;
+protected:
static void _bind_methods();
-public:
- void set_value(const String& p_section, const String& p_key, const Variant& p_value);
- Variant get_value(const String& p_section, const String& p_key, Variant p_default=Variant()) const;
+public:
+ void set_value(const String &p_section, const String &p_key, const Variant &p_value);
+ Variant get_value(const String &p_section, const String &p_key, Variant p_default = Variant()) const;
- bool has_section(const String& p_section) const;
- bool has_section_key(const String& p_section,const String& p_key) const;
+ bool has_section(const String &p_section) const;
+ bool has_section_key(const String &p_section, const String &p_key) const;
void get_sections(List<String> *r_sections) const;
- void get_section_keys(const String& p_section,List<String> *r_keys) const;
+ void get_section_keys(const String &p_section, List<String> *r_keys) const;
- void erase_section(const String& p_section);
+ void erase_section(const String &p_section);
- Error save(const String& p_path);
- Error load(const String& p_path);
+ Error save(const String &p_path);
+ Error load(const String &p_path);
ConfigFile();
};
diff --git a/core/io/file_access_buffered.cpp b/core/io/file_access_buffered.cpp
index 71518de38b..dd4d3e6e8f 100644
--- a/core/io/file_access_buffered.cpp
+++ b/core/io/file_access_buffered.cpp
@@ -92,7 +92,7 @@ bool FileAccessBuffered::eof_reached() const {
uint8_t FileAccessBuffered::get_8() const {
- ERR_FAIL_COND_V(!file.open,0);
+ ERR_FAIL_COND_V(!file.open, 0);
uint8_t byte = 0;
if (cache_data_left() >= 1) {
@@ -105,7 +105,7 @@ uint8_t FileAccessBuffered::get_8() const {
return byte;
};
-int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const {
+int FileAccessBuffered::get_buffer(uint8_t *p_dest, int p_elements) const {
ERR_FAIL_COND_V(!file.open, -1);
@@ -135,7 +135,6 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const {
return total_read;
};
-
int to_read = p_elements;
int total_read = 0;
while (to_read > 0) {
@@ -154,7 +153,7 @@ int FileAccessBuffered::get_buffer(uint8_t *p_dest,int p_elements) const {
int r = MIN(left, to_read);
//PoolVector<uint8_t>::Read read = cache.buffer.read();
//memcpy(p_dest+total_read, &read.ptr()[file.offset - cache.offset], r);
- memcpy(p_dest+total_read, cache.buffer.ptr() + (file.offset - cache.offset), r);
+ memcpy(p_dest + total_read, cache.buffer.ptr() + (file.offset - cache.offset), r);
file.offset += r;
total_read += r;
@@ -179,6 +178,5 @@ FileAccessBuffered::FileAccessBuffered() {
cache_size = DEFAULT_CACHE_SIZE;
};
-FileAccessBuffered::~FileAccessBuffered(){
-
+FileAccessBuffered::~FileAccessBuffered() {
}
diff --git a/core/io/file_access_buffered.h b/core/io/file_access_buffered.h
index be8ea714b1..964152af5e 100644
--- a/core/io/file_access_buffered.h
+++ b/core/io/file_access_buffered.h
@@ -42,14 +42,12 @@ public:
};
private:
-
int cache_size;
int cache_data_left() const;
mutable Error last_error;
protected:
-
Error set_error(Error p_error) const;
mutable struct File {
@@ -67,23 +65,22 @@ protected:
int offset;
} cache;
- virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const =0;
+ virtual int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const = 0;
void set_cache_size(int p_size);
int get_cache_size();
public:
-
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual bool eof_reached() const;
virtual uint8_t get_8() const;
- virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes
+ virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes
virtual bool is_open() const;
@@ -94,4 +91,3 @@ public:
};
#endif
-
diff --git a/core/io/file_access_buffered_fa.h b/core/io/file_access_buffered_fa.h
index 000c2b45f3..dd1e99f8f6 100644
--- a/core/io/file_access_buffered_fa.h
+++ b/core/io/file_access_buffered_fa.h
@@ -31,16 +31,16 @@
#include "core/io/file_access_buffered.h"
-template<class T>
+template <class T>
class FileAccessBufferedFA : public FileAccessBuffered {
T f;
int read_data_block(int p_offset, int p_size, uint8_t *p_dest = 0) const {
- ERR_FAIL_COND_V( !f.is_open(), -1 );
+ ERR_FAIL_COND_V(!f.is_open(), -1);
- ((T*)&f)->seek(p_offset);
+ ((T *)&f)->seek(p_offset);
if (p_dest) {
@@ -63,9 +63,9 @@ class FileAccessBufferedFA : public FileAccessBuffered {
};
};
- static FileAccess* create() {
+ static FileAccess *create() {
- return memnew( FileAccessBufferedFA<T>() );
+ return memnew(FileAccessBufferedFA<T>());
};
protected:
@@ -75,29 +75,27 @@ protected:
};
public:
-
-
void store_8(uint8_t p_dest) {
f.store_8(p_dest);
};
- void store_buffer(const uint8_t *p_src,int p_length) {
+ void store_buffer(const uint8_t *p_src, int p_length) {
f.store_buffer(p_src, p_length);
};
- bool file_exists(const String& p_name) {
+ bool file_exists(const String &p_name) {
return f.file_exists(p_name);
};
- Error _open(const String& p_path, int p_mode_flags) {
+ Error _open(const String &p_path, int p_mode_flags) {
close();
Error ret = f._open(p_path, p_mode_flags);
- if (ret !=OK)
+ if (ret != OK)
return ret;
//ERR_FAIL_COND_V( ret != OK, ret );
@@ -133,16 +131,14 @@ public:
};
*/
- virtual uint64_t _get_modified_time(const String& p_file) {
+ virtual uint64_t _get_modified_time(const String &p_file) {
return f._get_modified_time(p_file);
}
- FileAccessBufferedFA() {
-
+ FileAccessBufferedFA(){
};
};
-
#endif // FILE_ACCESS_BUFFERED_FA_H
diff --git a/core/io/file_access_compressed.cpp b/core/io/file_access_compressed.cpp
index 3bcfade526..d8ae3e6ff1 100644
--- a/core/io/file_access_compressed.cpp
+++ b/core/io/file_access_compressed.cpp
@@ -28,244 +28,223 @@
/*************************************************************************/
#include "file_access_compressed.h"
#include "print_string.h"
-void FileAccessCompressed::configure(const String& p_magic, Compression::Mode p_mode, int p_block_size) {
+void FileAccessCompressed::configure(const String &p_magic, Compression::Mode p_mode, int p_block_size) {
- magic=p_magic.ascii().get_data();
- if (magic.length()>4)
- magic=magic.substr(0,4);
+ magic = p_magic.ascii().get_data();
+ if (magic.length() > 4)
+ magic = magic.substr(0, 4);
else {
- while(magic.length()<4)
- magic+=" ";
+ while (magic.length() < 4)
+ magic += " ";
}
- cmode=p_mode;
- block_size=p_block_size;
-
-}
-
-
-#define WRITE_FIT(m_bytes) \
-{\
-if (write_pos+(m_bytes) > write_max) {\
- write_max=write_pos+(m_bytes);\
-}\
-if (write_max > write_buffer_size) {\
- write_buffer_size = nearest_power_of_2( write_max );\
- buffer.resize(write_buffer_size);\
- write_ptr=buffer.ptr();\
-}\
+ cmode = p_mode;
+ block_size = p_block_size;
}
+#define WRITE_FIT(m_bytes) \
+ { \
+ if (write_pos + (m_bytes) > write_max) { \
+ write_max = write_pos + (m_bytes); \
+ } \
+ if (write_max > write_buffer_size) { \
+ write_buffer_size = nearest_power_of_2(write_max); \
+ buffer.resize(write_buffer_size); \
+ write_ptr = buffer.ptr(); \
+ } \
+ }
Error FileAccessCompressed::open_after_magic(FileAccess *p_base) {
-
- f=p_base;
- cmode=(Compression::Mode)f->get_32();
- block_size=f->get_32();
- read_total=f->get_32();
- int bc = (read_total/block_size)+1;
- int acc_ofs=f->get_pos()+bc*4;
- int max_bs=0;
- for(int i=0;i<bc;i++) {
+ f = p_base;
+ cmode = (Compression::Mode)f->get_32();
+ block_size = f->get_32();
+ read_total = f->get_32();
+ int bc = (read_total / block_size) + 1;
+ int acc_ofs = f->get_pos() + bc * 4;
+ int max_bs = 0;
+ for (int i = 0; i < bc; i++) {
ReadBlock rb;
- rb.offset=acc_ofs;
- rb.csize=f->get_32();
- acc_ofs+=rb.csize;
- max_bs=MAX(max_bs,rb.csize);
+ rb.offset = acc_ofs;
+ rb.csize = f->get_32();
+ acc_ofs += rb.csize;
+ max_bs = MAX(max_bs, rb.csize);
read_blocks.push_back(rb);
-
-
}
comp_buffer.resize(max_bs);
buffer.resize(block_size);
- read_ptr=buffer.ptr();
- f->get_buffer(comp_buffer.ptr(),read_blocks[0].csize);
- at_end=false;
- read_eof=false;
- read_block_count=bc;
- read_block_size=read_blocks.size()==1?read_total:block_size;
+ read_ptr = buffer.ptr();
+ f->get_buffer(comp_buffer.ptr(), read_blocks[0].csize);
+ at_end = false;
+ read_eof = false;
+ read_block_count = bc;
+ read_block_size = read_blocks.size() == 1 ? read_total : block_size;
- Compression::decompress(buffer.ptr(),read_block_size,comp_buffer.ptr(),read_blocks[0].csize,cmode);
- read_block=0;
- read_pos=0;
+ Compression::decompress(buffer.ptr(), read_block_size, comp_buffer.ptr(), read_blocks[0].csize, cmode);
+ read_block = 0;
+ read_pos = 0;
return OK;
-
}
-Error FileAccessCompressed::_open(const String& p_path, int p_mode_flags){
+Error FileAccessCompressed::_open(const String &p_path, int p_mode_flags) {
- ERR_FAIL_COND_V(p_mode_flags==READ_WRITE,ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(p_mode_flags == READ_WRITE, ERR_UNAVAILABLE);
if (f)
close();
-
Error err;
- f = FileAccess::open(p_path,p_mode_flags,&err);
- if (err!=OK) {
+ f = FileAccess::open(p_path, p_mode_flags, &err);
+ if (err != OK) {
//not openable
- f=NULL;
+ f = NULL;
return err;
}
- if (p_mode_flags&WRITE) {
+ if (p_mode_flags & WRITE) {
buffer.clear();
- writing=true;
- write_pos=0;
- write_buffer_size=256;
+ writing = true;
+ write_pos = 0;
+ write_buffer_size = 256;
buffer.resize(256);
- write_max=0;
- write_ptr=buffer.ptr();
-
-
+ write_max = 0;
+ write_ptr = buffer.ptr();
//don't store anything else unless it's done saving!
} else {
char rmagic[5];
- f->get_buffer((uint8_t*)rmagic,4);
- rmagic[4]=0;
- if (magic!=rmagic) {
+ f->get_buffer((uint8_t *)rmagic, 4);
+ rmagic[4] = 0;
+ if (magic != rmagic) {
memdelete(f);
- f=NULL;
+ f = NULL;
return ERR_FILE_UNRECOGNIZED;
}
open_after_magic(f);
-
}
return OK;
-
}
-void FileAccessCompressed::close(){
+void FileAccessCompressed::close() {
if (!f)
return;
-
if (writing) {
//save block table and all compressed blocks
CharString mgc = magic.utf8();
- f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //write header 4
+ f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //write header 4
f->store_32(cmode); //write compression mode 4
f->store_32(block_size); //write block size 4
f->store_32(write_max); //max amount of data written 4
- int bc=(write_max/block_size)+1;
+ int bc = (write_max / block_size) + 1;
- for(int i=0;i<bc;i++) {
+ for (int i = 0; i < bc; i++) {
f->store_32(0); //compressed sizes, will update later
}
-
Vector<int> block_sizes;
- for(int i=0;i<bc;i++) {
+ for (int i = 0; i < bc; i++) {
- int bl = i==(bc-1) ? write_max % block_size : block_size;
- uint8_t *bp = &write_ptr[i*block_size];
+ int bl = i == (bc - 1) ? write_max % block_size : block_size;
+ uint8_t *bp = &write_ptr[i * block_size];
Vector<uint8_t> cblock;
- cblock.resize(Compression::get_max_compressed_buffer_size(bl,cmode));
- int s = Compression::compress(cblock.ptr(),bp,bl,cmode);
+ cblock.resize(Compression::get_max_compressed_buffer_size(bl, cmode));
+ int s = Compression::compress(cblock.ptr(), bp, bl, cmode);
- f->store_buffer(cblock.ptr(),s);
+ f->store_buffer(cblock.ptr(), s);
block_sizes.push_back(s);
}
f->seek(16); //ok write block sizes
- for(int i=0;i<bc;i++)
+ for (int i = 0; i < bc; i++)
f->store_32(block_sizes[i]);
f->seek_end();
- f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //magic at the end too
+ f->store_buffer((const uint8_t *)mgc.get_data(), mgc.length()); //magic at the end too
buffer.clear();
} else {
-
comp_buffer.clear();
buffer.clear();
read_blocks.clear();
}
memdelete(f);
- f=NULL;
-
+ f = NULL;
}
-bool FileAccessCompressed::is_open() const{
+bool FileAccessCompressed::is_open() const {
- return f!=NULL;
+ return f != NULL;
}
-void FileAccessCompressed::seek(size_t p_position){
+void FileAccessCompressed::seek(size_t p_position) {
ERR_FAIL_COND(!f);
if (writing) {
- ERR_FAIL_COND(p_position>write_max);
+ ERR_FAIL_COND(p_position > write_max);
- write_pos=p_position;
+ write_pos = p_position;
} else {
- ERR_FAIL_COND(p_position>read_total);
- if (p_position==read_total) {
- at_end=true;
+ ERR_FAIL_COND(p_position > read_total);
+ if (p_position == read_total) {
+ at_end = true;
} else {
- int block_idx = p_position/block_size;
- if (block_idx!=read_block) {
+ int block_idx = p_position / block_size;
+ if (block_idx != read_block) {
- read_block=block_idx;
+ read_block = block_idx;
f->seek(read_blocks[read_block].offset);
- f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize);
- Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode);
- read_block_size=read_block==read_block_count-1?read_total%block_size:block_size;
+ f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize);
+ Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
+ read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
}
- read_pos=p_position%block_size;
+ read_pos = p_position % block_size;
}
}
}
-
-void FileAccessCompressed::seek_end(int64_t p_position){
+void FileAccessCompressed::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
if (writing) {
- seek(write_max+p_position);
+ seek(write_max + p_position);
} else {
- seek(read_total+p_position);
-
+ seek(read_total + p_position);
}
-
-
}
-size_t FileAccessCompressed::get_pos() const{
+size_t FileAccessCompressed::get_pos() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
if (writing) {
return write_pos;
} else {
- return read_block*block_size+read_pos;
+ return read_block * block_size + read_pos;
}
-
}
-size_t FileAccessCompressed::get_len() const{
+size_t FileAccessCompressed::get_len() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
if (writing) {
return write_max;
@@ -274,9 +253,9 @@ size_t FileAccessCompressed::get_len() const{
}
}
-bool FileAccessCompressed::eof_reached() const{
+bool FileAccessCompressed::eof_reached() const {
- ERR_FAIL_COND_V(!f,false);
+ ERR_FAIL_COND_V(!f, false);
if (writing) {
return false;
} else {
@@ -284,106 +263,99 @@ bool FileAccessCompressed::eof_reached() const{
}
}
-uint8_t FileAccessCompressed::get_8() const{
+uint8_t FileAccessCompressed::get_8() const {
- ERR_FAIL_COND_V(writing,0);
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(writing, 0);
+ ERR_FAIL_COND_V(!f, 0);
if (at_end) {
- read_eof=true;
+ read_eof = true;
return 0;
}
uint8_t ret = read_ptr[read_pos];
read_pos++;
- if (read_pos>=read_block_size) {
+ if (read_pos >= read_block_size) {
read_block++;
- if (read_block<read_block_count) {
+ if (read_block < read_block_count) {
//read another block of compressed data
- f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize);
- Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode);
- read_block_size=read_block==read_block_count-1?read_total%block_size:block_size;
- read_pos=0;
+ f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize);
+ Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
+ read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
+ read_pos = 0;
} else {
read_block--;
- at_end=true;
- ret =0;
+ at_end = true;
+ ret = 0;
}
}
return ret;
-
}
-int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const{
+int FileAccessCompressed::get_buffer(uint8_t *p_dst, int p_length) const {
- ERR_FAIL_COND_V(writing,0);
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(writing, 0);
+ ERR_FAIL_COND_V(!f, 0);
if (at_end) {
- read_eof=true;
+ read_eof = true;
return 0;
}
+ for (int i = 0; i < p_length; i++) {
- for(int i=0;i<p_length;i++) {
-
-
- p_dst[i]=read_ptr[read_pos];
+ p_dst[i] = read_ptr[read_pos];
read_pos++;
- if (read_pos>=read_block_size) {
+ if (read_pos >= read_block_size) {
read_block++;
- if (read_block<read_block_count) {
+ if (read_block < read_block_count) {
//read another block of compressed data
- f->get_buffer(comp_buffer.ptr(),read_blocks[read_block].csize);
- Compression::decompress(buffer.ptr(),read_blocks.size()==1?read_total:block_size,comp_buffer.ptr(),read_blocks[read_block].csize,cmode);
- read_block_size=read_block==read_block_count-1?read_total%block_size:block_size;
- read_pos=0;
+ f->get_buffer(comp_buffer.ptr(), read_blocks[read_block].csize);
+ Compression::decompress(buffer.ptr(), read_blocks.size() == 1 ? read_total : block_size, comp_buffer.ptr(), read_blocks[read_block].csize, cmode);
+ read_block_size = read_block == read_block_count - 1 ? read_total % block_size : block_size;
+ read_pos = 0;
} else {
read_block--;
- at_end=true;
- if (i<p_length-1)
- read_eof=true;
+ at_end = true;
+ if (i < p_length - 1)
+ read_eof = true;
return i;
-
}
}
-
}
return p_length;
-
}
-Error FileAccessCompressed::get_error() const{
+Error FileAccessCompressed::get_error() const {
- return read_eof?ERR_FILE_EOF:OK;
+ return read_eof ? ERR_FILE_EOF : OK;
}
-void FileAccessCompressed::store_8(uint8_t p_dest){
+void FileAccessCompressed::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
ERR_FAIL_COND(!writing);
WRITE_FIT(1);
- write_ptr[write_pos++]=p_dest;
-
+ write_ptr[write_pos++] = p_dest;
}
-bool FileAccessCompressed::file_exists(const String& p_name){
+bool FileAccessCompressed::file_exists(const String &p_name) {
- FileAccess *fa = FileAccess::open(p_name,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(p_name, FileAccess::READ);
if (!fa)
return false;
memdelete(fa);
return true;
}
-uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) {
+uint64_t FileAccessCompressed::_get_modified_time(const String &p_file) {
if (f)
return f->get_modified_time(p_file);
@@ -393,29 +365,27 @@ uint64_t FileAccessCompressed::_get_modified_time(const String& p_file) {
FileAccessCompressed::FileAccessCompressed() {
- f=NULL;
- magic="GCMP";
- block_size=16384;
- cmode=Compression::MODE_DEFLATE;
- writing=false;
- write_ptr=0;
- write_buffer_size=0;
- write_max=0;
- block_size=0;
- read_eof=false;
- at_end=false;
- read_total=0;
- read_ptr=NULL;
- read_block=0;
- read_block_count=0;
- read_block_size=0;
- read_pos=0;
-
+ f = NULL;
+ magic = "GCMP";
+ block_size = 16384;
+ cmode = Compression::MODE_DEFLATE;
+ writing = false;
+ write_ptr = 0;
+ write_buffer_size = 0;
+ write_max = 0;
+ block_size = 0;
+ read_eof = false;
+ at_end = false;
+ read_total = 0;
+ read_ptr = NULL;
+ read_block = 0;
+ read_block_count = 0;
+ read_block_size = 0;
+ read_pos = 0;
}
-FileAccessCompressed::~FileAccessCompressed(){
+FileAccessCompressed::~FileAccessCompressed() {
if (f)
close();
-
}
diff --git a/core/io/file_access_compressed.h b/core/io/file_access_compressed.h
index 70034120f9..ea45c110d2 100644
--- a/core/io/file_access_compressed.h
+++ b/core/io/file_access_compressed.h
@@ -37,7 +37,7 @@ class FileAccessCompressed : public FileAccess {
Compression::Mode cmode;
bool writing;
int write_pos;
- uint8_t*write_ptr;
+ uint8_t *write_ptr;
int write_buffer_size;
int write_max;
int block_size;
@@ -58,24 +58,21 @@ class FileAccessCompressed : public FileAccess {
Vector<ReadBlock> read_blocks;
int read_total;
-
-
-
String magic;
mutable Vector<uint8_t> buffer;
FileAccess *f;
-public:
- void configure(const String& p_magic, Compression::Mode p_mode=Compression::MODE_FASTLZ, int p_block_size=4096);
+public:
+ void configure(const String &p_magic, Compression::Mode p_mode = Compression::MODE_FASTLZ, int p_block_size = 4096);
Error open_after_magic(FileAccess *p_base);
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -88,14 +85,12 @@ public:
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_name); ///< return true if a file exists
-
- virtual uint64_t _get_modified_time(const String& p_file);
+ virtual bool file_exists(const String &p_name); ///< return true if a file exists
+ virtual uint64_t _get_modified_time(const String &p_file);
FileAccessCompressed();
virtual ~FileAccessCompressed();
-
};
#endif // FILE_ACCESS_COMPRESSED_H
diff --git a/core/io/file_access_encrypted.cpp b/core/io/file_access_encrypted.cpp
index 039458237d..03700cad48 100644
--- a/core/io/file_access_encrypted.cpp
+++ b/core/io/file_access_encrypted.cpp
@@ -36,55 +36,55 @@
#include "core/variant.h"
#include <stdio.h>
-Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode) {
+Error FileAccessEncrypted::open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode) {
//print_line("open and parse!");
- ERR_FAIL_COND_V(file!=NULL,ERR_ALREADY_IN_USE);
- ERR_FAIL_COND_V(p_key.size()!=32,ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(file != NULL, ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(p_key.size() != 32, ERR_INVALID_PARAMETER);
- pos=0;
- eofed=false;
+ pos = 0;
+ eofed = false;
- if (p_mode==MODE_WRITE_AES256) {
+ if (p_mode == MODE_WRITE_AES256) {
data.clear();
- writing=true;
- file=p_base;
- mode=p_mode;
- key=p_key;
+ writing = true;
+ file = p_base;
+ mode = p_mode;
+ key = p_key;
- } else if (p_mode==MODE_READ) {
+ } else if (p_mode == MODE_READ) {
- writing=false;
- key=p_key;
+ writing = false;
+ key = p_key;
uint32_t magic = p_base->get_32();
- print_line("MAGIC: "+itos(magic));
- ERR_FAIL_COND_V(magic!=COMP_MAGIC,ERR_FILE_UNRECOGNIZED);
- mode=Mode(p_base->get_32());
- ERR_FAIL_INDEX_V(mode,MODE_MAX,ERR_FILE_CORRUPT);
- ERR_FAIL_COND_V(mode==0,ERR_FILE_CORRUPT);
- print_line("MODE: "+itos(mode));
+ print_line("MAGIC: " + itos(magic));
+ ERR_FAIL_COND_V(magic != COMP_MAGIC, ERR_FILE_UNRECOGNIZED);
+ mode = Mode(p_base->get_32());
+ ERR_FAIL_INDEX_V(mode, MODE_MAX, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(mode == 0, ERR_FILE_CORRUPT);
+ print_line("MODE: " + itos(mode));
unsigned char md5d[16];
- p_base->get_buffer(md5d,16);
- length=p_base->get_64();
- base=p_base->get_pos();
- ERR_FAIL_COND_V(p_base->get_len() < base+length, ERR_FILE_CORRUPT );
+ p_base->get_buffer(md5d, 16);
+ length = p_base->get_64();
+ base = p_base->get_pos();
+ ERR_FAIL_COND_V(p_base->get_len() < base + length, ERR_FILE_CORRUPT);
int ds = length;
if (ds % 16) {
- ds+=16-(ds % 16);
+ ds += 16 - (ds % 16);
}
data.resize(ds);
- int blen = p_base->get_buffer(data.ptr(),ds);
- ERR_FAIL_COND_V(blen!=ds,ERR_FILE_CORRUPT);
+ int blen = p_base->get_buffer(data.ptr(), ds);
+ ERR_FAIL_COND_V(blen != ds, ERR_FILE_CORRUPT);
aes256_context ctx;
- aes256_init(&ctx,key.ptr());
+ aes256_init(&ctx, key.ptr());
- for(size_t i=0;i<ds;i+=16) {
+ for (size_t i = 0; i < ds; i += 16) {
- aes256_decrypt_ecb(&ctx,&data[i]);
+ aes256_decrypt_ecb(&ctx, &data[i]);
}
aes256_done(&ctx);
@@ -93,37 +93,32 @@ Error FileAccessEncrypted::open_and_parse(FileAccess *p_base,const Vector<uint8_
MD5_CTX md5;
MD5Init(&md5);
- MD5Update(&md5,data.ptr(),data.size());
+ MD5Update(&md5, data.ptr(), data.size());
MD5Final(&md5);
+ ERR_FAIL_COND_V(String::md5(md5.digest) != String::md5(md5d), ERR_FILE_CORRUPT);
- ERR_FAIL_COND_V(String::md5(md5.digest)!=String::md5(md5d),ERR_FILE_CORRUPT) ;
-
-
- file=p_base;
+ file = p_base;
}
return OK;
}
-Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode){
-
+Error FileAccessEncrypted::open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode) {
String cs = p_key.md5_text();
- ERR_FAIL_COND_V(cs.length()!=32,ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(cs.length() != 32, ERR_INVALID_PARAMETER);
Vector<uint8_t> key;
key.resize(32);
- for(int i=0;i<32;i++) {
+ for (int i = 0; i < 32; i++) {
- key[i]=cs[i];
+ key[i] = cs[i];
}
- return open_and_parse(p_base,key,p_mode);
+ return open_and_parse(p_base, key, p_mode);
}
-
-
-Error FileAccessEncrypted::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessEncrypted::_open(const String &p_path, int p_mode_flags) {
return OK;
}
@@ -137,26 +132,26 @@ void FileAccessEncrypted::close() {
Vector<uint8_t> compressed;
size_t len = data.size();
if (len % 16) {
- len+=16-(len % 16);
+ len += 16 - (len % 16);
}
MD5_CTX md5;
MD5Init(&md5);
- MD5Update(&md5,data.ptr(),data.size());
+ MD5Update(&md5, data.ptr(), data.size());
MD5Final(&md5);
compressed.resize(len);
- zeromem( compressed.ptr(), len );
- for(int i=0;i<data.size();i++) {
- compressed[i]=data[i];
+ zeromem(compressed.ptr(), len);
+ for (int i = 0; i < data.size(); i++) {
+ compressed[i] = data[i];
}
aes256_context ctx;
- aes256_init(&ctx,key.ptr());
+ aes256_init(&ctx, key.ptr());
- for(size_t i=0;i<len;i+=16) {
+ for (size_t i = 0; i < len; i += 16) {
- aes256_encrypt_ecb(&ctx,&compressed[i]);
+ aes256_encrypt_ecb(&ctx, &compressed[i]);
}
aes256_done(&ctx);
@@ -164,14 +159,13 @@ void FileAccessEncrypted::close() {
file->store_32(COMP_MAGIC);
file->store_32(mode);
-
- file->store_buffer(md5.digest,16);
+ file->store_buffer(md5.digest, 16);
file->store_64(data.size());
- file->store_buffer(compressed.ptr(),compressed.size());
+ file->store_buffer(compressed.ptr(), compressed.size());
file->close();
memdelete(file);
- file=NULL;
+ file = NULL;
data.clear();
} else {
@@ -179,143 +173,133 @@ void FileAccessEncrypted::close() {
file->close();
memdelete(file);
data.clear();
- file=NULL;
+ file = NULL;
}
-
-
-
}
-bool FileAccessEncrypted::is_open() const{
+bool FileAccessEncrypted::is_open() const {
- return file!=NULL;
+ return file != NULL;
}
-void FileAccessEncrypted::seek(size_t p_position){
+void FileAccessEncrypted::seek(size_t p_position) {
if (p_position > (size_t)data.size())
- p_position=data.size();
-
- pos=p_position;
- eofed=false;
+ p_position = data.size();
+ pos = p_position;
+ eofed = false;
}
+void FileAccessEncrypted::seek_end(int64_t p_position) {
-void FileAccessEncrypted::seek_end(int64_t p_position){
-
- seek( data.size() + p_position );
+ seek(data.size() + p_position);
}
-size_t FileAccessEncrypted::get_pos() const{
+size_t FileAccessEncrypted::get_pos() const {
return pos;
}
-size_t FileAccessEncrypted::get_len() const{
+size_t FileAccessEncrypted::get_len() const {
return data.size();
}
-bool FileAccessEncrypted::eof_reached() const{
+bool FileAccessEncrypted::eof_reached() const {
return eofed;
}
-uint8_t FileAccessEncrypted::get_8() const{
+uint8_t FileAccessEncrypted::get_8() const {
- ERR_FAIL_COND_V(writing,0);
- if (pos>=data.size()) {
- eofed=true;
+ ERR_FAIL_COND_V(writing, 0);
+ if (pos >= data.size()) {
+ eofed = true;
return 0;
}
uint8_t b = data[pos];
pos++;
return b;
-
}
-int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const{
+int FileAccessEncrypted::get_buffer(uint8_t *p_dst, int p_length) const {
- ERR_FAIL_COND_V(writing,0);
+ ERR_FAIL_COND_V(writing, 0);
- int to_copy=MIN(p_length,data.size()-pos);
- for(int i=0;i<to_copy;i++) {
+ int to_copy = MIN(p_length, data.size() - pos);
+ for (int i = 0; i < to_copy; i++) {
- p_dst[i]=data[pos++];
+ p_dst[i] = data[pos++];
}
- if (to_copy<p_length) {
- eofed=true;
+ if (to_copy < p_length) {
+ eofed = true;
}
-
return to_copy;
}
-Error FileAccessEncrypted::get_error() const{
+Error FileAccessEncrypted::get_error() const {
- return eofed?ERR_FILE_EOF:OK;
+ return eofed ? ERR_FILE_EOF : OK;
}
-void FileAccessEncrypted::store_buffer(const uint8_t *p_src,int p_length) {
+void FileAccessEncrypted::store_buffer(const uint8_t *p_src, int p_length) {
ERR_FAIL_COND(!writing);
- if (pos<data.size()) {
+ if (pos < data.size()) {
- for(int i=0;i<p_length;i++) {
+ for (int i = 0; i < p_length; i++) {
store_8(p_src[i]);
}
- } else if (pos==data.size()) {
+ } else if (pos == data.size()) {
- data.resize(pos+p_length);
- for(int i=0;i<p_length;i++) {
+ data.resize(pos + p_length);
+ for (int i = 0; i < p_length; i++) {
- data[pos+i]=p_src[i];
+ data[pos + i] = p_src[i];
}
- pos+=p_length;
+ pos += p_length;
}
}
-
-void FileAccessEncrypted::store_8(uint8_t p_dest){
+void FileAccessEncrypted::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!writing);
- if (pos<data.size()) {
- data[pos]=p_dest;
+ if (pos < data.size()) {
+ data[pos] = p_dest;
pos++;
- } else if (pos==data.size()){
+ } else if (pos == data.size()) {
data.push_back(p_dest);
pos++;
}
}
-bool FileAccessEncrypted::file_exists(const String& p_name){
+bool FileAccessEncrypted::file_exists(const String &p_name) {
- FileAccess *fa = FileAccess::open(p_name,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(p_name, FileAccess::READ);
if (!fa)
return false;
memdelete(fa);
return true;
}
-uint64_t FileAccessEncrypted::_get_modified_time(const String& p_file){
-
+uint64_t FileAccessEncrypted::_get_modified_time(const String &p_file) {
return 0;
}
FileAccessEncrypted::FileAccessEncrypted() {
- file=NULL;
- pos=0;
- eofed=false;
- mode=MODE_MAX;
- writing=false;
+ file = NULL;
+ pos = 0;
+ eofed = false;
+ mode = MODE_MAX;
+ writing = false;
}
-
FileAccessEncrypted::~FileAccessEncrypted() {
if (file)
diff --git a/core/io/file_access_encrypted.h b/core/io/file_access_encrypted.h
index 51ed9a8677..ac4d2bd1c7 100644
--- a/core/io/file_access_encrypted.h
+++ b/core/io/file_access_encrypted.h
@@ -29,12 +29,10 @@
#ifndef FILE_ACCESS_ENCRYPTED_H
#define FILE_ACCESS_ENCRYPTED_H
-
#include "os/file_access.h"
class FileAccessEncrypted : public FileAccess {
public:
-
enum Mode {
MODE_READ,
MODE_WRITE_AES256,
@@ -42,8 +40,6 @@ public:
};
private:
-
-
Mode mode;
Vector<uint8_t> key;
bool writing;
@@ -54,21 +50,16 @@ private:
mutable size_t pos;
mutable bool eofed;
-
public:
+ Error open_and_parse(FileAccess *p_base, const Vector<uint8_t> &p_key, Mode p_mode);
+ Error open_and_parse_password(FileAccess *p_base, const String &p_key, Mode p_mode);
-
-
-
- Error open_and_parse(FileAccess *p_base,const Vector<uint8_t>& p_key,Mode p_mode);
- Error open_and_parse_password(FileAccess *p_base,const String& p_key,Mode p_mode);
-
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -80,11 +71,11 @@ public:
virtual Error get_error() const; ///< get last error
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes
+ virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes
- virtual bool file_exists(const String& p_name); ///< return true if a file exists
+ virtual bool file_exists(const String &p_name); ///< return true if a file exists
- virtual uint64_t _get_modified_time(const String& p_file);
+ virtual uint64_t _get_modified_time(const String &p_file);
FileAccessEncrypted();
~FileAccessEncrypted();
diff --git a/core/io/file_access_memory.cpp b/core/io/file_access_memory.cpp
index b4ba14ddc9..966109bfe1 100644
--- a/core/io/file_access_memory.cpp
+++ b/core/io/file_access_memory.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "file_access_memory.h"
-#include "os/dir_access.h"
-#include "os/copymem.h"
#include "global_config.h"
#include "map.h"
+#include "os/copymem.h"
+#include "os/dir_access.h"
-static Map<String, Vector<uint8_t> >* files = NULL;
+static Map<String, Vector<uint8_t> > *files = NULL;
void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) {
@@ -59,13 +59,12 @@ void FileAccessMemory::cleanup() {
memdelete(files);
}
-
-FileAccess* FileAccessMemory::create() {
+FileAccess *FileAccessMemory::create() {
return memnew(FileAccessMemory);
}
-bool FileAccessMemory::file_exists(const String& p_name) {
+bool FileAccessMemory::file_exists(const String &p_name) {
String name = fix_path(p_name);
//name = DirAccess::normalize_path(name);
@@ -73,23 +72,22 @@ bool FileAccessMemory::file_exists(const String& p_name) {
return files && (files->find(name) != NULL);
}
+Error FileAccessMemory::open_custom(const uint8_t *p_data, int p_len) {
-Error FileAccessMemory::open_custom(const uint8_t* p_data, int p_len) {
-
- data=(uint8_t*)p_data;
- length=p_len;
- pos=0;
+ data = (uint8_t *)p_data;
+ length = p_len;
+ pos = 0;
return OK;
}
-Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessMemory::_open(const String &p_path, int p_mode_flags) {
ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND);
String name = fix_path(p_path);
//name = DirAccess::normalize_path(name);
- Map<String, Vector<uint8_t> >::Element* E = files->find(name);
+ Map<String, Vector<uint8_t> >::Element *E = files->find(name);
ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND);
data = &(E->get()[0]);
@@ -149,7 +147,7 @@ uint8_t FileAccessMemory::get_8() const {
return ret;
}
-int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const {
+int FileAccessMemory::get_buffer(uint8_t *p_dst, int p_length) const {
ERR_FAIL_COND_V(!data, -1);
@@ -178,7 +176,7 @@ void FileAccessMemory::store_8(uint8_t p_byte) {
data[pos++] = p_byte;
}
-void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) {
+void FileAccessMemory::store_buffer(const uint8_t *p_src, int p_length) {
int left = length - pos;
int write = MIN(p_length, left);
diff --git a/core/io/file_access_memory.h b/core/io/file_access_memory.h
index c6dda07971..687e3e9bee 100644
--- a/core/io/file_access_memory.h
+++ b/core/io/file_access_memory.h
@@ -33,19 +33,18 @@
class FileAccessMemory : public FileAccess {
- uint8_t* data;
+ uint8_t *data;
int length;
mutable int pos;
- static FileAccess* create();
+ static FileAccess *create();
public:
-
static void register_file(String p_name, Vector<uint8_t> p_data);
static void cleanup();
- virtual Error open_custom(const uint8_t* p_data, int p_len); ///< open a file
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error open_custom(const uint8_t *p_data, int p_len); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
@@ -58,18 +57,16 @@ public:
virtual uint8_t get_8() const; ///< get a byte
- virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes
+ virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes
virtual Error get_error() const; ///< get last error
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes
-
- virtual bool file_exists(const String& p_name); ///< return true if a file exists
-
- virtual uint64_t _get_modified_time(const String& p_file) { return 0; }
+ virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes
+ virtual bool file_exists(const String &p_name); ///< return true if a file exists
+ virtual uint64_t _get_modified_time(const String &p_file) { return 0; }
FileAccessMemory();
};
diff --git a/core/io/file_access_network.cpp b/core/io/file_access_network.cpp
index d9fdc9cedc..9120b55565 100644
--- a/core/io/file_access_network.cpp
+++ b/core/io/file_access_network.cpp
@@ -27,19 +27,16 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "file_access_network.h"
-#include "marshalls.h"
#include "global_config.h"
-#include "os/os.h"
#include "io/ip.h"
-
-
+#include "marshalls.h"
+#include "os/os.h"
//#define DEBUG_PRINT(m_p) print_line(m_p)
//#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n",m_what,OS::get_singleton()->get_ticks_usec());
#define DEBUG_PRINT(m_p)
#define DEBUG_TIME(m_what)
-
void FileAccessNetworkClient::lock_mutex() {
mutex->lock();
@@ -50,59 +47,55 @@ void FileAccessNetworkClient::unlock_mutex() {
lockcount--;
mutex->unlock();
-
}
void FileAccessNetworkClient::put_32(int p_32) {
uint8_t buf[4];
- encode_uint32(p_32,buf);
- client->put_data(buf,4);
- DEBUG_PRINT("put32: "+itos(p_32));
+ encode_uint32(p_32, buf);
+ client->put_data(buf, 4);
+ DEBUG_PRINT("put32: " + itos(p_32));
}
void FileAccessNetworkClient::put_64(int64_t p_64) {
uint8_t buf[8];
- encode_uint64(p_64,buf);
- client->put_data(buf,8);
- DEBUG_PRINT("put64: "+itos(p_64));
-
+ encode_uint64(p_64, buf);
+ client->put_data(buf, 8);
+ DEBUG_PRINT("put64: " + itos(p_64));
}
int FileAccessNetworkClient::get_32() {
uint8_t buf[4];
- client->get_data(buf,4);
+ client->get_data(buf, 4);
return decode_uint32(buf);
-
}
int64_t FileAccessNetworkClient::get_64() {
uint8_t buf[8];
- client->get_data(buf,8);
+ client->get_data(buf, 8);
return decode_uint64(buf);
-
}
void FileAccessNetworkClient::_thread_func() {
client->set_nodelay(true);
- while(!quit) {
+ while (!quit) {
- DEBUG_PRINT("SEM WAIT - "+itos(sem->get()));
+ DEBUG_PRINT("SEM WAIT - " + itos(sem->get()));
Error err = sem->wait();
DEBUG_TIME("sem_unlock");
//DEBUG_PRINT("semwait returned "+itos(werr));
- DEBUG_PRINT("MUTEX LOCK "+itos(lockcount));
+ DEBUG_PRINT("MUTEX LOCK " + itos(lockcount));
DEBUG_PRINT("POPO");
DEBUG_PRINT("PEPE");
lock_mutex();
DEBUG_PRINT("MUTEX PASS");
blockrequest_mutex->lock();
- while(block_requests.size()) {
+ while (block_requests.size()) {
put_32(block_requests.front()->get().id);
put_32(FileAccessNetwork::COMMAND_READ_BLOCK);
put_64(block_requests.front()->get().offset);
@@ -117,35 +110,32 @@ void FileAccessNetworkClient::_thread_func() {
int id = get_32();
int response = get_32();
- DEBUG_PRINT("GET RESPONSE: "+itos(response));
+ DEBUG_PRINT("GET RESPONSE: " + itos(response));
- FileAccessNetwork *fa=NULL;
+ FileAccessNetwork *fa = NULL;
- if (response!=FileAccessNetwork::RESPONSE_DATA) {
+ if (response != FileAccessNetwork::RESPONSE_DATA) {
ERR_FAIL_COND(!accesses.has(id));
}
if (accesses.has(id))
- fa=accesses[id];
+ fa = accesses[id];
-
- switch(response) {
+ switch (response) {
case FileAccessNetwork::RESPONSE_OPEN: {
-
DEBUG_TIME("sem_open");
int status = get_32();
- if (status!=OK) {
- fa->_respond(0,Error(status));
+ if (status != OK) {
+ fa->_respond(0, Error(status));
} else {
uint64_t len = get_64();
- fa->_respond(len,Error(status));
+ fa->_respond(len, Error(status));
}
fa->sem->post();
-
} break;
case FileAccessNetwork::RESPONSE_DATA: {
@@ -154,104 +144,95 @@ void FileAccessNetworkClient::_thread_func() {
Vector<uint8_t> block;
block.resize(len);
- client->get_data(block.ptr(),len);
+ client->get_data(block.ptr(), len);
if (fa) //may have been queued
- fa->_set_block(offset,block);
+ fa->_set_block(offset, block);
} break;
case FileAccessNetwork::RESPONSE_FILE_EXISTS: {
-
int status = get_32();
- fa->exists_modtime=status!=0;
+ fa->exists_modtime = status != 0;
fa->sem->post();
-
-
} break;
case FileAccessNetwork::RESPONSE_GET_MODTIME: {
-
uint64_t status = get_64();
- fa->exists_modtime=status;
+ fa->exists_modtime = status;
fa->sem->post();
} break;
-
}
-
unlock_mutex();
}
-
}
void FileAccessNetworkClient::_thread_func(void *s) {
- FileAccessNetworkClient *self =(FileAccessNetworkClient*)s;
+ FileAccessNetworkClient *self = (FileAccessNetworkClient *)s;
self->_thread_func();
-
}
-Error FileAccessNetworkClient::connect(const String& p_host,int p_port,const String& p_password) {
+Error FileAccessNetworkClient::connect(const String &p_host, int p_port, const String &p_password) {
IP_Address ip;
if (p_host.is_valid_ip_address()) {
- ip=p_host;
+ ip = p_host;
} else {
- ip=IP::get_singleton()->resolve_hostname(p_host);
+ ip = IP::get_singleton()->resolve_hostname(p_host);
}
- DEBUG_PRINT("IP: "+String(ip)+" port "+itos(p_port));
- Error err = client->connect_to_host(ip,p_port);
- ERR_FAIL_COND_V(err,err);
- while(client->get_status()==StreamPeerTCP::STATUS_CONNECTING) {
-//DEBUG_PRINT("trying to connect....");
+ DEBUG_PRINT("IP: " + String(ip) + " port " + itos(p_port));
+ Error err = client->connect_to_host(ip, p_port);
+ ERR_FAIL_COND_V(err, err);
+ while (client->get_status() == StreamPeerTCP::STATUS_CONNECTING) {
+ //DEBUG_PRINT("trying to connect....");
OS::get_singleton()->delay_usec(1000);
}
- if (client->get_status()!=StreamPeerTCP::STATUS_CONNECTED) {
+ if (client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
return ERR_CANT_CONNECT;
}
CharString cs = p_password.utf8();
put_32(cs.length());
- client->put_data((const uint8_t*)cs.ptr(),cs.length());
+ client->put_data((const uint8_t *)cs.ptr(), cs.length());
int e = get_32();
- if (e!=OK) {
+ if (e != OK) {
return ERR_INVALID_PARAMETER;
}
- thread = Thread::create(_thread_func,this);
+ thread = Thread::create(_thread_func, this);
return OK;
}
-FileAccessNetworkClient *FileAccessNetworkClient::singleton=NULL;
-
+FileAccessNetworkClient *FileAccessNetworkClient::singleton = NULL;
FileAccessNetworkClient::FileAccessNetworkClient() {
- thread=NULL;
+ thread = NULL;
mutex = Mutex::create();
blockrequest_mutex = Mutex::create();
- quit=false;
- singleton=this;
- last_id=0;
- client = Ref<StreamPeerTCP>( StreamPeerTCP::create_ref() );
- sem=Semaphore::create();
- lockcount=0;
+ quit = false;
+ singleton = this;
+ last_id = 0;
+ client = Ref<StreamPeerTCP>(StreamPeerTCP::create_ref());
+ sem = Semaphore::create();
+ lockcount = 0;
}
FileAccessNetworkClient::~FileAccessNetworkClient() {
if (thread) {
- quit=true;
+ quit = true;
sem->post();
Thread::wait_to_finish(thread);
memdelete(thread);
@@ -260,70 +241,62 @@ FileAccessNetworkClient::~FileAccessNetworkClient() {
memdelete(blockrequest_mutex);
memdelete(mutex);
memdelete(sem);
-
-
}
-void FileAccessNetwork::_set_block(size_t p_offset,const Vector<uint8_t>& p_block) {
+void FileAccessNetwork::_set_block(size_t p_offset, const Vector<uint8_t> &p_block) {
-
- int page = p_offset/page_size;
- ERR_FAIL_INDEX(page,pages.size());
- if (page<pages.size()-1) {
- ERR_FAIL_COND(p_block.size()!=page_size);
+ int page = p_offset / page_size;
+ ERR_FAIL_INDEX(page, pages.size());
+ if (page < pages.size() - 1) {
+ ERR_FAIL_COND(p_block.size() != page_size);
} else {
- ERR_FAIL_COND( (p_block.size() != (total_size%page_size)));
+ ERR_FAIL_COND((p_block.size() != (total_size % page_size)));
}
buffer_mutex->lock();
- pages[page].buffer=p_block;
- pages[page].queued=false;
+ pages[page].buffer = p_block;
+ pages[page].queued = false;
buffer_mutex->unlock();
- if (waiting_on_page==page) {
- waiting_on_page=-1;
+ if (waiting_on_page == page) {
+ waiting_on_page = -1;
page_sem->post();
}
}
+void FileAccessNetwork::_respond(size_t p_len, Error p_status) {
-void FileAccessNetwork::_respond(size_t p_len,Error p_status) {
-
- DEBUG_PRINT("GOT RESPONSE - len: "+itos(p_len)+" status: "+itos(p_status));
- response=p_status;
- if (response!=OK)
+ DEBUG_PRINT("GOT RESPONSE - len: " + itos(p_len) + " status: " + itos(p_status));
+ response = p_status;
+ if (response != OK)
return;
- opened=true;
- total_size=p_len;
- int pc = ((total_size-1)/page_size)+1;
+ opened = true;
+ total_size = p_len;
+ int pc = ((total_size - 1) / page_size) + 1;
pages.resize(pc);
-
-
-
-
}
-Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessNetwork::_open(const String &p_path, int p_mode_flags) {
- ERR_FAIL_COND_V(p_mode_flags!=READ,ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(p_mode_flags != READ, ERR_UNAVAILABLE);
if (opened)
close();
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
- DEBUG_PRINT("open: "+p_path);
+ DEBUG_PRINT("open: " + p_path);
DEBUG_TIME("open_begin");
nc->lock_mutex();
nc->put_32(id);
- nc->accesses[id]=this;
+ nc->accesses[id] = this;
nc->put_32(COMMAND_OPEN_FILE);
- CharString cs =p_path.utf8();
+ CharString cs = p_path.utf8();
nc->put_32(cs.length());
- nc->client->put_data((const uint8_t*)cs.ptr(),cs.length());
- pos=0;
- eof_flag=false;
- last_page=-1;
- last_page_buff=NULL;
+ nc->client->put_data((const uint8_t *)cs.ptr(), cs.length());
+ pos = 0;
+ eof_flag = false;
+ last_page = -1;
+ last_page_buff = NULL;
//buffers.clear();
nc->unlock_mutex();
@@ -338,7 +311,7 @@ Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) {
return response;
}
-void FileAccessNetwork::close(){
+void FileAccessNetwork::close() {
if (!opened)
return;
@@ -350,110 +323,103 @@ void FileAccessNetwork::close(){
nc->put_32(id);
nc->put_32(COMMAND_CLOSE);
pages.clear();
- opened=false;
+ opened = false;
nc->unlock_mutex();
-
-
}
-bool FileAccessNetwork::is_open() const{
+bool FileAccessNetwork::is_open() const {
return opened;
}
-void FileAccessNetwork::seek(size_t p_position){
+void FileAccessNetwork::seek(size_t p_position) {
ERR_FAIL_COND(!opened);
- eof_flag=p_position>total_size;
+ eof_flag = p_position > total_size;
- if (p_position>=total_size) {
- p_position=total_size;
+ if (p_position >= total_size) {
+ p_position = total_size;
}
- pos=p_position;
+ pos = p_position;
}
-void FileAccessNetwork::seek_end(int64_t p_position){
-
- seek(total_size+p_position);
+void FileAccessNetwork::seek_end(int64_t p_position) {
+ seek(total_size + p_position);
}
-size_t FileAccessNetwork::get_pos() const{
+size_t FileAccessNetwork::get_pos() const {
- ERR_FAIL_COND_V(!opened,0);
+ ERR_FAIL_COND_V(!opened, 0);
return pos;
}
-size_t FileAccessNetwork::get_len() const{
+size_t FileAccessNetwork::get_len() const {
- ERR_FAIL_COND_V(!opened,0);
+ ERR_FAIL_COND_V(!opened, 0);
return total_size;
}
-bool FileAccessNetwork::eof_reached() const{
+bool FileAccessNetwork::eof_reached() const {
- ERR_FAIL_COND_V(!opened,false);
+ ERR_FAIL_COND_V(!opened, false);
return eof_flag;
}
-uint8_t FileAccessNetwork::get_8() const{
+uint8_t FileAccessNetwork::get_8() const {
uint8_t v;
- get_buffer(&v,1);
+ get_buffer(&v, 1);
return v;
-
}
-
void FileAccessNetwork::_queue_page(int p_page) const {
- if (p_page>=pages.size())
+ if (p_page >= pages.size())
return;
if (pages[p_page].buffer.empty() && !pages[p_page].queued) {
-
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
nc->blockrequest_mutex->lock();
FileAccessNetworkClient::BlockRequest br;
- br.id=id;
- br.offset=size_t(p_page)*page_size;
- br.size=page_size;
+ br.id = id;
+ br.offset = size_t(p_page) * page_size;
+ br.size = page_size;
nc->block_requests.push_back(br);
- pages[p_page].queued=true;
+ pages[p_page].queued = true;
nc->blockrequest_mutex->unlock();
DEBUG_PRINT("QUEUE PAGE POST");
nc->sem->post();
- DEBUG_PRINT("queued "+itos(p_page));
+ DEBUG_PRINT("queued " + itos(p_page));
}
-
}
-int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{
+int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const {
//bool eof=false;
- if (pos+p_length>total_size) {
- eof_flag=true;
+ if (pos + p_length > total_size) {
+ eof_flag = true;
}
- if (pos+p_length>=total_size) {
- p_length=total_size-pos;
+ if (pos + p_length >= total_size) {
+ p_length = total_size - pos;
}
//FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
- uint8_t *buff=last_page_buff;
+ uint8_t *buff = last_page_buff;
- for(int i=0;i<p_length;i++) {
+ for (int i = 0; i < p_length; i++) {
- int page=pos/page_size;
+ int page = pos / page_size;
- if (page!=last_page) {
+ if (page != last_page) {
buffer_mutex->lock();
if (pages[page].buffer.empty()) {
//fuck
- waiting_on_page=page;
- for(int j=0;j<read_ahead;j++) {
+ waiting_on_page = page;
+ for (int j = 0; j < read_ahead; j++) {
- _queue_page(page+j);
+ _queue_page(page + j);
}
buffer_mutex->unlock();
DEBUG_PRINT("wait");
@@ -461,30 +427,30 @@ int FileAccessNetwork::get_buffer(uint8_t *p_dst, int p_length) const{
DEBUG_PRINT("done");
} else {
- for(int j=0;j<read_ahead;j++) {
+ for (int j = 0; j < read_ahead; j++) {
- _queue_page(page+j);
+ _queue_page(page + j);
}
- buff=pages[page].buffer.ptr();
+ buff = pages[page].buffer.ptr();
//queue pages
buffer_mutex->unlock();
}
- buff=pages[page].buffer.ptr();
- last_page_buff=buff;
- last_page=page;
+ buff = pages[page].buffer.ptr();
+ last_page_buff = buff;
+ last_page = page;
}
- p_dst[i]=buff[pos-uint64_t(page)*page_size];
+ p_dst[i] = buff[pos - uint64_t(page) * page_size];
pos++;
}
return p_length;
}
-Error FileAccessNetwork::get_error() const{
+Error FileAccessNetwork::get_error() const {
- return pos==total_size?ERR_FILE_EOF:OK;
+ return pos == total_size ? ERR_FILE_EOF : OK;
}
void FileAccessNetwork::store_8(uint8_t p_dest) {
@@ -492,71 +458,66 @@ void FileAccessNetwork::store_8(uint8_t p_dest) {
ERR_FAIL();
}
-bool FileAccessNetwork::file_exists(const String& p_path){
+bool FileAccessNetwork::file_exists(const String &p_path) {
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
nc->lock_mutex();
nc->put_32(id);
nc->put_32(COMMAND_FILE_EXISTS);
- CharString cs=p_path.utf8();
+ CharString cs = p_path.utf8();
nc->put_32(cs.length());
- nc->client->put_data((const uint8_t*)cs.ptr(),cs.length());
+ nc->client->put_data((const uint8_t *)cs.ptr(), cs.length());
nc->unlock_mutex();
DEBUG_PRINT("FILE EXISTS POST");
nc->sem->post();
sem->wait();
- return exists_modtime!=0;
-
+ return exists_modtime != 0;
}
-uint64_t FileAccessNetwork::_get_modified_time(const String& p_file){
+uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) {
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
nc->lock_mutex();
nc->put_32(id);
nc->put_32(COMMAND_GET_MODTIME);
- CharString cs=p_file.utf8();
+ CharString cs = p_file.utf8();
nc->put_32(cs.length());
- nc->client->put_data((const uint8_t*)cs.ptr(),cs.length());
+ nc->client->put_data((const uint8_t *)cs.ptr(), cs.length());
nc->unlock_mutex();
DEBUG_PRINT("MODTIME POST");
nc->sem->post();
sem->wait();
return exists_modtime;
-
}
void FileAccessNetwork::configure() {
- GLOBAL_DEF("network/remote_fs/page_size",65536);
- GLOBAL_DEF("network/remote_fs/page_read_ahead",4);
- GLOBAL_DEF("network/remote_fs/max_pages",20);
-
+ GLOBAL_DEF("network/remote_fs/page_size", 65536);
+ GLOBAL_DEF("network/remote_fs/page_read_ahead", 4);
+ GLOBAL_DEF("network/remote_fs/max_pages", 20);
}
FileAccessNetwork::FileAccessNetwork() {
- eof_flag=false;
- opened=false;
- pos=0;
- sem=Semaphore::create();
- page_sem=Semaphore::create();
- buffer_mutex=Mutex::create();
+ eof_flag = false;
+ opened = false;
+ pos = 0;
+ sem = Semaphore::create();
+ page_sem = Semaphore::create();
+ buffer_mutex = Mutex::create();
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
nc->lock_mutex();
- id=nc->last_id++;
- nc->accesses[id]=this;
+ id = nc->last_id++;
+ nc->accesses[id] = this;
nc->unlock_mutex();
page_size = GLOBAL_GET("network/remote_fs/page_size");
read_ahead = GLOBAL_GET("network/remote_fs/page_read_ahead");
max_pages = GLOBAL_GET("network/remote_fs/max_pages");
- last_activity_val=0;
- waiting_on_page=-1;
- last_page=-1;
-
-
+ last_activity_val = 0;
+ waiting_on_page = -1;
+ last_page = -1;
}
FileAccessNetwork::~FileAccessNetwork() {
@@ -568,8 +529,7 @@ FileAccessNetwork::~FileAccessNetwork() {
FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
nc->lock_mutex();
- id=nc->last_id++;
+ id = nc->last_id++;
nc->accesses.erase(id);
nc->unlock_mutex();
-
}
diff --git a/core/io/file_access_network.h b/core/io/file_access_network.h
index 4dbfb04b10..bb3d22c1e9 100644
--- a/core/io/file_access_network.h
+++ b/core/io/file_access_network.h
@@ -29,16 +29,15 @@
#ifndef FILE_ACCESS_NETWORK_H
#define FILE_ACCESS_NETWORK_H
+#include "io/stream_peer_tcp.h"
#include "os/file_access.h"
#include "os/semaphore.h"
#include "os/thread.h"
-#include "io/stream_peer_tcp.h"
class FileAccessNetwork;
class FileAccessNetworkClient {
-
struct BlockRequest {
int id;
@@ -55,7 +54,7 @@ class FileAccessNetworkClient {
bool quit;
Mutex *mutex;
Mutex *blockrequest_mutex;
- Map<int,FileAccessNetwork*> accesses;
+ Map<int, FileAccessNetwork *> accesses;
Ref<StreamPeerTCP> client;
int last_id;
@@ -72,18 +71,16 @@ class FileAccessNetworkClient {
void lock_mutex();
void unlock_mutex();
-friend class FileAccessNetwork;
+ friend class FileAccessNetwork;
static FileAccessNetworkClient *singleton;
public:
-
static FileAccessNetworkClient *get_singleton() { return singleton; }
- Error connect(const String& p_host,int p_port,const String& p_password="");
+ Error connect(const String &p_host, int p_port, const String &p_password = "");
FileAccessNetworkClient();
~FileAccessNetworkClient();
-
};
class FileAccessNetwork : public FileAccess {
@@ -109,21 +106,23 @@ class FileAccessNetwork : public FileAccess {
int activity;
bool queued;
Vector<uint8_t> buffer;
- Page() { activity=0; queued=false; }
+ Page() {
+ activity = 0;
+ queued = false;
+ }
};
- mutable Vector< Page > pages;
+ mutable Vector<Page> pages;
mutable Error response;
uint64_t exists_modtime;
-friend class FileAccessNetworkClient;
+ friend class FileAccessNetworkClient;
void _queue_page(int p_page) const;
- void _respond(size_t p_len,Error p_status);
- void _set_block(size_t p_offset,const Vector<uint8_t>& p_block);
+ void _respond(size_t p_len, Error p_status);
+ void _set_block(size_t p_offset, const Vector<uint8_t> &p_block);
public:
-
enum Command {
COMMAND_OPEN_FILE,
COMMAND_READ_BLOCK,
@@ -139,13 +138,12 @@ public:
RESPONSE_GET_MODTIME,
};
-
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -158,9 +156,9 @@ public:
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_path); ///< return true if a file exists
+ virtual bool file_exists(const String &p_path); ///< return true if a file exists
- virtual uint64_t _get_modified_time(const String& p_file);
+ virtual uint64_t _get_modified_time(const String &p_file);
static void configure();
diff --git a/core/io/file_access_pack.cpp b/core/io/file_access_pack.cpp
index fa1bebde16..91d256ee2b 100644
--- a/core/io/file_access_pack.cpp
+++ b/core/io/file_access_pack.cpp
@@ -33,9 +33,9 @@
#define PACK_VERSION 1
-Error PackedData::add_pack(const String& p_path) {
+Error PackedData::add_pack(const String &p_path) {
- for (int i=0; i<sources.size(); i++) {
+ for (int i = 0; i < sources.size(); i++) {
if (sources[i]->try_open_pack(p_path)) {
@@ -46,7 +46,7 @@ Error PackedData::add_pack(const String& p_path) {
return ERR_FILE_UNRECOGNIZED;
};
-void PackedData::add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src) {
+void PackedData::add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src) {
PathMD5 pmd5(path.md5_buffer());
//printf("adding path %ls, %lli, %lli\n", path.c_str(), pmd5.a, pmd5.b);
@@ -54,35 +54,35 @@ void PackedData::add_path(const String& pkg_path, const String& path, uint64_t o
bool exists = files.has(pmd5);
PackedFile pf;
- pf.pack=pkg_path;
- pf.offset=ofs;
- pf.size=size;
- for(int i=0;i<16;i++)
- pf.md5[i]=p_md5[i];
+ pf.pack = pkg_path;
+ pf.offset = ofs;
+ pf.size = size;
+ for (int i = 0; i < 16; i++)
+ pf.md5[i] = p_md5[i];
pf.src = p_src;
- files[pmd5]=pf;
+ files[pmd5] = pf;
if (!exists) {
//search for dir
- String p = path.replace_first("res://","");
- PackedDir *cd=root;
+ String p = path.replace_first("res://", "");
+ PackedDir *cd = root;
- if (p.find("/")!=-1) { //in a subdir
+ if (p.find("/") != -1) { //in a subdir
- Vector<String> ds=p.get_base_dir().split("/");
+ Vector<String> ds = p.get_base_dir().split("/");
- for(int j=0;j<ds.size();j++) {
+ for (int j = 0; j < ds.size(); j++) {
if (!cd->subdirs.has(ds[j])) {
- PackedDir *pd = memnew( PackedDir );
- pd->name=ds[j];
- pd->parent=cd;
- cd->subdirs[pd->name]=pd;
- cd=pd;
+ PackedDir *pd = memnew(PackedDir);
+ pd->name = ds[j];
+ pd->parent = cd;
+ cd->subdirs[pd->name] = pd;
+ cd = pd;
} else {
- cd=cd->subdirs[ds[j]];
+ cd = cd->subdirs[ds[j]];
}
}
}
@@ -97,61 +97,59 @@ void PackedData::add_pack_source(PackSource *p_source) {
}
};
-PackedData *PackedData::singleton=NULL;
+PackedData *PackedData::singleton = NULL;
PackedData::PackedData() {
- singleton=this;
- root=memnew(PackedDir);
- root->parent=NULL;
- disabled=false;
+ singleton = this;
+ root = memnew(PackedDir);
+ root->parent = NULL;
+ disabled = false;
add_pack_source(memnew(PackedSourcePCK));
}
void PackedData::_free_packed_dirs(PackedDir *p_dir) {
- for (Map<String,PackedDir*>::Element *E=p_dir->subdirs.front();E;E=E->next())
+ for (Map<String, PackedDir *>::Element *E = p_dir->subdirs.front(); E; E = E->next())
_free_packed_dirs(E->get());
memdelete(p_dir);
}
PackedData::~PackedData() {
- for(int i=0;i<sources.size();i++) {
+ for (int i = 0; i < sources.size(); i++) {
memdelete(sources[i]);
}
_free_packed_dirs(root);
}
-
//////////////////////////////////////////////////////////////////
-bool PackedSourcePCK::try_open_pack(const String& p_path) {
+bool PackedSourcePCK::try_open_pack(const String &p_path) {
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f)
return false;
//printf("try open %ls!\n", p_path.c_str());
- uint32_t magic= f->get_32();
+ uint32_t magic = f->get_32();
if (magic != 0x43504447) {
//maybe at he end.... self contained exe
f->seek_end();
- f->seek( f->get_pos() -4 );
+ f->seek(f->get_pos() - 4);
magic = f->get_32();
if (magic != 0x43504447) {
memdelete(f);
return false;
}
- f->seek( f->get_pos() -12 );
-
+ f->seek(f->get_pos() - 12);
uint64_t ds = f->get_64();
- f->seek( f->get_pos() -ds-8 );
+ f->seek(f->get_pos() - ds - 8);
magic = f->get_32();
if (magic != 0x43504447) {
@@ -159,7 +157,6 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) {
memdelete(f);
return false;
}
-
}
uint32_t version = f->get_32();
@@ -167,25 +164,25 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) {
uint32_t ver_minor = f->get_32();
uint32_t ver_rev = f->get_32();
- ERR_EXPLAIN("Pack version unsupported: "+itos(version));
- ERR_FAIL_COND_V( version != PACK_VERSION, ERR_INVALID_DATA);
- ERR_EXPLAIN("Pack created with a newer version of the engine: "+itos(ver_major)+"."+itos(ver_minor)+"."+itos(ver_rev));
- ERR_FAIL_COND_V( ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA);
+ ERR_EXPLAIN("Pack version unsupported: " + itos(version));
+ ERR_FAIL_COND_V(version != PACK_VERSION, ERR_INVALID_DATA);
+ ERR_EXPLAIN("Pack created with a newer version of the engine: " + itos(ver_major) + "." + itos(ver_minor) + "." + itos(ver_rev));
+ ERR_FAIL_COND_V(ver_major > VERSION_MAJOR || (ver_major == VERSION_MAJOR && ver_minor > VERSION_MINOR), ERR_INVALID_DATA);
- for(int i=0;i<16;i++) {
+ for (int i = 0; i < 16; i++) {
//reserved
f->get_32();
}
int file_count = f->get_32();
- for(int i=0;i<file_count;i++) {
+ for (int i = 0; i < file_count; i++) {
uint32_t sl = f->get_32();
CharString cs;
- cs.resize(sl+1);
- f->get_buffer((uint8_t*)cs.ptr(),sl);
- cs[sl]=0;
+ cs.resize(sl + 1);
+ f->get_buffer((uint8_t *)cs.ptr(), sl);
+ cs[sl] = 0;
String path;
path.parse_utf8(cs.ptr());
@@ -193,22 +190,21 @@ bool PackedSourcePCK::try_open_pack(const String& p_path) {
uint64_t ofs = f->get_64();
uint64_t size = f->get_64();
uint8_t md5[16];
- f->get_buffer(md5,16);
- PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5,this);
+ f->get_buffer(md5, 16);
+ PackedData::get_singleton()->add_path(p_path, path, ofs, size, md5, this);
};
return true;
};
-FileAccess* PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile* p_file) {
+FileAccess *PackedSourcePCK::get_file(const String &p_path, PackedData::PackedFile *p_file) {
- return memnew( FileAccessPack(p_path, *p_file));
+ return memnew(FileAccessPack(p_path, *p_file));
};
//////////////////////////////////////////////////////////////////
-
-Error FileAccessPack::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessPack::_open(const String &p_path, int p_mode_flags) {
ERR_FAIL_V(ERR_UNAVAILABLE);
return ERR_UNAVAILABLE;
@@ -219,45 +215,44 @@ void FileAccessPack::close() {
f->close();
}
-bool FileAccessPack::is_open() const{
+bool FileAccessPack::is_open() const {
return f->is_open();
}
-void FileAccessPack::seek(size_t p_position){
+void FileAccessPack::seek(size_t p_position) {
- if (p_position>pf.size) {
- eof=true;
+ if (p_position > pf.size) {
+ eof = true;
} else {
- eof=false;
+ eof = false;
}
- f->seek(pf.offset+p_position);
- pos=p_position;
+ f->seek(pf.offset + p_position);
+ pos = p_position;
}
-void FileAccessPack::seek_end(int64_t p_position){
-
- seek(pf.size+p_position);
+void FileAccessPack::seek_end(int64_t p_position) {
+ seek(pf.size + p_position);
}
size_t FileAccessPack::get_pos() const {
return pos;
}
-size_t FileAccessPack::get_len() const{
+size_t FileAccessPack::get_len() const {
return pf.size;
}
-bool FileAccessPack::eof_reached() const{
+bool FileAccessPack::eof_reached() const {
return eof;
}
uint8_t FileAccessPack::get_8() const {
- if (pos>=pf.size) {
- eof=true;
+ if (pos >= pf.size) {
+ eof = true;
return 0;
}
@@ -265,23 +260,22 @@ uint8_t FileAccessPack::get_8() const {
return f->get_8();
}
-
-int FileAccessPack::get_buffer(uint8_t *p_dst,int p_length) const {
+int FileAccessPack::get_buffer(uint8_t *p_dst, int p_length) const {
if (eof)
return 0;
- int64_t to_read=p_length;
- if (to_read+pos > pf.size) {
- eof=true;
- to_read=int64_t(pf.size)-int64_t(pos);
+ int64_t to_read = p_length;
+ if (to_read + pos > pf.size) {
+ eof = true;
+ to_read = int64_t(pf.size) - int64_t(pos);
}
- pos+=p_length;
+ pos += p_length;
- if (to_read<=0)
+ if (to_read <= 0)
return 0;
- f->get_buffer(p_dst,to_read);
+ f->get_buffer(p_dst, to_read);
return to_read;
}
@@ -301,32 +295,29 @@ Error FileAccessPack::get_error() const {
void FileAccessPack::store_8(uint8_t p_dest) {
ERR_FAIL();
-
}
-void FileAccessPack::store_buffer(const uint8_t *p_src,int p_length) {
+void FileAccessPack::store_buffer(const uint8_t *p_src, int p_length) {
ERR_FAIL();
-
}
-bool FileAccessPack::file_exists(const String& p_name) {
+bool FileAccessPack::file_exists(const String &p_name) {
return false;
}
+FileAccessPack::FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file) {
-FileAccessPack::FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file) {
-
- pf=p_file;
- f=FileAccess::open(pf.pack,FileAccess::READ);
+ pf = p_file;
+ f = FileAccess::open(pf.pack, FileAccess::READ);
if (!f) {
- ERR_EXPLAIN("Can't open pack-referenced file: "+String(pf.pack));
+ ERR_EXPLAIN("Can't open pack-referenced file: " + String(pf.pack));
ERR_FAIL_COND(!f);
}
f->seek(pf.offset);
- pos=0;
- eof=false;
+ pos = 0;
+ eof = false;
}
FileAccessPack::~FileAccessPack() {
@@ -334,24 +325,21 @@ FileAccessPack::~FileAccessPack() {
memdelete(f);
}
-
//////////////////////////////////////////////////////////////////////////////////
// DIR ACCESS
//////////////////////////////////////////////////////////////////////////////////
-
Error DirAccessPack::list_dir_begin() {
-
list_dirs.clear();
list_files.clear();
- for (Map<String,PackedData::PackedDir*>::Element *E=current->subdirs.front();E;E=E->next()) {
+ for (Map<String, PackedData::PackedDir *>::Element *E = current->subdirs.front(); E; E = E->next()) {
list_dirs.push_back(E->key());
}
- for (Set<String>::Element *E=current->files.front();E;E=E->next()) {
+ for (Set<String>::Element *E = current->files.front(); E; E = E->next()) {
list_files.push_back(E->get());
}
@@ -359,15 +347,15 @@ Error DirAccessPack::list_dir_begin() {
return OK;
}
-String DirAccessPack::get_next(){
+String DirAccessPack::get_next() {
if (list_dirs.size()) {
- cdir=true;
+ cdir = true;
String d = list_dirs.front()->get();
list_dirs.pop_front();
return d;
} else if (list_files.size()) {
- cdir=false;
+ cdir = false;
String f = list_files.front()->get();
list_files.pop_front();
return f;
@@ -375,11 +363,11 @@ String DirAccessPack::get_next(){
return String();
}
}
-bool DirAccessPack::current_is_dir() const{
+bool DirAccessPack::current_is_dir() const {
return cdir;
}
-bool DirAccessPack::current_is_hidden() const{
+bool DirAccessPack::current_is_hidden() const {
return false;
}
@@ -400,20 +388,20 @@ String DirAccessPack::get_drive(int p_drive) {
Error DirAccessPack::change_dir(String p_dir) {
- String nd = p_dir.replace("\\","/");
- bool absolute=false;
+ String nd = p_dir.replace("\\", "/");
+ bool absolute = false;
if (nd.begins_with("res://")) {
- nd=nd.replace_first("res://","");
- absolute=true;
+ nd = nd.replace_first("res://", "");
+ absolute = true;
}
- nd=nd.simplify_path();
+ nd = nd.simplify_path();
if (nd == "") nd = ".";
if (nd.begins_with("/")) {
- nd=nd.replace_first("/","") ;
- absolute=true;
+ nd = nd.replace_first("/", "");
+ absolute = true;
}
Vector<String> paths = nd.split("/");
@@ -425,18 +413,18 @@ Error DirAccessPack::change_dir(String p_dir) {
else
pd = current;
- for(int i=0;i<paths.size();i++) {
+ for (int i = 0; i < paths.size(); i++) {
String p = paths[i];
- if (p==".") {
+ if (p == ".") {
continue;
- } else if (p=="..") {
+ } else if (p == "..") {
if (pd->parent) {
- pd=pd->parent;
+ pd = pd->parent;
}
} else if (pd->subdirs.has(p)) {
- pd=pd->subdirs[p];
+ pd = pd->subdirs[p];
} else {
@@ -444,29 +432,26 @@ Error DirAccessPack::change_dir(String p_dir) {
}
}
- current=pd;
+ current = pd;
return OK;
-
-
}
String DirAccessPack::get_current_dir() {
String p;
PackedData::PackedDir *pd = current;
- while(pd->parent) {
+ while (pd->parent) {
- if (pd!=current)
- p="/"+p;
- p=p+pd->name;
+ if (pd != current)
+ p = "/" + p;
+ p = p + pd->name;
}
- return "res://"+p;
-
+ return "res://" + p;
}
-bool DirAccessPack::file_exists(String p_file){
+bool DirAccessPack::file_exists(String p_file) {
return current->files.has(p_file);
}
@@ -476,36 +461,30 @@ bool DirAccessPack::dir_exists(String p_dir) {
return current->subdirs.has(p_dir);
}
-Error DirAccessPack::make_dir(String p_dir){
+Error DirAccessPack::make_dir(String p_dir) {
return ERR_UNAVAILABLE;
}
-Error DirAccessPack::rename(String p_from, String p_to){
+Error DirAccessPack::rename(String p_from, String p_to) {
return ERR_UNAVAILABLE;
-
}
-Error DirAccessPack::remove(String p_name){
+Error DirAccessPack::remove(String p_name) {
return ERR_UNAVAILABLE;
-
}
-size_t DirAccessPack::get_space_left(){
+size_t DirAccessPack::get_space_left() {
return 0;
}
DirAccessPack::DirAccessPack() {
- current=PackedData::get_singleton()->root;
- cdir=false;
+ current = PackedData::get_singleton()->root;
+ cdir = false;
}
DirAccessPack::~DirAccessPack() {
-
-
}
-
-
diff --git a/core/io/file_access_pack.h b/core/io/file_access_pack.h
index 0a1320e57b..d16f5c461e 100644
--- a/core/io/file_access_pack.h
+++ b/core/io/file_access_pack.h
@@ -29,18 +29,18 @@
#ifndef FILE_ACCESS_PACK_H
#define FILE_ACCESS_PACK_H
-#include "os/file_access.h"
-#include "os/dir_access.h"
-#include "map.h"
#include "list.h"
+#include "map.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
#include "print_string.h"
class PackSource;
class PackedData {
-friend class FileAccessPack;
-friend class DirAccessPack;
-friend class PackSource;
+ friend class FileAccessPack;
+ friend class DirAccessPack;
+ friend class PackSource;
public:
struct PackedFile {
@@ -49,21 +49,21 @@ public:
uint64_t offset; //if offset is ZERO, the file was ERASED
uint64_t size;
uint8_t md5[16];
- PackSource* src;
+ PackSource *src;
};
private:
struct PackedDir {
PackedDir *parent;
String name;
- Map<String,PackedDir*> subdirs;
+ Map<String, PackedDir *> subdirs;
Set<String> files;
};
struct PathMD5 {
uint64_t a;
uint64_t b;
- bool operator < (const PathMD5& p_md5) const {
+ bool operator<(const PathMD5 &p_md5) const {
if (p_md5.a == a) {
return b < p_md5.b;
@@ -72,7 +72,7 @@ private:
}
}
- bool operator == (const PathMD5& p_md5) const {
+ bool operator==(const PathMD5 &p_md5) const {
return a == p_md5.a && b == p_md5.b;
};
@@ -81,14 +81,14 @@ private:
};
PathMD5(const Vector<uint8_t> p_buf) {
- a = *((uint64_t*)&p_buf[0]);
- b = *((uint64_t*)&p_buf[8]);
+ a = *((uint64_t *)&p_buf[0]);
+ b = *((uint64_t *)&p_buf[8]);
};
};
- Map<PathMD5,PackedFile> files;
+ Map<PathMD5, PackedFile> files;
- Vector<PackSource*> sources;
+ Vector<PackSource *> sources;
PackedDir *root;
//Map<String,PackedDir*> dirs;
@@ -99,18 +99,17 @@ private:
void _free_packed_dirs(PackedDir *p_dir);
public:
+ void add_pack_source(PackSource *p_source);
+ void add_path(const String &pkg_path, const String &path, uint64_t ofs, uint64_t size, const uint8_t *p_md5, PackSource *p_src); // for PackSource
- void add_pack_source(PackSource* p_source);
- void add_path(const String& pkg_path, const String& path, uint64_t ofs, uint64_t size,const uint8_t* p_md5, PackSource* p_src); // for PackSource
-
- void set_disabled(bool p_disabled) { disabled=p_disabled; }
+ void set_disabled(bool p_disabled) { disabled = p_disabled; }
_FORCE_INLINE_ bool is_disabled() const { return disabled; }
static PackedData *get_singleton() { return singleton; }
- Error add_pack(const String& p_path);
+ Error add_pack(const String &p_path);
- _FORCE_INLINE_ FileAccess *try_open_path(const String& p_path);
- _FORCE_INLINE_ bool has_path(const String& p_path);
+ _FORCE_INLINE_ FileAccess *try_open_path(const String &p_path);
+ _FORCE_INLINE_ bool has_path(const String &p_path);
PackedData();
~PackedData();
@@ -119,21 +118,18 @@ public:
class PackSource {
public:
-
- virtual bool try_open_pack(const String& p_path)=0;
- virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file)=0;
+ virtual bool try_open_pack(const String &p_path) = 0;
+ virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file) = 0;
virtual ~PackSource() {}
};
class PackedSourcePCK : public PackSource {
public:
-
virtual bool try_open_pack(const String &p_path);
- virtual FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file);
+ virtual FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file);
};
-
class FileAccessPack : public FileAccess {
PackedData::PackedFile pf;
@@ -142,17 +138,15 @@ class FileAccessPack : public FileAccess {
mutable bool eof;
FileAccess *f;
- virtual Error _open(const String& p_path, int p_mode_flags);
- virtual uint64_t _get_modified_time(const String& p_file) { return 0; }
+ virtual Error _open(const String &p_path, int p_mode_flags);
+ virtual uint64_t _get_modified_time(const String &p_file) { return 0; }
public:
-
-
virtual void close();
virtual bool is_open() const;
virtual void seek(size_t p_position);
- virtual void seek_end(int64_t p_position=0);
+ virtual void seek_end(int64_t p_position = 0);
virtual size_t get_pos() const;
virtual size_t get_len() const;
@@ -160,8 +154,7 @@ public:
virtual uint8_t get_8() const;
-
- virtual int get_buffer(uint8_t *p_dst,int p_length) const;
+ virtual int get_buffer(uint8_t *p_dst, int p_length) const;
virtual void set_endian_swap(bool p_swap);
@@ -169,38 +162,34 @@ public:
virtual void store_8(uint8_t p_dest);
- virtual void store_buffer(const uint8_t *p_src,int p_length);
-
- virtual bool file_exists(const String& p_name);
+ virtual void store_buffer(const uint8_t *p_src, int p_length);
+ virtual bool file_exists(const String &p_name);
- FileAccessPack(const String& p_path, const PackedData::PackedFile& p_file);
+ FileAccessPack(const String &p_path, const PackedData::PackedFile &p_file);
~FileAccessPack();
};
-
-FileAccess *PackedData::try_open_path(const String& p_path) {
+FileAccess *PackedData::try_open_path(const String &p_path) {
//print_line("try open path " + p_path);
PathMD5 pmd5(p_path.md5_buffer());
- Map<PathMD5,PackedFile>::Element *E=files.find(pmd5);
+ Map<PathMD5, PackedFile>::Element *E = files.find(pmd5);
if (!E)
return NULL; //not found
- if (E->get().offset==0)
+ if (E->get().offset == 0)
return NULL; //was erased
return E->get().src->get_file(p_path, &E->get());
}
-bool PackedData::has_path(const String& p_path) {
+bool PackedData::has_path(const String &p_path) {
return files.has(PathMD5(p_path.md5_buffer()));
}
-
class DirAccessPack : public DirAccess {
-
PackedData::PackedDir *current;
List<String> list_dirs;
@@ -208,7 +197,6 @@ class DirAccessPack : public DirAccess {
bool cdir;
public:
-
virtual Error list_dir_begin();
virtual String get_next();
virtual bool current_is_dir() const;
@@ -221,7 +209,6 @@ public:
virtual Error change_dir(String p_dir);
virtual String get_current_dir();
-
virtual bool file_exists(String p_file);
virtual bool dir_exists(String p_dir);
@@ -234,8 +221,6 @@ public:
DirAccessPack();
~DirAccessPack();
-
};
-
#endif // FILE_ACCESS_PACK_H
diff --git a/core/io/file_access_zip.cpp b/core/io/file_access_zip.cpp
index 87f07cb7b1..4cc2edd1c3 100644
--- a/core/io/file_access_zip.cpp
+++ b/core/io/file_access_zip.cpp
@@ -30,78 +30,75 @@
#include "file_access_zip.h"
-#include "core/os/file_access.h"
#include "core/os/copymem.h"
+#include "core/os/file_access.h"
-ZipArchive* ZipArchive::instance = NULL;
+ZipArchive *ZipArchive::instance = NULL;
extern "C" {
-static void* godot_open(void* data, const char* p_fname, int mode) {
+static void *godot_open(void *data, const char *p_fname, int mode) {
if (mode & ZLIB_FILEFUNC_MODE_WRITE) {
return NULL;
};
- FileAccess* f = (FileAccess*)data;
+ FileAccess *f = (FileAccess *)data;
f->open(p_fname, FileAccess::READ);
- return f->is_open()?data:NULL;
-
+ return f->is_open() ? data : NULL;
};
-static uLong godot_read(void* data, void* fdata, void* buf, uLong size) {
+static uLong godot_read(void *data, void *fdata, void *buf, uLong size) {
- FileAccess* f = (FileAccess*)data;
- f->get_buffer((uint8_t*)buf, size);
+ FileAccess *f = (FileAccess *)data;
+ f->get_buffer((uint8_t *)buf, size);
return size;
};
-static uLong godot_write(voidpf opaque, voidpf stream, const void* buf, uLong size) {
+static uLong godot_write(voidpf opaque, voidpf stream, const void *buf, uLong size) {
return 0;
};
+static long godot_tell(voidpf opaque, voidpf stream) {
-static long godot_tell (voidpf opaque, voidpf stream) {
-
- FileAccess* f = (FileAccess*)opaque;
+ FileAccess *f = (FileAccess *)opaque;
return f->get_pos();
};
static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) {
- FileAccess* f = (FileAccess*)opaque;
+ FileAccess *f = (FileAccess *)opaque;
int pos = offset;
switch (origin) {
- case ZLIB_FILEFUNC_SEEK_CUR:
- pos = f->get_pos() + offset;
- break;
- case ZLIB_FILEFUNC_SEEK_END:
- pos = f->get_len() + offset;
- break;
- default:
- break;
+ case ZLIB_FILEFUNC_SEEK_CUR:
+ pos = f->get_pos() + offset;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END:
+ pos = f->get_len() + offset;
+ break;
+ default:
+ break;
};
f->seek(pos);
return 0;
};
-
static int godot_close(voidpf opaque, voidpf stream) {
- FileAccess* f = (FileAccess*)opaque;
+ FileAccess *f = (FileAccess *)opaque;
f->close();
return 0;
};
static int godot_testerror(voidpf opaque, voidpf stream) {
- FileAccess* f = (FileAccess*)opaque;
- return f->get_error()!=OK?1:0;
+ FileAccess *f = (FileAccess *)opaque;
+ return f->get_error() != OK ? 1 : 0;
};
static voidpf godot_alloc(voidpf opaque, uInt items, uInt size) {
@@ -119,7 +116,7 @@ static void godot_free(voidpf opaque, voidpf address) {
void ZipArchive::close_handle(unzFile p_file) const {
ERR_FAIL_COND(!p_file);
- FileAccess* f = (FileAccess*)unzGetOpaque(p_file);
+ FileAccess *f = (FileAccess *)unzGetOpaque(p_file);
unzCloseCurrentFile(p_file);
unzClose(p_file);
memdelete(f);
@@ -130,7 +127,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const {
ERR_FAIL_COND_V(!file_exists(p_file), NULL);
File file = files[p_file];
- FileAccess* f = FileAccess::open(packages[file.package].filename, FileAccess::READ);
+ FileAccess *f = FileAccess::open(packages[file.package].filename, FileAccess::READ);
ERR_FAIL_COND_V(!f, NULL);
zlib_filefunc_def io;
@@ -162,7 +159,7 @@ unzFile ZipArchive::get_file_handle(String p_file) const {
return pkg;
};
-bool ZipArchive::try_open_pack(const String& p_name) {
+bool ZipArchive::try_open_pack(const String &p_name) {
//printf("opening zip pack %ls, %i, %i\n", p_name.c_str(), p_name.extension().nocasecmp_to("zip"), p_name.extension().nocasecmp_to("pcz"));
if (p_name.get_extension().nocasecmp_to("zip") != 0 && p_name.get_extension().nocasecmp_to("pcz") != 0)
@@ -170,7 +167,7 @@ bool ZipArchive::try_open_pack(const String& p_name) {
zlib_filefunc_def io;
- FileAccess* f = FileAccess::open(p_name, FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_name, FileAccess::READ);
if (!f)
return false;
io.opaque = f;
@@ -188,20 +185,20 @@ bool ZipArchive::try_open_pack(const String& p_name) {
unz_global_info64 gi;
int err = unzGetGlobalInfo64(zfile, &gi);
- ERR_FAIL_COND_V(err!=UNZ_OK, false);
+ ERR_FAIL_COND_V(err != UNZ_OK, false);
Package pkg;
pkg.filename = p_name;
pkg.zfile = zfile;
packages.push_back(pkg);
- int pkg_num = packages.size()-1;
+ int pkg_num = packages.size() - 1;
- for (unsigned int i=0;i<gi.number_entry;i++) {
+ for (unsigned int i = 0; i < gi.number_entry; i++) {
char filename_inzip[256];
unz_file_info64 file_info;
- err = unzGetCurrentFileInfo64(zfile,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
+ err = unzGetCurrentFileInfo64(zfile, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
ERR_CONTINUE(err != UNZ_OK);
File f;
@@ -211,11 +208,11 @@ bool ZipArchive::try_open_pack(const String& p_name) {
String fname = String("res://") + filename_inzip;
files[fname] = f;
- uint8_t md5[16]={0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0};
+ uint8_t md5[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
PackedData::get_singleton()->add_path(p_name, fname, 1, 0, md5, this);
//printf("packed data add path %ls, %ls\n", p_name.c_str(), fname.c_str());
- if ((i+1)<gi.number_entry) {
+ if ((i + 1) < gi.number_entry) {
unzGoToNextFile(zfile);
};
};
@@ -228,13 +225,12 @@ bool ZipArchive::file_exists(String p_name) const {
return files.has(p_name);
};
-FileAccess* ZipArchive::get_file(const String& p_path, PackedData::PackedFile* p_file) {
+FileAccess *ZipArchive::get_file(const String &p_path, PackedData::PackedFile *p_file) {
return memnew(FileAccessZip(p_path, *p_file));
};
-
-ZipArchive* ZipArchive::get_singleton() {
+ZipArchive *ZipArchive::get_singleton() {
if (instance == NULL) {
instance = memnew(ZipArchive);
@@ -251,9 +247,9 @@ ZipArchive::ZipArchive() {
ZipArchive::~ZipArchive() {
- for (int i=0; i<packages.size(); i++) {
+ for (int i = 0; i < packages.size(); i++) {
- FileAccess* f = (FileAccess*)unzGetOpaque(packages[i].zfile);
+ FileAccess *f = (FileAccess *)unzGetOpaque(packages[i].zfile);
unzClose(packages[i].zfile);
memdelete(f);
};
@@ -261,18 +257,17 @@ ZipArchive::~ZipArchive() {
packages.clear();
};
-
-Error FileAccessZip::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessZip::_open(const String &p_path, int p_mode_flags) {
close();
ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, FAILED);
- ZipArchive* arch = ZipArchive::get_singleton();
+ ZipArchive *arch = ZipArchive::get_singleton();
ERR_FAIL_COND_V(!arch, FAILED);
zfile = arch->get_file_handle(p_path);
ERR_FAIL_COND_V(!zfile, FAILED);
- int err = unzGetCurrentFileInfo64(zfile,&file_info,NULL,0,NULL,0,NULL,0);
+ int err = unzGetCurrentFileInfo64(zfile, &file_info, NULL, 0, NULL, 0, NULL, 0);
ERR_FAIL_COND_V(err != UNZ_OK, FAILED);
return OK;
@@ -283,7 +278,7 @@ void FileAccessZip::close() {
if (!zfile)
return;
- ZipArchive* arch = ZipArchive::get_singleton();
+ ZipArchive *arch = ZipArchive::get_singleton();
ERR_FAIL_COND(!arch);
arch->close_handle(zfile);
zfile = NULL;
@@ -332,7 +327,7 @@ uint8_t FileAccessZip::get_8() const {
return ret;
};
-int FileAccessZip::get_buffer(uint8_t *p_dst,int p_length) const {
+int FileAccessZip::get_buffer(uint8_t *p_dst, int p_length) const {
ERR_FAIL_COND_V(!zfile, -1);
at_eof = unzeof(zfile);
@@ -363,13 +358,12 @@ void FileAccessZip::store_8(uint8_t p_dest) {
ERR_FAIL();
};
-bool FileAccessZip::file_exists(const String& p_name) {
+bool FileAccessZip::file_exists(const String &p_name) {
return false;
};
-
-FileAccessZip::FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file) {
+FileAccessZip::FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file) {
zfile = NULL;
_open(p_path, FileAccess::READ);
diff --git a/core/io/file_access_zip.h b/core/io/file_access_zip.h
index e34bc1283a..7d5be8678d 100644
--- a/core/io/file_access_zip.h
+++ b/core/io/file_access_zip.h
@@ -31,15 +31,14 @@
#ifndef FILE_ACCESS_Zip_H
#define FILE_ACCESS_Zip_H
-#include <stdlib.h>
#include "core/io/file_access_pack.h"
-#include "unzip.h"
#include "map.h"
+#include "unzip.h"
+#include <stdlib.h>
class ZipArchive : public PackSource {
public:
-
struct File {
int package;
@@ -50,23 +49,20 @@ public:
};
};
-
private:
-
struct Package {
String filename;
unzFile zfile;
};
Vector<Package> packages;
- Map<String,File> files;
+ Map<String, File> files;
- static ZipArchive* instance;
+ static ZipArchive *instance;
FileAccess::CreateFunc fa_create_func;
public:
-
void close_handle(unzFile p_file) const;
unzFile get_file_handle(String p_file) const;
@@ -74,49 +70,47 @@ public:
bool file_exists(String p_name) const;
- virtual bool try_open_pack(const String& p_path);
- FileAccess* get_file(const String& p_path, PackedData::PackedFile* p_file);
+ virtual bool try_open_pack(const String &p_path);
+ FileAccess *get_file(const String &p_path, PackedData::PackedFile *p_file);
- static ZipArchive* get_singleton();
+ static ZipArchive *get_singleton();
ZipArchive();
~ZipArchive();
};
-
class FileAccessZip : public FileAccess {
unzFile zfile;
- unz_file_info64 file_info;
+ unz_file_info64 file_info;
mutable bool at_eof;
- ZipArchive* archive;
+ ZipArchive *archive;
public:
-
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
virtual bool eof_reached() const; ///< reading passed EOF
virtual uint8_t get_8() const; ///< get a byte
- virtual int get_buffer(uint8_t *p_dst,int p_length) const;
+ virtual int get_buffer(uint8_t *p_dst, int p_length) const;
virtual Error get_error() const; ///< get last error
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_name); ///< return true if a file exists
+ virtual bool file_exists(const String &p_name); ///< return true if a file exists
- virtual uint64_t _get_modified_time(const String& p_file) { return 0; } // todo
+ virtual uint64_t _get_modified_time(const String &p_file) { return 0; } // todo
- FileAccessZip(const String& p_path, const PackedData::PackedFile& p_file);
+ FileAccessZip(const String &p_path, const PackedData::PackedFile &p_file);
~FileAccessZip();
};
diff --git a/core/io/http_client.cpp b/core/io/http_client.cpp
index ae14f8fa38..be5309ddfa 100644
--- a/core/io/http_client.cpp
+++ b/core/io/http_client.cpp
@@ -29,52 +29,47 @@
#include "http_client.h"
#include "io/stream_peer_ssl.h"
-Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl,bool p_verify_host){
+Error HTTPClient::connect_to_host(const String &p_host, int p_port, bool p_ssl, bool p_verify_host) {
close();
- conn_port=p_port;
- conn_host=p_host;
+ conn_port = p_port;
+ conn_host = p_host;
if (conn_host.begins_with("http://")) {
- conn_host=conn_host.replace_first("http://","");
+ conn_host = conn_host.replace_first("http://", "");
} else if (conn_host.begins_with("https://")) {
//use https
- conn_host=conn_host.replace_first("https://","");
+ conn_host = conn_host.replace_first("https://", "");
}
-
- ssl=p_ssl;
- ssl_verify_host=p_verify_host;
- connection=tcp_connection;
-
-
+ ssl = p_ssl;
+ ssl_verify_host = p_verify_host;
+ connection = tcp_connection;
if (conn_host.is_valid_ip_address()) {
//is ip
- Error err = tcp_connection->connect_to_host(IP_Address(conn_host),p_port);
+ Error err = tcp_connection->connect_to_host(IP_Address(conn_host), p_port);
if (err) {
- status=STATUS_CANT_CONNECT;
+ status = STATUS_CANT_CONNECT;
return err;
}
- status=STATUS_CONNECTING;
+ status = STATUS_CONNECTING;
} else {
//is hostname
- resolving=IP::get_singleton()->resolve_hostname_queue_item(conn_host);
- status=STATUS_RESOLVING;
-
+ resolving = IP::get_singleton()->resolve_hostname_queue_item(conn_host);
+ status = STATUS_RESOLVING;
}
return OK;
}
-void HTTPClient::set_connection(const Ref<StreamPeer>& p_connection){
+void HTTPClient::set_connection(const Ref<StreamPeer> &p_connection) {
close();
- connection=p_connection;
- status=STATUS_CONNECTED;
-
+ connection = p_connection;
+ status = STATUS_CONNECTED;
}
Ref<StreamPeer> HTTPClient::get_connection() const {
@@ -82,14 +77,13 @@ Ref<StreamPeer> HTTPClient::get_connection() const {
return connection;
}
-Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body) {
-
- ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA);
+Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body) {
+ ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
- static const char* _methods[METHOD_MAX]={
+ static const char *_methods[METHOD_MAX] = {
"GET",
"HEAD",
"POST",
@@ -97,54 +91,54 @@ Error HTTPClient::request_raw( Method p_method, const String& p_url, const Vecto
"DELETE",
"OPTIONS",
"TRACE",
- "CONNECT"};
-
- String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n";
- request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n";
- bool add_clen=p_body.size()>0;
- for(int i=0;i<p_headers.size();i++) {
- request+=p_headers[i]+"\r\n";
- if (add_clen && p_headers[i].find("Content-Length:")==0) {
- add_clen=false;
+ "CONNECT"
+ };
+
+ String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
+ request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
+ bool add_clen = p_body.size() > 0;
+ for (int i = 0; i < p_headers.size(); i++) {
+ request += p_headers[i] + "\r\n";
+ if (add_clen && p_headers[i].find("Content-Length:") == 0) {
+ add_clen = false;
}
}
if (add_clen) {
- request+="Content-Length: "+itos(p_body.size())+"\r\n";
+ request += "Content-Length: " + itos(p_body.size()) + "\r\n";
//should it add utf8 encoding? not sure
}
- request+="\r\n";
- CharString cs=request.utf8();
+ request += "\r\n";
+ CharString cs = request.utf8();
PoolVector<uint8_t> data;
//Maybe this goes faster somehow?
- for(int i=0;i<cs.length();i++) {
- data.append( cs[i] );
+ for (int i = 0; i < cs.length(); i++) {
+ data.append(cs[i]);
}
- data.append_array( p_body );
+ data.append_array(p_body);
PoolVector<uint8_t>::Read r = data.read();
Error err = connection->put_data(&r[0], data.size());
if (err) {
close();
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return err;
}
- status=STATUS_REQUESTING;
+ status = STATUS_REQUESTING;
return OK;
}
-Error HTTPClient::request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body) {
+Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {
- ERR_FAIL_INDEX_V(p_method,METHOD_MAX,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(status!=STATUS_CONNECTED,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(connection.is_null(),ERR_INVALID_DATA);
+ ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);
-
- static const char* _methods[METHOD_MAX]={
+ static const char *_methods[METHOD_MAX] = {
"GET",
"HEAD",
"POST",
@@ -152,50 +146,51 @@ Error HTTPClient::request( Method p_method, const String& p_url, const Vector<St
"DELETE",
"OPTIONS",
"TRACE",
- "CONNECT"};
-
- String request=String(_methods[p_method])+" "+p_url+" HTTP/1.1\r\n";
- request+="Host: "+conn_host+":"+itos(conn_port)+"\r\n";
- bool add_clen=p_body.length()>0;
- for(int i=0;i<p_headers.size();i++) {
- request+=p_headers[i]+"\r\n";
- if (add_clen && p_headers[i].find("Content-Length:")==0) {
- add_clen=false;
+ "CONNECT"
+ };
+
+ String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
+ request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
+ bool add_clen = p_body.length() > 0;
+ for (int i = 0; i < p_headers.size(); i++) {
+ request += p_headers[i] + "\r\n";
+ if (add_clen && p_headers[i].find("Content-Length:") == 0) {
+ add_clen = false;
}
}
if (add_clen) {
- request+="Content-Length: "+itos(p_body.utf8().length())+"\r\n";
+ request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n";
//should it add utf8 encoding? not sure
}
- request+="\r\n";
- request+=p_body;
+ request += "\r\n";
+ request += p_body;
- CharString cs=request.utf8();
- Error err = connection->put_data((const uint8_t*)cs.ptr(),cs.length());
+ CharString cs = request.utf8();
+ Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length());
if (err) {
close();
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return err;
}
- status=STATUS_REQUESTING;
+ status = STATUS_REQUESTING;
return OK;
}
-Error HTTPClient::send_body_text(const String& p_body){
+Error HTTPClient::send_body_text(const String &p_body) {
return OK;
}
-Error HTTPClient::send_body_data(const PoolByteArray& p_body){
+Error HTTPClient::send_body_data(const PoolByteArray &p_body) {
return OK;
}
bool HTTPClient::has_response() const {
- return response_headers.size()!=0;
+ return response_headers.size() != 0;
}
bool HTTPClient::is_response_chunked() const {
@@ -213,7 +208,7 @@ Error HTTPClient::get_response_headers(List<String> *r_response) {
if (!response_headers.size())
return ERR_INVALID_PARAMETER;
- for(int i=0;i<response_headers.size();i++) {
+ for (int i = 0; i < response_headers.size(); i++) {
r_response->push_back(response_headers[i]);
}
@@ -223,71 +218,67 @@ Error HTTPClient::get_response_headers(List<String> *r_response) {
return OK;
}
+void HTTPClient::close() {
-void HTTPClient::close(){
-
- if (tcp_connection->get_status()!=StreamPeerTCP::STATUS_NONE)
+ if (tcp_connection->get_status() != StreamPeerTCP::STATUS_NONE)
tcp_connection->disconnect_from_host();
connection.unref();
- status=STATUS_DISCONNECTED;
- if (resolving!=IP::RESOLVER_INVALID_ID) {
+ status = STATUS_DISCONNECTED;
+ if (resolving != IP::RESOLVER_INVALID_ID) {
IP::get_singleton()->erase_resolve_item(resolving);
- resolving=IP::RESOLVER_INVALID_ID;
-
+ resolving = IP::RESOLVER_INVALID_ID;
}
response_headers.clear();
response_str.clear();
- body_size=0;
- body_left=0;
- chunk_left=0;
- response_num=0;
+ body_size = 0;
+ body_left = 0;
+ chunk_left = 0;
+ response_num = 0;
}
+Error HTTPClient::poll() {
-Error HTTPClient::poll(){
-
- switch(status) {
-
+ switch (status) {
case STATUS_RESOLVING: {
- ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG);
+ ERR_FAIL_COND_V(resolving == IP::RESOLVER_INVALID_ID, ERR_BUG);
IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
- switch(rstatus) {
- case IP::RESOLVER_STATUS_WAITING: return OK; //still resolving
+ switch (rstatus) {
+ case IP::RESOLVER_STATUS_WAITING:
+ return OK; //still resolving
case IP::RESOLVER_STATUS_DONE: {
IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving);
- Error err = tcp_connection->connect_to_host(host,conn_port);
+ Error err = tcp_connection->connect_to_host(host, conn_port);
IP::get_singleton()->erase_resolve_item(resolving);
- resolving=IP::RESOLVER_INVALID_ID;
+ resolving = IP::RESOLVER_INVALID_ID;
if (err) {
- status=STATUS_CANT_CONNECT;
+ status = STATUS_CANT_CONNECT;
return err;
}
- status=STATUS_CONNECTING;
+ status = STATUS_CONNECTING;
} break;
case IP::RESOLVER_STATUS_NONE:
case IP::RESOLVER_STATUS_ERROR: {
IP::get_singleton()->erase_resolve_item(resolving);
- resolving=IP::RESOLVER_INVALID_ID;
+ resolving = IP::RESOLVER_INVALID_ID;
close();
- status=STATUS_CANT_RESOLVE;
+ status = STATUS_CANT_RESOLVE;
return ERR_CANT_RESOLVE;
} break;
-
}
} break;
case STATUS_CONNECTING: {
StreamPeerTCP::Status s = tcp_connection->get_status();
- switch(s) {
+ switch (s) {
case StreamPeerTCP::STATUS_CONNECTING: {
return OK; //do none
@@ -295,23 +286,23 @@ Error HTTPClient::poll(){
case StreamPeerTCP::STATUS_CONNECTED: {
if (ssl) {
Ref<StreamPeerSSL> ssl = StreamPeerSSL::create();
- Error err = ssl->connect_to_stream(tcp_connection,true,ssl_verify_host?conn_host:String());
- if (err!=OK) {
+ Error err = ssl->connect_to_stream(tcp_connection, true, ssl_verify_host ? conn_host : String());
+ if (err != OK) {
close();
- status=STATUS_SSL_HANDSHAKE_ERROR;
+ status = STATUS_SSL_HANDSHAKE_ERROR;
return ERR_CANT_CONNECT;
}
//print_line("SSL! TURNED ON!");
- connection=ssl;
+ connection = ssl;
}
- status=STATUS_CONNECTED;
+ status = STATUS_CONNECTED;
return OK;
} break;
case StreamPeerTCP::STATUS_ERROR:
case StreamPeerTCP::STATUS_NONE: {
close();
- status=STATUS_CANT_CONNECT;
+ status = STATUS_CANT_CONNECT;
return ERR_CANT_CONNECT;
} break;
}
@@ -322,78 +313,73 @@ Error HTTPClient::poll(){
} break;
case STATUS_REQUESTING: {
-
- while(true) {
+ while (true) {
uint8_t byte;
- int rec=0;
- Error err = _get_http_data(&byte,1,rec);
- if (err!=OK) {
+ int rec = 0;
+ Error err = _get_http_data(&byte, 1, rec);
+ if (err != OK) {
close();
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return ERR_CONNECTION_ERROR;
}
- if (rec==0)
+ if (rec == 0)
return OK; //keep trying!
response_str.push_back(byte);
int rs = response_str.size();
if (
- (rs>=2 && response_str[rs-2]=='\n' && response_str[rs-1]=='\n') ||
- (rs>=4 && response_str[rs-4]=='\r' && response_str[rs-3]=='\n' && response_str[rs-2]=='\r' && response_str[rs-1]=='\n')
- ) {
-
+ (rs >= 2 && response_str[rs - 2] == '\n' && response_str[rs - 1] == '\n') ||
+ (rs >= 4 && response_str[rs - 4] == '\r' && response_str[rs - 3] == '\n' && response_str[rs - 2] == '\r' && response_str[rs - 1] == '\n')) {
//end of response, parse.
response_str.push_back(0);
String response;
- response.parse_utf8((const char*)response_str.ptr());
+ response.parse_utf8((const char *)response_str.ptr());
//print_line("END OF RESPONSE? :\n"+response+"\n------");
Vector<String> responses = response.split("\n");
- body_size=0;
- chunked=false;
- body_left=0;
- chunk_left=0;
+ body_size = 0;
+ chunked = false;
+ body_left = 0;
+ chunk_left = 0;
response_str.clear();
response_headers.clear();
response_num = RESPONSE_OK;
- for(int i=0;i<responses.size();i++) {
+ for (int i = 0; i < responses.size(); i++) {
String header = responses[i].strip_edges();
String s = header.to_lower();
- if (s.length()==0)
+ if (s.length() == 0)
continue;
if (s.begins_with("content-length:")) {
- body_size = s.substr(s.find(":")+1,s.length()).strip_edges().to_int();
- body_left=body_size;
+ body_size = s.substr(s.find(":") + 1, s.length()).strip_edges().to_int();
+ body_left = body_size;
}
if (s.begins_with("transfer-encoding:")) {
- String encoding = header.substr(header.find(":")+1,header.length()).strip_edges();
+ String encoding = header.substr(header.find(":") + 1, header.length()).strip_edges();
//print_line("TRANSFER ENCODING: "+encoding);
- if (encoding=="chunked") {
- chunked=true;
+ if (encoding == "chunked") {
+ chunked = true;
}
-
}
- if (i==0 && responses[i].begins_with("HTTP")) {
+ if (i == 0 && responses[i].begins_with("HTTP")) {
- String num = responses[i].get_slicec(' ',1);
- response_num=num.to_int();
+ String num = responses[i].get_slicec(' ', 1);
+ response_num = num.to_int();
} else {
response_headers.push_back(header);
}
-
}
- if (body_size==0 && !chunked) {
+ if (body_size == 0 && !chunked) {
- status=STATUS_CONNECTED; //ask for something again?
+ status = STATUS_CONNECTED; //ask for something again?
} else {
- status=STATUS_BODY;
+ status = STATUS_BODY;
}
return OK;
}
@@ -415,25 +401,22 @@ Error HTTPClient::poll(){
} break;
}
-
return OK;
}
-
Dictionary HTTPClient::_get_response_headers_as_dictionary() {
List<String> rh;
get_response_headers(&rh);
Dictionary ret;
- for(const List<String>::Element *E=rh.front();E;E=E->next()) {
+ for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
String s = E->get();
int sp = s.find(":");
- if (sp==-1)
+ if (sp == -1)
continue;
- String key = s.substr(0,sp).strip_edges();
- String value = s.substr(sp+1,s.length()).strip_edges();
- ret[key]=value;
-
+ String key = s.substr(0, sp).strip_edges();
+ String value = s.substr(sp + 1, s.length()).strip_edges();
+ ret[key] = value;
}
return ret;
@@ -445,9 +428,9 @@ PoolStringArray HTTPClient::_get_response_headers() {
get_response_headers(&rh);
PoolStringArray ret;
ret.resize(rh.size());
- int idx=0;
- for(const List<String>::Element *E=rh.front();E;E=E->next()) {
- ret.set(idx++,E->get());
+ int idx = 0;
+ for (const List<String>::Element *E = rh.front(); E; E = E->next()) {
+ ret.set(idx++, E->get());
}
return ret;
@@ -460,96 +443,93 @@ int HTTPClient::get_response_body_length() const {
PoolByteArray HTTPClient::read_response_body_chunk() {
- ERR_FAIL_COND_V( status !=STATUS_BODY, PoolByteArray() );
+ ERR_FAIL_COND_V(status != STATUS_BODY, PoolByteArray());
- Error err=OK;
+ Error err = OK;
if (chunked) {
- while(true) {
+ while (true) {
- if (chunk_left==0) {
+ if (chunk_left == 0) {
//reading len
uint8_t b;
- int rec=0;
- err = _get_http_data(&b,1,rec);
+ int rec = 0;
+ err = _get_http_data(&b, 1, rec);
- if (rec==0)
+ if (rec == 0)
break;
chunk.push_back(b);
- if (chunk.size()>32) {
+ if (chunk.size() > 32) {
ERR_PRINT("HTTP Invalid chunk hex len");
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return PoolByteArray();
}
- if (chunk.size()>2 && chunk[chunk.size()-2]=='\r' && chunk[chunk.size()-1]=='\n') {
+ if (chunk.size() > 2 && chunk[chunk.size() - 2] == '\r' && chunk[chunk.size() - 1] == '\n') {
- int len=0;
- for(int i=0;i<chunk.size()-2;i++) {
+ int len = 0;
+ for (int i = 0; i < chunk.size() - 2; i++) {
char c = chunk[i];
- int v=0;
- if (c>='0' && c<='9')
- v=c-'0';
- else if (c>='a' && c<='f')
- v=c-'a'+10;
- else if (c>='A' && c<='F')
- v=c-'A'+10;
+ int v = 0;
+ if (c >= '0' && c <= '9')
+ v = c - '0';
+ else if (c >= 'a' && c <= 'f')
+ v = c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ v = c - 'A' + 10;
else {
ERR_PRINT("HTTP Chunk len not in hex!!");
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return PoolByteArray();
}
- len<<=4;
- len|=v;
- if (len>(1<<24)) {
+ len <<= 4;
+ len |= v;
+ if (len > (1 << 24)) {
ERR_PRINT("HTTP Chunk too big!! >16mb");
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return PoolByteArray();
}
-
}
- if (len==0) {
+ if (len == 0) {
//end!
- status=STATUS_CONNECTED;
+ status = STATUS_CONNECTED;
chunk.clear();
return PoolByteArray();
}
- chunk_left=len+2;
+ chunk_left = len + 2;
chunk.resize(chunk_left);
-
}
} else {
- int rec=0;
- err = _get_http_data(&chunk[chunk.size()-chunk_left],chunk_left,rec);
- if (rec==0) {
+ int rec = 0;
+ err = _get_http_data(&chunk[chunk.size() - chunk_left], chunk_left, rec);
+ if (rec == 0) {
break;
}
- chunk_left-=rec;
+ chunk_left -= rec;
- if (chunk_left==0) {
+ if (chunk_left == 0) {
- if (chunk[chunk.size()-2]!='\r' || chunk[chunk.size()-1]!='\n') {
+ if (chunk[chunk.size() - 2] != '\r' || chunk[chunk.size() - 1] != '\n') {
ERR_PRINT("HTTP Invalid chunk terminator (not \\r\\n)");
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
return PoolByteArray();
}
PoolByteArray ret;
- ret.resize(chunk.size()-2);
+ ret.resize(chunk.size() - 2);
{
PoolByteArray::Write w = ret.write();
- copymem(w.ptr(),chunk.ptr(),chunk.size()-2);
+ copymem(w.ptr(), chunk.ptr(), chunk.size() - 2);
}
chunk.clear();
return ret;
-
}
break;
@@ -558,46 +538,44 @@ PoolByteArray HTTPClient::read_response_body_chunk() {
} else {
- int to_read = MIN(body_left,read_chunk_size);
+ int to_read = MIN(body_left, read_chunk_size);
PoolByteArray ret;
ret.resize(to_read);
int _offset = 0;
while (to_read > 0) {
- int rec=0;
+ int rec = 0;
{
PoolByteArray::Write w = ret.write();
- err = _get_http_data(w.ptr()+_offset,to_read,rec);
+ err = _get_http_data(w.ptr() + _offset, to_read, rec);
}
- if (rec>0) {
- body_left-=rec;
- to_read-=rec;
+ if (rec > 0) {
+ body_left -= rec;
+ to_read -= rec;
_offset += rec;
} else {
- if (to_read>0) //ended up reading less
+ if (to_read > 0) //ended up reading less
ret.resize(_offset);
break;
}
}
- if (body_left==0) {
- status=STATUS_CONNECTED;
+ if (body_left == 0) {
+ status = STATUS_CONNECTED;
}
return ret;
-
}
-
- if (err!=OK) {
+ if (err != OK) {
close();
- if (err==ERR_FILE_EOF) {
+ if (err == ERR_FILE_EOF) {
- status=STATUS_DISCONNECTED; //server disconnected
+ status = STATUS_DISCONNECTED; //server disconnected
} else {
- status=STATUS_CONNECTION_ERROR;
+ status = STATUS_CONNECTION_ERROR;
}
- } else if (body_left==0 && !chunked) {
+ } else if (body_left == 0 && !chunked) {
- status=STATUS_CONNECTED;
+ status = STATUS_CONNECTED;
}
return PoolByteArray();
@@ -605,179 +583,172 @@ PoolByteArray HTTPClient::read_response_body_chunk() {
HTTPClient::Status HTTPClient::get_status() const {
-
return status;
}
void HTTPClient::set_blocking_mode(bool p_enable) {
- blocking=p_enable;
+ blocking = p_enable;
}
-bool HTTPClient::is_blocking_mode_enabled() const{
+bool HTTPClient::is_blocking_mode_enabled() const {
return blocking;
}
-Error HTTPClient::_get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received) {
+Error HTTPClient::_get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
if (blocking) {
- Error err = connection->get_data(p_buffer,p_bytes);
- if (err==OK)
- r_received=p_bytes;
+ Error err = connection->get_data(p_buffer, p_bytes);
+ if (err == OK)
+ r_received = p_bytes;
else
- r_received=0;
+ r_received = 0;
return err;
} else {
- return connection->get_partial_data(p_buffer,p_bytes,r_received);
+ return connection->get_partial_data(p_buffer, p_bytes, r_received);
}
}
void HTTPClient::_bind_methods() {
- ClassDB::bind_method(D_METHOD("connect_to_host:Error","host","port","use_ssl","verify_host"),&HTTPClient::connect_to_host,DEFVAL(false),DEFVAL(true));
- ClassDB::bind_method(D_METHOD("set_connection","connection:StreamPeer"),&HTTPClient::set_connection);
- ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"),&HTTPClient::get_connection);
- ClassDB::bind_method(D_METHOD("request_raw","method","url","headers","body"),&HTTPClient::request_raw);
- ClassDB::bind_method(D_METHOD("request","method","url","headers","body"),&HTTPClient::request,DEFVAL(String()));
- ClassDB::bind_method(D_METHOD("send_body_text","body"),&HTTPClient::send_body_text);
- ClassDB::bind_method(D_METHOD("send_body_data","body"),&HTTPClient::send_body_data);
- ClassDB::bind_method(D_METHOD("close"),&HTTPClient::close);
-
- ClassDB::bind_method(D_METHOD("has_response"),&HTTPClient::has_response);
- ClassDB::bind_method(D_METHOD("is_response_chunked"),&HTTPClient::is_response_chunked);
- ClassDB::bind_method(D_METHOD("get_response_code"),&HTTPClient::get_response_code);
- ClassDB::bind_method(D_METHOD("get_response_headers"),&HTTPClient::_get_response_headers);
- ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"),&HTTPClient::_get_response_headers_as_dictionary);
- ClassDB::bind_method(D_METHOD("get_response_body_length"),&HTTPClient::get_response_body_length);
- ClassDB::bind_method(D_METHOD("read_response_body_chunk"),&HTTPClient::read_response_body_chunk);
- ClassDB::bind_method(D_METHOD("set_read_chunk_size","bytes"),&HTTPClient::set_read_chunk_size);
-
- ClassDB::bind_method(D_METHOD("set_blocking_mode","enabled"),&HTTPClient::set_blocking_mode);
- ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"),&HTTPClient::is_blocking_mode_enabled);
-
- ClassDB::bind_method(D_METHOD("get_status"),&HTTPClient::get_status);
- ClassDB::bind_method(D_METHOD("poll:Error"),&HTTPClient::poll);
-
- ClassDB::bind_method(D_METHOD("query_string_from_dict:String","fields"),&HTTPClient::query_string_from_dict);
-
-
- BIND_CONSTANT( METHOD_GET );
- BIND_CONSTANT( METHOD_HEAD );
- BIND_CONSTANT( METHOD_POST );
- BIND_CONSTANT( METHOD_PUT );
- BIND_CONSTANT( METHOD_DELETE );
- BIND_CONSTANT( METHOD_OPTIONS );
- BIND_CONSTANT( METHOD_TRACE );
- BIND_CONSTANT( METHOD_CONNECT );
- BIND_CONSTANT( METHOD_MAX );
-
- BIND_CONSTANT( STATUS_DISCONNECTED );
- BIND_CONSTANT( STATUS_RESOLVING ); //resolving hostname (if passed a hostname)
- BIND_CONSTANT( STATUS_CANT_RESOLVE );
- BIND_CONSTANT( STATUS_CONNECTING ); //connecting to ip
- BIND_CONSTANT( STATUS_CANT_CONNECT );
- BIND_CONSTANT( STATUS_CONNECTED ); //connected ); requests only accepted here
- BIND_CONSTANT( STATUS_REQUESTING ); // request in progress
- BIND_CONSTANT( STATUS_BODY ); // request resulted in body ); which must be read
- BIND_CONSTANT( STATUS_CONNECTION_ERROR );
- BIND_CONSTANT( STATUS_SSL_HANDSHAKE_ERROR );
-
-
- BIND_CONSTANT( RESPONSE_CONTINUE );
- BIND_CONSTANT( RESPONSE_SWITCHING_PROTOCOLS );
- BIND_CONSTANT( RESPONSE_PROCESSING );
+ ClassDB::bind_method(D_METHOD("connect_to_host:Error", "host", "port", "use_ssl", "verify_host"), &HTTPClient::connect_to_host, DEFVAL(false), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("set_connection", "connection:StreamPeer"), &HTTPClient::set_connection);
+ ClassDB::bind_method(D_METHOD("get_connection:StreamPeer"), &HTTPClient::get_connection);
+ ClassDB::bind_method(D_METHOD("request_raw", "method", "url", "headers", "body"), &HTTPClient::request_raw);
+ ClassDB::bind_method(D_METHOD("request", "method", "url", "headers", "body"), &HTTPClient::request, DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("send_body_text", "body"), &HTTPClient::send_body_text);
+ ClassDB::bind_method(D_METHOD("send_body_data", "body"), &HTTPClient::send_body_data);
+ ClassDB::bind_method(D_METHOD("close"), &HTTPClient::close);
+
+ ClassDB::bind_method(D_METHOD("has_response"), &HTTPClient::has_response);
+ ClassDB::bind_method(D_METHOD("is_response_chunked"), &HTTPClient::is_response_chunked);
+ ClassDB::bind_method(D_METHOD("get_response_code"), &HTTPClient::get_response_code);
+ ClassDB::bind_method(D_METHOD("get_response_headers"), &HTTPClient::_get_response_headers);
+ ClassDB::bind_method(D_METHOD("get_response_headers_as_dictionary"), &HTTPClient::_get_response_headers_as_dictionary);
+ ClassDB::bind_method(D_METHOD("get_response_body_length"), &HTTPClient::get_response_body_length);
+ ClassDB::bind_method(D_METHOD("read_response_body_chunk"), &HTTPClient::read_response_body_chunk);
+ ClassDB::bind_method(D_METHOD("set_read_chunk_size", "bytes"), &HTTPClient::set_read_chunk_size);
+
+ ClassDB::bind_method(D_METHOD("set_blocking_mode", "enabled"), &HTTPClient::set_blocking_mode);
+ ClassDB::bind_method(D_METHOD("is_blocking_mode_enabled"), &HTTPClient::is_blocking_mode_enabled);
+
+ ClassDB::bind_method(D_METHOD("get_status"), &HTTPClient::get_status);
+ ClassDB::bind_method(D_METHOD("poll:Error"), &HTTPClient::poll);
+
+ ClassDB::bind_method(D_METHOD("query_string_from_dict:String", "fields"), &HTTPClient::query_string_from_dict);
+
+ BIND_CONSTANT(METHOD_GET);
+ BIND_CONSTANT(METHOD_HEAD);
+ BIND_CONSTANT(METHOD_POST);
+ BIND_CONSTANT(METHOD_PUT);
+ BIND_CONSTANT(METHOD_DELETE);
+ BIND_CONSTANT(METHOD_OPTIONS);
+ BIND_CONSTANT(METHOD_TRACE);
+ BIND_CONSTANT(METHOD_CONNECT);
+ BIND_CONSTANT(METHOD_MAX);
+
+ BIND_CONSTANT(STATUS_DISCONNECTED);
+ BIND_CONSTANT(STATUS_RESOLVING); //resolving hostname (if passed a hostname)
+ BIND_CONSTANT(STATUS_CANT_RESOLVE);
+ BIND_CONSTANT(STATUS_CONNECTING); //connecting to ip
+ BIND_CONSTANT(STATUS_CANT_CONNECT);
+ BIND_CONSTANT(STATUS_CONNECTED); //connected ); requests only accepted here
+ BIND_CONSTANT(STATUS_REQUESTING); // request in progress
+ BIND_CONSTANT(STATUS_BODY); // request resulted in body ); which must be read
+ BIND_CONSTANT(STATUS_CONNECTION_ERROR);
+ BIND_CONSTANT(STATUS_SSL_HANDSHAKE_ERROR);
+
+ BIND_CONSTANT(RESPONSE_CONTINUE);
+ BIND_CONSTANT(RESPONSE_SWITCHING_PROTOCOLS);
+ BIND_CONSTANT(RESPONSE_PROCESSING);
// 2xx successful
- BIND_CONSTANT( RESPONSE_OK );
- BIND_CONSTANT( RESPONSE_CREATED );
- BIND_CONSTANT( RESPONSE_ACCEPTED );
- BIND_CONSTANT( RESPONSE_NON_AUTHORITATIVE_INFORMATION );
- BIND_CONSTANT( RESPONSE_NO_CONTENT );
- BIND_CONSTANT( RESPONSE_RESET_CONTENT );
- BIND_CONSTANT( RESPONSE_PARTIAL_CONTENT );
- BIND_CONSTANT( RESPONSE_MULTI_STATUS );
- BIND_CONSTANT( RESPONSE_IM_USED );
+ BIND_CONSTANT(RESPONSE_OK);
+ BIND_CONSTANT(RESPONSE_CREATED);
+ BIND_CONSTANT(RESPONSE_ACCEPTED);
+ BIND_CONSTANT(RESPONSE_NON_AUTHORITATIVE_INFORMATION);
+ BIND_CONSTANT(RESPONSE_NO_CONTENT);
+ BIND_CONSTANT(RESPONSE_RESET_CONTENT);
+ BIND_CONSTANT(RESPONSE_PARTIAL_CONTENT);
+ BIND_CONSTANT(RESPONSE_MULTI_STATUS);
+ BIND_CONSTANT(RESPONSE_IM_USED);
// 3xx redirection
- BIND_CONSTANT( RESPONSE_MULTIPLE_CHOICES );
- BIND_CONSTANT( RESPONSE_MOVED_PERMANENTLY );
- BIND_CONSTANT( RESPONSE_FOUND );
- BIND_CONSTANT( RESPONSE_SEE_OTHER );
- BIND_CONSTANT( RESPONSE_NOT_MODIFIED );
- BIND_CONSTANT( RESPONSE_USE_PROXY );
- BIND_CONSTANT( RESPONSE_TEMPORARY_REDIRECT );
+ BIND_CONSTANT(RESPONSE_MULTIPLE_CHOICES);
+ BIND_CONSTANT(RESPONSE_MOVED_PERMANENTLY);
+ BIND_CONSTANT(RESPONSE_FOUND);
+ BIND_CONSTANT(RESPONSE_SEE_OTHER);
+ BIND_CONSTANT(RESPONSE_NOT_MODIFIED);
+ BIND_CONSTANT(RESPONSE_USE_PROXY);
+ BIND_CONSTANT(RESPONSE_TEMPORARY_REDIRECT);
// 4xx client error
- BIND_CONSTANT( RESPONSE_BAD_REQUEST );
- BIND_CONSTANT( RESPONSE_UNAUTHORIZED );
- BIND_CONSTANT( RESPONSE_PAYMENT_REQUIRED );
- BIND_CONSTANT( RESPONSE_FORBIDDEN );
- BIND_CONSTANT( RESPONSE_NOT_FOUND );
- BIND_CONSTANT( RESPONSE_METHOD_NOT_ALLOWED );
- BIND_CONSTANT( RESPONSE_NOT_ACCEPTABLE );
- BIND_CONSTANT( RESPONSE_PROXY_AUTHENTICATION_REQUIRED );
- BIND_CONSTANT( RESPONSE_REQUEST_TIMEOUT );
- BIND_CONSTANT( RESPONSE_CONFLICT );
- BIND_CONSTANT( RESPONSE_GONE );
- BIND_CONSTANT( RESPONSE_LENGTH_REQUIRED );
- BIND_CONSTANT( RESPONSE_PRECONDITION_FAILED );
- BIND_CONSTANT( RESPONSE_REQUEST_ENTITY_TOO_LARGE );
- BIND_CONSTANT( RESPONSE_REQUEST_URI_TOO_LONG );
- BIND_CONSTANT( RESPONSE_UNSUPPORTED_MEDIA_TYPE );
- BIND_CONSTANT( RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE );
- BIND_CONSTANT( RESPONSE_EXPECTATION_FAILED );
- BIND_CONSTANT( RESPONSE_UNPROCESSABLE_ENTITY );
- BIND_CONSTANT( RESPONSE_LOCKED );
- BIND_CONSTANT( RESPONSE_FAILED_DEPENDENCY );
- BIND_CONSTANT( RESPONSE_UPGRADE_REQUIRED );
+ BIND_CONSTANT(RESPONSE_BAD_REQUEST);
+ BIND_CONSTANT(RESPONSE_UNAUTHORIZED);
+ BIND_CONSTANT(RESPONSE_PAYMENT_REQUIRED);
+ BIND_CONSTANT(RESPONSE_FORBIDDEN);
+ BIND_CONSTANT(RESPONSE_NOT_FOUND);
+ BIND_CONSTANT(RESPONSE_METHOD_NOT_ALLOWED);
+ BIND_CONSTANT(RESPONSE_NOT_ACCEPTABLE);
+ BIND_CONSTANT(RESPONSE_PROXY_AUTHENTICATION_REQUIRED);
+ BIND_CONSTANT(RESPONSE_REQUEST_TIMEOUT);
+ BIND_CONSTANT(RESPONSE_CONFLICT);
+ BIND_CONSTANT(RESPONSE_GONE);
+ BIND_CONSTANT(RESPONSE_LENGTH_REQUIRED);
+ BIND_CONSTANT(RESPONSE_PRECONDITION_FAILED);
+ BIND_CONSTANT(RESPONSE_REQUEST_ENTITY_TOO_LARGE);
+ BIND_CONSTANT(RESPONSE_REQUEST_URI_TOO_LONG);
+ BIND_CONSTANT(RESPONSE_UNSUPPORTED_MEDIA_TYPE);
+ BIND_CONSTANT(RESPONSE_REQUESTED_RANGE_NOT_SATISFIABLE);
+ BIND_CONSTANT(RESPONSE_EXPECTATION_FAILED);
+ BIND_CONSTANT(RESPONSE_UNPROCESSABLE_ENTITY);
+ BIND_CONSTANT(RESPONSE_LOCKED);
+ BIND_CONSTANT(RESPONSE_FAILED_DEPENDENCY);
+ BIND_CONSTANT(RESPONSE_UPGRADE_REQUIRED);
// 5xx server error
- BIND_CONSTANT( RESPONSE_INTERNAL_SERVER_ERROR );
- BIND_CONSTANT( RESPONSE_NOT_IMPLEMENTED );
- BIND_CONSTANT( RESPONSE_BAD_GATEWAY );
- BIND_CONSTANT( RESPONSE_SERVICE_UNAVAILABLE );
- BIND_CONSTANT( RESPONSE_GATEWAY_TIMEOUT );
- BIND_CONSTANT( RESPONSE_HTTP_VERSION_NOT_SUPPORTED );
- BIND_CONSTANT( RESPONSE_INSUFFICIENT_STORAGE );
- BIND_CONSTANT( RESPONSE_NOT_EXTENDED );
-
+ BIND_CONSTANT(RESPONSE_INTERNAL_SERVER_ERROR);
+ BIND_CONSTANT(RESPONSE_NOT_IMPLEMENTED);
+ BIND_CONSTANT(RESPONSE_BAD_GATEWAY);
+ BIND_CONSTANT(RESPONSE_SERVICE_UNAVAILABLE);
+ BIND_CONSTANT(RESPONSE_GATEWAY_TIMEOUT);
+ BIND_CONSTANT(RESPONSE_HTTP_VERSION_NOT_SUPPORTED);
+ BIND_CONSTANT(RESPONSE_INSUFFICIENT_STORAGE);
+ BIND_CONSTANT(RESPONSE_NOT_EXTENDED);
}
void HTTPClient::set_read_chunk_size(int p_size) {
- ERR_FAIL_COND(p_size<256 || p_size>(1<<24));
- read_chunk_size=p_size;
+ ERR_FAIL_COND(p_size < 256 || p_size > (1 << 24));
+ read_chunk_size = p_size;
}
-String HTTPClient::query_string_from_dict(const Dictionary& p_dict) {
- String query = "";
- Array keys = p_dict.keys();
- for (int i = 0; i < keys.size(); ++i) {
- query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape();
- }
- query.erase(0, 1);
- return query;
+String HTTPClient::query_string_from_dict(const Dictionary &p_dict) {
+ String query = "";
+ Array keys = p_dict.keys();
+ for (int i = 0; i < keys.size(); ++i) {
+ query += "&" + String(keys[i]).http_escape() + "=" + String(p_dict[keys[i]]).http_escape();
+ }
+ query.erase(0, 1);
+ return query;
}
-HTTPClient::HTTPClient(){
+HTTPClient::HTTPClient() {
tcp_connection = StreamPeerTCP::create_ref();
resolving = IP::RESOLVER_INVALID_ID;
- status=STATUS_DISCONNECTED;
- conn_port=80;
- body_size=0;
- chunked=false;
- body_left=0;
- chunk_left=0;
- response_num=0;
- ssl=false;
- blocking=false;
- read_chunk_size=4096;
+ status = STATUS_DISCONNECTED;
+ conn_port = 80;
+ body_size = 0;
+ chunked = false;
+ body_left = 0;
+ chunk_left = 0;
+ response_num = 0;
+ ssl = false;
+ blocking = false;
+ read_chunk_size = 4096;
}
-HTTPClient::~HTTPClient(){
-
-
+HTTPClient::~HTTPClient() {
}
-
diff --git a/core/io/http_client.h b/core/io/http_client.h
index 4b0c1b730f..e2b0e9ccea 100644
--- a/core/io/http_client.h
+++ b/core/io/http_client.h
@@ -29,17 +29,16 @@
#ifndef HTTP_CLIENT_H
#define HTTP_CLIENT_H
+#include "io/ip.h"
#include "io/stream_peer.h"
#include "io/stream_peer_tcp.h"
-#include "io/ip.h"
#include "reference.h"
-
class HTTPClient : public Reference {
- GDCLASS(HTTPClient,Reference);
-public:
+ GDCLASS(HTTPClient, Reference);
+public:
enum ResponseCode {
// 1xx informational
@@ -131,7 +130,6 @@ public:
};
private:
-
Status status;
IP::ResolverID resolving;
int conn_port;
@@ -159,21 +157,19 @@ private:
Dictionary _get_response_headers_as_dictionary();
int read_chunk_size;
- Error _get_http_data(uint8_t* p_buffer, int p_bytes,int &r_received);
+ Error _get_http_data(uint8_t *p_buffer, int p_bytes, int &r_received);
public:
-
-
//Error connect_and_get(const String& p_url,bool p_verify_host=true); //connects to a full url and perform request
- Error connect_to_host(const String &p_host,int p_port,bool p_ssl=false,bool p_verify_host=true);
+ Error connect_to_host(const String &p_host, int p_port, bool p_ssl = false, bool p_verify_host = true);
- void set_connection(const Ref<StreamPeer>& p_connection);
+ void set_connection(const Ref<StreamPeer> &p_connection);
Ref<StreamPeer> get_connection() const;
- Error request_raw( Method p_method, const String& p_url, const Vector<String>& p_headers,const PoolVector<uint8_t>& p_body);
- Error request( Method p_method, const String& p_url, const Vector<String>& p_headers,const String& p_body=String());
- Error send_body_text(const String& p_body);
- Error send_body_data(const PoolByteArray& p_body);
+ Error request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body);
+ Error request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body = String());
+ Error send_body_text(const String &p_body);
+ Error send_body_data(const PoolByteArray &p_body);
void close();
@@ -194,7 +190,7 @@ public:
Error poll();
- String query_string_from_dict(const Dictionary& p_dict);
+ String query_string_from_dict(const Dictionary &p_dict);
HTTPClient();
~HTTPClient();
diff --git a/core/io/image_loader.cpp b/core/io/image_loader.cpp
index 2b01e865f4..5f88ca65e3 100644
--- a/core/io/image_loader.cpp
+++ b/core/io/image_loader.cpp
@@ -29,90 +29,78 @@
#include "image_loader.h"
#include "print_string.h"
-bool ImageFormatLoader::recognize(const String& p_extension) const {
-
+bool ImageFormatLoader::recognize(const String &p_extension) const {
List<String> extensions;
get_recognized_extensions(&extensions);
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
- if (E->get().nocasecmp_to(p_extension.get_extension())==0)
+ if (E->get().nocasecmp_to(p_extension.get_extension()) == 0)
return true;
}
return false;
}
-Error ImageLoader::load_image(String p_file,Image *p_image, FileAccess *p_custom) {
-
+Error ImageLoader::load_image(String p_file, Image *p_image, FileAccess *p_custom) {
- FileAccess *f=p_custom;
+ FileAccess *f = p_custom;
if (!f) {
Error err;
- f=FileAccess::open(p_file,FileAccess::READ,&err);
+ f = FileAccess::open(p_file, FileAccess::READ, &err);
if (!f) {
- ERR_PRINTS("Error opening file: "+p_file);
+ ERR_PRINTS("Error opening file: " + p_file);
return err;
}
}
String extension = p_file.get_extension();
-
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
if (!loader[i]->recognize(extension))
continue;
- Error err = loader[i]->load_image(p_image,f);
-
- if (err!=ERR_FILE_UNRECOGNIZED) {
+ Error err = loader[i]->load_image(p_image, f);
+ if (err != ERR_FILE_UNRECOGNIZED) {
if (!p_custom)
memdelete(f);
return err;
}
-
-
}
if (!p_custom)
memdelete(f);
return ERR_FILE_UNRECOGNIZED;
-
}
void ImageLoader::get_recognized_extensions(List<String> *p_extensions) {
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
loader[i]->get_recognized_extensions(p_extensions);
-
}
}
-bool ImageLoader::recognize(const String& p_extension) {
+bool ImageLoader::recognize(const String &p_extension) {
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
if (loader[i]->recognize(p_extension))
return true;
-
}
return false;
}
ImageFormatLoader *ImageLoader::loader[MAX_LOADERS];
-int ImageLoader::loader_count=0;
+int ImageLoader::loader_count = 0;
void ImageLoader::add_image_format_loader(ImageFormatLoader *p_loader) {
- ERR_FAIL_COND(loader_count >=MAX_LOADERS );
- loader[loader_count++]=p_loader;
+ ERR_FAIL_COND(loader_count >= MAX_LOADERS);
+ loader[loader_count++] = p_loader;
}
-
-
-
diff --git a/core/io/image_loader.h b/core/io/image_loader.h
index 4de7706ab0..b70170303d 100644
--- a/core/io/image_loader.h
+++ b/core/io/image_loader.h
@@ -30,14 +30,13 @@
#define IMAGE_LOADER_H
#include "image.h"
-#include "ustring.h"
-#include "os/file_access.h"
#include "list.h"
+#include "os/file_access.h"
+#include "ustring.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
/**
* @class ImageScanLineLoader
* @author Juan Linietsky <reduzio@gmail.com>
@@ -46,21 +45,19 @@
*/
class ImageLoader;
-
/**
* @class ImageLoader
* Base Class and singleton for loading images from disk
* Can load images in one go, or by scanline
*/
-
class ImageFormatLoader {
-friend class ImageLoader;
-protected:
- virtual Error load_image(Image *p_image,FileAccess *p_fileaccess)=0;
- virtual void get_recognized_extensions(List<String> *p_extensions) const=0;
- bool recognize(const String& p_extension) const;
+ friend class ImageLoader;
+protected:
+ virtual Error load_image(Image *p_image, FileAccess *p_fileaccess) = 0;
+ virtual void get_recognized_extensions(List<String> *p_extensions) const = 0;
+ bool recognize(const String &p_extension) const;
public:
virtual ~ImageFormatLoader() {}
@@ -69,23 +66,19 @@ public:
class ImageLoader {
enum {
- MAX_LOADERS=8
+ MAX_LOADERS = 8
};
static ImageFormatLoader *loader[MAX_LOADERS];
static int loader_count;
protected:
-
-
public:
-
- static Error load_image(String p_file,Image *p_image, FileAccess *p_custom=NULL);
- static void get_recognized_extensions(List<String> *p_extensions) ;
- static bool recognize(const String& p_extension) ;
+ static Error load_image(String p_file, Image *p_image, FileAccess *p_custom = NULL);
+ static void get_recognized_extensions(List<String> *p_extensions);
+ static bool recognize(const String &p_extension);
static void add_image_format_loader(ImageFormatLoader *p_loader);
-
};
#endif
diff --git a/core/io/ip.cpp b/core/io/ip.cpp
index d820273a14..6713963495 100644
--- a/core/io/ip.cpp
+++ b/core/io/ip.cpp
@@ -27,15 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "ip.h"
-#include "os/thread.h"
-#include "os/semaphore.h"
#include "hash_map.h"
+#include "os/semaphore.h"
+#include "os/thread.h"
VARIANT_ENUM_CAST(IP::ResolverStatus);
/************* RESOLVER ******************/
-
struct _IP_ResolverPrivate {
struct QueueItem {
@@ -49,7 +48,7 @@ struct _IP_ResolverPrivate {
status = IP::RESOLVER_STATUS_NONE;
response = IP_Address();
type = IP::TYPE_NONE;
- hostname="";
+ hostname = "";
};
QueueItem() {
@@ -61,8 +60,8 @@ struct _IP_ResolverPrivate {
IP::ResolverID find_empty_id() const {
- for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) {
- if (queue[i].status==IP::RESOLVER_STATUS_NONE)
+ for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) {
+ if (queue[i].status == IP::RESOLVER_STATUS_NONE)
return i;
}
return IP::RESOLVER_INVALID_ID;
@@ -70,39 +69,35 @@ struct _IP_ResolverPrivate {
Semaphore *sem;
- Thread* thread;
+ Thread *thread;
//Semaphore* semaphore;
bool thread_abort;
void resolve_queues() {
- for(int i=0;i<IP::RESOLVER_MAX_QUERIES;i++) {
+ for (int i = 0; i < IP::RESOLVER_MAX_QUERIES; i++) {
- if (queue[i].status!=IP::RESOLVER_STATUS_WAITING)
+ if (queue[i].status != IP::RESOLVER_STATUS_WAITING)
continue;
- queue[i].response=IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type);
+ queue[i].response = IP::get_singleton()->resolve_hostname(queue[i].hostname, queue[i].type);
if (!queue[i].response.is_valid())
- queue[i].status=IP::RESOLVER_STATUS_ERROR;
+ queue[i].status = IP::RESOLVER_STATUS_ERROR;
else
- queue[i].status=IP::RESOLVER_STATUS_DONE;
-
+ queue[i].status = IP::RESOLVER_STATUS_DONE;
}
}
-
static void _thread_function(void *self) {
- _IP_ResolverPrivate *ipr=(_IP_ResolverPrivate*)self;
+ _IP_ResolverPrivate *ipr = (_IP_ResolverPrivate *)self;
- while(!ipr->thread_abort) {
+ while (!ipr->thread_abort) {
ipr->sem->wait();
GLOBAL_LOCK_FUNCTION;
ipr->resolve_queues();
-
}
-
}
HashMap<String, IP_Address> cache;
@@ -110,12 +105,9 @@ struct _IP_ResolverPrivate {
static String get_cache_key(String p_hostname, IP::Type p_type) {
return itos(p_type) + p_hostname;
}
-
};
-
-
-IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) {
+IP_Address IP::resolve_hostname(const String &p_hostname, IP::Type p_type) {
GLOBAL_LOCK_FUNCTION;
@@ -124,30 +116,29 @@ IP_Address IP::resolve_hostname(const String& p_hostname, IP::Type p_type) {
return resolver->cache[key];
IP_Address res = _resolve_hostname(p_hostname, p_type);
- resolver->cache[key]=res;
+ resolver->cache[key] = res;
return res;
-
}
-IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Type p_type) {
+IP::ResolverID IP::resolve_hostname_queue_item(const String &p_hostname, IP::Type p_type) {
GLOBAL_LOCK_FUNCTION;
ResolverID id = resolver->find_empty_id();
- if (id==RESOLVER_INVALID_ID) {
+ if (id == RESOLVER_INVALID_ID) {
WARN_PRINT("Out of resolver queries");
return id;
}
String key = _IP_ResolverPrivate::get_cache_key(p_hostname, p_type);
- resolver->queue[id].hostname=p_hostname;
+ resolver->queue[id].hostname = p_hostname;
resolver->queue[id].type = p_type;
if (resolver->cache.has(key)) {
- resolver->queue[id].response=resolver->cache[key];
- resolver->queue[id].status=IP::RESOLVER_STATUS_DONE;
+ resolver->queue[id].response = resolver->cache[key];
+ resolver->queue[id].status = IP::RESOLVER_STATUS_DONE;
} else {
- resolver->queue[id].response=IP_Address();
- resolver->queue[id].status=IP::RESOLVER_STATUS_WAITING;
+ resolver->queue[id].response = IP_Address();
+ resolver->queue[id].status = IP::RESOLVER_STATUS_WAITING;
if (resolver->thread)
resolver->sem->post();
else
@@ -159,37 +150,33 @@ IP::ResolverID IP::resolve_hostname_queue_item(const String& p_hostname, IP::Typ
IP::ResolverStatus IP::get_resolve_item_status(ResolverID p_id) const {
- ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP::RESOLVER_STATUS_NONE);
+ ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP::RESOLVER_STATUS_NONE);
GLOBAL_LOCK_FUNCTION;
- ERR_FAIL_COND_V(resolver->queue[p_id].status==IP::RESOLVER_STATUS_NONE,IP::RESOLVER_STATUS_NONE);
+ ERR_FAIL_COND_V(resolver->queue[p_id].status == IP::RESOLVER_STATUS_NONE, IP::RESOLVER_STATUS_NONE);
return resolver->queue[p_id].status;
-
}
IP_Address IP::get_resolve_item_address(ResolverID p_id) const {
- ERR_FAIL_INDEX_V(p_id,IP::RESOLVER_MAX_QUERIES,IP_Address());
+ ERR_FAIL_INDEX_V(p_id, IP::RESOLVER_MAX_QUERIES, IP_Address());
GLOBAL_LOCK_FUNCTION;
- if (resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE) {
- ERR_EXPLAIN("Resolve of '"+resolver->queue[p_id].hostname+"'' didn't complete yet.");
- ERR_FAIL_COND_V(resolver->queue[p_id].status!=IP::RESOLVER_STATUS_DONE,IP_Address());
+ if (resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE) {
+ ERR_EXPLAIN("Resolve of '" + resolver->queue[p_id].hostname + "'' didn't complete yet.");
+ ERR_FAIL_COND_V(resolver->queue[p_id].status != IP::RESOLVER_STATUS_DONE, IP_Address());
}
-
return resolver->queue[p_id].response;
-
}
void IP::erase_resolve_item(ResolverID p_id) {
- ERR_FAIL_INDEX(p_id,IP::RESOLVER_MAX_QUERIES);
+ ERR_FAIL_INDEX(p_id, IP::RESOLVER_MAX_QUERIES);
GLOBAL_LOCK_FUNCTION;
- resolver->queue[p_id].status=IP::RESOLVER_STATUS_NONE;
-
+ resolver->queue[p_id].status = IP::RESOLVER_STATUS_NONE;
}
void IP::clear_cache(const String &p_hostname) {
@@ -209,7 +196,7 @@ Array IP::_get_local_addresses() const {
Array addresses;
List<IP_Address> ip_addresses;
get_local_addresses(&ip_addresses);
- for(List<IP_Address>::Element *E=ip_addresses.front();E;E=E->next()) {
+ for (List<IP_Address>::Element *E = ip_addresses.front(); E; E = E->next()) {
addresses.push_back(E->get());
}
@@ -218,87 +205,82 @@ Array IP::_get_local_addresses() const {
void IP::_bind_methods() {
- ClassDB::bind_method(D_METHOD("resolve_hostname","host","ip_type"),&IP::resolve_hostname,DEFVAL(IP::TYPE_ANY));
- ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item","host","ip_type"),&IP::resolve_hostname_queue_item,DEFVAL(IP::TYPE_ANY));
- ClassDB::bind_method(D_METHOD("get_resolve_item_status","id"),&IP::get_resolve_item_status);
- ClassDB::bind_method(D_METHOD("get_resolve_item_address","id"),&IP::get_resolve_item_address);
- ClassDB::bind_method(D_METHOD("erase_resolve_item","id"),&IP::erase_resolve_item);
- ClassDB::bind_method(D_METHOD("get_local_addresses"),&IP::_get_local_addresses);
- ClassDB::bind_method(D_METHOD("clear_cache"),&IP::clear_cache, DEFVAL(""));
-
- BIND_CONSTANT( RESOLVER_STATUS_NONE );
- BIND_CONSTANT( RESOLVER_STATUS_WAITING );
- BIND_CONSTANT( RESOLVER_STATUS_DONE );
- BIND_CONSTANT( RESOLVER_STATUS_ERROR );
-
- BIND_CONSTANT( RESOLVER_MAX_QUERIES );
- BIND_CONSTANT( RESOLVER_INVALID_ID );
-
- BIND_CONSTANT( TYPE_NONE );
- BIND_CONSTANT( TYPE_IPV4 );
- BIND_CONSTANT( TYPE_IPV6 );
- BIND_CONSTANT( TYPE_ANY );
+ ClassDB::bind_method(D_METHOD("resolve_hostname", "host", "ip_type"), &IP::resolve_hostname, DEFVAL(IP::TYPE_ANY));
+ ClassDB::bind_method(D_METHOD("resolve_hostname_queue_item", "host", "ip_type"), &IP::resolve_hostname_queue_item, DEFVAL(IP::TYPE_ANY));
+ ClassDB::bind_method(D_METHOD("get_resolve_item_status", "id"), &IP::get_resolve_item_status);
+ ClassDB::bind_method(D_METHOD("get_resolve_item_address", "id"), &IP::get_resolve_item_address);
+ ClassDB::bind_method(D_METHOD("erase_resolve_item", "id"), &IP::erase_resolve_item);
+ ClassDB::bind_method(D_METHOD("get_local_addresses"), &IP::_get_local_addresses);
+ ClassDB::bind_method(D_METHOD("clear_cache"), &IP::clear_cache, DEFVAL(""));
+
+ BIND_CONSTANT(RESOLVER_STATUS_NONE);
+ BIND_CONSTANT(RESOLVER_STATUS_WAITING);
+ BIND_CONSTANT(RESOLVER_STATUS_DONE);
+ BIND_CONSTANT(RESOLVER_STATUS_ERROR);
+
+ BIND_CONSTANT(RESOLVER_MAX_QUERIES);
+ BIND_CONSTANT(RESOLVER_INVALID_ID);
+
+ BIND_CONSTANT(TYPE_NONE);
+ BIND_CONSTANT(TYPE_IPV4);
+ BIND_CONSTANT(TYPE_IPV6);
+ BIND_CONSTANT(TYPE_ANY);
}
+IP *IP::singleton = NULL;
-IP*IP::singleton=NULL;
-
-IP* IP::get_singleton() {
+IP *IP::get_singleton() {
return singleton;
}
+IP *(*IP::_create)() = NULL;
-IP* (*IP::_create)()=NULL;
+IP *IP::create() {
-IP* IP::create() {
-
- ERR_FAIL_COND_V(singleton,NULL);
- ERR_FAIL_COND_V(!_create,NULL);
+ ERR_FAIL_COND_V(singleton, NULL);
+ ERR_FAIL_COND_V(!_create, NULL);
return _create();
}
IP::IP() {
- singleton=this;
- resolver = memnew( _IP_ResolverPrivate );
- resolver->sem=NULL;
+ singleton = this;
+ resolver = memnew(_IP_ResolverPrivate);
+ resolver->sem = NULL;
#ifndef NO_THREADS
//resolver->sem = Semaphore::create();
- resolver->sem=NULL;
+ resolver->sem = NULL;
if (resolver->sem) {
- resolver->thread_abort=false;
+ resolver->thread_abort = false;
- resolver->thread = Thread::create( _IP_ResolverPrivate::_thread_function,resolver );
+ resolver->thread = Thread::create(_IP_ResolverPrivate::_thread_function, resolver);
if (!resolver->thread)
memdelete(resolver->sem); //wtf
} else {
- resolver->thread=NULL;
+ resolver->thread = NULL;
}
#else
resolver->sem = NULL;
- resolver->thread=NULL;
+ resolver->thread = NULL;
#endif
-
-
}
IP::~IP() {
#ifndef NO_THREADS
if (resolver->thread) {
- resolver->thread_abort=true;
+ resolver->thread_abort = true;
resolver->sem->post();
Thread::wait_to_finish(resolver->thread);
- memdelete( resolver->thread );
- memdelete( resolver->sem);
+ memdelete(resolver->thread);
+ memdelete(resolver->sem);
}
memdelete(resolver);
#endif
-
}
diff --git a/core/io/ip.h b/core/io/ip.h
index 3e028f2613..052a0e08cc 100644
--- a/core/io/ip.h
+++ b/core/io/ip.h
@@ -29,17 +29,16 @@
#ifndef IP_H
#define IP_H
-
-#include "os/os.h"
#include "io/ip_address.h"
+#include "os/os.h"
struct _IP_ResolverPrivate;
class IP : public Object {
- GDCLASS( IP, Object );
+ GDCLASS(IP, Object);
OBJ_CATEGORY("Networking");
-public:
+public:
enum ResolverStatus {
RESOLVER_STATUS_NONE,
@@ -58,47 +57,40 @@ public:
enum {
RESOLVER_MAX_QUERIES = 32,
- RESOLVER_INVALID_ID=-1
+ RESOLVER_INVALID_ID = -1
};
-
typedef int ResolverID;
-
private:
-
_IP_ResolverPrivate *resolver;
-protected:
- static IP*singleton;
+protected:
+ static IP *singleton;
static void _bind_methods();
- virtual IP_Address _resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY)=0;
+ virtual IP_Address _resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY) = 0;
Array _get_local_addresses() const;
- static IP* (*_create)();
-public:
-
+ static IP *(*_create)();
-
- IP_Address resolve_hostname(const String& p_hostname, Type p_type = TYPE_ANY);
+public:
+ IP_Address resolve_hostname(const String &p_hostname, Type p_type = TYPE_ANY);
// async resolver hostname
- ResolverID resolve_hostname_queue_item(const String& p_hostname, Type p_type = TYPE_ANY);
+ ResolverID resolve_hostname_queue_item(const String &p_hostname, Type p_type = TYPE_ANY);
ResolverStatus get_resolve_item_status(ResolverID p_id) const;
IP_Address get_resolve_item_address(ResolverID p_id) const;
- virtual void get_local_addresses(List<IP_Address> *r_addresses) const=0;
+ virtual void get_local_addresses(List<IP_Address> *r_addresses) const = 0;
void erase_resolve_item(ResolverID p_id);
- void clear_cache(const String& p_hostname = "");
+ void clear_cache(const String &p_hostname = "");
- static IP* get_singleton();
+ static IP *get_singleton();
- static IP* create();
+ static IP *create();
IP();
~IP();
-
-
};
VARIANT_ENUM_CAST(IP::Type);
diff --git a/core/io/ip_address.cpp b/core/io/ip_address.cpp
index 69c7df619d..fa0eab4f0d 100644
--- a/core/io/ip_address.cpp
+++ b/core/io/ip_address.cpp
@@ -33,32 +33,32 @@ IP_Address::operator Variant() const {
return operator String();
}*/
-#include <string.h>
#include <stdio.h>
+#include <string.h>
IP_Address::operator String() const {
- if(!valid)
+ if (!valid)
return "";
- if(is_ipv4())
+ if (is_ipv4())
// IPv4 address mapped to IPv6
- return itos(field8[12])+"."+itos(field8[13])+"."+itos(field8[14])+"."+itos(field8[15]);
+ return itos(field8[12]) + "." + itos(field8[13]) + "." + itos(field8[14]) + "." + itos(field8[15]);
String ret;
- for (int i=0; i<8; i++) {
+ for (int i = 0; i < 8; i++) {
if (i > 0)
ret = ret + ":";
- uint16_t num = (field8[i*2] << 8) + field8[i*2+1];
+ uint16_t num = (field8[i * 2] << 8) + field8[i * 2 + 1];
ret = ret + String::num_int64(num, 16);
};
return ret;
}
-static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) {
+static void _parse_hex(const String &p_string, int p_start, uint8_t *p_dst) {
uint16_t ret = 0;
- for (int i=p_start; i<p_start + 4; i++) {
+ for (int i = p_start; i < p_start + 4; i++) {
if (i >= p_string.length()) {
break;
@@ -87,17 +87,17 @@ static void _parse_hex(const String& p_string, int p_start, uint8_t* p_dst) {
p_dst[1] = ret & 0xff;
};
-void IP_Address::_parse_ipv6(const String& p_string) {
+void IP_Address::_parse_ipv6(const String &p_string) {
static const int parts_total = 8;
- int parts[parts_total] = {0};
+ int parts[parts_total] = { 0 };
int parts_count = 0;
bool part_found = false;
bool part_skip = false;
bool part_ipv4 = false;
int parts_idx = 0;
- for (int i=0; i<p_string.length(); i++) {
+ for (int i = 0; i < p_string.length(); i++) {
CharType c = p_string[i];
if (c == ':') {
@@ -133,26 +133,25 @@ void IP_Address::_parse_ipv6(const String& p_string) {
};
int idx = 0;
- for (int i=0; i<parts_idx; i++) {
+ for (int i = 0; i < parts_idx; i++) {
if (parts[i] == -1) {
- for (int j=0; j<parts_extra; j++) {
+ for (int j = 0; j < parts_extra; j++) {
field16[idx++] = 0;
};
continue;
};
if (part_ipv4 && i == parts_idx - 1) {
- _parse_ipv4(p_string, parts[i], (uint8_t*)&field16[idx]); // should be the last one
+ _parse_ipv4(p_string, parts[i], (uint8_t *)&field16[idx]); // should be the last one
} else {
- _parse_hex(p_string, parts[i], (uint8_t*)&(field16[idx++]));
+ _parse_hex(p_string, parts[i], (uint8_t *)&(field16[idx++]));
};
};
-
};
-void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret) {
+void IP_Address::_parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret) {
String ip;
if (p_start != 0) {
@@ -162,12 +161,12 @@ void IP_Address::_parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret
};
int slices = ip.get_slice_count(".");
- if (slices!=4) {
- ERR_EXPLAIN("Invalid IP Address String: "+ip);
+ if (slices != 4) {
+ ERR_EXPLAIN("Invalid IP Address String: " + ip);
ERR_FAIL();
}
- for(int i=0;i<4;i++) {
- p_ret[i]=ip.get_slicec('.',i).to_int();
+ for (int i = 0; i < 4; i++) {
+ p_ret[i] = ip.get_slicec('.', i).to_int();
}
};
@@ -178,34 +177,34 @@ void IP_Address::clear() {
wildcard = false;
};
-bool IP_Address::is_ipv4() const{
- return (field32[0]==0 && field32[1]==0 && field16[4]==0 && field16[5]==0xffff);
+bool IP_Address::is_ipv4() const {
+ return (field32[0] == 0 && field32[1] == 0 && field16[4] == 0 && field16[5] == 0xffff);
}
-const uint8_t *IP_Address::get_ipv4() const{
- ERR_FAIL_COND_V(!is_ipv4(),0);
+const uint8_t *IP_Address::get_ipv4() const {
+ ERR_FAIL_COND_V(!is_ipv4(), 0);
return &(field8[12]);
}
void IP_Address::set_ipv4(const uint8_t *p_ip) {
clear();
valid = true;
- field16[5]=0xffff;
- field32[3]=*((const uint32_t *)p_ip);
+ field16[5] = 0xffff;
+ field32[3] = *((const uint32_t *)p_ip);
}
-const uint8_t *IP_Address::get_ipv6() const{
+const uint8_t *IP_Address::get_ipv6() const {
return field8;
}
void IP_Address::set_ipv6(const uint8_t *p_buf) {
clear();
valid = true;
- for (int i=0; i<16; i++)
+ for (int i = 0; i < 16; i++)
field8[i] = p_buf[i];
}
-IP_Address::IP_Address(const String& p_string) {
+IP_Address::IP_Address(const String &p_string) {
clear();
@@ -229,7 +228,7 @@ IP_Address::IP_Address(const String& p_string) {
}
}
-_FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) {
+_FORCE_INLINE_ static void _32_to_buf(uint8_t *p_dst, uint32_t p_n) {
p_dst[0] = (p_n >> 24) & 0xff;
p_dst[1] = (p_n >> 16) & 0xff;
@@ -237,17 +236,17 @@ _FORCE_INLINE_ static void _32_to_buf(uint8_t* p_dst, uint32_t p_n) {
p_dst[3] = (p_n >> 0) & 0xff;
};
-IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6) {
+IP_Address::IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6) {
clear();
valid = true;
if (!is_v6) {
// Mapped to IPv6
- field16[5]=0xffff;
- field8[12]=p_a;
- field8[13]=p_b;
- field8[14]=p_c;
- field8[15]=p_d;
+ field16[5] = 0xffff;
+ field8[12] = p_a;
+ field8[13] = p_b;
+ field8[14] = p_c;
+ field8[15] = p_d;
} else {
_32_to_buf(&field8[0], p_a);
@@ -255,5 +254,4 @@ IP_Address::IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool
_32_to_buf(&field8[8], p_c);
_32_to_buf(&field8[12], p_d);
}
-
}
diff --git a/core/io/ip_address.h b/core/io/ip_address.h
index 257836601a..52d6974d5e 100644
--- a/core/io/ip_address.h
+++ b/core/io/ip_address.h
@@ -34,7 +34,6 @@
struct IP_Address {
private:
-
union {
uint8_t field8[16];
uint16_t field16[8];
@@ -45,31 +44,31 @@ private:
bool wildcard;
protected:
- void _parse_ipv6(const String& p_string);
- void _parse_ipv4(const String& p_string, int p_start, uint8_t* p_ret);
+ void _parse_ipv6(const String &p_string);
+ void _parse_ipv4(const String &p_string, int p_start, uint8_t *p_ret);
public:
//operator Variant() const;
- bool operator==(const IP_Address& p_ip) const {
+ bool operator==(const IP_Address &p_ip) const {
if (p_ip.valid != valid) return false;
if (!valid) return false;
- for (int i=0; i<4; i++)
+ for (int i = 0; i < 4; i++)
if (field32[i] != p_ip.field32[i])
return false;
return true;
}
- bool operator!=(const IP_Address& p_ip) const {
+ bool operator!=(const IP_Address &p_ip) const {
if (p_ip.valid != valid) return true;
if (!valid) return true;
- for (int i=0; i<4; i++)
+ for (int i = 0; i < 4; i++)
if (field32[i] != p_ip.field32[i])
return true;
return false;
}
void clear();
- bool is_wildcard() const {return wildcard;}
- bool is_valid() const {return valid;}
+ bool is_wildcard() const { return wildcard; }
+ bool is_valid() const { return valid; }
bool is_ipv4() const;
const uint8_t *get_ipv4() const;
void set_ipv4(const uint8_t *p_ip);
@@ -78,11 +77,9 @@ public:
void set_ipv6(const uint8_t *buf);
operator String() const;
- IP_Address(const String& p_string);
- IP_Address(uint32_t p_a,uint32_t p_b,uint32_t p_c,uint32_t p_d, bool is_v6=false);
+ IP_Address(const String &p_string);
+ IP_Address(uint32_t p_a, uint32_t p_b, uint32_t p_c, uint32_t p_d, bool is_v6 = false);
IP_Address() { clear(); }
};
-
-
#endif // IP_ADDRESS_H
diff --git a/core/io/json.cpp b/core/io/json.cpp
index 5ade25aab4..98d48ce4ae 100644
--- a/core/io/json.cpp
+++ b/core/io/json.cpp
@@ -29,7 +29,7 @@
#include "json.h"
#include "print_string.h"
-const char * JSON::tk_name[TK_MAX] = {
+const char *JSON::tk_name[TK_MAX] = {
"'{'",
"'}'",
"'['",
@@ -42,14 +42,12 @@ const char * JSON::tk_name[TK_MAX] = {
"EOF",
};
+String JSON::_print_var(const Variant &p_var) {
-
-String JSON::_print_var(const Variant& p_var) {
-
- switch(p_var.get_type()) {
+ switch (p_var.get_type()) {
case Variant::NIL: return "null";
- case Variant::BOOL: return p_var.operator bool() ? "true": "false";
+ case Variant::BOOL: return p_var.operator bool() ? "true" : "false";
case Variant::INT: return itos(p_var);
case Variant::REAL: return rtos(p_var);
case Variant::POOL_INT_ARRAY:
@@ -59,12 +57,12 @@ String JSON::_print_var(const Variant& p_var) {
String s = "[";
Array a = p_var;
- for(int i=0;i<a.size();i++) {
- if (i>0)
- s+=", ";
- s+=_print_var(a[i]);
+ for (int i = 0; i < a.size(); i++) {
+ if (i > 0)
+ s += ", ";
+ s += _print_var(a[i]);
}
- s+="]";
+ s += "]";
return s;
};
case Variant::DICTIONARY: {
@@ -74,34 +72,31 @@ String JSON::_print_var(const Variant& p_var) {
List<Variant> keys;
d.get_key_list(&keys);
- for (List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
- if (E!=keys.front())
- s+=", ";
- s+=_print_var(String(E->get()));
- s+=":";
- s+=_print_var(d[E->get()]);
+ if (E != keys.front())
+ s += ", ";
+ s += _print_var(String(E->get()));
+ s += ":";
+ s += _print_var(d[E->get()]);
}
- s+="}";
+ s += "}";
return s;
};
- default: return "\""+String(p_var).json_escape()+"\"";
-
+ default: return "\"" + String(p_var).json_escape() + "\"";
}
-
}
-String JSON::print(const Variant& p_var) {
+String JSON::print(const Variant &p_var) {
return _print_var(p_var);
}
-
-Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) {
+Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) {
while (p_len > 0) {
- switch(p_str[idx]) {
+ switch (p_str[idx]) {
case '\n': {
@@ -110,42 +105,42 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke
break;
};
case 0: {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
} break;
case '{': {
- r_token.type=TK_CURLY_BRACKET_OPEN;
+ r_token.type = TK_CURLY_BRACKET_OPEN;
idx++;
return OK;
};
case '}': {
- r_token.type=TK_CURLY_BRACKET_CLOSE;
+ r_token.type = TK_CURLY_BRACKET_CLOSE;
idx++;
return OK;
};
case '[': {
- r_token.type=TK_BRACKET_OPEN;
+ r_token.type = TK_BRACKET_OPEN;
idx++;
return OK;
};
case ']': {
- r_token.type=TK_BRACKET_CLOSE;
+ r_token.type = TK_BRACKET_CLOSE;
idx++;
return OK;
};
case ':': {
- r_token.type=TK_COLON;
+ r_token.type = TK_COLON;
idx++;
return OK;
};
case ',': {
- r_token.type=TK_COMMA;
+ r_token.type = TK_COMMA;
idx++;
return OK;
};
@@ -153,66 +148,62 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke
idx++;
String str;
- while(true) {
- if (p_str[idx]==0) {
- r_err_str="Unterminated String";
+ while (true) {
+ if (p_str[idx] == 0) {
+ r_err_str = "Unterminated String";
return ERR_PARSE_ERROR;
- } else if (p_str[idx]=='"') {
+ } else if (p_str[idx] == '"') {
idx++;
break;
- } else if (p_str[idx]=='\\') {
+ } else if (p_str[idx] == '\\') {
//escaped characters...
idx++;
CharType next = p_str[idx];
- if (next==0) {
- r_err_str="Unterminated String";
- return ERR_PARSE_ERROR;
+ if (next == 0) {
+ r_err_str = "Unterminated String";
+ return ERR_PARSE_ERROR;
}
- CharType res=0;
+ CharType res = 0;
- switch(next) {
+ 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': {
//hexnumbarh - oct is deprecated
-
- for(int j=0;j<4;j++) {
- CharType c = p_str[idx+j+1];
- if (c==0) {
- r_err_str="Unterminated String";
+ for (int j = 0; j < 4; j++) {
+ CharType c = p_str[idx + j + 1];
+ if (c == 0) {
+ r_err_str = "Unterminated String";
return ERR_PARSE_ERROR;
}
- if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
- r_err_str="Malformed hex constant in string";
+ r_err_str = "Malformed hex constant in string";
return ERR_PARSE_ERROR;
}
CharType v;
- 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;
+ 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 {
ERR_PRINT("BUG");
- v=0;
+ v = 0;
}
- res<<=4;
- res|=v;
-
-
+ res <<= 4;
+ res |= v;
}
- idx+=4; //will add at the end anyway
-
+ idx += 4; //will add at the end anyway
} break;
//case '\"': res='\"'; break;
@@ -225,250 +216,232 @@ Error JSON::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_toke
} break;
}
- str+=res;
+ str += res;
} else {
- if (p_str[idx]=='\n')
+ if (p_str[idx] == '\n')
line++;
- str+=p_str[idx];
+ str += p_str[idx];
}
idx++;
}
- r_token.type=TK_STRING;
- r_token.value=str;
+ r_token.type = TK_STRING;
+ r_token.value = str;
return OK;
} break;
default: {
- if (p_str[idx]<=32) {
+ if (p_str[idx] <= 32) {
idx++;
break;
}
- if (p_str[idx]=='-' || (p_str[idx]>='0' && p_str[idx]<='9')) {
+ if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) {
//a number
const CharType *rptr;
- double number = String::to_double(&p_str[idx],&rptr);
- idx+=(rptr - &p_str[idx]);
- r_token.type=TK_NUMBER;
- r_token.value=number;
+ double number = String::to_double(&p_str[idx], &rptr);
+ idx += (rptr - &p_str[idx]);
+ r_token.type = TK_NUMBER;
+ r_token.value = number;
return OK;
- } else if ((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) {
+ } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
String id;
- while((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) {
+ while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
- id+=p_str[idx];
+ id += p_str[idx];
idx++;
}
- r_token.type=TK_IDENTIFIER;
- r_token.value=id;
+ r_token.type = TK_IDENTIFIER;
+ r_token.value = id;
return OK;
} else {
- r_err_str="Unexpected character.";
+ r_err_str = "Unexpected character.";
return ERR_PARSE_ERROR;
}
}
-
}
}
return ERR_PARSE_ERROR;
}
+Error JSON::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
-
-Error JSON::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) {
-
-
- if (token.type==TK_CURLY_BRACKET_OPEN) {
+ if (token.type == TK_CURLY_BRACKET_OPEN) {
Dictionary d;
- Error err = _parse_object(d,p_str,index,p_len,line,r_err_str);
+ Error err = _parse_object(d, p_str, index, p_len, line, r_err_str);
if (err)
return err;
- value=d;
+ value = d;
return OK;
- } else if (token.type==TK_BRACKET_OPEN) {
+ } else if (token.type == TK_BRACKET_OPEN) {
Array a;
- Error err = _parse_array(a,p_str,index,p_len,line,r_err_str);
+ Error err = _parse_array(a, p_str, index, p_len, line, r_err_str);
if (err)
return err;
- value=a;
+ value = a;
return OK;
- } else if (token.type==TK_IDENTIFIER) {
+ } else if (token.type == TK_IDENTIFIER) {
String id = token.value;
- if (id=="true")
- value=true;
- else if (id=="false")
- value=false;
- else if (id=="null")
- value=Variant();
+ if (id == "true")
+ value = true;
+ else if (id == "false")
+ value = false;
+ else if (id == "null")
+ value = Variant();
else {
- r_err_str="Expected 'true','false' or 'null', got '"+id+"'.";
+ r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
return ERR_PARSE_ERROR;
}
return OK;
- } else if (token.type==TK_NUMBER) {
+ } else if (token.type == TK_NUMBER) {
- value=token.value;
+ value = token.value;
return OK;
- } else if (token.type==TK_STRING) {
+ } else if (token.type == TK_STRING) {
- value=token.value;
+ value = token.value;
return OK;
} else {
- r_err_str="Expected value, got "+String(tk_name[token.type])+".";
+ r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
return ERR_PARSE_ERROR;
}
return ERR_PARSE_ERROR;
}
-
-Error JSON::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) {
+Error JSON::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
Token token;
- bool need_comma=false;
-
+ bool need_comma = false;
- while(index<p_len) {
+ while (index < p_len) {
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_BRACKET_CLOSE) {
+ if (token.type == TK_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected ','";
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
Variant v;
- err = _parse_value(v,token,p_str,index,p_len,line,r_err_str);
+ err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
if (err)
return err;
array.push_back(v);
- need_comma=true;
-
+ need_comma = true;
}
return ERR_PARSE_ERROR;
-
}
-Error JSON::_parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str) {
+Error JSON::_parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str) {
- bool at_key=true;
+ bool at_key = true;
String key;
Token token;
- bool need_comma=false;
-
-
- while(index<p_len) {
+ bool need_comma = false;
+ while (index < p_len) {
if (at_key) {
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_CURLY_BRACKET_CLOSE) {
+ if (token.type == TK_CURLY_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected '}' or ','";
+ r_err_str = "Expected '}' or ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
- if (token.type!=TK_STRING) {
-
+ if (token.type != TK_STRING) {
- r_err_str="Expected key";
+ r_err_str = "Expected key";
return ERR_PARSE_ERROR;
}
- key=token.value;
- err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ key = token.value;
+ err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type!=TK_COLON) {
+ if (token.type != TK_COLON) {
- r_err_str="Expected ':'";
+ r_err_str = "Expected ':'";
return ERR_PARSE_ERROR;
}
- at_key=false;
+ at_key = false;
} else {
-
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
Variant v;
- err = _parse_value(v,token,p_str,index,p_len,line,r_err_str);
+ err = _parse_value(v, token, p_str, index, p_len, line, r_err_str);
if (err)
return err;
- object[key]=v;
- need_comma=true;
- at_key=true;
+ object[key] = v;
+ need_comma = true;
+ at_key = true;
}
}
return ERR_PARSE_ERROR;
}
-
-Error JSON::parse(const String& p_json, Variant &r_ret, String &r_err_str, int &r_err_line) {
-
+Error JSON::parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line) {
const CharType *str = p_json.ptr();
int idx = 0;
int len = p_json.length();
Token token;
- r_err_line=0;
+ r_err_line = 0;
String aux_key;
- Error err = _get_token(str,idx,len,token,r_err_line,r_err_str);
+ Error err = _get_token(str, idx, len, token, r_err_line, r_err_str);
if (err)
return err;
- err = _parse_value(r_ret,token,str,idx,len,r_err_line,r_err_str);
+ err = _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str);
return err;
-
-
}
-
-
diff --git a/core/io/json.h b/core/io/json.h
index 97457d223e..afd97c85b5 100644
--- a/core/io/json.h
+++ b/core/io/json.h
@@ -29,11 +29,8 @@
#ifndef JSON_H
#define JSON_H
-
-
#include "variant.h"
-
class JSON {
enum TokenType {
@@ -64,18 +61,18 @@ class JSON {
Variant value;
};
- static const char * tk_name[TK_MAX];
+ static const char *tk_name[TK_MAX];
- static String _print_var(const Variant& p_var);
+ static String _print_var(const Variant &p_var);
- static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str);
- static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str);
- static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str);
- static Error _parse_object(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str);
+ static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str);
+ static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str);
+ static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str);
+ static Error _parse_object(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str);
public:
static String print(const Variant &p_var);
- static Error parse(const String& p_json,Variant& r_ret,String &r_err_str,int &r_err_line);
+ static Error parse(const String &p_json, Variant &r_ret, String &r_err_str, int &r_err_line);
};
#endif // JSON_H
diff --git a/core/io/marshalls.cpp b/core/io/marshalls.cpp
index a8c1cd0a10..927ce31744 100644
--- a/core/io/marshalls.cpp
+++ b/core/io/marshalls.cpp
@@ -27,99 +27,96 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "marshalls.h"
-#include "print_string.h"
#include "os/keyboard.h"
+#include "print_string.h"
#include <stdio.h>
+#define ENCODE_MASK 0xFF
+#define ENCODE_FLAG_64 1 << 16
-#define ENCODE_MASK 0xFF
-#define ENCODE_FLAG_64 1<<16
+Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) {
-Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len) {
+ const uint8_t *buf = p_buffer;
+ int len = p_len;
- const uint8_t * buf=p_buffer;
- int len=p_len;
+ if (len < 4) {
- if (len<4) {
-
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
}
+ uint32_t type = decode_uint32(buf);
- uint32_t type=decode_uint32(buf);
-
- ERR_FAIL_COND_V((type&ENCODE_MASK)>=Variant::VARIANT_MAX,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V((type & ENCODE_MASK) >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
if (r_len)
- *r_len=4;
+ *r_len = 4;
- switch(type&ENCODE_MASK) {
+ switch (type & ENCODE_MASK) {
case Variant::NIL: {
- r_variant=Variant();
+ r_variant = Variant();
} break;
case Variant::BOOL: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
bool val = decode_uint32(buf);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
} break;
case Variant::INT: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
- if (type&ENCODE_FLAG_64) {
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
+ if (type & ENCODE_FLAG_64) {
int64_t val = decode_uint64(buf);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=8;
+ (*r_len) += 8;
} else {
int32_t val = decode_uint32(buf);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
}
} break;
case Variant::REAL: {
- ERR_FAIL_COND_V(len<(int)4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4, ERR_INVALID_DATA);
- if (type&ENCODE_FLAG_64) {
+ if (type & ENCODE_FLAG_64) {
double val = decode_double(buf);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=8;
+ (*r_len) += 8;
} else {
float val = decode_float(buf);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
}
} break;
case Variant::STRING: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t strlen = decode_uint32(buf);
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA);
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA);
String str;
- str.parse_utf8((const char*)buf,strlen);
- r_variant=str;
+ str.parse_utf8((const char *)buf, strlen);
+ r_variant = str;
if (r_len) {
- if (strlen%4)
- (*r_len)+=4-strlen%4;
- (*r_len)+=4+strlen;
-
+ if (strlen % 4)
+ (*r_len) += 4 - strlen % 4;
+ (*r_len) += 4 + strlen;
}
} break;
@@ -127,268 +124,262 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
case Variant::VECTOR2: {
- ERR_FAIL_COND_V(len<(int)4*2,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 2, ERR_INVALID_DATA);
Vector2 val;
- val.x=decode_float(&buf[0]);
- val.y=decode_float(&buf[4]);
- r_variant=val;
+ val.x = decode_float(&buf[0]);
+ val.y = decode_float(&buf[4]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*2;
+ (*r_len) += 4 * 2;
- } break; // 5
+ } break; // 5
case Variant::RECT2: {
- ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA);
Rect2 val;
- val.pos.x=decode_float(&buf[0]);
- val.pos.y=decode_float(&buf[4]);
- val.size.x=decode_float(&buf[8]);
- val.size.y=decode_float(&buf[12]);
- r_variant=val;
+ val.pos.x = decode_float(&buf[0]);
+ val.pos.y = decode_float(&buf[4]);
+ val.size.x = decode_float(&buf[8]);
+ val.size.y = decode_float(&buf[12]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*4;
+ (*r_len) += 4 * 4;
} break;
case Variant::VECTOR3: {
- ERR_FAIL_COND_V(len<(int)4*3,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 3, ERR_INVALID_DATA);
Vector3 val;
- val.x=decode_float(&buf[0]);
- val.y=decode_float(&buf[4]);
- val.z=decode_float(&buf[8]);
- r_variant=val;
+ val.x = decode_float(&buf[0]);
+ val.y = decode_float(&buf[4]);
+ val.z = decode_float(&buf[8]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*3;
+ (*r_len) += 4 * 3;
} break;
case Variant::TRANSFORM2D: {
- ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA);
Transform2D val;
- for(int i=0;i<3;i++) {
- for(int j=0;j<2;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 2; j++) {
- val.elements[i][j]=decode_float(&buf[(i*2+j)*4]);
+ val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]);
}
}
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4*6;
+ (*r_len) += 4 * 6;
} break;
case Variant::PLANE: {
- ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA);
Plane val;
- val.normal.x=decode_float(&buf[0]);
- val.normal.y=decode_float(&buf[4]);
- val.normal.z=decode_float(&buf[8]);
- val.d=decode_float(&buf[12]);
- r_variant=val;
+ val.normal.x = decode_float(&buf[0]);
+ val.normal.y = decode_float(&buf[4]);
+ val.normal.z = decode_float(&buf[8]);
+ val.d = decode_float(&buf[12]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*4;
+ (*r_len) += 4 * 4;
} break;
case Variant::QUAT: {
- ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA);
Quat val;
- val.x=decode_float(&buf[0]);
- val.y=decode_float(&buf[4]);
- val.z=decode_float(&buf[8]);
- val.w=decode_float(&buf[12]);
- r_variant=val;
+ val.x = decode_float(&buf[0]);
+ val.y = decode_float(&buf[4]);
+ val.z = decode_float(&buf[8]);
+ val.w = decode_float(&buf[12]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*4;
+ (*r_len) += 4 * 4;
} break;
case Variant::RECT3: {
- ERR_FAIL_COND_V(len<(int)4*6,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 6, ERR_INVALID_DATA);
Rect3 val;
- val.pos.x=decode_float(&buf[0]);
- val.pos.y=decode_float(&buf[4]);
- val.pos.z=decode_float(&buf[8]);
- val.size.x=decode_float(&buf[12]);
- val.size.y=decode_float(&buf[16]);
- val.size.z=decode_float(&buf[20]);
- r_variant=val;
+ val.pos.x = decode_float(&buf[0]);
+ val.pos.y = decode_float(&buf[4]);
+ val.pos.z = decode_float(&buf[8]);
+ val.size.x = decode_float(&buf[12]);
+ val.size.y = decode_float(&buf[16]);
+ val.size.z = decode_float(&buf[20]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*6;
+ (*r_len) += 4 * 6;
} break;
case Variant::BASIS: {
- ERR_FAIL_COND_V(len<(int)4*9,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 9, ERR_INVALID_DATA);
Basis val;
- for(int i=0;i<3;i++) {
- for(int j=0;j<3;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- val.elements[i][j]=decode_float(&buf[(i*3+j)*4]);
+ val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]);
}
}
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4*9;
+ (*r_len) += 4 * 9;
} break;
case Variant::TRANSFORM: {
- ERR_FAIL_COND_V(len<(int)4*12,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 12, ERR_INVALID_DATA);
Transform val;
- for(int i=0;i<3;i++) {
- for(int j=0;j<3;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- val.basis.elements[i][j]=decode_float(&buf[(i*3+j)*4]);
+ val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]);
}
}
- val.origin[0]=decode_float(&buf[36]);
- val.origin[1]=decode_float(&buf[40]);
- val.origin[2]=decode_float(&buf[44]);
+ val.origin[0] = decode_float(&buf[36]);
+ val.origin[1] = decode_float(&buf[40]);
+ val.origin[2] = decode_float(&buf[44]);
- r_variant=val;
+ r_variant = val;
if (r_len)
- (*r_len)+=4*12;
+ (*r_len) += 4 * 12;
} break;
// misc types
case Variant::COLOR: {
- ERR_FAIL_COND_V(len<(int)4*4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)4 * 4, ERR_INVALID_DATA);
Color val;
- val.r=decode_float(&buf[0]);
- val.g=decode_float(&buf[4]);
- val.b=decode_float(&buf[8]);
- val.a=decode_float(&buf[12]);
- r_variant=val;
+ val.r = decode_float(&buf[0]);
+ val.g = decode_float(&buf[4]);
+ val.b = decode_float(&buf[8]);
+ val.a = decode_float(&buf[12]);
+ r_variant = val;
if (r_len)
- (*r_len)+=4*4;
+ (*r_len) += 4 * 4;
} break;
case Variant::IMAGE: {
- ERR_FAIL_COND_V(len<(int)5*4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < (int)5 * 4, ERR_INVALID_DATA);
Image::Format fmt = (Image::Format)decode_uint32(&buf[0]);
- ERR_FAIL_INDEX_V( fmt, Image::FORMAT_MAX, ERR_INVALID_DATA);
+ ERR_FAIL_INDEX_V(fmt, Image::FORMAT_MAX, ERR_INVALID_DATA);
uint32_t mipmaps = decode_uint32(&buf[4]);
uint32_t w = decode_uint32(&buf[8]);
uint32_t h = decode_uint32(&buf[12]);
uint32_t datalen = decode_uint32(&buf[16]);
Image img;
- if (datalen>0) {
- len-=5*4;
- ERR_FAIL_COND_V( len < datalen, ERR_INVALID_DATA );
+ if (datalen > 0) {
+ len -= 5 * 4;
+ ERR_FAIL_COND_V(len < datalen, ERR_INVALID_DATA);
PoolVector<uint8_t> data;
data.resize(datalen);
PoolVector<uint8_t>::Write wr = data.write();
- copymem(&wr[0],&buf[20],datalen);
+ copymem(&wr[0], &buf[20], datalen);
wr = PoolVector<uint8_t>::Write();
-
-
- img=Image(w,h,mipmaps,fmt,data);
+ img = Image(w, h, mipmaps, fmt, data);
}
- r_variant=img;
+ r_variant = img;
if (r_len) {
- if (datalen%4)
- (*r_len)+=4-datalen%4;
+ if (datalen % 4)
+ (*r_len) += 4 - datalen % 4;
- (*r_len)+=4*5+datalen;
+ (*r_len) += 4 * 5 + datalen;
}
} break;
case Variant::NODE_PATH: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t strlen = decode_uint32(buf);
- if (strlen&0x80000000) {
+ if (strlen & 0x80000000) {
//new format
- ERR_FAIL_COND_V(len<12,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA);
Vector<StringName> names;
Vector<StringName> subnames;
StringName prop;
- uint32_t namecount=strlen&=0x7FFFFFFF;
- uint32_t subnamecount = decode_uint32(buf+4);
- uint32_t flags = decode_uint32(buf+8);
+ uint32_t namecount = strlen &= 0x7FFFFFFF;
+ uint32_t subnamecount = decode_uint32(buf + 4);
+ uint32_t flags = decode_uint32(buf + 8);
- len-=12;
- buf+=12;
+ len -= 12;
+ buf += 12;
- int total=namecount+subnamecount;
- if (flags&2)
+ int total = namecount + subnamecount;
+ if (flags & 2)
total++;
if (r_len)
- (*r_len)+=12;
-
+ (*r_len) += 12;
- for(int i=0;i<total;i++) {
+ for (int i = 0; i < total; i++) {
- ERR_FAIL_COND_V((int)len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V((int)len < 4, ERR_INVALID_DATA);
strlen = decode_uint32(buf);
- int pad=0;
+ int pad = 0;
- if (strlen%4)
- pad+=4-strlen%4;
+ if (strlen % 4)
+ pad += 4 - strlen % 4;
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)strlen+pad>len,ERR_INVALID_DATA);
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)strlen + pad > len, ERR_INVALID_DATA);
String str;
- str.parse_utf8((const char*)buf,strlen);
-
+ str.parse_utf8((const char *)buf, strlen);
- if (i<namecount)
+ if (i < namecount)
names.push_back(str);
- else if (i<namecount+subnamecount)
+ else if (i < namecount + subnamecount)
subnames.push_back(str);
else
- prop=str;
+ prop = str;
- buf+=strlen+pad;
- len-=strlen+pad;
+ buf += strlen + pad;
+ len -= strlen + pad;
if (r_len)
- (*r_len)+=4+strlen+pad;
-
+ (*r_len) += 4 + strlen + pad;
}
- r_variant=NodePath(names,subnames,flags&1,prop);
+ r_variant = NodePath(names, subnames, flags & 1, prop);
} else {
//old format, just a string
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA);
-
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA);
String str;
- str.parse_utf8((const char*)buf,strlen);
+ str.parse_utf8((const char *)buf, strlen);
- r_variant=NodePath(str);
+ r_variant = NodePath(str);
if (r_len)
- (*r_len)+=4+strlen;
+ (*r_len) += 4 + strlen;
}
} break;
@@ -403,64 +394,62 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
} break;
case Variant::OBJECT: {
-
- r_variant = (Object*)NULL;
+ r_variant = (Object *)NULL;
} break;
case Variant::INPUT_EVENT: {
InputEvent ie;
- ie.type=decode_uint32(&buf[0]);
- ie.device=decode_uint32(&buf[4]);
+ ie.type = decode_uint32(&buf[0]);
+ ie.device = decode_uint32(&buf[4]);
if (r_len)
- (*r_len)+=12;
+ (*r_len) += 12;
- switch(ie.type) {
+ switch (ie.type) {
case InputEvent::KEY: {
- uint32_t mods=decode_uint32(&buf[12]);
- if (mods&KEY_MASK_SHIFT)
- ie.key.mod.shift=true;
- if (mods&KEY_MASK_CTRL)
- ie.key.mod.control=true;
- if (mods&KEY_MASK_ALT)
- ie.key.mod.alt=true;
- if (mods&KEY_MASK_META)
- ie.key.mod.meta=true;
- ie.key.scancode=decode_uint32(&buf[16]);
+ uint32_t mods = decode_uint32(&buf[12]);
+ if (mods & KEY_MASK_SHIFT)
+ ie.key.mod.shift = true;
+ if (mods & KEY_MASK_CTRL)
+ ie.key.mod.control = true;
+ if (mods & KEY_MASK_ALT)
+ ie.key.mod.alt = true;
+ if (mods & KEY_MASK_META)
+ ie.key.mod.meta = true;
+ ie.key.scancode = decode_uint32(&buf[16]);
if (r_len)
- (*r_len)+=8;
-
+ (*r_len) += 8;
} break;
case InputEvent::MOUSE_BUTTON: {
- ie.mouse_button.button_index=decode_uint32(&buf[12]);
+ ie.mouse_button.button_index = decode_uint32(&buf[12]);
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
} break;
case InputEvent::JOYPAD_BUTTON: {
- ie.joy_button.button_index=decode_uint32(&buf[12]);
+ ie.joy_button.button_index = decode_uint32(&buf[12]);
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
} break;
case InputEvent::SCREEN_TOUCH: {
- ie.screen_touch.index=decode_uint32(&buf[12]);
+ ie.screen_touch.index = decode_uint32(&buf[12]);
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
} break;
case InputEvent::JOYPAD_MOTION: {
- ie.joy_motion.axis=decode_uint32(&buf[12]);
- ie.joy_motion.axis_value=decode_float(&buf[16]);
+ ie.joy_motion.axis = decode_uint32(&buf[12]);
+ ie.joy_motion.axis_value = decode_float(&buf[16]);
if (r_len)
- (*r_len)+=8;
+ (*r_len) += 8;
} break;
}
@@ -469,125 +458,121 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
} break;
case Variant::DICTIONARY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
- uint32_t count = decode_uint32(buf);
- // bool shared = count&0x80000000;
- count&=0x7FFFFFFF;
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
+ uint32_t count = decode_uint32(buf);
+ // bool shared = count&0x80000000;
+ count &= 0x7FFFFFFF;
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
if (r_len) {
- (*r_len)+=4;
+ (*r_len) += 4;
}
- Dictionary d;
+ Dictionary d;
- for(uint32_t i=0;i<count;i++) {
+ for (uint32_t i = 0; i < count; i++) {
- Variant key,value;
+ Variant key, value;
int used;
- Error err = decode_variant(key,buf,len,&used);
- ERR_FAIL_COND_V(err,err);
+ Error err = decode_variant(key, buf, len, &used);
+ ERR_FAIL_COND_V(err, err);
- buf+=used;
- len-=used;
+ buf += used;
+ len -= used;
if (r_len) {
- (*r_len)+=used;
+ (*r_len) += used;
}
- err = decode_variant(value,buf,len,&used);
- ERR_FAIL_COND_V(err,err);
+ err = decode_variant(value, buf, len, &used);
+ ERR_FAIL_COND_V(err, err);
- buf+=used;
- len-=used;
+ buf += used;
+ len -= used;
if (r_len) {
- (*r_len)+=used;
+ (*r_len) += used;
}
- d[key]=value;
+ d[key] = value;
}
- r_variant=d;
+ r_variant = d;
} break;
case Variant::ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- // bool shared = count&0x80000000;
- count&=0x7FFFFFFF;
+ // bool shared = count&0x80000000;
+ count &= 0x7FFFFFFF;
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
if (r_len) {
- (*r_len)+=4;
+ (*r_len) += 4;
}
- Array varr;
+ Array varr;
- for(uint32_t i=0;i<count;i++) {
+ for (uint32_t i = 0; i < count; i++) {
- int used=0;
+ int used = 0;
Variant v;
- Error err = decode_variant(v,buf,len,&used);
- ERR_FAIL_COND_V(err,err);
- buf+=used;
- len-=used;
+ Error err = decode_variant(v, buf, len, &used);
+ ERR_FAIL_COND_V(err, err);
+ buf += used;
+ len -= used;
varr.push_back(v);
if (r_len) {
- (*r_len)+=used;
+ (*r_len) += used;
}
}
- r_variant=varr;
-
+ r_variant = varr;
} break;
// arrays
case Variant::POOL_BYTE_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)count>len,ERR_INVALID_DATA);
-
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)count > len, ERR_INVALID_DATA);
PoolVector<uint8_t> data;
if (count) {
data.resize(count);
PoolVector<uint8_t>::Write w = data.write();
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- w[i]=buf[i];
+ w[i] = buf[i];
}
w = PoolVector<uint8_t>::Write();
}
- r_variant=data;
+ r_variant = data;
if (r_len) {
- if (count%4)
- (*r_len)+=4-count%4;
- (*r_len)+=4+count;
+ if (count % 4)
+ (*r_len) += 4 - count % 4;
+ (*r_len) += 4 + count;
}
-
-
} break;
case Variant::POOL_INT_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA);
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA);
PoolVector<int> data;
@@ -595,26 +580,26 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
//const int*rbuf=(const int*)buf;
data.resize(count);
PoolVector<int>::Write w = data.write();
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- w[i]=decode_uint32(&buf[i*4]);
+ w[i] = decode_uint32(&buf[i * 4]);
}
w = PoolVector<int>::Write();
}
- r_variant=Variant(data);
+ r_variant = Variant(data);
if (r_len) {
- (*r_len)+=4+count*sizeof(int);
+ (*r_len) += 4 + count * sizeof(int);
}
} break;
case Variant::POOL_REAL_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)count*4>len,ERR_INVALID_DATA);
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)count * 4 > len, ERR_INVALID_DATA);
PoolVector<float> data;
@@ -622,182 +607,173 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
//const float*rbuf=(const float*)buf;
data.resize(count);
PoolVector<float>::Write w = data.write();
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- w[i]=decode_float(&buf[i*4]);
+ w[i] = decode_float(&buf[i * 4]);
}
w = PoolVector<float>::Write();
}
- r_variant=data;
+ r_variant = data;
if (r_len) {
- (*r_len)+=4+count*sizeof(float);
+ (*r_len) += 4 + count * sizeof(float);
}
-
} break;
case Variant::POOL_STRING_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
PoolVector<String> strings;
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
if (r_len)
- (*r_len)+=4;
+ (*r_len) += 4;
//printf("string count: %i\n",count);
- for(int i=0;i<(int)count;i++) {
+ for (int i = 0; i < (int)count; i++) {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t strlen = decode_uint32(buf);
- buf+=4;
- len-=4;
- ERR_FAIL_COND_V((int)strlen>len,ERR_INVALID_DATA);
+ buf += 4;
+ len -= 4;
+ ERR_FAIL_COND_V((int)strlen > len, ERR_INVALID_DATA);
//printf("loaded string: %s\n",(const char*)buf);
String str;
- str.parse_utf8((const char*)buf,strlen);
+ str.parse_utf8((const char *)buf, strlen);
strings.push_back(str);
- buf+=strlen;
- len-=strlen;
+ buf += strlen;
+ len -= strlen;
if (r_len)
- (*r_len)+=4+strlen;
+ (*r_len) += 4 + strlen;
- if (strlen%4) {
- int pad = 4-(strlen%4);
- buf+=pad;
- len-=pad;
+ if (strlen % 4) {
+ int pad = 4 - (strlen % 4);
+ buf += pad;
+ len -= pad;
if (r_len) {
- (*r_len)+=pad;
+ (*r_len) += pad;
}
}
-
}
- r_variant=strings;
-
+ r_variant = strings;
} break;
case Variant::POOL_VECTOR2_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
- ERR_FAIL_COND_V((int)count*4*2>len,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V((int)count * 4 * 2 > len, ERR_INVALID_DATA);
PoolVector<Vector2> varray;
if (r_len) {
- (*r_len)+=4;
+ (*r_len) += 4;
}
if (count) {
varray.resize(count);
PoolVector<Vector2>::Write w = varray.write();
- for(int i=0;i<(int)count;i++) {
-
- w[i].x=decode_float(buf+i*4*2+4*0);
- w[i].y=decode_float(buf+i*4*2+4*1);
+ for (int i = 0; i < (int)count; i++) {
+ w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0);
+ w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1);
}
- int adv = 4*2*count;
+ int adv = 4 * 2 * count;
if (r_len)
- (*r_len)+=adv;
- len-=adv;
- buf+=adv;
-
+ (*r_len) += adv;
+ len -= adv;
+ buf += adv;
}
- r_variant=varray;
+ r_variant = varray;
} break;
case Variant::POOL_VECTOR3_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
- ERR_FAIL_COND_V((int)count*4*3>len,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V((int)count * 4 * 3 > len, ERR_INVALID_DATA);
PoolVector<Vector3> varray;
if (r_len) {
- (*r_len)+=4;
+ (*r_len) += 4;
}
if (count) {
varray.resize(count);
PoolVector<Vector3>::Write w = varray.write();
- for(int i=0;i<(int)count;i++) {
-
- w[i].x=decode_float(buf+i*4*3+4*0);
- w[i].y=decode_float(buf+i*4*3+4*1);
- w[i].z=decode_float(buf+i*4*3+4*2);
+ for (int i = 0; i < (int)count; i++) {
+ w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0);
+ w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1);
+ w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2);
}
- int adv = 4*3*count;
+ int adv = 4 * 3 * count;
if (r_len)
- (*r_len)+=adv;
- len-=adv;
- buf+=adv;
-
+ (*r_len) += adv;
+ len -= adv;
+ buf += adv;
}
- r_variant=varray;
+ r_variant = varray;
} break;
case Variant::POOL_COLOR_ARRAY: {
- ERR_FAIL_COND_V(len<4,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t count = decode_uint32(buf);
- buf+=4;
- len-=4;
+ buf += 4;
+ len -= 4;
- ERR_FAIL_COND_V((int)count*4*4>len,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V((int)count * 4 * 4 > len, ERR_INVALID_DATA);
PoolVector<Color> carray;
if (r_len) {
- (*r_len)+=4;
+ (*r_len) += 4;
}
if (count) {
carray.resize(count);
PoolVector<Color>::Write w = carray.write();
- for(int i=0;i<(int)count;i++) {
-
- w[i].r=decode_float(buf+i*4*4+4*0);
- w[i].g=decode_float(buf+i*4*4+4*1);
- w[i].b=decode_float(buf+i*4*4+4*2);
- w[i].a=decode_float(buf+i*4*4+4*3);
+ for (int i = 0; i < (int)count; i++) {
+ w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0);
+ w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1);
+ w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2);
+ w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3);
}
- int adv = 4*4*count;
+ int adv = 4 * 4 * count;
if (r_len)
- (*r_len)+=adv;
- len-=adv;
- buf+=adv;
-
+ (*r_len) += adv;
+ len -= adv;
+ buf += adv;
}
- r_variant=carray;
+ r_variant = carray;
} break;
default: { ERR_FAIL_V(ERR_BUG); }
@@ -806,39 +782,39 @@ Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *
return OK;
}
-Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
+Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) {
- uint8_t * buf=r_buffer;
+ uint8_t *buf = r_buffer;
- r_len=0;
+ r_len = 0;
- uint32_t flags=0;
+ uint32_t flags = 0;
- switch(p_variant.get_type()) {
+ switch (p_variant.get_type()) {
case Variant::INT: {
int64_t val = p_variant;
- if (val>0x7FFFFFFF || val < -0x80000000) {
- flags|=ENCODE_FLAG_64;
+ if (val > 0x7FFFFFFF || val < -0x80000000) {
+ flags |= ENCODE_FLAG_64;
}
} break;
case Variant::REAL: {
double d = p_variant;
float f = d;
- if (double(f)!=d) {
- flags|=ENCODE_FLAG_64; //always encode real as double
+ if (double(f) != d) {
+ flags |= ENCODE_FLAG_64; //always encode real as double
}
} break;
}
if (buf) {
- encode_uint32(p_variant.get_type()|flags,buf);
- buf+=4;
+ encode_uint32(p_variant.get_type() | flags, buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
- switch(p_variant.get_type()) {
+ switch (p_variant.get_type()) {
case Variant::NIL: {
@@ -847,118 +823,115 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
case Variant::BOOL: {
if (buf) {
- encode_uint32(p_variant.operator bool(),buf);
+ encode_uint32(p_variant.operator bool(), buf);
}
- r_len+=4;
+ r_len += 4;
} break;
case Variant::INT: {
int64_t val = p_variant;
- if (val>0x7FFFFFFF || val < -0x80000000) {
+ if (val > 0x7FFFFFFF || val < -0x80000000) {
//64 bits
if (buf) {
- encode_uint64(val,buf);
+ encode_uint64(val, buf);
}
- r_len+=8;
+ r_len += 8;
} else {
if (buf) {
- encode_uint32(int32_t(val),buf);
+ encode_uint32(int32_t(val), buf);
}
- r_len+=4;
+ r_len += 4;
}
} break;
case Variant::REAL: {
double d = p_variant;
float f = d;
- if (double(f)!=d) {
+ if (double(f) != d) {
if (buf) {
- encode_double(p_variant.operator double(),buf);
+ encode_double(p_variant.operator double(), buf);
}
- r_len+=8;
+ r_len += 8;
} else {
if (buf) {
- encode_double(p_variant.operator float(),buf);
+ encode_double(p_variant.operator float(), buf);
}
- r_len+=4;
+ r_len += 4;
}
-
} break;
case Variant::NODE_PATH: {
- NodePath np=p_variant;
+ NodePath np = p_variant;
if (buf) {
- encode_uint32(uint32_t(np.get_name_count())|0x80000000,buf); //for compatibility with the old format
- encode_uint32(np.get_subname_count(),buf+4);
- uint32_t flags=0;
+ encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format
+ encode_uint32(np.get_subname_count(), buf + 4);
+ uint32_t flags = 0;
if (np.is_absolute())
- flags|=1;
- if (np.get_property()!=StringName())
- flags|=2;
+ flags |= 1;
+ if (np.get_property() != StringName())
+ flags |= 2;
- encode_uint32(flags,buf+8);
+ encode_uint32(flags, buf + 8);
- buf+=12;
+ buf += 12;
}
- r_len+=12;
+ r_len += 12;
- int total = np.get_name_count()+np.get_subname_count();
- if (np.get_property()!=StringName())
+ int total = np.get_name_count() + np.get_subname_count();
+ if (np.get_property() != StringName())
total++;
- for(int i=0;i<total;i++) {
+ for (int i = 0; i < total; i++) {
String str;
- if (i<np.get_name_count())
- str=np.get_name(i);
- else if (i<np.get_name_count()+np.get_subname_count())
- str=np.get_subname(i-np.get_subname_count());
+ if (i < np.get_name_count())
+ str = np.get_name(i);
+ else if (i < np.get_name_count() + np.get_subname_count())
+ str = np.get_subname(i - np.get_subname_count());
else
- str=np.get_property();
+ str = np.get_property();
CharString utf8 = str.utf8();
int pad = 0;
- if (utf8.length()%4)
- pad=4-utf8.length()%4;
+ if (utf8.length() % 4)
+ pad = 4 - utf8.length() % 4;
if (buf) {
- encode_uint32(utf8.length(),buf);
- buf+=4;
- copymem(buf,utf8.get_data(),utf8.length());
- buf+=pad+utf8.length();
+ encode_uint32(utf8.length(), buf);
+ buf += 4;
+ copymem(buf, utf8.get_data(), utf8.length());
+ buf += pad + utf8.length();
}
-
- r_len+=4+utf8.length()+pad;
+ r_len += 4 + utf8.length() + pad;
}
} break;
case Variant::STRING: {
-
CharString utf8 = p_variant.operator String().utf8();
if (buf) {
- encode_uint32(utf8.length(),buf);
- buf+=4;
- copymem(buf,utf8.get_data(),utf8.length());
+ encode_uint32(utf8.length(), buf);
+ buf += 4;
+ copymem(buf, utf8.get_data(), utf8.length());
}
- r_len+=4+utf8.length();
- while (r_len%4)
+ r_len += 4 + utf8.length();
+ while (r_len % 4)
r_len++; //pad
} break;
@@ -967,132 +940,126 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
case Variant::VECTOR2: {
if (buf) {
- Vector2 v2=p_variant;
- encode_float(v2.x,&buf[0]);
- encode_float(v2.y,&buf[4]);
-
+ Vector2 v2 = p_variant;
+ encode_float(v2.x, &buf[0]);
+ encode_float(v2.y, &buf[4]);
}
- r_len+=2*4;
+ r_len += 2 * 4;
- } break; // 5
+ } break; // 5
case Variant::RECT2: {
if (buf) {
- Rect2 r2=p_variant;
- encode_float(r2.pos.x,&buf[0]);
- encode_float(r2.pos.y,&buf[4]);
- encode_float(r2.size.x,&buf[8]);
- encode_float(r2.size.y,&buf[12]);
+ Rect2 r2 = p_variant;
+ encode_float(r2.pos.x, &buf[0]);
+ encode_float(r2.pos.y, &buf[4]);
+ encode_float(r2.size.x, &buf[8]);
+ encode_float(r2.size.y, &buf[12]);
}
- r_len+=4*4;
+ r_len += 4 * 4;
} break;
case Variant::VECTOR3: {
if (buf) {
- Vector3 v3=p_variant;
- encode_float(v3.x,&buf[0]);
- encode_float(v3.y,&buf[4]);
- encode_float(v3.z,&buf[8]);
+ Vector3 v3 = p_variant;
+ encode_float(v3.x, &buf[0]);
+ encode_float(v3.y, &buf[4]);
+ encode_float(v3.z, &buf[8]);
}
- r_len+=3*4;
+ r_len += 3 * 4;
} break;
case Variant::TRANSFORM2D: {
if (buf) {
- Transform2D val=p_variant;
- for(int i=0;i<3;i++) {
- for(int j=0;j<2;j++) {
+ Transform2D val = p_variant;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 2; j++) {
- copymem(&buf[(i*2+j)*4],&val.elements[i][j],sizeof(float));
+ copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float));
}
}
}
-
- r_len+=6*4;
+ r_len += 6 * 4;
} break;
case Variant::PLANE: {
if (buf) {
- Plane p=p_variant;
- encode_float(p.normal.x,&buf[0]);
- encode_float(p.normal.y,&buf[4]);
- encode_float(p.normal.z,&buf[8]);
- encode_float(p.d,&buf[12]);
+ Plane p = p_variant;
+ encode_float(p.normal.x, &buf[0]);
+ encode_float(p.normal.y, &buf[4]);
+ encode_float(p.normal.z, &buf[8]);
+ encode_float(p.d, &buf[12]);
}
- r_len+=4*4;
+ r_len += 4 * 4;
} break;
case Variant::QUAT: {
if (buf) {
- Quat q=p_variant;
- encode_float(q.x,&buf[0]);
- encode_float(q.y,&buf[4]);
- encode_float(q.z,&buf[8]);
- encode_float(q.w,&buf[12]);
+ Quat q = p_variant;
+ encode_float(q.x, &buf[0]);
+ encode_float(q.y, &buf[4]);
+ encode_float(q.z, &buf[8]);
+ encode_float(q.w, &buf[12]);
}
- r_len+=4*4;
+ r_len += 4 * 4;
} break;
case Variant::RECT3: {
if (buf) {
- Rect3 aabb=p_variant;
- encode_float(aabb.pos.x,&buf[0]);
- encode_float(aabb.pos.y,&buf[4]);
- encode_float(aabb.pos.z,&buf[8]);
- encode_float(aabb.size.x,&buf[12]);
- encode_float(aabb.size.y,&buf[16]);
- encode_float(aabb.size.z,&buf[20]);
+ Rect3 aabb = p_variant;
+ encode_float(aabb.pos.x, &buf[0]);
+ encode_float(aabb.pos.y, &buf[4]);
+ encode_float(aabb.pos.z, &buf[8]);
+ encode_float(aabb.size.x, &buf[12]);
+ encode_float(aabb.size.y, &buf[16]);
+ encode_float(aabb.size.z, &buf[20]);
}
- r_len+=6*4;
-
+ r_len += 6 * 4;
} break;
case Variant::BASIS: {
if (buf) {
- Basis val=p_variant;
- for(int i=0;i<3;i++) {
- for(int j=0;j<3;j++) {
+ Basis val = p_variant;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- copymem(&buf[(i*3+j)*4],&val.elements[i][j],sizeof(float));
+ copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float));
}
}
}
-
- r_len+=9*4;
+ r_len += 9 * 4;
} break;
case Variant::TRANSFORM: {
if (buf) {
- Transform val=p_variant;
- for(int i=0;i<3;i++) {
- for(int j=0;j<3;j++) {
+ Transform val = p_variant;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- copymem(&buf[(i*3+j)*4],&val.basis.elements[i][j],sizeof(float));
+ copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float));
}
}
- encode_float(val.origin.x,&buf[36]);
- encode_float(val.origin.y,&buf[40]);
- encode_float(val.origin.z,&buf[44]);
-
-
+ encode_float(val.origin.x, &buf[36]);
+ encode_float(val.origin.y, &buf[40]);
+ encode_float(val.origin.z, &buf[44]);
}
- r_len+=12*4;
+ r_len += 12 * 4;
} break;
@@ -1100,38 +1067,38 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
case Variant::COLOR: {
if (buf) {
- Color c=p_variant;
- encode_float(c.r,&buf[0]);
- encode_float(c.g,&buf[4]);
- encode_float(c.b,&buf[8]);
- encode_float(c.a,&buf[12]);
+ Color c = p_variant;
+ encode_float(c.r, &buf[0]);
+ encode_float(c.g, &buf[4]);
+ encode_float(c.b, &buf[8]);
+ encode_float(c.a, &buf[12]);
}
- r_len+=4*4;
+ r_len += 4 * 4;
} break;
case Variant::IMAGE: {
Image image = p_variant;
- PoolVector<uint8_t> data=image.get_data();
+ PoolVector<uint8_t> data = image.get_data();
if (buf) {
- encode_uint32(image.get_format(),&buf[0]);
- encode_uint32(image.has_mipmaps(),&buf[4]);
- encode_uint32(image.get_width(),&buf[8]);
- encode_uint32(image.get_height(),&buf[12]);
- int ds=data.size();
- encode_uint32(ds,&buf[16]);
+ encode_uint32(image.get_format(), &buf[0]);
+ encode_uint32(image.has_mipmaps(), &buf[4]);
+ encode_uint32(image.get_width(), &buf[8]);
+ encode_uint32(image.get_height(), &buf[12]);
+ int ds = data.size();
+ encode_uint32(ds, &buf[16]);
PoolVector<uint8_t>::Read r = data.read();
- copymem(&buf[20],&r[0],ds);
+ copymem(&buf[20], &r[0], ds);
}
- int pad=0;
- if (data.size()%4)
- pad=4-data.size()%4;
+ int pad = 0;
+ if (data.size() % 4)
+ pad = 4 - data.size() % 4;
- r_len+=data.size()+5*4+pad;
+ r_len += data.size() + 5 * 4 + pad;
} break;
/*case Variant::RESOURCE: {
@@ -1142,84 +1109,81 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
case Variant::_RID:
case Variant::OBJECT: {
-
} break;
case Variant::INPUT_EVENT: {
-
- InputEvent ie=p_variant;
+ InputEvent ie = p_variant;
if (buf) {
- encode_uint32(ie.type,&buf[0]);
- encode_uint32(ie.device,&buf[4]);
- encode_uint32(0,&buf[8]);
+ encode_uint32(ie.type, &buf[0]);
+ encode_uint32(ie.device, &buf[4]);
+ encode_uint32(0, &buf[8]);
}
- int llen=12;
+ int llen = 12;
- switch(ie.type) {
+ switch (ie.type) {
case InputEvent::KEY: {
if (buf) {
- uint32_t mods=0;
+ uint32_t mods = 0;
if (ie.key.mod.shift)
- mods|=KEY_MASK_SHIFT;
+ mods |= KEY_MASK_SHIFT;
if (ie.key.mod.control)
- mods|=KEY_MASK_CTRL;
+ mods |= KEY_MASK_CTRL;
if (ie.key.mod.alt)
- mods|=KEY_MASK_ALT;
+ mods |= KEY_MASK_ALT;
if (ie.key.mod.meta)
- mods|=KEY_MASK_META;
+ mods |= KEY_MASK_META;
- encode_uint32(mods,&buf[llen]);
- encode_uint32(ie.key.scancode,&buf[llen+4]);
+ encode_uint32(mods, &buf[llen]);
+ encode_uint32(ie.key.scancode, &buf[llen + 4]);
}
- llen+=8;
+ llen += 8;
} break;
case InputEvent::MOUSE_BUTTON: {
if (buf) {
- encode_uint32(ie.mouse_button.button_index,&buf[llen]);
+ encode_uint32(ie.mouse_button.button_index, &buf[llen]);
}
- llen+=4;
+ llen += 4;
} break;
case InputEvent::JOYPAD_BUTTON: {
if (buf) {
- encode_uint32(ie.joy_button.button_index,&buf[llen]);
+ encode_uint32(ie.joy_button.button_index, &buf[llen]);
}
- llen+=4;
+ llen += 4;
} break;
case InputEvent::SCREEN_TOUCH: {
if (buf) {
- encode_uint32(ie.screen_touch.index,&buf[llen]);
+ encode_uint32(ie.screen_touch.index, &buf[llen]);
}
- llen+=4;
+ llen += 4;
} break;
case InputEvent::JOYPAD_MOTION: {
if (buf) {
int axis = ie.joy_motion.axis;
- encode_uint32(axis,&buf[llen]);
- encode_float(ie.joy_motion.axis_value, &buf[llen+4]);
+ encode_uint32(axis, &buf[llen]);
+ encode_float(ie.joy_motion.axis_value, &buf[llen + 4]);
}
- llen+=8;
+ llen += 8;
} break;
}
if (buf)
- encode_uint32(llen,&buf[8]);
- r_len+=llen;
-
+ encode_uint32(llen, &buf[8]);
+ r_len += llen;
// not supported
} break;
@@ -1228,16 +1192,15 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
Dictionary d = p_variant;
if (buf) {
- encode_uint32(uint32_t(d.size()),buf);
- buf+=4;
+ encode_uint32(uint32_t(d.size()), buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
List<Variant> keys;
d.get_key_list(&keys);
-
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
/*
CharString utf8 = E->->utf8();
@@ -1253,14 +1216,14 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
r_len++; //pad
*/
int len;
- encode_variant(E->get(),buf,len);
- ERR_FAIL_COND_V(len%4,ERR_BUG);
- r_len+=len;
+ encode_variant(E->get(), buf, len);
+ ERR_FAIL_COND_V(len % 4, ERR_BUG);
+ r_len += len;
if (buf)
buf += len;
- encode_variant(d[E->get()],buf,len);
- ERR_FAIL_COND_V(len%4,ERR_BUG);
- r_len+=len;
+ encode_variant(d[E->get()], buf, len);
+ ERR_FAIL_COND_V(len % 4, ERR_BUG);
+ r_len += len;
if (buf)
buf += len;
}
@@ -1271,107 +1234,101 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
Array v = p_variant;
if (buf) {
- encode_uint32(uint32_t(v.size()),buf);
- buf+=4;
+ encode_uint32(uint32_t(v.size()), buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
- for(int i=0;i<v.size();i++) {
+ for (int i = 0; i < v.size(); i++) {
int len;
- encode_variant(v.get(i),buf,len);
- ERR_FAIL_COND_V(len%4,ERR_BUG);
- r_len+=len;
+ encode_variant(v.get(i), buf, len);
+ ERR_FAIL_COND_V(len % 4, ERR_BUG);
+ r_len += len;
if (buf)
- buf+=len;
+ buf += len;
}
-
} break;
// arrays
case Variant::POOL_BYTE_ARRAY: {
PoolVector<uint8_t> data = p_variant;
- int datalen=data.size();
- int datasize=sizeof(uint8_t);
+ int datalen = data.size();
+ int datasize = sizeof(uint8_t);
if (buf) {
- encode_uint32(datalen,buf);
- buf+=4;
+ encode_uint32(datalen, buf);
+ buf += 4;
PoolVector<uint8_t>::Read r = data.read();
- copymem(buf,&r[0],datalen*datasize);
-
+ copymem(buf, &r[0], datalen * datasize);
}
- r_len+=4+datalen*datasize;
- while(r_len%4)
+ r_len += 4 + datalen * datasize;
+ while (r_len % 4)
r_len++;
} break;
case Variant::POOL_INT_ARRAY: {
PoolVector<int> data = p_variant;
- int datalen=data.size();
- int datasize=sizeof(int32_t);
+ int datalen = data.size();
+ int datasize = sizeof(int32_t);
if (buf) {
- encode_uint32(datalen,buf);
- buf+=4;
+ encode_uint32(datalen, buf);
+ buf += 4;
PoolVector<int>::Read r = data.read();
- for(int i=0;i<datalen;i++)
- encode_uint32(r[i],&buf[i*datasize]);
-
+ for (int i = 0; i < datalen; i++)
+ encode_uint32(r[i], &buf[i * datasize]);
}
- r_len+=4+datalen*datasize;
+ r_len += 4 + datalen * datasize;
} break;
case Variant::POOL_REAL_ARRAY: {
PoolVector<real_t> data = p_variant;
- int datalen=data.size();
- int datasize=sizeof(real_t);
+ int datalen = data.size();
+ int datasize = sizeof(real_t);
if (buf) {
- encode_uint32(datalen,buf);
- buf+=4;
+ encode_uint32(datalen, buf);
+ buf += 4;
PoolVector<real_t>::Read r = data.read();
- for(int i=0;i<datalen;i++)
- encode_float(r[i],&buf[i*datasize]);
-
+ for (int i = 0; i < datalen; i++)
+ encode_float(r[i], &buf[i * datasize]);
}
- r_len+=4+datalen*datasize;
+ r_len += 4 + datalen * datasize;
} break;
case Variant::POOL_STRING_ARRAY: {
-
PoolVector<String> data = p_variant;
- int len=data.size();
+ int len = data.size();
if (buf) {
- encode_uint32(len,buf);
- buf+=4;
+ encode_uint32(len, buf);
+ buf += 4;
}
- r_len+=4;
-
- for(int i=0;i<len;i++) {
+ r_len += 4;
+ for (int i = 0; i < len; i++) {
CharString utf8 = data.get(i).utf8();
if (buf) {
- encode_uint32(utf8.length()+1,buf);
- buf+=4;
- copymem(buf,utf8.get_data(),utf8.length()+1);
- buf+=utf8.length()+1;
+ encode_uint32(utf8.length() + 1, buf);
+ buf += 4;
+ copymem(buf, utf8.get_data(), utf8.length() + 1);
+ buf += utf8.length() + 1;
}
- r_len+=4+utf8.length()+1;
- while (r_len%4) {
+ r_len += 4 + utf8.length() + 1;
+ while (r_len % 4) {
r_len++; //pad
if (buf)
buf++;
@@ -1382,95 +1339,89 @@ Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len) {
case Variant::POOL_VECTOR2_ARRAY: {
PoolVector<Vector2> data = p_variant;
- int len=data.size();
+ int len = data.size();
if (buf) {
- encode_uint32(len,buf);
- buf+=4;
+ encode_uint32(len, buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
if (buf) {
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
Vector2 v = data.get(i);
- encode_float(v.x,&buf[0]);
- encode_float(v.y,&buf[4]);
- buf+=4*2;
-
+ encode_float(v.x, &buf[0]);
+ encode_float(v.y, &buf[4]);
+ buf += 4 * 2;
}
}
- r_len+=4*2*len;
+ r_len += 4 * 2 * len;
} break;
case Variant::POOL_VECTOR3_ARRAY: {
PoolVector<Vector3> data = p_variant;
- int len=data.size();
+ int len = data.size();
if (buf) {
- encode_uint32(len,buf);
- buf+=4;
+ encode_uint32(len, buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
if (buf) {
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
Vector3 v = data.get(i);
- encode_float(v.x,&buf[0]);
- encode_float(v.y,&buf[4]);
- encode_float(v.z,&buf[8]);
- buf+=4*3;
-
+ encode_float(v.x, &buf[0]);
+ encode_float(v.y, &buf[4]);
+ encode_float(v.z, &buf[8]);
+ buf += 4 * 3;
}
}
- r_len+=4*3*len;
+ r_len += 4 * 3 * len;
} break;
case Variant::POOL_COLOR_ARRAY: {
PoolVector<Color> data = p_variant;
- int len=data.size();
+ int len = data.size();
if (buf) {
- encode_uint32(len,buf);
- buf+=4;
+ encode_uint32(len, buf);
+ buf += 4;
}
- r_len+=4;
+ r_len += 4;
if (buf) {
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
Color c = data.get(i);
-
- encode_float(c.r,&buf[0]);
- encode_float(c.g,&buf[4]);
- encode_float(c.b,&buf[8]);
- encode_float(c.a,&buf[12]);
- buf+=4*4;
+ encode_float(c.r, &buf[0]);
+ encode_float(c.g, &buf[4]);
+ encode_float(c.b, &buf[8]);
+ encode_float(c.a, &buf[12]);
+ buf += 4 * 4;
}
}
- r_len+=4*4*len;
+ r_len += 4 * 4 * len;
} break;
default: { ERR_FAIL_V(ERR_BUG); }
}
return OK;
-
}
-
-
diff --git a/core/io/marshalls.h b/core/io/marshalls.h
index f04ec9a256..939ed9cea9 100644
--- a/core/io/marshalls.h
+++ b/core/io/marshalls.h
@@ -38,7 +38,6 @@
* in an endian independent way
*/
-
union MarshallFloat {
uint32_t i; ///< int
@@ -53,41 +52,44 @@ union MarshallDouble {
static inline unsigned int encode_uint16(uint16_t p_uint, uint8_t *p_arr) {
- for (int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- *p_arr=p_uint&0xFF;
- p_arr++; p_uint>>=8;
+ *p_arr = p_uint & 0xFF;
+ p_arr++;
+ p_uint >>= 8;
}
- return sizeof( uint16_t );
+ return sizeof(uint16_t);
}
static inline unsigned int encode_uint32(uint32_t p_uint, uint8_t *p_arr) {
- for (int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- *p_arr=p_uint&0xFF;
- p_arr++; p_uint>>=8;
+ *p_arr = p_uint & 0xFF;
+ p_arr++;
+ p_uint >>= 8;
}
- return sizeof( uint32_t );
+ return sizeof(uint32_t);
}
static inline unsigned int encode_float(float p_float, uint8_t *p_arr) {
MarshallFloat mf;
- mf.f=p_float;
- encode_uint32( mf.i, p_arr );
+ mf.f = p_float;
+ encode_uint32(mf.i, p_arr);
- return sizeof( uint32_t );
+ return sizeof(uint32_t);
}
static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) {
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- *p_arr=p_uint&0xFF;
- p_arr++; p_uint>>=8;
+ *p_arr = p_uint & 0xFF;
+ p_arr++;
+ p_uint >>= 8;
}
return sizeof(uint64_t);
@@ -96,23 +98,21 @@ static inline unsigned int encode_uint64(uint64_t p_uint, uint8_t *p_arr) {
static inline unsigned int encode_double(double p_double, uint8_t *p_arr) {
MarshallDouble md;
- md.d=p_double;
- encode_uint64( md.l, p_arr );
+ md.d = p_double;
+ encode_uint64(md.l, p_arr);
return sizeof(uint64_t);
-
}
+static inline int encode_cstring(const char *p_string, uint8_t *p_data) {
-static inline int encode_cstring(const char *p_string, uint8_t * p_data) {
-
- int len=0;
+ int len = 0;
while (*p_string) {
if (p_data) {
- *p_data=(uint8_t)*p_string;
+ *p_data = (uint8_t)*p_string;
p_data++;
}
p_string++;
@@ -120,18 +120,18 @@ static inline int encode_cstring(const char *p_string, uint8_t * p_data) {
};
if (p_data) *p_data = 0;
- return len+1;
+ return len + 1;
}
static inline uint16_t decode_uint16(const uint8_t *p_arr) {
- uint16_t u=0;
+ uint16_t u = 0;
- for (int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
uint16_t b = *p_arr;
- b<<=(i*8);
- u|=b;
+ b <<= (i * 8);
+ u |= b;
p_arr++;
}
@@ -140,13 +140,13 @@ static inline uint16_t decode_uint16(const uint8_t *p_arr) {
static inline uint32_t decode_uint32(const uint8_t *p_arr) {
- uint32_t u=0;
+ uint32_t u = 0;
- for (int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
uint32_t b = *p_arr;
- b<<=(i*8);
- u|=b;
+ b <<= (i * 8);
+ u |= b;
p_arr++;
}
@@ -162,13 +162,13 @@ static inline float decode_float(const uint8_t *p_arr) {
static inline uint64_t decode_uint64(const uint8_t *p_arr) {
- uint64_t u=0;
+ uint64_t u = 0;
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- uint64_t b = (*p_arr)&0xFF;
- b<<=(i*8);
- u|=b;
+ uint64_t b = (*p_arr) & 0xFF;
+ b <<= (i * 8);
+ u |= b;
p_arr++;
}
@@ -178,13 +178,11 @@ static inline uint64_t decode_uint64(const uint8_t *p_arr) {
static inline double decode_double(const uint8_t *p_arr) {
MarshallDouble md;
- md.l = decode_uint64( p_arr );
+ md.l = decode_uint64(p_arr);
return md.d;
-
}
-
-Error decode_variant(Variant& r_variant,const uint8_t *p_buffer, int p_len,int *r_len=NULL);
-Error encode_variant(const Variant& p_variant, uint8_t *r_buffer, int &r_len);
+Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len = NULL);
+Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len);
#endif
diff --git a/core/io/networked_multiplayer_peer.cpp b/core/io/networked_multiplayer_peer.cpp
index fb81a806e2..da661d0981 100644
--- a/core/io/networked_multiplayer_peer.cpp
+++ b/core/io/networked_multiplayer_peer.cpp
@@ -28,42 +28,38 @@
/*************************************************************************/
#include "networked_multiplayer_peer.h"
-
void NetworkedMultiplayerPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_transfer_mode","mode"), &NetworkedMultiplayerPeer::set_transfer_mode );
- ClassDB::bind_method(D_METHOD("set_target_peer","id"), &NetworkedMultiplayerPeer::set_target_peer );
-
- ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer );
+ ClassDB::bind_method(D_METHOD("set_transfer_mode", "mode"), &NetworkedMultiplayerPeer::set_transfer_mode);
+ ClassDB::bind_method(D_METHOD("set_target_peer", "id"), &NetworkedMultiplayerPeer::set_target_peer);
- ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll );
+ ClassDB::bind_method(D_METHOD("get_packet_peer"), &NetworkedMultiplayerPeer::get_packet_peer);
- ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status );
- ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id );
+ ClassDB::bind_method(D_METHOD("poll"), &NetworkedMultiplayerPeer::poll);
- ClassDB::bind_method(D_METHOD("set_refuse_new_connections","enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections );
- ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections );
+ ClassDB::bind_method(D_METHOD("get_connection_status"), &NetworkedMultiplayerPeer::get_connection_status);
+ ClassDB::bind_method(D_METHOD("get_unique_id"), &NetworkedMultiplayerPeer::get_unique_id);
- BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE );
- BIND_CONSTANT( TRANSFER_MODE_UNRELIABLE_ORDERED );
- BIND_CONSTANT( TRANSFER_MODE_RELIABLE );
+ ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "enable"), &NetworkedMultiplayerPeer::set_refuse_new_connections);
+ ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &NetworkedMultiplayerPeer::is_refusing_new_connections);
- BIND_CONSTANT( CONNECTION_DISCONNECTED );
- BIND_CONSTANT( CONNECTION_CONNECTING );
- BIND_CONSTANT( CONNECTION_CONNECTED );
+ BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE);
+ BIND_CONSTANT(TRANSFER_MODE_UNRELIABLE_ORDERED);
+ BIND_CONSTANT(TRANSFER_MODE_RELIABLE);
- BIND_CONSTANT( TARGET_PEER_BROADCAST );
- BIND_CONSTANT( TARGET_PEER_SERVER );
+ BIND_CONSTANT(CONNECTION_DISCONNECTED);
+ BIND_CONSTANT(CONNECTION_CONNECTING);
+ BIND_CONSTANT(CONNECTION_CONNECTED);
+ BIND_CONSTANT(TARGET_PEER_BROADCAST);
+ BIND_CONSTANT(TARGET_PEER_SERVER);
- ADD_SIGNAL( MethodInfo("peer_connected",PropertyInfo(Variant::INT,"id")));
- ADD_SIGNAL( MethodInfo("peer_disconnected",PropertyInfo(Variant::INT,"id")));
- ADD_SIGNAL( MethodInfo("server_disconnected"));
- ADD_SIGNAL( MethodInfo("connection_succeeded") );
- ADD_SIGNAL( MethodInfo("connection_failed") );
+ ADD_SIGNAL(MethodInfo("peer_connected", PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("peer_disconnected", PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("server_disconnected"));
+ ADD_SIGNAL(MethodInfo("connection_succeeded"));
+ ADD_SIGNAL(MethodInfo("connection_failed"));
}
NetworkedMultiplayerPeer::NetworkedMultiplayerPeer() {
-
-
}
diff --git a/core/io/networked_multiplayer_peer.h b/core/io/networked_multiplayer_peer.h
index 5d859a2f25..1324a61c72 100644
--- a/core/io/networked_multiplayer_peer.h
+++ b/core/io/networked_multiplayer_peer.h
@@ -33,15 +33,15 @@
class NetworkedMultiplayerPeer : public PacketPeer {
- GDCLASS(NetworkedMultiplayerPeer,PacketPeer);
+ GDCLASS(NetworkedMultiplayerPeer, PacketPeer);
protected:
static void _bind_methods();
-public:
+public:
enum {
- TARGET_PEER_BROADCAST=0,
- TARGET_PEER_SERVER=1
+ TARGET_PEER_BROADCAST = 0,
+ TARGET_PEER_SERVER = 1
};
enum TransferMode {
TRANSFER_MODE_UNRELIABLE,
@@ -55,28 +55,26 @@ public:
CONNECTION_CONNECTED,
};
+ virtual void set_transfer_mode(TransferMode p_mode) = 0;
+ virtual void set_target_peer(int p_peer_id) = 0;
- virtual void set_transfer_mode(TransferMode p_mode)=0;
- virtual void set_target_peer(int p_peer_id)=0;
-
- virtual int get_packet_peer() const=0;
-
- virtual bool is_server() const=0;
+ virtual int get_packet_peer() const = 0;
- virtual void poll()=0;
+ virtual bool is_server() const = 0;
- virtual int get_unique_id() const=0;
+ virtual void poll() = 0;
- virtual void set_refuse_new_connections(bool p_enable)=0;
- virtual bool is_refusing_new_connections() const=0;
+ virtual int get_unique_id() const = 0;
+ virtual void set_refuse_new_connections(bool p_enable) = 0;
+ virtual bool is_refusing_new_connections() const = 0;
- virtual ConnectionStatus get_connection_status() const=0;
+ virtual ConnectionStatus get_connection_status() const = 0;
NetworkedMultiplayerPeer();
};
-VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::TransferMode )
-VARIANT_ENUM_CAST( NetworkedMultiplayerPeer::ConnectionStatus )
+VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::TransferMode)
+VARIANT_ENUM_CAST(NetworkedMultiplayerPeer::ConnectionStatus)
#endif // NetworkedMultiplayerPeer_H
diff --git a/core/io/packet_peer.cpp b/core/io/packet_peer.cpp
index cf5883121f..8115673d46 100644
--- a/core/io/packet_peer.cpp
+++ b/core/io/packet_peer.cpp
@@ -28,77 +28,71 @@
/*************************************************************************/
#include "packet_peer.h"
-#include "io/marshalls.h"
#include "global_config.h"
+#include "io/marshalls.h"
/* helpers / binders */
-
-
PacketPeer::PacketPeer() {
- last_get_error=OK;
+ last_get_error = OK;
}
Error PacketPeer::get_packet_buffer(PoolVector<uint8_t> &r_buffer) const {
const uint8_t *buffer;
int buffer_size;
- Error err = get_packet(&buffer,buffer_size);
+ Error err = get_packet(&buffer, buffer_size);
if (err)
return err;
r_buffer.resize(buffer_size);
- if (buffer_size==0)
+ if (buffer_size == 0)
return OK;
PoolVector<uint8_t>::Write w = r_buffer.write();
- for(int i=0;i<buffer_size;i++)
- w[i]=buffer[i];
+ for (int i = 0; i < buffer_size; i++)
+ w[i] = buffer[i];
return OK;
-
}
Error PacketPeer::put_packet_buffer(const PoolVector<uint8_t> &p_buffer) {
int len = p_buffer.size();
- if (len==0)
+ if (len == 0)
return OK;
PoolVector<uint8_t>::Read r = p_buffer.read();
- return put_packet(&r[0],len);
-
+ return put_packet(&r[0], len);
}
Error PacketPeer::get_var(Variant &r_variant) const {
const uint8_t *buffer;
int buffer_size;
- Error err = get_packet(&buffer,buffer_size);
+ Error err = get_packet(&buffer, buffer_size);
if (err)
return err;
- return decode_variant(r_variant,buffer,buffer_size);
-
+ return decode_variant(r_variant, buffer, buffer_size);
}
-Error PacketPeer::put_var(const Variant& p_packet) {
+Error PacketPeer::put_var(const Variant &p_packet) {
int len;
- Error err = encode_variant(p_packet,NULL,len); // compute len first
+ Error err = encode_variant(p_packet, NULL, len); // compute len first
if (err)
return err;
- if (len==0)
+ if (len == 0)
return OK;
- uint8_t *buf = (uint8_t*)alloca(len);
- ERR_FAIL_COND_V(!buf,ERR_OUT_OF_MEMORY);
- err = encode_variant(p_packet,buf,len);
+ uint8_t *buf = (uint8_t *)alloca(len);
+ ERR_FAIL_COND_V(!buf, ERR_OUT_OF_MEMORY);
+ err = encode_variant(p_packet, buf, len);
ERR_FAIL_COND_V(err, err);
return put_packet(buf, len);
-
}
Variant PacketPeer::_bnd_get_var() const {
@@ -108,13 +102,13 @@ Variant PacketPeer::_bnd_get_var() const {
return var;
};
-Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) {
+Error PacketPeer::_put_packet(const PoolVector<uint8_t> &p_buffer) {
return put_packet_buffer(p_buffer);
}
PoolVector<uint8_t> PacketPeer::_get_packet() const {
PoolVector<uint8_t> raw;
- last_get_error=get_packet_buffer(raw);
+ last_get_error = get_packet_buffer(raw);
return raw;
}
@@ -123,20 +117,18 @@ Error PacketPeer::_get_packet_error() const {
return last_get_error;
}
-
void PacketPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_var:Variant"),&PacketPeer::_bnd_get_var);
- ClassDB::bind_method(D_METHOD("put_var", "var:Variant"),&PacketPeer::put_var);
- ClassDB::bind_method(D_METHOD("get_packet"),&PacketPeer::_get_packet);
- ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"),&PacketPeer::_put_packet);
- ClassDB::bind_method(D_METHOD("get_packet_error:Error"),&PacketPeer::_get_packet_error);
- ClassDB::bind_method(D_METHOD("get_available_packet_count"),&PacketPeer::get_available_packet_count);
+ ClassDB::bind_method(D_METHOD("get_var:Variant"), &PacketPeer::_bnd_get_var);
+ ClassDB::bind_method(D_METHOD("put_var", "var:Variant"), &PacketPeer::put_var);
+ ClassDB::bind_method(D_METHOD("get_packet"), &PacketPeer::_get_packet);
+ ClassDB::bind_method(D_METHOD("put_packet:Error", "buffer"), &PacketPeer::_put_packet);
+ ClassDB::bind_method(D_METHOD("get_packet_error:Error"), &PacketPeer::_get_packet_error);
+ ClassDB::bind_method(D_METHOD("get_available_packet_count"), &PacketPeer::get_available_packet_count);
};
/***************/
-
void PacketPeerStream::_set_stream_peer(REF p_peer) {
ERR_FAIL_COND(p_peer.is_null());
@@ -145,22 +137,22 @@ void PacketPeerStream::_set_stream_peer(REF p_peer) {
void PacketPeerStream::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_stream_peer","peer:StreamPeer"),&PacketPeerStream::_set_stream_peer);
+ ClassDB::bind_method(D_METHOD("set_stream_peer", "peer:StreamPeer"), &PacketPeerStream::_set_stream_peer);
}
Error PacketPeerStream::_poll_buffer() const {
- ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED);
int read = 0;
Error err = peer->get_partial_data(&temp_buffer[0], ring_buffer.space_left(), read);
if (err)
return err;
- if (read==0)
+ if (read == 0)
return OK;
- int w = ring_buffer.write(&temp_buffer[0],read);
- ERR_FAIL_COND_V(w!=read,ERR_BUG);
+ int w = ring_buffer.write(&temp_buffer[0], read);
+ ERR_FAIL_COND_V(w != read, ERR_BUG);
return OK;
}
@@ -171,73 +163,71 @@ int PacketPeerStream::get_available_packet_count() const {
uint32_t remaining = ring_buffer.data_left();
- int ofs=0;
- int count=0;
+ int ofs = 0;
+ int count = 0;
- while(remaining>=4) {
+ while (remaining >= 4) {
uint8_t lbuf[4];
- ring_buffer.copy(lbuf,ofs,4);
+ ring_buffer.copy(lbuf, ofs, 4);
uint32_t len = decode_uint32(lbuf);
- remaining-=4;
- ofs+=4;
- if (len>remaining)
+ remaining -= 4;
+ ofs += 4;
+ if (len > remaining)
break;
- remaining-=len;
- ofs+=len;
+ remaining -= len;
+ ofs += len;
count++;
}
return count;
}
-Error PacketPeerStream::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const {
+Error PacketPeerStream::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const {
- ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED);
_poll_buffer();
int remaining = ring_buffer.data_left();
- ERR_FAIL_COND_V(remaining<4,ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(remaining < 4, ERR_UNAVAILABLE);
uint8_t lbuf[4];
- ring_buffer.copy(lbuf,0,4);
- remaining-=4;
+ ring_buffer.copy(lbuf, 0, 4);
+ remaining -= 4;
uint32_t len = decode_uint32(lbuf);
- ERR_FAIL_COND_V(remaining<(int)len,ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(remaining < (int)len, ERR_UNAVAILABLE);
- ring_buffer.read(lbuf,4); //get rid of first 4 bytes
- ring_buffer.read(&temp_buffer[0],len); // read packet
+ ring_buffer.read(lbuf, 4); //get rid of first 4 bytes
+ ring_buffer.read(&temp_buffer[0], len); // read packet
- *r_buffer=&temp_buffer[0];
- r_buffer_size=len;
+ *r_buffer = &temp_buffer[0];
+ r_buffer_size = len;
return OK;
-
}
-Error PacketPeerStream::put_packet(const uint8_t *p_buffer,int p_buffer_size) {
+Error PacketPeerStream::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
- ERR_FAIL_COND_V(peer.is_null(),ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED);
Error err = _poll_buffer(); //won't hurt to poll here too
if (err)
return err;
- if (p_buffer_size==0)
+ if (p_buffer_size == 0)
return OK;
- ERR_FAIL_COND_V( p_buffer_size<0, ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V( p_buffer_size+4 > temp_buffer.size(), ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_buffer_size < 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_buffer_size + 4 > temp_buffer.size(), ERR_INVALID_PARAMETER);
- encode_uint32(p_buffer_size,&temp_buffer[0]);
- uint8_t *dst=&temp_buffer[4];
- for(int i=0;i<p_buffer_size;i++)
- dst[i]=p_buffer[i];
+ encode_uint32(p_buffer_size, &temp_buffer[0]);
+ uint8_t *dst = &temp_buffer[4];
+ for (int i = 0; i < p_buffer_size; i++)
+ dst[i] = p_buffer[i];
- return peer->put_data(&temp_buffer[0],p_buffer_size+4);
+ return peer->put_data(&temp_buffer[0], p_buffer_size + 4);
}
int PacketPeerStream::get_max_packet_size() const {
-
return temp_buffer.size();
}
@@ -249,7 +239,7 @@ void PacketPeerStream::set_stream_peer(const Ref<StreamPeer> &p_peer) {
ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer
};
- peer=p_peer;
+ peer = p_peer;
}
void PacketPeerStream::set_input_buffer_max_size(int p_max_size) {
@@ -257,19 +247,14 @@ void PacketPeerStream::set_input_buffer_max_size(int p_max_size) {
//warning may lose packets
ERR_EXPLAIN("Buffer in use, resizing would cause loss of data");
ERR_FAIL_COND(ring_buffer.data_left());
- ring_buffer.resize(nearest_shift(p_max_size+4));
- temp_buffer.resize(nearest_power_of_2(p_max_size+4));
-
+ ring_buffer.resize(nearest_shift(p_max_size + 4));
+ temp_buffer.resize(nearest_power_of_2(p_max_size + 4));
}
PacketPeerStream::PacketPeerStream() {
-
- int rbsize=GLOBAL_GET( "network/packets/packet_stream_peer_max_buffer_po2");
-
+ int rbsize = GLOBAL_GET("network/packets/packet_stream_peer_max_buffer_po2");
ring_buffer.resize(rbsize);
- temp_buffer.resize(1<<rbsize);
-
-
+ temp_buffer.resize(1 << rbsize);
}
diff --git a/core/io/packet_peer.h b/core/io/packet_peer.h
index bacd5214f1..5f8d63f8c8 100644
--- a/core/io/packet_peer.h
+++ b/core/io/packet_peer.h
@@ -29,33 +29,30 @@
#ifndef PACKET_PEER_H
#define PACKET_PEER_H
-#include "object.h"
#include "io/stream_peer.h"
+#include "object.h"
#include "ring_buffer.h"
class PacketPeer : public Reference {
- GDCLASS( PacketPeer, Reference );
+ GDCLASS(PacketPeer, Reference);
Variant _bnd_get_var() const;
- void _bnd_put_var(const Variant& p_var);
+ void _bnd_put_var(const Variant &p_var);
static void _bind_methods();
-
Error _put_packet(const PoolVector<uint8_t> &p_buffer);
PoolVector<uint8_t> _get_packet() const;
Error _get_packet_error() const;
-
mutable Error last_get_error;
public:
+ virtual int get_available_packet_count() const = 0;
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const = 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_available_packet_count() const=0;
- virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const=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;
+ virtual int get_max_packet_size() const = 0;
/* helpers / binders */
@@ -63,15 +60,15 @@ public:
virtual Error put_packet_buffer(const PoolVector<uint8_t> &p_buffer);
virtual Error get_var(Variant &r_variant) const;
- virtual Error put_var(const Variant& p_packet);
+ virtual Error put_var(const Variant &p_packet);
PacketPeer();
- ~PacketPeer(){}
+ ~PacketPeer() {}
};
class PacketPeerStream : public PacketPeer {
- GDCLASS(PacketPeerStream,PacketPeer);
+ GDCLASS(PacketPeerStream, PacketPeer);
//the way the buffers work sucks, will change later
@@ -80,25 +77,21 @@ class PacketPeerStream : public PacketPeer {
mutable Vector<uint8_t> temp_buffer;
Error _poll_buffer() const;
-protected:
+protected:
void _set_stream_peer(REF p_peer);
static void _bind_methods();
-public:
+public:
virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const;
- virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size);
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
virtual int get_max_packet_size() const;
-
-
- void set_stream_peer(const Ref<StreamPeer>& p_peer);
+ void set_stream_peer(const Ref<StreamPeer> &p_peer);
void set_input_buffer_max_size(int p_max_size);
PacketPeerStream();
-
};
-
#endif // PACKET_STREAM_H
diff --git a/core/io/packet_peer_udp.cpp b/core/io/packet_peer_udp.cpp
index c4a6fd79a8..46accf420a 100644
--- a/core/io/packet_peer_udp.cpp
+++ b/core/io/packet_peer_udp.cpp
@@ -29,40 +29,38 @@
#include "packet_peer_udp.h"
#include "io/ip.h"
-PacketPeerUDP* (*PacketPeerUDP::_create)()=NULL;
+PacketPeerUDP *(*PacketPeerUDP::_create)() = NULL;
String PacketPeerUDP::_get_packet_ip() const {
return get_packet_address();
}
-Error PacketPeerUDP::_set_dest_address(const String& p_address, int p_port) {
+Error PacketPeerUDP::_set_dest_address(const String &p_address, int p_port) {
IP_Address ip;
if (p_address.is_valid_ip_address()) {
- ip=p_address;
+ ip = p_address;
} else {
- ip=IP::get_singleton()->resolve_hostname(p_address);
+ ip = IP::get_singleton()->resolve_hostname(p_address);
if (!ip.is_valid())
return ERR_CANT_RESOLVE;
}
- set_dest_address(ip,p_port);
+ set_dest_address(ip, p_port);
return OK;
}
void PacketPeerUDP::_bind_methods() {
- ClassDB::bind_method(D_METHOD("listen:Error","port", "bind_address", "recv_buf_size"),&PacketPeerUDP::listen,DEFVAL("*"),DEFVAL(65536));
- ClassDB::bind_method(D_METHOD("close"),&PacketPeerUDP::close);
- ClassDB::bind_method(D_METHOD("wait:Error"),&PacketPeerUDP::wait);
- ClassDB::bind_method(D_METHOD("is_listening"),&PacketPeerUDP::is_listening);
- ClassDB::bind_method(D_METHOD("get_packet_ip"),&PacketPeerUDP::_get_packet_ip);
+ ClassDB::bind_method(D_METHOD("listen:Error", "port", "bind_address", "recv_buf_size"), &PacketPeerUDP::listen, DEFVAL("*"), DEFVAL(65536));
+ ClassDB::bind_method(D_METHOD("close"), &PacketPeerUDP::close);
+ ClassDB::bind_method(D_METHOD("wait:Error"), &PacketPeerUDP::wait);
+ ClassDB::bind_method(D_METHOD("is_listening"), &PacketPeerUDP::is_listening);
+ ClassDB::bind_method(D_METHOD("get_packet_ip"), &PacketPeerUDP::_get_packet_ip);
//ClassDB::bind_method(D_METHOD("get_packet_address"),&PacketPeerUDP::_get_packet_address);
- ClassDB::bind_method(D_METHOD("get_packet_port"),&PacketPeerUDP::get_packet_port);
- ClassDB::bind_method(D_METHOD("set_dest_address","host","port"),&PacketPeerUDP::_set_dest_address);
-
-
+ ClassDB::bind_method(D_METHOD("get_packet_port"), &PacketPeerUDP::get_packet_port);
+ ClassDB::bind_method(D_METHOD("set_dest_address", "host", "port"), &PacketPeerUDP::_set_dest_address);
}
Ref<PacketPeerUDP> PacketPeerUDP::create_ref() {
@@ -72,14 +70,12 @@ Ref<PacketPeerUDP> PacketPeerUDP::create_ref() {
return Ref<PacketPeerUDP>(_create());
}
-PacketPeerUDP* PacketPeerUDP::create() {
+PacketPeerUDP *PacketPeerUDP::create() {
if (!_create)
return NULL;
return _create();
}
-PacketPeerUDP::PacketPeerUDP()
-{
-
+PacketPeerUDP::PacketPeerUDP() {
}
diff --git a/core/io/packet_peer_udp.h b/core/io/packet_peer_udp.h
index 726406887c..c316faad4b 100644
--- a/core/io/packet_peer_udp.h
+++ b/core/io/packet_peer_udp.h
@@ -29,35 +29,31 @@
#ifndef PACKET_PEER_UDP_H
#define PACKET_PEER_UDP_H
-
#include "io/ip.h"
#include "io/packet_peer.h"
class PacketPeerUDP : public PacketPeer {
- GDCLASS(PacketPeerUDP,PacketPeer);
+ GDCLASS(PacketPeerUDP, PacketPeer);
protected:
-
- static PacketPeerUDP* (*_create)();
+ static PacketPeerUDP *(*_create)();
static void _bind_methods();
String _get_packet_ip() const;
- Error _set_dest_address(const String& p_address,int p_port);
+ Error _set_dest_address(const String &p_address, int p_port);
public:
-
- virtual Error listen(int p_port, IP_Address p_bind_address=IP_Address("*"), int p_recv_buffer_size=65536)=0;
- virtual void close()=0;
- virtual Error wait()=0;
- virtual bool is_listening() const=0;
- virtual IP_Address get_packet_address() const=0;
- virtual int get_packet_port() const=0;
- virtual void set_dest_address(const IP_Address& p_address,int p_port)=0;
-
+ virtual Error listen(int p_port, IP_Address p_bind_address = IP_Address("*"), int p_recv_buffer_size = 65536) = 0;
+ virtual void close() = 0;
+ virtual Error wait() = 0;
+ virtual bool is_listening() const = 0;
+ virtual IP_Address get_packet_address() const = 0;
+ virtual int get_packet_port() const = 0;
+ virtual void set_dest_address(const IP_Address &p_address, int p_port) = 0;
static Ref<PacketPeerUDP> create_ref();
- static PacketPeerUDP* create();
+ static PacketPeerUDP *create();
PacketPeerUDP();
};
diff --git a/core/io/pck_packer.cpp b/core/io/pck_packer.cpp
index 2cd46843e8..9dd9b044a2 100644
--- a/core/io/pck_packer.cpp
+++ b/core/io/pck_packer.cpp
@@ -42,9 +42,9 @@ static uint64_t _align(uint64_t p_n, int p_alignment) {
return p_n + (p_alignment - rest);
};
-static void _pad(FileAccess* p_file, int p_bytes) {
+static void _pad(FileAccess *p_file, int p_bytes) {
- for (int i=0; i<p_bytes; i++) {
+ for (int i = 0; i < p_bytes; i++) {
p_file->store_8(0);
};
@@ -52,13 +52,12 @@ static void _pad(FileAccess* p_file, int p_bytes) {
void PCKPacker::_bind_methods() {
- ClassDB::bind_method(D_METHOD("pck_start","pck_name","alignment"),&PCKPacker::pck_start);
- ClassDB::bind_method(D_METHOD("add_file","pck_path","source_path"),&PCKPacker::add_file);
- ClassDB::bind_method(D_METHOD("flush","verbose"),&PCKPacker::flush);
+ ClassDB::bind_method(D_METHOD("pck_start", "pck_name", "alignment"), &PCKPacker::pck_start);
+ ClassDB::bind_method(D_METHOD("add_file", "pck_path", "source_path"), &PCKPacker::add_file);
+ ClassDB::bind_method(D_METHOD("flush", "verbose"), &PCKPacker::flush);
};
-
-Error PCKPacker::pck_start(const String& p_file, int p_alignment) {
+Error PCKPacker::pck_start(const String &p_file, int p_alignment) {
file = FileAccess::open(p_file, FileAccess::WRITE);
if (file == NULL) {
@@ -74,7 +73,7 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) {
file->store_32(0); // # minor
file->store_32(0); // # revision
- for (int i=0; i<16; i++) {
+ for (int i = 0; i < 16; i++) {
file->store_32(0); // reserved
};
@@ -84,9 +83,9 @@ Error PCKPacker::pck_start(const String& p_file, int p_alignment) {
return OK;
};
-Error PCKPacker::add_file(const String& p_file, const String& p_src) {
+Error PCKPacker::add_file(const String &p_file, const String &p_src) {
- FileAccess* f = FileAccess::open(p_src, FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_src, FileAccess::READ);
if (!f) {
return ERR_FILE_CANT_OPEN;
};
@@ -116,7 +115,7 @@ Error PCKPacker::flush(bool p_verbose) {
file->store_32(files.size());
- for (int i=0; i<files.size(); i++) {
+ for (int i = 0; i < files.size(); i++) {
file->store_pascal_string(files[i].path);
files[i].offset_offset = file->get_pos();
@@ -130,7 +129,6 @@ Error PCKPacker::flush(bool p_verbose) {
file->store_32(0);
};
-
uint64_t ofs = file->get_pos();
ofs = _align(ofs, alignment);
@@ -140,9 +138,9 @@ Error PCKPacker::flush(bool p_verbose) {
uint8_t *buf = memnew_arr(uint8_t, buf_max);
int count = 0;
- for (int i=0; i<files.size(); i++) {
+ for (int i = 0; i < files.size(); i++) {
- FileAccess* src = FileAccess::open(files[i].src_path, FileAccess::READ);
+ FileAccess *src = FileAccess::open(files[i].src_path, FileAccess::READ);
uint64_t to_write = files[i].size;
while (to_write > 0) {
diff --git a/core/io/pck_packer.h b/core/io/pck_packer.h
index a4eba04f2d..1edb14ab27 100644
--- a/core/io/pck_packer.h
+++ b/core/io/pck_packer.h
@@ -34,7 +34,7 @@ class PCKPacker : public Reference {
GDCLASS(PCKPacker, Reference);
- FileAccess* file;
+ FileAccess *file;
int alignment;
static void _bind_methods();
@@ -49,11 +49,10 @@ class PCKPacker : public Reference {
Vector<File> files;
public:
- Error pck_start(const String& p_file, int p_alignment);
- Error add_file(const String& p_file, const String& p_src);
+ Error pck_start(const String &p_file, int p_alignment);
+ Error add_file(const String &p_file, const String &p_src);
Error flush(bool p_verbose = false);
-
PCKPacker();
~PCKPacker();
};
diff --git a/core/io/resource_format_binary.cpp b/core/io/resource_format_binary.cpp
index 2d733842fa..60dccebebf 100644
--- a/core/io/resource_format_binary.cpp
+++ b/core/io/resource_format_binary.cpp
@@ -26,315 +26,303 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "version.h"
#include "resource_format_binary.h"
#include "global_config.h"
#include "io/file_access_compressed.h"
#include "io/marshalls.h"
#include "os/dir_access.h"
+#include "version.h"
//#define print_bl(m_what) print_line(m_what)
#define print_bl(m_what)
-
enum {
//numbering must be different from variant, in case new variant types are added (variant must be always contiguous for jumptable optimization)
- VARIANT_NIL=1,
- VARIANT_BOOL=2,
- VARIANT_INT=3,
- VARIANT_REAL=4,
- VARIANT_STRING=5,
- VARIANT_VECTOR2=10,
- VARIANT_RECT2=11,
- VARIANT_VECTOR3=12,
- VARIANT_PLANE=13,
- VARIANT_QUAT=14,
- VARIANT_AABB=15,
- VARIANT_MATRIX3=16,
- VARIANT_TRANSFORM=17,
- VARIANT_MATRIX32=18,
- VARIANT_COLOR=20,
- VARIANT_IMAGE=21,
- VARIANT_NODE_PATH=22,
- VARIANT_RID=23,
- VARIANT_OBJECT=24,
- VARIANT_INPUT_EVENT=25,
- VARIANT_DICTIONARY=26,
- VARIANT_ARRAY=30,
- VARIANT_RAW_ARRAY=31,
- VARIANT_INT_ARRAY=32,
- VARIANT_REAL_ARRAY=33,
- VARIANT_STRING_ARRAY=34,
- VARIANT_VECTOR3_ARRAY=35,
- VARIANT_COLOR_ARRAY=36,
- VARIANT_VECTOR2_ARRAY=37,
- VARIANT_INT64=40,
- VARIANT_DOUBLE=41,
-
- IMAGE_ENCODING_EMPTY=0,
- IMAGE_ENCODING_RAW=1,
- IMAGE_ENCODING_LOSSLESS=2,
- IMAGE_ENCODING_LOSSY=3,
-
- OBJECT_EMPTY=0,
- OBJECT_EXTERNAL_RESOURCE=1,
- OBJECT_INTERNAL_RESOURCE=2,
- OBJECT_EXTERNAL_RESOURCE_INDEX=3,
+ VARIANT_NIL = 1,
+ VARIANT_BOOL = 2,
+ VARIANT_INT = 3,
+ VARIANT_REAL = 4,
+ VARIANT_STRING = 5,
+ VARIANT_VECTOR2 = 10,
+ VARIANT_RECT2 = 11,
+ VARIANT_VECTOR3 = 12,
+ VARIANT_PLANE = 13,
+ VARIANT_QUAT = 14,
+ VARIANT_AABB = 15,
+ VARIANT_MATRIX3 = 16,
+ VARIANT_TRANSFORM = 17,
+ VARIANT_MATRIX32 = 18,
+ VARIANT_COLOR = 20,
+ VARIANT_IMAGE = 21,
+ VARIANT_NODE_PATH = 22,
+ VARIANT_RID = 23,
+ VARIANT_OBJECT = 24,
+ VARIANT_INPUT_EVENT = 25,
+ VARIANT_DICTIONARY = 26,
+ VARIANT_ARRAY = 30,
+ VARIANT_RAW_ARRAY = 31,
+ VARIANT_INT_ARRAY = 32,
+ VARIANT_REAL_ARRAY = 33,
+ VARIANT_STRING_ARRAY = 34,
+ VARIANT_VECTOR3_ARRAY = 35,
+ VARIANT_COLOR_ARRAY = 36,
+ VARIANT_VECTOR2_ARRAY = 37,
+ VARIANT_INT64 = 40,
+ VARIANT_DOUBLE = 41,
+
+ IMAGE_ENCODING_EMPTY = 0,
+ IMAGE_ENCODING_RAW = 1,
+ IMAGE_ENCODING_LOSSLESS = 2,
+ IMAGE_ENCODING_LOSSY = 3,
+
+ OBJECT_EMPTY = 0,
+ OBJECT_EXTERNAL_RESOURCE = 1,
+ OBJECT_INTERNAL_RESOURCE = 2,
+ OBJECT_EXTERNAL_RESOURCE_INDEX = 3,
//version 2: added 64 bits support for float and int
- FORMAT_VERSION=2,
- FORMAT_VERSION_CAN_RENAME_DEPS=1
-
+ FORMAT_VERSION = 2,
+ FORMAT_VERSION_CAN_RENAME_DEPS = 1
};
-
void ResourceInteractiveLoaderBinary::_advance_padding(uint32_t p_len) {
- uint32_t extra = 4-(p_len%4);
- if (extra<4) {
- for(uint32_t i=0;i<extra;i++)
+ uint32_t extra = 4 - (p_len % 4);
+ if (extra < 4) {
+ for (uint32_t i = 0; i < extra; i++)
f->get_8(); //pad to 32
}
-
}
-
StringName ResourceInteractiveLoaderBinary::_get_string() {
uint32_t id = f->get_32();
- if (id&0x80000000) {
- uint32_t len = id&0x7FFFFFFF;
- if (len>str_buf.size()) {
+ if (id & 0x80000000) {
+ uint32_t len = id & 0x7FFFFFFF;
+ if (len > str_buf.size()) {
str_buf.resize(len);
}
- if (len==0)
+ if (len == 0)
return StringName();
- f->get_buffer((uint8_t*)&str_buf[0],len);
+ f->get_buffer((uint8_t *)&str_buf[0], len);
String s;
s.parse_utf8(&str_buf[0]);
return s;
}
return string_map[id];
-
}
-Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
-
+Error ResourceInteractiveLoaderBinary::parse_variant(Variant &r_v) {
uint32_t type = f->get_32();
- print_bl("find property of type: "+itos(type));
-
+ print_bl("find property of type: " + itos(type));
- switch(type) {
+ switch (type) {
case VARIANT_NIL: {
- r_v=Variant();
+ r_v = Variant();
} break;
case VARIANT_BOOL: {
- r_v=bool(f->get_32());
+ r_v = bool(f->get_32());
} break;
case VARIANT_INT: {
- r_v=int(f->get_32());
+ r_v = int(f->get_32());
} break;
case VARIANT_INT64: {
- r_v=int64_t(f->get_64());
+ r_v = int64_t(f->get_64());
} break;
case VARIANT_REAL: {
- r_v=f->get_real();
+ r_v = f->get_real();
} break;
case VARIANT_DOUBLE: {
- r_v=f->get_double();
+ r_v = f->get_double();
} break;
case VARIANT_STRING: {
- r_v=get_unicode_string();
+ r_v = get_unicode_string();
} break;
case VARIANT_VECTOR2: {
Vector2 v;
- v.x=f->get_real();
- v.y=f->get_real();
- r_v=v;
+ v.x = f->get_real();
+ v.y = f->get_real();
+ r_v = v;
} break;
case VARIANT_RECT2: {
Rect2 v;
- v.pos.x=f->get_real();
- v.pos.y=f->get_real();
- v.size.x=f->get_real();
- v.size.y=f->get_real();
- r_v=v;
+ v.pos.x = f->get_real();
+ v.pos.y = f->get_real();
+ v.size.x = f->get_real();
+ v.size.y = f->get_real();
+ r_v = v;
} break;
case VARIANT_VECTOR3: {
Vector3 v;
- v.x=f->get_real();
- v.y=f->get_real();
- v.z=f->get_real();
- r_v=v;
+ v.x = f->get_real();
+ v.y = f->get_real();
+ v.z = f->get_real();
+ r_v = v;
} break;
case VARIANT_PLANE: {
Plane v;
- v.normal.x=f->get_real();
- v.normal.y=f->get_real();
- v.normal.z=f->get_real();
- v.d=f->get_real();
- r_v=v;
+ v.normal.x = f->get_real();
+ v.normal.y = f->get_real();
+ v.normal.z = f->get_real();
+ v.d = f->get_real();
+ r_v = v;
} break;
case VARIANT_QUAT: {
Quat v;
- v.x=f->get_real();
- v.y=f->get_real();
- v.z=f->get_real();
- v.w=f->get_real();
- r_v=v;
+ v.x = f->get_real();
+ v.y = f->get_real();
+ v.z = f->get_real();
+ v.w = f->get_real();
+ r_v = v;
} break;
case VARIANT_AABB: {
Rect3 v;
- v.pos.x=f->get_real();
- v.pos.y=f->get_real();
- v.pos.z=f->get_real();
- v.size.x=f->get_real();
- v.size.y=f->get_real();
- v.size.z=f->get_real();
- r_v=v;
+ v.pos.x = f->get_real();
+ v.pos.y = f->get_real();
+ v.pos.z = f->get_real();
+ v.size.x = f->get_real();
+ v.size.y = f->get_real();
+ v.size.z = f->get_real();
+ r_v = v;
} break;
case VARIANT_MATRIX32: {
Transform2D v;
- v.elements[0].x=f->get_real();
- v.elements[0].y=f->get_real();
- v.elements[1].x=f->get_real();
- v.elements[1].y=f->get_real();
- v.elements[2].x=f->get_real();
- v.elements[2].y=f->get_real();
- r_v=v;
+ v.elements[0].x = f->get_real();
+ v.elements[0].y = f->get_real();
+ v.elements[1].x = f->get_real();
+ v.elements[1].y = f->get_real();
+ v.elements[2].x = f->get_real();
+ v.elements[2].y = f->get_real();
+ r_v = v;
} break;
case VARIANT_MATRIX3: {
Basis v;
- v.elements[0].x=f->get_real();
- v.elements[0].y=f->get_real();
- v.elements[0].z=f->get_real();
- v.elements[1].x=f->get_real();
- v.elements[1].y=f->get_real();
- v.elements[1].z=f->get_real();
- v.elements[2].x=f->get_real();
- v.elements[2].y=f->get_real();
- v.elements[2].z=f->get_real();
- r_v=v;
+ v.elements[0].x = f->get_real();
+ v.elements[0].y = f->get_real();
+ v.elements[0].z = f->get_real();
+ v.elements[1].x = f->get_real();
+ v.elements[1].y = f->get_real();
+ v.elements[1].z = f->get_real();
+ v.elements[2].x = f->get_real();
+ v.elements[2].y = f->get_real();
+ v.elements[2].z = f->get_real();
+ r_v = v;
} break;
case VARIANT_TRANSFORM: {
Transform v;
- v.basis.elements[0].x=f->get_real();
- v.basis.elements[0].y=f->get_real();
- v.basis.elements[0].z=f->get_real();
- v.basis.elements[1].x=f->get_real();
- v.basis.elements[1].y=f->get_real();
- v.basis.elements[1].z=f->get_real();
- v.basis.elements[2].x=f->get_real();
- v.basis.elements[2].y=f->get_real();
- v.basis.elements[2].z=f->get_real();
- v.origin.x=f->get_real();
- v.origin.y=f->get_real();
- v.origin.z=f->get_real();
- r_v=v;
+ v.basis.elements[0].x = f->get_real();
+ v.basis.elements[0].y = f->get_real();
+ v.basis.elements[0].z = f->get_real();
+ v.basis.elements[1].x = f->get_real();
+ v.basis.elements[1].y = f->get_real();
+ v.basis.elements[1].z = f->get_real();
+ v.basis.elements[2].x = f->get_real();
+ v.basis.elements[2].y = f->get_real();
+ v.basis.elements[2].z = f->get_real();
+ v.origin.x = f->get_real();
+ v.origin.y = f->get_real();
+ v.origin.z = f->get_real();
+ r_v = v;
} break;
case VARIANT_COLOR: {
Color v;
- v.r=f->get_real();
- v.g=f->get_real();
- v.b=f->get_real();
- v.a=f->get_real();
- r_v=v;
+ v.r = f->get_real();
+ v.g = f->get_real();
+ v.b = f->get_real();
+ v.a = f->get_real();
+ r_v = v;
} break;
case VARIANT_IMAGE: {
-
uint32_t encoding = f->get_32();
- if (encoding==IMAGE_ENCODING_EMPTY) {
- r_v=Variant();
+ if (encoding == IMAGE_ENCODING_EMPTY) {
+ r_v = Variant();
break;
- } else if (encoding==IMAGE_ENCODING_RAW) {
+ } else if (encoding == IMAGE_ENCODING_RAW) {
uint32_t width = f->get_32();
uint32_t height = f->get_32();
uint32_t mipmaps = f->get_32();
uint32_t format = f->get_32();
- const uint32_t format_version_shift=24;
- const uint32_t format_version_mask=format_version_shift-1;
+ const uint32_t format_version_shift = 24;
+ const uint32_t format_version_mask = format_version_shift - 1;
- uint32_t format_version = format>>format_version_shift;
+ uint32_t format_version = format >> format_version_shift;
const uint32_t current_version = 0;
- if (format_version>current_version) {
+ if (format_version > current_version) {
ERR_PRINT("Format version for encoded binary image is too new");
return ERR_PARSE_ERROR;
}
-
- Image::Format fmt=Image::Format(format&format_version_mask); //if format changes, we can add a compatibility bit on top
+ Image::Format fmt = Image::Format(format & format_version_mask); //if format changes, we can add a compatibility bit on top
uint32_t datalen = f->get_32();
- print_line("image format: "+String(Image::get_format_name(fmt))+" datalen "+itos(datalen));
+ print_line("image format: " + String(Image::get_format_name(fmt)) + " datalen " + itos(datalen));
PoolVector<uint8_t> imgdata;
imgdata.resize(datalen);
PoolVector<uint8_t>::Write w = imgdata.write();
- f->get_buffer(w.ptr(),datalen);
+ f->get_buffer(w.ptr(), datalen);
_advance_padding(datalen);
- w=PoolVector<uint8_t>::Write();
+ w = PoolVector<uint8_t>::Write();
#ifdef TOOLS_ENABLED
-//compatibility
- int correct_size = Image::get_image_data_size(width,height,fmt,mipmaps?-1:0);
+ //compatibility
+ int correct_size = Image::get_image_data_size(width, height, fmt, mipmaps ? -1 : 0);
if (correct_size < datalen) {
WARN_PRINT("Image data was too large, shrinking for compatibility")
imgdata.resize(correct_size);
}
#endif
- r_v=Image(width,height,mipmaps,fmt,imgdata);
+ r_v = Image(width, height, mipmaps, fmt, imgdata);
} else {
//compressed
PoolVector<uint8_t> data;
data.resize(f->get_32());
PoolVector<uint8_t>::Write w = data.write();
- f->get_buffer(w.ptr(),data.size());
+ f->get_buffer(w.ptr(), data.size());
w = PoolVector<uint8_t>::Write();
Image img;
- if (encoding==IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) {
+ if (encoding == IMAGE_ENCODING_LOSSY && Image::lossy_unpacker) {
img = Image::lossy_unpacker(data);
- } else if (encoding==IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) {
+ } else if (encoding == IMAGE_ENCODING_LOSSLESS && Image::lossless_unpacker) {
img = Image::lossless_unpacker(data);
}
_advance_padding(data.size());
-
- r_v=img;
-
+ r_v = img;
}
} break;
@@ -347,44 +335,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
int name_count = f->get_16();
uint32_t subname_count = f->get_16();
- absolute=subname_count&0x8000;
- subname_count&=0x7FFF;
-
+ absolute = subname_count & 0x8000;
+ subname_count &= 0x7FFF;
- for(int i=0;i<name_count;i++)
+ for (int i = 0; i < name_count; i++)
names.push_back(_get_string());
- for(uint32_t i=0;i<subname_count;i++)
+ for (uint32_t i = 0; i < subname_count; i++)
subnames.push_back(_get_string());
- property=_get_string();
+ property = _get_string();
- NodePath np = NodePath(names,subnames,absolute,property);
+ NodePath np = NodePath(names, subnames, absolute, property);
//print_line("got path: "+String(np));
- r_v=np;
+ r_v = np;
} break;
case VARIANT_RID: {
- r_v=f->get_32();
+ r_v = f->get_32();
} break;
case VARIANT_OBJECT: {
- uint32_t type=f->get_32();
+ uint32_t type = f->get_32();
- switch(type) {
+ switch (type) {
case OBJECT_EMPTY: {
//do none
} break;
case OBJECT_INTERNAL_RESOURCE: {
- uint32_t index=f->get_32();
- String path = res_path+"::"+itos(index);
+ uint32_t index = f->get_32();
+ String path = res_path + "::" + itos(index);
RES res = ResourceLoader::load(path);
if (res.is_null()) {
- WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data());
+ WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data());
}
- r_v=res;
+ r_v = res;
} break;
case OBJECT_EXTERNAL_RESOURCE: {
@@ -393,51 +380,48 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
String type = get_unicode_string();
String path = get_unicode_string();
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
-
+ path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
}
if (remaps.find(path)) {
- path=remaps[path];
+ path = remaps[path];
}
- RES res=ResourceLoader::load(path,type);
+ RES res = ResourceLoader::load(path, type);
if (res.is_null()) {
- WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data());
+ WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data());
}
- r_v=res;
+ r_v = res;
} break;
case OBJECT_EXTERNAL_RESOURCE_INDEX: {
//new file format, just refers to an index in the external list
uint32_t erindex = f->get_32();
- if (erindex>=external_resources.size()) {
+ if (erindex >= external_resources.size()) {
WARN_PRINT("Broken external resource! (index out of size");
- r_v=Variant();
+ r_v = Variant();
} else {
String type = external_resources[erindex].type;
String path = external_resources[erindex].path;
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
-
+ path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
}
- RES res=ResourceLoader::load(path,type);
+ RES res = ResourceLoader::load(path, type);
if (res.is_null()) {
- WARN_PRINT(String("Couldn't load resource: "+path).utf8().get_data());
+ WARN_PRINT(String("Couldn't load resource: " + path).utf8().get_data());
}
- r_v=res;
+ r_v = res;
}
-
} break;
default: {
@@ -449,39 +433,39 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
case VARIANT_INPUT_EVENT: {
InputEvent ev;
- ev.type=f->get_32(); //will only work for null though.
- r_v=ev;
+ ev.type = f->get_32(); //will only work for null though.
+ r_v = ev;
} break;
case VARIANT_DICTIONARY: {
- uint32_t len=f->get_32();
+ uint32_t len = f->get_32();
Dictionary d; //last bit means shared
- len&=0x7FFFFFFF;
- for(uint32_t i=0;i<len;i++) {
+ len &= 0x7FFFFFFF;
+ for (uint32_t i = 0; i < len; i++) {
Variant key;
Error err = parse_variant(key);
- ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT);
Variant value;
err = parse_variant(value);
- ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
- d[key]=value;
+ ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT);
+ d[key] = value;
}
- r_v=d;
+ r_v = d;
} break;
case VARIANT_ARRAY: {
- uint32_t len=f->get_32();
+ uint32_t len = f->get_32();
Array a; //last bit means shared
- len&=0x7FFFFFFF;
+ len &= 0x7FFFFFFF;
a.resize(len);
- for(uint32_t i=0;i<len;i++) {
+ for (uint32_t i = 0; i < len; i++) {
Variant val;
Error err = parse_variant(val);
- ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
- a[i]=val;
+ ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT);
+ a[i] = val;
}
- r_v=a;
+ r_v = a;
} break;
case VARIANT_RAW_ARRAY: {
@@ -491,10 +475,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<uint8_t> array;
array.resize(len);
PoolVector<uint8_t>::Write w = array.write();
- f->get_buffer(w.ptr(),len);
+ f->get_buffer(w.ptr(), len);
_advance_padding(len);
- w=PoolVector<uint8_t>::Write();
- r_v=array;
+ w = PoolVector<uint8_t>::Write();
+ r_v = array;
} break;
case VARIANT_INT_ARRAY: {
@@ -504,19 +488,19 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<int> array;
array.resize(len);
PoolVector<int>::Write w = array.write();
- f->get_buffer((uint8_t*)w.ptr(),len*4);
+ f->get_buffer((uint8_t *)w.ptr(), len * 4);
#ifdef BIG_ENDIAN_ENABLED
{
- uint32_t *ptr=(uint32_t*)w.ptr();
- for(int i=0;i<len;i++) {
+ uint32_t *ptr = (uint32_t *)w.ptr();
+ for (int i = 0; i < len; i++) {
- ptr[i]=BSWAP32(ptr[i]);
+ ptr[i] = BSWAP32(ptr[i]);
}
}
#endif
- w=PoolVector<int>::Write();
- r_v=array;
+ w = PoolVector<int>::Write();
+ r_v = array;
} break;
case VARIANT_REAL_ARRAY: {
@@ -525,20 +509,20 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<real_t> array;
array.resize(len);
PoolVector<real_t>::Write w = array.write();
- f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t));
+ f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t));
#ifdef BIG_ENDIAN_ENABLED
{
- uint32_t *ptr=(uint32_t*)w.ptr();
- for(int i=0;i<len;i++) {
+ uint32_t *ptr = (uint32_t *)w.ptr();
+ for (int i = 0; i < len; i++) {
- ptr[i]=BSWAP32(ptr[i]);
+ ptr[i] = BSWAP32(ptr[i]);
}
}
#endif
- w=PoolVector<real_t>::Write();
- r_v=array;
+ w = PoolVector<real_t>::Write();
+ r_v = array;
} break;
case VARIANT_STRING_ARRAY: {
@@ -546,11 +530,10 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<String> array;
array.resize(len);
PoolVector<String>::Write w = array.write();
- for(uint32_t i=0;i<len;i++)
- w[i]=get_unicode_string();
- w=PoolVector<String>::Write();
- r_v=array;
-
+ for (uint32_t i = 0; i < len; i++)
+ w[i] = get_unicode_string();
+ w = PoolVector<String>::Write();
+ r_v = array;
} break;
case VARIANT_VECTOR2_ARRAY: {
@@ -560,16 +543,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<Vector2> array;
array.resize(len);
PoolVector<Vector2>::Write w = array.write();
- if (sizeof(Vector2)==8) {
- f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*2);
+ if (sizeof(Vector2) == 8) {
+ f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 2);
#ifdef BIG_ENDIAN_ENABLED
- {
- uint32_t *ptr=(uint32_t*)w.ptr();
- for(int i=0;i<len*2;i++) {
+ {
+ uint32_t *ptr = (uint32_t *)w.ptr();
+ for (int i = 0; i < len * 2; i++) {
- ptr[i]=BSWAP32(ptr[i]);
+ ptr[i] = BSWAP32(ptr[i]);
+ }
}
- }
#endif
@@ -577,8 +560,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
ERR_EXPLAIN("Vector2 size is NOT 8!");
ERR_FAIL_V(ERR_UNAVAILABLE);
}
- w=PoolVector<Vector2>::Write();
- r_v=array;
+ w = PoolVector<Vector2>::Write();
+ r_v = array;
} break;
case VARIANT_VECTOR3_ARRAY: {
@@ -588,14 +571,14 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<Vector3> array;
array.resize(len);
PoolVector<Vector3>::Write w = array.write();
- if (sizeof(Vector3)==12) {
- f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*3);
+ if (sizeof(Vector3) == 12) {
+ f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 3);
#ifdef BIG_ENDIAN_ENABLED
{
- uint32_t *ptr=(uint32_t*)w.ptr();
- for(int i=0;i<len*3;i++) {
+ uint32_t *ptr = (uint32_t *)w.ptr();
+ for (int i = 0; i < len * 3; i++) {
- ptr[i]=BSWAP32(ptr[i]);
+ ptr[i] = BSWAP32(ptr[i]);
}
}
@@ -605,8 +588,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
ERR_EXPLAIN("Vector3 size is NOT 12!");
ERR_FAIL_V(ERR_UNAVAILABLE);
}
- w=PoolVector<Vector3>::Write();
- r_v=array;
+ w = PoolVector<Vector3>::Write();
+ r_v = array;
} break;
case VARIANT_COLOR_ARRAY: {
@@ -616,16 +599,16 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
PoolVector<Color> array;
array.resize(len);
PoolVector<Color>::Write w = array.write();
- if (sizeof(Color)==16) {
- f->get_buffer((uint8_t*)w.ptr(),len*sizeof(real_t)*4);
+ if (sizeof(Color) == 16) {
+ f->get_buffer((uint8_t *)w.ptr(), len * sizeof(real_t) * 4);
#ifdef BIG_ENDIAN_ENABLED
- {
- uint32_t *ptr=(uint32_t*)w.ptr();
- for(int i=0;i<len*4;i++) {
+ {
+ uint32_t *ptr = (uint32_t *)w.ptr();
+ for (int i = 0; i < len * 4; i++) {
- ptr[i]=BSWAP32(ptr[i]);
+ ptr[i] = BSWAP32(ptr[i]);
+ }
}
- }
#endif
@@ -633,8 +616,8 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
ERR_EXPLAIN("Color size is NOT 16!");
ERR_FAIL_V(ERR_UNAVAILABLE);
}
- w=PoolVector<Color>::Write();
- r_v=array;
+ w = PoolVector<Color>::Write();
+ r_v = array;
} break;
default: {
@@ -642,49 +625,43 @@ Error ResourceInteractiveLoaderBinary::parse_variant(Variant& r_v) {
} break;
}
-
-
return OK; //never reach anyway
-
}
+void ResourceInteractiveLoaderBinary::set_local_path(const String &p_local_path) {
-void ResourceInteractiveLoaderBinary::set_local_path(const String& p_local_path) {
-
- res_path=p_local_path;
+ res_path = p_local_path;
}
-Ref<Resource> ResourceInteractiveLoaderBinary::get_resource(){
-
+Ref<Resource> ResourceInteractiveLoaderBinary::get_resource() {
return resource;
}
-Error ResourceInteractiveLoaderBinary::poll(){
+Error ResourceInteractiveLoaderBinary::poll() {
- if (error!=OK)
+ if (error != OK)
return error;
-
int s = stage;
- if (s<external_resources.size()) {
+ if (s < external_resources.size()) {
String path = external_resources[s].path;
- print_line("load external res: "+path);
+ print_line("load external res: " + path);
if (remaps.has(path)) {
- path=remaps[path];
+ path = remaps[path];
}
- RES res = ResourceLoader::load(path,external_resources[s].type);
+ RES res = ResourceLoader::load(path, external_resources[s].type);
if (res.is_null()) {
if (!ResourceLoader::get_abort_on_missing_resources()) {
- ResourceLoader::notify_dependency_error(local_path,path,external_resources[s].type);
+ ResourceLoader::notify_dependency_error(local_path, path, external_resources[s].type);
} else {
- error=ERR_FILE_MISSING_DEPENDENCIES;
- ERR_EXPLAIN("Can't load dependency: "+path);
+ error = ERR_FILE_MISSING_DEPENDENCIES;
+ ERR_EXPLAIN("Can't load dependency: " + path);
ERR_FAIL_V(error);
}
@@ -696,44 +673,39 @@ Error ResourceInteractiveLoaderBinary::poll(){
return error;
}
- s-=external_resources.size();
-
+ s -= external_resources.size();
- if (s>=internal_resources.size()) {
+ if (s >= internal_resources.size()) {
- error=ERR_BUG;
- ERR_FAIL_COND_V(s>=internal_resources.size(),error);
+ error = ERR_BUG;
+ ERR_FAIL_COND_V(s >= internal_resources.size(), error);
}
- bool main = s==(internal_resources.size()-1);
+ bool main = s == (internal_resources.size() - 1);
//maybe it is loaded already
String path;
- int subindex=0;
-
-
+ int subindex = 0;
if (!main) {
- path=internal_resources[s].path;
+ path = internal_resources[s].path;
if (path.begins_with("local://")) {
- path=path.replace_first("local://","");
+ path = path.replace_first("local://", "");
subindex = path.to_int();
- path=res_path+"::"+path;
+ path = res_path + "::" + path;
}
-
-
if (ResourceCache::has(path)) {
//already loaded, don't do anything
stage++;
- error=OK;
+ error = OK;
return error;
}
} else {
if (!ResourceCache::has(res_path))
- path=res_path;
+ path = res_path;
}
uint64_t offset = internal_resources[s].offset;
@@ -742,24 +714,24 @@ Error ResourceInteractiveLoaderBinary::poll(){
String t = get_unicode_string();
-// print_line("loading resource of type "+t+" path is "+path);
+ // print_line("loading resource of type "+t+" path is "+path);
Object *obj = ClassDB::instance(t);
if (!obj) {
- error=ERR_FILE_CORRUPT;
- ERR_EXPLAIN(local_path+":Resource of unrecognized type in file: "+t);
+ error = ERR_FILE_CORRUPT;
+ ERR_EXPLAIN(local_path + ":Resource of unrecognized type in file: " + t);
}
- ERR_FAIL_COND_V(!obj,ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(!obj, ERR_FILE_CORRUPT);
Resource *r = obj->cast_to<Resource>();
if (!r) {
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
memdelete(obj); //bye
- ERR_EXPLAIN(local_path+":Resoucre type in resource field not a resource, type is: "+obj->get_class());
- ERR_FAIL_COND_V(!r,ERR_FILE_CORRUPT);
+ ERR_EXPLAIN(local_path + ":Resoucre type in resource field not a resource, type is: " + obj->get_class());
+ ERR_FAIL_COND_V(!r, ERR_FILE_CORRUPT);
}
- RES res = RES( r );
+ RES res = RES(r);
r->set_path(path);
r->set_subindex(subindex);
@@ -768,11 +740,11 @@ Error ResourceInteractiveLoaderBinary::poll(){
//set properties
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
StringName name = _get_string();
- if (name==StringName()) {
- error=ERR_FILE_CORRUPT;
+ if (name == StringName()) {
+ error = ERR_FILE_CORRUPT;
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
@@ -782,7 +754,7 @@ Error ResourceInteractiveLoaderBinary::poll(){
if (error)
return error;
- res->set(name,value);
+ res->set(name, value);
}
#ifdef TOOLS_ENABLED
res->set_edited(false);
@@ -794,41 +766,37 @@ Error ResourceInteractiveLoaderBinary::poll(){
if (main) {
f->close();
- resource=res;
- error=ERR_FILE_EOF;
+ resource = res;
+ error = ERR_FILE_EOF;
} else {
- error=OK;
+ error = OK;
}
return OK;
-
}
-int ResourceInteractiveLoaderBinary::get_stage() const{
+int ResourceInteractiveLoaderBinary::get_stage() const {
return stage;
}
int ResourceInteractiveLoaderBinary::get_stage_count() const {
- return external_resources.size()+internal_resources.size();
+ return external_resources.size() + internal_resources.size();
}
-
-static void save_ustring(FileAccess* f,const String& p_string) {
-
+static void save_ustring(FileAccess *f, const String &p_string) {
CharString utf8 = p_string.utf8();
- f->store_32(utf8.length()+1);
- f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1);
+ f->store_32(utf8.length() + 1);
+ f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1);
}
-
static String get_ustring(FileAccess *f) {
int len = f->get_32();
Vector<char> str_buf;
str_buf.resize(len);
- f->get_buffer((uint8_t*)&str_buf[0],len);
+ f->get_buffer((uint8_t *)&str_buf[0], len);
String s;
s.parse_utf8(&str_buf[0]);
return s;
@@ -837,60 +805,53 @@ static String get_ustring(FileAccess *f) {
String ResourceInteractiveLoaderBinary::get_unicode_string() {
int len = f->get_32();
- if (len>str_buf.size()) {
+ if (len > str_buf.size()) {
str_buf.resize(len);
}
- if (len==0)
+ if (len == 0)
return String();
- f->get_buffer((uint8_t*)&str_buf[0],len);
+ f->get_buffer((uint8_t *)&str_buf[0], len);
String s;
s.parse_utf8(&str_buf[0]);
return s;
}
-
-
-void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f,List<String> *p_dependencies,bool p_add_types) {
+void ResourceInteractiveLoaderBinary::get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types) {
open(p_f);
if (error)
return;
- for(int i=0;i<external_resources.size();i++) {
+ for (int i = 0; i < external_resources.size(); i++) {
- String dep=external_resources[i].path;
+ String dep = external_resources[i].path;
- if (p_add_types && external_resources[i].type!=String()) {
- dep+="::"+external_resources[i].type;
+ if (p_add_types && external_resources[i].type != String()) {
+ dep += "::" + external_resources[i].type;
}
p_dependencies->push_back(dep);
}
-
}
-
-
-
void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
+ error = OK;
- error=OK;
-
- f=p_f;
+ f = p_f;
uint8_t header[4];
- f->get_buffer(header,4);
- if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') {
+ f->get_buffer(header, 4);
+ if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') {
//compressed
- FileAccessCompressed *fac = memnew( FileAccessCompressed );
+ FileAccessCompressed *fac = memnew(FileAccessCompressed);
fac->open_after_magic(f);
- f=fac;
+ f = fac;
- } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') {
+ } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') {
//not normal
- error=ERR_FILE_UNRECOGNIZED;
- ERR_EXPLAIN("Unrecognized binary resource file: "+local_path);
+ error = ERR_FILE_UNRECOGNIZED;
+ ERR_EXPLAIN("Unrecognized binary resource file: " + local_path);
ERR_FAIL();
}
@@ -903,53 +864,51 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
bool use_real64 = f->get_32();
- f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian
+ f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian
- uint32_t ver_major=f->get_32();
- uint32_t ver_minor=f->get_32();
- uint32_t ver_format=f->get_32();
+ uint32_t ver_major = f->get_32();
+ uint32_t ver_minor = f->get_32();
+ uint32_t ver_format = f->get_32();
- print_bl("big endian: "+itos(big_endian));
- print_bl("endian swap: "+itos(endian_swap));
- print_bl("real64: "+itos(use_real64));
- print_bl("major: "+itos(ver_major));
- print_bl("minor: "+itos(ver_minor));
- print_bl("format: "+itos(ver_format));
+ print_bl("big endian: " + itos(big_endian));
+ print_bl("endian swap: " + itos(endian_swap));
+ print_bl("real64: " + itos(use_real64));
+ print_bl("major: " + itos(ver_major));
+ print_bl("minor: " + itos(ver_minor));
+ print_bl("format: " + itos(ver_format));
- if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) {
+ if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) {
f->close();
- ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path);
+ ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path);
ERR_FAIL();
-
}
- type=get_unicode_string();
+ type = get_unicode_string();
- print_bl("type: "+type);
+ print_bl("type: " + type);
importmd_ofs = f->get_64();
- for(int i=0;i<14;i++)
+ for (int i = 0; i < 14; i++)
f->get_32(); //skip a few reserved fields
- uint32_t string_table_size=f->get_32();
+ uint32_t string_table_size = f->get_32();
string_map.resize(string_table_size);
- for(uint32_t i=0;i<string_table_size;i++) {
+ for (uint32_t i = 0; i < string_table_size; i++) {
StringName s = get_unicode_string();
- string_map[i]=s;
+ string_map[i] = s;
}
- print_bl("strings: "+itos(string_table_size));
+ print_bl("strings: " + itos(string_table_size));
- uint32_t ext_resources_size=f->get_32();
- for(uint32_t i=0;i<ext_resources_size;i++) {
+ uint32_t ext_resources_size = f->get_32();
+ for (uint32_t i = 0; i < ext_resources_size; i++) {
ExtResoucre er;
- er.type=get_unicode_string();
- er.path=get_unicode_string();
+ er.type = get_unicode_string();
+ er.path = get_unicode_string();
external_resources.push_back(er);
-
}
//see if the exporter has different set of external resources for more efficient loading
@@ -966,46 +925,43 @@ void ResourceInteractiveLoaderBinary::open(FileAccess *p_f) {
print_line(res_path+" - EXTERNAL RESOURCES: "+itos(external_resources.size()));
}*/
- print_bl("ext resources: "+itos(ext_resources_size));
- uint32_t int_resources_size=f->get_32();
+ print_bl("ext resources: " + itos(ext_resources_size));
+ uint32_t int_resources_size = f->get_32();
- for(uint32_t i=0;i<int_resources_size;i++) {
+ for (uint32_t i = 0; i < int_resources_size; i++) {
IntResoucre ir;
- ir.path=get_unicode_string();
- ir.offset=f->get_64();
+ ir.path = get_unicode_string();
+ ir.offset = f->get_64();
internal_resources.push_back(ir);
}
- print_bl("int resources: "+itos(int_resources_size));
-
+ print_bl("int resources: " + itos(int_resources_size));
if (f->eof_reached()) {
- error=ERR_FILE_CORRUPT;
- ERR_EXPLAIN("Premature End Of File: "+local_path);
+ error = ERR_FILE_CORRUPT;
+ ERR_EXPLAIN("Premature End Of File: " + local_path);
ERR_FAIL();
}
-
}
String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) {
- error=OK;
+ error = OK;
-
- f=p_f;
+ f = p_f;
uint8_t header[4];
- f->get_buffer(header,4);
- if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') {
+ f->get_buffer(header, 4);
+ if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') {
//compressed
- FileAccessCompressed *fac = memnew( FileAccessCompressed );
+ FileAccessCompressed *fac = memnew(FileAccessCompressed);
fac->open_after_magic(f);
- f=fac;
+ f = fac;
- } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') {
+ } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') {
//not normal
- error=ERR_FILE_UNRECOGNIZED;
+ error = ERR_FILE_UNRECOGNIZED;
return "";
}
@@ -1018,30 +974,30 @@ String ResourceInteractiveLoaderBinary::recognize(FileAccess *p_f) {
bool use_real64 = f->get_32();
- f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian
+ f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian
- uint32_t ver_major=f->get_32();
- uint32_t ver_minor=f->get_32();
- uint32_t ver_format=f->get_32();
+ uint32_t ver_major = f->get_32();
+ uint32_t ver_minor = f->get_32();
+ uint32_t ver_format = f->get_32();
- if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) {
+ if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) {
f->close();
return "";
}
- String type=get_unicode_string();
+ String type = get_unicode_string();
return type;
}
ResourceInteractiveLoaderBinary::ResourceInteractiveLoaderBinary() {
- f=NULL;
- stage=0;
- endian_swap=false;
- use_real64=false;
- error=OK;
+ f = NULL;
+ stage = 0;
+ endian_swap = false;
+ use_real64 = false;
+ error = OK;
}
ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() {
@@ -1050,126 +1006,117 @@ ResourceInteractiveLoaderBinary::~ResourceInteractiveLoaderBinary() {
memdelete(f);
}
-
Ref<ResourceInteractiveLoader> ResourceFormatLoaderBinary::load_interactive(const String &p_path, Error *r_error) {
if (r_error)
- *r_error=ERR_FILE_CANT_OPEN;
+ *r_error = ERR_FILE_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
- if (err!=OK) {
+ if (err != OK) {
- ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>());
+ ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>());
}
- Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( Globals::get_singleton()->localize_path(p_path) );
ria->open(f);
-
return ria;
}
-void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const {
+void ResourceFormatLoaderBinary::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
- if (p_type=="") {
+ if (p_type == "") {
get_recognized_extensions(p_extensions);
return;
}
List<String> extensions;
- ClassDB::get_extensions_for_type(p_type,&extensions);
+ ClassDB::get_extensions_for_type(p_type, &extensions);
extensions.sort();
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
String ext = E->get().to_lower();
p_extensions->push_back(ext);
}
-
}
-void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceFormatLoaderBinary::get_recognized_extensions(List<String> *p_extensions) const {
List<String> extensions;
ClassDB::get_resource_base_extensions(&extensions);
extensions.sort();
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
String ext = E->get().to_lower();
p_extensions->push_back(ext);
}
-
}
-bool ResourceFormatLoaderBinary::handles_type(const String& p_type) const{
-
+bool ResourceFormatLoaderBinary::handles_type(const String &p_type) const {
return true; //handles all
}
+void ResourceFormatLoaderBinary::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
-void ResourceFormatLoaderBinary::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) {
-
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
ERR_FAIL_COND(!f);
- Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( Globals::get_singleton()->localize_path(p_path) );
- ria->get_dependencies(f,p_dependencies,p_add_types);
+ ria->get_dependencies(f, p_dependencies, p_add_types);
}
-Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const Map<String,String>& p_map) {
-
+Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
//Error error=OK;
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
- FileAccess *f=FileAccess::open(p_path,FileAccess::READ);
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
-
- FileAccess* fw=NULL;//=FileAccess::open(p_path+".depren");
+ FileAccess *fw = NULL; //=FileAccess::open(p_path+".depren");
- String local_path=p_path.get_base_dir();
+ String local_path = p_path.get_base_dir();
uint8_t header[4];
- f->get_buffer(header,4);
- if (header[0]=='R' && header[1]=='S' && header[2]=='C' && header[3]=='C') {
+ f->get_buffer(header, 4);
+ if (header[0] == 'R' && header[1] == 'S' && header[2] == 'C' && header[3] == 'C') {
//compressed
- FileAccessCompressed *fac = memnew( FileAccessCompressed );
+ FileAccessCompressed *fac = memnew(FileAccessCompressed);
fac->open_after_magic(f);
- f=fac;
+ f = fac;
- FileAccessCompressed *facw = memnew( FileAccessCompressed );
+ FileAccessCompressed *facw = memnew(FileAccessCompressed);
facw->configure("RSCC");
- Error err = facw->_open(p_path+".depren",FileAccess::WRITE);
+ Error err = facw->_open(p_path + ".depren", FileAccess::WRITE);
if (err) {
memdelete(fac);
memdelete(facw);
- ERR_FAIL_COND_V(err,ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(err, ERR_FILE_CORRUPT);
}
- fw=facw;
+ fw = facw;
-
- } else if (header[0]!='R' || header[1]!='S' || header[2]!='R' || header[3]!='C') {
+ } else if (header[0] != 'R' || header[1] != 'S' || header[2] != 'R' || header[3] != 'C') {
//not normal
//error=ERR_FILE_UNRECOGNIZED;
memdelete(f);
- ERR_EXPLAIN("Unrecognized binary resource file: "+local_path);
+ ERR_EXPLAIN("Unrecognized binary resource file: " + local_path);
ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
} else {
- fw = FileAccess::open(p_path+".depren",FileAccess::WRITE);
+ fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
if (!fw) {
memdelete(f);
}
- ERR_FAIL_COND_V(!fw,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!fw, ERR_CANT_CREATE);
}
bool big_endian = f->get_32();
@@ -1181,144 +1128,139 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const
bool use_real64 = f->get_32();
- f->set_endian_swap(big_endian!=0); //read big endian if saved as big endian
+ f->set_endian_swap(big_endian != 0); //read big endian if saved as big endian
fw->store_32(endian_swap);
- fw->set_endian_swap(big_endian!=0);
+ fw->set_endian_swap(big_endian != 0);
fw->store_32(use_real64); //use real64
- uint32_t ver_major=f->get_32();
- uint32_t ver_minor=f->get_32();
- uint32_t ver_format=f->get_32();
+ uint32_t ver_major = f->get_32();
+ uint32_t ver_minor = f->get_32();
+ uint32_t ver_format = f->get_32();
- if (ver_format<FORMAT_VERSION_CAN_RENAME_DEPS) {
+ if (ver_format < FORMAT_VERSION_CAN_RENAME_DEPS) {
memdelete(f);
memdelete(fw);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- da->remove(p_path+".depren");
+ da->remove(p_path + ".depren");
memdelete(da);
//fuck it, use the old approach;
- WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: "+p_path).utf8().get_data());
+ WARN_PRINT(("This file is old, so it can't refactor dependencies, opening and resaving: " + p_path).utf8().get_data());
Error err;
- f = FileAccess::open(p_path,FileAccess::READ,&err);
- if (err!=OK) {
- ERR_FAIL_COND_V(err!=OK,ERR_FILE_CANT_OPEN);
+ f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (err != OK) {
+ ERR_FAIL_COND_V(err != OK, ERR_FILE_CANT_OPEN);
}
- Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
- ria->remaps=p_map;
+ Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
+ ria->remaps = p_map;
//ria->set_local_path( Globals::get_singleton()->localize_path(p_path) );
ria->open(f);
err = ria->poll();
- while(err==OK) {
- err=ria->poll();
+ while (err == OK) {
+ err = ria->poll();
}
- ERR_FAIL_COND_V(err!=ERR_FILE_EOF,ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(err != ERR_FILE_EOF, ERR_FILE_CORRUPT);
RES res = ria->get_resource();
- ERR_FAIL_COND_V(!res.is_valid(),ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(!res.is_valid(), ERR_FILE_CORRUPT);
- return ResourceFormatSaverBinary::singleton->save(p_path,res);
+ return ResourceFormatSaverBinary::singleton->save(p_path, res);
}
- if (ver_format>FORMAT_VERSION || ver_major>VERSION_MAJOR) {
+ if (ver_format > FORMAT_VERSION || ver_major > VERSION_MAJOR) {
memdelete(f);
memdelete(fw);
- ERR_EXPLAIN("File Format '"+itos(FORMAT_VERSION)+"."+itos(ver_major)+"."+itos(ver_minor)+"' is too new! Please upgrade to a a new engine version: "+local_path);
+ ERR_EXPLAIN("File Format '" + itos(FORMAT_VERSION) + "." + itos(ver_major) + "." + itos(ver_minor) + "' is too new! Please upgrade to a a new engine version: " + local_path);
ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
-
}
- fw->store_32( VERSION_MAJOR ); //current version
- fw->store_32( VERSION_MINOR );
- fw->store_32( FORMAT_VERSION );
-
- save_ustring(fw,get_ustring(f)); //type
+ fw->store_32(VERSION_MAJOR); //current version
+ fw->store_32(VERSION_MINOR);
+ fw->store_32(FORMAT_VERSION);
+ save_ustring(fw, get_ustring(f)); //type
size_t md_ofs = f->get_pos();
size_t importmd_ofs = f->get_64();
fw->store_64(0); //metadata offset
- for(int i=0;i<14;i++) {
+ for (int i = 0; i < 14; i++) {
fw->store_32(0);
f->get_32();
}
//string table
- uint32_t string_table_size=f->get_32();
+ uint32_t string_table_size = f->get_32();
fw->store_32(string_table_size);
- for(uint32_t i=0;i<string_table_size;i++) {
+ for (uint32_t i = 0; i < string_table_size; i++) {
String s = get_ustring(f);
- save_ustring(fw,s);
+ save_ustring(fw, s);
}
//external resources
- uint32_t ext_resources_size=f->get_32();
+ uint32_t ext_resources_size = f->get_32();
fw->store_32(ext_resources_size);
- for(uint32_t i=0;i<ext_resources_size;i++) {
+ for (uint32_t i = 0; i < ext_resources_size; i++) {
String type = get_ustring(f);
String path = get_ustring(f);
- bool relative=false;
+ bool relative = false;
if (!path.begins_with("res://")) {
- path=local_path.plus_file(path).simplify_path();
- relative=true;
+ path = local_path.plus_file(path).simplify_path();
+ relative = true;
}
-
if (p_map.has(path)) {
- String np=p_map[path];
- path=np;
+ String np = p_map[path];
+ path = np;
}
if (relative) {
//restore relative
- path=local_path.path_to_file(path);
+ path = local_path.path_to_file(path);
}
- save_ustring(fw,type);
- save_ustring(fw,path);
+ save_ustring(fw, type);
+ save_ustring(fw, path);
}
int64_t size_diff = (int64_t)fw->get_pos() - (int64_t)f->get_pos();
//internal resources
- uint32_t int_resources_size=f->get_32();
+ uint32_t int_resources_size = f->get_32();
fw->store_32(int_resources_size);
- for(uint32_t i=0;i<int_resources_size;i++) {
+ for (uint32_t i = 0; i < int_resources_size; i++) {
-
- String path=get_ustring(f);
- uint64_t offset=f->get_64();
- save_ustring(fw,path);
- fw->store_64(offset+size_diff);
+ String path = get_ustring(f);
+ uint64_t offset = f->get_64();
+ save_ustring(fw, path);
+ fw->store_64(offset + size_diff);
}
//rest of file
uint8_t b = f->get_8();
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
fw->store_8(b);
b = f->get_8();
}
- bool all_ok = fw->get_error()==OK;
+ bool all_ok = fw->get_error() == OK;
fw->seek(md_ofs);
- fw->store_64(importmd_ofs+size_diff);
-
+ fw->store_64(importmd_ofs + size_diff);
memdelete(f);
memdelete(fw);
@@ -1329,50 +1271,42 @@ Error ResourceFormatLoaderBinary::rename_dependencies(const String &p_path,const
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
da->remove(p_path);
- da->rename(p_path+".depren",p_path);
+ da->rename(p_path + ".depren", p_path);
memdelete(da);
return OK;
}
-
String ResourceFormatLoaderBinary::get_resource_type(const String &p_path) const {
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
return ""; //could not rwead
}
- Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderBinary> ria = memnew(ResourceInteractiveLoaderBinary);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( Globals::get_singleton()->localize_path(p_path) );
String r = ria->recognize(f);
return r;
-
-
}
-
-
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
-
void ResourceFormatSaverBinaryInstance::_pad_buffer(int p_bytes) {
- int extra = 4-(p_bytes%4);
- if (extra<4) {
- for(int i=0;i<extra;i++)
+ int extra = 4 - (p_bytes % 4);
+ if (extra < 4) {
+ for (int i = 0; i < extra; i++)
f->store_8(0); //pad to 32
}
-
}
+void ResourceFormatSaverBinaryInstance::write_variant(const Variant &p_property, const PropertyInfo &p_hint) {
-void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,const PropertyInfo& p_hint) {
-
- switch(p_property.get_type()) {
+ switch (p_property.get_type()) {
case Variant::NIL: {
@@ -1382,51 +1316,48 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::BOOL: {
f->store_32(VARIANT_BOOL);
- bool val=p_property;
+ bool val = p_property;
f->store_32(val);
} break;
case Variant::INT: {
int64_t val = p_property;
- if (val>0x7FFFFFFF || val < -0x80000000) {
+ if (val > 0x7FFFFFFF || val < -0x80000000) {
f->store_32(VARIANT_INT64);
f->store_64(val);
} else {
f->store_32(VARIANT_INT);
- int val=p_property;
+ int val = p_property;
f->store_32(int32_t(val));
-
}
} break;
case Variant::REAL: {
-
double d = p_property;
float fl = d;
- if (double(fl)!=d) {
+ if (double(fl) != d) {
f->store_32(VARIANT_DOUBLE);
f->store_double(d);
} else {
f->store_32(VARIANT_REAL);
f->store_real(fl);
-
}
} break;
case Variant::STRING: {
f->store_32(VARIANT_STRING);
- String val=p_property;
+ String val = p_property;
save_unicode_string(val);
} break;
case Variant::VECTOR2: {
f->store_32(VARIANT_VECTOR2);
- Vector2 val=p_property;
+ Vector2 val = p_property;
f->store_real(val.x);
f->store_real(val.y);
@@ -1434,7 +1365,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::RECT2: {
f->store_32(VARIANT_RECT2);
- Rect2 val=p_property;
+ Rect2 val = p_property;
f->store_real(val.pos.x);
f->store_real(val.pos.y);
f->store_real(val.size.x);
@@ -1444,7 +1375,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::VECTOR3: {
f->store_32(VARIANT_VECTOR3);
- Vector3 val=p_property;
+ Vector3 val = p_property;
f->store_real(val.x);
f->store_real(val.y);
f->store_real(val.z);
@@ -1453,7 +1384,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::PLANE: {
f->store_32(VARIANT_PLANE);
- Plane val=p_property;
+ Plane val = p_property;
f->store_real(val.normal.x);
f->store_real(val.normal.y);
f->store_real(val.normal.z);
@@ -1463,7 +1394,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::QUAT: {
f->store_32(VARIANT_QUAT);
- Quat val=p_property;
+ Quat val = p_property;
f->store_real(val.x);
f->store_real(val.y);
f->store_real(val.z);
@@ -1473,7 +1404,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::RECT3: {
f->store_32(VARIANT_AABB);
- Rect3 val=p_property;
+ Rect3 val = p_property;
f->store_real(val.pos.x);
f->store_real(val.pos.y);
f->store_real(val.pos.z);
@@ -1485,7 +1416,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::TRANSFORM2D: {
f->store_32(VARIANT_MATRIX32);
- Transform2D val=p_property;
+ Transform2D val = p_property;
f->store_real(val.elements[0].x);
f->store_real(val.elements[0].y);
f->store_real(val.elements[1].x);
@@ -1497,7 +1428,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::BASIS: {
f->store_32(VARIANT_MATRIX3);
- Basis val=p_property;
+ Basis val = p_property;
f->store_real(val.elements[0].x);
f->store_real(val.elements[0].y);
f->store_real(val.elements[0].z);
@@ -1512,7 +1443,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::TRANSFORM: {
f->store_32(VARIANT_TRANSFORM);
- Transform val=p_property;
+ Transform val = p_property;
f->store_real(val.basis.elements[0].x);
f->store_real(val.basis.elements[0].y);
f->store_real(val.basis.elements[0].z);
@@ -1530,7 +1461,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::COLOR: {
f->store_32(VARIANT_COLOR);
- Color val=p_property;
+ Color val = p_property;
f->store_real(val.r);
f->store_real(val.g);
f->store_real(val.b);
@@ -1540,34 +1471,32 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
case Variant::IMAGE: {
f->store_32(VARIANT_IMAGE);
- Image val =p_property;
+ Image val = p_property;
if (val.empty()) {
f->store_32(IMAGE_ENCODING_EMPTY);
break;
}
- int encoding=IMAGE_ENCODING_RAW;
- float quality=0.7;
+ int encoding = IMAGE_ENCODING_RAW;
+ float quality = 0.7;
if (!val.is_compressed()) {
//can only compress uncompressed stuff
- if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) {
- encoding=IMAGE_ENCODING_LOSSY;
- float qs=p_hint.hint_string.to_double();
- if (qs!=0.0)
- quality=qs;
-
- } else if (p_hint.hint==PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) {
- encoding=IMAGE_ENCODING_LOSSLESS;
+ if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSY && Image::lossy_packer) {
+ encoding = IMAGE_ENCODING_LOSSY;
+ float qs = p_hint.hint_string.to_double();
+ if (qs != 0.0)
+ quality = qs;
+ } else if (p_hint.hint == PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS && Image::lossless_packer) {
+ encoding = IMAGE_ENCODING_LOSSLESS;
}
}
f->store_32(encoding); //raw encoding
- if (encoding==IMAGE_ENCODING_RAW) {
-
+ if (encoding == IMAGE_ENCODING_RAW) {
f->store_32(val.get_width());
f->store_32(val.get_height());
@@ -1577,42 +1506,40 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
int dlen = val.get_data().size();
f->store_32(dlen);
PoolVector<uint8_t>::Read r = val.get_data().read();
- f->store_buffer(r.ptr(),dlen);
+ f->store_buffer(r.ptr(), dlen);
_pad_buffer(dlen);
} else {
PoolVector<uint8_t> data;
- if (encoding==IMAGE_ENCODING_LOSSY) {
- data=Image::lossy_packer(val,quality);
-
- } else if (encoding==IMAGE_ENCODING_LOSSLESS) {
- data=Image::lossless_packer(val);
+ if (encoding == IMAGE_ENCODING_LOSSY) {
+ data = Image::lossy_packer(val, quality);
+ } else if (encoding == IMAGE_ENCODING_LOSSLESS) {
+ data = Image::lossless_packer(val);
}
- int ds=data.size();
+ int ds = data.size();
f->store_32(ds);
- if (ds>0) {
+ if (ds > 0) {
PoolVector<uint8_t>::Read r = data.read();
- f->store_buffer(r.ptr(),ds);
+ f->store_buffer(r.ptr(), ds);
_pad_buffer(ds);
-
}
}
} break;
case Variant::NODE_PATH: {
f->store_32(VARIANT_NODE_PATH);
- NodePath np=p_property;
+ NodePath np = p_property;
f->store_16(np.get_name_count());
uint16_t snc = np.get_subname_count();
if (np.is_absolute())
- snc|=0x8000;
+ snc |= 0x8000;
f->store_16(snc);
- for(int i=0;i<np.get_name_count();i++)
+ for (int i = 0; i < np.get_name_count(); i++)
f->store_32(get_string_index(np.get_name(i)));
- for(int i=0;i<np.get_subname_count();i++)
+ for (int i = 0; i < np.get_subname_count(); i++)
f->store_32(get_string_index(np.get_subname(i)));
f->store_32(get_string_index(np.get_property()));
@@ -1633,7 +1560,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
return; // don't save it
}
- if (res->get_path().length() && res->get_path().find("::")==-1) {
+ if (res->get_path().length() && res->get_path().find("::") == -1) {
f->store_32(OBJECT_EXTERNAL_RESOURCE_INDEX);
f->store_32(external_resources[res]);
} else {
@@ -1649,12 +1576,11 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
//internal resource
}
-
} break;
case Variant::INPUT_EVENT: {
f->store_32(VARIANT_INPUT_EVENT);
- InputEvent event=p_property;
+ InputEvent event = p_property;
f->store_32(0); //event type none, nothing else suported for now.
} break;
@@ -1667,7 +1593,7 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
List<Variant> keys;
d.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
/*
if (!_check_type(dict[E->get()]))
@@ -1678,14 +1604,13 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
write_variant(d[E->get()]);
}
-
} break;
case Variant::ARRAY: {
f->store_32(VARIANT_ARRAY);
- Array a=p_property;
+ Array a = p_property;
f->store_32(uint32_t(a.size()));
- for(int i=0;i<a.size();i++) {
+ for (int i = 0; i < a.size(); i++) {
write_variant(a[i]);
}
@@ -1695,10 +1620,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_RAW_ARRAY);
PoolVector<uint8_t> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<uint8_t>::Read r = arr.read();
- f->store_buffer(r.ptr(),len);
+ f->store_buffer(r.ptr(), len);
_pad_buffer(len);
} break;
@@ -1706,10 +1631,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_INT_ARRAY);
PoolVector<int> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<int>::Read r = arr.read();
- for(int i=0;i<len;i++)
+ for (int i = 0; i < len; i++)
f->store_32(r[i]);
} break;
@@ -1717,10 +1642,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_REAL_ARRAY);
PoolVector<real_t> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<real_t>::Read r = arr.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
f->store_real(r[i]);
}
@@ -1729,10 +1654,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_STRING_ARRAY);
PoolVector<String> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<String>::Read r = arr.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
save_unicode_string(r[i]);
}
@@ -1741,10 +1666,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_VECTOR3_ARRAY);
PoolVector<Vector3> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<Vector3>::Read r = arr.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
f->store_real(r[i].x);
f->store_real(r[i].y);
f->store_real(r[i].z);
@@ -1755,10 +1680,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_VECTOR2_ARRAY);
PoolVector<Vector2> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<Vector2>::Read r = arr.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
f->store_real(r[i].x);
f->store_real(r[i].y);
}
@@ -1768,10 +1693,10 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
f->store_32(VARIANT_COLOR_ARRAY);
PoolVector<Color> arr = p_property;
- int len=arr.size();
+ int len = arr.size();
f->store_32(len);
PoolVector<Color>::Read r = arr.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
f->store_real(r[i].r);
f->store_real(r[i].g);
f->store_real(r[i].b);
@@ -1787,26 +1712,22 @@ void ResourceFormatSaverBinaryInstance::write_variant(const Variant& p_property,
}
}
+void ResourceFormatSaverBinaryInstance::_find_resources(const Variant &p_variant, bool p_main) {
-void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant,bool p_main) {
-
-
- switch(p_variant.get_type()) {
+ switch (p_variant.get_type()) {
case Variant::OBJECT: {
-
RES res = p_variant.operator RefPtr();
if (res.is_null() || external_resources.has(res))
return;
- if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) {
+ if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) {
int idx = external_resources.size();
- external_resources[res]=idx;
+ external_resources[res] = idx;
return;
}
-
if (resource_set.has(res))
return;
@@ -1814,9 +1735,9 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant
res->get_property_list(&property_list);
- for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
- if (E->get().usage&PROPERTY_USAGE_STORAGE) {
+ if (E->get().usage & PROPERTY_USAGE_STORAGE) {
_find_resources(res->get(E->get().name));
}
@@ -1829,11 +1750,11 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant
case Variant::ARRAY: {
- Array varray=p_variant;
- int len=varray.size();
- for(int i=0;i<len;i++) {
+ Array varray = p_variant;
+ int len = varray.size();
+ for (int i = 0; i < len; i++) {
- Variant v=varray.get(i);
+ Variant v = varray.get(i);
_find_resources(v);
}
@@ -1841,10 +1762,10 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant
case Variant::DICTIONARY: {
- Dictionary d=p_variant;
+ Dictionary d = p_variant;
List<Variant> keys;
d.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
_find_resources(E->get());
Variant v = d[E->get()];
@@ -1854,18 +1775,16 @@ void ResourceFormatSaverBinaryInstance::_find_resources(const Variant& p_variant
case Variant::NODE_PATH: {
//take the chance and save node path strings
NodePath np = p_variant;
- for(int i=0;i<np.get_name_count();i++)
+ for (int i = 0; i < np.get_name_count(); i++)
get_string_index(np.get_name(i));
- for(int i=0;i<np.get_subname_count();i++)
+ for (int i = 0; i < np.get_subname_count(); i++)
get_string_index(np.get_subname(i));
get_string_index(np.get_property());
-
} break;
default: {}
}
-
}
#if 0
Error ResourceFormatSaverBinary::_save_obj(const Object *p_object,SavedObject *so) {
@@ -1916,64 +1835,60 @@ Error ResourceFormatSaverBinary::save(const Object *p_object,const Variant &p_me
}
#endif
-void ResourceFormatSaverBinaryInstance::save_unicode_string(const String& p_string) {
-
+void ResourceFormatSaverBinaryInstance::save_unicode_string(const String &p_string) {
CharString utf8 = p_string.utf8();
- f->store_32(utf8.length()+1);
- f->store_buffer((const uint8_t*)utf8.get_data(),utf8.length()+1);
+ f->store_32(utf8.length() + 1);
+ f->store_buffer((const uint8_t *)utf8.get_data(), utf8.length() + 1);
}
-int ResourceFormatSaverBinaryInstance::get_string_index(const String& p_string) {
+int ResourceFormatSaverBinaryInstance::get_string_index(const String &p_string) {
- StringName s=p_string;
+ StringName s = p_string;
if (string_map.has(s))
return string_map[s];
- string_map[s]=strings.size();
+ string_map[s] = strings.size();
strings.push_back(s);
- return strings.size()-1;
+ return strings.size() - 1;
}
-
-Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
+Error ResourceFormatSaverBinaryInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
Error err;
- if (p_flags&ResourceSaver::FLAG_COMPRESS) {
- FileAccessCompressed *fac = memnew( FileAccessCompressed );
+ if (p_flags & ResourceSaver::FLAG_COMPRESS) {
+ FileAccessCompressed *fac = memnew(FileAccessCompressed);
fac->configure("RSCC");
- f=fac;
- err = fac->_open(p_path,FileAccess::WRITE);
+ f = fac;
+ err = fac->_open(p_path, FileAccess::WRITE);
if (err)
memdelete(f);
} else {
- f=FileAccess::open(p_path,FileAccess::WRITE,&err);
+ f = FileAccess::open(p_path, FileAccess::WRITE, &err);
}
-
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
FileAccessRef _fref(f);
-
- relative_paths=p_flags&ResourceSaver::FLAG_RELATIVE_PATHS;
- skip_editor=p_flags&ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
- bundle_resources=p_flags&ResourceSaver::FLAG_BUNDLE_RESOURCES;
- big_endian=p_flags&ResourceSaver::FLAG_SAVE_BIG_ENDIAN;
- takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
+ relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
+ skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
+ bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
+ big_endian = p_flags & ResourceSaver::FLAG_SAVE_BIG_ENDIAN;
+ takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
if (!p_path.begins_with("res://"))
- takeover_paths=false;
+ takeover_paths = false;
- local_path=p_path.get_base_dir();
+ local_path = p_path.get_base_dir();
//bin_meta_idx = get_string_index("__bin_meta__"); //is often used, so create
- _find_resources(p_resource,true);
+ _find_resources(p_resource, true);
- if (!(p_flags&ResourceSaver::FLAG_COMPRESS)) {
+ if (!(p_flags & ResourceSaver::FLAG_COMPRESS)) {
//save header compressed
- static const uint8_t header[4]={'R','S','R','C'};
- f->store_buffer(header,4);
+ static const uint8_t header[4] = { 'R', 'S', 'R', 'C' };
+ f->store_buffer(header, 4);
}
if (big_endian) {
@@ -1987,7 +1902,7 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
f->store_32(VERSION_MINOR);
f->store_32(FORMAT_VERSION);
- if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) {
+ if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
f->close();
return ERR_CANT_CREATE;
}
@@ -1996,50 +1911,41 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
save_unicode_string(p_resource->get_class());
uint64_t md_at = f->get_pos();
f->store_64(0); //offset to impoty metadata
- for(int i=0;i<14;i++)
+ for (int i = 0; i < 14; i++)
f->store_32(0); // reserved
-
List<ResourceData> resources;
-
{
-
- for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {
-
+ for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
ResourceData &rd = resources.push_back(ResourceData())->get();
- rd.type=E->get()->get_class();
+ rd.type = E->get()->get_class();
List<PropertyInfo> property_list;
- E->get()->get_property_list( &property_list );
+ E->get()->get_property_list(&property_list);
- for(List<PropertyInfo>::Element *F=property_list.front();F;F=F->next()) {
+ for (List<PropertyInfo>::Element *F = property_list.front(); F; F = F->next()) {
if (skip_editor && F->get().name.begins_with("__editor"))
continue;
- if (F->get().usage&PROPERTY_USAGE_STORAGE ) {
+ if (F->get().usage & PROPERTY_USAGE_STORAGE) {
Property p;
- p.name_idx=get_string_index(F->get().name);
- p.value=E->get()->get(F->get().name);
- if ((F->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero())||(F->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one()) )
+ p.name_idx = get_string_index(F->get().name);
+ p.value = E->get()->get(F->get().name);
+ if ((F->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && p.value.is_zero()) || (F->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && p.value.is_one()))
continue;
- p.pi=F->get();
+ p.pi = F->get();
rd.properties.push_back(p);
-
}
}
-
-
-
}
}
-
f->store_32(strings.size()); //string table size
- for(int i=0;i<strings.size();i++) {
+ for (int i = 0; i < strings.size(); i++) {
//print_bl("saving string: "+strings[i]);
save_unicode_string(strings[i]);
}
@@ -2049,15 +1955,15 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
Vector<RES> save_order;
save_order.resize(external_resources.size());
- for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) {
- save_order[E->get()]=E->key();
+ for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
+ save_order[E->get()] = E->key();
}
- for(int i=0;i<save_order.size();i++) {
+ for (int i = 0; i < save_order.size(); i++) {
save_unicode_string(save_order[i]->get_save_class());
String path = save_order[i]->get_path();
- path=relative_paths?local_path.path_to_file(path):path;
+ path = relative_paths ? local_path.path_to_file(path) : path;
save_unicode_string(path);
}
// save internal resource table
@@ -2065,12 +1971,12 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
Vector<uint64_t> ofs_pos;
Set<int> used_indices;
- for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {
+ for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
RES r = E->get();
- if (r->get_path()=="" || r->get_path().find("::")!=-1) {
+ if (r->get_path() == "" || r->get_path().find("::") != -1) {
- if (r->get_subindex()!=0) {
+ if (r->get_subindex() != 0) {
if (used_indices.has(r->get_subindex())) {
r->set_subindex(0); //repeated
} else {
@@ -2078,29 +1984,25 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
}
}
}
-
}
-
- for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {
-
+ for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
RES r = E->get();
- if (r->get_path()=="" || r->get_path().find("::")!=-1) {
- if (r->get_subindex()==0) {
- int new_subindex=1;
+ if (r->get_path() == "" || r->get_path().find("::") != -1) {
+ if (r->get_subindex() == 0) {
+ int new_subindex = 1;
if (used_indices.size()) {
- new_subindex=used_indices.back()->get()+1;
+ new_subindex = used_indices.back()->get() + 1;
}
r->set_subindex(new_subindex);
used_indices.insert(new_subindex);
-
}
- save_unicode_string("local://"+itos(r->get_subindex()));
+ save_unicode_string("local://" + itos(r->get_subindex()));
if (takeover_paths) {
- r->set_path(p_path+"::"+itos(r->get_subindex()),true);
+ r->set_path(p_path + "::" + itos(r->get_subindex()), true);
}
#ifdef TOOLS_ENABLED
r->set_edited(false);
@@ -2116,74 +2018,64 @@ Error ResourceFormatSaverBinaryInstance::save(const String &p_path,const RES& p_
//int saved_idx=0;
//now actually save the resources
- for(List<ResourceData>::Element *E=resources.front();E;E=E->next()) {
+ for (List<ResourceData>::Element *E = resources.front(); E; E = E->next()) {
- ResourceData & rd = E->get();
+ ResourceData &rd = E->get();
ofs_table.push_back(f->get_pos());
save_unicode_string(rd.type);
f->store_32(rd.properties.size());
- for (List<Property>::Element *F=rd.properties.front();F;F=F->next()) {
+ for (List<Property>::Element *F = rd.properties.front(); F; F = F->next()) {
- Property &p=F->get();
+ Property &p = F->get();
f->store_32(p.name_idx);
- write_variant(p.value,F->get().pi);
+ write_variant(p.value, F->get().pi);
}
-
}
- for(int i=0;i<ofs_table.size();i++) {
+ for (int i = 0; i < ofs_table.size(); i++) {
f->seek(ofs_pos[i]);
f->store_64(ofs_table[i]);
}
f->seek_end();
+ f->store_buffer((const uint8_t *)"RSRC", 4); //magic at end
- f->store_buffer((const uint8_t*)"RSRC",4); //magic at end
-
- if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) {
+ if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
f->close();
return ERR_CANT_CREATE;
}
f->close();
-
return OK;
}
-
-
-Error ResourceFormatSaverBinary::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
-
+Error ResourceFormatSaverBinary::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
String local_path = GlobalConfig::get_singleton()->localize_path(p_path);
ResourceFormatSaverBinaryInstance saver;
- return saver.save(local_path,p_resource,p_flags);
-
+ return saver.save(local_path, p_resource, p_flags);
}
-
-bool ResourceFormatSaverBinary::recognize(const RES& p_resource) const {
+bool ResourceFormatSaverBinary::recognize(const RES &p_resource) const {
return true; //all recognized
-
}
-void ResourceFormatSaverBinary::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
+void ResourceFormatSaverBinary::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
String base = p_resource->get_base_extension().to_lower();
p_extensions->push_back(base);
- if (base!="res")
+ if (base != "res")
p_extensions->push_back("res");
-
}
-ResourceFormatSaverBinary* ResourceFormatSaverBinary::singleton=NULL;
+ResourceFormatSaverBinary *ResourceFormatSaverBinary::singleton = NULL;
ResourceFormatSaverBinary::ResourceFormatSaverBinary() {
- singleton=this;
+ singleton = this;
}
diff --git a/core/io/resource_format_binary.h b/core/io/resource_format_binary.h
index 1fab6144d5..f378d0eae9 100644
--- a/core/io/resource_format_binary.h
+++ b/core/io/resource_format_binary.h
@@ -33,7 +33,6 @@
#include "io/resource_saver.h"
#include "os/file_access.h"
-
class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader {
String local_path;
@@ -43,7 +42,6 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader {
FileAccess *f;
-
bool endian_swap;
bool use_real64;
uint64_t importmd_ofs;
@@ -73,58 +71,46 @@ class ResourceInteractiveLoaderBinary : public ResourceInteractiveLoader {
String get_unicode_string();
void _advance_padding(uint32_t p_len);
- Map<String,String> remaps;
+ Map<String, String> remaps;
Error error;
int stage;
-friend class ResourceFormatLoaderBinary;
+ friend class ResourceFormatLoaderBinary;
-
- Error parse_variant(Variant& r_v);
+ Error parse_variant(Variant &r_v);
public:
-
- virtual void set_local_path(const String& p_local_path);
+ virtual void set_local_path(const String &p_local_path);
virtual Ref<Resource> get_resource();
virtual Error poll();
virtual int get_stage() const;
virtual int get_stage_count() const;
- void set_remaps(const Map<String,String>& p_remaps) { remaps=p_remaps; }
+ void set_remaps(const Map<String, String> &p_remaps) { remaps = p_remaps; }
void open(FileAccess *p_f);
String recognize(FileAccess *p_f);
void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types);
-
ResourceInteractiveLoaderBinary();
~ResourceInteractiveLoaderBinary();
-
};
class ResourceFormatLoaderBinary : public ResourceFormatLoader {
public:
-
- virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL);
- virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const;
+ virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL);
+ virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
- virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false);
- virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map);
-
-
-
+ virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
+ virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map);
};
-
-
-
-class ResourceFormatSaverBinaryInstance {
+class ResourceFormatSaverBinaryInstance {
String local_path;
-
bool relative_paths;
bool bundle_resources;
bool skip_editor;
@@ -134,19 +120,16 @@ class ResourceFormatSaverBinaryInstance {
FileAccess *f;
String magic;
Set<RES> resource_set;
- Map<StringName,int> string_map;
+ Map<StringName, int> string_map;
Vector<StringName> strings;
-
- Map<RES,int> external_resources;
+ Map<RES, int> external_resources;
List<RES> saved_resources;
-
struct Property {
int name_idx;
Variant value;
PropertyInfo pi;
-
};
struct ResourceData {
@@ -155,36 +138,25 @@ class ResourceFormatSaverBinaryInstance {
List<Property> properties;
};
-
-
-
void _pad_buffer(int p_bytes);
- void write_variant(const Variant& p_property,const PropertyInfo& p_hint=PropertyInfo());
- void _find_resources(const Variant& p_variant,bool p_main=false);
- void save_unicode_string(const String& p_string);
- int get_string_index(const String& p_string);
-public:
+ void write_variant(const Variant &p_property, const PropertyInfo &p_hint = PropertyInfo());
+ void _find_resources(const Variant &p_variant, bool p_main = false);
+ void save_unicode_string(const String &p_string);
+ int get_string_index(const String &p_string);
-
- Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
+public:
+ Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
};
-
-
-class ResourceFormatSaverBinary : public ResourceFormatSaver {
-
-
-
+class ResourceFormatSaverBinary : public ResourceFormatSaver {
public:
-
- static ResourceFormatSaverBinary* singleton;
- virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
- virtual bool recognize(const RES& p_resource) const;
- virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const;
+ static ResourceFormatSaverBinary *singleton;
+ virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
+ virtual bool recognize(const RES &p_resource) const;
+ virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
ResourceFormatSaverBinary();
};
-
#endif // RESOURCE_FORMAT_BINARY_H
diff --git a/core/io/resource_import.cpp b/core/io/resource_import.cpp
index 41245db173..27173a721d 100644
--- a/core/io/resource_import.cpp
+++ b/core/io/resource_import.cpp
@@ -28,106 +28,101 @@
/*************************************************************************/
#include "resource_import.h"
-#include "variant_parser.h"
#include "os/os.h"
+#include "variant_parser.h"
-Error ResourceFormatImporter::_get_path_and_type(const String& p_path, PathAndType &r_path_and_type) const {
+Error ResourceFormatImporter::_get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const {
Error err;
- FileAccess *f= FileAccess::open(p_path+".import",FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f)
return err;
VariantParser::StreamFile stream;
- stream.f=f;
+ stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
- int lines=0;
+ int lines = 0;
String error_text;
- while(true) {
+ while (true) {
- assign=Variant();
+ assign = Variant();
next_tag.fields.clear();
- next_tag.name=String();
+ next_tag.name = String();
- err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true);
- if (err==ERR_FILE_EOF) {
+ err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
+ if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
- }
- else if (err!=OK) {
- ERR_PRINTS("ResourceFormatImporter::load - "+p_path+".import:"+itos(lines)+" error: "+error_text);
+ } else if (err != OK) {
+ ERR_PRINTS("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return err;
}
- if (assign!=String()) {
- if (assign.begins_with("path.") && r_path_and_type.path==String()) {
- String feature = assign.get_slicec('.',1);
+ if (assign != String()) {
+ if (assign.begins_with("path.") && r_path_and_type.path == String()) {
+ String feature = assign.get_slicec('.', 1);
if (OS::get_singleton()->check_feature_support(feature)) {
- r_path_and_type.path=value;
+ r_path_and_type.path = value;
}
- } else if (assign=="path") {
- r_path_and_type.path=value;
- } else if (assign=="type") {
- r_path_and_type.type=value;
+ } else if (assign == "path") {
+ r_path_and_type.path = value;
+ } else if (assign == "type") {
+ r_path_and_type.type = value;
}
- } else if (next_tag.name!="remap") {
+ } else if (next_tag.name != "remap") {
break;
}
}
memdelete(f);
- if (r_path_and_type.path==String() || r_path_and_type.type==String()) {
+ if (r_path_and_type.path == String() || r_path_and_type.type == String()) {
return ERR_FILE_CORRUPT;
}
return OK;
-
}
-
-RES ResourceFormatImporter::load(const String &p_path,const String& p_original_path,Error *r_error) {
+RES ResourceFormatImporter::load(const String &p_path, const String &p_original_path, Error *r_error) {
PathAndType pat;
- Error err = _get_path_and_type(p_path,pat);
+ Error err = _get_path_and_type(p_path, pat);
- if (err!=OK) {
+ if (err != OK) {
if (r_error)
- *r_error=err;
+ *r_error = err;
return RES();
}
-
- RES res = ResourceLoader::load(pat.path,pat.type,false,r_error);
+ RES res = ResourceLoader::load(pat.path, pat.type, false, r_error);
#ifdef TOOLS_ENABLED
if (res.is_valid()) {
- res->set_import_last_modified_time( res->get_last_modified_time() ); //pass this, if used
+ res->set_import_last_modified_time(res->get_last_modified_time()); //pass this, if used
res->set_import_path(pat.path);
}
#endif
return res;
-
}
-void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extensions) const {
Set<String> found;
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
List<String> local_exts;
E->get()->get_recognized_extensions(&local_exts);
- for (List<String>::Element *F=local_exts.front();F;F=F->next()) {
+ for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
@@ -136,25 +131,25 @@ void ResourceFormatImporter::get_recognized_extensions(List<String> *p_extension
}
}
-void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const{
+void ResourceFormatImporter::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
- if (p_type=="") {
+ if (p_type == "") {
return get_recognized_extensions(p_extensions);
}
Set<String> found;
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
String res_type = E->get()->get_resource_type();
- if (res_type==String())
+ if (res_type == String())
continue;
- if (!ClassDB::is_parent_class(res_type,p_type))
+ if (!ClassDB::is_parent_class(res_type, p_type))
continue;
List<String> local_exts;
E->get()->get_recognized_extensions(&local_exts);
- for (List<String>::Element *F=local_exts.front();F;F=F->next()) {
+ for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
if (!found.has(F->get())) {
p_extensions->push_back(F->get());
found.insert(F->get());
@@ -163,40 +158,36 @@ void ResourceFormatImporter::get_recognized_extensions_for_type(const String& p_
}
}
-bool ResourceFormatImporter::recognize_path(const String& p_path,const String& p_for_type) const{
-
- return FileAccess::exists(p_path+".import");
+bool ResourceFormatImporter::recognize_path(const String &p_path, const String &p_for_type) const {
+ return FileAccess::exists(p_path + ".import");
}
-bool ResourceFormatImporter::can_be_imported(const String& p_path) const {
+bool ResourceFormatImporter::can_be_imported(const String &p_path) const {
return ResourceFormatLoader::recognize_path(p_path);
}
+bool ResourceFormatImporter::handles_type(const String &p_type) const {
-bool ResourceFormatImporter::handles_type(const String& p_type) const {
-
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
String res_type = E->get()->get_resource_type();
- if (res_type==String())
+ if (res_type == String())
continue;
- if (ClassDB::is_parent_class(res_type,p_type))
+ if (ClassDB::is_parent_class(res_type, p_type))
return true;
-
}
return true;
}
-
-String ResourceFormatImporter::get_internal_resource_path(const String& p_path) const {
+String ResourceFormatImporter::get_internal_resource_path(const String &p_path) const {
PathAndType pat;
- Error err = _get_path_and_type(p_path,pat);
+ Error err = _get_path_and_type(p_path, pat);
- if (err!=OK) {
+ if (err != OK) {
return String();
}
@@ -207,9 +198,9 @@ String ResourceFormatImporter::get_internal_resource_path(const String& p_path)
String ResourceFormatImporter::get_resource_type(const String &p_path) const {
PathAndType pat;
- Error err = _get_path_and_type(p_path,pat);
+ Error err = _get_path_and_type(p_path, pat);
- if (err!=OK) {
+ if (err != OK) {
return "";
}
@@ -217,23 +208,23 @@ String ResourceFormatImporter::get_resource_type(const String &p_path) const {
return pat.type;
}
-void ResourceFormatImporter::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types){
+void ResourceFormatImporter::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
PathAndType pat;
- Error err = _get_path_and_type(p_path,pat);
+ Error err = _get_path_and_type(p_path, pat);
- if (err!=OK) {
+ if (err != OK) {
return;
}
- return ResourceLoader::get_dependencies(pat.path,p_dependencies,p_add_types);
+ return ResourceLoader::get_dependencies(pat.path, p_dependencies, p_add_types);
}
-Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String& p_name) {
+Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String &p_name) {
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
- if (E->get()->get_importer_name()==p_name) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
+ if (E->get()->get_importer_name() == p_name) {
return E->get();
}
}
@@ -241,34 +232,32 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_name(const String&
return Ref<ResourceImporter>();
}
+void ResourceFormatImporter::get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers) {
-void ResourceFormatImporter::get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers) {
-
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
List<String> local_exts;
E->get()->get_recognized_extensions(&local_exts);
- for (List<String>::Element *F=local_exts.front();F;F=F->next()) {
- if (p_extension.to_lower()==F->get()) {
+ for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
+ if (p_extension.to_lower() == F->get()) {
r_importers->push_back(E->get());
}
}
}
}
-Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String& p_extension) {
-
+Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const String &p_extension) {
Ref<ResourceImporter> importer;
- float priority=0;
+ float priority = 0;
- for (Set< Ref<ResourceImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
List<String> local_exts;
E->get()->get_recognized_extensions(&local_exts);
- for (List<String>::Element *F=local_exts.front();F;F=F->next()) {
- if (p_extension.to_lower()==F->get() && E->get()->get_priority() > priority) {
- importer=E->get();
- priority=E->get()->get_priority();
+ for (List<String>::Element *F = local_exts.front(); F; F = F->next()) {
+ if (p_extension.to_lower() == F->get() && E->get()->get_priority() > priority) {
+ importer = E->get();
+ priority = E->get()->get_priority();
}
}
}
@@ -276,13 +265,13 @@ Ref<ResourceImporter> ResourceFormatImporter::get_importer_by_extension(const St
return importer;
}
-String ResourceFormatImporter::get_import_base_path(const String& p_for_file) const {
+String ResourceFormatImporter::get_import_base_path(const String &p_for_file) const {
- return "res://.import/"+p_for_file.get_file()+"-"+p_for_file.md5_text();
+ return "res://.import/" + p_for_file.get_file() + "-" + p_for_file.md5_text();
}
-ResourceFormatImporter *ResourceFormatImporter::singleton=NULL;
+ResourceFormatImporter *ResourceFormatImporter::singleton = NULL;
ResourceFormatImporter::ResourceFormatImporter() {
- singleton=this;
+ singleton = this;
}
diff --git a/core/io/resource_import.h b/core/io/resource_import.h
index dd7a82fe75..f4349a9c61 100644
--- a/core/io/resource_import.h
+++ b/core/io/resource_import.h
@@ -29,7 +29,6 @@
#ifndef RESOURCE_IMPORT_H
#define RESOURCE_IMPORT_H
-
#include "io/resource_loader.h"
class ResourceImporter;
@@ -40,66 +39,64 @@ class ResourceFormatImporter : public ResourceFormatLoader {
String type;
};
-
- Error _get_path_and_type(const String& p_path,PathAndType & r_path_and_type) const;
+ Error _get_path_and_type(const String &p_path, PathAndType &r_path_and_type) const;
static ResourceFormatImporter *singleton;
- Set< Ref<ResourceImporter> > importers;
-public:
+ Set<Ref<ResourceImporter> > importers;
+public:
static ResourceFormatImporter *get_singleton() { return singleton; }
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const;
- virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
+ virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
- virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false);
+ virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
- virtual bool can_be_imported(const String& p_path) const;
+ virtual bool can_be_imported(const String &p_path) const;
- String get_internal_resource_path(const String& p_path) const;
+ String get_internal_resource_path(const String &p_path) const;
- void add_importer(const Ref<ResourceImporter>& p_importer) { importers.insert(p_importer); }
- Ref<ResourceImporter> get_importer_by_name(const String& p_name);
- Ref<ResourceImporter> get_importer_by_extension(const String& p_extension);
- void get_importers_for_extension(const String& p_extension,List<Ref<ResourceImporter> > *r_importers);
+ void add_importer(const Ref<ResourceImporter> &p_importer) { importers.insert(p_importer); }
+ Ref<ResourceImporter> get_importer_by_name(const String &p_name);
+ Ref<ResourceImporter> get_importer_by_extension(const String &p_extension);
+ void get_importers_for_extension(const String &p_extension, List<Ref<ResourceImporter> > *r_importers);
- String get_import_base_path(const String& p_for_file) const;
+ String get_import_base_path(const String &p_for_file) const;
ResourceFormatImporter();
};
-
class ResourceImporter : public Reference {
- GDCLASS(ResourceImporter,Reference)
+ GDCLASS(ResourceImporter, Reference)
public:
- virtual String get_importer_name() const=0;
- virtual String get_visible_name() const=0;
- virtual void get_recognized_extensions(List<String> *p_extensions) const=0;
- virtual String get_save_extension() const=0;
- virtual String get_resource_type() const=0;
+ virtual String get_importer_name() const = 0;
+ virtual String get_visible_name() const = 0;
+ virtual void get_recognized_extensions(List<String> *p_extensions) const = 0;
+ virtual String get_save_extension() const = 0;
+ virtual String get_resource_type() const = 0;
virtual float get_priority() const { return 1.0; }
struct ImportOption {
PropertyInfo option;
Variant default_value;
- ImportOption(const PropertyInfo& p_info,const Variant& p_default) { option=p_info; default_value=p_default; }
+ ImportOption(const PropertyInfo &p_info, const Variant &p_default) {
+ option = p_info;
+ default_value = p_default;
+ }
ImportOption() {}
};
-
virtual int get_preset_count() const { return 0; }
virtual String get_preset_name(int p_idx) const { return String(); }
- virtual void get_import_options(List<ImportOption> *r_options,int p_preset=0) const=0;
- virtual bool get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const=0;
-
-
- 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=NULL)=0;
+ virtual void get_import_options(List<ImportOption> *r_options, int p_preset = 0) const = 0;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const = 0;
+ 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 = NULL) = 0;
};
#endif // RESOURCE_IMPORT_H
diff --git a/core/io/resource_loader.cpp b/core/io/resource_loader.cpp
index c14389eefa..5d8ec57ee0 100644
--- a/core/io/resource_loader.cpp
+++ b/core/io/resource_loader.cpp
@@ -27,81 +27,76 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "resource_loader.h"
-#include "print_string.h"
#include "global_config.h"
-#include "path_remap.h"
#include "os/file_access.h"
#include "os/os.h"
+#include "path_remap.h"
+#include "print_string.h"
ResourceFormatLoader *ResourceLoader::loader[MAX_LOADERS];
-int ResourceLoader::loader_count=0;
-
+int ResourceLoader::loader_count = 0;
Error ResourceInteractiveLoader::wait() {
Error err = poll();
- while (err==OK) {
- err=poll();
+ while (err == OK) {
+ err = poll();
}
return err;
}
-bool ResourceFormatLoader::recognize_path(const String& p_path,const String& p_for_type) const {
-
+bool ResourceFormatLoader::recognize_path(const String &p_path, const String &p_for_type) const {
String extension = p_path.get_extension();
List<String> extensions;
- if (p_for_type==String()) {
+ if (p_for_type == String()) {
get_recognized_extensions(&extensions);
} else {
- get_recognized_extensions_for_type(p_for_type,&extensions);
+ get_recognized_extensions_for_type(p_for_type, &extensions);
}
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
-
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
- if (E->get().nocasecmp_to(extension)==0)
+ if (E->get().nocasecmp_to(extension) == 0)
return true;
}
return false;
-
}
+void ResourceFormatLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
-void ResourceFormatLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const {
-
- if (p_type=="" || handles_type(p_type))
+ if (p_type == "" || handles_type(p_type))
get_recognized_extensions(p_extensions);
}
-void ResourceLoader::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) {
+void ResourceLoader::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) {
- for (int i=0;i<loader_count;i++) {
- loader[i]->get_recognized_extensions_for_type(p_type,p_extensions);
+ for (int i = 0; i < loader_count; i++) {
+ loader[i]->get_recognized_extensions_for_type(p_type, p_extensions);
}
-
}
void ResourceInteractiveLoader::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_resource"),&ResourceInteractiveLoader::get_resource);
- ClassDB::bind_method(D_METHOD("poll"),&ResourceInteractiveLoader::poll);
- ClassDB::bind_method(D_METHOD("wait"),&ResourceInteractiveLoader::wait);
- ClassDB::bind_method(D_METHOD("get_stage"),&ResourceInteractiveLoader::get_stage);
- ClassDB::bind_method(D_METHOD("get_stage_count"),&ResourceInteractiveLoader::get_stage_count);
+ ClassDB::bind_method(D_METHOD("get_resource"), &ResourceInteractiveLoader::get_resource);
+ ClassDB::bind_method(D_METHOD("poll"), &ResourceInteractiveLoader::poll);
+ ClassDB::bind_method(D_METHOD("wait"), &ResourceInteractiveLoader::wait);
+ ClassDB::bind_method(D_METHOD("get_stage"), &ResourceInteractiveLoader::get_stage);
+ ClassDB::bind_method(D_METHOD("get_stage_count"), &ResourceInteractiveLoader::get_stage_count);
}
class ResourceInteractiveLoaderDefault : public ResourceInteractiveLoader {
- GDCLASS( ResourceInteractiveLoaderDefault, ResourceInteractiveLoader );
-public:
+ GDCLASS(ResourceInteractiveLoaderDefault, ResourceInteractiveLoader);
+public:
Ref<Resource> resource;
- virtual void set_local_path(const String& p_local_path) { /*scene->set_filename(p_local_path);*/ }
+ virtual void set_local_path(const String &p_local_path) { /*scene->set_filename(p_local_path);*/
+ }
virtual Ref<Resource> get_resource() { return resource; }
virtual Error poll() { return ERR_FILE_EOF; }
virtual int get_stage() const { return 1; }
@@ -110,94 +105,87 @@ public:
ResourceInteractiveLoaderDefault() {}
};
-
-
Ref<ResourceInteractiveLoader> ResourceFormatLoader::load_interactive(const String &p_path, Error *r_error) {
//either this
- Ref<Resource> res = load(p_path,p_path,r_error);
+ Ref<Resource> res = load(p_path, p_path, r_error);
if (res.is_null())
return Ref<ResourceInteractiveLoader>();
- Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>( memnew( ResourceInteractiveLoaderDefault ));
- ril->resource=res;
+ Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
+ ril->resource = res;
return ril;
}
-RES ResourceFormatLoader::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoader::load(const String &p_path, const String &p_original_path, Error *r_error) {
-
- String path=p_path;
+ String path = p_path;
//or this must be implemented
- Ref<ResourceInteractiveLoader> ril = load_interactive(p_path,r_error);
+ Ref<ResourceInteractiveLoader> ril = load_interactive(p_path, r_error);
if (!ril.is_valid())
return RES();
ril->set_local_path(p_original_path);
- while(true) {
+ while (true) {
Error err = ril->poll();
- if (err==ERR_FILE_EOF) {
+ if (err == ERR_FILE_EOF) {
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return ril->get_resource();
}
if (r_error)
- *r_error=err;
+ *r_error = err;
- ERR_FAIL_COND_V(err!=OK,RES());
+ ERR_FAIL_COND_V(err != OK, RES());
}
return RES();
-
}
-void ResourceFormatLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) {
+void ResourceFormatLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
//do nothing by default
}
-
///////////////////////////////////
-
-RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p_no_cache, Error *r_error) {
+RES ResourceLoader::load(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
String local_path;
if (p_path.is_rel_path())
- local_path="res://"+p_path;
+ local_path = "res://" + p_path;
else
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
-
- ERR_FAIL_COND_V(local_path=="",RES());
+ ERR_FAIL_COND_V(local_path == "", RES());
if (!p_no_cache && ResourceCache::has(local_path)) {
if (OS::get_singleton()->is_stdout_verbose())
- print_line("load resource: "+local_path+" (cached)");
+ print_line("load resource: " + local_path + " (cached)");
- return RES( ResourceCache::get(local_path ) );
+ return RES(ResourceCache::get(local_path));
}
if (OS::get_singleton()->is_stdout_verbose())
- print_line("load resource: "+local_path);
- bool found=false;
+ print_line("load resource: " + local_path);
+ bool found = false;
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
- if (!loader[i]->recognize_path(local_path,p_type_hint)) {
+ if (!loader[i]->recognize_path(local_path, p_type_hint)) {
print_line("path not recognized");
continue;
}
- found=true;
- RES res = loader[i]->load(local_path,local_path,r_error);
+ found = true;
+ RES res = loader[i]->load(local_path, local_path, r_error);
if (res.is_null()) {
continue;
}
@@ -217,37 +205,31 @@ RES ResourceLoader::load(const String &p_path, const String& p_type_hint, bool p
}
if (found) {
- ERR_EXPLAIN("Failed loading resource: "+p_path);
+ ERR_EXPLAIN("Failed loading resource: " + p_path);
} else {
- ERR_EXPLAIN("No loader found for resource: "+p_path);
+ ERR_EXPLAIN("No loader found for resource: " + p_path);
}
ERR_FAIL_V(RES());
return RES();
}
-
-
-Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path,const String& p_type_hint,bool p_no_cache,Error *r_error) {
-
+Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_path, const String &p_type_hint, bool p_no_cache, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
String local_path;
if (p_path.is_rel_path())
- local_path="res://"+p_path;
+ local_path = "res://" + p_path;
else
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
-
- ERR_FAIL_COND_V(local_path=="",Ref<ResourceInteractiveLoader>());
-
-
+ ERR_FAIL_COND_V(local_path == "", Ref<ResourceInteractiveLoader>());
if (!p_no_cache && ResourceCache::has(local_path)) {
if (OS::get_singleton()->is_stdout_verbose())
- print_line("load resource: "+local_path+" (cached)");
+ print_line("load resource: " + local_path + " (cached)");
Ref<Resource> res_cached = ResourceCache::get(local_path);
Ref<ResourceInteractiveLoaderDefault> ril = Ref<ResourceInteractiveLoaderDefault>(memnew(ResourceInteractiveLoaderDefault));
@@ -259,14 +241,14 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_
if (OS::get_singleton()->is_stdout_verbose())
print_line("load resource: ");
- bool found=false;
+ bool found = false;
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
- if (!loader[i]->recognize_path(local_path,p_type_hint))
+ if (!loader[i]->recognize_path(local_path, p_type_hint))
continue;
- found=true;
- Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path,r_error);
+ found = true;
+ Ref<ResourceInteractiveLoader> ril = loader[i]->load_interactive(local_path, r_error);
if (ril.is_null())
continue;
if (!p_no_cache)
@@ -276,39 +258,37 @@ Ref<ResourceInteractiveLoader> ResourceLoader::load_interactive(const String &p_
}
if (found) {
- ERR_EXPLAIN("Failed loading resource: "+p_path);
+ ERR_EXPLAIN("Failed loading resource: " + p_path);
} else {
- ERR_EXPLAIN("No loader found for resource: "+p_path);
+ ERR_EXPLAIN("No loader found for resource: " + p_path);
}
ERR_FAIL_V(Ref<ResourceInteractiveLoader>());
return Ref<ResourceInteractiveLoader>();
-
}
void ResourceLoader::add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front) {
- ERR_FAIL_COND( loader_count >= MAX_LOADERS );
+ ERR_FAIL_COND(loader_count >= MAX_LOADERS);
if (p_at_front) {
- for(int i=loader_count;i>0;i--) {
- loader[i]=loader[i-1];
+ for (int i = loader_count; i > 0; i--) {
+ loader[i] = loader[i - 1];
}
- loader[0]=p_format_loader;
+ loader[0] = p_format_loader;
loader_count++;
} else {
- loader[loader_count++]=p_format_loader;
+ loader[loader_count++] = p_format_loader;
}
}
-void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types) {
-
+void ResourceLoader::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
String local_path;
if (p_path.is_rel_path())
- local_path="res://"+p_path;
+ local_path = "res://" + p_path;
else
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
if (!loader[i]->recognize_path(local_path))
continue;
@@ -317,22 +297,19 @@ void ResourceLoader::get_dependencies(const String& p_path, List<String> *p_depe
continue;
*/
- loader[i]->get_dependencies(local_path,p_dependencies,p_add_types);
-
+ loader[i]->get_dependencies(local_path, p_dependencies, p_add_types);
}
}
-Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String,String>& p_map) {
-
+Error ResourceLoader::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
String local_path;
if (p_path.is_rel_path())
- local_path="res://"+p_path;
+ local_path = "res://" + p_path;
else
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
-
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
if (!loader[i]->recognize_path(local_path))
continue;
@@ -341,41 +318,34 @@ Error ResourceLoader::rename_dependencies(const String &p_path,const Map<String,
continue;
*/
- return loader[i]->rename_dependencies(local_path,p_map);
-
+ return loader[i]->rename_dependencies(local_path, p_map);
}
return OK; // ??
-
}
-
-
String ResourceLoader::get_resource_type(const String &p_path) {
String local_path;
if (p_path.is_rel_path())
- local_path="res://"+p_path;
+ local_path = "res://" + p_path;
else
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
-
- for (int i=0;i<loader_count;i++) {
+ for (int i = 0; i < loader_count; i++) {
String result = loader[i]->get_resource_type(local_path);
- if (result!="")
+ if (result != "")
return result;
}
return "";
-
}
-ResourceLoadErrorNotify ResourceLoader::err_notify=NULL;
-void *ResourceLoader::err_notify_ud=NULL;
-
-DependencyErrorNotify ResourceLoader::dep_err_notify=NULL;
-void *ResourceLoader::dep_err_notify_ud=NULL;
+ResourceLoadErrorNotify ResourceLoader::err_notify = NULL;
+void *ResourceLoader::err_notify_ud = NULL;
-bool ResourceLoader::abort_on_missing_resource=true;
-bool ResourceLoader::timestamp_on_load=false;
+DependencyErrorNotify ResourceLoader::dep_err_notify = NULL;
+void *ResourceLoader::dep_err_notify_ud = NULL;
+bool ResourceLoader::abort_on_missing_resource = true;
+bool ResourceLoader::timestamp_on_load = false;
diff --git a/core/io/resource_loader.h b/core/io/resource_loader.h
index f464415e12..0d51b07414 100644
--- a/core/io/resource_loader.h
+++ b/core/io/resource_loader.h
@@ -37,86 +37,86 @@
class ResourceInteractiveLoader : public Reference {
- GDCLASS(ResourceInteractiveLoader,Reference);
-protected:
+ GDCLASS(ResourceInteractiveLoader, Reference);
+protected:
static void _bind_methods();
-public:
- virtual void set_local_path(const String& p_local_path)=0;
- virtual Ref<Resource> get_resource()=0;
- virtual Error poll()=0;
- virtual int get_stage() const=0;
- virtual int get_stage_count() const=0;
+public:
+ virtual void set_local_path(const String &p_local_path) = 0;
+ virtual Ref<Resource> get_resource() = 0;
+ virtual Error poll() = 0;
+ virtual int get_stage() const = 0;
+ virtual int get_stage_count() const = 0;
virtual Error wait();
ResourceInteractiveLoader() {}
};
-
class ResourceFormatLoader {
public:
-
- virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL);
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
- virtual void get_recognized_extensions(List<String> *p_extensions) const=0;
- virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const;
- virtual bool recognize_path(const String& p_path,const String& p_for_type=String()) const;
- virtual bool handles_type(const String& p_type) const=0;
- virtual String get_resource_type(const String &p_path) const=0;
- virtual void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false);
- virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map) { return OK; }
+ virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
+ virtual void get_recognized_extensions(List<String> *p_extensions) const = 0;
+ virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
+ virtual bool recognize_path(const String &p_path, const String &p_for_type = String()) const;
+ virtual bool handles_type(const String &p_type) const = 0;
+ virtual String get_resource_type(const String &p_path) const = 0;
+ virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
+ virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map) { return OK; }
virtual ~ResourceFormatLoader() {}
};
-
-typedef void (*ResourceLoadErrorNotify)(void *p_ud,const String& p_text);
-typedef void (*DependencyErrorNotify)(void *p_ud,const String& p_loading,const String& p_which,const String& p_type);
-
+typedef void (*ResourceLoadErrorNotify)(void *p_ud, const String &p_text);
+typedef void (*DependencyErrorNotify)(void *p_ud, const String &p_loading, const String &p_which, const String &p_type);
class ResourceLoader {
enum {
- MAX_LOADERS=64
+ MAX_LOADERS = 64
};
static ResourceFormatLoader *loader[MAX_LOADERS];
static int loader_count;
static bool timestamp_on_load;
- static void* err_notify_ud;
+ static void *err_notify_ud;
static ResourceLoadErrorNotify err_notify;
- static void* dep_err_notify_ud;
+ static void *dep_err_notify_ud;
static DependencyErrorNotify dep_err_notify;
static bool abort_on_missing_resource;
public:
+ static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL);
+ static RES load(const String &p_path, const String &p_type_hint = "", bool p_no_cache = false, Error *r_error = NULL);
-
-
- static Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL);
- static RES load(const String &p_path,const String& p_type_hint="",bool p_no_cache=false,Error *r_error=NULL);
-
- static void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions);
- static void add_resource_format_loader(ResourceFormatLoader *p_format_loader,bool p_at_front=false);
+ static void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions);
+ static void add_resource_format_loader(ResourceFormatLoader *p_format_loader, bool p_at_front = false);
static String get_resource_type(const String &p_path);
- static void get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types=false);
- static Error rename_dependencies(const String &p_path,const Map<String,String>& p_map);
-
- static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load=p_timestamp; }
-
- static void notify_load_error(const String& p_err) { if (err_notify) err_notify(err_notify_ud,p_err); }
- static void set_error_notify_func(void* p_ud,ResourceLoadErrorNotify p_err_notify) { err_notify=p_err_notify; err_notify_ud=p_ud;}
-
- static void notify_dependency_error(const String& p_path,const String& p_dependency,const String& p_type) { if (dep_err_notify) dep_err_notify(dep_err_notify_ud,p_path,p_dependency,p_type); }
- static void set_dependency_error_notify_func(void* p_ud,DependencyErrorNotify p_err_notify) { dep_err_notify=p_err_notify; dep_err_notify_ud=p_ud;}
-
-
- static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource=p_abort; }
+ static void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
+ static Error rename_dependencies(const String &p_path, const Map<String, String> &p_map);
+
+ static void set_timestamp_on_load(bool p_timestamp) { timestamp_on_load = p_timestamp; }
+
+ static void notify_load_error(const String &p_err) {
+ if (err_notify) err_notify(err_notify_ud, p_err);
+ }
+ static void set_error_notify_func(void *p_ud, ResourceLoadErrorNotify p_err_notify) {
+ err_notify = p_err_notify;
+ err_notify_ud = p_ud;
+ }
+
+ static void notify_dependency_error(const String &p_path, const String &p_dependency, const String &p_type) {
+ if (dep_err_notify) dep_err_notify(dep_err_notify_ud, p_path, p_dependency, p_type);
+ }
+ static void set_dependency_error_notify_func(void *p_ud, DependencyErrorNotify p_err_notify) {
+ dep_err_notify = p_err_notify;
+ dep_err_notify_ud = p_ud;
+ }
+
+ static void set_abort_on_missing_resources(bool p_abort) { abort_on_missing_resource = p_abort; }
static bool get_abort_on_missing_resources() { return abort_on_missing_resource; }
};
-
-
#endif
diff --git a/core/io/resource_saver.cpp b/core/io/resource_saver.cpp
index f0bea30051..e4548b16ff 100644
--- a/core/io/resource_saver.cpp
+++ b/core/io/resource_saver.cpp
@@ -29,62 +29,61 @@
#include "resource_saver.h"
#include "global_config.h"
#include "os/file_access.h"
-#include "script_language.h"
#include "resource_loader.h"
+#include "script_language.h"
ResourceFormatSaver *ResourceSaver::saver[MAX_SAVERS];
-int ResourceSaver::saver_count=0;
-bool ResourceSaver::timestamp_on_save=false;
-ResourceSavedCallback ResourceSaver::save_callback=0;
+int ResourceSaver::saver_count = 0;
+bool ResourceSaver::timestamp_on_save = false;
+ResourceSavedCallback ResourceSaver::save_callback = 0;
-Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
+Error ResourceSaver::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
- String extension=p_path.get_extension();
- Error err=ERR_FILE_UNRECOGNIZED;
+ String extension = p_path.get_extension();
+ Error err = ERR_FILE_UNRECOGNIZED;
- for (int i=0;i<saver_count;i++) {
+ for (int i = 0; i < saver_count; i++) {
if (!saver[i]->recognize(p_resource))
continue;
List<String> extensions;
- bool recognized=false;
- saver[i]->get_recognized_extensions(p_resource,&extensions);
+ bool recognized = false;
+ saver[i]->get_recognized_extensions(p_resource, &extensions);
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
- if (E->get().nocasecmp_to(extension.get_extension())==0)
- recognized=true;
+ if (E->get().nocasecmp_to(extension.get_extension()) == 0)
+ recognized = true;
}
if (!recognized)
continue;
- String old_path=p_resource->get_path();
+ String old_path = p_resource->get_path();
-
- String local_path=GlobalConfig::get_singleton()->localize_path(p_path);
+ String local_path = GlobalConfig::get_singleton()->localize_path(p_path);
RES rwcopy = p_resource;
- if (p_flags&FLAG_CHANGE_PATH)
+ if (p_flags & FLAG_CHANGE_PATH)
rwcopy->set_path(local_path);
- err = saver[i]->save(p_path,p_resource,p_flags);
+ err = saver[i]->save(p_path, p_resource, p_flags);
- if (err == OK ) {
+ if (err == OK) {
#ifdef TOOLS_ENABLED
- ((Resource*)p_resource.ptr())->set_edited(false);
+ ((Resource *)p_resource.ptr())->set_edited(false);
if (timestamp_on_save) {
uint64_t mt = FileAccess::get_modified_time(p_path);
- ((Resource*)p_resource.ptr())->set_last_modified_time(mt);
+ ((Resource *)p_resource.ptr())->set_last_modified_time(mt);
}
#endif
- if (p_flags&FLAG_CHANGE_PATH)
+ if (p_flags & FLAG_CHANGE_PATH)
rwcopy->set_path(old_path);
if (save_callback && p_path.begins_with("res://"))
@@ -92,46 +91,36 @@ Error ResourceSaver::save(const String &p_path,const RES& p_resource,uint32_t p_
return OK;
} else {
-
}
}
return err;
}
-
void ResourceSaver::set_save_callback(ResourceSavedCallback p_callback) {
- save_callback=p_callback;
+ save_callback = p_callback;
}
+void ResourceSaver::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) {
-void ResourceSaver::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) {
-
-
- for (int i=0;i<saver_count;i++) {
+ for (int i = 0; i < saver_count; i++) {
- saver[i]->get_recognized_extensions(p_resource,p_extensions);
+ saver[i]->get_recognized_extensions(p_resource, p_extensions);
}
-
}
void ResourceSaver::add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front) {
- ERR_FAIL_COND( saver_count >= MAX_SAVERS );
+ ERR_FAIL_COND(saver_count >= MAX_SAVERS);
if (p_at_front) {
- for(int i=saver_count;i>0;i--) {
- saver[i]=saver[i-1];
+ for (int i = saver_count; i > 0; i--) {
+ saver[i] = saver[i - 1];
}
- saver[0]=p_format_saver;
+ saver[0] = p_format_saver;
saver_count++;
} else {
- saver[saver_count++]=p_format_saver;
+ saver[saver_count++] = p_format_saver;
}
-
}
-
-
-
-
diff --git a/core/io/resource_saver.h b/core/io/resource_saver.h
index f00f074090..b9bb2aafae 100644
--- a/core/io/resource_saver.h
+++ b/core/io/resource_saver.h
@@ -35,27 +35,21 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
-
-
-
class ResourceFormatSaver {
public:
-
- virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0)=0;
- virtual bool recognize(const RES& p_resource) const=0;
- virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const=0;
+ virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0) = 0;
+ virtual bool recognize(const RES &p_resource) const = 0;
+ virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const = 0;
virtual ~ResourceFormatSaver() {}
};
-typedef void (*ResourceSavedCallback)(const String& p_path);
+typedef void (*ResourceSavedCallback)(const String &p_path);
class ResourceSaver {
enum {
- MAX_SAVERS=64
+ MAX_SAVERS = 64
};
static ResourceFormatSaver *saver[MAX_SAVERS];
@@ -63,31 +57,24 @@ class ResourceSaver {
static bool timestamp_on_save;
static ResourceSavedCallback save_callback;
-
public:
-
enum SaverFlags {
- FLAG_RELATIVE_PATHS=1,
- FLAG_BUNDLE_RESOURCES=2,
- FLAG_CHANGE_PATH=4,
- FLAG_OMIT_EDITOR_PROPERTIES=8,
- FLAG_SAVE_BIG_ENDIAN=16,
- FLAG_COMPRESS=32,
- FLAG_REPLACE_SUBRESOURCE_PATHS=64,
+ FLAG_RELATIVE_PATHS = 1,
+ FLAG_BUNDLE_RESOURCES = 2,
+ FLAG_CHANGE_PATH = 4,
+ FLAG_OMIT_EDITOR_PROPERTIES = 8,
+ FLAG_SAVE_BIG_ENDIAN = 16,
+ FLAG_COMPRESS = 32,
+ FLAG_REPLACE_SUBRESOURCE_PATHS = 64,
};
+ static Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
+ static void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions);
+ static void add_resource_format_saver(ResourceFormatSaver *p_format_saver, bool p_at_front = false);
- static Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
- static void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions);
- static void add_resource_format_saver(ResourceFormatSaver *p_format_saver,bool p_at_front=false);
-
- static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save=p_timestamp; }
+ static void set_timestamp_on_save(bool p_timestamp) { timestamp_on_save = p_timestamp; }
static void set_save_callback(ResourceSavedCallback p_callback);
-
-
-
};
-
#endif
diff --git a/core/io/stream_peer.cpp b/core/io/stream_peer.cpp
index 3c4719269f..07df47f8c0 100644
--- a/core/io/stream_peer.cpp
+++ b/core/io/stream_peer.cpp
@@ -29,21 +29,21 @@
#include "stream_peer.h"
#include "io/marshalls.h"
-Error StreamPeer::_put_data(const PoolVector<uint8_t>& p_data) {
+Error StreamPeer::_put_data(const PoolVector<uint8_t> &p_data) {
int len = p_data.size();
- if (len==0)
+ if (len == 0)
return OK;
PoolVector<uint8_t>::Read r = p_data.read();
- return put_data(&r[0],len);
+ return put_data(&r[0], len);
}
-Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) {
+Array StreamPeer::_put_partial_data(const PoolVector<uint8_t> &p_data) {
Array ret;
int len = p_data.size();
- if (len==0) {
+ if (len == 0) {
ret.push_back(OK);
ret.push_back(0);
return ret;
@@ -51,24 +51,23 @@ Array StreamPeer::_put_partial_data(const PoolVector<uint8_t>& p_data) {
PoolVector<uint8_t>::Read r = p_data.read();
int sent;
- Error err = put_partial_data(&r[0],len,sent);
+ Error err = put_partial_data(&r[0], len, sent);
- if (err!=OK) {
- sent=0;
+ if (err != OK) {
+ sent = 0;
}
ret.push_back(err);
ret.push_back(sent);
return ret;
}
-
Array StreamPeer::_get_data(int p_bytes) {
Array ret;
PoolVector<uint8_t> data;
data.resize(p_bytes);
- if (data.size()!=p_bytes) {
+ if (data.size() != p_bytes) {
ret.push_back(ERR_OUT_OF_MEMORY);
ret.push_back(PoolVector<uint8_t>());
@@ -76,12 +75,11 @@ Array StreamPeer::_get_data(int p_bytes) {
}
PoolVector<uint8_t>::Write w = data.write();
- Error err = get_data(&w[0],p_bytes);
+ Error err = get_data(&w[0], p_bytes);
w = PoolVector<uint8_t>::Write();
ret.push_back(err);
ret.push_back(data);
return ret;
-
}
Array StreamPeer::_get_partial_data(int p_bytes) {
@@ -90,7 +88,7 @@ Array StreamPeer::_get_partial_data(int p_bytes) {
PoolVector<uint8_t> data;
data.resize(p_bytes);
- if (data.size()!=p_bytes) {
+ if (data.size() != p_bytes) {
ret.push_back(ERR_OUT_OF_MEMORY);
ret.push_back(PoolVector<uint8_t>());
@@ -99,12 +97,12 @@ Array StreamPeer::_get_partial_data(int p_bytes) {
PoolVector<uint8_t>::Write w = data.write();
int received;
- Error err = get_partial_data(&w[0],p_bytes,received);
+ Error err = get_partial_data(&w[0], p_bytes, received);
w = PoolVector<uint8_t>::Write();
- if (err!=OK) {
+ if (err != OK) {
data.resize(0);
- } else if (received!=data.size()) {
+ } else if (received != data.size()) {
data.resize(received);
}
@@ -112,12 +110,11 @@ Array StreamPeer::_get_partial_data(int p_bytes) {
ret.push_back(err);
ret.push_back(data);
return ret;
-
}
void StreamPeer::set_big_endian(bool p_enable) {
- big_endian=p_enable;
+ big_endian = p_enable;
}
bool StreamPeer::is_big_endian_enabled() const {
@@ -125,389 +122,359 @@ bool StreamPeer::is_big_endian_enabled() const {
return big_endian;
}
-
void StreamPeer::put_u8(uint8_t p_val) {
- put_data((const uint8_t*)&p_val,1);
-
+ put_data((const uint8_t *)&p_val, 1);
}
-void StreamPeer::put_8(int8_t p_val){
+void StreamPeer::put_8(int8_t p_val) {
- put_data((const uint8_t*)&p_val,1);
+ put_data((const uint8_t *)&p_val, 1);
}
-void StreamPeer::put_u16(uint16_t p_val){
+void StreamPeer::put_u16(uint16_t p_val) {
if (big_endian) {
- p_val=BSWAP16(p_val);
+ p_val = BSWAP16(p_val);
}
uint8_t buf[2];
- encode_uint16(p_val,buf);
- put_data(buf,2);
-
+ encode_uint16(p_val, buf);
+ put_data(buf, 2);
}
-void StreamPeer::put_16(int16_t p_val){
+void StreamPeer::put_16(int16_t p_val) {
if (big_endian) {
- p_val=BSWAP16(p_val);
+ p_val = BSWAP16(p_val);
}
uint8_t buf[2];
- encode_uint16(p_val,buf);
- put_data(buf,2);
-
+ encode_uint16(p_val, buf);
+ put_data(buf, 2);
}
-void StreamPeer::put_u32(uint32_t p_val){
+void StreamPeer::put_u32(uint32_t p_val) {
if (big_endian) {
- p_val=BSWAP32(p_val);
+ p_val = BSWAP32(p_val);
}
uint8_t buf[4];
- encode_uint32(p_val,buf);
- put_data(buf,4);
-
+ encode_uint32(p_val, buf);
+ put_data(buf, 4);
}
-void StreamPeer::put_32(int32_t p_val){
+void StreamPeer::put_32(int32_t p_val) {
if (big_endian) {
- p_val=BSWAP32(p_val);
+ p_val = BSWAP32(p_val);
}
uint8_t buf[4];
- encode_uint32(p_val,buf);
- put_data(buf,4);
-
+ encode_uint32(p_val, buf);
+ put_data(buf, 4);
}
-void StreamPeer::put_u64(uint64_t p_val){
+void StreamPeer::put_u64(uint64_t p_val) {
if (big_endian) {
- p_val=BSWAP64(p_val);
+ p_val = BSWAP64(p_val);
}
uint8_t buf[8];
- encode_uint64(p_val,buf);
- put_data(buf,8);
-
+ encode_uint64(p_val, buf);
+ put_data(buf, 8);
}
-void StreamPeer::put_64(int64_t p_val){
+void StreamPeer::put_64(int64_t p_val) {
if (big_endian) {
- p_val=BSWAP64(p_val);
+ p_val = BSWAP64(p_val);
}
uint8_t buf[8];
- encode_uint64(p_val,buf);
- put_data(buf,8);
-
+ encode_uint64(p_val, buf);
+ put_data(buf, 8);
}
-void StreamPeer::put_float(float p_val){
+void StreamPeer::put_float(float p_val) {
uint8_t buf[4];
- encode_float(p_val,buf);
+ encode_float(p_val, buf);
if (big_endian) {
- uint32_t *p32=(uint32_t *)buf;
- *p32=BSWAP32(*p32);
+ uint32_t *p32 = (uint32_t *)buf;
+ *p32 = BSWAP32(*p32);
}
- put_data(buf,4);
-
+ put_data(buf, 4);
}
-void StreamPeer::put_double(double p_val){
+void StreamPeer::put_double(double p_val) {
uint8_t buf[8];
- encode_double(p_val,buf);
+ encode_double(p_val, buf);
if (big_endian) {
- uint64_t *p64=(uint64_t *)buf;
- *p64=BSWAP64(*p64);
+ uint64_t *p64 = (uint64_t *)buf;
+ *p64 = BSWAP64(*p64);
}
- put_data(buf,8);
-
+ put_data(buf, 8);
}
-void StreamPeer::put_utf8_string(const String& p_string) {
+void StreamPeer::put_utf8_string(const String &p_string) {
- CharString cs=p_string.utf8();
+ CharString cs = p_string.utf8();
put_u32(p_string.length());
- put_data((const uint8_t*)cs.get_data(),cs.length());
-
+ put_data((const uint8_t *)cs.get_data(), cs.length());
}
-void StreamPeer::put_var(const Variant& p_variant){
+void StreamPeer::put_var(const Variant &p_variant) {
- int len=0;
+ int len = 0;
Vector<uint8_t> buf;
- encode_variant(p_variant,NULL,len);
+ encode_variant(p_variant, NULL, len);
buf.resize(len);
put_32(len);
- encode_variant(p_variant,buf.ptr(),len);
- put_data(buf.ptr(),buf.size());
-
-
+ encode_variant(p_variant, buf.ptr(), len);
+ put_data(buf.ptr(), buf.size());
}
-uint8_t StreamPeer::get_u8(){
+uint8_t StreamPeer::get_u8() {
uint8_t buf[1];
- get_data(buf,1);
+ get_data(buf, 1);
return buf[0];
}
-int8_t StreamPeer::get_8(){
+int8_t StreamPeer::get_8() {
uint8_t buf[1];
- get_data(buf,1);
+ get_data(buf, 1);
return buf[0];
-
}
-uint16_t StreamPeer::get_u16(){
+uint16_t StreamPeer::get_u16() {
uint8_t buf[2];
- get_data(buf,2);
+ get_data(buf, 2);
uint16_t r = decode_uint16(buf);
if (big_endian) {
- r=BSWAP16(r);
+ r = BSWAP16(r);
}
return r;
-
}
-int16_t StreamPeer::get_16(){
+int16_t StreamPeer::get_16() {
uint8_t buf[2];
- get_data(buf,2);
+ get_data(buf, 2);
uint16_t r = decode_uint16(buf);
if (big_endian) {
- r=BSWAP16(r);
+ r = BSWAP16(r);
}
return r;
-
}
-uint32_t StreamPeer::get_u32(){
+uint32_t StreamPeer::get_u32() {
uint8_t buf[4];
- get_data(buf,4);
+ get_data(buf, 4);
uint32_t r = decode_uint32(buf);
if (big_endian) {
- r=BSWAP32(r);
+ r = BSWAP32(r);
}
return r;
-
}
-int32_t StreamPeer::get_32(){
+int32_t StreamPeer::get_32() {
uint8_t buf[4];
- get_data(buf,4);
+ get_data(buf, 4);
uint32_t r = decode_uint32(buf);
if (big_endian) {
- r=BSWAP32(r);
+ r = BSWAP32(r);
}
return r;
-
}
-uint64_t StreamPeer::get_u64(){
+uint64_t StreamPeer::get_u64() {
uint8_t buf[8];
- get_data(buf,8);
+ get_data(buf, 8);
uint64_t r = decode_uint64(buf);
if (big_endian) {
- r=BSWAP64(r);
+ r = BSWAP64(r);
}
return r;
-
}
-int64_t StreamPeer::get_64(){
+int64_t StreamPeer::get_64() {
uint8_t buf[8];
- get_data(buf,8);
+ get_data(buf, 8);
uint64_t r = decode_uint64(buf);
if (big_endian) {
- r=BSWAP64(r);
+ r = BSWAP64(r);
}
return r;
-
}
-float StreamPeer::get_float(){
+float StreamPeer::get_float() {
uint8_t buf[4];
- get_data(buf,4);
+ get_data(buf, 4);
if (big_endian) {
- uint32_t *p32=(uint32_t *)buf;
- *p32=BSWAP32(*p32);
+ uint32_t *p32 = (uint32_t *)buf;
+ *p32 = BSWAP32(*p32);
}
return decode_float(buf);
}
-float StreamPeer::get_double(){
+float StreamPeer::get_double() {
uint8_t buf[8];
- get_data(buf,8);
+ get_data(buf, 8);
if (big_endian) {
- uint64_t *p64=(uint64_t *)buf;
- *p64=BSWAP64(*p64);
+ uint64_t *p64 = (uint64_t *)buf;
+ *p64 = BSWAP64(*p64);
}
return decode_double(buf);
-
}
-String StreamPeer::get_string(int p_bytes){
+String StreamPeer::get_string(int p_bytes) {
- ERR_FAIL_COND_V(p_bytes<0,String());
+ ERR_FAIL_COND_V(p_bytes < 0, String());
Vector<char> buf;
- Error err = buf.resize(p_bytes+1);
- ERR_FAIL_COND_V(err!=OK,String());
- err = get_data((uint8_t*)&buf[0],p_bytes);
- ERR_FAIL_COND_V(err!=OK,String());
- buf[p_bytes]=0;
+ Error err = buf.resize(p_bytes + 1);
+ ERR_FAIL_COND_V(err != OK, String());
+ err = get_data((uint8_t *)&buf[0], p_bytes);
+ ERR_FAIL_COND_V(err != OK, String());
+ buf[p_bytes] = 0;
return buf.ptr();
-
}
-String StreamPeer::get_utf8_string(int p_bytes){
+String StreamPeer::get_utf8_string(int p_bytes) {
- ERR_FAIL_COND_V(p_bytes<0,String());
+ ERR_FAIL_COND_V(p_bytes < 0, String());
Vector<uint8_t> buf;
Error err = buf.resize(p_bytes);
- ERR_FAIL_COND_V(err!=OK,String());
- err = get_data(buf.ptr(),p_bytes);
- ERR_FAIL_COND_V(err!=OK,String());
+ ERR_FAIL_COND_V(err != OK, String());
+ err = get_data(buf.ptr(), p_bytes);
+ ERR_FAIL_COND_V(err != OK, String());
String ret;
- ret.parse_utf8((const char*)buf.ptr(),buf.size());
+ ret.parse_utf8((const char *)buf.ptr(), buf.size());
return ret;
-
}
-Variant StreamPeer::get_var(){
+Variant StreamPeer::get_var() {
int len = get_32();
Vector<uint8_t> var;
Error err = var.resize(len);
- ERR_FAIL_COND_V(err!=OK,Variant());
- err = get_data(var.ptr(),len);
- ERR_FAIL_COND_V(err!=OK,Variant());
+ ERR_FAIL_COND_V(err != OK, Variant());
+ err = get_data(var.ptr(), len);
+ ERR_FAIL_COND_V(err != OK, Variant());
Variant ret;
- decode_variant(ret,var.ptr(),len);
+ decode_variant(ret, var.ptr(), len);
return ret;
}
-
void StreamPeer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("put_data","data"),&StreamPeer::_put_data);
- ClassDB::bind_method(D_METHOD("put_partial_data","data"),&StreamPeer::_put_partial_data);
-
- ClassDB::bind_method(D_METHOD("get_data","bytes"),&StreamPeer::_get_data);
- ClassDB::bind_method(D_METHOD("get_partial_data","bytes"),&StreamPeer::_get_partial_data);
-
- ClassDB::bind_method(D_METHOD("get_available_bytes"),&StreamPeer::get_available_bytes);
-
- ClassDB::bind_method(D_METHOD("set_big_endian","enable"),&StreamPeer::set_big_endian);
- ClassDB::bind_method(D_METHOD("is_big_endian_enabled"),&StreamPeer::is_big_endian_enabled);
-
- ClassDB::bind_method(D_METHOD("put_8","val"),&StreamPeer::put_8);
- ClassDB::bind_method(D_METHOD("put_u8","val"),&StreamPeer::put_u8);
- ClassDB::bind_method(D_METHOD("put_16","val"),&StreamPeer::put_16);
- ClassDB::bind_method(D_METHOD("put_u16","val"),&StreamPeer::put_u16);
- ClassDB::bind_method(D_METHOD("put_32","val"),&StreamPeer::put_32);
- ClassDB::bind_method(D_METHOD("put_u32","val"),&StreamPeer::put_u32);
- ClassDB::bind_method(D_METHOD("put_64","val"),&StreamPeer::put_64);
- ClassDB::bind_method(D_METHOD("put_u64","val"),&StreamPeer::put_u64);
- ClassDB::bind_method(D_METHOD("put_float","val"),&StreamPeer::put_float);
- ClassDB::bind_method(D_METHOD("put_double","val"),&StreamPeer::put_double);
- ClassDB::bind_method(D_METHOD("put_utf8_string","val"),&StreamPeer::put_utf8_string);
- ClassDB::bind_method(D_METHOD("put_var","val:Variant"),&StreamPeer::put_var);
-
- ClassDB::bind_method(D_METHOD("get_8"),&StreamPeer::get_8);
- ClassDB::bind_method(D_METHOD("get_u8"),&StreamPeer::get_u8);
- ClassDB::bind_method(D_METHOD("get_16"),&StreamPeer::get_16);
- ClassDB::bind_method(D_METHOD("get_u16"),&StreamPeer::get_u16);
- ClassDB::bind_method(D_METHOD("get_32"),&StreamPeer::get_32);
- ClassDB::bind_method(D_METHOD("get_u32"),&StreamPeer::get_u32);
- ClassDB::bind_method(D_METHOD("get_64"),&StreamPeer::get_64);
- ClassDB::bind_method(D_METHOD("get_u64"),&StreamPeer::get_u64);
- ClassDB::bind_method(D_METHOD("get_float"),&StreamPeer::get_float);
- ClassDB::bind_method(D_METHOD("get_double"),&StreamPeer::get_double);
- ClassDB::bind_method(D_METHOD("get_string","bytes"),&StreamPeer::get_string);
- ClassDB::bind_method(D_METHOD("get_utf8_string","bytes"),&StreamPeer::get_utf8_string);
- ClassDB::bind_method(D_METHOD("get_var:Variant"),&StreamPeer::get_var);
+ ClassDB::bind_method(D_METHOD("put_data", "data"), &StreamPeer::_put_data);
+ ClassDB::bind_method(D_METHOD("put_partial_data", "data"), &StreamPeer::_put_partial_data);
+
+ ClassDB::bind_method(D_METHOD("get_data", "bytes"), &StreamPeer::_get_data);
+ ClassDB::bind_method(D_METHOD("get_partial_data", "bytes"), &StreamPeer::_get_partial_data);
+
+ ClassDB::bind_method(D_METHOD("get_available_bytes"), &StreamPeer::get_available_bytes);
+
+ ClassDB::bind_method(D_METHOD("set_big_endian", "enable"), &StreamPeer::set_big_endian);
+ ClassDB::bind_method(D_METHOD("is_big_endian_enabled"), &StreamPeer::is_big_endian_enabled);
+
+ ClassDB::bind_method(D_METHOD("put_8", "val"), &StreamPeer::put_8);
+ ClassDB::bind_method(D_METHOD("put_u8", "val"), &StreamPeer::put_u8);
+ ClassDB::bind_method(D_METHOD("put_16", "val"), &StreamPeer::put_16);
+ ClassDB::bind_method(D_METHOD("put_u16", "val"), &StreamPeer::put_u16);
+ ClassDB::bind_method(D_METHOD("put_32", "val"), &StreamPeer::put_32);
+ ClassDB::bind_method(D_METHOD("put_u32", "val"), &StreamPeer::put_u32);
+ ClassDB::bind_method(D_METHOD("put_64", "val"), &StreamPeer::put_64);
+ ClassDB::bind_method(D_METHOD("put_u64", "val"), &StreamPeer::put_u64);
+ ClassDB::bind_method(D_METHOD("put_float", "val"), &StreamPeer::put_float);
+ ClassDB::bind_method(D_METHOD("put_double", "val"), &StreamPeer::put_double);
+ ClassDB::bind_method(D_METHOD("put_utf8_string", "val"), &StreamPeer::put_utf8_string);
+ ClassDB::bind_method(D_METHOD("put_var", "val:Variant"), &StreamPeer::put_var);
+
+ ClassDB::bind_method(D_METHOD("get_8"), &StreamPeer::get_8);
+ ClassDB::bind_method(D_METHOD("get_u8"), &StreamPeer::get_u8);
+ ClassDB::bind_method(D_METHOD("get_16"), &StreamPeer::get_16);
+ ClassDB::bind_method(D_METHOD("get_u16"), &StreamPeer::get_u16);
+ ClassDB::bind_method(D_METHOD("get_32"), &StreamPeer::get_32);
+ ClassDB::bind_method(D_METHOD("get_u32"), &StreamPeer::get_u32);
+ ClassDB::bind_method(D_METHOD("get_64"), &StreamPeer::get_64);
+ ClassDB::bind_method(D_METHOD("get_u64"), &StreamPeer::get_u64);
+ ClassDB::bind_method(D_METHOD("get_float"), &StreamPeer::get_float);
+ ClassDB::bind_method(D_METHOD("get_double"), &StreamPeer::get_double);
+ ClassDB::bind_method(D_METHOD("get_string", "bytes"), &StreamPeer::get_string);
+ ClassDB::bind_method(D_METHOD("get_utf8_string", "bytes"), &StreamPeer::get_utf8_string);
+ ClassDB::bind_method(D_METHOD("get_var:Variant"), &StreamPeer::get_var);
}
////////////////////////////////
-
void StreamPeerBuffer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("seek","pos"),&StreamPeerBuffer::seek);
- ClassDB::bind_method(D_METHOD("get_size"),&StreamPeerBuffer::get_size);
- ClassDB::bind_method(D_METHOD("get_pos"),&StreamPeerBuffer::get_pos);
- ClassDB::bind_method(D_METHOD("resize","size"),&StreamPeerBuffer::resize);
- ClassDB::bind_method(D_METHOD("set_data_array","data"),&StreamPeerBuffer::set_data_array);
- ClassDB::bind_method(D_METHOD("get_data_array"),&StreamPeerBuffer::get_data_array);
- ClassDB::bind_method(D_METHOD("clear"),&StreamPeerBuffer::clear);
- ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"),&StreamPeerBuffer::duplicate);
-
+ ClassDB::bind_method(D_METHOD("seek", "pos"), &StreamPeerBuffer::seek);
+ ClassDB::bind_method(D_METHOD("get_size"), &StreamPeerBuffer::get_size);
+ ClassDB::bind_method(D_METHOD("get_pos"), &StreamPeerBuffer::get_pos);
+ ClassDB::bind_method(D_METHOD("resize", "size"), &StreamPeerBuffer::resize);
+ ClassDB::bind_method(D_METHOD("set_data_array", "data"), &StreamPeerBuffer::set_data_array);
+ ClassDB::bind_method(D_METHOD("get_data_array"), &StreamPeerBuffer::get_data_array);
+ ClassDB::bind_method(D_METHOD("clear"), &StreamPeerBuffer::clear);
+ ClassDB::bind_method(D_METHOD("duplicate:StreamPeerBuffer"), &StreamPeerBuffer::duplicate);
}
+Error StreamPeerBuffer::put_data(const uint8_t *p_data, int p_bytes) {
-Error StreamPeerBuffer::put_data(const uint8_t* p_data,int p_bytes) {
-
- if (p_bytes<=0)
+ if (p_bytes <= 0)
return OK;
- if (pointer+p_bytes > data.size()) {
- data.resize(pointer+p_bytes);
-
+ if (pointer + p_bytes > data.size()) {
+ data.resize(pointer + p_bytes);
}
PoolVector<uint8_t>::Write w = data.write();
- copymem(&w[pointer],p_data,p_bytes);
+ copymem(&w[pointer], p_data, p_bytes);
- pointer+=p_bytes;
+ pointer += p_bytes;
return OK;
}
-Error StreamPeerBuffer::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent){
+Error StreamPeerBuffer::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
- r_sent=p_bytes;
- return put_data(p_data,p_bytes);
+ r_sent = p_bytes;
+ return put_data(p_data, p_bytes);
}
-Error StreamPeerBuffer::get_data(uint8_t* p_buffer, int p_bytes){
+Error StreamPeerBuffer::get_data(uint8_t *p_buffer, int p_bytes) {
int recv;
- get_partial_data(p_buffer,p_bytes,recv);
- if (recv!=p_bytes)
+ get_partial_data(p_buffer, p_bytes, recv);
+ if (recv != p_bytes)
return ERR_INVALID_PARAMETER;
return OK;
-
}
-Error StreamPeerBuffer::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received){
-
+Error StreamPeerBuffer::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
- if (pointer+p_bytes > data.size()) {
- r_received=data.size()-pointer;
- if (r_received<=0) {
- r_received=0;
+ if (pointer + p_bytes > data.size()) {
+ r_received = data.size() - pointer;
+ if (r_received <= 0) {
+ r_received = 0;
return OK; //you got 0
}
} else {
- r_received=p_bytes;
+ r_received = p_bytes;
}
PoolVector<uint8_t>::Read r = data.read();
- copymem(p_buffer,r.ptr(),r_received);
-
+ copymem(p_buffer, r.ptr(), r_received);
+
// FIXME: return what? OK or ERR_*
}
int StreamPeerBuffer::get_available_bytes() const {
- return data.size()-pointer;
+ return data.size() - pointer;
}
-void StreamPeerBuffer::seek(int p_pos){
+void StreamPeerBuffer::seek(int p_pos) {
ERR_FAIL_COND(p_pos < 0);
ERR_FAIL_COND(p_pos > data.size());
- pointer=p_pos;
+ pointer = p_pos;
}
-int StreamPeerBuffer::get_size() const{
+int StreamPeerBuffer::get_size() const {
return data.size();
}
@@ -517,40 +484,37 @@ int StreamPeerBuffer::get_pos() const {
return pointer;
}
-void StreamPeerBuffer::resize(int p_size){
+void StreamPeerBuffer::resize(int p_size) {
data.resize(p_size);
}
-void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> & p_data){
+void StreamPeerBuffer::set_data_array(const PoolVector<uint8_t> &p_data) {
- data=p_data;
- pointer=0;
+ data = p_data;
+ pointer = 0;
}
-PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const{
+PoolVector<uint8_t> StreamPeerBuffer::get_data_array() const {
return data;
}
-
void StreamPeerBuffer::clear() {
data.resize(0);
- pointer=0;
+ pointer = 0;
}
-
Ref<StreamPeerBuffer> StreamPeerBuffer::duplicate() const {
Ref<StreamPeerBuffer> spb;
spb.instance();
- spb->data=data;
+ spb->data = data;
return spb;
}
-
StreamPeerBuffer::StreamPeerBuffer() {
- pointer=0;
+ pointer = 0;
}
diff --git a/core/io/stream_peer.h b/core/io/stream_peer.h
index eb0f90ba50..7c20d10b10 100644
--- a/core/io/stream_peer.h
+++ b/core/io/stream_peer.h
@@ -32,14 +32,15 @@
#include "reference.h"
class StreamPeer : public Reference {
- GDCLASS( StreamPeer, Reference );
+ GDCLASS(StreamPeer, Reference);
OBJ_CATEGORY("Networking");
+
protected:
static void _bind_methods();
//bind helpers
- Error _put_data(const PoolVector<uint8_t>& p_data);
- Array _put_partial_data(const PoolVector<uint8_t>& p_data);
+ Error _put_data(const PoolVector<uint8_t> &p_data);
+ Array _put_partial_data(const PoolVector<uint8_t> &p_data);
Array _get_data(int p_bytes);
Array _get_partial_data(int p_bytes);
@@ -47,14 +48,13 @@ protected:
bool big_endian;
public:
+ virtual Error put_data(const uint8_t *p_data, int p_bytes) = 0; ///< put a whole chunk of data, blocking until it sent
+ virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) = 0; ///< put as much data as possible, without blocking.
- virtual Error put_data(const uint8_t* p_data,int p_bytes)=0; ///< put a whole chunk of data, blocking until it sent
- virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent)=0; ///< put as much data as possible, without blocking.
-
- virtual Error get_data(uint8_t* p_buffer, int p_bytes)=0; ///< read p_bytes of data, if p_bytes > available, it will block
- virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received)=0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received
+ virtual Error get_data(uint8_t *p_buffer, int p_bytes) = 0; ///< read p_bytes of data, if p_bytes > available, it will block
+ virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) = 0; ///< read as much data as p_bytes into buffer, if less was read, return in r_received
- virtual int get_available_bytes() const=0;
+ virtual int get_available_bytes() const = 0;
void set_big_endian(bool p_enable);
bool is_big_endian_enabled() const;
@@ -69,8 +69,8 @@ public:
void put_u64(uint64_t p_val);
void put_float(float p_val);
void put_double(double p_val);
- void put_utf8_string(const String& p_string);
- void put_var(const Variant& p_variant);
+ void put_utf8_string(const String &p_string);
+ void put_var(const Variant &p_variant);
uint8_t get_u8();
int8_t get_8();
@@ -86,27 +86,25 @@ public:
String get_utf8_string(int p_bytes);
Variant get_var();
-
-
- StreamPeer() { big_endian=false; }
+ StreamPeer() { big_endian = false; }
};
-
class StreamPeerBuffer : public StreamPeer {
- GDCLASS(StreamPeerBuffer,StreamPeer);
+ GDCLASS(StreamPeerBuffer, StreamPeer);
PoolVector<uint8_t> data;
int pointer;
-protected:
+protected:
static void _bind_methods();
+
public:
- 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 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);
+ Error get_data(uint8_t *p_buffer, int p_bytes);
+ Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received);
virtual int get_available_bytes() const;
@@ -115,8 +113,7 @@ public:
int get_pos() const;
void resize(int p_size);
-
- void set_data_array(const PoolVector<uint8_t> & p_data);
+ void set_data_array(const PoolVector<uint8_t> &p_data);
PoolVector<uint8_t> get_data_array() const;
void clear();
@@ -126,5 +123,4 @@ public:
StreamPeerBuffer();
};
-
#endif // STREAM_PEER_H
diff --git a/core/io/stream_peer_ssl.cpp b/core/io/stream_peer_ssl.cpp
index 5f7247bd7a..6db6eb30ed 100644
--- a/core/io/stream_peer_ssl.cpp
+++ b/core/io/stream_peer_ssl.cpp
@@ -28,24 +28,18 @@
/*************************************************************************/
#include "stream_peer_ssl.h"
-
-StreamPeerSSL* (*StreamPeerSSL::_create)()=NULL;
-
-
-
+StreamPeerSSL *(*StreamPeerSSL::_create)() = NULL;
StreamPeerSSL *StreamPeerSSL::create() {
return _create();
}
+StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func = NULL;
+bool StreamPeerSSL::available = false;
+bool StreamPeerSSL::initialize_certs = true;
-
-StreamPeerSSL::LoadCertsFromMemory StreamPeerSSL::load_certs_func=NULL;
-bool StreamPeerSSL::available=false;
-bool StreamPeerSSL::initialize_certs=true;
-
-void StreamPeerSSL::load_certs_from_memory(const PoolByteArray& p_memory) {
+void StreamPeerSSL::load_certs_from_memory(const PoolByteArray &p_memory) {
if (load_certs_func)
load_certs_func(p_memory);
}
@@ -56,18 +50,15 @@ bool StreamPeerSSL::is_available() {
void StreamPeerSSL::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("accept_stream:Error","stream:StreamPeer"),&StreamPeerSSL::accept_stream);
- ClassDB::bind_method(D_METHOD("connect_to_stream:Error","stream:StreamPeer","validate_certs","for_hostname"),&StreamPeerSSL::connect_to_stream,DEFVAL(false),DEFVAL(String()));
- ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerSSL::get_status);
- ClassDB::bind_method(D_METHOD("disconnect_from_stream"),&StreamPeerSSL::disconnect_from_stream);
- BIND_CONSTANT( STATUS_DISCONNECTED );
- BIND_CONSTANT( STATUS_CONNECTED );
- BIND_CONSTANT( STATUS_ERROR_NO_CERTIFICATE );
- BIND_CONSTANT( STATUS_ERROR_HOSTNAME_MISMATCH );
-
+ ClassDB::bind_method(D_METHOD("accept_stream:Error", "stream:StreamPeer"), &StreamPeerSSL::accept_stream);
+ ClassDB::bind_method(D_METHOD("connect_to_stream:Error", "stream:StreamPeer", "validate_certs", "for_hostname"), &StreamPeerSSL::connect_to_stream, DEFVAL(false), DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerSSL::get_status);
+ ClassDB::bind_method(D_METHOD("disconnect_from_stream"), &StreamPeerSSL::disconnect_from_stream);
+ BIND_CONSTANT(STATUS_DISCONNECTED);
+ BIND_CONSTANT(STATUS_CONNECTED);
+ BIND_CONSTANT(STATUS_ERROR_NO_CERTIFICATE);
+ BIND_CONSTANT(STATUS_ERROR_HOSTNAME_MISMATCH);
}
-StreamPeerSSL::StreamPeerSSL()
-{
+StreamPeerSSL::StreamPeerSSL() {
}
diff --git a/core/io/stream_peer_ssl.h b/core/io/stream_peer_ssl.h
index 9aafac874d..468cef66a2 100644
--- a/core/io/stream_peer_ssl.h
+++ b/core/io/stream_peer_ssl.h
@@ -32,24 +32,22 @@
#include "io/stream_peer.h"
class StreamPeerSSL : public StreamPeer {
- GDCLASS(StreamPeerSSL,StreamPeer);
+ GDCLASS(StreamPeerSSL, StreamPeer);
+
public:
+ typedef void (*LoadCertsFromMemory)(const PoolByteArray &p_certs);
- typedef void (*LoadCertsFromMemory)(const PoolByteArray& p_certs);
protected:
- static StreamPeerSSL* (*_create)();
+ static StreamPeerSSL *(*_create)();
static void _bind_methods();
static LoadCertsFromMemory load_certs_func;
static bool available;
-
-friend class Main;
+ friend class Main;
static bool initialize_certs;
public:
-
-
enum Status {
STATUS_DISCONNECTED,
STATUS_CONNECTED,
@@ -57,20 +55,20 @@ public:
STATUS_ERROR_HOSTNAME_MISMATCH
};
- virtual Error accept_stream(Ref<StreamPeer> p_base)=0;
- virtual Error connect_to_stream(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String())=0;
- virtual Status get_status() const=0;
+ virtual Error accept_stream(Ref<StreamPeer> p_base) = 0;
+ virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String()) = 0;
+ virtual Status get_status() const = 0;
- virtual void disconnect_from_stream()=0;
+ virtual void disconnect_from_stream() = 0;
- static StreamPeerSSL* create();
+ static StreamPeerSSL *create();
- static void load_certs_from_memory(const PoolByteArray& p_memory);
+ static void load_certs_from_memory(const PoolByteArray &p_memory);
static bool is_available();
StreamPeerSSL();
};
-VARIANT_ENUM_CAST( StreamPeerSSL::Status );
+VARIANT_ENUM_CAST(StreamPeerSSL::Status);
#endif // STREAM_PEER_SSL_H
diff --git a/core/io/stream_peer_tcp.cpp b/core/io/stream_peer_tcp.cpp
index cedc33079e..db5952e16f 100644
--- a/core/io/stream_peer_tcp.cpp
+++ b/core/io/stream_peer_tcp.cpp
@@ -28,37 +28,36 @@
/*************************************************************************/
#include "stream_peer_tcp.h"
-StreamPeerTCP* (*StreamPeerTCP::_create)()=NULL;
+StreamPeerTCP *(*StreamPeerTCP::_create)() = NULL;
-Error StreamPeerTCP::_connect(const String& p_address,int p_port) {
+Error StreamPeerTCP::_connect(const String &p_address, int p_port) {
IP_Address ip;
if (p_address.is_valid_ip_address()) {
- ip=p_address;
+ ip = p_address;
} else {
- ip=IP::get_singleton()->resolve_hostname(p_address);
+ ip = IP::get_singleton()->resolve_hostname(p_address);
if (!ip.is_valid())
return ERR_CANT_RESOLVE;
}
- connect_to_host(ip,p_port);
+ connect_to_host(ip, p_port);
return OK;
}
void StreamPeerTCP::_bind_methods() {
- ClassDB::bind_method(D_METHOD("connect_to_host","host","port"),&StreamPeerTCP::_connect);
- ClassDB::bind_method(D_METHOD("is_connected_to_host"),&StreamPeerTCP::is_connected_to_host);
- ClassDB::bind_method(D_METHOD("get_status"),&StreamPeerTCP::get_status);
- ClassDB::bind_method(D_METHOD("get_connected_host"),&StreamPeerTCP::get_connected_host);
- ClassDB::bind_method(D_METHOD("get_connected_port"),&StreamPeerTCP::get_connected_port);
- ClassDB::bind_method(D_METHOD("disconnect_from_host"),&StreamPeerTCP::disconnect_from_host);
-
- BIND_CONSTANT( STATUS_NONE );
- BIND_CONSTANT( STATUS_CONNECTING );
- BIND_CONSTANT( STATUS_CONNECTED );
- BIND_CONSTANT( STATUS_ERROR );
-
+ ClassDB::bind_method(D_METHOD("connect_to_host", "host", "port"), &StreamPeerTCP::_connect);
+ ClassDB::bind_method(D_METHOD("is_connected_to_host"), &StreamPeerTCP::is_connected_to_host);
+ ClassDB::bind_method(D_METHOD("get_status"), &StreamPeerTCP::get_status);
+ ClassDB::bind_method(D_METHOD("get_connected_host"), &StreamPeerTCP::get_connected_host);
+ ClassDB::bind_method(D_METHOD("get_connected_port"), &StreamPeerTCP::get_connected_port);
+ ClassDB::bind_method(D_METHOD("disconnect_from_host"), &StreamPeerTCP::disconnect_from_host);
+
+ BIND_CONSTANT(STATUS_NONE);
+ BIND_CONSTANT(STATUS_CONNECTING);
+ BIND_CONSTANT(STATUS_CONNECTED);
+ BIND_CONSTANT(STATUS_ERROR);
}
Ref<StreamPeerTCP> StreamPeerTCP::create_ref() {
@@ -68,7 +67,7 @@ Ref<StreamPeerTCP> StreamPeerTCP::create_ref() {
return Ref<StreamPeerTCP>(_create());
}
-StreamPeerTCP* StreamPeerTCP::create() {
+StreamPeerTCP *StreamPeerTCP::create() {
if (!_create)
return NULL;
@@ -76,10 +75,8 @@ StreamPeerTCP* StreamPeerTCP::create() {
}
StreamPeerTCP::StreamPeerTCP() {
-
}
-StreamPeerTCP::~StreamPeerTCP() {
+StreamPeerTCP::~StreamPeerTCP(){
};
-
diff --git a/core/io/stream_peer_tcp.h b/core/io/stream_peer_tcp.h
index 4401378743..1733619a1c 100644
--- a/core/io/stream_peer_tcp.h
+++ b/core/io/stream_peer_tcp.h
@@ -31,16 +31,15 @@
#include "stream_peer.h"
-#include "ip_address.h"
#include "io/ip.h"
+#include "ip_address.h"
class StreamPeerTCP : public StreamPeer {
- GDCLASS( StreamPeerTCP, StreamPeer );
+ GDCLASS(StreamPeerTCP, StreamPeer);
OBJ_CATEGORY("Networking");
public:
-
enum Status {
STATUS_NONE,
@@ -50,31 +49,29 @@ public:
};
protected:
-
- virtual Error _connect(const String& p_address, int p_port);
- static StreamPeerTCP* (*_create)();
+ virtual Error _connect(const String &p_address, int p_port);
+ static StreamPeerTCP *(*_create)();
static void _bind_methods();
public:
-
- virtual Error connect_to_host(const IP_Address& p_host, uint16_t p_port)=0;
+ virtual Error connect_to_host(const IP_Address &p_host, uint16_t p_port) = 0;
//read/write from streampeer
- virtual bool is_connected_to_host() const=0;
- virtual Status get_status() const=0;
- virtual void disconnect_from_host()=0;
- virtual IP_Address get_connected_host() const=0;
- virtual uint16_t get_connected_port() const=0;
- virtual void set_nodelay(bool p_enabled)=0;
+ virtual bool is_connected_to_host() const = 0;
+ virtual Status get_status() const = 0;
+ virtual void disconnect_from_host() = 0;
+ virtual IP_Address get_connected_host() const = 0;
+ virtual uint16_t get_connected_port() const = 0;
+ virtual void set_nodelay(bool p_enabled) = 0;
static Ref<StreamPeerTCP> create_ref();
- static StreamPeerTCP* create();
+ static StreamPeerTCP *create();
StreamPeerTCP();
~StreamPeerTCP();
};
-VARIANT_ENUM_CAST( StreamPeerTCP::Status );
+VARIANT_ENUM_CAST(StreamPeerTCP::Status);
#endif
diff --git a/core/io/tcp_server.cpp b/core/io/tcp_server.cpp
index 5127bd6e3b..f602b569ad 100644
--- a/core/io/tcp_server.cpp
+++ b/core/io/tcp_server.cpp
@@ -28,7 +28,7 @@
/*************************************************************************/
#include "tcp_server.h"
-TCP_Server* (*TCP_Server::_create)()=NULL;
+TCP_Server *(*TCP_Server::_create)() = NULL;
Ref<TCP_Server> TCP_Server::create_ref() {
@@ -37,7 +37,7 @@ Ref<TCP_Server> TCP_Server::create_ref() {
return Ref<TCP_Server>(_create());
}
-TCP_Server* TCP_Server::create() {
+TCP_Server *TCP_Server::create() {
if (!_create)
return NULL;
@@ -46,15 +46,11 @@ TCP_Server* TCP_Server::create() {
void TCP_Server::_bind_methods() {
- ClassDB::bind_method(D_METHOD("listen","port","bind_address"),&TCP_Server::listen,DEFVAL("*"));
- ClassDB::bind_method(D_METHOD("is_connection_available"),&TCP_Server::is_connection_available);
- ClassDB::bind_method(D_METHOD("take_connection"),&TCP_Server::take_connection);
- ClassDB::bind_method(D_METHOD("stop"),&TCP_Server::stop);
-
+ ClassDB::bind_method(D_METHOD("listen", "port", "bind_address"), &TCP_Server::listen, DEFVAL("*"));
+ ClassDB::bind_method(D_METHOD("is_connection_available"), &TCP_Server::is_connection_available);
+ ClassDB::bind_method(D_METHOD("take_connection"), &TCP_Server::take_connection);
+ ClassDB::bind_method(D_METHOD("stop"), &TCP_Server::stop);
}
-
-TCP_Server::TCP_Server()
-{
-
+TCP_Server::TCP_Server() {
}
diff --git a/core/io/tcp_server.h b/core/io/tcp_server.h
index 3cbd8c58cf..736aa16f99 100644
--- a/core/io/tcp_server.h
+++ b/core/io/tcp_server.h
@@ -29,29 +29,29 @@
#ifndef TCP_SERVER_H
#define TCP_SERVER_H
-#include "io/stream_peer.h"
#include "io/ip.h"
+#include "io/stream_peer.h"
#include "stream_peer_tcp.h"
class TCP_Server : public Reference {
- GDCLASS( TCP_Server, Reference );
-protected:
+ GDCLASS(TCP_Server, Reference);
- static TCP_Server* (*_create)();
+protected:
+ static TCP_Server *(*_create)();
//bind helper
static void _bind_methods();
-public:
- virtual Error listen(uint16_t p_port, const IP_Address p_bind_address=IP_Address("*"))=0;
- virtual bool is_connection_available() const=0;
- virtual Ref<StreamPeerTCP> take_connection()=0;
+public:
+ virtual Error listen(uint16_t p_port, const IP_Address p_bind_address = IP_Address("*")) = 0;
+ virtual bool is_connection_available() const = 0;
+ virtual Ref<StreamPeerTCP> take_connection() = 0;
- virtual void stop()=0; //stop listening
+ virtual void stop() = 0; //stop listening
static Ref<TCP_Server> create_ref();
- static TCP_Server* create();
+ static TCP_Server *create();
TCP_Server();
};
diff --git a/core/io/translation_loader_po.cpp b/core/io/translation_loader_po.cpp
index bee38e037f..4da661e675 100644
--- a/core/io/translation_loader_po.cpp
+++ b/core/io/translation_loader_po.cpp
@@ -30,7 +30,6 @@
#include "os/file_access.h"
#include "translation.h"
-
RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const String &p_path) {
enum Status {
@@ -40,175 +39,169 @@ RES TranslationLoaderPO::load_translation(FileAccess *f, Error *r_error, const S
STATUS_READING_STRING,
};
- Status status=STATUS_NONE;
+ Status status = STATUS_NONE;
String msg_id;
String msg_str;
String config;
if (r_error)
- *r_error=ERR_FILE_CORRUPT;
+ *r_error = ERR_FILE_CORRUPT;
- Ref<Translation> translation = Ref<Translation>( memnew( Translation ));
+ Ref<Translation> translation = Ref<Translation>(memnew(Translation));
int line = 1;
- while(true) {
+ while (true) {
String l = f->get_line();
if (f->eof_reached()) {
- if ( status == STATUS_READING_STRING) {
+ if (status == STATUS_READING_STRING) {
- if (msg_id!="")
- translation->add_message(msg_id,msg_str);
- else if (config=="")
- config=msg_str;
+ if (msg_id != "")
+ translation->add_message(msg_id, msg_str);
+ else if (config == "")
+ config = msg_str;
break;
- } else if ( status==STATUS_NONE)
+ } else if (status == STATUS_NONE)
break;
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected EOF while reading 'msgid' at file: ");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected EOF while reading 'msgid' at file: ");
ERR_FAIL_V(RES());
}
- l=l.strip_edges();
+ l = l.strip_edges();
if (l.begins_with("msgid")) {
- if (status==STATUS_READING_ID) {
+ if (status == STATUS_READING_ID) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgid', was expecting 'msgstr' while parsing: ");
ERR_FAIL_V(RES());
}
- if (msg_id!="")
- translation->add_message(msg_id,msg_str);
- else if (config=="")
- config=msg_str;
+ if (msg_id != "")
+ translation->add_message(msg_id, msg_str);
+ else if (config == "")
+ config = msg_str;
- l=l.substr(5,l.length()).strip_edges();
- status=STATUS_READING_ID;
- msg_id="";
- msg_str="";
+ l = l.substr(5, l.length()).strip_edges();
+ status = STATUS_READING_ID;
+ msg_id = "";
+ msg_str = "";
}
if (l.begins_with("msgstr")) {
- if (status!=STATUS_READING_ID) {
+ if (status != STATUS_READING_ID) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+" Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + " Unexpected 'msgstr', was expecting 'msgid' while parsing: ");
ERR_FAIL_V(RES());
}
- l=l.substr(6,l.length()).strip_edges();
- status=STATUS_READING_STRING;
+ l = l.substr(6, l.length()).strip_edges();
+ status = STATUS_READING_STRING;
}
- if (l=="" || l.begins_with("#")) {
+ if (l == "" || l.begins_with("#")) {
line++;
continue; //nothing to read or comment
}
- if (!l.begins_with("\"") || status==STATUS_NONE) {
+ if (!l.begins_with("\"") || status == STATUS_NONE) {
//not a string? failure!
- ERR_EXPLAIN(p_path+":"+itos(line)+" Invalid line '"+l+"' while parsing: ");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + " Invalid line '" + l + "' while parsing: ");
ERR_FAIL_V(RES());
-
}
- l=l.substr(1,l.length());
+ l = l.substr(1, l.length());
//find final quote
- int end_pos=-1;
- for(int i=0;i<l.length();i++) {
+ int end_pos = -1;
+ for (int i = 0; i < l.length(); i++) {
- if (l[i]=='"' && (i==0 || l[i-1]!='\\')) {
- end_pos=i;
+ if (l[i] == '"' && (i == 0 || l[i - 1] != '\\')) {
+ end_pos = i;
break;
}
}
- if (end_pos==-1) {
- ERR_EXPLAIN(p_path+":"+itos(line)+" Expected '\"' at end of message while parsing file: ");
+ if (end_pos == -1) {
+ ERR_EXPLAIN(p_path + ":" + itos(line) + " Expected '\"' at end of message while parsing file: ");
ERR_FAIL_V(RES());
}
- l=l.substr(0,end_pos);
- l=l.c_unescape();
-
+ l = l.substr(0, end_pos);
+ l = l.c_unescape();
- if (status==STATUS_READING_ID)
- msg_id+=l;
+ if (status == STATUS_READING_ID)
+ msg_id += l;
else
- msg_str+=l;
+ msg_str += l;
line++;
}
-
f->close();
memdelete(f);
- if (config=="") {
- ERR_EXPLAIN("No config found in file: "+p_path);
+ if (config == "") {
+ ERR_EXPLAIN("No config found in file: " + p_path);
ERR_FAIL_V(RES());
}
Vector<String> configs = config.split("\n");
- for(int i=0;i<configs.size();i++) {
+ for (int i = 0; i < configs.size(); i++) {
String c = configs[i].strip_edges();
int p = c.find(":");
- if (p==-1)
+ if (p == -1)
continue;
- String prop = c.substr(0,p).strip_edges();
- String value = c.substr(p+1,c.length()).strip_edges();
+ String prop = c.substr(0, p).strip_edges();
+ String value = c.substr(p + 1, c.length()).strip_edges();
- if (prop=="X-Language") {
+ if (prop == "X-Language") {
translation->set_locale(value);
}
}
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return translation;
}
-RES TranslationLoaderPO::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES TranslationLoaderPO::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
-
- FileAccess *f=FileAccess::open(p_path,FileAccess::READ);
- ERR_FAIL_COND_V(!f,RES());
-
+ *r_error = ERR_CANT_OPEN;
- return load_translation(f,r_error);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, RES());
+ return load_translation(f, r_error);
}
-void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const{
+void TranslationLoaderPO::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("po");
//p_extensions->push_back("mo"); //mo in the future...
}
-bool TranslationLoaderPO::handles_type(const String& p_type) const{
+bool TranslationLoaderPO::handles_type(const String &p_type) const {
- return (p_type=="Translation");
+ return (p_type == "Translation");
}
String TranslationLoaderPO::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="po")
+ if (p_path.get_extension().to_lower() == "po")
return "Translation";
return "";
}
-TranslationLoaderPO::TranslationLoaderPO()
-{
+TranslationLoaderPO::TranslationLoaderPO() {
}
diff --git a/core/io/translation_loader_po.h b/core/io/translation_loader_po.h
index 127c8dafab..fe0440cb2a 100644
--- a/core/io/translation_loader_po.h
+++ b/core/io/translation_loader_po.h
@@ -30,18 +30,16 @@
#define TRANSLATION_LOADER_PO_H
#include "io/resource_loader.h"
-#include "translation.h"
#include "os/file_access.h"
+#include "translation.h"
class TranslationLoaderPO : public ResourceFormatLoader {
public:
-
- static RES load_translation(FileAccess *f, Error *r_error,const String& p_path=String());
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ static RES load_translation(FileAccess *f, Error *r_error, const String &p_path = String());
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
TranslationLoaderPO();
};
diff --git a/core/io/xml_parser.cpp b/core/io/xml_parser.cpp
index 1a4ff1a8d4..e3b669409a 100644
--- a/core/io/xml_parser.cpp
+++ b/core/io/xml_parser.cpp
@@ -32,19 +32,18 @@
VARIANT_ENUM_CAST(XMLParser::NodeType);
-static bool _equalsn(const CharType* str1, const CharType* str2, int len) {
+static bool _equalsn(const CharType *str1, const CharType *str2, int len) {
int i;
- for(i=0; i < len && str1[i] && str2[i] ; ++i)
- if (str1[i] != str2[i])
- return false;
+ for (i = 0; i < len && str1[i] && str2[i]; ++i)
+ if (str1[i] != str2[i])
+ return false;
// if one (or both) of the strings was smaller then they
// are only equal if they have the same lenght
return (i == len) || (str1[i] == 0 && str2[i] == 0);
}
-
-String XMLParser::_replace_special_characters(const String& origstr) {
+String XMLParser::_replace_special_characters(const String &origstr) {
int pos = origstr.find("&");
int oldPos = 0;
@@ -54,30 +53,25 @@ String XMLParser::_replace_special_characters(const String& origstr) {
String newstr;
- while(pos != -1 && pos < origstr.length()-2) {
+ while (pos != -1 && pos < origstr.length() - 2) {
// check if it is one of the special characters
int specialChar = -1;
- for (int i=0; i<(int)special_characters.size(); ++i)
- {
- const CharType* p = &origstr[pos]+1;
+ for (int i = 0; i < (int)special_characters.size(); ++i) {
+ const CharType *p = &origstr[pos] + 1;
- if (_equalsn(&special_characters[i][1], p, special_characters[i].length()-1))
- {
+ if (_equalsn(&special_characters[i][1], p, special_characters[i].length() - 1)) {
specialChar = i;
break;
}
}
- if (specialChar != -1)
- {
- newstr+=(origstr.substr(oldPos, pos - oldPos));
- newstr+=(special_characters[specialChar][0]);
+ if (specialChar != -1) {
+ newstr += (origstr.substr(oldPos, pos - oldPos));
+ newstr += (special_characters[specialChar][0]);
pos += special_characters[specialChar].length();
- }
- else
- {
- newstr+=(origstr.substr(oldPos, pos - oldPos + 1));
+ } else {
+ newstr += (origstr.substr(oldPos, pos - oldPos + 1));
pos += 1;
}
@@ -86,27 +80,23 @@ String XMLParser::_replace_special_characters(const String& origstr) {
pos = origstr.find("&", pos);
}
- if (oldPos < origstr.length()-1)
- newstr+=(origstr.substr(oldPos, origstr.length()-oldPos));
+ if (oldPos < origstr.length() - 1)
+ newstr += (origstr.substr(oldPos, origstr.length() - oldPos));
return newstr;
}
-
-static inline bool _is_white_space(char c)
-{
- return (c==' ' || c=='\t' || c=='\n' || c=='\r');
+static inline bool _is_white_space(char c) {
+ return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
}
-
//! sets the state that text was found. Returns true if set should be set
-bool XMLParser::_set_text(char* start, char* end) {
+bool XMLParser::_set_text(char *start, char *end) {
// check if text is more than 2 characters, and if not, check if there is
// only white space, so that this text won't be reported
- if (end - start < 3)
- {
- char* p = start;
- for(; p != end; ++p)
+ if (end - start < 3) {
+ char *p = start;
+ for (; p != end; ++p)
if (!_is_white_space(*p))
break;
@@ -130,14 +120,14 @@ void XMLParser::_parse_closing_xml_element() {
attributes.clear();
++P;
- const char* pBeginClose = P;
+ const char *pBeginClose = P;
- while(*P != '>')
+ while (*P != '>')
++P;
node_name = String::utf8(pBeginClose, (int)(P - pBeginClose));
#ifdef DEBUG_XML
- print_line("XML CLOSE: "+node_name);
+ print_line("XML CLOSE: " + node_name);
#endif
++P;
}
@@ -145,25 +135,24 @@ void XMLParser::_parse_closing_xml_element() {
void XMLParser::_ignore_definition() {
node_type = NODE_UNKNOWN;
- char *F=P;
+ char *F = P;
// move until end marked with '>' reached
- while(*P != '>')
+ while (*P != '>')
++P;
- node_name.parse_utf8(F,P-F);
+ node_name.parse_utf8(F, P - F);
++P;
}
bool XMLParser::_parse_cdata() {
- if (*(P+1) != '[')
+ if (*(P + 1) != '[')
return false;
node_type = NODE_CDATA;
// skip '<![CDATA['
- int count=0;
- while( *P && count<8 )
- {
+ int count = 0;
+ while (*P && count < 8) {
++P;
++count;
}
@@ -175,23 +164,22 @@ bool XMLParser::_parse_cdata() {
char *cDataEnd = 0;
// find end of CDATA
- while(*P && !cDataEnd) {
+ while (*P && !cDataEnd) {
if (*P == '>' &&
- (*(P-1) == ']') &&
- (*(P-2) == ']'))
- {
+ (*(P - 1) == ']') &&
+ (*(P - 2) == ']')) {
cDataEnd = P - 2;
}
++P;
}
- if ( cDataEnd )
+ if (cDataEnd)
node_name = String::utf8(cDataBegin, (int)(cDataEnd - cDataBegin));
else
node_name = "";
#ifdef DEBUG_XML
- print_line("XML CDATA: "+node_name);
+ print_line("XML CDATA: " + node_name);
#endif
return true;
@@ -207,24 +195,21 @@ void XMLParser::_parse_comment() {
int count = 1;
// move until end of comment reached
- while(count)
- {
+ while (count) {
if (*P == '>')
--count;
- else
- if (*P == '<')
+ else if (*P == '<')
++count;
++P;
}
P -= 3;
- node_name = String::utf8(pCommentBegin+2, (int)(P - pCommentBegin-2));
+ node_name = String::utf8(pCommentBegin + 2, (int)(P - pCommentBegin - 2));
P += 3;
#ifdef DEBUG_XML
- print_line("XML COMMENT: "+node_name);
+ print_line("XML COMMENT: " + node_name);
#endif
-
}
void XMLParser::_parse_opening_xml_element() {
@@ -234,37 +219,34 @@ void XMLParser::_parse_opening_xml_element() {
attributes.clear();
// find name
- const char* startName = P;
+ const char *startName = P;
// find end of element
- while(*P != '>' && !_is_white_space(*P))
+ while (*P != '>' && !_is_white_space(*P))
++P;
- const char* endName = P;
+ const char *endName = P;
// find attributes
- while(*P != '>')
- {
+ while (*P != '>') {
if (_is_white_space(*P))
++P;
- else
- {
- if (*P != '/')
- {
+ else {
+ if (*P != '/') {
// we've got an attribute
// read the attribute names
- const char* attributeNameBegin = P;
+ const char *attributeNameBegin = P;
- while(!_is_white_space(*P) && *P != '=')
+ while (!_is_white_space(*P) && *P != '=')
++P;
- const char* attributeNameEnd = P;
+ const char *attributeNameEnd = P;
++P;
// read the attribute value
// check for quotes and single quotes, thx to murphy
- while( (*P != '\"') && (*P != '\'') && *P)
+ while ((*P != '\"') && (*P != '\'') && *P)
++P;
if (!*P) // malformatted xml file
@@ -273,29 +255,27 @@ void XMLParser::_parse_opening_xml_element() {
const char attributeQuoteChar = *P;
++P;
- const char* attributeValueBegin = P;
+ const char *attributeValueBegin = P;
- while(*P != attributeQuoteChar && *P)
+ while (*P != attributeQuoteChar && *P)
++P;
if (!*P) // malformatted xml file
return;
- const char* attributeValueEnd = P;
+ const char *attributeValueEnd = P;
++P;
Attribute attr;
attr.name = String::utf8(attributeNameBegin,
- (int)(attributeNameEnd - attributeNameBegin));
+ (int)(attributeNameEnd - attributeNameBegin));
- String s =String::utf8(attributeValueBegin,
- (int)(attributeValueEnd - attributeValueBegin));
+ String s = String::utf8(attributeValueBegin,
+ (int)(attributeValueEnd - attributeValueBegin));
attr.value = _replace_special_characters(s);
attributes.push_back(attr);
- }
- else
- {
+ } else {
// tag is closed directly
++P;
node_empty = true;
@@ -305,8 +285,7 @@ void XMLParser::_parse_opening_xml_element() {
}
// check if this tag is closing directly
- if (endName > startName && *(endName-1) == '/')
- {
+ if (endName > startName && *(endName - 1) == '/') {
// directly closing tag
node_empty = true;
endName--;
@@ -314,27 +293,25 @@ void XMLParser::_parse_opening_xml_element() {
node_name = String::utf8(startName, (int)(endName - startName));
#ifdef DEBUG_XML
- print_line("XML OPEN: "+node_name);
+ print_line("XML OPEN: " + node_name);
#endif
++P;
}
-
void XMLParser::_parse_current_node() {
- char* start = P;
+ char *start = P;
node_offset = P - data;
// more forward until '<' found
- while(*P != '<' && *P)
+ while (*P != '<' && *P)
++P;
if (!*P)
return;
- if (P - start > 0)
- {
+ if (P - start > 0) {
// we found some text, store it
if (_set_text(start, P))
return;
@@ -343,25 +320,23 @@ void XMLParser::_parse_current_node() {
++P;
// based on current token, parse and report next element
- switch(*P)
- {
- case '/':
- _parse_closing_xml_element();
- break;
- case '?':
- _ignore_definition();
- break;
- case '!':
- if (!_parse_cdata())
- _parse_comment();
- break;
- default:
- _parse_opening_xml_element();
- break;
+ switch (*P) {
+ case '/':
+ _parse_closing_xml_element();
+ break;
+ case '?':
+ _ignore_definition();
+ break;
+ case '!':
+ if (!_parse_cdata())
+ _parse_comment();
+ break;
+ default:
+ _parse_opening_xml_element();
+ break;
}
}
-
uint64_t XMLParser::get_node_offset() const {
return node_offset;
@@ -379,41 +354,37 @@ Error XMLParser::seek(uint64_t p_pos) {
void XMLParser::_bind_methods() {
- ClassDB::bind_method(D_METHOD("read"),&XMLParser::read);
- ClassDB::bind_method(D_METHOD("get_node_type"),&XMLParser::get_node_type);
- ClassDB::bind_method(D_METHOD("get_node_name"),&XMLParser::get_node_name);
- ClassDB::bind_method(D_METHOD("get_node_data"),&XMLParser::get_node_data);
- ClassDB::bind_method(D_METHOD("get_node_offset"),&XMLParser::get_node_offset);
- ClassDB::bind_method(D_METHOD("get_attribute_count"),&XMLParser::get_attribute_count);
- ClassDB::bind_method(D_METHOD("get_attribute_name","idx"),&XMLParser::get_attribute_name);
- ClassDB::bind_method(D_METHOD("get_attribute_value","idx"),(String (XMLParser::*)(int) const) &XMLParser::get_attribute_value);
- ClassDB::bind_method(D_METHOD("has_attribute","name"),&XMLParser::has_attribute);
- ClassDB::bind_method(D_METHOD("get_named_attribute_value","name"), (String (XMLParser::*)(const String&) const) &XMLParser::get_attribute_value);
- ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe","name"), &XMLParser::get_attribute_value_safe);
- ClassDB::bind_method(D_METHOD("is_empty"),&XMLParser::is_empty);
- ClassDB::bind_method(D_METHOD("get_current_line"),&XMLParser::get_current_line);
- ClassDB::bind_method(D_METHOD("skip_section"),&XMLParser::skip_section);
- ClassDB::bind_method(D_METHOD("seek","pos"),&XMLParser::seek);
- ClassDB::bind_method(D_METHOD("open","file"),&XMLParser::open);
- ClassDB::bind_method(D_METHOD("open_buffer","buffer"),&XMLParser::open_buffer);
-
- BIND_CONSTANT( NODE_NONE );
- BIND_CONSTANT( NODE_ELEMENT );
- BIND_CONSTANT( NODE_ELEMENT_END );
- BIND_CONSTANT( NODE_TEXT );
- BIND_CONSTANT( NODE_COMMENT );
- BIND_CONSTANT( NODE_CDATA );
- BIND_CONSTANT( NODE_UNKNOWN );
-
+ ClassDB::bind_method(D_METHOD("read"), &XMLParser::read);
+ ClassDB::bind_method(D_METHOD("get_node_type"), &XMLParser::get_node_type);
+ ClassDB::bind_method(D_METHOD("get_node_name"), &XMLParser::get_node_name);
+ ClassDB::bind_method(D_METHOD("get_node_data"), &XMLParser::get_node_data);
+ ClassDB::bind_method(D_METHOD("get_node_offset"), &XMLParser::get_node_offset);
+ ClassDB::bind_method(D_METHOD("get_attribute_count"), &XMLParser::get_attribute_count);
+ ClassDB::bind_method(D_METHOD("get_attribute_name", "idx"), &XMLParser::get_attribute_name);
+ ClassDB::bind_method(D_METHOD("get_attribute_value", "idx"), (String(XMLParser::*)(int) const) & XMLParser::get_attribute_value);
+ ClassDB::bind_method(D_METHOD("has_attribute", "name"), &XMLParser::has_attribute);
+ ClassDB::bind_method(D_METHOD("get_named_attribute_value", "name"), (String(XMLParser::*)(const String &) const) & XMLParser::get_attribute_value);
+ ClassDB::bind_method(D_METHOD("get_named_attribute_value_safe", "name"), &XMLParser::get_attribute_value_safe);
+ ClassDB::bind_method(D_METHOD("is_empty"), &XMLParser::is_empty);
+ ClassDB::bind_method(D_METHOD("get_current_line"), &XMLParser::get_current_line);
+ ClassDB::bind_method(D_METHOD("skip_section"), &XMLParser::skip_section);
+ ClassDB::bind_method(D_METHOD("seek", "pos"), &XMLParser::seek);
+ ClassDB::bind_method(D_METHOD("open", "file"), &XMLParser::open);
+ ClassDB::bind_method(D_METHOD("open_buffer", "buffer"), &XMLParser::open_buffer);
+
+ BIND_CONSTANT(NODE_NONE);
+ BIND_CONSTANT(NODE_ELEMENT);
+ BIND_CONSTANT(NODE_ELEMENT_END);
+ BIND_CONSTANT(NODE_TEXT);
+ BIND_CONSTANT(NODE_COMMENT);
+ BIND_CONSTANT(NODE_CDATA);
+ BIND_CONSTANT(NODE_UNKNOWN);
};
-
-
Error XMLParser::read() {
// if not end reached, parse the node
- if (P && (P - data) < length - 1 && *P != 0)
- {
+ if (P && (P - data) < length - 1 && *P != 0) {
_parse_current_node();
return OK;
}
@@ -427,12 +398,12 @@ XMLParser::NodeType XMLParser::get_node_type() {
}
String XMLParser::get_node_data() const {
- ERR_FAIL_COND_V( node_type != NODE_TEXT, "");
+ ERR_FAIL_COND_V(node_type != NODE_TEXT, "");
return node_name;
}
String XMLParser::get_node_name() const {
- ERR_FAIL_COND_V( node_type == NODE_TEXT, "");
+ ERR_FAIL_COND_V(node_type == NODE_TEXT, "");
return node_name;
}
int XMLParser::get_attribute_count() const {
@@ -441,95 +412,91 @@ int XMLParser::get_attribute_count() const {
}
String XMLParser::get_attribute_name(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,attributes.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
return attributes[p_idx].name;
}
String XMLParser::get_attribute_value(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,attributes.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, attributes.size(), "");
return attributes[p_idx].value;
}
-bool XMLParser::has_attribute(const String& p_name) const {
+bool XMLParser::has_attribute(const String &p_name) const {
- for(int i=0;i<attributes.size();i++) {
- if (attributes[i].name==p_name)
+ for (int i = 0; i < attributes.size(); i++) {
+ if (attributes[i].name == p_name)
return true;
}
return false;
}
-String XMLParser::get_attribute_value(const String& p_name) const {
+String XMLParser::get_attribute_value(const String &p_name) const {
- int idx=-1;
- for(int i=0;i<attributes.size();i++) {
- if (attributes[i].name==p_name) {
- idx=i;
+ int idx = -1;
+ for (int i = 0; i < attributes.size(); i++) {
+ if (attributes[i].name == p_name) {
+ idx = i;
break;
}
}
- if (idx<0) {
- ERR_EXPLAIN("Attribute not found: "+p_name);
+ if (idx < 0) {
+ ERR_EXPLAIN("Attribute not found: " + p_name);
}
- ERR_FAIL_COND_V(idx<0,"");
+ ERR_FAIL_COND_V(idx < 0, "");
return attributes[idx].value;
-
}
-String XMLParser::get_attribute_value_safe(const String& p_name) const {
+String XMLParser::get_attribute_value_safe(const String &p_name) const {
- int idx=-1;
- for(int i=0;i<attributes.size();i++) {
- if (attributes[i].name==p_name) {
- idx=i;
+ int idx = -1;
+ for (int i = 0; i < attributes.size(); i++) {
+ if (attributes[i].name == p_name) {
+ idx = i;
break;
}
}
- if (idx<0)
+ if (idx < 0)
return "";
return attributes[idx].value;
-
}
bool XMLParser::is_empty() const {
return node_empty;
}
-Error XMLParser::open_buffer(const Vector<uint8_t>& p_buffer) {
+Error XMLParser::open_buffer(const Vector<uint8_t> &p_buffer) {
- ERR_FAIL_COND_V(p_buffer.size()==0,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_buffer.size() == 0, ERR_INVALID_DATA);
length = p_buffer.size();
- data = memnew_arr( char, length+1);
- copymem(data,p_buffer.ptr(),length);
- data[length]=0;
- P=data;
+ data = memnew_arr(char, length + 1);
+ copymem(data, p_buffer.ptr(), length);
+ data[length] = 0;
+ P = data;
return OK;
-
}
-Error XMLParser::open(const String& p_path) {
+Error XMLParser::open(const String &p_path) {
Error err;
- FileAccess * file = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *file = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V(err!=OK,err);
+ ERR_FAIL_COND_V(err != OK, err);
}
length = file->get_len();
- ERR_FAIL_COND_V(length<1, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(length < 1, ERR_FILE_CORRUPT);
- data = memnew_arr( char, length+1);
- file->get_buffer((uint8_t*)data,length);
- data[length]=0;
- P=data;
+ data = memnew_arr(char, length + 1);
+ file->get_buffer((uint8_t *)data, length);
+ data[length] = 0;
+ P = data;
memdelete(file);
return OK;
-
}
void XMLParser::skip_section() {
@@ -541,29 +508,24 @@ void XMLParser::skip_section() {
// read until we've reached the last element in this section
int tagcount = 1;
- while(tagcount && read()==OK)
- {
+ while (tagcount && read() == OK) {
if (get_node_type() == XMLParser::NODE_ELEMENT &&
- !is_empty())
- {
+ !is_empty()) {
++tagcount;
- }
- else
- if (get_node_type() == XMLParser::NODE_ELEMENT_END)
+ } else if (get_node_type() == XMLParser::NODE_ELEMENT_END)
--tagcount;
}
-
}
void XMLParser::close() {
if (data)
memdelete_arr(data);
- data=NULL;
- length=0;
- P=NULL;
- node_empty=false;
- node_type=NODE_NONE;
+ data = NULL;
+ length = 0;
+ P = NULL;
+ node_empty = false;
+ node_type = NODE_NONE;
node_offset = 0;
}
@@ -574,19 +536,16 @@ int XMLParser::get_current_line() const {
XMLParser::XMLParser() {
- data=NULL;
+ data = NULL;
close();
special_characters.push_back("&amp;");
special_characters.push_back("<lt;");
special_characters.push_back(">gt;");
special_characters.push_back("\"quot;");
special_characters.push_back("'apos;");
-
-
}
XMLParser::~XMLParser() {
-
if (data)
memdelete_arr(data);
}
diff --git a/core/io/xml_parser.h b/core/io/xml_parser.h
index 7f80751156..631d77a41e 100644
--- a/core/io/xml_parser.h
+++ b/core/io/xml_parser.h
@@ -29,10 +29,10 @@
#ifndef XML_PARSER_H
#define XML_PARSER_H
-#include "ustring.h"
-#include "vector.h"
#include "os/file_access.h"
#include "reference.h"
+#include "ustring.h"
+#include "vector.h"
/*
Based on irrXML (see their zlib license). Added mainly for compatibility with their Collada loader.
@@ -40,7 +40,8 @@
class XMLParser : public Reference {
- GDCLASS( XMLParser, Reference );
+ GDCLASS(XMLParser, Reference);
+
public:
//! Enumeration of all supported source text file formats
enum SourceFormat {
@@ -63,11 +64,10 @@ public:
};
private:
-
char *data;
char *P;
int length;
- void unescape(String& p_str);
+ void unescape(String &p_str);
Vector<String> special_characters;
String node_name;
bool node_empty;
@@ -81,8 +81,8 @@ private:
Vector<Attribute> attributes;
- String _replace_special_characters(const String& origstr);
- bool _set_text(char* start, char* end);
+ String _replace_special_characters(const String &origstr);
+ bool _set_text(char *start, char *end);
void _parse_closing_xml_element();
void _ignore_definition();
bool _parse_cdata();
@@ -93,8 +93,6 @@ private:
static void _bind_methods();
public:
-
-
Error read();
NodeType get_node_type();
String get_node_name() const;
@@ -103,17 +101,17 @@ public:
int get_attribute_count() const;
String get_attribute_name(int p_idx) const;
String get_attribute_value(int p_idx) const;
- bool has_attribute(const String& p_name) const;
- String get_attribute_value(const String& p_name) const;
- String get_attribute_value_safe(const String& p_name) const; // do not print error if doesn't exist
+ bool has_attribute(const String &p_name) const;
+ String get_attribute_value(const String &p_name) const;
+ String get_attribute_value_safe(const String &p_name) const; // do not print error if doesn't exist
bool is_empty() const;
int get_current_line() const;
void skip_section();
Error seek(uint64_t p_pos);
- Error open(const String& p_path);
- Error open_buffer(const Vector<uint8_t>& p_buffer);
+ Error open(const String &p_path);
+ Error open_buffer(const Vector<uint8_t> &p_buffer);
void close();
@@ -122,4 +120,3 @@ public:
};
#endif
-
diff --git a/core/io/zip_io.h b/core/io/zip_io.h
index c994593518..4da9fc9c8d 100644
--- a/core/io/zip_io.h
+++ b/core/io/zip_io.h
@@ -29,69 +29,65 @@
#ifndef ZIP_IO_H
#define ZIP_IO_H
-#include "io/zip.h"
#include "io/unzip.h"
-#include "os/file_access.h"
+#include "io/zip.h"
#include "os/copymem.h"
+#include "os/file_access.h"
+static void *zipio_open(void *data, const char *p_fname, int mode) {
-static void* zipio_open(void* data, const char* p_fname, int mode) {
-
- FileAccess *&f = *(FileAccess**)data;
+ FileAccess *&f = *(FileAccess **)data;
String fname;
fname.parse_utf8(p_fname);
if (mode & ZLIB_FILEFUNC_MODE_WRITE) {
- f = FileAccess::open(fname,FileAccess::WRITE);
+ f = FileAccess::open(fname, FileAccess::WRITE);
} else {
- f = FileAccess::open(fname,FileAccess::READ);
+ f = FileAccess::open(fname, FileAccess::READ);
}
if (!f)
return NULL;
return data;
-
};
-static uLong zipio_read(void* data, void* fdata, void* buf, uLong size) {
-
- FileAccess* f = *(FileAccess**)data;
- return f->get_buffer((uint8_t*)buf, size);
+static uLong zipio_read(void *data, void *fdata, void *buf, uLong size) {
+ FileAccess *f = *(FileAccess **)data;
+ return f->get_buffer((uint8_t *)buf, size);
};
-static uLong zipio_write(voidpf opaque, voidpf stream, const void* buf, uLong size) {
+static uLong zipio_write(voidpf opaque, voidpf stream, const void *buf, uLong size) {
- FileAccess* f = *(FileAccess**)opaque;
- f->store_buffer((uint8_t*)buf, size);
+ FileAccess *f = *(FileAccess **)opaque;
+ f->store_buffer((uint8_t *)buf, size);
return size;
};
+static long zipio_tell(voidpf opaque, voidpf stream) {
-static long zipio_tell (voidpf opaque, voidpf stream) {
-
- FileAccess* f = *(FileAccess**)opaque;
+ FileAccess *f = *(FileAccess **)opaque;
return f->get_pos();
};
static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) {
- FileAccess* f = *(FileAccess**)opaque;
+ FileAccess *f = *(FileAccess **)opaque;
int pos = offset;
switch (origin) {
- case ZLIB_FILEFUNC_SEEK_CUR:
- pos = f->get_pos() + offset;
- break;
- case ZLIB_FILEFUNC_SEEK_END:
- pos = f->get_len() + offset;
- break;
- default:
- break;
+ case ZLIB_FILEFUNC_SEEK_CUR:
+ pos = f->get_pos() + offset;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END:
+ pos = f->get_len() + offset;
+ break;
+ default:
+ break;
};
f->seek(pos);
@@ -100,36 +96,32 @@ static long zipio_seek(voidpf opaque, voidpf stream, uLong offset, int origin) {
static int zipio_close(voidpf opaque, voidpf stream) {
- FileAccess*& f = *(FileAccess**)opaque;
+ FileAccess *&f = *(FileAccess **)opaque;
if (f) {
f->close();
- f=NULL;
+ f = NULL;
}
return 0;
};
static int zipio_testerror(voidpf opaque, voidpf stream) {
- FileAccess* f = *(FileAccess**)opaque;
- return (f && f->get_error()!=OK)?1:0;
+ FileAccess *f = *(FileAccess **)opaque;
+ return (f && f->get_error() != OK) ? 1 : 0;
};
-
-
static voidpf zipio_alloc(voidpf opaque, uInt items, uInt size) {
- voidpf ptr =memalloc(items*size);
- zeromem(ptr,items*size);
+ voidpf ptr = memalloc(items * size);
+ zeromem(ptr, items * size);
return ptr;
}
-
static void zipio_free(voidpf opaque, voidpf address) {
memfree(address);
}
-
static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) {
zlib_filefunc_def io;
@@ -141,11 +133,9 @@ static zlib_filefunc_def zipio_create_io_from_file(FileAccess **p_file) {
io.zseek_file = zipio_seek;
io.zclose_file = zipio_close;
io.zerror_file = zipio_testerror;
- io.alloc_mem=zipio_alloc;
- io.free_mem=zipio_free;
+ io.alloc_mem = zipio_alloc;
+ io.free_mem = zipio_free;
return io;
}
-
-
#endif // ZIP_IO_H
diff --git a/core/list.h b/core/list.h
index c464af7475..6924580380 100644
--- a/core/list.h
+++ b/core/list.h
@@ -40,34 +40,33 @@
* from the iterator.
*/
-template <class T,class A=DefaultAllocator>
+template <class T, class A = DefaultAllocator>
class List {
struct _Data;
-public:
-
+public:
class Element {
private:
- friend class List<T,A>;
+ friend class List<T, A>;
T value;
- Element* next_ptr;
- Element* prev_ptr;
+ Element *next_ptr;
+ Element *prev_ptr;
_Data *data;
- public:
+ public:
/**
* Get NEXT Element iterator, for constant lists.
*/
- _FORCE_INLINE_ const Element* next() const {
+ _FORCE_INLINE_ const Element *next() const {
return next_ptr;
};
/**
* Get NEXT Element iterator,
*/
- _FORCE_INLINE_ Element* next() {
+ _FORCE_INLINE_ Element *next() {
return next_ptr;
};
@@ -75,14 +74,14 @@ public:
/**
* Get PREV Element iterator, for constant lists.
*/
- _FORCE_INLINE_ const Element* prev() const {
+ _FORCE_INLINE_ const Element *prev() const {
return prev_ptr;
};
/**
* Get PREV Element iterator,
*/
- _FORCE_INLINE_ Element* prev() {
+ _FORCE_INLINE_ Element *prev() {
return prev_ptr;
};
@@ -90,47 +89,47 @@ public:
/**
* * operator, for using as *iterator, when iterators are defined on stack.
*/
- _FORCE_INLINE_ const T& operator *() const {
+ _FORCE_INLINE_ const T &operator*() const {
return value;
};
/**
* operator->, for using as iterator->, when iterators are defined on stack, for constant lists.
*/
- _FORCE_INLINE_ const T* operator->() const {
+ _FORCE_INLINE_ const T *operator->() const {
return &value;
};
/**
* * operator, for using as *iterator, when iterators are defined on stack,
*/
- _FORCE_INLINE_ T& operator *() {
+ _FORCE_INLINE_ T &operator*() {
return value;
};
/**
* operator->, for using as iterator->, when iterators are defined on stack, for constant lists.
*/
- _FORCE_INLINE_ T* operator->() {
+ _FORCE_INLINE_ T *operator->() {
return &value;
};
/**
* get the value stored in this element.
*/
- _FORCE_INLINE_ T& get() {
+ _FORCE_INLINE_ T &get() {
return value;
};
/**
* get the value stored in this element, for constant lists
*/
- _FORCE_INLINE_ const T& get() const {
+ _FORCE_INLINE_ const T &get() const {
return value;
};
/**
* set the value stored in this element.
*/
- _FORCE_INLINE_ void set(const T& p_value) {
- value = (T&)p_value;
- };
+ _FORCE_INLINE_ void set(const T &p_value) {
+ value = (T &)p_value;
+ };
void erase() {
@@ -140,38 +139,36 @@ public:
_FORCE_INLINE_ Element() {
next_ptr = 0;
prev_ptr = 0;
- data=NULL;
+ data = NULL;
};
};
private:
-
struct _Data {
- Element* first;
- Element* last;
+ Element *first;
+ Element *last;
int size_cache;
+ bool erase(const Element *p_I) {
- bool erase(const Element* p_I) {
+ ERR_FAIL_COND_V(!p_I, false);
+ ERR_FAIL_COND_V(p_I->data != this, false);
- ERR_FAIL_COND_V(!p_I,false);
- ERR_FAIL_COND_V(p_I->data!=this,false);
-
- if (first==p_I) {
- first=p_I->next_ptr;
+ if (first == p_I) {
+ first = p_I->next_ptr;
};
- if (last==p_I)
- last=p_I->prev_ptr;
+ if (last == p_I)
+ last = p_I->prev_ptr;
if (p_I->prev_ptr)
- p_I->prev_ptr->next_ptr=p_I->next_ptr;
+ p_I->prev_ptr->next_ptr = p_I->next_ptr;
if (p_I->next_ptr)
- p_I->next_ptr->prev_ptr=p_I->prev_ptr;
+ p_I->next_ptr->prev_ptr = p_I->prev_ptr;
- memdelete_allocator<Element,A>( const_cast<Element*>(p_I) );
+ memdelete_allocator<Element, A>(const_cast<Element *>(p_I));
size_cache--;
return true;
@@ -180,69 +177,67 @@ private:
_Data *_data;
-
public:
-
/**
* return an const iterator to the begining of the list.
*/
- _FORCE_INLINE_ const Element* front() const {
+ _FORCE_INLINE_ const Element *front() const {
- return _data?_data->first:0;
+ return _data ? _data->first : 0;
};
/**
* return an iterator to the begining of the list.
*/
- _FORCE_INLINE_ Element* front() {
- return _data?_data->first:0;
+ _FORCE_INLINE_ Element *front() {
+ return _data ? _data->first : 0;
};
/**
* return an const iterator to the last member of the list.
*/
- _FORCE_INLINE_ const Element* back() const {
+ _FORCE_INLINE_ const Element *back() const {
- return _data?_data->last:0;
+ return _data ? _data->last : 0;
};
/**
* return an iterator to the last member of the list.
*/
- _FORCE_INLINE_ Element* back() {
+ _FORCE_INLINE_ Element *back() {
- return _data?_data->last:0;
+ return _data ? _data->last : 0;
};
/**
* store a new element at the end of the list
*/
- Element* push_back(const T& value) {
+ Element *push_back(const T &value) {
if (!_data) {
- _data=memnew_allocator(_Data,A);
- _data->first=NULL;
- _data->last=NULL;
- _data->size_cache=0;
+ _data = memnew_allocator(_Data, A);
+ _data->first = NULL;
+ _data->last = NULL;
+ _data->size_cache = 0;
}
- Element* n = memnew_allocator(Element,A);
- n->value = (T&)value;
+ Element *n = memnew_allocator(Element, A);
+ n->value = (T &)value;
- n->prev_ptr=_data->last;
- n->next_ptr=0;
- n->data=_data;
+ n->prev_ptr = _data->last;
+ n->next_ptr = 0;
+ n->data = _data;
if (_data->last) {
- _data->last->next_ptr=n;
+ _data->last->next_ptr = n;
}
_data->last = n;
if (!_data->first)
- _data->first=n;
+ _data->first = n;
_data->size_cache++;
@@ -258,31 +253,31 @@ public:
/**
* store a new element at the begining of the list
*/
- Element* push_front(const T& value) {
+ Element *push_front(const T &value) {
if (!_data) {
- _data=memnew_allocator(_Data,A);
- _data->first=NULL;
- _data->last=NULL;
- _data->size_cache=0;
+ _data = memnew_allocator(_Data, A);
+ _data->first = NULL;
+ _data->last = NULL;
+ _data->size_cache = 0;
}
- Element* n = memnew_allocator(Element,A);
- n->value = (T&)value;
+ Element *n = memnew_allocator(Element, A);
+ n->value = (T &)value;
n->prev_ptr = 0;
n->next_ptr = _data->first;
- n->data=_data;
+ n->data = _data;
if (_data->first) {
- _data->first->prev_ptr=n;
+ _data->first->prev_ptr = n;
}
_data->first = n;
if (!_data->last)
- _data->last=n;
+ _data->last = n;
_data->size_cache++;
@@ -298,10 +293,10 @@ public:
/**
* find an element in the list,
*/
- template<class T_v>
- Element* find(const T_v& p_val) {
+ template <class T_v>
+ Element *find(const T_v &p_val) {
- Element* it = front();
+ Element *it = front();
while (it) {
if (it->value == p_val) return it;
it = it->next();
@@ -313,14 +308,14 @@ public:
/**
* erase an element in the list, by iterator pointing to it. Return true if it was found/erased.
*/
- bool erase(const Element* p_I) {
+ bool erase(const Element *p_I) {
if (_data) {
- bool ret = _data->erase(p_I);
+ bool ret = _data->erase(p_I);
- if (_data->size_cache==0) {
- memdelete_allocator<_Data,A>(_data);
- _data=NULL;
+ if (_data->size_cache == 0) {
+ memdelete_allocator<_Data, A>(_data);
+ _data = NULL;
}
return ret;
@@ -332,9 +327,9 @@ public:
/**
* erase the first element in the list, that contains value
*/
- bool erase(const T& value) {
+ bool erase(const T &value) {
- Element* I = find(value);
+ Element *I = find(value);
return erase(I);
};
@@ -358,121 +353,115 @@ public:
_FORCE_INLINE_ int size() const {
- return _data?_data->size_cache:0;
-
+ return _data ? _data->size_cache : 0;
}
- void swap(Element* p_A, Element *p_B) {
+ void swap(Element *p_A, Element *p_B) {
ERR_FAIL_COND(!p_A || !p_B);
- ERR_FAIL_COND(p_A->data!=_data);
- ERR_FAIL_COND(p_B->data!=_data);
+ ERR_FAIL_COND(p_A->data != _data);
+ ERR_FAIL_COND(p_B->data != _data);
- Element* A_prev=p_A->prev_ptr;
- Element* A_next=p_A->next_ptr;
+ Element *A_prev = p_A->prev_ptr;
+ Element *A_next = p_A->next_ptr;
- p_A->next_ptr=p_B->next_ptr;
- p_A->prev_ptr=p_B->prev_ptr;
+ p_A->next_ptr = p_B->next_ptr;
+ p_A->prev_ptr = p_B->prev_ptr;
- p_B->next_ptr=A_next;
- p_B->prev_ptr=A_prev;
+ p_B->next_ptr = A_next;
+ p_B->prev_ptr = A_prev;
if (p_A->prev_ptr)
- p_A->prev_ptr->next_ptr=p_A;
+ p_A->prev_ptr->next_ptr = p_A;
if (p_A->next_ptr)
- p_A->next_ptr->prev_ptr=p_A;
+ p_A->next_ptr->prev_ptr = p_A;
if (p_B->prev_ptr)
- p_B->prev_ptr->next_ptr=p_B;
+ p_B->prev_ptr->next_ptr = p_B;
if (p_B->next_ptr)
- p_B->next_ptr->prev_ptr=p_B;
-
+ p_B->next_ptr->prev_ptr = p_B;
}
/**
* copy the list
*/
- void operator=(const List& p_list) {
+ void operator=(const List &p_list) {
clear();
- const Element *it=p_list.front();
+ const Element *it = p_list.front();
while (it) {
- push_back( it->get() );
- it=it->next();
+ push_back(it->get());
+ it = it->next();
}
-
}
- T& operator[](int p_index) {
+ T &operator[](int p_index) {
- if (p_index<0 || p_index>=size()) {
- T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux);
+ if (p_index < 0 || p_index >= size()) {
+ T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux);
}
- Element *I=front();
- int c=0;
- while(I) {
+ Element *I = front();
+ int c = 0;
+ while (I) {
- if (c==p_index) {
+ if (c == p_index) {
return I->get();
}
- I=I->next();
+ I = I->next();
c++;
}
- ERR_FAIL_V( *((T*)0) ); // bug!!
+ ERR_FAIL_V(*((T *)0)); // bug!!
}
- const T& operator[](int p_index) const {
+ const T &operator[](int p_index) const {
- if (p_index<0 || p_index>=size()) {
- T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux);
+ if (p_index < 0 || p_index >= size()) {
+ T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux);
}
- const Element *I=front();
- int c=0;
- while(I) {
+ const Element *I = front();
+ int c = 0;
+ while (I) {
- if (c==p_index) {
+ if (c == p_index) {
return I->get();
}
- I=I->next();
+ I = I->next();
c++;
}
- ERR_FAIL_V( *((T*)0) ); // bug!
+ ERR_FAIL_V(*((T *)0)); // bug!
}
+ void move_to_back(Element *p_I) {
- void move_to_back(Element* p_I) {
-
- ERR_FAIL_COND(p_I->data!=_data);
+ ERR_FAIL_COND(p_I->data != _data);
if (!p_I->next_ptr)
return;
- if (_data->first==p_I) {
- _data->first=p_I->next_ptr;
+ if (_data->first == p_I) {
+ _data->first = p_I->next_ptr;
};
- if (_data->last==p_I)
- _data->last=p_I->prev_ptr;
+ if (_data->last == p_I)
+ _data->last = p_I->prev_ptr;
if (p_I->prev_ptr)
- p_I->prev_ptr->next_ptr=p_I->next_ptr;
+ p_I->prev_ptr->next_ptr = p_I->next_ptr;
if (p_I->next_ptr)
- p_I->next_ptr->prev_ptr=p_I->prev_ptr;
-
-
- _data->last->next_ptr=p_I;
- p_I->prev_ptr=_data->last;
- p_I->next_ptr=NULL;
- _data->last=p_I;
+ p_I->next_ptr->prev_ptr = p_I->prev_ptr;
+ _data->last->next_ptr = p_I;
+ p_I->prev_ptr = _data->last;
+ p_I->next_ptr = NULL;
+ _data->last = p_I;
}
void invert() {
@@ -480,52 +469,49 @@ public:
int s = size() / 2;
Element *F = front();
Element *B = back();
- for(int i=0;i<s;i++) {
+ for (int i = 0; i < s; i++) {
- SWAP( F->value, B->value );
- F=F->next();
- B=B->prev();
+ SWAP(F->value, B->value);
+ F = F->next();
+ B = B->prev();
}
}
- void move_to_front(Element* p_I) {
+ void move_to_front(Element *p_I) {
- ERR_FAIL_COND(p_I->data!=_data);
+ ERR_FAIL_COND(p_I->data != _data);
if (!p_I->prev_ptr)
return;
- if (_data->first==p_I) {
- _data->first=p_I->next_ptr;
+ if (_data->first == p_I) {
+ _data->first = p_I->next_ptr;
};
- if (_data->last==p_I)
- _data->last=p_I->prev_ptr;
+ if (_data->last == p_I)
+ _data->last = p_I->prev_ptr;
if (p_I->prev_ptr)
- p_I->prev_ptr->next_ptr=p_I->next_ptr;
+ p_I->prev_ptr->next_ptr = p_I->next_ptr;
if (p_I->next_ptr)
- p_I->next_ptr->prev_ptr=p_I->prev_ptr;
-
- _data->first->prev_ptr=p_I;
- p_I->next_ptr=_data->first;
- p_I->prev_ptr=NULL;
- _data->first=p_I;
+ p_I->next_ptr->prev_ptr = p_I->prev_ptr;
+ _data->first->prev_ptr = p_I;
+ p_I->next_ptr = _data->first;
+ p_I->prev_ptr = NULL;
+ _data->first = p_I;
}
- void move_before(Element* value, Element* where) {
+ void move_before(Element *value, Element *where) {
if (value->prev_ptr) {
value->prev_ptr->next_ptr = value->next_ptr;
- }
- else {
+ } else {
_data->first = value->next_ptr;
}
if (value->next_ptr) {
value->next_ptr->prev_ptr = value->prev_ptr;
- }
- else {
+ } else {
_data->last = value->prev_ptr;
}
@@ -553,138 +539,133 @@ public:
void sort() {
- sort_custom< Comparator<T> >();
+ sort_custom<Comparator<T> >();
}
- template<class C>
+ template <class C>
void sort_custom_inplace() {
- if(size()<2)
+ if (size() < 2)
return;
- Element *from=front();
- Element *current=from;
- Element *to=from;
+ Element *from = front();
+ Element *current = from;
+ Element *to = from;
- while(current) {
+ while (current) {
- Element *next=current->next_ptr;
+ Element *next = current->next_ptr;
//disconnect
- current->next_ptr=NULL;
+ current->next_ptr = NULL;
- if (from!=current) {
+ if (from != current) {
- current->prev_ptr=NULL;
- current->next_ptr=from;
+ current->prev_ptr = NULL;
+ current->next_ptr = from;
- Element *find=from;
+ Element *find = from;
C less;
- while( find && less(find->value,current->value) ) {
+ while (find && less(find->value, current->value)) {
- current->prev_ptr=find;
- current->next_ptr=find->next_ptr;
- find=find->next_ptr;
+ current->prev_ptr = find;
+ current->next_ptr = find->next_ptr;
+ find = find->next_ptr;
}
if (current->prev_ptr)
- current->prev_ptr->next_ptr=current;
+ current->prev_ptr->next_ptr = current;
else
- from=current;
+ from = current;
if (current->next_ptr)
- current->next_ptr->prev_ptr=current;
+ current->next_ptr->prev_ptr = current;
else
- to=current;
+ to = current;
} else {
- current->prev_ptr=NULL;
- current->next_ptr=NULL;
-
+ current->prev_ptr = NULL;
+ current->next_ptr = NULL;
}
- current=next;
+ current = next;
}
- _data->first=from;
- _data->last=to;
+ _data->first = from;
+ _data->last = to;
}
- template<class C>
+ template <class C>
struct AuxiliaryComparator {
C compare;
- _FORCE_INLINE_ bool operator()(const Element *a,const Element* b) const {
+ _FORCE_INLINE_ bool operator()(const Element *a, const Element *b) const {
- return compare(a->value,b->value);
+ return compare(a->value, b->value);
}
};
- template<class C>
+ template <class C>
void sort_custom() {
//this version uses auxiliary memory for speed.
//if you don't want to use auxiliary memory, use the in_place version
int s = size();
- if(s<2)
+ if (s < 2)
return;
+ Element **aux_buffer = memnew_arr(Element *, s);
- Element **aux_buffer = memnew_arr(Element*,s);
+ int idx = 0;
+ for (Element *E = front(); E; E = E->next_ptr) {
- int idx=0;
- for(Element *E=front();E;E=E->next_ptr) {
-
- aux_buffer[idx]=E;
+ aux_buffer[idx] = E;
idx++;
}
- SortArray<Element*,AuxiliaryComparator<C> > sort;
- sort.sort(aux_buffer,s);
-
- _data->first=aux_buffer[0];
- aux_buffer[0]->prev_ptr=NULL;
- aux_buffer[0]->next_ptr=aux_buffer[1];
+ SortArray<Element *, AuxiliaryComparator<C> > sort;
+ sort.sort(aux_buffer, s);
- _data->last=aux_buffer[s-1];
- aux_buffer[s-1]->prev_ptr=aux_buffer[s-2];
- aux_buffer[s-1]->next_ptr=NULL;
+ _data->first = aux_buffer[0];
+ aux_buffer[0]->prev_ptr = NULL;
+ aux_buffer[0]->next_ptr = aux_buffer[1];
- for(int i=1;i<s-1;i++) {
+ _data->last = aux_buffer[s - 1];
+ aux_buffer[s - 1]->prev_ptr = aux_buffer[s - 2];
+ aux_buffer[s - 1]->next_ptr = NULL;
- aux_buffer[i]->prev_ptr=aux_buffer[i-1];
- aux_buffer[i]->next_ptr=aux_buffer[i+1];
+ for (int i = 1; i < s - 1; i++) {
+ aux_buffer[i]->prev_ptr = aux_buffer[i - 1];
+ aux_buffer[i]->next_ptr = aux_buffer[i + 1];
}
memdelete_arr(aux_buffer);
}
-
/**
* copy constructor for the list
*/
- List(const List& p_list) {
+ List(const List &p_list) {
- _data=NULL;
- const Element *it=p_list.front();
+ _data = NULL;
+ const Element *it = p_list.front();
while (it) {
- push_back( it->get() );
- it=it->next();
+ push_back(it->get());
+ it = it->next();
}
-
}
List() {
- _data=NULL;
+ _data = NULL;
};
~List() {
clear();
if (_data) {
ERR_FAIL_COND(_data->size_cache);
- memdelete_allocator<_Data,A>(_data);
+ memdelete_allocator<_Data, A>(_data);
}
};
};
diff --git a/core/map.h b/core/map.h
index d1a4c209ad..e9700ff371 100644
--- a/core/map.h
+++ b/core/map.h
@@ -37,7 +37,7 @@
// based on the very nice implementation of rb-trees by:
// http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html
-template <class K,class V,class C=Comparator<K>,class A=DefaultAllocator>
+template <class K, class V, class C = Comparator<K>, class A = DefaultAllocator>
class Map {
enum Color {
@@ -45,26 +45,25 @@ class Map {
BLACK
};
struct _Data;
-public:
+public:
class Element {
private:
- friend class Map<K,V,C,A>;
+ friend class Map<K, V, C, A>;
//Color color;
int color;
- Element* right;
- Element* left;
- Element* parent;
- Element* _next;
- Element* _prev;
+ Element *right;
+ Element *left;
+ Element *parent;
+ Element *_next;
+ Element *_prev;
K _key;
V _value;
//_Data *data;
public:
-
const Element *next() const {
return _next;
@@ -81,64 +80,62 @@ public:
return _prev;
}
- const K& key() const {
+ const K &key() const {
return _key;
};
- V& value() {
+ V &value() {
return _value;
};
- const V& value() const {
+ const V &value() const {
return _value;
};
- V& get() {
+ V &get() {
return _value;
};
- const V& get() const {
+ const V &get() const {
return _value;
};
Element() {
- color=RED;
- right=NULL;
- left=NULL;
- parent=NULL;
- _next=NULL;
- _prev=NULL;
+ color = RED;
+ right = NULL;
+ left = NULL;
+ parent = NULL;
+ _next = NULL;
+ _prev = NULL;
};
};
-
private:
-
struct _Data {
- Element* _root;
- Element* _nil;
+ Element *_root;
+ Element *_nil;
int size_cache;
_FORCE_INLINE_ _Data() {
#ifdef GLOBALNIL_DISABLED
- _nil = memnew_allocator( Element, A );
- _nil->parent=_nil->left=_nil->right=_nil;
- _nil->color=BLACK;
+ _nil = memnew_allocator(Element, A);
+ _nil->parent = _nil->left = _nil->right = _nil;
+ _nil->color = BLACK;
#else
- _nil=(Element*)&_GlobalNilClass::_nil;
+ _nil = (Element *)&_GlobalNilClass::_nil;
#endif
- _root=NULL;
- size_cache=0;
+ _root = NULL;
+ size_cache = 0;
}
void _create_root() {
- _root = memnew_allocator( Element,A );
- _root->parent=_root->left=_root->right=_nil;
- _root->color=BLACK;
+ _root = memnew_allocator(Element, A);
+ _root->parent = _root->left = _root->right = _nil;
+ _root->color = BLACK;
}
void _free_root() {
if (_root) {
- memdelete_allocator<Element,A>(_root);
- _root=NULL;
+ memdelete_allocator<Element, A>(_root);
+ _root = NULL;
}
}
@@ -147,7 +144,7 @@ private:
_free_root();
#ifdef GLOBALNIL_DISABLED
- memdelete_allocator<Element,A>(_nil);
+ memdelete_allocator<Element, A>(_nil);
#endif
//memdelete_allocator<Element,A>(_root);
}
@@ -157,58 +154,56 @@ private:
inline void _set_color(Element *p_node, int p_color) {
- ERR_FAIL_COND( p_node == _data._nil && p_color == RED );
- p_node->color=p_color;
+ ERR_FAIL_COND(p_node == _data._nil && p_color == RED);
+ p_node->color = p_color;
}
inline void _rotate_left(Element *p_node) {
- Element *r=p_node->right;
- p_node->right=r->left;
- if (r->left != _data._nil )
- r->left->parent=p_node;
- r->parent=p_node->parent;
- if (p_node==p_node->parent->left)
- p_node->parent->left=r;
+ Element *r = p_node->right;
+ p_node->right = r->left;
+ if (r->left != _data._nil)
+ r->left->parent = p_node;
+ r->parent = p_node->parent;
+ if (p_node == p_node->parent->left)
+ p_node->parent->left = r;
else
- p_node->parent->right=r;
-
- r->left=p_node;
- p_node->parent=r;
+ p_node->parent->right = r;
+ r->left = p_node;
+ p_node->parent = r;
}
inline void _rotate_right(Element *p_node) {
- Element *l=p_node->left;
- p_node->left=l->right;
+ Element *l = p_node->left;
+ p_node->left = l->right;
if (l->right != _data._nil)
- l->right->parent=p_node;
- l->parent=p_node->parent;
- if (p_node==p_node->parent->right)
- p_node->parent->right=l;
+ l->right->parent = p_node;
+ l->parent = p_node->parent;
+ if (p_node == p_node->parent->right)
+ p_node->parent->right = l;
else
- p_node->parent->left=l;
-
- l->right=p_node;
- p_node->parent=l;
+ p_node->parent->left = l;
+ l->right = p_node;
+ p_node->parent = l;
}
- inline Element* _successor(Element *p_node) const {
+ inline Element *_successor(Element *p_node) const {
- Element *node=p_node;
+ Element *node = p_node;
if (node->right != _data._nil) {
- node=node->right;
- while(node->left != _data._nil) { /* returns the minium of the right subtree of node */
- node=node->left;
+ node = node->right;
+ while (node->left != _data._nil) { /* returns the minium of the right subtree of node */
+ node = node->left;
}
return node;
} else {
- while(node == node->parent->right) {
- node=node->parent;
+ while (node == node->parent->right) {
+ node = node->parent;
}
if (node->parent == _data._root)
return NULL;
@@ -216,419 +211,408 @@ private:
}
}
- inline Element* _predecessor(Element *p_node) const {
- Element *node=p_node;
+ inline Element *_predecessor(Element *p_node) const {
+ Element *node = p_node;
if (node->left != _data._nil) {
- node=node->left;
- while(node->right != _data._nil) { /* returns the minium of the left subtree of node */
- node=node->right;
+ node = node->left;
+ while (node->right != _data._nil) { /* returns the minium of the left subtree of node */
+ node = node->right;
}
return node;
} else {
- while(node == node->parent->left) {
+ while (node == node->parent->left) {
if (node->parent == _data._root)
return NULL;
- node=node->parent;
+ node = node->parent;
}
return node->parent;
}
}
-
- Element *_find(const K& p_key) const {
+ Element *_find(const K &p_key) const {
Element *node = _data._root->left;
C less;
- while(node!=_data._nil) {
+ while (node != _data._nil) {
- if (less(p_key,node->_key))
- node=node->left;
- else if (less(node->_key,p_key))
- node=node->right;
+ if (less(p_key, node->_key))
+ node = node->left;
+ else if (less(node->_key, p_key))
+ node = node->right;
else
break; // found
}
- return (node!=_data._nil)?node:NULL;
+ return (node != _data._nil) ? node : NULL;
}
- Element *_find_closest(const K& p_key) const {
+ Element *_find_closest(const K &p_key) const {
Element *node = _data._root->left;
Element *prev = NULL;
C less;
- while(node!=_data._nil) {
- prev=node;
+ while (node != _data._nil) {
+ prev = node;
- if (less(p_key,node->_key))
- node=node->left;
- else if (less(node->_key,p_key))
- node=node->right;
+ if (less(p_key, node->_key))
+ node = node->left;
+ else if (less(node->_key, p_key))
+ node = node->right;
else
break; // found
}
- if (node==_data._nil) {
- if (prev==NULL)
+ if (node == _data._nil) {
+ if (prev == NULL)
return NULL;
- if (less(p_key,prev->_key)) {
+ if (less(p_key, prev->_key)) {
- prev=prev->_prev;
+ prev = prev->_prev;
}
return prev;
} else
return node;
-
}
- Element *_insert(const K& p_key, bool& r_exists) {
+ Element *_insert(const K &p_key, bool &r_exists) {
- Element *new_parent=_data._root;
+ Element *new_parent = _data._root;
Element *node = _data._root->left;
C less;
- while (node!=_data._nil) {
+ while (node != _data._nil) {
- new_parent=node;
+ new_parent = node;
- if (less(p_key,node->_key))
- node=node->left;
- else if (less(node->_key,p_key))
- node=node->right;
+ if (less(p_key, node->_key))
+ node = node->left;
+ else if (less(node->_key, p_key))
+ node = node->right;
else {
- r_exists=true;
+ r_exists = true;
return node;
}
}
- Element *new_node = memnew_allocator( Element, A );
+ Element *new_node = memnew_allocator(Element, A);
-
- new_node->parent=new_parent;
- new_node->right=_data._nil;
- new_node->left=_data._nil;
- new_node->_key=p_key;
+ new_node->parent = new_parent;
+ new_node->right = _data._nil;
+ new_node->left = _data._nil;
+ new_node->_key = p_key;
//new_node->data=_data;
- if (new_parent==_data._root || less(p_key,new_parent->_key)) {
+ if (new_parent == _data._root || less(p_key, new_parent->_key)) {
- new_parent->left=new_node;
+ new_parent->left = new_node;
} else {
- new_parent->right=new_node;
+ new_parent->right = new_node;
}
- r_exists=false;
+ r_exists = false;
- new_node->_next=_successor(new_node);
- new_node->_prev=_predecessor(new_node);
+ new_node->_next = _successor(new_node);
+ new_node->_prev = _predecessor(new_node);
if (new_node->_next)
- new_node->_next->_prev=new_node;
+ new_node->_next->_prev = new_node;
if (new_node->_prev)
- new_node->_prev->_next=new_node;
-
+ new_node->_prev->_next = new_node;
return new_node;
}
- Element * _insert_rb(const K& p_key, const V& p_value) {
+ Element *_insert_rb(const K &p_key, const V &p_value) {
- bool exists=false;
- Element *new_node = _insert(p_key,exists);
+ bool exists = false;
+ Element *new_node = _insert(p_key, exists);
if (new_node) {
- new_node->_value=p_value;
+ new_node->_value = p_value;
}
if (exists)
return new_node;
- Element *node=new_node;
+ Element *node = new_node;
_data.size_cache++;
- while(node->parent->color==RED) {
+ while (node->parent->color == RED) {
if (node->parent == node->parent->parent->left) {
- Element *aux=node->parent->parent->right;
+ Element *aux = node->parent->parent->right;
- if (aux->color==RED) {
- _set_color(node->parent,BLACK);
- _set_color(aux,BLACK);
- _set_color(node->parent->parent,RED);
- node=node->parent->parent;
+ if (aux->color == RED) {
+ _set_color(node->parent, BLACK);
+ _set_color(aux, BLACK);
+ _set_color(node->parent->parent, RED);
+ node = node->parent->parent;
} else {
if (node == node->parent->right) {
- node=node->parent;
+ node = node->parent;
_rotate_left(node);
}
- _set_color(node->parent,BLACK);
- _set_color(node->parent->parent,RED);
+ _set_color(node->parent, BLACK);
+ _set_color(node->parent->parent, RED);
_rotate_right(node->parent->parent);
}
} else {
- Element *aux=node->parent->parent->left;
+ Element *aux = node->parent->parent->left;
- if (aux->color==RED) {
- _set_color(node->parent,BLACK);
- _set_color(aux,BLACK);
- _set_color(node->parent->parent,RED);
- node=node->parent->parent;
+ if (aux->color == RED) {
+ _set_color(node->parent, BLACK);
+ _set_color(aux, BLACK);
+ _set_color(node->parent->parent, RED);
+ node = node->parent->parent;
} else {
if (node == node->parent->left) {
- node=node->parent;
+ node = node->parent;
_rotate_right(node);
}
- _set_color(node->parent,BLACK);
- _set_color(node->parent->parent,RED);
+ _set_color(node->parent, BLACK);
+ _set_color(node->parent->parent, RED);
_rotate_left(node->parent->parent);
}
}
}
- _set_color(_data._root->left,BLACK);
+ _set_color(_data._root->left, BLACK);
return new_node;
}
void _erase_fix(Element *p_node) {
Element *root = _data._root->left;
- Element *node=p_node;
-
+ Element *node = p_node;
- while( (node->color==BLACK) && (root != node)) {
+ while ((node->color == BLACK) && (root != node)) {
if (node == node->parent->left) {
- Element *aux=node->parent->right;
- if (aux->color==RED) {
- _set_color(aux,BLACK);
- _set_color(node->parent,RED);
+ Element *aux = node->parent->right;
+ if (aux->color == RED) {
+ _set_color(aux, BLACK);
+ _set_color(node->parent, RED);
_rotate_left(node->parent);
- aux=node->parent->right;
+ aux = node->parent->right;
}
- if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) {
- _set_color(aux,RED);
- node=node->parent;
+ if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) {
+ _set_color(aux, RED);
+ node = node->parent;
} else {
- if (aux->right->color==BLACK) {
- _set_color(aux->left,BLACK);
- _set_color(aux,RED);
+ if (aux->right->color == BLACK) {
+ _set_color(aux->left, BLACK);
+ _set_color(aux, RED);
_rotate_right(aux);
- aux=node->parent->right;
+ aux = node->parent->right;
}
- _set_color(aux,node->parent->color);
- _set_color(node->parent,BLACK);
- _set_color(aux->right,BLACK);
+ _set_color(aux, node->parent->color);
+ _set_color(node->parent, BLACK);
+ _set_color(aux->right, BLACK);
_rotate_left(node->parent);
- node=root; /* this is to exit while loop */
+ node = root; /* this is to exit while loop */
}
} else { /* the code below is has left and right switched from above */
- Element *aux=node->parent->left;
- if (aux->color==RED) {
- _set_color(aux,BLACK);
- _set_color(node->parent,RED);
+ Element *aux = node->parent->left;
+ if (aux->color == RED) {
+ _set_color(aux, BLACK);
+ _set_color(node->parent, RED);
_rotate_right(node->parent);
- aux=node->parent->left;
+ aux = node->parent->left;
}
- if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) {
- _set_color(aux,RED);
- node=node->parent;
+ if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) {
+ _set_color(aux, RED);
+ node = node->parent;
} else {
- if (aux->left->color==BLACK) {
- _set_color(aux->right,BLACK);
- _set_color(aux,RED);
+ if (aux->left->color == BLACK) {
+ _set_color(aux->right, BLACK);
+ _set_color(aux, RED);
_rotate_left(aux);
- aux=node->parent->left;
+ aux = node->parent->left;
}
- _set_color(aux,node->parent->color);
- _set_color(node->parent,BLACK);
- _set_color(aux->left,BLACK);
+ _set_color(aux, node->parent->color);
+ _set_color(node->parent, BLACK);
+ _set_color(aux->left, BLACK);
_rotate_right(node->parent);
- node=root;
+ node = root;
}
}
}
- _set_color(node,BLACK);
+ _set_color(node, BLACK);
- ERR_FAIL_COND(_data._nil->color!=BLACK);
+ ERR_FAIL_COND(_data._nil->color != BLACK);
}
void _erase(Element *p_node) {
-
- Element *rp= ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node);
+ Element *rp = ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node);
if (!rp)
- rp=_data._nil;
- Element *node= (rp->left == _data._nil) ? rp->right : rp->left;
+ rp = _data._nil;
+ Element *node = (rp->left == _data._nil) ? rp->right : rp->left;
- if (_data._root == (node->parent=rp->parent) ) {
- _data._root->left=node;
+ if (_data._root == (node->parent = rp->parent)) {
+ _data._root->left = node;
} else {
if (rp == rp->parent->left) {
- rp->parent->left=node;
+ rp->parent->left = node;
} else {
- rp->parent->right=node;
+ rp->parent->right = node;
}
}
if (rp != p_node) {
- ERR_FAIL_COND( rp == _data._nil );
+ ERR_FAIL_COND(rp == _data._nil);
- if (rp->color==BLACK)
+ if (rp->color == BLACK)
_erase_fix(node);
-
- rp->left=p_node->left;
- rp->right=p_node->right;
- rp->parent=p_node->parent;
- rp->color=p_node->color;
- p_node->left->parent=rp;
- p_node->right->parent=rp;
+ rp->left = p_node->left;
+ rp->right = p_node->right;
+ rp->parent = p_node->parent;
+ rp->color = p_node->color;
+ p_node->left->parent = rp;
+ p_node->right->parent = rp;
if (p_node == p_node->parent->left) {
- p_node->parent->left=rp;
+ p_node->parent->left = rp;
} else {
- p_node->parent->right=rp;
+ p_node->parent->right = rp;
}
} else {
- if (p_node->color==BLACK)
+ if (p_node->color == BLACK)
_erase_fix(node);
-
}
-
if (p_node->_next)
- p_node->_next->_prev=p_node->_prev;
+ p_node->_next->_prev = p_node->_prev;
if (p_node->_prev)
- p_node->_prev->_next=p_node->_next;
+ p_node->_prev->_next = p_node->_next;
- memdelete_allocator<Element,A>(p_node);
+ memdelete_allocator<Element, A>(p_node);
_data.size_cache--;
- ERR_FAIL_COND( _data._nil->color==RED );
+ ERR_FAIL_COND(_data._nil->color == RED);
}
+ void _calculate_depth(Element *p_element, int &max_d, int d) const {
- void _calculate_depth(Element *p_element,int &max_d,int d) const {
-
- if (p_element==_data._nil) {
+ if (p_element == _data._nil) {
return;
}
- _calculate_depth(p_element->left,max_d,d+1);
- _calculate_depth(p_element->right,max_d,d+1);
- if (d>max_d)
- max_d=d;
+ _calculate_depth(p_element->left, max_d, d + 1);
+ _calculate_depth(p_element->right, max_d, d + 1);
+ if (d > max_d)
+ max_d = d;
}
void _cleanup_tree(Element *p_element) {
- if (p_element==_data._nil)
+ if (p_element == _data._nil)
return;
_cleanup_tree(p_element->left);
_cleanup_tree(p_element->right);
- memdelete_allocator<Element,A>( p_element );
+ memdelete_allocator<Element, A>(p_element);
}
- void _copy_from( const Map& p_map) {
+ void _copy_from(const Map &p_map) {
clear();
// not the fastest way, but safeset to write.
- for(Element *I=p_map.front();I;I=I->next()) {
+ for (Element *I = p_map.front(); I; I = I->next()) {
- insert(I->key(),I->value());
+ insert(I->key(), I->value());
}
}
-public:
- const Element *find(const K& p_key) const {
+public:
+ const Element *find(const K &p_key) const {
if (!_data._root)
return NULL;
- const Element *res=_find(p_key);
+ const Element *res = _find(p_key);
return res;
}
- Element *find(const K& p_key) {
+ Element *find(const K &p_key) {
if (!_data._root)
return NULL;
- Element *res=_find(p_key);
+ Element *res = _find(p_key);
return res;
}
- const Element *find_closest(const K& p_key) const {
+ const Element *find_closest(const K &p_key) const {
if (!_data._root)
return NULL;
- const Element *res=_find_closest(p_key);
+ const Element *res = _find_closest(p_key);
return res;
}
- Element *find_closest(const K& p_key) {
+ Element *find_closest(const K &p_key) {
if (!_data._root)
return NULL;
- Element *res=_find_closest(p_key);
+ Element *res = _find_closest(p_key);
return res;
}
- Element *insert(const K& p_key,const V& p_value) {
+ Element *insert(const K &p_key, const V &p_value) {
if (!_data._root)
_data._create_root();
- return _insert_rb(p_key,p_value);
-
+ return _insert_rb(p_key, p_value);
}
- void erase(Element* p_element) {
+ void erase(Element *p_element) {
if (!_data._root)
return;
_erase(p_element);
- if (_data.size_cache==0 && _data._root)
+ if (_data.size_cache == 0 && _data._root)
_data._free_root();
}
- bool erase(const K& p_key) {
+ bool erase(const K &p_key) {
if (!_data._root)
return false;
- Element *e=find(p_key);
+ Element *e = find(p_key);
if (!e)
return false;
_erase(e);
return true;
}
- bool has(const K& p_key) const {
+ bool has(const K &p_key) const {
if (!_data._root)
return false;
return find(p_key) != NULL;
}
- const V& operator[](const K& p_key) const {
+ const V &operator[](const K &p_key) const {
- ERR_FAIL_COND_V(!_data._root, *(V*)NULL); // crash on purpose
- const Element *e=find(p_key);
- ERR_FAIL_COND_V(!e, *(V*)NULL); // crash on purpose
+ ERR_FAIL_COND_V(!_data._root, *(V *)NULL); // crash on purpose
+ const Element *e = find(p_key);
+ ERR_FAIL_COND_V(!e, *(V *)NULL); // crash on purpose
return e->_value;
}
- V& operator[](const K& p_key) {
+ V &operator[](const K &p_key) {
if (!_data._root)
_data._create_root();
- Element *e=find(p_key);
+ Element *e = find(p_key);
if (!e)
- e=insert(p_key,V());
+ e = insert(p_key, V());
- ERR_FAIL_COND_V(!e, *(V*)NULL); // crash on purpose
+ ERR_FAIL_COND_V(!e, *(V *)NULL); // crash on purpose
return e->_value;
}
@@ -637,12 +621,12 @@ public:
if (!_data._root)
return NULL;
- Element *e=_data._root->left;
- if (e==_data._nil)
+ Element *e = _data._root->left;
+ if (e == _data._nil)
return NULL;
- while(e->left!=_data._nil)
- e=e->left;
+ while (e->left != _data._nil)
+ e = e->left;
return e;
}
@@ -651,24 +635,24 @@ public:
if (!_data._root)
return NULL;
- Element *e=_data._root->left;
- if (e==_data._nil)
+ Element *e = _data._root->left;
+ if (e == _data._nil)
return NULL;
- while(e->right!=_data._nil)
- e=e->right;
+ while (e->right != _data._nil)
+ e = e->right;
return e;
}
- inline bool empty() const { return _data.size_cache==0; }
+ inline bool empty() const { return _data.size_cache == 0; }
inline int size() const { return _data.size_cache; }
int calculate_depth() const {
// used for debug mostly
if (!_data._root)
return 0;
- int max_d=0;
- _calculate_depth(_data._root->left,max_d,0);
+ int max_d = 0;
+ _calculate_depth(_data._root->left, max_d, 0);
return max_d;
}
@@ -677,32 +661,29 @@ public:
if (!_data._root)
return;
_cleanup_tree(_data._root->left);
- _data._root->left=_data._nil;
- _data.size_cache=0;
- _data._nil->parent=_data._nil;
+ _data._root->left = _data._nil;
+ _data.size_cache = 0;
+ _data._nil->parent = _data._nil;
_data._free_root();
}
- void operator=(const Map& p_map) {
+ void operator=(const Map &p_map) {
- _copy_from( p_map );
+ _copy_from(p_map);
}
- Map(const Map& p_map) {
+ Map(const Map &p_map) {
- _copy_from( p_map );
+ _copy_from(p_map);
}
_FORCE_INLINE_ Map() {
-
}
-
~Map() {
clear();
}
-
};
#endif
diff --git a/core/math/a_star.cpp b/core/math/a_star.cpp
index 7e31957e3e..110185c2d2 100644
--- a/core/math/a_star.cpp
+++ b/core/math/a_star.cpp
@@ -29,55 +29,52 @@
#include "a_star.h"
#include "geometry.h"
-
int AStar::get_available_point_id() const {
if (points.empty()) {
return 1;
}
- return points.back()->key()+1;
+ return points.back()->key() + 1;
}
void AStar::add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale) {
- ERR_FAIL_COND(p_id<0);
+ ERR_FAIL_COND(p_id < 0);
if (!points.has(p_id)) {
- Point *pt = memnew( Point );
- pt->id=p_id;
- pt->pos=p_pos;
- pt->weight_scale=p_weight_scale;
- pt->prev_point=NULL;
- pt->last_pass=0;
- points[p_id]=pt;
+ Point *pt = memnew(Point);
+ pt->id = p_id;
+ pt->pos = p_pos;
+ pt->weight_scale = p_weight_scale;
+ pt->prev_point = NULL;
+ pt->last_pass = 0;
+ points[p_id] = pt;
} else {
- points[p_id]->pos=p_pos;
- points[p_id]->weight_scale=p_weight_scale;
+ points[p_id]->pos = p_pos;
+ points[p_id]->weight_scale = p_weight_scale;
}
}
-Vector3 AStar::get_point_pos(int p_id) const{
+Vector3 AStar::get_point_pos(int p_id) const {
- ERR_FAIL_COND_V(!points.has(p_id),Vector3());
+ ERR_FAIL_COND_V(!points.has(p_id), Vector3());
return points[p_id]->pos;
-
}
-real_t AStar::get_point_weight_scale(int p_id) const{
+real_t AStar::get_point_weight_scale(int p_id) const {
- ERR_FAIL_COND_V(!points.has(p_id),0);
+ ERR_FAIL_COND_V(!points.has(p_id), 0);
return points[p_id]->weight_scale;
-
}
-void AStar::remove_point(int p_id){
+void AStar::remove_point(int p_id) {
ERR_FAIL_COND(!points.has(p_id));
- Point* p = points[p_id];
+ Point *p = points[p_id];
- for(int i=0;i<p->neighbours.size();i++) {
+ for (int i = 0; i < p->neighbours.size(); i++) {
- Segment s(p_id,p->neighbours[i]->id);
+ Segment s(p_id, p->neighbours[i]->id);
segments.erase(s);
p->neighbours[i]->neighbours.erase(p);
}
@@ -86,54 +83,49 @@ void AStar::remove_point(int p_id){
points.erase(p_id);
}
-void AStar::connect_points(int p_id,int p_with_id){
+void AStar::connect_points(int p_id, int p_with_id) {
ERR_FAIL_COND(!points.has(p_id));
ERR_FAIL_COND(!points.has(p_with_id));
- ERR_FAIL_COND(p_id==p_with_id);
+ ERR_FAIL_COND(p_id == p_with_id);
-
- Point* a = points[p_id];
- Point* b = points[p_with_id];
+ Point *a = points[p_id];
+ Point *b = points[p_with_id];
a->neighbours.push_back(b);
b->neighbours.push_back(a);
- Segment s(p_id,p_with_id);
- if (s.from==p_id) {
- s.from_point=a;
- s.to_point=b;
+ Segment s(p_id, p_with_id);
+ if (s.from == p_id) {
+ s.from_point = a;
+ s.to_point = b;
} else {
- s.from_point=b;
- s.to_point=a;
+ s.from_point = b;
+ s.to_point = a;
}
segments.insert(s);
-
-
}
-void AStar::disconnect_points(int p_id,int p_with_id){
+void AStar::disconnect_points(int p_id, int p_with_id) {
- Segment s(p_id,p_with_id);
+ Segment s(p_id, p_with_id);
ERR_FAIL_COND(!segments.has(s));
-
segments.erase(s);
Point *a = points[p_id];
Point *b = points[p_with_id];
a->neighbours.erase(b);
b->neighbours.erase(a);
-
}
-bool AStar::are_points_connected(int p_id,int p_with_id) const{
+bool AStar::are_points_connected(int p_id, int p_with_id) const {
- Segment s(p_id,p_with_id);
+ Segment s(p_id, p_with_id);
return segments.has(s);
}
-void AStar::clear(){
+void AStar::clear() {
- for (const Map<int,Point*>::Element *E=points.front();E;E=E->next()) {
+ for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) {
memdelete(E->get());
}
@@ -141,142 +133,130 @@ void AStar::clear(){
points.clear();
}
+int AStar::get_closest_point(const Vector3 &p_point) const {
-int AStar::get_closest_point(const Vector3& p_point) const{
-
- int closest_id=-1;
- real_t closest_dist=1e20;
+ int closest_id = -1;
+ real_t closest_dist = 1e20;
- for (const Map<int,Point*>::Element *E=points.front();E;E=E->next()) {
+ for (const Map<int, Point *>::Element *E = points.front(); E; E = E->next()) {
real_t d = p_point.distance_squared_to(E->get()->pos);
- if (closest_id<0 || d<closest_dist) {
- closest_dist=d;
- closest_id=E->key();
+ if (closest_id < 0 || d < closest_dist) {
+ closest_dist = d;
+ closest_id = E->key();
}
}
return closest_id;
-
-
}
-Vector3 AStar::get_closest_pos_in_segment(const Vector3& p_point) const {
+Vector3 AStar::get_closest_pos_in_segment(const Vector3 &p_point) const {
real_t closest_dist = 1e20;
- bool found=false;
+ bool found = false;
Vector3 closest_point;
+ for (const Set<Segment>::Element *E = segments.front(); E; E = E->next()) {
- for (const Set<Segment>::Element *E=segments.front();E;E=E->next()) {
-
- Vector3 segment[2]={
+ Vector3 segment[2] = {
E->get().from_point->pos,
E->get().to_point->pos,
};
- Vector3 p = Geometry::get_closest_point_to_segment(p_point,segment);
+ Vector3 p = Geometry::get_closest_point_to_segment(p_point, segment);
real_t d = p_point.distance_squared_to(p);
- if (!found || d<closest_dist) {
+ if (!found || d < closest_dist) {
- closest_point=p;
- closest_dist=d;
- found=true;
+ closest_point = p;
+ closest_dist = d;
+ found = true;
}
}
return closest_point;
}
-bool AStar::_solve(Point* begin_point, Point* end_point) {
+bool AStar::_solve(Point *begin_point, Point *end_point) {
pass++;
SelfList<Point>::List open_list;
- bool found_route=false;
-
+ bool found_route = false;
- for(int i=0;i<begin_point->neighbours.size();i++) {
+ for (int i = 0; i < begin_point->neighbours.size(); i++) {
Point *n = begin_point->neighbours[i];
- n->prev_point=begin_point;
- n->distance=n->pos.distance_to(begin_point->pos);
- n->distance*=n->weight_scale;
- n->last_pass=pass;
+ n->prev_point = begin_point;
+ n->distance = n->pos.distance_to(begin_point->pos);
+ n->distance *= n->weight_scale;
+ n->last_pass = pass;
open_list.add(&n->list);
- if (end_point==n) {
- found_route=true;
+ if (end_point == n) {
+ found_route = true;
break;
}
}
- while(!found_route) {
+ while (!found_route) {
- if (open_list.first()==NULL) {
+ if (open_list.first() == NULL) {
//could not find path sadly
break;
}
//check open list
- SelfList<Point> *least_cost_point=NULL;
- real_t least_cost=1e30;
+ SelfList<Point> *least_cost_point = NULL;
+ real_t least_cost = 1e30;
//this could be faster (cache previous results)
- for (SelfList<Point> *E=open_list.first();E;E=E->next()) {
+ for (SelfList<Point> *E = open_list.first(); E; E = E->next()) {
- Point *p=E->self();
+ Point *p = E->self();
- real_t cost=p->distance;
- cost+=p->pos.distance_to(end_point->pos);
- cost*=p->weight_scale;
+ real_t cost = p->distance;
+ cost += p->pos.distance_to(end_point->pos);
+ cost *= p->weight_scale;
- if (cost<least_cost) {
+ if (cost < least_cost) {
- least_cost_point=E;
- least_cost=cost;
+ least_cost_point = E;
+ least_cost = cost;
}
}
-
- Point *p=least_cost_point->self();
+ Point *p = least_cost_point->self();
//open the neighbours for search
int es = p->neighbours.size();
- for(int i=0;i<es;i++) {
-
-
- Point* e=p->neighbours[i];
+ for (int i = 0; i < es; i++) {
+ Point *e = p->neighbours[i];
real_t distance = p->pos.distance_to(e->pos) + p->distance;
- distance*=e->weight_scale;
-
-
+ distance *= e->weight_scale;
- if (e->last_pass==pass) {
+ if (e->last_pass == pass) {
//oh this was visited already, can we win the cost?
- if (e->distance>distance) {
+ if (e->distance > distance) {
- e->prev_point=p;
- e->distance=distance;
+ e->prev_point = p;
+ e->distance = distance;
}
} else {
//add to open neighbours
- e->prev_point=p;
- e->distance=distance;
- e->last_pass=pass; //mark as used
+ e->prev_point = p;
+ e->distance = distance;
+ e->last_pass = pass; //mark as used
open_list.add(&e->list);
- if (e==end_point) {
+ if (e == end_point) {
//oh my reached end! stop algorithm
- found_route=true;
+ found_route = true;
break;
-
}
-
}
}
@@ -287,46 +267,43 @@ bool AStar::_solve(Point* begin_point, Point* end_point) {
}
//clear the openf list
- while(open_list.first()) {
- open_list.remove( open_list.first() );
+ while (open_list.first()) {
+ open_list.remove(open_list.first());
}
return found_route;
-
}
PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) {
- ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector<Vector3>());
- ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector<Vector3>());
-
+ ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<Vector3>());
+ ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<Vector3>());
pass++;
- Point* a = points[p_from_id];
- Point* b = points[p_to_id];
+ Point *a = points[p_from_id];
+ Point *b = points[p_to_id];
- if (a==b) {
+ if (a == b) {
PoolVector<Vector3> ret;
ret.push_back(a->pos);
return ret;
}
+ Point *begin_point = a;
+ Point *end_point = b;
- Point *begin_point=a;
- Point *end_point=b;
-
- bool found_route=_solve(begin_point,end_point);
+ bool found_route = _solve(begin_point, end_point);
if (!found_route)
return PoolVector<Vector3>();
//midpoints
- Point *p=end_point;
- int pc=1; //begin point
- while(p!=begin_point) {
+ Point *p = end_point;
+ int pc = 1; //begin point
+ while (p != begin_point) {
pc++;
- p=p->prev_point;
+ p = p->prev_point;
}
PoolVector<Vector3> path;
@@ -335,54 +312,49 @@ PoolVector<Vector3> AStar::get_point_path(int p_from_id, int p_to_id) {
{
PoolVector<Vector3>::Write w = path.write();
- Point *p=end_point;
- int idx=pc-1;
- while(p!=begin_point) {
- w[idx--]=p->pos;
- p=p->prev_point;
+ Point *p = end_point;
+ int idx = pc - 1;
+ while (p != begin_point) {
+ w[idx--] = p->pos;
+ p = p->prev_point;
}
- w[0]=p->pos; //assign first
-
+ w[0] = p->pos; //assign first
}
return path;
-
}
-
PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
- ERR_FAIL_COND_V(!points.has(p_from_id),PoolVector<int>());
- ERR_FAIL_COND_V(!points.has(p_to_id),PoolVector<int>());
-
+ ERR_FAIL_COND_V(!points.has(p_from_id), PoolVector<int>());
+ ERR_FAIL_COND_V(!points.has(p_to_id), PoolVector<int>());
pass++;
- Point* a = points[p_from_id];
- Point* b = points[p_to_id];
+ Point *a = points[p_from_id];
+ Point *b = points[p_to_id];
- if (a==b) {
+ if (a == b) {
PoolVector<int> ret;
ret.push_back(a->id);
return ret;
}
+ Point *begin_point = a;
+ Point *end_point = b;
- Point *begin_point=a;
- Point *end_point=b;
-
- bool found_route=_solve(begin_point,end_point);
+ bool found_route = _solve(begin_point, end_point);
if (!found_route)
return PoolVector<int>();
//midpoints
- Point *p=end_point;
- int pc=1; //begin point
- while(p!=begin_point) {
+ Point *p = end_point;
+ int pc = 1; //begin point
+ while (p != begin_point) {
pc++;
- p=p->prev_point;
+ p = p->prev_point;
}
PoolVector<int> path;
@@ -391,15 +363,14 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
{
PoolVector<int>::Write w = path.write();
- p=end_point;
- int idx=pc-1;
- while(p!=begin_point) {
- w[idx--]=p->id;
- p=p->prev_point;
+ p = end_point;
+ int idx = pc - 1;
+ while (p != begin_point) {
+ w[idx--] = p->id;
+ p = p->prev_point;
}
- w[0]=p->id; //assign first
-
+ w[0] = p->id; //assign first
}
return path;
@@ -407,34 +378,31 @@ PoolVector<int> AStar::get_id_path(int p_from_id, int p_to_id) {
void AStar::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_available_point_id"),&AStar::get_available_point_id);
- ClassDB::bind_method(D_METHOD("add_point","id","pos","weight_scale"),&AStar::add_point,DEFVAL(1.0));
- ClassDB::bind_method(D_METHOD("get_point_pos","id"),&AStar::get_point_pos);
- ClassDB::bind_method(D_METHOD("get_point_weight_scale","id"),&AStar::get_point_weight_scale);
- ClassDB::bind_method(D_METHOD("remove_point","id"),&AStar::remove_point);
-
- ClassDB::bind_method(D_METHOD("connect_points","id","to_id"),&AStar::connect_points);
- ClassDB::bind_method(D_METHOD("disconnect_points","id","to_id"),&AStar::disconnect_points);
- ClassDB::bind_method(D_METHOD("are_points_connected","id","to_id"),&AStar::are_points_connected);
+ ClassDB::bind_method(D_METHOD("get_available_point_id"), &AStar::get_available_point_id);
+ ClassDB::bind_method(D_METHOD("add_point", "id", "pos", "weight_scale"), &AStar::add_point, DEFVAL(1.0));
+ ClassDB::bind_method(D_METHOD("get_point_pos", "id"), &AStar::get_point_pos);
+ ClassDB::bind_method(D_METHOD("get_point_weight_scale", "id"), &AStar::get_point_weight_scale);
+ ClassDB::bind_method(D_METHOD("remove_point", "id"), &AStar::remove_point);
- ClassDB::bind_method(D_METHOD("clear"),&AStar::clear);
+ ClassDB::bind_method(D_METHOD("connect_points", "id", "to_id"), &AStar::connect_points);
+ ClassDB::bind_method(D_METHOD("disconnect_points", "id", "to_id"), &AStar::disconnect_points);
+ ClassDB::bind_method(D_METHOD("are_points_connected", "id", "to_id"), &AStar::are_points_connected);
- ClassDB::bind_method(D_METHOD("get_closest_point","to_pos"),&AStar::get_closest_point);
- ClassDB::bind_method(D_METHOD("get_closest_pos_in_segment","to_pos"),&AStar::get_closest_pos_in_segment);
+ ClassDB::bind_method(D_METHOD("clear"), &AStar::clear);
- ClassDB::bind_method(D_METHOD("get_point_path","from_id","to_id"),&AStar::get_point_path);
- ClassDB::bind_method(D_METHOD("get_id_path","from_id","to_id"),&AStar::get_id_path);
+ ClassDB::bind_method(D_METHOD("get_closest_point", "to_pos"), &AStar::get_closest_point);
+ ClassDB::bind_method(D_METHOD("get_closest_pos_in_segment", "to_pos"), &AStar::get_closest_pos_in_segment);
+ ClassDB::bind_method(D_METHOD("get_point_path", "from_id", "to_id"), &AStar::get_point_path);
+ ClassDB::bind_method(D_METHOD("get_id_path", "from_id", "to_id"), &AStar::get_id_path);
}
-
AStar::AStar() {
- pass=1;
+ pass = 1;
}
-
AStar::~AStar() {
- pass=1;
+ pass = 1;
}
diff --git a/core/math/a_star.h b/core/math/a_star.h
index c4c955ed2d..2ac855737c 100644
--- a/core/math/a_star.h
+++ b/core/math/a_star.h
@@ -35,10 +35,9 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-class AStar: public Reference {
-
- GDCLASS(AStar,Reference)
+class AStar : public Reference {
+ GDCLASS(AStar, Reference)
uint64_t pass;
@@ -51,16 +50,17 @@ class AStar: public Reference {
real_t weight_scale;
uint64_t last_pass;
- Vector<Point*> neighbours;
+ Vector<Point *> neighbours;
//used for pathfinding
Point *prev_point;
real_t distance;
- Point() : list(this) {}
+ Point()
+ : list(this) {}
};
- Map<int,Point*> points;
+ Map<int, Point *> points;
struct Segment {
union {
@@ -74,44 +74,41 @@ class AStar: public Reference {
Point *from_point;
Point *to_point;
- bool operator<(const Segment& p_s) const { return key<p_s.key; }
- Segment() { key=0; }
- Segment(int p_from,int p_to) {
+ bool operator<(const Segment &p_s) const { return key < p_s.key; }
+ Segment() { key = 0; }
+ Segment(int p_from, int p_to) {
if (p_from > p_to) {
- SWAP(p_from,p_to);
+ SWAP(p_from, p_to);
}
- from=p_from;
- to=p_to;
+ from = p_from;
+ to = p_to;
}
};
-
Set<Segment> segments;
bool _solve(Point *begin_point, Point *end_point);
protected:
-
static void _bind_methods();
-public:
+public:
int get_available_point_id() const;
- void add_point(int p_id,const Vector3& p_pos,real_t p_weight_scale=1);
+ void add_point(int p_id, const Vector3 &p_pos, real_t p_weight_scale = 1);
Vector3 get_point_pos(int p_id) const;
real_t get_point_weight_scale(int p_id) const;
void remove_point(int p_id);
- void connect_points(int p_id,int p_with_id);
- void disconnect_points(int p_id,int p_with_id);
- bool are_points_connected(int p_id,int p_with_id) const;
+ void connect_points(int p_id, int p_with_id);
+ void disconnect_points(int p_id, int p_with_id);
+ bool are_points_connected(int p_id, int p_with_id) const;
void clear();
-
- int get_closest_point(const Vector3& p_point) const;
- Vector3 get_closest_pos_in_segment(const Vector3& p_point) const;
+ int get_closest_point(const Vector3 &p_point) const;
+ Vector3 get_closest_pos_in_segment(const Vector3 &p_point) const;
PoolVector<Vector3> get_point_path(int p_from_id, int p_to_id);
PoolVector<int> get_id_path(int p_from_id, int p_to_id);
diff --git a/core/math/audio_frame.cpp b/core/math/audio_frame.cpp
index aae1561a84..e56157ffef 100644
--- a/core/math/audio_frame.cpp
+++ b/core/math/audio_frame.cpp
@@ -27,4 +27,3 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "audio_frame.h"
-
diff --git a/core/math/audio_frame.h b/core/math/audio_frame.h
index e4e93f34fa..dd43f48df4 100644
--- a/core/math/audio_frame.h
+++ b/core/math/audio_frame.h
@@ -31,9 +31,7 @@
#include "typedefs.h"
-
-static inline float undenormalise(volatile float f)
-{
+static inline float undenormalise(volatile float f) {
union {
uint32_t i;
float f;
@@ -46,42 +44,71 @@ static inline float undenormalise(volatile float f)
return (v.i & 0x7f800000) < 0x08000000 ? 0.0f : f;
}
-
struct AudioFrame {
//left and right samples
- float l,r;
+ float l, r;
- _ALWAYS_INLINE_ const float& operator[](int idx) const { return idx==0?l:r; }
- _ALWAYS_INLINE_ float& operator[](int idx) { return idx==0?l:r; }
+ _ALWAYS_INLINE_ const float &operator[](int idx) const { return idx == 0 ? l : r; }
+ _ALWAYS_INLINE_ float &operator[](int idx) { return idx == 0 ? l : r; }
- _ALWAYS_INLINE_ AudioFrame operator+(const AudioFrame& p_frame) const { return AudioFrame(l+p_frame.l,r+p_frame.r); }
- _ALWAYS_INLINE_ AudioFrame operator-(const AudioFrame& p_frame) const { return AudioFrame(l-p_frame.l,r-p_frame.r); }
- _ALWAYS_INLINE_ AudioFrame operator*(const AudioFrame& p_frame) const { return AudioFrame(l*p_frame.l,r*p_frame.r); }
- _ALWAYS_INLINE_ AudioFrame operator/(const AudioFrame& p_frame) const { return AudioFrame(l/p_frame.l,r/p_frame.r); }
+ _ALWAYS_INLINE_ AudioFrame operator+(const AudioFrame &p_frame) const { return AudioFrame(l + p_frame.l, r + p_frame.r); }
+ _ALWAYS_INLINE_ AudioFrame operator-(const AudioFrame &p_frame) const { return AudioFrame(l - p_frame.l, r - p_frame.r); }
+ _ALWAYS_INLINE_ AudioFrame operator*(const AudioFrame &p_frame) const { return AudioFrame(l * p_frame.l, r * p_frame.r); }
+ _ALWAYS_INLINE_ AudioFrame operator/(const AudioFrame &p_frame) const { return AudioFrame(l / p_frame.l, r / p_frame.r); }
- _ALWAYS_INLINE_ AudioFrame operator+(float p_sample) const { return AudioFrame(l+p_sample,r+p_sample); }
- _ALWAYS_INLINE_ AudioFrame operator-(float p_sample) const { return AudioFrame(l-p_sample,r-p_sample); }
- _ALWAYS_INLINE_ AudioFrame operator*(float p_sample) const { return AudioFrame(l*p_sample,r*p_sample); }
- _ALWAYS_INLINE_ AudioFrame operator/(float p_sample) const { return AudioFrame(l/p_sample,r/p_sample); }
+ _ALWAYS_INLINE_ AudioFrame operator+(float p_sample) const { return AudioFrame(l + p_sample, r + p_sample); }
+ _ALWAYS_INLINE_ AudioFrame operator-(float p_sample) const { return AudioFrame(l - p_sample, r - p_sample); }
+ _ALWAYS_INLINE_ AudioFrame operator*(float p_sample) const { return AudioFrame(l * p_sample, r * p_sample); }
+ _ALWAYS_INLINE_ AudioFrame operator/(float p_sample) const { return AudioFrame(l / p_sample, r / p_sample); }
- _ALWAYS_INLINE_ void operator+=(const AudioFrame& p_frame) { l+=p_frame.l; r+=p_frame.r; }
- _ALWAYS_INLINE_ void operator-=(const AudioFrame& p_frame) { l-=p_frame.l; r-=p_frame.r; }
- _ALWAYS_INLINE_ void operator*=(const AudioFrame& p_frame) { l*=p_frame.l; r*=p_frame.r; }
- _ALWAYS_INLINE_ void operator/=(const AudioFrame& p_frame) { l/=p_frame.l; r/=p_frame.r; }
+ _ALWAYS_INLINE_ void operator+=(const AudioFrame &p_frame) {
+ l += p_frame.l;
+ r += p_frame.r;
+ }
+ _ALWAYS_INLINE_ void operator-=(const AudioFrame &p_frame) {
+ l -= p_frame.l;
+ r -= p_frame.r;
+ }
+ _ALWAYS_INLINE_ void operator*=(const AudioFrame &p_frame) {
+ l *= p_frame.l;
+ r *= p_frame.r;
+ }
+ _ALWAYS_INLINE_ void operator/=(const AudioFrame &p_frame) {
+ l /= p_frame.l;
+ r /= p_frame.r;
+ }
- _ALWAYS_INLINE_ void operator+=(float p_sample) { l+=p_sample; r+=p_sample; }
- _ALWAYS_INLINE_ void operator-=(float p_sample) { l-=p_sample; r-=p_sample; }
- _ALWAYS_INLINE_ void operator*=(float p_sample) { l*=p_sample; r*=p_sample; }
- _ALWAYS_INLINE_ void operator/=(float p_sample) { l/=p_sample; r/=p_sample; }
+ _ALWAYS_INLINE_ void operator+=(float p_sample) {
+ l += p_sample;
+ r += p_sample;
+ }
+ _ALWAYS_INLINE_ void operator-=(float p_sample) {
+ l -= p_sample;
+ r -= p_sample;
+ }
+ _ALWAYS_INLINE_ void operator*=(float p_sample) {
+ l *= p_sample;
+ r *= p_sample;
+ }
+ _ALWAYS_INLINE_ void operator/=(float p_sample) {
+ l /= p_sample;
+ r /= p_sample;
+ }
_ALWAYS_INLINE_ void undenormalise() {
l = ::undenormalise(l);
r = ::undenormalise(r);
}
- _ALWAYS_INLINE_ AudioFrame(float p_l, float p_r) {l=p_l; r=p_r;}
- _ALWAYS_INLINE_ AudioFrame(const AudioFrame& p_frame) {l=p_frame.l; r=p_frame.r;}
+ _ALWAYS_INLINE_ AudioFrame(float p_l, float p_r) {
+ l = p_l;
+ r = p_r;
+ }
+ _ALWAYS_INLINE_ AudioFrame(const AudioFrame &p_frame) {
+ l = p_frame.l;
+ r = p_frame.r;
+ }
_ALWAYS_INLINE_ AudioFrame() {}
};
diff --git a/core/math/bsp_tree.cpp b/core/math/bsp_tree.cpp
index 1ca6385032..ef229a0553 100644
--- a/core/math/bsp_tree.cpp
+++ b/core/math/bsp_tree.cpp
@@ -30,32 +30,31 @@
#include "error_macros.h"
#include "print_string.h"
-
-void BSP_Tree::from_aabb(const Rect3& p_aabb) {
+void BSP_Tree::from_aabb(const Rect3 &p_aabb) {
planes.clear();
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 n;
- n[i]=1;
- planes.push_back(Plane(n,p_aabb.pos[i]+p_aabb.size[i]));
- planes.push_back(Plane(-n,-p_aabb.pos[i]));
+ n[i] = 1;
+ planes.push_back(Plane(n, p_aabb.pos[i] + p_aabb.size[i]));
+ planes.push_back(Plane(-n, -p_aabb.pos[i]));
}
nodes.clear();
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
Node n;
- n.plane=i;
- n.under=(i==0)?UNDER_LEAF:i-1;
- n.over=OVER_LEAF;
+ n.plane = i;
+ n.under = (i == 0) ? UNDER_LEAF : i - 1;
+ n.over = OVER_LEAF;
nodes.push_back(n);
}
- aabb=p_aabb;
- error_radius=0;
+ aabb = p_aabb;
+ error_radius = 0;
}
Vector<BSP_Tree::Node> BSP_Tree::get_nodes() const {
@@ -72,143 +71,136 @@ Rect3 BSP_Tree::get_aabb() const {
return aabb;
}
-int BSP_Tree::_get_points_inside(int p_node,const Vector3* p_points,int *p_indices, const Vector3& p_center,const Vector3& p_half_extents,int p_indices_count) const {
-
+int BSP_Tree::_get_points_inside(int p_node, const Vector3 *p_points, int *p_indices, const Vector3 &p_center, const Vector3 &p_half_extents, int p_indices_count) const {
- const Node *node =&nodes[p_node];
+ const Node *node = &nodes[p_node];
const Plane &p = planes[node->plane];
Vector3 min(
- (p.normal.x>0) ? -p_half_extents.x : p_half_extents.x,
- (p.normal.y>0) ? -p_half_extents.y : p_half_extents.y,
- (p.normal.z>0) ? -p_half_extents.z : p_half_extents.z
- );
- Vector3 max=-min;
- max+=p_center;
- min+=p_center;
+ (p.normal.x > 0) ? -p_half_extents.x : p_half_extents.x,
+ (p.normal.y > 0) ? -p_half_extents.y : p_half_extents.y,
+ (p.normal.z > 0) ? -p_half_extents.z : p_half_extents.z);
+ Vector3 max = -min;
+ max += p_center;
+ min += p_center;
real_t dist_min = p.distance_to(min);
real_t dist_max = p.distance_to(max);
- if ((dist_min * dist_max) < CMP_EPSILON ) { //intersection, test point by point
-
+ if ((dist_min * dist_max) < CMP_EPSILON) { //intersection, test point by point
- int under_count=0;
+ int under_count = 0;
//sort points, so the are under first, over last
- for(int i=0;i<p_indices_count;i++) {
+ for (int i = 0; i < p_indices_count; i++) {
- int index=p_indices[i];
+ int index = p_indices[i];
if (p.is_point_over(p_points[index])) {
// kind of slow (but cache friendly), should try something else,
// but this is a corner case most of the time
- for(int j=index;j<p_indices_count-1;j++)
- p_indices[j]=p_indices[j+1];
+ for (int j = index; j < p_indices_count - 1; j++)
+ p_indices[j] = p_indices[j + 1];
- p_indices[p_indices_count-1]=index;
+ p_indices[p_indices_count - 1] = index;
} else {
under_count++;
}
-
}
- int total=0;
+ int total = 0;
- if (under_count>0) {
- if (node->under==UNDER_LEAF) {
- total+=under_count;
+ if (under_count > 0) {
+ if (node->under == UNDER_LEAF) {
+ total += under_count;
} else {
- total+=_get_points_inside(node->under,p_points,p_indices,p_center,p_half_extents,under_count);
+ total += _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, under_count);
}
}
- if (under_count!=p_indices_count) {
- if (node->over==OVER_LEAF) {
+ if (under_count != p_indices_count) {
+ if (node->over == OVER_LEAF) {
//total+=0 //if they are over an OVER_LEAF, they are outside the model
} else {
- total+=_get_points_inside(node->over,p_points,&p_indices[under_count],p_center,p_half_extents,p_indices_count-under_count);
+ total += _get_points_inside(node->over, p_points, &p_indices[under_count], p_center, p_half_extents, p_indices_count - under_count);
}
}
return total;
- } else if (dist_min > 0 ) { //all points over plane
+ } else if (dist_min > 0) { //all points over plane
- if (node->over==OVER_LEAF) {
+ if (node->over == OVER_LEAF) {
return 0; // all these points are not visible
}
+ return _get_points_inside(node->over, p_points, p_indices, p_center, p_half_extents, p_indices_count);
+ } else if (dist_min <= 0) { //all points behind plane
- return _get_points_inside(node->over,p_points,p_indices,p_center,p_half_extents,p_indices_count);
- } else if (dist_min <= 0 ) { //all points behind plane
-
- if (node->under==UNDER_LEAF) {
+ if (node->under == UNDER_LEAF) {
return p_indices_count; // all these points are visible
}
- return _get_points_inside(node->under,p_points,p_indices,p_center,p_half_extents,p_indices_count);
+ return _get_points_inside(node->under, p_points, p_indices, p_center, p_half_extents, p_indices_count);
}
return 0;
}
-int BSP_Tree::get_points_inside(const Vector3* p_points,int p_point_count) const {
-
+int BSP_Tree::get_points_inside(const Vector3 *p_points, int p_point_count) const {
- if (nodes.size()==0)
+ if (nodes.size() == 0)
return 0;
#if 1
-//this version is easier to debug, and and MUCH faster in real world cases
+ //this version is easier to debug, and and MUCH faster in real world cases
int pass_count = 0;
- const Node *nodesptr=&nodes[0];
- const Plane *planesptr=&planes[0];
- int plane_count=planes.size();
- int node_count=nodes.size();
+ const Node *nodesptr = &nodes[0];
+ const Plane *planesptr = &planes[0];
+ int plane_count = planes.size();
+ int node_count = nodes.size();
- if (node_count==0) // no nodes!
+ if (node_count == 0) // no nodes!
return 0;
- for(int i=0;i<p_point_count;i++) {
+ for (int i = 0; i < p_point_count; i++) {
- const Vector3& point = p_points[i];
+ const Vector3 &point = p_points[i];
if (!aabb.has_point(point)) {
continue;
}
- int idx=node_count-1;
+ int idx = node_count - 1;
- bool pass=false;
+ bool pass = false;
- while(true) {
+ while (true) {
- if (idx==OVER_LEAF) {
- pass=false;
+ if (idx == OVER_LEAF) {
+ pass = false;
break;
- } else if (idx==UNDER_LEAF) {
- pass=true;
+ } else if (idx == UNDER_LEAF) {
+ pass = true;
break;
}
- uint16_t plane=nodesptr[ idx ].plane;
+ uint16_t plane = nodesptr[idx].plane;
#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V( plane, plane_count, false );
+ ERR_FAIL_INDEX_V(plane, plane_count, false);
#endif
- idx = planesptr[ nodesptr[ idx ].plane ].is_point_over(point) ? nodes[ idx ].over : nodes[ idx ].under;
+ idx = planesptr[nodesptr[idx].plane].is_point_over(point) ? nodes[idx].over : nodes[idx].under;
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND_V( idx<MAX_NODES && idx>=node_count, false );
+ ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
#endif
-
}
if (pass)
@@ -218,69 +210,65 @@ int BSP_Tree::get_points_inside(const Vector3* p_points,int p_point_count) const
return pass_count;
#else
-//this version scales better but it's slower for real world cases
+ //this version scales better but it's slower for real world cases
- int *indices = (int*)alloca(p_point_count*sizeof(int));
+ int *indices = (int *)alloca(p_point_count * sizeof(int));
AABB bounds;
- for(int i=0;i<p_point_count;i++) {
+ for (int i = 0; i < p_point_count; i++) {
- indices[i]=i;
- if (i==0)
- bounds.pos=p_points[i];
+ indices[i] = i;
+ if (i == 0)
+ bounds.pos = p_points[i];
else
bounds.expand_to(p_points[i]);
-
}
- Vector3 half_extents = bounds.size/2.0;
- return _get_points_inside(nodes.size()+1,p_points,indices,bounds.pos+half_extents,half_extents,p_point_count);
+ Vector3 half_extents = bounds.size / 2.0;
+ return _get_points_inside(nodes.size() + 1, p_points, indices, bounds.pos + half_extents, half_extents, p_point_count);
#endif
}
-
-
-bool BSP_Tree::point_is_inside(const Vector3& p_point) const {
+bool BSP_Tree::point_is_inside(const Vector3 &p_point) const {
if (!aabb.has_point(p_point)) {
return false;
}
- int node_count=nodes.size();
+ int node_count = nodes.size();
- if (node_count==0) // no nodes!
+ if (node_count == 0) // no nodes!
return false;
+ const Node *nodesptr = &nodes[0];
+ const Plane *planesptr = &planes[0];
+ int plane_count = planes.size();
- const Node *nodesptr=&nodes[0];
- const Plane *planesptr=&planes[0];
- int plane_count=planes.size();
-
- int idx=node_count-1;
- int steps=0;
+ int idx = node_count - 1;
+ int steps = 0;
- while(true) {
+ while (true) {
- if (idx==OVER_LEAF) {
+ if (idx == OVER_LEAF) {
return false;
}
- if (idx==UNDER_LEAF) {
+ if (idx == UNDER_LEAF) {
return true;
}
- uint16_t plane=nodesptr[ idx ].plane;
+ uint16_t plane = nodesptr[idx].plane;
#ifdef DEBUG_ENABLED
- ERR_FAIL_INDEX_V( plane, plane_count, false );
+ ERR_FAIL_INDEX_V(plane, plane_count, false);
#endif
- bool over = planesptr[ nodesptr[ idx ].plane ].is_point_over(p_point);
+ bool over = planesptr[nodesptr[idx].plane].is_point_over(p_point);
- idx = over ? nodes[ idx ].over : nodes[ idx ].under;
+ idx = over ? nodes[idx].over : nodes[idx].under;
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND_V( idx<MAX_NODES && idx>=node_count, false );
+ ERR_FAIL_COND_V(idx < MAX_NODES && idx >= node_count, false);
#endif
steps++;
@@ -289,44 +277,42 @@ bool BSP_Tree::point_is_inside(const Vector3& p_point) const {
return false;
}
-
-static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector<int>& p_indices,real_t p_tolerance) {
+static int _bsp_find_best_half_plane(const Face3 *p_faces, const Vector<int> &p_indices, real_t p_tolerance) {
int ic = p_indices.size();
- const int*indices=p_indices.ptr();
+ const int *indices = p_indices.ptr();
int best_plane = -1;
real_t best_plane_cost = 1e20;
// Loop to find the polygon that best divides the set.
- for (int i=0;i<ic;i++) {
+ for (int i = 0; i < ic; i++) {
- const Face3& f=p_faces[ indices[i] ];
+ const Face3 &f = p_faces[indices[i]];
Plane p = f.get_plane();
- int num_over=0,num_under=0,num_spanning=0;
+ int num_over = 0, num_under = 0, num_spanning = 0;
- for(int j=0;j<ic;j++) {
+ for (int j = 0; j < ic; j++) {
- if (i==j)
+ if (i == j)
continue;
- const Face3& g=p_faces[ indices[j] ];
- int over=0,under=0;
+ const Face3 &g = p_faces[indices[j]];
+ int over = 0, under = 0;
- for(int k=0;k<3;k++) {
+ for (int k = 0; k < 3; k++) {
real_t d = p.distance_to(g.vertex[j]);
- if (Math::abs(d)>p_tolerance) {
+ if (Math::abs(d) > p_tolerance) {
if (d > 0)
over++;
else
under++;
}
-
}
if (over && under)
@@ -335,13 +321,10 @@ static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector<int>& p_i
num_over++;
else
num_under++;
-
}
-
-
//real_t split_cost = num_spanning / (real_t) face_count;
- real_t relation = Math::abs(num_over-num_under) / (real_t) ic;
+ real_t relation = Math::abs(num_over - num_under) / (real_t)ic;
// being honest, i never found a way to add split cost to the mix in a meaninguful way
// in this engine, also, will likely be ignored anyway
@@ -349,59 +332,55 @@ static int _bsp_find_best_half_plane(const Face3* p_faces,const Vector<int>& p_i
real_t plane_cost = /*split_cost +*/ relation;
//printf("plane %i, %i over, %i under, %i spanning, cost is %g\n",i,num_over,num_under,num_spanning,plane_cost);
- if (plane_cost<best_plane_cost) {
+ if (plane_cost < best_plane_cost) {
- best_plane=i;
- best_plane_cost=plane_cost;
+ best_plane = i;
+ best_plane_cost = plane_cost;
}
-
}
return best_plane;
-
}
+static int _bsp_create_node(const Face3 *p_faces, const Vector<int> &p_indices, Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes, real_t p_tolerance) {
-static int _bsp_create_node(const Face3 *p_faces,const Vector<int>& p_indices,Vector<Plane> &p_planes, Vector<BSP_Tree::Node> &p_nodes,real_t p_tolerance) {
-
- ERR_FAIL_COND_V( p_nodes.size() == BSP_Tree::MAX_NODES, -1 );
+ ERR_FAIL_COND_V(p_nodes.size() == BSP_Tree::MAX_NODES, -1);
// should not reach here
- ERR_FAIL_COND_V( p_indices.size() == 0, -1 )
+ ERR_FAIL_COND_V(p_indices.size() == 0, -1)
int ic = p_indices.size();
- const int*indices=p_indices.ptr();
+ const int *indices = p_indices.ptr();
- int divisor_idx = _bsp_find_best_half_plane(p_faces,p_indices,p_tolerance);
+ int divisor_idx = _bsp_find_best_half_plane(p_faces, p_indices, p_tolerance);
// returned error
- ERR_FAIL_COND_V( divisor_idx<0 , -1 );
-
+ ERR_FAIL_COND_V(divisor_idx < 0, -1);
Vector<int> faces_over;
Vector<int> faces_under;
- Plane divisor_plane=p_faces[ indices[divisor_idx] ].get_plane();
+ Plane divisor_plane = p_faces[indices[divisor_idx]].get_plane();
- for (int i=0;i<ic;i++) {
+ for (int i = 0; i < ic; i++) {
- if (i==divisor_idx)
+ if (i == divisor_idx)
continue;
- const Face3& f=p_faces[ indices[i] ];
+ const Face3 &f = p_faces[indices[i]];
/*
if (f.get_plane().is_almost_like(divisor_plane))
continue;
*/
- int over_count=0;
- int under_count=0;
+ int over_count = 0;
+ int under_count = 0;
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
real_t d = divisor_plane.distance_to(f.vertex[j]);
- if (Math::abs(d)>p_tolerance) {
+ if (Math::abs(d) > p_tolerance) {
if (d > 0)
over_count++;
@@ -411,183 +390,169 @@ static int _bsp_create_node(const Face3 *p_faces,const Vector<int>& p_indices,Ve
}
if (over_count)
- faces_over.push_back( indices[i] );
+ faces_over.push_back(indices[i]);
if (under_count)
- faces_under.push_back( indices[i] );
-
+ faces_under.push_back(indices[i]);
}
+ uint16_t over_idx = BSP_Tree::OVER_LEAF, under_idx = BSP_Tree::UNDER_LEAF;
+ if (faces_over.size() > 0) { //have facess above?
- uint16_t over_idx=BSP_Tree::OVER_LEAF,under_idx=BSP_Tree::UNDER_LEAF;
-
- if (faces_over.size()>0) { //have facess above?
-
- int idx = _bsp_create_node( p_faces, faces_over, p_planes, p_nodes,p_tolerance );
- if (idx>=0)
- over_idx=idx;
+ int idx = _bsp_create_node(p_faces, faces_over, p_planes, p_nodes, p_tolerance);
+ if (idx >= 0)
+ over_idx = idx;
}
- if (faces_under.size()>0) { //have facess above?
+ if (faces_under.size() > 0) { //have facess above?
- int idx = _bsp_create_node( p_faces,faces_under, p_planes, p_nodes,p_tolerance );
- if (idx>=0)
- under_idx=idx;
+ int idx = _bsp_create_node(p_faces, faces_under, p_planes, p_nodes, p_tolerance);
+ if (idx >= 0)
+ under_idx = idx;
}
/* Create the node */
// find existing divisor plane
- int divisor_plane_idx=-1;
-
+ int divisor_plane_idx = -1;
- for (int i=0;i<p_planes.size();i++) {
+ for (int i = 0; i < p_planes.size(); i++) {
- if (p_planes[i].is_almost_like( divisor_plane )) {
- divisor_plane_idx=i;
+ if (p_planes[i].is_almost_like(divisor_plane)) {
+ divisor_plane_idx = i;
break;
}
}
- if (divisor_plane_idx==-1) {
+ if (divisor_plane_idx == -1) {
- ERR_FAIL_COND_V( p_planes.size() == BSP_Tree::MAX_PLANES, -1 );
- divisor_plane_idx=p_planes.size();
- p_planes.push_back( divisor_plane );
+ ERR_FAIL_COND_V(p_planes.size() == BSP_Tree::MAX_PLANES, -1);
+ divisor_plane_idx = p_planes.size();
+ p_planes.push_back(divisor_plane);
}
BSP_Tree::Node node;
- node.plane=divisor_plane_idx;
- node.under=under_idx;
- node.over=over_idx;
+ node.plane = divisor_plane_idx;
+ node.under = under_idx;
+ node.over = over_idx;
p_nodes.push_back(node);
- return p_nodes.size()-1;
+ return p_nodes.size() - 1;
}
-
BSP_Tree::operator Variant() const {
-
Dictionary d;
- d["error_radius"]=error_radius;
+ d["error_radius"] = error_radius;
Vector<real_t> plane_values;
- plane_values.resize(planes.size()*4);
+ plane_values.resize(planes.size() * 4);
- for(int i=0;i<planes.size();i++) {
+ for (int i = 0; i < planes.size(); i++) {
- plane_values[i*4+0]=planes[i].normal.x;
- plane_values[i*4+1]=planes[i].normal.y;
- plane_values[i*4+2]=planes[i].normal.z;
- plane_values[i*4+3]=planes[i].d;
+ plane_values[i * 4 + 0] = planes[i].normal.x;
+ plane_values[i * 4 + 1] = planes[i].normal.y;
+ plane_values[i * 4 + 2] = planes[i].normal.z;
+ plane_values[i * 4 + 3] = planes[i].d;
}
- d["planes"]=plane_values;
+ d["planes"] = plane_values;
PoolVector<int> dst_nodes;
- dst_nodes.resize(nodes.size()*3);
+ dst_nodes.resize(nodes.size() * 3);
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
- dst_nodes.set(i*3+0,nodes[i].over);
- dst_nodes.set(i*3+1,nodes[i].under);
- dst_nodes.set(i*3+2,nodes[i].plane);
+ dst_nodes.set(i * 3 + 0, nodes[i].over);
+ dst_nodes.set(i * 3 + 1, nodes[i].under);
+ dst_nodes.set(i * 3 + 2, nodes[i].plane);
}
-
- d["nodes"]=dst_nodes;
+ d["nodes"] = dst_nodes;
d["aabb"] = aabb;
return Variant(d);
}
BSP_Tree::BSP_Tree() {
-
}
+BSP_Tree::BSP_Tree(const Variant &p_variant) {
-BSP_Tree::BSP_Tree(const Variant& p_variant) {
-
- Dictionary d=p_variant;
+ Dictionary d = p_variant;
ERR_FAIL_COND(!d.has("nodes"));
ERR_FAIL_COND(!d.has("planes"));
ERR_FAIL_COND(!d.has("aabb"));
ERR_FAIL_COND(!d.has("error_radius"));
PoolVector<int> src_nodes = d["nodes"];
- ERR_FAIL_COND(src_nodes.size()%3);
+ ERR_FAIL_COND(src_nodes.size() % 3);
+ if (d["planes"].get_type() == Variant::POOL_REAL_ARRAY) {
- if (d["planes"].get_type()==Variant::POOL_REAL_ARRAY) {
-
- PoolVector<real_t> src_planes=d["planes"];
- int plane_count=src_planes.size();
- ERR_FAIL_COND(plane_count%4);
- planes.resize(plane_count/4);
+ PoolVector<real_t> src_planes = d["planes"];
+ int plane_count = src_planes.size();
+ ERR_FAIL_COND(plane_count % 4);
+ planes.resize(plane_count / 4);
if (plane_count) {
PoolVector<real_t>::Read r = src_planes.read();
- for(int i=0;i<plane_count/4;i++) {
+ for (int i = 0; i < plane_count / 4; i++) {
- planes[i].normal.x=r[i*4+0];
- planes[i].normal.y=r[i*4+1];
- planes[i].normal.z=r[i*4+2];
- planes[i].d=r[i*4+3];
+ planes[i].normal.x = r[i * 4 + 0];
+ planes[i].normal.y = r[i * 4 + 1];
+ planes[i].normal.z = r[i * 4 + 2];
+ planes[i].d = r[i * 4 + 3];
}
}
-
} else {
planes = d["planes"];
}
-
error_radius = d["error"];
aabb = d["aabb"];
//int node_count = src_nodes.size();
- nodes.resize(src_nodes.size()/3);
+ nodes.resize(src_nodes.size() / 3);
PoolVector<int>::Read r = src_nodes.read();
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
- nodes[i].over=r[i*3+0];
- nodes[i].under=r[i*3+1];
- nodes[i].plane=r[i*3+2];
+ nodes[i].over = r[i * 3 + 0];
+ nodes[i].under = r[i * 3 + 1];
+ nodes[i].plane = r[i * 3 + 2];
}
-
}
-BSP_Tree::BSP_Tree(const PoolVector<Face3>& p_faces,real_t p_error_radius) {
+BSP_Tree::BSP_Tree(const PoolVector<Face3> &p_faces, real_t p_error_radius) {
// compute aabb
- int face_count=p_faces.size();
- PoolVector<Face3>::Read faces_r=p_faces.read();
+ int face_count = p_faces.size();
+ PoolVector<Face3>::Read faces_r = p_faces.read();
const Face3 *facesptr = faces_r.ptr();
-
- bool first=true;
+ bool first = true;
Vector<int> indices;
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- const Face3& f=facesptr[i];
+ const Face3 &f = facesptr[i];
if (f.is_degenerate())
continue;
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
if (first) {
- aabb.pos=f.vertex[0];
- first=false;
+ aabb.pos = f.vertex[0];
+ first = false;
} else {
aabb.expand_to(f.vertex[j]);
@@ -595,36 +560,29 @@ BSP_Tree::BSP_Tree(const PoolVector<Face3>& p_faces,real_t p_error_radius) {
}
indices.push_back(i);
-
}
- ERR_FAIL_COND( aabb.has_no_area() );
+ ERR_FAIL_COND(aabb.has_no_area());
- int top = _bsp_create_node(faces_r.ptr(),indices,planes,nodes,aabb.get_longest_axis_size()*0.0001);
+ int top = _bsp_create_node(faces_r.ptr(), indices, planes, nodes, aabb.get_longest_axis_size() * 0.0001);
- if (top<0) {
+ if (top < 0) {
nodes.clear();
planes.clear();
- ERR_FAIL_COND( top < 0 );
+ ERR_FAIL_COND(top < 0);
}
-
-
-
- error_radius=p_error_radius;
+ error_radius = p_error_radius;
}
-BSP_Tree::BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3& p_aabb,real_t p_error_radius) {
-
- nodes=p_nodes;
- planes=p_planes;
- aabb=p_aabb;
- error_radius=p_error_radius;
+BSP_Tree::BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3 &p_aabb, real_t p_error_radius) {
+ nodes = p_nodes;
+ planes = p_planes;
+ aabb = p_aabb;
+ error_radius = p_error_radius;
}
BSP_Tree::~BSP_Tree() {
-
-
}
diff --git a/core/math/bsp_tree.h b/core/math/bsp_tree.h
index c0071438db..4cfac35a2c 100644
--- a/core/math/bsp_tree.h
+++ b/core/math/bsp_tree.h
@@ -29,25 +29,24 @@
#ifndef BSP_TREE_H
#define BSP_TREE_H
+#include "dvector.h"
+#include "face3.h"
+#include "method_ptrcall.h"
#include "plane.h"
#include "rect3.h"
-#include "face3.h"
-#include "vector.h"
-#include "dvector.h"
#include "variant.h"
-#include "method_ptrcall.h"
+#include "vector.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class BSP_Tree {
public:
-
enum {
- UNDER_LEAF=0xFFFF,
- OVER_LEAF=0xFFFE,
- MAX_NODES=0xFFFE,
- MAX_PLANES=(1<<16)
+ UNDER_LEAF = 0xFFFF,
+ OVER_LEAF = 0xFFFE,
+ MAX_NODES = 0xFFFE,
+ MAX_PLANES = (1 << 16)
};
struct Node {
@@ -57,7 +56,6 @@ public:
uint16_t over;
};
-
private:
// thanks to the properties of Vector,
// this class can be assigned and passed around between threads
@@ -68,95 +66,90 @@ private:
Rect3 aabb;
real_t error_radius;
- int _get_points_inside(int p_node,const Vector3* p_points,int *p_indices, const Vector3& p_center,const Vector3& p_half_extents,int p_indices_count) const;
+ int _get_points_inside(int p_node, const Vector3 *p_points, int *p_indices, const Vector3 &p_center, const Vector3 &p_half_extents, int p_indices_count) const;
- template<class T>
- bool _test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const;
+ template <class T>
+ bool _test_convex(const Node *p_nodes, const Plane *p_planes, int p_current, const T &p_convex) const;
public:
-
- bool is_empty() const { return nodes.size()==0; }
+ bool is_empty() const { return nodes.size() == 0; }
Vector<Node> get_nodes() const;
Vector<Plane> get_planes() const;
Rect3 get_aabb() const;
- bool point_is_inside(const Vector3& p_point) const;
- int get_points_inside(const Vector3* p_points, int p_point_count) const;
- template<class T>
- bool convex_is_inside(const T& p_convex) const;
+ bool point_is_inside(const Vector3 &p_point) const;
+ int get_points_inside(const Vector3 *p_points, int p_point_count) const;
+ template <class T>
+ bool convex_is_inside(const T &p_convex) const;
operator Variant() const;
- void from_aabb(const Rect3& p_aabb);
+ void from_aabb(const Rect3 &p_aabb);
BSP_Tree();
- BSP_Tree(const Variant& p_variant);
- BSP_Tree(const PoolVector<Face3>& p_faces,real_t p_error_radius=0);
- BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3& p_aabb,real_t p_error_radius=0);
+ BSP_Tree(const Variant &p_variant);
+ BSP_Tree(const PoolVector<Face3> &p_faces, real_t p_error_radius = 0);
+ BSP_Tree(const Vector<Node> &p_nodes, const Vector<Plane> &p_planes, const Rect3 &p_aabb, real_t p_error_radius = 0);
~BSP_Tree();
-
};
-template<class T>
-bool BSP_Tree::_test_convex(const Node* p_nodes, const Plane* p_planes,int p_current, const T& p_convex) const {
+template <class T>
+bool BSP_Tree::_test_convex(const Node *p_nodes, const Plane *p_planes, int p_current, const T &p_convex) const {
- if (p_current==UNDER_LEAF)
+ if (p_current == UNDER_LEAF)
return true;
- else if (p_current==OVER_LEAF)
+ else if (p_current == OVER_LEAF)
return false;
- bool collided=false;
- const Node&n=p_nodes[p_current];
+ bool collided = false;
+ const Node &n = p_nodes[p_current];
- const Plane& p=p_planes[n.plane];
+ const Plane &p = p_planes[n.plane];
- real_t min,max;
- p_convex.project_range(p.normal,min,max);
+ real_t min, max;
+ p_convex.project_range(p.normal, min, max);
bool go_under = min < p.d;
bool go_over = max >= p.d;
- if (go_under && _test_convex(p_nodes,p_planes,n.under,p_convex))
- collided=true;
- if (go_over && _test_convex(p_nodes,p_planes,n.over,p_convex))
- collided=true;
+ if (go_under && _test_convex(p_nodes, p_planes, n.under, p_convex))
+ collided = true;
+ if (go_over && _test_convex(p_nodes, p_planes, n.over, p_convex))
+ collided = true;
return collided;
-
}
-template<class T>
-bool BSP_Tree::convex_is_inside(const T& p_convex) const {
+template <class T>
+bool BSP_Tree::convex_is_inside(const T &p_convex) const {
int node_count = nodes.size();
- if (node_count==0)
+ if (node_count == 0)
return false;
- const Node* nodes=&this->nodes[0];
- const Plane* planes = &this->planes[0];
+ const Node *nodes = &this->nodes[0];
+ const Plane *planes = &this->planes[0];
- return _test_convex(nodes,planes,node_count-1,p_convex);
+ return _test_convex(nodes, planes, node_count - 1, p_convex);
}
-
#ifdef PTRCALL_ENABLED
-
-template<>
+template <>
struct PtrToArg<BSP_Tree> {
- _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) {
- BSP_Tree s( Variant( *reinterpret_cast<const Dictionary*>(p_ptr) ) );
+ _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) {
+ BSP_Tree s(Variant(*reinterpret_cast<const Dictionary *>(p_ptr)));
return s;
}
- _FORCE_INLINE_ static void encode(BSP_Tree p_val,void* p_ptr) {
- Dictionary *d = reinterpret_cast<Dictionary*>(p_ptr);
- *d=Variant(p_val);
+ _FORCE_INLINE_ static void encode(BSP_Tree p_val, void *p_ptr) {
+ Dictionary *d = reinterpret_cast<Dictionary *>(p_ptr);
+ *d = Variant(p_val);
}
};
-template<>
-struct PtrToArg<const BSP_Tree&> {
- _FORCE_INLINE_ static BSP_Tree convert(const void* p_ptr) {
- BSP_Tree s( Variant( *reinterpret_cast<const Dictionary*>(p_ptr) ) );
+template <>
+struct PtrToArg<const BSP_Tree &> {
+ _FORCE_INLINE_ static BSP_Tree convert(const void *p_ptr) {
+ BSP_Tree s(Variant(*reinterpret_cast<const Dictionary *>(p_ptr)));
return s;
}
};
diff --git a/core/math/camera_matrix.cpp b/core/math/camera_matrix.cpp
index 3b47a75c65..227f586c43 100644
--- a/core/math/camera_matrix.cpp
+++ b/core/math/camera_matrix.cpp
@@ -32,29 +32,27 @@
void CameraMatrix::set_identity() {
- for (int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- for (int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- matrix[i][j]=(i==j)?1:0;
+ matrix[i][j] = (i == j) ? 1 : 0;
}
}
}
-
void CameraMatrix::set_zero() {
- for (int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- for (int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- matrix[i][j]=0;
+ matrix[i][j] = 0;
}
}
}
-
-Plane CameraMatrix::xform4(const Plane& p_vec4) const {
+Plane CameraMatrix::xform4(const Plane &p_vec4) const {
Plane ret;
@@ -65,11 +63,10 @@ Plane CameraMatrix::xform4(const Plane& p_vec4) const {
return ret;
}
-void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far,bool p_flip_fov) {
+void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov) {
if (p_flip_fov) {
- p_fovy_degrees=get_fovy(p_fovy_degrees,1.0/p_aspect);
-
+ p_fovy_degrees = get_fovy(p_fovy_degrees, 1.0 / p_aspect);
}
real_t sine, cotangent, deltaZ;
@@ -78,8 +75,8 @@ void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_
deltaZ = p_z_far - p_z_near;
sine = Math::sin(radians);
- if ((deltaZ == 0) || (sine == 0) || (p_aspect == 0)) {
- return ;
+ if ((deltaZ == 0) || (sine == 0) || (p_aspect == 0)) {
+ return;
}
cotangent = Math::cos(radians) / sine;
@@ -91,35 +88,30 @@ void CameraMatrix::set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_
matrix[2][3] = -1;
matrix[3][2] = -2 * p_z_near * p_z_far / deltaZ;
matrix[3][3] = 0;
-
}
-void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar) {
-
+void CameraMatrix::set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar) {
set_identity();
- matrix[0][0] = 2.0/(p_right-p_left);
- matrix[3][0] = -((p_right+p_left)/(p_right-p_left));
- matrix[1][1] = 2.0/(p_top-p_bottom);
- matrix[3][1] = -((p_top+p_bottom)/(p_top-p_bottom));
- matrix[2][2] = -2.0/(p_zfar-p_znear);
- matrix[3][2] = -((p_zfar+p_znear)/(p_zfar-p_znear));
+ matrix[0][0] = 2.0 / (p_right - p_left);
+ matrix[3][0] = -((p_right + p_left) / (p_right - p_left));
+ matrix[1][1] = 2.0 / (p_top - p_bottom);
+ matrix[3][1] = -((p_top + p_bottom) / (p_top - p_bottom));
+ matrix[2][2] = -2.0 / (p_zfar - p_znear);
+ matrix[3][2] = -((p_zfar + p_znear) / (p_zfar - p_znear));
matrix[3][3] = 1.0;
-
}
-void CameraMatrix::set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar,bool p_flip_fov) {
+void CameraMatrix::set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar, bool p_flip_fov) {
if (!p_flip_fov) {
- p_size*=p_aspect;
+ p_size *= p_aspect;
}
- set_orthogonal(-p_size/2,+p_size/2,-p_size/p_aspect/2,+p_size/p_aspect/2,p_znear,p_zfar);
+ set_orthogonal(-p_size / 2, +p_size / 2, -p_size / p_aspect / 2, +p_size / p_aspect / 2, p_znear, p_zfar);
}
-
-
void CameraMatrix::set_frustum(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t p_far) {
#if 0
///@TODO, give a check to this. I'm not sure if it's working.
@@ -135,13 +127,13 @@ void CameraMatrix::set_frustum(real_t p_left, real_t p_right, real_t p_bottom, r
matrix[3][3]=0;
#else
real_t *te = &matrix[0][0];
- real_t x = 2 * p_near / ( p_right - p_left );
- real_t y = 2 * p_near / ( p_top - p_bottom );
+ real_t x = 2 * p_near / (p_right - p_left);
+ real_t y = 2 * p_near / (p_top - p_bottom);
- real_t a = ( p_right + p_left ) / ( p_right - p_left );
- real_t b = ( p_top + p_bottom ) / ( p_top - p_bottom );
- real_t c = - ( p_far + p_near ) / ( p_far - p_near );
- real_t d = - 2 * p_far * p_near / ( p_far - p_near );
+ real_t a = (p_right + p_left) / (p_right - p_left);
+ real_t b = (p_top + p_bottom) / (p_top - p_bottom);
+ real_t c = -(p_far + p_near) / (p_far - p_near);
+ real_t d = -2 * p_far * p_near / (p_far - p_near);
te[0] = x;
te[1] = 0;
@@ -161,120 +153,117 @@ void CameraMatrix::set_frustum(real_t p_left, real_t p_right, real_t p_bottom, r
te[15] = 0;
#endif
-
}
-
-
real_t CameraMatrix::get_z_far() const {
- const real_t * matrix = (const real_t*)this->matrix;
- Plane new_plane=Plane(matrix[ 3] - matrix[ 2],
- matrix[ 7] - matrix[ 6],
- matrix[11] - matrix[10],
- matrix[15] - matrix[14]);
+ const real_t *matrix = (const real_t *)this->matrix;
+ Plane new_plane = Plane(matrix[3] - matrix[2],
+ matrix[7] - matrix[6],
+ matrix[11] - matrix[10],
+ matrix[15] - matrix[14]);
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
return new_plane.d;
}
real_t CameraMatrix::get_z_near() const {
- const real_t * matrix = (const real_t*)this->matrix;
- Plane new_plane=Plane(matrix[ 3] + matrix[ 2],
- matrix[ 7] + matrix[ 6],
- matrix[11] + matrix[10],
- -matrix[15] - matrix[14]);
+ const real_t *matrix = (const real_t *)this->matrix;
+ Plane new_plane = Plane(matrix[3] + matrix[2],
+ matrix[7] + matrix[6],
+ matrix[11] + matrix[10],
+ -matrix[15] - matrix[14]);
new_plane.normalize();
return new_plane.d;
}
-void CameraMatrix::get_viewport_size(real_t& r_width, real_t& r_height) const {
+void CameraMatrix::get_viewport_size(real_t &r_width, real_t &r_height) const {
- const real_t * matrix = (const real_t*)this->matrix;
+ const real_t *matrix = (const real_t *)this->matrix;
///////--- Near Plane ---///////
- Plane near_plane=Plane(matrix[ 3] + matrix[ 2],
- matrix[ 7] + matrix[ 6],
- matrix[11] + matrix[10],
+ Plane near_plane = Plane(matrix[3] + matrix[2],
+ matrix[7] + matrix[6],
+ matrix[11] + matrix[10],
-matrix[15] - matrix[14]);
near_plane.normalize();
///////--- Right Plane ---///////
- Plane right_plane=Plane(matrix[ 3] - matrix[ 0],
- matrix[ 7] - matrix[ 4],
- matrix[11] - matrix[ 8],
- - matrix[15] + matrix[12]);
+ Plane right_plane = Plane(matrix[3] - matrix[0],
+ matrix[7] - matrix[4],
+ matrix[11] - matrix[8],
+ -matrix[15] + matrix[12]);
right_plane.normalize();
- Plane top_plane=Plane(matrix[ 3] - matrix[ 1],
- matrix[ 7] - matrix[ 5],
- matrix[11] - matrix[ 9],
+ Plane top_plane = Plane(matrix[3] - matrix[1],
+ matrix[7] - matrix[5],
+ matrix[11] - matrix[9],
-matrix[15] + matrix[13]);
top_plane.normalize();
Vector3 res;
- near_plane.intersect_3(right_plane,top_plane,&res);
+ near_plane.intersect_3(right_plane, top_plane, &res);
- r_width=res.x;
- r_height=res.y;
+ r_width = res.x;
+ r_height = res.y;
}
-bool CameraMatrix::get_endpoints(const Transform& p_transform, Vector3 *p_8points) const {
+bool CameraMatrix::get_endpoints(const Transform &p_transform, Vector3 *p_8points) const {
- const real_t * matrix = (const real_t*)this->matrix;
+ const real_t *matrix = (const real_t *)this->matrix;
///////--- Near Plane ---///////
- Plane near_plane=Plane(matrix[ 3] + matrix[ 2],
- matrix[ 7] + matrix[ 6],
- matrix[11] + matrix[10],
+ Plane near_plane = Plane(matrix[3] + matrix[2],
+ matrix[7] + matrix[6],
+ matrix[11] + matrix[10],
-matrix[15] - matrix[14]);
near_plane.normalize();
///////--- Far Plane ---///////
- Plane far_plane=Plane(matrix[ 2] - matrix[ 3],
- matrix[ 6] - matrix[ 7],
- matrix[10] - matrix[11],
- matrix[15] - matrix[14]);
+ Plane far_plane = Plane(matrix[2] - matrix[3],
+ matrix[6] - matrix[7],
+ matrix[10] - matrix[11],
+ matrix[15] - matrix[14]);
far_plane.normalize();
///////--- Right Plane ---///////
- Plane right_plane=Plane(matrix[ 0] - matrix[ 3],
- matrix[ 4] - matrix[ 7],
- matrix[8] - matrix[ 11],
- - matrix[15] + matrix[12]);
+ Plane right_plane = Plane(matrix[0] - matrix[3],
+ matrix[4] - matrix[7],
+ matrix[8] - matrix[11],
+ -matrix[15] + matrix[12]);
right_plane.normalize();
///////--- Top Plane ---///////
- Plane top_plane=Plane(matrix[ 1] - matrix[ 3],
- matrix[ 5] - matrix[ 7],
- matrix[9] - matrix[ 11],
+ Plane top_plane = Plane(matrix[1] - matrix[3],
+ matrix[5] - matrix[7],
+ matrix[9] - matrix[11],
-matrix[15] + matrix[13]);
top_plane.normalize();
Vector3 near_endpoint;
Vector3 far_endpoint;
- bool res=near_plane.intersect_3(right_plane,top_plane,&near_endpoint);
- ERR_FAIL_COND_V(!res,false);
+ bool res = near_plane.intersect_3(right_plane, top_plane, &near_endpoint);
+ ERR_FAIL_COND_V(!res, false);
- res=far_plane.intersect_3(right_plane,top_plane,&far_endpoint);
- ERR_FAIL_COND_V(!res,false);
+ res = far_plane.intersect_3(right_plane, top_plane, &far_endpoint);
+ ERR_FAIL_COND_V(!res, false);
- p_8points[0]=p_transform.xform( Vector3( near_endpoint.x, near_endpoint.y, near_endpoint.z ) );
- p_8points[1]=p_transform.xform( Vector3( near_endpoint.x,-near_endpoint.y, near_endpoint.z ) );
- p_8points[2]=p_transform.xform( Vector3(-near_endpoint.x, near_endpoint.y, near_endpoint.z ) );
- p_8points[3]=p_transform.xform( Vector3(-near_endpoint.x,-near_endpoint.y, near_endpoint.z ) );
- p_8points[4]=p_transform.xform( Vector3( far_endpoint.x, far_endpoint.y, far_endpoint.z ) );
- p_8points[5]=p_transform.xform( Vector3( far_endpoint.x,-far_endpoint.y, far_endpoint.z ) );
- p_8points[6]=p_transform.xform( Vector3(-far_endpoint.x, far_endpoint.y, far_endpoint.z ) );
- p_8points[7]=p_transform.xform( Vector3(-far_endpoint.x,-far_endpoint.y, far_endpoint.z ) );
+ p_8points[0] = p_transform.xform(Vector3(near_endpoint.x, near_endpoint.y, near_endpoint.z));
+ p_8points[1] = p_transform.xform(Vector3(near_endpoint.x, -near_endpoint.y, near_endpoint.z));
+ p_8points[2] = p_transform.xform(Vector3(-near_endpoint.x, near_endpoint.y, near_endpoint.z));
+ p_8points[3] = p_transform.xform(Vector3(-near_endpoint.x, -near_endpoint.y, near_endpoint.z));
+ p_8points[4] = p_transform.xform(Vector3(far_endpoint.x, far_endpoint.y, far_endpoint.z));
+ p_8points[5] = p_transform.xform(Vector3(far_endpoint.x, -far_endpoint.y, far_endpoint.z));
+ p_8points[6] = p_transform.xform(Vector3(-far_endpoint.x, far_endpoint.y, far_endpoint.z));
+ p_8points[7] = p_transform.xform(Vector3(-far_endpoint.x, -far_endpoint.y, far_endpoint.z));
return true;
}
-Vector<Plane> CameraMatrix::get_projection_planes(const Transform& p_transform) const {
+Vector<Plane> CameraMatrix::get_projection_planes(const Transform &p_transform) const {
/** Fast Plane Extraction from combined modelview/projection matrices.
* References:
@@ -284,88 +273,79 @@ Vector<Plane> CameraMatrix::get_projection_planes(const Transform& p_transform)
Vector<Plane> planes;
- const real_t * matrix = (const real_t*)this->matrix;
+ const real_t *matrix = (const real_t *)this->matrix;
Plane new_plane;
///////--- Near Plane ---///////
- new_plane=Plane(matrix[ 3] + matrix[ 2],
- matrix[ 7] + matrix[ 6],
- matrix[11] + matrix[10],
- matrix[15] + matrix[14]);
+ new_plane = Plane(matrix[3] + matrix[2],
+ matrix[7] + matrix[6],
+ matrix[11] + matrix[10],
+ matrix[15] + matrix[14]);
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
+ planes.push_back(p_transform.xform(new_plane));
///////--- Far Plane ---///////
- new_plane=Plane(matrix[ 3] - matrix[ 2],
- matrix[ 7] - matrix[ 6],
- matrix[11] - matrix[10],
- matrix[15] - matrix[14]);
+ new_plane = Plane(matrix[3] - matrix[2],
+ matrix[7] - matrix[6],
+ matrix[11] - matrix[10],
+ matrix[15] - matrix[14]);
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
-
+ planes.push_back(p_transform.xform(new_plane));
///////--- Left Plane ---///////
- new_plane=Plane(matrix[ 3] + matrix[ 0],
- matrix[ 7] + matrix[ 4],
- matrix[11] + matrix[ 8],
- matrix[15] + matrix[12]);
+ new_plane = Plane(matrix[3] + matrix[0],
+ matrix[7] + matrix[4],
+ matrix[11] + matrix[8],
+ matrix[15] + matrix[12]);
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
-
+ planes.push_back(p_transform.xform(new_plane));
///////--- Top Plane ---///////
- new_plane=Plane(matrix[ 3] - matrix[ 1],
- matrix[ 7] - matrix[ 5],
- matrix[11] - matrix[ 9],
- matrix[15] - matrix[13]);
+ new_plane = Plane(matrix[3] - matrix[1],
+ matrix[7] - matrix[5],
+ matrix[11] - matrix[9],
+ matrix[15] - matrix[13]);
-
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
-
+ planes.push_back(p_transform.xform(new_plane));
///////--- Right Plane ---///////
- new_plane=Plane(matrix[ 3] - matrix[ 0],
- matrix[ 7] - matrix[ 4],
- matrix[11] - matrix[ 8],
- matrix[15] - matrix[12]);
+ new_plane = Plane(matrix[3] - matrix[0],
+ matrix[7] - matrix[4],
+ matrix[11] - matrix[8],
+ matrix[15] - matrix[12]);
-
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
-
+ planes.push_back(p_transform.xform(new_plane));
///////--- Bottom Plane ---///////
- new_plane=Plane(matrix[ 3] + matrix[ 1],
- matrix[ 7] + matrix[ 5],
- matrix[11] + matrix[ 9],
- matrix[15] + matrix[13]);
+ new_plane = Plane(matrix[3] + matrix[1],
+ matrix[7] + matrix[5],
+ matrix[11] + matrix[9],
+ matrix[15] + matrix[13]);
-
- new_plane.normal=-new_plane.normal;
+ new_plane.normal = -new_plane.normal;
new_plane.normalize();
- planes.push_back( p_transform.xform(new_plane) );
+ planes.push_back(p_transform.xform(new_plane));
return planes;
}
-
-
CameraMatrix CameraMatrix::inverse() const {
CameraMatrix cm = *this;
@@ -375,98 +355,96 @@ CameraMatrix CameraMatrix::inverse() const {
void CameraMatrix::invert() {
- int i,j,k;
- int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */
- real_t pvt_val; /* Value of current pivot element */
- real_t hold; /* Temporary storage */
- real_t determinat; /* Determinant */
+ int i, j, k;
+ int pvt_i[4], pvt_j[4]; /* Locations of pivot matrix */
+ real_t pvt_val; /* Value of current pivot element */
+ real_t hold; /* Temporary storage */
+ real_t determinat; /* Determinant */
determinat = 1.0;
- for (k=0; k<4; k++) {
+ for (k = 0; k < 4; k++) {
/** Locate k'th pivot element **/
- pvt_val=matrix[k][k]; /** Initialize for search **/
- pvt_i[k]=k;
- pvt_j[k]=k;
- for (i=k; i<4; i++) {
- for (j=k; j<4; j++) {
+ pvt_val = matrix[k][k]; /** Initialize for search **/
+ pvt_i[k] = k;
+ pvt_j[k] = k;
+ for (i = k; i < 4; i++) {
+ for (j = k; j < 4; j++) {
if (Math::absd(matrix[i][j]) > Math::absd(pvt_val)) {
- pvt_i[k]=i;
- pvt_j[k]=j;
- pvt_val=matrix[i][j];
+ pvt_i[k] = i;
+ pvt_j[k] = j;
+ pvt_val = matrix[i][j];
}
}
}
/** Product of pivots, gives determinant when finished **/
- determinat*=pvt_val;
- if (Math::absd(determinat)<1e-7) {
+ determinat *= pvt_val;
+ if (Math::absd(determinat) < 1e-7) {
return; //(false); /** Matrix is singular (zero determinant). **/
}
/** "Interchange" rows (with sign change stuff) **/
- i=pvt_i[k];
- if (i!=k) { /** If rows are different **/
- for (j=0; j<4; j++) {
- hold=-matrix[k][j];
- matrix[k][j]=matrix[i][j];
- matrix[i][j]=hold;
+ i = pvt_i[k];
+ if (i != k) { /** If rows are different **/
+ for (j = 0; j < 4; j++) {
+ hold = -matrix[k][j];
+ matrix[k][j] = matrix[i][j];
+ matrix[i][j] = hold;
}
}
/** "Interchange" columns **/
- j=pvt_j[k];
- if (j!=k) { /** If columns are different **/
- for (i=0; i<4; i++) {
- hold=-matrix[i][k];
- matrix[i][k]=matrix[i][j];
- matrix[i][j]=hold;
+ j = pvt_j[k];
+ if (j != k) { /** If columns are different **/
+ for (i = 0; i < 4; i++) {
+ hold = -matrix[i][k];
+ matrix[i][k] = matrix[i][j];
+ matrix[i][j] = hold;
}
}
/** Divide column by minus pivot value **/
- for (i=0; i<4; i++) {
- if (i!=k) matrix[i][k]/=( -pvt_val) ;
+ for (i = 0; i < 4; i++) {
+ if (i != k) matrix[i][k] /= (-pvt_val);
}
/** Reduce the matrix **/
- for (i=0; i<4; i++) {
+ for (i = 0; i < 4; i++) {
hold = matrix[i][k];
- for (j=0; j<4; j++) {
- if (i!=k && j!=k) matrix[i][j]+=hold*matrix[k][j];
+ for (j = 0; j < 4; j++) {
+ if (i != k && j != k) matrix[i][j] += hold * matrix[k][j];
}
}
/** Divide row by pivot **/
- for (j=0; j<4; j++) {
- if (j!=k) matrix[k][j]/=pvt_val;
+ for (j = 0; j < 4; j++) {
+ if (j != k) matrix[k][j] /= pvt_val;
}
/** Replace pivot by reciprocal (at last we can touch it). **/
- matrix[k][k] = 1.0/pvt_val;
+ matrix[k][k] = 1.0 / pvt_val;
}
/* That was most of the work, one final pass of row/column interchange */
/* to finish */
- for (k=4-2; k>=0; k--) { /* Don't need to work with 1 by 1 corner*/
- i=pvt_j[k]; /* Rows to swap correspond to pivot COLUMN */
- if (i!=k) { /* If rows are different */
- for(j=0; j<4; j++) {
+ for (k = 4 - 2; k >= 0; k--) { /* Don't need to work with 1 by 1 corner*/
+ i = pvt_j[k]; /* Rows to swap correspond to pivot COLUMN */
+ if (i != k) { /* If rows are different */
+ for (j = 0; j < 4; j++) {
hold = matrix[k][j];
- matrix[k][j]=-matrix[i][j];
- matrix[i][j]=hold;
+ matrix[k][j] = -matrix[i][j];
+ matrix[i][j] = hold;
}
}
- j=pvt_i[k]; /* Columns to swap correspond to pivot ROW */
- if (j!=k) /* If columns are different */
- for (i=0; i<4; i++) {
- hold=matrix[i][k];
- matrix[i][k]=-matrix[i][j];
- matrix[i][j]=hold;
+ j = pvt_i[k]; /* Columns to swap correspond to pivot ROW */
+ if (j != k) /* If columns are different */
+ for (i = 0; i < 4; i++) {
+ hold = matrix[i][k];
+ matrix[i][k] = -matrix[i][j];
+ matrix[i][j] = hold;
}
}
-
-
}
CameraMatrix::CameraMatrix() {
@@ -474,15 +452,15 @@ CameraMatrix::CameraMatrix() {
set_identity();
}
-CameraMatrix CameraMatrix::operator*(const CameraMatrix& p_matrix) const {
+CameraMatrix CameraMatrix::operator*(const CameraMatrix &p_matrix) const {
CameraMatrix new_matrix;
- for( int j = 0; j < 4; j++ ) {
- for( int i = 0; i < 4; i++ ) {
+ for (int j = 0; j < 4; j++) {
+ for (int i = 0; i < 4; i++) {
real_t ab = 0;
- for( int k = 0; k < 4; k++ )
- ab += matrix[k][i] * p_matrix.matrix[j][k] ;
+ for (int k = 0; k < 4; k++)
+ ab += matrix[k][i] * p_matrix.matrix[j][k];
new_matrix.matrix[j][i] = ab;
}
}
@@ -492,173 +470,164 @@ CameraMatrix CameraMatrix::operator*(const CameraMatrix& p_matrix) const {
void CameraMatrix::set_light_bias() {
- real_t *m=&matrix[0][0];
-
- m[0]=0.5,
- m[1]=0.0,
- m[2]=0.0,
- m[3]=0.0,
- m[4]=0.0,
- m[5]=0.5,
- m[6]=0.0,
- m[7]=0.0,
- m[8]=0.0,
- m[9]=0.0,
- m[10]=0.5,
- m[11]=0.0,
- m[12]=0.5,
- m[13]=0.5,
- m[14]=0.5,
- m[15]=1.0;
-
+ real_t *m = &matrix[0][0];
+
+ m[0] = 0.5,
+ m[1] = 0.0,
+ m[2] = 0.0,
+ m[3] = 0.0,
+ m[4] = 0.0,
+ m[5] = 0.5,
+ m[6] = 0.0,
+ m[7] = 0.0,
+ m[8] = 0.0,
+ m[9] = 0.0,
+ m[10] = 0.5,
+ m[11] = 0.0,
+ m[12] = 0.5,
+ m[13] = 0.5,
+ m[14] = 0.5,
+ m[15] = 1.0;
}
-void CameraMatrix::set_light_atlas_rect(const Rect2& p_rect) {
-
- real_t *m=&matrix[0][0];
-
- m[0]=p_rect.size.width,
- m[1]=0.0,
- m[2]=0.0,
- m[3]=0.0,
- m[4]=0.0,
- m[5]=p_rect.size.height,
- m[6]=0.0,
- m[7]=0.0,
- m[8]=0.0,
- m[9]=0.0,
- m[10]=1.0,
- m[11]=0.0,
- m[12]=p_rect.pos.x,
- m[13]=p_rect.pos.y,
- m[14]=0.0,
- m[15]=1.0;
+void CameraMatrix::set_light_atlas_rect(const Rect2 &p_rect) {
+
+ real_t *m = &matrix[0][0];
+
+ m[0] = p_rect.size.width,
+ m[1] = 0.0,
+ m[2] = 0.0,
+ m[3] = 0.0,
+ m[4] = 0.0,
+ m[5] = p_rect.size.height,
+ m[6] = 0.0,
+ m[7] = 0.0,
+ m[8] = 0.0,
+ m[9] = 0.0,
+ m[10] = 1.0,
+ m[11] = 0.0,
+ m[12] = p_rect.pos.x,
+ m[13] = p_rect.pos.y,
+ m[14] = 0.0,
+ m[15] = 1.0;
}
CameraMatrix::operator String() const {
String str;
- for (int i=0;i<4;i++)
- for (int j=0;j<4;j++)
- str+=String((j>0)?", ":"\n")+rtos(matrix[i][j]);
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ str += String((j > 0) ? ", " : "\n") + rtos(matrix[i][j]);
return str;
}
real_t CameraMatrix::get_aspect() const {
- real_t w,h;
- get_viewport_size(w,h);
- return w/h;
+ real_t w, h;
+ get_viewport_size(w, h);
+ return w / h;
}
int CameraMatrix::get_pixels_per_meter(int p_for_pixel_width) const {
-
- Vector3 result = xform(Vector3(1,0,-1));
+ Vector3 result = xform(Vector3(1, 0, -1));
return int((result.x * 0.5 + 0.5) * p_for_pixel_width);
-
}
real_t CameraMatrix::get_fov() const {
- const real_t * matrix = (const real_t*)this->matrix;
+ const real_t *matrix = (const real_t *)this->matrix;
- Plane right_plane=Plane(matrix[ 3] - matrix[ 0],
- matrix[ 7] - matrix[ 4],
- matrix[11] - matrix[ 8],
- - matrix[15] + matrix[12]);
+ Plane right_plane = Plane(matrix[3] - matrix[0],
+ matrix[7] - matrix[4],
+ matrix[11] - matrix[8],
+ -matrix[15] + matrix[12]);
right_plane.normalize();
- return Math::rad2deg(Math::acos(Math::abs(right_plane.normal.x)))*2.0;
+ return Math::rad2deg(Math::acos(Math::abs(right_plane.normal.x))) * 2.0;
}
-
void CameraMatrix::make_scale(const Vector3 &p_scale) {
set_identity();
- matrix[0][0]=p_scale.x;
- matrix[1][1]=p_scale.y;
- matrix[2][2]=p_scale.z;
-
+ matrix[0][0] = p_scale.x;
+ matrix[1][1] = p_scale.y;
+ matrix[2][2] = p_scale.z;
}
-void CameraMatrix::scale_translate_to_fit(const Rect3& p_aabb) {
+void CameraMatrix::scale_translate_to_fit(const Rect3 &p_aabb) {
Vector3 min = p_aabb.pos;
- Vector3 max = p_aabb.pos+p_aabb.size;
-
-
- matrix[0][0]=2/(max.x-min.x);
- matrix[1][0]=0;
- matrix[2][0]=0;
- matrix[3][0]=-(max.x+min.x)/(max.x-min.x);
-
- matrix[0][1]=0;
- matrix[1][1]=2/(max.y-min.y);
- matrix[2][1]=0;
- matrix[3][1]=-(max.y+min.y)/(max.y-min.y);
-
- matrix[0][2]=0;
- matrix[1][2]=0;
- matrix[2][2]=2/(max.z-min.z);
- matrix[3][2]=-(max.z+min.z)/(max.z-min.z);
-
- matrix[0][3]=0;
- matrix[1][3]=0;
- matrix[2][3]=0;
- matrix[3][3]=1;
+ Vector3 max = p_aabb.pos + p_aabb.size;
+
+ matrix[0][0] = 2 / (max.x - min.x);
+ matrix[1][0] = 0;
+ matrix[2][0] = 0;
+ matrix[3][0] = -(max.x + min.x) / (max.x - min.x);
+
+ matrix[0][1] = 0;
+ matrix[1][1] = 2 / (max.y - min.y);
+ matrix[2][1] = 0;
+ matrix[3][1] = -(max.y + min.y) / (max.y - min.y);
+
+ matrix[0][2] = 0;
+ matrix[1][2] = 0;
+ matrix[2][2] = 2 / (max.z - min.z);
+ matrix[3][2] = -(max.z + min.z) / (max.z - min.z);
+
+ matrix[0][3] = 0;
+ matrix[1][3] = 0;
+ matrix[2][3] = 0;
+ matrix[3][3] = 1;
}
CameraMatrix::operator Transform() const {
Transform tr;
- const real_t *m=&matrix[0][0];
+ const real_t *m = &matrix[0][0];
- tr.basis.elements[0][0]=m[0];
- tr.basis.elements[1][0]=m[1];
- tr.basis.elements[2][0]=m[2];
+ tr.basis.elements[0][0] = m[0];
+ tr.basis.elements[1][0] = m[1];
+ tr.basis.elements[2][0] = m[2];
- tr.basis.elements[0][1]=m[4];
- tr.basis.elements[1][1]=m[5];
- tr.basis.elements[2][1]=m[6];
+ tr.basis.elements[0][1] = m[4];
+ tr.basis.elements[1][1] = m[5];
+ tr.basis.elements[2][1] = m[6];
- tr.basis.elements[0][2]=m[8];
- tr.basis.elements[1][2]=m[9];
- tr.basis.elements[2][2]=m[10];
+ tr.basis.elements[0][2] = m[8];
+ tr.basis.elements[1][2] = m[9];
+ tr.basis.elements[2][2] = m[10];
- tr.origin.x=m[12];
- tr.origin.y=m[13];
- tr.origin.z=m[14];
+ tr.origin.x = m[12];
+ tr.origin.y = m[13];
+ tr.origin.z = m[14];
return tr;
}
-CameraMatrix::CameraMatrix(const Transform& p_transform) {
+CameraMatrix::CameraMatrix(const Transform &p_transform) {
const Transform &tr = p_transform;
- real_t *m=&matrix[0][0];
-
- m[0]=tr.basis.elements[0][0];
- m[1]=tr.basis.elements[1][0];
- m[2]=tr.basis.elements[2][0];
- m[3]=0.0;
- m[4]=tr.basis.elements[0][1];
- m[5]=tr.basis.elements[1][1];
- m[6]=tr.basis.elements[2][1];
- m[7]=0.0;
- m[8]=tr.basis.elements[0][2];
- m[9]=tr.basis.elements[1][2];
- m[10]=tr.basis.elements[2][2];
- m[11]=0.0;
- m[12]=tr.origin.x;
- m[13]=tr.origin.y;
- m[14]=tr.origin.z;
- m[15]=1.0;
+ real_t *m = &matrix[0][0];
+
+ m[0] = tr.basis.elements[0][0];
+ m[1] = tr.basis.elements[1][0];
+ m[2] = tr.basis.elements[2][0];
+ m[3] = 0.0;
+ m[4] = tr.basis.elements[0][1];
+ m[5] = tr.basis.elements[1][1];
+ m[6] = tr.basis.elements[2][1];
+ m[7] = 0.0;
+ m[8] = tr.basis.elements[0][2];
+ m[9] = tr.basis.elements[1][2];
+ m[10] = tr.basis.elements[2][2];
+ m[11] = 0.0;
+ m[12] = tr.origin.x;
+ m[13] = tr.origin.y;
+ m[14] = tr.origin.z;
+ m[15] = 1.0;
}
-CameraMatrix::~CameraMatrix()
-{
+CameraMatrix::~CameraMatrix() {
}
-
-
diff --git a/core/math/camera_matrix.h b/core/math/camera_matrix.h
index c96f8259b5..857628c703 100644
--- a/core/math/camera_matrix.h
+++ b/core/math/camera_matrix.h
@@ -29,14 +29,12 @@
#ifndef CAMERA_MATRIX_H
#define CAMERA_MATRIX_H
-#include "transform.h"
#include "math_2d.h"
+#include "transform.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
struct CameraMatrix {
enum Planes {
@@ -48,21 +46,20 @@ struct CameraMatrix {
PLANE_BOTTOM
};
- real_t matrix[4][4];
-
+ real_t matrix[4][4];
void set_identity();
void set_zero();
void set_light_bias();
- void set_light_atlas_rect(const Rect2& p_rect);
- void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far,bool p_flip_fov=false);
- void set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar);
- void set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar,bool p_flip_fov=false);
+ void set_light_atlas_rect(const Rect2 &p_rect);
+ void set_perspective(real_t p_fovy_degrees, real_t p_aspect, real_t p_z_near, real_t p_z_far, bool p_flip_fov = false);
+ void set_orthogonal(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_znear, real_t p_zfar);
+ void set_orthogonal(real_t p_size, real_t p_aspect, real_t p_znear, real_t p_zfar, bool p_flip_fov = false);
void set_frustum(real_t p_left, real_t p_right, real_t p_bottom, real_t p_top, real_t p_near, real_t p_far);
- static real_t get_fovy(real_t p_fovx,real_t p_aspect) {
+ static real_t get_fovy(real_t p_fovx, real_t p_aspect) {
- return Math::rad2deg(Math::atan(p_aspect * Math::tan(Math::deg2rad(p_fovx) * 0.5))*2.0);
+ return Math::rad2deg(Math::atan(p_aspect * Math::tan(Math::deg2rad(p_fovx) * 0.5)) * 2.0);
}
real_t get_z_far() const;
@@ -70,40 +67,39 @@ struct CameraMatrix {
real_t get_aspect() const;
real_t get_fov() const;
- Vector<Plane> get_projection_planes(const Transform& p_transform) const;
+ Vector<Plane> get_projection_planes(const Transform &p_transform) const;
- bool get_endpoints(const Transform& p_transform,Vector3 *p_8points) const;
- void get_viewport_size(real_t& r_width, real_t& r_height) const;
+ bool get_endpoints(const Transform &p_transform, Vector3 *p_8points) const;
+ void get_viewport_size(real_t &r_width, real_t &r_height) const;
void invert();
CameraMatrix inverse() const;
- CameraMatrix operator*(const CameraMatrix& p_matrix) const;
+ CameraMatrix operator*(const CameraMatrix &p_matrix) const;
- Plane xform4(const Plane& p_vec4) const;
- _FORCE_INLINE_ Vector3 xform(const Vector3& p_vec3) const;
+ Plane xform4(const Plane &p_vec4) const;
+ _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vec3) const;
operator String() const;
- void scale_translate_to_fit(const Rect3& p_aabb);
+ void scale_translate_to_fit(const Rect3 &p_aabb);
void make_scale(const Vector3 &p_scale);
int get_pixels_per_meter(int p_for_pixel_width) const;
operator Transform() const;
CameraMatrix();
- CameraMatrix(const Transform& p_transform);
+ CameraMatrix(const Transform &p_transform);
~CameraMatrix();
-
};
-Vector3 CameraMatrix::xform(const Vector3& p_vec3) const {
+Vector3 CameraMatrix::xform(const Vector3 &p_vec3) const {
Vector3 ret;
ret.x = matrix[0][0] * p_vec3.x + matrix[1][0] * p_vec3.y + matrix[2][0] * p_vec3.z + matrix[3][0];
ret.y = matrix[0][1] * p_vec3.x + matrix[1][1] * p_vec3.y + matrix[2][1] * p_vec3.z + matrix[3][1];
ret.z = matrix[0][2] * p_vec3.x + matrix[1][2] * p_vec3.y + matrix[2][2] * p_vec3.z + matrix[3][2];
real_t w = matrix[0][3] * p_vec3.x + matrix[1][3] * p_vec3.y + matrix[2][3] * p_vec3.z + matrix[3][3];
- return ret/w;
+ return ret / w;
}
#endif
diff --git a/core/math/face3.cpp b/core/math/face3.cpp
index 60fab6748a..d9d99b0384 100644
--- a/core/math/face3.cpp
+++ b/core/math/face3.cpp
@@ -29,121 +29,112 @@
#include "face3.h"
#include "geometry.h"
-int Face3::split_by_plane(const Plane& p_plane,Face3 p_res[3],bool p_is_point_over[3]) const {
+int Face3::split_by_plane(const Plane &p_plane, Face3 p_res[3], bool p_is_point_over[3]) const {
- ERR_FAIL_COND_V(is_degenerate(),0);
+ ERR_FAIL_COND_V(is_degenerate(), 0);
-
- Vector3 above[4];
- int above_count=0;
+ Vector3 above[4];
+ int above_count = 0;
Vector3 below[4];
- int below_count=0;
+ int below_count = 0;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (p_plane.has_point( vertex[i], CMP_EPSILON )) { // point is in plane
+ if (p_plane.has_point(vertex[i], CMP_EPSILON)) { // point is in plane
- ERR_FAIL_COND_V(above_count>=4,0);
- above[above_count++]=vertex[i];
- ERR_FAIL_COND_V(below_count>=4,0);
- below[below_count++]=vertex[i];
+ ERR_FAIL_COND_V(above_count >= 4, 0);
+ above[above_count++] = vertex[i];
+ ERR_FAIL_COND_V(below_count >= 4, 0);
+ below[below_count++] = vertex[i];
} else {
- if (p_plane.is_point_over( vertex[i])) {
+ if (p_plane.is_point_over(vertex[i])) {
//Point is over
- ERR_FAIL_COND_V(above_count>=4,0);
- above[above_count++]=vertex[i];
+ ERR_FAIL_COND_V(above_count >= 4, 0);
+ above[above_count++] = vertex[i];
} else {
//Point is under
- ERR_FAIL_COND_V(below_count>=4,0);
- below[below_count++]=vertex[i];
+ ERR_FAIL_COND_V(below_count >= 4, 0);
+ below[below_count++] = vertex[i];
}
/* Check for Intersection between this and the next vertex*/
Vector3 inters;
- if (!p_plane.intersects_segment( vertex[i],vertex[(i+1)%3],&inters))
+ if (!p_plane.intersects_segment(vertex[i], vertex[(i + 1) % 3], &inters))
continue;
/* Intersection goes to both */
- ERR_FAIL_COND_V(above_count>=4,0);
- above[above_count++]=inters;
- ERR_FAIL_COND_V(below_count>=4,0);
- below[below_count++]=inters;
+ ERR_FAIL_COND_V(above_count >= 4, 0);
+ above[above_count++] = inters;
+ ERR_FAIL_COND_V(below_count >= 4, 0);
+ below[below_count++] = inters;
}
}
- int polygons_created=0;
+ int polygons_created = 0;
- ERR_FAIL_COND_V( above_count>=4 && below_count>=4 , 0 ); //bug in the algo
+ ERR_FAIL_COND_V(above_count >= 4 && below_count >= 4, 0); //bug in the algo
- if (above_count>=3) {
+ if (above_count >= 3) {
- p_res[polygons_created]=Face3( above[0], above[1], above[2] );
- p_is_point_over[polygons_created]=true;
+ p_res[polygons_created] = Face3(above[0], above[1], above[2]);
+ p_is_point_over[polygons_created] = true;
polygons_created++;
- if (above_count==4) {
+ if (above_count == 4) {
- p_res[polygons_created]=Face3( above[2], above[3], above[0] );
- p_is_point_over[polygons_created]=true;
+ p_res[polygons_created] = Face3(above[2], above[3], above[0]);
+ p_is_point_over[polygons_created] = true;
polygons_created++;
-
}
}
- if (below_count>=3) {
+ if (below_count >= 3) {
- p_res[polygons_created]=Face3( below[0], below[1], below[2] );
- p_is_point_over[polygons_created]=false;
+ p_res[polygons_created] = Face3(below[0], below[1], below[2]);
+ p_is_point_over[polygons_created] = false;
polygons_created++;
- if (below_count==4) {
+ if (below_count == 4) {
- p_res[polygons_created]=Face3( below[2], below[3], below[0] );
- p_is_point_over[polygons_created]=false;
+ p_res[polygons_created] = Face3(below[2], below[3], below[0]);
+ p_is_point_over[polygons_created] = false;
polygons_created++;
-
}
}
return polygons_created;
}
+bool Face3::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const {
-
-bool Face3::intersects_ray(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection) const {
-
- return Geometry::ray_intersects_triangle(p_from,p_dir,vertex[0],vertex[1],vertex[2],p_intersection);
-
+ return Geometry::ray_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
}
-bool Face3::intersects_segment(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection) const {
-
- return Geometry::segment_intersects_triangle(p_from,p_dir,vertex[0],vertex[1],vertex[2],p_intersection);
+bool Face3::intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection) const {
+ return Geometry::segment_intersects_triangle(p_from, p_dir, vertex[0], vertex[1], vertex[2], p_intersection);
}
-
bool Face3::is_degenerate() const {
- Vector3 normal=vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]);
+ Vector3 normal = vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]);
return (normal.length_squared() < CMP_EPSILON2);
}
+Face3::Side Face3::get_side_of(const Face3 &p_face, ClockDirection p_clock_dir) const {
-Face3::Side Face3::get_side_of(const Face3& p_face,ClockDirection p_clock_dir) const {
+ int over = 0, under = 0;
- int over=0,under=0;
+ Plane plane = get_plane(p_clock_dir);
- Plane plane=get_plane(p_clock_dir);
+ for (int i = 0; i < 3; i++) {
- for (int i=0;i<3;i++) {
-
- const Vector3 &v=p_face.vertex[i];
+ const Vector3 &v = p_face.vertex[i];
if (plane.has_point(v)) //coplanar, dont bother
continue;
@@ -152,81 +143,73 @@ Face3::Side Face3::get_side_of(const Face3& p_face,ClockDirection p_clock_dir) c
over++;
else
under++;
-
}
- if ( over > 0 && under == 0 )
+ if (over > 0 && under == 0)
return SIDE_OVER;
- else if (under > 0 && over ==0 )
+ else if (under > 0 && over == 0)
return SIDE_UNDER;
- else if (under ==0 && over == 0)
+ else if (under == 0 && over == 0)
return SIDE_COPLANAR;
else
return SIDE_SPANNING;
-
}
Vector3 Face3::get_random_point_inside() const {
- real_t a=Math::random(0,1);
- real_t b=Math::random(0,1);
- if (a>b) {
- SWAP(a,b);
+ real_t a = Math::random(0, 1);
+ real_t b = Math::random(0, 1);
+ if (a > b) {
+ SWAP(a, b);
}
- return vertex[0]*a + vertex[1]*(b-a) + vertex[2]*(1.0-b);
-
+ return vertex[0] * a + vertex[1] * (b - a) + vertex[2] * (1.0 - b);
}
Plane Face3::get_plane(ClockDirection p_dir) const {
- return Plane( vertex[0], vertex[1], vertex[2] , p_dir );
-
+ return Plane(vertex[0], vertex[1], vertex[2], p_dir);
}
Vector3 Face3::get_median_point() const {
- return (vertex[0] + vertex[1] + vertex[2])/3.0;
+ return (vertex[0] + vertex[1] + vertex[2]) / 3.0;
}
-
real_t Face3::get_area() const {
- return vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]).length();
+ return vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]).length();
}
ClockDirection Face3::get_clock_dir() const {
-
- Vector3 normal=vec3_cross(vertex[0]-vertex[1], vertex[0]-vertex[2]);
+ Vector3 normal = vec3_cross(vertex[0] - vertex[1], vertex[0] - vertex[2]);
//printf("normal is %g,%g,%g x %g,%g,%g- wtfu is %g\n",tofloat(normal.x),tofloat(normal.y),tofloat(normal.z),tofloat(vertex[0].x),tofloat(vertex[0].y),tofloat(vertex[0].z),tofloat( normal.dot( vertex[0] ) ) );
- return ( normal.dot( vertex[0] ) >= 0 ) ? CLOCKWISE : COUNTERCLOCKWISE;
-
+ return (normal.dot(vertex[0]) >= 0) ? CLOCKWISE : COUNTERCLOCKWISE;
}
-
-bool Face3::intersects_aabb(const Rect3& p_aabb) const {
+bool Face3::intersects_aabb(const Rect3 &p_aabb) const {
/** TEST PLANE **/
- if (!p_aabb.intersects_plane( get_plane() ))
+ if (!p_aabb.intersects_plane(get_plane()))
return false;
- /** TEST FACE AXIS */
-
-#define TEST_AXIS(m_ax)\
- {\
- real_t aabb_min=p_aabb.pos.m_ax;\
- real_t aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\
- real_t tri_min,tri_max;\
- for (int i=0;i<3;i++) {\
- if (i==0 || vertex[i].m_ax > tri_max)\
- tri_max=vertex[i].m_ax;\
- if (i==0 || vertex[i].m_ax < tri_min)\
- tri_min=vertex[i].m_ax;\
- }\
-\
- if (tri_max<aabb_min || aabb_max<tri_min)\
- return false;\
+/** TEST FACE AXIS */
+
+#define TEST_AXIS(m_ax) \
+ { \
+ real_t aabb_min = p_aabb.pos.m_ax; \
+ real_t aabb_max = p_aabb.pos.m_ax + p_aabb.size.m_ax; \
+ real_t tri_min, tri_max; \
+ for (int i = 0; i < 3; i++) { \
+ if (i == 0 || vertex[i].m_ax > tri_max) \
+ tri_max = vertex[i].m_ax; \
+ if (i == 0 || vertex[i].m_ax < tri_min) \
+ tri_min = vertex[i].m_ax; \
+ } \
+ \
+ if (tri_max < aabb_min || aabb_max < tri_min) \
+ return false; \
}
TEST_AXIS(x);
@@ -235,221 +218,188 @@ bool Face3::intersects_aabb(const Rect3& p_aabb) const {
/** TEST ALL EDGES **/
- Vector3 edge_norms[3]={
- vertex[0]-vertex[1],
- vertex[1]-vertex[2],
- vertex[2]-vertex[0],
+ Vector3 edge_norms[3] = {
+ vertex[0] - vertex[1],
+ vertex[1] - vertex[2],
+ vertex[2] - vertex[0],
};
- for (int i=0;i<12;i++) {
+ for (int i = 0; i < 12; i++) {
- Vector3 from,to;
- p_aabb.get_edge(i,from,to);
- Vector3 e1=from-to;
- for (int j=0;j<3;j++) {
- Vector3 e2=edge_norms[j];
+ Vector3 from, to;
+ p_aabb.get_edge(i, from, to);
+ Vector3 e1 = from - to;
+ for (int j = 0; j < 3; j++) {
+ Vector3 e2 = edge_norms[j];
- Vector3 axis=vec3_cross( e1, e2 );
+ Vector3 axis = vec3_cross(e1, e2);
- if (axis.length_squared()<0.0001)
+ if (axis.length_squared() < 0.0001)
continue; // coplanar
axis.normalize();
- real_t minA,maxA,minB,maxB;
- p_aabb.project_range_in_plane(Plane(axis,0),minA,maxA);
- project_range(axis,Transform(),minB,maxB);
+ real_t minA, maxA, minB, maxB;
+ p_aabb.project_range_in_plane(Plane(axis, 0), minA, maxA);
+ project_range(axis, Transform(), minB, maxB);
- if (maxA<minB || maxB<minA)
+ if (maxA < minB || maxB < minA)
return false;
}
}
return true;
-
}
Face3::operator String() const {
- return String()+vertex[0]+", "+vertex[1]+", "+vertex[2];
+ return String() + vertex[0] + ", " + vertex[1] + ", " + vertex[2];
}
-void Face3::project_range(const Vector3& p_normal,const Transform& p_transform,real_t& r_min, real_t& r_max) const {
+void Face3::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 v=p_transform.xform(vertex[i]);
- real_t d=p_normal.dot(v);
+ Vector3 v = p_transform.xform(vertex[i]);
+ real_t d = p_normal.dot(v);
- if (i==0 || d > r_max)
- r_max=d;
+ if (i == 0 || d > r_max)
+ r_max = d;
- if (i==0 || d < r_min)
- r_min=d;
+ if (i == 0 || d < r_min)
+ r_min = d;
}
}
-
-
-void Face3::get_support(const Vector3& p_normal,const Transform& p_transform,Vector3 *p_vertices,int* p_count,int p_max) const {
+void Face3::get_support(const Vector3 &p_normal, const Transform &p_transform, Vector3 *p_vertices, int *p_count, int p_max) const {
#define _FACE_IS_VALID_SUPPORT_TRESHOLD 0.98
#define _EDGE_IS_VALID_SUPPORT_TRESHOLD 0.05
- if (p_max<=0)
+ if (p_max <= 0)
return;
- Vector3 n=p_transform.basis.xform_inv(p_normal);
+ Vector3 n = p_transform.basis.xform_inv(p_normal);
/** TEST FACE AS SUPPORT **/
if (get_plane().normal.dot(n) > _FACE_IS_VALID_SUPPORT_TRESHOLD) {
- *p_count=MIN(3,p_max);
+ *p_count = MIN(3, p_max);
- for (int i=0;i<*p_count;i++) {
+ for (int i = 0; i < *p_count; i++) {
- p_vertices[i]=p_transform.xform(vertex[i]);
+ p_vertices[i] = p_transform.xform(vertex[i]);
}
return;
-
}
/** FIND SUPPORT VERTEX **/
- int vert_support_idx=-1;
+ int vert_support_idx = -1;
real_t support_max;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- real_t d=n.dot(vertex[i]);
+ real_t d = n.dot(vertex[i]);
- if (i==0 || d > support_max) {
- support_max=d;
- vert_support_idx=i;
+ if (i == 0 || d > support_max) {
+ support_max = d;
+ vert_support_idx = i;
}
}
/** TEST EDGES AS SUPPORT **/
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (i!=vert_support_idx && i+1!=vert_support_idx)
+ if (i != vert_support_idx && i + 1 != vert_support_idx)
continue;
- // check if edge is valid as a support
- real_t dot=(vertex[i]-vertex[(i+1)%3]).normalized().dot(n);
- dot=ABS(dot);
+ // check if edge is valid as a support
+ real_t dot = (vertex[i] - vertex[(i + 1) % 3]).normalized().dot(n);
+ dot = ABS(dot);
if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD) {
- *p_count=MIN(2,p_max);
+ *p_count = MIN(2, p_max);
- for (int j=0;j<*p_count;j++)
- p_vertices[j]=p_transform.xform(vertex[(j+i)%3]);
+ for (int j = 0; j < *p_count; j++)
+ p_vertices[j] = p_transform.xform(vertex[(j + i) % 3]);
return;
}
}
-
- *p_count=1;
- p_vertices[0]=p_transform.xform(vertex[vert_support_idx]);
-
+ *p_count = 1;
+ p_vertices[0] = p_transform.xform(vertex[vert_support_idx]);
}
-
-Vector3 Face3::get_closest_point_to(const Vector3& p_point) const {
-
- Vector3 edge0 = vertex[1] - vertex[0];
- Vector3 edge1 = vertex[2] - vertex[0];
- Vector3 v0 = vertex[0] - p_point;
-
- real_t a = edge0.dot( edge0 );
- real_t b = edge0.dot( edge1 );
- real_t c = edge1.dot( edge1 );
- real_t d = edge0.dot( v0 );
- real_t e = edge1.dot( v0 );
-
- real_t det = a*c - b*b;
- real_t s = b*e - c*d;
- real_t t = b*d - a*e;
-
- if ( s + t < det )
- {
- if ( s < 0.f )
- {
- if ( t < 0.f )
- {
- if ( d < 0.f )
- {
- s = CLAMP( -d/a, 0.f, 1.f );
- t = 0.f;
- }
- else
- {
- s = 0.f;
- t = CLAMP( -e/c, 0.f, 1.f );
+Vector3 Face3::get_closest_point_to(const Vector3 &p_point) const {
+
+ Vector3 edge0 = vertex[1] - vertex[0];
+ Vector3 edge1 = vertex[2] - vertex[0];
+ Vector3 v0 = vertex[0] - p_point;
+
+ real_t a = edge0.dot(edge0);
+ real_t b = edge0.dot(edge1);
+ real_t c = edge1.dot(edge1);
+ real_t d = edge0.dot(v0);
+ real_t e = edge1.dot(v0);
+
+ real_t det = a * c - b * b;
+ real_t s = b * e - c * d;
+ real_t t = b * d - a * e;
+
+ if (s + t < det) {
+ if (s < 0.f) {
+ if (t < 0.f) {
+ if (d < 0.f) {
+ s = CLAMP(-d / a, 0.f, 1.f);
+ t = 0.f;
+ } else {
+ s = 0.f;
+ t = CLAMP(-e / c, 0.f, 1.f);
+ }
+ } else {
+ s = 0.f;
+ t = CLAMP(-e / c, 0.f, 1.f);
}
- }
- else
- {
- s = 0.f;
- t = CLAMP( -e/c, 0.f, 1.f );
- }
- }
- else if ( t < 0.f )
- {
- s = CLAMP( -d/a, 0.f, 1.f );
- t = 0.f;
- }
- else
- {
- real_t invDet = 1.f / det;
- s *= invDet;
- t *= invDet;
- }
- }
- else
- {
- if ( s < 0.f )
- {
- real_t tmp0 = b+d;
- real_t tmp1 = c+e;
- if ( tmp1 > tmp0 )
- {
- real_t numer = tmp1 - tmp0;
- real_t denom = a-2*b+c;
- s = CLAMP( numer/denom, 0.f, 1.f );
- t = 1-s;
- }
- else
- {
- t = CLAMP( -e/c, 0.f, 1.f );
- s = 0.f;
- }
- }
- else if ( t < 0.f )
- {
- if ( a+d > b+e )
- {
- real_t numer = c+e-b-d;
- real_t denom = a-2*b+c;
- s = CLAMP( numer/denom, 0.f, 1.f );
- t = 1-s;
- }
- else
- {
- s = CLAMP( -e/c, 0.f, 1.f );
+ } else if (t < 0.f) {
+ s = CLAMP(-d / a, 0.f, 1.f);
t = 0.f;
- }
+ } else {
+ real_t invDet = 1.f / det;
+ s *= invDet;
+ t *= invDet;
}
- else
- {
- real_t numer = c+e-b-d;
- real_t denom = a-2*b+c;
- s = CLAMP( numer/denom, 0.f, 1.f );
- t = 1.f - s;
+ } else {
+ if (s < 0.f) {
+ real_t tmp0 = b + d;
+ real_t tmp1 = c + e;
+ if (tmp1 > tmp0) {
+ real_t numer = tmp1 - tmp0;
+ real_t denom = a - 2 * b + c;
+ s = CLAMP(numer / denom, 0.f, 1.f);
+ t = 1 - s;
+ } else {
+ t = CLAMP(-e / c, 0.f, 1.f);
+ s = 0.f;
+ }
+ } else if (t < 0.f) {
+ if (a + d > b + e) {
+ real_t numer = c + e - b - d;
+ real_t denom = a - 2 * b + c;
+ s = CLAMP(numer / denom, 0.f, 1.f);
+ t = 1 - s;
+ } else {
+ s = CLAMP(-e / c, 0.f, 1.f);
+ t = 0.f;
+ }
+ } else {
+ real_t numer = c + e - b - d;
+ real_t denom = a - 2 * b + c;
+ s = CLAMP(numer / denom, 0.f, 1.f);
+ t = 1.f - s;
}
- }
-
- return vertex[0] + s * edge0 + t * edge1;
+ }
+ return vertex[0] + s * edge0 + t * edge1;
}
diff --git a/core/math/face3.h b/core/math/face3.h
index a0da588ea5..6d15c60e3b 100644
--- a/core/math/face3.h
+++ b/core/math/face3.h
@@ -29,25 +29,23 @@
#ifndef FACE3_H
#define FACE3_H
-#include "vector3.h"
#include "plane.h"
#include "rect3.h"
#include "transform.h"
+#include "vector3.h"
class Face3 {
public:
+ enum Side {
+ SIDE_OVER,
+ SIDE_UNDER,
+ SIDE_SPANNING,
+ SIDE_COPLANAR
+ };
- enum Side {
- SIDE_OVER,
- SIDE_UNDER,
- SIDE_SPANNING,
- SIDE_COPLANAR
- };
-
-
- Vector3 vertex[3];
+ Vector3 vertex[3];
- /**
+ /**
*
* @param p_plane plane used to split the face
* @param p_res array of at least 3 faces, amount used in functio return
@@ -56,81 +54,80 @@ public:
* @return amount of faces generated by the split, either 0 (means no split possible), 2 or 3
*/
- int split_by_plane(const Plane& p_plane,Face3 *p_res,bool *p_is_point_over) const;
+ int split_by_plane(const Plane &p_plane, Face3 *p_res, bool *p_is_point_over) const;
- Plane get_plane(ClockDirection p_dir=CLOCKWISE) const;
+ Plane get_plane(ClockDirection p_dir = CLOCKWISE) const;
Vector3 get_random_point_inside() const;
+ Side get_side_of(const Face3 &p_face, ClockDirection p_clock_dir = CLOCKWISE) const;
- Side get_side_of(const Face3& p_face,ClockDirection p_clock_dir=CLOCKWISE) const;
-
- bool is_degenerate() const;
+ bool is_degenerate() const;
real_t get_area() const;
- Vector3 get_median_point() const;
- Vector3 get_closest_point_to(const Vector3& p_point) const;
+ Vector3 get_median_point() const;
+ Vector3 get_closest_point_to(const Vector3 &p_point) const;
- bool intersects_ray(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection=0) const;
- bool intersects_segment(const Vector3& p_from,const Vector3& p_dir,Vector3 * p_intersection=0) const;
+ bool intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = 0) const;
+ bool intersects_segment(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *p_intersection = 0) const;
- ClockDirection get_clock_dir() const; ///< todo, test if this is returning the proper clockwisity
+ ClockDirection get_clock_dir() const; ///< todo, test if this is returning the proper clockwisity
- void get_support(const Vector3& p_normal,const Transform& p_transform,Vector3 *p_vertices,int* p_count,int p_max) const;
- void project_range(const Vector3& p_normal,const Transform& p_transform,real_t& r_min, real_t& r_max) const;
+ void get_support(const Vector3 &p_normal, const Transform &p_transform, Vector3 *p_vertices, int *p_count, int p_max) const;
+ void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
- Rect3 get_aabb() const {
+ Rect3 get_aabb() const {
- Rect3 aabb( vertex[0], Vector3() );
- aabb.expand_to( vertex[1] );
- aabb.expand_to( vertex[2] );
- return aabb;
- }
+ Rect3 aabb(vertex[0], Vector3());
+ aabb.expand_to(vertex[1]);
+ aabb.expand_to(vertex[2]);
+ return aabb;
+ }
- bool intersects_aabb(const Rect3& p_aabb) const;
- _FORCE_INLINE_ bool intersects_aabb2(const Rect3& p_aabb) const;
+ bool intersects_aabb(const Rect3 &p_aabb) const;
+ _FORCE_INLINE_ bool intersects_aabb2(const Rect3 &p_aabb) const;
operator String() const;
- inline Face3() {}
- inline Face3(const Vector3 &p_v1,const Vector3 &p_v2,const Vector3 &p_v3) { vertex[0]=p_v1; vertex[1]=p_v2; vertex[2]=p_v3; }
-
+ inline Face3() {}
+ inline Face3(const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) {
+ vertex[0] = p_v1;
+ vertex[1] = p_v2;
+ vertex[2] = p_v3;
+ }
};
+bool Face3::intersects_aabb2(const Rect3 &p_aabb) const {
-bool Face3::intersects_aabb2(const Rect3& p_aabb) const {
-
- Vector3 perp = (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]);
+ Vector3 perp = (vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]);
Vector3 half_extents = p_aabb.size * 0.5;
Vector3 ofs = p_aabb.pos + half_extents;
- Vector3 sup =Vector3(
- (perp.x>0) ? -half_extents.x : half_extents.x,
- (perp.y>0) ? -half_extents.y : half_extents.y,
- (perp.z>0) ? -half_extents.z : half_extents.z
- );
+ Vector3 sup = Vector3(
+ (perp.x > 0) ? -half_extents.x : half_extents.x,
+ (perp.y > 0) ? -half_extents.y : half_extents.y,
+ (perp.z > 0) ? -half_extents.z : half_extents.z);
real_t d = perp.dot(vertex[0]);
- real_t dist_a = perp.dot(ofs+sup)-d;
- real_t dist_b = perp.dot(ofs-sup)-d;
+ real_t dist_a = perp.dot(ofs + sup) - d;
+ real_t dist_b = perp.dot(ofs - sup) - d;
- if (dist_a*dist_b > 0)
+ if (dist_a * dist_b > 0)
return false; //does not intersect the plane
-
-#define TEST_AXIS(m_ax)\
- {\
- real_t aabb_min=p_aabb.pos.m_ax;\
- real_t aabb_max=p_aabb.pos.m_ax+p_aabb.size.m_ax;\
- real_t tri_min,tri_max;\
- for (int i=0;i<3;i++) {\
- if (i==0 || vertex[i].m_ax > tri_max)\
- tri_max=vertex[i].m_ax;\
- if (i==0 || vertex[i].m_ax < tri_min)\
- tri_min=vertex[i].m_ax;\
- }\
-\
- if (tri_max<aabb_min || aabb_max<tri_min)\
- return false;\
+#define TEST_AXIS(m_ax) \
+ { \
+ real_t aabb_min = p_aabb.pos.m_ax; \
+ real_t aabb_max = p_aabb.pos.m_ax + p_aabb.size.m_ax; \
+ real_t tri_min, tri_max; \
+ for (int i = 0; i < 3; i++) { \
+ if (i == 0 || vertex[i].m_ax > tri_max) \
+ tri_max = vertex[i].m_ax; \
+ if (i == 0 || vertex[i].m_ax < tri_min) \
+ tri_min = vertex[i].m_ax; \
+ } \
+ \
+ if (tri_max < aabb_min || aabb_max < tri_min) \
+ return false; \
}
TEST_AXIS(x);
@@ -139,131 +136,125 @@ bool Face3::intersects_aabb2(const Rect3& p_aabb) const {
#undef TEST_AXIS
-
- Vector3 edge_norms[3]={
- vertex[0]-vertex[1],
- vertex[1]-vertex[2],
- vertex[2]-vertex[0],
+ Vector3 edge_norms[3] = {
+ vertex[0] - vertex[1],
+ vertex[1] - vertex[2],
+ vertex[2] - vertex[0],
};
- for (int i=0;i<12;i++) {
+ for (int i = 0; i < 12; i++) {
- Vector3 from,to;
- switch(i) {
+ Vector3 from, to;
+ switch (i) {
- case 0:{
+ case 0: {
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z);
} break;
- case 1:{
+ case 1: {
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z);
} break;
- case 2:{
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
+ case 2: {
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
} break;
- case 3:{
+ case 3: {
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
} break;
- case 4:{
+ case 4: {
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
} break;
- case 5:{
+ case 5: {
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
} break;
- case 6:{
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
+ case 6: {
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
} break;
- case 7:{
+ case 7: {
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
} break;
- case 8:{
+ case 8: {
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
} break;
- case 9:{
+ case 9: {
- from=Vector3( p_aabb.pos.x , p_aabb.pos.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
} break;
- case 10:{
+ case 10: {
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z );
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z);
} break;
- case 11:{
+ case 11: {
- from=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y , p_aabb.pos.z+p_aabb.size.z );
- to=Vector3( p_aabb.pos.x+p_aabb.size.x , p_aabb.pos.y+p_aabb.size.y , p_aabb.pos.z+p_aabb.size.z );
+ from = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z);
+ to = Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z);
} break;
-
}
- Vector3 e1=from-to;
- for (int j=0;j<3;j++) {
- Vector3 e2=edge_norms[j];
+ Vector3 e1 = from - to;
+ for (int j = 0; j < 3; j++) {
+ Vector3 e2 = edge_norms[j];
- Vector3 axis=vec3_cross( e1, e2 );
+ Vector3 axis = vec3_cross(e1, e2);
- if (axis.length_squared()<0.0001)
+ if (axis.length_squared() < 0.0001)
continue; // coplanar
//axis.normalize();
- Vector3 sup2 =Vector3(
- (axis.x>0) ? -half_extents.x : half_extents.x,
- (axis.y>0) ? -half_extents.y : half_extents.y,
- (axis.z>0) ? -half_extents.z : half_extents.z
- );
+ Vector3 sup2 = Vector3(
+ (axis.x > 0) ? -half_extents.x : half_extents.x,
+ (axis.y > 0) ? -half_extents.y : half_extents.y,
+ (axis.z > 0) ? -half_extents.z : half_extents.z);
- real_t maxB = axis.dot(ofs+sup2);
- real_t minB = axis.dot(ofs-sup2);
- if (minB>maxB) {
- SWAP(maxB,minB);
+ real_t maxB = axis.dot(ofs + sup2);
+ real_t minB = axis.dot(ofs - sup2);
+ if (minB > maxB) {
+ SWAP(maxB, minB);
}
- real_t minT=1e20,maxT=-1e20;
- for (int k=0;k<3;k++) {
+ real_t minT = 1e20, maxT = -1e20;
+ for (int k = 0; k < 3; k++) {
- real_t d=axis.dot(vertex[k]);
+ real_t d = axis.dot(vertex[k]);
if (d > maxT)
- maxT=d;
+ maxT = d;
if (d < minT)
- minT=d;
+ minT = d;
}
- if (maxB<minT || maxT<minB)
+ if (maxB < minT || maxT < minB)
return false;
}
}
return true;
-
-
}
-
//this sucks...
#endif // FACE3_H
diff --git a/core/math/geometry.cpp b/core/math/geometry.cpp
index 6570dfe672..ec4d352a8f 100644
--- a/core/math/geometry.cpp
+++ b/core/math/geometry.cpp
@@ -29,58 +29,54 @@
#include "geometry.h"
#include "print_string.h"
-
-
void Geometry::MeshData::optimize_vertices() {
- Map<int,int> vtx_remap;
+ Map<int, int> vtx_remap;
- for(int i=0;i<faces.size();i++) {
+ for (int i = 0; i < faces.size(); i++) {
- for(int j=0;j<faces[i].indices.size();j++) {
+ for (int j = 0; j < faces[i].indices.size(); j++) {
int idx = faces[i].indices[j];
if (!vtx_remap.has(idx)) {
int ni = vtx_remap.size();
- vtx_remap[idx]=ni;
-
-
+ vtx_remap[idx] = ni;
}
- faces[i].indices[j]=vtx_remap[idx];
+ faces[i].indices[j] = vtx_remap[idx];
}
}
- for(int i=0;i<edges.size();i++) {
+ for (int i = 0; i < edges.size(); i++) {
int a = edges[i].a;
int b = edges[i].b;
if (!vtx_remap.has(a)) {
int ni = vtx_remap.size();
- vtx_remap[a]=ni;
+ vtx_remap[a] = ni;
}
if (!vtx_remap.has(b)) {
int ni = vtx_remap.size();
- vtx_remap[b]=ni;
+ vtx_remap[b] = ni;
}
- edges[i].a=vtx_remap[a];
- edges[i].b=vtx_remap[b];
+ edges[i].a = vtx_remap[a];
+ edges[i].b = vtx_remap[b];
}
Vector<Vector3> new_vertices;
new_vertices.resize(vtx_remap.size());
- for(int i=0;i<vertices.size();i++) {
+ for (int i = 0; i < vertices.size(); i++) {
if (vtx_remap.has(i))
- new_vertices[vtx_remap[i]]=vertices[i];
+ new_vertices[vtx_remap[i]] = vertices[i];
}
- vertices=new_vertices;
+ vertices = new_vertices;
}
-Vector< Vector<Vector2> > (*Geometry::_decompose_func)(const Vector<Vector2>& p_polygon)=NULL;
+Vector<Vector<Vector2> > (*Geometry::_decompose_func)(const Vector<Vector2> &p_polygon) = NULL;
struct _FaceClassify {
@@ -88,16 +84,22 @@ struct _FaceClassify {
int face;
int edge;
- void clear() { face=-1; edge=-1; }
- _Link() { face=-1; edge=-1; }
+ void clear() {
+ face = -1;
+ edge = -1;
+ }
+ _Link() {
+ face = -1;
+ edge = -1;
+ }
};
bool valid;
int group;
_Link links[3];
Face3 face;
_FaceClassify() {
- group=-1;
- valid=false;
+ group = -1;
+ valid = false;
};
};
@@ -105,76 +107,73 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
/* connect faces, error will occur if an edge is shared between more than 2 faces */
/* clear connections */
- bool error=false;
+ bool error = false;
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
p_faces[i].links[j].clear();
}
}
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (p_faces[i].group!=p_group)
+ if (p_faces[i].group != p_group)
continue;
- for (int j=i+1;j<len;j++) {
+ for (int j = i + 1; j < len; j++) {
- if (p_faces[j].group!=p_group)
+ if (p_faces[j].group != p_group)
continue;
- for (int k=0;k<3;k++) {
+ for (int k = 0; k < 3; k++) {
- Vector3 vi1=p_faces[i].face.vertex[k];
- Vector3 vi2=p_faces[i].face.vertex[(k+1)%3];
+ Vector3 vi1 = p_faces[i].face.vertex[k];
+ Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
- for (int l=0;l<3;l++) {
+ for (int l = 0; l < 3; l++) {
- Vector3 vj2=p_faces[j].face.vertex[l];
- Vector3 vj1=p_faces[j].face.vertex[(l+1)%3];
+ Vector3 vj2 = p_faces[j].face.vertex[l];
+ Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
- if (vi1.distance_to(vj1)<0.00001 &&
- vi2.distance_to(vj2)<0.00001
- ) {
- if (p_faces[i].links[k].face!=-1) {
+ if (vi1.distance_to(vj1) < 0.00001 &&
+ vi2.distance_to(vj2) < 0.00001) {
+ if (p_faces[i].links[k].face != -1) {
ERR_PRINT("already linked\n");
- error=true;
+ error = true;
break;
}
- if (p_faces[j].links[l].face!=-1) {
+ if (p_faces[j].links[l].face != -1) {
ERR_PRINT("already linked\n");
- error=true;
+ error = true;
break;
}
- p_faces[i].links[k].face=j;
- p_faces[i].links[k].edge=l;
- p_faces[j].links[l].face=i;
- p_faces[j].links[l].edge=k;
- }
+ p_faces[i].links[k].face = j;
+ p_faces[i].links[k].edge = l;
+ p_faces[j].links[l].face = i;
+ p_faces[j].links[l].edge = k;
+ }
}
if (error)
break;
-
}
if (error)
break;
-
}
if (error)
break;
}
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- p_faces[i].valid=true;
- for (int j=0;j<3;j++) {
+ p_faces[i].valid = true;
+ for (int j = 0; j < 3; j++) {
- if (p_faces[i].links[j].face==-1)
- p_faces[i].valid=false;
+ if (p_faces[i].links[j].face == -1)
+ p_faces[i].valid = false;
}
/*printf("face %i is valid: %i, group %i. connected to %i:%i,%i:%i,%i:%i\n",i,p_faces[i].valid,p_faces[i].group,
p_faces[i].links[0].face,
@@ -187,152 +186,146 @@ static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
return error;
}
-static bool _group_face(_FaceClassify *p_faces, int len, int p_index,int p_group) {
+static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
- if (p_faces[p_index].group>=0)
+ if (p_faces[p_index].group >= 0)
return false;
- p_faces[p_index].group=p_group;
+ p_faces[p_index].group = p_group;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face,len,true);
- _group_face(p_faces,len,p_faces[p_index].links[i].face,p_group);
+ ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
+ _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
}
return true;
}
+PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_array) {
-PoolVector< PoolVector< Face3 > > Geometry::separate_objects( PoolVector< Face3 > p_array ) {
-
- PoolVector< PoolVector< Face3 > > objects;
+ PoolVector<PoolVector<Face3> > objects;
int len = p_array.size();
- PoolVector<Face3>::Read r=p_array.read();
+ PoolVector<Face3>::Read r = p_array.read();
- const Face3* arrayptr = r.ptr();
+ const Face3 *arrayptr = r.ptr();
- PoolVector< _FaceClassify> fc;
+ PoolVector<_FaceClassify> fc;
- fc.resize( len );
+ fc.resize(len);
- PoolVector< _FaceClassify >::Write fcw=fc.write();
+ PoolVector<_FaceClassify>::Write fcw = fc.write();
- _FaceClassify * _fcptr = fcw.ptr();
+ _FaceClassify *_fcptr = fcw.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- _fcptr[i].face=arrayptr[i];
+ _fcptr[i].face = arrayptr[i];
}
- bool error=_connect_faces(_fcptr,len,-1);
+ bool error = _connect_faces(_fcptr, len, -1);
if (error) {
- ERR_FAIL_COND_V(error, PoolVector< PoolVector< Face3 > >() ); // invalid geometry
+ ERR_FAIL_COND_V(error, PoolVector<PoolVector<Face3> >()); // invalid geometry
}
/* group connected faces in separate objects */
- int group=0;
- for (int i=0;i<len;i++) {
+ int group = 0;
+ for (int i = 0; i < len; i++) {
if (!_fcptr[i].valid)
continue;
- if (_group_face(_fcptr,len,i,group)) {
+ if (_group_face(_fcptr, len, i, group)) {
group++;
}
}
/* group connected faces in separate objects */
+ for (int i = 0; i < len; i++) {
- for (int i=0;i<len;i++) {
-
- _fcptr[i].face=arrayptr[i];
+ _fcptr[i].face = arrayptr[i];
}
- if (group>=0) {
+ if (group >= 0) {
objects.resize(group);
- PoolVector< PoolVector<Face3> >::Write obw=objects.write();
- PoolVector< Face3 > *group_faces = obw.ptr();
+ PoolVector<PoolVector<Face3> >::Write obw = objects.write();
+ PoolVector<Face3> *group_faces = obw.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
if (!_fcptr[i].valid)
continue;
- if (_fcptr[i].group>=0 && _fcptr[i].group<group) {
+ if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
- group_faces[_fcptr[i].group].push_back( _fcptr[i].face );
+ group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
}
}
}
-
return objects;
-
}
/*** GEOMETRY WRAPPER ***/
enum _CellFlags {
- _CELL_SOLID=1,
- _CELL_EXTERIOR=2,
- _CELL_STEP_MASK=0x1C,
- _CELL_STEP_NONE=0<<2,
- _CELL_STEP_Y_POS=1<<2,
- _CELL_STEP_Y_NEG=2<<2,
- _CELL_STEP_X_POS=3<<2,
- _CELL_STEP_X_NEG=4<<2,
- _CELL_STEP_Z_POS=5<<2,
- _CELL_STEP_Z_NEG=6<<2,
- _CELL_STEP_DONE=7<<2,
- _CELL_PREV_MASK=0xE0,
- _CELL_PREV_NONE=0<<5,
- _CELL_PREV_Y_POS=1<<5,
- _CELL_PREV_Y_NEG=2<<5,
- _CELL_PREV_X_POS=3<<5,
- _CELL_PREV_X_NEG=4<<5,
- _CELL_PREV_Z_POS=5<<5,
- _CELL_PREV_Z_NEG=6<<5,
- _CELL_PREV_FIRST=7<<5,
+ _CELL_SOLID = 1,
+ _CELL_EXTERIOR = 2,
+ _CELL_STEP_MASK = 0x1C,
+ _CELL_STEP_NONE = 0 << 2,
+ _CELL_STEP_Y_POS = 1 << 2,
+ _CELL_STEP_Y_NEG = 2 << 2,
+ _CELL_STEP_X_POS = 3 << 2,
+ _CELL_STEP_X_NEG = 4 << 2,
+ _CELL_STEP_Z_POS = 5 << 2,
+ _CELL_STEP_Z_NEG = 6 << 2,
+ _CELL_STEP_DONE = 7 << 2,
+ _CELL_PREV_MASK = 0xE0,
+ _CELL_PREV_NONE = 0 << 5,
+ _CELL_PREV_Y_POS = 1 << 5,
+ _CELL_PREV_Y_NEG = 2 << 5,
+ _CELL_PREV_X_POS = 3 << 5,
+ _CELL_PREV_X_NEG = 4 << 5,
+ _CELL_PREV_Z_POS = 5 << 5,
+ _CELL_PREV_Z_NEG = 6 << 5,
+ _CELL_PREV_FIRST = 7 << 5,
};
-static inline void _plot_face(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z,const Vector3& voxelsize,const Face3& p_face) {
+static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, const Vector3 &voxelsize, const Face3 &p_face) {
- Rect3 aabb( Vector3(x,y,z),Vector3(len_x,len_y,len_z));
- aabb.pos=aabb.pos*voxelsize;
- aabb.size=aabb.size*voxelsize;
+ Rect3 aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
+ aabb.pos = aabb.pos * voxelsize;
+ aabb.size = aabb.size * voxelsize;
if (!p_face.intersects_aabb(aabb))
return;
- if (len_x==1 && len_y==1 && len_z==1) {
+ if (len_x == 1 && len_y == 1 && len_z == 1) {
- p_cell_status[x][y][z]=_CELL_SOLID;
+ p_cell_status[x][y][z] = _CELL_SOLID;
return;
}
-
-
- int div_x=len_x>1?2:1;
- int div_y=len_y>1?2:1;
- int div_z=len_z>1?2:1;
-
-#define _SPLIT(m_i,m_div,m_v,m_len_v,m_new_v,m_new_len_v)\
- if (m_div==1) {\
- m_new_v=m_v;\
- m_new_len_v=1; \
- } else if (m_i==0) {\
- m_new_v=m_v;\
- m_new_len_v=m_len_v/2;\
- } else {\
- m_new_v=m_v+m_len_v/2;\
- m_new_len_v=m_len_v-m_len_v/2; \
+ int div_x = len_x > 1 ? 2 : 1;
+ int div_y = len_y > 1 ? 2 : 1;
+ int div_z = len_z > 1 ? 2 : 1;
+
+#define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
+ if (m_div == 1) { \
+ m_new_v = m_v; \
+ m_new_len_v = 1; \
+ } else if (m_i == 0) { \
+ m_new_v = m_v; \
+ m_new_len_v = m_len_v / 2; \
+ } else { \
+ m_new_v = m_v + m_len_v / 2; \
+ m_new_len_v = m_len_v - m_len_v / 2; \
}
int new_x;
@@ -342,84 +335,83 @@ static inline void _plot_face(uint8_t*** p_cell_status,int x,int y,int z,int len
int new_z;
int new_len_z;
- for (int i=0;i<div_x;i++) {
-
+ for (int i = 0; i < div_x; i++) {
- _SPLIT(i,div_x,x,len_x,new_x,new_len_x);
+ _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
- for (int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- _SPLIT(j,div_y,y,len_y,new_y,new_len_y);
+ _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
- for (int k=0;k<div_z;k++) {
+ for (int k = 0; k < div_z; k++) {
- _SPLIT(k,div_z,z,len_z,new_z,new_len_z);
+ _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
- _plot_face(p_cell_status,new_x,new_y,new_z,new_len_x,new_len_y,new_len_z,voxelsize,p_face);
+ _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
}
}
}
}
-static inline void _mark_outside(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z) {
+static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) {
- if (p_cell_status[x][y][z]&3)
+ if (p_cell_status[x][y][z] & 3)
return; // nothing to do, already used and/or visited
- p_cell_status[x][y][z]=_CELL_PREV_FIRST;
+ p_cell_status[x][y][z] = _CELL_PREV_FIRST;
- while(true) {
+ while (true) {
uint8_t &c = p_cell_status[x][y][z];
//printf("at %i,%i,%i\n",x,y,z);
- if ( (c&_CELL_STEP_MASK)==_CELL_STEP_NONE) {
+ if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
/* Haven't been in here, mark as outside */
- p_cell_status[x][y][z]|=_CELL_EXTERIOR;
+ p_cell_status[x][y][z] |= _CELL_EXTERIOR;
//printf("not marked as anything, marking exterior\n");
}
//printf("cell step is %i\n",(c&_CELL_STEP_MASK));
- if ( (c&_CELL_STEP_MASK)!=_CELL_STEP_DONE) {
+ if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
/* if not done, increase step */
- c+=1<<2;
+ c += 1 << 2;
//printf("incrementing cell step\n");
}
- if ( (c&_CELL_STEP_MASK)==_CELL_STEP_DONE) {
+ if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
/* Go back */
//printf("done, going back a cell\n");
- switch(c&_CELL_PREV_MASK) {
+ switch (c & _CELL_PREV_MASK) {
case _CELL_PREV_FIRST: {
//printf("at end, finished marking\n");
return;
} break;
case _CELL_PREV_Y_POS: {
y++;
- ERR_FAIL_COND(y>=len_y);
+ ERR_FAIL_COND(y >= len_y);
} break;
case _CELL_PREV_Y_NEG: {
y--;
- ERR_FAIL_COND(y<0);
+ ERR_FAIL_COND(y < 0);
} break;
case _CELL_PREV_X_POS: {
x++;
- ERR_FAIL_COND(x>=len_x);
+ ERR_FAIL_COND(x >= len_x);
} break;
case _CELL_PREV_X_NEG: {
x--;
- ERR_FAIL_COND(x<0);
+ ERR_FAIL_COND(x < 0);
} break;
case _CELL_PREV_Z_POS: {
z++;
- ERR_FAIL_COND(z>=len_z);
+ ERR_FAIL_COND(z >= len_z);
} break;
case _CELL_PREV_Z_NEG: {
z--;
- ERR_FAIL_COND(z<0);
+ ERR_FAIL_COND(z < 0);
} break;
default: {
ERR_FAIL();
@@ -430,70 +422,69 @@ static inline void _mark_outside(uint8_t*** p_cell_status,int x,int y,int z,int
//printf("attempting new cell!\n");
- int next_x=x,next_y=y,next_z=z;
- uint8_t prev=0;
+ int next_x = x, next_y = y, next_z = z;
+ uint8_t prev = 0;
- switch(c&_CELL_STEP_MASK) {
+ switch (c & _CELL_STEP_MASK) {
case _CELL_STEP_Y_POS: {
next_y++;
- prev=_CELL_PREV_Y_NEG;
+ prev = _CELL_PREV_Y_NEG;
} break;
case _CELL_STEP_Y_NEG: {
next_y--;
- prev=_CELL_PREV_Y_POS;
+ prev = _CELL_PREV_Y_POS;
} break;
case _CELL_STEP_X_POS: {
next_x++;
- prev=_CELL_PREV_X_NEG;
+ prev = _CELL_PREV_X_NEG;
} break;
case _CELL_STEP_X_NEG: {
next_x--;
- prev=_CELL_PREV_X_POS;
+ prev = _CELL_PREV_X_POS;
} break;
case _CELL_STEP_Z_POS: {
next_z++;
- prev=_CELL_PREV_Z_NEG;
+ prev = _CELL_PREV_Z_NEG;
} break;
case _CELL_STEP_Z_NEG: {
next_z--;
- prev=_CELL_PREV_Z_POS;
+ prev = _CELL_PREV_Z_POS;
} break;
default: ERR_FAIL();
-
}
//printf("testing if new cell will be ok...!\n");
- if (next_x<0 || next_x>=len_x)
+ if (next_x < 0 || next_x >= len_x)
continue;
- if (next_y<0 || next_y>=len_y)
+ if (next_y < 0 || next_y >= len_y)
continue;
- if (next_z<0 || next_z>=len_z)
+ if (next_z < 0 || next_z >= len_z)
continue;
//printf("testing if new cell is traversable\n");
- if (p_cell_status[next_x][next_y][next_z]&3)
+ if (p_cell_status[next_x][next_y][next_z] & 3)
continue;
//printf("move to it\n");
- x=next_x;
- y=next_y;
- z=next_z;
- p_cell_status[x][y][z]|=prev;
+ x = next_x;
+ y = next_y;
+ z = next_z;
+ p_cell_status[x][y][z] |= prev;
}
}
-static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int len_x,int len_y,int len_z,PoolVector<Face3>& p_faces) {
+static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, PoolVector<Face3> &p_faces) {
- ERR_FAIL_INDEX(x,len_x);
- ERR_FAIL_INDEX(y,len_y);
- ERR_FAIL_INDEX(z,len_z);
+ ERR_FAIL_INDEX(x, len_x);
+ ERR_FAIL_INDEX(y, len_y);
+ ERR_FAIL_INDEX(z, len_z);
- if (p_cell_status[x][y][z]&_CELL_EXTERIOR)
+ if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
return;
/* static const Vector3 vertices[8]={
@@ -507,18 +498,18 @@ static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int l
Vector3(1,1,1),
};
*/
-#define vert(m_idx) Vector3( (m_idx&4)>>2, (m_idx&2)>>1, m_idx&1 )
+#define vert(m_idx) Vector3((m_idx & 4) >> 2, (m_idx & 2) >> 1, m_idx & 1)
- static const uint8_t indices[6][4]={
- {7,6,4,5},
- {7,3,2,6},
- {7,5,1,3},
- {0,2,3,1},
- {0,1,5,4},
- {0,4,6,2},
+ static const uint8_t indices[6][4] = {
+ { 7, 6, 4, 5 },
+ { 7, 3, 2, 6 },
+ { 7, 5, 1, 3 },
+ { 0, 2, 3, 1 },
+ { 0, 1, 5, 4 },
+ { 0, 4, 6, 2 },
};
-/*
+ /*
{0,1,2,3},
{0,1,4,5},
@@ -535,114 +526,107 @@ static inline void _build_faces(uint8_t*** p_cell_status,int x,int y,int z,int l
{7,5,1,3},
*/
- for (int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
- int disp_x=x+((i%3)==0?((i<3)?1:-1):0);
- int disp_y=y+(((i-1)%3)==0?((i<3)?1:-1):0);
- int disp_z=z+(((i-2)%3)==0?((i<3)?1:-1):0);
+ int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
+ int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
+ int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
- bool plot=false;
+ bool plot = false;
- if (disp_x<0 || disp_x>=len_x)
- plot=true;
- if (disp_y<0 || disp_y>=len_y)
- plot=true;
- if (disp_z<0 || disp_z>=len_z)
- plot=true;
+ if (disp_x < 0 || disp_x >= len_x)
+ plot = true;
+ if (disp_y < 0 || disp_y >= len_y)
+ plot = true;
+ if (disp_z < 0 || disp_z >= len_z)
+ plot = true;
- if (!plot && (p_cell_status[disp_x][disp_y][disp_z]&_CELL_EXTERIOR))
- plot=true;
+ if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
+ plot = true;
if (!plot)
continue;
- for (int j=0;j<4;j++)
- face_points[j]=vert( indices[i][j] ) + Vector3(x,y,z);
+ for (int j = 0; j < 4; j++)
+ face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
p_faces.push_back(
- Face3(
- face_points[0],
- face_points[1],
- face_points[2]
- )
- );
+ Face3(
+ face_points[0],
+ face_points[1],
+ face_points[2]));
p_faces.push_back(
- Face3(
- face_points[2],
- face_points[3],
- face_points[0]
- )
- );
-
+ Face3(
+ face_points[2],
+ face_points[3],
+ face_points[0]));
}
-
}
-PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t *p_error ) {
+PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
#define _MIN_SIZE 1.0
#define _MAX_LENGTH 20
- int face_count=p_array.size();
- PoolVector<Face3>::Read facesr=p_array.read();
+ int face_count = p_array.size();
+ PoolVector<Face3>::Read facesr = p_array.read();
const Face3 *faces = facesr.ptr();
Rect3 global_aabb;
- for(int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- if (i==0) {
+ if (i == 0) {
- global_aabb=faces[i].get_aabb();
+ global_aabb = faces[i].get_aabb();
} else {
- global_aabb.merge_with( faces[i].get_aabb() );
+ global_aabb.merge_with(faces[i].get_aabb());
}
}
global_aabb.grow_by(0.01); // avoid numerical error
// determine amount of cells in grid axis
- int div_x,div_y,div_z;
+ int div_x, div_y, div_z;
- if (global_aabb.size.x/_MIN_SIZE<_MAX_LENGTH)
- div_x=(int)(global_aabb.size.x/_MIN_SIZE)+1;
+ if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
+ div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
else
- div_x=_MAX_LENGTH;
+ div_x = _MAX_LENGTH;
- if (global_aabb.size.y/_MIN_SIZE<_MAX_LENGTH)
- div_y=(int)(global_aabb.size.y/_MIN_SIZE)+1;
+ if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
+ div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
else
- div_y=_MAX_LENGTH;
+ div_y = _MAX_LENGTH;
- if (global_aabb.size.z/_MIN_SIZE<_MAX_LENGTH)
- div_z=(int)(global_aabb.size.z/_MIN_SIZE)+1;
+ if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
+ div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
else
- div_z=_MAX_LENGTH;
-
- Vector3 voxelsize=global_aabb.size;
- voxelsize.x/=div_x;
- voxelsize.y/=div_y;
- voxelsize.z/=div_z;
+ div_z = _MAX_LENGTH;
+ Vector3 voxelsize = global_aabb.size;
+ voxelsize.x /= div_x;
+ voxelsize.y /= div_y;
+ voxelsize.z /= div_z;
// create and initialize cells to zero
//print_line("Wrapper: Initializing Cells");
- uint8_t ***cell_status=memnew_arr(uint8_t**,div_x);
- for(int i=0;i<div_x;i++) {
+ uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
+ for (int i = 0; i < div_x; i++) {
- cell_status[i]=memnew_arr(uint8_t*,div_y);
+ cell_status[i] = memnew_arr(uint8_t *, div_y);
- for(int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- cell_status[i][j]=memnew_arr(uint8_t,div_z);
+ cell_status[i][j] = memnew_arr(uint8_t, div_z);
- for(int k=0;k<div_z;k++) {
+ for (int k = 0; k < div_z; k++) {
- cell_status[i][j][k]=0;
+ cell_status[i][j][k] = 0;
}
}
}
@@ -650,45 +634,44 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t
// plot faces into cells
//print_line("Wrapper (1/6): Plotting Faces");
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- Face3 f=faces[i];
- for (int j=0;j<3;j++) {
+ Face3 f = faces[i];
+ for (int j = 0; j < 3; j++) {
- f.vertex[j]-=global_aabb.pos;
+ f.vertex[j] -= global_aabb.pos;
}
- _plot_face(cell_status,0,0,0,div_x,div_y,div_z,voxelsize,f);
+ _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
}
-
// determine which cells connect to the outside by traversing the outside and recursively flood-fill marking
//print_line("Wrapper (2/6): Flood Filling");
- for (int i=0;i<div_x;i++) {
+ for (int i = 0; i < div_x; i++) {
- for (int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- _mark_outside(cell_status,i,j,0,div_x,div_y,div_z);
- _mark_outside(cell_status,i,j,div_z-1,div_x,div_y,div_z);
+ _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
+ _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
}
}
- for (int i=0;i<div_z;i++) {
+ for (int i = 0; i < div_z; i++) {
- for (int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- _mark_outside(cell_status,0,j,i,div_x,div_y,div_z);
- _mark_outside(cell_status,div_x-1,j,i,div_x,div_y,div_z);
+ _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
+ _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
}
}
- for (int i=0;i<div_x;i++) {
+ for (int i = 0; i < div_x; i++) {
- for (int j=0;j<div_z;j++) {
+ for (int j = 0; j < div_z; j++) {
- _mark_outside(cell_status,i,0,j,div_x,div_y,div_z);
- _mark_outside(cell_status,i,div_y-1,j,div_x,div_y,div_z);
+ _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
+ _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
}
}
@@ -698,13 +681,13 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t
PoolVector<Face3> wrapped_faces;
- for (int i=0;i<div_x;i++) {
+ for (int i = 0; i < div_x; i++) {
- for (int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- for (int k=0;k<div_z;k++) {
+ for (int k = 0; k < div_z; k++) {
- _build_faces(cell_status,i,j,k,div_x,div_y,div_z,wrapped_faces);
+ _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
}
}
}
@@ -713,36 +696,36 @@ PoolVector< Face3 > Geometry::wrap_geometry( PoolVector< Face3 > p_array,real_t
// transform face vertices to global coords
- int wrapped_faces_count=wrapped_faces.size();
- PoolVector<Face3>::Write wrapped_facesw=wrapped_faces.write();
- Face3* wrapped_faces_ptr=wrapped_facesw.ptr();
+ int wrapped_faces_count = wrapped_faces.size();
+ PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write();
+ Face3 *wrapped_faces_ptr = wrapped_facesw.ptr();
- for(int i=0;i<wrapped_faces_count;i++) {
+ for (int i = 0; i < wrapped_faces_count; i++) {
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- Vector3& v = wrapped_faces_ptr[i].vertex[j];
- v=v*voxelsize;
- v+=global_aabb.pos;
+ Vector3 &v = wrapped_faces_ptr[i].vertex[j];
+ v = v * voxelsize;
+ v += global_aabb.pos;
}
}
// clean up grid
//print_line("Wrapper (5/6): Grid Cleanup");
- for(int i=0;i<div_x;i++) {
+ for (int i = 0; i < div_x; i++) {
- for(int j=0;j<div_y;j++) {
+ for (int j = 0; j < div_y; j++) {
- memdelete_arr( cell_status[i][j] );
+ memdelete_arr(cell_status[i][j]);
}
- memdelete_arr( cell_status[i] );
+ memdelete_arr(cell_status[i]);
}
memdelete_arr(cell_status);
if (p_error)
- *p_error=voxelsize.length();
+ *p_error = voxelsize.length();
//print_line("Wrapper (6/6): Finished.");
return wrapped_faces;
@@ -752,131 +735,125 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes
MeshData mesh;
-
#define SUBPLANE_SIZE 1024.0
real_t subplane_size = 1024.0; // should compute this from the actual plane
- for (int i=0;i<p_planes.size();i++) {
+ for (int i = 0; i < p_planes.size(); i++) {
- Plane p =p_planes[i];
+ Plane p = p_planes[i];
- Vector3 ref=Vector3(0.0,1.0,0.0);
+ Vector3 ref = Vector3(0.0, 1.0, 0.0);
- if (ABS(p.normal.dot(ref))>0.95)
- ref=Vector3(0.0,0.0,1.0); // change axis
+ if (ABS(p.normal.dot(ref)) > 0.95)
+ ref = Vector3(0.0, 0.0, 1.0); // change axis
Vector3 right = p.normal.cross(ref).normalized();
- Vector3 up = p.normal.cross( right ).normalized();
+ Vector3 up = p.normal.cross(right).normalized();
- Vector< Vector3 > vertices;
+ Vector<Vector3> vertices;
Vector3 center = p.get_any_point();
// make a quad clockwise
- vertices.push_back( center - up * subplane_size + right * subplane_size );
- vertices.push_back( center - up * subplane_size - right * subplane_size );
- vertices.push_back( center + up * subplane_size - right * subplane_size );
- vertices.push_back( center + up * subplane_size + right * subplane_size );
+ vertices.push_back(center - up * subplane_size + right * subplane_size);
+ vertices.push_back(center - up * subplane_size - right * subplane_size);
+ vertices.push_back(center + up * subplane_size - right * subplane_size);
+ vertices.push_back(center + up * subplane_size + right * subplane_size);
- for (int j=0;j<p_planes.size();j++) {
+ for (int j = 0; j < p_planes.size(); j++) {
- if (j==i)
+ if (j == i)
continue;
+ Vector<Vector3> new_vertices;
+ Plane clip = p_planes[j];
- Vector< Vector3 > new_vertices;
- Plane clip=p_planes[j];
-
- if (clip.normal.dot(p.normal)>0.95)
+ if (clip.normal.dot(p.normal) > 0.95)
continue;
- if (vertices.size()<3)
+ if (vertices.size() < 3)
break;
- for(int k=0;k<vertices.size();k++) {
+ for (int k = 0; k < vertices.size(); k++) {
- int k_n=(k+1)%vertices.size();
+ int k_n = (k + 1) % vertices.size();
- Vector3 edge0_A=vertices[k];
- Vector3 edge1_A=vertices[k_n];
+ Vector3 edge0_A = vertices[k];
+ Vector3 edge1_A = vertices[k_n];
real_t dist0 = clip.distance_to(edge0_A);
real_t dist1 = clip.distance_to(edge1_A);
-
- if ( dist0 <= 0 ) { // behind plane
+ if (dist0 <= 0) { // behind plane
new_vertices.push_back(vertices[k]);
}
-
// check for different sides and non coplanar
- if ( (dist0*dist1) < 0) {
+ if ((dist0 * dist1) < 0) {
// calculate intersection
Vector3 rel = edge1_A - edge0_A;
- real_t den=clip.normal.dot( rel );
- if (Math::abs(den)<CMP_EPSILON)
+ real_t den = clip.normal.dot(rel);
+ if (Math::abs(den) < CMP_EPSILON)
continue; // point too short
- real_t dist=-(clip.normal.dot( edge0_A )-clip.d)/den;
- Vector3 inters = edge0_A+rel*dist;
+ real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
+ Vector3 inters = edge0_A + rel * dist;
new_vertices.push_back(inters);
}
}
- vertices=new_vertices;
+ vertices = new_vertices;
}
- if (vertices.size()<3)
+ if (vertices.size() < 3)
continue;
-
//result is a clockwise face
MeshData::Face face;
// add face indices
- for (int j=0;j<vertices.size();j++) {
-
+ for (int j = 0; j < vertices.size(); j++) {
- int idx=-1;
- for (int k=0;k<mesh.vertices.size();k++) {
+ int idx = -1;
+ for (int k = 0; k < mesh.vertices.size(); k++) {
- if (mesh.vertices[k].distance_to(vertices[j])<0.001) {
+ if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
- idx=k;
+ idx = k;
break;
}
}
- if (idx==-1) {
+ if (idx == -1) {
- idx=mesh.vertices.size();
+ idx = mesh.vertices.size();
mesh.vertices.push_back(vertices[j]);
}
face.indices.push_back(idx);
}
- face.plane=p;
+ face.plane = p;
mesh.faces.push_back(face);
//add edge
- for(int j=0;j<face.indices.size();j++) {
+ for (int j = 0; j < face.indices.size(); j++) {
- int a=face.indices[j];
- int b=face.indices[(j+1)%face.indices.size()];
+ int a = face.indices[j];
+ int b = face.indices[(j + 1) % face.indices.size()];
- bool found=false;
- for(int k=0;k<mesh.edges.size();k++) {
+ bool found = false;
+ for (int k = 0; k < mesh.edges.size(); k++) {
- if (mesh.edges[k].a==a && mesh.edges[k].b==b) {
- found=true;
+ if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
+ found = true;
break;
}
- if (mesh.edges[k].b==a && mesh.edges[k].a==b) {
- found=true;
+ if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
+ found = true;
break;
}
}
@@ -884,28 +861,25 @@ Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes
if (found)
continue;
MeshData::Edge edge;
- edge.a=a;
- edge.b=b;
+ edge.a = a;
+ edge.b = b;
mesh.edges.push_back(edge);
}
-
-
}
return mesh;
}
-
-PoolVector<Plane> Geometry::build_box_planes(const Vector3& p_extents) {
+PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
PoolVector<Plane> planes;
- planes.push_back( Plane( Vector3(1,0,0), p_extents.x ) );
- planes.push_back( Plane( Vector3(-1,0,0), p_extents.x ) );
- planes.push_back( Plane( Vector3(0,1,0), p_extents.y ) );
- planes.push_back( Plane( Vector3(0,-1,0), p_extents.y ) );
- planes.push_back( Plane( Vector3(0,0,1), p_extents.z ) );
- planes.push_back( Plane( Vector3(0,0,-1), p_extents.z ) );
+ planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
+ planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
+ planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
+ planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
+ planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
+ planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
return planes;
}
@@ -914,103 +888,95 @@ PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_heig
PoolVector<Plane> planes;
- for (int i=0;i<p_sides;i++) {
+ for (int i = 0; i < p_sides; i++) {
Vector3 normal;
- normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_sides);
- normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_sides);
+ normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
+ normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
- planes.push_back( Plane( normal, p_radius ) );
+ planes.push_back(Plane(normal, p_radius));
}
Vector3 axis;
- axis[p_axis]=1.0;
+ axis[p_axis] = 1.0;
- planes.push_back( Plane( axis, p_height*0.5 ) );
- planes.push_back( Plane( -axis, p_height*0.5 ) );
+ planes.push_back(Plane(axis, p_height * 0.5));
+ planes.push_back(Plane(-axis, p_height * 0.5));
return planes;
-
}
-PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats,int p_lons, Vector3::Axis p_axis) {
-
+PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
PoolVector<Plane> planes;
Vector3 axis;
- axis[p_axis]=1.0;
+ axis[p_axis] = 1.0;
Vector3 axis_neg;
- axis_neg[(p_axis+1)%3]=1.0;
- axis_neg[(p_axis+2)%3]=1.0;
- axis_neg[p_axis]=-1.0;
+ axis_neg[(p_axis + 1) % 3] = 1.0;
+ axis_neg[(p_axis + 2) % 3] = 1.0;
+ axis_neg[p_axis] = -1.0;
- for (int i=0;i<p_lons;i++) {
+ for (int i = 0; i < p_lons; i++) {
Vector3 normal;
- normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_lons);
- normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_lons);
+ normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
+ normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
- planes.push_back( Plane( normal, p_radius ) );
+ planes.push_back(Plane(normal, p_radius));
- for (int j=1;j<=p_lats;j++) {
+ for (int j = 1; j <= p_lats; j++) {
//todo this is stupid, fix
- Vector3 angle = normal.linear_interpolate(axis,j/(real_t)p_lats).normalized();
- Vector3 pos = angle*p_radius;
- planes.push_back( Plane( pos, angle ) );
- planes.push_back( Plane( pos * axis_neg, angle * axis_neg) );
-
+ Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
+ Vector3 pos = angle * p_radius;
+ planes.push_back(Plane(pos, angle));
+ planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
}
}
return planes;
-
}
PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
PoolVector<Plane> planes;
- Vector3 axis;
- axis[p_axis]=1.0;
+ Vector3 axis;
+ axis[p_axis] = 1.0;
Vector3 axis_neg;
- axis_neg[(p_axis+1)%3]=1.0;
- axis_neg[(p_axis+2)%3]=1.0;
- axis_neg[p_axis]=-1.0;
+ axis_neg[(p_axis + 1) % 3] = 1.0;
+ axis_neg[(p_axis + 2) % 3] = 1.0;
+ axis_neg[p_axis] = -1.0;
- for (int i=0;i<p_sides;i++) {
+ for (int i = 0; i < p_sides; i++) {
Vector3 normal;
- normal[(p_axis+1)%3]=Math::cos(i*(2.0*Math_PI)/p_sides);
- normal[(p_axis+2)%3]=Math::sin(i*(2.0*Math_PI)/p_sides);
-
- planes.push_back( Plane( normal, p_radius ) );
+ normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
+ normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
- for (int j=1;j<=p_lats;j++) {
+ planes.push_back(Plane(normal, p_radius));
- Vector3 angle = normal.linear_interpolate(axis,j/(real_t)p_lats).normalized();
- Vector3 pos = axis*p_height*0.5 + angle*p_radius;
- planes.push_back( Plane( pos, angle ) );
- planes.push_back( Plane( pos * axis_neg, angle * axis_neg) );
+ for (int j = 1; j <= p_lats; j++) {
+ Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
+ Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
+ planes.push_back(Plane(pos, angle));
+ planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
}
}
-
return planes;
-
}
-
struct _AtlasWorkRect {
Size2i s;
Point2i p;
int idx;
- _FORCE_INLINE_ bool operator<(const _AtlasWorkRect& p_r) const { return s.width > p_r.s.width; };
+ _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
};
struct _AtlasWorkRectResult {
@@ -1020,7 +986,7 @@ struct _AtlasWorkRectResult {
int max_h;
};
-void Geometry::make_atlas(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size) {
+void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
//super simple, almost brute force scanline stacking fitter
//it's pretty basic for now, but it tries to make sure that the aspect ratio of the
@@ -1030,108 +996,100 @@ void Geometry::make_atlas(const Vector<Size2i>& p_rects,Vector<Point2i>& r_resul
// for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
// 256x8192 atlas (won't work anywhere).
- ERR_FAIL_COND(p_rects.size()==0);
+ ERR_FAIL_COND(p_rects.size() == 0);
Vector<_AtlasWorkRect> wrects;
wrects.resize(p_rects.size());
- for(int i=0;i<p_rects.size();i++) {
- wrects[i].s=p_rects[i];
- wrects[i].idx=i;
+ for (int i = 0; i < p_rects.size(); i++) {
+ wrects[i].s = p_rects[i];
+ wrects[i].idx = i;
}
wrects.sort();
int widest = wrects[0].s.width;
Vector<_AtlasWorkRectResult> results;
- for(int i=0;i<=12;i++) {
+ for (int i = 0; i <= 12; i++) {
- int w = 1<<i;
- int max_h=0;
- int max_w=0;
- if ( w < widest )
+ int w = 1 << i;
+ int max_h = 0;
+ int max_w = 0;
+ if (w < widest)
continue;
Vector<int> hmax;
hmax.resize(w);
- for(int j=0;j<w;j++)
- hmax[j]=0;
+ for (int j = 0; j < w; j++)
+ hmax[j] = 0;
//place them
- int ofs=0;
- int limit_h=0;
- for(int j=0;j<wrects.size();j++) {
-
+ int ofs = 0;
+ int limit_h = 0;
+ for (int j = 0; j < wrects.size(); j++) {
- if (ofs+wrects[j].s.width > w) {
+ if (ofs + wrects[j].s.width > w) {
- ofs=0;
+ ofs = 0;
}
- int from_y=0;
- for(int k=0;k<wrects[j].s.width;k++) {
+ int from_y = 0;
+ for (int k = 0; k < wrects[j].s.width; k++) {
- if (hmax[ofs+k] > from_y)
- from_y=hmax[ofs+k];
+ if (hmax[ofs + k] > from_y)
+ from_y = hmax[ofs + k];
}
- wrects[j].p.x=ofs;
- wrects[j].p.y=from_y;
- int end_h = from_y+wrects[j].s.height;
- int end_w = ofs+wrects[j].s.width;
- if (ofs==0)
- limit_h=end_h;
+ wrects[j].p.x = ofs;
+ wrects[j].p.y = from_y;
+ int end_h = from_y + wrects[j].s.height;
+ int end_w = ofs + wrects[j].s.width;
+ if (ofs == 0)
+ limit_h = end_h;
- for(int k=0;k<wrects[j].s.width;k++) {
+ for (int k = 0; k < wrects[j].s.width; k++) {
- hmax[ofs+k]=end_h;
+ hmax[ofs + k] = end_h;
}
if (end_h > max_h)
- max_h=end_h;
+ max_h = end_h;
if (end_w > max_w)
- max_w=end_w;
-
- if (ofs==0 || end_h>limit_h ) //while h limit not reched, keep stacking
- ofs+=wrects[j].s.width;
+ max_w = end_w;
+ if (ofs == 0 || end_h > limit_h) //while h limit not reched, keep stacking
+ ofs += wrects[j].s.width;
}
_AtlasWorkRectResult result;
- result.result=wrects;
- result.max_h=max_h;
- result.max_w=max_w;
+ result.result = wrects;
+ result.max_h = max_h;
+ result.max_w = max_w;
results.push_back(result);
-
}
//find the result with the best aspect ratio
- int best=-1;
- real_t best_aspect=1e20;
+ int best = -1;
+ real_t best_aspect = 1e20;
- for(int i=0;i<results.size();i++) {
+ for (int i = 0; i < results.size(); i++) {
real_t h = nearest_power_of_2(results[i].max_h);
real_t w = nearest_power_of_2(results[i].max_w);
- real_t aspect = h>w ? h/w : w/h;
+ real_t aspect = h > w ? h / w : w / h;
if (aspect < best_aspect) {
- best=i;
- best_aspect=aspect;
+ best = i;
+ best_aspect = aspect;
}
}
r_result.resize(p_rects.size());
- for(int i=0;i<p_rects.size();i++) {
+ for (int i = 0; i < p_rects.size(); i++) {
- r_result[ results[best].result[i].idx ]=results[best].result[i].p;
+ r_result[results[best].result[i].idx] = results[best].result[i].p;
}
- r_size=Size2(results[best].max_w,results[best].max_h );
-
+ r_size = Size2(results[best].max_w, results[best].max_h);
}
-
-
-
-
diff --git a/core/math/geometry.h b/core/math/geometry.h
index 1dd7df038d..93ab0be2e0 100644
--- a/core/math/geometry.h
+++ b/core/math/geometry.h
@@ -29,26 +29,23 @@
#ifndef GEOMETRY_H
#define GEOMETRY_H
-#include "vector3.h"
-#include "face3.h"
#include "dvector.h"
+#include "face3.h"
#include "math_2d.h"
-#include "vector.h"
-#include "print_string.h"
#include "object.h"
+#include "print_string.h"
#include "triangulate.h"
+#include "vector.h"
+#include "vector3.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class Geometry {
Geometry();
-public:
-
-
-
- static real_t get_closest_points_between_segments( const Vector2& p1,const Vector2& q1, const Vector2& p2,const Vector2& q2, Vector2& c1, Vector2& c2) {
+public:
+ static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
Vector2 d1 = q1 - p1; // Direction vector of segment S1
Vector2 d2 = q2 - p2; // Direction vector of segment S2
@@ -56,7 +53,7 @@ public:
real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative
real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative
real_t f = d2.dot(r);
- real_t s,t;
+ real_t s, t;
// Check if either or both segments degenerate into points
if (a <= CMP_EPSILON && e <= CMP_EPSILON) {
// Both segments degenerate into points
@@ -78,16 +75,16 @@ public:
} else {
// The general nondegenerate case starts here
real_t b = d1.dot(d2);
- real_t denom = a*e-b*b; // Always nonnegative
+ real_t denom = a * e - b * b; // Always nonnegative
// If segments not parallel, compute closest point on L1 to L2 and
// clamp to segment S1. Else pick arbitrary s (here 0)
if (denom != 0.0) {
- s = CLAMP((b*f - c*e) / denom, 0.0, 1.0);
+ s = CLAMP((b * f - c * e) / denom, 0.0, 1.0);
} else
s = 0.0;
// Compute point on L2 closest to S1(s) using
// t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
- t = (b*s + f) / e;
+ t = (b * s + f) / e;
//If t in [0,1] done. Else clamp t, recompute s for the new value
// of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
@@ -106,12 +103,10 @@ public:
return Math::sqrt((c1 - c2).dot(c1 - c2));
}
-
- static void get_closest_points_between_segments(const Vector3& p1,const Vector3& p2,const Vector3& q1,const Vector3& q2,Vector3& c1, Vector3& c2)
- {
+ static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) {
#if 0
//do the function 'd' as defined by pb. I think is is dot product of some sort
-#define d_of(m,n,o,p) ( (m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z) )
+#define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z))
//caluclate the parpametric position on the 2 curves, mua and mub
real_t mua = ( d_of(p1,q1,q2,q1) * d_of(q2,q1,p2,p1) - d_of(p1,q1,p2,p1) * d_of(q2,q1,q2,q1) ) / ( d_of(p2,p1,p2,p1) * d_of(q2,q1,q2,q1) - d_of(q2,q1,p2,p1) * d_of(q2,q1,p2,p1) );
@@ -126,25 +121,24 @@ public:
c2 = q1.linear_interpolate(q2,mub);
#endif
- Vector3 u = p2 - p1;
- Vector3 v = q2 - q1;
- Vector3 w = p1 - q1;
- float a = u.dot(u);
- float b = u.dot(v);
- float c = v.dot(v); // always >= 0
- float d = u.dot(w);
- float e = v.dot(w);
- float D = a*c - b*b; // always >= 0
- float sc, tc;
+ Vector3 u = p2 - p1;
+ Vector3 v = q2 - q1;
+ Vector3 w = p1 - q1;
+ float a = u.dot(u);
+ float b = u.dot(v);
+ float c = v.dot(v); // always >= 0
+ float d = u.dot(w);
+ float e = v.dot(w);
+ float D = a * c - b * b; // always >= 0
+ float sc, tc;
// compute the line parameters of the two closest points
- if (D < CMP_EPSILON) { // the lines are almost parallel
+ if (D < CMP_EPSILON) { // the lines are almost parallel
sc = 0.0;
- tc = (b>c ? d/b : e/c); // use the largest denominator
- }
- else {
- sc = (b*e - c*d) / D;
- tc = (a*e - b*d) / D;
+ tc = (b > c ? d / b : e / c); // use the largest denominator
+ } else {
+ sc = (b * e - c * d) / D;
+ tc = (a * e - b * d) / D;
}
c1 = w + sc * u;
@@ -153,92 +147,89 @@ public:
//Vector dP = w + (sc * u) - (tc * v); // = L1(sc) - L2(tc)
}
- static real_t get_closest_distance_between_segments( const Vector3& p_from_a,const Vector3& p_to_a, const Vector3& p_from_b,const Vector3& p_to_b) {
- Vector3 u = p_to_a - p_from_a;
- Vector3 v = p_to_b - p_from_b;
- Vector3 w = p_from_a - p_to_a;
- real_t a = u.dot(u); // always >= 0
- real_t b = u.dot(v);
- real_t c = v.dot(v); // always >= 0
- real_t d = u.dot(w);
- real_t e = v.dot(w);
- real_t D = a*c - b*b; // always >= 0
- real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
- real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
-
- // compute the line parameters of the two closest points
- if (D < CMP_EPSILON) { // the lines are almost parallel
- sN = 0.0; // force using point P0 on segment S1
- sD = 1.0; // to prevent possible division by 0.0 later
- tN = e;
- tD = c;
- }
- else { // get the closest points on the infinite lines
- sN = (b*e - c*d);
- tN = (a*e - b*d);
- if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
- sN = 0.0;
- tN = e;
- tD = c;
- }
- else if (sN > sD) { // sc > 1 => the s=1 edge is visible
- sN = sD;
- tN = e + b;
- tD = c;
- }
- }
-
- if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
- tN = 0.0;
- // recompute sc for this edge
- if (-d < 0.0)
- sN = 0.0;
- else if (-d > a)
- sN = sD;
- else {
- sN = -d;
- sD = a;
+ static real_t get_closest_distance_between_segments(const Vector3 &p_from_a, const Vector3 &p_to_a, const Vector3 &p_from_b, const Vector3 &p_to_b) {
+ Vector3 u = p_to_a - p_from_a;
+ Vector3 v = p_to_b - p_from_b;
+ Vector3 w = p_from_a - p_to_a;
+ real_t a = u.dot(u); // always >= 0
+ real_t b = u.dot(v);
+ real_t c = v.dot(v); // always >= 0
+ real_t d = u.dot(w);
+ real_t e = v.dot(w);
+ real_t D = a * c - b * b; // always >= 0
+ real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
+ real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
+
+ // compute the line parameters of the two closest points
+ if (D < CMP_EPSILON) { // the lines are almost parallel
+ sN = 0.0; // force using point P0 on segment S1
+ sD = 1.0; // to prevent possible division by 0.0 later
+ tN = e;
+ tD = c;
+ } else { // get the closest points on the infinite lines
+ sN = (b * e - c * d);
+ tN = (a * e - b * d);
+ if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
+ sN = 0.0;
+ tN = e;
+ tD = c;
+ } else if (sN > sD) { // sc > 1 => the s=1 edge is visible
+ sN = sD;
+ tN = e + b;
+ tD = c;
+ }
}
- }
- else if (tN > tD) { // tc > 1 => the t=1 edge is visible
- tN = tD;
- // recompute sc for this edge
- if ((-d + b) < 0.0)
- sN = 0;
- else if ((-d + b) > a)
- sN = sD;
- else {
- sN = (-d + b);
- sD = a;
+
+ if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
+ tN = 0.0;
+ // recompute sc for this edge
+ if (-d < 0.0)
+ sN = 0.0;
+ else if (-d > a)
+ sN = sD;
+ else {
+ sN = -d;
+ sD = a;
+ }
+ } else if (tN > tD) { // tc > 1 => the t=1 edge is visible
+ tN = tD;
+ // recompute sc for this edge
+ if ((-d + b) < 0.0)
+ sN = 0;
+ else if ((-d + b) > a)
+ sN = sD;
+ else {
+ sN = (-d + b);
+ sD = a;
+ }
}
- }
- // finally do the division to get sc and tc
- sc = (Math::abs(sN) < CMP_EPSILON ? 0.0 : sN / sD);
- tc = (Math::abs(tN) < CMP_EPSILON ? 0.0 : tN / tD);
+ // finally do the division to get sc and tc
+ sc = (Math::abs(sN) < CMP_EPSILON ? 0.0 : sN / sD);
+ tc = (Math::abs(tN) < CMP_EPSILON ? 0.0 : tN / tD);
- // get the difference of the two closest points
- Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
+ // get the difference of the two closest points
+ Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
- return dP.length(); // return the closest distance
+ return dP.length(); // return the closest distance
}
- static inline bool ray_intersects_triangle( const Vector3& p_from, const Vector3& p_dir, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2,Vector3* r_res=0) {
- Vector3 e1=p_v1-p_v0;
- Vector3 e2=p_v2-p_v0;
+ static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
+ Vector3 e1 = p_v1 - p_v0;
+ Vector3 e2 = p_v2 - p_v0;
Vector3 h = p_dir.cross(e2);
- real_t a =e1.dot(h);
- if (a>-CMP_EPSILON && a < CMP_EPSILON) // parallel test
+ real_t a = e1.dot(h);
+ if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test
return false;
- real_t f=1.0/a;
+ real_t f = 1.0 / a;
- Vector3 s=p_from-p_v0;
+ Vector3 s = p_from - p_v0;
real_t u = f * s.dot(h);
- if ( u< 0.0 || u > 1.0)
+ if (u < 0.0 || u > 1.0)
return false;
- Vector3 q=s.cross(e1);
+ Vector3 q = s.cross(e1);
real_t v = f * p_dir.dot(q);
@@ -249,34 +240,34 @@ public:
// the intersection point is on the line
real_t t = f * e2.dot(q);
- if (t > 0.00001) {// ray intersection
+ if (t > 0.00001) { // ray intersection
if (r_res)
- *r_res=p_from+p_dir*t;
+ *r_res = p_from + p_dir * t;
return true;
} else // this means that there is a line intersection
// but not a ray intersection
return false;
}
- static inline bool segment_intersects_triangle( const Vector3& p_from, const Vector3& p_to, const Vector3& p_v0,const Vector3& p_v1,const Vector3& p_v2,Vector3* r_res=0) {
+ static inline bool segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
- Vector3 rel=p_to-p_from;
- Vector3 e1=p_v1-p_v0;
- Vector3 e2=p_v2-p_v0;
+ Vector3 rel = p_to - p_from;
+ Vector3 e1 = p_v1 - p_v0;
+ Vector3 e2 = p_v2 - p_v0;
Vector3 h = rel.cross(e2);
- real_t a =e1.dot(h);
- if (a>-CMP_EPSILON && a < CMP_EPSILON) // parallel test
+ real_t a = e1.dot(h);
+ if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test
return false;
- real_t f=1.0/a;
+ real_t f = 1.0 / a;
- Vector3 s=p_from-p_v0;
+ Vector3 s = p_from - p_v0;
real_t u = f * s.dot(h);
- if ( u< 0.0 || u > 1.0)
+ if (u < 0.0 || u > 1.0)
return false;
- Vector3 q=s.cross(e1);
+ Vector3 q = s.cross(e1);
real_t v = f * rel.dot(q);
@@ -287,124 +278,122 @@ public:
// the intersection point is on the line
real_t t = f * e2.dot(q);
- if (t > CMP_EPSILON && t<=1.0) {// ray intersection
+ if (t > CMP_EPSILON && t <= 1.0) { // ray intersection
if (r_res)
- *r_res=p_from+rel*t;
+ *r_res = p_from + rel * t;
return true;
} else // this means that there is a line intersection
// but not a ray intersection
return false;
}
- static inline bool segment_intersects_sphere( const Vector3& p_from, const Vector3& p_to, const Vector3& p_sphere_pos,real_t p_sphere_radius,Vector3* r_res=0,Vector3 *r_norm=0) {
-
+ static inline bool segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
- Vector3 sphere_pos=p_sphere_pos-p_from;
- Vector3 rel=(p_to-p_from);
- real_t rel_l=rel.length();
- if (rel_l<CMP_EPSILON)
+ Vector3 sphere_pos = p_sphere_pos - p_from;
+ Vector3 rel = (p_to - p_from);
+ real_t rel_l = rel.length();
+ if (rel_l < CMP_EPSILON)
return false; // both points are the same
- Vector3 normal=rel/rel_l;
+ Vector3 normal = rel / rel_l;
- real_t sphere_d=normal.dot(sphere_pos);
+ real_t sphere_d = normal.dot(sphere_pos);
//Vector3 ray_closest=normal*sphere_d;
- real_t ray_distance=sphere_pos.distance_to(normal*sphere_d);
+ real_t ray_distance = sphere_pos.distance_to(normal * sphere_d);
- if (ray_distance>=p_sphere_radius)
+ if (ray_distance >= p_sphere_radius)
return false;
- real_t inters_d2=p_sphere_radius*p_sphere_radius - ray_distance*ray_distance;
- real_t inters_d=sphere_d;
+ real_t inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance;
+ real_t inters_d = sphere_d;
- if (inters_d2>=CMP_EPSILON)
- inters_d-=Math::sqrt(inters_d2);
+ if (inters_d2 >= CMP_EPSILON)
+ inters_d -= Math::sqrt(inters_d2);
// check in segment
- if (inters_d<0 || inters_d>rel_l)
+ if (inters_d < 0 || inters_d > rel_l)
return false;
- Vector3 result=p_from+normal*inters_d;
+ Vector3 result = p_from + normal * inters_d;
if (r_res)
- *r_res=result;
+ *r_res = result;
if (r_norm)
- *r_norm=(result-p_sphere_pos).normalized();
+ *r_norm = (result - p_sphere_pos).normalized();
return true;
}
- static inline bool segment_intersects_cylinder( const Vector3& p_from, const Vector3& p_to, real_t p_height,real_t p_radius,Vector3* r_res=0,Vector3 *r_norm=0) {
+ static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, real_t p_height, real_t p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
- Vector3 rel=(p_to-p_from);
- real_t rel_l=rel.length();
- if (rel_l<CMP_EPSILON)
+ Vector3 rel = (p_to - p_from);
+ real_t rel_l = rel.length();
+ if (rel_l < CMP_EPSILON)
return false; // both points are the same
// first check if they are parallel
- Vector3 normal=(rel/rel_l);
- Vector3 crs = normal.cross(Vector3(0,0,1));
- real_t crs_l=crs.length();
+ Vector3 normal = (rel / rel_l);
+ Vector3 crs = normal.cross(Vector3(0, 0, 1));
+ real_t crs_l = crs.length();
Vector3 z_dir;
- if(crs_l<CMP_EPSILON) {
+ if (crs_l < CMP_EPSILON) {
//blahblah parallel
- z_dir=Vector3(1,0,0); //any x/y vector ok
+ z_dir = Vector3(1, 0, 0); //any x/y vector ok
} else {
- z_dir=crs/crs_l;
+ z_dir = crs / crs_l;
}
- real_t dist=z_dir.dot(p_from);
+ real_t dist = z_dir.dot(p_from);
- if (dist>=p_radius)
+ if (dist >= p_radius)
return false; // too far away
// convert to 2D
- real_t w2=p_radius*p_radius-dist*dist;
- if (w2<CMP_EPSILON)
+ real_t w2 = p_radius * p_radius - dist * dist;
+ if (w2 < CMP_EPSILON)
return false; //avoid numerical error
- Size2 size(Math::sqrt(w2),p_height*0.5);
-
- Vector3 x_dir=z_dir.cross(Vector3(0,0,1)).normalized();
+ Size2 size(Math::sqrt(w2), p_height * 0.5);
- Vector2 from2D(x_dir.dot(p_from),p_from.z);
- Vector2 to2D(x_dir.dot(p_to),p_to.z);
+ Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized();
- real_t min=0,max=1;
+ Vector2 from2D(x_dir.dot(p_from), p_from.z);
+ Vector2 to2D(x_dir.dot(p_to), p_to.z);
- int axis=-1;
+ real_t min = 0, max = 1;
- for(int i=0;i<2;i++) {
+ int axis = -1;
- real_t seg_from=from2D[i];
- real_t seg_to=to2D[i];
- real_t box_begin=-size[i];
- real_t box_end=size[i];
- real_t cmin,cmax;
+ for (int i = 0; i < 2; i++) {
+ real_t seg_from = from2D[i];
+ real_t seg_to = to2D[i];
+ real_t box_begin = -size[i];
+ real_t box_end = size[i];
+ real_t cmin, cmax;
if (seg_from < seg_to) {
if (seg_from > box_end || seg_to < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0;
- cmax = (seg_to > box_end)?((box_end - seg_from)/length):1;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
+ cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
} else {
if (seg_to > box_end || seg_from < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from > box_end)?(box_end - seg_from)/length:0;
- cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
+ cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
}
if (cmin > min) {
min = cmin;
- axis=i;
+ axis = i;
}
if (cmax < max)
max = cmax;
@@ -412,254 +401,245 @@ public:
return false;
}
-
// convert to 3D again
- Vector3 result = p_from + (rel*min);
+ Vector3 result = p_from + (rel * min);
Vector3 res_normal = result;
- if (axis==0) {
- res_normal.z=0;
+ if (axis == 0) {
+ res_normal.z = 0;
} else {
- res_normal.x=0;
- res_normal.y=0;
+ res_normal.x = 0;
+ res_normal.y = 0;
}
-
res_normal.normalize();
if (r_res)
- *r_res=result;
+ *r_res = result;
if (r_norm)
- *r_norm=res_normal;
+ *r_norm = res_normal;
return true;
}
+ static bool segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Plane *p_planes, int p_plane_count, Vector3 *p_res, Vector3 *p_norm) {
- static bool segment_intersects_convex(const Vector3& p_from, const Vector3& p_to,const Plane* p_planes, int p_plane_count,Vector3 *p_res, Vector3 *p_norm) {
+ real_t min = -1e20, max = 1e20;
- real_t min=-1e20,max=1e20;
+ Vector3 rel = p_to - p_from;
+ real_t rel_l = rel.length();
- Vector3 rel=p_to-p_from;
- real_t rel_l=rel.length();
-
- if (rel_l<CMP_EPSILON)
+ if (rel_l < CMP_EPSILON)
return false;
- Vector3 dir=rel/rel_l;
+ Vector3 dir = rel / rel_l;
- int min_index=-1;
+ int min_index = -1;
- for (int i=0;i<p_plane_count;i++) {
+ for (int i = 0; i < p_plane_count; i++) {
- const Plane&p=p_planes[i];
+ const Plane &p = p_planes[i];
- real_t den=p.normal.dot( dir );
+ real_t den = p.normal.dot(dir);
//printf("den is %i\n",den);
- if (Math::abs(den)<=CMP_EPSILON)
+ if (Math::abs(den) <= CMP_EPSILON)
continue; // ignore parallel plane
+ real_t dist = -p.distance_to(p_from) / den;
- real_t dist=-p.distance_to(p_from ) / den;
-
- if (den>0) {
+ if (den > 0) {
//backwards facing plane
- if (dist<max)
- max=dist;
+ if (dist < max)
+ max = dist;
} else {
//front facing plane
- if (dist>min) {
- min=dist;
- min_index=i;
+ if (dist > min) {
+ min = dist;
+ min_index = i;
}
}
}
- if (max<=min || min<0 || min>rel_l || min_index==-1) // exit conditions
+ if (max <= min || min < 0 || min > rel_l || min_index == -1) // exit conditions
return false; // no intersection
if (p_res)
- *p_res=p_from+dir*min;
+ *p_res = p_from + dir * min;
if (p_norm)
- *p_norm=p_planes[min_index].normal;
+ *p_norm = p_planes[min_index].normal;
return true;
}
- static Vector3 get_closest_point_to_segment(const Vector3& p_point, const Vector3 *p_segment) {
+ static Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 *p_segment) {
- Vector3 p=p_point-p_segment[0];
- Vector3 n=p_segment[1]-p_segment[0];
- real_t l =n.length();
- if (l<1e-10)
+ Vector3 p = p_point - p_segment[0];
+ Vector3 n = p_segment[1] - p_segment[0];
+ real_t l = n.length();
+ if (l < 1e-10)
return p_segment[0]; // both points are the same, just give any
- n/=l;
+ n /= l;
- real_t d=n.dot(p);
+ real_t d = n.dot(p);
- if (d<=0.0)
+ if (d <= 0.0)
return p_segment[0]; // before first point
- else if (d>=l)
+ else if (d >= l)
return p_segment[1]; // after first point
else
- return p_segment[0]+n*d; // inside
+ return p_segment[0] + n * d; // inside
}
- static Vector3 get_closest_point_to_segment_uncapped(const Vector3& p_point, const Vector3 *p_segment) {
+ static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) {
- Vector3 p=p_point-p_segment[0];
- Vector3 n=p_segment[1]-p_segment[0];
- real_t l =n.length();
- if (l<1e-10)
+ Vector3 p = p_point - p_segment[0];
+ Vector3 n = p_segment[1] - p_segment[0];
+ real_t l = n.length();
+ if (l < 1e-10)
return p_segment[0]; // both points are the same, just give any
- n/=l;
+ n /= l;
- real_t d=n.dot(p);
+ real_t d = n.dot(p);
- return p_segment[0]+n*d; // inside
+ return p_segment[0] + n * d; // inside
}
- static Vector2 get_closest_point_to_segment_2d(const Vector2& p_point, const Vector2 *p_segment) {
+ static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) {
- Vector2 p=p_point-p_segment[0];
- Vector2 n=p_segment[1]-p_segment[0];
- real_t l =n.length();
- if (l<1e-10)
+ Vector2 p = p_point - p_segment[0];
+ Vector2 n = p_segment[1] - p_segment[0];
+ real_t l = n.length();
+ if (l < 1e-10)
return p_segment[0]; // both points are the same, just give any
- n/=l;
+ n /= l;
- real_t d=n.dot(p);
+ real_t d = n.dot(p);
- if (d<=0.0)
+ if (d <= 0.0)
return p_segment[0]; // before first point
- else if (d>=l)
+ else if (d >= l)
return p_segment[1]; // after first point
else
- return p_segment[0]+n*d; // inside
+ return p_segment[0] + n * d; // inside
}
- static bool is_point_in_triangle(const Vector2& s, const Vector2& a, const Vector2& b, const Vector2& c)
- {
- int as_x = s.x-a.x;
- int as_y = s.y-a.y;
+ static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
+ int as_x = s.x - a.x;
+ int as_y = s.y - a.y;
- bool s_ab = (b.x-a.x)*as_y-(b.y-a.y)*as_x > 0;
+ bool s_ab = (b.x - a.x) * as_y - (b.y - a.y) * as_x > 0;
- if(((c.x-a.x)*as_y-(c.y-a.y)*as_x > 0) == s_ab) return false;
+ if (((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0) == s_ab) return false;
- if(((c.x-b.x)*(s.y-b.y)-(c.y-b.y)*(s.x-b.x) > 0) != s_ab) return false;
+ if (((c.x - b.x) * (s.y - b.y) - (c.y - b.y) * (s.x - b.x) > 0) != s_ab) return false;
- return true;
+ return true;
}
- static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2& p_point, const Vector2 *p_segment) {
+ static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) {
- Vector2 p=p_point-p_segment[0];
- Vector2 n=p_segment[1]-p_segment[0];
- real_t l =n.length();
- if (l<1e-10)
+ Vector2 p = p_point - p_segment[0];
+ Vector2 n = p_segment[1] - p_segment[0];
+ real_t l = n.length();
+ if (l < 1e-10)
return p_segment[0]; // both points are the same, just give any
- n/=l;
+ n /= l;
- real_t d=n.dot(p);
+ real_t d = n.dot(p);
- return p_segment[0]+n*d; // inside
+ return p_segment[0] + n * d; // inside
}
- static bool segment_intersects_segment_2d(const Vector2& p_from_a,const Vector2& p_to_a,const Vector2& p_from_b,const Vector2& p_to_b,Vector2* r_result) {
+ static bool segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) {
- Vector2 B = p_to_a-p_from_a;
- Vector2 C = p_from_b-p_from_a;
- Vector2 D = p_to_b-p_from_a;
+ Vector2 B = p_to_a - p_from_a;
+ Vector2 C = p_from_b - p_from_a;
+ Vector2 D = p_to_b - p_from_a;
real_t ABlen = B.dot(B);
- if (ABlen<=0)
+ if (ABlen <= 0)
return false;
- Vector2 Bn = B/ABlen;
- C = Vector2( C.x*Bn.x + C.y*Bn.y, C.y*Bn.x - C.x*Bn.y );
- D = Vector2( D.x*Bn.x + D.y*Bn.y, D.y*Bn.x - D.x*Bn.y );
+ Vector2 Bn = B / ABlen;
+ C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
+ D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
- if ((C.y<0 && D.y<0) || (C.y>=0 && D.y>=0))
+ if ((C.y < 0 && D.y < 0) || (C.y >= 0 && D.y >= 0))
return false;
- real_t ABpos=D.x+(C.x-D.x)*D.y/(D.y-C.y);
+ real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
// Fail if segment C-D crosses line A-B outside of segment A-B.
- if (ABpos<0 || ABpos>1.0)
+ if (ABpos < 0 || ABpos > 1.0)
return false;
// (4) Apply the discovered position to line A-B in the original coordinate system.
if (r_result)
- *r_result=p_from_a+B*ABpos;
+ *r_result = p_from_a + B * ABpos;
return true;
}
+ static inline bool point_in_projected_triangle(const Vector3 &p_point, const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) {
- static inline bool point_in_projected_triangle(const Vector3& p_point,const Vector3& p_v1,const Vector3& p_v2,const Vector3& p_v3) {
-
-
- Vector3 face_n = (p_v1-p_v3).cross(p_v1-p_v2);
+ Vector3 face_n = (p_v1 - p_v3).cross(p_v1 - p_v2);
- Vector3 n1 = (p_point-p_v3).cross(p_point-p_v2);
+ Vector3 n1 = (p_point - p_v3).cross(p_point - p_v2);
- if (face_n.dot(n1)<0)
+ if (face_n.dot(n1) < 0)
return false;
- Vector3 n2 = (p_v1-p_v3).cross(p_v1-p_point);
+ Vector3 n2 = (p_v1 - p_v3).cross(p_v1 - p_point);
- if (face_n.dot(n2)<0)
+ if (face_n.dot(n2) < 0)
return false;
- Vector3 n3 = (p_v1-p_point).cross(p_v1-p_v2);
+ Vector3 n3 = (p_v1 - p_point).cross(p_v1 - p_v2);
- if (face_n.dot(n3)<0)
+ if (face_n.dot(n3) < 0)
return false;
return true;
-
}
- static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle,const Vector3& p_normal,const Vector3& p_sphere_pos, real_t p_sphere_radius,Vector3& r_triangle_contact,Vector3& r_sphere_contact) {
+ static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle, const Vector3 &p_normal, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 &r_triangle_contact, Vector3 &r_sphere_contact) {
- real_t d=p_normal.dot(p_sphere_pos)-p_normal.dot(p_triangle[0]);
+ real_t d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]);
if (d > p_sphere_radius || d < -p_sphere_radius) // not touching the plane of the face, return
return false;
- Vector3 contact=p_sphere_pos - (p_normal*d);
+ Vector3 contact = p_sphere_pos - (p_normal * d);
/** 2nd) TEST INSIDE TRIANGLE **/
-
- if (Geometry::point_in_projected_triangle(contact,p_triangle[0],p_triangle[1],p_triangle[2])) {
- r_triangle_contact=contact;
- r_sphere_contact=p_sphere_pos-p_normal*p_sphere_radius;
+ if (Geometry::point_in_projected_triangle(contact, p_triangle[0], p_triangle[1], p_triangle[2])) {
+ r_triangle_contact = contact;
+ r_sphere_contact = p_sphere_pos - p_normal * p_sphere_radius;
//printf("solved inside triangle\n");
return true;
}
/** 3rd TEST INSIDE EDGE CYLINDERS **/
- const Vector3 verts[4]={p_triangle[0],p_triangle[1],p_triangle[2],p_triangle[0]}; // for() friendly
+ const Vector3 verts[4] = { p_triangle[0], p_triangle[1], p_triangle[2], p_triangle[0] }; // for() friendly
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
// check edge cylinder
- Vector3 n1=verts[i]-verts[i+1];
- Vector3 n2=p_sphere_pos-verts[i+1];
+ Vector3 n1 = verts[i] - verts[i + 1];
+ Vector3 n2 = p_sphere_pos - verts[i + 1];
///@TODO i could discard by range here to make the algorithm quicker? dunno..
// check point within cylinder radius
- Vector3 axis =n1.cross(n2).cross(n1);
+ Vector3 axis = n1.cross(n2).cross(n1);
axis.normalize(); // ugh
- real_t ad=axis.dot(n2);
+ real_t ad = axis.dot(n2);
- if (ABS(ad)>p_sphere_radius) {
+ if (ABS(ad) > p_sphere_radius) {
// no chance with this edge, too far away
continue;
}
@@ -669,34 +649,34 @@ public:
real_t sphere_at = n1.dot(n2);
- if (sphere_at>=0 && sphere_at<n1.dot(n1)) {
+ if (sphere_at >= 0 && sphere_at < n1.dot(n1)) {
- r_triangle_contact=p_sphere_pos-axis*(axis.dot(n2));
- r_sphere_contact=p_sphere_pos-axis*p_sphere_radius;
+ r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2));
+ r_sphere_contact = p_sphere_pos - axis * p_sphere_radius;
// point inside here
//printf("solved inside edge\n");
return true;
}
- real_t r2=p_sphere_radius*p_sphere_radius;
+ real_t r2 = p_sphere_radius * p_sphere_radius;
- if (n2.length_squared()<r2) {
+ if (n2.length_squared() < r2) {
- Vector3 n=(p_sphere_pos-verts[i+1]).normalized();
+ Vector3 n = (p_sphere_pos - verts[i + 1]).normalized();
//r_triangle_contact=verts[i+1]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2));
- r_triangle_contact=verts[i+1];
- r_sphere_contact=p_sphere_pos-n*p_sphere_radius;
+ r_triangle_contact = verts[i + 1];
+ r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
//printf("solved inside point segment 1\n");
return true;
}
- if (n2.distance_squared_to(n1)<r2) {
- Vector3 n=(p_sphere_pos-verts[i]).normalized();
+ if (n2.distance_squared_to(n1) < r2) {
+ Vector3 n = (p_sphere_pos - verts[i]).normalized();
//r_triangle_contact=verts[i]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2));
- r_triangle_contact=verts[i];
- r_sphere_contact=p_sphere_pos-n*p_sphere_radius;
+ r_triangle_contact = verts[i];
+ r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
//printf("solved inside point segment 1\n");
return true;
}
@@ -707,56 +687,51 @@ public:
return false;
}
+ static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
+ Vector2 line_vec = p_to - p_from;
+ Vector2 vec_to_line = p_from - p_circle_pos;
- static real_t segment_intersects_circle(const Vector2& p_from, const Vector2& p_to, const Vector2& p_circle_pos, real_t p_circle_radius) {
-
- Vector2 line_vec = p_to - p_from;
- Vector2 vec_to_line = p_from - p_circle_pos;
-
- /* create a quadratic formula of the form ax^2 + bx + c = 0 */
- real_t a, b, c;
+ /* create a quadratic formula of the form ax^2 + bx + c = 0 */
+ real_t a, b, c;
- a = line_vec.dot(line_vec);
- b = 2 * vec_to_line.dot(line_vec);
- c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
+ a = line_vec.dot(line_vec);
+ b = 2 * vec_to_line.dot(line_vec);
+ c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
- /* solve for t */
- real_t sqrtterm = b*b - 4*a*c;
+ /* solve for t */
+ real_t sqrtterm = b * b - 4 * a * c;
- /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */
- if(sqrtterm < 0) return -1;
+ /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */
+ if (sqrtterm < 0) return -1;
- /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) then the following can be skipped and we can just return the equivalent of res1 */
- sqrtterm = Math::sqrt(sqrtterm);
- real_t res1 = ( -b - sqrtterm ) / (2 * a);
- //real_t res2 = ( -b + sqrtterm ) / (2 * a);
-
- return (res1 >= 0 && res1 <= 1) ? res1 : -1;
+ /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) then the following can be skipped and we can just return the equivalent of res1 */
+ sqrtterm = Math::sqrt(sqrtterm);
+ real_t res1 = (-b - sqrtterm) / (2 * a);
+ //real_t res2 = ( -b + sqrtterm ) / (2 * a);
+ return (res1 >= 0 && res1 <= 1) ? res1 : -1;
}
-
-
- static inline Vector<Vector3> clip_polygon(const Vector<Vector3>& polygon,const Plane& p_plane) {
+ static inline Vector<Vector3> clip_polygon(const Vector<Vector3> &polygon, const Plane &p_plane) {
enum LocationCache {
- LOC_INSIDE=1,
- LOC_BOUNDARY=0,
- LOC_OUTSIDE=-1
+ LOC_INSIDE = 1,
+ LOC_BOUNDARY = 0,
+ LOC_OUTSIDE = -1
};
- if (polygon.size()==0)
+ if (polygon.size() == 0)
return polygon;
- int *location_cache = (int*)alloca(sizeof(int)*polygon.size());
+ int *location_cache = (int *)alloca(sizeof(int) * polygon.size());
int inside_count = 0;
int outside_count = 0;
for (int a = 0; a < polygon.size(); a++) {
//real_t p_plane.d = (*this) * polygon[a];
real_t dist = p_plane.distance_to(polygon[a]);
- if (dist <-CMP_POINT_IN_PLANE_EPSILON) {
+ if (dist < -CMP_POINT_IN_PLANE_EPSILON) {
location_cache[a] = LOC_INSIDE;
inside_count++;
} else {
@@ -785,24 +760,24 @@ public:
int loc = location_cache[index];
if (loc == LOC_OUTSIDE) {
if (location_cache[previous] == LOC_INSIDE) {
- const Vector3& v1 = polygon[previous];
- const Vector3& v2 = polygon[index];
-
- Vector3 segment= v1 - v2;
- real_t den=p_plane.normal.dot( segment );
- real_t dist=p_plane.distance_to( v1 ) / den;
- dist=-dist;
- clipped.push_back( v1 + segment * dist );
+ const Vector3 &v1 = polygon[previous];
+ const Vector3 &v2 = polygon[index];
+
+ Vector3 segment = v1 - v2;
+ real_t den = p_plane.normal.dot(segment);
+ real_t dist = p_plane.distance_to(v1) / den;
+ dist = -dist;
+ clipped.push_back(v1 + segment * dist);
}
} else {
- const Vector3& v1 = polygon[index];
+ const Vector3 &v1 = polygon[index];
if ((loc == LOC_INSIDE) && (location_cache[previous] == LOC_OUTSIDE)) {
- const Vector3& v2 = polygon[previous];
- Vector3 segment= v1 - v2;
- real_t den=p_plane.normal.dot( segment );
- real_t dist=p_plane.distance_to( v1 ) / den;
- dist=-dist;
- clipped.push_back( v1 + segment * dist );
+ const Vector3 &v2 = polygon[previous];
+ Vector3 segment = v1 - v2;
+ real_t den = p_plane.normal.dot(segment);
+ real_t dist = p_plane.distance_to(v1) / den;
+ dist = -dist;
+ clipped.push_back(v1 + segment * dist);
}
clipped.push_back(v1);
@@ -814,30 +789,26 @@ public:
return clipped;
}
-
- static Vector<int> triangulate_polygon(const Vector<Vector2>& p_polygon) {
+ static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
Vector<int> triangles;
- if (!Triangulate::triangulate(p_polygon,triangles))
+ if (!Triangulate::triangulate(p_polygon, triangles))
return Vector<int>(); //fail
return triangles;
}
- static Vector< Vector<Vector2> > (*_decompose_func)(const Vector<Vector2>& p_polygon);
- static Vector< Vector<Vector2> > decompose_polygon(const Vector<Vector2>& p_polygon) {
+ static Vector<Vector<Vector2> > (*_decompose_func)(const Vector<Vector2> &p_polygon);
+ static Vector<Vector<Vector2> > decompose_polygon(const Vector<Vector2> &p_polygon) {
if (_decompose_func)
return _decompose_func(p_polygon);
- return Vector< Vector<Vector2> >();
-
+ return Vector<Vector<Vector2> >();
}
+ static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array);
- static PoolVector< PoolVector< Face3 > > separate_objects( PoolVector< Face3 > p_array );
-
- static PoolVector< Face3 > wrap_geometry( PoolVector< Face3 > p_array, real_t *p_error=NULL ); ///< create a "wrap" that encloses the given geometry
-
+ static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL); ///< create a "wrap" that encloses the given geometry
struct MeshData {
@@ -850,94 +821,89 @@ public:
struct Edge {
- int a,b;
+ int a, b;
};
Vector<Edge> edges;
- Vector< Vector3 > vertices;
+ Vector<Vector3> vertices;
void optimize_vertices();
};
+ _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3 &p_vector) {
+ int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 4.0 / Math_PI + 0.5));
- _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3& p_vector) {
-
- int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0,1,0)))*4.0/Math_PI+0.5));
-
- if (lat==0) {
+ if (lat == 0) {
return 24;
- } else if (lat==4) {
+ } else if (lat == 4) {
return 25;
}
- int lon = Math::fast_ftoi(Math::floor( (Math_PI+Math::atan2(p_vector.x,p_vector.z))*8.0/(Math_PI*2.0) + 0.5))%8;
+ int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 8.0 / (Math_PI * 2.0) + 0.5)) % 8;
- return lon+(lat-1)*8;
+ return lon + (lat - 1) * 8;
}
_FORCE_INLINE_ static int get_uv84_normal_bit_neighbors(int p_idx) {
- if (p_idx==24) {
- return 1|2|4|8;
- } else if (p_idx==25) {
- return (1<<23)|(1<<22)|(1<<21)|(1<<20);
+ if (p_idx == 24) {
+ return 1 | 2 | 4 | 8;
+ } else if (p_idx == 25) {
+ return (1 << 23) | (1 << 22) | (1 << 21) | (1 << 20);
} else {
int ret = 0;
- if ((p_idx%8) == 0)
- ret|=(1<<(p_idx+7));
+ if ((p_idx % 8) == 0)
+ ret |= (1 << (p_idx + 7));
else
- ret|=(1<<(p_idx-1));
- if ((p_idx%8) == 7)
- ret|=(1<<(p_idx-7));
+ ret |= (1 << (p_idx - 1));
+ if ((p_idx % 8) == 7)
+ ret |= (1 << (p_idx - 7));
else
- ret|=(1<<(p_idx+1));
+ ret |= (1 << (p_idx + 1));
- int mask = ret|(1<<p_idx);
- if (p_idx<8)
- ret|=24;
+ int mask = ret | (1 << p_idx);
+ if (p_idx < 8)
+ ret |= 24;
else
- ret|=mask>>8;
+ ret |= mask >> 8;
- if (p_idx>=16)
- ret|=25;
+ if (p_idx >= 16)
+ ret |= 25;
else
- ret|=mask<<8;
+ ret |= mask << 8;
return ret;
}
-
}
-
- static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B)
- {
+ static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
}
// Returns a list of points on the convex hull in counter-clockwise order.
// Note: the last point in the returned list is the same as the first one.
- static Vector<Point2> convex_hull_2d(Vector<Point2> P)
- {
+ static Vector<Point2> convex_hull_2d(Vector<Point2> P) {
int n = P.size(), k = 0;
Vector<Point2> H;
- H.resize(2*n);
+ H.resize(2 * n);
// Sort points lexicographically
P.sort();
-
// Build lower hull
for (int i = 0; i < n; ++i) {
- while (k >= 2 && vec2_cross(H[k-2], H[k-1], P[i]) <= 0) k--;
+ while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
+ k--;
H[k++] = P[i];
}
// Build upper hull
- for (int i = n-2, t = k+1; i >= 0; i--) {
- while (k >= t && vec2_cross(H[k-2], H[k-1], P[i]) <= 0) k--;
+ for (int i = n - 2, t = k + 1; i >= 0; i--) {
+ while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
+ k--;
H[k++] = P[i];
}
@@ -946,16 +912,12 @@ public:
}
static MeshData build_convex_mesh(const PoolVector<Plane> &p_planes);
- static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis=Vector3::AXIS_Z);
- static PoolVector<Plane> build_box_planes(const Vector3& p_extents);
- static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis=Vector3::AXIS_Z);
- static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis=Vector3::AXIS_Z);
-
- static void make_atlas(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size);
-
+ static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ static PoolVector<Plane> build_box_planes(const Vector3 &p_extents);
+ static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
+ static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
};
-
-
#endif
diff --git a/core/math/math_2d.cpp b/core/math/math_2d.cpp
index 76eeece688..021b1fbf55 100644
--- a/core/math/math_2d.cpp
+++ b/core/math/math_2d.cpp
@@ -28,91 +28,91 @@
/*************************************************************************/
#include "math_2d.h"
-
real_t Vector2::angle() const {
- return Math::atan2(y,x);
+ return Math::atan2(y, x);
}
real_t Vector2::length() const {
- return Math::sqrt( x*x + y*y );
+ return Math::sqrt(x * x + y * y);
}
real_t Vector2::length_squared() const {
- return x*x + y*y;
+ return x * x + y * y;
}
void Vector2::normalize() {
- real_t l = x*x + y*y;
- if (l!=0) {
+ real_t l = x * x + y * y;
+ if (l != 0) {
- l=Math::sqrt(l);
- x/=l;
- y/=l;
+ l = Math::sqrt(l);
+ x /= l;
+ y /= l;
}
}
Vector2 Vector2::normalized() const {
- Vector2 v=*this;
+ Vector2 v = *this;
v.normalize();
return v;
}
-real_t Vector2::distance_to(const Vector2& p_vector2) const {
+real_t Vector2::distance_to(const Vector2 &p_vector2) const {
- return Math::sqrt( (x-p_vector2.x)*(x-p_vector2.x) + (y-p_vector2.y)*(y-p_vector2.y));
+ return Math::sqrt((x - p_vector2.x) * (x - p_vector2.x) + (y - p_vector2.y) * (y - p_vector2.y));
}
-real_t Vector2::distance_squared_to(const Vector2& p_vector2) const {
+real_t Vector2::distance_squared_to(const Vector2 &p_vector2) const {
- return (x-p_vector2.x)*(x-p_vector2.x) + (y-p_vector2.y)*(y-p_vector2.y);
+ return (x - p_vector2.x) * (x - p_vector2.x) + (y - p_vector2.y) * (y - p_vector2.y);
}
-real_t Vector2::angle_to(const Vector2& p_vector2) const {
+real_t Vector2::angle_to(const Vector2 &p_vector2) const {
- return Math::atan2( cross(p_vector2), dot(p_vector2) );
+ return Math::atan2(cross(p_vector2), dot(p_vector2));
}
-real_t Vector2::angle_to_point(const Vector2& p_vector2) const {
+real_t Vector2::angle_to_point(const Vector2 &p_vector2) const {
- return Math::atan2( y - p_vector2.y, x-p_vector2.x );
+ return Math::atan2(y - p_vector2.y, x - p_vector2.x);
}
-real_t Vector2::dot(const Vector2& p_other) const {
+real_t Vector2::dot(const Vector2 &p_other) const {
- return x*p_other.x + y*p_other.y;
+ return x * p_other.x + y * p_other.y;
}
-real_t Vector2::cross(const Vector2& p_other) const {
+real_t Vector2::cross(const Vector2 &p_other) const {
- return x*p_other.y - y*p_other.x;
+ return x * p_other.y - y * p_other.x;
}
Vector2 Vector2::cross(real_t p_other) const {
- return Vector2(p_other*y,-p_other*x);
+ return Vector2(p_other * y, -p_other * x);
}
+Vector2 Vector2::operator+(const Vector2 &p_v) const {
-Vector2 Vector2::operator+(const Vector2& p_v) const {
-
- return Vector2(x+p_v.x,y+p_v.y);
+ return Vector2(x + p_v.x, y + p_v.y);
}
-void Vector2::operator+=(const Vector2& p_v) {
+void Vector2::operator+=(const Vector2 &p_v) {
- x+=p_v.x; y+=p_v.y;
+ x += p_v.x;
+ y += p_v.y;
}
-Vector2 Vector2::operator-(const Vector2& p_v) const {
+Vector2 Vector2::operator-(const Vector2 &p_v) const {
- return Vector2(x-p_v.x,y-p_v.y);
+ return Vector2(x - p_v.x, y - p_v.y);
}
-void Vector2::operator-=(const Vector2& p_v) {
+void Vector2::operator-=(const Vector2 &p_v) {
- x-=p_v.x; y-=p_v.y;
+ x -= p_v.x;
+ y -= p_v.y;
}
Vector2 Vector2::operator*(const Vector2 &p_v1) const {
@@ -126,7 +126,8 @@ Vector2 Vector2::operator*(const real_t &rvalue) const {
};
void Vector2::operator*=(const real_t &rvalue) {
- x *= rvalue; y *= rvalue;
+ x *= rvalue;
+ y *= rvalue;
};
Vector2 Vector2::operator/(const Vector2 &p_v1) const {
@@ -141,64 +142,64 @@ Vector2 Vector2::operator/(const real_t &rvalue) const {
void Vector2::operator/=(const real_t &rvalue) {
- x /= rvalue; y /= rvalue;
+ x /= rvalue;
+ y /= rvalue;
};
Vector2 Vector2::operator-() const {
- return Vector2(-x,-y);
+ return Vector2(-x, -y);
}
-bool Vector2::operator==(const Vector2& p_vec2) const {
+bool Vector2::operator==(const Vector2 &p_vec2) const {
- return x==p_vec2.x && y==p_vec2.y;
+ return x == p_vec2.x && y == p_vec2.y;
}
-bool Vector2::operator!=(const Vector2& p_vec2) const {
+bool Vector2::operator!=(const Vector2 &p_vec2) const {
- return x!=p_vec2.x || y!=p_vec2.y;
+ return x != p_vec2.x || y != p_vec2.y;
}
Vector2 Vector2::floor() const {
- return Vector2( Math::floor(x), Math::floor(y) );
+ return Vector2(Math::floor(x), Math::floor(y));
}
Vector2 Vector2::rotated(real_t p_by) const {
Vector2 v;
- v.set_rotation(angle()+p_by);
- v*=length();
+ v.set_rotation(angle() + p_by);
+ v *= length();
return v;
}
-Vector2 Vector2::project(const Vector2& p_vec) const {
+Vector2 Vector2::project(const Vector2 &p_vec) const {
- Vector2 v1=p_vec;
- Vector2 v2=*this;
- return v2 * ( v1.dot(v2) / v2.dot(v2));
+ Vector2 v1 = p_vec;
+ Vector2 v2 = *this;
+ return v2 * (v1.dot(v2) / v2.dot(v2));
}
-Vector2 Vector2::snapped(const Vector2& p_by) const {
+Vector2 Vector2::snapped(const Vector2 &p_by) const {
return Vector2(
- Math::stepify(x,p_by.x),
- Math::stepify(y,p_by.y)
- );
+ Math::stepify(x, p_by.x),
+ Math::stepify(y, p_by.y));
}
Vector2 Vector2::clamped(real_t p_len) const {
real_t l = length();
Vector2 v = *this;
- if (l>0 && p_len<l) {
+ if (l > 0 && p_len < l) {
- v/=l;
- v*=p_len;
+ v /= l;
+ v *= p_len;
}
return v;
}
-Vector2 Vector2::cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const {
+Vector2 Vector2::cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const {
#if 0
k[0] = ((*this) (vi[0] + 1, vi[1], vi[2])) - ((*this) (vi[0],
vi[1],vi[2])); //fk = a0
@@ -225,27 +226,25 @@ Vector2 Vector2::cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_
return Vector2();
}
-Vector2 Vector2::cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const {
-
-
+Vector2 Vector2::cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const {
- Vector2 p0=p_pre_a;
- Vector2 p1=*this;
- Vector2 p2=p_b;
- Vector2 p3=p_post_b;
+ Vector2 p0 = p_pre_a;
+ Vector2 p1 = *this;
+ Vector2 p2 = p_b;
+ Vector2 p3 = p_post_b;
real_t t = p_t;
real_t t2 = t * t;
real_t t3 = t2 * t;
Vector2 out;
- out = 0.5 * ( ( p1 * 2.0) +
- ( -p0 + p2 ) * t +
- ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 +
- ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 );
+ out = 0.5 * ((p1 * 2.0) +
+ (-p0 + p2) * t +
+ (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 +
+ (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
return out;
-/*
+ /*
real_t mu = p_t;
real_t mu2 = mu*mu;
@@ -273,57 +272,54 @@ Vector2 Vector2::cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, co
(a * p_a.y) + (b *p_b.y) + (c * p_pre_a.y) + (d * p_post_b.y)
);
*/
-
}
-Vector2 Vector2::slide(const Vector2& p_vec) const {
+Vector2 Vector2::slide(const Vector2 &p_vec) const {
return p_vec - *this * this->dot(p_vec);
}
-Vector2 Vector2::reflect(const Vector2& p_vec) const {
+Vector2 Vector2::reflect(const Vector2 &p_vec) const {
return p_vec - *this * this->dot(p_vec) * 2.0;
-
}
+bool Rect2::intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos, Point2 *r_normal) const {
-bool Rect2::intersects_segment(const Point2& p_from, const Point2& p_to, Point2* r_pos,Point2* r_normal) const {
+ real_t min = 0, max = 1;
+ int axis = 0;
+ real_t sign = 0;
- real_t min=0,max=1;
- int axis=0;
- real_t sign=0;
-
- for(int i=0;i<2;i++) {
- real_t seg_from=p_from[i];
- real_t seg_to=p_to[i];
- real_t box_begin=pos[i];
- real_t box_end=box_begin+size[i];
- real_t cmin,cmax;
+ for (int i = 0; i < 2; i++) {
+ real_t seg_from = p_from[i];
+ real_t seg_to = p_to[i];
+ real_t box_begin = pos[i];
+ real_t box_end = box_begin + size[i];
+ real_t cmin, cmax;
real_t csign;
if (seg_from < seg_to) {
if (seg_from > box_end || seg_to < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0;
- cmax = (seg_to > box_end)?((box_end - seg_from)/length):1;
- csign=-1.0;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
+ cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
+ csign = -1.0;
} else {
if (seg_to > box_end || seg_from < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from > box_end)?(box_end - seg_from)/length:0;
- cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1;
- csign=1.0;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
+ cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
+ csign = 1.0;
}
if (cmin > min) {
min = cmin;
- axis=i;
- sign=csign;
+ axis = i;
+ sign = csign;
}
if (cmax < max)
max = cmax;
@@ -331,38 +327,39 @@ bool Rect2::intersects_segment(const Point2& p_from, const Point2& p_to, Point2*
return false;
}
-
- Vector2 rel=p_to-p_from;
+ Vector2 rel = p_to - p_from;
if (r_normal) {
Vector2 normal;
- normal[axis]=sign;
- *r_normal=normal;
+ normal[axis] = sign;
+ *r_normal = normal;
}
if (r_pos)
- *r_pos=p_from+rel*min;
+ *r_pos = p_from + rel * min;
return true;
}
/* Point2i */
-Point2i Point2i::operator+(const Point2i& p_v) const {
+Point2i Point2i::operator+(const Point2i &p_v) const {
- return Point2i(x+p_v.x,y+p_v.y);
+ return Point2i(x + p_v.x, y + p_v.y);
}
-void Point2i::operator+=(const Point2i& p_v) {
+void Point2i::operator+=(const Point2i &p_v) {
- x+=p_v.x; y+=p_v.y;
+ x += p_v.x;
+ y += p_v.y;
}
-Point2i Point2i::operator-(const Point2i& p_v) const {
+Point2i Point2i::operator-(const Point2i &p_v) const {
- return Point2i(x-p_v.x,y-p_v.y);
+ return Point2i(x - p_v.x, y - p_v.y);
}
-void Point2i::operator-=(const Point2i& p_v) {
+void Point2i::operator-=(const Point2i &p_v) {
- x-=p_v.x; y-=p_v.y;
+ x -= p_v.x;
+ y -= p_v.y;
}
Point2i Point2i::operator*(const Point2i &p_v1) const {
@@ -376,7 +373,8 @@ Point2i Point2i::operator*(const int &rvalue) const {
};
void Point2i::operator*=(const int &rvalue) {
- x *= rvalue; y *= rvalue;
+ x *= rvalue;
+ y *= rvalue;
};
Point2i Point2i::operator/(const Point2i &p_v1) const {
@@ -391,225 +389,215 @@ Point2i Point2i::operator/(const int &rvalue) const {
void Point2i::operator/=(const int &rvalue) {
- x /= rvalue; y /= rvalue;
+ x /= rvalue;
+ y /= rvalue;
};
Point2i Point2i::operator-() const {
- return Point2i(-x,-y);
+ return Point2i(-x, -y);
}
-bool Point2i::operator==(const Point2i& p_vec2) const {
+bool Point2i::operator==(const Point2i &p_vec2) const {
- return x==p_vec2.x && y==p_vec2.y;
+ return x == p_vec2.x && y == p_vec2.y;
}
-bool Point2i::operator!=(const Point2i& p_vec2) const {
+bool Point2i::operator!=(const Point2i &p_vec2) const {
- return x!=p_vec2.x || y!=p_vec2.y;
+ return x != p_vec2.x || y != p_vec2.y;
}
void Transform2D::invert() {
// FIXME: this function assumes the basis is a rotation matrix, with no scaling.
// Transform2D::affine_inverse can handle matrices with scaling, so GDScript should eventually use that.
- SWAP(elements[0][1],elements[1][0]);
+ SWAP(elements[0][1], elements[1][0]);
elements[2] = basis_xform(-elements[2]);
}
Transform2D Transform2D::inverse() const {
- Transform2D inv=*this;
+ Transform2D inv = *this;
inv.invert();
return inv;
-
}
void Transform2D::affine_invert() {
real_t det = basis_determinant();
- ERR_FAIL_COND(det==0);
+ ERR_FAIL_COND(det == 0);
real_t idet = 1.0 / det;
- SWAP( elements[0][0],elements[1][1] );
- elements[0]*=Vector2(idet,-idet);
- elements[1]*=Vector2(-idet,idet);
+ SWAP(elements[0][0], elements[1][1]);
+ elements[0] *= Vector2(idet, -idet);
+ elements[1] *= Vector2(-idet, idet);
elements[2] = basis_xform(-elements[2]);
-
}
Transform2D Transform2D::affine_inverse() const {
- Transform2D inv=*this;
+ Transform2D inv = *this;
inv.affine_invert();
return inv;
}
void Transform2D::rotate(real_t p_phi) {
- *this = Transform2D(p_phi,Vector2()) * (*this);
+ *this = Transform2D(p_phi, Vector2()) * (*this);
}
real_t Transform2D::get_rotation() const {
real_t det = basis_determinant();
Transform2D m = orthonormalized();
if (det < 0) {
- m.scale_basis(Size2(-1,-1));
+ m.scale_basis(Size2(-1, -1));
}
- return Math::atan2(m[0].y,m[0].x);
+ return Math::atan2(m[0].y, m[0].x);
}
void Transform2D::set_rotation(real_t p_rot) {
real_t cr = Math::cos(p_rot);
real_t sr = Math::sin(p_rot);
- elements[0][0]=cr;
- elements[0][1]=sr;
- elements[1][0]=-sr;
- elements[1][1]=cr;
+ elements[0][0] = cr;
+ elements[0][1] = sr;
+ elements[1][0] = -sr;
+ elements[1][1] = cr;
}
-Transform2D::Transform2D(real_t p_rot, const Vector2& p_pos) {
+Transform2D::Transform2D(real_t p_rot, const Vector2 &p_pos) {
real_t cr = Math::cos(p_rot);
real_t sr = Math::sin(p_rot);
- elements[0][0]=cr;
- elements[0][1]=sr;
- elements[1][0]=-sr;
- elements[1][1]=cr;
- elements[2]=p_pos;
+ elements[0][0] = cr;
+ elements[0][1] = sr;
+ elements[1][0] = -sr;
+ elements[1][1] = cr;
+ elements[2] = p_pos;
}
Size2 Transform2D::get_scale() const {
real_t det_sign = basis_determinant() > 0 ? 1 : -1;
- return det_sign * Size2( elements[0].length(), elements[1].length() );
+ return det_sign * Size2(elements[0].length(), elements[1].length());
}
-void Transform2D::scale(const Size2& p_scale) {
+void Transform2D::scale(const Size2 &p_scale) {
scale_basis(p_scale);
- elements[2]*=p_scale;
+ elements[2] *= p_scale;
}
-void Transform2D::scale_basis(const Size2& p_scale) {
-
- elements[0][0]*=p_scale.x;
- elements[0][1]*=p_scale.y;
- elements[1][0]*=p_scale.x;
- elements[1][1]*=p_scale.y;
+void Transform2D::scale_basis(const Size2 &p_scale) {
+ elements[0][0] *= p_scale.x;
+ elements[0][1] *= p_scale.y;
+ elements[1][0] *= p_scale.x;
+ elements[1][1] *= p_scale.y;
}
-void Transform2D::translate( real_t p_tx, real_t p_ty) {
+void Transform2D::translate(real_t p_tx, real_t p_ty) {
- translate(Vector2(p_tx,p_ty));
+ translate(Vector2(p_tx, p_ty));
}
-void Transform2D::translate( const Vector2& p_translation ) {
+void Transform2D::translate(const Vector2 &p_translation) {
- elements[2]+=basis_xform(p_translation);
+ elements[2] += basis_xform(p_translation);
}
void Transform2D::orthonormalize() {
// Gram-Schmidt Process
- Vector2 x=elements[0];
- Vector2 y=elements[1];
+ Vector2 x = elements[0];
+ Vector2 y = elements[1];
x.normalize();
- y = (y-x*(x.dot(y)));
+ y = (y - x * (x.dot(y)));
y.normalize();
- elements[0]=x;
- elements[1]=y;
+ elements[0] = x;
+ elements[1] = y;
}
Transform2D Transform2D::orthonormalized() const {
- Transform2D on=*this;
+ Transform2D on = *this;
on.orthonormalize();
return on;
-
}
-bool Transform2D::operator==(const Transform2D& p_transform) const {
+bool Transform2D::operator==(const Transform2D &p_transform) const {
- for(int i=0;i<3;i++) {
- if (elements[i]!=p_transform.elements[i])
+ for (int i = 0; i < 3; i++) {
+ if (elements[i] != p_transform.elements[i])
return false;
}
return true;
}
-bool Transform2D::operator!=(const Transform2D& p_transform) const {
+bool Transform2D::operator!=(const Transform2D &p_transform) const {
- for(int i=0;i<3;i++) {
- if (elements[i]!=p_transform.elements[i])
+ for (int i = 0; i < 3; i++) {
+ if (elements[i] != p_transform.elements[i])
return true;
}
return false;
-
}
-void Transform2D::operator*=(const Transform2D& p_transform) {
+void Transform2D::operator*=(const Transform2D &p_transform) {
elements[2] = xform(p_transform.elements[2]);
- real_t x0,x1,y0,y1;
+ real_t x0, x1, y0, y1;
x0 = tdotx(p_transform.elements[0]);
x1 = tdoty(p_transform.elements[0]);
y0 = tdotx(p_transform.elements[1]);
y1 = tdoty(p_transform.elements[1]);
- elements[0][0]=x0;
- elements[0][1]=x1;
- elements[1][0]=y0;
- elements[1][1]=y1;
+ elements[0][0] = x0;
+ elements[0][1] = x1;
+ elements[1][0] = y0;
+ elements[1][1] = y1;
}
-
-Transform2D Transform2D::operator*(const Transform2D& p_transform) const {
+Transform2D Transform2D::operator*(const Transform2D &p_transform) const {
Transform2D t = *this;
- t*=p_transform;
+ t *= p_transform;
return t;
-
}
-Transform2D Transform2D::scaled(const Size2& p_scale) const {
+Transform2D Transform2D::scaled(const Size2 &p_scale) const {
- Transform2D copy=*this;
+ Transform2D copy = *this;
copy.scale(p_scale);
return copy;
-
}
-Transform2D Transform2D::basis_scaled(const Size2& p_scale) const {
+Transform2D Transform2D::basis_scaled(const Size2 &p_scale) const {
- Transform2D copy=*this;
+ Transform2D copy = *this;
copy.scale_basis(p_scale);
return copy;
-
}
Transform2D Transform2D::untranslated() const {
- Transform2D copy=*this;
- copy.elements[2]=Vector2();
+ Transform2D copy = *this;
+ copy.elements[2] = Vector2();
return copy;
}
-Transform2D Transform2D::translated(const Vector2& p_offset) const {
+Transform2D Transform2D::translated(const Vector2 &p_offset) const {
- Transform2D copy=*this;
+ Transform2D copy = *this;
copy.translate(p_offset);
return copy;
-
}
Transform2D Transform2D::rotated(real_t p_phi) const {
- Transform2D copy=*this;
+ Transform2D copy = *this;
copy.rotate(p_phi);
return copy;
-
}
real_t Transform2D::basis_determinant() const {
@@ -617,7 +605,7 @@ real_t Transform2D::basis_determinant() const {
return elements[0].x * elements[1].y - elements[0].y * elements[1].x;
}
-Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t p_c) const {
+Transform2D Transform2D::interpolate_with(const Transform2D &p_transform, real_t p_c) const {
//extract parameters
Vector2 p1 = get_origin();
@@ -642,9 +630,9 @@ Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t
if (dot > 0.9995) {
v = Vector2::linear_interpolate(v1, v2, p_c).normalized(); //linearly interpolate to avoid numerical precision issues
} else {
- real_t angle = p_c*Math::acos(dot);
- Vector2 v3 = (v2 - v1*dot).normalized();
- v = v1*Math::cos(angle) + v3*Math::sin(angle);
+ real_t angle = p_c * Math::acos(dot);
+ Vector2 v3 = (v2 - v1 * dot).normalized();
+ v = v1 * Math::cos(angle) + v3 * Math::sin(angle);
}
//construct matrix
@@ -655,5 +643,5 @@ Transform2D Transform2D::interpolate_with(const Transform2D& p_transform, real_t
Transform2D::operator String() const {
- return String(String()+elements[0]+", "+elements[1]+", "+elements[2]);
+ return String(String() + elements[0] + ", " + elements[1] + ", " + elements[2]);
}
diff --git a/core/math/math_2d.h b/core/math/math_2d.h
index a24c4266ee..af6437d7f1 100644
--- a/core/math/math_2d.h
+++ b/core/math/math_2d.h
@@ -73,12 +73,11 @@ struct Vector2 {
real_t height;
};
-
- _FORCE_INLINE_ real_t& operator[](int p_idx) {
- return p_idx?y:x;
+ _FORCE_INLINE_ real_t &operator[](int p_idx) {
+ return p_idx ? y : x;
}
- _FORCE_INLINE_ const real_t& operator[](int p_idx) const {
- return p_idx?y:x;
+ _FORCE_INLINE_ const real_t &operator[](int p_idx) const {
+ return p_idx ? y : x;
}
void normalize();
@@ -87,32 +86,32 @@ struct Vector2 {
real_t length() const;
real_t length_squared() const;
- real_t distance_to(const Vector2& p_vector2) const;
- real_t distance_squared_to(const Vector2& p_vector2) const;
- real_t angle_to(const Vector2& p_vector2) const;
- real_t angle_to_point(const Vector2& p_vector2) const;
+ real_t distance_to(const Vector2 &p_vector2) const;
+ real_t distance_squared_to(const Vector2 &p_vector2) const;
+ real_t angle_to(const Vector2 &p_vector2) const;
+ real_t angle_to_point(const Vector2 &p_vector2) const;
- real_t dot(const Vector2& p_other) const;
- real_t cross(const Vector2& p_other) const;
+ real_t dot(const Vector2 &p_other) const;
+ real_t cross(const Vector2 &p_other) const;
Vector2 cross(real_t p_other) const;
- Vector2 project(const Vector2& p_vec) const;
+ Vector2 project(const Vector2 &p_vec) const;
- Vector2 plane_project(real_t p_d, const Vector2& p_vec) const;
+ Vector2 plane_project(real_t p_d, const Vector2 &p_vec) const;
Vector2 clamped(real_t p_len) const;
- _FORCE_INLINE_ static Vector2 linear_interpolate(const Vector2& p_a, const Vector2& p_b,real_t p_t);
- _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2& p_b,real_t p_t) const;
- Vector2 cubic_interpolate(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const;
- Vector2 cubic_interpolate_soft(const Vector2& p_b,const Vector2& p_pre_a, const Vector2& p_post_b,real_t p_t) const;
+ _FORCE_INLINE_ static Vector2 linear_interpolate(const Vector2 &p_a, const Vector2 &p_b, real_t p_t);
+ _FORCE_INLINE_ Vector2 linear_interpolate(const Vector2 &p_b, real_t p_t) const;
+ Vector2 cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const;
+ Vector2 cubic_interpolate_soft(const Vector2 &p_b, const Vector2 &p_pre_a, const Vector2 &p_post_b, real_t p_t) const;
- Vector2 slide(const Vector2& p_vec) const;
- Vector2 reflect(const Vector2& p_vec) const;
+ Vector2 slide(const Vector2 &p_vec) const;
+ Vector2 reflect(const Vector2 &p_vec) const;
- Vector2 operator+(const Vector2& p_v) const;
- void operator+=(const Vector2& p_v);
- Vector2 operator-(const Vector2& p_v) const;
- void operator-=(const Vector2& p_v);
+ Vector2 operator+(const Vector2 &p_v) const;
+ void operator+=(const Vector2 &p_v);
+ Vector2 operator-(const Vector2 &p_v) const;
+ void operator-=(const Vector2 &p_v);
Vector2 operator*(const Vector2 &p_v1) const;
Vector2 operator*(const real_t &rvalue) const;
@@ -127,70 +126,73 @@ struct Vector2 {
Vector2 operator-() const;
- bool operator==(const Vector2& p_vec2) const;
- bool operator!=(const Vector2& p_vec2) const;
+ bool operator==(const Vector2 &p_vec2) const;
+ bool operator!=(const Vector2 &p_vec2) const;
- bool operator<(const Vector2& p_vec2) const { return (x==p_vec2.x)?(y<p_vec2.y):(x<p_vec2.x); }
- bool operator<=(const Vector2& p_vec2) const { return (x==p_vec2.x)?(y<=p_vec2.y):(x<=p_vec2.x); }
+ bool operator<(const Vector2 &p_vec2) const { return (x == p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); }
+ bool operator<=(const Vector2 &p_vec2) const { return (x == p_vec2.x) ? (y <= p_vec2.y) : (x <= p_vec2.x); }
real_t angle() const;
void set_rotation(real_t p_radians) {
- x=Math::cos(p_radians);
- y=Math::sin(p_radians);
+ x = Math::cos(p_radians);
+ y = Math::sin(p_radians);
}
_FORCE_INLINE_ Vector2 abs() const {
- return Vector2( Math::abs(x), Math::abs(y) );
+ return Vector2(Math::abs(x), Math::abs(y));
}
Vector2 rotated(real_t p_by) const;
Vector2 tangent() const {
- return Vector2(y,-x);
+ return Vector2(y, -x);
}
Vector2 floor() const;
- Vector2 snapped(const Vector2& p_by) const;
- real_t aspect() const { return width/height; }
-
+ Vector2 snapped(const Vector2 &p_by) const;
+ real_t aspect() const { return width / height; }
- operator String() const { return String::num(x)+", "+String::num(y); }
+ operator String() const { return String::num(x) + ", " + String::num(y); }
- _FORCE_INLINE_ Vector2(real_t p_x,real_t p_y) { x=p_x; y=p_y; }
- _FORCE_INLINE_ Vector2() { x=0; y=0; }
+ _FORCE_INLINE_ Vector2(real_t p_x, real_t p_y) {
+ x = p_x;
+ y = p_y;
+ }
+ _FORCE_INLINE_ Vector2() {
+ x = 0;
+ y = 0;
+ }
};
-_FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2& p_vec) const {
+_FORCE_INLINE_ Vector2 Vector2::plane_project(real_t p_d, const Vector2 &p_vec) const {
- return p_vec - *this * ( dot(p_vec) -p_d);
+ return p_vec - *this * (dot(p_vec) - p_d);
}
+_FORCE_INLINE_ Vector2 operator*(real_t p_scalar, const Vector2 &p_vec) {
-_FORCE_INLINE_ Vector2 operator*(real_t p_scalar, const Vector2& p_vec) {
-
- return p_vec*p_scalar;
+ return p_vec * p_scalar;
}
-Vector2 Vector2::linear_interpolate(const Vector2& p_b,real_t p_t) const {
+Vector2 Vector2::linear_interpolate(const Vector2 &p_b, real_t p_t) const {
- Vector2 res=*this;
+ Vector2 res = *this;
- res.x+= (p_t * (p_b.x-x));
- res.y+= (p_t * (p_b.y-y));
+ res.x += (p_t * (p_b.x - x));
+ res.y += (p_t * (p_b.y - y));
return res;
-
}
-Vector2 Vector2::linear_interpolate(const Vector2& p_a, const Vector2& p_b,real_t p_t) {
+Vector2 Vector2::linear_interpolate(const Vector2 &p_a, const Vector2 &p_b, real_t p_t) {
- Vector2 res=p_a;
+ Vector2 res = p_a;
- res.x+= (p_t * (p_b.x-p_a.x));
- res.y+= (p_t * (p_b.y-p_a.y));
+ res.x += (p_t * (p_b.x - p_a.x));
+ res.y += (p_t * (p_b.y - p_a.y));
return res;
}
@@ -200,170 +202,170 @@ typedef Vector2 Point2;
struct Transform2D;
-
struct Rect2 {
Point2 pos;
Size2 size;
- const Vector2& get_pos() const { return pos; }
- void set_pos(const Vector2& p_pos) { pos=p_pos; }
- const Vector2& get_size() const { return size; }
- void set_size(const Vector2& p_size) { size=p_size; }
+ const Vector2 &get_pos() const { return pos; }
+ void set_pos(const Vector2 &p_pos) { pos = p_pos; }
+ const Vector2 &get_size() const { return size; }
+ void set_size(const Vector2 &p_size) { size = p_size; }
- real_t get_area() const { return size.width*size.height; }
+ real_t get_area() const { return size.width * size.height; }
- inline bool intersects(const Rect2& p_rect) const {
- if ( pos.x >= (p_rect.pos.x + p_rect.size.width) )
+ inline bool intersects(const Rect2 &p_rect) const {
+ if (pos.x >= (p_rect.pos.x + p_rect.size.width))
return false;
- if ( (pos.x+size.width) <= p_rect.pos.x )
+ if ((pos.x + size.width) <= p_rect.pos.x)
return false;
- if ( pos.y >= (p_rect.pos.y + p_rect.size.height) )
+ if (pos.y >= (p_rect.pos.y + p_rect.size.height))
return false;
- if ( (pos.y+size.height) <= p_rect.pos.y )
+ if ((pos.y + size.height) <= p_rect.pos.y)
return false;
return true;
}
- inline real_t distance_to(const Vector2& p_point) const {
+ inline real_t distance_to(const Vector2 &p_point) const {
real_t dist = 1e20;
if (p_point.x < pos.x) {
- dist=MIN(dist,pos.x-p_point.x);
+ dist = MIN(dist, pos.x - p_point.x);
}
if (p_point.y < pos.y) {
- dist=MIN(dist,pos.y-p_point.y);
+ dist = MIN(dist, pos.y - p_point.y);
}
- if (p_point.x >= (pos.x+size.x) ) {
- dist=MIN(p_point.x-(pos.x+size.x),dist);
+ if (p_point.x >= (pos.x + size.x)) {
+ dist = MIN(p_point.x - (pos.x + size.x), dist);
}
- if (p_point.y >= (pos.y+size.y) ) {
- dist=MIN(p_point.y-(pos.y+size.y),dist);
+ if (p_point.y >= (pos.y + size.y)) {
+ dist = MIN(p_point.y - (pos.y + size.y), dist);
}
- if (dist==1e20)
+ if (dist == 1e20)
return 0;
else
return dist;
}
- _FORCE_INLINE_ bool intersects_transformed(const Transform2D& p_xform, const Rect2& p_rect) const;
-
- bool intersects_segment(const Point2& p_from, const Point2& p_to, Point2* r_pos=NULL, Point2* r_normal=NULL) const;
+ _FORCE_INLINE_ bool intersects_transformed(const Transform2D &p_xform, const Rect2 &p_rect) const;
- inline bool encloses(const Rect2& p_rect) const {
+ bool intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos = NULL, Point2 *r_normal = NULL) const;
- return (p_rect.pos.x>=pos.x) && (p_rect.pos.y>=pos.y) &&
- ((p_rect.pos.x+p_rect.size.x)<(pos.x+size.x)) &&
- ((p_rect.pos.y+p_rect.size.y)<(pos.y+size.y));
+ inline bool encloses(const Rect2 &p_rect) const {
+ return (p_rect.pos.x >= pos.x) && (p_rect.pos.y >= pos.y) &&
+ ((p_rect.pos.x + p_rect.size.x) < (pos.x + size.x)) &&
+ ((p_rect.pos.y + p_rect.size.y) < (pos.y + size.y));
}
inline bool has_no_area() const {
- return (size.x<=0 || size.y<=0);
-
+ return (size.x <= 0 || size.y <= 0);
}
- inline Rect2 clip(const Rect2& p_rect) const { /// return a clipped rect
+ inline Rect2 clip(const Rect2 &p_rect) const { /// return a clipped rect
- Rect2 new_rect=p_rect;
+ Rect2 new_rect = p_rect;
- if (!intersects( new_rect ))
+ if (!intersects(new_rect))
return Rect2();
- new_rect.pos.x = MAX( p_rect.pos.x , pos.x );
- new_rect.pos.y = MAX( p_rect.pos.y , pos.y );
+ new_rect.pos.x = MAX(p_rect.pos.x, pos.x);
+ new_rect.pos.y = MAX(p_rect.pos.y, pos.y);
- Point2 p_rect_end=p_rect.pos+p_rect.size;
- Point2 end=pos+size;
+ Point2 p_rect_end = p_rect.pos + p_rect.size;
+ Point2 end = pos + size;
- new_rect.size.x=MIN(p_rect_end.x,end.x) - new_rect.pos.x;
- new_rect.size.y=MIN(p_rect_end.y,end.y) - new_rect.pos.y;
+ new_rect.size.x = MIN(p_rect_end.x, end.x) - new_rect.pos.x;
+ new_rect.size.y = MIN(p_rect_end.y, end.y) - new_rect.pos.y;
return new_rect;
}
- inline Rect2 merge(const Rect2& p_rect) const { ///< return a merged rect
+ inline Rect2 merge(const Rect2 &p_rect) const { ///< return a merged rect
Rect2 new_rect;
- new_rect.pos.x=MIN( p_rect.pos.x , pos.x );
- new_rect.pos.y=MIN( p_rect.pos.y , pos.y );
-
+ new_rect.pos.x = MIN(p_rect.pos.x, pos.x);
+ new_rect.pos.y = MIN(p_rect.pos.y, pos.y);
- new_rect.size.x = MAX( p_rect.pos.x+p_rect.size.x , pos.x+size.x );
- new_rect.size.y = MAX( p_rect.pos.y+p_rect.size.y , pos.y+size.y );
+ new_rect.size.x = MAX(p_rect.pos.x + p_rect.size.x, pos.x + size.x);
+ new_rect.size.y = MAX(p_rect.pos.y + p_rect.size.y, pos.y + size.y);
new_rect.size = new_rect.size - new_rect.pos; //make relative again
return new_rect;
};
- inline bool has_point(const Point2& p_point) const {
+ inline bool has_point(const Point2 &p_point) const {
if (p_point.x < pos.x)
return false;
if (p_point.y < pos.y)
return false;
- if (p_point.x >= (pos.x+size.x) )
+ if (p_point.x >= (pos.x + size.x))
return false;
- if (p_point.y >= (pos.y+size.y) )
+ if (p_point.y >= (pos.y + size.y))
return false;
return true;
}
- inline bool no_area() const { return (size.width<=0 || size.height<=0 ); }
+ inline bool no_area() const { return (size.width <= 0 || size.height <= 0); }
- bool operator==(const Rect2& p_rect) const { return pos==p_rect.pos && size==p_rect.size; }
- bool operator!=(const Rect2& p_rect) const { return pos!=p_rect.pos || size!=p_rect.size; }
+ bool operator==(const Rect2 &p_rect) const { return pos == p_rect.pos && size == p_rect.size; }
+ bool operator!=(const Rect2 &p_rect) const { return pos != p_rect.pos || size != p_rect.size; }
inline Rect2 grow(real_t p_by) const {
- Rect2 g=*this;
- g.pos.x-=p_by;
- g.pos.y-=p_by;
- g.size.width+=p_by*2;
- g.size.height+=p_by*2;
+ Rect2 g = *this;
+ g.pos.x -= p_by;
+ g.pos.y -= p_by;
+ g.size.width += p_by * 2;
+ g.size.height += p_by * 2;
return g;
}
- inline Rect2 expand(const Vector2& p_vector) const {
+ inline Rect2 expand(const Vector2 &p_vector) const {
Rect2 r = *this;
r.expand_to(p_vector);
return r;
}
- inline void expand_to(const Vector2& p_vector) { //in place function for speed
+ inline void expand_to(const Vector2 &p_vector) { //in place function for speed
- Vector2 begin=pos;
- Vector2 end=pos+size;
+ Vector2 begin = pos;
+ Vector2 end = pos + size;
- if (p_vector.x<begin.x)
- begin.x=p_vector.x;
- if (p_vector.y<begin.y)
- begin.y=p_vector.y;
+ if (p_vector.x < begin.x)
+ begin.x = p_vector.x;
+ if (p_vector.y < begin.y)
+ begin.y = p_vector.y;
- if (p_vector.x>end.x)
- end.x=p_vector.x;
- if (p_vector.y>end.y)
- end.y=p_vector.y;
+ if (p_vector.x > end.x)
+ end.x = p_vector.x;
+ if (p_vector.y > end.y)
+ end.y = p_vector.y;
- pos=begin;
- size=end-begin;
+ pos = begin;
+ size = end - begin;
}
-
- operator String() const { return String(pos)+", "+String(size); }
+ operator String() const { return String(pos) + ", " + String(size); }
Rect2() {}
- Rect2( real_t p_x, real_t p_y, real_t p_width, real_t p_height) { pos=Point2(p_x,p_y); size=Size2( p_width, p_height ); }
- Rect2( const Point2& p_pos, const Size2& p_size ) { pos=p_pos; size=p_size; }
+ Rect2(real_t p_x, real_t p_y, real_t p_width, real_t p_height) {
+ pos = Point2(p_x, p_y);
+ size = Size2(p_width, p_height);
+ }
+ Rect2(const Point2 &p_pos, const Size2 &p_size) {
+ pos = p_pos;
+ size = p_size;
+ }
};
-
/* INTEGER STUFF */
struct Point2i {
@@ -377,18 +379,17 @@ struct Point2i {
int height;
};
-
- _FORCE_INLINE_ int& operator[](int p_idx) {
- return p_idx?y:x;
+ _FORCE_INLINE_ int &operator[](int p_idx) {
+ return p_idx ? y : x;
}
- _FORCE_INLINE_ const int& operator[](int p_idx) const {
- return p_idx?y:x;
+ _FORCE_INLINE_ const int &operator[](int p_idx) const {
+ return p_idx ? y : x;
}
- Point2i operator+(const Point2i& p_v) const;
- void operator+=(const Point2i& p_v);
- Point2i operator-(const Point2i& p_v) const;
- void operator-=(const Point2i& p_v);
+ Point2i operator+(const Point2i &p_v) const;
+ void operator+=(const Point2i &p_v);
+ Point2i operator-(const Point2i &p_v) const;
+ void operator-=(const Point2i &p_v);
Point2i operator*(const Point2i &p_v1) const;
Point2i operator*(const int &rvalue) const;
@@ -401,20 +402,29 @@ struct Point2i {
void operator/=(const int &rvalue);
Point2i operator-() const;
- bool operator<(const Point2i& p_vec2) const { return (x==p_vec2.x)?(y<p_vec2.y):(x<p_vec2.x); }
- bool operator>(const Point2i& p_vec2) const { return (x==p_vec2.x)?(y>p_vec2.y):(x>p_vec2.x); }
+ bool operator<(const Point2i &p_vec2) const { return (x == p_vec2.x) ? (y < p_vec2.y) : (x < p_vec2.x); }
+ bool operator>(const Point2i &p_vec2) const { return (x == p_vec2.x) ? (y > p_vec2.y) : (x > p_vec2.x); }
- bool operator==(const Point2i& p_vec2) const;
- bool operator!=(const Point2i& p_vec2) const;
+ bool operator==(const Point2i &p_vec2) const;
+ bool operator!=(const Point2i &p_vec2) const;
- real_t get_aspect() const { return width/(real_t)height; }
+ real_t get_aspect() const { return width / (real_t)height; }
- operator String() const { return String::num(x)+", "+String::num(y); }
+ operator String() const { return String::num(x) + ", " + String::num(y); }
- operator Vector2() const { return Vector2(x,y); }
- inline Point2i(const Vector2& p_vec2) { x=(int)p_vec2.x; y=(int)p_vec2.y; }
- inline Point2i(int p_x,int p_y) { x=p_x; y=p_y; }
- inline Point2i() { x=0; y=0; }
+ operator Vector2() const { return Vector2(x, y); }
+ inline Point2i(const Vector2 &p_vec2) {
+ x = (int)p_vec2.x;
+ y = (int)p_vec2.y;
+ }
+ inline Point2i(int p_x, int p_y) {
+ x = p_x;
+ y = p_y;
+ }
+ inline Point2i() {
+ x = 0;
+ y = 0;
+ }
};
typedef Point2i Size2i;
@@ -424,133 +434,136 @@ struct Rect2i {
Point2i pos;
Size2i size;
- const Point2i& get_pos() const { return pos; }
- void set_pos(const Point2i& p_pos) { pos=p_pos; }
- const Point2i& get_size() const { return size; }
- void set_size(const Point2i& p_size) { size=p_size; }
+ const Point2i &get_pos() const { return pos; }
+ void set_pos(const Point2i &p_pos) { pos = p_pos; }
+ const Point2i &get_size() const { return size; }
+ void set_size(const Point2i &p_size) { size = p_size; }
- int get_area() const { return size.width*size.height; }
+ int get_area() const { return size.width * size.height; }
- inline bool intersects(const Rect2i& p_rect) const {
- if ( pos.x > (p_rect.pos.x + p_rect.size.width) )
+ inline bool intersects(const Rect2i &p_rect) const {
+ if (pos.x > (p_rect.pos.x + p_rect.size.width))
return false;
- if ( (pos.x+size.width) < p_rect.pos.x )
+ if ((pos.x + size.width) < p_rect.pos.x)
return false;
- if ( pos.y > (p_rect.pos.y + p_rect.size.height) )
+ if (pos.y > (p_rect.pos.y + p_rect.size.height))
return false;
- if ( (pos.y+size.height) < p_rect.pos.y )
+ if ((pos.y + size.height) < p_rect.pos.y)
return false;
return true;
}
- inline bool encloses(const Rect2i& p_rect) const {
-
- return (p_rect.pos.x>=pos.x) && (p_rect.pos.y>=pos.y) &&
- ((p_rect.pos.x+p_rect.size.x)<(pos.x+size.x)) &&
- ((p_rect.pos.y+p_rect.size.y)<(pos.y+size.y));
+ inline bool encloses(const Rect2i &p_rect) const {
+ return (p_rect.pos.x >= pos.x) && (p_rect.pos.y >= pos.y) &&
+ ((p_rect.pos.x + p_rect.size.x) < (pos.x + size.x)) &&
+ ((p_rect.pos.y + p_rect.size.y) < (pos.y + size.y));
}
inline bool has_no_area() const {
- return (size.x<=0 || size.y<=0);
-
+ return (size.x <= 0 || size.y <= 0);
}
- inline Rect2i clip(const Rect2i& p_rect) const { /// return a clipped rect
+ inline Rect2i clip(const Rect2i &p_rect) const { /// return a clipped rect
- Rect2i new_rect=p_rect;
+ Rect2i new_rect = p_rect;
- if (!intersects( new_rect ))
+ if (!intersects(new_rect))
return Rect2i();
- new_rect.pos.x = MAX( p_rect.pos.x , pos.x );
- new_rect.pos.y = MAX( p_rect.pos.y , pos.y );
+ new_rect.pos.x = MAX(p_rect.pos.x, pos.x);
+ new_rect.pos.y = MAX(p_rect.pos.y, pos.y);
- Point2 p_rect_end=p_rect.pos+p_rect.size;
- Point2 end=pos+size;
+ Point2 p_rect_end = p_rect.pos + p_rect.size;
+ Point2 end = pos + size;
- new_rect.size.x=(int)(MIN(p_rect_end.x,end.x) - new_rect.pos.x);
- new_rect.size.y=(int)(MIN(p_rect_end.y,end.y) - new_rect.pos.y);
+ new_rect.size.x = (int)(MIN(p_rect_end.x, end.x) - new_rect.pos.x);
+ new_rect.size.y = (int)(MIN(p_rect_end.y, end.y) - new_rect.pos.y);
return new_rect;
}
- inline Rect2i merge(const Rect2i& p_rect) const { ///< return a merged rect
+ inline Rect2i merge(const Rect2i &p_rect) const { ///< return a merged rect
Rect2i new_rect;
- new_rect.pos.x=MIN( p_rect.pos.x , pos.x );
- new_rect.pos.y=MIN( p_rect.pos.y , pos.y );
-
+ new_rect.pos.x = MIN(p_rect.pos.x, pos.x);
+ new_rect.pos.y = MIN(p_rect.pos.y, pos.y);
- new_rect.size.x = MAX( p_rect.pos.x+p_rect.size.x , pos.x+size.x );
- new_rect.size.y = MAX( p_rect.pos.y+p_rect.size.y , pos.y+size.y );
+ new_rect.size.x = MAX(p_rect.pos.x + p_rect.size.x, pos.x + size.x);
+ new_rect.size.y = MAX(p_rect.pos.y + p_rect.size.y, pos.y + size.y);
new_rect.size = new_rect.size - new_rect.pos; //make relative again
return new_rect;
};
- bool has_point(const Point2& p_point) const {
+ bool has_point(const Point2 &p_point) const {
if (p_point.x < pos.x)
return false;
if (p_point.y < pos.y)
return false;
- if (p_point.x >= (pos.x+size.x) )
+ if (p_point.x >= (pos.x + size.x))
return false;
- if (p_point.y >= (pos.y+size.y) )
+ if (p_point.y >= (pos.y + size.y))
return false;
return true;
}
- bool no_area() { return (size.width<=0 || size.height<=0 ); }
+ bool no_area() { return (size.width <= 0 || size.height <= 0); }
- bool operator==(const Rect2i& p_rect) const { return pos==p_rect.pos && size==p_rect.size; }
- bool operator!=(const Rect2i& p_rect) const { return pos!=p_rect.pos || size!=p_rect.size; }
+ bool operator==(const Rect2i &p_rect) const { return pos == p_rect.pos && size == p_rect.size; }
+ bool operator!=(const Rect2i &p_rect) const { return pos != p_rect.pos || size != p_rect.size; }
Rect2i grow(int p_by) const {
- Rect2i g=*this;
- g.pos.x-=p_by;
- g.pos.y-=p_by;
- g.size.width+=p_by*2;
- g.size.height+=p_by*2;
+ Rect2i g = *this;
+ g.pos.x -= p_by;
+ g.pos.y -= p_by;
+ g.size.width += p_by * 2;
+ g.size.height += p_by * 2;
return g;
}
- inline void expand_to(const Point2i& p_vector) {
+ inline void expand_to(const Point2i &p_vector) {
- Point2i begin=pos;
- Point2i end=pos+size;
+ Point2i begin = pos;
+ Point2i end = pos + size;
- if (p_vector.x<begin.x)
- begin.x=p_vector.x;
- if (p_vector.y<begin.y)
- begin.y=p_vector.y;
+ if (p_vector.x < begin.x)
+ begin.x = p_vector.x;
+ if (p_vector.y < begin.y)
+ begin.y = p_vector.y;
- if (p_vector.x>end.x)
- end.x=p_vector.x;
- if (p_vector.y>end.y)
- end.y=p_vector.y;
+ if (p_vector.x > end.x)
+ end.x = p_vector.x;
+ if (p_vector.y > end.y)
+ end.y = p_vector.y;
- pos=begin;
- size=end-begin;
+ pos = begin;
+ size = end - begin;
}
+ operator String() const { return String(pos) + ", " + String(size); }
- operator String() const { return String(pos)+", "+String(size); }
-
- operator Rect2() const { return Rect2(pos,size); }
- Rect2i(const Rect2& p_r2) { pos=p_r2.pos; size=p_r2.size; }
+ operator Rect2() const { return Rect2(pos, size); }
+ Rect2i(const Rect2 &p_r2) {
+ pos = p_r2.pos;
+ size = p_r2.size;
+ }
Rect2i() {}
- Rect2i( int p_x, int p_y, int p_width, int p_height) { pos=Point2(p_x,p_y); size=Size2( p_width, p_height ); }
- Rect2i( const Point2& p_pos, const Size2& p_size ) { pos=p_pos; size=p_size; }
+ Rect2i(int p_x, int p_y, int p_width, int p_height) {
+ pos = Point2(p_x, p_y);
+ size = Size2(p_width, p_height);
+ }
+ Rect2i(const Point2 &p_pos, const Size2 &p_size) {
+ pos = p_pos;
+ size = p_size;
+ }
};
-
-
struct Transform2D {
// Warning #1: basis of Transform2D is stored differently from Basis. In terms of elements array, the basis matrix looks like "on paper":
// M = (elements[0][0] elements[1][0])
@@ -558,21 +571,27 @@ struct Transform2D {
// This is such that the columns, which can be interpreted as basis vectors of the coordinate system "painted" on the object, can be accessed as elements[i].
// Note that this is the opposite of the indices in mathematical texts, meaning: $M_{12}$ in a math book corresponds to elements[1][0] here.
// This requires additional care when working with explicit indices.
- // See https://en.wikipedia.org/wiki/Row-_and_column-major_order for further reading.
+ // See https://en.wikipedia.org/wiki/Row-_and_column-major_order for further reading.
// Warning #2: 2D be aware that unlike 3D code, 2D code uses a left-handed coordinate system: Y-axis points down,
// and angle is measure from +X to +Y in a clockwise-fashion.
Vector2 elements[3];
- _FORCE_INLINE_ real_t tdotx(const Vector2& v) const { return elements[0][0] * v.x + elements[1][0] * v.y; }
- _FORCE_INLINE_ real_t tdoty(const Vector2& v) const { return elements[0][1] * v.x + elements[1][1] * v.y; }
+ _FORCE_INLINE_ real_t tdotx(const Vector2 &v) const { return elements[0][0] * v.x + elements[1][0] * v.y; }
+ _FORCE_INLINE_ real_t tdoty(const Vector2 &v) const { return elements[0][1] * v.x + elements[1][1] * v.y; }
- const Vector2& operator[](int p_idx) const { return elements[p_idx]; }
- Vector2& operator[](int p_idx) { return elements[p_idx]; }
+ const Vector2 &operator[](int p_idx) const { return elements[p_idx]; }
+ Vector2 &operator[](int p_idx) { return elements[p_idx]; }
- _FORCE_INLINE_ Vector2 get_axis(int p_axis) const { ERR_FAIL_INDEX_V(p_axis,3,Vector2()); return elements[p_axis]; }
- _FORCE_INLINE_ void set_axis(int p_axis,const Vector2& p_vec) { ERR_FAIL_INDEX(p_axis,3); elements[p_axis]=p_vec; }
+ _FORCE_INLINE_ Vector2 get_axis(int p_axis) const {
+ ERR_FAIL_INDEX_V(p_axis, 3, Vector2());
+ return elements[p_axis];
+ }
+ _FORCE_INLINE_ void set_axis(int p_axis, const Vector2 &p_vec) {
+ ERR_FAIL_INDEX(p_axis, 3);
+ elements[p_axis] = p_vec;
+ }
void invert();
Transform2D inverse() const;
@@ -582,24 +601,24 @@ struct Transform2D {
void set_rotation(real_t p_phi);
real_t get_rotation() const;
- _FORCE_INLINE_ void set_rotation_and_scale(real_t p_phi,const Size2& p_scale);
+ _FORCE_INLINE_ void set_rotation_and_scale(real_t p_phi, const Size2 &p_scale);
void rotate(real_t p_phi);
- void scale(const Size2& p_scale);
- void scale_basis(const Size2& p_scale);
- void translate( real_t p_tx, real_t p_ty);
- void translate( const Vector2& p_translation );
+ void scale(const Size2 &p_scale);
+ void scale_basis(const Size2 &p_scale);
+ void translate(real_t p_tx, real_t p_ty);
+ void translate(const Vector2 &p_translation);
real_t basis_determinant() const;
Size2 get_scale() const;
- _FORCE_INLINE_ const Vector2& get_origin() const { return elements[2]; }
- _FORCE_INLINE_ void set_origin(const Vector2& p_origin) { elements[2]=p_origin; }
+ _FORCE_INLINE_ const Vector2 &get_origin() const { return elements[2]; }
+ _FORCE_INLINE_ void set_origin(const Vector2 &p_origin) { elements[2] = p_origin; }
- Transform2D scaled(const Size2& p_scale) const;
- Transform2D basis_scaled(const Size2& p_scale) const;
- Transform2D translated(const Vector2& p_offset) const;
+ Transform2D scaled(const Size2 &p_scale) const;
+ Transform2D basis_scaled(const Size2 &p_scale) const;
+ Transform2D translated(const Vector2 &p_offset) const;
Transform2D rotated(real_t p_phi) const;
Transform2D untranslated() const;
@@ -607,20 +626,20 @@ struct Transform2D {
void orthonormalize();
Transform2D orthonormalized() const;
- bool operator==(const Transform2D& p_transform) const;
- bool operator!=(const Transform2D& p_transform) const;
+ bool operator==(const Transform2D &p_transform) const;
+ bool operator!=(const Transform2D &p_transform) const;
- void operator*=(const Transform2D& p_transform);
- Transform2D operator*(const Transform2D& p_transform) const;
+ void operator*=(const Transform2D &p_transform);
+ Transform2D operator*(const Transform2D &p_transform) const;
- Transform2D interpolate_with(const Transform2D& p_transform, real_t p_c) const;
+ Transform2D interpolate_with(const Transform2D &p_transform, real_t p_c) const;
- _FORCE_INLINE_ Vector2 basis_xform(const Vector2& p_vec) const;
- _FORCE_INLINE_ Vector2 basis_xform_inv(const Vector2& p_vec) const;
- _FORCE_INLINE_ Vector2 xform(const Vector2& p_vec) const;
- _FORCE_INLINE_ Vector2 xform_inv(const Vector2& p_vec) const;
- _FORCE_INLINE_ Rect2 xform(const Rect2& p_vec) const;
- _FORCE_INLINE_ Rect2 xform_inv(const Rect2& p_vec) const;
+ _FORCE_INLINE_ Vector2 basis_xform(const Vector2 &p_vec) const;
+ _FORCE_INLINE_ Vector2 basis_xform_inv(const Vector2 &p_vec) const;
+ _FORCE_INLINE_ Vector2 xform(const Vector2 &p_vec) const;
+ _FORCE_INLINE_ Vector2 xform_inv(const Vector2 &p_vec) const;
+ _FORCE_INLINE_ Rect2 xform(const Rect2 &p_vec) const;
+ _FORCE_INLINE_ Rect2 xform_inv(const Rect2 &p_vec) const;
operator String() const;
@@ -634,232 +653,226 @@ struct Transform2D {
elements[2][1] = oy;
}
- Transform2D(real_t p_rot, const Vector2& p_pos);
- Transform2D() { elements[0][0]=1.0; elements[1][1]=1.0; }
+ Transform2D(real_t p_rot, const Vector2 &p_pos);
+ Transform2D() {
+ elements[0][0] = 1.0;
+ elements[1][1] = 1.0;
+ }
};
-bool Rect2::intersects_transformed(const Transform2D& p_xform, const Rect2& p_rect) const {
+bool Rect2::intersects_transformed(const Transform2D &p_xform, const Rect2 &p_rect) const {
//SAT intersection between local and transformed rect2
- Vector2 xf_points[4]={
+ Vector2 xf_points[4] = {
p_xform.xform(p_rect.pos),
- p_xform.xform(Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y)),
- p_xform.xform(Vector2(p_rect.pos.x,p_rect.pos.y+p_rect.size.y)),
- p_xform.xform(Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y+p_rect.size.y)),
+ p_xform.xform(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y)),
+ p_xform.xform(Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.y)),
+ p_xform.xform(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y + p_rect.size.y)),
};
real_t low_limit;
//base rect2 first (faster)
- if (xf_points[0].y>pos.y)
+ if (xf_points[0].y > pos.y)
goto next1;
- if (xf_points[1].y>pos.y)
+ if (xf_points[1].y > pos.y)
goto next1;
- if (xf_points[2].y>pos.y)
+ if (xf_points[2].y > pos.y)
goto next1;
- if (xf_points[3].y>pos.y)
+ if (xf_points[3].y > pos.y)
goto next1;
return false;
- next1:
+next1:
- low_limit=pos.y+size.y;
+ low_limit = pos.y + size.y;
- if (xf_points[0].y<low_limit)
+ if (xf_points[0].y < low_limit)
goto next2;
- if (xf_points[1].y<low_limit)
+ if (xf_points[1].y < low_limit)
goto next2;
- if (xf_points[2].y<low_limit)
+ if (xf_points[2].y < low_limit)
goto next2;
- if (xf_points[3].y<low_limit)
+ if (xf_points[3].y < low_limit)
goto next2;
return false;
- next2:
+next2:
- if (xf_points[0].x>pos.x)
+ if (xf_points[0].x > pos.x)
goto next3;
- if (xf_points[1].x>pos.x)
+ if (xf_points[1].x > pos.x)
goto next3;
- if (xf_points[2].x>pos.x)
+ if (xf_points[2].x > pos.x)
goto next3;
- if (xf_points[3].x>pos.x)
+ if (xf_points[3].x > pos.x)
goto next3;
return false;
- next3:
+next3:
- low_limit=pos.x+size.x;
+ low_limit = pos.x + size.x;
- if (xf_points[0].x<low_limit)
+ if (xf_points[0].x < low_limit)
goto next4;
- if (xf_points[1].x<low_limit)
+ if (xf_points[1].x < low_limit)
goto next4;
- if (xf_points[2].x<low_limit)
+ if (xf_points[2].x < low_limit)
goto next4;
- if (xf_points[3].x<low_limit)
+ if (xf_points[3].x < low_limit)
goto next4;
return false;
- next4:
+next4:
- Vector2 xf_points2[4]={
+ Vector2 xf_points2[4] = {
pos,
- Vector2(pos.x+size.x,pos.y),
- Vector2(pos.x,pos.y+size.y),
- Vector2(pos.x+size.x,pos.y+size.y),
+ Vector2(pos.x + size.x, pos.y),
+ Vector2(pos.x, pos.y + size.y),
+ Vector2(pos.x + size.x, pos.y + size.y),
};
- real_t maxa=p_xform.elements[0].dot(xf_points2[0]);
- real_t mina=maxa;
+ real_t maxa = p_xform.elements[0].dot(xf_points2[0]);
+ real_t mina = maxa;
real_t dp = p_xform.elements[0].dot(xf_points2[1]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
dp = p_xform.elements[0].dot(xf_points2[2]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
dp = p_xform.elements[0].dot(xf_points2[3]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
- real_t maxb=p_xform.elements[0].dot(xf_points[0]);
- real_t minb=maxb;
+ real_t maxb = p_xform.elements[0].dot(xf_points[0]);
+ real_t minb = maxb;
dp = p_xform.elements[0].dot(xf_points[1]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
dp = p_xform.elements[0].dot(xf_points[2]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
dp = p_xform.elements[0].dot(xf_points[3]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
-
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
- if ( mina > maxb )
+ if (mina > maxb)
return false;
- if ( minb > maxa )
+ if (minb > maxa)
return false;
- maxa=p_xform.elements[1].dot(xf_points2[0]);
- mina=maxa;
+ maxa = p_xform.elements[1].dot(xf_points2[0]);
+ mina = maxa;
dp = p_xform.elements[1].dot(xf_points2[1]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
dp = p_xform.elements[1].dot(xf_points2[2]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
dp = p_xform.elements[1].dot(xf_points2[3]);
- maxa=MAX(dp,maxa);
- mina=MIN(dp,mina);
+ maxa = MAX(dp, maxa);
+ mina = MIN(dp, mina);
- maxb=p_xform.elements[1].dot(xf_points[0]);
- minb=maxb;
+ maxb = p_xform.elements[1].dot(xf_points[0]);
+ minb = maxb;
dp = p_xform.elements[1].dot(xf_points[1]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
dp = p_xform.elements[1].dot(xf_points[2]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
dp = p_xform.elements[1].dot(xf_points[3]);
- maxb=MAX(dp,maxb);
- minb=MIN(dp,minb);
+ maxb = MAX(dp, maxb);
+ minb = MIN(dp, minb);
-
- if ( mina > maxb )
+ if (mina > maxb)
return false;
- if ( minb > maxa )
+ if (minb > maxa)
return false;
-
return true;
-
}
-Vector2 Transform2D::basis_xform(const Vector2& v) const {
+Vector2 Transform2D::basis_xform(const Vector2 &v) const {
return Vector2(
- tdotx(v),
- tdoty(v)
- );
+ tdotx(v),
+ tdoty(v));
}
-Vector2 Transform2D::basis_xform_inv(const Vector2& v) const{
+Vector2 Transform2D::basis_xform_inv(const Vector2 &v) const {
return Vector2(
- elements[0].dot(v),
- elements[1].dot(v)
- );
+ elements[0].dot(v),
+ elements[1].dot(v));
}
-Vector2 Transform2D::xform(const Vector2& v) const {
+Vector2 Transform2D::xform(const Vector2 &v) const {
return Vector2(
- tdotx(v),
- tdoty(v)
- ) + elements[2];
+ tdotx(v),
+ tdoty(v)) +
+ elements[2];
}
-Vector2 Transform2D::xform_inv(const Vector2& p_vec) const {
+Vector2 Transform2D::xform_inv(const Vector2 &p_vec) const {
Vector2 v = p_vec - elements[2];
return Vector2(
- elements[0].dot(v),
- elements[1].dot(v)
- );
-
+ elements[0].dot(v),
+ elements[1].dot(v));
}
-Rect2 Transform2D::xform(const Rect2& p_rect) const {
+Rect2 Transform2D::xform(const Rect2 &p_rect) const {
- Vector2 x=elements[0]*p_rect.size.x;
- Vector2 y=elements[1]*p_rect.size.y;
- Vector2 pos = xform( p_rect.pos );
+ Vector2 x = elements[0] * p_rect.size.x;
+ Vector2 y = elements[1] * p_rect.size.y;
+ Vector2 pos = xform(p_rect.pos);
Rect2 new_rect;
- new_rect.pos=pos;
- new_rect.expand_to( pos+x );
- new_rect.expand_to( pos+y );
- new_rect.expand_to( pos+x+y );
+ new_rect.pos = pos;
+ new_rect.expand_to(pos + x);
+ new_rect.expand_to(pos + y);
+ new_rect.expand_to(pos + x + y);
return new_rect;
}
-void Transform2D::set_rotation_and_scale(real_t p_rot,const Size2& p_scale) {
-
- elements[0][0]=Math::cos(p_rot)*p_scale.x;
- elements[1][1]=Math::cos(p_rot)*p_scale.y;
- elements[1][0]=-Math::sin(p_rot)*p_scale.y;
- elements[0][1]=Math::sin(p_rot)*p_scale.x;
+void Transform2D::set_rotation_and_scale(real_t p_rot, const Size2 &p_scale) {
+ elements[0][0] = Math::cos(p_rot) * p_scale.x;
+ elements[1][1] = Math::cos(p_rot) * p_scale.y;
+ elements[1][0] = -Math::sin(p_rot) * p_scale.y;
+ elements[0][1] = Math::sin(p_rot) * p_scale.x;
}
-Rect2 Transform2D::xform_inv(const Rect2& p_rect) const {
+Rect2 Transform2D::xform_inv(const Rect2 &p_rect) const {
- Vector2 ends[4]={
- xform_inv( p_rect.pos ),
- xform_inv( Vector2(p_rect.pos.x,p_rect.pos.y+p_rect.size.y ) ),
- xform_inv( Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y+p_rect.size.y ) ),
- xform_inv( Vector2(p_rect.pos.x+p_rect.size.x,p_rect.pos.y ) )
+ Vector2 ends[4] = {
+ xform_inv(p_rect.pos),
+ xform_inv(Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.y)),
+ xform_inv(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y + p_rect.size.y)),
+ xform_inv(Vector2(p_rect.pos.x + p_rect.size.x, p_rect.pos.y))
};
Rect2 new_rect;
- new_rect.pos=ends[0];
+ new_rect.pos = ends[0];
new_rect.expand_to(ends[1]);
new_rect.expand_to(ends[2]);
new_rect.expand_to(ends[3]);
@@ -867,5 +880,4 @@ Rect2 Transform2D::xform_inv(const Rect2& p_rect) const {
return new_rect;
}
-
#endif
diff --git a/core/math/math_defs.h b/core/math/math_defs.h
index feaff38a44..08f4e27e64 100644
--- a/core/math/math_defs.h
+++ b/core/math/math_defs.h
@@ -30,11 +30,11 @@
#define MATH_DEFS_H
#define CMP_EPSILON 0.00001
-#define CMP_EPSILON2 (CMP_EPSILON*CMP_EPSILON)
+#define CMP_EPSILON2 (CMP_EPSILON * CMP_EPSILON)
#define CMP_NORMALIZE_TOLERANCE 0.000001
#define CMP_POINT_IN_PLANE_EPSILON 0.00001
-#define USEC_TO_SEC(m_usec) ((m_usec)/1000000.0)
+#define USEC_TO_SEC(m_usec) ((m_usec) / 1000000.0)
/**
* "Real" is a type that will be translated to either floats or fixed depending
* on the compilation setting
@@ -42,11 +42,10 @@
enum ClockDirection {
- CLOCKWISE,
+ CLOCKWISE,
COUNTERCLOCKWISE
};
-
#ifdef REAL_T_IS_DOUBLE
typedef double real_t;
@@ -57,5 +56,4 @@ typedef float real_t;
#endif
-
#endif // MATH_DEFS_H
diff --git a/core/math/math_funcs.cpp b/core/math/math_funcs.cpp
index c730b4fa30..ccc463c114 100644
--- a/core/math/math_funcs.cpp
+++ b/core/math/math_funcs.cpp
@@ -29,7 +29,7 @@
#include "math_funcs.h"
#include "core/os/os.h"
-pcg32_random_t Math::default_pcg = {1, PCG_DEFAULT_INC_64};
+pcg32_random_t Math::default_pcg = { 1, PCG_DEFAULT_INC_64 };
#define PHI 0x9e3779b9
@@ -39,30 +39,29 @@ static uint32_t Q[4096];
// TODO: we should eventually expose pcg.inc too
uint32_t Math::rand_from_seed(uint64_t *seed) {
- pcg32_random_t pcg = {*seed, PCG_DEFAULT_INC_64};
+ pcg32_random_t pcg = { *seed, PCG_DEFAULT_INC_64 };
uint32_t r = pcg32_random_r(&pcg);
*seed = pcg.state;
return r;
}
void Math::seed(uint64_t x) {
- default_pcg.state=x;
+ default_pcg.state = x;
}
void Math::randomize() {
OS::Time time = OS::get_singleton()->get_time();
- seed(OS::get_singleton()->get_ticks_usec()*(time.hour+1)*(time.min+1)*(time.sec+1)*rand()); // TODO: can be simplified.
+ seed(OS::get_singleton()->get_ticks_usec() * (time.hour + 1) * (time.min + 1) * (time.sec + 1) * rand()); // TODO: can be simplified.
}
uint32_t Math::rand() {
return pcg32_random_r(&default_pcg);
}
-
int Math::step_decimals(double p_step) {
- static const int maxn=9;
- static const double sd[maxn]={
+ static const int maxn = 9;
+ static const double sd[maxn] = {
0.9999, // somehow compensate for floating point error
0.09999,
0.009999,
@@ -74,9 +73,9 @@ int Math::step_decimals(double p_step) {
0.000000009999
};
- double as=Math::abs(p_step);
- for(int i=0;i<maxn;i++) {
- if (as>=sd[i]) {
+ double as = Math::abs(p_step);
+ for (int i = 0; i < maxn; i++) {
+ if (as >= sd[i]) {
return i;
}
}
@@ -84,46 +83,45 @@ int Math::step_decimals(double p_step) {
return maxn;
}
-double Math::dectime(double p_value,double p_amount, double p_step) {
+double Math::dectime(double p_value, double p_amount, double p_step) {
double sgn = p_value < 0 ? -1.0 : 1.0;
double val = Math::abs(p_value);
- val-=p_amount*p_step;
- if (val<0.0)
- val=0.0;
- return val*sgn;
+ val -= p_amount * p_step;
+ if (val < 0.0)
+ val = 0.0;
+ return val * sgn;
}
double Math::ease(double p_x, double p_c) {
- if (p_x<0)
- p_x=0;
- else if (p_x>1.0)
- p_x=1.0;
- if (p_c>0) {
- if (p_c<1.0) {
- return 1.0-Math::pow(1.0-p_x,1.0/p_c);
+ if (p_x < 0)
+ p_x = 0;
+ else if (p_x > 1.0)
+ p_x = 1.0;
+ if (p_c > 0) {
+ if (p_c < 1.0) {
+ return 1.0 - Math::pow(1.0 - p_x, 1.0 / p_c);
} else {
- return Math::pow(p_x,p_c);
+ return Math::pow(p_x, p_c);
}
- } else if (p_c<0) {
+ } else if (p_c < 0) {
//inout ease
- if (p_x<0.5) {
- return Math::pow(p_x*2.0,-p_c)*0.5;
+ if (p_x < 0.5) {
+ return Math::pow(p_x * 2.0, -p_c) * 0.5;
} else {
- return (1.0-Math::pow(1.0-(p_x-0.5)*2.0,-p_c))*0.5+0.5;
+ return (1.0 - Math::pow(1.0 - (p_x - 0.5) * 2.0, -p_c)) * 0.5 + 0.5;
}
} else
return 0; // no ease (raw)
}
-double Math::stepify(double p_value,double p_step) {
- if (p_step!=0) {
- p_value=Math::floor( p_value / p_step + 0.5 ) * p_step;
+double Math::stepify(double p_value, double p_step) {
+ if (p_step != 0) {
+ p_value = Math::floor(p_value / p_step + 0.5) * p_step;
}
return p_value;
}
-
uint32_t Math::larger_prime(uint32_t p_val) {
static const uint32_t primes[] = {
@@ -159,11 +157,11 @@ uint32_t Math::larger_prime(uint32_t p_val) {
0,
};
- int idx=0;
+ int idx = 0;
while (true) {
- ERR_FAIL_COND_V(primes[idx]==0,0);
- if (primes[idx]>p_val)
+ ERR_FAIL_COND_V(primes[idx] == 0, 0);
+ if (primes[idx] > p_val)
return primes[idx];
idx++;
}
@@ -173,14 +171,12 @@ uint32_t Math::larger_prime(uint32_t p_val) {
double Math::random(double from, double to) {
unsigned int r = Math::rand();
- double ret = (double)r/(double)RANDOM_MAX;
- return (ret)*(to-from) + from;
+ double ret = (double)r / (double)RANDOM_MAX;
+ return (ret) * (to - from) + from;
}
float Math::random(float from, float to) {
unsigned int r = Math::rand();
- float ret = (float)r/(float)RANDOM_MAX;
- return (ret)*(to-from) + from;
+ float ret = (float)r / (float)RANDOM_MAX;
+ return (ret) * (to - from) + from;
}
-
-
diff --git a/core/math/math_funcs.h b/core/math/math_funcs.h
index ae461eda2e..3e02ac0bb8 100644
--- a/core/math/math_funcs.h
+++ b/core/math/math_funcs.h
@@ -29,13 +29,13 @@
#ifndef MATH_FUNCS_H
#define MATH_FUNCS_H
-#include "typedefs.h"
#include "math_defs.h"
#include "pcg.h"
+#include "typedefs.h"
-#include <math.h>
#include <float.h>
-
+#include <math.h>
+
#define Math_PI 3.14159265358979323846
#define Math_SQRT12 0.7071067811865475244008443621048490
#define Math_LN2 0.693147180559945309417
@@ -50,10 +50,9 @@ public:
Math() {} // useless to instance
enum {
- RANDOM_MAX=4294967295L
+ RANDOM_MAX = 4294967295L
};
-
static _ALWAYS_INLINE_ double sin(double p_x) { return ::sin(p_x); }
static _ALWAYS_INLINE_ float sin(float p_x) { return ::sinf(p_x); }
@@ -81,14 +80,14 @@ public:
static _ALWAYS_INLINE_ double atan(double p_x) { return ::atan(p_x); }
static _ALWAYS_INLINE_ float atan(float p_x) { return ::atanf(p_x); }
- static _ALWAYS_INLINE_ double atan2(double p_y, double p_x) { return ::atan2(p_y,p_x); }
- static _ALWAYS_INLINE_ float atan2(float p_y, float p_x) { return ::atan2f(p_y,p_x); }
+ static _ALWAYS_INLINE_ double atan2(double p_y, double p_x) { return ::atan2(p_y, p_x); }
+ static _ALWAYS_INLINE_ float atan2(float p_y, float p_x) { return ::atan2f(p_y, p_x); }
static _ALWAYS_INLINE_ double sqrt(double p_x) { return ::sqrt(p_x); }
static _ALWAYS_INLINE_ float sqrt(float p_x) { return ::sqrtf(p_x); }
- static _ALWAYS_INLINE_ double fmod(double p_x,double p_y) { return ::fmod(p_x,p_y); }
- static _ALWAYS_INLINE_ float fmod(float p_x,float p_y) { return ::fmodf(p_x,p_y); }
+ static _ALWAYS_INLINE_ double fmod(double p_x, double p_y) { return ::fmod(p_x, p_y); }
+ static _ALWAYS_INLINE_ float fmod(float p_x, float p_y) { return ::fmodf(p_x, p_y); }
static _ALWAYS_INLINE_ double floor(double p_x) { return ::floor(p_x); }
static _ALWAYS_INLINE_ float floor(float p_x) { return ::floorf(p_x); }
@@ -96,8 +95,8 @@ public:
static _ALWAYS_INLINE_ double ceil(double p_x) { return ::ceil(p_x); }
static _ALWAYS_INLINE_ float ceil(float p_x) { return ::ceilf(p_x); }
- static _ALWAYS_INLINE_ double pow(double p_x, double p_y) { return ::pow(p_x,p_y); }
- static _ALWAYS_INLINE_ float pow(float p_x, float p_y) { return ::powf(p_x,p_y); }
+ static _ALWAYS_INLINE_ double pow(double p_x, double p_y) { return ::pow(p_x, p_y); }
+ static _ALWAYS_INLINE_ float pow(float p_x, float p_y) { return ::powf(p_x, p_y); }
static _ALWAYS_INLINE_ double log(double p_x) { return ::log(p_x); }
static _ALWAYS_INLINE_ float log(float p_x) { return ::logf(p_x); }
@@ -105,59 +104,59 @@ public:
static _ALWAYS_INLINE_ double exp(double p_x) { return ::exp(p_x); }
static _ALWAYS_INLINE_ float exp(float p_x) { return ::expf(p_x); }
- static _ALWAYS_INLINE_ bool is_nan(double p_val) { return (p_val!=p_val); }
- static _ALWAYS_INLINE_ bool is_nan(float p_val) { return (p_val!=p_val); }
+ static _ALWAYS_INLINE_ bool is_nan(double p_val) { return (p_val != p_val); }
+ static _ALWAYS_INLINE_ bool is_nan(float p_val) { return (p_val != p_val); }
static _ALWAYS_INLINE_ bool is_inf(double p_val) {
- #ifdef _MSC_VER
+#ifdef _MSC_VER
return !_finite(p_val);
- #else
+#else
return isinf(p_val);
- #endif
+#endif
}
-
+
static _ALWAYS_INLINE_ bool is_inf(float p_val) {
- #ifdef _MSC_VER
+#ifdef _MSC_VER
return !_finite(p_val);
- #else
+#else
return isinf(p_val);
- #endif
+#endif
}
-
+
static _ALWAYS_INLINE_ double abs(double g) { return absd(g); }
static _ALWAYS_INLINE_ float abs(float g) { return absf(g); }
static _ALWAYS_INLINE_ int abs(int g) { return g > 0 ? g : -g; }
- static _ALWAYS_INLINE_ double fposmod(double p_x,double p_y) { return (p_x>=0) ? Math::fmod(p_x,p_y) : p_y-Math::fmod(-p_x,p_y); }
- static _ALWAYS_INLINE_ float fposmod(float p_x,float p_y) { return (p_x>=0) ? Math::fmod(p_x,p_y) : p_y-Math::fmod(-p_x,p_y); }
+ static _ALWAYS_INLINE_ double fposmod(double p_x, double p_y) { return (p_x >= 0) ? Math::fmod(p_x, p_y) : p_y - Math::fmod(-p_x, p_y); }
+ static _ALWAYS_INLINE_ float fposmod(float p_x, float p_y) { return (p_x >= 0) ? Math::fmod(p_x, p_y) : p_y - Math::fmod(-p_x, p_y); }
- static _ALWAYS_INLINE_ double deg2rad(double p_y) { return p_y*Math_PI/180.0; }
- static _ALWAYS_INLINE_ float deg2rad(float p_y) { return p_y*Math_PI/180.0; }
+ static _ALWAYS_INLINE_ double deg2rad(double p_y) { return p_y * Math_PI / 180.0; }
+ static _ALWAYS_INLINE_ float deg2rad(float p_y) { return p_y * Math_PI / 180.0; }
- static _ALWAYS_INLINE_ double rad2deg(double p_y) { return p_y*180.0/Math_PI; }
- static _ALWAYS_INLINE_ float rad2deg(float p_y) { return p_y*180.0/Math_PI; }
+ static _ALWAYS_INLINE_ double rad2deg(double p_y) { return p_y * 180.0 / Math_PI; }
+ static _ALWAYS_INLINE_ float rad2deg(float p_y) { return p_y * 180.0 / Math_PI; }
- static _ALWAYS_INLINE_ double lerp(double a, double b, double c) { return a+(b-a)*c; }
- static _ALWAYS_INLINE_ float lerp(float a, float b, float c) { return a+(b-a)*c; }
+ static _ALWAYS_INLINE_ double lerp(double a, double b, double c) { return a + (b - a) * c; }
+ static _ALWAYS_INLINE_ float lerp(float a, float b, float c) { return a + (b - a) * c; }
- static _ALWAYS_INLINE_ double linear2db(double p_linear) { return Math::log( p_linear ) * 8.6858896380650365530225783783321; }
- static _ALWAYS_INLINE_ float linear2db(float p_linear) { return Math::log( p_linear ) * 8.6858896380650365530225783783321; }
+ static _ALWAYS_INLINE_ double linear2db(double p_linear) { return Math::log(p_linear) * 8.6858896380650365530225783783321; }
+ static _ALWAYS_INLINE_ float linear2db(float p_linear) { return Math::log(p_linear) * 8.6858896380650365530225783783321; }
- static _ALWAYS_INLINE_ double db2linear(double p_db) { return Math::exp( p_db * 0.11512925464970228420089957273422 ); }
- static _ALWAYS_INLINE_ float db2linear(float p_db) { return Math::exp( p_db * 0.11512925464970228420089957273422 ); }
+ static _ALWAYS_INLINE_ double db2linear(double p_db) { return Math::exp(p_db * 0.11512925464970228420089957273422); }
+ static _ALWAYS_INLINE_ float db2linear(float p_db) { return Math::exp(p_db * 0.11512925464970228420089957273422); }
- static _ALWAYS_INLINE_ double round(double p_val) { return (p_val>=0) ? Math::floor(p_val+0.5) : -Math::floor(-p_val+0.5); }
- static _ALWAYS_INLINE_ float round(float p_val) { return (p_val>=0) ? Math::floor(p_val+0.5) : -Math::floor(-p_val+0.5); }
+ static _ALWAYS_INLINE_ double round(double p_val) { return (p_val >= 0) ? Math::floor(p_val + 0.5) : -Math::floor(-p_val + 0.5); }
+ static _ALWAYS_INLINE_ float round(float p_val) { return (p_val >= 0) ? Math::floor(p_val + 0.5) : -Math::floor(-p_val + 0.5); }
// double only, as these functions are mainly used by the editor and not performance-critical,
static double ease(double p_x, double p_c);
static int step_decimals(double p_step);
- static double stepify(double p_value,double p_step);
- static double dectime(double p_value,double p_amount, double p_step);
+ static double stepify(double p_value, double p_step);
+ static double dectime(double p_value, double p_amount, double p_step);
static uint32_t larger_prime(uint32_t p_val);
- static void seed(uint64_t x=0);
+ static void seed(uint64_t x = 0);
static void randomize();
static uint32_t rand_from_seed(uint64_t *seed);
static uint32_t rand();
@@ -168,17 +167,15 @@ public:
static float random(float from, float to);
static real_t random(int from, int to) { return (real_t)random((real_t)from, (real_t)to); }
-
static _ALWAYS_INLINE_ bool isequal_approx(real_t a, real_t b) {
// TODO: Comparing floats for approximate-equality is non-trivial.
// Using epsilon should cover the typical cases in Godot (where a == b is used to compare two reals), such as matrix and vector comparison operators.
// A proper implementation in terms of ULPs should eventually replace the contents of this function.
// See https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ for details.
- return abs(a-b) < CMP_EPSILON;
+ return abs(a - b) < CMP_EPSILON;
}
-
static _ALWAYS_INLINE_ float absf(float g) {
union {
@@ -186,8 +183,8 @@ public:
uint32_t i;
} u;
- u.f=g;
- u.i&=2147483647u;
+ u.f = g;
+ u.i &= 2147483647u;
return u.f;
}
@@ -197,8 +194,8 @@ public:
double d;
uint64_t i;
} u;
- u.d=g;
- u.i&=(uint64_t)9223372036854775807ll;
+ u.d = g;
+ u.i &= (uint64_t)9223372036854775807ll;
return u.d;
}
@@ -208,11 +205,10 @@ public:
static int b;
#if (defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0603) || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // windows 8 phone?
- b = (int)((a>0.0) ? (a + 0.5):(a -0.5));
+ b = (int)((a > 0.0) ? (a + 0.5) : (a - 0.5));
#elif defined(_MSC_VER) && _MSC_VER < 1800
- __asm fld a
- __asm fistp b
+ __asm fld a __asm fistp b
/*#elif defined( __GNUC__ ) && ( defined( __i386__ ) || defined( __x86_64__ ) )
// use AT&T inline assembly style, document that
// we use memory as output (=m) and input (m)
@@ -223,12 +219,11 @@ public:
: "m" (a));*/
#else
- b=lrintf(a); //assuming everything but msvc 2012 or earlier has lrint
+ b = lrintf(a); //assuming everything but msvc 2012 or earlier has lrint
#endif
- return b;
+ return b;
}
-
#if defined(__GNUC__)
static _ALWAYS_INLINE_ int64_t dtoll(double p_double) { return (int64_t)p_double; } ///@TODO OPTIMIZE
@@ -239,37 +234,35 @@ public:
static _ALWAYS_INLINE_ int64_t dtoll(float p_float) { return (int64_t)p_float; } ///@TODO OPTIMIZE and rename
#endif
-
- static _ALWAYS_INLINE_ uint32_t halfbits_to_floatbits(uint16_t h)
- {
- uint16_t h_exp, h_sig;
- uint32_t f_sgn, f_exp, f_sig;
-
- h_exp = (h&0x7c00u);
- f_sgn = ((uint32_t)h&0x8000u) << 16;
- switch (h_exp) {
- case 0x0000u: /* 0 or subnormal */
- h_sig = (h&0x03ffu);
- /* Signed zero */
- if (h_sig == 0) {
- return f_sgn;
- }
- /* Subnormal */
- h_sig <<= 1;
- while ((h_sig&0x0400u) == 0) {
- h_sig <<= 1;
- h_exp++;
- }
- f_exp = ((uint32_t)(127 - 15 - h_exp)) << 23;
- f_sig = ((uint32_t)(h_sig&0x03ffu)) << 13;
- return f_sgn + f_exp + f_sig;
- case 0x7c00u: /* inf or NaN */
- /* All-ones exponent and a copy of the significand */
- return f_sgn + 0x7f800000u + (((uint32_t)(h&0x03ffu)) << 13);
- default: /* normalized */
- /* Just need to adjust the exponent and shift */
- return f_sgn + (((uint32_t)(h&0x7fffu) + 0x1c000u) << 13);
- }
+ static _ALWAYS_INLINE_ uint32_t halfbits_to_floatbits(uint16_t h) {
+ uint16_t h_exp, h_sig;
+ uint32_t f_sgn, f_exp, f_sig;
+
+ h_exp = (h & 0x7c00u);
+ f_sgn = ((uint32_t)h & 0x8000u) << 16;
+ switch (h_exp) {
+ case 0x0000u: /* 0 or subnormal */
+ h_sig = (h & 0x03ffu);
+ /* Signed zero */
+ if (h_sig == 0) {
+ return f_sgn;
+ }
+ /* Subnormal */
+ h_sig <<= 1;
+ while ((h_sig & 0x0400u) == 0) {
+ h_sig <<= 1;
+ h_exp++;
+ }
+ f_exp = ((uint32_t)(127 - 15 - h_exp)) << 23;
+ f_sig = ((uint32_t)(h_sig & 0x03ffu)) << 13;
+ return f_sgn + f_exp + f_sig;
+ case 0x7c00u: /* inf or NaN */
+ /* All-ones exponent and a copy of the significand */
+ return f_sgn + 0x7f800000u + (((uint32_t)(h & 0x03ffu)) << 13);
+ default: /* normalized */
+ /* Just need to adjust the exponent and shift */
+ return f_sgn + (((uint32_t)(h & 0x7fffu) + 0x1c000u) << 13);
+ }
}
static _ALWAYS_INLINE_ float halfptr_to_float(const uint16_t *h) {
@@ -279,70 +272,58 @@ public:
float f32;
} u;
- u.u32=halfbits_to_floatbits(*h);
+ u.u32 = halfbits_to_floatbits(*h);
return u.f32;
}
static _ALWAYS_INLINE_ uint16_t make_half_float(float f) {
- union {
- float fv;
- uint32_t ui;
- } ci;
- ci.fv=f;
-
- uint32_t x = ci.ui;
- uint32_t sign = (unsigned short)(x >> 31);
- uint32_t mantissa;
- uint32_t exp;
- uint16_t hf;
-
- // get mantissa
- mantissa = x & ((1 << 23) - 1);
- // get exponent bits
- exp = x & (0xFF << 23);
- if (exp >= 0x47800000)
- {
- // check if the original single precision float number is a NaN
- if (mantissa && (exp == (0xFF << 23)))
- {
- // we have a single precision NaN
- mantissa = (1 << 23) - 1;
- }
- else
- {
- // 16-bit half-float representation stores number as Inf
- mantissa = 0;
+ union {
+ float fv;
+ uint32_t ui;
+ } ci;
+ ci.fv = f;
+
+ uint32_t x = ci.ui;
+ uint32_t sign = (unsigned short)(x >> 31);
+ uint32_t mantissa;
+ uint32_t exp;
+ uint16_t hf;
+
+ // get mantissa
+ mantissa = x & ((1 << 23) - 1);
+ // get exponent bits
+ exp = x & (0xFF << 23);
+ if (exp >= 0x47800000) {
+ // check if the original single precision float number is a NaN
+ if (mantissa && (exp == (0xFF << 23))) {
+ // we have a single precision NaN
+ mantissa = (1 << 23) - 1;
+ } else {
+ // 16-bit half-float representation stores number as Inf
+ mantissa = 0;
+ }
+ hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) |
+ (uint16_t)(mantissa >> 13);
}
- hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) |
- (uint16_t)(mantissa >> 13);
- }
- // check if exponent is <= -15
- else if (exp <= 0x38000000)
- {
-
- /*// store a denorm half-float value or zero
+ // check if exponent is <= -15
+ else if (exp <= 0x38000000) {
+
+ /*// store a denorm half-float value or zero
exp = (0x38000000 - exp) >> 23;
mantissa >>= (14 + exp);
hf = (((uint16_t)sign) << 15) | (uint16_t)(mantissa);
*/
- hf=0; //denormals do not work for 3D, convert to zero
- }
- else
- {
- hf = (((uint16_t)sign) << 15) |
- (uint16_t)((exp - 0x38000000) >> 13) |
- (uint16_t)(mantissa >> 13);
- }
-
- return hf;
- }
-
-
+ hf = 0; //denormals do not work for 3D, convert to zero
+ } else {
+ hf = (((uint16_t)sign) << 15) |
+ (uint16_t)((exp - 0x38000000) >> 13) |
+ (uint16_t)(mantissa >> 13);
+ }
+ return hf;
+ }
};
-
-
#endif // MATH_FUNCS_H
diff --git a/core/math/matrix3.cpp b/core/math/matrix3.cpp
index 1fabfbbd4c..5f73d91ef3 100644
--- a/core/math/matrix3.cpp
+++ b/core/math/matrix3.cpp
@@ -30,46 +30,44 @@
#include "math_funcs.h"
#include "os/copymem.h"
-#define cofac(row1,col1, row2, col2)\
+#define cofac(row1, col1, row2, col2) \
(elements[row1][col1] * elements[row2][col2] - elements[row1][col2] * elements[row2][col1])
-void Basis::from_z(const Vector3& p_z) {
+void Basis::from_z(const Vector3 &p_z) {
- if (Math::abs(p_z.z) > Math_SQRT12 ) {
+ if (Math::abs(p_z.z) > Math_SQRT12) {
// choose p in y-z plane
- real_t a = p_z[1]*p_z[1] + p_z[2]*p_z[2];
- real_t k = 1.0/Math::sqrt(a);
- elements[0]=Vector3(0,-p_z[2]*k,p_z[1]*k);
- elements[1]=Vector3(a*k,-p_z[0]*elements[0][2],p_z[0]*elements[0][1]);
+ real_t a = p_z[1] * p_z[1] + p_z[2] * p_z[2];
+ real_t k = 1.0 / Math::sqrt(a);
+ elements[0] = Vector3(0, -p_z[2] * k, p_z[1] * k);
+ elements[1] = Vector3(a * k, -p_z[0] * elements[0][2], p_z[0] * elements[0][1]);
} else {
// choose p in x-y plane
- real_t a = p_z.x*p_z.x + p_z.y*p_z.y;
- real_t k = 1.0/Math::sqrt(a);
- elements[0]=Vector3(-p_z.y*k,p_z.x*k,0);
- elements[1]=Vector3(-p_z.z*elements[0].y,p_z.z*elements[0].x,a*k);
+ real_t a = p_z.x * p_z.x + p_z.y * p_z.y;
+ real_t k = 1.0 / Math::sqrt(a);
+ elements[0] = Vector3(-p_z.y * k, p_z.x * k, 0);
+ elements[1] = Vector3(-p_z.z * elements[0].y, p_z.z * elements[0].x, a * k);
}
- elements[2]=p_z;
+ elements[2] = p_z;
}
void Basis::invert() {
-
- real_t co[3]={
+ real_t co[3] = {
cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)
};
- real_t det = elements[0][0] * co[0]+
- elements[0][1] * co[1]+
- elements[0][2] * co[2];
-
- ERR_FAIL_COND( det == 0 );
- real_t s = 1.0/det;
+ real_t det = elements[0][0] * co[0] +
+ elements[0][1] * co[1] +
+ elements[0][2] * co[2];
- set( co[0]*s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
- co[1]*s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
- co[2]*s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s );
+ ERR_FAIL_COND(det == 0);
+ real_t s = 1.0 / det;
+ set(co[0] * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
+ co[1] * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
+ co[2] * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
}
void Basis::orthonormalize() {
@@ -77,20 +75,19 @@ void Basis::orthonormalize() {
// Gram-Schmidt Process
- Vector3 x=get_axis(0);
- Vector3 y=get_axis(1);
- Vector3 z=get_axis(2);
+ Vector3 x = get_axis(0);
+ Vector3 y = get_axis(1);
+ Vector3 z = get_axis(2);
x.normalize();
- y = (y-x*(x.dot(y)));
+ y = (y - x * (x.dot(y)));
y.normalize();
- z = (z-x*(x.dot(z))-y*(y.dot(z)));
+ z = (z - x * (x.dot(z)) - y * (y.dot(z)));
z.normalize();
- set_axis(0,x);
- set_axis(1,y);
- set_axis(2,z);
-
+ set_axis(0, x);
+ set_axis(1, y);
+ set_axis(2, z);
}
Basis Basis::orthonormalized() const {
@@ -102,16 +99,15 @@ Basis Basis::orthonormalized() const {
bool Basis::is_orthogonal() const {
Basis id;
- Basis m = (*this)*transposed();
+ Basis m = (*this) * transposed();
- return isequal_approx(id,m);
+ return isequal_approx(id, m);
}
bool Basis::is_rotation() const {
return Math::isequal_approx(determinant(), 1) && is_orthogonal();
}
-
bool Basis::is_symmetric() const {
if (Math::abs(elements[0][1] - elements[1][0]) > CMP_EPSILON)
@@ -124,21 +120,20 @@ bool Basis::is_symmetric() const {
return true;
}
-
Basis Basis::diagonalize() {
//NOTE: only implemented for symmetric matrices
//with the Jacobi iterative method method
-
+
ERR_FAIL_COND_V(!is_symmetric(), Basis());
const int ite_max = 1024;
- real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2];
+ real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2];
int ite = 0;
Basis acc_rot;
- while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max ) {
+ while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max) {
real_t el01_2 = elements[0][1] * elements[0][1];
real_t el02_2 = elements[0][2] * elements[0][2];
real_t el12_2 = elements[1][2] * elements[1][2];
@@ -151,7 +146,7 @@ Basis Basis::diagonalize() {
} else {
i = 0;
j = 1;
- }
+ }
} else {
if (el12_2 > el02_2) {
i = 1;
@@ -163,17 +158,17 @@ Basis Basis::diagonalize() {
}
// Compute the rotation angle
- real_t angle;
+ real_t angle;
if (Math::abs(elements[j][j] - elements[i][i]) < CMP_EPSILON) {
angle = Math_PI / 4;
} else {
- angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i]));
+ angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i]));
}
// Compute the rotation matrix
Basis rot;
rot.elements[i][i] = rot.elements[j][j] = Math::cos(angle);
- rot.elements[i][j] = - (rot.elements[j][i] = Math::sin(angle));
+ rot.elements[i][j] = -(rot.elements[j][i] = Math::sin(angle));
// Update the off matrix norm
off_matrix_norm_2 -= elements[i][j] * elements[i][j];
@@ -188,41 +183,41 @@ Basis Basis::diagonalize() {
Basis Basis::inverse() const {
- Basis inv=*this;
+ Basis inv = *this;
inv.invert();
return inv;
}
void Basis::transpose() {
- SWAP(elements[0][1],elements[1][0]);
- SWAP(elements[0][2],elements[2][0]);
- SWAP(elements[1][2],elements[2][1]);
+ SWAP(elements[0][1], elements[1][0]);
+ SWAP(elements[0][2], elements[2][0]);
+ SWAP(elements[1][2], elements[2][1]);
}
Basis Basis::transposed() const {
- Basis tr=*this;
+ Basis tr = *this;
tr.transpose();
return tr;
}
// Multiplies the matrix from left by the scaling matrix: M -> S.M
// See the comment for Basis::rotated for further explanation.
-void Basis::scale(const Vector3& p_scale) {
+void Basis::scale(const Vector3 &p_scale) {
- elements[0][0]*=p_scale.x;
- elements[0][1]*=p_scale.x;
- elements[0][2]*=p_scale.x;
- elements[1][0]*=p_scale.y;
- elements[1][1]*=p_scale.y;
- elements[1][2]*=p_scale.y;
- elements[2][0]*=p_scale.z;
- elements[2][1]*=p_scale.z;
- elements[2][2]*=p_scale.z;
+ elements[0][0] *= p_scale.x;
+ elements[0][1] *= p_scale.x;
+ elements[0][2] *= p_scale.x;
+ elements[1][0] *= p_scale.y;
+ elements[1][1] *= p_scale.y;
+ elements[1][2] *= p_scale.y;
+ elements[2][0] *= p_scale.z;
+ elements[2][1] *= p_scale.z;
+ elements[2][2] *= p_scale.z;
}
-Basis Basis::scaled( const Vector3& p_scale ) const {
+Basis Basis::scaled(const Vector3 &p_scale) const {
Basis m = *this;
m.scale(p_scale);
@@ -236,12 +231,10 @@ Vector3 Basis::get_scale() const {
// (such that it can be represented by a Quat or Euler angles), we absorb the sign flip into the scaling matrix.
// As such, it works in conjuction with get_rotation().
real_t det_sign = determinant() > 0 ? 1 : -1;
- return det_sign*Vector3(
- Vector3(elements[0][0],elements[1][0],elements[2][0]).length(),
- Vector3(elements[0][1],elements[1][1],elements[2][1]).length(),
- Vector3(elements[0][2],elements[1][2],elements[2][2]).length()
- );
-
+ return det_sign * Vector3(
+ Vector3(elements[0][0], elements[1][0], elements[2][0]).length(),
+ Vector3(elements[0][1], elements[1][1], elements[2][1]).length(),
+ Vector3(elements[0][2], elements[1][2], elements[2][2]).length());
}
// Multiplies the matrix from left by the rotation matrix: M -> R.M
@@ -250,19 +243,19 @@ Vector3 Basis::get_scale() const {
// The main use of Basis is as Transform.basis, which is used a the transformation matrix
// of 3D object. Rotate here refers to rotation of the object (which is R * (*this)),
// not the matrix itself (which is R * (*this) * R.transposed()).
-Basis Basis::rotated(const Vector3& p_axis, real_t p_phi) const {
+Basis Basis::rotated(const Vector3 &p_axis, real_t p_phi) const {
return Basis(p_axis, p_phi) * (*this);
}
-void Basis::rotate(const Vector3& p_axis, real_t p_phi) {
+void Basis::rotate(const Vector3 &p_axis, real_t p_phi) {
*this = rotated(p_axis, p_phi);
}
-Basis Basis::rotated(const Vector3& p_euler) const {
+Basis Basis::rotated(const Vector3 &p_euler) const {
return Basis(p_euler) * (*this);
}
-void Basis::rotate(const Vector3& p_euler) {
+void Basis::rotate(const Vector3 &p_euler) {
*this = rotated(p_euler);
}
@@ -274,7 +267,7 @@ Vector3 Basis::get_rotation() const {
real_t det = m.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.
- m.scale(Vector3(-1,-1,-1));
+ m.scale(Vector3(-1, -1, -1));
}
return m.get_euler();
@@ -304,67 +297,64 @@ Vector3 Basis::get_euler() const {
ERR_FAIL_COND_V(is_rotation() == false, euler);
euler.y = Math::asin(elements[0][2]);
- if ( euler.y < Math_PI*0.5) {
- if ( euler.y > -Math_PI*0.5) {
- euler.x = Math::atan2(-elements[1][2],elements[2][2]);
- euler.z = Math::atan2(-elements[0][1],elements[0][0]);
+ if (euler.y < Math_PI * 0.5) {
+ if (euler.y > -Math_PI * 0.5) {
+ euler.x = Math::atan2(-elements[1][2], elements[2][2]);
+ euler.z = Math::atan2(-elements[0][1], elements[0][0]);
} else {
- real_t r = Math::atan2(elements[1][0],elements[1][1]);
+ real_t r = Math::atan2(elements[1][0], elements[1][1]);
euler.z = 0.0;
euler.x = euler.z - r;
-
}
} else {
- real_t r = Math::atan2(elements[0][1],elements[1][1]);
+ real_t r = Math::atan2(elements[0][1], elements[1][1]);
euler.z = 0;
euler.x = r - euler.z;
}
return euler;
-
-
}
// set_euler expects a vector containing the Euler angles in the format
// (c,b,a), where a is the angle of the first rotation, and c is the last.
// The current implementation uses XYZ convention (Z is the first rotation).
-void Basis::set_euler(const Vector3& p_euler) {
+void Basis::set_euler(const Vector3 &p_euler) {
real_t c, s;
c = Math::cos(p_euler.x);
s = Math::sin(p_euler.x);
- Basis xmat(1.0,0.0,0.0,0.0,c,-s,0.0,s,c);
+ Basis xmat(1.0, 0.0, 0.0, 0.0, c, -s, 0.0, s, c);
c = Math::cos(p_euler.y);
s = Math::sin(p_euler.y);
- Basis ymat(c,0.0,s,0.0,1.0,0.0,-s,0.0,c);
+ Basis ymat(c, 0.0, s, 0.0, 1.0, 0.0, -s, 0.0, c);
c = Math::cos(p_euler.z);
s = Math::sin(p_euler.z);
- Basis zmat(c,-s,0.0,s,c,0.0,0.0,0.0,1.0);
+ Basis zmat(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0);
//optimizer will optimize away all this anyway
- *this = xmat*(ymat*zmat);
+ *this = xmat * (ymat * zmat);
}
-bool Basis::isequal_approx(const Basis& a, const Basis& b) const {
+bool Basis::isequal_approx(const Basis &a, const Basis &b) const {
- for (int i=0;i<3;i++) {
- for (int j=0;j<3;j++) {
- if (Math::isequal_approx(a.elements[i][j],b.elements[i][j]) == false)
- return false;
- }
- }
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
+ if (Math::isequal_approx(a.elements[i][j], b.elements[i][j]) == false)
+ return false;
+ }
+ }
- return true;
+ return true;
}
-bool Basis::operator==(const Basis& p_matrix) const {
+bool Basis::operator==(const Basis &p_matrix) const {
- for (int i=0;i<3;i++) {
- for (int j=0;j<3;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
if (elements[i][j] != p_matrix.elements[i][j])
return false;
}
@@ -373,22 +363,22 @@ bool Basis::operator==(const Basis& p_matrix) const {
return true;
}
-bool Basis::operator!=(const Basis& p_matrix) const {
+bool Basis::operator!=(const Basis &p_matrix) const {
- return (!(*this==p_matrix));
+ return (!(*this == p_matrix));
}
Basis::operator String() const {
String mtx;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- if (i!=0 || j!=0)
- mtx+=", ";
+ if (i != 0 || j != 0)
+ mtx += ", ";
- mtx+=rtos( elements[i][j] );
+ mtx += rtos(elements[i][j]);
}
}
@@ -401,21 +391,18 @@ Basis::operator Quat() const {
real_t trace = elements[0][0] + elements[1][1] + elements[2][2];
real_t temp[4];
- if (trace > 0.0)
- {
+ if (trace > 0.0) {
real_t s = Math::sqrt(trace + 1.0);
- temp[3]=(s * 0.5);
+ temp[3] = (s * 0.5);
s = 0.5 / s;
- temp[0]=((elements[2][1] - elements[1][2]) * s);
- temp[1]=((elements[0][2] - elements[2][0]) * s);
- temp[2]=((elements[1][0] - elements[0][1]) * s);
- }
- else
- {
+ temp[0] = ((elements[2][1] - elements[1][2]) * s);
+ temp[1] = ((elements[0][2] - elements[2][0]) * s);
+ temp[2] = ((elements[1][0] - elements[0][1]) * s);
+ } else {
int i = elements[0][0] < elements[1][1] ?
- (elements[1][1] < elements[2][2] ? 2 : 1) :
- (elements[0][0] < elements[2][2] ? 2 : 0);
+ (elements[1][1] < elements[2][2] ? 2 : 1) :
+ (elements[0][0] < elements[2][2] ? 2 : 0);
int j = (i + 1) % 3;
int k = (i + 2) % 3;
@@ -428,11 +415,10 @@ Basis::operator Quat() const {
temp[k] = (elements[k][i] + elements[i][k]) * s;
}
- return Quat(temp[0],temp[1],temp[2],temp[3]);
-
+ return Quat(temp[0], temp[1], temp[2], temp[3]);
}
-static const Basis _ortho_bases[24]={
+static const Basis _ortho_bases[24] = {
Basis(1, 0, 0, 0, 1, 0, 0, 0, 1),
Basis(0, -1, 0, 1, 0, 0, 0, 0, 1),
Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1),
@@ -462,164 +448,147 @@ static const Basis _ortho_bases[24]={
int Basis::get_orthogonal_index() const {
//could be sped up if i come up with a way
- Basis orth=*this;
- for(int i=0;i<3;i++) {
- for(int j=0;j<3;j++) {
+ Basis orth = *this;
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
real_t v = orth[i][j];
- if (v>0.5)
- v=1.0;
- else if (v<-0.5)
- v=-1.0;
+ if (v > 0.5)
+ v = 1.0;
+ else if (v < -0.5)
+ v = -1.0;
else
- v=0;
+ v = 0;
- orth[i][j]=v;
+ orth[i][j] = v;
}
}
- for(int i=0;i<24;i++) {
+ for (int i = 0; i < 24; i++) {
- if (_ortho_bases[i]==orth)
+ if (_ortho_bases[i] == orth)
return i;
-
-
}
return 0;
}
-void Basis::set_orthogonal_index(int p_index){
+void Basis::set_orthogonal_index(int p_index) {
//there only exist 24 orthogonal bases in r3
- ERR_FAIL_INDEX(p_index,24);
-
-
- *this=_ortho_bases[p_index];
+ ERR_FAIL_INDEX(p_index, 24);
+ *this = _ortho_bases[p_index];
}
-
-void Basis::get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const {
+void Basis::get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const {
ERR_FAIL_COND(is_rotation() == false);
+ real_t angle, x, y, z; // variables for result
+ real_t epsilon = 0.01; // margin to allow for rounding errors
+ real_t epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees
- real_t angle,x,y,z; // variables for result
- real_t epsilon = 0.01; // margin to allow for rounding errors
- real_t epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees
-
- if ( (Math::abs(elements[1][0]-elements[0][1])< epsilon)
- && (Math::abs(elements[2][0]-elements[0][2])< epsilon)
- && (Math::abs(elements[2][1]-elements[1][2])< epsilon)) {
- // singularity found
- // first check for identity matrix which must have +1 for all terms
- // in leading diagonaland zero in other terms
- if ((Math::abs(elements[1][0]+elements[0][1]) < epsilon2)
- && (Math::abs(elements[2][0]+elements[0][2]) < epsilon2)
- && (Math::abs(elements[2][1]+elements[1][2]) < epsilon2)
- && (Math::abs(elements[0][0]+elements[1][1]+elements[2][2]-3) < epsilon2)) {
+ if ((Math::abs(elements[1][0] - elements[0][1]) < epsilon) && (Math::abs(elements[2][0] - elements[0][2]) < epsilon) && (Math::abs(elements[2][1] - elements[1][2]) < epsilon)) {
+ // singularity found
+ // first check for identity matrix which must have +1 for all terms
+ // in leading diagonaland zero in other terms
+ if ((Math::abs(elements[1][0] + elements[0][1]) < epsilon2) && (Math::abs(elements[2][0] + elements[0][2]) < epsilon2) && (Math::abs(elements[2][1] + elements[1][2]) < epsilon2) && (Math::abs(elements[0][0] + elements[1][1] + elements[2][2] - 3) < epsilon2)) {
// this singularity is identity matrix so angle = 0
- r_axis=Vector3(0,1,0);
- r_angle=0;
+ r_axis = Vector3(0, 1, 0);
+ r_angle = 0;
return;
}
// otherwise this singularity is angle = 180
angle = Math_PI;
- real_t xx = (elements[0][0]+1)/2;
- real_t yy = (elements[1][1]+1)/2;
- real_t zz = (elements[2][2]+1)/2;
- real_t xy = (elements[1][0]+elements[0][1])/4;
- real_t xz = (elements[2][0]+elements[0][2])/4;
- real_t yz = (elements[2][1]+elements[1][2])/4;
+ real_t xx = (elements[0][0] + 1) / 2;
+ real_t yy = (elements[1][1] + 1) / 2;
+ real_t zz = (elements[2][2] + 1) / 2;
+ real_t xy = (elements[1][0] + elements[0][1]) / 4;
+ real_t xz = (elements[2][0] + elements[0][2]) / 4;
+ real_t yz = (elements[2][1] + elements[1][2]) / 4;
if ((xx > yy) && (xx > zz)) { // elements[0][0] is the largest diagonal term
- if (xx< epsilon) {
+ if (xx < epsilon) {
x = 0;
y = 0.7071;
z = 0.7071;
} else {
x = Math::sqrt(xx);
- y = xy/x;
- z = xz/x;
+ y = xy / x;
+ z = xz / x;
}
} else if (yy > zz) { // elements[1][1] is the largest diagonal term
- if (yy< epsilon) {
+ if (yy < epsilon) {
x = 0.7071;
y = 0;
z = 0.7071;
} else {
y = Math::sqrt(yy);
- x = xy/y;
- z = yz/y;
+ x = xy / y;
+ z = yz / y;
}
} else { // elements[2][2] is the largest diagonal term so base result on this
- if (zz< epsilon) {
+ if (zz < epsilon) {
x = 0.7071;
y = 0.7071;
z = 0;
} else {
z = Math::sqrt(zz);
- x = xz/z;
- y = yz/z;
+ x = xz / z;
+ y = yz / z;
}
}
- r_axis=Vector3(x,y,z);
- r_angle=angle;
+ r_axis = Vector3(x, y, z);
+ r_angle = angle;
return;
}
// as we have reached here there are no singularities so we can handle normally
- real_t s = Math::sqrt((elements[1][2] - elements[2][1])*(elements[1][2] - elements[2][1])
- +(elements[2][0] - elements[0][2])*(elements[2][0] - elements[0][2])
- +(elements[0][1] - elements[1][0])*(elements[0][1] - elements[1][0])); // s=|axis||sin(angle)|, used to normalise
+ real_t s = Math::sqrt((elements[1][2] - elements[2][1]) * (elements[1][2] - elements[2][1]) + (elements[2][0] - elements[0][2]) * (elements[2][0] - elements[0][2]) + (elements[0][1] - elements[1][0]) * (elements[0][1] - elements[1][0])); // s=|axis||sin(angle)|, used to normalise
- angle = Math::acos(( elements[0][0] + elements[1][1] + elements[2][2] - 1)/2);
+ angle = Math::acos((elements[0][0] + elements[1][1] + elements[2][2] - 1) / 2);
if (angle < 0) s = -s;
- x = (elements[2][1] - elements[1][2])/s;
- y = (elements[0][2] - elements[2][0])/s;
- z = (elements[1][0] - elements[0][1])/s;
+ x = (elements[2][1] - elements[1][2]) / s;
+ y = (elements[0][2] - elements[2][0]) / s;
+ z = (elements[1][0] - elements[0][1]) / s;
- r_axis=Vector3(x,y,z);
- r_angle=angle;
+ r_axis = Vector3(x, y, z);
+ r_angle = angle;
}
-Basis::Basis(const Vector3& p_euler) {
-
- set_euler( p_euler );
+Basis::Basis(const Vector3 &p_euler) {
+ set_euler(p_euler);
}
-Basis::Basis(const Quat& p_quat) {
+Basis::Basis(const Quat &p_quat) {
real_t d = p_quat.length_squared();
real_t s = 2.0 / d;
- real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s;
- real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs;
- real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs;
- real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs;
- set( 1.0 - (yy + zz), xy - wz, xz + wy,
- xy + wz, 1.0 - (xx + zz), yz - wx,
- xz - wy, yz + wx, 1.0 - (xx + yy)) ;
-
+ real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s;
+ real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs;
+ real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs;
+ real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs;
+ set(1.0 - (yy + zz), xy - wz, xz + wy,
+ xy + wz, 1.0 - (xx + zz), yz - wx,
+ xz - wy, yz + wx, 1.0 - (xx + yy));
}
-Basis::Basis(const Vector3& p_axis, real_t p_phi) {
+Basis::Basis(const Vector3 &p_axis, real_t p_phi) {
// Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
- Vector3 axis_sq(p_axis.x*p_axis.x,p_axis.y*p_axis.y,p_axis.z*p_axis.z);
-
- real_t cosine= Math::cos(p_phi);
- real_t sine= Math::sin(p_phi);
+ Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z);
- elements[0][0] = axis_sq.x + cosine * ( 1.0 - axis_sq.x );
- elements[0][1] = p_axis.x * p_axis.y * ( 1.0 - cosine ) - p_axis.z * sine;
- elements[0][2] = p_axis.z * p_axis.x * ( 1.0 - cosine ) + p_axis.y * sine;
+ real_t cosine = Math::cos(p_phi);
+ real_t sine = Math::sin(p_phi);
- elements[1][0] = p_axis.x * p_axis.y * ( 1.0 - cosine ) + p_axis.z * sine;
- elements[1][1] = axis_sq.y + cosine * ( 1.0 - axis_sq.y );
- elements[1][2] = p_axis.y * p_axis.z * ( 1.0 - cosine ) - p_axis.x * sine;
+ elements[0][0] = axis_sq.x + cosine * (1.0 - axis_sq.x);
+ elements[0][1] = p_axis.x * p_axis.y * (1.0 - cosine) - p_axis.z * sine;
+ elements[0][2] = p_axis.z * p_axis.x * (1.0 - cosine) + p_axis.y * sine;
- elements[2][0] = p_axis.z * p_axis.x * ( 1.0 - cosine ) - p_axis.y * sine;
- elements[2][1] = p_axis.y * p_axis.z * ( 1.0 - cosine ) + p_axis.x * sine;
- elements[2][2] = axis_sq.z + cosine * ( 1.0 - axis_sq.z );
+ elements[1][0] = p_axis.x * p_axis.y * (1.0 - cosine) + p_axis.z * sine;
+ elements[1][1] = axis_sq.y + cosine * (1.0 - axis_sq.y);
+ elements[1][2] = p_axis.y * p_axis.z * (1.0 - cosine) - p_axis.x * sine;
+ elements[2][0] = p_axis.z * p_axis.x * (1.0 - cosine) - p_axis.y * sine;
+ elements[2][1] = p_axis.y * p_axis.z * (1.0 - cosine) + p_axis.x * sine;
+ elements[2][2] = axis_sq.z + cosine * (1.0 - axis_sq.z);
}
-
diff --git a/core/math/matrix3.h b/core/math/matrix3.h
index abce1ee45d..0240bc8610 100644
--- a/core/math/matrix3.h
+++ b/core/math/matrix3.h
@@ -39,14 +39,13 @@
*/
class Basis {
public:
-
Vector3 elements[3];
- _FORCE_INLINE_ const Vector3& operator[](int axis) const {
+ _FORCE_INLINE_ const Vector3 &operator[](int axis) const {
return elements[axis];
}
- _FORCE_INLINE_ Vector3& operator[](int axis) {
+ _FORCE_INLINE_ Vector3 &operator[](int axis) {
return elements[axis];
}
@@ -59,57 +58,57 @@ public:
_FORCE_INLINE_ real_t determinant() const;
- void from_z(const Vector3& p_z);
+ void from_z(const Vector3 &p_z);
_FORCE_INLINE_ Vector3 get_axis(int p_axis) const {
// get actual basis axis (elements is transposed for performance)
- return Vector3( elements[0][p_axis], elements[1][p_axis], elements[2][p_axis] );
+ return Vector3(elements[0][p_axis], elements[1][p_axis], elements[2][p_axis]);
}
- _FORCE_INLINE_ void set_axis(int p_axis, const Vector3& p_value) {
+ _FORCE_INLINE_ void set_axis(int p_axis, const Vector3 &p_value) {
// get actual basis axis (elements is transposed for performance)
- elements[0][p_axis]=p_value.x;
- elements[1][p_axis]=p_value.y;
- elements[2][p_axis]=p_value.z;
+ elements[0][p_axis] = p_value.x;
+ elements[1][p_axis] = p_value.y;
+ elements[2][p_axis] = p_value.z;
}
- void rotate(const Vector3& p_axis, real_t p_phi);
- Basis rotated(const Vector3& p_axis, real_t p_phi) const;
+ void rotate(const Vector3 &p_axis, real_t p_phi);
+ Basis rotated(const Vector3 &p_axis, real_t p_phi) const;
- void rotate(const Vector3& p_euler);
- Basis rotated(const Vector3& p_euler) const;
+ void rotate(const Vector3 &p_euler);
+ Basis rotated(const Vector3 &p_euler) const;
Vector3 get_rotation() const;
- void scale( const Vector3& p_scale );
- Basis scaled( const Vector3& p_scale ) const;
+ void scale(const Vector3 &p_scale);
+ Basis scaled(const Vector3 &p_scale) const;
Vector3 get_scale() const;
Vector3 get_euler() const;
- void set_euler(const Vector3& p_euler);
+ void set_euler(const Vector3 &p_euler);
// transposed dot products
- _FORCE_INLINE_ real_t tdotx(const Vector3& v) const {
+ _FORCE_INLINE_ real_t tdotx(const Vector3 &v) const {
return elements[0][0] * v[0] + elements[1][0] * v[1] + elements[2][0] * v[2];
}
- _FORCE_INLINE_ real_t tdoty(const Vector3& v) const {
+ _FORCE_INLINE_ real_t tdoty(const Vector3 &v) const {
return elements[0][1] * v[0] + elements[1][1] * v[1] + elements[2][1] * v[2];
}
- _FORCE_INLINE_ real_t tdotz(const Vector3& v) const {
+ _FORCE_INLINE_ real_t tdotz(const Vector3 &v) const {
return elements[0][2] * v[0] + elements[1][2] * v[1] + elements[2][2] * v[2];
}
- bool isequal_approx(const Basis& a, const Basis& b) const;
+ bool isequal_approx(const Basis &a, const Basis &b) const;
- bool operator==(const Basis& p_matrix) const;
- bool operator!=(const Basis& p_matrix) const;
+ bool operator==(const Basis &p_matrix) const;
+ bool operator!=(const Basis &p_matrix) const;
- _FORCE_INLINE_ Vector3 xform(const Vector3& p_vector) const;
- _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vector) const;
- _FORCE_INLINE_ void operator*=(const Basis& p_matrix);
- _FORCE_INLINE_ Basis operator*(const Basis& p_matrix) const;
- _FORCE_INLINE_ void operator+=(const Basis& p_matrix);
- _FORCE_INLINE_ Basis operator+(const Basis& p_matrix) const;
- _FORCE_INLINE_ void operator-=(const Basis& p_matrix);
- _FORCE_INLINE_ Basis operator-(const Basis& p_matrix) const;
+ _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vector) const;
+ _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vector) const;
+ _FORCE_INLINE_ void operator*=(const Basis &p_matrix);
+ _FORCE_INLINE_ Basis operator*(const Basis &p_matrix) const;
+ _FORCE_INLINE_ void operator+=(const Basis &p_matrix);
+ _FORCE_INLINE_ Basis operator+(const Basis &p_matrix) const;
+ _FORCE_INLINE_ void operator-=(const Basis &p_matrix);
+ _FORCE_INLINE_ Basis operator-(const Basis &p_matrix) const;
_FORCE_INLINE_ void operator*=(real_t p_val);
_FORCE_INLINE_ Basis operator*(real_t p_val) const;
@@ -121,40 +120,39 @@ public:
operator String() const;
- void get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const;
+ void get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const;
/* create / set */
-
_FORCE_INLINE_ void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz) {
- elements[0][0]=xx;
- elements[0][1]=xy;
- elements[0][2]=xz;
- elements[1][0]=yx;
- elements[1][1]=yy;
- elements[1][2]=yz;
- elements[2][0]=zx;
- elements[2][1]=zy;
- elements[2][2]=zz;
+ elements[0][0] = xx;
+ elements[0][1] = xy;
+ elements[0][2] = xz;
+ elements[1][0] = yx;
+ elements[1][1] = yy;
+ elements[1][2] = yz;
+ elements[2][0] = zx;
+ elements[2][1] = zy;
+ elements[2][2] = zz;
}
_FORCE_INLINE_ Vector3 get_column(int i) const {
- return Vector3(elements[0][i],elements[1][i],elements[2][i]);
+ return Vector3(elements[0][i], elements[1][i], elements[2][i]);
}
_FORCE_INLINE_ Vector3 get_row(int i) const {
- return Vector3(elements[i][0],elements[i][1],elements[i][2]);
+ return Vector3(elements[i][0], elements[i][1], elements[i][2]);
}
_FORCE_INLINE_ Vector3 get_main_diagonal() const {
- return Vector3(elements[0][0],elements[1][1],elements[2][2]);
+ return Vector3(elements[0][0], elements[1][1], elements[2][2]);
}
- _FORCE_INLINE_ void set_row(int i, const Vector3& p_row) {
- elements[i][0]=p_row.x;
- elements[i][1]=p_row.y;
- elements[i][2]=p_row.z;
+ _FORCE_INLINE_ void set_row(int i, const Vector3 &p_row) {
+ elements[i][0] = p_row.x;
+ elements[i][1] = p_row.y;
+ elements[i][2] = p_row.z;
}
_FORCE_INLINE_ void set_zero() {
@@ -163,18 +161,17 @@ public:
elements[2].zero();
}
- _FORCE_INLINE_ Basis transpose_xform(const Basis& m) const
- {
+ _FORCE_INLINE_ Basis transpose_xform(const Basis &m) const {
return Basis(
- elements[0].x * m[0].x + elements[1].x * m[1].x + elements[2].x * m[2].x,
- elements[0].x * m[0].y + elements[1].x * m[1].y + elements[2].x * m[2].y,
- elements[0].x * m[0].z + elements[1].x * m[1].z + elements[2].x * m[2].z,
- elements[0].y * m[0].x + elements[1].y * m[1].x + elements[2].y * m[2].x,
- elements[0].y * m[0].y + elements[1].y * m[1].y + elements[2].y * m[2].y,
- elements[0].y * m[0].z + elements[1].y * m[1].z + elements[2].y * m[2].z,
- elements[0].z * m[0].x + elements[1].z * m[1].x + elements[2].z * m[2].x,
- elements[0].z * m[0].y + elements[1].z * m[1].y + elements[2].z * m[2].y,
- elements[0].z * m[0].z + elements[1].z * m[1].z + elements[2].z * m[2].z);
+ elements[0].x * m[0].x + elements[1].x * m[1].x + elements[2].x * m[2].x,
+ elements[0].x * m[0].y + elements[1].x * m[1].y + elements[2].x * m[2].y,
+ elements[0].x * m[0].z + elements[1].x * m[1].z + elements[2].x * m[2].z,
+ elements[0].y * m[0].x + elements[1].y * m[1].x + elements[2].y * m[2].x,
+ elements[0].y * m[0].y + elements[1].y * m[1].y + elements[2].y * m[2].y,
+ elements[0].y * m[0].z + elements[1].y * m[1].z + elements[2].y * m[2].z,
+ elements[0].z * m[0].x + elements[1].z * m[1].x + elements[2].z * m[2].x,
+ elements[0].z * m[0].y + elements[1].z * m[1].y + elements[2].z * m[2].y,
+ elements[0].z * m[0].z + elements[1].z * m[1].z + elements[2].z * m[2].z);
}
Basis(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz) {
@@ -189,75 +186,69 @@ public:
operator Quat() const;
- Basis(const Quat& p_quat); // euler
- Basis(const Vector3& p_euler); // euler
- Basis(const Vector3& p_axis, real_t p_phi);
+ Basis(const Quat &p_quat); // euler
+ Basis(const Vector3 &p_euler); // euler
+ Basis(const Vector3 &p_axis, real_t p_phi);
- _FORCE_INLINE_ Basis(const Vector3& row0, const Vector3& row1, const Vector3& row2)
- {
- elements[0]=row0;
- elements[1]=row1;
- elements[2]=row2;
+ _FORCE_INLINE_ Basis(const Vector3 &row0, const Vector3 &row1, const Vector3 &row2) {
+ elements[0] = row0;
+ elements[1] = row1;
+ elements[2] = row2;
}
_FORCE_INLINE_ Basis() {
- elements[0][0]=1;
- elements[0][1]=0;
- elements[0][2]=0;
- elements[1][0]=0;
- elements[1][1]=1;
- elements[1][2]=0;
- elements[2][0]=0;
- elements[2][1]=0;
- elements[2][2]=1;
+ elements[0][0] = 1;
+ elements[0][1] = 0;
+ elements[0][2] = 0;
+ elements[1][0] = 0;
+ elements[1][1] = 1;
+ elements[1][2] = 0;
+ elements[2][0] = 0;
+ elements[2][1] = 0;
+ elements[2][2] = 1;
}
-
-
};
-_FORCE_INLINE_ void Basis::operator*=(const Basis& p_matrix) {
+_FORCE_INLINE_ void Basis::operator*=(const Basis &p_matrix) {
set(
- p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]),
- p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]),
- p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2]));
-
+ p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]),
+ p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]),
+ p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2]));
}
-_FORCE_INLINE_ Basis Basis::operator*(const Basis& p_matrix) const {
+_FORCE_INLINE_ Basis Basis::operator*(const Basis &p_matrix) const {
return Basis(
- p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]),
- p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]),
- p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2]) );
-
+ p_matrix.tdotx(elements[0]), p_matrix.tdoty(elements[0]), p_matrix.tdotz(elements[0]),
+ p_matrix.tdotx(elements[1]), p_matrix.tdoty(elements[1]), p_matrix.tdotz(elements[1]),
+ p_matrix.tdotx(elements[2]), p_matrix.tdoty(elements[2]), p_matrix.tdotz(elements[2]));
}
-
-_FORCE_INLINE_ void Basis::operator+=(const Basis& p_matrix) {
+_FORCE_INLINE_ void Basis::operator+=(const Basis &p_matrix) {
elements[0] += p_matrix.elements[0];
elements[1] += p_matrix.elements[1];
elements[2] += p_matrix.elements[2];
}
-_FORCE_INLINE_ Basis Basis::operator+(const Basis& p_matrix) const {
-
+_FORCE_INLINE_ Basis Basis::operator+(const Basis &p_matrix) const {
+
Basis ret(*this);
ret += p_matrix;
return ret;
}
-_FORCE_INLINE_ void Basis::operator-=(const Basis& p_matrix) {
+_FORCE_INLINE_ void Basis::operator-=(const Basis &p_matrix) {
elements[0] -= p_matrix.elements[0];
elements[1] -= p_matrix.elements[1];
elements[2] -= p_matrix.elements[2];
}
-_FORCE_INLINE_ Basis Basis::operator-(const Basis& p_matrix) const {
-
+_FORCE_INLINE_ Basis Basis::operator-(const Basis &p_matrix) const {
+
Basis ret(*this);
ret -= p_matrix;
return ret;
@@ -265,40 +256,38 @@ _FORCE_INLINE_ Basis Basis::operator-(const Basis& p_matrix) const {
_FORCE_INLINE_ void Basis::operator*=(real_t p_val) {
- elements[0]*=p_val;
- elements[1]*=p_val;
- elements[2]*=p_val;
+ elements[0] *= p_val;
+ elements[1] *= p_val;
+ elements[2] *= p_val;
}
_FORCE_INLINE_ Basis Basis::operator*(real_t p_val) const {
- Basis ret(*this);
- ret *= p_val;
- return ret;
+ Basis ret(*this);
+ ret *= p_val;
+ return ret;
}
-Vector3 Basis::xform(const Vector3& p_vector) const {
+Vector3 Basis::xform(const Vector3 &p_vector) const {
return Vector3(
- elements[0].dot(p_vector),
- elements[1].dot(p_vector),
- elements[2].dot(p_vector)
- );
+ elements[0].dot(p_vector),
+ elements[1].dot(p_vector),
+ elements[2].dot(p_vector));
}
-Vector3 Basis::xform_inv(const Vector3& p_vector) const {
+Vector3 Basis::xform_inv(const Vector3 &p_vector) const {
return Vector3(
- (elements[0][0]*p_vector.x ) + ( elements[1][0]*p_vector.y ) + ( elements[2][0]*p_vector.z ),
- (elements[0][1]*p_vector.x ) + ( elements[1][1]*p_vector.y ) + ( elements[2][1]*p_vector.z ),
- (elements[0][2]*p_vector.x ) + ( elements[1][2]*p_vector.y ) + ( elements[2][2]*p_vector.z )
- );
+ (elements[0][0] * p_vector.x) + (elements[1][0] * p_vector.y) + (elements[2][0] * p_vector.z),
+ (elements[0][1] * p_vector.x) + (elements[1][1] * p_vector.y) + (elements[2][1] * p_vector.z),
+ (elements[0][2] * p_vector.x) + (elements[1][2] * p_vector.y) + (elements[2][2] * p_vector.z));
}
real_t Basis::determinant() const {
- return elements[0][0]*(elements[1][1]*elements[2][2] - elements[2][1]*elements[1][2]) -
- elements[1][0]*(elements[0][1]*elements[2][2] - elements[2][1]*elements[0][2]) +
- elements[2][0]*(elements[0][1]*elements[1][2] - elements[1][1]*elements[0][2]);
+ return elements[0][0] * (elements[1][1] * elements[2][2] - elements[2][1] * elements[1][2]) -
+ elements[1][0] * (elements[0][1] * elements[2][2] - elements[2][1] * elements[0][2]) +
+ elements[2][0] * (elements[0][1] * elements[1][2] - elements[1][1] * elements[0][2]);
}
#endif
diff --git a/core/math/octree.h b/core/math/octree.h
index e566df6a4f..06c5791b11 100644
--- a/core/math/octree.h
+++ b/core/math/octree.h
@@ -29,12 +29,12 @@
#ifndef OCTREE_H
#define OCTREE_H
-#include "vector3.h"
-#include "rect3.h"
#include "list.h"
-#include "variant.h"
#include "map.h"
#include "print_string.h"
+#include "rect3.h"
+#include "variant.h"
+#include "vector3.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -45,18 +45,17 @@ typedef uint32_t OctreeElementID;
#define OCTREE_ELEMENT_INVALID_ID 0
#define OCTREE_SIZE_LIMIT 1e15
-template<class T,bool use_pairs=false,class AL=DefaultAllocator>
+template <class T, bool use_pairs = false, class AL = DefaultAllocator>
class Octree {
public:
-
- typedef void* (*PairCallback)(void*,OctreeElementID, T*,int,OctreeElementID, T*,int);
- typedef void (*UnpairCallback)(void*,OctreeElementID, T*,int,OctreeElementID, T*,int,void*);
+ typedef void *(*PairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int);
+ typedef void (*UnpairCallback)(void *, OctreeElementID, T *, int, OctreeElementID, T *, int, void *);
private:
enum {
- NEG=0,
- POS=1,
+ NEG = 0,
+ POS = 1,
};
enum {
@@ -70,7 +69,6 @@ private:
OCTANT_PX_PY_PZ
};
-
struct PairKey {
union {
@@ -81,21 +79,21 @@ private:
uint64_t key;
};
- _FORCE_INLINE_ bool operator<(const PairKey& p_pair) const {
+ _FORCE_INLINE_ bool operator<(const PairKey &p_pair) const {
- return key<p_pair.key;
+ return key < p_pair.key;
}
- _FORCE_INLINE_ PairKey( OctreeElementID p_A, OctreeElementID p_B) {
+ _FORCE_INLINE_ PairKey(OctreeElementID p_A, OctreeElementID p_B) {
- if (p_A<p_B) {
+ if (p_A < p_B) {
- A=p_A;
- B=p_B;
+ A = p_A;
+ B = p_B;
} else {
- B=p_A;
- A=p_B;
+ B = p_A;
+ A = p_B;
}
}
@@ -116,16 +114,16 @@ private:
int children_count; // cache for amount of childrens (fast check for removal)
int parent_index; // cache for parent index (fast check for removal)
- List<Element*,AL> pairable_elements;
- List<Element*,AL> elements;
+ List<Element *, AL> pairable_elements;
+ List<Element *, AL> elements;
Octant() {
- children_count=0;
- parent_index=-1;
- last_pass=0;
- parent=NULL;
- for (int i=0;i<8;i++)
- children[i]=NULL;
+ children_count = 0;
+ parent_index = -1;
+ last_pass = 0;
+ parent = NULL;
+ for (int i = 0; i < 8; i++)
+ children[i] = NULL;
}
~Octant() {
@@ -137,7 +135,6 @@ private:
}
};
-
struct PairData;
struct Element {
@@ -157,28 +154,36 @@ private:
Rect3 aabb;
Rect3 container_aabb;
- List<PairData*,AL> pair_list;
+ List<PairData *, AL> pair_list;
struct OctantOwner {
Octant *octant;
- typename List<Element*,AL>::Element *E;
+ typename List<Element *, AL>::Element *E;
}; // an element can be in max 8 octants
- List<OctantOwner,AL> octant_owners;
-
-
- Element() { last_pass=0; _id=0; pairable=false; subindex=0; userdata=0; octree=0; pairable_mask=0; pairable_type=0; common_parent=NULL; }
+ List<OctantOwner, AL> octant_owners;
+
+ Element() {
+ last_pass = 0;
+ _id = 0;
+ pairable = false;
+ subindex = 0;
+ userdata = 0;
+ octree = 0;
+ pairable_mask = 0;
+ pairable_type = 0;
+ common_parent = NULL;
+ }
};
-
struct PairData {
int refcount;
bool intersect;
- Element *A,*B;
+ Element *A, *B;
void *ud;
- typename List<PairData*,AL>::Element *eA,*eB;
+ typename List<PairData *, AL>::Element *eA, *eB;
};
typedef Map<OctreeElementID, Element, Comparator<OctreeElementID>, AL> ElementMap;
@@ -199,58 +204,52 @@ private:
int octant_count;
int pair_count;
-
-
_FORCE_INLINE_ void _pair_check(PairData *p_pair) {
- bool intersect=p_pair->A->aabb.intersects_inclusive( p_pair->B->aabb );
+ bool intersect = p_pair->A->aabb.intersects_inclusive(p_pair->B->aabb);
- if (intersect!=p_pair->intersect) {
+ if (intersect != p_pair->intersect) {
if (intersect) {
if (pair_callback) {
- p_pair->ud=pair_callback(pair_callback_userdata,p_pair->A->_id, p_pair->A->userdata,p_pair->A->subindex,p_pair->B->_id, p_pair->B->userdata,p_pair->B->subindex);
-
+ p_pair->ud = pair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex);
}
pair_count++;
} else {
-
if (unpair_callback) {
- unpair_callback(pair_callback_userdata,p_pair->A->_id, p_pair->A->userdata,p_pair->A->subindex,p_pair->B->_id, p_pair->B->userdata,p_pair->B->subindex,p_pair->ud);
+ unpair_callback(pair_callback_userdata, p_pair->A->_id, p_pair->A->userdata, p_pair->A->subindex, p_pair->B->_id, p_pair->B->userdata, p_pair->B->subindex, p_pair->ud);
}
pair_count--;
-
}
- p_pair->intersect=intersect;
-
+ p_pair->intersect = intersect;
}
}
- _FORCE_INLINE_ void _pair_reference(Element* p_A,Element* p_B) {
+ _FORCE_INLINE_ void _pair_reference(Element *p_A, Element *p_B) {
- if (p_A==p_B || (p_A->userdata==p_B->userdata && p_A->userdata))
+ if (p_A == p_B || (p_A->userdata == p_B->userdata && p_A->userdata))
return;
- if ( !(p_A->pairable_type&p_B->pairable_mask) &&
- !(p_B->pairable_type&p_A->pairable_mask) )
+ if (!(p_A->pairable_type & p_B->pairable_mask) &&
+ !(p_B->pairable_type & p_A->pairable_mask))
return; // none can pair with none
PairKey key(p_A->_id, p_B->_id);
- typename PairMap::Element *E=pair_map.find(key);
+ typename PairMap::Element *E = pair_map.find(key);
if (!E) {
PairData pdata;
- pdata.refcount=1;
- pdata.A=p_A;
- pdata.B=p_B;
- pdata.intersect=false;
- E=pair_map.insert(key,pdata);
- E->get().eA=p_A->pair_list.push_back(&E->get());
- E->get().eB=p_B->pair_list.push_back(&E->get());
+ pdata.refcount = 1;
+ pdata.A = p_A;
+ pdata.B = p_B;
+ pdata.intersect = false;
+ E = pair_map.insert(key, pdata);
+ E->get().eA = p_A->pair_list.push_back(&E->get());
+ E->get().eB = p_B->pair_list.push_back(&E->get());
/*
if (pair_callback)
@@ -260,189 +259,178 @@ private:
E->get().refcount++;
}
-
}
- _FORCE_INLINE_ void _pair_unreference(Element* p_A,Element* p_B) {
+ _FORCE_INLINE_ void _pair_unreference(Element *p_A, Element *p_B) {
- if (p_A==p_B)
+ if (p_A == p_B)
return;
PairKey key(p_A->_id, p_B->_id);
- typename PairMap::Element *E=pair_map.find(key);
+ typename PairMap::Element *E = pair_map.find(key);
if (!E) {
return; // no pair
}
E->get().refcount--;
-
- if (E->get().refcount==0) {
+ if (E->get().refcount == 0) {
// bye pair
if (E->get().intersect) {
if (unpair_callback) {
- unpair_callback(pair_callback_userdata,p_A->_id, p_A->userdata,p_A->subindex,p_B->_id, p_B->userdata,p_B->subindex,E->get().ud);
+ unpair_callback(pair_callback_userdata, p_A->_id, p_A->userdata, p_A->subindex, p_B->_id, p_B->userdata, p_B->subindex, E->get().ud);
}
pair_count--;
}
- if (p_A==E->get().B) {
+ if (p_A == E->get().B) {
//may be reaching inverted
- SWAP(p_A,p_B);
+ SWAP(p_A, p_B);
}
- p_A->pair_list.erase( E->get().eA );
- p_B->pair_list.erase( E->get().eB );
+ p_A->pair_list.erase(E->get().eA);
+ p_B->pair_list.erase(E->get().eB);
pair_map.erase(E);
}
-
}
_FORCE_INLINE_ void _element_check_pairs(Element *p_element) {
- typename List<PairData*,AL>::Element *E=p_element->pair_list.front();
- while(E) {
+ typename List<PairData *, AL>::Element *E = p_element->pair_list.front();
+ while (E) {
- _pair_check( E->get() );
- E=E->next();
+ _pair_check(E->get());
+ E = E->next();
}
-
}
_FORCE_INLINE_ void _optimize() {
+ while (root && root->children_count < 2 && !root->elements.size() && !(use_pairs && root->pairable_elements.size())) {
- while(root && root->children_count<2 && !root->elements.size() && !(use_pairs && root->pairable_elements.size())) {
-
-
- Octant *new_root=NULL;
- if (root->children_count==1) {
+ Octant *new_root = NULL;
+ if (root->children_count == 1) {
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (root->children[i]) {
- new_root=root->children[i];
- root->children[i]=NULL;
+ new_root = root->children[i];
+ root->children[i] = NULL;
break;
}
}
ERR_FAIL_COND(!new_root);
- new_root->parent=NULL;
- new_root->parent_index=-1;
+ new_root->parent = NULL;
+ new_root->parent_index = -1;
}
- memdelete_allocator<Octant,AL>( root );
+ memdelete_allocator<Octant, AL>(root);
octant_count--;
- root=new_root;
-
+ root = new_root;
}
}
-
- void _insert_element(Element *p_element,Octant *p_octant);
- void _ensure_valid_root(const Rect3& p_aabb);
- bool _remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit=NULL);
+ void _insert_element(Element *p_element, Octant *p_octant);
+ void _ensure_valid_root(const Rect3 &p_aabb);
+ bool _remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit = NULL);
void _remove_element(Element *p_element);
- void _pair_element(Element *p_element,Octant *p_octant);
- void _unpair_element(Element *p_element,Octant *p_octant);
-
+ void _pair_element(Element *p_element, Octant *p_octant);
+ void _unpair_element(Element *p_element, Octant *p_octant);
struct _CullConvexData {
- const Plane* planes;
+ const Plane *planes;
int plane_count;
- T** result_array;
+ T **result_array;
int *result_idx;
int result_max;
uint32_t mask;
};
- void _cull_convex(Octant *p_octant,_CullConvexData *p_cull);
- void _cull_AABB(Octant *p_octant,const Rect3& p_aabb, T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask);
- void _cull_segment(Octant *p_octant,const Vector3& p_from, const Vector3& p_to,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask);
- void _cull_point(Octant *p_octant,const Vector3& p_point,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask);
+ void _cull_convex(Octant *p_octant, _CullConvexData *p_cull);
+ void _cull_AABB(Octant *p_octant, const Rect3 &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
+ void _cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
+ void _cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask);
void _remove_tree(Octant *p_octant) {
if (!p_octant)
return;
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i])
_remove_tree(p_octant->children[i]);
}
- memdelete_allocator<Octant,AL>(p_octant);
+ memdelete_allocator<Octant, AL>(p_octant);
}
-public:
- OctreeElementID create(T* p_userdata, const Rect3& p_aabb=Rect3(), int p_subindex=0, bool p_pairable=false,uint32_t p_pairable_type=0,uint32_t pairable_mask=1);
- void move(OctreeElementID p_id, const Rect3& p_aabb);
- void set_pairable(OctreeElementID p_id,bool p_pairable=false,uint32_t p_pairable_type=0,uint32_t pairable_mask=1);
+public:
+ OctreeElementID create(T *p_userdata, const Rect3 &p_aabb = Rect3(), int p_subindex = 0, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1);
+ void move(OctreeElementID p_id, const Rect3 &p_aabb);
+ void set_pairable(OctreeElementID p_id, bool p_pairable = false, uint32_t p_pairable_type = 0, uint32_t pairable_mask = 1);
void erase(OctreeElementID p_id);
bool is_pairable(OctreeElementID p_id) const;
T *get(OctreeElementID p_id) const;
int get_subindex(OctreeElementID p_id) const;
- int cull_convex(const Vector<Plane>& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask=0xFFFFFFFF);
- int cull_AABB(const Rect3& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF);
- int cull_segment(const Vector3& p_from, const Vector3& p_to,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF);
+ int cull_convex(const Vector<Plane> &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask = 0xFFFFFFFF);
+ int cull_AABB(const Rect3 &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF);
+ int cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF);
- int cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array=NULL,uint32_t p_mask=0xFFFFFFFF);
+ int cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array = NULL, uint32_t p_mask = 0xFFFFFFFF);
- void set_pair_callback( PairCallback p_callback, void *p_userdata );
- void set_unpair_callback( UnpairCallback p_callback, void *p_userdata );
+ void set_pair_callback(PairCallback p_callback, void *p_userdata);
+ void set_unpair_callback(UnpairCallback p_callback, void *p_userdata);
int get_octant_count() const { return octant_count; }
int get_pair_count() const { return pair_count; }
- Octree(real_t p_unit_size=1.0);
+ Octree(real_t p_unit_size = 1.0);
~Octree() { _remove_tree(root); }
};
-
/* PRIVATE FUNCTIONS */
-template<class T,bool use_pairs,class AL>
-T *Octree<T,use_pairs,AL>::get(OctreeElementID p_id) const {
+template <class T, bool use_pairs, class AL>
+T *Octree<T, use_pairs, AL>::get(OctreeElementID p_id) const {
const typename ElementMap::Element *E = element_map.find(p_id);
- ERR_FAIL_COND_V(!E,NULL);
+ ERR_FAIL_COND_V(!E, NULL);
return E->get().userdata;
}
-
-template<class T,bool use_pairs,class AL>
-bool Octree<T,use_pairs,AL>::is_pairable(OctreeElementID p_id) const {
+template <class T, bool use_pairs, class AL>
+bool Octree<T, use_pairs, AL>::is_pairable(OctreeElementID p_id) const {
const typename ElementMap::Element *E = element_map.find(p_id);
- ERR_FAIL_COND_V(!E,false);
+ ERR_FAIL_COND_V(!E, false);
return E->get().pairable;
}
-template<class T,bool use_pairs,class AL>
-int Octree<T,use_pairs,AL>::get_subindex(OctreeElementID p_id) const {
+template <class T, bool use_pairs, class AL>
+int Octree<T, use_pairs, AL>::get_subindex(OctreeElementID p_id) const {
const typename ElementMap::Element *E = element_map.find(p_id);
- ERR_FAIL_COND_V(!E,-1);
+ ERR_FAIL_COND_V(!E, -1);
return E->get().subindex;
}
#define OCTREE_DIVISOR 4
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_insert_element(Element *p_element,Octant *p_octant) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_insert_element(Element *p_element, Octant *p_octant) {
real_t element_size = p_element->aabb.get_longest_axis_size() * 1.01; // avoid precision issues
- if (p_octant->aabb.size.x/OCTREE_DIVISOR < element_size) {
- //if (p_octant->aabb.size.x*0.5 < element_size) {
+ if (p_octant->aabb.size.x / OCTREE_DIVISOR < element_size) {
+ //if (p_octant->aabb.size.x*0.5 < element_size) {
/* at smallest possible size for the element */
typename Element::OctantOwner owner;
- owner.octant=p_octant;
+ owner.octant = p_octant;
if (use_pairs && p_element->pairable) {
@@ -454,426 +442,409 @@ void Octree<T,use_pairs,AL>::_insert_element(Element *p_element,Octant *p_octant
owner.E = p_octant->elements.back();
}
- p_element->octant_owners.push_back( owner );
+ p_element->octant_owners.push_back(owner);
- if (p_element->common_parent==NULL) {
- p_element->common_parent=p_octant;
- p_element->container_aabb=p_octant->aabb;
+ if (p_element->common_parent == NULL) {
+ p_element->common_parent = p_octant;
+ p_element->container_aabb = p_octant->aabb;
} else {
p_element->container_aabb.merge_with(p_octant->aabb);
}
-
- if (use_pairs && p_octant->children_count>0) {
+ if (use_pairs && p_octant->children_count > 0) {
pass++; //elements below this only get ONE reference added
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i]) {
- _pair_element(p_element,p_octant->children[i]);
+ _pair_element(p_element, p_octant->children[i]);
}
}
}
} else {
/* not big enough, send it to subitems */
- int splits=0;
- bool candidate=p_element->common_parent==NULL;
+ int splits = 0;
+ bool candidate = p_element->common_parent == NULL;
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i]) {
/* element exists, go straight to it */
- if (p_octant->children[i]->aabb.intersects_inclusive( p_element->aabb ) ) {
- _insert_element( p_element, p_octant->children[i] );
+ if (p_octant->children[i]->aabb.intersects_inclusive(p_element->aabb)) {
+ _insert_element(p_element, p_octant->children[i]);
splits++;
}
} else {
/* check againt AABB where child should be */
- Rect3 aabb=p_octant->aabb;
- aabb.size*=0.5;
+ Rect3 aabb = p_octant->aabb;
+ aabb.size *= 0.5;
- if (i&1)
- aabb.pos.x+=aabb.size.x;
- if (i&2)
- aabb.pos.y+=aabb.size.y;
- if (i&4)
- aabb.pos.z+=aabb.size.z;
+ if (i & 1)
+ aabb.pos.x += aabb.size.x;
+ if (i & 2)
+ aabb.pos.y += aabb.size.y;
+ if (i & 4)
+ aabb.pos.z += aabb.size.z;
- if (aabb.intersects_inclusive( p_element->aabb) ) {
+ if (aabb.intersects_inclusive(p_element->aabb)) {
/* if actually intersects, create the child */
- Octant *child = memnew_allocator( Octant, AL );
- p_octant->children[i]=child;
- child->parent=p_octant;
- child->parent_index=i;
+ Octant *child = memnew_allocator(Octant, AL);
+ p_octant->children[i] = child;
+ child->parent = p_octant;
+ child->parent_index = i;
- child->aabb=aabb;
+ child->aabb = aabb;
p_octant->children_count++;
- _insert_element( p_element, child );
+ _insert_element(p_element, child);
octant_count++;
splits++;
-
}
}
-
}
- if (candidate && splits>1) {
+ if (candidate && splits > 1) {
- p_element->common_parent=p_octant;
+ p_element->common_parent = p_octant;
}
-
}
if (use_pairs) {
- typename List<Element*,AL>::Element *E=p_octant->pairable_elements.front();
+ typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
- while(E) {
- _pair_reference( p_element,E->get() );
- E=E->next();
+ while (E) {
+ _pair_reference(p_element, E->get());
+ E = E->next();
}
if (p_element->pairable) {
// and always test non-pairable if element is pairable
- E=p_octant->elements.front();
- while(E) {
- _pair_reference( p_element,E->get() );
- E=E->next();
+ E = p_octant->elements.front();
+ while (E) {
+ _pair_reference(p_element, E->get());
+ E = E->next();
}
}
}
-
-
}
-
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_ensure_valid_root(const Rect3& p_aabb) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_ensure_valid_root(const Rect3 &p_aabb) {
if (!root) {
// octre is empty
- Rect3 base( Vector3(), Vector3(1.0,1.0,1.0) * unit_size);
+ Rect3 base(Vector3(), Vector3(1.0, 1.0, 1.0) * unit_size);
- while ( !base.encloses(p_aabb) ) {
+ while (!base.encloses(p_aabb)) {
- if ( ABS(base.pos.x+base.size.x) <= ABS(base.pos.x) ) {
+ if (ABS(base.pos.x + base.size.x) <= ABS(base.pos.x)) {
/* grow towards positive */
- base.size*=2.0;
+ base.size *= 2.0;
} else {
- base.pos-=base.size;
- base.size*=2.0;
+ base.pos -= base.size;
+ base.size *= 2.0;
}
}
- root = memnew_allocator( Octant, AL );
+ root = memnew_allocator(Octant, AL);
- root->parent=NULL;
- root->parent_index=-1;
- root->aabb=base;
+ root->parent = NULL;
+ root->parent_index = -1;
+ root->aabb = base;
octant_count++;
-
} else {
- Rect3 base=root->aabb;
+ Rect3 base = root->aabb;
- while( !base.encloses( p_aabb ) ) {
+ while (!base.encloses(p_aabb)) {
if (base.size.x > OCTREE_SIZE_LIMIT) {
ERR_EXPLAIN("Octree upper size limit reeached, does the AABB supplied contain NAN?");
ERR_FAIL();
}
- Octant * gp = memnew_allocator( Octant, AL );
+ Octant *gp = memnew_allocator(Octant, AL);
octant_count++;
- root->parent=gp;
+ root->parent = gp;
- if ( ABS(base.pos.x+base.size.x) <= ABS(base.pos.x) ) {
+ if (ABS(base.pos.x + base.size.x) <= ABS(base.pos.x)) {
/* grow towards positive */
- base.size*=2.0;
- gp->aabb=base;
- gp->children[0]=root;
- root->parent_index=0;
+ base.size *= 2.0;
+ gp->aabb = base;
+ gp->children[0] = root;
+ root->parent_index = 0;
} else {
- base.pos-=base.size;
- base.size*=2.0;
- gp->aabb=base;
- gp->children[(1<<0)|(1<<1)|(1<<2)]=root; // add at all-positive
- root->parent_index=(1<<0)|(1<<1)|(1<<2);
+ base.pos -= base.size;
+ base.size *= 2.0;
+ gp->aabb = base;
+ gp->children[(1 << 0) | (1 << 1) | (1 << 2)] = root; // add at all-positive
+ root->parent_index = (1 << 0) | (1 << 1) | (1 << 2);
}
- gp->children_count=1;
- root=gp;
+ gp->children_count = 1;
+ root = gp;
}
}
}
-template<class T,bool use_pairs,class AL>
-bool Octree<T,use_pairs,AL>::_remove_element_from_octant(Element *p_element,Octant *p_octant,Octant *p_limit) {
+template <class T, bool use_pairs, class AL>
+bool Octree<T, use_pairs, AL>::_remove_element_from_octant(Element *p_element, Octant *p_octant, Octant *p_limit) {
- bool octant_removed=false;
+ bool octant_removed = false;
- while(true) {
+ while (true) {
// check all exit conditions
- if (p_octant==p_limit) // reached limit, nothing to erase, exit
+ if (p_octant == p_limit) // reached limit, nothing to erase, exit
return octant_removed;
- bool unpaired=false;
+ bool unpaired = false;
- if (use_pairs && p_octant->last_pass!=pass) {
+ if (use_pairs && p_octant->last_pass != pass) {
// check wether we should unpair stuff
// always test pairable
- typename List<Element*,AL>::Element *E=p_octant->pairable_elements.front();
- while(E) {
- _pair_unreference( p_element,E->get() );
- E=E->next();
+ typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
+ while (E) {
+ _pair_unreference(p_element, E->get());
+ E = E->next();
}
if (p_element->pairable) {
// and always test non-pairable if element is pairable
- E=p_octant->elements.front();
- while(E) {
- _pair_unreference( p_element,E->get() );
- E=E->next();
+ E = p_octant->elements.front();
+ while (E) {
+ _pair_unreference(p_element, E->get());
+ E = E->next();
}
}
- p_octant->last_pass=pass;
- unpaired=true;
+ p_octant->last_pass = pass;
+ unpaired = true;
}
- bool removed=false;
+ bool removed = false;
- Octant *parent=p_octant->parent;
+ Octant *parent = p_octant->parent;
- if (p_octant->children_count==0 && p_octant->elements.empty() && p_octant->pairable_elements.empty()) {
+ if (p_octant->children_count == 0 && p_octant->elements.empty() && p_octant->pairable_elements.empty()) {
// erase octant
- if (p_octant==root) { // won't have a parent, just erase
+ if (p_octant == root) { // won't have a parent, just erase
- root=NULL;
+ root = NULL;
} else {
- ERR_FAIL_INDEX_V(p_octant->parent_index,8,octant_removed);
+ ERR_FAIL_INDEX_V(p_octant->parent_index, 8, octant_removed);
- parent->children[ p_octant->parent_index ]=NULL;
+ parent->children[p_octant->parent_index] = NULL;
parent->children_count--;
}
- memdelete_allocator<Octant,AL>(p_octant);
+ memdelete_allocator<Octant, AL>(p_octant);
octant_count--;
- removed=true;
- octant_removed=true;
+ removed = true;
+ octant_removed = true;
}
if (!removed && !unpaired)
return octant_removed; // no reason to keep going up anymore! was already visited and was not removed
- p_octant=parent;
-
+ p_octant = parent;
}
return octant_removed;
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_unpair_element(Element *p_element,Octant *p_octant) {
-
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_unpair_element(Element *p_element, Octant *p_octant) {
// always test pairable
- typename List<Element*,AL>::Element *E=p_octant->pairable_elements.front();
- while(E) {
- if (E->get()->last_pass!=pass) { // only remove ONE reference
- _pair_unreference( p_element,E->get() );
- E->get()->last_pass=pass;
+ typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
+ while (E) {
+ if (E->get()->last_pass != pass) { // only remove ONE reference
+ _pair_unreference(p_element, E->get());
+ E->get()->last_pass = pass;
}
- E=E->next();
+ E = E->next();
}
if (p_element->pairable) {
// and always test non-pairable if element is pairable
- E=p_octant->elements.front();
- while(E) {
- if (E->get()->last_pass!=pass) { // only remove ONE reference
- _pair_unreference( p_element,E->get() );
- E->get()->last_pass=pass;
+ E = p_octant->elements.front();
+ while (E) {
+ if (E->get()->last_pass != pass) { // only remove ONE reference
+ _pair_unreference(p_element, E->get());
+ E->get()->last_pass = pass;
}
- E=E->next();
+ E = E->next();
}
}
- p_octant->last_pass=pass;
+ p_octant->last_pass = pass;
- if (p_octant->children_count==0)
+ if (p_octant->children_count == 0)
return; // small optimization for leafs
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i])
- _unpair_element(p_element,p_octant->children[i]);
+ _unpair_element(p_element, p_octant->children[i]);
}
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_pair_element(Element *p_element,Octant *p_octant) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_pair_element(Element *p_element, Octant *p_octant) {
// always test pairable
- typename List<Element*,AL>::Element *E=p_octant->pairable_elements.front();
+ typename List<Element *, AL>::Element *E = p_octant->pairable_elements.front();
- while(E) {
+ while (E) {
- if (E->get()->last_pass!=pass) { // only get ONE reference
- _pair_reference( p_element,E->get() );
- E->get()->last_pass=pass;
+ if (E->get()->last_pass != pass) { // only get ONE reference
+ _pair_reference(p_element, E->get());
+ E->get()->last_pass = pass;
}
- E=E->next();
+ E = E->next();
}
if (p_element->pairable) {
// and always test non-pairable if element is pairable
- E=p_octant->elements.front();
- while(E) {
- if (E->get()->last_pass!=pass) { // only get ONE reference
- _pair_reference( p_element,E->get() );
- E->get()->last_pass=pass;
+ E = p_octant->elements.front();
+ while (E) {
+ if (E->get()->last_pass != pass) { // only get ONE reference
+ _pair_reference(p_element, E->get());
+ E->get()->last_pass = pass;
}
- E=E->next();
+ E = E->next();
}
}
- p_octant->last_pass=pass;
+ p_octant->last_pass = pass;
- if (p_octant->children_count==0)
+ if (p_octant->children_count == 0)
return; // small optimization for leafs
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i])
- _pair_element(p_element,p_octant->children[i]);
+ _pair_element(p_element, p_octant->children[i]);
}
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_remove_element(Element *p_element) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_remove_element(Element *p_element) {
pass++; // will do a new pass for this
- typename List< typename Element::OctantOwner,AL >::Element *I=p_element->octant_owners.front();
-
+ typename List<typename Element::OctantOwner, AL>::Element *I = p_element->octant_owners.front();
/* FIRST remove going up normally */
- for(;I;I=I->next()) {
+ for (; I; I = I->next()) {
- Octant *o=I->get().octant;
+ Octant *o = I->get().octant;
if (!use_pairs) // small speedup
- o->elements.erase( I->get().E );
-
- _remove_element_from_octant( p_element, o );
+ o->elements.erase(I->get().E);
+ _remove_element_from_octant(p_element, o);
}
/* THEN remove going down */
- I=p_element->octant_owners.front();
+ I = p_element->octant_owners.front();
if (use_pairs) {
- for(;I;I=I->next()) {
+ for (; I; I = I->next()) {
- Octant *o=I->get().octant;
+ Octant *o = I->get().octant;
// erase children pairs, they are erased ONCE even if repeated
pass++;
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (o->children[i])
- _unpair_element(p_element,o->children[i]);
+ _unpair_element(p_element, o->children[i]);
}
if (p_element->pairable)
- o->pairable_elements.erase( I->get().E );
+ o->pairable_elements.erase(I->get().E);
else
- o->elements.erase( I->get().E );
-
+ o->elements.erase(I->get().E);
}
}
p_element->octant_owners.clear();
- if(use_pairs) {
+ if (use_pairs) {
- int remaining=p_element->pair_list.size();
+ int remaining = p_element->pair_list.size();
//p_element->pair_list.clear();
- ERR_FAIL_COND( remaining );
+ ERR_FAIL_COND(remaining);
}
-
}
-template<class T,bool use_pairs,class AL>
-OctreeElementID Octree<T,use_pairs,AL>::create(T* p_userdata, const Rect3& p_aabb, int p_subindex,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) {
+template <class T, bool use_pairs, class AL>
+OctreeElementID Octree<T, use_pairs, AL>::create(T *p_userdata, const Rect3 &p_aabb, int p_subindex, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
- // check for AABB validity
+// check for AABB validity
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND_V( p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15, 0 );
- ERR_FAIL_COND_V( p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15, 0 );
- ERR_FAIL_COND_V( p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15, 0 );
- ERR_FAIL_COND_V( p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0, 0 );
- ERR_FAIL_COND_V( p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0, 0 );
- ERR_FAIL_COND_V( p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0, 0 );
- ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.x) , 0 );
- ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.y) , 0 );
- ERR_FAIL_COND_V( Math::is_nan(p_aabb.size.z) , 0 );
-
+ ERR_FAIL_COND_V(p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15, 0);
+ ERR_FAIL_COND_V(p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15, 0);
+ ERR_FAIL_COND_V(p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15, 0);
+ ERR_FAIL_COND_V(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0, 0);
+ ERR_FAIL_COND_V(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0, 0);
+ ERR_FAIL_COND_V(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0, 0);
+ ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.x), 0);
+ ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.y), 0);
+ ERR_FAIL_COND_V(Math::is_nan(p_aabb.size.z), 0);
#endif
typename ElementMap::Element *E = element_map.insert(last_element_id++,
- Element());
+ Element());
Element &e = E->get();
- e.aabb=p_aabb;
- e.userdata=p_userdata;
- e.subindex=p_subindex;
- e.last_pass=0;
- e.octree=this;
- e.pairable=p_pairable;
- e.pairable_type=p_pairable_type;
- e.pairable_mask=p_pairable_mask;
- e._id=last_element_id-1;
+ e.aabb = p_aabb;
+ e.userdata = p_userdata;
+ e.subindex = p_subindex;
+ e.last_pass = 0;
+ e.octree = this;
+ e.pairable = p_pairable;
+ e.pairable_type = p_pairable_type;
+ e.pairable_mask = p_pairable_mask;
+ e._id = last_element_id - 1;
if (!e.aabb.has_no_surface()) {
_ensure_valid_root(p_aabb);
- _insert_element(&e,root);
+ _insert_element(&e, root);
if (use_pairs)
_element_check_pairs(&e);
}
- return last_element_id-1;
+ return last_element_id - 1;
}
-
-
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::move(OctreeElementID p_id, const Rect3 &p_aabb) {
#ifdef DEBUG_ENABLED
// check for AABB validity
- ERR_FAIL_COND( p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15 );
- ERR_FAIL_COND( p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15 );
- ERR_FAIL_COND( p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15 );
- ERR_FAIL_COND( p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0 );
- ERR_FAIL_COND( p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0 );
- ERR_FAIL_COND( p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0 );
- ERR_FAIL_COND( Math::is_nan(p_aabb.size.x) );
- ERR_FAIL_COND( Math::is_nan(p_aabb.size.y) );
- ERR_FAIL_COND( Math::is_nan(p_aabb.size.z) );
+ ERR_FAIL_COND(p_aabb.pos.x > 1e15 || p_aabb.pos.x < -1e15);
+ ERR_FAIL_COND(p_aabb.pos.y > 1e15 || p_aabb.pos.y < -1e15);
+ ERR_FAIL_COND(p_aabb.pos.z > 1e15 || p_aabb.pos.z < -1e15);
+ ERR_FAIL_COND(p_aabb.size.x > 1e15 || p_aabb.size.x < 0.0);
+ ERR_FAIL_COND(p_aabb.size.y > 1e15 || p_aabb.size.y < 0.0);
+ ERR_FAIL_COND(p_aabb.size.z > 1e15 || p_aabb.size.z < 0.0);
+ ERR_FAIL_COND(Math::is_nan(p_aabb.size.x));
+ ERR_FAIL_COND(Math::is_nan(p_aabb.size.y));
+ ERR_FAIL_COND(Math::is_nan(p_aabb.size.z));
#endif
typename ElementMap::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
@@ -901,25 +872,23 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) {
#else
- bool old_has_surf=!e.aabb.has_no_surface();
- bool new_has_surf=!p_aabb.has_no_surface();
-
- if (old_has_surf!=new_has_surf) {
+ bool old_has_surf = !e.aabb.has_no_surface();
+ bool new_has_surf = !p_aabb.has_no_surface();
+ if (old_has_surf != new_has_surf) {
if (old_has_surf) {
_remove_element(&e); // removing
- e.common_parent=NULL;
- e.aabb=Rect3();
+ e.common_parent = NULL;
+ e.aabb = Rect3();
_optimize();
} else {
_ensure_valid_root(p_aabb); // inserting
- e.common_parent=NULL;
- e.aabb=p_aabb;
- _insert_element(&e,root);
+ e.common_parent = NULL;
+ e.aabb = p_aabb;
+ _insert_element(&e, root);
if (use_pairs)
_element_check_pairs(&e);
-
}
return;
@@ -931,48 +900,46 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) {
// it still is enclosed in the same AABB it was assigned to
if (e.container_aabb.encloses(p_aabb)) {
- e.aabb=p_aabb;
+ e.aabb = p_aabb;
if (use_pairs)
_element_check_pairs(&e); // must check pairs anyway
-
return;
}
- Rect3 combined=e.aabb;
+ Rect3 combined = e.aabb;
combined.merge_with(p_aabb);
_ensure_valid_root(combined);
- ERR_FAIL_COND( e.octant_owners.front()==NULL );
+ ERR_FAIL_COND(e.octant_owners.front() == NULL);
/* FIND COMMON PARENT */
- List<typename Element::OctantOwner,AL> owners = e.octant_owners; // save the octant owners
- Octant *common_parent=e.common_parent;
+ List<typename Element::OctantOwner, AL> owners = e.octant_owners; // save the octant owners
+ Octant *common_parent = e.common_parent;
ERR_FAIL_COND(!common_parent);
-
//src is now the place towards where insertion is going to happen
pass++;
- while(common_parent && !common_parent->aabb.encloses(p_aabb))
- common_parent=common_parent->parent;
+ while (common_parent && !common_parent->aabb.encloses(p_aabb))
+ common_parent = common_parent->parent;
ERR_FAIL_COND(!common_parent);
//prepare for reinsert
e.octant_owners.clear();
- e.common_parent=NULL;
- e.aabb=p_aabb;
+ e.common_parent = NULL;
+ e.aabb = p_aabb;
- _insert_element(&e,common_parent); // reinsert from this point
+ _insert_element(&e, common_parent); // reinsert from this point
pass++;
- for(typename List<typename Element::OctantOwner,AL>::Element *E=owners.front();E;) {
+ for (typename List<typename Element::OctantOwner, AL>::Element *E = owners.front(); E;) {
- Octant *o=E->get().octant;
- typename List<typename Element::OctantOwner,AL>::Element *N=E->next();
+ Octant *o = E->get().octant;
+ typename List<typename Element::OctantOwner, AL>::Element *N = E->next();
/*
if (!use_pairs)
@@ -980,77 +947,70 @@ void Octree<T,use_pairs,AL>::move(OctreeElementID p_id, const Rect3& p_aabb) {
*/
if (use_pairs && e.pairable)
- o->pairable_elements.erase( E->get().E );
+ o->pairable_elements.erase(E->get().E);
else
- o->elements.erase( E->get().E );
+ o->elements.erase(E->get().E);
- if (_remove_element_from_octant( &e, o, common_parent->parent )) {
+ if (_remove_element_from_octant(&e, o, common_parent->parent)) {
owners.erase(E);
}
- E=N;
+ E = N;
}
-
if (use_pairs) {
//unpair child elements in anything that survived
- for(typename List<typename Element::OctantOwner,AL>::Element *E=owners.front();E;E=E->next()) {
+ for (typename List<typename Element::OctantOwner, AL>::Element *E = owners.front(); E; E = E->next()) {
- Octant *o=E->get().octant;
+ Octant *o = E->get().octant;
// erase children pairs, unref ONCE
pass++;
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (o->children[i])
- _unpair_element(&e,o->children[i]);
+ _unpair_element(&e, o->children[i]);
}
-
}
_element_check_pairs(&e);
}
-
_optimize();
#endif
-
-
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::set_pairable(OctreeElementID p_id,bool p_pairable,uint32_t p_pairable_type,uint32_t p_pairable_mask) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::set_pairable(OctreeElementID p_id, bool p_pairable, uint32_t p_pairable_type, uint32_t p_pairable_mask) {
typename ElementMap::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
Element &e = E->get();
- if (p_pairable == e.pairable && e.pairable_type==p_pairable_type && e.pairable_mask==p_pairable_mask)
+ if (p_pairable == e.pairable && e.pairable_type == p_pairable_type && e.pairable_mask == p_pairable_mask)
return; // no changes, return
if (!e.aabb.has_no_surface()) {
_remove_element(&e);
}
- e.pairable=p_pairable;
- e.pairable_type=p_pairable_type;
- e.pairable_mask=p_pairable_mask;
- e.common_parent=NULL;
+ e.pairable = p_pairable;
+ e.pairable_type = p_pairable_type;
+ e.pairable_mask = p_pairable_mask;
+ e.common_parent = NULL;
if (!e.aabb.has_no_surface()) {
_ensure_valid_root(e.aabb);
- _insert_element(&e,root);
+ _insert_element(&e, root);
if (use_pairs)
_element_check_pairs(&e);
-
}
}
-
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::erase(OctreeElementID p_id) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::erase(OctreeElementID p_id) {
typename ElementMap::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
@@ -1066,28 +1026,28 @@ void Octree<T,use_pairs,AL>::erase(OctreeElementID p_id) {
_optimize();
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_cull_convex(Octant *p_octant,_CullConvexData *p_cull) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_cull_convex(Octant *p_octant, _CullConvexData *p_cull) {
- if (*p_cull->result_idx==p_cull->result_max)
+ if (*p_cull->result_idx == p_cull->result_max)
return; //pointless
if (!p_octant->elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->elements.front();
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->elements.front();
- for(;I;I=I->next()) {
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_cull->mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
- if (e->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) {
+ if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
- if (*p_cull->result_idx<p_cull->result_max) {
+ if (*p_cull->result_idx < p_cull->result_max) {
p_cull->result_array[*p_cull->result_idx] = e->userdata;
(*p_cull->result_idx)++;
} else {
@@ -1100,20 +1060,20 @@ void Octree<T,use_pairs,AL>::_cull_convex(Octant *p_octant,_CullConvexData *p_cu
if (use_pairs && !p_octant->pairable_elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->pairable_elements.front();
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->pairable_elements.front();
- for(;I;I=I->next()) {
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_cull->mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_cull->mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
- if (e->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) {
+ if (e->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
- if (*p_cull->result_idx<p_cull->result_max) {
+ if (*p_cull->result_idx < p_cull->result_max) {
p_cull->result_array[*p_cull->result_idx] = e->userdata;
(*p_cull->result_idx)++;
@@ -1125,36 +1085,35 @@ void Octree<T,use_pairs,AL>::_cull_convex(Octant *p_octant,_CullConvexData *p_cu
}
}
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_convex_shape(p_cull->planes,p_cull->plane_count)) {
- _cull_convex(p_octant->children[i],p_cull);
+ if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_convex_shape(p_cull->planes, p_cull->plane_count)) {
+ _cull_convex(p_octant->children[i], p_cull);
}
}
}
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_cull_AABB(Octant *p_octant, const Rect3 &p_aabb, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& p_aabb, T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
-
- if (*p_result_idx==p_result_max)
+ if (*p_result_idx == p_result_max)
return; //pointless
if (!p_octant->elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
if (p_aabb.intersects_inclusive(e->aabb)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1171,19 +1130,19 @@ void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& p_aabb, T*
if (use_pairs && !p_octant->pairable_elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->pairable_elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->pairable_elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
if (p_aabb.intersects_inclusive(e->aabb)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1197,36 +1156,35 @@ void Octree<T,use_pairs,AL>::_cull_AABB(Octant *p_octant,const Rect3& p_aabb, T*
}
}
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_inclusive(p_aabb)) {
- _cull_AABB(p_octant->children[i],p_aabb, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask);
+ _cull_AABB(p_octant->children[i], p_aabb, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
}
}
-
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_cull_segment(Octant *p_octant,const Vector3& p_from, const Vector3& p_to,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_cull_segment(Octant *p_octant, const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
- if (*p_result_idx==p_result_max)
+ if (*p_result_idx == p_result_max)
return; //pointless
if (!p_octant->elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
- if (e->aabb.intersects_segment(p_from,p_to)) {
+ if (e->aabb.intersects_segment(p_from, p_to)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1243,20 +1201,20 @@ void Octree<T,use_pairs,AL>::_cull_segment(Octant *p_octant,const Vector3& p_fro
if (use_pairs && !p_octant->pairable_elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->pairable_elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->pairable_elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
- if (e->aabb.intersects_segment(p_from,p_to)) {
+ if (e->aabb.intersects_segment(p_from, p_to)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1272,37 +1230,35 @@ void Octree<T,use_pairs,AL>::_cull_segment(Octant *p_octant,const Vector3& p_fro
}
}
+ for (int i = 0; i < 8; i++) {
- for (int i=0;i<8;i++) {
-
- if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_segment(p_from,p_to)) {
- _cull_segment(p_octant->children[i],p_from,p_to, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask);
+ if (p_octant->children[i] && p_octant->children[i]->aabb.intersects_segment(p_from, p_to)) {
+ _cull_segment(p_octant->children[i], p_from, p_to, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
}
}
}
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::_cull_point(Octant *p_octant, const Vector3 &p_point, T **p_result_array, int *p_result_idx, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::_cull_point(Octant *p_octant,const Vector3& p_point,T** p_result_array,int *p_result_idx,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
-
- if (*p_result_idx==p_result_max)
+ if (*p_result_idx == p_result_max)
return; //pointless
if (!p_octant->elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
if (e->aabb.has_point(p_point)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1319,20 +1275,20 @@ void Octree<T,use_pairs,AL>::_cull_point(Octant *p_octant,const Vector3& p_point
if (use_pairs && !p_octant->pairable_elements.empty()) {
- typename List< Element*,AL >::Element *I;
- I=p_octant->pairable_elements.front();
- for(;I;I=I->next()) {
+ typename List<Element *, AL>::Element *I;
+ I = p_octant->pairable_elements.front();
+ for (; I; I = I->next()) {
- Element *e=I->get();
+ Element *e = I->get();
- if (e->last_pass==pass || (use_pairs && !(e->pairable_type&p_mask)))
+ if (e->last_pass == pass || (use_pairs && !(e->pairable_type & p_mask)))
continue;
- e->last_pass=pass;
+ e->last_pass = pass;
if (e->aabb.has_point(p_point)) {
- if (*p_result_idx<p_result_max) {
+ if (*p_result_idx < p_result_max) {
p_result_array[*p_result_idx] = e->userdata;
if (p_subindex_array)
@@ -1348,120 +1304,103 @@ void Octree<T,use_pairs,AL>::_cull_point(Octant *p_octant,const Vector3& p_point
}
}
-
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
//could be optimized..
if (p_octant->children[i] && p_octant->children[i]->aabb.has_point(p_point)) {
- _cull_point(p_octant->children[i],p_point, p_result_array,p_result_idx,p_result_max,p_subindex_array,p_mask);
+ _cull_point(p_octant->children[i], p_point, p_result_array, p_result_idx, p_result_max, p_subindex_array, p_mask);
}
}
}
-template<class T,bool use_pairs,class AL>
-int Octree<T,use_pairs,AL>::cull_convex(const Vector<Plane>& p_convex,T** p_result_array,int p_result_max,uint32_t p_mask) {
+template <class T, bool use_pairs, class AL>
+int Octree<T, use_pairs, AL>::cull_convex(const Vector<Plane> &p_convex, T **p_result_array, int p_result_max, uint32_t p_mask) {
if (!root)
return 0;
- int result_count=0;
+ int result_count = 0;
pass++;
_CullConvexData cdata;
- cdata.planes=&p_convex[0];
- cdata.plane_count=p_convex.size();
- cdata.result_array=p_result_array;
- cdata.result_max=p_result_max;
- cdata.result_idx=&result_count;
- cdata.mask=p_mask;
+ cdata.planes = &p_convex[0];
+ cdata.plane_count = p_convex.size();
+ cdata.result_array = p_result_array;
+ cdata.result_max = p_result_max;
+ cdata.result_idx = &result_count;
+ cdata.mask = p_mask;
- _cull_convex(root,&cdata);
+ _cull_convex(root, &cdata);
return result_count;
}
-
-
-template<class T,bool use_pairs,class AL>
-int Octree<T,use_pairs,AL>::cull_AABB(const Rect3& p_aabb,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
-
+template <class T, bool use_pairs, class AL>
+int Octree<T, use_pairs, AL>::cull_AABB(const Rect3 &p_aabb, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
if (!root)
return 0;
- int result_count=0;
+ int result_count = 0;
pass++;
- _cull_AABB(root,p_aabb,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask);
+ _cull_AABB(root, p_aabb, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
return result_count;
}
-
-template<class T,bool use_pairs,class AL>
-int Octree<T,use_pairs,AL>::cull_segment(const Vector3& p_from, const Vector3& p_to,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
+template <class T, bool use_pairs, class AL>
+int Octree<T, use_pairs, AL>::cull_segment(const Vector3 &p_from, const Vector3 &p_to, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
if (!root)
return 0;
- int result_count=0;
+ int result_count = 0;
pass++;
- _cull_segment(root,p_from,p_to,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask);
+ _cull_segment(root, p_from, p_to, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
return result_count;
-
}
-template<class T,bool use_pairs,class AL>
-int Octree<T,use_pairs,AL>::cull_point(const Vector3& p_point,T** p_result_array,int p_result_max,int *p_subindex_array,uint32_t p_mask) {
+template <class T, bool use_pairs, class AL>
+int Octree<T, use_pairs, AL>::cull_point(const Vector3 &p_point, T **p_result_array, int p_result_max, int *p_subindex_array, uint32_t p_mask) {
if (!root)
return 0;
- int result_count=0;
+ int result_count = 0;
pass++;
- _cull_point(root,p_point,p_result_array,&result_count,p_result_max,p_subindex_array,p_mask);
+ _cull_point(root, p_point, p_result_array, &result_count, p_result_max, p_subindex_array, p_mask);
return result_count;
-
}
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::set_pair_callback(PairCallback p_callback, void *p_userdata) {
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::set_pair_callback( PairCallback p_callback, void *p_userdata ) {
-
- pair_callback=p_callback;
- pair_callback_userdata=p_userdata;
+ pair_callback = p_callback;
+ pair_callback_userdata = p_userdata;
}
-template<class T,bool use_pairs,class AL>
-void Octree<T,use_pairs,AL>::set_unpair_callback( UnpairCallback p_callback, void *p_userdata ) {
-
- unpair_callback=p_callback;
- unpair_callback_userdata=p_userdata;
+template <class T, bool use_pairs, class AL>
+void Octree<T, use_pairs, AL>::set_unpair_callback(UnpairCallback p_callback, void *p_userdata) {
+ unpair_callback = p_callback;
+ unpair_callback_userdata = p_userdata;
}
+template <class T, bool use_pairs, class AL>
+Octree<T, use_pairs, AL>::Octree(real_t p_unit_size) {
-template<class T,bool use_pairs,class AL>
-Octree<T,use_pairs,AL>::Octree(real_t p_unit_size) {
-
- last_element_id=1;
- pass=1;
- unit_size=p_unit_size;
- root=NULL;
-
- octant_count=0;
- pair_count=0;
-
- pair_callback=NULL;
- unpair_callback=NULL;
- pair_callback_userdata=NULL;
- unpair_callback_userdata=NULL;
-
-
+ last_element_id = 1;
+ pass = 1;
+ unit_size = p_unit_size;
+ root = NULL;
+ octant_count = 0;
+ pair_count = 0;
+ pair_callback = NULL;
+ unpair_callback = NULL;
+ pair_callback_userdata = NULL;
+ unpair_callback_userdata = NULL;
}
-
-
-
#endif
diff --git a/core/math/plane.cpp b/core/math/plane.cpp
index 2a97932049..29e7f2e75c 100644
--- a/core/math/plane.cpp
+++ b/core/math/plane.cpp
@@ -33,20 +33,20 @@
#define _PLANE_EQ_DOT_EPSILON 0.999
#define _PLANE_EQ_D_EPSILON 0.0001
-void Plane::set_normal(const Vector3& p_normal) {
+void Plane::set_normal(const Vector3 &p_normal) {
- normal=p_normal;
+ normal = p_normal;
}
void Plane::normalize() {
real_t l = normal.length();
- if (l==0) {
- *this=Plane(0,0,0,0);
+ if (l == 0) {
+ *this = Plane(0, 0, 0, 0);
return;
}
- normal/=l;
- d/=l;
+ normal /= l;
+ d /= l;
}
Plane Plane::normalized() const {
@@ -58,21 +58,21 @@ Plane Plane::normalized() const {
Vector3 Plane::get_any_point() const {
- return get_normal()*d;
+ return get_normal() * d;
}
Vector3 Plane::get_any_perpendicular_normal() const {
- static const Vector3 p1 = Vector3(1,0,0);
- static const Vector3 p2 = Vector3(0,1,0);
+ static const Vector3 p1 = Vector3(1, 0, 0);
+ static const Vector3 p2 = Vector3(0, 1, 0);
Vector3 p;
if (ABS(normal.dot(p1)) > 0.99) // if too similar to p1
- p=p2; // use p2
+ p = p2; // use p2
else
- p=p1; // use p1
+ p = p1; // use p1
- p-=normal * normal.dot(p);
+ p -= normal * normal.dot(p);
p.normalize();
return p;
@@ -82,71 +82,71 @@ Vector3 Plane::get_any_perpendicular_normal() const {
bool Plane::intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result) const {
- const Plane &p_plane0=*this;
- Vector3 normal0=p_plane0.normal;
- Vector3 normal1=p_plane1.normal;
- Vector3 normal2=p_plane2.normal;
+ const Plane &p_plane0 = *this;
+ Vector3 normal0 = p_plane0.normal;
+ Vector3 normal1 = p_plane1.normal;
+ Vector3 normal2 = p_plane2.normal;
- real_t denom=vec3_cross(normal0,normal1).dot(normal2);
+ real_t denom = vec3_cross(normal0, normal1).dot(normal2);
- if (ABS(denom)<=CMP_EPSILON)
+ if (ABS(denom) <= CMP_EPSILON)
return false;
- if (r_result) {
- *r_result = ( (vec3_cross(normal1, normal2) * p_plane0.d) +
- (vec3_cross(normal2, normal0) * p_plane1.d) +
- (vec3_cross(normal0, normal1) * p_plane2.d) )/denom;
- }
+ if (r_result) {
+ *r_result = ((vec3_cross(normal1, normal2) * p_plane0.d) +
+ (vec3_cross(normal2, normal0) * p_plane1.d) +
+ (vec3_cross(normal0, normal1) * p_plane2.d)) /
+ denom;
+ }
return true;
}
+bool Plane::intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3 *p_intersection) const {
-bool Plane::intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3* p_intersection) const {
-
- Vector3 segment=p_dir;
- real_t den=normal.dot( segment );
+ Vector3 segment = p_dir;
+ real_t den = normal.dot(segment);
//printf("den is %i\n",den);
- if (Math::abs(den)<=CMP_EPSILON) {
+ if (Math::abs(den) <= CMP_EPSILON) {
return false;
}
- real_t dist=(normal.dot( p_from ) - d) / den;
+ real_t dist = (normal.dot(p_from) - d) / den;
//printf("dist is %i\n",dist);
- if (dist>CMP_EPSILON) { //this is a ray, before the emiting pos (p_from) doesnt exist
+ if (dist > CMP_EPSILON) { //this is a ray, before the emiting pos (p_from) doesnt exist
return false;
}
- dist=-dist;
+ dist = -dist;
*p_intersection = p_from + segment * dist;
return true;
}
-bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_intersection) const {
+bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3 *p_intersection) const {
- Vector3 segment= p_begin - p_end;
- real_t den=normal.dot( segment );
+ Vector3 segment = p_begin - p_end;
+ real_t den = normal.dot(segment);
//printf("den is %i\n",den);
- if (Math::abs(den)<=CMP_EPSILON) {
+ if (Math::abs(den) <= CMP_EPSILON) {
return false;
}
- real_t dist=(normal.dot( p_begin ) - d) / den;
+ real_t dist = (normal.dot(p_begin) - d) / den;
//printf("dist is %i\n",dist);
- if (dist<-CMP_EPSILON || dist > (1.0 +CMP_EPSILON)) {
+ if (dist < -CMP_EPSILON || dist > (1.0 + CMP_EPSILON)) {
return false;
}
- dist=-dist;
+ dist = -dist;
*p_intersection = p_begin + segment * dist;
return true;
@@ -154,12 +154,11 @@ bool Plane::intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_inters
/* misc */
-bool Plane::is_almost_like(const Plane& p_plane) const {
+bool Plane::is_almost_like(const Plane &p_plane) const {
- return (normal.dot( p_plane.normal ) > _PLANE_EQ_DOT_EPSILON && Math::absd(d-p_plane.d) < _PLANE_EQ_D_EPSILON);
+ return (normal.dot(p_plane.normal) > _PLANE_EQ_DOT_EPSILON && Math::absd(d - p_plane.d) < _PLANE_EQ_D_EPSILON);
}
-
Plane::operator String() const {
return normal.operator String() + ", " + rtos(d);
diff --git a/core/math/plane.h b/core/math/plane.h
index 8235c59135..380452f6d2 100644
--- a/core/math/plane.h
+++ b/core/math/plane.h
@@ -29,64 +29,58 @@
#ifndef PLANE_H
#define PLANE_H
-
#include "vector3.h"
class Plane {
public:
-
Vector3 normal;
real_t d;
-
- void set_normal(const Vector3& p_normal);
+ void set_normal(const Vector3 &p_normal);
_FORCE_INLINE_ Vector3 get_normal() const { return normal; }; ///Point is coplanar, CMP_EPSILON for precision
void normalize();
Plane normalized() const;
- /* Plane-Point operations */
+ /* Plane-Point operations */
- _FORCE_INLINE_ Vector3 center() const { return normal*d; }
+ _FORCE_INLINE_ Vector3 center() const { return normal * d; }
Vector3 get_any_point() const;
Vector3 get_any_perpendicular_normal() const;
_FORCE_INLINE_ bool is_point_over(const Vector3 &p_point) const; ///< Point is over plane
_FORCE_INLINE_ real_t distance_to(const Vector3 &p_point) const;
- _FORCE_INLINE_ bool has_point(const Vector3 &p_point,real_t _epsilon=CMP_EPSILON) const;
+ _FORCE_INLINE_ bool has_point(const Vector3 &p_point, real_t _epsilon = CMP_EPSILON) const;
- /* intersections */
+ /* intersections */
- bool intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result=0) const;
- bool intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3* p_intersection) const;
- bool intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3* p_intersection) const;
+ bool intersect_3(const Plane &p_plane1, const Plane &p_plane2, Vector3 *r_result = 0) const;
+ bool intersects_ray(Vector3 p_from, Vector3 p_dir, Vector3 *p_intersection) const;
+ bool intersects_segment(Vector3 p_begin, Vector3 p_end, Vector3 *p_intersection) const;
- _FORCE_INLINE_ Vector3 project(const Vector3& p_point) const {
+ _FORCE_INLINE_ Vector3 project(const Vector3 &p_point) const {
return p_point - normal * distance_to(p_point);
}
- /* misc */
+ /* misc */
- Plane operator-() const { return Plane(-normal,-d); }
- bool is_almost_like(const Plane& p_plane) const;
+ Plane operator-() const { return Plane(-normal, -d); }
+ bool is_almost_like(const Plane &p_plane) const;
- _FORCE_INLINE_ bool operator==(const Plane& p_plane) const;
- _FORCE_INLINE_ bool operator!=(const Plane& p_plane) const;
+ _FORCE_INLINE_ bool operator==(const Plane &p_plane) const;
+ _FORCE_INLINE_ bool operator!=(const Plane &p_plane) const;
operator String() const;
- _FORCE_INLINE_ Plane() { d=0; }
- _FORCE_INLINE_ Plane(real_t p_a, real_t p_b, real_t p_c, real_t p_d) : normal(p_a,p_b,p_c), d(p_d) { };
+ _FORCE_INLINE_ Plane() { d = 0; }
+ _FORCE_INLINE_ Plane(real_t p_a, real_t p_b, real_t p_c, real_t p_d)
+ : normal(p_a, p_b, p_c), d(p_d){};
_FORCE_INLINE_ Plane(const Vector3 &p_normal, real_t p_d);
- _FORCE_INLINE_ Plane(const Vector3 &p_point, const Vector3& p_normal);
- _FORCE_INLINE_ Plane(const Vector3 &p_point1, const Vector3 &p_point2,const Vector3 &p_point3,ClockDirection p_dir = CLOCKWISE);
-
-
+ _FORCE_INLINE_ Plane(const Vector3 &p_point, const Vector3 &p_normal);
+ _FORCE_INLINE_ Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3, ClockDirection p_dir = CLOCKWISE);
};
-
-
bool Plane::is_point_over(const Vector3 &p_point) const {
return (normal.dot(p_point) > d);
@@ -94,53 +88,47 @@ bool Plane::is_point_over(const Vector3 &p_point) const {
real_t Plane::distance_to(const Vector3 &p_point) const {
- return (normal.dot(p_point)-d);
+ return (normal.dot(p_point) - d);
}
-bool Plane::has_point(const Vector3 &p_point,real_t _epsilon) const {
-
- real_t dist=normal.dot(p_point) - d;
- dist=ABS(dist);
- return ( dist <= _epsilon);
+bool Plane::has_point(const Vector3 &p_point, real_t _epsilon) const {
+ real_t dist = normal.dot(p_point) - d;
+ dist = ABS(dist);
+ return (dist <= _epsilon);
}
Plane::Plane(const Vector3 &p_normal, real_t p_d) {
- normal=p_normal;
- d=p_d;
+ normal = p_normal;
+ d = p_d;
}
-Plane::Plane(const Vector3 &p_point, const Vector3& p_normal) {
+Plane::Plane(const Vector3 &p_point, const Vector3 &p_normal) {
- normal=p_normal;
- d=p_normal.dot(p_point);
+ normal = p_normal;
+ d = p_normal.dot(p_point);
}
-Plane::Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3,ClockDirection p_dir) {
+Plane::Plane(const Vector3 &p_point1, const Vector3 &p_point2, const Vector3 &p_point3, ClockDirection p_dir) {
if (p_dir == CLOCKWISE)
- normal=(p_point1-p_point3).cross(p_point1-p_point2);
+ normal = (p_point1 - p_point3).cross(p_point1 - p_point2);
else
- normal=(p_point1-p_point2).cross(p_point1-p_point3);
-
+ normal = (p_point1 - p_point2).cross(p_point1 - p_point3);
normal.normalize();
d = normal.dot(p_point1);
-
-
}
-bool Plane::operator==(const Plane& p_plane) const {
+bool Plane::operator==(const Plane &p_plane) const {
- return normal==p_plane.normal && d == p_plane.d;
+ return normal == p_plane.normal && d == p_plane.d;
}
-bool Plane::operator!=(const Plane& p_plane) const {
-
- return normal!=p_plane.normal || d != p_plane.d;
+bool Plane::operator!=(const Plane &p_plane) const {
+ return normal != p_plane.normal || d != p_plane.d;
}
#endif // PLANE_H
-
diff --git a/core/math/quat.cpp b/core/math/quat.cpp
index 4085f9b84a..b990e9184f 100644
--- a/core/math/quat.cpp
+++ b/core/math/quat.cpp
@@ -33,7 +33,7 @@
// set_euler expects a vector containing the Euler angles in the format
// (c,b,a), where a is the angle of the first rotation, and c is the last.
// The current implementation uses XYZ convention (Z is the first rotation).
-void Quat::set_euler(const Vector3& p_euler) {
+void Quat::set_euler(const Vector3 &p_euler) {
real_t half_a1 = p_euler.x * 0.5;
real_t half_a2 = p_euler.y * 0.5;
real_t half_a3 = p_euler.z * 0.5;
@@ -49,10 +49,10 @@ void Quat::set_euler(const Vector3& p_euler) {
real_t cos_a3 = Math::cos(half_a3);
real_t sin_a3 = Math::sin(half_a3);
- set(sin_a1*cos_a2*cos_a3 + sin_a2*sin_a3*cos_a1,
- -sin_a1*sin_a3*cos_a2 + sin_a2*cos_a1*cos_a3,
- sin_a1*sin_a2*cos_a3 + sin_a3*cos_a1*cos_a2,
- -sin_a1*sin_a2*sin_a3 + cos_a1*cos_a2*cos_a3);
+ set(sin_a1 * cos_a2 * cos_a3 + sin_a2 * sin_a3 * cos_a1,
+ -sin_a1 * sin_a3 * cos_a2 + sin_a2 * cos_a1 * cos_a3,
+ sin_a1 * sin_a2 * cos_a3 + sin_a3 * cos_a1 * cos_a2,
+ -sin_a1 * sin_a2 * sin_a3 + cos_a1 * cos_a2 * cos_a3);
}
// get_euler returns a vector containing the Euler angles in the format
@@ -63,24 +63,21 @@ Vector3 Quat::get_euler() const {
return m.get_euler();
}
-void Quat::operator*=(const Quat& q) {
+void Quat::operator*=(const Quat &q) {
- set(w * q.x+x * q.w+y * q.z - z * q.y,
- w * q.y+y * q.w+z * q.x - x * q.z,
- w * q.z+z * q.w+x * q.y - y * q.x,
- w * q.w - x * q.x - y * q.y - z * q.z);
+ set(w * q.x + x * q.w + y * q.z - z * q.y,
+ w * q.y + y * q.w + z * q.x - x * q.z,
+ w * q.z + z * q.w + x * q.y - y * q.x,
+ w * q.w - x * q.x - y * q.y - z * q.z);
}
-Quat Quat::operator*(const Quat& q) const {
+Quat Quat::operator*(const Quat &q) const {
- Quat r=*this;
- r*=q;
+ Quat r = *this;
+ r *= q;
return r;
}
-
-
-
real_t Quat::length() const {
return Math::sqrt(length_squared());
@@ -90,17 +87,15 @@ void Quat::normalize() {
*this /= length();
}
-
Quat Quat::normalized() const {
return *this / length();
}
Quat Quat::inverse() const {
- return Quat( -x, -y, -z, w );
+ return Quat(-x, -y, -z, w);
}
-
-Quat Quat::slerp(const Quat& q, const real_t& t) const {
+Quat Quat::slerp(const Quat &q, const real_t &t) const {
#if 0
@@ -144,31 +139,29 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const {
}
#else
- Quat to1;
- real_t omega, cosom, sinom, scale0, scale1;
-
+ Quat to1;
+ real_t omega, cosom, sinom, scale0, scale1;
// calc cosine
cosom = dot(q);
// adjust signs (if necessary)
- if ( cosom <0.0 ) {
+ if (cosom < 0.0) {
cosom = -cosom;
- to1.x = - q.x;
- to1.y = - q.y;
- to1.z = - q.z;
- to1.w = - q.w;
- } else {
+ to1.x = -q.x;
+ to1.y = -q.y;
+ to1.z = -q.z;
+ to1.w = -q.w;
+ } else {
to1.x = q.x;
to1.y = q.y;
to1.z = q.z;
to1.w = q.w;
}
-
// calculate coefficients
- if ( (1.0 - cosom) > CMP_EPSILON ) {
+ if ((1.0 - cosom) > CMP_EPSILON) {
// standard case (slerp)
omega = Math::acos(cosom);
sinom = Math::sin(omega);
@@ -182,15 +175,14 @@ Quat Quat::slerp(const Quat& q, const real_t& t) const {
}
// calculate final values
return Quat(
- scale0 * x + scale1 * to1.x,
- scale0 * y + scale1 * to1.y,
- scale0 * z + scale1 * to1.z,
- scale0 * w + scale1 * to1.w
- );
+ scale0 * x + scale1 * to1.x,
+ scale0 * y + scale1 * to1.y,
+ scale0 * z + scale1 * to1.z,
+ scale0 * w + scale1 * to1.w);
#endif
}
-Quat Quat::slerpni(const Quat& q, const real_t& t) const {
+Quat Quat::slerpni(const Quat &q, const real_t &t) const {
const Quat &from = *this;
@@ -198,15 +190,15 @@ Quat Quat::slerpni(const Quat& q, const real_t& t) const {
if (Math::absf(dot) > 0.9999) return from;
- real_t theta = Math::acos(dot),
- sinT = 1.0 / Math::sin(theta),
- newFactor = Math::sin(t * theta) * sinT,
- invFactor = Math::sin((1.0 - t) * theta) * sinT;
+ real_t theta = Math::acos(dot),
+ sinT = 1.0 / Math::sin(theta),
+ newFactor = Math::sin(t * theta) * sinT,
+ invFactor = Math::sin((1.0 - t) * theta) * sinT;
return Quat(invFactor * from.x + newFactor * q.x,
- invFactor * from.y + newFactor * q.y,
- invFactor * from.z + newFactor * q.z,
- invFactor * from.w + newFactor * q.w);
+ invFactor * from.y + newFactor * q.y,
+ invFactor * from.z + newFactor * q.z,
+ invFactor * from.w + newFactor * q.w);
#if 0
real_t to1[4];
@@ -256,31 +248,29 @@ Quat Quat::slerpni(const Quat& q, const real_t& t) const {
#endif
}
-Quat Quat::cubic_slerp(const Quat& q, const Quat& prep, const Quat& postq,const real_t& t) const {
+Quat Quat::cubic_slerp(const Quat &q, const Quat &prep, const Quat &postq, const real_t &t) const {
//the only way to do slerp :|
- real_t t2 = (1.0-t)*t*2;
- Quat sp = this->slerp(q,t);
- Quat sq = prep.slerpni(postq,t);
- return sp.slerpni(sq,t2);
-
+ real_t t2 = (1.0 - t) * t * 2;
+ Quat sp = this->slerp(q, t);
+ Quat sq = prep.slerpni(postq, t);
+ return sp.slerpni(sq, t2);
}
-
Quat::operator String() const {
- return String::num(x)+", "+String::num(y)+", "+ String::num(z)+", "+ String::num(w);
+ return String::num(x) + ", " + String::num(y) + ", " + String::num(z) + ", " + String::num(w);
}
-Quat::Quat(const Vector3& axis, const real_t& angle) {
+Quat::Quat(const Vector3 &axis, const real_t &angle) {
real_t d = axis.length();
- if (d==0)
- set(0,0,0,0);
+ if (d == 0)
+ set(0, 0, 0, 0);
else {
real_t sin_angle = Math::sin(angle * 0.5);
real_t cos_angle = Math::cos(angle * 0.5);
real_t s = sin_angle / d;
set(axis.x * s, axis.y * s, axis.z * s,
- cos_angle);
+ cos_angle);
}
}
diff --git a/core/math/quat.h b/core/math/quat.h
index d3a50343a3..3fc843b83a 100644
--- a/core/math/quat.h
+++ b/core/math/quat.h
@@ -39,159 +39,166 @@
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-class Quat{
+class Quat {
public:
-
- real_t x,y,z,w;
+ real_t x, y, z, w;
_FORCE_INLINE_ real_t length_squared() const;
real_t length() const;
void normalize();
Quat normalized() const;
Quat inverse() const;
- _FORCE_INLINE_ real_t dot(const Quat& q) const;
- void set_euler(const Vector3& p_euler);
+ _FORCE_INLINE_ real_t dot(const Quat &q) const;
+ void set_euler(const Vector3 &p_euler);
Vector3 get_euler() const;
- Quat slerp(const Quat& q, const real_t& t) const;
- Quat slerpni(const Quat& q, const real_t& t) const;
- Quat cubic_slerp(const Quat& q, const Quat& prep, const Quat& postq,const real_t& t) const;
+ Quat slerp(const Quat &q, const real_t &t) const;
+ Quat slerpni(const Quat &q, const real_t &t) const;
+ Quat cubic_slerp(const Quat &q, const Quat &prep, const Quat &postq, const real_t &t) const;
- _FORCE_INLINE_ void get_axis_and_angle(Vector3& r_axis, real_t &r_angle) const {
+ _FORCE_INLINE_ void get_axis_and_angle(Vector3 &r_axis, real_t &r_angle) const {
r_angle = 2 * Math::acos(w);
- r_axis.x = x / Math::sqrt(1-w*w);
- r_axis.y = y / Math::sqrt(1-w*w);
- r_axis.z = z / Math::sqrt(1-w*w);
+ r_axis.x = x / Math::sqrt(1 - w * w);
+ r_axis.y = y / Math::sqrt(1 - w * w);
+ r_axis.z = z / Math::sqrt(1 - w * w);
}
- void operator*=(const Quat& q);
- Quat operator*(const Quat& q) const;
-
-
+ void operator*=(const Quat &q);
+ Quat operator*(const Quat &q) const;
- Quat operator*(const Vector3& v) const
- {
- return Quat( w * v.x + y * v.z - z * v.y,
- w * v.y + z * v.x - x * v.z,
- w * v.z + x * v.y - y * v.x,
- -x * v.x - y * v.y - z * v.z);
+ Quat operator*(const Vector3 &v) const {
+ return Quat(w * v.x + y * v.z - z * v.y,
+ w * v.y + z * v.x - x * v.z,
+ w * v.z + x * v.y - y * v.x,
+ -x * v.x - y * v.y - z * v.z);
}
- _FORCE_INLINE_ Vector3 xform(const Vector3& v) const {
+ _FORCE_INLINE_ Vector3 xform(const Vector3 &v) const {
Quat q = *this * v;
q *= this->inverse();
- return Vector3(q.x,q.y,q.z);
+ return Vector3(q.x, q.y, q.z);
}
- _FORCE_INLINE_ void operator+=(const Quat& q);
- _FORCE_INLINE_ void operator-=(const Quat& q);
- _FORCE_INLINE_ void operator*=(const real_t& s);
- _FORCE_INLINE_ void operator/=(const real_t& s);
- _FORCE_INLINE_ Quat operator+(const Quat& q2) const;
- _FORCE_INLINE_ Quat operator-(const Quat& q2) const;
+ _FORCE_INLINE_ void operator+=(const Quat &q);
+ _FORCE_INLINE_ void operator-=(const Quat &q);
+ _FORCE_INLINE_ void operator*=(const real_t &s);
+ _FORCE_INLINE_ void operator/=(const real_t &s);
+ _FORCE_INLINE_ Quat operator+(const Quat &q2) const;
+ _FORCE_INLINE_ Quat operator-(const Quat &q2) const;
_FORCE_INLINE_ Quat operator-() const;
- _FORCE_INLINE_ Quat operator*(const real_t& s) const;
- _FORCE_INLINE_ Quat operator/(const real_t& s) const;
-
+ _FORCE_INLINE_ Quat operator*(const real_t &s) const;
+ _FORCE_INLINE_ Quat operator/(const real_t &s) const;
- _FORCE_INLINE_ bool operator==(const Quat& p_quat) const;
- _FORCE_INLINE_ bool operator!=(const Quat& p_quat) const;
+ _FORCE_INLINE_ bool operator==(const Quat &p_quat) const;
+ _FORCE_INLINE_ bool operator!=(const Quat &p_quat) const;
operator String() const;
- inline void set( real_t p_x, real_t p_y, real_t p_z, real_t p_w) {
- x=p_x; y=p_y; z=p_z; w=p_w;
+ inline void set(real_t p_x, real_t p_y, real_t p_z, real_t p_w) {
+ x = p_x;
+ y = p_y;
+ z = p_z;
+ w = p_w;
}
inline Quat(real_t p_x, real_t p_y, real_t p_z, real_t p_w) {
- x=p_x; y=p_y; z=p_z; w=p_w;
+ x = p_x;
+ y = p_y;
+ z = p_z;
+ w = p_w;
}
- Quat(const Vector3& axis, const real_t& angle);
+ Quat(const Vector3 &axis, const real_t &angle);
- Quat(const Vector3& v0, const Vector3& v1) // shortest arc
+ Quat(const Vector3 &v0, const Vector3 &v1) // shortest arc
{
Vector3 c = v0.cross(v1);
- real_t d = v0.dot(v1);
+ real_t d = v0.dot(v1);
if (d < -1.0 + CMP_EPSILON) {
- x=0;
- y=1;
- z=0;
- w=0;
+ x = 0;
+ y = 1;
+ z = 0;
+ w = 0;
} else {
- real_t s = Math::sqrt((1.0 + d) * 2.0);
+ real_t s = Math::sqrt((1.0 + d) * 2.0);
real_t rs = 1.0 / s;
- x=c.x*rs;
- y=c.y*rs;
- z=c.z*rs;
- w=s * 0.5;
+ x = c.x * rs;
+ y = c.y * rs;
+ z = c.z * rs;
+ w = s * 0.5;
}
}
- inline Quat() {x=y=z=0; w=1; }
-
-
+ inline Quat() {
+ x = y = z = 0;
+ w = 1;
+ }
};
-
-real_t Quat::dot(const Quat& q) const {
- return x * q.x+y * q.y+z * q.z+w * q.w;
+real_t Quat::dot(const Quat &q) const {
+ return x * q.x + y * q.y + z * q.z + w * q.w;
}
real_t Quat::length_squared() const {
return dot(*this);
}
-void Quat::operator+=(const Quat& q) {
- x += q.x; y += q.y; z += q.z; w += q.w;
+void Quat::operator+=(const Quat &q) {
+ x += q.x;
+ y += q.y;
+ z += q.z;
+ w += q.w;
}
-void Quat::operator-=(const Quat& q) {
- x -= q.x; y -= q.y; z -= q.z; w -= q.w;
+void Quat::operator-=(const Quat &q) {
+ x -= q.x;
+ y -= q.y;
+ z -= q.z;
+ w -= q.w;
}
-void Quat::operator*=(const real_t& s) {
- x *= s; y *= s; z *= s; w *= s;
+void Quat::operator*=(const real_t &s) {
+ x *= s;
+ y *= s;
+ z *= s;
+ w *= s;
}
-
-void Quat::operator/=(const real_t& s) {
+void Quat::operator/=(const real_t &s) {
*this *= 1.0 / s;
}
-Quat Quat::operator+(const Quat& q2) const {
- const Quat& q1 = *this;
- return Quat( q1.x+q2.x, q1.y+q2.y, q1.z+q2.z, q1.w+q2.w );
+Quat Quat::operator+(const Quat &q2) const {
+ const Quat &q1 = *this;
+ return Quat(q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w);
}
-Quat Quat::operator-(const Quat& q2) const {
- const Quat& q1 = *this;
- return Quat( q1.x-q2.x, q1.y-q2.y, q1.z-q2.z, q1.w-q2.w);
+Quat Quat::operator-(const Quat &q2) const {
+ const Quat &q1 = *this;
+ return Quat(q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w);
}
Quat Quat::operator-() const {
- const Quat& q2 = *this;
- return Quat( -q2.x, -q2.y, -q2.z, -q2.w);
+ const Quat &q2 = *this;
+ return Quat(-q2.x, -q2.y, -q2.z, -q2.w);
}
-Quat Quat::operator*(const real_t& s) const {
+Quat Quat::operator*(const real_t &s) const {
return Quat(x * s, y * s, z * s, w * s);
}
-Quat Quat::operator/(const real_t& s) const {
+Quat Quat::operator/(const real_t &s) const {
return *this * (1.0 / s);
}
-
-bool Quat::operator==(const Quat& p_quat) const {
- return x==p_quat.x && y==p_quat.y && z==p_quat.z && w==p_quat.w;
+bool Quat::operator==(const Quat &p_quat) const {
+ return x == p_quat.x && y == p_quat.y && z == p_quat.z && w == p_quat.w;
}
-bool Quat::operator!=(const Quat& p_quat) const {
- return x!=p_quat.x || y!=p_quat.y || z!=p_quat.z || w!=p_quat.w;
+bool Quat::operator!=(const Quat &p_quat) const {
+ return x != p_quat.x || y != p_quat.y || z != p_quat.z || w != p_quat.w;
}
-
#endif
diff --git a/core/math/quick_hull.cpp b/core/math/quick_hull.cpp
index 32fc0e01e8..a235d1cf32 100644
--- a/core/math/quick_hull.cpp
+++ b/core/math/quick_hull.cpp
@@ -29,49 +29,44 @@
#include "quick_hull.h"
#include "map.h"
-uint32_t QuickHull::debug_stop_after=0xFFFFFFFF;
-
-Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_mesh) {
+uint32_t QuickHull::debug_stop_after = 0xFFFFFFFF;
+Error QuickHull::build(const Vector<Vector3> &p_points, Geometry::MeshData &r_mesh) {
static const real_t over_tolerance = 0.0001;
/* CREATE AABB VOLUME */
Rect3 aabb;
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
- if (i==0) {
- aabb.pos=p_points[i];
+ if (i == 0) {
+ aabb.pos = p_points[i];
} else {
aabb.expand_to(p_points[i]);
}
}
-
- if (aabb.size==Vector3()) {
+ if (aabb.size == Vector3()) {
return ERR_CANT_CREATE;
}
-
Vector<bool> valid_points;
valid_points.resize(p_points.size());
Set<Vector3> valid_cache;
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
Vector3 sp = p_points[i].snapped(0.0001);
if (valid_cache.has(sp)) {
- valid_points[i]=false;
+ valid_points[i] = false;
//print_line("INVALIDATED: "+itos(i));
- }else {
- valid_points[i]=true;
+ } else {
+ valid_points[i] = true;
valid_cache.insert(sp);
}
}
-
-
/* CREATE INITIAL SIMPLEX */
int longest_axis = aabb.get_longest_axis_index();
@@ -80,46 +75,44 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
int simplex[4];
{
- real_t max,min;
+ real_t max, min;
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
if (!valid_points[i])
continue;
real_t d = p_points[i][longest_axis];
- if (i==0 || d < min) {
+ if (i == 0 || d < min) {
- simplex[0]=i;
- min=d;
+ simplex[0] = i;
+ min = d;
}
- if (i==0 || d > max) {
- simplex[1]=i;
- max=d;
+ if (i == 0 || d > max) {
+ simplex[1] = i;
+ max = d;
}
-
}
}
//third vertex is one most further away from the line
-
{
real_t maxd;
- Vector3 rel12 = p_points[simplex[0]] - p_points[simplex[1]];
+ Vector3 rel12 = p_points[simplex[0]] - p_points[simplex[1]];
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
if (!valid_points[i])
continue;
- Vector3 n = rel12.cross(p_points[simplex[0]]-p_points[i]).cross(rel12).normalized();
- real_t d = Math::abs(n.dot(p_points[simplex[0]])-n.dot(p_points[i]));
+ Vector3 n = rel12.cross(p_points[simplex[0]] - p_points[i]).cross(rel12).normalized();
+ real_t d = Math::abs(n.dot(p_points[simplex[0]]) - n.dot(p_points[i]));
- if (i==0 || d>maxd) {
+ if (i == 0 || d > maxd) {
- maxd=d;
- simplex[2]=i;
+ maxd = d;
+ simplex[2] = i;
}
}
}
@@ -128,102 +121,92 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
{
real_t maxd;
- Plane p(p_points[simplex[0]],p_points[simplex[1]],p_points[simplex[2]]);
+ Plane p(p_points[simplex[0]], p_points[simplex[1]], p_points[simplex[2]]);
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
if (!valid_points[i])
continue;
real_t d = Math::abs(p.distance_to(p_points[i]));
- if (i==0 || d>maxd) {
+ if (i == 0 || d > maxd) {
- maxd=d;
- simplex[3]=i;
+ maxd = d;
+ simplex[3] = i;
}
}
}
-
//compute center of simplex, this is a point always warranted to be inside
Vector3 center;
- for(int i=0;i<4;i++) {
- center+=p_points[simplex[i]];
+ for (int i = 0; i < 4; i++) {
+ center += p_points[simplex[i]];
}
- center/=4.0;
+ center /= 4.0;
//add faces
List<Face> faces;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- static const int face_order[4][3]={
- {0,1,2},
- {0,1,3},
- {0,2,3},
- {1,2,3}
+ static const int face_order[4][3] = {
+ { 0, 1, 2 },
+ { 0, 1, 3 },
+ { 0, 2, 3 },
+ { 1, 2, 3 }
};
Face f;
- for(int j=0;j<3;j++) {
- f.vertices[j]=simplex[face_order[i][j]];
+ for (int j = 0; j < 3; j++) {
+ f.vertices[j] = simplex[face_order[i][j]];
}
-
- Plane p(p_points[f.vertices[0]],p_points[f.vertices[1]],p_points[f.vertices[2]]);
+ Plane p(p_points[f.vertices[0]], p_points[f.vertices[1]], p_points[f.vertices[2]]);
if (p.is_point_over(center)) {
//flip face to clockwise if facing inwards
- SWAP( f.vertices[0], f.vertices[1] );
- p=-p;
+ SWAP(f.vertices[0], f.vertices[1]);
+ p = -p;
}
-
f.plane = p;
faces.push_back(f);
-
}
-
/* COMPUTE AVAILABLE VERTICES */
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
- if (i==simplex[0])
+ if (i == simplex[0])
continue;
- if (i==simplex[1])
+ if (i == simplex[1])
continue;
- if (i==simplex[2])
+ if (i == simplex[2])
continue;
- if (i==simplex[3])
+ if (i == simplex[3])
continue;
if (!valid_points[i])
continue;
- for(List<Face>::Element *E=faces.front();E;E=E->next()) {
+ for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
- if (E->get().plane.distance_to(p_points[i]) > over_tolerance ) {
+ if (E->get().plane.distance_to(p_points[i]) > over_tolerance) {
E->get().points_over.push_back(i);
break;
}
}
-
-
-
}
faces.sort(); // sort them, so the ones with points are in the back
-
/* BUILD HULL */
-
//poop face (while still remain)
//find further away point
//find lit faces
@@ -231,72 +214,68 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
//build new faces with horizon edges, them assign points side from all lit faces
//remove lit faces
-
uint32_t debug_stop = debug_stop_after;
- while(debug_stop>0 && faces.back()->get().points_over.size()) {
+ while (debug_stop > 0 && faces.back()->get().points_over.size()) {
debug_stop--;
- Face& f = faces.back()->get();
+ Face &f = faces.back()->get();
//find vertex most outside
- int next=-1;
- real_t next_d=0;
+ int next = -1;
+ real_t next_d = 0;
- for(int i=0;i<f.points_over.size();i++) {
+ for (int i = 0; i < f.points_over.size(); i++) {
real_t d = f.plane.distance_to(p_points[f.points_over[i]]);
if (d > next_d) {
- next_d=d;
- next=i;
+ next_d = d;
+ next = i;
}
}
- ERR_FAIL_COND_V(next==-1,ERR_BUG);
-
-
+ ERR_FAIL_COND_V(next == -1, ERR_BUG);
Vector3 v = p_points[f.points_over[next]];
//find lit faces and lit edges
- List< List<Face>::Element* > lit_faces; //lit face is a death sentence
+ List<List<Face>::Element *> lit_faces; //lit face is a death sentence
- Map<Edge,FaceConnect> lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot
+ Map<Edge, FaceConnect> lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot
- for(List<Face>::Element *E=faces.front();E;E=E->next()) {
+ for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
- if (E->get().plane.distance_to(v) >0 ) {
+ if (E->get().plane.distance_to(v) > 0) {
lit_faces.push_back(E);
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
uint32_t a = E->get().vertices[i];
- uint32_t b = E->get().vertices[(i+1)%3];
- Edge e(a,b);
+ uint32_t b = E->get().vertices[(i + 1) % 3];
+ Edge e(a, b);
- Map<Edge,FaceConnect>::Element *F=lit_edges.find(e);
+ Map<Edge, FaceConnect>::Element *F = lit_edges.find(e);
if (!F) {
- F=lit_edges.insert(e,FaceConnect());
+ F = lit_edges.insert(e, FaceConnect());
}
- if (e.vertices[0]==a) {
+ if (e.vertices[0] == a) {
//left
- F->get().left=E;
+ F->get().left = E;
} else {
- F->get().right=E;
+ F->get().right = E;
}
}
}
}
-
//create new faces from horizon edges
- List< List<Face>::Element* > new_faces; //new faces
+ List<List<Face>::Element *> new_faces; //new faces
- for(Map<Edge,FaceConnect>::Element *E=lit_edges.front();E;E=E->next()) {
+ for (Map<Edge, FaceConnect>::Element *E = lit_edges.front(); E; E = E->next()) {
- FaceConnect& fc = E->get();
+ FaceConnect &fc = E->get();
if (fc.left && fc.right) {
continue; //edge is uninteresting, not on horizont
}
@@ -304,50 +283,48 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
//create new face!
Face face;
- face.vertices[0]=f.points_over[next];
- face.vertices[1]=E->key().vertices[0];
- face.vertices[2]=E->key().vertices[1];
+ face.vertices[0] = f.points_over[next];
+ face.vertices[1] = E->key().vertices[0];
+ face.vertices[2] = E->key().vertices[1];
- Plane p(p_points[face.vertices[0]],p_points[face.vertices[1]],p_points[face.vertices[2]]);
+ Plane p(p_points[face.vertices[0]], p_points[face.vertices[1]], p_points[face.vertices[2]]);
if (p.is_point_over(center)) {
//flip face to clockwise if facing inwards
- SWAP( face.vertices[0], face.vertices[1] );
+ SWAP(face.vertices[0], face.vertices[1]);
p = -p;
}
face.plane = p;
- new_faces.push_back( faces.push_back(face) );
+ new_faces.push_back(faces.push_back(face));
}
//distribute points into new faces
- for(List< List<Face>::Element* >::Element *F=lit_faces.front();F;F=F->next()) {
+ for (List<List<Face>::Element *>::Element *F = lit_faces.front(); F; F = F->next()) {
Face &lf = F->get()->get();
- for(int i=0;i<lf.points_over.size();i++) {
+ for (int i = 0; i < lf.points_over.size(); i++) {
- if (lf.points_over[i]==f.points_over[next]) //do not add current one
+ if (lf.points_over[i] == f.points_over[next]) //do not add current one
continue;
Vector3 p = p_points[lf.points_over[i]];
- for (List< List<Face>::Element* >::Element *E=new_faces.front();E;E=E->next()) {
+ for (List<List<Face>::Element *>::Element *E = new_faces.front(); E; E = E->next()) {
Face &f2 = E->get()->get();
- if (f2.plane.distance_to(p)>over_tolerance) {
+ if (f2.plane.distance_to(p) > over_tolerance) {
f2.points_over.push_back(lf.points_over[i]);
break;
}
}
-
-
}
}
//erase lit faces
- while(lit_faces.size()) {
+ while (lit_faces.size()) {
faces.erase(lit_faces.front()->get());
lit_faces.pop_front();
@@ -355,129 +332,115 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
//put faces that contain no points on the front
- for (List< List<Face>::Element* >::Element *E=new_faces.front();E;E=E->next()) {
+ for (List<List<Face>::Element *>::Element *E = new_faces.front(); E; E = E->next()) {
Face &f2 = E->get()->get();
- if (f2.points_over.size()==0) {
+ if (f2.points_over.size() == 0) {
faces.move_to_front(E->get());
}
}
//whew, done with iteration, go next
-
-
-
}
/* CREATE MESHDATA */
-
//make a map of edges again
- Map<Edge,RetFaceConnect> ret_edges;
+ Map<Edge, RetFaceConnect> ret_edges;
List<Geometry::MeshData::Face> ret_faces;
-
- for(List<Face>::Element *E=faces.front();E;E=E->next()) {
+ for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
Geometry::MeshData::Face f;
f.plane = E->get().plane;
-
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
f.indices.push_back(E->get().vertices[i]);
}
List<Geometry::MeshData::Face>::Element *F = ret_faces.push_back(f);
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
uint32_t a = E->get().vertices[i];
- uint32_t b = E->get().vertices[(i+1)%3];
- Edge e(a,b);
+ uint32_t b = E->get().vertices[(i + 1) % 3];
+ Edge e(a, b);
- Map<Edge,RetFaceConnect>::Element *G=ret_edges.find(e);
+ Map<Edge, RetFaceConnect>::Element *G = ret_edges.find(e);
if (!G) {
- G=ret_edges.insert(e,RetFaceConnect());
+ G = ret_edges.insert(e, RetFaceConnect());
}
- if (e.vertices[0]==a) {
+ if (e.vertices[0] == a) {
//left
- G->get().left=F;
+ G->get().left = F;
} else {
- G->get().right=F;
+ G->get().right = F;
}
}
}
//fill faces
- for (List<Geometry::MeshData::Face>::Element *E=ret_faces.front();E;E=E->next()) {
+ for (List<Geometry::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
- Geometry::MeshData::Face& f = E->get();
+ Geometry::MeshData::Face &f = E->get();
- for(int i=0;i<f.indices.size();i++) {
+ for (int i = 0; i < f.indices.size(); i++) {
uint32_t a = E->get().indices[i];
- uint32_t b = E->get().indices[(i+1)%f.indices.size()];
- Edge e(a,b);
+ uint32_t b = E->get().indices[(i + 1) % f.indices.size()];
+ Edge e(a, b);
- Map<Edge,RetFaceConnect>::Element *F=ret_edges.find(e);
+ Map<Edge, RetFaceConnect>::Element *F = ret_edges.find(e);
ERR_CONTINUE(!F);
List<Geometry::MeshData::Face>::Element *O = F->get().left == E ? F->get().right : F->get().left;
- ERR_CONTINUE(O==E);
- ERR_CONTINUE(O==NULL);
+ ERR_CONTINUE(O == E);
+ ERR_CONTINUE(O == NULL);
if (O->get().plane.is_almost_like(f.plane)) {
//merge and delete edge and contiguous face, while repointing edges (uuugh!)
int ois = O->get().indices.size();
- int merged=0;
-
+ int merged = 0;
- for(int j=0;j<ois;j++) {
+ for (int j = 0; j < ois; j++) {
//search a
- if (O->get().indices[j]==a) {
+ if (O->get().indices[j] == a) {
//append the rest
- for(int k=0;k<ois;k++) {
+ for (int k = 0; k < ois; k++) {
- int idx = O->get().indices[(k+j)%ois];
- int idxn = O->get().indices[(k+j+1)%ois];
- if (idx==b && idxn==a) {//already have b!
+ int idx = O->get().indices[(k + j) % ois];
+ int idxn = O->get().indices[(k + j + 1) % ois];
+ if (idx == b && idxn == a) { //already have b!
break;
}
- if (idx!=a) {
- f.indices.insert(i+1,idx);
+ if (idx != a) {
+ f.indices.insert(i + 1, idx);
i++;
merged++;
}
- Edge e2(idx,idxn);
+ Edge e2(idx, idxn);
- Map<Edge,RetFaceConnect>::Element *F2=ret_edges.find(e2);
+ Map<Edge, RetFaceConnect>::Element *F2 = ret_edges.find(e2);
ERR_CONTINUE(!F2);
//change faceconnect, point to this face instead
if (F2->get().left == O)
- F2->get().left=E;
+ F2->get().left = E;
else if (F2->get().right == O)
- F2->get().right=E;
-
+ F2->get().right = E;
}
break;
}
}
-
ret_edges.erase(F); //remove the edge
ret_faces.erase(O); //remove the face
-
-
}
-
}
-
}
//fill mesh
@@ -485,26 +448,24 @@ Error QuickHull::build(const Vector<Vector3>& p_points, Geometry::MeshData &r_me
r_mesh.faces.resize(ret_faces.size());
//print_line("FACECOUNT: "+itos(r_mesh.faces.size()));
- int idx=0;
- for (List<Geometry::MeshData::Face>::Element *E=ret_faces.front();E;E=E->next()) {
- r_mesh.faces[idx++]=E->get();
-
-
+ int idx = 0;
+ for (List<Geometry::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
+ r_mesh.faces[idx++] = E->get();
}
r_mesh.edges.resize(ret_edges.size());
- idx=0;
- for(Map<Edge,RetFaceConnect>::Element *E=ret_edges.front();E;E=E->next()) {
+ idx = 0;
+ for (Map<Edge, RetFaceConnect>::Element *E = ret_edges.front(); E; E = E->next()) {
Geometry::MeshData::Edge e;
- e.a=E->key().vertices[0];
- e.b=E->key().vertices[1];
- r_mesh.edges[idx++]=e;
+ e.a = E->key().vertices[0];
+ e.b = E->key().vertices[1];
+ r_mesh.edges[idx++] = e;
}
- r_mesh.vertices=p_points;
+ r_mesh.vertices = p_points;
//r_mesh.optimize_vertices();
-/*
+ /*
print_line("FACES: "+itos(r_mesh.faces.size()));
print_line("EDGES: "+itos(r_mesh.edges.size()));
print_line("VERTICES: "+itos(r_mesh.vertices.size()));
diff --git a/core/math/quick_hull.h b/core/math/quick_hull.h
index 7bd23d31f2..43a802e6bd 100644
--- a/core/math/quick_hull.h
+++ b/core/math/quick_hull.h
@@ -29,16 +29,14 @@
#ifndef QUICK_HULL_H
#define QUICK_HULL_H
+#include "geometry.h"
+#include "list.h"
#include "rect3.h"
#include "set.h"
-#include "list.h"
-#include "geometry.h"
class QuickHull {
public:
-
-
struct Edge {
union {
@@ -46,19 +44,18 @@ public:
uint64_t id;
};
-
- bool operator<(const Edge& p_edge) const {
+ bool operator<(const Edge &p_edge) const {
return id < p_edge.id;
}
- Edge(int p_vtx_a=0,int p_vtx_b=0) {
+ Edge(int p_vtx_a = 0, int p_vtx_b = 0) {
- if (p_vtx_a>p_vtx_b) {
- SWAP(p_vtx_a,p_vtx_b);
+ if (p_vtx_a > p_vtx_b) {
+ SWAP(p_vtx_a, p_vtx_b);
}
- vertices[0]=p_vtx_a;
- vertices[1]=p_vtx_b;
+ vertices[0] = p_vtx_a;
+ vertices[1] = p_vtx_b;
}
};
@@ -68,28 +65,31 @@ public:
int vertices[3];
Vector<int> points_over;
- bool operator<(const Face& p_face) const {
+ bool operator<(const Face &p_face) const {
return points_over.size() < p_face.points_over.size();
}
-
};
-private:
+private:
struct FaceConnect {
- List<Face>::Element *left,*right;
- FaceConnect() { left=NULL; right=NULL; }
+ List<Face>::Element *left, *right;
+ FaceConnect() {
+ left = NULL;
+ right = NULL;
+ }
};
struct RetFaceConnect {
- List<Geometry::MeshData::Face>::Element *left,*right;
- RetFaceConnect() { left=NULL; right=NULL; }
+ List<Geometry::MeshData::Face>::Element *left, *right;
+ RetFaceConnect() {
+ left = NULL;
+ right = NULL;
+ }
};
public:
-
static uint32_t debug_stop_after;
- static Error build(const Vector<Vector3>& p_points,Geometry::MeshData& r_mesh);
-
+ static Error build(const Vector<Vector3> &p_points, Geometry::MeshData &r_mesh);
};
#endif // QUICK_HULL_H
diff --git a/core/math/rect3.cpp b/core/math/rect3.cpp
index d3f95b89e8..c0cd66d9bb 100644
--- a/core/math/rect3.cpp
+++ b/core/math/rect3.cpp
@@ -32,94 +32,87 @@
real_t Rect3::get_area() const {
- return size.x*size.y*size.z;
-
+ return size.x * size.y * size.z;
}
-bool Rect3::operator==(const Rect3& p_rval) const {
-
- return ((pos==p_rval.pos) && (size==p_rval.size));
+bool Rect3::operator==(const Rect3 &p_rval) const {
+ return ((pos == p_rval.pos) && (size == p_rval.size));
}
-bool Rect3::operator!=(const Rect3& p_rval) const {
-
- return ((pos!=p_rval.pos) || (size!=p_rval.size));
+bool Rect3::operator!=(const Rect3 &p_rval) const {
+ return ((pos != p_rval.pos) || (size != p_rval.size));
}
-void Rect3::merge_with(const Rect3& p_aabb) {
+void Rect3::merge_with(const Rect3 &p_aabb) {
- Vector3 beg_1,beg_2;
- Vector3 end_1,end_2;
- Vector3 min,max;
+ Vector3 beg_1, beg_2;
+ Vector3 end_1, end_2;
+ Vector3 min, max;
- beg_1=pos;
- beg_2=p_aabb.pos;
- end_1=Vector3(size.x,size.y,size.z)+beg_1;
- end_2=Vector3(p_aabb.size.x,p_aabb.size.y,p_aabb.size.z)+beg_2;
+ beg_1 = pos;
+ beg_2 = p_aabb.pos;
+ end_1 = Vector3(size.x, size.y, size.z) + beg_1;
+ end_2 = Vector3(p_aabb.size.x, p_aabb.size.y, p_aabb.size.z) + beg_2;
- min.x=(beg_1.x<beg_2.x)?beg_1.x:beg_2.x;
- min.y=(beg_1.y<beg_2.y)?beg_1.y:beg_2.y;
- min.z=(beg_1.z<beg_2.z)?beg_1.z:beg_2.z;
+ min.x = (beg_1.x < beg_2.x) ? beg_1.x : beg_2.x;
+ min.y = (beg_1.y < beg_2.y) ? beg_1.y : beg_2.y;
+ min.z = (beg_1.z < beg_2.z) ? beg_1.z : beg_2.z;
- max.x=(end_1.x>end_2.x)?end_1.x:end_2.x;
- max.y=(end_1.y>end_2.y)?end_1.y:end_2.y;
- max.z=(end_1.z>end_2.z)?end_1.z:end_2.z;
+ max.x = (end_1.x > end_2.x) ? end_1.x : end_2.x;
+ max.y = (end_1.y > end_2.y) ? end_1.y : end_2.y;
+ max.z = (end_1.z > end_2.z) ? end_1.z : end_2.z;
- pos=min;
- size=max-min;
+ pos = min;
+ size = max - min;
}
-Rect3 Rect3::intersection(const Rect3& p_aabb) const {
+Rect3 Rect3::intersection(const Rect3 &p_aabb) const {
- Vector3 src_min=pos;
- Vector3 src_max=pos+size;
- Vector3 dst_min=p_aabb.pos;
- Vector3 dst_max=p_aabb.pos+p_aabb.size;
+ Vector3 src_min = pos;
+ Vector3 src_max = pos + size;
+ Vector3 dst_min = p_aabb.pos;
+ Vector3 dst_max = p_aabb.pos + p_aabb.size;
- Vector3 min,max;
+ Vector3 min, max;
- if (src_min.x > dst_max.x || src_max.x < dst_min.x )
+ if (src_min.x > dst_max.x || src_max.x < dst_min.x)
return Rect3();
else {
- min.x= ( src_min.x > dst_min.x ) ? src_min.x :dst_min.x;
- max.x= ( src_max.x < dst_max.x ) ? src_max.x :dst_max.x;
-
+ min.x = (src_min.x > dst_min.x) ? src_min.x : dst_min.x;
+ max.x = (src_max.x < dst_max.x) ? src_max.x : dst_max.x;
}
- if (src_min.y > dst_max.y || src_max.y < dst_min.y )
+ if (src_min.y > dst_max.y || src_max.y < dst_min.y)
return Rect3();
else {
- min.y= ( src_min.y > dst_min.y ) ? src_min.y :dst_min.y;
- max.y= ( src_max.y < dst_max.y ) ? src_max.y :dst_max.y;
-
+ min.y = (src_min.y > dst_min.y) ? src_min.y : dst_min.y;
+ max.y = (src_max.y < dst_max.y) ? src_max.y : dst_max.y;
}
- if (src_min.z > dst_max.z || src_max.z < dst_min.z )
+ if (src_min.z > dst_max.z || src_max.z < dst_min.z)
return Rect3();
else {
- min.z= ( src_min.z > dst_min.z ) ? src_min.z :dst_min.z;
- max.z= ( src_max.z < dst_max.z ) ? src_max.z :dst_max.z;
-
+ min.z = (src_min.z > dst_min.z) ? src_min.z : dst_min.z;
+ max.z = (src_max.z < dst_max.z) ? src_max.z : dst_max.z;
}
-
- return Rect3( min, max-min );
+ return Rect3(min, max - min);
}
-bool Rect3::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r_clip,Vector3* r_normal) const {
+bool Rect3::intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *r_clip, Vector3 *r_normal) const {
Vector3 c1, c2;
- Vector3 end = pos+size;
- real_t near=-1e20;
- real_t far=1e20;
- int axis=0;
+ Vector3 end = pos + size;
+ real_t near = -1e20;
+ real_t far = 1e20;
+ int axis = 0;
- for (int i=0;i<3;i++){
- if (p_dir[i] == 0){
+ for (int i = 0; i < 3; i++) {
+ if (p_dir[i] == 0) {
if ((p_from[i] < pos[i]) || (p_from[i] > end[i])) {
return false;
}
@@ -127,71 +120,69 @@ bool Rect3::intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3*
c1[i] = (pos[i] - p_from[i]) / p_dir[i];
c2[i] = (end[i] - p_from[i]) / p_dir[i];
- if(c1[i] > c2[i]){
- SWAP(c1,c2);
+ if (c1[i] > c2[i]) {
+ SWAP(c1, c2);
}
- if (c1[i] > near){
+ if (c1[i] > near) {
near = c1[i];
- axis=i;
+ axis = i;
}
- if (c2[i] < far){
+ if (c2[i] < far) {
far = c2[i];
}
- if( (near > far) || (far < 0) ){
+ if ((near > far) || (far < 0)) {
return false;
}
}
}
if (r_clip)
- *r_clip=c1;
+ *r_clip = c1;
if (r_normal) {
- *r_normal=Vector3();
- (*r_normal)[axis]=p_dir[axis]?-1:1;
+ *r_normal = Vector3();
+ (*r_normal)[axis] = p_dir[axis] ? -1 : 1;
}
return true;
-
}
+bool Rect3::intersects_segment(const Vector3 &p_from, const Vector3 &p_to, Vector3 *r_clip, Vector3 *r_normal) const {
-bool Rect3::intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector3* r_clip,Vector3* r_normal) const {
+ real_t min = 0, max = 1;
+ int axis = 0;
+ real_t sign = 0;
- real_t min=0,max=1;
- int axis=0;
- real_t sign=0;
-
- for(int i=0;i<3;i++) {
- real_t seg_from=p_from[i];
- real_t seg_to=p_to[i];
- real_t box_begin=pos[i];
- real_t box_end=box_begin+size[i];
- real_t cmin,cmax;
+ for (int i = 0; i < 3; i++) {
+ real_t seg_from = p_from[i];
+ real_t seg_to = p_to[i];
+ real_t box_begin = pos[i];
+ real_t box_end = box_begin + size[i];
+ real_t cmin, cmax;
real_t csign;
if (seg_from < seg_to) {
if (seg_from > box_end || seg_to < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from < box_begin)?((box_begin - seg_from)/length):0;
- cmax = (seg_to > box_end)?((box_end - seg_from)/length):1;
- csign=-1.0;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
+ cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
+ csign = -1.0;
} else {
if (seg_to > box_end || seg_from < box_begin)
return false;
- real_t length=seg_to-seg_from;
- cmin = (seg_from > box_end)?(box_end - seg_from)/length:0;
- cmax = (seg_to < box_begin)?(box_begin - seg_from)/length:1;
- csign=1.0;
+ real_t length = seg_to - seg_from;
+ cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
+ cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
+ csign = 1.0;
}
if (cmin > min) {
min = cmin;
- axis=i;
- sign=csign;
+ axis = i;
+ sign = csign;
}
if (cmax < max)
max = cmax;
@@ -199,220 +190,210 @@ bool Rect3::intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector
return false;
}
-
- Vector3 rel=p_to-p_from;
+ Vector3 rel = p_to - p_from;
if (r_normal) {
Vector3 normal;
- normal[axis]=sign;
- *r_normal=normal;
+ normal[axis] = sign;
+ *r_normal = normal;
}
if (r_clip)
- *r_clip=p_from+rel*min;
+ *r_clip = p_from + rel * min;
return true;
-
}
-
bool Rect3::intersects_plane(const Plane &p_plane) const {
Vector3 points[8] = {
- Vector3( pos.x , pos.y , pos.z ),
- Vector3( pos.x , pos.y , pos.z+size.z ),
- Vector3( pos.x , pos.y+size.y , pos.z ),
- Vector3( pos.x , pos.y+size.y , pos.z+size.z ),
- Vector3( pos.x+size.x , pos.y , pos.z ),
- Vector3( pos.x+size.x , pos.y , pos.z+size.z ),
- Vector3( pos.x+size.x , pos.y+size.y , pos.z ),
- Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ),
+ Vector3(pos.x, pos.y, pos.z),
+ Vector3(pos.x, pos.y, pos.z + size.z),
+ Vector3(pos.x, pos.y + size.y, pos.z),
+ Vector3(pos.x, pos.y + size.y, pos.z + size.z),
+ Vector3(pos.x + size.x, pos.y, pos.z),
+ Vector3(pos.x + size.x, pos.y, pos.z + size.z),
+ Vector3(pos.x + size.x, pos.y + size.y, pos.z),
+ Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z),
};
- bool over=false;
- bool under=false;
+ bool over = false;
+ bool under = false;
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- if (p_plane.distance_to(points[i])>0)
- over=true;
+ if (p_plane.distance_to(points[i]) > 0)
+ over = true;
else
- under=true;
-
+ under = true;
}
return under && over;
}
-
-
Vector3 Rect3::get_longest_axis() const {
- Vector3 axis(1,0,0);
- real_t max_size=size.x;
+ Vector3 axis(1, 0, 0);
+ real_t max_size = size.x;
- if (size.y > max_size ) {
- axis=Vector3(0,1,0);
- max_size=size.y;
+ if (size.y > max_size) {
+ axis = Vector3(0, 1, 0);
+ max_size = size.y;
}
- if (size.z > max_size ) {
- axis=Vector3(0,0,1);
- max_size=size.z;
+ if (size.z > max_size) {
+ axis = Vector3(0, 0, 1);
+ max_size = size.z;
}
return axis;
}
int Rect3::get_longest_axis_index() const {
- int axis=0;
- real_t max_size=size.x;
+ int axis = 0;
+ real_t max_size = size.x;
- if (size.y > max_size ) {
- axis=1;
- max_size=size.y;
+ if (size.y > max_size) {
+ axis = 1;
+ max_size = size.y;
}
- if (size.z > max_size ) {
- axis=2;
- max_size=size.z;
+ if (size.z > max_size) {
+ axis = 2;
+ max_size = size.z;
}
return axis;
}
-
Vector3 Rect3::get_shortest_axis() const {
- Vector3 axis(1,0,0);
- real_t max_size=size.x;
+ Vector3 axis(1, 0, 0);
+ real_t max_size = size.x;
- if (size.y < max_size ) {
- axis=Vector3(0,1,0);
- max_size=size.y;
+ if (size.y < max_size) {
+ axis = Vector3(0, 1, 0);
+ max_size = size.y;
}
- if (size.z < max_size ) {
- axis=Vector3(0,0,1);
- max_size=size.z;
+ if (size.z < max_size) {
+ axis = Vector3(0, 0, 1);
+ max_size = size.z;
}
return axis;
}
int Rect3::get_shortest_axis_index() const {
- int axis=0;
- real_t max_size=size.x;
+ int axis = 0;
+ real_t max_size = size.x;
- if (size.y < max_size ) {
- axis=1;
- max_size=size.y;
+ if (size.y < max_size) {
+ axis = 1;
+ max_size = size.y;
}
- if (size.z < max_size ) {
- axis=2;
- max_size=size.z;
+ if (size.z < max_size) {
+ axis = 2;
+ max_size = size.z;
}
return axis;
}
-Rect3 Rect3::merge(const Rect3& p_with) const {
+Rect3 Rect3::merge(const Rect3 &p_with) const {
- Rect3 aabb=*this;
+ Rect3 aabb = *this;
aabb.merge_with(p_with);
return aabb;
}
-Rect3 Rect3::expand(const Vector3& p_vector) const {
- Rect3 aabb=*this;
+Rect3 Rect3::expand(const Vector3 &p_vector) const {
+ Rect3 aabb = *this;
aabb.expand_to(p_vector);
return aabb;
-
}
Rect3 Rect3::grow(real_t p_by) const {
- Rect3 aabb=*this;
+ Rect3 aabb = *this;
aabb.grow_by(p_by);
return aabb;
}
-void Rect3::get_edge(int p_edge,Vector3& r_from,Vector3& r_to) const {
+void Rect3::get_edge(int p_edge, Vector3 &r_from, Vector3 &r_to) const {
- ERR_FAIL_INDEX(p_edge,12);
- switch(p_edge) {
+ ERR_FAIL_INDEX(p_edge, 12);
+ switch (p_edge) {
- case 0:{
+ case 0: {
- r_from=Vector3( pos.x+size.x , pos.y , pos.z );
- r_to=Vector3( pos.x , pos.y , pos.z );
+ r_from = Vector3(pos.x + size.x, pos.y, pos.z);
+ r_to = Vector3(pos.x, pos.y, pos.z);
} break;
- case 1:{
+ case 1: {
- r_from=Vector3( pos.x+size.x , pos.y , pos.z+size.z );
- r_to=Vector3( pos.x+size.x , pos.y , pos.z );
+ r_from = Vector3(pos.x + size.x, pos.y, pos.z + size.z);
+ r_to = Vector3(pos.x + size.x, pos.y, pos.z);
} break;
- case 2:{
- r_from=Vector3( pos.x , pos.y , pos.z+size.z );
- r_to=Vector3( pos.x+size.x , pos.y , pos.z+size.z );
+ case 2: {
+ r_from = Vector3(pos.x, pos.y, pos.z + size.z);
+ r_to = Vector3(pos.x + size.x, pos.y, pos.z + size.z);
} break;
- case 3:{
+ case 3: {
- r_from=Vector3( pos.x , pos.y , pos.z );
- r_to=Vector3( pos.x , pos.y , pos.z+size.z );
+ r_from = Vector3(pos.x, pos.y, pos.z);
+ r_to = Vector3(pos.x, pos.y, pos.z + size.z);
} break;
- case 4:{
+ case 4: {
- r_from=Vector3( pos.x , pos.y+size.y , pos.z );
- r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z );
+ r_from = Vector3(pos.x, pos.y + size.y, pos.z);
+ r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z);
} break;
- case 5:{
+ case 5: {
- r_from=Vector3( pos.x+size.x , pos.y+size.y , pos.z );
- r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z );
+ r_from = Vector3(pos.x + size.x, pos.y + size.y, pos.z);
+ r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z);
} break;
- case 6:{
- r_from=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z );
- r_to=Vector3( pos.x , pos.y+size.y , pos.z+size.z );
+ case 6: {
+ r_from = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z);
+ r_to = Vector3(pos.x, pos.y + size.y, pos.z + size.z);
} break;
- case 7:{
+ case 7: {
- r_from=Vector3( pos.x , pos.y+size.y , pos.z+size.z );
- r_to=Vector3( pos.x , pos.y+size.y , pos.z );
+ r_from = Vector3(pos.x, pos.y + size.y, pos.z + size.z);
+ r_to = Vector3(pos.x, pos.y + size.y, pos.z);
} break;
- case 8:{
+ case 8: {
- r_from=Vector3( pos.x , pos.y , pos.z+size.z );
- r_to=Vector3( pos.x , pos.y+size.y , pos.z+size.z );
+ r_from = Vector3(pos.x, pos.y, pos.z + size.z);
+ r_to = Vector3(pos.x, pos.y + size.y, pos.z + size.z);
} break;
- case 9:{
+ case 9: {
- r_from=Vector3( pos.x , pos.y , pos.z );
- r_to=Vector3( pos.x , pos.y+size.y , pos.z );
+ r_from = Vector3(pos.x, pos.y, pos.z);
+ r_to = Vector3(pos.x, pos.y + size.y, pos.z);
} break;
- case 10:{
+ case 10: {
- r_from=Vector3( pos.x+size.x , pos.y , pos.z );
- r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z );
+ r_from = Vector3(pos.x + size.x, pos.y, pos.z);
+ r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z);
} break;
- case 11:{
+ case 11: {
- r_from=Vector3( pos.x+size.x , pos.y , pos.z+size.z );
- r_to=Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z );
+ r_from = Vector3(pos.x + size.x, pos.y, pos.z + size.z);
+ r_to = Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z);
} break;
-
}
-
}
Rect3::operator String() const {
- return String()+pos +" - "+ size;
+ return String() + pos + " - " + size;
}
diff --git a/core/math/rect3.h b/core/math/rect3.h
index 902592b02c..26198537c2 100644
--- a/core/math/rect3.h
+++ b/core/math/rect3.h
@@ -29,19 +29,15 @@
#ifndef AABB_H
#define AABB_H
-
-
-#include "vector3.h"
-#include "plane.h"
#include "math_defs.h"
+#include "plane.h"
+#include "vector3.h"
/**
* AABB / AABB (Axis Aligned Bounding Box)
* This is implemented by a point (pos) and the box size
*/
-
-
class Rect3 {
public:
Vector3 pos;
@@ -50,40 +46,38 @@ public:
real_t get_area() const; /// get area
_FORCE_INLINE_ bool has_no_area() const {
- return (size.x<=CMP_EPSILON || size.y<=CMP_EPSILON || size.z<=CMP_EPSILON);
+ return (size.x <= CMP_EPSILON || size.y <= CMP_EPSILON || size.z <= CMP_EPSILON);
}
_FORCE_INLINE_ bool has_no_surface() const {
- return (size.x<=CMP_EPSILON && size.y<=CMP_EPSILON && size.z<=CMP_EPSILON);
+ return (size.x <= CMP_EPSILON && size.y <= CMP_EPSILON && size.z <= CMP_EPSILON);
}
- const Vector3& get_pos() const { return pos; }
- void set_pos(const Vector3& p_pos) { pos=p_pos; }
- const Vector3& get_size() const { return size; }
- void set_size(const Vector3& p_size) { size=p_size; }
+ const Vector3 &get_pos() const { return pos; }
+ void set_pos(const Vector3 &p_pos) { pos = p_pos; }
+ const Vector3 &get_size() const { return size; }
+ void set_size(const Vector3 &p_size) { size = p_size; }
+ bool operator==(const Rect3 &p_rval) const;
+ bool operator!=(const Rect3 &p_rval) const;
- bool operator==(const Rect3& p_rval) const;
- bool operator!=(const Rect3& p_rval) const;
+ _FORCE_INLINE_ bool intersects(const Rect3 &p_aabb) const; /// Both AABBs overlap
+ _FORCE_INLINE_ bool intersects_inclusive(const Rect3 &p_aabb) const; /// Both AABBs (or their faces) overlap
+ _FORCE_INLINE_ bool encloses(const Rect3 &p_aabb) const; /// p_aabb is completely inside this
- _FORCE_INLINE_ bool intersects(const Rect3& p_aabb) const; /// Both AABBs overlap
- _FORCE_INLINE_ bool intersects_inclusive(const Rect3& p_aabb) const; /// Both AABBs (or their faces) overlap
- _FORCE_INLINE_ bool encloses(const Rect3 & p_aabb) const; /// p_aabb is completely inside this
-
- Rect3 merge(const Rect3& p_with) const;
- void merge_with(const Rect3& p_aabb); ///merge with another AABB
- Rect3 intersection(const Rect3& p_aabb) const; ///get box where two intersect, empty if no intersection occurs
- bool intersects_segment(const Vector3& p_from, const Vector3& p_to,Vector3* r_clip=NULL,Vector3* r_normal=NULL) const;
- bool intersects_ray(const Vector3& p_from, const Vector3& p_dir,Vector3* r_clip=NULL,Vector3* r_normal=NULL) const;
- _FORCE_INLINE_ bool smits_intersect_ray(const Vector3 &from,const Vector3& p_dir, real_t t0, real_t t1) const;
+ Rect3 merge(const Rect3 &p_with) const;
+ void merge_with(const Rect3 &p_aabb); ///merge with another AABB
+ Rect3 intersection(const Rect3 &p_aabb) const; ///get box where two intersect, empty if no intersection occurs
+ bool intersects_segment(const Vector3 &p_from, const Vector3 &p_to, Vector3 *r_clip = NULL, Vector3 *r_normal = NULL) const;
+ bool intersects_ray(const Vector3 &p_from, const Vector3 &p_dir, Vector3 *r_clip = NULL, Vector3 *r_normal = NULL) const;
+ _FORCE_INLINE_ bool smits_intersect_ray(const Vector3 &from, const Vector3 &p_dir, real_t t0, real_t t1) const;
_FORCE_INLINE_ bool intersects_convex_shape(const Plane *p_plane, int p_plane_count) const;
bool intersects_plane(const Plane &p_plane) const;
- _FORCE_INLINE_ bool has_point(const Vector3& p_point) const;
- _FORCE_INLINE_ Vector3 get_support(const Vector3& p_normal) const;
-
+ _FORCE_INLINE_ bool has_point(const Vector3 &p_point) const;
+ _FORCE_INLINE_ Vector3 get_support(const Vector3 &p_normal) const;
Vector3 get_longest_axis() const;
int get_longest_axis_index() const;
@@ -96,98 +90,97 @@ public:
Rect3 grow(real_t p_by) const;
_FORCE_INLINE_ void grow_by(real_t p_amount);
- void get_edge(int p_edge,Vector3& r_from,Vector3& r_to) const;
+ void get_edge(int p_edge, Vector3 &r_from, Vector3 &r_to) const;
_FORCE_INLINE_ Vector3 get_endpoint(int p_point) const;
- Rect3 expand(const Vector3& p_vector) const;
- _FORCE_INLINE_ void project_range_in_plane(const Plane& p_plane,real_t &r_min,real_t& r_max) const;
- _FORCE_INLINE_ void expand_to(const Vector3& p_vector); /** expand to contain a point if necesary */
+ Rect3 expand(const Vector3 &p_vector) const;
+ _FORCE_INLINE_ void project_range_in_plane(const Plane &p_plane, real_t &r_min, real_t &r_max) const;
+ _FORCE_INLINE_ void expand_to(const Vector3 &p_vector); /** expand to contain a point if necesary */
operator String() const;
_FORCE_INLINE_ Rect3() {}
- inline Rect3(const Vector3 &p_pos,const Vector3& p_size) { pos=p_pos; size=p_size; }
+ inline Rect3(const Vector3 &p_pos, const Vector3 &p_size) {
+ pos = p_pos;
+ size = p_size;
+ }
+};
+inline bool Rect3::intersects(const Rect3 &p_aabb) const {
-};
+ if (pos.x >= (p_aabb.pos.x + p_aabb.size.x))
+ return false;
+ if ((pos.x + size.x) <= p_aabb.pos.x)
+ return false;
+ if (pos.y >= (p_aabb.pos.y + p_aabb.size.y))
+ return false;
+ if ((pos.y + size.y) <= p_aabb.pos.y)
+ return false;
+ if (pos.z >= (p_aabb.pos.z + p_aabb.size.z))
+ return false;
+ if ((pos.z + size.z) <= p_aabb.pos.z)
+ return false;
-inline bool Rect3::intersects(const Rect3& p_aabb) const {
-
- if ( pos.x >= (p_aabb.pos.x + p_aabb.size.x) )
- return false;
- if ( (pos.x+size.x) <= p_aabb.pos.x )
- return false;
- if ( pos.y >= (p_aabb.pos.y + p_aabb.size.y) )
- return false;
- if ( (pos.y+size.y) <= p_aabb.pos.y )
- return false;
- if ( pos.z >= (p_aabb.pos.z + p_aabb.size.z) )
- return false;
- if ( (pos.z+size.z) <= p_aabb.pos.z )
- return false;
-
- return true;
+ return true;
}
-inline bool Rect3::intersects_inclusive(const Rect3& p_aabb) const {
-
- if ( pos.x > (p_aabb.pos.x + p_aabb.size.x) )
- return false;
- if ( (pos.x+size.x) < p_aabb.pos.x )
- return false;
- if ( pos.y > (p_aabb.pos.y + p_aabb.size.y) )
- return false;
- if ( (pos.y+size.y) < p_aabb.pos.y )
- return false;
- if ( pos.z > (p_aabb.pos.z + p_aabb.size.z) )
- return false;
- if ( (pos.z+size.z) < p_aabb.pos.z )
- return false;
-
- return true;
+inline bool Rect3::intersects_inclusive(const Rect3 &p_aabb) const {
+
+ if (pos.x > (p_aabb.pos.x + p_aabb.size.x))
+ return false;
+ if ((pos.x + size.x) < p_aabb.pos.x)
+ return false;
+ if (pos.y > (p_aabb.pos.y + p_aabb.size.y))
+ return false;
+ if ((pos.y + size.y) < p_aabb.pos.y)
+ return false;
+ if (pos.z > (p_aabb.pos.z + p_aabb.size.z))
+ return false;
+ if ((pos.z + size.z) < p_aabb.pos.z)
+ return false;
+
+ return true;
}
-inline bool Rect3::encloses(const Rect3 & p_aabb) const {
+inline bool Rect3::encloses(const Rect3 &p_aabb) const {
- Vector3 src_min=pos;
- Vector3 src_max=pos+size;
- Vector3 dst_min=p_aabb.pos;
- Vector3 dst_max=p_aabb.pos+p_aabb.size;
+ Vector3 src_min = pos;
+ Vector3 src_max = pos + size;
+ Vector3 dst_min = p_aabb.pos;
+ Vector3 dst_max = p_aabb.pos + p_aabb.size;
- return (
- (src_min.x <= dst_min.x) &&
+ return (
+ (src_min.x <= dst_min.x) &&
(src_max.x > dst_max.x) &&
(src_min.y <= dst_min.y) &&
(src_max.y > dst_max.y) &&
(src_min.z <= dst_min.z) &&
- (src_max.z > dst_max.z) );
-
+ (src_max.z > dst_max.z));
}
-Vector3 Rect3::get_support(const Vector3& p_normal) const {
+Vector3 Rect3::get_support(const Vector3 &p_normal) const {
Vector3 half_extents = size * 0.5;
Vector3 ofs = pos + half_extents;
return Vector3(
- (p_normal.x>0) ? -half_extents.x : half_extents.x,
- (p_normal.y>0) ? -half_extents.y : half_extents.y,
- (p_normal.z>0) ? -half_extents.z : half_extents.z
- )+ofs;
+ (p_normal.x > 0) ? -half_extents.x : half_extents.x,
+ (p_normal.y > 0) ? -half_extents.y : half_extents.y,
+ (p_normal.z > 0) ? -half_extents.z : half_extents.z) +
+ ofs;
}
-
Vector3 Rect3::get_endpoint(int p_point) const {
- switch(p_point) {
- case 0: return Vector3( pos.x , pos.y , pos.z );
- case 1: return Vector3( pos.x , pos.y , pos.z+size.z );
- case 2: return Vector3( pos.x , pos.y+size.y , pos.z );
- case 3: return Vector3( pos.x , pos.y+size.y , pos.z+size.z );
- case 4: return Vector3( pos.x+size.x , pos.y , pos.z );
- case 5: return Vector3( pos.x+size.x , pos.y , pos.z+size.z );
- case 6: return Vector3( pos.x+size.x , pos.y+size.y , pos.z );
- case 7: return Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z );
+ switch (p_point) {
+ case 0: return Vector3(pos.x, pos.y, pos.z);
+ case 1: return Vector3(pos.x, pos.y, pos.z + size.z);
+ case 2: return Vector3(pos.x, pos.y + size.y, pos.z);
+ case 3: return Vector3(pos.x, pos.y + size.y, pos.z + size.z);
+ case 4: return Vector3(pos.x + size.x, pos.y, pos.z);
+ case 5: return Vector3(pos.x + size.x, pos.y, pos.z + size.z);
+ case 6: return Vector3(pos.x + size.x, pos.y + size.y, pos.z);
+ case 7: return Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z);
};
ERR_FAIL_V(Vector3());
@@ -200,14 +193,13 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co
Vector3 half_extents = size * 0.5;
Vector3 ofs = pos + half_extents;
- for(int i=0;i<p_plane_count;i++) {
- const Plane &p=p_planes[i];
+ for (int i = 0; i < p_plane_count; i++) {
+ const Plane &p = p_planes[i];
Vector3 point(
- (p.normal.x>0) ? -half_extents.x : half_extents.x,
- (p.normal.y>0) ? -half_extents.y : half_extents.y,
- (p.normal.z>0) ? -half_extents.z : half_extents.z
- );
- point+=ofs;
+ (p.normal.x > 0) ? -half_extents.x : half_extents.x,
+ (p.normal.y > 0) ? -half_extents.y : half_extents.y,
+ (p.normal.z > 0) ? -half_extents.z : half_extents.z);
+ point += ofs;
if (p.is_point_over(point))
return false;
}
@@ -215,33 +207,31 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co
return true;
#else
//cache all points to check against!
-// #warning should be easy to optimize, just use the same as when taking the support and use only that point
+ // #warning should be easy to optimize, just use the same as when taking the support and use only that point
Vector3 points[8] = {
- Vector3( pos.x , pos.y , pos.z ),
- Vector3( pos.x , pos.y , pos.z+size.z ),
- Vector3( pos.x , pos.y+size.y , pos.z ),
- Vector3( pos.x , pos.y+size.y , pos.z+size.z ),
- Vector3( pos.x+size.x , pos.y , pos.z ),
- Vector3( pos.x+size.x , pos.y , pos.z+size.z ),
- Vector3( pos.x+size.x , pos.y+size.y , pos.z ),
- Vector3( pos.x+size.x , pos.y+size.y , pos.z+size.z ),
+ Vector3(pos.x, pos.y, pos.z),
+ Vector3(pos.x, pos.y, pos.z + size.z),
+ Vector3(pos.x, pos.y + size.y, pos.z),
+ Vector3(pos.x, pos.y + size.y, pos.z + size.z),
+ Vector3(pos.x + size.x, pos.y, pos.z),
+ Vector3(pos.x + size.x, pos.y, pos.z + size.z),
+ Vector3(pos.x + size.x, pos.y + size.y, pos.z),
+ Vector3(pos.x + size.x, pos.y + size.y, pos.z + size.z),
};
- for (int i=0;i<p_plane_count;i++) { //for each plane
+ for (int i = 0; i < p_plane_count; i++) { //for each plane
- const Plane & plane=p_planes[i];
- bool all_points_over=true;
+ const Plane &plane = p_planes[i];
+ bool all_points_over = true;
//test if it has all points over!
- for (int j=0;j<8;j++) {
-
+ for (int j = 0; j < 8; j++) {
- if (!plane.is_point_over( points[j] )) {
+ if (!plane.is_point_over(points[j])) {
- all_points_over=false;
+ all_points_over = false;
break;
}
-
}
if (all_points_over) {
@@ -253,69 +243,68 @@ bool Rect3::intersects_convex_shape(const Plane *p_planes, int p_plane_count) co
#endif
}
-bool Rect3::has_point(const Vector3& p_point) const {
+bool Rect3::has_point(const Vector3 &p_point) const {
- if (p_point.x<pos.x)
+ if (p_point.x < pos.x)
return false;
- if (p_point.y<pos.y)
+ if (p_point.y < pos.y)
return false;
- if (p_point.z<pos.z)
+ if (p_point.z < pos.z)
return false;
- if (p_point.x>pos.x+size.x)
+ if (p_point.x > pos.x + size.x)
return false;
- if (p_point.y>pos.y+size.y)
+ if (p_point.y > pos.y + size.y)
return false;
- if (p_point.z>pos.z+size.z)
+ if (p_point.z > pos.z + size.z)
return false;
return true;
}
+inline void Rect3::expand_to(const Vector3 &p_vector) {
-inline void Rect3::expand_to(const Vector3& p_vector) {
-
- Vector3 begin=pos;
- Vector3 end=pos+size;
+ Vector3 begin = pos;
+ Vector3 end = pos + size;
- if (p_vector.x<begin.x)
- begin.x=p_vector.x;
- if (p_vector.y<begin.y)
- begin.y=p_vector.y;
- if (p_vector.z<begin.z)
- begin.z=p_vector.z;
+ if (p_vector.x < begin.x)
+ begin.x = p_vector.x;
+ if (p_vector.y < begin.y)
+ begin.y = p_vector.y;
+ if (p_vector.z < begin.z)
+ begin.z = p_vector.z;
- if (p_vector.x>end.x)
- end.x=p_vector.x;
- if (p_vector.y>end.y)
- end.y=p_vector.y;
- if (p_vector.z>end.z)
- end.z=p_vector.z;
+ if (p_vector.x > end.x)
+ end.x = p_vector.x;
+ if (p_vector.y > end.y)
+ end.y = p_vector.y;
+ if (p_vector.z > end.z)
+ end.z = p_vector.z;
- pos=begin;
- size=end-begin;
+ pos = begin;
+ size = end - begin;
}
-void Rect3::project_range_in_plane(const Plane& p_plane,real_t &r_min,real_t& r_max) const {
+void Rect3::project_range_in_plane(const Plane &p_plane, real_t &r_min, real_t &r_max) const {
- Vector3 half_extents( size.x * 0.5, size.y * 0.5, size.z * 0.5 );
- Vector3 center( pos.x + half_extents.x, pos.y + half_extents.y, pos.z + half_extents.z );
+ Vector3 half_extents(size.x * 0.5, size.y * 0.5, size.z * 0.5);
+ Vector3 center(pos.x + half_extents.x, pos.y + half_extents.y, pos.z + half_extents.z);
real_t length = p_plane.normal.abs().dot(half_extents);
- real_t distance = p_plane.distance_to( center );
+ real_t distance = p_plane.distance_to(center);
r_min = distance - length;
r_max = distance + length;
}
inline real_t Rect3::get_longest_axis_size() const {
- real_t max_size=size.x;
+ real_t max_size = size.x;
- if (size.y > max_size ) {
- max_size=size.y;
+ if (size.y > max_size) {
+ max_size = size.y;
}
- if (size.z > max_size ) {
- max_size=size.z;
+ if (size.z > max_size) {
+ max_size = size.z;
}
return max_size;
@@ -323,75 +312,71 @@ inline real_t Rect3::get_longest_axis_size() const {
inline real_t Rect3::get_shortest_axis_size() const {
- real_t max_size=size.x;
+ real_t max_size = size.x;
- if (size.y < max_size ) {
- max_size=size.y;
+ if (size.y < max_size) {
+ max_size = size.y;
}
- if (size.z < max_size ) {
- max_size=size.z;
+ if (size.z < max_size) {
+ max_size = size.z;
}
return max_size;
}
-bool Rect3::smits_intersect_ray(const Vector3 &from,const Vector3& dir, real_t t0, real_t t1) const {
+bool Rect3::smits_intersect_ray(const Vector3 &from, const Vector3 &dir, real_t t0, real_t t1) const {
- real_t divx=1.0/dir.x;
- real_t divy=1.0/dir.y;
- real_t divz=1.0/dir.z;
+ real_t divx = 1.0 / dir.x;
+ real_t divy = 1.0 / dir.y;
+ real_t divz = 1.0 / dir.z;
- Vector3 upbound=pos+size;
+ Vector3 upbound = pos + size;
real_t tmin, tmax, tymin, tymax, tzmin, tzmax;
if (dir.x >= 0) {
tmin = (pos.x - from.x) * divx;
tmax = (upbound.x - from.x) * divx;
- }
- else {
+ } else {
tmin = (upbound.x - from.x) * divx;
tmax = (pos.x - from.x) * divx;
}
if (dir.y >= 0) {
tymin = (pos.y - from.y) * divy;
tymax = (upbound.y - from.y) * divy;
- }
- else {
+ } else {
tymin = (upbound.y - from.y) * divy;
tymax = (pos.y - from.y) * divy;
}
- if ( (tmin > tymax) || (tymin > tmax) )
+ if ((tmin > tymax) || (tymin > tmax))
return false;
if (tymin > tmin)
- tmin = tymin;
+ tmin = tymin;
if (tymax < tmax)
tmax = tymax;
if (dir.z >= 0) {
tzmin = (pos.z - from.z) * divz;
tzmax = (upbound.z - from.z) * divz;
- }
- else {
+ } else {
tzmin = (upbound.z - from.z) * divz;
tzmax = (pos.z - from.z) * divz;
}
- if ( (tmin > tzmax) || (tzmin > tmax) )
+ if ((tmin > tzmax) || (tzmin > tmax))
return false;
if (tzmin > tmin)
tmin = tzmin;
if (tzmax < tmax)
tmax = tzmax;
- return ( (tmin < t1) && (tmax > t0) );
+ return ((tmin < t1) && (tmax > t0));
}
void Rect3::grow_by(real_t p_amount) {
- pos.x-=p_amount;
- pos.y-=p_amount;
- pos.z-=p_amount;
- size.x+=2.0*p_amount;
- size.y+=2.0*p_amount;
- size.z+=2.0*p_amount;
+ pos.x -= p_amount;
+ pos.y -= p_amount;
+ pos.z -= p_amount;
+ size.x += 2.0 * p_amount;
+ size.y += 2.0 * p_amount;
+ size.z += 2.0 * p_amount;
}
-
#endif // AABB_H
diff --git a/core/math/transform.cpp b/core/math/transform.cpp
index 6d9324c176..d35938e559 100644
--- a/core/math/transform.cpp
+++ b/core/math/transform.cpp
@@ -31,7 +31,6 @@
#include "os/copymem.h"
#include "print_string.h"
-
void Transform::affine_invert() {
basis.invert();
@@ -40,13 +39,11 @@ void Transform::affine_invert() {
Transform Transform::affine_inverse() const {
- Transform ret=*this;
+ Transform ret = *this;
ret.affine_invert();
return ret;
-
}
-
void Transform::invert() {
basis.transpose();
@@ -56,35 +53,34 @@ void Transform::invert() {
Transform Transform::inverse() const {
// FIXME: this function assumes the basis is a rotation matrix, with no scaling.
// Transform::affine_inverse can handle matrices with scaling, so GDScript should eventually use that.
- Transform ret=*this;
+ Transform ret = *this;
ret.invert();
return ret;
}
-
-void Transform::rotate(const Vector3& p_axis,real_t p_phi) {
+void Transform::rotate(const Vector3 &p_axis, real_t p_phi) {
*this = rotated(p_axis, p_phi);
}
-Transform Transform::rotated(const Vector3& p_axis,real_t p_phi) const{
+Transform Transform::rotated(const Vector3 &p_axis, real_t p_phi) const {
- return Transform(Basis( p_axis, p_phi ), Vector3()) * (*this);
+ return Transform(Basis(p_axis, p_phi), Vector3()) * (*this);
}
-void Transform::rotate_basis(const Vector3& p_axis,real_t p_phi) {
+void Transform::rotate_basis(const Vector3 &p_axis, real_t p_phi) {
- basis.rotate(p_axis,p_phi);
+ basis.rotate(p_axis, p_phi);
}
-Transform Transform::looking_at( const Vector3& p_target, const Vector3& p_up ) const {
+Transform Transform::looking_at(const Vector3 &p_target, const Vector3 &p_up) const {
Transform t = *this;
- t.set_look_at(origin,p_target,p_up);
+ t.set_look_at(origin, p_target, p_up);
return t;
}
-void Transform::set_look_at( const Vector3& p_eye, const Vector3& p_target, const Vector3& p_up ) {
+void Transform::set_look_at(const Vector3 &p_eye, const Vector3 &p_target, const Vector3 &p_up) {
// Reference: MESA source code
Vector3 v_x, v_y, v_z;
@@ -98,23 +94,21 @@ void Transform::set_look_at( const Vector3& p_eye, const Vector3& p_target, cons
v_y = p_up;
-
- v_x=v_y.cross(v_z);
+ v_x = v_y.cross(v_z);
/* Recompute Y = Z cross X */
- v_y=v_z.cross(v_x);
+ v_y = v_z.cross(v_x);
v_x.normalize();
v_y.normalize();
- basis.set_axis(0,v_x);
- basis.set_axis(1,v_y);
- basis.set_axis(2,v_z);
- origin=p_eye;
-
+ basis.set_axis(0, v_x);
+ basis.set_axis(1, v_y);
+ basis.set_axis(2, v_z);
+ origin = p_eye;
}
-Transform Transform::interpolate_with(const Transform& p_transform, real_t p_c) const {
+Transform Transform::interpolate_with(const Transform &p_transform, real_t p_c) const {
/* not sure if very "efficient" but good enough? */
@@ -127,45 +121,44 @@ Transform Transform::interpolate_with(const Transform& p_transform, real_t p_c)
Vector3 dst_loc = p_transform.origin;
Transform dst;
- dst.basis=src_rot.slerp(dst_rot,p_c);
- dst.basis.scale(src_scale.linear_interpolate(dst_scale,p_c));
- dst.origin=src_loc.linear_interpolate(dst_loc,p_c);
+ dst.basis = src_rot.slerp(dst_rot, p_c);
+ dst.basis.scale(src_scale.linear_interpolate(dst_scale, p_c));
+ dst.origin = src_loc.linear_interpolate(dst_loc, p_c);
return dst;
}
-void Transform::scale(const Vector3& p_scale) {
+void Transform::scale(const Vector3 &p_scale) {
basis.scale(p_scale);
- origin*=p_scale;
+ origin *= p_scale;
}
-Transform Transform::scaled(const Vector3& p_scale) const {
+Transform Transform::scaled(const Vector3 &p_scale) const {
Transform t = *this;
t.scale(p_scale);
return t;
}
-void Transform::scale_basis(const Vector3& p_scale) {
+void Transform::scale_basis(const Vector3 &p_scale) {
basis.scale(p_scale);
}
-void Transform::translate( real_t p_tx, real_t p_ty, real_t p_tz) {
- translate( Vector3(p_tx,p_ty,p_tz) );
-
+void Transform::translate(real_t p_tx, real_t p_ty, real_t p_tz) {
+ translate(Vector3(p_tx, p_ty, p_tz));
}
-void Transform::translate( const Vector3& p_translation ) {
+void Transform::translate(const Vector3 &p_translation) {
- for( int i = 0; i < 3; i++ ) {
+ for (int i = 0; i < 3; i++) {
origin[i] += basis[i].dot(p_translation);
}
}
-Transform Transform::translated( const Vector3& p_translation ) const {
+Transform Transform::translated(const Vector3 &p_translation) const {
- Transform t=*this;
+ Transform t = *this;
t.translate(p_translation);
return t;
}
@@ -182,25 +175,25 @@ Transform Transform::orthonormalized() const {
return _copy;
}
-bool Transform::operator==(const Transform& p_transform) const {
+bool Transform::operator==(const Transform &p_transform) const {
- return (basis==p_transform.basis && origin==p_transform.origin);
+ return (basis == p_transform.basis && origin == p_transform.origin);
}
-bool Transform::operator!=(const Transform& p_transform) const {
+bool Transform::operator!=(const Transform &p_transform) const {
- return (basis!=p_transform.basis || origin!=p_transform.origin);
+ return (basis != p_transform.basis || origin != p_transform.origin);
}
-void Transform::operator*=(const Transform& p_transform) {
+void Transform::operator*=(const Transform &p_transform) {
- origin=xform(p_transform.origin);
- basis*=p_transform.basis;
+ origin = xform(p_transform.origin);
+ basis *= p_transform.basis;
}
-Transform Transform::operator*(const Transform& p_transform) const {
+Transform Transform::operator*(const Transform &p_transform) const {
- Transform t=*this;
- t*=p_transform;
+ Transform t = *this;
+ t *= p_transform;
return t;
}
@@ -209,11 +202,8 @@ Transform::operator String() const {
return basis.operator String() + " - " + origin.operator String();
}
+Transform::Transform(const Basis &p_basis, const Vector3 &p_origin) {
-Transform::Transform(const Basis& p_basis, const Vector3& p_origin) {
-
- basis=p_basis;
- origin=p_origin;
+ basis = p_basis;
+ origin = p_origin;
}
-
-
diff --git a/core/math/transform.h b/core/math/transform.h
index 45d7b2a12c..e307aba129 100644
--- a/core/math/transform.h
+++ b/core/math/transform.h
@@ -37,7 +37,6 @@
*/
class Transform {
public:
-
Basis basis;
Vector3 origin;
@@ -47,199 +46,187 @@ public:
void affine_invert();
Transform affine_inverse() const;
- Transform rotated(const Vector3& p_axis,real_t p_phi) const;
+ Transform rotated(const Vector3 &p_axis, real_t p_phi) const;
- void rotate(const Vector3& p_axis,real_t p_phi);
- void rotate_basis(const Vector3& p_axis,real_t p_phi);
+ void rotate(const Vector3 &p_axis, real_t p_phi);
+ void rotate_basis(const Vector3 &p_axis, real_t p_phi);
- void set_look_at( const Vector3& p_eye, const Vector3& p_target, const Vector3& p_up );
- Transform looking_at( const Vector3& p_target, const Vector3& p_up ) const;
+ void set_look_at(const Vector3 &p_eye, const Vector3 &p_target, const Vector3 &p_up);
+ Transform looking_at(const Vector3 &p_target, const Vector3 &p_up) const;
- void scale(const Vector3& p_scale);
- Transform scaled(const Vector3& p_scale) const;
- void scale_basis(const Vector3& p_scale);
- void translate( real_t p_tx, real_t p_ty, real_t p_tz );
- void translate( const Vector3& p_translation );
- Transform translated( const Vector3& p_translation ) const;
+ void scale(const Vector3 &p_scale);
+ Transform scaled(const Vector3 &p_scale) const;
+ void scale_basis(const Vector3 &p_scale);
+ void translate(real_t p_tx, real_t p_ty, real_t p_tz);
+ void translate(const Vector3 &p_translation);
+ Transform translated(const Vector3 &p_translation) const;
- const Basis& get_basis() const { return basis; }
- void set_basis(const Basis& p_basis) { basis=p_basis; }
+ const Basis &get_basis() const { return basis; }
+ void set_basis(const Basis &p_basis) { basis = p_basis; }
- const Vector3& get_origin() const { return origin; }
- void set_origin(const Vector3& p_origin) { origin=p_origin; }
+ const Vector3 &get_origin() const { return origin; }
+ void set_origin(const Vector3 &p_origin) { origin = p_origin; }
void orthonormalize();
Transform orthonormalized() const;
- bool operator==(const Transform& p_transform) const;
- bool operator!=(const Transform& p_transform) const;
+ bool operator==(const Transform &p_transform) const;
+ bool operator!=(const Transform &p_transform) const;
- _FORCE_INLINE_ Vector3 xform(const Vector3& p_vector) const;
- _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vector) const;
+ _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vector) const;
+ _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vector) const;
- _FORCE_INLINE_ Plane xform(const Plane& p_plane) const;
- _FORCE_INLINE_ Plane xform_inv(const Plane& p_plane) const;
+ _FORCE_INLINE_ Plane xform(const Plane &p_plane) const;
+ _FORCE_INLINE_ Plane xform_inv(const Plane &p_plane) const;
- _FORCE_INLINE_ Rect3 xform(const Rect3& p_aabb) const;
- _FORCE_INLINE_ Rect3 xform_inv(const Rect3& p_aabb) const;
+ _FORCE_INLINE_ Rect3 xform(const Rect3 &p_aabb) const;
+ _FORCE_INLINE_ Rect3 xform_inv(const Rect3 &p_aabb) const;
- void operator*=(const Transform& p_transform);
- Transform operator*(const Transform& p_transform) const;
+ void operator*=(const Transform &p_transform);
+ Transform operator*(const Transform &p_transform) const;
- Transform interpolate_with(const Transform& p_transform, real_t p_c) const;
+ Transform interpolate_with(const Transform &p_transform, real_t p_c) const;
- _FORCE_INLINE_ Transform inverse_xform(const Transform& t) const {
+ _FORCE_INLINE_ Transform inverse_xform(const Transform &t) const {
Vector3 v = t.origin - origin;
return Transform(basis.transpose_xform(t.basis),
- basis.xform(v));
+ basis.xform(v));
}
- void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz,real_t tx, real_t ty, real_t tz) {
-
- basis.elements[0][0]=xx;
- basis.elements[0][1]=xy;
- basis.elements[0][2]=xz;
- basis.elements[1][0]=yx;
- basis.elements[1][1]=yy;
- basis.elements[1][2]=yz;
- basis.elements[2][0]=zx;
- basis.elements[2][1]=zy;
- basis.elements[2][2]=zz;
- origin.x=tx;
- origin.y=ty;
- origin.z=tz;
+ void set(real_t xx, real_t xy, real_t xz, real_t yx, real_t yy, real_t yz, real_t zx, real_t zy, real_t zz, real_t tx, real_t ty, real_t tz) {
+
+ basis.elements[0][0] = xx;
+ basis.elements[0][1] = xy;
+ basis.elements[0][2] = xz;
+ basis.elements[1][0] = yx;
+ basis.elements[1][1] = yy;
+ basis.elements[1][2] = yz;
+ basis.elements[2][0] = zx;
+ basis.elements[2][1] = zy;
+ basis.elements[2][2] = zz;
+ origin.x = tx;
+ origin.y = ty;
+ origin.z = tz;
}
operator String() const;
- Transform(const Basis& p_basis, const Vector3& p_origin=Vector3());
+ Transform(const Basis &p_basis, const Vector3 &p_origin = Vector3());
Transform() {}
-
};
-
-_FORCE_INLINE_ Vector3 Transform::xform(const Vector3& p_vector) const {
+_FORCE_INLINE_ Vector3 Transform::xform(const Vector3 &p_vector) const {
return Vector3(
- basis[0].dot(p_vector)+origin.x,
- basis[1].dot(p_vector)+origin.y,
- basis[2].dot(p_vector)+origin.z
- );
+ basis[0].dot(p_vector) + origin.x,
+ basis[1].dot(p_vector) + origin.y,
+ basis[2].dot(p_vector) + origin.z);
}
-_FORCE_INLINE_ Vector3 Transform::xform_inv(const Vector3& p_vector) const {
+_FORCE_INLINE_ Vector3 Transform::xform_inv(const Vector3 &p_vector) const {
Vector3 v = p_vector - origin;
return Vector3(
- (basis.elements[0][0]*v.x ) + ( basis.elements[1][0]*v.y ) + ( basis.elements[2][0]*v.z ),
- (basis.elements[0][1]*v.x ) + ( basis.elements[1][1]*v.y ) + ( basis.elements[2][1]*v.z ),
- (basis.elements[0][2]*v.x ) + ( basis.elements[1][2]*v.y ) + ( basis.elements[2][2]*v.z )
- );
+ (basis.elements[0][0] * v.x) + (basis.elements[1][0] * v.y) + (basis.elements[2][0] * v.z),
+ (basis.elements[0][1] * v.x) + (basis.elements[1][1] * v.y) + (basis.elements[2][1] * v.z),
+ (basis.elements[0][2] * v.x) + (basis.elements[1][2] * v.y) + (basis.elements[2][2] * v.z));
}
-_FORCE_INLINE_ Plane Transform::xform(const Plane& p_plane) const {
+_FORCE_INLINE_ Plane Transform::xform(const Plane &p_plane) const {
+ Vector3 point = p_plane.normal * p_plane.d;
+ Vector3 point_dir = point + p_plane.normal;
+ point = xform(point);
+ point_dir = xform(point_dir);
- Vector3 point=p_plane.normal*p_plane.d;
- Vector3 point_dir=point+p_plane.normal;
- point=xform(point);
- point_dir=xform(point_dir);
-
- Vector3 normal=point_dir-point;
+ Vector3 normal = point_dir - point;
normal.normalize();
- real_t d=normal.dot(point);
-
- return Plane(normal,d);
+ real_t d = normal.dot(point);
+ return Plane(normal, d);
}
-_FORCE_INLINE_ Plane Transform::xform_inv(const Plane& p_plane) const {
+_FORCE_INLINE_ Plane Transform::xform_inv(const Plane &p_plane) const {
- Vector3 point=p_plane.normal*p_plane.d;
- Vector3 point_dir=point+p_plane.normal;
+ Vector3 point = p_plane.normal * p_plane.d;
+ Vector3 point_dir = point + p_plane.normal;
xform_inv(point);
xform_inv(point_dir);
- Vector3 normal=point_dir-point;
+ Vector3 normal = point_dir - point;
normal.normalize();
- real_t d=normal.dot(point);
-
- return Plane(normal,d);
+ real_t d = normal.dot(point);
+ return Plane(normal, d);
}
-_FORCE_INLINE_ Rect3 Transform::xform(const Rect3& p_aabb) const {
- /* define vertices */
+_FORCE_INLINE_ Rect3 Transform::xform(const Rect3 &p_aabb) const {
+/* define vertices */
#if 1
- Vector3 x=basis.get_axis(0)*p_aabb.size.x;
- Vector3 y=basis.get_axis(1)*p_aabb.size.y;
- Vector3 z=basis.get_axis(2)*p_aabb.size.z;
- Vector3 pos = xform( p_aabb.pos );
-//could be even further optimized
+ Vector3 x = basis.get_axis(0) * p_aabb.size.x;
+ Vector3 y = basis.get_axis(1) * p_aabb.size.y;
+ Vector3 z = basis.get_axis(2) * p_aabb.size.z;
+ Vector3 pos = xform(p_aabb.pos);
+ //could be even further optimized
Rect3 new_aabb;
- new_aabb.pos=pos;
- new_aabb.expand_to( pos+x );
- new_aabb.expand_to( pos+y );
- new_aabb.expand_to( pos+z );
- new_aabb.expand_to( pos+x+y );
- new_aabb.expand_to( pos+x+z );
- new_aabb.expand_to( pos+y+z );
- new_aabb.expand_to( pos+x+y+z );
+ new_aabb.pos = pos;
+ new_aabb.expand_to(pos + x);
+ new_aabb.expand_to(pos + y);
+ new_aabb.expand_to(pos + z);
+ new_aabb.expand_to(pos + x + y);
+ new_aabb.expand_to(pos + x + z);
+ new_aabb.expand_to(pos + y + z);
+ new_aabb.expand_to(pos + x + y + z);
return new_aabb;
#else
-
- Vector3 vertices[8]={
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z)
+ Vector3 vertices[8] = {
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z)
};
-
AABB ret;
- ret.pos=xform(vertices[0]);
+ ret.pos = xform(vertices[0]);
- for (int i=1;i<8;i++) {
+ for (int i = 1; i < 8; i++) {
- ret.expand_to( xform(vertices[i]) );
+ ret.expand_to(xform(vertices[i]));
}
return ret;
#endif
-
}
-_FORCE_INLINE_ Rect3 Transform::xform_inv(const Rect3& p_aabb) const {
+_FORCE_INLINE_ Rect3 Transform::xform_inv(const Rect3 &p_aabb) const {
/* define vertices */
- Vector3 vertices[8]={
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z),
- Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z)
+ Vector3 vertices[8] = {
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z),
+ Vector3(p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z)
};
-
Rect3 ret;
- ret.pos=xform_inv(vertices[0]);
+ ret.pos = xform_inv(vertices[0]);
- for (int i=1;i<8;i++) {
+ for (int i = 1; i < 8; i++) {
- ret.expand_to( xform_inv(vertices[i]) );
+ ret.expand_to(xform_inv(vertices[i]));
}
return ret;
-
}
#ifdef OPTIMIZED_TRANSFORM_IMPL_OVERRIDE
@@ -250,16 +237,16 @@ struct OptimizedTransform {
Transform transform;
- _FORCE_INLINE_ void invert() {transform.invert(); }
- _FORCE_INLINE_ void affine_invert() {transform.affine_invert(); }
- _FORCE_INLINE_ Vector3 xform(const Vector3& p_vec) const { return transform.xform(p_vec); };
- _FORCE_INLINE_ Vector3 xform_inv(const Vector3& p_vec) const { return transform.xform_inv(p_vec); };
- _FORCE_INLINE_ OptimizedTransform operator*(const OptimizedTransform& p_ot ) const { return OptimizedTransform( transform * p_ot.transform ) ; }
+ _FORCE_INLINE_ void invert() { transform.invert(); }
+ _FORCE_INLINE_ void affine_invert() { transform.affine_invert(); }
+ _FORCE_INLINE_ Vector3 xform(const Vector3 &p_vec) const { return transform.xform(p_vec); };
+ _FORCE_INLINE_ Vector3 xform_inv(const Vector3 &p_vec) const { return transform.xform_inv(p_vec); };
+ _FORCE_INLINE_ OptimizedTransform operator*(const OptimizedTransform &p_ot) const { return OptimizedTransform(transform * p_ot.transform); }
_FORCE_INLINE_ Transform get_transform() const { return transform; }
- _FORCE_INLINE_ void set_transform(const Transform& p_transform) { transform=p_transform; }
+ _FORCE_INLINE_ void set_transform(const Transform &p_transform) { transform = p_transform; }
- OptimizedTransform(const Transform& p_transform) {
- transform=p_transform;
+ OptimizedTransform(const Transform &p_transform) {
+ transform = p_transform;
}
};
diff --git a/core/math/triangle_mesh.cpp b/core/math/triangle_mesh.cpp
index 247cb90a48..93c6b2786e 100644
--- a/core/math/triangle_mesh.cpp
+++ b/core/math/triangle_mesh.cpp
@@ -29,81 +29,73 @@
#include "triangle_mesh.h"
#include "sort.h"
+int TriangleMesh::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &max_depth, int &max_alloc) {
-
-int TriangleMesh::_create_bvh(BVH*p_bvh,BVH** p_bb,int p_from,int p_size,int p_depth,int&max_depth,int&max_alloc) {
-
-
- if (p_depth>max_depth) {
- max_depth=p_depth;
+ if (p_depth > max_depth) {
+ max_depth = p_depth;
}
- if (p_size==1) {
+ if (p_size == 1) {
-
- return p_bb[p_from]-p_bvh;
- } else if (p_size==0) {
+ return p_bb[p_from] - p_bvh;
+ } else if (p_size == 0) {
return -1;
}
-
Rect3 aabb;
- aabb=p_bb[p_from]->aabb;
- for(int i=1;i<p_size;i++) {
+ aabb = p_bb[p_from]->aabb;
+ for (int i = 1; i < p_size; i++) {
- aabb.merge_with(p_bb[p_from+i]->aabb);
+ aabb.merge_with(p_bb[p_from + i]->aabb);
}
- int li=aabb.get_longest_axis_index();
+ int li = aabb.get_longest_axis_index();
- switch(li) {
+ switch (li) {
case Vector3::AXIS_X: {
- SortArray<BVH*,BVHCmpX> sort_x;
- sort_x.nth_element(0,p_size,p_size/2,&p_bb[p_from]);
+ SortArray<BVH *, BVHCmpX> sort_x;
+ sort_x.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
//sort_x.sort(&p_bb[p_from],p_size);
} break;
case Vector3::AXIS_Y: {
- SortArray<BVH*,BVHCmpY> sort_y;
- sort_y.nth_element(0,p_size,p_size/2,&p_bb[p_from]);
+ SortArray<BVH *, BVHCmpY> sort_y;
+ sort_y.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
//sort_y.sort(&p_bb[p_from],p_size);
} break;
case Vector3::AXIS_Z: {
- SortArray<BVH*,BVHCmpZ> sort_z;
- sort_z.nth_element(0,p_size,p_size/2,&p_bb[p_from]);
+ SortArray<BVH *, BVHCmpZ> sort_z;
+ sort_z.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
//sort_z.sort(&p_bb[p_from],p_size);
} break;
}
+ int left = _create_bvh(p_bvh, p_bb, p_from, p_size / 2, p_depth + 1, max_depth, max_alloc);
+ int right = _create_bvh(p_bvh, p_bb, p_from + p_size / 2, p_size - p_size / 2, p_depth + 1, max_depth, max_alloc);
- int left = _create_bvh(p_bvh,p_bb,p_from,p_size/2,p_depth+1,max_depth,max_alloc);
- int right = _create_bvh(p_bvh,p_bb,p_from+p_size/2,p_size-p_size/2,p_depth+1,max_depth,max_alloc);
-
- int index=max_alloc++;
+ int index = max_alloc++;
BVH *_new = &p_bvh[index];
- _new->aabb=aabb;
- _new->center=aabb.pos+aabb.size*0.5;
- _new->face_index=-1;
- _new->left=left;
- _new->right=right;
+ _new->aabb = aabb;
+ _new->center = aabb.pos + aabb.size * 0.5;
+ _new->face_index = -1;
+ _new->left = left;
+ _new->right = right;
return index;
-
}
+void TriangleMesh::create(const PoolVector<Vector3> &p_faces) {
-void TriangleMesh::create(const PoolVector<Vector3>& p_faces) {
+ valid = false;
- valid=false;
-
- int fc=p_faces.size();
- ERR_FAIL_COND(!fc || ((fc%3) != 0));
- fc/=3;
+ int fc = p_faces.size();
+ ERR_FAIL_COND(!fc || ((fc % 3) != 0));
+ fc /= 3;
triangles.resize(fc);
- bvh.resize(fc*3); //will never be larger than this (todo make better)
+ bvh.resize(fc * 3); //will never be larger than this (todo make better)
PoolVector<BVH>::Write bw = bvh.write();
{
@@ -114,148 +106,143 @@ void TriangleMesh::create(const PoolVector<Vector3>& p_faces) {
PoolVector<Vector3>::Read r = p_faces.read();
PoolVector<Triangle>::Write w = triangles.write();
- Map<Vector3,int> db;
+ Map<Vector3, int> db;
- for(int i=0;i<fc;i++) {
+ for (int i = 0; i < fc; i++) {
- Triangle&f=w[i];
- const Vector3 *v=&r[i*3];
+ Triangle &f = w[i];
+ const Vector3 *v = &r[i * 3];
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- int vidx=-1;
- Vector3 vs=v[j].snapped(0.0001);
- Map<Vector3,int>::Element *E=db.find(vs);
+ int vidx = -1;
+ Vector3 vs = v[j].snapped(0.0001);
+ Map<Vector3, int>::Element *E = db.find(vs);
if (E) {
- vidx=E->get();
+ vidx = E->get();
} else {
- vidx=db.size();
- db[vs]=vidx;
+ vidx = db.size();
+ db[vs] = vidx;
}
- f.indices[j]=vidx;
- if (j==0)
- bw[i].aabb.pos=vs;
+ f.indices[j] = vidx;
+ if (j == 0)
+ bw[i].aabb.pos = vs;
else
bw[i].aabb.expand_to(vs);
}
- f.normal=Face3(r[i*3+0],r[i*3+1],r[i*3+2]).get_plane().get_normal();
+ f.normal = Face3(r[i * 3 + 0], r[i * 3 + 1], r[i * 3 + 2]).get_plane().get_normal();
- bw[i].left=-1;
- bw[i].right=-1;
- bw[i].face_index=i;
- bw[i].center=bw[i].aabb.pos+bw[i].aabb.size*0.5;
+ bw[i].left = -1;
+ bw[i].right = -1;
+ bw[i].face_index = i;
+ bw[i].center = bw[i].aabb.pos + bw[i].aabb.size * 0.5;
}
vertices.resize(db.size());
PoolVector<Vector3>::Write vw = vertices.write();
- for (Map<Vector3,int>::Element *E=db.front();E;E=E->next()) {
- vw[E->get()]=E->key();
+ for (Map<Vector3, int>::Element *E = db.front(); E; E = E->next()) {
+ vw[E->get()] = E->key();
}
-
}
- PoolVector<BVH*> bwptrs;
+ PoolVector<BVH *> bwptrs;
bwptrs.resize(fc);
- PoolVector<BVH*>::Write bwp = bwptrs.write();
- for(int i=0;i<fc;i++) {
+ PoolVector<BVH *>::Write bwp = bwptrs.write();
+ for (int i = 0; i < fc; i++) {
- bwp[i]=&bw[i];
+ bwp[i] = &bw[i];
}
- max_depth=0;
- int max_alloc=fc;
- int max=_create_bvh(bw.ptr(),bwp.ptr(),0,fc,1,max_depth,max_alloc);
+ max_depth = 0;
+ int max_alloc = fc;
+ int max = _create_bvh(bw.ptr(), bwp.ptr(), 0, fc, 1, max_depth, max_alloc);
- bw=PoolVector<BVH>::Write(); //clearup
+ bw = PoolVector<BVH>::Write(); //clearup
bvh.resize(max_alloc); //resize back
- valid=true;
-
+ valid = true;
}
+Vector3 TriangleMesh::get_area_normal(const Rect3 &p_aabb) const {
-Vector3 TriangleMesh::get_area_normal(const Rect3& p_aabb) const {
-
- uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth);
+ uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
enum {
- TEST_AABB_BIT=0,
- VISIT_LEFT_BIT=1,
- VISIT_RIGHT_BIT=2,
- VISIT_DONE_BIT=3,
- VISITED_BIT_SHIFT=29,
- NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1,
- VISITED_BIT_MASK=~NODE_IDX_MASK,
-
+ TEST_AABB_BIT = 0,
+ VISIT_LEFT_BIT = 1,
+ VISIT_RIGHT_BIT = 2,
+ VISIT_DONE_BIT = 3,
+ VISITED_BIT_SHIFT = 29,
+ NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
+ VISITED_BIT_MASK = ~NODE_IDX_MASK,
};
- int n_count=0;
+ int n_count = 0;
Vector3 n;
- int level=0;
+ int level = 0;
PoolVector<Triangle>::Read trianglesr = triangles.read();
- PoolVector<Vector3>::Read verticesr=vertices.read();
- PoolVector<BVH>::Read bvhr=bvh.read();
+ PoolVector<Vector3>::Read verticesr = vertices.read();
+ PoolVector<BVH>::Read bvhr = bvh.read();
- const Triangle *triangleptr=trianglesr.ptr();
- int pos=bvh.size()-1;
+ const Triangle *triangleptr = trianglesr.ptr();
+ int pos = bvh.size() - 1;
const BVH *bvhptr = bvhr.ptr();
- stack[0]=pos;
- while(true) {
+ stack[0] = pos;
+ while (true) {
- uint32_t node = stack[level]&NODE_IDX_MASK;
- const BVH &b = bvhptr[ node ];
- bool done=false;
+ uint32_t node = stack[level] & NODE_IDX_MASK;
+ const BVH &b = bvhptr[node];
+ bool done = false;
- switch(stack[level]>>VISITED_BIT_SHIFT) {
+ switch (stack[level] >> VISITED_BIT_SHIFT) {
case TEST_AABB_BIT: {
-
bool valid = b.aabb.intersects(p_aabb);
if (!valid) {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- if (b.face_index>=0) {
+ if (b.face_index >= 0) {
- const Triangle &s=triangleptr[ b.face_index ];
- n+=s.normal;
+ const Triangle &s = triangleptr[b.face_index];
+ n += s.normal;
n_count++;
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
}
}
continue;
}
case VISIT_LEFT_BIT: {
- stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.left|TEST_AABB_BIT;
+ stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.left | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_RIGHT_BIT: {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.right|TEST_AABB_BIT;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.right | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_DONE_BIT: {
- if (level==0) {
- done=true;
+ if (level == 0) {
+ done = true;
break;
} else
level--;
@@ -263,121 +250,111 @@ Vector3 TriangleMesh::get_area_normal(const Rect3& p_aabb) const {
}
}
-
if (done)
break;
}
-
- if (n_count>0)
- n/=n_count;
+ if (n_count > 0)
+ n /= n_count;
return n;
-
}
+bool TriangleMesh::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const {
-bool TriangleMesh::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const {
-
-
- uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth);
+ uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
enum {
- TEST_AABB_BIT=0,
- VISIT_LEFT_BIT=1,
- VISIT_RIGHT_BIT=2,
- VISIT_DONE_BIT=3,
- VISITED_BIT_SHIFT=29,
- NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1,
- VISITED_BIT_MASK=~NODE_IDX_MASK,
-
+ TEST_AABB_BIT = 0,
+ VISIT_LEFT_BIT = 1,
+ VISIT_RIGHT_BIT = 2,
+ VISIT_DONE_BIT = 3,
+ VISITED_BIT_SHIFT = 29,
+ NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
+ VISITED_BIT_MASK = ~NODE_IDX_MASK,
};
- Vector3 n = (p_end-p_begin).normalized();
- real_t d=1e10;
- bool inters=false;
+ Vector3 n = (p_end - p_begin).normalized();
+ real_t d = 1e10;
+ bool inters = false;
- int level=0;
+ int level = 0;
PoolVector<Triangle>::Read trianglesr = triangles.read();
- PoolVector<Vector3>::Read verticesr=vertices.read();
- PoolVector<BVH>::Read bvhr=bvh.read();
+ PoolVector<Vector3>::Read verticesr = vertices.read();
+ PoolVector<BVH>::Read bvhr = bvh.read();
- const Triangle *triangleptr=trianglesr.ptr();
- const Vector3 *vertexptr=verticesr.ptr();
- int pos=bvh.size()-1;
+ const Triangle *triangleptr = trianglesr.ptr();
+ const Vector3 *vertexptr = verticesr.ptr();
+ int pos = bvh.size() - 1;
const BVH *bvhptr = bvhr.ptr();
- stack[0]=pos;
- while(true) {
+ stack[0] = pos;
+ while (true) {
- uint32_t node = stack[level]&NODE_IDX_MASK;
- const BVH &b = bvhptr[ node ];
- bool done=false;
+ uint32_t node = stack[level] & NODE_IDX_MASK;
+ const BVH &b = bvhptr[node];
+ bool done = false;
- switch(stack[level]>>VISITED_BIT_SHIFT) {
+ switch (stack[level] >> VISITED_BIT_SHIFT) {
case TEST_AABB_BIT: {
-
- bool valid = b.aabb.intersects_segment(p_begin,p_end);
+ bool valid = b.aabb.intersects_segment(p_begin, p_end);
//bool valid = b.aabb.intersects(ray_aabb);
if (!valid) {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- if (b.face_index>=0) {
-
- const Triangle &s=triangleptr[ b.face_index ];
- Face3 f3(vertexptr[ s.indices[0] ],vertexptr[ s.indices[1] ],vertexptr[ s.indices[2] ]);
+ if (b.face_index >= 0) {
+ const Triangle &s = triangleptr[b.face_index];
+ Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]);
Vector3 res;
- if (f3.intersects_segment(p_begin,p_end,&res)) {
-
+ if (f3.intersects_segment(p_begin, p_end, &res)) {
real_t nd = n.dot(res);
- if (nd<d) {
+ if (nd < d) {
- d=nd;
- r_point=res;
- r_normal=f3.get_plane().get_normal();
- inters=true;
+ d = nd;
+ r_point = res;
+ r_normal = f3.get_plane().get_normal();
+ inters = true;
}
-
}
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
}
}
continue;
}
case VISIT_LEFT_BIT: {
- stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.left|TEST_AABB_BIT;
+ stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.left | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_RIGHT_BIT: {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.right|TEST_AABB_BIT;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.right | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_DONE_BIT: {
- if (level==0) {
- done=true;
+ if (level == 0) {
+ done = true;
break;
} else
level--;
@@ -385,121 +362,112 @@ bool TriangleMesh::intersect_segment(const Vector3& p_begin,const Vector3& p_end
}
}
-
if (done)
break;
}
-
if (inters) {
- if (n.dot(r_normal)>0)
- r_normal=-r_normal;
+ if (n.dot(r_normal) > 0)
+ r_normal = -r_normal;
}
return inters;
}
+bool TriangleMesh::intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, Vector3 &r_point, Vector3 &r_normal) const {
-bool TriangleMesh::intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vector3 &r_point, Vector3 &r_normal) const {
-
-
- uint32_t* stack = (uint32_t*)alloca(sizeof(int)*max_depth);
+ uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
enum {
- TEST_AABB_BIT=0,
- VISIT_LEFT_BIT=1,
- VISIT_RIGHT_BIT=2,
- VISIT_DONE_BIT=3,
- VISITED_BIT_SHIFT=29,
- NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1,
- VISITED_BIT_MASK=~NODE_IDX_MASK,
-
+ TEST_AABB_BIT = 0,
+ VISIT_LEFT_BIT = 1,
+ VISIT_RIGHT_BIT = 2,
+ VISIT_DONE_BIT = 3,
+ VISITED_BIT_SHIFT = 29,
+ NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
+ VISITED_BIT_MASK = ~NODE_IDX_MASK,
};
Vector3 n = p_dir;
- real_t d=1e20;
- bool inters=false;
+ real_t d = 1e20;
+ bool inters = false;
- int level=0;
+ int level = 0;
PoolVector<Triangle>::Read trianglesr = triangles.read();
- PoolVector<Vector3>::Read verticesr=vertices.read();
- PoolVector<BVH>::Read bvhr=bvh.read();
+ PoolVector<Vector3>::Read verticesr = vertices.read();
+ PoolVector<BVH>::Read bvhr = bvh.read();
- const Triangle *triangleptr=trianglesr.ptr();
- const Vector3 *vertexptr=verticesr.ptr();
- int pos=bvh.size()-1;
+ const Triangle *triangleptr = trianglesr.ptr();
+ const Vector3 *vertexptr = verticesr.ptr();
+ int pos = bvh.size() - 1;
const BVH *bvhptr = bvhr.ptr();
- stack[0]=pos;
- while(true) {
+ stack[0] = pos;
+ while (true) {
- uint32_t node = stack[level]&NODE_IDX_MASK;
- const BVH &b = bvhptr[ node ];
- bool done=false;
+ uint32_t node = stack[level] & NODE_IDX_MASK;
+ const BVH &b = bvhptr[node];
+ bool done = false;
- switch(stack[level]>>VISITED_BIT_SHIFT) {
+ switch (stack[level] >> VISITED_BIT_SHIFT) {
case TEST_AABB_BIT: {
-
- bool valid = b.aabb.intersects_ray(p_begin,p_dir);
+ bool valid = b.aabb.intersects_ray(p_begin, p_dir);
if (!valid) {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- if (b.face_index>=0) {
-
- const Triangle &s=triangleptr[ b.face_index ];
- Face3 f3(vertexptr[ s.indices[0] ],vertexptr[ s.indices[1] ],vertexptr[ s.indices[2] ]);
+ if (b.face_index >= 0) {
+ const Triangle &s = triangleptr[b.face_index];
+ Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]);
Vector3 res;
- if (f3.intersects_ray(p_begin,p_dir,&res)) {
-
+ if (f3.intersects_ray(p_begin, p_dir, &res)) {
real_t nd = n.dot(res);
- if (nd<d) {
+ if (nd < d) {
- d=nd;
- r_point=res;
- r_normal=f3.get_plane().get_normal();
- inters=true;
+ d = nd;
+ r_point = res;
+ r_normal = f3.get_plane().get_normal();
+ inters = true;
}
-
}
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
}
}
continue;
}
case VISIT_LEFT_BIT: {
- stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.left|TEST_AABB_BIT;
+ stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.left | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_RIGHT_BIT: {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.right|TEST_AABB_BIT;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.right | TEST_AABB_BIT;
level++;
continue;
}
case VISIT_DONE_BIT: {
- if (level==0) {
- done=true;
+ if (level == 0) {
+ done = true;
break;
} else
level--;
@@ -507,16 +475,14 @@ bool TriangleMesh::intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vec
}
}
-
if (done)
break;
}
-
if (inters) {
- if (n.dot(r_normal)>0)
- r_normal=-r_normal;
+ if (n.dot(r_normal) > 0)
+ r_normal = -r_normal;
}
return inters;
@@ -536,13 +502,13 @@ PoolVector<Face3> TriangleMesh::get_faces() const {
int ts = triangles.size();
faces.resize(triangles.size());
- PoolVector<Face3>::Write w=faces.write();
+ PoolVector<Face3>::Write w = faces.write();
PoolVector<Triangle>::Read r = triangles.read();
PoolVector<Vector3>::Read rv = vertices.read();
- for(int i=0;i<ts;i++) {
- for(int j=0;j<3;j++) {
- w[i].vertex[j]=rv[r[i].indices[j]];
+ for (int i = 0; i < ts; i++) {
+ for (int j = 0; j < 3; j++) {
+ w[i].vertex[j] = rv[r[i].indices[j]];
}
}
@@ -552,6 +518,6 @@ PoolVector<Face3> TriangleMesh::get_faces() const {
TriangleMesh::TriangleMesh() {
- valid=false;
- max_depth=0;
+ valid = false;
+ max_depth = 0;
}
diff --git a/core/math/triangle_mesh.h b/core/math/triangle_mesh.h
index 65250c023d..7f81e54613 100644
--- a/core/math/triangle_mesh.h
+++ b/core/math/triangle_mesh.h
@@ -29,11 +29,11 @@
#ifndef TRIANGLE_MESH_H
#define TRIANGLE_MESH_H
-#include "reference.h"
#include "face3.h"
+#include "reference.h"
class TriangleMesh : public Reference {
- GDCLASS( TriangleMesh, Reference);
+ GDCLASS(TriangleMesh, Reference);
struct Triangle {
@@ -56,7 +56,7 @@ class TriangleMesh : public Reference {
struct BVHCmpX {
- bool operator()(const BVH* p_left, const BVH* p_right) const {
+ bool operator()(const BVH *p_left, const BVH *p_right) const {
return p_left->center.x < p_right->center.x;
}
@@ -64,35 +64,33 @@ class TriangleMesh : public Reference {
struct BVHCmpY {
- bool operator()(const BVH* p_left, const BVH* p_right) const {
+ bool operator()(const BVH *p_left, const BVH *p_right) const {
return p_left->center.y < p_right->center.y;
}
};
struct BVHCmpZ {
- bool operator()(const BVH* p_left, const BVH* p_right) const {
+ bool operator()(const BVH *p_left, const BVH *p_right) const {
return p_left->center.z < p_right->center.z;
}
};
- int _create_bvh(BVH*p_bvh,BVH** p_bb,int p_from,int p_size,int p_depth,int&max_depth,int&max_alloc);
+ int _create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &max_depth, int &max_alloc);
PoolVector<BVH> bvh;
int max_depth;
bool valid;
public:
-
bool is_valid() const;
- bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const;
- bool intersect_ray(const Vector3& p_begin,const Vector3& p_dir,Vector3 &r_point, Vector3 &r_normal) const;
- Vector3 get_area_normal(const Rect3& p_aabb) const;
+ bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const;
+ bool intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, Vector3 &r_point, Vector3 &r_normal) const;
+ Vector3 get_area_normal(const Rect3 &p_aabb) const;
PoolVector<Face3> get_faces() const;
-
- void create(const PoolVector<Vector3>& p_faces);
+ void create(const PoolVector<Vector3> &p_faces);
TriangleMesh();
};
diff --git a/core/math/triangulate.cpp b/core/math/triangulate.cpp
index 128b6ca331..8568a963ab 100644
--- a/core/math/triangulate.cpp
+++ b/core/math/triangulate.cpp
@@ -28,136 +28,140 @@
/*************************************************************************/
#include "triangulate.h"
-real_t Triangulate::get_area(const Vector<Vector2> &contour)
-{
+real_t Triangulate::get_area(const Vector<Vector2> &contour) {
- int n = contour.size();
- const Vector2 *c=&contour[0];
+ int n = contour.size();
+ const Vector2 *c = &contour[0];
- real_t A=0.0;
+ real_t A = 0.0;
- for(int p=n-1,q=0; q<n; p=q++)
- {
- A+= c[p].cross(c[q]);
- }
- return A*0.5;
+ for (int p = n - 1, q = 0; q < n; p = q++) {
+ A += c[p].cross(c[q]);
+ }
+ return A * 0.5;
}
- /*
+/*
is_inside_triangle decides if a point P is Inside of the triangle
defined by A, B, C.
*/
bool Triangulate::is_inside_triangle(real_t Ax, real_t Ay,
- real_t Bx, real_t By,
- real_t Cx, real_t Cy,
- real_t Px, real_t Py)
+ real_t Bx, real_t By,
+ real_t Cx, real_t Cy,
+ real_t Px, real_t Py)
{
- real_t ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
- real_t cCROSSap, bCROSScp, aCROSSbp;
-
- ax = Cx - Bx; ay = Cy - By;
- bx = Ax - Cx; by = Ay - Cy;
- cx = Bx - Ax; cy = By - Ay;
- apx= Px - Ax; apy= Py - Ay;
- bpx= Px - Bx; bpy= Py - By;
- cpx= Px - Cx; cpy= Py - Cy;
-
- aCROSSbp = ax*bpy - ay*bpx;
- cCROSSap = cx*apy - cy*apx;
- bCROSScp = bx*cpy - by*cpx;
-
- return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0));
+ real_t ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
+ real_t cCROSSap, bCROSScp, aCROSSbp;
+
+ ax = Cx - Bx;
+ ay = Cy - By;
+ bx = Ax - Cx;
+ by = Ay - Cy;
+ cx = Bx - Ax;
+ cy = By - Ay;
+ apx = Px - Ax;
+ apy = Py - Ay;
+ bpx = Px - Bx;
+ bpy = Py - By;
+ cpx = Px - Cx;
+ cpy = Py - Cy;
+
+ aCROSSbp = ax * bpy - ay * bpx;
+ cCROSSap = cx * apy - cy * apx;
+ bCROSScp = bx * cpy - by * cpx;
+
+ return ((aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0));
};
-bool Triangulate::snip(const Vector<Vector2> &p_contour,int u,int v,int w,int n,const Vector<int>& V)
-{
- int p;
- real_t Ax, Ay, Bx, By, Cx, Cy, Px, Py;
- const Vector2 *contour=&p_contour[0];
+bool Triangulate::snip(const Vector<Vector2> &p_contour, int u, int v, int w, int n, const Vector<int> &V) {
+ int p;
+ real_t Ax, Ay, Bx, By, Cx, Cy, Px, Py;
+ const Vector2 *contour = &p_contour[0];
- Ax = contour[V[u]].x;
- Ay = contour[V[u]].y;
+ Ax = contour[V[u]].x;
+ Ay = contour[V[u]].y;
- Bx = contour[V[v]].x;
- By = contour[V[v]].y;
+ Bx = contour[V[v]].x;
+ By = contour[V[v]].y;
- Cx = contour[V[w]].x;
- Cy = contour[V[w]].y;
+ Cx = contour[V[w]].x;
+ Cy = contour[V[w]].y;
- if ( CMP_EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) ) return false;
+ if (CMP_EPSILON > (((Bx - Ax) * (Cy - Ay)) - ((By - Ay) * (Cx - Ax)))) return false;
- for (p=0;p<n;p++)
- {
- if( (p == u) || (p == v) || (p == w) ) continue;
- Px = contour[V[p]].x;
- Py = contour[V[p]].y;
- if (is_inside_triangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py)) return false;
- }
+ for (p = 0; p < n; p++) {
+ if ((p == u) || (p == v) || (p == w)) continue;
+ Px = contour[V[p]].x;
+ Py = contour[V[p]].y;
+ if (is_inside_triangle(Ax, Ay, Bx, By, Cx, Cy, Px, Py)) return false;
+ }
- return true;
+ return true;
}
-bool Triangulate::triangulate(const Vector<Vector2> &contour,Vector<int> &result)
-{
- /* allocate and initialize list of Vertices in polygon */
-
- int n = contour.size();
- if ( n < 3 ) return false;
+bool Triangulate::triangulate(const Vector<Vector2> &contour, Vector<int> &result) {
+ /* allocate and initialize list of Vertices in polygon */
+ int n = contour.size();
+ if (n < 3) return false;
- Vector<int> V;
- V.resize(n);
+ Vector<int> V;
+ V.resize(n);
- /* we want a counter-clockwise polygon in V */
+ /* we want a counter-clockwise polygon in V */
- if ( 0.0 < get_area(contour) )
- for (int v=0; v<n; v++) V[v] = v;
- else
- for(int v=0; v<n; v++) V[v] = (n-1)-v;
+ if (0.0 < get_area(contour))
+ for (int v = 0; v < n; v++)
+ V[v] = v;
+ else
+ for (int v = 0; v < n; v++)
+ V[v] = (n - 1) - v;
- int nv = n;
+ int nv = n;
- /* remove nv-2 Vertices, creating 1 triangle every time */
- int count = 2*nv; /* error detection */
+ /* remove nv-2 Vertices, creating 1 triangle every time */
+ int count = 2 * nv; /* error detection */
- for(int v=nv-1; nv>2; )
- {
- /* if we loop, it is probably a non-simple polygon */
- if (0 >= (count--))
- {
- //** Triangulate: ERROR - probable bad polygon!
- return false;
- }
+ for (int v = nv - 1; nv > 2;) {
+ /* if we loop, it is probably a non-simple polygon */
+ if (0 >= (count--)) {
+ //** Triangulate: ERROR - probable bad polygon!
+ return false;
+ }
- /* three consecutive vertices in current polygon, <u,v,w> */
- int u = v ; if (nv <= u) u = 0; /* previous */
- v = u+1; if (nv <= v) v = 0; /* new v */
- int w = v+1; if (nv <= w) w = 0; /* next */
+ /* three consecutive vertices in current polygon, <u,v,w> */
+ int u = v;
+ if (nv <= u) u = 0; /* previous */
+ v = u + 1;
+ if (nv <= v) v = 0; /* new v */
+ int w = v + 1;
+ if (nv <= w) w = 0; /* next */
- if ( snip(contour,u,v,w,nv,V) )
- {
- int a,b,c,s,t;
+ if (snip(contour, u, v, w, nv, V)) {
+ int a, b, c, s, t;
- /* true names of the vertices */
- a = V[u]; b = V[v]; c = V[w];
+ /* true names of the vertices */
+ a = V[u];
+ b = V[v];
+ c = V[w];
- /* output Triangle */
- result.push_back( a );
- result.push_back( b );
- result.push_back( c );
+ /* output Triangle */
+ result.push_back(a);
+ result.push_back(b);
+ result.push_back(c);
- /* remove v from remaining polygon */
- for(s=v,t=v+1;t<nv;s++,t++)
- V[s] = V[t];
+ /* remove v from remaining polygon */
+ for (s = v, t = v + 1; t < nv; s++, t++)
+ V[s] = V[t];
- nv--;
+ nv--;
- /* resest error detection counter */
- count = 2*nv;
- }
- }
+ /* resest error detection counter */
+ count = 2 * nv;
+ }
+ }
- return true;
+ return true;
}
diff --git a/core/math/triangulate.h b/core/math/triangulate.h
index ce77334519..c23d3ba27d 100644
--- a/core/math/triangulate.h
+++ b/core/math/triangulate.h
@@ -31,35 +31,28 @@
#include "math_2d.h"
-
/*
http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
*/
-class Triangulate
-{
+class Triangulate {
public:
-
// triangulate a contour/polygon, places results in STL vector
// as series of triangles.
- static bool triangulate(const Vector< Vector2 > &contour, Vector<int> &result);
+ static bool triangulate(const Vector<Vector2> &contour, Vector<int> &result);
// compute area of a contour/polygon
- static real_t get_area(const Vector< Vector2 > &contour);
+ static real_t get_area(const Vector<Vector2> &contour);
// decide if point Px/Py is inside triangle defined by
// (Ax,Ay) (Bx,By) (Cx,Cy)
static bool is_inside_triangle(real_t Ax, real_t Ay,
- real_t Bx, real_t By,
- real_t Cx, real_t Cy,
- real_t Px, real_t Py);
-
+ real_t Bx, real_t By,
+ real_t Cx, real_t Cy,
+ real_t Px, real_t Py);
private:
- static bool snip(const Vector<Vector2> &p_contour,int u,int v,int w,int n,const Vector<int>& V);
-
+ static bool snip(const Vector<Vector2> &p_contour, int u, int v, int w, int n, const Vector<int> &V);
};
-
-
#endif
diff --git a/core/math/vector3.cpp b/core/math/vector3.cpp
index 2ab5fa0465..235840e06a 100644
--- a/core/math/vector3.cpp
+++ b/core/math/vector3.cpp
@@ -29,27 +29,25 @@
#include "vector3.h"
#include "matrix3.h"
+void Vector3::rotate(const Vector3 &p_axis, real_t p_phi) {
-void Vector3::rotate(const Vector3& p_axis,real_t p_phi) {
-
- *this=Basis(p_axis,p_phi).xform(*this);
+ *this = Basis(p_axis, p_phi).xform(*this);
}
-Vector3 Vector3::rotated(const Vector3& p_axis,real_t p_phi) const {
+Vector3 Vector3::rotated(const Vector3 &p_axis, real_t p_phi) const {
Vector3 r = *this;
- r.rotate(p_axis,p_phi);
+ r.rotate(p_axis, p_phi);
return r;
}
-void Vector3::set_axis(int p_axis,real_t p_value) {
- ERR_FAIL_INDEX(p_axis,3);
- coord[p_axis]=p_value;
-
+void Vector3::set_axis(int p_axis, real_t p_value) {
+ ERR_FAIL_INDEX(p_axis, 3);
+ coord[p_axis] = p_value;
}
real_t Vector3::get_axis(int p_axis) const {
- ERR_FAIL_INDEX_V(p_axis,3,0);
+ ERR_FAIL_INDEX_V(p_axis, 3, 0);
return operator[](p_axis);
}
@@ -62,27 +60,25 @@ int Vector3::max_axis() const {
return x < y ? (y < z ? 2 : 1) : (x < z ? 2 : 0);
}
-
void Vector3::snap(real_t p_val) {
- x=Math::stepify(x,p_val);
- y=Math::stepify(y,p_val);
- z=Math::stepify(z,p_val);
+ x = Math::stepify(x, p_val);
+ y = Math::stepify(y, p_val);
+ z = Math::stepify(z, p_val);
}
Vector3 Vector3::snapped(real_t p_val) const {
- Vector3 v=*this;
+ Vector3 v = *this;
v.snap(p_val);
return v;
}
+Vector3 Vector3::cubic_interpolaten(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const {
-Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const {
-
- Vector3 p0=p_pre_a;
- Vector3 p1=*this;
- Vector3 p2=p_b;
- Vector3 p3=p_post_b;
+ Vector3 p0 = p_pre_a;
+ Vector3 p1 = *this;
+ Vector3 p2 = p_b;
+ Vector3 p3 = p_post_b;
{
//normalize
@@ -91,44 +87,41 @@ Vector3 Vector3::cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, c
real_t bc = p1.distance_to(p2);
real_t cd = p2.distance_to(p3);
- if (ab>0)
- p0 = p1+(p0-p1)*(bc/ab);
- if (cd>0)
- p3 = p2+(p3-p2)*(bc/cd);
+ if (ab > 0)
+ p0 = p1 + (p0 - p1) * (bc / ab);
+ if (cd > 0)
+ p3 = p2 + (p3 - p2) * (bc / cd);
}
-
real_t t = p_t;
real_t t2 = t * t;
real_t t3 = t2 * t;
Vector3 out;
- out = 0.5 * ( ( p1 * 2.0) +
- ( -p0 + p2 ) * t +
- ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 +
- ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 );
+ out = 0.5 * ((p1 * 2.0) +
+ (-p0 + p2) * t +
+ (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 +
+ (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
return out;
-
}
-Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const {
+Vector3 Vector3::cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const {
- Vector3 p0=p_pre_a;
- Vector3 p1=*this;
- Vector3 p2=p_b;
- Vector3 p3=p_post_b;
+ Vector3 p0 = p_pre_a;
+ Vector3 p1 = *this;
+ Vector3 p2 = p_b;
+ Vector3 p3 = p_post_b;
real_t t = p_t;
real_t t2 = t * t;
real_t t3 = t2 * t;
Vector3 out;
- out = 0.5 * ( ( p1 * 2.0) +
- ( -p0 + p2 ) * t +
- ( 2.0 * p0 - 5.0 * p1 + 4 * p2 - p3 ) * t2 +
- ( -p0 + 3.0 * p1 - 3.0 * p2 + p3 ) * t3 );
+ out = 0.5 * ((p1 * 2.0) +
+ (-p0 + p2) * t +
+ (2.0 * p0 - 5.0 * p1 + 4 * p2 - p3) * t2 +
+ (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3);
return out;
-
}
#if 0
@@ -175,8 +168,8 @@ Vector3 Vector3::cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, co
( -p0.z + 3.0 * p1.z - 3.0 * p2.z + p3.z ) * t3 );
return out;
}
-# endif
+#endif
Vector3::operator String() const {
- return (rtos(x)+", "+rtos(y)+", "+rtos(z));
+ return (rtos(x) + ", " + rtos(y) + ", " + rtos(z));
}
diff --git a/core/math/vector3.h b/core/math/vector3.h
index a289f9bf4c..fc02e66c33 100644
--- a/core/math/vector3.h
+++ b/core/math/vector3.h
@@ -29,9 +29,9 @@
#ifndef VECTOR3_H
#define VECTOR3_H
-#include "typedefs.h"
#include "math_defs.h"
#include "math_funcs.h"
+#include "typedefs.h"
#include "ustring.h"
class Basis;
@@ -54,17 +54,17 @@ struct Vector3 {
real_t coord[3];
};
- _FORCE_INLINE_ const real_t& operator[](int p_axis) const {
+ _FORCE_INLINE_ const real_t &operator[](int p_axis) const {
return coord[p_axis];
}
- _FORCE_INLINE_ real_t& operator[](int p_axis) {
+ _FORCE_INLINE_ real_t &operator[](int p_axis) {
return coord[p_axis];
}
- void set_axis(int p_axis,real_t p_value);
+ void set_axis(int p_axis, real_t p_value);
real_t get_axis(int p_axis) const;
int min_axis() const;
@@ -82,63 +82,63 @@ struct Vector3 {
void snap(real_t p_val);
Vector3 snapped(real_t p_val) const;
- void rotate(const Vector3& p_axis,real_t p_phi);
- Vector3 rotated(const Vector3& p_axis,real_t p_phi) const;
+ void rotate(const Vector3 &p_axis, real_t p_phi);
+ Vector3 rotated(const Vector3 &p_axis, real_t p_phi) const;
/* Static Methods between 2 vector3s */
- _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3& p_b,real_t p_t) const;
- Vector3 cubic_interpolate(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const;
- Vector3 cubic_interpolaten(const Vector3& p_b,const Vector3& p_pre_a, const Vector3& p_post_b,real_t p_t) const;
+ _FORCE_INLINE_ Vector3 linear_interpolate(const Vector3 &p_b, real_t p_t) const;
+ Vector3 cubic_interpolate(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const;
+ Vector3 cubic_interpolaten(const Vector3 &p_b, const Vector3 &p_pre_a, const Vector3 &p_post_b, real_t p_t) const;
- _FORCE_INLINE_ Vector3 cross(const Vector3& p_b) const;
- _FORCE_INLINE_ real_t dot(const Vector3& p_b) const;
- _FORCE_INLINE_ Basis outer(const Vector3& p_b) const;
+ _FORCE_INLINE_ Vector3 cross(const Vector3 &p_b) const;
+ _FORCE_INLINE_ real_t dot(const Vector3 &p_b) const;
+ _FORCE_INLINE_ Basis outer(const Vector3 &p_b) const;
_FORCE_INLINE_ Basis to_diagonal_matrix() const;
_FORCE_INLINE_ Vector3 abs() const;
_FORCE_INLINE_ Vector3 floor() const;
_FORCE_INLINE_ Vector3 ceil() const;
- _FORCE_INLINE_ real_t distance_to(const Vector3& p_b) const;
- _FORCE_INLINE_ real_t distance_squared_to(const Vector3& p_b) const;
-
- _FORCE_INLINE_ real_t angle_to(const Vector3& p_b) const;
-
+ _FORCE_INLINE_ real_t distance_to(const Vector3 &p_b) const;
+ _FORCE_INLINE_ real_t distance_squared_to(const Vector3 &p_b) const;
- _FORCE_INLINE_ Vector3 slide(const Vector3& p_vec) const;
- _FORCE_INLINE_ Vector3 reflect(const Vector3& p_vec) const;
+ _FORCE_INLINE_ real_t angle_to(const Vector3 &p_b) const;
+ _FORCE_INLINE_ Vector3 slide(const Vector3 &p_vec) const;
+ _FORCE_INLINE_ Vector3 reflect(const Vector3 &p_vec) const;
/* Operators */
- _FORCE_INLINE_ Vector3& operator+=(const Vector3& p_v);
- _FORCE_INLINE_ Vector3 operator+(const Vector3& p_v) const;
- _FORCE_INLINE_ Vector3& operator-=(const Vector3& p_v);
- _FORCE_INLINE_ Vector3 operator-(const Vector3& p_v) const;
- _FORCE_INLINE_ Vector3& operator*=(const Vector3& p_v);
- _FORCE_INLINE_ Vector3 operator*(const Vector3& p_v) const;
- _FORCE_INLINE_ Vector3& operator/=(const Vector3& p_v);
- _FORCE_INLINE_ Vector3 operator/(const Vector3& p_v) const;
+ _FORCE_INLINE_ Vector3 &operator+=(const Vector3 &p_v);
+ _FORCE_INLINE_ Vector3 operator+(const Vector3 &p_v) const;
+ _FORCE_INLINE_ Vector3 &operator-=(const Vector3 &p_v);
+ _FORCE_INLINE_ Vector3 operator-(const Vector3 &p_v) const;
+ _FORCE_INLINE_ Vector3 &operator*=(const Vector3 &p_v);
+ _FORCE_INLINE_ Vector3 operator*(const Vector3 &p_v) const;
+ _FORCE_INLINE_ Vector3 &operator/=(const Vector3 &p_v);
+ _FORCE_INLINE_ Vector3 operator/(const Vector3 &p_v) const;
-
- _FORCE_INLINE_ Vector3& operator*=(real_t p_scalar);
+ _FORCE_INLINE_ Vector3 &operator*=(real_t p_scalar);
_FORCE_INLINE_ Vector3 operator*(real_t p_scalar) const;
- _FORCE_INLINE_ Vector3& operator/=(real_t p_scalar);
+ _FORCE_INLINE_ Vector3 &operator/=(real_t p_scalar);
_FORCE_INLINE_ Vector3 operator/(real_t p_scalar) const;
_FORCE_INLINE_ Vector3 operator-() const;
- _FORCE_INLINE_ bool operator==(const Vector3& p_v) const;
- _FORCE_INLINE_ bool operator!=(const Vector3& p_v) const;
- _FORCE_INLINE_ bool operator<(const Vector3& p_v) const;
- _FORCE_INLINE_ bool operator<=(const Vector3& p_v) const;
+ _FORCE_INLINE_ bool operator==(const Vector3 &p_v) const;
+ _FORCE_INLINE_ bool operator!=(const Vector3 &p_v) const;
+ _FORCE_INLINE_ bool operator<(const Vector3 &p_v) const;
+ _FORCE_INLINE_ bool operator<=(const Vector3 &p_v) const;
operator String() const;
- _FORCE_INLINE_ Vector3() { x=y=z=0; }
- _FORCE_INLINE_ Vector3(real_t p_x,real_t p_y,real_t p_z) { x=p_x; y=p_y; z=p_z; }
-
+ _FORCE_INLINE_ Vector3() { x = y = z = 0; }
+ _FORCE_INLINE_ Vector3(real_t p_x, real_t p_y, real_t p_z) {
+ x = p_x;
+ y = p_y;
+ z = p_z;
+ }
};
#ifdef VECTOR3_IMPL_OVERRIDE
@@ -149,260 +149,258 @@ struct Vector3 {
#include "matrix3.h"
-Vector3 Vector3::cross(const Vector3& p_b) const {
+Vector3 Vector3::cross(const Vector3 &p_b) const {
- Vector3 ret (
- (y * p_b.z) - (z * p_b.y),
- (z * p_b.x) - (x * p_b.z),
- (x * p_b.y) - (y * p_b.x)
- );
+ Vector3 ret(
+ (y * p_b.z) - (z * p_b.y),
+ (z * p_b.x) - (x * p_b.z),
+ (x * p_b.y) - (y * p_b.x));
return ret;
}
-real_t Vector3::dot(const Vector3& p_b) const {
+real_t Vector3::dot(const Vector3 &p_b) const {
- return x*p_b.x + y*p_b.y + z*p_b.z;
+ return x * p_b.x + y * p_b.y + z * p_b.z;
}
-Basis Vector3::outer(const Vector3& p_b) const {
-
- Vector3 row0(x*p_b.x, x*p_b.y, x*p_b.z);
- Vector3 row1(y*p_b.x, y*p_b.y, y*p_b.z);
- Vector3 row2(z*p_b.x, z*p_b.y, z*p_b.z);
+Basis Vector3::outer(const Vector3 &p_b) const {
+
+ Vector3 row0(x * p_b.x, x * p_b.y, x * p_b.z);
+ Vector3 row1(y * p_b.x, y * p_b.y, y * p_b.z);
+ Vector3 row2(z * p_b.x, z * p_b.y, z * p_b.z);
return Basis(row0, row1, row2);
}
Basis Vector3::to_diagonal_matrix() const {
return Basis(x, 0, 0,
- 0, y, 0,
- 0, 0, z);
+ 0, y, 0,
+ 0, 0, z);
}
Vector3 Vector3::abs() const {
- return Vector3( Math::abs(x), Math::abs(y), Math::abs(z) );
+ return Vector3(Math::abs(x), Math::abs(y), Math::abs(z));
}
Vector3 Vector3::floor() const {
- return Vector3( Math::floor(x), Math::floor(y), Math::floor(z) );
+ return Vector3(Math::floor(x), Math::floor(y), Math::floor(z));
}
Vector3 Vector3::ceil() const {
- return Vector3( Math::ceil(x), Math::ceil(y), Math::ceil(z) );
+ return Vector3(Math::ceil(x), Math::ceil(y), Math::ceil(z));
}
-Vector3 Vector3::linear_interpolate(const Vector3& p_b,real_t p_t) const {
+Vector3 Vector3::linear_interpolate(const Vector3 &p_b, real_t p_t) const {
return Vector3(
- x+(p_t * (p_b.x-x)),
- y+(p_t * (p_b.y-y)),
- z+(p_t * (p_b.z-z))
- );
+ x + (p_t * (p_b.x - x)),
+ y + (p_t * (p_b.y - y)),
+ z + (p_t * (p_b.z - z)));
}
-real_t Vector3::distance_to(const Vector3& p_b) const {
+real_t Vector3::distance_to(const Vector3 &p_b) const {
- return (p_b-*this).length();
+ return (p_b - *this).length();
}
-real_t Vector3::distance_squared_to(const Vector3& p_b) const {
+real_t Vector3::distance_squared_to(const Vector3 &p_b) const {
- return (p_b-*this).length_squared();
+ return (p_b - *this).length_squared();
}
-real_t Vector3::angle_to(const Vector3& p_b) const {
+real_t Vector3::angle_to(const Vector3 &p_b) const {
return Math::acos(this->dot(p_b) / Math::sqrt(this->length_squared() * p_b.length_squared()));
}
/* Operators */
-Vector3& Vector3::operator+=(const Vector3& p_v) {
+Vector3 &Vector3::operator+=(const Vector3 &p_v) {
- x+=p_v.x;
- y+=p_v.y;
- z+=p_v.z;
+ x += p_v.x;
+ y += p_v.y;
+ z += p_v.z;
return *this;
}
-Vector3 Vector3::operator+(const Vector3& p_v) const {
+Vector3 Vector3::operator+(const Vector3 &p_v) const {
- return Vector3(x+p_v.x, y+p_v.y, z+ p_v.z);
+ return Vector3(x + p_v.x, y + p_v.y, z + p_v.z);
}
-Vector3& Vector3::operator-=(const Vector3& p_v) {
+Vector3 &Vector3::operator-=(const Vector3 &p_v) {
- x-=p_v.x;
- y-=p_v.y;
- z-=p_v.z;
+ x -= p_v.x;
+ y -= p_v.y;
+ z -= p_v.z;
return *this;
}
-Vector3 Vector3::operator-(const Vector3& p_v) const {
+Vector3 Vector3::operator-(const Vector3 &p_v) const {
- return Vector3(x-p_v.x, y-p_v.y, z- p_v.z);
+ return Vector3(x - p_v.x, y - p_v.y, z - p_v.z);
}
-Vector3& Vector3::operator*=(const Vector3& p_v) {
+Vector3 &Vector3::operator*=(const Vector3 &p_v) {
- x*=p_v.x;
- y*=p_v.y;
- z*=p_v.z;
+ x *= p_v.x;
+ y *= p_v.y;
+ z *= p_v.z;
return *this;
}
-Vector3 Vector3::operator*(const Vector3& p_v) const {
+Vector3 Vector3::operator*(const Vector3 &p_v) const {
- return Vector3(x*p_v.x, y*p_v.y, z* p_v.z);
+ return Vector3(x * p_v.x, y * p_v.y, z * p_v.z);
}
-Vector3& Vector3::operator/=(const Vector3& p_v) {
+Vector3 &Vector3::operator/=(const Vector3 &p_v) {
- x/=p_v.x;
- y/=p_v.y;
- z/=p_v.z;
+ x /= p_v.x;
+ y /= p_v.y;
+ z /= p_v.z;
return *this;
}
-Vector3 Vector3::operator/(const Vector3& p_v) const {
+Vector3 Vector3::operator/(const Vector3 &p_v) const {
- return Vector3(x/p_v.x, y/p_v.y, z/ p_v.z);
+ return Vector3(x / p_v.x, y / p_v.y, z / p_v.z);
}
-Vector3& Vector3::operator*=(real_t p_scalar) {
+Vector3 &Vector3::operator*=(real_t p_scalar) {
- x*=p_scalar;
- y*=p_scalar;
- z*=p_scalar;
+ x *= p_scalar;
+ y *= p_scalar;
+ z *= p_scalar;
return *this;
}
-_FORCE_INLINE_ Vector3 operator*(real_t p_scalar, const Vector3& p_vec) {
+_FORCE_INLINE_ Vector3 operator*(real_t p_scalar, const Vector3 &p_vec) {
return p_vec * p_scalar;
}
Vector3 Vector3::operator*(real_t p_scalar) const {
- return Vector3( x*p_scalar, y*p_scalar, z*p_scalar);
+ return Vector3(x * p_scalar, y * p_scalar, z * p_scalar);
}
-Vector3& Vector3::operator/=(real_t p_scalar) {
+Vector3 &Vector3::operator/=(real_t p_scalar) {
- x/=p_scalar;
- y/=p_scalar;
- z/=p_scalar;
+ x /= p_scalar;
+ y /= p_scalar;
+ z /= p_scalar;
return *this;
}
Vector3 Vector3::operator/(real_t p_scalar) const {
- return Vector3( x/p_scalar, y/p_scalar, z/p_scalar);
+ return Vector3(x / p_scalar, y / p_scalar, z / p_scalar);
}
Vector3 Vector3::operator-() const {
- return Vector3( -x, -y, -z );
+ return Vector3(-x, -y, -z);
}
-bool Vector3::operator==(const Vector3& p_v) const {
+bool Vector3::operator==(const Vector3 &p_v) const {
- return (x==p_v.x && y==p_v.y && z==p_v.z);
+ return (x == p_v.x && y == p_v.y && z == p_v.z);
}
-bool Vector3::operator!=(const Vector3& p_v) const {
- return (x!=p_v.x || y!=p_v.y || z!=p_v.z);
+bool Vector3::operator!=(const Vector3 &p_v) const {
+ return (x != p_v.x || y != p_v.y || z != p_v.z);
}
-bool Vector3::operator<(const Vector3& p_v) const {
+bool Vector3::operator<(const Vector3 &p_v) const {
- if (x==p_v.x) {
- if (y==p_v.y)
- return z<p_v.z;
+ if (x == p_v.x) {
+ if (y == p_v.y)
+ return z < p_v.z;
else
- return y<p_v.y;
+ return y < p_v.y;
} else {
- return x<p_v.x;
+ return x < p_v.x;
}
}
-bool Vector3::operator<=(const Vector3& p_v) const {
+bool Vector3::operator<=(const Vector3 &p_v) const {
- if (x==p_v.x) {
- if (y==p_v.y)
- return z<=p_v.z;
+ if (x == p_v.x) {
+ if (y == p_v.y)
+ return z <= p_v.z;
else
- return y<p_v.y;
+ return y < p_v.y;
} else {
- return x<p_v.x;
+ return x < p_v.x;
}
}
-_FORCE_INLINE_ Vector3 vec3_cross(const Vector3& p_a, const Vector3& p_b) {
+_FORCE_INLINE_ Vector3 vec3_cross(const Vector3 &p_a, const Vector3 &p_b) {
return p_a.cross(p_b);
}
-_FORCE_INLINE_ real_t vec3_dot(const Vector3& p_a, const Vector3& p_b) {
+_FORCE_INLINE_ real_t vec3_dot(const Vector3 &p_a, const Vector3 &p_b) {
return p_a.dot(p_b);
}
real_t Vector3::length() const {
- real_t x2=x*x;
- real_t y2=y*y;
- real_t z2=z*z;
+ real_t x2 = x * x;
+ real_t y2 = y * y;
+ real_t z2 = z * z;
- return Math::sqrt(x2+y2+z2);
+ return Math::sqrt(x2 + y2 + z2);
}
real_t Vector3::length_squared() const {
- real_t x2=x*x;
- real_t y2=y*y;
- real_t z2=z*z;
+ real_t x2 = x * x;
+ real_t y2 = y * y;
+ real_t z2 = z * z;
- return x2+y2+z2;
+ return x2 + y2 + z2;
}
void Vector3::normalize() {
- real_t l=length();
- if (l==0) {
- x=y=z=0;
+ real_t l = length();
+ if (l == 0) {
+ x = y = z = 0;
} else {
- x/=l;
- y/=l;
- z/=l;
+ x /= l;
+ y /= l;
+ z /= l;
}
}
Vector3 Vector3::normalized() const {
- Vector3 v=*this;
+ Vector3 v = *this;
v.normalize();
return v;
}
Vector3 Vector3::inverse() const {
- return Vector3( 1.0/x, 1.0/y, 1.0/z );
+ return Vector3(1.0 / x, 1.0 / y, 1.0 / z);
}
void Vector3::zero() {
- x=y=z=0;
+ x = y = z = 0;
}
-Vector3 Vector3::slide(const Vector3& p_vec) const {
+Vector3 Vector3::slide(const Vector3 &p_vec) const {
return p_vec - *this * this->dot(p_vec);
}
-Vector3 Vector3::reflect(const Vector3& p_vec) const {
+Vector3 Vector3::reflect(const Vector3 &p_vec) const {
return p_vec - *this * this->dot(p_vec) * 2.0;
}
diff --git a/core/message_queue.cpp b/core/message_queue.cpp
index 50b52e4970..56c944081a 100644
--- a/core/message_queue.cpp
+++ b/core/message_queue.cpp
@@ -31,95 +31,90 @@
#include "global_config.h"
#include "script_language.h"
-MessageQueue *MessageQueue::singleton=NULL;
+MessageQueue *MessageQueue::singleton = NULL;
MessageQueue *MessageQueue::get_singleton() {
return singleton;
}
-Error MessageQueue::push_call(ObjectID p_id,const StringName& p_method,const Variant** p_args,int p_argcount,bool p_show_error) {
+Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {
_THREAD_SAFE_METHOD_
- int room_needed=sizeof(Message)+sizeof(Variant)*p_argcount;
+ int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;
- if ((buffer_end+room_needed) >= buffer_size) {
+ if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
- type=ObjectDB::get_instance(p_id)->get_class();
- print_line("failed method: "+type+":"+p_method+" target ID: "+itos(p_id));
+ type = ObjectDB::get_instance(p_id)->get_class();
+ print_line("failed method: " + type + ":" + p_method + " target ID: " + itos(p_id));
statistics();
-
}
- ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY );
- Message * msg = memnew_placement( &buffer[ buffer_end ], Message );
- msg->args=p_argcount;
- msg->instance_ID=p_id;
- msg->target=p_method;
- msg->type=TYPE_CALL;
+ ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
+ Message *msg = memnew_placement(&buffer[buffer_end], Message);
+ msg->args = p_argcount;
+ msg->instance_ID = p_id;
+ msg->target = p_method;
+ msg->type = TYPE_CALL;
if (p_show_error)
- msg->type|=FLAG_SHOW_ERROR;
-
- buffer_end+=sizeof(Message);
+ msg->type |= FLAG_SHOW_ERROR;
- for(int i=0;i<p_argcount;i++) {
+ buffer_end += sizeof(Message);
- Variant * v = memnew_placement( &buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=*p_args[i];
+ for (int i = 0; i < p_argcount; i++) {
+ Variant *v = memnew_placement(&buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = *p_args[i];
}
return OK;
}
-Error MessageQueue::push_call(ObjectID p_id, const StringName& p_method, VARIANT_ARG_DECLARE) {
+Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
+ int argc = 0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
- return push_call(p_id,p_method,argptr,argc,false);
-
+ return push_call(p_id, p_method, argptr, argc, false);
}
-Error MessageQueue::push_set(ObjectID p_id, const StringName& p_prop, const Variant& p_value) {
+Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {
_THREAD_SAFE_METHOD_
- uint8_t room_needed=sizeof(Message)+sizeof(Variant);
+ uint8_t room_needed = sizeof(Message) + sizeof(Variant);
- if ((buffer_end+room_needed) >= buffer_size) {
+ if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
- type=ObjectDB::get_instance(p_id)->get_class();
- print_line("failed set: "+type+":"+p_prop+" target ID: "+itos(p_id));
+ type = ObjectDB::get_instance(p_id)->get_class();
+ print_line("failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id));
statistics();
-
}
- ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY );
-
- Message * msg = memnew_placement( &buffer[ buffer_end ], Message );
- msg->args=1;
- msg->instance_ID=p_id;
- msg->target=p_prop;
- msg->type=TYPE_SET;
+ ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
- buffer_end+=sizeof(Message);
+ Message *msg = memnew_placement(&buffer[buffer_end], Message);
+ msg->args = 1;
+ msg->instance_ID = p_id;
+ msg->target = p_prop;
+ msg->type = TYPE_SET;
- Variant * v = memnew_placement( &buffer[ buffer_end ], Variant );
- buffer_end+=sizeof(Variant);
- *v=p_value;
+ buffer_end += sizeof(Message);
+ Variant *v = memnew_placement(&buffer[buffer_end], Variant);
+ buffer_end += sizeof(Variant);
+ *v = p_value;
return OK;
}
@@ -128,73 +123,66 @@ Error MessageQueue::push_notification(ObjectID p_id, int p_notification) {
_THREAD_SAFE_METHOD_
- ERR_FAIL_COND_V(p_notification<0, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);
- uint8_t room_needed=sizeof(Message);
+ uint8_t room_needed = sizeof(Message);
- if ((buffer_end+room_needed) >= buffer_size) {
+ if ((buffer_end + room_needed) >= buffer_size) {
String type;
if (ObjectDB::get_instance(p_id))
- type=ObjectDB::get_instance(p_id)->get_class();
- print_line("failed notification: "+itos(p_notification)+" target ID: "+itos(p_id));
+ type = ObjectDB::get_instance(p_id)->get_class();
+ print_line("failed notification: " + itos(p_notification) + " target ID: " + itos(p_id));
statistics();
-
}
+ ERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);
+ Message *msg = memnew_placement(&buffer[buffer_end], Message);
-
-
- ERR_FAIL_COND_V( (buffer_end+room_needed) >= buffer_size , ERR_OUT_OF_MEMORY );
- Message * msg = memnew_placement( &buffer[ buffer_end ], Message );
-
- msg->type=TYPE_NOTIFICATION;
- msg->instance_ID=p_id;
+ msg->type = TYPE_NOTIFICATION;
+ msg->instance_ID = p_id;
//msg->target;
- msg->notification=p_notification;
-
- buffer_end+=sizeof(Message);
+ msg->notification = p_notification;
+ buffer_end += sizeof(Message);
return OK;
}
-Error MessageQueue::push_call(Object *p_object, const StringName& p_method, VARIANT_ARG_DECLARE) {
+Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {
- return push_call(p_object->get_instance_ID(),p_method,VARIANT_ARG_PASS);
+ return push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS);
}
Error MessageQueue::push_notification(Object *p_object, int p_notification) {
- return push_notification(p_object->get_instance_ID(),p_notification);
+ return push_notification(p_object->get_instance_ID(), p_notification);
}
-Error MessageQueue::push_set(Object *p_object, const StringName& p_prop, const Variant& p_value) {
+Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {
- return push_set(p_object->get_instance_ID(),p_prop,p_value);
+ return push_set(p_object->get_instance_ID(), p_prop, p_value);
}
-
void MessageQueue::statistics() {
- Map<StringName,int> set_count;
- Map<int,int> notify_count;
- Map<StringName,int> call_count;
- int null_count=0;
+ Map<StringName, int> set_count;
+ Map<int, int> notify_count;
+ Map<StringName, int> call_count;
+ int null_count = 0;
- uint32_t read_pos=0;
- while (read_pos < buffer_end ) {
- Message *message = (Message*)&buffer[ read_pos ];
+ uint32_t read_pos = 0;
+ while (read_pos < buffer_end) {
+ Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
- if (target!=NULL) {
-
+ if (target != NULL) {
- switch(message->type&FLAG_MASK) {
+ switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
if (!call_count.has(message->target))
- call_count[message->target]=0;
+ call_count[message->target] = 0;
call_count[message->target]++;
@@ -202,7 +190,7 @@ void MessageQueue::statistics() {
case TYPE_NOTIFICATION: {
if (!notify_count.has(message->notification))
- notify_count[message->notification]=0;
+ notify_count[message->notification] = 0;
notify_count[message->notification]++;
@@ -210,12 +198,11 @@ void MessageQueue::statistics() {
case TYPE_SET: {
if (!set_count.has(message->target))
- set_count[message->target]=0;
+ set_count[message->target] = 0;
set_count[message->target]++;
} break;
-
}
//object was deleted
@@ -226,31 +213,28 @@ void MessageQueue::statistics() {
null_count++;
}
-
- read_pos+=sizeof(Message);
- if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION)
- read_pos+=sizeof(Variant)*message->args;
+ read_pos += sizeof(Message);
+ if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
+ read_pos += sizeof(Variant) * message->args;
}
+ print_line("TOTAL BYTES: " + itos(buffer_end));
+ print_line("NULL count: " + itos(null_count));
- print_line("TOTAL BYTES: "+itos(buffer_end));
- print_line("NULL count: "+itos(null_count));
+ for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {
- for(Map<StringName,int>::Element *E=set_count.front();E;E=E->next()) {
-
- print_line("SET "+E->key()+": "+itos(E->get()));
+ print_line("SET " + E->key() + ": " + itos(E->get()));
}
- for(Map<StringName,int>::Element *E=call_count.front();E;E=E->next()) {
+ for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {
- print_line("CALL "+E->key()+": "+itos(E->get()));
+ print_line("CALL " + E->key() + ": " + itos(E->get()));
}
- for(Map<int,int>::Element *E=notify_count.front();E;E=E->next()) {
+ for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {
- print_line("NOTIFY "+itos(E->key())+": "+itos(E->get()));
+ print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get()));
}
-
}
bool MessageQueue::print() {
@@ -299,62 +283,58 @@ int MessageQueue::get_max_buffer_usage() const {
return buffer_max_used;
}
+void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {
-void MessageQueue::_call_function(Object* p_target, const StringName& p_func, const Variant *p_args, int p_argcount,bool p_show_error) {
-
- const Variant **argptrs=NULL;
+ const Variant **argptrs = NULL;
if (p_argcount) {
- argptrs = (const Variant**)alloca(sizeof(Variant*)*p_argcount);
- for(int i=0;i<p_argcount;i++) {
- argptrs[i]=&p_args[i];
+ argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);
+ for (int i = 0; i < p_argcount; i++) {
+ argptrs[i] = &p_args[i];
}
}
Variant::CallError ce;
- p_target->call(p_func,argptrs,p_argcount,ce);
- if (p_show_error && ce.error!=Variant::CallError::CALL_OK) {
-
- ERR_PRINTS("Error calling deferred method: "+Variant::get_call_error_text(p_target,p_func,argptrs,p_argcount,ce));
+ p_target->call(p_func, argptrs, p_argcount, ce);
+ if (p_show_error && ce.error != Variant::CallError::CALL_OK) {
+ ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));
}
}
void MessageQueue::flush() {
-
if (buffer_end > buffer_max_used) {
- buffer_max_used=buffer_end;
+ buffer_max_used = buffer_end;
//statistics();
}
- uint32_t read_pos=0;
+ uint32_t read_pos = 0;
//using reverse locking strategy
_THREAD_SAFE_LOCK_
- while (read_pos<buffer_end) {
+ while (read_pos < buffer_end) {
_THREAD_SAFE_UNLOCK_
//lock on each interation, so a call can re-add itself to the message queue
- Message *message = (Message*)&buffer[ read_pos ];
+ Message *message = (Message *)&buffer[read_pos];
Object *target = ObjectDB::get_instance(message->instance_ID);
- if (target!=NULL) {
+ if (target != NULL) {
- switch(message->type&FLAG_MASK) {
+ switch (message->type & FLAG_MASK) {
case TYPE_CALL: {
- Variant *args= (Variant*)(message+1);
+ Variant *args = (Variant *)(message + 1);
// messages don't expect a return value
+ _call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);
- _call_function(target,message->target,args,message->args,message->type&FLAG_SHOW_ERROR);
-
- for(int i=0;i<message->args;i++) {
+ for (int i = 0; i < message->args; i++) {
args[i].~Variant();
}
@@ -367,65 +347,60 @@ void MessageQueue::flush() {
} break;
case TYPE_SET: {
- Variant *arg= (Variant*)(message+1);
+ Variant *arg = (Variant *)(message + 1);
// messages don't expect a return value
- target->set(message->target,*arg);
+ target->set(message->target, *arg);
arg->~Variant();
} break;
}
-
}
uint32_t advance = sizeof(Message);
- if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION)
- advance+=sizeof(Variant)*message->args;
+ if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
+ advance += sizeof(Variant) * message->args;
message->~Message();
_THREAD_SAFE_LOCK_
- read_pos+=advance;
-
+ read_pos += advance;
}
-
- buffer_end=0; // reset buffer
+ buffer_end = 0; // reset buffer
_THREAD_SAFE_UNLOCK_
-
}
MessageQueue::MessageQueue() {
- ERR_FAIL_COND(singleton!=NULL);
- singleton=this;
+ ERR_FAIL_COND(singleton != NULL);
+ singleton = this;
- buffer_end=0;
- buffer_max_used=0;
- buffer_size=GLOBAL_DEF( "memory/buffers/message_queue_max_size_kb", DEFAULT_QUEUE_SIZE_KB );
- buffer_size*=1024;
- buffer = memnew_arr( uint8_t, buffer_size );
+ buffer_end = 0;
+ buffer_max_used = 0;
+ buffer_size = GLOBAL_DEF("memory/buffers/message_queue_max_size_kb", DEFAULT_QUEUE_SIZE_KB);
+ buffer_size *= 1024;
+ buffer = memnew_arr(uint8_t, buffer_size);
}
-
MessageQueue::~MessageQueue() {
- uint32_t read_pos=0;
+ uint32_t read_pos = 0;
- while (read_pos < buffer_end ) {
+ while (read_pos < buffer_end) {
- Message *message = (Message*)&buffer[ read_pos ];
- Variant *args= (Variant*)(message+1);
+ Message *message = (Message *)&buffer[read_pos];
+ Variant *args = (Variant *)(message + 1);
int argc = message->args;
- if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION) {
- for (int i=0;i<argc;i++)
+ if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {
+ for (int i = 0; i < argc; i++)
args[i].~Variant();
}
message->~Message();
- read_pos+=sizeof(Message);
- if ((message->type&FLAG_MASK)!=TYPE_NOTIFICATION)
- read_pos+=sizeof(Variant)*message->args;
+ read_pos += sizeof(Message);
+ if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)
+ read_pos += sizeof(Variant) * message->args;
}
- singleton=NULL;
- memdelete_arr( buffer );
+ singleton = NULL;
+ memdelete_arr(buffer);
}
diff --git a/core/message_queue.h b/core/message_queue.h
index 1b1a20ba9a..e04530f24c 100644
--- a/core/message_queue.h
+++ b/core/message_queue.h
@@ -38,7 +38,7 @@ class MessageQueue {
enum {
- DEFAULT_QUEUE_SIZE_KB=1024
+ DEFAULT_QUEUE_SIZE_KB = 1024
};
Mutex *mutex;
@@ -47,8 +47,8 @@ class MessageQueue {
TYPE_CALL,
TYPE_NOTIFICATION,
TYPE_SET,
- FLAG_SHOW_ERROR=1<<14,
- FLAG_MASK=FLAG_SHOW_ERROR-1
+ FLAG_SHOW_ERROR = 1 << 14,
+ FLAG_MASK = FLAG_SHOW_ERROR - 1
};
@@ -68,21 +68,21 @@ class MessageQueue {
uint32_t buffer_max_used;
uint32_t buffer_size;
- void _call_function(Object* p_target,const StringName& p_func,const Variant *p_args,int p_argcount,bool p_show_error);
+ void _call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error);
static MessageQueue *singleton;
-public:
+public:
static MessageQueue *get_singleton();
- Error push_call(ObjectID p_id,const StringName& p_method,const Variant** p_args,int p_argcount,bool p_show_error=false);
- Error push_call(ObjectID p_id, const StringName& p_method, VARIANT_ARG_LIST);
+ Error push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error = false);
+ Error push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_LIST);
Error push_notification(ObjectID p_id, int p_notification);
- Error push_set(ObjectID p_id, const StringName& p_prop, const Variant& p_value);
+ Error push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value);
- Error push_call(Object *p_object, const StringName& p_method, VARIANT_ARG_LIST);
+ Error push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_LIST);
Error push_notification(Object *p_object, int p_notification);
- Error push_set(Object *p_object, const StringName& p_prop, const Variant& p_value);
+ Error push_set(Object *p_object, const StringName &p_prop, const Variant &p_value);
bool print();
void statistics();
diff --git a/core/method_bind.cpp b/core/method_bind.cpp
index 3465edff63..0f192a3b8a 100644
--- a/core/method_bind.cpp
+++ b/core/method_bind.cpp
@@ -32,59 +32,54 @@
#include "method_bind.h"
-
#ifdef DEBUG_METHODS_ENABLED
PropertyInfo MethodBind::get_argument_info(int p_argument) const {
+ if (p_argument >= 0) {
- if (p_argument>=0) {
-
- String name = (p_argument<arg_names.size())?String(arg_names[p_argument]):String("arg"+itos(p_argument));
- PropertyInfo pi( get_argument_type(p_argument), name );
- if ((pi.type==Variant::OBJECT) && name.find(":")!=-1) {
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string=name.get_slicec(':',1);
- pi.name=name.get_slicec(':',0);
+ String name = (p_argument < arg_names.size()) ? String(arg_names[p_argument]) : String("arg" + itos(p_argument));
+ PropertyInfo pi(get_argument_type(p_argument), name);
+ if ((pi.type == Variant::OBJECT) && name.find(":") != -1) {
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = name.get_slicec(':', 1);
+ pi.name = name.get_slicec(':', 0);
}
return pi;
} else {
Variant::Type at = get_argument_type(-1);
- if (at==Variant::OBJECT && ret_type)
- return PropertyInfo( at, "ret", PROPERTY_HINT_RESOURCE_TYPE, ret_type );
+ if (at == Variant::OBJECT && ret_type)
+ return PropertyInfo(at, "ret", PROPERTY_HINT_RESOURCE_TYPE, ret_type);
else
- return PropertyInfo( at, "ret" );
+ return PropertyInfo(at, "ret");
}
-
return PropertyInfo();
}
#endif
void MethodBind::_set_const(bool p_const) {
- _const=p_const;
+ _const = p_const;
}
void MethodBind::_set_returns(bool p_returns) {
- _returns=p_returns;
+ _returns = p_returns;
}
-
StringName MethodBind::get_name() const {
return name;
}
-void MethodBind::set_name(const StringName& p_name) {
- name=p_name;
+void MethodBind::set_name(const StringName &p_name) {
+ name = p_name;
}
#ifdef DEBUG_METHODS_ENABLED
-void MethodBind::set_argument_names(const Vector<StringName>& p_names) {
-
- arg_names=p_names;
+void MethodBind::set_argument_names(const Vector<StringName> &p_names) {
+ arg_names = p_names;
}
Vector<StringName> MethodBind::get_argument_names() const {
@@ -93,41 +88,36 @@ Vector<StringName> MethodBind::get_argument_names() const {
#endif
-
-
-void MethodBind::set_default_arguments(const Vector<Variant>& p_defargs) {
- default_arguments=p_defargs;
- default_argument_count=default_arguments.size();
-
+void MethodBind::set_default_arguments(const Vector<Variant> &p_defargs) {
+ default_arguments = p_defargs;
+ default_argument_count = default_arguments.size();
}
#ifdef DEBUG_METHODS_ENABLED
void MethodBind::_generate_argument_types(int p_count) {
-
set_argument_count(p_count);
- Variant::Type *argt = memnew_arr(Variant::Type,p_count+1);
- argt[0]=_gen_argument_type(-1);
- for(int i=0;i<p_count;i++) {
- argt[i+1]=_gen_argument_type(i);
+ Variant::Type *argt = memnew_arr(Variant::Type, p_count + 1);
+ argt[0] = _gen_argument_type(-1);
+ for (int i = 0; i < p_count; i++) {
+ argt[i + 1] = _gen_argument_type(i);
}
set_argument_types(argt);
-
}
#endif
MethodBind::MethodBind() {
- static int last_id=0;
- method_id=last_id++;
- hint_flags=METHOD_FLAGS_DEFAULT;
- argument_count=0;
- default_argument_count=0;
+ static int last_id = 0;
+ method_id = last_id++;
+ hint_flags = METHOD_FLAGS_DEFAULT;
+ argument_count = 0;
+ default_argument_count = 0;
#ifdef DEBUG_METHODS_ENABLED
- argument_types=NULL;
+ argument_types = NULL;
#endif
- _const=false;
- _returns=false;
+ _const = false;
+ _returns = false;
}
MethodBind::~MethodBind() {
@@ -136,4 +126,3 @@ MethodBind::~MethodBind() {
memdelete_arr(argument_types);
#endif
}
-
diff --git a/core/method_bind.h b/core/method_bind.h
index 7b59e6a6b0..f915a7563e 100644
--- a/core/method_bind.h
+++ b/core/method_bind.h
@@ -30,10 +30,10 @@
#define METHOD_BIND_H
#include "list.h"
-#include "variant.h"
+#include "method_ptrcall.h"
#include "object.h"
+#include "variant.h"
#include <stdio.h>
-#include "method_ptrcall.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -45,123 +45,118 @@
enum MethodFlags {
- METHOD_FLAG_NORMAL=1,
- METHOD_FLAG_EDITOR=2,
- METHOD_FLAG_NOSCRIPT=4,
- METHOD_FLAG_CONST=8,
- METHOD_FLAG_REVERSE=16, // used for events
- METHOD_FLAG_VIRTUAL=32,
- METHOD_FLAG_FROM_SCRIPT=64,
- METHOD_FLAG_VARARG=128,
- METHOD_FLAGS_DEFAULT=METHOD_FLAG_NORMAL,
+ METHOD_FLAG_NORMAL = 1,
+ METHOD_FLAG_EDITOR = 2,
+ METHOD_FLAG_NOSCRIPT = 4,
+ METHOD_FLAG_CONST = 8,
+ METHOD_FLAG_REVERSE = 16, // used for events
+ METHOD_FLAG_VIRTUAL = 32,
+ METHOD_FLAG_FROM_SCRIPT = 64,
+ METHOD_FLAG_VARARG = 128,
+ METHOD_FLAGS_DEFAULT = METHOD_FLAG_NORMAL,
};
-template<class T>
+template <class T>
struct VariantCaster {
- static _FORCE_INLINE_ T cast(const Variant& p_variant) {
+ static _FORCE_INLINE_ T cast(const Variant &p_variant) {
return p_variant;
}
};
-template<class T>
-struct VariantCaster<T&> {
+template <class T>
+struct VariantCaster<T &> {
- static _FORCE_INLINE_ T cast(const Variant& p_variant) {
+ static _FORCE_INLINE_ T cast(const Variant &p_variant) {
return p_variant;
}
};
-template<class T>
-struct VariantCaster<const T&> {
+template <class T>
+struct VariantCaster<const T &> {
- static _FORCE_INLINE_ T cast(const Variant& p_variant) {
+ static _FORCE_INLINE_ T cast(const Variant &p_variant) {
return p_variant;
}
};
-#define _VC( m_idx )\
- (VariantCaster<P##m_idx>::cast( (m_idx-1)>=p_arg_count?get_default_argument(m_idx-1):*p_args[m_idx-1] ))
+#define _VC(m_idx) \
+ (VariantCaster<P##m_idx>::cast((m_idx - 1) >= p_arg_count ? get_default_argument(m_idx - 1) : *p_args[m_idx - 1]))
//SIMPLE_NUMERIC_TYPE is used to avoid a warning on Variant::get_type_for
#ifdef PTRCALL_ENABLED
-
-#define VARIANT_ENUM_CAST( m_enum ) \
-SIMPLE_NUMERIC_TYPE( m_enum );\
-template<> \
-struct VariantCaster<m_enum> {\
-\
- static _FORCE_INLINE_ m_enum cast(const Variant& p_variant) {\
- return (m_enum)p_variant.operator int();\
- }\
-};\
-template<>\
-struct PtrToArg< m_enum > {\
- _FORCE_INLINE_ static m_enum convert(const void* p_ptr) {\
- return m_enum(*reinterpret_cast<const int*>(p_ptr));\
- }\
- _FORCE_INLINE_ static void encode(m_enum p_val,const void* p_ptr) {\
- *(int*)p_ptr=p_val;\
- }\
-};
+#define VARIANT_ENUM_CAST(m_enum) \
+ SIMPLE_NUMERIC_TYPE(m_enum); \
+ template <> \
+ struct VariantCaster<m_enum> { \
+ \
+ static _FORCE_INLINE_ m_enum cast(const Variant &p_variant) { \
+ return (m_enum)p_variant.operator int(); \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<m_enum> { \
+ _FORCE_INLINE_ static m_enum convert(const void *p_ptr) { \
+ return m_enum(*reinterpret_cast<const int *>(p_ptr)); \
+ } \
+ _FORCE_INLINE_ static void encode(m_enum p_val, const void *p_ptr) { \
+ *(int *)p_ptr = p_val; \
+ } \
+ };
#else
-
-#define VARIANT_ENUM_CAST( m_enum ) \
-SIMPLE_NUMERIC_TYPE( m_enum );\
-template<> \
-struct VariantCaster<m_enum> {\
-\
- static _FORCE_INLINE_ m_enum cast(const Variant& p_variant) {\
- return (m_enum)p_variant.operator int();\
- }\
-};
-
+#define VARIANT_ENUM_CAST(m_enum) \
+ SIMPLE_NUMERIC_TYPE(m_enum); \
+ template <> \
+ struct VariantCaster<m_enum> { \
+ \
+ static _FORCE_INLINE_ m_enum cast(const Variant &p_variant) { \
+ return (m_enum)p_variant.operator int(); \
+ } \
+ };
#endif
-
-#define CHECK_ARG(m_arg)\
- if ((m_arg-1)<p_arg_count) {\
- Variant::Type argtype=get_argument_type(m_arg-1);\
- if (!Variant::can_convert_strict(p_args[m_arg-1]->get_type(),argtype)) {\
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\
- r_error.argument=m_arg-1;\
- r_error.expected=argtype;\
- return Variant();\
- }\
+#define CHECK_ARG(m_arg) \
+ if ((m_arg - 1) < p_arg_count) { \
+ Variant::Type argtype = get_argument_type(m_arg - 1); \
+ if (!Variant::can_convert_strict(p_args[m_arg - 1]->get_type(), argtype)) { \
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \
+ r_error.argument = m_arg - 1; \
+ r_error.expected = argtype; \
+ return Variant(); \
+ } \
}
-#define CHECK_NOARG(m_arg)\
- {\
- if (p_arg##m_arg.get_type()!=Variant::NIL) {\
- if (r_argerror) *r_argerror=(m_arg-1);\
- return CALL_ERROR_EXTRA_ARGUMENT;\
- }\
+#define CHECK_NOARG(m_arg) \
+ { \
+ if (p_arg##m_arg.get_type() != Variant::NIL) { \
+ if (r_argerror) *r_argerror = (m_arg - 1); \
+ return CALL_ERROR_EXTRA_ARGUMENT; \
+ } \
}
// some helpers
-VARIANT_ENUM_CAST( Vector3::Axis );
-VARIANT_ENUM_CAST( Image::Format );
-VARIANT_ENUM_CAST( Error );
-VARIANT_ENUM_CAST( wchar_t );
-VARIANT_ENUM_CAST( Margin );
-VARIANT_ENUM_CAST( Orientation );
-VARIANT_ENUM_CAST( HAlign );
-VARIANT_ENUM_CAST( Variant::Type );
-VARIANT_ENUM_CAST( Variant::Operator );
-VARIANT_ENUM_CAST( InputEvent::Type );
+VARIANT_ENUM_CAST(Vector3::Axis);
+VARIANT_ENUM_CAST(Image::Format);
+VARIANT_ENUM_CAST(Error);
+VARIANT_ENUM_CAST(wchar_t);
+VARIANT_ENUM_CAST(Margin);
+VARIANT_ENUM_CAST(Orientation);
+VARIANT_ENUM_CAST(HAlign);
+VARIANT_ENUM_CAST(Variant::Type);
+VARIANT_ENUM_CAST(Variant::Operator);
+VARIANT_ENUM_CAST(InputEvent::Type);
class MethodBind {
-
int method_id;
uint32_t hint_flags;
StringName name;
@@ -176,27 +171,25 @@ class MethodBind {
bool _const;
bool _returns;
-
protected:
-
void _set_const(bool p_const);
void _set_returns(bool p_returns);
#ifdef DEBUG_METHODS_ENABLED
- virtual Variant::Type _gen_argument_type(int p_arg) const=0;
+ virtual Variant::Type _gen_argument_type(int p_arg) const = 0;
void _generate_argument_types(int p_count);
- void set_argument_types(Variant::Type *p_types) { argument_types=p_types; }
+ void set_argument_types(Variant::Type *p_types) { argument_types = p_types; }
#endif
- void set_argument_count(int p_count) { argument_count=p_count; }
-public:
+ void set_argument_count(int p_count) { argument_count = p_count; }
+public:
Vector<Variant> get_default_arguments() const { return default_arguments; }
_FORCE_INLINE_ int get_default_argument_count() const { return default_argument_count; }
_FORCE_INLINE_ Variant has_default_argument(int p_arg) const {
- int idx=argument_count-p_arg-1;
+ int idx = argument_count - p_arg - 1;
- if (idx<0 || idx>=default_arguments.size())
+ if (idx < 0 || idx >= default_arguments.size())
return false;
else
return true;
@@ -204,9 +197,9 @@ public:
_FORCE_INLINE_ Variant get_default_argument(int p_arg) const {
- int idx=argument_count-p_arg-1;
+ int idx = argument_count - p_arg - 1;
- if (idx<0 || idx>=default_arguments.size())
+ if (idx < 0 || idx >= default_arguments.size())
return Variant();
else
return default_arguments[idx];
@@ -214,24 +207,23 @@ public:
#ifdef DEBUG_METHODS_ENABLED
- _FORCE_INLINE_ void set_return_type(const StringName& p_type) { ret_type=p_type; }
+ _FORCE_INLINE_ void set_return_type(const StringName &p_type) { ret_type = p_type; }
_FORCE_INLINE_ StringName get_return_type() const { return ret_type; }
_FORCE_INLINE_ Variant::Type get_argument_type(int p_argument) const {
- ERR_FAIL_COND_V(p_argument<-1 || p_argument>argument_count,Variant::NIL);
- return argument_types[p_argument+1];
-
+ ERR_FAIL_COND_V(p_argument < -1 || p_argument > argument_count, Variant::NIL);
+ return argument_types[p_argument + 1];
}
PropertyInfo get_argument_info(int p_argument) const;
- void set_argument_names(const Vector<StringName>& p_names);
+ void set_argument_names(const Vector<StringName> &p_names);
Vector<StringName> get_argument_names() const;
#endif
- void set_hint_flags(uint32_t p_hint) { hint_flags=p_hint; }
- uint32_t get_hint_flags() const { return hint_flags|(is_const()?METHOD_FLAG_CONST:0)|(is_vararg()?METHOD_FLAG_VARARG:0); }
- virtual String get_instance_class() const=0;
+ void set_hint_flags(uint32_t p_hint) { hint_flags = p_hint; }
+ uint32_t get_hint_flags() const { return hint_flags | (is_const() ? METHOD_FLAG_CONST : 0) | (is_vararg() ? METHOD_FLAG_VARARG : 0); }
+ virtual String get_instance_class() const = 0;
_FORCE_INLINE_ int get_argument_count() const { return argument_count; };
@@ -257,60 +249,58 @@ public:
return Variant();
}
#endif
- virtual Variant call(Object* p_object,const Variant** p_args,int p_arg_count, Variant::CallError& r_error)=0;
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Variant::CallError &r_error) = 0;
#ifdef PTRCALL_ENABLED
- virtual void ptrcall(Object* p_object,const void** p_args,void* r_ret)=0;
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) = 0;
#endif
StringName get_name() const;
- void set_name(const StringName& p_name);
+ void set_name(const StringName &p_name);
_FORCE_INLINE_ int get_method_id() const { return method_id; }
_FORCE_INLINE_ bool is_const() const { return _const; }
_FORCE_INLINE_ bool has_return() const { return _returns; }
virtual bool is_vararg() const { return false; }
- void set_default_arguments(const Vector<Variant>& p_defargs);
+ void set_default_arguments(const Vector<Variant> &p_defargs);
MethodBind();
virtual ~MethodBind();
};
-
-template<class T>
+template <class T>
class MethodBindVarArg : public MethodBind {
public:
- typedef Variant (T::*NativeCall)(const Variant**,int ,Variant::CallError &);
-protected:
+ typedef Variant (T::*NativeCall)(const Variant **, int, Variant::CallError &);
+protected:
NativeCall call_method;
-public:
+public:
virtual Variant::Type _gen_argument_type(int p_arg) const {
return Variant::NIL;
}
- virtual Variant call(Object* p_object,const Variant** p_args,int p_arg_count, Variant::CallError& r_error) {
+ virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Variant::CallError &r_error) {
- T* instance=static_cast<T*>(p_object);
- return (instance->*call_method)(p_args,p_arg_count,r_error);
+ T *instance = static_cast<T *>(p_object);
+ return (instance->*call_method)(p_args, p_arg_count, r_error);
}
- void set_method_info(const MethodInfo& p_info) {
+ void set_method_info(const MethodInfo &p_info) {
-
- set_argument_count( p_info.arguments.size() );
+ set_argument_count(p_info.arguments.size());
#ifdef DEBUG_METHODS_ENABLED
- Variant::Type *at = memnew_arr( Variant::Type , p_info.arguments.size()+1 );
- at[0]=p_info.return_val.type;
+ Variant::Type *at = memnew_arr(Variant::Type, p_info.arguments.size() + 1);
+ at[0] = p_info.return_val.type;
if (p_info.arguments.size()) {
Vector<StringName> names;
names.resize(p_info.arguments.size());
- for(int i=0;i<p_info.arguments.size();i++) {
+ for (int i = 0; i < p_info.arguments.size(); i++) {
- at[i+1]=p_info.arguments[i].type;
- names[i]=p_info.arguments[i].name;
+ at[i + 1] = p_info.arguments[i].type;
+ names[i] = p_info.arguments[i].name;
}
set_argument_names(names);
@@ -320,32 +310,32 @@ public:
}
#ifdef PTRCALL_ENABLED
- virtual void ptrcall(Object* p_object,const void** p_args,void* r_ret) {
+ virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) {
ERR_FAIL(); //can't call
} //todo
#endif
-
- void set_method(NativeCall p_method) { call_method=p_method; }
+ void set_method(NativeCall p_method) { call_method = p_method; }
virtual bool is_const() const { return false; }
virtual String get_instance_class() const { return T::get_class_static(); }
virtual bool is_vararg() const { return true; }
- MethodBindVarArg() { call_method=NULL; _set_returns(true);}
+ MethodBindVarArg() {
+ call_method = NULL;
+ _set_returns(true);
+ }
};
+template <class T>
+MethodBind *create_vararg_method_bind(Variant (T::*p_method)(const Variant **, int, Variant::CallError &), const MethodInfo &p_info) {
-template<class T >
-MethodBind* create_vararg_method_bind( Variant (T::*p_method)(const Variant**,int ,Variant::CallError &), const MethodInfo& p_info ) {
-
- MethodBindVarArg<T > * a = memnew( (MethodBindVarArg<T >) );
+ MethodBindVarArg<T> *a = memnew((MethodBindVarArg<T>));
a->set_method(p_method);
a->set_method_info(p_info);
return a;
}
-
/** This amazing hack is based on the FastDelegates theory */
// tale of an amazing hack.. //
@@ -353,7 +343,6 @@ MethodBind* create_vararg_method_bind( Variant (T::*p_method)(const Variant**,in
// if you declare an nonexistent class..
class __UnexistingClass;
-
#include "method_bind.inc"
#endif
diff --git a/core/method_ptrcall.h b/core/method_ptrcall.h
index 3a205d5e78..26d7538bf8 100644
--- a/core/method_ptrcall.h
+++ b/core/method_ptrcall.h
@@ -29,71 +29,67 @@
#ifndef METHOD_PTRCALL_H
#define METHOD_PTRCALL_H
-#include "typedefs.h"
#include "math_2d.h"
+#include "typedefs.h"
#include "variant.h"
#ifdef PTRCALL_ENABLED
-template<class T>
+template <class T>
struct PtrToArg {
-
};
-#define MAKE_PTRARG(m_type) \
-template<>\
-struct PtrToArg<m_type> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- return *reinterpret_cast<const m_type*>(p_ptr);\
- }\
- _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\
- *((m_type*)p_ptr)=p_val;\
- }\
-};\
-template<>\
-struct PtrToArg<const m_type&> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- return *reinterpret_cast<const m_type*>(p_ptr);\
- }\
- _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\
- *((m_type*)p_ptr)=p_val;\
- }\
-}
-
-
-#define MAKE_PTRARGR(m_type,m_ret) \
-template<>\
-struct PtrToArg<m_type> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- return *reinterpret_cast<const m_type*>(p_ptr);\
- }\
- _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\
- *((m_ret*)p_ptr)=p_val;\
- }\
-};\
-template<>\
-struct PtrToArg<const m_type&> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- return *reinterpret_cast<const m_type*>(p_ptr);\
- }\
- _FORCE_INLINE_ static void encode(m_type p_val, void* p_ptr) {\
- *((m_ret*)p_ptr)=p_val;\
- }\
-}
-
+#define MAKE_PTRARG(m_type) \
+ template <> \
+ struct PtrToArg<m_type> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ return *reinterpret_cast<const m_type *>(p_ptr); \
+ } \
+ _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \
+ *((m_type *)p_ptr) = p_val; \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<const m_type &> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ return *reinterpret_cast<const m_type *>(p_ptr); \
+ } \
+ _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \
+ *((m_type *)p_ptr) = p_val; \
+ } \
+ }
+#define MAKE_PTRARGR(m_type, m_ret) \
+ template <> \
+ struct PtrToArg<m_type> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ return *reinterpret_cast<const m_type *>(p_ptr); \
+ } \
+ _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \
+ *((m_ret *)p_ptr) = p_val; \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<const m_type &> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ return *reinterpret_cast<const m_type *>(p_ptr); \
+ } \
+ _FORCE_INLINE_ static void encode(m_type p_val, void *p_ptr) { \
+ *((m_ret *)p_ptr) = p_val; \
+ } \
+ }
MAKE_PTRARG(bool);
-MAKE_PTRARGR(uint8_t,int);
-MAKE_PTRARGR(int8_t,int);
-MAKE_PTRARGR(uint16_t,int);
-MAKE_PTRARGR(int16_t,int);
-MAKE_PTRARGR(uint32_t,int);
-MAKE_PTRARGR(int32_t,int);
-MAKE_PTRARGR(int64_t,int);
-MAKE_PTRARGR(uint64_t,int);
+MAKE_PTRARGR(uint8_t, int);
+MAKE_PTRARGR(int8_t, int);
+MAKE_PTRARGR(uint16_t, int);
+MAKE_PTRARGR(int16_t, int);
+MAKE_PTRARGR(uint32_t, int);
+MAKE_PTRARGR(int32_t, int);
+MAKE_PTRARGR(int64_t, int);
+MAKE_PTRARGR(uint64_t, int);
MAKE_PTRARG(float);
-MAKE_PTRARGR(double,float);
+MAKE_PTRARGR(double, float);
MAKE_PTRARG(String);
MAKE_PTRARG(Vector2);
@@ -122,86 +118,82 @@ MAKE_PTRARG(PoolColorArray);
MAKE_PTRARG(Variant);
MAKE_PTRARG(PowerState);
-
//this is for Object
-template<class T>
-struct PtrToArg< T* > {
+template <class T>
+struct PtrToArg<T *> {
- _FORCE_INLINE_ static T* convert(const void* p_ptr) {
+ _FORCE_INLINE_ static T *convert(const void *p_ptr) {
- return const_cast<T*>(reinterpret_cast<const T*>(p_ptr));
+ return const_cast<T *>(reinterpret_cast<const T *>(p_ptr));
}
- _FORCE_INLINE_ static void encode(T* p_var, void* p_ptr) {
+ _FORCE_INLINE_ static void encode(T *p_var, void *p_ptr) {
- *((T**)p_ptr)=p_var;
+ *((T **)p_ptr) = p_var;
}
-
};
-template<class T>
-struct PtrToArg< const T* > {
+template <class T>
+struct PtrToArg<const T *> {
- _FORCE_INLINE_ static const T* convert(const void* p_ptr) {
+ _FORCE_INLINE_ static const T *convert(const void *p_ptr) {
- return reinterpret_cast<const T*>(p_ptr);
+ return reinterpret_cast<const T *>(p_ptr);
}
- _FORCE_INLINE_ static void encode(T* p_var, void* p_ptr) {
+ _FORCE_INLINE_ static void encode(T *p_var, void *p_ptr) {
- *((T**)p_ptr)=p_var;
+ *((T **)p_ptr) = p_var;
}
-
};
-
//this is for the special cases used by Variant
-#define MAKE_VECARG(m_type) \
-template<>\
-struct PtrToArg<Vector<m_type> > {\
- _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\
- const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr);\
- Vector<m_type> ret;\
- int len = dvs->size();\
- ret.resize(len);\
- {\
- PoolVector<m_type>::Read r=dvs->read();\
- for(int i=0;i<len;i++) {\
- ret[i]=r[i];\
- }\
- } \
- return ret;\
- }\
- _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void* p_ptr) {\
- PoolVector<m_type> *dv = reinterpret_cast<PoolVector<m_type> *>(p_ptr);\
- int len=p_vec.size();\
- dv->resize(len);\
- {\
- PoolVector<m_type>::Write w=dv->write();\
- for(int i=0;i<len;i++) {\
- w[i]=p_vec[i];\
- }\
- } \
- }\
-};\
-template<>\
-struct PtrToArg<const Vector<m_type>& > {\
- _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\
- const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr);\
- Vector<m_type> ret;\
- int len = dvs->size();\
- ret.resize(len);\
- {\
- PoolVector<m_type>::Read r=dvs->read();\
- for(int i=0;i<len;i++) {\
- ret[i]=r[i];\
- }\
- } \
- return ret;\
- }\
-}
+#define MAKE_VECARG(m_type) \
+ template <> \
+ struct PtrToArg<Vector<m_type> > { \
+ _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \
+ const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr); \
+ Vector<m_type> ret; \
+ int len = dvs->size(); \
+ ret.resize(len); \
+ { \
+ PoolVector<m_type>::Read r = dvs->read(); \
+ for (int i = 0; i < len; i++) { \
+ ret[i] = r[i]; \
+ } \
+ } \
+ return ret; \
+ } \
+ _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void *p_ptr) { \
+ PoolVector<m_type> *dv = reinterpret_cast<PoolVector<m_type> *>(p_ptr); \
+ int len = p_vec.size(); \
+ dv->resize(len); \
+ { \
+ PoolVector<m_type>::Write w = dv->write(); \
+ for (int i = 0; i < len; i++) { \
+ w[i] = p_vec[i]; \
+ } \
+ } \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<const Vector<m_type> &> { \
+ _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \
+ const PoolVector<m_type> *dvs = reinterpret_cast<const PoolVector<m_type> *>(p_ptr); \
+ Vector<m_type> ret; \
+ int len = dvs->size(); \
+ ret.resize(len); \
+ { \
+ PoolVector<m_type>::Read r = dvs->read(); \
+ for (int i = 0; i < len; i++) { \
+ ret[i] = r[i]; \
+ } \
+ } \
+ return ret; \
+ } \
+ }
MAKE_VECARG(String);
MAKE_VECARG(uint8_t);
@@ -212,172 +204,170 @@ MAKE_VECARG(Vector3);
MAKE_VECARG(Color);
//for stuff that gets converted to Array vectors
-#define MAKE_VECARR(m_type) \
-template<>\
-struct PtrToArg<Vector<m_type> > {\
- _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\
- const Array *arr = reinterpret_cast<const Array *>(p_ptr);\
- Vector<m_type> ret;\
- int len = arr->size();\
- ret.resize(len);\
- for(int i=0;i<len;i++) {\
- ret[i]=(*arr)[i];\
- }\
- return ret;\
- }\
- _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void* p_ptr) {\
- Array *arr = reinterpret_cast<Array *>(p_ptr);\
- int len = p_vec.size();\
- arr->resize(len);\
- for(int i=0;i<len;i++) {\
- (*arr)[i]=p_vec[i];\
- }\
- } \
-};\
-template<>\
-struct PtrToArg<const Vector<m_type>& > {\
- _FORCE_INLINE_ static Vector<m_type> convert(const void* p_ptr) {\
- const Array *arr = reinterpret_cast<const Array *>(p_ptr);\
- Vector<m_type> ret;\
- int len = arr->size();\
- ret.resize(len);\
- for(int i=0;i<len;i++) {\
- ret[i]=(*arr)[i];\
- }\
- return ret;\
- }\
-}
-
+#define MAKE_VECARR(m_type) \
+ template <> \
+ struct PtrToArg<Vector<m_type> > { \
+ _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \
+ const Array *arr = reinterpret_cast<const Array *>(p_ptr); \
+ Vector<m_type> ret; \
+ int len = arr->size(); \
+ ret.resize(len); \
+ for (int i = 0; i < len; i++) { \
+ ret[i] = (*arr)[i]; \
+ } \
+ return ret; \
+ } \
+ _FORCE_INLINE_ static void encode(Vector<m_type> p_vec, void *p_ptr) { \
+ Array *arr = reinterpret_cast<Array *>(p_ptr); \
+ int len = p_vec.size(); \
+ arr->resize(len); \
+ for (int i = 0; i < len; i++) { \
+ (*arr)[i] = p_vec[i]; \
+ } \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<const Vector<m_type> &> { \
+ _FORCE_INLINE_ static Vector<m_type> convert(const void *p_ptr) { \
+ const Array *arr = reinterpret_cast<const Array *>(p_ptr); \
+ Vector<m_type> ret; \
+ int len = arr->size(); \
+ ret.resize(len); \
+ for (int i = 0; i < len; i++) { \
+ ret[i] = (*arr)[i]; \
+ } \
+ return ret; \
+ } \
+ }
MAKE_VECARR(Variant);
MAKE_VECARR(RID);
MAKE_VECARR(Plane);
-#define MAKE_DVECARR(m_type) \
-template<>\
-struct PtrToArg<PoolVector<m_type> > {\
- _FORCE_INLINE_ static PoolVector<m_type> convert(const void* p_ptr) {\
- const Array *arr = reinterpret_cast<const Array *>(p_ptr);\
- PoolVector<m_type> ret;\
- int len = arr->size();\
- ret.resize(len);\
- {\
- PoolVector<m_type>::Write w=ret.write();\
- for(int i=0;i<len;i++) {\
- w[i]=(*arr)[i];\
- }\
- }\
- return ret;\
- }\
- _FORCE_INLINE_ static void encode(PoolVector<m_type> p_vec, void* p_ptr) {\
- Array *arr = reinterpret_cast<Array *>(p_ptr);\
- int len = p_vec.size();\
- arr->resize(len);\
- {\
- PoolVector<m_type>::Read r=p_vec.read();\
- for(int i=0;i<len;i++) {\
- (*arr)[i]=r[i];\
- }\
- }\
- } \
-};\
-template<>\
-struct PtrToArg<const PoolVector<m_type>& > {\
- _FORCE_INLINE_ static PoolVector<m_type> convert(const void* p_ptr) {\
- const Array *arr = reinterpret_cast<const Array *>(p_ptr);\
- PoolVector<m_type> ret;\
- int len = arr->size();\
- ret.resize(len);\
- {\
- PoolVector<m_type>::Write w=ret.write();\
- for(int i=0;i<len;i++) {\
- w[i]=(*arr)[i];\
- }\
- }\
- return ret;\
- }\
-}
+#define MAKE_DVECARR(m_type) \
+ template <> \
+ struct PtrToArg<PoolVector<m_type> > { \
+ _FORCE_INLINE_ static PoolVector<m_type> convert(const void *p_ptr) { \
+ const Array *arr = reinterpret_cast<const Array *>(p_ptr); \
+ PoolVector<m_type> ret; \
+ int len = arr->size(); \
+ ret.resize(len); \
+ { \
+ PoolVector<m_type>::Write w = ret.write(); \
+ for (int i = 0; i < len; i++) { \
+ w[i] = (*arr)[i]; \
+ } \
+ } \
+ return ret; \
+ } \
+ _FORCE_INLINE_ static void encode(PoolVector<m_type> p_vec, void *p_ptr) { \
+ Array *arr = reinterpret_cast<Array *>(p_ptr); \
+ int len = p_vec.size(); \
+ arr->resize(len); \
+ { \
+ PoolVector<m_type>::Read r = p_vec.read(); \
+ for (int i = 0; i < len; i++) { \
+ (*arr)[i] = r[i]; \
+ } \
+ } \
+ } \
+ }; \
+ template <> \
+ struct PtrToArg<const PoolVector<m_type> &> { \
+ _FORCE_INLINE_ static PoolVector<m_type> convert(const void *p_ptr) { \
+ const Array *arr = reinterpret_cast<const Array *>(p_ptr); \
+ PoolVector<m_type> ret; \
+ int len = arr->size(); \
+ ret.resize(len); \
+ { \
+ PoolVector<m_type>::Write w = ret.write(); \
+ for (int i = 0; i < len; i++) { \
+ w[i] = (*arr)[i]; \
+ } \
+ } \
+ return ret; \
+ } \
+ }
MAKE_DVECARR(Plane);
//for special case StringName
-#define MAKE_STRINGCONV(m_type) \
-template<>\
-struct PtrToArg<m_type> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- m_type s = *reinterpret_cast<const String*>(p_ptr);\
- return s;\
- }\
- _FORCE_INLINE_ static void encode(m_type p_vec, void* p_ptr) {\
- String *arr = reinterpret_cast<String *>(p_ptr);\
- *arr=p_vec;\
- }\
-};\
-\
-template<>\
-struct PtrToArg<const m_type&> {\
- _FORCE_INLINE_ static m_type convert(const void* p_ptr) {\
- m_type s = *reinterpret_cast<const String*>(p_ptr);\
- return s;\
- }\
-}
+#define MAKE_STRINGCONV(m_type) \
+ template <> \
+ struct PtrToArg<m_type> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ m_type s = *reinterpret_cast<const String *>(p_ptr); \
+ return s; \
+ } \
+ _FORCE_INLINE_ static void encode(m_type p_vec, void *p_ptr) { \
+ String *arr = reinterpret_cast<String *>(p_ptr); \
+ *arr = p_vec; \
+ } \
+ }; \
+ \
+ template <> \
+ struct PtrToArg<const m_type &> { \
+ _FORCE_INLINE_ static m_type convert(const void *p_ptr) { \
+ m_type s = *reinterpret_cast<const String *>(p_ptr); \
+ return s; \
+ } \
+ }
MAKE_STRINGCONV(StringName);
MAKE_STRINGCONV(IP_Address);
-template<>
+template <>
struct PtrToArg<PoolVector<Face3> > {
- _FORCE_INLINE_ static PoolVector<Face3> convert(const void* p_ptr) {
+ _FORCE_INLINE_ static PoolVector<Face3> convert(const void *p_ptr) {
const PoolVector<Vector3> *dvs = reinterpret_cast<const PoolVector<Vector3> *>(p_ptr);
PoolVector<Face3> ret;
- int len = dvs->size()/3;
+ int len = dvs->size() / 3;
ret.resize(len);
{
- PoolVector<Vector3>::Read r=dvs->read();
- PoolVector<Face3>::Write w=ret.write();
- for(int i=0;i<len;i++) {
- w[i].vertex[0]=r[i*3+0];
- w[i].vertex[1]=r[i*3+1];
- w[i].vertex[2]=r[i*3+2];
+ PoolVector<Vector3>::Read r = dvs->read();
+ PoolVector<Face3>::Write w = ret.write();
+ for (int i = 0; i < len; i++) {
+ w[i].vertex[0] = r[i * 3 + 0];
+ w[i].vertex[1] = r[i * 3 + 1];
+ w[i].vertex[2] = r[i * 3 + 2];
}
}
return ret;
}
- _FORCE_INLINE_ static void encode(PoolVector<Face3> p_vec, void* p_ptr) {\
- PoolVector<Vector3> *arr = reinterpret_cast<PoolVector<Vector3> *>(p_ptr);\
- int len = p_vec.size();\
- arr->resize(len*3);\
- {\
- PoolVector<Face3>::Read r=p_vec.read();\
- PoolVector<Vector3>::Write w=arr->write();\
- for(int i=0;i<len;i++) {\
- w[i*3+0]=r[i].vertex[0];\
- w[i*3+1]=r[i].vertex[1];\
- w[i*3+2]=r[i].vertex[2];\
- }\
- }\
- } \
+ _FORCE_INLINE_ static void encode(PoolVector<Face3> p_vec, void *p_ptr) {
+ PoolVector<Vector3> *arr = reinterpret_cast<PoolVector<Vector3> *>(p_ptr);
+ int len = p_vec.size();
+ arr->resize(len * 3);
+ {
+ PoolVector<Face3>::Read r = p_vec.read();
+ PoolVector<Vector3>::Write w = arr->write();
+ for (int i = 0; i < len; i++) {
+ w[i * 3 + 0] = r[i].vertex[0];
+ w[i * 3 + 1] = r[i].vertex[1];
+ w[i * 3 + 2] = r[i].vertex[2];
+ }
+ }
+ }
};
-template<>
-struct PtrToArg<const PoolVector<Face3>& > {
- _FORCE_INLINE_ static PoolVector<Face3> convert(const void* p_ptr) {
+template <>
+struct PtrToArg<const PoolVector<Face3> &> {
+ _FORCE_INLINE_ static PoolVector<Face3> convert(const void *p_ptr) {
const PoolVector<Vector3> *dvs = reinterpret_cast<const PoolVector<Vector3> *>(p_ptr);
PoolVector<Face3> ret;
- int len = dvs->size()/3;
+ int len = dvs->size() / 3;
ret.resize(len);
{
- PoolVector<Vector3>::Read r=dvs->read();
- PoolVector<Face3>::Write w=ret.write();
- for(int i=0;i<len;i++) {
- w[i].vertex[0]=r[i*3+0];
- w[i].vertex[1]=r[i*3+1];
- w[i].vertex[2]=r[i*3+2];
+ PoolVector<Vector3>::Read r = dvs->read();
+ PoolVector<Face3>::Write w = ret.write();
+ for (int i = 0; i < len; i++) {
+ w[i].vertex[0] = r[i * 3 + 0];
+ w[i].vertex[1] = r[i * 3 + 1];
+ w[i].vertex[2] = r[i * 3 + 2];
}
}
return ret;
}
};
-
#endif // METHOD_PTRCALL_H
#endif
diff --git a/core/object.cpp b/core/object.cpp
index 79905a6be6..e9b332fafa 100644
--- a/core/object.cpp
+++ b/core/object.cpp
@@ -28,14 +28,14 @@
/*************************************************************************/
#include "object.h"
-#include "print_string.h"
#include "class_db.h"
-#include "script_language.h"
-#include "message_queue.h"
#include "core_string_names.h"
-#include "translation.h"
+#include "message_queue.h"
#include "os/os.h"
+#include "print_string.h"
#include "resource.h"
+#include "script_language.h"
+#include "translation.h"
#ifdef DEBUG_ENABLED
@@ -44,7 +44,7 @@ struct _ObjectDebugLock {
Object *obj;
_ObjectDebugLock(Object *p_obj) {
- obj=p_obj;
+ obj = p_obj;
obj->_lock_index.ref();
}
~_ObjectDebugLock() {
@@ -60,48 +60,44 @@ struct _ObjectDebugLock {
#endif
-
PropertyInfo::operator Dictionary() const {
Dictionary d;
- d["name"]=name;
- d["type"]=type;
- d["hint"]=hint;
- d["hint_string"]=hint_string;
- d["usage"]=usage;
+ d["name"] = name;
+ d["type"] = type;
+ d["hint"] = hint;
+ d["hint_string"] = hint_string;
+ d["usage"] = usage;
return d;
-
}
-PropertyInfo PropertyInfo::from_dict(const Dictionary& p_dict) {
+PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
PropertyInfo pi;
if (p_dict.has("type"))
- pi.type=Variant::Type(int(p_dict["type"]));
+ pi.type = Variant::Type(int(p_dict["type"]));
if (p_dict.has("name"))
- pi.name=p_dict["name"];
+ pi.name = p_dict["name"];
if (p_dict.has("hint"))
- pi.hint=PropertyHint(int(p_dict["hint"]));
+ pi.hint = PropertyHint(int(p_dict["hint"]));
if (p_dict.has("hint_string"))
- pi.hint_string=p_dict["hint_string"];
+ pi.hint_string = p_dict["hint_string"];
if (p_dict.has("usage"))
- pi.usage=p_dict["usage"];
+ pi.usage = p_dict["usage"];
return pi;
}
-
-Array convert_property_list(const List<PropertyInfo> * p_list) {
+Array convert_property_list(const List<PropertyInfo> *p_list) {
Array va;
- for (const List<PropertyInfo>::Element *E=p_list->front();E;E=E->next()) {
-
+ for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
va.push_back(Dictionary(E->get()));
}
@@ -111,201 +107,198 @@ Array convert_property_list(const List<PropertyInfo> * p_list) {
MethodInfo::operator Dictionary() const {
-
Dictionary d;
- d["name"]=name;
- d["args"]=convert_property_list(&arguments);
+ d["name"] = name;
+ d["args"] = convert_property_list(&arguments);
Array da;
- for(int i=0;i<default_arguments.size();i++)
+ for (int i = 0; i < default_arguments.size(); i++)
da.push_back(default_arguments[i]);
- d["default_args"]=da;
- d["flags"]=flags;
- d["id"]=id;
+ d["default_args"] = da;
+ d["flags"] = flags;
+ d["id"] = id;
Dictionary r = return_val;
- d["return"]=r;
+ d["return"] = r;
return d;
-
}
MethodInfo::MethodInfo() {
- id=0;
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo MethodInfo::from_dict(const Dictionary& p_dict) {
+MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) {
MethodInfo mi;
if (p_dict.has("name"))
- mi.name=p_dict["name"];
+ mi.name = p_dict["name"];
Array args;
if (p_dict.has("args")) {
- args=p_dict["args"];
+ args = p_dict["args"];
}
- for(int i=0;i<args.size();i++) {
+ for (int i = 0; i < args.size(); i++) {
Dictionary d = args[i];
mi.arguments.push_back(PropertyInfo::from_dict(d));
}
Array defargs;
if (p_dict.has("default_args")) {
- defargs=p_dict["default_args"];
+ defargs = p_dict["default_args"];
}
- for(int i=0;i<defargs.size();i++) {
+ for (int i = 0; i < defargs.size(); i++) {
mi.default_arguments.push_back(defargs[i]);
}
if (p_dict.has("return")) {
- mi.return_val=PropertyInfo::from_dict(p_dict["return"]);
+ mi.return_val = PropertyInfo::from_dict(p_dict["return"]);
}
if (p_dict.has("flags"))
- mi.flags=p_dict["flags"];
+ mi.flags = p_dict["flags"];
return mi;
}
-MethodInfo::MethodInfo(const String& p_name) {
+MethodInfo::MethodInfo(const String &p_name) {
- id=0;
- name=p_name;
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ name = p_name;
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1) {
+MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2) {
+MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3) {
+MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4) {
+MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- arguments.push_back( p_param4 );
- flags=METHOD_FLAG_NORMAL;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ arguments.push_back(p_param4);
+ flags = METHOD_FLAG_NORMAL;
}
-MethodInfo::MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- arguments.push_back( p_param4 );
- arguments.push_back( p_param5 );
- flags=METHOD_FLAG_NORMAL;
+MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) {
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ arguments.push_back(p_param4);
+ arguments.push_back(p_param5);
+ flags = METHOD_FLAG_NORMAL;
}
MethodInfo::MethodInfo(Variant::Type ret) {
- id=0;
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name) {
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name) {
- id=0;
- name=p_name;
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ name = p_name;
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1) {
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2) {
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3) {
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4) {
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- arguments.push_back( p_param4 );
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ arguments.push_back(p_param4);
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
-MethodInfo::MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5) {
- id=0;
- name=p_name;
- arguments.push_back( p_param1 );
- arguments.push_back( p_param2 );
- arguments.push_back( p_param3 );
- arguments.push_back( p_param4 );
- arguments.push_back( p_param5 );
- flags=METHOD_FLAG_NORMAL;
- return_val.type=ret;
+MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) {
+ id = 0;
+ name = p_name;
+ arguments.push_back(p_param1);
+ arguments.push_back(p_param2);
+ arguments.push_back(p_param3);
+ arguments.push_back(p_param4);
+ arguments.push_back(p_param5);
+ flags = METHOD_FLAG_NORMAL;
+ return_val.type = ret;
}
Object::Connection::operator Variant() const {
Dictionary d;
- d["source"]=source;
- d["signal"]=signal;
- d["target"]=target;
- d["method"]=method;
- d["flags"]=flags;
- d["binds"]=binds;
+ d["source"] = source;
+ d["signal"] = signal;
+ d["target"] = target;
+ d["method"] = method;
+ d["flags"] = flags;
+ d["binds"] = binds;
return d;
}
-bool Object::Connection::operator<(const Connection& p_conn) const {
+bool Object::Connection::operator<(const Connection &p_conn) const {
- if (source==p_conn.source) {
+ if (source == p_conn.source) {
if (signal == p_conn.signal) {
-
if (target == p_conn.target) {
return method < p_conn.method;
@@ -316,52 +309,45 @@ bool Object::Connection::operator<(const Connection& p_conn) const {
} else
return signal < p_conn.signal;
} else {
- return source<p_conn.source;
+ return source < p_conn.source;
}
}
-Object::Connection::Connection(const Variant& p_variant) {
+Object::Connection::Connection(const Variant &p_variant) {
- Dictionary d=p_variant;
+ Dictionary d = p_variant;
if (d.has("source"))
- source=d["source"];
+ source = d["source"];
if (d.has("signal"))
- signal=d["signal"];
+ signal = d["signal"];
if (d.has("target"))
- target=d["target"];
+ target = d["target"];
if (d.has("method"))
- method=d["method"];
+ method = d["method"];
if (d.has("flags"))
- flags=d["flags"];
+ flags = d["flags"];
if (d.has("binds"))
- binds=d["binds"];
+ binds = d["binds"];
}
-
bool Object::_predelete() {
- _predelete_ok=1;
- notification(NOTIFICATION_PREDELETE,true);
+ _predelete_ok = 1;
+ notification(NOTIFICATION_PREDELETE, true);
if (_predelete_ok) {
- _class_ptr=NULL; //must restore so destructors can access class ptr correctly
+ _class_ptr = NULL; //must restore so destructors can access class ptr correctly
}
return _predelete_ok;
-
}
void Object::_postinitialize() {
- _class_ptr=_get_class_namev();
+ _class_ptr = _get_class_namev();
_initialize_classv();
notification(NOTIFICATION_POSTINITIALIZE);
-
}
void Object::get_valid_parents_static(List<String> *p_parents) {
-
-
}
void Object::_get_valid_parents_static(List<String> *p_parents) {
-
-
}
#if 0
//old style set, deprecated
@@ -393,26 +379,25 @@ void Object::set(const String& p_name, const Variant& p_value) {
}
#endif
-void Object::set(const StringName& p_name, const Variant& p_value, bool *r_valid) {
+void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) {
#ifdef TOOLS_ENABLED
- _edited=true;
+ _edited = true;
#endif
if (script_instance) {
- if (script_instance->set(p_name,p_value)) {
+ if (script_instance->set(p_name, p_value)) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return;
}
-
}
//try built-in setgetter
{
- if (ClassDB::set_property(this,p_name,p_value,r_valid)) {
+ if (ClassDB::set_property(this, p_name, p_value, r_valid)) {
/*
if (r_valid)
*r_valid=true;
@@ -421,85 +406,76 @@ void Object::set(const StringName& p_name, const Variant& p_value, bool *r_valid
}
}
-
- if (p_name==CoreStringNames::get_singleton()->_script) {
+ if (p_name == CoreStringNames::get_singleton()->_script) {
set_script(p_value);
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return;
- } else if (p_name==CoreStringNames::get_singleton()->_meta) {
+ } else if (p_name == CoreStringNames::get_singleton()->_meta) {
//set_meta(p_name,p_value);
- metadata=p_value;
+ metadata = p_value;
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return;
} else {
//something inside the object... :|
- bool success = _setv(p_name,p_value);
+ bool success = _setv(p_name, p_value);
if (success) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return;
}
- setvar(p_name,p_value,r_valid);
+ setvar(p_name, p_value, r_valid);
}
-
}
-Variant Object::get(const StringName& p_name, bool *r_valid) const{
-
+Variant Object::get(const StringName &p_name, bool *r_valid) const {
Variant ret;
if (script_instance) {
- if (script_instance->get(p_name,ret)) {
+ if (script_instance->get(p_name, ret)) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return ret;
}
-
}
-
//try built-in setgetter
{
- if (ClassDB::get_property(const_cast<Object*>(this),p_name,ret)) {
+ if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return ret;
}
}
-
- if (p_name==CoreStringNames::get_singleton()->_script) {
+ if (p_name == CoreStringNames::get_singleton()->_script) {
ret = get_script();
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return ret;
- } else if (p_name==CoreStringNames::get_singleton()->_meta) {
+ } else if (p_name == CoreStringNames::get_singleton()->_meta) {
ret = metadata;
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return ret;
} else {
//something inside the object... :|
- bool success = _getv(p_name,ret);
+ bool success = _getv(p_name, ret);
if (success) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return ret;
}
//if nothing else, use getvar
- return getvar(p_name,r_valid);
+ return getvar(p_name, r_valid);
}
-
-
}
-
#if 0
//old style get, deprecated
Variant Object::get(const String& p_name) const {
@@ -528,86 +504,78 @@ Variant Object::get(const String& p_name) const {
}
#endif
-void Object::get_property_list(List<PropertyInfo> *p_list,bool p_reversed) const {
+void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const {
if (script_instance && p_reversed) {
- p_list->push_back( PropertyInfo(Variant::NIL,"Script Variables",PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY));
+ p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY));
script_instance->get_property_list(p_list);
}
- _get_property_listv(p_list,p_reversed);
-
+ _get_property_listv(p_list, p_reversed);
if (!is_class("Script")) // can still be set, but this is for userfriendlyness
- p_list->push_back( PropertyInfo( Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NONZERO));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NONZERO));
if (!metadata.empty())
- p_list->push_back( PropertyInfo( Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_STORE_IF_NONZERO));
+ p_list->push_back(PropertyInfo(Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_STORE_IF_NONZERO));
if (script_instance && !p_reversed) {
- p_list->push_back( PropertyInfo(Variant::NIL,"Script Variables",PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY));
+ p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY));
script_instance->get_property_list(p_list);
}
-
}
-void Object::_validate_property(PropertyInfo& property) const {
-
+void Object::_validate_property(PropertyInfo &property) const {
}
void Object::get_method_list(List<MethodInfo> *p_list) const {
- ClassDB::get_method_list(get_class_name(),p_list);
+ ClassDB::get_method_list(get_class_name(), p_list);
if (script_instance) {
script_instance->get_method_list(p_list);
}
}
+Variant Object::_call_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-
-Variant Object::_call_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- if (p_argcount<1) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=0;
+ if (p_argcount < 1) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
return Variant();
}
StringName method = *p_args[0];
- return call(method,&p_args[1],p_argcount-1,r_error);
-
-
+ return call(method, &p_args[1], p_argcount - 1, r_error);
}
-Variant Object::_call_deferred_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
+Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- if (p_argcount<1) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=0;
+ if (p_argcount < 1) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
return Variant();
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
StringName method = *p_args[0];
- MessageQueue::get_singleton()->push_call(get_instance_ID(),method,&p_args[1],p_argcount-1);
+ MessageQueue::get_singleton()->push_call(get_instance_ID(), method, &p_args[1], p_argcount - 1);
return Variant();
-
}
#if 0
@@ -627,10 +595,9 @@ void Object::_call_deferred_bind(const StringName& p_name, const Variant& p_arg1
};
#endif
#ifdef DEBUG_ENABLED
-static bool _test_call_error(const StringName& p_func,const Variant::CallError& error) {
-
+static bool _test_call_error(const StringName &p_func, const Variant::CallError &error) {
- switch(error.error) {
+ switch (error.error) {
case Variant::CallError::CALL_OK:
return true;
@@ -638,37 +605,36 @@ static bool _test_call_error(const StringName& p_func,const Variant::CallError&
return false;
case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: {
- ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Invalid type for argument "+itos(error.argument)+", expected "+Variant::get_type_name(error.expected));
+ ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Invalid type for argument " + itos(error.argument) + ", expected " + Variant::get_type_name(error.expected));
ERR_FAIL_V(true);
} break;
case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
- ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Too many arguments, expected "+itos(error.argument));
+ ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too many arguments, expected " + itos(error.argument));
ERR_FAIL_V(true);
} break;
case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
- ERR_EXPLAIN("Error Calling Function: "+String(p_func)+" - Too few arguments, expected "+itos(error.argument));
+ ERR_EXPLAIN("Error Calling Function: " + String(p_func) + " - Too few arguments, expected " + itos(error.argument));
ERR_FAIL_V(true);
} break;
- case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {} //?
-
+ case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
+ } //?
}
return true;
}
#else
-#define _test_call_error(m_str,m_err) ((m_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD)?false:true)
+#define _test_call_error(m_str, m_err) ((m_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) ? false : true)
#endif
-void Object::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
-
+void Object::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
- if (p_method==CoreStringNames::get_singleton()->_free) {
+ if (p_method == CoreStringNames::get_singleton()->_free) {
#ifdef DEBUG_ENABLED
if (cast_to<Reference>()) {
ERR_EXPLAIN("Can't 'free' a reference.");
@@ -676,8 +642,7 @@ void Object::call_multilevel(const StringName& p_method,const Variant** p_args,i
return;
}
-
- if (_lock_index.get()>1) {
+ if (_lock_index.get() > 1) {
ERR_EXPLAIN("Object is locked and can't be freed.");
ERR_FAIL();
return;
@@ -695,59 +660,51 @@ void Object::call_multilevel(const StringName& p_method,const Variant** p_args,i
Variant::CallError error;
if (script_instance) {
- script_instance->call_multilevel(p_method,p_args,p_argcount);
+ script_instance->call_multilevel(p_method, p_args, p_argcount);
//_test_call_error(p_method,error);
-
}
- MethodBind *method=ClassDB::get_method(get_class_name(),p_method);
+ MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
if (method) {
- method->call(this,p_args,p_argcount,error);
- _test_call_error(p_method,error);
+ method->call(this, p_args, p_argcount, error);
+ _test_call_error(p_method, error);
}
-
}
-void Object::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
+void Object::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
-
- MethodBind *method=ClassDB::get_method(get_class_name(),p_method);
+ MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
Variant::CallError error;
OBJ_DEBUG_LOCK
if (method) {
- method->call(this,p_args,p_argcount,error);
- _test_call_error(p_method,error);
+ method->call(this, p_args, p_argcount, error);
+ _test_call_error(p_method, error);
}
//Variant ret;
-
-
if (script_instance) {
- script_instance->call_multilevel_reversed(p_method,p_args,p_argcount);
+ script_instance->call_multilevel_reversed(p_method, p_args, p_argcount);
//_test_call_error(p_method,error);
-
}
-
}
-bool Object::has_method(const StringName& p_method) const {
+bool Object::has_method(const StringName &p_method) const {
- if (p_method==CoreStringNames::get_singleton()->_free) {
+ if (p_method == CoreStringNames::get_singleton()->_free) {
return true;
}
-
if (script_instance && script_instance->has_method(p_method)) {
return true;
}
- MethodBind *method=ClassDB::get_method(get_class_name(),p_method);
+ MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
if (method) {
return true;
@@ -756,42 +713,39 @@ bool Object::has_method(const StringName& p_method) const {
return false;
}
-
-Variant Object::getvar(const Variant& p_key, bool *r_valid) const {
+Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return Variant();
}
-void Object::setvar(const Variant& p_key, const Variant& p_value,bool *r_valid) {
+void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
}
+Variant Object::callv(const StringName &p_method, const Array &p_args) {
-Variant Object::callv(const StringName& p_method,const Array& p_args) {
-
- if (p_args.size()==0) {
+ if (p_args.size() == 0) {
return call(p_method);
}
Vector<Variant> args;
args.resize(p_args.size());
- Vector<const Variant*> argptrs;
+ Vector<const Variant *> argptrs;
argptrs.resize(p_args.size());
- for(int i=0;i<p_args.size();i++) {
- args[i]=p_args[i];
- argptrs[i]=&args[i];
+ for (int i = 0; i < p_args.size(); i++) {
+ args[i] = p_args[i];
+ argptrs[i] = &args[i];
}
Variant::CallError ce;
- return call(p_method,argptrs.ptr(),p_args.size(),ce);
-
+ return call(p_method, argptrs.ptr(), p_args.size(), ce);
}
-Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) {
+Variant Object::call(const StringName &p_name, VARIANT_ARG_DECLARE) {
#if 0
if (p_name==CoreStringNames::get_singleton()->_free) {
#ifdef DEBUG_ENABLED
@@ -843,23 +797,22 @@ Variant Object::call(const StringName& p_name, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
Variant::CallError error;
- Variant ret = call(p_name,argptr,argc,error);
+ Variant ret = call(p_name, argptr, argc, error);
return ret;
#endif
-
}
-void Object::call_multilevel(const StringName& p_name, VARIANT_ARG_DECLARE) {
+void Object::call_multilevel(const StringName &p_name, VARIANT_ARG_DECLARE) {
#if 0
if (p_name==CoreStringNames::get_singleton()->_free) {
#ifdef DEBUG_ENABLED
@@ -904,62 +857,58 @@ void Object::call_multilevel(const StringName& p_name, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
//Variant::CallError error;
- call_multilevel(p_name,argptr,argc);
+ call_multilevel(p_name, argptr, argc);
#endif
-
}
+Variant Object::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
+ r_error.error = Variant::CallError::CALL_OK;
-Variant Object::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
-
- r_error.error=Variant::CallError::CALL_OK;
-
- if (p_method==CoreStringNames::get_singleton()->_free) {
- //free must be here, before anything, always ready
+ if (p_method == CoreStringNames::get_singleton()->_free) {
+//free must be here, before anything, always ready
#ifdef DEBUG_ENABLED
- if (p_argcount!=0) {
- r_error.argument=0;
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ if (p_argcount != 0) {
+ r_error.argument = 0;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
return Variant();
}
if (cast_to<Reference>()) {
- r_error.argument=0;
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.argument = 0;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
ERR_EXPLAIN("Can't 'free' a reference.");
ERR_FAIL_V(Variant());
}
- if (_lock_index.get()>1) {
- r_error.argument=0;
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ if (_lock_index.get() > 1) {
+ r_error.argument = 0;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
ERR_EXPLAIN("Object is locked and can't be freed.");
ERR_FAIL_V(Variant());
-
}
#endif
//must be here, must be before everything,
memdelete(this);
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
return Variant();
}
Variant ret;
OBJ_DEBUG_LOCK
if (script_instance) {
- ret = script_instance->call(p_method,p_args,p_argcount,r_error);
+ ret = script_instance->call(p_method, p_args, p_argcount, r_error);
//force jumptable
- switch(r_error.error) {
+ switch (r_error.error) {
case Variant::CallError::CALL_OK:
return ret;
@@ -969,45 +918,41 @@ Variant Object::call(const StringName& p_method,const Variant** p_args,int p_arg
case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
return ret;
- case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {}
-
+ case Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
+ }
}
}
- MethodBind *method=ClassDB::get_method(get_class_name(),p_method);
+ MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
if (method) {
- ret=method->call(this,p_args,p_argcount,r_error);
+ ret = method->call(this, p_args, p_argcount, r_error);
} else {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
return ret;
}
+void Object::notification(int p_notification, bool p_reversed) {
-void Object::notification(int p_notification,bool p_reversed) {
-
-
- _notificationv(p_notification,p_reversed);
+ _notificationv(p_notification, p_reversed);
if (script_instance) {
script_instance->notification(p_notification);
}
}
-void Object::_changed_callback(Object *p_changed,const char *p_prop) {
-
-
+void Object::_changed_callback(Object *p_changed, const char *p_prop) {
}
-void Object::add_change_receptor( Object *p_receptor ) {
+void Object::add_change_receptor(Object *p_receptor) {
change_receptors.insert(p_receptor);
}
-void Object::remove_change_receptor( Object *p_receptor ) {
+void Object::remove_change_receptor(Object *p_receptor) {
change_receptors.erase(p_receptor);
}
@@ -1019,47 +964,45 @@ void Object::property_list_changed_notify() {
void Object::cancel_delete() {
- _predelete_ok=true;
+ _predelete_ok = true;
}
-void Object::set_script(const RefPtr& p_script) {
+void Object::set_script(const RefPtr &p_script) {
- if (script==p_script)
+ if (script == p_script)
return;
if (script_instance) {
memdelete(script_instance);
- script_instance=NULL;
+ script_instance = NULL;
}
- script=p_script;
+ script = p_script;
Ref<Script> s(script);
- if (!s.is_null() && s->can_instance() ) {
+ if (!s.is_null() && s->can_instance()) {
OBJ_DEBUG_LOCK
script_instance = s->instance_create(this);
-
}
_change_notify("script");
emit_signal(CoreStringNames::get_singleton()->script_changed);
-
}
void Object::set_script_instance(ScriptInstance *p_instance) {
- if (script_instance==p_instance)
+ if (script_instance == p_instance)
return;
if (script_instance)
memdelete(script_instance);
- script_instance=p_instance;
+ script_instance = p_instance;
if (p_instance)
- script=p_instance->get_script().get_ref_ptr();
+ script = p_instance->get_script().get_ref_ptr();
else
- script=RefPtr();
+ script = RefPtr();
}
RefPtr Object::get_script() const {
@@ -1067,28 +1010,27 @@ RefPtr Object::get_script() const {
return script;
}
-bool Object::has_meta(const String& p_name) const {
+bool Object::has_meta(const String &p_name) const {
return metadata.has(p_name);
}
-void Object::set_meta(const String& p_name, const Variant& p_value ) {
+void Object::set_meta(const String &p_name, const Variant &p_value) {
if (p_value.get_type() == Variant::NIL) {
metadata.erase(p_name);
return;
};
- metadata[p_name]=p_value;
+ metadata[p_name] = p_value;
}
-Variant Object::get_meta(const String& p_name) const {
+Variant Object::get_meta(const String &p_name) const {
- ERR_FAIL_COND_V(!metadata.has(p_name),Variant());
+ ERR_FAIL_COND_V(!metadata.has(p_name), Variant());
return metadata[p_name];
}
-
Array Object::_get_property_list_bind() const {
List<PropertyInfo> lpi;
@@ -1096,15 +1038,13 @@ Array Object::_get_property_list_bind() const {
return convert_property_list(&lpi);
}
-
-
Array Object::_get_method_list_bind() const {
List<MethodInfo> ml;
get_method_list(&ml);
Array ret;
- for(List<MethodInfo>::Element *E=ml.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
Dictionary d = E->get();
//va.push_back(d);
@@ -1112,7 +1052,6 @@ Array Object::_get_method_list_bind() const {
}
return ret;
-
}
PoolVector<String> Object::_get_meta_list_bind() const {
@@ -1121,7 +1060,7 @@ PoolVector<String> Object::_get_meta_list_bind() const {
List<Variant> keys;
metadata.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
_metaret.push_back(E->get());
}
@@ -1132,27 +1071,27 @@ void Object::get_meta_list(List<String> *p_list) const {
List<Variant> keys;
metadata.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
}
-void Object::add_user_signal(const MethodInfo& p_signal) {
+void Object::add_user_signal(const MethodInfo &p_signal) {
- ERR_FAIL_COND(p_signal.name=="");
- ERR_FAIL_COND( ClassDB::has_signal(get_class_name(),p_signal.name ) );
+ ERR_FAIL_COND(p_signal.name == "");
+ ERR_FAIL_COND(ClassDB::has_signal(get_class_name(), p_signal.name));
ERR_FAIL_COND(signal_map.has(p_signal.name));
Signal s;
- s.user=p_signal;
- signal_map[p_signal.name]=s;
+ s.user = p_signal;
+ signal_map[p_signal.name] = s;
}
-bool Object::_has_user_signal(const StringName& p_name) const {
+bool Object::_has_user_signal(const StringName &p_name) const {
if (!signal_map.has(p_name))
return false;
- return signal_map[p_name].user.name.length()>0;
+ return signal_map[p_name].user.name.length() > 0;
}
struct _ObjectSignalDisconnectData {
@@ -1160,7 +1099,6 @@ struct _ObjectSignalDisconnectData {
StringName signal;
Object *target;
StringName method;
-
};
#if 0
@@ -1179,39 +1117,35 @@ void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){
#endif
-Variant Object::_emit_signal(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
+Variant Object::_emit_signal(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- ERR_FAIL_COND_V(p_argcount<1,Variant());
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- ERR_FAIL_COND_V(p_args[0]->get_type()!=Variant::STRING,Variant());
+ ERR_FAIL_COND_V(p_argcount < 1, Variant());
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
+ ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING, Variant());
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
StringName signal = *p_args[0];
+ const Variant **args = NULL;
- const Variant**args=NULL;
-
- int argc=p_argcount-1;
+ int argc = p_argcount - 1;
if (argc) {
- args=&p_args[1];
+ args = &p_args[1];
}
- emit_signal(signal,args,argc);
+ emit_signal(signal, args, argc);
return Variant();
-
}
-
-void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_argcount) {
+void Object::emit_signal(const StringName &p_name, const Variant **p_args, int p_argcount) {
if (_block_signals)
return; //no emit, signals blocked
@@ -1219,10 +1153,10 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a
Signal *s = signal_map.getptr(p_name);
if (!s) {
#ifdef DEBUG_ENABLED
- bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_name);
+ bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
//check in script
if (!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name)) {
- ERR_EXPLAIN("Can't emit non-existing signal " + String("\"")+p_name+"\".");
+ ERR_EXPLAIN("Can't emit non-existing signal " + String("\"") + p_name + "\".");
ERR_FAIL();
}
#endif
@@ -1230,23 +1164,20 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a
return;
}
-
List<_ObjectSignalDisconnectData> disconnect_data;
-
//copy on write will ensure that disconnecting the signal or even deleting the object will not affect the signal calling.
//this happens automatically and will not change the performance of calling.
//awesome, isn't it?
- VMap<Signal::Target,Signal::Slot> slot_map = s->slot_map;
+ VMap<Signal::Target, Signal::Slot> slot_map = s->slot_map;
int ssize = slot_map.size();
OBJ_DEBUG_LOCK
- Vector<const Variant*> bind_mem;
-
+ Vector<const Variant *> bind_mem;
- for(int i=0;i<ssize;i++) {
+ for (int i = 0; i < ssize; i++) {
const Connection &c = slot_map.getv(i).conn;
@@ -1255,107 +1186,97 @@ void Object::emit_signal(const StringName& p_name,const Variant** p_args,int p_a
target = ObjectDB::get_instance(slot_map.getk(i)._id);
ERR_CONTINUE(!target);
#else
- target=c.target;
+ target = c.target;
#endif
-
- const Variant **args=p_args;
- int argc=p_argcount;
+ const Variant **args = p_args;
+ int argc = p_argcount;
if (c.binds.size()) {
//handle binds
- bind_mem.resize(p_argcount+c.binds.size());
+ bind_mem.resize(p_argcount + c.binds.size());
- for(int j=0;j<p_argcount;j++) {
- bind_mem[j]=p_args[j];
+ for (int j = 0; j < p_argcount; j++) {
+ bind_mem[j] = p_args[j];
}
- for(int j=0;j<c.binds.size();j++) {
- bind_mem[p_argcount+j]=&c.binds[j];
+ for (int j = 0; j < c.binds.size(); j++) {
+ bind_mem[p_argcount + j] = &c.binds[j];
}
- args=bind_mem.ptr();
- argc=bind_mem.size();
+ args = bind_mem.ptr();
+ argc = bind_mem.size();
}
- if (c.flags&CONNECT_DEFERRED) {
- MessageQueue::get_singleton()->push_call(target->get_instance_ID(),c.method,args,argc,true);
+ if (c.flags & CONNECT_DEFERRED) {
+ MessageQueue::get_singleton()->push_call(target->get_instance_ID(), c.method, args, argc, true);
} else {
Variant::CallError ce;
- target->call( c.method, args, argc,ce );
- if (ce.error!=Variant::CallError::CALL_OK) {
+ target->call(c.method, args, argc, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
- if (ce.error==Variant::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists( target->get_class_name() ) ) {
+ if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) {
//most likely object is not initialized yet, do not throw error.
} else {
- ERR_PRINTS("Error calling method from signal '"+String(p_name)+"': "+Variant::get_call_error_text(target,c.method,args,argc,ce));
+ ERR_PRINTS("Error calling method from signal '" + String(p_name) + "': " + Variant::get_call_error_text(target, c.method, args, argc, ce));
}
}
}
- if (c.flags&CONNECT_ONESHOT) {
+ if (c.flags & CONNECT_ONESHOT) {
_ObjectSignalDisconnectData dd;
- dd.signal=p_name;
- dd.target=target;
- dd.method=c.method;
+ dd.signal = p_name;
+ dd.target = target;
+ dd.method = c.method;
disconnect_data.push_back(dd);
}
-
}
-
while (!disconnect_data.empty()) {
const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get();
- disconnect(dd.signal,dd.target,dd.method);
+ disconnect(dd.signal, dd.target, dd.method);
disconnect_data.pop_front();
}
-
}
-void Object::emit_signal(const StringName& p_name,VARIANT_ARG_DECLARE) {
+void Object::emit_signal(const StringName &p_name, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
+ int argc = 0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
-
- emit_signal(p_name,argptr,argc);
-
+ emit_signal(p_name, argptr, argc);
}
-
-void Object::_add_user_signal(const String& p_name, const Array& p_args) {
+void Object::_add_user_signal(const String &p_name, const Array &p_args) {
// this version of add_user_signal is meant to be used from scripts or external apis
// without access to ADD_SIGNAL in bind_methods
// added events are per instance, as opposed to the other ones, which are global
-
-
MethodInfo mi;
- mi.name=p_name;
+ mi.name = p_name;
- for(int i=0;i<p_args.size();i++) {
+ for (int i = 0; i < p_args.size(); i++) {
- Dictionary d=p_args[i];
+ Dictionary d = p_args[i];
PropertyInfo param;
if (d.has("name"))
- param.name=d["name"];
+ param.name = d["name"];
if (d.has("type"))
- param.type=(Variant::Type)(int)d["type"];
+ param.type = (Variant::Type)(int)d["type"];
mi.arguments.push_back(param);
}
add_user_signal(mi);
-
}
#if 0
void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){
@@ -1372,105 +1293,99 @@ void Object::_emit_signal(const StringName& p_name,const Array& p_pargs){
}
#endif
-Array Object::_get_signal_list() const{
+Array Object::_get_signal_list() const {
List<MethodInfo> signal_list;
get_signal_list(&signal_list);
Array ret;
- for (List<MethodInfo>::Element *E=signal_list.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = signal_list.front(); E; E = E->next()) {
ret.push_back(Dictionary(E->get()));
}
return ret;
}
-Array Object::_get_signal_connection_list(const String& p_signal) const{
+Array Object::_get_signal_connection_list(const String &p_signal) const {
List<Connection> conns;
get_all_signal_connections(&conns);
Array ret;
- for (List<Connection>::Element *E=conns.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = conns.front(); E; E = E->next()) {
- Connection &c=E->get();
- if (c.signal == p_signal){
+ Connection &c = E->get();
+ if (c.signal == p_signal) {
Dictionary rc;
- rc["signal"]=c.signal;
- rc["method"]=c.method;
- rc["source"]=c.source;
- rc["target"]=c.target;
- rc["binds"]=c.binds;
- rc["flags"]=c.flags;
+ rc["signal"] = c.signal;
+ rc["method"] = c.method;
+ rc["source"] = c.source;
+ rc["target"] = c.target;
+ rc["binds"] = c.binds;
+ rc["flags"] = c.flags;
ret.push_back(rc);
}
}
return ret;
-
}
-
-void Object::get_signal_list(List<MethodInfo> *p_signals ) const {
+void Object::get_signal_list(List<MethodInfo> *p_signals) const {
if (!script.is_null()) {
Ref<Script>(script)->get_script_signal_list(p_signals);
}
- ClassDB::get_signal_list(get_class_name(),p_signals);
+ ClassDB::get_signal_list(get_class_name(), p_signals);
//find maybe usersignals?
- const StringName *S=NULL;
+ const StringName *S = NULL;
- while((S=signal_map.next(S))) {
+ while ((S = signal_map.next(S))) {
- if (signal_map[*S].user.name!="") {
+ if (signal_map[*S].user.name != "") {
//user signal
p_signals->push_back(signal_map[*S].user);
}
}
-
}
-
void Object::get_all_signal_connections(List<Connection> *p_connections) const {
- const StringName *S=NULL;
+ const StringName *S = NULL;
- while((S=signal_map.next(S))) {
+ while ((S = signal_map.next(S))) {
- const Signal *s=&signal_map[*S];
+ const Signal *s = &signal_map[*S];
- for(int i=0;i<s->slot_map.size();i++) {
+ for (int i = 0; i < s->slot_map.size(); i++) {
p_connections->push_back(s->slot_map.getv(i).conn);
}
}
-
}
-void Object::get_signal_connection_list(const StringName& p_signal,List<Connection> *p_connections) const {
+void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
- const Signal *s=signal_map.getptr(p_signal);
+ const Signal *s = signal_map.getptr(p_signal);
if (!s)
return; //nothing
- for(int i=0;i<s->slot_map.size();i++)
+ for (int i = 0; i < s->slot_map.size(); i++)
p_connections->push_back(s->slot_map.getv(i).conn);
-
}
bool Object::has_persistent_signal_connections() const {
- const StringName *S=NULL;
+ const StringName *S = NULL;
- while((S=signal_map.next(S))) {
+ while ((S = signal_map.next(S))) {
- const Signal *s=&signal_map[*S];
+ const Signal *s = &signal_map[*S];
- for(int i=0;i<s->slot_map.size();i++) {
+ for (int i = 0; i < s->slot_map.size(); i++) {
- if (s->slot_map.getv(i).conn.flags&CONNECT_PERSIST)
+ if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST)
return true;
}
}
@@ -1480,128 +1395,125 @@ bool Object::has_persistent_signal_connections() const {
void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
- for (const List<Connection>::Element *E=connections.front();E;E=E->next()) {
+ for (const List<Connection>::Element *E = connections.front(); E; E = E->next()) {
p_connections->push_back(E->get());
}
}
+Error Object::connect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds, uint32_t p_flags) {
-Error Object::connect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method,const Vector<Variant>& p_binds,uint32_t p_flags) {
-
- ERR_FAIL_NULL_V(p_to_object,ERR_INVALID_PARAMETER);
+ ERR_FAIL_NULL_V(p_to_object, ERR_INVALID_PARAMETER);
Signal *s = signal_map.getptr(p_signal);
if (!s) {
- bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_signal);
+ bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
//check in script
if (!signal_is_valid && !script.is_null() && Ref<Script>(script)->has_script_signal(p_signal))
- signal_is_valid=true;
+ signal_is_valid = true;
if (!signal_is_valid) {
- ERR_EXPLAIN("In Object of type '"+String(get_class())+"': Attempt to connect nonexistent signal '"+p_signal+"' to method '"+p_to_object->get_class()+"."+p_to_method+"'");
- ERR_FAIL_COND_V(!signal_is_valid,ERR_INVALID_PARAMETER);
+ ERR_EXPLAIN("In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to method '" + p_to_object->get_class() + "." + p_to_method + "'");
+ ERR_FAIL_COND_V(!signal_is_valid, ERR_INVALID_PARAMETER);
}
- signal_map[p_signal]=Signal();
- s=&signal_map[p_signal];
+ signal_map[p_signal] = Signal();
+ s = &signal_map[p_signal];
}
- Signal::Target target(p_to_object->get_instance_ID(),p_to_method);
+ Signal::Target target(p_to_object->get_instance_ID(), p_to_method);
if (s->slot_map.has(target)) {
- ERR_EXPLAIN("Signal '"+p_signal+"'' already connected to given method '"+p_to_method+"' in that object.");
- ERR_FAIL_COND_V(s->slot_map.has(target),ERR_INVALID_PARAMETER);
+ ERR_EXPLAIN("Signal '" + p_signal + "'' already connected to given method '" + p_to_method + "' in that object.");
+ ERR_FAIL_COND_V(s->slot_map.has(target), ERR_INVALID_PARAMETER);
}
Signal::Slot slot;
Connection conn;
- conn.source=this;
- conn.target=p_to_object;
- conn.method=p_to_method;
- conn.signal=p_signal;
- conn.flags=p_flags;
- conn.binds=p_binds;
- slot.conn=conn;
- slot.cE=p_to_object->connections.push_back(conn);
- s->slot_map[target]=slot;
+ conn.source = this;
+ conn.target = p_to_object;
+ conn.method = p_to_method;
+ conn.signal = p_signal;
+ conn.flags = p_flags;
+ conn.binds = p_binds;
+ slot.conn = conn;
+ slot.cE = p_to_object->connections.push_back(conn);
+ s->slot_map[target] = slot;
return OK;
}
-bool Object::is_connected(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) const {
+bool Object::is_connected(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) const {
- ERR_FAIL_NULL_V(p_to_object,false);
+ ERR_FAIL_NULL_V(p_to_object, false);
const Signal *s = signal_map.getptr(p_signal);
if (!s) {
- bool signal_is_valid = ClassDB::has_signal(get_class_name(),p_signal);
+ bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
if (signal_is_valid)
return false;
if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal))
return false;
- ERR_EXPLAIN("Nonexistent signal: "+p_signal);
- ERR_FAIL_COND_V(!s,false);
+ ERR_EXPLAIN("Nonexistent signal: " + p_signal);
+ ERR_FAIL_COND_V(!s, false);
}
- Signal::Target target(p_to_object->get_instance_ID(),p_to_method);
+ Signal::Target target(p_to_object->get_instance_ID(), p_to_method);
return s->slot_map.has(target);
//const Map<Signal::Target,Signal::Slot>::Element *E = s->slot_map.find(target);
//return (E!=NULL);
-
}
-void Object::disconnect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) {
+void Object::disconnect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) {
ERR_FAIL_NULL(p_to_object);
Signal *s = signal_map.getptr(p_signal);
if (!s) {
- ERR_EXPLAIN("Nonexistent signal: "+p_signal);
+ ERR_EXPLAIN("Nonexistent signal: " + p_signal);
ERR_FAIL_COND(!s);
}
- if (s->lock>0) {
- ERR_EXPLAIN("Attempt to disconnect signal '"+p_signal+"' while emitting (locks: "+itos(s->lock)+")");
- ERR_FAIL_COND(s->lock>0);
+ if (s->lock > 0) {
+ ERR_EXPLAIN("Attempt to disconnect signal '" + p_signal + "' while emitting (locks: " + itos(s->lock) + ")");
+ ERR_FAIL_COND(s->lock > 0);
}
- Signal::Target target(p_to_object->get_instance_ID(),p_to_method);
+ Signal::Target target(p_to_object->get_instance_ID(), p_to_method);
if (!s->slot_map.has(target)) {
- ERR_EXPLAIN("Disconnecting nonexistent signal '"+p_signal+"', slot: "+itos(target._id)+":"+target.method);
+ ERR_EXPLAIN("Disconnecting nonexistent signal '" + p_signal + "', slot: " + itos(target._id) + ":" + target.method);
ERR_FAIL();
}
p_to_object->connections.erase(s->slot_map[target].cE);
s->slot_map.erase(target);
- if (s->slot_map.empty() && ClassDB::has_signal(get_class_name(),p_signal )) {
+ if (s->slot_map.empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
//not user signal, delete
signal_map.erase(p_signal);
}
}
+void Object::_set_bind(const String &p_set, const Variant &p_value) {
-void Object::_set_bind(const String& p_set,const Variant& p_value) {
-
- set(p_set,p_value);
+ set(p_set, p_value);
}
-Variant Object::_get_bind(const String& p_name) const {
+Variant Object::_get_bind(const String &p_name) const {
return get(p_name);
}
void Object::initialize_class() {
- static bool initialized=false;
+ static bool initialized = false;
if (initialized)
return;
ClassDB::_add_class<Object>();
_bind_methods();
- initialized=true;
+ initialized = true;
}
-StringName Object::XL_MESSAGE(const StringName& p_message) const {
+StringName Object::XL_MESSAGE(const StringName &p_message) const {
if (!_can_translate || !TranslationServer::get_singleton())
return p_message;
@@ -1609,16 +1521,14 @@ StringName Object::XL_MESSAGE(const StringName& p_message) const {
return TranslationServer::get_singleton()->translate(p_message);
}
-StringName Object::tr(const StringName& p_message) const {
+StringName Object::tr(const StringName &p_message) const {
return XL_MESSAGE(p_message);
-
}
-
void Object::_clear_internal_resource_paths(const Variant &p_var) {
- switch(p_var.get_type()) {
+ switch (p_var.get_type()) {
case Variant::OBJECT: {
@@ -1626,10 +1536,10 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) {
if (!r.is_valid())
return;
- if (!r->get_path().begins_with("res://") || r->get_path().find("::")==-1)
+ if (!r->get_path().begins_with("res://") || r->get_path().find("::") == -1)
return; //not an internal resource
- Object *object=p_var;
+ Object *object = p_var;
if (!object)
return;
@@ -1638,19 +1548,19 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) {
} break;
case Variant::ARRAY: {
- Array a=p_var;
- for(int i=0;i<a.size();i++) {
+ Array a = p_var;
+ for (int i = 0; i < a.size(); i++) {
_clear_internal_resource_paths(a[i]);
}
} break;
case Variant::DICTIONARY: {
- Dictionary d=p_var;
+ Dictionary d = p_var;
List<Variant> keys;
d.get_key_list(&keys);
- for (List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
_clear_internal_resource_paths(E->get());
_clear_internal_resource_paths(d[E->get()]);
@@ -1658,7 +1568,6 @@ void Object::_clear_internal_resource_paths(const Variant &p_var) {
} break;
default: {}
}
-
}
void Object::clear_internal_resource_paths() {
@@ -1667,7 +1576,7 @@ void Object::clear_internal_resource_paths() {
get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
_clear_internal_resource_paths(get(E->get().name));
}
@@ -1675,122 +1584,116 @@ void Object::clear_internal_resource_paths() {
void Object::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_class"),&Object::get_class);
- ClassDB::bind_method(D_METHOD("is_class","type"),&Object::is_class);
- ClassDB::bind_method(D_METHOD("set","property","value"),&Object::_set_bind);
- ClassDB::bind_method(D_METHOD("get","property"),&Object::_get_bind);
- ClassDB::bind_method(D_METHOD("get_property_list"),&Object::_get_property_list_bind);
- ClassDB::bind_method(D_METHOD("get_method_list"),&Object::_get_method_list_bind);
- ClassDB::bind_method(D_METHOD("notification","what","reversed"),&Object::notification,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_instance_ID"),&Object::get_instance_ID);
+ ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
+ ClassDB::bind_method(D_METHOD("is_class", "type"), &Object::is_class);
+ ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
+ ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
+ ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
+ ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
+ ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_instance_ID"), &Object::get_instance_ID);
- ClassDB::bind_method(D_METHOD("set_script","script:Script"),&Object::set_script);
- ClassDB::bind_method(D_METHOD("get_script:Script"),&Object::get_script);
+ ClassDB::bind_method(D_METHOD("set_script", "script:Script"), &Object::set_script);
+ ClassDB::bind_method(D_METHOD("get_script:Script"), &Object::get_script);
- ClassDB::bind_method(D_METHOD("set_meta","name","value"),&Object::set_meta);
- ClassDB::bind_method(D_METHOD("get_meta","name","value"),&Object::get_meta);
- ClassDB::bind_method(D_METHOD("has_meta","name"),&Object::has_meta);
- ClassDB::bind_method(D_METHOD("get_meta_list"),&Object::_get_meta_list_bind);
+ ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
+ ClassDB::bind_method(D_METHOD("get_meta", "name", "value"), &Object::get_meta);
+ ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
+ ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
//todo reimplement this per language so all 5 arguments can be called
//ClassDB::bind_method(D_METHOD("call","method","arg1","arg2","arg3","arg4"),&Object::_call_bind,DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()));
//ClassDB::bind_method(D_METHOD("call_deferred","method","arg1","arg2","arg3","arg4"),&Object::_call_deferred_bind,DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()),DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("add_user_signal","signal","arguments"),&Object::_add_user_signal,DEFVAL(Array()));
- ClassDB::bind_method(D_METHOD("has_user_signal","signal"),&Object::_has_user_signal);
+ ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
+ ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
//ClassDB::bind_method(D_METHOD("emit_signal","signal","arguments"),&Object::_emit_signal,DEFVAL(Array()));
-
{
MethodInfo mi;
- mi.name="emit_signal";
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "signal"));
+ mi.name = "emit_signal";
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal"));
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"emit_signal",&Object::_emit_signal,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi);
}
{
MethodInfo mi;
- mi.name="call";
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
+ mi.name = "call";
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
-
-
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call:Variant",&Object::_call_bind,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call:Variant", &Object::_call_bind, mi);
}
{
MethodInfo mi;
- mi.name="call_deferred";
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
+ mi.name = "call_deferred";
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_deferred",&Object::_call_deferred_bind,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi);
}
- ClassDB::bind_method(D_METHOD("callv:Variant","method","arg_array"),&Object::callv);
+ ClassDB::bind_method(D_METHOD("callv:Variant", "method", "arg_array"), &Object::callv);
- ClassDB::bind_method(D_METHOD("has_method","method"),&Object::has_method);
+ ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
- ClassDB::bind_method(D_METHOD("get_signal_list"),&Object::_get_signal_list);
- ClassDB::bind_method(D_METHOD("get_signal_connection_list","signal"),&Object::_get_signal_connection_list);
+ ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
+ ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
- ClassDB::bind_method(D_METHOD("connect","signal","target:Object","method","binds","flags"),&Object::connect,DEFVAL(Array()),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("disconnect","signal","target:Object","method"),&Object::disconnect);
- ClassDB::bind_method(D_METHOD("is_connected","signal","target:Object","method"),&Object::is_connected);
+ ClassDB::bind_method(D_METHOD("connect", "signal", "target:Object", "method", "binds", "flags"), &Object::connect, DEFVAL(Array()), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("disconnect", "signal", "target:Object", "method"), &Object::disconnect);
+ ClassDB::bind_method(D_METHOD("is_connected", "signal", "target:Object", "method"), &Object::is_connected);
- ClassDB::bind_method(D_METHOD("set_block_signals","enable"),&Object::set_block_signals);
- ClassDB::bind_method(D_METHOD("is_blocking_signals"),&Object::is_blocking_signals);
- ClassDB::bind_method(D_METHOD("set_message_translation","enable"),&Object::set_message_translation);
- ClassDB::bind_method(D_METHOD("can_translate_messages"),&Object::can_translate_messages);
- ClassDB::bind_method(D_METHOD("property_list_changed_notify"),&Object::property_list_changed_notify);
+ ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
+ ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
+ ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
+ ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
+ ClassDB::bind_method(D_METHOD("property_list_changed_notify"), &Object::property_list_changed_notify);
- ClassDB::bind_method(D_METHOD("XL_MESSAGE","message"),&Object::XL_MESSAGE);
- ClassDB::bind_method(D_METHOD("tr","message"),&Object::tr);
+ ClassDB::bind_method(D_METHOD("XL_MESSAGE", "message"), &Object::XL_MESSAGE);
+ ClassDB::bind_method(D_METHOD("tr", "message"), &Object::tr);
- ClassDB::bind_method(D_METHOD("is_queued_for_deletion"),&Object::is_queued_for_deletion);
+ ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
- ClassDB::add_virtual_method("Object",MethodInfo("free"),false);
+ ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
- ADD_SIGNAL( MethodInfo("script_changed"));
+ ADD_SIGNAL(MethodInfo("script_changed"));
- BIND_VMETHOD( MethodInfo("_notification",PropertyInfo(Variant::INT,"what")) );
- BIND_VMETHOD( MethodInfo("_set",PropertyInfo(Variant::STRING,"property"),PropertyInfo(Variant::NIL,"value")) );
+ BIND_VMETHOD(MethodInfo("_notification", PropertyInfo(Variant::INT, "what")));
+ BIND_VMETHOD(MethodInfo("_set", PropertyInfo(Variant::STRING, "property"), PropertyInfo(Variant::NIL, "value")));
#ifdef TOOLS_ENABLED
- MethodInfo miget("_get",PropertyInfo(Variant::STRING,"property") );
- miget.return_val.name="var";
- BIND_VMETHOD( miget );
+ MethodInfo miget("_get", PropertyInfo(Variant::STRING, "property"));
+ miget.return_val.name = "var";
+ BIND_VMETHOD(miget);
MethodInfo plget("_get_property_list");
- plget.return_val.type=Variant::ARRAY;
- BIND_VMETHOD( plget );
+ plget.return_val.type = Variant::ARRAY;
+ BIND_VMETHOD(plget);
#endif
- BIND_VMETHOD( MethodInfo("_init") );
-
-
-
- BIND_CONSTANT( NOTIFICATION_POSTINITIALIZE );
- BIND_CONSTANT( NOTIFICATION_PREDELETE );
+ BIND_VMETHOD(MethodInfo("_init"));
- BIND_CONSTANT( CONNECT_DEFERRED );
- BIND_CONSTANT( CONNECT_PERSIST );
- BIND_CONSTANT( CONNECT_ONESHOT );
+ BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
+ BIND_CONSTANT(NOTIFICATION_PREDELETE);
+ BIND_CONSTANT(CONNECT_DEFERRED);
+ BIND_CONSTANT(CONNECT_PERSIST);
+ BIND_CONSTANT(CONNECT_ONESHOT);
}
-void Object::call_deferred(const StringName& p_method,VARIANT_ARG_DECLARE) {
+void Object::call_deferred(const StringName &p_method, VARIANT_ARG_DECLARE) {
- MessageQueue::get_singleton()->push_call(this,p_method,VARIANT_ARG_PASS);
+ MessageQueue::get_singleton()->push_call(this, p_method, VARIANT_ARG_PASS);
}
void Object::set_block_signals(bool p_block) {
- _block_signals=p_block;
+ _block_signals = p_block;
}
-bool Object::is_blocking_signals() const{
+bool Object::is_blocking_signals() const {
return _block_signals;
}
@@ -1800,39 +1703,37 @@ void Object::get_translatable_strings(List<String> *p_strings) const {
List<PropertyInfo> plist;
get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_INTERNATIONALIZED))
+ if (!(E->get().usage & PROPERTY_USAGE_INTERNATIONALIZED))
continue;
- String text = get( E->get().name );
+ String text = get(E->get().name);
- if (text=="")
+ if (text == "")
continue;
p_strings->push_back(text);
}
-
}
-Variant::Type Object::get_static_property_type(const StringName& p_property, bool *r_valid) const {
+Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
bool valid;
- Variant::Type t = ClassDB::get_property_type(get_class_name(),p_property,&valid);
+ Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
if (valid) {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return t;
}
if (get_script_instance()) {
- return get_script_instance()->get_property_type(p_property,r_valid);
+ return get_script_instance()->get_property_type(p_property, r_valid);
}
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return Variant::NIL;
-
}
bool Object::is_queued_for_deletion() const {
@@ -1842,14 +1743,13 @@ bool Object::is_queued_for_deletion() const {
#ifdef TOOLS_ENABLED
void Object::set_edited(bool p_edited) {
- _edited=p_edited;
+ _edited = p_edited;
_edited_version++;
}
bool Object::is_edited() const {
return _edited;
-
}
uint32_t Object::get_edited_version() const {
@@ -1860,76 +1760,66 @@ uint32_t Object::get_edited_version() const {
Object::Object() {
- _class_ptr=NULL;
- _block_signals=false;
- _predelete_ok=0;
- _instance_ID=0;
+ _class_ptr = NULL;
+ _block_signals = false;
+ _predelete_ok = 0;
+ _instance_ID = 0;
_instance_ID = ObjectDB::add_instance(this);
- _can_translate=true;
- _is_queued_for_deletion=false;
- script_instance=NULL;
+ _can_translate = true;
+ _is_queued_for_deletion = false;
+ script_instance = NULL;
#ifdef TOOLS_ENABLED
- _edited=false;
- _edited_version=0;
+ _edited = false;
+ _edited_version = 0;
#endif
#ifdef DEBUG_ENABLED
_lock_index.init(1);
#endif
-
-
-
}
-
Object::~Object() {
-
-
if (script_instance)
memdelete(script_instance);
- script_instance=NULL;
-
+ script_instance = NULL;
List<Connection> sconnections;
- const StringName *S=NULL;
+ const StringName *S = NULL;
- while((S=signal_map.next(S))) {
+ while ((S = signal_map.next(S))) {
- Signal *s=&signal_map[*S];
+ Signal *s = &signal_map[*S];
ERR_EXPLAIN("Attempt to delete an object in the middle of a signal emission from it");
- ERR_CONTINUE(s->lock>0);
+ ERR_CONTINUE(s->lock > 0);
- for(int i=0;i<s->slot_map.size();i++) {
+ for (int i = 0; i < s->slot_map.size(); i++) {
sconnections.push_back(s->slot_map.getv(i).conn);
}
}
- for(List<Connection>::Element *E=sconnections.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = sconnections.front(); E; E = E->next()) {
Connection &c = E->get();
- ERR_CONTINUE(c.source!=this); //bug?
+ ERR_CONTINUE(c.source != this); //bug?
- this->disconnect(c.signal,c.target,c.method);
+ this->disconnect(c.signal, c.target, c.method);
}
- while(connections.size()) {
+ while (connections.size()) {
Connection c = connections.front()->get();
- c.source->disconnect(c.signal,c.target,c.method);
+ c.source->disconnect(c.signal, c.target, c.method);
}
ObjectDB::remove_instance(this);
- _instance_ID=0;
- _predelete_ok=2;
-
+ _instance_ID = 0;
+ _predelete_ok = 2;
}
-
-
bool predelete_handler(Object *p_object) {
return p_object->_predelete();
@@ -1940,18 +1830,17 @@ void postinitialize_handler(Object *p_object) {
p_object->_postinitialize();
}
-HashMap<uint32_t,Object*> ObjectDB::instances;
-uint32_t ObjectDB::instance_counter=1;
-HashMap<Object*,ObjectID,ObjectDB::ObjectPtrHash> ObjectDB::instance_checks;
+HashMap<uint32_t, Object *> ObjectDB::instances;
+uint32_t ObjectDB::instance_counter = 1;
+HashMap<Object *, ObjectID, ObjectDB::ObjectPtrHash> ObjectDB::instance_checks;
uint32_t ObjectDB::add_instance(Object *p_object) {
-
- ERR_FAIL_COND_V( p_object->get_instance_ID()!=0, 0 );
+ ERR_FAIL_COND_V(p_object->get_instance_ID() != 0, 0);
rw_lock->write_lock();
- instances[++instance_counter]=p_object;
+ instances[++instance_counter] = p_object;
#ifdef DEBUG_ENABLED
- instance_checks[p_object]=instance_counter;
+ instance_checks[p_object] = instance_counter;
#endif
rw_lock->write_unlock();
@@ -1960,10 +1849,9 @@ uint32_t ObjectDB::add_instance(Object *p_object) {
void ObjectDB::remove_instance(Object *p_object) {
-
rw_lock->write_lock();
- instances.erase( p_object->get_instance_ID() );
+ instances.erase(p_object->get_instance_ID());
#ifdef DEBUG_ENABLED
instance_checks.erase(p_object);
#endif
@@ -1973,7 +1861,7 @@ void ObjectDB::remove_instance(Object *p_object) {
Object *ObjectDB::get_instance(uint32_t p_instance_ID) {
rw_lock->read_lock();
- Object**obj=instances.getptr(p_instance_ID);
+ Object **obj = instances.getptr(p_instance_ID);
rw_lock->read_unlock();
if (!obj)
@@ -1985,34 +1873,28 @@ void ObjectDB::debug_objects(DebugFunc p_func) {
rw_lock->read_lock();
- const uint32_t *K=NULL;
- while((K=instances.next(K))) {
+ const uint32_t *K = NULL;
+ while ((K = instances.next(K))) {
p_func(instances[*K]);
}
rw_lock->read_unlock();
-
}
-
-void Object::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
-
-
+void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
}
int ObjectDB::get_object_count() {
rw_lock->read_lock();
- int count =instances.size();
+ int count = instances.size();
rw_lock->read_unlock();
return count;
-
}
-RWLock *ObjectDB::rw_lock=NULL;
-
+RWLock *ObjectDB::rw_lock = NULL;
void ObjectDB::setup() {
@@ -2021,21 +1903,20 @@ void ObjectDB::setup() {
void ObjectDB::cleanup() {
-
rw_lock->write_lock();
if (instances.size()) {
WARN_PRINT("ObjectDB Instances still exist!");
if (OS::get_singleton()->is_stdout_verbose()) {
- const uint32_t *K=NULL;
- while((K=instances.next(K))) {
+ const uint32_t *K = NULL;
+ while ((K = instances.next(K))) {
String node_name;
if (instances[*K]->is_class("Node"))
- node_name=" - Node Name: "+String(instances[*K]->call("get_name"));
+ node_name = " - Node Name: " + String(instances[*K]->call("get_name"));
if (instances[*K]->is_class("Resoucre"))
- node_name=" - Resource Name: "+String(instances[*K]->call("get_name"))+" Path: "+String(instances[*K]->call("get_path"));
- print_line("Leaked Instance: "+String(instances[*K]->get_class())+":"+itos(*K)+node_name);
+ node_name = " - Resource Name: " + String(instances[*K]->call("get_name")) + " Path: " + String(instances[*K]->call("get_path"));
+ print_line("Leaked Instance: " + String(instances[*K]->get_class()) + ":" + itos(*K) + node_name);
}
}
}
diff --git a/core/object.h b/core/object.h
index 3fe31bee6b..a5836b74ff 100644
--- a/core/object.h
+++ b/core/object.h
@@ -30,19 +30,19 @@
#define OBJECT_H
#include "list.h"
-#include "variant.h"
-#include "set.h"
#include "map.h"
-#include "vmap.h"
#include "os/rw_lock.h"
+#include "set.h"
+#include "variant.h"
+#include "vmap.h"
-#define VARIANT_ARG_LIST const Variant& p_arg1=Variant(),const Variant& p_arg2=Variant(),const Variant& p_arg3=Variant(),const Variant& p_arg4=Variant(),const Variant& p_arg5=Variant()
-#define VARIANT_ARG_PASS p_arg1,p_arg2,p_arg3,p_arg4,p_arg5
-#define VARIANT_ARG_DECLARE const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5
+#define VARIANT_ARG_LIST const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant()
+#define VARIANT_ARG_PASS p_arg1, p_arg2, p_arg3, p_arg4, p_arg5
+#define VARIANT_ARG_DECLARE const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5
#define VARIANT_ARG_MAX 5
-#define VARIANT_ARGPTRS const Variant *argptr[5]={&p_arg1,&p_arg2,&p_arg3,&p_arg4,&p_arg5};
-#define VARIANT_ARGPTRS_PASS *argptr[0],*argptr[1],*argptr[2],*argptr[3],*argptr[4]
-#define VARIANT_ARGS_FROM_ARRAY(m_arr) m_arr[0],m_arr[1],m_arr[2],m_arr[3],m_arr[4]
+#define VARIANT_ARGPTRS const Variant *argptr[5] = { &p_arg1, &p_arg2, &p_arg3, &p_arg4, &p_arg5 };
+#define VARIANT_ARGPTRS_PASS *argptr[0], *argptr[1], *argptr[2], *argptr[3], *argptr[4]
+#define VARIANT_ARGS_FROM_ARRAY(m_arr) m_arr[0], m_arr[1], m_arr[2], m_arr[3], m_arr[4]
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -87,40 +87,37 @@ enum PropertyHint {
enum PropertyUsageFlags {
- PROPERTY_USAGE_STORAGE=1,
- PROPERTY_USAGE_EDITOR=2,
- PROPERTY_USAGE_NETWORK=4,
- PROPERTY_USAGE_EDITOR_HELPER=8,
- PROPERTY_USAGE_CHECKABLE=16, //used for editing global variables
- PROPERTY_USAGE_CHECKED=32, //used for editing global variables
- PROPERTY_USAGE_INTERNATIONALIZED=64, //hint for internationalized strings
- PROPERTY_USAGE_GROUP=128, //used for grouping props in the editor
- PROPERTY_USAGE_CATEGORY=256,
- PROPERTY_USAGE_STORE_IF_NONZERO=512, //only store if nonzero
- PROPERTY_USAGE_STORE_IF_NONONE=1024, //only store if false
- PROPERTY_USAGE_NO_INSTANCE_STATE=2048,
- PROPERTY_USAGE_RESTART_IF_CHANGED=4096,
- PROPERTY_USAGE_SCRIPT_VARIABLE=8192,
- PROPERTY_USAGE_STORE_IF_NULL=16384,
- PROPERTY_USAGE_ANIMATE_AS_TRIGGER=32768,
- PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED=65536,
-
- PROPERTY_USAGE_DEFAULT=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_NETWORK,
- PROPERTY_USAGE_DEFAULT_INTL=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_NETWORK|PROPERTY_USAGE_INTERNATIONALIZED,
- PROPERTY_USAGE_NOEDITOR=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_NETWORK,
+ PROPERTY_USAGE_STORAGE = 1,
+ PROPERTY_USAGE_EDITOR = 2,
+ PROPERTY_USAGE_NETWORK = 4,
+ PROPERTY_USAGE_EDITOR_HELPER = 8,
+ PROPERTY_USAGE_CHECKABLE = 16, //used for editing global variables
+ PROPERTY_USAGE_CHECKED = 32, //used for editing global variables
+ PROPERTY_USAGE_INTERNATIONALIZED = 64, //hint for internationalized strings
+ PROPERTY_USAGE_GROUP = 128, //used for grouping props in the editor
+ PROPERTY_USAGE_CATEGORY = 256,
+ PROPERTY_USAGE_STORE_IF_NONZERO = 512, //only store if nonzero
+ PROPERTY_USAGE_STORE_IF_NONONE = 1024, //only store if false
+ PROPERTY_USAGE_NO_INSTANCE_STATE = 2048,
+ PROPERTY_USAGE_RESTART_IF_CHANGED = 4096,
+ PROPERTY_USAGE_SCRIPT_VARIABLE = 8192,
+ PROPERTY_USAGE_STORE_IF_NULL = 16384,
+ PROPERTY_USAGE_ANIMATE_AS_TRIGGER = 32768,
+ PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED = 65536,
+
+ PROPERTY_USAGE_DEFAULT = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_NETWORK,
+ PROPERTY_USAGE_DEFAULT_INTL = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_NETWORK | PROPERTY_USAGE_INTERNATIONALIZED,
+ PROPERTY_USAGE_NOEDITOR = PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_NETWORK,
};
-
-
-
-#define ADD_SIGNAL( m_signal ) ClassDB::add_signal( get_class_static(), m_signal )
-#define ADD_PROPERTY( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter) )
-#define ADD_PROPERTYI( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter), m_index )
-#define ADD_PROPERTYNZ( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter) )
-#define ADD_PROPERTYINZ( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter), m_index )
-#define ADD_PROPERTYNO( m_property, m_setter, m_getter ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter) )
-#define ADD_PROPERTYINO( m_property, m_setter, m_getter, m_index ) ClassDB::add_property( get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter), m_index )
-#define ADD_GROUP( m_name, m_prefix ) ClassDB::add_property_group( get_class_static(), m_name, m_prefix )
+#define ADD_SIGNAL(m_signal) ClassDB::add_signal(get_class_static(), m_signal)
+#define ADD_PROPERTY(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter))
+#define ADD_PROPERTYI(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), m_property, _scs_create(m_setter), _scs_create(m_getter), m_index)
+#define ADD_PROPERTYNZ(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter))
+#define ADD_PROPERTYINZ(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONZERO), _scs_create(m_setter), _scs_create(m_getter), m_index)
+#define ADD_PROPERTYNO(m_property, m_setter, m_getter) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter))
+#define ADD_PROPERTYINO(m_property, m_setter, m_getter, m_index) ClassDB::add_property(get_class_static(), (m_property).added_usage(PROPERTY_USAGE_STORE_IF_NONONE), _scs_create(m_setter), _scs_create(m_getter), m_index)
+#define ADD_GROUP(m_name, m_prefix) ClassDB::add_property_group(get_class_static(), m_name, m_prefix)
struct PropertyInfo {
@@ -130,25 +127,34 @@ struct PropertyInfo {
String hint_string;
uint32_t usage;
- _FORCE_INLINE_ PropertyInfo added_usage(int p_fl) const { PropertyInfo pi=*this; pi.usage|=p_fl; return pi; }
-
+ _FORCE_INLINE_ PropertyInfo added_usage(int p_fl) const {
+ PropertyInfo pi = *this;
+ pi.usage |= p_fl;
+ return pi;
+ }
operator Dictionary() const;
- static PropertyInfo from_dict(const Dictionary& p_dict);
+ static PropertyInfo from_dict(const Dictionary &p_dict);
- PropertyInfo() { type=Variant::NIL; hint=PROPERTY_HINT_NONE; usage = PROPERTY_USAGE_DEFAULT; }
- PropertyInfo( Variant::Type p_type, const String p_name, PropertyHint p_hint=PROPERTY_HINT_NONE, const String& p_hint_string="",uint32_t p_usage=PROPERTY_USAGE_DEFAULT) {
- type=p_type; name=p_name; hint=p_hint; hint_string=p_hint_string; usage=p_usage;
+ PropertyInfo() {
+ type = Variant::NIL;
+ hint = PROPERTY_HINT_NONE;
+ usage = PROPERTY_USAGE_DEFAULT;
+ }
+ PropertyInfo(Variant::Type p_type, const String p_name, PropertyHint p_hint = PROPERTY_HINT_NONE, const String &p_hint_string = "", uint32_t p_usage = PROPERTY_USAGE_DEFAULT) {
+ type = p_type;
+ name = p_name;
+ hint = p_hint;
+ hint_string = p_hint_string;
+ usage = p_usage;
}
- bool operator<(const PropertyInfo& p_info) const {
- return name<p_info.name;
+ bool operator<(const PropertyInfo &p_info) const {
+ return name < p_info.name;
}
};
-
-
-Array convert_property_list(const List<PropertyInfo> * p_list);
+Array convert_property_list(const List<PropertyInfo> *p_list);
struct MethodInfo {
@@ -159,25 +165,25 @@ struct MethodInfo {
uint32_t flags;
int id;
- inline bool operator<(const MethodInfo& p_method) const { return id==p_method.id?(name < p_method.name):(id<p_method.id); }
+ inline bool operator<(const MethodInfo &p_method) const { return id == p_method.id ? (name < p_method.name) : (id < p_method.id); }
operator Dictionary() const;
- static MethodInfo from_dict(const Dictionary& p_dict);
+ static MethodInfo from_dict(const Dictionary &p_dict);
MethodInfo();
- MethodInfo(const String& p_name);
- MethodInfo(const String& p_name, const PropertyInfo& p_param1);
- MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2);
- MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3);
- MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4);
- MethodInfo(const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5);
+ MethodInfo(const String &p_name);
+ MethodInfo(const String &p_name, const PropertyInfo &p_param1);
+ MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2);
+ MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3);
+ MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4);
+ MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5);
MethodInfo(Variant::Type ret);
- MethodInfo(Variant::Type ret,const String& p_name);
- MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1);
- MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2);
- MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3);
- MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4);
- MethodInfo(Variant::Type ret,const String& p_name, const PropertyInfo& p_param1,const PropertyInfo& p_param2,const PropertyInfo& p_param3,const PropertyInfo& p_param4,const PropertyInfo& p_param5);
+ MethodInfo(Variant::Type ret, const String &p_name);
+ MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1);
+ MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2);
+ MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3);
+ MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4);
+ MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5);
};
// old cast_to
@@ -190,154 +196,156 @@ struct MethodInfo {
the following is an uncomprehensible blob of hacks and workarounds to compensate for many of the fallencies in C++. As a plus, this macro pretty much alone defines the object model.
*/
-#define REVERSE_GET_PROPERTY_LIST \
-public:\
-_FORCE_INLINE_ bool _is_gpl_reversed() const { return true; };\
+#define REVERSE_GET_PROPERTY_LIST \
+public: \
+ _FORCE_INLINE_ bool _is_gpl_reversed() const { return true; }; \
+ \
private:
-#define UNREVERSE_GET_PROPERTY_LIST \
-public:\
-_FORCE_INLINE_ bool _is_gpl_reversed() const { return false; };\
+#define UNREVERSE_GET_PROPERTY_LIST \
+public: \
+ _FORCE_INLINE_ bool _is_gpl_reversed() const { return false; }; \
+ \
private:
-
-
-#define GDCLASS( m_class, m_inherits )\
-private:\
- void operator=(const m_class& p_rval) {}\
- mutable StringName _class_name;\
- friend class ClassDB;\
-public:\
-virtual String get_class() const { \
- return String(#m_class);\
-}\
-virtual const StringName* _get_class_namev() const { \
- if (!_class_name)\
- _class_name=get_class_static();\
- return &_class_name;\
-}\
-static _FORCE_INLINE_ void* get_class_ptr_static() { \
- static int ptr;\
- return &ptr;\
-}\
-static _FORCE_INLINE_ String get_class_static() { \
- return String(#m_class);\
-}\
-static _FORCE_INLINE_ String get_parent_class_static() { \
- return m_inherits::get_class_static();\
-}\
-static void get_inheritance_list_static(List<String>* p_inheritance_list) { \
- m_inherits::get_inheritance_list_static(p_inheritance_list);\
- p_inheritance_list->push_back(String(#m_class));\
-}\
-static String get_category_static() { \
- String category = m_inherits::get_category_static();\
- if (_get_category!=m_inherits::_get_category) {\
- if (category!="")\
- category+="/";\
- category+=_get_category();\
- }\
- return category;\
-}\
-static String inherits_static() {\
- return String(#m_inherits);\
-}\
-virtual bool is_class(const String& p_class) const { return (p_class==(#m_class))?true:m_inherits::is_class(p_class); }\
-virtual bool is_class_ptr(void *p_ptr) const { return (p_ptr==get_class_ptr_static())?true:m_inherits::is_class_ptr(p_ptr); }\
-\
-\
-static void get_valid_parents_static(List<String> *p_parents) {\
-\
- if (m_class::_get_valid_parents_static!=m_inherits::_get_valid_parents_static) { \
- m_class::_get_valid_parents_static(p_parents);\
- }\
-\
- m_inherits::get_valid_parents_static(p_parents);\
-}\
-protected:\
-_FORCE_INLINE_ static void (*_get_bind_methods())() {\
- return &m_class::_bind_methods;\
-}\
-public:\
-static void initialize_class() {\
- static bool initialized=false;\
- if (initialized)\
- return;\
- m_inherits::initialize_class();\
- ClassDB::_add_class<m_class>();\
- if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods())\
- _bind_methods();\
- initialized=true;\
-}\
-protected:\
-virtual void _initialize_classv() {\
- initialize_class();\
-}\
-_FORCE_INLINE_ bool (Object::* (_get_get() const))(const StringName& p_name,Variant&) const {\
- return (bool (Object::*)(const StringName&,Variant&)const) &m_class::_get;\
-}\
-virtual bool _getv(const StringName& p_name, Variant& r_ret) const { \
- if (m_class::_get_get() != m_inherits::_get_get()) {\
- if (_get(p_name,r_ret))\
- return true;\
- }\
- return m_inherits::_getv(p_name,r_ret);\
-}\
-_FORCE_INLINE_ bool (Object::* (_get_set() const))(const StringName& p_name,const Variant &p_property) {\
- return (bool (Object::*)(const StringName&, const Variant&))&m_class::_set;\
-}\
-virtual bool _setv(const StringName& p_name,const Variant &p_property) { \
- if (m_inherits::_setv(p_name,p_property)) return true;\
- if (m_class::_get_set() != m_inherits::_get_set()) {\
- return _set(p_name,p_property);\
- \
- }\
- return false;\
-}\
-_FORCE_INLINE_ void (Object::* (_get_get_property_list() const))(List<PropertyInfo> *p_list) const{\
- return (void (Object::*)(List<PropertyInfo>*)const)&m_class::_get_property_list;\
-}\
-virtual void _get_property_listv(List<PropertyInfo> *p_list,bool p_reversed) const { \
- if (!p_reversed) {\
- m_inherits::_get_property_listv(p_list,p_reversed);\
- }\
- p_list->push_back( PropertyInfo(Variant::NIL,get_class_static(),PROPERTY_HINT_NONE,String(),PROPERTY_USAGE_CATEGORY));\
- if (!_is_gpl_reversed())\
- ClassDB::get_property_list(#m_class,p_list,true,this);\
- if (m_class::_get_get_property_list() != m_inherits::_get_get_property_list()) {\
- _get_property_list(p_list);\
- }\
- if (_is_gpl_reversed())\
- ClassDB::get_property_list(#m_class,p_list,true,this);\
- if (p_reversed) {\
- m_inherits::_get_property_listv(p_list,p_reversed);\
- }\
-\
-}\
-_FORCE_INLINE_ void (Object::* (_get_notification() const))(int){\
- return (void (Object::*)(int)) &m_class::_notification;\
-}\
-virtual void _notificationv(int p_notification,bool p_reversed) { \
- if (!p_reversed) \
- m_inherits::_notificationv(p_notification,p_reversed);\
- if (m_class::_get_notification() != m_inherits::_get_notification()) {\
- _notification(p_notification);\
- }\
- if (p_reversed)\
- m_inherits::_notificationv(p_notification,p_reversed);\
-}\
-\
+#define GDCLASS(m_class, m_inherits) \
+private: \
+ void operator=(const m_class &p_rval) {} \
+ mutable StringName _class_name; \
+ friend class ClassDB; \
+ \
+public: \
+ virtual String get_class() const { \
+ return String(#m_class); \
+ } \
+ virtual const StringName *_get_class_namev() const { \
+ if (!_class_name) \
+ _class_name = get_class_static(); \
+ return &_class_name; \
+ } \
+ static _FORCE_INLINE_ void *get_class_ptr_static() { \
+ static int ptr; \
+ return &ptr; \
+ } \
+ static _FORCE_INLINE_ String get_class_static() { \
+ return String(#m_class); \
+ } \
+ static _FORCE_INLINE_ String get_parent_class_static() { \
+ return m_inherits::get_class_static(); \
+ } \
+ static void get_inheritance_list_static(List<String> *p_inheritance_list) { \
+ m_inherits::get_inheritance_list_static(p_inheritance_list); \
+ p_inheritance_list->push_back(String(#m_class)); \
+ } \
+ static String get_category_static() { \
+ String category = m_inherits::get_category_static(); \
+ if (_get_category != m_inherits::_get_category) { \
+ if (category != "") \
+ category += "/"; \
+ category += _get_category(); \
+ } \
+ return category; \
+ } \
+ static String inherits_static() { \
+ return String(#m_inherits); \
+ } \
+ virtual bool is_class(const String &p_class) const { return (p_class == (#m_class)) ? true : m_inherits::is_class(p_class); } \
+ virtual bool is_class_ptr(void *p_ptr) const { return (p_ptr == get_class_ptr_static()) ? true : m_inherits::is_class_ptr(p_ptr); } \
+ \
+ static void get_valid_parents_static(List<String> *p_parents) { \
+ \
+ if (m_class::_get_valid_parents_static != m_inherits::_get_valid_parents_static) { \
+ m_class::_get_valid_parents_static(p_parents); \
+ } \
+ \
+ m_inherits::get_valid_parents_static(p_parents); \
+ } \
+ \
+protected: \
+ _FORCE_INLINE_ static void (*_get_bind_methods())() { \
+ return &m_class::_bind_methods; \
+ } \
+ \
+public: \
+ static void initialize_class() { \
+ static bool initialized = false; \
+ if (initialized) \
+ return; \
+ m_inherits::initialize_class(); \
+ ClassDB::_add_class<m_class>(); \
+ if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods()) \
+ _bind_methods(); \
+ initialized = true; \
+ } \
+ \
+protected: \
+ virtual void _initialize_classv() { \
+ initialize_class(); \
+ } \
+ _FORCE_INLINE_ bool (Object::*(_get_get() const))(const StringName &p_name, Variant &) const { \
+ return (bool (Object::*)(const StringName &, Variant &) const) & m_class::_get; \
+ } \
+ virtual bool _getv(const StringName &p_name, Variant &r_ret) const { \
+ if (m_class::_get_get() != m_inherits::_get_get()) { \
+ if (_get(p_name, r_ret)) \
+ return true; \
+ } \
+ return m_inherits::_getv(p_name, r_ret); \
+ } \
+ _FORCE_INLINE_ bool (Object::*(_get_set() const))(const StringName &p_name, const Variant &p_property) { \
+ return (bool (Object::*)(const StringName &, const Variant &)) & m_class::_set; \
+ } \
+ virtual bool _setv(const StringName &p_name, const Variant &p_property) { \
+ if (m_inherits::_setv(p_name, p_property)) return true; \
+ if (m_class::_get_set() != m_inherits::_get_set()) { \
+ return _set(p_name, p_property); \
+ } \
+ return false; \
+ } \
+ _FORCE_INLINE_ void (Object::*(_get_get_property_list() const))(List<PropertyInfo> * p_list) const { \
+ return (void (Object::*)(List<PropertyInfo> *) const) & m_class::_get_property_list; \
+ } \
+ virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const { \
+ if (!p_reversed) { \
+ m_inherits::_get_property_listv(p_list, p_reversed); \
+ } \
+ p_list->push_back(PropertyInfo(Variant::NIL, get_class_static(), PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); \
+ if (!_is_gpl_reversed()) \
+ ClassDB::get_property_list(#m_class, p_list, true, this); \
+ if (m_class::_get_get_property_list() != m_inherits::_get_get_property_list()) { \
+ _get_property_list(p_list); \
+ } \
+ if (_is_gpl_reversed()) \
+ ClassDB::get_property_list(#m_class, p_list, true, this); \
+ if (p_reversed) { \
+ m_inherits::_get_property_listv(p_list, p_reversed); \
+ } \
+ } \
+ _FORCE_INLINE_ void (Object::*(_get_notification() const))(int) { \
+ return (void (Object::*)(int)) & m_class::_notification; \
+ } \
+ virtual void _notificationv(int p_notification, bool p_reversed) { \
+ if (!p_reversed) \
+ m_inherits::_notificationv(p_notification, p_reversed); \
+ if (m_class::_get_notification() != m_inherits::_get_notification()) { \
+ _notification(p_notification); \
+ } \
+ if (p_reversed) \
+ m_inherits::_notificationv(p_notification, p_reversed); \
+ } \
+ \
private:
-
-#define OBJ_CATEGORY(m_category)\
-protected:\
-_FORCE_INLINE_ static String _get_category() { return m_category; }\
+#define OBJ_CATEGORY(m_category) \
+protected: \
+ _FORCE_INLINE_ static String _get_category() { return m_category; } \
+ \
private:
-#define OBJ_SAVE_TYPE(m_class) \
-public: \
-virtual String get_save_class() const { return #m_class; }\
+#define OBJ_SAVE_TYPE(m_class) \
+public: \
+ virtual String get_save_class() const { return #m_class; } \
+ \
private:
class ScriptInstance;
@@ -345,12 +353,11 @@ typedef uint32_t ObjectID;
class Object {
public:
-
enum ConnectFlags {
- CONNECT_DEFERRED=1,
- CONNECT_PERSIST=2, // hint for scene to save this connection
- CONNECT_ONESHOT=4
+ CONNECT_DEFERRED = 1,
+ CONNECT_PERSIST = 2, // hint for scene to save this connection
+ CONNECT_ONESHOT = 4
};
struct Connection {
@@ -361,19 +368,23 @@ public:
StringName method;
uint32_t flags;
Vector<Variant> binds;
- bool operator<(const Connection& p_conn) const;
+ bool operator<(const Connection &p_conn) const;
operator Variant() const;
- Connection() { source=NULL; target=NULL; flags=0; }
- Connection(const Variant& p_variant);
+ Connection() {
+ source = NULL;
+ target = NULL;
+ flags = 0;
+ }
+ Connection(const Variant &p_variant);
};
+
private:
#ifdef DEBUG_ENABLED
-friend class _ObjectDebugLock;
+ friend class _ObjectDebugLock;
#endif
-friend bool predelete_handler(Object*);
-friend void postinitialize_handler(Object*);
-
+ friend bool predelete_handler(Object *);
+ friend void postinitialize_handler(Object *);
struct Signal {
@@ -382,10 +393,13 @@ friend void postinitialize_handler(Object*);
ObjectID _id;
StringName method;
- _FORCE_INLINE_ bool operator<(const Target& p_target) const { return (_id==p_target._id)?(method<p_target.method):(_id<p_target._id); }
+ _FORCE_INLINE_ bool operator<(const Target &p_target) const { return (_id == p_target._id) ? (method < p_target.method) : (_id < p_target._id); }
- Target(const ObjectID& p_id, const StringName& p_method) { _id=p_id; method=p_method; }
- Target() { _id=0; }
+ Target(const ObjectID &p_id, const StringName &p_method) {
+ _id = p_id;
+ method = p_method;
+ }
+ Target() { _id = 0; }
};
struct Slot {
@@ -395,21 +409,19 @@ friend void postinitialize_handler(Object*);
};
MethodInfo user;
- VMap<Target,Slot> slot_map;
+ VMap<Target, Slot> slot_map;
int lock;
- Signal() { lock=0; }
-
+ Signal() { lock = 0; }
};
-
- HashMap< StringName, Signal, StringNameHasher> signal_map;
+ HashMap<StringName, Signal, StringNameHasher> signal_map;
List<Connection> connections;
#ifdef DEBUG_ENABLED
SafeRefCount _lock_index;
#endif
bool _block_signals;
int _predelete_ok;
- Set<Object*> change_receptors;
+ Set<Object *> change_receptors;
uint32_t _instance_ID;
bool _predelete();
void _postinitialize();
@@ -422,67 +434,63 @@ friend void postinitialize_handler(Object*);
RefPtr script;
Dictionary metadata;
mutable StringName _class_name;
- mutable const StringName* _class_ptr;
+ mutable const StringName *_class_ptr;
- void _add_user_signal(const String& p_name, const Array& p_pargs=Array());
- bool _has_user_signal(const StringName& p_name) const;
- Variant _emit_signal(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+ void _add_user_signal(const String &p_name, const Array &p_pargs = Array());
+ bool _has_user_signal(const StringName &p_name) const;
+ Variant _emit_signal(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
Array _get_signal_list() const;
- Array _get_signal_connection_list(const String& p_signal) const;
- void _set_bind(const String& p_set,const Variant& p_value);
- Variant _get_bind(const String& p_name) const;
+ Array _get_signal_connection_list(const String &p_signal) const;
+ void _set_bind(const String &p_set, const Variant &p_value);
+ Variant _get_bind(const String &p_name) const;
void property_list_changed_notify();
protected:
-
-
virtual void _initialize_classv() { initialize_class(); }
- virtual bool _setv(const StringName& p_name,const Variant &p_property) { return false; };
- virtual bool _getv(const StringName& p_name,Variant &r_property) const { return false; };
- virtual void _get_property_listv(List<PropertyInfo> *p_list,bool p_reversed) const {};
- virtual void _notificationv(int p_notification,bool p_reversed) {};
+ virtual bool _setv(const StringName &p_name, const Variant &p_property) { return false; };
+ virtual bool _getv(const StringName &p_name, Variant &r_property) const { return false; };
+ virtual void _get_property_listv(List<PropertyInfo> *p_list, bool p_reversed) const {};
+ virtual void _notificationv(int p_notification, bool p_reversed){};
static String _get_category() { return ""; }
static void _bind_methods();
- bool _set(const StringName& p_name,const Variant &p_property) { return false; };
- bool _get(const StringName& p_name,Variant &r_property) const { return false; };
+ bool _set(const StringName &p_name, const Variant &p_property) { return false; };
+ bool _get(const StringName &p_name, Variant &r_property) const { return false; };
void _get_property_list(List<PropertyInfo> *p_list) const {};
- void _notification(int p_notification) {};
+ void _notification(int p_notification){};
_FORCE_INLINE_ static void (*_get_bind_methods())() {
return &Object::_bind_methods;
}
- _FORCE_INLINE_ bool (Object::* (_get_get() const))(const StringName& p_name,Variant &r_ret) const {
+ _FORCE_INLINE_ bool (Object::*(_get_get() const))(const StringName &p_name, Variant &r_ret) const {
return &Object::_get;
}
- _FORCE_INLINE_ bool (Object::* (_get_set() const))(const StringName& p_name,const Variant &p_property) {
- return &Object::_set;
+ _FORCE_INLINE_ bool (Object::*(_get_set() const))(const StringName &p_name, const Variant &p_property) {
+ return &Object::_set;
}
- _FORCE_INLINE_ void (Object::* (_get_get_property_list() const))(List<PropertyInfo> *p_list) const{
- return &Object::_get_property_list;
+ _FORCE_INLINE_ void (Object::*(_get_get_property_list() const))(List<PropertyInfo> *p_list) const {
+ return &Object::_get_property_list;
}
- _FORCE_INLINE_ void (Object::* (_get_notification() const))(int){
- return &Object::_notification;
+ _FORCE_INLINE_ void (Object::*(_get_notification() const))(int) {
+ return &Object::_notification;
}
static void get_valid_parents_static(List<String> *p_parents);
static void _get_valid_parents_static(List<String> *p_parents);
-
void cancel_delete();
- virtual void _changed_callback(Object *p_changed,const char *p_prop);
+ virtual void _changed_callback(Object *p_changed, const char *p_prop);
//Variant _call_bind(const StringName& p_name, const Variant& p_arg1 = Variant(), const Variant& p_arg2 = Variant(), const Variant& p_arg3 = Variant(), const Variant& p_arg4 = Variant());
//void _call_deferred_bind(const StringName& p_name, const Variant& p_arg1 = Variant(), const Variant& p_arg2 = Variant(), const Variant& p_arg3 = Variant(), const Variant& p_arg4 = Variant());
- Variant _call_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _call_deferred_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
-
+ Variant _call_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _call_deferred_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
- virtual const StringName* _get_class_namev() const {
+ virtual const StringName *_get_class_namev() const {
if (!_class_name)
- _class_name=get_class_static();
+ _class_name = get_class_static();
return &_class_name;
}
@@ -492,21 +500,24 @@ protected:
void _clear_internal_resource_paths(const Variant &p_var);
-friend class ClassDB;
- virtual void _validate_property(PropertyInfo& property) const;
+ friend class ClassDB;
+ virtual void _validate_property(PropertyInfo &property) const;
public: //should be protected, but bug in clang++
static void initialize_class();
- _FORCE_INLINE_ static void register_custom_data_to_otdb() {};
+ _FORCE_INLINE_ static void register_custom_data_to_otdb(){};
public:
-
#ifdef TOOLS_ENABLED
- _FORCE_INLINE_ void _change_notify(const char *p_property="") { _edited=true; for(Set<Object*>::Element *E=change_receptors.front();E;E=E->next()) ((Object*)(E->get()))->_changed_callback(this,p_property); }
+ _FORCE_INLINE_ void _change_notify(const char *p_property = "") {
+ _edited = true;
+ for (Set<Object *>::Element *E = change_receptors.front(); E; E = E->next())
+ ((Object *)(E->get()))->_changed_callback(this, p_property);
+ }
#else
- _FORCE_INLINE_ void _change_notify(const char *p_what="") { }
+ _FORCE_INLINE_ void _change_notify(const char *p_what = "") {}
#endif
- static void* get_class_ptr_static() {
+ static void *get_class_ptr_static() {
static int ptr;
return &ptr;
}
@@ -516,34 +527,34 @@ public:
_FORCE_INLINE_ ObjectID get_instance_ID() const { return _instance_ID; }
// this is used for editors
- void add_change_receptor( Object *p_receptor );
- void remove_change_receptor( Object *p_receptor );
+ void add_change_receptor(Object *p_receptor);
+ void remove_change_receptor(Object *p_receptor);
- template<class T>
+ template <class T>
T *cast_to() {
#ifndef NO_SAFE_CAST
- return SAFE_CAST<T*>(this);
+ return SAFE_CAST<T *>(this);
#else
if (!this)
return NULL;
if (is_class_ptr(T::get_class_ptr_static()))
- return static_cast<T*>(this);
+ return static_cast<T *>(this);
else
return NULL;
#endif
}
- template<class T>
+ template <class T>
const T *cast_to() const {
#ifndef NO_SAFE_CAST
- return SAFE_CAST<const T*>(this);
+ return SAFE_CAST<const T *>(this);
#else
if (!this)
return NULL;
if (is_class_ptr(T::get_class_ptr_static()))
- return static_cast<const T*>(this);
+ return static_cast<const T *>(this);
else
return NULL;
#endif
@@ -551,27 +562,24 @@ public:
enum {
- NOTIFICATION_POSTINITIALIZE=0,
- NOTIFICATION_PREDELETE=1
+ NOTIFICATION_POSTINITIALIZE = 0,
+ NOTIFICATION_PREDELETE = 1
};
/* TYPE API */
- static void get_inheritance_list_static(List<String>* p_inheritance_list) { p_inheritance_list->push_back("Object"); }
+ static void get_inheritance_list_static(List<String> *p_inheritance_list) { p_inheritance_list->push_back("Object"); }
static String get_class_static() { return "Object"; }
static String get_parent_class_static() { return String(); }
static String get_category_static() { return String(); }
-
virtual String get_class() const { return "Object"; }
virtual String get_save_class() const { return get_class(); } //class stored when saving
+ virtual bool is_class(const String &p_class) const { return (p_class == "Object"); }
+ virtual bool is_class_ptr(void *p_ptr) const { return get_class_ptr_static() == p_ptr; }
-
- virtual bool is_class(const String& p_class) const { return (p_class=="Object"); }
- virtual bool is_class_ptr(void *p_ptr) const { return get_class_ptr_static()==p_ptr; }
-
- _FORCE_INLINE_ const StringName& get_class_name() const {
+ _FORCE_INLINE_ const StringName &get_class_name() const {
if (!_class_ptr) {
return *_get_class_namev();
} else {
@@ -583,36 +591,36 @@ public:
//void set(const String& p_name, const Variant& p_value);
//Variant get(const String& p_name) const;
- void set(const StringName& p_name, const Variant& p_value, bool *r_valid=NULL);
- Variant get(const StringName& p_name, bool *r_valid=NULL) const;
+ void set(const StringName &p_name, const Variant &p_value, bool *r_valid = NULL);
+ Variant get(const StringName &p_name, bool *r_valid = NULL) const;
- void get_property_list(List<PropertyInfo> *p_list,bool p_reversed=false) const;
+ void get_property_list(List<PropertyInfo> *p_list, bool p_reversed = false) const;
- bool has_method(const StringName& p_method) const;
+ bool has_method(const StringName &p_method) const;
void get_method_list(List<MethodInfo> *p_list) const;
- Variant callv(const StringName& p_method,const Array& p_args);
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::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 call(const StringName& p_name, VARIANT_ARG_LIST); // C++ helper
- void call_multilevel(const StringName& p_name, VARIANT_ARG_LIST); // C++ helper
+ Variant callv(const StringName &p_method, const Array &p_args);
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::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 call(const StringName &p_name, VARIANT_ARG_LIST); // C++ helper
+ void call_multilevel(const StringName &p_name, VARIANT_ARG_LIST); // C++ helper
- void notification(int p_notification,bool p_reversed=false);
+ void notification(int p_notification, bool p_reversed = false);
//used mainly by script, get and set all INCLUDING string
- virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const;
- virtual void setvar(const Variant& p_key, const Variant& p_value,bool *r_valid=NULL);
+ virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const;
+ virtual void setvar(const Variant &p_key, const Variant &p_value, bool *r_valid = NULL);
/* SCRIPT */
- void set_script(const RefPtr& p_script);
+ void set_script(const RefPtr &p_script);
RefPtr get_script() const;
/* SCRIPT */
- bool has_meta(const String& p_name) const;
- void set_meta(const String& p_name, const Variant& p_value );
- Variant get_meta(const String& p_name) const;
+ bool has_meta(const String &p_name) const;
+ void set_meta(const String &p_name, const Variant &p_value);
+ Variant get_meta(const String &p_name) const;
void get_meta_list(List<String> *p_list) const;
#ifdef TOOLS_ENABLED
@@ -622,50 +630,47 @@ public:
#endif
void set_script_instance(ScriptInstance *p_instance);
- _FORCE_INLINE_ ScriptInstance* get_script_instance() const { return script_instance; }
-
+ _FORCE_INLINE_ ScriptInstance *get_script_instance() const { return script_instance; }
- void add_user_signal(const MethodInfo& p_signal);
- void emit_signal(const StringName& p_name,VARIANT_ARG_LIST);
- void emit_signal(const StringName& p_name, const Variant** p_args, int p_argcount);
- void get_signal_list(List<MethodInfo> *p_signals ) const;
- void get_signal_connection_list(const StringName& p_signal,List<Connection> *p_connections) const;
+ void add_user_signal(const MethodInfo &p_signal);
+ void emit_signal(const StringName &p_name, VARIANT_ARG_LIST);
+ void emit_signal(const StringName &p_name, const Variant **p_args, int p_argcount);
+ void get_signal_list(List<MethodInfo> *p_signals) const;
+ void get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const;
void get_all_signal_connections(List<Connection> *p_connections) const;
bool has_persistent_signal_connections() const;
void get_signals_connected_to_this(List<Connection> *p_connections) const;
- Error connect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method,const Vector<Variant>& p_binds=Vector<Variant>(),uint32_t p_flags=0);
- void disconnect(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method);
- bool is_connected(const StringName& p_signal, Object *p_to_object, const StringName& p_to_method) const;
+ Error connect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds = Vector<Variant>(), uint32_t p_flags = 0);
+ void disconnect(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method);
+ bool is_connected(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) const;
- void call_deferred(const StringName& p_method,VARIANT_ARG_LIST);
+ void call_deferred(const StringName &p_method, VARIANT_ARG_LIST);
void set_block_signals(bool p_block);
bool is_blocking_signals() const;
- Variant::Type get_static_property_type(const StringName& p_property,bool *r_valid=NULL) const;
+ Variant::Type get_static_property_type(const StringName &p_property, bool *r_valid = NULL) const;
virtual void get_translatable_strings(List<String> *p_strings) const;
- virtual void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
+ virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
- StringName XL_MESSAGE(const StringName& p_message) const; //translate message (internationalization)
- StringName tr(const StringName& p_message) const; //translate message (alternative)
+ StringName XL_MESSAGE(const StringName &p_message) const; //translate message (internationalization)
+ StringName tr(const StringName &p_message) const; //translate message (alternative)
bool _is_queued_for_deletion; // set to true by SceneTree::queue_delete()
bool is_queued_for_deletion() const;
- _FORCE_INLINE_ void set_message_translation(bool p_enable) { _can_translate=p_enable; }
+ _FORCE_INLINE_ void set_message_translation(bool p_enable) { _can_translate = p_enable; }
_FORCE_INLINE_ bool can_translate_messages() const { return _can_translate; }
void clear_internal_resource_paths();
Object();
virtual ~Object();
-
};
-
bool predelete_handler(Object *p_object);
void postinitialize_handler(Object *p_object);
@@ -676,31 +681,29 @@ class ObjectDB {
static _FORCE_INLINE_ uint32_t hash(const Object *p_obj) {
union {
- const Object*p;
+ const Object *p;
unsigned long i;
} u;
- u.p=p_obj;
+ u.p = p_obj;
return HashMapHasherDefault::hash((uint64_t)u.i);
}
};
- static HashMap<uint32_t,Object*> instances;
- static HashMap<Object*,ObjectID,ObjectPtrHash> instance_checks;
+ static HashMap<uint32_t, Object *> instances;
+ static HashMap<Object *, ObjectID, ObjectPtrHash> instance_checks;
static uint32_t instance_counter;
-friend class Object;
-friend void unregister_core_types();
-
+ friend class Object;
+ friend void unregister_core_types();
static RWLock *rw_lock;
static void cleanup();
static uint32_t add_instance(Object *p_object);
static void remove_instance(Object *p_object);
-friend void register_core_types();
+ friend void register_core_types();
static void setup();
public:
-
typedef void (*DebugFunc)(Object *p_obj);
static Object *get_instance(uint32_t p_instance_ID);
@@ -708,17 +711,14 @@ public:
static int get_object_count();
#ifdef DEBUG_ENABLED
- _FORCE_INLINE_ static bool instance_validate(Object* p_ptr) {
+ _FORCE_INLINE_ static bool instance_validate(Object *p_ptr) {
return instance_checks.has(p_ptr);
}
#else
- _FORCE_INLINE_ static bool instance_validate(Object* p_ptr) { return true; }
+ _FORCE_INLINE_ static bool instance_validate(Object *p_ptr) { return true; }
#endif
-
-
-
};
//needed by macros
diff --git a/core/os/copymem.h b/core/os/copymem.h
index 0452b1a36c..9b13d6c731 100644
--- a/core/os/copymem.h
+++ b/core/os/copymem.h
@@ -39,7 +39,7 @@
#include <string.h>
-#define copymem(to,from,count) memcpy(to,from,count)
+#define copymem(to, from, count) memcpy(to, from, count)
#define zeromem(to, count) memset(to, 0, count)
#define movemem(to, from, count) memmove(to, from, count)
diff --git a/core/os/dir_access.cpp b/core/os/dir_access.cpp
index 974225a3e8..6f7255372f 100644
--- a/core/os/dir_access.cpp
+++ b/core/os/dir_access.cpp
@@ -27,15 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "dir_access.h"
+#include "global_config.h"
#include "os/file_access.h"
#include "os/memory.h"
#include "os/os.h"
-#include "global_config.h"
-
String DirAccess::_get_root_path() const {
- switch(_access_type) {
+ switch (_access_type) {
case ACCESS_RESOURCES: return GlobalConfig::get_singleton()->get_resource_path();
case ACCESS_USERDATA: return OS::get_singleton()->get_data_dir();
@@ -46,7 +45,7 @@ String DirAccess::_get_root_path() const {
}
String DirAccess::_get_root_string() const {
- switch(_access_type) {
+ switch (_access_type) {
case ACCESS_RESOURCES: return "res://";
case ACCESS_USERDATA: return "user://";
@@ -59,7 +58,7 @@ String DirAccess::_get_root_string() const {
int DirAccess::get_current_drive() {
String path = get_current_dir().to_lower();
- for(int i=0;i<get_drive_count();i++) {
+ for (int i = 0; i < get_drive_count(); i++) {
String d = get_drive(i).to_lower();
if (path.begins_with(d))
return i;
@@ -75,9 +74,9 @@ static Error _erase_recursive(DirAccess *da) {
da->list_dir_begin();
String n = da->get_next();
- while(n!=String()) {
+ while (n != String()) {
- if (n!="." && n!="..") {
+ if (n != "." && n != "..") {
if (da->current_is_dir())
dirs.push_back(n);
@@ -85,43 +84,43 @@ static Error _erase_recursive(DirAccess *da) {
files.push_back(n);
}
- n=da->get_next();
+ n = da->get_next();
}
da->list_dir_end();
- for(List<String>::Element *E=dirs.front();E;E=E->next()) {
+ for (List<String>::Element *E = dirs.front(); E; E = E->next()) {
Error err = da->change_dir(E->get());
- if (err==OK) {
+ if (err == OK) {
err = _erase_recursive(da);
if (err) {
- print_line("err recurso "+E->get());
+ print_line("err recurso " + E->get());
return err;
}
err = da->change_dir("..");
if (err) {
- print_line("no go back "+E->get());
+ print_line("no go back " + E->get());
return err;
}
err = da->remove(da->get_current_dir().plus_file(E->get()));
if (err) {
- print_line("no remove dir"+E->get());
+ print_line("no remove dir" + E->get());
return err;
}
} else {
- print_line("no change to "+E->get());
+ print_line("no change to " + E->get());
return err;
}
}
- for(List<String>::Element *E=files.front();E;E=E->next()) {
+ for (List<String>::Element *E = files.front(); E; E = E->next()) {
Error err = da->remove(da->get_current_dir().plus_file(E->get()));
if (err) {
- print_line("no remove file"+E->get());
+ print_line("no remove file" + E->get());
return err;
}
}
@@ -129,13 +128,11 @@ static Error _erase_recursive(DirAccess *da) {
return OK;
}
-
Error DirAccess::erase_contents_recursive() {
return _erase_recursive(this);
}
-
Error DirAccess::make_dir_recursive(String p_dir) {
if (p_dir.length() < 1) {
@@ -145,39 +142,39 @@ Error DirAccess::make_dir_recursive(String p_dir) {
String full_dir;
if (p_dir.is_rel_path()) {
- //append current
- full_dir=get_current_dir().plus_file(p_dir);
+ //append current
+ full_dir = get_current_dir().plus_file(p_dir);
} else {
- full_dir=p_dir;
+ full_dir = p_dir;
}
- full_dir=full_dir.replace("\\","/");
+ full_dir = full_dir.replace("\\", "/");
//int slices = full_dir.get_slice_count("/");
String base;
if (full_dir.begins_with("res://"))
- base="res://";
+ base = "res://";
else if (full_dir.begins_with("user://"))
- base="user://";
+ base = "user://";
else if (full_dir.begins_with("/"))
- base="/";
- else if (full_dir.find(":/")!=-1) {
- base=full_dir.substr(0,full_dir.find(":/")+2);
+ base = "/";
+ else if (full_dir.find(":/") != -1) {
+ base = full_dir.substr(0, full_dir.find(":/") + 2);
} else {
ERR_FAIL_V(ERR_INVALID_PARAMETER);
}
- full_dir=full_dir.replace_first(base,"").simplify_path();
+ full_dir = full_dir.replace_first(base, "").simplify_path();
- Vector<String> subdirs=full_dir.split("/");
+ Vector<String> subdirs = full_dir.split("/");
- String curpath=base;
- for(int i=0;i<subdirs.size();i++) {
+ String curpath = base;
+ for (int i = 0; i < subdirs.size(); i++) {
- curpath=curpath.plus_file(subdirs[i]);
+ curpath = curpath.plus_file(subdirs[i]);
Error err = make_dir(curpath);
if (err != OK && err != ERR_ALREADY_EXISTS) {
@@ -188,19 +185,17 @@ Error DirAccess::make_dir_recursive(String p_dir) {
return OK;
}
+String DirAccess::get_next(bool *p_is_dir) {
-
-String DirAccess::get_next(bool* p_is_dir) {
-
- String next=get_next();
+ String next = get_next();
if (p_is_dir)
- *p_is_dir=current_is_dir();
+ *p_is_dir = current_is_dir();
return next;
}
String DirAccess::fix_path(String p_path) const {
- switch(_access_type) {
+ switch (_access_type) {
case ACCESS_RESOURCES: {
@@ -210,23 +205,21 @@ String DirAccess::fix_path(String p_path) const {
String resource_path = GlobalConfig::get_singleton()->get_resource_path();
if (resource_path != "") {
- return p_path.replace_first("res:/",resource_path);
+ return p_path.replace_first("res:/", resource_path);
};
return p_path.replace_first("res://", "");
}
}
-
} break;
case ACCESS_USERDATA: {
-
if (p_path.begins_with("user://")) {
- String data_dir=OS::get_singleton()->get_data_dir();
+ String data_dir = OS::get_singleton()->get_data_dir();
if (data_dir != "") {
- return p_path.replace_first("user:/",data_dir);
+ return p_path.replace_first("user:/", data_dir);
};
return p_path.replace_first("user://", "");
}
@@ -241,35 +234,34 @@ String DirAccess::fix_path(String p_path) const {
return p_path;
}
+DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX] = { 0, 0, 0 };
-DirAccess::CreateFunc DirAccess::create_func[ACCESS_MAX]={0,0,0};
+DirAccess *DirAccess::create_for_path(const String &p_path) {
-DirAccess *DirAccess::create_for_path(const String& p_path) {
-
- DirAccess *da=NULL;
+ DirAccess *da = NULL;
if (p_path.begins_with("res://")) {
- da=create(ACCESS_RESOURCES);
+ da = create(ACCESS_RESOURCES);
} else if (p_path.begins_with("user://")) {
- da=create(ACCESS_USERDATA);
+ da = create(ACCESS_USERDATA);
} else {
- da=create(ACCESS_FILESYSTEM);
+ da = create(ACCESS_FILESYSTEM);
}
return da;
}
-DirAccess *DirAccess::open(const String& p_path,Error *r_error) {
+DirAccess *DirAccess::open(const String &p_path, Error *r_error) {
- DirAccess *da=create_for_path(p_path);
+ DirAccess *da = create_for_path(p_path);
- ERR_FAIL_COND_V(!da,NULL);
+ ERR_FAIL_COND_V(!da, NULL);
Error err = da->change_dir(p_path);
if (r_error)
- *r_error=err;
- if (err!=OK) {
+ *r_error = err;
+ if (err != OK) {
memdelete(da);
return NULL;
}
@@ -279,63 +271,61 @@ DirAccess *DirAccess::open(const String& p_path,Error *r_error) {
DirAccess *DirAccess::create(AccessType p_access) {
- DirAccess * da = create_func[p_access]?create_func[p_access]():NULL;
+ DirAccess *da = create_func[p_access] ? create_func[p_access]() : NULL;
if (da) {
- da->_access_type=p_access;
+ da->_access_type = p_access;
}
return da;
};
+String DirAccess::get_full_path(const String &p_path, AccessType p_access) {
-String DirAccess::get_full_path(const String& p_path,AccessType p_access) {
-
- DirAccess *d=DirAccess::create(p_access);
+ DirAccess *d = DirAccess::create(p_access);
if (!d)
return p_path;
d->change_dir(p_path);
- String full=d->get_current_dir();
+ String full = d->get_current_dir();
memdelete(d);
return full;
}
-Error DirAccess::copy(String p_from,String p_to) {
+Error DirAccess::copy(String p_from, String p_to) {
//printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data());
Error err;
- FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ,&err);
+ FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V( err, err );
+ ERR_FAIL_COND_V(err, err);
}
-
- FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE,&err );
+ FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE, &err);
if (err) {
fsrc->close();
- memdelete( fsrc );
- ERR_FAIL_COND_V( err, err );
+ memdelete(fsrc);
+ ERR_FAIL_COND_V(err, err);
}
fsrc->seek_end(0);
int size = fsrc->get_pos();
fsrc->seek(0);
err = OK;
- while(size--) {
+ while (size--) {
- if (fsrc->get_error()!=OK) {
- err= fsrc->get_error();
+ if (fsrc->get_error() != OK) {
+ err = fsrc->get_error();
break;
}
- if (fdst->get_error()!=OK) {
- err= fdst->get_error();
+ if (fdst->get_error() != OK) {
+ err = fdst->get_error();
break;
}
- fdst->store_8( fsrc->get_8() );
+ fdst->store_8(fsrc->get_8());
}
memdelete(fsrc);
@@ -346,21 +336,16 @@ Error DirAccess::copy(String p_from,String p_to) {
bool DirAccess::exists(String p_dir) {
- DirAccess* da = DirAccess::create_for_path(p_dir);
- bool valid = da->change_dir(p_dir)==OK;
+ DirAccess *da = DirAccess::create_for_path(p_dir);
+ bool valid = da->change_dir(p_dir) == OK;
memdelete(da);
return valid;
-
}
-DirAccess::DirAccess(){
+DirAccess::DirAccess() {
- _access_type=ACCESS_FILESYSTEM;
+ _access_type = ACCESS_FILESYSTEM;
}
-
DirAccess::~DirAccess() {
-
}
-
-
diff --git a/core/os/dir_access.h b/core/os/dir_access.h
index 7c173fc780..1ac2d0e03a 100644
--- a/core/os/dir_access.h
+++ b/core/os/dir_access.h
@@ -29,7 +29,6 @@
#ifndef DIR_ACCESS_H
#define DIR_ACCESS_H
-
#include "typedefs.h"
#include "ustring.h"
@@ -40,7 +39,6 @@
//@ TOOD, excellent candidate for THREAD_SAFE MACRO, should go through all these and add THREAD_SAFE where it applies
class DirAccess {
public:
-
enum AccessType {
ACCESS_RESOURCES,
ACCESS_USERDATA,
@@ -48,13 +46,9 @@ public:
ACCESS_MAX
};
-
-
- typedef DirAccess*(*CreateFunc)();
+ typedef DirAccess *(*CreateFunc)();
private:
-
-
AccessType _access_type;
static CreateFunc create_func[ACCESS_MAX]; ///< set this to instance a filesystem object
protected:
@@ -64,45 +58,44 @@ protected:
String fix_path(String p_path) const;
bool next_is_dir;
- template<class T>
- static DirAccess* _create_builtin() {
+ template <class T>
+ static DirAccess *_create_builtin() {
- return memnew( T );
+ return memnew(T);
}
public:
+ virtual Error list_dir_begin() = 0; ///< This starts dir listing
+ virtual String get_next(bool *p_is_dir); // compatibility
+ virtual String get_next() = 0;
+ virtual bool current_is_dir() const = 0;
+ virtual bool current_is_hidden() const = 0;
- virtual Error list_dir_begin()=0; ///< This starts dir listing
- virtual String get_next(bool* p_is_dir); // compatibility
- virtual String get_next()=0;
- virtual bool current_is_dir() const=0;
- virtual bool current_is_hidden() const=0;
-
- virtual void list_dir_end()=0; ///<
+ virtual void list_dir_end() = 0; ///<
- virtual int get_drive_count()=0;
- virtual String get_drive(int p_drive)=0;
+ virtual int get_drive_count() = 0;
+ virtual String get_drive(int p_drive) = 0;
virtual int get_current_drive();
- virtual Error change_dir(String p_dir)=0; ///< can be relative or absolute, return false on success
- virtual String get_current_dir()=0; ///< return current dir location
- virtual Error make_dir(String p_dir)=0;
+ virtual Error change_dir(String p_dir) = 0; ///< can be relative or absolute, return false on success
+ virtual String get_current_dir() = 0; ///< return current dir location
+ virtual Error make_dir(String p_dir) = 0;
virtual Error make_dir_recursive(String p_dir);
virtual Error erase_contents_recursive(); //super dangerous, use with care!
- virtual bool file_exists(String p_file)=0;
- virtual bool dir_exists(String p_dir)=0;
+ virtual bool file_exists(String p_file) = 0;
+ virtual bool dir_exists(String p_dir) = 0;
static bool exists(String p_dir);
- virtual size_t get_space_left()=0;
+ virtual size_t get_space_left() = 0;
- virtual Error copy(String p_from,String p_to);
- virtual Error rename(String p_from, String p_to)=0;
- virtual Error remove(String p_name)=0;
+ virtual Error copy(String p_from, String p_to);
+ virtual Error rename(String p_from, String p_to) = 0;
+ virtual Error remove(String p_name) = 0;
- static String get_full_path(const String& p_path,AccessType p_access);
- static DirAccess *create_for_path(const String& p_path);
+ static String get_full_path(const String &p_path, AccessType p_access);
+ static DirAccess *create_for_path(const String &p_path);
-/*
+ /*
enum DirType {
FILE_TYPE_INVALID,
@@ -114,30 +107,31 @@ public:
*/
static DirAccess *create(AccessType p_access);
- template<class T>
+ template <class T>
static void make_default(AccessType p_access) {
- create_func[p_access]=_create_builtin<T>;
+ create_func[p_access] = _create_builtin<T>;
}
- static DirAccess *open(const String& p_path,Error *r_error=NULL);
+ static DirAccess *open(const String &p_path, Error *r_error = NULL);
DirAccess();
virtual ~DirAccess();
-
};
struct DirAccessRef {
- _FORCE_INLINE_ DirAccess* operator->() {
+ _FORCE_INLINE_ DirAccess *operator->() {
return f;
}
- operator bool() const { return f!=NULL; }
+ operator bool() const { return f != NULL; }
DirAccess *f;
DirAccessRef(DirAccess *fa) { f = fa; }
- ~DirAccessRef() { if (f) memdelete(f); }
+ ~DirAccessRef() {
+ if (f) memdelete(f);
+ }
};
#endif
diff --git a/core/os/file_access.cpp b/core/os/file_access.cpp
index ae592720e8..3aac1f6f21 100644
--- a/core/os/file_access.cpp
+++ b/core/os/file_access.cpp
@@ -27,42 +27,39 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "file_access.h"
-#include "global_config.h"
-#include "os/os.h"
+#include "core/io/file_access_pack.h"
#include "core/io/marshalls.h"
+#include "global_config.h"
#include "io/md5.h"
#include "io/sha256.h"
-#include "core/io/file_access_pack.h"
-
-FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX]={0,0};
+#include "os/os.h"
-FileAccess::FileCloseFailNotify FileAccess::close_fail_notify=NULL;
+FileAccess::CreateFunc FileAccess::create_func[ACCESS_MAX] = { 0, 0 };
+FileAccess::FileCloseFailNotify FileAccess::close_fail_notify = NULL;
-bool FileAccess::backup_save=false;
+bool FileAccess::backup_save = false;
-FileAccess *FileAccess::create(AccessType p_access){
+FileAccess *FileAccess::create(AccessType p_access) {
- ERR_FAIL_COND_V( !create_func, 0 );
- ERR_FAIL_INDEX_V( p_access,ACCESS_MAX, 0 );
+ ERR_FAIL_COND_V(!create_func, 0);
+ ERR_FAIL_INDEX_V(p_access, ACCESS_MAX, 0);
FileAccess *ret = create_func[p_access]();
ret->_set_access_type(p_access);
return ret;
}
-bool FileAccess::exists(const String& p_name) {
+bool FileAccess::exists(const String &p_name) {
if (PackedData::get_singleton()->has_path(p_name))
return true;
- FileAccess *f=open(p_name,READ);
+ FileAccess *f = open(p_name, READ);
if (!f)
return false;
memdelete(f);
return true;
-
-
}
void FileAccess::_set_access_type(AccessType p_access) {
@@ -70,9 +67,9 @@ void FileAccess::_set_access_type(AccessType p_access) {
_access_type = p_access;
};
-FileAccess *FileAccess::create_for_path(const String& p_path) {
+FileAccess *FileAccess::create_for_path(const String &p_path) {
- FileAccess *ret=NULL;
+ FileAccess *ret = NULL;
if (p_path.begins_with("res://")) {
ret = create(ACCESS_RESOURCES);
@@ -86,56 +83,52 @@ FileAccess *FileAccess::create_for_path(const String& p_path) {
}
return ret;
-
-
}
-Error FileAccess::reopen(const String& p_path, int p_mode_flags) {
+Error FileAccess::reopen(const String &p_path, int p_mode_flags) {
return _open(p_path, p_mode_flags);
};
-
-FileAccess *FileAccess::open(const String& p_path, int p_mode_flags, Error *r_error) {
+FileAccess *FileAccess::open(const String &p_path, int p_mode_flags, Error *r_error) {
//try packed data first
- FileAccess *ret=NULL;
- if (!(p_mode_flags&WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) {
+ FileAccess *ret = NULL;
+ if (!(p_mode_flags & WRITE) && PackedData::get_singleton() && !PackedData::get_singleton()->is_disabled()) {
ret = PackedData::get_singleton()->try_open_path(p_path);
if (ret) {
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return ret;
}
}
- ret=create_for_path(p_path);
- Error err = ret->_open(p_path,p_mode_flags);
+ ret = create_for_path(p_path);
+ Error err = ret->_open(p_path, p_mode_flags);
if (r_error)
- *r_error=err;
- if (err!=OK) {
+ *r_error = err;
+ if (err != OK) {
memdelete(ret);
- ret=NULL;
+ ret = NULL;
}
return ret;
}
-
FileAccess::CreateFunc FileAccess::get_create_func(AccessType p_access) {
return create_func[p_access];
};
-String FileAccess::fix_path(const String& p_path) const {
+String FileAccess::fix_path(const String &p_path) const {
//helper used by file accesses that use a single filesystem
String r_path = p_path.replace("\\", "/");
- switch(_access_type) {
+ switch (_access_type) {
case ACCESS_RESOURCES: {
@@ -145,23 +138,21 @@ String FileAccess::fix_path(const String& p_path) const {
String resource_path = GlobalConfig::get_singleton()->get_resource_path();
if (resource_path != "") {
- return r_path.replace("res:/",resource_path);
+ return r_path.replace("res:/", resource_path);
};
return r_path.replace("res://", "");
}
}
-
} break;
case ACCESS_USERDATA: {
-
if (r_path.begins_with("user://")) {
- String data_dir=OS::get_singleton()->get_data_dir();
+ String data_dir = OS::get_singleton()->get_data_dir();
if (data_dir != "") {
- return r_path.replace("user:/",data_dir);
+ return r_path.replace("user:/", data_dir);
};
return r_path.replace("user://", "");
}
@@ -178,63 +169,62 @@ String FileAccess::fix_path(const String& p_path) const {
/* these are all implemented for ease of porting, then can later be optimized */
-uint16_t FileAccess::get_16()const {
+uint16_t FileAccess::get_16() const {
uint16_t res;
- uint8_t a,b;
+ uint8_t a, b;
- a=get_8();
- b=get_8();
+ a = get_8();
+ b = get_8();
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
- res=b;
- res<<=8;
- res|=a;
+ res = b;
+ res <<= 8;
+ res |= a;
return res;
}
-uint32_t FileAccess::get_32() const{
+uint32_t FileAccess::get_32() const {
uint32_t res;
- uint16_t a,b;
+ uint16_t a, b;
- a=get_16();
- b=get_16();
+ a = get_16();
+ b = get_16();
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
- res=b;
- res<<=16;
- res|=a;
+ res = b;
+ res <<= 16;
+ res |= a;
return res;
}
-uint64_t FileAccess::get_64()const {
+uint64_t FileAccess::get_64() const {
uint64_t res;
- uint32_t a,b;
+ uint32_t a, b;
- a=get_32();
- b=get_32();
+ a = get_32();
+ b = get_32();
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
- res=b;
- res<<=32;
- res|=a;
+ res = b;
+ res <<= 32;
+ res |= a;
return res;
-
}
float FileAccess::get_float() const {
@@ -250,7 +240,6 @@ real_t FileAccess::get_real() const {
return get_double();
else
return get_float();
-
}
double FileAccess::get_double() const {
@@ -264,17 +253,17 @@ String FileAccess::get_line() const {
CharString line;
- CharType c=get_8();
+ CharType c = get_8();
- while(!eof_reached()) {
+ while (!eof_reached()) {
- if (c=='\n' || c=='\0') {
+ if (c == '\n' || c == '\0') {
line.push_back(0);
return String::utf8(line.get_data());
- } else if (c!='\r')
+ } else if (c != '\r')
line.push_back(c);
- c=get_8();
+ c = get_8();
}
line.push_back(0);
return String::utf8(line.get_data());
@@ -282,51 +271,48 @@ String FileAccess::get_line() const {
Vector<String> FileAccess::get_csv_line(String delim) const {
- ERR_FAIL_COND_V(delim.length()!=1,Vector<String>());
+ ERR_FAIL_COND_V(delim.length() != 1, Vector<String>());
String l;
- int qc=0;
+ int qc = 0;
do {
- l+=get_line()+"\n";
- qc=0;
- for(int i=0;i<l.length();i++) {
+ l += get_line() + "\n";
+ qc = 0;
+ for (int i = 0; i < l.length(); i++) {
- if (l[i]=='"')
+ if (l[i] == '"')
qc++;
}
+ } while (qc % 2);
- } while (qc%2);
-
- l=l.substr(0, l.length()-1);
+ l = l.substr(0, l.length() - 1);
Vector<String> strings;
- bool in_quote=false;
+ bool in_quote = false;
String current;
- for(int i=0;i<l.length();i++) {
+ for (int i = 0; i < l.length(); i++) {
CharType c = l[i];
- CharType s[2]={0,0};
-
+ CharType s[2] = { 0, 0 };
- if (!in_quote && c==delim[0]) {
+ if (!in_quote && c == delim[0]) {
strings.push_back(current);
- current=String();
- } else if (c=='"') {
- if (l[i+1]=='"') {
- s[0]='"';
- current+=s;
+ current = String();
+ } else if (c == '"') {
+ if (l[i + 1] == '"') {
+ s[0] = '"';
+ current += s;
i++;
} else {
- in_quote=!in_quote;
+ in_quote = !in_quote;
}
} else {
- s[0]=c;
- current+=s;
+ s[0] = c;
+ current += s;
}
-
}
strings.push_back(current);
@@ -334,73 +320,67 @@ Vector<String> FileAccess::get_csv_line(String delim) const {
return strings;
}
+int FileAccess::get_buffer(uint8_t *p_dst, int p_length) const {
-int FileAccess::get_buffer(uint8_t *p_dst,int p_length) const{
-
- int i=0;
- for (i=0; i<p_length && !eof_reached(); i++)
- p_dst[i]=get_8();
+ int i = 0;
+ for (i = 0; i < p_length && !eof_reached(); i++)
+ p_dst[i] = get_8();
return i;
}
void FileAccess::store_16(uint16_t p_dest) {
- uint8_t a,b;
+ uint8_t a, b;
- a=p_dest&0xFF;
- b=p_dest>>8;
+ a = p_dest & 0xFF;
+ b = p_dest >> 8;
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
store_8(a);
store_8(b);
-
}
void FileAccess::store_32(uint32_t p_dest) {
+ uint16_t a, b;
- uint16_t a,b;
-
- a=p_dest&0xFFFF;
- b=p_dest>>16;
+ a = p_dest & 0xFFFF;
+ b = p_dest >> 16;
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
store_16(a);
store_16(b);
-
}
void FileAccess::store_64(uint64_t p_dest) {
- uint32_t a,b;
+ uint32_t a, b;
- a=p_dest&0xFFFFFFFF;
- b=p_dest>>32;
+ a = p_dest & 0xFFFFFFFF;
+ b = p_dest >> 32;
if (endian_swap) {
- SWAP( a,b );
+ SWAP(a, b);
}
store_32(a);
store_32(b);
-
}
void FileAccess::store_real(real_t p_real) {
- if (sizeof(real_t)==4)
+ if (sizeof(real_t) == 4)
store_float(p_real);
else
store_double(p_real);
-
}
void FileAccess::store_float(float p_dest) {
@@ -417,40 +397,39 @@ void FileAccess::store_double(double p_dest) {
store_64(m.l);
};
-uint64_t FileAccess::get_modified_time(const String& p_file) {
+uint64_t FileAccess::get_modified_time(const String &p_file) {
FileAccess *fa = create_for_path(p_file);
- ERR_FAIL_COND_V(!fa,0);
+ ERR_FAIL_COND_V(!fa, 0);
uint64_t mt = fa->_get_modified_time(p_file);
memdelete(fa);
return mt;
}
-void FileAccess::store_string(const String& p_string) {
+void FileAccess::store_string(const String &p_string) {
- if (p_string.length()==0)
+ if (p_string.length() == 0)
return;
- CharString cs=p_string.utf8();
- store_buffer((uint8_t*)&cs[0],cs.length());
-
+ CharString cs = p_string.utf8();
+ store_buffer((uint8_t *)&cs[0], cs.length());
}
-void FileAccess::store_pascal_string(const String& p_string) {
+void FileAccess::store_pascal_string(const String &p_string) {
CharString cs = p_string.utf8();
store_32(cs.length());
- store_buffer((uint8_t*)&cs[0], cs.length());
+ store_buffer((uint8_t *)&cs[0], cs.length());
};
String FileAccess::get_pascal_string() {
uint32_t sl = get_32();
CharString cs;
- cs.resize(sl+1);
- get_buffer((uint8_t*)cs.ptr(),sl);
- cs[sl]=0;
+ cs.resize(sl + 1);
+ get_buffer((uint8_t *)cs.ptr(), sl);
+ cs[sl] = 0;
String ret;
ret.parse_utf8(cs.ptr());
@@ -458,35 +437,32 @@ String FileAccess::get_pascal_string() {
return ret;
};
-
-void FileAccess::store_line(const String& p_line) {
+void FileAccess::store_line(const String &p_line) {
store_string(p_line);
store_8('\n');
}
-void FileAccess::store_buffer(const uint8_t *p_src,int p_length) {
+void FileAccess::store_buffer(const uint8_t *p_src, int p_length) {
- for (int i=0;i<p_length;i++)
+ for (int i = 0; i < p_length; i++)
store_8(p_src[i]);
}
-Vector<uint8_t> FileAccess::get_file_as_array(const String& p_file) {
+Vector<uint8_t> FileAccess::get_file_as_array(const String &p_file) {
- FileAccess *f=FileAccess::open(p_file,READ);
- ERR_FAIL_COND_V(!f,Vector<uint8_t>());
+ FileAccess *f = FileAccess::open(p_file, READ);
+ ERR_FAIL_COND_V(!f, Vector<uint8_t>());
Vector<uint8_t> data;
data.resize(f->get_len());
- f->get_buffer(data.ptr(),data.size());
+ f->get_buffer(data.ptr(), data.size());
memdelete(f);
return data;
-
-
}
-String FileAccess::get_md5(const String& p_file) {
+String FileAccess::get_md5(const String &p_file) {
- FileAccess *f=FileAccess::open(p_file,READ);
+ FileAccess *f = FileAccess::open(p_file, READ);
if (!f)
return String();
@@ -495,32 +471,28 @@ String FileAccess::get_md5(const String& p_file) {
unsigned char step[32768];
- while(true) {
+ while (true) {
- int br = f->get_buffer(step,32768);
- if (br>0) {
+ int br = f->get_buffer(step, 32768);
+ if (br > 0) {
- MD5Update(&md5,step,br);
+ MD5Update(&md5, step, br);
}
if (br < 4096)
break;
-
}
MD5Final(&md5);
String ret = String::md5(md5.digest);
-
-
memdelete(f);
return ret;
-
}
-String FileAccess::get_sha256(const String& p_file) {
+String FileAccess::get_sha256(const String &p_file) {
- FileAccess *f=FileAccess::open(p_file,READ);
+ FileAccess *f = FileAccess::open(p_file, READ);
if (!f)
return String();
@@ -529,16 +501,15 @@ String FileAccess::get_sha256(const String& p_file) {
unsigned char step[32768];
- while(true) {
+ while (true) {
- int br = f->get_buffer(step,32768);
- if (br>0) {
+ int br = f->get_buffer(step, 32768);
+ if (br > 0) {
- sha256_hash(&sha256,step,br);
+ sha256_hash(&sha256, step, br);
}
if (br < 4096)
break;
-
}
unsigned char hash[32];
@@ -547,12 +518,11 @@ String FileAccess::get_sha256(const String& p_file) {
memdelete(f);
return String::hex_encode_buffer(hash, 32);
-
}
FileAccess::FileAccess() {
- endian_swap=false;
- real_is_double=false;
- _access_type=ACCESS_FILESYSTEM;
+ endian_swap = false;
+ real_is_double = false;
+ _access_type = ACCESS_FILESYSTEM;
};
diff --git a/core/os/file_access.h b/core/os/file_access.h
index 7d61099bc2..10d3ffebbb 100644
--- a/core/os/file_access.h
+++ b/core/os/file_access.h
@@ -29,10 +29,10 @@
#ifndef FILE_ACCESS_H
#define FILE_ACCESS_H
+#include "math_defs.h"
+#include "os/memory.h"
#include "typedefs.h"
#include "ustring.h"
-#include "os/memory.h"
-#include "math_defs.h"
/**
* Multi-Platform abstraction for accessing to files.
*/
@@ -47,57 +47,54 @@ public:
ACCESS_MAX
};
- typedef void (*FileCloseFailNotify)(const String&);
+ typedef void (*FileCloseFailNotify)(const String &);
- typedef FileAccess*(*CreateFunc)();
+ typedef FileAccess *(*CreateFunc)();
bool endian_swap;
bool real_is_double;
-protected:
- String fix_path(const String& p_path) const;
- virtual Error _open(const String& p_path, int p_mode_flags)=0; ///< open a file
- virtual uint64_t _get_modified_time(const String& p_file)=0;
+protected:
+ String fix_path(const String &p_path) const;
+ virtual Error _open(const String &p_path, int p_mode_flags) = 0; ///< open a file
+ virtual uint64_t _get_modified_time(const String &p_file) = 0;
static FileCloseFailNotify close_fail_notify;
-private:
+private:
static bool backup_save;
AccessType _access_type;
static CreateFunc create_func[ACCESS_MAX]; /** default file access creation function for a platform */
- template<class T>
- static FileAccess* _create_builtin() {
+ template <class T>
+ static FileAccess *_create_builtin() {
- return memnew( T );
+ return memnew(T);
}
-
-
public:
-
- static void set_file_close_fail_notify_callback(FileCloseFailNotify p_cbk) { close_fail_notify=p_cbk; }
+ static void set_file_close_fail_notify_callback(FileCloseFailNotify p_cbk) { close_fail_notify = p_cbk; }
virtual void _set_access_type(AccessType p_access);
- enum ModeFlags {
+ enum ModeFlags {
- READ=1,
- WRITE=2,
- READ_WRITE=3,
- WRITE_READ=7,
+ READ = 1,
+ WRITE = 2,
+ READ_WRITE = 3,
+ WRITE_READ = 7,
};
- virtual void close()=0; ///< close a file
- virtual bool is_open() const=0; ///< true when file is open
+ virtual void close() = 0; ///< close a file
+ virtual bool is_open() const = 0; ///< true when file is open
- virtual void seek(size_t p_position)=0; ///< seek to a given position
- virtual void seek_end(int64_t p_position=0)=0; ///< seek from the end of file
- virtual size_t get_pos() const=0; ///< get position in the file
- virtual size_t get_len() const=0; ///< get size of the file
+ virtual void seek(size_t p_position) = 0; ///< seek to a given position
+ virtual void seek_end(int64_t p_position = 0) = 0; ///< seek from the end of file
+ virtual size_t get_pos() const = 0; ///< get position in the file
+ virtual size_t get_len() const = 0; ///< get size of the file
- virtual bool eof_reached() const=0; ///< reading passed EOF
+ virtual bool eof_reached() const = 0; ///< reading passed EOF
- virtual uint8_t get_8() const=0; ///< get a byte
+ virtual uint8_t get_8() const = 0; ///< get a byte
virtual uint16_t get_16() const; ///< get 16 bits uint
virtual uint32_t get_32() const; ///< get 32 bits uint
virtual uint64_t get_64() const; ///< get 64 bits uint
@@ -106,21 +103,21 @@ public:
virtual double get_double() const;
virtual real_t get_real() const;
- virtual int get_buffer(uint8_t *p_dst,int p_length) const; ///< get an array of bytes
+ virtual int get_buffer(uint8_t *p_dst, int p_length) const; ///< get an array of bytes
virtual String get_line() const;
- virtual Vector<String> get_csv_line(String delim=",") const;
+ virtual Vector<String> get_csv_line(String delim = ",") const;
/**< use this for files WRITTEN in _big_ endian machines (ie, amiga/mac)
* It's not about the current CPU type but file formats.
* this flags get reset to false (little endian) on each open
*/
- virtual void set_endian_swap(bool p_swap) { endian_swap=p_swap; }
+ virtual void set_endian_swap(bool p_swap) { endian_swap = p_swap; }
inline bool get_endian_swap() const { return endian_swap; }
- virtual Error get_error() const=0; ///< get last error
+ virtual Error get_error() const = 0; ///< get last error
- virtual void store_8(uint8_t p_dest)=0; ///< store a byte
+ virtual void store_8(uint8_t p_dest) = 0; ///< store a byte
virtual void store_16(uint16_t p_dest); ///< store 16 bits uint
virtual void store_32(uint32_t p_dest); ///< store 32 bits uint
virtual void store_64(uint64_t p_dest); ///< store 64 bits uint
@@ -129,58 +126,56 @@ public:
virtual void store_double(double p_dest);
virtual void store_real(real_t p_real);
- virtual void store_string(const String& p_string);
- virtual void store_line(const String& p_string);
+ virtual void store_string(const String &p_string);
+ virtual void store_line(const String &p_string);
- virtual void store_pascal_string(const String& p_string);
+ virtual void store_pascal_string(const String &p_string);
virtual String get_pascal_string();
- virtual void store_buffer(const uint8_t *p_src,int p_length); ///< store an array of bytes
+ virtual void store_buffer(const uint8_t *p_src, int p_length); ///< store an array of bytes
- virtual bool file_exists(const String& p_name)=0; ///< return true if a file exists
+ virtual bool file_exists(const String &p_name) = 0; ///< return true if a file exists
- virtual Error reopen(const String& p_path, int p_mode_flags); ///< does not change the AccessType
+ virtual Error reopen(const String &p_path, int p_mode_flags); ///< does not change the AccessType
static FileAccess *create(AccessType p_access); /// Create a file access (for the current platform) this is the only portable way of accessing files.
- static FileAccess *create_for_path(const String& p_path);
- static FileAccess *open(const String& p_path, int p_mode_flags, Error *r_error=NULL); /// Create a file access (for the current platform) this is the only portable way of accessing files.
+ static FileAccess *create_for_path(const String &p_path);
+ static FileAccess *open(const String &p_path, int p_mode_flags, Error *r_error = NULL); /// Create a file access (for the current platform) this is the only portable way of accessing files.
static CreateFunc get_create_func(AccessType p_access);
- static bool exists(const String& p_name); ///< return true if a file exists
- static uint64_t get_modified_time(const String& p_file);
-
+ static bool exists(const String &p_name); ///< return true if a file exists
+ static uint64_t get_modified_time(const String &p_file);
- static void set_backup_save(bool p_enable) { backup_save=p_enable; };
+ static void set_backup_save(bool p_enable) { backup_save = p_enable; };
static bool is_backup_save_enabled() { return backup_save; };
- static String get_md5(const String& p_file);
- static String get_sha256(const String& p_file);
+ static String get_md5(const String &p_file);
+ static String get_sha256(const String &p_file);
- static Vector<uint8_t> get_file_as_array(const String& p_path);
+ static Vector<uint8_t> get_file_as_array(const String &p_path);
-
- template<class T>
+ template <class T>
static void make_default(AccessType p_access) {
- create_func[p_access]=_create_builtin<T>;
+ create_func[p_access] = _create_builtin<T>;
}
FileAccess();
- virtual ~FileAccess(){}
-
+ virtual ~FileAccess() {}
};
-
struct FileAccessRef {
- _FORCE_INLINE_ FileAccess* operator->() {
+ _FORCE_INLINE_ FileAccess *operator->() {
return f;
}
- operator bool() const { return f!=NULL; }
+ operator bool() const { return f != NULL; }
FileAccess *f;
FileAccessRef(FileAccess *fa) { f = fa; }
- ~FileAccessRef() { if (f) memdelete(f); }
+ ~FileAccessRef() {
+ if (f) memdelete(f);
+ }
};
#endif
diff --git a/core/os/input.cpp b/core/os/input.cpp
index 34883e63ba..63efbe4d11 100644
--- a/core/os/input.cpp
+++ b/core/os/input.cpp
@@ -27,10 +27,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "input.h"
+#include "global_config.h"
#include "input_map.h"
#include "os/os.h"
-#include "global_config.h"
-Input *Input::singleton=NULL;
+Input *Input::singleton = NULL;
Input *Input::get_singleton() {
@@ -38,7 +38,7 @@ Input *Input::get_singleton() {
}
void Input::set_mouse_mode(MouseMode p_mode) {
- ERR_FAIL_INDEX(p_mode,4);
+ ERR_FAIL_INDEX(p_mode, 4);
OS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode);
}
@@ -49,19 +49,19 @@ Input::MouseMode Input::get_mouse_mode() const {
void Input::_bind_methods() {
- ClassDB::bind_method(D_METHOD("is_key_pressed","scancode"),&Input::is_key_pressed);
- ClassDB::bind_method(D_METHOD("is_mouse_button_pressed","button"),&Input::is_mouse_button_pressed);
- ClassDB::bind_method(D_METHOD("is_joy_button_pressed","device","button"),&Input::is_joy_button_pressed);
- ClassDB::bind_method(D_METHOD("is_action_pressed","action"),&Input::is_action_pressed);
- ClassDB::bind_method(D_METHOD("is_action_just_pressed","action"),&Input::is_action_just_pressed);
- ClassDB::bind_method(D_METHOD("is_action_just_released","action"),&Input::is_action_just_released);
- ClassDB::bind_method(D_METHOD("add_joy_mapping","mapping", "update_existing"),&Input::add_joy_mapping, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("remove_joy_mapping","guid"),&Input::remove_joy_mapping);
- ClassDB::bind_method(D_METHOD("is_joy_known","device"),&Input::is_joy_known);
- ClassDB::bind_method(D_METHOD("get_joy_axis","device","axis"),&Input::get_joy_axis);
- ClassDB::bind_method(D_METHOD("get_joy_name","device"),&Input::get_joy_name);
- ClassDB::bind_method(D_METHOD("get_joy_guid","device"),&Input::get_joy_guid);
- ClassDB::bind_method(D_METHOD("get_connected_joypads"),&Input::get_connected_joypads);
+ ClassDB::bind_method(D_METHOD("is_key_pressed", "scancode"), &Input::is_key_pressed);
+ ClassDB::bind_method(D_METHOD("is_mouse_button_pressed", "button"), &Input::is_mouse_button_pressed);
+ ClassDB::bind_method(D_METHOD("is_joy_button_pressed", "device", "button"), &Input::is_joy_button_pressed);
+ ClassDB::bind_method(D_METHOD("is_action_pressed", "action"), &Input::is_action_pressed);
+ ClassDB::bind_method(D_METHOD("is_action_just_pressed", "action"), &Input::is_action_just_pressed);
+ ClassDB::bind_method(D_METHOD("is_action_just_released", "action"), &Input::is_action_just_released);
+ ClassDB::bind_method(D_METHOD("add_joy_mapping", "mapping", "update_existing"), &Input::add_joy_mapping, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("remove_joy_mapping", "guid"), &Input::remove_joy_mapping);
+ ClassDB::bind_method(D_METHOD("is_joy_known", "device"), &Input::is_joy_known);
+ ClassDB::bind_method(D_METHOD("get_joy_axis", "device", "axis"), &Input::get_joy_axis);
+ ClassDB::bind_method(D_METHOD("get_joy_name", "device"), &Input::get_joy_name);
+ ClassDB::bind_method(D_METHOD("get_joy_guid", "device"), &Input::get_joy_guid);
+ ClassDB::bind_method(D_METHOD("get_connected_joypads"), &Input::get_connected_joypads);
ClassDB::bind_method(D_METHOD("get_joy_vibration_strength", "device"), &Input::get_joy_vibration_strength);
ClassDB::bind_method(D_METHOD("get_joy_vibration_duration", "device"), &Input::get_joy_vibration_duration);
ClassDB::bind_method(D_METHOD("get_joy_button_string", "button_index"), &Input::get_joy_button_string);
@@ -70,57 +70,53 @@ void Input::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_joy_axis_index_from_string", "axis"), &Input::get_joy_axis_index_from_string);
ClassDB::bind_method(D_METHOD("start_joy_vibration", "device", "weak_magnitude", "strong_magnitude", "duration"), &Input::start_joy_vibration, DEFVAL(0));
ClassDB::bind_method(D_METHOD("stop_joy_vibration", "device"), &Input::stop_joy_vibration);
- ClassDB::bind_method(D_METHOD("get_gravity"),&Input::get_gravity);
- ClassDB::bind_method(D_METHOD("get_accelerometer"),&Input::get_accelerometer);
- ClassDB::bind_method(D_METHOD("get_magnetometer"),&Input::get_magnetometer);
- ClassDB::bind_method(D_METHOD("get_gyroscope"),&Input::get_gyroscope);
+ ClassDB::bind_method(D_METHOD("get_gravity"), &Input::get_gravity);
+ ClassDB::bind_method(D_METHOD("get_accelerometer"), &Input::get_accelerometer);
+ ClassDB::bind_method(D_METHOD("get_magnetometer"), &Input::get_magnetometer);
+ ClassDB::bind_method(D_METHOD("get_gyroscope"), &Input::get_gyroscope);
//ClassDB::bind_method(D_METHOD("get_mouse_pos"),&Input::get_mouse_pos); - this is not the function you want
- ClassDB::bind_method(D_METHOD("get_last_mouse_speed"),&Input::get_last_mouse_speed);
- ClassDB::bind_method(D_METHOD("get_mouse_button_mask"),&Input::get_mouse_button_mask);
- ClassDB::bind_method(D_METHOD("set_mouse_mode","mode"),&Input::set_mouse_mode);
- ClassDB::bind_method(D_METHOD("get_mouse_mode"),&Input::get_mouse_mode);
- ClassDB::bind_method(D_METHOD("warp_mouse_pos","to"),&Input::warp_mouse_pos);
- ClassDB::bind_method(D_METHOD("action_press","action"),&Input::action_press);
- ClassDB::bind_method(D_METHOD("action_release","action"),&Input::action_release);
- ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor","image:Texture","hotspot"),&Input::set_custom_mouse_cursor,DEFVAL(Vector2()));
-
- BIND_CONSTANT( MOUSE_MODE_VISIBLE );
- BIND_CONSTANT( MOUSE_MODE_HIDDEN );
- BIND_CONSTANT( MOUSE_MODE_CAPTURED );
- BIND_CONSTANT( MOUSE_MODE_CONFINED );
-
- ADD_SIGNAL( MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected")) );
+ ClassDB::bind_method(D_METHOD("get_last_mouse_speed"), &Input::get_last_mouse_speed);
+ ClassDB::bind_method(D_METHOD("get_mouse_button_mask"), &Input::get_mouse_button_mask);
+ ClassDB::bind_method(D_METHOD("set_mouse_mode", "mode"), &Input::set_mouse_mode);
+ ClassDB::bind_method(D_METHOD("get_mouse_mode"), &Input::get_mouse_mode);
+ ClassDB::bind_method(D_METHOD("warp_mouse_pos", "to"), &Input::warp_mouse_pos);
+ ClassDB::bind_method(D_METHOD("action_press", "action"), &Input::action_press);
+ ClassDB::bind_method(D_METHOD("action_release", "action"), &Input::action_release);
+ ClassDB::bind_method(D_METHOD("set_custom_mouse_cursor", "image:Texture", "hotspot"), &Input::set_custom_mouse_cursor, DEFVAL(Vector2()));
+
+ BIND_CONSTANT(MOUSE_MODE_VISIBLE);
+ BIND_CONSTANT(MOUSE_MODE_HIDDEN);
+ BIND_CONSTANT(MOUSE_MODE_CAPTURED);
+ BIND_CONSTANT(MOUSE_MODE_CONFINED);
+
+ ADD_SIGNAL(MethodInfo("joy_connection_changed", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "connected")));
}
-void Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
+void Input::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
#ifdef TOOLS_ENABLED
- String pf=p_function;
- if (p_idx==0 && (pf=="is_action_pressed" || pf=="action_press" || pf=="action_release" || pf=="is_action_just_pressed" || pf=="is_action_just_released")) {
+ String pf = p_function;
+ if (p_idx == 0 && (pf == "is_action_pressed" || pf == "action_press" || pf == "action_release" || pf == "is_action_just_pressed" || pf == "is_action_just_released")) {
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
- r_options->push_back("\""+name+"\"");
-
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
+ r_options->push_back("\"" + name + "\"");
}
}
#endif
-
}
Input::Input() {
- singleton=this;
+ singleton = this;
}
-
//////////////////////////////////////////////////////////
-
diff --git a/core/os/input.h b/core/os/input.h
index 2cea154a50..86755e632c 100644
--- a/core/os/input.h
+++ b/core/os/input.h
@@ -30,20 +30,19 @@
#define INPUT_H
#include "object.h"
-#include "os/thread_safe.h"
#include "os/main_loop.h"
+#include "os/thread_safe.h"
class Input : public Object {
- GDCLASS( Input, Object );
+ GDCLASS(Input, Object);
static Input *singleton;
protected:
-
static void _bind_methods();
-public:
+public:
enum MouseMode {
MOUSE_MODE_VISIBLE,
MOUSE_MODE_HIDDEN,
@@ -56,57 +55,56 @@ public:
static Input *get_singleton();
- virtual bool is_key_pressed(int p_scancode) const=0;
- virtual bool is_mouse_button_pressed(int p_button) const=0;
- virtual bool is_joy_button_pressed(int p_device, int p_button) const=0;
- virtual bool is_action_pressed(const StringName& p_action) const=0;
- virtual bool is_action_just_pressed(const StringName& p_action) const=0;
- virtual bool is_action_just_released(const StringName& p_action) const=0;
-
- virtual float get_joy_axis(int p_device,int p_axis) const=0;
- virtual String get_joy_name(int p_idx)=0;
- virtual Array get_connected_joypads()=0;
- virtual void joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid)=0;
- virtual void add_joy_mapping(String p_mapping, bool p_update_existing=false)=0;
- virtual void remove_joy_mapping(String p_guid)=0;
- virtual bool is_joy_known(int p_device)=0;
- virtual String get_joy_guid(int p_device) const=0;
- virtual Vector2 get_joy_vibration_strength(int p_device)=0;
- virtual float get_joy_vibration_duration(int p_device)=0;
- virtual uint64_t get_joy_vibration_timestamp(int p_device)=0;
- virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration=0)=0;
- virtual void stop_joy_vibration(int p_device)=0;
-
- virtual Point2 get_mouse_pos() const=0;
- virtual Point2 get_last_mouse_speed() const=0;
- virtual int get_mouse_button_mask() const=0;
-
- virtual void warp_mouse_pos(const Vector2& p_to)=0;
-
- virtual Vector3 get_gravity() const=0;
- virtual Vector3 get_accelerometer() const=0;
- virtual Vector3 get_magnetometer() const=0;
- virtual Vector3 get_gyroscope() const=0;
-
- virtual void action_press(const StringName& p_action)=0;
- virtual void action_release(const StringName& p_action)=0;
-
- void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
-
- virtual bool is_emulating_touchscreen() const=0;
-
- virtual void set_custom_mouse_cursor(const RES& p_cursor,const Vector2& p_hotspot=Vector2())=0;
- virtual void set_mouse_in_window(bool p_in_window)=0;
-
- virtual String get_joy_button_string(int p_button)=0;
- virtual String get_joy_axis_string(int p_axis)=0;
- virtual int get_joy_button_index_from_string(String p_button)=0;
- virtual int get_joy_axis_index_from_string(String p_axis)=0;
+ virtual bool is_key_pressed(int p_scancode) const = 0;
+ virtual bool is_mouse_button_pressed(int p_button) const = 0;
+ virtual bool is_joy_button_pressed(int p_device, int p_button) const = 0;
+ virtual bool is_action_pressed(const StringName &p_action) const = 0;
+ virtual bool is_action_just_pressed(const StringName &p_action) const = 0;
+ virtual bool is_action_just_released(const StringName &p_action) const = 0;
+
+ virtual float get_joy_axis(int p_device, int p_axis) const = 0;
+ virtual String get_joy_name(int p_idx) = 0;
+ virtual Array get_connected_joypads() = 0;
+ virtual void joy_connection_changed(int p_idx, bool p_connected, String p_name, String p_guid) = 0;
+ virtual void add_joy_mapping(String p_mapping, bool p_update_existing = false) = 0;
+ virtual void remove_joy_mapping(String p_guid) = 0;
+ virtual bool is_joy_known(int p_device) = 0;
+ virtual String get_joy_guid(int p_device) const = 0;
+ virtual Vector2 get_joy_vibration_strength(int p_device) = 0;
+ virtual float get_joy_vibration_duration(int p_device) = 0;
+ virtual uint64_t get_joy_vibration_timestamp(int p_device) = 0;
+ virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration = 0) = 0;
+ virtual void stop_joy_vibration(int p_device) = 0;
+
+ virtual Point2 get_mouse_pos() const = 0;
+ virtual Point2 get_last_mouse_speed() const = 0;
+ virtual int get_mouse_button_mask() const = 0;
+
+ virtual void warp_mouse_pos(const Vector2 &p_to) = 0;
+
+ virtual Vector3 get_gravity() const = 0;
+ virtual Vector3 get_accelerometer() const = 0;
+ virtual Vector3 get_magnetometer() const = 0;
+ virtual Vector3 get_gyroscope() const = 0;
+
+ virtual void action_press(const StringName &p_action) = 0;
+ virtual void action_release(const StringName &p_action) = 0;
+
+ void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
+
+ virtual bool is_emulating_touchscreen() const = 0;
+
+ virtual void set_custom_mouse_cursor(const RES &p_cursor, const Vector2 &p_hotspot = Vector2()) = 0;
+ virtual void set_mouse_in_window(bool p_in_window) = 0;
+
+ virtual String get_joy_button_string(int p_button) = 0;
+ virtual String get_joy_axis_string(int p_axis) = 0;
+ virtual int get_joy_button_index_from_string(String p_button) = 0;
+ virtual int get_joy_axis_index_from_string(String p_axis) = 0;
Input();
};
VARIANT_ENUM_CAST(Input::MouseMode);
-
#endif // INPUT_H
diff --git a/core/os/input_event.cpp b/core/os/input_event.cpp
index 4ef99558ad..ebb1f4ed01 100644
--- a/core/os/input_event.cpp
+++ b/core/os/input_event.cpp
@@ -34,11 +34,11 @@
*/
bool InputEvent::operator==(const InputEvent &p_event) const {
- if (type != p_event.type){
+ if (type != p_event.type) {
return false;
}
- switch(type) {
+ switch (type) {
/** Current clang-format style doesn't play well with the aligned return values of that switch. */
/* clang-format off */
case NONE:
@@ -91,9 +91,9 @@ bool InputEvent::operator==(const InputEvent &p_event) const {
}
InputEvent::operator String() const {
- String str="Device "+itos(device)+" ID "+itos(ID)+" ";
+ String str = "Device " + itos(device) + " ID " + itos(ID) + " ";
- switch(type) {
+ switch (type) {
case NONE: {
@@ -101,108 +101,107 @@ InputEvent::operator String() const {
} break;
case KEY: {
- str+= "Event: Key ";
- str=str+"Unicode: "+String::chr(key.unicode)+" Scan: "+itos( key.scancode )+" Echo: "+String(key.echo?"True":"False")+" Pressed"+String(key.pressed?"True":"False")+" Mod: ";
+ str += "Event: Key ";
+ str = str + "Unicode: " + String::chr(key.unicode) + " Scan: " + itos(key.scancode) + " Echo: " + String(key.echo ? "True" : "False") + " Pressed" + String(key.pressed ? "True" : "False") + " Mod: ";
if (key.mod.shift)
- str+="S";
+ str += "S";
if (key.mod.control)
- str+="C";
+ str += "C";
if (key.mod.alt)
- str+="A";
+ str += "A";
if (key.mod.meta)
- str+="M";
+ str += "M";
return str;
} break;
case MOUSE_MOTION: {
- str+= "Event: Motion ";
- str=str+" Pos: " +itos(mouse_motion.x)+","+itos(mouse_motion.y)+" Rel: "+itos(mouse_motion.relative_x)+","+itos(mouse_motion.relative_y)+" Mask: ";
- for (int i=0;i<8;i++) {
+ str += "Event: Motion ";
+ str = str + " Pos: " + itos(mouse_motion.x) + "," + itos(mouse_motion.y) + " Rel: " + itos(mouse_motion.relative_x) + "," + itos(mouse_motion.relative_y) + " Mask: ";
+ for (int i = 0; i < 8; i++) {
- if ((1<<i)&mouse_motion.button_mask)
- str+=itos(i+1);
+ if ((1 << i) & mouse_motion.button_mask)
+ str += itos(i + 1);
}
- str+=" Mod: ";
+ str += " Mod: ";
if (key.mod.shift)
- str+="S";
+ str += "S";
if (key.mod.control)
- str+="C";
+ str += "C";
if (key.mod.alt)
- str+="A";
+ str += "A";
if (key.mod.meta)
- str+="M";
+ str += "M";
return str;
} break;
case MOUSE_BUTTON: {
- str+= "Event: Button ";
- str=str+"Pressed: "+itos(mouse_button.pressed)+" Pos: " +itos(mouse_button.x)+","+itos(mouse_button.y)+" Button: "+itos(mouse_button.button_index)+" Mask: ";
- for (int i=0;i<8;i++) {
+ str += "Event: Button ";
+ str = str + "Pressed: " + itos(mouse_button.pressed) + " Pos: " + itos(mouse_button.x) + "," + itos(mouse_button.y) + " Button: " + itos(mouse_button.button_index) + " Mask: ";
+ for (int i = 0; i < 8; i++) {
- if ((1<<i)&mouse_button.button_mask)
- str+=itos(i+1);
+ if ((1 << i) & mouse_button.button_mask)
+ str += itos(i + 1);
}
- str+=" Mod: ";
+ str += " Mod: ";
if (key.mod.shift)
- str+="S";
+ str += "S";
if (key.mod.control)
- str+="C";
+ str += "C";
if (key.mod.alt)
- str+="A";
+ str += "A";
if (key.mod.meta)
- str+="M";
+ str += "M";
- str+=String(" DoubleClick: ")+(mouse_button.doubleclick?"Yes":"No");
+ str += String(" DoubleClick: ") + (mouse_button.doubleclick ? "Yes" : "No");
return str;
} break;
case JOYPAD_MOTION: {
- str+= "Event: JoypadMotion ";
- str=str+"Axis: "+itos(joy_motion.axis)+" Value: " +rtos(joy_motion.axis_value);
+ str += "Event: JoypadMotion ";
+ str = str + "Axis: " + itos(joy_motion.axis) + " Value: " + rtos(joy_motion.axis_value);
return str;
} break;
case JOYPAD_BUTTON: {
- str+= "Event: JoypadButton ";
- str=str+"Pressed: "+itos(joy_button.pressed)+" Index: " +itos(joy_button.button_index)+" pressure "+rtos(joy_button.pressure);
+ str += "Event: JoypadButton ";
+ str = str + "Pressed: " + itos(joy_button.pressed) + " Index: " + itos(joy_button.button_index) + " pressure " + rtos(joy_button.pressure);
return str;
} break;
case SCREEN_TOUCH: {
- str+= "Event: ScreenTouch ";
- str=str+"Pressed: "+itos(screen_touch.pressed)+" Index: " +itos(screen_touch.index)+" pos "+rtos(screen_touch.x)+","+rtos(screen_touch.y);
+ str += "Event: ScreenTouch ";
+ str = str + "Pressed: " + itos(screen_touch.pressed) + " Index: " + itos(screen_touch.index) + " pos " + rtos(screen_touch.x) + "," + rtos(screen_touch.y);
return str;
} break;
case SCREEN_DRAG: {
- str+= "Event: ScreenDrag ";
- str=str+" Index: " +itos(screen_drag.index)+" pos "+rtos(screen_drag.x)+","+rtos(screen_drag.y);
+ str += "Event: ScreenDrag ";
+ str = str + " Index: " + itos(screen_drag.index) + " pos " + rtos(screen_drag.x) + "," + rtos(screen_drag.y);
return str;
} break;
case ACTION: {
- str+= "Event: Action: "+InputMap::get_singleton()->get_action_from_id(action.action)+" Pressed: "+itos(action.pressed);
+ str += "Event: Action: " + InputMap::get_singleton()->get_action_from_id(action.action) + " Pressed: " + itos(action.pressed);
return str;
} break;
-
}
return "";
}
-void InputEvent::set_as_action(const String& p_action, bool p_pressed) {
+void InputEvent::set_as_action(const String &p_action, bool p_pressed) {
- type=ACTION;
- action.action=InputMap::get_singleton()->get_action_id(p_action);
- action.pressed=p_pressed;
+ type = ACTION;
+ action.action = InputMap::get_singleton()->get_action_id(p_action);
+ action.pressed = p_pressed;
}
bool InputEvent::is_pressed() const {
- switch(type) {
+ switch (type) {
case KEY: return key.pressed;
case MOUSE_BUTTON: return mouse_button.pressed;
@@ -218,93 +217,89 @@ bool InputEvent::is_pressed() const {
bool InputEvent::is_echo() const {
- return (type==KEY && key.echo);
+ return (type == KEY && key.echo);
}
-bool InputEvent::is_action(const String& p_action) const {
+bool InputEvent::is_action(const String &p_action) const {
- return InputMap::get_singleton()->event_is_action(*this,p_action);
+ return InputMap::get_singleton()->event_is_action(*this, p_action);
}
-bool InputEvent::is_action_pressed(const String& p_action) const {
+bool InputEvent::is_action_pressed(const String &p_action) const {
return is_action(p_action) && is_pressed() && !is_echo();
}
-bool InputEvent::is_action_released(const String& p_action) const {
+bool InputEvent::is_action_released(const String &p_action) const {
return is_action(p_action) && !is_pressed();
}
uint32_t InputEventKey::get_scancode_with_modifiers() const {
- uint32_t sc=scancode;
+ uint32_t sc = scancode;
if (mod.control)
- sc|=KEY_MASK_CTRL;
+ sc |= KEY_MASK_CTRL;
if (mod.alt)
- sc|=KEY_MASK_ALT;
+ sc |= KEY_MASK_ALT;
if (mod.shift)
- sc|=KEY_MASK_SHIFT;
+ sc |= KEY_MASK_SHIFT;
if (mod.meta)
- sc|=KEY_MASK_META;
+ sc |= KEY_MASK_META;
return sc;
-
}
-InputEvent InputEvent::xform_by(const Transform2D& p_xform) const {
-
+InputEvent InputEvent::xform_by(const Transform2D &p_xform) const {
- InputEvent ev=*this;
+ InputEvent ev = *this;
- switch(ev.type) {
+ switch (ev.type) {
case InputEvent::MOUSE_BUTTON: {
- Vector2 g = p_xform.xform(Vector2(ev.mouse_button.global_x,ev.mouse_button.global_y));
- Vector2 l = p_xform.xform(Vector2(ev.mouse_button.x,ev.mouse_button.y));
- ev.mouse_button.x=l.x;
- ev.mouse_button.y=l.y;
- ev.mouse_button.global_x=g.x;
- ev.mouse_button.global_y=g.y;
+ Vector2 g = p_xform.xform(Vector2(ev.mouse_button.global_x, ev.mouse_button.global_y));
+ Vector2 l = p_xform.xform(Vector2(ev.mouse_button.x, ev.mouse_button.y));
+ ev.mouse_button.x = l.x;
+ ev.mouse_button.y = l.y;
+ ev.mouse_button.global_x = g.x;
+ ev.mouse_button.global_y = g.y;
} break;
case InputEvent::MOUSE_MOTION: {
- Vector2 g = p_xform.xform(Vector2(ev.mouse_motion.global_x,ev.mouse_motion.global_y));
- Vector2 l = p_xform.xform(Vector2(ev.mouse_motion.x,ev.mouse_motion.y));
- Vector2 r = p_xform.basis_xform(Vector2(ev.mouse_motion.relative_x,ev.mouse_motion.relative_y));
- Vector2 s = p_xform.basis_xform(Vector2(ev.mouse_motion.speed_x,ev.mouse_motion.speed_y));
- ev.mouse_motion.x=l.x;
- ev.mouse_motion.y=l.y;
- ev.mouse_motion.global_x=g.x;
- ev.mouse_motion.global_y=g.y;
- ev.mouse_motion.relative_x=r.x;
- ev.mouse_motion.relative_y=r.y;
- ev.mouse_motion.speed_x=s.x;
- ev.mouse_motion.speed_y=s.y;
+ Vector2 g = p_xform.xform(Vector2(ev.mouse_motion.global_x, ev.mouse_motion.global_y));
+ Vector2 l = p_xform.xform(Vector2(ev.mouse_motion.x, ev.mouse_motion.y));
+ Vector2 r = p_xform.basis_xform(Vector2(ev.mouse_motion.relative_x, ev.mouse_motion.relative_y));
+ Vector2 s = p_xform.basis_xform(Vector2(ev.mouse_motion.speed_x, ev.mouse_motion.speed_y));
+ ev.mouse_motion.x = l.x;
+ ev.mouse_motion.y = l.y;
+ ev.mouse_motion.global_x = g.x;
+ ev.mouse_motion.global_y = g.y;
+ ev.mouse_motion.relative_x = r.x;
+ ev.mouse_motion.relative_y = r.y;
+ ev.mouse_motion.speed_x = s.x;
+ ev.mouse_motion.speed_y = s.y;
} break;
case InputEvent::SCREEN_TOUCH: {
-
- Vector2 t = p_xform.xform(Vector2(ev.screen_touch.x,ev.screen_touch.y));
- ev.screen_touch.x=t.x;
- ev.screen_touch.y=t.y;
+ Vector2 t = p_xform.xform(Vector2(ev.screen_touch.x, ev.screen_touch.y));
+ ev.screen_touch.x = t.x;
+ ev.screen_touch.y = t.y;
} break;
case InputEvent::SCREEN_DRAG: {
-
- Vector2 t = p_xform.xform(Vector2(ev.screen_drag.x,ev.screen_drag.y));
- Vector2 r = p_xform.basis_xform(Vector2(ev.screen_drag.relative_x,ev.screen_drag.relative_y));
- Vector2 s = p_xform.basis_xform(Vector2(ev.screen_drag.speed_x,ev.screen_drag.speed_y));
- ev.screen_drag.x=t.x;
- ev.screen_drag.y=t.y;
- ev.screen_drag.relative_x=r.x;
- ev.screen_drag.relative_y=r.y;
- ev.screen_drag.speed_x=s.x;
- ev.screen_drag.speed_y=s.y;
+ Vector2 t = p_xform.xform(Vector2(ev.screen_drag.x, ev.screen_drag.y));
+ Vector2 r = p_xform.basis_xform(Vector2(ev.screen_drag.relative_x, ev.screen_drag.relative_y));
+ Vector2 s = p_xform.basis_xform(Vector2(ev.screen_drag.speed_x, ev.screen_drag.speed_y));
+ ev.screen_drag.x = t.x;
+ ev.screen_drag.y = t.y;
+ ev.screen_drag.relative_x = r.x;
+ ev.screen_drag.relative_y = r.y;
+ ev.screen_drag.speed_x = s.x;
+ ev.screen_drag.speed_y = s.y;
} break;
}
diff --git a/core/os/input_event.h b/core/os/input_event.h
index 1af4ef20c2..fd3f8c4cec 100644
--- a/core/os/input_event.h
+++ b/core/os/input_event.h
@@ -29,33 +29,30 @@
#ifndef INPUT_EVENT_H
#define INPUT_EVENT_H
-
-#include "typedefs.h"
+#include "math_2d.h"
#include "os/copymem.h"
+#include "typedefs.h"
#include "ustring.h"
-#include "math_2d.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
/**
* Input Event classes. These are used in the main loop.
* The events are pretty obvious.
*/
enum {
- BUTTON_LEFT=1,
- BUTTON_RIGHT=2,
- BUTTON_MIDDLE=3,
- BUTTON_WHEEL_UP=4,
- BUTTON_WHEEL_DOWN=5,
- BUTTON_WHEEL_LEFT=6,
- BUTTON_WHEEL_RIGHT=7,
- BUTTON_MASK_LEFT=(1<<(BUTTON_LEFT-1)),
- BUTTON_MASK_RIGHT=(1<<(BUTTON_RIGHT-1)),
- BUTTON_MASK_MIDDLE=(1<<(BUTTON_MIDDLE-1)),
+ BUTTON_LEFT = 1,
+ BUTTON_RIGHT = 2,
+ BUTTON_MIDDLE = 3,
+ BUTTON_WHEEL_UP = 4,
+ BUTTON_WHEEL_DOWN = 5,
+ BUTTON_WHEEL_LEFT = 6,
+ BUTTON_WHEEL_RIGHT = 7,
+ BUTTON_MASK_LEFT = (1 << (BUTTON_LEFT - 1)),
+ BUTTON_MASK_RIGHT = (1 << (BUTTON_RIGHT - 1)),
+ BUTTON_MASK_MIDDLE = (1 << (BUTTON_MIDDLE - 1)),
};
@@ -99,20 +96,20 @@ enum {
JOY_SNES_Y = JOY_BUTTON_2,
JOY_SNES_X = JOY_BUTTON_3,
- JOY_SONY_CIRCLE=JOY_SNES_A,
- JOY_SONY_X=JOY_SNES_B,
- JOY_SONY_SQUARE=JOY_SNES_Y,
- JOY_SONY_TRIANGLE=JOY_SNES_X,
+ JOY_SONY_CIRCLE = JOY_SNES_A,
+ JOY_SONY_X = JOY_SNES_B,
+ JOY_SONY_SQUARE = JOY_SNES_Y,
+ JOY_SONY_TRIANGLE = JOY_SNES_X,
- JOY_SEGA_B=JOY_SNES_A,
- JOY_SEGA_A=JOY_SNES_B,
- JOY_SEGA_X=JOY_SNES_Y,
- JOY_SEGA_Y=JOY_SNES_X,
+ JOY_SEGA_B = JOY_SNES_A,
+ JOY_SEGA_A = JOY_SNES_B,
+ JOY_SEGA_X = JOY_SNES_Y,
+ JOY_SEGA_Y = JOY_SNES_X,
- JOY_XBOX_B=JOY_SEGA_B,
- JOY_XBOX_A=JOY_SEGA_A,
- JOY_XBOX_X=JOY_SEGA_X,
- JOY_XBOX_Y=JOY_SEGA_Y,
+ JOY_XBOX_B = JOY_SEGA_B,
+ JOY_XBOX_A = JOY_SEGA_A,
+ JOY_XBOX_X = JOY_SEGA_X,
+ JOY_XBOX_Y = JOY_SEGA_Y,
JOY_DS_A = JOY_SNES_A,
JOY_DS_B = JOY_SNES_B,
@@ -127,15 +124,15 @@ enum {
// end of history
- JOY_AXIS_0=0,
- JOY_AXIS_1=1,
- JOY_AXIS_2=2,
- JOY_AXIS_3=3,
- JOY_AXIS_4=4,
- JOY_AXIS_5=5,
- JOY_AXIS_6=6,
- JOY_AXIS_7=7,
- JOY_AXIS_MAX=8,
+ JOY_AXIS_0 = 0,
+ JOY_AXIS_1 = 1,
+ JOY_AXIS_2 = 2,
+ JOY_AXIS_3 = 3,
+ JOY_AXIS_4 = 4,
+ JOY_AXIS_5 = 5,
+ JOY_AXIS_6 = 6,
+ JOY_AXIS_7 = 7,
+ JOY_AXIS_MAX = 8,
JOY_ANALOG_0_X = JOY_AXIS_0,
JOY_ANALOG_0_Y = JOY_AXIS_1,
@@ -150,7 +147,6 @@ enum {
JOY_ANALOG_R2 = JOY_AXIS_7,
};
-
/**
* Input Modifier Status
* for keyboard/mouse events.
@@ -161,32 +157,27 @@ struct InputModifierState {
bool alt;
#ifdef APPLE_STYLE_KEYS
union {
- bool command;
- bool meta; //< windows/mac key
+ bool command;
+ bool meta; //< windows/mac key
};
bool control;
#else
union {
- bool command; //< windows/mac key
- bool control;
+ bool command; //< windows/mac key
+ bool control;
};
bool meta; //< windows/mac key
#endif
- bool operator==(const InputModifierState& rvalue) const {
+ bool operator==(const InputModifierState &rvalue) const {
- return ( (shift==rvalue.shift) && (alt==rvalue.alt) && (control==rvalue.control) && (meta==rvalue.meta));
+ return ((shift == rvalue.shift) && (alt == rvalue.alt) && (control == rvalue.control) && (meta == rvalue.meta));
}
};
-
-
-
-
-
-struct InputEventKey {
+struct InputEventKey {
InputModifierState mod;
@@ -200,66 +191,61 @@ struct InputEventKey {
bool echo; /// true if this is an echo key
};
-
-struct InputEventMouse {
+struct InputEventMouse {
InputModifierState mod;
int button_mask;
- float x,y;
- float global_x,global_y;
+ float x, y;
+ float global_x, global_y;
int pointer_index;
};
struct InputEventMouseButton : public InputEventMouse {
-
int button_index;
bool pressed; //otherwise released
bool doubleclick; //last even less than doubleclick time
-
};
struct InputEventMouseMotion : public InputEventMouse {
- float relative_x,relative_y;
- float speed_x,speed_y;
+ float relative_x, relative_y;
+ float speed_x, speed_y;
};
-struct InputEventJoypadMotion {
+struct InputEventJoypadMotion {
int axis; ///< Joypad axis
float axis_value; ///< -1 to 1
};
-struct InputEventJoypadButton {
+struct InputEventJoypadButton {
int button_index;
bool pressed;
float pressure; //0 to 1
};
-struct InputEventScreenTouch {
+struct InputEventScreenTouch {
int index;
- float x,y;
+ float x, y;
bool pressed;
};
-struct InputEventScreenDrag {
+struct InputEventScreenDrag {
int index;
- float x,y;
- float relative_x,relative_y;
- float speed_x,speed_y;
+ float x, y;
+ float relative_x, relative_y;
+ float speed_x, speed_y;
};
-struct InputEventAction {
+struct InputEventAction {
int action;
bool pressed;
};
-
-
struct InputEvent {
enum Type {
@@ -291,18 +277,16 @@ struct InputEvent {
};
bool is_pressed() const;
- bool is_action(const String& p_action) const;
- bool is_action_pressed(const String& p_action) const;
- bool is_action_released(const String& p_action) const;
+ bool is_action(const String &p_action) const;
+ bool is_action_pressed(const String &p_action) const;
+ bool is_action_released(const String &p_action) const;
bool is_echo() const;
- void set_as_action(const String& p_action, bool p_pressed);
+ void set_as_action(const String &p_action, bool p_pressed);
-
- InputEvent xform_by(const Transform2D& p_xform) const;
+ InputEvent xform_by(const Transform2D &p_xform) const;
bool operator==(const InputEvent &p_event) const;
operator String() const;
- InputEvent() { zeromem(this,sizeof(InputEvent)); }
+ InputEvent() { zeromem(this, sizeof(InputEvent)); }
};
-
#endif
diff --git a/core/os/keyboard.cpp b/core/os/keyboard.cpp
index 40fa86d09f..a5f8bfa144 100644
--- a/core/os/keyboard.cpp
+++ b/core/os/keyboard.cpp
@@ -34,9 +34,9 @@ struct _KeyCodeText {
const char *text;
};
-static const _KeyCodeText _keycodes[]={
+static const _KeyCodeText _keycodes[] = {
- /* clang-format off */
+ /* clang-format off */
{KEY_ESCAPE ,"Escape"},
{KEY_TAB ,"Tab"},
{KEY_BACKTAB ,"BackTab"},
@@ -283,25 +283,105 @@ static const _KeyCodeText _keycodes[]={
{KEY_DIVISION ,"Division"},
{KEY_YDIAERESIS ,"Ydiaeresis"},
{0 ,0}
- /* clang-format on */
+ /* clang-format on */
};
bool keycode_has_unicode(uint32_t p_keycode) {
-
- switch(p_keycode) {
-
- case KEY_ESCAPE: case KEY_TAB: case KEY_BACKTAB: case KEY_BACKSPACE: case KEY_RETURN: case KEY_ENTER: case KEY_INSERT: case KEY_DELETE: case KEY_PAUSE:
- case KEY_PRINT: case KEY_SYSREQ: case KEY_CLEAR: case KEY_HOME: case KEY_END: case KEY_LEFT: case KEY_UP: case KEY_RIGHT: case KEY_DOWN: case KEY_PAGEUP:
- case KEY_PAGEDOWN: case KEY_SHIFT: case KEY_CONTROL: case KEY_META: case KEY_ALT: case KEY_CAPSLOCK: case KEY_NUMLOCK: case KEY_SCROLLLOCK: case KEY_F1:
- case KEY_F2: case KEY_F3: case KEY_F4: case KEY_F5: case KEY_F6: case KEY_F7: case KEY_F8: case KEY_F9: case KEY_F10: case KEY_F11: case KEY_F12: case KEY_F13: case KEY_F14:
- case KEY_F15: case KEY_F16: case KEY_KP_ENTER: case KEY_SUPER_L: case KEY_SUPER_R: case KEY_MENU: case KEY_HYPER_L: case KEY_HYPER_R: case KEY_HELP:
- case KEY_DIRECTION_L: case KEY_DIRECTION_R: case KEY_BACK: case KEY_FORWARD: case KEY_STOP: case KEY_REFRESH: case KEY_VOLUMEDOWN: case KEY_VOLUMEMUTE:
- case KEY_VOLUMEUP: case KEY_BASSBOOST: case KEY_BASSUP: case KEY_BASSDOWN: case KEY_TREBLEUP: case KEY_TREBLEDOWN: case KEY_MEDIAPLAY: case KEY_MEDIASTOP:
- case KEY_MEDIAPREVIOUS: case KEY_MEDIANEXT: case KEY_MEDIARECORD: case KEY_HOMEPAGE: case KEY_FAVORITES: case KEY_SEARCH: case KEY_STANDBY:
- case KEY_OPENURL: case KEY_LAUNCHMAIL: case KEY_LAUNCHMEDIA: case KEY_LAUNCH0: case KEY_LAUNCH1: case KEY_LAUNCH2: case KEY_LAUNCH3: case KEY_LAUNCH4:
- case KEY_LAUNCH5: case KEY_LAUNCH6: case KEY_LAUNCH7: case KEY_LAUNCH8: case KEY_LAUNCH9: case KEY_LAUNCHA: case KEY_LAUNCHB: case KEY_LAUNCHC: case KEY_LAUNCHD:
- case KEY_LAUNCHE: case KEY_LAUNCHF:
+ switch (p_keycode) {
+
+ case KEY_ESCAPE:
+ case KEY_TAB:
+ case KEY_BACKTAB:
+ case KEY_BACKSPACE:
+ case KEY_RETURN:
+ case KEY_ENTER:
+ case KEY_INSERT:
+ case KEY_DELETE:
+ case KEY_PAUSE:
+ case KEY_PRINT:
+ case KEY_SYSREQ:
+ case KEY_CLEAR:
+ case KEY_HOME:
+ case KEY_END:
+ case KEY_LEFT:
+ case KEY_UP:
+ case KEY_RIGHT:
+ case KEY_DOWN:
+ case KEY_PAGEUP:
+ case KEY_PAGEDOWN:
+ case KEY_SHIFT:
+ case KEY_CONTROL:
+ case KEY_META:
+ case KEY_ALT:
+ case KEY_CAPSLOCK:
+ case KEY_NUMLOCK:
+ case KEY_SCROLLLOCK:
+ case KEY_F1:
+ case KEY_F2:
+ case KEY_F3:
+ case KEY_F4:
+ case KEY_F5:
+ case KEY_F6:
+ case KEY_F7:
+ case KEY_F8:
+ case KEY_F9:
+ case KEY_F10:
+ case KEY_F11:
+ case KEY_F12:
+ case KEY_F13:
+ case KEY_F14:
+ case KEY_F15:
+ case KEY_F16:
+ case KEY_KP_ENTER:
+ case KEY_SUPER_L:
+ case KEY_SUPER_R:
+ case KEY_MENU:
+ case KEY_HYPER_L:
+ case KEY_HYPER_R:
+ case KEY_HELP:
+ case KEY_DIRECTION_L:
+ case KEY_DIRECTION_R:
+ case KEY_BACK:
+ case KEY_FORWARD:
+ case KEY_STOP:
+ case KEY_REFRESH:
+ case KEY_VOLUMEDOWN:
+ case KEY_VOLUMEMUTE:
+ case KEY_VOLUMEUP:
+ case KEY_BASSBOOST:
+ case KEY_BASSUP:
+ case KEY_BASSDOWN:
+ case KEY_TREBLEUP:
+ case KEY_TREBLEDOWN:
+ case KEY_MEDIAPLAY:
+ case KEY_MEDIASTOP:
+ case KEY_MEDIAPREVIOUS:
+ case KEY_MEDIANEXT:
+ case KEY_MEDIARECORD:
+ case KEY_HOMEPAGE:
+ case KEY_FAVORITES:
+ case KEY_SEARCH:
+ case KEY_STANDBY:
+ case KEY_OPENURL:
+ case KEY_LAUNCHMAIL:
+ case KEY_LAUNCHMEDIA:
+ case KEY_LAUNCH0:
+ case KEY_LAUNCH1:
+ case KEY_LAUNCH2:
+ case KEY_LAUNCH3:
+ case KEY_LAUNCH4:
+ case KEY_LAUNCH5:
+ case KEY_LAUNCH6:
+ case KEY_LAUNCH7:
+ case KEY_LAUNCH8:
+ case KEY_LAUNCH9:
+ case KEY_LAUNCHA:
+ case KEY_LAUNCHB:
+ case KEY_LAUNCHC:
+ case KEY_LAUNCHD:
+ case KEY_LAUNCHE:
+ case KEY_LAUNCHF:
return false;
}
@@ -311,133 +391,127 @@ bool keycode_has_unicode(uint32_t p_keycode) {
String keycode_get_string(uint32_t p_code) {
String codestr;
- if (p_code&KEY_MASK_SHIFT)
- codestr+="Shift+";
- if (p_code&KEY_MASK_ALT)
- codestr+="Alt+";
- if (p_code&KEY_MASK_CTRL)
- codestr+="Ctrl+";
- if (p_code&KEY_MASK_META)
- codestr+="Meta+";
+ if (p_code & KEY_MASK_SHIFT)
+ codestr += "Shift+";
+ if (p_code & KEY_MASK_ALT)
+ codestr += "Alt+";
+ if (p_code & KEY_MASK_CTRL)
+ codestr += "Ctrl+";
+ if (p_code & KEY_MASK_META)
+ codestr += "Meta+";
- p_code&=KEY_CODE_MASK;
+ p_code &= KEY_CODE_MASK;
- const _KeyCodeText *kct =&_keycodes[0];
+ const _KeyCodeText *kct = &_keycodes[0];
- while(kct->text) {
+ while (kct->text) {
- if (kct->code==(int)p_code) {
+ if (kct->code == (int)p_code) {
- codestr+=kct->text;
+ codestr += kct->text;
return codestr;
}
kct++;
}
- codestr+=String::chr(p_code);
+ codestr += String::chr(p_code);
return codestr;
-
}
-int find_keycode(const String& p_code) {
+int find_keycode(const String &p_code) {
- const _KeyCodeText *kct =&_keycodes[0];
+ const _KeyCodeText *kct = &_keycodes[0];
- while(kct->text) {
+ while (kct->text) {
- if (p_code.nocasecmp_to(kct->text)==0) {
+ if (p_code.nocasecmp_to(kct->text) == 0) {
return kct->code;
-
}
kct++;
}
return 0;
-
}
-
-
-
struct _KeyCodeReplace {
int from;
int to;
};
-static const _KeyCodeReplace _keycode_replace_qwertz[]={
-{KEY_Y,KEY_Z},
-{KEY_Z,KEY_Y},
-{0,0}
+static const _KeyCodeReplace _keycode_replace_qwertz[] = {
+ { KEY_Y, KEY_Z },
+ { KEY_Z, KEY_Y },
+ { 0, 0 }
};
-static const _KeyCodeReplace _keycode_replace_azerty[]={
-{KEY_W,KEY_Z},
-{KEY_Z,KEY_W},
-{KEY_A,KEY_Q},
-{KEY_Q,KEY_A},
-{KEY_SEMICOLON,KEY_M},
-{KEY_M,KEY_SEMICOLON},
-{0,0}
+static const _KeyCodeReplace _keycode_replace_azerty[] = {
+ { KEY_W, KEY_Z },
+ { KEY_Z, KEY_W },
+ { KEY_A, KEY_Q },
+ { KEY_Q, KEY_A },
+ { KEY_SEMICOLON, KEY_M },
+ { KEY_M, KEY_SEMICOLON },
+ { 0, 0 }
};
-static const _KeyCodeReplace _keycode_replace_qzerty[]={
-{KEY_W,KEY_Z},
-{KEY_Z,KEY_W},
-{KEY_SEMICOLON,KEY_M},
-{KEY_M,KEY_SEMICOLON},
-{0,0}
+static const _KeyCodeReplace _keycode_replace_qzerty[] = {
+ { KEY_W, KEY_Z },
+ { KEY_Z, KEY_W },
+ { KEY_SEMICOLON, KEY_M },
+ { KEY_M, KEY_SEMICOLON },
+ { 0, 0 }
};
-static const _KeyCodeReplace _keycode_replace_dvorak[]={
-{KEY_UNDERSCORE,KEY_BRACELEFT},
-{KEY_EQUAL,KEY_BRACERIGHT},
-{KEY_Q,KEY_APOSTROPHE},
-{KEY_W,KEY_COMMA},
-{KEY_E,KEY_PERIOD},
-{KEY_R,KEY_P},
-{KEY_T,KEY_Y},
-{KEY_Y,KEY_F},
-{KEY_U,KEY_G},
-{KEY_I,KEY_C},
-{KEY_O,KEY_R},
-{KEY_P,KEY_L},
-{KEY_BRACELEFT,KEY_SLASH},
-{KEY_BRACERIGHT,KEY_EQUAL},
-{KEY_A,KEY_A},
-{KEY_S,KEY_O},
-{KEY_D,KEY_E},
-{KEY_F,KEY_U},
-{KEY_G,KEY_I},
-{KEY_H,KEY_D},
-{KEY_J,KEY_H},
-{KEY_K,KEY_T},
-{KEY_L,KEY_N},
-{KEY_SEMICOLON,KEY_S},
-{KEY_APOSTROPHE,KEY_UNDERSCORE},
-{KEY_Z,KEY_SEMICOLON},
-{KEY_X,KEY_Q},
-{KEY_C,KEY_J},
-{KEY_V,KEY_K},
-{KEY_B,KEY_X},
-{KEY_N,KEY_B},
-{KEY_M,KEY_M},
-{KEY_COMMA,KEY_W},
-{KEY_PERIOD,KEY_V},
-{KEY_SLASH,KEY_Z},
-{0,0}
+static const _KeyCodeReplace _keycode_replace_dvorak[] = {
+ { KEY_UNDERSCORE, KEY_BRACELEFT },
+ { KEY_EQUAL, KEY_BRACERIGHT },
+ { KEY_Q, KEY_APOSTROPHE },
+ { KEY_W, KEY_COMMA },
+ { KEY_E, KEY_PERIOD },
+ { KEY_R, KEY_P },
+ { KEY_T, KEY_Y },
+ { KEY_Y, KEY_F },
+ { KEY_U, KEY_G },
+ { KEY_I, KEY_C },
+ { KEY_O, KEY_R },
+ { KEY_P, KEY_L },
+ { KEY_BRACELEFT, KEY_SLASH },
+ { KEY_BRACERIGHT, KEY_EQUAL },
+ { KEY_A, KEY_A },
+ { KEY_S, KEY_O },
+ { KEY_D, KEY_E },
+ { KEY_F, KEY_U },
+ { KEY_G, KEY_I },
+ { KEY_H, KEY_D },
+ { KEY_J, KEY_H },
+ { KEY_K, KEY_T },
+ { KEY_L, KEY_N },
+ { KEY_SEMICOLON, KEY_S },
+ { KEY_APOSTROPHE, KEY_UNDERSCORE },
+ { KEY_Z, KEY_SEMICOLON },
+ { KEY_X, KEY_Q },
+ { KEY_C, KEY_J },
+ { KEY_V, KEY_K },
+ { KEY_B, KEY_X },
+ { KEY_N, KEY_B },
+ { KEY_M, KEY_M },
+ { KEY_COMMA, KEY_W },
+ { KEY_PERIOD, KEY_V },
+ { KEY_SLASH, KEY_Z },
+ { 0, 0 }
};
-static const _KeyCodeReplace _keycode_replace_neo[]={
-{0,0}
+static const _KeyCodeReplace _keycode_replace_neo[] = {
+ { 0, 0 }
};
int keycode_get_count() {
- const _KeyCodeText *kct =&_keycodes[0];
+ const _KeyCodeText *kct = &_keycodes[0];
- int count=0;
- while(kct->text) {
+ int count = 0;
+ while (kct->text) {
count++;
kct++;
@@ -449,22 +523,21 @@ int keycode_get_value_by_index(int p_index) {
return _keycodes[p_index].code;
}
-const char* keycode_get_name_by_index(int p_index) {
+const char *keycode_get_name_by_index(int p_index) {
return _keycodes[p_index].text;
}
-
int latin_keyboard_keycode_convert(int p_keycode) {
- const _KeyCodeReplace *kcr=NULL;
- switch(OS::get_singleton()->get_latin_keyboard_variant()) {
+ const _KeyCodeReplace *kcr = NULL;
+ switch (OS::get_singleton()->get_latin_keyboard_variant()) {
case OS::LATIN_KEYBOARD_QWERTY: return p_keycode; break;
- case OS::LATIN_KEYBOARD_QWERTZ: kcr=_keycode_replace_qwertz; break;
- case OS::LATIN_KEYBOARD_AZERTY: kcr=_keycode_replace_azerty; break;
- case OS::LATIN_KEYBOARD_QZERTY: kcr=_keycode_replace_qzerty; break;
- case OS::LATIN_KEYBOARD_DVORAK: kcr=_keycode_replace_dvorak; break;
- case OS::LATIN_KEYBOARD_NEO: kcr=_keycode_replace_neo; break;
+ case OS::LATIN_KEYBOARD_QWERTZ: kcr = _keycode_replace_qwertz; break;
+ case OS::LATIN_KEYBOARD_AZERTY: kcr = _keycode_replace_azerty; break;
+ case OS::LATIN_KEYBOARD_QZERTY: kcr = _keycode_replace_qzerty; break;
+ case OS::LATIN_KEYBOARD_DVORAK: kcr = _keycode_replace_dvorak; break;
+ case OS::LATIN_KEYBOARD_NEO: kcr = _keycode_replace_neo; break;
default: return p_keycode;
}
@@ -472,8 +545,8 @@ int latin_keyboard_keycode_convert(int p_keycode) {
return p_keycode;
}
- while(kcr->from) {
- if (kcr->from==p_keycode)
+ while (kcr->from) {
+ if (kcr->from == p_keycode)
return kcr->to;
kcr++;
}
diff --git a/core/os/keyboard.h b/core/os/keyboard.h
index 1357cc8b8e..1f6bc77334 100644
--- a/core/os/keyboard.h
+++ b/core/os/keyboard.h
@@ -47,290 +47,288 @@
modifiers. This way everything (char/keycode) can fit nicely in one 32 bits unsigned integer.
*/
enum {
- SPKEY = (1<<24)
+ SPKEY = (1 << 24)
};
enum KeyList {
-/* CURSOR/FUNCTION/BROWSER/MULTIMEDIA/MISC KEYS */
- KEY_ESCAPE=SPKEY | 0x01,
- KEY_TAB=SPKEY | 0x02,
- KEY_BACKTAB=SPKEY | 0x03,
- KEY_BACKSPACE=SPKEY | 0x04,
- KEY_RETURN=SPKEY | 0x05,
- KEY_ENTER=SPKEY | 0x06,
- KEY_INSERT=SPKEY | 0x07,
- KEY_DELETE=SPKEY | 0x08,
- KEY_PAUSE=SPKEY | 0x09,
- KEY_PRINT=SPKEY | 0x0A,
- KEY_SYSREQ=SPKEY | 0x0B,
- KEY_CLEAR=SPKEY | 0x0C,
- KEY_HOME=SPKEY | 0x0D,
- KEY_END=SPKEY | 0x0E,
- KEY_LEFT=SPKEY | 0x0F,
- KEY_UP=SPKEY | 0x10,
- KEY_RIGHT=SPKEY | 0x11,
- KEY_DOWN=SPKEY | 0x12,
- KEY_PAGEUP=SPKEY | 0x13,
- KEY_PAGEDOWN=SPKEY | 0x14,
- KEY_SHIFT=SPKEY | 0x15,
- KEY_CONTROL=SPKEY | 0x16,
- KEY_META=SPKEY | 0x17,
- KEY_ALT=SPKEY | 0x18,
- KEY_CAPSLOCK=SPKEY | 0x19,
- KEY_NUMLOCK=SPKEY | 0x1A,
- KEY_SCROLLLOCK=SPKEY | 0x1B,
- KEY_F1=SPKEY | 0x1C,
- KEY_F2=SPKEY | 0x1D,
- KEY_F3=SPKEY | 0x1E,
- KEY_F4=SPKEY | 0x1F,
- KEY_F5=SPKEY | 0x20,
- KEY_F6=SPKEY | 0x21,
- KEY_F7=SPKEY | 0x22,
- KEY_F8=SPKEY | 0x23,
- KEY_F9=SPKEY | 0x24,
- KEY_F10=SPKEY | 0x25,
- KEY_F11=SPKEY | 0x26,
- KEY_F12=SPKEY | 0x27,
- KEY_F13=SPKEY | 0x28,
- KEY_F14=SPKEY | 0x29,
- KEY_F15=SPKEY | 0x2A,
- KEY_F16=SPKEY | 0x2B,
- KEY_KP_ENTER=SPKEY | 0x80,
- KEY_KP_MULTIPLY=SPKEY | 0x81,
- KEY_KP_DIVIDE=SPKEY | 0x82,
- KEY_KP_SUBTRACT=SPKEY | 0x83,
- KEY_KP_PERIOD=SPKEY | 0x84,
- KEY_KP_ADD=SPKEY | 0x85,
- KEY_KP_0=SPKEY | 0x86,
- KEY_KP_1=SPKEY | 0x87,
- KEY_KP_2=SPKEY | 0x88,
- KEY_KP_3=SPKEY | 0x89,
- KEY_KP_4=SPKEY | 0x8A,
- KEY_KP_5=SPKEY | 0x8B,
- KEY_KP_6=SPKEY | 0x8C,
- KEY_KP_7=SPKEY | 0x8D,
- KEY_KP_8=SPKEY | 0x8E,
- KEY_KP_9=SPKEY | 0x8F,
- KEY_SUPER_L=SPKEY | 0x2C,
- KEY_SUPER_R=SPKEY | 0x2D,
- KEY_MENU=SPKEY | 0x2E,
- KEY_HYPER_L=SPKEY | 0x2F,
- KEY_HYPER_R=SPKEY | 0x30,
- KEY_HELP=SPKEY | 0x31,
- KEY_DIRECTION_L=SPKEY | 0x32,
- KEY_DIRECTION_R=SPKEY | 0x33,
- KEY_BACK=SPKEY | 0x40,
- KEY_FORWARD=SPKEY | 0x41,
- KEY_STOP=SPKEY | 0x42,
- KEY_REFRESH=SPKEY | 0x43,
- KEY_VOLUMEDOWN=SPKEY | 0x44,
- KEY_VOLUMEMUTE=SPKEY | 0x45,
- KEY_VOLUMEUP=SPKEY | 0x46,
- KEY_BASSBOOST=SPKEY | 0x47,
- KEY_BASSUP=SPKEY | 0x48,
- KEY_BASSDOWN=SPKEY | 0x49,
- KEY_TREBLEUP=SPKEY | 0x4A,
- KEY_TREBLEDOWN=SPKEY | 0x4B,
- KEY_MEDIAPLAY=SPKEY | 0x4C,
- KEY_MEDIASTOP=SPKEY | 0x4D,
- KEY_MEDIAPREVIOUS=SPKEY | 0x4E,
- KEY_MEDIANEXT=SPKEY | 0x4F,
- KEY_MEDIARECORD= SPKEY | 0x50,
- KEY_HOMEPAGE=SPKEY | 0x51,
- KEY_FAVORITES=SPKEY | 0x52,
- KEY_SEARCH=SPKEY | 0x53,
- KEY_STANDBY=SPKEY | 0x54,
- KEY_OPENURL=SPKEY | 0x55,
- KEY_LAUNCHMAIL=SPKEY | 0x56,
- KEY_LAUNCHMEDIA=SPKEY | 0x57,
- KEY_LAUNCH0=SPKEY | 0x58,
- KEY_LAUNCH1=SPKEY | 0x59,
- KEY_LAUNCH2=SPKEY | 0x5A,
- KEY_LAUNCH3=SPKEY | 0x5B,
- KEY_LAUNCH4=SPKEY | 0x5C,
- KEY_LAUNCH5=SPKEY | 0x5D,
- KEY_LAUNCH6=SPKEY | 0x5E,
- KEY_LAUNCH7=SPKEY | 0x5F,
- KEY_LAUNCH8=SPKEY | 0x60,
- KEY_LAUNCH9=SPKEY | 0x61,
- KEY_LAUNCHA=SPKEY | 0x62,
- KEY_LAUNCHB=SPKEY | 0x63,
- KEY_LAUNCHC=SPKEY | 0x64,
- KEY_LAUNCHD=SPKEY | 0x65,
- KEY_LAUNCHE=SPKEY | 0x66,
- KEY_LAUNCHF=SPKEY | 0x67,
+ /* CURSOR/FUNCTION/BROWSER/MULTIMEDIA/MISC KEYS */
+ KEY_ESCAPE = SPKEY | 0x01,
+ KEY_TAB = SPKEY | 0x02,
+ KEY_BACKTAB = SPKEY | 0x03,
+ KEY_BACKSPACE = SPKEY | 0x04,
+ KEY_RETURN = SPKEY | 0x05,
+ KEY_ENTER = SPKEY | 0x06,
+ KEY_INSERT = SPKEY | 0x07,
+ KEY_DELETE = SPKEY | 0x08,
+ KEY_PAUSE = SPKEY | 0x09,
+ KEY_PRINT = SPKEY | 0x0A,
+ KEY_SYSREQ = SPKEY | 0x0B,
+ KEY_CLEAR = SPKEY | 0x0C,
+ KEY_HOME = SPKEY | 0x0D,
+ KEY_END = SPKEY | 0x0E,
+ KEY_LEFT = SPKEY | 0x0F,
+ KEY_UP = SPKEY | 0x10,
+ KEY_RIGHT = SPKEY | 0x11,
+ KEY_DOWN = SPKEY | 0x12,
+ KEY_PAGEUP = SPKEY | 0x13,
+ KEY_PAGEDOWN = SPKEY | 0x14,
+ KEY_SHIFT = SPKEY | 0x15,
+ KEY_CONTROL = SPKEY | 0x16,
+ KEY_META = SPKEY | 0x17,
+ KEY_ALT = SPKEY | 0x18,
+ KEY_CAPSLOCK = SPKEY | 0x19,
+ KEY_NUMLOCK = SPKEY | 0x1A,
+ KEY_SCROLLLOCK = SPKEY | 0x1B,
+ KEY_F1 = SPKEY | 0x1C,
+ KEY_F2 = SPKEY | 0x1D,
+ KEY_F3 = SPKEY | 0x1E,
+ KEY_F4 = SPKEY | 0x1F,
+ KEY_F5 = SPKEY | 0x20,
+ KEY_F6 = SPKEY | 0x21,
+ KEY_F7 = SPKEY | 0x22,
+ KEY_F8 = SPKEY | 0x23,
+ KEY_F9 = SPKEY | 0x24,
+ KEY_F10 = SPKEY | 0x25,
+ KEY_F11 = SPKEY | 0x26,
+ KEY_F12 = SPKEY | 0x27,
+ KEY_F13 = SPKEY | 0x28,
+ KEY_F14 = SPKEY | 0x29,
+ KEY_F15 = SPKEY | 0x2A,
+ KEY_F16 = SPKEY | 0x2B,
+ KEY_KP_ENTER = SPKEY | 0x80,
+ KEY_KP_MULTIPLY = SPKEY | 0x81,
+ KEY_KP_DIVIDE = SPKEY | 0x82,
+ KEY_KP_SUBTRACT = SPKEY | 0x83,
+ KEY_KP_PERIOD = SPKEY | 0x84,
+ KEY_KP_ADD = SPKEY | 0x85,
+ KEY_KP_0 = SPKEY | 0x86,
+ KEY_KP_1 = SPKEY | 0x87,
+ KEY_KP_2 = SPKEY | 0x88,
+ KEY_KP_3 = SPKEY | 0x89,
+ KEY_KP_4 = SPKEY | 0x8A,
+ KEY_KP_5 = SPKEY | 0x8B,
+ KEY_KP_6 = SPKEY | 0x8C,
+ KEY_KP_7 = SPKEY | 0x8D,
+ KEY_KP_8 = SPKEY | 0x8E,
+ KEY_KP_9 = SPKEY | 0x8F,
+ KEY_SUPER_L = SPKEY | 0x2C,
+ KEY_SUPER_R = SPKEY | 0x2D,
+ KEY_MENU = SPKEY | 0x2E,
+ KEY_HYPER_L = SPKEY | 0x2F,
+ KEY_HYPER_R = SPKEY | 0x30,
+ KEY_HELP = SPKEY | 0x31,
+ KEY_DIRECTION_L = SPKEY | 0x32,
+ KEY_DIRECTION_R = SPKEY | 0x33,
+ KEY_BACK = SPKEY | 0x40,
+ KEY_FORWARD = SPKEY | 0x41,
+ KEY_STOP = SPKEY | 0x42,
+ KEY_REFRESH = SPKEY | 0x43,
+ KEY_VOLUMEDOWN = SPKEY | 0x44,
+ KEY_VOLUMEMUTE = SPKEY | 0x45,
+ KEY_VOLUMEUP = SPKEY | 0x46,
+ KEY_BASSBOOST = SPKEY | 0x47,
+ KEY_BASSUP = SPKEY | 0x48,
+ KEY_BASSDOWN = SPKEY | 0x49,
+ KEY_TREBLEUP = SPKEY | 0x4A,
+ KEY_TREBLEDOWN = SPKEY | 0x4B,
+ KEY_MEDIAPLAY = SPKEY | 0x4C,
+ KEY_MEDIASTOP = SPKEY | 0x4D,
+ KEY_MEDIAPREVIOUS = SPKEY | 0x4E,
+ KEY_MEDIANEXT = SPKEY | 0x4F,
+ KEY_MEDIARECORD = SPKEY | 0x50,
+ KEY_HOMEPAGE = SPKEY | 0x51,
+ KEY_FAVORITES = SPKEY | 0x52,
+ KEY_SEARCH = SPKEY | 0x53,
+ KEY_STANDBY = SPKEY | 0x54,
+ KEY_OPENURL = SPKEY | 0x55,
+ KEY_LAUNCHMAIL = SPKEY | 0x56,
+ KEY_LAUNCHMEDIA = SPKEY | 0x57,
+ KEY_LAUNCH0 = SPKEY | 0x58,
+ KEY_LAUNCH1 = SPKEY | 0x59,
+ KEY_LAUNCH2 = SPKEY | 0x5A,
+ KEY_LAUNCH3 = SPKEY | 0x5B,
+ KEY_LAUNCH4 = SPKEY | 0x5C,
+ KEY_LAUNCH5 = SPKEY | 0x5D,
+ KEY_LAUNCH6 = SPKEY | 0x5E,
+ KEY_LAUNCH7 = SPKEY | 0x5F,
+ KEY_LAUNCH8 = SPKEY | 0x60,
+ KEY_LAUNCH9 = SPKEY | 0x61,
+ KEY_LAUNCHA = SPKEY | 0x62,
+ KEY_LAUNCHB = SPKEY | 0x63,
+ KEY_LAUNCHC = SPKEY | 0x64,
+ KEY_LAUNCHD = SPKEY | 0x65,
+ KEY_LAUNCHE = SPKEY | 0x66,
+ KEY_LAUNCHF = SPKEY | 0x67,
- KEY_UNKNOWN=SPKEY | 0xFFFFFF,
+ KEY_UNKNOWN = SPKEY | 0xFFFFFF,
-/* PRINTABLE LATIN 1 CODES */
+ /* PRINTABLE LATIN 1 CODES */
- KEY_SPACE=0x0020,
- KEY_EXCLAM=0x0021,
- KEY_QUOTEDBL=0x0022,
- KEY_NUMBERSIGN=0x0023,
- KEY_DOLLAR=0x0024,
- KEY_PERCENT=0x0025,
- KEY_AMPERSAND=0x0026,
- KEY_APOSTROPHE=0x0027,
- KEY_PARENLEFT=0x0028,
- KEY_PARENRIGHT=0x0029,
- KEY_ASTERISK=0x002A,
- KEY_PLUS=0x002B,
- KEY_COMMA=0x002C,
- KEY_MINUS=0x002D,
- KEY_PERIOD=0x002E,
- KEY_SLASH=0x002F,
- KEY_0=0x0030,
- KEY_1=0x0031,
- KEY_2=0x0032,
- KEY_3=0x0033,
- KEY_4=0x0034,
- KEY_5=0x0035,
- KEY_6=0x0036,
- KEY_7=0x0037,
- KEY_8=0x0038,
- KEY_9=0x0039,
- KEY_COLON=0x003A,
- KEY_SEMICOLON=0x003B,
- KEY_LESS=0x003C,
- KEY_EQUAL=0x003D,
- KEY_GREATER=0x003E,
- KEY_QUESTION=0x003F,
- KEY_AT=0x0040,
- KEY_A=0x0041,
- KEY_B=0x0042,
- KEY_C=0x0043,
- KEY_D=0x0044,
- KEY_E=0x0045,
- KEY_F=0x0046,
- KEY_G=0x0047,
- KEY_H=0x0048,
- KEY_I=0x0049,
- KEY_J=0x004A,
- KEY_K=0x004B,
- KEY_L=0x004C,
- KEY_M=0x004D,
- KEY_N=0x004E,
- KEY_O=0x004F,
- KEY_P=0x0050,
- KEY_Q=0x0051,
- KEY_R=0x0052,
- KEY_S=0x0053,
- KEY_T=0x0054,
- KEY_U=0x0055,
- KEY_V=0x0056,
- KEY_W=0x0057,
- KEY_X=0x0058,
- KEY_Y=0x0059,
- KEY_Z=0x005A,
- KEY_BRACKETLEFT=0x005B,
- KEY_BACKSLASH=0x005C,
- KEY_BRACKETRIGHT=0x005D,
- KEY_ASCIICIRCUM=0x005E,
- KEY_UNDERSCORE=0x005F,
- KEY_QUOTELEFT=0x0060,
- KEY_BRACELEFT=0x007B,
- KEY_BAR=0x007C,
- KEY_BRACERIGHT=0x007D,
- KEY_ASCIITILDE=0x007E,
- KEY_NOBREAKSPACE=0x00A0,
- KEY_EXCLAMDOWN=0x00A1,
- KEY_CENT=0x00A2,
- KEY_STERLING=0x00A3,
- KEY_CURRENCY=0x00A4,
- KEY_YEN=0x00A5,
- KEY_BROKENBAR=0x00A6,
- KEY_SECTION=0x00A7,
- KEY_DIAERESIS=0x00A8,
- KEY_COPYRIGHT=0x00A9,
- KEY_ORDFEMININE=0x00AA,
- KEY_GUILLEMOTLEFT=0x00AB,
- KEY_NOTSIGN=0x00AC,
- KEY_HYPHEN=0x00AD,
- KEY_REGISTERED=0x00AE,
- KEY_MACRON=0x00AF,
- KEY_DEGREE=0x00B0,
- KEY_PLUSMINUS=0x00B1,
- KEY_TWOSUPERIOR=0x00B2,
- KEY_THREESUPERIOR=0x00B3,
- KEY_ACUTE=0x00B4,
- KEY_MU=0x00B5,
- KEY_PARAGRAPH=0x00B6,
- KEY_PERIODCENTERED=0x00B7,
- KEY_CEDILLA=0x00B8,
- KEY_ONESUPERIOR=0x00B9,
- KEY_MASCULINE=0x00BA,
- KEY_GUILLEMOTRIGHT=0x00BB,
- KEY_ONEQUARTER=0x00BC,
- KEY_ONEHALF=0x00BD,
- KEY_THREEQUARTERS=0x00BE,
- KEY_QUESTIONDOWN=0x00BF,
- KEY_AGRAVE=0x00C0,
- KEY_AACUTE=0x00C1,
- KEY_ACIRCUMFLEX=0x00C2,
- KEY_ATILDE=0x00C3,
- KEY_ADIAERESIS=0x00C4,
- KEY_ARING=0x00C5,
- KEY_AE=0x00C6,
- KEY_CCEDILLA=0x00C7,
- KEY_EGRAVE=0x00C8,
- KEY_EACUTE=0x00C9,
- KEY_ECIRCUMFLEX=0x00CA,
- KEY_EDIAERESIS=0x00CB,
- KEY_IGRAVE=0x00CC,
- KEY_IACUTE=0x00CD,
- KEY_ICIRCUMFLEX=0x00CE,
- KEY_IDIAERESIS=0x00CF,
- KEY_ETH=0x00D0,
- KEY_NTILDE=0x00D1,
- KEY_OGRAVE=0x00D2,
- KEY_OACUTE=0x00D3,
- KEY_OCIRCUMFLEX=0x00D4,
- KEY_OTILDE=0x00D5,
- KEY_ODIAERESIS=0x00D6,
- KEY_MULTIPLY=0x00D7,
- KEY_OOBLIQUE=0x00D8,
- KEY_UGRAVE=0x00D9,
- KEY_UACUTE=0x00DA,
- KEY_UCIRCUMFLEX=0x00DB,
- KEY_UDIAERESIS=0x00DC,
- KEY_YACUTE=0x00DD,
- KEY_THORN=0x00DE,
- KEY_SSHARP=0x00DF,
-
- KEY_DIVISION=0x00F7,
- KEY_YDIAERESIS=0x00FF,
+ KEY_SPACE = 0x0020,
+ KEY_EXCLAM = 0x0021,
+ KEY_QUOTEDBL = 0x0022,
+ KEY_NUMBERSIGN = 0x0023,
+ KEY_DOLLAR = 0x0024,
+ KEY_PERCENT = 0x0025,
+ KEY_AMPERSAND = 0x0026,
+ KEY_APOSTROPHE = 0x0027,
+ KEY_PARENLEFT = 0x0028,
+ KEY_PARENRIGHT = 0x0029,
+ KEY_ASTERISK = 0x002A,
+ KEY_PLUS = 0x002B,
+ KEY_COMMA = 0x002C,
+ KEY_MINUS = 0x002D,
+ KEY_PERIOD = 0x002E,
+ KEY_SLASH = 0x002F,
+ KEY_0 = 0x0030,
+ KEY_1 = 0x0031,
+ KEY_2 = 0x0032,
+ KEY_3 = 0x0033,
+ KEY_4 = 0x0034,
+ KEY_5 = 0x0035,
+ KEY_6 = 0x0036,
+ KEY_7 = 0x0037,
+ KEY_8 = 0x0038,
+ KEY_9 = 0x0039,
+ KEY_COLON = 0x003A,
+ KEY_SEMICOLON = 0x003B,
+ KEY_LESS = 0x003C,
+ KEY_EQUAL = 0x003D,
+ KEY_GREATER = 0x003E,
+ KEY_QUESTION = 0x003F,
+ KEY_AT = 0x0040,
+ KEY_A = 0x0041,
+ KEY_B = 0x0042,
+ KEY_C = 0x0043,
+ KEY_D = 0x0044,
+ KEY_E = 0x0045,
+ KEY_F = 0x0046,
+ KEY_G = 0x0047,
+ KEY_H = 0x0048,
+ KEY_I = 0x0049,
+ KEY_J = 0x004A,
+ KEY_K = 0x004B,
+ KEY_L = 0x004C,
+ KEY_M = 0x004D,
+ KEY_N = 0x004E,
+ KEY_O = 0x004F,
+ KEY_P = 0x0050,
+ KEY_Q = 0x0051,
+ KEY_R = 0x0052,
+ KEY_S = 0x0053,
+ KEY_T = 0x0054,
+ KEY_U = 0x0055,
+ KEY_V = 0x0056,
+ KEY_W = 0x0057,
+ KEY_X = 0x0058,
+ KEY_Y = 0x0059,
+ KEY_Z = 0x005A,
+ KEY_BRACKETLEFT = 0x005B,
+ KEY_BACKSLASH = 0x005C,
+ KEY_BRACKETRIGHT = 0x005D,
+ KEY_ASCIICIRCUM = 0x005E,
+ KEY_UNDERSCORE = 0x005F,
+ KEY_QUOTELEFT = 0x0060,
+ KEY_BRACELEFT = 0x007B,
+ KEY_BAR = 0x007C,
+ KEY_BRACERIGHT = 0x007D,
+ KEY_ASCIITILDE = 0x007E,
+ KEY_NOBREAKSPACE = 0x00A0,
+ KEY_EXCLAMDOWN = 0x00A1,
+ KEY_CENT = 0x00A2,
+ KEY_STERLING = 0x00A3,
+ KEY_CURRENCY = 0x00A4,
+ KEY_YEN = 0x00A5,
+ KEY_BROKENBAR = 0x00A6,
+ KEY_SECTION = 0x00A7,
+ KEY_DIAERESIS = 0x00A8,
+ KEY_COPYRIGHT = 0x00A9,
+ KEY_ORDFEMININE = 0x00AA,
+ KEY_GUILLEMOTLEFT = 0x00AB,
+ KEY_NOTSIGN = 0x00AC,
+ KEY_HYPHEN = 0x00AD,
+ KEY_REGISTERED = 0x00AE,
+ KEY_MACRON = 0x00AF,
+ KEY_DEGREE = 0x00B0,
+ KEY_PLUSMINUS = 0x00B1,
+ KEY_TWOSUPERIOR = 0x00B2,
+ KEY_THREESUPERIOR = 0x00B3,
+ KEY_ACUTE = 0x00B4,
+ KEY_MU = 0x00B5,
+ KEY_PARAGRAPH = 0x00B6,
+ KEY_PERIODCENTERED = 0x00B7,
+ KEY_CEDILLA = 0x00B8,
+ KEY_ONESUPERIOR = 0x00B9,
+ KEY_MASCULINE = 0x00BA,
+ KEY_GUILLEMOTRIGHT = 0x00BB,
+ KEY_ONEQUARTER = 0x00BC,
+ KEY_ONEHALF = 0x00BD,
+ KEY_THREEQUARTERS = 0x00BE,
+ KEY_QUESTIONDOWN = 0x00BF,
+ KEY_AGRAVE = 0x00C0,
+ KEY_AACUTE = 0x00C1,
+ KEY_ACIRCUMFLEX = 0x00C2,
+ KEY_ATILDE = 0x00C3,
+ KEY_ADIAERESIS = 0x00C4,
+ KEY_ARING = 0x00C5,
+ KEY_AE = 0x00C6,
+ KEY_CCEDILLA = 0x00C7,
+ KEY_EGRAVE = 0x00C8,
+ KEY_EACUTE = 0x00C9,
+ KEY_ECIRCUMFLEX = 0x00CA,
+ KEY_EDIAERESIS = 0x00CB,
+ KEY_IGRAVE = 0x00CC,
+ KEY_IACUTE = 0x00CD,
+ KEY_ICIRCUMFLEX = 0x00CE,
+ KEY_IDIAERESIS = 0x00CF,
+ KEY_ETH = 0x00D0,
+ KEY_NTILDE = 0x00D1,
+ KEY_OGRAVE = 0x00D2,
+ KEY_OACUTE = 0x00D3,
+ KEY_OCIRCUMFLEX = 0x00D4,
+ KEY_OTILDE = 0x00D5,
+ KEY_ODIAERESIS = 0x00D6,
+ KEY_MULTIPLY = 0x00D7,
+ KEY_OOBLIQUE = 0x00D8,
+ KEY_UGRAVE = 0x00D9,
+ KEY_UACUTE = 0x00DA,
+ KEY_UCIRCUMFLEX = 0x00DB,
+ KEY_UDIAERESIS = 0x00DC,
+ KEY_YACUTE = 0x00DD,
+ KEY_THORN = 0x00DE,
+ KEY_SSHARP = 0x00DF,
+ KEY_DIVISION = 0x00F7,
+ KEY_YDIAERESIS = 0x00FF,
};
-
enum KeyModifierMask {
- KEY_CODE_MASK=((1<<25)-1), ///< Apply this mask to any keycode to remove modifiers.
- KEY_MODIFIER_MASK=(0xFF<<24), ///< Apply this mask to isolate modifiers.
- KEY_MASK_SHIFT = (1<<25),
- KEY_MASK_ALT = (1<<26),
- KEY_MASK_META = (1<<27),
- KEY_MASK_CTRL = (1<<28),
+ KEY_CODE_MASK = ((1 << 25) - 1), ///< Apply this mask to any keycode to remove modifiers.
+ KEY_MODIFIER_MASK = (0xFF << 24), ///< Apply this mask to isolate modifiers.
+ KEY_MASK_SHIFT = (1 << 25),
+ KEY_MASK_ALT = (1 << 26),
+ KEY_MASK_META = (1 << 27),
+ KEY_MASK_CTRL = (1 << 28),
#ifdef APPLE_STYLE_KEYS
KEY_MASK_CMD = KEY_MASK_META,
#else
KEY_MASK_CMD = KEY_MASK_CTRL,
#endif
- KEY_MASK_KPAD = (1<<29),
- KEY_MASK_GROUP_SWITCH = (1<<30)
+ KEY_MASK_KPAD = (1 << 29),
+ KEY_MASK_GROUP_SWITCH = (1 << 30)
// bit 31 can't be used because variant uses regular 32 bits int as datatype
};
String keycode_get_string(uint32_t p_code);
bool keycode_has_unicode(uint32_t p_unicode);
-int find_keycode(const String& p_code);
+int find_keycode(const String &p_code);
int keycode_get_count();
int keycode_get_value_by_index(int p_index);
-const char* keycode_get_name_by_index(int p_index);
+const char *keycode_get_name_by_index(int p_index);
int latin_keyboard_keycode_convert(int p_keycode);
#endif
diff --git a/core/os/main_loop.cpp b/core/os/main_loop.cpp
index dcda8e8952..644536d940 100644
--- a/core/os/main_loop.cpp
+++ b/core/os/main_loop.cpp
@@ -31,20 +31,20 @@
void MainLoop::_bind_methods() {
- ClassDB::bind_method(D_METHOD("input_event","ev"),&MainLoop::input_event);
- ClassDB::bind_method(D_METHOD("input_text","text"),&MainLoop::input_text);
- ClassDB::bind_method(D_METHOD("init"),&MainLoop::init);
- ClassDB::bind_method(D_METHOD("iteration","delta"),&MainLoop::iteration);
- ClassDB::bind_method(D_METHOD("idle","delta"),&MainLoop::idle);
- ClassDB::bind_method(D_METHOD("finish"),&MainLoop::finish);
-
- BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::INPUT_EVENT,"ev")) );
- BIND_VMETHOD( MethodInfo("_input_text",PropertyInfo(Variant::STRING,"text")) );
- BIND_VMETHOD( MethodInfo("_initialize") );
- BIND_VMETHOD( MethodInfo("_iteration",PropertyInfo(Variant::REAL,"delta")) );
- BIND_VMETHOD( MethodInfo("_idle",PropertyInfo(Variant::REAL,"delta")) );
- BIND_VMETHOD( MethodInfo("_drop_files",PropertyInfo(Variant::POOL_STRING_ARRAY,"files"),PropertyInfo(Variant::INT,"screen")) );
- BIND_VMETHOD( MethodInfo("_finalize") );
+ ClassDB::bind_method(D_METHOD("input_event", "ev"), &MainLoop::input_event);
+ ClassDB::bind_method(D_METHOD("input_text", "text"), &MainLoop::input_text);
+ ClassDB::bind_method(D_METHOD("init"), &MainLoop::init);
+ ClassDB::bind_method(D_METHOD("iteration", "delta"), &MainLoop::iteration);
+ ClassDB::bind_method(D_METHOD("idle", "delta"), &MainLoop::idle);
+ ClassDB::bind_method(D_METHOD("finish"), &MainLoop::finish);
+
+ BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::INPUT_EVENT, "ev")));
+ BIND_VMETHOD(MethodInfo("_input_text", PropertyInfo(Variant::STRING, "text")));
+ BIND_VMETHOD(MethodInfo("_initialize"));
+ BIND_VMETHOD(MethodInfo("_iteration", PropertyInfo(Variant::REAL, "delta")));
+ BIND_VMETHOD(MethodInfo("_idle", PropertyInfo(Variant::REAL, "delta")));
+ BIND_VMETHOD(MethodInfo("_drop_files", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen")));
+ BIND_VMETHOD(MethodInfo("_finalize"));
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_ENTER);
BIND_CONSTANT(NOTIFICATION_WM_MOUSE_EXIT);
@@ -53,36 +53,29 @@ void MainLoop::_bind_methods() {
BIND_CONSTANT(NOTIFICATION_WM_QUIT_REQUEST);
BIND_CONSTANT(NOTIFICATION_WM_UNFOCUS_REQUEST);
BIND_CONSTANT(NOTIFICATION_OS_MEMORY_WARNING);
-
};
-void MainLoop::set_init_script(const Ref<Script>& p_init_script) {
+void MainLoop::set_init_script(const Ref<Script> &p_init_script) {
- init_script=p_init_script;
+ init_script = p_init_script;
}
MainLoop::MainLoop() {
}
-
-MainLoop::~MainLoop()
-{
+MainLoop::~MainLoop() {
}
-
-
-void MainLoop::input_text( const String& p_text ) {
+void MainLoop::input_text(const String &p_text) {
if (get_script_instance())
- get_script_instance()->call("_input_text",p_text);
-
+ get_script_instance()->call("_input_text", p_text);
}
-void MainLoop::input_event( const InputEvent& p_event ) {
+void MainLoop::input_event(const InputEvent &p_event) {
if (get_script_instance())
- get_script_instance()->call("_input_event",p_event);
-
+ get_script_instance()->call("_input_event", p_event);
}
void MainLoop::init() {
@@ -92,30 +85,26 @@ void MainLoop::init() {
if (get_script_instance())
get_script_instance()->call("_initialize");
-
}
bool MainLoop::iteration(float p_time) {
if (get_script_instance())
- return get_script_instance()->call("_iteration",p_time);
+ return get_script_instance()->call("_iteration", p_time);
return false;
-
}
bool MainLoop::idle(float p_time) {
if (get_script_instance())
- return get_script_instance()->call("_idle",p_time);
+ return get_script_instance()->call("_idle", p_time);
return false;
}
-void MainLoop::drop_files(const Vector<String>& p_files,int p_from_screen) {
-
+void MainLoop::drop_files(const Vector<String> &p_files, int p_from_screen) {
if (get_script_instance())
- get_script_instance()->call("_drop_files",p_files,p_from_screen);
-
+ get_script_instance()->call("_drop_files", p_files, p_from_screen);
}
void MainLoop::finish() {
@@ -124,7 +113,4 @@ void MainLoop::finish() {
get_script_instance()->call("_finalize");
set_script(RefPtr()); //clear script
}
-
-
}
-
diff --git a/core/os/main_loop.h b/core/os/main_loop.h
index 456a6be4d3..a33aeb9762 100644
--- a/core/os/main_loop.h
+++ b/core/os/main_loop.h
@@ -37,15 +37,15 @@
*/
class MainLoop : public Object {
- GDCLASS( MainLoop, Object );
+ GDCLASS(MainLoop, Object);
OBJ_CATEGORY("Main Loop");
Ref<Script> init_script;
+
protected:
static void _bind_methods();
public:
-
enum {
NOTIFICATION_WM_MOUSE_ENTER = 2,
NOTIFICATION_WM_MOUSE_EXIT = 3,
@@ -58,22 +58,20 @@ public:
NOTIFICATION_TRANSLATION_CHANGED = 10,
};
- virtual void input_event( const InputEvent& p_event );
- virtual void input_text( const String& p_text );
+ virtual void input_event(const InputEvent &p_event);
+ virtual void input_text(const String &p_text);
virtual void init();
virtual bool iteration(float p_time);
virtual bool idle(float p_time);
virtual void finish();
- virtual void drop_files(const Vector<String>& p_files,int p_from_screen=0);
+ virtual void drop_files(const Vector<String> &p_files, int p_from_screen = 0);
- void set_init_script(const Ref<Script>& p_init_script);
+ void set_init_script(const Ref<Script> &p_init_script);
MainLoop();
virtual ~MainLoop();
-
-
};
#endif
diff --git a/core/os/memory.cpp b/core/os/memory.cpp
index 37a523b763..b6866561fc 100644
--- a/core/os/memory.cpp
+++ b/core/os/memory.cpp
@@ -27,19 +27,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "memory.h"
-#include "error_macros.h"
#include "copymem.h"
+#include "error_macros.h"
#include <stdio.h>
#include <stdlib.h>
+void *operator new(size_t p_size, const char *p_description) {
-
-void * operator new(size_t p_size,const char *p_description) {
-
- return Memory::alloc_static( p_size, false );
+ return Memory::alloc_static(p_size, false);
}
-void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)) {
+void *operator new(size_t p_size, void *(*p_allocfunc)(size_t p_size)) {
return p_allocfunc(p_size);
}
@@ -47,38 +45,36 @@ void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)) {
#include <stdio.h>
#ifdef DEBUG_ENABLED
-size_t Memory::mem_usage=0;
-size_t Memory::max_usage=0;
+size_t Memory::mem_usage = 0;
+size_t Memory::max_usage = 0;
#endif
-size_t Memory::alloc_count=0;
-
-
-void * Memory::alloc_static(size_t p_bytes,bool p_pad_align) {
+size_t Memory::alloc_count = 0;
+void *Memory::alloc_static(size_t p_bytes, bool p_pad_align) {
#ifdef DEBUG_ENABLED
- bool prepad=true;
+ bool prepad = true;
#else
- bool prepad=p_pad_align;
+ bool prepad = p_pad_align;
#endif
- void * mem = malloc( p_bytes + (prepad?PAD_ALIGN:0));
+ void *mem = malloc(p_bytes + (prepad ? PAD_ALIGN : 0));
alloc_count++;
- ERR_FAIL_COND_V(!mem,NULL);
+ ERR_FAIL_COND_V(!mem, NULL);
if (prepad) {
- uint64_t *s = (uint64_t*)mem;
- *s=p_bytes;
+ uint64_t *s = (uint64_t *)mem;
+ *s = p_bytes;
- uint8_t *s8 = (uint8_t*)mem;
+ uint8_t *s8 = (uint8_t *)mem;
#ifdef DEBUG_ENABLED
- mem_usage+=p_bytes;
- if (mem_usage>max_usage) {
- max_usage=mem_usage;
+ mem_usage += p_bytes;
+ if (mem_usage > max_usage) {
+ max_usage = mem_usage;
}
#endif
return s8 + PAD_ALIGN;
@@ -87,74 +83,74 @@ void * Memory::alloc_static(size_t p_bytes,bool p_pad_align) {
}
}
-void * Memory::realloc_static(void *p_memory,size_t p_bytes,bool p_pad_align) {
+void *Memory::realloc_static(void *p_memory, size_t p_bytes, bool p_pad_align) {
- if (p_memory==NULL) {
- return alloc_static(p_bytes,p_pad_align);
+ if (p_memory == NULL) {
+ return alloc_static(p_bytes, p_pad_align);
}
- uint8_t *mem = (uint8_t*)p_memory;
+ uint8_t *mem = (uint8_t *)p_memory;
#ifdef DEBUG_ENABLED
- bool prepad=true;
+ bool prepad = true;
#else
- bool prepad=p_pad_align;
+ bool prepad = p_pad_align;
#endif
if (prepad) {
- mem-=PAD_ALIGN;
- uint64_t *s = (uint64_t*)mem;
+ mem -= PAD_ALIGN;
+ uint64_t *s = (uint64_t *)mem;
#ifdef DEBUG_ENABLED
- mem_usage-=*s;
- mem_usage+=p_bytes;
+ mem_usage -= *s;
+ mem_usage += p_bytes;
#endif
- if (p_bytes==0) {
+ if (p_bytes == 0) {
free(mem);
return NULL;
} else {
- *s=p_bytes;
+ *s = p_bytes;
- mem = (uint8_t*)realloc(mem,p_bytes+PAD_ALIGN);
- ERR_FAIL_COND_V(!mem,NULL);
+ mem = (uint8_t *)realloc(mem, p_bytes + PAD_ALIGN);
+ ERR_FAIL_COND_V(!mem, NULL);
- s = (uint64_t*)mem;
+ s = (uint64_t *)mem;
- *s=p_bytes;
+ *s = p_bytes;
- return mem+PAD_ALIGN;
+ return mem + PAD_ALIGN;
}
} else {
- mem = (uint8_t*)realloc(mem,p_bytes);
+ mem = (uint8_t *)realloc(mem, p_bytes);
- ERR_FAIL_COND_V(mem==NULL && p_bytes>0,NULL);
+ ERR_FAIL_COND_V(mem == NULL && p_bytes > 0, NULL);
return mem;
}
}
-void Memory::free_static(void *p_ptr,bool p_pad_align) {
+void Memory::free_static(void *p_ptr, bool p_pad_align) {
- ERR_FAIL_COND(p_ptr==NULL);
+ ERR_FAIL_COND(p_ptr == NULL);
- uint8_t *mem = (uint8_t*)p_ptr;
+ uint8_t *mem = (uint8_t *)p_ptr;
#ifdef DEBUG_ENABLED
- bool prepad=true;
+ bool prepad = true;
#else
- bool prepad=p_pad_align;
+ bool prepad = p_pad_align;
#endif
alloc_count--;
if (prepad) {
- mem-=PAD_ALIGN;
- uint64_t *s = (uint64_t*)mem;
+ mem -= PAD_ALIGN;
+ uint64_t *s = (uint64_t *)mem;
#ifdef DEBUG_ENABLED
- mem_usage-=*s;
+ mem_usage -= *s;
#endif
free(mem);
@@ -162,23 +158,21 @@ void Memory::free_static(void *p_ptr,bool p_pad_align) {
free(mem);
}
-
}
size_t Memory::get_mem_available() {
return 0xFFFFFFFFFFFFF;
-
}
-size_t Memory::get_mem_usage(){
+size_t Memory::get_mem_usage() {
#ifdef DEBUG_ENABLED
return mem_usage;
#else
return 0;
#endif
}
-size_t Memory::get_mem_max_usage(){
+size_t Memory::get_mem_max_usage() {
#ifdef DEBUG_ENABLED
return max_usage;
#else
@@ -186,16 +180,12 @@ size_t Memory::get_mem_max_usage(){
#endif
}
-
-
-
_GlobalNil::_GlobalNil() {
- color=1;
- left=this;
- right=this;
- parent=this;
+ color = 1;
+ left = this;
+ right = this;
+ parent = this;
}
_GlobalNil _GlobalNilClass::_nil;
-
diff --git a/core/os/memory.h b/core/os/memory.h
index 49424037ff..b788068f53 100644
--- a/core/os/memory.h
+++ b/core/os/memory.h
@@ -29,9 +29,8 @@
#ifndef MEMORY_H
#define MEMORY_H
-#include <stddef.h>
#include "safe_refcount.h"
-
+#include <stddef.h>
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -41,9 +40,7 @@
#define PAD_ALIGN 16 //must always be greater than this at much
#endif
-
-
-class Memory{
+class Memory {
Memory();
#ifdef DEBUG_ENABLED
@@ -54,72 +51,65 @@ class Memory{
static size_t alloc_count;
public:
-
- static void * alloc_static(size_t p_bytes,bool p_pad_align=false);
- static void * realloc_static(void *p_memory,size_t p_bytes,bool p_pad_align=false);
- static void free_static(void *p_ptr,bool p_pad_align=false);
+ static void *alloc_static(size_t p_bytes, bool p_pad_align = false);
+ static void *realloc_static(void *p_memory, size_t p_bytes, bool p_pad_align = false);
+ static void free_static(void *p_ptr, bool p_pad_align = false);
static size_t get_mem_available();
static size_t get_mem_usage();
static size_t get_mem_max_usage();
-
-
};
class DefaultAllocator {
public:
_FORCE_INLINE_ static void *alloc(size_t p_memory) { return Memory::alloc_static(p_memory, false); }
- _FORCE_INLINE_ static void free(void *p_ptr) { return Memory::free_static(p_ptr,false); }
-
+ _FORCE_INLINE_ static void free(void *p_ptr) { return Memory::free_static(p_ptr, false); }
};
+void *operator new(size_t p_size, const char *p_description); ///< operator new that takes a description and uses MemoryStaticPool
+void *operator new(size_t p_size, void *(*p_allocfunc)(size_t p_size)); ///< operator new that takes a description and uses MemoryStaticPool
-void * operator new(size_t p_size,const char *p_description); ///< operator new that takes a description and uses MemoryStaticPool
-void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)); ///< operator new that takes a description and uses MemoryStaticPool
-
-void * operator new(size_t p_size,void *p_pointer,size_t check, const char *p_description); ///< operator new that takes a description and uses a pointer to the preallocated memory
+void *operator new(size_t p_size, void *p_pointer, size_t check, const char *p_description); ///< operator new that takes a description and uses a pointer to the preallocated memory
#define memalloc(m_size) Memory::alloc_static(m_size)
-#define memrealloc(m_mem,m_size) Memory::realloc_static(m_mem,m_size)
+#define memrealloc(m_mem, m_size) Memory::realloc_static(m_mem, m_size)
#define memfree(m_size) Memory::free_static(m_size)
-
_ALWAYS_INLINE_ void postinitialize_handler(void *) {}
-
-template<class T>
+template <class T>
_ALWAYS_INLINE_ T *_post_initialize(T *p_obj) {
postinitialize_handler(p_obj);
return p_obj;
}
-#define memnew(m_class) _post_initialize(new("") m_class)
+#define memnew(m_class) _post_initialize(new ("") m_class)
-_ALWAYS_INLINE_ void * operator new(size_t p_size,void *p_pointer,size_t check, const char *p_description) {
+_ALWAYS_INLINE_ void *operator new(size_t p_size, void *p_pointer, size_t check, const char *p_description) {
//void *failptr=0;
//ERR_FAIL_COND_V( check < p_size , failptr); /** bug, or strange compiler, most likely */
return p_pointer;
}
+#define memnew_allocator(m_class, m_allocator) _post_initialize(new (m_allocator::alloc) m_class)
+#define memnew_placement(m_placement, m_class) _post_initialize(new (m_placement, sizeof(m_class), "") m_class)
-#define memnew_allocator(m_class,m_allocator) _post_initialize(new(m_allocator::alloc) m_class)
-#define memnew_placement(m_placement,m_class) _post_initialize(new(m_placement,sizeof(m_class),"") m_class)
-
-
-_ALWAYS_INLINE_ bool predelete_handler(void *) { return true; }
+_ALWAYS_INLINE_ bool predelete_handler(void *) {
+ return true;
+}
-template<class T>
+template <class T>
void memdelete(T *p_class) {
if (!predelete_handler(p_class))
return; // doesn't want to be deleted
p_class->~T();
- Memory::free_static(p_class,false);
+ Memory::free_static(p_class, false);
}
-template<class T,class A>
+template <class T, class A>
void memdelete_allocator(T *p_class) {
if (!predelete_handler(p_class))
@@ -128,33 +118,35 @@ void memdelete_allocator(T *p_class) {
A::free(p_class);
}
-#define memdelete_notnull(m_v) { if (m_v) memdelete(m_v); }
-
-#define memnew_arr( m_class, m_count ) memnew_arr_template<m_class>(m_count)
+#define memdelete_notnull(m_v) \
+ { \
+ if (m_v) memdelete(m_v); \
+ }
+#define memnew_arr(m_class, m_count) memnew_arr_template<m_class>(m_count)
-template<typename T>
-T* memnew_arr_template(size_t p_elements,const char *p_descr="") {
+template <typename T>
+T *memnew_arr_template(size_t p_elements, const char *p_descr = "") {
- if (p_elements==0)
+ if (p_elements == 0)
return 0;
/** overloading operator new[] cannot be done , because it may not return the real allocated address (it may pad the 'element count' before the actual array). Because of that, it must be done by hand. This is the
same strategy used by std::vector, and the PoolVector class, so it should be safe.*/
size_t len = sizeof(T) * p_elements;
- uint64_t *mem = (uint64_t*)Memory::alloc_static( len , true );
- T *failptr=0; //get rid of a warning
- ERR_FAIL_COND_V( !mem, failptr );
- *(mem-1)=p_elements;
+ uint64_t *mem = (uint64_t *)Memory::alloc_static(len, true);
+ T *failptr = 0; //get rid of a warning
+ ERR_FAIL_COND_V(!mem, failptr);
+ *(mem - 1) = p_elements;
- T* elems = (T*)mem;
+ T *elems = (T *)mem;
/* call operator new */
- for (size_t i=0;i<p_elements;i++) {
- new(&elems[i],sizeof(T),p_descr) T;
+ for (size_t i = 0; i < p_elements; i++) {
+ new (&elems[i], sizeof(T), p_descr) T;
}
- return (T*)mem;
+ return (T *)mem;
}
/**
@@ -162,28 +154,27 @@ T* memnew_arr_template(size_t p_elements,const char *p_descr="") {
* an allocated-with memnew_arr() array
*/
-template<typename T>
+template <typename T>
size_t memarr_len(const T *p_class) {
- uint64_t* ptr = (uint64_t*)p_class;
- return *(ptr-1);
+ uint64_t *ptr = (uint64_t *)p_class;
+ return *(ptr - 1);
}
-template<typename T>
+template <typename T>
void memdelete_arr(T *p_class) {
- uint64_t* ptr = (uint64_t*)p_class;
+ uint64_t *ptr = (uint64_t *)p_class;
- uint64_t elem_count = *(ptr-1);
+ uint64_t elem_count = *(ptr - 1);
- for (uint64_t i=0;i<elem_count;i++) {
+ for (uint64_t i = 0; i < elem_count; i++) {
p_class[i].~T();
};
- Memory::free_static(ptr,true);
+ Memory::free_static(ptr, true);
}
-
struct _GlobalNil {
int color;
@@ -192,7 +183,6 @@ struct _GlobalNil {
_GlobalNil *parent;
_GlobalNil();
-
};
struct _GlobalNilClass {
@@ -200,6 +190,4 @@ struct _GlobalNilClass {
static _GlobalNil _nil;
};
-
-
#endif
diff --git a/core/os/mutex.cpp b/core/os/mutex.cpp
index acdcb492d9..cdc18effdd 100644
--- a/core/os/mutex.cpp
+++ b/core/os/mutex.cpp
@@ -30,24 +30,19 @@
#include "error_macros.h"
#include <stddef.h>
-
-
-Mutex* (*Mutex::create_func)(bool)=0;
+Mutex *(*Mutex::create_func)(bool) = 0;
Mutex *Mutex::create(bool p_recursive) {
- ERR_FAIL_COND_V( !create_func, 0 );
+ ERR_FAIL_COND_V(!create_func, 0);
return create_func(p_recursive);
}
-
Mutex::~Mutex() {
-
-
}
-Mutex *_global_mutex=NULL;
+Mutex *_global_mutex = NULL;
void _global_lock() {
@@ -59,4 +54,3 @@ void _global_unlock() {
if (_global_mutex)
_global_mutex->unlock();
}
-
diff --git a/core/os/mutex.h b/core/os/mutex.h
index a1004965bb..8ec4f573b7 100644
--- a/core/os/mutex.h
+++ b/core/os/mutex.h
@@ -31,7 +31,6 @@
#include "error_list.h"
-
/**
* @class Mutex
* @author Juan Linietsky
@@ -41,18 +40,16 @@
* Lockp( mutex );
*/
-
class Mutex {
protected:
- static Mutex* (*create_func)(bool);
+ static Mutex *(*create_func)(bool);
public:
+ virtual void lock() = 0; ///< Lock the mutex, block if locked by someone else
+ virtual void unlock() = 0; ///< Unlock the mutex, let other threads continue
+ virtual Error try_lock() = 0; ///< Attempt to lock the mutex, OK on success, ERROR means it can't lock.
- virtual void lock()=0; ///< Lock the mutex, block if locked by someone else
- virtual void unlock()=0; ///< Unlock the mutex, let other threads continue
- virtual Error try_lock()=0; ///< Attempt to lock the mutex, OK on success, ERROR means it can't lock.
-
- static Mutex * create(bool p_recursive=true); ///< Create a mutex
+ static Mutex *create(bool p_recursive = true); ///< Create a mutex
virtual ~Mutex();
};
@@ -60,11 +57,15 @@ public:
class MutexLock {
Mutex *mutex;
-public:
-
- MutexLock(Mutex* p_mutex) { mutex=p_mutex; if (mutex) mutex->lock(); }
- ~MutexLock() { if (mutex) mutex->unlock(); }
+public:
+ MutexLock(Mutex *p_mutex) {
+ mutex = p_mutex;
+ if (mutex) mutex->lock();
+ }
+ ~MutexLock() {
+ if (mutex) mutex->unlock();
+ }
};
#endif
diff --git a/core/os/os.cpp b/core/os/os.cpp
index 1d670b4466..03b48f4554 100644
--- a/core/os/os.cpp
+++ b/core/os/os.cpp
@@ -35,15 +35,16 @@
#include <stdarg.h>
-OS* OS::singleton=NULL;
+OS *OS::singleton = NULL;
-OS* OS::get_singleton() {
+OS *OS::get_singleton() {
return singleton;
}
-uint32_t OS::get_ticks_msec() const
-{ return get_ticks_usec()/1000; }
+uint32_t OS::get_ticks_msec() const {
+ return get_ticks_usec() / 1000;
+}
uint64_t OS::get_splash_tick_msec() const {
return _msec_splash;
@@ -55,29 +56,27 @@ uint64_t OS::get_unix_time() const {
uint64_t OS::get_system_time_secs() const {
return 0;
}
-void OS::debug_break() {
+void OS::debug_break(){
// something
};
+void OS::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
-void OS::print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type) {
-
- const char* err_type;
- switch(p_type) {
- case ERR_ERROR: err_type="**ERROR**"; break;
- case ERR_WARNING: err_type="**WARNING**"; break;
- case ERR_SCRIPT: err_type="**SCRIPT ERROR**"; break;
- case ERR_SHADER: err_type="**SHADER ERROR**"; break;
+ const char *err_type;
+ switch (p_type) {
+ case ERR_ERROR: err_type = "**ERROR**"; break;
+ case ERR_WARNING: err_type = "**WARNING**"; break;
+ case ERR_SCRIPT: err_type = "**SCRIPT ERROR**"; break;
+ case ERR_SHADER: err_type = "**SHADER ERROR**"; break;
}
if (p_rationale && *p_rationale)
- print("%s: %s\n ",err_type,p_rationale);
- print("%s: At: %s:%i:%s() - %s\n",err_type,p_file,p_line,p_function,p_code);
+ print("%s: %s\n ", err_type, p_rationale);
+ print("%s: At: %s:%i:%s() - %s\n", err_type, p_file, p_line, p_function, p_code);
}
-void OS::print(const char* p_format, ...) {
-
+void OS::print(const char *p_format, ...) {
va_list argp;
va_start(argp, p_format);
@@ -87,7 +86,7 @@ void OS::print(const char* p_format, ...) {
va_end(argp);
};
-void OS::printerr(const char* p_format, ...) {
+void OS::printerr(const char *p_format, ...) {
va_list argp;
va_start(argp, p_format);
@@ -97,9 +96,8 @@ void OS::printerr(const char* p_format, ...) {
va_end(argp);
};
-
void OS::set_keep_screen_on(bool p_enabled) {
- _keep_screen_on=p_enabled;
+ _keep_screen_on = p_enabled;
}
bool OS::is_keep_screen_on() const {
@@ -108,7 +106,7 @@ bool OS::is_keep_screen_on() const {
void OS::set_low_processor_usage_mode(bool p_enabled) {
- low_processor_usage_mode=p_enabled;
+ low_processor_usage_mode = p_enabled;
}
bool OS::is_in_low_processor_usage_mode() const {
@@ -116,9 +114,9 @@ bool OS::is_in_low_processor_usage_mode() const {
return low_processor_usage_mode;
}
-void OS::set_clipboard(const String& p_text) {
+void OS::set_clipboard(const String &p_text) {
- _local_clipboard=p_text;
+ _local_clipboard = p_text;
}
String OS::get_clipboard() const {
@@ -135,41 +133,40 @@ int OS::get_process_ID() const {
return -1;
};
-
bool OS::is_stdout_verbose() const {
return _verbose_stdout;
}
-void OS::set_last_error(const char* p_error) {
+void OS::set_last_error(const char *p_error) {
GLOBAL_LOCK_FUNCTION
- if (p_error==NULL)
- p_error="Unknown Error";
+ if (p_error == NULL)
+ p_error = "Unknown Error";
if (last_error)
memfree(last_error);
- last_error=NULL;
- int len =0;
- while(p_error[len++]);
-
- last_error=(char*)memalloc(len);
- for(int i=0;i<len;i++)
- last_error[i]=p_error[i];
+ last_error = NULL;
+ int len = 0;
+ while (p_error[len++])
+ ;
+ last_error = (char *)memalloc(len);
+ for (int i = 0; i < len; i++)
+ last_error[i] = p_error[i];
}
const char *OS::get_last_error() const {
GLOBAL_LOCK_FUNCTION
- return last_error?last_error:"";
+ return last_error ? last_error : "";
}
-void OS::dump_memory_to_file(const char* p_file) {
+void OS::dump_memory_to_file(const char *p_file) {
//Memory::dump_static_mem_to_file(p_file);
}
-static FileAccess *_OSPRF=NULL;
+static FileAccess *_OSPRF = NULL;
static void _OS_printres(Object *p_obj) {
@@ -177,12 +174,11 @@ static void _OS_printres(Object *p_obj) {
if (!res)
return;
- String str = itos(res->get_instance_ID())+String(res->get_class())+":"+String(res->get_name())+" - "+res->get_path();
+ String str = itos(res->get_instance_ID()) + String(res->get_class()) + ":" + String(res->get_name()) + " - " + res->get_path();
if (_OSPRF)
_OSPRF->store_line(str);
else
print_line(str);
-
}
bool OS::has_virtual_keyboard() const {
@@ -190,61 +186,56 @@ bool OS::has_virtual_keyboard() const {
return false;
}
-void OS::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) {
-
+void OS::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
}
-void OS::hide_virtual_keyboard(){
-
+void OS::hide_virtual_keyboard() {
}
void OS::print_all_resources(String p_to_file) {
- ERR_FAIL_COND(p_to_file!="" && _OSPRF);
- if (p_to_file!="") {
+ ERR_FAIL_COND(p_to_file != "" && _OSPRF);
+ if (p_to_file != "") {
Error err;
- _OSPRF=FileAccess::open(p_to_file,FileAccess::WRITE,&err);
- if (err!=OK) {
- _OSPRF=NULL;
- ERR_FAIL_COND(err!=OK);
+ _OSPRF = FileAccess::open(p_to_file, FileAccess::WRITE, &err);
+ if (err != OK) {
+ _OSPRF = NULL;
+ ERR_FAIL_COND(err != OK);
}
}
ObjectDB::debug_objects(_OS_printres);
- if (p_to_file!="") {
+ if (p_to_file != "") {
if (_OSPRF)
memdelete(_OSPRF);
- _OSPRF=NULL;
+ _OSPRF = NULL;
}
}
void OS::print_resources_in_use(bool p_short) {
-
- ResourceCache::dump(NULL,p_short);
+ ResourceCache::dump(NULL, p_short);
}
-void OS::dump_resources_to_file(const char* p_file) {
+void OS::dump_resources_to_file(const char *p_file) {
ResourceCache::dump(p_file);
}
-
void OS::clear_last_error() {
GLOBAL_LOCK_FUNCTION
if (last_error)
memfree(last_error);
- last_error=NULL;
+ last_error = NULL;
}
-
void OS::set_no_window_mode(bool p_enable) {
- _no_window=p_enable;
+ _no_window = p_enable;
}
bool OS::is_no_window_mode_enabled() const {
@@ -258,7 +249,7 @@ int OS::get_exit_code() const {
}
void OS::set_exit_code(int p_code) {
- _exit_code=p_code;
+ _exit_code = p_code;
}
String OS::get_locale() const {
@@ -271,7 +262,6 @@ String OS::get_resource_dir() const {
return GlobalConfig::get_singleton()->get_resource_path();
}
-
String OS::get_system_dir(SystemDir p_dir) const {
return ".";
@@ -280,8 +270,8 @@ String OS::get_system_dir(SystemDir p_dir) const {
String OS::get_safe_application_name() const {
String an = GlobalConfig::get_singleton()->get("application/name");
Vector<String> invalid_char = String("\\ / : * ? \" < > |").split(" ");
- for (int i=0;i<invalid_char.size();i++) {
- an = an.replace(invalid_char[i],"-");
+ for (int i = 0; i < invalid_char.size(); i++) {
+ an = an.replace(invalid_char[i], "-");
}
return an;
}
@@ -296,14 +286,14 @@ Error OS::shell_open(String p_uri) {
};
// implement these with the canvas?
-Error OS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object* p_obj, String p_callback) {
+Error OS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object *p_obj, String p_callback) {
while (true) {
print("%ls\n--------\n%ls\n", p_title.c_str(), p_description.c_str());
- for (int i=0; i<p_buttons.size(); i++) {
- if (i>0) print(", ");
- print("%i=%ls", i+1, p_buttons[i].c_str());
+ for (int i = 0; i < p_buttons.size(); i++) {
+ if (i > 0) print(", ");
+ print("%i=%ls", i + 1, p_buttons[i].c_str());
};
print("\n");
String res = get_stdin_string().strip_edges();
@@ -319,7 +309,7 @@ Error OS::dialog_show(String p_title, String p_description, Vector<String> p_but
return OK;
};
-Error OS::dialog_input_text(String p_title, String p_description, String p_partial, Object* p_obj, String p_callback) {
+Error OS::dialog_input_text(String p_title, String p_description, String p_partial, Object *p_obj, String p_callback) {
ERR_FAIL_COND_V(!p_obj, FAILED);
ERR_FAIL_COND_V(p_callback == "", FAILED);
@@ -340,7 +330,7 @@ int OS::get_static_memory_usage() const {
return Memory::get_mem_usage();
}
-int OS::get_dynamic_memory_usage() const{
+int OS::get_dynamic_memory_usage() const {
return MemoryPool::total_memory;
}
@@ -350,7 +340,7 @@ int OS::get_static_memory_peak_usage() const {
return Memory::get_mem_max_usage();
}
-Error OS::set_cwd(const String& p_cwd) {
+Error OS::set_cwd(const String &p_cwd) {
return ERR_CANT_OPEN;
}
@@ -367,13 +357,11 @@ int OS::get_free_static_memory() const {
}
void OS::yield() {
-
-
}
void OS::set_screen_orientation(ScreenOrientation p_orientation) {
- _orientation=p_orientation;
+ _orientation = p_orientation;
}
OS::ScreenOrientation OS::get_screen_orientation() const {
@@ -381,7 +369,6 @@ OS::ScreenOrientation OS::get_screen_orientation() const {
return (OS::ScreenOrientation)_orientation;
}
-
void OS::_ensure_data_dir() {
String dd = get_data_dir();
@@ -393,45 +380,35 @@ void OS::_ensure_data_dir() {
da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
Error err = da->make_dir_recursive(dd);
- if (err!=OK) {
- ERR_EXPLAIN("Error attempting to create data dir: "+dd);
+ if (err != OK) {
+ ERR_EXPLAIN("Error attempting to create data dir: " + dd);
}
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
memdelete(da);
-
-
}
-void OS::set_icon(const Image& p_icon) {
-
-
+void OS::set_icon(const Image &p_icon) {
}
String OS::get_model_name() const {
- return "GenericDevice";
+ return "GenericDevice";
}
-
-void OS::set_cmdline(const char* p_execpath, const List<String>& p_args) {
+void OS::set_cmdline(const char *p_execpath, const List<String> &p_args) {
_execpath = p_execpath;
_cmdline = p_args;
};
void OS::release_rendering_thread() {
-
-
}
void OS::make_rendering_thread() {
-
-
}
void OS::swap_buffers() {
-
}
String OS::get_unique_ID() const {
@@ -454,20 +431,19 @@ bool OS::native_video_is_playing() const {
return false;
};
-void OS::native_video_pause() {
+void OS::native_video_pause(){
};
-void OS::native_video_unpause() {
+void OS::native_video_unpause(){
};
-void OS::native_video_stop() {
+void OS::native_video_stop(){
};
void OS::set_mouse_mode(MouseMode p_mode) {
-
}
bool OS::can_use_threads() const {
@@ -479,19 +455,16 @@ bool OS::can_use_threads() const {
#endif
}
-OS::MouseMode OS::get_mouse_mode() const{
+OS::MouseMode OS::get_mouse_mode() const {
return MOUSE_MODE_VISIBLE;
}
-
OS::LatinKeyboardVariant OS::get_latin_keyboard_variant() const {
return LATIN_KEYBOARD_QWERTY;
}
-
-
bool OS::is_joy_known(int p_device) {
return true;
}
@@ -501,18 +474,15 @@ String OS::get_joy_guid(int p_device) const {
}
void OS::set_context(int p_context) {
-
}
void OS::set_use_vsync(bool p_enable) {
-
}
-bool OS::is_vsync_enabled() const{
+bool OS::is_vsync_enabled() const {
return true;
}
-
PowerState OS::get_power_state() {
return POWERSTATE_UNKNOWN;
}
@@ -524,26 +494,22 @@ int OS::get_power_percent_left() {
}
OS::OS() {
- last_error=NULL;
- singleton=this;
- _keep_screen_on=true; // set default value to true, because this had been true before godot 2.0.
- low_processor_usage_mode=false;
- _verbose_stdout=false;
- _no_window=false;
- _exit_code=0;
- _orientation=SCREEN_LANDSCAPE;
-
- _render_thread_mode=RENDER_THREAD_SAFE;
-
-
- _allow_hidpi=true;
+ last_error = NULL;
+ singleton = this;
+ _keep_screen_on = true; // set default value to true, because this had been true before godot 2.0.
+ low_processor_usage_mode = false;
+ _verbose_stdout = false;
+ _no_window = false;
+ _exit_code = 0;
+ _orientation = SCREEN_LANDSCAPE;
+
+ _render_thread_mode = RENDER_THREAD_SAFE;
+
+ _allow_hidpi = true;
Math::seed(1234567);
}
-
OS::~OS() {
- singleton=NULL;
+ singleton = NULL;
}
-
-
diff --git a/core/os/os.h b/core/os/os.h
index 7c8100679a..46e57e5186 100644
--- a/core/os/os.h
+++ b/core/os/os.h
@@ -29,22 +29,21 @@
#ifndef OS_H
#define OS_H
-#include "ustring.h"
-#include "list.h"
-#include "vector.h"
#include "engine.h"
+#include "list.h"
#include "os/main_loop.h"
#include "power.h"
+#include "ustring.h"
+#include "vector.h"
#include <stdarg.h>
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class OS {
- static OS* singleton;
+ static OS *singleton;
String _execpath;
List<String> _cmdline;
bool _keep_screen_on;
@@ -57,7 +56,6 @@ class OS {
int _orientation;
bool _allow_hidpi;
-
char *last_error;
public:
@@ -69,45 +67,51 @@ public:
};
struct VideoMode {
- int width,height;
+ int width, height;
bool fullscreen;
bool resizable;
bool borderless_window;
- float get_aspect() const { return (float)width/(float)height; }
- VideoMode(int p_width=1024,int p_height=600,bool p_fullscreen=false, bool p_resizable = true,bool p_borderless_window=false) { width=p_width; height=p_height; fullscreen=p_fullscreen; resizable = p_resizable; borderless_window=p_borderless_window; }
+ float get_aspect() const { return (float)width / (float)height; }
+ VideoMode(int p_width = 1024, int p_height = 600, bool p_fullscreen = false, bool p_resizable = true, bool p_borderless_window = false) {
+ width = p_width;
+ height = p_height;
+ fullscreen = p_fullscreen;
+ resizable = p_resizable;
+ borderless_window = p_borderless_window;
+ }
};
+
protected:
-friend class Main;
+ friend class Main;
RenderThreadMode _render_thread_mode;
// functions used by main to initialize/deintialize the OS
- virtual int get_video_driver_count() const=0;
- virtual const char * get_video_driver_name(int p_driver) const=0;
+ virtual int get_video_driver_count() const = 0;
+ virtual const char *get_video_driver_name(int p_driver) const = 0;
- virtual VideoMode get_default_video_mode() const=0;
+ virtual VideoMode get_default_video_mode() const = 0;
- virtual int get_audio_driver_count() const=0;
- virtual const char * get_audio_driver_name(int p_driver) const=0;
+ virtual int get_audio_driver_count() const = 0;
+ virtual const char *get_audio_driver_name(int p_driver) const = 0;
- virtual void initialize_core()=0;
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver)=0;
+ virtual void initialize_core() = 0;
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) = 0;
- virtual void set_main_loop( MainLoop * p_main_loop )=0;
- virtual void delete_main_loop()=0;
+ virtual void set_main_loop(MainLoop *p_main_loop) = 0;
+ virtual void delete_main_loop() = 0;
- virtual void finalize()=0;
- virtual void finalize_core()=0;
+ virtual void finalize() = 0;
+ virtual void finalize_core() = 0;
- virtual void set_cmdline(const char* p_execpath, const List<String>& p_args);
+ virtual void set_cmdline(const char *p_execpath, const List<String> &p_args);
void _ensure_data_dir();
public:
-
typedef int64_t ProcessID;
- static OS* get_singleton();
+ static OS *get_singleton();
enum ErrorType {
ERR_ERROR,
@@ -116,20 +120,18 @@ public:
ERR_SHADER
};
- virtual void print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type=ERR_ERROR);
+ virtual void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR);
- virtual void print(const char *p_format, ... );
- virtual void printerr(const char *p_format, ... );
- virtual void vprint(const char* p_format, va_list p_list, bool p_stderr=false)=0;
- virtual void alert(const String& p_alert,const String& p_title="ALERT!")=0;
- virtual String get_stdin_string(bool p_block = true)=0;
+ virtual void print(const char *p_format, ...);
+ virtual void printerr(const char *p_format, ...);
+ virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false) = 0;
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!") = 0;
+ virtual String get_stdin_string(bool p_block = true) = 0;
- virtual void set_last_error(const char* p_error);
+ virtual void set_last_error(const char *p_error);
virtual const char *get_last_error() const;
virtual void clear_last_error();
-
-
enum MouseMode {
MOUSE_MODE_VISIBLE,
MOUSE_MODE_HIDDEN,
@@ -140,30 +142,28 @@ public:
virtual void set_mouse_mode(MouseMode p_mode);
virtual MouseMode get_mouse_mode() const;
+ virtual void warp_mouse_pos(const Point2 &p_to) {}
+ virtual Point2 get_mouse_pos() const = 0;
+ virtual int get_mouse_button_state() const = 0;
+ virtual void set_window_title(const String &p_title) = 0;
- virtual void warp_mouse_pos(const Point2& p_to) {}
- virtual Point2 get_mouse_pos() const=0;
- virtual int get_mouse_button_state() const=0;
- virtual void set_window_title(const String& p_title)=0;
-
- virtual void set_clipboard(const String& p_text);
+ virtual void set_clipboard(const String &p_text);
virtual String get_clipboard() const;
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0)=0;
- virtual VideoMode get_video_mode(int p_screen=0) const=0;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const=0;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0) = 0;
+ virtual VideoMode get_video_mode(int p_screen = 0) const = 0;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const = 0;
-
- virtual int get_screen_count() const{ return 1; }
+ virtual int get_screen_count() const { return 1; }
virtual int get_current_screen() const { return 0; }
- virtual void set_current_screen(int p_screen) { }
- virtual Point2 get_screen_position(int p_screen=0) const { return Point2(); }
- virtual Size2 get_screen_size(int p_screen=0) const { return get_window_size(); }
- virtual int get_screen_dpi(int p_screen=0) const { return 72; }
+ virtual void set_current_screen(int p_screen) {}
+ virtual Point2 get_screen_position(int p_screen = 0) const { return Point2(); }
+ virtual Size2 get_screen_size(int p_screen = 0) const { return get_window_size(); }
+ virtual int get_screen_dpi(int p_screen = 0) const { return 72; }
virtual Point2 get_window_position() const { return Vector2(); }
- virtual void set_window_position(const Point2& p_position) {}
- virtual Size2 get_window_size() const=0;
- virtual void set_window_size(const Size2 p_size){}
+ virtual void set_window_position(const Point2 &p_position) {}
+ virtual Size2 get_window_size() const = 0;
+ virtual void set_window_size(const Size2 p_size) {}
virtual void set_window_fullscreen(bool p_enabled) {}
virtual bool is_window_fullscreen() const { return true; }
virtual void set_window_resizable(bool p_enabled) {}
@@ -172,12 +172,11 @@ public:
virtual bool is_window_minimized() const { return false; }
virtual void set_window_maximized(bool p_enabled) {}
virtual bool is_window_maximized() const { return true; }
- virtual void request_attention() { }
+ virtual void request_attention() {}
virtual void set_borderless_window(int p_borderless) {}
virtual bool get_borderless_window() { return 0; }
-
virtual void set_keep_screen_on(bool p_enabled);
virtual bool is_keep_screen_on() const;
virtual void set_low_processor_usage_mode(bool p_enabled);
@@ -185,22 +184,21 @@ public:
virtual String get_installed_templates_path() const { return ""; }
virtual String get_executable_path() const;
- virtual Error execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id=NULL,String* r_pipe=NULL,int *r_exitcode=NULL)=0;
- virtual Error kill(const ProcessID& p_pid)=0;
+ virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL) = 0;
+ virtual Error kill(const ProcessID &p_pid) = 0;
virtual int get_process_ID() const;
virtual Error shell_open(String p_uri);
- virtual Error set_cwd(const String& p_cwd);
+ virtual Error set_cwd(const String &p_cwd);
- virtual bool has_environment(const String& p_var) const=0;
- virtual String get_environment(const String& p_var) const=0;
+ virtual bool has_environment(const String &p_var) const = 0;
+ virtual String get_environment(const String &p_var) const = 0;
- virtual String get_name()=0;
+ virtual String get_name() = 0;
virtual List<String> get_cmdline_args() const { return _cmdline; }
- virtual String get_model_name() const;
-
- virtual MainLoop *get_main_loop() const=0;
+ virtual String get_model_name() const;
+ virtual MainLoop *get_main_loop() const = 0;
virtual void yield();
@@ -252,18 +250,17 @@ public:
String name;
};
- virtual Date get_date(bool local=false) const=0;
- virtual Time get_time(bool local=false) const=0;
- virtual TimeZoneInfo get_time_zone_info() const=0;
+ virtual Date get_date(bool local = false) const = 0;
+ virtual Time get_time(bool local = false) const = 0;
+ virtual TimeZoneInfo get_time_zone_info() const = 0;
virtual uint64_t get_unix_time() const;
virtual uint64_t get_system_time_secs() const;
- virtual void delay_usec(uint32_t p_usec) const=0;
- virtual uint64_t get_ticks_usec() const=0;
+ virtual void delay_usec(uint32_t p_usec) const = 0;
+ virtual uint64_t get_ticks_usec() const = 0;
uint32_t get_ticks_msec() const;
uint64_t get_splash_tick_msec() const;
-
virtual bool can_draw() const = 0;
bool is_stdout_verbose() const;
@@ -289,18 +286,17 @@ public:
CURSOR_MAX
};
-
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect=Rect2());
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2());
virtual void hide_virtual_keyboard();
- virtual void set_cursor_shape(CursorShape p_shape)=0;
+ virtual void set_cursor_shape(CursorShape p_shape) = 0;
virtual bool get_swap_ok_cancel() { return false; }
- virtual void dump_memory_to_file(const char* p_file);
- virtual void dump_resources_to_file(const char* p_file);
- virtual void print_resources_in_use(bool p_short=false);
- virtual void print_all_resources(String p_to_file="");
+ virtual void dump_memory_to_file(const char *p_file);
+ virtual void dump_resources_to_file(const char *p_file);
+ virtual void print_resources_in_use(bool p_short = false);
+ virtual void print_all_resources(String p_to_file = "");
virtual int get_static_memory_usage() const;
virtual int get_static_memory_peak_usage() const;
@@ -328,7 +324,6 @@ public:
virtual String get_system_dir(SystemDir p_dir) const;
-
virtual void set_no_window_mode(bool p_enable);
virtual bool is_no_window_mode_enabled() const;
@@ -357,8 +352,7 @@ public:
virtual void make_rendering_thread();
virtual void swap_buffers();
-
- virtual void set_icon(const Image& p_icon);
+ virtual void set_icon(const Image &p_icon);
virtual int get_exit_code() const;
virtual void set_exit_code(int p_code);
@@ -375,9 +369,8 @@ public:
virtual bool can_use_threads() const;
- virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object* p_obj, String p_callback);
- virtual Error dialog_input_text(String p_title, String p_description, String p_partial, Object* p_obj, String p_callback);
-
+ virtual Error dialog_show(String p_title, String p_description, Vector<String> p_buttons, Object *p_obj, String p_callback);
+ virtual Error dialog_input_text(String p_title, String p_description, String p_partial, Object *p_obj, String p_callback);
enum LatinKeyboardVariant {
LATIN_KEYBOARD_QWERTY,
@@ -388,12 +381,10 @@ public:
LATIN_KEYBOARD_NEO,
};
-
virtual LatinKeyboardVariant get_latin_keyboard_variant() const;
-
virtual bool is_joy_known(int p_device);
- virtual String get_joy_guid(int p_device)const;
+ virtual String get_joy_guid(int p_device) const;
enum EngineContext {
CONTEXT_EDITOR,
@@ -404,18 +395,16 @@ public:
virtual void set_use_vsync(bool p_enable);
virtual bool is_vsync_enabled() const;
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
- virtual bool check_feature_support(const String& p_feature)=0;
+ virtual bool check_feature_support(const String &p_feature) = 0;
bool is_hidpi_allowed() const { return _allow_hidpi; }
OS();
virtual ~OS();
-
};
#endif
-
diff --git a/core/os/power.h b/core/os/power.h
index c92348ff50..9e70e82f5d 100644
--- a/core/os/power.h
+++ b/core/os/power.h
@@ -30,15 +30,12 @@
#ifndef CORE_OS_POWER_H_
#define CORE_OS_POWER_H_
-
-typedef enum
-{
- POWERSTATE_UNKNOWN, /**< cannot determine power status */
- POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */
- POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */
- POWERSTATE_CHARGING, /**< Plugged in, charging battery */
- POWERSTATE_CHARGED /**< Plugged in, battery charged */
+typedef enum {
+ POWERSTATE_UNKNOWN, /**< cannot determine power status */
+ POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */
+ POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */
+ POWERSTATE_CHARGING, /**< Plugged in, charging battery */
+ POWERSTATE_CHARGED /**< Plugged in, battery charged */
} PowerState;
-
#endif /* CORE_OS_POWER_H_ */
diff --git a/core/os/rw_lock.cpp b/core/os/rw_lock.cpp
index 3af62aa8da..83f8a9ffde 100644
--- a/core/os/rw_lock.cpp
+++ b/core/os/rw_lock.cpp
@@ -32,19 +32,14 @@
#include <stddef.h>
-
-RWLock* (*RWLock::create_func)()=0;
+RWLock *(*RWLock::create_func)() = 0;
RWLock *RWLock::create() {
- ERR_FAIL_COND_V( !create_func, 0 );
+ ERR_FAIL_COND_V(!create_func, 0);
return create_func();
}
-
RWLock::~RWLock() {
-
-
}
-
diff --git a/core/os/rw_lock.h b/core/os/rw_lock.h
index 6b4af83bf9..6d3079df51 100644
--- a/core/os/rw_lock.h
+++ b/core/os/rw_lock.h
@@ -33,42 +33,48 @@
class RWLock {
protected:
- static RWLock* (*create_func)();
+ static RWLock *(*create_func)();
public:
+ virtual void read_lock() = 0; ///< Lock the rwlock, block if locked by someone else
+ virtual void read_unlock() = 0; ///< Unlock the rwlock, let other threads continue
+ virtual Error read_try_lock() = 0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock.
- virtual void read_lock()=0; ///< Lock the rwlock, block if locked by someone else
- virtual void read_unlock()=0; ///< Unlock the rwlock, let other threads continue
- virtual Error read_try_lock()=0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock.
+ virtual void write_lock() = 0; ///< Lock the rwlock, block if locked by someone else
+ virtual void write_unlock() = 0; ///< Unlock the rwlock, let other thwrites continue
+ virtual Error write_try_lock() = 0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock.
- virtual void write_lock()=0; ///< Lock the rwlock, block if locked by someone else
- virtual void write_unlock()=0; ///< Unlock the rwlock, let other thwrites continue
- virtual Error write_try_lock()=0; ///< Attempt to lock the rwlock, OK on success, ERROR means it can't lock.
-
- static RWLock * create(); ///< Create a rwlock
+ static RWLock *create(); ///< Create a rwlock
virtual ~RWLock();
};
-
class RWLockRead {
RWLock *lock;
-public:
-
- RWLockRead(RWLock* p_lock) { lock=p_lock; if (lock) lock->read_lock(); }
- ~RWLockRead() { if (lock) lock->read_unlock(); }
+public:
+ RWLockRead(RWLock *p_lock) {
+ lock = p_lock;
+ if (lock) lock->read_lock();
+ }
+ ~RWLockRead() {
+ if (lock) lock->read_unlock();
+ }
};
class RWLockWrite {
RWLock *lock;
-public:
-
- RWLockWrite(RWLock* p_lock) { lock=p_lock; if (lock) lock->write_lock(); }
- ~RWLockWrite() { if (lock) lock->write_unlock(); }
+public:
+ RWLockWrite(RWLock *p_lock) {
+ lock = p_lock;
+ if (lock) lock->write_lock();
+ }
+ ~RWLockWrite() {
+ if (lock) lock->write_unlock();
+ }
};
#endif // RWLOCK_H
diff --git a/core/os/semaphore.cpp b/core/os/semaphore.cpp
index fe476c5888..6bbae72f63 100644
--- a/core/os/semaphore.cpp
+++ b/core/os/semaphore.cpp
@@ -29,16 +29,14 @@
#include "semaphore.h"
#include "error_macros.h"
-Semaphore* (*Semaphore::create_func)()=0;
+Semaphore *(*Semaphore::create_func)() = 0;
Semaphore *Semaphore::create() {
- ERR_FAIL_COND_V( !create_func, 0 );
+ ERR_FAIL_COND_V(!create_func, 0);
return create_func();
}
-
Semaphore::~Semaphore() {
-
}
diff --git a/core/os/semaphore.h b/core/os/semaphore.h
index e0b4460b22..8956fb7c39 100644
--- a/core/os/semaphore.h
+++ b/core/os/semaphore.h
@@ -36,18 +36,16 @@
*/
class Semaphore {
protected:
- static Semaphore* (*create_func)();
+ static Semaphore *(*create_func)();
public:
+ virtual Error wait() = 0; ///< wait until semaphore has positive value, then decrement and pass
+ virtual Error post() = 0; ///< unlock the semaphore, incrementing the value
+ virtual int get() const = 0; ///< get semaphore value
- virtual Error wait()=0; ///< wait until semaphore has positive value, then decrement and pass
- virtual Error post()=0; ///< unlock the semaphore, incrementing the value
- virtual int get() const=0; ///< get semaphore value
-
- static Semaphore * create(); ///< Create a mutex
+ static Semaphore *create(); ///< Create a mutex
virtual ~Semaphore();
};
-
#endif
diff --git a/core/os/shell.cpp b/core/os/shell.cpp
index 60f4203dbe..77726afd9d 100644
--- a/core/os/shell.cpp
+++ b/core/os/shell.cpp
@@ -28,24 +28,17 @@
/*************************************************************************/
#include "shell.h"
+Shell *Shell::singleton = NULL;
-Shell * Shell::singleton=NULL;
-
-
-Shell * Shell::get_singleton() {
+Shell *Shell::get_singleton() {
return singleton;
}
-
Shell::~Shell() {
-
}
Shell::Shell() {
- singleton=this;
+ singleton = this;
}
-
-
-
diff --git a/core/os/shell.h b/core/os/shell.h
index f26f01846e..b2b0aa2260 100644
--- a/core/os/shell.h
+++ b/core/os/shell.h
@@ -37,11 +37,11 @@
*/
class Shell {
- static Shell * singleton;
-public:
+ static Shell *singleton;
- static Shell * get_singleton();
- virtual void execute(String p_path)=0;
+public:
+ static Shell *get_singleton();
+ virtual void execute(String p_path) = 0;
Shell();
virtual ~Shell();
diff --git a/core/os/thread.cpp b/core/os/thread.cpp
index 689fed7537..1c6ccaa504 100644
--- a/core/os/thread.cpp
+++ b/core/os/thread.cpp
@@ -28,13 +28,12 @@
/*************************************************************************/
#include "thread.h"
+Thread *(*Thread::create_func)(ThreadCreateCallback, void *, const Settings &) = NULL;
+Thread::ID (*Thread::get_thread_ID_func)() = NULL;
+void (*Thread::wait_to_finish_func)(Thread *) = NULL;
+Error (*Thread::set_name_func)(const String &) = NULL;
-Thread* (*Thread::create_func)(ThreadCreateCallback,void *,const Settings&)=NULL;
-Thread::ID (*Thread::get_thread_ID_func)()=NULL;
-void (*Thread::wait_to_finish_func)(Thread*)=NULL;
-Error (*Thread::set_name_func)(const String&)=NULL;
-
-Thread::ID Thread::_main_thread_id=0;
+Thread::ID Thread::_main_thread_id = 0;
Thread::ID Thread::get_caller_ID() {
@@ -43,11 +42,11 @@ Thread::ID Thread::get_caller_ID() {
return 0;
}
-Thread* Thread::create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings) {
+Thread *Thread::create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings) {
if (create_func) {
- return create_func(p_callback,p_user,p_settings);
+ return create_func(p_callback, p_user, p_settings);
}
return NULL;
}
@@ -56,7 +55,6 @@ void Thread::wait_to_finish(Thread *p_thread) {
if (wait_to_finish_func)
wait_to_finish_func(p_thread);
-
}
Error Thread::set_name(const String &p_name) {
@@ -67,13 +65,8 @@ Error Thread::set_name(const String &p_name) {
return ERR_UNAVAILABLE;
};
-Thread::Thread()
-{
+Thread::Thread() {
}
-
-Thread::~Thread()
-{
+Thread::~Thread() {
}
-
-
diff --git a/core/os/thread.h b/core/os/thread.h
index 23ed76d486..9e0ab93cb9 100644
--- a/core/os/thread.h
+++ b/core/os/thread.h
@@ -29,7 +29,6 @@
#ifndef THREAD_H
#define THREAD_H
-
#include "typedefs.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -39,54 +38,45 @@
typedef void (*ThreadCreateCallback)(void *p_userdata);
-
-
class Thread {
public:
-
enum Priority {
PRIORITY_LOW,
- PRIORITY_NORMAL,
+ PRIORITY_NORMAL,
PRIORITY_HIGH
};
struct Settings {
Priority priority;
- Settings() { priority=PRIORITY_NORMAL; }
+ Settings() { priority = PRIORITY_NORMAL; }
};
-
-
typedef uint64_t ID;
protected:
- static Thread* (*create_func)(ThreadCreateCallback p_callback,void *,const Settings&);
+ static Thread *(*create_func)(ThreadCreateCallback p_callback, void *, const Settings &);
static ID (*get_thread_ID_func)();
- static void (*wait_to_finish_func)(Thread*);
- static Error (*set_name_func)(const String&);
+ static void (*wait_to_finish_func)(Thread *);
+ static Error (*set_name_func)(const String &);
friend class Main;
static ID _main_thread_id;
-
Thread();
-public:
- virtual ID get_ID() const=0;
+public:
+ virtual ID get_ID() const = 0;
static Error set_name(const String &p_name);
_FORCE_INLINE_ static ID get_main_ID() { return _main_thread_id; } ///< get the ID of the main thread
static ID get_caller_ID(); ///< get the ID of the caller function ID
static void wait_to_finish(Thread *p_thread); ///< waits until thread is finished, and deallocates it.
- static Thread * create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings=Settings()); ///< Static function to create a thread, will call p_callback
-
+ static Thread *create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings = Settings()); ///< Static function to create a thread, will call p_callback
virtual ~Thread();
-
};
#endif
-
diff --git a/core/os/thread_dummy.cpp b/core/os/thread_dummy.cpp
index 93a020b7a8..a17f7f09a8 100644
--- a/core/os/thread_dummy.cpp
+++ b/core/os/thread_dummy.cpp
@@ -30,7 +30,7 @@
#include "memory.h"
-Thread* ThreadDummy::create(ThreadCreateCallback p_callback,void * p_user,const Thread::Settings& p_settings) {
+Thread *ThreadDummy::create(ThreadCreateCallback p_callback, void *p_user, const Thread::Settings &p_settings) {
return memnew(ThreadDummy);
};
@@ -38,7 +38,7 @@ void ThreadDummy::make_default() {
Thread::create_func = &ThreadDummy::create;
};
-Mutex* MutexDummy::create(bool p_recursive) {
+Mutex *MutexDummy::create(bool p_recursive) {
return memnew(MutexDummy);
};
@@ -46,14 +46,10 @@ void MutexDummy::make_default() {
Mutex::create_func = &MutexDummy::create;
};
-
-Semaphore* SemaphoreDummy::create() {
+Semaphore *SemaphoreDummy::create() {
return memnew(SemaphoreDummy);
};
void SemaphoreDummy::make_default() {
Semaphore::create_func = &SemaphoreDummy::create;
};
-
-
-
diff --git a/core/os/thread_dummy.h b/core/os/thread_dummy.h
index 01e366e2fa..8d0ca0340d 100644
--- a/core/os/thread_dummy.h
+++ b/core/os/thread_dummy.h
@@ -29,13 +29,13 @@
#ifndef THREAD_DUMMY_H
#define THREAD_DUMMY_H
-#include "thread.h"
#include "mutex.h"
#include "semaphore.h"
+#include "thread.h"
class ThreadDummy : public Thread {
- static Thread* create(ThreadCreateCallback p_callback,void * p_user,const Settings& p_settings=Settings());
+ static Thread *create(ThreadCreateCallback p_callback, void *p_user, const Settings &p_settings = Settings());
public:
virtual ID get_ID() const { return 0; };
@@ -45,12 +45,11 @@ public:
class MutexDummy : public Mutex {
- static Mutex* create(bool p_recursive);
+ static Mutex *create(bool p_recursive);
public:
-
- virtual void lock() {};
- virtual void unlock() {};
+ virtual void lock(){};
+ virtual void unlock(){};
virtual Error try_lock() { return OK; };
static void make_default();
@@ -58,7 +57,7 @@ public:
class SemaphoreDummy : public Semaphore {
- static Semaphore* create();
+ static Semaphore *create();
public:
virtual Error wait() { return OK; };
@@ -66,7 +65,6 @@ public:
virtual int get() const { return 0; }; ///< get semaphore value
static void make_default();
-
};
#endif
diff --git a/core/os/thread_safe.cpp b/core/os/thread_safe.cpp
index a0bfb86c82..ebdf86733c 100644
--- a/core/os/thread_safe.cpp
+++ b/core/os/thread_safe.cpp
@@ -42,5 +42,5 @@ ThreadSafe::ThreadSafe() {
ThreadSafe::~ThreadSafe() {
if (mutex)
- memdelete( mutex );
+ memdelete(mutex);
}
diff --git a/core/os/thread_safe.h b/core/os/thread_safe.h
index c9a832b41b..a60773e8ed 100644
--- a/core/os/thread_safe.h
+++ b/core/os/thread_safe.h
@@ -29,41 +29,42 @@
#ifndef THREAD_SAFE_H
#define THREAD_SAFE_H
-
#include "os/mutex.h"
class ThreadSafe {
Mutex *mutex;
-public:
- inline void lock() const { if (mutex) mutex->lock(); }
- inline void unlock() const { if (mutex) mutex->unlock(); }
+public:
+ inline void lock() const {
+ if (mutex) mutex->lock();
+ }
+ inline void unlock() const {
+ if (mutex) mutex->unlock();
+ }
ThreadSafe();
~ThreadSafe();
-
};
-
class ThreadSafeMethod {
const ThreadSafe *_ts;
+
public:
ThreadSafeMethod(const ThreadSafe *p_ts) {
- _ts=p_ts;
+ _ts = p_ts;
_ts->lock();
}
~ThreadSafeMethod() { _ts->unlock(); }
};
-
#ifndef NO_THREADS
#define _THREAD_SAFE_CLASS_ ThreadSafe __thread__safe__;
-#define _THREAD_SAFE_METHOD_ ThreadSafeMethod __thread_safe_method__(&__thread__safe__);
+#define _THREAD_SAFE_METHOD_ ThreadSafeMethod __thread_safe_method__(&__thread__safe__);
#define _THREAD_SAFE_LOCK_ __thread__safe__.lock();
#define _THREAD_SAFE_UNLOCK_ __thread__safe__.unlock();
@@ -76,7 +77,4 @@ public:
#endif
-
-
-
#endif
diff --git a/core/packed_data_container.cpp b/core/packed_data_container.cpp
index 803a217fca..b2922a6173 100644
--- a/core/packed_data_container.cpp
+++ b/core/packed_data_container.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "packed_data_container.h"
-#include "io/marshalls.h"
#include "core_string_names.h"
+#include "io/marshalls.h"
+Variant PackedDataContainer::getvar(const Variant &p_key, bool *r_valid) const {
-Variant PackedDataContainer::getvar(const Variant& p_key, bool *r_valid) const {
-
- bool err=false;
- Variant ret = _key_at_ofs(0,p_key,err);
+ bool err = false;
+ Variant ret = _key_at_ofs(0, p_key, err);
if (r_valid)
- *r_valid=!err;
+ *r_valid = !err;
return ret;
}
@@ -46,93 +45,88 @@ int PackedDataContainer::size() const {
return _size(0);
};
-Variant PackedDataContainer::_iter_init_ofs(const Array& p_iter,uint32_t p_offset) {
+Variant PackedDataContainer::_iter_init_ofs(const Array &p_iter, uint32_t p_offset) {
- Array ref=p_iter;
+ Array ref = p_iter;
uint32_t size = _size(p_offset);
- if (size==0 || ref.size()!=1)
+ if (size == 0 || ref.size() != 1)
return false;
else {
- ref[0]=0;
+ ref[0] = 0;
return true;
}
-
-
}
-Variant PackedDataContainer::_iter_next_ofs(const Array& p_iter,uint32_t p_offset){
+Variant PackedDataContainer::_iter_next_ofs(const Array &p_iter, uint32_t p_offset) {
- Array ref=p_iter;
+ Array ref = p_iter;
uint32_t size = _size(p_offset);
- if (ref.size()!=1)
+ if (ref.size() != 1)
return false;
int pos = ref[0];
- if (pos<0 || pos>=size)
+ if (pos < 0 || pos >= size)
return false;
- pos+=1;
- ref[0]=pos;
- return pos!=size;
-
+ pos += 1;
+ ref[0] = pos;
+ return pos != size;
}
-Variant PackedDataContainer::_iter_get_ofs(const Variant& p_iter,uint32_t p_offset){
+Variant PackedDataContainer::_iter_get_ofs(const Variant &p_iter, uint32_t p_offset) {
uint32_t size = _size(p_offset);
- int pos=p_iter;
- if (pos<0 || pos>=size)
+ int pos = p_iter;
+ if (pos < 0 || pos >= size)
return Variant();
- PoolVector<uint8_t>::Read rd=data.read();
- const uint8_t *r=&rd[p_offset];
+ PoolVector<uint8_t>::Read rd = data.read();
+ const uint8_t *r = &rd[p_offset];
uint32_t type = decode_uint32(r);
- bool err=false;
- if (type==TYPE_ARRAY) {
+ bool err = false;
+ if (type == TYPE_ARRAY) {
- uint32_t vpos = decode_uint32(rd.ptr() + p_offset+8+pos*4);
- return _get_at_ofs(vpos,rd.ptr(),err);
+ uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 4);
+ return _get_at_ofs(vpos, rd.ptr(), err);
- } else if (type==TYPE_DICT) {
+ } else if (type == TYPE_DICT) {
- uint32_t vpos = decode_uint32(rd.ptr() + p_offset+8+pos*12+4);
- return _get_at_ofs(vpos,rd.ptr(),err);
+ uint32_t vpos = decode_uint32(rd.ptr() + p_offset + 8 + pos * 12 + 4);
+ return _get_at_ofs(vpos, rd.ptr(), err);
} else {
ERR_FAIL_V(Variant());
}
}
-
-Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs,const uint8_t *p_buf,bool &err) const {
+Variant PackedDataContainer::_get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const {
uint32_t type = decode_uint32(p_buf + p_ofs);
- if (type==TYPE_ARRAY || type==TYPE_DICT) {
+ if (type == TYPE_ARRAY || type == TYPE_DICT) {
- Ref<PackedDataContainerRef> pdcr = memnew( PackedDataContainerRef );
- Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer*)this);
+ Ref<PackedDataContainerRef> pdcr = memnew(PackedDataContainerRef);
+ Ref<PackedDataContainer> pdc = Ref<PackedDataContainer>((PackedDataContainer *)this);
- pdcr->from=pdc;
- pdcr->offset=p_ofs;
+ pdcr->from = pdc;
+ pdcr->offset = p_ofs;
return pdcr;
} else {
Variant v;
- Error rerr = decode_variant(v,p_buf + p_ofs,datalen-p_ofs,NULL);
+ Error rerr = decode_variant(v, p_buf + p_ofs, datalen - p_ofs, NULL);
- if (rerr!=OK) {
+ if (rerr != OK) {
- err=true;
- ERR_FAIL_COND_V(err!=OK,Variant());
+ err = true;
+ ERR_FAIL_COND_V(err != OK, Variant());
}
return v;
}
-
}
uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const {
- PoolVector<uint8_t>::Read rd=data.read();
- const uint8_t *r=&rd[p_ofs];
+ PoolVector<uint8_t>::Read rd = data.read();
+ const uint8_t *r = &rd[p_ofs];
uint32_t type = decode_uint32(r);
return type;
@@ -140,87 +134,84 @@ uint32_t PackedDataContainer::_type_at_ofs(uint32_t p_ofs) const {
int PackedDataContainer::_size(uint32_t p_ofs) const {
- PoolVector<uint8_t>::Read rd=data.read();
- const uint8_t *r=&rd[p_ofs];
+ PoolVector<uint8_t>::Read rd = data.read();
+ const uint8_t *r = &rd[p_ofs];
uint32_t type = decode_uint32(r);
- if (type==TYPE_ARRAY) {
+ if (type == TYPE_ARRAY) {
- uint32_t len = decode_uint32(r+4);
+ uint32_t len = decode_uint32(r + 4);
return len;
- } else if (type==TYPE_DICT) {
+ } else if (type == TYPE_DICT) {
- uint32_t len = decode_uint32(r+4);
+ uint32_t len = decode_uint32(r + 4);
return len;
};
return -1;
};
-Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs,const Variant& p_key,bool &err) const {
+Variant PackedDataContainer::_key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const {
- PoolVector<uint8_t>::Read rd=data.read();
- const uint8_t *r=&rd[p_ofs];
+ PoolVector<uint8_t>::Read rd = data.read();
+ const uint8_t *r = &rd[p_ofs];
uint32_t type = decode_uint32(r);
-
- if (type==TYPE_ARRAY) {
+ if (type == TYPE_ARRAY) {
if (p_key.is_num()) {
- int idx=p_key;
- uint32_t len = decode_uint32(r+4);
- if (idx<0 || idx>=len) {
- err=true;
+ int idx = p_key;
+ uint32_t len = decode_uint32(r + 4);
+ if (idx < 0 || idx >= len) {
+ err = true;
return Variant();
}
- uint32_t ofs = decode_uint32(r+8+4*idx);
- return _get_at_ofs(ofs,rd.ptr(),err);
+ uint32_t ofs = decode_uint32(r + 8 + 4 * idx);
+ return _get_at_ofs(ofs, rd.ptr(), err);
} else {
- err=true;
+ err = true;
return Variant();
}
- } else if (type==TYPE_DICT) {
+ } else if (type == TYPE_DICT) {
- uint32_t hash=p_key.hash();
- uint32_t len = decode_uint32(r+4);
+ uint32_t hash = p_key.hash();
+ uint32_t len = decode_uint32(r + 4);
- bool found=false;
- for(int i=0;i<len;i++) {
- uint32_t khash=decode_uint32(r+8+i*12+0);
- if (khash==hash) {
- Variant key = _get_at_ofs(decode_uint32(r+8+i*12+4),rd.ptr(),err);
+ bool found = false;
+ for (int i = 0; i < len; i++) {
+ uint32_t khash = decode_uint32(r + 8 + i * 12 + 0);
+ if (khash == hash) {
+ Variant key = _get_at_ofs(decode_uint32(r + 8 + i * 12 + 4), rd.ptr(), err);
if (err)
return Variant();
- if (key==p_key) {
+ if (key == p_key) {
//key matches, return value
- return _get_at_ofs(decode_uint32(r+8+i*12+8),rd.ptr(),err);
+ return _get_at_ofs(decode_uint32(r + 8 + i * 12 + 8), rd.ptr(), err);
}
- found=true;
+ found = true;
} else {
if (found)
break;
}
}
- err=true;
+ err = true;
return Variant();
} else {
- err=true;
+ err = true;
return Variant();
}
-
-
}
-uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpdata, Map<String,uint32_t>& string_cache) {
+uint32_t PackedDataContainer::_pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache) {
- switch(p_data.get_type()) {
+ switch (p_data.get_type()) {
case Variant::STRING: {
@@ -229,7 +220,7 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd
return string_cache[s];
}
- string_cache[s]=tmpdata.size();
+ string_cache[s] = tmpdata.size();
}; //fallthrough
case Variant::NIL:
@@ -258,9 +249,9 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd
uint32_t pos = tmpdata.size();
int len;
- encode_variant(p_data,NULL,len);
- tmpdata.resize(tmpdata.size()+len);
- encode_variant(p_data,&tmpdata[pos],len);
+ encode_variant(p_data, NULL, len);
+ tmpdata.resize(tmpdata.size() + len);
+ encode_variant(p_data, &tmpdata[pos], len);
return pos;
} break;
@@ -268,67 +259,64 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd
case Variant::_RID:
case Variant::OBJECT: {
- return _pack(Variant(),tmpdata,string_cache);
+ return _pack(Variant(), tmpdata, string_cache);
} break;
case Variant::DICTIONARY: {
- Dictionary d=p_data;
+ Dictionary d = p_data;
//size is known, use sort
uint32_t pos = tmpdata.size();
- int len=d.size();
- tmpdata.resize(tmpdata.size()+len*12+8);
- encode_uint32(TYPE_DICT,&tmpdata[pos+0]);
- encode_uint32(len,&tmpdata[pos+4]);
+ int len = d.size();
+ tmpdata.resize(tmpdata.size() + len * 12 + 8);
+ encode_uint32(TYPE_DICT, &tmpdata[pos + 0]);
+ encode_uint32(len, &tmpdata[pos + 4]);
List<Variant> keys;
d.get_key_list(&keys);
List<DictKey> sortk;
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
DictKey dk;
- dk.hash=E->get().hash();
- dk.key=E->get();
+ dk.hash = E->get().hash();
+ dk.key = E->get();
sortk.push_back(dk);
}
sortk.sort();
- int idx=0;
- for(List<DictKey>::Element *E=sortk.front();E;E=E->next()) {
+ int idx = 0;
+ for (List<DictKey>::Element *E = sortk.front(); E; E = E->next()) {
- encode_uint32(E->get().hash,&tmpdata[pos+8+idx*12+0]);
- uint32_t ofs = _pack(E->get().key,tmpdata,string_cache);
- encode_uint32(ofs,&tmpdata[pos+8+idx*12+4]);
- ofs = _pack(d[E->get().key],tmpdata,string_cache);
- encode_uint32(ofs,&tmpdata[pos+8+idx*12+8]);
+ encode_uint32(E->get().hash, &tmpdata[pos + 8 + idx * 12 + 0]);
+ uint32_t ofs = _pack(E->get().key, tmpdata, string_cache);
+ encode_uint32(ofs, &tmpdata[pos + 8 + idx * 12 + 4]);
+ ofs = _pack(d[E->get().key], tmpdata, string_cache);
+ encode_uint32(ofs, &tmpdata[pos + 8 + idx * 12 + 8]);
idx++;
}
return pos;
-
-
} break;
case Variant::ARRAY: {
- Array a=p_data;
+ Array a = p_data;
//size is known, use sort
uint32_t pos = tmpdata.size();
- int len=a.size();
- tmpdata.resize(tmpdata.size()+len*4+8);
- encode_uint32(TYPE_ARRAY,&tmpdata[pos+0]);
- encode_uint32(len,&tmpdata[pos+4]);
+ int len = a.size();
+ tmpdata.resize(tmpdata.size() + len * 4 + 8);
+ encode_uint32(TYPE_ARRAY, &tmpdata[pos + 0]);
+ encode_uint32(len, &tmpdata[pos + 4]);
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- uint32_t ofs = _pack(a[i],tmpdata,string_cache);
- encode_uint32(ofs,&tmpdata[pos+8+i*4]);
+ uint32_t ofs = _pack(a[i], tmpdata, string_cache);
+ encode_uint32(ofs, &tmpdata[pos + 8 + i * 4]);
}
return pos;
-
} break;
default: {}
@@ -337,86 +325,75 @@ uint32_t PackedDataContainer::_pack(const Variant& p_data, Vector<uint8_t>& tmpd
return OK;
}
-Error PackedDataContainer::pack(const Variant& p_data) {
+Error PackedDataContainer::pack(const Variant &p_data) {
Vector<uint8_t> tmpdata;
- Map<String,uint32_t> string_cache;
- _pack(p_data,tmpdata,string_cache);
- datalen=tmpdata.size();
+ Map<String, uint32_t> string_cache;
+ _pack(p_data, tmpdata, string_cache);
+ datalen = tmpdata.size();
data.resize(tmpdata.size());
PoolVector<uint8_t>::Write w = data.write();
- copymem(w.ptr(),tmpdata.ptr(),tmpdata.size());
+ copymem(w.ptr(), tmpdata.ptr(), tmpdata.size());
return OK;
}
+void PackedDataContainer::_set_data(const PoolVector<uint8_t> &p_data) {
-void PackedDataContainer::_set_data(const PoolVector<uint8_t>& p_data) {
-
- data=p_data;
- datalen=data.size();
-
+ data = p_data;
+ datalen = data.size();
}
PoolVector<uint8_t> PackedDataContainer::_get_data() const {
return data;
}
+Variant PackedDataContainer::_iter_init(const Array &p_iter) {
-Variant PackedDataContainer::_iter_init(const Array& p_iter) {
-
-
- return _iter_init_ofs(p_iter,0);
+ return _iter_init_ofs(p_iter, 0);
}
-Variant PackedDataContainer::_iter_next(const Array& p_iter){
-
- return _iter_next_ofs(p_iter,0);
+Variant PackedDataContainer::_iter_next(const Array &p_iter) {
+ return _iter_next_ofs(p_iter, 0);
}
-Variant PackedDataContainer::_iter_get(const Variant& p_iter){
+Variant PackedDataContainer::_iter_get(const Variant &p_iter) {
- return _iter_get_ofs(p_iter,0);
+ return _iter_get_ofs(p_iter, 0);
}
-
void PackedDataContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_set_data"),&PackedDataContainer::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"),&PackedDataContainer::_get_data);
- ClassDB::bind_method(D_METHOD("_iter_init"),&PackedDataContainer::_iter_init);
- ClassDB::bind_method(D_METHOD("_iter_get"),&PackedDataContainer::_iter_get);
- ClassDB::bind_method(D_METHOD("_iter_next"),&PackedDataContainer::_iter_next);
- ClassDB::bind_method(D_METHOD("pack:Error","value"),&PackedDataContainer::pack);
- ClassDB::bind_method(D_METHOD("size"),&PackedDataContainer::size);
+ ClassDB::bind_method(D_METHOD("_set_data"), &PackedDataContainer::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &PackedDataContainer::_get_data);
+ ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainer::_iter_init);
+ ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainer::_iter_get);
+ ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainer::_iter_next);
+ ClassDB::bind_method(D_METHOD("pack:Error", "value"), &PackedDataContainer::pack);
+ ClassDB::bind_method(D_METHOD("size"), &PackedDataContainer::size);
- ADD_PROPERTY( PropertyInfo(Variant::POOL_BYTE_ARRAY,"__data__"),"_set_data","_get_data");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "__data__"), "_set_data", "_get_data");
}
-
PackedDataContainer::PackedDataContainer() {
- datalen=0;
+ datalen = 0;
}
-
//////////////////
+Variant PackedDataContainerRef::_iter_init(const Array &p_iter) {
-Variant PackedDataContainerRef::_iter_init(const Array& p_iter) {
-
-
- return from->_iter_init_ofs(p_iter,offset);
+ return from->_iter_init_ofs(p_iter, offset);
}
-Variant PackedDataContainerRef::_iter_next(const Array& p_iter){
-
- return from->_iter_next_ofs(p_iter,offset);
+Variant PackedDataContainerRef::_iter_next(const Array &p_iter) {
+ return from->_iter_next_ofs(p_iter, offset);
}
-Variant PackedDataContainerRef::_iter_get(const Variant& p_iter){
+Variant PackedDataContainerRef::_iter_get(const Variant &p_iter) {
- return from->_iter_get_ofs(p_iter,offset);
+ return from->_iter_get_ofs(p_iter, offset);
}
bool PackedDataContainerRef::_is_dictionary() const {
@@ -426,20 +403,19 @@ bool PackedDataContainerRef::_is_dictionary() const {
void PackedDataContainerRef::_bind_methods() {
- ClassDB::bind_method(D_METHOD("size"),&PackedDataContainerRef::size);
- ClassDB::bind_method(D_METHOD("_iter_init"),&PackedDataContainerRef::_iter_init);
- ClassDB::bind_method(D_METHOD("_iter_get"),&PackedDataContainerRef::_iter_get);
- ClassDB::bind_method(D_METHOD("_iter_next"),&PackedDataContainerRef::_iter_next);
- ClassDB::bind_method(D_METHOD("_is_dictionary"),&PackedDataContainerRef::_is_dictionary);
+ ClassDB::bind_method(D_METHOD("size"), &PackedDataContainerRef::size);
+ ClassDB::bind_method(D_METHOD("_iter_init"), &PackedDataContainerRef::_iter_init);
+ ClassDB::bind_method(D_METHOD("_iter_get"), &PackedDataContainerRef::_iter_get);
+ ClassDB::bind_method(D_METHOD("_iter_next"), &PackedDataContainerRef::_iter_next);
+ ClassDB::bind_method(D_METHOD("_is_dictionary"), &PackedDataContainerRef::_is_dictionary);
}
+Variant PackedDataContainerRef::getvar(const Variant &p_key, bool *r_valid) const {
-Variant PackedDataContainerRef::getvar(const Variant& p_key, bool *r_valid) const {
-
- bool err=false;
- Variant ret = from->_key_at_ofs(offset,p_key,err);
+ bool err = false;
+ Variant ret = from->_key_at_ofs(offset, p_key, err);
if (r_valid)
- *r_valid=!err;
+ *r_valid = !err;
return ret;
}
@@ -449,5 +425,4 @@ int PackedDataContainerRef::size() const {
};
PackedDataContainerRef::PackedDataContainerRef() {
-
}
diff --git a/core/packed_data_container.h b/core/packed_data_container.h
index f8ff43f9b0..b7ce505836 100644
--- a/core/packed_data_container.h
+++ b/core/packed_data_container.h
@@ -29,57 +29,50 @@
#ifndef PACKED_DATA_CONTAINER_H
#define PACKED_DATA_CONTAINER_H
-
#include "resource.h"
-
-
class PackedDataContainer : public Resource {
- GDCLASS(PackedDataContainer,Resource);
+ GDCLASS(PackedDataContainer, Resource);
enum {
- TYPE_DICT=0xFFFFFFFF,
- TYPE_ARRAY=0xFFFFFFFE,
+ TYPE_DICT = 0xFFFFFFFF,
+ TYPE_ARRAY = 0xFFFFFFFE,
};
struct DictKey {
uint32_t hash;
Variant key;
- bool operator<(const DictKey& p_key) const { return hash < p_key.hash; }
+ bool operator<(const DictKey &p_key) const { return hash < p_key.hash; }
};
-
PoolVector<uint8_t> data;
int datalen;
+ uint32_t _pack(const Variant &p_data, Vector<uint8_t> &tmpdata, Map<String, uint32_t> &string_cache);
- uint32_t _pack(const Variant& p_data,Vector<uint8_t>& tmpdata,Map<String,uint32_t>& string_cache);
-
+ Variant _iter_init_ofs(const Array &p_iter, uint32_t p_offset);
+ Variant _iter_next_ofs(const Array &p_iter, uint32_t p_offset);
+ Variant _iter_get_ofs(const Variant &p_iter, uint32_t p_offset);
- Variant _iter_init_ofs(const Array& p_iter,uint32_t p_offset);
- Variant _iter_next_ofs(const Array& p_iter,uint32_t p_offset);
- Variant _iter_get_ofs(const Variant& p_iter,uint32_t p_offset);
+ Variant _iter_init(const Array &p_iter);
+ Variant _iter_next(const Array &p_iter);
+ Variant _iter_get(const Variant &p_iter);
- Variant _iter_init(const Array& p_iter);
- Variant _iter_next(const Array& p_iter);
- Variant _iter_get(const Variant& p_iter);
-
-friend class PackedDataContainerRef;
- Variant _key_at_ofs(uint32_t p_ofs,const Variant& p_key,bool &err) const;
+ friend class PackedDataContainerRef;
+ Variant _key_at_ofs(uint32_t p_ofs, const Variant &p_key, bool &err) const;
Variant _get_at_ofs(uint32_t p_ofs, const uint8_t *p_buf, bool &err) const;
uint32_t _type_at_ofs(uint32_t p_ofs) const;
int _size(uint32_t p_ofs) const;
protected:
-
- void _set_data(const PoolVector<uint8_t>& p_data);
+ void _set_data(const PoolVector<uint8_t> &p_data);
PoolVector<uint8_t> _get_data() const;
static void _bind_methods();
-public:
- virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const;
- Error pack(const Variant& p_data);
+public:
+ virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const;
+ Error pack(const Variant &p_data);
int size() const;
@@ -87,9 +80,9 @@ public:
};
class PackedDataContainerRef : public Reference {
- GDCLASS(PackedDataContainerRef,Reference);
+ GDCLASS(PackedDataContainerRef, Reference);
-friend class PackedDataContainer;
+ friend class PackedDataContainer;
uint32_t offset;
Ref<PackedDataContainer> from;
@@ -97,14 +90,13 @@ protected:
static void _bind_methods();
public:
-
- Variant _iter_init(const Array& p_iter);
- Variant _iter_next(const Array& p_iter);
- Variant _iter_get(const Variant& p_iter);
+ Variant _iter_init(const Array &p_iter);
+ Variant _iter_next(const Array &p_iter);
+ Variant _iter_get(const Variant &p_iter);
bool _is_dictionary() const;
int size() const;
- virtual Variant getvar(const Variant& p_key, bool *r_valid=NULL) const;
+ virtual Variant getvar(const Variant &p_key, bool *r_valid = NULL) const;
PackedDataContainerRef();
};
diff --git a/core/pair.h b/core/pair.h
index 174ffb3883..faa3febfd4 100644
--- a/core/pair.h
+++ b/core/pair.h
@@ -29,23 +29,25 @@
#ifndef PAIR_H
#define PAIR_H
-template<class F,class S>
+template <class F, class S>
struct Pair {
F first;
S second;
Pair() {}
- Pair( F p_first, S p_second) { first=p_first; second=p_second; }
+ Pair(F p_first, S p_second) {
+ first = p_first;
+ second = p_second;
+ }
};
-template<class F,class S>
+template <class F, class S>
struct PairSort {
- bool operator()(const Pair<F,S>& A, const Pair<F,S>& B) const {
+ bool operator()(const Pair<F, S> &A, const Pair<F, S> &B) const {
return A.first < B.first;
}
};
-
#endif // PAIR_H
diff --git a/core/path_db.cpp b/core/path_db.cpp
index 679372898c..239a2d7654 100644
--- a/core/path_db.cpp
+++ b/core/path_db.cpp
@@ -38,25 +38,24 @@ uint32_t NodePath::hash() const {
uint32_t h = data->absolute ? 1 : 0;
int pc = data->path.size();
const StringName *sn = data->path.ptr();
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
h = h ^ sn[i].hash();
}
int spc = data->subpath.size();
const StringName *ssn = data->subpath.ptr();
- for(int i=0;i<spc;i++) {
+ for (int i = 0; i < spc; i++) {
h = h ^ ssn[i].hash();
}
h = h ^ data->property.hash();
return h;
-
}
void NodePath::prepend_period() {
- if (data->path.size() && data->path[0].operator String()!=".") {
- data->path.insert(0,".");
+ if (data->path.size() && data->path[0].operator String() != ".") {
+ data->path.insert(0, ".");
}
}
@@ -66,7 +65,6 @@ bool NodePath::is_absolute() const {
return false;
return data->absolute;
-
}
int NodePath::get_name_count() const {
@@ -74,12 +72,11 @@ int NodePath::get_name_count() const {
return 0;
return data->path.size();
-
}
StringName NodePath::get_name(int p_idx) const {
- ERR_FAIL_COND_V(!data,StringName());
- ERR_FAIL_INDEX_V(p_idx,data->path.size(),StringName());
+ ERR_FAIL_COND_V(!data, StringName());
+ ERR_FAIL_INDEX_V(p_idx, data->path.size(), StringName());
return data->path[p_idx];
}
@@ -96,29 +93,26 @@ int NodePath::get_subname_count() const {
return 0;
return data->subpath.size();
-
}
StringName NodePath::get_subname(int p_idx) const {
- ERR_FAIL_COND_V(!data,StringName());
- ERR_FAIL_INDEX_V(p_idx,data->subpath.size(),StringName());
+ ERR_FAIL_COND_V(!data, StringName());
+ ERR_FAIL_INDEX_V(p_idx, data->subpath.size(), StringName());
return data->subpath[p_idx];
}
-
void NodePath::unref() {
if (data && data->refcount.unref()) {
memdelete(data);
}
- data=NULL;
-
+ data = NULL;
}
-bool NodePath::operator==(const NodePath& p_path) const {
+bool NodePath::operator==(const NodePath &p_path) const {
- if (data==p_path.data)
+ if (data == p_path.data)
return true;
if (!data || !p_path.data)
@@ -136,36 +130,35 @@ bool NodePath::operator==(const NodePath& p_path) const {
if (data->property != p_path.data->property)
return false;
- for (int i=0;i<data->path.size();i++) {
+ for (int i = 0; i < data->path.size(); i++) {
- if (data->path[i]!=p_path.data->path[i])
+ if (data->path[i] != p_path.data->path[i])
return false;
}
- for (int i=0;i<data->subpath.size();i++) {
+ for (int i = 0; i < data->subpath.size(); i++) {
- if (data->subpath[i]!=p_path.data->subpath[i])
+ if (data->subpath[i] != p_path.data->subpath[i])
return false;
}
return true;
}
-bool NodePath::operator!=(const NodePath& p_path) const {
+bool NodePath::operator!=(const NodePath &p_path) const {
return (!(*this == p_path));
}
+void NodePath::operator=(const NodePath &p_path) {
-void NodePath::operator=(const NodePath& p_path) {
-
- if (this==&p_path)
+ if (this == &p_path)
return;
unref();
if (p_path.data && p_path.data->refcount.ref()) {
- data=p_path.data;
+ data = p_path.data;
}
}
@@ -176,33 +169,32 @@ NodePath::operator String() const {
String ret;
if (data->absolute)
- ret="/";
+ ret = "/";
- for (int i=0;i<data->path.size();i++) {
+ for (int i = 0; i < data->path.size(); i++) {
- if (i>0)
- ret+="/";
- ret+=data->path[i].operator String();
+ if (i > 0)
+ ret += "/";
+ ret += data->path[i].operator String();
}
- for (int i=0;i<data->subpath.size();i++) {
+ for (int i = 0; i < data->subpath.size(); i++) {
- ret+=":"+data->subpath[i].operator String();
+ ret += ":" + data->subpath[i].operator String();
}
- if (data->property.operator String()!="")
- ret+=":"+String(data->property);
+ if (data->property.operator String() != "")
+ ret += ":" + String(data->property);
return ret;
}
+NodePath::NodePath(const NodePath &p_path) {
-NodePath::NodePath(const NodePath& p_path) {
-
- data=NULL;
+ data = NULL;
if (p_path.data && p_path.data->refcount.ref()) {
- data=p_path.data;
+ data = p_path.data;
}
}
@@ -212,32 +204,30 @@ Vector<StringName> NodePath::get_names() const {
return data->path;
return Vector<StringName>();
}
-Vector<StringName> NodePath::get_subnames() const{
+Vector<StringName> NodePath::get_subnames() const {
if (data)
return data->subpath;
return Vector<StringName>();
-
}
+NodePath NodePath::rel_path_to(const NodePath &p_np) const {
-NodePath NodePath::rel_path_to(const NodePath& p_np) const {
-
- ERR_FAIL_COND_V( !is_absolute(), NodePath() );
- ERR_FAIL_COND_V( !p_np.is_absolute(), NodePath() );
+ ERR_FAIL_COND_V(!is_absolute(), NodePath());
+ ERR_FAIL_COND_V(!p_np.is_absolute(), NodePath());
Vector<StringName> src_dirs = get_names();
Vector<StringName> dst_dirs = p_np.get_names();
//find common parent
- int common_parent=0;
+ int common_parent = 0;
- while(true) {
- if (src_dirs.size()==common_parent)
+ while (true) {
+ if (src_dirs.size() == common_parent)
break;
- if (dst_dirs.size()==common_parent)
+ if (dst_dirs.size() == common_parent)
break;
- if (src_dirs[common_parent]!=dst_dirs[common_parent])
+ if (src_dirs[common_parent] != dst_dirs[common_parent])
break;
common_parent++;
}
@@ -246,69 +236,67 @@ NodePath NodePath::rel_path_to(const NodePath& p_np) const {
Vector<StringName> relpath;
- for(int i=src_dirs.size()-1;i>common_parent;i--) {
+ for (int i = src_dirs.size() - 1; i > common_parent; i--) {
relpath.push_back("..");
}
- for(int i=common_parent+1;i<dst_dirs.size();i++) {
+ for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
relpath.push_back(dst_dirs[i]);
}
- if (relpath.size()==0)
+ if (relpath.size() == 0)
relpath.push_back(".");
- return NodePath(relpath,p_np.get_subnames(),false,p_np.get_property());
+ return NodePath(relpath, p_np.get_subnames(), false, p_np.get_property());
}
+NodePath::NodePath(const Vector<StringName> &p_path, bool p_absolute, const String &p_property) {
-NodePath::NodePath(const Vector<StringName>& p_path,bool p_absolute,const String& p_property) {
+ data = NULL;
- data=NULL;
-
- if (p_path.size()==0)
+ if (p_path.size() == 0)
return;
- data = memnew( Data );
+ data = memnew(Data);
data->refcount.init();
- data->absolute=p_absolute;
- data->path=p_path;
- data->property=p_property;
+ data->absolute = p_absolute;
+ data->path = p_path;
+ data->property = p_property;
}
-NodePath::NodePath(const Vector<StringName>& p_path,const Vector<StringName>& p_subpath,bool p_absolute,const String& p_property) {
+NodePath::NodePath(const Vector<StringName> &p_path, const Vector<StringName> &p_subpath, bool p_absolute, const String &p_property) {
- data=NULL;
+ data = NULL;
- if (p_path.size()==0)
+ if (p_path.size() == 0)
return;
- data = memnew( Data );
+ data = memnew(Data);
data->refcount.init();
- data->absolute=p_absolute;
- data->path=p_path;
- data->subpath=p_subpath;
- data->property=p_property;
+ data->absolute = p_absolute;
+ data->path = p_path;
+ data->subpath = p_subpath;
+ data->property = p_property;
}
-
void NodePath::simplify() {
if (!data)
return;
- for(int i=0;i<data->path.size();i++) {
- if (data->path.size()==1)
+ for (int i = 0; i < data->path.size(); i++) {
+ if (data->path.size() == 1)
break;
- if (data->path[i].operator String()==".") {
+ if (data->path[i].operator String() == ".") {
data->path.remove(i);
i--;
- } else if (data->path[i].operator String()==".." && i>0 && data->path[i-1].operator String()!="." && data->path[i-1].operator String()!="..") {
+ } else if (data->path[i].operator String() == ".." && i > 0 && data->path[i - 1].operator String() != "." && data->path[i - 1].operator String() != "..") {
//remove both
- data->path.remove(i-1);
- data->path.remove(i-1);
- i-=2;
- if (data->path.size()==0) {
+ data->path.remove(i - 1);
+ data->path.remove(i - 1);
+ i -= 2;
+ if (data->path.size() == 0) {
data->path.push_back(".");
break;
}
@@ -318,108 +306,100 @@ void NodePath::simplify() {
NodePath NodePath::simplified() const {
- NodePath np=*this;
+ NodePath np = *this;
np.simplify();
return np;
}
-NodePath::NodePath(const String& p_path) {
+NodePath::NodePath(const String &p_path) {
- data=NULL;
+ data = NULL;
- if (p_path.length()==0)
+ if (p_path.length() == 0)
return;
- String path=p_path;
+ String path = p_path;
StringName property;
Vector<StringName> subpath;
- int absolute=(path[0]=='/')?1:0;
- bool last_is_slash=true;
- int slices=0;
- int subpath_pos=path.find(":");
-
+ int absolute = (path[0] == '/') ? 1 : 0;
+ bool last_is_slash = true;
+ int slices = 0;
+ int subpath_pos = path.find(":");
+ if (subpath_pos != -1) {
- if (subpath_pos!=-1) {
+ int from = subpath_pos + 1;
- int from=subpath_pos+1;
+ for (int i = from; i <= path.length(); i++) {
- for (int i=from;i<=path.length();i++) {
+ if (path[i] == ':' || path[i] == 0) {
- if (path[i]==':' || path[i]==0) {
-
- String str = path.substr(from,i-from);
- if (path[i]==':') {
- if (str=="") {
- ERR_EXPLAIN("Invalid NodePath: "+p_path);
+ String str = path.substr(from, i - from);
+ if (path[i] == ':') {
+ if (str == "") {
+ ERR_EXPLAIN("Invalid NodePath: " + p_path);
ERR_FAIL();
}
subpath.push_back(str);
} else {
//property can be empty
- property=str;
+ property = str;
}
- from=i+1;
+ from = i + 1;
}
-
}
- path=path.substr(0,subpath_pos);
+ path = path.substr(0, subpath_pos);
}
- for (int i=absolute;i<path.length();i++) {
+ for (int i = absolute; i < path.length(); i++) {
- if (path[i]=='/') {
+ if (path[i] == '/') {
- last_is_slash=true;
+ last_is_slash = true;
} else {
if (last_is_slash)
slices++;
- last_is_slash=false;
+ last_is_slash = false;
}
-
-
}
- if (slices==0 && !absolute && !property)
+ if (slices == 0 && !absolute && !property)
return;
- data = memnew( Data );
+ data = memnew(Data);
data->refcount.init();
- data->absolute=absolute?true:false;
- data->property=property;
- data->subpath=subpath;
+ data->absolute = absolute ? true : false;
+ data->property = property;
+ data->subpath = subpath;
- if (slices==0)
+ if (slices == 0)
return;
data->path.resize(slices);
- last_is_slash=true;
- int from=absolute;
- int slice=0;
+ last_is_slash = true;
+ int from = absolute;
+ int slice = 0;
- for (int i=absolute;i<path.length()+1;i++) {
+ for (int i = absolute; i < path.length() + 1; i++) {
- if (path[i]=='/' || path[i]==0) {
+ if (path[i] == '/' || path[i] == 0) {
if (!last_is_slash) {
- String name=path.substr(from,i-from);
- ERR_FAIL_INDEX( slice,data->path.size() );
- data->path[slice++]=name;
+ String name = path.substr(from, i - from);
+ ERR_FAIL_INDEX(slice, data->path.size());
+ data->path[slice++] = name;
}
- from=i+1;
- last_is_slash=true;
+ from = i + 1;
+ last_is_slash = true;
} else {
- last_is_slash=false;
+ last_is_slash = false;
}
-
}
-
-
}
bool NodePath::is_empty() const {
@@ -428,7 +408,7 @@ bool NodePath::is_empty() const {
}
NodePath::NodePath() {
- data=NULL;
+ data = NULL;
}
NodePath::~NodePath() {
diff --git a/core/path_db.h b/core/path_db.h
index db756c3420..eec29676e2 100644
--- a/core/path_db.h
+++ b/core/path_db.h
@@ -29,15 +29,12 @@
#ifndef PATH_DB_H
#define PATH_DB_H
-
-#include "ustring.h"
#include "string_db.h"
+#include "ustring.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
class NodePath {
struct Data {
@@ -51,11 +48,11 @@ class NodePath {
Data *data;
void unref();
-public:
+public:
_FORCE_INLINE_ StringName get_sname() const {
- if (data && data->path.size()==1 && data->subpath.empty() && !data->property) {
+ if (data && data->path.size() == 1 && data->subpath.empty() && !data->property) {
return data->path[0];
} else {
return operator String();
@@ -70,7 +67,7 @@ public:
Vector<StringName> get_names() const;
Vector<StringName> get_subnames() const;
- NodePath rel_path_to(const NodePath& p_np) const;
+ NodePath rel_path_to(const NodePath &p_np) const;
void prepend_period();
@@ -83,17 +80,17 @@ public:
operator String() const;
bool is_empty() const;
- bool operator==(const NodePath& p_path) const;
- bool operator!=(const NodePath& p_path) const;
- void operator=(const NodePath& p_path);
+ bool operator==(const NodePath &p_path) const;
+ bool operator!=(const NodePath &p_path) const;
+ void operator=(const NodePath &p_path);
void simplify();
NodePath simplified() const;
- NodePath(const Vector<StringName>& p_path,bool p_absolute,const String& p_property="");
- NodePath(const Vector<StringName>& p_path,const Vector<StringName>& p_subpath,bool p_absolute,const String& p_property="");
- NodePath(const NodePath& p_path);
- NodePath(const String& p_path);
+ NodePath(const Vector<StringName> &p_path, bool p_absolute, const String &p_property = "");
+ NodePath(const Vector<StringName> &p_path, const Vector<StringName> &p_subpath, bool p_absolute, const String &p_property = "");
+ NodePath(const NodePath &p_path);
+ NodePath(const String &p_path);
NodePath();
~NodePath();
};
diff --git a/core/path_remap.cpp b/core/path_remap.cpp
index bbaba71bba..bd76790b85 100644
--- a/core/path_remap.cpp
+++ b/core/path_remap.cpp
@@ -27,4 +27,3 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "path_remap.h"
-
diff --git a/core/pool_allocator.cpp b/core/pool_allocator.cpp
index 3260225ac3..68de05a765 100644
--- a/core/pool_allocator.cpp
+++ b/core/pool_allocator.cpp
@@ -28,43 +28,39 @@
/*************************************************************************/
#include "pool_allocator.h"
-#include "error_macros.h"
#include "core/os/os.h"
-#include "os/memory.h"
+#include "error_macros.h"
#include "os/copymem.h"
+#include "os/memory.h"
#include "print_string.h"
#include <assert.h>
-#define COMPACT_CHUNK( m_entry , m_to_pos ) \
-do { \
- void *_dst=&((unsigned char*)pool)[m_to_pos]; \
- void *_src=&((unsigned char*)pool)[(m_entry).pos]; \
- movemem(_dst,_src,aligned((m_entry).len)); \
- (m_entry).pos=m_to_pos; \
-} while (0);
+#define COMPACT_CHUNK(m_entry, m_to_pos) \
+ do { \
+ void *_dst = &((unsigned char *)pool)[m_to_pos]; \
+ void *_src = &((unsigned char *)pool)[(m_entry).pos]; \
+ movemem(_dst, _src, aligned((m_entry).len)); \
+ (m_entry).pos = m_to_pos; \
+ } while (0);
void PoolAllocator::mt_lock() const {
-
}
void PoolAllocator::mt_unlock() const {
-
}
+bool PoolAllocator::get_free_entry(EntryArrayPos *p_pos) {
-bool PoolAllocator::get_free_entry(EntryArrayPos* p_pos) {
-
- if (entry_count==entry_max)
+ if (entry_count == entry_max)
return false;
- for (int i=0;i<entry_max;i++) {
+ for (int i = 0; i < entry_max; i++) {
- if (entry_array[i].len==0) {
- *p_pos=i;
+ if (entry_array[i].len == 0) {
+ *p_pos = i;
return true;
}
-
}
ERR_PRINT("Out of memory Chunks!");
@@ -82,134 +78,121 @@ bool PoolAllocator::find_hole(EntryArrayPos *p_pos, int p_for_size) {
/* position where previous entry ends. Defaults to zero (begin of pool) */
- int prev_entry_end_pos=0;
+ int prev_entry_end_pos = 0;
- for (int i=0;i<entry_count;i++) {
+ for (int i = 0; i < entry_count; i++) {
-
- Entry &entry=entry_array[ entry_indices[ i ] ];
+ Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to previous entry */
- int hole_size=entry.pos-prev_entry_end_pos;
+ int hole_size = entry.pos - prev_entry_end_pos;
/* detemine if what we want fits in that hole */
- if (hole_size>=p_for_size) {
- *p_pos=i;
+ if (hole_size >= p_for_size) {
+ *p_pos = i;
return true;
}
/* prepare for next one */
- prev_entry_end_pos=entry_end(entry);
+ prev_entry_end_pos = entry_end(entry);
}
/* No holes between entrys, check at the end..*/
- if ( (pool_size-prev_entry_end_pos)>=p_for_size ) {
- *p_pos=entry_count;
+ if ((pool_size - prev_entry_end_pos) >= p_for_size) {
+ *p_pos = entry_count;
return true;
}
return false;
-
}
-
void PoolAllocator::compact(int p_up_to) {
- uint32_t prev_entry_end_pos=0;
-
- if (p_up_to<0)
- p_up_to=entry_count;
- for (int i=0;i<p_up_to;i++) {
+ uint32_t prev_entry_end_pos = 0;
+ if (p_up_to < 0)
+ p_up_to = entry_count;
+ for (int i = 0; i < p_up_to; i++) {
- Entry &entry=entry_array[ entry_indices[ i ] ];
+ Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to previous entry */
- int hole_size=entry.pos-prev_entry_end_pos;
+ int hole_size = entry.pos - prev_entry_end_pos;
/* if we can compact, do it */
- if (hole_size>0 && !entry.lock) {
-
- COMPACT_CHUNK(entry,prev_entry_end_pos);
+ if (hole_size > 0 && !entry.lock) {
+ COMPACT_CHUNK(entry, prev_entry_end_pos);
}
/* prepare for next one */
- prev_entry_end_pos=entry_end(entry);
+ prev_entry_end_pos = entry_end(entry);
}
-
-
}
void PoolAllocator::compact_up(int p_from) {
- uint32_t next_entry_end_pos=pool_size; // - static_area_size;
+ uint32_t next_entry_end_pos = pool_size; // - static_area_size;
- for (int i=entry_count-1;i>=p_from;i--) {
+ for (int i = entry_count - 1; i >= p_from; i--) {
-
- Entry &entry=entry_array[ entry_indices[ i ] ];
+ Entry &entry = entry_array[entry_indices[i]];
/* determine hole size to nextious entry */
- int hole_size=next_entry_end_pos-(entry.pos+aligned(entry.len));
+ int hole_size = next_entry_end_pos - (entry.pos + aligned(entry.len));
/* if we can compact, do it */
- if (hole_size>0 && !entry.lock) {
-
- COMPACT_CHUNK(entry,(next_entry_end_pos-aligned(entry.len)));
+ if (hole_size > 0 && !entry.lock) {
+ COMPACT_CHUNK(entry, (next_entry_end_pos - aligned(entry.len)));
}
/* prepare for next one */
- next_entry_end_pos=entry.pos;
+ next_entry_end_pos = entry.pos;
}
-
}
+bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry) {
-bool PoolAllocator::find_entry_index(EntryIndicesPos *p_map_pos,Entry *p_entry) {
+ EntryArrayPos entry_pos = entry_max;
- EntryArrayPos entry_pos=entry_max;
+ for (int i = 0; i < entry_count; i++) {
- for (int i=0;i<entry_count;i++) {
+ if (&entry_array[entry_indices[i]] == p_entry) {
- if (&entry_array[ entry_indices[ i ] ]==p_entry) {
-
- entry_pos=i;
+ entry_pos = i;
break;
}
}
- if (entry_pos==entry_max)
+ if (entry_pos == entry_max)
return false;
- *p_map_pos=entry_pos;
+ *p_map_pos = entry_pos;
return true;
-
}
PoolAllocator::ID PoolAllocator::alloc(int p_size) {
- ERR_FAIL_COND_V(p_size<1,POOL_ALLOCATOR_INVALID_ID);
+ ERR_FAIL_COND_V(p_size < 1, POOL_ALLOCATOR_INVALID_ID);
#ifdef DEBUG_ENABLED
if (p_size > free_mem) OS::get_singleton()->debug_break();
#endif
- ERR_FAIL_COND_V(p_size>free_mem,POOL_ALLOCATOR_INVALID_ID);
+ ERR_FAIL_COND_V(p_size > free_mem, POOL_ALLOCATOR_INVALID_ID);
mt_lock();
- if (entry_count==entry_max) {
+ if (entry_count == entry_max) {
mt_unlock();
ERR_PRINT("entry_count==entry_max");
return POOL_ALLOCATOR_INVALID_ID;
}
-
- int size_to_alloc=aligned(p_size);
+ int size_to_alloc = aligned(p_size);
EntryIndicesPos new_entry_indices_pos;
@@ -228,60 +211,59 @@ PoolAllocator::ID PoolAllocator::alloc(int p_size) {
EntryArrayPos new_entry_array_pos;
- bool found_free_entry=get_free_entry(&new_entry_array_pos);
+ bool found_free_entry = get_free_entry(&new_entry_array_pos);
if (!found_free_entry) {
mt_unlock();
- ERR_FAIL_COND_V( !found_free_entry , POOL_ALLOCATOR_INVALID_ID );
+ ERR_FAIL_COND_V(!found_free_entry, POOL_ALLOCATOR_INVALID_ID);
}
/* move all entry indices up, make room for this one */
- for (int i=entry_count;i>new_entry_indices_pos;i-- ) {
+ for (int i = entry_count; i > new_entry_indices_pos; i--) {
- entry_indices[i]=entry_indices[i-1];
+ entry_indices[i] = entry_indices[i - 1];
}
- entry_indices[new_entry_indices_pos]=new_entry_array_pos;
+ entry_indices[new_entry_indices_pos] = new_entry_array_pos;
entry_count++;
- Entry &entry=entry_array[ entry_indices[ new_entry_indices_pos ] ];
+ Entry &entry = entry_array[entry_indices[new_entry_indices_pos]];
- entry.len=p_size;
- entry.pos=(new_entry_indices_pos==0)?0:entry_end(entry_array[ entry_indices[ new_entry_indices_pos-1 ] ]); //alloc either at begining or end of previous
- entry.lock=0;
- entry.check=(check_count++)&CHECK_MASK;
- free_mem-=size_to_alloc;
- if (free_mem<free_mem_peak)
- free_mem_peak=free_mem;
+ entry.len = p_size;
+ entry.pos = (new_entry_indices_pos == 0) ? 0 : entry_end(entry_array[entry_indices[new_entry_indices_pos - 1]]); //alloc either at begining or end of previous
+ entry.lock = 0;
+ entry.check = (check_count++) & CHECK_MASK;
+ free_mem -= size_to_alloc;
+ if (free_mem < free_mem_peak)
+ free_mem_peak = free_mem;
- ID retval = (entry_indices[ new_entry_indices_pos ]<<CHECK_BITS)|entry.check;
+ ID retval = (entry_indices[new_entry_indices_pos] << CHECK_BITS) | entry.check;
mt_unlock();
//ERR_FAIL_COND_V( (uintptr_t)get(retval)%align != 0, retval );
return retval;
-
}
-PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) {
+PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) {
- unsigned int check=p_mem&CHECK_MASK;
- int entry=p_mem>>CHECK_BITS;
- ERR_FAIL_INDEX_V(entry,entry_max,NULL);
- ERR_FAIL_COND_V(entry_array[entry].check!=check,NULL);
- ERR_FAIL_COND_V(entry_array[entry].len==0,NULL);
+ unsigned int check = p_mem & CHECK_MASK;
+ int entry = p_mem >> CHECK_BITS;
+ ERR_FAIL_INDEX_V(entry, entry_max, NULL);
+ ERR_FAIL_COND_V(entry_array[entry].check != check, NULL);
+ ERR_FAIL_COND_V(entry_array[entry].len == 0, NULL);
return &entry_array[entry];
}
-const PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) const {
+const PoolAllocator::Entry *PoolAllocator::get_entry(ID p_mem) const {
- unsigned int check=p_mem&CHECK_MASK;
- int entry=p_mem>>CHECK_BITS;
- ERR_FAIL_INDEX_V(entry,entry_max,NULL);
- ERR_FAIL_COND_V(entry_array[entry].check!=check,NULL);
- ERR_FAIL_COND_V(entry_array[entry].len==0,NULL);
+ unsigned int check = p_mem & CHECK_MASK;
+ int entry = p_mem >> CHECK_BITS;
+ ERR_FAIL_INDEX_V(entry, entry_max, NULL);
+ ERR_FAIL_COND_V(entry_array[entry].check != check, NULL);
+ ERR_FAIL_COND_V(entry_array[entry].len == 0, NULL);
return &entry_array[entry];
}
@@ -289,7 +271,7 @@ const PoolAllocator::Entry * PoolAllocator::get_entry(ID p_mem) const {
void PoolAllocator::free(ID p_mem) {
mt_lock();
- Entry *e=get_entry(p_mem);
+ Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
ERR_PRINT("!e");
@@ -303,22 +285,20 @@ void PoolAllocator::free(ID p_mem) {
EntryIndicesPos entry_indices_pos;
- bool index_found = find_entry_index(&entry_indices_pos,e);
+ bool index_found = find_entry_index(&entry_indices_pos, e);
if (!index_found) {
mt_unlock();
ERR_FAIL_COND(!index_found);
}
+ for (int i = entry_indices_pos; i < (entry_count - 1); i++) {
-
- for (int i=entry_indices_pos;i<(entry_count-1);i++) {
-
- entry_indices[ i ] = entry_indices[ i+1 ];
+ entry_indices[i] = entry_indices[i + 1];
}
entry_count--;
- free_mem+=aligned(e->len);
+ free_mem += aligned(e->len);
e->clear();
mt_unlock();
}
@@ -328,7 +308,7 @@ int PoolAllocator::get_size(ID p_mem) const {
int size;
mt_lock();
- const Entry *e=get_entry(p_mem);
+ const Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
@@ -336,40 +316,40 @@ int PoolAllocator::get_size(ID p_mem) const {
return 0;
}
- size=e->len;
+ size = e->len;
mt_unlock();
return size;
}
-Error PoolAllocator::resize(ID p_mem,int p_new_size) {
+Error PoolAllocator::resize(ID p_mem, int p_new_size) {
mt_lock();
- Entry *e=get_entry(p_mem);
+ Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
- ERR_FAIL_COND_V(!e,ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!e, ERR_INVALID_PARAMETER);
}
if (needs_locking && e->lock) {
mt_unlock();
- ERR_FAIL_COND_V(e->lock,ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(e->lock, ERR_ALREADY_IN_USE);
}
int alloc_size = aligned(p_new_size);
- if (aligned(e->len)==alloc_size) {
+ if (aligned(e->len) == alloc_size) {
- e->len=p_new_size;
+ e->len = p_new_size;
mt_unlock();
return OK;
- } else if (e->len>(uint32_t)p_new_size) {
+ } else if (e->len > (uint32_t)p_new_size) {
free_mem += aligned(e->len);
free_mem -= alloc_size;
- e->len=p_new_size;
+ e->len = p_new_size;
mt_unlock();
return OK;
}
@@ -379,77 +359,74 @@ Error PoolAllocator::resize(ID p_mem,int p_new_size) {
if ((_free + aligned(e->len)) - alloc_size < 0) {
mt_unlock();
- ERR_FAIL_V( ERR_OUT_OF_MEMORY );
+ ERR_FAIL_V(ERR_OUT_OF_MEMORY);
};
EntryIndicesPos entry_indices_pos;
- bool index_found = find_entry_index(&entry_indices_pos,e);
+ bool index_found = find_entry_index(&entry_indices_pos, e);
if (!index_found) {
mt_unlock();
- ERR_FAIL_COND_V(!index_found,ERR_BUG);
+ ERR_FAIL_COND_V(!index_found, ERR_BUG);
}
//no need to move stuff around, it fits before the next block
int next_pos;
- if (entry_indices_pos+1 == entry_count) {
+ if (entry_indices_pos + 1 == entry_count) {
next_pos = pool_size; // - static_area_size;
} else {
- next_pos = entry_array[entry_indices[entry_indices_pos+1]].pos;
+ next_pos = entry_array[entry_indices[entry_indices_pos + 1]].pos;
};
if ((next_pos - e->pos) > alloc_size) {
- free_mem+=aligned(e->len);
- e->len=p_new_size;
- free_mem-=alloc_size;
+ free_mem += aligned(e->len);
+ e->len = p_new_size;
+ free_mem -= alloc_size;
mt_unlock();
return OK;
}
//it doesn't fit, compact around BEFORE current index (make room behind)
- compact(entry_indices_pos+1);
-
+ compact(entry_indices_pos + 1);
if ((next_pos - e->pos) > alloc_size) {
//now fits! hooray!
- free_mem+=aligned(e->len);
- e->len=p_new_size;
- free_mem-=alloc_size;
+ free_mem += aligned(e->len);
+ e->len = p_new_size;
+ free_mem -= alloc_size;
mt_unlock();
- if (free_mem<free_mem_peak)
- free_mem_peak=free_mem;
+ if (free_mem < free_mem_peak)
+ free_mem_peak = free_mem;
return OK;
}
//STILL doesn't fit, compact around AFTER current index (make room after)
- compact_up(entry_indices_pos+1);
+ compact_up(entry_indices_pos + 1);
- if ((entry_array[entry_indices[entry_indices_pos+1]].pos - e->pos) > alloc_size) {
+ if ((entry_array[entry_indices[entry_indices_pos + 1]].pos - e->pos) > alloc_size) {
//now fits! hooray!
- free_mem+=aligned(e->len);
- e->len=p_new_size;
- free_mem-=alloc_size;
+ free_mem += aligned(e->len);
+ e->len = p_new_size;
+ free_mem -= alloc_size;
mt_unlock();
- if (free_mem<free_mem_peak)
- free_mem_peak=free_mem;
+ if (free_mem < free_mem_peak)
+ free_mem_peak = free_mem;
return OK;
}
mt_unlock();
ERR_FAIL_V(ERR_OUT_OF_MEMORY);
-
}
-
Error PoolAllocator::lock(ID p_mem) {
if (!needs_locking)
return OK;
mt_lock();
- Entry *e=get_entry(p_mem);
+ Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
@@ -467,7 +444,7 @@ bool PoolAllocator::is_locked(ID p_mem) const {
return false;
mt_lock();
- const Entry *e=((PoolAllocator*)(this))->get_entry(p_mem);
+ const Entry *e = ((PoolAllocator *)(this))->get_entry(p_mem);
if (!e) {
mt_unlock();
@@ -483,91 +460,87 @@ const void *PoolAllocator::get(ID p_mem) const {
if (!needs_locking) {
- const Entry *e=get_entry(p_mem);
- ERR_FAIL_COND_V(!e,NULL);
+ const Entry *e = get_entry(p_mem);
+ ERR_FAIL_COND_V(!e, NULL);
return &pool[e->pos];
-
}
mt_lock();
- const Entry *e=get_entry(p_mem);
+ const Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
- ERR_FAIL_COND_V(!e,NULL);
+ ERR_FAIL_COND_V(!e, NULL);
}
- if (e->lock==0) {
+ if (e->lock == 0) {
mt_unlock();
- ERR_PRINT( "e->lock == 0" );
+ ERR_PRINT("e->lock == 0");
return NULL;
}
- if ((int)e->pos>=pool_size) {
+ if ((int)e->pos >= pool_size) {
mt_unlock();
ERR_PRINT("e->pos<0 || e->pos>=pool_size");
return NULL;
}
- const void *ptr=&pool[e->pos];
+ const void *ptr = &pool[e->pos];
mt_unlock();
return ptr;
-
}
void *PoolAllocator::get(ID p_mem) {
if (!needs_locking) {
- Entry *e=get_entry(p_mem);
+ Entry *e = get_entry(p_mem);
if (!e) {
- ERR_FAIL_COND_V(!e,NULL);
+ ERR_FAIL_COND_V(!e, NULL);
};
return &pool[e->pos];
-
}
mt_lock();
- Entry *e=get_entry(p_mem);
+ Entry *e = get_entry(p_mem);
if (!e) {
mt_unlock();
- ERR_FAIL_COND_V(!e,NULL);
+ ERR_FAIL_COND_V(!e, NULL);
}
- if (e->lock==0) {
+ if (e->lock == 0) {
//assert(0);
mt_unlock();
- ERR_PRINT( "e->lock == 0" );
+ ERR_PRINT("e->lock == 0");
return NULL;
}
- if ((int)e->pos>=pool_size) {
+ if ((int)e->pos >= pool_size) {
mt_unlock();
ERR_PRINT("e->pos<0 || e->pos>=pool_size");
return NULL;
}
- void *ptr=&pool[e->pos];
+ void *ptr = &pool[e->pos];
mt_unlock();
return ptr;
-
}
void PoolAllocator::unlock(ID p_mem) {
if (!needs_locking)
return;
mt_lock();
- Entry *e=get_entry(p_mem);
- if (e->lock == 0 ) {
+ Entry *e = get_entry(p_mem);
+ if (e->lock == 0) {
mt_unlock();
- ERR_PRINT( "e->lock == 0" );
+ ERR_PRINT("e->lock == 0");
return;
}
e->lock--;
@@ -576,7 +549,7 @@ void PoolAllocator::unlock(ID p_mem) {
int PoolAllocator::get_used_mem() const {
- return pool_size-free_mem;
+ return pool_size - free_mem;
}
int PoolAllocator::get_free_peak() {
@@ -589,72 +562,69 @@ int PoolAllocator::get_free_mem() {
return free_mem;
}
-void PoolAllocator::create_pool(void * p_mem,int p_size,int p_max_entries) {
+void PoolAllocator::create_pool(void *p_mem, int p_size, int p_max_entries) {
- pool=(uint8_t*)p_mem;
- pool_size=p_size;
+ pool = (uint8_t *)p_mem;
+ pool_size = p_size;
- entry_array = memnew_arr( Entry, p_max_entries );
- entry_indices = memnew_arr( int, p_max_entries );
+ entry_array = memnew_arr(Entry, p_max_entries);
+ entry_indices = memnew_arr(int, p_max_entries);
entry_max = p_max_entries;
- entry_count=0;
+ entry_count = 0;
- free_mem=p_size;
- free_mem_peak=p_size;
+ free_mem = p_size;
+ free_mem_peak = p_size;
- check_count=0;
+ check_count = 0;
}
-PoolAllocator::PoolAllocator(int p_size,bool p_needs_locking,int p_max_entries) {
+PoolAllocator::PoolAllocator(int p_size, bool p_needs_locking, int p_max_entries) {
- mem_ptr=memalloc( p_size);
+ mem_ptr = memalloc(p_size);
ERR_FAIL_COND(!mem_ptr);
- align=1;
- create_pool(mem_ptr,p_size,p_max_entries);
- needs_locking=p_needs_locking;
-
+ align = 1;
+ create_pool(mem_ptr, p_size, p_max_entries);
+ needs_locking = p_needs_locking;
}
-PoolAllocator::PoolAllocator(void * p_mem,int p_size, int p_align ,bool p_needs_locking,int p_max_entries) {
+PoolAllocator::PoolAllocator(void *p_mem, int p_size, int p_align, bool p_needs_locking, int p_max_entries) {
if (p_align > 1) {
- uint8_t *mem8=(uint8_t*)p_mem;
+ uint8_t *mem8 = (uint8_t *)p_mem;
uint64_t ofs = (uint64_t)mem8;
- if (ofs%p_align) {
- int dif = p_align-(ofs%p_align);
- mem8+=p_align-(ofs%p_align);
+ if (ofs % p_align) {
+ int dif = p_align - (ofs % p_align);
+ mem8 += p_align - (ofs % p_align);
p_size -= dif;
- p_mem = (void*)mem8;
+ p_mem = (void *)mem8;
};
};
- create_pool( p_mem,p_size,p_max_entries);
- needs_locking=p_needs_locking;
- align=p_align;
- mem_ptr=NULL;
+ create_pool(p_mem, p_size, p_max_entries);
+ needs_locking = p_needs_locking;
+ align = p_align;
+ mem_ptr = NULL;
}
-PoolAllocator::PoolAllocator(int p_align,int p_size,bool p_needs_locking,int p_max_entries) {
+PoolAllocator::PoolAllocator(int p_align, int p_size, bool p_needs_locking, int p_max_entries) {
- ERR_FAIL_COND(p_align<1);
- mem_ptr=Memory::alloc_static( p_size+p_align,"PoolAllocator()");
- uint8_t *mem8=(uint8_t*)mem_ptr;
+ ERR_FAIL_COND(p_align < 1);
+ mem_ptr = Memory::alloc_static(p_size + p_align, "PoolAllocator()");
+ uint8_t *mem8 = (uint8_t *)mem_ptr;
uint64_t ofs = (uint64_t)mem8;
- if (ofs%p_align)
- mem8+=p_align-(ofs%p_align);
- create_pool( mem8 ,p_size,p_max_entries);
- needs_locking=p_needs_locking;
- align=p_align;
+ if (ofs % p_align)
+ mem8 += p_align - (ofs % p_align);
+ create_pool(mem8, p_size, p_max_entries);
+ needs_locking = p_needs_locking;
+ align = p_align;
}
PoolAllocator::~PoolAllocator() {
if (mem_ptr)
- memfree( mem_ptr );
-
- memdelete_arr( entry_array );
- memdelete_arr( entry_indices );
+ memfree(mem_ptr);
+ memdelete_arr(entry_array);
+ memdelete_arr(entry_indices);
}
-
diff --git a/core/pool_allocator.h b/core/pool_allocator.h
index a5911688f7..1dc6167ceb 100644
--- a/core/pool_allocator.h
+++ b/core/pool_allocator.h
@@ -42,21 +42,21 @@
enum {
- POOL_ALLOCATOR_INVALID_ID=-1 ///< default invalid value. use INVALID_ID( id ) to test
+ POOL_ALLOCATOR_INVALID_ID = -1 ///< default invalid value. use INVALID_ID( id ) to test
};
class PoolAllocator {
public:
typedef int ID;
+
private:
enum {
- CHECK_BITS=8,
- CHECK_LEN=(1<<CHECK_BITS),
- CHECK_MASK=CHECK_LEN-1
+ CHECK_BITS = 8,
+ CHECK_LEN = (1 << CHECK_BITS),
+ CHECK_MASK = CHECK_LEN - 1
};
-
struct Entry {
unsigned int pos;
@@ -64,11 +64,15 @@ private:
unsigned int lock;
unsigned int check;
- inline void clear() { pos=0; len=0; lock=0; check=0; }
+ inline void clear() {
+ pos = 0;
+ len = 0;
+ lock = 0;
+ check = 0;
+ }
Entry() { clear(); }
};
-
typedef int EntryArrayPos;
typedef int EntryIndicesPos;
@@ -89,40 +93,40 @@ private:
bool needs_locking;
- inline int entry_end(const Entry& p_entry) const {
- return p_entry.pos+aligned(p_entry.len);
+ inline int entry_end(const Entry &p_entry) const {
+ return p_entry.pos + aligned(p_entry.len);
}
inline int aligned(int p_size) const {
- int rem=p_size%align;
+ int rem = p_size % align;
if (rem)
- p_size+=align-rem;
+ p_size += align - rem;
return p_size;
}
- void compact(int p_up_to=-1);
- void compact_up(int p_from=0);
- bool get_free_entry(EntryArrayPos* p_pos);
+ void compact(int p_up_to = -1);
+ void compact_up(int p_from = 0);
+ bool get_free_entry(EntryArrayPos *p_pos);
bool find_hole(EntryArrayPos *p_pos, int p_for_size);
- bool find_entry_index(EntryIndicesPos *p_map_pos,Entry *p_entry);
- Entry* get_entry(ID p_mem);
- const Entry* get_entry(ID p_mem) const;
+ bool find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry);
+ Entry *get_entry(ID p_mem);
+ const Entry *get_entry(ID p_mem) const;
+
+ void create_pool(void *p_mem, int p_size, int p_max_entries);
- void create_pool(void * p_mem,int p_size,int p_max_entries);
protected:
virtual void mt_lock() const; ///< Reimplement for custom mt locking
virtual void mt_unlock() const; ///< Reimplement for custom mt locking
public:
-
enum {
- DEFAULT_MAX_ALLOCS=4096,
+ DEFAULT_MAX_ALLOCS = 4096,
};
ID alloc(int p_size); ///< Alloc memory, get an ID on success, POOL_ALOCATOR_INVALID_ID on failure
void free(ID p_mem); ///< Free allocated memory
- Error resize(ID p_mem,int p_new_size); ///< resize a memory chunk
+ Error resize(ID p_mem, int p_new_size); ///< resize a memory chunk
int get_size(ID p_mem) const;
int get_free_mem(); ///< get free memory
@@ -135,12 +139,11 @@ public:
void unlock(ID p_mem);
bool is_locked(ID p_mem) const;
- PoolAllocator(int p_size,bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS);
- PoolAllocator(void * p_mem,int p_size, int p_align = 1, bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS);
- PoolAllocator(int p_align,int p_size,bool p_needs_locking=false,int p_max_entries=DEFAULT_MAX_ALLOCS);
+ PoolAllocator(int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
+ PoolAllocator(void *p_mem, int p_size, int p_align = 1, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
+ PoolAllocator(int p_align, int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
virtual ~PoolAllocator();
-
};
#endif
diff --git a/core/print_string.cpp b/core/print_string.cpp
index 36316af619..1cb07802c5 100644
--- a/core/print_string.cpp
+++ b/core/print_string.cpp
@@ -32,15 +32,15 @@
#include <stdio.h>
-static PrintHandlerList *print_handler_list=NULL;
-bool _print_line_enabled=true;
+static PrintHandlerList *print_handler_list = NULL;
+bool _print_line_enabled = true;
bool _print_error_enabled = true;
void add_print_handler(PrintHandlerList *p_handler) {
_global_lock();
- p_handler->next=print_handler_list;
- print_handler_list=p_handler;
+ p_handler->next = print_handler_list;
+ print_handler_list = p_handler;
_global_unlock();
}
@@ -51,43 +51,39 @@ void remove_print_handler(PrintHandlerList *p_handler) {
PrintHandlerList *prev = NULL;
PrintHandlerList *l = print_handler_list;
- while(l) {
+ while (l) {
- if (l==p_handler) {
+ if (l == p_handler) {
if (prev)
- prev->next=l->next;
+ prev->next = l->next;
else
- print_handler_list=l->next;
+ print_handler_list = l->next;
break;
}
- prev=l;
- l=l->next;
-
+ prev = l;
+ l = l->next;
}
//OS::get_singleton()->print("print handler list is %p\n",print_handler_list);
- ERR_FAIL_COND(l==NULL);
+ ERR_FAIL_COND(l == NULL);
_global_unlock();
-
}
-
void print_line(String p_string) {
if (!_print_line_enabled)
return;
- OS::get_singleton()->print("%s\n",p_string.utf8().get_data());
+ OS::get_singleton()->print("%s\n", p_string.utf8().get_data());
_global_lock();
PrintHandlerList *l = print_handler_list;
- while(l) {
+ while (l) {
- l->printfunc(l->userdata,p_string);
- l=l->next;
+ l->printfunc(l->userdata, p_string);
+ l = l->next;
}
_global_unlock();
-
}
diff --git a/core/print_string.h b/core/print_string.h
index a13abd4e38..ddbe55f8ed 100644
--- a/core/print_string.h
+++ b/core/print_string.h
@@ -33,21 +33,22 @@
extern void (*_print_func)(String);
-
-typedef void (*PrintHandlerFunc)(void*,const String& p_string);
+typedef void (*PrintHandlerFunc)(void *, const String &p_string);
struct PrintHandlerList {
PrintHandlerFunc printfunc;
void *userdata;
- PrintHandlerList*next;
+ PrintHandlerList *next;
- PrintHandlerList() { printfunc=0; next=0; userdata=0; }
+ PrintHandlerList() {
+ printfunc = 0;
+ next = 0;
+ userdata = 0;
+ }
};
-
-
void add_print_handler(PrintHandlerList *p_handler);
void remove_print_handler(PrintHandlerList *p_handler);
diff --git a/core/ref_ptr.cpp b/core/ref_ptr.cpp
index 29ffe974d2..867d0b9246 100644
--- a/core/ref_ptr.cpp
+++ b/core/ref_ptr.cpp
@@ -31,43 +31,41 @@
#include "reference.h"
#include "resource.h"
-void RefPtr::operator=(const RefPtr& p_other) {
+void RefPtr::operator=(const RefPtr &p_other) {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
- Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
+ Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0]));
*ref = *ref_other;
}
-bool RefPtr::operator==(const RefPtr& p_other) const {
+bool RefPtr::operator==(const RefPtr &p_other) const {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
- Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
+ Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0]));
return *ref == *ref_other;
}
-RefPtr::RefPtr(const RefPtr& p_other) {
+RefPtr::RefPtr(const RefPtr &p_other) {
- memnew_placement(&data[0],Ref<Reference>);
+ memnew_placement(&data[0], Ref<Reference>);
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
- Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference>*>( const_cast<char*>(&p_other.data[0]) );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
+ Ref<Reference> *ref_other = reinterpret_cast<Ref<Reference> *>(const_cast<char *>(&p_other.data[0]));
*ref = *ref_other;
}
bool RefPtr::is_null() const {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
return ref->is_null();
-
-
}
RID RefPtr::get_rid() const {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
if (ref->is_null())
return RID();
Resource *res = (*ref)->cast_to<Resource>();
@@ -78,21 +76,18 @@ RID RefPtr::get_rid() const {
void RefPtr::unref() {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
ref->unref();
}
RefPtr::RefPtr() {
- ERR_FAIL_COND(sizeof(Ref<Reference>)>DATASIZE);
- memnew_placement(&data[0],Ref<Reference>);
+ ERR_FAIL_COND(sizeof(Ref<Reference>) > DATASIZE);
+ memnew_placement(&data[0], Ref<Reference>);
}
-
RefPtr::~RefPtr() {
- Ref<Reference> *ref = reinterpret_cast<Ref<Reference>*>( &data[0] );
+ Ref<Reference> *ref = reinterpret_cast<Ref<Reference> *>(&data[0]);
ref->~Ref<Reference>();
}
-
-
diff --git a/core/ref_ptr.h b/core/ref_ptr.h
index c9824639dc..04c7bb51ed 100644
--- a/core/ref_ptr.h
+++ b/core/ref_ptr.h
@@ -36,27 +36,24 @@
#include "rid.h"
-
class RefPtr {
enum {
- DATASIZE=sizeof(void*) //*4 -ref was shrunk
+ DATASIZE = sizeof(void *) //*4 -ref was shrunk
};
mutable char data[DATASIZE]; // too much probably, virtual class + pointer
public:
-
bool is_null() const;
- void operator=(const RefPtr& p_other);
- bool operator==(const RefPtr& p_other) const;
+ void operator=(const RefPtr &p_other);
+ bool operator==(const RefPtr &p_other) const;
RID get_rid() const;
void unref();
_FORCE_INLINE_ void *get_data() const { return data; }
- RefPtr(const RefPtr& p_other);
+ RefPtr(const RefPtr &p_other);
RefPtr();
~RefPtr();
-
};
#endif // REF_PTR_H
diff --git a/core/reference.cpp b/core/reference.cpp
index 5e8244d2ca..5285888f78 100644
--- a/core/reference.cpp
+++ b/core/reference.cpp
@@ -30,7 +30,6 @@
#include "script_language.h"
-
bool Reference::init_ref() {
if (refcount.ref()) {
@@ -39,7 +38,7 @@ bool Reference::init_ref() {
// at the same time, which is never likely to happen (would be crazy to do)
// so don't do it.
- if (refcount_init.get()>0) {
+ if (refcount_init.get() > 0) {
refcount_init.unref();
refcount.unref(); // first referencing is already 1, so compensate for the ref above
}
@@ -49,30 +48,27 @@ bool Reference::init_ref() {
return false;
}
-
}
-
void Reference::_bind_methods() {
- ClassDB::bind_method(D_METHOD("init_ref"),&Reference::init_ref);
- ClassDB::bind_method(D_METHOD("reference"),&Reference::reference);
- ClassDB::bind_method(D_METHOD("unreference"),&Reference::unreference);
+ ClassDB::bind_method(D_METHOD("init_ref"), &Reference::init_ref);
+ ClassDB::bind_method(D_METHOD("reference"), &Reference::reference);
+ ClassDB::bind_method(D_METHOD("unreference"), &Reference::unreference);
}
int Reference::reference_get_count() const {
return refcount.get();
}
-void Reference::reference(){
+void Reference::reference() {
refcount.ref();
if (get_script_instance()) {
get_script_instance()->refcount_incremented();
}
-
}
-bool Reference::unreference(){
+bool Reference::unreference() {
bool die = refcount.unref();
@@ -81,7 +77,6 @@ bool Reference::unreference(){
}
return die;
-
}
Reference::Reference() {
@@ -90,14 +85,12 @@ Reference::Reference() {
refcount_init.init();
}
-
Reference::~Reference() {
-
}
Variant WeakRef::get_ref() const {
- if (ref==0)
+ if (ref == 0)
return Variant();
Object *obj = ObjectDB::get_instance(ref);
@@ -113,21 +106,21 @@ Variant WeakRef::get_ref() const {
}
void WeakRef::set_obj(Object *p_object) {
- ref=p_object ? p_object->get_instance_ID() : 0;
+ ref = p_object ? p_object->get_instance_ID() : 0;
}
-void WeakRef::set_ref(const REF& p_ref) {
+void WeakRef::set_ref(const REF &p_ref) {
- ref=p_ref.is_valid() ? p_ref->get_instance_ID() : 0;
+ ref = p_ref.is_valid() ? p_ref->get_instance_ID() : 0;
}
WeakRef::WeakRef() {
- ref=0;
+ ref = 0;
}
void WeakRef::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_ref:Object"),&WeakRef::get_ref);
+ ClassDB::bind_method(D_METHOD("get_ref:Object"), &WeakRef::get_ref);
}
#if 0
diff --git a/core/reference.h b/core/reference.h
index e130b4c2b4..af7071a198 100644
--- a/core/reference.h
+++ b/core/reference.h
@@ -29,27 +29,26 @@
#ifndef REFERENCE_H
#define REFERENCE_H
+#include "class_db.h"
#include "object.h"
-#include "safe_refcount.h"
#include "ref_ptr.h"
-#include "class_db.h"
+#include "safe_refcount.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-class Reference : public Object{
+class Reference : public Object {
- GDCLASS( Reference, Object );
-friend class RefBase;
+ GDCLASS(Reference, Object);
+ friend class RefBase;
SafeRefCount refcount;
SafeRefCount refcount_init;
-protected:
+protected:
static void _bind_methods();
-public:
-
- _FORCE_INLINE_ bool is_referenced() const { return refcount_init.get()<1; }
+public:
+ _FORCE_INLINE_ bool is_referenced() const { return refcount_init.get() < 1; }
bool init_ref();
void reference();
bool unreference();
@@ -74,73 +73,71 @@ public:
};
#endif
-template<class T>
+template <class T>
class Ref {
T *reference;
- void ref( const Ref& p_from ) {
+ void ref(const Ref &p_from) {
- if (p_from.reference==reference)
+ if (p_from.reference == reference)
return;
unref();
- reference=p_from.reference;
+ reference = p_from.reference;
if (reference)
reference->reference();
}
- void ref_pointer( T* p_ref ) {
+ void ref_pointer(T *p_ref) {
ERR_FAIL_COND(!p_ref);
if (p_ref->init_ref())
- reference=p_ref;
+ reference = p_ref;
}
//virtual Reference * get_reference() const { return reference; }
public:
+ _FORCE_INLINE_ bool operator<(const Ref<T> &p_r) const {
-
- _FORCE_INLINE_ bool operator<(const Ref<T>& p_r) const {
-
- return reference<p_r.reference;
+ return reference < p_r.reference;
}
- _FORCE_INLINE_ bool operator==(const Ref<T>& p_r) const {
+ _FORCE_INLINE_ bool operator==(const Ref<T> &p_r) const {
- return reference==p_r.reference;
+ return reference == p_r.reference;
}
- _FORCE_INLINE_ bool operator!=(const Ref<T>& p_r) const {
+ _FORCE_INLINE_ bool operator!=(const Ref<T> &p_r) const {
- return reference!=p_r.reference;
+ return reference != p_r.reference;
}
- _FORCE_INLINE_ T* operator->() {
+ _FORCE_INLINE_ T *operator->() {
return reference;
}
- _FORCE_INLINE_ T* operator*() {
+ _FORCE_INLINE_ T *operator*() {
return reference;
}
- _FORCE_INLINE_ const T* operator->() const {
+ _FORCE_INLINE_ const T *operator->() const {
return reference;
}
- _FORCE_INLINE_ const T* ptr() const {
+ _FORCE_INLINE_ const T *ptr() const {
return reference;
}
- _FORCE_INLINE_ T* ptr() {
+ _FORCE_INLINE_ T *ptr() {
return reference;
}
- _FORCE_INLINE_ const T* operator*() const {
+ _FORCE_INLINE_ const T *operator*() const {
return reference;
}
@@ -148,7 +145,7 @@ public:
RefPtr get_ref_ptr() const {
RefPtr refptr;
- Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() );
+ Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data());
*irr = *this;
return refptr;
};
@@ -164,123 +161,120 @@ public:
#if 1
operator Variant() const {
- return Variant( get_ref_ptr() );
+ return Variant(get_ref_ptr());
}
#endif
- void operator=( const Ref& p_from ) {
+ void operator=(const Ref &p_from) {
ref(p_from);
}
- template<class T_Other>
- void operator=( const Ref<T_Other>& p_from ) {
+ template <class T_Other>
+ void operator=(const Ref<T_Other> &p_from) {
- Reference *refb = const_cast<Reference*>(static_cast<const Reference*>(p_from.ptr()));
+ Reference *refb = const_cast<Reference *>(static_cast<const Reference *>(p_from.ptr()));
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
- void operator=( const RefPtr& p_refptr ) {
+ void operator=(const RefPtr &p_refptr) {
- Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( p_refptr.get_data() );
+ Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(p_refptr.get_data());
Reference *refb = irr->ptr();
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
+ void operator=(const Variant &p_variant) {
- void operator=( const Variant& p_variant ) {
-
- RefPtr refptr=p_variant;
- Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() );
+ RefPtr refptr = p_variant;
+ Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data());
Reference *refb = irr->ptr();
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
- Ref( const Ref& p_from ) {
+ Ref(const Ref &p_from) {
- reference=NULL;
+ reference = NULL;
ref(p_from);
}
- template<class T_Other>
- Ref( const Ref<T_Other>& p_from ) {
+ template <class T_Other>
+ Ref(const Ref<T_Other> &p_from) {
- reference=NULL;
- Reference *refb = const_cast<Reference*>(static_cast<const Reference*>(p_from.ptr()));
+ reference = NULL;
+ Reference *refb = const_cast<Reference *>(static_cast<const Reference *>(p_from.ptr()));
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
- Ref( T* p_reference ) {
+ Ref(T *p_reference) {
if (p_reference)
ref_pointer(p_reference);
else
- reference=NULL;
+ reference = NULL;
}
- Ref( const Variant& p_variant) {
+ Ref(const Variant &p_variant) {
- RefPtr refptr=p_variant;
- Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( refptr.get_data() );
- reference=NULL;
+ RefPtr refptr = p_variant;
+ Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(refptr.get_data());
+ reference = NULL;
Reference *refb = irr->ptr();
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
+ Ref(const RefPtr &p_refptr) {
-
- Ref( const RefPtr& p_refptr) {
-
- Ref<Reference> * irr = reinterpret_cast<Ref<Reference>*>( p_refptr.get_data() );
- reference=NULL;
+ Ref<Reference> *irr = reinterpret_cast<Ref<Reference> *>(p_refptr.get_data());
+ reference = NULL;
Reference *refb = irr->ptr();
if (!refb) {
unref();
return;
}
Ref r;
- r.reference=refb->cast_to<T>();
+ r.reference = refb->cast_to<T>();
ref(r);
- r.reference=NULL;
+ r.reference = NULL;
}
- inline bool is_valid() const { return reference!=NULL; }
- inline bool is_null() const { return reference==NULL; }
+ inline bool is_valid() const { return reference != NULL; }
+ inline bool is_null() const { return reference == NULL; }
void unref() {
//TODO this should be moved to mutexes, since this engine does not really
@@ -291,99 +285,92 @@ public:
memdelete(reference);
}
- reference=NULL;
+ reference = NULL;
}
void instance() {
- ref( memnew( T ));
+ ref(memnew(T));
}
Ref() {
- reference=NULL;
+ reference = NULL;
}
~Ref() {
unref();
}
-
};
typedef Ref<Reference> REF;
-
class WeakRef : public Reference {
- GDCLASS(WeakRef,Reference);
+ GDCLASS(WeakRef, Reference);
ObjectID ref;
+
protected:
static void _bind_methods();
public:
Variant get_ref() const;
void set_obj(Object *p_object);
- void set_ref(const REF& p_ref);
+ void set_ref(const REF &p_ref);
WeakRef();
};
#ifdef PTRCALL_ENABLED
-template<class T>
-struct PtrToArg< Ref<T> > {
+template <class T>
+struct PtrToArg<Ref<T> > {
- _FORCE_INLINE_ static Ref<T> convert(const void* p_ptr) {
+ _FORCE_INLINE_ static Ref<T> convert(const void *p_ptr) {
- return Ref<T>(reinterpret_cast<const T*>(p_ptr));
+ return Ref<T>(reinterpret_cast<const T *>(p_ptr));
}
- _FORCE_INLINE_ static void encode(Ref<T> p_val,const void* p_ptr) {
+ _FORCE_INLINE_ static void encode(Ref<T> p_val, const void *p_ptr) {
- *(Ref<Reference>*)p_ptr=p_val;
+ *(Ref<Reference> *)p_ptr = p_val;
}
-
};
+template <class T>
+struct PtrToArg<const Ref<T> &> {
-template<class T>
-struct PtrToArg< const Ref<T>& > {
+ _FORCE_INLINE_ static Ref<T> convert(const void *p_ptr) {
- _FORCE_INLINE_ static Ref<T> convert(const void* p_ptr) {
-
- return Ref<T>(reinterpret_cast<const T*>(p_ptr));
+ return Ref<T>(reinterpret_cast<const T *>(p_ptr));
}
-
};
-
//this is for RefPtr
-template<>
-struct PtrToArg< RefPtr > {
+template <>
+struct PtrToArg<RefPtr> {
- _FORCE_INLINE_ static RefPtr convert(const void* p_ptr) {
+ _FORCE_INLINE_ static RefPtr convert(const void *p_ptr) {
- return Ref<Reference>(reinterpret_cast<const Reference*>(p_ptr)).get_ref_ptr();
+ return Ref<Reference>(reinterpret_cast<const Reference *>(p_ptr)).get_ref_ptr();
}
- _FORCE_INLINE_ static void encode(RefPtr p_val,const void* p_ptr) {
+ _FORCE_INLINE_ static void encode(RefPtr p_val, const void *p_ptr) {
Ref<Reference> r = p_val;
- *(Ref<Reference>*)p_ptr=r;
+ *(Ref<Reference> *)p_ptr = r;
}
-
};
-template<>
-struct PtrToArg< const RefPtr& > {
+template <>
+struct PtrToArg<const RefPtr &> {
- _FORCE_INLINE_ static RefPtr convert(const void* p_ptr) {
+ _FORCE_INLINE_ static RefPtr convert(const void *p_ptr) {
- return Ref<Reference>(reinterpret_cast<const Reference*>(p_ptr)).get_ref_ptr();
+ return Ref<Reference>(reinterpret_cast<const Reference *>(p_ptr)).get_ref_ptr();
}
-
};
#endif
diff --git a/core/register_core_types.cpp b/core/register_core_types.cpp
index 00f6f8662f..7ebacb5b5d 100644
--- a/core/register_core_types.cpp
+++ b/core/register_core_types.cpp
@@ -28,90 +28,82 @@
/*************************************************************************/
#include "register_core_types.h"
-#include "io/tcp_server.h"
-#include "io/packet_peer_udp.h"
-#include "io/config_file.h"
-#include "os/main_loop.h"
-#include "io/packet_peer.h"
-#include "math/a_star.h"
-#include "math/triangle_mesh.h"
-#include "global_config.h"
-#include "class_db.h"
-#include "geometry.h"
#include "bind/core_bind.h"
-#include "core_string_names.h"
-#include "path_remap.h"
-#include "translation.h"
+#include "class_db.h"
#include "compressed_translation.h"
-#include "io/translation_loader_po.h"
+#include "core/io/xml_parser.h"
+#include "core_string_names.h"
+#include "func_ref.h"
+#include "geometry.h"
+#include "global_config.h"
+#include "input_map.h"
+#include "io/config_file.h"
+#include "io/http_client.h"
+#include "io/packet_peer.h"
+#include "io/packet_peer_udp.h"
+#include "io/pck_packer.h"
#include "io/resource_format_binary.h"
#include "io/resource_import.h"
#include "io/stream_peer_ssl.h"
+#include "io/tcp_server.h"
+#include "io/translation_loader_po.h"
+#include "math/a_star.h"
+#include "math/triangle_mesh.h"
#include "os/input.h"
-#include "core/io/xml_parser.h"
-#include "io/http_client.h"
-#include "io/pck_packer.h"
+#include "os/main_loop.h"
#include "packed_data_container.h"
-#include "func_ref.h"
-#include "input_map.h"
+#include "path_remap.h"
+#include "translation.h"
#include "undo_redo.h"
-static ResourceFormatSaverBinary *resource_saver_binary=NULL;
-static ResourceFormatLoaderBinary *resource_loader_binary=NULL;
-static ResourceFormatImporter *resource_format_importer=NULL;
+static ResourceFormatSaverBinary *resource_saver_binary = NULL;
+static ResourceFormatLoaderBinary *resource_loader_binary = NULL;
+static ResourceFormatImporter *resource_format_importer = NULL;
-static _ResourceLoader *_resource_loader=NULL;
-static _ResourceSaver *_resource_saver=NULL;
-static _OS *_os=NULL;
-static _Engine *_engine=NULL;
-static _ClassDB *_classdb=NULL;
+static _ResourceLoader *_resource_loader = NULL;
+static _ResourceSaver *_resource_saver = NULL;
+static _OS *_os = NULL;
+static _Engine *_engine = NULL;
+static _ClassDB *_classdb = NULL;
static _Marshalls *_marshalls = NULL;
-static TranslationLoaderPO *resource_format_po=NULL;
+static TranslationLoaderPO *resource_format_po = NULL;
-static IP* ip = NULL;
+static IP *ip = NULL;
-static _Geometry *_geometry=NULL;
+static _Geometry *_geometry = NULL;
extern Mutex *_global_mutex;
-
-
extern void register_variant_methods();
extern void unregister_variant_methods();
-
void register_core_types() {
ObjectDB::setup();
ResourceCache::setup();
MemoryPool::setup();
- _global_mutex=Mutex::create();
-
+ _global_mutex = Mutex::create();
StringName::setup();
-
register_variant_methods();
-
CoreStringNames::create();
- resource_format_po = memnew( TranslationLoaderPO );
- ResourceLoader::add_resource_format_loader( resource_format_po );
-
+ resource_format_po = memnew(TranslationLoaderPO);
+ ResourceLoader::add_resource_format_loader(resource_format_po);
- resource_saver_binary = memnew( ResourceFormatSaverBinary );
+ resource_saver_binary = memnew(ResourceFormatSaverBinary);
ResourceSaver::add_resource_format_saver(resource_saver_binary);
- resource_loader_binary = memnew( ResourceFormatLoaderBinary );
+ resource_loader_binary = memnew(ResourceFormatLoaderBinary);
ResourceLoader::add_resource_format_loader(resource_loader_binary);
- resource_format_importer = memnew( ResourceFormatImporter );
+ resource_format_importer = memnew(ResourceFormatImporter);
ResourceLoader::add_resource_format_loader(resource_format_importer);
ClassDB::register_class<Object>();
-
ClassDB::register_class<Reference>();
ClassDB::register_class<WeakRef>();
ClassDB::register_class<Resource>();
@@ -153,58 +145,47 @@ void register_core_types() {
ip = IP::create();
-
_geometry = memnew(_Geometry);
-
- _resource_loader=memnew(_ResourceLoader);
- _resource_saver=memnew(_ResourceSaver);
- _os=memnew(_OS);
- _engine=memnew(_Engine);
- _classdb=memnew(_ClassDB);
+ _resource_loader = memnew(_ResourceLoader);
+ _resource_saver = memnew(_ResourceSaver);
+ _os = memnew(_OS);
+ _engine = memnew(_Engine);
+ _classdb = memnew(_ClassDB);
_marshalls = memnew(_Marshalls);
-
-
-
}
void register_core_settings() {
//since in register core types, globals may not e present
- GLOBAL_DEF( "network/packets/packet_stream_peer_max_buffer_po2",(16));
-
+ GLOBAL_DEF("network/packets/packet_stream_peer_max_buffer_po2", (16));
}
void register_core_singletons() {
-
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("GlobalConfig",GlobalConfig::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("IP",IP::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Geometry",_Geometry::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ResourceLoader",_ResourceLoader::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ResourceSaver",_ResourceSaver::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("OS",_OS::get_singleton() ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Engine",_Engine::get_singleton() ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("ClassDB",_classdb ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Marshalls",_Marshalls::get_singleton() ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("TranslationServer",TranslationServer::get_singleton() ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Input",Input::get_singleton() ) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("InputMap",InputMap::get_singleton() ) );
-
-
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("GlobalConfig", GlobalConfig::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("IP", IP::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Geometry", _Geometry::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ResourceLoader", _ResourceLoader::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ResourceSaver", _ResourceSaver::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("OS", _OS::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Engine", _Engine::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ClassDB", _classdb));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Marshalls", _Marshalls::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("TranslationServer", TranslationServer::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Input", Input::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("InputMap", InputMap::get_singleton()));
}
void unregister_core_types() {
+ memdelete(_resource_loader);
+ memdelete(_resource_saver);
+ memdelete(_os);
+ memdelete(_engine);
+ memdelete(_classdb);
+ memdelete(_marshalls);
-
- memdelete( _resource_loader );
- memdelete( _resource_saver );
- memdelete( _os);
- memdelete( _engine );
- memdelete( _classdb );
- memdelete( _marshalls );
-
- memdelete( _geometry );
+ memdelete(_geometry);
if (resource_saver_binary)
memdelete(resource_saver_binary);
@@ -213,13 +194,11 @@ void unregister_core_types() {
if (resource_format_importer)
memdelete(resource_format_importer);
-
- memdelete( resource_format_po );
+ memdelete(resource_format_po);
if (ip)
memdelete(ip);
-
ObjectDB::cleanup();
unregister_variant_methods();
@@ -231,9 +210,8 @@ void unregister_core_types() {
if (_global_mutex) {
memdelete(_global_mutex);
- _global_mutex=NULL; //still needed at a few places
+ _global_mutex = NULL; //still needed at a few places
};
MemoryPool::cleanup();
-
}
diff --git a/core/resource.cpp b/core/resource.cpp
index fe3cb2df92..e9ce4038d9 100644
--- a/core/resource.cpp
+++ b/core/resource.cpp
@@ -29,40 +29,36 @@
#include "resource.h"
#include "core_string_names.h"
-#include "os/file_access.h"
#include "io/resource_loader.h"
+#include "os/file_access.h"
#include "script_language.h"
#include <stdio.h>
-
void Resource::emit_changed() {
emit_signal(CoreStringNames::get_singleton()->changed);
}
-
void Resource::_resource_path_changed() {
-
-
}
-void Resource::set_path(const String& p_path, bool p_take_over) {
+void Resource::set_path(const String &p_path, bool p_take_over) {
- if (path_cache==p_path)
+ if (path_cache == p_path)
return;
- if (path_cache!="") {
+ if (path_cache != "") {
ResourceCache::lock->write_lock();
ResourceCache::resources.erase(path_cache);
ResourceCache::lock->write_unlock();
}
- path_cache="";
+ path_cache = "";
ResourceCache::lock->read_lock();
- bool has_path = ResourceCache::resources.has( p_path );
+ bool has_path = ResourceCache::resources.has(p_path);
ResourceCache::lock->read_unlock();
if (has_path) {
@@ -72,28 +68,26 @@ void Resource::set_path(const String& p_path, bool p_take_over) {
ResourceCache::resources.get(p_path)->set_name("");
ResourceCache::lock->write_unlock();
} else {
- ERR_EXPLAIN("Another resource is loaded from path: "+p_path);
+ ERR_EXPLAIN("Another resource is loaded from path: " + p_path);
ResourceCache::lock->read_lock();
- bool exists = ResourceCache::resources.has( p_path );
+ bool exists = ResourceCache::resources.has(p_path);
ResourceCache::lock->read_unlock();
- ERR_FAIL_COND( exists );
+ ERR_FAIL_COND(exists);
}
-
}
- path_cache=p_path;
+ path_cache = p_path;
- if (path_cache!="") {
+ if (path_cache != "") {
ResourceCache::lock->write_lock();
- ResourceCache::resources[path_cache]=this;
+ ResourceCache::resources[path_cache] = this;
ResourceCache::lock->write_unlock();
}
_change_notify("resource_path");
_resource_path_changed();
-
}
String Resource::get_path() const {
@@ -103,20 +97,18 @@ String Resource::get_path() const {
void Resource::set_subindex(int p_sub_index) {
- subindex=p_sub_index;
+ subindex = p_sub_index;
}
-int Resource::get_subindex() const{
+int Resource::get_subindex() const {
return subindex;
}
+void Resource::set_name(const String &p_name) {
-void Resource::set_name(const String& p_name) {
-
- name=p_name;
+ name = p_name;
_change_notify("resource_name");
-
}
String Resource::get_name() const {
@@ -130,12 +122,11 @@ bool Resource::editor_can_reload_from_file() {
void Resource::reload_from_file() {
-
- String path=get_path();
+ String path = get_path();
if (!path.is_resource_file())
return;
- Ref<Resource> s = ResourceLoader::load(path,get_class(),true);
+ Ref<Resource> s = ResourceLoader::load(path, get_class(), true);
if (!s.is_valid())
return;
@@ -143,56 +134,51 @@ void Resource::reload_from_file() {
List<PropertyInfo> pi;
s->get_property_list(&pi);
- for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
- if (E->get().name=="resource_path")
+ if (E->get().name == "resource_path")
continue; //do not change path
- set(E->get().name,s->get(E->get().name));
-
+ set(E->get().name, s->get(E->get().name));
}
}
-
Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, Map<Ref<Resource>, Ref<Resource> > &remap_cache) {
-
List<PropertyInfo> plist;
get_property_list(&plist);
+ Resource *r = (Resource *)ClassDB::instance(get_class());
+ ERR_FAIL_COND_V(!r, Ref<Resource>());
- Resource *r = (Resource*)ClassDB::instance(get_class());
- ERR_FAIL_COND_V(!r,Ref<Resource>());
-
- r->local_scene=p_for_scene;
+ r->local_scene = p_for_scene;
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
Variant p = get(E->get().name);
- if (p.get_type()==Variant::OBJECT) {
+ if (p.get_type() == Variant::OBJECT) {
RES sr = p;
if (sr.is_valid()) {
if (sr->is_local_to_scene()) {
if (remap_cache.has(sr)) {
- p=remap_cache[sr];
+ p = remap_cache[sr];
} else {
-
- RES dupe = sr->duplicate_for_local_scene(p_for_scene,remap_cache);
- p=dupe;
- remap_cache[sr]=dupe;
+ RES dupe = sr->duplicate_for_local_scene(p_for_scene, remap_cache);
+ p = dupe;
+ remap_cache[sr] = dupe;
}
}
}
}
- r->set(E->get().name,p);
+ r->set(E->get().name, p);
}
return Ref<Resource>(r);
@@ -200,50 +186,45 @@ Ref<Resource> Resource::duplicate_for_local_scene(Node *p_for_scene, Map<Ref<Res
Ref<Resource> Resource::duplicate(bool p_subresources) {
-
List<PropertyInfo> plist;
get_property_list(&plist);
+ Resource *r = (Resource *)ClassDB::instance(get_class());
+ ERR_FAIL_COND_V(!r, Ref<Resource>());
- Resource *r = (Resource*)ClassDB::instance(get_class());
- ERR_FAIL_COND_V(!r,Ref<Resource>());
-
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
Variant p = get(E->get().name);
- if (p.get_type()==Variant::OBJECT && p_subresources) {
+ if (p.get_type() == Variant::OBJECT && p_subresources) {
RES sr = p;
if (sr.is_valid())
- p=sr->duplicate(true);
+ p = sr->duplicate(true);
}
- r->set(E->get().name,p);
+ r->set(E->get().name, p);
}
return Ref<Resource>(r);
}
+void Resource::_set_path(const String &p_path) {
-void Resource::_set_path(const String& p_path) {
-
- set_path(p_path,false);
+ set_path(p_path, false);
}
-void Resource::_take_over_path(const String& p_path) {
+void Resource::_take_over_path(const String &p_path) {
- set_path(p_path,true);
+ set_path(p_path, true);
}
-
RID Resource::get_rid() const {
return RID();
}
-
void Resource::register_owner(Object *p_owner) {
owners.insert(p_owner->get_instance_ID());
@@ -252,23 +233,20 @@ void Resource::register_owner(Object *p_owner) {
void Resource::unregister_owner(Object *p_owner) {
owners.erase(p_owner->get_instance_ID());
-
}
-
void Resource::notify_change_to_owners() {
- for(Set<ObjectID>::Element *E=owners.front();E;E=E->next()) {
+ for (Set<ObjectID>::Element *E = owners.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->get());
ERR_EXPLAIN("Object was deleted, while still owning a resource");
ERR_CONTINUE(!obj); //wtf
//TODO store string
- obj->call("resource_changed",RES(this));
+ obj->call("resource_changed", RES(this));
}
}
-
#ifdef TOOLS_ENABLED
uint32_t Resource::hash_edited_version() const {
@@ -278,25 +256,24 @@ uint32_t Resource::hash_edited_version() const {
List<PropertyInfo> plist;
get_property_list(&plist);
- for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (E->get().type==Variant::OBJECT && E->get().hint==PROPERTY_HINT_RESOURCE_TYPE) {
+ if (E->get().type == Variant::OBJECT && E->get().hint == PROPERTY_HINT_RESOURCE_TYPE) {
RES res = get(E->get().name);
if (res.is_valid()) {
- hash = hash_djb2_one_32(res->hash_edited_version(),hash);
+ hash = hash_djb2_one_32(res->hash_edited_version(), hash);
}
}
}
return hash;
-
}
#endif
void Resource::set_local_to_scene(bool p_enable) {
- local_to_scene=p_enable;
+ local_to_scene = p_enable;
}
bool Resource::is_local_to_scene() const {
@@ -304,7 +281,7 @@ bool Resource::is_local_to_scene() const {
return local_to_scene;
}
-Node* Resource::get_local_scene() const {
+Node *Resource::get_local_scene() const {
if (local_scene)
return local_scene;
@@ -322,51 +299,46 @@ void Resource::setup_local_to_scene() {
get_script_instance()->call("_setup_local_to_scene");
}
-Node* (*Resource::_get_local_scene_func)()=NULL;
-
+Node *(*Resource::_get_local_scene_func)() = NULL;
void Resource::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_path","path"),&Resource::_set_path);
- ClassDB::bind_method(D_METHOD("take_over_path","path"),&Resource::_take_over_path);
- ClassDB::bind_method(D_METHOD("get_path"),&Resource::get_path);
- ClassDB::bind_method(D_METHOD("set_name","name"),&Resource::set_name);
- ClassDB::bind_method(D_METHOD("get_name"),&Resource::get_name);
- ClassDB::bind_method(D_METHOD("get_rid"),&Resource::get_rid);
- ClassDB::bind_method(D_METHOD("set_local_to_scene","enable"),&Resource::set_local_to_scene);
- ClassDB::bind_method(D_METHOD("is_local_to_scene"),&Resource::is_local_to_scene);
- ClassDB::bind_method(D_METHOD("get_local_scene:Node"),&Resource::get_local_scene);
- ClassDB::bind_method(D_METHOD("setup_local_to_scene"),&Resource::setup_local_to_scene);
-
- ClassDB::bind_method(D_METHOD("duplicate","subresources"),&Resource::duplicate,DEFVAL(false));
- ADD_SIGNAL( MethodInfo("changed") );
- ADD_GROUP("Resource","resource_");
- ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"resource_local_to_scene" ), "set_local_to_scene","is_local_to_scene");
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"resource_path",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR ), "set_path","get_path");
- ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"resource_name"), "set_name","get_name");
+ ClassDB::bind_method(D_METHOD("set_path", "path"), &Resource::_set_path);
+ ClassDB::bind_method(D_METHOD("take_over_path", "path"), &Resource::_take_over_path);
+ ClassDB::bind_method(D_METHOD("get_path"), &Resource::get_path);
+ ClassDB::bind_method(D_METHOD("set_name", "name"), &Resource::set_name);
+ ClassDB::bind_method(D_METHOD("get_name"), &Resource::get_name);
+ ClassDB::bind_method(D_METHOD("get_rid"), &Resource::get_rid);
+ ClassDB::bind_method(D_METHOD("set_local_to_scene", "enable"), &Resource::set_local_to_scene);
+ ClassDB::bind_method(D_METHOD("is_local_to_scene"), &Resource::is_local_to_scene);
+ ClassDB::bind_method(D_METHOD("get_local_scene:Node"), &Resource::get_local_scene);
+ ClassDB::bind_method(D_METHOD("setup_local_to_scene"), &Resource::setup_local_to_scene);
- BIND_VMETHOD( MethodInfo("_setup_local_to_scene") );
+ ClassDB::bind_method(D_METHOD("duplicate", "subresources"), &Resource::duplicate, DEFVAL(false));
+ ADD_SIGNAL(MethodInfo("changed"));
+ ADD_GROUP("Resource", "resource_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "resource_local_to_scene"), "set_local_to_scene", "is_local_to_scene");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "resource_path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_path", "get_path");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "resource_name"), "set_name", "get_name");
+ BIND_VMETHOD(MethodInfo("_setup_local_to_scene"));
}
Resource::Resource() {
#ifdef TOOLS_ENABLED
- last_modified_time=0;
- import_last_modified_time=0;
+ last_modified_time = 0;
+ import_last_modified_time = 0;
#endif
- subindex=0;
- local_to_scene=false;
- local_scene=NULL;
+ subindex = 0;
+ local_to_scene = false;
+ local_scene = NULL;
}
-
-
-
Resource::~Resource() {
- if (path_cache!="") {
+ if (path_cache != "") {
ResourceCache::lock->write_lock();
ResourceCache::resources.erase(path_cache);
ResourceCache::lock->write_unlock();
@@ -376,9 +348,9 @@ Resource::~Resource() {
}
}
-HashMap<String,Resource*> ResourceCache::resources;
+HashMap<String, Resource *> ResourceCache::resources;
-RWLock *ResourceCache::lock=NULL;
+RWLock *ResourceCache::lock = NULL;
void ResourceCache::setup() {
@@ -393,7 +365,6 @@ void ResourceCache::clear() {
memdelete(lock);
}
-
void ResourceCache::reload_externals() {
/*
@@ -404,16 +375,15 @@ void ResourceCache::reload_externals() {
*/
}
-bool ResourceCache::has(const String& p_path) {
+bool ResourceCache::has(const String &p_path) {
lock->read_lock();
bool b = resources.has(p_path);
lock->read_unlock();
-
return b;
}
-Resource *ResourceCache::get(const String& p_path) {
+Resource *ResourceCache::get(const String &p_path) {
lock->read_lock();
@@ -428,20 +398,16 @@ Resource *ResourceCache::get(const String& p_path) {
return *res;
}
-
void ResourceCache::get_cached_resources(List<Ref<Resource> > *p_resources) {
-
lock->read_lock();
- const String* K=NULL;
- while((K=resources.next(K))) {
+ const String *K = NULL;
+ while ((K = resources.next(K))) {
Resource *r = resources[*K];
- p_resources->push_back( Ref<Resource>( r ));
-
+ p_resources->push_back(Ref<Resource>(r));
}
lock->read_unlock();
-
}
int ResourceCache::get_cached_resource_count() {
@@ -453,42 +419,39 @@ int ResourceCache::get_cached_resource_count() {
return rc;
}
-void ResourceCache::dump(const char* p_file,bool p_short) {
+void ResourceCache::dump(const char *p_file, bool p_short) {
#ifdef DEBUG_ENABLED
lock->read_lock();
- Map<String,int> type_count;
-
+ Map<String, int> type_count;
- FileAccess *f=NULL;
+ FileAccess *f = NULL;
if (p_file) {
- f = FileAccess::open(p_file,FileAccess::WRITE);
+ f = FileAccess::open(p_file, FileAccess::WRITE);
ERR_FAIL_COND(!f);
-
}
- const String* K=NULL;
- while((K=resources.next(K))) {
+ const String *K = NULL;
+ while ((K = resources.next(K))) {
Resource *r = resources[*K];
if (!type_count.has(r->get_class())) {
- type_count[r->get_class()]=0;
+ type_count[r->get_class()] = 0;
}
-
type_count[r->get_class()]++;
if (!p_short) {
if (f)
- f->store_line(r->get_class()+": "+r->get_path());
+ f->store_line(r->get_class() + ": " + r->get_path());
}
}
- for(Map<String,int>::Element *E=type_count.front();E;E=E->next()) {
+ for (Map<String, int>::Element *E = type_count.front(); E; E = E->next()) {
if (f)
- f->store_line(E->key()+" count: "+itos(E->get()));
+ f->store_line(E->key() + " count: " + itos(E->get()));
}
if (f) {
f->close();
diff --git a/core/resource.h b/core/resource.h
index b29077a3b8..96a3a16fc5 100644
--- a/core/resource.h
+++ b/core/resource.h
@@ -29,34 +29,33 @@
#ifndef RESOURCE_H
#define RESOURCE_H
+#include "class_db.h"
#include "object.h"
-#include "safe_refcount.h"
#include "ref_ptr.h"
#include "reference.h"
-#include "class_db.h"
+#include "safe_refcount.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-#define RES_BASE_EXTENSION(m_ext)\
-public:\
-static void register_custom_data_to_otdb() { ClassDB::add_resource_base_extension(m_ext,get_class_static()); }\
-virtual String get_base_extension() const { return m_ext; }\
+#define RES_BASE_EXTENSION(m_ext) \
+public: \
+ static void register_custom_data_to_otdb() { ClassDB::add_resource_base_extension(m_ext, get_class_static()); } \
+ virtual String get_base_extension() const { return m_ext; } \
+ \
private:
-
-
class Resource : public Reference {
- GDCLASS( Resource, Reference );
+ GDCLASS(Resource, Reference);
OBJ_CATEGORY("Resources");
RES_BASE_EXTENSION("res");
Set<ObjectID> owners;
-friend class ResBase;
-friend class ResourceCache;
+ friend class ResBase;
+ friend class ResourceCache;
String name;
String path_cache;
@@ -71,11 +70,10 @@ friend class ResourceCache;
#endif
bool local_to_scene;
-friend class SceneState;
- Node* local_scene;
+ friend class SceneState;
+ Node *local_scene;
protected:
-
void emit_changed();
void notify_change_to_owners();
@@ -83,11 +81,11 @@ protected:
virtual void _resource_path_changed();
static void _bind_methods();
- void _set_path(const String& p_path);
- void _take_over_path(const String& p_path);
-public:
+ void _set_path(const String &p_path);
+ void _take_over_path(const String &p_path);
- static Node* (*_get_local_scene_func)(); //used by editor
+public:
+ static Node *(*_get_local_scene_func)(); //used by editor
virtual bool editor_can_reload_from_file();
virtual void reload_from_file();
@@ -95,35 +93,35 @@ public:
void register_owner(Object *p_owner);
void unregister_owner(Object *p_owner);
- void set_name(const String& p_name);
+ void set_name(const String &p_name);
String get_name() const;
- virtual void set_path(const String& p_path,bool p_take_over=false);
+ virtual void set_path(const String &p_path, bool p_take_over = false);
String get_path() const;
void set_subindex(int p_sub_index);
int get_subindex() const;
- Ref<Resource> duplicate(bool p_subresources=false);
- Ref<Resource> duplicate_for_local_scene(Node *p_scene,Map<Ref<Resource>,Ref<Resource> >& remap_cache);
+ Ref<Resource> duplicate(bool p_subresources = false);
+ Ref<Resource> duplicate_for_local_scene(Node *p_scene, Map<Ref<Resource>, Ref<Resource> > &remap_cache);
void set_local_to_scene(bool p_enable);
bool is_local_to_scene() const;
virtual void setup_local_to_scene();
- Node* get_local_scene() const;
+ Node *get_local_scene() const;
#ifdef TOOLS_ENABLED
uint32_t hash_edited_version() const;
- virtual void set_last_modified_time(uint64_t p_time) { last_modified_time=p_time; }
+ virtual void set_last_modified_time(uint64_t p_time) { last_modified_time = p_time; }
uint64_t get_last_modified_time() const { return last_modified_time; }
- virtual void set_import_last_modified_time(uint64_t p_time) { import_last_modified_time=p_time; }
+ virtual void set_import_last_modified_time(uint64_t p_time) { import_last_modified_time = p_time; }
uint64_t get_import_last_modified_time() const { return import_last_modified_time; }
- void set_import_path(const String& p_path) { import_path=p_path; }
+ void set_import_path(const String &p_path) { import_path = p_path; }
String get_import_path() const { return import_path; }
#endif
@@ -132,29 +130,26 @@ public:
Resource();
~Resource();
-
};
-
typedef Ref<Resource> RES;
class ResourceCache {
-friend class Resource;
+ friend class Resource;
static RWLock *lock;
- static HashMap<String,Resource*> resources;
-friend void unregister_core_types();
+ static HashMap<String, Resource *> resources;
+ friend void unregister_core_types();
static void clear();
-friend void register_core_types();
+ friend void register_core_types();
static void setup();
-public:
+public:
static void reload_externals();
- static bool has(const String& p_path);
- static Resource* get(const String& p_path);
- static void dump(const char* p_file=NULL,bool p_short=false);
+ static bool has(const String &p_path);
+ static Resource *get(const String &p_path);
+ static void dump(const char *p_file = NULL, bool p_short = false);
static void get_cached_resources(List<Ref<Resource> > *p_resources);
static int get_cached_resource_count();
-
};
#endif
diff --git a/core/rid.cpp b/core/rid.cpp
index c7e487f91a..1c673f8ba2 100644
--- a/core/rid.cpp
+++ b/core/rid.cpp
@@ -28,13 +28,9 @@
/*************************************************************************/
#include "rid.h"
-
-
RID_Data::~RID_Data() {
-
}
-
SafeRefCount RID_OwnerBase::refcount;
void RID_OwnerBase::init_rid() {
diff --git a/core/rid.h b/core/rid.h
index 8dc535c9c1..2711ac6598 100644
--- a/core/rid.h
+++ b/core/rid.h
@@ -29,169 +29,151 @@
#ifndef RID_H
#define RID_H
-
-#include "safe_refcount.h"
-#include "typedefs.h"
+#include "list.h"
#include "os/memory.h"
+#include "safe_refcount.h"
#include "set.h"
-#include "list.h"
+#include "typedefs.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class RID_OwnerBase;
class RID_Data {
-friend class RID_OwnerBase;
+ friend class RID_OwnerBase;
#ifndef DEBUG_ENABLED
RID_OwnerBase *_owner;
#endif
uint32_t _id;
+
public:
_FORCE_INLINE_ uint32_t get_id() const { return _id; }
virtual ~RID_Data();
};
-
class RID {
-friend class RID_OwnerBase;
+ friend class RID_OwnerBase;
mutable RID_Data *_data;
public:
-
_FORCE_INLINE_ RID_Data *get_data() const { return _data; }
- _FORCE_INLINE_ bool operator==(const RID& p_rid) const {
+ _FORCE_INLINE_ bool operator==(const RID &p_rid) const {
- return _data==p_rid._data;
+ return _data == p_rid._data;
}
- _FORCE_INLINE_ bool operator<(const RID& p_rid) const {
+ _FORCE_INLINE_ bool operator<(const RID &p_rid) const {
return _data < p_rid._data;
}
- _FORCE_INLINE_ bool operator<=(const RID& p_rid) const {
+ _FORCE_INLINE_ bool operator<=(const RID &p_rid) const {
return _data <= p_rid._data;
}
- _FORCE_INLINE_ bool operator>(const RID& p_rid) const {
+ _FORCE_INLINE_ bool operator>(const RID &p_rid) const {
return _data > p_rid._data;
}
- _FORCE_INLINE_ bool operator!=(const RID& p_rid) const {
+ _FORCE_INLINE_ bool operator!=(const RID &p_rid) const {
- return _data!=p_rid._data;
+ return _data != p_rid._data;
}
- _FORCE_INLINE_ bool is_valid() const { return _data!=NULL; }
+ _FORCE_INLINE_ bool is_valid() const { return _data != NULL; }
- _FORCE_INLINE_ uint32_t get_id() const { return _data?_data->get_id():0; }
+ _FORCE_INLINE_ uint32_t get_id() const { return _data ? _data->get_id() : 0; }
_FORCE_INLINE_ RID() {
- _data=NULL;
+ _data = NULL;
}
-
};
-
class RID_OwnerBase {
protected:
-
static SafeRefCount refcount;
- _FORCE_INLINE_ void _set_data(RID& p_rid, RID_Data* p_data) {
- p_rid._data=p_data;
+ _FORCE_INLINE_ void _set_data(RID &p_rid, RID_Data *p_data) {
+ p_rid._data = p_data;
refcount.ref();
- p_data->_id=refcount.get();
+ p_data->_id = refcount.get();
#ifndef DEBUG_ENABLED
- p_data->_owner=this;
+ p_data->_owner = this;
#endif
}
#ifndef DEBUG_ENABLED
- _FORCE_INLINE_ bool _is_owner(const RID& p_rid) const {
-
- return this==p_rid._data->_owner;
+ _FORCE_INLINE_ bool _is_owner(const RID &p_rid) const {
+ return this == p_rid._data->_owner;
}
- _FORCE_INLINE_ void _remove_owner(RID& p_rid) {
-
- p_rid._data->_owner=NULL;
+ _FORCE_INLINE_ void _remove_owner(RID &p_rid) {
+ p_rid._data->_owner = NULL;
}
#
#endif
-
public:
-
-
- virtual void get_owned_list(List<RID> *p_owned)=0;
+ virtual void get_owned_list(List<RID> *p_owned) = 0;
static void init_rid();
virtual ~RID_OwnerBase() {}
};
-template<class T>
+template <class T>
class RID_Owner : public RID_OwnerBase {
public:
#ifdef DEBUG_ENABLED
- mutable Set<RID_Data*> id_map;
+ mutable Set<RID_Data *> id_map;
#endif
public:
-
- _FORCE_INLINE_ RID make_rid(T * p_data) {
-
+ _FORCE_INLINE_ RID make_rid(T *p_data) {
RID rid;
- _set_data(rid,p_data);
+ _set_data(rid, p_data);
#ifdef DEBUG_ENABLED
- id_map.insert(p_data) ;
+ id_map.insert(p_data);
#endif
return rid;
}
- _FORCE_INLINE_ T * get(const RID& p_rid) {
+ _FORCE_INLINE_ T *get(const RID &p_rid) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND_V(!p_rid.is_valid(),NULL);
- ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()),NULL);
+ ERR_FAIL_COND_V(!p_rid.is_valid(), NULL);
+ ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()), NULL);
#endif
- return static_cast<T*>(p_rid.get_data());
-
+ return static_cast<T *>(p_rid.get_data());
}
- _FORCE_INLINE_ T * getornull(const RID& p_rid) {
+ _FORCE_INLINE_ T *getornull(const RID &p_rid) {
#ifdef DEBUG_ENABLED
if (p_rid.get_data()) {
- ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()),NULL);
+ ERR_FAIL_COND_V(!id_map.has(p_rid.get_data()), NULL);
}
#endif
- return static_cast<T*>(p_rid.get_data());
-
+ return static_cast<T *>(p_rid.get_data());
}
+ _FORCE_INLINE_ T *getptr(const RID &p_rid) {
- _FORCE_INLINE_ T * getptr(const RID& p_rid) {
-
- return static_cast<T*>(p_rid.get_data());
-
+ return static_cast<T *>(p_rid.get_data());
}
+ _FORCE_INLINE_ bool owns(const RID &p_rid) const {
- _FORCE_INLINE_ bool owns(const RID& p_rid) const {
-
- if (p_rid.get_data()==NULL)
+ if (p_rid.get_data() == NULL)
return false;
#ifdef DEBUG_ENABLED
return id_map.has(p_rid.get_data());
@@ -211,20 +193,15 @@ public:
void get_owned_list(List<RID> *p_owned) {
-
-
#ifdef DEBUG_ENABLED
- for (typename Set<RID_Data*>::Element *E=id_map.front();E;E=E->next()) {
+ for (typename Set<RID_Data *>::Element *E = id_map.front(); E; E = E->next()) {
RID r;
- _set_data(r,static_cast<T*>(E->get()));
+ _set_data(r, static_cast<T *>(E->get()));
p_owned->push_back(r);
}
#endif
-
}
-
};
-
#endif
diff --git a/core/ring_buffer.h b/core/ring_buffer.h
index a4da0086e0..3c13cb8d1e 100644
--- a/core/ring_buffer.h
+++ b/core/ring_buffer.h
@@ -39,31 +39,30 @@ class RingBuffer {
int write_pos;
int size_mask;
- inline int inc(int& p_var, int p_size) {
+ inline int inc(int &p_var, int p_size) {
int ret = p_var;
p_var += p_size;
- p_var = p_var&size_mask;
+ p_var = p_var & size_mask;
return ret;
};
public:
-
T read() {
ERR_FAIL_COND_V(space_left() < 1, T());
return data[inc(read_pos, 1)];
};
- int read(T* p_buf, int p_size, bool p_advance=true) {
+ int read(T *p_buf, int p_size, bool p_advance = true) {
int left = data_left();
p_size = MIN(left, p_size);
int pos = read_pos;
int to_read = p_size;
int dst = 0;
- while(to_read) {
+ while (to_read) {
int end = pos + to_read;
end = MIN(end, size());
int total = end - pos;
- for (int i=0; i<total; i++) {
+ for (int i = 0; i < total; i++) {
p_buf[dst++] = data[pos + i];
};
to_read -= total;
@@ -75,24 +74,24 @@ public:
return p_size;
};
- int copy(T* p_buf, int p_offset, int p_size) {
+ int copy(T *p_buf, int p_offset, int p_size) {
int left = data_left();
- if ((p_offset+p_size)>left) {
- p_size-=left-p_offset;
- if (p_size<=0)
+ if ((p_offset + p_size) > left) {
+ p_size -= left - p_offset;
+ if (p_size <= 0)
return 0;
}
p_size = MIN(left, p_size);
int pos = read_pos;
- inc(pos,p_offset);
+ inc(pos, p_offset);
int to_read = p_size;
int dst = 0;
- while(to_read) {
+ while (to_read) {
int end = pos + to_read;
end = MIN(end, size());
int total = end - pos;
- for (int i=0; i<total; i++) {
+ for (int i = 0; i < total; i++) {
p_buf[dst++] = data[pos + i];
};
to_read -= total;
@@ -107,13 +106,13 @@ public:
return p_n;
};
- Error write(const T& p_v) {
- ERR_FAIL_COND_V( space_left() < 1, FAILED);
+ Error write(const T &p_v) {
+ ERR_FAIL_COND_V(space_left() < 1, FAILED);
data[inc(write_pos, 1)] = p_v;
return OK;
};
- int write(const T* p_buf, int p_size) {
+ int write(const T *p_buf, int p_size) {
int left = space_left();
p_size = MIN(left, p_size);
@@ -127,8 +126,8 @@ public:
end = MIN(end, size());
int total = end - pos;
- for (int i=0; i<total; i++) {
- data[pos+i] = p_buf[src++];
+ for (int i = 0; i < total; i++) {
+ data[pos + i] = p_buf[src++];
};
to_write -= total;
pos = 0;
@@ -144,9 +143,9 @@ public:
return size() + left - 1;
};
if (left == 0) {
- return size()-1;
+ return size() - 1;
};
- return left -1;
+ return left - 1;
};
inline int data_left() {
return size() - space_left() - 1;
@@ -159,17 +158,16 @@ public:
inline void clear() {
read_pos = 0;
write_pos = 0;
-
}
void resize(int p_power) {
int old_size = size();
- int new_size = 1<<p_power;
+ int new_size = 1 << p_power;
int mask = new_size - 1;
- data.resize(1<<p_power);
+ data.resize(1 << p_power);
if (old_size < new_size && read_pos > write_pos) {
- for (int i=0; i<write_pos; i++) {
- data[(old_size + i)&mask] = data[i];
+ for (int i = 0; i < write_pos; i++) {
+ data[(old_size + i) & mask] = data[i];
};
write_pos = (old_size + write_pos) & mask;
} else {
@@ -180,12 +178,12 @@ public:
size_mask = mask;
};
- RingBuffer<T>(int p_power=0) {
+ RingBuffer<T>(int p_power = 0) {
read_pos = 0;
write_pos = 0;
resize(p_power);
};
- ~RingBuffer<T>() {};
+ ~RingBuffer<T>(){};
};
#endif
diff --git a/core/safe_refcount.cpp b/core/safe_refcount.cpp
index 50617f2062..cbd79a322f 100644
--- a/core/safe_refcount.cpp
+++ b/core/safe_refcount.cpp
@@ -28,15 +28,13 @@
/*************************************************************************/
#include "safe_refcount.h"
-
// Atomic functions, these are used for multithread safe reference counters!
#ifdef NO_THREADS
+uint32_t atomic_conditional_increment(register uint32_t *pw) {
-uint32_t atomic_conditional_increment( register uint32_t * pw ) {
-
- if (*pw==0)
+ if (*pw == 0)
return 0;
(*pw)++;
@@ -44,20 +42,18 @@ uint32_t atomic_conditional_increment( register uint32_t * pw ) {
return *pw;
}
-uint32_t atomic_increment( register uint32_t * pw ) {
+uint32_t atomic_increment(register uint32_t *pw) {
(*pw)++;
return *pw;
-
}
-uint32_t atomic_decrement( register uint32_t * pw ) {
+uint32_t atomic_decrement(register uint32_t *pw) {
(*pw)--;
return *pw;
-
}
#else
@@ -66,54 +62,52 @@ uint32_t atomic_decrement( register uint32_t * pw ) {
// don't pollute my namespace!
#include <windows.h>
-uint32_t atomic_conditional_increment( register uint32_t * pw ) {
+uint32_t atomic_conditional_increment(register uint32_t *pw) {
/* try to increment until it actually works */
// taken from boost
while (true) {
- uint32_t tmp = static_cast< uint32_t const volatile& >( *pw );
- if( tmp == 0 )
- return 0; // if zero, can't add to it anymore
- if( InterlockedCompareExchange( (LONG volatile*)pw, tmp + 1, tmp ) == tmp )
- return tmp+1;
+ uint32_t tmp = static_cast<uint32_t const volatile &>(*pw);
+ if (tmp == 0)
+ return 0; // if zero, can't add to it anymore
+ if (InterlockedCompareExchange((LONG volatile *)pw, tmp + 1, tmp) == tmp)
+ return tmp + 1;
}
}
-uint32_t atomic_decrement( register uint32_t * pw ) {
- return InterlockedDecrement( (LONG volatile*)pw );
+uint32_t atomic_decrement(register uint32_t *pw) {
+ return InterlockedDecrement((LONG volatile *)pw);
}
-uint32_t atomic_increment( register uint32_t * pw ) {
- return InterlockedIncrement( (LONG volatile*)pw );
+uint32_t atomic_increment(register uint32_t *pw) {
+ return InterlockedIncrement((LONG volatile *)pw);
}
#elif defined(__GNUC__)
-uint32_t atomic_conditional_increment( register uint32_t * pw ) {
+uint32_t atomic_conditional_increment(register uint32_t *pw) {
while (true) {
- uint32_t tmp = static_cast< uint32_t const volatile& >( *pw );
- if( tmp == 0 )
- return 0; // if zero, can't add to it anymore
- if( __sync_val_compare_and_swap( pw, tmp, tmp + 1 ) == tmp )
- return tmp+1;
+ uint32_t tmp = static_cast<uint32_t const volatile &>(*pw);
+ if (tmp == 0)
+ return 0; // if zero, can't add to it anymore
+ if (__sync_val_compare_and_swap(pw, tmp, tmp + 1) == tmp)
+ return tmp + 1;
}
}
-uint32_t atomic_decrement( register uint32_t * pw ) {
-
- return __sync_sub_and_fetch(pw,1);
+uint32_t atomic_decrement(register uint32_t *pw) {
+ return __sync_sub_and_fetch(pw, 1);
}
-uint32_t atomic_increment( register uint32_t * pw ) {
-
- return __sync_add_and_fetch(pw,1);
+uint32_t atomic_increment(register uint32_t *pw) {
+ return __sync_add_and_fetch(pw, 1);
}
#else
- //no threads supported?
+//no threads supported?
#error Must provide atomic functions for this platform or compiler!
#endif
diff --git a/core/safe_refcount.h b/core/safe_refcount.h
index 6e349d89d8..eeadeea8cf 100644
--- a/core/safe_refcount.h
+++ b/core/safe_refcount.h
@@ -35,34 +35,30 @@
#include "platform_config.h"
#include "typedefs.h"
-
-uint32_t atomic_conditional_increment( register uint32_t * counter );
-uint32_t atomic_decrement( register uint32_t * pw );
-uint32_t atomic_increment( register uint32_t * pw );
-
-
+uint32_t atomic_conditional_increment(register uint32_t *counter);
+uint32_t atomic_decrement(register uint32_t *pw);
+uint32_t atomic_increment(register uint32_t *pw);
struct SafeRefCount {
- uint32_t count;
+ uint32_t count;
public:
-
// destroy() is called when weak_count_ drops to zero.
- bool ref() { //true on success
+ bool ref() { //true on success
- return atomic_conditional_increment( &count ) != 0;
+ return atomic_conditional_increment(&count) != 0;
}
- uint32_t refval() { //true on success
+ uint32_t refval() { //true on success
- return atomic_conditional_increment( &count );
+ return atomic_conditional_increment(&count);
}
bool unref() { // true if must be disposed of
- if( atomic_decrement ( &count ) == 0 ) {
+ if (atomic_decrement(&count) == 0) {
return true;
}
@@ -74,13 +70,10 @@ public:
return count;
}
- void init(uint32_t p_value=1) {
+ void init(uint32_t p_value = 1) {
- count=p_value;
+ count = p_value;
}
-
};
-
-
#endif
diff --git a/core/script_debugger_local.cpp b/core/script_debugger_local.cpp
index 22aceac4c5..b5ed9773f0 100644
--- a/core/script_debugger_local.cpp
+++ b/core/script_debugger_local.cpp
@@ -30,91 +30,91 @@
#include "os/os.h"
-void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) {
+void ScriptDebuggerLocal::debug(ScriptLanguage *p_script, bool p_can_continue) {
- print_line("Debugger Break, Reason: '"+p_script->debug_get_error()+"'");
- print_line("*Frame "+itos(0)+" - "+p_script->debug_get_stack_level_source(0)+":"+itos(p_script->debug_get_stack_level_line(0))+" in function '"+p_script->debug_get_stack_level_function(0)+"'");
+ print_line("Debugger Break, Reason: '" + p_script->debug_get_error() + "'");
+ print_line("*Frame " + itos(0) + " - " + p_script->debug_get_stack_level_source(0) + ":" + itos(p_script->debug_get_stack_level_line(0)) + " in function '" + p_script->debug_get_stack_level_function(0) + "'");
print_line("Enter \"help\" for assistance.");
- int current_frame=0;
- int total_frames=p_script->debug_get_stack_level_count();
- while(true) {
+ int current_frame = 0;
+ int total_frames = p_script->debug_get_stack_level_count();
+ while (true) {
OS::get_singleton()->print("debug> ");
String line = OS::get_singleton()->get_stdin_string().strip_edges();
- if (line=="") {
- print_line("Debugger Break, Reason: '"+p_script->debug_get_error()+"'");
- print_line("*Frame "+itos(current_frame)+" - "+p_script->debug_get_stack_level_source(current_frame)+":"+itos(p_script->debug_get_stack_level_line(current_frame))+" in function '"+p_script->debug_get_stack_level_function(current_frame)+"'");
+ if (line == "") {
+ print_line("Debugger Break, Reason: '" + p_script->debug_get_error() + "'");
+ print_line("*Frame " + itos(current_frame) + " - " + p_script->debug_get_stack_level_source(current_frame) + ":" + itos(p_script->debug_get_stack_level_line(current_frame)) + " in function '" + p_script->debug_get_stack_level_function(current_frame) + "'");
print_line("Enter \"help\" for assistance.");
- } else if (line=="c" || line=="continue")
+ } else if (line == "c" || line == "continue")
break;
- else if (line=="bt" || line=="breakpoint") {
+ else if (line == "bt" || line == "breakpoint") {
- for(int i=0;i<total_frames;i++) {
+ for (int i = 0; i < total_frames; i++) {
- String cfi=(current_frame==i)?"*":" "; //current frame indicator
- print_line(cfi+"Frame "+itos(i)+" - "+p_script->debug_get_stack_level_source(i)+":"+itos(p_script->debug_get_stack_level_line(i))+" in function '"+p_script->debug_get_stack_level_function(i)+"'");
+ String cfi = (current_frame == i) ? "*" : " "; //current frame indicator
+ print_line(cfi + "Frame " + itos(i) + " - " + p_script->debug_get_stack_level_source(i) + ":" + itos(p_script->debug_get_stack_level_line(i)) + " in function '" + p_script->debug_get_stack_level_function(i) + "'");
}
} else if (line.begins_with("fr") || line.begins_with("frame")) {
- if (line.get_slice_count(" ")==1) {
- print_line("*Frame "+itos(current_frame)+" - "+p_script->debug_get_stack_level_source(current_frame)+":"+itos(p_script->debug_get_stack_level_line(current_frame))+" in function '"+p_script->debug_get_stack_level_function(current_frame)+"'");
+ if (line.get_slice_count(" ") == 1) {
+ print_line("*Frame " + itos(current_frame) + " - " + p_script->debug_get_stack_level_source(current_frame) + ":" + itos(p_script->debug_get_stack_level_line(current_frame)) + " in function '" + p_script->debug_get_stack_level_function(current_frame) + "'");
} else {
- int frame = line.get_slicec(' ',1).to_int();
- if (frame<0 || frame >=total_frames) {
+ int frame = line.get_slicec(' ', 1).to_int();
+ if (frame < 0 || frame >= total_frames) {
print_line("Error: Invalid frame.");
} else {
- current_frame=frame;
- print_line("*Frame "+itos(frame)+" - "+p_script->debug_get_stack_level_source(frame)+":"+itos(p_script->debug_get_stack_level_line(frame))+" in function '"+p_script->debug_get_stack_level_function(frame)+"'");
+ current_frame = frame;
+ print_line("*Frame " + itos(frame) + " - " + p_script->debug_get_stack_level_source(frame) + ":" + itos(p_script->debug_get_stack_level_line(frame)) + " in function '" + p_script->debug_get_stack_level_function(frame) + "'");
}
}
- } else if (line=="lv" || line=="locals") {
+ } else if (line == "lv" || line == "locals") {
List<String> locals;
List<Variant> values;
- p_script->debug_get_stack_level_locals(current_frame,&locals, &values);
- List<Variant>::Element* V = values.front();
- for (List<String>::Element *E=locals.front();E;E=E->next()) {
+ p_script->debug_get_stack_level_locals(current_frame, &locals, &values);
+ List<Variant>::Element *V = values.front();
+ for (List<String>::Element *E = locals.front(); E; E = E->next()) {
print_line(E->get() + ": " + String(V->get()));
V = V->next();
}
- } else if (line=="gv" || line=="globals") {
+ } else if (line == "gv" || line == "globals") {
List<String> locals;
List<Variant> values;
p_script->debug_get_globals(&locals, &values);
- List<Variant>::Element* V = values.front();
- for (List<String>::Element *E=locals.front();E;E=E->next()) {
+ List<Variant>::Element *V = values.front();
+ for (List<String>::Element *E = locals.front(); E; E = E->next()) {
print_line(E->get() + ": " + String(V->get()));
V = V->next();
}
- } else if (line=="mv" || line=="members") {
+ } else if (line == "mv" || line == "members") {
List<String> locals;
List<Variant> values;
- p_script->debug_get_stack_level_members(current_frame,&locals, &values);
- List<Variant>::Element* V = values.front();
- for (List<String>::Element *E=locals.front();E;E=E->next()) {
+ p_script->debug_get_stack_level_members(current_frame, &locals, &values);
+ List<Variant>::Element *V = values.front();
+ for (List<String>::Element *E = locals.front(); E; E = E->next()) {
print_line(E->get() + ": " + String(V->get()));
V = V->next();
}
} else if (line.begins_with("p") || line.begins_with("print")) {
- if (line.get_slice_count(" ")<=1) {
+ if (line.get_slice_count(" ") <= 1) {
print_line("Usage: print <expre>");
} else {
- String expr = line.get_slicec(' ',2);
- String res = p_script->debug_parse_stack_level_expression(current_frame,expr);
+ String expr = line.get_slicec(' ', 2);
+ String res = p_script->debug_parse_stack_level_expression(current_frame, expr);
print_line(res);
}
- } else if (line=="s" || line=="step") {
+ } else if (line == "s" || line == "step") {
set_depth(-1);
set_lines_left(1);
@@ -126,41 +126,39 @@ void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) {
break;
} else if (line.begins_with("br") || line.begins_with("break")) {
- if (line.get_slice_count(" ")<=1) {
+ if (line.get_slice_count(" ") <= 1) {
//show breakpoints
} else {
-
- String bppos=line.get_slicec(' ',1);
- String source=bppos.get_slicec(':',0).strip_edges();
- int line=bppos.get_slicec(':',1).strip_edges().to_int();
+ String bppos = line.get_slicec(' ', 1);
+ String source = bppos.get_slicec(':', 0).strip_edges();
+ int line = bppos.get_slicec(':', 1).strip_edges().to_int();
source = breakpoint_find_source(source);
- insert_breakpoint(line,source);
+ insert_breakpoint(line, source);
- print_line("BreakPoint at "+source+":"+itos(line));
+ print_line("BreakPoint at " + source + ":" + itos(line));
}
} else if (line.begins_with("delete")) {
- if (line.get_slice_count(" ")<=1) {
+ if (line.get_slice_count(" ") <= 1) {
clear_breakpoints();
} else {
- String bppos=line.get_slicec(' ',1);
- String source=bppos.get_slicec(':',0).strip_edges();
- int line=bppos.get_slicec(':',1).strip_edges().to_int();
+ String bppos = line.get_slicec(' ', 1);
+ String source = bppos.get_slicec(':', 0).strip_edges();
+ int line = bppos.get_slicec(':', 1).strip_edges().to_int();
source = breakpoint_find_source(source);
- remove_breakpoint(line,source);
-
- print_line("Removed BreakPoint at "+source+":"+itos(line));
+ remove_breakpoint(line, source);
+ print_line("Removed BreakPoint at " + source + ":" + itos(line));
}
- } else if (line=="h" || line=="help") {
+ } else if (line == "h" || line == "help") {
print_line("Built-In Debugger command list:\n");
print_line("\tc,continue :\t\t Continue execution.");
@@ -182,20 +180,17 @@ void ScriptDebuggerLocal::debug(ScriptLanguage *p_script,bool p_can_continue) {
struct _ScriptDebuggerLocalProfileInfoSort {
- bool operator()(const ScriptLanguage::ProfilingInfo &A,const ScriptLanguage::ProfilingInfo &B) const {
+ bool operator()(const ScriptLanguage::ProfilingInfo &A, const ScriptLanguage::ProfilingInfo &B) const {
return A.total_time > B.total_time;
}
};
-void ScriptDebuggerLocal::profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time) {
-
-
- frame_time=p_frame_time;
- idle_time=p_idle_time;
- fixed_time=p_fixed_time;
- fixed_frame_time=p_fixed_frame_time;
-
+void ScriptDebuggerLocal::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) {
+ frame_time = p_frame_time;
+ idle_time = p_idle_time;
+ fixed_time = p_fixed_time;
+ fixed_frame_time = p_fixed_frame_time;
}
void ScriptDebuggerLocal::idle_poll() {
@@ -205,107 +200,100 @@ void ScriptDebuggerLocal::idle_poll() {
uint64_t diff = OS::get_singleton()->get_ticks_usec() - idle_accum;
- if (diff<1000000) //show every one second
+ if (diff < 1000000) //show every one second
return;
idle_accum = OS::get_singleton()->get_ticks_usec();
- int ofs=0;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- ofs+=ScriptServer::get_language(i)->profiling_get_frame_data(&pinfo[ofs],pinfo.size()-ofs);
+ int ofs = 0;
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&pinfo[ofs], pinfo.size() - ofs);
}
- SortArray<ScriptLanguage::ProfilingInfo,_ScriptDebuggerLocalProfileInfoSort> sort;
- sort.sort(pinfo.ptr(),ofs);
+ SortArray<ScriptLanguage::ProfilingInfo, _ScriptDebuggerLocalProfileInfoSort> sort;
+ sort.sort(pinfo.ptr(), ofs);
//falta el frame time
- uint64_t script_time_us=0;
+ uint64_t script_time_us = 0;
- for(int i=0;i<ofs;i++) {
+ for (int i = 0; i < ofs; i++) {
- script_time_us+=pinfo[i].self_time;
+ script_time_us += pinfo[i].self_time;
}
+ float script_time = USEC_TO_SEC(script_time_us);
- float script_time=USEC_TO_SEC(script_time_us);
-
- float total_time=frame_time;
+ float total_time = frame_time;
//print script total
- print_line("FRAME: total: "+rtos(frame_time)+" script: "+rtos(script_time)+"/"+itos(script_time*100/total_time)+" %");
+ print_line("FRAME: total: " + rtos(frame_time) + " script: " + rtos(script_time) + "/" + itos(script_time * 100 / total_time) + " %");
- for(int i=0;i<ofs;i++) {
+ for (int i = 0; i < ofs; i++) {
- print_line(itos(i)+":"+pinfo[i].signature);
- float tt=USEC_TO_SEC(pinfo[i].total_time);
- float st=USEC_TO_SEC(pinfo[i].self_time);
- print_line("\ttotal: "+rtos(tt)+"/"+itos(tt*100/total_time)+" % \tself: "+rtos(st)+"/"+itos(st*100/total_time)+" % tcalls: "+itos(pinfo[i].call_count));
+ print_line(itos(i) + ":" + pinfo[i].signature);
+ float tt = USEC_TO_SEC(pinfo[i].total_time);
+ float st = USEC_TO_SEC(pinfo[i].self_time);
+ print_line("\ttotal: " + rtos(tt) + "/" + itos(tt * 100 / total_time) + " % \tself: " + rtos(st) + "/" + itos(st * 100 / total_time) + " % tcalls: " + itos(pinfo[i].call_count));
}
-
-
-
}
void ScriptDebuggerLocal::profiling_start() {
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->profiling_start();
}
-
print_line("BEGIN PROFILING");
- profiling=true;
+ profiling = true;
pinfo.resize(32768);
- frame_time=0;
- fixed_time=0;
- idle_time=0;
- fixed_frame_time=0;
-
+ frame_time = 0;
+ fixed_time = 0;
+ idle_time = 0;
+ fixed_frame_time = 0;
}
-
void ScriptDebuggerLocal::profiling_end() {
- int ofs=0;
+ int ofs = 0;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- ofs+=ScriptServer::get_language(i)->profiling_get_accumulated_data(&pinfo[ofs],pinfo.size()-ofs);
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&pinfo[ofs], pinfo.size() - ofs);
}
- SortArray<ScriptLanguage::ProfilingInfo,_ScriptDebuggerLocalProfileInfoSort> sort;
- sort.sort(pinfo.ptr(),ofs);
+ SortArray<ScriptLanguage::ProfilingInfo, _ScriptDebuggerLocalProfileInfoSort> sort;
+ sort.sort(pinfo.ptr(), ofs);
- uint64_t total_us=0;
- for(int i=0;i<ofs;i++) {
- total_us+=pinfo[i].self_time;
+ uint64_t total_us = 0;
+ for (int i = 0; i < ofs; i++) {
+ total_us += pinfo[i].self_time;
}
- float total_time=total_us/1000000.0;
+ float total_time = total_us / 1000000.0;
- for(int i=0;i<ofs;i++) {
+ for (int i = 0; i < ofs; i++) {
- print_line(itos(i)+":"+pinfo[i].signature);
- float tt=USEC_TO_SEC(pinfo[i].total_time);
- float st=USEC_TO_SEC(pinfo[i].self_time);
- print_line("\ttotal_ms: "+rtos(tt)+"\tself_ms: "+rtos(st)+"total%: "+itos(tt*100/total_time)+"\tself%: "+itos(st*100/total_time)+"\tcalls: "+itos(pinfo[i].call_count));
+ print_line(itos(i) + ":" + pinfo[i].signature);
+ float tt = USEC_TO_SEC(pinfo[i].total_time);
+ float st = USEC_TO_SEC(pinfo[i].self_time);
+ print_line("\ttotal_ms: " + rtos(tt) + "\tself_ms: " + rtos(st) + "total%: " + itos(tt * 100 / total_time) + "\tself%: " + itos(st * 100 / total_time) + "\tcalls: " + itos(pinfo[i].call_count));
}
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->profiling_stop();
}
- profiling=false;
+ profiling = false;
}
-void ScriptDebuggerLocal::send_message(const String& p_message, const Array &p_args) {
+void ScriptDebuggerLocal::send_message(const String &p_message, const Array &p_args) {
- print_line("MESSAGE: '"+p_message+"' - "+String(Variant(p_args)));
+ print_line("MESSAGE: '" + p_message + "' - " + String(Variant(p_args)));
}
ScriptDebuggerLocal::ScriptDebuggerLocal() {
- profiling=false;
- idle_accum=OS::get_singleton()->get_ticks_usec();
+ profiling = false;
+ idle_accum = OS::get_singleton()->get_ticks_usec();
}
diff --git a/core/script_debugger_local.h b/core/script_debugger_local.h
index 6e2057ef45..b3b323c7a6 100644
--- a/core/script_debugger_local.h
+++ b/core/script_debugger_local.h
@@ -34,26 +34,23 @@
class ScriptDebuggerLocal : public ScriptDebugger {
bool profiling;
- float frame_time,idle_time,fixed_time,fixed_frame_time;
+ float frame_time, idle_time, fixed_time, fixed_frame_time;
uint64_t idle_accum;
Vector<ScriptLanguage::ProfilingInfo> pinfo;
-
public:
-
- void debug(ScriptLanguage *p_script,bool p_can_continue);
- virtual void send_message(const String& p_message, const Array& p_args);
+ void debug(ScriptLanguage *p_script, bool p_can_continue);
+ virtual void send_message(const String &p_message, const Array &p_args);
virtual bool is_profiling() const { return profiling; }
- virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data) {}
+ virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data) {}
virtual void idle_poll();
virtual void profiling_start();
virtual void profiling_end();
- virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time);
-
+ virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time);
ScriptDebuggerLocal();
};
diff --git a/core/script_debugger_remote.cpp b/core/script_debugger_remote.cpp
index b14eb51b6c..bb7ed22c28 100644
--- a/core/script_debugger_remote.cpp
+++ b/core/script_debugger_remote.cpp
@@ -28,10 +28,10 @@
/*************************************************************************/
#include "script_debugger_remote.h"
-#include "os/os.h"
-#include "io/ip.h"
#include "global_config.h"
+#include "io/ip.h"
#include "os/input.h"
+#include "os/os.h"
void ScriptDebuggerRemote::_send_video_memory() {
@@ -42,70 +42,66 @@ void ScriptDebuggerRemote::_send_video_memory() {
usage.sort();
packet_peer_stream->put_var("message:video_mem");
- packet_peer_stream->put_var(usage.size()*4);
-
+ packet_peer_stream->put_var(usage.size() * 4);
- for(List<ResourceUsage>::Element *E=usage.front();E;E=E->next()) {
+ for (List<ResourceUsage>::Element *E = usage.front(); E; E = E->next()) {
packet_peer_stream->put_var(E->get().path);
packet_peer_stream->put_var(E->get().type);
packet_peer_stream->put_var(E->get().format);
packet_peer_stream->put_var(E->get().vram);
}
-
}
-Error ScriptDebuggerRemote::connect_to_host(const String& p_host,uint16_t p_port) {
-
-
- IP_Address ip;
- if (p_host.is_valid_ip_address())
- ip=p_host;
- else
- ip = IP::get_singleton()->resolve_hostname(p_host);
+Error ScriptDebuggerRemote::connect_to_host(const String &p_host, uint16_t p_port) {
+ IP_Address ip;
+ if (p_host.is_valid_ip_address())
+ ip = p_host;
+ else
+ ip = IP::get_singleton()->resolve_hostname(p_host);
- int port = p_port;
+ int port = p_port;
- int tries = 3;
- tcp_client->connect_to_host(ip, port);
+ int tries = 3;
+ tcp_client->connect_to_host(ip, port);
- while (tries--) {
+ while (tries--) {
- if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
- break;
- } else {
+ if (tcp_client->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
+ break;
+ } else {
- OS::get_singleton()->delay_usec(1000000);
- print_line("Remote Debugger: Connection failed with status: " + String::num(tcp_client->get_status())+"'', retrying in 1 sec.");
- };
- };
+ OS::get_singleton()->delay_usec(1000000);
+ print_line("Remote Debugger: Connection failed with status: " + String::num(tcp_client->get_status()) + "'', retrying in 1 sec.");
+ };
+ };
- if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
+ if (tcp_client->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
- print_line("Remote Debugger: Unable to connect");
- return FAILED;
- };
+ print_line("Remote Debugger: Unable to connect");
+ return FAILED;
+ };
-// print_line("Remote Debugger: Connection OK!");
- packet_peer_stream->set_stream_peer(tcp_client);
+ // print_line("Remote Debugger: Connection OK!");
+ packet_peer_stream->set_stream_peer(tcp_client);
- return OK;
+ return OK;
}
-static int _ScriptDebuggerRemote_found_id=0;
-static Object* _ScriptDebuggerRemote_find=NULL;
+static int _ScriptDebuggerRemote_found_id = 0;
+static Object *_ScriptDebuggerRemote_find = NULL;
static void _ScriptDebuggerRemote_debug_func(Object *p_obj) {
- if (_ScriptDebuggerRemote_find==p_obj) {
- _ScriptDebuggerRemote_found_id=p_obj->get_instance_ID();
+ if (_ScriptDebuggerRemote_find == p_obj) {
+ _ScriptDebuggerRemote_found_id = p_obj->get_instance_ID();
}
}
-static ObjectID safe_get_instance_id(const Variant& p_v) {
+static ObjectID safe_get_instance_id(const Variant &p_v) {
Object *o = p_v;
- if (o==NULL)
+ if (o == NULL)
return 0;
else {
@@ -115,22 +111,19 @@ static ObjectID safe_get_instance_id(const Variant& p_v) {
return r->get_instance_ID();
} else {
-
- _ScriptDebuggerRemote_found_id=0;
- _ScriptDebuggerRemote_find=NULL;
+ _ScriptDebuggerRemote_found_id = 0;
+ _ScriptDebuggerRemote_find = NULL;
ObjectDB::debug_objects(_ScriptDebuggerRemote_debug_func);
return _ScriptDebuggerRemote_found_id;
-
}
}
}
-void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) {
+void ScriptDebuggerRemote::debug(ScriptLanguage *p_script, bool p_can_continue) {
//this function is called when there is a debugger break (bug on script)
//or when execution is paused from editor
-
if (!tcp_client->is_connected_to_host()) {
ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway.");
ERR_FAIL();
@@ -143,86 +136,81 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) {
packet_peer_stream->put_var(p_can_continue);
packet_peer_stream->put_var(p_script->debug_get_error());
- skip_profile_frame=true; // to avoid super long frame time for the frame
+ skip_profile_frame = true; // to avoid super long frame time for the frame
- Input::MouseMode mouse_mode=Input::get_singleton()->get_mouse_mode();
- if (mouse_mode!=Input::MOUSE_MODE_VISIBLE)
+ Input::MouseMode mouse_mode = Input::get_singleton()->get_mouse_mode();
+ if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
-
- while(true) {
+ while (true) {
_get_output();
- if (packet_peer_stream->get_available_packet_count()>0) {
+ if (packet_peer_stream->get_available_packet_count() > 0) {
Variant var;
Error err = packet_peer_stream->get_var(var);
- ERR_CONTINUE( err != OK);
- ERR_CONTINUE( var.get_type()!=Variant::ARRAY );
+ ERR_CONTINUE(err != OK);
+ ERR_CONTINUE(var.get_type() != Variant::ARRAY);
Array cmd = var;
- ERR_CONTINUE( cmd.size()==0);
- ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING );
+ ERR_CONTINUE(cmd.size() == 0);
+ ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
String command = cmd[0];
-
-
- if (command=="get_stack_dump") {
+ if (command == "get_stack_dump") {
packet_peer_stream->put_var("stack_dump");
int slc = p_script->debug_get_stack_level_count();
- packet_peer_stream->put_var( slc );
+ packet_peer_stream->put_var(slc);
- for(int i=0;i<slc;i++) {
+ for (int i = 0; i < slc; i++) {
Dictionary d;
- d["file"]=p_script->debug_get_stack_level_source(i);
- d["line"]=p_script->debug_get_stack_level_line(i);
- d["function"]=p_script->debug_get_stack_level_function(i);
+ d["file"] = p_script->debug_get_stack_level_source(i);
+ d["line"] = p_script->debug_get_stack_level_line(i);
+ d["function"] = p_script->debug_get_stack_level_function(i);
//d["id"]=p_script->debug_get_stack_level_
- d["id"]=0;
+ d["id"] = 0;
- packet_peer_stream->put_var( d );
+ packet_peer_stream->put_var(d);
}
- } else if (command=="get_stack_frame_vars") {
+ } else if (command == "get_stack_frame_vars") {
cmd.remove(0);
- ERR_CONTINUE( cmd.size()!=1 );
+ ERR_CONTINUE(cmd.size() != 1);
int lv = cmd[0];
List<String> members;
List<Variant> member_vals;
- p_script->debug_get_stack_level_members(lv,&members,&member_vals);
-
+ p_script->debug_get_stack_level_members(lv, &members, &member_vals);
-
- ERR_CONTINUE( members.size() !=member_vals.size() );
+ ERR_CONTINUE(members.size() != member_vals.size());
List<String> locals;
List<Variant> local_vals;
- p_script->debug_get_stack_level_locals(lv,&locals,&local_vals);
+ p_script->debug_get_stack_level_locals(lv, &locals, &local_vals);
- ERR_CONTINUE( locals.size() !=local_vals.size() );
+ ERR_CONTINUE(locals.size() != local_vals.size());
packet_peer_stream->put_var("stack_frame_vars");
- packet_peer_stream->put_var(2+locals.size()*2+members.size()*2);
+ packet_peer_stream->put_var(2 + locals.size() * 2 + members.size() * 2);
{ //members
packet_peer_stream->put_var(members.size());
- List<String>::Element *E=members.front();
- List<Variant>::Element *F=member_vals.front();
+ List<String>::Element *E = members.front();
+ List<Variant>::Element *F = member_vals.front();
- while(E) {
+ while (E) {
- if (F->get().get_type()==Variant::OBJECT) {
- packet_peer_stream->put_var("*"+E->get());
+ if (F->get().get_type() == Variant::OBJECT) {
+ packet_peer_stream->put_var("*" + E->get());
String pretty_print = F->get().operator String();
packet_peer_stream->put_var(pretty_print.ascii().get_data());
} else {
@@ -230,23 +218,21 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) {
packet_peer_stream->put_var(F->get());
}
- E=E->next();
- F=F->next();
+ E = E->next();
+ F = F->next();
}
-
}
-
{ //locals
packet_peer_stream->put_var(locals.size());
- List<String>::Element *E=locals.front();
- List<Variant>::Element *F=local_vals.front();
+ List<String>::Element *E = locals.front();
+ List<Variant>::Element *F = local_vals.front();
- while(E) {
+ while (E) {
- if (F->get().get_type()==Variant::OBJECT) {
- packet_peer_stream->put_var("*"+E->get());
+ if (F->get().get_type() == Variant::OBJECT) {
+ packet_peer_stream->put_var("*" + E->get());
String pretty_print = F->get().operator String();
packet_peer_stream->put_var(pretty_print.ascii().get_data());
} else {
@@ -254,116 +240,107 @@ void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) {
packet_peer_stream->put_var(F->get());
}
- E=E->next();
- F=F->next();
+ E = E->next();
+ F = F->next();
}
-
}
-
-
- } else if (command=="step") {
+ } else if (command == "step") {
set_depth(-1);
set_lines_left(1);
break;
- } else if (command=="next") {
+ } else if (command == "next") {
set_depth(0);
set_lines_left(1);
break;
- } else if (command=="continue") {
+ } else if (command == "continue") {
set_depth(-1);
set_lines_left(-1);
OS::get_singleton()->move_window_to_foreground();
break;
- } else if (command=="break") {
+ } else if (command == "break") {
ERR_PRINT("Got break when already broke!");
break;
- } else if (command=="request_scene_tree") {
+ } else if (command == "request_scene_tree") {
if (request_scene_tree)
request_scene_tree(request_scene_tree_ud);
- } else if (command=="request_video_mem") {
+ } else if (command == "request_video_mem") {
_send_video_memory();
- } else if (command=="inspect_object") {
+ } else if (command == "inspect_object") {
ObjectID id = cmd[1];
_send_object_id(id);
- } else if (command=="set_object_property") {
+ } else if (command == "set_object_property") {
- _set_object_property(cmd[1],cmd[2],cmd[3]);
+ _set_object_property(cmd[1], cmd[2], cmd[3]);
- } else if (command=="reload_scripts") {
- reload_all_scripts=true;
- } else if (command=="breakpoint") {
+ } else if (command == "reload_scripts") {
+ reload_all_scripts = true;
+ } else if (command == "breakpoint") {
bool set = cmd[3];
if (set)
- insert_breakpoint(cmd[2],cmd[1]);
+ insert_breakpoint(cmd[2], cmd[1]);
else
- remove_breakpoint(cmd[2],cmd[1]);
+ remove_breakpoint(cmd[2], cmd[1]);
} else {
_parse_live_edit(cmd);
}
-
-
} else {
OS::get_singleton()->delay_usec(10000);
}
-
}
packet_peer_stream->put_var("debug_exit");
packet_peer_stream->put_var(0);
- if (mouse_mode!=Input::MOUSE_MODE_VISIBLE)
+ if (mouse_mode != Input::MOUSE_MODE_VISIBLE)
Input::get_singleton()->set_mouse_mode(mouse_mode);
-
}
-
void ScriptDebuggerRemote::_get_output() {
mutex->lock();
if (output_strings.size()) {
- locking=true;
+ locking = true;
packet_peer_stream->put_var("output");
- packet_peer_stream->put_var(output_strings .size());
+ packet_peer_stream->put_var(output_strings.size());
- while(output_strings.size()) {
+ while (output_strings.size()) {
packet_peer_stream->put_var(output_strings.front()->get());
output_strings.pop_front();
}
- locking=false;
-
+ locking = false;
}
while (messages.size()) {
- locking=true;
- packet_peer_stream->put_var("message:"+messages.front()->get().message);
+ locking = true;
+ packet_peer_stream->put_var("message:" + messages.front()->get().message);
packet_peer_stream->put_var(messages.front()->get().data.size());
- for(int i=0;i<messages.front()->get().data.size();i++) {
+ for (int i = 0; i < messages.front()->get().data.size(); i++) {
packet_peer_stream->put_var(messages.front()->get().data[i]);
}
messages.pop_front();
- locking=false;
+ locking = false;
}
while (errors.size()) {
- locking=true;
+ locking = true;
packet_peer_stream->put_var("error");
OutputError oe = errors.front()->get();
- packet_peer_stream->put_var(oe.callstack.size()+2);
+ packet_peer_stream->put_var(oe.callstack.size() + 2);
Array error_data;
@@ -379,14 +356,12 @@ void ScriptDebuggerRemote::_get_output() {
error_data.push_back(oe.warning);
packet_peer_stream->put_var(error_data);
packet_peer_stream->put_var(oe.callstack.size());
- for(int i=0;i<oe.callstack.size();i++) {
+ for (int i = 0; i < oe.callstack.size(); i++) {
packet_peer_stream->put_var(oe.callstack[i]);
-
}
errors.pop_front();
- locking=false;
-
+ locking = false;
}
mutex->unlock();
}
@@ -395,56 +370,53 @@ void ScriptDebuggerRemote::line_poll() {
//the purpose of this is just processing events every now and then when the script might get too busy
//otherwise bugs like infinite loops cant be catched
- if (poll_every%2048==0)
+ if (poll_every % 2048 == 0)
_poll_events();
poll_every++;
-
}
+void ScriptDebuggerRemote::_err_handler(void *ud, const char *p_func, const char *p_file, int p_line, const char *p_err, const char *p_descr, ErrorHandlerType p_type) {
-void ScriptDebuggerRemote::_err_handler(void* ud,const char* p_func,const char*p_file,int p_line,const char *p_err, const char * p_descr,ErrorHandlerType p_type) {
-
- if (p_type==ERR_HANDLER_SCRIPT)
+ if (p_type == ERR_HANDLER_SCRIPT)
return; //ignore script errors, those go through debugger
- ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote*)ud;
+ ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)ud;
OutputError oe;
- oe.error=p_err;
- oe.error_descr=p_descr;
- oe.source_file=p_file;
- oe.source_line=p_line;
- oe.source_func=p_func;
- oe.warning=p_type==ERR_HANDLER_WARNING;
+ oe.error = p_err;
+ oe.error_descr = p_descr;
+ oe.source_file = p_file;
+ oe.source_line = p_line;
+ oe.source_func = p_func;
+ oe.warning = p_type == ERR_HANDLER_WARNING;
uint64_t time = OS::get_singleton()->get_ticks_msec();
- oe.hr=time/3600000;
- oe.min=(time/60000)%60;
- oe.sec=(time/1000)%60;
- oe.msec=time%1000;
+ oe.hr = time / 3600000;
+ oe.min = (time / 60000) % 60;
+ oe.sec = (time / 1000) % 60;
+ oe.msec = time % 1000;
Array cstack;
Vector<ScriptLanguage::StackInfo> si;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- si=ScriptServer::get_language(i)->debug_get_current_stack_info();
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ si = ScriptServer::get_language(i)->debug_get_current_stack_info();
if (si.size())
break;
}
- cstack.resize(si.size()*2);
- for(int i=0;i<si.size();i++) {
+ cstack.resize(si.size() * 2);
+ for (int i = 0; i < si.size(); i++) {
String path;
- int line=0;
+ int line = 0;
if (si[i].script.is_valid()) {
- path=si[i].script->get_path();
- line=si[i].line;
+ path = si[i].script->get_path();
+ line = si[i].line;
}
- cstack[i*2+0]=path;
- cstack[i*2+1]=line;
+ cstack[i * 2 + 0] = path;
+ cstack[i * 2 + 1] = line;
}
- oe.callstack=cstack;
-
+ oe.callstack = cstack;
sdr->mutex->lock();
@@ -456,97 +428,95 @@ void ScriptDebuggerRemote::_err_handler(void* ud,const char* p_func,const char*p
sdr->mutex->unlock();
}
-
-bool ScriptDebuggerRemote::_parse_live_edit(const Array& cmd) {
+bool ScriptDebuggerRemote::_parse_live_edit(const Array &cmd) {
String cmdstr = cmd[0];
if (!live_edit_funcs || !cmdstr.begins_with("live_"))
return false;
-
//print_line(Variant(cmd).get_construct_string());
- if (cmdstr=="live_set_root") {
+ if (cmdstr == "live_set_root") {
if (!live_edit_funcs->root_func)
return true;
//print_line("root: "+Variant(cmd).get_construct_string());
- live_edit_funcs->root_func(live_edit_funcs->udata,cmd[1],cmd[2]);
+ live_edit_funcs->root_func(live_edit_funcs->udata, cmd[1], cmd[2]);
- } else if (cmdstr=="live_node_path") {
+ } else if (cmdstr == "live_node_path") {
if (!live_edit_funcs->node_path_func)
return true;
//print_line("path: "+Variant(cmd).get_construct_string());
- live_edit_funcs->node_path_func(live_edit_funcs->udata,cmd[1],cmd[2]);
+ live_edit_funcs->node_path_func(live_edit_funcs->udata, cmd[1], cmd[2]);
- } else if (cmdstr=="live_res_path") {
+ } else if (cmdstr == "live_res_path") {
if (!live_edit_funcs->res_path_func)
return true;
- live_edit_funcs->res_path_func(live_edit_funcs->udata,cmd[1],cmd[2]);
+ live_edit_funcs->res_path_func(live_edit_funcs->udata, cmd[1], cmd[2]);
- } else if (cmdstr=="live_node_prop_res") {
+ } else if (cmdstr == "live_node_prop_res") {
if (!live_edit_funcs->node_set_res_func)
return true;
- live_edit_funcs->node_set_res_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->node_set_res_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_node_prop") {
+ } else if (cmdstr == "live_node_prop") {
if (!live_edit_funcs->node_set_func)
return true;
- live_edit_funcs->node_set_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->node_set_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_res_prop_res") {
+ } else if (cmdstr == "live_res_prop_res") {
if (!live_edit_funcs->res_set_res_func)
return true;
- live_edit_funcs->res_set_res_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->res_set_res_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_res_prop") {
+ } else if (cmdstr == "live_res_prop") {
if (!live_edit_funcs->res_set_func)
return true;
- live_edit_funcs->res_set_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->res_set_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_node_call") {
+ } else if (cmdstr == "live_node_call") {
if (!live_edit_funcs->node_call_func)
return true;
- live_edit_funcs->node_call_func(live_edit_funcs->udata,cmd[1],cmd[2], cmd[3],cmd[4],cmd[5],cmd[6],cmd[7]);
+ live_edit_funcs->node_call_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6], cmd[7]);
- } else if (cmdstr=="live_res_call") {
+ } else if (cmdstr == "live_res_call") {
if (!live_edit_funcs->res_call_func)
return true;
- live_edit_funcs->res_call_func(live_edit_funcs->udata,cmd[1],cmd[2], cmd[3],cmd[4],cmd[5],cmd[6],cmd[7]);
+ live_edit_funcs->res_call_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6], cmd[7]);
- } else if (cmdstr=="live_create_node") {
+ } else if (cmdstr == "live_create_node") {
- live_edit_funcs->tree_create_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->tree_create_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_instance_node") {
+ } else if (cmdstr == "live_instance_node") {
- live_edit_funcs->tree_instance_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->tree_instance_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_remove_node") {
+ } else if (cmdstr == "live_remove_node") {
- live_edit_funcs->tree_remove_node_func(live_edit_funcs->udata,cmd[1]);
+ live_edit_funcs->tree_remove_node_func(live_edit_funcs->udata, cmd[1]);
- } else if (cmdstr=="live_remove_and_keep_node") {
+ } else if (cmdstr == "live_remove_and_keep_node") {
- live_edit_funcs->tree_remove_and_keep_node_func(live_edit_funcs->udata,cmd[1],cmd[2]);
- } else if (cmdstr=="live_restore_node") {
+ live_edit_funcs->tree_remove_and_keep_node_func(live_edit_funcs->udata, cmd[1], cmd[2]);
+ } else if (cmdstr == "live_restore_node") {
- live_edit_funcs->tree_restore_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3]);
+ live_edit_funcs->tree_restore_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3]);
- } else if (cmdstr=="live_duplicate_node") {
+ } else if (cmdstr == "live_duplicate_node") {
- live_edit_funcs->tree_duplicate_node_func(live_edit_funcs->udata,cmd[1],cmd[2]);
- } else if (cmdstr=="live_reparent_node") {
+ live_edit_funcs->tree_duplicate_node_func(live_edit_funcs->udata, cmd[1], cmd[2]);
+ } else if (cmdstr == "live_reparent_node") {
- live_edit_funcs->tree_reparent_node_func(live_edit_funcs->udata,cmd[1],cmd[2],cmd[3],cmd[4]);
+ live_edit_funcs->tree_reparent_node_func(live_edit_funcs->udata, cmd[1], cmd[2], cmd[3], cmd[4]);
} else {
@@ -556,26 +526,25 @@ bool ScriptDebuggerRemote::_parse_live_edit(const Array& cmd) {
return true;
}
-
void ScriptDebuggerRemote::_send_object_id(ObjectID p_id) {
- Object* obj = ObjectDB::get_instance(p_id);
+ Object *obj = ObjectDB::get_instance(p_id);
if (!obj)
return;
List<PropertyInfo> pinfo;
- obj->get_property_list(&pinfo,true);
+ obj->get_property_list(&pinfo, true);
- int props_to_send=0;
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ int props_to_send = 0;
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().usage&(PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CATEGORY)) {
+ if (E->get().usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CATEGORY)) {
props_to_send++;
}
}
packet_peer_stream->put_var("message:inspect_object");
- packet_peer_stream->put_var(props_to_send*5+4);
+ packet_peer_stream->put_var(props_to_send * 5 + 4);
packet_peer_stream->put_var(p_id);
packet_peer_stream->put_var(obj->get_class());
if (obj->is_class("Resource") || obj->is_class("Node"))
@@ -585,58 +554,56 @@ void ScriptDebuggerRemote::_send_object_id(ObjectID p_id) {
packet_peer_stream->put_var(props_to_send);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().usage&(PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CATEGORY)) {
+ if (E->get().usage & (PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CATEGORY)) {
- if (E->get().usage&PROPERTY_USAGE_CATEGORY) {
- packet_peer_stream->put_var("*"+E->get().name);
+ if (E->get().usage & PROPERTY_USAGE_CATEGORY) {
+ packet_peer_stream->put_var("*" + E->get().name);
} else {
packet_peer_stream->put_var(E->get().name);
}
Variant var = obj->get(E->get().name);
- if (E->get().type==Variant::OBJECT || var.get_type()==Variant::OBJECT) {
+ if (E->get().type == Variant::OBJECT || var.get_type() == Variant::OBJECT) {
ObjectID id2;
- Object *obj=var;
+ Object *obj = var;
if (obj) {
- id2=obj->get_instance_ID();
+ id2 = obj->get_instance_ID();
} else {
- id2=0;
+ id2 = 0;
}
packet_peer_stream->put_var(Variant::INT); //hint string
packet_peer_stream->put_var(PROPERTY_HINT_OBJECT_ID); //hint
packet_peer_stream->put_var(E->get().hint_string); //hint string
- packet_peer_stream->put_var(id2); //value
+ packet_peer_stream->put_var(id2); //value
} else {
packet_peer_stream->put_var(E->get().type);
packet_peer_stream->put_var(E->get().hint);
packet_peer_stream->put_var(E->get().hint_string);
//only send information that can be sent..
- if (var.get_type()==Variant::IMAGE) {
- var=Image();
+ if (var.get_type() == Variant::IMAGE) {
+ var = Image();
}
- if (var.get_type()>=Variant::DICTIONARY) {
- var=Array(); //send none for now, may be to big
+ if (var.get_type() >= Variant::DICTIONARY) {
+ var = Array(); //send none for now, may be to big
}
packet_peer_stream->put_var(var);
}
-
}
}
-
}
-void ScriptDebuggerRemote::_set_object_property(ObjectID p_id, const String& p_property, const Variant& p_value) {
+void ScriptDebuggerRemote::_set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value) {
- Object* obj = ObjectDB::get_instance(p_id);
+ Object *obj = ObjectDB::get_instance(p_id);
if (!obj)
return;
- obj->set(p_property,p_value);
+ obj->set(p_property, p_value);
}
void ScriptDebuggerRemote::_poll_events() {
@@ -644,7 +611,7 @@ void ScriptDebuggerRemote::_poll_events() {
//this si called from ::idle_poll, happens only when running the game,
//does not get called while on debug break
- while(packet_peer_stream->get_available_packet_count()>0) {
+ while (packet_peer_stream->get_available_packet_count() > 0) {
_get_output();
@@ -653,105 +620,99 @@ void ScriptDebuggerRemote::_poll_events() {
Variant var;
Error err = packet_peer_stream->get_var(var);
- ERR_CONTINUE( err != OK);
- ERR_CONTINUE( var.get_type()!=Variant::ARRAY );
+ ERR_CONTINUE(err != OK);
+ ERR_CONTINUE(var.get_type() != Variant::ARRAY);
Array cmd = var;
- ERR_CONTINUE( cmd.size()==0);
- ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING );
+ ERR_CONTINUE(cmd.size() == 0);
+ ERR_CONTINUE(cmd[0].get_type() != Variant::STRING);
String command = cmd[0];
//cmd.remove(0);
- if (command=="break") {
+ if (command == "break") {
if (get_break_language())
debug(get_break_language());
- } else if (command=="request_scene_tree") {
+ } else if (command == "request_scene_tree") {
if (request_scene_tree)
request_scene_tree(request_scene_tree_ud);
- } else if (command=="request_video_mem") {
+ } else if (command == "request_video_mem") {
_send_video_memory();
- } else if (command=="inspect_object") {
+ } else if (command == "inspect_object") {
ObjectID id = cmd[1];
_send_object_id(id);
- } else if (command=="set_object_property") {
+ } else if (command == "set_object_property") {
- _set_object_property(cmd[1],cmd[2],cmd[3]);
+ _set_object_property(cmd[1], cmd[2], cmd[3]);
- } else if (command=="start_profiling") {
+ } else if (command == "start_profiling") {
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->profiling_start();
}
- max_frame_functions=cmd[1];
+ max_frame_functions = cmd[1];
profiler_function_signature_map.clear();
- profiling=true;
- frame_time=0;
- idle_time=0;
- fixed_time=0;
- fixed_frame_time=0;
+ profiling = true;
+ frame_time = 0;
+ idle_time = 0;
+ fixed_time = 0;
+ fixed_frame_time = 0;
print_line("PROFILING ALRIGHT!");
- } else if (command=="stop_profiling") {
+ } else if (command == "stop_profiling") {
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->profiling_stop();
}
- profiling=false;
+ profiling = false;
_send_profiling_data(false);
print_line("PROFILING END!");
- } else if (command=="reload_scripts") {
- reload_all_scripts=true;
- } else if (command=="breakpoint") {
+ } else if (command == "reload_scripts") {
+ reload_all_scripts = true;
+ } else if (command == "breakpoint") {
bool set = cmd[3];
if (set)
- insert_breakpoint(cmd[2],cmd[1]);
+ insert_breakpoint(cmd[2], cmd[1]);
else
- remove_breakpoint(cmd[2],cmd[1]);
+ remove_breakpoint(cmd[2], cmd[1]);
} else {
_parse_live_edit(cmd);
}
-
}
-
}
-
void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
+ int ofs = 0;
-
-
- int ofs=0;
-
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
if (p_for_frame)
- ofs+=ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info[ofs],profile_info.size()-ofs);
+ ofs += ScriptServer::get_language(i)->profiling_get_frame_data(&profile_info[ofs], profile_info.size() - ofs);
else
- ofs+=ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info[ofs],profile_info.size()-ofs);
+ ofs += ScriptServer::get_language(i)->profiling_get_accumulated_data(&profile_info[ofs], profile_info.size() - ofs);
}
- for(int i=0;i<ofs;i++) {
- profile_info_ptrs[i]=&profile_info[i];
+ for (int i = 0; i < ofs; i++) {
+ profile_info_ptrs[i] = &profile_info[i];
}
- SortArray<ScriptLanguage::ProfilingInfo*,ProfileInfoSort> sa;
- sa.sort(profile_info_ptrs.ptr(),ofs);
+ SortArray<ScriptLanguage::ProfilingInfo *, ProfileInfoSort> sa;
+ sa.sort(profile_info_ptrs.ptr(), ofs);
- int to_send=MIN(ofs,max_frame_functions);
+ int to_send = MIN(ofs, max_frame_functions);
//check signatures first
- uint64_t total_script_time=0;
+ uint64_t total_script_time = 0;
- for(int i=0;i<to_send;i++) {
+ for (int i = 0; i < to_send; i++) {
if (!profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
@@ -761,25 +722,22 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
packet_peer_stream->put_var(profile_info_ptrs[i]->signature);
packet_peer_stream->put_var(idx);
- profiler_function_signature_map[profile_info_ptrs[i]->signature]=idx;
-
-
+ profiler_function_signature_map[profile_info_ptrs[i]->signature] = idx;
}
- total_script_time+=profile_info_ptrs[i]->self_time;
+ total_script_time += profile_info_ptrs[i]->self_time;
}
//send frames then
if (p_for_frame) {
packet_peer_stream->put_var("profile_frame");
- packet_peer_stream->put_var(8+profile_frame_data.size()*2+to_send*4);
+ packet_peer_stream->put_var(8 + profile_frame_data.size() * 2 + to_send * 4);
} else {
packet_peer_stream->put_var("profile_total");
- packet_peer_stream->put_var(8+to_send*4);
+ packet_peer_stream->put_var(8 + to_send * 4);
}
-
packet_peer_stream->put_var(Engine::get_singleton()->get_frames_drawn()); //total frame time
packet_peer_stream->put_var(frame_time); //total frame time
packet_peer_stream->put_var(idle_time); //idle frame time
@@ -790,10 +748,9 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
if (p_for_frame) {
- packet_peer_stream->put_var(profile_frame_data.size()); //how many profile framedatas to send
+ packet_peer_stream->put_var(profile_frame_data.size()); //how many profile framedatas to send
packet_peer_stream->put_var(to_send); //how many script functions to send
- for (int i=0;i<profile_frame_data.size();i++) {
-
+ for (int i = 0; i < profile_frame_data.size(); i++) {
packet_peer_stream->put_var(profile_frame_data[i].name);
packet_peer_stream->put_var(profile_frame_data[i].data);
@@ -803,28 +760,23 @@ void ScriptDebuggerRemote::_send_profiling_data(bool p_for_frame) {
packet_peer_stream->put_var(to_send); //how many script functions to send
}
+ for (int i = 0; i < to_send; i++) {
-
- for(int i=0;i<to_send;i++) {
-
- int sig_id=-1;
+ int sig_id = -1;
if (profiler_function_signature_map.has(profile_info_ptrs[i]->signature)) {
- sig_id=profiler_function_signature_map[profile_info_ptrs[i]->signature];
+ sig_id = profiler_function_signature_map[profile_info_ptrs[i]->signature];
}
-
-
packet_peer_stream->put_var(sig_id);
packet_peer_stream->put_var(profile_info_ptrs[i]->call_count);
- packet_peer_stream->put_var(profile_info_ptrs[i]->total_time/1000000.0);
- packet_peer_stream->put_var(profile_info_ptrs[i]->self_time/1000000.0);
+ packet_peer_stream->put_var(profile_info_ptrs[i]->total_time / 1000000.0);
+ packet_peer_stream->put_var(profile_info_ptrs[i]->self_time / 1000000.0);
}
if (p_for_frame) {
profile_frame_data.clear();
}
-
}
void ScriptDebuggerRemote::idle_poll() {
@@ -832,101 +784,94 @@ void ScriptDebuggerRemote::idle_poll() {
// this function is called every frame, except when there is a debugger break (::debug() in this class)
// execution stops and remains in the ::debug function
- _get_output();
-
+ _get_output();
- if (requested_quit) {
-
- packet_peer_stream->put_var("kill_me");
- packet_peer_stream->put_var(0);
- requested_quit=false;
-
- }
+ if (requested_quit) {
+ packet_peer_stream->put_var("kill_me");
+ packet_peer_stream->put_var(0);
+ requested_quit = false;
+ }
- if (performance) {
+ if (performance) {
uint64_t pt = OS::get_singleton()->get_ticks_msec();
- if (pt-last_perf_time > 1000) {
+ if (pt - last_perf_time > 1000) {
- last_perf_time=pt;
+ last_perf_time = pt;
int max = performance->get("MONITOR_MAX");
Array arr;
arr.resize(max);
- for(int i=0;i<max;i++) {
- arr[i]=performance->call("get_monitor",i);
+ for (int i = 0; i < max; i++) {
+ arr[i] = performance->call("get_monitor", i);
}
packet_peer_stream->put_var("performance");
packet_peer_stream->put_var(1);
packet_peer_stream->put_var(arr);
-
}
- }
+ }
- if (profiling) {
+ if (profiling) {
- if (skip_profile_frame) {
- skip_profile_frame=false;
- } else {
+ if (skip_profile_frame) {
+ skip_profile_frame = false;
+ } else {
//send profiling info normally
_send_profiling_data(true);
- }
- }
-
- if (reload_all_scripts) {
+ }
+ }
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- ScriptServer::get_language(i)->reload_all_scripts();
- }
- reload_all_scripts=false;
- }
+ if (reload_all_scripts) {
- _poll_events();
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ScriptServer::get_language(i)->reload_all_scripts();
+ }
+ reload_all_scripts = false;
+ }
+ _poll_events();
}
-
-void ScriptDebuggerRemote::send_message(const String& p_message, const Array &p_args) {
+void ScriptDebuggerRemote::send_message(const String &p_message, const Array &p_args) {
mutex->lock();
if (!locking && tcp_client->is_connected_to_host()) {
Message msg;
- msg.message=p_message;
- msg.data=p_args;
+ msg.message = p_message;
+ msg.data = p_args;
messages.push_back(msg);
}
mutex->unlock();
}
+void ScriptDebuggerRemote::_print_handler(void *p_this, const String &p_string) {
-void ScriptDebuggerRemote::_print_handler(void *p_this,const String& p_string) {
-
- ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote*)p_this;
+ ScriptDebuggerRemote *sdr = (ScriptDebuggerRemote *)p_this;
- uint64_t ticks = OS::get_singleton()->get_ticks_usec()/1000;
- sdr->msec_count+=ticks-sdr->last_msec;
- sdr->last_msec=ticks;
+ uint64_t ticks = OS::get_singleton()->get_ticks_usec() / 1000;
+ sdr->msec_count += ticks - sdr->last_msec;
+ sdr->last_msec = ticks;
- if (sdr->msec_count>1000) {
- sdr->char_count=0;
- sdr->msec_count=0;
+ if (sdr->msec_count > 1000) {
+ sdr->char_count = 0;
+ sdr->msec_count = 0;
}
String s = p_string;
- int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count,0), s.length());
+ int allowed_chars = MIN(MAX(sdr->max_cps - sdr->char_count, 0), s.length());
- if (allowed_chars==0)
+ if (allowed_chars == 0)
return;
- if (allowed_chars<s.length()) {
- s=s.substr(0,allowed_chars);
+ if (allowed_chars < s.length()) {
+ s = s.substr(0, allowed_chars);
}
- sdr->char_count+=allowed_chars;
+ sdr->char_count += allowed_chars;
- if (sdr->char_count>=sdr->max_cps) {
- s+="\n[output overflow, print less text!]\n";
+ if (sdr->char_count >= sdr->max_cps) {
+ s += "\n[output overflow, print less text!]\n";
}
sdr->mutex->lock();
@@ -939,42 +884,42 @@ void ScriptDebuggerRemote::_print_handler(void *p_this,const String& p_string) {
void ScriptDebuggerRemote::request_quit() {
- requested_quit=true;
+ requested_quit = true;
}
void ScriptDebuggerRemote::set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata) {
- request_scene_tree=p_func;
- request_scene_tree_ud=p_udata;
+ request_scene_tree = p_func;
+ request_scene_tree_ud = p_udata;
}
void ScriptDebuggerRemote::set_live_edit_funcs(LiveEditFuncs *p_funcs) {
- live_edit_funcs=p_funcs;
+ live_edit_funcs = p_funcs;
}
bool ScriptDebuggerRemote::is_profiling() const {
return profiling;
}
-void ScriptDebuggerRemote::add_profiling_frame_data(const StringName& p_name,const Array& p_data){
+void ScriptDebuggerRemote::add_profiling_frame_data(const StringName &p_name, const Array &p_data) {
- int idx=-1;
- for(int i=0;i<profile_frame_data.size();i++) {
- if (profile_frame_data[i].name==p_name) {
- idx=i;
+ int idx = -1;
+ for (int i = 0; i < profile_frame_data.size(); i++) {
+ if (profile_frame_data[i].name == p_name) {
+ idx = i;
break;
}
}
FrameData fd;
- fd.name=p_name;
- fd.data=p_data;
+ fd.name = p_name;
+ fd.data = p_data;
- if (idx==-1) {
+ if (idx == -1) {
profile_frame_data.push_back(fd);
} else {
- profile_frame_data[idx]=fd;
+ profile_frame_data[idx] = fd;
}
}
@@ -988,50 +933,46 @@ void ScriptDebuggerRemote::profiling_end() {
void ScriptDebuggerRemote::profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) {
- frame_time=p_frame_time;
- idle_time=p_idle_time;
- fixed_time=p_fixed_time;
- fixed_frame_time=p_fixed_frame_time;
-
-
+ frame_time = p_frame_time;
+ idle_time = p_idle_time;
+ fixed_time = p_fixed_time;
+ fixed_frame_time = p_fixed_frame_time;
}
-
-ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func=NULL;
+ScriptDebuggerRemote::ResourceUsageFunc ScriptDebuggerRemote::resource_usage_func = NULL;
ScriptDebuggerRemote::ScriptDebuggerRemote() {
- tcp_client = StreamPeerTCP::create_ref();
- packet_peer_stream = Ref<PacketPeerStream>( memnew(PacketPeerStream) );
+ tcp_client = StreamPeerTCP::create_ref();
+ packet_peer_stream = Ref<PacketPeerStream>(memnew(PacketPeerStream));
packet_peer_stream->set_stream_peer(tcp_client);
mutex = Mutex::create();
- locking=false;
+ locking = false;
- phl.printfunc=_print_handler;
- phl.userdata=this;
+ phl.printfunc = _print_handler;
+ phl.userdata = this;
add_print_handler(&phl);
- requested_quit=false;
+ requested_quit = false;
performance = GlobalConfig::get_singleton()->get_singleton_object("Performance");
- last_perf_time=0;
- poll_every=0;
- request_scene_tree=NULL;
- live_edit_funcs=NULL;
- max_cps = GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second",2048);
- char_count=0;
- msec_count=0;
- last_msec=0;
- skip_profile_frame=false;
-
- eh.errfunc=_err_handler;
- eh.userdata=this;
+ last_perf_time = 0;
+ poll_every = 0;
+ request_scene_tree = NULL;
+ live_edit_funcs = NULL;
+ max_cps = GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second", 2048);
+ char_count = 0;
+ msec_count = 0;
+ last_msec = 0;
+ skip_profile_frame = false;
+
+ eh.errfunc = _err_handler;
+ eh.userdata = this;
add_error_handler(&eh);
- profile_info.resize(CLAMP(int(GlobalConfig::get_singleton()->get("debug/profiler/max_functions")),128,65535));
+ profile_info.resize(CLAMP(int(GlobalConfig::get_singleton()->get("debug/profiler/max_functions")), 128, 65535));
profile_info_ptrs.resize(profile_info.size());
- profiling=false;
- max_frame_functions=16;
- reload_all_scripts=false;
-
+ profiling = false;
+ max_frame_functions = 16;
+ reload_all_scripts = false;
}
ScriptDebuggerRemote::~ScriptDebuggerRemote() {
@@ -1039,6 +980,4 @@ ScriptDebuggerRemote::~ScriptDebuggerRemote() {
remove_print_handler(&phl);
remove_error_handler(&eh);
memdelete(mutex);
-
-
}
diff --git a/core/script_debugger_remote.h b/core/script_debugger_remote.h
index 4b991e2f0c..9bdf116495 100644
--- a/core/script_debugger_remote.h
+++ b/core/script_debugger_remote.h
@@ -29,11 +29,10 @@
#ifndef SCRIPT_DEBUGGER_REMOTE_H
#define SCRIPT_DEBUGGER_REMOTE_H
-
-#include "script_language.h"
-#include "io/stream_peer_tcp.h"
#include "io/packet_peer.h"
+#include "io/stream_peer_tcp.h"
#include "list.h"
+#include "script_language.h"
class ScriptDebuggerRemote : public ScriptDebugger {
@@ -43,26 +42,24 @@ class ScriptDebuggerRemote : public ScriptDebugger {
Array data;
};
-
struct ProfileInfoSort {
- bool operator()(ScriptLanguage::ProfilingInfo*A,ScriptLanguage::ProfilingInfo*B) const {
+ bool operator()(ScriptLanguage::ProfilingInfo *A, ScriptLanguage::ProfilingInfo *B) const {
return A->total_time < B->total_time;
}
};
Vector<ScriptLanguage::ProfilingInfo> profile_info;
- Vector<ScriptLanguage::ProfilingInfo*> profile_info_ptrs;
+ Vector<ScriptLanguage::ProfilingInfo *> profile_info_ptrs;
- Map<StringName,int> profiler_function_signature_map;
- float frame_time,idle_time,fixed_time,fixed_frame_time;
+ Map<StringName, int> profiler_function_signature_map;
+ float frame_time, idle_time, fixed_time, fixed_frame_time;
bool profiling;
int max_frame_functions;
bool skip_profile_frame;
bool reload_all_scripts;
-
Ref<StreamPeerTCP> tcp_client;
Ref<PacketPeerStream> packet_peer_stream;
@@ -84,7 +81,6 @@ class ScriptDebuggerRemote : public ScriptDebugger {
String error_descr;
bool warning;
Array callstack;
-
};
List<String> output_strings;
@@ -97,7 +93,7 @@ class ScriptDebuggerRemote : public ScriptDebugger {
uint64_t msec_count;
bool locking; //hack to avoid a deadloop
- static void _print_handler(void *p_this,const String& p_string);
+ static void _print_handler(void *p_this, const String &p_string);
PrintHandlerList phl;
@@ -105,25 +101,22 @@ class ScriptDebuggerRemote : public ScriptDebugger {
void _poll_events();
uint32_t poll_every;
-
-
bool _parse_live_edit(const Array &p_command);
RequestSceneTreeMessageFunc request_scene_tree;
void *request_scene_tree_ud;
- void _set_object_property(ObjectID p_id, const String& p_property, const Variant& p_value);
+ void _set_object_property(ObjectID p_id, const String &p_property, const Variant &p_value);
void _send_object_id(ObjectID p_id);
void _send_video_memory();
LiveEditFuncs *live_edit_funcs;
ErrorHandlerList eh;
- static void _err_handler(void*,const char*,const char*,int p_line,const char *, const char *,ErrorHandlerType p_type);
+ static void _err_handler(void *, const char *, const char *, int p_line, const char *, const char *, ErrorHandlerType p_type);
void _send_profiling_data(bool p_for_frame);
-
struct FrameData {
StringName name;
@@ -132,9 +125,7 @@ class ScriptDebuggerRemote : public ScriptDebugger {
Vector<FrameData> profile_frame_data;
-
public:
-
struct ResourceUsage {
String path;
@@ -142,33 +133,32 @@ public:
String type;
RID id;
int vram;
- bool operator<(const ResourceUsage& p_img) const { return vram==p_img.vram ? id<p_img.id : vram > p_img.vram; }
+ bool operator<(const ResourceUsage &p_img) const { return vram == p_img.vram ? id < p_img.id : vram > p_img.vram; }
};
- typedef void (*ResourceUsageFunc)(List<ResourceUsage>*);
+ typedef void (*ResourceUsageFunc)(List<ResourceUsage> *);
static ResourceUsageFunc resource_usage_func;
- Error connect_to_host(const String& p_host,uint16_t p_port);
- virtual void debug(ScriptLanguage *p_script,bool p_can_continue=true);
+ Error connect_to_host(const String &p_host, uint16_t p_port);
+ virtual void debug(ScriptLanguage *p_script, bool p_can_continue = true);
virtual void idle_poll();
virtual void line_poll();
virtual bool is_remote() const { return true; }
virtual void request_quit();
- virtual void send_message(const String& p_message, const Array& p_args);
+ virtual void send_message(const String &p_message, const Array &p_args);
virtual void set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata);
virtual void set_live_edit_funcs(LiveEditFuncs *p_funcs);
virtual bool is_profiling() const;
- virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data);
+ virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data);
virtual void profiling_start();
virtual void profiling_end();
- virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time);
-
+ virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time);
ScriptDebuggerRemote();
~ScriptDebuggerRemote();
diff --git a/core/script_language.cpp b/core/script_language.cpp
index 32db35d018..2d565571a7 100644
--- a/core/script_language.cpp
+++ b/core/script_language.cpp
@@ -29,15 +29,15 @@
#include "script_language.h"
ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES];
-int ScriptServer::_language_count=0;
+int ScriptServer::_language_count = 0;
-bool ScriptServer::scripting_enabled=true;
-bool ScriptServer::reload_scripts_on_save=false;
-ScriptEditRequestFunction ScriptServer::edit_request_func=NULL;
+bool ScriptServer::scripting_enabled = true;
+bool ScriptServer::reload_scripts_on_save = false;
+ScriptEditRequestFunction ScriptServer::edit_request_func = NULL;
-void Script::_notification( int p_what) {
+void Script::_notification(int p_what) {
- if (p_what==NOTIFICATION_POSTINITIALIZE) {
+ if (p_what == NOTIFICATION_POSTINITIALIZE) {
if (ScriptDebugger::get_singleton())
ScriptDebugger::get_singleton()->set_break_language(get_language());
@@ -46,19 +46,18 @@ void Script::_notification( int p_what) {
void Script::_bind_methods() {
- ClassDB::bind_method(D_METHOD("can_instance"),&Script::can_instance);
+ ClassDB::bind_method(D_METHOD("can_instance"), &Script::can_instance);
//ClassDB::bind_method(D_METHOD("instance_create","base_object"),&Script::instance_create);
- ClassDB::bind_method(D_METHOD("instance_has","base_object"),&Script::instance_has);
- ClassDB::bind_method(D_METHOD("has_source_code"),&Script::has_source_code);
- ClassDB::bind_method(D_METHOD("get_source_code"),&Script::get_source_code);
- ClassDB::bind_method(D_METHOD("set_source_code","source"),&Script::set_source_code);
- ClassDB::bind_method(D_METHOD("reload","keep_state"),&Script::reload,DEFVAL(false));
-
+ ClassDB::bind_method(D_METHOD("instance_has", "base_object"), &Script::instance_has);
+ ClassDB::bind_method(D_METHOD("has_source_code"), &Script::has_source_code);
+ ClassDB::bind_method(D_METHOD("get_source_code"), &Script::get_source_code);
+ ClassDB::bind_method(D_METHOD("set_source_code", "source"), &Script::set_source_code);
+ ClassDB::bind_method(D_METHOD("reload", "keep_state"), &Script::reload, DEFVAL(false));
}
void ScriptServer::set_scripting_enabled(bool p_enabled) {
- scripting_enabled=p_enabled;
+ scripting_enabled = p_enabled;
}
bool ScriptServer::is_scripting_enabled() {
@@ -66,34 +65,31 @@ bool ScriptServer::is_scripting_enabled() {
return scripting_enabled;
}
-
int ScriptServer::get_language_count() {
return _language_count;
-
}
-ScriptLanguage* ScriptServer::get_language(int p_idx) {
+ScriptLanguage *ScriptServer::get_language(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,_language_count,NULL);
+ ERR_FAIL_INDEX_V(p_idx, _language_count, NULL);
return _languages[p_idx];
}
void ScriptServer::register_language(ScriptLanguage *p_language) {
- ERR_FAIL_COND( _language_count >= MAX_LANGUAGES );
- _languages[_language_count++]=p_language;
+ ERR_FAIL_COND(_language_count >= MAX_LANGUAGES);
+ _languages[_language_count++] = p_language;
}
void ScriptServer::unregister_language(ScriptLanguage *p_language) {
-
- for(int i=0;i<_language_count;i++) {
- if (_languages[i]==p_language) {
+ for (int i = 0; i < _language_count; i++) {
+ if (_languages[i] == p_language) {
_language_count--;
- if (i<_language_count) {
- SWAP(_languages[i],_languages[_language_count]);
+ if (i < _language_count) {
+ SWAP(_languages[i], _languages[_language_count]);
}
return;
}
@@ -102,14 +98,14 @@ void ScriptServer::unregister_language(ScriptLanguage *p_language) {
void ScriptServer::init_languages() {
- for(int i=0;i<_language_count;i++) {
+ for (int i = 0; i < _language_count; i++) {
_languages[i]->init();
}
}
void ScriptServer::set_reload_scripts_on_save(bool p_enable) {
- reload_scripts_on_save=p_enable;
+ reload_scripts_on_save = p_enable;
}
bool ScriptServer::is_reload_scripts_on_save_enabled() {
@@ -119,99 +115,87 @@ bool ScriptServer::is_reload_scripts_on_save_enabled() {
void ScriptServer::thread_enter() {
- for(int i=0;i<_language_count;i++) {
+ for (int i = 0; i < _language_count; i++) {
_languages[i]->thread_enter();
}
}
void ScriptServer::thread_exit() {
- for(int i=0;i<_language_count;i++) {
+ for (int i = 0; i < _language_count; i++) {
_languages[i]->thread_exit();
}
-
}
-
void ScriptInstance::get_property_state(List<Pair<StringName, Variant> > &state) {
List<PropertyInfo> pinfo;
get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().usage&PROPERTY_USAGE_STORAGE) {
- Pair<StringName,Variant> p;
- p.first=E->get().name;
- if (get(p.first,p.second))
+ if (E->get().usage & PROPERTY_USAGE_STORAGE) {
+ Pair<StringName, Variant> p;
+ p.first = E->get().name;
+ if (get(p.first, p.second))
state.push_back(p);
}
}
}
-
-Variant ScriptInstance::call(const StringName& p_method,VARIANT_ARG_DECLARE) {
+Variant ScriptInstance::call(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
Variant::CallError error;
- return call(p_method,argptr,argc,error);
+ return call(p_method, argptr, argc, error);
}
-
-void ScriptInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
+void ScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
Variant::CallError ce;
- call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls
+ call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls
}
-void ScriptInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
+void ScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
Variant::CallError ce;
- call(p_method,p_args,p_argcount,ce); // script may not support multilevel calls
+ call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls
}
-void ScriptInstance::call_multilevel(const StringName& p_method,VARIANT_ARG_DECLARE) {
+void ScriptInstance::call_multilevel(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
Variant::CallError error;
- call_multilevel(p_method,argptr,argc);
+ call_multilevel(p_method, argptr, argc);
}
ScriptInstance::~ScriptInstance() {
-
-
}
-
-ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton=NULL;
+ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton = NULL;
ScriptCodeCompletionCache::ScriptCodeCompletionCache() {
- singleton=this;
+ singleton = this;
}
-
-
void ScriptLanguage::frame() {
-
-
}
-ScriptDebugger * ScriptDebugger::singleton=NULL;
-
+ScriptDebugger *ScriptDebugger::singleton = NULL;
void ScriptDebugger::set_lines_left(int p_left) {
- lines_left=p_left;
+ lines_left = p_left;
}
int ScriptDebugger::get_lines_left() const {
@@ -221,7 +205,7 @@ int ScriptDebugger::get_lines_left() const {
void ScriptDebugger::set_depth(int p_depth) {
- depth=p_depth;
+ depth = p_depth;
}
int ScriptDebugger::get_depth() const {
@@ -229,38 +213,34 @@ int ScriptDebugger::get_depth() const {
return depth;
}
-void ScriptDebugger::insert_breakpoint(int p_line, const StringName& p_source) {
+void ScriptDebugger::insert_breakpoint(int p_line, const StringName &p_source) {
if (!breakpoints.has(p_line))
- breakpoints[p_line]=Set<StringName>();
+ breakpoints[p_line] = Set<StringName>();
breakpoints[p_line].insert(p_source);
-
}
-void ScriptDebugger::remove_breakpoint(int p_line, const StringName& p_source) {
+void ScriptDebugger::remove_breakpoint(int p_line, const StringName &p_source) {
if (!breakpoints.has(p_line))
return;
breakpoints[p_line].erase(p_source);
- if (breakpoints[p_line].size()==0)
+ if (breakpoints[p_line].size() == 0)
breakpoints.erase(p_line);
}
-bool ScriptDebugger::is_breakpoint(int p_line,const StringName& p_source) const {
+bool ScriptDebugger::is_breakpoint(int p_line, const StringName &p_source) const {
if (!breakpoints.has(p_line))
return false;
return breakpoints[p_line].has(p_source);
-
}
bool ScriptDebugger::is_breakpoint_line(int p_line) const {
return breakpoints.has(p_line);
-
}
-
-String ScriptDebugger::breakpoint_find_source(const String& p_source) const {
+String ScriptDebugger::breakpoint_find_source(const String &p_source) const {
return p_source;
}
@@ -271,116 +251,108 @@ void ScriptDebugger::clear_breakpoints() {
}
void ScriptDebugger::idle_poll() {
-
-
}
-
void ScriptDebugger::line_poll() {
-
-
}
void ScriptDebugger::set_break_language(ScriptLanguage *p_lang) {
- break_lang=p_lang;
+ break_lang = p_lang;
}
-ScriptLanguage* ScriptDebugger::get_break_language() const{
+ScriptLanguage *ScriptDebugger::get_break_language() const {
return break_lang;
}
-
ScriptDebugger::ScriptDebugger() {
- singleton=this;
- lines_left=-1;
- depth=-1;
- break_lang=NULL;
+ singleton = this;
+ lines_left = -1;
+ depth = -1;
+ break_lang = NULL;
}
-
-bool PlaceHolderScriptInstance::set(const StringName& p_name, const Variant& p_value) {
+bool PlaceHolderScriptInstance::set(const StringName &p_name, const Variant &p_value) {
if (values.has(p_name)) {
- values[p_name]=p_value;
+ values[p_name] = p_value;
return true;
}
return false;
}
-bool PlaceHolderScriptInstance::get(const StringName& p_name, Variant &r_ret) const {
+bool PlaceHolderScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
if (values.has(p_name)) {
- r_ret=values[p_name];
+ r_ret = values[p_name];
return true;
- } return false;
+ }
+ return false;
}
void PlaceHolderScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
- for(const List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
+ for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
p_properties->push_back(E->get());
}
}
-Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const {
+Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
- if (values.has(p_name)) {
+ if (values.has(p_name)) {
if (r_is_valid)
- *r_is_valid=true;
+ *r_is_valid = true;
return values[p_name].get_type();
}
if (r_is_valid)
- *r_is_valid=false;
+ *r_is_valid = false;
return Variant::NIL;
}
-
-void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties,const Map<StringName,Variant>& p_values) {
-
+void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values) {
Set<StringName> new_values;
- for(const List<PropertyInfo>::Element *E=p_properties.front();E;E=E->next()) {
+ for (const List<PropertyInfo>::Element *E = p_properties.front(); E; E = E->next()) {
StringName n = E->get().name;
new_values.insert(n);
- if (!values.has(n) || values[n].get_type()!=E->get().type) {
+ if (!values.has(n) || values[n].get_type() != E->get().type) {
if (p_values.has(n))
- values[n]=p_values[n];
+ values[n] = p_values[n];
}
}
- properties=p_properties;
+ properties = p_properties;
List<StringName> to_remove;
- for(Map<StringName,Variant>::Element *E=values.front();E;E=E->next()) {
+ for (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) {
if (!new_values.has(E->key()))
to_remove.push_back(E->key());
}
- while(to_remove.size()) {
+ while (to_remove.size()) {
values.erase(to_remove.front()->get());
to_remove.pop_front();
}
- if (owner && owner->get_script_instance()==this) {
+ if (owner && owner->get_script_instance() == this) {
owner->_change_notify();
}
//change notify
}
-PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script,Object *p_owner) {
+PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner) {
- language=p_language;
- script=p_script;
- owner=p_owner;
+ language = p_language;
+ script = p_script;
+ owner = p_owner;
}
PlaceHolderScriptInstance::~PlaceHolderScriptInstance() {
diff --git a/core/script_language.h b/core/script_language.h
index fd96541b18..6c37074639 100644
--- a/core/script_language.h
+++ b/core/script_language.h
@@ -29,29 +29,29 @@
#ifndef SCRIPT_LANGUAGE_H
#define SCRIPT_LANGUAGE_H
-#include "resource.h"
#include "map.h"
#include "pair.h"
+#include "resource.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class ScriptLanguage;
-typedef void (*ScriptEditRequestFunction)(const String& p_path);
+typedef void (*ScriptEditRequestFunction)(const String &p_path);
class ScriptServer {
enum {
- MAX_LANGUAGES=4
+ MAX_LANGUAGES = 4
};
static ScriptLanguage *_languages[MAX_LANGUAGES];
static int _language_count;
static bool scripting_enabled;
static bool reload_scripts_on_save;
-public:
+public:
static ScriptEditRequestFunction edit_request_func;
static void set_scripting_enabled(bool p_enabled);
@@ -70,82 +70,76 @@ public:
static void init_languages();
};
-
-
class ScriptInstance;
class PlaceHolderScriptInstance;
class Script : public Resource {
- GDCLASS( Script, Resource );
- OBJ_SAVE_TYPE( Script );
+ GDCLASS(Script, Resource);
+ OBJ_SAVE_TYPE(Script);
protected:
-
virtual bool editor_can_reload_from_file() { return false; } // this is handled by editor better
- void _notification( int p_what);
+ void _notification(int p_what);
static void _bind_methods();
-friend class PlaceHolderScriptInstance;
+ friend class PlaceHolderScriptInstance;
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {}
-public:
-
- virtual bool can_instance() const=0;
- virtual Ref<Script> get_base_script() const=0; //for script inheritance
+public:
+ virtual bool can_instance() const = 0;
- virtual StringName get_instance_base_type() const=0; // this may not work in all scripts, will return empty if so
- virtual ScriptInstance* instance_create(Object *p_this)=0;
- virtual bool instance_has(const Object *p_this) const=0;
+ virtual Ref<Script> get_base_script() const = 0; //for script inheritance
+ virtual StringName get_instance_base_type() const = 0; // this may not work in all scripts, will return empty if so
+ virtual ScriptInstance *instance_create(Object *p_this) = 0;
+ virtual bool instance_has(const Object *p_this) const = 0;
- virtual bool has_source_code() const=0;
- virtual String get_source_code() const=0;
- virtual void set_source_code(const String& p_code)=0;
- virtual Error reload(bool p_keep_state=false)=0;
+ virtual bool has_source_code() const = 0;
+ virtual String get_source_code() const = 0;
+ virtual void set_source_code(const String &p_code) = 0;
+ virtual Error reload(bool p_keep_state = false) = 0;
- virtual bool has_method(const StringName& p_method) const=0;
- virtual MethodInfo get_method_info(const StringName& p_method) const=0;
+ virtual bool has_method(const StringName &p_method) const = 0;
+ virtual MethodInfo get_method_info(const StringName &p_method) const = 0;
- virtual bool is_tool() const=0;
+ virtual bool is_tool() const = 0;
- virtual String get_node_type() const=0;
+ virtual String get_node_type() const = 0;
- virtual ScriptLanguage *get_language() const=0;
+ virtual ScriptLanguage *get_language() const = 0;
- virtual bool has_script_signal(const StringName& p_signal) const=0;
- virtual void get_script_signal_list(List<MethodInfo> *r_signals) const=0;
+ virtual bool has_script_signal(const StringName &p_signal) const = 0;
+ virtual void get_script_signal_list(List<MethodInfo> *r_signals) const = 0;
- virtual bool get_property_default_value(const StringName& p_property,Variant& r_value) const=0;
+ virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const = 0;
virtual void update_exports() {} //editor tool
- virtual void get_script_method_list(List<MethodInfo> *p_list) const=0;
- virtual void get_script_property_list(List<PropertyInfo> *p_list) const=0;
+ virtual void get_script_method_list(List<MethodInfo> *p_list) const = 0;
+ virtual void get_script_property_list(List<PropertyInfo> *p_list) const = 0;
- virtual int get_member_line(const StringName& p_member) const { return 0; }
+ virtual int get_member_line(const StringName &p_member) const { return 0; }
Script() {}
};
class ScriptInstance {
public:
-
-
- virtual bool set(const StringName& p_name, const Variant& p_value)=0;
- virtual bool get(const StringName& p_name, Variant &r_ret) const=0;
- virtual void get_property_list(List<PropertyInfo> *p_properties) const=0;
- virtual Variant::Type get_property_type(const StringName& p_name,bool *r_is_valid=NULL) const=0;
-
- virtual void get_property_state(List<Pair<StringName,Variant> > &state);
-
- virtual void get_method_list(List<MethodInfo> *p_list) const=0;
- virtual bool has_method(const StringName& p_method) const=0;
- virtual Variant call(const StringName& p_method,VARIANT_ARG_LIST);
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error)=0;
- virtual void call_multilevel(const StringName& p_method,VARIANT_ARG_LIST);
- 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)=0;
+ virtual bool set(const StringName &p_name, const Variant &p_value) = 0;
+ virtual bool get(const StringName &p_name, Variant &r_ret) const = 0;
+ virtual void get_property_list(List<PropertyInfo> *p_properties) const = 0;
+ virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const = 0;
+
+ virtual void get_property_state(List<Pair<StringName, Variant> > &state);
+
+ virtual void get_method_list(List<MethodInfo> *p_list) const = 0;
+ virtual bool has_method(const StringName &p_method) const = 0;
+ virtual Variant call(const StringName &p_method, VARIANT_ARG_LIST);
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) = 0;
+ virtual void call_multilevel(const StringName &p_method, VARIANT_ARG_LIST);
+ 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) = 0;
//this is used by script languages that keep a reference counter of their own
//you can make make Ref<> not die when it reaches zero, so deleting the reference
@@ -154,7 +148,7 @@ public:
virtual void refcount_incremented() {}
virtual bool refcount_decremented() { return true; } //return true if it can die
- virtual Ref<Script> get_script() const=0;
+ virtual Ref<Script> get_script() const = 0;
virtual bool is_placeholder() const { return false; }
@@ -166,50 +160,48 @@ public:
RPC_MODE_SLAVE,
};
- virtual RPCMode get_rpc_mode(const StringName& p_method) const=0;
- virtual RPCMode get_rset_mode(const StringName& p_variable) const=0;
+ virtual RPCMode get_rpc_mode(const StringName &p_method) const = 0;
+ virtual RPCMode get_rset_mode(const StringName &p_variable) const = 0;
- virtual ScriptLanguage *get_language()=0;
+ virtual ScriptLanguage *get_language() = 0;
virtual ~ScriptInstance();
};
class ScriptCodeCompletionCache {
static ScriptCodeCompletionCache *singleton;
-public:
- virtual RES get_cached_resource(const String& p_path)=0;
+public:
+ virtual RES get_cached_resource(const String &p_path) = 0;
- static ScriptCodeCompletionCache* get_sigleton() { return singleton; }
+ static ScriptCodeCompletionCache *get_sigleton() { return singleton; }
ScriptCodeCompletionCache();
-
};
class ScriptLanguage {
public:
-
- virtual String get_name() const=0;
+ virtual String get_name() const = 0;
/* LANGUAGE FUNCTIONS */
- virtual void init()=0;
- virtual String get_type() const=0;
- virtual String get_extension() const=0;
- virtual Error execute_file(const String& p_path) =0;
- virtual void finish()=0;
+ virtual void init() = 0;
+ virtual String get_type() const = 0;
+ virtual String get_extension() const = 0;
+ virtual Error execute_file(const String &p_path) = 0;
+ virtual void finish() = 0;
/* EDITOR FUNCTIONS */
- virtual void get_reserved_words(List<String> *p_words) const=0;
- virtual void get_comment_delimiters(List<String> *p_delimiters) const=0;
- virtual void get_string_delimiters(List<String> *p_delimiters) const=0;
- virtual Ref<Script> get_template(const String& p_class_name, const String& p_base_class_name) const=0;
- 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=NULL) const=0;
- virtual Script *create_script() const=0;
- virtual bool has_named_classes() const=0;
- virtual int find_function(const String& p_function,const String& p_code) const=0;
- virtual String make_function(const String& p_class,const String& p_name,const PoolStringArray& p_args) const=0;
-
- virtual Error complete_code(const String& p_code, const String& p_base_path, Object*p_owner,List<String>* r_options,String& r_call_hint) { return ERR_UNAVAILABLE; }
+ virtual void get_reserved_words(List<String> *p_words) const = 0;
+ virtual void get_comment_delimiters(List<String> *p_delimiters) const = 0;
+ virtual void get_string_delimiters(List<String> *p_delimiters) const = 0;
+ virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const = 0;
+ 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 = NULL) const = 0;
+ virtual Script *create_script() const = 0;
+ virtual bool has_named_classes() const = 0;
+ virtual int find_function(const String &p_function, const String &p_code) const = 0;
+ virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const = 0;
+
+ virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return ERR_UNAVAILABLE; }
struct LookupResult {
enum Type {
@@ -226,10 +218,10 @@ public:
int location;
};
- virtual Error lookup_code(const String& p_code, const String& p_symbol,const String& p_base_path, Object*p_owner,LookupResult& r_result) { return ERR_UNAVAILABLE; }
+ virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result) { return ERR_UNAVAILABLE; }
- virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const=0;
- virtual void add_global_constant(const StringName& p_variable,const Variant& p_value)=0;
+ virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const = 0;
+ virtual void add_global_constant(const StringName &p_variable, const Variant &p_value) = 0;
/* MULTITHREAD FUNCTIONS */
@@ -239,15 +231,15 @@ public:
/* DEBUGGER FUNCTIONS */
- virtual String debug_get_error() const=0;
- virtual int debug_get_stack_level_count() const=0;
- virtual int debug_get_stack_level_line(int p_level) const=0;
- virtual String debug_get_stack_level_function(int p_level) const=0;
- virtual String debug_get_stack_level_source(int p_level) const=0;
- virtual void debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0;
- virtual void debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0;
- virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1)=0;
- virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1)=0;
+ virtual String debug_get_error() const = 0;
+ virtual int debug_get_stack_level_count() const = 0;
+ virtual int debug_get_stack_level_line(int p_level) const = 0;
+ virtual String debug_get_stack_level_function(int p_level) const = 0;
+ virtual String debug_get_stack_level_source(int p_level) const = 0;
+ virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0;
+ virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0;
+ virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1) = 0;
+ virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1) = 0;
struct StackInfo {
Ref<Script> script;
@@ -256,32 +248,30 @@ public:
virtual Vector<StackInfo> debug_get_current_stack_info() { return Vector<StackInfo>(); }
- virtual void reload_all_scripts()=0;
- virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload)=0;
+ virtual void reload_all_scripts() = 0;
+ virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) = 0;
/* LOADER FUNCTIONS */
- virtual void get_recognized_extensions(List<String> *p_extensions) const=0;
- virtual void get_public_functions(List<MethodInfo> *p_functions) const=0;
- virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const=0;
+ virtual void get_recognized_extensions(List<String> *p_extensions) const = 0;
+ virtual void get_public_functions(List<MethodInfo> *p_functions) const = 0;
+ virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const = 0;
struct ProfilingInfo {
StringName signature;
uint64_t call_count;
uint64_t total_time;
uint64_t self_time;
-
};
- virtual void profiling_start()=0;
- virtual void profiling_stop()=0;
-
- virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max)=0;
- virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max)=0;
+ virtual void profiling_start() = 0;
+ virtual void profiling_stop() = 0;
+ virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) = 0;
+ virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) = 0;
virtual void frame();
- virtual ~ScriptLanguage() {};
+ virtual ~ScriptLanguage(){};
};
extern uint8_t script_encryption_key[32];
@@ -290,42 +280,42 @@ class PlaceHolderScriptInstance : public ScriptInstance {
Object *owner;
List<PropertyInfo> properties;
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
ScriptLanguage *language;
Ref<Script> script;
public:
- virtual bool set(const StringName& p_name, const Variant& p_value);
- virtual bool get(const StringName& p_name, Variant &r_ret) const;
+ 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=NULL) const;
+ virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const;
virtual void get_method_list(List<MethodInfo> *p_list) const {}
- virtual bool has_method(const StringName& p_method) const { return false; }
- virtual Variant call(const StringName& p_method,VARIANT_ARG_LIST) { return Variant();}
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; return Variant(); }
+ virtual bool has_method(const StringName &p_method) const { return false; }
+ virtual Variant call(const StringName &p_method, VARIANT_ARG_LIST) { return Variant(); }
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ return Variant();
+ }
//virtual void call_multilevel(const StringName& p_method,VARIANT_ARG_LIST) { return Variant(); }
//virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) { return Variant(); }
virtual void notification(int p_notification) {}
-
virtual Ref<Script> get_script() const { return script; }
virtual ScriptLanguage *get_language() { return language; }
Object *get_owner() { return owner; }
- void update(const List<PropertyInfo> &p_properties,const Map<StringName,Variant>& p_values); //likely changed in editor
+ void update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values); //likely changed in editor
virtual bool is_placeholder() const { return true; }
- virtual RPCMode get_rpc_mode(const StringName& p_method) const { return RPC_MODE_DISABLED; }
- virtual RPCMode get_rset_mode(const StringName& p_variable) const { return RPC_MODE_DISABLED; }
+ virtual RPCMode get_rpc_mode(const StringName &p_method) const { return RPC_MODE_DISABLED; }
+ virtual RPCMode get_rset_mode(const StringName &p_variable) const { return RPC_MODE_DISABLED; }
- PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script,Object *p_owner);
+ PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner);
~PlaceHolderScriptInstance();
-
-
};
class ScriptDebugger {
@@ -333,64 +323,59 @@ class ScriptDebugger {
int lines_left;
int depth;
- static ScriptDebugger * singleton;
- Map<int,Set<StringName> > breakpoints;
+ static ScriptDebugger *singleton;
+ Map<int, Set<StringName> > breakpoints;
ScriptLanguage *break_lang;
-public:
+public:
typedef void (*RequestSceneTreeMessageFunc)(void *);
struct LiveEditFuncs {
void *udata;
- void (*node_path_func)(void *,const NodePath &p_path,int p_id);
- void (*res_path_func)(void *,const String &p_path,int p_id);
-
- void (*node_set_func)(void *,int p_id,const StringName& p_prop,const Variant& p_value);
- void (*node_set_res_func)(void *,int p_id,const StringName& p_prop,const String& p_value);
- void (*node_call_func)(void *,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE);
- void (*res_set_func)(void *,int p_id,const StringName& p_prop,const Variant& p_value);
- void (*res_set_res_func)(void *,int p_id,const StringName& p_prop,const String& p_value);
- void (*res_call_func)(void *,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE);
- void (*root_func)(void*, const NodePath& p_scene_path,const String& p_scene_from);
-
- void (*tree_create_node_func)(void*,const NodePath& p_parent,const String& p_type,const String& p_name);
- void (*tree_instance_node_func)(void*,const NodePath& p_parent,const String& p_path,const String& p_name);
- void (*tree_remove_node_func)(void*,const NodePath& p_at);
- void (*tree_remove_and_keep_node_func)(void*,const NodePath& p_at,ObjectID p_keep_id);
- void (*tree_restore_node_func)(void*,ObjectID p_id,const NodePath& p_at,int p_at_pos);
- void (*tree_duplicate_node_func)(void*,const NodePath& p_at,const String& p_new_name);
- void (*tree_reparent_node_func)(void*,const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos);
-
+ void (*node_path_func)(void *, const NodePath &p_path, int p_id);
+ void (*res_path_func)(void *, const String &p_path, int p_id);
+
+ void (*node_set_func)(void *, int p_id, const StringName &p_prop, const Variant &p_value);
+ void (*node_set_res_func)(void *, int p_id, const StringName &p_prop, const String &p_value);
+ void (*node_call_func)(void *, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE);
+ void (*res_set_func)(void *, int p_id, const StringName &p_prop, const Variant &p_value);
+ void (*res_set_res_func)(void *, int p_id, const StringName &p_prop, const String &p_value);
+ void (*res_call_func)(void *, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE);
+ void (*root_func)(void *, const NodePath &p_scene_path, const String &p_scene_from);
+
+ void (*tree_create_node_func)(void *, const NodePath &p_parent, const String &p_type, const String &p_name);
+ void (*tree_instance_node_func)(void *, const NodePath &p_parent, const String &p_path, const String &p_name);
+ void (*tree_remove_node_func)(void *, const NodePath &p_at);
+ void (*tree_remove_and_keep_node_func)(void *, const NodePath &p_at, ObjectID p_keep_id);
+ void (*tree_restore_node_func)(void *, ObjectID p_id, const NodePath &p_at, int p_at_pos);
+ void (*tree_duplicate_node_func)(void *, const NodePath &p_at, const String &p_new_name);
+ void (*tree_reparent_node_func)(void *, const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos);
};
-
-
- _FORCE_INLINE_ static ScriptDebugger * get_singleton() { return singleton; }
+ _FORCE_INLINE_ static ScriptDebugger *get_singleton() { return singleton; }
void set_lines_left(int p_left);
int get_lines_left() const;
void set_depth(int p_depth);
int get_depth() const;
- String breakpoint_find_source(const String& p_source) const;
- void insert_breakpoint(int p_line, const StringName& p_source);
- void remove_breakpoint(int p_line, const StringName& p_source);
- bool is_breakpoint(int p_line,const StringName& p_source) const;
+ String breakpoint_find_source(const String &p_source) const;
+ void insert_breakpoint(int p_line, const StringName &p_source);
+ void remove_breakpoint(int p_line, const StringName &p_source);
+ bool is_breakpoint(int p_line, const StringName &p_source) const;
bool is_breakpoint_line(int p_line) const;
void clear_breakpoints();
-
- virtual void debug(ScriptLanguage *p_script,bool p_can_continue=true)=0;
+ virtual void debug(ScriptLanguage *p_script, bool p_can_continue = true) = 0;
virtual void idle_poll();
virtual void line_poll();
-
void set_break_language(ScriptLanguage *p_lang);
- ScriptLanguage* get_break_language() const;
+ ScriptLanguage *get_break_language() const;
- virtual void send_message(const String& p_message, const Array& p_args)=0;
+ virtual void send_message(const String &p_message, const Array &p_args) = 0;
virtual bool is_remote() const { return false; }
virtual void request_quit() {}
@@ -398,18 +383,14 @@ public:
virtual void set_request_scene_tree_message_func(RequestSceneTreeMessageFunc p_func, void *p_udata) {}
virtual void set_live_edit_funcs(LiveEditFuncs *p_funcs) {}
- virtual bool is_profiling() const=0;
- virtual void add_profiling_frame_data(const StringName& p_name,const Array& p_data)=0;
- virtual void profiling_start()=0;
- virtual void profiling_end()=0;
- virtual void profiling_set_frame_times(float p_frame_time,float p_idle_time,float p_fixed_time,float p_fixed_frame_time)=0;
-
+ virtual bool is_profiling() const = 0;
+ virtual void add_profiling_frame_data(const StringName &p_name, const Array &p_data) = 0;
+ virtual void profiling_start() = 0;
+ virtual void profiling_end() = 0;
+ virtual void profiling_set_frame_times(float p_frame_time, float p_idle_time, float p_fixed_time, float p_fixed_frame_time) = 0;
ScriptDebugger();
- virtual ~ScriptDebugger() {singleton=NULL;}
-
+ virtual ~ScriptDebugger() { singleton = NULL; }
};
-
-
#endif
diff --git a/core/self_list.h b/core/self_list.h
index aec3c33adc..45986d77e9 100644
--- a/core/self_list.h
+++ b/core/self_list.h
@@ -31,78 +31,74 @@
#include "typedefs.h"
-template<class T>
+template <class T>
class SelfList {
public:
-
-
-
class List {
-
SelfList<T> *_first;
+
public:
void add(SelfList<T> *p_elem) {
ERR_FAIL_COND(p_elem->_root);
- p_elem->_root=this;
- p_elem->_next=_first;
- p_elem->_prev=NULL;
+ p_elem->_root = this;
+ p_elem->_next = _first;
+ p_elem->_prev = NULL;
if (_first)
- _first->_prev=p_elem;
- _first=p_elem;
+ _first->_prev = p_elem;
+ _first = p_elem;
}
void remove(SelfList<T> *p_elem) {
- ERR_FAIL_COND(p_elem->_root!=this);
+ ERR_FAIL_COND(p_elem->_root != this);
if (p_elem->_next) {
- p_elem->_next->_prev=p_elem->_prev;
+ p_elem->_next->_prev = p_elem->_prev;
}
if (p_elem->_prev) {
- p_elem->_prev->_next=p_elem->_next;
+ p_elem->_prev->_next = p_elem->_next;
}
- if (_first==p_elem) {
+ if (_first == p_elem) {
- _first=p_elem->_next;
+ _first = p_elem->_next;
}
- p_elem->_next=NULL;
- p_elem->_prev=NULL;
- p_elem->_root=NULL;
+ p_elem->_next = NULL;
+ p_elem->_prev = NULL;
+ p_elem->_root = NULL;
}
_FORCE_INLINE_ SelfList<T> *first() { return _first; }
_FORCE_INLINE_ const SelfList<T> *first() const { return _first; }
- _FORCE_INLINE_ List() { _first=NULL; }
- _FORCE_INLINE_ ~List() { ERR_FAIL_COND(_first!=NULL); }
-
+ _FORCE_INLINE_ List() { _first = NULL; }
+ _FORCE_INLINE_ ~List() { ERR_FAIL_COND(_first != NULL); }
};
+
private:
List *_root;
T *_self;
SelfList<T> *_next;
SelfList<T> *_prev;
-public:
+public:
_FORCE_INLINE_ bool in_list() const { return _root; }
_FORCE_INLINE_ SelfList<T> *next() { return _next; }
_FORCE_INLINE_ SelfList<T> *prev() { return _prev; }
_FORCE_INLINE_ const SelfList<T> *next() const { return _next; }
_FORCE_INLINE_ const SelfList<T> *prev() const { return _prev; }
- _FORCE_INLINE_ T*self() const { return _self; }
-
+ _FORCE_INLINE_ T *self() const { return _self; }
_FORCE_INLINE_ SelfList(T *p_self) {
- _self=p_self;
- _next=NULL;
- _prev=NULL;
- _root=NULL;
+ _self = p_self;
+ _next = NULL;
+ _prev = NULL;
+ _root = NULL;
}
_FORCE_INLINE_ ~SelfList() {
@@ -110,7 +106,6 @@ public:
if (_root)
_root->remove(this);
}
-
};
#endif // SELF_LIST_H
diff --git a/core/set.h b/core/set.h
index a921fc661f..e6ec64e787 100644
--- a/core/set.h
+++ b/core/set.h
@@ -29,18 +29,17 @@
#ifndef SET_H
#define SET_H
-#include "typedefs.h"
#include "os/memory.h"
+#include "typedefs.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
// based on the very nice implementation of rb-trees by:
// http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html
-template <class T,class C=Comparator<T>,class A=DefaultAllocator >
+template <class T, class C = Comparator<T>, class A = DefaultAllocator>
class Set {
enum Color {
@@ -48,25 +47,22 @@ class Set {
BLACK
};
struct _Data;
-public:
-
-
+public:
class Element {
private:
- friend class Set<T,C,A>;
+ friend class Set<T, C, A>;
int color;
- Element* right;
- Element* left;
- Element* parent;
- Element* _next;
- Element* _prev;
+ Element *right;
+ Element *left;
+ Element *parent;
+ Element *_next;
+ Element *_prev;
T value;
//_Data *data;
public:
-
const Element *next() const {
return _next;
@@ -83,55 +79,52 @@ public:
return _prev;
}
- const T& get() const {
+ const T &get() const {
return value;
};
Element() {
- color=RED;
- right=NULL;
- left=NULL;
- parent=NULL;
- _next=NULL;
- _prev=NULL;
+ color = RED;
+ right = NULL;
+ left = NULL;
+ parent = NULL;
+ _next = NULL;
+ _prev = NULL;
};
};
-
private:
-
struct _Data {
- Element* _root;
- Element* _nil;
+ Element *_root;
+ Element *_nil;
int size_cache;
-
_Data() {
#ifdef GLOBALNIL_DISABLED
- _nil = memnew_allocator( Element,A );
- _nil->parent=_nil->left=_nil->right=_nil;
- _nil->color=BLACK;
+ _nil = memnew_allocator(Element, A);
+ _nil->parent = _nil->left = _nil->right = _nil;
+ _nil->color = BLACK;
#else
- _nil=(Element*)&_GlobalNilClass::_nil;
+ _nil = (Element *)&_GlobalNilClass::_nil;
#endif
_root = NULL;
- size_cache=0;
+ size_cache = 0;
}
void _create_root() {
- _root = memnew_allocator( Element,A );
- _root->parent=_root->left=_root->right=_nil;
- _root->color=BLACK;
+ _root = memnew_allocator(Element, A);
+ _root->parent = _root->left = _root->right = _nil;
+ _root->color = BLACK;
}
void _free_root() {
if (_root) {
- memdelete_allocator<Element,A>(_root);
- _root=NULL;
+ memdelete_allocator<Element, A>(_root);
+ _root = NULL;
}
}
@@ -139,7 +132,7 @@ private:
_free_root();
#ifdef GLOBALNIL_DISABLED
- memdelete_allocator<Element,A>(_nil);
+ memdelete_allocator<Element, A>(_nil);
#endif
//memdelete_allocator<Element,A>(_root);
}
@@ -149,58 +142,56 @@ private:
inline void _set_color(Element *p_node, int p_color) {
- ERR_FAIL_COND( p_node == _data._nil && p_color == RED );
- p_node->color=p_color;
+ ERR_FAIL_COND(p_node == _data._nil && p_color == RED);
+ p_node->color = p_color;
}
inline void _rotate_left(Element *p_node) {
- Element *r=p_node->right;
- p_node->right=r->left;
- if (r->left != _data._nil )
- r->left->parent=p_node;
- r->parent=p_node->parent;
- if (p_node==p_node->parent->left)
- p_node->parent->left=r;
+ Element *r = p_node->right;
+ p_node->right = r->left;
+ if (r->left != _data._nil)
+ r->left->parent = p_node;
+ r->parent = p_node->parent;
+ if (p_node == p_node->parent->left)
+ p_node->parent->left = r;
else
- p_node->parent->right=r;
-
- r->left=p_node;
- p_node->parent=r;
+ p_node->parent->right = r;
+ r->left = p_node;
+ p_node->parent = r;
}
inline void _rotate_right(Element *p_node) {
- Element *l=p_node->left;
- p_node->left=l->right;
+ Element *l = p_node->left;
+ p_node->left = l->right;
if (l->right != _data._nil)
- l->right->parent=p_node;
- l->parent=p_node->parent;
- if (p_node==p_node->parent->right)
- p_node->parent->right=l;
+ l->right->parent = p_node;
+ l->parent = p_node->parent;
+ if (p_node == p_node->parent->right)
+ p_node->parent->right = l;
else
- p_node->parent->left=l;
-
- l->right=p_node;
- p_node->parent=l;
+ p_node->parent->left = l;
+ l->right = p_node;
+ p_node->parent = l;
}
- inline Element* _successor(Element *p_node) const {
+ inline Element *_successor(Element *p_node) const {
- Element *node=p_node;
+ Element *node = p_node;
if (node->right != _data._nil) {
- node=node->right;
- while(node->left != _data._nil) { /* returns the minium of the right subtree of node */
- node=node->left;
+ node = node->right;
+ while (node->left != _data._nil) { /* returns the minium of the right subtree of node */
+ node = node->left;
}
return node;
} else {
- while(node == node->parent->right) {
- node=node->parent;
+ while (node == node->parent->right) {
+ node = node->parent;
}
if (node->parent == _data._root)
return NULL;
@@ -208,70 +199,69 @@ private:
}
}
- inline Element* _predecessor(Element *p_node) const {
- Element *node=p_node;
+ inline Element *_predecessor(Element *p_node) const {
+ Element *node = p_node;
if (node->left != _data._nil) {
- node=node->left;
- while(node->right != _data._nil) { /* returns the minium of the left subtree of node */
- node=node->right;
+ node = node->left;
+ while (node->right != _data._nil) { /* returns the minium of the left subtree of node */
+ node = node->right;
}
return node;
} else {
- while(node == node->parent->left) {
+ while (node == node->parent->left) {
if (node->parent == _data._root)
return NULL;
- node=node->parent;
+ node = node->parent;
}
return node->parent;
}
}
-
- Element *_find(const T& p_value) const {
+ Element *_find(const T &p_value) const {
Element *node = _data._root->left;
C less;
- while(node!=_data._nil) {
+ while (node != _data._nil) {
- if (less(p_value,node->value))
- node=node->left;
- else if (less(node->value,p_value))
- node=node->right;
+ if (less(p_value, node->value))
+ node = node->left;
+ else if (less(node->value, p_value))
+ node = node->right;
else
break; // found
}
- return (node!=_data._nil)?node:NULL;
+ return (node != _data._nil) ? node : NULL;
}
- Element *_lower_bound(const T& p_value) const {
+ Element *_lower_bound(const T &p_value) const {
Element *node = _data._root->left;
Element *prev = NULL;
C less;
- while(node!=_data._nil) {
- prev=node;
+ while (node != _data._nil) {
+ prev = node;
- if (less(p_value,node->value))
- node=node->left;
- else if (less(node->value,p_value))
- node=node->right;
+ if (less(p_value, node->value))
+ node = node->left;
+ else if (less(node->value, p_value))
+ node = node->right;
else
break; // found
}
- if (node==_data._nil) {
- if (prev==NULL)
+ if (node == _data._nil) {
+ if (prev == NULL)
return NULL;
- if (less(prev->value,p_value)) {
+ if (less(prev->value, p_value)) {
- prev=prev->_next;
+ prev = prev->_next;
}
return prev;
@@ -280,308 +270,299 @@ private:
return node;
}
+ Element *_insert(const T &p_value, bool &r_exists) {
- Element *_insert(const T& p_value, bool& r_exists) {
-
- Element *new_parent=_data._root;
+ Element *new_parent = _data._root;
Element *node = _data._root->left;
C less;
- while (node!=_data._nil) {
+ while (node != _data._nil) {
- new_parent=node;
+ new_parent = node;
- if (less(p_value,node->value))
- node=node->left;
- else if (less(node->value,p_value))
- node=node->right;
+ if (less(p_value, node->value))
+ node = node->left;
+ else if (less(node->value, p_value))
+ node = node->right;
else {
- r_exists=true;
+ r_exists = true;
return node;
}
}
- Element *new_node = memnew_allocator( Element,A );
+ Element *new_node = memnew_allocator(Element, A);
- new_node->parent=new_parent;
- new_node->right=_data._nil;
- new_node->left=_data._nil;
- new_node->value=p_value;
+ new_node->parent = new_parent;
+ new_node->right = _data._nil;
+ new_node->left = _data._nil;
+ new_node->value = p_value;
//new_node->data=_data;
- if (new_parent==_data._root || less(p_value,new_parent->value)) {
+ if (new_parent == _data._root || less(p_value, new_parent->value)) {
- new_parent->left=new_node;
+ new_parent->left = new_node;
} else {
- new_parent->right=new_node;
+ new_parent->right = new_node;
}
- r_exists=false;
+ r_exists = false;
- new_node->_next=_successor(new_node);
- new_node->_prev=_predecessor(new_node);
+ new_node->_next = _successor(new_node);
+ new_node->_prev = _predecessor(new_node);
if (new_node->_next)
- new_node->_next->_prev=new_node;
+ new_node->_next->_prev = new_node;
if (new_node->_prev)
- new_node->_prev->_next=new_node;
-
+ new_node->_prev->_next = new_node;
return new_node;
}
- Element * _insert_rb(const T& p_value) {
+ Element *_insert_rb(const T &p_value) {
- bool exists=false;
- Element *new_node = _insert(p_value,exists);
+ bool exists = false;
+ Element *new_node = _insert(p_value, exists);
if (exists)
return new_node;
- Element *node=new_node;
+ Element *node = new_node;
_data.size_cache++;
- while(node->parent->color==RED) {
+ while (node->parent->color == RED) {
if (node->parent == node->parent->parent->left) {
- Element *aux=node->parent->parent->right;
+ Element *aux = node->parent->parent->right;
- if (aux->color==RED) {
- _set_color(node->parent,BLACK);
- _set_color(aux,BLACK);
- _set_color(node->parent->parent,RED);
- node=node->parent->parent;
+ if (aux->color == RED) {
+ _set_color(node->parent, BLACK);
+ _set_color(aux, BLACK);
+ _set_color(node->parent->parent, RED);
+ node = node->parent->parent;
} else {
if (node == node->parent->right) {
- node=node->parent;
+ node = node->parent;
_rotate_left(node);
}
- _set_color(node->parent,BLACK);
- _set_color(node->parent->parent,RED);
+ _set_color(node->parent, BLACK);
+ _set_color(node->parent->parent, RED);
_rotate_right(node->parent->parent);
}
} else {
- Element *aux=node->parent->parent->left;
+ Element *aux = node->parent->parent->left;
- if (aux->color==RED) {
- _set_color(node->parent,BLACK);
- _set_color(aux,BLACK);
- _set_color(node->parent->parent,RED);
- node=node->parent->parent;
+ if (aux->color == RED) {
+ _set_color(node->parent, BLACK);
+ _set_color(aux, BLACK);
+ _set_color(node->parent->parent, RED);
+ node = node->parent->parent;
} else {
if (node == node->parent->left) {
- node=node->parent;
+ node = node->parent;
_rotate_right(node);
}
- _set_color(node->parent,BLACK);
- _set_color(node->parent->parent,RED);
+ _set_color(node->parent, BLACK);
+ _set_color(node->parent->parent, RED);
_rotate_left(node->parent->parent);
}
}
}
- _set_color(_data._root->left,BLACK);
+ _set_color(_data._root->left, BLACK);
return new_node;
}
void _erase_fix(Element *p_node) {
Element *root = _data._root->left;
- Element *node=p_node;
-
+ Element *node = p_node;
- while( (node->color==BLACK) && (root != node)) {
+ while ((node->color == BLACK) && (root != node)) {
if (node == node->parent->left) {
- Element *aux=node->parent->right;
- if (aux->color==RED) {
- _set_color(aux,BLACK);
- _set_color(node->parent,RED);
+ Element *aux = node->parent->right;
+ if (aux->color == RED) {
+ _set_color(aux, BLACK);
+ _set_color(node->parent, RED);
_rotate_left(node->parent);
- aux=node->parent->right;
+ aux = node->parent->right;
}
- if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) {
- _set_color(aux,RED);
- node=node->parent;
+ if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) {
+ _set_color(aux, RED);
+ node = node->parent;
} else {
- if (aux->right->color==BLACK) {
- _set_color(aux->left,BLACK);
- _set_color(aux,RED);
+ if (aux->right->color == BLACK) {
+ _set_color(aux->left, BLACK);
+ _set_color(aux, RED);
_rotate_right(aux);
- aux=node->parent->right;
+ aux = node->parent->right;
}
- _set_color(aux,node->parent->color);
- _set_color(node->parent,BLACK);
- _set_color(aux->right,BLACK);
+ _set_color(aux, node->parent->color);
+ _set_color(node->parent, BLACK);
+ _set_color(aux->right, BLACK);
_rotate_left(node->parent);
- node=root; /* this is to exit while loop */
+ node = root; /* this is to exit while loop */
}
} else { /* the code below is has left and right switched from above */
- Element *aux=node->parent->left;
- if (aux->color==RED) {
- _set_color(aux,BLACK);
- _set_color(node->parent,RED);
+ Element *aux = node->parent->left;
+ if (aux->color == RED) {
+ _set_color(aux, BLACK);
+ _set_color(node->parent, RED);
_rotate_right(node->parent);
- aux=node->parent->left;
+ aux = node->parent->left;
}
- if ( (aux->right->color==BLACK) && (aux->left->color==BLACK) ) {
- _set_color(aux,RED);
- node=node->parent;
+ if ((aux->right->color == BLACK) && (aux->left->color == BLACK)) {
+ _set_color(aux, RED);
+ node = node->parent;
} else {
- if (aux->left->color==BLACK) {
- _set_color(aux->right,BLACK);
- _set_color(aux,RED);
+ if (aux->left->color == BLACK) {
+ _set_color(aux->right, BLACK);
+ _set_color(aux, RED);
_rotate_left(aux);
- aux=node->parent->left;
+ aux = node->parent->left;
}
- _set_color(aux,node->parent->color);
- _set_color(node->parent,BLACK);
- _set_color(aux->left,BLACK);
+ _set_color(aux, node->parent->color);
+ _set_color(node->parent, BLACK);
+ _set_color(aux->left, BLACK);
_rotate_right(node->parent);
- node=root;
+ node = root;
}
}
}
- _set_color(node,BLACK);
+ _set_color(node, BLACK);
- ERR_FAIL_COND(_data._nil->color!=BLACK);
+ ERR_FAIL_COND(_data._nil->color != BLACK);
}
void _erase(Element *p_node) {
-
- Element *rp= ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node);
+ Element *rp = ((p_node->left == _data._nil) || (p_node->right == _data._nil)) ? p_node : _successor(p_node);
if (!rp)
- rp=_data._nil;
- Element *node= (rp->left == _data._nil) ? rp->right : rp->left;
+ rp = _data._nil;
+ Element *node = (rp->left == _data._nil) ? rp->right : rp->left;
- if (_data._root == (node->parent=rp->parent) ) {
- _data._root->left=node;
+ if (_data._root == (node->parent = rp->parent)) {
+ _data._root->left = node;
} else {
if (rp == rp->parent->left) {
- rp->parent->left=node;
+ rp->parent->left = node;
} else {
- rp->parent->right=node;
+ rp->parent->right = node;
}
}
if (rp != p_node) {
- ERR_FAIL_COND( rp == _data._nil );
+ ERR_FAIL_COND(rp == _data._nil);
- if (rp->color==BLACK)
+ if (rp->color == BLACK)
_erase_fix(node);
-
- rp->left=p_node->left;
- rp->right=p_node->right;
- rp->parent=p_node->parent;
- rp->color=p_node->color;
- p_node->left->parent=rp;
- p_node->right->parent=rp;
+ rp->left = p_node->left;
+ rp->right = p_node->right;
+ rp->parent = p_node->parent;
+ rp->color = p_node->color;
+ p_node->left->parent = rp;
+ p_node->right->parent = rp;
if (p_node == p_node->parent->left) {
- p_node->parent->left=rp;
+ p_node->parent->left = rp;
} else {
- p_node->parent->right=rp;
+ p_node->parent->right = rp;
}
} else {
- if (p_node->color==BLACK)
+ if (p_node->color == BLACK)
_erase_fix(node);
-
}
-
if (p_node->_next)
- p_node->_next->_prev=p_node->_prev;
+ p_node->_next->_prev = p_node->_prev;
if (p_node->_prev)
- p_node->_prev->_next=p_node->_next;
+ p_node->_prev->_next = p_node->_next;
- memdelete_allocator<Element,A>(p_node);
+ memdelete_allocator<Element, A>(p_node);
_data.size_cache--;
- ERR_FAIL_COND( _data._nil->color==RED );
+ ERR_FAIL_COND(_data._nil->color == RED);
}
+ void _calculate_depth(Element *p_element, int &max_d, int d) const {
- void _calculate_depth(Element *p_element,int &max_d,int d) const {
-
- if (p_element==_data._nil) {
+ if (p_element == _data._nil) {
return;
}
- _calculate_depth(p_element->left,max_d,d+1);
- _calculate_depth(p_element->right,max_d,d+1);
- if (d>max_d)
- max_d=d;
+ _calculate_depth(p_element->left, max_d, d + 1);
+ _calculate_depth(p_element->right, max_d, d + 1);
+ if (d > max_d)
+ max_d = d;
}
void _cleanup_tree(Element *p_element) {
- if (p_element==_data._nil)
+ if (p_element == _data._nil)
return;
_cleanup_tree(p_element->left);
_cleanup_tree(p_element->right);
- memdelete_allocator<Element,A>( p_element );
+ memdelete_allocator<Element, A>(p_element);
}
- void _copy_from( const Set& p_set) {
+ void _copy_from(const Set &p_set) {
clear();
// not the fastest way, but safeset to write.
- for(Element *I=p_set.front();I;I=I->next()) {
+ for (Element *I = p_set.front(); I; I = I->next()) {
insert(I->get());
}
}
-public:
- const Element *find(const T& p_value) const {
+public:
+ const Element *find(const T &p_value) const {
if (!_data._root)
return NULL;
- const Element *res=_find(p_value);
+ const Element *res = _find(p_value);
return res;
}
- Element *find(const T& p_value) {
+ Element *find(const T &p_value) {
if (!_data._root)
return NULL;
- Element *res=_find(p_value);
+ Element *res = _find(p_value);
return res;
}
- bool has(const T& p_value) const {
+ bool has(const T &p_value) const {
if (!_data._root)
return false;
- return find(p_value)!=NULL;
+ return find(p_value) != NULL;
}
- Element *insert(const T& p_value) {
+ Element *insert(const T &p_value) {
if (!_data._root)
_data._create_root();
return _insert_rb(p_value);
-
}
- void erase(Element* p_element) {
+ void erase(Element *p_element) {
if (!_data._root)
return;
_erase(p_element);
- if (_data.size_cache==0 && _data._root)
+ if (_data.size_cache == 0 && _data._root)
_data._free_root();
}
- bool erase(const T& p_value) {
+ bool erase(const T &p_value) {
if (!_data._root)
return false;
- Element *e=find(p_value);
+ Element *e = find(p_value);
if (!e)
return false;
_erase(e);
- if (_data.size_cache==0 && _data._root)
+ if (_data.size_cache == 0 && _data._root)
_data._free_root();
return true;
}
@@ -590,12 +571,12 @@ public:
if (!_data._root)
return NULL;
- Element *e=_data._root->left;
- if (e==_data._nil)
+ Element *e = _data._root->left;
+ if (e == _data._nil)
return NULL;
- while(e->left!=_data._nil)
- e=e->left;
+ while (e->left != _data._nil)
+ e = e->left;
return e;
}
@@ -604,29 +585,28 @@ public:
if (!_data._root)
return NULL;
- Element *e=_data._root->left;
- if (e==_data._nil)
+ Element *e = _data._root->left;
+ if (e == _data._nil)
return NULL;
- while(e->right!=_data._nil)
- e=e->right;
+ while (e->right != _data._nil)
+ e = e->right;
return e;
}
- Element *lower_bound(const T& p_value) const {
+ Element *lower_bound(const T &p_value) const {
return _lower_bound(p_value);
}
-
inline int size() const { return _data.size_cache; }
int calculate_depth() const {
// used for debug mostly
if (!_data._root)
return 0;
- int max_d=0;
- _calculate_depth(_data._root->left,max_d,0);
+ int max_d = 0;
+ _calculate_depth(_data._root->left, max_d, 0);
return max_d;
}
@@ -636,32 +616,28 @@ public:
return;
_cleanup_tree(_data._root->left);
- _data._root->left=_data._nil;
- _data.size_cache=0;
- _data._nil->parent=_data._nil;
+ _data._root->left = _data._nil;
+ _data.size_cache = 0;
+ _data._nil->parent = _data._nil;
_data._free_root();
}
- void operator=(const Set& p_set) {
+ void operator=(const Set &p_set) {
- _copy_from( p_set );
+ _copy_from(p_set);
}
- Set(const Set& p_set) {
+ Set(const Set &p_set) {
- _copy_from( p_set );
+ _copy_from(p_set);
}
_FORCE_INLINE_ Set() {
-
-
}
-
~Set() {
clear();
}
-
};
#endif
diff --git a/core/simple_type.h b/core/simple_type.h
index 6d4a1ba455..b5182559d7 100644
--- a/core/simple_type.h
+++ b/core/simple_type.h
@@ -31,89 +31,85 @@
/* Batch of specializations to obtain the actual simple type */
-template<class T>
+template <class T>
struct GetSimpleType {
T type;
};
-template<class T>
+template <class T>
struct GetSimpleTypeT {
typedef T type_t;
};
-template<class T>
-struct GetSimpleType<T&> {
+template <class T>
+struct GetSimpleType<T &> {
T type;
-
};
-template<class T>
-struct GetSimpleTypeT<T&> {
+template <class T>
+struct GetSimpleTypeT<T &> {
typedef T type_t;
};
-template<class T>
+template <class T>
struct GetSimpleType<T const> {
T type;
- _FORCE_INLINE_ GetSimpleType() { }
-
+ _FORCE_INLINE_ GetSimpleType() {}
};
-template<class T>
+template <class T>
struct GetSimpleTypeT<T const> {
typedef T type_t;
};
-template<class T>
-struct GetSimpleType<const T&> {
+template <class T>
+struct GetSimpleType<const T &> {
T type;
- _FORCE_INLINE_ GetSimpleType() { }
-
+ _FORCE_INLINE_ GetSimpleType() {}
};
-template<class T>
-struct GetSimpleType<T*> {
+template <class T>
+struct GetSimpleType<T *> {
T *type;
- _FORCE_INLINE_ GetSimpleType() { type=NULL; }
+ _FORCE_INLINE_ GetSimpleType() { type = NULL; }
};
-template<class T>
-struct GetSimpleType<const T*> {
+template <class T>
+struct GetSimpleType<const T *> {
T *type;
- _FORCE_INLINE_ GetSimpleType() { type=NULL; }
+ _FORCE_INLINE_ GetSimpleType() { type = NULL; }
};
-
-#define SIMPLE_NUMERIC_TYPE(m_type)\
-template<>\
-struct GetSimpleType<m_type> { \
- m_type type;\
- _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \
-};\
-template<>\
-struct GetSimpleType<m_type const> { \
- m_type type;\
- _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \
-};\
-template<>\
-struct GetSimpleType<m_type&> { \
- m_type type;\
- _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \
-};\
-template<>\
-struct GetSimpleType<const m_type&> { \
- m_type type;\
- _FORCE_INLINE_ GetSimpleType() { type=(m_type)0; } \
-};\
+#define SIMPLE_NUMERIC_TYPE(m_type) \
+ template <> \
+ struct GetSimpleType<m_type> { \
+ m_type type; \
+ _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \
+ }; \
+ template <> \
+ struct GetSimpleType<m_type const> { \
+ m_type type; \
+ _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \
+ }; \
+ template <> \
+ struct GetSimpleType<m_type &> { \
+ m_type type; \
+ _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \
+ }; \
+ template <> \
+ struct GetSimpleType<const m_type &> { \
+ m_type type; \
+ _FORCE_INLINE_ GetSimpleType() { type = (m_type)0; } \
+ };
SIMPLE_NUMERIC_TYPE(bool);
SIMPLE_NUMERIC_TYPE(uint8_t);
@@ -127,8 +123,4 @@ SIMPLE_NUMERIC_TYPE(uint64_t);
SIMPLE_NUMERIC_TYPE(float);
SIMPLE_NUMERIC_TYPE(double);
-
-
-
#endif
-
diff --git a/core/sort.h b/core/sort.h
index fd3b57251a..8ec1cc6bd1 100644
--- a/core/sort.h
+++ b/core/sort.h
@@ -34,26 +34,24 @@
@author ,,, <red@lunatea>
*/
-template<class T>
+template <class T>
struct _DefaultComparator {
- inline bool operator()(const T&a,const T&b) const { return (a<b); }
+ inline bool operator()(const T &a, const T &b) const { return (a < b); }
};
-template<class T, class Comparator=_DefaultComparator<T> >
+template <class T, class Comparator = _DefaultComparator<T> >
class SortArray {
enum {
- INTROSORT_TRESHOLD=16
+ INTROSORT_TRESHOLD = 16
};
public:
-
Comparator compare;
-
- inline const T& median_of_3(const T& a, const T& b, const T& c) const {
+ inline const T &median_of_3(const T &a, const T &b, const T &c) const {
if (compare(a, b))
if (compare(b, c))
@@ -70,8 +68,6 @@ public:
return b;
}
-
-
inline int bitlog(int n) const {
int k;
for (k = 0; n != 1; n >>= 1)
@@ -79,10 +75,9 @@ public:
return k;
}
-
/* Heap / Heapsort functions */
- inline void push_heap(int p_first,int p_hole_idx,int p_top_index,T p_value,T* p_array) const {
+ inline void push_heap(int p_first, int p_hole_idx, int p_top_index, T p_value, T *p_array) const {
int parent = (p_hole_idx - 1) / 2;
while (p_hole_idx > p_top_index && compare(p_array[p_first + parent], p_value)) {
@@ -94,25 +89,24 @@ public:
p_array[p_first + p_hole_idx] = p_value;
}
- inline void pop_heap(int p_first, int p_last, int p_result, T p_value, T* p_array) const {
+ inline void pop_heap(int p_first, int p_last, int p_result, T p_value, T *p_array) const {
- p_array[p_result]=p_array[p_first];
- adjust_heap(p_first,0,p_last-p_first,p_value,p_array);
+ p_array[p_result] = p_array[p_first];
+ adjust_heap(p_first, 0, p_last - p_first, p_value, p_array);
}
- inline void pop_heap(int p_first,int p_last,T* p_array) const {
+ inline void pop_heap(int p_first, int p_last, T *p_array) const {
- pop_heap(p_first,p_last-1,p_last-1,p_array[p_last-1],p_array);
+ pop_heap(p_first, p_last - 1, p_last - 1, p_array[p_last - 1], p_array);
}
- inline void adjust_heap(int p_first,int p_hole_idx,int p_len,T p_value,T* p_array) const {
-
+ inline void adjust_heap(int p_first, int p_hole_idx, int p_len, T p_value, T *p_array) const {
int top_index = p_hole_idx;
int second_child = 2 * p_hole_idx + 2;
while (second_child < p_len) {
- if (compare(p_array[p_first + second_child],p_array[p_first + (second_child - 1)]))
+ if (compare(p_array[p_first + second_child], p_array[p_first + (second_child - 1)]))
second_child--;
p_array[p_first + p_hole_idx] = p_array[p_first + second_child];
@@ -124,22 +118,22 @@ public:
p_array[p_first + p_hole_idx] = p_array[p_first + (second_child - 1)];
p_hole_idx = second_child - 1;
}
- push_heap(p_first, p_hole_idx, top_index, p_value,p_array);
+ push_heap(p_first, p_hole_idx, top_index, p_value, p_array);
}
- inline void sort_heap(int p_first,int p_last,T* p_array) const {
+ inline void sort_heap(int p_first, int p_last, T *p_array) const {
- while(p_last-p_first > 1) {
+ while (p_last - p_first > 1) {
- pop_heap(p_first,p_last--,p_array);
+ pop_heap(p_first, p_last--, p_array);
}
}
- inline void make_heap(int p_first, int p_last,T* p_array) const {
+ inline void make_heap(int p_first, int p_last, T *p_array) const {
if (p_last - p_first < 2)
return;
int len = p_last - p_first;
- int parent = (len - 2)/2;
+ int parent = (len - 2) / 2;
while (true) {
adjust_heap(p_first, parent, len, p_array[p_first + parent], p_array);
@@ -149,174 +143,163 @@ public:
}
}
- inline void partial_sort(int p_first,int p_last,int p_middle,T* p_array) const {
+ inline void partial_sort(int p_first, int p_last, int p_middle, T *p_array) const {
- make_heap(p_first,p_middle,p_array);
- for(int i=p_middle;i<p_last;i++)
- if (compare( p_array[i],p_array[p_first]))
- pop_heap(p_first,p_middle,i,p_array[i],p_array);
- sort_heap(p_first,p_middle,p_array);
+ make_heap(p_first, p_middle, p_array);
+ for (int i = p_middle; i < p_last; i++)
+ if (compare(p_array[i], p_array[p_first]))
+ pop_heap(p_first, p_middle, i, p_array[i], p_array);
+ sort_heap(p_first, p_middle, p_array);
}
- inline void partial_select(int p_first,int p_last,int p_middle,T* p_array) const {
+ inline void partial_select(int p_first, int p_last, int p_middle, T *p_array) const {
- make_heap(p_first,p_middle,p_array);
- for(int i=p_middle;i<p_last;i++)
- if (compare( p_array[i],p_array[p_first]))
- pop_heap(p_first,p_middle,i,p_array[i],p_array);
+ make_heap(p_first, p_middle, p_array);
+ for (int i = p_middle; i < p_last; i++)
+ if (compare(p_array[i], p_array[p_first]))
+ pop_heap(p_first, p_middle, i, p_array[i], p_array);
}
- inline int partitioner(int p_first, int p_last, T p_pivot, T* p_array) const {
+ inline int partitioner(int p_first, int p_last, T p_pivot, T *p_array) const {
while (true) {
- while (compare(p_array[p_first],p_pivot))
+ while (compare(p_array[p_first], p_pivot))
p_first++;
p_last--;
- while (compare(p_pivot,p_array[p_last]))
+ while (compare(p_pivot, p_array[p_last]))
p_last--;
if (!(p_first < p_last))
return p_first;
- SWAP(p_array[p_first],p_array[p_last]);
+ SWAP(p_array[p_first], p_array[p_last]);
p_first++;
}
}
- inline void introsort(int p_first, int p_last, T* p_array, int p_max_depth) const {
+ inline void introsort(int p_first, int p_last, T *p_array, int p_max_depth) const {
- while( p_last - p_first > INTROSORT_TRESHOLD ) {
+ while (p_last - p_first > INTROSORT_TRESHOLD) {
if (p_max_depth == 0) {
- partial_sort(p_first,p_last,p_last,p_array);
+ partial_sort(p_first, p_last, p_last, p_array);
return;
}
p_max_depth--;
int cut = partitioner(
- p_first,
- p_last,
- median_of_3(
- p_array[p_first],
- p_array[p_first + (p_last-p_first)/2],
- p_array[p_last-1]
- ),
- p_array
- );
-
- introsort(cut,p_last,p_array,p_max_depth);
- p_last=cut;
-
+ p_first,
+ p_last,
+ median_of_3(
+ p_array[p_first],
+ p_array[p_first + (p_last - p_first) / 2],
+ p_array[p_last - 1]),
+ p_array);
+
+ introsort(cut, p_last, p_array, p_max_depth);
+ p_last = cut;
}
- }
+ }
- inline void introselect(int p_first, int p_nth, int p_last, T* p_array, int p_max_depth) const {
+ inline void introselect(int p_first, int p_nth, int p_last, T *p_array, int p_max_depth) const {
- while( p_last - p_first > 3 ) {
+ while (p_last - p_first > 3) {
if (p_max_depth == 0) {
- partial_select(p_first,p_nth+1,p_last,p_array);
- SWAP(p_first,p_nth);
+ partial_select(p_first, p_nth + 1, p_last, p_array);
+ SWAP(p_first, p_nth);
return;
}
p_max_depth--;
int cut = partitioner(
- p_first,
- p_last,
- median_of_3(
- p_array[p_first],
- p_array[p_first + (p_last-p_first)/2],
- p_array[p_last-1]
- ),
- p_array
- );
-
- if (cut<=p_nth)
- p_first=cut;
+ p_first,
+ p_last,
+ median_of_3(
+ p_array[p_first],
+ p_array[p_first + (p_last - p_first) / 2],
+ p_array[p_last - 1]),
+ p_array);
+
+ if (cut <= p_nth)
+ p_first = cut;
else
- p_last=cut;
-
+ p_last = cut;
}
- insertion_sort(p_first,p_last,p_array);
+ insertion_sort(p_first, p_last, p_array);
}
- inline void unguarded_linear_insert(int p_last,T p_value,T* p_array) const {
+ inline void unguarded_linear_insert(int p_last, T p_value, T *p_array) const {
- int next = p_last-1;
- while (compare(p_value,p_array[next])) {
- p_array[p_last]=p_array[next];
+ int next = p_last - 1;
+ while (compare(p_value, p_array[next])) {
+ p_array[p_last] = p_array[next];
p_last = next;
next--;
}
p_array[p_last] = p_value;
}
- inline void linear_insert(int p_first,int p_last,T*p_array) const {
+ inline void linear_insert(int p_first, int p_last, T *p_array) const {
T val = p_array[p_last];
if (compare(val, p_array[p_first])) {
- for (int i=p_last; i>p_first; i--)
- p_array[i]=p_array[i-1];
+ for (int i = p_last; i > p_first; i--)
+ p_array[i] = p_array[i - 1];
p_array[p_first] = val;
} else
unguarded_linear_insert(p_last, val, p_array);
}
- inline void insertion_sort(int p_first,int p_last,T* p_array) const {
+ inline void insertion_sort(int p_first, int p_last, T *p_array) const {
- if (p_first==p_last)
+ if (p_first == p_last)
return;
- for (int i=p_first+1; i!=p_last ; i++)
- linear_insert(p_first,i,p_array);
+ for (int i = p_first + 1; i != p_last; i++)
+ linear_insert(p_first, i, p_array);
}
- inline void unguarded_insertion_sort(int p_first,int p_last,T* p_array) const {
+ inline void unguarded_insertion_sort(int p_first, int p_last, T *p_array) const {
- for (int i=p_first; i!=p_last ; i++)
- unguarded_linear_insert(i,p_array[i],p_array);
+ for (int i = p_first; i != p_last; i++)
+ unguarded_linear_insert(i, p_array[i], p_array);
}
- inline void final_insertion_sort(int p_first,int p_last,T* p_array) const {
+ inline void final_insertion_sort(int p_first, int p_last, T *p_array) const {
if (p_last - p_first > INTROSORT_TRESHOLD) {
- insertion_sort(p_first,p_first+INTROSORT_TRESHOLD,p_array);
- unguarded_insertion_sort(p_first+INTROSORT_TRESHOLD,p_last,p_array);
+ insertion_sort(p_first, p_first + INTROSORT_TRESHOLD, p_array);
+ unguarded_insertion_sort(p_first + INTROSORT_TRESHOLD, p_last, p_array);
} else {
- insertion_sort(p_first,p_last,p_array);
-
+ insertion_sort(p_first, p_last, p_array);
}
- }
+ }
- inline void sort_range(int p_first, int p_last,T* p_array) const {
+ inline void sort_range(int p_first, int p_last, T *p_array) const {
if (p_first != p_last) {
- introsort(p_first, p_last,p_array,bitlog(p_last - p_first) * 2);
+ introsort(p_first, p_last, p_array, bitlog(p_last - p_first) * 2);
final_insertion_sort(p_first, p_last, p_array);
}
}
- inline void sort(T* p_array,int p_len) const {
+ inline void sort(T *p_array, int p_len) const {
- sort_range(0,p_len,p_array);
+ sort_range(0, p_len, p_array);
}
- inline void nth_element(int p_first,int p_last,int p_nth,T* p_array) const {
+ inline void nth_element(int p_first, int p_last, int p_nth, T *p_array) const {
- if (p_first==p_last || p_nth==p_last)
+ if (p_first == p_last || p_nth == p_last)
return;
- introselect(p_first,p_nth,p_last,p_array,bitlog(p_last - p_first) * 2);
+ introselect(p_first, p_nth, p_last, p_array, bitlog(p_last - p_first) * 2);
}
-
};
-
-
-
#endif
diff --git a/core/string_db.cpp b/core/string_db.cpp
index 004b07b9e5..54535fa06b 100644
--- a/core/string_db.cpp
+++ b/core/string_db.cpp
@@ -28,61 +28,63 @@
/*************************************************************************/
#include "string_db.h"
-#include "print_string.h"
#include "os/os.h"
+#include "print_string.h"
StaticCString StaticCString::create(const char *p_ptr) {
- StaticCString scs; scs.ptr=p_ptr; return scs;
+ StaticCString scs;
+ scs.ptr = p_ptr;
+ return scs;
}
StringName::_Data *StringName::_table[STRING_TABLE_LEN];
StringName _scs_create(const char *p_chr) {
- return (p_chr[0]?StringName(StaticCString::create(p_chr)):StringName());
+ return (p_chr[0] ? StringName(StaticCString::create(p_chr)) : StringName());
}
-bool StringName::configured=false;
-Mutex* StringName::lock=NULL;
+bool StringName::configured = false;
+Mutex *StringName::lock = NULL;
void StringName::setup() {
lock = Mutex::create();
ERR_FAIL_COND(configured);
- for(int i=0;i<STRING_TABLE_LEN;i++) {
+ for (int i = 0; i < STRING_TABLE_LEN; i++) {
- _table[i]=NULL;
+ _table[i] = NULL;
}
- configured=true;
+ configured = true;
}
void StringName::cleanup() {
lock->lock();
- int lost_strings=0;
- for(int i=0;i<STRING_TABLE_LEN;i++) {
+ int lost_strings = 0;
+ for (int i = 0; i < STRING_TABLE_LEN; i++) {
- while(_table[i]) {
+ while (_table[i]) {
- _Data*d=_table[i];
+ _Data *d = _table[i];
lost_strings++;
if (OS::get_singleton()->is_stdout_verbose()) {
if (d->cname) {
- print_line("Orphan StringName: "+String(d->cname));
+ print_line("Orphan StringName: " + String(d->cname));
} else {
- print_line("Orphan StringName: "+String(d->name));
+ print_line("Orphan StringName: " + String(d->name));
}
}
- _table[i]=_table[i]->next;
+ _table[i] = _table[i]->next;
memdelete(d);
}
}
if (OS::get_singleton()->is_stdout_verbose() && lost_strings) {
- print_line("StringName: "+itos(lost_strings)+" unclaimed string names at exit.");
+ print_line("StringName: " + itos(lost_strings) + " unclaimed string names at exit.");
}
lock->unlock();
@@ -98,65 +100,59 @@ void StringName::unref() {
lock->lock();
if (_data->prev) {
- _data->prev->next=_data->next;
+ _data->prev->next = _data->next;
} else {
- if (_table[_data->idx]!=_data) {
+ if (_table[_data->idx] != _data) {
ERR_PRINT("BUG!");
}
- _table[_data->idx]=_data->next;
+ _table[_data->idx] = _data->next;
}
if (_data->next) {
- _data->next->prev=_data->prev;
-
+ _data->next->prev = _data->prev;
}
memdelete(_data);
lock->unlock();
}
- _data=NULL;
-
+ _data = NULL;
}
-bool StringName::operator==(const String& p_name) const {
+bool StringName::operator==(const String &p_name) const {
if (!_data) {
- return (p_name.length()==0);
+ return (p_name.length() == 0);
}
- return (_data->get_name()==p_name);
+ return (_data->get_name() == p_name);
}
-bool StringName::operator==(const char* p_name) const {
+bool StringName::operator==(const char *p_name) const {
if (!_data) {
- return (p_name[0]==0);
+ return (p_name[0] == 0);
}
- return (_data->get_name()==p_name);
+ return (_data->get_name() == p_name);
}
-bool StringName::operator!=(const String& p_name) const {
+bool StringName::operator!=(const String &p_name) const {
return !(operator==(p_name));
}
-
-
-bool StringName::operator!=(const StringName& p_name) const {
+bool StringName::operator!=(const StringName &p_name) const {
// the real magic of all this mess happens here.
// this is why path comparisons are very fast
- return _data!=p_name._data;
-
+ return _data != p_name._data;
}
+void StringName::operator=(const StringName &p_name) {
-void StringName::operator=(const StringName& p_name) {
-
- if (this==&p_name)
+ if (this == &p_name)
return;
unref();
@@ -175,10 +171,10 @@ StringName::operator String() const {
return "";
}
*/
-StringName::StringName(const StringName& p_name) {
+StringName::StringName(const StringName &p_name) {
ERR_FAIL_COND(!configured);
- _data=NULL;
+ _data = NULL;
if (p_name._data && p_name._data->refcount.ref()) {
_data = p_name._data;
@@ -187,168 +183,154 @@ StringName::StringName(const StringName& p_name) {
StringName::StringName(const char *p_name) {
- _data=NULL;
+ _data = NULL;
ERR_FAIL_COND(!configured);
- if (!p_name || p_name[0]==0)
+ if (!p_name || p_name[0] == 0)
return; //empty, ignore
lock->lock();
uint32_t hash = String::hash(p_name);
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _data=_table[idx];
+ _data = _table[idx];
- while(_data) {
+ while (_data) {
// compare hash first
- if (_data->hash==hash && _data->get_name()==p_name)
+ if (_data->hash == hash && _data->get_name() == p_name)
break;
- _data=_data->next;
+ _data = _data->next;
}
-
if (_data) {
if (_data->refcount.ref()) {
// exists
lock->unlock();
return;
} else {
-
}
}
- _data = memnew( _Data );
- _data->name=p_name;
+ _data = memnew(_Data);
+ _data->name = p_name;
_data->refcount.init();
- _data->hash=hash;
- _data->idx=idx;
- _data->cname=NULL;
- _data->next=_table[idx];
- _data->prev=NULL;
+ _data->hash = hash;
+ _data->idx = idx;
+ _data->cname = NULL;
+ _data->next = _table[idx];
+ _data->prev = NULL;
if (_table[idx])
- _table[idx]->prev=_data;
- _table[idx]=_data;
-
+ _table[idx]->prev = _data;
+ _table[idx] = _data;
lock->unlock();
}
-StringName::StringName(const StaticCString& p_static_string) {
+StringName::StringName(const StaticCString &p_static_string) {
- _data=NULL;
+ _data = NULL;
ERR_FAIL_COND(!configured);
- ERR_FAIL_COND( !p_static_string.ptr || !p_static_string.ptr[0]);
+ ERR_FAIL_COND(!p_static_string.ptr || !p_static_string.ptr[0]);
lock->lock();
uint32_t hash = String::hash(p_static_string.ptr);
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _data=_table[idx];
+ _data = _table[idx];
- while(_data) {
+ while (_data) {
// compare hash first
- if (_data->hash==hash && _data->get_name()==p_static_string.ptr)
+ if (_data->hash == hash && _data->get_name() == p_static_string.ptr)
break;
- _data=_data->next;
+ _data = _data->next;
}
-
if (_data) {
if (_data->refcount.ref()) {
// exists
lock->unlock();
return;
} else {
-
}
}
- _data = memnew( _Data );
+ _data = memnew(_Data);
_data->refcount.init();
- _data->hash=hash;
- _data->idx=idx;
- _data->cname=p_static_string.ptr;
- _data->next=_table[idx];
- _data->prev=NULL;
+ _data->hash = hash;
+ _data->idx = idx;
+ _data->cname = p_static_string.ptr;
+ _data->next = _table[idx];
+ _data->prev = NULL;
if (_table[idx])
- _table[idx]->prev=_data;
- _table[idx]=_data;
-
+ _table[idx]->prev = _data;
+ _table[idx] = _data;
lock->unlock();
-
-
}
+StringName::StringName(const String &p_name) {
-StringName::StringName(const String& p_name) {
-
- _data=NULL;
+ _data = NULL;
ERR_FAIL_COND(!configured);
- if (p_name==String())
+ if (p_name == String())
return;
lock->lock();
uint32_t hash = p_name.hash();
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _data=_table[idx];
+ _data = _table[idx];
- while(_data) {
+ while (_data) {
- if (_data->hash==hash && _data->get_name()==p_name)
+ if (_data->hash == hash && _data->get_name() == p_name)
break;
- _data=_data->next;
+ _data = _data->next;
}
-
if (_data) {
if (_data->refcount.ref()) {
// exists
lock->unlock();
return;
} else {
-
-
}
}
-
- _data = memnew( _Data );
- _data->name=p_name;
+ _data = memnew(_Data);
+ _data->name = p_name;
_data->refcount.init();
- _data->hash=hash;
- _data->idx=idx;
- _data->cname=NULL;
- _data->next=_table[idx];
- _data->prev=NULL;
+ _data->hash = hash;
+ _data->idx = idx;
+ _data->cname = NULL;
+ _data->next = _table[idx];
+ _data->prev = NULL;
if (_table[idx])
- _table[idx]->prev=_data;
- _table[idx]=_data;
+ _table[idx]->prev = _data;
+ _table[idx] = _data;
lock->unlock();
-
}
StringName StringName::search(const char *p_name) {
- ERR_FAIL_COND_V(!configured,StringName());
+ ERR_FAIL_COND_V(!configured, StringName());
- ERR_FAIL_COND_V( !p_name, StringName() );
+ ERR_FAIL_COND_V(!p_name, StringName());
if (!p_name[0])
return StringName();
@@ -356,36 +338,33 @@ StringName StringName::search(const char *p_name) {
uint32_t hash = String::hash(p_name);
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _Data *_data=_table[idx];
+ _Data *_data = _table[idx];
- while(_data) {
+ while (_data) {
// compare hash first
- if (_data->hash==hash && _data->get_name()==p_name)
+ if (_data->hash == hash && _data->get_name() == p_name)
break;
- _data=_data->next;
+ _data = _data->next;
}
if (_data && _data->refcount.ref()) {
lock->unlock();
return StringName(_data);
-
}
lock->unlock();
return StringName(); //does not exist
-
-
}
StringName StringName::search(const CharType *p_name) {
- ERR_FAIL_COND_V(!configured,StringName());
+ ERR_FAIL_COND_V(!configured, StringName());
- ERR_FAIL_COND_V( !p_name, StringName() );
+ ERR_FAIL_COND_V(!p_name, StringName());
if (!p_name[0])
return StringName();
@@ -393,67 +372,61 @@ StringName StringName::search(const CharType *p_name) {
uint32_t hash = String::hash(p_name);
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _Data *_data=_table[idx];
+ _Data *_data = _table[idx];
- while(_data) {
+ while (_data) {
// compare hash first
- if (_data->hash==hash && _data->get_name()==p_name)
+ if (_data->hash == hash && _data->get_name() == p_name)
break;
- _data=_data->next;
+ _data = _data->next;
}
if (_data && _data->refcount.ref()) {
lock->unlock();
return StringName(_data);
-
}
lock->unlock();
return StringName(); //does not exist
-
}
StringName StringName::search(const String &p_name) {
- ERR_FAIL_COND_V( p_name=="", StringName() );
+ ERR_FAIL_COND_V(p_name == "", StringName());
lock->lock();
uint32_t hash = p_name.hash();
- uint32_t idx=hash&STRING_TABLE_MASK;
+ uint32_t idx = hash & STRING_TABLE_MASK;
- _Data *_data=_table[idx];
+ _Data *_data = _table[idx];
- while(_data) {
+ while (_data) {
// compare hash first
- if (_data->hash==hash && p_name==_data->get_name())
+ if (_data->hash == hash && p_name == _data->get_name())
break;
- _data=_data->next;
+ _data = _data->next;
}
if (_data && _data->refcount.ref()) {
lock->unlock();
return StringName(_data);
-
}
lock->unlock();
return StringName(); //does not exist
-
}
-
StringName::StringName() {
- _data=NULL;
+ _data = NULL;
}
StringName::~StringName() {
unref();
}
-
diff --git a/core/string_db.h b/core/string_db.h
index 2c5262adaa..b8f8d6f3dc 100644
--- a/core/string_db.h
+++ b/core/string_db.h
@@ -30,9 +30,9 @@
#define STRING_DB_H
#include "hash_map.h"
-#include "ustring.h"
-#include "safe_refcount.h"
#include "os/mutex.h"
+#include "safe_refcount.h"
+#include "ustring.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -43,32 +43,32 @@ struct StaticCString {
static StaticCString create(const char *p_ptr);
};
-
-
class StringName {
-
enum {
- STRING_TABLE_BITS=12,
- STRING_TABLE_LEN=1<<STRING_TABLE_BITS,
- STRING_TABLE_MASK=STRING_TABLE_LEN-1
+ STRING_TABLE_BITS = 12,
+ STRING_TABLE_LEN = 1 << STRING_TABLE_BITS,
+ STRING_TABLE_MASK = STRING_TABLE_LEN - 1
};
struct _Data {
SafeRefCount refcount;
- const char* cname;
+ const char *cname;
String name;
- String get_name() const { return cname?String(cname):name; }
+ String get_name() const { return cname ? String(cname) : name; }
int idx;
uint32_t hash;
_Data *prev;
_Data *next;
- _Data() { cname=NULL; next=prev=NULL; hash=0; }
+ _Data() {
+ cname = NULL;
+ next = prev = NULL;
+ hash = 0;
+ }
};
-
static _Data *_table[STRING_TABLE_LEN];
_Data *_data;
@@ -80,31 +80,30 @@ class StringName {
};
void unref();
-friend void register_core_types();
-friend void unregister_core_types();
+ friend void register_core_types();
+ friend void unregister_core_types();
static Mutex *lock;
static void setup();
static void cleanup();
static bool configured;
- StringName(_Data *p_data) { _data=p_data; }
-public:
-
+ StringName(_Data *p_data) { _data = p_data; }
- operator const void*() const { return (_data && (_data->cname || !_data->name.empty()))?(void*)1:0; }
+public:
+ operator const void *() const { return (_data && (_data->cname || !_data->name.empty())) ? (void *)1 : 0; }
- bool operator==(const String& p_name) const;
- bool operator==(const char* p_name) const;
- bool operator!=(const String& p_name) const;
- _FORCE_INLINE_ bool operator<(const StringName& p_name) const {
+ bool operator==(const String &p_name) const;
+ bool operator==(const char *p_name) const;
+ bool operator!=(const String &p_name) const;
+ _FORCE_INLINE_ bool operator<(const StringName &p_name) const {
- return _data<p_name._data;
+ return _data < p_name._data;
}
- _FORCE_INLINE_ bool operator==(const StringName& p_name) const {
+ _FORCE_INLINE_ bool operator==(const StringName &p_name) const {
// the real magic of all this mess happens here.
// this is why path comparisons are very fast
- return _data==p_name._data;
+ return _data == p_name._data;
}
_FORCE_INLINE_ uint32_t hash() const {
@@ -113,12 +112,12 @@ public:
else
return 0;
}
- bool operator!=(const StringName& p_name) const;
+ bool operator!=(const StringName &p_name) const;
_FORCE_INLINE_ operator String() const {
if (_data) {
- if (_data->cname )
+ if (_data->cname)
return String(_data->cname);
else
return _data->name;
@@ -133,17 +132,17 @@ public:
struct AlphCompare {
- _FORCE_INLINE_ bool operator()(const StringName& l,const StringName& r) const {
+ _FORCE_INLINE_ bool operator()(const StringName &l, const StringName &r) const {
return l.operator String() < r.operator String();
}
};
- void operator=(const StringName& p_name);
+ void operator=(const StringName &p_name);
StringName(const char *p_name);
- StringName(const StringName& p_name);
- StringName(const String& p_name);
- StringName(const StaticCString& p_static_string);
+ StringName(const StringName &p_name);
+ StringName(const String &p_name);
+ StringName(const StaticCString &p_static_string);
StringName();
~StringName();
};
diff --git a/core/translation.cpp b/core/translation.cpp
index d9d4fe7784..013f46f54f 100644
--- a/core/translation.cpp
+++ b/core/translation.cpp
@@ -32,746 +32,745 @@
#include "io/resource_loader.h"
#include "os/os.h"
-static const char* locale_list[]={
-"aa", // Afar
-"aa_DJ", // Afar (Djibouti)
-"aa_ER", // Afar (Eritrea)
-"aa_ET", // Afar (Ethiopia)
-"af", // Afrikaans
-"af_ZA", // Afrikaans (South Africa)
-"agr_PE", // Aguaruna (Peru)
-"ak_GH", // Akan (Ghana)
-"am_ET", // Amharic (Ethiopia)
-"an_ES", // Aragonese (Spain)
-"anp_IN", // Angika (India)
-"ar", // Arabic
-"ar_AE", // Arabic (United Arab Emirates)
-"ar_BH", // Arabic (Bahrain)
-"ar_DZ", // Arabic (Algeria)
-"ar_EG", // Arabic (Egypt)
-"ar_IN", // Arabic (India)
-"ar_IQ", // Arabic (Iraq)
-"ar_JO", // Arabic (Jordan)
-"ar_KW", // Arabic (Kuwait)
-"ar_LB", // Arabic (Lebanon)
-"ar_LY", // Arabic (Libya)
-"ar_MA", // Arabic (Morocco)
-"ar_OM", // Arabic (Oman)
-"ar_QA", // Arabic (Qatar)
-"ar_SA", // Arabic (Saudi Arabia)
-"ar_SD", // Arabic (Sudan)
-"ar_SS", // Arabic (South Soudan)
-"ar_SY", // Arabic (Syria)
-"ar_TN", // Arabic (Tunisia)
-"ar_YE", // Arabic (Yemen)
-"as_IN", // Assamese (India)
-"ast_ES", // Asturian (Spain)
-"ayc_PE", // Southern Aymara (Peru)
-"ay_PE", // Aymara (Peru)
-"az_AZ", // Azerbaijani (Azerbaijan)
-"be", // Belarusian
-"be_BY", // Belarusian (Belarus)
-"bem_ZM", // Bemba (Zambia)
-"ber_DZ", // Berber languages (Algeria)
-"ber_MA", // Berber languages (Morocco)
-"bg", // Bulgarian
-"bg_BG", // Bulgarian (Bulgaria)
-"bhb_IN", // Bhili (India)
-"bho_IN", // Bhojpuri (India)
-"bi_TV", // Bislama (Tuvalu)
-"bn", // Bengali
-"bn_BD", // Bengali (Bangladesh)
-"bn_IN", // Bengali (India)
-"bo", // Tibetan
-"bo_CN", // Tibetan (China)
-"bo_IN", // Tibetan (India)
-"br_FR", // Breton (France)
-"brx_IN", // Bodo (India)
-"bs_BA", // Bosnian (Bosnia and Herzegovina)
-"byn_ER", // Bilin (Eritrea)
-"ca", // Catalan
-"ca_AD", // Catalan (Andorra)
-"ca_ES", // Catalan (Spain)
-"ca_FR", // Catalan (France)
-"ca_IT", // Catalan (Italy)
-"ce_RU", // Chechen (Russia)
-"chr_US", // Cherokee (United States)
-"cmn_TW", // Mandarin Chinese (Taiwan)
-"crh_UA", // Crimean Tatar (Ukraine)
-"csb_PL", // Kashubian (Poland)
-"cs", // Czech
-"cs_CZ", // Czech (Czech Republic)
-"cv_RU", // Chuvash (Russia)
-"cy_GB", // Welsh (United Kingdom)
-"da", // Danish
-"da_DK", // Danish (Denmark)
-"de", // German
-"de_AT", // German (Austria)
-"de_BE", // German (Belgium)
-"de_CH", // German (Switzerland)
-"de_DE", // German (Germany)
-"de_IT", // German (Italy)
-"de_LU", // German (Luxembourg)
-"doi_IN", // Dogri (India)
-"dv_MV", // Dhivehi (Maldives)
-"dz_BT", // Dzongkha (Bhutan)
-"el", // Greek
-"el_CY", // Greek (Cyprus)
-"el_GR", // Greek (Greece)
-"en", // English
-"en_AG", // English (Antigua and Barbuda)
-"en_AU", // English (Australia)
-"en_BW", // English (Botswana)
-"en_CA", // English (Canada)
-"en_DK", // English (Denmark)
-"en_GB", // English (United Kingdom)
-"en_HK", // English (Hong Kong)
-"en_IE", // English (Ireland)
-"en_IL", // English (Israel)
-"en_IN", // English (India)
-"en_NG", // English (Nigeria)
-"en_NZ", // English (New Zealand)
-"en_PH", // English (Philippines)
-"en_SG", // English (Singapore)
-"en_US", // English (United States)
-"en_ZA", // English (South Africa)
-"en_ZM", // English (Zambia)
-"en_ZW", // English (Zimbabwe)
-"eo", // Esperanto
-"es", // Spanish
-"es_AR", // Spanish (Argentina)
-"es_BO", // Spanish (Bolivia)
-"es_CL", // Spanish (Chile)
-"es_CO", // Spanish (Colombia)
-"es_CR", // Spanish (Costa Rica)
-"es_CU", // Spanish (Cuba)
-"es_DO", // Spanish (Dominican Republic)
-"es_EC", // Spanish (Ecuador)
-"es_ES", // Spanish (Spain)
-"es_GT", // Spanish (Guatemala)
-"es_HN", // Spanish (Honduras)
-"es_MX", // Spanish (Mexico)
-"es_NI", // Spanish (Nicaragua)
-"es_PA", // Spanish (Panama)
-"es_PE", // Spanish (Peru)
-"es_PR", // Spanish (Puerto Rico)
-"es_PY", // Spanish (Paraguay)
-"es_SV", // Spanish (El Salvador)
-"es_US", // Spanish (United States)
-"es_UY", // Spanish (Uruguay)
-"es_VE", // Spanish (Venezuela)
-"et", // Estonian
-"et_EE", // Estonian (Estonia)
-"eu", // Basque
-"eu_ES", // Basque (Spain)
-"fa", // Persian
-"fa_IR", // Persian (Iran)
-"ff_SN", // Fulah (Senegal)
-"fi", // Finnish
-"fi_FI", // Finnish (Finland)
-"fil_PH", // Filipino (Philippines)
-"fo_FO", // Faroese (Faroe Islands)
-"fr", // French
-"fr_BE", // French (Belgium)
-"fr_CA", // French (Canada)
-"fr_CH", // French (Switzerland)
-"fr_FR", // French (France)
-"fr_LU", // French (Luxembourg)
-"fur_IT", // Friulian (Italy)
-"fy_DE", // Western Frisian (Germany)
-"fy_NL", // Western Frisian (Netherlands)
-"ga", // Irish
-"ga_IE", // Irish (Ireland)
-"gd_GB", // Scottish Gaelic (United Kingdom)
-"gez_ER", // Geez (Eritrea)
-"gez_ET", // Geez (Ethiopia)
-"gl_ES", // Galician (Spain)
-"gu_IN", // Gujarati (India)
-"gv_GB", // Manx (United Kingdom)
-"hak_TW", // Hakka Chinese (Taiwan)
-"ha_NG", // Hausa (Nigeria)
-"he", // Hebrew
-"he_IL", // Hebrew (Israel)
-"hi", // Hindi
-"hi_IN", // Hindi (India)
-"hne_IN", // Chhattisgarhi (India)
-"hr", // Croatian
-"hr_HR", // Croatian (Croatia)
-"hsb_DE", // Upper Sorbian (Germany)
-"ht_HT", // Haitian (Haiti)
-"hu", // Hungarian
-"hu_HU", // Hungarian (Hungary)
-"hus_MX", // Huastec (Mexico)
-"hy_AM", // Armenian (Armenia)
-"ia_FR", // Interlingua (France)
-"id", // Indonesian
-"id_ID", // Indonesian (Indonesia)
-"ig_NG", // Igbo (Nigeria)
-"ik_CA", // Inupiaq (Canada)
-"is", // Icelandic
-"is_IS", // Icelandic (Iceland)
-"it", // Italian
-"it_CH", // Italian (Switzerland)
-"it_IT", // Italian (Italy)
-"iu_CA", // Inuktitut (Canada)
-"ja", // Japanese
-"ja_JP", // Japanese (Japan)
-"kab_DZ", // Kabyle (Algeria)
-"ka_GE", // Georgian (Georgia)
-"kk_KZ", // Kazakh (Kazakhstan)
-"kl_GL", // Kalaallisut (Greenland)
-"km_KH", // Central Khmer (Cambodia)
-"kn_IN", // Kannada (India)
-"kok_IN", // Konkani (India)
-"ko", // Korean
-"ko_KR", // Korean (South Korea)
-"ks_IN", // Kashmiri (India)
-"ku", // Kurdish
-"ku_TR", // Kurdish (Turkey)
-"kw_GB", // Cornish (United Kingdom)
-"ky_KG", // Kirghiz (Kyrgyzstan)
-"lb_LU", // Luxembourgish (Luxembourg)
-"lg_UG", // Ganda (Uganda)
-"li_BE", // Limburgan (Belgium)
-"li_NL", // Limburgan (Netherlands)
-"lij_IT", // Ligurian (Italy)
-"ln_CD", // Lingala (Congo)
-"lo_LA", // Lao (Laos)
-"lt", // Lithuanian
-"lt_LT", // Lithuanian (Lithuania)
-"lv", // Latvian
-"lv_LV", // Latvian (Latvia)
-"lzh_TW", // Literary Chinese (Taiwan)
-"mag_IN", // Magahi (India)
-"mai_IN", // Maithili (India)
-"mg_MG", // Malagasy (Madagascar)
-"mh_MH", // Marshallese (Marshall Islands)
-"mhr_RU", // Eastern Mari (Russia)
-"mi_NZ", // Maori (New Zealand)
-"miq_NI", // Mískito (Nicaragua)
-"mk", // Macedonian
-"mk_MK", // Macedonian (Macedonia)
-"ml_IN", // Malayalam (India)
-"mni_IN", // Manipuri (India)
-"mn_MN", // Mongolian (Mongolia)
-"mr_IN", // Marathi (India)
-"ms", // Malay
-"ms_MY", // Malay (Malaysia)
-"mt", // Maltese
-"mt_MT", // Maltese (Malta)
-"my_MM", // Burmese (Myanmar)
-"myv_RU", // Erzya (Russia)
-"nah_MX", // Nahuatl languages (Mexico)
-"nan_TW", // Min Nan Chinese (Taiwan)
-"nb", // Norwegian Bokmål
-"nb_NO", // Norwegian Bokmål (Norway)
-"nds_DE", // Low German (Germany)
-"nds_NL", // Low German (Netherlands)
-"ne_NP", // Nepali (Nepal)
-"nhn_MX", // Central Nahuatl (Mexico)
-"niu_NU", // Niuean (Niue)
-"niu_NZ", // Niuean (New Zealand)
-"nl", // Dutch
-"nl_AW", // Dutch (Aruba)
-"nl_BE", // Dutch (Belgium)
-"nl_NL", // Dutch (Netherlands)
-"nn", // Norwegian Nynorsk
-"nn_NO", // Norwegian Nynorsk (Norway)
-"nr_ZA", // South Ndebele (South Africa)
-"nso_ZA", // Pedi (South Africa)
-"oc_FR", // Occitan (France)
-"om", // Oromo
-"om_ET", // Oromo (Ethiopia)
-"om_KE", // Oromo (Kenya)
-"or_IN", // Oriya (India)
-"os_RU", // Ossetian (Russia)
-"pa_IN", // Panjabi (India)
-"pap", // Papiamento
-"pap_AN", // Papiamento (Netherlands Antilles)
-"pap_AW", // Papiamento (Aruba)
-"pap_CW", // Papiamento (Curaçao)
-"pa_PK", // Panjabi (Pakistan)
-"pl", // Polish
-"pl_PL", // Polish (Poland)
-"pr", // Pirate
-"ps_AF", // Pushto (Afghanistan)
-"pt", // Portuguese
-"pt_BR", // Portuguese (Brazil)
-"pt_PT", // Portuguese (Portugal)
-"quy_PE", // Ayacucho Quechua (Peru)
-"quz_PE", // Cusco Quechua (Peru)
-"raj_IN", // Rajasthani (India)
-"ro", // Romanian
-"ro_RO", // Romanian (Romania)
-"ru", // Russian
-"ru_RU", // Russian (Russia)
-"ru_UA", // Russian (Ukraine)
-"rw_RW", // Kinyarwanda (Rwanda)
-"sa_IN", // Sanskrit (India)
-"sat_IN", // Santali (India)
-"sc_IT", // Sardinian (Italy)
-"sco", // Scots
-"sd_IN", // Sindhi (India)
-"se_NO", // Northern Sami (Norway)
-"sgs_LT", // Samogitian (Lithuania)
-"shs_CA", // Shuswap (Canada)
-"sid_ET", // Sidamo (Ethiopia)
-"si_LK", // Sinhala (Sri Lanka)
-"sk", // Slovak
-"sk_SK", // Slovak (Slovakia)
-"sl", // Slovenian
-"sl_SI", // Slovenian (Slovenia)
-"so", // Somali
-"so_DJ", // Somali (Djibouti)
-"so_ET", // Somali (Ethiopia)
-"so_KE", // Somali (Kenya)
-"so_SO", // Somali (Somalia)
-"son_ML", // Songhai languages (Mali)
-"sq", // Albanian
-"sq_AL", // Albanian (Albania)
-"sq_KV", // Albanian (Kosovo)
-"sq_MK", // Albanian (Macedonia)
-"sr", // Serbian
-"sr_ME", // Serbian (Montenegro)
-"sr_RS", // Serbian (Serbia)
-"ss_ZA", // Swati (South Africa)
-"st_ZA", // Southern Sotho (South Africa)
-"sv", // Swedish
-"sv_FI", // Swedish (Finland)
-"sv_SE", // Swedish (Sweden)
-"sw_KE", // Swahili (Kenya)
-"sw_TZ", // Swahili (Tanzania)
-"szl_PL", // Silesian (Poland)
-"ta", // Tamil
-"ta_IN", // Tamil (India)
-"ta_LK", // Tamil (Sri Lanka)
-"tcy_IN", // Tulu (India)
-"te_IN", // Telugu (India)
-"tg_TJ", // Tajik (Tajikistan)
-"the_NP", // Chitwania Tharu (Nepal)
-"th", // Thai
-"th_TH", // Thai (Thailand)
-"ti", // Tigrinya
-"ti_ER", // Tigrinya (Eritrea)
-"ti_ET", // Tigrinya (Ethiopia)
-"tig_ER", // Tigre (Eritrea)
-"tk_TM", // Turkmen (Turkmenistan)
-"tl_PH", // Tagalog (Philippines)
-"tn_ZA", // Tswana (South Africa)
-"tr", // Turkish
-"tr_CY", // Turkish (Cyprus)
-"tr_TR", // Turkish (Turkey)
-"ts_ZA", // Tsonga (South Africa)
-"tt_RU", // Tatar (Russia)
-"ug_CN", // Uighur (China)
-"uk", // Ukrainian
-"uk_UA", // Ukrainian (Ukraine)
-"unm_US", // Unami (United States)
-"ur", // Urdu
-"ur_IN", // Urdu (India)
-"ur_PK", // Urdu (Pakistan)
-"uz", // Uzbek
-"uz_UZ", // Uzbek (Uzbekistan)
-"ve_ZA", // Venda (South Africa)
-"vi", // Vietnamese
-"vi_VN", // Vietnamese (Vietnam)
-"wa_BE", // Walloon (Belgium)
-"wae_CH", // Walser (Switzerland)
-"wal_ET", // Wolaytta (Ethiopia)
-"wo_SN", // Wolof (Senegal)
-"xh_ZA", // Xhosa (South Africa)
-"yi_US", // Yiddish (United States)
-"yo_NG", // Yoruba (Nigeria)
-"yue_HK", // Yue Chinese (Hong Kong)
-"zh", // Chinese
-"zh_CN", // Chinese (China)
-"zh_HK", // Chinese (Hong Kong)
-"zh_SG", // Chinese (Singapore)
-"zh_TW", // Chinese (Taiwan)
-"zu_ZA", // Zulu (South Africa)
-0
+static const char *locale_list[] = {
+ "aa", // Afar
+ "aa_DJ", // Afar (Djibouti)
+ "aa_ER", // Afar (Eritrea)
+ "aa_ET", // Afar (Ethiopia)
+ "af", // Afrikaans
+ "af_ZA", // Afrikaans (South Africa)
+ "agr_PE", // Aguaruna (Peru)
+ "ak_GH", // Akan (Ghana)
+ "am_ET", // Amharic (Ethiopia)
+ "an_ES", // Aragonese (Spain)
+ "anp_IN", // Angika (India)
+ "ar", // Arabic
+ "ar_AE", // Arabic (United Arab Emirates)
+ "ar_BH", // Arabic (Bahrain)
+ "ar_DZ", // Arabic (Algeria)
+ "ar_EG", // Arabic (Egypt)
+ "ar_IN", // Arabic (India)
+ "ar_IQ", // Arabic (Iraq)
+ "ar_JO", // Arabic (Jordan)
+ "ar_KW", // Arabic (Kuwait)
+ "ar_LB", // Arabic (Lebanon)
+ "ar_LY", // Arabic (Libya)
+ "ar_MA", // Arabic (Morocco)
+ "ar_OM", // Arabic (Oman)
+ "ar_QA", // Arabic (Qatar)
+ "ar_SA", // Arabic (Saudi Arabia)
+ "ar_SD", // Arabic (Sudan)
+ "ar_SS", // Arabic (South Soudan)
+ "ar_SY", // Arabic (Syria)
+ "ar_TN", // Arabic (Tunisia)
+ "ar_YE", // Arabic (Yemen)
+ "as_IN", // Assamese (India)
+ "ast_ES", // Asturian (Spain)
+ "ayc_PE", // Southern Aymara (Peru)
+ "ay_PE", // Aymara (Peru)
+ "az_AZ", // Azerbaijani (Azerbaijan)
+ "be", // Belarusian
+ "be_BY", // Belarusian (Belarus)
+ "bem_ZM", // Bemba (Zambia)
+ "ber_DZ", // Berber languages (Algeria)
+ "ber_MA", // Berber languages (Morocco)
+ "bg", // Bulgarian
+ "bg_BG", // Bulgarian (Bulgaria)
+ "bhb_IN", // Bhili (India)
+ "bho_IN", // Bhojpuri (India)
+ "bi_TV", // Bislama (Tuvalu)
+ "bn", // Bengali
+ "bn_BD", // Bengali (Bangladesh)
+ "bn_IN", // Bengali (India)
+ "bo", // Tibetan
+ "bo_CN", // Tibetan (China)
+ "bo_IN", // Tibetan (India)
+ "br_FR", // Breton (France)
+ "brx_IN", // Bodo (India)
+ "bs_BA", // Bosnian (Bosnia and Herzegovina)
+ "byn_ER", // Bilin (Eritrea)
+ "ca", // Catalan
+ "ca_AD", // Catalan (Andorra)
+ "ca_ES", // Catalan (Spain)
+ "ca_FR", // Catalan (France)
+ "ca_IT", // Catalan (Italy)
+ "ce_RU", // Chechen (Russia)
+ "chr_US", // Cherokee (United States)
+ "cmn_TW", // Mandarin Chinese (Taiwan)
+ "crh_UA", // Crimean Tatar (Ukraine)
+ "csb_PL", // Kashubian (Poland)
+ "cs", // Czech
+ "cs_CZ", // Czech (Czech Republic)
+ "cv_RU", // Chuvash (Russia)
+ "cy_GB", // Welsh (United Kingdom)
+ "da", // Danish
+ "da_DK", // Danish (Denmark)
+ "de", // German
+ "de_AT", // German (Austria)
+ "de_BE", // German (Belgium)
+ "de_CH", // German (Switzerland)
+ "de_DE", // German (Germany)
+ "de_IT", // German (Italy)
+ "de_LU", // German (Luxembourg)
+ "doi_IN", // Dogri (India)
+ "dv_MV", // Dhivehi (Maldives)
+ "dz_BT", // Dzongkha (Bhutan)
+ "el", // Greek
+ "el_CY", // Greek (Cyprus)
+ "el_GR", // Greek (Greece)
+ "en", // English
+ "en_AG", // English (Antigua and Barbuda)
+ "en_AU", // English (Australia)
+ "en_BW", // English (Botswana)
+ "en_CA", // English (Canada)
+ "en_DK", // English (Denmark)
+ "en_GB", // English (United Kingdom)
+ "en_HK", // English (Hong Kong)
+ "en_IE", // English (Ireland)
+ "en_IL", // English (Israel)
+ "en_IN", // English (India)
+ "en_NG", // English (Nigeria)
+ "en_NZ", // English (New Zealand)
+ "en_PH", // English (Philippines)
+ "en_SG", // English (Singapore)
+ "en_US", // English (United States)
+ "en_ZA", // English (South Africa)
+ "en_ZM", // English (Zambia)
+ "en_ZW", // English (Zimbabwe)
+ "eo", // Esperanto
+ "es", // Spanish
+ "es_AR", // Spanish (Argentina)
+ "es_BO", // Spanish (Bolivia)
+ "es_CL", // Spanish (Chile)
+ "es_CO", // Spanish (Colombia)
+ "es_CR", // Spanish (Costa Rica)
+ "es_CU", // Spanish (Cuba)
+ "es_DO", // Spanish (Dominican Republic)
+ "es_EC", // Spanish (Ecuador)
+ "es_ES", // Spanish (Spain)
+ "es_GT", // Spanish (Guatemala)
+ "es_HN", // Spanish (Honduras)
+ "es_MX", // Spanish (Mexico)
+ "es_NI", // Spanish (Nicaragua)
+ "es_PA", // Spanish (Panama)
+ "es_PE", // Spanish (Peru)
+ "es_PR", // Spanish (Puerto Rico)
+ "es_PY", // Spanish (Paraguay)
+ "es_SV", // Spanish (El Salvador)
+ "es_US", // Spanish (United States)
+ "es_UY", // Spanish (Uruguay)
+ "es_VE", // Spanish (Venezuela)
+ "et", // Estonian
+ "et_EE", // Estonian (Estonia)
+ "eu", // Basque
+ "eu_ES", // Basque (Spain)
+ "fa", // Persian
+ "fa_IR", // Persian (Iran)
+ "ff_SN", // Fulah (Senegal)
+ "fi", // Finnish
+ "fi_FI", // Finnish (Finland)
+ "fil_PH", // Filipino (Philippines)
+ "fo_FO", // Faroese (Faroe Islands)
+ "fr", // French
+ "fr_BE", // French (Belgium)
+ "fr_CA", // French (Canada)
+ "fr_CH", // French (Switzerland)
+ "fr_FR", // French (France)
+ "fr_LU", // French (Luxembourg)
+ "fur_IT", // Friulian (Italy)
+ "fy_DE", // Western Frisian (Germany)
+ "fy_NL", // Western Frisian (Netherlands)
+ "ga", // Irish
+ "ga_IE", // Irish (Ireland)
+ "gd_GB", // Scottish Gaelic (United Kingdom)
+ "gez_ER", // Geez (Eritrea)
+ "gez_ET", // Geez (Ethiopia)
+ "gl_ES", // Galician (Spain)
+ "gu_IN", // Gujarati (India)
+ "gv_GB", // Manx (United Kingdom)
+ "hak_TW", // Hakka Chinese (Taiwan)
+ "ha_NG", // Hausa (Nigeria)
+ "he", // Hebrew
+ "he_IL", // Hebrew (Israel)
+ "hi", // Hindi
+ "hi_IN", // Hindi (India)
+ "hne_IN", // Chhattisgarhi (India)
+ "hr", // Croatian
+ "hr_HR", // Croatian (Croatia)
+ "hsb_DE", // Upper Sorbian (Germany)
+ "ht_HT", // Haitian (Haiti)
+ "hu", // Hungarian
+ "hu_HU", // Hungarian (Hungary)
+ "hus_MX", // Huastec (Mexico)
+ "hy_AM", // Armenian (Armenia)
+ "ia_FR", // Interlingua (France)
+ "id", // Indonesian
+ "id_ID", // Indonesian (Indonesia)
+ "ig_NG", // Igbo (Nigeria)
+ "ik_CA", // Inupiaq (Canada)
+ "is", // Icelandic
+ "is_IS", // Icelandic (Iceland)
+ "it", // Italian
+ "it_CH", // Italian (Switzerland)
+ "it_IT", // Italian (Italy)
+ "iu_CA", // Inuktitut (Canada)
+ "ja", // Japanese
+ "ja_JP", // Japanese (Japan)
+ "kab_DZ", // Kabyle (Algeria)
+ "ka_GE", // Georgian (Georgia)
+ "kk_KZ", // Kazakh (Kazakhstan)
+ "kl_GL", // Kalaallisut (Greenland)
+ "km_KH", // Central Khmer (Cambodia)
+ "kn_IN", // Kannada (India)
+ "kok_IN", // Konkani (India)
+ "ko", // Korean
+ "ko_KR", // Korean (South Korea)
+ "ks_IN", // Kashmiri (India)
+ "ku", // Kurdish
+ "ku_TR", // Kurdish (Turkey)
+ "kw_GB", // Cornish (United Kingdom)
+ "ky_KG", // Kirghiz (Kyrgyzstan)
+ "lb_LU", // Luxembourgish (Luxembourg)
+ "lg_UG", // Ganda (Uganda)
+ "li_BE", // Limburgan (Belgium)
+ "li_NL", // Limburgan (Netherlands)
+ "lij_IT", // Ligurian (Italy)
+ "ln_CD", // Lingala (Congo)
+ "lo_LA", // Lao (Laos)
+ "lt", // Lithuanian
+ "lt_LT", // Lithuanian (Lithuania)
+ "lv", // Latvian
+ "lv_LV", // Latvian (Latvia)
+ "lzh_TW", // Literary Chinese (Taiwan)
+ "mag_IN", // Magahi (India)
+ "mai_IN", // Maithili (India)
+ "mg_MG", // Malagasy (Madagascar)
+ "mh_MH", // Marshallese (Marshall Islands)
+ "mhr_RU", // Eastern Mari (Russia)
+ "mi_NZ", // Maori (New Zealand)
+ "miq_NI", // Mískito (Nicaragua)
+ "mk", // Macedonian
+ "mk_MK", // Macedonian (Macedonia)
+ "ml_IN", // Malayalam (India)
+ "mni_IN", // Manipuri (India)
+ "mn_MN", // Mongolian (Mongolia)
+ "mr_IN", // Marathi (India)
+ "ms", // Malay
+ "ms_MY", // Malay (Malaysia)
+ "mt", // Maltese
+ "mt_MT", // Maltese (Malta)
+ "my_MM", // Burmese (Myanmar)
+ "myv_RU", // Erzya (Russia)
+ "nah_MX", // Nahuatl languages (Mexico)
+ "nan_TW", // Min Nan Chinese (Taiwan)
+ "nb", // Norwegian Bokmål
+ "nb_NO", // Norwegian Bokmål (Norway)
+ "nds_DE", // Low German (Germany)
+ "nds_NL", // Low German (Netherlands)
+ "ne_NP", // Nepali (Nepal)
+ "nhn_MX", // Central Nahuatl (Mexico)
+ "niu_NU", // Niuean (Niue)
+ "niu_NZ", // Niuean (New Zealand)
+ "nl", // Dutch
+ "nl_AW", // Dutch (Aruba)
+ "nl_BE", // Dutch (Belgium)
+ "nl_NL", // Dutch (Netherlands)
+ "nn", // Norwegian Nynorsk
+ "nn_NO", // Norwegian Nynorsk (Norway)
+ "nr_ZA", // South Ndebele (South Africa)
+ "nso_ZA", // Pedi (South Africa)
+ "oc_FR", // Occitan (France)
+ "om", // Oromo
+ "om_ET", // Oromo (Ethiopia)
+ "om_KE", // Oromo (Kenya)
+ "or_IN", // Oriya (India)
+ "os_RU", // Ossetian (Russia)
+ "pa_IN", // Panjabi (India)
+ "pap", // Papiamento
+ "pap_AN", // Papiamento (Netherlands Antilles)
+ "pap_AW", // Papiamento (Aruba)
+ "pap_CW", // Papiamento (Curaçao)
+ "pa_PK", // Panjabi (Pakistan)
+ "pl", // Polish
+ "pl_PL", // Polish (Poland)
+ "pr", // Pirate
+ "ps_AF", // Pushto (Afghanistan)
+ "pt", // Portuguese
+ "pt_BR", // Portuguese (Brazil)
+ "pt_PT", // Portuguese (Portugal)
+ "quy_PE", // Ayacucho Quechua (Peru)
+ "quz_PE", // Cusco Quechua (Peru)
+ "raj_IN", // Rajasthani (India)
+ "ro", // Romanian
+ "ro_RO", // Romanian (Romania)
+ "ru", // Russian
+ "ru_RU", // Russian (Russia)
+ "ru_UA", // Russian (Ukraine)
+ "rw_RW", // Kinyarwanda (Rwanda)
+ "sa_IN", // Sanskrit (India)
+ "sat_IN", // Santali (India)
+ "sc_IT", // Sardinian (Italy)
+ "sco", // Scots
+ "sd_IN", // Sindhi (India)
+ "se_NO", // Northern Sami (Norway)
+ "sgs_LT", // Samogitian (Lithuania)
+ "shs_CA", // Shuswap (Canada)
+ "sid_ET", // Sidamo (Ethiopia)
+ "si_LK", // Sinhala (Sri Lanka)
+ "sk", // Slovak
+ "sk_SK", // Slovak (Slovakia)
+ "sl", // Slovenian
+ "sl_SI", // Slovenian (Slovenia)
+ "so", // Somali
+ "so_DJ", // Somali (Djibouti)
+ "so_ET", // Somali (Ethiopia)
+ "so_KE", // Somali (Kenya)
+ "so_SO", // Somali (Somalia)
+ "son_ML", // Songhai languages (Mali)
+ "sq", // Albanian
+ "sq_AL", // Albanian (Albania)
+ "sq_KV", // Albanian (Kosovo)
+ "sq_MK", // Albanian (Macedonia)
+ "sr", // Serbian
+ "sr_ME", // Serbian (Montenegro)
+ "sr_RS", // Serbian (Serbia)
+ "ss_ZA", // Swati (South Africa)
+ "st_ZA", // Southern Sotho (South Africa)
+ "sv", // Swedish
+ "sv_FI", // Swedish (Finland)
+ "sv_SE", // Swedish (Sweden)
+ "sw_KE", // Swahili (Kenya)
+ "sw_TZ", // Swahili (Tanzania)
+ "szl_PL", // Silesian (Poland)
+ "ta", // Tamil
+ "ta_IN", // Tamil (India)
+ "ta_LK", // Tamil (Sri Lanka)
+ "tcy_IN", // Tulu (India)
+ "te_IN", // Telugu (India)
+ "tg_TJ", // Tajik (Tajikistan)
+ "the_NP", // Chitwania Tharu (Nepal)
+ "th", // Thai
+ "th_TH", // Thai (Thailand)
+ "ti", // Tigrinya
+ "ti_ER", // Tigrinya (Eritrea)
+ "ti_ET", // Tigrinya (Ethiopia)
+ "tig_ER", // Tigre (Eritrea)
+ "tk_TM", // Turkmen (Turkmenistan)
+ "tl_PH", // Tagalog (Philippines)
+ "tn_ZA", // Tswana (South Africa)
+ "tr", // Turkish
+ "tr_CY", // Turkish (Cyprus)
+ "tr_TR", // Turkish (Turkey)
+ "ts_ZA", // Tsonga (South Africa)
+ "tt_RU", // Tatar (Russia)
+ "ug_CN", // Uighur (China)
+ "uk", // Ukrainian
+ "uk_UA", // Ukrainian (Ukraine)
+ "unm_US", // Unami (United States)
+ "ur", // Urdu
+ "ur_IN", // Urdu (India)
+ "ur_PK", // Urdu (Pakistan)
+ "uz", // Uzbek
+ "uz_UZ", // Uzbek (Uzbekistan)
+ "ve_ZA", // Venda (South Africa)
+ "vi", // Vietnamese
+ "vi_VN", // Vietnamese (Vietnam)
+ "wa_BE", // Walloon (Belgium)
+ "wae_CH", // Walser (Switzerland)
+ "wal_ET", // Wolaytta (Ethiopia)
+ "wo_SN", // Wolof (Senegal)
+ "xh_ZA", // Xhosa (South Africa)
+ "yi_US", // Yiddish (United States)
+ "yo_NG", // Yoruba (Nigeria)
+ "yue_HK", // Yue Chinese (Hong Kong)
+ "zh", // Chinese
+ "zh_CN", // Chinese (China)
+ "zh_HK", // Chinese (Hong Kong)
+ "zh_SG", // Chinese (Singapore)
+ "zh_TW", // Chinese (Taiwan)
+ "zu_ZA", // Zulu (South Africa)
+ 0
};
-static const char* locale_names[]={
-"Afar",
-"Afar (Djibouti)",
-"Afar (Eritrea)",
-"Afar (Ethiopia)",
-"Afrikaans",
-"Afrikaans (South Africa)",
-"Aguaruna (Peru)",
-"Akan (Ghana)",
-"Amharic (Ethiopia)",
-"Aragonese (Spain)",
-"Angika (India)",
-"Arabic",
-"Arabic (United Arab Emirates)",
-"Arabic (Bahrain)",
-"Arabic (Algeria)",
-"Arabic (Egypt)",
-"Arabic (India)",
-"Arabic (Iraq)",
-"Arabic (Jordan)",
-"Arabic (Kuwait)",
-"Arabic (Lebanon)",
-"Arabic (Libya)",
-"Arabic (Morocco)",
-"Arabic (Oman)",
-"Arabic (Qatar)",
-"Arabic (Saudi Arabia)",
-"Arabic (Sudan)",
-"Arabic (South Soudan)",
-"Arabic (Syria)",
-"Arabic (Tunisia)",
-"Arabic (Yemen)",
-"Assamese (India)",
-"Asturian (Spain)",
-"Southern Aymara (Peru)",
-"Aymara (Peru)",
-"Azerbaijani (Azerbaijan)",
-"Belarusian",
-"Belarusian (Belarus)",
-"Bemba (Zambia)",
-"Berber languages (Algeria)",
-"Berber languages (Morocco)",
-"Bulgarian",
-"Bulgarian (Bulgaria)",
-"Bhili (India)",
-"Bhojpuri (India)",
-"Bislama (Tuvalu)",
-"Bengali",
-"Bengali (Bangladesh)",
-"Bengali (India)",
-"Tibetan",
-"Tibetan (China)",
-"Tibetan (India)",
-"Breton (France)",
-"Bodo (India)",
-"Bosnian (Bosnia and Herzegovina)",
-"Bilin (Eritrea)",
-"Catalan",
-"Catalan (Andorra)",
-"Catalan (Spain)",
-"Catalan (France)",
-"Catalan (Italy)",
-"Chechen (Russia)",
-"Cherokee (United States)",
-"Mandarin Chinese (Taiwan)",
-"Crimean Tatar (Ukraine)",
-"Kashubian (Poland)",
-"Czech",
-"Czech (Czech Republic)",
-"Chuvash (Russia)",
-"Welsh (United Kingdom)",
-"Danish",
-"Danish (Denmark)",
-"German",
-"German (Austria)",
-"German (Belgium)",
-"German (Switzerland)",
-"German (Germany)",
-"German (Italy)",
-"German (Luxembourg)",
-"Dogri (India)",
-"Dhivehi (Maldives)",
-"Dzongkha (Bhutan)",
-"Greek",
-"Greek (Cyprus)",
-"Greek (Greece)",
-"English",
-"English (Antigua and Barbuda)",
-"English (Australia)",
-"English (Botswana)",
-"English (Canada)",
-"English (Denmark)",
-"English (United Kingdom)",
-"English (Hong Kong)",
-"English (Ireland)",
-"English (Israel)",
-"English (India)",
-"English (Nigeria)",
-"English (New Zealand)",
-"English (Philippines)",
-"English (Singapore)",
-"English (United States)",
-"English (South Africa)",
-"English (Zambia)",
-"English (Zimbabwe)",
-"Esperanto",
-"Spanish",
-"Spanish (Argentina)",
-"Spanish (Bolivia)",
-"Spanish (Chile)",
-"Spanish (Colombia)",
-"Spanish (Costa Rica)",
-"Spanish (Cuba)",
-"Spanish (Dominican Republic)",
-"Spanish (Ecuador)",
-"Spanish (Spain)",
-"Spanish (Guatemala)",
-"Spanish (Honduras)",
-"Spanish (Mexico)",
-"Spanish (Nicaragua)",
-"Spanish (Panama)",
-"Spanish (Peru)",
-"Spanish (Puerto Rico)",
-"Spanish (Paraguay)",
-"Spanish (El Salvador)",
-"Spanish (United States)",
-"Spanish (Uruguay)",
-"Spanish (Venezuela)",
-"Estonian",
-"Estonian (Estonia)",
-"Basque",
-"Basque (Spain)",
-"Persian",
-"Persian (Iran)",
-"Fulah (Senegal)",
-"Finnish",
-"Finnish (Finland)",
-"Filipino (Philippines)",
-"Faroese (Faroe Islands)",
-"French",
-"French (Belgium)",
-"French (Canada)",
-"French (Switzerland)",
-"French (France)",
-"French (Luxembourg)",
-"Friulian (Italy)",
-"Western Frisian (Germany)",
-"Western Frisian (Netherlands)",
-"Irish",
-"Irish (Ireland)",
-"Scottish Gaelic (United Kingdom)",
-"Geez (Eritrea)",
-"Geez (Ethiopia)",
-"Galician (Spain)",
-"Gujarati (India)",
-"Manx (United Kingdom)",
-"Hakka Chinese (Taiwan)",
-"Hausa (Nigeria)",
-"Hebrew",
-"Hebrew (Israel)",
-"Hindi",
-"Hindi (India)",
-"Chhattisgarhi (India)",
-"Croatian",
-"Croatian (Croatia)",
-"Upper Sorbian (Germany)",
-"Haitian (Haiti)",
-"Hungarian",
-"Hungarian (Hungary)",
-"Huastec (Mexico)",
-"Armenian (Armenia)",
-"Interlingua (France)",
-"Indonesian",
-"Indonesian (Indonesia)",
-"Igbo (Nigeria)",
-"Inupiaq (Canada)",
-"Icelandic",
-"Icelandic (Iceland)",
-"Italian",
-"Italian (Switzerland)",
-"Italian (Italy)",
-"Inuktitut (Canada)",
-"Japanese",
-"Japanese (Japan)",
-"Kabyle (Algeria)",
-"Georgian (Georgia)",
-"Kazakh (Kazakhstan)",
-"Kalaallisut (Greenland)",
-"Central Khmer (Cambodia)",
-"Kannada (India)",
-"Konkani (India)",
-"Korean",
-"Korean (South Korea)",
-"Kashmiri (India)",
-"Kurdish",
-"Kurdish (Turkey)",
-"Cornish (United Kingdom)",
-"Kirghiz (Kyrgyzstan)",
-"Luxembourgish (Luxembourg)",
-"Ganda (Uganda)",
-"Limburgan (Belgium)",
-"Limburgan (Netherlands)",
-"Ligurian (Italy)",
-"Lingala (Congo)",
-"Lao (Laos)",
-"Lithuanian",
-"Lithuanian (Lithuania)",
-"Latvian",
-"Latvian (Latvia)",
-"Literary Chinese (Taiwan)",
-"Magahi (India)",
-"Maithili (India)",
-"Malagasy (Madagascar)",
-"Marshallese (Marshall Islands)",
-"Eastern Mari (Russia)",
-"Maori (New Zealand)",
-"Mískito (Nicaragua)",
-"Macedonian",
-"Macedonian (Macedonia)",
-"Malayalam (India)",
-"Manipuri (India)",
-"Mongolian (Mongolia)",
-"Marathi (India)",
-"Malay",
-"Malay (Malaysia)",
-"Maltese",
-"Maltese (Malta)",
-"Burmese (Myanmar)",
-"Erzya (Russia)",
-"Nahuatl languages (Mexico)",
-"Min Nan Chinese (Taiwan)",
-"Norwegian Bokmål",
-"Norwegian Bokmål (Norway)",
-"Low German (Germany)",
-"Low German (Netherlands)",
-"Nepali (Nepal)",
-"Central Nahuatl (Mexico)",
-"Niuean (Niue)",
-"Niuean (New Zealand)",
-"Dutch",
-"Dutch (Aruba)",
-"Dutch (Belgium)",
-"Dutch (Netherlands)",
-"Norwegian Nynorsk",
-"Norwegian Nynorsk (Norway)",
-"South Ndebele (South Africa)",
-"Pedi (South Africa)",
-"Occitan (France)",
-"Oromo",
-"Oromo (Ethiopia)",
-"Oromo (Kenya)",
-"Oriya (India)",
-"Ossetian (Russia)",
-"Panjabi (India)",
-"Papiamento",
-"Papiamento (Netherlands Antilles)",
-"Papiamento (Aruba)",
-"Papiamento (Curaçao)",
-"Panjabi (Pakistan)",
-"Polish",
-"Polish (Poland)",
-"Pirate",
-"Pushto (Afghanistan)",
-"Portuguese",
-"Portuguese (Brazil)",
-"Portuguese (Portugal)",
-"Ayacucho Quechua (Peru)",
-"Cusco Quechua (Peru)",
-"Rajasthani (India)",
-"Romanian",
-"Romanian (Romania)",
-"Russian",
-"Russian (Russia)",
-"Russian (Ukraine)",
-"Kinyarwanda (Rwanda)",
-"Sanskrit (India)",
-"Santali (India)",
-"Sardinian (Italy)",
-"Scots (Scotland)",
-"Sindhi (India)",
-"Northern Sami (Norway)",
-"Samogitian (Lithuania)",
-"Shuswap (Canada)",
-"Sidamo (Ethiopia)",
-"Sinhala (Sri Lanka)",
-"Slovak",
-"Slovak (Slovakia)",
-"Slovenian",
-"Slovenian (Slovenia)",
-"Somali",
-"Somali (Djibouti)",
-"Somali (Ethiopia)",
-"Somali (Kenya)",
-"Somali (Somalia)",
-"Songhai languages (Mali)",
-"Albanian",
-"Albanian (Albania)",
-"Albanian (Kosovo)",
-"Albanian (Macedonia)",
-"Serbian",
-"Serbian (Montenegro)",
-"Serbian (Serbia)",
-"Swati (South Africa)",
-"Southern Sotho (South Africa)",
-"Swedish",
-"Swedish (Finland)",
-"Swedish (Sweden)",
-"Swahili (Kenya)",
-"Swahili (Tanzania)",
-"Silesian (Poland)",
-"Tamil",
-"Tamil (India)",
-"Tamil (Sri Lanka)",
-"Tulu (India)",
-"Telugu (India)",
-"Tajik (Tajikistan)",
-"Chitwania Tharu (Nepal)",
-"Thai",
-"Thai (Thailand)",
-"Tigrinya",
-"Tigrinya (Eritrea)",
-"Tigrinya (Ethiopia)",
-"Tigre (Eritrea)",
-"Turkmen (Turkmenistan)",
-"Tagalog (Philippines)",
-"Tswana (South Africa)",
-"Turkish",
-"Turkish (Cyprus)",
-"Turkish (Turkey)",
-"Tsonga (South Africa)",
-"Tatar (Russia)",
-"Uighur (China)",
-"Ukrainian",
-"Ukrainian (Ukraine)",
-"Unami (United States)",
-"Urdu",
-"Urdu (India)",
-"Urdu (Pakistan)",
-"Uzbek",
-"Uzbek (Uzbekistan)",
-"Venda (South Africa)",
-"Vietnamese",
-"Vietnamese (Vietnam)",
-"Walloon (Belgium)",
-"Walser (Switzerland)",
-"Wolaytta (Ethiopia)",
-"Wolof (Senegal)",
-"Xhosa (South Africa)",
-"Yiddish (United States)",
-"Yoruba (Nigeria)",
-"Yue Chinese (Hong Kong)",
-"Chinese",
-"Chinese (China)",
-"Chinese (Hong Kong)",
-"Chinese (Singapore)",
-"Chinese (Taiwan)",
-"Zulu (South Africa)",
-0
+static const char *locale_names[] = {
+ "Afar",
+ "Afar (Djibouti)",
+ "Afar (Eritrea)",
+ "Afar (Ethiopia)",
+ "Afrikaans",
+ "Afrikaans (South Africa)",
+ "Aguaruna (Peru)",
+ "Akan (Ghana)",
+ "Amharic (Ethiopia)",
+ "Aragonese (Spain)",
+ "Angika (India)",
+ "Arabic",
+ "Arabic (United Arab Emirates)",
+ "Arabic (Bahrain)",
+ "Arabic (Algeria)",
+ "Arabic (Egypt)",
+ "Arabic (India)",
+ "Arabic (Iraq)",
+ "Arabic (Jordan)",
+ "Arabic (Kuwait)",
+ "Arabic (Lebanon)",
+ "Arabic (Libya)",
+ "Arabic (Morocco)",
+ "Arabic (Oman)",
+ "Arabic (Qatar)",
+ "Arabic (Saudi Arabia)",
+ "Arabic (Sudan)",
+ "Arabic (South Soudan)",
+ "Arabic (Syria)",
+ "Arabic (Tunisia)",
+ "Arabic (Yemen)",
+ "Assamese (India)",
+ "Asturian (Spain)",
+ "Southern Aymara (Peru)",
+ "Aymara (Peru)",
+ "Azerbaijani (Azerbaijan)",
+ "Belarusian",
+ "Belarusian (Belarus)",
+ "Bemba (Zambia)",
+ "Berber languages (Algeria)",
+ "Berber languages (Morocco)",
+ "Bulgarian",
+ "Bulgarian (Bulgaria)",
+ "Bhili (India)",
+ "Bhojpuri (India)",
+ "Bislama (Tuvalu)",
+ "Bengali",
+ "Bengali (Bangladesh)",
+ "Bengali (India)",
+ "Tibetan",
+ "Tibetan (China)",
+ "Tibetan (India)",
+ "Breton (France)",
+ "Bodo (India)",
+ "Bosnian (Bosnia and Herzegovina)",
+ "Bilin (Eritrea)",
+ "Catalan",
+ "Catalan (Andorra)",
+ "Catalan (Spain)",
+ "Catalan (France)",
+ "Catalan (Italy)",
+ "Chechen (Russia)",
+ "Cherokee (United States)",
+ "Mandarin Chinese (Taiwan)",
+ "Crimean Tatar (Ukraine)",
+ "Kashubian (Poland)",
+ "Czech",
+ "Czech (Czech Republic)",
+ "Chuvash (Russia)",
+ "Welsh (United Kingdom)",
+ "Danish",
+ "Danish (Denmark)",
+ "German",
+ "German (Austria)",
+ "German (Belgium)",
+ "German (Switzerland)",
+ "German (Germany)",
+ "German (Italy)",
+ "German (Luxembourg)",
+ "Dogri (India)",
+ "Dhivehi (Maldives)",
+ "Dzongkha (Bhutan)",
+ "Greek",
+ "Greek (Cyprus)",
+ "Greek (Greece)",
+ "English",
+ "English (Antigua and Barbuda)",
+ "English (Australia)",
+ "English (Botswana)",
+ "English (Canada)",
+ "English (Denmark)",
+ "English (United Kingdom)",
+ "English (Hong Kong)",
+ "English (Ireland)",
+ "English (Israel)",
+ "English (India)",
+ "English (Nigeria)",
+ "English (New Zealand)",
+ "English (Philippines)",
+ "English (Singapore)",
+ "English (United States)",
+ "English (South Africa)",
+ "English (Zambia)",
+ "English (Zimbabwe)",
+ "Esperanto",
+ "Spanish",
+ "Spanish (Argentina)",
+ "Spanish (Bolivia)",
+ "Spanish (Chile)",
+ "Spanish (Colombia)",
+ "Spanish (Costa Rica)",
+ "Spanish (Cuba)",
+ "Spanish (Dominican Republic)",
+ "Spanish (Ecuador)",
+ "Spanish (Spain)",
+ "Spanish (Guatemala)",
+ "Spanish (Honduras)",
+ "Spanish (Mexico)",
+ "Spanish (Nicaragua)",
+ "Spanish (Panama)",
+ "Spanish (Peru)",
+ "Spanish (Puerto Rico)",
+ "Spanish (Paraguay)",
+ "Spanish (El Salvador)",
+ "Spanish (United States)",
+ "Spanish (Uruguay)",
+ "Spanish (Venezuela)",
+ "Estonian",
+ "Estonian (Estonia)",
+ "Basque",
+ "Basque (Spain)",
+ "Persian",
+ "Persian (Iran)",
+ "Fulah (Senegal)",
+ "Finnish",
+ "Finnish (Finland)",
+ "Filipino (Philippines)",
+ "Faroese (Faroe Islands)",
+ "French",
+ "French (Belgium)",
+ "French (Canada)",
+ "French (Switzerland)",
+ "French (France)",
+ "French (Luxembourg)",
+ "Friulian (Italy)",
+ "Western Frisian (Germany)",
+ "Western Frisian (Netherlands)",
+ "Irish",
+ "Irish (Ireland)",
+ "Scottish Gaelic (United Kingdom)",
+ "Geez (Eritrea)",
+ "Geez (Ethiopia)",
+ "Galician (Spain)",
+ "Gujarati (India)",
+ "Manx (United Kingdom)",
+ "Hakka Chinese (Taiwan)",
+ "Hausa (Nigeria)",
+ "Hebrew",
+ "Hebrew (Israel)",
+ "Hindi",
+ "Hindi (India)",
+ "Chhattisgarhi (India)",
+ "Croatian",
+ "Croatian (Croatia)",
+ "Upper Sorbian (Germany)",
+ "Haitian (Haiti)",
+ "Hungarian",
+ "Hungarian (Hungary)",
+ "Huastec (Mexico)",
+ "Armenian (Armenia)",
+ "Interlingua (France)",
+ "Indonesian",
+ "Indonesian (Indonesia)",
+ "Igbo (Nigeria)",
+ "Inupiaq (Canada)",
+ "Icelandic",
+ "Icelandic (Iceland)",
+ "Italian",
+ "Italian (Switzerland)",
+ "Italian (Italy)",
+ "Inuktitut (Canada)",
+ "Japanese",
+ "Japanese (Japan)",
+ "Kabyle (Algeria)",
+ "Georgian (Georgia)",
+ "Kazakh (Kazakhstan)",
+ "Kalaallisut (Greenland)",
+ "Central Khmer (Cambodia)",
+ "Kannada (India)",
+ "Konkani (India)",
+ "Korean",
+ "Korean (South Korea)",
+ "Kashmiri (India)",
+ "Kurdish",
+ "Kurdish (Turkey)",
+ "Cornish (United Kingdom)",
+ "Kirghiz (Kyrgyzstan)",
+ "Luxembourgish (Luxembourg)",
+ "Ganda (Uganda)",
+ "Limburgan (Belgium)",
+ "Limburgan (Netherlands)",
+ "Ligurian (Italy)",
+ "Lingala (Congo)",
+ "Lao (Laos)",
+ "Lithuanian",
+ "Lithuanian (Lithuania)",
+ "Latvian",
+ "Latvian (Latvia)",
+ "Literary Chinese (Taiwan)",
+ "Magahi (India)",
+ "Maithili (India)",
+ "Malagasy (Madagascar)",
+ "Marshallese (Marshall Islands)",
+ "Eastern Mari (Russia)",
+ "Maori (New Zealand)",
+ "Mískito (Nicaragua)",
+ "Macedonian",
+ "Macedonian (Macedonia)",
+ "Malayalam (India)",
+ "Manipuri (India)",
+ "Mongolian (Mongolia)",
+ "Marathi (India)",
+ "Malay",
+ "Malay (Malaysia)",
+ "Maltese",
+ "Maltese (Malta)",
+ "Burmese (Myanmar)",
+ "Erzya (Russia)",
+ "Nahuatl languages (Mexico)",
+ "Min Nan Chinese (Taiwan)",
+ "Norwegian Bokmål",
+ "Norwegian Bokmål (Norway)",
+ "Low German (Germany)",
+ "Low German (Netherlands)",
+ "Nepali (Nepal)",
+ "Central Nahuatl (Mexico)",
+ "Niuean (Niue)",
+ "Niuean (New Zealand)",
+ "Dutch",
+ "Dutch (Aruba)",
+ "Dutch (Belgium)",
+ "Dutch (Netherlands)",
+ "Norwegian Nynorsk",
+ "Norwegian Nynorsk (Norway)",
+ "South Ndebele (South Africa)",
+ "Pedi (South Africa)",
+ "Occitan (France)",
+ "Oromo",
+ "Oromo (Ethiopia)",
+ "Oromo (Kenya)",
+ "Oriya (India)",
+ "Ossetian (Russia)",
+ "Panjabi (India)",
+ "Papiamento",
+ "Papiamento (Netherlands Antilles)",
+ "Papiamento (Aruba)",
+ "Papiamento (Curaçao)",
+ "Panjabi (Pakistan)",
+ "Polish",
+ "Polish (Poland)",
+ "Pirate",
+ "Pushto (Afghanistan)",
+ "Portuguese",
+ "Portuguese (Brazil)",
+ "Portuguese (Portugal)",
+ "Ayacucho Quechua (Peru)",
+ "Cusco Quechua (Peru)",
+ "Rajasthani (India)",
+ "Romanian",
+ "Romanian (Romania)",
+ "Russian",
+ "Russian (Russia)",
+ "Russian (Ukraine)",
+ "Kinyarwanda (Rwanda)",
+ "Sanskrit (India)",
+ "Santali (India)",
+ "Sardinian (Italy)",
+ "Scots (Scotland)",
+ "Sindhi (India)",
+ "Northern Sami (Norway)",
+ "Samogitian (Lithuania)",
+ "Shuswap (Canada)",
+ "Sidamo (Ethiopia)",
+ "Sinhala (Sri Lanka)",
+ "Slovak",
+ "Slovak (Slovakia)",
+ "Slovenian",
+ "Slovenian (Slovenia)",
+ "Somali",
+ "Somali (Djibouti)",
+ "Somali (Ethiopia)",
+ "Somali (Kenya)",
+ "Somali (Somalia)",
+ "Songhai languages (Mali)",
+ "Albanian",
+ "Albanian (Albania)",
+ "Albanian (Kosovo)",
+ "Albanian (Macedonia)",
+ "Serbian",
+ "Serbian (Montenegro)",
+ "Serbian (Serbia)",
+ "Swati (South Africa)",
+ "Southern Sotho (South Africa)",
+ "Swedish",
+ "Swedish (Finland)",
+ "Swedish (Sweden)",
+ "Swahili (Kenya)",
+ "Swahili (Tanzania)",
+ "Silesian (Poland)",
+ "Tamil",
+ "Tamil (India)",
+ "Tamil (Sri Lanka)",
+ "Tulu (India)",
+ "Telugu (India)",
+ "Tajik (Tajikistan)",
+ "Chitwania Tharu (Nepal)",
+ "Thai",
+ "Thai (Thailand)",
+ "Tigrinya",
+ "Tigrinya (Eritrea)",
+ "Tigrinya (Ethiopia)",
+ "Tigre (Eritrea)",
+ "Turkmen (Turkmenistan)",
+ "Tagalog (Philippines)",
+ "Tswana (South Africa)",
+ "Turkish",
+ "Turkish (Cyprus)",
+ "Turkish (Turkey)",
+ "Tsonga (South Africa)",
+ "Tatar (Russia)",
+ "Uighur (China)",
+ "Ukrainian",
+ "Ukrainian (Ukraine)",
+ "Unami (United States)",
+ "Urdu",
+ "Urdu (India)",
+ "Urdu (Pakistan)",
+ "Uzbek",
+ "Uzbek (Uzbekistan)",
+ "Venda (South Africa)",
+ "Vietnamese",
+ "Vietnamese (Vietnam)",
+ "Walloon (Belgium)",
+ "Walser (Switzerland)",
+ "Wolaytta (Ethiopia)",
+ "Wolof (Senegal)",
+ "Xhosa (South Africa)",
+ "Yiddish (United States)",
+ "Yoruba (Nigeria)",
+ "Yue Chinese (Hong Kong)",
+ "Chinese",
+ "Chinese (China)",
+ "Chinese (Hong Kong)",
+ "Chinese (Singapore)",
+ "Chinese (Taiwan)",
+ "Zulu (South Africa)",
+ 0
};
-bool TranslationServer::is_locale_valid(const String& p_locale) {
+bool TranslationServer::is_locale_valid(const String &p_locale) {
- const char **ptr=locale_list;
+ const char **ptr = locale_list;
while (*ptr) {
- if (*ptr==p_locale)
+ if (*ptr == p_locale)
return true;
ptr++;
}
return false;
-
}
Vector<String> TranslationServer::get_all_locales() {
Vector<String> locales;
- const char **ptr=locale_list;
+ const char **ptr = locale_list;
while (*ptr) {
locales.push_back(*ptr);
@@ -779,14 +778,13 @@ Vector<String> TranslationServer::get_all_locales() {
}
return locales;
-
}
-Vector<String> TranslationServer::get_all_locale_names(){
+Vector<String> TranslationServer::get_all_locale_names() {
Vector<String> locales;
- const char **ptr=locale_names;
+ const char **ptr = locale_names;
while (*ptr) {
locales.push_back(*ptr);
@@ -794,21 +792,19 @@ Vector<String> TranslationServer::get_all_locale_names(){
}
return locales;
-
}
+static String get_trimmed_locale(const String &p_locale) {
-static String get_trimmed_locale(const String& p_locale) {
-
- return p_locale.substr(0,2);
+ return p_locale.substr(0, 2);
}
-static bool is_valid_locale(const String& p_locale) {
+static bool is_valid_locale(const String &p_locale) {
- const char **ptr=locale_list;
+ const char **ptr = locale_list;
while (*ptr) {
- if (p_locale==*ptr)
+ if (p_locale == *ptr)
return true;
ptr++;
}
@@ -819,13 +815,13 @@ static bool is_valid_locale(const String& p_locale) {
PoolVector<String> Translation::_get_messages() const {
PoolVector<String> msgs;
- msgs.resize(translation_map.size()*2);
- int idx=0;
- for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) {
+ msgs.resize(translation_map.size() * 2);
+ int idx = 0;
+ for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) {
- msgs.set(idx+0,E->key());
- msgs.set(idx+1,E->get());
- idx+=2;
+ msgs.set(idx + 0, E->key());
+ msgs.set(idx + 1, E->get());
+ idx += 2;
}
return msgs;
@@ -835,76 +831,70 @@ PoolVector<String> Translation::_get_message_list() const {
PoolVector<String> msgs;
msgs.resize(translation_map.size());
- int idx=0;
- for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) {
- msgs.set(idx,E->key());
- idx+=1;
+ msgs.set(idx, E->key());
+ idx += 1;
}
return msgs;
-
}
-void Translation::_set_messages(const PoolVector<String>& p_messages){
+void Translation::_set_messages(const PoolVector<String> &p_messages) {
- int msg_count=p_messages.size();
- ERR_FAIL_COND(msg_count%2);
+ int msg_count = p_messages.size();
+ ERR_FAIL_COND(msg_count % 2);
PoolVector<String>::Read r = p_messages.read();
- for(int i=0;i<msg_count;i+=2) {
+ for (int i = 0; i < msg_count; i += 2) {
- add_message( r[i+0], r[i+1] );
+ add_message(r[i + 0], r[i + 1]);
}
-
}
-
-void Translation::set_locale(const String& p_locale) {
+void Translation::set_locale(const String &p_locale) {
// replaces '-' with '_' for macOS Sierra-style locales
String univ_locale = p_locale.replace("-", "_");
-
- if(!is_valid_locale(univ_locale)) {
+
+ if (!is_valid_locale(univ_locale)) {
String trimmed_locale = get_trimmed_locale(univ_locale);
-
- ERR_EXPLAIN("Invalid Locale: "+trimmed_locale);
+
+ ERR_EXPLAIN("Invalid Locale: " + trimmed_locale);
ERR_FAIL_COND(!is_valid_locale(trimmed_locale));
-
- locale=trimmed_locale;
- }
- else {
- locale=univ_locale;
+
+ locale = trimmed_locale;
+ } else {
+ locale = univ_locale;
}
}
-void Translation::add_message( const StringName& p_src_text, const StringName& p_xlated_text ) {
-
- translation_map[p_src_text]=p_xlated_text;
+void Translation::add_message(const StringName &p_src_text, const StringName &p_xlated_text) {
+ translation_map[p_src_text] = p_xlated_text;
}
-StringName Translation::get_message(const StringName& p_src_text) const {
+StringName Translation::get_message(const StringName &p_src_text) const {
- const Map<StringName, StringName>::Element *E=translation_map.find(p_src_text);
+ const Map<StringName, StringName>::Element *E = translation_map.find(p_src_text);
if (!E)
return StringName();
return E->get();
}
-void Translation::erase_message(const StringName& p_src_text) {
+void Translation::erase_message(const StringName &p_src_text) {
translation_map.erase(p_src_text);
}
void Translation::get_message_list(List<StringName> *r_messages) const {
- for (const Map<StringName, StringName>::Element *E=translation_map.front();E;E=E->next()) {
+ for (const Map<StringName, StringName>::Element *E = translation_map.front(); E; E = E->next()) {
r_messages->push_back(E->key());
}
-
}
int Translation::get_message_count() const {
@@ -912,48 +902,43 @@ int Translation::get_message_count() const {
return translation_map.size();
};
-
void Translation::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_locale","locale"),&Translation::set_locale);
- ClassDB::bind_method(D_METHOD("get_locale"),&Translation::get_locale);
- ClassDB::bind_method(D_METHOD("add_message","src_message","xlated_message"),&Translation::add_message);
- ClassDB::bind_method(D_METHOD("get_message","src_message"),&Translation::get_message);
- ClassDB::bind_method(D_METHOD("erase_message","src_message"),&Translation::erase_message);
- ClassDB::bind_method(D_METHOD("get_message_list"),&Translation::_get_message_list);
- ClassDB::bind_method(D_METHOD("get_message_count"),&Translation::get_message_count);
- ClassDB::bind_method(D_METHOD("_set_messages"),&Translation::_set_messages);
- ClassDB::bind_method(D_METHOD("_get_messages"),&Translation::_get_messages);
-
- ADD_PROPERTY( PropertyInfo(Variant::POOL_STRING_ARRAY,"messages",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_messages", "_get_messages") ;
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"locale"), "set_locale", "get_locale") ;
+ ClassDB::bind_method(D_METHOD("set_locale", "locale"), &Translation::set_locale);
+ ClassDB::bind_method(D_METHOD("get_locale"), &Translation::get_locale);
+ ClassDB::bind_method(D_METHOD("add_message", "src_message", "xlated_message"), &Translation::add_message);
+ ClassDB::bind_method(D_METHOD("get_message", "src_message"), &Translation::get_message);
+ ClassDB::bind_method(D_METHOD("erase_message", "src_message"), &Translation::erase_message);
+ ClassDB::bind_method(D_METHOD("get_message_list"), &Translation::_get_message_list);
+ ClassDB::bind_method(D_METHOD("get_message_count"), &Translation::get_message_count);
+ ClassDB::bind_method(D_METHOD("_set_messages"), &Translation::_set_messages);
+ ClassDB::bind_method(D_METHOD("_get_messages"), &Translation::_get_messages);
+
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_STRING_ARRAY, "messages", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_messages", "_get_messages");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "locale"), "set_locale", "get_locale");
}
Translation::Translation() {
- locale="en";
+ locale = "en";
}
-
-
///////////////////////////////////////////////
-
-void TranslationServer::set_locale(const String& p_locale) {
+void TranslationServer::set_locale(const String &p_locale) {
// replaces '-' with '_' for macOS Sierra-style locales
String univ_locale = p_locale.replace("-", "_");
-
- if(!is_valid_locale(univ_locale)) {
+
+ if (!is_valid_locale(univ_locale)) {
String trimmed_locale = get_trimmed_locale(univ_locale);
-
- ERR_EXPLAIN("Invalid Locale: "+trimmed_locale);
+
+ ERR_EXPLAIN("Invalid Locale: " + trimmed_locale);
ERR_FAIL_COND(!is_valid_locale(trimmed_locale));
-
- locale=trimmed_locale;
- }
- else {
- locale=univ_locale;
+
+ locale = trimmed_locale;
+ } else {
+ locale = univ_locale;
}
if (OS::get_singleton()->get_main_loop()) {
@@ -964,13 +949,11 @@ void TranslationServer::set_locale(const String& p_locale) {
String TranslationServer::get_locale() const {
return locale;
-
}
void TranslationServer::add_translation(const Ref<Translation> &p_translation) {
translations.insert(p_translation);
-
}
void TranslationServer::remove_translation(const Ref<Translation> &p_translation) {
@@ -982,7 +965,7 @@ void TranslationServer::clear() {
translations.clear();
};
-StringName TranslationServer::translate(const StringName& p_message) const {
+StringName TranslationServer::translate(const StringName &p_message) const {
//translate using locale
@@ -990,93 +973,88 @@ StringName TranslationServer::translate(const StringName& p_message) const {
return p_message;
StringName res;
- bool near_match=false;
- const CharType *lptr=&locale[0];
+ bool near_match = false;
+ const CharType *lptr = &locale[0];
+ for (const Set<Ref<Translation> >::Element *E = translations.front(); E; E = E->next()) {
- for (const Set< Ref<Translation> >::Element *E=translations.front();E;E=E->next()) {
-
- const Ref<Translation>& t = E->get();
+ const Ref<Translation> &t = E->get();
String l = t->get_locale();
- if (lptr[0]!=l[0] || lptr[1]!=l[1])
+ if (lptr[0] != l[0] || lptr[1] != l[1])
continue; // locale not match
//near match
- bool match = (l!=locale);
+ bool match = (l != locale);
if (near_match && !match)
continue; //only near-match once
- StringName r=t->get_message(p_message);
-
+ StringName r = t->get_message(p_message);
if (!r)
continue;
- res=r;
+ res = r;
if (match)
break;
else
- near_match=true;
-
+ near_match = true;
}
if (!res) {
//try again with fallback
- if (fallback.length()>=2) {
+ if (fallback.length() >= 2) {
- const CharType *fptr=&fallback[0];
- bool near_match=false;
- for (const Set< Ref<Translation> >::Element *E=translations.front();E;E=E->next()) {
+ const CharType *fptr = &fallback[0];
+ bool near_match = false;
+ for (const Set<Ref<Translation> >::Element *E = translations.front(); E; E = E->next()) {
- const Ref<Translation>& t = E->get();
+ const Ref<Translation> &t = E->get();
String l = t->get_locale();
- if (fptr[0]!=l[0] || fptr[1]!=l[1])
+ if (fptr[0] != l[0] || fptr[1] != l[1])
continue; // locale not match
//near match
- bool match = (l!=fallback);
+ bool match = (l != fallback);
if (near_match && !match)
continue; //only near-match once
- StringName r=t->get_message(p_message);
+ StringName r = t->get_message(p_message);
if (!r)
continue;
- res=r;
+ res = r;
if (match)
break;
else
- near_match=true;
-
+ near_match = true;
}
}
}
-
if (!res)
return p_message;
return res;
}
-TranslationServer *TranslationServer::singleton=NULL;
+TranslationServer *TranslationServer::singleton = NULL;
-bool TranslationServer::_load_translations(const String& p_from) {
+bool TranslationServer::_load_translations(const String &p_from) {
if (GlobalConfig::get_singleton()->has(p_from)) {
- PoolVector<String> translations=GlobalConfig::get_singleton()->get(p_from);
+ PoolVector<String> translations = GlobalConfig::get_singleton()->get(p_from);
- int tcount=translations.size();
+ int tcount = translations.size();
if (tcount) {
PoolVector<String>::Read r = translations.read();
- for(int i=0;i<tcount;i++) {
+ for (int i = 0; i < tcount; i++) {
//print_line( "Loading translation from " + r[i] );
Ref<Translation> tr = ResourceLoader::load(r[i]);
@@ -1092,36 +1070,35 @@ bool TranslationServer::_load_translations(const String& p_from) {
void TranslationServer::setup() {
- String test = GLOBAL_DEF("locale/test","");
- test=test.strip_edges();
- if (test!="")
- set_locale( test );
+ String test = GLOBAL_DEF("locale/test", "");
+ test = test.strip_edges();
+ if (test != "")
+ set_locale(test);
else
- set_locale( OS::get_singleton()->get_locale() );
- fallback = GLOBAL_DEF("locale/fallback","en");
+ set_locale(OS::get_singleton()->get_locale());
+ fallback = GLOBAL_DEF("locale/fallback", "en");
#ifdef TOOLS_ENABLED
{
- String options="";
- int idx=0;
- while(locale_list[idx]) {
- if (idx>0)
- options+=", ";
- options+=locale_list[idx];
+ String options = "";
+ int idx = 0;
+ while (locale_list[idx]) {
+ if (idx > 0)
+ options += ", ";
+ options += locale_list[idx];
idx++;
}
- GlobalConfig::get_singleton()->set_custom_property_info("locale/fallback",PropertyInfo(Variant::STRING,"locale/fallback",PROPERTY_HINT_ENUM,options));
+ GlobalConfig::get_singleton()->set_custom_property_info("locale/fallback", PropertyInfo(Variant::STRING, "locale/fallback", PROPERTY_HINT_ENUM, options));
}
#endif
//load translations
-
}
-void TranslationServer::set_tool_translation(const Ref<Translation>& p_translation) {
- tool_translation=p_translation;
+void TranslationServer::set_tool_translation(const Ref<Translation> &p_translation) {
+ tool_translation = p_translation;
}
-StringName TranslationServer::tool_translate(const StringName& p_message) const {
+StringName TranslationServer::tool_translate(const StringName &p_message) const {
if (tool_translation.is_valid()) {
StringName r = tool_translation->get_message(p_message);
@@ -1134,19 +1111,17 @@ StringName TranslationServer::tool_translate(const StringName& p_message) const
return p_message;
}
-
void TranslationServer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_locale","locale"),&TranslationServer::set_locale);
- ClassDB::bind_method(D_METHOD("get_locale"),&TranslationServer::get_locale);
-
- ClassDB::bind_method(D_METHOD("translate","message"),&TranslationServer::translate);
+ ClassDB::bind_method(D_METHOD("set_locale", "locale"), &TranslationServer::set_locale);
+ ClassDB::bind_method(D_METHOD("get_locale"), &TranslationServer::get_locale);
- ClassDB::bind_method(D_METHOD("add_translation","translation:Translation"),&TranslationServer::add_translation);
- ClassDB::bind_method(D_METHOD("remove_translation","translation:Translation"),&TranslationServer::remove_translation);
+ ClassDB::bind_method(D_METHOD("translate", "message"), &TranslationServer::translate);
- ClassDB::bind_method(D_METHOD("clear"),&TranslationServer::clear);
+ ClassDB::bind_method(D_METHOD("add_translation", "translation:Translation"), &TranslationServer::add_translation);
+ ClassDB::bind_method(D_METHOD("remove_translation", "translation:Translation"), &TranslationServer::remove_translation);
+ ClassDB::bind_method(D_METHOD("clear"), &TranslationServer::clear);
}
void TranslationServer::load_translations() {
@@ -1154,21 +1129,17 @@ void TranslationServer::load_translations() {
String locale = get_locale();
bool found = _load_translations("locale/translations"); //all
- if (_load_translations("locale/translations_"+locale.substr(0,2)))
- found=true;
- if ( locale.substr(0,2) != locale ) {
- if (_load_translations("locale/translations_"+locale))
- found=true;
+ if (_load_translations("locale/translations_" + locale.substr(0, 2)))
+ found = true;
+ if (locale.substr(0, 2) != locale) {
+ if (_load_translations("locale/translations_" + locale))
+ found = true;
}
-
-
}
TranslationServer::TranslationServer() {
-
- singleton=this;
- locale="en";
- enabled=true;
-
+ singleton = this;
+ locale = "en";
+ enabled = true;
}
diff --git a/core/translation.h b/core/translation.h
index feed352549..90ec3fddce 100644
--- a/core/translation.h
+++ b/core/translation.h
@@ -31,12 +31,10 @@
#include "resource.h"
-
class Translation : public Resource {
-
- GDCLASS( Translation, Resource );
- OBJ_SAVE_TYPE( Translation );
+ GDCLASS(Translation, Resource);
+ OBJ_SAVE_TYPE(Translation);
RES_BASE_EXTENSION("xl");
String locale;
@@ -45,19 +43,18 @@ class Translation : public Resource {
PoolVector<String> _get_message_list() const;
PoolVector<String> _get_messages() const;
- void _set_messages(const PoolVector<String>& p_messages);
+ void _set_messages(const PoolVector<String> &p_messages);
+
protected:
static void _bind_methods();
public:
-
-
- void set_locale(const String& p_locale);
+ void set_locale(const String &p_locale);
_FORCE_INLINE_ String get_locale() const { return locale; }
- void add_message( const StringName& p_src_text, const StringName& p_xlated_text );
- virtual StringName get_message(const StringName& p_src_text) const; //overridable for other implementations
- void erase_message(const StringName& p_src_text);
+ void add_message(const StringName &p_src_text, const StringName &p_xlated_text);
+ virtual StringName get_message(const StringName &p_src_text) const; //overridable for other implementations
+ void erase_message(const StringName &p_src_text);
void get_message_list(List<StringName> *r_messages) const;
int get_message_count() const;
@@ -65,7 +62,6 @@ public:
Translation();
};
-
class TranslationServer : public Object {
GDCLASS(TranslationServer, Object);
@@ -73,39 +69,38 @@ class TranslationServer : public Object {
String locale;
String fallback;
-
- Set< Ref<Translation> > translations;
+ Set<Ref<Translation> > translations;
Ref<Translation> tool_translation;
bool enabled;
static TranslationServer *singleton;
- bool _load_translations(const String& p_from);
+ bool _load_translations(const String &p_from);
static void _bind_methods();
-public:
+public:
_FORCE_INLINE_ static TranslationServer *get_singleton() { return singleton; }
//yes, portuguese is supported!
- void set_enabled(bool p_enabled) { enabled=p_enabled; }
+ void set_enabled(bool p_enabled) { enabled = p_enabled; }
_FORCE_INLINE_ bool is_enabled() const { return enabled; }
- void set_locale(const String& p_locale);
+ void set_locale(const String &p_locale);
String get_locale() const;
void add_translation(const Ref<Translation> &p_translation);
void remove_translation(const Ref<Translation> &p_translation);
- StringName translate(const StringName& p_message) const;
+ StringName translate(const StringName &p_message) const;
static Vector<String> get_all_locales();
static Vector<String> get_all_locale_names();
- static bool is_locale_valid(const String& p_locale);
+ static bool is_locale_valid(const String &p_locale);
- void set_tool_translation(const Ref<Translation>& p_translation);
- StringName tool_translate(const StringName& p_message) const;
+ void set_tool_translation(const Ref<Translation> &p_translation);
+ StringName tool_translate(const StringName &p_message) const;
void setup();
diff --git a/core/typedefs.h b/core/typedefs.h
index c630887924..469c9ebd95 100644
--- a/core/typedefs.h
+++ b/core/typedefs.h
@@ -52,10 +52,9 @@
#endif // VERSION_PATCH
#define VERSION_FULL_NAME "" _MKSTR(VERSION_NAME) " v" VERSION_MKSTRING
-
#ifndef _ALWAYS_INLINE_
-#if defined(__GNUC__) && (__GNUC__ >= 4 )
+#if defined(__GNUC__) && (__GNUC__ >= 4)
#define _ALWAYS_INLINE_ __attribute__((always_inline)) inline
#elif defined(__llvm__)
#define _ALWAYS_INLINE_ __attribute__((always_inline)) inline
@@ -75,13 +74,15 @@
#endif
#endif
-
//custom, gcc-safe offsetof, because gcc complains a lot.
-template<class T>
-T *_nullptr() { T*t=NULL; return t; }
+template <class T>
+T *_nullptr() {
+ T *t = NULL;
+ return t;
+}
#define OFFSET_OF(st, m) \
-((size_t) ( (char *)&(_nullptr<st>()->m) - (char *)0 ))
+ ((size_t)((char *)&(_nullptr<st>()->m) - (char *)0))
/**
* Some platforms (devices) not define NULL
*/
@@ -107,43 +108,43 @@ T *_nullptr() { T*t=NULL; return t; }
#undef OK
#endif
-#include "error_macros.h"
#include "error_list.h"
+#include "error_macros.h"
#include "int_types.h"
/** Generic ABS function, for math uses please use Math::abs */
#ifndef ABS
-#define ABS(m_v) ((m_v<0)?(-(m_v)):(m_v))
+#define ABS(m_v) ((m_v < 0) ? (-(m_v)) : (m_v))
#endif
#ifndef SGN
-#define SGN(m_v) ((m_v<0)?(-1.0):(+1.0))
+#define SGN(m_v) ((m_v < 0) ? (-1.0) : (+1.0))
#endif
#ifndef MIN
-#define MIN(m_a,m_b) (((m_a)<(m_b))?(m_a):(m_b))
+#define MIN(m_a, m_b) (((m_a) < (m_b)) ? (m_a) : (m_b))
#endif
#ifndef MAX
-#define MAX(m_a,m_b) (((m_a)>(m_b))?(m_a):(m_b))
+#define MAX(m_a, m_b) (((m_a) > (m_b)) ? (m_a) : (m_b))
#endif
#ifndef CLAMP
-#define CLAMP(m_a,m_min,m_max) (((m_a)<(m_min))?(m_min):(((m_a)>(m_max))?m_max:m_a))
+#define CLAMP(m_a, m_min, m_max) (((m_a) < (m_min)) ? (m_min) : (((m_a) > (m_max)) ? m_max : m_a))
#endif
/** Generic swap template */
#ifndef SWAP
-#define SWAP(m_x,m_y) __swap_tmpl(m_x,m_y)
-template<class T>
-inline void __swap_tmpl(T &x, T &y ) {
+#define SWAP(m_x, m_y) __swap_tmpl(m_x, m_y)
+template <class T>
+inline void __swap_tmpl(T &x, T &y) {
- T aux=x;
- x=y;
- y=aux;
+ T aux = x;
+ x = y;
+ y = aux;
}
#endif //swap
@@ -171,7 +172,6 @@ inline void __swap_tmpl(T &x, T &y ) {
#define _add_overflow __builtin_add_overflow
#endif
-
/** Function to find the nearest (bigger) power of 2 to an integer */
static _FORCE_INLINE_ unsigned int nearest_power_of_2(unsigned int x) {
@@ -189,7 +189,7 @@ static _FORCE_INLINE_ unsigned int nearest_power_of_2(unsigned int x) {
// We need this definition inside the function below.
static inline int get_shift_from_power_of_2(unsigned int p_pixel);
-template<class T>
+template <class T>
static _FORCE_INLINE_ T nearest_power_of_2_templated(T x) {
--x;
@@ -211,23 +211,22 @@ static _FORCE_INLINE_ T nearest_power_of_2_templated(T x) {
static inline unsigned int nearest_shift(unsigned int p_number) {
- for (int i=30;i>=0;i--) {
+ for (int i = 30; i >= 0; i--) {
- if (p_number&(1<<i))
- return i+1;
+ if (p_number & (1 << i))
+ return i + 1;
}
return 0;
}
/** get a shift value from a power of 2 */
-static inline int get_shift_from_power_of_2( unsigned int p_pixel ) {
+static inline int get_shift_from_power_of_2(unsigned int p_pixel) {
// return a GL_TEXTURE_SIZE_ENUM
+ for (unsigned int i = 0; i < 32; i++) {
- for (unsigned int i=0;i<32;i++) {
-
- if (p_pixel==(unsigned int)(1<<i))
+ if (p_pixel == (unsigned int)(1 << i))
return i;
}
@@ -236,18 +235,18 @@ static inline int get_shift_from_power_of_2( unsigned int p_pixel ) {
/** Swap 16 bits value for endianness */
static inline uint16_t BSWAP16(uint16_t x) {
- return (x>>8)|(x<<8);
+ return (x >> 8) | (x << 8);
}
/** Swap 32 bits value for endianness */
static inline uint32_t BSWAP32(uint32_t x) {
- return((x<<24)|((x<<8)&0x00FF0000)|((x>>8)&0x0000FF00)|(x>>24));
+ return ((x << 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x >> 24));
}
/** Swap 64 bits value for endianness */
static inline uint64_t BSWAP64(uint64_t x) {
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
- x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
+ x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
return x;
}
@@ -256,14 +255,12 @@ static inline uint64_t BSWAP64(uint64_t x) {
* is used besides casting by enum.
*/
-template<class T>
+template <class T>
struct Comparator {
- inline bool operator()(const T& p_a, const T& p_b) const { return (p_a<p_b); }
-
+ inline bool operator()(const T &p_a, const T &p_b) const { return (p_a < p_b); }
};
-
void _global_lock();
void _global_unlock();
@@ -286,4 +283,4 @@ struct _GlobalLock {
#define __STRX(m_index) #m_index
#define __STR(m_index) __STRX(m_index)
-#endif /* typedefs.h */
+#endif /* typedefs.h */
diff --git a/core/ucaps.h b/core/ucaps.h
index 55b6509269..0e4b5709e6 100644
--- a/core/ucaps.h
+++ b/core/ucaps.h
@@ -32,1358 +32,1356 @@
//satan invented unicode?
#define CAPS_LEN 666
-static const int caps_table[CAPS_LEN][2]={
-{0x0061,0x0041},
-{0x0062,0x0042},
-{0x0063,0x0043},
-{0x0064,0x0044},
-{0x0065,0x0045},
-{0x0066,0x0046},
-{0x0067,0x0047},
-{0x0068,0x0048},
-{0x0069,0x0049},
-{0x006A,0x004A},
-{0x006B,0x004B},
-{0x006C,0x004C},
-{0x006D,0x004D},
-{0x006E,0x004E},
-{0x006F,0x004F},
-{0x0070,0x0050},
-{0x0071,0x0051},
-{0x0072,0x0052},
-{0x0073,0x0053},
-{0x0074,0x0054},
-{0x0075,0x0055},
-{0x0076,0x0056},
-{0x0077,0x0057},
-{0x0078,0x0058},
-{0x0079,0x0059},
-{0x007A,0x005A},
-{0x00E0,0x00C0},
-{0x00E1,0x00C1},
-{0x00E2,0x00C2},
-{0x00E3,0x00C3},
-{0x00E4,0x00C4},
-{0x00E5,0x00C5},
-{0x00E6,0x00C6},
-{0x00E7,0x00C7},
-{0x00E8,0x00C8},
-{0x00E9,0x00C9},
-{0x00EA,0x00CA},
-{0x00EB,0x00CB},
-{0x00EC,0x00CC},
-{0x00ED,0x00CD},
-{0x00EE,0x00CE},
-{0x00EF,0x00CF},
-{0x00F0,0x00D0},
-{0x00F1,0x00D1},
-{0x00F2,0x00D2},
-{0x00F3,0x00D3},
-{0x00F4,0x00D4},
-{0x00F5,0x00D5},
-{0x00F6,0x00D6},
-{0x00F8,0x00D8},
-{0x00F9,0x00D9},
-{0x00FA,0x00DA},
-{0x00FB,0x00DB},
-{0x00FC,0x00DC},
-{0x00FD,0x00DD},
-{0x00FE,0x00DE},
-{0x00FF,0x0178},
-{0x0101,0x0100},
-{0x0103,0x0102},
-{0x0105,0x0104},
-{0x0107,0x0106},
-{0x0109,0x0108},
-{0x010B,0x010A},
-{0x010D,0x010C},
-{0x010F,0x010E},
-{0x0111,0x0110},
-{0x0113,0x0112},
-{0x0115,0x0114},
-{0x0117,0x0116},
-{0x0119,0x0118},
-{0x011B,0x011A},
-{0x011D,0x011C},
-{0x011F,0x011E},
-{0x0121,0x0120},
-{0x0123,0x0122},
-{0x0125,0x0124},
-{0x0127,0x0126},
-{0x0129,0x0128},
-{0x012B,0x012A},
-{0x012D,0x012C},
-{0x012F,0x012E},
-{0x0131,0x0049},
-{0x0133,0x0132},
-{0x0135,0x0134},
-{0x0137,0x0136},
-{0x013A,0x0139},
-{0x013C,0x013B},
-{0x013E,0x013D},
-{0x0140,0x013F},
-{0x0142,0x0141},
-{0x0144,0x0143},
-{0x0146,0x0145},
-{0x0148,0x0147},
-{0x014B,0x014A},
-{0x014D,0x014C},
-{0x014F,0x014E},
-{0x0151,0x0150},
-{0x0153,0x0152},
-{0x0155,0x0154},
-{0x0157,0x0156},
-{0x0159,0x0158},
-{0x015B,0x015A},
-{0x015D,0x015C},
-{0x015F,0x015E},
-{0x0161,0x0160},
-{0x0163,0x0162},
-{0x0165,0x0164},
-{0x0167,0x0166},
-{0x0169,0x0168},
-{0x016B,0x016A},
-{0x016D,0x016C},
-{0x016F,0x016E},
-{0x0171,0x0170},
-{0x0173,0x0172},
-{0x0175,0x0174},
-{0x0177,0x0176},
-{0x017A,0x0179},
-{0x017C,0x017B},
-{0x017E,0x017D},
-{0x0183,0x0182},
-{0x0185,0x0184},
-{0x0188,0x0187},
-{0x018C,0x018B},
-{0x0192,0x0191},
-{0x0199,0x0198},
-{0x01A1,0x01A0},
-{0x01A3,0x01A2},
-{0x01A5,0x01A4},
-{0x01A8,0x01A7},
-{0x01AD,0x01AC},
-{0x01B0,0x01AF},
-{0x01B4,0x01B3},
-{0x01B6,0x01B5},
-{0x01B9,0x01B8},
-{0x01BD,0x01BC},
-{0x01C6,0x01C4},
-{0x01C9,0x01C7},
-{0x01CC,0x01CA},
-{0x01CE,0x01CD},
-{0x01D0,0x01CF},
-{0x01D2,0x01D1},
-{0x01D4,0x01D3},
-{0x01D6,0x01D5},
-{0x01D8,0x01D7},
-{0x01DA,0x01D9},
-{0x01DC,0x01DB},
-{0x01DF,0x01DE},
-{0x01E1,0x01E0},
-{0x01E3,0x01E2},
-{0x01E5,0x01E4},
-{0x01E7,0x01E6},
-{0x01E9,0x01E8},
-{0x01EB,0x01EA},
-{0x01ED,0x01EC},
-{0x01EF,0x01EE},
-{0x01F3,0x01F1},
-{0x01F5,0x01F4},
-{0x01FB,0x01FA},
-{0x01FD,0x01FC},
-{0x01FF,0x01FE},
-{0x0201,0x0200},
-{0x0203,0x0202},
-{0x0205,0x0204},
-{0x0207,0x0206},
-{0x0209,0x0208},
-{0x020B,0x020A},
-{0x020D,0x020C},
-{0x020F,0x020E},
-{0x0211,0x0210},
-{0x0213,0x0212},
-{0x0215,0x0214},
-{0x0217,0x0216},
-{0x0253,0x0181},
-{0x0254,0x0186},
-{0x0257,0x018A},
-{0x0258,0x018E},
-{0x0259,0x018F},
-{0x025B,0x0190},
-{0x0260,0x0193},
-{0x0263,0x0194},
-{0x0268,0x0197},
-{0x0269,0x0196},
-{0x026F,0x019C},
-{0x0272,0x019D},
-{0x0275,0x019F},
-{0x0283,0x01A9},
-{0x0288,0x01AE},
-{0x028A,0x01B1},
-{0x028B,0x01B2},
-{0x0292,0x01B7},
-{0x03AC,0x0386},
-{0x03AD,0x0388},
-{0x03AE,0x0389},
-{0x03AF,0x038A},
-{0x03B1,0x0391},
-{0x03B2,0x0392},
-{0x03B3,0x0393},
-{0x03B4,0x0394},
-{0x03B5,0x0395},
-{0x03B6,0x0396},
-{0x03B7,0x0397},
-{0x03B8,0x0398},
-{0x03B9,0x0399},
-{0x03BA,0x039A},
-{0x03BB,0x039B},
-{0x03BC,0x039C},
-{0x03BD,0x039D},
-{0x03BE,0x039E},
-{0x03BF,0x039F},
-{0x03C0,0x03A0},
-{0x03C1,0x03A1},
-{0x03C3,0x03A3},
-{0x03C4,0x03A4},
-{0x03C5,0x03A5},
-{0x03C6,0x03A6},
-{0x03C7,0x03A7},
-{0x03C8,0x03A8},
-{0x03C9,0x03A9},
-{0x03CA,0x03AA},
-{0x03CB,0x03AB},
-{0x03CC,0x038C},
-{0x03CD,0x038E},
-{0x03CE,0x038F},
-{0x03E3,0x03E2},
-{0x03E5,0x03E4},
-{0x03E7,0x03E6},
-{0x03E9,0x03E8},
-{0x03EB,0x03EA},
-{0x03ED,0x03EC},
-{0x03EF,0x03EE},
-{0x0430,0x0410},
-{0x0431,0x0411},
-{0x0432,0x0412},
-{0x0433,0x0413},
-{0x0434,0x0414},
-{0x0435,0x0415},
-{0x0436,0x0416},
-{0x0437,0x0417},
-{0x0438,0x0418},
-{0x0439,0x0419},
-{0x043A,0x041A},
-{0x043B,0x041B},
-{0x043C,0x041C},
-{0x043D,0x041D},
-{0x043E,0x041E},
-{0x043F,0x041F},
-{0x0440,0x0420},
-{0x0441,0x0421},
-{0x0442,0x0422},
-{0x0443,0x0423},
-{0x0444,0x0424},
-{0x0445,0x0425},
-{0x0446,0x0426},
-{0x0447,0x0427},
-{0x0448,0x0428},
-{0x0449,0x0429},
-{0x044A,0x042A},
-{0x044B,0x042B},
-{0x044C,0x042C},
-{0x044D,0x042D},
-{0x044E,0x042E},
-{0x044F,0x042F},
-{0x0451,0x0401},
-{0x0452,0x0402},
-{0x0453,0x0403},
-{0x0454,0x0404},
-{0x0455,0x0405},
-{0x0456,0x0406},
-{0x0457,0x0407},
-{0x0458,0x0408},
-{0x0459,0x0409},
-{0x045A,0x040A},
-{0x045B,0x040B},
-{0x045C,0x040C},
-{0x045E,0x040E},
-{0x045F,0x040F},
-{0x0461,0x0460},
-{0x0463,0x0462},
-{0x0465,0x0464},
-{0x0467,0x0466},
-{0x0469,0x0468},
-{0x046B,0x046A},
-{0x046D,0x046C},
-{0x046F,0x046E},
-{0x0471,0x0470},
-{0x0473,0x0472},
-{0x0475,0x0474},
-{0x0477,0x0476},
-{0x0479,0x0478},
-{0x047B,0x047A},
-{0x047D,0x047C},
-{0x047F,0x047E},
-{0x0481,0x0480},
-{0x0491,0x0490},
-{0x0493,0x0492},
-{0x0495,0x0494},
-{0x0497,0x0496},
-{0x0499,0x0498},
-{0x049B,0x049A},
-{0x049D,0x049C},
-{0x049F,0x049E},
-{0x04A1,0x04A0},
-{0x04A3,0x04A2},
-{0x04A5,0x04A4},
-{0x04A7,0x04A6},
-{0x04A9,0x04A8},
-{0x04AB,0x04AA},
-{0x04AD,0x04AC},
-{0x04AF,0x04AE},
-{0x04B1,0x04B0},
-{0x04B3,0x04B2},
-{0x04B5,0x04B4},
-{0x04B7,0x04B6},
-{0x04B9,0x04B8},
-{0x04BB,0x04BA},
-{0x04BD,0x04BC},
-{0x04BF,0x04BE},
-{0x04C2,0x04C1},
-{0x04C4,0x04C3},
-{0x04C8,0x04C7},
-{0x04CC,0x04CB},
-{0x04D1,0x04D0},
-{0x04D3,0x04D2},
-{0x04D5,0x04D4},
-{0x04D7,0x04D6},
-{0x04D9,0x04D8},
-{0x04DB,0x04DA},
-{0x04DD,0x04DC},
-{0x04DF,0x04DE},
-{0x04E1,0x04E0},
-{0x04E3,0x04E2},
-{0x04E5,0x04E4},
-{0x04E7,0x04E6},
-{0x04E9,0x04E8},
-{0x04EB,0x04EA},
-{0x04EF,0x04EE},
-{0x04F1,0x04F0},
-{0x04F3,0x04F2},
-{0x04F5,0x04F4},
-{0x04F9,0x04F8},
-{0x0561,0x0531},
-{0x0562,0x0532},
-{0x0563,0x0533},
-{0x0564,0x0534},
-{0x0565,0x0535},
-{0x0566,0x0536},
-{0x0567,0x0537},
-{0x0568,0x0538},
-{0x0569,0x0539},
-{0x056A,0x053A},
-{0x056B,0x053B},
-{0x056C,0x053C},
-{0x056D,0x053D},
-{0x056E,0x053E},
-{0x056F,0x053F},
-{0x0570,0x0540},
-{0x0571,0x0541},
-{0x0572,0x0542},
-{0x0573,0x0543},
-{0x0574,0x0544},
-{0x0575,0x0545},
-{0x0576,0x0546},
-{0x0577,0x0547},
-{0x0578,0x0548},
-{0x0579,0x0549},
-{0x057A,0x054A},
-{0x057B,0x054B},
-{0x057C,0x054C},
-{0x057D,0x054D},
-{0x057E,0x054E},
-{0x057F,0x054F},
-{0x0580,0x0550},
-{0x0581,0x0551},
-{0x0582,0x0552},
-{0x0583,0x0553},
-{0x0584,0x0554},
-{0x0585,0x0555},
-{0x0586,0x0556},
-{0x10D0,0x10A0},
-{0x10D1,0x10A1},
-{0x10D2,0x10A2},
-{0x10D3,0x10A3},
-{0x10D4,0x10A4},
-{0x10D5,0x10A5},
-{0x10D6,0x10A6},
-{0x10D7,0x10A7},
-{0x10D8,0x10A8},
-{0x10D9,0x10A9},
-{0x10DA,0x10AA},
-{0x10DB,0x10AB},
-{0x10DC,0x10AC},
-{0x10DD,0x10AD},
-{0x10DE,0x10AE},
-{0x10DF,0x10AF},
-{0x10E0,0x10B0},
-{0x10E1,0x10B1},
-{0x10E2,0x10B2},
-{0x10E3,0x10B3},
-{0x10E4,0x10B4},
-{0x10E5,0x10B5},
-{0x10E6,0x10B6},
-{0x10E7,0x10B7},
-{0x10E8,0x10B8},
-{0x10E9,0x10B9},
-{0x10EA,0x10BA},
-{0x10EB,0x10BB},
-{0x10EC,0x10BC},
-{0x10ED,0x10BD},
-{0x10EE,0x10BE},
-{0x10EF,0x10BF},
-{0x10F0,0x10C0},
-{0x10F1,0x10C1},
-{0x10F2,0x10C2},
-{0x10F3,0x10C3},
-{0x10F4,0x10C4},
-{0x10F5,0x10C5},
-{0x1E01,0x1E00},
-{0x1E03,0x1E02},
-{0x1E05,0x1E04},
-{0x1E07,0x1E06},
-{0x1E09,0x1E08},
-{0x1E0B,0x1E0A},
-{0x1E0D,0x1E0C},
-{0x1E0F,0x1E0E},
-{0x1E11,0x1E10},
-{0x1E13,0x1E12},
-{0x1E15,0x1E14},
-{0x1E17,0x1E16},
-{0x1E19,0x1E18},
-{0x1E1B,0x1E1A},
-{0x1E1D,0x1E1C},
-{0x1E1F,0x1E1E},
-{0x1E21,0x1E20},
-{0x1E23,0x1E22},
-{0x1E25,0x1E24},
-{0x1E27,0x1E26},
-{0x1E29,0x1E28},
-{0x1E2B,0x1E2A},
-{0x1E2D,0x1E2C},
-{0x1E2F,0x1E2E},
-{0x1E31,0x1E30},
-{0x1E33,0x1E32},
-{0x1E35,0x1E34},
-{0x1E37,0x1E36},
-{0x1E39,0x1E38},
-{0x1E3B,0x1E3A},
-{0x1E3D,0x1E3C},
-{0x1E3F,0x1E3E},
-{0x1E41,0x1E40},
-{0x1E43,0x1E42},
-{0x1E45,0x1E44},
-{0x1E47,0x1E46},
-{0x1E49,0x1E48},
-{0x1E4B,0x1E4A},
-{0x1E4D,0x1E4C},
-{0x1E4F,0x1E4E},
-{0x1E51,0x1E50},
-{0x1E53,0x1E52},
-{0x1E55,0x1E54},
-{0x1E57,0x1E56},
-{0x1E59,0x1E58},
-{0x1E5B,0x1E5A},
-{0x1E5D,0x1E5C},
-{0x1E5F,0x1E5E},
-{0x1E61,0x1E60},
-{0x1E63,0x1E62},
-{0x1E65,0x1E64},
-{0x1E67,0x1E66},
-{0x1E69,0x1E68},
-{0x1E6B,0x1E6A},
-{0x1E6D,0x1E6C},
-{0x1E6F,0x1E6E},
-{0x1E71,0x1E70},
-{0x1E73,0x1E72},
-{0x1E75,0x1E74},
-{0x1E77,0x1E76},
-{0x1E79,0x1E78},
-{0x1E7B,0x1E7A},
-{0x1E7D,0x1E7C},
-{0x1E7F,0x1E7E},
-{0x1E81,0x1E80},
-{0x1E83,0x1E82},
-{0x1E85,0x1E84},
-{0x1E87,0x1E86},
-{0x1E89,0x1E88},
-{0x1E8B,0x1E8A},
-{0x1E8D,0x1E8C},
-{0x1E8F,0x1E8E},
-{0x1E91,0x1E90},
-{0x1E93,0x1E92},
-{0x1E95,0x1E94},
-{0x1EA1,0x1EA0},
-{0x1EA3,0x1EA2},
-{0x1EA5,0x1EA4},
-{0x1EA7,0x1EA6},
-{0x1EA9,0x1EA8},
-{0x1EAB,0x1EAA},
-{0x1EAD,0x1EAC},
-{0x1EAF,0x1EAE},
-{0x1EB1,0x1EB0},
-{0x1EB3,0x1EB2},
-{0x1EB5,0x1EB4},
-{0x1EB7,0x1EB6},
-{0x1EB9,0x1EB8},
-{0x1EBB,0x1EBA},
-{0x1EBD,0x1EBC},
-{0x1EBF,0x1EBE},
-{0x1EC1,0x1EC0},
-{0x1EC3,0x1EC2},
-{0x1EC5,0x1EC4},
-{0x1EC7,0x1EC6},
-{0x1EC9,0x1EC8},
-{0x1ECB,0x1ECA},
-{0x1ECD,0x1ECC},
-{0x1ECF,0x1ECE},
-{0x1ED1,0x1ED0},
-{0x1ED3,0x1ED2},
-{0x1ED5,0x1ED4},
-{0x1ED7,0x1ED6},
-{0x1ED9,0x1ED8},
-{0x1EDB,0x1EDA},
-{0x1EDD,0x1EDC},
-{0x1EDF,0x1EDE},
-{0x1EE1,0x1EE0},
-{0x1EE3,0x1EE2},
-{0x1EE5,0x1EE4},
-{0x1EE7,0x1EE6},
-{0x1EE9,0x1EE8},
-{0x1EEB,0x1EEA},
-{0x1EED,0x1EEC},
-{0x1EEF,0x1EEE},
-{0x1EF1,0x1EF0},
-{0x1EF3,0x1EF2},
-{0x1EF5,0x1EF4},
-{0x1EF7,0x1EF6},
-{0x1EF9,0x1EF8},
-{0x1F00,0x1F08},
-{0x1F01,0x1F09},
-{0x1F02,0x1F0A},
-{0x1F03,0x1F0B},
-{0x1F04,0x1F0C},
-{0x1F05,0x1F0D},
-{0x1F06,0x1F0E},
-{0x1F07,0x1F0F},
-{0x1F10,0x1F18},
-{0x1F11,0x1F19},
-{0x1F12,0x1F1A},
-{0x1F13,0x1F1B},
-{0x1F14,0x1F1C},
-{0x1F15,0x1F1D},
-{0x1F20,0x1F28},
-{0x1F21,0x1F29},
-{0x1F22,0x1F2A},
-{0x1F23,0x1F2B},
-{0x1F24,0x1F2C},
-{0x1F25,0x1F2D},
-{0x1F26,0x1F2E},
-{0x1F27,0x1F2F},
-{0x1F30,0x1F38},
-{0x1F31,0x1F39},
-{0x1F32,0x1F3A},
-{0x1F33,0x1F3B},
-{0x1F34,0x1F3C},
-{0x1F35,0x1F3D},
-{0x1F36,0x1F3E},
-{0x1F37,0x1F3F},
-{0x1F40,0x1F48},
-{0x1F41,0x1F49},
-{0x1F42,0x1F4A},
-{0x1F43,0x1F4B},
-{0x1F44,0x1F4C},
-{0x1F45,0x1F4D},
-{0x1F51,0x1F59},
-{0x1F53,0x1F5B},
-{0x1F55,0x1F5D},
-{0x1F57,0x1F5F},
-{0x1F60,0x1F68},
-{0x1F61,0x1F69},
-{0x1F62,0x1F6A},
-{0x1F63,0x1F6B},
-{0x1F64,0x1F6C},
-{0x1F65,0x1F6D},
-{0x1F66,0x1F6E},
-{0x1F67,0x1F6F},
-{0x1F80,0x1F88},
-{0x1F81,0x1F89},
-{0x1F82,0x1F8A},
-{0x1F83,0x1F8B},
-{0x1F84,0x1F8C},
-{0x1F85,0x1F8D},
-{0x1F86,0x1F8E},
-{0x1F87,0x1F8F},
-{0x1F90,0x1F98},
-{0x1F91,0x1F99},
-{0x1F92,0x1F9A},
-{0x1F93,0x1F9B},
-{0x1F94,0x1F9C},
-{0x1F95,0x1F9D},
-{0x1F96,0x1F9E},
-{0x1F97,0x1F9F},
-{0x1FA0,0x1FA8},
-{0x1FA1,0x1FA9},
-{0x1FA2,0x1FAA},
-{0x1FA3,0x1FAB},
-{0x1FA4,0x1FAC},
-{0x1FA5,0x1FAD},
-{0x1FA6,0x1FAE},
-{0x1FA7,0x1FAF},
-{0x1FB0,0x1FB8},
-{0x1FB1,0x1FB9},
-{0x1FD0,0x1FD8},
-{0x1FD1,0x1FD9},
-{0x1FE0,0x1FE8},
-{0x1FE1,0x1FE9},
-{0x24D0,0x24B6},
-{0x24D1,0x24B7},
-{0x24D2,0x24B8},
-{0x24D3,0x24B9},
-{0x24D4,0x24BA},
-{0x24D5,0x24BB},
-{0x24D6,0x24BC},
-{0x24D7,0x24BD},
-{0x24D8,0x24BE},
-{0x24D9,0x24BF},
-{0x24DA,0x24C0},
-{0x24DB,0x24C1},
-{0x24DC,0x24C2},
-{0x24DD,0x24C3},
-{0x24DE,0x24C4},
-{0x24DF,0x24C5},
-{0x24E0,0x24C6},
-{0x24E1,0x24C7},
-{0x24E2,0x24C8},
-{0x24E3,0x24C9},
-{0x24E4,0x24CA},
-{0x24E5,0x24CB},
-{0x24E6,0x24CC},
-{0x24E7,0x24CD},
-{0x24E8,0x24CE},
-{0x24E9,0x24CF},
-{0xFF41,0xFF21},
-{0xFF42,0xFF22},
-{0xFF43,0xFF23},
-{0xFF44,0xFF24},
-{0xFF45,0xFF25},
-{0xFF46,0xFF26},
-{0xFF47,0xFF27},
-{0xFF48,0xFF28},
-{0xFF49,0xFF29},
-{0xFF4A,0xFF2A},
-{0xFF4B,0xFF2B},
-{0xFF4C,0xFF2C},
-{0xFF4D,0xFF2D},
-{0xFF4E,0xFF2E},
-{0xFF4F,0xFF2F},
-{0xFF50,0xFF30},
-{0xFF51,0xFF31},
-{0xFF52,0xFF32},
-{0xFF53,0xFF33},
-{0xFF54,0xFF34},
-{0xFF55,0xFF35},
-{0xFF56,0xFF36},
-{0xFF57,0xFF37},
-{0xFF58,0xFF38},
-{0xFF59,0xFF39},
-{0xFF5A,0xFF3A},
+static const int caps_table[CAPS_LEN][2] = {
+ { 0x0061, 0x0041 },
+ { 0x0062, 0x0042 },
+ { 0x0063, 0x0043 },
+ { 0x0064, 0x0044 },
+ { 0x0065, 0x0045 },
+ { 0x0066, 0x0046 },
+ { 0x0067, 0x0047 },
+ { 0x0068, 0x0048 },
+ { 0x0069, 0x0049 },
+ { 0x006A, 0x004A },
+ { 0x006B, 0x004B },
+ { 0x006C, 0x004C },
+ { 0x006D, 0x004D },
+ { 0x006E, 0x004E },
+ { 0x006F, 0x004F },
+ { 0x0070, 0x0050 },
+ { 0x0071, 0x0051 },
+ { 0x0072, 0x0052 },
+ { 0x0073, 0x0053 },
+ { 0x0074, 0x0054 },
+ { 0x0075, 0x0055 },
+ { 0x0076, 0x0056 },
+ { 0x0077, 0x0057 },
+ { 0x0078, 0x0058 },
+ { 0x0079, 0x0059 },
+ { 0x007A, 0x005A },
+ { 0x00E0, 0x00C0 },
+ { 0x00E1, 0x00C1 },
+ { 0x00E2, 0x00C2 },
+ { 0x00E3, 0x00C3 },
+ { 0x00E4, 0x00C4 },
+ { 0x00E5, 0x00C5 },
+ { 0x00E6, 0x00C6 },
+ { 0x00E7, 0x00C7 },
+ { 0x00E8, 0x00C8 },
+ { 0x00E9, 0x00C9 },
+ { 0x00EA, 0x00CA },
+ { 0x00EB, 0x00CB },
+ { 0x00EC, 0x00CC },
+ { 0x00ED, 0x00CD },
+ { 0x00EE, 0x00CE },
+ { 0x00EF, 0x00CF },
+ { 0x00F0, 0x00D0 },
+ { 0x00F1, 0x00D1 },
+ { 0x00F2, 0x00D2 },
+ { 0x00F3, 0x00D3 },
+ { 0x00F4, 0x00D4 },
+ { 0x00F5, 0x00D5 },
+ { 0x00F6, 0x00D6 },
+ { 0x00F8, 0x00D8 },
+ { 0x00F9, 0x00D9 },
+ { 0x00FA, 0x00DA },
+ { 0x00FB, 0x00DB },
+ { 0x00FC, 0x00DC },
+ { 0x00FD, 0x00DD },
+ { 0x00FE, 0x00DE },
+ { 0x00FF, 0x0178 },
+ { 0x0101, 0x0100 },
+ { 0x0103, 0x0102 },
+ { 0x0105, 0x0104 },
+ { 0x0107, 0x0106 },
+ { 0x0109, 0x0108 },
+ { 0x010B, 0x010A },
+ { 0x010D, 0x010C },
+ { 0x010F, 0x010E },
+ { 0x0111, 0x0110 },
+ { 0x0113, 0x0112 },
+ { 0x0115, 0x0114 },
+ { 0x0117, 0x0116 },
+ { 0x0119, 0x0118 },
+ { 0x011B, 0x011A },
+ { 0x011D, 0x011C },
+ { 0x011F, 0x011E },
+ { 0x0121, 0x0120 },
+ { 0x0123, 0x0122 },
+ { 0x0125, 0x0124 },
+ { 0x0127, 0x0126 },
+ { 0x0129, 0x0128 },
+ { 0x012B, 0x012A },
+ { 0x012D, 0x012C },
+ { 0x012F, 0x012E },
+ { 0x0131, 0x0049 },
+ { 0x0133, 0x0132 },
+ { 0x0135, 0x0134 },
+ { 0x0137, 0x0136 },
+ { 0x013A, 0x0139 },
+ { 0x013C, 0x013B },
+ { 0x013E, 0x013D },
+ { 0x0140, 0x013F },
+ { 0x0142, 0x0141 },
+ { 0x0144, 0x0143 },
+ { 0x0146, 0x0145 },
+ { 0x0148, 0x0147 },
+ { 0x014B, 0x014A },
+ { 0x014D, 0x014C },
+ { 0x014F, 0x014E },
+ { 0x0151, 0x0150 },
+ { 0x0153, 0x0152 },
+ { 0x0155, 0x0154 },
+ { 0x0157, 0x0156 },
+ { 0x0159, 0x0158 },
+ { 0x015B, 0x015A },
+ { 0x015D, 0x015C },
+ { 0x015F, 0x015E },
+ { 0x0161, 0x0160 },
+ { 0x0163, 0x0162 },
+ { 0x0165, 0x0164 },
+ { 0x0167, 0x0166 },
+ { 0x0169, 0x0168 },
+ { 0x016B, 0x016A },
+ { 0x016D, 0x016C },
+ { 0x016F, 0x016E },
+ { 0x0171, 0x0170 },
+ { 0x0173, 0x0172 },
+ { 0x0175, 0x0174 },
+ { 0x0177, 0x0176 },
+ { 0x017A, 0x0179 },
+ { 0x017C, 0x017B },
+ { 0x017E, 0x017D },
+ { 0x0183, 0x0182 },
+ { 0x0185, 0x0184 },
+ { 0x0188, 0x0187 },
+ { 0x018C, 0x018B },
+ { 0x0192, 0x0191 },
+ { 0x0199, 0x0198 },
+ { 0x01A1, 0x01A0 },
+ { 0x01A3, 0x01A2 },
+ { 0x01A5, 0x01A4 },
+ { 0x01A8, 0x01A7 },
+ { 0x01AD, 0x01AC },
+ { 0x01B0, 0x01AF },
+ { 0x01B4, 0x01B3 },
+ { 0x01B6, 0x01B5 },
+ { 0x01B9, 0x01B8 },
+ { 0x01BD, 0x01BC },
+ { 0x01C6, 0x01C4 },
+ { 0x01C9, 0x01C7 },
+ { 0x01CC, 0x01CA },
+ { 0x01CE, 0x01CD },
+ { 0x01D0, 0x01CF },
+ { 0x01D2, 0x01D1 },
+ { 0x01D4, 0x01D3 },
+ { 0x01D6, 0x01D5 },
+ { 0x01D8, 0x01D7 },
+ { 0x01DA, 0x01D9 },
+ { 0x01DC, 0x01DB },
+ { 0x01DF, 0x01DE },
+ { 0x01E1, 0x01E0 },
+ { 0x01E3, 0x01E2 },
+ { 0x01E5, 0x01E4 },
+ { 0x01E7, 0x01E6 },
+ { 0x01E9, 0x01E8 },
+ { 0x01EB, 0x01EA },
+ { 0x01ED, 0x01EC },
+ { 0x01EF, 0x01EE },
+ { 0x01F3, 0x01F1 },
+ { 0x01F5, 0x01F4 },
+ { 0x01FB, 0x01FA },
+ { 0x01FD, 0x01FC },
+ { 0x01FF, 0x01FE },
+ { 0x0201, 0x0200 },
+ { 0x0203, 0x0202 },
+ { 0x0205, 0x0204 },
+ { 0x0207, 0x0206 },
+ { 0x0209, 0x0208 },
+ { 0x020B, 0x020A },
+ { 0x020D, 0x020C },
+ { 0x020F, 0x020E },
+ { 0x0211, 0x0210 },
+ { 0x0213, 0x0212 },
+ { 0x0215, 0x0214 },
+ { 0x0217, 0x0216 },
+ { 0x0253, 0x0181 },
+ { 0x0254, 0x0186 },
+ { 0x0257, 0x018A },
+ { 0x0258, 0x018E },
+ { 0x0259, 0x018F },
+ { 0x025B, 0x0190 },
+ { 0x0260, 0x0193 },
+ { 0x0263, 0x0194 },
+ { 0x0268, 0x0197 },
+ { 0x0269, 0x0196 },
+ { 0x026F, 0x019C },
+ { 0x0272, 0x019D },
+ { 0x0275, 0x019F },
+ { 0x0283, 0x01A9 },
+ { 0x0288, 0x01AE },
+ { 0x028A, 0x01B1 },
+ { 0x028B, 0x01B2 },
+ { 0x0292, 0x01B7 },
+ { 0x03AC, 0x0386 },
+ { 0x03AD, 0x0388 },
+ { 0x03AE, 0x0389 },
+ { 0x03AF, 0x038A },
+ { 0x03B1, 0x0391 },
+ { 0x03B2, 0x0392 },
+ { 0x03B3, 0x0393 },
+ { 0x03B4, 0x0394 },
+ { 0x03B5, 0x0395 },
+ { 0x03B6, 0x0396 },
+ { 0x03B7, 0x0397 },
+ { 0x03B8, 0x0398 },
+ { 0x03B9, 0x0399 },
+ { 0x03BA, 0x039A },
+ { 0x03BB, 0x039B },
+ { 0x03BC, 0x039C },
+ { 0x03BD, 0x039D },
+ { 0x03BE, 0x039E },
+ { 0x03BF, 0x039F },
+ { 0x03C0, 0x03A0 },
+ { 0x03C1, 0x03A1 },
+ { 0x03C3, 0x03A3 },
+ { 0x03C4, 0x03A4 },
+ { 0x03C5, 0x03A5 },
+ { 0x03C6, 0x03A6 },
+ { 0x03C7, 0x03A7 },
+ { 0x03C8, 0x03A8 },
+ { 0x03C9, 0x03A9 },
+ { 0x03CA, 0x03AA },
+ { 0x03CB, 0x03AB },
+ { 0x03CC, 0x038C },
+ { 0x03CD, 0x038E },
+ { 0x03CE, 0x038F },
+ { 0x03E3, 0x03E2 },
+ { 0x03E5, 0x03E4 },
+ { 0x03E7, 0x03E6 },
+ { 0x03E9, 0x03E8 },
+ { 0x03EB, 0x03EA },
+ { 0x03ED, 0x03EC },
+ { 0x03EF, 0x03EE },
+ { 0x0430, 0x0410 },
+ { 0x0431, 0x0411 },
+ { 0x0432, 0x0412 },
+ { 0x0433, 0x0413 },
+ { 0x0434, 0x0414 },
+ { 0x0435, 0x0415 },
+ { 0x0436, 0x0416 },
+ { 0x0437, 0x0417 },
+ { 0x0438, 0x0418 },
+ { 0x0439, 0x0419 },
+ { 0x043A, 0x041A },
+ { 0x043B, 0x041B },
+ { 0x043C, 0x041C },
+ { 0x043D, 0x041D },
+ { 0x043E, 0x041E },
+ { 0x043F, 0x041F },
+ { 0x0440, 0x0420 },
+ { 0x0441, 0x0421 },
+ { 0x0442, 0x0422 },
+ { 0x0443, 0x0423 },
+ { 0x0444, 0x0424 },
+ { 0x0445, 0x0425 },
+ { 0x0446, 0x0426 },
+ { 0x0447, 0x0427 },
+ { 0x0448, 0x0428 },
+ { 0x0449, 0x0429 },
+ { 0x044A, 0x042A },
+ { 0x044B, 0x042B },
+ { 0x044C, 0x042C },
+ { 0x044D, 0x042D },
+ { 0x044E, 0x042E },
+ { 0x044F, 0x042F },
+ { 0x0451, 0x0401 },
+ { 0x0452, 0x0402 },
+ { 0x0453, 0x0403 },
+ { 0x0454, 0x0404 },
+ { 0x0455, 0x0405 },
+ { 0x0456, 0x0406 },
+ { 0x0457, 0x0407 },
+ { 0x0458, 0x0408 },
+ { 0x0459, 0x0409 },
+ { 0x045A, 0x040A },
+ { 0x045B, 0x040B },
+ { 0x045C, 0x040C },
+ { 0x045E, 0x040E },
+ { 0x045F, 0x040F },
+ { 0x0461, 0x0460 },
+ { 0x0463, 0x0462 },
+ { 0x0465, 0x0464 },
+ { 0x0467, 0x0466 },
+ { 0x0469, 0x0468 },
+ { 0x046B, 0x046A },
+ { 0x046D, 0x046C },
+ { 0x046F, 0x046E },
+ { 0x0471, 0x0470 },
+ { 0x0473, 0x0472 },
+ { 0x0475, 0x0474 },
+ { 0x0477, 0x0476 },
+ { 0x0479, 0x0478 },
+ { 0x047B, 0x047A },
+ { 0x047D, 0x047C },
+ { 0x047F, 0x047E },
+ { 0x0481, 0x0480 },
+ { 0x0491, 0x0490 },
+ { 0x0493, 0x0492 },
+ { 0x0495, 0x0494 },
+ { 0x0497, 0x0496 },
+ { 0x0499, 0x0498 },
+ { 0x049B, 0x049A },
+ { 0x049D, 0x049C },
+ { 0x049F, 0x049E },
+ { 0x04A1, 0x04A0 },
+ { 0x04A3, 0x04A2 },
+ { 0x04A5, 0x04A4 },
+ { 0x04A7, 0x04A6 },
+ { 0x04A9, 0x04A8 },
+ { 0x04AB, 0x04AA },
+ { 0x04AD, 0x04AC },
+ { 0x04AF, 0x04AE },
+ { 0x04B1, 0x04B0 },
+ { 0x04B3, 0x04B2 },
+ { 0x04B5, 0x04B4 },
+ { 0x04B7, 0x04B6 },
+ { 0x04B9, 0x04B8 },
+ { 0x04BB, 0x04BA },
+ { 0x04BD, 0x04BC },
+ { 0x04BF, 0x04BE },
+ { 0x04C2, 0x04C1 },
+ { 0x04C4, 0x04C3 },
+ { 0x04C8, 0x04C7 },
+ { 0x04CC, 0x04CB },
+ { 0x04D1, 0x04D0 },
+ { 0x04D3, 0x04D2 },
+ { 0x04D5, 0x04D4 },
+ { 0x04D7, 0x04D6 },
+ { 0x04D9, 0x04D8 },
+ { 0x04DB, 0x04DA },
+ { 0x04DD, 0x04DC },
+ { 0x04DF, 0x04DE },
+ { 0x04E1, 0x04E0 },
+ { 0x04E3, 0x04E2 },
+ { 0x04E5, 0x04E4 },
+ { 0x04E7, 0x04E6 },
+ { 0x04E9, 0x04E8 },
+ { 0x04EB, 0x04EA },
+ { 0x04EF, 0x04EE },
+ { 0x04F1, 0x04F0 },
+ { 0x04F3, 0x04F2 },
+ { 0x04F5, 0x04F4 },
+ { 0x04F9, 0x04F8 },
+ { 0x0561, 0x0531 },
+ { 0x0562, 0x0532 },
+ { 0x0563, 0x0533 },
+ { 0x0564, 0x0534 },
+ { 0x0565, 0x0535 },
+ { 0x0566, 0x0536 },
+ { 0x0567, 0x0537 },
+ { 0x0568, 0x0538 },
+ { 0x0569, 0x0539 },
+ { 0x056A, 0x053A },
+ { 0x056B, 0x053B },
+ { 0x056C, 0x053C },
+ { 0x056D, 0x053D },
+ { 0x056E, 0x053E },
+ { 0x056F, 0x053F },
+ { 0x0570, 0x0540 },
+ { 0x0571, 0x0541 },
+ { 0x0572, 0x0542 },
+ { 0x0573, 0x0543 },
+ { 0x0574, 0x0544 },
+ { 0x0575, 0x0545 },
+ { 0x0576, 0x0546 },
+ { 0x0577, 0x0547 },
+ { 0x0578, 0x0548 },
+ { 0x0579, 0x0549 },
+ { 0x057A, 0x054A },
+ { 0x057B, 0x054B },
+ { 0x057C, 0x054C },
+ { 0x057D, 0x054D },
+ { 0x057E, 0x054E },
+ { 0x057F, 0x054F },
+ { 0x0580, 0x0550 },
+ { 0x0581, 0x0551 },
+ { 0x0582, 0x0552 },
+ { 0x0583, 0x0553 },
+ { 0x0584, 0x0554 },
+ { 0x0585, 0x0555 },
+ { 0x0586, 0x0556 },
+ { 0x10D0, 0x10A0 },
+ { 0x10D1, 0x10A1 },
+ { 0x10D2, 0x10A2 },
+ { 0x10D3, 0x10A3 },
+ { 0x10D4, 0x10A4 },
+ { 0x10D5, 0x10A5 },
+ { 0x10D6, 0x10A6 },
+ { 0x10D7, 0x10A7 },
+ { 0x10D8, 0x10A8 },
+ { 0x10D9, 0x10A9 },
+ { 0x10DA, 0x10AA },
+ { 0x10DB, 0x10AB },
+ { 0x10DC, 0x10AC },
+ { 0x10DD, 0x10AD },
+ { 0x10DE, 0x10AE },
+ { 0x10DF, 0x10AF },
+ { 0x10E0, 0x10B0 },
+ { 0x10E1, 0x10B1 },
+ { 0x10E2, 0x10B2 },
+ { 0x10E3, 0x10B3 },
+ { 0x10E4, 0x10B4 },
+ { 0x10E5, 0x10B5 },
+ { 0x10E6, 0x10B6 },
+ { 0x10E7, 0x10B7 },
+ { 0x10E8, 0x10B8 },
+ { 0x10E9, 0x10B9 },
+ { 0x10EA, 0x10BA },
+ { 0x10EB, 0x10BB },
+ { 0x10EC, 0x10BC },
+ { 0x10ED, 0x10BD },
+ { 0x10EE, 0x10BE },
+ { 0x10EF, 0x10BF },
+ { 0x10F0, 0x10C0 },
+ { 0x10F1, 0x10C1 },
+ { 0x10F2, 0x10C2 },
+ { 0x10F3, 0x10C3 },
+ { 0x10F4, 0x10C4 },
+ { 0x10F5, 0x10C5 },
+ { 0x1E01, 0x1E00 },
+ { 0x1E03, 0x1E02 },
+ { 0x1E05, 0x1E04 },
+ { 0x1E07, 0x1E06 },
+ { 0x1E09, 0x1E08 },
+ { 0x1E0B, 0x1E0A },
+ { 0x1E0D, 0x1E0C },
+ { 0x1E0F, 0x1E0E },
+ { 0x1E11, 0x1E10 },
+ { 0x1E13, 0x1E12 },
+ { 0x1E15, 0x1E14 },
+ { 0x1E17, 0x1E16 },
+ { 0x1E19, 0x1E18 },
+ { 0x1E1B, 0x1E1A },
+ { 0x1E1D, 0x1E1C },
+ { 0x1E1F, 0x1E1E },
+ { 0x1E21, 0x1E20 },
+ { 0x1E23, 0x1E22 },
+ { 0x1E25, 0x1E24 },
+ { 0x1E27, 0x1E26 },
+ { 0x1E29, 0x1E28 },
+ { 0x1E2B, 0x1E2A },
+ { 0x1E2D, 0x1E2C },
+ { 0x1E2F, 0x1E2E },
+ { 0x1E31, 0x1E30 },
+ { 0x1E33, 0x1E32 },
+ { 0x1E35, 0x1E34 },
+ { 0x1E37, 0x1E36 },
+ { 0x1E39, 0x1E38 },
+ { 0x1E3B, 0x1E3A },
+ { 0x1E3D, 0x1E3C },
+ { 0x1E3F, 0x1E3E },
+ { 0x1E41, 0x1E40 },
+ { 0x1E43, 0x1E42 },
+ { 0x1E45, 0x1E44 },
+ { 0x1E47, 0x1E46 },
+ { 0x1E49, 0x1E48 },
+ { 0x1E4B, 0x1E4A },
+ { 0x1E4D, 0x1E4C },
+ { 0x1E4F, 0x1E4E },
+ { 0x1E51, 0x1E50 },
+ { 0x1E53, 0x1E52 },
+ { 0x1E55, 0x1E54 },
+ { 0x1E57, 0x1E56 },
+ { 0x1E59, 0x1E58 },
+ { 0x1E5B, 0x1E5A },
+ { 0x1E5D, 0x1E5C },
+ { 0x1E5F, 0x1E5E },
+ { 0x1E61, 0x1E60 },
+ { 0x1E63, 0x1E62 },
+ { 0x1E65, 0x1E64 },
+ { 0x1E67, 0x1E66 },
+ { 0x1E69, 0x1E68 },
+ { 0x1E6B, 0x1E6A },
+ { 0x1E6D, 0x1E6C },
+ { 0x1E6F, 0x1E6E },
+ { 0x1E71, 0x1E70 },
+ { 0x1E73, 0x1E72 },
+ { 0x1E75, 0x1E74 },
+ { 0x1E77, 0x1E76 },
+ { 0x1E79, 0x1E78 },
+ { 0x1E7B, 0x1E7A },
+ { 0x1E7D, 0x1E7C },
+ { 0x1E7F, 0x1E7E },
+ { 0x1E81, 0x1E80 },
+ { 0x1E83, 0x1E82 },
+ { 0x1E85, 0x1E84 },
+ { 0x1E87, 0x1E86 },
+ { 0x1E89, 0x1E88 },
+ { 0x1E8B, 0x1E8A },
+ { 0x1E8D, 0x1E8C },
+ { 0x1E8F, 0x1E8E },
+ { 0x1E91, 0x1E90 },
+ { 0x1E93, 0x1E92 },
+ { 0x1E95, 0x1E94 },
+ { 0x1EA1, 0x1EA0 },
+ { 0x1EA3, 0x1EA2 },
+ { 0x1EA5, 0x1EA4 },
+ { 0x1EA7, 0x1EA6 },
+ { 0x1EA9, 0x1EA8 },
+ { 0x1EAB, 0x1EAA },
+ { 0x1EAD, 0x1EAC },
+ { 0x1EAF, 0x1EAE },
+ { 0x1EB1, 0x1EB0 },
+ { 0x1EB3, 0x1EB2 },
+ { 0x1EB5, 0x1EB4 },
+ { 0x1EB7, 0x1EB6 },
+ { 0x1EB9, 0x1EB8 },
+ { 0x1EBB, 0x1EBA },
+ { 0x1EBD, 0x1EBC },
+ { 0x1EBF, 0x1EBE },
+ { 0x1EC1, 0x1EC0 },
+ { 0x1EC3, 0x1EC2 },
+ { 0x1EC5, 0x1EC4 },
+ { 0x1EC7, 0x1EC6 },
+ { 0x1EC9, 0x1EC8 },
+ { 0x1ECB, 0x1ECA },
+ { 0x1ECD, 0x1ECC },
+ { 0x1ECF, 0x1ECE },
+ { 0x1ED1, 0x1ED0 },
+ { 0x1ED3, 0x1ED2 },
+ { 0x1ED5, 0x1ED4 },
+ { 0x1ED7, 0x1ED6 },
+ { 0x1ED9, 0x1ED8 },
+ { 0x1EDB, 0x1EDA },
+ { 0x1EDD, 0x1EDC },
+ { 0x1EDF, 0x1EDE },
+ { 0x1EE1, 0x1EE0 },
+ { 0x1EE3, 0x1EE2 },
+ { 0x1EE5, 0x1EE4 },
+ { 0x1EE7, 0x1EE6 },
+ { 0x1EE9, 0x1EE8 },
+ { 0x1EEB, 0x1EEA },
+ { 0x1EED, 0x1EEC },
+ { 0x1EEF, 0x1EEE },
+ { 0x1EF1, 0x1EF0 },
+ { 0x1EF3, 0x1EF2 },
+ { 0x1EF5, 0x1EF4 },
+ { 0x1EF7, 0x1EF6 },
+ { 0x1EF9, 0x1EF8 },
+ { 0x1F00, 0x1F08 },
+ { 0x1F01, 0x1F09 },
+ { 0x1F02, 0x1F0A },
+ { 0x1F03, 0x1F0B },
+ { 0x1F04, 0x1F0C },
+ { 0x1F05, 0x1F0D },
+ { 0x1F06, 0x1F0E },
+ { 0x1F07, 0x1F0F },
+ { 0x1F10, 0x1F18 },
+ { 0x1F11, 0x1F19 },
+ { 0x1F12, 0x1F1A },
+ { 0x1F13, 0x1F1B },
+ { 0x1F14, 0x1F1C },
+ { 0x1F15, 0x1F1D },
+ { 0x1F20, 0x1F28 },
+ { 0x1F21, 0x1F29 },
+ { 0x1F22, 0x1F2A },
+ { 0x1F23, 0x1F2B },
+ { 0x1F24, 0x1F2C },
+ { 0x1F25, 0x1F2D },
+ { 0x1F26, 0x1F2E },
+ { 0x1F27, 0x1F2F },
+ { 0x1F30, 0x1F38 },
+ { 0x1F31, 0x1F39 },
+ { 0x1F32, 0x1F3A },
+ { 0x1F33, 0x1F3B },
+ { 0x1F34, 0x1F3C },
+ { 0x1F35, 0x1F3D },
+ { 0x1F36, 0x1F3E },
+ { 0x1F37, 0x1F3F },
+ { 0x1F40, 0x1F48 },
+ { 0x1F41, 0x1F49 },
+ { 0x1F42, 0x1F4A },
+ { 0x1F43, 0x1F4B },
+ { 0x1F44, 0x1F4C },
+ { 0x1F45, 0x1F4D },
+ { 0x1F51, 0x1F59 },
+ { 0x1F53, 0x1F5B },
+ { 0x1F55, 0x1F5D },
+ { 0x1F57, 0x1F5F },
+ { 0x1F60, 0x1F68 },
+ { 0x1F61, 0x1F69 },
+ { 0x1F62, 0x1F6A },
+ { 0x1F63, 0x1F6B },
+ { 0x1F64, 0x1F6C },
+ { 0x1F65, 0x1F6D },
+ { 0x1F66, 0x1F6E },
+ { 0x1F67, 0x1F6F },
+ { 0x1F80, 0x1F88 },
+ { 0x1F81, 0x1F89 },
+ { 0x1F82, 0x1F8A },
+ { 0x1F83, 0x1F8B },
+ { 0x1F84, 0x1F8C },
+ { 0x1F85, 0x1F8D },
+ { 0x1F86, 0x1F8E },
+ { 0x1F87, 0x1F8F },
+ { 0x1F90, 0x1F98 },
+ { 0x1F91, 0x1F99 },
+ { 0x1F92, 0x1F9A },
+ { 0x1F93, 0x1F9B },
+ { 0x1F94, 0x1F9C },
+ { 0x1F95, 0x1F9D },
+ { 0x1F96, 0x1F9E },
+ { 0x1F97, 0x1F9F },
+ { 0x1FA0, 0x1FA8 },
+ { 0x1FA1, 0x1FA9 },
+ { 0x1FA2, 0x1FAA },
+ { 0x1FA3, 0x1FAB },
+ { 0x1FA4, 0x1FAC },
+ { 0x1FA5, 0x1FAD },
+ { 0x1FA6, 0x1FAE },
+ { 0x1FA7, 0x1FAF },
+ { 0x1FB0, 0x1FB8 },
+ { 0x1FB1, 0x1FB9 },
+ { 0x1FD0, 0x1FD8 },
+ { 0x1FD1, 0x1FD9 },
+ { 0x1FE0, 0x1FE8 },
+ { 0x1FE1, 0x1FE9 },
+ { 0x24D0, 0x24B6 },
+ { 0x24D1, 0x24B7 },
+ { 0x24D2, 0x24B8 },
+ { 0x24D3, 0x24B9 },
+ { 0x24D4, 0x24BA },
+ { 0x24D5, 0x24BB },
+ { 0x24D6, 0x24BC },
+ { 0x24D7, 0x24BD },
+ { 0x24D8, 0x24BE },
+ { 0x24D9, 0x24BF },
+ { 0x24DA, 0x24C0 },
+ { 0x24DB, 0x24C1 },
+ { 0x24DC, 0x24C2 },
+ { 0x24DD, 0x24C3 },
+ { 0x24DE, 0x24C4 },
+ { 0x24DF, 0x24C5 },
+ { 0x24E0, 0x24C6 },
+ { 0x24E1, 0x24C7 },
+ { 0x24E2, 0x24C8 },
+ { 0x24E3, 0x24C9 },
+ { 0x24E4, 0x24CA },
+ { 0x24E5, 0x24CB },
+ { 0x24E6, 0x24CC },
+ { 0x24E7, 0x24CD },
+ { 0x24E8, 0x24CE },
+ { 0x24E9, 0x24CF },
+ { 0xFF41, 0xFF21 },
+ { 0xFF42, 0xFF22 },
+ { 0xFF43, 0xFF23 },
+ { 0xFF44, 0xFF24 },
+ { 0xFF45, 0xFF25 },
+ { 0xFF46, 0xFF26 },
+ { 0xFF47, 0xFF27 },
+ { 0xFF48, 0xFF28 },
+ { 0xFF49, 0xFF29 },
+ { 0xFF4A, 0xFF2A },
+ { 0xFF4B, 0xFF2B },
+ { 0xFF4C, 0xFF2C },
+ { 0xFF4D, 0xFF2D },
+ { 0xFF4E, 0xFF2E },
+ { 0xFF4F, 0xFF2F },
+ { 0xFF50, 0xFF30 },
+ { 0xFF51, 0xFF31 },
+ { 0xFF52, 0xFF32 },
+ { 0xFF53, 0xFF33 },
+ { 0xFF54, 0xFF34 },
+ { 0xFF55, 0xFF35 },
+ { 0xFF56, 0xFF36 },
+ { 0xFF57, 0xFF37 },
+ { 0xFF58, 0xFF38 },
+ { 0xFF59, 0xFF39 },
+ { 0xFF5A, 0xFF3A },
};
-static const int reverse_caps_table[CAPS_LEN-1][2]={
-{0x41,0x61},
-{0x42,0x62},
-{0x43,0x63},
-{0x44,0x64},
-{0x45,0x65},
-{0x46,0x66},
-{0x47,0x67},
-{0x48,0x68},
-{0x49,0x69},
-{0x4a,0x6a},
-{0x4b,0x6b},
-{0x4c,0x6c},
-{0x4d,0x6d},
-{0x4e,0x6e},
-{0x4f,0x6f},
-{0x50,0x70},
-{0x51,0x71},
-{0x52,0x72},
-{0x53,0x73},
-{0x54,0x74},
-{0x55,0x75},
-{0x56,0x76},
-{0x57,0x77},
-{0x58,0x78},
-{0x59,0x79},
-{0x5a,0x7a},
-{0xc0,0xe0},
-{0xc1,0xe1},
-{0xc2,0xe2},
-{0xc3,0xe3},
-{0xc4,0xe4},
-{0xc5,0xe5},
-{0xc6,0xe6},
-{0xc7,0xe7},
-{0xc8,0xe8},
-{0xc9,0xe9},
-{0xca,0xea},
-{0xcb,0xeb},
-{0xcc,0xec},
-{0xcd,0xed},
-{0xce,0xee},
-{0xcf,0xef},
-{0xd0,0xf0},
-{0xd1,0xf1},
-{0xd2,0xf2},
-{0xd3,0xf3},
-{0xd4,0xf4},
-{0xd5,0xf5},
-{0xd6,0xf6},
-{0xd8,0xf8},
-{0xd9,0xf9},
-{0xda,0xfa},
-{0xdb,0xfb},
-{0xdc,0xfc},
-{0xdd,0xfd},
-{0xde,0xfe},
-{0x178,0xff},
-{0x100,0x101},
-{0x102,0x103},
-{0x104,0x105},
-{0x106,0x107},
-{0x108,0x109},
-{0x10a,0x10b},
-{0x10c,0x10d},
-{0x10e,0x10f},
-{0x110,0x111},
-{0x112,0x113},
-{0x114,0x115},
-{0x116,0x117},
-{0x118,0x119},
-{0x11a,0x11b},
-{0x11c,0x11d},
-{0x11e,0x11f},
-{0x120,0x121},
-{0x122,0x123},
-{0x124,0x125},
-{0x126,0x127},
-{0x128,0x129},
-{0x12a,0x12b},
-{0x12c,0x12d},
-{0x12e,0x12f},
-//{0x49,0x131},
-{0x132,0x133},
-{0x134,0x135},
-{0x136,0x137},
-{0x139,0x13a},
-{0x13b,0x13c},
-{0x13d,0x13e},
-{0x13f,0x140},
-{0x141,0x142},
-{0x143,0x144},
-{0x145,0x146},
-{0x147,0x148},
-{0x14a,0x14b},
-{0x14c,0x14d},
-{0x14e,0x14f},
-{0x150,0x151},
-{0x152,0x153},
-{0x154,0x155},
-{0x156,0x157},
-{0x158,0x159},
-{0x15a,0x15b},
-{0x15c,0x15d},
-{0x15e,0x15f},
-{0x160,0x161},
-{0x162,0x163},
-{0x164,0x165},
-{0x166,0x167},
-{0x168,0x169},
-{0x16a,0x16b},
-{0x16c,0x16d},
-{0x16e,0x16f},
-{0x170,0x171},
-{0x172,0x173},
-{0x174,0x175},
-{0x176,0x177},
-{0x179,0x17a},
-{0x17b,0x17c},
-{0x17d,0x17e},
-{0x182,0x183},
-{0x184,0x185},
-{0x187,0x188},
-{0x18b,0x18c},
-{0x191,0x192},
-{0x198,0x199},
-{0x1a0,0x1a1},
-{0x1a2,0x1a3},
-{0x1a4,0x1a5},
-{0x1a7,0x1a8},
-{0x1ac,0x1ad},
-{0x1af,0x1b0},
-{0x1b3,0x1b4},
-{0x1b5,0x1b6},
-{0x1b8,0x1b9},
-{0x1bc,0x1bd},
-{0x1c4,0x1c6},
-{0x1c7,0x1c9},
-{0x1ca,0x1cc},
-{0x1cd,0x1ce},
-{0x1cf,0x1d0},
-{0x1d1,0x1d2},
-{0x1d3,0x1d4},
-{0x1d5,0x1d6},
-{0x1d7,0x1d8},
-{0x1d9,0x1da},
-{0x1db,0x1dc},
-{0x1de,0x1df},
-{0x1e0,0x1e1},
-{0x1e2,0x1e3},
-{0x1e4,0x1e5},
-{0x1e6,0x1e7},
-{0x1e8,0x1e9},
-{0x1ea,0x1eb},
-{0x1ec,0x1ed},
-{0x1ee,0x1ef},
-{0x1f1,0x1f3},
-{0x1f4,0x1f5},
-{0x1fa,0x1fb},
-{0x1fc,0x1fd},
-{0x1fe,0x1ff},
-{0x200,0x201},
-{0x202,0x203},
-{0x204,0x205},
-{0x206,0x207},
-{0x208,0x209},
-{0x20a,0x20b},
-{0x20c,0x20d},
-{0x20e,0x20f},
-{0x210,0x211},
-{0x212,0x213},
-{0x214,0x215},
-{0x216,0x217},
-{0x181,0x253},
-{0x186,0x254},
-{0x18a,0x257},
-{0x18e,0x258},
-{0x18f,0x259},
-{0x190,0x25b},
-{0x193,0x260},
-{0x194,0x263},
-{0x197,0x268},
-{0x196,0x269},
-{0x19c,0x26f},
-{0x19d,0x272},
-{0x19f,0x275},
-{0x1a9,0x283},
-{0x1ae,0x288},
-{0x1b1,0x28a},
-{0x1b2,0x28b},
-{0x1b7,0x292},
-{0x386,0x3ac},
-{0x388,0x3ad},
-{0x389,0x3ae},
-{0x38a,0x3af},
-{0x391,0x3b1},
-{0x392,0x3b2},
-{0x393,0x3b3},
-{0x394,0x3b4},
-{0x395,0x3b5},
-{0x396,0x3b6},
-{0x397,0x3b7},
-{0x398,0x3b8},
-{0x399,0x3b9},
-{0x39a,0x3ba},
-{0x39b,0x3bb},
-{0x39c,0x3bc},
-{0x39d,0x3bd},
-{0x39e,0x3be},
-{0x39f,0x3bf},
-{0x3a0,0x3c0},
-{0x3a1,0x3c1},
-{0x3a3,0x3c3},
-{0x3a4,0x3c4},
-{0x3a5,0x3c5},
-{0x3a6,0x3c6},
-{0x3a7,0x3c7},
-{0x3a8,0x3c8},
-{0x3a9,0x3c9},
-{0x3aa,0x3ca},
-{0x3ab,0x3cb},
-{0x38c,0x3cc},
-{0x38e,0x3cd},
-{0x38f,0x3ce},
-{0x3e2,0x3e3},
-{0x3e4,0x3e5},
-{0x3e6,0x3e7},
-{0x3e8,0x3e9},
-{0x3ea,0x3eb},
-{0x3ec,0x3ed},
-{0x3ee,0x3ef},
-{0x410,0x430},
-{0x411,0x431},
-{0x412,0x432},
-{0x413,0x433},
-{0x414,0x434},
-{0x415,0x435},
-{0x416,0x436},
-{0x417,0x437},
-{0x418,0x438},
-{0x419,0x439},
-{0x41a,0x43a},
-{0x41b,0x43b},
-{0x41c,0x43c},
-{0x41d,0x43d},
-{0x41e,0x43e},
-{0x41f,0x43f},
-{0x420,0x440},
-{0x421,0x441},
-{0x422,0x442},
-{0x423,0x443},
-{0x424,0x444},
-{0x425,0x445},
-{0x426,0x446},
-{0x427,0x447},
-{0x428,0x448},
-{0x429,0x449},
-{0x42a,0x44a},
-{0x42b,0x44b},
-{0x42c,0x44c},
-{0x42d,0x44d},
-{0x42e,0x44e},
-{0x42f,0x44f},
-{0x401,0x451},
-{0x402,0x452},
-{0x403,0x453},
-{0x404,0x454},
-{0x405,0x455},
-{0x406,0x456},
-{0x407,0x457},
-{0x408,0x458},
-{0x409,0x459},
-{0x40a,0x45a},
-{0x40b,0x45b},
-{0x40c,0x45c},
-{0x40e,0x45e},
-{0x40f,0x45f},
-{0x460,0x461},
-{0x462,0x463},
-{0x464,0x465},
-{0x466,0x467},
-{0x468,0x469},
-{0x46a,0x46b},
-{0x46c,0x46d},
-{0x46e,0x46f},
-{0x470,0x471},
-{0x472,0x473},
-{0x474,0x475},
-{0x476,0x477},
-{0x478,0x479},
-{0x47a,0x47b},
-{0x47c,0x47d},
-{0x47e,0x47f},
-{0x480,0x481},
-{0x490,0x491},
-{0x492,0x493},
-{0x494,0x495},
-{0x496,0x497},
-{0x498,0x499},
-{0x49a,0x49b},
-{0x49c,0x49d},
-{0x49e,0x49f},
-{0x4a0,0x4a1},
-{0x4a2,0x4a3},
-{0x4a4,0x4a5},
-{0x4a6,0x4a7},
-{0x4a8,0x4a9},
-{0x4aa,0x4ab},
-{0x4ac,0x4ad},
-{0x4ae,0x4af},
-{0x4b0,0x4b1},
-{0x4b2,0x4b3},
-{0x4b4,0x4b5},
-{0x4b6,0x4b7},
-{0x4b8,0x4b9},
-{0x4ba,0x4bb},
-{0x4bc,0x4bd},
-{0x4be,0x4bf},
-{0x4c1,0x4c2},
-{0x4c3,0x4c4},
-{0x4c7,0x4c8},
-{0x4cb,0x4cc},
-{0x4d0,0x4d1},
-{0x4d2,0x4d3},
-{0x4d4,0x4d5},
-{0x4d6,0x4d7},
-{0x4d8,0x4d9},
-{0x4da,0x4db},
-{0x4dc,0x4dd},
-{0x4de,0x4df},
-{0x4e0,0x4e1},
-{0x4e2,0x4e3},
-{0x4e4,0x4e5},
-{0x4e6,0x4e7},
-{0x4e8,0x4e9},
-{0x4ea,0x4eb},
-{0x4ee,0x4ef},
-{0x4f0,0x4f1},
-{0x4f2,0x4f3},
-{0x4f4,0x4f5},
-{0x4f8,0x4f9},
-{0x531,0x561},
-{0x532,0x562},
-{0x533,0x563},
-{0x534,0x564},
-{0x535,0x565},
-{0x536,0x566},
-{0x537,0x567},
-{0x538,0x568},
-{0x539,0x569},
-{0x53a,0x56a},
-{0x53b,0x56b},
-{0x53c,0x56c},
-{0x53d,0x56d},
-{0x53e,0x56e},
-{0x53f,0x56f},
-{0x540,0x570},
-{0x541,0x571},
-{0x542,0x572},
-{0x543,0x573},
-{0x544,0x574},
-{0x545,0x575},
-{0x546,0x576},
-{0x547,0x577},
-{0x548,0x578},
-{0x549,0x579},
-{0x54a,0x57a},
-{0x54b,0x57b},
-{0x54c,0x57c},
-{0x54d,0x57d},
-{0x54e,0x57e},
-{0x54f,0x57f},
-{0x550,0x580},
-{0x551,0x581},
-{0x552,0x582},
-{0x553,0x583},
-{0x554,0x584},
-{0x555,0x585},
-{0x556,0x586},
-{0x10a0,0x10d0},
-{0x10a1,0x10d1},
-{0x10a2,0x10d2},
-{0x10a3,0x10d3},
-{0x10a4,0x10d4},
-{0x10a5,0x10d5},
-{0x10a6,0x10d6},
-{0x10a7,0x10d7},
-{0x10a8,0x10d8},
-{0x10a9,0x10d9},
-{0x10aa,0x10da},
-{0x10ab,0x10db},
-{0x10ac,0x10dc},
-{0x10ad,0x10dd},
-{0x10ae,0x10de},
-{0x10af,0x10df},
-{0x10b0,0x10e0},
-{0x10b1,0x10e1},
-{0x10b2,0x10e2},
-{0x10b3,0x10e3},
-{0x10b4,0x10e4},
-{0x10b5,0x10e5},
-{0x10b6,0x10e6},
-{0x10b7,0x10e7},
-{0x10b8,0x10e8},
-{0x10b9,0x10e9},
-{0x10ba,0x10ea},
-{0x10bb,0x10eb},
-{0x10bc,0x10ec},
-{0x10bd,0x10ed},
-{0x10be,0x10ee},
-{0x10bf,0x10ef},
-{0x10c0,0x10f0},
-{0x10c1,0x10f1},
-{0x10c2,0x10f2},
-{0x10c3,0x10f3},
-{0x10c4,0x10f4},
-{0x10c5,0x10f5},
-{0x1e00,0x1e01},
-{0x1e02,0x1e03},
-{0x1e04,0x1e05},
-{0x1e06,0x1e07},
-{0x1e08,0x1e09},
-{0x1e0a,0x1e0b},
-{0x1e0c,0x1e0d},
-{0x1e0e,0x1e0f},
-{0x1e10,0x1e11},
-{0x1e12,0x1e13},
-{0x1e14,0x1e15},
-{0x1e16,0x1e17},
-{0x1e18,0x1e19},
-{0x1e1a,0x1e1b},
-{0x1e1c,0x1e1d},
-{0x1e1e,0x1e1f},
-{0x1e20,0x1e21},
-{0x1e22,0x1e23},
-{0x1e24,0x1e25},
-{0x1e26,0x1e27},
-{0x1e28,0x1e29},
-{0x1e2a,0x1e2b},
-{0x1e2c,0x1e2d},
-{0x1e2e,0x1e2f},
-{0x1e30,0x1e31},
-{0x1e32,0x1e33},
-{0x1e34,0x1e35},
-{0x1e36,0x1e37},
-{0x1e38,0x1e39},
-{0x1e3a,0x1e3b},
-{0x1e3c,0x1e3d},
-{0x1e3e,0x1e3f},
-{0x1e40,0x1e41},
-{0x1e42,0x1e43},
-{0x1e44,0x1e45},
-{0x1e46,0x1e47},
-{0x1e48,0x1e49},
-{0x1e4a,0x1e4b},
-{0x1e4c,0x1e4d},
-{0x1e4e,0x1e4f},
-{0x1e50,0x1e51},
-{0x1e52,0x1e53},
-{0x1e54,0x1e55},
-{0x1e56,0x1e57},
-{0x1e58,0x1e59},
-{0x1e5a,0x1e5b},
-{0x1e5c,0x1e5d},
-{0x1e5e,0x1e5f},
-{0x1e60,0x1e61},
-{0x1e62,0x1e63},
-{0x1e64,0x1e65},
-{0x1e66,0x1e67},
-{0x1e68,0x1e69},
-{0x1e6a,0x1e6b},
-{0x1e6c,0x1e6d},
-{0x1e6e,0x1e6f},
-{0x1e70,0x1e71},
-{0x1e72,0x1e73},
-{0x1e74,0x1e75},
-{0x1e76,0x1e77},
-{0x1e78,0x1e79},
-{0x1e7a,0x1e7b},
-{0x1e7c,0x1e7d},
-{0x1e7e,0x1e7f},
-{0x1e80,0x1e81},
-{0x1e82,0x1e83},
-{0x1e84,0x1e85},
-{0x1e86,0x1e87},
-{0x1e88,0x1e89},
-{0x1e8a,0x1e8b},
-{0x1e8c,0x1e8d},
-{0x1e8e,0x1e8f},
-{0x1e90,0x1e91},
-{0x1e92,0x1e93},
-{0x1e94,0x1e95},
-{0x1ea0,0x1ea1},
-{0x1ea2,0x1ea3},
-{0x1ea4,0x1ea5},
-{0x1ea6,0x1ea7},
-{0x1ea8,0x1ea9},
-{0x1eaa,0x1eab},
-{0x1eac,0x1ead},
-{0x1eae,0x1eaf},
-{0x1eb0,0x1eb1},
-{0x1eb2,0x1eb3},
-{0x1eb4,0x1eb5},
-{0x1eb6,0x1eb7},
-{0x1eb8,0x1eb9},
-{0x1eba,0x1ebb},
-{0x1ebc,0x1ebd},
-{0x1ebe,0x1ebf},
-{0x1ec0,0x1ec1},
-{0x1ec2,0x1ec3},
-{0x1ec4,0x1ec5},
-{0x1ec6,0x1ec7},
-{0x1ec8,0x1ec9},
-{0x1eca,0x1ecb},
-{0x1ecc,0x1ecd},
-{0x1ece,0x1ecf},
-{0x1ed0,0x1ed1},
-{0x1ed2,0x1ed3},
-{0x1ed4,0x1ed5},
-{0x1ed6,0x1ed7},
-{0x1ed8,0x1ed9},
-{0x1eda,0x1edb},
-{0x1edc,0x1edd},
-{0x1ede,0x1edf},
-{0x1ee0,0x1ee1},
-{0x1ee2,0x1ee3},
-{0x1ee4,0x1ee5},
-{0x1ee6,0x1ee7},
-{0x1ee8,0x1ee9},
-{0x1eea,0x1eeb},
-{0x1eec,0x1eed},
-{0x1eee,0x1eef},
-{0x1ef0,0x1ef1},
-{0x1ef2,0x1ef3},
-{0x1ef4,0x1ef5},
-{0x1ef6,0x1ef7},
-{0x1ef8,0x1ef9},
-{0x1f08,0x1f00},
-{0x1f09,0x1f01},
-{0x1f0a,0x1f02},
-{0x1f0b,0x1f03},
-{0x1f0c,0x1f04},
-{0x1f0d,0x1f05},
-{0x1f0e,0x1f06},
-{0x1f0f,0x1f07},
-{0x1f18,0x1f10},
-{0x1f19,0x1f11},
-{0x1f1a,0x1f12},
-{0x1f1b,0x1f13},
-{0x1f1c,0x1f14},
-{0x1f1d,0x1f15},
-{0x1f28,0x1f20},
-{0x1f29,0x1f21},
-{0x1f2a,0x1f22},
-{0x1f2b,0x1f23},
-{0x1f2c,0x1f24},
-{0x1f2d,0x1f25},
-{0x1f2e,0x1f26},
-{0x1f2f,0x1f27},
-{0x1f38,0x1f30},
-{0x1f39,0x1f31},
-{0x1f3a,0x1f32},
-{0x1f3b,0x1f33},
-{0x1f3c,0x1f34},
-{0x1f3d,0x1f35},
-{0x1f3e,0x1f36},
-{0x1f3f,0x1f37},
-{0x1f48,0x1f40},
-{0x1f49,0x1f41},
-{0x1f4a,0x1f42},
-{0x1f4b,0x1f43},
-{0x1f4c,0x1f44},
-{0x1f4d,0x1f45},
-{0x1f59,0x1f51},
-{0x1f5b,0x1f53},
-{0x1f5d,0x1f55},
-{0x1f5f,0x1f57},
-{0x1f68,0x1f60},
-{0x1f69,0x1f61},
-{0x1f6a,0x1f62},
-{0x1f6b,0x1f63},
-{0x1f6c,0x1f64},
-{0x1f6d,0x1f65},
-{0x1f6e,0x1f66},
-{0x1f6f,0x1f67},
-{0x1f88,0x1f80},
-{0x1f89,0x1f81},
-{0x1f8a,0x1f82},
-{0x1f8b,0x1f83},
-{0x1f8c,0x1f84},
-{0x1f8d,0x1f85},
-{0x1f8e,0x1f86},
-{0x1f8f,0x1f87},
-{0x1f98,0x1f90},
-{0x1f99,0x1f91},
-{0x1f9a,0x1f92},
-{0x1f9b,0x1f93},
-{0x1f9c,0x1f94},
-{0x1f9d,0x1f95},
-{0x1f9e,0x1f96},
-{0x1f9f,0x1f97},
-{0x1fa8,0x1fa0},
-{0x1fa9,0x1fa1},
-{0x1faa,0x1fa2},
-{0x1fab,0x1fa3},
-{0x1fac,0x1fa4},
-{0x1fad,0x1fa5},
-{0x1fae,0x1fa6},
-{0x1faf,0x1fa7},
-{0x1fb8,0x1fb0},
-{0x1fb9,0x1fb1},
-{0x1fd8,0x1fd0},
-{0x1fd9,0x1fd1},
-{0x1fe8,0x1fe0},
-{0x1fe9,0x1fe1},
-{0x24b6,0x24d0},
-{0x24b7,0x24d1},
-{0x24b8,0x24d2},
-{0x24b9,0x24d3},
-{0x24ba,0x24d4},
-{0x24bb,0x24d5},
-{0x24bc,0x24d6},
-{0x24bd,0x24d7},
-{0x24be,0x24d8},
-{0x24bf,0x24d9},
-{0x24c0,0x24da},
-{0x24c1,0x24db},
-{0x24c2,0x24dc},
-{0x24c3,0x24dd},
-{0x24c4,0x24de},
-{0x24c5,0x24df},
-{0x24c6,0x24e0},
-{0x24c7,0x24e1},
-{0x24c8,0x24e2},
-{0x24c9,0x24e3},
-{0x24ca,0x24e4},
-{0x24cb,0x24e5},
-{0x24cc,0x24e6},
-{0x24cd,0x24e7},
-{0x24ce,0x24e8},
-{0x24cf,0x24e9},
-{0xff21,0xff41},
-{0xff22,0xff42},
-{0xff23,0xff43},
-{0xff24,0xff44},
-{0xff25,0xff45},
-{0xff26,0xff46},
-{0xff27,0xff47},
-{0xff28,0xff48},
-{0xff29,0xff49},
-{0xff2a,0xff4a},
-{0xff2b,0xff4b},
-{0xff2c,0xff4c},
-{0xff2d,0xff4d},
-{0xff2e,0xff4e},
-{0xff2f,0xff4f},
-{0xff30,0xff50},
-{0xff31,0xff51},
-{0xff32,0xff52},
-{0xff33,0xff53},
-{0xff34,0xff54},
-{0xff35,0xff55},
-{0xff36,0xff56},
-{0xff37,0xff57},
-{0xff38,0xff58},
-{0xff39,0xff59},
-{0xff3a,0xff5a}
+static const int reverse_caps_table[CAPS_LEN - 1][2] = {
+ { 0x41, 0x61 },
+ { 0x42, 0x62 },
+ { 0x43, 0x63 },
+ { 0x44, 0x64 },
+ { 0x45, 0x65 },
+ { 0x46, 0x66 },
+ { 0x47, 0x67 },
+ { 0x48, 0x68 },
+ { 0x49, 0x69 },
+ { 0x4a, 0x6a },
+ { 0x4b, 0x6b },
+ { 0x4c, 0x6c },
+ { 0x4d, 0x6d },
+ { 0x4e, 0x6e },
+ { 0x4f, 0x6f },
+ { 0x50, 0x70 },
+ { 0x51, 0x71 },
+ { 0x52, 0x72 },
+ { 0x53, 0x73 },
+ { 0x54, 0x74 },
+ { 0x55, 0x75 },
+ { 0x56, 0x76 },
+ { 0x57, 0x77 },
+ { 0x58, 0x78 },
+ { 0x59, 0x79 },
+ { 0x5a, 0x7a },
+ { 0xc0, 0xe0 },
+ { 0xc1, 0xe1 },
+ { 0xc2, 0xe2 },
+ { 0xc3, 0xe3 },
+ { 0xc4, 0xe4 },
+ { 0xc5, 0xe5 },
+ { 0xc6, 0xe6 },
+ { 0xc7, 0xe7 },
+ { 0xc8, 0xe8 },
+ { 0xc9, 0xe9 },
+ { 0xca, 0xea },
+ { 0xcb, 0xeb },
+ { 0xcc, 0xec },
+ { 0xcd, 0xed },
+ { 0xce, 0xee },
+ { 0xcf, 0xef },
+ { 0xd0, 0xf0 },
+ { 0xd1, 0xf1 },
+ { 0xd2, 0xf2 },
+ { 0xd3, 0xf3 },
+ { 0xd4, 0xf4 },
+ { 0xd5, 0xf5 },
+ { 0xd6, 0xf6 },
+ { 0xd8, 0xf8 },
+ { 0xd9, 0xf9 },
+ { 0xda, 0xfa },
+ { 0xdb, 0xfb },
+ { 0xdc, 0xfc },
+ { 0xdd, 0xfd },
+ { 0xde, 0xfe },
+ { 0x178, 0xff },
+ { 0x100, 0x101 },
+ { 0x102, 0x103 },
+ { 0x104, 0x105 },
+ { 0x106, 0x107 },
+ { 0x108, 0x109 },
+ { 0x10a, 0x10b },
+ { 0x10c, 0x10d },
+ { 0x10e, 0x10f },
+ { 0x110, 0x111 },
+ { 0x112, 0x113 },
+ { 0x114, 0x115 },
+ { 0x116, 0x117 },
+ { 0x118, 0x119 },
+ { 0x11a, 0x11b },
+ { 0x11c, 0x11d },
+ { 0x11e, 0x11f },
+ { 0x120, 0x121 },
+ { 0x122, 0x123 },
+ { 0x124, 0x125 },
+ { 0x126, 0x127 },
+ { 0x128, 0x129 },
+ { 0x12a, 0x12b },
+ { 0x12c, 0x12d },
+ { 0x12e, 0x12f },
+ //{0x49,0x131},
+ { 0x132, 0x133 },
+ { 0x134, 0x135 },
+ { 0x136, 0x137 },
+ { 0x139, 0x13a },
+ { 0x13b, 0x13c },
+ { 0x13d, 0x13e },
+ { 0x13f, 0x140 },
+ { 0x141, 0x142 },
+ { 0x143, 0x144 },
+ { 0x145, 0x146 },
+ { 0x147, 0x148 },
+ { 0x14a, 0x14b },
+ { 0x14c, 0x14d },
+ { 0x14e, 0x14f },
+ { 0x150, 0x151 },
+ { 0x152, 0x153 },
+ { 0x154, 0x155 },
+ { 0x156, 0x157 },
+ { 0x158, 0x159 },
+ { 0x15a, 0x15b },
+ { 0x15c, 0x15d },
+ { 0x15e, 0x15f },
+ { 0x160, 0x161 },
+ { 0x162, 0x163 },
+ { 0x164, 0x165 },
+ { 0x166, 0x167 },
+ { 0x168, 0x169 },
+ { 0x16a, 0x16b },
+ { 0x16c, 0x16d },
+ { 0x16e, 0x16f },
+ { 0x170, 0x171 },
+ { 0x172, 0x173 },
+ { 0x174, 0x175 },
+ { 0x176, 0x177 },
+ { 0x179, 0x17a },
+ { 0x17b, 0x17c },
+ { 0x17d, 0x17e },
+ { 0x182, 0x183 },
+ { 0x184, 0x185 },
+ { 0x187, 0x188 },
+ { 0x18b, 0x18c },
+ { 0x191, 0x192 },
+ { 0x198, 0x199 },
+ { 0x1a0, 0x1a1 },
+ { 0x1a2, 0x1a3 },
+ { 0x1a4, 0x1a5 },
+ { 0x1a7, 0x1a8 },
+ { 0x1ac, 0x1ad },
+ { 0x1af, 0x1b0 },
+ { 0x1b3, 0x1b4 },
+ { 0x1b5, 0x1b6 },
+ { 0x1b8, 0x1b9 },
+ { 0x1bc, 0x1bd },
+ { 0x1c4, 0x1c6 },
+ { 0x1c7, 0x1c9 },
+ { 0x1ca, 0x1cc },
+ { 0x1cd, 0x1ce },
+ { 0x1cf, 0x1d0 },
+ { 0x1d1, 0x1d2 },
+ { 0x1d3, 0x1d4 },
+ { 0x1d5, 0x1d6 },
+ { 0x1d7, 0x1d8 },
+ { 0x1d9, 0x1da },
+ { 0x1db, 0x1dc },
+ { 0x1de, 0x1df },
+ { 0x1e0, 0x1e1 },
+ { 0x1e2, 0x1e3 },
+ { 0x1e4, 0x1e5 },
+ { 0x1e6, 0x1e7 },
+ { 0x1e8, 0x1e9 },
+ { 0x1ea, 0x1eb },
+ { 0x1ec, 0x1ed },
+ { 0x1ee, 0x1ef },
+ { 0x1f1, 0x1f3 },
+ { 0x1f4, 0x1f5 },
+ { 0x1fa, 0x1fb },
+ { 0x1fc, 0x1fd },
+ { 0x1fe, 0x1ff },
+ { 0x200, 0x201 },
+ { 0x202, 0x203 },
+ { 0x204, 0x205 },
+ { 0x206, 0x207 },
+ { 0x208, 0x209 },
+ { 0x20a, 0x20b },
+ { 0x20c, 0x20d },
+ { 0x20e, 0x20f },
+ { 0x210, 0x211 },
+ { 0x212, 0x213 },
+ { 0x214, 0x215 },
+ { 0x216, 0x217 },
+ { 0x181, 0x253 },
+ { 0x186, 0x254 },
+ { 0x18a, 0x257 },
+ { 0x18e, 0x258 },
+ { 0x18f, 0x259 },
+ { 0x190, 0x25b },
+ { 0x193, 0x260 },
+ { 0x194, 0x263 },
+ { 0x197, 0x268 },
+ { 0x196, 0x269 },
+ { 0x19c, 0x26f },
+ { 0x19d, 0x272 },
+ { 0x19f, 0x275 },
+ { 0x1a9, 0x283 },
+ { 0x1ae, 0x288 },
+ { 0x1b1, 0x28a },
+ { 0x1b2, 0x28b },
+ { 0x1b7, 0x292 },
+ { 0x386, 0x3ac },
+ { 0x388, 0x3ad },
+ { 0x389, 0x3ae },
+ { 0x38a, 0x3af },
+ { 0x391, 0x3b1 },
+ { 0x392, 0x3b2 },
+ { 0x393, 0x3b3 },
+ { 0x394, 0x3b4 },
+ { 0x395, 0x3b5 },
+ { 0x396, 0x3b6 },
+ { 0x397, 0x3b7 },
+ { 0x398, 0x3b8 },
+ { 0x399, 0x3b9 },
+ { 0x39a, 0x3ba },
+ { 0x39b, 0x3bb },
+ { 0x39c, 0x3bc },
+ { 0x39d, 0x3bd },
+ { 0x39e, 0x3be },
+ { 0x39f, 0x3bf },
+ { 0x3a0, 0x3c0 },
+ { 0x3a1, 0x3c1 },
+ { 0x3a3, 0x3c3 },
+ { 0x3a4, 0x3c4 },
+ { 0x3a5, 0x3c5 },
+ { 0x3a6, 0x3c6 },
+ { 0x3a7, 0x3c7 },
+ { 0x3a8, 0x3c8 },
+ { 0x3a9, 0x3c9 },
+ { 0x3aa, 0x3ca },
+ { 0x3ab, 0x3cb },
+ { 0x38c, 0x3cc },
+ { 0x38e, 0x3cd },
+ { 0x38f, 0x3ce },
+ { 0x3e2, 0x3e3 },
+ { 0x3e4, 0x3e5 },
+ { 0x3e6, 0x3e7 },
+ { 0x3e8, 0x3e9 },
+ { 0x3ea, 0x3eb },
+ { 0x3ec, 0x3ed },
+ { 0x3ee, 0x3ef },
+ { 0x410, 0x430 },
+ { 0x411, 0x431 },
+ { 0x412, 0x432 },
+ { 0x413, 0x433 },
+ { 0x414, 0x434 },
+ { 0x415, 0x435 },
+ { 0x416, 0x436 },
+ { 0x417, 0x437 },
+ { 0x418, 0x438 },
+ { 0x419, 0x439 },
+ { 0x41a, 0x43a },
+ { 0x41b, 0x43b },
+ { 0x41c, 0x43c },
+ { 0x41d, 0x43d },
+ { 0x41e, 0x43e },
+ { 0x41f, 0x43f },
+ { 0x420, 0x440 },
+ { 0x421, 0x441 },
+ { 0x422, 0x442 },
+ { 0x423, 0x443 },
+ { 0x424, 0x444 },
+ { 0x425, 0x445 },
+ { 0x426, 0x446 },
+ { 0x427, 0x447 },
+ { 0x428, 0x448 },
+ { 0x429, 0x449 },
+ { 0x42a, 0x44a },
+ { 0x42b, 0x44b },
+ { 0x42c, 0x44c },
+ { 0x42d, 0x44d },
+ { 0x42e, 0x44e },
+ { 0x42f, 0x44f },
+ { 0x401, 0x451 },
+ { 0x402, 0x452 },
+ { 0x403, 0x453 },
+ { 0x404, 0x454 },
+ { 0x405, 0x455 },
+ { 0x406, 0x456 },
+ { 0x407, 0x457 },
+ { 0x408, 0x458 },
+ { 0x409, 0x459 },
+ { 0x40a, 0x45a },
+ { 0x40b, 0x45b },
+ { 0x40c, 0x45c },
+ { 0x40e, 0x45e },
+ { 0x40f, 0x45f },
+ { 0x460, 0x461 },
+ { 0x462, 0x463 },
+ { 0x464, 0x465 },
+ { 0x466, 0x467 },
+ { 0x468, 0x469 },
+ { 0x46a, 0x46b },
+ { 0x46c, 0x46d },
+ { 0x46e, 0x46f },
+ { 0x470, 0x471 },
+ { 0x472, 0x473 },
+ { 0x474, 0x475 },
+ { 0x476, 0x477 },
+ { 0x478, 0x479 },
+ { 0x47a, 0x47b },
+ { 0x47c, 0x47d },
+ { 0x47e, 0x47f },
+ { 0x480, 0x481 },
+ { 0x490, 0x491 },
+ { 0x492, 0x493 },
+ { 0x494, 0x495 },
+ { 0x496, 0x497 },
+ { 0x498, 0x499 },
+ { 0x49a, 0x49b },
+ { 0x49c, 0x49d },
+ { 0x49e, 0x49f },
+ { 0x4a0, 0x4a1 },
+ { 0x4a2, 0x4a3 },
+ { 0x4a4, 0x4a5 },
+ { 0x4a6, 0x4a7 },
+ { 0x4a8, 0x4a9 },
+ { 0x4aa, 0x4ab },
+ { 0x4ac, 0x4ad },
+ { 0x4ae, 0x4af },
+ { 0x4b0, 0x4b1 },
+ { 0x4b2, 0x4b3 },
+ { 0x4b4, 0x4b5 },
+ { 0x4b6, 0x4b7 },
+ { 0x4b8, 0x4b9 },
+ { 0x4ba, 0x4bb },
+ { 0x4bc, 0x4bd },
+ { 0x4be, 0x4bf },
+ { 0x4c1, 0x4c2 },
+ { 0x4c3, 0x4c4 },
+ { 0x4c7, 0x4c8 },
+ { 0x4cb, 0x4cc },
+ { 0x4d0, 0x4d1 },
+ { 0x4d2, 0x4d3 },
+ { 0x4d4, 0x4d5 },
+ { 0x4d6, 0x4d7 },
+ { 0x4d8, 0x4d9 },
+ { 0x4da, 0x4db },
+ { 0x4dc, 0x4dd },
+ { 0x4de, 0x4df },
+ { 0x4e0, 0x4e1 },
+ { 0x4e2, 0x4e3 },
+ { 0x4e4, 0x4e5 },
+ { 0x4e6, 0x4e7 },
+ { 0x4e8, 0x4e9 },
+ { 0x4ea, 0x4eb },
+ { 0x4ee, 0x4ef },
+ { 0x4f0, 0x4f1 },
+ { 0x4f2, 0x4f3 },
+ { 0x4f4, 0x4f5 },
+ { 0x4f8, 0x4f9 },
+ { 0x531, 0x561 },
+ { 0x532, 0x562 },
+ { 0x533, 0x563 },
+ { 0x534, 0x564 },
+ { 0x535, 0x565 },
+ { 0x536, 0x566 },
+ { 0x537, 0x567 },
+ { 0x538, 0x568 },
+ { 0x539, 0x569 },
+ { 0x53a, 0x56a },
+ { 0x53b, 0x56b },
+ { 0x53c, 0x56c },
+ { 0x53d, 0x56d },
+ { 0x53e, 0x56e },
+ { 0x53f, 0x56f },
+ { 0x540, 0x570 },
+ { 0x541, 0x571 },
+ { 0x542, 0x572 },
+ { 0x543, 0x573 },
+ { 0x544, 0x574 },
+ { 0x545, 0x575 },
+ { 0x546, 0x576 },
+ { 0x547, 0x577 },
+ { 0x548, 0x578 },
+ { 0x549, 0x579 },
+ { 0x54a, 0x57a },
+ { 0x54b, 0x57b },
+ { 0x54c, 0x57c },
+ { 0x54d, 0x57d },
+ { 0x54e, 0x57e },
+ { 0x54f, 0x57f },
+ { 0x550, 0x580 },
+ { 0x551, 0x581 },
+ { 0x552, 0x582 },
+ { 0x553, 0x583 },
+ { 0x554, 0x584 },
+ { 0x555, 0x585 },
+ { 0x556, 0x586 },
+ { 0x10a0, 0x10d0 },
+ { 0x10a1, 0x10d1 },
+ { 0x10a2, 0x10d2 },
+ { 0x10a3, 0x10d3 },
+ { 0x10a4, 0x10d4 },
+ { 0x10a5, 0x10d5 },
+ { 0x10a6, 0x10d6 },
+ { 0x10a7, 0x10d7 },
+ { 0x10a8, 0x10d8 },
+ { 0x10a9, 0x10d9 },
+ { 0x10aa, 0x10da },
+ { 0x10ab, 0x10db },
+ { 0x10ac, 0x10dc },
+ { 0x10ad, 0x10dd },
+ { 0x10ae, 0x10de },
+ { 0x10af, 0x10df },
+ { 0x10b0, 0x10e0 },
+ { 0x10b1, 0x10e1 },
+ { 0x10b2, 0x10e2 },
+ { 0x10b3, 0x10e3 },
+ { 0x10b4, 0x10e4 },
+ { 0x10b5, 0x10e5 },
+ { 0x10b6, 0x10e6 },
+ { 0x10b7, 0x10e7 },
+ { 0x10b8, 0x10e8 },
+ { 0x10b9, 0x10e9 },
+ { 0x10ba, 0x10ea },
+ { 0x10bb, 0x10eb },
+ { 0x10bc, 0x10ec },
+ { 0x10bd, 0x10ed },
+ { 0x10be, 0x10ee },
+ { 0x10bf, 0x10ef },
+ { 0x10c0, 0x10f0 },
+ { 0x10c1, 0x10f1 },
+ { 0x10c2, 0x10f2 },
+ { 0x10c3, 0x10f3 },
+ { 0x10c4, 0x10f4 },
+ { 0x10c5, 0x10f5 },
+ { 0x1e00, 0x1e01 },
+ { 0x1e02, 0x1e03 },
+ { 0x1e04, 0x1e05 },
+ { 0x1e06, 0x1e07 },
+ { 0x1e08, 0x1e09 },
+ { 0x1e0a, 0x1e0b },
+ { 0x1e0c, 0x1e0d },
+ { 0x1e0e, 0x1e0f },
+ { 0x1e10, 0x1e11 },
+ { 0x1e12, 0x1e13 },
+ { 0x1e14, 0x1e15 },
+ { 0x1e16, 0x1e17 },
+ { 0x1e18, 0x1e19 },
+ { 0x1e1a, 0x1e1b },
+ { 0x1e1c, 0x1e1d },
+ { 0x1e1e, 0x1e1f },
+ { 0x1e20, 0x1e21 },
+ { 0x1e22, 0x1e23 },
+ { 0x1e24, 0x1e25 },
+ { 0x1e26, 0x1e27 },
+ { 0x1e28, 0x1e29 },
+ { 0x1e2a, 0x1e2b },
+ { 0x1e2c, 0x1e2d },
+ { 0x1e2e, 0x1e2f },
+ { 0x1e30, 0x1e31 },
+ { 0x1e32, 0x1e33 },
+ { 0x1e34, 0x1e35 },
+ { 0x1e36, 0x1e37 },
+ { 0x1e38, 0x1e39 },
+ { 0x1e3a, 0x1e3b },
+ { 0x1e3c, 0x1e3d },
+ { 0x1e3e, 0x1e3f },
+ { 0x1e40, 0x1e41 },
+ { 0x1e42, 0x1e43 },
+ { 0x1e44, 0x1e45 },
+ { 0x1e46, 0x1e47 },
+ { 0x1e48, 0x1e49 },
+ { 0x1e4a, 0x1e4b },
+ { 0x1e4c, 0x1e4d },
+ { 0x1e4e, 0x1e4f },
+ { 0x1e50, 0x1e51 },
+ { 0x1e52, 0x1e53 },
+ { 0x1e54, 0x1e55 },
+ { 0x1e56, 0x1e57 },
+ { 0x1e58, 0x1e59 },
+ { 0x1e5a, 0x1e5b },
+ { 0x1e5c, 0x1e5d },
+ { 0x1e5e, 0x1e5f },
+ { 0x1e60, 0x1e61 },
+ { 0x1e62, 0x1e63 },
+ { 0x1e64, 0x1e65 },
+ { 0x1e66, 0x1e67 },
+ { 0x1e68, 0x1e69 },
+ { 0x1e6a, 0x1e6b },
+ { 0x1e6c, 0x1e6d },
+ { 0x1e6e, 0x1e6f },
+ { 0x1e70, 0x1e71 },
+ { 0x1e72, 0x1e73 },
+ { 0x1e74, 0x1e75 },
+ { 0x1e76, 0x1e77 },
+ { 0x1e78, 0x1e79 },
+ { 0x1e7a, 0x1e7b },
+ { 0x1e7c, 0x1e7d },
+ { 0x1e7e, 0x1e7f },
+ { 0x1e80, 0x1e81 },
+ { 0x1e82, 0x1e83 },
+ { 0x1e84, 0x1e85 },
+ { 0x1e86, 0x1e87 },
+ { 0x1e88, 0x1e89 },
+ { 0x1e8a, 0x1e8b },
+ { 0x1e8c, 0x1e8d },
+ { 0x1e8e, 0x1e8f },
+ { 0x1e90, 0x1e91 },
+ { 0x1e92, 0x1e93 },
+ { 0x1e94, 0x1e95 },
+ { 0x1ea0, 0x1ea1 },
+ { 0x1ea2, 0x1ea3 },
+ { 0x1ea4, 0x1ea5 },
+ { 0x1ea6, 0x1ea7 },
+ { 0x1ea8, 0x1ea9 },
+ { 0x1eaa, 0x1eab },
+ { 0x1eac, 0x1ead },
+ { 0x1eae, 0x1eaf },
+ { 0x1eb0, 0x1eb1 },
+ { 0x1eb2, 0x1eb3 },
+ { 0x1eb4, 0x1eb5 },
+ { 0x1eb6, 0x1eb7 },
+ { 0x1eb8, 0x1eb9 },
+ { 0x1eba, 0x1ebb },
+ { 0x1ebc, 0x1ebd },
+ { 0x1ebe, 0x1ebf },
+ { 0x1ec0, 0x1ec1 },
+ { 0x1ec2, 0x1ec3 },
+ { 0x1ec4, 0x1ec5 },
+ { 0x1ec6, 0x1ec7 },
+ { 0x1ec8, 0x1ec9 },
+ { 0x1eca, 0x1ecb },
+ { 0x1ecc, 0x1ecd },
+ { 0x1ece, 0x1ecf },
+ { 0x1ed0, 0x1ed1 },
+ { 0x1ed2, 0x1ed3 },
+ { 0x1ed4, 0x1ed5 },
+ { 0x1ed6, 0x1ed7 },
+ { 0x1ed8, 0x1ed9 },
+ { 0x1eda, 0x1edb },
+ { 0x1edc, 0x1edd },
+ { 0x1ede, 0x1edf },
+ { 0x1ee0, 0x1ee1 },
+ { 0x1ee2, 0x1ee3 },
+ { 0x1ee4, 0x1ee5 },
+ { 0x1ee6, 0x1ee7 },
+ { 0x1ee8, 0x1ee9 },
+ { 0x1eea, 0x1eeb },
+ { 0x1eec, 0x1eed },
+ { 0x1eee, 0x1eef },
+ { 0x1ef0, 0x1ef1 },
+ { 0x1ef2, 0x1ef3 },
+ { 0x1ef4, 0x1ef5 },
+ { 0x1ef6, 0x1ef7 },
+ { 0x1ef8, 0x1ef9 },
+ { 0x1f08, 0x1f00 },
+ { 0x1f09, 0x1f01 },
+ { 0x1f0a, 0x1f02 },
+ { 0x1f0b, 0x1f03 },
+ { 0x1f0c, 0x1f04 },
+ { 0x1f0d, 0x1f05 },
+ { 0x1f0e, 0x1f06 },
+ { 0x1f0f, 0x1f07 },
+ { 0x1f18, 0x1f10 },
+ { 0x1f19, 0x1f11 },
+ { 0x1f1a, 0x1f12 },
+ { 0x1f1b, 0x1f13 },
+ { 0x1f1c, 0x1f14 },
+ { 0x1f1d, 0x1f15 },
+ { 0x1f28, 0x1f20 },
+ { 0x1f29, 0x1f21 },
+ { 0x1f2a, 0x1f22 },
+ { 0x1f2b, 0x1f23 },
+ { 0x1f2c, 0x1f24 },
+ { 0x1f2d, 0x1f25 },
+ { 0x1f2e, 0x1f26 },
+ { 0x1f2f, 0x1f27 },
+ { 0x1f38, 0x1f30 },
+ { 0x1f39, 0x1f31 },
+ { 0x1f3a, 0x1f32 },
+ { 0x1f3b, 0x1f33 },
+ { 0x1f3c, 0x1f34 },
+ { 0x1f3d, 0x1f35 },
+ { 0x1f3e, 0x1f36 },
+ { 0x1f3f, 0x1f37 },
+ { 0x1f48, 0x1f40 },
+ { 0x1f49, 0x1f41 },
+ { 0x1f4a, 0x1f42 },
+ { 0x1f4b, 0x1f43 },
+ { 0x1f4c, 0x1f44 },
+ { 0x1f4d, 0x1f45 },
+ { 0x1f59, 0x1f51 },
+ { 0x1f5b, 0x1f53 },
+ { 0x1f5d, 0x1f55 },
+ { 0x1f5f, 0x1f57 },
+ { 0x1f68, 0x1f60 },
+ { 0x1f69, 0x1f61 },
+ { 0x1f6a, 0x1f62 },
+ { 0x1f6b, 0x1f63 },
+ { 0x1f6c, 0x1f64 },
+ { 0x1f6d, 0x1f65 },
+ { 0x1f6e, 0x1f66 },
+ { 0x1f6f, 0x1f67 },
+ { 0x1f88, 0x1f80 },
+ { 0x1f89, 0x1f81 },
+ { 0x1f8a, 0x1f82 },
+ { 0x1f8b, 0x1f83 },
+ { 0x1f8c, 0x1f84 },
+ { 0x1f8d, 0x1f85 },
+ { 0x1f8e, 0x1f86 },
+ { 0x1f8f, 0x1f87 },
+ { 0x1f98, 0x1f90 },
+ { 0x1f99, 0x1f91 },
+ { 0x1f9a, 0x1f92 },
+ { 0x1f9b, 0x1f93 },
+ { 0x1f9c, 0x1f94 },
+ { 0x1f9d, 0x1f95 },
+ { 0x1f9e, 0x1f96 },
+ { 0x1f9f, 0x1f97 },
+ { 0x1fa8, 0x1fa0 },
+ { 0x1fa9, 0x1fa1 },
+ { 0x1faa, 0x1fa2 },
+ { 0x1fab, 0x1fa3 },
+ { 0x1fac, 0x1fa4 },
+ { 0x1fad, 0x1fa5 },
+ { 0x1fae, 0x1fa6 },
+ { 0x1faf, 0x1fa7 },
+ { 0x1fb8, 0x1fb0 },
+ { 0x1fb9, 0x1fb1 },
+ { 0x1fd8, 0x1fd0 },
+ { 0x1fd9, 0x1fd1 },
+ { 0x1fe8, 0x1fe0 },
+ { 0x1fe9, 0x1fe1 },
+ { 0x24b6, 0x24d0 },
+ { 0x24b7, 0x24d1 },
+ { 0x24b8, 0x24d2 },
+ { 0x24b9, 0x24d3 },
+ { 0x24ba, 0x24d4 },
+ { 0x24bb, 0x24d5 },
+ { 0x24bc, 0x24d6 },
+ { 0x24bd, 0x24d7 },
+ { 0x24be, 0x24d8 },
+ { 0x24bf, 0x24d9 },
+ { 0x24c0, 0x24da },
+ { 0x24c1, 0x24db },
+ { 0x24c2, 0x24dc },
+ { 0x24c3, 0x24dd },
+ { 0x24c4, 0x24de },
+ { 0x24c5, 0x24df },
+ { 0x24c6, 0x24e0 },
+ { 0x24c7, 0x24e1 },
+ { 0x24c8, 0x24e2 },
+ { 0x24c9, 0x24e3 },
+ { 0x24ca, 0x24e4 },
+ { 0x24cb, 0x24e5 },
+ { 0x24cc, 0x24e6 },
+ { 0x24cd, 0x24e7 },
+ { 0x24ce, 0x24e8 },
+ { 0x24cf, 0x24e9 },
+ { 0xff21, 0xff41 },
+ { 0xff22, 0xff42 },
+ { 0xff23, 0xff43 },
+ { 0xff24, 0xff44 },
+ { 0xff25, 0xff45 },
+ { 0xff26, 0xff46 },
+ { 0xff27, 0xff47 },
+ { 0xff28, 0xff48 },
+ { 0xff29, 0xff49 },
+ { 0xff2a, 0xff4a },
+ { 0xff2b, 0xff4b },
+ { 0xff2c, 0xff4c },
+ { 0xff2d, 0xff4d },
+ { 0xff2e, 0xff4e },
+ { 0xff2f, 0xff4f },
+ { 0xff30, 0xff50 },
+ { 0xff31, 0xff51 },
+ { 0xff32, 0xff52 },
+ { 0xff33, 0xff53 },
+ { 0xff34, 0xff54 },
+ { 0xff35, 0xff55 },
+ { 0xff36, 0xff56 },
+ { 0xff37, 0xff57 },
+ { 0xff38, 0xff58 },
+ { 0xff39, 0xff59 },
+ { 0xff3a, 0xff5a }
};
-static int _find_upper(int ch) {
-
+static int _find_upper(int ch) {
int low = 0;
- int high = CAPS_LEN -1;
+ int high = CAPS_LEN - 1;
int middle;
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( ch < caps_table[ middle][0] ) {
+ if (ch < caps_table[middle][0]) {
high = middle - 1; //search low end of array
- } else if ( caps_table[middle][0] < ch) {
+ } else if (caps_table[middle][0] < ch) {
low = middle + 1; //search high end of array
} else {
return caps_table[middle][1];
@@ -1393,21 +1391,18 @@ static int _find_upper(int ch) {
return ch;
}
-
-static int _find_lower(int ch) {
-
+static int _find_lower(int ch) {
int low = 0;
- int high = CAPS_LEN -2;
+ int high = CAPS_LEN - 2;
int middle;
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( ch < reverse_caps_table[ middle][0] ) {
+ if (ch < reverse_caps_table[middle][0]) {
high = middle - 1; //search low end of array
- } else if ( reverse_caps_table[middle][0] < ch) {
+ } else if (reverse_caps_table[middle][0] < ch) {
low = middle + 1; //search high end of array
} else {
return reverse_caps_table[middle][1];
diff --git a/core/undo_redo.cpp b/core/undo_redo.cpp
index f91f1aa14b..76eee40b9c 100644
--- a/core/undo_redo.cpp
+++ b/core/undo_redo.cpp
@@ -32,14 +32,14 @@
void UndoRedo::_discard_redo() {
- if (current_action==actions.size()-1)
+ if (current_action == actions.size() - 1)
return;
- for(int i=current_action+1;i<actions.size();i++) {
+ for (int i = current_action + 1; i < actions.size(); i++) {
- for (List<Operation>::Element *E=actions[i].do_ops.front();E;E=E->next()) {
+ for (List<Operation>::Element *E = actions[i].do_ops.front(); E; E = E->next()) {
- if (E->get().type==Operation::TYPE_REFERENCE) {
+ if (E->get().type == Operation::TYPE_REFERENCE) {
Object *obj = ObjectDB::get_instance(E->get().object);
if (obj)
@@ -49,169 +49,163 @@ void UndoRedo::_discard_redo() {
//ERASE do data
}
- actions.resize(current_action+1);
-
+ actions.resize(current_action + 1);
}
-void UndoRedo::create_action(const String& p_name,MergeMode p_mode) {
+void UndoRedo::create_action(const String &p_name, MergeMode p_mode) {
uint32_t ticks = OS::get_singleton()->get_ticks_msec();
- if (action_level==0) {
+ if (action_level == 0) {
_discard_redo();
// Check if the merge operation is valid
- if (p_mode!=MERGE_DISABLE && actions.size() && actions[actions.size()-1].name==p_name && actions[actions.size()-1].last_tick+800 > ticks) {
+ if (p_mode != MERGE_DISABLE && actions.size() && actions[actions.size() - 1].name == p_name && actions[actions.size() - 1].last_tick + 800 > ticks) {
- current_action=actions.size()-2;
+ current_action = actions.size() - 2;
- if (p_mode==MERGE_ENDS) {
+ if (p_mode == MERGE_ENDS) {
// Clear all do ops from last action, and delete all object references
- List<Operation>::Element *E=actions[current_action+1].do_ops.front();
+ List<Operation>::Element *E = actions[current_action + 1].do_ops.front();
while (E) {
- if (E->get().type==Operation::TYPE_REFERENCE) {
+ if (E->get().type == Operation::TYPE_REFERENCE) {
- Object *obj=ObjectDB::get_instance(E->get().object);
+ Object *obj = ObjectDB::get_instance(E->get().object);
if (obj)
memdelete(obj);
}
- E=E->next();
- actions[current_action+1].do_ops.pop_front();
+ E = E->next();
+ actions[current_action + 1].do_ops.pop_front();
}
}
- actions[actions.size()-1].last_tick=ticks;
+ actions[actions.size() - 1].last_tick = ticks;
- merge_mode=p_mode;
+ merge_mode = p_mode;
} else {
Action new_action;
- new_action.name=p_name;
- new_action.last_tick=ticks;
+ new_action.name = p_name;
+ new_action.last_tick = ticks;
actions.push_back(new_action);
- merge_mode=MERGE_DISABLE;
+ merge_mode = MERGE_DISABLE;
}
}
action_level++;
}
-void UndoRedo::add_do_method(Object *p_object,const String& p_method,VARIANT_ARG_DECLARE) {
+void UndoRedo::add_do_method(Object *p_object, const String &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
Operation do_op;
- do_op.object=p_object->get_instance_ID();
+ do_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- do_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
+ do_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
- do_op.type=Operation::TYPE_METHOD;
- do_op.name=p_method;
+ do_op.type = Operation::TYPE_METHOD;
+ do_op.name = p_method;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- do_op.args[i]=*argptr[i];
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ do_op.args[i] = *argptr[i];
}
- actions[current_action+1].do_ops.push_back(do_op);
+ actions[current_action + 1].do_ops.push_back(do_op);
}
-void UndoRedo::add_undo_method(Object *p_object,const String& p_method,VARIANT_ARG_DECLARE) {
+void UndoRedo::add_undo_method(Object *p_object, const String &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
// No undo if the merge mode is MERGE_ENDS
- if (merge_mode==MERGE_ENDS)
+ if (merge_mode == MERGE_ENDS)
return;
Operation undo_op;
- undo_op.object=p_object->get_instance_ID();
+ undo_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
+ undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
- undo_op.type=Operation::TYPE_METHOD;
- undo_op.name=p_method;
+ undo_op.type = Operation::TYPE_METHOD;
+ undo_op.name = p_method;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- undo_op.args[i]=*argptr[i];
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ undo_op.args[i] = *argptr[i];
}
- actions[current_action+1].undo_ops.push_back(undo_op);
-
+ actions[current_action + 1].undo_ops.push_back(undo_op);
}
-void UndoRedo::add_do_property(Object *p_object,const String& p_property,const Variant& p_value) {
+void UndoRedo::add_do_property(Object *p_object, const String &p_property, const Variant &p_value) {
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
Operation do_op;
- do_op.object=p_object->get_instance_ID();
+ do_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- do_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
-
- do_op.type=Operation::TYPE_PROPERTY;
- do_op.name=p_property;
- do_op.args[0]=p_value;
- actions[current_action+1].do_ops.push_back(do_op);
+ do_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
+ do_op.type = Operation::TYPE_PROPERTY;
+ do_op.name = p_property;
+ do_op.args[0] = p_value;
+ actions[current_action + 1].do_ops.push_back(do_op);
}
-void UndoRedo::add_undo_property(Object *p_object,const String& p_property,const Variant& p_value) {
+void UndoRedo::add_undo_property(Object *p_object, const String &p_property, const Variant &p_value) {
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
// No undo if the merge mode is MERGE_ENDS
- if (merge_mode==MERGE_ENDS)
+ if (merge_mode == MERGE_ENDS)
return;
Operation undo_op;
- undo_op.object=p_object->get_instance_ID();
+ undo_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
-
- undo_op.type=Operation::TYPE_PROPERTY;
- undo_op.name=p_property;
- undo_op.args[0]=p_value;
- actions[current_action+1].undo_ops.push_back(undo_op);
+ undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
+ undo_op.type = Operation::TYPE_PROPERTY;
+ undo_op.name = p_property;
+ undo_op.args[0] = p_value;
+ actions[current_action + 1].undo_ops.push_back(undo_op);
}
void UndoRedo::add_do_reference(Object *p_object) {
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
Operation do_op;
- do_op.object=p_object->get_instance_ID();
+ do_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- do_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
-
- do_op.type=Operation::TYPE_REFERENCE;
- actions[current_action+1].do_ops.push_back(do_op);
+ do_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
+ do_op.type = Operation::TYPE_REFERENCE;
+ actions[current_action + 1].do_ops.push_back(do_op);
}
void UndoRedo::add_undo_reference(Object *p_object) {
- ERR_FAIL_COND(action_level<=0);
- ERR_FAIL_COND((current_action+1)>=actions.size());
+ ERR_FAIL_COND(action_level <= 0);
+ ERR_FAIL_COND((current_action + 1) >= actions.size());
// No undo if the merge mode is MERGE_ENDS
- if (merge_mode==MERGE_ENDS)
+ if (merge_mode == MERGE_ENDS)
return;
Operation undo_op;
- undo_op.object=p_object->get_instance_ID();
+ undo_op.object = p_object->get_instance_ID();
if (p_object->cast_to<Resource>())
- undo_op.resref=Ref<Resource>(p_object->cast_to<Resource>());
-
- undo_op.type=Operation::TYPE_REFERENCE;
- actions[current_action+1].undo_ops.push_back(undo_op);
+ undo_op.resref = Ref<Resource>(p_object->cast_to<Resource>());
+ undo_op.type = Operation::TYPE_REFERENCE;
+ actions[current_action + 1].undo_ops.push_back(undo_op);
}
void UndoRedo::_pop_history_tail() {
@@ -221,9 +215,9 @@ void UndoRedo::_pop_history_tail() {
if (!actions.size())
return;
- for (List<Operation>::Element *E=actions[0].undo_ops.front();E;E=E->next()) {
+ for (List<Operation>::Element *E = actions[0].undo_ops.front(); E; E = E->next()) {
- if (E->get().type==Operation::TYPE_REFERENCE) {
+ if (E->get().type == Operation::TYPE_REFERENCE) {
Object *obj = ObjectDB::get_instance(E->get().object);
if (obj)
@@ -237,82 +231,78 @@ void UndoRedo::_pop_history_tail() {
void UndoRedo::commit_action() {
- ERR_FAIL_COND(action_level<=0);
+ ERR_FAIL_COND(action_level <= 0);
action_level--;
- if (action_level>0)
+ if (action_level > 0)
return; //still nested
redo(); // perform action
- if (max_steps>0 && actions.size()>max_steps) {
+ if (max_steps > 0 && actions.size() > max_steps) {
//clear early steps
- while(actions.size() > max_steps)
+ while (actions.size() > max_steps)
_pop_history_tail();
-
}
- if (callback && actions.size()>0) {
- callback(callback_ud,actions[actions.size()-1].name);
+ if (callback && actions.size() > 0) {
+ callback(callback_ud, actions[actions.size() - 1].name);
}
}
-
void UndoRedo::_process_operation_list(List<Operation>::Element *E) {
- for (;E;E=E->next()) {
+ for (; E; E = E->next()) {
- Operation &op=E->get();
+ Operation &op = E->get();
Object *obj = ObjectDB::get_instance(op.object);
if (!obj) {
//corruption
clear_history();
ERR_FAIL_COND(!obj);
-
}
- switch(op.type) {
+ switch (op.type) {
case Operation::TYPE_METHOD: {
- obj->call(op.name,VARIANT_ARGS_FROM_ARRAY(op.args));
+ obj->call(op.name, VARIANT_ARGS_FROM_ARRAY(op.args));
#ifdef TOOLS_ENABLED
- Resource* res = obj->cast_to<Resource>();
+ Resource *res = obj->cast_to<Resource>();
if (res)
res->set_edited(true);
#endif
if (method_callback) {
- method_callback(method_callbck_ud,obj,op.name,VARIANT_ARGS_FROM_ARRAY(op.args));
+ method_callback(method_callbck_ud, obj, op.name, VARIANT_ARGS_FROM_ARRAY(op.args));
}
} break;
case Operation::TYPE_PROPERTY: {
- obj->set(op.name,op.args[0]);
+ obj->set(op.name, op.args[0]);
#ifdef TOOLS_ENABLED
- Resource* res = obj->cast_to<Resource>();
+ Resource *res = obj->cast_to<Resource>();
if (res)
res->set_edited(true);
#endif
if (property_callback) {
- property_callback(prop_callback_ud,obj,op.name,op.args[0]);
+ property_callback(prop_callback_ud, obj, op.name, op.args[0]);
}
} break;
case Operation::TYPE_REFERENCE: {
//do nothing
} break;
-
}
}
}
void UndoRedo::redo() {
- ERR_FAIL_COND(action_level>0);
+ ERR_FAIL_COND(action_level > 0);
- if ((current_action+1)>=actions.size())
+ if ((current_action + 1) >= actions.size())
return; //nothing to redo
current_action++;
@@ -322,8 +312,8 @@ void UndoRedo::redo() {
void UndoRedo::undo() {
- ERR_FAIL_COND(action_level>0);
- if (current_action<0)
+ ERR_FAIL_COND(action_level > 0);
+ if (current_action < 0)
return; //nothing to redo
_process_operation_list(actions[current_action].undo_ops.front());
current_action--;
@@ -332,10 +322,10 @@ void UndoRedo::undo() {
void UndoRedo::clear_history() {
- ERR_FAIL_COND(action_level>0);
+ ERR_FAIL_COND(action_level > 0);
_discard_redo();
- while(actions.size())
+ while (actions.size())
_pop_history_tail();
//version++;
@@ -343,15 +333,15 @@ void UndoRedo::clear_history() {
String UndoRedo::get_current_action_name() const {
- ERR_FAIL_COND_V(action_level>0,"");
- if (current_action<0)
+ ERR_FAIL_COND_V(action_level > 0, "");
+ if (current_action < 0)
return ""; //nothing to redo
return actions[current_action].name;
}
void UndoRedo::set_max_steps(int p_max_steps) {
- max_steps=p_max_steps;
+ max_steps = p_max_steps;
}
int UndoRedo::get_max_steps() const {
@@ -364,40 +354,38 @@ uint64_t UndoRedo::get_version() const {
return version;
}
-void UndoRedo::set_commit_notify_callback(CommitNotifyCallback p_callback,void* p_ud) {
+void UndoRedo::set_commit_notify_callback(CommitNotifyCallback p_callback, void *p_ud) {
- callback=p_callback;
- callback_ud=p_ud;
+ callback = p_callback;
+ callback_ud = p_ud;
}
-void UndoRedo::set_method_notify_callback(MethodNotifyCallback p_method_callback,void* p_ud) {
+void UndoRedo::set_method_notify_callback(MethodNotifyCallback p_method_callback, void *p_ud) {
- method_callback=p_method_callback;
- method_callbck_ud=p_ud;
+ method_callback = p_method_callback;
+ method_callbck_ud = p_ud;
}
-void UndoRedo::set_property_notify_callback(PropertyNotifyCallback p_property_callback,void* p_ud){
+void UndoRedo::set_property_notify_callback(PropertyNotifyCallback p_property_callback, void *p_ud) {
- property_callback=p_property_callback;
- prop_callback_ud=p_ud;
+ property_callback = p_property_callback;
+ prop_callback_ud = p_ud;
}
-
UndoRedo::UndoRedo() {
- version=1;
- action_level=0;
- current_action=-1;
- max_steps=-1;
- merge_mode=MERGE_DISABLE;
- callback=NULL;
- callback_ud=NULL;
-
- method_callbck_ud=NULL;
- prop_callback_ud=NULL;
- method_callback=NULL;
- property_callback=NULL;
-
+ version = 1;
+ action_level = 0;
+ current_action = -1;
+ max_steps = -1;
+ merge_mode = MERGE_DISABLE;
+ callback = NULL;
+ callback_ud = NULL;
+
+ method_callbck_ud = NULL;
+ prop_callback_ud = NULL;
+ method_callback = NULL;
+ property_callback = NULL;
}
UndoRedo::~UndoRedo() {
@@ -405,119 +393,115 @@ UndoRedo::~UndoRedo() {
clear_history();
}
-Variant UndoRedo::_add_do_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
+Variant UndoRedo::_add_do_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- if (p_argcount<2) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=0;
+ if (p_argcount < 2) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
+ if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
return Variant();
}
- if (p_args[1]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
+ if (p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
return Variant();
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Object* object = *p_args[0];
+ Object *object = *p_args[0];
String method = *p_args[1];
Variant v[VARIANT_ARG_MAX];
+ for (int i = 0; i < MIN(VARIANT_ARG_MAX, p_argcount - 2); ++i) {
- for(int i=0;i<MIN(VARIANT_ARG_MAX,p_argcount-2);++i) {
-
- v[i]=*p_args[i+2];
+ v[i] = *p_args[i + 2];
}
- add_do_method(object,method,v[0],v[1],v[2],v[3],v[4]);
+ add_do_method(object, method, v[0], v[1], v[2], v[3], v[4]);
return Variant();
}
-Variant UndoRedo::_add_undo_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
+Variant UndoRedo::_add_undo_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- if (p_argcount<2) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=0;
+ if (p_argcount < 2) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 0;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
+ if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
return Variant();
}
- if (p_args[1]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
+ if (p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
return Variant();
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Object* object = *p_args[0];
+ Object *object = *p_args[0];
String method = *p_args[1];
Variant v[VARIANT_ARG_MAX];
+ for (int i = 0; i < MIN(VARIANT_ARG_MAX, p_argcount - 2); ++i) {
- for(int i=0;i<MIN(VARIANT_ARG_MAX,p_argcount-2);++i) {
-
- v[i]=*p_args[i+2];
+ v[i] = *p_args[i + 2];
}
- add_undo_method(object,method,v[0],v[1],v[2],v[3],v[4]);
+ add_undo_method(object, method, v[0], v[1], v[2], v[3], v[4]);
return Variant();
}
void UndoRedo::_bind_methods() {
- ClassDB::bind_method(D_METHOD("create_action","name","merge_mode"),&UndoRedo::create_action, DEFVAL(MERGE_DISABLE) );
- ClassDB::bind_method(D_METHOD("commit_action"),&UndoRedo::commit_action);
+ ClassDB::bind_method(D_METHOD("create_action", "name", "merge_mode"), &UndoRedo::create_action, DEFVAL(MERGE_DISABLE));
+ ClassDB::bind_method(D_METHOD("commit_action"), &UndoRedo::commit_action);
//ClassDB::bind_method(D_METHOD("add_do_method","p_object", "p_method", "VARIANT_ARG_LIST"),&UndoRedo::add_do_method);
//ClassDB::bind_method(D_METHOD("add_undo_method","p_object", "p_method", "VARIANT_ARG_LIST"),&UndoRedo::add_undo_method);
{
MethodInfo mi;
- mi.name="add_do_method";
- mi.arguments.push_back( PropertyInfo( Variant::OBJECT, "object"));
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
+ mi.name = "add_do_method";
+ mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
-
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"add_do_method",&UndoRedo::_add_do_method,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_do_method", &UndoRedo::_add_do_method, mi);
}
{
MethodInfo mi;
- mi.name="add_undo_method";
- mi.arguments.push_back( PropertyInfo( Variant::OBJECT, "object"));
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
-
+ mi.name = "add_undo_method";
+ mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"add_undo_method",&UndoRedo::_add_undo_method,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "add_undo_method", &UndoRedo::_add_undo_method, mi);
}
- ClassDB::bind_method(D_METHOD("add_do_property","object", "property", "value:Variant"),&UndoRedo::add_do_property);
- ClassDB::bind_method(D_METHOD("add_undo_property","object", "property", "value:Variant"),&UndoRedo::add_undo_property);
- ClassDB::bind_method(D_METHOD("add_do_reference","object"),&UndoRedo::add_do_reference);
- ClassDB::bind_method(D_METHOD("add_undo_reference","object"),&UndoRedo::add_undo_reference);
- ClassDB::bind_method(D_METHOD("clear_history"),&UndoRedo::clear_history);
- ClassDB::bind_method(D_METHOD("get_current_action_name"),&UndoRedo::get_current_action_name);
- ClassDB::bind_method(D_METHOD("get_version"),&UndoRedo::get_version);
+ ClassDB::bind_method(D_METHOD("add_do_property", "object", "property", "value:Variant"), &UndoRedo::add_do_property);
+ ClassDB::bind_method(D_METHOD("add_undo_property", "object", "property", "value:Variant"), &UndoRedo::add_undo_property);
+ ClassDB::bind_method(D_METHOD("add_do_reference", "object"), &UndoRedo::add_do_reference);
+ ClassDB::bind_method(D_METHOD("add_undo_reference", "object"), &UndoRedo::add_undo_reference);
+ ClassDB::bind_method(D_METHOD("clear_history"), &UndoRedo::clear_history);
+ ClassDB::bind_method(D_METHOD("get_current_action_name"), &UndoRedo::get_current_action_name);
+ ClassDB::bind_method(D_METHOD("get_version"), &UndoRedo::get_version);
BIND_CONSTANT(MERGE_DISABLE);
BIND_CONSTANT(MERGE_ENDS);
diff --git a/core/undo_redo.h b/core/undo_redo.h
index 7664cf7cb5..30601fa321 100644
--- a/core/undo_redo.h
+++ b/core/undo_redo.h
@@ -32,27 +32,24 @@
#include "object.h"
#include "resource.h"
-
-
-
class UndoRedo : public Object {
- GDCLASS(UndoRedo,Object);
- OBJ_SAVE_TYPE( UndoRedo );
-public:
+ GDCLASS(UndoRedo, Object);
+ OBJ_SAVE_TYPE(UndoRedo);
+public:
enum MergeMode {
MERGE_DISABLE,
MERGE_ENDS,
MERGE_ALL
};
- typedef void (*CommitNotifyCallback)(void *p_ud,const String& p_name);
- Variant _add_do_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _add_undo_method(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+ typedef void (*CommitNotifyCallback)(void *p_ud, const String &p_name);
+ Variant _add_do_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _add_undo_method(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
- typedef void (*MethodNotifyCallback)(void *p_ud,Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE);
- typedef void (*PropertyNotifyCallback)(void *p_ud,Object*p_base,const StringName& p_property,const Variant& p_value);
+ typedef void (*MethodNotifyCallback)(void *p_ud, Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE);
+ typedef void (*PropertyNotifyCallback)(void *p_ud, Object *p_base, const StringName &p_property, const Variant &p_value);
private:
struct Operation {
@@ -68,10 +65,8 @@ private:
ObjectID object;
String name;
Variant args[VARIANT_ARG_MAX];
-
};
-
struct Action {
String name;
List<Operation> do_ops;
@@ -90,27 +85,24 @@ private:
void _process_operation_list(List<Operation>::Element *E);
void _discard_redo();
-
CommitNotifyCallback callback;
- void* callback_ud;
- void* method_callbck_ud;
- void* prop_callback_ud;
+ void *callback_ud;
+ void *method_callbck_ud;
+ void *prop_callback_ud;
MethodNotifyCallback method_callback;
PropertyNotifyCallback property_callback;
-
protected:
static void _bind_methods();
public:
+ void create_action(const String &p_name = "", MergeMode p_mode = MERGE_DISABLE);
- void create_action(const String& p_name="",MergeMode p_mode=MERGE_DISABLE);
-
- void add_do_method(Object *p_object,const String& p_method,VARIANT_ARG_LIST);
- void add_undo_method(Object *p_object,const String& p_method,VARIANT_ARG_LIST);
- void add_do_property(Object *p_object,const String& p_property,const Variant& p_value);
- void add_undo_property(Object *p_object,const String& p_property,const Variant& p_value);
+ void add_do_method(Object *p_object, const String &p_method, VARIANT_ARG_LIST);
+ void add_undo_method(Object *p_object, const String &p_method, VARIANT_ARG_LIST);
+ void add_do_property(Object *p_object, const String &p_property, const Variant &p_value);
+ void add_undo_property(Object *p_object, const String &p_property, const Variant &p_value);
void add_do_reference(Object *p_object);
void add_undo_reference(Object *p_object);
@@ -126,15 +118,15 @@ public:
uint64_t get_version() const;
- void set_commit_notify_callback(CommitNotifyCallback p_callback,void* p_ud);
+ void set_commit_notify_callback(CommitNotifyCallback p_callback, void *p_ud);
- void set_method_notify_callback(MethodNotifyCallback p_method_callback,void* p_ud);
- void set_property_notify_callback(PropertyNotifyCallback p_property_callback,void* p_ud);
+ void set_method_notify_callback(MethodNotifyCallback p_method_callback, void *p_ud);
+ void set_property_notify_callback(PropertyNotifyCallback p_property_callback, void *p_ud);
UndoRedo();
~UndoRedo();
};
-VARIANT_ENUM_CAST( UndoRedo::MergeMode );
+VARIANT_ENUM_CAST(UndoRedo::MergeMode);
#endif // UNDO_REDO_H
diff --git a/core/ustring.cpp b/core/ustring.cpp
index 7d88989d04..db85db28ef 100644
--- a/core/ustring.cpp
+++ b/core/ustring.cpp
@@ -28,20 +28,20 @@
/*************************************************************************/
#include "ustring.h"
-#include "os/memory.h"
-#include "print_string.h"
-#include "math_funcs.h"
+#include "color.h"
#include "io/md5.h"
#include "io/sha256.h"
+#include "math_funcs.h"
+#include "os/memory.h"
+#include "print_string.h"
#include "ucaps.h"
-#include "color.h"
#include "variant.h"
#include <wchar.h>
#ifndef NO_USE_STDLIB
-#include <stdlib.h>
#include <stdio.h>
+#include <stdlib.h>
#endif
#if defined(MINGW_ENABLED) || defined(_MSC_VER)
@@ -49,34 +49,30 @@
#endif
#define MAX_DIGITS 6
-#define UPPERCASE(m_c) (((m_c)>='a' && (m_c)<='z')?((m_c)-('a'-'A')):(m_c))
-#define LOWERCASE(m_c) (((m_c)>='A' && (m_c)<='Z')?((m_c)+('a'-'A')):(m_c))
-
-
-
+#define UPPERCASE(m_c) (((m_c) >= 'a' && (m_c) <= 'z') ? ((m_c) - ('a' - 'A')) : (m_c))
+#define LOWERCASE(m_c) (((m_c) >= 'A' && (m_c) <= 'Z') ? ((m_c) + ('a' - 'A')) : (m_c))
/** STRING **/
-bool CharString::operator<(const CharString& p_right) const {
+bool CharString::operator<(const CharString &p_right) const {
- if (length()==0) {
- return p_right.length()!=0;
+ if (length() == 0) {
+ return p_right.length() != 0;
}
-
- const char *this_str=get_data();
- const char *that_str=get_data();
+ const char *this_str = get_data();
+ const char *that_str = get_data();
while (true) {
- if (*that_str==0 && *this_str==0)
+ if (*that_str == 0 && *this_str == 0)
return false; //this can't be equal, sadly
- else if (*this_str==0)
+ else if (*this_str == 0)
return true; //if this is empty, and the other one is not, then we're less.. I think?
- else if (*that_str==0)
+ else if (*that_str == 0)
return false; //otherwise the other one is smaller..
- else if (*this_str < *that_str ) //more than
+ else if (*this_str < *that_str) //more than
return true;
- else if (*this_str > *that_str ) //less than
+ else if (*this_str > *that_str) //less than
return false;
this_str++;
@@ -96,98 +92,92 @@ const char *CharString::get_data() const {
void String::copy_from(const char *p_cstr) {
- int len=0;
- const char *ptr=p_cstr;
- while (*(ptr++)!=0)
+ int len = 0;
+ const char *ptr = p_cstr;
+ while (*(ptr++) != 0)
len++;
- if (len==0) {
+ if (len == 0) {
resize(0);
return;
}
-
- resize(len+1); // include 0
+ resize(len + 1); // include 0
CharType *dst = this->ptr();
- for (int i=0;i<len+1;i++) {
+ for (int i = 0; i < len + 1; i++) {
- dst[i]=p_cstr[i];
+ dst[i] = p_cstr[i];
}
-
}
-void String::copy_from(const CharType* p_cstr, int p_clip_to) {
+void String::copy_from(const CharType *p_cstr, int p_clip_to) {
- int len=0;
- const CharType *ptr=p_cstr;
- while (*(ptr++)!=0)
+ int len = 0;
+ const CharType *ptr = p_cstr;
+ while (*(ptr++) != 0)
len++;
- if (p_clip_to>=0 && len>p_clip_to)
- len=p_clip_to;
+ if (p_clip_to >= 0 && len > p_clip_to)
+ len = p_clip_to;
- if (len==0) {
+ if (len == 0) {
resize(0);
return;
}
- resize(len+1);
- set(len,0);
+ resize(len + 1);
+ set(len, 0);
CharType *dst = &operator[](0);
+ for (int i = 0; i < len; i++) {
- for (int i=0;i<len;i++) {
-
- dst[i]=p_cstr[i];
+ dst[i] = p_cstr[i];
}
}
-void String::copy_from(const CharType& p_char) {
+void String::copy_from(const CharType &p_char) {
resize(2);
- set(0,p_char);
- set(1,0);
+ set(0, p_char);
+ set(1, 0);
}
+bool String::operator==(const String &p_str) const {
-bool String::operator==(const String& p_str) const {
-
- if (length()!=p_str.length())
+ if (length() != p_str.length())
return false;
if (empty())
return true;
- int l=length();
+ int l = length();
const CharType *src = c_str();
const CharType *dst = p_str.c_str();
/* Compare char by char */
- for (int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- if (src[i]!=dst[i])
+ if (src[i] != dst[i])
return false;
}
return true;
}
-bool String::operator!=(const String& p_str) const {
+bool String::operator!=(const String &p_str) const {
- return !(*this==p_str);
+ return !(*this == p_str);
}
+String String::operator+(const String &p_str) const {
-
-String String::operator+(const String& p_str) const {
-
- String res=*this;
- res+=p_str;
+ String res = *this;
+ res += p_str;
return res;
}
@@ -199,104 +189,96 @@ String String::operator+(CharType p_chr) const {
return res;
}
*/
-String& String::operator+=(const String &p_str) {
+String &String::operator+=(const String &p_str) {
if (empty()) {
- *this=p_str;
+ *this = p_str;
return *this;
}
if (p_str.empty())
return *this;
- int from=length();
+ int from = length();
- resize( length() + p_str.size() );
+ resize(length() + p_str.size());
const CharType *src = p_str.c_str();
CharType *dst = &operator[](0);
- set( length(), 0 );
+ set(length(), 0);
- for (int i=0;i<p_str.length();i++)
- dst[from+i]=src[i];
+ for (int i = 0; i < p_str.length(); i++)
+ dst[from + i] = src[i];
return *this;
-
}
-String& String::operator+=(const CharType *p_str) {
-
+String &String::operator+=(const CharType *p_str) {
- *this+=String(p_str);
+ *this += String(p_str);
return *this;
}
+String &String::operator+=(CharType p_char) {
-String& String::operator+=(CharType p_char) {
-
-
- resize( size() ? size() + 1 : 2);
- set( length(), 0 );
- set( length() -1, p_char );
+ resize(size() ? size() + 1 : 2);
+ set(length(), 0);
+ set(length() - 1, p_char);
return *this;
-
}
-String& String::operator+=(const char * p_str) {
+String &String::operator+=(const char *p_str) {
- if (!p_str || p_str[0]==0)
+ if (!p_str || p_str[0] == 0)
return *this;
- int src_len=0;
- const char *ptr=p_str;
- while (*(ptr++)!=0)
+ int src_len = 0;
+ const char *ptr = p_str;
+ while (*(ptr++) != 0)
src_len++;
- int from=length();
+ int from = length();
- resize( from + src_len + 1 );
+ resize(from + src_len + 1);
CharType *dst = &operator[](0);
- set( length(), 0 );
+ set(length(), 0);
- for (int i=0;i<src_len;i++)
- dst[from+i]=p_str[i];
+ for (int i = 0; i < src_len; i++)
+ dst[from + i] = p_str[i];
return *this;
-
}
void String::operator=(const char *p_str) {
copy_from(p_str);
-
}
void String::operator=(const CharType *p_str) {
copy_from(p_str);
-
}
bool String::operator==(const StrRange &p_range) const {
- int len=p_range.len;
+ int len = p_range.len;
- if (length()!=len)
+ if (length() != len)
return false;
if (empty())
return true;
- const CharType *c_str=p_range.c_str;
+ const CharType *c_str = p_range.c_str;
const CharType *dst = &operator[](0);
/* Compare char by char */
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (c_str[i]!=dst[i])
+ if (c_str[i] != dst[i])
return false;
}
@@ -305,94 +287,87 @@ bool String::operator==(const StrRange &p_range) const {
bool String::operator==(const char *p_str) const {
- int len=0;
- const char *aux=p_str;
+ int len = 0;
+ const char *aux = p_str;
- while (*(aux++)!=0)
+ while (*(aux++) != 0)
len++;
- if (length()!=len)
+ if (length() != len)
return false;
if (empty())
return true;
- int l=length();
+ int l = length();
const CharType *dst = c_str();
/* Compare char by char */
- for (int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- if (p_str[i]!=dst[i])
+ if (p_str[i] != dst[i])
return false;
}
return true;
-
-
}
bool String::operator==(const CharType *p_str) const {
- int len=0;
- const CharType *aux=p_str;
+ int len = 0;
+ const CharType *aux = p_str;
- while (*(aux++)!=0)
+ while (*(aux++) != 0)
len++;
- if (length()!=len)
+ if (length() != len)
return false;
if (empty())
return true;
- int l=length();
+ int l = length();
const CharType *dst = c_str();
/* Compare char by char */
- for (int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- if (p_str[i]!=dst[i])
+ if (p_str[i] != dst[i])
return false;
}
return true;
-
}
bool String::operator!=(const char *p_str) const {
- return (! ( *this==p_str ) );
+ return (!(*this == p_str));
}
-
bool String::operator!=(const CharType *p_str) const {
- return (! ( *this==p_str ) );
-
+ return (!(*this == p_str));
}
bool String::operator<(const CharType *p_str) const {
-
- if (empty() && p_str[0]==0)
+ if (empty() && p_str[0] == 0)
return false;
if (empty())
return true;
-
- const CharType *this_str=c_str();
+ const CharType *this_str = c_str();
while (true) {
- if (*p_str==0 && *this_str==0)
+ if (*p_str == 0 && *this_str == 0)
return false; //this can't be equal, sadly
- else if (*this_str==0)
+ else if (*this_str == 0)
return true; //if this is empty, and the other one is not, then we're less.. I think?
- else if (*p_str==0)
+ else if (*p_str == 0)
return false; //otherwise the other one is smaller..
- else if (*this_str < *p_str ) //more than
+ else if (*this_str < *p_str) //more than
return true;
- else if (*this_str > *p_str ) //less than
+ else if (*this_str > *p_str) //less than
return false;
this_str++;
@@ -400,33 +375,32 @@ bool String::operator<(const CharType *p_str) const {
}
return false; //should never reach here anyway
-
}
bool String::operator<=(String p_str) const {
- return (*this<p_str) || (*this==p_str);
+ return (*this < p_str) || (*this == p_str);
}
bool String::operator<(const char *p_str) const {
- if (empty() && p_str[0]==0)
+ if (empty() && p_str[0] == 0)
return false;
if (empty())
return true;
- const CharType *this_str=c_str();
+ const CharType *this_str = c_str();
while (true) {
- if (*p_str==0 && *this_str==0)
+ if (*p_str == 0 && *this_str == 0)
return false; //this can't be equal, sadly
- else if (*this_str==0)
+ else if (*this_str == 0)
return true; //if this is empty, and the other one is not, then we're less.. I think?
- else if (*p_str==0)
+ else if (*p_str == 0)
return false; //otherwise the other one is smaller..
- else if (*this_str < *p_str ) //more than
+ else if (*this_str < *p_str) //more than
return true;
- else if (*this_str > *p_str ) //less than
+ else if (*this_str > *p_str) //less than
return false;
this_str++;
@@ -434,11 +408,8 @@ bool String::operator<(const char *p_str) const {
}
return false; //should never reach here anyway
-
}
-
-
bool String::operator<(String p_str) const {
return operator<(p_str.c_str());
@@ -453,20 +424,20 @@ signed char String::nocasecmp_to(const String &p_str) const {
if (p_str.empty())
return 1;
- const CharType *that_str=p_str.c_str();
- const CharType *this_str=c_str();
+ const CharType *that_str = p_str.c_str();
+ const CharType *this_str = c_str();
while (true) {
- if (*that_str==0 && *this_str==0)
+ if (*that_str == 0 && *this_str == 0)
return 0; //we're equal
- else if (*this_str==0)
+ else if (*this_str == 0)
return -1; //if this is empty, and the other one is not, then we're less.. I think?
- else if (*that_str==0)
+ else if (*that_str == 0)
return 1; //otherwise the other one is smaller..
- else if (_find_upper(*this_str) < _find_upper(*that_str) ) //more than
+ else if (_find_upper(*this_str) < _find_upper(*that_str)) //more than
return -1;
- else if (_find_upper(*this_str) > _find_upper(*that_str) ) //less than
+ else if (_find_upper(*this_str) > _find_upper(*that_str)) //less than
return 1;
this_str++;
@@ -474,7 +445,6 @@ signed char String::nocasecmp_to(const String &p_str) const {
}
return 0; //should never reach anyway
-
}
signed char String::casecmp_to(const String &p_str) const {
@@ -486,20 +456,20 @@ signed char String::casecmp_to(const String &p_str) const {
if (p_str.empty())
return 1;
- const CharType *that_str=p_str.c_str();
- const CharType *this_str=c_str();
+ const CharType *that_str = p_str.c_str();
+ const CharType *this_str = c_str();
while (true) {
- if (*that_str==0 && *this_str==0)
+ if (*that_str == 0 && *this_str == 0)
return 0; //we're equal
- else if (*this_str==0)
+ else if (*this_str == 0)
return -1; //if this is empty, and the other one is not, then we're less.. I think?
- else if (*that_str==0)
+ else if (*that_str == 0)
return 1; //otherwise the other one is smaller..
- else if (*this_str < *that_str ) //more than
+ else if (*this_str < *that_str) //more than
return -1;
- else if (*this_str > *that_str ) //less than
+ else if (*this_str > *that_str) //less than
return 1;
this_str++;
@@ -507,32 +477,26 @@ signed char String::casecmp_to(const String &p_str) const {
}
return 0; //should never reach anyway
-
}
void String::erase(int p_pos, int p_chars) {
-
- *this=left(p_pos)+substr( p_pos + p_chars , length() - ( (p_pos+p_chars) ) );
-
-
+ *this = left(p_pos) + substr(p_pos + p_chars, length() - ((p_pos + p_chars)));
}
-
-
String String::capitalize() const {
- String aux=this->replace("_"," ").to_lower();
+ String aux = this->replace("_", " ").to_lower();
String cap;
- for (int i=0;i<aux.get_slice_count(" ");i++) {
+ for (int i = 0; i < aux.get_slice_count(" "); i++) {
- String slice=aux.get_slicec(' ',i);
- if (slice.length()>0) {
+ String slice = aux.get_slicec(' ', i);
+ if (slice.length() > 0) {
- slice[0]=_find_upper(slice[0]);
- if (i>0)
- cap+=" ";
- cap+=slice;
+ slice[0] = _find_upper(slice[0]);
+ if (i > 0)
+ cap += " ";
+ cap += slice;
}
}
@@ -540,19 +504,19 @@ String String::capitalize() const {
}
String String::camelcase_to_underscore(bool lowercase) const {
- const CharType * cstr = c_str();
+ const CharType *cstr = c_str();
String new_string;
const char A = 'A', Z = 'Z';
const char a = 'a', z = 'z';
int start_index = 0;
- for ( size_t i = 1; i < this->size(); i++ ) {
+ for (size_t i = 1; i < this->size(); i++) {
bool is_upper = cstr[i] >= A && cstr[i] <= Z;
bool are_next_2_lower = false;
- bool was_precedent_upper = cstr[i-1] >= A && cstr[i-1] <= Z;
+ bool was_precedent_upper = cstr[i - 1] >= A && cstr[i - 1] <= Z;
- if (i+2 < this->size()) {
- are_next_2_lower = cstr[i+1] >= a && cstr[i+1] <= z && cstr[i+2] >= a && cstr[i+2] <= z;
+ if (i + 2 < this->size()) {
+ are_next_2_lower = cstr[i + 1] >= a && cstr[i + 1] <= z && cstr[i + 2] >= a && cstr[i + 2] <= z;
}
bool should_split = ((is_upper && !was_precedent_upper) || (was_precedent_upper && is_upper && are_next_2_lower));
@@ -566,22 +530,20 @@ String String::camelcase_to_underscore(bool lowercase) const {
return lowercase ? new_string.to_lower() : new_string;
}
-
-
-int String::get_slice_count(String p_splitter) const{
+int String::get_slice_count(String p_splitter) const {
if (empty())
return 0;
if (p_splitter.empty())
return 0;
- int pos=0;
- int slices=1;
+ int pos = 0;
+ int slices = 1;
- while ( (pos=find(p_splitter,pos))>=0) {
+ while ((pos = find(p_splitter, pos)) >= 0) {
slices++;
- pos+=p_splitter.length();
+ pos += p_splitter.length();
}
return slices;
@@ -592,38 +554,37 @@ String String::get_slice(String p_splitter, int p_slice) const {
if (empty() || p_splitter.empty())
return "";
- int pos=0;
- int prev_pos=0;
+ int pos = 0;
+ int prev_pos = 0;
//int slices=1;
- if (p_slice<0)
+ if (p_slice < 0)
return "";
- if (find(p_splitter)==-1)
+ if (find(p_splitter) == -1)
return *this;
- int i=0;
- while(true) {
+ int i = 0;
+ while (true) {
- pos=find(p_splitter,pos);
- if (pos==-1)
- pos=length(); //reached end
+ pos = find(p_splitter, pos);
+ if (pos == -1)
+ pos = length(); //reached end
- int from=prev_pos;
+ int from = prev_pos;
//int to=pos;
- if (p_slice==i) {
+ if (p_slice == i) {
- return substr( from, pos-from );
+ return substr(from, pos - from);
}
- if (pos==length()) //reached end and no find
+ if (pos == length()) //reached end and no find
break;
- pos+=p_splitter.length();
- prev_pos=pos;
+ pos += p_splitter.length();
+ prev_pos = pos;
i++;
}
return ""; //no find!
-
}
String String::get_slicec(CharType p_splitter, int p_slice) const {
@@ -631,226 +592,213 @@ String String::get_slicec(CharType p_splitter, int p_slice) const {
if (empty())
return String();
- if (p_slice<0)
+ if (p_slice < 0)
return String();
- const CharType *c=this->ptr();
- int i=0;
- int prev=0;
- int count=0;
- while(true) {
-
+ const CharType *c = this->ptr();
+ int i = 0;
+ int prev = 0;
+ int count = 0;
+ while (true) {
- if (c[i]==0 || c[i]==p_splitter) {
+ if (c[i] == 0 || c[i] == p_splitter) {
- if (p_slice==count) {
+ if (p_slice == count) {
- return substr(prev,i-prev);
- } else if (c[i]==0) {
+ return substr(prev, i - prev);
+ } else if (c[i] == 0) {
return String();
} else {
count++;
- prev=i+1;
+ prev = i + 1;
}
-
}
i++;
-
}
return String(); //no find!
-
}
-
Vector<String> String::split_spaces() const {
Vector<String> ret;
- int from=0;
- int i=0;
+ int from = 0;
+ int i = 0;
int len = length();
- bool inside=false;
+ bool inside = false;
- while(true) {
+ while (true) {
- bool empty=operator[](i)<33;
+ bool empty = operator[](i) < 33;
- if (i==0)
- inside=!empty;
+ if (i == 0)
+ inside = !empty;
if (!empty && !inside) {
- inside=true;
- from=i;
+ inside = true;
+ from = i;
}
if (empty && inside) {
- ret.push_back(substr(from,i-from));
- inside=false;
+ ret.push_back(substr(from, i - from));
+ inside = false;
}
- if (i==len)
+ if (i == len)
break;
i++;
}
return ret;
-
}
-Vector<String> String::split(const String &p_splitter,bool p_allow_empty) const {
+Vector<String> String::split(const String &p_splitter, bool p_allow_empty) const {
Vector<String> ret;
- int from=0;
+ int from = 0;
int len = length();
- while(true) {
+ while (true) {
- int end=find(p_splitter,from);
- if (end<0)
- end=len;
- if (p_allow_empty || (end>from))
- ret.push_back(substr(from,end-from));
+ int end = find(p_splitter, from);
+ if (end < 0)
+ end = len;
+ if (p_allow_empty || (end > from))
+ ret.push_back(substr(from, end - from));
- if (end==len)
+ if (end == len)
break;
- from = end+p_splitter.length();
+ from = end + p_splitter.length();
}
return ret;
}
-Vector<float> String::split_floats(const String &p_splitter,bool p_allow_empty) const {
+Vector<float> String::split_floats(const String &p_splitter, bool p_allow_empty) const {
Vector<float> ret;
- int from=0;
+ int from = 0;
int len = length();
- while(true) {
+ while (true) {
- int end=find(p_splitter,from);
- if (end<0)
- end=len;
- if (p_allow_empty || (end>from))
+ int end = find(p_splitter, from);
+ if (end < 0)
+ end = len;
+ if (p_allow_empty || (end > from))
ret.push_back(String::to_double(&c_str()[from]));
- if (end==len)
+ if (end == len)
break;
- from = end+p_splitter.length();
+ from = end + p_splitter.length();
}
return ret;
}
-Vector<float> String::split_floats_mk(const Vector<String> &p_splitters,bool p_allow_empty) const {
+Vector<float> String::split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
Vector<float> ret;
- int from=0;
+ int from = 0;
int len = length();
- while(true) {
+ while (true) {
int idx;
- int end=findmk(p_splitters,from,&idx);
- int spl_len=1;
- if (end<0) {
- end=len;
+ int end = findmk(p_splitters, from, &idx);
+ int spl_len = 1;
+ if (end < 0) {
+ end = len;
} else {
- spl_len=p_splitters[idx].length();
+ spl_len = p_splitters[idx].length();
}
- if (p_allow_empty || (end>from)) {
+ if (p_allow_empty || (end > from)) {
ret.push_back(String::to_double(&c_str()[from]));
}
- if (end==len)
+ if (end == len)
break;
- from = end+spl_len;
+ from = end + spl_len;
}
return ret;
-
-
}
-
-Vector<int> String::split_ints(const String &p_splitter,bool p_allow_empty) const {
+Vector<int> String::split_ints(const String &p_splitter, bool p_allow_empty) const {
Vector<int> ret;
- int from=0;
+ int from = 0;
int len = length();
- while(true) {
+ while (true) {
- int end=find(p_splitter,from);
- if (end<0)
- end=len;
- if (p_allow_empty || (end>from))
- ret.push_back(String::to_int(&c_str()[from],end-from));
+ int end = find(p_splitter, from);
+ if (end < 0)
+ end = len;
+ if (p_allow_empty || (end > from))
+ ret.push_back(String::to_int(&c_str()[from], end - from));
- if (end==len)
+ if (end == len)
break;
- from = end+p_splitter.length();
+ from = end + p_splitter.length();
}
return ret;
}
-Vector<int> String::split_ints_mk(const Vector<String> &p_splitters,bool p_allow_empty) const {
+Vector<int> String::split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty) const {
Vector<int> ret;
- int from=0;
+ int from = 0;
int len = length();
- while(true) {
+ while (true) {
int idx;
- int end=findmk(p_splitters,from,&idx);
- int spl_len=1;
- if (end<0) {
- end=len;
+ int end = findmk(p_splitters, from, &idx);
+ int spl_len = 1;
+ if (end < 0) {
+ end = len;
} else {
- spl_len=p_splitters[idx].length();
+ spl_len = p_splitters[idx].length();
}
- if (p_allow_empty || (end>from))
- ret.push_back(String::to_int(&c_str()[from],end-from));
+ if (p_allow_empty || (end > from))
+ ret.push_back(String::to_int(&c_str()[from], end - from));
- if (end==len)
+ if (end == len)
break;
- from = end+spl_len;
+ from = end + spl_len;
}
return ret;
-
-
}
-
CharType String::char_uppercase(CharType p_char) {
return _find_upper(p_char);
}
-CharType String::char_lowercase(CharType p_char){
+CharType String::char_lowercase(CharType p_char) {
return _find_lower(p_char);
}
-
String String::to_upper() const {
- String upper=*this;
+ String upper = *this;
- for(int i=0;i<upper.size();i++) {
+ for (int i = 0; i < upper.size(); i++) {
- upper[i]=_find_upper(upper[i]);
+ upper[i] = _find_upper(upper[i]);
}
return upper;
@@ -858,11 +806,11 @@ String String::to_upper() const {
String String::to_lower() const {
- String upper=*this;
+ String upper = *this;
- for(int i=0;i<upper.size();i++) {
+ for (int i = 0; i < upper.size(); i++) {
- upper[i]=_find_lower(upper[i]);
+ upper[i] = _find_lower(upper[i]);
}
return upper;
@@ -870,16 +818,15 @@ String String::to_lower() const {
int String::length() const {
- int s=size();
- return s?(s-1):0; // length does not include zero
+ int s = size();
+ return s ? (s - 1) : 0; // length does not include zero
}
+const CharType *String::c_str() const {
-const CharType * String::c_str() const {
+ static const CharType zero = 0;
- static const CharType zero=0;
-
- return size()?&operator[](0):&zero;
+ return size() ? &operator[](0) : &zero;
}
String String::md5(const uint8_t *p_md5) {
@@ -887,16 +834,16 @@ String String::md5(const uint8_t *p_md5) {
}
String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
- static const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
+ static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
String ret;
- char v[2]={0,0};
+ char v[2] = { 0, 0 };
- for(int i=0;i<p_len;i++) {
- v[0]=hex[p_buffer[i]>>4];
- ret+=v;
- v[0]=hex[p_buffer[i]&0xF];
- ret+=v;
+ for (int i = 0; i < p_len; i++) {
+ v[0] = hex[p_buffer[i] >> 4];
+ ret += v;
+ v[0] = hex[p_buffer[i] & 0xF];
+ ret += v;
}
return ret;
@@ -904,73 +851,68 @@ String String::hex_encode_buffer(const uint8_t *p_buffer, int p_len) {
String String::chr(CharType p_char) {
- CharType c[2]={p_char,0};
+ CharType c[2] = { p_char, 0 };
return String(c);
-
}
-String String::num(double p_num,int p_decimals) {
-
+String String::num(double p_num, int p_decimals) {
#ifndef NO_USE_STDLIB
- if (p_decimals>12)
- p_decimals=12;
-
+ if (p_decimals > 12)
+ p_decimals = 12;
char fmt[7];
- fmt[0]='%';
- fmt[1]='.';
+ fmt[0] = '%';
+ fmt[1] = '.';
- if (p_decimals<0) {
+ if (p_decimals < 0) {
- fmt[1]='l';
- fmt[2]='f';
- fmt[3]=0;
+ fmt[1] = 'l';
+ fmt[2] = 'f';
+ fmt[3] = 0;
- } else if(p_decimals<10) {
- fmt[2]='0'+p_decimals;
- fmt[3]='l';
- fmt[4]='f';
- fmt[5]=0;
+ } else if (p_decimals < 10) {
+ fmt[2] = '0' + p_decimals;
+ fmt[3] = 'l';
+ fmt[4] = 'f';
+ fmt[5] = 0;
} else {
- fmt[2]='0'+(p_decimals/10);
- fmt[3]='0'+(p_decimals%10);
- fmt[4]='l';
- fmt[5]='f';
- fmt[6]=0;
-
+ fmt[2] = '0' + (p_decimals / 10);
+ fmt[3] = '0' + (p_decimals % 10);
+ fmt[4] = 'l';
+ fmt[5] = 'f';
+ fmt[6] = 0;
}
char buf[256];
#if defined(__GNUC__) || defined(_MSC_VER)
- snprintf(buf,256,fmt,p_num);
+ snprintf(buf, 256, fmt, p_num);
#else
- sprintf(buf,fmt,p_num);
+ sprintf(buf, fmt, p_num);
#endif
- buf[255]=0;
+ buf[255] = 0;
//destroy trailing zeroes
{
- bool period=false;
- int z=0;
- while(buf[z]) {
- if (buf[z]=='.')
- period=true;
+ bool period = false;
+ int z = 0;
+ while (buf[z]) {
+ if (buf[z] == '.')
+ period = true;
z++;
}
if (period) {
z--;
- while(z>0) {
-
+ while (z > 0) {
- if (buf[z]=='0') {
+ if (buf[z] == '0') {
- buf[z]=0;
- } else if (buf[z]=='.') {
+ buf[z] = 0;
+ } else if (buf[z] == '.') {
- buf[z]=0;
+ buf[z] = 0;
break;
} else {
@@ -978,13 +920,10 @@ String String::num(double p_num,int p_decimals) {
}
z--;
-
}
}
}
-
-
return buf;
#else
@@ -992,55 +931,49 @@ String String::num(double p_num,int p_decimals) {
String sd;
/* integer part */
- bool neg=p_num<0;
- p_num=ABS(p_num);
- int intn=(int)p_num;
-
+ bool neg = p_num < 0;
+ p_num = ABS(p_num);
+ int intn = (int)p_num;
/* decimal part */
+ if (p_decimals > 0 || (p_decimals == -1 && (int)p_num != p_num)) {
- if (p_decimals>0 || (p_decimals==-1 && (int)p_num!=p_num)) {
-
- double dec=p_num-(float)((int)p_num);
+ double dec = p_num - (float)((int)p_num);
- int digit=0;
- if (p_decimals>MAX_DIGITS)
- p_decimals=MAX_DIGITS;
+ int digit = 0;
+ if (p_decimals > MAX_DIGITS)
+ p_decimals = MAX_DIGITS;
- int dec_int=0;
- int dec_max=0;
+ int dec_int = 0;
+ int dec_max = 0;
while (true) {
- dec*=10.0;
- dec_int=dec_int*10+(int)dec%10;
- dec_max=dec_max*10+9;
+ dec *= 10.0;
+ dec_int = dec_int * 10 + (int)dec % 10;
+ dec_max = dec_max * 10 + 9;
digit++;
+ if (p_decimals == -1) {
-
- if (p_decimals==-1) {
-
- if (digit==MAX_DIGITS) //no point in going to infinite
+ if (digit == MAX_DIGITS) //no point in going to infinite
break;
- if ((dec-(float)((int)dec))<1e-6)
+ if ((dec - (float)((int)dec)) < 1e-6)
break;
}
- if (digit==p_decimals)
+ if (digit == p_decimals)
break;
-
-
}
- dec*=10;
- int last=(int)dec%10;
+ dec *= 10;
+ int last = (int)dec % 10;
- if (last>5) {
- if (dec_int==dec_max) {
+ if (last > 5) {
+ if (dec_int == dec_max) {
- dec_int=0;
+ dec_int = 0;
intn++;
} else {
@@ -1049,73 +982,69 @@ String String::num(double p_num,int p_decimals) {
}
String decimal;
- for (int i=0;i<digit;i++) {
-
- char num[2]={0,0};
- num[0]='0'+dec_int%10;
- decimal=num+decimal;
- dec_int/=10;
+ for (int i = 0; i < digit; i++) {
+ char num[2] = { 0, 0 };
+ num[0] = '0' + dec_int % 10;
+ decimal = num + decimal;
+ dec_int /= 10;
}
- sd='.'+decimal;
-
+ sd = '.' + decimal;
}
- if (intn==0)
+ if (intn == 0)
- s="0";
+ s = "0";
else {
- while(intn) {
-
- CharType num='0'+(intn%10);
- intn/=10;
- s=num+s;
+ while (intn) {
+ CharType num = '0' + (intn % 10);
+ intn /= 10;
+ s = num + s;
}
}
- s=s+sd;
+ s = s + sd;
if (neg)
- s="-"+s;
+ s = "-" + s;
return s;
#endif
-
}
String String::num_int64(int64_t p_num, int base, bool capitalize_hex) {
- bool sign=p_num<0;
- int64_t num=ABS(p_num);
+ bool sign = p_num < 0;
+ int64_t num = ABS(p_num);
- int64_t n=num;
+ int64_t n = num;
- int chars=0;
+ int chars = 0;
do {
- n/=base;
+ n /= base;
chars++;
- } while(n);
+ } while (n);
if (sign)
chars++;
String s;
- s.resize(chars+1);
- CharType *c=s.ptr();
- c[chars]=0;
- n=num;
+ s.resize(chars + 1);
+ CharType *c = s.ptr();
+ c[chars] = 0;
+ n = num;
do {
- int mod = n%base;
+ int mod = n % base;
if (mod >= 10) {
char a = (capitalize_hex ? 'A' : 'a');
- c[--chars]=a+(mod - 10);
+ c[--chars] = a + (mod - 10);
} else {
- c[--chars]='0'+mod;
+ c[--chars] = '0' + mod;
}
- n/=base;
- } while(n);
+ n /= base;
+ } while (n);
if (sign)
- c[0]='-';
+ c[0] = '-';
return s;
}
@@ -1126,45 +1055,43 @@ String String::num_real(double p_num) {
String sd;
/* integer part */
- bool neg=p_num<0;
- p_num=ABS(p_num);
- int intn=(int)p_num;
+ bool neg = p_num < 0;
+ p_num = ABS(p_num);
+ int intn = (int)p_num;
/* decimal part */
+ if ((int)p_num != p_num) {
- if ((int)p_num!=p_num) {
-
- double dec=p_num-(float)((int)p_num);
+ double dec = p_num - (float)((int)p_num);
- int digit=0;
- int decimals=MAX_DIGITS;
+ int digit = 0;
+ int decimals = MAX_DIGITS;
- int dec_int=0;
- int dec_max=0;
+ int dec_int = 0;
+ int dec_max = 0;
while (true) {
- dec*=10.0;
- dec_int=dec_int*10+(int)dec%10;
- dec_max=dec_max*10+9;
+ dec *= 10.0;
+ dec_int = dec_int * 10 + (int)dec % 10;
+ dec_max = dec_max * 10 + 9;
digit++;
- if ((dec-(float)((int)dec))<1e-6)
+ if ((dec - (float)((int)dec)) < 1e-6)
break;
- if (digit==decimals)
+ if (digit == decimals)
break;
-
}
- dec*=10;
- int last=(int)dec%10;
+ dec *= 10;
+ int last = (int)dec % 10;
- if (last>5) {
- if (dec_int==dec_max) {
+ if (last > 5) {
+ if (dec_int == dec_max) {
- dec_int=0;
+ dec_int = 0;
intn++;
} else {
@@ -1173,54 +1100,49 @@ String String::num_real(double p_num) {
}
String decimal;
- for (int i=0;i<digit;i++) {
-
- char num[2]={0,0};
- num[0]='0'+dec_int%10;
- decimal=num+decimal;
- dec_int/=10;
+ for (int i = 0; i < digit; i++) {
+ char num[2] = { 0, 0 };
+ num[0] = '0' + dec_int % 10;
+ decimal = num + decimal;
+ dec_int /= 10;
}
- sd='.'+decimal;
+ sd = '.' + decimal;
} else {
- sd=".0";
+ sd = ".0";
}
- if (intn==0)
+ if (intn == 0)
- s="0";
+ s = "0";
else {
- while(intn) {
-
- CharType num='0'+(intn%10);
- intn/=10;
- s=num+s;
+ while (intn) {
+ CharType num = '0' + (intn % 10);
+ intn /= 10;
+ s = num + s;
}
}
- s=s+sd;
+ s = s + sd;
if (neg)
- s="-"+s;
+ s = "-" + s;
return s;
-
}
-
String String::num_scientific(double p_num) {
#ifndef NO_USE_STDLIB
-
char buf[256];
#if defined(__GNUC__) || defined(_MSC_VER)
- snprintf(buf,256,"%lg",p_num);
+ snprintf(buf, 256, "%lg", p_num);
#else
- sprintf(buf,"%.16lg",p_num);
+ sprintf(buf, "%.16lg", p_num);
#endif
- buf[255]=0;
+ buf[255] = 0;
return buf;
#else
@@ -1237,17 +1159,16 @@ CharString String::ascii(bool p_allow_extended) const {
CharString cs;
cs.resize(size());
- for (int i=0;i<size();i++)
- cs[i]=operator[](i);
+ for (int i = 0; i < size(); i++)
+ cs[i] = operator[](i);
return cs;
-
}
-String String::utf8(const char* p_utf8,int p_len) {
+String String::utf8(const char *p_utf8, int p_len) {
String ret;
- ret.parse_utf8(p_utf8,p_len);
+ ret.parse_utf8(p_utf8, p_len);
return ret;
};
@@ -1311,57 +1232,57 @@ _FORCE_INLINE static int parse_utf8_char(const char *p_utf8,unsigned int *p_ucs4
}
#endif
-bool String::parse_utf8(const char* p_utf8,int p_len) {
+bool String::parse_utf8(const char *p_utf8, int p_len) {
-#define _UNICERROR(m_err) print_line("unicode error: "+String(m_err));
+#define _UNICERROR(m_err) print_line("unicode error: " + String(m_err));
String aux;
- int cstr_size=0;
- int str_size=0;
+ int cstr_size = 0;
+ int str_size = 0;
/* HANDLE BOM (Byte Order Mark) */
- if (p_len<0 || p_len>=3) {
+ if (p_len < 0 || p_len >= 3) {
- bool has_bom = uint8_t(p_utf8[0])==0xEF && uint8_t(p_utf8[1])==0xBB && uint8_t(p_utf8[2])==0xBF;
+ bool has_bom = uint8_t(p_utf8[0]) == 0xEF && uint8_t(p_utf8[1]) == 0xBB && uint8_t(p_utf8[2]) == 0xBF;
if (has_bom) {
//just skip it
- if (p_len>=0)
- p_len-=3;
- p_utf8+=3;
+ if (p_len >= 0)
+ p_len -= 3;
+ p_utf8 += 3;
}
}
{
- const char *ptrtmp=p_utf8;
- const char *ptrtmp_limit=&p_utf8[p_len];
- int skip=0;
- while (ptrtmp!=ptrtmp_limit && *ptrtmp) {
+ const char *ptrtmp = p_utf8;
+ const char *ptrtmp_limit = &p_utf8[p_len];
+ int skip = 0;
+ while (ptrtmp != ptrtmp_limit && *ptrtmp) {
- if (skip==0) {
+ if (skip == 0) {
uint8_t c = *ptrtmp;
/* Determine the number of characters in sequence */
- if ((c & 0x80)==0)
- skip=0;
- else if ((c & 0xE0)==0xC0)
- skip=1;
- else if ((c & 0xF0)==0xE0)
- skip=2;
- else if ((c & 0xF8)==0xF0)
- skip=3;
- else if ((c & 0xFC)==0xF8)
- skip=4;
- else if ((c & 0xFE)==0xFC)
- skip=5;
+ if ((c & 0x80) == 0)
+ skip = 0;
+ else if ((c & 0xE0) == 0xC0)
+ skip = 1;
+ else if ((c & 0xF0) == 0xE0)
+ skip = 2;
+ else if ((c & 0xF8) == 0xF0)
+ skip = 3;
+ else if ((c & 0xFC) == 0xF8)
+ skip = 4;
+ else if ((c & 0xFE) == 0xFC)
+ skip = 5;
else {
_UNICERROR("invalid skip");
return true; //invalid utf8
}
- if (skip==1 && (c&0x1E)==0) {
+ if (skip == 1 && (c & 0x1E) == 0) {
//printf("overlong rejected\n");
_UNICERROR("overlong rejected");
return true; //reject overlong
@@ -1369,7 +1290,6 @@ bool String::parse_utf8(const char* p_utf8,int p_len) {
str_size++;
-
} else {
--skip;
@@ -1383,48 +1303,46 @@ bool String::parse_utf8(const char* p_utf8,int p_len) {
_UNICERROR("no space left");
return true; //not enough spac
}
-
}
- if (str_size==0) {
+ if (str_size == 0) {
clear();
return false;
}
- resize(str_size+1);
+ resize(str_size + 1);
CharType *dst = &operator[](0);
- dst[str_size]=0;
+ dst[str_size] = 0;
while (cstr_size) {
-
- int len=0;
-
- /* Determine the number of characters in sequence */
- if ((*p_utf8 & 0x80)==0)
- len=1;
- else if ((*p_utf8 & 0xE0)==0xC0)
- len=2;
- else if ((*p_utf8 & 0xF0)==0xE0)
- len=3;
- else if ((*p_utf8 & 0xF8)==0xF0)
- len=4;
- else if ((*p_utf8 & 0xFC)==0xF8)
- len=5;
- else if ((*p_utf8 & 0xFE)==0xFC)
- len=6;
+ int len = 0;
+
+ /* Determine the number of characters in sequence */
+ if ((*p_utf8 & 0x80) == 0)
+ len = 1;
+ else if ((*p_utf8 & 0xE0) == 0xC0)
+ len = 2;
+ else if ((*p_utf8 & 0xF0) == 0xE0)
+ len = 3;
+ else if ((*p_utf8 & 0xF8) == 0xF0)
+ len = 4;
+ else if ((*p_utf8 & 0xFC) == 0xF8)
+ len = 5;
+ else if ((*p_utf8 & 0xFE) == 0xFC)
+ len = 6;
else {
_UNICERROR("invalid len");
return true; //invalid UTF8
}
- if (len>cstr_size) {
+ if (len > cstr_size) {
_UNICERROR("no space left");
return true; //not enough space
}
- if (len==2 && (*p_utf8&0x1E)==0) {
+ if (len == 2 && (*p_utf8 & 0x1E) == 0) {
//printf("overlong rejected\n");
_UNICERROR("no space left");
return true; //reject overlong
@@ -1432,21 +1350,21 @@ bool String::parse_utf8(const char* p_utf8,int p_len) {
/* Convert the first character */
- uint32_t unichar=0;
+ uint32_t unichar = 0;
if (len == 1)
- unichar=*p_utf8;
+ unichar = *p_utf8;
else {
- unichar=(0xFF >> (len +1)) & *p_utf8;
+ unichar = (0xFF >> (len + 1)) & *p_utf8;
- for (int i=1;i<len;i++) {
+ for (int i = 1; i < len; i++) {
if ((p_utf8[i] & 0xC0) != 0x80) {
_UNICERROR("invalid utf8");
return true; //invalid utf8
}
- if (unichar==0 && i==2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) {
+ if (unichar == 0 && i == 2 && ((p_utf8[i] & 0x7F) >> (7 - len)) == 0) {
_UNICERROR("invalid utf8 overlong");
return true; //no overlong
}
@@ -1455,104 +1373,99 @@ bool String::parse_utf8(const char* p_utf8,int p_len) {
}
//printf("char %i, len %i\n",unichar,len);
- if (sizeof(wchar_t)==2 && unichar>0xFFFF) {
- unichar=' '; //too long for windows
-
+ if (sizeof(wchar_t) == 2 && unichar > 0xFFFF) {
+ unichar = ' '; //too long for windows
}
*(dst++) = unichar;
- cstr_size-=len;
+ cstr_size -= len;
p_utf8 += len;
}
return false;
}
-
-
CharString String::utf8() const {
int l = length();
if (!l)
return CharString();
- const CharType *d=&operator[](0);
- int fl=0;
- for (int i=0;i<l;i++) {
+ const CharType *d = &operator[](0);
+ int fl = 0;
+ for (int i = 0; i < l; i++) {
- uint32_t c=d[i];
+ uint32_t c = d[i];
if (c <= 0x7f) // 7 bits.
- fl+=1;
- else if (c <= 0x7ff) { // 11 bits
- fl+=2;
+ fl += 1;
+ else if (c <= 0x7ff) { // 11 bits
+ fl += 2;
} else if (c <= 0xffff) { // 16 bits
- fl+=3;
+ fl += 3;
} else if (c <= 0x001fffff) { // 21 bits
- fl+=4;
+ fl += 4;
} else if (c <= 0x03ffffff) { // 26 bits
- fl+=5;
- } else if (c <= 0x7fffffff) { // 31 bits
- fl+=6;
+ fl += 5;
+ } else if (c <= 0x7fffffff) { // 31 bits
+ fl += 6;
}
}
-
CharString utf8s;
- if (fl==0) {
+ if (fl == 0) {
return utf8s;
}
- utf8s.resize(fl+1);
- uint8_t *cdst=(uint8_t*)utf8s.get_data();
+ utf8s.resize(fl + 1);
+ uint8_t *cdst = (uint8_t *)utf8s.get_data();
-#define APPEND_CHAR( m_c ) *(cdst++) = m_c
+#define APPEND_CHAR(m_c) *(cdst++) = m_c
- for (int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- uint32_t c=d[i];
+ uint32_t c = d[i];
if (c <= 0x7f) // 7 bits.
- APPEND_CHAR( c );
- else if (c <= 0x7ff) { // 11 bits
+ APPEND_CHAR(c);
+ else if (c <= 0x7ff) { // 11 bits
- APPEND_CHAR( uint32_t(0xc0 | ((c >> 6) & 0x1f)) ); // Top 5 bits.
- APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits.
+ APPEND_CHAR(uint32_t(0xc0 | ((c >> 6) & 0x1f))); // Top 5 bits.
+ APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
} else if (c <= 0xffff) { // 16 bits
- APPEND_CHAR( uint32_t(0xe0 | ((c >> 12) & 0x0f)) ); // Top 4 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits.
+ APPEND_CHAR(uint32_t(0xe0 | ((c >> 12) & 0x0f))); // Top 4 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
} else if (c <= 0x001fffff) { // 21 bits
- APPEND_CHAR( uint32_t(0xf0 | ((c >> 18) & 0x07)) ); // Top 3 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // Upper middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits.
+ APPEND_CHAR(uint32_t(0xf0 | ((c >> 18) & 0x07))); // Top 3 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
} else if (c <= 0x03ffffff) { // 26 bits
- APPEND_CHAR( uint32_t(0xf8 | ((c >> 24) & 0x03)) ); // Top 2 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 18) & 0x3f)) ); // Upper middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits.
- } else if (c <= 0x7fffffff) { // 31 bits
-
- APPEND_CHAR( uint32_t(0xfc | ((c >> 30) & 0x01)) ); // Top 1 bit.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 24) & 0x3f)) ); // Upper upper middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 18) & 0x3f)) ); // Lower upper middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 12) & 0x3f)) ); // Upper lower middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | ((c >> 6) & 0x3f)) ); // Lower lower middle 6 bits.
- APPEND_CHAR( uint32_t(0x80 | (c & 0x3f)) ); // Bottom 6 bits.
+ APPEND_CHAR(uint32_t(0xf8 | ((c >> 24) & 0x03))); // Top 2 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Upper middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
+ } else if (c <= 0x7fffffff) { // 31 bits
+
+ APPEND_CHAR(uint32_t(0xfc | ((c >> 30) & 0x01))); // Top 1 bit.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 24) & 0x3f))); // Upper upper middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 18) & 0x3f))); // Lower upper middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 12) & 0x3f))); // Upper lower middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | ((c >> 6) & 0x3f))); // Lower lower middle 6 bits.
+ APPEND_CHAR(uint32_t(0x80 | (c & 0x3f))); // Bottom 6 bits.
}
}
#undef APPEND_CHAR
- *cdst=0; //trailing zero
+ *cdst = 0; //trailing zero
return utf8s;
}
-
/*
String::String(CharType p_char) {
@@ -1565,203 +1478,194 @@ String::String(const char *p_str) {
copy_from(p_str);
}
-String::String(const CharType *p_str,int p_clip_to_len) {
+String::String(const CharType *p_str, int p_clip_to_len) {
- copy_from(p_str,p_clip_to_len);
+ copy_from(p_str, p_clip_to_len);
}
-
-String::String(const StrRange& p_range) {
+String::String(const StrRange &p_range) {
if (!p_range.c_str)
return;
- copy_from(p_range.c_str,p_range.len);
+ copy_from(p_range.c_str, p_range.len);
}
int String::hex_to_int(bool p_with_prefix) const {
int l = length();
- if (p_with_prefix && l<3)
+ if (p_with_prefix && l < 3)
return 0;
- const CharType *s=ptr();
+ const CharType *s = ptr();
- int sign = s[0]=='-' ? -1 : 1;
+ int sign = s[0] == '-' ? -1 : 1;
- if (sign<0) {
+ if (sign < 0) {
s++;
l--;
- if (p_with_prefix && l<2)
+ if (p_with_prefix && l < 2)
return 0;
}
if (p_with_prefix) {
- if (s[0]!='0' || s[1]!='x')
+ if (s[0] != '0' || s[1] != 'x')
return 0;
- s+=2;
- l-=2;
+ s += 2;
+ l -= 2;
};
- int hex=0;
+ int hex = 0;
- while(*s) {
+ while (*s) {
CharType c = LOWERCASE(*s);
int n;
- if (c>='0' && c<='9') {
- n=c-'0';
- } else if (c>='a' && c<='f') {
- n=(c-'a')+10;
+ if (c >= '0' && c <= '9') {
+ n = c - '0';
+ } else if (c >= 'a' && c <= 'f') {
+ n = (c - 'a') + 10;
} else {
return 0;
}
- hex*=16;
- hex+=n;
+ hex *= 16;
+ hex += n;
s++;
}
- return hex*sign;
-
+ return hex * sign;
}
-
int64_t String::hex_to_int64(bool p_with_prefix) const {
int l = length();
- if (p_with_prefix && l<3)
+ if (p_with_prefix && l < 3)
return 0;
- const CharType *s=ptr();
+ const CharType *s = ptr();
- int64_t sign = s[0]=='-' ? -1 : 1;
+ int64_t sign = s[0] == '-' ? -1 : 1;
- if (sign<0) {
+ if (sign < 0) {
s++;
l--;
- if (p_with_prefix && l<2)
+ if (p_with_prefix && l < 2)
return 0;
}
if (p_with_prefix) {
- if (s[0]!='0' || s[1]!='x')
+ if (s[0] != '0' || s[1] != 'x')
return 0;
- s+=2;
- l-=2;
+ s += 2;
+ l -= 2;
};
- int64_t hex=0;
+ int64_t hex = 0;
- while(*s) {
+ while (*s) {
CharType c = LOWERCASE(*s);
int64_t n;
- if (c>='0' && c<='9') {
- n=c-'0';
- } else if (c>='a' && c<='f') {
- n=(c-'a')+10;
+ if (c >= '0' && c <= '9') {
+ n = c - '0';
+ } else if (c >= 'a' && c <= 'f') {
+ n = (c - 'a') + 10;
} else {
return 0;
}
- hex*=16;
- hex+=n;
+ hex *= 16;
+ hex += n;
s++;
}
- return hex*sign;
-
+ return hex * sign;
}
int String::to_int() const {
- if (length()==0)
+ if (length() == 0)
return 0;
- int to=(find(".")>=0) ? find(".") : length() ;
+ int to = (find(".") >= 0) ? find(".") : length();
- int integer=0;
- int sign=1;
+ int integer = 0;
+ int sign = 1;
- for (int i=0;i<to;i++) {
+ for (int i = 0; i < to; i++) {
- CharType c=operator[](i);
- if (c>='0' && c<='9') {
+ CharType c = operator[](i);
+ if (c >= '0' && c <= '9') {
- integer*=10;
- integer+=c-'0';
+ integer *= 10;
+ integer += c - '0';
- } else if (integer==0 && c=='-') {
+ } else if (integer == 0 && c == '-') {
- sign=-sign;
+ sign = -sign;
}
-
}
- return integer*sign;
+ return integer * sign;
}
int64_t String::to_int64() const {
- if (length()==0)
+ if (length() == 0)
return 0;
- int to=(find(".")>=0) ? find(".") : length() ;
+ int to = (find(".") >= 0) ? find(".") : length();
- int64_t integer=0;
- int64_t sign=1;
+ int64_t integer = 0;
+ int64_t sign = 1;
- for (int i=0;i<to;i++) {
+ for (int i = 0; i < to; i++) {
- CharType c=operator[](i);
- if (c>='0' && c<='9') {
+ CharType c = operator[](i);
+ if (c >= '0' && c <= '9') {
- integer*=10;
- integer+=c-'0';
+ integer *= 10;
+ integer += c - '0';
- } else if (integer==0 && c=='-') {
+ } else if (integer == 0 && c == '-') {
- sign=-sign;
+ sign = -sign;
}
-
}
- return integer*sign;
+ return integer * sign;
}
-int String::to_int(const char* p_str,int p_len) {
-
+int String::to_int(const char *p_str, int p_len) {
- int to=0;
- if (p_len>=0)
- to=p_len;
+ int to = 0;
+ if (p_len >= 0)
+ to = p_len;
else {
- while(p_str[to]!=0 && p_str[to]!='.')
+ while (p_str[to] != 0 && p_str[to] != '.')
to++;
}
+ int integer = 0;
+ int sign = 1;
- int integer=0;
- int sign=1;
+ for (int i = 0; i < to; i++) {
- for (int i=0;i<to;i++) {
+ char c = p_str[i];
+ if (c >= '0' && c <= '9') {
- char c=p_str[i];
- if (c>='0' && c<='9') {
+ integer *= 10;
+ integer += c - '0';
- integer*=10;
- integer+=c-'0';
+ } else if (c == '-' && integer == 0) {
- } else if (c=='-' && integer==0) {
-
- sign=-sign;
- } else if (c!=' ')
+ sign = -sign;
+ } else if (c != ' ')
break;
-
}
- return integer*sign;
+ return integer * sign;
}
bool String::is_numeric() const {
@@ -1773,7 +1677,7 @@ bool String::is_numeric() const {
int s = 0;
if (operator[](0) == '-') ++s;
bool dot = false;
- for (int i=s; i<length(); i++) {
+ for (int i = s; i < length(); i++) {
CharType c = operator[](i);
if (c == '.') {
@@ -1790,11 +1694,11 @@ bool String::is_numeric() const {
return true; // TODO: Use the parser below for this instead
};
-#define IS_DIGIT(m_d) ( (m_d)>='0' && (m_d)<='9' )
-#define IS_HEX_DIGIT(m_d) ( ( (m_d)>='0' && (m_d)<='9' ) || ( (m_d)>='a' && (m_d)<='f' ) || ( (m_d)>='A' && (m_d)<='F' ) )
+#define IS_DIGIT(m_d) ((m_d) >= '0' && (m_d) <= '9')
+#define IS_HEX_DIGIT(m_d) (((m_d) >= '0' && (m_d) <= '9') || ((m_d) >= 'a' && (m_d) <= 'f') || ((m_d) >= 'A' && (m_d) <= 'F'))
-template<class C>
-static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number,
+template <class C>
+static double built_in_strtod(const C *string, /* A decimal ASCII floating-point number,
* optionally preceded by white space. Must
* have form "-I.FE-X", where I is the integer
* part of the mantissa, F is the fractional
@@ -1805,36 +1709,34 @@ static double built_in_strtod(const C *string, /* A decimal ASCII floati
* necessary unless F is present. The "E" may
* actually be an "e". E and X may both be
* omitted (but not just one). */
- C **endPtr=NULL) /* If non-NULL, store terminating Cacter's
+ C **endPtr = NULL) /* If non-NULL, store terminating Cacter's
* address here. */
{
-
- static const int maxExponent = 511; /* Largest possible base 10 exponent. Any
+ static const int maxExponent = 511; /* Largest possible base 10 exponent. Any
* exponent larger than this will already
* produce underflow or overflow, so there's
* no need to worry about additional digits.
*/
- static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */
- 10., /* is 10^2^i. Used to convert decimal */
- 100., /* exponents into floating-point numbers. */
- 1.0e4,
- 1.0e8,
- 1.0e16,
- 1.0e32,
- 1.0e64,
- 1.0e128,
- 1.0e256
+ static const double powersOf10[] = { /* Table giving binary powers of 10. Entry */
+ 10., /* is 10^2^i. Used to convert decimal */
+ 100., /* exponents into floating-point numbers. */
+ 1.0e4,
+ 1.0e8,
+ 1.0e16,
+ 1.0e32,
+ 1.0e64,
+ 1.0e128,
+ 1.0e256
};
-
- int sign, expSign = false;
- double fraction, dblExp;
- const double *d;
- register const C *p;
- register int c;
- int exp = 0; /* Exponent read from "EX" field. */
- int fracExp = 0; /* Exponent that derives from the fractional
+ int sign, expSign = false;
+ double fraction, dblExp;
+ const double *d;
+ register const C *p;
+ register int c;
+ int exp = 0; /* Exponent read from "EX" field. */
+ int fracExp = 0; /* Exponent that derives from the fractional
* part. Under normal circumstatnces, it is
* the negative of the number of digits in F.
* However, if I is very long, the last digits
@@ -1843,182 +1745,179 @@ static double built_in_strtod(const C *string, /* A decimal ASCII floati
* unnecessary overflow on I alone). In this
* case, fracExp is incremented one for each
* dropped digit. */
- int mantSize; /* Number of digits in mantissa. */
- int decPt; /* Number of mantissa digits BEFORE decimal
+ int mantSize; /* Number of digits in mantissa. */
+ int decPt; /* Number of mantissa digits BEFORE decimal
* point. */
- const C *pExp; /* Temporarily holds location of exponent in
+ const C *pExp; /* Temporarily holds location of exponent in
* string. */
- /*
+ /*
* Strip off leading blanks and check for a sign.
*/
- p = string;
- while (*p == ' ' || *p=='\t' || *p=='\n') {
- p += 1;
- }
- if (*p == '-') {
- sign = true;
- p += 1;
- } else {
- if (*p == '+') {
- p += 1;
- }
- sign = false;
- }
-
- /*
+ p = string;
+ while (*p == ' ' || *p == '\t' || *p == '\n') {
+ p += 1;
+ }
+ if (*p == '-') {
+ sign = true;
+ p += 1;
+ } else {
+ if (*p == '+') {
+ p += 1;
+ }
+ sign = false;
+ }
+
+ /*
* Count the number of digits in the mantissa (including the decimal
* point), and also locate the decimal point.
*/
- decPt = -1;
- for (mantSize = 0; ; mantSize += 1)
- {
- c = *p;
- if (!IS_DIGIT(c)) {
- if ((c != '.') || (decPt >= 0)) {
- break;
- }
- decPt = mantSize;
+ decPt = -1;
+ for (mantSize = 0;; mantSize += 1) {
+ c = *p;
+ if (!IS_DIGIT(c)) {
+ if ((c != '.') || (decPt >= 0)) {
+ break;
+ }
+ decPt = mantSize;
+ }
+ p += 1;
}
- p += 1;
- }
- /*
+ /*
* Now suck up the digits in the mantissa. Use two integers to collect 9
* digits each (this is faster than using floating-point). If the mantissa
* has more than 18 digits, ignore the extras, since they can't affect the
* value anyway.
*/
- pExp = p;
- p -= mantSize;
- if (decPt < 0) {
- decPt = mantSize;
- } else {
- mantSize -= 1; /* One of the digits was the point. */
- }
- if (mantSize > 18) {
- fracExp = decPt - 18;
- mantSize = 18;
- } else {
- fracExp = decPt - mantSize;
- }
- if (mantSize == 0) {
- fraction = 0.0;
- p = string;
- goto done;
- } else {
- int frac1, frac2;
-
- frac1 = 0;
- for ( ; mantSize > 9; mantSize -= 1) {
- c = *p;
- p += 1;
- if (c == '.') {
- c = *p;
- p += 1;
- }
- frac1 = 10*frac1 + (c - '0');
- }
- frac2 = 0;
- for (; mantSize > 0; mantSize -= 1) {
- c = *p;
- p += 1;
- if (c == '.') {
- c = *p;
- p += 1;
- }
- frac2 = 10*frac2 + (c - '0');
+ pExp = p;
+ p -= mantSize;
+ if (decPt < 0) {
+ decPt = mantSize;
+ } else {
+ mantSize -= 1; /* One of the digits was the point. */
+ }
+ if (mantSize > 18) {
+ fracExp = decPt - 18;
+ mantSize = 18;
+ } else {
+ fracExp = decPt - mantSize;
+ }
+ if (mantSize == 0) {
+ fraction = 0.0;
+ p = string;
+ goto done;
+ } else {
+ int frac1, frac2;
+
+ frac1 = 0;
+ for (; mantSize > 9; mantSize -= 1) {
+ c = *p;
+ p += 1;
+ if (c == '.') {
+ c = *p;
+ p += 1;
+ }
+ frac1 = 10 * frac1 + (c - '0');
+ }
+ frac2 = 0;
+ for (; mantSize > 0; mantSize -= 1) {
+ c = *p;
+ p += 1;
+ if (c == '.') {
+ c = *p;
+ p += 1;
+ }
+ frac2 = 10 * frac2 + (c - '0');
+ }
+ fraction = (1.0e9 * frac1) + frac2;
}
- fraction = (1.0e9 * frac1) + frac2;
- }
- /*
+ /*
* Skim off the exponent.
*/
- p = pExp;
- if ((*p == 'E') || (*p == 'e')) {
- p += 1;
- if (*p == '-') {
- expSign = true;
- p += 1;
- } else {
- if (*p == '+') {
+ p = pExp;
+ if ((*p == 'E') || (*p == 'e')) {
p += 1;
- }
- expSign = false;
- }
- if (!IS_DIGIT(CharType(*p))) {
- p = pExp;
- goto done;
+ if (*p == '-') {
+ expSign = true;
+ p += 1;
+ } else {
+ if (*p == '+') {
+ p += 1;
+ }
+ expSign = false;
+ }
+ if (!IS_DIGIT(CharType(*p))) {
+ p = pExp;
+ goto done;
+ }
+ while (IS_DIGIT(CharType(*p))) {
+ exp = exp * 10 + (*p - '0');
+ p += 1;
+ }
}
- while (IS_DIGIT(CharType(*p))) {
- exp = exp * 10 + (*p - '0');
- p += 1;
+ if (expSign) {
+ exp = fracExp - exp;
+ } else {
+ exp = fracExp + exp;
}
- }
- if (expSign) {
- exp = fracExp - exp;
- } else {
- exp = fracExp + exp;
- }
- /*
+ /*
* Generate a floating-point number that represents the exponent. Do this
* by processing the exponent one bit at a time to combine many powers of
* 2 of 10. Then combine the exponent with the fraction.
*/
- if (exp < 0) {
- expSign = true;
- exp = -exp;
- } else {
- expSign = false;
- }
+ if (exp < 0) {
+ expSign = true;
+ exp = -exp;
+ } else {
+ expSign = false;
+ }
- if (exp > maxExponent) {
- exp = maxExponent;
- WARN_PRINT("Exponent too high");
- }
- dblExp = 1.0;
- for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
- if (exp & 01) {
- dblExp *= *d;
+ if (exp > maxExponent) {
+ exp = maxExponent;
+ WARN_PRINT("Exponent too high");
+ }
+ dblExp = 1.0;
+ for (d = powersOf10; exp != 0; exp >>= 1, ++d) {
+ if (exp & 01) {
+ dblExp *= *d;
+ }
+ }
+ if (expSign) {
+ fraction /= dblExp;
+ } else {
+ fraction *= dblExp;
}
- }
- if (expSign) {
- fraction /= dblExp;
- } else {
- fraction *= dblExp;
- }
- done:
- if (endPtr != NULL) {
- *endPtr = (C *) p;
- }
+done:
+ if (endPtr != NULL) {
+ *endPtr = (C *)p;
+ }
- if (sign) {
- return -fraction;
- }
- return fraction;
+ if (sign) {
+ return -fraction;
+ }
+ return fraction;
}
-
-
#define READING_SIGN 0
#define READING_INT 1
#define READING_DEC 2
#define READING_EXP 3
#define READING_DONE 4
-double String::to_double(const char* p_str) {
+double String::to_double(const char *p_str) {
#ifndef NO_USE_STDLIB
return built_in_strtod<char>(p_str);
- //return atof(p_str); DOES NOT WORK ON ANDROID(??)
+//return atof(p_str); DOES NOT WORK ON ANDROID(??)
#else
return built_in_strtod<char>(p_str);
#endif
@@ -2112,15 +2011,14 @@ double String::to_double(const char* p_str) {
#endif
}
-
float String::to_float() const {
return to_double();
}
-double String::to_double(const CharType* p_str, const CharType **r_end) {
+double String::to_double(const CharType *p_str, const CharType **r_end) {
- return built_in_strtod<CharType>(p_str,(CharType**)r_end);
+ return built_in_strtod<CharType>(p_str, (CharType **)r_end);
#if 0
#if 0
//ndef NO_USE_STDLIB
@@ -2217,34 +2115,34 @@ double String::to_double(const CharType* p_str, const CharType **r_end) {
#endif
}
-int64_t String::to_int(const CharType* p_str,int p_len) {
+int64_t String::to_int(const CharType *p_str, int p_len) {
- if (p_len==0 || !p_str[0])
+ if (p_len == 0 || !p_str[0])
return 0;
-///@todo make more exact so saving and loading does not lose precision
+ ///@todo make more exact so saving and loading does not lose precision
- int64_t integer=0;
- int64_t sign=1;
- int reading=READING_SIGN;
+ int64_t integer = 0;
+ int64_t sign = 1;
+ int reading = READING_SIGN;
- const CharType *str=p_str;
- const CharType *limit=&p_str[p_len];
+ const CharType *str = p_str;
+ const CharType *limit = &p_str[p_len];
- while(*str && reading!=READING_DONE && str!=limit) {
+ while (*str && reading != READING_DONE && str != limit) {
- CharType c=*(str++);
- switch(reading) {
+ CharType c = *(str++);
+ switch (reading) {
case READING_SIGN: {
- if (c>='0' && c<='9') {
- reading=READING_INT;
+ if (c >= '0' && c <= '9') {
+ reading = READING_INT;
// let it fallthrough
- } else if (c=='-') {
- sign=-1;
- reading=READING_INT;
+ } else if (c == '-') {
+ sign = -1;
+ reading = READING_INT;
break;
- } else if (c=='+') {
- sign=1;
- reading=READING_INT;
+ } else if (c == '+') {
+ sign = 1;
+ reading = READING_INT;
break;
} else {
break;
@@ -2252,30 +2150,28 @@ int64_t String::to_int(const CharType* p_str,int p_len) {
}
case READING_INT: {
- if (c>='0' && c<='9') {
+ if (c >= '0' && c <= '9') {
- integer*=10;
- integer+=c-'0';
+ integer *= 10;
+ integer += c - '0';
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
}
}
- return sign*integer;
-
+ return sign * integer;
}
-
double String::to_double() const {
if (empty())
return 0;
#ifndef NO_USE_STDLIB
return built_in_strtod<CharType>(c_str());
- //return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :(
+//return wcstod(c_str(),NULL); DOES NOT WORK ON ANDROID :(
#else
return built_in_strtod<CharType>(c_str());
#endif
@@ -2373,26 +2269,23 @@ double String::to_double() const {
#endif
}
+bool operator==(const char *p_chr, const String &p_str) {
-bool operator==(const char*p_chr, const String& p_str) {
-
- return p_str==p_chr;
+ return p_str == p_chr;
}
-String operator+(const char*p_chr, const String& p_str) {
+String operator+(const char *p_chr, const String &p_str) {
- String tmp=p_chr;
- tmp+=p_str;
+ String tmp = p_chr;
+ tmp += p_str;
return tmp;
-
}
-String operator+(CharType p_chr, const String& p_str) {
-
- return (String::chr(p_chr)+p_str);
+String operator+(CharType p_chr, const String &p_str) {
+ return (String::chr(p_chr) + p_str);
}
-uint32_t String::hash(const char* p_cstr) {
+uint32_t String::hash(const char *p_cstr) {
uint32_t hashv = 5381;
uint32_t c;
@@ -2403,25 +2296,25 @@ uint32_t String::hash(const char* p_cstr) {
return hashv;
}
-uint32_t String::hash(const char* p_cstr,int p_len) {
+uint32_t String::hash(const char *p_cstr, int p_len) {
uint32_t hashv = 5381;
- for(int i=0;i<p_len;i++)
+ for (int i = 0; i < p_len; i++)
hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
return hashv;
}
-uint32_t String::hash(const CharType* p_cstr,int p_len) {
+uint32_t String::hash(const CharType *p_cstr, int p_len) {
uint32_t hashv = 5381;
- for(int i=0;i<p_len;i++)
+ for (int i = 0; i < p_len; i++)
hashv = ((hashv << 5) + hashv) + p_cstr[i]; /* hash * 33 + c */
return hashv;
}
-uint32_t String::hash(const CharType* p_cstr) {
+uint32_t String::hash(const CharType *p_cstr) {
uint32_t hashv = 5381;
uint32_t c;
@@ -2436,7 +2329,7 @@ uint32_t String::hash() const {
/* simple djb2 hashing */
- const CharType * chr = c_str();
+ const CharType *chr = c_str();
uint32_t hashv = 5381;
uint32_t c;
@@ -2444,15 +2337,13 @@ uint32_t String::hash() const {
hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
return hashv;
-
-
}
uint64_t String::hash64() const {
/* simple djb2 hashing */
- const CharType * chr = c_str();
+ const CharType *chr = c_str();
uint64_t hashv = 5381;
uint64_t c;
@@ -2460,41 +2351,39 @@ uint64_t String::hash64() const {
hashv = ((hashv << 5) + hashv) + c; /* hash * 33 + c */
return hashv;
-
-
}
String String::md5_text() const {
- CharString cs=utf8();
+ CharString cs = utf8();
MD5_CTX ctx;
MD5Init(&ctx);
- MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length());
+ MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length());
MD5Final(&ctx);
return String::md5(ctx.digest);
}
String String::sha256_text() const {
- CharString cs=utf8();
+ CharString cs = utf8();
unsigned char hash[32];
sha256_context ctx;
sha256_init(&ctx);
- sha256_hash(&ctx,(unsigned char*)cs.ptr(),cs.length());
+ sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length());
sha256_done(&ctx, hash);
return String::hex_encode_buffer(hash, 32);
}
Vector<uint8_t> String::md5_buffer() const {
- CharString cs=utf8();
+ CharString cs = utf8();
MD5_CTX ctx;
MD5Init(&ctx);
- MD5Update(&ctx,(unsigned char*)cs.ptr(),cs.length());
+ MD5Update(&ctx, (unsigned char *)cs.ptr(), cs.length());
MD5Final(&ctx);
Vector<uint8_t> ret;
ret.resize(16);
- for (int i=0; i<16; i++) {
+ for (int i = 0; i < 16; i++) {
ret[i] = ctx.digest[i];
};
@@ -2506,7 +2395,7 @@ Vector<uint8_t> String::sha256_buffer() const {
unsigned char hash[32];
sha256_context ctx;
sha256_init(&ctx);
- sha256_hash(&ctx, (unsigned char*)cs.ptr(), cs.length());
+ sha256_hash(&ctx, (unsigned char *)cs.ptr(), cs.length());
sha256_done(&ctx, hash);
Vector<uint8_t> ret;
@@ -2518,85 +2407,79 @@ Vector<uint8_t> String::sha256_buffer() const {
return ret;
}
+String String::insert(int p_at_pos, String p_string) const {
-String String::insert(int p_at_pos,String p_string) const {
-
- if (p_at_pos<0)
+ if (p_at_pos < 0)
return *this;
- if (p_at_pos>length())
- p_at_pos=length();
-
+ if (p_at_pos > length())
+ p_at_pos = length();
String pre;
- if (p_at_pos>0)
- pre=substr( 0, p_at_pos );
+ if (p_at_pos > 0)
+ pre = substr(0, p_at_pos);
String post;
- if (p_at_pos<length())
- post=substr( p_at_pos, length()-p_at_pos);
-
- return pre+p_string+post;
+ if (p_at_pos < length())
+ post = substr(p_at_pos, length() - p_at_pos);
+ return pre + p_string + post;
}
-String String::substr(int p_from,int p_chars) const{
+String String::substr(int p_from, int p_chars) const {
- if (empty() || p_from<0 || p_from>=length() || p_chars<=0)
+ if (empty() || p_from < 0 || p_from >= length() || p_chars <= 0)
return "";
- if ( (p_from+p_chars)>length()) {
+ if ((p_from + p_chars) > length()) {
- p_chars=length()-p_from;
+ p_chars = length() - p_from;
}
- return String(&c_str()[p_from],p_chars);
-
+ return String(&c_str()[p_from], p_chars);
}
int String::find_last(String p_str) const {
- int pos=-1;
- int findfrom=0;
- int findres=-1;
- while((findres=find(p_str,findfrom))!=-1) {
+ int pos = -1;
+ int findfrom = 0;
+ int findres = -1;
+ while ((findres = find(p_str, findfrom)) != -1) {
- pos=findres;
- findfrom=pos+1;
+ pos = findres;
+ findfrom = pos + 1;
}
return pos;
}
-int String::find(String p_str,int p_from) const {
+int String::find(String p_str, int p_from) const {
- if (p_from<0)
+ if (p_from < 0)
return -1;
- int src_len=p_str.length();
+ int src_len = p_str.length();
- int len=length();
+ int len = length();
- if(src_len==0 || len==0)
+ if (src_len == 0 || len == 0)
return -1; //wont find anything!
-
const CharType *src = c_str();
- for (int i=p_from;i<=(len-src_len);i++) {
+ for (int i = p_from; i <= (len - src_len); i++) {
- bool found=true;
- for (int j=0;j<src_len;j++) {
+ bool found = true;
+ for (int j = 0; j < src_len; j++) {
- int read_pos=i+j;
+ int read_pos = i + j;
- if (read_pos>=len) {
+ if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
};
-
- if (src[read_pos]!=p_str[j]) {
- found=false;
+ if (src[read_pos] != p_str[j]) {
+ found = false;
break;
}
}
@@ -2608,48 +2491,46 @@ int String::find(String p_str,int p_from) const {
return -1;
}
-int String::findmk(const Vector<String>& p_keys,int p_from,int *r_key) const {
+int String::findmk(const Vector<String> &p_keys, int p_from, int *r_key) const {
- if (p_from<0)
+ if (p_from < 0)
return -1;
- if (p_keys.size()==0)
+ if (p_keys.size() == 0)
return -1;
//int src_len=p_str.length();
- const String *keys=&p_keys[0];
- int key_count=p_keys.size();
+ const String *keys = &p_keys[0];
+ int key_count = p_keys.size();
int len = length();
- if(len==0)
+ if (len == 0)
return -1; //wont find anything!
const CharType *src = c_str();
+ for (int i = p_from; i < len; i++) {
- for (int i=p_from;i<len;i++) {
-
- bool found=true;
- for(int k=0;k<key_count;k++) {
+ bool found = true;
+ for (int k = 0; k < key_count; k++) {
- found=true;
+ found = true;
if (r_key)
- *r_key=k;
- const CharType *cmp=keys[k].c_str();
- int l=keys[k].length();
+ *r_key = k;
+ const CharType *cmp = keys[k].c_str();
+ int l = keys[k].length();
- for (int j=0;j<l;j++) {
+ for (int j = 0; j < l; j++) {
- int read_pos=i+j;
+ int read_pos = i + j;
- if (read_pos>=len) {
+ if (read_pos >= len) {
- found=false;
+ found = false;
break;
};
-
- if (src[read_pos]!=cmp[j]) {
- found=false;
+ if (src[read_pos] != cmp[j]) {
+ found = false;
break;
}
}
@@ -2662,41 +2543,38 @@ int String::findmk(const Vector<String>& p_keys,int p_from,int *r_key) const {
}
return -1;
-
}
+int String::findn(String p_str, int p_from) const {
-int String::findn(String p_str,int p_from) const {
-
- if (p_from<0)
+ if (p_from < 0)
return -1;
- int src_len=p_str.length();
+ int src_len = p_str.length();
- if(src_len==0 || length()==0)
+ if (src_len == 0 || length() == 0)
return -1; //wont find anything!
const CharType *srcd = c_str();
- for (int i=p_from;i<=(length()-src_len);i++) {
+ for (int i = p_from; i <= (length() - src_len); i++) {
- bool found=true;
- for (int j=0;j<src_len;j++) {
+ bool found = true;
+ for (int j = 0; j < src_len; j++) {
- int read_pos=i+j;
+ int read_pos = i + j;
- if (read_pos>=length()) {
+ if (read_pos >= length()) {
ERR_PRINT("read_pos>=length()");
return -1;
};
+ CharType src = _find_lower(srcd[read_pos]);
+ CharType dst = _find_lower(p_str[j]);
- CharType src=_find_lower(srcd[read_pos]);
- CharType dst=_find_lower(p_str[j]);
-
- if (src!=dst) {
- found=false;
+ if (src != dst) {
+ found = false;
break;
}
}
@@ -2708,44 +2586,42 @@ int String::findn(String p_str,int p_from) const {
return -1;
}
-int String::rfind(String p_str,int p_from) const {
+int String::rfind(String p_str, int p_from) const {
//stabilish a limit
- int limit = length()-p_str.length();
- if (limit<0)
+ int limit = length() - p_str.length();
+ if (limit < 0)
return -1;
//stabilish a starting point
- if (p_from<0)
- p_from=limit;
- else if (p_from>limit)
- p_from=limit;
+ if (p_from < 0)
+ p_from = limit;
+ else if (p_from > limit)
+ p_from = limit;
- int src_len=p_str.length();
- int len=length();
+ int src_len = p_str.length();
+ int len = length();
- if(src_len==0 || len==0)
+ if (src_len == 0 || len == 0)
return -1; //wont find anything!
-
const CharType *src = c_str();
- for (int i=p_from;i>=0;i--) {
+ for (int i = p_from; i >= 0; i--) {
- bool found=true;
- for (int j=0;j<src_len;j++) {
+ bool found = true;
+ for (int j = 0; j < src_len; j++) {
- int read_pos=i+j;
+ int read_pos = i + j;
- if (read_pos>=len) {
+ if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
};
-
- if (src[read_pos]!=p_str[j]) {
- found=false;
+ if (src[read_pos] != p_str[j]) {
+ found = false;
break;
}
}
@@ -2756,47 +2632,45 @@ int String::rfind(String p_str,int p_from) const {
return -1;
}
-int String::rfindn(String p_str,int p_from) const {
+int String::rfindn(String p_str, int p_from) const {
//stabilish a limit
- int limit = length()-p_str.length();
- if (limit<0)
+ int limit = length() - p_str.length();
+ if (limit < 0)
return -1;
//stabilish a starting point
- if (p_from<0)
- p_from=limit;
- else if (p_from>limit)
- p_from=limit;
+ if (p_from < 0)
+ p_from = limit;
+ else if (p_from > limit)
+ p_from = limit;
- int src_len=p_str.length();
- int len=length();
+ int src_len = p_str.length();
+ int len = length();
- if(src_len==0 || len==0)
+ if (src_len == 0 || len == 0)
return -1; //wont find anything!
-
const CharType *src = c_str();
- for (int i=p_from;i>=0;i--) {
+ for (int i = p_from; i >= 0; i--) {
- bool found=true;
- for (int j=0;j<src_len;j++) {
+ bool found = true;
+ for (int j = 0; j < src_len; j++) {
- int read_pos=i+j;
+ int read_pos = i + j;
- if (read_pos>=len) {
+ if (read_pos >= len) {
ERR_PRINT("read_pos>=len");
return -1;
};
- CharType srcc=_find_lower(src[read_pos]);
- CharType dstc=_find_lower(p_str[j]);
-
+ CharType srcc = _find_lower(src[read_pos]);
+ CharType dstc = _find_lower(p_str[j]);
- if (srcc!=dstc) {
- found=false;
+ if (srcc != dstc) {
+ found = false;
break;
}
}
@@ -2808,75 +2682,69 @@ int String::rfindn(String p_str,int p_from) const {
return -1;
}
-
-bool String::ends_with(const String& p_string) const {
-
+bool String::ends_with(const String &p_string) const {
int pos = find_last(p_string);
- if (pos==-1)
+ if (pos == -1)
return false;
- return pos+p_string.length()==length();
-
+ return pos + p_string.length() == length();
}
-bool String::begins_with(const String& p_string) const {
+bool String::begins_with(const String &p_string) const {
if (p_string.length() > length())
return false;
- int l=p_string.length();
- if (l==0)
+ int l = p_string.length();
+ if (l == 0)
return true;
- const CharType *src=&p_string[0];
- const CharType *str=&operator[](0);
+ const CharType *src = &p_string[0];
+ const CharType *str = &operator[](0);
int i = 0;
- for (;i<l;i++) {
+ for (; i < l; i++) {
- if (src[i]!=str[i])
+ if (src[i] != str[i])
return false;
}
// only if i == l the p_string matches the beginning
return i == l;
-
}
-bool String::begins_with(const char* p_string) const {
+bool String::begins_with(const char *p_string) const {
- int l=length();
- if (l==0||!p_string)
+ int l = length();
+ if (l == 0 || !p_string)
return false;
- const CharType *str=&operator[](0);
- int i=0;
+ const CharType *str = &operator[](0);
+ int i = 0;
- while (*p_string && i<l) {
+ while (*p_string && i < l) {
if (*p_string != str[i])
return false;
i++;
p_string++;
-
}
return *p_string == 0;
-
}
-bool String::is_subsequence_of(const String& p_string) const {
+bool String::is_subsequence_of(const String &p_string) const {
return _base_is_subsequence_of(p_string, false);
}
-bool String::is_subsequence_ofi(const String& p_string) const {
+bool String::is_subsequence_ofi(const String &p_string) const {
return _base_is_subsequence_of(p_string, true);
}
-bool String::_base_is_subsequence_of(const String& p_string, bool case_insensitive) const {
+bool String::_base_is_subsequence_of(const String &p_string, bool case_insensitive) const {
- int len=length();
+ int len = length();
if (len == 0) {
// Technically an empty string is subsequence of any string
return true;
@@ -2889,7 +2757,7 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti
const CharType *src = &operator[](0);
const CharType *tgt = &p_string[0];
- for (;*src && *tgt;tgt++) {
+ for (; *src && *tgt; tgt++) {
bool match = false;
if (case_insensitive) {
CharType srcc = _find_lower(*src);
@@ -2900,7 +2768,7 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti
}
if (match) {
src++;
- if(!*src) {
+ if (!*src) {
return true;
}
}
@@ -2912,19 +2780,19 @@ bool String::_base_is_subsequence_of(const String& p_string, bool case_insensiti
Vector<String> String::bigrams() const {
int n_pairs = length() - 1;
Vector<String> b;
- if(n_pairs <= 0) {
+ if (n_pairs <= 0) {
return b;
}
b.resize(n_pairs);
- for(int i = 0; i < n_pairs; i++) {
- b[i] = substr(i,2);
+ for (int i = 0; i < n_pairs; i++) {
+ b[i] = substr(i, 2);
}
return b;
}
// Similarity according to Sorensen-Dice coefficient
-float String::similarity(const String& p_string) const {
- if(operator==(p_string)) {
+float String::similarity(const String &p_string) const {
+ if (operator==(p_string)) {
// Equal strings are totally similar
return 1.0f;
}
@@ -2950,187 +2818,183 @@ float String::similarity(const String& p_string) const {
}
}
- return (2.0f * inter)/sum;
+ return (2.0f * inter) / sum;
}
-static bool _wildcard_match(const CharType* p_pattern, const CharType* p_string,bool p_case_sensitive) {
+static bool _wildcard_match(const CharType *p_pattern, const CharType *p_string, bool p_case_sensitive) {
switch (*p_pattern) {
- case '\0':
- return !*p_string;
- case '*' :
- return _wildcard_match(p_pattern+1, p_string,p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string+1,p_case_sensitive));
- case '?' :
- return *p_string && (*p_string != '.') && _wildcard_match(p_pattern+1, p_string+1,p_case_sensitive);
- default :
-
- return (p_case_sensitive?(*p_string==*p_pattern):(_find_upper(*p_string)==_find_upper(*p_pattern))) && _wildcard_match(p_pattern+1, p_string+1,p_case_sensitive);
+ case '\0':
+ return !*p_string;
+ case '*':
+ return _wildcard_match(p_pattern + 1, p_string, p_case_sensitive) || (*p_string && _wildcard_match(p_pattern, p_string + 1, p_case_sensitive));
+ case '?':
+ return *p_string && (*p_string != '.') && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
+ default:
+
+ return (p_case_sensitive ? (*p_string == *p_pattern) : (_find_upper(*p_string) == _find_upper(*p_pattern))) && _wildcard_match(p_pattern + 1, p_string + 1, p_case_sensitive);
}
}
-
-bool String::match(const String& p_wildcard) const {
+bool String::match(const String &p_wildcard) const {
if (!p_wildcard.length() || !length())
return false;
- return _wildcard_match(p_wildcard.c_str(),c_str(),true);
-
+ return _wildcard_match(p_wildcard.c_str(), c_str(), true);
}
-bool String::matchn(const String& p_wildcard) const {
+bool String::matchn(const String &p_wildcard) const {
if (!p_wildcard.length() || !length())
return false;
- return _wildcard_match(p_wildcard.c_str(),c_str(),false);
-
+ return _wildcard_match(p_wildcard.c_str(), c_str(), false);
}
-String String::format(const Variant& values,String placeholder) const {
+String String::format(const Variant &values, String placeholder) const {
- String new_string = String( this->ptr() );
+ String new_string = String(this->ptr());
- if( values.get_type() == Variant::ARRAY ) {
+ if (values.get_type() == Variant::ARRAY) {
Array values_arr = values;
- for(int i=0;i<values_arr.size();i++) {
- String i_as_str = String::num_int64( i );
+ for (int i = 0; i < values_arr.size(); i++) {
+ String i_as_str = String::num_int64(i);
- if( values_arr[i].get_type() == Variant::ARRAY ) {//Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
+ if (values_arr[i].get_type() == Variant::ARRAY) { //Array in Array structure [["name","RobotGuy"],[0,"godot"],["strength",9000.91]]
Array value_arr = values_arr[i];
- if( value_arr.size()==2 ) {
+ if (value_arr.size() == 2) {
Variant v_key = value_arr[0];
String key;
key = v_key.get_construct_string();
- if( key.left(1)=="\"" && key.right(key.length()-1)=="\"" ) {
- key = key.substr(1,key.length()-2);
+ if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") {
+ key = key.substr(1, key.length() - 2);
}
Variant v_val = value_arr[1];
String val;
val = v_val.get_construct_string();
- if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) {
- val = val.substr(1,val.length()-2);
+ if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
+ val = val.substr(1, val.length() - 2);
}
- new_string = new_string.replacen( placeholder.replace("_", key ), val );
- }else {
+ new_string = new_string.replacen(placeholder.replace("_", key), val);
+ } else {
ERR_PRINT(String("STRING.format Inner Array size != 2 ").ascii().get_data());
}
- } else {//Array structure ["RobotGuy","Logis","rookie"]
+ } else { //Array structure ["RobotGuy","Logis","rookie"]
Variant v_val = values_arr[i];
String val;
val = v_val.get_construct_string();
- if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) {
- val = val.substr(1,val.length()-2);
+ if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
+ val = val.substr(1, val.length() - 2);
}
- new_string = new_string.replacen( placeholder.replace("_", i_as_str ), val );
+ new_string = new_string.replacen(placeholder.replace("_", i_as_str), val);
}
}
- }else if( values.get_type() == Variant::DICTIONARY ) {
+ } else if (values.get_type() == Variant::DICTIONARY) {
Dictionary d = values;
List<Variant> keys;
d.get_key_list(&keys);
- for (List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
String key = E->get().get_construct_string();
String val = d[E->get()].get_construct_string();
- if( key.left(1)=="\"" && key.right(key.length()-1)=="\"" ) {
- key = key.substr(1,key.length()-2);
+ if (key.left(1) == "\"" && key.right(key.length() - 1) == "\"") {
+ key = key.substr(1, key.length() - 2);
}
- if( val.left(1)=="\"" && val.right(val.length()-1)=="\"" ) {
- val = val.substr(1,val.length()-2);
+ if (val.left(1) == "\"" && val.right(val.length() - 1) == "\"") {
+ val = val.substr(1, val.length() - 2);
}
- new_string = new_string.replacen( placeholder.replace("_", key ), val );
+ new_string = new_string.replacen(placeholder.replace("_", key), val);
}
- }else{
+ } else {
ERR_PRINT(String("Invalid type: use Array or Dictionary.").ascii().get_data());
}
return new_string;
}
-String String::replace(String p_key,String p_with) const {
+String String::replace(String p_key, String p_with) const {
String new_string;
- int search_from=0;
- int result=0;
+ int search_from = 0;
+ int result = 0;
- while( (result=find(p_key,search_from))>=0 ) {
+ while ((result = find(p_key, search_from)) >= 0) {
- new_string+=substr(search_from,result-search_from);
- new_string+=p_with;
- search_from=result+p_key.length();
+ new_string += substr(search_from, result - search_from);
+ new_string += p_with;
+ search_from = result + p_key.length();
}
- new_string+=substr(search_from,length()-search_from);
+ new_string += substr(search_from, length() - search_from);
return new_string;
}
-String String::replace_first(String p_key,String p_with) const {
+String String::replace_first(String p_key, String p_with) const {
String new_string;
- int search_from=0;
- int result=0;
+ int search_from = 0;
+ int result = 0;
- while( (result=find(p_key,search_from))>=0 ) {
+ while ((result = find(p_key, search_from)) >= 0) {
- new_string+=substr(search_from,result-search_from);
- new_string+=p_with;
- search_from=result+p_key.length();
+ new_string += substr(search_from, result - search_from);
+ new_string += p_with;
+ search_from = result + p_key.length();
break;
}
- new_string+=substr(search_from,length()-search_from);
+ new_string += substr(search_from, length() - search_from);
return new_string;
}
-String String::replacen(String p_key,String p_with) const {
+String String::replacen(String p_key, String p_with) const {
String new_string;
- int search_from=0;
- int result=0;
+ int search_from = 0;
+ int result = 0;
- while( (result=findn(p_key,search_from))>=0 ) {
+ while ((result = findn(p_key, search_from)) >= 0) {
- new_string+=substr(search_from,result-search_from);
- new_string+=p_with;
- search_from=result+p_key.length();
+ new_string += substr(search_from, result - search_from);
+ new_string += p_with;
+ search_from = result + p_key.length();
}
- new_string+=substr(search_from,length()-search_from);
+ new_string += substr(search_from, length() - search_from);
return new_string;
}
-
String String::left(int p_pos) const {
- if (p_pos<=0)
+ if (p_pos <= 0)
return "";
- if (p_pos>=length())
+ if (p_pos >= length())
return *this;
- return substr(0,p_pos);
+ return substr(0, p_pos);
}
String String::right(int p_pos) const {
- if (p_pos>=size())
+ if (p_pos >= size())
return *this;
- if (p_pos<0)
+ if (p_pos < 0)
return "";
- return substr(p_pos,(length()-p_pos));
+ return substr(p_pos, (length() - p_pos));
}
CharType String::ord_at(int p_idx) const {
@@ -3141,140 +3005,141 @@ CharType String::ord_at(int p_idx) const {
String String::strip_edges(bool left, bool right) const {
- int len=length();
- int beg=0,end=len;
+ int len = length();
+ int beg = 0, end = len;
- if(left) {
- for (int i=0;i<len;i++) {
+ if (left) {
+ for (int i = 0; i < len; i++) {
- if (operator[](i)<=32)
+ if (operator[](i) <= 32)
beg++;
else
break;
}
}
- if(right) {
- for (int i=(int)(len-1);i>=0;i--) {
+ if (right) {
+ for (int i = (int)(len - 1); i >= 0; i--) {
- if (operator[](i)<=32)
+ if (operator[](i) <= 32)
end--;
else
break;
}
}
- if (beg==0 && end==len)
+ if (beg == 0 && end == len)
return *this;
- return substr(beg,end-beg);
+ return substr(beg, end - beg);
}
String String::strip_escapes() const {
- int len=length();
- int beg=0,end=len;
+ int len = length();
+ int beg = 0, end = len;
- for (int i=0;i<length();i++) {
+ for (int i = 0; i < length(); i++) {
- if (operator[](i)<=31)
+ if (operator[](i) <= 31)
beg++;
else
break;
}
- for (int i=(int)(length()-1);i>=0;i--) {
+ for (int i = (int)(length() - 1); i >= 0; i--) {
- if (operator[](i)<=31)
+ if (operator[](i) <= 31)
end--;
else
break;
}
- if (beg==0 && end==len)
+ if (beg == 0 && end == len)
return *this;
- return substr(beg,end-beg);
+ return substr(beg, end - beg);
}
String String::simplify_path() const {
-
String s = *this;
String drive;
if (s.begins_with("local://")) {
- drive="local://";
- s=s.substr(8,s.length());
+ drive = "local://";
+ s = s.substr(8, s.length());
} else if (s.begins_with("res://")) {
- drive="res://";
- s=s.substr(6,s.length());
+ drive = "res://";
+ s = s.substr(6, s.length());
} else if (s.begins_with("user://")) {
- drive="user://";
- s=s.substr(6,s.length());
+ drive = "user://";
+ s = s.substr(6, s.length());
} else if (s.begins_with("/") || s.begins_with("\\")) {
- drive=s.substr(0,1);
- s=s.substr(1,s.length()-1);
+ drive = s.substr(0, 1);
+ s = s.substr(1, s.length() - 1);
} else {
int p = s.find(":/");
- if (p==-1)
- p=s.find(":\\");
- if (p!=-1 && p < s.find("/")) {
+ if (p == -1)
+ p = s.find(":\\");
+ if (p != -1 && p < s.find("/")) {
- drive=s.substr(0,p+2);
- s=s.substr(p+2,s.length());
+ drive = s.substr(0, p + 2);
+ s = s.substr(p + 2, s.length());
}
}
- s =s.replace("\\","/");
- while(true){ // in case of using 2 or more slash
- String compare = s.replace("//","/");
- if (s==compare) break;
- else s=compare;
+ s = s.replace("\\", "/");
+ while (true) { // in case of using 2 or more slash
+ String compare = s.replace("//", "/");
+ if (s == compare)
+ break;
+ else
+ s = compare;
}
- Vector<String> dirs = s.split("/",false);
+ Vector<String> dirs = s.split("/", false);
- for(int i=0;i<dirs.size();i++) {
+ for (int i = 0; i < dirs.size(); i++) {
String d = dirs[i];
- if (d==".") {
+ if (d == ".") {
dirs.remove(i);
i--;
- } else if (d=="..") {
+ } else if (d == "..") {
- if (i==0) {
+ if (i == 0) {
dirs.remove(i);
i--;
} else {
dirs.remove(i);
- dirs.remove(i-1);
- i-=2;
+ dirs.remove(i - 1);
+ i -= 2;
}
}
}
- s="";
+ s = "";
- for(int i=0;i<dirs.size();i++) {
+ for (int i = 0; i < dirs.size(); i++) {
- if (i>0)
- s+="/";
- s+=dirs[i];
+ if (i > 0)
+ s += "/";
+ s += dirs[i];
}
- return drive+s;
+ return drive + s;
}
static int _humanize_digits(int p_num) {
- if (p_num<10)
+ if (p_num < 10)
return 2;
- else if (p_num<100)
+ else if (p_num < 100)
return 2;
- else if (p_num<1024)
+ else if (p_num < 1024)
return 1;
else
return 0;
@@ -3282,26 +3147,26 @@ static int _humanize_digits(int p_num) {
String String::humanize_size(size_t p_size) {
- uint64_t _div=1;
- static const char* prefix[]={" Bytes"," KB"," MB"," GB","TB"," PB","HB",""};
- int prefix_idx=0;
+ uint64_t _div = 1;
+ static const char *prefix[] = { " Bytes", " KB", " MB", " GB", "TB", " PB", "HB", "" };
+ int prefix_idx = 0;
- while(p_size>(_div*1024) && prefix[prefix_idx][0]) {
- _div*=1024;
+ while (p_size > (_div * 1024) && prefix[prefix_idx][0]) {
+ _div *= 1024;
prefix_idx++;
}
- int digits=prefix_idx>0?_humanize_digits(p_size/_div):0;
- double divisor = prefix_idx>0?_div:1;
+ int digits = prefix_idx > 0 ? _humanize_digits(p_size / _div) : 0;
+ double divisor = prefix_idx > 0 ? _div : 1;
- return String::num(p_size/divisor,digits)+prefix[prefix_idx];
+ return String::num(p_size / divisor, digits) + prefix[prefix_idx];
}
bool String::is_abs_path() const {
- if (length()>1)
- return (operator[](0)=='/' || operator[](0)=='\\' || find(":/")!=-1 || find(":\\")!=-1);
- else if ((length())==1)
- return (operator[](0)=='/' || operator[](0)=='\\');
+ if (length() > 1)
+ return (operator[](0) == '/' || operator[](0) == '\\' || find(":/") != -1 || find(":\\") != -1);
+ else if ((length()) == 1)
+ return (operator[](0) == '/' || operator[](0) == '\\');
else
return false;
}
@@ -3310,24 +3175,22 @@ bool String::is_valid_identifier() const {
int len = length();
- if (len==0)
+ if (len == 0)
return false;
- const wchar_t * str = &operator[](0);
-
+ const wchar_t *str = &operator[](0);
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i==0) {
- if (str[0]>='0' && str[0]<='9')
+ if (i == 0) {
+ if (str[0] >= '0' && str[0] <= '9')
return false; // no start with number plz
}
- bool valid_char = (str[i]>='0' && str[i]<='9') || (str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z') || str[i]=='_';
+ bool valid_char = (str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '_';
if (!valid_char)
return false;
-
}
return true;
@@ -3337,150 +3200,150 @@ bool String::is_valid_identifier() const {
String String::word_wrap(int p_chars_per_line) const {
- int from=0;
- int last_space=0;
+ int from = 0;
+ int last_space = 0;
String ret;
- for(int i=0;i<length();i++) {
- if (i-from>=p_chars_per_line) {
- if (last_space==-1) {
- ret+=substr(from,i-from+1)+"\n";
+ for (int i = 0; i < length(); i++) {
+ if (i - from >= p_chars_per_line) {
+ if (last_space == -1) {
+ ret += substr(from, i - from + 1) + "\n";
} else {
- ret+=substr(from,last_space-from)+"\n";
- i=last_space; //rewind
+ ret += substr(from, last_space - from) + "\n";
+ i = last_space; //rewind
}
- from=i+1;
- last_space=-1;
- } else if (operator[](i)==' ' || operator[](i)=='\t') {
- last_space=i;
- } else if (operator[](i)=='\n') {
- ret+=substr(from,i-from)+"\n";
- from=i+1;
- last_space=-1;
+ from = i + 1;
+ last_space = -1;
+ } else if (operator[](i) == ' ' || operator[](i) == '\t') {
+ last_space = i;
+ } else if (operator[](i) == '\n') {
+ ret += substr(from, i - from) + "\n";
+ from = i + 1;
+ last_space = -1;
}
}
- if (from<length()) {
- ret+=substr(from,length());
+ if (from < length()) {
+ ret += substr(from, length());
}
return ret;
}
String String::http_escape() const {
- const CharString temp = utf8();
- String res;
- for (int i = 0; i < length(); ++i) {
- CharType ord = temp[i];
- if (ord == '.' || ord == '-' || ord == '_' || ord == '~' ||
- (ord >= 'a' && ord <= 'z') ||
- (ord >= 'A' && ord <= 'Z') ||
- (ord >= '0' && ord <= '9')) {
- res += ord;
- } else {
- char h_Val[3];
+ const CharString temp = utf8();
+ String res;
+ for (int i = 0; i < length(); ++i) {
+ CharType ord = temp[i];
+ if (ord == '.' || ord == '-' || ord == '_' || ord == '~' ||
+ (ord >= 'a' && ord <= 'z') ||
+ (ord >= 'A' && ord <= 'Z') ||
+ (ord >= '0' && ord <= '9')) {
+ res += ord;
+ } else {
+ char h_Val[3];
#if defined(__GNUC__) || defined(_MSC_VER)
- snprintf(h_Val, 3, "%.2X", ord);
+ snprintf(h_Val, 3, "%.2X", ord);
#else
- sprintf(h_Val, "%.2X", ord);
+ sprintf(h_Val, "%.2X", ord);
#endif
- res += "%";
- res += h_Val;
- }
- }
- return res;
+ res += "%";
+ res += h_Val;
+ }
+ }
+ return res;
}
String String::http_unescape() const {
- String res;
- for (int i = 0; i < length(); ++i) {
- if (ord_at(i) == '%' && i+2 < length()) {
- CharType ord1 = ord_at(i+1);
- if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) {
- CharType ord2 = ord_at(i+2);
- if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) {
- char bytes[2] = {ord1, ord2};
- res += (char)strtol(bytes, NULL, 16);
- i+=2;
- }
- } else {
- res += ord_at(i);
- }
- } else {
- res += ord_at(i);
- }
- }
- return String::utf8(res.ascii());
+ String res;
+ for (int i = 0; i < length(); ++i) {
+ if (ord_at(i) == '%' && i + 2 < length()) {
+ CharType ord1 = ord_at(i + 1);
+ if ((ord1 >= '0' && ord1 <= '9') || (ord1 >= 'A' && ord1 <= 'Z')) {
+ CharType ord2 = ord_at(i + 2);
+ if ((ord2 >= '0' && ord2 <= '9') || (ord2 >= 'A' && ord2 <= 'Z')) {
+ char bytes[2] = { ord1, ord2 };
+ res += (char)strtol(bytes, NULL, 16);
+ i += 2;
+ }
+ } else {
+ res += ord_at(i);
+ }
+ } else {
+ res += ord_at(i);
+ }
+ }
+ return String::utf8(res.ascii());
}
String String::c_unescape() const {
- String escaped=*this;
- escaped=escaped.replace("\\a","\a");
- escaped=escaped.replace("\\b","\b");
- escaped=escaped.replace("\\f","\f");
- escaped=escaped.replace("\\n","\n");
- escaped=escaped.replace("\\r","\r");
- escaped=escaped.replace("\\t","\t");
- escaped=escaped.replace("\\v","\v");
- escaped=escaped.replace("\\'","\'");
- escaped=escaped.replace("\\\"","\"");
- escaped=escaped.replace("\\?","\?");
- escaped=escaped.replace("\\\\","\\");
+ String escaped = *this;
+ escaped = escaped.replace("\\a", "\a");
+ escaped = escaped.replace("\\b", "\b");
+ escaped = escaped.replace("\\f", "\f");
+ escaped = escaped.replace("\\n", "\n");
+ escaped = escaped.replace("\\r", "\r");
+ escaped = escaped.replace("\\t", "\t");
+ escaped = escaped.replace("\\v", "\v");
+ escaped = escaped.replace("\\'", "\'");
+ escaped = escaped.replace("\\\"", "\"");
+ escaped = escaped.replace("\\?", "\?");
+ escaped = escaped.replace("\\\\", "\\");
return escaped;
}
String String::c_escape() const {
- String escaped=*this;
- escaped=escaped.replace("\\","\\\\");
- escaped=escaped.replace("\a","\\a");
- escaped=escaped.replace("\b","\\b");
- escaped=escaped.replace("\f","\\f");
- escaped=escaped.replace("\n","\\n");
- escaped=escaped.replace("\r","\\r");
- escaped=escaped.replace("\t","\\t");
- escaped=escaped.replace("\v","\\v");
- escaped=escaped.replace("\'","\\'");
- escaped=escaped.replace("\?","\\?");
- escaped=escaped.replace("\"","\\\"");
+ String escaped = *this;
+ escaped = escaped.replace("\\", "\\\\");
+ escaped = escaped.replace("\a", "\\a");
+ escaped = escaped.replace("\b", "\\b");
+ escaped = escaped.replace("\f", "\\f");
+ escaped = escaped.replace("\n", "\\n");
+ escaped = escaped.replace("\r", "\\r");
+ escaped = escaped.replace("\t", "\\t");
+ escaped = escaped.replace("\v", "\\v");
+ escaped = escaped.replace("\'", "\\'");
+ escaped = escaped.replace("\?", "\\?");
+ escaped = escaped.replace("\"", "\\\"");
return escaped;
}
String String::c_escape_multiline() const {
- String escaped=*this;
- escaped=escaped.replace("\\","\\\\");
- escaped=escaped.replace("\"","\\\"");
+ String escaped = *this;
+ escaped = escaped.replace("\\", "\\\\");
+ escaped = escaped.replace("\"", "\\\"");
return escaped;
}
String String::json_escape() const {
- String escaped=*this;
- escaped=escaped.replace("\\","\\\\");
- escaped=escaped.replace("\b","\\b");
- escaped=escaped.replace("\f","\\f");
- escaped=escaped.replace("\n","\\n");
- escaped=escaped.replace("\r","\\r");
- escaped=escaped.replace("\t","\\t");
- escaped=escaped.replace("\v","\\v");
- escaped=escaped.replace("\"","\\\"");
+ String escaped = *this;
+ escaped = escaped.replace("\\", "\\\\");
+ escaped = escaped.replace("\b", "\\b");
+ escaped = escaped.replace("\f", "\\f");
+ escaped = escaped.replace("\n", "\\n");
+ escaped = escaped.replace("\r", "\\r");
+ escaped = escaped.replace("\t", "\\t");
+ escaped = escaped.replace("\v", "\\v");
+ escaped = escaped.replace("\"", "\\\"");
return escaped;
}
String String::xml_escape(bool p_escape_quotes) const {
- String str=*this;
- str=str.replace("&","&amp;");
- str=str.replace("<","&lt;");
- str=str.replace(">","&gt;");
+ String str = *this;
+ str = str.replace("&", "&amp;");
+ str = str.replace("<", "&lt;");
+ str = str.replace(">", "&gt;");
if (p_escape_quotes) {
- str=str.replace("'","&apos;");
- str=str.replace("\"","&quot;");
+ str = str.replace("'", "&apos;");
+ str = str.replace("\"", "&quot;");
}
/*
for (int i=1;i<32;i++) {
@@ -3491,84 +3354,83 @@ String String::xml_escape(bool p_escape_quotes) const {
return str;
}
-static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src,int p_src_len,CharType *p_dst) {
+static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src, int p_src_len, CharType *p_dst) {
- int len=0;
- while(p_src_len) {
+ int len = 0;
+ while (p_src_len) {
- if (*p_src=='&') {
+ if (*p_src == '&') {
- int eat=0;
+ int eat = 0;
- if (p_src_len>=4 && p_src[1]=='#') {
+ if (p_src_len >= 4 && p_src[1] == '#') {
- CharType c=0;
+ CharType c = 0;
- for(int i=2;i<p_src_len;i++) {
+ for (int i = 2; i < p_src_len; i++) {
- eat=i+1;
- CharType ct=p_src[i];
- if (ct==';') {
+ eat = i + 1;
+ CharType ct = p_src[i];
+ if (ct == ';') {
break;
- } else if (ct>='0' && ct<='9') {
- ct=ct-'0';
- } else if (ct>='a' && ct<='f') {
- ct=(ct-'a')+10;
- } else if (ct>='A' && ct<='F') {
- ct=(ct-'A')+10;
+ } else if (ct >= '0' && ct <= '9') {
+ ct = ct - '0';
+ } else if (ct >= 'a' && ct <= 'f') {
+ ct = (ct - 'a') + 10;
+ } else if (ct >= 'A' && ct <= 'F') {
+ ct = (ct - 'A') + 10;
} else {
continue;
}
- c<<=4;
- c|=ct;
+ c <<= 4;
+ c |= ct;
}
if (p_dst)
- *p_dst=c;
+ *p_dst = c;
- } else if (p_src_len>=4 && p_src[1]=='g' && p_src[2]=='t' && p_src[3]==';') {
+ } else if (p_src_len >= 4 && p_src[1] == 'g' && p_src[2] == 't' && p_src[3] == ';') {
if (p_dst)
- *p_dst='>';
- eat=4;
- } else if (p_src_len>=4 && p_src[1]=='l' && p_src[2]=='t' && p_src[3]==';') {
+ *p_dst = '>';
+ eat = 4;
+ } else if (p_src_len >= 4 && p_src[1] == 'l' && p_src[2] == 't' && p_src[3] == ';') {
if (p_dst)
- *p_dst='<';
- eat=4;
- } else if (p_src_len>=5 && p_src[1]=='a' && p_src[2]=='m' && p_src[3]=='p' && p_src[4]==';') {
+ *p_dst = '<';
+ eat = 4;
+ } else if (p_src_len >= 5 && p_src[1] == 'a' && p_src[2] == 'm' && p_src[3] == 'p' && p_src[4] == ';') {
if (p_dst)
- *p_dst='&';
- eat=5;
- } else if (p_src_len>=6 && p_src[1]=='q' && p_src[2]=='u' && p_src[3]=='o' && p_src[4]=='t' && p_src[5]==';') {
+ *p_dst = '&';
+ eat = 5;
+ } else if (p_src_len >= 6 && p_src[1] == 'q' && p_src[2] == 'u' && p_src[3] == 'o' && p_src[4] == 't' && p_src[5] == ';') {
if (p_dst)
- *p_dst='"';
- eat=6;
- } else if (p_src_len>=6 && p_src[1]=='a' && p_src[2]=='p' && p_src[3]=='o' && p_src[4]=='s' && p_src[5]==';') {
+ *p_dst = '"';
+ eat = 6;
+ } else if (p_src_len >= 6 && p_src[1] == 'a' && p_src[2] == 'p' && p_src[3] == 'o' && p_src[4] == 's' && p_src[5] == ';') {
if (p_dst)
- *p_dst='\'';
- eat=6;
+ *p_dst = '\'';
+ eat = 6;
} else {
if (p_dst)
- *p_dst=*p_src;
- eat=1;
-
+ *p_dst = *p_src;
+ eat = 1;
}
if (p_dst)
p_dst++;
len++;
- p_src+=eat;
- p_src_len-=eat;
+ p_src += eat;
+ p_src_len -= eat;
} else {
if (p_dst) {
- *p_dst=*p_src;
+ *p_dst = *p_src;
p_dst++;
}
len++;
@@ -3578,45 +3440,43 @@ static _FORCE_INLINE_ int _xml_unescape(const CharType *p_src,int p_src_len,Char
}
return len;
-
}
String String::xml_unescape() const {
-
String str;
int l = length();
- int len = _xml_unescape(c_str(),l,NULL);
- if (len==0)
+ int len = _xml_unescape(c_str(), l, NULL);
+ if (len == 0)
return String();
- str.resize(len+1);
- _xml_unescape(c_str(),l,&str[0]);
- str[len]=0;
+ str.resize(len + 1);
+ _xml_unescape(c_str(), l, &str[0]);
+ str[len] = 0;
return str;
}
String String::pad_decimals(int p_digits) const {
- String s=*this;
+ String s = *this;
int c = s.find(".");
- if (c==-1) {
- if (p_digits<=0) {
+ if (c == -1) {
+ if (p_digits <= 0) {
return s;
}
- s+=".";
- c=s.length()-1;
+ s += ".";
+ c = s.length() - 1;
} else {
- if (p_digits<=0) {
- return s.substr(0,c);
+ if (p_digits <= 0) {
+ return s.substr(0, c);
}
}
- if (s.length()-(c+1) > p_digits) {
- s=s.substr(0,c+p_digits+1);
+ if (s.length() - (c + 1) > p_digits) {
+ s = s.substr(0, c + p_digits + 1);
} else {
- while(s.length()-(c+1) < p_digits) {
- s+="0";
+ while (s.length() - (c + 1) < p_digits) {
+ s += "0";
}
}
return s;
@@ -3624,30 +3484,28 @@ String String::pad_decimals(int p_digits) const {
String String::pad_zeros(int p_digits) const {
- String s=*this;
+ String s = *this;
int end = s.find(".");
- if (end==-1) {
- end=s.length();
+ if (end == -1) {
+ end = s.length();
}
-
- if (end==0)
+ if (end == 0)
return s;
- int begin=0;
+ int begin = 0;
- while (begin<end && (s[begin]<'0' || s[begin]>'9')) {
+ while (begin < end && (s[begin] < '0' || s[begin] > '9')) {
begin++;
}
- if (begin>=end)
+ if (begin >= end)
return s;
+ while (end - begin < p_digits) {
- while(end-begin < p_digits) {
-
- s=s.insert(begin,"0");
+ s = s.insert(begin, "0");
end++;
}
@@ -3658,22 +3516,20 @@ bool String::is_valid_integer() const {
int len = length();
- if (len==0)
+ if (len == 0)
return false;
- int from=0;
- if (len!=1 && (operator[](0)=='+' || operator[](0)=='-'))
+ int from = 0;
+ if (len != 1 && (operator[](0) == '+' || operator[](0) == '-'))
from++;
- for(int i=from;i<len;i++) {
+ for (int i = from; i < len; i++) {
- if (operator[](i)<'0' || operator[](i)>'9')
+ if (operator[](i) < '0' || operator[](i) > '9')
return false; // no start with number plz
-
}
return true;
-
}
bool String::is_valid_hex_number(bool p_with_prefix) const {
@@ -3681,20 +3537,20 @@ bool String::is_valid_hex_number(bool p_with_prefix) const {
int from = 0;
int len = length();
- if (len!=1 && (operator[](0)=='+' || operator[](0)=='-'))
+ if (len != 1 && (operator[](0) == '+' || operator[](0) == '-'))
from++;
if (p_with_prefix) {
if (len < 2)
return false;
- if (operator[](from) != '0' || operator[](from+1) != 'x') {
+ if (operator[](from) != '0' || operator[](from + 1) != 'x') {
return false;
};
from += 2;
};
- for (int i=from; i<len; i++) {
+ for (int i = from; i < len; i++) {
CharType c = operator[](i);
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
@@ -3705,114 +3561,110 @@ bool String::is_valid_hex_number(bool p_with_prefix) const {
return true;
};
-
bool String::is_valid_float() const {
int len = length();
- if (len==0)
+ if (len == 0)
return false;
- int from=0;
- if (operator[](0)=='+' || operator[](0)=='-') {
+ int from = 0;
+ if (operator[](0) == '+' || operator[](0) == '-') {
from++;
}
//this was pulled out of my ass, i wonder if it's correct...
- bool exponent_found=false;
- bool period_found=false;
- bool sign_found=false;
- bool exponent_values_found=false;
- bool numbers_found=false;
+ bool exponent_found = false;
+ bool period_found = false;
+ bool sign_found = false;
+ bool exponent_values_found = false;
+ bool numbers_found = false;
- for(int i=from;i<len;i++) {
+ for (int i = from; i < len; i++) {
- if (operator[](i)>='0' && operator[](i)<='9') {
+ if (operator[](i) >= '0' && operator[](i) <= '9') {
if (exponent_found)
- exponent_values_found=true;
+ exponent_values_found = true;
else
- numbers_found=true;
- } else if (numbers_found && !exponent_found && operator[](i)=='e') {
- exponent_found=true;
- } else if (!period_found && !exponent_found && operator[](i)=='.') {
- period_found=true;
- } else if ((operator[](i)=='-' || operator[](i)=='+') && exponent_found && !exponent_values_found && !sign_found) {
- sign_found=true;
+ numbers_found = true;
+ } else if (numbers_found && !exponent_found && operator[](i) == 'e') {
+ exponent_found = true;
+ } else if (!period_found && !exponent_found && operator[](i) == '.') {
+ period_found = true;
+ } else if ((operator[](i) == '-' || operator[](i) == '+') && exponent_found && !exponent_values_found && !sign_found) {
+ sign_found = true;
} else
return false; // no start with number plz
-
}
return numbers_found;
-
}
-String String::path_to_file(const String& p_path) const {
+String String::path_to_file(const String &p_path) const {
- String src=this->replace("\\","/").get_base_dir();
- String dst=p_path.replace("\\","/").get_base_dir();
+ String src = this->replace("\\", "/").get_base_dir();
+ String dst = p_path.replace("\\", "/").get_base_dir();
String rel = src.path_to(dst);
- if (rel==dst) // failed
+ if (rel == dst) // failed
return p_path;
else
- return rel+p_path.get_file();
+ return rel + p_path.get_file();
}
-String String::path_to(const String& p_path) const {
+String String::path_to(const String &p_path) const {
- String src=this->replace("\\","/");
- String dst=p_path.replace("\\","/");
+ String src = this->replace("\\", "/");
+ String dst = p_path.replace("\\", "/");
if (!src.ends_with("/"))
- src+="/";
+ src += "/";
if (!dst.ends_with("/"))
- dst+="/";
-
+ dst += "/";
String base;
if (src.begins_with("res://") && dst.begins_with("res://")) {
- base="res:/";
- src=src.replace("res://","/");
- dst=dst.replace("res://","/");
+ base = "res:/";
+ src = src.replace("res://", "/");
+ dst = dst.replace("res://", "/");
} else if (src.begins_with("user://") && dst.begins_with("user://")) {
- base="user:/";
- src=src.replace("user://","/");
- dst=dst.replace("user://","/");
+ base = "user:/";
+ src = src.replace("user://", "/");
+ dst = dst.replace("user://", "/");
} else if (src.begins_with("/") && dst.begins_with("/")) {
//nothing
} else {
//dos style
- String src_begin=src.get_slicec('/',0);
- String dst_begin=dst.get_slicec('/',0);
+ String src_begin = src.get_slicec('/', 0);
+ String dst_begin = dst.get_slicec('/', 0);
- if (src_begin!=dst_begin)
+ if (src_begin != dst_begin)
return p_path; //impossible to do this
- base=src_begin;
- src=src.substr(src_begin.length(),src.length());
- dst=dst.substr(dst_begin.length(),dst.length());
+ base = src_begin;
+ src = src.substr(src_begin.length(), src.length());
+ dst = dst.substr(dst_begin.length(), dst.length());
}
//remove leading and trailing slash and split
- Vector<String> src_dirs=src.substr(1,src.length()-2).split("/");
- Vector<String> dst_dirs=dst.substr(1,dst.length()-2).split("/");
+ Vector<String> src_dirs = src.substr(1, src.length() - 2).split("/");
+ Vector<String> dst_dirs = dst.substr(1, dst.length() - 2).split("/");
//find common parent
- int common_parent=0;
+ int common_parent = 0;
- while(true) {
- if (src_dirs.size()==common_parent)
+ while (true) {
+ if (src_dirs.size() == common_parent)
break;
- if (dst_dirs.size()==common_parent)
+ if (dst_dirs.size() == common_parent)
break;
- if (src_dirs[common_parent]!=dst_dirs[common_parent])
+ if (src_dirs[common_parent] != dst_dirs[common_parent])
break;
common_parent++;
}
@@ -3821,34 +3673,32 @@ String String::path_to(const String& p_path) const {
String dir;
- for(int i=src_dirs.size()-1;i>common_parent;i--) {
+ for (int i = src_dirs.size() - 1; i > common_parent; i--) {
- dir+="../";
+ dir += "../";
}
- for(int i=common_parent+1;i<dst_dirs.size();i++) {
+ for (int i = common_parent + 1; i < dst_dirs.size(); i++) {
- dir+=dst_dirs[i]+"/";
+ dir += dst_dirs[i] + "/";
}
- if (dir.length()==0)
- dir="./";
+ if (dir.length() == 0)
+ dir = "./";
return dir;
}
bool String::is_valid_html_color() const {
return Color::html_is_valid(*this);
-
}
-
bool String::is_valid_ip_address() const {
if (find(":") >= 0) {
Vector<String> ip = split(":");
- for (int i=0; i<ip.size(); i++) {
+ for (int i = 0; i < ip.size(); i++) {
String n = ip[i];
if (n.empty())
@@ -3865,15 +3715,15 @@ bool String::is_valid_ip_address() const {
} else {
Vector<String> ip = split(".");
- if (ip.size()!=4)
+ if (ip.size() != 4)
return false;
- for(int i=0;i<ip.size();i++) {
+ for (int i = 0; i < ip.size(); i++) {
String n = ip[i];
if (!n.is_valid_integer())
return false;
int val = n.to_int();
- if (val<0 || val>255)
+ if (val < 0 || val > 255)
return false;
}
};
@@ -3883,7 +3733,7 @@ bool String::is_valid_ip_address() const {
bool String::is_resource_file() const {
- return begins_with("res://") && find("::")==-1;
+ return begins_with("res://") && find("::") == -1;
}
bool String::is_rel_path() const {
@@ -3896,71 +3746,70 @@ String String::get_base_dir() const {
int basepos = find("://");
String rs;
String base;
- if (basepos!=-1) {
- int end = basepos+3;
- rs = substr(end,length());
- base = substr(0,end);
+ if (basepos != -1) {
+ int end = basepos + 3;
+ rs = substr(end, length());
+ base = substr(0, end);
} else {
if (begins_with("/")) {
- rs=substr(1,length());
- base="/";
+ rs = substr(1, length());
+ base = "/";
} else {
- rs=*this;
+ rs = *this;
}
}
- int sep = MAX( rs.find_last("/"), rs.find_last("\\") );
- if (sep==-1)
+ int sep = MAX(rs.find_last("/"), rs.find_last("\\"));
+ if (sep == -1)
return base;
- return base+rs.substr(0,sep);
-
+ return base + rs.substr(0, sep);
}
String String::get_file() const {
- int sep = MAX( find_last("/"), find_last("\\") );
- if (sep==-1)
+ int sep = MAX(find_last("/"), find_last("\\"));
+ if (sep == -1)
return *this;
- return substr(sep+1,length());
+ return substr(sep + 1, length());
}
String String::get_extension() const {
int pos = find_last(".");
- if (pos<0)
+ if (pos < 0)
return *this;
- return substr( pos+1, length() );
+ return substr(pos + 1, length());
}
-String String::plus_file(const String& p_file) const {
+String String::plus_file(const String &p_file) const {
if (empty())
return p_file;
- if (operator [](length()-1)=='/' || (p_file.size()>0 && p_file.operator [](0)=='/'))
- return *this+p_file;
- return *this+"/"+p_file;
+ if (operator[](length() - 1) == '/' || (p_file.size() > 0 && p_file.operator[](0) == '/'))
+ return *this + p_file;
+ return *this + "/" + p_file;
}
String String::percent_encode() const {
CharString cs = utf8();
String encoded;
- for(int i=0;i<cs.length();i++) {
+ for (int i = 0; i < cs.length(); i++) {
uint8_t c = cs[i];
- if ( (c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9') || c=='-' || c=='_' || c=='~' || c=='.') {
+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '~' || c == '.') {
- char p[2]={(char)c,0};
- encoded+=p;
+ char p[2] = { (char)c, 0 };
+ encoded += p;
} else {
- char p[4]={'%',0,0,0};
- static const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
+ char p[4] = { '%', 0, 0, 0 };
+ static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
- p[1]=hex[c>>4];
- p[2]=hex[c&0xF];
- encoded+=p;
+ p[1] = hex[c >> 4];
+ p[2] = hex[c & 0xF];
+ encoded += p;
}
}
@@ -3971,32 +3820,32 @@ String String::percent_decode() const {
CharString pe;
CharString cs = utf8();
- for(int i=0;i<cs.length();i++) {
+ for (int i = 0; i < cs.length(); i++) {
uint8_t c = cs[i];
- if (c=='%' && i<length()-2) {
+ if (c == '%' && i < length() - 2) {
- uint8_t a = LOWERCASE(cs[i+1]);
- uint8_t b = LOWERCASE(cs[i+2]);
+ uint8_t a = LOWERCASE(cs[i + 1]);
+ uint8_t b = LOWERCASE(cs[i + 2]);
- c=0;
- if (a>='0' && a<='9')
- c=(a-'0')<<4;
- else if (a>='a' && a<='f')
- c=(a-'a'+10)<<4;
+ c = 0;
+ if (a >= '0' && a <= '9')
+ c = (a - '0') << 4;
+ else if (a >= 'a' && a <= 'f')
+ c = (a - 'a' + 10) << 4;
else
continue;
- uint8_t d=0;
+ uint8_t d = 0;
- if (b>='0' && b<='9')
- d=(b-'0');
- else if (b>='a' && b<='f')
- d=(b-'a'+10);
+ if (b >= '0' && b <= '9')
+ d = (b - '0');
+ else if (b >= 'a' && b <= 'f')
+ d = (b - 'a' + 10);
else
continue;
- c+=d;
- i+=2;
+ c += d;
+ i += 2;
}
pe.push_back(c);
}
@@ -4009,10 +3858,10 @@ String String::percent_decode() const {
String String::get_basename() const {
int pos = find_last(".");
- if (pos<0)
+ if (pos < 0)
return *this;
- return substr( 0, pos );
+ return substr(0, pos);
}
String itos(int64_t p_val) {
@@ -4031,21 +3880,23 @@ String rtoss(double p_val) {
}
// Right-pad with a character.
-String String::rpad(int min_length, const String& character) const {
+String String::rpad(int min_length, const String &character) const {
String s = *this;
int padding = min_length - s.length();
if (padding > 0) {
- for (int i = 0; i < padding; i++) s = s + character;
+ for (int i = 0; i < padding; i++)
+ s = s + character;
}
return s;
}
// Left-pad with a character.
-String String::lpad(int min_length, const String& character) const {
+String String::lpad(int min_length, const String &character) const {
String s = *this;
int padding = min_length - s.length();
if (padding > 0) {
- for (int i = 0; i < padding; i++) s = character + s;
+ for (int i = 0; i < padding; i++)
+ s = character + s;
}
return s;
@@ -4055,9 +3906,9 @@ String String::lpad(int min_length, const String& character) const {
// "fish %s pie" % "frog"
// "fish %s %d pie" % ["frog", 12]
// In case of an error, the string returned is the error description and "error" is true.
-String String::sprintf(const Array& values, bool* error) const {
+String String::sprintf(const Array &values, bool *error) const {
String formatted;
- CharType* self = (CharType*)c_str();
+ CharType *self = (CharType *)c_str();
bool in_format = false;
int value_index = 0;
int min_chars;
@@ -4098,7 +3949,10 @@ String String::sprintf(const Array& values, bool* error) const {
case 'd': base = 10; break;
case 'o': base = 8; break;
case 'x': base = 16; break;
- case 'X': base = 16; capitalize = true; break;
+ case 'X':
+ base = 16;
+ capitalize = true;
+ break;
}
// Get basic number.
String str = String::num_int64(ABS(value), base, capitalize);
@@ -4114,9 +3968,9 @@ String String::sprintf(const Array& values, bool* error) const {
// Sign.
if (show_sign && value >= 0) {
- str = str.insert(pad_with_zeroes?0:str.length()-number_len, "+");
+ str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "+");
} else if (value < 0) {
- str = str.insert(pad_with_zeroes?0:str.length()-number_len, "-");
+ str = str.insert(pad_with_zeroes ? 0 : str.length() - number_len, "-");
}
formatted += str;
@@ -4220,8 +4074,16 @@ String String::sprintf(const Array& values, bool* error) const {
show_sign = true;
break;
}
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9': {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
int n = c - '0';
if (in_decimals) {
min_decimals *= 10;
@@ -4268,7 +4130,7 @@ String String::sprintf(const Array& values, bool* error) const {
default: {
return "unsupported format character";
- }
+ }
}
} else { // Not in format string.
switch (c) {
@@ -4303,7 +4165,7 @@ String String::sprintf(const Array& values, bool* error) const {
#include "translation.h"
#ifdef TOOLS_ENABLED
-String TTR(const String& p_text) {
+String TTR(const String &p_text) {
if (TranslationServer::get_singleton()) {
return TranslationServer::get_singleton()->tool_translate(p_text);
@@ -4314,13 +4176,11 @@ String TTR(const String& p_text) {
#endif
-String RTR(const String& p_text) {
-
-
+String RTR(const String &p_text) {
if (TranslationServer::get_singleton()) {
String rtr = TranslationServer::get_singleton()->tool_translate(p_text);
- if (rtr==String() || rtr==p_text) {
+ if (rtr == String() || rtr == p_text) {
return TranslationServer::get_singleton()->translate(p_text);
} else {
return rtr;
diff --git a/core/ustring.h b/core/ustring.h
index 87289f9e16..6a69d8b147 100644
--- a/core/ustring.h
+++ b/core/ustring.h
@@ -29,67 +29,60 @@
#ifndef RSTRING_H
#define RSTRING_H
+#include "array.h"
#include "typedefs.h"
#include "vector.h"
-#include "array.h"
/**
@author red <red@killy>
*/
-
-
class CharString : public Vector<char> {
public:
-
- bool operator<(const CharString& p_right) const;
- int length() const { return size() ? size()-1 : 0; }
+ bool operator<(const CharString &p_right) const;
+ int length() const { return size() ? size() - 1 : 0; }
const char *get_data() const;
- operator const char*() {return get_data();};
+ operator const char *() { return get_data(); };
};
-
typedef wchar_t CharType;
-
struct StrRange {
const CharType *c_str;
int len;
- StrRange(const CharType *p_c_str=NULL,int p_len=0) { c_str=p_c_str; len=p_len; }
-
+ StrRange(const CharType *p_c_str = NULL, int p_len = 0) {
+ c_str = p_c_str;
+ len = p_len;
+ }
};
class String : public Vector<CharType> {
void copy_from(const char *p_cstr);
- void copy_from(const CharType* p_cstr, int p_clip_to=-1);
- void copy_from(const CharType& p_char);
- bool _base_is_subsequence_of(const String& p_string, bool case_insensitive) const;
-
+ void copy_from(const CharType *p_cstr, int p_clip_to = -1);
+ void copy_from(const CharType &p_char);
+ bool _base_is_subsequence_of(const String &p_string, bool case_insensitive) const;
public:
-
enum {
- npos=-1 ///<for "some" compatibility with std::string (npos is a huge value in std::string)
+ npos = -1 ///<for "some" compatibility with std::string (npos is a huge value in std::string)
};
-
- bool operator==(const String& p_str) const;
- bool operator!=(const String& p_str) const;
- String operator+(const String & p_str) const;
+ bool operator==(const String &p_str) const;
+ bool operator!=(const String &p_str) const;
+ String operator+(const String &p_str) const;
//String operator+(CharType p_char) const;
- String& operator+=(const String &);
- String& operator+=(CharType p_str);
- String& operator+=(const char * p_str);
- String& operator+=(const CharType * p_str);
+ String &operator+=(const String &);
+ String &operator+=(CharType p_str);
+ String &operator+=(const char *p_str);
+ String &operator+=(const CharType *p_str);
/* Compatibility Operators */
-
void operator=(const char *p_str);
void operator=(const CharType *p_str);
bool operator==(const char *p_str) const;
@@ -102,45 +95,45 @@ public:
bool operator<(String p_str) const;
bool operator<=(String p_str) const;
- signed char casecmp_to(const String& p_str) const;
- signed char nocasecmp_to(const String& p_str) const;
+ signed char casecmp_to(const String &p_str) const;
+ signed char nocasecmp_to(const String &p_str) const;
- const CharType * c_str() const;
+ const CharType *c_str() const;
/* standard size stuff */
int length() const;
/* complex helpers */
- String substr(int p_from,int p_chars) const;
- int find(String p_str,int p_from=0) const; ///< return <0 if failed
+ String substr(int p_from, int p_chars) const;
+ int find(String p_str, int p_from = 0) const; ///< return <0 if failed
int find_last(String p_str) const; ///< return <0 if failed
- int findn(String p_str,int p_from=0) const; ///< return <0 if failed, case insensitive
- int rfind(String p_str,int p_from=-1) const; ///< return <0 if failed
- int rfindn(String p_str,int p_from=-1) const; ///< return <0 if failed, case insensitive
- int findmk(const Vector<String>& p_keys,int p_from=0,int *r_key=NULL) const; ///< return <0 if failed
- bool match(const String& p_wildcard) const;
- bool matchn(const String& p_wildcard) const;
- bool begins_with(const String& p_string) const;
- bool begins_with(const char* p_string) const;
- bool ends_with(const String& p_string) const;
- bool is_subsequence_of(const String& p_string) const;
- bool is_subsequence_ofi(const String& p_string) const;
+ int findn(String p_str, int p_from = 0) const; ///< return <0 if failed, case insensitive
+ int rfind(String p_str, int p_from = -1) const; ///< return <0 if failed
+ int rfindn(String p_str, int p_from = -1) const; ///< return <0 if failed, case insensitive
+ int findmk(const Vector<String> &p_keys, int p_from = 0, int *r_key = NULL) const; ///< return <0 if failed
+ bool match(const String &p_wildcard) const;
+ bool matchn(const String &p_wildcard) const;
+ bool begins_with(const String &p_string) const;
+ bool begins_with(const char *p_string) const;
+ bool ends_with(const String &p_string) const;
+ bool is_subsequence_of(const String &p_string) const;
+ bool is_subsequence_ofi(const String &p_string) const;
Vector<String> bigrams() const;
- float similarity(const String& p_string) const;
- String format(const Variant& values,String placeholder="{_}") const;
- String replace_first(String p_key,String p_with) const;
- String replace(String p_key,String p_with) const;
- String replacen(String p_key,String p_with) const;
- String insert(int p_at_pos,String p_string) const;
+ float similarity(const String &p_string) const;
+ String format(const Variant &values, String placeholder = "{_}") const;
+ String replace_first(String p_key, String p_with) const;
+ String replace(String p_key, String p_with) const;
+ String replacen(String p_key, String p_with) const;
+ String insert(int p_at_pos, String p_string) const;
String pad_decimals(int p_digits) const;
String pad_zeros(int p_digits) const;
- String lpad(int min_length,const String& character=" ") const;
- String rpad(int min_length,const String& character=" ") const;
- String sprintf(const Array& values, bool* error) const;
- static String num(double p_num,int p_decimals=-1);
+ String lpad(int min_length, const String &character = " ") const;
+ String rpad(int min_length, const String &character = " ") const;
+ String sprintf(const Array &values, bool *error) const;
+ static String num(double p_num, int p_decimals = -1);
static String num_scientific(double p_num);
static String num_real(double p_num);
- static String num_int64(int64_t p_num,int base=10,bool capitalize_hex=false);
+ static String num_int64(int64_t p_num, int base = 10, bool capitalize_hex = false);
static String chr(CharType p_char);
static String md5(const uint8_t *p_md5);
static String hex_encode_buffer(const uint8_t *p_buffer, int p_len);
@@ -152,23 +145,23 @@ public:
int64_t hex_to_int64(bool p_with_prefix = true) const;
int64_t to_int64() const;
- static int to_int(const char* p_str, int p_len=-1);
- static double to_double(const char* p_str);
- static double to_double(const CharType* p_str, const CharType **r_end=NULL);
- static int64_t to_int(const CharType* p_str,int p_len=-1);
+ static int to_int(const char *p_str, int p_len = -1);
+ static double to_double(const char *p_str);
+ static double to_double(const CharType *p_str, const CharType **r_end = NULL);
+ static int64_t to_int(const CharType *p_str, int p_len = -1);
String capitalize() const;
- String camelcase_to_underscore(bool lowercase=true) const;
+ String camelcase_to_underscore(bool lowercase = true) const;
int get_slice_count(String p_splitter) const;
- String get_slice(String p_splitter,int p_slice) const;
- String get_slicec(CharType splitter,int p_slice) const;
+ String get_slice(String p_splitter, int p_slice) const;
+ String get_slicec(CharType splitter, int p_slice) const;
- Vector<String> split(const String &p_splitter,bool p_allow_empty=true) const;
+ Vector<String> split(const String &p_splitter, bool p_allow_empty = true) const;
Vector<String> split_spaces() const;
- Vector<float> split_floats(const String &p_splitter,bool p_allow_empty=true) const;
- Vector<float> split_floats_mk(const Vector<String> &p_splitters,bool p_allow_empty=true) const;
- Vector<int> split_ints(const String &p_splitter,bool p_allow_empty=true) const;
- Vector<int> split_ints_mk(const Vector<String> &p_splitters,bool p_allow_empty=true) const;
+ Vector<float> split_floats(const String &p_splitter, bool p_allow_empty = true) const;
+ Vector<float> split_floats_mk(const Vector<String> &p_splitters, bool p_allow_empty = true) const;
+ Vector<int> split_ints(const String &p_splitter, bool p_allow_empty = true) const;
+ Vector<int> split_ints_mk(const Vector<String> &p_splitters, bool p_allow_empty = true) const;
static CharType char_uppercase(CharType p_char);
static CharType char_lowercase(CharType p_char);
@@ -181,20 +174,20 @@ public:
String strip_escapes() const;
String get_extension() const;
String get_basename() const;
- String plus_file(const String& p_file) const;
+ String plus_file(const String &p_file) const;
CharType ord_at(int p_idx) const;
void erase(int p_pos, int p_chars);
- CharString ascii(bool p_allow_extended=false) const;
+ CharString ascii(bool p_allow_extended = false) const;
CharString utf8() const;
- bool parse_utf8(const char* p_utf8,int p_len=-1); //return true on error
- static String utf8(const char* p_utf8,int p_len=-1);
+ bool parse_utf8(const char *p_utf8, int p_len = -1); //return true on error
+ static String utf8(const char *p_utf8, int p_len = -1);
- static uint32_t hash(const CharType* p_str,int p_len); /* hash the string */
- static uint32_t hash(const CharType* p_str); /* hash the string */
- static uint32_t hash(const char* p_cstr,int p_len); /* hash the string */
- static uint32_t hash(const char* p_cstr); /* hash the string */
+ static uint32_t hash(const CharType *p_str, int p_len); /* hash the string */
+ static uint32_t hash(const CharType *p_str); /* hash the string */
+ static uint32_t hash(const char *p_cstr, int p_len); /* hash the string */
+ static uint32_t hash(const char *p_cstr); /* hash the string */
uint32_t hash() const; /* hash the string */
uint64_t hash64() const; /* hash the string */
String md5_text() const;
@@ -208,17 +201,17 @@ public:
bool is_abs_path() const;
bool is_rel_path() const;
bool is_resource_file() const;
- String path_to(const String& p_path) const;
- String path_to_file(const String& p_path) const;
+ String path_to(const String &p_path) const;
+ String path_to_file(const String &p_path) const;
String get_base_dir() const;
String get_file() const;
static String humanize_size(size_t p_size);
String simplify_path() const;
- String xml_escape(bool p_escape_quotes=false) const;
+ String xml_escape(bool p_escape_quotes = false) const;
String xml_unescape() const;
- String http_escape() const;
- String http_unescape() const;
+ String http_escape() const;
+ String http_unescape() const;
String c_escape() const;
String c_escape_multiline() const;
String c_unescape() const;
@@ -238,40 +231,36 @@ public:
/**
* The constructors must not depend on other overloads
*/
-/* String(CharType p_char);*/
+ /* String(CharType p_char);*/
inline String() {}
String(const char *p_str);
- String(const CharType *p_str,int p_clip_to_len=-1);
- String(const StrRange& p_range);
-
-
+ String(const CharType *p_str, int p_clip_to_len = -1);
+ String(const StrRange &p_range);
};
+bool operator==(const char *p_chr, const String &p_str);
-bool operator==(const char*p_chr, const String& p_str);
-
-String operator+(const char*p_chr, const String& p_str);
-String operator+(CharType p_chr, const String& p_str);
+String operator+(const char *p_chr, const String &p_str);
+String operator+(CharType p_chr, const String &p_str);
String itos(int64_t p_val);
String rtos(double p_val);
String rtoss(double p_val); //scientific version
-
struct NoCaseComparator {
- bool operator()(const String& p_a, const String& p_b) const {
+ bool operator()(const String &p_a, const String &p_b) const {
- return p_a.nocasecmp_to(p_b)<0;
+ return p_a.nocasecmp_to(p_b) < 0;
}
};
- /* end of namespace */
+/* end of namespace */
//tool translate
#ifdef TOOLS_ENABLED
-String TTR(const String&);
+String TTR(const String &);
#else
@@ -280,6 +269,6 @@ String TTR(const String&);
#endif
//tool or regular translate
-String RTR(const String&);
+String RTR(const String &);
#endif
diff --git a/core/variant.cpp b/core/variant.cpp
index 6fd0618250..771d97a4eb 100644
--- a/core/variant.cpp
+++ b/core/variant.cpp
@@ -28,25 +28,24 @@
/*************************************************************************/
#include "variant.h"
+#include "core_string_names.h"
+#include "io/marshalls.h"
#include "math_funcs.h"
-#include "resource.h"
#include "print_string.h"
-#include "scene/main/node.h"
+#include "resource.h"
#include "scene/gui/control.h"
-#include "io/marshalls.h"
-#include "core_string_names.h"
+#include "scene/main/node.h"
#include "variant_parser.h"
-
String Variant::get_type_name(Variant::Type p_type) {
- switch( p_type ) {
+ switch (p_type) {
case NIL: {
return "Nil";
} break;
- // atomic types
+ // atomic types
case BOOL: {
return "bool";
@@ -66,7 +65,7 @@ String Variant::get_type_name(Variant::Type p_type) {
return "String";
} break;
- // math types
+ // math types
case VECTOR2: {
@@ -89,7 +88,7 @@ String Variant::get_type_name(Variant::Type p_type) {
return "Plane";
} break;
- /*
+ /*
case QUAT: {
@@ -114,7 +113,7 @@ String Variant::get_type_name(Variant::Type p_type) {
} break;
- // misc types
+ // misc types
case COLOR: {
return "Color";
@@ -154,7 +153,7 @@ String Variant::get_type_name(Variant::Type p_type) {
} break;
- // arrays
+ // arrays
case POOL_BYTE_ARRAY: {
return "PoolByteArray";
@@ -190,114 +189,110 @@ String Variant::get_type_name(Variant::Type p_type) {
} break;
default: {}
- }
+ }
return "";
}
+bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) {
-bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) {
-
- if (p_type_from==p_type_to)
+ if (p_type_from == p_type_to)
return true;
- if (p_type_to==NIL && p_type_from!=NIL) //nil can convert to anything
+ if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything
return true;
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
};
- const Type *valid_types=NULL;
- const Type *invalid_types=NULL;
+ const Type *valid_types = NULL;
+ const Type *invalid_types = NULL;
- switch(p_type_to) {
+ switch (p_type_to) {
case BOOL: {
- static const Type valid[]={
+ static const Type valid[] = {
INT,
REAL,
STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case INT: {
- static const Type valid[]={
+ static const Type valid[] = {
BOOL,
REAL,
STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case REAL: {
- static const Type valid[]={
+ static const Type valid[] = {
BOOL,
INT,
STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case STRING: {
-
- static const Type invalid[]={
+ static const Type invalid[] = {
OBJECT,
IMAGE,
NIL
};
- invalid_types=invalid;
+ invalid_types = invalid;
} break;
case TRANSFORM2D: {
-
- static const Type valid[]={
+ static const Type valid[] = {
TRANSFORM,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case QUAT: {
- static const Type valid[]={
+ static const Type valid[] = {
BASIS,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case BASIS: {
- static const Type valid[]={
+ static const Type valid[] = {
QUAT,
NIL
};
- valid_types=valid;
-
+ valid_types = valid;
} break;
case TRANSFORM: {
- static const Type valid[]={
+ static const Type valid[] = {
TRANSFORM2D,
QUAT,
BASIS,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
@@ -315,34 +310,33 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) {
case _RID: {
- static const Type valid[]={
+ static const Type valid[] = {
OBJECT,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case OBJECT: {
- static const Type valid[]={
+ static const Type valid[] = {
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case NODE_PATH: {
- static const Type valid[]={
+ static const Type valid[] = {
STRING,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case ARRAY: {
-
- static const Type valid[]={
+ static const Type valid[] = {
POOL_BYTE_ARRAY,
POOL_INT_ARRAY,
POOL_STRING_ARRAY,
@@ -353,92 +347,90 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) {
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
- // arrays
+ // arrays
case POOL_BYTE_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_INT_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_REAL_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_STRING_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_VECTOR2_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_VECTOR3_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_COLOR_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
default: {}
}
-
if (valid_types) {
- int i=0;
- while(valid_types[i]!=NIL) {
+ int i = 0;
+ while (valid_types[i] != NIL) {
- if (p_type_from==valid_types[i])
+ if (p_type_from == valid_types[i])
return true;
i++;
}
} else if (invalid_types) {
+ int i = 0;
+ while (invalid_types[i] != NIL) {
- int i=0;
- while(invalid_types[i]!=NIL) {
-
- if (p_type_from==invalid_types[i])
+ if (p_type_from == invalid_types[i])
return false;
i++;
}
@@ -447,109 +439,105 @@ bool Variant::can_convert(Variant::Type p_type_from,Variant::Type p_type_to) {
}
return false;
-
}
-bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_to) {
+bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type_to) {
- if (p_type_from==p_type_to)
+ if (p_type_from == p_type_to)
return true;
- if (p_type_to==NIL && p_type_from!=NIL) //nil can convert to anything
+ if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything
return true;
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
};
- const Type *valid_types=NULL;
+ const Type *valid_types = NULL;
- switch(p_type_to) {
+ switch (p_type_to) {
case BOOL: {
- static const Type valid[]={
+ static const Type valid[] = {
INT,
REAL,
//STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case INT: {
- static const Type valid[]={
+ static const Type valid[] = {
BOOL,
REAL,
//STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case REAL: {
- static const Type valid[]={
+ static const Type valid[] = {
BOOL,
INT,
//STRING,
NIL,
};
- valid_types=valid;
+ valid_types = valid;
} break;
case STRING: {
-
- static const Type valid[]={
+ static const Type valid[] = {
NODE_PATH,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case TRANSFORM2D: {
-
- static const Type valid[]={
+ static const Type valid[] = {
TRANSFORM,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case QUAT: {
- static const Type valid[]={
+ static const Type valid[] = {
BASIS,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case BASIS: {
- static const Type valid[]={
+ static const Type valid[] = {
QUAT,
NIL
};
- valid_types=valid;
-
+ valid_types = valid;
} break;
case TRANSFORM: {
- static const Type valid[]={
+ static const Type valid[] = {
TRANSFORM2D,
QUAT,
BASIS,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
@@ -567,34 +555,33 @@ bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_
case _RID: {
- static const Type valid[]={
+ static const Type valid[] = {
OBJECT,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case OBJECT: {
- static const Type valid[]={
+ static const Type valid[] = {
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case NODE_PATH: {
- static const Type valid[]={
+ static const Type valid[] = {
STRING,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case ARRAY: {
-
- static const Type valid[]={
+ static const Type valid[] = {
POOL_BYTE_ARRAY,
POOL_INT_ARRAY,
POOL_STRING_ARRAY,
@@ -605,124 +592,120 @@ bool Variant::can_convert_strict(Variant::Type p_type_from,Variant::Type p_type_
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
- // arrays
+ // arrays
case POOL_BYTE_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_INT_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_REAL_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_STRING_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_VECTOR2_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_VECTOR3_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
case POOL_COLOR_ARRAY: {
- static const Type valid[]={
+ static const Type valid[] = {
ARRAY,
NIL
};
- valid_types=valid;
+ valid_types = valid;
} break;
default: {}
}
-
if (valid_types) {
- int i=0;
- while(valid_types[i]!=NIL) {
+ int i = 0;
+ while (valid_types[i] != NIL) {
- if (p_type_from==valid_types[i])
+ if (p_type_from == valid_types[i])
return true;
i++;
}
}
return false;
-
}
-bool Variant::operator==(const Variant& p_variant) const {
+bool Variant::operator==(const Variant &p_variant) const {
- if (type!=p_variant.type) //evaluation of operator== needs to be more strict
+ if (type != p_variant.type) //evaluation of operator== needs to be more strict
return false;
bool v;
Variant r;
- evaluate(OP_EQUAL,*this,p_variant,r,v);
+ evaluate(OP_EQUAL, *this, p_variant, r, v);
return r;
-
}
-bool Variant::operator!=(const Variant& p_variant) const {
+bool Variant::operator!=(const Variant &p_variant) const {
- if (type!=p_variant.type) //evaluation of operator== needs to be more strict
+ if (type != p_variant.type) //evaluation of operator== needs to be more strict
return true;
bool v;
Variant r;
- evaluate(OP_NOT_EQUAL,*this,p_variant,r,v);
+ evaluate(OP_NOT_EQUAL, *this, p_variant, r, v);
return r;
-
}
-bool Variant::operator<(const Variant& p_variant) const {
- if (type!=p_variant.type) //if types differ, then order by type first
- return type<p_variant.type;
+bool Variant::operator<(const Variant &p_variant) const {
+ if (type != p_variant.type) //if types differ, then order by type first
+ return type < p_variant.type;
bool v;
Variant r;
- evaluate(OP_LESS,*this,p_variant,r,v);
+ evaluate(OP_LESS, *this, p_variant, r, v);
return r;
}
bool Variant::is_zero() const {
- switch( type ) {
+ switch (type) {
case NIL: {
return true;
@@ -731,21 +714,21 @@ bool Variant::is_zero() const {
// atomic types
case BOOL: {
- return _data._bool==false;
+ return _data._bool == false;
} break;
case INT: {
- return _data._int==0;
+ return _data._int == 0;
} break;
case REAL: {
- return _data._real==0;
+ return _data._real == 0;
} break;
case STRING: {
- return *reinterpret_cast<const String*>(_data._mem)==String();
+ return *reinterpret_cast<const String *>(_data._mem) == String();
} break;
@@ -753,46 +736,46 @@ bool Variant::is_zero() const {
case VECTOR2: {
- return *reinterpret_cast<const Vector2*>(_data._mem)==Vector2();
+ return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2();
} break;
case RECT2: {
- return *reinterpret_cast<const Rect2*>(_data._mem)==Rect2();
+ return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2();
} break;
case TRANSFORM2D: {
- return *_data._transform2d==Transform2D();
+ return *_data._transform2d == Transform2D();
} break;
case VECTOR3: {
- return *reinterpret_cast<const Vector3*>(_data._mem)==Vector3();
+ return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3();
} break;
case PLANE: {
- return *reinterpret_cast<const Plane*>(_data._mem)==Plane();
+ return *reinterpret_cast<const Plane *>(_data._mem) == Plane();
} break;
-/*
+ /*
case QUAT: {
} break;*/
case RECT3: {
- return *_data._rect3==Rect3();
+ return *_data._rect3 == Rect3();
} break;
case QUAT: {
- return *reinterpret_cast<const Quat*>(_data._mem)==Quat();
+ return *reinterpret_cast<const Quat *>(_data._mem) == Quat();
} break;
case BASIS: {
- return *_data._basis==Basis();
+ return *_data._basis == Basis();
} break;
case TRANSFORM: {
@@ -804,7 +787,7 @@ bool Variant::is_zero() const {
// misc types
case COLOR: {
- return *reinterpret_cast<const Color*>(_data._mem)==Color();
+ return *reinterpret_cast<const Color *>(_data._mem) == Color();
} break;
case IMAGE: {
@@ -814,67 +797,67 @@ bool Variant::is_zero() const {
} break;
case _RID: {
- return *reinterpret_cast<const RID*>(_data._mem)==RID();
+ return *reinterpret_cast<const RID *>(_data._mem) == RID();
} break;
case OBJECT: {
- return _get_obj().obj==NULL;
+ return _get_obj().obj == NULL;
} break;
case NODE_PATH: {
- return reinterpret_cast<const NodePath*>(_data._mem)->is_empty();
+ return reinterpret_cast<const NodePath *>(_data._mem)->is_empty();
} break;
case INPUT_EVENT: {
- return _data._input_event->type==InputEvent::NONE;
+ return _data._input_event->type == InputEvent::NONE;
} break;
case DICTIONARY: {
- return reinterpret_cast<const Dictionary*>(_data._mem)->empty();
+ return reinterpret_cast<const Dictionary *>(_data._mem)->empty();
} break;
case ARRAY: {
- return reinterpret_cast<const Array*>(_data._mem)->empty();
+ return reinterpret_cast<const Array *>(_data._mem)->empty();
} break;
// arrays
case POOL_BYTE_ARRAY: {
- return reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem)->size() == 0;
} break;
case POOL_INT_ARRAY: {
- return reinterpret_cast<const PoolVector<int>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<int> *>(_data._mem)->size() == 0;
} break;
case POOL_REAL_ARRAY: {
- return reinterpret_cast<const PoolVector<real_t>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<real_t> *>(_data._mem)->size() == 0;
} break;
case POOL_STRING_ARRAY: {
- return reinterpret_cast<const PoolVector<String>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<String> *>(_data._mem)->size() == 0;
} break;
case POOL_VECTOR2_ARRAY: {
- return reinterpret_cast<const PoolVector<Vector2>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<Vector2> *>(_data._mem)->size() == 0;
} break;
case POOL_VECTOR3_ARRAY: {
- return reinterpret_cast<const PoolVector<Vector3>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<Vector3> *>(_data._mem)->size() == 0;
} break;
case POOL_COLOR_ARRAY: {
- return reinterpret_cast<const PoolVector<Color>*>(_data._mem)->size()==0;
+ return reinterpret_cast<const PoolVector<Color> *>(_data._mem)->size() == 0;
} break;
default: {}
@@ -883,10 +866,9 @@ bool Variant::is_zero() const {
return false;
}
-
bool Variant::is_one() const {
- switch( type ) {
+ switch (type) {
case NIL: {
return true;
@@ -895,41 +877,41 @@ bool Variant::is_one() const {
// atomic types
case BOOL: {
- return _data._bool==true;
+ return _data._bool == true;
} break;
case INT: {
- return _data._int==1;
+ return _data._int == 1;
} break;
case REAL: {
- return _data._real==1;
+ return _data._real == 1;
} break;
case VECTOR2: {
- return *reinterpret_cast<const Vector2*>(_data._mem)==Vector2(1,1);
+ return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(1, 1);
} break;
case RECT2: {
- return *reinterpret_cast<const Rect2*>(_data._mem)==Rect2(1,1,1,1);
+ return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(1, 1, 1, 1);
} break;
case VECTOR3: {
- return *reinterpret_cast<const Vector3*>(_data._mem)==Vector3(1,1,1);
+ return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(1, 1, 1);
} break;
case PLANE: {
- return *reinterpret_cast<const Plane*>(_data._mem)==Plane(1,1,1,1);
+ return *reinterpret_cast<const Plane *>(_data._mem) == Plane(1, 1, 1, 1);
} break;
case COLOR: {
- return *reinterpret_cast<const Color*>(_data._mem)==Color(1,1,1,1);
+ return *reinterpret_cast<const Color *>(_data._mem) == Color(1, 1, 1, 1);
} break;
@@ -939,18 +921,16 @@ bool Variant::is_one() const {
return false;
}
-
-void Variant::reference(const Variant& p_variant) {
-
+void Variant::reference(const Variant &p_variant) {
if (this == &p_variant)
return;
clear();
- type=p_variant.type;
+ type = p_variant.type;
- switch( p_variant.type ) {
+ switch (p_variant.type) {
case NIL: {
// none
@@ -959,21 +939,21 @@ void Variant::reference(const Variant& p_variant) {
// atomic types
case BOOL: {
- _data._bool=p_variant._data._bool;
+ _data._bool = p_variant._data._bool;
} break;
case INT: {
- _data._int=p_variant._data._int;
+ _data._int = p_variant._data._int;
} break;
case REAL: {
- _data._real=p_variant._data._real;
+ _data._real = p_variant._data._real;
} break;
case STRING: {
- memnew_placement( _data._mem, String( *reinterpret_cast<const String*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, String(*reinterpret_cast<const String *>(p_variant._data._mem)));
} break;
@@ -981,158 +961,156 @@ void Variant::reference(const Variant& p_variant) {
case VECTOR2: {
- memnew_placement( _data._mem, Vector2( *reinterpret_cast<const Vector2*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Vector2(*reinterpret_cast<const Vector2 *>(p_variant._data._mem)));
} break;
case RECT2: {
- memnew_placement( _data._mem, Rect2( *reinterpret_cast<const Rect2*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Rect2(*reinterpret_cast<const Rect2 *>(p_variant._data._mem)));
} break;
case TRANSFORM2D: {
- _data._transform2d = memnew( Transform2D( *p_variant._data._transform2d ) );
+ _data._transform2d = memnew(Transform2D(*p_variant._data._transform2d));
} break;
case VECTOR3: {
- memnew_placement( _data._mem, Vector3( *reinterpret_cast<const Vector3*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Vector3(*reinterpret_cast<const Vector3 *>(p_variant._data._mem)));
} break;
case PLANE: {
- memnew_placement( _data._mem, Plane( *reinterpret_cast<const Plane*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Plane(*reinterpret_cast<const Plane *>(p_variant._data._mem)));
} break;
-/*
+ /*
case QUAT: {
} break;*/
case RECT3: {
- _data._rect3 = memnew( Rect3( *p_variant._data._rect3 ) );
+ _data._rect3 = memnew(Rect3(*p_variant._data._rect3));
} break;
case QUAT: {
- memnew_placement( _data._mem, Quat( *reinterpret_cast<const Quat*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Quat(*reinterpret_cast<const Quat *>(p_variant._data._mem)));
} break;
case BASIS: {
- _data._basis = memnew( Basis( *p_variant._data._basis ) );
+ _data._basis = memnew(Basis(*p_variant._data._basis));
} break;
case TRANSFORM: {
- _data._transform = memnew( Transform( *p_variant._data._transform ) );
+ _data._transform = memnew(Transform(*p_variant._data._transform));
} break;
// misc types
case COLOR: {
- memnew_placement( _data._mem, Color( *reinterpret_cast<const Color*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Color(*reinterpret_cast<const Color *>(p_variant._data._mem)));
} break;
case IMAGE: {
- _data._image = memnew( Image( *p_variant._data._image ) );
+ _data._image = memnew(Image(*p_variant._data._image));
} break;
case _RID: {
- memnew_placement( _data._mem, RID( *reinterpret_cast<const RID*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, RID(*reinterpret_cast<const RID *>(p_variant._data._mem)));
} break;
case OBJECT: {
- memnew_placement( _data._mem, ObjData( p_variant._get_obj() ) );
+ memnew_placement(_data._mem, ObjData(p_variant._get_obj()));
} break;
case NODE_PATH: {
- memnew_placement( _data._mem, NodePath( *reinterpret_cast<const NodePath*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, NodePath(*reinterpret_cast<const NodePath *>(p_variant._data._mem)));
} break;
case INPUT_EVENT: {
- _data._input_event= memnew( InputEvent( *p_variant._data._input_event ) );
+ _data._input_event = memnew(InputEvent(*p_variant._data._input_event));
} break;
case DICTIONARY: {
- memnew_placement( _data._mem, Dictionary( *reinterpret_cast<const Dictionary*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Dictionary(*reinterpret_cast<const Dictionary *>(p_variant._data._mem)));
} break;
case ARRAY: {
- memnew_placement( _data._mem, Array ( *reinterpret_cast<const Array*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, Array(*reinterpret_cast<const Array *>(p_variant._data._mem)));
} break;
// arrays
case POOL_BYTE_ARRAY: {
- memnew_placement( _data._mem, PoolVector<uint8_t> ( *reinterpret_cast<const PoolVector<uint8_t>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<uint8_t>(*reinterpret_cast<const PoolVector<uint8_t> *>(p_variant._data._mem)));
} break;
case POOL_INT_ARRAY: {
- memnew_placement( _data._mem, PoolVector<int> ( *reinterpret_cast<const PoolVector<int>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<int>(*reinterpret_cast<const PoolVector<int> *>(p_variant._data._mem)));
} break;
case POOL_REAL_ARRAY: {
- memnew_placement( _data._mem, PoolVector<real_t> ( *reinterpret_cast<const PoolVector<real_t>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<real_t>(*reinterpret_cast<const PoolVector<real_t> *>(p_variant._data._mem)));
} break;
case POOL_STRING_ARRAY: {
- memnew_placement( _data._mem, PoolVector<String> ( *reinterpret_cast<const PoolVector<String>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<String>(*reinterpret_cast<const PoolVector<String> *>(p_variant._data._mem)));
} break;
case POOL_VECTOR2_ARRAY: {
- memnew_placement( _data._mem, PoolVector<Vector2> ( *reinterpret_cast<const PoolVector<Vector2>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<Vector2>(*reinterpret_cast<const PoolVector<Vector2> *>(p_variant._data._mem)));
} break;
case POOL_VECTOR3_ARRAY: {
- memnew_placement( _data._mem, PoolVector<Vector3> ( *reinterpret_cast<const PoolVector<Vector3>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<Vector3>(*reinterpret_cast<const PoolVector<Vector3> *>(p_variant._data._mem)));
} break;
case POOL_COLOR_ARRAY: {
- memnew_placement( _data._mem, PoolVector<Color> ( *reinterpret_cast<const PoolVector<Color>*>(p_variant._data._mem) ) );
+ memnew_placement(_data._mem, PoolVector<Color>(*reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem)));
} break;
default: {}
}
-
-
}
void Variant::zero() {
- switch(type) {
+ switch (type) {
case NIL: break;
case BOOL: this->_data._bool = false; break;
case INT: this->_data._int = 0; break;
case REAL: this->_data._real = 0; break;
- case VECTOR2: *reinterpret_cast<Vector2*>(this->_data._mem) = Vector2(); break;
- case RECT2: *reinterpret_cast<Rect2*>(this->_data._mem) = Rect2(); break;
- case VECTOR3: *reinterpret_cast<Vector3*>(this->_data._mem) = Vector3(); break;
- case PLANE: *reinterpret_cast<Plane*>(this->_data._mem) = Plane(); break;
- case QUAT: *reinterpret_cast<Quat*>(this->_data._mem) = Quat(); break;
- case COLOR: *reinterpret_cast<Color*>(this->_data._mem) = Color(); break;
+ case VECTOR2: *reinterpret_cast<Vector2 *>(this->_data._mem) = Vector2(); break;
+ case RECT2: *reinterpret_cast<Rect2 *>(this->_data._mem) = Rect2(); break;
+ case VECTOR3: *reinterpret_cast<Vector3 *>(this->_data._mem) = Vector3(); break;
+ case PLANE: *reinterpret_cast<Plane *>(this->_data._mem) = Plane(); break;
+ case QUAT: *reinterpret_cast<Quat *>(this->_data._mem) = Quat(); break;
+ case COLOR: *reinterpret_cast<Color *>(this->_data._mem) = Color(); break;
default: this->clear(); break;
}
}
void Variant::clear() {
- switch(type) {
+ switch (type) {
case STRING: {
- reinterpret_cast<String*>(_data._mem)->~String();
+ reinterpret_cast<String *>(_data._mem)->~String();
} break;
- /*
+ /*
// no point, they don't allocate memory
VECTOR3,
PLANE,
@@ -1143,107 +1121,105 @@ void Variant::clear() {
*/
case TRANSFORM2D: {
- memdelete( _data._transform2d );
+ memdelete(_data._transform2d);
} break;
case RECT3: {
- memdelete( _data._rect3 );
+ memdelete(_data._rect3);
} break;
case BASIS: {
- memdelete( _data._basis );
+ memdelete(_data._basis);
} break;
case TRANSFORM: {
- memdelete( _data._transform );
+ memdelete(_data._transform);
} break;
// misc types
case IMAGE: {
- memdelete( _data._image );
+ memdelete(_data._image);
} break;
case NODE_PATH: {
- reinterpret_cast<NodePath*>(_data._mem)->~NodePath();
+ reinterpret_cast<NodePath *>(_data._mem)->~NodePath();
} break;
case OBJECT: {
- _get_obj().obj=NULL;
+ _get_obj().obj = NULL;
_get_obj().ref.unref();
} break;
case _RID: {
// not much need probably
- reinterpret_cast<RID*>(_data._mem)->~RID();
+ reinterpret_cast<RID *>(_data._mem)->~RID();
} break;
case DICTIONARY: {
- reinterpret_cast<Dictionary*>(_data._mem)->~Dictionary();
+ reinterpret_cast<Dictionary *>(_data._mem)->~Dictionary();
} break;
case ARRAY: {
- reinterpret_cast<Array*>(_data._mem)->~Array();
+ reinterpret_cast<Array *>(_data._mem)->~Array();
} break;
case INPUT_EVENT: {
- memdelete( _data._input_event );
+ memdelete(_data._input_event);
} break;
// arrays
case POOL_BYTE_ARRAY: {
- reinterpret_cast< PoolVector<uint8_t>* >(_data._mem)->~PoolVector<uint8_t>();
+ reinterpret_cast<PoolVector<uint8_t> *>(_data._mem)->~PoolVector<uint8_t>();
} break;
case POOL_INT_ARRAY: {
- reinterpret_cast< PoolVector<int>* >(_data._mem)->~PoolVector<int>();
+ reinterpret_cast<PoolVector<int> *>(_data._mem)->~PoolVector<int>();
} break;
case POOL_REAL_ARRAY: {
- reinterpret_cast< PoolVector<real_t>* >(_data._mem)->~PoolVector<real_t>();
+ reinterpret_cast<PoolVector<real_t> *>(_data._mem)->~PoolVector<real_t>();
} break;
case POOL_STRING_ARRAY: {
- reinterpret_cast< PoolVector<String>* >(_data._mem)->~PoolVector<String>();
+ reinterpret_cast<PoolVector<String> *>(_data._mem)->~PoolVector<String>();
} break;
case POOL_VECTOR2_ARRAY: {
- reinterpret_cast< PoolVector<Vector2>* >(_data._mem)->~PoolVector<Vector2>();
+ reinterpret_cast<PoolVector<Vector2> *>(_data._mem)->~PoolVector<Vector2>();
} break;
case POOL_VECTOR3_ARRAY: {
- reinterpret_cast< PoolVector<Vector3>* >(_data._mem)->~PoolVector<Vector3>();
+ reinterpret_cast<PoolVector<Vector3> *>(_data._mem)->~PoolVector<Vector3>();
} break;
case POOL_COLOR_ARRAY: {
- reinterpret_cast< PoolVector<Color>* >(_data._mem)->~PoolVector<Color>();
+ reinterpret_cast<PoolVector<Color> *>(_data._mem)->~PoolVector<Color>();
} break;
default: {} /* not needed */
}
- type=NIL;
-
+ type = NIL;
}
-
Variant::operator signed int() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1260,7 +1236,7 @@ Variant::operator signed int() const {
}
Variant::operator unsigned int() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1278,7 +1254,7 @@ Variant::operator unsigned int() const {
Variant::operator int64_t() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1316,7 +1292,7 @@ Variant::operator long unsigned int() const {
Variant::operator uint64_t() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1335,7 +1311,7 @@ Variant::operator uint64_t() const {
#ifdef NEED_LONG_INT
Variant::operator signed long() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1353,7 +1329,7 @@ Variant::operator signed long() const {
Variant::operator unsigned long() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1370,10 +1346,9 @@ Variant::operator unsigned long() const {
};
#endif
-
Variant::operator signed short() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1390,7 +1365,7 @@ Variant::operator signed short() const {
}
Variant::operator unsigned short() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1407,7 +1382,7 @@ Variant::operator unsigned short() const {
}
Variant::operator signed char() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1424,7 +1399,7 @@ Variant::operator signed char() const {
}
Variant::operator unsigned char() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
@@ -1445,10 +1420,9 @@ Variant::operator CharType() const {
return operator unsigned int();
}
-
Variant::operator float() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1.0 : 0.0;
@@ -1465,7 +1439,7 @@ Variant::operator float() const {
}
Variant::operator double() const {
- switch( type ) {
+ switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1.0 : 0.0;
@@ -1483,8 +1457,8 @@ Variant::operator double() const {
Variant::operator StringName() const {
- if (type==NODE_PATH) {
- return reinterpret_cast<const NodePath*>(_data._mem)->get_sname();
+ if (type == NODE_PATH) {
+ return reinterpret_cast<const NodePath *>(_data._mem)->get_sname();
}
return StringName(operator String());
}
@@ -1494,7 +1468,7 @@ struct _VariantStrPair {
String key;
String value;
- bool operator<(const _VariantStrPair& p) const {
+ bool operator<(const _VariantStrPair &p) const {
return key < p.key;
}
@@ -1502,57 +1476,58 @@ struct _VariantStrPair {
Variant::operator String() const {
- switch( type ) {
+ switch (type) {
case NIL: return "Null";
case BOOL: return _data._bool ? "True" : "False";
case INT: return itos(_data._int);
case REAL: return rtos(_data._real);
- case STRING: return *reinterpret_cast<const String*>(_data._mem);
- case VECTOR2: return "("+operator Vector2()+")";
- case RECT2: return "("+operator Rect2()+")";
+ case STRING: return *reinterpret_cast<const String *>(_data._mem);
+ case VECTOR2: return "(" + operator Vector2() + ")";
+ case RECT2: return "(" + operator Rect2() + ")";
case TRANSFORM2D: {
Transform2D mat32 = operator Transform2D();
- return "("+Variant(mat32.elements[0]).operator String()+", "+Variant(mat32.elements[1]).operator String()+", "+Variant(mat32.elements[2]).operator String()+")";
+ return "(" + Variant(mat32.elements[0]).operator String() + ", " + Variant(mat32.elements[1]).operator String() + ", " + Variant(mat32.elements[2]).operator String() + ")";
} break;
- case VECTOR3: return "("+operator Vector3()+")";
- case PLANE: return operator Plane();
+ case VECTOR3: return "(" + operator Vector3() + ")";
+ case PLANE:
+ return operator Plane();
//case QUAT:
case RECT3: return operator Rect3();
- case QUAT: return "("+operator Quat()+")";
+ case QUAT: return "(" + operator Quat() + ")";
case BASIS: {
Basis mat3 = operator Basis();
String mtx("(");
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (i!=0)
- mtx+=", ";
+ if (i != 0)
+ mtx += ", ";
- mtx+="(";
+ mtx += "(";
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- if (j!=0)
- mtx+=", ";
+ if (j != 0)
+ mtx += ", ";
- mtx+=Variant( mat3.elements[i][j] ).operator String();
+ mtx += Variant(mat3.elements[i][j]).operator String();
}
- mtx+=")";
+ mtx += ")";
}
- return mtx+")";
+ return mtx + ")";
} break;
case TRANSFORM: return operator Transform();
case NODE_PATH: return operator NodePath();
case INPUT_EVENT: return operator InputEvent();
- case COLOR: return String::num( operator Color().r)+","+String::num( operator Color().g)+","+String::num( operator Color().b)+","+String::num( operator Color().a) ;
+ case COLOR: return String::num(operator Color().r) + "," + String::num(operator Color().g) + "," + String::num(operator Color().b) + "," + String::num(operator Color().a);
case DICTIONARY: {
- const Dictionary &d =*reinterpret_cast<const Dictionary*>(_data._mem);
+ const Dictionary &d = *reinterpret_cast<const Dictionary *>(_data._mem);
//const String *K=NULL;
String str;
List<Variant> keys;
@@ -1560,20 +1535,20 @@ Variant::operator String() const {
Vector<_VariantStrPair> pairs;
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
_VariantStrPair sp;
- sp.key=String(E->get());
- sp.value=d[E->get()];
+ sp.key = String(E->get());
+ sp.value = d[E->get()];
pairs.push_back(sp);
}
pairs.sort();
- for(int i=0;i<pairs.size();i++) {
- if (i>0)
- str+=", ";
- str+="("+pairs[i].key+":"+pairs[i].value+")";
+ for (int i = 0; i < pairs.size(); i++) {
+ if (i > 0)
+ str += ", ";
+ str += "(" + pairs[i].key + ":" + pairs[i].value + ")";
}
return str;
@@ -1582,11 +1557,11 @@ Variant::operator String() const {
PoolVector<Vector2> vec = operator PoolVector<Vector2>();
String str("[");
- for(int i=0;i<vec.size();i++) {
+ for (int i = 0; i < vec.size(); i++) {
- if (i>0)
- str+=", ";
- str=str+Variant( vec[i] );
+ if (i > 0)
+ str += ", ";
+ str = str + Variant(vec[i]);
}
str += "]";
return str;
@@ -1595,11 +1570,11 @@ Variant::operator String() const {
PoolVector<Vector3> vec = operator PoolVector<Vector3>();
String str("[");
- for(int i=0;i<vec.size();i++) {
+ for (int i = 0; i < vec.size(); i++) {
- if (i>0)
- str+=", ";
- str=str+Variant( vec[i] );
+ if (i > 0)
+ str += ", ";
+ str = str + Variant(vec[i]);
}
str += "]";
return str;
@@ -1608,11 +1583,11 @@ Variant::operator String() const {
PoolVector<String> vec = operator PoolVector<String>();
String str("[");
- for(int i=0;i<vec.size();i++) {
+ for (int i = 0; i < vec.size(); i++) {
- if (i>0)
- str+=", ";
- str=str+vec[i];
+ if (i > 0)
+ str += ", ";
+ str = str + vec[i];
}
str += "]";
return str;
@@ -1621,11 +1596,11 @@ Variant::operator String() const {
PoolVector<int> vec = operator PoolVector<int>();
String str("[");
- for(int i=0;i<vec.size();i++) {
+ for (int i = 0; i < vec.size(); i++) {
- if (i>0)
- str+=", ";
- str=str+itos(vec[i]);
+ if (i > 0)
+ str += ", ";
+ str = str + itos(vec[i]);
}
str += "]";
return str;
@@ -1634,11 +1609,11 @@ Variant::operator String() const {
PoolVector<real_t> vec = operator PoolVector<real_t>();
String str("[");
- for(int i=0;i<vec.size();i++) {
+ for (int i = 0; i < vec.size(); i++) {
- if (i>0)
- str+=", ";
- str=str+rtos(vec[i]);
+ if (i > 0)
+ str += ", ";
+ str = str + rtos(vec[i]);
}
str += "]";
return str;
@@ -1647,9 +1622,9 @@ Variant::operator String() const {
Array arr = operator Array();
String str("[");
- for (int i=0; i<arr.size(); i++) {
+ for (int i = 0; i < arr.size(); i++) {
if (i)
- str+=", ";
+ str += ", ";
str += String(arr[i]);
};
str += "]";
@@ -1659,21 +1634,21 @@ Variant::operator String() const {
case OBJECT: {
if (_get_obj().obj) {
- #ifdef DEBUG_ENABLED
- if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
- //only if debugging!
- if (!ObjectDB::instance_validate(_get_obj().obj)) {
- return "[Deleted Object]";
- };
+#ifdef DEBUG_ENABLED
+ if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
+ //only if debugging!
+ if (!ObjectDB::instance_validate(_get_obj().obj)) {
+ return "[Deleted Object]";
};
- #endif
- return "["+_get_obj().obj->get_class()+":"+itos(_get_obj().obj->get_instance_ID())+"]";
+ };
+#endif
+ return "[" + _get_obj().obj->get_class() + ":" + itos(_get_obj().obj->get_instance_ID()) + "]";
} else
return "[Object:null]";
} break;
default: {
- return "["+get_type_name(type)+"]";
+ return "[" + get_type_name(type) + "]";
}
}
@@ -1682,42 +1657,38 @@ Variant::operator String() const {
Variant::operator Vector2() const {
- if (type==VECTOR2)
- return *reinterpret_cast<const Vector2*>(_data._mem);
- else if (type==VECTOR3)
- return Vector2(reinterpret_cast<const Vector3*>(_data._mem)->x,reinterpret_cast<const Vector3*>(_data._mem)->y);
+ if (type == VECTOR2)
+ return *reinterpret_cast<const Vector2 *>(_data._mem);
+ else if (type == VECTOR3)
+ return Vector2(reinterpret_cast<const Vector3 *>(_data._mem)->x, reinterpret_cast<const Vector3 *>(_data._mem)->y);
else
return Vector2();
-
}
Variant::operator Rect2() const {
- if (type==RECT2)
- return *reinterpret_cast<const Rect2*>(_data._mem);
+ if (type == RECT2)
+ return *reinterpret_cast<const Rect2 *>(_data._mem);
else
return Rect2();
-
}
Variant::operator Vector3() const {
- if (type==VECTOR3)
- return *reinterpret_cast<const Vector3*>(_data._mem);
+ if (type == VECTOR3)
+ return *reinterpret_cast<const Vector3 *>(_data._mem);
else
return Vector3();
-
}
Variant::operator Plane() const {
- if (type==PLANE)
- return *reinterpret_cast<const Plane*>(_data._mem);
+ if (type == PLANE)
+ return *reinterpret_cast<const Plane *>(_data._mem);
else
return Plane();
-
}
Variant::operator Rect3() const {
- if (type==RECT3)
+ if (type == RECT3)
return *_data._rect3;
else
return Rect3();
@@ -1725,11 +1696,11 @@ Variant::operator Rect3() const {
Variant::operator Basis() const {
- if (type==BASIS)
+ if (type == BASIS)
return *_data._basis;
- else if (type==QUAT)
- return *reinterpret_cast<const Quat*>(_data._mem);
- else if (type==TRANSFORM)
+ else if (type == QUAT)
+ return *reinterpret_cast<const Quat *>(_data._mem);
+ else if (type == TRANSFORM)
return _data._transform->basis;
else
return Basis();
@@ -1737,63 +1708,60 @@ Variant::operator Basis() const {
Variant::operator Quat() const {
- if (type==QUAT)
- return *reinterpret_cast<const Quat*>(_data._mem);
- else if (type==BASIS)
- return *_data._basis;
- else if (type==TRANSFORM)
- return _data._transform->basis;
+ if (type == QUAT)
+ return *reinterpret_cast<const Quat *>(_data._mem);
+ else if (type == BASIS)
+ return *_data._basis;
+ else if (type == TRANSFORM)
+ return _data._transform->basis;
else
return Quat();
}
-
-
Variant::operator Transform() const {
- if (type==TRANSFORM)
+ if (type == TRANSFORM)
return *_data._transform;
- else if (type==BASIS)
- return Transform(*_data._basis,Vector3());
- else if (type==QUAT)
- return Transform(Basis(*reinterpret_cast<const Quat*>(_data._mem)),Vector3());
+ else if (type == BASIS)
+ return Transform(*_data._basis, Vector3());
+ else if (type == QUAT)
+ return Transform(Basis(*reinterpret_cast<const Quat *>(_data._mem)), Vector3());
else
return Transform();
}
- Variant::operator Transform2D() const {
+Variant::operator Transform2D() const {
- if (type==TRANSFORM2D) {
- return *_data._transform2d;
- } else if (type==TRANSFORM) {
- const Transform& t = *_data._transform;
- Transform2D m;
- m.elements[0][0]=t.basis.elements[0][0];
- m.elements[0][1]=t.basis.elements[1][0];
- m.elements[1][0]=t.basis.elements[0][1];
- m.elements[1][1]=t.basis.elements[1][1];
- m.elements[2][0]=t.origin[0];
- m.elements[2][1]=t.origin[1];
- return m;
- } else
- return Transform2D();
+ if (type == TRANSFORM2D) {
+ return *_data._transform2d;
+ } else if (type == TRANSFORM) {
+ const Transform &t = *_data._transform;
+ Transform2D m;
+ m.elements[0][0] = t.basis.elements[0][0];
+ m.elements[0][1] = t.basis.elements[1][0];
+ m.elements[1][0] = t.basis.elements[0][1];
+ m.elements[1][1] = t.basis.elements[1][1];
+ m.elements[2][0] = t.origin[0];
+ m.elements[2][1] = t.origin[1];
+ return m;
+ } else
+ return Transform2D();
}
-
Variant::operator Color() const {
- if (type==COLOR)
- return *reinterpret_cast<const Color*>(_data._mem);
- else if (type==STRING)
- return Color::html( operator String() );
- else if (type==INT)
- return Color::hex( operator int() );
+ if (type == COLOR)
+ return *reinterpret_cast<const Color *>(_data._mem);
+ else if (type == STRING)
+ return Color::html(operator String());
+ else if (type == INT)
+ return Color::hex(operator int());
else
return Color();
}
Variant::operator Image() const {
- if (type==IMAGE)
+ if (type == IMAGE)
return *_data._image;
else
return Image();
@@ -1801,18 +1769,17 @@ Variant::operator Image() const {
Variant::operator NodePath() const {
- if (type==NODE_PATH)
- return *reinterpret_cast<const NodePath*>(_data._mem);
- else if (type==STRING)
+ if (type == NODE_PATH)
+ return *reinterpret_cast<const NodePath *>(_data._mem);
+ else if (type == STRING)
return NodePath(operator String());
else
return NodePath();
}
-
Variant::operator RefPtr() const {
- if (type==OBJECT)
+ if (type == OBJECT)
return _get_obj().ref;
else
return RefPtr();
@@ -1820,14 +1787,14 @@ Variant::operator RefPtr() const {
Variant::operator RID() const {
- if (type==_RID)
- return *reinterpret_cast<const RID*>(_data._mem);
- else if (type==OBJECT && !_get_obj().ref.is_null()) {
+ if (type == _RID)
+ return *reinterpret_cast<const RID *>(_data._mem);
+ else if (type == OBJECT && !_get_obj().ref.is_null()) {
return _get_obj().ref.get_rid();
- } else if (type==OBJECT && _get_obj().obj) {
+ } else if (type == OBJECT && _get_obj().obj) {
Variant::CallError ce;
- Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid,NULL,0,ce);
- if (ce.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::_RID) {
+ Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid, NULL, 0, ce);
+ if (ce.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::_RID) {
return ret;
}
return RID();
@@ -1836,72 +1803,87 @@ Variant::operator RID() const {
}
}
-Variant::operator Object*() const {
+Variant::operator Object *() const {
- if (type==OBJECT)
+ if (type == OBJECT)
return _get_obj().obj;
else
return NULL;
}
-Variant::operator Node*() const {
+Variant::operator Node *() const {
- if (type==OBJECT)
- return _get_obj().obj?_get_obj().obj->cast_to<Node>():NULL;
+ if (type == OBJECT)
+ return _get_obj().obj ? _get_obj().obj->cast_to<Node>() : NULL;
else
return NULL;
}
-Variant::operator Control*() const {
+Variant::operator Control *() const {
- if (type==OBJECT)
- return _get_obj().obj?_get_obj().obj->cast_to<Control>():NULL;
+ if (type == OBJECT)
+ return _get_obj().obj ? _get_obj().obj->cast_to<Control>() : NULL;
else
return NULL;
}
Variant::operator InputEvent() const {
- if (type==INPUT_EVENT)
- return *reinterpret_cast<const InputEvent*>(_data._input_event);
+ if (type == INPUT_EVENT)
+ return *reinterpret_cast<const InputEvent *>(_data._input_event);
else
return InputEvent();
}
Variant::operator Dictionary() const {
- if (type==DICTIONARY)
- return *reinterpret_cast<const Dictionary*>(_data._mem);
+ if (type == DICTIONARY)
+ return *reinterpret_cast<const Dictionary *>(_data._mem);
else
return Dictionary();
}
-template<class DA,class SA>
-inline DA _convert_array(const SA& p_array) {
+template <class DA, class SA>
+inline DA _convert_array(const SA &p_array) {
DA da;
da.resize(p_array.size());
- for(int i=0;i<p_array.size();i++) {
+ for (int i = 0; i < p_array.size(); i++) {
- da.set( i, Variant(p_array.get(i)) );
+ da.set(i, Variant(p_array.get(i)));
}
return da;
}
-template<class DA>
-inline DA _convert_array_from_variant(const Variant& p_variant) {
-
- switch(p_variant.get_type()) {
+template <class DA>
+inline DA _convert_array_from_variant(const Variant &p_variant) {
+ switch (p_variant.get_type()) {
- case Variant::ARRAY: { return _convert_array<DA,Array >( p_variant.operator Array () ); }
- case Variant::POOL_BYTE_ARRAY: { return _convert_array<DA,PoolVector<uint8_t> >( p_variant.operator PoolVector<uint8_t> () ); }
- case Variant::POOL_INT_ARRAY: { return _convert_array<DA,PoolVector<int> >( p_variant.operator PoolVector<int> () ); }
- case Variant::POOL_REAL_ARRAY: { return _convert_array<DA,PoolVector<real_t> >( p_variant.operator PoolVector<real_t> () ); }
- case Variant::POOL_STRING_ARRAY: { return _convert_array<DA,PoolVector<String> >( p_variant.operator PoolVector<String> () ); }
- case Variant::POOL_VECTOR2_ARRAY: { return _convert_array<DA,PoolVector<Vector2> >( p_variant.operator PoolVector<Vector2> () ); }
- case Variant::POOL_VECTOR3_ARRAY: { return _convert_array<DA,PoolVector<Vector3> >( p_variant.operator PoolVector<Vector3> () ); }
- case Variant::POOL_COLOR_ARRAY: { return _convert_array<DA,PoolVector<Color> >( p_variant.operator PoolVector<Color>() ); }
+ case Variant::ARRAY: {
+ return _convert_array<DA, Array>(p_variant.operator Array());
+ }
+ case Variant::POOL_BYTE_ARRAY: {
+ return _convert_array<DA, PoolVector<uint8_t> >(p_variant.operator PoolVector<uint8_t>());
+ }
+ case Variant::POOL_INT_ARRAY: {
+ return _convert_array<DA, PoolVector<int> >(p_variant.operator PoolVector<int>());
+ }
+ case Variant::POOL_REAL_ARRAY: {
+ return _convert_array<DA, PoolVector<real_t> >(p_variant.operator PoolVector<real_t>());
+ }
+ case Variant::POOL_STRING_ARRAY: {
+ return _convert_array<DA, PoolVector<String> >(p_variant.operator PoolVector<String>());
+ }
+ case Variant::POOL_VECTOR2_ARRAY: {
+ return _convert_array<DA, PoolVector<Vector2> >(p_variant.operator PoolVector<Vector2>());
+ }
+ case Variant::POOL_VECTOR3_ARRAY: {
+ return _convert_array<DA, PoolVector<Vector3> >(p_variant.operator PoolVector<Vector3>());
+ }
+ case Variant::POOL_COLOR_ARRAY: {
+ return _convert_array<DA, PoolVector<Color> >(p_variant.operator PoolVector<Color>());
+ }
default: { return DA(); }
}
@@ -1910,278 +1892,265 @@ inline DA _convert_array_from_variant(const Variant& p_variant) {
Variant::operator Array() const {
- if (type==ARRAY)
- return *reinterpret_cast<const Array*>(_data._mem);
+ if (type == ARRAY)
+ return *reinterpret_cast<const Array *>(_data._mem);
else
- return _convert_array_from_variant<Array >(*this);
+ return _convert_array_from_variant<Array>(*this);
}
Variant::operator PoolVector<uint8_t>() const {
- if (type==POOL_BYTE_ARRAY)
- return *reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem);
+ if (type == POOL_BYTE_ARRAY)
+ return *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<uint8_t> >(*this);
}
Variant::operator PoolVector<int>() const {
- if (type==POOL_INT_ARRAY)
- return *reinterpret_cast<const PoolVector<int>* >(_data._mem);
+ if (type == POOL_INT_ARRAY)
+ return *reinterpret_cast<const PoolVector<int> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<int> >(*this);
-
}
Variant::operator PoolVector<real_t>() const {
- if (type==POOL_REAL_ARRAY)
- return *reinterpret_cast<const PoolVector<real_t>* >(_data._mem);
+ if (type == POOL_REAL_ARRAY)
+ return *reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<real_t> >(*this);
-
}
Variant::operator PoolVector<String>() const {
- if (type==POOL_STRING_ARRAY)
- return *reinterpret_cast<const PoolVector<String>* >(_data._mem);
+ if (type == POOL_STRING_ARRAY)
+ return *reinterpret_cast<const PoolVector<String> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<String> >(*this);
-
-
}
Variant::operator PoolVector<Vector3>() const {
- if (type==POOL_VECTOR3_ARRAY)
- return *reinterpret_cast<const PoolVector<Vector3>* >(_data._mem);
+ if (type == POOL_VECTOR3_ARRAY)
+ return *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Vector3> >(*this);
-
-
}
Variant::operator PoolVector<Vector2>() const {
- if (type==POOL_VECTOR2_ARRAY)
- return *reinterpret_cast<const PoolVector<Vector2>* >(_data._mem);
+ if (type == POOL_VECTOR2_ARRAY)
+ return *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Vector2> >(*this);
-
-
}
Variant::operator PoolVector<Color>() const {
- if (type==POOL_COLOR_ARRAY)
- return *reinterpret_cast<const PoolVector<Color>* >(_data._mem);
+ if (type == POOL_COLOR_ARRAY)
+ return *reinterpret_cast<const PoolVector<Color> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Color> >(*this);
-
}
/* helpers */
-
Variant::operator Vector<RID>() const {
- Array va= operator Array();
+ Array va = operator Array();
Vector<RID> rids;
rids.resize(va.size());
- for(int i=0;i<rids.size();i++)
- rids[i]=va[i];
+ for (int i = 0; i < rids.size(); i++)
+ rids[i] = va[i];
return rids;
}
Variant::operator Vector<Vector2>() const {
- PoolVector<Vector2> from=operator PoolVector<Vector2>();
+ PoolVector<Vector2> from = operator PoolVector<Vector2>();
Vector<Vector2> to;
- int len=from.size();
- if (len==0)
+ int len = from.size();
+ if (len == 0)
return Vector<Vector2>();
to.resize(len);
PoolVector<Vector2>::Read r = from.read();
Vector2 *w = &to[0];
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- w[i]=r[i];
+ w[i] = r[i];
}
return to;
}
Variant::operator PoolVector<Plane>() const {
- Array va= operator Array();
+ Array va = operator Array();
PoolVector<Plane> planes;
- int va_size=va.size();
- if (va_size==0)
+ int va_size = va.size();
+ if (va_size == 0)
return planes;
planes.resize(va_size);
PoolVector<Plane>::Write w = planes.write();
- for(int i=0;i<va_size;i++)
- w[i]=va[i];
+ for (int i = 0; i < va_size; i++)
+ w[i] = va[i];
return planes;
}
Variant::operator PoolVector<Face3>() const {
- PoolVector<Vector3> va= operator PoolVector<Vector3>();
+ PoolVector<Vector3> va = operator PoolVector<Vector3>();
PoolVector<Face3> faces;
- int va_size=va.size();
- if (va_size==0)
+ int va_size = va.size();
+ if (va_size == 0)
return faces;
- faces.resize(va_size/3);
+ faces.resize(va_size / 3);
PoolVector<Face3>::Write w = faces.write();
PoolVector<Vector3>::Read r = va.read();
- for(int i=0;i<va_size;i++)
- w[i/3].vertex[i%3]=r[i];
+ for (int i = 0; i < va_size; i++)
+ w[i / 3].vertex[i % 3] = r[i];
return faces;
}
Variant::operator Vector<Plane>() const {
- Array va= operator Array();
+ Array va = operator Array();
Vector<Plane> planes;
- int va_size=va.size();
- if (va_size==0)
+ int va_size = va.size();
+ if (va_size == 0)
return planes;
planes.resize(va_size);
- for(int i=0;i<va_size;i++)
- planes[i]=va[i];
+ for (int i = 0; i < va_size; i++)
+ planes[i] = va[i];
return planes;
}
Variant::operator Vector<Variant>() const {
- Array from=operator Array();
+ Array from = operator Array();
Vector<Variant> to;
- int len=from.size();
+ int len = from.size();
to.resize(len);
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- to[i]=from[i];
+ to[i] = from[i];
}
return to;
-
}
Variant::operator Vector<uint8_t>() const {
- PoolVector<uint8_t> from=operator PoolVector<uint8_t>();
+ PoolVector<uint8_t> from = operator PoolVector<uint8_t>();
Vector<uint8_t> to;
- int len=from.size();
+ int len = from.size();
to.resize(len);
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- to[i]=from[i];
+ to[i] = from[i];
}
return to;
}
Variant::operator Vector<int>() const {
- PoolVector<int> from=operator PoolVector<int>();
+ PoolVector<int> from = operator PoolVector<int>();
Vector<int> to;
- int len=from.size();
+ int len = from.size();
to.resize(len);
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- to[i]=from[i];
+ to[i] = from[i];
}
return to;
}
Variant::operator Vector<real_t>() const {
- PoolVector<real_t> from=operator PoolVector<real_t>();
+ PoolVector<real_t> from = operator PoolVector<real_t>();
Vector<real_t> to;
- int len=from.size();
+ int len = from.size();
to.resize(len);
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- to[i]=from[i];
+ to[i] = from[i];
}
return to;
}
Variant::operator Vector<String>() const {
- PoolVector<String> from=operator PoolVector<String>();
+ PoolVector<String> from = operator PoolVector<String>();
Vector<String> to;
- int len=from.size();
+ int len = from.size();
to.resize(len);
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- to[i]=from[i];
+ to[i] = from[i];
}
return to;
-
}
Variant::operator Vector<Vector3>() const {
- PoolVector<Vector3> from=operator PoolVector<Vector3>();
+ PoolVector<Vector3> from = operator PoolVector<Vector3>();
Vector<Vector3> to;
- int len=from.size();
- if (len==0)
+ int len = from.size();
+ if (len == 0)
return Vector<Vector3>();
to.resize(len);
PoolVector<Vector3>::Read r = from.read();
Vector3 *w = &to[0];
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- w[i]=r[i];
+ w[i] = r[i];
}
return to;
-
}
Variant::operator Vector<Color>() const {
- PoolVector<Color> from=operator PoolVector<Color>();
+ PoolVector<Color> from = operator PoolVector<Color>();
Vector<Color> to;
- int len=from.size();
- if (len==0)
+ int len = from.size();
+ if (len == 0)
return Vector<Color>();
to.resize(len);
PoolVector<Color>::Read r = from.read();
Color *w = &to[0];
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- w[i]=r[i];
+ w[i] = r[i];
}
return to;
}
Variant::operator Margin() const {
- return (Margin)operator int();
+ return (Margin) operator int();
}
Variant::operator Orientation() const {
- return (Orientation)operator int();
+ return (Orientation) operator int();
}
Variant::operator IP_Address() const {
- if (type==POOL_REAL_ARRAY || type==POOL_INT_ARRAY || type==POOL_BYTE_ARRAY) {
+ if (type == POOL_REAL_ARRAY || type == POOL_INT_ARRAY || type == POOL_BYTE_ARRAY) {
- PoolVector<int> addr=operator PoolVector<int>();
- if (addr.size()==4) {
- return IP_Address(addr.get(0),addr.get(1),addr.get(2),addr.get(3));
+ PoolVector<int> addr = operator PoolVector<int>();
+ if (addr.size() == 4) {
+ return IP_Address(addr.get(0), addr.get(1), addr.get(2), addr.get(3));
}
}
- return IP_Address( operator String() );
+ return IP_Address(operator String());
}
Variant::Variant(bool p_bool) {
- type=BOOL;
- _data._bool=p_bool;
+ type = BOOL;
+ _data._bool = p_bool;
}
/*
@@ -2194,358 +2163,314 @@ Variant::Variant(long unsigned int p_long) {
Variant::Variant(signed int p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
Variant::Variant(unsigned int p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
#ifdef NEED_LONG_INT
Variant::Variant(signed long p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
Variant::Variant(unsigned long p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
#endif
Variant::Variant(int64_t p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
Variant::Variant(uint64_t p_int) {
- type=INT;
- _data._int=p_int;
-
+ type = INT;
+ _data._int = p_int;
}
Variant::Variant(signed short p_short) {
- type=INT;
- _data._int=p_short;
-
+ type = INT;
+ _data._int = p_short;
}
Variant::Variant(unsigned short p_short) {
- type=INT;
- _data._int=p_short;
-
+ type = INT;
+ _data._int = p_short;
}
Variant::Variant(signed char p_char) {
- type=INT;
- _data._int=p_char;
-
+ type = INT;
+ _data._int = p_char;
}
Variant::Variant(unsigned char p_char) {
- type=INT;
- _data._int=p_char;
-
+ type = INT;
+ _data._int = p_char;
}
Variant::Variant(float p_float) {
- type=REAL;
- _data._real=p_float;
-
+ type = REAL;
+ _data._real = p_float;
}
Variant::Variant(double p_double) {
- type=REAL;
- _data._real=p_double;
+ type = REAL;
+ _data._real = p_double;
}
-Variant::Variant(const StringName& p_string) {
-
- type=STRING;
- memnew_placement( _data._mem, String( p_string.operator String() ) );
+Variant::Variant(const StringName &p_string) {
+ type = STRING;
+ memnew_placement(_data._mem, String(p_string.operator String()));
}
-Variant::Variant(const String& p_string) {
-
- type=STRING;
- memnew_placement( _data._mem, String( p_string ) );
+Variant::Variant(const String &p_string) {
+ type = STRING;
+ memnew_placement(_data._mem, String(p_string));
}
-Variant::Variant(const char * const p_cstring) {
-
- type=STRING;
- memnew_placement( _data._mem, String( (const char*)p_cstring ) );
+Variant::Variant(const char *const p_cstring) {
+ type = STRING;
+ memnew_placement(_data._mem, String((const char *)p_cstring));
}
-Variant::Variant(const CharType * p_wstring) {
-
- type=STRING;
- memnew_placement( _data._mem, String( p_wstring ) );
+Variant::Variant(const CharType *p_wstring) {
+ type = STRING;
+ memnew_placement(_data._mem, String(p_wstring));
}
-Variant::Variant(const Vector3& p_vector3) {
-
- type=VECTOR3;
- memnew_placement( _data._mem, Vector3( p_vector3 ) );
+Variant::Variant(const Vector3 &p_vector3) {
+ type = VECTOR3;
+ memnew_placement(_data._mem, Vector3(p_vector3));
}
-Variant::Variant(const Vector2& p_vector2) {
-
- type=VECTOR2;
- memnew_placement( _data._mem, Vector2( p_vector2 ) );
+Variant::Variant(const Vector2 &p_vector2) {
+ type = VECTOR2;
+ memnew_placement(_data._mem, Vector2(p_vector2));
}
-Variant::Variant(const Rect2& p_rect2) {
-
- type=RECT2;
- memnew_placement( _data._mem, Rect2( p_rect2 ) );
+Variant::Variant(const Rect2 &p_rect2) {
+ type = RECT2;
+ memnew_placement(_data._mem, Rect2(p_rect2));
}
-Variant::Variant(const Plane& p_plane) {
-
- type=PLANE;
- memnew_placement( _data._mem, Plane( p_plane ) );
+Variant::Variant(const Plane &p_plane) {
+ type = PLANE;
+ memnew_placement(_data._mem, Plane(p_plane));
}
-Variant::Variant(const Rect3& p_aabb) {
+Variant::Variant(const Rect3 &p_aabb) {
- type=RECT3;
- _data._rect3 = memnew( Rect3( p_aabb ) );
+ type = RECT3;
+ _data._rect3 = memnew(Rect3(p_aabb));
}
-Variant::Variant(const Basis& p_matrix) {
-
- type=BASIS;
- _data._basis= memnew( Basis( p_matrix ) );
+Variant::Variant(const Basis &p_matrix) {
+ type = BASIS;
+ _data._basis = memnew(Basis(p_matrix));
}
-Variant::Variant(const Quat& p_quat) {
-
- type=QUAT;
- memnew_placement( _data._mem, Quat( p_quat ) );
+Variant::Variant(const Quat &p_quat) {
+ type = QUAT;
+ memnew_placement(_data._mem, Quat(p_quat));
}
-Variant::Variant(const Transform& p_transform) {
-
- type=TRANSFORM;
- _data._transform = memnew( Transform( p_transform ) );
+Variant::Variant(const Transform &p_transform) {
+ type = TRANSFORM;
+ _data._transform = memnew(Transform(p_transform));
}
-Variant::Variant(const Transform2D& p_transform) {
-
- type=TRANSFORM2D;
- _data._transform2d = memnew( Transform2D( p_transform ) );
+Variant::Variant(const Transform2D &p_transform) {
+ type = TRANSFORM2D;
+ _data._transform2d = memnew(Transform2D(p_transform));
}
-Variant::Variant(const Color& p_color) {
-
- type=COLOR;
- memnew_placement( _data._mem, Color(p_color) );
+Variant::Variant(const Color &p_color) {
+ type = COLOR;
+ memnew_placement(_data._mem, Color(p_color));
}
-Variant::Variant(const Image& p_image) {
-
- type=IMAGE;
- _data._image=memnew( Image(p_image) );
+Variant::Variant(const Image &p_image) {
+ type = IMAGE;
+ _data._image = memnew(Image(p_image));
}
-Variant::Variant(const NodePath& p_node_path) {
-
- type=NODE_PATH;
- memnew_placement( _data._mem, NodePath(p_node_path) );
+Variant::Variant(const NodePath &p_node_path) {
+ type = NODE_PATH;
+ memnew_placement(_data._mem, NodePath(p_node_path));
}
-Variant::Variant(const InputEvent& p_input_event) {
-
- type=INPUT_EVENT;
- _data._input_event = memnew( InputEvent(p_input_event) );
+Variant::Variant(const InputEvent &p_input_event) {
+ type = INPUT_EVENT;
+ _data._input_event = memnew(InputEvent(p_input_event));
}
-Variant::Variant(const RefPtr& p_resource) {
+Variant::Variant(const RefPtr &p_resource) {
- type=OBJECT;
- memnew_placement( _data._mem, ObjData );
+ type = OBJECT;
+ memnew_placement(_data._mem, ObjData);
REF ref = p_resource;
- _get_obj().obj=ref.ptr();
- _get_obj().ref=p_resource;
-
+ _get_obj().obj = ref.ptr();
+ _get_obj().ref = p_resource;
}
-Variant::Variant(const RID& p_rid) {
-
- type=_RID;
- memnew_placement( _data._mem, RID(p_rid) );
+Variant::Variant(const RID &p_rid) {
+ type = _RID;
+ memnew_placement(_data._mem, RID(p_rid));
}
-Variant::Variant(const Object* p_object) {
+Variant::Variant(const Object *p_object) {
- type=OBJECT;
+ type = OBJECT;
- memnew_placement( _data._mem, ObjData );
- _get_obj().obj=const_cast<Object*>(p_object);
+ memnew_placement(_data._mem, ObjData);
+ _get_obj().obj = const_cast<Object *>(p_object);
}
-Variant::Variant(const Dictionary& p_dictionary) {
-
- type=DICTIONARY;
- memnew_placement( _data._mem, (Dictionary)( p_dictionary) );
+Variant::Variant(const Dictionary &p_dictionary) {
+ type = DICTIONARY;
+ memnew_placement(_data._mem, (Dictionary)(p_dictionary));
}
-Variant::Variant(const Array& p_array) {
-
- type=ARRAY;
- memnew_placement( _data._mem, Array(p_array) );
+Variant::Variant(const Array &p_array) {
+ type = ARRAY;
+ memnew_placement(_data._mem, Array(p_array));
}
-Variant::Variant(const PoolVector<Plane>& p_array) {
+Variant::Variant(const PoolVector<Plane> &p_array) {
+ type = ARRAY;
- type=ARRAY;
+ Array *plane_array = memnew_placement(_data._mem, Array);
- Array *plane_array=memnew_placement( _data._mem, Array );
+ plane_array->resize(p_array.size());
- plane_array->resize( p_array.size() );
+ for (int i = 0; i < p_array.size(); i++) {
- for (int i=0;i<p_array.size();i++) {
-
- plane_array->operator [](i)=Variant(p_array[i]);
+ plane_array->operator[](i) = Variant(p_array[i]);
}
}
-Variant::Variant(const Vector<Plane>& p_array) {
-
+Variant::Variant(const Vector<Plane> &p_array) {
- type=ARRAY;
+ type = ARRAY;
- Array *plane_array=memnew_placement( _data._mem, Array );
+ Array *plane_array = memnew_placement(_data._mem, Array);
- plane_array->resize( p_array.size() );
+ plane_array->resize(p_array.size());
- for (int i=0;i<p_array.size();i++) {
+ for (int i = 0; i < p_array.size(); i++) {
- plane_array->operator [](i)=Variant(p_array[i]);
+ plane_array->operator[](i) = Variant(p_array[i]);
}
}
-Variant::Variant(const Vector<RID>& p_array) {
+Variant::Variant(const Vector<RID> &p_array) {
+ type = ARRAY;
- type=ARRAY;
+ Array *rid_array = memnew_placement(_data._mem, Array);
- Array *rid_array=memnew_placement( _data._mem, Array );
+ rid_array->resize(p_array.size());
- rid_array->resize( p_array.size() );
+ for (int i = 0; i < p_array.size(); i++) {
- for (int i=0;i<p_array.size();i++) {
-
- rid_array->set(i,Variant(p_array[i]));
+ rid_array->set(i, Variant(p_array[i]));
}
}
-Variant::Variant(const Vector<Vector2>& p_array) {
-
+Variant::Variant(const Vector<Vector2> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<Vector2> v;
- int len=p_array.size();
- if (len>0) {
+ int len = p_array.size();
+ if (len > 0) {
v.resize(len);
PoolVector<Vector2>::Write w = v.write();
const Vector2 *r = p_array.ptr();
- for (int i=0;i<len;i++)
- w[i]=r[i];
+ for (int i = 0; i < len; i++)
+ w[i] = r[i];
}
- *this=v;
+ *this = v;
}
+Variant::Variant(const PoolVector<uint8_t> &p_raw_array) {
-Variant::Variant(const PoolVector<uint8_t>& p_raw_array) {
-
- type=POOL_BYTE_ARRAY;
- memnew_placement( _data._mem, PoolVector<uint8_t>(p_raw_array) );
-
+ type = POOL_BYTE_ARRAY;
+ memnew_placement(_data._mem, PoolVector<uint8_t>(p_raw_array));
}
-Variant::Variant(const PoolVector<int>& p_int_array) {
-
- type=POOL_INT_ARRAY;
- memnew_placement( _data._mem, PoolVector<int>(p_int_array) );
+Variant::Variant(const PoolVector<int> &p_int_array) {
+ type = POOL_INT_ARRAY;
+ memnew_placement(_data._mem, PoolVector<int>(p_int_array));
}
-Variant::Variant(const PoolVector<real_t>& p_real_array) {
-
- type=POOL_REAL_ARRAY;
- memnew_placement( _data._mem, PoolVector<real_t>(p_real_array) );
+Variant::Variant(const PoolVector<real_t> &p_real_array) {
+ type = POOL_REAL_ARRAY;
+ memnew_placement(_data._mem, PoolVector<real_t>(p_real_array));
}
-Variant::Variant(const PoolVector<String>& p_string_array) {
-
- type=POOL_STRING_ARRAY;
- memnew_placement( _data._mem, PoolVector<String>(p_string_array) );
+Variant::Variant(const PoolVector<String> &p_string_array) {
+ type = POOL_STRING_ARRAY;
+ memnew_placement(_data._mem, PoolVector<String>(p_string_array));
}
-Variant::Variant(const PoolVector<Vector3>& p_vector3_array) {
-
- type=POOL_VECTOR3_ARRAY;
- memnew_placement( _data._mem, PoolVector<Vector3>(p_vector3_array) );
+Variant::Variant(const PoolVector<Vector3> &p_vector3_array) {
+ type = POOL_VECTOR3_ARRAY;
+ memnew_placement(_data._mem, PoolVector<Vector3>(p_vector3_array));
}
-Variant::Variant(const PoolVector<Vector2>& p_vector2_array) {
-
- type=POOL_VECTOR2_ARRAY;
- memnew_placement( _data._mem, PoolVector<Vector2>(p_vector2_array) );
+Variant::Variant(const PoolVector<Vector2> &p_vector2_array) {
+ type = POOL_VECTOR2_ARRAY;
+ memnew_placement(_data._mem, PoolVector<Vector2>(p_vector2_array));
}
-Variant::Variant(const PoolVector<Color>& p_color_array) {
+Variant::Variant(const PoolVector<Color> &p_color_array) {
- type=POOL_COLOR_ARRAY;
- memnew_placement( _data._mem, PoolVector<Color>(p_color_array) );
+ type = POOL_COLOR_ARRAY;
+ memnew_placement(_data._mem, PoolVector<Color>(p_color_array));
}
-Variant::Variant(const PoolVector<Face3>& p_face_array) {
-
+Variant::Variant(const PoolVector<Face3> &p_face_array) {
PoolVector<Vector3> vertices;
- int face_count=p_face_array.size();
- vertices.resize(face_count*3);
+ int face_count = p_face_array.size();
+ vertices.resize(face_count * 3);
if (face_count) {
PoolVector<Face3>::Read r = p_face_array.read();
PoolVector<Vector3>::Write w = vertices.write();
- for(int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- for(int j=0;j<3;j++)
- w[i*3+j]=r[i].vertex[j];
+ for (int j = 0; j < 3; j++)
+ w[i * 3 + j] = r[i].vertex[j];
}
- r=PoolVector<Face3>::Read();
- w=PoolVector<Vector3>::Write();
-
+ r = PoolVector<Face3>::Read();
+ w = PoolVector<Vector3>::Write();
}
type = NIL;
@@ -2555,107 +2480,105 @@ Variant::Variant(const PoolVector<Face3>& p_face_array) {
/* helpers */
-Variant::Variant(const Vector<Variant>& p_array) {
+Variant::Variant(const Vector<Variant> &p_array) {
- type=NIL;
+ type = NIL;
Array v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-Variant::Variant(const Vector<uint8_t>& p_array) {
+Variant::Variant(const Vector<uint8_t> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<uint8_t> v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-Variant::Variant(const Vector<int>& p_array) {
+Variant::Variant(const Vector<int> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<int> v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-Variant::Variant(const Vector<real_t>& p_array) {
+Variant::Variant(const Vector<real_t> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<real_t> v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-Variant::Variant(const Vector<String>& p_array) {
+Variant::Variant(const Vector<String> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<String> v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-Variant::Variant(const Vector<Vector3>& p_array) {
+Variant::Variant(const Vector<Vector3> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<Vector3> v;
- int len=p_array.size();
- if (len>0) {
+ int len = p_array.size();
+ if (len > 0) {
v.resize(len);
PoolVector<Vector3>::Write w = v.write();
const Vector3 *r = p_array.ptr();
- for (int i=0;i<len;i++)
- w[i]=r[i];
+ for (int i = 0; i < len; i++)
+ w[i] = r[i];
}
- *this=v;
+ *this = v;
}
-Variant::Variant(const Vector<Color>& p_array) {
+Variant::Variant(const Vector<Color> &p_array) {
- type=NIL;
+ type = NIL;
PoolVector<Color> v;
- int len=p_array.size();
+ int len = p_array.size();
v.resize(len);
- for (int i=0;i<len;i++)
- v.set(i,p_array[i]);
- *this=v;
+ for (int i = 0; i < len; i++)
+ v.set(i, p_array[i]);
+ *this = v;
}
-void Variant::operator=(const Variant& p_variant) {
+void Variant::operator=(const Variant &p_variant) {
reference(p_variant);
}
-Variant::Variant(const IP_Address& p_address) {
+Variant::Variant(const IP_Address &p_address) {
- type=STRING;
- memnew_placement( _data._mem, String( p_address ) );
+ type = STRING;
+ memnew_placement(_data._mem, String(p_address));
}
+Variant::Variant(const Variant &p_variant) {
-Variant::Variant(const Variant& p_variant) {
-
- type=NIL;
+ type = NIL;
reference(p_variant);
}
-
/*
Variant::~Variant() {
@@ -2664,14 +2587,14 @@ Variant::~Variant() {
uint32_t Variant::hash() const {
- switch( type ) {
+ switch (type) {
case NIL: {
return 0;
} break;
case BOOL: {
- return _data._bool?1:0;
+ return _data._bool ? 1 : 0;
} break;
case INT: {
@@ -2683,29 +2606,29 @@ uint32_t Variant::hash() const {
} break;
case STRING: {
- return reinterpret_cast<const String*>(_data._mem)->hash();
+ return reinterpret_cast<const String *>(_data._mem)->hash();
} break;
- // math types
+ // math types
case VECTOR2: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2*>(_data._mem)->x);
- return hash_djb2_one_float(reinterpret_cast<const Vector2*>(_data._mem)->y,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->x);
+ return hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->y, hash);
} break;
case RECT2: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->pos.x);
- hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->pos.y,hash);
- hash = hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->size.x,hash);
- return hash_djb2_one_float(reinterpret_cast<const Rect2*>(_data._mem)->size.y,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->pos.x);
+ hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->pos.y, hash);
+ hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.x, hash);
+ return hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.y, hash);
} break;
case TRANSFORM2D: {
uint32_t hash = 5831;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- for(int j=0;j<2;j++) {
- hash = hash_djb2_one_float(_data._transform2d->elements[i][j],hash);
+ for (int j = 0; j < 2; j++) {
+ hash = hash_djb2_one_float(_data._transform2d->elements[i][j], hash);
}
}
@@ -2713,19 +2636,19 @@ uint32_t Variant::hash() const {
} break;
case VECTOR3: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->x);
- hash = hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->y,hash);
- return hash_djb2_one_float(reinterpret_cast<const Vector3*>(_data._mem)->z,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->x);
+ hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->y, hash);
+ return hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->z, hash);
} break;
case PLANE: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.x);
- hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.y,hash);
- hash = hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->normal.z,hash);
- return hash_djb2_one_float(reinterpret_cast<const Plane*>(_data._mem)->d,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.x);
+ hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.y, hash);
+ hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.z, hash);
+ return hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->d, hash);
} break;
- /*
+ /*
case QUAT: {
@@ -2733,31 +2656,30 @@ uint32_t Variant::hash() const {
case RECT3: {
uint32_t hash = 5831;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- hash = hash_djb2_one_float(_data._rect3->pos[i],hash);
- hash = hash_djb2_one_float(_data._rect3->size[i],hash);
+ hash = hash_djb2_one_float(_data._rect3->pos[i], hash);
+ hash = hash_djb2_one_float(_data._rect3->size[i], hash);
}
-
return hash;
} break;
case QUAT: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->x);
- hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->y,hash);
- hash = hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->z,hash);
- return hash_djb2_one_float(reinterpret_cast<const Quat*>(_data._mem)->w,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->x);
+ hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->y, hash);
+ hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->z, hash);
+ return hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->w, hash);
} break;
case BASIS: {
uint32_t hash = 5831;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- for(int j=0;j<3;j++) {
- hash = hash_djb2_one_float(_data._basis->elements[i][j],hash);
+ for (int j = 0; j < 3; j++) {
+ hash = hash_djb2_one_float(_data._basis->elements[i][j], hash);
}
}
@@ -2767,26 +2689,25 @@ uint32_t Variant::hash() const {
case TRANSFORM: {
uint32_t hash = 5831;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- for(int j=0;j<3;j++) {
- hash = hash_djb2_one_float(_data._transform->basis.elements[i][j],hash);
+ for (int j = 0; j < 3; j++) {
+ hash = hash_djb2_one_float(_data._transform->basis.elements[i][j], hash);
}
- hash = hash_djb2_one_float(_data._transform->origin[i],hash);
+ hash = hash_djb2_one_float(_data._transform->origin[i], hash);
}
-
return hash;
} break;
- // misc types
+ // misc types
case COLOR: {
- uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->r);
- hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->g,hash);
- hash = hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->b,hash);
- return hash_djb2_one_float(reinterpret_cast<const Color*>(_data._mem)->a,hash);
+ uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->r);
+ hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->g, hash);
+ hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->b, hash);
+ return hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->a, hash);
} break;
case IMAGE: {
@@ -2796,7 +2717,7 @@ uint32_t Variant::hash() const {
} break;
case _RID: {
- return hash_djb2_one_64(reinterpret_cast<const RID*>(_data._mem)->get_id());
+ return hash_djb2_one_64(reinterpret_cast<const RID *>(_data._mem)->get_id());
} break;
case OBJECT: {
@@ -2804,75 +2725,74 @@ uint32_t Variant::hash() const {
} break;
case NODE_PATH: {
- return reinterpret_cast<const NodePath*>(_data._mem)->hash();
+ return reinterpret_cast<const NodePath *>(_data._mem)->hash();
} break;
case INPUT_EVENT: {
- return hash_djb2_buffer((uint8_t*)_data._input_event,sizeof(InputEvent));
+ return hash_djb2_buffer((uint8_t *)_data._input_event, sizeof(InputEvent));
} break;
case DICTIONARY: {
- return reinterpret_cast<const Dictionary*>(_data._mem)->hash();
-
+ return reinterpret_cast<const Dictionary *>(_data._mem)->hash();
} break;
case ARRAY: {
- const Array& arr = *reinterpret_cast<const Array* >(_data._mem);
+ const Array &arr = *reinterpret_cast<const Array *>(_data._mem);
return arr.hash();
} break;
case POOL_BYTE_ARRAY: {
- const PoolVector<uint8_t>& arr = *reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem);
+ const PoolVector<uint8_t> &arr = *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
int len = arr.size();
PoolVector<uint8_t>::Read r = arr.read();
- return hash_djb2_buffer((uint8_t*)&r[0],len);
+ return hash_djb2_buffer((uint8_t *)&r[0], len);
} break;
case POOL_INT_ARRAY: {
- const PoolVector<int>& arr = *reinterpret_cast<const PoolVector<int>* >(_data._mem);
+ const PoolVector<int> &arr = *reinterpret_cast<const PoolVector<int> *>(_data._mem);
int len = arr.size();
PoolVector<int>::Read r = arr.read();
- return hash_djb2_buffer((uint8_t*)&r[0],len*sizeof(int));
+ return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(int));
} break;
case POOL_REAL_ARRAY: {
- const PoolVector<real_t>& arr = *reinterpret_cast<const PoolVector<real_t>* >(_data._mem);
+ const PoolVector<real_t> &arr = *reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
int len = arr.size();
PoolVector<real_t>::Read r = arr.read();
- return hash_djb2_buffer((uint8_t*)&r[0],len*sizeof(real_t));
+ return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(real_t));
} break;
case POOL_STRING_ARRAY: {
- uint32_t hash=5831;
- const PoolVector<String>& arr = *reinterpret_cast<const PoolVector<String>* >(_data._mem);
+ uint32_t hash = 5831;
+ const PoolVector<String> &arr = *reinterpret_cast<const PoolVector<String> *>(_data._mem);
int len = arr.size();
PoolVector<String>::Read r = arr.read();
- for(int i=0;i<len;i++) {
- hash = hash_djb2_one_32(r[i].hash(),hash);
+ for (int i = 0; i < len; i++) {
+ hash = hash_djb2_one_32(r[i].hash(), hash);
}
return hash;
} break;
case POOL_VECTOR2_ARRAY: {
- uint32_t hash=5831;
- const PoolVector<Vector2>& arr = *reinterpret_cast<const PoolVector<Vector2>* >(_data._mem);
+ uint32_t hash = 5831;
+ const PoolVector<Vector2> &arr = *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
int len = arr.size();
PoolVector<Vector2>::Read r = arr.read();
- for(int i=0;i<len;i++) {
- hash = hash_djb2_one_float(r[i].x,hash);
- hash = hash_djb2_one_float(r[i].y,hash);
+ for (int i = 0; i < len; i++) {
+ hash = hash_djb2_one_float(r[i].x, hash);
+ hash = hash_djb2_one_float(r[i].y, hash);
}
return hash;
@@ -2880,15 +2800,15 @@ uint32_t Variant::hash() const {
} break;
case POOL_VECTOR3_ARRAY: {
- uint32_t hash=5831;
- const PoolVector<Vector3>& arr = *reinterpret_cast<const PoolVector<Vector3>* >(_data._mem);
+ uint32_t hash = 5831;
+ const PoolVector<Vector3> &arr = *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
int len = arr.size();
PoolVector<Vector3>::Read r = arr.read();
- for(int i=0;i<len;i++) {
- hash = hash_djb2_one_float(r[i].x,hash);
- hash = hash_djb2_one_float(r[i].y,hash);
- hash = hash_djb2_one_float(r[i].z,hash);
+ for (int i = 0; i < len; i++) {
+ hash = hash_djb2_one_float(r[i].x, hash);
+ hash = hash_djb2_one_float(r[i].y, hash);
+ hash = hash_djb2_one_float(r[i].z, hash);
}
return hash;
@@ -2896,100 +2816,98 @@ uint32_t Variant::hash() const {
} break;
case POOL_COLOR_ARRAY: {
- uint32_t hash=5831;
- const PoolVector<Color>& arr = *reinterpret_cast<const PoolVector<Color>* >(_data._mem);
+ uint32_t hash = 5831;
+ const PoolVector<Color> &arr = *reinterpret_cast<const PoolVector<Color> *>(_data._mem);
int len = arr.size();
PoolVector<Color>::Read r = arr.read();
- for(int i=0;i<len;i++) {
- hash = hash_djb2_one_float(r[i].r,hash);
- hash = hash_djb2_one_float(r[i].g,hash);
- hash = hash_djb2_one_float(r[i].b,hash);
- hash = hash_djb2_one_float(r[i].a,hash);
+ for (int i = 0; i < len; i++) {
+ hash = hash_djb2_one_float(r[i].r, hash);
+ hash = hash_djb2_one_float(r[i].g, hash);
+ hash = hash_djb2_one_float(r[i].b, hash);
+ hash = hash_djb2_one_float(r[i].a, hash);
}
return hash;
} break;
default: {}
-
- }
+ }
return 0;
-
}
-#define hash_compare_scalar(p_lhs, p_rhs)\
+#define hash_compare_scalar(p_lhs, p_rhs) \
((p_lhs) == (p_rhs)) || (Math::is_nan(p_lhs) == Math::is_nan(p_rhs))
-#define hash_compare_vector2(p_lhs, p_rhs)\
- (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
- (hash_compare_scalar((p_lhs).y, (p_rhs).y))
-
-#define hash_compare_vector3(p_lhs, p_rhs)\
+#define hash_compare_vector2(p_lhs, p_rhs) \
(hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
- (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
- (hash_compare_scalar((p_lhs).z, (p_rhs).z))
-
-#define hash_compare_quat(p_lhs, p_rhs)\
- (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
- (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
- (hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \
- (hash_compare_scalar((p_lhs).w, (p_rhs).w))
-
-#define hash_compare_color(p_lhs, p_rhs)\
- (hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \
- (hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \
- (hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \
- (hash_compare_scalar((p_lhs).a, (p_rhs).a))
-
-#define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func)\
- const PoolVector<p_type>& l = *reinterpret_cast<const PoolVector<p_type>*>(p_lhs);\
- const PoolVector<p_type>& r = *reinterpret_cast<const PoolVector<p_type>*>(p_rhs);\
- \
- if(l.size() != r.size()) \
- return false; \
- \
- PoolVector<p_type>::Read lr = l.read(); \
- PoolVector<p_type>::Read rr = r.read(); \
- \
- for(int i = 0; i < l.size(); ++i) { \
- if(! p_compare_func((lr[i]), (rr[i]))) \
- return false; \
- }\
- \
- return true
-
-bool Variant::hash_compare(const Variant& p_variant) const {
+ (hash_compare_scalar((p_lhs).y, (p_rhs).y))
+
+#define hash_compare_vector3(p_lhs, p_rhs) \
+ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
+ (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
+ (hash_compare_scalar((p_lhs).z, (p_rhs).z))
+
+#define hash_compare_quat(p_lhs, p_rhs) \
+ (hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
+ (hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
+ (hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \
+ (hash_compare_scalar((p_lhs).w, (p_rhs).w))
+
+#define hash_compare_color(p_lhs, p_rhs) \
+ (hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \
+ (hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \
+ (hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \
+ (hash_compare_scalar((p_lhs).a, (p_rhs).a))
+
+#define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func) \
+ const PoolVector<p_type> &l = *reinterpret_cast<const PoolVector<p_type> *>(p_lhs); \
+ const PoolVector<p_type> &r = *reinterpret_cast<const PoolVector<p_type> *>(p_rhs); \
+ \
+ if (l.size() != r.size()) \
+ return false; \
+ \
+ PoolVector<p_type>::Read lr = l.read(); \
+ PoolVector<p_type>::Read rr = r.read(); \
+ \
+ for (int i = 0; i < l.size(); ++i) { \
+ if (!p_compare_func((lr[i]), (rr[i]))) \
+ return false; \
+ } \
+ \
+ return true
+
+bool Variant::hash_compare(const Variant &p_variant) const {
if (type != p_variant.type)
return false;
- switch( type ) {
+ switch (type) {
case REAL: {
return hash_compare_scalar(_data._real, p_variant._data._real);
} break;
case VECTOR2: {
- const Vector2* l = reinterpret_cast<const Vector2*>(_data._mem);
- const Vector2* r = reinterpret_cast<const Vector2*>(p_variant._data._mem);
+ const Vector2 *l = reinterpret_cast<const Vector2 *>(_data._mem);
+ const Vector2 *r = reinterpret_cast<const Vector2 *>(p_variant._data._mem);
return hash_compare_vector2(*l, *r);
} break;
case RECT2: {
- const Rect2* l = reinterpret_cast<const Rect2*>(_data._mem);
- const Rect2* r = reinterpret_cast<const Rect2*>(p_variant._data._mem);
+ const Rect2 *l = reinterpret_cast<const Rect2 *>(_data._mem);
+ const Rect2 *r = reinterpret_cast<const Rect2 *>(p_variant._data._mem);
return (hash_compare_vector2(l->pos, r->pos)) &&
- (hash_compare_vector2(l->size, r->size));
+ (hash_compare_vector2(l->size, r->size));
} break;
case TRANSFORM2D: {
- Transform2D* l = _data._transform2d;
- Transform2D* r = p_variant._data._transform2d;
+ Transform2D *l = _data._transform2d;
+ Transform2D *r = p_variant._data._transform2d;
- for(int i=0;i<3;i++) {
- if (! (hash_compare_vector2(l->elements[i], r->elements[i])))
+ for (int i = 0; i < 3; i++) {
+ if (!(hash_compare_vector2(l->elements[i], r->elements[i])))
return false;
}
@@ -2997,23 +2915,23 @@ bool Variant::hash_compare(const Variant& p_variant) const {
} break;
case VECTOR3: {
- const Vector3* l = reinterpret_cast<const Vector3*>(_data._mem);
- const Vector3* r = reinterpret_cast<const Vector3*>(p_variant._data._mem);
+ const Vector3 *l = reinterpret_cast<const Vector3 *>(_data._mem);
+ const Vector3 *r = reinterpret_cast<const Vector3 *>(p_variant._data._mem);
return hash_compare_vector3(*l, *r);
} break;
case PLANE: {
- const Plane* l = reinterpret_cast<const Plane*>(_data._mem);
- const Plane* r = reinterpret_cast<const Plane*>(p_variant._data._mem);
+ const Plane *l = reinterpret_cast<const Plane *>(_data._mem);
+ const Plane *r = reinterpret_cast<const Plane *>(p_variant._data._mem);
return (hash_compare_vector3(l->normal, r->normal)) &&
- (hash_compare_scalar(l->d, r->d));
+ (hash_compare_scalar(l->d, r->d));
} break;
case RECT3: {
- const Rect3* l = _data._rect3;
- const Rect3* r = p_variant._data._rect3;
+ const Rect3 *l = _data._rect3;
+ const Rect3 *r = p_variant._data._rect3;
return (hash_compare_vector3(l->pos, r->pos) &&
(hash_compare_vector3(l->size, r->size)));
@@ -3021,18 +2939,18 @@ bool Variant::hash_compare(const Variant& p_variant) const {
} break;
case QUAT: {
- const Quat* l = reinterpret_cast<const Quat*>(_data._mem);
- const Quat* r = reinterpret_cast<const Quat*>(p_variant._data._mem);
+ const Quat *l = reinterpret_cast<const Quat *>(_data._mem);
+ const Quat *r = reinterpret_cast<const Quat *>(p_variant._data._mem);
return hash_compare_quat(*l, *r);
} break;
case BASIS: {
- const Basis* l = _data._basis;
- const Basis* r = p_variant._data._basis;
+ const Basis *l = _data._basis;
+ const Basis *r = p_variant._data._basis;
- for(int i=0;i<3;i++) {
- if (! (hash_compare_vector3(l->elements[i], r->elements[i])))
+ for (int i = 0; i < 3; i++) {
+ if (!(hash_compare_vector3(l->elements[i], r->elements[i])))
return false;
}
@@ -3040,11 +2958,11 @@ bool Variant::hash_compare(const Variant& p_variant) const {
} break;
case TRANSFORM: {
- const Transform* l = _data._transform;
- const Transform* r = p_variant._data._transform;
+ const Transform *l = _data._transform;
+ const Transform *r = p_variant._data._transform;
- for(int i=0;i<3;i++) {
- if (! (hash_compare_vector3(l->basis.elements[i], r->basis.elements[i])))
+ for (int i = 0; i < 3; i++) {
+ if (!(hash_compare_vector3(l->basis.elements[i], r->basis.elements[i])))
return false;
}
@@ -3052,21 +2970,21 @@ bool Variant::hash_compare(const Variant& p_variant) const {
} break;
case COLOR: {
- const Color* l = reinterpret_cast<const Color*>(_data._mem);
- const Color* r = reinterpret_cast<const Color*>(p_variant._data._mem);
+ const Color *l = reinterpret_cast<const Color *>(_data._mem);
+ const Color *r = reinterpret_cast<const Color *>(p_variant._data._mem);
return hash_compare_color(*l, *r);
} break;
case ARRAY: {
- const Array& l = *(reinterpret_cast<const Array*>(_data._mem));
- const Array& r = *(reinterpret_cast<const Array*>(p_variant._data._mem));
+ const Array &l = *(reinterpret_cast<const Array *>(_data._mem));
+ const Array &r = *(reinterpret_cast<const Array *>(p_variant._data._mem));
- if(l.size() != r.size())
+ if (l.size() != r.size())
return false;
- for(int i = 0; i < l.size(); ++i) {
- if(! l[i].hash_compare(r[i]))
+ for (int i = 0; i < l.size(); ++i) {
+ if (!l[i].hash_compare(r[i]))
return false;
}
@@ -3092,39 +3010,37 @@ bool Variant::hash_compare(const Variant& p_variant) const {
default:
bool v;
Variant r;
- evaluate(OP_EQUAL,*this,p_variant,r,v);
+ evaluate(OP_EQUAL, *this, p_variant, r, v);
return r;
- }
+ }
return false;
}
-
bool Variant::is_ref() const {
- return type==OBJECT && !_get_obj().ref.is_null();
+ return type == OBJECT && !_get_obj().ref.is_null();
}
-
Vector<Variant> varray() {
return Vector<Variant>();
}
-Vector<Variant> varray(const Variant& p_arg1) {
+Vector<Variant> varray(const Variant &p_arg1) {
Vector<Variant> v;
v.push_back(p_arg1);
return v;
}
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2) {
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2) {
Vector<Variant> v;
v.push_back(p_arg1);
v.push_back(p_arg2);
return v;
}
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3) {
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3) {
Vector<Variant> v;
v.push_back(p_arg1);
@@ -3132,7 +3048,7 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant
v.push_back(p_arg3);
return v;
}
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4) {
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4) {
Vector<Variant> v;
v.push_back(p_arg1);
@@ -3142,7 +3058,7 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant
return v;
}
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5) {
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5) {
Vector<Variant> v;
v.push_back(p_arg1);
@@ -3151,57 +3067,53 @@ Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant
v.push_back(p_arg4);
v.push_back(p_arg5);
return v;
-
}
-void Variant::static_assign(const Variant& p_variant) {
-
-
+void Variant::static_assign(const Variant &p_variant) {
}
bool Variant::is_shared() const {
- switch(type) {
-
- case OBJECT: return true;
- case ARRAY: return true;
- case DICTIONARY: return true;
- default: {}
+ switch (type) {
- }
+ case OBJECT: return true;
+ case ARRAY: return true;
+ case DICTIONARY: return true;
+ default: {}
+ }
- return false;
+ return false;
}
-Variant Variant::call(const StringName& p_method,VARIANT_ARG_DECLARE) {
+Variant Variant::call(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
CallError error;
- Variant ret = call(p_method,argptr,argc,error);
+ Variant ret = call(p_method, argptr, argc, error);
- switch(error.error) {
+ switch (error.error) {
case CallError::CALL_ERROR_INVALID_ARGUMENT: {
- String err = "Invalid type for argument #"+itos(error.argument)+", expected '"+Variant::get_type_name(error.expected)+"'.";
+ String err = "Invalid type for argument #" + itos(error.argument) + ", expected '" + Variant::get_type_name(error.expected) + "'.";
ERR_PRINT(err.utf8().get_data());
} break;
case CallError::CALL_ERROR_INVALID_METHOD: {
- String err = "Invalid method '"+p_method+"' for type '"+Variant::get_type_name(type)+"'.";
+ String err = "Invalid method '" + p_method + "' for type '" + Variant::get_type_name(type) + "'.";
ERR_PRINT(err.utf8().get_data());
} break;
case CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
- String err = "Too many arguments for method '"+p_method+"'";
+ String err = "Too many arguments for method '" + p_method + "'";
ERR_PRINT(err.utf8().get_data());
} break;
default: {}
@@ -3210,38 +3122,35 @@ Variant Variant::call(const StringName& p_method,VARIANT_ARG_DECLARE) {
return ret;
}
-void Variant::construct_from_string(const String& p_string,Variant& r_value,ObjectConstruct p_obj_construct,void *p_construct_ud) {
+void Variant::construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct, void *p_construct_ud) {
- r_value=Variant();
+ r_value = Variant();
}
-
String Variant::get_construct_string() const {
String vars;
- VariantWriter::write_to_string(*this,vars);
+ VariantWriter::write_to_string(*this, vars);
return vars;
-
}
-String Variant::get_call_error_text(Object* p_base, const StringName& p_method,const Variant** p_argptrs,int p_argcount,const Variant::CallError &ce) {
-
+String Variant::get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce) {
String err_text;
- if (ce.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- int errorarg=ce.argument;
- err_text="Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(p_argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(ce.expected)+".";
- } else if (ce.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- err_text="Method expected "+itos(ce.argument)+" arguments, but called with "+itos(p_argcount)+".";
- } else if (ce.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- err_text="Method expected "+itos(ce.argument)+" arguments, but called with "+itos(p_argcount)+".";
- } else if (ce.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
- err_text="Method not found.";
- } else if (ce.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
- err_text="Instance is null";
- } else if (ce.error==Variant::CallError::CALL_OK){
+ if (ce.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ int errorarg = ce.argument;
+ err_text = "Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(p_argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(ce.expected) + ".";
+ } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
+ err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + ".";
+ } else if (ce.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
+ err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + ".";
+ } else if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
+ err_text = "Method not found.";
+ } else if (ce.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
+ err_text = "Instance is null";
+ } else if (ce.error == Variant::CallError::CALL_OK) {
return "Call OK";
}
@@ -3249,51 +3158,43 @@ String Variant::get_call_error_text(Object* p_base, const StringName& p_method,c
Ref<Script> script = p_base->get_script();
if (script.is_valid() && script->get_path().is_resource_file()) {
- class_name+="("+script->get_path().get_file()+")";
+ class_name += "(" + script->get_path().get_file() + ")";
}
- return "'"+class_name+"::"+String(p_method)+"': "+err_text;
+ return "'" + class_name + "::" + String(p_method) + "': " + err_text;
}
-
-String vformat(const String& p_text, const Variant& p1,const Variant& p2,const Variant& p3,const Variant& p4,const Variant& p5) {
+String vformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
Array args;
- if (p1.get_type()!=Variant::NIL) {
+ if (p1.get_type() != Variant::NIL) {
args.push_back(p1);
- if (p2.get_type()!=Variant::NIL) {
+ if (p2.get_type() != Variant::NIL) {
args.push_back(p2);
- if (p3.get_type()!=Variant::NIL) {
+ if (p3.get_type() != Variant::NIL) {
args.push_back(p3);
- if (p4.get_type()!=Variant::NIL) {
+ if (p4.get_type() != Variant::NIL) {
args.push_back(p4);
- if (p5.get_type()!=Variant::NIL) {
+ if (p5.get_type() != Variant::NIL) {
args.push_back(p5);
-
}
-
}
-
-
}
-
}
-
}
- bool error=false;
- String fmt = p_text.sprintf(args,&error);
+ bool error = false;
+ String fmt = p_text.sprintf(args, &error);
- ERR_FAIL_COND_V(error,String());
+ ERR_FAIL_COND_V(error, String());
return fmt;
-
}
diff --git a/core/variant.h b/core/variant.h
index f0c0d65852..c9f7ada3ac 100644
--- a/core/variant.h
+++ b/core/variant.h
@@ -33,27 +33,27 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-#include "rect3.h"
-#include "ustring.h"
-#include "vector3.h"
-#include "plane.h"
-#include "quat.h"
-#include "matrix3.h"
-#include "transform.h"
-#include "image.h"
+#include "array.h"
+#include "color.h"
+#include "dictionary.h"
#include "dvector.h"
-#include "path_db.h"
-#include "simple_type.h"
+#include "face3.h"
+#include "image.h"
+#include "io/ip_address.h"
+#include "math_2d.h"
+#include "matrix3.h"
#include "os/input_event.h"
#include "os/power.h"
-#include "color.h"
-#include "face3.h"
+#include "path_db.h"
+#include "plane.h"
+#include "quat.h"
+#include "rect3.h"
#include "ref_ptr.h"
-#include "math_2d.h"
#include "rid.h"
-#include "io/ip_address.h"
-#include "dictionary.h"
-#include "array.h"
+#include "simple_type.h"
+#include "transform.h"
+#include "ustring.h"
+#include "vector3.h"
class RefPtr;
class Object;
@@ -63,7 +63,6 @@ class Control; // helper
struct PropertyInfo;
struct MethodInfo;
-
typedef PoolVector<uint8_t> PoolByteArray;
typedef PoolVector<int> PoolIntArray;
typedef PoolVector<real_t> PoolRealArray;
@@ -74,7 +73,6 @@ typedef PoolVector<Color> PoolColorArray;
class Variant {
public:
-
enum Type {
NIL,
@@ -87,31 +85,31 @@ public:
// math types
- VECTOR2, // 5
+ VECTOR2, // 5
RECT2,
VECTOR3,
TRANSFORM2D,
PLANE,
- QUAT, // 10
+ QUAT, // 10
RECT3, //sorry naming convention fail :( not like it's used often
BASIS,
TRANSFORM,
// misc types
COLOR,
- IMAGE, // 15
+ IMAGE, // 15
NODE_PATH,
_RID,
OBJECT,
INPUT_EVENT,
- DICTIONARY, // 20
+ DICTIONARY, // 20
ARRAY,
// arrays
POOL_BYTE_ARRAY,
POOL_INT_ARRAY,
POOL_REAL_ARRAY,
- POOL_STRING_ARRAY, // 25
+ POOL_STRING_ARRAY, // 25
POOL_VECTOR2_ARRAY,
POOL_VECTOR3_ARRAY,
POOL_COLOR_ARRAY,
@@ -121,8 +119,6 @@ public:
};
private:
-
-
friend class _VariantCall;
// Variant takes 20 bytes when real_t is float, and 36 if double
// it only allocates extra memory for aabb/matrix.
@@ -135,9 +131,8 @@ private:
RefPtr ref;
};
-
- _FORCE_INLINE_ ObjData& _get_obj();
- _FORCE_INLINE_ const ObjData& _get_obj() const;
+ _FORCE_INLINE_ ObjData &_get_obj();
+ _FORCE_INLINE_ const ObjData &_get_obj() const;
union {
@@ -145,29 +140,26 @@ private:
int64_t _int;
double _real;
Transform2D *_transform2d;
- Rect3* _rect3;
+ Rect3 *_rect3;
Basis *_basis;
Transform *_transform;
RefPtr *_resource;
InputEvent *_input_event;
Image *_image;
void *_ptr; //generic pointer
- uint8_t _mem[sizeof(ObjData) > (sizeof(real_t)*4) ? sizeof(ObjData) : (sizeof(real_t)*4)];
+ uint8_t _mem[sizeof(ObjData) > (sizeof(real_t) * 4) ? sizeof(ObjData) : (sizeof(real_t) * 4)];
} _data;
-
- void reference(const Variant& p_variant);
+ void reference(const Variant &p_variant);
void clear();
-public:
+public:
_FORCE_INLINE_ Type get_type() const { return type; }
static String get_type_name(Variant::Type p_type);
static bool can_convert(Type p_type_from, Type p_type_to);
static bool can_convert_strict(Type p_type_from, Type p_type_to);
-
-
- template<class T>
+ template <class T>
static Type get_type_for() {
GetSimpleType<T> t;
@@ -176,10 +168,9 @@ public:
return r;
}
-
bool is_ref() const;
- _FORCE_INLINE_ bool is_num() const { return type==INT || type==REAL; };
- _FORCE_INLINE_ bool is_array() const { return type>=ARRAY; };
+ _FORCE_INLINE_ bool is_num() const { return type == INT || type == REAL; };
+ _FORCE_INLINE_ bool is_array() const { return type >= ARRAY; };
bool is_shared() const;
bool is_zero() const;
bool is_one() const;
@@ -199,7 +190,6 @@ public:
operator unsigned long() const;
#endif
-
operator CharType() const;
operator float() const;
operator double() const;
@@ -221,9 +211,9 @@ public:
operator RefPtr() const;
operator RID() const;
operator InputEvent() const;
- operator Object*() const;
- operator Node*() const;
- operator Control*() const;
+ operator Object *() const;
+ operator Node *() const;
+ operator Control *() const;
operator Dictionary() const;
operator Array() const;
@@ -237,7 +227,6 @@ public:
operator PoolVector<Plane>() const;
operator PoolVector<Face3>() const;
-
operator Vector<Variant>() const;
operator Vector<uint8_t>() const;
operator Vector<int>() const;
@@ -256,14 +245,13 @@ public:
operator IP_Address() const;
-
Variant(bool p_bool);
Variant(signed int p_int); // real one
Variant(unsigned int p_int);
#ifdef NEED_LONG_INT
Variant(signed long p_long); // real one
Variant(unsigned long p_long);
- //Variant(long unsigned int p_long);
+//Variant(long unsigned int p_long);
#endif
Variant(signed short p_short); // real one
Variant(unsigned short p_short);
@@ -273,54 +261,51 @@ public:
Variant(uint64_t p_char);
Variant(float p_float);
Variant(double p_double);
- Variant(const String& p_string);
- Variant(const StringName& p_string);
- Variant(const char * const p_cstring);
- Variant(const CharType * p_wstring);
- Variant(const Vector2& p_vector2);
- Variant(const Rect2& p_rect2);
- Variant(const Vector3& p_vector3);
- Variant(const Plane& p_plane);
- Variant(const Rect3& p_aabb);
- Variant(const Quat& p_quat);
- Variant(const Basis& p_transform);
- Variant(const Transform2D& p_transform);
- Variant(const Transform& p_transform);
- Variant(const Color& p_color);
- Variant(const Image& p_image);
- Variant(const NodePath& p_path);
- Variant(const RefPtr& p_resource);
- Variant(const RID& p_rid);
- Variant(const Object* p_object);
- Variant(const InputEvent& p_input_event);
- Variant(const Dictionary& p_dictionary);
-
- Variant(const Array& p_array);
- Variant(const PoolVector<Plane>& p_array); // helper
- Variant(const PoolVector<uint8_t>& p_raw_array);
- Variant(const PoolVector<int>& p_int_array);
- Variant(const PoolVector<real_t>& p_real_array);
- Variant(const PoolVector<String>& p_string_array);
- Variant(const PoolVector<Vector3>& p_vector3_array);
- Variant(const PoolVector<Color>& p_color_array);
- Variant(const PoolVector<Face3>& p_face_array);
-
-
- Variant(const Vector<Variant>& p_array);
- Variant(const Vector<uint8_t>& p_raw_array);
- Variant(const Vector<int>& p_int_array);
- Variant(const Vector<real_t>& p_real_array);
- Variant(const Vector<String>& p_string_array);
- Variant(const Vector<Vector3>& p_vector3_array);
- Variant(const Vector<Color>& p_color_array);
- Variant(const Vector<Plane>& p_array); // helper
- Variant(const Vector<RID>& p_array); // helper
- Variant(const Vector<Vector2>& p_array); // helper
- Variant(const PoolVector<Vector2>& p_array); // helper
-
- Variant(const IP_Address& p_address);
-
-
+ Variant(const String &p_string);
+ Variant(const StringName &p_string);
+ Variant(const char *const p_cstring);
+ Variant(const CharType *p_wstring);
+ Variant(const Vector2 &p_vector2);
+ Variant(const Rect2 &p_rect2);
+ Variant(const Vector3 &p_vector3);
+ Variant(const Plane &p_plane);
+ Variant(const Rect3 &p_aabb);
+ Variant(const Quat &p_quat);
+ Variant(const Basis &p_transform);
+ Variant(const Transform2D &p_transform);
+ Variant(const Transform &p_transform);
+ Variant(const Color &p_color);
+ Variant(const Image &p_image);
+ Variant(const NodePath &p_path);
+ Variant(const RefPtr &p_resource);
+ Variant(const RID &p_rid);
+ Variant(const Object *p_object);
+ Variant(const InputEvent &p_input_event);
+ Variant(const Dictionary &p_dictionary);
+
+ Variant(const Array &p_array);
+ Variant(const PoolVector<Plane> &p_array); // helper
+ Variant(const PoolVector<uint8_t> &p_raw_array);
+ Variant(const PoolVector<int> &p_int_array);
+ Variant(const PoolVector<real_t> &p_real_array);
+ Variant(const PoolVector<String> &p_string_array);
+ Variant(const PoolVector<Vector3> &p_vector3_array);
+ Variant(const PoolVector<Color> &p_color_array);
+ Variant(const PoolVector<Face3> &p_face_array);
+
+ Variant(const Vector<Variant> &p_array);
+ Variant(const Vector<uint8_t> &p_raw_array);
+ Variant(const Vector<int> &p_int_array);
+ Variant(const Vector<real_t> &p_real_array);
+ Variant(const Vector<String> &p_string_array);
+ Variant(const Vector<Vector3> &p_vector3_array);
+ Variant(const Vector<Color> &p_color_array);
+ Variant(const Vector<Plane> &p_array); // helper
+ Variant(const Vector<RID> &p_array); // helper
+ Variant(const Vector<Vector2> &p_array); // helper
+ Variant(const PoolVector<Vector2> &p_array); // helper
+
+ Variant(const IP_Address &p_address);
enum Operator {
@@ -358,20 +343,19 @@ public:
};
-
static String get_operator_name(Operator p_op);
- static void evaluate(const Operator& p_op,const Variant& p_a, const Variant& p_b,Variant &r_ret,bool &r_valid);
- static _FORCE_INLINE_ Variant evaluate(const Operator& p_op,const Variant& p_a, const Variant& p_b) {
+ static void evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b, Variant &r_ret, bool &r_valid);
+ static _FORCE_INLINE_ Variant evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b) {
- bool valid=true;
+ bool valid = true;
Variant res;
- evaluate(p_op,p_a,p_b,res,valid);
+ evaluate(p_op, p_a, p_b, res, valid);
return res;
}
void zero();
- static void blend(const Variant& a, const Variant& b, float c,Variant &r_dst);
- static void interpolate(const Variant& a, const Variant& b, float c,Variant &r_dst);
+ static void blend(const Variant &a, const Variant &b, float c, Variant &r_dst);
+ static void interpolate(const Variant &a, const Variant &b, float c, Variant &r_dst);
struct CallError {
enum Error {
@@ -387,95 +371,93 @@ public:
Type expected;
};
- void call_ptr(const StringName& p_method,const Variant** p_args,int p_argcount,Variant* r_ret,CallError &r_error);
- Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,CallError &r_error);
- Variant call(const StringName& p_method,const Variant& p_arg1=Variant(),const Variant& p_arg2=Variant(),const Variant& p_arg3=Variant(),const Variant& p_arg4=Variant(),const Variant& p_arg5=Variant());
+ void call_ptr(const StringName &p_method, const Variant **p_args, int p_argcount, Variant *r_ret, CallError &r_error);
+ Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, CallError &r_error);
+ Variant call(const StringName &p_method, const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant());
- static String get_call_error_text(Object* p_base, const StringName& p_method,const Variant** p_argptrs,int p_argcount,const Variant::CallError &ce);
+ static String get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce);
- static Variant construct(const Variant::Type,const Variant** p_args,int p_argcount,CallError &r_error,bool p_strict=true);
+ static Variant construct(const Variant::Type, const Variant **p_args, int p_argcount, CallError &r_error, bool p_strict = true);
void get_method_list(List<MethodInfo> *p_list) const;
- bool has_method(const StringName& p_method) const;
- static Vector<Variant::Type> get_method_argument_types(Variant::Type p_type,const StringName& p_method);
- static Vector<Variant> get_method_default_arguments(Variant::Type p_type,const StringName& p_method);
- static Variant::Type get_method_return_type(Variant::Type p_type,const StringName& p_method,bool* r_has_return=NULL);
- static Vector<StringName> get_method_argument_names(Variant::Type p_type,const StringName& p_method);
+ bool has_method(const StringName &p_method) const;
+ static Vector<Variant::Type> get_method_argument_types(Variant::Type p_type, const StringName &p_method);
+ static Vector<Variant> get_method_default_arguments(Variant::Type p_type, const StringName &p_method);
+ static Variant::Type get_method_return_type(Variant::Type p_type, const StringName &p_method, bool *r_has_return = NULL);
+ static Vector<StringName> get_method_argument_names(Variant::Type p_type, const StringName &p_method);
- void set_named(const StringName& p_index, const Variant& p_value, bool *r_valid=NULL);
- Variant get_named(const StringName& p_index, bool *r_valid=NULL) const;
+ void set_named(const StringName &p_index, const Variant &p_value, bool *r_valid = NULL);
+ Variant get_named(const StringName &p_index, bool *r_valid = NULL) const;
- void set(const Variant& p_index, const Variant& p_value, bool *r_valid=NULL);
- Variant get(const Variant& p_index, bool *r_valid=NULL) const;
- bool in(const Variant& p_index, bool *r_valid=NULL) const;
+ void set(const Variant &p_index, const Variant &p_value, bool *r_valid = NULL);
+ Variant get(const Variant &p_index, bool *r_valid = NULL) const;
+ bool in(const Variant &p_index, bool *r_valid = NULL) const;
- bool iter_init(Variant& r_iter,bool &r_valid) const;
- bool iter_next(Variant& r_iter,bool &r_valid) const;
- Variant iter_get(const Variant& r_iter,bool &r_valid) const;
+ bool iter_init(Variant &r_iter, bool &r_valid) const;
+ bool iter_next(Variant &r_iter, bool &r_valid) const;
+ Variant iter_get(const Variant &r_iter, bool &r_valid) const;
void get_property_list(List<PropertyInfo> *p_list) const;
//argsVariant call()
- bool operator==(const Variant& p_variant) const;
- bool operator!=(const Variant& p_variant) const;
- bool operator<(const Variant& p_variant) const;
+ bool operator==(const Variant &p_variant) const;
+ bool operator!=(const Variant &p_variant) const;
+ bool operator<(const Variant &p_variant) const;
uint32_t hash() const;
- bool hash_compare(const Variant& p_variant) const;
+ bool hash_compare(const Variant &p_variant) const;
bool booleanize(bool &valid) const;
- void static_assign(const Variant& p_variant);
+ void static_assign(const Variant &p_variant);
static void get_constructor_list(Variant::Type p_type, List<MethodInfo> *p_list);
static void get_numeric_constants_for_type(Variant::Type p_type, List<StringName> *p_constants);
- static bool has_numeric_constant(Variant::Type p_type, const StringName& p_value);
- static int get_numeric_constant_value(Variant::Type p_type, const StringName& p_value,bool *r_valid=NULL);
+ static bool has_numeric_constant(Variant::Type p_type, const StringName &p_value);
+ static int get_numeric_constant_value(Variant::Type p_type, const StringName &p_value, bool *r_valid = NULL);
- typedef String (*ObjectDeConstruct)(const Variant& p_object,void *ud);
- typedef void (*ObjectConstruct)(const String& p_text,void *ud,Variant& r_value);
+ typedef String (*ObjectDeConstruct)(const Variant &p_object, void *ud);
+ typedef void (*ObjectConstruct)(const String &p_text, void *ud, Variant &r_value);
String get_construct_string() const;
- static void construct_from_string(const String& p_string,Variant& r_value,ObjectConstruct p_obj_construct=NULL,void *p_construct_ud=NULL);
-
- void operator=(const Variant& p_variant); // only this is enough for all the other types
- Variant(const Variant& p_variant);
- _FORCE_INLINE_ Variant() { type=NIL; }
- _FORCE_INLINE_ ~Variant() { if (type!=Variant::NIL) clear(); }
+ static void construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct = NULL, void *p_construct_ud = NULL);
+ void operator=(const Variant &p_variant); // only this is enough for all the other types
+ Variant(const Variant &p_variant);
+ _FORCE_INLINE_ Variant() { type = NIL; }
+ _FORCE_INLINE_ ~Variant() {
+ if (type != Variant::NIL) clear();
+ }
};
//typedef Dictionary Dictionary; no
//typedef Array Array;
-
-
Vector<Variant> varray();
-Vector<Variant> varray(const Variant& p_arg1);
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2);
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3);
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4);
-Vector<Variant> varray(const Variant& p_arg1,const Variant& p_arg2,const Variant& p_arg3,const Variant& p_arg4,const Variant& p_arg5);
+Vector<Variant> varray(const Variant &p_arg1);
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2);
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3);
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4);
+Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5);
struct VariantHasher {
- static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); }
+ static _FORCE_INLINE_ uint32_t hash(const Variant &p_variant) { return p_variant.hash(); }
};
struct VariantComparator {
- static _FORCE_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { return p_lhs.hash_compare(p_rhs); }
+ static _FORCE_INLINE_ bool compare(const Variant &p_lhs, const Variant &p_rhs) { return p_lhs.hash_compare(p_rhs); }
};
-Variant::ObjData& Variant::_get_obj() {
+Variant::ObjData &Variant::_get_obj() {
- return *reinterpret_cast<ObjData*>(&_data._mem[0]);
+ return *reinterpret_cast<ObjData *>(&_data._mem[0]);
}
-const Variant::ObjData& Variant::_get_obj() const {
+const Variant::ObjData &Variant::_get_obj() const {
- return *reinterpret_cast<const ObjData*>(&_data._mem[0]);
+ return *reinterpret_cast<const ObjData *>(&_data._mem[0]);
}
-
-String vformat(const String& p_text, const Variant& p1=Variant(),const Variant& p2=Variant(),const Variant& p3=Variant(),const Variant& p4=Variant(),const Variant& p5=Variant());
+String vformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant());
#endif
diff --git a/core/variant_call.cpp b/core/variant_call.cpp
index 376e646fc2..758500a873 100644
--- a/core/variant_call.cpp
+++ b/core/variant_call.cpp
@@ -28,27 +28,22 @@
/*************************************************************************/
#include "variant.h"
+#include "core_string_names.h"
#include "object.h"
#include "os/os.h"
-#include "core_string_names.h"
#include "script_language.h"
-
-typedef void (*VariantFunc)(Variant& r_ret,Variant& p_self,const Variant** p_args);
-typedef void (*VariantConstructFunc)(Variant& r_ret,const Variant** p_args);
+typedef void (*VariantFunc)(Variant &r_ret, Variant &p_self, const Variant **p_args);
+typedef void (*VariantConstructFunc)(Variant &r_ret, const Variant **p_args);
VARIANT_ENUM_CAST(Image::CompressMode);
//VARIANT_ENUM_CAST(Image::Format);
-
struct _VariantCall {
+ static void Vector3_dot(Variant &r_ret, Variant &p_self, const Variant **p_args) {
-
-
- static void Vector3_dot(Variant& r_ret,Variant& p_self,const Variant** p_args) {
-
- r_ret=reinterpret_cast<Vector3*>(p_self._data._mem)->dot(*reinterpret_cast<const Vector3*>(p_args[0]->_data._mem));
+ r_ret = reinterpret_cast<Vector3 *>(p_self._data._mem)->dot(*reinterpret_cast<const Vector3 *>(p_args[0]->_data._mem));
}
struct FuncData {
@@ -64,107 +59,101 @@ struct _VariantCall {
#endif
VariantFunc func;
- _FORCE_INLINE_ bool verify_arguments(const Variant **p_args,Variant::CallError &r_error) {
+ _FORCE_INLINE_ bool verify_arguments(const Variant **p_args, Variant::CallError &r_error) {
- if (arg_count==0)
+ if (arg_count == 0)
return true;
Variant::Type *tptr = &arg_types[0];
- for(int i=0;i<arg_count;i++) {
+ for (int i = 0; i < arg_count; i++) {
- if (!tptr[i] || tptr[i]==p_args[i]->type)
+ if (!tptr[i] || tptr[i] == p_args[i]->type)
continue; // all good
- if (!Variant::can_convert(p_args[i]->type,tptr[i])) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=i;
- r_error.expected=tptr[i];
+ if (!Variant::can_convert(p_args[i]->type, tptr[i])) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = i;
+ r_error.expected = tptr[i];
return false;
-
}
}
return true;
}
- _FORCE_INLINE_ void call(Variant& r_ret,Variant& p_self,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+ _FORCE_INLINE_ void call(Variant &r_ret, Variant &p_self, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
#ifdef DEBUG_ENABLED
- if(p_argcount>arg_count) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=arg_count;
+ if (p_argcount > arg_count) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = arg_count;
return;
} else
#endif
- if (p_argcount<arg_count) {
+ if (p_argcount < arg_count) {
int def_argcount = default_args.size();
#ifdef DEBUG_ENABLED
- if (p_argcount<(arg_count-def_argcount)) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=arg_count-def_argcount;
+ if (p_argcount < (arg_count - def_argcount)) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = arg_count - def_argcount;
return;
}
#endif
- ERR_FAIL_COND(p_argcount>VARIANT_ARG_MAX);
+ ERR_FAIL_COND(p_argcount > VARIANT_ARG_MAX);
const Variant *newargs[VARIANT_ARG_MAX];
- for(int i=0;i<p_argcount;i++)
- newargs[i]=p_args[i];
- int defargcount=def_argcount;
- for(int i=p_argcount;i<arg_count;i++)
- newargs[i]=&default_args[defargcount-(i-p_argcount)-1]; //default arguments
+ for (int i = 0; i < p_argcount; i++)
+ newargs[i] = p_args[i];
+ int defargcount = def_argcount;
+ for (int i = p_argcount; i < arg_count; i++)
+ newargs[i] = &default_args[defargcount - (i - p_argcount) - 1]; //default arguments
#ifdef DEBUG_ENABLED
- if (!verify_arguments(newargs,r_error))
+ if (!verify_arguments(newargs, r_error))
return;
#endif
- func(r_ret,p_self,newargs);
+ func(r_ret, p_self, newargs);
} else {
#ifdef DEBUG_ENABLED
- if (!verify_arguments(p_args,r_error))
+ if (!verify_arguments(p_args, r_error))
return;
#endif
- func(r_ret,p_self,p_args);
+ func(r_ret, p_self, p_args);
}
-
}
-
};
-
struct TypeFunc {
- Map<StringName,FuncData> functions;
+ Map<StringName, FuncData> functions;
};
- static TypeFunc* type_funcs;
-
-
-
-
+ static TypeFunc *type_funcs;
struct Arg {
StringName name;
Variant::Type type;
- Arg() { type=Variant::NIL;}
- Arg(Variant::Type p_type,const StringName &p_name) { name=p_name; type=p_type; }
+ Arg() { type = Variant::NIL; }
+ Arg(Variant::Type p_type, const StringName &p_name) {
+ name = p_name;
+ type = p_type;
+ }
};
//void addfunc(Variant::Type p_type, const StringName& p_name,VariantFunc p_func);
- static void make_func_return_variant(Variant::Type p_type,const StringName& p_name) {
+ static void make_func_return_variant(Variant::Type p_type, const StringName &p_name) {
#ifdef DEBUG_ENABLED
- type_funcs[p_type].functions[p_name].returns=true;
+ type_funcs[p_type].functions[p_name].returns = true;
#endif
}
-
- static void addfunc(Variant::Type p_type, Variant::Type p_return,const StringName& p_name,VariantFunc p_func, const Vector<Variant>& p_defaultarg,const Arg& p_argtype1=Arg(),const Arg& p_argtype2=Arg(),const Arg& p_argtype3=Arg(),const Arg& p_argtype4=Arg(),const Arg& p_argtype5=Arg()) {
+ static void addfunc(Variant::Type p_type, Variant::Type p_return, const StringName &p_name, VariantFunc p_func, const Vector<Variant> &p_defaultarg, const Arg &p_argtype1 = Arg(), const Arg &p_argtype2 = Arg(), const Arg &p_argtype3 = Arg(), const Arg &p_argtype4 = Arg(), const Arg &p_argtype5 = Arg()) {
FuncData funcdata;
- funcdata.func=p_func;
- funcdata.default_args=p_defaultarg;
+ funcdata.func = p_func;
+ funcdata.default_args = p_defaultarg;
#ifdef DEBUG_ENABLED
- funcdata.return_type=p_return;
- funcdata.returns=p_return!=Variant::NIL;
+ funcdata.return_type = p_return;
+ funcdata.returns = p_return != Variant::NIL;
#endif
if (p_argtype1.name) {
@@ -210,106 +199,104 @@ struct _VariantCall {
} else
goto end;
- end:
-
- funcdata.arg_count=funcdata.arg_types.size();
- type_funcs[p_type].functions[p_name]=funcdata;
+ end:
+ funcdata.arg_count = funcdata.arg_types.size();
+ type_funcs[p_type].functions[p_name] = funcdata;
}
-#define VCALL_LOCALMEM0(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(); }
-#define VCALL_LOCALMEM0R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(); }
-#define VCALL_LOCALMEM1(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0]); }
-#define VCALL_LOCALMEM1R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0]); }
-#define VCALL_LOCALMEM2(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1]); }
-#define VCALL_LOCALMEM2R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1]); }
-#define VCALL_LOCALMEM3(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2]); }
-#define VCALL_LOCALMEM3R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2]); }
-#define VCALL_LOCALMEM4(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); }
-#define VCALL_LOCALMEM4R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); }
-#define VCALL_LOCALMEM5(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); }
-#define VCALL_LOCALMEM5R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._mem)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); }
-
+#define VCALL_LOCALMEM0(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(); }
+#define VCALL_LOCALMEM0R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(); }
+#define VCALL_LOCALMEM1(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0]); }
+#define VCALL_LOCALMEM1R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0]); }
+#define VCALL_LOCALMEM2(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1]); }
+#define VCALL_LOCALMEM2R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1]); }
+#define VCALL_LOCALMEM3(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2]); }
+#define VCALL_LOCALMEM3R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2]); }
+#define VCALL_LOCALMEM4(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); }
+#define VCALL_LOCALMEM4R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); }
+#define VCALL_LOCALMEM5(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); }
+#define VCALL_LOCALMEM5R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._mem)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); }
// built-in functions of localmem based types
- VCALL_LOCALMEM1R(String,casecmp_to);
- VCALL_LOCALMEM1R(String,nocasecmp_to);
- VCALL_LOCALMEM0R(String,length);
- VCALL_LOCALMEM2R(String,substr);
- VCALL_LOCALMEM2R(String,find);
- VCALL_LOCALMEM1R(String,find_last);
- VCALL_LOCALMEM2R(String,findn);
- VCALL_LOCALMEM2R(String,rfind);
- VCALL_LOCALMEM2R(String,rfindn);
- VCALL_LOCALMEM1R(String,match);
- VCALL_LOCALMEM1R(String,matchn);
- VCALL_LOCALMEM1R(String,begins_with);
- VCALL_LOCALMEM1R(String,ends_with);
- VCALL_LOCALMEM1R(String,is_subsequence_of);
- VCALL_LOCALMEM1R(String,is_subsequence_ofi);
- VCALL_LOCALMEM0R(String,bigrams);
- VCALL_LOCALMEM1R(String,similarity);
- VCALL_LOCALMEM2R(String,format);
- VCALL_LOCALMEM2R(String,replace);
- VCALL_LOCALMEM2R(String,replacen);
- VCALL_LOCALMEM2R(String,insert);
- VCALL_LOCALMEM0R(String,capitalize);
- VCALL_LOCALMEM2R(String,split);
- VCALL_LOCALMEM2R(String,split_floats);
- VCALL_LOCALMEM0R(String,to_upper);
- VCALL_LOCALMEM0R(String,to_lower);
- VCALL_LOCALMEM1R(String,left);
- VCALL_LOCALMEM1R(String,right);
- VCALL_LOCALMEM2R(String,strip_edges);
- VCALL_LOCALMEM0R(String,get_extension);
- VCALL_LOCALMEM0R(String,get_basename);
- VCALL_LOCALMEM1R(String,plus_file);
- VCALL_LOCALMEM1R(String,ord_at);
- VCALL_LOCALMEM2(String,erase);
- VCALL_LOCALMEM0R(String,hash);
- VCALL_LOCALMEM0R(String,md5_text);
- VCALL_LOCALMEM0R(String,sha256_text);
- VCALL_LOCALMEM0R(String,md5_buffer);
- VCALL_LOCALMEM0R(String,sha256_buffer);
- VCALL_LOCALMEM0R(String,empty);
- VCALL_LOCALMEM0R(String,is_abs_path);
- VCALL_LOCALMEM0R(String,is_rel_path);
- VCALL_LOCALMEM0R(String,get_base_dir);
- VCALL_LOCALMEM0R(String,get_file);
- VCALL_LOCALMEM0R(String,xml_escape);
- VCALL_LOCALMEM0R(String,xml_unescape);
- VCALL_LOCALMEM0R(String,c_escape);
- VCALL_LOCALMEM0R(String,c_unescape);
- VCALL_LOCALMEM0R(String,json_escape);
- VCALL_LOCALMEM0R(String,percent_encode);
- VCALL_LOCALMEM0R(String,percent_decode);
- VCALL_LOCALMEM0R(String,is_valid_identifier);
- VCALL_LOCALMEM0R(String,is_valid_integer);
- VCALL_LOCALMEM0R(String,is_valid_float);
- VCALL_LOCALMEM0R(String,is_valid_html_color);
- VCALL_LOCALMEM0R(String,is_valid_ip_address);
- VCALL_LOCALMEM0R(String,to_int);
- VCALL_LOCALMEM0R(String,to_float);
- VCALL_LOCALMEM0R(String,hex_to_int);
- VCALL_LOCALMEM1R(String,pad_decimals);
- VCALL_LOCALMEM1R(String,pad_zeros);
-
- static void _call_String_to_ascii(Variant& r_ret,Variant& p_self,const Variant** p_args) {
-
- String *s = reinterpret_cast<String*>(p_self._data._mem);
+ VCALL_LOCALMEM1R(String, casecmp_to);
+ VCALL_LOCALMEM1R(String, nocasecmp_to);
+ VCALL_LOCALMEM0R(String, length);
+ VCALL_LOCALMEM2R(String, substr);
+ VCALL_LOCALMEM2R(String, find);
+ VCALL_LOCALMEM1R(String, find_last);
+ VCALL_LOCALMEM2R(String, findn);
+ VCALL_LOCALMEM2R(String, rfind);
+ VCALL_LOCALMEM2R(String, rfindn);
+ VCALL_LOCALMEM1R(String, match);
+ VCALL_LOCALMEM1R(String, matchn);
+ VCALL_LOCALMEM1R(String, begins_with);
+ VCALL_LOCALMEM1R(String, ends_with);
+ VCALL_LOCALMEM1R(String, is_subsequence_of);
+ VCALL_LOCALMEM1R(String, is_subsequence_ofi);
+ VCALL_LOCALMEM0R(String, bigrams);
+ VCALL_LOCALMEM1R(String, similarity);
+ VCALL_LOCALMEM2R(String, format);
+ VCALL_LOCALMEM2R(String, replace);
+ VCALL_LOCALMEM2R(String, replacen);
+ VCALL_LOCALMEM2R(String, insert);
+ VCALL_LOCALMEM0R(String, capitalize);
+ VCALL_LOCALMEM2R(String, split);
+ VCALL_LOCALMEM2R(String, split_floats);
+ VCALL_LOCALMEM0R(String, to_upper);
+ VCALL_LOCALMEM0R(String, to_lower);
+ VCALL_LOCALMEM1R(String, left);
+ VCALL_LOCALMEM1R(String, right);
+ VCALL_LOCALMEM2R(String, strip_edges);
+ VCALL_LOCALMEM0R(String, get_extension);
+ VCALL_LOCALMEM0R(String, get_basename);
+ VCALL_LOCALMEM1R(String, plus_file);
+ VCALL_LOCALMEM1R(String, ord_at);
+ VCALL_LOCALMEM2(String, erase);
+ VCALL_LOCALMEM0R(String, hash);
+ VCALL_LOCALMEM0R(String, md5_text);
+ VCALL_LOCALMEM0R(String, sha256_text);
+ VCALL_LOCALMEM0R(String, md5_buffer);
+ VCALL_LOCALMEM0R(String, sha256_buffer);
+ VCALL_LOCALMEM0R(String, empty);
+ VCALL_LOCALMEM0R(String, is_abs_path);
+ VCALL_LOCALMEM0R(String, is_rel_path);
+ VCALL_LOCALMEM0R(String, get_base_dir);
+ VCALL_LOCALMEM0R(String, get_file);
+ VCALL_LOCALMEM0R(String, xml_escape);
+ VCALL_LOCALMEM0R(String, xml_unescape);
+ VCALL_LOCALMEM0R(String, c_escape);
+ VCALL_LOCALMEM0R(String, c_unescape);
+ VCALL_LOCALMEM0R(String, json_escape);
+ VCALL_LOCALMEM0R(String, percent_encode);
+ VCALL_LOCALMEM0R(String, percent_decode);
+ VCALL_LOCALMEM0R(String, is_valid_identifier);
+ VCALL_LOCALMEM0R(String, is_valid_integer);
+ VCALL_LOCALMEM0R(String, is_valid_float);
+ VCALL_LOCALMEM0R(String, is_valid_html_color);
+ VCALL_LOCALMEM0R(String, is_valid_ip_address);
+ VCALL_LOCALMEM0R(String, to_int);
+ VCALL_LOCALMEM0R(String, to_float);
+ VCALL_LOCALMEM0R(String, hex_to_int);
+ VCALL_LOCALMEM1R(String, pad_decimals);
+ VCALL_LOCALMEM1R(String, pad_zeros);
+
+ static void _call_String_to_ascii(Variant &r_ret, Variant &p_self, const Variant **p_args) {
+
+ String *s = reinterpret_cast<String *>(p_self._data._mem);
CharString charstr = s->ascii();
PoolByteArray retval;
@@ -322,9 +309,9 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
r_ret = retval;
}
- static void _call_String_to_utf8(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_String_to_utf8(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- String *s = reinterpret_cast<String*>(p_self._data._mem);
+ String *s = reinterpret_cast<String *>(p_self._data._mem);
CharString charstr = s->utf8();
PoolByteArray retval;
@@ -337,38 +324,37 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
r_ret = retval;
}
-
- VCALL_LOCALMEM0R(Vector2,normalized);
- VCALL_LOCALMEM0R(Vector2,length);
- VCALL_LOCALMEM0R(Vector2,length_squared);
- VCALL_LOCALMEM1R(Vector2,distance_to);
- VCALL_LOCALMEM1R(Vector2,distance_squared_to);
- VCALL_LOCALMEM1R(Vector2,angle_to);
- VCALL_LOCALMEM1R(Vector2,angle_to_point);
- VCALL_LOCALMEM2R(Vector2,linear_interpolate);
- VCALL_LOCALMEM4R(Vector2,cubic_interpolate);
- VCALL_LOCALMEM1R(Vector2,rotated);
- VCALL_LOCALMEM0R(Vector2,tangent);
- VCALL_LOCALMEM0R(Vector2,floor);
- VCALL_LOCALMEM1R(Vector2,snapped);
- VCALL_LOCALMEM0R(Vector2,aspect);
- VCALL_LOCALMEM1R(Vector2,dot);
- VCALL_LOCALMEM1R(Vector2,slide);
- VCALL_LOCALMEM1R(Vector2,reflect);
- VCALL_LOCALMEM0R(Vector2,angle);
+ VCALL_LOCALMEM0R(Vector2, normalized);
+ VCALL_LOCALMEM0R(Vector2, length);
+ VCALL_LOCALMEM0R(Vector2, length_squared);
+ VCALL_LOCALMEM1R(Vector2, distance_to);
+ VCALL_LOCALMEM1R(Vector2, distance_squared_to);
+ VCALL_LOCALMEM1R(Vector2, angle_to);
+ VCALL_LOCALMEM1R(Vector2, angle_to_point);
+ VCALL_LOCALMEM2R(Vector2, linear_interpolate);
+ VCALL_LOCALMEM4R(Vector2, cubic_interpolate);
+ VCALL_LOCALMEM1R(Vector2, rotated);
+ VCALL_LOCALMEM0R(Vector2, tangent);
+ VCALL_LOCALMEM0R(Vector2, floor);
+ VCALL_LOCALMEM1R(Vector2, snapped);
+ VCALL_LOCALMEM0R(Vector2, aspect);
+ VCALL_LOCALMEM1R(Vector2, dot);
+ VCALL_LOCALMEM1R(Vector2, slide);
+ VCALL_LOCALMEM1R(Vector2, reflect);
+ VCALL_LOCALMEM0R(Vector2, angle);
//VCALL_LOCALMEM1R(Vector2,cross);
- VCALL_LOCALMEM0R(Vector2,abs);
- VCALL_LOCALMEM1R(Vector2,clamped);
-
- VCALL_LOCALMEM0R(Rect2,get_area);
- VCALL_LOCALMEM1R(Rect2,intersects);
- VCALL_LOCALMEM1R(Rect2,encloses);
- VCALL_LOCALMEM0R(Rect2,has_no_area);
- VCALL_LOCALMEM1R(Rect2,clip);
- VCALL_LOCALMEM1R(Rect2,merge);
- VCALL_LOCALMEM1R(Rect2,has_point);
- VCALL_LOCALMEM1R(Rect2,grow);
- VCALL_LOCALMEM1R(Rect2,expand);
+ VCALL_LOCALMEM0R(Vector2, abs);
+ VCALL_LOCALMEM1R(Vector2, clamped);
+
+ VCALL_LOCALMEM0R(Rect2, get_area);
+ VCALL_LOCALMEM1R(Rect2, intersects);
+ VCALL_LOCALMEM1R(Rect2, encloses);
+ VCALL_LOCALMEM0R(Rect2, has_no_area);
+ VCALL_LOCALMEM1R(Rect2, clip);
+ VCALL_LOCALMEM1R(Rect2, merge);
+ VCALL_LOCALMEM1R(Rect2, has_point);
+ VCALL_LOCALMEM1R(Rect2, grow);
+ VCALL_LOCALMEM1R(Rect2, expand);
VCALL_LOCALMEM0R(Vector3, min_axis);
VCALL_LOCALMEM0R(Vector3, max_axis);
@@ -393,374 +379,367 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
VCALL_LOCALMEM1R(Vector3, slide);
VCALL_LOCALMEM1R(Vector3, reflect);
-
- VCALL_LOCALMEM0R(Plane,normalized);
- VCALL_LOCALMEM0R(Plane,center);
- VCALL_LOCALMEM0R(Plane,get_any_point);
- VCALL_LOCALMEM1R(Plane,is_point_over);
- VCALL_LOCALMEM1R(Plane,distance_to);
- VCALL_LOCALMEM2R(Plane,has_point);
- VCALL_LOCALMEM1R(Plane,project);
+ VCALL_LOCALMEM0R(Plane, normalized);
+ VCALL_LOCALMEM0R(Plane, center);
+ VCALL_LOCALMEM0R(Plane, get_any_point);
+ VCALL_LOCALMEM1R(Plane, is_point_over);
+ VCALL_LOCALMEM1R(Plane, distance_to);
+ VCALL_LOCALMEM2R(Plane, has_point);
+ VCALL_LOCALMEM1R(Plane, project);
//return vector3 if intersected, nil if not
- static void _call_Plane_intersect_3(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Plane_intersect_3(Variant &r_ret, Variant &p_self, const Variant **p_args) {
Vector3 result;
- if (reinterpret_cast<Plane*>(p_self._data._mem)->intersect_3(*p_args[0],*p_args[1],&result))
- r_ret=result;
+ if (reinterpret_cast<Plane *>(p_self._data._mem)->intersect_3(*p_args[0], *p_args[1], &result))
+ r_ret = result;
else
- r_ret=Variant();
+ r_ret = Variant();
}
- static void _call_Plane_intersects_ray(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Plane_intersects_ray(Variant &r_ret, Variant &p_self, const Variant **p_args) {
Vector3 result;
- if (reinterpret_cast<Plane*>(p_self._data._mem)->intersects_ray(*p_args[0],*p_args[1],&result))
- r_ret=result;
+ if (reinterpret_cast<Plane *>(p_self._data._mem)->intersects_ray(*p_args[0], *p_args[1], &result))
+ r_ret = result;
else
- r_ret=Variant();
+ r_ret = Variant();
}
- static void _call_Plane_intersects_segment(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Plane_intersects_segment(Variant &r_ret, Variant &p_self, const Variant **p_args) {
Vector3 result;
- if (reinterpret_cast<Plane*>(p_self._data._mem)->intersects_segment(*p_args[0],*p_args[1],&result))
- r_ret=result;
+ if (reinterpret_cast<Plane *>(p_self._data._mem)->intersects_segment(*p_args[0], *p_args[1], &result))
+ r_ret = result;
else
- r_ret=Variant();
+ r_ret = Variant();
}
- VCALL_LOCALMEM0R(Quat,length);
- VCALL_LOCALMEM0R(Quat,length_squared);
- VCALL_LOCALMEM0R(Quat,normalized);
- VCALL_LOCALMEM0R(Quat,inverse);
- VCALL_LOCALMEM1R(Quat,dot);
- VCALL_LOCALMEM1R(Quat,xform);
- VCALL_LOCALMEM2R(Quat,slerp);
- VCALL_LOCALMEM2R(Quat,slerpni);
- VCALL_LOCALMEM4R(Quat,cubic_slerp);
-
- VCALL_LOCALMEM0R(Color,to_32);
- VCALL_LOCALMEM0R(Color,to_ARGB32);
- VCALL_LOCALMEM0R(Color,gray);
- VCALL_LOCALMEM0R(Color,inverted);
- VCALL_LOCALMEM0R(Color,contrasted);
- VCALL_LOCALMEM2R(Color,linear_interpolate);
- VCALL_LOCALMEM1R(Color,blend);
- VCALL_LOCALMEM1R(Color,to_html);
-
- VCALL_LOCALMEM0R(RID,get_id);
-
- VCALL_LOCALMEM0R(NodePath,is_absolute);
- VCALL_LOCALMEM0R(NodePath,get_name_count);
- VCALL_LOCALMEM1R(NodePath,get_name);
- VCALL_LOCALMEM0R(NodePath,get_subname_count);
- VCALL_LOCALMEM1R(NodePath,get_subname);
- VCALL_LOCALMEM0R(NodePath,get_property);
- VCALL_LOCALMEM0R(NodePath,is_empty);
-
- VCALL_LOCALMEM0R(Dictionary,size);
- VCALL_LOCALMEM0R(Dictionary,empty);
- VCALL_LOCALMEM0(Dictionary,clear);
- VCALL_LOCALMEM1R(Dictionary,has);
- VCALL_LOCALMEM1R(Dictionary,has_all);
- VCALL_LOCALMEM1(Dictionary,erase);
- VCALL_LOCALMEM0R(Dictionary,hash);
- VCALL_LOCALMEM0R(Dictionary,keys);
- VCALL_LOCALMEM0R(Dictionary,values);
-
- VCALL_LOCALMEM2(Array,set);
- VCALL_LOCALMEM1R(Array,get);
- VCALL_LOCALMEM0R(Array,size);
- VCALL_LOCALMEM0R(Array,empty);
- VCALL_LOCALMEM0(Array,clear);
- VCALL_LOCALMEM0R(Array,hash);
- VCALL_LOCALMEM1(Array,push_back);
- VCALL_LOCALMEM1(Array,push_front);
- VCALL_LOCALMEM0R(Array,pop_back);
- VCALL_LOCALMEM0R(Array,pop_front);
- VCALL_LOCALMEM1(Array,append);
- VCALL_LOCALMEM1(Array,resize);
- VCALL_LOCALMEM2(Array,insert);
- VCALL_LOCALMEM1(Array,remove);
- VCALL_LOCALMEM0R(Array,front);
- VCALL_LOCALMEM0R(Array,back);
- VCALL_LOCALMEM2R(Array,find);
- VCALL_LOCALMEM2R(Array,rfind);
- VCALL_LOCALMEM1R(Array,find_last);
- VCALL_LOCALMEM1R(Array,count);
- VCALL_LOCALMEM1R(Array,has);
- VCALL_LOCALMEM1(Array,erase);
- VCALL_LOCALMEM0(Array,sort);
- VCALL_LOCALMEM2(Array,sort_custom);
- VCALL_LOCALMEM0(Array,invert);
-
-
- static void _call_PoolByteArray_get_string_from_ascii(Variant& r_ret,Variant& p_self,const Variant** p_args) {
-
- PoolByteArray* ba = reinterpret_cast<PoolByteArray*>(p_self._data._mem);
+ VCALL_LOCALMEM0R(Quat, length);
+ VCALL_LOCALMEM0R(Quat, length_squared);
+ VCALL_LOCALMEM0R(Quat, normalized);
+ VCALL_LOCALMEM0R(Quat, inverse);
+ VCALL_LOCALMEM1R(Quat, dot);
+ VCALL_LOCALMEM1R(Quat, xform);
+ VCALL_LOCALMEM2R(Quat, slerp);
+ VCALL_LOCALMEM2R(Quat, slerpni);
+ VCALL_LOCALMEM4R(Quat, cubic_slerp);
+
+ VCALL_LOCALMEM0R(Color, to_32);
+ VCALL_LOCALMEM0R(Color, to_ARGB32);
+ VCALL_LOCALMEM0R(Color, gray);
+ VCALL_LOCALMEM0R(Color, inverted);
+ VCALL_LOCALMEM0R(Color, contrasted);
+ VCALL_LOCALMEM2R(Color, linear_interpolate);
+ VCALL_LOCALMEM1R(Color, blend);
+ VCALL_LOCALMEM1R(Color, to_html);
+
+ VCALL_LOCALMEM0R(RID, get_id);
+
+ VCALL_LOCALMEM0R(NodePath, is_absolute);
+ VCALL_LOCALMEM0R(NodePath, get_name_count);
+ VCALL_LOCALMEM1R(NodePath, get_name);
+ VCALL_LOCALMEM0R(NodePath, get_subname_count);
+ VCALL_LOCALMEM1R(NodePath, get_subname);
+ VCALL_LOCALMEM0R(NodePath, get_property);
+ VCALL_LOCALMEM0R(NodePath, is_empty);
+
+ VCALL_LOCALMEM0R(Dictionary, size);
+ VCALL_LOCALMEM0R(Dictionary, empty);
+ VCALL_LOCALMEM0(Dictionary, clear);
+ VCALL_LOCALMEM1R(Dictionary, has);
+ VCALL_LOCALMEM1R(Dictionary, has_all);
+ VCALL_LOCALMEM1(Dictionary, erase);
+ VCALL_LOCALMEM0R(Dictionary, hash);
+ VCALL_LOCALMEM0R(Dictionary, keys);
+ VCALL_LOCALMEM0R(Dictionary, values);
+
+ VCALL_LOCALMEM2(Array, set);
+ VCALL_LOCALMEM1R(Array, get);
+ VCALL_LOCALMEM0R(Array, size);
+ VCALL_LOCALMEM0R(Array, empty);
+ VCALL_LOCALMEM0(Array, clear);
+ VCALL_LOCALMEM0R(Array, hash);
+ VCALL_LOCALMEM1(Array, push_back);
+ VCALL_LOCALMEM1(Array, push_front);
+ VCALL_LOCALMEM0R(Array, pop_back);
+ VCALL_LOCALMEM0R(Array, pop_front);
+ VCALL_LOCALMEM1(Array, append);
+ VCALL_LOCALMEM1(Array, resize);
+ VCALL_LOCALMEM2(Array, insert);
+ VCALL_LOCALMEM1(Array, remove);
+ VCALL_LOCALMEM0R(Array, front);
+ VCALL_LOCALMEM0R(Array, back);
+ VCALL_LOCALMEM2R(Array, find);
+ VCALL_LOCALMEM2R(Array, rfind);
+ VCALL_LOCALMEM1R(Array, find_last);
+ VCALL_LOCALMEM1R(Array, count);
+ VCALL_LOCALMEM1R(Array, has);
+ VCALL_LOCALMEM1(Array, erase);
+ VCALL_LOCALMEM0(Array, sort);
+ VCALL_LOCALMEM2(Array, sort_custom);
+ VCALL_LOCALMEM0(Array, invert);
+
+ static void _call_PoolByteArray_get_string_from_ascii(Variant &r_ret, Variant &p_self, const Variant **p_args) {
+
+ PoolByteArray *ba = reinterpret_cast<PoolByteArray *>(p_self._data._mem);
String s;
- if (ba->size()>=0) {
+ if (ba->size() >= 0) {
PoolByteArray::Read r = ba->read();
CharString cs;
- cs.resize(ba->size()+1);
- copymem(cs.ptr(),r.ptr(),ba->size());
- cs[ba->size()]=0;
+ cs.resize(ba->size() + 1);
+ copymem(cs.ptr(), r.ptr(), ba->size());
+ cs[ba->size()] = 0;
s = cs.get_data();
}
- r_ret=s;
+ r_ret = s;
}
- static void _call_PoolByteArray_get_string_from_utf8(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_PoolByteArray_get_string_from_utf8(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- PoolByteArray* ba = reinterpret_cast<PoolByteArray*>(p_self._data._mem);
+ PoolByteArray *ba = reinterpret_cast<PoolByteArray *>(p_self._data._mem);
String s;
- if (ba->size()>=0) {
+ if (ba->size() >= 0) {
PoolByteArray::Read r = ba->read();
- s.parse_utf8((const char*)r.ptr(),ba->size());
+ s.parse_utf8((const char *)r.ptr(), ba->size());
}
- r_ret=s;
+ r_ret = s;
}
- VCALL_LOCALMEM0R(PoolByteArray,size);
- VCALL_LOCALMEM2(PoolByteArray,set);
- VCALL_LOCALMEM1R(PoolByteArray,get);
- VCALL_LOCALMEM1(PoolByteArray,push_back);
- VCALL_LOCALMEM1(PoolByteArray,resize);
- VCALL_LOCALMEM2R(PoolByteArray,insert);
- VCALL_LOCALMEM1(PoolByteArray,remove);
- VCALL_LOCALMEM1(PoolByteArray,append);
- VCALL_LOCALMEM1(PoolByteArray,append_array);
- VCALL_LOCALMEM0(PoolByteArray,invert);
- VCALL_LOCALMEM2R(PoolByteArray,subarray);
-
- VCALL_LOCALMEM0R(PoolIntArray,size);
- VCALL_LOCALMEM2(PoolIntArray,set);
- VCALL_LOCALMEM1R(PoolIntArray,get);
- VCALL_LOCALMEM1(PoolIntArray,push_back);
- VCALL_LOCALMEM1(PoolIntArray,resize);
- VCALL_LOCALMEM2R(PoolIntArray,insert);
- VCALL_LOCALMEM1(PoolIntArray,remove);
- VCALL_LOCALMEM1(PoolIntArray,append);
- VCALL_LOCALMEM1(PoolIntArray,append_array);
- VCALL_LOCALMEM0(PoolIntArray,invert);
-
- VCALL_LOCALMEM0R(PoolRealArray,size);
- VCALL_LOCALMEM2(PoolRealArray,set);
- VCALL_LOCALMEM1R(PoolRealArray,get);
- VCALL_LOCALMEM1(PoolRealArray,push_back);
- VCALL_LOCALMEM1(PoolRealArray,resize);
- VCALL_LOCALMEM2R(PoolRealArray,insert);
- VCALL_LOCALMEM1(PoolRealArray,remove);
- VCALL_LOCALMEM1(PoolRealArray,append);
- VCALL_LOCALMEM1(PoolRealArray,append_array);
- VCALL_LOCALMEM0(PoolRealArray,invert);
-
- VCALL_LOCALMEM0R(PoolStringArray,size);
- VCALL_LOCALMEM2(PoolStringArray,set);
- VCALL_LOCALMEM1R(PoolStringArray,get);
- VCALL_LOCALMEM1(PoolStringArray,push_back);
- VCALL_LOCALMEM1(PoolStringArray,resize);
- VCALL_LOCALMEM2R(PoolStringArray,insert);
- VCALL_LOCALMEM1(PoolStringArray,remove);
- VCALL_LOCALMEM1(PoolStringArray,append);
- VCALL_LOCALMEM1(PoolStringArray,append_array);
- VCALL_LOCALMEM0(PoolStringArray,invert);
- VCALL_LOCALMEM1R(PoolStringArray,join);
-
- VCALL_LOCALMEM0R(PoolVector2Array,size);
- VCALL_LOCALMEM2(PoolVector2Array,set);
- VCALL_LOCALMEM1R(PoolVector2Array,get);
- VCALL_LOCALMEM1(PoolVector2Array,push_back);
- VCALL_LOCALMEM1(PoolVector2Array,resize);
- VCALL_LOCALMEM2R(PoolVector2Array,insert);
- VCALL_LOCALMEM1(PoolVector2Array,remove);
- VCALL_LOCALMEM1(PoolVector2Array,append);
- VCALL_LOCALMEM1(PoolVector2Array,append_array);
- VCALL_LOCALMEM0(PoolVector2Array,invert);
-
- VCALL_LOCALMEM0R(PoolVector3Array,size);
- VCALL_LOCALMEM2(PoolVector3Array,set);
- VCALL_LOCALMEM1R(PoolVector3Array,get);
- VCALL_LOCALMEM1(PoolVector3Array,push_back);
- VCALL_LOCALMEM1(PoolVector3Array,resize);
- VCALL_LOCALMEM2R(PoolVector3Array,insert);
- VCALL_LOCALMEM1(PoolVector3Array,remove);
- VCALL_LOCALMEM1(PoolVector3Array,append);
- VCALL_LOCALMEM1(PoolVector3Array,append_array);
- VCALL_LOCALMEM0(PoolVector3Array,invert);
-
- VCALL_LOCALMEM0R(PoolColorArray,size);
- VCALL_LOCALMEM2(PoolColorArray,set);
- VCALL_LOCALMEM1R(PoolColorArray,get);
- VCALL_LOCALMEM1(PoolColorArray,push_back);
- VCALL_LOCALMEM1(PoolColorArray,resize);
- VCALL_LOCALMEM2R(PoolColorArray,insert);
- VCALL_LOCALMEM1(PoolColorArray,remove);
- VCALL_LOCALMEM1(PoolColorArray,append);
- VCALL_LOCALMEM1(PoolColorArray,append_array);
- VCALL_LOCALMEM0(PoolColorArray,invert);
-
-#define VCALL_PTR0(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(); }
-#define VCALL_PTR0R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(); }
-#define VCALL_PTR1(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0]); }
-#define VCALL_PTR1R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0]); }
-#define VCALL_PTR2(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1]); }
-#define VCALL_PTR2R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1]); }
-#define VCALL_PTR3(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2]); }
-#define VCALL_PTR3R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2]); }
-#define VCALL_PTR4(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); }
-#define VCALL_PTR4R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3]); }
-#define VCALL_PTR5(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); }
-#define VCALL_PTR5R(m_type,m_method)\
-static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Variant** p_args) { r_ret=reinterpret_cast<m_type*>(p_self._data._ptr)->m_method(*p_args[0],*p_args[1],*p_args[2],*p_args[3],*p_args[4]); }
-
- VCALL_PTR0R(Image,get_format);
- VCALL_PTR0R(Image,get_width);
- VCALL_PTR0R(Image,get_height);
- VCALL_PTR0R(Image,empty);
- VCALL_PTR0R(Image,get_used_rect);
- VCALL_PTR1R(Image,load);
- VCALL_PTR1R(Image,save_png);
- VCALL_PTR1R(Image,get_rect);
- VCALL_PTR1R(Image,compressed);
- VCALL_PTR0R(Image,decompressed);
+ VCALL_LOCALMEM0R(PoolByteArray, size);
+ VCALL_LOCALMEM2(PoolByteArray, set);
+ VCALL_LOCALMEM1R(PoolByteArray, get);
+ VCALL_LOCALMEM1(PoolByteArray, push_back);
+ VCALL_LOCALMEM1(PoolByteArray, resize);
+ VCALL_LOCALMEM2R(PoolByteArray, insert);
+ VCALL_LOCALMEM1(PoolByteArray, remove);
+ VCALL_LOCALMEM1(PoolByteArray, append);
+ VCALL_LOCALMEM1(PoolByteArray, append_array);
+ VCALL_LOCALMEM0(PoolByteArray, invert);
+ VCALL_LOCALMEM2R(PoolByteArray, subarray);
+
+ VCALL_LOCALMEM0R(PoolIntArray, size);
+ VCALL_LOCALMEM2(PoolIntArray, set);
+ VCALL_LOCALMEM1R(PoolIntArray, get);
+ VCALL_LOCALMEM1(PoolIntArray, push_back);
+ VCALL_LOCALMEM1(PoolIntArray, resize);
+ VCALL_LOCALMEM2R(PoolIntArray, insert);
+ VCALL_LOCALMEM1(PoolIntArray, remove);
+ VCALL_LOCALMEM1(PoolIntArray, append);
+ VCALL_LOCALMEM1(PoolIntArray, append_array);
+ VCALL_LOCALMEM0(PoolIntArray, invert);
+
+ VCALL_LOCALMEM0R(PoolRealArray, size);
+ VCALL_LOCALMEM2(PoolRealArray, set);
+ VCALL_LOCALMEM1R(PoolRealArray, get);
+ VCALL_LOCALMEM1(PoolRealArray, push_back);
+ VCALL_LOCALMEM1(PoolRealArray, resize);
+ VCALL_LOCALMEM2R(PoolRealArray, insert);
+ VCALL_LOCALMEM1(PoolRealArray, remove);
+ VCALL_LOCALMEM1(PoolRealArray, append);
+ VCALL_LOCALMEM1(PoolRealArray, append_array);
+ VCALL_LOCALMEM0(PoolRealArray, invert);
+
+ VCALL_LOCALMEM0R(PoolStringArray, size);
+ VCALL_LOCALMEM2(PoolStringArray, set);
+ VCALL_LOCALMEM1R(PoolStringArray, get);
+ VCALL_LOCALMEM1(PoolStringArray, push_back);
+ VCALL_LOCALMEM1(PoolStringArray, resize);
+ VCALL_LOCALMEM2R(PoolStringArray, insert);
+ VCALL_LOCALMEM1(PoolStringArray, remove);
+ VCALL_LOCALMEM1(PoolStringArray, append);
+ VCALL_LOCALMEM1(PoolStringArray, append_array);
+ VCALL_LOCALMEM0(PoolStringArray, invert);
+ VCALL_LOCALMEM1R(PoolStringArray, join);
+
+ VCALL_LOCALMEM0R(PoolVector2Array, size);
+ VCALL_LOCALMEM2(PoolVector2Array, set);
+ VCALL_LOCALMEM1R(PoolVector2Array, get);
+ VCALL_LOCALMEM1(PoolVector2Array, push_back);
+ VCALL_LOCALMEM1(PoolVector2Array, resize);
+ VCALL_LOCALMEM2R(PoolVector2Array, insert);
+ VCALL_LOCALMEM1(PoolVector2Array, remove);
+ VCALL_LOCALMEM1(PoolVector2Array, append);
+ VCALL_LOCALMEM1(PoolVector2Array, append_array);
+ VCALL_LOCALMEM0(PoolVector2Array, invert);
+
+ VCALL_LOCALMEM0R(PoolVector3Array, size);
+ VCALL_LOCALMEM2(PoolVector3Array, set);
+ VCALL_LOCALMEM1R(PoolVector3Array, get);
+ VCALL_LOCALMEM1(PoolVector3Array, push_back);
+ VCALL_LOCALMEM1(PoolVector3Array, resize);
+ VCALL_LOCALMEM2R(PoolVector3Array, insert);
+ VCALL_LOCALMEM1(PoolVector3Array, remove);
+ VCALL_LOCALMEM1(PoolVector3Array, append);
+ VCALL_LOCALMEM1(PoolVector3Array, append_array);
+ VCALL_LOCALMEM0(PoolVector3Array, invert);
+
+ VCALL_LOCALMEM0R(PoolColorArray, size);
+ VCALL_LOCALMEM2(PoolColorArray, set);
+ VCALL_LOCALMEM1R(PoolColorArray, get);
+ VCALL_LOCALMEM1(PoolColorArray, push_back);
+ VCALL_LOCALMEM1(PoolColorArray, resize);
+ VCALL_LOCALMEM2R(PoolColorArray, insert);
+ VCALL_LOCALMEM1(PoolColorArray, remove);
+ VCALL_LOCALMEM1(PoolColorArray, append);
+ VCALL_LOCALMEM1(PoolColorArray, append_array);
+ VCALL_LOCALMEM0(PoolColorArray, invert);
+
+#define VCALL_PTR0(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(); }
+#define VCALL_PTR0R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(); }
+#define VCALL_PTR1(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0]); }
+#define VCALL_PTR1R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0]); }
+#define VCALL_PTR2(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1]); }
+#define VCALL_PTR2R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1]); }
+#define VCALL_PTR3(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2]); }
+#define VCALL_PTR3R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2]); }
+#define VCALL_PTR4(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); }
+#define VCALL_PTR4R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3]); }
+#define VCALL_PTR5(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); }
+#define VCALL_PTR5R(m_type, m_method) \
+ static void _call_##m_type##_##m_method(Variant &r_ret, Variant &p_self, const Variant **p_args) { r_ret = reinterpret_cast<m_type *>(p_self._data._ptr)->m_method(*p_args[0], *p_args[1], *p_args[2], *p_args[3], *p_args[4]); }
+
+ VCALL_PTR0R(Image, get_format);
+ VCALL_PTR0R(Image, get_width);
+ VCALL_PTR0R(Image, get_height);
+ VCALL_PTR0R(Image, empty);
+ VCALL_PTR0R(Image, get_used_rect);
+ VCALL_PTR1R(Image, load);
+ VCALL_PTR1R(Image, save_png);
+ VCALL_PTR1R(Image, get_rect);
+ VCALL_PTR1R(Image, compressed);
+ VCALL_PTR0R(Image, decompressed);
VCALL_PTR3R(Image, resized);
VCALL_PTR0R(Image, get_data);
VCALL_PTR3(Image, blit_rect);
VCALL_PTR1R(Image, converted);
VCALL_PTR0(Image, fix_alpha_edges);
- VCALL_PTR0R( Rect3, get_area );
- VCALL_PTR0R( Rect3, has_no_area );
- VCALL_PTR0R( Rect3, has_no_surface );
- VCALL_PTR1R( Rect3, intersects );
- VCALL_PTR1R( Rect3, encloses );
- VCALL_PTR1R( Rect3, merge );
- VCALL_PTR1R( Rect3, intersection );
- VCALL_PTR1R( Rect3, intersects_plane );
- VCALL_PTR2R( Rect3, intersects_segment );
- VCALL_PTR1R( Rect3, has_point );
- VCALL_PTR1R( Rect3, get_support );
- VCALL_PTR0R( Rect3, get_longest_axis );
- VCALL_PTR0R( Rect3, get_longest_axis_index );
- VCALL_PTR0R( Rect3, get_longest_axis_size );
- VCALL_PTR0R( Rect3, get_shortest_axis );
- VCALL_PTR0R( Rect3, get_shortest_axis_index );
- VCALL_PTR0R( Rect3, get_shortest_axis_size );
- VCALL_PTR1R( Rect3, expand );
- VCALL_PTR1R( Rect3, grow );
- VCALL_PTR1R( Rect3, get_endpoint );
-
- VCALL_PTR0R( Transform2D, inverse );
- VCALL_PTR0R( Transform2D, affine_inverse );
- VCALL_PTR0R( Transform2D, get_rotation );
- VCALL_PTR0R( Transform2D, get_origin );
- VCALL_PTR0R( Transform2D, get_scale );
- VCALL_PTR0R( Transform2D, orthonormalized );
- VCALL_PTR1R( Transform2D, rotated );
- VCALL_PTR1R( Transform2D, scaled );
- VCALL_PTR1R( Transform2D, translated );
- VCALL_PTR2R( Transform2D, interpolate_with );
-
- static void _call_Transform2D_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) {
-
- switch(p_args[0]->type) {
-
- case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform( p_args[0]->operator Vector2()); return;
- case Variant::RECT2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform( p_args[0]->operator Rect2()); return;
- default: r_ret=Variant();
+ VCALL_PTR0R(Rect3, get_area);
+ VCALL_PTR0R(Rect3, has_no_area);
+ VCALL_PTR0R(Rect3, has_no_surface);
+ VCALL_PTR1R(Rect3, intersects);
+ VCALL_PTR1R(Rect3, encloses);
+ VCALL_PTR1R(Rect3, merge);
+ VCALL_PTR1R(Rect3, intersection);
+ VCALL_PTR1R(Rect3, intersects_plane);
+ VCALL_PTR2R(Rect3, intersects_segment);
+ VCALL_PTR1R(Rect3, has_point);
+ VCALL_PTR1R(Rect3, get_support);
+ VCALL_PTR0R(Rect3, get_longest_axis);
+ VCALL_PTR0R(Rect3, get_longest_axis_index);
+ VCALL_PTR0R(Rect3, get_longest_axis_size);
+ VCALL_PTR0R(Rect3, get_shortest_axis);
+ VCALL_PTR0R(Rect3, get_shortest_axis_index);
+ VCALL_PTR0R(Rect3, get_shortest_axis_size);
+ VCALL_PTR1R(Rect3, expand);
+ VCALL_PTR1R(Rect3, grow);
+ VCALL_PTR1R(Rect3, get_endpoint);
+
+ VCALL_PTR0R(Transform2D, inverse);
+ VCALL_PTR0R(Transform2D, affine_inverse);
+ VCALL_PTR0R(Transform2D, get_rotation);
+ VCALL_PTR0R(Transform2D, get_origin);
+ VCALL_PTR0R(Transform2D, get_scale);
+ VCALL_PTR0R(Transform2D, orthonormalized);
+ VCALL_PTR1R(Transform2D, rotated);
+ VCALL_PTR1R(Transform2D, scaled);
+ VCALL_PTR1R(Transform2D, translated);
+ VCALL_PTR2R(Transform2D, interpolate_with);
+
+ static void _call_Transform2D_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) {
+
+ switch (p_args[0]->type) {
+
+ case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform(p_args[0]->operator Vector2()); return;
+ case Variant::RECT2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform(p_args[0]->operator Rect2()); return;
+ default: r_ret = Variant();
}
-
}
- static void _call_Transform2D_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Transform2D_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- switch(p_args[0]->type) {
+ switch (p_args[0]->type) {
- case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Vector2()); return;
- case Variant::RECT2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Rect2()); return;
- default: r_ret=Variant();
+ case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Vector2()); return;
+ case Variant::RECT2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Rect2()); return;
+ default: r_ret = Variant();
}
}
- static void _call_Transform2D_basis_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Transform2D_basis_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- switch(p_args[0]->type) {
+ switch (p_args[0]->type) {
- case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->basis_xform( p_args[0]->operator Vector2()); return;
- default: r_ret=Variant();
+ case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->basis_xform(p_args[0]->operator Vector2()); return;
+ default: r_ret = Variant();
}
-
}
- static void _call_Transform2D_basis_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Transform2D_basis_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- switch(p_args[0]->type) {
+ switch (p_args[0]->type) {
- case Variant::VECTOR2: r_ret=reinterpret_cast<Transform2D*>(p_self._data._ptr)->basis_xform_inv( p_args[0]->operator Vector2()); return;
- default: r_ret=Variant();
+ case Variant::VECTOR2: r_ret = reinterpret_cast<Transform2D *>(p_self._data._ptr)->basis_xform_inv(p_args[0]->operator Vector2()); return;
+ default: r_ret = Variant();
}
}
-
- VCALL_PTR0R( Basis, inverse );
- VCALL_PTR0R( Basis, transposed );
- VCALL_PTR0R( Basis, determinant );
- VCALL_PTR2R( Basis, rotated );
- VCALL_PTR1R( Basis, scaled );
- VCALL_PTR0R( Basis, get_scale );
- VCALL_PTR0R( Basis, get_euler );
- VCALL_PTR1R( Basis, tdotx );
- VCALL_PTR1R( Basis, tdoty );
- VCALL_PTR1R( Basis, tdotz );
- VCALL_PTR1R( Basis, xform );
- VCALL_PTR1R( Basis, xform_inv );
- VCALL_PTR0R( Basis, get_orthogonal_index );
- VCALL_PTR0R( Basis, orthonormalized );
-
-
- VCALL_PTR0R( Transform, inverse );
- VCALL_PTR0R( Transform, affine_inverse );
- VCALL_PTR2R( Transform, rotated );
- VCALL_PTR1R( Transform, scaled );
- VCALL_PTR1R( Transform, translated );
- VCALL_PTR0R( Transform, orthonormalized );
- VCALL_PTR2R( Transform, looking_at );
-
- static void _call_Transform_xform(Variant& r_ret,Variant& p_self,const Variant** p_args) {
-
- switch(p_args[0]->type) {
-
- case Variant::VECTOR3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Vector3()); return;
- case Variant::PLANE: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Plane()); return;
- case Variant::RECT3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform( p_args[0]->operator Rect3()); return;
- default: r_ret=Variant();
+ VCALL_PTR0R(Basis, inverse);
+ VCALL_PTR0R(Basis, transposed);
+ VCALL_PTR0R(Basis, determinant);
+ VCALL_PTR2R(Basis, rotated);
+ VCALL_PTR1R(Basis, scaled);
+ VCALL_PTR0R(Basis, get_scale);
+ VCALL_PTR0R(Basis, get_euler);
+ VCALL_PTR1R(Basis, tdotx);
+ VCALL_PTR1R(Basis, tdoty);
+ VCALL_PTR1R(Basis, tdotz);
+ VCALL_PTR1R(Basis, xform);
+ VCALL_PTR1R(Basis, xform_inv);
+ VCALL_PTR0R(Basis, get_orthogonal_index);
+ VCALL_PTR0R(Basis, orthonormalized);
+
+ VCALL_PTR0R(Transform, inverse);
+ VCALL_PTR0R(Transform, affine_inverse);
+ VCALL_PTR2R(Transform, rotated);
+ VCALL_PTR1R(Transform, scaled);
+ VCALL_PTR1R(Transform, translated);
+ VCALL_PTR0R(Transform, orthonormalized);
+ VCALL_PTR2R(Transform, looking_at);
+
+ static void _call_Transform_xform(Variant &r_ret, Variant &p_self, const Variant **p_args) {
+
+ switch (p_args[0]->type) {
+
+ case Variant::VECTOR3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Vector3()); return;
+ case Variant::PLANE: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Plane()); return;
+ case Variant::RECT3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform(p_args[0]->operator Rect3()); return;
+ default: r_ret = Variant();
}
-
}
- static void _call_Transform_xform_inv(Variant& r_ret,Variant& p_self,const Variant** p_args) {
+ static void _call_Transform_xform_inv(Variant &r_ret, Variant &p_self, const Variant **p_args) {
- switch(p_args[0]->type) {
+ switch (p_args[0]->type) {
- case Variant::VECTOR3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Vector3()); return;
- case Variant::PLANE: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Plane()); return;
- case Variant::RECT3: r_ret=reinterpret_cast<Transform*>(p_self._data._ptr)->xform_inv( p_args[0]->operator Rect3()); return;
- default: r_ret=Variant();
+ case Variant::VECTOR3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Vector3()); return;
+ case Variant::PLANE: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Plane()); return;
+ case Variant::RECT3: r_ret = reinterpret_cast<Transform *>(p_self._data._ptr)->xform_inv(p_args[0]->operator Rect3()); return;
+ default: r_ret = Variant();
}
}
-/*
+ /*
VCALL_PTR0( Transform, invert );
VCALL_PTR0( Transform, affine_invert );
VCALL_PTR2( Transform, rotate );
@@ -768,21 +747,19 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
VCALL_PTR1( Transform, translate );
VCALL_PTR0( Transform, orthonormalize ); */
- VCALL_PTR0R( InputEvent, is_pressed );
- VCALL_PTR1R( InputEvent, is_action );
- VCALL_PTR1R( InputEvent, is_action_pressed );
- VCALL_PTR1R( InputEvent, is_action_released );
- VCALL_PTR0R( InputEvent, is_echo );
- VCALL_PTR2( InputEvent, set_as_action );
+ VCALL_PTR0R(InputEvent, is_pressed);
+ VCALL_PTR1R(InputEvent, is_action);
+ VCALL_PTR1R(InputEvent, is_action_pressed);
+ VCALL_PTR1R(InputEvent, is_action_released);
+ VCALL_PTR0R(InputEvent, is_echo);
+ VCALL_PTR2(InputEvent, set_as_action);
struct ConstructData {
-
int arg_count;
Vector<Variant::Type> arg_types;
Vector<String> arg_names;
VariantConstructFunc func;
-
};
struct ConstructFunc {
@@ -790,180 +767,179 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
List<ConstructData> constructors;
};
- static ConstructFunc* construct_funcs;
+ static ConstructFunc *construct_funcs;
- static void Vector2_init1(Variant& r_ret,const Variant** p_args) {
+ static void Vector2_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Vector2(*p_args[0],*p_args[1]);
+ r_ret = Vector2(*p_args[0], *p_args[1]);
}
- static void Rect2_init1(Variant& r_ret,const Variant** p_args) {
+ static void Rect2_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Rect2(*p_args[0],*p_args[1]);
+ r_ret = Rect2(*p_args[0], *p_args[1]);
}
- static void Rect2_init2(Variant& r_ret,const Variant** p_args) {
+ static void Rect2_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Rect2(*p_args[0],*p_args[1],*p_args[2],*p_args[3]);
+ r_ret = Rect2(*p_args[0], *p_args[1], *p_args[2], *p_args[3]);
}
- static void Transform2D_init2(Variant& r_ret,const Variant** p_args) {
+ static void Transform2D_init2(Variant &r_ret, const Variant **p_args) {
Transform2D m(*p_args[0], *p_args[1]);
- r_ret=m;
+ r_ret = m;
}
- static void Transform2D_init3(Variant& r_ret,const Variant** p_args) {
+ static void Transform2D_init3(Variant &r_ret, const Variant **p_args) {
Transform2D m;
- m[0]=*p_args[0];
- m[1]=*p_args[1];
- m[2]=*p_args[2];
- r_ret=m;
+ m[0] = *p_args[0];
+ m[1] = *p_args[1];
+ m[2] = *p_args[2];
+ r_ret = m;
}
- static void Vector3_init1(Variant& r_ret,const Variant** p_args) {
+ static void Vector3_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Vector3(*p_args[0],*p_args[1],*p_args[2]);
+ r_ret = Vector3(*p_args[0], *p_args[1], *p_args[2]);
}
- static void Plane_init1(Variant& r_ret,const Variant** p_args) {
+ static void Plane_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Plane(*p_args[0],*p_args[1],*p_args[2],*p_args[3]);
+ r_ret = Plane(*p_args[0], *p_args[1], *p_args[2], *p_args[3]);
}
- static void Plane_init2(Variant& r_ret,const Variant** p_args) {
+ static void Plane_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Plane(*p_args[0],*p_args[1],*p_args[2]);
+ r_ret = Plane(*p_args[0], *p_args[1], *p_args[2]);
}
- static void Plane_init3(Variant& r_ret,const Variant** p_args) {
+ static void Plane_init3(Variant &r_ret, const Variant **p_args) {
- r_ret=Plane(p_args[0]->operator Vector3(),p_args[1]->operator real_t());
+ r_ret = Plane(p_args[0]->operator Vector3(), p_args[1]->operator real_t());
}
- static void Plane_init4(Variant& r_ret,const Variant** p_args) {
+ static void Plane_init4(Variant &r_ret, const Variant **p_args) {
- r_ret=Plane(p_args[0]->operator Vector3(),p_args[1]->operator Vector3());
+ r_ret = Plane(p_args[0]->operator Vector3(), p_args[1]->operator Vector3());
}
- static void Quat_init1(Variant& r_ret,const Variant** p_args) {
+ static void Quat_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Quat(*p_args[0],*p_args[1],*p_args[2],*p_args[3]);
+ r_ret = Quat(*p_args[0], *p_args[1], *p_args[2], *p_args[3]);
}
- static void Quat_init2(Variant& r_ret,const Variant** p_args) {
+ static void Quat_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Quat(((Vector3)(*p_args[0])),((float)(*p_args[1])));
- }
+ r_ret = Quat(((Vector3)(*p_args[0])), ((float)(*p_args[1])));
+ }
- static void Color_init1(Variant& r_ret,const Variant** p_args) {
+ static void Color_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Color(*p_args[0],*p_args[1],*p_args[2],*p_args[3]);
+ r_ret = Color(*p_args[0], *p_args[1], *p_args[2], *p_args[3]);
}
- static void Color_init2(Variant& r_ret,const Variant** p_args) {
+ static void Color_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Color(*p_args[0],*p_args[1],*p_args[2]);
+ r_ret = Color(*p_args[0], *p_args[1], *p_args[2]);
}
- static void Color_init3(Variant& r_ret,const Variant** p_args) {
+ static void Color_init3(Variant &r_ret, const Variant **p_args) {
- r_ret=Color::html(*p_args[0]);
+ r_ret = Color::html(*p_args[0]);
}
- static void Color_init4(Variant& r_ret,const Variant** p_args) {
+ static void Color_init4(Variant &r_ret, const Variant **p_args) {
- r_ret=Color::hex(*p_args[0]);
+ r_ret = Color::hex(*p_args[0]);
}
- static void Rect3_init1(Variant& r_ret,const Variant** p_args) {
+ static void Rect3_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Rect3(*p_args[0],*p_args[1]);
+ r_ret = Rect3(*p_args[0], *p_args[1]);
}
- static void Basis_init1(Variant& r_ret,const Variant** p_args) {
+ static void Basis_init1(Variant &r_ret, const Variant **p_args) {
Basis m;
- m.set_axis(0,*p_args[0]);
- m.set_axis(1,*p_args[1]);
- m.set_axis(2,*p_args[2]);
- r_ret=m;
+ m.set_axis(0, *p_args[0]);
+ m.set_axis(1, *p_args[1]);
+ m.set_axis(2, *p_args[2]);
+ r_ret = m;
}
- static void Basis_init2(Variant& r_ret,const Variant** p_args) {
+ static void Basis_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Basis(p_args[0]->operator Vector3(),p_args[1]->operator real_t());
+ r_ret = Basis(p_args[0]->operator Vector3(), p_args[1]->operator real_t());
}
- static void Transform_init1(Variant& r_ret,const Variant** p_args) {
+ static void Transform_init1(Variant &r_ret, const Variant **p_args) {
Transform t;
- t.basis.set_axis(0,*p_args[0]);
- t.basis.set_axis(1,*p_args[1]);
- t.basis.set_axis(2,*p_args[2]);
- t.origin=*p_args[3];
- r_ret=t;
+ t.basis.set_axis(0, *p_args[0]);
+ t.basis.set_axis(1, *p_args[1]);
+ t.basis.set_axis(2, *p_args[2]);
+ t.origin = *p_args[3];
+ r_ret = t;
}
- static void Transform_init2(Variant& r_ret,const Variant** p_args) {
+ static void Transform_init2(Variant &r_ret, const Variant **p_args) {
- r_ret=Transform(p_args[0]->operator Basis(),p_args[1]->operator Vector3());
+ r_ret = Transform(p_args[0]->operator Basis(), p_args[1]->operator Vector3());
}
- static void Image_init1(Variant& r_ret, const Variant** p_args) {
+ static void Image_init1(Variant &r_ret, const Variant **p_args) {
- r_ret=Image(*p_args[0],*p_args[1],*p_args[2],Image::Format(p_args[3]->operator int()));
+ r_ret = Image(*p_args[0], *p_args[1], *p_args[2], Image::Format(p_args[3]->operator int()));
}
- static void add_constructor(VariantConstructFunc p_func,const Variant::Type p_type,
- const String& p_name1="", const Variant::Type p_type1=Variant::NIL,
- const String& p_name2="", const Variant::Type p_type2=Variant::NIL,
- const String& p_name3="", const Variant::Type p_type3=Variant::NIL,
- const String& p_name4="", const Variant::Type p_type4=Variant::NIL ) {
+ static void add_constructor(VariantConstructFunc p_func, const Variant::Type p_type,
+ const String &p_name1 = "", const Variant::Type p_type1 = Variant::NIL,
+ const String &p_name2 = "", const Variant::Type p_type2 = Variant::NIL,
+ const String &p_name3 = "", const Variant::Type p_type3 = Variant::NIL,
+ const String &p_name4 = "", const Variant::Type p_type4 = Variant::NIL) {
ConstructData cd;
- cd.func=p_func;
- cd.arg_count=0;
+ cd.func = p_func;
+ cd.arg_count = 0;
- if (p_name1=="")
+ if (p_name1 == "")
goto end;
cd.arg_count++;
cd.arg_names.push_back(p_name1);
cd.arg_types.push_back(p_type1);
- if (p_name2=="")
+ if (p_name2 == "")
goto end;
cd.arg_count++;
cd.arg_names.push_back(p_name2);
cd.arg_types.push_back(p_type2);
- if (p_name3=="")
+ if (p_name3 == "")
goto end;
cd.arg_count++;
cd.arg_names.push_back(p_name3);
cd.arg_types.push_back(p_type3);
- if (p_name4=="")
+ if (p_name4 == "")
goto end;
cd.arg_count++;
cd.arg_names.push_back(p_name4);
cd.arg_types.push_back(p_type4);
- end:
+ end:
construct_funcs[p_type].constructors.push_back(cd);
}
-
struct ConstantData {
- Map<StringName,int> value;
+ Map<StringName, int> value;
#ifdef DEBUG_ENABLED
List<StringName> value_ordered;
#endif
};
- static ConstantData* constant_data;
+ static ConstantData *constant_data;
static void add_constant(int p_type, StringName p_constant_name, int p_constant_value) {
@@ -971,198 +947,213 @@ static void _call_##m_type##_##m_method(Variant& r_ret,Variant& p_self,const Var
#ifdef DEBUG_ENABLED
constant_data[p_type].value_ordered.push_back(p_constant_name);
#endif
-
}
-
};
-_VariantCall::TypeFunc* _VariantCall::type_funcs=NULL;
-_VariantCall::ConstructFunc* _VariantCall::construct_funcs=NULL;
-_VariantCall::ConstantData* _VariantCall::constant_data=NULL;
+_VariantCall::TypeFunc *_VariantCall::type_funcs = NULL;
+_VariantCall::ConstructFunc *_VariantCall::construct_funcs = NULL;
+_VariantCall::ConstantData *_VariantCall::constant_data = NULL;
-
-Variant Variant::call(const StringName& p_method,const Variant** p_args,int p_argcount,CallError &r_error) {
+Variant Variant::call(const StringName &p_method, const Variant **p_args, int p_argcount, CallError &r_error) {
Variant ret;
- call_ptr(p_method,p_args,p_argcount,&ret,r_error);
+ call_ptr(p_method, p_args, p_argcount, &ret, r_error);
return ret;
}
-void Variant::call_ptr(const StringName& p_method,const Variant** p_args,int p_argcount,Variant* r_ret,CallError &r_error) {
+void Variant::call_ptr(const StringName &p_method, const Variant **p_args, int p_argcount, Variant *r_ret, CallError &r_error) {
Variant ret;
- if (type==Variant::OBJECT) {
+ if (type == Variant::OBJECT) {
//call object
Object *obj = _get_obj().obj;
if (!obj) {
- r_error.error=CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ r_error.error = CallError::CALL_ERROR_INSTANCE_IS_NULL;
return;
}
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
//only if debugging!
if (!ObjectDB::instance_validate(obj)) {
- r_error.error=CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ r_error.error = CallError::CALL_ERROR_INSTANCE_IS_NULL;
return;
}
}
-
#endif
- ret=_get_obj().obj->call(p_method,p_args,p_argcount,r_error);
+ ret = _get_obj().obj->call(p_method, p_args, p_argcount, r_error);
- //else if (type==Variant::METHOD) {
+ //else if (type==Variant::METHOD) {
} else {
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Map<StringName,_VariantCall::FuncData>::Element *E=_VariantCall::type_funcs[type].functions.find(p_method);
+ Map<StringName, _VariantCall::FuncData>::Element *E = _VariantCall::type_funcs[type].functions.find(p_method);
#ifdef DEBUG_ENABLED
if (!E) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return;
}
#endif
- _VariantCall::FuncData& funcdata = E->get();
- funcdata.call(ret,*this,p_args,p_argcount,r_error);
+ _VariantCall::FuncData &funcdata = E->get();
+ funcdata.call(ret, *this, p_args, p_argcount, r_error);
}
- if (r_error.error==Variant::CallError::CALL_OK && r_ret)
- *r_ret=ret;
+ if (r_error.error == Variant::CallError::CALL_OK && r_ret)
+ *r_ret = ret;
}
-#define VCALL(m_type,m_method) _VariantCall::_call_##m_type##_##m_method
+#define VCALL(m_type, m_method) _VariantCall::_call_##m_type##_##m_method
+Variant Variant::construct(const Variant::Type p_type, const Variant **p_args, int p_argcount, CallError &r_error, bool p_strict) {
-Variant Variant::construct(const Variant::Type p_type, const Variant** p_args, int p_argcount, CallError &r_error, bool p_strict) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ ERR_FAIL_INDEX_V(p_type, VARIANT_MAX, Variant());
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- ERR_FAIL_INDEX_V(p_type,VARIANT_MAX,Variant());
+ r_error.error = Variant::CallError::CALL_OK;
+ if (p_argcount == 0) { //generic construct
- r_error.error=Variant::CallError::CALL_OK;
- if (p_argcount==0) { //generic construct
-
- switch(p_type) {
- case NIL: return Variant();
+ switch (p_type) {
+ case NIL:
+ return Variant();
// atomic types
- case BOOL: return Variant( false );
+ case BOOL: return Variant(false);
case INT: return 0;
case REAL: return 0.0f;
- case STRING: return String();
+ case STRING:
+ return String();
// math types
- case VECTOR2: return Vector2(); // 5
+ case VECTOR2:
+ return Vector2(); // 5
case RECT2: return Rect2();
case VECTOR3: return Vector3();
case TRANSFORM2D: return Transform2D();
case PLANE: return Plane();
case QUAT: return Quat();
- case RECT3: return Rect3(); // 10
+ case RECT3:
+ return Rect3(); // 10
case BASIS: return Basis();
- case TRANSFORM: return Transform();
+ case TRANSFORM:
+ return Transform();
// misc types
case COLOR: return Color();
case IMAGE: return Image();
- case NODE_PATH: return NodePath(); // 15
+ case NODE_PATH:
+ return NodePath(); // 15
case _RID: return RID();
- case OBJECT: return (Object*)NULL;
+ case OBJECT: return (Object *)NULL;
case INPUT_EVENT: return InputEvent();
case DICTIONARY: return Dictionary();
- case ARRAY: return Array(); // 20
+ case ARRAY:
+ return Array(); // 20
case POOL_BYTE_ARRAY: return PoolByteArray();
case POOL_INT_ARRAY: return PoolIntArray();
case POOL_REAL_ARRAY: return PoolRealArray();
case POOL_STRING_ARRAY: return PoolStringArray();
- case POOL_VECTOR2_ARRAY: return PoolVector2Array(); // 25
+ case POOL_VECTOR2_ARRAY:
+ return PoolVector2Array(); // 25
case POOL_VECTOR3_ARRAY: return PoolVector3Array();
case POOL_COLOR_ARRAY: return PoolColorArray();
default: return Variant();
}
- } else if (p_argcount>1) {
+ } else if (p_argcount > 1) {
- _VariantCall::ConstructFunc & c = _VariantCall::construct_funcs[p_type];
+ _VariantCall::ConstructFunc &c = _VariantCall::construct_funcs[p_type];
- for(List<_VariantCall::ConstructData>::Element *E=c.constructors.front();E;E=E->next()) {
+ for (List<_VariantCall::ConstructData>::Element *E = c.constructors.front(); E; E = E->next()) {
const _VariantCall::ConstructData &cd = E->get();
- if (cd.arg_count!=p_argcount)
+ if (cd.arg_count != p_argcount)
continue;
//validate parameters
- for(int i=0;i<cd.arg_count;i++) {
- if (!Variant::can_convert(p_args[i]->type,cd.arg_types[i])) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; //no such constructor
- r_error.argument=i;
- r_error.expected=cd.arg_types[i];
+ for (int i = 0; i < cd.arg_count; i++) {
+ if (!Variant::can_convert(p_args[i]->type, cd.arg_types[i])) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; //no such constructor
+ r_error.argument = i;
+ r_error.expected = cd.arg_types[i];
return Variant();
}
}
Variant v;
- cd.func(v,p_args);
+ cd.func(v, p_args);
return v;
}
-
- } else if (p_argcount==1 && p_args[0]->type==p_type) {
+ } else if (p_argcount == 1 && p_args[0]->type == p_type) {
return *p_args[0]; //copy construct
- } else if (p_argcount==1 && (!p_strict || Variant::can_convert(p_args[0]->type,p_type))) {
+ } else if (p_argcount == 1 && (!p_strict || Variant::can_convert(p_args[0]->type, p_type))) {
//near match construct
- switch(p_type) {
+ switch (p_type) {
case NIL: {
return Variant();
} break;
- case BOOL: { return Variant(bool(*p_args[0])); }
- case INT: { return (int(*p_args[0])); }
- case REAL: { return real_t(*p_args[0]); }
- case STRING: { return String(*p_args[0]); }
- case VECTOR2: { return Vector2(*p_args[0]); }
+ case BOOL: {
+ return Variant(bool(*p_args[0]));
+ }
+ case INT: {
+ return (int(*p_args[0]));
+ }
+ case REAL: {
+ return real_t(*p_args[0]);
+ }
+ case STRING: {
+ return String(*p_args[0]);
+ }
+ case VECTOR2: {
+ return Vector2(*p_args[0]);
+ }
case RECT2: return (Rect2(*p_args[0]));
case VECTOR3: return (Vector3(*p_args[0]));
case PLANE: return (Plane(*p_args[0]));
case QUAT: return (Quat(*p_args[0]));
- case RECT3: return (Rect3(*p_args[0])); // 10
+ case RECT3:
+ return (Rect3(*p_args[0])); // 10
case BASIS: return (Basis(p_args[0]->operator Basis()));
- case TRANSFORM: return (Transform(p_args[0]->operator Transform()));
+ case TRANSFORM:
+ return (Transform(p_args[0]->operator Transform()));
// misc types
case COLOR: return p_args[0]->type == Variant::STRING ? Color::html(*p_args[0]) : Color::hex(*p_args[0]);
case IMAGE: return (Image(*p_args[0]));
- case NODE_PATH: return (NodePath(p_args[0]->operator NodePath())); // 15
+ case NODE_PATH:
+ return (NodePath(p_args[0]->operator NodePath())); // 15
case _RID: return (RID(*p_args[0]));
- case OBJECT: return ((Object*)(p_args[0]->operator Object *()));
+ case OBJECT: return ((Object *)(p_args[0]->operator Object *()));
case INPUT_EVENT: return (InputEvent(*p_args[0]));
case DICTIONARY: return p_args[0]->operator Dictionary();
- case ARRAY: return p_args[0]->operator Array(); // 20
+ case ARRAY:
+ return p_args[0]->operator Array(); // 20
// arrays
case POOL_BYTE_ARRAY: return (PoolByteArray(*p_args[0]));
case POOL_INT_ARRAY: return (PoolIntArray(*p_args[0]));
case POOL_REAL_ARRAY: return (PoolRealArray(*p_args[0]));
case POOL_STRING_ARRAY: return (PoolStringArray(*p_args[0]));
- case POOL_VECTOR2_ARRAY: return (PoolVector2Array(*p_args[0])); // 25
+ case POOL_VECTOR2_ARRAY:
+ return (PoolVector2Array(*p_args[0])); // 25
case POOL_VECTOR3_ARRAY: return (PoolVector3Array(*p_args[0]));
case POOL_COLOR_ARRAY: return (PoolColorArray(*p_args[0]));
default: return Variant();
}
}
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD; //no such constructor
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD; //no such constructor
return Variant();
}
+bool Variant::has_method(const StringName &p_method) const {
-bool Variant::has_method(const StringName& p_method) const {
-
-
- if (type==OBJECT) {
- Object *obj = operator Object*();
+ if (type == OBJECT) {
+ Object *obj = operator Object *();
if (!obj)
return false;
#ifdef DEBUG_ENABLED
@@ -1171,367 +1162,351 @@ bool Variant::has_method(const StringName& p_method) const {
#endif
return obj->has_method(p_method);
#ifdef DEBUG_ENABLED
-
}
}
#endif
}
-
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[type];
return fd.functions.has(p_method);
-
}
-Vector<Variant::Type> Variant::get_method_argument_types(Variant::Type p_type,const StringName& p_method) {
+Vector<Variant::Type> Variant::get_method_argument_types(Variant::Type p_type, const StringName &p_method) {
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type];
- const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
+ const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
if (!E)
return Vector<Variant::Type>();
return E->get().arg_types;
}
-Vector<StringName> Variant::get_method_argument_names(Variant::Type p_type,const StringName& p_method) {
-
+Vector<StringName> Variant::get_method_argument_names(Variant::Type p_type, const StringName &p_method) {
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type];
- const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
+ const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
if (!E)
return Vector<StringName>();
return E->get().arg_names;
-
}
-Variant::Type Variant::get_method_return_type(Variant::Type p_type,const StringName& p_method,bool* r_has_return) {
+Variant::Type Variant::get_method_return_type(Variant::Type p_type, const StringName &p_method, bool *r_has_return) {
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type];
- const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
+ const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
if (!E)
return Variant::NIL;
if (r_has_return)
- *r_has_return=E->get().return_type;
+ *r_has_return = E->get().return_type;
return E->get().return_type;
}
-Vector<Variant> Variant::get_method_default_arguments(Variant::Type p_type,const StringName& p_method) {
+Vector<Variant> Variant::get_method_default_arguments(Variant::Type p_type, const StringName &p_method) {
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[p_type];
- const Map<StringName,_VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
+ const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.find(p_method);
if (!E)
return Vector<Variant>();
return E->get().default_args;
-
}
void Variant::get_method_list(List<MethodInfo> *p_list) const {
-
const _VariantCall::TypeFunc &fd = _VariantCall::type_funcs[type];
- for (const Map<StringName,_VariantCall::FuncData>::Element *E=fd.functions.front();E;E=E->next()) {
+ for (const Map<StringName, _VariantCall::FuncData>::Element *E = fd.functions.front(); E; E = E->next()) {
const _VariantCall::FuncData &fd = E->get();
MethodInfo mi;
- mi.name=E->key();
+ mi.name = E->key();
- for(int i=0;i<fd.arg_types.size();i++) {
+ for (int i = 0; i < fd.arg_types.size(); i++) {
PropertyInfo pi;
- pi.type=fd.arg_types[i];
+ pi.type = fd.arg_types[i];
#ifdef DEBUG_ENABLED
- pi.name=fd.arg_names[i];
+ pi.name = fd.arg_names[i];
#endif
mi.arguments.push_back(pi);
}
- mi.default_arguments=fd.default_args;
+ mi.default_arguments = fd.default_args;
PropertyInfo ret;
#ifdef DEBUG_ENABLED
- ret.type=fd.return_type;
+ ret.type = fd.return_type;
if (fd.returns)
- ret.name="ret";
- mi.return_val=ret;
+ ret.name = "ret";
+ mi.return_val = ret;
#endif
p_list->push_back(mi);
}
-
}
void Variant::get_constructor_list(Variant::Type p_type, List<MethodInfo> *p_list) {
- ERR_FAIL_INDEX(p_type,VARIANT_MAX);
+ ERR_FAIL_INDEX(p_type, VARIANT_MAX);
//custom constructors
- for(const List<_VariantCall::ConstructData>::Element *E=_VariantCall::construct_funcs[p_type].constructors.front();E;E=E->next()) {
+ for (const List<_VariantCall::ConstructData>::Element *E = _VariantCall::construct_funcs[p_type].constructors.front(); E; E = E->next()) {
const _VariantCall::ConstructData &cd = E->get();
MethodInfo mi;
- mi.name=Variant::get_type_name(p_type);
- mi.return_val.type=p_type;
- for(int i=0;i<cd.arg_count;i++) {
+ mi.name = Variant::get_type_name(p_type);
+ mi.return_val.type = p_type;
+ for (int i = 0; i < cd.arg_count; i++) {
PropertyInfo pi;
- pi.name=cd.arg_names[i];
- pi.type=cd.arg_types[i];
+ pi.name = cd.arg_names[i];
+ pi.type = cd.arg_types[i];
mi.arguments.push_back(pi);
}
p_list->push_back(mi);
}
//default constructors
- for(int i=0;i<VARIANT_MAX;i++) {
- if (i==p_type)
+ for (int i = 0; i < VARIANT_MAX; i++) {
+ if (i == p_type)
continue;
- if (!Variant::can_convert(Variant::Type(i),p_type))
+ if (!Variant::can_convert(Variant::Type(i), p_type))
continue;
MethodInfo mi;
- mi.name=Variant::get_type_name(p_type);
+ mi.name = Variant::get_type_name(p_type);
PropertyInfo pi;
- pi.name="from";
- pi.type=Variant::Type(i);
+ pi.name = "from";
+ pi.type = Variant::Type(i);
mi.arguments.push_back(pi);
- mi.return_val.type=p_type;
+ mi.return_val.type = p_type;
p_list->push_back(mi);
}
}
-
void Variant::get_numeric_constants_for_type(Variant::Type p_type, List<StringName> *p_constants) {
- ERR_FAIL_INDEX(p_type,Variant::VARIANT_MAX);
+ ERR_FAIL_INDEX(p_type, Variant::VARIANT_MAX);
- _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type];
+ _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type];
#ifdef DEBUG_ENABLED
- for(List<StringName>::Element *E=cd.value_ordered.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = cd.value_ordered.front(); E; E = E->next()) {
p_constants->push_back(E->get());
#else
- for(Map<StringName,int>::Element *E=cd.value.front();E;E=E->next()) {
+ for (Map<StringName, int>::Element *E = cd.value.front(); E; E = E->next()) {
p_constants->push_back(E->key());
#endif
}
}
+bool Variant::has_numeric_constant(Variant::Type p_type, const StringName &p_value) {
-bool Variant::has_numeric_constant(Variant::Type p_type, const StringName& p_value) {
-
- ERR_FAIL_INDEX_V(p_type,Variant::VARIANT_MAX,false);
- _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type];
+ ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, false);
+ _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type];
return cd.value.has(p_value);
}
-int Variant::get_numeric_constant_value(Variant::Type p_type, const StringName& p_value, bool *r_valid) {
+int Variant::get_numeric_constant_value(Variant::Type p_type, const StringName &p_value, bool *r_valid) {
if (r_valid)
- *r_valid=false;
-
- ERR_FAIL_INDEX_V(p_type,Variant::VARIANT_MAX,0);
- _VariantCall::ConstantData& cd = _VariantCall::constant_data[p_type];
+ *r_valid = false;
+ ERR_FAIL_INDEX_V(p_type, Variant::VARIANT_MAX, 0);
+ _VariantCall::ConstantData &cd = _VariantCall::constant_data[p_type];
- Map<StringName,int>::Element *E = cd.value.find(p_value);
+ Map<StringName, int>::Element *E = cd.value.find(p_value);
if (!E) {
return -1;
}
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
return E->get();
}
-
-
void register_variant_methods() {
- _VariantCall::type_funcs = memnew_arr(_VariantCall::TypeFunc,Variant::VARIANT_MAX );
+ _VariantCall::type_funcs = memnew_arr(_VariantCall::TypeFunc, Variant::VARIANT_MAX);
- _VariantCall::construct_funcs = memnew_arr(_VariantCall::ConstructFunc,Variant::VARIANT_MAX );
+ _VariantCall::construct_funcs = memnew_arr(_VariantCall::ConstructFunc, Variant::VARIANT_MAX);
_VariantCall::constant_data = memnew_arr(_VariantCall::ConstantData, Variant::VARIANT_MAX);
-#define ADDFUNC0(m_vtype,m_ret,m_class,m_method,m_defarg)\
-_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg);
-#define ADDFUNC1(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_defarg)\
-_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)) );
-#define ADDFUNC2(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_defarg)\
-_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2)));
-#define ADDFUNC3(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_arg3,m_argname3,m_defarg)\
-_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2)),_VariantCall::Arg(Variant::m_arg3,_scs_create(m_argname3)));
-#define ADDFUNC4(m_vtype,m_ret,m_class,m_method,m_arg1,m_argname1,m_arg2,m_argname2,m_arg3,m_argname3,m_arg4,m_argname4,m_defarg)\
-_VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCALL(m_class,m_method),m_defarg,_VariantCall::Arg(Variant::m_arg1,_scs_create(m_argname1)),_VariantCall::Arg(Variant::m_arg2,_scs_create(m_argname2)),_VariantCall::Arg(Variant::m_arg3,_scs_create(m_argname3)),_VariantCall::Arg(Variant::m_arg4,_scs_create(m_argname4)));
-
+#define ADDFUNC0(m_vtype, m_ret, m_class, m_method, m_defarg) \
+ _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg);
+#define ADDFUNC1(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_defarg) \
+ _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)));
+#define ADDFUNC2(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_defarg) \
+ _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2)));
+#define ADDFUNC3(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_arg3, m_argname3, m_defarg) \
+ _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2)), _VariantCall::Arg(Variant::m_arg3, _scs_create(m_argname3)));
+#define ADDFUNC4(m_vtype, m_ret, m_class, m_method, m_arg1, m_argname1, m_arg2, m_argname2, m_arg3, m_argname3, m_arg4, m_argname4, m_defarg) \
+ _VariantCall::addfunc(Variant::m_vtype, Variant::m_ret, _scs_create(#m_method), VCALL(m_class, m_method), m_defarg, _VariantCall::Arg(Variant::m_arg1, _scs_create(m_argname1)), _VariantCall::Arg(Variant::m_arg2, _scs_create(m_argname2)), _VariantCall::Arg(Variant::m_arg3, _scs_create(m_argname3)), _VariantCall::Arg(Variant::m_arg4, _scs_create(m_argname4)));
/* STRING */
- ADDFUNC1(STRING,INT,String,casecmp_to,STRING,"to",varray());
- ADDFUNC1(STRING,INT,String,nocasecmp_to,STRING,"to",varray());
- ADDFUNC0(STRING,INT,String,length,varray());
- ADDFUNC2(STRING,STRING,String,substr,INT,"from",INT,"len",varray());
-
- ADDFUNC2(STRING,INT,String,find,STRING,"what",INT,"from",varray(0));
-
- ADDFUNC1(STRING,INT,String,find_last,STRING,"what",varray());
- ADDFUNC2(STRING,INT,String,findn,STRING,"what",INT,"from",varray(0));
- ADDFUNC2(STRING,INT,String,rfind,STRING,"what",INT,"from",varray(-1));
- ADDFUNC2(STRING,INT,String,rfindn,STRING,"what",INT,"from",varray(-1));
- ADDFUNC1(STRING,BOOL,String,match,STRING,"expr",varray());
- ADDFUNC1(STRING,BOOL,String,matchn,STRING,"expr",varray());
- ADDFUNC1(STRING,BOOL,String,begins_with,STRING,"text",varray());
- ADDFUNC1(STRING,BOOL,String,ends_with,STRING,"text",varray());
- ADDFUNC1(STRING,BOOL,String,is_subsequence_of,STRING,"text",varray());
- ADDFUNC1(STRING,BOOL,String,is_subsequence_ofi,STRING,"text",varray());
- ADDFUNC0(STRING,POOL_STRING_ARRAY,String,bigrams,varray());
- ADDFUNC1(STRING,REAL,String,similarity,STRING,"text",varray());
-
- ADDFUNC2(STRING,STRING,String,format,NIL,"values",STRING,"placeholder",varray("{_}"));
- ADDFUNC2(STRING,STRING,String,replace,STRING,"what",STRING,"forwhat",varray());
- ADDFUNC2(STRING,STRING,String,replacen,STRING,"what",STRING,"forwhat",varray());
- ADDFUNC2(STRING,STRING,String,insert,INT,"pos",STRING,"what",varray());
- ADDFUNC0(STRING,STRING,String,capitalize,varray());
- ADDFUNC2(STRING,POOL_STRING_ARRAY,String,split,STRING,"divisor",BOOL,"allow_empty",varray(true));
- ADDFUNC2(STRING,POOL_REAL_ARRAY,String,split_floats,STRING,"divisor",BOOL,"allow_empty",varray(true));
-
- ADDFUNC0(STRING,STRING,String,to_upper,varray());
- ADDFUNC0(STRING,STRING,String,to_lower,varray());
-
- ADDFUNC1(STRING,STRING,String,left,INT,"pos",varray());
- ADDFUNC1(STRING,STRING,String,right,INT,"pos",varray());
- ADDFUNC2(STRING,STRING,String,strip_edges,BOOL,"left",BOOL,"right",varray(true,true));
- ADDFUNC0(STRING,STRING,String,get_extension,varray());
- ADDFUNC0(STRING,STRING,String,get_basename,varray());
- ADDFUNC1(STRING,STRING,String,plus_file,STRING,"file",varray());
- ADDFUNC1(STRING,INT,String,ord_at,INT,"at",varray());
- ADDFUNC2(STRING,NIL,String,erase,INT,"pos",INT,"chars", varray());
- ADDFUNC0(STRING,INT,String,hash,varray());
- ADDFUNC0(STRING,STRING,String,md5_text,varray());
- ADDFUNC0(STRING,STRING,String,sha256_text,varray());
- ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,md5_buffer,varray());
- ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,sha256_buffer,varray());
- ADDFUNC0(STRING,BOOL,String,empty,varray());
- ADDFUNC0(STRING,BOOL,String,is_abs_path,varray());
- ADDFUNC0(STRING,BOOL,String,is_rel_path,varray());
- ADDFUNC0(STRING,STRING,String,get_base_dir,varray());
- ADDFUNC0(STRING,STRING,String,get_file,varray());
- ADDFUNC0(STRING,STRING,String,xml_escape,varray());
- ADDFUNC0(STRING,STRING,String,xml_unescape,varray());
- ADDFUNC0(STRING,STRING,String,c_escape,varray());
- ADDFUNC0(STRING,STRING,String,c_unescape,varray());
- ADDFUNC0(STRING,STRING,String,json_escape,varray());
- ADDFUNC0(STRING,STRING,String,percent_encode,varray());
- ADDFUNC0(STRING,STRING,String,percent_decode,varray());
- ADDFUNC0(STRING,BOOL,String,is_valid_identifier,varray());
- ADDFUNC0(STRING,BOOL,String,is_valid_integer,varray());
- ADDFUNC0(STRING,BOOL,String,is_valid_float,varray());
- ADDFUNC0(STRING,BOOL,String,is_valid_html_color,varray());
- ADDFUNC0(STRING,BOOL,String,is_valid_ip_address,varray());
- ADDFUNC0(STRING,INT,String,to_int,varray());
- ADDFUNC0(STRING,REAL,String,to_float,varray());
- ADDFUNC0(STRING,INT,String,hex_to_int,varray());
- ADDFUNC1(STRING,STRING,String,pad_decimals,INT,"digits",varray());
- ADDFUNC1(STRING,STRING,String,pad_zeros,INT,"digits",varray());
-
- ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,to_ascii,varray());
- ADDFUNC0(STRING,POOL_BYTE_ARRAY,String,to_utf8,varray());
-
-
-
- ADDFUNC0(VECTOR2,VECTOR2,Vector2,normalized,varray());
- ADDFUNC0(VECTOR2,REAL,Vector2,length,varray());
- ADDFUNC0(VECTOR2,REAL,Vector2,angle,varray());
- ADDFUNC0(VECTOR2,REAL,Vector2,length_squared,varray());
- ADDFUNC1(VECTOR2,REAL,Vector2,distance_to,VECTOR2,"to",varray());
- ADDFUNC1(VECTOR2,REAL,Vector2,distance_squared_to,VECTOR2,"to",varray());
- ADDFUNC1(VECTOR2,REAL,Vector2,angle_to,VECTOR2,"to",varray());
- ADDFUNC1(VECTOR2,REAL,Vector2,angle_to_point,VECTOR2,"to",varray());
- ADDFUNC2(VECTOR2,VECTOR2,Vector2,linear_interpolate,VECTOR2,"b",REAL,"t",varray());
- ADDFUNC4(VECTOR2,VECTOR2,Vector2,cubic_interpolate,VECTOR2,"b",VECTOR2,"pre_a",VECTOR2,"post_b",REAL,"t",varray());
- ADDFUNC1(VECTOR2,VECTOR2,Vector2,rotated,REAL,"phi",varray());
- ADDFUNC0(VECTOR2,VECTOR2,Vector2,tangent,varray());
- ADDFUNC0(VECTOR2,VECTOR2,Vector2,floor,varray());
- ADDFUNC1(VECTOR2,VECTOR2,Vector2,snapped,VECTOR2,"by",varray());
- ADDFUNC0(VECTOR2,REAL,Vector2,aspect,varray());
- ADDFUNC1(VECTOR2,REAL,Vector2,dot,VECTOR2,"with",varray());
- ADDFUNC1(VECTOR2,VECTOR2,Vector2,slide,VECTOR2,"vec",varray());
- ADDFUNC1(VECTOR2,VECTOR2,Vector2,reflect,VECTOR2,"vec",varray());
+ ADDFUNC1(STRING, INT, String, casecmp_to, STRING, "to", varray());
+ ADDFUNC1(STRING, INT, String, nocasecmp_to, STRING, "to", varray());
+ ADDFUNC0(STRING, INT, String, length, varray());
+ ADDFUNC2(STRING, STRING, String, substr, INT, "from", INT, "len", varray());
+
+ ADDFUNC2(STRING, INT, String, find, STRING, "what", INT, "from", varray(0));
+
+ ADDFUNC1(STRING, INT, String, find_last, STRING, "what", varray());
+ ADDFUNC2(STRING, INT, String, findn, STRING, "what", INT, "from", varray(0));
+ ADDFUNC2(STRING, INT, String, rfind, STRING, "what", INT, "from", varray(-1));
+ ADDFUNC2(STRING, INT, String, rfindn, STRING, "what", INT, "from", varray(-1));
+ ADDFUNC1(STRING, BOOL, String, match, STRING, "expr", varray());
+ ADDFUNC1(STRING, BOOL, String, matchn, STRING, "expr", varray());
+ ADDFUNC1(STRING, BOOL, String, begins_with, STRING, "text", varray());
+ ADDFUNC1(STRING, BOOL, String, ends_with, STRING, "text", varray());
+ ADDFUNC1(STRING, BOOL, String, is_subsequence_of, STRING, "text", varray());
+ ADDFUNC1(STRING, BOOL, String, is_subsequence_ofi, STRING, "text", varray());
+ ADDFUNC0(STRING, POOL_STRING_ARRAY, String, bigrams, varray());
+ ADDFUNC1(STRING, REAL, String, similarity, STRING, "text", varray());
+
+ ADDFUNC2(STRING, STRING, String, format, NIL, "values", STRING, "placeholder", varray("{_}"));
+ ADDFUNC2(STRING, STRING, String, replace, STRING, "what", STRING, "forwhat", varray());
+ ADDFUNC2(STRING, STRING, String, replacen, STRING, "what", STRING, "forwhat", varray());
+ ADDFUNC2(STRING, STRING, String, insert, INT, "pos", STRING, "what", varray());
+ ADDFUNC0(STRING, STRING, String, capitalize, varray());
+ ADDFUNC2(STRING, POOL_STRING_ARRAY, String, split, STRING, "divisor", BOOL, "allow_empty", varray(true));
+ ADDFUNC2(STRING, POOL_REAL_ARRAY, String, split_floats, STRING, "divisor", BOOL, "allow_empty", varray(true));
+
+ ADDFUNC0(STRING, STRING, String, to_upper, varray());
+ ADDFUNC0(STRING, STRING, String, to_lower, varray());
+
+ ADDFUNC1(STRING, STRING, String, left, INT, "pos", varray());
+ ADDFUNC1(STRING, STRING, String, right, INT, "pos", varray());
+ ADDFUNC2(STRING, STRING, String, strip_edges, BOOL, "left", BOOL, "right", varray(true, true));
+ ADDFUNC0(STRING, STRING, String, get_extension, varray());
+ ADDFUNC0(STRING, STRING, String, get_basename, varray());
+ ADDFUNC1(STRING, STRING, String, plus_file, STRING, "file", varray());
+ ADDFUNC1(STRING, INT, String, ord_at, INT, "at", varray());
+ ADDFUNC2(STRING, NIL, String, erase, INT, "pos", INT, "chars", varray());
+ ADDFUNC0(STRING, INT, String, hash, varray());
+ ADDFUNC0(STRING, STRING, String, md5_text, varray());
+ ADDFUNC0(STRING, STRING, String, sha256_text, varray());
+ ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, md5_buffer, varray());
+ ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, sha256_buffer, varray());
+ ADDFUNC0(STRING, BOOL, String, empty, varray());
+ ADDFUNC0(STRING, BOOL, String, is_abs_path, varray());
+ ADDFUNC0(STRING, BOOL, String, is_rel_path, varray());
+ ADDFUNC0(STRING, STRING, String, get_base_dir, varray());
+ ADDFUNC0(STRING, STRING, String, get_file, varray());
+ ADDFUNC0(STRING, STRING, String, xml_escape, varray());
+ ADDFUNC0(STRING, STRING, String, xml_unescape, varray());
+ ADDFUNC0(STRING, STRING, String, c_escape, varray());
+ ADDFUNC0(STRING, STRING, String, c_unescape, varray());
+ ADDFUNC0(STRING, STRING, String, json_escape, varray());
+ ADDFUNC0(STRING, STRING, String, percent_encode, varray());
+ ADDFUNC0(STRING, STRING, String, percent_decode, varray());
+ ADDFUNC0(STRING, BOOL, String, is_valid_identifier, varray());
+ ADDFUNC0(STRING, BOOL, String, is_valid_integer, varray());
+ ADDFUNC0(STRING, BOOL, String, is_valid_float, varray());
+ ADDFUNC0(STRING, BOOL, String, is_valid_html_color, varray());
+ ADDFUNC0(STRING, BOOL, String, is_valid_ip_address, varray());
+ ADDFUNC0(STRING, INT, String, to_int, varray());
+ ADDFUNC0(STRING, REAL, String, to_float, varray());
+ ADDFUNC0(STRING, INT, String, hex_to_int, varray());
+ ADDFUNC1(STRING, STRING, String, pad_decimals, INT, "digits", varray());
+ ADDFUNC1(STRING, STRING, String, pad_zeros, INT, "digits", varray());
+
+ ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, to_ascii, varray());
+ ADDFUNC0(STRING, POOL_BYTE_ARRAY, String, to_utf8, varray());
+
+ ADDFUNC0(VECTOR2, VECTOR2, Vector2, normalized, varray());
+ ADDFUNC0(VECTOR2, REAL, Vector2, length, varray());
+ ADDFUNC0(VECTOR2, REAL, Vector2, angle, varray());
+ ADDFUNC0(VECTOR2, REAL, Vector2, length_squared, varray());
+ ADDFUNC1(VECTOR2, REAL, Vector2, distance_to, VECTOR2, "to", varray());
+ ADDFUNC1(VECTOR2, REAL, Vector2, distance_squared_to, VECTOR2, "to", varray());
+ ADDFUNC1(VECTOR2, REAL, Vector2, angle_to, VECTOR2, "to", varray());
+ ADDFUNC1(VECTOR2, REAL, Vector2, angle_to_point, VECTOR2, "to", varray());
+ ADDFUNC2(VECTOR2, VECTOR2, Vector2, linear_interpolate, VECTOR2, "b", REAL, "t", varray());
+ ADDFUNC4(VECTOR2, VECTOR2, Vector2, cubic_interpolate, VECTOR2, "b", VECTOR2, "pre_a", VECTOR2, "post_b", REAL, "t", varray());
+ ADDFUNC1(VECTOR2, VECTOR2, Vector2, rotated, REAL, "phi", varray());
+ ADDFUNC0(VECTOR2, VECTOR2, Vector2, tangent, varray());
+ ADDFUNC0(VECTOR2, VECTOR2, Vector2, floor, varray());
+ ADDFUNC1(VECTOR2, VECTOR2, Vector2, snapped, VECTOR2, "by", varray());
+ ADDFUNC0(VECTOR2, REAL, Vector2, aspect, varray());
+ ADDFUNC1(VECTOR2, REAL, Vector2, dot, VECTOR2, "with", varray());
+ ADDFUNC1(VECTOR2, VECTOR2, Vector2, slide, VECTOR2, "vec", varray());
+ ADDFUNC1(VECTOR2, VECTOR2, Vector2, reflect, VECTOR2, "vec", varray());
//ADDFUNC1(VECTOR2,REAL,Vector2,cross,VECTOR2,"with",varray());
- ADDFUNC0(VECTOR2,VECTOR2,Vector2,abs,varray());
- ADDFUNC1(VECTOR2,VECTOR2,Vector2,clamped,REAL,"length",varray());
-
- ADDFUNC0(RECT2,REAL,Rect2,get_area,varray());
- ADDFUNC1(RECT2,BOOL,Rect2,intersects,RECT2,"b",varray());
- ADDFUNC1(RECT2,BOOL,Rect2,encloses,RECT2,"b",varray());
- ADDFUNC0(RECT2,BOOL,Rect2,has_no_area,varray());
- ADDFUNC1(RECT2,RECT2,Rect2,clip,RECT2,"b",varray());
- ADDFUNC1(RECT2,RECT2,Rect2,merge,RECT2,"b",varray());
- ADDFUNC1(RECT2,BOOL,Rect2,has_point,VECTOR2,"point",varray());
- ADDFUNC1(RECT2,RECT2,Rect2,grow,REAL,"by",varray());
- ADDFUNC1(RECT2,RECT2,Rect2,expand,VECTOR2,"to",varray());
-
- ADDFUNC0(VECTOR3,INT,Vector3,min_axis,varray());
- ADDFUNC0(VECTOR3,INT,Vector3,max_axis,varray());
- ADDFUNC0(VECTOR3,REAL,Vector3,length,varray());
- ADDFUNC0(VECTOR3,REAL,Vector3,length_squared,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,normalized,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,inverse,varray());
- ADDFUNC1(VECTOR3,VECTOR3,Vector3,snapped,REAL,"by",varray());
- ADDFUNC2(VECTOR3,VECTOR3,Vector3,rotated,VECTOR3,"axis",REAL,"phi",varray());
- ADDFUNC2(VECTOR3,VECTOR3,Vector3,linear_interpolate,VECTOR3,"b",REAL,"t",varray());
- ADDFUNC4(VECTOR3,VECTOR3,Vector3,cubic_interpolate,VECTOR3,"b",VECTOR3,"pre_a",VECTOR3,"post_b",REAL,"t",varray());
- ADDFUNC1(VECTOR3,REAL,Vector3,dot,VECTOR3,"b",varray());
- ADDFUNC1(VECTOR3,VECTOR3,Vector3,cross,VECTOR3,"b",varray());
- ADDFUNC1(VECTOR3,BASIS,Vector3,outer,VECTOR3,"b",varray());
- ADDFUNC0(VECTOR3,BASIS,Vector3,to_diagonal_matrix,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,abs,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,abs,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,floor,varray());
- ADDFUNC0(VECTOR3,VECTOR3,Vector3,ceil,varray());
- ADDFUNC1(VECTOR3,REAL,Vector3,distance_to,VECTOR3,"b",varray());
- ADDFUNC1(VECTOR3,REAL,Vector3,distance_squared_to,VECTOR3,"b",varray());
- ADDFUNC1(VECTOR3,REAL,Vector3,angle_to,VECTOR3,"to",varray());
- ADDFUNC1(VECTOR3,VECTOR3,Vector3,slide,VECTOR3,"by",varray());
- ADDFUNC1(VECTOR3,VECTOR3,Vector3,reflect,VECTOR3,"by",varray());
-
- ADDFUNC0(PLANE,PLANE,Plane,normalized,varray());
- ADDFUNC0(PLANE,VECTOR3,Plane,center,varray());
- ADDFUNC0(PLANE,VECTOR3,Plane,get_any_point,varray());
- ADDFUNC1(PLANE,BOOL,Plane,is_point_over,VECTOR3,"point",varray());
- ADDFUNC1(PLANE,REAL,Plane,distance_to,VECTOR3,"point",varray());
- ADDFUNC2(PLANE,BOOL,Plane,has_point,VECTOR3,"point",REAL,"epsilon",varray(CMP_EPSILON));
- ADDFUNC1(PLANE,VECTOR3,Plane,project,VECTOR3,"point",varray());
- ADDFUNC2(PLANE,VECTOR3,Plane,intersect_3,PLANE,"b",PLANE,"c",varray());
- ADDFUNC2(PLANE,VECTOR3,Plane,intersects_ray,VECTOR3,"from",VECTOR3,"dir",varray());
- ADDFUNC2(PLANE,VECTOR3,Plane,intersects_segment,VECTOR3,"begin",VECTOR3,"end",varray());
-
- ADDFUNC0(QUAT,REAL,Quat,length,varray());
- ADDFUNC0(QUAT,REAL,Quat,length_squared,varray());
- ADDFUNC0(QUAT,QUAT,Quat,normalized,varray());
- ADDFUNC0(QUAT,QUAT,Quat,inverse,varray());
- ADDFUNC1(QUAT,REAL,Quat,dot,QUAT,"b",varray());
- ADDFUNC1(QUAT,VECTOR3,Quat,xform,VECTOR3,"v",varray());
- ADDFUNC2(QUAT,QUAT,Quat,slerp,QUAT,"b",REAL,"t",varray());
- ADDFUNC2(QUAT,QUAT,Quat,slerpni,QUAT,"b",REAL,"t",varray());
- ADDFUNC4(QUAT,QUAT,Quat,cubic_slerp,QUAT,"b",QUAT,"pre_a",QUAT,"post_b",REAL,"t",varray());
-
- ADDFUNC0(COLOR,INT,Color,to_32,varray());
- ADDFUNC0(COLOR,INT,Color,to_ARGB32,varray());
- ADDFUNC0(COLOR,REAL,Color,gray,varray());
- ADDFUNC0(COLOR,COLOR,Color,inverted,varray());
- ADDFUNC0(COLOR,COLOR,Color,contrasted,varray());
- ADDFUNC2(COLOR,COLOR,Color,linear_interpolate,COLOR,"b",REAL,"t",varray());
- ADDFUNC1(COLOR,COLOR,Color,blend,COLOR,"over",varray());
- ADDFUNC1(COLOR,STRING,Color,to_html,BOOL,"with_alpha",varray(true));
+ ADDFUNC0(VECTOR2, VECTOR2, Vector2, abs, varray());
+ ADDFUNC1(VECTOR2, VECTOR2, Vector2, clamped, REAL, "length", varray());
+
+ ADDFUNC0(RECT2, REAL, Rect2, get_area, varray());
+ ADDFUNC1(RECT2, BOOL, Rect2, intersects, RECT2, "b", varray());
+ ADDFUNC1(RECT2, BOOL, Rect2, encloses, RECT2, "b", varray());
+ ADDFUNC0(RECT2, BOOL, Rect2, has_no_area, varray());
+ ADDFUNC1(RECT2, RECT2, Rect2, clip, RECT2, "b", varray());
+ ADDFUNC1(RECT2, RECT2, Rect2, merge, RECT2, "b", varray());
+ ADDFUNC1(RECT2, BOOL, Rect2, has_point, VECTOR2, "point", varray());
+ ADDFUNC1(RECT2, RECT2, Rect2, grow, REAL, "by", varray());
+ ADDFUNC1(RECT2, RECT2, Rect2, expand, VECTOR2, "to", varray());
+
+ ADDFUNC0(VECTOR3, INT, Vector3, min_axis, varray());
+ ADDFUNC0(VECTOR3, INT, Vector3, max_axis, varray());
+ ADDFUNC0(VECTOR3, REAL, Vector3, length, varray());
+ ADDFUNC0(VECTOR3, REAL, Vector3, length_squared, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, normalized, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, inverse, varray());
+ ADDFUNC1(VECTOR3, VECTOR3, Vector3, snapped, REAL, "by", varray());
+ ADDFUNC2(VECTOR3, VECTOR3, Vector3, rotated, VECTOR3, "axis", REAL, "phi", varray());
+ ADDFUNC2(VECTOR3, VECTOR3, Vector3, linear_interpolate, VECTOR3, "b", REAL, "t", varray());
+ ADDFUNC4(VECTOR3, VECTOR3, Vector3, cubic_interpolate, VECTOR3, "b", VECTOR3, "pre_a", VECTOR3, "post_b", REAL, "t", varray());
+ ADDFUNC1(VECTOR3, REAL, Vector3, dot, VECTOR3, "b", varray());
+ ADDFUNC1(VECTOR3, VECTOR3, Vector3, cross, VECTOR3, "b", varray());
+ ADDFUNC1(VECTOR3, BASIS, Vector3, outer, VECTOR3, "b", varray());
+ ADDFUNC0(VECTOR3, BASIS, Vector3, to_diagonal_matrix, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, abs, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, abs, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, floor, varray());
+ ADDFUNC0(VECTOR3, VECTOR3, Vector3, ceil, varray());
+ ADDFUNC1(VECTOR3, REAL, Vector3, distance_to, VECTOR3, "b", varray());
+ ADDFUNC1(VECTOR3, REAL, Vector3, distance_squared_to, VECTOR3, "b", varray());
+ ADDFUNC1(VECTOR3, REAL, Vector3, angle_to, VECTOR3, "to", varray());
+ ADDFUNC1(VECTOR3, VECTOR3, Vector3, slide, VECTOR3, "by", varray());
+ ADDFUNC1(VECTOR3, VECTOR3, Vector3, reflect, VECTOR3, "by", varray());
+
+ ADDFUNC0(PLANE, PLANE, Plane, normalized, varray());
+ ADDFUNC0(PLANE, VECTOR3, Plane, center, varray());
+ ADDFUNC0(PLANE, VECTOR3, Plane, get_any_point, varray());
+ ADDFUNC1(PLANE, BOOL, Plane, is_point_over, VECTOR3, "point", varray());
+ ADDFUNC1(PLANE, REAL, Plane, distance_to, VECTOR3, "point", varray());
+ ADDFUNC2(PLANE, BOOL, Plane, has_point, VECTOR3, "point", REAL, "epsilon", varray(CMP_EPSILON));
+ ADDFUNC1(PLANE, VECTOR3, Plane, project, VECTOR3, "point", varray());
+ ADDFUNC2(PLANE, VECTOR3, Plane, intersect_3, PLANE, "b", PLANE, "c", varray());
+ ADDFUNC2(PLANE, VECTOR3, Plane, intersects_ray, VECTOR3, "from", VECTOR3, "dir", varray());
+ ADDFUNC2(PLANE, VECTOR3, Plane, intersects_segment, VECTOR3, "begin", VECTOR3, "end", varray());
+
+ ADDFUNC0(QUAT, REAL, Quat, length, varray());
+ ADDFUNC0(QUAT, REAL, Quat, length_squared, varray());
+ ADDFUNC0(QUAT, QUAT, Quat, normalized, varray());
+ ADDFUNC0(QUAT, QUAT, Quat, inverse, varray());
+ ADDFUNC1(QUAT, REAL, Quat, dot, QUAT, "b", varray());
+ ADDFUNC1(QUAT, VECTOR3, Quat, xform, VECTOR3, "v", varray());
+ ADDFUNC2(QUAT, QUAT, Quat, slerp, QUAT, "b", REAL, "t", varray());
+ ADDFUNC2(QUAT, QUAT, Quat, slerpni, QUAT, "b", REAL, "t", varray());
+ ADDFUNC4(QUAT, QUAT, Quat, cubic_slerp, QUAT, "b", QUAT, "pre_a", QUAT, "post_b", REAL, "t", varray());
+
+ ADDFUNC0(COLOR, INT, Color, to_32, varray());
+ ADDFUNC0(COLOR, INT, Color, to_ARGB32, varray());
+ ADDFUNC0(COLOR, REAL, Color, gray, varray());
+ ADDFUNC0(COLOR, COLOR, Color, inverted, varray());
+ ADDFUNC0(COLOR, COLOR, Color, contrasted, varray());
+ ADDFUNC2(COLOR, COLOR, Color, linear_interpolate, COLOR, "b", REAL, "t", varray());
+ ADDFUNC1(COLOR, COLOR, Color, blend, COLOR, "over", varray());
+ ADDFUNC1(COLOR, STRING, Color, to_html, BOOL, "with_alpha", varray(true));
ADDFUNC0(IMAGE, INT, Image, get_format, varray());
ADDFUNC0(IMAGE, INT, Image, get_width, varray());
@@ -1549,312 +1524,302 @@ _VariantCall::addfunc(Variant::m_vtype,Variant::m_ret,_scs_create(#m_method),VCA
ADDFUNC1(IMAGE, IMAGE, Image, converted, INT, "format", varray(0));
ADDFUNC0(IMAGE, NIL, Image, fix_alpha_edges, varray());
- ADDFUNC0(_RID,INT,RID,get_id,varray());
-
- ADDFUNC0(NODE_PATH,BOOL,NodePath,is_absolute,varray());
- ADDFUNC0(NODE_PATH,INT,NodePath,get_name_count,varray());
- ADDFUNC1(NODE_PATH,STRING,NodePath,get_name,INT,"idx",varray());
- ADDFUNC0(NODE_PATH,INT,NodePath,get_subname_count,varray());
- ADDFUNC1(NODE_PATH,STRING,NodePath,get_subname,INT,"idx",varray());
- ADDFUNC0(NODE_PATH,STRING,NodePath,get_property,varray());
- ADDFUNC0(NODE_PATH,BOOL,NodePath,is_empty,varray());
-
- ADDFUNC0(DICTIONARY,INT,Dictionary,size,varray());
- ADDFUNC0(DICTIONARY,BOOL,Dictionary,empty,varray());
- ADDFUNC0(DICTIONARY,NIL,Dictionary,clear,varray());
- ADDFUNC1(DICTIONARY,BOOL,Dictionary,has,NIL,"key",varray());
- ADDFUNC1(DICTIONARY,BOOL,Dictionary,has_all,ARRAY,"keys",varray());
- ADDFUNC1(DICTIONARY,NIL,Dictionary,erase,NIL,"key",varray());
- ADDFUNC0(DICTIONARY,INT,Dictionary,hash,varray());
- ADDFUNC0(DICTIONARY,ARRAY,Dictionary,keys,varray());
- ADDFUNC0(DICTIONARY,ARRAY,Dictionary,values,varray());
-
- ADDFUNC0(ARRAY,INT,Array,size,varray());
- ADDFUNC0(ARRAY,BOOL,Array,empty,varray());
- ADDFUNC0(ARRAY,NIL,Array,clear,varray());
- ADDFUNC0(ARRAY,INT,Array,hash,varray());
- ADDFUNC1(ARRAY,NIL,Array,push_back,NIL,"value",varray());
- ADDFUNC1(ARRAY,NIL,Array,push_front,NIL,"value",varray());
- ADDFUNC1(ARRAY,NIL,Array,append,NIL,"value",varray());
- ADDFUNC1(ARRAY,NIL,Array,resize,INT,"pos",varray());
- ADDFUNC2(ARRAY,NIL,Array,insert,INT,"pos",NIL,"value",varray());
- ADDFUNC1(ARRAY,NIL,Array,remove,INT,"pos",varray());
- ADDFUNC1(ARRAY,NIL,Array,erase,NIL,"value",varray());
- ADDFUNC0(ARRAY,NIL,Array,front,varray());
- ADDFUNC0(ARRAY,NIL,Array,back,varray());
- ADDFUNC2(ARRAY,INT,Array,find,NIL,"what",INT,"from",varray(0));
- ADDFUNC2(ARRAY,INT,Array,rfind,NIL,"what",INT,"from",varray(-1));
- ADDFUNC1(ARRAY,INT,Array,find_last,NIL,"value",varray());
- ADDFUNC1(ARRAY,INT,Array,count,NIL,"value",varray());
- ADDFUNC1(ARRAY,BOOL,Array,has,NIL,"value",varray());
- ADDFUNC0(ARRAY,NIL,Array,pop_back,varray());
- ADDFUNC0(ARRAY,NIL,Array,pop_front,varray());
- ADDFUNC0(ARRAY,NIL,Array,sort,varray());
- ADDFUNC2(ARRAY,NIL,Array,sort_custom,OBJECT,"obj",STRING,"func",varray());
- ADDFUNC0(ARRAY,NIL,Array,invert,varray());
-
-
- ADDFUNC0(POOL_BYTE_ARRAY,INT,PoolByteArray,size,varray());
- ADDFUNC2(POOL_BYTE_ARRAY,NIL,PoolByteArray,set,INT,"idx",INT,"byte",varray());
- ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,push_back,INT,"byte",varray());
- ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,append,INT,"byte",varray());
- ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,append_array,POOL_BYTE_ARRAY,"array",varray());
- ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,remove,INT,"idx",varray());
- ADDFUNC2(POOL_BYTE_ARRAY,INT,PoolByteArray,insert,INT,"idx",INT,"byte",varray());
- ADDFUNC1(POOL_BYTE_ARRAY,NIL,PoolByteArray,resize,INT,"idx",varray());
- ADDFUNC0(POOL_BYTE_ARRAY,NIL,PoolByteArray,invert,varray());
- ADDFUNC2(POOL_BYTE_ARRAY,POOL_BYTE_ARRAY,PoolByteArray,subarray,INT,"from",INT,"to",varray());
-
- ADDFUNC0(POOL_BYTE_ARRAY,STRING,PoolByteArray,get_string_from_ascii,varray());
- ADDFUNC0(POOL_BYTE_ARRAY,STRING,PoolByteArray,get_string_from_utf8,varray());
-
-
- ADDFUNC0(POOL_INT_ARRAY,INT,PoolIntArray,size,varray());
- ADDFUNC2(POOL_INT_ARRAY,NIL,PoolIntArray,set,INT,"idx",INT,"integer",varray());
- ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,push_back,INT,"integer",varray());
- ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,append,INT,"integer",varray());
- ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,append_array,POOL_INT_ARRAY,"array",varray());
- ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,remove,INT,"idx",varray());
- ADDFUNC2(POOL_INT_ARRAY,INT,PoolIntArray,insert,INT,"idx",INT,"integer",varray());
- ADDFUNC1(POOL_INT_ARRAY,NIL,PoolIntArray,resize,INT,"idx",varray());
- ADDFUNC0(POOL_INT_ARRAY,NIL,PoolIntArray,invert,varray());
-
- ADDFUNC0(POOL_REAL_ARRAY,INT,PoolRealArray,size,varray());
- ADDFUNC2(POOL_REAL_ARRAY,NIL,PoolRealArray,set,INT,"idx",REAL,"value",varray());
- ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,push_back,REAL,"value",varray());
- ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,append,REAL,"value",varray());
- ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,append_array,POOL_REAL_ARRAY,"array",varray());
- ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,remove,INT,"idx",varray());
- ADDFUNC2(POOL_REAL_ARRAY,INT,PoolRealArray,insert,INT,"idx",REAL,"value",varray());
- ADDFUNC1(POOL_REAL_ARRAY,NIL,PoolRealArray,resize,INT,"idx",varray());
- ADDFUNC0(POOL_REAL_ARRAY,NIL,PoolRealArray,invert,varray());
-
- ADDFUNC0(POOL_STRING_ARRAY,INT,PoolStringArray,size,varray());
- ADDFUNC2(POOL_STRING_ARRAY,NIL,PoolStringArray,set,INT,"idx",STRING,"string",varray());
- ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,push_back,STRING,"string",varray());
- ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,append,STRING,"string",varray());
- ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,append_array,POOL_STRING_ARRAY,"array",varray());
- ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,remove,INT,"idx",varray());
- ADDFUNC2(POOL_STRING_ARRAY,INT,PoolStringArray,insert,INT,"idx",STRING,"string",varray());
- ADDFUNC1(POOL_STRING_ARRAY,NIL,PoolStringArray,resize,INT,"idx",varray());
- ADDFUNC0(POOL_STRING_ARRAY,NIL,PoolStringArray,invert,varray());
- ADDFUNC1(POOL_STRING_ARRAY,STRING,PoolStringArray,join,STRING,"string",varray());
-
- ADDFUNC0(POOL_VECTOR2_ARRAY,INT,PoolVector2Array,size,varray());
- ADDFUNC2(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,set,INT,"idx",VECTOR2,"vector2",varray());
- ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,push_back,VECTOR2,"vector2",varray());
- ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,append,VECTOR2,"vector2",varray());
- ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,append_array,POOL_VECTOR2_ARRAY,"array",varray());
- ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,remove,INT,"idx",varray());
- ADDFUNC2(POOL_VECTOR2_ARRAY,INT,PoolVector2Array,insert,INT,"idx",VECTOR2,"vector2",varray());
- ADDFUNC1(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,resize,INT,"idx",varray());
- ADDFUNC0(POOL_VECTOR2_ARRAY,NIL,PoolVector2Array,invert,varray());
-
- ADDFUNC0(POOL_VECTOR3_ARRAY,INT,PoolVector3Array,size,varray());
- ADDFUNC2(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,set,INT,"idx",VECTOR3,"vector3",varray());
- ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,push_back,VECTOR3,"vector3",varray());
- ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,append,VECTOR3,"vector3",varray());
- ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,append_array,POOL_VECTOR3_ARRAY,"array",varray());
- ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,remove,INT,"idx",varray());
- ADDFUNC2(POOL_VECTOR3_ARRAY,INT,PoolVector3Array,insert,INT,"idx",VECTOR3,"vector3",varray());
- ADDFUNC1(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,resize,INT,"idx",varray());
- ADDFUNC0(POOL_VECTOR3_ARRAY,NIL,PoolVector3Array,invert,varray());
-
- ADDFUNC0(POOL_COLOR_ARRAY,INT,PoolColorArray,size,varray());
- ADDFUNC2(POOL_COLOR_ARRAY,NIL,PoolColorArray,set,INT,"idx",COLOR,"color",varray());
- ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,push_back,COLOR,"color",varray());
- ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,append,COLOR,"color",varray());
- ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,append_array,POOL_COLOR_ARRAY,"array",varray());
- ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,remove,INT,"idx",varray());
- ADDFUNC2(POOL_COLOR_ARRAY,INT,PoolColorArray,insert,INT,"idx",COLOR,"color",varray());
- ADDFUNC1(POOL_COLOR_ARRAY,NIL,PoolColorArray,resize,INT,"idx",varray());
- ADDFUNC0(POOL_COLOR_ARRAY,NIL,PoolColorArray,invert,varray());
+ ADDFUNC0(_RID, INT, RID, get_id, varray());
+
+ ADDFUNC0(NODE_PATH, BOOL, NodePath, is_absolute, varray());
+ ADDFUNC0(NODE_PATH, INT, NodePath, get_name_count, varray());
+ ADDFUNC1(NODE_PATH, STRING, NodePath, get_name, INT, "idx", varray());
+ ADDFUNC0(NODE_PATH, INT, NodePath, get_subname_count, varray());
+ ADDFUNC1(NODE_PATH, STRING, NodePath, get_subname, INT, "idx", varray());
+ ADDFUNC0(NODE_PATH, STRING, NodePath, get_property, varray());
+ ADDFUNC0(NODE_PATH, BOOL, NodePath, is_empty, varray());
+
+ ADDFUNC0(DICTIONARY, INT, Dictionary, size, varray());
+ ADDFUNC0(DICTIONARY, BOOL, Dictionary, empty, varray());
+ ADDFUNC0(DICTIONARY, NIL, Dictionary, clear, varray());
+ ADDFUNC1(DICTIONARY, BOOL, Dictionary, has, NIL, "key", varray());
+ ADDFUNC1(DICTIONARY, BOOL, Dictionary, has_all, ARRAY, "keys", varray());
+ ADDFUNC1(DICTIONARY, NIL, Dictionary, erase, NIL, "key", varray());
+ ADDFUNC0(DICTIONARY, INT, Dictionary, hash, varray());
+ ADDFUNC0(DICTIONARY, ARRAY, Dictionary, keys, varray());
+ ADDFUNC0(DICTIONARY, ARRAY, Dictionary, values, varray());
+
+ ADDFUNC0(ARRAY, INT, Array, size, varray());
+ ADDFUNC0(ARRAY, BOOL, Array, empty, varray());
+ ADDFUNC0(ARRAY, NIL, Array, clear, varray());
+ ADDFUNC0(ARRAY, INT, Array, hash, varray());
+ ADDFUNC1(ARRAY, NIL, Array, push_back, NIL, "value", varray());
+ ADDFUNC1(ARRAY, NIL, Array, push_front, NIL, "value", varray());
+ ADDFUNC1(ARRAY, NIL, Array, append, NIL, "value", varray());
+ ADDFUNC1(ARRAY, NIL, Array, resize, INT, "pos", varray());
+ ADDFUNC2(ARRAY, NIL, Array, insert, INT, "pos", NIL, "value", varray());
+ ADDFUNC1(ARRAY, NIL, Array, remove, INT, "pos", varray());
+ ADDFUNC1(ARRAY, NIL, Array, erase, NIL, "value", varray());
+ ADDFUNC0(ARRAY, NIL, Array, front, varray());
+ ADDFUNC0(ARRAY, NIL, Array, back, varray());
+ ADDFUNC2(ARRAY, INT, Array, find, NIL, "what", INT, "from", varray(0));
+ ADDFUNC2(ARRAY, INT, Array, rfind, NIL, "what", INT, "from", varray(-1));
+ ADDFUNC1(ARRAY, INT, Array, find_last, NIL, "value", varray());
+ ADDFUNC1(ARRAY, INT, Array, count, NIL, "value", varray());
+ ADDFUNC1(ARRAY, BOOL, Array, has, NIL, "value", varray());
+ ADDFUNC0(ARRAY, NIL, Array, pop_back, varray());
+ ADDFUNC0(ARRAY, NIL, Array, pop_front, varray());
+ ADDFUNC0(ARRAY, NIL, Array, sort, varray());
+ ADDFUNC2(ARRAY, NIL, Array, sort_custom, OBJECT, "obj", STRING, "func", varray());
+ ADDFUNC0(ARRAY, NIL, Array, invert, varray());
+
+ ADDFUNC0(POOL_BYTE_ARRAY, INT, PoolByteArray, size, varray());
+ ADDFUNC2(POOL_BYTE_ARRAY, NIL, PoolByteArray, set, INT, "idx", INT, "byte", varray());
+ ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, push_back, INT, "byte", varray());
+ ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, append, INT, "byte", varray());
+ ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, append_array, POOL_BYTE_ARRAY, "array", varray());
+ ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_BYTE_ARRAY, INT, PoolByteArray, insert, INT, "idx", INT, "byte", varray());
+ ADDFUNC1(POOL_BYTE_ARRAY, NIL, PoolByteArray, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_BYTE_ARRAY, NIL, PoolByteArray, invert, varray());
+ ADDFUNC2(POOL_BYTE_ARRAY, POOL_BYTE_ARRAY, PoolByteArray, subarray, INT, "from", INT, "to", varray());
+
+ ADDFUNC0(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_ascii, varray());
+ ADDFUNC0(POOL_BYTE_ARRAY, STRING, PoolByteArray, get_string_from_utf8, varray());
+
+ ADDFUNC0(POOL_INT_ARRAY, INT, PoolIntArray, size, varray());
+ ADDFUNC2(POOL_INT_ARRAY, NIL, PoolIntArray, set, INT, "idx", INT, "integer", varray());
+ ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, push_back, INT, "integer", varray());
+ ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, append, INT, "integer", varray());
+ ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, append_array, POOL_INT_ARRAY, "array", varray());
+ ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_INT_ARRAY, INT, PoolIntArray, insert, INT, "idx", INT, "integer", varray());
+ ADDFUNC1(POOL_INT_ARRAY, NIL, PoolIntArray, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_INT_ARRAY, NIL, PoolIntArray, invert, varray());
+
+ ADDFUNC0(POOL_REAL_ARRAY, INT, PoolRealArray, size, varray());
+ ADDFUNC2(POOL_REAL_ARRAY, NIL, PoolRealArray, set, INT, "idx", REAL, "value", varray());
+ ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, push_back, REAL, "value", varray());
+ ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, append, REAL, "value", varray());
+ ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, append_array, POOL_REAL_ARRAY, "array", varray());
+ ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_REAL_ARRAY, INT, PoolRealArray, insert, INT, "idx", REAL, "value", varray());
+ ADDFUNC1(POOL_REAL_ARRAY, NIL, PoolRealArray, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_REAL_ARRAY, NIL, PoolRealArray, invert, varray());
+
+ ADDFUNC0(POOL_STRING_ARRAY, INT, PoolStringArray, size, varray());
+ ADDFUNC2(POOL_STRING_ARRAY, NIL, PoolStringArray, set, INT, "idx", STRING, "string", varray());
+ ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, push_back, STRING, "string", varray());
+ ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, append, STRING, "string", varray());
+ ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, append_array, POOL_STRING_ARRAY, "array", varray());
+ ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_STRING_ARRAY, INT, PoolStringArray, insert, INT, "idx", STRING, "string", varray());
+ ADDFUNC1(POOL_STRING_ARRAY, NIL, PoolStringArray, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_STRING_ARRAY, NIL, PoolStringArray, invert, varray());
+ ADDFUNC1(POOL_STRING_ARRAY, STRING, PoolStringArray, join, STRING, "string", varray());
+
+ ADDFUNC0(POOL_VECTOR2_ARRAY, INT, PoolVector2Array, size, varray());
+ ADDFUNC2(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, set, INT, "idx", VECTOR2, "vector2", varray());
+ ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, push_back, VECTOR2, "vector2", varray());
+ ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, append, VECTOR2, "vector2", varray());
+ ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, append_array, POOL_VECTOR2_ARRAY, "array", varray());
+ ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_VECTOR2_ARRAY, INT, PoolVector2Array, insert, INT, "idx", VECTOR2, "vector2", varray());
+ ADDFUNC1(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_VECTOR2_ARRAY, NIL, PoolVector2Array, invert, varray());
+
+ ADDFUNC0(POOL_VECTOR3_ARRAY, INT, PoolVector3Array, size, varray());
+ ADDFUNC2(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, set, INT, "idx", VECTOR3, "vector3", varray());
+ ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, push_back, VECTOR3, "vector3", varray());
+ ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, append, VECTOR3, "vector3", varray());
+ ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, append_array, POOL_VECTOR3_ARRAY, "array", varray());
+ ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_VECTOR3_ARRAY, INT, PoolVector3Array, insert, INT, "idx", VECTOR3, "vector3", varray());
+ ADDFUNC1(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_VECTOR3_ARRAY, NIL, PoolVector3Array, invert, varray());
+
+ ADDFUNC0(POOL_COLOR_ARRAY, INT, PoolColorArray, size, varray());
+ ADDFUNC2(POOL_COLOR_ARRAY, NIL, PoolColorArray, set, INT, "idx", COLOR, "color", varray());
+ ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, push_back, COLOR, "color", varray());
+ ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, append, COLOR, "color", varray());
+ ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, append_array, POOL_COLOR_ARRAY, "array", varray());
+ ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, remove, INT, "idx", varray());
+ ADDFUNC2(POOL_COLOR_ARRAY, INT, PoolColorArray, insert, INT, "idx", COLOR, "color", varray());
+ ADDFUNC1(POOL_COLOR_ARRAY, NIL, PoolColorArray, resize, INT, "idx", varray());
+ ADDFUNC0(POOL_COLOR_ARRAY, NIL, PoolColorArray, invert, varray());
//pointerbased
- ADDFUNC0(RECT3,REAL,Rect3,get_area,varray());
- ADDFUNC0(RECT3,BOOL,Rect3,has_no_area,varray());
- ADDFUNC0(RECT3,BOOL,Rect3,has_no_surface,varray());
- ADDFUNC1(RECT3,BOOL,Rect3,intersects,RECT3,"with",varray());
- ADDFUNC1(RECT3,BOOL,Rect3,encloses,RECT3,"with",varray());
- ADDFUNC1(RECT3,RECT3,Rect3,merge,RECT3,"with",varray());
- ADDFUNC1(RECT3,RECT3,Rect3,intersection,RECT3,"with",varray());
- ADDFUNC1(RECT3,BOOL,Rect3,intersects_plane,PLANE,"plane",varray());
- ADDFUNC2(RECT3,BOOL,Rect3,intersects_segment,VECTOR3,"from",VECTOR3,"to",varray());
- ADDFUNC1(RECT3,BOOL,Rect3,has_point,VECTOR3,"point",varray());
- ADDFUNC1(RECT3,VECTOR3,Rect3,get_support,VECTOR3,"dir",varray());
- ADDFUNC0(RECT3,VECTOR3,Rect3,get_longest_axis,varray());
- ADDFUNC0(RECT3,INT,Rect3,get_longest_axis_index,varray());
- ADDFUNC0(RECT3,REAL,Rect3,get_longest_axis_size,varray());
- ADDFUNC0(RECT3,VECTOR3,Rect3,get_shortest_axis,varray());
- ADDFUNC0(RECT3,INT,Rect3,get_shortest_axis_index,varray());
- ADDFUNC0(RECT3,REAL,Rect3,get_shortest_axis_size,varray());
- ADDFUNC1(RECT3,RECT3,Rect3,expand,VECTOR3,"to_point",varray());
- ADDFUNC1(RECT3,RECT3,Rect3,grow,REAL,"by",varray());
- ADDFUNC1(RECT3,VECTOR3,Rect3,get_endpoint,INT,"idx",varray());
-
- ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,inverse,varray());
- ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,affine_inverse,varray());
- ADDFUNC0(TRANSFORM2D,REAL,Transform2D,get_rotation,varray());
- ADDFUNC0(TRANSFORM2D,VECTOR2,Transform2D,get_origin,varray());
- ADDFUNC0(TRANSFORM2D,VECTOR2,Transform2D,get_scale,varray());
- ADDFUNC0(TRANSFORM2D,TRANSFORM2D,Transform2D,orthonormalized,varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,rotated,REAL,"phi",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,scaled,VECTOR2,"scale",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,translated,VECTOR2,"offset",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,xform,NIL,"v",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,xform_inv,NIL,"v",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,basis_xform,NIL,"v",varray());
- ADDFUNC1(TRANSFORM2D,TRANSFORM2D,Transform2D,basis_xform_inv,NIL,"v",varray());
- ADDFUNC2(TRANSFORM2D,TRANSFORM2D,Transform2D,interpolate_with,TRANSFORM2D,"m",REAL,"c",varray());
-
- ADDFUNC0(BASIS,BASIS,Basis,inverse,varray());
- ADDFUNC0(BASIS,BASIS,Basis,transposed,varray());
- ADDFUNC0(BASIS,BASIS,Basis,orthonormalized,varray());
- ADDFUNC0(BASIS,REAL,Basis,determinant,varray());
- ADDFUNC2(BASIS,BASIS,Basis,rotated,VECTOR3,"axis",REAL,"phi",varray());
- ADDFUNC1(BASIS,BASIS,Basis,scaled,VECTOR3,"scale",varray());
- ADDFUNC0(BASIS,VECTOR3,Basis,get_scale,varray());
- ADDFUNC0(BASIS,VECTOR3,Basis,get_euler,varray());
- ADDFUNC1(BASIS,REAL,Basis,tdotx,VECTOR3,"with",varray());
- ADDFUNC1(BASIS,REAL,Basis,tdoty,VECTOR3,"with",varray());
- ADDFUNC1(BASIS,REAL,Basis,tdotz,VECTOR3,"with",varray());
- ADDFUNC1(BASIS,VECTOR3,Basis,xform,VECTOR3,"v",varray());
- ADDFUNC1(BASIS,VECTOR3,Basis,xform_inv,VECTOR3,"v",varray());
- ADDFUNC0(BASIS,INT,Basis,get_orthogonal_index,varray());
-
- ADDFUNC0(TRANSFORM,TRANSFORM,Transform,inverse,varray());
- ADDFUNC0(TRANSFORM,TRANSFORM,Transform,affine_inverse,varray());
- ADDFUNC0(TRANSFORM,TRANSFORM,Transform,orthonormalized,varray());
- ADDFUNC2(TRANSFORM,TRANSFORM,Transform,rotated,VECTOR3,"axis",REAL,"phi",varray());
- ADDFUNC1(TRANSFORM,TRANSFORM,Transform,scaled,VECTOR3,"scale",varray());
- ADDFUNC1(TRANSFORM,TRANSFORM,Transform,translated,VECTOR3,"ofs",varray());
- ADDFUNC2(TRANSFORM,TRANSFORM,Transform,looking_at,VECTOR3,"target",VECTOR3,"up",varray());
- ADDFUNC1(TRANSFORM,NIL,Transform,xform,NIL,"v",varray());
- ADDFUNC1(TRANSFORM,NIL,Transform,xform_inv,NIL,"v",varray());
+ ADDFUNC0(RECT3, REAL, Rect3, get_area, varray());
+ ADDFUNC0(RECT3, BOOL, Rect3, has_no_area, varray());
+ ADDFUNC0(RECT3, BOOL, Rect3, has_no_surface, varray());
+ ADDFUNC1(RECT3, BOOL, Rect3, intersects, RECT3, "with", varray());
+ ADDFUNC1(RECT3, BOOL, Rect3, encloses, RECT3, "with", varray());
+ ADDFUNC1(RECT3, RECT3, Rect3, merge, RECT3, "with", varray());
+ ADDFUNC1(RECT3, RECT3, Rect3, intersection, RECT3, "with", varray());
+ ADDFUNC1(RECT3, BOOL, Rect3, intersects_plane, PLANE, "plane", varray());
+ ADDFUNC2(RECT3, BOOL, Rect3, intersects_segment, VECTOR3, "from", VECTOR3, "to", varray());
+ ADDFUNC1(RECT3, BOOL, Rect3, has_point, VECTOR3, "point", varray());
+ ADDFUNC1(RECT3, VECTOR3, Rect3, get_support, VECTOR3, "dir", varray());
+ ADDFUNC0(RECT3, VECTOR3, Rect3, get_longest_axis, varray());
+ ADDFUNC0(RECT3, INT, Rect3, get_longest_axis_index, varray());
+ ADDFUNC0(RECT3, REAL, Rect3, get_longest_axis_size, varray());
+ ADDFUNC0(RECT3, VECTOR3, Rect3, get_shortest_axis, varray());
+ ADDFUNC0(RECT3, INT, Rect3, get_shortest_axis_index, varray());
+ ADDFUNC0(RECT3, REAL, Rect3, get_shortest_axis_size, varray());
+ ADDFUNC1(RECT3, RECT3, Rect3, expand, VECTOR3, "to_point", varray());
+ ADDFUNC1(RECT3, RECT3, Rect3, grow, REAL, "by", varray());
+ ADDFUNC1(RECT3, VECTOR3, Rect3, get_endpoint, INT, "idx", varray());
+
+ ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, inverse, varray());
+ ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, affine_inverse, varray());
+ ADDFUNC0(TRANSFORM2D, REAL, Transform2D, get_rotation, varray());
+ ADDFUNC0(TRANSFORM2D, VECTOR2, Transform2D, get_origin, varray());
+ ADDFUNC0(TRANSFORM2D, VECTOR2, Transform2D, get_scale, varray());
+ ADDFUNC0(TRANSFORM2D, TRANSFORM2D, Transform2D, orthonormalized, varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, rotated, REAL, "phi", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, scaled, VECTOR2, "scale", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, translated, VECTOR2, "offset", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, xform, NIL, "v", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, xform_inv, NIL, "v", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, basis_xform, NIL, "v", varray());
+ ADDFUNC1(TRANSFORM2D, TRANSFORM2D, Transform2D, basis_xform_inv, NIL, "v", varray());
+ ADDFUNC2(TRANSFORM2D, TRANSFORM2D, Transform2D, interpolate_with, TRANSFORM2D, "m", REAL, "c", varray());
+
+ ADDFUNC0(BASIS, BASIS, Basis, inverse, varray());
+ ADDFUNC0(BASIS, BASIS, Basis, transposed, varray());
+ ADDFUNC0(BASIS, BASIS, Basis, orthonormalized, varray());
+ ADDFUNC0(BASIS, REAL, Basis, determinant, varray());
+ ADDFUNC2(BASIS, BASIS, Basis, rotated, VECTOR3, "axis", REAL, "phi", varray());
+ ADDFUNC1(BASIS, BASIS, Basis, scaled, VECTOR3, "scale", varray());
+ ADDFUNC0(BASIS, VECTOR3, Basis, get_scale, varray());
+ ADDFUNC0(BASIS, VECTOR3, Basis, get_euler, varray());
+ ADDFUNC1(BASIS, REAL, Basis, tdotx, VECTOR3, "with", varray());
+ ADDFUNC1(BASIS, REAL, Basis, tdoty, VECTOR3, "with", varray());
+ ADDFUNC1(BASIS, REAL, Basis, tdotz, VECTOR3, "with", varray());
+ ADDFUNC1(BASIS, VECTOR3, Basis, xform, VECTOR3, "v", varray());
+ ADDFUNC1(BASIS, VECTOR3, Basis, xform_inv, VECTOR3, "v", varray());
+ ADDFUNC0(BASIS, INT, Basis, get_orthogonal_index, varray());
+
+ ADDFUNC0(TRANSFORM, TRANSFORM, Transform, inverse, varray());
+ ADDFUNC0(TRANSFORM, TRANSFORM, Transform, affine_inverse, varray());
+ ADDFUNC0(TRANSFORM, TRANSFORM, Transform, orthonormalized, varray());
+ ADDFUNC2(TRANSFORM, TRANSFORM, Transform, rotated, VECTOR3, "axis", REAL, "phi", varray());
+ ADDFUNC1(TRANSFORM, TRANSFORM, Transform, scaled, VECTOR3, "scale", varray());
+ ADDFUNC1(TRANSFORM, TRANSFORM, Transform, translated, VECTOR3, "ofs", varray());
+ ADDFUNC2(TRANSFORM, TRANSFORM, Transform, looking_at, VECTOR3, "target", VECTOR3, "up", varray());
+ ADDFUNC1(TRANSFORM, NIL, Transform, xform, NIL, "v", varray());
+ ADDFUNC1(TRANSFORM, NIL, Transform, xform_inv, NIL, "v", varray());
#ifdef DEBUG_ENABLED
- _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform"].returns=true;
- _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform_inv"].returns=true;
+ _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform"].returns = true;
+ _VariantCall::type_funcs[Variant::TRANSFORM].functions["xform_inv"].returns = true;
#endif
- ADDFUNC0(INPUT_EVENT,BOOL,InputEvent,is_pressed,varray());
- ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action,STRING,"action",varray());
- ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action_pressed,STRING,"action",varray());
- ADDFUNC1(INPUT_EVENT,BOOL,InputEvent,is_action_released,STRING,"action",varray());
- ADDFUNC0(INPUT_EVENT,BOOL,InputEvent,is_echo,varray());
- ADDFUNC2(INPUT_EVENT,NIL,InputEvent,set_as_action,STRING,"action",BOOL,"pressed",varray());
+ ADDFUNC0(INPUT_EVENT, BOOL, InputEvent, is_pressed, varray());
+ ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action, STRING, "action", varray());
+ ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action_pressed, STRING, "action", varray());
+ ADDFUNC1(INPUT_EVENT, BOOL, InputEvent, is_action_released, STRING, "action", varray());
+ ADDFUNC0(INPUT_EVENT, BOOL, InputEvent, is_echo, varray());
+ ADDFUNC2(INPUT_EVENT, NIL, InputEvent, set_as_action, STRING, "action", BOOL, "pressed", varray());
/* REGISTER CONSTRUCTORS */
- _VariantCall::add_constructor(_VariantCall::Vector2_init1,Variant::VECTOR2,"x",Variant::REAL,"y",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Vector2_init1, Variant::VECTOR2, "x", Variant::REAL, "y", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Rect2_init1,Variant::RECT2,"pos",Variant::VECTOR2,"size",Variant::VECTOR2);
- _VariantCall::add_constructor(_VariantCall::Rect2_init2,Variant::RECT2,"x",Variant::REAL,"y",Variant::REAL,"width",Variant::REAL,"height",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Rect2_init1, Variant::RECT2, "pos", Variant::VECTOR2, "size", Variant::VECTOR2);
+ _VariantCall::add_constructor(_VariantCall::Rect2_init2, Variant::RECT2, "x", Variant::REAL, "y", Variant::REAL, "width", Variant::REAL, "height", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Transform2D_init2,Variant::TRANSFORM2D,"rot",Variant::REAL,"pos",Variant::VECTOR2);
- _VariantCall::add_constructor(_VariantCall::Transform2D_init3,Variant::TRANSFORM2D,"x_axis",Variant::VECTOR2,"y_axis",Variant::VECTOR2,"origin",Variant::VECTOR2);
+ _VariantCall::add_constructor(_VariantCall::Transform2D_init2, Variant::TRANSFORM2D, "rot", Variant::REAL, "pos", Variant::VECTOR2);
+ _VariantCall::add_constructor(_VariantCall::Transform2D_init3, Variant::TRANSFORM2D, "x_axis", Variant::VECTOR2, "y_axis", Variant::VECTOR2, "origin", Variant::VECTOR2);
- _VariantCall::add_constructor(_VariantCall::Vector3_init1,Variant::VECTOR3,"x",Variant::REAL,"y",Variant::REAL,"z",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Vector3_init1, Variant::VECTOR3, "x", Variant::REAL, "y", Variant::REAL, "z", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Plane_init1,Variant::PLANE,"a",Variant::REAL,"b",Variant::REAL,"c",Variant::REAL,"d",Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Plane_init2,Variant::PLANE,"v1",Variant::VECTOR3,"v2",Variant::VECTOR3,"v3",Variant::VECTOR3);
- _VariantCall::add_constructor(_VariantCall::Plane_init3,Variant::PLANE,"normal",Variant::VECTOR3,"d",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Plane_init1, Variant::PLANE, "a", Variant::REAL, "b", Variant::REAL, "c", Variant::REAL, "d", Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Plane_init2, Variant::PLANE, "v1", Variant::VECTOR3, "v2", Variant::VECTOR3, "v3", Variant::VECTOR3);
+ _VariantCall::add_constructor(_VariantCall::Plane_init3, Variant::PLANE, "normal", Variant::VECTOR3, "d", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Quat_init1,Variant::QUAT,"x",Variant::REAL,"y",Variant::REAL,"z",Variant::REAL,"w",Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Quat_init2,Variant::QUAT,"axis",Variant::VECTOR3,"angle",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Quat_init1, Variant::QUAT, "x", Variant::REAL, "y", Variant::REAL, "z", Variant::REAL, "w", Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Quat_init2, Variant::QUAT, "axis", Variant::VECTOR3, "angle", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Color_init1,Variant::COLOR,"r",Variant::REAL,"g",Variant::REAL,"b",Variant::REAL,"a",Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Color_init2,Variant::COLOR,"r",Variant::REAL,"g",Variant::REAL,"b",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Color_init1, Variant::COLOR, "r", Variant::REAL, "g", Variant::REAL, "b", Variant::REAL, "a", Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Color_init2, Variant::COLOR, "r", Variant::REAL, "g", Variant::REAL, "b", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Rect3_init1,Variant::RECT3,"pos",Variant::VECTOR3,"size",Variant::VECTOR3);
+ _VariantCall::add_constructor(_VariantCall::Rect3_init1, Variant::RECT3, "pos", Variant::VECTOR3, "size", Variant::VECTOR3);
- _VariantCall::add_constructor(_VariantCall::Basis_init1,Variant::BASIS,"x_axis",Variant::VECTOR3,"y_axis",Variant::VECTOR3,"z_axis",Variant::VECTOR3);
- _VariantCall::add_constructor(_VariantCall::Basis_init2,Variant::BASIS,"axis",Variant::VECTOR3,"phi",Variant::REAL);
+ _VariantCall::add_constructor(_VariantCall::Basis_init1, Variant::BASIS, "x_axis", Variant::VECTOR3, "y_axis", Variant::VECTOR3, "z_axis", Variant::VECTOR3);
+ _VariantCall::add_constructor(_VariantCall::Basis_init2, Variant::BASIS, "axis", Variant::VECTOR3, "phi", Variant::REAL);
- _VariantCall::add_constructor(_VariantCall::Transform_init1,Variant::TRANSFORM,"x_axis",Variant::VECTOR3,"y_axis",Variant::VECTOR3,"z_axis",Variant::VECTOR3,"origin",Variant::VECTOR3);
- _VariantCall::add_constructor(_VariantCall::Transform_init2,Variant::TRANSFORM,"basis",Variant::BASIS,"origin",Variant::VECTOR3);
+ _VariantCall::add_constructor(_VariantCall::Transform_init1, Variant::TRANSFORM, "x_axis", Variant::VECTOR3, "y_axis", Variant::VECTOR3, "z_axis", Variant::VECTOR3, "origin", Variant::VECTOR3);
+ _VariantCall::add_constructor(_VariantCall::Transform_init2, Variant::TRANSFORM, "basis", Variant::BASIS, "origin", Variant::VECTOR3);
- _VariantCall::add_constructor(_VariantCall::Image_init1,Variant::IMAGE,"width",Variant::INT,"height",Variant::INT,"mipmaps",Variant::BOOL,"format",Variant::INT);
+ _VariantCall::add_constructor(_VariantCall::Image_init1, Variant::IMAGE, "width", Variant::INT, "height", Variant::INT, "mipmaps", Variant::BOOL, "format", Variant::INT);
/* REGISTER CONSTANTS */
- _VariantCall::add_constant(Variant::VECTOR3,"AXIS_X",Vector3::AXIS_X);
- _VariantCall::add_constant(Variant::VECTOR3,"AXIS_Y",Vector3::AXIS_Y);
- _VariantCall::add_constant(Variant::VECTOR3,"AXIS_Z",Vector3::AXIS_Z);
-
-
- _VariantCall::add_constant(Variant::INPUT_EVENT,"NONE",InputEvent::NONE);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"KEY",InputEvent::KEY);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"MOUSE_MOTION",InputEvent::MOUSE_MOTION);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"MOUSE_BUTTON",InputEvent::MOUSE_BUTTON);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"JOYPAD_MOTION",InputEvent::JOYPAD_MOTION);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"JOYPAD_BUTTON",InputEvent::JOYPAD_BUTTON);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"SCREEN_TOUCH",InputEvent::SCREEN_TOUCH);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"SCREEN_DRAG",InputEvent::SCREEN_DRAG);
- _VariantCall::add_constant(Variant::INPUT_EVENT,"ACTION",InputEvent::ACTION);
-
-
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_16BIT",Image::COMPRESS_16BIT);
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_S3TC",Image::COMPRESS_S3TC);
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_PVRTC2",Image::COMPRESS_PVRTC2);
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_PVRTC4",Image::COMPRESS_PVRTC4);
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_ETC",Image::COMPRESS_ETC);
- _VariantCall::add_constant(Variant::IMAGE,"COMPRESS_ETC2",Image::COMPRESS_ETC2);
-
-
-
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_L8",Image::FORMAT_L8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_LA8",Image::FORMAT_LA8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_R8",Image::FORMAT_R8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RG8",Image::FORMAT_RG8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGB8",Image::FORMAT_RGB8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA8",Image::FORMAT_RGBA8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGB565",Image::FORMAT_RGB565);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA4444",Image::FORMAT_RGBA4444);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBA5551",Image::FORMAT_DXT1);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RF",Image::FORMAT_RF);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGF",Image::FORMAT_RGF);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBF",Image::FORMAT_RGBF);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBAF",Image::FORMAT_RGBAF);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RH",Image::FORMAT_RH);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGH",Image::FORMAT_RGH);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBH",Image::FORMAT_RGBH);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_RGBAH",Image::FORMAT_RGBAH);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT1",Image::FORMAT_DXT1);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT3",Image::FORMAT_DXT3);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_DXT5",Image::FORMAT_DXT5);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ATI1",Image::FORMAT_ATI1);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ATI2",Image::FORMAT_ATI2);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBA",Image::FORMAT_BPTC_RGBA);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBF",Image::FORMAT_BPTC_RGBF);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_BPTC_RGBFU",Image::FORMAT_BPTC_RGBFU);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC2",Image::FORMAT_PVRTC2);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC2A",Image::FORMAT_PVRTC2A);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC4",Image::FORMAT_PVRTC4);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_PVRTC4A",Image::FORMAT_PVRTC4A);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC",Image::FORMAT_ETC);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_R11",Image::FORMAT_ETC2_R11);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_R11S",Image::FORMAT_ETC2_R11S);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RG11",Image::FORMAT_ETC2_RG11);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RG11S",Image::FORMAT_ETC2_RG11S);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGB8",Image::FORMAT_ETC2_RGB8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGBA8",Image::FORMAT_ETC2_RGBA8);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_ETC2_RGB8A1",Image::FORMAT_ETC2_RGB8A1);
- _VariantCall::add_constant(Variant::IMAGE,"FORMAT_MAX",Image::FORMAT_MAX);
-
- _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_NEAREST",Image::INTERPOLATE_NEAREST);
- _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_BILINEAR",Image::INTERPOLATE_BILINEAR);
- _VariantCall::add_constant(Variant::IMAGE,"INTERPOLATE_CUBIC",Image::INTERPOLATE_CUBIC);
-
+ _VariantCall::add_constant(Variant::VECTOR3, "AXIS_X", Vector3::AXIS_X);
+ _VariantCall::add_constant(Variant::VECTOR3, "AXIS_Y", Vector3::AXIS_Y);
+ _VariantCall::add_constant(Variant::VECTOR3, "AXIS_Z", Vector3::AXIS_Z);
+
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "NONE", InputEvent::NONE);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "KEY", InputEvent::KEY);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "MOUSE_MOTION", InputEvent::MOUSE_MOTION);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "MOUSE_BUTTON", InputEvent::MOUSE_BUTTON);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "JOYPAD_MOTION", InputEvent::JOYPAD_MOTION);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "JOYPAD_BUTTON", InputEvent::JOYPAD_BUTTON);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "SCREEN_TOUCH", InputEvent::SCREEN_TOUCH);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "SCREEN_DRAG", InputEvent::SCREEN_DRAG);
+ _VariantCall::add_constant(Variant::INPUT_EVENT, "ACTION", InputEvent::ACTION);
+
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_16BIT", Image::COMPRESS_16BIT);
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_S3TC", Image::COMPRESS_S3TC);
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_PVRTC2", Image::COMPRESS_PVRTC2);
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_PVRTC4", Image::COMPRESS_PVRTC4);
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_ETC", Image::COMPRESS_ETC);
+ _VariantCall::add_constant(Variant::IMAGE, "COMPRESS_ETC2", Image::COMPRESS_ETC2);
+
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_L8", Image::FORMAT_L8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_LA8", Image::FORMAT_LA8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_R8", Image::FORMAT_R8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RG8", Image::FORMAT_RG8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGB8", Image::FORMAT_RGB8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA8", Image::FORMAT_RGBA8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGB565", Image::FORMAT_RGB565);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA4444", Image::FORMAT_RGBA4444);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBA5551", Image::FORMAT_DXT1);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RF", Image::FORMAT_RF);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGF", Image::FORMAT_RGF);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBF", Image::FORMAT_RGBF);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBAF", Image::FORMAT_RGBAF);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RH", Image::FORMAT_RH);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGH", Image::FORMAT_RGH);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBH", Image::FORMAT_RGBH);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_RGBAH", Image::FORMAT_RGBAH);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT1", Image::FORMAT_DXT1);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT3", Image::FORMAT_DXT3);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_DXT5", Image::FORMAT_DXT5);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ATI1", Image::FORMAT_ATI1);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ATI2", Image::FORMAT_ATI2);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBA", Image::FORMAT_BPTC_RGBA);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBF", Image::FORMAT_BPTC_RGBF);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_BPTC_RGBFU", Image::FORMAT_BPTC_RGBFU);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC2", Image::FORMAT_PVRTC2);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC2A", Image::FORMAT_PVRTC2A);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC4", Image::FORMAT_PVRTC4);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_PVRTC4A", Image::FORMAT_PVRTC4A);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC", Image::FORMAT_ETC);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_R11", Image::FORMAT_ETC2_R11);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_R11S", Image::FORMAT_ETC2_R11S);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RG11", Image::FORMAT_ETC2_RG11);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RG11S", Image::FORMAT_ETC2_RG11S);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGB8", Image::FORMAT_ETC2_RGB8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGBA8", Image::FORMAT_ETC2_RGBA8);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_ETC2_RGB8A1", Image::FORMAT_ETC2_RGB8A1);
+ _VariantCall::add_constant(Variant::IMAGE, "FORMAT_MAX", Image::FORMAT_MAX);
+
+ _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_NEAREST", Image::INTERPOLATE_NEAREST);
+ _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_BILINEAR", Image::INTERPOLATE_BILINEAR);
+ _VariantCall::add_constant(Variant::IMAGE, "INTERPOLATE_CUBIC", Image::INTERPOLATE_CUBIC);
}
void unregister_variant_methods() {
-
memdelete_arr(_VariantCall::type_funcs);
memdelete_arr(_VariantCall::construct_funcs);
- memdelete_arr( _VariantCall::constant_data );
-
-
+ memdelete_arr(_VariantCall::constant_data);
}
diff --git a/core/variant_construct_string.cpp b/core/variant_construct_string.cpp
index 56aa9891fb..7f176749d3 100644
--- a/core/variant_construct_string.cpp
+++ b/core/variant_construct_string.cpp
@@ -58,22 +58,20 @@ class VariantConstruct {
Variant value;
};
- static const char * tk_name[TK_MAX];
+ static const char *tk_name[TK_MAX];
- static String _print_var(const Variant& p_var);
+ static String _print_var(const Variant &p_var);
- static Error _get_token(const CharType *p_str,int &index, int p_len,Token& r_token,int &line,String &r_err_str);
- static Error _parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud);
- static Error _parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud);
- static Error _parse_dict(Dictionary &object,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud);
+ static Error _get_token(const CharType *p_str, int &index, int p_len, Token &r_token, int &line, String &r_err_str);
+ static Error _parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud);
+ static Error _parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud);
+ static Error _parse_dict(Dictionary &object, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud);
public:
-
- static Error parse(const String& p_string,Variant& r_ret,String &r_err_str,int &r_err_line,Variant::ObjectConstruct* p_construct,void* p_ud);
+ static Error parse(const String &p_string, Variant &r_ret, String &r_err_str, int &r_err_line, Variant::ObjectConstruct *p_construct, void *p_ud);
};
-
-const char * VariantConstruct::tk_name[TK_MAX] = {
+const char *VariantConstruct::tk_name[TK_MAX] = {
"'{'",
"'}'",
"'['",
@@ -86,12 +84,10 @@ const char * VariantConstruct::tk_name[TK_MAX] = {
"EOF",
};
-
-
-Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, Token& r_token,int &line,String &r_err_str) {
+Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, Token &r_token, int &line, String &r_err_str) {
while (true) {
- switch(p_str[idx]) {
+ switch (p_str[idx]) {
case '\n': {
@@ -100,42 +96,42 @@ Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, T
break;
};
case 0: {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
} break;
case '{': {
- r_token.type=TK_CURLY_BRACKET_OPEN;
+ r_token.type = TK_CURLY_BRACKET_OPEN;
idx++;
return OK;
};
case '}': {
- r_token.type=TK_CURLY_BRACKET_CLOSE;
+ r_token.type = TK_CURLY_BRACKET_CLOSE;
idx++;
return OK;
};
case '[': {
- r_token.type=TK_BRACKET_OPEN;
+ r_token.type = TK_BRACKET_OPEN;
idx++;
return OK;
};
case ']': {
- r_token.type=TK_BRACKET_CLOSE;
+ r_token.type = TK_BRACKET_CLOSE;
idx++;
return OK;
};
case ':': {
- r_token.type=TK_COLON;
+ r_token.type = TK_COLON;
idx++;
return OK;
};
case ',': {
- r_token.type=TK_COMMA;
+ r_token.type = TK_COMMA;
idx++;
return OK;
};
@@ -143,318 +139,298 @@ Error VariantConstruct::_get_token(const CharType *p_str, int &idx, int p_len, T
idx++;
String str;
- while(true) {
- if (p_str[idx]==0) {
- r_err_str="Unterminated String";
+ while (true) {
+ if (p_str[idx] == 0) {
+ r_err_str = "Unterminated String";
return ERR_PARSE_ERROR;
- } else if (p_str[idx]=='"') {
+ } else if (p_str[idx] == '"') {
idx++;
break;
- } else if (p_str[idx]=='\\') {
+ } else if (p_str[idx] == '\\') {
//escaped characters...
idx++;
CharType next = p_str[idx];
- if (next==0) {
- r_err_str="Unterminated String";
- return ERR_PARSE_ERROR;
+ if (next == 0) {
+ r_err_str = "Unterminated String";
+ return ERR_PARSE_ERROR;
}
- CharType 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 '\"': res='\"'; break;
- case '\\': res='\\'; break;
- case '/': res='/'; break;
+ CharType 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 '\"': res = '\"'; break;
+ case '\\': res = '\\'; break;
+ case '/': res = '/'; break;
case 'u': {
//hexnumbarh - oct is deprecated
-
- for(int j=0;j<4;j++) {
- CharType c = p_str[idx+j+1];
- if (c==0) {
- r_err_str="Unterminated String";
+ for (int j = 0; j < 4; j++) {
+ CharType c = p_str[idx + j + 1];
+ if (c == 0) {
+ r_err_str = "Unterminated String";
return ERR_PARSE_ERROR;
}
- if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
- r_err_str="Malformed hex constant in string";
+ r_err_str = "Malformed hex constant in string";
return ERR_PARSE_ERROR;
}
CharType v;
- 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;
+ 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 {
ERR_PRINT("BUG");
- v=0;
+ v = 0;
}
- res<<=4;
- res|=v;
-
-
+ res <<= 4;
+ res |= v;
}
- idx+=4; //will add at the end anyway
-
+ idx += 4; //will add at the end anyway
} break;
default: {
- r_err_str="Invalid escape sequence";
+ r_err_str = "Invalid escape sequence";
return ERR_PARSE_ERROR;
} break;
}
- str+=res;
+ str += res;
} else {
- if (p_str[idx]=='\n')
+ if (p_str[idx] == '\n')
line++;
- str+=p_str[idx];
+ str += p_str[idx];
}
idx++;
}
- r_token.type=TK_STRING;
- r_token.value=str;
+ r_token.type = TK_STRING;
+ r_token.value = str;
return OK;
} break;
default: {
- if (p_str[idx]<=32) {
+ if (p_str[idx] <= 32) {
idx++;
break;
}
- if (p_str[idx]=='-' || (p_str[idx]>='0' && p_str[idx]<='9')) {
+ if (p_str[idx] == '-' || (p_str[idx] >= '0' && p_str[idx] <= '9')) {
//a number
const CharType *rptr;
- double number = String::to_double(&p_str[idx],&rptr);
- idx+=(rptr - &p_str[idx]);
- r_token.type=TK_NUMBER;
- r_token.value=number;
+ double number = String::to_double(&p_str[idx], &rptr);
+ idx += (rptr - &p_str[idx]);
+ r_token.type = TK_NUMBER;
+ r_token.value = number;
return OK;
- } else if ((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) {
+ } else if ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
String id;
- while((p_str[idx]>='A' && p_str[idx]<='Z') || (p_str[idx]>='a' && p_str[idx]<='z')) {
+ while ((p_str[idx] >= 'A' && p_str[idx] <= 'Z') || (p_str[idx] >= 'a' && p_str[idx] <= 'z')) {
- id+=p_str[idx];
+ id += p_str[idx];
idx++;
}
- r_token.type=TK_IDENTIFIER;
- r_token.value=id;
+ r_token.type = TK_IDENTIFIER;
+ r_token.value = id;
return OK;
} else {
- r_err_str="Unexpected character.";
+ r_err_str = "Unexpected character.";
return ERR_PARSE_ERROR;
}
}
-
}
}
return ERR_PARSE_ERROR;
}
+Error VariantConstruct::_parse_value(Variant &value, Token &token, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) {
-
-Error VariantConstruct::_parse_value(Variant &value,Token& token,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) {
-
-
- if (token.type==TK_CURLY_BRACKET_OPEN) {
+ if (token.type == TK_CURLY_BRACKET_OPEN) {
Dictionary d;
- Error err = _parse_dict(d,p_str,index,p_len,line,r_err_str,p_construct,p_ud);
+ Error err = _parse_dict(d, p_str, index, p_len, line, r_err_str, p_construct, p_ud);
if (err)
return err;
- value=d;
+ value = d;
return OK;
- } else if (token.type==TK_BRACKET_OPEN) {
+ } else if (token.type == TK_BRACKET_OPEN) {
Array a;
- Error err = _parse_array(a,p_str,index,p_len,line,r_err_str,p_construct,p_ud);
+ Error err = _parse_array(a, p_str, index, p_len, line, r_err_str, p_construct, p_ud);
if (err)
return err;
- value=a;
+ value = a;
return OK;
- } else if (token.type==TK_IDENTIFIER) {
+ } else if (token.type == TK_IDENTIFIER) {
String id = token.value;
- if (id=="true")
- value=true;
- else if (id=="false")
- value=false;
- else if (id=="null")
- value=Variant();
+ if (id == "true")
+ value = true;
+ else if (id == "false")
+ value = false;
+ else if (id == "null")
+ value = Variant();
else {
- r_err_str="Expected 'true','false' or 'null', got '"+id+"'.";
+ r_err_str = "Expected 'true','false' or 'null', got '" + id + "'.";
return ERR_PARSE_ERROR;
}
return OK;
- } else if (token.type==TK_NUMBER) {
+ } else if (token.type == TK_NUMBER) {
- value=token.value;
+ value = token.value;
return OK;
- } else if (token.type==TK_STRING) {
+ } else if (token.type == TK_STRING) {
- value=token.value;
+ value = token.value;
return OK;
} else {
- r_err_str="Expected value, got "+String(tk_name[token.type])+".";
+ r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
return ERR_PARSE_ERROR;
}
return ERR_PARSE_ERROR;
}
-
-Error VariantConstruct::_parse_array(Array &array,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) {
+Error VariantConstruct::_parse_array(Array &array, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) {
Token token;
- bool need_comma=false;
-
+ bool need_comma = false;
- while(index<p_len) {
+ while (index < p_len) {
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_BRACKET_CLOSE) {
+ if (token.type == TK_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected ','";
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
Variant v;
- err = _parse_value(v,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud);
+ err = _parse_value(v, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud);
if (err)
return err;
array.push_back(v);
- need_comma=true;
-
+ need_comma = true;
}
return OK;
-
}
-Error VariantConstruct::_parse_dict(Dictionary &dict,const CharType *p_str,int &index, int p_len,int &line,String &r_err_str,Variant::ObjectConstruct* p_construct,void* p_ud) {
+Error VariantConstruct::_parse_dict(Dictionary &dict, const CharType *p_str, int &index, int p_len, int &line, String &r_err_str, Variant::ObjectConstruct *p_construct, void *p_ud) {
- bool at_key=true;
+ bool at_key = true;
Variant key;
Token token;
- bool need_comma=false;
-
-
- while(index<p_len) {
+ bool need_comma = false;
+ while (index < p_len) {
if (at_key) {
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_CURLY_BRACKET_CLOSE) {
+ if (token.type == TK_CURLY_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected '}' or ','";
+ r_err_str = "Expected '}' or ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
- err = _parse_value(key,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud);
+ err = _parse_value(key, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud);
-
- if (err!=OK)
+ if (err != OK)
return err;
- err = _get_token(p_str,index,p_len,token,line,r_err_str);
+ err = _get_token(p_str, index, p_len, token, line, r_err_str);
- if (err!=OK)
+ if (err != OK)
return err;
- if (token.type!=TK_COLON) {
+ if (token.type != TK_COLON) {
- r_err_str="Expected ':'";
+ r_err_str = "Expected ':'";
return ERR_PARSE_ERROR;
}
- at_key=false;
+ at_key = false;
} else {
-
- Error err = _get_token(p_str,index,p_len,token,line,r_err_str);
- if (err!=OK)
+ Error err = _get_token(p_str, index, p_len, token, line, r_err_str);
+ if (err != OK)
return err;
Variant v;
- err = _parse_value(v,token,p_str,index,p_len,line,r_err_str,p_construct,p_ud);
+ err = _parse_value(v, token, p_str, index, p_len, line, r_err_str, p_construct, p_ud);
if (err)
return err;
- dict[key]=v;
- need_comma=true;
- at_key=true;
+ dict[key] = v;
+ need_comma = true;
+ at_key = true;
}
}
return OK;
}
-
-Error VariantConstruct::parse(const String& p_string,Variant& r_ret,String &r_err_str,int &r_err_line,Variant::ObjectConstruct* p_construct,void* p_ud) {
-
+Error VariantConstruct::parse(const String &p_string, Variant &r_ret, String &r_err_str, int &r_err_line, Variant::ObjectConstruct *p_construct, void *p_ud) {
const CharType *str = p_string.ptr();
int idx = 0;
int len = p_string.length();
Token token;
- r_err_line=0;
+ r_err_line = 0;
String aux_key;
- Error err = _get_token(str,idx,len,token,r_err_line,r_err_str);
+ Error err = _get_token(str, idx, len, token, r_err_line, r_err_str);
if (err)
return err;
- return _parse_value(r_ret,token,str,idx,len,r_err_line,r_err_str,p_construct,p_ud);
+ return _parse_value(r_ret, token, str, idx, len, r_err_line, r_err_str, p_construct, p_ud);
}
-
-
diff --git a/core/variant_op.cpp b/core/variant_op.cpp
index 28e804b5bf..71d03b159e 100644
--- a/core/variant_op.cpp
+++ b/core/variant_op.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "variant.h"
+#include "core_string_names.h"
#include "object.h"
#include "script_language.h"
-#include "core_string_names.h"
Variant::operator bool() const {
@@ -40,13 +40,13 @@ Variant::operator bool() const {
bool Variant::booleanize(bool &r_valid) const {
- r_valid=true;
- switch(type) {
+ r_valid = true;
+ switch (type) {
case NIL: return false;
case BOOL: return _data._bool;
case INT: return _data._int;
case REAL: return _data._real;
- case STRING: return (*reinterpret_cast<const String*>(_data._mem))!="";
+ case STRING: return (*reinterpret_cast<const String *>(_data._mem)) != "";
case VECTOR2:
case RECT2:
case TRANSFORM2D:
@@ -57,10 +57,10 @@ bool Variant::booleanize(bool &r_valid) const {
case BASIS:
case TRANSFORM:
case COLOR:
- case IMAGE: r_valid=false; return false;
- case _RID: return (*reinterpret_cast<const RID*>(_data._mem)).is_valid();
- case OBJECT: return _get_obj().obj;
- case NODE_PATH: return (*reinterpret_cast<const NodePath*>(_data._mem))!=NodePath();
+ case IMAGE: r_valid = false; return false;
+ case _RID: return (*reinterpret_cast<const RID *>(_data._mem)).is_valid();
+ case OBJECT: return _get_obj().obj;
+ case NODE_PATH: return (*reinterpret_cast<const NodePath *>(_data._mem)) != NodePath();
case INPUT_EVENT:
case DICTIONARY:
case ARRAY:
@@ -71,293 +71,299 @@ bool Variant::booleanize(bool &r_valid) const {
case POOL_VECTOR2_ARRAY:
case POOL_VECTOR3_ARRAY:
case POOL_COLOR_ARRAY:
- r_valid=false;
+ r_valid = false;
return false;
- default: {}
+ default: {}
}
return false;
}
-#define _RETURN(m_what) { r_ret=m_what; return; }
-
-#define DEFAULT_OP_NUM(m_op,m_name,m_type)\
-case m_name: {\
- switch(p_b.type) {\
- case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool);\
- case INT: _RETURN(p_a._data.m_type m_op p_b._data._int);\
- case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real);\
- default: {}\
- }\
- r_valid=false;\
- return;\
-};
-
-#define DEFAULT_OP_NUM_NEG(m_name,m_type)\
-case m_name: {\
-\
- _RETURN( -p_a._data.m_type);\
-};
-
-#define DEFAULT_OP_NUM_POS(m_name,m_type)\
-case m_name: {\
-\
- _RETURN( p_a._data.m_type);\
-};
-
-#define DEFAULT_OP_NUM_VEC(m_op,m_name,m_type)\
-case m_name: {\
- switch(p_b.type) {\
- case BOOL: _RETURN( p_a._data.m_type m_op p_b._data._bool);\
- case INT: _RETURN( p_a._data.m_type m_op p_b._data._int);\
- case REAL: _RETURN( p_a._data.m_type m_op p_b._data._real);\
- case VECTOR2: _RETURN( p_a._data.m_type m_op *reinterpret_cast<const Vector2*>(p_b._data._mem));\
- case VECTOR3: _RETURN( p_a._data.m_type m_op *reinterpret_cast<const Vector3*>(p_b._data._mem));\
- default: {}\
- }\
- r_valid=false;\
- return;\
-};
-
-#define DEFAULT_OP_STR(m_op,m_name,m_type)\
-case m_name: {\
- switch(p_b.type) {\
- case STRING: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const String*>(p_b._data._mem));\
- case NODE_PATH: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const NodePath*>(p_b._data._mem));\
- default: {}\
- }\
- r_valid=false;\
- return;\
-};
-
-#define DEFAULT_OP_LOCALMEM(m_op,m_name,m_type)\
-case m_name: {switch(p_b.type) {\
- case m_name: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const m_type*>(p_b._data._mem));\
- default: {}\
-}\
-r_valid=false;\
-return;}
-
+#define _RETURN(m_what) \
+ { \
+ r_ret = m_what; \
+ return; \
+ }
-#define DEFAULT_OP_LOCALMEM_NEG(m_name,m_type)\
-case m_name: {\
- _RETURN( -*reinterpret_cast<const m_type*>(p_a._data._mem));\
-}
+#define DEFAULT_OP_NUM(m_op, m_name, m_type) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool); \
+ case INT: _RETURN(p_a._data.m_type m_op p_b._data._int); \
+ case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ };
+
+#define DEFAULT_OP_NUM_NEG(m_name, m_type) \
+ case m_name: { \
+ \
+ _RETURN(-p_a._data.m_type); \
+ };
+
+#define DEFAULT_OP_NUM_POS(m_name, m_type) \
+ case m_name: { \
+ \
+ _RETURN(p_a._data.m_type); \
+ };
+
+#define DEFAULT_OP_NUM_VEC(m_op, m_name, m_type) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case BOOL: _RETURN(p_a._data.m_type m_op p_b._data._bool); \
+ case INT: _RETURN(p_a._data.m_type m_op p_b._data._int); \
+ case REAL: _RETURN(p_a._data.m_type m_op p_b._data._real); \
+ case VECTOR2: _RETURN(p_a._data.m_type m_op *reinterpret_cast<const Vector2 *>(p_b._data._mem)); \
+ case VECTOR3: _RETURN(p_a._data.m_type m_op *reinterpret_cast<const Vector3 *>(p_b._data._mem)); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ };
+
+#define DEFAULT_OP_STR(m_op, m_name, m_type) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case STRING: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const String *>(p_b._data._mem)); \
+ case NODE_PATH: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const NodePath *>(p_b._data._mem)); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ };
+
+#define DEFAULT_OP_LOCALMEM(m_op, m_name, m_type) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case m_name: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const m_type *>(p_b._data._mem)); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ }
-#define DEFAULT_OP_LOCALMEM_POS(m_name,m_type)\
-case m_name: {\
- _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem));\
-}
+#define DEFAULT_OP_LOCALMEM_NEG(m_name, m_type) \
+ case m_name: { \
+ _RETURN(-*reinterpret_cast<const m_type *>(p_a._data._mem)); \
+ }
-#define DEFAULT_OP_LOCALMEM_NUM(m_op,m_name,m_type)\
-case m_name: {switch(p_b.type) {\
- case m_name: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op *reinterpret_cast<const m_type*>(p_b._data._mem));\
- case BOOL: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._bool);\
- case INT: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._int);\
- case REAL: _RETURN( *reinterpret_cast<const m_type*>(p_a._data._mem) m_op p_b._data._real);\
- default: {}\
-}\
-r_valid=false;\
-return;}
-
-#define DEFAULT_OP_PTR(m_op,m_name,m_sub)\
-case m_name: {switch(p_b.type) {\
- case m_name: _RETURN( p_a._data.m_sub m_op p_b._data.m_sub);\
- default: {}\
-}\
-r_valid=false;\
-return;}
-
-#define DEFAULT_OP_PTRREF(m_op,m_name,m_sub)\
-case m_name: {switch(p_b.type) {\
- case m_name: _RETURN( *p_a._data.m_sub m_op *p_b._data.m_sub);\
- default: {}\
-}\
-r_valid=false;\
-return;}
-
-#define DEFAULT_OP_ARRAY_EQ(m_name,m_type)\
-DEFAULT_OP_ARRAY_OP(m_name,m_type,!=,!=,true,false,false)
-
-#define DEFAULT_OP_ARRAY_LT(m_name,m_type)\
-DEFAULT_OP_ARRAY_OP(m_name,m_type,<,!=,false,a_len<array_b.size(),true)
-
-#define DEFAULT_OP_ARRAY_OP(m_name,m_type,m_opa,m_opb,m_ret_def,m_ret_s,m_ret_f)\
-case m_name: { \
- if (p_a.type!=p_b.type) {\
- r_valid=false;\
- return;\
- }\
- const PoolVector<m_type> &array_a=*reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem);\
- const PoolVector<m_type> &array_b=*reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem);\
-\
- int a_len = array_a.size();\
- if (a_len m_opa array_b.size()){\
- _RETURN( m_ret_s);\
- }else {\
-\
- PoolVector<m_type>::Read ra = array_a.read();\
- PoolVector<m_type>::Read rb = array_b.read();\
-\
- for(int i=0;i<a_len;i++) {\
- if (ra[i] m_opb rb[i])\
- _RETURN( m_ret_f);\
- }\
-\
- _RETURN( m_ret_def);\
- }\
-}
+#define DEFAULT_OP_LOCALMEM_POS(m_name, m_type) \
+ case m_name: { \
+ _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem)); \
+ }
-#define DEFAULT_OP_ARRAY_ADD(m_name,m_type)\
-case m_name: { \
- if (p_a.type!=p_b.type) {\
- r_valid=false;\
- _RETURN( NIL);\
- }\
- const PoolVector<m_type> &array_a=*reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem);\
- const PoolVector<m_type> &array_b=*reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem);\
- PoolVector<m_type> sum = array_a;\
- sum.append_array(array_b);\
- _RETURN( sum );\
-}
+#define DEFAULT_OP_LOCALMEM_NUM(m_op, m_name, m_type) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case m_name: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op *reinterpret_cast<const m_type *>(p_b._data._mem)); \
+ case BOOL: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._bool); \
+ case INT: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._int); \
+ case REAL: _RETURN(*reinterpret_cast<const m_type *>(p_a._data._mem) m_op p_b._data._real); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ }
+#define DEFAULT_OP_PTR(m_op, m_name, m_sub) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case m_name: _RETURN(p_a._data.m_sub m_op p_b._data.m_sub); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ }
+#define DEFAULT_OP_PTRREF(m_op, m_name, m_sub) \
+ case m_name: { \
+ switch (p_b.type) { \
+ case m_name: _RETURN(*p_a._data.m_sub m_op *p_b._data.m_sub); \
+ default: {} \
+ } \
+ r_valid = false; \
+ return; \
+ }
-#define DEFAULT_OP_FAIL(m_name)\
-case m_name: {r_valid=false;\
-return;}
+#define DEFAULT_OP_ARRAY_EQ(m_name, m_type) \
+ DEFAULT_OP_ARRAY_OP(m_name, m_type, !=, !=, true, false, false)
+
+#define DEFAULT_OP_ARRAY_LT(m_name, m_type) \
+ DEFAULT_OP_ARRAY_OP(m_name, m_type, <, !=, false, a_len < array_b.size(), true)
+
+#define DEFAULT_OP_ARRAY_OP(m_name, m_type, m_opa, m_opb, m_ret_def, m_ret_s, m_ret_f) \
+ case m_name: { \
+ if (p_a.type != p_b.type) { \
+ r_valid = false; \
+ return; \
+ } \
+ const PoolVector<m_type> &array_a = *reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem); \
+ const PoolVector<m_type> &array_b = *reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem); \
+ \
+ int a_len = array_a.size(); \
+ if (a_len m_opa array_b.size()) { \
+ _RETURN(m_ret_s); \
+ } else { \
+ \
+ PoolVector<m_type>::Read ra = array_a.read(); \
+ PoolVector<m_type>::Read rb = array_b.read(); \
+ \
+ for (int i = 0; i < a_len; i++) { \
+ if (ra[i] m_opb rb[i]) \
+ _RETURN(m_ret_f); \
+ } \
+ \
+ _RETURN(m_ret_def); \
+ } \
+ }
+#define DEFAULT_OP_ARRAY_ADD(m_name, m_type) \
+ case m_name: { \
+ if (p_a.type != p_b.type) { \
+ r_valid = false; \
+ _RETURN(NIL); \
+ } \
+ const PoolVector<m_type> &array_a = *reinterpret_cast<const PoolVector<m_type> *>(p_a._data._mem); \
+ const PoolVector<m_type> &array_b = *reinterpret_cast<const PoolVector<m_type> *>(p_b._data._mem); \
+ PoolVector<m_type> sum = array_a; \
+ sum.append_array(array_b); \
+ _RETURN(sum); \
+ }
-void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant& p_b, Variant &r_ret, bool &r_valid) {
+#define DEFAULT_OP_FAIL(m_name) \
+ case m_name: { \
+ r_valid = false; \
+ return; \
+ }
+void Variant::evaluate(const Operator &p_op, const Variant &p_a, const Variant &p_b, Variant &r_ret, bool &r_valid) {
- r_valid=true;
+ r_valid = true;
- switch(p_op) {
+ switch (p_op) {
case OP_EQUAL: {
- if ((int(p_a.type)*int(p_b.type))==0) {
+ if ((int(p_a.type) * int(p_b.type)) == 0) {
//null case is an exception, one of both is null
- if (p_a.type==p_b.type) //null against null is true
+ if (p_a.type == p_b.type) //null against null is true
_RETURN(true);
//only against object is allowed
- if (p_a.type==Variant::OBJECT) {
- _RETURN(p_a._get_obj().obj==NULL);
- } else if (p_b.type==Variant::OBJECT) {
- _RETURN(p_b._get_obj().obj==NULL);
+ if (p_a.type == Variant::OBJECT) {
+ _RETURN(p_a._get_obj().obj == NULL);
+ } else if (p_b.type == Variant::OBJECT) {
+ _RETURN(p_b._get_obj().obj == NULL);
}
//otherwise, always false
_RETURN(false);
}
- switch(p_a.type) {
+ switch (p_a.type) {
case NIL: {
- _RETURN(p_b.type==NIL || (p_b.type==Variant::OBJECT && !p_b._get_obj().obj));
+ _RETURN(p_b.type == NIL || (p_b.type == Variant::OBJECT && !p_b._get_obj().obj));
} break;
- DEFAULT_OP_NUM(==,BOOL,_bool);
- DEFAULT_OP_NUM(==,INT,_int);
- DEFAULT_OP_NUM(==,REAL,_real);
- DEFAULT_OP_STR(==,STRING,String);
- DEFAULT_OP_LOCALMEM(==,VECTOR2,Vector2);
- DEFAULT_OP_LOCALMEM(==,RECT2,Rect2);
- DEFAULT_OP_PTRREF(==,TRANSFORM2D,_transform2d);
- DEFAULT_OP_LOCALMEM(==,VECTOR3,Vector3);
- DEFAULT_OP_LOCALMEM(==,PLANE,Plane);
- DEFAULT_OP_LOCALMEM(==,QUAT,Quat);
- DEFAULT_OP_PTRREF(==,RECT3,_rect3);
- DEFAULT_OP_PTRREF(==,BASIS,_basis);
- DEFAULT_OP_PTRREF(==,TRANSFORM,_transform);
-
- DEFAULT_OP_LOCALMEM(==,COLOR,Color);
- DEFAULT_OP_PTRREF(==,IMAGE,_image);
- DEFAULT_OP_STR(==,NODE_PATH,NodePath);
- DEFAULT_OP_LOCALMEM(==,_RID,RID);
+ DEFAULT_OP_NUM(==, BOOL, _bool);
+ DEFAULT_OP_NUM(==, INT, _int);
+ DEFAULT_OP_NUM(==, REAL, _real);
+ DEFAULT_OP_STR(==, STRING, String);
+ DEFAULT_OP_LOCALMEM(==, VECTOR2, Vector2);
+ DEFAULT_OP_LOCALMEM(==, RECT2, Rect2);
+ DEFAULT_OP_PTRREF(==, TRANSFORM2D, _transform2d);
+ DEFAULT_OP_LOCALMEM(==, VECTOR3, Vector3);
+ DEFAULT_OP_LOCALMEM(==, PLANE, Plane);
+ DEFAULT_OP_LOCALMEM(==, QUAT, Quat);
+ DEFAULT_OP_PTRREF(==, RECT3, _rect3);
+ DEFAULT_OP_PTRREF(==, BASIS, _basis);
+ DEFAULT_OP_PTRREF(==, TRANSFORM, _transform);
+
+ DEFAULT_OP_LOCALMEM(==, COLOR, Color);
+ DEFAULT_OP_PTRREF(==, IMAGE, _image);
+ DEFAULT_OP_STR(==, NODE_PATH, NodePath);
+ DEFAULT_OP_LOCALMEM(==, _RID, RID);
case OBJECT: {
- if (p_b.type==OBJECT)
- _RETURN( (p_a._get_obj().obj == p_b._get_obj().obj) );
- if (p_b.type==NIL)
- _RETURN( !p_a._get_obj().obj );
+ if (p_b.type == OBJECT)
+ _RETURN((p_a._get_obj().obj == p_b._get_obj().obj));
+ if (p_b.type == NIL)
+ _RETURN(!p_a._get_obj().obj);
} break;
- DEFAULT_OP_PTRREF(==,INPUT_EVENT,_input_event);
+ DEFAULT_OP_PTRREF(==, INPUT_EVENT, _input_event);
case DICTIONARY: {
- if (p_b.type!=DICTIONARY)
- _RETURN( false );
+ if (p_b.type != DICTIONARY)
+ _RETURN(false);
- const Dictionary *arr_a=reinterpret_cast<const Dictionary*>(p_a._data._mem);
- const Dictionary *arr_b=reinterpret_cast<const Dictionary*>(p_b._data._mem);
+ const Dictionary *arr_a = reinterpret_cast<const Dictionary *>(p_a._data._mem);
+ const Dictionary *arr_b = reinterpret_cast<const Dictionary *>(p_b._data._mem);
- _RETURN( *arr_a == *arr_b );
+ _RETURN(*arr_a == *arr_b);
} break;
case ARRAY: {
- if (p_b.type!=ARRAY)
- _RETURN( false );
+ if (p_b.type != ARRAY)
+ _RETURN(false);
- const Array *arr_a=reinterpret_cast<const Array*>(p_a._data._mem);
- const Array *arr_b=reinterpret_cast<const Array*>(p_b._data._mem);
+ const Array *arr_a = reinterpret_cast<const Array *>(p_a._data._mem);
+ const Array *arr_b = reinterpret_cast<const Array *>(p_b._data._mem);
int l = arr_a->size();
- if (arr_b->size()!=l)
- _RETURN( false );
- for(int i=0;i<l;i++) {
- if (!((*arr_a)[i]==(*arr_b)[i])) {
- _RETURN( false );
+ if (arr_b->size() != l)
+ _RETURN(false);
+ for (int i = 0; i < l; i++) {
+ if (!((*arr_a)[i] == (*arr_b)[i])) {
+ _RETURN(false);
}
}
- _RETURN( true );
+ _RETURN(true);
} break;
-
- DEFAULT_OP_ARRAY_EQ(POOL_BYTE_ARRAY,uint8_t);
- DEFAULT_OP_ARRAY_EQ(POOL_INT_ARRAY,int);
- DEFAULT_OP_ARRAY_EQ(POOL_REAL_ARRAY,real_t);
- DEFAULT_OP_ARRAY_EQ(POOL_STRING_ARRAY,String);
- DEFAULT_OP_ARRAY_EQ(POOL_VECTOR2_ARRAY,Vector3);
- DEFAULT_OP_ARRAY_EQ(POOL_VECTOR3_ARRAY,Vector3);
- DEFAULT_OP_ARRAY_EQ(POOL_COLOR_ARRAY,Color);
+ DEFAULT_OP_ARRAY_EQ(POOL_BYTE_ARRAY, uint8_t);
+ DEFAULT_OP_ARRAY_EQ(POOL_INT_ARRAY, int);
+ DEFAULT_OP_ARRAY_EQ(POOL_REAL_ARRAY, real_t);
+ DEFAULT_OP_ARRAY_EQ(POOL_STRING_ARRAY, String);
+ DEFAULT_OP_ARRAY_EQ(POOL_VECTOR2_ARRAY, Vector3);
+ DEFAULT_OP_ARRAY_EQ(POOL_VECTOR3_ARRAY, Vector3);
+ DEFAULT_OP_ARRAY_EQ(POOL_COLOR_ARRAY, Color);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
-
}
} break;
case OP_NOT_EQUAL: {
Variant res;
- evaluate(OP_EQUAL,p_a,p_b,res,r_valid);
+ evaluate(OP_EQUAL, p_a, p_b, res, r_valid);
if (!r_valid)
return;
- if (res.type==BOOL)
- res._data._bool=!res._data._bool;
- _RETURN( res );
+ if (res.type == BOOL)
+ res._data._bool = !res._data._bool;
+ _RETURN(res);
} break;
case OP_LESS: {
- switch(p_a.type) {
+ switch (p_a.type) {
DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(<,BOOL,_bool);
- DEFAULT_OP_NUM(<,INT,_int);
- DEFAULT_OP_NUM(<,REAL,_real);
- DEFAULT_OP_STR(<,STRING,String);
- DEFAULT_OP_LOCALMEM(<,VECTOR2,Vector2);
+ DEFAULT_OP_NUM(<, BOOL, _bool);
+ DEFAULT_OP_NUM(<, INT, _int);
+ DEFAULT_OP_NUM(<, REAL, _real);
+ DEFAULT_OP_STR(<, STRING, String);
+ DEFAULT_OP_LOCALMEM(<, VECTOR2, Vector2);
DEFAULT_OP_FAIL(RECT2);
DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM(<,VECTOR3,Vector3);
+ DEFAULT_OP_LOCALMEM(<, VECTOR3, Vector3);
DEFAULT_OP_FAIL(PLANE);
DEFAULT_OP_FAIL(QUAT);
DEFAULT_OP_FAIL(RECT3);
@@ -367,63 +373,62 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
DEFAULT_OP_FAIL(COLOR);
DEFAULT_OP_FAIL(IMAGE);
DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_LOCALMEM(<,_RID,RID);
+ DEFAULT_OP_LOCALMEM(<, _RID, RID);
case OBJECT: {
- if (p_b.type==OBJECT)
- _RETURN( (p_a._get_obj().obj < p_b._get_obj().obj) );
+ if (p_b.type == OBJECT)
+ _RETURN((p_a._get_obj().obj < p_b._get_obj().obj));
} break;
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
case ARRAY: {
- if (p_b.type!=ARRAY)
- _RETURN( false );
+ if (p_b.type != ARRAY)
+ _RETURN(false);
- const Array *arr_a=reinterpret_cast<const Array*>(p_a._data._mem);
- const Array *arr_b=reinterpret_cast<const Array*>(p_b._data._mem);
+ const Array *arr_a = reinterpret_cast<const Array *>(p_a._data._mem);
+ const Array *arr_b = reinterpret_cast<const Array *>(p_b._data._mem);
int l = arr_a->size();
- if (arr_b->size()<l)
- _RETURN( false );
- for(int i=0;i<l;i++) {
- if (!((*arr_a)[i]<(*arr_b)[i])) {
- _RETURN( true );
+ if (arr_b->size() < l)
+ _RETURN(false);
+ for (int i = 0; i < l; i++) {
+ if (!((*arr_a)[i] < (*arr_b)[i])) {
+ _RETURN(true);
}
}
- _RETURN( false );
+ _RETURN(false);
} break;
- DEFAULT_OP_ARRAY_LT(POOL_BYTE_ARRAY,uint8_t);
- DEFAULT_OP_ARRAY_LT(POOL_INT_ARRAY,int);
- DEFAULT_OP_ARRAY_LT(POOL_REAL_ARRAY,real_t);
- DEFAULT_OP_ARRAY_LT(POOL_STRING_ARRAY,String);
- DEFAULT_OP_ARRAY_LT(POOL_VECTOR2_ARRAY,Vector3);
- DEFAULT_OP_ARRAY_LT(POOL_VECTOR3_ARRAY,Vector3);
- DEFAULT_OP_ARRAY_LT(POOL_COLOR_ARRAY,Color);
+ DEFAULT_OP_ARRAY_LT(POOL_BYTE_ARRAY, uint8_t);
+ DEFAULT_OP_ARRAY_LT(POOL_INT_ARRAY, int);
+ DEFAULT_OP_ARRAY_LT(POOL_REAL_ARRAY, real_t);
+ DEFAULT_OP_ARRAY_LT(POOL_STRING_ARRAY, String);
+ DEFAULT_OP_ARRAY_LT(POOL_VECTOR2_ARRAY, Vector3);
+ DEFAULT_OP_ARRAY_LT(POOL_VECTOR3_ARRAY, Vector3);
+ DEFAULT_OP_ARRAY_LT(POOL_COLOR_ARRAY, Color);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
}
} break;
case OP_LESS_EQUAL: {
- switch(p_a.type) {
+ switch (p_a.type) {
DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(<=,BOOL,_bool);
- DEFAULT_OP_NUM(<=,INT,_int);
- DEFAULT_OP_NUM(<=,REAL,_real);
- DEFAULT_OP_STR(<=,STRING,String);
- DEFAULT_OP_LOCALMEM(<=,VECTOR2,Vector2);
+ DEFAULT_OP_NUM(<=, BOOL, _bool);
+ DEFAULT_OP_NUM(<=, INT, _int);
+ DEFAULT_OP_NUM(<=, REAL, _real);
+ DEFAULT_OP_STR(<=, STRING, String);
+ DEFAULT_OP_LOCALMEM(<=, VECTOR2, Vector2);
DEFAULT_OP_FAIL(RECT2);
DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM(<=,VECTOR3,Vector3);
+ DEFAULT_OP_LOCALMEM(<=, VECTOR3, Vector3);
DEFAULT_OP_FAIL(PLANE);
DEFAULT_OP_FAIL(QUAT);
DEFAULT_OP_FAIL(RECT3);
@@ -433,35 +438,34 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
DEFAULT_OP_FAIL(COLOR);
DEFAULT_OP_FAIL(IMAGE);
DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_LOCALMEM(<=,_RID,RID);
+ DEFAULT_OP_LOCALMEM(<=, _RID, RID);
case OBJECT: {
- if (p_b.type==OBJECT)
- _RETURN( (p_a._get_obj().obj <= p_b._get_obj().obj) );
+ if (p_b.type == OBJECT)
+ _RETURN((p_a._get_obj().obj <= p_b._get_obj().obj));
} break;
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
- DEFAULT_OP_FAIL(ARRAY);
- DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
- DEFAULT_OP_FAIL(POOL_INT_ARRAY);
- DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
- DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
- DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(ARRAY);
+ DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
+ DEFAULT_OP_FAIL(POOL_INT_ARRAY);
+ DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
+ DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
+ DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
}
} break;
case OP_GREATER: {
Variant res;
- evaluate(OP_LESS,p_b,p_a,res,r_valid);
+ evaluate(OP_LESS, p_b, p_a, res, r_valid);
if (!r_valid)
return;
_RETURN(res);
@@ -470,82 +474,81 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
case OP_GREATER_EQUAL: {
Variant res;
- evaluate(OP_LESS_EQUAL,p_b,p_a,res,r_valid);
+ evaluate(OP_LESS_EQUAL, p_b, p_a, res, r_valid);
if (!r_valid)
return;
- _RETURN( res );
+ _RETURN(res);
} break;
//mathematic
case OP_ADD: {
- switch(p_a.type) {
-
- DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(+,BOOL,_bool);
- DEFAULT_OP_NUM(+,INT,_int);
- DEFAULT_OP_NUM(+,REAL,_real);
- DEFAULT_OP_STR(+,STRING,String);
- DEFAULT_OP_LOCALMEM(+,VECTOR2,Vector2);
- DEFAULT_OP_FAIL(RECT2);
- DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM(+,VECTOR3,Vector3);
- DEFAULT_OP_FAIL(PLANE);
- DEFAULT_OP_LOCALMEM(+, QUAT, Quat);
- DEFAULT_OP_FAIL(RECT3);
- DEFAULT_OP_FAIL(BASIS);
- DEFAULT_OP_FAIL(TRANSFORM);
+ switch (p_a.type) {
- DEFAULT_OP_FAIL(COLOR);
- DEFAULT_OP_FAIL(IMAGE);
- DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_FAIL(_RID);
- DEFAULT_OP_FAIL(OBJECT);
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(NIL);
+ DEFAULT_OP_NUM(+, BOOL, _bool);
+ DEFAULT_OP_NUM(+, INT, _int);
+ DEFAULT_OP_NUM(+, REAL, _real);
+ DEFAULT_OP_STR(+, STRING, String);
+ DEFAULT_OP_LOCALMEM(+, VECTOR2, Vector2);
+ DEFAULT_OP_FAIL(RECT2);
+ DEFAULT_OP_FAIL(TRANSFORM2D);
+ DEFAULT_OP_LOCALMEM(+, VECTOR3, Vector3);
+ DEFAULT_OP_FAIL(PLANE);
+ DEFAULT_OP_LOCALMEM(+, QUAT, Quat);
+ DEFAULT_OP_FAIL(RECT3);
+ DEFAULT_OP_FAIL(BASIS);
+ DEFAULT_OP_FAIL(TRANSFORM);
- case ARRAY: {
- if (p_a.type!=p_b.type) {
- r_valid=false;
- return;
- }
- const Array &array_a=*reinterpret_cast<const Array *>(p_a._data._mem);
- const Array &array_b=*reinterpret_cast<const Array *>(p_b._data._mem);
- Array sum;
- int asize=array_a.size();
- int bsize=array_b.size();
- sum.resize(asize+bsize);
- for(int i=0;i<asize;i++)
- sum[i]=array_a[i];
- for(int i=0;i<bsize;i++)
- sum[i+asize]=array_b[i];
- _RETURN( sum );
- }
- DEFAULT_OP_ARRAY_ADD(POOL_BYTE_ARRAY,uint8_t);
- DEFAULT_OP_ARRAY_ADD(POOL_INT_ARRAY,int);
- DEFAULT_OP_ARRAY_ADD(POOL_REAL_ARRAY,real_t);
- DEFAULT_OP_ARRAY_ADD(POOL_STRING_ARRAY,String);
- DEFAULT_OP_ARRAY_ADD(POOL_VECTOR2_ARRAY,Vector2);
- DEFAULT_OP_ARRAY_ADD(POOL_VECTOR3_ARRAY,Vector3);
- DEFAULT_OP_ARRAY_ADD(POOL_COLOR_ARRAY,Color);
- case VARIANT_MAX: {
- r_valid=false;
- return;
+ DEFAULT_OP_FAIL(COLOR);
+ DEFAULT_OP_FAIL(IMAGE);
+ DEFAULT_OP_FAIL(NODE_PATH);
+ DEFAULT_OP_FAIL(_RID);
+ DEFAULT_OP_FAIL(OBJECT);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
- } break;
+ case ARRAY: {
+ if (p_a.type != p_b.type) {
+ r_valid = false;
+ return;
+ }
+ const Array &array_a = *reinterpret_cast<const Array *>(p_a._data._mem);
+ const Array &array_b = *reinterpret_cast<const Array *>(p_b._data._mem);
+ Array sum;
+ int asize = array_a.size();
+ int bsize = array_b.size();
+ sum.resize(asize + bsize);
+ for (int i = 0; i < asize; i++)
+ sum[i] = array_a[i];
+ for (int i = 0; i < bsize; i++)
+ sum[i + asize] = array_b[i];
+ _RETURN(sum);
+ }
+ DEFAULT_OP_ARRAY_ADD(POOL_BYTE_ARRAY, uint8_t);
+ DEFAULT_OP_ARRAY_ADD(POOL_INT_ARRAY, int);
+ DEFAULT_OP_ARRAY_ADD(POOL_REAL_ARRAY, real_t);
+ DEFAULT_OP_ARRAY_ADD(POOL_STRING_ARRAY, String);
+ DEFAULT_OP_ARRAY_ADD(POOL_VECTOR2_ARRAY, Vector2);
+ DEFAULT_OP_ARRAY_ADD(POOL_VECTOR3_ARRAY, Vector3);
+ DEFAULT_OP_ARRAY_ADD(POOL_COLOR_ARRAY, Color);
+ case VARIANT_MAX: {
+ r_valid = false;
+ return;
- }
+ } break;
+ }
} break;
case OP_SUBSTRACT: {
- switch(p_a.type) {
+ switch (p_a.type) {
DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(-,BOOL,_bool);
- DEFAULT_OP_NUM(-,INT,_int);
- DEFAULT_OP_NUM(-,REAL,_real);
+ DEFAULT_OP_NUM(-, BOOL, _bool);
+ DEFAULT_OP_NUM(-, INT, _int);
+ DEFAULT_OP_NUM(-, REAL, _real);
DEFAULT_OP_FAIL(STRING);
- DEFAULT_OP_LOCALMEM(-,VECTOR2,Vector2);
+ DEFAULT_OP_LOCALMEM(-, VECTOR2, Vector2);
DEFAULT_OP_FAIL(RECT2);
DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM(-,VECTOR3,Vector3);
+ DEFAULT_OP_LOCALMEM(-, VECTOR3, Vector3);
DEFAULT_OP_FAIL(PLANE);
DEFAULT_OP_LOCALMEM(-, QUAT, Quat);
DEFAULT_OP_FAIL(RECT3);
@@ -568,165 +571,201 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
}
} break;
case OP_MULTIPLY: {
- switch(p_a.type) {
+ switch (p_a.type) {
DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(*,BOOL,_bool);
- DEFAULT_OP_NUM_VEC(*,INT,_int);
- DEFAULT_OP_NUM_VEC(*,REAL,_real);
+ DEFAULT_OP_NUM(*, BOOL, _bool);
+ DEFAULT_OP_NUM_VEC(*, INT, _int);
+ DEFAULT_OP_NUM_VEC(*, REAL, _real);
DEFAULT_OP_FAIL(STRING);
- DEFAULT_OP_LOCALMEM_NUM(*,VECTOR2,Vector2);
+ DEFAULT_OP_LOCALMEM_NUM(*, VECTOR2, Vector2);
DEFAULT_OP_FAIL(RECT2);
case TRANSFORM2D: {
- if (p_b.type==TRANSFORM2D) {
- _RETURN( *p_a._data._transform2d * *p_b._data._transform2d );
+ if (p_b.type == TRANSFORM2D) {
+ _RETURN(*p_a._data._transform2d * *p_b._data._transform2d);
};
- if (p_b.type==VECTOR2) {
- _RETURN( p_a._data._transform2d->xform( *(const Vector2*)p_b._data._mem) );
+ if (p_b.type == VECTOR2) {
+ _RETURN(p_a._data._transform2d->xform(*(const Vector2 *)p_b._data._mem));
};
- r_valid=false;
+ r_valid = false;
return;
} break;
- DEFAULT_OP_LOCALMEM_NUM(*,VECTOR3,Vector3);
- DEFAULT_OP_FAIL(PLANE);
+ DEFAULT_OP_LOCALMEM_NUM(*, VECTOR3, Vector3);
+ DEFAULT_OP_FAIL(PLANE);
case QUAT: {
- switch(p_b.type) {
+ switch (p_b.type) {
case VECTOR3: {
- _RETURN( reinterpret_cast<const Quat*>(p_a._data._mem)->xform( *(const Vector3*)p_b._data._mem) );
+ _RETURN(reinterpret_cast<const Quat *>(p_a._data._mem)->xform(*(const Vector3 *)p_b._data._mem));
} break;
case QUAT: {
- _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) * *reinterpret_cast<const Quat*>(p_b._data._mem) );
+ _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) * *reinterpret_cast<const Quat *>(p_b._data._mem));
} break;
case REAL: {
- _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) * p_b._data._real);
+ _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) * p_b._data._real);
} break;
default: {}
};
- r_valid=false;
+ r_valid = false;
return;
} break;
- DEFAULT_OP_FAIL(RECT3);
+ DEFAULT_OP_FAIL(RECT3);
case BASIS: {
- switch(p_b.type) {
+ switch (p_b.type) {
case VECTOR3: {
- _RETURN( p_a._data._basis->xform( *(const Vector3*)p_b._data._mem) );
-
- } ;
+ _RETURN(p_a._data._basis->xform(*(const Vector3 *)p_b._data._mem));
+ };
case BASIS: {
- _RETURN( *p_a._data._basis * *p_b._data._basis );
-
+ _RETURN(*p_a._data._basis * *p_b._data._basis);
};
default: {}
- } ;
- r_valid=false;
+ };
+ r_valid = false;
return;
} break;
case TRANSFORM: {
- switch(p_b.type) {
+ switch (p_b.type) {
case VECTOR3: {
- _RETURN( p_a._data._transform->xform( *(const Vector3*)p_b._data._mem) );
-
- } ;
+ _RETURN(p_a._data._transform->xform(*(const Vector3 *)p_b._data._mem));
+ };
case TRANSFORM: {
- _RETURN( *p_a._data._transform * *p_b._data._transform );
-
+ _RETURN(*p_a._data._transform * *p_b._data._transform);
};
default: {}
- } ;
- r_valid=false;
+ };
+ r_valid = false;
return;
} break;
- DEFAULT_OP_FAIL(COLOR);
- DEFAULT_OP_FAIL(IMAGE);
- DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_FAIL(_RID);
- DEFAULT_OP_FAIL(OBJECT);
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
- DEFAULT_OP_FAIL(ARRAY);
- DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
- DEFAULT_OP_FAIL(POOL_INT_ARRAY);
- DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
- DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
- DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
+ DEFAULT_OP_FAIL(COLOR);
+ DEFAULT_OP_FAIL(IMAGE);
+ DEFAULT_OP_FAIL(NODE_PATH);
+ DEFAULT_OP_FAIL(_RID);
+ DEFAULT_OP_FAIL(OBJECT);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(ARRAY);
+ DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
+ DEFAULT_OP_FAIL(POOL_INT_ARRAY);
+ DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
+ DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
+ DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
}
} break;
case OP_DIVIDE: {
- switch(p_a.type) {
+ switch (p_a.type) {
DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM(/,BOOL,_bool);
+ DEFAULT_OP_NUM(/, BOOL, _bool);
case INT: {
- switch(p_b.type) {
+ switch (p_b.type) {
case BOOL: {
int64_t b = p_b._data._bool;
- if (b==0) {
+ if (b == 0) {
- r_valid=false;
- _RETURN( "Division By False" );
+ r_valid = false;
+ _RETURN("Division By False");
}
- _RETURN( p_a._data._int / b );
+ _RETURN(p_a._data._int / b);
} break;
case INT: {
int64_t b = p_b._data._int;
- if (b==0) {
+ if (b == 0) {
- r_valid=false;
- _RETURN( "Division By Zero" );
+ r_valid = false;
+ _RETURN("Division By Zero");
}
- _RETURN( p_a._data._int / b );
+ _RETURN(p_a._data._int / b);
} break;
- case REAL: _RETURN( p_a._data._int / p_b._data._real );
+ case REAL: _RETURN(p_a._data._int / p_b._data._real);
default: {}
}
- r_valid=false;
+ r_valid = false;
return;
};
- DEFAULT_OP_NUM(/,REAL,_real);
- DEFAULT_OP_FAIL(STRING);
- DEFAULT_OP_LOCALMEM_NUM(/,VECTOR2,Vector2);
- DEFAULT_OP_FAIL(RECT2);
- DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM_NUM(/,VECTOR3,Vector3);
- DEFAULT_OP_FAIL(PLANE);
+ DEFAULT_OP_NUM(/, REAL, _real);
+ DEFAULT_OP_FAIL(STRING);
+ DEFAULT_OP_LOCALMEM_NUM(/, VECTOR2, Vector2);
+ DEFAULT_OP_FAIL(RECT2);
+ DEFAULT_OP_FAIL(TRANSFORM2D);
+ DEFAULT_OP_LOCALMEM_NUM(/, VECTOR3, Vector3);
+ DEFAULT_OP_FAIL(PLANE);
case QUAT: {
if (p_b.type != REAL) {
r_valid = false;
return;
}
- _RETURN( *reinterpret_cast<const Quat*>(p_a._data._mem) / p_b._data._real);
+ _RETURN(*reinterpret_cast<const Quat *>(p_a._data._mem) / p_b._data._real);
} break;
+ DEFAULT_OP_FAIL(RECT3);
+ DEFAULT_OP_FAIL(BASIS);
+ DEFAULT_OP_FAIL(TRANSFORM);
+
+ DEFAULT_OP_FAIL(COLOR);
+ DEFAULT_OP_FAIL(IMAGE);
+ DEFAULT_OP_FAIL(NODE_PATH);
+ DEFAULT_OP_FAIL(_RID);
+ DEFAULT_OP_FAIL(OBJECT);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(ARRAY);
+ DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
+ DEFAULT_OP_FAIL(POOL_INT_ARRAY);
+ DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
+ DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
+ DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
+ case VARIANT_MAX: {
+ r_valid = false;
+ return;
+
+ } break;
+ }
+
+ } break;
+ case OP_POSITIVE: {
+ // Simple case when user defines variable as +value.
+ switch (p_a.type) {
+
+ DEFAULT_OP_FAIL(NIL);
+ DEFAULT_OP_FAIL(STRING);
+ DEFAULT_OP_FAIL(RECT2);
+ DEFAULT_OP_FAIL(TRANSFORM2D);
DEFAULT_OP_FAIL(RECT3);
DEFAULT_OP_FAIL(BASIS);
DEFAULT_OP_FAIL(TRANSFORM);
+ DEFAULT_OP_NUM_POS(BOOL, _bool);
+ DEFAULT_OP_NUM_POS(INT, _int);
+ DEFAULT_OP_NUM_POS(REAL, _real);
+ DEFAULT_OP_LOCALMEM_POS(VECTOR3, Vector3);
+ DEFAULT_OP_LOCALMEM_POS(PLANE, Plane);
+ DEFAULT_OP_LOCALMEM_POS(QUAT, Quat);
+ DEFAULT_OP_LOCALMEM_POS(VECTOR2, Vector2);
DEFAULT_OP_FAIL(COLOR);
DEFAULT_OP_FAIL(IMAGE);
@@ -744,182 +783,138 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
case VARIANT_MAX: {
- r_valid=false;
+ r_valid = false;
return;
} break;
-
}
-
- } break;
- case OP_POSITIVE: {
- // Simple case when user defines variable as +value.
- switch(p_a.type) {
-
- DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_FAIL(STRING);
- DEFAULT_OP_FAIL(RECT2);
- DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_FAIL(RECT3);
- DEFAULT_OP_FAIL(BASIS);
- DEFAULT_OP_FAIL(TRANSFORM);
- DEFAULT_OP_NUM_POS(BOOL,_bool);
- DEFAULT_OP_NUM_POS(INT,_int);
- DEFAULT_OP_NUM_POS(REAL,_real);
- DEFAULT_OP_LOCALMEM_POS(VECTOR3,Vector3);
- DEFAULT_OP_LOCALMEM_POS(PLANE,Plane);
- DEFAULT_OP_LOCALMEM_POS(QUAT,Quat);
- DEFAULT_OP_LOCALMEM_POS(VECTOR2,Vector2);
-
- DEFAULT_OP_FAIL(COLOR);
- DEFAULT_OP_FAIL(IMAGE);
- DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_FAIL(_RID);
- DEFAULT_OP_FAIL(OBJECT);
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
- DEFAULT_OP_FAIL(ARRAY);
- DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
- DEFAULT_OP_FAIL(POOL_INT_ARRAY);
- DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
- DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
- DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
- case VARIANT_MAX: {
- r_valid=false;
- return;
-
- } break;
-
- }
} break;
case OP_NEGATE: {
- switch(p_a.type) {
+ switch (p_a.type) {
- DEFAULT_OP_FAIL(NIL);
- DEFAULT_OP_NUM_NEG(BOOL,_bool);
- DEFAULT_OP_NUM_NEG(INT,_int);
- DEFAULT_OP_NUM_NEG(REAL,_real);
- DEFAULT_OP_FAIL(STRING);
- DEFAULT_OP_LOCALMEM_NEG(VECTOR2,Vector2);
- DEFAULT_OP_FAIL(RECT2);
- DEFAULT_OP_FAIL(TRANSFORM2D);
- DEFAULT_OP_LOCALMEM_NEG(VECTOR3,Vector3);
- DEFAULT_OP_LOCALMEM_NEG(PLANE,Plane);
- DEFAULT_OP_LOCALMEM_NEG(QUAT,Quat);
- DEFAULT_OP_FAIL(RECT3);
- DEFAULT_OP_FAIL(BASIS);
- DEFAULT_OP_FAIL(TRANSFORM);
+ DEFAULT_OP_FAIL(NIL);
+ DEFAULT_OP_NUM_NEG(BOOL, _bool);
+ DEFAULT_OP_NUM_NEG(INT, _int);
+ DEFAULT_OP_NUM_NEG(REAL, _real);
+ DEFAULT_OP_FAIL(STRING);
+ DEFAULT_OP_LOCALMEM_NEG(VECTOR2, Vector2);
+ DEFAULT_OP_FAIL(RECT2);
+ DEFAULT_OP_FAIL(TRANSFORM2D);
+ DEFAULT_OP_LOCALMEM_NEG(VECTOR3, Vector3);
+ DEFAULT_OP_LOCALMEM_NEG(PLANE, Plane);
+ DEFAULT_OP_LOCALMEM_NEG(QUAT, Quat);
+ DEFAULT_OP_FAIL(RECT3);
+ DEFAULT_OP_FAIL(BASIS);
+ DEFAULT_OP_FAIL(TRANSFORM);
- DEFAULT_OP_FAIL(COLOR);
- DEFAULT_OP_FAIL(IMAGE);
- DEFAULT_OP_FAIL(NODE_PATH);
- DEFAULT_OP_FAIL(_RID);
- DEFAULT_OP_FAIL(OBJECT);
- DEFAULT_OP_FAIL(INPUT_EVENT);
- DEFAULT_OP_FAIL(DICTIONARY);
- DEFAULT_OP_FAIL(ARRAY);
- DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
- DEFAULT_OP_FAIL(POOL_INT_ARRAY);
- DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
- DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
- DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
- DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
- case VARIANT_MAX: {
- r_valid=false;
- return;
+ DEFAULT_OP_FAIL(COLOR);
+ DEFAULT_OP_FAIL(IMAGE);
+ DEFAULT_OP_FAIL(NODE_PATH);
+ DEFAULT_OP_FAIL(_RID);
+ DEFAULT_OP_FAIL(OBJECT);
+ DEFAULT_OP_FAIL(INPUT_EVENT);
+ DEFAULT_OP_FAIL(DICTIONARY);
+ DEFAULT_OP_FAIL(ARRAY);
+ DEFAULT_OP_FAIL(POOL_BYTE_ARRAY);
+ DEFAULT_OP_FAIL(POOL_INT_ARRAY);
+ DEFAULT_OP_FAIL(POOL_REAL_ARRAY);
+ DEFAULT_OP_FAIL(POOL_STRING_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR2_ARRAY);
+ DEFAULT_OP_FAIL(POOL_VECTOR3_ARRAY);
+ DEFAULT_OP_FAIL(POOL_COLOR_ARRAY);
+ case VARIANT_MAX: {
+ r_valid = false;
+ return;
- } break;
- }
+ } break;
+ }
} break;
case OP_MODULE: {
- if (p_a.type==INT && p_b.type==INT) {
+ if (p_a.type == INT && p_b.type == INT) {
#ifdef DEBUG_ENABLED
- if (p_b._data._int==0) {
- r_valid=false;
- _RETURN( "Division By Zero" );
+ if (p_b._data._int == 0) {
+ r_valid = false;
+ _RETURN("Division By Zero");
}
#endif
- _RETURN( p_a._data._int % p_b._data._int );
+ _RETURN(p_a._data._int % p_b._data._int);
- } else if (p_a.type==STRING) {
- const String* format=reinterpret_cast<const String*>(p_a._data._mem);
+ } else if (p_a.type == STRING) {
+ const String *format = reinterpret_cast<const String *>(p_a._data._mem);
String result;
bool error;
- if (p_b.type==ARRAY) {
+ if (p_b.type == ARRAY) {
// e.g. "frog %s %d" % ["fish", 12]
- const Array* args=reinterpret_cast<const Array*>(p_b._data._mem);
- result=format->sprintf(*args, &error);
+ const Array *args = reinterpret_cast<const Array *>(p_b._data._mem);
+ result = format->sprintf(*args, &error);
} else {
// e.g. "frog %d" % 12
Array args;
args.push_back(p_b);
- result=format->sprintf(args, &error);
+ result = format->sprintf(args, &error);
}
r_valid = !error;
_RETURN(result);
}
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_STRING_CONCAT: {
- _RETURN( p_a.operator String() + p_b.operator String() );
+ _RETURN(p_a.operator String() + p_b.operator String());
} break;
//bitwise
case OP_SHIFT_LEFT: {
- if (p_a.type==INT && p_b.type==INT)
- _RETURN( p_a._data._int << p_b._data._int );
+ if (p_a.type == INT && p_b.type == INT)
+ _RETURN(p_a._data._int << p_b._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_SHIFT_RIGHT: {
- if (p_a.type==INT && p_b.type==INT)
- _RETURN( p_a._data._int >> p_b._data._int );
+ if (p_a.type == INT && p_b.type == INT)
+ _RETURN(p_a._data._int >> p_b._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_BIT_AND: {
- if (p_a.type==INT && p_b.type==INT)
- _RETURN( p_a._data._int & p_b._data._int );
+ if (p_a.type == INT && p_b.type == INT)
+ _RETURN(p_a._data._int & p_b._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_BIT_OR: {
- if (p_a.type==INT && p_b.type==INT)
- _RETURN( p_a._data._int | p_b._data._int );
+ if (p_a.type == INT && p_b.type == INT)
+ _RETURN(p_a._data._int | p_b._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_BIT_XOR: {
- if (p_a.type==INT && p_b.type==INT)
- _RETURN( p_a._data._int ^ p_b._data._int );
+ if (p_a.type == INT && p_b.type == INT)
+ _RETURN(p_a._data._int ^ p_b._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
case OP_BIT_NEGATE: {
- if (p_a.type==INT)
- _RETURN( ~p_a._data._int );
+ if (p_a.type == INT)
+ _RETURN(~p_a._data._int);
- r_valid=false;
+ r_valid = false;
return;
} break;
@@ -932,7 +927,7 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
if (!r_valid)
return;
- _RETURN( l && r );
+ _RETURN(l && r);
} break;
case OP_OR: {
bool l = p_a.booleanize(r_valid);
@@ -942,7 +937,7 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
if (!r_valid)
return;
- _RETURN( l || r );
+ _RETURN(l || r);
} break;
case OP_XOR: {
@@ -953,246 +948,249 @@ void Variant::evaluate(const Operator& p_op, const Variant& p_a, const Variant&
if (!r_valid)
return;
- _RETURN( (l || r) && !(l && r) );
+ _RETURN((l || r) && !(l && r));
} break;
case OP_NOT: {
bool l = p_a.booleanize(r_valid);
if (!r_valid)
return;
- _RETURN( !l );
+ _RETURN(!l);
} break;
case OP_IN: {
- _RETURN( p_b.in(p_a,&r_valid) );
+ _RETURN(p_b.in(p_a, &r_valid));
} break;
case OP_MAX: {
- r_valid=false;
+ r_valid = false;
ERR_FAIL();
}
-
}
- r_valid=false;
+ r_valid = false;
}
-void Variant::set_named(const StringName& p_index, const Variant& p_value, bool *r_valid) {
+void Variant::set_named(const StringName &p_index, const Variant &p_value, bool *r_valid) {
- if (type==OBJECT) {
+ if (type == OBJECT) {
#ifdef DEBUG_ENABLED
if (!_get_obj().obj) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return;
} else {
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return;
}
-
}
#endif
- _get_obj().obj->set(p_index,p_value,r_valid);
+ _get_obj().obj->set(p_index, p_value, r_valid);
return;
}
- set(p_index.operator String(),p_value,r_valid);
+ set(p_index.operator String(), p_value, r_valid);
}
-Variant Variant::get_named(const StringName& p_index, bool *r_valid) const {
+Variant Variant::get_named(const StringName &p_index, bool *r_valid) const {
- if (type==OBJECT) {
+ if (type == OBJECT) {
#ifdef DEBUG_ENABLED
if (!_get_obj().obj) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return "Instance base is null.";
} else {
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return "Attempted use of stray pointer object.";
}
}
#endif
- return _get_obj().obj->get(p_index,r_valid);
+ return _get_obj().obj->get(p_index, r_valid);
}
- return get(p_index.operator String(),r_valid);
+ return get(p_index.operator String(), r_valid);
}
-
-#define DEFAULT_OP_ARRAY_CMD(m_name, m_type, skip_test, cmd)\
- case m_name: {\
- skip_test;\
-\
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {\
- int index = p_index;\
- m_type *arr=reinterpret_cast<m_type* >(_data._mem);\
-\
- if (index<0)\
- index += arr->size();\
- if (index>=0 && index<arr->size()) {\
- valid=true;\
- cmd;\
- }\
- }\
+#define DEFAULT_OP_ARRAY_CMD(m_name, m_type, skip_test, cmd) \
+ case m_name: { \
+ skip_test; \
+ \
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) { \
+ int index = p_index; \
+ m_type *arr = reinterpret_cast<m_type *>(_data._mem); \
+ \
+ if (index < 0) \
+ index += arr->size(); \
+ if (index >= 0 && index < arr->size()) { \
+ valid = true; \
+ cmd; \
+ } \
+ } \
} break;
-#define DEFAULT_OP_DVECTOR_SET(m_name, dv_type, skip_cond)\
- DEFAULT_OP_ARRAY_CMD(m_name, PoolVector<dv_type>, if(skip_cond) return;, arr->set(index, p_value);return)
+#define DEFAULT_OP_DVECTOR_SET(m_name, dv_type, skip_cond) \
+ DEFAULT_OP_ARRAY_CMD(m_name, PoolVector<dv_type>, if (skip_cond) return;, arr->set(index, p_value); return )
-#define DEFAULT_OP_DVECTOR_GET(m_name, dv_type)\
+#define DEFAULT_OP_DVECTOR_GET(m_name, dv_type) \
DEFAULT_OP_ARRAY_CMD(m_name, const PoolVector<dv_type>, ;, return arr->get(index))
-void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid) {
+void Variant::set(const Variant &p_index, const Variant &p_value, bool *r_valid) {
- static bool _dummy=false;
+ static bool _dummy = false;
bool &valid = r_valid ? *r_valid : _dummy;
- valid=false;
+ valid = false;
- switch(type) {
- case NIL: { return; } break;
- case BOOL: { return; } break;
- case INT: { return; } break;
- case REAL: { return; } break;
+ switch (type) {
+ case NIL: {
+ return;
+ } break;
+ case BOOL: {
+ return;
+ } break;
+ case INT: {
+ return;
+ } break;
+ case REAL: {
+ return;
+ } break;
case STRING: {
-
- if (p_index.type!=Variant::INT && p_index.type!=Variant::REAL)
+ if (p_index.type != Variant::INT && p_index.type != Variant::REAL)
return;
- int idx=p_index;
- String *str=reinterpret_cast<String*>(_data._mem);
+ int idx = p_index;
+ String *str = reinterpret_cast<String *>(_data._mem);
int len = str->length();
- if (idx<0)
+ if (idx < 0)
idx += len;
- if (idx<0 || idx>=len)
+ if (idx < 0 || idx >= len)
return;
String chr;
- if (p_value.type==Variant::INT || p_value.type==Variant::REAL) {
+ if (p_value.type == Variant::INT || p_value.type == Variant::REAL) {
chr = String::chr(p_value);
- } else if (p_value.type==Variant::STRING) {
+ } else if (p_value.type == Variant::STRING) {
chr = p_value;
} else {
return;
}
- *str = str->substr(0,idx)+chr+str->substr(idx+1, len);
- valid=true;
+ *str = str->substr(0, idx) + chr + str->substr(idx + 1, len);
+ valid = true;
return;
-
} break;
case VECTOR2: {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
// scalar index
- int idx=p_index;
+ int idx = p_index;
- if (idx<0)
+ if (idx < 0)
idx += 2;
- if (idx>=0 && idx<2) {
+ if (idx >= 0 && idx < 2) {
- Vector2 *v=reinterpret_cast<Vector2*>(_data._mem);
- valid=true;
- (*v)[idx]=p_value;
+ Vector2 *v = reinterpret_cast<Vector2 *>(_data._mem);
+ valid = true;
+ (*v)[idx] = p_value;
return;
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Vector2 *v=reinterpret_cast<Vector2*>(_data._mem);
- if (*str=="x" || *str=="width") {
- valid=true;
- v->x=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Vector2 *v = reinterpret_cast<Vector2 *>(_data._mem);
+ if (*str == "x" || *str == "width") {
+ valid = true;
+ v->x = p_value;
return;
- } else if (*str=="y" || *str=="height") {
- valid=true;
- v->y=p_value;
+ } else if (*str == "y" || *str == "height") {
+ valid = true;
+ v->y = p_value;
return;
}
}
- } break; // 5
+ } break; // 5
case RECT2: {
- if (p_value.type!=Variant::VECTOR2)
+ if (p_value.type != Variant::VECTOR2)
return;
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Rect2 *v=reinterpret_cast<Rect2*>(_data._mem);
- if (*str=="pos") {
- valid=true;
- v->pos=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Rect2 *v = reinterpret_cast<Rect2 *>(_data._mem);
+ if (*str == "pos") {
+ valid = true;
+ v->pos = p_value;
return;
- } else if (*str=="size") {
- valid=true;
- v->size=p_value;
+ } else if (*str == "size") {
+ valid = true;
+ v->size = p_value;
return;
- } else if (*str=="end") {
- valid=true;
- v->size=Vector2(p_value) - v->pos;
+ } else if (*str == "end") {
+ valid = true;
+ v->size = Vector2(p_value) - v->pos;
return;
}
}
} break;
case TRANSFORM2D: {
- if (p_value.type!=Variant::VECTOR2)
+ if (p_value.type != Variant::VECTOR2)
return;
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 3;
- if (index>=0 && index<3) {
- Transform2D *v=_data._transform2d;
+ if (index >= 0 && index < 3) {
+ Transform2D *v = _data._transform2d;
- valid=true;
- v->elements[index]=p_value;
+ valid = true;
+ v->elements[index] = p_value;
return;
}
- } else if (p_index.get_type()==Variant::STRING && p_value.get_type()==Variant::VECTOR2) {
+ } else if (p_index.get_type() == Variant::STRING && p_value.get_type() == Variant::VECTOR2) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Transform2D *v=_data._transform2d;
- if (*str=="x") {
- valid=true;
- v->elements[0]=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Transform2D *v = _data._transform2d;
+ if (*str == "x") {
+ valid = true;
+ v->elements[0] = p_value;
return;
- } else if (*str=="y" ) {
- valid=true;
- v->elements[1]=p_value;
+ } else if (*str == "y") {
+ valid = true;
+ v->elements[1] = p_value;
return;
- } else if (*str=="o" ) {
- valid=true;
- v->elements[2]=p_value;
+ } else if (*str == "o") {
+ valid = true;
+ v->elements[2] = p_value;
return;
}
}
@@ -1200,37 +1198,37 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case VECTOR3: {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
//scalar index
- int idx=p_index;
- if (idx<0)
+ int idx = p_index;
+ if (idx < 0)
idx += 3;
- if (idx>=0 && idx<3) {
+ if (idx >= 0 && idx < 3) {
- Vector3 *v=reinterpret_cast<Vector3*>(_data._mem);
- valid=true;
- (*v)[idx]=p_value;
+ Vector3 *v = reinterpret_cast<Vector3 *>(_data._mem);
+ valid = true;
+ (*v)[idx] = p_value;
return;
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Vector3 *v=reinterpret_cast<Vector3*>(_data._mem);
- if (*str=="x") {
- valid=true;
- v->x=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Vector3 *v = reinterpret_cast<Vector3 *>(_data._mem);
+ if (*str == "x") {
+ valid = true;
+ v->x = p_value;
return;
- } else if (*str=="y" ) {
- valid=true;
- v->y=p_value;
+ } else if (*str == "y") {
+ valid = true;
+ v->y = p_value;
return;
- } else if (*str=="z" ) {
- valid=true;
- v->z=p_value;
+ } else if (*str == "z") {
+ valid = true;
+ v->z = p_value;
return;
}
}
@@ -1238,41 +1236,41 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case PLANE: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Plane *v=reinterpret_cast<Plane*>(_data._mem);
- if (*str=="x") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Plane *v = reinterpret_cast<Plane *>(_data._mem);
+ if (*str == "x") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- v->normal.x=p_value;
+ valid = true;
+ v->normal.x = p_value;
return;
- } else if (*str=="y" ) {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (*str == "y") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- v->normal.y=p_value;
+ valid = true;
+ v->normal.y = p_value;
return;
- } else if (*str=="z" ) {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (*str == "z") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- v->normal.z=p_value;
+ valid = true;
+ v->normal.z = p_value;
return;
- } else if (*str=="normal" ) {
- if (p_value.type!=Variant::VECTOR3)
+ } else if (*str == "normal") {
+ if (p_value.type != Variant::VECTOR3)
return;
- valid=true;
- v->normal=p_value;
+ valid = true;
+ v->normal = p_value;
return;
- } else if (*str=="d" ) {
- valid=true;
- v->d=p_value;
+ } else if (*str == "d") {
+ valid = true;
+ v->d = p_value;
return;
}
}
@@ -1280,28 +1278,28 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case QUAT: {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Quat *v=reinterpret_cast<Quat*>(_data._mem);
- if (*str=="x") {
- valid=true;
- v->x=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Quat *v = reinterpret_cast<Quat *>(_data._mem);
+ if (*str == "x") {
+ valid = true;
+ v->x = p_value;
return;
- } else if (*str=="y" ) {
- valid=true;
- v->y=p_value;
+ } else if (*str == "y") {
+ valid = true;
+ v->y = p_value;
return;
- } else if (*str=="z" ) {
- valid=true;
- v->z=p_value;
+ } else if (*str == "z") {
+ valid = true;
+ v->z = p_value;
return;
- } else if (*str=="w" ) {
- valid=true;
- v->w=p_value;
+ } else if (*str == "w") {
+ valid = true;
+ v->w = p_value;
return;
}
}
@@ -1309,64 +1307,63 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case RECT3: {
- if (p_value.type!=Variant::VECTOR3)
+ if (p_value.type != Variant::VECTOR3)
return;
-
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Rect3 *v=_data._rect3;
- if (*str=="pos") {
- valid=true;
- v->pos=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Rect3 *v = _data._rect3;
+ if (*str == "pos") {
+ valid = true;
+ v->pos = p_value;
return;
- } else if (*str=="size") {
- valid=true;
- v->size=p_value;
+ } else if (*str == "size") {
+ valid = true;
+ v->size = p_value;
return;
- } else if (*str=="end") {
- valid=true;
- v->size=Vector3(p_value) - v->pos;
+ } else if (*str == "end") {
+ valid = true;
+ v->size = Vector3(p_value) - v->pos;
return;
}
}
} break; //sorry naming convention fail :( not like it's used often // 10
case BASIS: {
- if (p_value.type!=Variant::VECTOR3)
+ if (p_value.type != Variant::VECTOR3)
return;
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 3;
- if (index>=0 && index<3) {
- Basis *v=_data._basis;
+ if (index >= 0 && index < 3) {
+ Basis *v = _data._basis;
- valid=true;
- v->set_axis(index,p_value);
+ valid = true;
+ v->set_axis(index, p_value);
return;
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Basis *v=_data._basis;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Basis *v = _data._basis;
- if (*str=="x") {
- valid=true;
- v->set_axis(0,p_value);
+ if (*str == "x") {
+ valid = true;
+ v->set_axis(0, p_value);
return;
- } else if (*str=="y" ) {
- valid=true;
- v->set_axis(1,p_value);
+ } else if (*str == "y") {
+ valid = true;
+ v->set_axis(1, p_value);
return;
- } else if (*str=="z" ) {
- valid=true;
- v->set_axis(2,p_value);
+ } else if (*str == "z") {
+ valid = true;
+ v->set_axis(2, p_value);
return;
}
}
@@ -1374,42 +1371,42 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case TRANSFORM: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
-
- if (p_value.type!=Variant::VECTOR3)
+ if (p_value.type != Variant::VECTOR3)
return;
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 4;
- if (index>=0 && index<4) {
- Transform *v=_data._transform;
- valid=true;
- if (index==3)
- v->origin=p_value;
+ if (index >= 0 && index < 4) {
+ Transform *v = _data._transform;
+ valid = true;
+ if (index == 3)
+ v->origin = p_value;
else
- v->basis.set_axis(index,p_value);
+ v->basis.set_axis(index, p_value);
return;
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
- Transform *v=_data._transform;
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
+ Transform *v = _data._transform;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
- if (*str=="basis") {
+ if (*str == "basis") {
- if (p_value.type!=Variant::BASIS)
+ if (p_value.type != Variant::BASIS)
return;
- valid=true;
- v->basis=p_value;
+ valid = true;
+ v->basis = p_value;
return;
- } if (*str=="origin") {
- if (p_value.type!=Variant::VECTOR3)
+ }
+ if (*str == "origin") {
+ if (p_value.type != Variant::VECTOR3)
return;
- valid=true;
- v->origin=p_value;
+ valid = true;
+ v->origin = p_value;
return;
}
}
@@ -1417,80 +1414,81 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case COLOR: {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- Color *v=reinterpret_cast<Color*>(_data._mem);
- if (*str=="r") {
- valid=true;
- v->r=p_value;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ Color *v = reinterpret_cast<Color *>(_data._mem);
+ if (*str == "r") {
+ valid = true;
+ v->r = p_value;
return;
- } else if (*str=="g" ) {
- valid=true;
- v->g=p_value;
+ } else if (*str == "g") {
+ valid = true;
+ v->g = p_value;
return;
- } else if (*str=="b" ) {
- valid=true;
- v->b=p_value;
+ } else if (*str == "b") {
+ valid = true;
+ v->b = p_value;
return;
- } else if (*str=="a" ) {
- valid=true;
- v->a=p_value;
+ } else if (*str == "a") {
+ valid = true;
+ v->a = p_value;
return;
- } else if (*str=="h") {
- valid=true;
- v->set_hsv(p_value,v->get_s(),v->get_v());
+ } else if (*str == "h") {
+ valid = true;
+ v->set_hsv(p_value, v->get_s(), v->get_v());
return;
- } else if (*str=="s" ) {
- valid=true;
- v->set_hsv(v->get_h(),p_value,v->get_v());
+ } else if (*str == "s") {
+ valid = true;
+ v->set_hsv(v->get_h(), p_value, v->get_v());
return;
- } else if (*str=="v" ) {
- valid=true;
- v->set_hsv(v->get_h(),v->get_s(),p_value);
+ } else if (*str == "v") {
+ valid = true;
+ v->set_hsv(v->get_h(), v->get_s(), p_value);
return;
- } else if (*str=="r8" ) {
- valid=true;
- v->r=float(p_value)/255.0;
+ } else if (*str == "r8") {
+ valid = true;
+ v->r = float(p_value) / 255.0;
return;
- } else if (*str=="g8" ) {
- valid=true;
- v->g=float(p_value)/255.0;
+ } else if (*str == "g8") {
+ valid = true;
+ v->g = float(p_value) / 255.0;
return;
- } else if (*str=="b8" ) {
- valid=true;
- v->b=float(p_value)/255.0;
+ } else if (*str == "b8") {
+ valid = true;
+ v->b = float(p_value) / 255.0;
return;
- } else if (*str=="a8" ) {\
- valid=true;
- v->a=float(p_value)/255.0;
+ } else if (*str == "a8") {
+ valid = true;
+ v->a = float(p_value) / 255.0;
return;
}
- } else if (p_index.get_type()==Variant::INT) {
+ } else if (p_index.get_type() == Variant::INT) {
int idx = p_index;
- if (idx<0)
+ if (idx < 0)
idx += 4;
- if (idx>=0 || idx<4) {
- Color *v=reinterpret_cast<Color*>(_data._mem);
- (*v)[idx]=p_value;
- valid=true;
+ if (idx >= 0 || idx < 4) {
+ Color *v = reinterpret_cast<Color *>(_data._mem);
+ (*v)[idx] = p_value;
+ valid = true;
}
}
-
-
} break;
- case IMAGE: { } break;
- case NODE_PATH: { } break; // 15
- case _RID: { } break;
+ case IMAGE: {
+ } break;
+ case NODE_PATH: {
+ } break; // 15
+ case _RID: {
+ } break;
case OBJECT: {
- Object *obj=_get_obj().obj;
- //only if debugging!
+ Object *obj = _get_obj().obj;
+ //only if debugging!
if (obj) {
#ifdef DEBUG_ENABLED
@@ -1498,384 +1496,398 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
if (!ObjectDB::instance_validate(obj)) {
WARN_PRINT("Attempted use of stray pointer object.");
- valid=false;
+ valid = false;
return;
}
}
#endif
- if (p_index.get_type()!=Variant::STRING) {
- obj->setvar(p_index,p_value,r_valid);
+ if (p_index.get_type() != Variant::STRING) {
+ obj->setvar(p_index, p_value, r_valid);
return;
}
- return obj->set(p_index,p_value,r_valid);
+ return obj->set(p_index, p_value, r_valid);
}
} break;
case INPUT_EVENT: {
InputEvent &ie = *_data._input_event;
- if (p_index.get_type()!=Variant::STRING)
+ if (p_index.get_type() != Variant::STRING)
return;
- const String &str=*reinterpret_cast<const String*>(p_index._data._mem);
+ const String &str = *reinterpret_cast<const String *>(p_index._data._mem);
- if (str=="type") {
+ if (str == "type") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- int type=p_value;
- if (type<0 || type>=InputEvent::TYPE_MAX)
+ int type = p_value;
+ if (type < 0 || type >= InputEvent::TYPE_MAX)
return; //fail
- valid=true;
- ie.type=InputEvent::Type(type);
+ valid = true;
+ ie.type = InputEvent::Type(type);
return;
- } else if (str=="device") {
+ } else if (str == "device") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.device=p_value;
+ valid = true;
+ ie.device = p_value;
return;
- } else if (str=="ID") {
+ } else if (str == "ID") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.ID=p_value;
+ valid = true;
+ ie.ID = p_value;
return;
}
- if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) {
+ if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) {
- if (str=="shift") {
+ if (str == "shift") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.key.mod.shift=p_value;
+ valid = true;
+ ie.key.mod.shift = p_value;
return;
- } if (str=="alt") {
+ }
+ if (str == "alt") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.key.mod.alt=p_value;
+ valid = true;
+ ie.key.mod.alt = p_value;
return;
- } if (str=="control") {
+ }
+ if (str == "control") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.key.mod.control=p_value;
+ valid = true;
+ ie.key.mod.control = p_value;
return;
- } if (str=="meta") {
+ }
+ if (str == "meta") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.key.mod.meta=p_value;
+ valid = true;
+ ie.key.mod.meta = p_value;
return;
}
}
- if (ie.type==InputEvent::KEY) {
+ if (ie.type == InputEvent::KEY) {
- if (str=="pressed") {
-
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
- return;
+ if (str == "pressed") {
- valid=true;
- ie.key.pressed=p_value;
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- } else if (str=="scancode") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
- return;
+ valid = true;
+ ie.key.pressed = p_value;
+ return;
+ } else if (str == "scancode") {
- valid=true;
- ie.key.scancode=p_value;
- return;
- } else if (str=="unicode") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
- return;
- valid=true;
- ie.key.unicode=p_value;
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- } else if (str=="echo") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
- return;
- valid=true;
- ie.key.echo=p_value;
+ valid = true;
+ ie.key.scancode = p_value;
+ return;
+ } else if (str == "unicode") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- }
+ valid = true;
+ ie.key.unicode = p_value;
+ return;
+ } else if (str == "echo") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
+ return;
+
+ valid = true;
+ ie.key.echo = p_value;
+ return;
+ }
}
- if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) {
+ if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) {
- if (str=="button_mask") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (str == "button_mask") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.button_mask=p_value;
+ valid = true;
+ ie.mouse_button.button_mask = p_value;
return;
- } else if (str=="x") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "x") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.x=p_value;
+ valid = true;
+ ie.mouse_button.x = p_value;
return;
- } else if (str=="y") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "y") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.y=p_value;
+ valid = true;
+ ie.mouse_button.y = p_value;
return;
- } else if (str=="pos") {
- if (p_value.type!=Variant::VECTOR2)
+ } else if (str == "pos") {
+ if (p_value.type != Variant::VECTOR2)
return;
- valid=true;
- Point2 value=p_value;
- ie.mouse_button.x=value.x;
- ie.mouse_button.y=value.y;
+ valid = true;
+ Point2 value = p_value;
+ ie.mouse_button.x = value.x;
+ ie.mouse_button.y = value.y;
return;
- } else if (str=="global_x") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "global_x") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.global_x=p_value;
+ valid = true;
+ ie.mouse_button.global_x = p_value;
return;
- } else if (str=="global_y") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "global_y") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.global_y=p_value;
+ valid = true;
+ ie.mouse_button.global_y = p_value;
return;
- } else if (str=="global_pos") {
- if (p_value.type!=Variant::VECTOR2)
+ } else if (str == "global_pos") {
+ if (p_value.type != Variant::VECTOR2)
return;
- valid=true;
- Point2 value=p_value;
- ie.mouse_button.global_x=value.x;
- ie.mouse_button.global_y=value.y;
+ valid = true;
+ Point2 value = p_value;
+ ie.mouse_button.global_x = value.x;
+ ie.mouse_button.global_y = value.y;
return;
} /*else if (str=="pointer_index") {
valid=true;
return ie.mouse_button.pointer_index;
}*/
+ if (ie.type == InputEvent::MOUSE_MOTION) {
- if (ie.type==InputEvent::MOUSE_MOTION) {
-
- if (str=="relative_x") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (str == "relative_x") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_motion.relative_x=p_value;
+ valid = true;
+ ie.mouse_motion.relative_x = p_value;
return;
- } else if (str=="relative_y") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "relative_y") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_motion.relative_y=p_value;
+ valid = true;
+ ie.mouse_motion.relative_y = p_value;
return;
- } else if (str=="relative_pos") {
- if (p_value.type!=Variant::VECTOR2)
+ } else if (str == "relative_pos") {
+ if (p_value.type != Variant::VECTOR2)
return;
- valid=true;
- Point2 value=p_value;
- ie.mouse_motion.relative_x=value.x;
- ie.mouse_motion.relative_y=value.y;
+ valid = true;
+ Point2 value = p_value;
+ ie.mouse_motion.relative_x = value.x;
+ ie.mouse_motion.relative_y = value.y;
return;
}
- if (str=="speed_x") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (str == "speed_x") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_motion.speed_x=p_value;
+ valid = true;
+ ie.mouse_motion.speed_x = p_value;
return;
- } else if (str=="speed_y") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ } else if (str == "speed_y") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_motion.speed_y=p_value;
+ valid = true;
+ ie.mouse_motion.speed_y = p_value;
return;
- } else if (str=="speed") {
- if (p_value.type!=Variant::VECTOR2)
+ } else if (str == "speed") {
+ if (p_value.type != Variant::VECTOR2)
return;
- valid=true;
- Point2 value=p_value;
- ie.mouse_motion.speed_x=value.x;
- ie.mouse_motion.speed_y=value.y;
+ valid = true;
+ Point2 value = p_value;
+ ie.mouse_motion.speed_x = value.x;
+ ie.mouse_motion.speed_y = value.y;
return;
}
- } else if (ie.type==InputEvent::MOUSE_BUTTON) {
+ } else if (ie.type == InputEvent::MOUSE_BUTTON) {
- if (str=="button_index") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL)
+ if (str == "button_index") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL)
return;
- valid=true;
- ie.mouse_button.button_index=p_value;
+ valid = true;
+ ie.mouse_button.button_index = p_value;
return;
- } else if (str=="pressed") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ } else if (str == "pressed") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.mouse_button.pressed=p_value;
+ valid = true;
+ ie.mouse_button.pressed = p_value;
return;
- } else if (str=="doubleclick") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ } else if (str == "doubleclick") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.mouse_button.doubleclick=p_value;
+ valid = true;
+ ie.mouse_button.doubleclick = p_value;
return;
}
}
-
}
- if (ie.type==InputEvent::JOYPAD_BUTTON) {
+ if (ie.type == InputEvent::JOYPAD_BUTTON) {
- if (str=="button_index") {
- if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT)
+ if (str == "button_index") {
+ if (p_value.type != Variant::REAL && p_value.type != Variant::INT)
return;
- valid=true;
- ie.joy_button.button_index=p_value;
+ valid = true;
+ ie.joy_button.button_index = p_value;
return;
- } if (str=="pressed") {
- if (p_value.type!=Variant::INT && p_value.type!=Variant::REAL && p_value.type!=Variant::BOOL)
+ }
+ if (str == "pressed") {
+ if (p_value.type != Variant::INT && p_value.type != Variant::REAL && p_value.type != Variant::BOOL)
return;
- valid=true;
- ie.joy_button.pressed=p_value;
+ valid = true;
+ ie.joy_button.pressed = p_value;
return;
- } if (str=="pressure") {
- if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT)
+ }
+ if (str == "pressure") {
+ if (p_value.type != Variant::REAL && p_value.type != Variant::INT)
return;
- valid=true;
- ie.joy_button.pressure=p_value;
+ valid = true;
+ ie.joy_button.pressure = p_value;
return;
}
-
}
- if (ie.type==InputEvent::JOYPAD_MOTION) {
+ if (ie.type == InputEvent::JOYPAD_MOTION) {
- if (str=="axis") {
- if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT)
+ if (str == "axis") {
+ if (p_value.type != Variant::REAL && p_value.type != Variant::INT)
return;
- valid=true;
- ie.joy_motion.axis=p_value;
+ valid = true;
+ ie.joy_motion.axis = p_value;
return;
- } if (str=="value") {
- if (p_value.type!=Variant::REAL && p_value.type!=Variant::INT)
+ }
+ if (str == "value") {
+ if (p_value.type != Variant::REAL && p_value.type != Variant::INT)
return;
- valid=true;
- ie.joy_motion.axis_value=p_value;
+ valid = true;
+ ie.joy_motion.axis_value = p_value;
return;
}
}
- if (ie.type==InputEvent::SCREEN_TOUCH) {
+ if (ie.type == InputEvent::SCREEN_TOUCH) {
- if (str=="index") {
- valid=true;
- ie.screen_touch.index=p_value;
+ if (str == "index") {
+ valid = true;
+ ie.screen_touch.index = p_value;
return;
- } if (str=="x") {
- valid=true;
- ie.screen_touch.x=p_value;
+ }
+ if (str == "x") {
+ valid = true;
+ ie.screen_touch.x = p_value;
return;
- } if (str=="y") {
- valid=true;
- ie.screen_touch.y=p_value;
+ }
+ if (str == "y") {
+ valid = true;
+ ie.screen_touch.y = p_value;
return;
- } if (str=="pos") {
- valid=true;
+ }
+ if (str == "pos") {
+ valid = true;
Vector2 v = p_value;
- ie.screen_touch.x=v.x;
- ie.screen_touch.y=v.y;
+ ie.screen_touch.x = v.x;
+ ie.screen_touch.y = v.y;
return;
- } if (str=="pressed") {
- valid=true;
- ie.screen_touch.pressed=p_value;
+ }
+ if (str == "pressed") {
+ valid = true;
+ ie.screen_touch.pressed = p_value;
return;
}
-
}
- if (ie.type==InputEvent::SCREEN_DRAG) {
+ if (ie.type == InputEvent::SCREEN_DRAG) {
- if (str=="index") {
- valid=true;
- ie.screen_drag.index=p_value;
+ if (str == "index") {
+ valid = true;
+ ie.screen_drag.index = p_value;
return;
- } if (str=="x") {
- valid=true;
- ie.screen_drag.x=p_value;
+ }
+ if (str == "x") {
+ valid = true;
+ ie.screen_drag.x = p_value;
return;
- } if (str=="y") {
- valid=true;
- ie.screen_drag.y=p_value;
+ }
+ if (str == "y") {
+ valid = true;
+ ie.screen_drag.y = p_value;
return;
- } if (str=="pos") {
- valid=true;
+ }
+ if (str == "pos") {
+ valid = true;
Vector2 v = p_value;
- ie.screen_drag.x=v.x;
- ie.screen_drag.y=v.y;
+ ie.screen_drag.x = v.x;
+ ie.screen_drag.y = v.y;
return;
- } if (str=="relative_x") {
- valid=true;
- ie.screen_drag.relative_x=p_value;
+ }
+ if (str == "relative_x") {
+ valid = true;
+ ie.screen_drag.relative_x = p_value;
return;
- } if (str=="relative_y") {
- valid=true;
- ie.screen_drag.relative_y=p_value;
+ }
+ if (str == "relative_y") {
+ valid = true;
+ ie.screen_drag.relative_y = p_value;
return;
- } if (str=="relative_pos") {
- valid=true;
- Vector2 v=p_value;
- ie.screen_drag.relative_x=v.x;
- ie.screen_drag.relative_y=v.y;
+ }
+ if (str == "relative_pos") {
+ valid = true;
+ Vector2 v = p_value;
+ ie.screen_drag.relative_x = v.x;
+ ie.screen_drag.relative_y = v.y;
return;
- } if (str=="speed_x") {
- valid=true;
- ie.screen_drag.speed_x=p_value;
+ }
+ if (str == "speed_x") {
+ valid = true;
+ ie.screen_drag.speed_x = p_value;
return;
- } if (str=="speed_y") {
- valid=true;
- ie.screen_drag.speed_y=p_value;
+ }
+ if (str == "speed_y") {
+ valid = true;
+ ie.screen_drag.speed_y = p_value;
return;
- } if (str=="speed") {
- valid=true;
- Vector2 v=p_value;
- ie.screen_drag.speed_x=v.x;
- ie.screen_drag.speed_y=v.y;
+ }
+ if (str == "speed") {
+ valid = true;
+ Vector2 v = p_value;
+ ie.screen_drag.speed_x = v.x;
+ ie.screen_drag.speed_y = v.y;
return;
}
}
if (ie.type == InputEvent::ACTION) {
- if (str =="action") {
- valid=true;
- ie.action.action=p_value;
+ if (str == "action") {
+ valid = true;
+ ie.action.action = p_value;
return;
- }
- else if (str == "pressed") {
- valid=true;
- ie.action.pressed=p_value;
+ } else if (str == "pressed") {
+ valid = true;
+ ie.action.pressed = p_value;
return;
}
}
@@ -1883,127 +1895,134 @@ void Variant::set(const Variant& p_index, const Variant& p_value, bool *r_valid)
} break;
case DICTIONARY: {
- Dictionary *dic=reinterpret_cast<Dictionary*>(_data._mem);
- dic->operator [](p_index)=p_value;
- valid=true; //always valid, i guess? should this really be ok?
+ Dictionary *dic = reinterpret_cast<Dictionary *>(_data._mem);
+ dic->operator[](p_index) = p_value;
+ valid = true; //always valid, i guess? should this really be ok?
return;
- } break; // 20
- DEFAULT_OP_ARRAY_CMD(ARRAY, Array, ;, (*arr)[index]=p_value;return)
- DEFAULT_OP_DVECTOR_SET(POOL_BYTE_ARRAY, uint8_t, p_value.type != Variant::REAL && p_value.type != Variant::INT)
- DEFAULT_OP_DVECTOR_SET(POOL_INT_ARRAY, int, p_value.type != Variant::REAL && p_value.type != Variant::INT)
- DEFAULT_OP_DVECTOR_SET(POOL_REAL_ARRAY, real_t, p_value.type != Variant::REAL && p_value.type != Variant::INT)
- DEFAULT_OP_DVECTOR_SET(POOL_STRING_ARRAY, String, p_value.type != Variant::STRING) // 25
- DEFAULT_OP_DVECTOR_SET(POOL_VECTOR2_ARRAY, Vector2, p_value.type != Variant::VECTOR2)
- DEFAULT_OP_DVECTOR_SET(POOL_VECTOR3_ARRAY, Vector3, p_value.type != Variant::VECTOR3)
- DEFAULT_OP_DVECTOR_SET(POOL_COLOR_ARRAY, Color, p_value.type != Variant::COLOR)
+ } break; // 20
+ DEFAULT_OP_ARRAY_CMD(ARRAY, Array, ;, (*arr)[index] = p_value; return )
+ DEFAULT_OP_DVECTOR_SET(POOL_BYTE_ARRAY, uint8_t, p_value.type != Variant::REAL && p_value.type != Variant::INT)
+ DEFAULT_OP_DVECTOR_SET(POOL_INT_ARRAY, int, p_value.type != Variant::REAL && p_value.type != Variant::INT)
+ DEFAULT_OP_DVECTOR_SET(POOL_REAL_ARRAY, real_t, p_value.type != Variant::REAL && p_value.type != Variant::INT)
+ DEFAULT_OP_DVECTOR_SET(POOL_STRING_ARRAY, String, p_value.type != Variant::STRING) // 25
+ DEFAULT_OP_DVECTOR_SET(POOL_VECTOR2_ARRAY, Vector2, p_value.type != Variant::VECTOR2)
+ DEFAULT_OP_DVECTOR_SET(POOL_VECTOR3_ARRAY, Vector3, p_value.type != Variant::VECTOR3)
+ DEFAULT_OP_DVECTOR_SET(POOL_COLOR_ARRAY, Color, p_value.type != Variant::COLOR)
default: return;
}
-
}
-Variant Variant::get(const Variant& p_index, bool *r_valid) const {
+Variant Variant::get(const Variant &p_index, bool *r_valid) const {
- static bool _dummy=false;
+ static bool _dummy = false;
bool &valid = r_valid ? *r_valid : _dummy;
- valid=false;
+ valid = false;
- switch(type) {
- case NIL: { return Variant(); } break;
- case BOOL: { return Variant(); } break;
- case INT: { return Variant(); } break;
- case REAL: { return Variant(); } break;
+ switch (type) {
+ case NIL: {
+ return Variant();
+ } break;
+ case BOOL: {
+ return Variant();
+ } break;
+ case INT: {
+ return Variant();
+ } break;
+ case REAL: {
+ return Variant();
+ } break;
case STRING: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
//string index
- int idx=p_index;
- const String *str=reinterpret_cast<const String*>(_data._mem);
- if (idx<0)
+ int idx = p_index;
+ const String *str = reinterpret_cast<const String *>(_data._mem);
+ if (idx < 0)
idx += str->length();
- if (idx >=0 && idx<str->length()) {
+ if (idx >= 0 && idx < str->length()) {
- valid=true;
- return str->substr(idx,1);
+ valid = true;
+ return str->substr(idx, 1);
}
}
} break;
case VECTOR2: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
// scalar index
- int idx=p_index;
- if (idx<0)
+ int idx = p_index;
+ if (idx < 0)
idx += 2;
- if (idx>=0 && idx<2) {
+ if (idx >= 0 && idx < 2) {
- const Vector2 *v=reinterpret_cast<const Vector2*>(_data._mem);
- valid=true;
+ const Vector2 *v = reinterpret_cast<const Vector2 *>(_data._mem);
+ valid = true;
return (*v)[idx];
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Vector2 *v=reinterpret_cast<const Vector2*>(_data._mem);
- if (*str=="x" || *str=="width") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Vector2 *v = reinterpret_cast<const Vector2 *>(_data._mem);
+ if (*str == "x" || *str == "width") {
+ valid = true;
return v->x;
- } else if (*str=="y" || *str=="height") {
- valid=true;
+ } else if (*str == "y" || *str == "height") {
+ valid = true;
return v->y;
}
}
- } break; // 5
+ } break; // 5
case RECT2: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Rect2 *v=reinterpret_cast<const Rect2*>(_data._mem);
- if (*str=="pos") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Rect2 *v = reinterpret_cast<const Rect2 *>(_data._mem);
+ if (*str == "pos") {
+ valid = true;
return v->pos;
- } else if (*str=="size") {
- valid=true;
+ } else if (*str == "size") {
+ valid = true;
return v->size;
- } else if (*str=="end") {
- valid=true;
- return v->size+v->pos;
+ } else if (*str == "end") {
+ valid = true;
+ return v->size + v->pos;
}
}
} break;
case VECTOR3: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
//scalar index
- int idx=p_index;
- if (idx<0)
+ int idx = p_index;
+ if (idx < 0)
idx += 3;
- if (idx>=0 && idx<3) {
+ if (idx >= 0 && idx < 3) {
- const Vector3 *v=reinterpret_cast<const Vector3*>(_data._mem);
- valid=true;
+ const Vector3 *v = reinterpret_cast<const Vector3 *>(_data._mem);
+ valid = true;
return (*v)[idx];
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Vector3 *v=reinterpret_cast<const Vector3*>(_data._mem);
- if (*str=="x") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Vector3 *v = reinterpret_cast<const Vector3 *>(_data._mem);
+ if (*str == "x") {
+ valid = true;
return v->x;
- } else if (*str=="y" ) {
- valid=true;
+ } else if (*str == "y") {
+ valid = true;
return v->y;
- } else if (*str=="z" ) {
- valid=true;
+ } else if (*str == "z") {
+ valid = true;
return v->z;
}
}
@@ -2011,31 +2030,31 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case TRANSFORM2D: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 3;
- if (index>=0 && index<3) {
- const Transform2D *v=_data._transform2d;
+ if (index >= 0 && index < 3) {
+ const Transform2D *v = _data._transform2d;
- valid=true;
+ valid = true;
return v->elements[index];
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Transform2D *v=_data._transform2d;
- if (*str=="x") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Transform2D *v = _data._transform2d;
+ if (*str == "x") {
+ valid = true;
return v->elements[0];
- } else if (*str=="y" ) {
- valid=true;
+ } else if (*str == "y") {
+ valid = true;
return v->elements[1];
- } else if (*str=="o" ) {
- valid=true;
+ } else if (*str == "o") {
+ valid = true;
return v->elements[2];
}
}
@@ -2043,24 +2062,24 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case PLANE: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Plane *v=reinterpret_cast<const Plane*>(_data._mem);
- if (*str=="x") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Plane *v = reinterpret_cast<const Plane *>(_data._mem);
+ if (*str == "x") {
+ valid = true;
return v->normal.x;
- } else if (*str=="y" ) {
- valid=true;
+ } else if (*str == "y") {
+ valid = true;
return v->normal.y;
- } else if (*str=="z" ) {
- valid=true;
+ } else if (*str == "z") {
+ valid = true;
return v->normal.z;
- } else if (*str=="normal" ) {
- valid=true;
+ } else if (*str == "normal") {
+ valid = true;
return v->normal;
- } else if (*str=="d" ) {
- valid=true;
+ } else if (*str == "d") {
+ valid = true;
return v->d;
}
}
@@ -2068,21 +2087,21 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case QUAT: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Quat *v=reinterpret_cast<const Quat*>(_data._mem);
- if (*str=="x") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Quat *v = reinterpret_cast<const Quat *>(_data._mem);
+ if (*str == "x") {
+ valid = true;
return v->x;
- } else if (*str=="y" ) {
- valid=true;
+ } else if (*str == "y") {
+ valid = true;
return v->y;
- } else if (*str=="z" ) {
- valid=true;
+ } else if (*str == "z") {
+ valid = true;
return v->z;
- } else if (*str=="w" ) {
- valid=true;
+ } else if (*str == "w") {
+ valid = true;
return v->w;
}
}
@@ -2090,49 +2109,49 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case RECT3: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//scalar name
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Rect3 *v=_data._rect3;
- if (*str=="pos") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Rect3 *v = _data._rect3;
+ if (*str == "pos") {
+ valid = true;
return v->pos;
- } else if (*str=="size") {
- valid=true;
+ } else if (*str == "size") {
+ valid = true;
return v->size;
- } else if (*str=="end") {
- valid=true;
- return v->size+v->pos;
+ } else if (*str == "end") {
+ valid = true;
+ return v->size + v->pos;
}
}
} break; //sorry naming convention fail :( not like it's used often // 10
case BASIS: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 3;
- if (index>=0 && index<3) {
- const Basis *v=_data._basis;
+ if (index >= 0 && index < 3) {
+ const Basis *v = _data._basis;
- valid=true;
+ valid = true;
return v->get_axis(index);
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Basis *v=_data._basis;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Basis *v = _data._basis;
- if (*str=="x") {
- valid=true;
+ if (*str == "x") {
+ valid = true;
return v->get_axis(0);
- } else if (*str=="y" ) {
- valid=true;
+ } else if (*str == "y") {
+ valid = true;
return v->get_axis(1);
- } else if (*str=="z" ) {
- valid=true;
+ } else if (*str == "z") {
+ valid = true;
return v->get_axis(2);
}
}
@@ -2140,26 +2159,27 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case TRANSFORM: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- if (index<0)
+ if (index < 0)
index += 4;
- if (index>=0 && index<4) {
- const Transform *v=_data._transform;
- valid=true;
- return index==3?v->origin:v->basis.get_axis(index);
+ if (index >= 0 && index < 4) {
+ const Transform *v = _data._transform;
+ valid = true;
+ return index == 3 ? v->origin : v->basis.get_axis(index);
}
- } else if (p_index.get_type()==Variant::STRING) {
+ } else if (p_index.get_type() == Variant::STRING) {
- const Transform *v=_data._transform;
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
+ const Transform *v = _data._transform;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
- if (*str=="basis") {
- valid=true;
+ if (*str == "basis") {
+ valid = true;
return v->basis;
- } if (*str=="origin") {
- valid=true;
+ }
+ if (*str == "origin") {
+ valid = true;
return v->origin;
}
}
@@ -2167,297 +2187,309 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case COLOR: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
- const String *str=reinterpret_cast<const String*>(p_index._data._mem);
- const Color *v=reinterpret_cast<const Color*>(_data._mem);
- if (*str=="r") {
- valid=true;
+ const String *str = reinterpret_cast<const String *>(p_index._data._mem);
+ const Color *v = reinterpret_cast<const Color *>(_data._mem);
+ if (*str == "r") {
+ valid = true;
return v->r;
- } else if (*str=="g" ) {
- valid=true;
+ } else if (*str == "g") {
+ valid = true;
return v->g;
- } else if (*str=="b" ) {
- valid=true;
+ } else if (*str == "b") {
+ valid = true;
return v->b;
- } else if (*str=="a" ) {
- valid=true;
+ } else if (*str == "a") {
+ valid = true;
return v->a;
- } else if (*str=="h") {
- valid=true;
+ } else if (*str == "h") {
+ valid = true;
return v->get_h();
- } else if (*str=="s" ) {
- valid=true;
+ } else if (*str == "s") {
+ valid = true;
return v->get_s();
- } else if (*str=="v" ) {
- valid=true;
+ } else if (*str == "v") {
+ valid = true;
return v->get_v();
- } else if (*str=="r8") {
- valid=true;
- return (int)Math::round(v->r*255.0);
- } else if (*str=="g8" ) {
- valid=true;
- return (int)Math::round(v->g*255.0);
- } else if (*str=="b8" ) {
- valid=true;
- return (int)Math::round(v->b*255.0);
- } else if (*str=="a8" ) {
- valid=true;
- return (int)Math::round(v->a*255.0);
- }
- } else if (p_index.get_type()==Variant::INT) {
+ } else if (*str == "r8") {
+ valid = true;
+ return (int)Math::round(v->r * 255.0);
+ } else if (*str == "g8") {
+ valid = true;
+ return (int)Math::round(v->g * 255.0);
+ } else if (*str == "b8") {
+ valid = true;
+ return (int)Math::round(v->b * 255.0);
+ } else if (*str == "a8") {
+ valid = true;
+ return (int)Math::round(v->a * 255.0);
+ }
+ } else if (p_index.get_type() == Variant::INT) {
int idx = p_index;
- if (idx<0)
+ if (idx < 0)
idx += 4;
- if (idx>=0 || idx<4) {
- const Color *v=reinterpret_cast<const Color*>(_data._mem);
- valid=true;
+ if (idx >= 0 || idx < 4) {
+ const Color *v = reinterpret_cast<const Color *>(_data._mem);
+ valid = true;
return (*v)[idx];
}
}
-
} break;
- case IMAGE: { } break;
- case NODE_PATH: { } break; // 15
- case _RID: { } break;
+ case IMAGE: {
+ } break;
+ case NODE_PATH: {
+ } break; // 15
+ case _RID: {
+ } break;
case OBJECT: {
Object *obj = _get_obj().obj;
if (obj) {
-
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
//only if debugging!
if (!ObjectDB::instance_validate(obj)) {
- valid=false;
+ valid = false;
return "Attempted get on stray pointer.";
}
}
#endif
- if (p_index.get_type()!=Variant::STRING) {
- return obj->getvar(p_index,r_valid);
+ if (p_index.get_type() != Variant::STRING) {
+ return obj->getvar(p_index, r_valid);
}
- return obj->get(p_index,r_valid);
+ return obj->get(p_index, r_valid);
}
-
} break;
case INPUT_EVENT: {
InputEvent ie = operator InputEvent();
- if (p_index.get_type()!=Variant::STRING)
+ if (p_index.get_type() != Variant::STRING)
break;
+ const String &str = *reinterpret_cast<const String *>(p_index._data._mem);
- const String &str=*reinterpret_cast<const String*>(p_index._data._mem);
-
- if (str=="type") {
- valid=true;
+ if (str == "type") {
+ valid = true;
return ie.type;
- } else if (str=="device") {
- valid=true;
+ } else if (str == "device") {
+ valid = true;
return ie.device;
- } else if (str=="ID") {
- valid=true;
+ } else if (str == "ID") {
+ valid = true;
return ie.ID;
}
- if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) {
+ if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) {
- if (str=="shift") {
- valid=true;
+ if (str == "shift") {
+ valid = true;
return ie.key.mod.shift;
- } if (str=="alt") {
- valid=true;
+ }
+ if (str == "alt") {
+ valid = true;
return ie.key.mod.alt;
- } if (str=="control") {
- valid=true;
+ }
+ if (str == "control") {
+ valid = true;
return ie.key.mod.control;
- } if (str=="meta") {
- valid=true;
+ }
+ if (str == "meta") {
+ valid = true;
return ie.key.mod.meta;
}
}
- if (ie.type==InputEvent::KEY) {
+ if (ie.type == InputEvent::KEY) {
- if (str=="pressed") {
- valid=true;
- return ie.key.pressed;
- } else if (str=="scancode") {
- valid=true;
- return ie.key.scancode;
- } else if (str=="unicode") {
- valid=true;
- return ie.key.unicode;
- } else if (str=="echo") {
- valid=true;
- return ie.key.echo;
- }
+ if (str == "pressed") {
+ valid = true;
+ return ie.key.pressed;
+ } else if (str == "scancode") {
+ valid = true;
+ return ie.key.scancode;
+ } else if (str == "unicode") {
+ valid = true;
+ return ie.key.unicode;
+ } else if (str == "echo") {
+ valid = true;
+ return ie.key.echo;
+ }
}
- if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) {
+ if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) {
- if (str=="button_mask") {
- valid=true;
+ if (str == "button_mask") {
+ valid = true;
return ie.mouse_button.button_mask;
- } else if (str=="x") {
- valid=true;
+ } else if (str == "x") {
+ valid = true;
return ie.mouse_button.x;
- } else if (str=="y") {
- valid=true;
+ } else if (str == "y") {
+ valid = true;
return ie.mouse_button.y;
- } else if (str=="pos") {
- valid=true;
- return Point2(ie.mouse_button.x,ie.mouse_button.y);
- } else if (str=="global_x") {
- valid=true;
+ } else if (str == "pos") {
+ valid = true;
+ return Point2(ie.mouse_button.x, ie.mouse_button.y);
+ } else if (str == "global_x") {
+ valid = true;
return ie.mouse_button.global_x;
- } else if (str=="global_y") {
- valid=true;
+ } else if (str == "global_y") {
+ valid = true;
return ie.mouse_button.global_y;
- } else if (str=="global_pos") {
- valid=true;
- return Point2(ie.mouse_button.global_x,ie.mouse_button.global_y);
+ } else if (str == "global_pos") {
+ valid = true;
+ return Point2(ie.mouse_button.global_x, ie.mouse_button.global_y);
} /*else if (str=="pointer_index") {
valid=true;
return ie.mouse_button.pointer_index;
}*/
+ if (ie.type == InputEvent::MOUSE_MOTION) {
- if (ie.type==InputEvent::MOUSE_MOTION) {
-
- if (str=="relative_x") {
- valid=true;
+ if (str == "relative_x") {
+ valid = true;
return ie.mouse_motion.relative_x;
- } else if (str=="relative_y") {
- valid=true;
+ } else if (str == "relative_y") {
+ valid = true;
return ie.mouse_motion.relative_y;
- } else if (str=="relative_pos") {
- valid=true;
- return Point2(ie.mouse_motion.relative_x,ie.mouse_motion.relative_y);
- } else if (str=="speed_x") {
- valid=true;
+ } else if (str == "relative_pos") {
+ valid = true;
+ return Point2(ie.mouse_motion.relative_x, ie.mouse_motion.relative_y);
+ } else if (str == "speed_x") {
+ valid = true;
return ie.mouse_motion.speed_x;
- } else if (str=="speed_y") {
- valid=true;
+ } else if (str == "speed_y") {
+ valid = true;
return ie.mouse_motion.speed_y;
- } else if (str=="speed") {
- valid=true;
- return Point2(ie.mouse_motion.speed_x,ie.mouse_motion.speed_y);
+ } else if (str == "speed") {
+ valid = true;
+ return Point2(ie.mouse_motion.speed_x, ie.mouse_motion.speed_y);
}
+ } else if (ie.type == InputEvent::MOUSE_BUTTON) {
- } else if (ie.type==InputEvent::MOUSE_BUTTON) {
-
- if (str=="button_index") {
- valid=true;
+ if (str == "button_index") {
+ valid = true;
return ie.mouse_button.button_index;
- } else if (str=="pressed") {
- valid=true;
+ } else if (str == "pressed") {
+ valid = true;
return ie.mouse_button.pressed;
- } else if (str=="doubleclick") {
- valid=true;
+ } else if (str == "doubleclick") {
+ valid = true;
return ie.mouse_button.doubleclick;
}
}
-
}
- if (ie.type==InputEvent::JOYPAD_BUTTON) {
+ if (ie.type == InputEvent::JOYPAD_BUTTON) {
- if (str=="button_index") {
- valid=true;
+ if (str == "button_index") {
+ valid = true;
return ie.joy_button.button_index;
- } if (str=="pressed") {
- valid=true;
+ }
+ if (str == "pressed") {
+ valid = true;
return ie.joy_button.pressed;
- } if (str=="pressure") {
- valid=true;
+ }
+ if (str == "pressure") {
+ valid = true;
return ie.joy_button.pressure;
}
-
}
- if (ie.type==InputEvent::JOYPAD_MOTION) {
+ if (ie.type == InputEvent::JOYPAD_MOTION) {
- if (str=="axis") {
- valid=true;
+ if (str == "axis") {
+ valid = true;
return ie.joy_motion.axis;
- } if (str=="value") {
- valid=true;
+ }
+ if (str == "value") {
+ valid = true;
return ie.joy_motion.axis_value;
}
}
- if (ie.type==InputEvent::SCREEN_TOUCH) {
+ if (ie.type == InputEvent::SCREEN_TOUCH) {
- if (str=="index") {
- valid=true;
+ if (str == "index") {
+ valid = true;
return ie.screen_touch.index;
- } if (str=="x") {
- valid=true;
+ }
+ if (str == "x") {
+ valid = true;
return ie.screen_touch.x;
- } if (str=="y") {
- valid=true;
+ }
+ if (str == "y") {
+ valid = true;
return ie.screen_touch.y;
- } if (str=="pos") {
- valid=true;
- return Vector2(ie.screen_touch.x,ie.screen_touch.y);
- } if (str=="pressed") {
- valid=true;
+ }
+ if (str == "pos") {
+ valid = true;
+ return Vector2(ie.screen_touch.x, ie.screen_touch.y);
+ }
+ if (str == "pressed") {
+ valid = true;
return ie.screen_touch.pressed;
}
-
}
- if (ie.type==InputEvent::SCREEN_DRAG) {
+ if (ie.type == InputEvent::SCREEN_DRAG) {
- if (str=="index") {
- valid=true;
+ if (str == "index") {
+ valid = true;
return ie.screen_drag.index;
- } if (str=="x") {
- valid=true;
+ }
+ if (str == "x") {
+ valid = true;
return ie.screen_drag.x;
- } if (str=="y") {
- valid=true;
+ }
+ if (str == "y") {
+ valid = true;
return ie.screen_drag.y;
- } if (str=="pos") {
- valid=true;
- return Vector2(ie.screen_drag.x,ie.screen_drag.y);
- } if (str=="relative_x") {
- valid=true;
+ }
+ if (str == "pos") {
+ valid = true;
+ return Vector2(ie.screen_drag.x, ie.screen_drag.y);
+ }
+ if (str == "relative_x") {
+ valid = true;
return ie.screen_drag.relative_x;
- } if (str=="relative_y") {
- valid=true;
+ }
+ if (str == "relative_y") {
+ valid = true;
return ie.screen_drag.relative_y;
- } if (str=="relative_pos") {
- valid=true;
- return Vector2(ie.screen_drag.relative_x,ie.screen_drag.relative_y);
- } if (str=="speed_x") {
- valid=true;
+ }
+ if (str == "relative_pos") {
+ valid = true;
+ return Vector2(ie.screen_drag.relative_x, ie.screen_drag.relative_y);
+ }
+ if (str == "speed_x") {
+ valid = true;
return ie.screen_drag.speed_x;
- } if (str=="speed_y") {
- valid=true;
+ }
+ if (str == "speed_y") {
+ valid = true;
return ie.screen_drag.speed_y;
- } if (str=="speed") {
- valid=true;
- return Vector2(ie.screen_drag.speed_x,ie.screen_drag.speed_y);
+ }
+ if (str == "speed") {
+ valid = true;
+ return Vector2(ie.screen_drag.speed_x, ie.screen_drag.speed_y);
}
}
if (ie.type == InputEvent::ACTION) {
- if (str =="action") {
- valid=true;
+ if (str == "action") {
+ valid = true;
return ie.action.action;
- }
- else if (str == "pressed") {
- valid=true;
+ } else if (str == "pressed") {
+ valid = true;
return ie.action.pressed;
}
}
@@ -2465,44 +2497,42 @@ Variant Variant::get(const Variant& p_index, bool *r_valid) const {
} break;
case DICTIONARY: {
- const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem);
- const Variant * res = dic->getptr(p_index);
+ const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem);
+ const Variant *res = dic->getptr(p_index);
if (res) {
- valid=true;
+ valid = true;
return *res;
}
- } break; // 20
- DEFAULT_OP_ARRAY_CMD(ARRAY, const Array, ;, return (*arr)[index])
- DEFAULT_OP_DVECTOR_GET(POOL_BYTE_ARRAY, uint8_t)
- DEFAULT_OP_DVECTOR_GET(POOL_INT_ARRAY, int)
- DEFAULT_OP_DVECTOR_GET(POOL_REAL_ARRAY, real_t)
- DEFAULT_OP_DVECTOR_GET(POOL_STRING_ARRAY, String)
- DEFAULT_OP_DVECTOR_GET(POOL_VECTOR2_ARRAY, Vector2)
- DEFAULT_OP_DVECTOR_GET(POOL_VECTOR3_ARRAY, Vector3)
- DEFAULT_OP_DVECTOR_GET(POOL_COLOR_ARRAY, Color)
+ } break; // 20
+ DEFAULT_OP_ARRAY_CMD(ARRAY, const Array, ;, return (*arr)[index])
+ DEFAULT_OP_DVECTOR_GET(POOL_BYTE_ARRAY, uint8_t)
+ DEFAULT_OP_DVECTOR_GET(POOL_INT_ARRAY, int)
+ DEFAULT_OP_DVECTOR_GET(POOL_REAL_ARRAY, real_t)
+ DEFAULT_OP_DVECTOR_GET(POOL_STRING_ARRAY, String)
+ DEFAULT_OP_DVECTOR_GET(POOL_VECTOR2_ARRAY, Vector2)
+ DEFAULT_OP_DVECTOR_GET(POOL_VECTOR3_ARRAY, Vector3)
+ DEFAULT_OP_DVECTOR_GET(POOL_COLOR_ARRAY, Color)
default: return Variant();
}
return Variant();
-
}
-
-bool Variant::in(const Variant& p_index, bool *r_valid) const {
+bool Variant::in(const Variant &p_index, bool *r_valid) const {
if (r_valid)
- *r_valid=true;
+ *r_valid = true;
- switch(type) {
+ switch (type) {
case STRING: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
//string index
- String idx=p_index;
- const String *str=reinterpret_cast<const String*>(_data._mem);
+ String idx = p_index;
+ const String *str = reinterpret_cast<const String *>(_data._mem);
- return str->find(idx)!=-1;
+ return str->find(idx) != -1;
}
} break;
@@ -2510,68 +2540,65 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
Object *obj = _get_obj().obj;
if (obj) {
-
- bool valid=false;
+ bool valid = false;
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
//only if debugging!
if (!ObjectDB::instance_validate(obj)) {
if (r_valid) {
- *r_valid=false;
+ *r_valid = false;
}
return "Attempted get on stray pointer.";
}
}
#endif
- if (p_index.get_type()!=Variant::STRING) {
- obj->getvar(p_index,&valid);
+ if (p_index.get_type() != Variant::STRING) {
+ obj->getvar(p_index, &valid);
} else {
- obj->get(p_index,&valid);
+ obj->get(p_index, &valid);
}
return valid;
} else {
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
}
return false;
} break;
case DICTIONARY: {
- const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem);
+ const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem);
return dic->has(p_index);
- } break; // 20
+ } break; // 20
case ARRAY: {
- const Array *arr=reinterpret_cast<const Array* >(_data._mem);
+ const Array *arr = reinterpret_cast<const Array *>(_data._mem);
int l = arr->size();
if (l) {
- for(int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- if (evaluate(OP_EQUAL,(*arr)[i],p_index))
+ if (evaluate(OP_EQUAL, (*arr)[i], p_index))
return true;
}
-
}
return false;
} break;
case POOL_BYTE_ARRAY: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>* >(_data._mem);
- int l=arr->size();
+ const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
+ int l = arr->size();
if (l) {
PoolVector<uint8_t>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2579,18 +2606,17 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
} break;
case POOL_INT_ARRAY: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
int index = p_index;
- const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>* >(_data._mem);
- int l=arr->size();
+ const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem);
+ int l = arr->size();
if (l) {
PoolVector<int>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2598,18 +2624,17 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
} break;
case POOL_REAL_ARRAY: {
- if (p_index.get_type()==Variant::INT || p_index.get_type()==Variant::REAL) {
+ if (p_index.get_type() == Variant::INT || p_index.get_type() == Variant::REAL) {
real_t index = p_index;
- const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>* >(_data._mem);
- int l=arr->size();
+ const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
+ int l = arr->size();
if (l) {
PoolVector<real_t>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2617,39 +2642,37 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
} break;
case POOL_STRING_ARRAY: {
- if (p_index.get_type()==Variant::STRING) {
+ if (p_index.get_type() == Variant::STRING) {
String index = p_index;
- const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>* >(_data._mem);
+ const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem);
- int l=arr->size();
+ int l = arr->size();
if (l) {
PoolVector<String>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
}
- } break; //25
+ } break; //25
case POOL_VECTOR2_ARRAY: {
- if (p_index.get_type()==Variant::VECTOR2) {
+ if (p_index.get_type() == Variant::VECTOR2) {
Vector2 index = p_index;
- const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>* >(_data._mem);
+ const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
- int l=arr->size();
+ int l = arr->size();
if (l) {
PoolVector<Vector2>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2657,19 +2680,18 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
} break;
case POOL_VECTOR3_ARRAY: {
- if (p_index.get_type()==Variant::VECTOR3) {
+ if (p_index.get_type() == Variant::VECTOR3) {
Vector3 index = p_index;
- const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>* >(_data._mem);
+ const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
- int l=arr->size();
+ int l = arr->size();
if (l) {
PoolVector<Vector3>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2678,20 +2700,18 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
} break;
case POOL_COLOR_ARRAY: {
- if (p_index.get_type()==Variant::COLOR) {
+ if (p_index.get_type() == Variant::COLOR) {
Color index = p_index;
- const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>* >(_data._mem);
-
+ const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem);
- int l=arr->size();
+ int l = arr->size();
if (l) {
PoolVector<Color>::Read r = arr->read();
- for(int i=0;i<l;i++) {
- if (r[i]==index)
+ for (int i = 0; i < l; i++) {
+ if (r[i] == index)
return true;
}
-
}
return false;
@@ -2701,98 +2721,100 @@ bool Variant::in(const Variant& p_index, bool *r_valid) const {
}
if (r_valid)
- *r_valid=false;
+ *r_valid = false;
return false;
}
void Variant::get_property_list(List<PropertyInfo> *p_list) const {
-
- switch(type) {
+ switch (type) {
case VECTOR2: {
- p_list->push_back( PropertyInfo(Variant::REAL,"x"));
- p_list->push_back( PropertyInfo(Variant::REAL,"y"));
- p_list->push_back( PropertyInfo(Variant::REAL,"width"));
- p_list->push_back( PropertyInfo(Variant::REAL,"height"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "width"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "height"));
- } break; // 5
+ } break; // 5
case RECT2: {
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos"));
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"size"));
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"end"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "size"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "end"));
} break;
case VECTOR3: {
- p_list->push_back( PropertyInfo(Variant::REAL,"x"));
- p_list->push_back( PropertyInfo(Variant::REAL,"y"));
- p_list->push_back( PropertyInfo(Variant::REAL,"z"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "z"));
} break;
case TRANSFORM2D: {
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"x"));
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"y"));
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"o"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "x"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "o"));
} break;
case PLANE: {
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"normal"));
- p_list->push_back( PropertyInfo(Variant::REAL,"x"));
- p_list->push_back( PropertyInfo(Variant::REAL,"y"));
- p_list->push_back( PropertyInfo(Variant::REAL,"z"));
- p_list->push_back( PropertyInfo(Variant::REAL,"d"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "normal"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "z"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "d"));
} break;
case QUAT: {
- p_list->push_back( PropertyInfo(Variant::REAL,"x"));
- p_list->push_back( PropertyInfo(Variant::REAL,"y"));
- p_list->push_back( PropertyInfo(Variant::REAL,"z"));
- p_list->push_back( PropertyInfo(Variant::REAL,"w"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "z"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "w"));
} break;
case RECT3: {
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"pos"));
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"size"));
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"end"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "pos"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "size"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "end"));
} break; //sorry naming convention fail :( not like it's used often // 10
case BASIS: {
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"x"));
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"y"));
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"z"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "x"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "z"));
} break;
case TRANSFORM: {
- p_list->push_back( PropertyInfo(Variant::BASIS,"basis"));
- p_list->push_back( PropertyInfo(Variant::VECTOR3,"origin"));
+ p_list->push_back(PropertyInfo(Variant::BASIS, "basis"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "origin"));
} break;
case COLOR: {
- p_list->push_back( PropertyInfo(Variant::REAL,"r"));
- p_list->push_back( PropertyInfo(Variant::REAL,"g"));
- p_list->push_back( PropertyInfo(Variant::REAL,"b"));
- p_list->push_back( PropertyInfo(Variant::REAL,"a"));
- p_list->push_back( PropertyInfo(Variant::REAL,"h"));
- p_list->push_back( PropertyInfo(Variant::REAL,"s"));
- p_list->push_back( PropertyInfo(Variant::REAL,"v"));
- p_list->push_back( PropertyInfo(Variant::INT,"r8"));
- p_list->push_back( PropertyInfo(Variant::INT,"g8"));
- p_list->push_back( PropertyInfo(Variant::INT,"b8"));
- p_list->push_back( PropertyInfo(Variant::INT,"a8"));
-
- } break;
- case IMAGE: { } break;
- case NODE_PATH: { } break; // 15
- case _RID: { } break;
+ p_list->push_back(PropertyInfo(Variant::REAL, "r"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "g"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "b"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "a"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "h"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "s"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "v"));
+ p_list->push_back(PropertyInfo(Variant::INT, "r8"));
+ p_list->push_back(PropertyInfo(Variant::INT, "g8"));
+ p_list->push_back(PropertyInfo(Variant::INT, "b8"));
+ p_list->push_back(PropertyInfo(Variant::INT, "a8"));
+
+ } break;
+ case IMAGE: {
+ } break;
+ case NODE_PATH: {
+ } break; // 15
+ case _RID: {
+ } break;
case OBJECT: {
- Object *obj=_get_obj().obj;
+ Object *obj = _get_obj().obj;
if (obj) {
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
@@ -2812,109 +2834,101 @@ void Variant::get_property_list(List<PropertyInfo> *p_list) const {
InputEvent ie = operator InputEvent();
+ p_list->push_back(PropertyInfo(Variant::INT, "type"));
+ p_list->push_back(PropertyInfo(Variant::INT, "device"));
+ p_list->push_back(PropertyInfo(Variant::INT, "ID"));
+ if (ie.type == InputEvent::KEY || ie.type == InputEvent::MOUSE_BUTTON || ie.type == InputEvent::MOUSE_MOTION) {
- p_list->push_back( PropertyInfo(Variant::INT,"type"));
- p_list->push_back( PropertyInfo(Variant::INT,"device"));
- p_list->push_back( PropertyInfo(Variant::INT,"ID"));
-
- if (ie.type==InputEvent::KEY || ie.type==InputEvent::MOUSE_BUTTON || ie.type==InputEvent::MOUSE_MOTION) {
-
- p_list->push_back( PropertyInfo(Variant::BOOL,"shift"));
- p_list->push_back( PropertyInfo(Variant::BOOL,"alt"));
- p_list->push_back( PropertyInfo(Variant::BOOL,"control"));
- p_list->push_back( PropertyInfo(Variant::BOOL,"meta"));
-
+ p_list->push_back(PropertyInfo(Variant::BOOL, "shift"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "alt"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "control"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "meta"));
}
- if (ie.type==InputEvent::KEY) {
+ if (ie.type == InputEvent::KEY) {
- p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") );
- p_list->push_back( PropertyInfo(Variant::BOOL,"echo") );
- p_list->push_back( PropertyInfo(Variant::INT,"scancode") );
- p_list->push_back( PropertyInfo(Variant::INT,"unicode") );
+ p_list->push_back(PropertyInfo(Variant::BOOL, "pressed"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "echo"));
+ p_list->push_back(PropertyInfo(Variant::INT, "scancode"));
+ p_list->push_back(PropertyInfo(Variant::INT, "unicode"));
}
- if (ie.type==InputEvent::MOUSE_MOTION || ie.type==InputEvent::MOUSE_BUTTON) {
-
- p_list->push_back( PropertyInfo(Variant::INT,"button_mask") );
- p_list->push_back( PropertyInfo(Variant::REAL,"x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") );
- p_list->push_back( PropertyInfo(Variant::REAL,"global_x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"global_y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"global_pos") );
+ if (ie.type == InputEvent::MOUSE_MOTION || ie.type == InputEvent::MOUSE_BUTTON) {
+ p_list->push_back(PropertyInfo(Variant::INT, "button_mask"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "global_x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "global_y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "global_pos"));
- if (ie.type==InputEvent::MOUSE_MOTION) {
+ if (ie.type == InputEvent::MOUSE_MOTION) {
- p_list->push_back( PropertyInfo(Variant::REAL,"relative_x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"relative_y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"relative_pos") );
- p_list->push_back( PropertyInfo(Variant::REAL,"speed_x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"speed_y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"speed") );
+ p_list->push_back(PropertyInfo(Variant::REAL, "relative_x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "relative_y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "relative_pos"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "speed_x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "speed_y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "speed"));
- } else if (ie.type==InputEvent::MOUSE_BUTTON) {
-
- p_list->push_back( PropertyInfo(Variant::INT,"button_index") );
- p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") );
- p_list->push_back( PropertyInfo(Variant::BOOL,"doubleclick") );
+ } else if (ie.type == InputEvent::MOUSE_BUTTON) {
+ p_list->push_back(PropertyInfo(Variant::INT, "button_index"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "pressed"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "doubleclick"));
}
-
}
- if (ie.type==InputEvent::JOYPAD_BUTTON) {
-
- p_list->push_back( PropertyInfo(Variant::INT,"button_index") );
- p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") );
- p_list->push_back( PropertyInfo(Variant::REAL,"pressure") );
+ if (ie.type == InputEvent::JOYPAD_BUTTON) {
+ p_list->push_back(PropertyInfo(Variant::INT, "button_index"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "pressed"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "pressure"));
}
- if (ie.type==InputEvent::JOYPAD_MOTION) {
-
- p_list->push_back( PropertyInfo(Variant::INT,"axis") );
- p_list->push_back( PropertyInfo(Variant::REAL,"value") );
+ if (ie.type == InputEvent::JOYPAD_MOTION) {
+ p_list->push_back(PropertyInfo(Variant::INT, "axis"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "value"));
}
- if (ie.type==InputEvent::SCREEN_TOUCH) {
+ if (ie.type == InputEvent::SCREEN_TOUCH) {
- p_list->push_back( PropertyInfo(Variant::INT,"index") );
- p_list->push_back( PropertyInfo(Variant::REAL,"x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") );
- p_list->push_back( PropertyInfo(Variant::BOOL,"pressed") );
+ p_list->push_back(PropertyInfo(Variant::INT, "index"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "pressed"));
}
- if (ie.type==InputEvent::SCREEN_DRAG) {
+ if (ie.type == InputEvent::SCREEN_DRAG) {
- p_list->push_back( PropertyInfo(Variant::INT,"index") );
- p_list->push_back( PropertyInfo(Variant::REAL,"x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"pos") );
- p_list->push_back( PropertyInfo(Variant::REAL,"relative_x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"relative_y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"relative_pos") );
- p_list->push_back( PropertyInfo(Variant::REAL,"speed_x") );
- p_list->push_back( PropertyInfo(Variant::REAL,"speed_y") );
- p_list->push_back( PropertyInfo(Variant::VECTOR2,"speed") );
+ p_list->push_back(PropertyInfo(Variant::INT, "index"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "pos"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "relative_x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "relative_y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "relative_pos"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "speed_x"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "speed_y"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "speed"));
}
} break;
case DICTIONARY: {
- const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem);
+ const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem);
List<Variant> keys;
dic->get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
- if (E->get().get_type()==Variant::STRING) {
- p_list->push_back(PropertyInfo(Variant::STRING,E->get()));
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
+ if (E->get().get_type() == Variant::STRING) {
+ p_list->push_back(PropertyInfo(Variant::STRING, E->get()));
}
}
- } break; // 20
+ } break; // 20
case ARRAY:
case POOL_BYTE_ARRAY:
case POOL_INT_ARRAY:
@@ -2927,44 +2941,41 @@ void Variant::get_property_list(List<PropertyInfo> *p_list) const {
} break;
default: {}
}
-
-
}
-bool Variant::iter_init(Variant& r_iter,bool &valid) const {
+bool Variant::iter_init(Variant &r_iter, bool &valid) const {
-
- valid=true;
- switch(type) {
+ valid = true;
+ switch (type) {
case INT: {
- r_iter=0;
- return _data._int>0;
+ r_iter = 0;
+ return _data._int > 0;
} break;
case REAL: {
- r_iter=0.0;
- return _data._real>0.0;
+ r_iter = 0.0;
+ return _data._real > 0.0;
} break;
case VECTOR2: {
- real_t from = reinterpret_cast<const Vector2*>(_data._mem)->x;
- real_t to = reinterpret_cast<const Vector2*>(_data._mem)->y;
+ real_t from = reinterpret_cast<const Vector2 *>(_data._mem)->x;
+ real_t to = reinterpret_cast<const Vector2 *>(_data._mem)->y;
- r_iter=from;
+ r_iter = from;
return from < to;
} break;
case VECTOR3: {
- real_t from = reinterpret_cast<const Vector3*>(_data._mem)->x;
- real_t to = reinterpret_cast<const Vector3*>(_data._mem)->y;
- real_t step = reinterpret_cast<const Vector3*>(_data._mem)->z;
+ real_t from = reinterpret_cast<const Vector3 *>(_data._mem)->x;
+ real_t to = reinterpret_cast<const Vector3 *>(_data._mem)->y;
+ real_t step = reinterpret_cast<const Vector3 *>(_data._mem)->z;
- r_iter=from;
+ r_iter = from;
- if (from == to ) {
+ if (from == to) {
return false;
} else if (from < to) {
- return step>0.0;
+ return step > 0.0;
} else {
- return step<0.0;
+ return step < 0.0;
}
//return true;
} break;
@@ -2972,35 +2983,35 @@ bool Variant::iter_init(Variant& r_iter,bool &valid) const {
#ifdef DEBUG_ENABLED
if (!_get_obj().obj) {
- valid=false;
+ valid = false;
return false;
}
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) {
- valid=false;
+ valid = false;
return false;
}
#endif
Variant::CallError ce;
- ce.error=Variant::CallError::CALL_OK;
+ ce.error = Variant::CallError::CALL_OK;
Array ref;
ref.push_back(r_iter);
- Variant vref=ref;
- const Variant *refp[]={&vref};
- Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_init,refp,1,ce);
+ Variant vref = ref;
+ const Variant *refp[] = { &vref };
+ Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_init, refp, 1, ce);
- if (ref.size()!=1 || ce.error!=Variant::CallError::CALL_OK) {
- valid=false;
+ if (ref.size() != 1 || ce.error != Variant::CallError::CALL_OK) {
+ valid = false;
return false;
}
- r_iter=ref[0];
+ r_iter = ref[0];
return ret;
} break;
case STRING: {
- const String *str=reinterpret_cast<const String*>(_data._mem);
+ const String *str = reinterpret_cast<const String *>(_data._mem);
if (str->empty())
return false;
r_iter = 0;
@@ -3008,91 +3019,89 @@ bool Variant::iter_init(Variant& r_iter,bool &valid) const {
} break;
case DICTIONARY: {
- const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem);
+ const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem);
if (dic->empty())
return false;
- const Variant *next=dic->next(NULL);
- r_iter=*next;
+ const Variant *next = dic->next(NULL);
+ r_iter = *next;
return true;
} break;
case ARRAY: {
- const Array *arr=reinterpret_cast<const Array*>(_data._mem);
+ const Array *arr = reinterpret_cast<const Array *>(_data._mem);
if (arr->empty())
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_BYTE_ARRAY: {
- const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_INT_ARRAY: {
- const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_REAL_ARRAY: {
- const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_STRING_ARRAY: {
- const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_VECTOR2_ARRAY: {
- const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_VECTOR3_ARRAY: {
- const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
case POOL_COLOR_ARRAY: {
- const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem);
- if (arr->size()==0)
+ const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem);
+ if (arr->size() == 0)
return false;
- r_iter=0;
+ r_iter = 0;
return true;
} break;
default: {}
-
}
- valid=false;
+ valid = false;
return false;
}
-bool Variant::iter_next(Variant& r_iter,bool &valid) const {
+bool Variant::iter_next(Variant &r_iter, bool &valid) const {
-
- valid=true;
- switch(type) {
+ valid = true;
+ switch (type) {
case INT: {
int64_t idx = r_iter;
@@ -3105,7 +3114,7 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const {
case REAL: {
double idx = r_iter;
- idx+=1.0;
+ idx += 1.0;
if (idx >= _data._real)
return false;
r_iter = idx;
@@ -3113,62 +3122,62 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const {
} break;
case VECTOR2: {
real_t idx = r_iter;
- idx+=1.0;
- if (idx>=reinterpret_cast<const Vector2*>(_data._mem)->y)
+ idx += 1.0;
+ if (idx >= reinterpret_cast<const Vector2 *>(_data._mem)->y)
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case VECTOR3: {
- real_t to = reinterpret_cast<const Vector3*>(_data._mem)->y;
- real_t step = reinterpret_cast<const Vector3*>(_data._mem)->z;
+ real_t to = reinterpret_cast<const Vector3 *>(_data._mem)->y;
+ real_t step = reinterpret_cast<const Vector3 *>(_data._mem)->z;
real_t idx = r_iter;
- idx+=step;
+ idx += step;
- if (step<0.0 && idx <= to)
+ if (step < 0.0 && idx <= to)
return false;
- if (step>0.0 && idx >= to)
+ if (step > 0.0 && idx >= to)
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case OBJECT: {
#ifdef DEBUG_ENABLED
if (!_get_obj().obj) {
- valid=false;
+ valid = false;
return false;
}
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) {
- valid=false;
+ valid = false;
return false;
}
#endif
Variant::CallError ce;
- ce.error=Variant::CallError::CALL_OK;
+ ce.error = Variant::CallError::CALL_OK;
Array ref;
ref.push_back(r_iter);
- Variant vref=ref;
- const Variant *refp[]={&vref};
- Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_next,refp,1,ce);
+ Variant vref = ref;
+ const Variant *refp[] = { &vref };
+ Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_next, refp, 1, ce);
- if (ref.size()!=1 || ce.error!=Variant::CallError::CALL_OK) {
- valid=false;
+ if (ref.size() != 1 || ce.error != Variant::CallError::CALL_OK) {
+ valid = false;
return false;
}
- r_iter=ref[0];
+ r_iter = ref[0];
return ret;
} break;
case STRING: {
- const String *str=reinterpret_cast<const String*>(_data._mem);
+ const String *str = reinterpret_cast<const String *>(_data._mem);
int idx = r_iter;
idx++;
if (idx >= str->length())
@@ -3178,107 +3187,105 @@ bool Variant::iter_next(Variant& r_iter,bool &valid) const {
} break;
case DICTIONARY: {
- const Dictionary *dic=reinterpret_cast<const Dictionary*>(_data._mem);
- const Variant *next=dic->next(&r_iter);
+ const Dictionary *dic = reinterpret_cast<const Dictionary *>(_data._mem);
+ const Variant *next = dic->next(&r_iter);
if (!next)
return false;
- r_iter=*next;
+ r_iter = *next;
return true;
} break;
case ARRAY: {
- const Array *arr=reinterpret_cast<const Array*>(_data._mem);
- int idx=r_iter;
+ const Array *arr = reinterpret_cast<const Array *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_BYTE_ARRAY: {
- const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_INT_ARRAY: {
- const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_REAL_ARRAY: {
- const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_STRING_ARRAY: {
- const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_VECTOR2_ARRAY: {
- const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_VECTOR3_ARRAY: {
- const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
case POOL_COLOR_ARRAY: {
- const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem);
+ int idx = r_iter;
idx++;
- if (idx>=arr->size())
+ if (idx >= arr->size())
return false;
- r_iter=idx;
+ r_iter = idx;
return true;
} break;
default: {}
-
}
- valid=false;
+ valid = false;
return false;
}
-Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
-
+Variant Variant::iter_get(const Variant &r_iter, bool &r_valid) const {
- r_valid=true;
- switch(type) {
+ r_valid = true;
+ switch (type) {
case INT: {
return r_iter;
@@ -3299,22 +3306,22 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
#ifdef DEBUG_ENABLED
if (!_get_obj().obj) {
- r_valid=false;
+ r_valid = false;
return Variant();
}
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null() && !ObjectDB::instance_validate(_get_obj().obj)) {
- r_valid=false;
+ r_valid = false;
return Variant();
}
#endif
Variant::CallError ce;
- ce.error=Variant::CallError::CALL_OK;
- const Variant *refp[]={&r_iter};
- Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_get,refp,1,ce);
+ ce.error = Variant::CallError::CALL_OK;
+ const Variant *refp[] = { &r_iter };
+ Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->_iter_get, refp, 1, ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
- r_valid=false;
+ if (ce.error != Variant::CallError::CALL_OK) {
+ r_valid = false;
return Variant();
}
@@ -3325,8 +3332,8 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
case STRING: {
- const String *str=reinterpret_cast<const String*>(_data._mem);
- return str->substr(r_iter,1);
+ const String *str = reinterpret_cast<const String *>(_data._mem);
+ return str->substr(r_iter, 1);
} break;
case DICTIONARY: {
@@ -3335,55 +3342,55 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
} break;
case ARRAY: {
- const Array *arr=reinterpret_cast<const Array*>(_data._mem);
- int idx=r_iter;
+ const Array *arr = reinterpret_cast<const Array *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
return arr->get(idx);
} break;
case POOL_BYTE_ARRAY: {
- const PoolVector<uint8_t> *arr=reinterpret_cast<const PoolVector<uint8_t>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<uint8_t> *arr = reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
return arr->get(idx);
} break;
case POOL_INT_ARRAY: {
- const PoolVector<int> *arr=reinterpret_cast<const PoolVector<int>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<int> *arr = reinterpret_cast<const PoolVector<int> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
return arr->get(idx);
} break;
case POOL_REAL_ARRAY: {
- const PoolVector<real_t> *arr=reinterpret_cast<const PoolVector<real_t>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<real_t> *arr = reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
return arr->get(idx);
} break;
case POOL_STRING_ARRAY: {
- const PoolVector<String> *arr=reinterpret_cast<const PoolVector<String>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<String> *arr = reinterpret_cast<const PoolVector<String> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
@@ -3391,23 +3398,23 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
} break;
case POOL_VECTOR2_ARRAY: {
- const PoolVector<Vector2> *arr=reinterpret_cast<const PoolVector<Vector2>*>(_data._mem);
- int idx=r_iter;
- #ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ const PoolVector<Vector2> *arr = reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
+ int idx = r_iter;
+#ifdef DEBUG_ENABLED
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
- #endif
+#endif
return arr->get(idx);
} break;
case POOL_VECTOR3_ARRAY: {
- const PoolVector<Vector3> *arr=reinterpret_cast<const PoolVector<Vector3>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<Vector3> *arr = reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
@@ -3415,240 +3422,318 @@ Variant Variant::iter_get(const Variant& r_iter,bool &r_valid) const {
} break;
case POOL_COLOR_ARRAY: {
- const PoolVector<Color> *arr=reinterpret_cast<const PoolVector<Color>*>(_data._mem);
- int idx=r_iter;
+ const PoolVector<Color> *arr = reinterpret_cast<const PoolVector<Color> *>(_data._mem);
+ int idx = r_iter;
#ifdef DEBUG_ENABLED
- if (idx<0 || idx>=arr->size()) {
- r_valid=false;
+ if (idx < 0 || idx >= arr->size()) {
+ r_valid = false;
return Variant();
}
#endif
return arr->get(idx);
} break;
default: {}
-
}
- r_valid=false;
+ r_valid = false;
return Variant();
-
}
-void Variant::blend(const Variant& a, const Variant& b, float c, Variant &r_dst) {
- if (a.type!=b.type) {
- if(a.is_num() && b.is_num()) {
- real_t va=a;
- real_t vb=b;
- r_dst=va + vb * c;
+void Variant::blend(const Variant &a, const Variant &b, float c, Variant &r_dst) {
+ if (a.type != b.type) {
+ if (a.is_num() && b.is_num()) {
+ real_t va = a;
+ real_t vb = b;
+ r_dst = va + vb * c;
} else {
- r_dst=a;
+ r_dst = a;
}
return;
}
- switch(a.type) {
- case NIL: { r_dst=Variant(); } return;
- case INT:{
- int64_t va=a._data._int;
- int64_t vb=b._data._int;
- r_dst=int(va + vb * c + 0.5);
- } return;
- case REAL:{
- double ra=a._data._real;
- double rb=b._data._real;
- r_dst=ra + rb * c;
- } return;
- case VECTOR2:{ r_dst=*reinterpret_cast<const Vector2*>(a._data._mem)+*reinterpret_cast<const Vector2*>(b._data._mem)*c; } return;
- case RECT2:{
- const Rect2 *ra = reinterpret_cast<const Rect2*>(a._data._mem);
- const Rect2 *rb = reinterpret_cast<const Rect2*>(b._data._mem);
- r_dst=Rect2(ra->pos + rb->pos * c, ra->size + rb->size * c);
- } return;
- case VECTOR3:{ r_dst=*reinterpret_cast<const Vector3*>(a._data._mem)+*reinterpret_cast<const Vector3*>(b._data._mem)*c; } return;
- case RECT3:{
- const Rect3 *ra = reinterpret_cast<const Rect3*>(a._data._mem);
- const Rect3 *rb = reinterpret_cast<const Rect3*>(b._data._mem);
- r_dst=Rect3(ra->pos + rb->pos * c, ra->size + rb->size * c);
- } return;
- case QUAT:{
- Quat empty_rot;
- const Quat *qa = reinterpret_cast<const Quat*>(a._data._mem);
- const Quat *qb = reinterpret_cast<const Quat*>(b._data._mem);
- r_dst=*qa * empty_rot.slerp(*qb,c);
- } return;
- case COLOR:{
- const Color *ca = reinterpret_cast<const Color*>(a._data._mem);
- const Color *cb = reinterpret_cast<const Color*>(b._data._mem);
- float r = ca->r + cb->r * c;
- float g = ca->g + cb->g * c;
- float b = ca->b + cb->b * c;
- float a = ca->a + cb->a * c;
- r = r > 1.0 ? 1.0 : r;
- g = g > 1.0 ? 1.0 : g;
- b = b > 1.0 ? 1.0 : b;
- a = a > 1.0 ? 1.0 : a;
- r_dst=Color(r, g, b, a);
- } return;
- default:{ r_dst = c<0.5 ? a : b; } return;
+ switch (a.type) {
+ case NIL: {
+ r_dst = Variant();
+ }
+ return;
+ case INT: {
+ int64_t va = a._data._int;
+ int64_t vb = b._data._int;
+ r_dst = int(va + vb * c + 0.5);
+ }
+ return;
+ case REAL: {
+ double ra = a._data._real;
+ double rb = b._data._real;
+ r_dst = ra + rb * c;
+ }
+ return;
+ case VECTOR2: {
+ r_dst = *reinterpret_cast<const Vector2 *>(a._data._mem) + *reinterpret_cast<const Vector2 *>(b._data._mem) * c;
+ }
+ return;
+ case RECT2: {
+ const Rect2 *ra = reinterpret_cast<const Rect2 *>(a._data._mem);
+ const Rect2 *rb = reinterpret_cast<const Rect2 *>(b._data._mem);
+ r_dst = Rect2(ra->pos + rb->pos * c, ra->size + rb->size * c);
+ }
+ return;
+ case VECTOR3: {
+ r_dst = *reinterpret_cast<const Vector3 *>(a._data._mem) + *reinterpret_cast<const Vector3 *>(b._data._mem) * c;
+ }
+ return;
+ case RECT3: {
+ const Rect3 *ra = reinterpret_cast<const Rect3 *>(a._data._mem);
+ const Rect3 *rb = reinterpret_cast<const Rect3 *>(b._data._mem);
+ r_dst = Rect3(ra->pos + rb->pos * c, ra->size + rb->size * c);
+ }
+ return;
+ case QUAT: {
+ Quat empty_rot;
+ const Quat *qa = reinterpret_cast<const Quat *>(a._data._mem);
+ const Quat *qb = reinterpret_cast<const Quat *>(b._data._mem);
+ r_dst = *qa * empty_rot.slerp(*qb, c);
+ }
+ return;
+ case COLOR: {
+ const Color *ca = reinterpret_cast<const Color *>(a._data._mem);
+ const Color *cb = reinterpret_cast<const Color *>(b._data._mem);
+ float r = ca->r + cb->r * c;
+ float g = ca->g + cb->g * c;
+ float b = ca->b + cb->b * c;
+ float a = ca->a + cb->a * c;
+ r = r > 1.0 ? 1.0 : r;
+ g = g > 1.0 ? 1.0 : g;
+ b = b > 1.0 ? 1.0 : b;
+ a = a > 1.0 ? 1.0 : a;
+ r_dst = Color(r, g, b, a);
+ }
+ return;
+ default: { r_dst = c < 0.5 ? a : b; }
+ return;
}
}
-void Variant::interpolate(const Variant& a, const Variant& b, float c,Variant &r_dst) {
+void Variant::interpolate(const Variant &a, const Variant &b, float c, Variant &r_dst) {
- if (a.type!=b.type) {
+ if (a.type != b.type) {
if (a.is_num() && b.is_num()) {
//not as efficient but..
- real_t va=a;
- real_t vb=b;
- r_dst=(1.0-c) * va + vb * c;
+ real_t va = a;
+ real_t vb = b;
+ r_dst = (1.0 - c) * va + vb * c;
} else {
- r_dst=a;
+ r_dst = a;
}
return;
}
+ switch (a.type) {
- switch(a.type) {
-
- case NIL:{ r_dst=Variant(); } return;
- case BOOL:{ r_dst=a; } return;
- case INT:{
- int64_t va=a._data._int;
- int64_t vb=b._data._int;
- r_dst=int((1.0-c) * va + vb * c);
- } return;
- case REAL:{
- real_t va=a._data._real;
- real_t vb=b._data._real;
- r_dst=(1.0-c) * va + vb * c;
-
- } return;
- case STRING:{
+ case NIL: {
+ r_dst = Variant();
+ }
+ return;
+ case BOOL: {
+ r_dst = a;
+ }
+ return;
+ case INT: {
+ int64_t va = a._data._int;
+ int64_t vb = b._data._int;
+ r_dst = int((1.0 - c) * va + vb * c);
+ }
+ return;
+ case REAL: {
+ real_t va = a._data._real;
+ real_t vb = b._data._real;
+ r_dst = (1.0 - c) * va + vb * c;
+ }
+ return;
+ case STRING: {
//this is pretty funny and bizarre, but artists like to use it for typewritter effects
- String sa = *reinterpret_cast<const String*>(a._data._mem);
- String sb = *reinterpret_cast<const String*>(b._data._mem);
+ String sa = *reinterpret_cast<const String *>(a._data._mem);
+ String sb = *reinterpret_cast<const String *>(b._data._mem);
String dst;
- int csize=sb.length() * c + sa.length() * (1.0-c);
- if (csize==0) {
- r_dst="";
+ int csize = sb.length() * c + sa.length() * (1.0 - c);
+ if (csize == 0) {
+ r_dst = "";
return;
}
- dst.resize(csize+1);
- dst[csize]=0;
- int split = csize/2;
+ dst.resize(csize + 1);
+ dst[csize] = 0;
+ int split = csize / 2;
- for(int i=0;i<csize;i++) {
+ for (int i = 0; i < csize; i++) {
- CharType chr=' ';
+ CharType chr = ' ';
- if (i<split) {
+ if (i < split) {
- if (i<sa.length())
- chr=sa[i];
- else if (i<sb.length())
- chr=sb[i];
+ if (i < sa.length())
+ chr = sa[i];
+ else if (i < sb.length())
+ chr = sb[i];
} else {
- if (i<sb.length())
- chr=sb[i];
- else if (i<sa.length())
- chr=sa[i];
- }
-
- dst[i]=chr;
- }
-
- r_dst=dst;
-
-
- } return;
- case VECTOR2:{ r_dst=reinterpret_cast<const Vector2*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector2*>(b._data._mem),c); } return;
- case RECT2:{ r_dst = Rect2( reinterpret_cast<const Rect2*>(a._data._mem)->pos.linear_interpolate(reinterpret_cast<const Rect2*>(b._data._mem)->pos,c), reinterpret_cast<const Rect2*>(a._data._mem)->size.linear_interpolate(reinterpret_cast<const Rect2*>(b._data._mem)->size,c) ); } return;
- case VECTOR3:{ r_dst=reinterpret_cast<const Vector3*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector3*>(b._data._mem),c); } return;
- case TRANSFORM2D:{ r_dst=a._data._transform2d->interpolate_with(*b._data._transform2d,c); } return;
- case PLANE:{ r_dst=a; } return;
- case QUAT:{ r_dst=reinterpret_cast<const Quat*>(a._data._mem)->slerp(*reinterpret_cast<const Quat*>(b._data._mem),c); } return;
- case RECT3:{ r_dst=Rect3( a._data._rect3->pos.linear_interpolate(b._data._rect3->pos,c), a._data._rect3->size.linear_interpolate(b._data._rect3->size,c) ); } return;
- case BASIS:{ r_dst=Transform(*a._data._basis).interpolate_with(Transform(*b._data._basis),c).basis; } return;
- case TRANSFORM:{ r_dst=a._data._transform->interpolate_with(*b._data._transform,c); } return;
- case COLOR:{ r_dst=reinterpret_cast<const Color*>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Color*>(b._data._mem),c); } return;
- case IMAGE:{ r_dst=a; } return;
- case NODE_PATH:{ r_dst=a; } return;
- case _RID:{ r_dst=a; } return;
- case OBJECT:{ r_dst=a; } return;
- case INPUT_EVENT:{ r_dst=a; } return;
- case DICTIONARY:{ } return;
- case ARRAY:{ r_dst=a; } return;
- case POOL_BYTE_ARRAY:{ r_dst=a; } return;
- case POOL_INT_ARRAY:{ r_dst=a; } return;
- case POOL_REAL_ARRAY:{ r_dst=a; } return;
- case POOL_STRING_ARRAY:{ r_dst=a; } return;
- case POOL_VECTOR2_ARRAY:{
- const PoolVector<Vector2> *arr_a=reinterpret_cast<const PoolVector<Vector2>* >(a._data._mem);
- const PoolVector<Vector2> *arr_b=reinterpret_cast<const PoolVector<Vector2>* >(b._data._mem);
+ if (i < sb.length())
+ chr = sb[i];
+ else if (i < sa.length())
+ chr = sa[i];
+ }
+
+ dst[i] = chr;
+ }
+
+ r_dst = dst;
+ }
+ return;
+ case VECTOR2: {
+ r_dst = reinterpret_cast<const Vector2 *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector2 *>(b._data._mem), c);
+ }
+ return;
+ case RECT2: {
+ r_dst = Rect2(reinterpret_cast<const Rect2 *>(a._data._mem)->pos.linear_interpolate(reinterpret_cast<const Rect2 *>(b._data._mem)->pos, c), reinterpret_cast<const Rect2 *>(a._data._mem)->size.linear_interpolate(reinterpret_cast<const Rect2 *>(b._data._mem)->size, c));
+ }
+ return;
+ case VECTOR3: {
+ r_dst = reinterpret_cast<const Vector3 *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Vector3 *>(b._data._mem), c);
+ }
+ return;
+ case TRANSFORM2D: {
+ r_dst = a._data._transform2d->interpolate_with(*b._data._transform2d, c);
+ }
+ return;
+ case PLANE: {
+ r_dst = a;
+ }
+ return;
+ case QUAT: {
+ r_dst = reinterpret_cast<const Quat *>(a._data._mem)->slerp(*reinterpret_cast<const Quat *>(b._data._mem), c);
+ }
+ return;
+ case RECT3: {
+ r_dst = Rect3(a._data._rect3->pos.linear_interpolate(b._data._rect3->pos, c), a._data._rect3->size.linear_interpolate(b._data._rect3->size, c));
+ }
+ return;
+ case BASIS: {
+ r_dst = Transform(*a._data._basis).interpolate_with(Transform(*b._data._basis), c).basis;
+ }
+ return;
+ case TRANSFORM: {
+ r_dst = a._data._transform->interpolate_with(*b._data._transform, c);
+ }
+ return;
+ case COLOR: {
+ r_dst = reinterpret_cast<const Color *>(a._data._mem)->linear_interpolate(*reinterpret_cast<const Color *>(b._data._mem), c);
+ }
+ return;
+ case IMAGE: {
+ r_dst = a;
+ }
+ return;
+ case NODE_PATH: {
+ r_dst = a;
+ }
+ return;
+ case _RID: {
+ r_dst = a;
+ }
+ return;
+ case OBJECT: {
+ r_dst = a;
+ }
+ return;
+ case INPUT_EVENT: {
+ r_dst = a;
+ }
+ return;
+ case DICTIONARY: {
+ }
+ return;
+ case ARRAY: {
+ r_dst = a;
+ }
+ return;
+ case POOL_BYTE_ARRAY: {
+ r_dst = a;
+ }
+ return;
+ case POOL_INT_ARRAY: {
+ r_dst = a;
+ }
+ return;
+ case POOL_REAL_ARRAY: {
+ r_dst = a;
+ }
+ return;
+ case POOL_STRING_ARRAY: {
+ r_dst = a;
+ }
+ return;
+ case POOL_VECTOR2_ARRAY: {
+ const PoolVector<Vector2> *arr_a = reinterpret_cast<const PoolVector<Vector2> *>(a._data._mem);
+ const PoolVector<Vector2> *arr_b = reinterpret_cast<const PoolVector<Vector2> *>(b._data._mem);
int sz = arr_a->size();
- if (sz==0 || arr_b->size()!=sz) {
+ if (sz == 0 || arr_b->size() != sz) {
- r_dst=a;
+ r_dst = a;
} else {
PoolVector<Vector2> v;
v.resize(sz);
{
- PoolVector<Vector2>::Write vw=v.write();
- PoolVector<Vector2>::Read ar=arr_a->read();
- PoolVector<Vector2>::Read br=arr_b->read();
+ PoolVector<Vector2>::Write vw = v.write();
+ PoolVector<Vector2>::Read ar = arr_a->read();
+ PoolVector<Vector2>::Read br = arr_b->read();
- for(int i=0;i<sz;i++) {
- vw[i]=ar[i].linear_interpolate(br[i],c);
+ for (int i = 0; i < sz; i++) {
+ vw[i] = ar[i].linear_interpolate(br[i], c);
}
}
- r_dst=v;
-
+ r_dst = v;
}
+ }
+ return;
+ case POOL_VECTOR3_ARRAY: {
-
- } return;
- case POOL_VECTOR3_ARRAY:{
-
-
- const PoolVector<Vector3> *arr_a=reinterpret_cast<const PoolVector<Vector3>* >(a._data._mem);
- const PoolVector<Vector3> *arr_b=reinterpret_cast<const PoolVector<Vector3>* >(b._data._mem);
+ const PoolVector<Vector3> *arr_a = reinterpret_cast<const PoolVector<Vector3> *>(a._data._mem);
+ const PoolVector<Vector3> *arr_b = reinterpret_cast<const PoolVector<Vector3> *>(b._data._mem);
int sz = arr_a->size();
- if (sz==0 || arr_b->size()!=sz) {
+ if (sz == 0 || arr_b->size() != sz) {
- r_dst=a;
+ r_dst = a;
} else {
PoolVector<Vector3> v;
v.resize(sz);
{
- PoolVector<Vector3>::Write vw=v.write();
- PoolVector<Vector3>::Read ar=arr_a->read();
- PoolVector<Vector3>::Read br=arr_b->read();
+ PoolVector<Vector3>::Write vw = v.write();
+ PoolVector<Vector3>::Read ar = arr_a->read();
+ PoolVector<Vector3>::Read br = arr_b->read();
- for(int i=0;i<sz;i++) {
- vw[i]=ar[i].linear_interpolate(br[i],c);
+ for (int i = 0; i < sz; i++) {
+ vw[i] = ar[i].linear_interpolate(br[i], c);
}
}
- r_dst=v;
-
+ r_dst = v;
}
-
- } return;
- case POOL_COLOR_ARRAY:{ r_dst=a; } return;
+ }
+ return;
+ case POOL_COLOR_ARRAY: {
+ r_dst = a;
+ }
+ return;
default: {
- r_dst=a;
+ r_dst = a;
}
-
}
}
-
-static const char *_op_names[Variant::OP_MAX]={
+static const char *_op_names[Variant::OP_MAX] = {
"==",
"!=",
"<",
@@ -3676,10 +3761,8 @@ static const char *_op_names[Variant::OP_MAX]={
};
-
-
String Variant::get_operator_name(Operator p_op) {
- ERR_FAIL_INDEX_V(p_op,OP_MAX,"");
+ ERR_FAIL_INDEX_V(p_op, OP_MAX, "");
return _op_names[p_op];
}
diff --git a/core/variant_parser.cpp b/core/variant_parser.cpp
index a2ecb1516d..67e4673ad6 100644
--- a/core/variant_parser.cpp
+++ b/core/variant_parser.cpp
@@ -31,7 +31,6 @@
#include "io/resource_loader.h"
#include "os/keyboard.h"
-
CharType VariantParser::StreamFile::get_char() {
return f->get_8();
@@ -46,10 +45,9 @@ bool VariantParser::StreamFile::is_eof() const {
return f->eof_reached();
}
-
CharType VariantParser::StreamString::get_char() {
- if (pos>=s.length())
+ if (pos >= s.length())
return 0;
else
return s[pos++];
@@ -59,15 +57,12 @@ bool VariantParser::StreamString::is_utf8() const {
return false;
}
bool VariantParser::StreamString::is_eof() const {
- return pos>s.length();
+ return pos > s.length();
}
-
/////////////////////////////////////////////////////////////////////////////////////////////////
-
-
-const char * VariantParser::tk_name[TK_MAX] = {
+const char *VariantParser::tk_name[TK_MAX] = {
"'{'",
"'}'",
"'['",
@@ -86,25 +81,23 @@ const char * VariantParser::tk_name[TK_MAX] = {
"ERROR"
};
-
-
-Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, String &r_err_str) {
+Error VariantParser::get_token(Stream *p_stream, Token &r_token, int &line, String &r_err_str) {
while (true) {
CharType cchar;
if (p_stream->saved) {
- cchar=p_stream->saved;
- p_stream->saved=0;
+ cchar = p_stream->saved;
+ p_stream->saved = 0;
} else {
- cchar=p_stream->get_char();
+ cchar = p_stream->get_char();
if (p_stream->is_eof()) {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
}
}
- switch(cchar) {
+ switch (cchar) {
case '\n': {
@@ -112,53 +105,53 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri
break;
};
case 0: {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
} break;
case '{': {
- r_token.type=TK_CURLY_BRACKET_OPEN;
+ r_token.type = TK_CURLY_BRACKET_OPEN;
return OK;
};
case '}': {
- r_token.type=TK_CURLY_BRACKET_CLOSE;
+ r_token.type = TK_CURLY_BRACKET_CLOSE;
return OK;
};
case '[': {
- r_token.type=TK_BRACKET_OPEN;
+ r_token.type = TK_BRACKET_OPEN;
return OK;
};
case ']': {
- r_token.type=TK_BRACKET_CLOSE;
+ r_token.type = TK_BRACKET_CLOSE;
return OK;
};
case '(': {
- r_token.type=TK_PARENTHESIS_OPEN;
+ r_token.type = TK_PARENTHESIS_OPEN;
return OK;
};
case ')': {
- r_token.type=TK_PARENTHESIS_CLOSE;
+ r_token.type = TK_PARENTHESIS_CLOSE;
return OK;
};
case ':': {
- r_token.type=TK_COLON;
+ r_token.type = TK_COLON;
return OK;
};
case ';': {
- while(true) {
- CharType ch=p_stream->get_char();
+ while (true) {
+ CharType ch = p_stream->get_char();
if (p_stream->is_eof()) {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
}
- if (ch=='\n')
+ if (ch == '\n')
break;
}
@@ -166,112 +159,104 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri
};
case ',': {
- r_token.type=TK_COMMA;
+ r_token.type = TK_COMMA;
return OK;
};
case '.': {
- r_token.type=TK_PERIOD;
+ r_token.type = TK_PERIOD;
return OK;
};
case '=': {
- r_token.type=TK_EQUAL;
+ r_token.type = TK_EQUAL;
return OK;
};
case '#': {
-
- String color_str="#";
- while(true) {
- CharType ch=p_stream->get_char();
+ String color_str = "#";
+ while (true) {
+ CharType ch = p_stream->get_char();
if (p_stream->is_eof()) {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
- } else if ( (ch>='0' && ch<='9') || (ch>='a' && ch<='f') || (ch>='A' && ch<='F') ) {
- color_str+=String::chr(ch);
+ } else if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
+ color_str += String::chr(ch);
} else {
- p_stream->saved=ch;
+ p_stream->saved = ch;
break;
}
}
- r_token.value=Color::html(color_str);
- r_token.type=TK_COLOR;
+ r_token.value = Color::html(color_str);
+ r_token.type = TK_COLOR;
return OK;
-
};
case '"': {
-
String str;
- while(true) {
+ while (true) {
- CharType ch=p_stream->get_char();
+ CharType ch = p_stream->get_char();
- if (ch==0) {
- r_err_str="Unterminated String";
- r_token.type=TK_ERROR;
+ if (ch == 0) {
+ r_err_str = "Unterminated String";
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
- } else if (ch=='"') {
+ } else if (ch == '"') {
break;
- } else if (ch=='\\') {
+ } else if (ch == '\\') {
//escaped characters...
CharType next = p_stream->get_char();
- if (next==0) {
- r_err_str="Unterminated String";
- r_token.type=TK_ERROR;
- return ERR_PARSE_ERROR;
+ if (next == 0) {
+ r_err_str = "Unterminated String";
+ r_token.type = TK_ERROR;
+ return ERR_PARSE_ERROR;
}
- CharType res=0;
+ CharType res = 0;
- switch(next) {
+ 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': {
//hexnumbarh - oct is deprecated
-
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
CharType c = p_stream->get_char();
- if (c==0) {
- r_err_str="Unterminated String";
- r_token.type=TK_ERROR;
+ if (c == 0) {
+ r_err_str = "Unterminated String";
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
- if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
- r_err_str="Malformed hex constant in string";
- r_token.type=TK_ERROR;
+ r_err_str = "Malformed hex constant in string";
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
CharType v;
- 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;
+ 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 {
ERR_PRINT("BUG");
- v=0;
+ v = 0;
}
- res<<=4;
- res|=v;
-
-
+ res <<= 4;
+ res |= v;
}
-
-
} break;
//case '\"': res='\"'; break;
//case '\\': res='\\'; break;
@@ -283,259 +268,242 @@ Error VariantParser::get_token(Stream *p_stream, Token& r_token, int &line, Stri
} break;
}
- str+=res;
+ str += res;
} else {
- if (ch=='\n')
+ if (ch == '\n')
line++;
- str+=ch;
+ str += ch;
}
}
if (p_stream->is_utf8()) {
- str.parse_utf8( str.ascii(true).get_data() );
+ str.parse_utf8(str.ascii(true).get_data());
}
- r_token.type=TK_STRING;
- r_token.value=str;
+ r_token.type = TK_STRING;
+ r_token.value = str;
return OK;
} break;
default: {
- if (cchar<=32) {
+ if (cchar <= 32) {
break;
}
- if (cchar=='-' || (cchar>='0' && cchar<='9')) {
+ if (cchar == '-' || (cchar >= '0' && cchar <= '9')) {
//a number
-
String num;
#define READING_SIGN 0
#define READING_INT 1
#define READING_DEC 2
#define READING_EXP 3
#define READING_DONE 4
- int reading=READING_INT;
-
- if (cchar=='-') {
- num+='-';
- cchar=p_stream->get_char();
+ int reading = READING_INT;
+ if (cchar == '-') {
+ num += '-';
+ cchar = p_stream->get_char();
}
-
-
CharType c = cchar;
- bool exp_sign=false;
- bool exp_beg=false;
- bool is_float=false;
+ bool exp_sign = false;
+ bool exp_beg = false;
+ bool is_float = false;
- while(true) {
+ while (true) {
- switch(reading) {
+ switch (reading) {
case READING_INT: {
- if (c>='0' && c<='9') {
+ if (c >= '0' && c <= '9') {
//pass
- } else if (c=='.') {
- reading=READING_DEC;
- is_float=true;
- } else if (c=='e') {
- reading=READING_EXP;
+ } else if (c == '.') {
+ reading = READING_DEC;
+ is_float = true;
+ } else if (c == 'e') {
+ reading = READING_EXP;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
case READING_DEC: {
- if (c>='0' && c<='9') {
+ if (c >= '0' && c <= '9') {
- } else if (c=='e') {
- reading=READING_EXP;
+ } else if (c == 'e') {
+ reading = READING_EXP;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
case READING_EXP: {
- if (c>='0' && c<='9') {
- exp_beg=true;
+ if (c >= '0' && c <= '9') {
+ exp_beg = true;
- } else if ((c=='-' || c=='+') && !exp_sign && !exp_beg) {
- if (c=='-')
- is_float=true;
- exp_sign=true;
+ } else if ((c == '-' || c == '+') && !exp_sign && !exp_beg) {
+ if (c == '-')
+ is_float = true;
+ exp_sign = true;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
}
- if (reading==READING_DONE)
+ if (reading == READING_DONE)
break;
- num+=String::chr(c);
+ num += String::chr(c);
c = p_stream->get_char();
-
-
}
- p_stream->saved=c;
+ p_stream->saved = c;
-
- r_token.type=TK_NUMBER;
+ r_token.type = TK_NUMBER;
if (is_float)
- r_token.value=num.to_double();
+ r_token.value = num.to_double();
else
- r_token.value=num.to_int();
+ r_token.value = num.to_int();
return OK;
- } else if ((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_') {
+ } else if ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_') {
String id;
- bool first=true;
+ bool first = true;
- while((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_' || (!first && cchar>='0' && cchar<='9')) {
+ while ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_' || (!first && cchar >= '0' && cchar <= '9')) {
- id+=String::chr(cchar);
- cchar=p_stream->get_char();
- first=false;
+ id += String::chr(cchar);
+ cchar = p_stream->get_char();
+ first = false;
}
- p_stream->saved=cchar;
+ p_stream->saved = cchar;
- r_token.type=TK_IDENTIFIER;
- r_token.value=id;
+ r_token.type = TK_IDENTIFIER;
+ r_token.value = id;
return OK;
} else {
- r_err_str="Unexpected character.";
- r_token.type=TK_ERROR;
+ r_err_str = "Unexpected character.";
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
}
}
}
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
-Error VariantParser::_parse_enginecfg(Stream *p_stream, Vector<String>& strings, int &line, String &r_err_str) {
+Error VariantParser::_parse_enginecfg(Stream *p_stream, Vector<String> &strings, int &line, String &r_err_str) {
Token token;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '(' in old-style godot.cfg construct";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '(' in old-style godot.cfg construct";
return ERR_PARSE_ERROR;
}
-
String accum;
- while(true) {
+ while (true) {
- CharType c=p_stream->get_char();
+ CharType c = p_stream->get_char();
if (p_stream->is_eof()) {
- r_err_str="Unexpected EOF while parsing old-style godot.cfg construct";
+ r_err_str = "Unexpected EOF while parsing old-style godot.cfg construct";
return ERR_PARSE_ERROR;
}
- if (c==',') {
+ if (c == ',') {
strings.push_back(accum.strip_edges());
- accum=String();
- } else if (c==')') {
+ accum = String();
+ } else if (c == ')') {
strings.push_back(accum.strip_edges());
return OK;
- } else if (c=='\n') {
+ } else if (c == '\n') {
line++;
}
-
}
return OK;
}
-template<class T>
-Error VariantParser::_parse_construct(Stream *p_stream,Vector<T>& r_construct,int &line,String &r_err_str) {
-
+template <class T>
+Error VariantParser::_parse_construct(Stream *p_stream, Vector<T> &r_construct, int &line, String &r_err_str) {
Token token;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '(' in constructor";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '(' in constructor";
return ERR_PARSE_ERROR;
}
-
- bool first=true;
- while(true) {
+ bool first = true;
+ while (true) {
if (!first) {
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_COMMA) {
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_COMMA) {
//do none
- } else if (token.type==TK_PARENTHESIS_CLOSE) {
+ } else if (token.type == TK_PARENTHESIS_CLOSE) {
break;
} else {
- r_err_str="Expected ',' or ')' in constructor";
+ r_err_str = "Expected ',' or ')' in constructor";
return ERR_PARSE_ERROR;
-
}
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (first && token.type==TK_PARENTHESIS_CLOSE) {
+ if (first && token.type == TK_PARENTHESIS_CLOSE) {
break;
- } else if (token.type!=TK_NUMBER) {
- r_err_str="Expected float in constructor";
+ } else if (token.type != TK_NUMBER) {
+ r_err_str = "Expected float in constructor";
return ERR_PARSE_ERROR;
}
-
r_construct.push_back(token.value);
- first=false;
+ first = false;
}
return OK;
-
}
-Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,int &line,String &r_err_str,ResourceParser *p_res_parser) {
+Error VariantParser::parse_value(Token &token, Variant &value, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) {
-
-
-/* {
+ /* {
Error err = get_token(p_stream,token,line,r_err_str);
if (err)
return err;
}*/
-
- if (token.type==TK_CURLY_BRACKET_OPEN) {
+ if (token.type == TK_CURLY_BRACKET_OPEN) {
Dictionary d;
- Error err = _parse_dictionary(d,p_stream,line,r_err_str,p_res_parser);
+ Error err = _parse_dictionary(d, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
- value=d;
+ value = d;
return OK;
- } else if (token.type==TK_BRACKET_OPEN) {
+ } else if (token.type == TK_BRACKET_OPEN) {
Array a;
- Error err = _parse_array(a,p_stream,line,r_err_str,p_res_parser);
+ Error err = _parse_array(a, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
- value=a;
+ value = a;
return OK;
- } else if (token.type==TK_IDENTIFIER) {
-/*
+ } else if (token.type == TK_IDENTIFIER) {
+ /*
VECTOR2, // 5
RECT2,
VECTOR3,
@@ -569,878 +537,853 @@ Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,in
*/
String id = token.value;
- if (id=="true")
- value=true;
- else if (id=="false")
- value=false;
- else if (id=="null" || id=="nil")
- value=Variant();
- else if (id=="Vector2"){
+ if (id == "true")
+ value = true;
+ else if (id == "false")
+ value = false;
+ else if (id == "null" || id == "nil")
+ value = Variant();
+ else if (id == "Vector2") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=2) {
- r_err_str="Expected 2 arguments for constructor";
+ if (args.size() != 2) {
+ r_err_str = "Expected 2 arguments for constructor";
}
- value=Vector2(args[0],args[1]);
+ value = Vector2(args[0], args[1]);
return OK;
- } else if (id=="Rect2"){
+ } else if (id == "Rect2") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=4) {
- r_err_str="Expected 4 arguments for constructor";
+ if (args.size() != 4) {
+ r_err_str = "Expected 4 arguments for constructor";
}
- value=Rect2(args[0],args[1],args[2],args[3]);
+ value = Rect2(args[0], args[1], args[2], args[3]);
return OK;
- } else if (id=="Vector3"){
+ } else if (id == "Vector3") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=3) {
- r_err_str="Expected 3 arguments for constructor";
+ if (args.size() != 3) {
+ r_err_str = "Expected 3 arguments for constructor";
}
- value=Vector3(args[0],args[1],args[2]);
+ value = Vector3(args[0], args[1], args[2]);
return OK;
- } else if (id=="Transform2D" || id=="Matrix32"){ //compatibility
+ } else if (id == "Transform2D" || id == "Matrix32") { //compatibility
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=6) {
- r_err_str="Expected 6 arguments for constructor";
+ if (args.size() != 6) {
+ r_err_str = "Expected 6 arguments for constructor";
}
Transform2D m;
- m[0]=Vector2(args[0],args[1]);
- m[1]=Vector2(args[2],args[3]);
- m[2]=Vector2(args[4],args[5]);
- value=m;
+ m[0] = Vector2(args[0], args[1]);
+ m[1] = Vector2(args[2], args[3]);
+ m[2] = Vector2(args[4], args[5]);
+ value = m;
return OK;
- } else if (id=="Plane") {
+ } else if (id == "Plane") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=4) {
- r_err_str="Expected 4 arguments for constructor";
+ if (args.size() != 4) {
+ r_err_str = "Expected 4 arguments for constructor";
}
- value=Plane(args[0],args[1],args[2],args[3]);
+ value = Plane(args[0], args[1], args[2], args[3]);
return OK;
- } else if (id=="Quat") {
+ } else if (id == "Quat") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=4) {
- r_err_str="Expected 4 arguments for constructor";
+ if (args.size() != 4) {
+ r_err_str = "Expected 4 arguments for constructor";
}
- value=Quat(args[0],args[1],args[2],args[3]);
+ value = Quat(args[0], args[1], args[2], args[3]);
return OK;
- } else if (id=="Rect3" || id=="AABB"){
+ } else if (id == "Rect3" || id == "AABB") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=6) {
- r_err_str="Expected 6 arguments for constructor";
+ if (args.size() != 6) {
+ r_err_str = "Expected 6 arguments for constructor";
}
- value=Rect3(Vector3(args[0],args[1],args[2]),Vector3(args[3],args[4],args[5]));
+ value = Rect3(Vector3(args[0], args[1], args[2]), Vector3(args[3], args[4], args[5]));
return OK;
- } else if (id=="Basis" || id=="Matrix3"){ //compatibility
+ } else if (id == "Basis" || id == "Matrix3") { //compatibility
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=9) {
- r_err_str="Expected 9 arguments for constructor";
+ if (args.size() != 9) {
+ r_err_str = "Expected 9 arguments for constructor";
}
- value=Basis(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]);
+ value = Basis(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
return OK;
- } else if (id=="Transform"){
+ } else if (id == "Transform") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=12) {
- r_err_str="Expected 12 arguments for constructor";
+ if (args.size() != 12) {
+ r_err_str = "Expected 12 arguments for constructor";
}
- value=Transform(Basis(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]),Vector3(args[9],args[10],args[11]));
+ value = Transform(Basis(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]), Vector3(args[9], args[10], args[11]));
return OK;
- } else if (id=="Color") {
+ } else if (id == "Color") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
- if (args.size()!=4) {
- r_err_str="Expected 4 arguments for constructor";
+ if (args.size() != 4) {
+ r_err_str = "Expected 4 arguments for constructor";
}
- value=Color(args[0],args[1],args[2],args[3]);
+ value = Color(args[0], args[1], args[2], args[3]);
return OK;
- } else if (id=="Image") {
+ } else if (id == "Image") {
//:|
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_PARENTHESIS_CLOSE) {
- value=Image(); // just an Image()
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_PARENTHESIS_CLOSE) {
+ value = Image(); // just an Image()
return OK;
- } else if (token.type!=TK_NUMBER) {
- r_err_str="Expected number (width)";
+ } else if (token.type != TK_NUMBER) {
+ r_err_str = "Expected number (width)";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- int width=token.value;
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ int width = token.value;
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected number (height)";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected number (height)";
return ERR_PARSE_ERROR;
}
- int height=token.value;
+ int height = token.value;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- bool has_mipmaps=false;
+ bool has_mipmaps = false;
- if (token.type==TK_NUMBER) {
- has_mipmaps=bool(token.value);
- } else if (token.type==TK_IDENTIFIER && String(token.value)=="true") {
- has_mipmaps=true;
- } else if (token.type==TK_IDENTIFIER && String(token.value)=="false") {
- has_mipmaps=false;
+ if (token.type == TK_NUMBER) {
+ has_mipmaps = bool(token.value);
+ } else if (token.type == TK_IDENTIFIER && String(token.value) == "true") {
+ has_mipmaps = true;
+ } else if (token.type == TK_IDENTIFIER && String(token.value) == "false") {
+ has_mipmaps = false;
} else {
- r_err_str="Expected number/true/false (mipmaps)";
+ r_err_str = "Expected number/true/false (mipmaps)";
return ERR_PARSE_ERROR;
}
- int mipmaps=token.value;
+ int mipmaps = token.value;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_IDENTIFIER) {
- r_err_str="Expected identifier (format)";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_IDENTIFIER) {
+ r_err_str = "Expected identifier (format)";
return ERR_PARSE_ERROR;
}
+ String sformat = token.value;
- String sformat=token.value;
-
- Image::Format format=Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_MAX;
- for(int i=0;i<Image::FORMAT_MAX;i++) {
- if (Image::get_format_name(format)==sformat) {
- format=Image::Format(i);
+ for (int i = 0; i < Image::FORMAT_MAX; i++) {
+ if (Image::get_format_name(format) == sformat) {
+ format = Image::Format(i);
}
}
- if (format==Image::FORMAT_MAX) {
- r_err_str="Unknown image format: "+String(sformat);
+ if (format == Image::FORMAT_MAX) {
+ r_err_str = "Unknown image format: " + String(sformat);
return ERR_PARSE_ERROR;
}
- int len = Image::get_image_data_size(width,height,format,mipmaps);
+ int len = Image::get_image_data_size(width, height, format, mipmaps);
PoolVector<uint8_t> buffer;
buffer.resize(len);
- if (buffer.size()!=len) {
- r_err_str="Couldn't allocate image buffer of size: "+itos(len);
+ if (buffer.size() != len) {
+ r_err_str = "Couldn't allocate image buffer of size: " + itos(len);
}
{
- PoolVector<uint8_t>::Write w=buffer.write();
+ PoolVector<uint8_t>::Write w = buffer.write();
- for(int i=0;i<len;i++) {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ for (int i = 0; i < len; i++) {
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected number";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected number";
return ERR_PARSE_ERROR;
}
- w[i]=int(token.value);
-
+ w[i] = int(token.value);
}
}
+ Image img(width, height, mipmaps, format, buffer);
- Image img(width,height,mipmaps,format,buffer);
-
- value=img;
+ value = img;
return OK;
+ } else if (id == "NodePath") {
- } else if (id=="NodePath") {
-
-
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_STRING) {
- r_err_str="Expected string as argument for NodePath()";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_STRING) {
+ r_err_str = "Expected string as argument for NodePath()";
return ERR_PARSE_ERROR;
}
- value=NodePath(String(token.value));
+ value = NodePath(String(token.value));
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- } else if (id=="RID") {
-
-
+ } else if (id == "RID") {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected number as argument";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected number as argument";
return ERR_PARSE_ERROR;
}
- value=token.value;
+ value = token.value;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
-
return OK;
- } else if (id=="Resource" || id=="SubResource" || id=="ExtResource") {
-
-
+ } else if (id == "Resource" || id == "SubResource" || id == "ExtResource") {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
-
- if (p_res_parser && id=="Resource" && p_res_parser->func){
+ if (p_res_parser && id == "Resource" && p_res_parser->func) {
RES res;
- Error err = p_res_parser->func(p_res_parser->userdata,p_stream,res,line,r_err_str);
+ Error err = p_res_parser->func(p_res_parser->userdata, p_stream, res, line, r_err_str);
if (err)
return err;
- value=res;
+ value = res;
return OK;
- } else if (p_res_parser && id=="ExtResource" && p_res_parser->ext_func){
+ } else if (p_res_parser && id == "ExtResource" && p_res_parser->ext_func) {
RES res;
- Error err = p_res_parser->ext_func(p_res_parser->userdata,p_stream,res,line,r_err_str);
+ Error err = p_res_parser->ext_func(p_res_parser->userdata, p_stream, res, line, r_err_str);
if (err)
return err;
- value=res;
+ value = res;
return OK;
- } else if (p_res_parser && id=="SubResource" && p_res_parser->sub_func){
+ } else if (p_res_parser && id == "SubResource" && p_res_parser->sub_func) {
RES res;
- Error err = p_res_parser->sub_func(p_res_parser->userdata,p_stream,res,line,r_err_str);
+ Error err = p_res_parser->sub_func(p_res_parser->userdata, p_stream, res, line, r_err_str);
if (err)
return err;
- value=res;
+ value = res;
return OK;
} else {
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_STRING) {
- String path=token.value;
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_STRING) {
+ String path = token.value;
RES res = ResourceLoader::load(path);
if (res.is_null()) {
- r_err_str="Can't load resource at path: '"+path+"'.";
+ r_err_str = "Can't load resource at path: '" + path + "'.";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- value=res;
+ value = res;
return OK;
} else {
- r_err_str="Expected string as argument for Resource().";
+ r_err_str = "Expected string as argument for Resource().";
return ERR_PARSE_ERROR;
}
}
return OK;
+ } else if (id == "InputEvent") {
- } else if (id=="InputEvent") {
-
-
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_IDENTIFIER) {
- r_err_str="Expected identifier";
+ if (token.type != TK_IDENTIFIER) {
+ r_err_str = "Expected identifier";
return ERR_PARSE_ERROR;
}
-
String id = token.value;
InputEvent ie;
- if (id=="NONE") {
+ if (id == "NONE") {
- ie.type=InputEvent::NONE;
+ ie.type = InputEvent::NONE;
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- } else if (id=="KEY") {
+ } else if (id == "KEY") {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- ie.type=InputEvent::KEY;
+ ie.type = InputEvent::KEY;
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_IDENTIFIER) {
+ String name = token.value;
+ ie.key.scancode = find_keycode(name);
+ } else if (token.type == TK_NUMBER) {
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_IDENTIFIER) {
- String name=token.value;
- ie.key.scancode=find_keycode(name);
- } else if (token.type==TK_NUMBER) {
-
- ie.key.scancode=token.value;
+ ie.key.scancode = token.value;
} else {
- r_err_str="Expected string or integer for keycode";
+ r_err_str = "Expected string or integer for keycode";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type==TK_COMMA) {
+ if (token.type == TK_COMMA) {
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_IDENTIFIER) {
- r_err_str="Expected identifier with modifier flas";
+ if (token.type != TK_IDENTIFIER) {
+ r_err_str = "Expected identifier with modifier flas";
return ERR_PARSE_ERROR;
}
- String mods=token.value;
+ String mods = token.value;
- if (mods.findn("C")!=-1)
- ie.key.mod.control=true;
- if (mods.findn("A")!=-1)
- ie.key.mod.alt=true;
- if (mods.findn("S")!=-1)
- ie.key.mod.shift=true;
- if (mods.findn("M")!=-1)
- ie.key.mod.meta=true;
+ if (mods.findn("C") != -1)
+ ie.key.mod.control = true;
+ if (mods.findn("A") != -1)
+ ie.key.mod.alt = true;
+ if (mods.findn("S") != -1)
+ ie.key.mod.shift = true;
+ if (mods.findn("M") != -1)
+ ie.key.mod.meta = true;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- } else if (token.type!=TK_PARENTHESIS_CLOSE) {
+ } else if (token.type != TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')' or modifier flags.";
+ r_err_str = "Expected ')' or modifier flags.";
return ERR_PARSE_ERROR;
}
+ } else if (id == "MBUTTON") {
- } else if (id=="MBUTTON") {
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- ie.type=InputEvent::MOUSE_BUTTON;
+ ie.type = InputEvent::MOUSE_BUTTON;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected button index";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected button index";
return ERR_PARSE_ERROR;
}
ie.mouse_button.button_index = token.value;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- } else if (id=="JBUTTON") {
+ } else if (id == "JBUTTON") {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- ie.type=InputEvent::JOYPAD_BUTTON;
+ ie.type = InputEvent::JOYPAD_BUTTON;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected button index";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected button index";
return ERR_PARSE_ERROR;
}
ie.joy_button.button_index = token.value;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
- } else if (id=="JAXIS") {
+ } else if (id == "JAXIS") {
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ','";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
}
- ie.type=InputEvent::JOYPAD_MOTION;
+ ie.type = InputEvent::JOYPAD_MOTION;
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected axis index";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected axis index";
return ERR_PARSE_ERROR;
}
ie.joy_motion.axis = token.value;
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_COMMA) {
- r_err_str="Expected ',' after axis index";
+ if (token.type != TK_COMMA) {
+ r_err_str = "Expected ',' after axis index";
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_NUMBER) {
- r_err_str="Expected axis sign";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_NUMBER) {
+ r_err_str = "Expected axis sign";
return ERR_PARSE_ERROR;
}
ie.joy_motion.axis_value = token.value;
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')' for jaxis";
+ if (token.type != TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')' for jaxis";
return ERR_PARSE_ERROR;
}
} else {
- r_err_str="Invalid input event type.";
+ r_err_str = "Invalid input event type.";
return ERR_PARSE_ERROR;
}
- value=ie;
+ value = ie;
return OK;
- } else if (id=="PoolByteArray"|| id=="ByteArray") {
+ } else if (id == "PoolByteArray" || id == "ByteArray") {
Vector<uint8_t> args;
- Error err = _parse_construct<uint8_t>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<uint8_t>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<uint8_t> arr;
{
- int len=args.size();
+ int len = args.size();
arr.resize(len);
PoolVector<uint8_t>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=args[i];
+ for (int i = 0; i < len; i++) {
+ w[i] = args[i];
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="PoolIntArray"|| id=="IntArray") {
+ } else if (id == "PoolIntArray" || id == "IntArray") {
Vector<int> args;
- Error err = _parse_construct<int>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<int>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<int> arr;
{
- int len=args.size();
+ int len = args.size();
arr.resize(len);
PoolVector<int>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=int(args[i]);
+ for (int i = 0; i < len; i++) {
+ w[i] = int(args[i]);
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="PoolFloatArray"|| id=="FloatArray") {
+ } else if (id == "PoolFloatArray" || id == "FloatArray") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<float> arr;
{
- int len=args.size();
+ int len = args.size();
arr.resize(len);
PoolVector<float>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=args[i];
+ for (int i = 0; i < len; i++) {
+ w[i] = args[i];
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="PoolStringArray"|| id=="StringArray") {
+ } else if (id == "PoolStringArray" || id == "StringArray") {
-
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '('";
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '('";
return ERR_PARSE_ERROR;
}
Vector<String> cs;
- bool first=true;
- while(true) {
+ bool first = true;
+ while (true) {
if (!first) {
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_COMMA) {
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_COMMA) {
//do none
- } else if (token.type==TK_PARENTHESIS_CLOSE) {
+ } else if (token.type == TK_PARENTHESIS_CLOSE) {
break;
} else {
- r_err_str="Expected ',' or ')'";
+ r_err_str = "Expected ',' or ')'";
return ERR_PARSE_ERROR;
-
}
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type==TK_PARENTHESIS_CLOSE) {
+ if (token.type == TK_PARENTHESIS_CLOSE) {
break;
- } else if (token.type!=TK_STRING) {
- r_err_str="Expected string";
+ } else if (token.type != TK_STRING) {
+ r_err_str = "Expected string";
return ERR_PARSE_ERROR;
}
- first=false;
+ first = false;
cs.push_back(token.value);
}
-
PoolVector<String> arr;
{
- int len=cs.size();
+ int len = cs.size();
arr.resize(len);
PoolVector<String>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=cs[i];
+ for (int i = 0; i < len; i++) {
+ w[i] = cs[i];
}
}
- value=arr;
+ value = arr;
return OK;
-
- } else if (id=="PoolVector2Array"|| id=="Vector2Array") {
+ } else if (id == "PoolVector2Array" || id == "Vector2Array") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<Vector2> arr;
{
- int len=args.size()/2;
+ int len = args.size() / 2;
arr.resize(len);
PoolVector<Vector2>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=Vector2(args[i*2+0],args[i*2+1]);
+ for (int i = 0; i < len; i++) {
+ w[i] = Vector2(args[i * 2 + 0], args[i * 2 + 1]);
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="PoolVector3Array"|| id=="Vector3Array") {
+ } else if (id == "PoolVector3Array" || id == "Vector3Array") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<Vector3> arr;
{
- int len=args.size()/3;
+ int len = args.size() / 3;
arr.resize(len);
PoolVector<Vector3>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=Vector3(args[i*3+0],args[i*3+1],args[i*3+2]);
+ for (int i = 0; i < len; i++) {
+ w[i] = Vector3(args[i * 3 + 0], args[i * 3 + 1], args[i * 3 + 2]);
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="PoolColorArray"|| id=="ColorArray") {
+ } else if (id == "PoolColorArray" || id == "ColorArray") {
Vector<float> args;
- Error err = _parse_construct<float>(p_stream,args,line,r_err_str);
+ Error err = _parse_construct<float>(p_stream, args, line, r_err_str);
if (err)
return err;
PoolVector<Color> arr;
{
- int len=args.size()/4;
+ int len = args.size() / 4;
arr.resize(len);
PoolVector<Color>::Write w = arr.write();
- for(int i=0;i<len;i++) {
- w[i]=Color(args[i*4+0],args[i*4+1],args[i*4+2],args[i*4+3]);
+ for (int i = 0; i < len; i++) {
+ w[i] = Color(args[i * 4 + 0], args[i * 4 + 1], args[i * 4 + 2], args[i * 4 + 3]);
}
}
- value=arr;
+ value = arr;
return OK;
- } else if (id=="key") { // compatibility with godot.cfg
+ } else if (id == "key") { // compatibility with godot.cfg
Vector<String> params;
- Error err = _parse_enginecfg(p_stream,params,line,r_err_str);
+ Error err = _parse_enginecfg(p_stream, params, line, r_err_str);
if (err)
return err;
- ERR_FAIL_COND_V(params.size()!=1 && params.size()!=2,ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(params.size() != 1 && params.size() != 2, ERR_PARSE_ERROR);
- int scode=0;
+ int scode = 0;
if (params[0].is_numeric()) {
- scode=params[0].to_int();
+ scode = params[0].to_int();
if (scode < 10) {
- scode=KEY_0+scode;
+ scode = KEY_0 + scode;
}
} else
- scode=find_keycode(params[0]);
+ scode = find_keycode(params[0]);
InputEvent ie;
- ie.type=InputEvent::KEY;
- ie.key.scancode=scode;
-
- if (params.size()==2) {
- String mods=params[1];
- if (mods.findn("C")!=-1)
- ie.key.mod.control=true;
- if (mods.findn("A")!=-1)
- ie.key.mod.alt=true;
- if (mods.findn("S")!=-1)
- ie.key.mod.shift=true;
- if (mods.findn("M")!=-1)
- ie.key.mod.meta=true;
- }
- value=ie;
+ ie.type = InputEvent::KEY;
+ ie.key.scancode = scode;
+
+ if (params.size() == 2) {
+ String mods = params[1];
+ if (mods.findn("C") != -1)
+ ie.key.mod.control = true;
+ if (mods.findn("A") != -1)
+ ie.key.mod.alt = true;
+ if (mods.findn("S") != -1)
+ ie.key.mod.shift = true;
+ if (mods.findn("M") != -1)
+ ie.key.mod.meta = true;
+ }
+ value = ie;
return OK;
- } else if (id=="mbutton") { // compatibility with godot.cfg
+ } else if (id == "mbutton") { // compatibility with godot.cfg
Vector<String> params;
- Error err = _parse_enginecfg(p_stream,params,line,r_err_str);
+ Error err = _parse_enginecfg(p_stream, params, line, r_err_str);
if (err)
return err;
- ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR);
InputEvent ie;
- ie.type=InputEvent::MOUSE_BUTTON;
- ie.device=params[0].to_int();
- ie.mouse_button.button_index=params[1].to_int();
+ ie.type = InputEvent::MOUSE_BUTTON;
+ ie.device = params[0].to_int();
+ ie.mouse_button.button_index = params[1].to_int();
- value=ie;
+ value = ie;
return OK;
- } else if (id=="jbutton") { // compatibility with godot.cfg
+ } else if (id == "jbutton") { // compatibility with godot.cfg
Vector<String> params;
- Error err = _parse_enginecfg(p_stream,params,line,r_err_str);
+ Error err = _parse_enginecfg(p_stream, params, line, r_err_str);
if (err)
return err;
- ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR);
InputEvent ie;
- ie.type=InputEvent::JOYPAD_BUTTON;
- ie.device=params[0].to_int();
- ie.joy_button.button_index=params[1].to_int();
+ ie.type = InputEvent::JOYPAD_BUTTON;
+ ie.device = params[0].to_int();
+ ie.joy_button.button_index = params[1].to_int();
- value=ie;
+ value = ie;
return OK;
- } else if (id=="jaxis") { // compatibility with godot.cfg
+ } else if (id == "jaxis") { // compatibility with godot.cfg
Vector<String> params;
- Error err = _parse_enginecfg(p_stream,params,line,r_err_str);
+ Error err = _parse_enginecfg(p_stream, params, line, r_err_str);
if (err)
return err;
- ERR_FAIL_COND_V(params.size()!=2,ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(params.size() != 2, ERR_PARSE_ERROR);
InputEvent ie;
- ie.type=InputEvent::JOYPAD_MOTION;
- ie.device=params[0].to_int();
- int axis=params[1].to_int();
- ie.joy_motion.axis=axis>>1;
- ie.joy_motion.axis_value=axis&1?1:-1;
+ ie.type = InputEvent::JOYPAD_MOTION;
+ ie.device = params[0].to_int();
+ int axis = params[1].to_int();
+ ie.joy_motion.axis = axis >> 1;
+ ie.joy_motion.axis_value = axis & 1 ? 1 : -1;
- value= ie;
+ value = ie;
return OK;
- } else if (id=="img") { // compatibility with godot.cfg
+ } else if (id == "img") { // compatibility with godot.cfg
- Token token; // FIXME: no need for this declaration? the first argument in line 509 is a Token& token.
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_PARENTHESIS_OPEN) {
- r_err_str="Expected '(' in old-style godot.cfg construct";
+ Token token; // FIXME: no need for this declaration? the first argument in line 509 is a Token& token.
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_PARENTHESIS_OPEN) {
+ r_err_str = "Expected '(' in old-style godot.cfg construct";
return ERR_PARSE_ERROR;
}
- while(true) {
+ while (true) {
CharType c = p_stream->get_char();
if (p_stream->is_eof()) {
- r_err_str="Unexpected EOF in old style godot.cfg img()";
+ r_err_str = "Unexpected EOF in old style godot.cfg img()";
return ERR_PARSE_ERROR;
}
- if (c==')')
+ if (c == ')')
break;
}
- value=Image();
+ value = Image();
return OK;
} else {
- r_err_str="Unexpected identifier: '"+id+"'.";
+ r_err_str = "Unexpected identifier: '" + id + "'.";
return ERR_PARSE_ERROR;
}
-
/*
VECTOR2, // 5
RECT2,
@@ -1477,338 +1420,317 @@ Error VariantParser::parse_value(Token& token,Variant &value,Stream *p_stream,in
return OK;
- } else if (token.type==TK_NUMBER) {
+ } else if (token.type == TK_NUMBER) {
- value=token.value;
+ value = token.value;
return OK;
- } else if (token.type==TK_STRING) {
+ } else if (token.type == TK_STRING) {
- value=token.value;
+ value = token.value;
return OK;
- } else if (token.type==TK_COLOR) {
+ } else if (token.type == TK_COLOR) {
- value=token.value;
+ value = token.value;
return OK;
} else {
- r_err_str="Expected value, got "+String(tk_name[token.type])+".";
+ r_err_str = "Expected value, got " + String(tk_name[token.type]) + ".";
return ERR_PARSE_ERROR;
}
return ERR_PARSE_ERROR;
}
-
Error VariantParser::_parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) {
Token token;
- bool need_comma=false;
-
+ bool need_comma = false;
- while(true) {
+ while (true) {
if (p_stream->is_eof()) {
- r_err_str="Unexpected End of File while parsing array";
+ r_err_str = "Unexpected End of File while parsing array";
return ERR_FILE_CORRUPT;
}
- Error err = get_token(p_stream,token,line,r_err_str);
- if (err!=OK)
+ Error err = get_token(p_stream, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_BRACKET_CLOSE) {
+ if (token.type == TK_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected ','";
+ r_err_str = "Expected ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
Variant v;
- err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser);
+ err = parse_value(token, v, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
array.push_back(v);
- need_comma=true;
-
+ need_comma = true;
}
return OK;
-
}
Error VariantParser::_parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser) {
- bool at_key=true;
+ bool at_key = true;
Variant key;
Token token;
- bool need_comma=false;
-
-
- while(true) {
+ bool need_comma = false;
+ while (true) {
if (p_stream->is_eof()) {
- r_err_str="Unexpected End of File while parsing dictionary";
+ r_err_str = "Unexpected End of File while parsing dictionary";
return ERR_FILE_CORRUPT;
}
if (at_key) {
- Error err = get_token(p_stream,token,line,r_err_str);
- if (err!=OK)
+ Error err = get_token(p_stream, token, line, r_err_str);
+ if (err != OK)
return err;
- if (token.type==TK_CURLY_BRACKET_CLOSE) {
+ if (token.type == TK_CURLY_BRACKET_CLOSE) {
return OK;
}
if (need_comma) {
- if (token.type!=TK_COMMA) {
+ if (token.type != TK_COMMA) {
- r_err_str="Expected '}' or ','";
+ r_err_str = "Expected '}' or ','";
return ERR_PARSE_ERROR;
} else {
- need_comma=false;
+ need_comma = false;
continue;
}
}
-
-
-
- err = parse_value(token,key,p_stream,line,r_err_str,p_res_parser);
+ err = parse_value(token, key, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
- err = get_token(p_stream,token,line,r_err_str);
+ err = get_token(p_stream, token, line, r_err_str);
- if (err!=OK)
+ if (err != OK)
return err;
- if (token.type!=TK_COLON) {
+ if (token.type != TK_COLON) {
- r_err_str="Expected ':'";
+ r_err_str = "Expected ':'";
return ERR_PARSE_ERROR;
}
- at_key=false;
+ at_key = false;
} else {
-
- Error err = get_token(p_stream,token,line,r_err_str);
- if (err!=OK)
+ Error err = get_token(p_stream, token, line, r_err_str);
+ if (err != OK)
return err;
Variant v;
- err = parse_value(token,v,p_stream,line,r_err_str,p_res_parser);
+ err = parse_value(token, v, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
- object[key]=v;
- need_comma=true;
- at_key=true;
+ object[key] = v;
+ need_comma = true;
+ at_key = true;
}
}
return OK;
}
-
-Error VariantParser::_parse_tag(Token& token, Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser,bool p_simple_tag) {
+Error VariantParser::_parse_tag(Token &token, Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser, bool p_simple_tag) {
r_tag.fields.clear();
- if (token.type!=TK_BRACKET_OPEN) {
- r_err_str="Expected '['";
+ if (token.type != TK_BRACKET_OPEN) {
+ r_err_str = "Expected '['";
return ERR_PARSE_ERROR;
}
-
if (p_simple_tag) {
- r_tag.name="";
+ r_tag.name = "";
r_tag.fields.clear();
- while(true) {
+ while (true) {
CharType c = p_stream->get_char();
if (p_stream->is_eof()) {
- r_err_str="Unexpected EOF while parsing simple tag";
+ r_err_str = "Unexpected EOF while parsing simple tag";
return ERR_PARSE_ERROR;
}
- if (c==']')
+ if (c == ']')
break;
- r_tag.name+=String::chr(c);
+ r_tag.name += String::chr(c);
}
r_tag.name = r_tag.name.strip_edges();
return OK;
-
}
- get_token(p_stream,token,line,r_err_str);
-
+ get_token(p_stream, token, line, r_err_str);
- if (token.type!=TK_IDENTIFIER) {
- r_err_str="Expected identifier (tag name)";
+ if (token.type != TK_IDENTIFIER) {
+ r_err_str = "Expected identifier (tag name)";
return ERR_PARSE_ERROR;
}
- r_tag.name=token.value;
- bool parsing_tag=true;
+ r_tag.name = token.value;
+ bool parsing_tag = true;
- while(true) {
+ while (true) {
if (p_stream->is_eof()) {
- r_err_str="Unexpected End of File while parsing tag: "+r_tag.name;
+ r_err_str = "Unexpected End of File while parsing tag: " + r_tag.name;
return ERR_FILE_CORRUPT;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type==TK_BRACKET_CLOSE)
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type == TK_BRACKET_CLOSE)
break;
- if (parsing_tag && token.type==TK_PERIOD) {
- r_tag.name+="."; //support tags such as [someprop.Anroid] for specific platforms
- get_token(p_stream,token,line,r_err_str);
- } else if (parsing_tag && token.type==TK_COLON) {
- r_tag.name+=":"; //support tags such as [someprop.Anroid] for specific platforms
- get_token(p_stream,token,line,r_err_str);
+ if (parsing_tag && token.type == TK_PERIOD) {
+ r_tag.name += "."; //support tags such as [someprop.Anroid] for specific platforms
+ get_token(p_stream, token, line, r_err_str);
+ } else if (parsing_tag && token.type == TK_COLON) {
+ r_tag.name += ":"; //support tags such as [someprop.Anroid] for specific platforms
+ get_token(p_stream, token, line, r_err_str);
} else {
- parsing_tag=false;
+ parsing_tag = false;
}
- if (token.type!=TK_IDENTIFIER) {
- r_err_str="Expected Identifier";
+ if (token.type != TK_IDENTIFIER) {
+ r_err_str = "Expected Identifier";
return ERR_PARSE_ERROR;
}
- String id=token.value;
+ String id = token.value;
if (parsing_tag) {
- r_tag.name+=id;
+ r_tag.name += id;
continue;
}
- get_token(p_stream,token,line,r_err_str);
- if (token.type!=TK_EQUAL) {
+ get_token(p_stream, token, line, r_err_str);
+ if (token.type != TK_EQUAL) {
return ERR_PARSE_ERROR;
}
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
Variant value;
- Error err = parse_value(token,value,p_stream,line,r_err_str,p_res_parser);
+ Error err = parse_value(token, value, p_stream, line, r_err_str, p_res_parser);
if (err)
return err;
- r_tag.fields[id]=value;
-
+ r_tag.fields[id] = value;
}
-
return OK;
-
}
-Error VariantParser::parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, ResourceParser *p_res_parser, bool p_simple_tag) {
+Error VariantParser::parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser, bool p_simple_tag) {
Token token;
- get_token(p_stream,token,line,r_err_str);
+ get_token(p_stream, token, line, r_err_str);
- if (token.type==TK_EOF) {
+ if (token.type == TK_EOF) {
return ERR_FILE_EOF;
}
- if (token.type!=TK_BRACKET_OPEN) {
- r_err_str="Expected '['";
+ if (token.type != TK_BRACKET_OPEN) {
+ r_err_str = "Expected '['";
return ERR_PARSE_ERROR;
}
- return _parse_tag(token,p_stream,line,r_err_str,r_tag,p_res_parser,p_simple_tag);
-
+ return _parse_tag(token, p_stream, line, r_err_str, r_tag, p_res_parser, p_simple_tag);
}
-Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser, bool p_simple_tag) {
-
+Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser, bool p_simple_tag) {
//assign..
- r_assign="";
+ r_assign = "";
String what;
- while(true) {
-
+ while (true) {
CharType c;
if (p_stream->saved) {
- c=p_stream->saved;
- p_stream->saved=0;
+ c = p_stream->saved;
+ p_stream->saved = 0;
} else {
- c=p_stream->get_char();
+ c = p_stream->get_char();
}
if (p_stream->is_eof())
return ERR_FILE_EOF;
- if (c==';') { //comment
- while(true) {
- CharType ch=p_stream->get_char();
+ if (c == ';') { //comment
+ while (true) {
+ CharType ch = p_stream->get_char();
if (p_stream->is_eof()) {
return ERR_FILE_EOF;
}
- if (ch=='\n')
+ if (ch == '\n')
break;
}
continue;
}
- if (c=='[' && what.length()==0) {
+ if (c == '[' && what.length() == 0) {
//it's a tag!
- p_stream->saved='['; //go back one
+ p_stream->saved = '['; //go back one
- Error err = parse_tag(p_stream,line,r_err_str,r_tag,p_res_parser,p_simple_tag);
+ Error err = parse_tag(p_stream, line, r_err_str, r_tag, p_res_parser, p_simple_tag);
return err;
}
- if (c>32) {
- if (c=='"') { //quoted
- p_stream->saved='"';
+ if (c > 32) {
+ if (c == '"') { //quoted
+ p_stream->saved = '"';
Token tk;
- Error err = get_token(p_stream,tk,line,r_err_str);
+ Error err = get_token(p_stream, tk, line, r_err_str);
if (err)
return err;
- if (tk.type!=TK_STRING) {
- r_err_str="Error reading quoted string";
+ if (tk.type != TK_STRING) {
+ r_err_str = "Error reading quoted string";
return err;
}
- what=tk.value;
+ what = tk.value;
- } else if (c!='=') {
- what+=String::chr(c);
+ } else if (c != '=') {
+ what += String::chr(c);
} else {
- r_assign=what;
+ r_assign = what;
Token token;
- get_token(p_stream,token,line,r_err_str);
- Error err = parse_value(token,r_value,p_stream,line,r_err_str,p_res_parser);
+ get_token(p_stream, token, line, r_err_str);
+ Error err = parse_value(token, r_value, p_stream, line, r_err_str, p_res_parser);
if (err) {
-
}
return err;
}
- } else if (c=='\n') {
+ } else if (c == '\n') {
line++;
}
}
@@ -1816,198 +1738,192 @@ Error VariantParser::parse_tag_assign_eof(Stream *p_stream, int &line, String &r
return OK;
}
-Error VariantParser::parse(Stream *p_stream, Variant& r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser) {
-
+Error VariantParser::parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser) {
Token token;
- Error err = get_token(p_stream,token,r_err_line,r_err_str);
+ Error err = get_token(p_stream, token, r_err_line, r_err_str);
if (err)
return err;
- if (token.type==TK_EOF) {
+ if (token.type == TK_EOF) {
return ERR_FILE_EOF;
}
- return parse_value(token,r_ret,p_stream,r_err_line,r_err_str,p_res_parser);
-
+ return parse_value(token, r_ret, p_stream, r_err_line, r_err_str, p_res_parser);
}
-
-
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static String rtosfix(double p_value) {
-
- if (p_value==0.0)
+ if (p_value == 0.0)
return "0"; //avoid negative zero (-0) being written, which may annoy git, svn, etc. for changes when they don't exist.
else
return rtoss(p_value);
}
-Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud,EncodeResourceFunc p_encode_res_func,void* p_encode_res_ud) {
+Error VariantWriter::write(const Variant &p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) {
- switch( p_variant.get_type() ) {
+ switch (p_variant.get_type()) {
case Variant::NIL: {
- p_store_string_func(p_store_string_ud,"null");
+ p_store_string_func(p_store_string_ud, "null");
} break;
case Variant::BOOL: {
- p_store_string_func(p_store_string_ud,p_variant.operator bool() ? "true":"false" );
+ p_store_string_func(p_store_string_ud, p_variant.operator bool() ? "true" : "false");
} break;
case Variant::INT: {
- p_store_string_func(p_store_string_ud, itos(p_variant.operator int()) );
+ p_store_string_func(p_store_string_ud, itos(p_variant.operator int()));
} break;
case Variant::REAL: {
String s = rtosfix(p_variant.operator real_t());
- if (s.find(".")==-1 && s.find("e")==-1)
- s+=".0";
- p_store_string_func(p_store_string_ud, s );
+ if (s.find(".") == -1 && s.find("e") == -1)
+ s += ".0";
+ p_store_string_func(p_store_string_ud, s);
} break;
case Variant::STRING: {
- String str=p_variant;
+ String str = p_variant;
- str="\""+str.c_escape_multiline()+"\"";
- p_store_string_func(p_store_string_ud, str );
+ str = "\"" + str.c_escape_multiline() + "\"";
+ p_store_string_func(p_store_string_ud, str);
} break;
case Variant::VECTOR2: {
Vector2 v = p_variant;
- p_store_string_func(p_store_string_ud,"Vector2( "+rtosfix(v.x) +", "+rtosfix(v.y)+" )" );
+ p_store_string_func(p_store_string_ud, "Vector2( " + rtosfix(v.x) + ", " + rtosfix(v.y) + " )");
} break;
case Variant::RECT2: {
Rect2 aabb = p_variant;
- p_store_string_func(p_store_string_ud,"Rect2( "+rtosfix(aabb.pos.x) +", "+rtosfix(aabb.pos.y) +", "+rtosfix(aabb.size.x) +", "+rtosfix(aabb.size.y)+" )" );
+ p_store_string_func(p_store_string_ud, "Rect2( " + rtosfix(aabb.pos.x) + ", " + rtosfix(aabb.pos.y) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + " )");
} break;
case Variant::VECTOR3: {
Vector3 v = p_variant;
- p_store_string_func(p_store_string_ud,"Vector3( "+rtosfix(v.x) +", "+rtosfix(v.y)+", "+rtosfix(v.z)+" )");
+ p_store_string_func(p_store_string_ud, "Vector3( " + rtosfix(v.x) + ", " + rtosfix(v.y) + ", " + rtosfix(v.z) + " )");
} break;
case Variant::PLANE: {
Plane p = p_variant;
- p_store_string_func(p_store_string_ud,"Plane( "+rtosfix(p.normal.x) +", "+rtosfix(p.normal.y)+", "+rtosfix(p.normal.z)+", "+rtosfix(p.d)+" )" );
+ p_store_string_func(p_store_string_ud, "Plane( " + rtosfix(p.normal.x) + ", " + rtosfix(p.normal.y) + ", " + rtosfix(p.normal.z) + ", " + rtosfix(p.d) + " )");
} break;
case Variant::RECT3: {
Rect3 aabb = p_variant;
- p_store_string_func(p_store_string_ud,"Rect3( "+rtosfix(aabb.pos.x) +", "+rtosfix(aabb.pos.y) +", "+rtosfix(aabb.pos.z) +", "+rtosfix(aabb.size.x) +", "+rtosfix(aabb.size.y) +", "+rtosfix(aabb.size.z)+" )" );
+ p_store_string_func(p_store_string_ud, "Rect3( " + rtosfix(aabb.pos.x) + ", " + rtosfix(aabb.pos.y) + ", " + rtosfix(aabb.pos.z) + ", " + rtosfix(aabb.size.x) + ", " + rtosfix(aabb.size.y) + ", " + rtosfix(aabb.size.z) + " )");
} break;
case Variant::QUAT: {
Quat quat = p_variant;
- p_store_string_func(p_store_string_ud,"Quat( "+rtosfix(quat.x)+", "+rtosfix(quat.y)+", "+rtosfix(quat.z)+", "+rtosfix(quat.w)+" )");
+ p_store_string_func(p_store_string_ud, "Quat( " + rtosfix(quat.x) + ", " + rtosfix(quat.y) + ", " + rtosfix(quat.z) + ", " + rtosfix(quat.w) + " )");
} break;
case Variant::TRANSFORM2D: {
- String s="Transform2D( ";
+ String s = "Transform2D( ";
Transform2D m3 = p_variant;
- for (int i=0;i<3;i++) {
- for (int j=0;j<2;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 2; j++) {
- if (i!=0 || j!=0)
- s+=", ";
- s+=rtosfix( m3.elements[i][j] );
+ if (i != 0 || j != 0)
+ s += ", ";
+ s += rtosfix(m3.elements[i][j]);
}
}
- p_store_string_func(p_store_string_ud,s+" )");
+ p_store_string_func(p_store_string_ud, s + " )");
} break;
case Variant::BASIS: {
- String s="Basis( ";
+ String s = "Basis( ";
Basis m3 = p_variant;
- for (int i=0;i<3;i++) {
- for (int j=0;j<3;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- if (i!=0 || j!=0)
- s+=", ";
- s+=rtosfix( m3.elements[i][j] );
+ if (i != 0 || j != 0)
+ s += ", ";
+ s += rtosfix(m3.elements[i][j]);
}
}
- p_store_string_func(p_store_string_ud,s+" )");
+ p_store_string_func(p_store_string_ud, s + " )");
} break;
case Variant::TRANSFORM: {
- String s="Transform( ";
+ String s = "Transform( ";
Transform t = p_variant;
Basis &m3 = t.basis;
- for (int i=0;i<3;i++) {
- for (int j=0;j<3;j++) {
+ for (int i = 0; i < 3; i++) {
+ for (int j = 0; j < 3; j++) {
- if (i!=0 || j!=0)
- s+=", ";
- s+=rtosfix( m3.elements[i][j] );
+ if (i != 0 || j != 0)
+ s += ", ";
+ s += rtosfix(m3.elements[i][j]);
}
}
- s=s+", "+rtosfix(t.origin.x) +", "+rtosfix(t.origin.y)+", "+rtosfix(t.origin.z);
+ s = s + ", " + rtosfix(t.origin.x) + ", " + rtosfix(t.origin.y) + ", " + rtosfix(t.origin.z);
- p_store_string_func(p_store_string_ud,s+" )");
+ p_store_string_func(p_store_string_ud, s + " )");
} break;
- // misc types
+ // misc types
case Variant::COLOR: {
Color c = p_variant;
- p_store_string_func(p_store_string_ud,"Color( "+rtosfix(c.r) +", "+rtosfix(c.g)+", "+rtosfix(c.b)+", "+rtosfix(c.a)+" )");
+ p_store_string_func(p_store_string_ud, "Color( " + rtosfix(c.r) + ", " + rtosfix(c.g) + ", " + rtosfix(c.b) + ", " + rtosfix(c.a) + " )");
} break;
case Variant::IMAGE: {
-
- Image img=p_variant;
+ Image img = p_variant;
if (img.empty()) {
- p_store_string_func(p_store_string_ud,"Image()");
+ p_store_string_func(p_store_string_ud, "Image()");
break;
}
- String imgstr="Image( ";
- imgstr+=itos(img.get_width());
- imgstr+=", "+itos(img.get_height());
- imgstr+=", "+String(img.has_mipmaps()?"true":"false");
- imgstr+=", "+Image::get_format_name(img.get_format());
+ String imgstr = "Image( ";
+ imgstr += itos(img.get_width());
+ imgstr += ", " + itos(img.get_height());
+ imgstr += ", " + String(img.has_mipmaps() ? "true" : "false");
+ imgstr += ", " + Image::get_format_name(img.get_format());
String s;
PoolVector<uint8_t> data = img.get_data();
int len = data.size();
PoolVector<uint8_t>::Read r = data.read();
- const uint8_t *ptr=r.ptr();
- for (int i=0;i<len;i++) {
+ const uint8_t *ptr = r.ptr();
+ for (int i = 0; i < len; i++) {
- if (i>0)
- s+=", ";
- s+=itos(ptr[i]);
+ if (i > 0)
+ s += ", ";
+ s += itos(ptr[i]);
}
- imgstr+=", ";
- p_store_string_func(p_store_string_ud,imgstr);
- p_store_string_func(p_store_string_ud,s);
- p_store_string_func(p_store_string_ud," )");
+ imgstr += ", ";
+ p_store_string_func(p_store_string_ud, imgstr);
+ p_store_string_func(p_store_string_ud, s);
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::NODE_PATH: {
- String str=p_variant;
+ String str = p_variant;
- str="NodePath(\""+str.c_escape()+"\")";
- p_store_string_func(p_store_string_ud,str);
+ str = "NodePath(\"" + str.c_escape() + "\")";
+ p_store_string_func(p_store_string_ud, str);
} break;
@@ -2015,7 +1931,7 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str
RES res = p_variant;
if (res.is_null()) {
- p_store_string_func(p_store_string_ud,"null");
+ p_store_string_func(p_store_string_ud, "null");
break; // don't save it
}
@@ -2023,64 +1939,64 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str
if (p_encode_res_func) {
- res_text=p_encode_res_func(p_encode_res_ud,res);
+ res_text = p_encode_res_func(p_encode_res_ud, res);
}
- if (res_text==String() && res->get_path().is_resource_file()) {
+ if (res_text == String() && res->get_path().is_resource_file()) {
//external resource
- String path=res->get_path();
- res_text="Resource( \""+path+"\")";
+ String path = res->get_path();
+ res_text = "Resource( \"" + path + "\")";
}
- if (res_text==String())
- res_text="null";
+ if (res_text == String())
+ res_text = "null";
- p_store_string_func(p_store_string_ud,res_text);
+ p_store_string_func(p_store_string_ud, res_text);
} break;
case Variant::INPUT_EVENT: {
- String str="InputEvent(";
+ String str = "InputEvent(";
- InputEvent ev=p_variant;
- switch(ev.type) {
+ InputEvent ev = p_variant;
+ switch (ev.type) {
case InputEvent::KEY: {
- str+="KEY,"+itos(ev.key.scancode);
+ str += "KEY," + itos(ev.key.scancode);
String mod;
if (ev.key.mod.alt)
- mod+="A";
+ mod += "A";
if (ev.key.mod.shift)
- mod+="S";
+ mod += "S";
if (ev.key.mod.control)
- mod+="C";
+ mod += "C";
if (ev.key.mod.meta)
- mod+="M";
+ mod += "M";
- if (mod!=String())
- str+=","+mod;
+ if (mod != String())
+ str += "," + mod;
} break;
case InputEvent::MOUSE_BUTTON: {
- str+="MBUTTON,"+itos(ev.mouse_button.button_index);
+ str += "MBUTTON," + itos(ev.mouse_button.button_index);
} break;
case InputEvent::JOYPAD_BUTTON: {
- str+="JBUTTON,"+itos(ev.joy_button.button_index);
+ str += "JBUTTON," + itos(ev.joy_button.button_index);
} break;
case InputEvent::JOYPAD_MOTION: {
- str+="JAXIS,"+itos(ev.joy_motion.axis)+","+itos(ev.joy_motion.axis_value);
+ str += "JAXIS," + itos(ev.joy_motion.axis) + "," + itos(ev.joy_motion.axis_value);
} break;
case InputEvent::NONE: {
- str+="NONE";
+ str += "NONE";
} break;
default: {}
}
- str+=")";
+ str += ")";
- p_store_string_func(p_store_string_ud,str); //will be added later
+ p_store_string_func(p_store_string_ud, str); //will be added later
} break;
case Variant::DICTIONARY: {
@@ -2091,196 +2007,186 @@ Error VariantWriter::write(const Variant& p_variant, StoreStringFunc p_store_str
dict.get_key_list(&keys);
keys.sort();
- p_store_string_func(p_store_string_ud,"{\n");
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ p_store_string_func(p_store_string_ud, "{\n");
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
/*
if (!_check_type(dict[E->get()]))
continue;
*/
- write(E->get(),p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud);
- p_store_string_func(p_store_string_ud,": ");
- write(dict[E->get()],p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud);
+ write(E->get(), p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud);
+ p_store_string_func(p_store_string_ud, ": ");
+ write(dict[E->get()], p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud);
if (E->next())
- p_store_string_func(p_store_string_ud,",\n");
+ p_store_string_func(p_store_string_ud, ",\n");
}
-
- p_store_string_func(p_store_string_ud,"\n}");
-
+ p_store_string_func(p_store_string_ud, "\n}");
} break;
case Variant::ARRAY: {
- p_store_string_func(p_store_string_ud,"[ ");
+ p_store_string_func(p_store_string_ud, "[ ");
Array array = p_variant;
- int len=array.size();
- for (int i=0;i<len;i++) {
-
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
- write(array[i],p_store_string_func,p_store_string_ud,p_encode_res_func,p_encode_res_ud);
+ int len = array.size();
+ for (int i = 0; i < len; i++) {
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ write(array[i], p_store_string_func, p_store_string_ud, p_encode_res_func, p_encode_res_ud);
}
- p_store_string_func(p_store_string_ud," ]");
+ p_store_string_func(p_store_string_ud, " ]");
} break;
case Variant::POOL_BYTE_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolByteArray( ");
+ p_store_string_func(p_store_string_ud, "PoolByteArray( ");
String s;
PoolVector<uint8_t> data = p_variant;
int len = data.size();
PoolVector<uint8_t>::Read r = data.read();
- const uint8_t *ptr=r.ptr();
- for (int i=0;i<len;i++) {
-
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
+ const uint8_t *ptr = r.ptr();
+ for (int i = 0; i < len; i++) {
- p_store_string_func(p_store_string_ud,itos(ptr[i]));
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ p_store_string_func(p_store_string_ud, itos(ptr[i]));
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_INT_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolIntArray( ");
+ p_store_string_func(p_store_string_ud, "PoolIntArray( ");
PoolVector<int> data = p_variant;
int len = data.size();
PoolVector<int>::Read r = data.read();
- const int *ptr=r.ptr();
+ const int *ptr = r.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
- p_store_string_func(p_store_string_ud,itos(ptr[i]));
+ p_store_string_func(p_store_string_ud, itos(ptr[i]));
}
-
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_REAL_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolFloatArray( ");
+ p_store_string_func(p_store_string_ud, "PoolFloatArray( ");
PoolVector<real_t> data = p_variant;
int len = data.size();
PoolVector<real_t>::Read r = data.read();
- const real_t *ptr=r.ptr();
+ const real_t *ptr = r.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
- p_store_string_func(p_store_string_ud,rtosfix(ptr[i]));
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ p_store_string_func(p_store_string_ud, rtosfix(ptr[i]));
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_STRING_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolStringArray( ");
+ p_store_string_func(p_store_string_ud, "PoolStringArray( ");
PoolVector<String> data = p_variant;
int len = data.size();
PoolVector<String>::Read r = data.read();
- const String *ptr=r.ptr();
+ const String *ptr = r.ptr();
String s;
//write_string("\n");
+ for (int i = 0; i < len; i++) {
-
- for (int i=0;i<len;i++) {
-
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
- String str=ptr[i];
- p_store_string_func(p_store_string_ud,"\""+str.c_escape()+"\"");
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ String str = ptr[i];
+ p_store_string_func(p_store_string_ud, "\"" + str.c_escape() + "\"");
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_VECTOR2_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolVector2Array( ");
+ p_store_string_func(p_store_string_ud, "PoolVector2Array( ");
PoolVector<Vector2> data = p_variant;
int len = data.size();
PoolVector<Vector2>::Read r = data.read();
- const Vector2 *ptr=r.ptr();
+ const Vector2 *ptr = r.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
- p_store_string_func(p_store_string_ud,rtosfix(ptr[i].x)+", "+rtosfix(ptr[i].y) );
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y));
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_VECTOR3_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolVector3Array( ");
+ p_store_string_func(p_store_string_ud, "PoolVector3Array( ");
PoolVector<Vector3> data = p_variant;
int len = data.size();
PoolVector<Vector3>::Read r = data.read();
- const Vector3 *ptr=r.ptr();
+ const Vector3 *ptr = r.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
- p_store_string_func(p_store_string_ud,rtosfix(ptr[i].x)+", "+rtosfix(ptr[i].y)+", "+rtosfix(ptr[i].z) );
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ p_store_string_func(p_store_string_ud, rtosfix(ptr[i].x) + ", " + rtosfix(ptr[i].y) + ", " + rtosfix(ptr[i].z));
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
case Variant::POOL_COLOR_ARRAY: {
- p_store_string_func(p_store_string_ud,"PoolColorArray( ");
+ p_store_string_func(p_store_string_ud, "PoolColorArray( ");
PoolVector<Color> data = p_variant;
int len = data.size();
PoolVector<Color>::Read r = data.read();
- const Color *ptr=r.ptr();
+ const Color *ptr = r.ptr();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i>0)
- p_store_string_func(p_store_string_ud,", ");
-
- p_store_string_func(p_store_string_ud,rtosfix(ptr[i].r)+", "+rtosfix(ptr[i].g)+", "+rtosfix(ptr[i].b)+", "+rtosfix(ptr[i].a) );
+ if (i > 0)
+ p_store_string_func(p_store_string_ud, ", ");
+ p_store_string_func(p_store_string_ud, rtosfix(ptr[i].r) + ", " + rtosfix(ptr[i].g) + ", " + rtosfix(ptr[i].b) + ", " + rtosfix(ptr[i].a));
}
- p_store_string_func(p_store_string_ud," )");
+ p_store_string_func(p_store_string_ud, " )");
} break;
default: {}
-
}
return OK;
}
-static Error _write_to_str(void *ud,const String& p_string) {
+static Error _write_to_str(void *ud, const String &p_string) {
- String *str=(String*)ud;
- (*str)+=p_string;
+ String *str = (String *)ud;
+ (*str) += p_string;
return OK;
}
-Error VariantWriter::write_to_string(const Variant& p_variant, String& r_string, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) {
-
- r_string=String();
+Error VariantWriter::write_to_string(const Variant &p_variant, String &r_string, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud) {
- return write(p_variant,_write_to_str,&r_string,p_encode_res_func,p_encode_res_ud);
+ r_string = String();
+ return write(p_variant, _write_to_str, &r_string, p_encode_res_func, p_encode_res_ud);
}
diff --git a/core/variant_parser.h b/core/variant_parser.h
index c69673b0e4..20cc72f20d 100644
--- a/core/variant_parser.h
+++ b/core/variant_parser.h
@@ -29,22 +29,21 @@
#ifndef VARIANT_PARSER_H
#define VARIANT_PARSER_H
-#include "variant.h"
#include "os/file_access.h"
#include "resource.h"
+#include "variant.h"
class VariantParser {
public:
-
struct Stream {
- virtual CharType get_char()=0;
- virtual bool is_utf8() const=0;
- virtual bool is_eof() const=0;
+ virtual CharType get_char() = 0;
+ virtual bool is_utf8() const = 0;
+ virtual bool is_eof() const = 0;
CharType saved;
- Stream() { saved=0; }
+ Stream() { saved = 0; }
virtual ~Stream() {}
};
@@ -56,8 +55,7 @@ public:
virtual bool is_utf8() const;
virtual bool is_eof() const;
- StreamFile() { f=NULL; }
-
+ StreamFile() { f = NULL; }
};
struct StreamString : public Stream {
@@ -69,11 +67,10 @@ public:
virtual bool is_utf8() const;
virtual bool is_eof() const;
- StreamString() { pos=0; }
-
+ StreamString() { pos = 0; }
};
- typedef Error (*ParseResourceFunc)(void* p_self, Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str);
+ typedef Error (*ParseResourceFunc)(void *p_self, Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str);
struct ResourceParser {
@@ -81,7 +78,6 @@ public:
ParseResourceFunc func;
ParseResourceFunc ext_func;
ParseResourceFunc sub_func;
-
};
enum TokenType {
@@ -121,47 +117,35 @@ public:
struct Tag {
String name;
- Map<String,Variant> fields;
+ Map<String, Variant> fields;
};
private:
- static const char * tk_name[TK_MAX];
+ static const char *tk_name[TK_MAX];
- template<class T>
- static Error _parse_construct(Stream *p_stream, Vector<T>& r_construct, int &line, String &r_err_str);
- static Error _parse_enginecfg(Stream *p_stream, Vector<String>& strings, int &line, String &r_err_str);
- static Error _parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL);
- static Error _parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL);
- static Error _parse_tag(Token& token,Stream *p_stream, int &line, String &r_err_str,Tag& r_tag,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false);
+ template <class T>
+ static Error _parse_construct(Stream *p_stream, Vector<T> &r_construct, int &line, String &r_err_str);
+ static Error _parse_enginecfg(Stream *p_stream, Vector<String> &strings, int &line, String &r_err_str);
+ static Error _parse_dictionary(Dictionary &object, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL);
+ static Error _parse_array(Array &array, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL);
+ static Error _parse_tag(Token &token, Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false);
public:
+ static Error parse_tag(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false);
+ static Error parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag &r_tag, String &r_assign, Variant &r_value, ResourceParser *p_res_parser = NULL, bool p_simple_tag = false);
- static Error parse_tag(Stream *p_stream, int &line, String &r_err_str,Tag& r_tag,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false);
- static Error parse_tag_assign_eof(Stream *p_stream, int &line, String &r_err_str, Tag& r_tag, String &r_assign, Variant &r_value,ResourceParser *p_res_parser=NULL,bool p_simple_tag=false);
-
- static Error parse_value(Token& token,Variant &value, Stream *p_stream, int &line, String &r_err_str,ResourceParser *p_res_parser=NULL);
- static Error get_token(Stream *p_stream,Token& r_token,int &line,String &r_err_str);
- static Error parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line,ResourceParser *p_res_parser=NULL);
+ static Error parse_value(Token &token, Variant &value, Stream *p_stream, int &line, String &r_err_str, ResourceParser *p_res_parser = NULL);
+ static Error get_token(Stream *p_stream, Token &r_token, int &line, String &r_err_str);
+ static Error parse(Stream *p_stream, Variant &r_ret, String &r_err_str, int &r_err_line, ResourceParser *p_res_parser = NULL);
};
-
-
-
class VariantWriter {
public:
+ typedef Error (*StoreStringFunc)(void *ud, const String &p_string);
+ typedef String (*EncodeResourceFunc)(void *ud, const RES &p_resource);
- typedef Error (*StoreStringFunc)(void *ud,const String& p_string);
- typedef String (*EncodeResourceFunc)(void *ud,const RES& p_resource);
-
- static Error write(const Variant& p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud,EncodeResourceFunc p_encode_res_func,void* p_encode_res_ud);
- static Error write_to_string(const Variant& p_variant, String& r_string, EncodeResourceFunc p_encode_res_func=NULL,void* p_encode_res_ud=NULL);
-
-
+ static Error write(const Variant &p_variant, StoreStringFunc p_store_string_func, void *p_store_string_ud, EncodeResourceFunc p_encode_res_func, void *p_encode_res_ud);
+ static Error write_to_string(const Variant &p_variant, String &r_string, EncodeResourceFunc p_encode_res_func = NULL, void *p_encode_res_ud = NULL);
};
-
-
-
-
-
#endif // VARIANT_PARSER_H
diff --git a/core/vector.h b/core/vector.h
index 1cb3fee256..b7b6b92ed0 100644
--- a/core/vector.h
+++ b/core/vector.h
@@ -34,45 +34,43 @@
* @author Juan Linietsky
* Vector container. Regular Vector Container. Use with care and for smaller arrays when possible. Use PoolVector for large arrays.
*/
-#include "os/memory.h"
#include "error_macros.h"
+#include "os/memory.h"
#include "safe_refcount.h"
#include "sort.h"
-template<class T>
+template <class T>
class Vector {
- mutable T* _ptr;
+ mutable T *_ptr;
- // internal helpers
+ // internal helpers
- _FORCE_INLINE_ uint32_t* _get_refcount() const {
+ _FORCE_INLINE_ uint32_t *_get_refcount() const {
if (!_ptr)
- return NULL;
+ return NULL;
- return reinterpret_cast<uint32_t*>(_ptr)-2;
- }
+ return reinterpret_cast<uint32_t *>(_ptr) - 2;
+ }
- _FORCE_INLINE_ uint32_t* _get_size() const {
+ _FORCE_INLINE_ uint32_t *_get_size() const {
if (!_ptr)
return NULL;
- return reinterpret_cast<uint32_t*>(_ptr)-1;
-
- }
- _FORCE_INLINE_ T* _get_data() const {
+ return reinterpret_cast<uint32_t *>(_ptr) - 1;
+ }
+ _FORCE_INLINE_ T *_get_data() const {
if (!_ptr)
- return NULL;
- return reinterpret_cast<T*>(_ptr);
-
- }
+ return NULL;
+ return reinterpret_cast<T *>(_ptr);
+ }
_FORCE_INLINE_ size_t _get_alloc_size(size_t p_elements) const {
//return nearest_power_of_2_templated(p_elements*sizeof(T)+sizeof(SafeRefCount)+sizeof(int));
- return nearest_power_of_2(p_elements*sizeof(T));
+ return nearest_power_of_2(p_elements * sizeof(T));
}
_FORCE_INLINE_ bool _get_alloc_size_checked(size_t p_elements, size_t *out) const {
@@ -93,19 +91,24 @@ class Vector {
void _unref(void *p_data);
- void _copy_from(const Vector& p_from);
+ void _copy_from(const Vector &p_from);
void _copy_on_write();
-public:
-
-
- _FORCE_INLINE_ T *ptr() { if (!_ptr) return NULL; _copy_on_write(); return (T*)_get_data(); }
- _FORCE_INLINE_ const T *ptr() const { if (!_ptr) return NULL; return _get_data(); }
+public:
+ _FORCE_INLINE_ T *ptr() {
+ if (!_ptr) return NULL;
+ _copy_on_write();
+ return (T *)_get_data();
+ }
+ _FORCE_INLINE_ const T *ptr() const {
+ if (!_ptr) return NULL;
+ return _get_data();
+ }
_FORCE_INLINE_ void clear() { resize(0); }
_FORCE_INLINE_ int size() const {
- uint32_t* size = (uint32_t*)_get_size();
+ uint32_t *size = (uint32_t *)_get_size();
if (size)
return *size;
else
@@ -116,21 +119,23 @@ public:
bool push_back(T p_elem);
void remove(int p_index);
- void erase(const T& p_val) { int idx = find(p_val); if (idx>=0) remove(idx); };
+ void erase(const T &p_val) {
+ int idx = find(p_val);
+ if (idx >= 0) remove(idx);
+ };
void invert();
-
template <class T_val>
- int find(const T_val& p_val, int p_from=0) const;
+ int find(const T_val &p_val, int p_from = 0) const;
- void set(int p_index,T p_elem);
+ void set(int p_index, T p_elem);
T get(int p_index) const;
- inline T& operator[](int p_index) {
+ inline T &operator[](int p_index) {
- if (p_index<0 || p_index>=size()) {
- T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux);
+ if (p_index < 0 || p_index >= size()) {
+ T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux);
}
_copy_on_write(); // wants to write, so copy on write.
@@ -138,27 +143,27 @@ public:
return _get_data()[p_index];
}
- inline const T& operator[](int p_index) const {
+ inline const T &operator[](int p_index) const {
- if (p_index<0 || p_index>=size()) {
- const T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(p_index<0 || p_index>=size(),aux);
+ if (p_index < 0 || p_index >= size()) {
+ const T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(p_index < 0 || p_index >= size(), aux);
}
// no cow needed, since it's reading
return _get_data()[p_index];
}
- Error insert(int p_pos,const T& p_val);
+ Error insert(int p_pos, const T &p_val);
- template<class C>
+ template <class C>
void sort_custom() {
int len = size();
- if (len==0)
+ if (len == 0)
return;
T *data = &operator[](0);
- SortArray<T,C> sorter;
- sorter.sort(data,len);
+ SortArray<T, C> sorter;
+ sorter.sort(data, len);
}
void sort() {
@@ -166,26 +171,25 @@ public:
sort_custom<_DefaultComparator<T> >();
}
- void ordered_insert(const T& p_val) {
- int i;
- for (i=0; i<size(); i++) {
+ void ordered_insert(const T &p_val) {
+ int i;
+ for (i = 0; i < size(); i++) {
- if (p_val < operator[](i)) {
- break;
- };
+ if (p_val < operator[](i)) {
+ break;
};
- insert(i, p_val);
+ };
+ insert(i, p_val);
}
- void operator=(const Vector& p_from);
- Vector(const Vector& p_from);
+ void operator=(const Vector &p_from);
+ Vector(const Vector &p_from);
_FORCE_INLINE_ Vector();
_FORCE_INLINE_ ~Vector();
-
};
-template<class T>
+template <class T>
void Vector<T>::_unref(void *p_data) {
if (!p_data)
@@ -193,24 +197,23 @@ void Vector<T>::_unref(void *p_data) {
uint32_t *refc = _get_refcount();
- if (atomic_decrement(refc)>0)
+ if (atomic_decrement(refc) > 0)
return; // still in use
// clean up
uint32_t *count = _get_size();
- T *data = (T*)(count+1);
+ T *data = (T *)(count + 1);
- for (uint32_t i=0;i<*count;i++) {
+ for (uint32_t i = 0; i < *count; i++) {
// call destructors
data[i].~T();
}
// free mem
- Memory::free_static((uint8_t*)p_data,true);
-
+ Memory::free_static((uint8_t *)p_data, true);
}
-template<class T>
+template <class T>
void Vector<T>::_copy_on_write() {
if (!_ptr)
@@ -222,34 +225,33 @@ void Vector<T>::_copy_on_write() {
/* in use by more than me */
uint32_t current_size = *_get_size();
- uint32_t* mem_new = (uint32_t*)Memory::alloc_static(_get_alloc_size(current_size),true);
+ uint32_t *mem_new = (uint32_t *)Memory::alloc_static(_get_alloc_size(current_size), true);
+ *(mem_new - 2) = 1; //refcount
+ *(mem_new - 1) = current_size; //size
- *(mem_new-2)=1; //refcount
- *(mem_new-1)=current_size; //size
-
- T*_data=(T*)(mem_new);
+ T *_data = (T *)(mem_new);
// initialize new elements
- for (uint32_t i=0;i<current_size;i++) {
+ for (uint32_t i = 0; i < current_size; i++) {
- memnew_placement(&_data[i], T( _get_data()[i] ) );
+ memnew_placement(&_data[i], T(_get_data()[i]));
}
_unref(_ptr);
- _ptr=_data;
+ _ptr = _data;
}
-
}
-template<class T> template<class T_val>
+template <class T>
+template <class T_val>
int Vector<T>::find(const T_val &p_val, int p_from) const {
int ret = -1;
if (p_from < 0 || size() == 0)
return ret;
- for (int i=p_from; i<size(); i++) {
+ for (int i = p_from; i < size(); i++) {
if (operator[](i) == p_val) {
ret = i;
@@ -260,18 +262,18 @@ int Vector<T>::find(const T_val &p_val, int p_from) const {
return ret;
}
-template<class T>
+template <class T>
Error Vector<T>::resize(int p_size) {
- ERR_FAIL_COND_V(p_size<0,ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_size < 0, ERR_INVALID_PARAMETER);
- if (p_size==size())
+ if (p_size == size())
return OK;
- if (p_size==0) {
+ if (p_size == 0) {
// wants to clean up
_unref(_ptr);
- _ptr=NULL;
+ _ptr = NULL;
return OK;
}
@@ -281,159 +283,150 @@ Error Vector<T>::resize(int p_size) {
size_t alloc_size;
ERR_FAIL_COND_V(!_get_alloc_size_checked(p_size, &alloc_size), ERR_OUT_OF_MEMORY);
- if (p_size>size()) {
+ if (p_size > size()) {
- if (size()==0) {
+ if (size() == 0) {
// alloc from scratch
- uint32_t *ptr=(uint32_t*)Memory::alloc_static(alloc_size,true);
- ERR_FAIL_COND_V( !ptr ,ERR_OUT_OF_MEMORY);
- *(ptr-1)=0; //size, currently none
- *(ptr-2)=1; //refcount
+ uint32_t *ptr = (uint32_t *)Memory::alloc_static(alloc_size, true);
+ ERR_FAIL_COND_V(!ptr, ERR_OUT_OF_MEMORY);
+ *(ptr - 1) = 0; //size, currently none
+ *(ptr - 2) = 1; //refcount
- _ptr=(T*)ptr;
+ _ptr = (T *)ptr;
} else {
- void *_ptrnew = (T*)Memory::realloc_static(_ptr, alloc_size,true);
- ERR_FAIL_COND_V( !_ptrnew ,ERR_OUT_OF_MEMORY);
- _ptr=(T*)(_ptrnew);
+ void *_ptrnew = (T *)Memory::realloc_static(_ptr, alloc_size, true);
+ ERR_FAIL_COND_V(!_ptrnew, ERR_OUT_OF_MEMORY);
+ _ptr = (T *)(_ptrnew);
}
// construct the newly created elements
- T*elems = _get_data();
+ T *elems = _get_data();
- for (int i=*_get_size();i<p_size;i++) {
+ for (int i = *_get_size(); i < p_size; i++) {
- memnew_placement(&elems[i], T) ;
+ memnew_placement(&elems[i], T);
}
- *_get_size()=p_size;
+ *_get_size() = p_size;
- } else if (p_size<size()) {
+ } else if (p_size < size()) {
// deinitialize no longer needed elements
- for (uint32_t i=p_size;i<*_get_size();i++) {
+ for (uint32_t i = p_size; i < *_get_size(); i++) {
- T* t = &_get_data()[i];
+ T *t = &_get_data()[i];
t->~T();
}
- void *_ptrnew = (T*)Memory::realloc_static(_ptr, alloc_size,true);
- ERR_FAIL_COND_V( !_ptrnew ,ERR_OUT_OF_MEMORY);
+ void *_ptrnew = (T *)Memory::realloc_static(_ptr, alloc_size, true);
+ ERR_FAIL_COND_V(!_ptrnew, ERR_OUT_OF_MEMORY);
- _ptr=(T*)(_ptrnew);
-
- *_get_size()=p_size;
+ _ptr = (T *)(_ptrnew);
+ *_get_size() = p_size;
}
return OK;
}
-
-template<class T>
+template <class T>
void Vector<T>::invert() {
- for(int i=0;i<size()/2;i++) {
+ for (int i = 0; i < size() / 2; i++) {
- SWAP( operator[](i), operator[](size()-i-1) );
+ SWAP(operator[](i), operator[](size() - i - 1));
}
}
-template<class T>
-void Vector<T>::set(int p_index,T p_elem) {
+template <class T>
+void Vector<T>::set(int p_index, T p_elem) {
- operator[](p_index)=p_elem;
+ operator[](p_index) = p_elem;
}
-template<class T>
+template <class T>
T Vector<T>::get(int p_index) const {
return operator[](p_index);
}
-template<class T>
+template <class T>
bool Vector<T>::push_back(T p_elem) {
- Error err = resize(size()+1);
- ERR_FAIL_COND_V( err, true )
- set(size()-1,p_elem);
+ Error err = resize(size() + 1);
+ ERR_FAIL_COND_V(err, true)
+ set(size() - 1, p_elem);
return false;
}
-
-template<class T>
+template <class T>
void Vector<T>::remove(int p_index) {
ERR_FAIL_INDEX(p_index, size());
- T*p=ptr();
- int len=size();
- for (int i=p_index; i<len-1; i++) {
+ T *p = ptr();
+ int len = size();
+ for (int i = p_index; i < len - 1; i++) {
- p[i]=p[i+1];
+ p[i] = p[i + 1];
};
- resize(len-1);
+ resize(len - 1);
};
-template<class T>
-void Vector<T>::_copy_from(const Vector& p_from) {
+template <class T>
+void Vector<T>::_copy_from(const Vector &p_from) {
if (_ptr == p_from._ptr)
return; // self assign, do nothing.
_unref(_ptr);
- _ptr=NULL;
+ _ptr = NULL;
if (!p_from._ptr)
return; //nothing to do
- if (atomic_conditional_increment(p_from._get_refcount())>0) { // could reference
- _ptr=p_from._ptr;
+ if (atomic_conditional_increment(p_from._get_refcount()) > 0) { // could reference
+ _ptr = p_from._ptr;
}
-
}
-template<class T>
-void Vector<T>::operator=(const Vector& p_from) {
+template <class T>
+void Vector<T>::operator=(const Vector &p_from) {
_copy_from(p_from);
}
+template <class T>
+Error Vector<T>::insert(int p_pos, const T &p_val) {
-template<class T>
-Error Vector<T>::insert(int p_pos,const T& p_val) {
-
- ERR_FAIL_INDEX_V(p_pos,size()+1,ERR_INVALID_PARAMETER);
- resize(size()+1);
- for (int i=(size()-1);i>p_pos;i--)
- set( i, get(i-1) );
- set( p_pos, p_val );
+ ERR_FAIL_INDEX_V(p_pos, size() + 1, ERR_INVALID_PARAMETER);
+ resize(size() + 1);
+ for (int i = (size() - 1); i > p_pos; i--)
+ set(i, get(i - 1));
+ set(p_pos, p_val);
return OK;
}
-template<class T>
-Vector<T>::Vector(const Vector& p_from) {
-
- _ptr=NULL;
- _copy_from( p_from );
+template <class T>
+Vector<T>::Vector(const Vector &p_from) {
+ _ptr = NULL;
+ _copy_from(p_from);
}
-template<class T>
+template <class T>
Vector<T>::Vector() {
- _ptr=NULL;
+ _ptr = NULL;
}
-
-template<class T>
+template <class T>
Vector<T>::~Vector() {
_unref(_ptr);
-
}
-
#endif
diff --git a/core/vmap.h b/core/vmap.h
index 3708cbed5b..8446015568 100644
--- a/core/vmap.h
+++ b/core/vmap.h
@@ -32,7 +32,7 @@
#include "typedefs.h"
#include "vector.h"
-template<class T,class V>
+template <class T, class V>
class VMap {
struct _Pair {
@@ -42,64 +42,61 @@ class VMap {
_FORCE_INLINE_ _Pair() {}
- _FORCE_INLINE_ _Pair(const T& p_key, const V& p_value) {
+ _FORCE_INLINE_ _Pair(const T &p_key, const V &p_value) {
- key=p_key;
- value=p_value;
+ key = p_key;
+ value = p_value;
}
-
};
Vector<_Pair> _data;
- _FORCE_INLINE_ int _find(const T& p_val,bool &r_exact) const {
+ _FORCE_INLINE_ int _find(const T &p_val, bool &r_exact) const {
- r_exact=false;
+ r_exact = false;
if (_data.empty())
return 0;
int low = 0;
- int high = _data.size() -1;
+ int high = _data.size() - 1;
int middle;
- const _Pair *a=&_data[0];
+ const _Pair *a = &_data[0];
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( p_val < a[ middle].key ) {
+ if (p_val < a[middle].key) {
high = middle - 1; //search low end of array
- } else if ( a[middle].key < p_val) {
+ } else if (a[middle].key < p_val) {
low = middle + 1; //search high end of array
} else {
- r_exact=true;
+ r_exact = true;
return middle;
}
}
//return the position where this would be inserted
- if (a[middle].key<p_val)
+ if (a[middle].key < p_val)
middle++;
return middle;
}
- _FORCE_INLINE_ int _find_exact(const T& p_val) const {
+ _FORCE_INLINE_ int _find_exact(const T &p_val) const {
if (_data.empty())
return -1;
int low = 0;
- int high = _data.size() -1;
+ int high = _data.size() - 1;
int middle;
- const _Pair *a=&_data[0];
+ const _Pair *a = &_data[0];
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( p_val < a[ middle].key ) {
+ if (p_val < a[middle].key) {
high = middle - 1; //search low end of array
- } else if ( a[middle].key < p_val) {
+ } else if (a[middle].key < p_val) {
low = middle + 1; //search high end of array
} else {
return middle;
@@ -110,49 +107,45 @@ class VMap {
}
public:
-
- int insert(const T& p_key,const V& p_val) {
+ int insert(const T &p_key, const V &p_val) {
bool exact;
- int pos = _find(p_key,exact);
+ int pos = _find(p_key, exact);
if (exact) {
- _data[pos].value=p_val;
+ _data[pos].value = p_val;
return pos;
}
- _data.insert(pos,_Pair(p_key,p_val));
+ _data.insert(pos, _Pair(p_key, p_val));
return pos;
}
- bool has(const T& p_val) const {
+ bool has(const T &p_val) const {
- return _find_exact(p_val)!=-1;
+ return _find_exact(p_val) != -1;
}
- void erase(const T& p_val) {
+ void erase(const T &p_val) {
int pos = _find_exact(p_val);
- if (pos<0)
+ if (pos < 0)
return;
_data.remove(pos);
}
- int find(const T& p_val) const {
+ int find(const T &p_val) const {
return _find_exact(p_val);
-
}
- int find_nearest(const T& p_val) const {
+ int find_nearest(const T &p_val) const {
bool exact;
- return _find(p_val,exact);
-
+ return _find(p_val, exact);
}
_FORCE_INLINE_ int size() const { return _data.size(); }
_FORCE_INLINE_ bool empty() const { return _data.empty(); }
-
const _Pair *get_array() const {
return _data.ptr();
@@ -163,55 +156,46 @@ public:
return _data.ptr();
}
-
- const V& getv(int p_index) const {
+ const V &getv(int p_index) const {
return _data[p_index].value;
}
- V& getv(int p_index) {
+ V &getv(int p_index) {
return _data[p_index].value;
}
-
- const T& getk(int p_index) const {
+ const T &getk(int p_index) const {
return _data[p_index].key;
}
- T& getk(int p_index) {
+ T &getk(int p_index) {
return _data[p_index].key;
}
-
- inline const V& operator[](const T& p_key) const {
+ inline const V &operator[](const T &p_key) const {
int pos = _find_exact(p_key);
- if (pos<0) {
- const T& aux=*((T*)0); //nullreturn
- ERR_FAIL_COND_V(pos<1,aux);
+ if (pos < 0) {
+ const T &aux = *((T *)0); //nullreturn
+ ERR_FAIL_COND_V(pos < 1, aux);
}
return _data[pos].value;
}
-
-
- inline V& operator[](const T& p_key) {
+ inline V &operator[](const T &p_key) {
int pos = _find_exact(p_key);
- if (pos<0) {
+ if (pos < 0) {
V val;
- pos = insert(p_key,val);
-
+ pos = insert(p_key, val);
}
return _data[pos].value;
}
-
-
-
};
#endif // VMAP_H
diff --git a/core/vset.h b/core/vset.h
index e0b5181263..e7e204115f 100644
--- a/core/vset.h
+++ b/core/vset.h
@@ -32,60 +32,57 @@
#include "typedefs.h"
#include "vector.h"
-template<class T>
+template <class T>
class VSet {
-
Vector<T> _data;
- _FORCE_INLINE_ int _find(const T& p_val,bool &r_exact) const {
+ _FORCE_INLINE_ int _find(const T &p_val, bool &r_exact) const {
- r_exact=false;
+ r_exact = false;
if (_data.empty())
return 0;
int low = 0;
- int high = _data.size() -1;
+ int high = _data.size() - 1;
int middle;
- const T *a=&_data[0];
+ const T *a = &_data[0];
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( p_val < a[ middle] ) {
+ if (p_val < a[middle]) {
high = middle - 1; //search low end of array
- } else if ( a[middle] < p_val) {
+ } else if (a[middle] < p_val) {
low = middle + 1; //search high end of array
} else {
- r_exact=true;
+ r_exact = true;
return middle;
}
}
//return the position where this would be inserted
- if (a[middle]<p_val)
+ if (a[middle] < p_val)
middle++;
return middle;
}
- _FORCE_INLINE_ int _find_exact(const T& p_val) const {
+ _FORCE_INLINE_ int _find_exact(const T &p_val) const {
if (_data.empty())
return -1;
int low = 0;
- int high = _data.size() -1;
+ int high = _data.size() - 1;
int middle;
- const T *a=&_data[0];
+ const T *a = &_data[0];
- while( low <= high )
- {
- middle = ( low + high ) / 2;
+ while (low <= high) {
+ middle = (low + high) / 2;
- if( p_val < a[ middle] ) {
+ if (p_val < a[middle]) {
high = middle - 1; //search low end of array
- } else if ( a[middle] < p_val) {
+ } else if (a[middle] < p_val) {
low = middle + 1; //search high end of array
} else {
return middle;
@@ -96,50 +93,46 @@ class VSet {
}
public:
-
- void insert(const T& p_val) {
+ void insert(const T &p_val) {
bool exact;
- int pos = _find(p_val,exact);
+ int pos = _find(p_val, exact);
if (exact)
return;
- _data.insert(pos,p_val);
+ _data.insert(pos, p_val);
}
- bool has(const T& p_val) const {
+ bool has(const T &p_val) const {
- return _find_exact(p_val)!=-1;
+ return _find_exact(p_val) != -1;
}
- void erase(const T& p_val) {
+ void erase(const T &p_val) {
int pos = _find_exact(p_val);
- if (pos<0)
+ if (pos < 0)
return;
_data.remove(pos);
}
- int find(const T& p_val) const {
+ int find(const T &p_val) const {
return _find_exact(p_val);
-
}
_FORCE_INLINE_ bool empty() const { return _data.empty(); }
_FORCE_INLINE_ int size() const { return _data.size(); }
- inline T& operator[](int p_index) {
+ inline T &operator[](int p_index) {
return _data[p_index];
}
- inline const T& operator[](int p_index) const {
+ inline const T &operator[](int p_index) const {
return _data[p_index];
}
-
-
};
#endif // VSET_H
diff --git a/drivers/alsa/audio_driver_alsa.cpp b/drivers/alsa/audio_driver_alsa.cpp
index f2616b11b8..7e445c7c10 100644
--- a/drivers/alsa/audio_driver_alsa.cpp
+++ b/drivers/alsa/audio_driver_alsa.cpp
@@ -36,27 +36,26 @@
Error AudioDriverALSA::init() {
- active=false;
- thread_exited=false;
- exit_thread=false;
+ active = false;
+ thread_exited = false;
+ exit_thread = false;
pcm_open = false;
samples_in = NULL;
samples_out = NULL;
- mix_rate = GLOBAL_DEF("audio/mix_rate",44100);
+ mix_rate = GLOBAL_DEF("audio/mix_rate", 44100);
speaker_mode = SPEAKER_MODE_STEREO;
channels = 2;
-
- int status;
+ int status;
snd_pcm_hw_params_t *hwparams;
snd_pcm_sw_params_t *swparams;
-#define CHECK_FAIL(m_cond)\
- if (m_cond) {\
- fprintf(stderr,"ALSA ERR: %s\n",snd_strerror(status));\
- snd_pcm_close(pcm_handle);\
- ERR_FAIL_COND_V(m_cond,ERR_CANT_OPEN);\
+#define CHECK_FAIL(m_cond) \
+ if (m_cond) { \
+ fprintf(stderr, "ALSA ERR: %s\n", snd_strerror(status)); \
+ snd_pcm_close(pcm_handle); \
+ ERR_FAIL_COND_V(m_cond, ERR_CANT_OPEN); \
}
//todo, add
@@ -65,81 +64,80 @@ Error AudioDriverALSA::init() {
status = snd_pcm_open(&pcm_handle, "default", SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
- ERR_FAIL_COND_V( status<0, ERR_CANT_OPEN );
+ ERR_FAIL_COND_V(status < 0, ERR_CANT_OPEN);
snd_pcm_hw_params_alloca(&hwparams);
status = snd_pcm_hw_params_any(pcm_handle, hwparams);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
status = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
//not interested in anything else
status = snd_pcm_hw_params_set_format(pcm_handle, hwparams, SND_PCM_FORMAT_S16_LE);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
//todo: support 4 and 6
status = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, 2);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
status = snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &mix_rate, NULL);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
- int latency = GLOBAL_DEF("audio/output_latency",25);
- buffer_size = nearest_power_of_2( latency * mix_rate / 1000 );
+ int latency = GLOBAL_DEF("audio/output_latency", 25);
+ buffer_size = nearest_power_of_2(latency * mix_rate / 1000);
// set buffer size from project settings
status = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hwparams, &buffer_size);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
- // make period size 1/8
+ // make period size 1/8
period_size = buffer_size >> 3;
status = snd_pcm_hw_params_set_period_size_near(pcm_handle, hwparams, &period_size, NULL);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
- unsigned int periods=2;
+ unsigned int periods = 2;
status = snd_pcm_hw_params_set_periods_near(pcm_handle, hwparams, &periods, NULL);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
- status = snd_pcm_hw_params(pcm_handle,hwparams);
- CHECK_FAIL( status<0 );
+ status = snd_pcm_hw_params(pcm_handle, hwparams);
+ CHECK_FAIL(status < 0);
//snd_pcm_hw_params_free(&hwparams);
-
snd_pcm_sw_params_alloca(&swparams);
status = snd_pcm_sw_params_current(pcm_handle, swparams);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
status = snd_pcm_sw_params_set_avail_min(pcm_handle, swparams, period_size);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
status = snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams, 1);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
status = snd_pcm_sw_params(pcm_handle, swparams);
- CHECK_FAIL( status<0 );
+ CHECK_FAIL(status < 0);
- samples_in = memnew_arr(int32_t, period_size*channels);
- samples_out = memnew_arr(int16_t, period_size*channels);
+ samples_in = memnew_arr(int32_t, period_size * channels);
+ samples_out = memnew_arr(int16_t, period_size * channels);
snd_pcm_nonblock(pcm_handle, 0);
- mutex=Mutex::create();
+ mutex = Mutex::create();
thread = Thread::create(AudioDriverALSA::thread_func, this);
return OK;
};
-void AudioDriverALSA::thread_func(void* p_udata) {
+void AudioDriverALSA::thread_func(void *p_udata) {
- AudioDriverALSA* ad = (AudioDriverALSA*)p_udata;
+ AudioDriverALSA *ad = (AudioDriverALSA *)p_udata;
while (!ad->exit_thread) {
if (!ad->active) {
- for (unsigned int i=0; i < ad->period_size*ad->channels; i++) {
+ for (unsigned int i = 0; i < ad->period_size * ad->channels; i++) {
ad->samples_out[i] = 0;
};
} else {
@@ -149,36 +147,35 @@ void AudioDriverALSA::thread_func(void* p_udata) {
ad->unlock();
- for(unsigned int i=0;i<ad->period_size*ad->channels;i++) {
- ad->samples_out[i]=ad->samples_in[i]>>16;
+ for (unsigned int i = 0; i < ad->period_size * ad->channels; i++) {
+ ad->samples_out[i] = ad->samples_in[i] >> 16;
}
};
-
int todo = ad->period_size;
int total = 0;
while (todo) {
if (ad->exit_thread)
break;
- uint8_t* src = (uint8_t*)ad->samples_out;
- int wrote = snd_pcm_writei(ad->pcm_handle, (void*)(src + (total*ad->channels)), todo);
+ uint8_t *src = (uint8_t *)ad->samples_out;
+ int wrote = snd_pcm_writei(ad->pcm_handle, (void *)(src + (total * ad->channels)), todo);
if (wrote < 0) {
if (ad->exit_thread)
break;
- if ( wrote == -EAGAIN ) {
+ if (wrote == -EAGAIN) {
//can't write yet (though this is blocking..)
- usleep(1000);
+ usleep(1000);
continue;
}
wrote = snd_pcm_recover(ad->pcm_handle, wrote, 0);
- if ( wrote < 0 ) {
+ if (wrote < 0) {
//absolute fail
fprintf(stderr, "ALSA failed and can't recover: %s\n", snd_strerror(wrote));
- ad->active=false;
- ad->exit_thread=true;
+ ad->active = false;
+ ad->exit_thread = true;
break;
}
continue;
@@ -189,8 +186,7 @@ void AudioDriverALSA::thread_func(void* p_udata) {
};
};
- ad->thread_exited=true;
-
+ ad->thread_exited = true;
};
void AudioDriverALSA::start() {
@@ -247,11 +243,11 @@ void AudioDriverALSA::finish() {
AudioDriverALSA::AudioDriverALSA() {
mutex = NULL;
- thread=NULL;
- pcm_handle=NULL;
+ thread = NULL;
+ pcm_handle = NULL;
};
-AudioDriverALSA::~AudioDriverALSA() {
+AudioDriverALSA::~AudioDriverALSA(){
};
diff --git a/drivers/alsa/audio_driver_alsa.h b/drivers/alsa/audio_driver_alsa.h
index 6ab98312b2..e545b7a511 100644
--- a/drivers/alsa/audio_driver_alsa.h
+++ b/drivers/alsa/audio_driver_alsa.h
@@ -30,22 +30,22 @@
#ifdef ALSA_ENABLED
-#include "core/os/thread.h"
#include "core/os/mutex.h"
+#include "core/os/thread.h"
#include <alsa/asoundlib.h>
class AudioDriverALSA : public AudioDriver {
- Thread* thread;
- Mutex* mutex;
+ Thread *thread;
+ Mutex *mutex;
- snd_pcm_t* pcm_handle;
+ snd_pcm_t *pcm_handle;
- int32_t* samples_in;
- int16_t* samples_out;
+ int32_t *samples_in;
+ int16_t *samples_out;
- static void thread_func(void* p_udata);
+ static void thread_func(void *p_udata);
unsigned int mix_rate;
SpeakerMode speaker_mode;
@@ -60,8 +60,7 @@ class AudioDriverALSA : public AudioDriver {
bool pcm_open;
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "ALSA";
};
diff --git a/drivers/convex_decomp/b2d_decompose.cpp b/drivers/convex_decomp/b2d_decompose.cpp
index f84faaf586..afafda1527 100644
--- a/drivers/convex_decomp/b2d_decompose.cpp
+++ b/drivers/convex_decomp/b2d_decompose.cpp
@@ -31,132 +31,129 @@
namespace b2ConvexDecomp {
-
-void add_to_res(Vector< Vector<Vector2> >& res,const b2Polygon& p_poly) {
+void add_to_res(Vector<Vector<Vector2> > &res, const b2Polygon &p_poly) {
Vector<Vector2> arr;
- for(int i=0;i<p_poly.nVertices;i++) {
+ for (int i = 0; i < p_poly.nVertices; i++) {
- arr.push_back(Vector2(p_poly.x[i],p_poly.y[i]));
+ arr.push_back(Vector2(p_poly.x[i], p_poly.y[i]));
}
res.push_back(arr);
-
}
-static Vector< Vector<Vector2> > _b2d_decompose(const Vector<Vector2>& p_polygon) {
+static Vector<Vector<Vector2> > _b2d_decompose(const Vector<Vector2> &p_polygon) {
-
- Vector< Vector<Vector2> > res;
- if (p_polygon.size()<3)
+ Vector<Vector<Vector2> > res;
+ if (p_polygon.size() < 3)
return res;
- b2Vec2 *polys = memnew_arr(b2Vec2,p_polygon.size());
- for(int i=0;i<p_polygon.size();i++)
- polys[i]=b2Vec2(p_polygon[i].x,p_polygon[i].y);
-
+ b2Vec2 *polys = memnew_arr(b2Vec2, p_polygon.size());
+ for (int i = 0; i < p_polygon.size(); i++)
+ polys[i] = b2Vec2(p_polygon[i].x, p_polygon[i].y);
- b2Polygon *p = new b2Polygon(polys,p_polygon.size());
- b2Polygon* decomposed = new b2Polygon[p->nVertices - 2]; //maximum number of polys
+ b2Polygon *p = new b2Polygon(polys, p_polygon.size());
+ b2Polygon *decomposed = new b2Polygon[p->nVertices - 2]; //maximum number of polys
memdelete_arr(polys);
int32 nPolys = DecomposeConvex(p, decomposed, p->nVertices - 2);
- //int32 extra = 0;
+ //int32 extra = 0;
for (int32 i = 0; i < nPolys; ++i) {
- // b2FixtureDef* toAdd = &pdarray[i+extra];
- // *toAdd = *prototype;
- //Hmm, shouldn't have to do all this...
- b2Polygon curr = decomposed[i];
- //TODO ewjordan: move this triangle handling to a better place so that
- //it happens even if this convenience function is not called.
- if (curr.nVertices == 3){
- //Check here for near-parallel edges, since we can't
- //handle this in merge routine
- for (int j=0; j<3; ++j){
- int32 lower = (j == 0) ? (curr.nVertices - 1) : (j - 1);
- int32 middle = j;
- int32 upper = (j == curr.nVertices - 1) ? (0) : (j + 1);
- float32 dx0 = curr.x[middle] - curr.x[lower]; float32 dy0 = curr.y[middle] - curr.y[lower];
- float32 dx1 = curr.x[upper] - curr.x[middle]; float32 dy1 = curr.y[upper] - curr.y[middle];
- float32 norm0 = sqrtf(dx0*dx0+dy0*dy0); float32 norm1 = sqrtf(dx1*dx1+dy1*dy1);
- if ( !(norm0 > 0.0f && norm1 > 0.0f) ) {
- //Identical points, don't do anything!
- goto Skip;
- }
- dx0 /= norm0; dy0 /= norm0;
- dx1 /= norm1; dy1 /= norm1;
- float32 cross = dx0 * dy1 - dx1 * dy0;
- float32 dot = dx0*dx1 + dy0*dy1;
- if (fabs(cross) < b2_angularSlop && dot > 0) {
- //Angle too close, split the triangle across from this point.
- //This is guaranteed to result in two triangles that satify
- //the tolerance (one of the angles is 90 degrees)
- float32 dx2 = curr.x[lower] - curr.x[upper]; float32 dy2 = curr.y[lower] - curr.y[upper];
- float32 norm2 = sqrtf(dx2*dx2+dy2*dy2);
- if (norm2 == 0.0f) {
- goto Skip;
- }
- dx2 /= norm2; dy2 /= norm2;
- float32 thisArea = curr.GetArea();
- float32 thisHeight = 2.0f * thisArea / norm2;
- float32 buffer2 = dx2;
- dx2 = dy2; dy2 = -buffer2;
- //Make two new polygons
- //printf("dx2: %f, dy2: %f, thisHeight: %f, middle: %d\n",dx2,dy2,thisHeight,middle);
- float32 newX1[3] = { curr.x[middle]+dx2*thisHeight, curr.x[lower], curr.x[middle] };
- float32 newY1[3] = { curr.y[middle]+dy2*thisHeight, curr.y[lower], curr.y[middle] };
- float32 newX2[3] = { newX1[0], curr.x[middle], curr.x[upper] };
- float32 newY2[3] = { newY1[0], curr.y[middle], curr.y[upper] };
- b2Polygon p1(newX1,newY1,3);
- b2Polygon p2(newX2,newY2,3);
- if (p1.IsUsable()){
- add_to_res(res,p1);
- //++extra;
- } else if (B2_POLYGON_REPORT_ERRORS){
- printf("Didn't add unusable polygon. Dumping vertices:\n");
- p1.print();
- }
- if (p2.IsUsable()){
- add_to_res(res,p2);
-
- //p2.AddTo(pdarray[i+extra]);
-
- //bd->CreateFixture(toAdd);
- } else if (B2_POLYGON_REPORT_ERRORS){
- printf("Didn't add unusable polygon. Dumping vertices:\n");
- p2.print();
- }
- goto Skip;
- }
+ // b2FixtureDef* toAdd = &pdarray[i+extra];
+ // *toAdd = *prototype;
+ //Hmm, shouldn't have to do all this...
+ b2Polygon curr = decomposed[i];
+ //TODO ewjordan: move this triangle handling to a better place so that
+ //it happens even if this convenience function is not called.
+ if (curr.nVertices == 3) {
+ //Check here for near-parallel edges, since we can't
+ //handle this in merge routine
+ for (int j = 0; j < 3; ++j) {
+ int32 lower = (j == 0) ? (curr.nVertices - 1) : (j - 1);
+ int32 middle = j;
+ int32 upper = (j == curr.nVertices - 1) ? (0) : (j + 1);
+ float32 dx0 = curr.x[middle] - curr.x[lower];
+ float32 dy0 = curr.y[middle] - curr.y[lower];
+ float32 dx1 = curr.x[upper] - curr.x[middle];
+ float32 dy1 = curr.y[upper] - curr.y[middle];
+ float32 norm0 = sqrtf(dx0 * dx0 + dy0 * dy0);
+ float32 norm1 = sqrtf(dx1 * dx1 + dy1 * dy1);
+ if (!(norm0 > 0.0f && norm1 > 0.0f)) {
+ //Identical points, don't do anything!
+ goto Skip;
+ }
+ dx0 /= norm0;
+ dy0 /= norm0;
+ dx1 /= norm1;
+ dy1 /= norm1;
+ float32 cross = dx0 * dy1 - dx1 * dy0;
+ float32 dot = dx0 * dx1 + dy0 * dy1;
+ if (fabs(cross) < b2_angularSlop && dot > 0) {
+ //Angle too close, split the triangle across from this point.
+ //This is guaranteed to result in two triangles that satify
+ //the tolerance (one of the angles is 90 degrees)
+ float32 dx2 = curr.x[lower] - curr.x[upper];
+ float32 dy2 = curr.y[lower] - curr.y[upper];
+ float32 norm2 = sqrtf(dx2 * dx2 + dy2 * dy2);
+ if (norm2 == 0.0f) {
+ goto Skip;
}
+ dx2 /= norm2;
+ dy2 /= norm2;
+ float32 thisArea = curr.GetArea();
+ float32 thisHeight = 2.0f * thisArea / norm2;
+ float32 buffer2 = dx2;
+ dx2 = dy2;
+ dy2 = -buffer2;
+ //Make two new polygons
+ //printf("dx2: %f, dy2: %f, thisHeight: %f, middle: %d\n",dx2,dy2,thisHeight,middle);
+ float32 newX1[3] = { curr.x[middle] + dx2 * thisHeight, curr.x[lower], curr.x[middle] };
+ float32 newY1[3] = { curr.y[middle] + dy2 * thisHeight, curr.y[lower], curr.y[middle] };
+ float32 newX2[3] = { newX1[0], curr.x[middle], curr.x[upper] };
+ float32 newY2[3] = { newY1[0], curr.y[middle], curr.y[upper] };
+ b2Polygon p1(newX1, newY1, 3);
+ b2Polygon p2(newX2, newY2, 3);
+ if (p1.IsUsable()) {
+ add_to_res(res, p1);
+ //++extra;
+ } else if (B2_POLYGON_REPORT_ERRORS) {
+ printf("Didn't add unusable polygon. Dumping vertices:\n");
+ p1.print();
+ }
+ if (p2.IsUsable()) {
+ add_to_res(res, p2);
+ //p2.AddTo(pdarray[i+extra]);
+
+ //bd->CreateFixture(toAdd);
+ } else if (B2_POLYGON_REPORT_ERRORS) {
+ printf("Didn't add unusable polygon. Dumping vertices:\n");
+ p2.print();
+ }
+ goto Skip;
+ }
}
- if (decomposed[i].IsUsable()){
- add_to_res(res,decomposed[i]);
-
- //decomposed[i].AddTo(*toAdd);
- //bd->CreateFixture((const b2FixtureDef*)toAdd);
- } else if (B2_POLYGON_REPORT_ERRORS){
- printf("Didn't add unusable polygon. Dumping vertices:\n");
- decomposed[i].print();
- }
-Skip:
- ;
+ }
+ if (decomposed[i].IsUsable()) {
+ add_to_res(res, decomposed[i]);
+
+ //decomposed[i].AddTo(*toAdd);
+ //bd->CreateFixture((const b2FixtureDef*)toAdd);
+ } else if (B2_POLYGON_REPORT_ERRORS) {
+ printf("Didn't add unusable polygon. Dumping vertices:\n");
+ decomposed[i].print();
+ }
+ Skip:;
}
//delete[] pdarray;
delete[] decomposed;
delete p;
- return res;// pdarray; //needs to be deleted after body is created
-
+ return res; // pdarray; //needs to be deleted after body is created
}
-
}
-
-Vector< Vector<Vector2> > b2d_decompose(const Vector<Vector2>& p_polygon) {
+Vector<Vector<Vector2> > b2d_decompose(const Vector<Vector2> &p_polygon) {
return b2ConvexDecomp::_b2d_decompose(p_polygon);
-
-
}
diff --git a/drivers/convex_decomp/b2d_decompose.h b/drivers/convex_decomp/b2d_decompose.h
index 3a35ca140d..c3765275ef 100644
--- a/drivers/convex_decomp/b2d_decompose.h
+++ b/drivers/convex_decomp/b2d_decompose.h
@@ -31,6 +31,6 @@
#include "math_2d.h"
#include "vector.h"
-Vector< Vector<Vector2> > b2d_decompose(const Vector<Vector2>& p_polygon);
+Vector<Vector<Vector2> > b2d_decompose(const Vector<Vector2> &p_polygon);
#endif // B2D_DECOMPOSE_H
diff --git a/drivers/gl_context/context_gl.cpp b/drivers/gl_context/context_gl.cpp
index e99ec93e11..9fe7fbf2b8 100644
--- a/drivers/gl_context/context_gl.cpp
+++ b/drivers/gl_context/context_gl.cpp
@@ -28,31 +28,26 @@
/*************************************************************************/
#include "context_gl.h"
+#if defined(OPENGL_ENABLED) || defined(GLES2_ENABLED)
-#if defined(OPENGL_ENABLED) || defined(GLES2_ENABLED)
-
-
-
-ContextGL *ContextGL::singleton=NULL;
+ContextGL *ContextGL::singleton = NULL;
ContextGL *ContextGL::get_singleton() {
return singleton;
}
-
ContextGL::ContextGL() {
-
+
ERR_FAIL_COND(singleton);
-
- singleton=this;
-}
+ singleton = this;
+}
ContextGL::~ContextGL() {
- if (singleton==this)
- singleton=NULL;
+ if (singleton == this)
+ singleton = NULL;
}
#endif
diff --git a/drivers/gl_context/context_gl.h b/drivers/gl_context/context_gl.h
index 535b492297..280da1aea6 100644
--- a/drivers/gl_context/context_gl.h
+++ b/drivers/gl_context/context_gl.h
@@ -37,34 +37,28 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class ContextGL {
static ContextGL *singleton;
-public:
+public:
static ContextGL *get_singleton();
-
- virtual void release_current()=0;
- virtual void make_current()=0;
+ virtual void release_current() = 0;
- virtual void swap_buffers()=0;
-
- virtual Error initialize()=0;
+ virtual void make_current() = 0;
- virtual void set_use_vsync(bool p_use)=0;
- virtual bool is_using_vsync() const=0;
+ virtual void swap_buffers() = 0;
+ virtual Error initialize() = 0;
-
-
- ContextGL();
- ~ContextGL();
+ virtual void set_use_vsync(bool p_use) = 0;
+ virtual bool is_using_vsync() const = 0;
+ ContextGL();
+ ~ContextGL();
};
-
#endif
#endif
diff --git a/drivers/gles2/rasterizer_gles2.cpp b/drivers/gles2/rasterizer_gles2.cpp
index 94c5ecdec1..5deb78977a 100644
--- a/drivers/gles2/rasterizer_gles2.cpp
+++ b/drivers/gles2/rasterizer_gles2.cpp
@@ -29,34 +29,33 @@
#ifdef GLES2_ENABLED
#include "rasterizer_gles2.h"
-#include "os/os.h"
+#include "gl_context/context_gl.h"
#include "global_config.h"
-#include <stdio.h>
-#include "servers/visual/shader_language.h"
+#include "os/os.h"
#include "servers/visual/particle_system_sw.h"
-#include "gl_context/context_gl.h"
-#include <string.h>
+#include "servers/visual/shader_language.h"
+#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#ifdef GLEW_ENABLED
-#define _GL_HALF_FLOAT_OES 0x140B
+#define _GL_HALF_FLOAT_OES 0x140B
#else
-#define _GL_HALF_FLOAT_OES 0x8D61
+#define _GL_HALF_FLOAT_OES 0x8D61
#endif
-#define _GL_RGBA16F_EXT 0x881A
-#define _GL_RGB16F_EXT 0x881B
-#define _GL_RG16F_EXT 0x822F
-#define _GL_R16F_EXT 0x822D
+#define _GL_RGBA16F_EXT 0x881A
+#define _GL_RGB16F_EXT 0x881B
+#define _GL_RG16F_EXT 0x822F
+#define _GL_R16F_EXT 0x822D
#define _GL_R32F_EXT 0x822E
+#define _GL_RED_EXT 0x1903
+#define _GL_RG_EXT 0x8227
+#define _GL_R8_EXT 0x8229
+#define _GL_RG8_EXT 0x822B
-#define _GL_RED_EXT 0x1903
-#define _GL_RG_EXT 0x8227
-#define _GL_R8_EXT 0x8229
-#define _GL_RG8_EXT 0x822B
-
-#define _DEPTH_COMPONENT24_OES 0x81A6
+#define _DEPTH_COMPONENT24_OES 0x81A6
#ifdef GLEW_ENABLED
#define _glClearDepth glClearDepth
@@ -64,25 +63,25 @@
#define _glClearDepth glClearDepthf
#endif
-
#define _GL_SRGB_EXT 0x8C40
#define _GL_SRGB_ALPHA_EXT 0x8C42
-#define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
-#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
+#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
//#define DEBUG_OPENGL
#ifdef DEBUG_OPENGL
-#define DEBUG_TEST_ERROR(m_section)\
-{\
- print_line("AT: "+String(m_section)); glFlush();\
- uint32_t err = glGetError();\
- if (err) {\
- print_line("OpenGL Error #"+itos(err)+" at: "+m_section);\
- }\
-}
+#define DEBUG_TEST_ERROR(m_section) \
+ { \
+ print_line("AT: " + String(m_section)); \
+ glFlush(); \
+ uint32_t err = glGetError(); \
+ if (err) { \
+ print_line("OpenGL Error #" + itos(err) + " at: " + m_section); \
+ } \
+ }
#else
@@ -90,97 +89,87 @@
#endif
-static RasterizerGLES2* _singleton = NULL;
+static RasterizerGLES2 *_singleton = NULL;
#ifdef GLES_NO_CLIENT_ARRAYS
-static float GlobalVertexBuffer[MAX_POLYGON_VERTICES * 8] = {0};
+static float GlobalVertexBuffer[MAX_POLYGON_VERTICES * 8] = { 0 };
#endif
-static const GLenum prim_type[]={GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+static const GLenum prim_type[] = { GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN };
-_FORCE_INLINE_ static void _set_color_attrib(const Color& p_color) {
+_FORCE_INLINE_ static void _set_color_attrib(const Color &p_color) {
- GLfloat c[4]= { p_color.r, p_color.g, p_color.b, p_color.a };
- glVertexAttrib4fv( VS::ARRAY_COLOR, c );
+ GLfloat c[4] = { p_color.r, p_color.g, p_color.b, p_color.a };
+ glVertexAttrib4fv(VS::ARRAY_COLOR, c);
}
-
-
static _FORCE_INLINE_ uint16_t make_half_float(float f) {
- union {
- float fv;
- uint32_t ui;
- } ci;
- ci.fv=f;
-
- unsigned int x = ci.ui;
- unsigned int sign = (unsigned short)(x >> 31);
- unsigned int mantissa;
- unsigned int exp;
- uint16_t hf;
-
- // get mantissa
- mantissa = x & ((1 << 23) - 1);
- // get exponent bits
- exp = x & (0xFF << 23);
- if (exp >= 0x47800000)
- {
- // check if the original single precision float number is a NaN
- if (mantissa && (exp == (0xFF << 23)))
- {
- // we have a single precision NaN
- mantissa = (1 << 23) - 1;
- }
- else
- {
- // 16-bit half-float representation stores number as Inf
- mantissa = 0;
+ union {
+ float fv;
+ uint32_t ui;
+ } ci;
+ ci.fv = f;
+
+ unsigned int x = ci.ui;
+ unsigned int sign = (unsigned short)(x >> 31);
+ unsigned int mantissa;
+ unsigned int exp;
+ uint16_t hf;
+
+ // get mantissa
+ mantissa = x & ((1 << 23) - 1);
+ // get exponent bits
+ exp = x & (0xFF << 23);
+ if (exp >= 0x47800000) {
+ // check if the original single precision float number is a NaN
+ if (mantissa && (exp == (0xFF << 23))) {
+ // we have a single precision NaN
+ mantissa = (1 << 23) - 1;
+ } else {
+ // 16-bit half-float representation stores number as Inf
+ mantissa = 0;
+ }
+ hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) |
+ (uint16_t)(mantissa >> 13);
}
- hf = (((uint16_t)sign) << 15) | (uint16_t)((0x1F << 10)) |
- (uint16_t)(mantissa >> 13);
- }
- // check if exponent is <= -15
- else if (exp <= 0x38000000)
- {
+ // check if exponent is <= -15
+ else if (exp <= 0x38000000) {
- /*// store a denorm half-float value or zero
+ /*// store a denorm half-float value or zero
exp = (0x38000000 - exp) >> 23;
mantissa >>= (14 + exp);
hf = (((uint16_t)sign) << 15) | (uint16_t)(mantissa);
*/
- hf=0; //denormals do not work for 3D, convert to zero
- }
- else
- {
- hf = (((uint16_t)sign) << 15) |
- (uint16_t)((exp - 0x38000000) >> 13) |
- (uint16_t)(mantissa >> 13);
- }
+ hf = 0; //denormals do not work for 3D, convert to zero
+ } else {
+ hf = (((uint16_t)sign) << 15) |
+ (uint16_t)((exp - 0x38000000) >> 13) |
+ (uint16_t)(mantissa >> 13);
+ }
- return hf;
+ return hf;
}
-void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, const Vector3 *p_normals, const Color* p_colors, const Vector3 *p_uvs,const Plane *p_tangents,int p_instanced) {
+void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, const Vector3 *p_normals, const Color *p_colors, const Vector3 *p_uvs, const Plane *p_tangents, int p_instanced) {
ERR_FAIL_COND(!p_vertices);
- ERR_FAIL_COND(p_points <1 || p_points>4);
+ ERR_FAIL_COND(p_points < 1 || p_points > 4);
- bool quad=false;
+ bool quad = false;
GLenum type;
- switch(p_points) {
+ switch (p_points) {
- case 1: type=GL_POINTS; break;
- case 2: type=GL_LINES; break;
- case 4: quad=true; p_points=3;
- case 3: type=GL_TRIANGLES; break;
+ case 1: type = GL_POINTS; break;
+ case 2: type = GL_LINES; break;
+ case 4: quad = true; p_points = 3;
+ case 3: type = GL_TRIANGLES; break;
};
-
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
GLfloat vert_array[18];
GLfloat normal_array[18];
@@ -189,40 +178,38 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
GLfloat uv_array[18];
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 3 ,GL_FLOAT, false, 0, vert_array );
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, vert_array);
- for (int i=0;i<p_points;i++) {
+ for (int i = 0; i < p_points; i++) {
- vert_array[i*3+0]=p_vertices[i].x;
- vert_array[i*3+1]=p_vertices[i].y;
- vert_array[i*3+2]=p_vertices[i].z;
+ vert_array[i * 3 + 0] = p_vertices[i].x;
+ vert_array[i * 3 + 1] = p_vertices[i].y;
+ vert_array[i * 3 + 2] = p_vertices[i].z;
if (quad) {
- int idx=2+i;
- if (idx==4)
- idx=0;
- vert_array[9+i*3+0]=p_vertices[idx].x;
- vert_array[9+i*3+1]=p_vertices[idx].y;
- vert_array[9+i*3+2]=p_vertices[idx].z;
-
+ int idx = 2 + i;
+ if (idx == 4)
+ idx = 0;
+ vert_array[9 + i * 3 + 0] = p_vertices[idx].x;
+ vert_array[9 + i * 3 + 1] = p_vertices[idx].y;
+ vert_array[9 + i * 3 + 2] = p_vertices[idx].z;
}
}
if (p_normals) {
glEnableVertexAttribArray(VS::ARRAY_NORMAL);
- glVertexAttribPointer( VS::ARRAY_NORMAL, 3 ,GL_FLOAT, false, 0, normal_array );
- for (int i=0;i<p_points;i++) {
+ glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false, 0, normal_array);
+ for (int i = 0; i < p_points; i++) {
- normal_array[i*3+0]=p_normals[i].x;
- normal_array[i*3+1]=p_normals[i].y;
- normal_array[i*3+2]=p_normals[i].z;
+ normal_array[i * 3 + 0] = p_normals[i].x;
+ normal_array[i * 3 + 1] = p_normals[i].y;
+ normal_array[i * 3 + 2] = p_normals[i].z;
if (quad) {
- int idx=2+i;
- if (idx==4)
- idx=0;
- normal_array[9+i*3+0]=p_normals[idx].x;
- normal_array[9+i*3+1]=p_normals[idx].y;
- normal_array[9+i*3+2]=p_normals[idx].z;
-
+ int idx = 2 + i;
+ if (idx == 4)
+ idx = 0;
+ normal_array[9 + i * 3 + 0] = p_normals[idx].x;
+ normal_array[9 + i * 3 + 1] = p_normals[idx].y;
+ normal_array[9 + i * 3 + 2] = p_normals[idx].z;
}
}
} else {
@@ -231,22 +218,21 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
if (p_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, 0, color_array );
- for (int i=0;i<p_points;i++) {
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, 0, color_array);
+ for (int i = 0; i < p_points; i++) {
- color_array[i*4+0]=p_colors[i].r;
- color_array[i*4+1]=p_colors[i].g;
- color_array[i*4+2]=p_colors[i].b;
- color_array[i*4+3]=p_colors[i].a;
+ color_array[i * 4 + 0] = p_colors[i].r;
+ color_array[i * 4 + 1] = p_colors[i].g;
+ color_array[i * 4 + 2] = p_colors[i].b;
+ color_array[i * 4 + 3] = p_colors[i].a;
if (quad) {
- int idx=2+i;
- if (idx==4)
- idx=0;
- color_array[12+i*4+0]=p_colors[idx].r;
- color_array[12+i*4+1]=p_colors[idx].g;
- color_array[12+i*4+2]=p_colors[idx].b;
- color_array[12+i*4+3]=p_colors[idx].a;
-
+ int idx = 2 + i;
+ if (idx == 4)
+ idx = 0;
+ color_array[12 + i * 4 + 0] = p_colors[idx].r;
+ color_array[12 + i * 4 + 1] = p_colors[idx].g;
+ color_array[12 + i * 4 + 2] = p_colors[idx].b;
+ color_array[12 + i * 4 + 3] = p_colors[idx].a;
}
}
} else {
@@ -255,22 +241,21 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
if (p_tangents) {
glEnableVertexAttribArray(VS::ARRAY_TANGENT);
- glVertexAttribPointer( VS::ARRAY_TANGENT, 4 ,GL_FLOAT, false, 0, tangent_array );
- for (int i=0;i<p_points;i++) {
+ glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false, 0, tangent_array);
+ for (int i = 0; i < p_points; i++) {
- tangent_array[i*4+0]=p_tangents[i].normal.x;
- tangent_array[i*4+1]=p_tangents[i].normal.y;
- tangent_array[i*4+2]=p_tangents[i].normal.z;
- tangent_array[i*4+3]=p_tangents[i].d;
+ tangent_array[i * 4 + 0] = p_tangents[i].normal.x;
+ tangent_array[i * 4 + 1] = p_tangents[i].normal.y;
+ tangent_array[i * 4 + 2] = p_tangents[i].normal.z;
+ tangent_array[i * 4 + 3] = p_tangents[i].d;
if (quad) {
- int idx=2+i;
- if (idx==4)
- idx=0;
- tangent_array[12+i*4+0]=p_tangents[idx].normal.x;
- tangent_array[12+i*4+1]=p_tangents[idx].normal.y;
- tangent_array[12+i*4+2]=p_tangents[idx].normal.z;
- tangent_array[12+i*4+3]=p_tangents[idx].d;
-
+ int idx = 2 + i;
+ if (idx == 4)
+ idx = 0;
+ tangent_array[12 + i * 4 + 0] = p_tangents[idx].normal.x;
+ tangent_array[12 + i * 4 + 1] = p_tangents[idx].normal.y;
+ tangent_array[12 + i * 4 + 2] = p_tangents[idx].normal.z;
+ tangent_array[12 + i * 4 + 3] = p_tangents[idx].d;
}
}
} else {
@@ -280,20 +265,19 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
if (p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 3 ,GL_FLOAT, false, 0, uv_array );
- for (int i=0;i<p_points;i++) {
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 3, GL_FLOAT, false, 0, uv_array);
+ for (int i = 0; i < p_points; i++) {
- uv_array[i*3+0]=p_uvs[i].x;
- uv_array[i*3+1]=p_uvs[i].y;
- uv_array[i*3+2]=p_uvs[i].z;
+ uv_array[i * 3 + 0] = p_uvs[i].x;
+ uv_array[i * 3 + 1] = p_uvs[i].y;
+ uv_array[i * 3 + 2] = p_uvs[i].z;
if (quad) {
- int idx=2+i;
- if (idx==4)
- idx=0;
- uv_array[9+i*3+0]=p_uvs[idx].x;
- uv_array[9+i*3+1]=p_uvs[idx].y;
- uv_array[9+i*3+2]=p_uvs[idx].z;
-
+ int idx = 2 + i;
+ if (idx == 4)
+ idx = 0;
+ uv_array[9 + i * 3 + 0] = p_uvs[idx].x;
+ uv_array[9 + i * 3 + 1] = p_uvs[idx].y;
+ uv_array[9 + i * 3 + 2] = p_uvs[idx].z;
}
}
@@ -307,32 +291,28 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
else
*/
- glDrawArrays(type,0,quad?6:p_points);
-
+ glDrawArrays(type, 0, quad ? 6 : p_points);
};
-
/* TEXTURE API */
-#define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
-#define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
-#define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
-#define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
-
-#define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
-#define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
-#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
-#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
+#define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
+#define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
+#define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
+#define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
+#define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
+#define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
+#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
+#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
#define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
-#define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
-#define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
-#define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
-#define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
-
+#define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
+#define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
+#define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
+#define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
#define _EXT_COMPRESSED_RED_RGTC1_EXT 0x8DBB
#define _EXT_COMPRESSED_RED_RGTC1 0x8DBB
@@ -342,71 +322,65 @@ void RasterizerGLES2::_draw_primitive(int p_points, const Vector3 *p_vertices, c
#define _EXT_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
#define _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
#define _EXT_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
-#define _EXT_ETC1_RGB8_OES 0x8D64
-
-
-
-#define _EXT_SLUMINANCE_NV 0x8C46
-#define _EXT_SLUMINANCE_ALPHA_NV 0x8C44
-#define _EXT_SRGB8_NV 0x8C41
-#define _EXT_SLUMINANCE8_NV 0x8C47
-#define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45
-
+#define _EXT_ETC1_RGB8_OES 0x8D64
-#define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
+#define _EXT_SLUMINANCE_NV 0x8C46
+#define _EXT_SLUMINANCE_ALPHA_NV 0x8C44
+#define _EXT_SRGB8_NV 0x8C41
+#define _EXT_SLUMINANCE8_NV 0x8C47
+#define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45
+#define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
-
-#define _EXT_ATC_RGB_AMD 0x8C92
-#define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
-#define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
-
+#define _EXT_ATC_RGB_AMD 0x8C92
+#define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
+#define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
/* TEXTURE API */
-Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,GLenum& r_gl_internal_format,int &r_gl_components,bool &r_has_alpha_cache,bool &r_compressed) {
+Image RasterizerGLES2::_get_gl_image_and_format(const Image &p_image, Image::Format p_format, uint32_t p_flags, GLenum &r_gl_format, GLenum &r_gl_internal_format, int &r_gl_components, bool &r_has_alpha_cache, bool &r_compressed) {
- r_has_alpha_cache=false;
- r_compressed=false;
- r_gl_format=0;
- Image image=p_image;
+ r_has_alpha_cache = false;
+ r_compressed = false;
+ r_gl_format = 0;
+ Image image = p_image;
- switch(p_format) {
+ switch (p_format) {
case Image::FORMAT_L8: {
- r_gl_components=1;
- r_gl_format=GL_LUMINANCE;
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_SLUMINANCE_NV:GL_LUMINANCE;
+ r_gl_components = 1;
+ r_gl_format = GL_LUMINANCE;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_SLUMINANCE_NV : GL_LUMINANCE;
} break;
case Image::FORMAT_INTENSITY: {
if (!image.empty())
image.convert(Image::FORMAT_RGBA8);
- r_gl_components=4;
- r_gl_format=GL_RGBA;
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_GL_SRGB_ALPHA_EXT:GL_RGBA;
- r_has_alpha_cache=true;
+ r_gl_components = 4;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _GL_SRGB_ALPHA_EXT : GL_RGBA;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_LA8: {
//image.convert(Image::FORMAT_RGBA8);
- r_gl_components=2;
- r_gl_format=GL_LUMINANCE_ALPHA;
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_SLUMINANCE_ALPHA_NV:GL_LUMINANCE_ALPHA;
- r_has_alpha_cache=true;
+ r_gl_components = 2;
+ r_gl_format = GL_LUMINANCE_ALPHA;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_SLUMINANCE_ALPHA_NV : GL_LUMINANCE_ALPHA;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_INDEXED: {
if (!image.empty())
image.convert(Image::FORMAT_RGB8);
- r_gl_components=3;
- r_gl_format=GL_RGB;
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_GL_SRGB_EXT:GL_RGB;
+ r_gl_components = 3;
+ r_gl_format = GL_RGB;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _GL_SRGB_EXT : GL_RGB;
} break;
@@ -414,153 +388,153 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty())
image.convert(Image::FORMAT_RGBA8);
- r_gl_components=4;
+ r_gl_components = 4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_RGB8: {
- r_gl_components=3;
+ r_gl_components = 3;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_internal_format=_GL_SRGB_EXT;
- r_gl_format=GL_RGB;
+ r_gl_internal_format = _GL_SRGB_EXT;
+ r_gl_format = GL_RGB;
} else {
- r_gl_internal_format=GL_RGB;
+ r_gl_internal_format = GL_RGB;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGB;
+ r_gl_internal_format = GL_RGB;
}
} break;
case Image::FORMAT_RGBA8: {
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
- r_gl_format=GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
//r_gl_internal_format=GL_RGBA;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_DXT1: {
- if (!s3tc_supported || (!s3tc_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!s3tc_supported || (!s3tc_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_components=1; //doesn't matter much
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT;
- r_compressed=true;
+ r_gl_components = 1; //doesn't matter much
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT;
+ r_compressed = true;
};
} break;
case Image::FORMAT_DXT3: {
- if (!s3tc_supported || (!s3tc_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!s3tc_supported || (!s3tc_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_components=1; //doesn't matter much
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT;
+ r_gl_components = 1; //doesn't matter much
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT;
- r_has_alpha_cache=true;
- r_compressed=true;
+ r_has_alpha_cache = true;
+ r_compressed = true;
};
} break;
case Image::FORMAT_DXT5: {
- if (!s3tc_supported || (!s3tc_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!s3tc_supported || (!s3tc_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_components=1; //doesn't matter much
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT;
- r_has_alpha_cache=true;
- r_compressed=true;
+ r_gl_components = 1; //doesn't matter much
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT;
+ r_has_alpha_cache = true;
+ r_compressed = true;
};
} break;
@@ -571,212 +545,207 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_LATC1_EXT;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_LUMINANCE_LATC1_EXT;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
};
} break;
case Image::FORMAT_ATI2: {
- if (!latc_supported ) {
+ if (!latc_supported) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
};
} break;
case Image::FORMAT_PVRTC2: {
- if (!pvr_supported || (!pvr_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!pvr_supported || (!pvr_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
-
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
-
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
case Image::FORMAT_PVRTC2A: {
- if (!pvr_supported || (!pvr_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!pvr_supported || (!pvr_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty())
image.decompress();
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
-
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=_EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
-
+ r_gl_internal_format = _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
case Image::FORMAT_PVRTC4: {
- if (!pvr_supported || (!pvr_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!pvr_supported || (!pvr_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty())
image.decompress();
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
case Image::FORMAT_PVRTC4A: {
- if (!pvr_supported || (!pvr_srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ if (!pvr_supported || (!pvr_srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
if (!image.empty())
image.decompress();
- r_gl_components=4;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 4;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=_GL_SRGB_ALPHA_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = _GL_SRGB_ALPHA_EXT;
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGBA;
+ r_gl_internal_format = GL_RGBA;
}
- r_has_alpha_cache=true;
+ r_has_alpha_cache = true;
} else {
- r_gl_internal_format=(srgb_supported && p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = (srgb_supported && p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
case Image::FORMAT_ETC: {
- if (!etc_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ if (!etc_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (!image.empty()) {
image.decompress();
}
- r_gl_components=3;
- if (p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ r_gl_components = 3;
+ if (p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
if (srgb_supported) {
- r_gl_format=GL_RGB;
- r_gl_internal_format=_GL_SRGB_EXT;
+ r_gl_format = GL_RGB;
+ r_gl_internal_format = _GL_SRGB_EXT;
} else {
- r_gl_internal_format=GL_RGB;
+ r_gl_internal_format = GL_RGB;
if (!image.empty())
image.srgb_to_linear();
}
} else {
- r_gl_internal_format=GL_RGB;
+ r_gl_internal_format = GL_RGB;
}
- r_gl_internal_format=GL_RGB;
-
+ r_gl_internal_format = GL_RGB;
} else {
- r_gl_internal_format=_EXT_ETC1_RGB8_OES;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_ETC1_RGB8_OES;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
@@ -787,15 +756,14 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty()) {
image.decompress();
}
- r_gl_components=3;
- r_gl_internal_format=GL_RGB;
-
+ r_gl_components = 3;
+ r_gl_internal_format = GL_RGB;
} else {
- r_gl_internal_format=_EXT_ATC_RGB_AMD;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_ATC_RGB_AMD;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
@@ -806,15 +774,14 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- r_gl_internal_format=GL_RGBA;
-
+ r_gl_components = 4;
+ r_gl_internal_format = GL_RGBA;
} else {
- r_gl_internal_format=_EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
@@ -825,15 +792,14 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty()) {
image.decompress();
}
- r_gl_components=4;
- r_gl_internal_format=GL_RGBA;
-
+ r_gl_components = 4;
+ r_gl_internal_format = GL_RGBA;
} else {
- r_gl_internal_format=_EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD;
- r_gl_components=1; //doesn't matter much
- r_compressed=true;
+ r_gl_internal_format = _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD;
+ r_gl_components = 1; //doesn't matter much
+ r_compressed = true;
}
} break;
@@ -842,8 +808,8 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
if (!image.empty())
image.convert(Image::FORMAT_RGB8);
- r_gl_internal_format=GL_RGB;
- r_gl_components=3;
+ r_gl_internal_format = GL_RGB;
+ r_gl_components = 3;
} break;
@@ -853,14 +819,14 @@ Image RasterizerGLES2::_get_gl_image_and_format(const Image& p_image, Image::For
}
}
- if (r_gl_format==0) {
- r_gl_format=r_gl_internal_format;
+ if (r_gl_format == 0) {
+ r_gl_format = r_gl_internal_format;
}
return image;
}
-static const GLenum _cube_side_enum[6]={
+static const GLenum _cube_side_enum[6] = {
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
@@ -874,16 +840,15 @@ static const GLenum _cube_side_enum[6]={
RID RasterizerGLES2::texture_create() {
Texture *texture = memnew(Texture);
- ERR_FAIL_COND_V(!texture,RID());
+ ERR_FAIL_COND_V(!texture, RID());
glGenTextures(1, &texture->tex_id);
- texture->active=false;
- texture->total_data_size=0;
-
- return texture_owner.make_rid( texture );
+ texture->active = false;
+ texture->total_data_size = 0;
+ return texture_owner.make_rid(texture);
}
-void RasterizerGLES2::texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags) {
+void RasterizerGLES2::texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags) {
bool has_alpha_cache;
int components;
@@ -891,26 +856,24 @@ void RasterizerGLES2::texture_allocate(RID p_texture,int p_width, int p_height,I
GLenum internal_format;
bool compressed;
- int po2_width = nearest_power_of_2(p_width);
- int po2_height = nearest_power_of_2(p_height);
+ int po2_width = nearest_power_of_2(p_width);
+ int po2_height = nearest_power_of_2(p_height);
- if (p_flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) {
- p_flags&=~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video
+ if (p_flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) {
+ p_flags &= ~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video
}
-
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->width=p_width;
- texture->height=p_height;
- texture->format=p_format;
- texture->flags=p_flags;
+ texture->width = p_width;
+ texture->height = p_height;
+ texture->format = p_format;
+ texture->flags = p_flags;
texture->target = (p_flags & VS::TEXTURE_FLAG_CUBEMAP) ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
- _get_gl_image_and_format(Image(),texture->format,texture->flags,format,internal_format,components,has_alpha_cache,compressed);
-
- bool scale_textures = !compressed && !(p_flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) && (!npo2_textures_available || p_flags&VS::TEXTURE_FLAG_MIPMAPS);
+ _get_gl_image_and_format(Image(), texture->format, texture->flags, format, internal_format, components, has_alpha_cache, compressed);
+ bool scale_textures = !compressed && !(p_flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) && (!npo2_textures_available || p_flags & VS::TEXTURE_FLAG_MIPMAPS);
if (scale_textures) {
texture->alloc_width = po2_width;
@@ -922,45 +885,40 @@ void RasterizerGLES2::texture_allocate(RID p_texture,int p_width, int p_height,I
texture->alloc_height = texture->height;
};
- if (!(p_flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) && shrink_textures_x2) {
- texture->alloc_height = MAX(1,texture->alloc_height/2);
- texture->alloc_width = MAX(1,texture->alloc_width/2);
+ if (!(p_flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) && shrink_textures_x2) {
+ texture->alloc_height = MAX(1, texture->alloc_height / 2);
+ texture->alloc_width = MAX(1, texture->alloc_width / 2);
}
-
- texture->gl_components_cache=components;
- texture->gl_format_cache=format;
- texture->gl_internal_format_cache=internal_format;
- texture->format_has_alpha=has_alpha_cache;
- texture->compressed=compressed;
- texture->has_alpha=false; //by default it doesn't have alpha unless something with alpha is blitteds
- texture->data_size=0;
- texture->mipmaps=0;
-
+ texture->gl_components_cache = components;
+ texture->gl_format_cache = format;
+ texture->gl_internal_format_cache = internal_format;
+ texture->format_has_alpha = has_alpha_cache;
+ texture->compressed = compressed;
+ texture->has_alpha = false; //by default it doesn't have alpha unless something with alpha is blitteds
+ texture->data_size = 0;
+ texture->mipmaps = 0;
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
-
-
-
- if (p_flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) {
+ if (p_flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) {
//prealloc if video
- glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, GL_UNSIGNED_BYTE,NULL);
+ glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, GL_UNSIGNED_BYTE, NULL);
}
- texture->active=true;
+ texture->active = true;
}
-void RasterizerGLES2::texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side) {
+void RasterizerGLES2::texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side) {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(!texture->active);
ERR_FAIL_COND(texture->render_target);
- ERR_FAIL_COND(texture->format != p_image.get_format() );
- ERR_FAIL_COND( p_image.empty() );
+ ERR_FAIL_COND(texture->format != p_image.get_format());
+ ERR_FAIL_COND(p_image.empty());
int components;
GLenum format;
@@ -968,85 +926,77 @@ void RasterizerGLES2::texture_set_data(RID p_texture,const Image& p_image,VS::Cu
bool alpha;
bool compressed;
- if (keep_copies && !(texture->flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) && !(use_reload_hooks && texture->reloader)) {
- texture->image[p_cube_side]=p_image;
+ if (keep_copies && !(texture->flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) && !(use_reload_hooks && texture->reloader)) {
+ texture->image[p_cube_side] = p_image;
}
- Image img = _get_gl_image_and_format(p_image, p_image.get_format(),texture->flags,format,internal_format,components,alpha,compressed);
+ Image img = _get_gl_image_and_format(p_image, p_image.get_format(), texture->flags, format, internal_format, components, alpha, compressed);
if (texture->alloc_width != img.get_width() || texture->alloc_height != img.get_height()) {
-
- if (texture->alloc_width == img.get_width()/2 && texture->alloc_height == img.get_height()/2) {
+ if (texture->alloc_width == img.get_width() / 2 && texture->alloc_height == img.get_height() / 2) {
img.shrink_x2();
} else if (img.get_format() <= Image::FORMAT_INDEXED_ALPHA) {
img.resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR);
-
}
};
-
-
- if (!(texture->flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) && img.detect_alpha()==Image::ALPHA_BLEND) {
- texture->has_alpha=true;
+ if (!(texture->flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) && img.detect_alpha() == Image::ALPHA_BLEND) {
+ texture->has_alpha = true;
}
+ GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_cube_side] : GL_TEXTURE_2D;
-
- GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP)?_cube_side_enum[p_cube_side]:GL_TEXTURE_2D;
-
- texture->data_size=img.get_data().size();
+ texture->data_size = img.get_data().size();
PoolVector<uint8_t>::Read read = img.get_data().read();
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
- texture->ignore_mipmaps = compressed && img.get_mipmaps()==0;
+ texture->ignore_mipmaps = compressed && img.get_mipmaps() == 0;
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps)
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR);
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps)
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
else {
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
-
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
}
- bool force_clamp_to_edge = !(texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) && (nearest_power_of_2(texture->alloc_height)!=texture->alloc_height || nearest_power_of_2(texture->alloc_width)!=texture->alloc_width);
+ bool force_clamp_to_edge = !(texture->flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) && (nearest_power_of_2(texture->alloc_height) != texture->alloc_height || nearest_power_of_2(texture->alloc_width) != texture->alloc_width);
- if (!force_clamp_to_edge && (texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
+ if (!force_clamp_to_edge && (texture->flags & VS::TEXTURE_FLAG_REPEAT || texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
- if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
- }
- else{
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
+ } else {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
if (use_anisotropic_filter) {
- if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropic_level);
} else {
@@ -1054,74 +1004,66 @@ void RasterizerGLES2::texture_set_data(RID p_texture,const Image& p_image,VS::Cu
}
}
- int mipmaps= (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && img.get_mipmaps()>0) ? img.get_mipmaps() +1 : 1;
+ int mipmaps = (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && img.get_mipmaps() > 0) ? img.get_mipmaps() + 1 : 1;
+ int w = img.get_width();
+ int h = img.get_height();
- int w=img.get_width();
- int h=img.get_height();
+ int tsize = 0;
+ for (int i = 0; i < mipmaps; i++) {
- int tsize=0;
- for(int i=0;i<mipmaps;i++) {
-
- int size,ofs;
- img.get_mipmap_offset_and_size(i,ofs,size);
+ int size, ofs;
+ img.get_mipmap_offset_and_size(i, ofs, size);
//print_line("mipmap: "+itos(i)+" size: "+itos(size)+" w: "+itos(mm_w)+", h: "+itos(mm_h));
if (texture->compressed) {
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
- glCompressedTexImage2D( blit_target, i, format,w,h,0,size,&read[ofs] );
+ glCompressedTexImage2D(blit_target, i, format, w, h, 0, size, &read[ofs]);
} else {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- if (texture->flags&VS::TEXTURE_FLAG_VIDEO_SURFACE) {
- glTexSubImage2D( blit_target, i, 0,0,w, h,format,GL_UNSIGNED_BYTE,&read[ofs] );
+ if (texture->flags & VS::TEXTURE_FLAG_VIDEO_SURFACE) {
+ glTexSubImage2D(blit_target, i, 0, 0, w, h, format, GL_UNSIGNED_BYTE, &read[ofs]);
} else {
- glTexImage2D(blit_target, i, internal_format, w, h, 0, format, GL_UNSIGNED_BYTE,&read[ofs]);
+ glTexImage2D(blit_target, i, internal_format, w, h, 0, format, GL_UNSIGNED_BYTE, &read[ofs]);
}
-
}
- tsize+=size;
-
- w = MAX(1,w>>1);
- h = MAX(1,h>>1);
+ tsize += size;
+ w = MAX(1, w >> 1);
+ h = MAX(1, h >> 1);
}
- _rinfo.texture_mem-=texture->total_data_size;
- texture->total_data_size=tsize;
- _rinfo.texture_mem+=texture->total_data_size;
+ _rinfo.texture_mem -= texture->total_data_size;
+ texture->total_data_size = tsize;
+ _rinfo.texture_mem += texture->total_data_size;
//printf("texture: %i x %i - size: %i - total: %i\n",texture->width,texture->height,tsize,_rinfo.texture_mem);
-
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && mipmaps==1 && !texture->ignore_mipmaps) {
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && mipmaps == 1 && !texture->ignore_mipmaps) {
//generate mipmaps if they were requested and the image does not contain them
glGenerateMipmap(texture->target);
}
- texture->mipmaps=mipmaps;
+ texture->mipmaps = mipmaps;
-
-
- if (mipmaps>1) {
+ if (mipmaps > 1) {
//glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mipmaps-1 ); - assumed to have all, always
}
//texture_set_flags(p_texture,texture->flags);
-
-
}
-Image RasterizerGLES2::texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side) const {
+Image RasterizerGLES2::texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,Image());
- ERR_FAIL_COND_V(!texture->active,Image());
- ERR_FAIL_COND_V(texture->data_size==0,Image());
- ERR_FAIL_COND_V(texture->render_target,Image());
+ ERR_FAIL_COND_V(!texture, Image());
+ ERR_FAIL_COND_V(!texture->active, Image());
+ ERR_FAIL_COND_V(texture->data_size == 0, Image());
+ ERR_FAIL_COND_V(texture->render_target, Image());
return texture->image[p_cube_side];
@@ -1275,46 +1217,42 @@ Image RasterizerGLES2::texture_get_data(RID p_texture,VS::CubeMapSide p_cube_sid
#endif
}
-void RasterizerGLES2::texture_set_flags(RID p_texture,uint32_t p_flags) {
+void RasterizerGLES2::texture_set_flags(RID p_texture, uint32_t p_flags) {
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
if (texture->render_target) {
- p_flags&=VS::TEXTURE_FLAG_FILTER;//can change only filter
+ p_flags &= VS::TEXTURE_FLAG_FILTER; //can change only filter
}
- bool had_mipmaps = texture->flags&VS::TEXTURE_FLAG_MIPMAPS;
+ bool had_mipmaps = texture->flags & VS::TEXTURE_FLAG_MIPMAPS;
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
uint32_t cube = texture->flags & VS::TEXTURE_FLAG_CUBEMAP;
- texture->flags=p_flags|cube; // can't remove a cube from being a cube
-
+ texture->flags = p_flags | cube; // can't remove a cube from being a cube
- bool force_clamp_to_edge = !(p_flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) && (nearest_power_of_2(texture->alloc_height)!=texture->alloc_height || nearest_power_of_2(texture->alloc_width)!=texture->alloc_width);
+ bool force_clamp_to_edge = !(p_flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) && (nearest_power_of_2(texture->alloc_height) != texture->alloc_height || nearest_power_of_2(texture->alloc_width) != texture->alloc_width);
- if (!force_clamp_to_edge && (texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
+ if (!force_clamp_to_edge && (texture->flags & VS::TEXTURE_FLAG_REPEAT || texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
- if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
- }
- else {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
+ } else {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
-
if (use_anisotropic_filter) {
- if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropic_level);
} else {
@@ -1322,182 +1260,171 @@ void RasterizerGLES2::texture_set_flags(RID p_texture,uint32_t p_flags) {
}
}
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) {
- if (!had_mipmaps && texture->mipmaps==1) {
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) {
+ if (!had_mipmaps && texture->mipmaps == 1) {
glGenerateMipmap(texture->target);
}
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR);
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
- } else{
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
+ } else {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
-
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
}
}
uint32_t RasterizerGLES2::texture_get_flags(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->flags;
-
}
Image::Format RasterizerGLES2::texture_get_format(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,Image::FORMAT_L8);
+ ERR_FAIL_COND_V(!texture, Image::FORMAT_L8);
return texture->format;
}
uint32_t RasterizerGLES2::texture_get_width(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->width;
}
uint32_t RasterizerGLES2::texture_get_height(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->height;
}
bool RasterizerGLES2::texture_has_alpha(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->has_alpha;
-
}
-void RasterizerGLES2::texture_set_size_override(RID p_texture,int p_width, int p_height) {
+void RasterizerGLES2::texture_set_size_override(RID p_texture, int p_width, int p_height) {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(texture->render_target);
- ERR_FAIL_COND(p_width<=0 || p_width>16384);
- ERR_FAIL_COND(p_height<=0 || p_height>16384);
+ ERR_FAIL_COND(p_width <= 0 || p_width > 16384);
+ ERR_FAIL_COND(p_height <= 0 || p_height > 16384);
//real texture size is in alloc width and height
- texture->width=p_width;
- texture->height=p_height;
-
+ texture->width = p_width;
+ texture->height = p_height;
}
-void RasterizerGLES2::texture_set_reload_hook(RID p_texture,ObjectID p_owner,const StringName& p_function) const {
+void RasterizerGLES2::texture_set_reload_hook(RID p_texture, ObjectID p_owner, const StringName &p_function) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(texture->render_target);
- texture->reloader=p_owner;
- texture->reloader_func=p_function;
+ texture->reloader = p_owner;
+ texture->reloader_func = p_function;
if (use_reload_hooks && p_owner && keep_copies) {
- for(int i=0;i<6;i++)
- texture->image[i]=Image();
+ for (int i = 0; i < 6; i++)
+ texture->image[i] = Image();
}
}
-
GLuint RasterizerGLES2::_texture_get_name(RID p_tex) {
- Texture * texture = texture_owner.get(p_tex);
+ Texture *texture = texture_owner.get(p_tex);
ERR_FAIL_COND_V(!texture, 0);
return texture->tex_id;
};
-void RasterizerGLES2::texture_set_path(RID p_texture,const String& p_path) {
- Texture * texture = texture_owner.get(p_texture);
+void RasterizerGLES2::texture_set_path(RID p_texture, const String &p_path) {
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->path=p_path;
-
+ texture->path = p_path;
}
-String RasterizerGLES2::texture_get_path(RID p_texture) const{
+String RasterizerGLES2::texture_get_path(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,String());
+ Texture *texture = texture_owner.get(p_texture);
+ ERR_FAIL_COND_V(!texture, String());
return texture->path;
}
-void RasterizerGLES2::texture_debug_usage(List<VS::TextureInfo> *r_info){
+void RasterizerGLES2::texture_debug_usage(List<VS::TextureInfo> *r_info) {
List<RID> textures;
texture_owner.get_owned_list(&textures);
- for (List<RID>::Element *E=textures.front();E;E=E->next()) {
+ for (List<RID>::Element *E = textures.front(); E; E = E->next()) {
Texture *t = texture_owner.get(E->get());
if (!t)
continue;
VS::TextureInfo tinfo;
- tinfo.path=t->path;
- tinfo.format=t->format;
- tinfo.size.x=t->alloc_width;
- tinfo.size.y=t->alloc_height;
- tinfo.bytes=t->total_data_size;
+ tinfo.path = t->path;
+ tinfo.format = t->format;
+ tinfo.size.x = t->alloc_width;
+ tinfo.size.y = t->alloc_height;
+ tinfo.bytes = t->total_data_size;
r_info->push_back(tinfo);
}
-
}
void RasterizerGLES2::texture_set_shrink_all_x2_on_set_data(bool p_enable) {
- shrink_textures_x2=p_enable;
+ shrink_textures_x2 = p_enable;
}
/* SHADER API */
RID RasterizerGLES2::shader_create(VS::ShaderMode p_mode) {
- Shader *shader = memnew( Shader );
- shader->mode=p_mode;
+ Shader *shader = memnew(Shader);
+ shader->mode = p_mode;
RID rid = shader_owner.make_rid(shader);
- shader_set_mode(rid,p_mode);
+ shader_set_mode(rid, p_mode);
_shader_make_dirty(shader);
return rid;
-
}
+void RasterizerGLES2::shader_set_mode(RID p_shader, VS::ShaderMode p_mode) {
-
-void RasterizerGLES2::shader_set_mode(RID p_shader,VS::ShaderMode p_mode) {
-
- ERR_FAIL_INDEX(p_mode,3);
- Shader *shader=shader_owner.get(p_shader);
+ ERR_FAIL_INDEX(p_mode, 3);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
- if (shader->custom_code_id && p_mode==shader->mode)
+ if (shader->custom_code_id && p_mode == shader->mode)
return;
-
if (shader->custom_code_id) {
- switch(shader->mode) {
+ switch (shader->mode) {
case VS::SHADER_MATERIAL: {
material_shader.free_custom_shader(shader->custom_code_id);
} break;
@@ -1506,75 +1433,68 @@ void RasterizerGLES2::shader_set_mode(RID p_shader,VS::ShaderMode p_mode) {
} break;
}
- shader->custom_code_id=0;
+ shader->custom_code_id = 0;
}
- shader->mode=p_mode;
+ shader->mode = p_mode;
- switch(shader->mode) {
+ switch (shader->mode) {
case VS::SHADER_MATERIAL: {
- shader->custom_code_id=material_shader.create_custom_shader();
+ shader->custom_code_id = material_shader.create_custom_shader();
} break;
case VS::SHADER_CANVAS_ITEM: {
- shader->custom_code_id=canvas_shader.create_custom_shader();
+ shader->custom_code_id = canvas_shader.create_custom_shader();
} break;
}
_shader_make_dirty(shader);
-
}
VS::ShaderMode RasterizerGLES2::shader_get_mode(RID p_shader) const {
- Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,VS::SHADER_MATERIAL);
+ Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, VS::SHADER_MATERIAL);
return shader->mode;
}
+void RasterizerGLES2::shader_set_code(RID p_shader, const String &p_vertex, const String &p_fragment, const String &p_light, int p_vertex_ofs, int p_fragment_ofs, int p_light_ofs) {
-void RasterizerGLES2::shader_set_code(RID p_shader, const String& p_vertex, const String& p_fragment,const String& p_light,int p_vertex_ofs,int p_fragment_ofs,int p_light_ofs) {
-
-
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
#ifdef DEBUG_ENABLED
- if (shader->vertex_code==p_vertex && shader->fragment_code==p_fragment && shader->light_code==p_light)
+ if (shader->vertex_code == p_vertex && shader->fragment_code == p_fragment && shader->light_code == p_light)
return;
#endif
- shader->fragment_code=p_fragment;
- shader->vertex_code=p_vertex;
- shader->light_code=p_light;
- shader->fragment_line=p_fragment_ofs;
- shader->vertex_line=p_vertex_ofs;
- shader->light_line=p_light_ofs;
+ shader->fragment_code = p_fragment;
+ shader->vertex_code = p_vertex;
+ shader->light_code = p_light;
+ shader->fragment_line = p_fragment_ofs;
+ shader->vertex_line = p_vertex_ofs;
+ shader->light_line = p_light_ofs;
_shader_make_dirty(shader);
-
}
String RasterizerGLES2::shader_get_vertex_code(RID p_shader) const {
- Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,String());
+ Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, String());
return shader->vertex_code;
-
}
String RasterizerGLES2::shader_get_fragment_code(RID p_shader) const {
- Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,String());
+ Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, String());
return shader->fragment_code;
-
}
String RasterizerGLES2::shader_get_light_code(RID p_shader) const {
- Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,String());
+ Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, String());
return shader->light_code;
-
}
-void RasterizerGLES2::_shader_make_dirty(Shader* p_shader) {
+void RasterizerGLES2::_shader_make_dirty(Shader *p_shader) {
if (p_shader->dirty_list.in_list())
return;
@@ -1584,30 +1504,25 @@ void RasterizerGLES2::_shader_make_dirty(Shader* p_shader) {
void RasterizerGLES2::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
-
if (shader->dirty_list.in_list())
_update_shader(shader); // ok should be not anymore dirty
+ Map<int, StringName> order;
- Map<int,StringName> order;
-
+ for (Map<StringName, ShaderLanguage::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
- for(Map<StringName,ShaderLanguage::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) {
-
-
- order[E->get().order]=E->key();
+ order[E->get().order] = E->key();
}
-
- for(Map<int,StringName>::Element *E=order.front();E;E=E->next()) {
+ for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
PropertyInfo pi;
- ShaderLanguage::Uniform &u=shader->uniforms[E->get()];
- pi.name=E->get();
- switch(u.type) {
+ ShaderLanguage::Uniform &u = shader->uniforms[E->get()];
+ pi.name = E->get();
+ switch (u.type) {
case ShaderLanguage::TYPE_VOID:
case ShaderLanguage::TYPE_BOOL:
@@ -1617,55 +1532,52 @@ void RasterizerGLES2::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_
case ShaderLanguage::TYPE_MAT3:
case ShaderLanguage::TYPE_MAT4:
case ShaderLanguage::TYPE_VEC4:
- pi.type=u.default_value.get_type();
+ pi.type = u.default_value.get_type();
break;
case ShaderLanguage::TYPE_TEXTURE:
- pi.type=Variant::_RID;
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string="Texture";
+ pi.type = Variant::_RID;
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = "Texture";
break;
case ShaderLanguage::TYPE_CUBEMAP:
- pi.type=Variant::_RID;
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string="CubeMap";
+ pi.type = Variant::_RID;
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = "CubeMap";
break;
};
p_param_list->push_back(pi);
-
}
-
}
-void RasterizerGLES2::shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture) {
+void RasterizerGLES2::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) {
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
ERR_FAIL_COND(p_texture.is_valid() && !texture_owner.owns(p_texture));
if (p_texture.is_valid())
- shader->default_textures[p_name]=p_texture;
+ shader->default_textures[p_name] = p_texture;
else
shader->default_textures.erase(p_name);
_shader_make_dirty(shader);
-
}
-RID RasterizerGLES2::shader_get_default_texture_param(RID p_shader, const StringName& p_name) const{
- const Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,RID());
+RID RasterizerGLES2::shader_get_default_texture_param(RID p_shader, const StringName &p_name) const {
+ const Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, RID());
- const Map<StringName,RID>::Element *E=shader->default_textures.find(p_name);
+ const Map<StringName, RID>::Element *E = shader->default_textures.find(p_name);
if (!E)
return RID();
return E->get();
}
-Variant RasterizerGLES2::shader_get_default_param(RID p_shader, const StringName& p_name) {
+Variant RasterizerGLES2::shader_get_default_param(RID p_shader, const StringName &p_name) {
- Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,Variant());
+ Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, Variant());
//update shader params if necesary
//make sure the shader is compiled and everything
@@ -1679,13 +1591,11 @@ Variant RasterizerGLES2::shader_get_default_param(RID p_shader, const StringName
return Variant();
}
-
/* COMMON MATERIAL API */
-
RID RasterizerGLES2::material_create() {
- RID material = material_owner.make_rid( memnew( Material ) );
+ RID material = material_owner.make_rid(memnew(Material));
return material;
}
@@ -1693,364 +1603,339 @@ void RasterizerGLES2::material_set_shader(RID p_material, RID p_shader) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- if (material->shader==p_shader)
+ if (material->shader == p_shader)
return;
- material->shader=p_shader;
- material->shader_version=0;
-
+ material->shader = p_shader;
+ material->shader_version = 0;
}
RID RasterizerGLES2::material_get_shader(RID p_material) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,RID());
+ ERR_FAIL_COND_V(!material, RID());
return material->shader;
}
-
-void RasterizerGLES2::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value) {
+void RasterizerGLES2::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- Map<StringName,Material::UniformData>::Element *E=material->shader_params.find(p_param);
+ Map<StringName, Material::UniformData>::Element *E = material->shader_params.find(p_param);
if (E) {
- if (p_value.get_type()==Variant::NIL) {
+ if (p_value.get_type() == Variant::NIL) {
material->shader_params.erase(E);
- material->shader_version=0; //get default!
+ material->shader_version = 0; //get default!
} else {
- E->get().value=p_value;
- E->get().inuse=true;
+ E->get().value = p_value;
+ E->get().inuse = true;
}
} else {
- if (p_value.get_type()==Variant::NIL)
+ if (p_value.get_type() == Variant::NIL)
return;
Material::UniformData ud;
- ud.index=-1;
- ud.value=p_value;
- ud.istexture=p_value.get_type()==Variant::_RID; /// cache it being texture
- ud.inuse=true;
- material->shader_params[p_param]=ud; //may be got at some point, or erased
-
+ ud.index = -1;
+ ud.value = p_value;
+ ud.istexture = p_value.get_type() == Variant::_RID; /// cache it being texture
+ ud.inuse = true;
+ material->shader_params[p_param] = ud; //may be got at some point, or erased
}
}
-Variant RasterizerGLES2::material_get_param(RID p_material, const StringName& p_param) const {
+Variant RasterizerGLES2::material_get_param(RID p_material, const StringName &p_param) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,Variant());
-
+ ERR_FAIL_COND_V(!material, Variant());
if (material->shader.is_valid()) {
//update shader params if necesary
//make sure the shader is compiled and everything
//so the actual parameters can be properly retrieved!
- material->shader_cache=shader_owner.get( material->shader );
+ material->shader_cache = shader_owner.get(material->shader);
if (!material->shader_cache) {
//invalidate
- material->shader=RID();
- material->shader_cache=NULL;
+ material->shader = RID();
+ material->shader_cache = NULL;
} else {
if (material->shader_cache->dirty_list.in_list())
_update_shader(material->shader_cache);
- if (material->shader_cache->valid && material->shader_cache->version!=material->shader_version) {
+ if (material->shader_cache->valid && material->shader_cache->version != material->shader_version) {
//validate
_update_material_shader_params(material);
}
}
}
-
if (material->shader_params.has(p_param) && material->shader_params[p_param].inuse)
return material->shader_params[p_param].value;
else
return Variant();
}
-
-void RasterizerGLES2::material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled) {
+void RasterizerGLES2::material_set_flag(RID p_material, VS::MaterialFlag p_flag, bool p_enabled) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- ERR_FAIL_INDEX(p_flag,VS::MATERIAL_FLAG_MAX);
-
- material->flags[p_flag]=p_enabled;
+ ERR_FAIL_INDEX(p_flag, VS::MATERIAL_FLAG_MAX);
+ material->flags[p_flag] = p_enabled;
}
-bool RasterizerGLES2::material_get_flag(RID p_material,VS::MaterialFlag p_flag) const {
+bool RasterizerGLES2::material_get_flag(RID p_material, VS::MaterialFlag p_flag) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,false);
- ERR_FAIL_INDEX_V(p_flag,VS::MATERIAL_FLAG_MAX,false);
+ ERR_FAIL_COND_V(!material, false);
+ ERR_FAIL_INDEX_V(p_flag, VS::MATERIAL_FLAG_MAX, false);
return material->flags[p_flag];
-
-
}
void RasterizerGLES2::material_set_depth_draw_mode(RID p_material, VS::MaterialDepthDrawMode p_mode) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- material->depth_draw_mode=p_mode;
-
+ material->depth_draw_mode = p_mode;
}
VS::MaterialDepthDrawMode RasterizerGLES2::material_get_depth_draw_mode(RID p_material) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,VS::MATERIAL_DEPTH_DRAW_ALWAYS);
+ ERR_FAIL_COND_V(!material, VS::MATERIAL_DEPTH_DRAW_ALWAYS);
return material->depth_draw_mode;
-
}
-
-
-void RasterizerGLES2::material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode) {
+void RasterizerGLES2::material_set_blend_mode(RID p_material, VS::MaterialBlendMode p_mode) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- material->blend_mode=p_mode;
-
+ material->blend_mode = p_mode;
}
VS::MaterialBlendMode RasterizerGLES2::material_get_blend_mode(RID p_material) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,VS::MATERIAL_BLEND_MODE_ADD);
+ ERR_FAIL_COND_V(!material, VS::MATERIAL_BLEND_MODE_ADD);
return material->blend_mode;
}
-void RasterizerGLES2::material_set_line_width(RID p_material,float p_line_width) {
+void RasterizerGLES2::material_set_line_width(RID p_material, float p_line_width) {
Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- material->line_width=p_line_width;
-
+ material->line_width = p_line_width;
}
float RasterizerGLES2::material_get_line_width(RID p_material) const {
Material *material = material_owner.get(p_material);
- ERR_FAIL_COND_V(!material,0);
+ ERR_FAIL_COND_V(!material, 0);
return material->line_width;
}
-
-
/* MESH API */
RID RasterizerGLES2::mesh_create() {
-
- return mesh_owner.make_rid( memnew( Mesh ) );
+ return mesh_owner.make_rid(memnew(Mesh));
}
+void RasterizerGLES2::mesh_add_surface(RID p_mesh, VS::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, bool p_alpha_sort) {
-
-void RasterizerGLES2::mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,bool p_alpha_sort) {
-
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX );
- ERR_FAIL_COND(p_arrays.size()!=VS::ARRAY_MAX);
+ ERR_FAIL_INDEX(p_primitive, VS::PRIMITIVE_MAX);
+ ERR_FAIL_COND(p_arrays.size() != VS::ARRAY_MAX);
- uint32_t format=0;
+ uint32_t format = 0;
// validation
- int index_array_len=0;
- int array_len=0;
+ int index_array_len = 0;
+ int array_len = 0;
- for(int i=0;i<p_arrays.size();i++) {
+ for (int i = 0; i < p_arrays.size(); i++) {
- if (p_arrays[i].get_type()==Variant::NIL)
+ if (p_arrays[i].get_type() == Variant::NIL)
continue;
- format|=(1<<i);
+ format |= (1 << i);
- if (i==VS::ARRAY_VERTEX) {
+ if (i == VS::ARRAY_VERTEX) {
- array_len=Vector3Array(p_arrays[i]).size();
- ERR_FAIL_COND(array_len==0);
- } else if (i==VS::ARRAY_INDEX) {
+ array_len = Vector3Array(p_arrays[i]).size();
+ ERR_FAIL_COND(array_len == 0);
+ } else if (i == VS::ARRAY_INDEX) {
- index_array_len=IntArray(p_arrays[i]).size();
+ index_array_len = IntArray(p_arrays[i]).size();
}
}
- ERR_FAIL_COND((format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory
+ ERR_FAIL_COND((format & VS::ARRAY_FORMAT_VERTEX) == 0); // mandatory
- ERR_FAIL_COND( mesh->morph_target_count!=p_blend_shapes.size() );
+ ERR_FAIL_COND(mesh->morph_target_count != p_blend_shapes.size());
if (mesh->morph_target_count) {
//validate format for morphs
- for(int i=0;i<p_blend_shapes.size();i++) {
+ for (int i = 0; i < p_blend_shapes.size(); i++) {
- uint32_t bsformat=0;
+ uint32_t bsformat = 0;
Array arr = p_blend_shapes[i];
- for(int j=0;j<arr.size();j++) {
-
+ for (int j = 0; j < arr.size(); j++) {
- if (arr[j].get_type()!=Variant::NIL)
- bsformat|=(1<<j);
+ if (arr[j].get_type() != Variant::NIL)
+ bsformat |= (1 << j);
}
- ERR_FAIL_COND( (bsformat)!=(format&(VS::ARRAY_FORMAT_BONES-1)));
+ ERR_FAIL_COND((bsformat) != (format & (VS::ARRAY_FORMAT_BONES - 1)));
}
}
- Surface *surface = memnew( Surface );
- ERR_FAIL_COND( !surface );
+ Surface *surface = memnew(Surface);
+ ERR_FAIL_COND(!surface);
- bool use_VBO=true; //glGenBuffersARB!=NULL; // TODO detect if it's in there
- if ((!use_hw_skeleton_xform && format&VS::ARRAY_FORMAT_WEIGHTS) || mesh->morph_target_count>0) {
+ bool use_VBO = true; //glGenBuffersARB!=NULL; // TODO detect if it's in there
+ if ((!use_hw_skeleton_xform && format & VS::ARRAY_FORMAT_WEIGHTS) || mesh->morph_target_count > 0) {
- use_VBO=false;
+ use_VBO = false;
}
//surface->packed=pack_arrays && use_VBO;
- int total_elem_size=0;
+ int total_elem_size = 0;
- for (int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
-
- Surface::ArrayData&ad=surface->array[i];
- ad.size=0;
- ad.ofs=0;
- int elem_size=0;
- int elem_count=0;
- bool valid_local=true;
+ Surface::ArrayData &ad = surface->array[i];
+ ad.size = 0;
+ ad.ofs = 0;
+ int elem_size = 0;
+ int elem_count = 0;
+ bool valid_local = true;
GLenum datatype;
- bool normalize=false;
- bool bind=false;
+ bool normalize = false;
+ bool bind = false;
- if (!(format&(1<<i))) // no array
+ if (!(format & (1 << i))) // no array
continue;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
if (use_VBO && use_half_float) {
- elem_size=3*sizeof(int16_t); // vertex
- datatype=_GL_HALF_FLOAT_OES;
+ elem_size = 3 * sizeof(int16_t); // vertex
+ datatype = _GL_HALF_FLOAT_OES;
} else {
- elem_size=3*sizeof(GLfloat); // vertex
- datatype=GL_FLOAT;
+ elem_size = 3 * sizeof(GLfloat); // vertex
+ datatype = GL_FLOAT;
}
- bind=true;
- elem_count=3;
+ bind = true;
+ elem_count = 3;
} break;
case VS::ARRAY_NORMAL: {
if (use_VBO) {
- elem_size=4*sizeof(int8_t); // vertex
- datatype=GL_BYTE;
- normalize=true;
+ elem_size = 4 * sizeof(int8_t); // vertex
+ datatype = GL_BYTE;
+ normalize = true;
} else {
- elem_size=3*sizeof(GLfloat); // vertex
- datatype=GL_FLOAT;
+ elem_size = 3 * sizeof(GLfloat); // vertex
+ datatype = GL_FLOAT;
}
- bind=true;
- elem_count=3;
+ bind = true;
+ elem_count = 3;
} break;
case VS::ARRAY_TANGENT: {
if (use_VBO) {
- elem_size=4*sizeof(int8_t); // vertex
- datatype=GL_BYTE;
- normalize=true;
+ elem_size = 4 * sizeof(int8_t); // vertex
+ datatype = GL_BYTE;
+ normalize = true;
} else {
- elem_size=4*sizeof(GLfloat); // vertex
- datatype=GL_FLOAT;
+ elem_size = 4 * sizeof(GLfloat); // vertex
+ datatype = GL_FLOAT;
}
- bind=true;
- elem_count=4;
+ bind = true;
+ elem_count = 4;
} break;
case VS::ARRAY_COLOR: {
- elem_size=4*sizeof(uint8_t); /* RGBA */
- datatype=GL_UNSIGNED_BYTE;
- elem_count=4;
- bind=true;
- normalize=true;
+ elem_size = 4 * sizeof(uint8_t); /* RGBA */
+ datatype = GL_UNSIGNED_BYTE;
+ elem_count = 4;
+ bind = true;
+ normalize = true;
} break;
case VS::ARRAY_TEX_UV:
case VS::ARRAY_TEX_UV2: {
if (use_VBO && use_half_float) {
- elem_size=2*sizeof(int16_t); // vertex
- datatype=_GL_HALF_FLOAT_OES;
+ elem_size = 2 * sizeof(int16_t); // vertex
+ datatype = _GL_HALF_FLOAT_OES;
} else {
- elem_size=2*sizeof(GLfloat); // vertex
- datatype=GL_FLOAT;
+ elem_size = 2 * sizeof(GLfloat); // vertex
+ datatype = GL_FLOAT;
}
- bind=true;
- elem_count=2;
+ bind = true;
+ elem_count = 2;
} break;
case VS::ARRAY_WEIGHTS: {
if (use_VBO) {
- elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLushort);
- valid_local=false;
- bind=true;
- normalize=true;
- datatype=GL_UNSIGNED_SHORT;
- elem_count=4;
+ elem_size = VS::ARRAY_WEIGHTS_SIZE * sizeof(GLushort);
+ valid_local = false;
+ bind = true;
+ normalize = true;
+ datatype = GL_UNSIGNED_SHORT;
+ elem_count = 4;
} else {
- elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLfloat);
- valid_local=false;
- bind=false;
- datatype=GL_FLOAT;
- elem_count=4;
+ elem_size = VS::ARRAY_WEIGHTS_SIZE * sizeof(GLfloat);
+ valid_local = false;
+ bind = false;
+ datatype = GL_FLOAT;
+ elem_count = 4;
}
} break;
case VS::ARRAY_BONES: {
if (use_VBO) {
- elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLubyte);
- valid_local=false;
- bind=true;
- datatype=GL_UNSIGNED_BYTE;
- elem_count=4;
+ elem_size = VS::ARRAY_WEIGHTS_SIZE * sizeof(GLubyte);
+ valid_local = false;
+ bind = true;
+ datatype = GL_UNSIGNED_BYTE;
+ elem_count = 4;
} else {
- elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLushort);
- valid_local=false;
- bind=false;
- datatype=GL_UNSIGNED_SHORT;
- elem_count=4;
-
+ elem_size = VS::ARRAY_WEIGHTS_SIZE * sizeof(GLushort);
+ valid_local = false;
+ bind = false;
+ datatype = GL_UNSIGNED_SHORT;
+ elem_count = 4;
}
-
} break;
case VS::ARRAY_INDEX: {
- if (index_array_len<=0) {
+ if (index_array_len <= 0) {
ERR_PRINT("index_array_len==NO_INDEX_ARRAY");
break;
}
/* determine wether using 16 or 32 bits indices */
- if (array_len>(1<<16)) {
+ if (array_len > (1 << 16)) {
- elem_size=4;
- datatype=GL_UNSIGNED_INT;
+ elem_size = 4;
+ datatype = GL_UNSIGNED_INT;
} else {
- elem_size=2;
- datatype=GL_UNSIGNED_SHORT;
+ elem_size = 2;
+ datatype = GL_UNSIGNED_SHORT;
}
-/*
+ /*
if (use_VBO) {
glGenBuffers(1,&surface->index_id);
@@ -2062,47 +1947,44 @@ void RasterizerGLES2::mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,
surface->index_array_local = (uint8_t*)memalloc(index_array_len*elem_size);
};
*/
- surface->index_array_len=index_array_len; // only way it can exist
- ad.ofs=0;
- ad.size=elem_size;
-
+ surface->index_array_len = index_array_len; // only way it can exist
+ ad.ofs = 0;
+ ad.size = elem_size;
continue;
} break;
default: {
- ERR_FAIL( );
+ ERR_FAIL();
}
}
- ad.ofs=total_elem_size;
- ad.size=elem_size;
- ad.datatype=datatype;
- ad.normalize=normalize;
- ad.bind=bind;
- ad.count=elem_count;
- total_elem_size+=elem_size;
+ ad.ofs = total_elem_size;
+ ad.size = elem_size;
+ ad.datatype = datatype;
+ ad.normalize = normalize;
+ ad.bind = bind;
+ ad.count = elem_count;
+ total_elem_size += elem_size;
if (valid_local) {
- surface->local_stride+=elem_size;
- surface->morph_format|=(1<<i);
+ surface->local_stride += elem_size;
+ surface->morph_format |= (1 << i);
}
-
-
}
- surface->stride=total_elem_size;
- surface->array_len=array_len;
- surface->format=format;
- surface->primitive=p_primitive;
- surface->morph_target_count=mesh->morph_target_count;
- surface->configured_format=0;
- surface->mesh=mesh;
+ surface->stride = total_elem_size;
+ surface->array_len = array_len;
+ surface->format = format;
+ surface->primitive = p_primitive;
+ surface->morph_target_count = mesh->morph_target_count;
+ surface->configured_format = 0;
+ surface->mesh = mesh;
if (keep_copies) {
- surface->data=p_arrays;
- surface->morph_data=p_blend_shapes;
+ surface->data = p_arrays;
+ surface->morph_data = p_blend_shapes;
}
- uint8_t *array_ptr=NULL;
- uint8_t *index_array_ptr=NULL;
+ uint8_t *array_ptr = NULL;
+ uint8_t *index_array_ptr = NULL;
PoolVector<uint8_t> array_pre_vbo;
PoolVector<uint8_t>::Write vaw;
PoolVector<uint8_t> index_array_pre_vbo;
@@ -2111,489 +1993,443 @@ void RasterizerGLES2::mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,
/* create pointers */
if (use_VBO) {
- array_pre_vbo.resize(surface->array_len*surface->stride);
+ array_pre_vbo.resize(surface->array_len * surface->stride);
vaw = array_pre_vbo.write();
- array_ptr=vaw.ptr();
+ array_ptr = vaw.ptr();
if (surface->index_array_len) {
- index_array_pre_vbo.resize(surface->index_array_len*surface->array[VS::ARRAY_INDEX].size);
+ index_array_pre_vbo.resize(surface->index_array_len * surface->array[VS::ARRAY_INDEX].size);
iaw = index_array_pre_vbo.write();
- index_array_ptr=iaw.ptr();
+ index_array_ptr = iaw.ptr();
}
- _surface_set_arrays(surface,array_ptr,index_array_ptr,p_arrays,true);
+ _surface_set_arrays(surface, array_ptr, index_array_ptr, p_arrays, true);
} else {
- surface->array_local = (uint8_t*)memalloc(surface->array_len*surface->stride);
- array_ptr=(uint8_t*)surface->array_local;
+ surface->array_local = (uint8_t *)memalloc(surface->array_len * surface->stride);
+ array_ptr = (uint8_t *)surface->array_local;
if (surface->index_array_len) {
- surface->index_array_local = (uint8_t*)memalloc(index_array_len*surface->array[VS::ARRAY_INDEX].size);
- index_array_ptr=(uint8_t*)surface->index_array_local;
+ surface->index_array_local = (uint8_t *)memalloc(index_array_len * surface->array[VS::ARRAY_INDEX].size);
+ index_array_ptr = (uint8_t *)surface->index_array_local;
}
- _surface_set_arrays(surface,array_ptr,index_array_ptr,p_arrays,true);
+ _surface_set_arrays(surface, array_ptr, index_array_ptr, p_arrays, true);
if (mesh->morph_target_count) {
- surface->morph_targets_local = memnew_arr(Surface::MorphTarget,mesh->morph_target_count);
- for(int i=0;i<mesh->morph_target_count;i++) {
+ surface->morph_targets_local = memnew_arr(Surface::MorphTarget, mesh->morph_target_count);
+ for (int i = 0; i < mesh->morph_target_count; i++) {
- surface->morph_targets_local[i].array=memnew_arr(uint8_t,surface->local_stride*surface->array_len);
- surface->morph_targets_local[i].configured_format=surface->morph_format;
- _surface_set_arrays(surface,surface->morph_targets_local[i].array,NULL,p_blend_shapes[i],false);
+ surface->morph_targets_local[i].array = memnew_arr(uint8_t, surface->local_stride * surface->array_len);
+ surface->morph_targets_local[i].configured_format = surface->morph_format;
+ _surface_set_arrays(surface, surface->morph_targets_local[i].array, NULL, p_blend_shapes[i], false);
}
}
}
-
-
-
-
/* create buffers!! */
if (use_VBO) {
- glGenBuffers(1,&surface->vertex_id);
- ERR_FAIL_COND(surface->vertex_id==0);
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
- glBufferData(GL_ARRAY_BUFFER,surface->array_len*surface->stride,array_ptr,GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &surface->vertex_id);
+ ERR_FAIL_COND(surface->vertex_id == 0);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, surface->array_len * surface->stride, array_ptr, GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
if (surface->index_array_len) {
- glGenBuffers(1,&surface->index_id);
- ERR_FAIL_COND(surface->index_id==0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,index_array_len*surface->array[VS::ARRAY_INDEX].size,index_array_ptr,GL_STATIC_DRAW);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
-
+ glGenBuffers(1, &surface->index_id);
+ ERR_FAIL_COND(surface->index_id == 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_array_len * surface->array[VS::ARRAY_INDEX].size, index_array_ptr, GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
}
}
mesh->surfaces.push_back(surface);
-
}
-Error RasterizerGLES2::_surface_set_arrays(Surface *p_surface, uint8_t *p_mem,uint8_t *p_index_mem,const Array& p_arrays,bool p_main) {
+Error RasterizerGLES2::_surface_set_arrays(Surface *p_surface, uint8_t *p_mem, uint8_t *p_index_mem, const Array &p_arrays, bool p_main) {
uint32_t stride = p_main ? p_surface->stride : p_surface->local_stride;
- for(int ai=0;ai<VS::ARRAY_MAX;ai++) {
- if (ai>=p_arrays.size())
+ for (int ai = 0; ai < VS::ARRAY_MAX; ai++) {
+ if (ai >= p_arrays.size())
break;
- if (p_arrays[ai].get_type()==Variant::NIL)
+ if (p_arrays[ai].get_type() == Variant::NIL)
continue;
- Surface::ArrayData &a=p_surface->array[ai];
-
- switch(ai) {
+ Surface::ArrayData &a = p_surface->array[ai];
+ switch (ai) {
case VS::ARRAY_VERTEX: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector3> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector3>::Read read = array.read();
- const Vector3* src=read.ptr();
+ const Vector3 *src = read.ptr();
// setting vertices means regenerating the AABB
AABB aabb;
- float scale=1;
-
-
- if (p_surface->array[VS::ARRAY_VERTEX].datatype==_GL_HALF_FLOAT_OES) {
+ float scale = 1;
- for (int i=0;i<p_surface->array_len;i++) {
+ if (p_surface->array[VS::ARRAY_VERTEX].datatype == _GL_HALF_FLOAT_OES) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- uint16_t vector[3]={ make_half_float(src[i].x), make_half_float(src[i].y), make_half_float(src[i].z) };
+ uint16_t vector[3] = { make_half_float(src[i].x), make_half_float(src[i].y), make_half_float(src[i].z) };
- copymem(&p_mem[a.ofs+i*stride], vector, a.size);
+ copymem(&p_mem[a.ofs + i * stride], vector, a.size);
- if (i==0) {
+ if (i == 0) {
- aabb=AABB(src[i],Vector3());
+ aabb = AABB(src[i], Vector3());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
-
} else {
- for (int i=0;i<p_surface->array_len;i++) {
-
+ for (int i = 0; i < p_surface->array_len; i++) {
- GLfloat vector[3]={ src[i].x, src[i].y, src[i].z };
+ GLfloat vector[3] = { src[i].x, src[i].y, src[i].z };
- copymem(&p_mem[a.ofs+i*stride], vector, a.size);
+ copymem(&p_mem[a.ofs + i * stride], vector, a.size);
- if (i==0) {
+ if (i == 0) {
- aabb=AABB(src[i],Vector3());
+ aabb = AABB(src[i], Vector3());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
}
if (p_main) {
- p_surface->aabb=aabb;
- p_surface->vertex_scale=scale;
+ p_surface->aabb = aabb;
+ p_surface->vertex_scale = scale;
}
-
} break;
case VS::ARRAY_NORMAL: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector3> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector3>::Read read = array.read();
- const Vector3* src=read.ptr();
+ const Vector3 *src = read.ptr();
// setting vertices means regenerating the AABB
- if (p_surface->array[VS::ARRAY_NORMAL].datatype==GL_BYTE) {
+ if (p_surface->array[VS::ARRAY_NORMAL].datatype == GL_BYTE) {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- GLbyte vector[4]={
- CLAMP(src[i].x*127,-128,127),
- CLAMP(src[i].y*127,-128,127),
- CLAMP(src[i].z*127,-128,127),
+ GLbyte vector[4] = {
+ CLAMP(src[i].x * 127, -128, 127),
+ CLAMP(src[i].y * 127, -128, 127),
+ CLAMP(src[i].z * 127, -128, 127),
0,
};
- copymem(&p_mem[a.ofs+i*stride], vector, a.size);
-
+ copymem(&p_mem[a.ofs + i * stride], vector, a.size);
}
} else {
- for (int i=0;i<p_surface->array_len;i++) {
-
-
- GLfloat vector[3]={ src[i].x, src[i].y, src[i].z };
- copymem(&p_mem[a.ofs+i*stride], vector, a.size);
+ for (int i = 0; i < p_surface->array_len; i++) {
+ GLfloat vector[3] = { src[i].x, src[i].y, src[i].z };
+ copymem(&p_mem[a.ofs + i * stride], vector, a.size);
}
}
-
} break;
case VS::ARRAY_TANGENT: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len*4, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len * 4, ERR_INVALID_PARAMETER);
PoolVector<real_t>::Read read = array.read();
- const real_t* src = read.ptr();
+ const real_t *src = read.ptr();
- if (p_surface->array[VS::ARRAY_TANGENT].datatype==GL_BYTE) {
+ if (p_surface->array[VS::ARRAY_TANGENT].datatype == GL_BYTE) {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- GLbyte xyzw[4]={
- CLAMP(src[i*4+0]*127,-128,127),
- CLAMP(src[i*4+1]*127,-128,127),
- CLAMP(src[i*4+2]*127,-128,127),
- CLAMP(src[i*4+3]*127,-128,127)
+ GLbyte xyzw[4] = {
+ CLAMP(src[i * 4 + 0] * 127, -128, 127),
+ CLAMP(src[i * 4 + 1] * 127, -128, 127),
+ CLAMP(src[i * 4 + 2] * 127, -128, 127),
+ CLAMP(src[i * 4 + 3] * 127, -128, 127)
};
- copymem(&p_mem[a.ofs+i*stride], xyzw, a.size);
-
+ copymem(&p_mem[a.ofs + i * stride], xyzw, a.size);
}
-
} else {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- GLfloat xyzw[4]={
- src[i*4+0],
- src[i*4+1],
- src[i*4+2],
- src[i*4+3]
+ GLfloat xyzw[4] = {
+ src[i * 4 + 0],
+ src[i * 4 + 1],
+ src[i * 4 + 2],
+ src[i * 4 + 3]
};
- copymem(&p_mem[a.ofs+i*stride], xyzw, a.size);
-
+ copymem(&p_mem[a.ofs + i * stride], xyzw, a.size);
}
}
} break;
case VS::ARRAY_COLOR: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::COLOR_ARRAY, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::COLOR_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Color> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len, ERR_INVALID_PARAMETER);
PoolVector<Color>::Read read = array.read();
- const Color* src = read.ptr();
- bool alpha=false;
+ const Color *src = read.ptr();
+ bool alpha = false;
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- if (src[i].a<0.98) // tolerate alpha a bit, for crappy exporters
- alpha=true;
+ if (src[i].a < 0.98) // tolerate alpha a bit, for crappy exporters
+ alpha = true;
uint8_t colors[4];
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- colors[j]=CLAMP( int((src[i][j])*255.0), 0,255 );
+ colors[j] = CLAMP(int((src[i][j]) * 255.0), 0, 255);
}
- copymem(&p_mem[a.ofs+i*stride], colors, a.size);
-
+ copymem(&p_mem[a.ofs + i * stride], colors, a.size);
}
if (p_main)
- p_surface->has_alpha=alpha;
+ p_surface->has_alpha = alpha;
} break;
case VS::ARRAY_TEX_UV:
case VS::ARRAY_TEX_UV2: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::VECTOR2_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::VECTOR2_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector2> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len , ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector2>::Read read = array.read();
- const Vector2 * src=read.ptr();
- float scale=1.0;
-
+ const Vector2 *src = read.ptr();
+ float scale = 1.0;
- if (p_surface->array[ai].datatype==_GL_HALF_FLOAT_OES) {
+ if (p_surface->array[ai].datatype == _GL_HALF_FLOAT_OES) {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- uint16_t uv[2]={ make_half_float(src[i].x) , make_half_float(src[i].y) };
- copymem(&p_mem[a.ofs+i*stride], uv, a.size);
+ uint16_t uv[2] = { make_half_float(src[i].x), make_half_float(src[i].y) };
+ copymem(&p_mem[a.ofs + i * stride], uv, a.size);
}
} else {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
- GLfloat uv[2]={ src[i].x , src[i].y };
-
- copymem(&p_mem[a.ofs+i*stride], uv, a.size);
+ GLfloat uv[2] = { src[i].x, src[i].y };
+ copymem(&p_mem[a.ofs + i * stride], uv, a.size);
}
}
if (p_main) {
- if (ai==VS::ARRAY_TEX_UV) {
+ if (ai == VS::ARRAY_TEX_UV) {
- p_surface->uv_scale=scale;
+ p_surface->uv_scale = scale;
}
- if (ai==VS::ARRAY_TEX_UV2) {
+ if (ai == VS::ARRAY_TEX_UV2) {
- p_surface->uv2_scale=scale;
+ p_surface->uv2_scale = scale;
}
}
} break;
case VS::ARRAY_WEIGHTS: {
-
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER);
PoolVector<real_t>::Read read = array.read();
- const real_t * src = read.ptr();
+ const real_t *src = read.ptr();
- if (p_surface->array[VS::ARRAY_WEIGHTS].datatype==GL_UNSIGNED_SHORT) {
+ if (p_surface->array[VS::ARRAY_WEIGHTS].datatype == GL_UNSIGNED_SHORT) {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
GLushort data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j]*65535,0,65535);
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j] * 65535, 0, 65535);
}
- copymem(&p_mem[a.ofs+i*stride], data, a.size);
+ copymem(&p_mem[a.ofs + i * stride], data, a.size);
}
} else {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
GLfloat data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j];
}
- copymem(&p_mem[a.ofs+i*stride], data, a.size);
-
-
+ copymem(&p_mem[a.ofs + i * stride], data, a.size);
}
-
-
}
} break;
case VS::ARRAY_BONES: {
-
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<int> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_surface->array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_surface->array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER);
PoolVector<int>::Read read = array.read();
- const int * src = read.ptr();
+ const int *src = read.ptr();
- p_surface->max_bone=0;
+ p_surface->max_bone = 0;
+ if (p_surface->array[VS::ARRAY_BONES].datatype == GL_UNSIGNED_BYTE) {
- if (p_surface->array[VS::ARRAY_BONES].datatype==GL_UNSIGNED_BYTE) {
-
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
GLubyte data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j],0,255);
- p_surface->max_bone=MAX(data[j],p_surface->max_bone);
-
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j], 0, 255);
+ p_surface->max_bone = MAX(data[j], p_surface->max_bone);
}
- copymem(&p_mem[a.ofs+i*stride], data, a.size);
-
-
+ copymem(&p_mem[a.ofs + i * stride], data, a.size);
}
} else {
- for (int i=0;i<p_surface->array_len;i++) {
+ for (int i = 0; i < p_surface->array_len; i++) {
GLushort data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
- p_surface->max_bone=MAX(data[j],p_surface->max_bone);
-
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j];
+ p_surface->max_bone = MAX(data[j], p_surface->max_bone);
}
- copymem(&p_mem[a.ofs+i*stride], data, a.size);
-
-
+ copymem(&p_mem[a.ofs + i * stride], data, a.size);
}
}
-
} break;
case VS::ARRAY_INDEX: {
- ERR_FAIL_COND_V( p_surface->index_array_len<=0, ERR_INVALID_DATA );
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::INT_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_surface->index_array_len <= 0, ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::INT_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<int> indices = p_arrays[ai];
- ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER );
- ERR_FAIL_COND_V( indices.size() != p_surface->index_array_len, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(indices.size() == 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(indices.size() != p_surface->index_array_len, ERR_INVALID_PARAMETER);
/* determine wether using 16 or 32 bits indices */
PoolVector<int>::Read read = indices.read();
- const int *src=read.ptr();
-
- for (int i=0;i<p_surface->index_array_len;i++) {
+ const int *src = read.ptr();
+ for (int i = 0; i < p_surface->index_array_len; i++) {
- if (a.size==2) {
- uint16_t v=src[i];
+ if (a.size == 2) {
+ uint16_t v = src[i];
- copymem(&p_index_mem[i*a.size], &v, a.size);
+ copymem(&p_index_mem[i * a.size], &v, a.size);
} else {
- uint32_t v=src[i];
+ uint32_t v = src[i];
- copymem(&p_index_mem[i*a.size], &v, a.size);
+ copymem(&p_index_mem[i * a.size], &v, a.size);
}
}
-
} break;
-
- default: { ERR_FAIL_V(ERR_INVALID_PARAMETER);}
+ default: { ERR_FAIL_V(ERR_INVALID_PARAMETER); }
}
- p_surface->configured_format|=(1<<ai);
+ p_surface->configured_format |= (1 << ai);
}
- if (p_surface->format&VS::ARRAY_FORMAT_BONES) {
+ if (p_surface->format & VS::ARRAY_FORMAT_BONES) {
//create AABBs for each detected bone
- int total_bones = p_surface->max_bone+1;
+ int total_bones = p_surface->max_bone + 1;
if (p_main) {
p_surface->skeleton_bone_aabb.resize(total_bones);
p_surface->skeleton_bone_used.resize(total_bones);
- for(int i=0;i<total_bones;i++)
- p_surface->skeleton_bone_used[i]=false;
+ for (int i = 0; i < total_bones; i++)
+ p_surface->skeleton_bone_used[i] = false;
}
PoolVector<Vector3> vertices = p_arrays[VS::ARRAY_VERTEX];
PoolVector<int> bones = p_arrays[VS::ARRAY_BONES];
PoolVector<float> weights = p_arrays[VS::ARRAY_WEIGHTS];
- bool any_valid=false;
+ bool any_valid = false;
- if (vertices.size() && bones.size()==vertices.size()*4 && weights.size()==bones.size()) {
+ if (vertices.size() && bones.size() == vertices.size() * 4 && weights.size() == bones.size()) {
//print_line("MAKING SKELETHONG");
int vs = vertices.size();
- PoolVector<Vector3>::Read rv =vertices.read();
- PoolVector<int>::Read rb=bones.read();
- PoolVector<float>::Read rw=weights.read();
+ PoolVector<Vector3>::Read rv = vertices.read();
+ PoolVector<int>::Read rb = bones.read();
+ PoolVector<float>::Read rw = weights.read();
Vector<bool> first;
first.resize(total_bones);
- for(int i=0;i<total_bones;i++) {
- first[i]=p_main;
+ for (int i = 0; i < total_bones; i++) {
+ first[i] = p_main;
}
AABB *bptr = p_surface->skeleton_bone_aabb.ptr();
- bool *fptr=first.ptr();
- bool *usedptr=p_surface->skeleton_bone_used.ptr();
+ bool *fptr = first.ptr();
+ bool *usedptr = p_surface->skeleton_bone_used.ptr();
- for(int i=0;i<vs;i++) {
+ for (int i = 0; i < vs; i++) {
Vector3 v = rv[i];
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- int idx = rb[i*4+j];
- float w = rw[i*4+j];
- if (w==0)
- continue;//break;
- ERR_FAIL_INDEX_V(idx,total_bones,ERR_INVALID_DATA);
+ int idx = rb[i * 4 + j];
+ float w = rw[i * 4 + j];
+ if (w == 0)
+ continue; //break;
+ ERR_FAIL_INDEX_V(idx, total_bones, ERR_INVALID_DATA);
if (fptr[idx]) {
- bptr[idx].pos=v;
- fptr[idx]=false;
- any_valid=true;
+ bptr[idx].pos = v;
+ fptr[idx] = false;
+ any_valid = true;
} else {
bptr[idx].expand_to(v);
}
- usedptr[idx]=true;
+ usedptr[idx] = true;
}
}
}
@@ -2608,218 +2444,202 @@ Error RasterizerGLES2::_surface_set_arrays(Surface *p_surface, uint8_t *p_mem,ui
return OK;
}
-
-
-void RasterizerGLES2::mesh_add_custom_surface(RID p_mesh,const Variant& p_dat) {
+void RasterizerGLES2::mesh_add_custom_surface(RID p_mesh, const Variant &p_dat) {
ERR_EXPLAIN("OpenGL Rasterizer does not support custom surfaces. Running on wrong platform?");
ERR_FAIL();
}
-Array RasterizerGLES2::mesh_get_surface_arrays(RID p_mesh,int p_surface) const {
+Array RasterizerGLES2::mesh_get_surface_arrays(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,Array());
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Array() );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, Array());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Array());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, Array() );
+ ERR_FAIL_COND_V(!surface, Array());
return surface->data;
-
-
}
-Array RasterizerGLES2::mesh_get_surface_morph_arrays(RID p_mesh,int p_surface) const{
+Array RasterizerGLES2::mesh_get_surface_morph_arrays(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,Array());
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Array() );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, Array());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Array());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, Array() );
+ ERR_FAIL_COND_V(!surface, Array());
return surface->morph_data;
-
}
+void RasterizerGLES2::mesh_set_morph_target_count(RID p_mesh, int p_amount) {
-void RasterizerGLES2::mesh_set_morph_target_count(RID p_mesh,int p_amount) {
-
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_COND( mesh->surfaces.size()!=0 );
-
- mesh->morph_target_count=p_amount;
+ ERR_FAIL_COND(mesh->surfaces.size() != 0);
+ mesh->morph_target_count = p_amount;
}
-int RasterizerGLES2::mesh_get_morph_target_count(RID p_mesh) const{
+int RasterizerGLES2::mesh_get_morph_target_count(RID p_mesh) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
return mesh->morph_target_count;
-
}
-void RasterizerGLES2::mesh_set_morph_target_mode(RID p_mesh,VS::MorphTargetMode p_mode) {
+void RasterizerGLES2::mesh_set_morph_target_mode(RID p_mesh, VS::MorphTargetMode p_mode) {
- ERR_FAIL_INDEX(p_mode,2);
- Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_INDEX(p_mode, 2);
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- mesh->morph_target_mode=p_mode;
-
+ mesh->morph_target_mode = p_mode;
}
VS::MorphTargetMode RasterizerGLES2::mesh_get_morph_target_mode(RID p_mesh) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,VS::MORPH_MODE_NORMALIZED);
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, VS::MORPH_MODE_NORMALIZED);
return mesh->morph_target_mode;
-
}
+void RasterizerGLES2::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material, bool p_owned) {
-
-void RasterizerGLES2::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned) {
-
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_surface, mesh->surfaces.size() );
+ ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND( !surface);
+ ERR_FAIL_COND(!surface);
if (surface->material_owned && surface->material.is_valid())
free(surface->material);
- surface->material_owned=p_owned;
+ surface->material_owned = p_owned;
- surface->material=p_material;
+ surface->material = p_material;
}
RID RasterizerGLES2::mesh_surface_get_material(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,RID());
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID() );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, RID());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, RID() );
+ ERR_FAIL_COND_V(!surface, RID());
return surface->material;
}
int RasterizerGLES2::mesh_surface_get_array_len(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, -1 );
+ ERR_FAIL_COND_V(!surface, -1);
return surface->array_len;
}
int RasterizerGLES2::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, -1 );
+ ERR_FAIL_COND_V(!surface, -1);
return surface->index_array_len;
}
uint32_t RasterizerGLES2::mesh_surface_get_format(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,0);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, 0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, 0 );
+ ERR_FAIL_COND_V(!surface, 0);
return surface->format;
}
VS::PrimitiveType RasterizerGLES2::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,VS::PRIMITIVE_POINTS);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_POINTS );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, VS::PRIMITIVE_POINTS);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_POINTS);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, VS::PRIMITIVE_POINTS );
+ ERR_FAIL_COND_V(!surface, VS::PRIMITIVE_POINTS);
return surface->primitive;
}
-void RasterizerGLES2::mesh_remove_surface(RID p_mesh,int p_index) {
+void RasterizerGLES2::mesh_remove_surface(RID p_mesh, int p_index) {
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_index, mesh->surfaces.size() );
+ ERR_FAIL_INDEX(p_index, mesh->surfaces.size());
Surface *surface = mesh->surfaces[p_index];
- ERR_FAIL_COND( !surface);
+ ERR_FAIL_COND(!surface);
if (surface->vertex_id)
- glDeleteBuffers(1,&surface->vertex_id);
+ glDeleteBuffers(1, &surface->vertex_id);
if (surface->index_id)
- glDeleteBuffers(1,&surface->index_id);
-
+ glDeleteBuffers(1, &surface->index_id);
if (mesh->morph_target_count) {
- for(int i=0;i<mesh->morph_target_count;i++)
+ for (int i = 0; i < mesh->morph_target_count; i++)
memfree(surface->morph_targets_local[i].array);
- memfree( surface->morph_targets_local );
+ memfree(surface->morph_targets_local);
}
- memdelete( mesh->surfaces[p_index] );
+ memdelete(mesh->surfaces[p_index]);
mesh->surfaces.remove(p_index);
-
}
int RasterizerGLES2::mesh_get_surface_count(RID p_mesh) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
return mesh->surfaces.size();
}
AABB RasterizerGLES2::mesh_get_aabb(RID p_mesh, RID p_skeleton) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,AABB());
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, AABB());
- if (mesh->custom_aabb!=AABB())
+ if (mesh->custom_aabb != AABB())
return mesh->custom_aabb;
- Skeleton *sk=NULL;
+ Skeleton *sk = NULL;
if (p_skeleton.is_valid())
- sk=skeleton_owner.get(p_skeleton);
+ sk = skeleton_owner.get(p_skeleton);
AABB aabb;
- if (sk && sk->bones.size()!=0) {
+ if (sk && sk->bones.size() != 0) {
-
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
AABB laabb;
- if (mesh->surfaces[i]->format&VS::ARRAY_FORMAT_BONES && mesh->surfaces[i]->skeleton_bone_aabb.size()) {
-
+ if (mesh->surfaces[i]->format & VS::ARRAY_FORMAT_BONES && mesh->surfaces[i]->skeleton_bone_aabb.size()) {
int bs = mesh->surfaces[i]->skeleton_bone_aabb.size();
const AABB *skbones = mesh->surfaces[i]->skeleton_bone_aabb.ptr();
const bool *skused = mesh->surfaces[i]->skeleton_bone_used.ptr();
int sbs = sk->bones.size();
- ERR_CONTINUE(bs>sbs);
+ ERR_CONTINUE(bs > sbs);
Skeleton::Bone *skb = sk->bones.ptr();
- bool first=true;
- for(int j=0;j<bs;j++) {
+ bool first = true;
+ for (int j = 0; j < bs; j++) {
if (!skused[j])
continue;
- AABB baabb = skb[ j ].transform_aabb ( skbones[j] );
+ AABB baabb = skb[j].transform_aabb(skbones[j]);
if (first) {
- laabb=baabb;
- first=false;
+ laabb = baabb;
+ first = false;
} else {
laabb.merge_with(baabb);
}
@@ -2827,43 +2647,40 @@ AABB RasterizerGLES2::mesh_get_aabb(RID p_mesh, RID p_skeleton) const {
} else {
- laabb=mesh->surfaces[i]->aabb;
+ laabb = mesh->surfaces[i]->aabb;
}
- if (i==0)
- aabb=laabb;
+ if (i == 0)
+ aabb = laabb;
else
aabb.merge_with(laabb);
}
} else {
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
- if (i==0)
- aabb=mesh->surfaces[i]->aabb;
+ if (i == 0)
+ aabb = mesh->surfaces[i]->aabb;
else
aabb.merge_with(mesh->surfaces[i]->aabb);
}
-
}
return aabb;
}
+void RasterizerGLES2::mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb) {
-void RasterizerGLES2::mesh_set_custom_aabb(RID p_mesh,const AABB& p_aabb) {
-
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- mesh->custom_aabb=p_aabb;
-
+ mesh->custom_aabb = p_aabb;
}
AABB RasterizerGLES2::mesh_get_custom_aabb(RID p_mesh) const {
- const Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,AABB());
+ const Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, AABB());
return mesh->custom_aabb;
}
@@ -2871,10 +2688,10 @@ AABB RasterizerGLES2::mesh_get_custom_aabb(RID p_mesh) const {
RID RasterizerGLES2::multimesh_create() {
- return multimesh_owner.make_rid( memnew( MultiMesh ));
+ return multimesh_owner.make_rid(memnew(MultiMesh));
}
-void RasterizerGLES2::multimesh_set_instance_count(RID p_multimesh,int p_count) {
+void RasterizerGLES2::multimesh_set_instance_count(RID p_multimesh, int p_count) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
@@ -2883,40 +2700,37 @@ void RasterizerGLES2::multimesh_set_instance_count(RID p_multimesh,int p_count)
if (use_texture_instancing) {
- if (nearest_power_of_2(p_count)!=nearest_power_of_2(multimesh->elements.size())) {
+ if (nearest_power_of_2(p_count) != nearest_power_of_2(multimesh->elements.size())) {
if (multimesh->tex_id) {
- glDeleteTextures(1,&multimesh->tex_id);
- multimesh->tex_id=0;
+ glDeleteTextures(1, &multimesh->tex_id);
+ multimesh->tex_id = 0;
}
if (p_count) {
uint32_t po2 = nearest_power_of_2(p_count);
- if (po2&0xAAAAAAAA) {
+ if (po2 & 0xAAAAAAAA) {
//half width
- multimesh->tw=Math::sqrt(po2*2);
- multimesh->th=multimesh->tw/2;
+ multimesh->tw = Math::sqrt(po2 * 2);
+ multimesh->th = multimesh->tw / 2;
} else {
- multimesh->tw=Math::sqrt(po2);
- multimesh->th=multimesh->tw;
-
+ multimesh->tw = Math::sqrt(po2);
+ multimesh->th = multimesh->tw;
}
- multimesh->tw*=4;
- if (multimesh->th==0)
- multimesh->th=1;
-
-
+ multimesh->tw *= 4;
+ if (multimesh->th == 0)
+ multimesh->th = 1;
glGenTextures(1, &multimesh->tex_id);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,multimesh->tex_id);
+ glBindTexture(GL_TEXTURE_2D, multimesh->tex_id);
#ifdef GLEW_ENABLED
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, multimesh->tw, multimesh->th, 0, GL_RGBA, GL_FLOAT,NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, multimesh->tw, multimesh->th, 0, GL_RGBA, GL_FLOAT, NULL);
#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, multimesh->tw, multimesh->th, 0, GL_RGBA, GL_FLOAT,NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, multimesh->tw, multimesh->th, 0, GL_RGBA, GL_FLOAT, NULL);
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
@@ -2924,186 +2738,173 @@ void RasterizerGLES2::multimesh_set_instance_count(RID p_multimesh,int p_count)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//multimesh->pixel_size=1.0/ps;
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, 0);
}
-
}
if (!multimesh->dirty_list.in_list()) {
_multimesh_dirty_list.add(&multimesh->dirty_list);
}
-
}
multimesh->elements.resize(p_count);
-
}
int RasterizerGLES2::multimesh_get_instance_count(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,-1);
+ ERR_FAIL_COND_V(!multimesh, -1);
return multimesh->elements.size();
}
-void RasterizerGLES2::multimesh_set_mesh(RID p_multimesh,RID p_mesh) {
+void RasterizerGLES2::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
- multimesh->mesh=p_mesh;
-
+ multimesh->mesh = p_mesh;
}
-void RasterizerGLES2::multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb) {
+void RasterizerGLES2::multimesh_set_aabb(RID p_multimesh, const AABB &p_aabb) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
- multimesh->aabb=p_aabb;
+ multimesh->aabb = p_aabb;
}
-void RasterizerGLES2::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform) {
+void RasterizerGLES2::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
- ERR_FAIL_INDEX(p_index,multimesh->elements.size());
- MultiMesh::Element &e=multimesh->elements[p_index];
-
- e.matrix[0]=p_transform.basis.elements[0][0];
- e.matrix[1]=p_transform.basis.elements[1][0];
- e.matrix[2]=p_transform.basis.elements[2][0];
- e.matrix[3]=0;
- e.matrix[4]=p_transform.basis.elements[0][1];
- e.matrix[5]=p_transform.basis.elements[1][1];
- e.matrix[6]=p_transform.basis.elements[2][1];
- e.matrix[7]=0;
- e.matrix[8]=p_transform.basis.elements[0][2];
- e.matrix[9]=p_transform.basis.elements[1][2];
- e.matrix[10]=p_transform.basis.elements[2][2];
- e.matrix[11]=0;
- e.matrix[12]=p_transform.origin.x;
- e.matrix[13]=p_transform.origin.y;
- e.matrix[14]=p_transform.origin.z;
- e.matrix[15]=1;
+ ERR_FAIL_INDEX(p_index, multimesh->elements.size());
+ MultiMesh::Element &e = multimesh->elements[p_index];
+
+ e.matrix[0] = p_transform.basis.elements[0][0];
+ e.matrix[1] = p_transform.basis.elements[1][0];
+ e.matrix[2] = p_transform.basis.elements[2][0];
+ e.matrix[3] = 0;
+ e.matrix[4] = p_transform.basis.elements[0][1];
+ e.matrix[5] = p_transform.basis.elements[1][1];
+ e.matrix[6] = p_transform.basis.elements[2][1];
+ e.matrix[7] = 0;
+ e.matrix[8] = p_transform.basis.elements[0][2];
+ e.matrix[9] = p_transform.basis.elements[1][2];
+ e.matrix[10] = p_transform.basis.elements[2][2];
+ e.matrix[11] = 0;
+ e.matrix[12] = p_transform.origin.x;
+ e.matrix[13] = p_transform.origin.y;
+ e.matrix[14] = p_transform.origin.z;
+ e.matrix[15] = 1;
if (!multimesh->dirty_list.in_list()) {
_multimesh_dirty_list.add(&multimesh->dirty_list);
}
-
}
-void RasterizerGLES2::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color) {
+void RasterizerGLES2::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh)
- ERR_FAIL_INDEX(p_index,multimesh->elements.size());
- MultiMesh::Element &e=multimesh->elements[p_index];
- e.color[0]=CLAMP(p_color.r*255,0,255);
- e.color[1]=CLAMP(p_color.g*255,0,255);
- e.color[2]=CLAMP(p_color.b*255,0,255);
- e.color[3]=CLAMP(p_color.a*255,0,255);
+ ERR_FAIL_INDEX(p_index, multimesh->elements.size());
+ MultiMesh::Element &e = multimesh->elements[p_index];
+ e.color[0] = CLAMP(p_color.r * 255, 0, 255);
+ e.color[1] = CLAMP(p_color.g * 255, 0, 255);
+ e.color[2] = CLAMP(p_color.b * 255, 0, 255);
+ e.color[3] = CLAMP(p_color.a * 255, 0, 255);
if (!multimesh->dirty_list.in_list()) {
_multimesh_dirty_list.add(&multimesh->dirty_list);
}
-
}
RID RasterizerGLES2::multimesh_get_mesh(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,RID());
+ ERR_FAIL_COND_V(!multimesh, RID());
return multimesh->mesh;
}
AABB RasterizerGLES2::multimesh_get_aabb(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,AABB());
+ ERR_FAIL_COND_V(!multimesh, AABB());
return multimesh->aabb;
}
-Transform RasterizerGLES2::multimesh_instance_get_transform(RID p_multimesh,int p_index) const {
+Transform RasterizerGLES2::multimesh_instance_get_transform(RID p_multimesh, int p_index) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Transform());
+ ERR_FAIL_COND_V(!multimesh, Transform());
- ERR_FAIL_INDEX_V(p_index,multimesh->elements.size(),Transform());
- MultiMesh::Element &e=multimesh->elements[p_index];
+ ERR_FAIL_INDEX_V(p_index, multimesh->elements.size(), Transform());
+ MultiMesh::Element &e = multimesh->elements[p_index];
Transform tr;
- tr.basis.elements[0][0]=e.matrix[0];
- tr.basis.elements[1][0]=e.matrix[1];
- tr.basis.elements[2][0]=e.matrix[2];
- tr.basis.elements[0][1]=e.matrix[4];
- tr.basis.elements[1][1]=e.matrix[5];
- tr.basis.elements[2][1]=e.matrix[6];
- tr.basis.elements[0][2]=e.matrix[8];
- tr.basis.elements[1][2]=e.matrix[9];
- tr.basis.elements[2][2]=e.matrix[10];
- tr.origin.x=e.matrix[12];
- tr.origin.y=e.matrix[13];
- tr.origin.z=e.matrix[14];
+ tr.basis.elements[0][0] = e.matrix[0];
+ tr.basis.elements[1][0] = e.matrix[1];
+ tr.basis.elements[2][0] = e.matrix[2];
+ tr.basis.elements[0][1] = e.matrix[4];
+ tr.basis.elements[1][1] = e.matrix[5];
+ tr.basis.elements[2][1] = e.matrix[6];
+ tr.basis.elements[0][2] = e.matrix[8];
+ tr.basis.elements[1][2] = e.matrix[9];
+ tr.basis.elements[2][2] = e.matrix[10];
+ tr.origin.x = e.matrix[12];
+ tr.origin.y = e.matrix[13];
+ tr.origin.z = e.matrix[14];
return tr;
}
-Color RasterizerGLES2::multimesh_instance_get_color(RID p_multimesh,int p_index) const {
+Color RasterizerGLES2::multimesh_instance_get_color(RID p_multimesh, int p_index) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Color());
- ERR_FAIL_INDEX_V(p_index,multimesh->elements.size(),Color());
- MultiMesh::Element &e=multimesh->elements[p_index];
+ ERR_FAIL_COND_V(!multimesh, Color());
+ ERR_FAIL_INDEX_V(p_index, multimesh->elements.size(), Color());
+ MultiMesh::Element &e = multimesh->elements[p_index];
Color c;
- c.r=e.color[0]/255.0;
- c.g=e.color[1]/255.0;
- c.b=e.color[2]/255.0;
- c.a=e.color[3]/255.0;
+ c.r = e.color[0] / 255.0;
+ c.g = e.color[1] / 255.0;
+ c.b = e.color[2] / 255.0;
+ c.a = e.color[3] / 255.0;
return c;
-
}
-void RasterizerGLES2::multimesh_set_visible_instances(RID p_multimesh,int p_visible) {
+void RasterizerGLES2::multimesh_set_visible_instances(RID p_multimesh, int p_visible) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
- multimesh->visible=p_visible;
-
+ multimesh->visible = p_visible;
}
int RasterizerGLES2::multimesh_get_visible_instances(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,-1);
+ ERR_FAIL_COND_V(!multimesh, -1);
return multimesh->visible;
-
}
/* IMMEDIATE API */
-
RID RasterizerGLES2::immediate_create() {
- Immediate *im = memnew( Immediate );
+ Immediate *im = memnew(Immediate);
return immediate_owner.make_rid(im);
-
}
-void RasterizerGLES2::immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture){
+void RasterizerGLES2::immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(im->building);
Immediate::Chunk ic;
- ic.texture=p_texture;
- ic.primitive=p_rimitive;
+ ic.texture = p_texture;
+ ic.primitive = p_rimitive;
im->chunks.push_back(ic);
- im->mask=0;
- im->building=true;
-
-
+ im->mask = 0;
+ im->building = true;
}
-void RasterizerGLES2::immediate_vertex(RID p_immediate,const Vector3& p_vertex){
+void RasterizerGLES2::immediate_vertex(RID p_immediate, const Vector3 &p_vertex) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
@@ -3111,90 +2912,81 @@ void RasterizerGLES2::immediate_vertex(RID p_immediate,const Vector3& p_vertex){
Immediate::Chunk *c = &im->chunks.back()->get();
+ if (c->vertices.empty() && im->chunks.size() == 1) {
- if (c->vertices.empty() && im->chunks.size()==1) {
-
- im->aabb.pos=p_vertex;
- im->aabb.size=Vector3();
+ im->aabb.pos = p_vertex;
+ im->aabb.size = Vector3();
} else {
im->aabb.expand_to(p_vertex);
}
- if (im->mask&VS::ARRAY_FORMAT_NORMAL)
+ if (im->mask & VS::ARRAY_FORMAT_NORMAL)
c->normals.push_back(chunk_normal);
- if (im->mask&VS::ARRAY_FORMAT_TANGENT)
+ if (im->mask & VS::ARRAY_FORMAT_TANGENT)
c->tangents.push_back(chunk_tangent);
- if (im->mask&VS::ARRAY_FORMAT_COLOR)
+ if (im->mask & VS::ARRAY_FORMAT_COLOR)
c->colors.push_back(chunk_color);
- if (im->mask&VS::ARRAY_FORMAT_TEX_UV)
+ if (im->mask & VS::ARRAY_FORMAT_TEX_UV)
c->uvs.push_back(chunk_uv);
- if (im->mask&VS::ARRAY_FORMAT_TEX_UV2)
+ if (im->mask & VS::ARRAY_FORMAT_TEX_UV2)
c->uvs2.push_back(chunk_uv2);
- im->mask|=VS::ARRAY_FORMAT_VERTEX;
+ im->mask |= VS::ARRAY_FORMAT_VERTEX;
c->vertices.push_back(p_vertex);
-
}
-
-void RasterizerGLES2::immediate_normal(RID p_immediate,const Vector3& p_normal){
+void RasterizerGLES2::immediate_normal(RID p_immediate, const Vector3 &p_normal) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_NORMAL;
- chunk_normal=p_normal;
-
+ im->mask |= VS::ARRAY_FORMAT_NORMAL;
+ chunk_normal = p_normal;
}
-void RasterizerGLES2::immediate_tangent(RID p_immediate,const Plane& p_tangent){
+void RasterizerGLES2::immediate_tangent(RID p_immediate, const Plane &p_tangent) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TANGENT;
- chunk_tangent=p_tangent;
-
+ im->mask |= VS::ARRAY_FORMAT_TANGENT;
+ chunk_tangent = p_tangent;
}
-void RasterizerGLES2::immediate_color(RID p_immediate,const Color& p_color){
+void RasterizerGLES2::immediate_color(RID p_immediate, const Color &p_color) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_COLOR;
- chunk_color=p_color;
-
+ im->mask |= VS::ARRAY_FORMAT_COLOR;
+ chunk_color = p_color;
}
-void RasterizerGLES2::immediate_uv(RID p_immediate,const Vector2& tex_uv){
+void RasterizerGLES2::immediate_uv(RID p_immediate, const Vector2 &tex_uv) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TEX_UV;
- chunk_uv=tex_uv;
-
+ im->mask |= VS::ARRAY_FORMAT_TEX_UV;
+ chunk_uv = tex_uv;
}
-void RasterizerGLES2::immediate_uv2(RID p_immediate,const Vector2& tex_uv){
+void RasterizerGLES2::immediate_uv2(RID p_immediate, const Vector2 &tex_uv) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TEX_UV2;
- chunk_uv2=tex_uv;
-
+ im->mask |= VS::ARRAY_FORMAT_TEX_UV2;
+ chunk_uv2 = tex_uv;
}
-void RasterizerGLES2::immediate_end(RID p_immediate){
+void RasterizerGLES2::immediate_end(RID p_immediate) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->building=false;
-
+ im->building = false;
}
void RasterizerGLES2::immediate_clear(RID p_immediate) {
@@ -3208,345 +3000,318 @@ void RasterizerGLES2::immediate_clear(RID p_immediate) {
AABB RasterizerGLES2::immediate_get_aabb(RID p_immediate) const {
Immediate *im = immediate_owner.get(p_immediate);
- ERR_FAIL_COND_V(!im,AABB());
+ ERR_FAIL_COND_V(!im, AABB());
return im->aabb;
}
-void RasterizerGLES2::immediate_set_material(RID p_immediate,RID p_material) {
+void RasterizerGLES2::immediate_set_material(RID p_immediate, RID p_material) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
- im->material=p_material;
-
+ im->material = p_material;
}
RID RasterizerGLES2::immediate_get_material(RID p_immediate) const {
const Immediate *im = immediate_owner.get(p_immediate);
- ERR_FAIL_COND_V(!im,RID());
+ ERR_FAIL_COND_V(!im, RID());
return im->material;
-
}
-
/* PARTICLES API */
RID RasterizerGLES2::particles_create() {
- Particles *particles = memnew( Particles );
- ERR_FAIL_COND_V(!particles,RID());
+ Particles *particles = memnew(Particles);
+ ERR_FAIL_COND_V(!particles, RID());
return particles_owner.make_rid(particles);
}
void RasterizerGLES2::particles_set_amount(RID p_particles, int p_amount) {
- ERR_FAIL_COND(p_amount<1);
- Particles* particles = particles_owner.get( p_particles );
+ ERR_FAIL_COND(p_amount < 1);
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.amount=p_amount;
-
+ particles->data.amount = p_amount;
}
int RasterizerGLES2::particles_get_amount(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.amount;
-
}
void RasterizerGLES2::particles_set_emitting(RID p_particles, bool p_emitting) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.emitting=p_emitting;
-
+ particles->data.emitting = p_emitting;
}
bool RasterizerGLES2::particles_is_emitting(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,false);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, false);
return particles->data.emitting;
-
}
-void RasterizerGLES2::particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility) {
+void RasterizerGLES2::particles_set_visibility_aabb(RID p_particles, const AABB &p_visibility) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.visibility_aabb=p_visibility;
-
+ particles->data.visibility_aabb = p_visibility;
}
-void RasterizerGLES2::particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents) {
+void RasterizerGLES2::particles_set_emission_half_extents(RID p_particles, const Vector3 &p_half_extents) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.emission_half_extents=p_half_extents;
+ particles->data.emission_half_extents = p_half_extents;
}
Vector3 RasterizerGLES2::particles_get_emission_half_extents(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,Vector3());
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, Vector3());
return particles->data.emission_half_extents;
}
-void RasterizerGLES2::particles_set_emission_base_velocity(RID p_particles, const Vector3& p_base_velocity) {
+void RasterizerGLES2::particles_set_emission_base_velocity(RID p_particles, const Vector3 &p_base_velocity) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.emission_base_velocity=p_base_velocity;
+ particles->data.emission_base_velocity = p_base_velocity;
}
Vector3 RasterizerGLES2::particles_get_emission_base_velocity(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,Vector3());
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, Vector3());
return particles->data.emission_base_velocity;
}
+void RasterizerGLES2::particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) {
-void RasterizerGLES2::particles_set_emission_points(RID p_particles, const PoolVector<Vector3>& p_points) {
-
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.emission_points=p_points;
+ particles->data.emission_points = p_points;
}
PoolVector<Vector3> RasterizerGLES2::particles_get_emission_points(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,PoolVector<Vector3>());
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, PoolVector<Vector3>());
return particles->data.emission_points;
-
}
-void RasterizerGLES2::particles_set_gravity_normal(RID p_particles, const Vector3& p_normal) {
+void RasterizerGLES2::particles_set_gravity_normal(RID p_particles, const Vector3 &p_normal) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.gravity_normal=p_normal;
-
+ particles->data.gravity_normal = p_normal;
}
Vector3 RasterizerGLES2::particles_get_gravity_normal(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,Vector3());
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, Vector3());
return particles->data.gravity_normal;
}
-
AABB RasterizerGLES2::particles_get_visibility_aabb(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,AABB());
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, AABB());
return particles->data.visibility_aabb;
-
}
-void RasterizerGLES2::particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value) {
+void RasterizerGLES2::particles_set_variable(RID p_particles, VS::ParticleVariable p_variable, float p_value) {
- ERR_FAIL_INDEX(p_variable,VS::PARTICLE_VAR_MAX);
+ ERR_FAIL_INDEX(p_variable, VS::PARTICLE_VAR_MAX);
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.particle_vars[p_variable]=p_value;
-
+ particles->data.particle_vars[p_variable] = p_value;
}
float RasterizerGLES2::particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.particle_vars[p_variable];
}
-void RasterizerGLES2::particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness) {
+void RasterizerGLES2::particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable, float p_randomness) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.particle_randomness[p_variable]=p_randomness;
-
+ particles->data.particle_randomness[p_variable] = p_randomness;
}
float RasterizerGLES2::particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.particle_randomness[p_variable];
-
}
void RasterizerGLES2::particles_set_color_phases(RID p_particles, int p_phases) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_COND( p_phases<0 || p_phases>VS::MAX_PARTICLE_COLOR_PHASES );
- particles->data.color_phase_count=p_phases;
-
+ ERR_FAIL_COND(p_phases < 0 || p_phases > VS::MAX_PARTICLE_COLOR_PHASES);
+ particles->data.color_phase_count = p_phases;
}
int RasterizerGLES2::particles_get_color_phases(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.color_phase_count;
}
-
void RasterizerGLES2::particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos) {
ERR_FAIL_INDEX(p_phase, VS::MAX_PARTICLE_COLOR_PHASES);
- if (p_pos<0.0)
- p_pos=0.0;
- if (p_pos>1.0)
- p_pos=1.0;
+ if (p_pos < 0.0)
+ p_pos = 0.0;
+ if (p_pos > 1.0)
+ p_pos = 1.0;
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.color_phases[p_phase].pos=p_pos;
-
+ particles->data.color_phases[p_phase].pos = p_pos;
}
float RasterizerGLES2::particles_get_color_phase_pos(RID p_particles, int p_phase) const {
ERR_FAIL_INDEX_V(p_phase, VS::MAX_PARTICLE_COLOR_PHASES, -1.0);
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.color_phases[p_phase].pos;
-
}
-void RasterizerGLES2::particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color) {
+void RasterizerGLES2::particles_set_color_phase_color(RID p_particles, int p_phase, const Color &p_color) {
ERR_FAIL_INDEX(p_phase, VS::MAX_PARTICLE_COLOR_PHASES);
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.color_phases[p_phase].color=p_color;
+ particles->data.color_phases[p_phase].color = p_color;
//update alpha
- particles->has_alpha=false;
- for(int i=0;i<VS::MAX_PARTICLE_COLOR_PHASES;i++) {
- if (particles->data.color_phases[i].color.a<0.99)
- particles->has_alpha=true;
+ particles->has_alpha = false;
+ for (int i = 0; i < VS::MAX_PARTICLE_COLOR_PHASES; i++) {
+ if (particles->data.color_phases[i].color.a < 0.99)
+ particles->has_alpha = true;
}
-
}
Color RasterizerGLES2::particles_get_color_phase_color(RID p_particles, int p_phase) const {
ERR_FAIL_INDEX_V(p_phase, VS::MAX_PARTICLE_COLOR_PHASES, Color());
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,Color());
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, Color());
return particles->data.color_phases[p_phase].color;
-
}
void RasterizerGLES2::particles_set_attractors(RID p_particles, int p_attractors) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_COND( p_attractors<0 || p_attractors>VisualServer::MAX_PARTICLE_ATTRACTORS );
- particles->data.attractor_count=p_attractors;
-
+ ERR_FAIL_COND(p_attractors < 0 || p_attractors > VisualServer::MAX_PARTICLE_ATTRACTORS);
+ particles->data.attractor_count = p_attractors;
}
int RasterizerGLES2::particles_get_attractors(RID p_particles) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,-1);
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, -1);
return particles->data.attractor_count;
}
-void RasterizerGLES2::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos) {
+void RasterizerGLES2::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3 &p_pos) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_INDEX(p_attractor,particles->data.attractor_count);
- particles->data.attractors[p_attractor].pos=p_pos;
+ ERR_FAIL_INDEX(p_attractor, particles->data.attractor_count);
+ particles->data.attractors[p_attractor].pos = p_pos;
}
-Vector3 RasterizerGLES2::particles_get_attractor_pos(RID p_particles,int p_attractor) const {
+Vector3 RasterizerGLES2::particles_get_attractor_pos(RID p_particles, int p_attractor) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,Vector3());
- ERR_FAIL_INDEX_V(p_attractor,particles->data.attractor_count,Vector3());
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, Vector3());
+ ERR_FAIL_INDEX_V(p_attractor, particles->data.attractor_count, Vector3());
return particles->data.attractors[p_attractor].pos;
}
void RasterizerGLES2::particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_INDEX(p_attractor,particles->data.attractor_count);
- particles->data.attractors[p_attractor].force=p_force;
+ ERR_FAIL_INDEX(p_attractor, particles->data.attractor_count);
+ particles->data.attractors[p_attractor].force = p_force;
}
-float RasterizerGLES2::particles_get_attractor_strength(RID p_particles,int p_attractor) const {
+float RasterizerGLES2::particles_get_attractor_strength(RID p_particles, int p_attractor) const {
- Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,0);
- ERR_FAIL_INDEX_V(p_attractor,particles->data.attractor_count,0);
+ Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, 0);
+ ERR_FAIL_INDEX_V(p_attractor, particles->data.attractor_count, 0);
return particles->data.attractors[p_attractor].force;
}
-void RasterizerGLES2::particles_set_material(RID p_particles, RID p_material,bool p_owned) {
+void RasterizerGLES2::particles_set_material(RID p_particles, RID p_material, bool p_owned) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
if (particles->material_owned && particles->material.is_valid())
free(particles->material);
- particles->material_owned=p_owned;
-
- particles->material=p_material;
+ particles->material_owned = p_owned;
+ particles->material = p_material;
}
RID RasterizerGLES2::particles_get_material(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,RID());
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, RID());
return particles->material;
-
}
void RasterizerGLES2::particles_set_use_local_coordinates(RID p_particles, bool p_enable) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.local_coordinates=p_enable;
-
+ particles->data.local_coordinates = p_enable;
}
bool RasterizerGLES2::particles_is_using_local_coordinates(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,false);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, false);
return particles->data.local_coordinates;
}
bool RasterizerGLES2::particles_has_height_from_velocity(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,false);
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, false);
return particles->data.height_from_velocity;
}
void RasterizerGLES2::particles_set_height_from_velocity(RID p_particles, bool p_enable) {
- Particles* particles = particles_owner.get( p_particles );
+ Particles *particles = particles_owner.get(p_particles);
ERR_FAIL_COND(!particles);
- particles->data.height_from_velocity=p_enable;
-
+ particles->data.height_from_velocity = p_enable;
}
AABB RasterizerGLES2::particles_get_aabb(RID p_particles) const {
- const Particles* particles = particles_owner.get( p_particles );
- ERR_FAIL_COND_V(!particles,AABB());
+ const Particles *particles = particles_owner.get(p_particles);
+ ERR_FAIL_COND_V(!particles, AABB());
return particles->data.visibility_aabb;
}
@@ -3554,208 +3319,201 @@ AABB RasterizerGLES2::particles_get_aabb(RID p_particles) const {
RID RasterizerGLES2::skeleton_create() {
- Skeleton *skeleton = memnew( Skeleton );
- ERR_FAIL_COND_V(!skeleton,RID());
- return skeleton_owner.make_rid( skeleton );
+ Skeleton *skeleton = memnew(Skeleton);
+ ERR_FAIL_COND_V(!skeleton, RID());
+ return skeleton_owner.make_rid(skeleton);
}
-void RasterizerGLES2::skeleton_resize(RID p_skeleton,int p_bones) {
+void RasterizerGLES2::skeleton_resize(RID p_skeleton, int p_bones) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND(!skeleton);
if (p_bones == skeleton->bones.size()) {
return;
};
if (use_hw_skeleton_xform) {
- if (nearest_power_of_2(p_bones)!=nearest_power_of_2(skeleton->bones.size())) {
+ if (nearest_power_of_2(p_bones) != nearest_power_of_2(skeleton->bones.size())) {
if (skeleton->tex_id) {
- glDeleteTextures(1,&skeleton->tex_id);
- skeleton->tex_id=0;
+ glDeleteTextures(1, &skeleton->tex_id);
+ skeleton->tex_id = 0;
}
if (p_bones) {
glGenTextures(1, &skeleton->tex_id);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,skeleton->tex_id);
- int ps = nearest_power_of_2(p_bones*3);
+ glBindTexture(GL_TEXTURE_2D, skeleton->tex_id);
+ int ps = nearest_power_of_2(p_bones * 3);
#ifdef GLEW_ENABLED
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, ps, 1, 0, GL_RGBA, GL_FLOAT,skel_default.ptr());
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, ps, 1, 0, GL_RGBA, GL_FLOAT, skel_default.ptr());
#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ps, 1, 0, GL_RGBA, GL_FLOAT,skel_default.ptr());
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ps, 1, 0, GL_RGBA, GL_FLOAT, skel_default.ptr());
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- skeleton->pixel_size=1.0/ps;
+ skeleton->pixel_size = 1.0 / ps;
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, 0);
}
-
}
if (!skeleton->dirty_list.in_list()) {
_skeleton_dirty_list.add(&skeleton->dirty_list);
}
-
}
skeleton->bones.resize(p_bones);
-
}
int RasterizerGLES2::skeleton_get_bone_count(RID p_skeleton) const {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND_V(!skeleton, -1);
return skeleton->bones.size();
}
-void RasterizerGLES2::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform) {
+void RasterizerGLES2::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND(!skeleton);
- ERR_FAIL_INDEX( p_bone, skeleton->bones.size() );
+ ERR_FAIL_INDEX(p_bone, skeleton->bones.size());
Skeleton::Bone &b = skeleton->bones[p_bone];
- b.mtx[0][0]=p_transform.basis[0][0];
- b.mtx[0][1]=p_transform.basis[1][0];
- b.mtx[0][2]=p_transform.basis[2][0];
- b.mtx[1][0]=p_transform.basis[0][1];
- b.mtx[1][1]=p_transform.basis[1][1];
- b.mtx[1][2]=p_transform.basis[2][1];
- b.mtx[2][0]=p_transform.basis[0][2];
- b.mtx[2][1]=p_transform.basis[1][2];
- b.mtx[2][2]=p_transform.basis[2][2];
- b.mtx[3][0]=p_transform.origin[0];
- b.mtx[3][1]=p_transform.origin[1];
- b.mtx[3][2]=p_transform.origin[2];
+ b.mtx[0][0] = p_transform.basis[0][0];
+ b.mtx[0][1] = p_transform.basis[1][0];
+ b.mtx[0][2] = p_transform.basis[2][0];
+ b.mtx[1][0] = p_transform.basis[0][1];
+ b.mtx[1][1] = p_transform.basis[1][1];
+ b.mtx[1][2] = p_transform.basis[2][1];
+ b.mtx[2][0] = p_transform.basis[0][2];
+ b.mtx[2][1] = p_transform.basis[1][2];
+ b.mtx[2][2] = p_transform.basis[2][2];
+ b.mtx[3][0] = p_transform.origin[0];
+ b.mtx[3][1] = p_transform.origin[1];
+ b.mtx[3][2] = p_transform.origin[2];
if (skeleton->tex_id) {
if (!skeleton->dirty_list.in_list()) {
_skeleton_dirty_list.add(&skeleton->dirty_list);
}
}
-
}
-Transform RasterizerGLES2::skeleton_bone_get_transform(RID p_skeleton,int p_bone) {
+Transform RasterizerGLES2::skeleton_bone_get_transform(RID p_skeleton, int p_bone) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND_V(!skeleton, Transform());
- ERR_FAIL_INDEX_V( p_bone, skeleton->bones.size(), Transform() );
+ ERR_FAIL_INDEX_V(p_bone, skeleton->bones.size(), Transform());
const Skeleton::Bone &b = skeleton->bones[p_bone];
Transform t;
- t.basis[0][0]=b.mtx[0][0];
- t.basis[1][0]=b.mtx[0][1];
- t.basis[2][0]=b.mtx[0][2];
- t.basis[0][1]=b.mtx[1][0];
- t.basis[1][1]=b.mtx[1][1];
- t.basis[2][1]=b.mtx[1][2];
- t.basis[0][2]=b.mtx[2][0];
- t.basis[1][2]=b.mtx[2][1];
- t.basis[2][2]=b.mtx[2][2];
- t.origin[0]=b.mtx[3][0];
- t.origin[1]=b.mtx[3][1];
- t.origin[2]=b.mtx[3][2];
+ t.basis[0][0] = b.mtx[0][0];
+ t.basis[1][0] = b.mtx[0][1];
+ t.basis[2][0] = b.mtx[0][2];
+ t.basis[0][1] = b.mtx[1][0];
+ t.basis[1][1] = b.mtx[1][1];
+ t.basis[2][1] = b.mtx[1][2];
+ t.basis[0][2] = b.mtx[2][0];
+ t.basis[1][2] = b.mtx[2][1];
+ t.basis[2][2] = b.mtx[2][2];
+ t.origin[0] = b.mtx[3][0];
+ t.origin[1] = b.mtx[3][1];
+ t.origin[2] = b.mtx[3][2];
return t;
-
}
-
/* LIGHT API */
RID RasterizerGLES2::light_create(VS::LightType p_type) {
- Light *light = memnew( Light );
- light->type=p_type;
+ Light *light = memnew(Light);
+ light->type = p_type;
return light_owner.make_rid(light);
}
VS::LightType RasterizerGLES2::light_get_type(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_OMNI);
return light->type;
}
-void RasterizerGLES2::light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color) {
+void RasterizerGLES2::light_set_color(RID p_light, VS::LightColor p_type, const Color &p_color) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- ERR_FAIL_INDEX( p_type, 3 );
- light->colors[p_type]=p_color;
+ ERR_FAIL_INDEX(p_type, 3);
+ light->colors[p_type] = p_color;
}
-Color RasterizerGLES2::light_get_color(RID p_light,VS::LightColor p_type) const {
+Color RasterizerGLES2::light_get_color(RID p_light, VS::LightColor p_type) const {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND_V(!light, Color());
- ERR_FAIL_INDEX_V( p_type, 3, Color() );
+ ERR_FAIL_INDEX_V(p_type, 3, Color());
return light->colors[p_type];
}
-void RasterizerGLES2::light_set_shadow(RID p_light,bool p_enabled) {
+void RasterizerGLES2::light_set_shadow(RID p_light, bool p_enabled) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->shadow_enabled=p_enabled;
+ light->shadow_enabled = p_enabled;
}
bool RasterizerGLES2::light_has_shadow(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,false);
+ ERR_FAIL_COND_V(!light, false);
return light->shadow_enabled;
}
-void RasterizerGLES2::light_set_volumetric(RID p_light,bool p_enabled) {
+void RasterizerGLES2::light_set_volumetric(RID p_light, bool p_enabled) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->volumetric_enabled=p_enabled;
-
+ light->volumetric_enabled = p_enabled;
}
bool RasterizerGLES2::light_is_volumetric(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,false);
+ ERR_FAIL_COND_V(!light, false);
return light->volumetric_enabled;
}
-void RasterizerGLES2::light_set_projector(RID p_light,RID p_texture) {
+void RasterizerGLES2::light_set_projector(RID p_light, RID p_texture) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->projector=p_texture;
+ light->projector = p_texture;
}
RID RasterizerGLES2::light_get_projector(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,RID());
+ ERR_FAIL_COND_V(!light, RID());
return light->projector;
}
void RasterizerGLES2::light_set_var(RID p_light, VS::LightParam p_var, float p_value) {
- Light * light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- ERR_FAIL_INDEX( p_var, VS::LIGHT_PARAM_MAX );
+ ERR_FAIL_INDEX(p_var, VS::LIGHT_PARAM_MAX);
- light->vars[p_var]=p_value;
+ light->vars[p_var] = p_value;
}
float RasterizerGLES2::light_get_var(RID p_light, VS::LightParam p_var) const {
- Light * light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,0);
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, 0);
- ERR_FAIL_INDEX_V( p_var, VS::LIGHT_PARAM_MAX,0 );
+ ERR_FAIL_INDEX_V(p_var, VS::LIGHT_PARAM_MAX, 0);
return light->vars[p_var];
}
-void RasterizerGLES2::light_set_operator(RID p_light,VS::LightOp p_op) {
+void RasterizerGLES2::light_set_operator(RID p_light, VS::LightOp p_op){
};
@@ -3764,71 +3522,69 @@ VS::LightOp RasterizerGLES2::light_get_operator(RID p_light) const {
return VS::LightOp();
};
-void RasterizerGLES2::light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode) {
+void RasterizerGLES2::light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode) {
- Light * light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->omni_shadow_mode=p_mode;
+ light->omni_shadow_mode = p_mode;
}
VS::LightOmniShadowMode RasterizerGLES2::light_omni_get_shadow_mode(RID p_light) const {
- const Light * light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI_SHADOW_DEFAULT);
+ const Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_OMNI_SHADOW_DEFAULT);
return light->omni_shadow_mode;
}
-void RasterizerGLES2::light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode) {
+void RasterizerGLES2::light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode) {
- Light * light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->directional_shadow_mode=p_mode;
+ light->directional_shadow_mode = p_mode;
}
-
VS::LightDirectionalShadowMode RasterizerGLES2::light_directional_get_shadow_mode(RID p_light) const {
- const Light * light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL);
+ const Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL);
return light->directional_shadow_mode;
}
-void RasterizerGLES2::light_directional_set_shadow_param(RID p_light,VS::LightDirectionalShadowParam p_param, float p_value) {
+void RasterizerGLES2::light_directional_set_shadow_param(RID p_light, VS::LightDirectionalShadowParam p_param, float p_value) {
- Light * light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->directional_shadow_param[p_param]=p_value;
+ light->directional_shadow_param[p_param] = p_value;
}
-float RasterizerGLES2::light_directional_get_shadow_param(RID p_light,VS::LightDirectionalShadowParam p_param) const {
+float RasterizerGLES2::light_directional_get_shadow_param(RID p_light, VS::LightDirectionalShadowParam p_param) const {
- const Light * light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,0);
+ const Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, 0);
return light->directional_shadow_param[p_param];
}
-
AABB RasterizerGLES2::light_get_aabb(RID p_light) const {
- Light *light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,AABB());
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, AABB());
- switch( light->type ) {
+ switch (light->type) {
case VS::LIGHT_SPOT: {
- float len=light->vars[VS::LIGHT_PARAM_RADIUS];
- float size=Math::tan(Math::deg2rad(light->vars[VS::LIGHT_PARAM_SPOT_ANGLE]))*len;
- return AABB( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) );
+ float len = light->vars[VS::LIGHT_PARAM_RADIUS];
+ float size = Math::tan(Math::deg2rad(light->vars[VS::LIGHT_PARAM_SPOT_ANGLE])) * len;
+ return AABB(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
} break;
case VS::LIGHT_OMNI: {
float r = light->vars[VS::LIGHT_PARAM_RADIUS];
- return AABB( -Vector3(r,r,r), Vector3(r,r,r)*2 );
+ return AABB(-Vector3(r, r, r), Vector3(r, r, r) * 2);
} break;
case VS::LIGHT_DIRECTIONAL: {
@@ -3837,54 +3593,51 @@ AABB RasterizerGLES2::light_get_aabb(RID p_light) const {
default: {}
}
- ERR_FAIL_V( AABB() );
+ ERR_FAIL_V(AABB());
}
-
RID RasterizerGLES2::light_instance_create(RID p_light) {
- Light *light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND_V(!light, RID());
- LightInstance *light_instance = memnew( LightInstance );
+ LightInstance *light_instance = memnew(LightInstance);
- light_instance->light=p_light;
- light_instance->base=light;
- light_instance->last_pass=0;
+ light_instance->light = p_light;
+ light_instance->base = light;
+ light_instance->last_pass = 0;
- return light_instance_owner.make_rid( light_instance );
+ return light_instance_owner.make_rid(light_instance);
}
-void RasterizerGLES2::light_instance_set_transform(RID p_light_instance,const Transform& p_transform) {
+void RasterizerGLES2::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!lighti);
- lighti->transform=p_transform;
-
+ lighti->transform = p_transform;
}
-
Rasterizer::ShadowType RasterizerGLES2::light_instance_get_shadow_type(RID p_light_instance, bool p_far) const {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
- ERR_FAIL_COND_V(!lighti,Rasterizer::SHADOW_NONE);
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
+ ERR_FAIL_COND_V(!lighti, Rasterizer::SHADOW_NONE);
- switch(lighti->base->type) {
+ switch (lighti->base->type) {
case VS::LIGHT_DIRECTIONAL: {
- switch(lighti->base->directional_shadow_mode) {
+ switch (lighti->base->directional_shadow_mode) {
case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: {
return SHADOW_ORTHOGONAL;
} break;
- case VS::LIGHT_DIRECTIONAL_SHADOW_PERSPECTIVE:{
+ case VS::LIGHT_DIRECTIONAL_SHADOW_PERSPECTIVE: {
return SHADOW_PSM;
} break;
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
- case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:{
+ case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: {
return SHADOW_PSSM;
} break;
}
- }break;
+ } break;
case VS::LIGHT_OMNI: return SHADOW_DUAL_PARABOLOID; break;
case VS::LIGHT_SPOT: return SHADOW_SIMPLE; break;
}
@@ -3894,13 +3647,13 @@ Rasterizer::ShadowType RasterizerGLES2::light_instance_get_shadow_type(RID p_lig
int RasterizerGLES2::light_instance_get_shadow_passes(RID p_light_instance) const {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
- ERR_FAIL_COND_V(!lighti,0);
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
+ ERR_FAIL_COND_V(!lighti, 0);
- if (lighti->base->type==VS::LIGHT_DIRECTIONAL && lighti->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ if (lighti->base->type == VS::LIGHT_DIRECTIONAL && lighti->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
return 4; // dp4
- } else if (lighti->base->type==VS::LIGHT_OMNI || (lighti->base->type==VS::LIGHT_DIRECTIONAL && lighti->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS)) {
+ } else if (lighti->base->type == VS::LIGHT_OMNI || (lighti->base->type == VS::LIGHT_DIRECTIONAL && lighti->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS)) {
return 2; // dp
} else
return 1;
@@ -3908,20 +3661,20 @@ int RasterizerGLES2::light_instance_get_shadow_passes(RID p_light_instance) cons
bool RasterizerGLES2::light_instance_get_pssm_shadow_overlap(RID p_light_instance) const {
- return shadow_filter>=SHADOW_FILTER_ESM;
+ return shadow_filter >= SHADOW_FILTER_ESM;
}
-void RasterizerGLES2::light_instance_set_shadow_transform(RID p_light_instance, int p_index, const CameraMatrix& p_camera, const Transform& p_transform, float p_split_near,float p_split_far) {
+void RasterizerGLES2::light_instance_set_shadow_transform(RID p_light_instance, int p_index, const CameraMatrix &p_camera, const Transform &p_transform, float p_split_near, float p_split_far) {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!lighti);
- ERR_FAIL_COND(lighti->base->type!=VS::LIGHT_DIRECTIONAL);
+ ERR_FAIL_COND(lighti->base->type != VS::LIGHT_DIRECTIONAL);
//ERR_FAIL_INDEX(p_index,1);
- lighti->custom_projection[p_index]=p_camera;
- lighti->custom_transform[p_index]=p_transform;
- lighti->shadow_split[p_index]=1.0/p_split_far;
+ lighti->custom_projection[p_index] = p_camera;
+ lighti->custom_transform[p_index] = p_transform;
+ lighti->shadow_split[p_index] = 1.0 / p_split_far;
#if 0
if (p_index==0) {
lighti->custom_projection=p_camera;
@@ -3942,23 +3695,21 @@ void RasterizerGLES2::light_instance_set_shadow_transform(RID p_light_instance,
#endif
}
-int RasterizerGLES2::light_instance_get_shadow_size(RID p_light_instance, int p_index) const{
+int RasterizerGLES2::light_instance_get_shadow_size(RID p_light_instance, int p_index) const {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
- ERR_FAIL_COND_V(!lighti,1);
- ERR_FAIL_COND_V(!lighti->near_shadow_buffer,256);
- return lighti->near_shadow_buffer->size/2;
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
+ ERR_FAIL_COND_V(!lighti, 1);
+ ERR_FAIL_COND_V(!lighti->near_shadow_buffer, 256);
+ return lighti->near_shadow_buffer->size / 2;
}
void RasterizerGLES2::shadow_clear_near() {
-
- for(int i=0;i<near_shadow_buffers.size();i++) {
+ for (int i = 0; i < near_shadow_buffers.size(); i++) {
if (near_shadow_buffers[i].owner)
near_shadow_buffers[i].owner->clear_near_shadow_buffers();
}
-
}
bool RasterizerGLES2::shadow_allocate_near(RID p_light) {
@@ -3967,32 +3718,31 @@ bool RasterizerGLES2::shadow_allocate_near(RID p_light) {
return false;
LightInstance *li = light_instance_owner.get(p_light);
- ERR_FAIL_COND_V(!li,false);
- ERR_FAIL_COND_V( li->near_shadow_buffer, false);
+ ERR_FAIL_COND_V(!li, false);
+ ERR_FAIL_COND_V(li->near_shadow_buffer, false);
- int skip=0;
+ int skip = 0;
if (framebuffer.active) {
int sc = framebuffer.scale;
- while(sc>1) {
- sc/=2;
+ while (sc > 1) {
+ sc /= 2;
skip++;
}
}
- for(int i=0;i<near_shadow_buffers.size();i++) {
+ for (int i = 0; i < near_shadow_buffers.size(); i++) {
-
- if (skip>0) {
+ if (skip > 0) {
skip--;
continue;
}
- if (near_shadow_buffers[i].owner!=NULL)
+ if (near_shadow_buffers[i].owner != NULL)
continue;
- near_shadow_buffers[i].owner=li;
- li->near_shadow_buffer=&near_shadow_buffers[i];
+ near_shadow_buffers[i].owner = li;
+ li->near_shadow_buffer = &near_shadow_buffers[i];
return true;
}
@@ -4004,38 +3754,35 @@ bool RasterizerGLES2::shadow_allocate_far(RID p_light) {
return false;
}
-
/* PARTICLES INSTANCE */
RID RasterizerGLES2::particles_instance_create(RID p_particles) {
- ERR_FAIL_COND_V(!particles_owner.owns(p_particles),RID());
- ParticlesInstance *particles_instance = memnew( ParticlesInstance );
- ERR_FAIL_COND_V(!particles_instance, RID() );
- particles_instance->particles=p_particles;
+ ERR_FAIL_COND_V(!particles_owner.owns(p_particles), RID());
+ ParticlesInstance *particles_instance = memnew(ParticlesInstance);
+ ERR_FAIL_COND_V(!particles_instance, RID());
+ particles_instance->particles = p_particles;
return particles_instance_owner.make_rid(particles_instance);
}
-void RasterizerGLES2::particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform) {
+void RasterizerGLES2::particles_instance_set_transform(RID p_particles_instance, const Transform &p_transform) {
- ParticlesInstance *particles_instance=particles_instance_owner.get(p_particles_instance);
+ ParticlesInstance *particles_instance = particles_instance_owner.get(p_particles_instance);
ERR_FAIL_COND(!particles_instance);
- particles_instance->transform=p_transform;
+ particles_instance->transform = p_transform;
}
-
-
RID RasterizerGLES2::viewport_data_create() {
- ViewportData *vd = memnew( ViewportData );
+ ViewportData *vd = memnew(ViewportData);
glActiveTexture(GL_TEXTURE0);
glGenFramebuffers(1, &vd->lum_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, vd->lum_fbo);
- GLuint format_luminance = use_fp16_fb?_GL_RG_EXT:GL_RGBA;
- GLuint format_luminance_type = use_fp16_fb?(full_float_fb_supported?GL_FLOAT:_GL_HALF_FLOAT_OES):GL_UNSIGNED_BYTE;
- GLuint format_luminance_components = use_fp16_fb?_GL_RG_EXT:GL_RGBA;
+ GLuint format_luminance = use_fp16_fb ? _GL_RG_EXT : GL_RGBA;
+ GLuint format_luminance_type = use_fp16_fb ? (full_float_fb_supported ? GL_FLOAT : _GL_HALF_FLOAT_OES) : GL_UNSIGNED_BYTE;
+ GLuint format_luminance_components = use_fp16_fb ? _GL_RG_EXT : GL_RGBA;
glGenTextures(1, &vd->lum_color);
glBindTexture(GL_TEXTURE_2D, vd->lum_color);
@@ -4048,11 +3795,10 @@ RID RasterizerGLES2::viewport_data_create() {
GL_RGBA, GL_UNSIGNED_BYTE, NULL);
*/
glTexImage2D(GL_TEXTURE_2D, 0, format_luminance, 1, 1, 0,
- format_luminance_components, format_luminance_type, NULL);
+ format_luminance_components, format_luminance_type, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, vd->lum_color, 0);
-
+ GL_TEXTURE_2D, vd->lum_color, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
@@ -4065,54 +3811,51 @@ RID RasterizerGLES2::viewport_data_create() {
return viewport_data_owner.make_rid(vd);
}
-RID RasterizerGLES2::render_target_create(){
+RID RasterizerGLES2::render_target_create() {
- RenderTarget *rt = memnew( RenderTarget );
- rt->fbo=0;
- rt->width=0;
- rt->height=0;
- rt->last_pass=0;
+ RenderTarget *rt = memnew(RenderTarget);
+ rt->fbo = 0;
+ rt->width = 0;
+ rt->height = 0;
+ rt->last_pass = 0;
Texture *texture = memnew(Texture);
- texture->active=false;
- texture->total_data_size=0;
- texture->render_target=rt;
- texture->ignore_mipmaps=true;
- rt->texture_ptr=texture;
- rt->texture=texture_owner.make_rid( texture );
- rt->texture_ptr->active=false;
+ texture->active = false;
+ texture->total_data_size = 0;
+ texture->render_target = rt;
+ texture->ignore_mipmaps = true;
+ rt->texture_ptr = texture;
+ rt->texture = texture_owner.make_rid(texture);
+ rt->texture_ptr->active = false;
return render_target_owner.make_rid(rt);
-
}
-void RasterizerGLES2::render_target_set_size(RID p_render_target,int p_width,int p_height){
+void RasterizerGLES2::render_target_set_size(RID p_render_target, int p_width, int p_height) {
RenderTarget *rt = render_target_owner.get(p_render_target);
- if (p_width==rt->width && p_height==rt->height)
+ if (p_width == rt->width && p_height == rt->height)
return;
- if (rt->width!=0 && rt->height!=0) {
-
- glDeleteFramebuffers(1,&rt->fbo);
- glDeleteRenderbuffers(1,&rt->depth);
- glDeleteTextures(1,&rt->color);
+ if (rt->width != 0 && rt->height != 0) {
- rt->fbo=0;
- rt->depth=0;
- rt->color=0;
- rt->width=0;
- rt->height=0;
- rt->texture_ptr->tex_id=0;
- rt->texture_ptr->active=false;
+ glDeleteFramebuffers(1, &rt->fbo);
+ glDeleteRenderbuffers(1, &rt->depth);
+ glDeleteTextures(1, &rt->color);
+ rt->fbo = 0;
+ rt->depth = 0;
+ rt->color = 0;
+ rt->width = 0;
+ rt->height = 0;
+ rt->texture_ptr->tex_id = 0;
+ rt->texture_ptr->active = false;
}
- if (p_width==0 || p_height==0)
+ if (p_width == 0 || p_height == 0)
return;
-
- rt->width=p_width;
- rt->height=p_height;
+ rt->width = p_width;
+ rt->height = p_height;
//fbo
glGenFramebuffers(1, &rt->fbo);
@@ -4121,9 +3864,9 @@ void RasterizerGLES2::render_target_set_size(RID p_render_target,int p_width,int
//depth
if (!low_memory_2d) {
glGenRenderbuffers(1, &rt->depth);
- glBindRenderbuffer(GL_RENDERBUFFER, rt->depth );
+ glBindRenderbuffer(GL_RENDERBUFFER, rt->depth);
- glRenderbufferStorage(GL_RENDERBUFFER, use_depth24?_DEPTH_COMPONENT24_OES:GL_DEPTH_COMPONENT16, rt->width,rt->height);
+ glRenderbufferStorage(GL_RENDERBUFFER, use_depth24 ? _DEPTH_COMPONENT24_OES : GL_DEPTH_COMPONENT16, rt->width, rt->height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->depth);
}
@@ -4131,9 +3874,9 @@ void RasterizerGLES2::render_target_set_size(RID p_render_target,int p_width,int
//color
glGenTextures(1, &rt->color);
glBindTexture(GL_TEXTURE_2D, rt->color);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rt->width, rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rt->width, rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
- if (rt->texture_ptr->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (rt->texture_ptr->flags & VS::TEXTURE_FLAG_FILTER) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
@@ -4146,157 +3889,139 @@ void RasterizerGLES2::render_target_set_size(RID p_render_target,int p_width,int
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0);
- rt->texture_ptr->tex_id=rt->color;
- rt->texture_ptr->active=true;
- rt->texture_ptr->width=p_width;
- rt->texture_ptr->height=p_height;
+ rt->texture_ptr->tex_id = rt->color;
+ rt->texture_ptr->active = true;
+ rt->texture_ptr->width = p_width;
+ rt->texture_ptr->height = p_height;
#
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- glDeleteRenderbuffers(1,&rt->fbo);
- glDeleteTextures(1,&rt->depth);
- glDeleteTextures(1,&rt->color);
- rt->fbo=0;
- rt->width=0;
- rt->height=0;
- rt->color=0;
- rt->depth=0;
- rt->texture_ptr->tex_id=0;
- rt->texture_ptr->active=false;
+ glDeleteRenderbuffers(1, &rt->fbo);
+ glDeleteTextures(1, &rt->depth);
+ glDeleteTextures(1, &rt->color);
+ rt->fbo = 0;
+ rt->width = 0;
+ rt->height = 0;
+ rt->color = 0;
+ rt->depth = 0;
+ rt->texture_ptr->tex_id = 0;
+ rt->texture_ptr->active = false;
WARN_PRINT("Could not create framebuffer!!");
}
glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer);
-
}
-RID RasterizerGLES2::render_target_get_texture(RID p_render_target) const{
+RID RasterizerGLES2::render_target_get_texture(RID p_render_target) const {
const RenderTarget *rt = render_target_owner.get(p_render_target);
- ERR_FAIL_COND_V(!rt,RID());
+ ERR_FAIL_COND_V(!rt, RID());
return rt->texture;
}
-bool RasterizerGLES2::render_target_renedered_in_frame(RID p_render_target){
+bool RasterizerGLES2::render_target_renedered_in_frame(RID p_render_target) {
RenderTarget *rt = render_target_owner.get(p_render_target);
- ERR_FAIL_COND_V(!rt,false);
- return rt->last_pass==frame;
+ ERR_FAIL_COND_V(!rt, false);
+ return rt->last_pass == frame;
}
-
/* RENDER API */
/* all calls (inside begin/end shadow) are always warranted to be in the following order: */
-
-
-
-
void RasterizerGLES2::begin_frame() {
-
-
-
_update_framebuffer();
glDepthFunc(GL_LEQUAL);
glFrontFace(GL_CW);
- //fragment_lighting=Globals::get_singleton()->get("rasterizer/use_fragment_lighting");
+//fragment_lighting=Globals::get_singleton()->get("rasterizer/use_fragment_lighting");
#ifdef TOOLS_ENABLED
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_PIXEL_SNAP,GLOBAL_DEF("display/use_2d_pixel_snap",false));
- shadow_filter=ShadowFilterTechnique(int(GlobalConfig::get_singleton()->get("rasterizer/shadow_filter")));
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_PIXEL_SNAP, GLOBAL_DEF("display/use_2d_pixel_snap", false));
+ shadow_filter = ShadowFilterTechnique(int(GlobalConfig::get_singleton()->get("rasterizer/shadow_filter")));
#endif
- canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_PCF5,shadow_filter==SHADOW_FILTER_PCF5);
- canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_PCF13,shadow_filter==SHADOW_FILTER_PCF13);
- canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_ESM,shadow_filter==SHADOW_FILTER_ESM);
+ canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_PCF5, shadow_filter == SHADOW_FILTER_PCF5);
+ canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_PCF13, shadow_filter == SHADOW_FILTER_PCF13);
+ canvas_shader.set_conditional(CanvasShaderGLES2::SHADOW_ESM, shadow_filter == SHADOW_FILTER_ESM);
- window_size = Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height );
+ window_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
- double time = (OS::get_singleton()->get_ticks_usec()/1000); // get msec
- time/=1000.0; // make secs
- time_delta=time-last_time;
- last_time=time;
+ double time = (OS::get_singleton()->get_ticks_usec() / 1000); // get msec
+ time /= 1000.0; // make secs
+ time_delta = time - last_time;
+ last_time = time;
frame++;
- _rinfo.vertex_count=0;
- _rinfo.object_count=0;
- _rinfo.mat_change_count=0;
- _rinfo.shader_change_count=0;
- _rinfo.ci_draw_commands=0;
- _rinfo.surface_count=0;
- _rinfo.draw_calls=0;
-
+ _rinfo.vertex_count = 0;
+ _rinfo.object_count = 0;
+ _rinfo.mat_change_count = 0;
+ _rinfo.shader_change_count = 0;
+ _rinfo.ci_draw_commands = 0;
+ _rinfo.surface_count = 0;
+ _rinfo.draw_calls = 0;
_update_fixed_materials();
- while(_shader_dirty_list.first()) {
+ while (_shader_dirty_list.first()) {
_update_shader(_shader_dirty_list.first()->self());
}
- while(_skeleton_dirty_list.first()) {
+ while (_skeleton_dirty_list.first()) {
+ Skeleton *s = _skeleton_dirty_list.first()->self();
- Skeleton *s=_skeleton_dirty_list.first()->self();
+ float *sk_float = (float *)skinned_buffer;
+ for (int i = 0; i < s->bones.size(); i++) {
- float *sk_float = (float*)skinned_buffer;
- for(int i=0;i<s->bones.size();i++) {
-
- float *m = &sk_float[i*12];
- const Skeleton::Bone &b=s->bones[i];
- m[0]=b.mtx[0][0];
- m[1]=b.mtx[1][0];
- m[2]=b.mtx[2][0];
- m[3]=b.mtx[3][0];
-
- m[4]=b.mtx[0][1];
- m[5]=b.mtx[1][1];
- m[6]=b.mtx[2][1];
- m[7]=b.mtx[3][1];
-
- m[8]=b.mtx[0][2];
- m[9]=b.mtx[1][2];
- m[10]=b.mtx[2][2];
- m[11]=b.mtx[3][2];
+ float *m = &sk_float[i * 12];
+ const Skeleton::Bone &b = s->bones[i];
+ m[0] = b.mtx[0][0];
+ m[1] = b.mtx[1][0];
+ m[2] = b.mtx[2][0];
+ m[3] = b.mtx[3][0];
+ m[4] = b.mtx[0][1];
+ m[5] = b.mtx[1][1];
+ m[6] = b.mtx[2][1];
+ m[7] = b.mtx[3][1];
+ m[8] = b.mtx[0][2];
+ m[9] = b.mtx[1][2];
+ m[10] = b.mtx[2][2];
+ m[11] = b.mtx[3][2];
}
-
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,s->tex_id);
- glTexSubImage2D(GL_TEXTURE_2D,0,0,0,nearest_power_of_2(s->bones.size()*3),1,GL_RGBA,GL_FLOAT,sk_float);
- _skeleton_dirty_list.remove( _skeleton_dirty_list.first() );
+ glBindTexture(GL_TEXTURE_2D, s->tex_id);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, nearest_power_of_2(s->bones.size() * 3), 1, GL_RGBA, GL_FLOAT, sk_float);
+ _skeleton_dirty_list.remove(_skeleton_dirty_list.first());
}
- while(_multimesh_dirty_list.first()) {
+ while (_multimesh_dirty_list.first()) {
+ MultiMesh *s = _multimesh_dirty_list.first()->self();
- MultiMesh *s=_multimesh_dirty_list.first()->self();
+ float *sk_float = (float *)skinned_buffer;
+ for (int i = 0; i < s->elements.size(); i++) {
- float *sk_float = (float*)skinned_buffer;
- for(int i=0;i<s->elements.size();i++) {
-
- float *m = &sk_float[i*16];
- const float *im=s->elements[i].matrix;
- for(int j=0;j<16;j++) {
- m[j]=im[j];
+ float *m = &sk_float[i * 16];
+ const float *im = s->elements[i].matrix;
+ for (int j = 0; j < 16; j++) {
+ m[j] = im[j];
}
-
}
-
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,s->tex_id);
- glTexSubImage2D(GL_TEXTURE_2D,0,0,0,s->tw,s->th,GL_RGBA,GL_FLOAT,sk_float);
- _multimesh_dirty_list.remove( _multimesh_dirty_list.first() );
+ glBindTexture(GL_TEXTURE_2D, s->tex_id);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, s->tw, s->th, GL_RGBA, GL_FLOAT, sk_float);
+ _multimesh_dirty_list.remove(_multimesh_dirty_list.first());
}
-
- draw_next_frame=false;
+ draw_next_frame = false;
//material_shader.set_uniform_default(MaterialShaderGLES2::SCREENZ_SCALE, Math::fmod(time, 3600.0));
/* nehe ?*/
@@ -4304,7 +4029,7 @@ void RasterizerGLES2::begin_frame() {
//glClear(GL_COLOR_BUFFER_BIT); //should not clear if anything else cleared..
}
-void RasterizerGLES2::capture_viewport(Image* r_capture) {
+void RasterizerGLES2::capture_viewport(Image *r_capture) {
#if 0
PoolVector<uint8_t> pixels;
pixels.resize(viewport.width*viewport.height*3);
@@ -4325,9 +4050,8 @@ void RasterizerGLES2::capture_viewport(Image* r_capture) {
r_capture->create(viewport.width,viewport.height,0,Image::FORMAT_RGB8,pixels);
#else
-
PoolVector<uint8_t> pixels;
- pixels.resize(viewport.width*viewport.height*4);
+ pixels.resize(viewport.width * viewport.height * 4);
PoolVector<uint8_t>::Write w = pixels.write();
glPixelStorei(GL_PACK_ALIGNMENT, 4);
@@ -4337,186 +4061,176 @@ void RasterizerGLES2::capture_viewport(Image* r_capture) {
#ifdef GLEW_ENABLED
glReadBuffer(GL_COLOR_ATTACHMENT0);
#endif
- glReadPixels( 0, 0, viewport.width, viewport.height,GL_RGBA,GL_UNSIGNED_BYTE,w.ptr() );
+ glReadPixels(0, 0, viewport.width, viewport.height, GL_RGBA, GL_UNSIGNED_BYTE, w.ptr());
} else {
// back?
- glReadPixels( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height,GL_RGBA,GL_UNSIGNED_BYTE,w.ptr());
+ glReadPixels(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height, GL_RGBA, GL_UNSIGNED_BYTE, w.ptr());
}
- bool flip = current_rt==NULL;
+ bool flip = current_rt == NULL;
if (flip) {
- uint32_t *imgptr = (uint32_t*)w.ptr();
- for(int y=0;y<(viewport.height/2);y++) {
+ uint32_t *imgptr = (uint32_t *)w.ptr();
+ for (int y = 0; y < (viewport.height / 2); y++) {
- uint32_t *ptr1 = &imgptr[y*viewport.width];
- uint32_t *ptr2 = &imgptr[(viewport.height-y-1)*viewport.width];
+ uint32_t *ptr1 = &imgptr[y * viewport.width];
+ uint32_t *ptr2 = &imgptr[(viewport.height - y - 1) * viewport.width];
- for(int x=0;x<viewport.width;x++) {
+ for (int x = 0; x < viewport.width; x++) {
uint32_t tmp = ptr1[x];
- ptr1[x]=ptr2[x];
- ptr2[x]=tmp;
+ ptr1[x] = ptr2[x];
+ ptr2[x] = tmp;
}
}
}
- w=PoolVector<uint8_t>::Write();
- r_capture->create(viewport.width,viewport.height,0,Image::FORMAT_RGBA8,pixels);
- //r_capture->flip_y();
-
+ w = PoolVector<uint8_t>::Write();
+ r_capture->create(viewport.width, viewport.height, 0, Image::FORMAT_RGBA8, pixels);
+//r_capture->flip_y();
#endif
-
}
-
-void RasterizerGLES2::clear_viewport(const Color& p_color) {
+void RasterizerGLES2::clear_viewport(const Color &p_color) {
if (current_rt || using_canvas_bg) {
- glScissor( 0, 0, viewport.width, viewport.height );
+ glScissor(0, 0, viewport.width, viewport.height);
} else {
- glScissor( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
+ glScissor(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height);
}
glEnable(GL_SCISSOR_TEST);
- glClearColor(p_color.r,p_color.g,p_color.b,p_color.a);
+ glClearColor(p_color.r, p_color.g, p_color.b, p_color.a);
glClear(GL_COLOR_BUFFER_BIT); //should not clear if anything else cleared..
glDisable(GL_SCISSOR_TEST);
};
-
void RasterizerGLES2::set_render_target(RID p_render_target, bool p_transparent_bg, bool p_vflip) {
-
-
if (!p_render_target.is_valid()) {
- glBindFramebuffer(GL_FRAMEBUFFER,base_framebuffer);
- current_rt=NULL;
- current_rt_vflip=false;
+ glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer);
+ current_rt = NULL;
+ current_rt_vflip = false;
} else {
RenderTarget *rt = render_target_owner.get(p_render_target);
ERR_FAIL_COND(!rt);
- ERR_FAIL_COND(rt->fbo==0);
- glBindFramebuffer(GL_FRAMEBUFFER,rt->fbo);
- current_rt=rt;
- current_rt_transparent=p_transparent_bg;
- current_rt_vflip=!p_vflip;
+ ERR_FAIL_COND(rt->fbo == 0);
+ glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
+ current_rt = rt;
+ current_rt_transparent = p_transparent_bg;
+ current_rt_vflip = !p_vflip;
}
-
}
-void RasterizerGLES2::set_viewport(const VS::ViewportRect& p_viewport) {
+void RasterizerGLES2::set_viewport(const VS::ViewportRect &p_viewport) {
- viewport=p_viewport;
+ viewport = p_viewport;
//viewport.width/=2;
//viewport.height/=2;
//print_line("viewport: "+itos(p_viewport.x)+","+itos(p_viewport.y)+","+itos(p_viewport.width)+","+itos(p_viewport.height));
if (current_rt) {
- glViewport( 0, 0,viewport.width, viewport.height );
+ glViewport(0, 0, viewport.width, viewport.height);
} else {
- glViewport( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
+ glViewport(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height);
}
}
-void RasterizerGLES2::begin_scene(RID p_viewport_data,RID p_env,VS::ScenarioDebugMode p_debug) {
-
+void RasterizerGLES2::begin_scene(RID p_viewport_data, RID p_env, VS::ScenarioDebugMode p_debug) {
- current_debug=p_debug;
+ current_debug = p_debug;
opaque_render_list.clear();
alpha_render_list.clear();
- light_instance_count=0;
+ light_instance_count = 0;
current_env = p_env.is_valid() ? environment_owner.get(p_env) : NULL;
scene_pass++;
- last_light_id=0;
- directional_light_count=0;
- lights_use_shadow=false;
- texscreen_used=false;
- current_vd=viewport_data_owner.get(p_viewport_data);
- if (current_debug==VS::SCENARIO_DEBUG_WIREFRAME) {
+ last_light_id = 0;
+ directional_light_count = 0;
+ lights_use_shadow = false;
+ texscreen_used = false;
+ current_vd = viewport_data_owner.get(p_viewport_data);
+ if (current_debug == VS::SCENARIO_DEBUG_WIREFRAME) {
#ifdef GLEW_ENABLED
- glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
}
//set state
glCullFace(GL_FRONT);
- cull_front=true;
+ cull_front = true;
};
-void RasterizerGLES2::begin_shadow_map( RID p_light_instance, int p_shadow_pass ) {
+void RasterizerGLES2::begin_shadow_map(RID p_light_instance, int p_shadow_pass) {
ERR_FAIL_COND(shadow);
shadow = light_instance_owner.get(p_light_instance);
- shadow_pass=p_shadow_pass;
+ shadow_pass = p_shadow_pass;
ERR_FAIL_COND(!shadow);
opaque_render_list.clear();
alpha_render_list.clear();
//pre_zpass_render_list.clear();
- light_instance_count=0;
+ light_instance_count = 0;
glCullFace(GL_FRONT);
- cull_front=true;
-
+ cull_front = true;
}
-void RasterizerGLES2::set_camera(const Transform& p_world,const CameraMatrix& p_projection,bool p_ortho_hint) {
+void RasterizerGLES2::set_camera(const Transform &p_world, const CameraMatrix &p_projection, bool p_ortho_hint) {
- camera_transform=p_world;
+ camera_transform = p_world;
if (current_rt && current_rt_vflip) {
- camera_transform.basis.set_axis(1,-camera_transform.basis.get_axis(1));
+ camera_transform.basis.set_axis(1, -camera_transform.basis.get_axis(1));
}
- camera_transform_inverse=camera_transform.inverse();
- camera_projection=p_projection;
- camera_plane = Plane( camera_transform.origin, -camera_transform.basis.get_axis(2) );
- camera_z_near=camera_projection.get_z_near();
- camera_z_far=camera_projection.get_z_far();
- camera_projection.get_viewport_size(camera_vp_size.x,camera_vp_size.y);
- camera_ortho=p_ortho_hint;
+ camera_transform_inverse = camera_transform.inverse();
+ camera_projection = p_projection;
+ camera_plane = Plane(camera_transform.origin, -camera_transform.basis.get_axis(2));
+ camera_z_near = camera_projection.get_z_near();
+ camera_z_far = camera_projection.get_z_far();
+ camera_projection.get_viewport_size(camera_vp_size.x, camera_vp_size.y);
+ camera_ortho = p_ortho_hint;
}
-void RasterizerGLES2::add_light( RID p_light_instance ) {
+void RasterizerGLES2::add_light(RID p_light_instance) {
#define LIGHT_FADE_TRESHOLD 0.05
- ERR_FAIL_COND( light_instance_count >= MAX_SCENE_LIGHTS );
+ ERR_FAIL_COND(light_instance_count >= MAX_SCENE_LIGHTS);
LightInstance *li = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!li);
-
- switch(li->base->type) {
+ switch (li->base->type) {
case VS::LIGHT_DIRECTIONAL: {
- ERR_FAIL_COND( directional_light_count >= RenderList::MAX_LIGHTS);
- directional_lights[directional_light_count++]=li;
+ ERR_FAIL_COND(directional_light_count >= RenderList::MAX_LIGHTS);
+ directional_lights[directional_light_count++] = li;
if (li->base->shadow_enabled) {
CameraMatrix bias;
bias.set_light_bias();
- int passes=light_instance_get_shadow_passes(p_light_instance);
+ int passes = light_instance_get_shadow_passes(p_light_instance);
- for(int i=0;i<passes;i++) {
- Transform modelview=Transform(camera_transform_inverse * li->custom_transform[i]).inverse();
+ for (int i = 0; i < passes; i++) {
+ Transform modelview = Transform(camera_transform_inverse * li->custom_transform[i]).inverse();
li->shadow_projection[i] = bias * li->custom_projection[i] * modelview;
}
- lights_use_shadow=true;
+ lights_use_shadow = true;
}
} break;
case VS::LIGHT_OMNI: {
if (li->base->shadow_enabled) {
li->shadow_projection[0] = Transform(camera_transform_inverse * li->transform).inverse();
- lights_use_shadow=true;
+ lights_use_shadow = true;
}
} break;
case VS::LIGHT_SPOT: {
@@ -4524,34 +4238,29 @@ void RasterizerGLES2::add_light( RID p_light_instance ) {
if (li->base->shadow_enabled) {
CameraMatrix bias;
bias.set_light_bias();
- Transform modelview=Transform(camera_transform_inverse * li->transform).inverse();
+ Transform modelview = Transform(camera_transform_inverse * li->transform).inverse();
li->shadow_projection[0] = bias * li->projection * modelview;
- lights_use_shadow=true;
+ lights_use_shadow = true;
}
} break;
-
}
-
/* make light hash */
// actually, not really a hash, but helps to sort the lights
// and avoid recompiling redudant shader versions
+ li->last_pass = scene_pass;
+ li->sort_key = light_instance_count;
- li->last_pass=scene_pass;
- li->sort_key=light_instance_count;
-
- light_instances[light_instance_count++]=li;
-
+ light_instances[light_instance_count++] = li;
}
-void RasterizerGLES2::_update_shader( Shader* p_shader) const {
+void RasterizerGLES2::_update_shader(Shader *p_shader) const {
- _shader_dirty_list.remove( &p_shader->dirty_list );
-
- p_shader->valid=false;
+ _shader_dirty_list.remove(&p_shader->dirty_list);
+ p_shader->valid = false;
p_shader->uniforms.clear();
Vector<StringName> uniform_names;
@@ -4562,18 +4271,17 @@ void RasterizerGLES2::_update_shader( Shader* p_shader) const {
ShaderCompilerGLES2::Flags fragment_flags;
ShaderCompilerGLES2::Flags light_flags;
- if (p_shader->mode==VS::SHADER_MATERIAL) {
- Error err = shader_precompiler.compile(p_shader->vertex_code,ShaderLanguage::SHADER_MATERIAL_VERTEX,vertex_code,vertex_globals,vertex_flags,&p_shader->uniforms);
+ if (p_shader->mode == VS::SHADER_MATERIAL) {
+ Error err = shader_precompiler.compile(p_shader->vertex_code, ShaderLanguage::SHADER_MATERIAL_VERTEX, vertex_code, vertex_globals, vertex_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
- } else if (p_shader->mode==VS::SHADER_CANVAS_ITEM) {
+ } else if (p_shader->mode == VS::SHADER_CANVAS_ITEM) {
- Error err = shader_precompiler.compile(p_shader->vertex_code,ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX,vertex_code,vertex_globals,vertex_flags,&p_shader->uniforms);
+ Error err = shader_precompiler.compile(p_shader->vertex_code, ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX, vertex_code, vertex_globals, vertex_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
-
}
//print_line("compiled vertex: "+vertex_code);
@@ -4583,60 +4291,58 @@ void RasterizerGLES2::_update_shader( Shader* p_shader) const {
String fragment_code;
String fragment_globals;
- if (p_shader->mode==VS::SHADER_MATERIAL) {
- Error err = shader_precompiler.compile(p_shader->fragment_code,ShaderLanguage::SHADER_MATERIAL_FRAGMENT,fragment_code,fragment_globals,fragment_flags,&p_shader->uniforms);
+ if (p_shader->mode == VS::SHADER_MATERIAL) {
+ Error err = shader_precompiler.compile(p_shader->fragment_code, ShaderLanguage::SHADER_MATERIAL_FRAGMENT, fragment_code, fragment_globals, fragment_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
- } else if (p_shader->mode==VS::SHADER_CANVAS_ITEM) {
- Error err = shader_precompiler.compile(p_shader->fragment_code,ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT,fragment_code,fragment_globals,fragment_flags,&p_shader->uniforms);
+ } else if (p_shader->mode == VS::SHADER_CANVAS_ITEM) {
+ Error err = shader_precompiler.compile(p_shader->fragment_code, ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT, fragment_code, fragment_globals, fragment_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
}
-
String light_code;
String light_globals;
- if (p_shader->mode==VS::SHADER_MATERIAL) {
+ if (p_shader->mode == VS::SHADER_MATERIAL) {
- Error err = shader_precompiler.compile(p_shader->light_code,(ShaderLanguage::SHADER_MATERIAL_LIGHT),light_code,light_globals,light_flags,&p_shader->uniforms);
+ Error err = shader_precompiler.compile(p_shader->light_code, (ShaderLanguage::SHADER_MATERIAL_LIGHT), light_code, light_globals, light_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
- } else if (p_shader->mode==VS::SHADER_CANVAS_ITEM) {
- Error err = shader_precompiler.compile(p_shader->light_code,(ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT),light_code,light_globals,light_flags,&p_shader->uniforms);
+ } else if (p_shader->mode == VS::SHADER_CANVAS_ITEM) {
+ Error err = shader_precompiler.compile(p_shader->light_code, (ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT), light_code, light_globals, light_flags, &p_shader->uniforms);
if (err) {
return; //invalid
}
}
- fragment_globals+=light_globals; //both fragment anyway
-
+ fragment_globals += light_globals; //both fragment anyway
//print_line("compiled fragment: "+fragment_code);
//("compiled fragment globals: "+fragment_globals);
//print_line("UCF: "+itos(p_shader->uniforms.size()));
- int first_tex_index=0xFFFFF;
- p_shader->first_texture=StringName();
+ int first_tex_index = 0xFFFFF;
+ p_shader->first_texture = StringName();
- for(Map<StringName,ShaderLanguage::Uniform>::Element *E=p_shader->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, ShaderLanguage::Uniform>::Element *E = p_shader->uniforms.front(); E; E = E->next()) {
- uniform_names.push_back("_"+String(E->key()));
- if (E->get().type==ShaderLanguage::TYPE_TEXTURE && E->get().order<first_tex_index) {
- p_shader->first_texture=E->key();
- first_tex_index=E->get().order;
+ uniform_names.push_back("_" + String(E->key()));
+ if (E->get().type == ShaderLanguage::TYPE_TEXTURE && E->get().order < first_tex_index) {
+ p_shader->first_texture = E->key();
+ first_tex_index = E->get().order;
}
}
- bool uses_time=false;
+ bool uses_time = false;
- if (p_shader->mode==VS::SHADER_MATERIAL) {
+ if (p_shader->mode == VS::SHADER_MATERIAL) {
//print_line("setting code to id.. "+itos(p_shader->custom_code_id));
- Vector<const char*> enablers;
+ Vector<const char *> enablers;
if (fragment_flags.use_color_interp || vertex_flags.use_color_interp)
enablers.push_back("#define ENABLE_COLOR_INTERP\n");
if (fragment_flags.use_uv_interp || vertex_flags.use_uv_interp)
@@ -4669,20 +4375,20 @@ void RasterizerGLES2::_update_shader( Shader* p_shader) const {
}
if (light_flags.uses_time || fragment_flags.uses_time || vertex_flags.uses_time) {
enablers.push_back("#define USE_TIME\n");
- uses_time=true;
+ uses_time = true;
}
if (vertex_flags.vertex_code_writes_position) {
enablers.push_back("#define VERTEX_SHADER_WRITE_POSITION\n");
}
- material_shader.set_custom_shader_code(p_shader->custom_code_id,vertex_code, vertex_globals,fragment_code, light_code, fragment_globals,uniform_names,enablers);
- } else if (p_shader->mode==VS::SHADER_CANVAS_ITEM) {
+ material_shader.set_custom_shader_code(p_shader->custom_code_id, vertex_code, vertex_globals, fragment_code, light_code, fragment_globals, uniform_names, enablers);
+ } else if (p_shader->mode == VS::SHADER_CANVAS_ITEM) {
- Vector<const char*> enablers;
+ Vector<const char *> enablers;
if (light_flags.uses_time || fragment_flags.uses_time || vertex_flags.uses_time) {
enablers.push_back("#define USE_TIME\n");
- uses_time=true;
+ uses_time = true;
}
if (fragment_flags.uses_normal) {
enablers.push_back("#define NORMAL_USED\n");
@@ -4714,117 +4420,109 @@ void RasterizerGLES2::_update_shader( Shader* p_shader) const {
if (vertex_flags.uses_worldvec) {
enablers.push_back("#define USE_WORLD_VEC\n");
}
- canvas_shader.set_custom_shader_code(p_shader->custom_code_id,vertex_code, vertex_globals,fragment_code, light_code, fragment_globals,uniform_names,enablers);
+ canvas_shader.set_custom_shader_code(p_shader->custom_code_id, vertex_code, vertex_globals, fragment_code, light_code, fragment_globals, uniform_names, enablers);
//postprocess_shader.set_custom_shader_code(p_shader->custom_code_id,vertex_code, vertex_globals,fragment_code, fragment_globals,uniform_names);
}
- p_shader->valid=true;
- p_shader->has_alpha=fragment_flags.uses_alpha || fragment_flags.uses_texscreen;
- p_shader->writes_vertex=vertex_flags.vertex_code_writes_vertex;
- p_shader->uses_discard=fragment_flags.uses_discard;
- p_shader->has_texscreen=fragment_flags.uses_texscreen;
- p_shader->has_screen_uv=fragment_flags.uses_screen_uv;
- p_shader->can_zpass=!fragment_flags.uses_discard && !vertex_flags.vertex_code_writes_vertex;
- p_shader->uses_normal=fragment_flags.uses_normal || light_flags.uses_normal;
- p_shader->uses_time=uses_time;
- p_shader->uses_texpixel_size=fragment_flags.uses_texpixel_size;
+ p_shader->valid = true;
+ p_shader->has_alpha = fragment_flags.uses_alpha || fragment_flags.uses_texscreen;
+ p_shader->writes_vertex = vertex_flags.vertex_code_writes_vertex;
+ p_shader->uses_discard = fragment_flags.uses_discard;
+ p_shader->has_texscreen = fragment_flags.uses_texscreen;
+ p_shader->has_screen_uv = fragment_flags.uses_screen_uv;
+ p_shader->can_zpass = !fragment_flags.uses_discard && !vertex_flags.vertex_code_writes_vertex;
+ p_shader->uses_normal = fragment_flags.uses_normal || light_flags.uses_normal;
+ p_shader->uses_time = uses_time;
+ p_shader->uses_texpixel_size = fragment_flags.uses_texpixel_size;
p_shader->version++;
-
}
+void RasterizerGLES2::_add_geometry(const Geometry *p_geometry, const InstanceData *p_instance, const Geometry *p_geometry_cmp, const GeometryOwner *p_owner, int p_material) {
-void RasterizerGLES2::_add_geometry( const Geometry* p_geometry, const InstanceData *p_instance, const Geometry *p_geometry_cmp, const GeometryOwner *p_owner,int p_material) {
-
- Material *m=NULL;
- RID m_src=p_instance->material_override.is_valid() ? p_instance->material_override :(p_material>=0?p_instance->materials[p_material]:p_geometry->material);
+ Material *m = NULL;
+ RID m_src = p_instance->material_override.is_valid() ? p_instance->material_override : (p_material >= 0 ? p_instance->materials[p_material] : p_geometry->material);
#ifdef DEBUG_ENABLED
- if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) {
- m_src=overdraw_material;
+ if (current_debug == VS::SCENARIO_DEBUG_OVERDRAW) {
+ m_src = overdraw_material;
}
#endif
if (m_src)
- m=material_owner.get( m_src );
+ m = material_owner.get(m_src);
if (!m) {
- m=material_owner.get( default_material );
+ m = material_owner.get(default_material);
}
ERR_FAIL_COND(!m);
- if (m->last_pass!=frame) {
+ if (m->last_pass != frame) {
if (m->shader.is_valid()) {
- m->shader_cache=shader_owner.get(m->shader);
+ m->shader_cache = shader_owner.get(m->shader);
if (m->shader_cache) {
-
-
if (!m->shader_cache->valid) {
- m->shader_cache=NULL;
+ m->shader_cache = NULL;
} else {
if (m->shader_cache->has_texscreen)
- texscreen_used=true;
+ texscreen_used = true;
}
} else {
- m->shader=RID();
+ m->shader = RID();
}
} else {
- m->shader_cache=NULL;
+ m->shader_cache = NULL;
}
- m->last_pass=frame;
+ m->last_pass = frame;
}
+ RenderList *render_list = NULL;
-
- RenderList *render_list=NULL;
-
- bool has_base_alpha=(m->shader_cache && m->shader_cache->has_alpha);
- bool has_blend_alpha=m->blend_mode!=VS::MATERIAL_BLEND_MODE_MIX || m->flags[VS::MATERIAL_FLAG_ONTOP];
+ bool has_base_alpha = (m->shader_cache && m->shader_cache->has_alpha);
+ bool has_blend_alpha = m->blend_mode != VS::MATERIAL_BLEND_MODE_MIX || m->flags[VS::MATERIAL_FLAG_ONTOP];
bool has_alpha = has_base_alpha || has_blend_alpha;
-
if (shadow) {
- if (has_blend_alpha || (has_base_alpha && m->depth_draw_mode!=VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA))
+ if (has_blend_alpha || (has_base_alpha && m->depth_draw_mode != VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA))
return; //bye
- if (!m->shader_cache || (!m->shader_cache->writes_vertex && !m->shader_cache->uses_discard && m->depth_draw_mode!=VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA)) {
+ if (!m->shader_cache || (!m->shader_cache->writes_vertex && !m->shader_cache->uses_discard && m->depth_draw_mode != VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA)) {
//shader does not use discard and does not write a vertex position, use generic material
if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED)
m = shadow_mat_double_sided_ptr;
else
m = shadow_mat_ptr;
- if (m->last_pass!=frame) {
+ if (m->last_pass != frame) {
if (m->shader.is_valid()) {
- m->shader_cache=shader_owner.get(m->shader);
+ m->shader_cache = shader_owner.get(m->shader);
if (m->shader_cache) {
-
if (!m->shader_cache->valid)
- m->shader_cache=NULL;
+ m->shader_cache = NULL;
} else {
- m->shader=RID();
+ m->shader = RID();
}
} else {
- m->shader_cache=NULL;
+ m->shader_cache = NULL;
}
- m->last_pass=frame;
+ m->last_pass = frame;
}
}
render_list = &opaque_render_list;
- /* notyet
+ /* notyet
if (!m->shader_cache || m->shader_cache->can_zpass)
render_list = &alpha_render_list;
} else {
@@ -4836,56 +4534,51 @@ void RasterizerGLES2::_add_geometry( const Geometry* p_geometry, const InstanceD
render_list = &alpha_render_list;
} else {
render_list = &opaque_render_list;
-
}
}
-
RenderList::Element *e = render_list->add_element();
if (!e)
return;
- e->geometry=p_geometry;
- e->geometry_cmp=p_geometry_cmp;
- e->material=m;
- e->instance=p_instance;
+ e->geometry = p_geometry;
+ e->geometry_cmp = p_geometry_cmp;
+ e->material = m;
+ e->instance = p_instance;
if (camera_ortho) {
- e->depth=camera_plane.distance_to(p_instance->transform.origin);
+ e->depth = camera_plane.distance_to(p_instance->transform.origin);
} else {
- e->depth=camera_transform.origin.distance_to(p_instance->transform.origin);
+ e->depth = camera_transform.origin.distance_to(p_instance->transform.origin);
}
- e->owner=p_owner;
- e->light_type=0;
- e->additive=false;
- e->additive_ptr=&e->additive;
- e->sort_flags=0;
-
+ e->owner = p_owner;
+ e->light_type = 0;
+ e->additive = false;
+ e->additive_ptr = &e->additive;
+ e->sort_flags = 0;
if (p_instance->skeleton.is_valid()) {
- e->skeleton=skeleton_owner.get(p_instance->skeleton);
+ e->skeleton = skeleton_owner.get(p_instance->skeleton);
if (!e->skeleton)
- const_cast<InstanceData*>(p_instance)->skeleton=RID();
+ const_cast<InstanceData *>(p_instance)->skeleton = RID();
else
- e->sort_flags|=RenderList::SORT_FLAG_SKELETON;
+ e->sort_flags |= RenderList::SORT_FLAG_SKELETON;
} else {
- e->skeleton=NULL;
-
+ e->skeleton = NULL;
}
- if (e->geometry->type==Geometry::GEOMETRY_MULTISURFACE)
- e->sort_flags|=RenderList::SORT_FLAG_INSTANCING;
-
+ if (e->geometry->type == Geometry::GEOMETRY_MULTISURFACE)
+ e->sort_flags |= RenderList::SORT_FLAG_INSTANCING;
- e->mirror=p_instance->mirror;
+ e->mirror = p_instance->mirror;
if (m->flags[VS::MATERIAL_FLAG_INVERT_FACES])
- e->mirror=!e->mirror;
+ e->mirror = !e->mirror;
//e->light_type=0xFF; // no lights!
- e->light_type=3; //light type 3 is no light?
- e->light=0xFFFF;
+ e->light_type = 3; //light type 3 is no light?
+ e->light = 0xFFFF;
- if (!shadow && !has_blend_alpha && has_alpha && m->depth_draw_mode==VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA) {
+ if (!shadow && !has_blend_alpha && has_alpha && m->depth_draw_mode == VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA) {
//if nothing exists, add this element as opaque too
RenderList::Element *oe = opaque_render_list.add_element();
@@ -4893,108 +4586,96 @@ void RasterizerGLES2::_add_geometry( const Geometry* p_geometry, const InstanceD
if (!oe)
return;
- memcpy(oe,e,sizeof(RenderList::Element));
- oe->additive_ptr=&oe->additive;
+ memcpy(oe, e, sizeof(RenderList::Element));
+ oe->additive_ptr = &oe->additive;
}
- if (shadow || m->flags[VS::MATERIAL_FLAG_UNSHADED] || current_debug==VS::SCENARIO_DEBUG_SHADELESS) {
+ if (shadow || m->flags[VS::MATERIAL_FLAG_UNSHADED] || current_debug == VS::SCENARIO_DEBUG_SHADELESS) {
- e->light_type=0x7F; //unshaded is zero
+ e->light_type = 0x7F; //unshaded is zero
} else {
- bool duplicate=false;
+ bool duplicate = false;
-
- for(int i=0;i<directional_light_count;i++) {
+ for (int i = 0; i < directional_light_count; i++) {
uint16_t sort_key = directional_lights[i]->sort_key;
uint8_t light_type = VS::LIGHT_DIRECTIONAL;
if (directional_lights[i]->base->shadow_enabled) {
- light_type|=0x8;
- if (directional_lights[i]->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS)
- light_type|=0x10;
- else if (directional_lights[i]->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS)
- light_type|=0x30;
-
+ light_type |= 0x8;
+ if (directional_lights[i]->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS)
+ light_type |= 0x10;
+ else if (directional_lights[i]->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS)
+ light_type |= 0x30;
}
RenderList::Element *ec;
if (duplicate) {
ec = render_list->add_element();
- memcpy(ec,e,sizeof(RenderList::Element));
+ memcpy(ec, e, sizeof(RenderList::Element));
} else {
- ec=e;
- duplicate=true;
+ ec = e;
+ duplicate = true;
}
- ec->light_type=light_type;
- ec->light=sort_key;
- ec->additive_ptr=&e->additive;
-
+ ec->light_type = light_type;
+ ec->light = sort_key;
+ ec->additive_ptr = &e->additive;
}
-
const RID *liptr = p_instance->light_instances.ptr();
- int ilc=p_instance->light_instances.size();
-
-
+ int ilc = p_instance->light_instances.size();
- for(int i=0;i<ilc;i++) {
+ for (int i = 0; i < ilc; i++) {
- LightInstance *li=light_instance_owner.get( liptr[i] );
- if (!li || li->last_pass!=scene_pass) //lit by light not in visible scene
+ LightInstance *li = light_instance_owner.get(liptr[i]);
+ if (!li || li->last_pass != scene_pass) //lit by light not in visible scene
continue;
- uint8_t light_type=li->base->type|0x40; //penalty to ensure directionals always go first
+ uint8_t light_type = li->base->type | 0x40; //penalty to ensure directionals always go first
if (li->base->shadow_enabled) {
- light_type|=0x8;
+ light_type |= 0x8;
}
- uint16_t sort_key =li->sort_key;
+ uint16_t sort_key = li->sort_key;
RenderList::Element *ec;
if (duplicate) {
ec = render_list->add_element();
- memcpy(ec,e,sizeof(RenderList::Element));
+ memcpy(ec, e, sizeof(RenderList::Element));
} else {
- duplicate=true;
- ec=e;
+ duplicate = true;
+ ec = e;
}
- ec->light_type=light_type;
- ec->light=sort_key;
- ec->additive_ptr=&e->additive;
-
+ ec->light_type = light_type;
+ ec->light = sort_key;
+ ec->additive_ptr = &e->additive;
}
-
-
-
}
DEBUG_TEST_ERROR("Add Geometry");
-
}
-void RasterizerGLES2::add_mesh( const RID& p_mesh, const InstanceData *p_data) {
+void RasterizerGLES2::add_mesh(const RID &p_mesh, const InstanceData *p_data) {
Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
int ssize = mesh->surfaces.size();
- for (int i=0;i<ssize;i++) {
+ for (int i = 0; i < ssize; i++) {
int mat_idx = p_data->materials[i].is_valid() ? i : -1;
Surface *s = mesh->surfaces[i];
- _add_geometry(s,p_data,s,NULL,mat_idx);
+ _add_geometry(s, p_data, s, NULL, mat_idx);
}
- mesh->last_pass=frame;
-
+ mesh->last_pass = frame;
}
-void RasterizerGLES2::add_multimesh( const RID& p_multimesh, const InstanceData *p_data){
+void RasterizerGLES2::add_multimesh(const RID &p_multimesh, const InstanceData *p_data) {
MultiMesh *multimesh = multimesh_owner.get(p_multimesh);
ERR_FAIL_COND(!multimesh);
@@ -5008,52 +4689,46 @@ void RasterizerGLES2::add_multimesh( const RID& p_multimesh, const InstanceData
ERR_FAIL_COND(!mesh);
int surf_count = mesh->surfaces.size();
- if (multimesh->last_pass!=scene_pass) {
+ if (multimesh->last_pass != scene_pass) {
multimesh->cache_surfaces.resize(surf_count);
- for(int i=0;i<surf_count;i++) {
+ for (int i = 0; i < surf_count; i++) {
- multimesh->cache_surfaces[i].material=mesh->surfaces[i]->material;
- multimesh->cache_surfaces[i].has_alpha=mesh->surfaces[i]->has_alpha;
- multimesh->cache_surfaces[i].surface=mesh->surfaces[i];
+ multimesh->cache_surfaces[i].material = mesh->surfaces[i]->material;
+ multimesh->cache_surfaces[i].has_alpha = mesh->surfaces[i]->has_alpha;
+ multimesh->cache_surfaces[i].surface = mesh->surfaces[i];
}
- multimesh->last_pass=scene_pass;
+ multimesh->last_pass = scene_pass;
}
- for(int i=0;i<surf_count;i++) {
+ for (int i = 0; i < surf_count; i++) {
- _add_geometry(&multimesh->cache_surfaces[i],p_data,multimesh->cache_surfaces[i].surface,multimesh);
+ _add_geometry(&multimesh->cache_surfaces[i], p_data, multimesh->cache_surfaces[i].surface, multimesh);
}
-
-
}
-void RasterizerGLES2::add_immediate( const RID& p_immediate, const InstanceData *p_data) {
-
+void RasterizerGLES2::add_immediate(const RID &p_immediate, const InstanceData *p_data) {
Immediate *immediate = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!immediate);
- _add_geometry(immediate,p_data,immediate,NULL);
-
+ _add_geometry(immediate, p_data, immediate, NULL);
}
-
-void RasterizerGLES2::add_particles( const RID& p_particle_instance, const InstanceData *p_data){
+void RasterizerGLES2::add_particles(const RID &p_particle_instance, const InstanceData *p_data) {
//print_line("adding particles");
ParticlesInstance *particles_instance = particles_instance_owner.get(p_particle_instance);
ERR_FAIL_COND(!particles_instance);
- Particles *p=particles_owner.get( particles_instance->particles );
+ Particles *p = particles_owner.get(particles_instance->particles);
ERR_FAIL_COND(!p);
- _add_geometry(p,p_data,p,particles_instance);
- draw_next_frame=true;
-
+ _add_geometry(p, p_data, p, particles_instance);
+ draw_next_frame = true;
}
-Color RasterizerGLES2::_convert_color(const Color& p_color) {
+Color RasterizerGLES2::_convert_color(const Color &p_color) {
if (current_env && current_env->fx_enabled[VS::ENV_FX_SRGB])
return p_color.to_linear();
@@ -5061,51 +4736,48 @@ Color RasterizerGLES2::_convert_color(const Color& p_color) {
return p_color;
}
-void RasterizerGLES2::_set_cull(bool p_front,bool p_reverse_cull) {
+void RasterizerGLES2::_set_cull(bool p_front, bool p_reverse_cull) {
bool front = p_front;
if (p_reverse_cull)
- front=!front;
+ front = !front;
- if (front!=cull_front) {
+ if (front != cull_front) {
- glCullFace(front?GL_FRONT:GL_BACK);
- cull_front=front;
+ glCullFace(front ? GL_FRONT : GL_BACK);
+ cull_front = front;
}
}
-
_FORCE_INLINE_ void RasterizerGLES2::_update_material_shader_params(Material *p_material) const {
-
- Map<StringName,Material::UniformData> old_mparams=p_material->shader_params;
- Map<StringName,Material::UniformData> &mparams=p_material->shader_params;
+ Map<StringName, Material::UniformData> old_mparams = p_material->shader_params;
+ Map<StringName, Material::UniformData> &mparams = p_material->shader_params;
mparams.clear();
- int idx=0;
- for(Map<StringName,ShaderLanguage::Uniform>::Element *E=p_material->shader_cache->uniforms.front();E;E=E->next()) {
+ int idx = 0;
+ for (Map<StringName, ShaderLanguage::Uniform>::Element *E = p_material->shader_cache->uniforms.front(); E; E = E->next()) {
Material::UniformData ud;
- bool keep=true; //keep material value
+ bool keep = true; //keep material value
- Map<StringName,Material::UniformData>::Element *OLD=old_mparams.find(E->key());
+ Map<StringName, Material::UniformData>::Element *OLD = old_mparams.find(E->key());
bool has_old = OLD;
- bool old_inuse=has_old && old_mparams[E->key()].inuse;
+ bool old_inuse = has_old && old_mparams[E->key()].inuse;
- ud.istexture=(E->get().type==ShaderLanguage::TYPE_TEXTURE || E->get().type==ShaderLanguage::TYPE_CUBEMAP);
+ ud.istexture = (E->get().type == ShaderLanguage::TYPE_TEXTURE || E->get().type == ShaderLanguage::TYPE_CUBEMAP);
if (!has_old || !old_inuse) {
- keep=false;
- }
- else if (OLD->get().value.get_type()!=E->value().default_value.get_type()) {
+ keep = false;
+ } else if (OLD->get().value.get_type() != E->value().default_value.get_type()) {
- if (OLD->get().value.get_type()==Variant::INT && E->get().type==ShaderLanguage::TYPE_FLOAT) {
+ if (OLD->get().value.get_type() == Variant::INT && E->get().type == ShaderLanguage::TYPE_FLOAT) {
//handle common mistake using shaders (feeding ints instead of float)
- OLD->get().value=float(OLD->get().value);
- keep=true;
- } else if (!ud.istexture && E->value().default_value.get_type()!=Variant::NIL) {
+ OLD->get().value = float(OLD->get().value);
+ keep = true;
+ } else if (!ud.istexture && E->value().default_value.get_type() != Variant::NIL) {
- keep=false;
+ keep = false;
}
//type changed between old and new
/* if (old_mparams[E->key()].value.get_type()==Variant::OBJECT) {
@@ -5118,17 +4790,16 @@ _FORCE_INLINE_ void RasterizerGLES2::_update_material_shader_params(Material *p_
;
}
-
if (keep) {
- ud.value=old_mparams[E->key()].value;
+ ud.value = old_mparams[E->key()].value;
//print_line("KEEP: "+String(E->key()));
} else {
if (ud.istexture && p_material->shader_cache->default_textures.has(E->key()))
- ud.value=p_material->shader_cache->default_textures[E->key()];
+ ud.value = p_material->shader_cache->default_textures[E->key()];
else
- ud.value=E->value().default_value;
- old_inuse=false; //if reverted to default, obviously did not work
+ ud.value = E->value().default_value;
+ old_inuse = false; //if reverted to default, obviously did not work
/*
print_line("NEW: "+String(E->key())+" because: hasold-"+itos(old_mparams.has(E->key())));
@@ -5137,17 +4808,15 @@ _FORCE_INLINE_ void RasterizerGLES2::_update_material_shader_params(Material *p_
*/
}
-
- ud.index=idx++;
- ud.inuse=old_inuse;
- mparams[E->key()]=ud;
+ ud.index = idx++;
+ ud.inuse = old_inuse;
+ mparams[E->key()] = ud;
}
- p_material->shader_version=p_material->shader_cache->version;
-
+ p_material->shader_version = p_material->shader_cache->version;
}
-bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material *p_material,bool p_no_const_light,bool p_opaque_pass) {
+bool RasterizerGLES2::_setup_material(const Geometry *p_geometry, const Material *p_material, bool p_no_const_light, bool p_opaque_pass) {
if (p_material->flags[VS::MATERIAL_FLAG_DOUBLE_SIDED]) {
glDisable(GL_CULL_FACE);
@@ -5167,56 +4836,48 @@ bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material
if (p_material->line_width)
glLineWidth(p_material->line_width);
-
//all goes to false by default
- material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PASS,shadow!=NULL);
- material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PCF,shadow_filter==SHADOW_FILTER_PCF5 || shadow_filter==SHADOW_FILTER_PCF13);
- material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PCF_HQ,shadow_filter==SHADOW_FILTER_PCF13);
- material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_ESM,shadow_filter==SHADOW_FILTER_ESM);
- material_shader.set_conditional(MaterialShaderGLES2::USE_LIGHTMAP_ON_UV2,p_material->flags[VS::MATERIAL_FLAG_LIGHTMAP_ON_UV2]);
- material_shader.set_conditional(MaterialShaderGLES2::USE_COLOR_ATTRIB_SRGB_TO_LINEAR,p_material->flags[VS::MATERIAL_FLAG_COLOR_ARRAY_SRGB] && current_env && current_env->fx_enabled[VS::ENV_FX_SRGB]);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PASS, shadow != NULL);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PCF, shadow_filter == SHADOW_FILTER_PCF5 || shadow_filter == SHADOW_FILTER_PCF13);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_PCF_HQ, shadow_filter == SHADOW_FILTER_PCF13);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SHADOW_ESM, shadow_filter == SHADOW_FILTER_ESM);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_LIGHTMAP_ON_UV2, p_material->flags[VS::MATERIAL_FLAG_LIGHTMAP_ON_UV2]);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_COLOR_ATTRIB_SRGB_TO_LINEAR, p_material->flags[VS::MATERIAL_FLAG_COLOR_ARRAY_SRGB] && current_env && current_env->fx_enabled[VS::ENV_FX_SRGB]);
- if (p_opaque_pass && p_material->depth_draw_mode==VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA && p_material->shader_cache && p_material->shader_cache->has_alpha) {
+ if (p_opaque_pass && p_material->depth_draw_mode == VS::MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA && p_material->shader_cache && p_material->shader_cache->has_alpha) {
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_CLIP_ALPHA,true);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_CLIP_ALPHA, true);
} else {
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_CLIP_ALPHA,false);
-
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_CLIP_ALPHA, false);
}
-
if (!shadow) {
- bool depth_test=!p_material->flags[VS::MATERIAL_FLAG_ONTOP];
- bool depth_write=p_material->depth_draw_mode!=VS::MATERIAL_DEPTH_DRAW_NEVER && (p_opaque_pass || p_material->depth_draw_mode==VS::MATERIAL_DEPTH_DRAW_ALWAYS);
+ bool depth_test = !p_material->flags[VS::MATERIAL_FLAG_ONTOP];
+ bool depth_write = p_material->depth_draw_mode != VS::MATERIAL_DEPTH_DRAW_NEVER && (p_opaque_pass || p_material->depth_draw_mode == VS::MATERIAL_DEPTH_DRAW_ALWAYS);
//bool depth_write=!p_material->hints[VS::MATERIAL_HINT_NO_DEPTH_DRAW] && (p_opaque_pass || !p_material->hints[VS::MATERIAL_HINT_NO_DEPTH_DRAW_FOR_ALPHA]);
- if (current_depth_mask!=depth_write) {
- current_depth_mask=depth_write;
- glDepthMask( depth_write );
-
+ if (current_depth_mask != depth_write) {
+ current_depth_mask = depth_write;
+ glDepthMask(depth_write);
}
+ if (current_depth_test != depth_test) {
- if (current_depth_test!=depth_test) {
-
-
- current_depth_test=depth_test;
- if(depth_test)
+ current_depth_test = depth_test;
+ if (depth_test)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
}
-
- material_shader.set_conditional(MaterialShaderGLES2::USE_FOG,current_env && current_env->fx_enabled[VS::ENV_FX_FOG]);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_FOG, current_env && current_env->fx_enabled[VS::ENV_FX_FOG]);
//glDepthMask( true );
}
-
DEBUG_TEST_ERROR("Pre Shader Bind");
- bool rebind=false;
+ bool rebind = false;
if (p_material->shader_cache && p_material->shader_cache->valid) {
@@ -5226,14 +4887,12 @@ bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material
material_shader.set_conditional((MaterialShaderGLES2::Conditionals)_tex_version[i],false);
*/
-
//material_shader.set_custom_shader(p_material->shader_cache->custom_code_id);
- if (p_material->shader_version!=p_material->shader_cache->version) {
+ if (p_material->shader_version != p_material->shader_cache->version) {
//shader changed somehow, must update uniforms
- _update_material_shader_params((Material*)p_material);
-
+ _update_material_shader_params((Material *)p_material);
}
material_shader.set_custom_shader(p_material->shader_cache->custom_code_id);
rebind = material_shader.bind();
@@ -5241,11 +4900,10 @@ bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material
DEBUG_TEST_ERROR("Shader Bind");
//set uniforms!
- int texcoord=0;
- for (Map<StringName,Material::UniformData>::Element *E=p_material->shader_params.front();E;E=E->next()) {
+ int texcoord = 0;
+ for (Map<StringName, Material::UniformData>::Element *E = p_material->shader_params.front(); E; E = E->next()) {
-
- if (E->get().index<0)
+ if (E->get().index < 0)
continue;
//print_line(String(E->key())+": "+E->get().value);
if (E->get().istexture) {
@@ -5253,61 +4911,55 @@ bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material
RID rid = E->get().value;
int loc = material_shader.get_custom_uniform_location(E->get().index); //should be automatic..
-
- Texture *t=NULL;
+ Texture *t = NULL;
if (rid.is_valid()) {
-
- t=texture_owner.get(rid);
+ t = texture_owner.get(rid);
if (!t) {
- E->get().value=RID(); //nullify, invalid texture
- rid=RID();
+ E->get().value = RID(); //nullify, invalid texture
+ rid = RID();
}
}
- glActiveTexture(GL_TEXTURE0+texcoord);
- glUniform1i(loc,texcoord); //TODO - this could happen automatically on compile...
+ glActiveTexture(GL_TEXTURE0 + texcoord);
+ glUniform1i(loc, texcoord); //TODO - this could happen automatically on compile...
if (t) {
if (t->render_target)
- t->render_target->last_pass=frame;
- if (E->key()==p_material->shader_cache->first_texture) {
- tc0_idx=texcoord;
- tc0_id_cache=t->tex_id;
+ t->render_target->last_pass = frame;
+ if (E->key() == p_material->shader_cache->first_texture) {
+ tc0_idx = texcoord;
+ tc0_id_cache = t->tex_id;
}
- glBindTexture(t->target,t->tex_id);
+ glBindTexture(t->target, t->tex_id);
} else
- glBindTexture(GL_TEXTURE_2D,white_tex); //no texture
+ glBindTexture(GL_TEXTURE_2D, white_tex); //no texture
texcoord++;
- } else if (E->get().value.get_type()==Variant::COLOR){
+ } else if (E->get().value.get_type() == Variant::COLOR) {
Color c = E->get().value;
- material_shader.set_custom_uniform(E->get().index,_convert_color(c));
+ material_shader.set_custom_uniform(E->get().index, _convert_color(c));
} else {
- material_shader.set_custom_uniform(E->get().index,E->get().value);
+ material_shader.set_custom_uniform(E->get().index, E->get().value);
}
-
}
-
if (p_material->shader_cache->has_texscreen && framebuffer.active) {
- material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_SCREEN_MULT,Vector2(float(viewport.width)/framebuffer.width,float(viewport.height)/framebuffer.height));
- material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_SCREEN_CLAMP,Color(0,0,float(viewport.width)/framebuffer.width,float(viewport.height)/framebuffer.height));
- material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_TEX,texcoord);
- glActiveTexture(GL_TEXTURE0+texcoord);
- glBindTexture(GL_TEXTURE_2D,framebuffer.sample_color);
-
+ material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_SCREEN_MULT, Vector2(float(viewport.width) / framebuffer.width, float(viewport.height) / framebuffer.height));
+ material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_SCREEN_CLAMP, Color(0, 0, float(viewport.width) / framebuffer.width, float(viewport.height) / framebuffer.height));
+ material_shader.set_uniform(MaterialShaderGLES2::TEXSCREEN_TEX, texcoord);
+ glActiveTexture(GL_TEXTURE0 + texcoord);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.sample_color);
}
if (p_material->shader_cache->has_screen_uv) {
- material_shader.set_uniform(MaterialShaderGLES2::SCREEN_UV_MULT,Vector2(1.0/viewport.width,1.0/viewport.height));
+ material_shader.set_uniform(MaterialShaderGLES2::SCREEN_UV_MULT, Vector2(1.0 / viewport.width, 1.0 / viewport.height));
}
DEBUG_TEST_ERROR("Material arameters");
if (p_material->shader_cache->uses_time) {
- material_shader.set_uniform(MaterialShaderGLES2::TIME,Math::fmod(last_time,shader_time_rollback));
- draw_next_frame=true;
+ material_shader.set_uniform(MaterialShaderGLES2::TIME, Math::fmod(last_time, shader_time_rollback));
+ draw_next_frame = true;
}
- //if uses TIME - draw_next_frame=true
-
+ //if uses TIME - draw_next_frame=true
} else {
@@ -5317,57 +4969,48 @@ bool RasterizerGLES2::_setup_material(const Geometry *p_geometry,const Material
DEBUG_TEST_ERROR("Shader bind2");
}
-
-
if (shadow) {
float zofs = shadow->base->vars[VS::LIGHT_PARAM_SHADOW_Z_OFFSET];
float zslope = shadow->base->vars[VS::LIGHT_PARAM_SHADOW_Z_SLOPE_SCALE];
- if (shadow_pass>=1 && shadow->base->type==VS::LIGHT_DIRECTIONAL) {
- float m = Math::pow(shadow->base->directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_ZOFFSET_SCALE],shadow_pass);
- zofs*=m;
- zslope*=m;
- }
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_Z_OFFSET,zofs);
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_Z_SLOPE_SCALE,zslope);
- if (shadow->base->type==VS::LIGHT_OMNI)
- material_shader.set_uniform(MaterialShaderGLES2::DUAL_PARABOLOID,shadow->dp);
+ if (shadow_pass >= 1 && shadow->base->type == VS::LIGHT_DIRECTIONAL) {
+ float m = Math::pow(shadow->base->directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_ZOFFSET_SCALE], shadow_pass);
+ zofs *= m;
+ zslope *= m;
+ }
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_Z_OFFSET, zofs);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_Z_SLOPE_SCALE, zslope);
+ if (shadow->base->type == VS::LIGHT_OMNI)
+ material_shader.set_uniform(MaterialShaderGLES2::DUAL_PARABOLOID, shadow->dp);
DEBUG_TEST_ERROR("Shadow uniforms");
-
}
-
if (current_env && current_env->fx_enabled[VS::ENV_FX_FOG]) {
Color col_begin = current_env->fx_param[VS::ENV_FX_PARAM_FOG_BEGIN_COLOR];
Color col_end = current_env->fx_param[VS::ENV_FX_PARAM_FOG_END_COLOR];
- col_begin=_convert_color(col_begin);
- col_end=_convert_color(col_end);
+ col_begin = _convert_color(col_begin);
+ col_end = _convert_color(col_end);
float from = current_env->fx_param[VS::ENV_FX_PARAM_FOG_BEGIN];
float zf = camera_z_far;
float curve = current_env->fx_param[VS::ENV_FX_PARAM_FOG_ATTENUATION];
- material_shader.set_uniform(MaterialShaderGLES2::FOG_PARAMS,Vector3(from,zf,curve));
- material_shader.set_uniform(MaterialShaderGLES2::FOG_COLOR_BEGIN,Vector3(col_begin.r,col_begin.g,col_begin.b));
- material_shader.set_uniform(MaterialShaderGLES2::FOG_COLOR_END,Vector3(col_end.r,col_end.g,col_end.b));
+ material_shader.set_uniform(MaterialShaderGLES2::FOG_PARAMS, Vector3(from, zf, curve));
+ material_shader.set_uniform(MaterialShaderGLES2::FOG_COLOR_BEGIN, Vector3(col_begin.r, col_begin.g, col_begin.b));
+ material_shader.set_uniform(MaterialShaderGLES2::FOG_COLOR_END, Vector3(col_end.r, col_end.g, col_end.b));
}
-
-
//material_shader.set_uniform(MaterialShaderGLES2::TIME,Math::fmod(last_time,300.0));
//if uses TIME - draw_next_frame=true
return rebind;
-
}
-
-
void RasterizerGLES2::_setup_light(uint16_t p_light) {
if (shadow)
return;
- if (p_light==0xFFFF)
+ if (p_light == 0xFFFF)
return;
enum {
@@ -5380,7 +5023,7 @@ void RasterizerGLES2::_setup_light(uint16_t p_light) {
VL_LIGHT_MAX
};
- static const MaterialShaderGLES2::Uniforms light_uniforms[VL_LIGHT_MAX]={
+ static const MaterialShaderGLES2::Uniforms light_uniforms[VL_LIGHT_MAX] = {
MaterialShaderGLES2::LIGHT_POS,
MaterialShaderGLES2::LIGHT_DIRECTION,
MaterialShaderGLES2::LIGHT_ATTENUATION,
@@ -5389,229 +5032,213 @@ void RasterizerGLES2::_setup_light(uint16_t p_light) {
MaterialShaderGLES2::LIGHT_SPECULAR,
};
-
GLfloat light_data[VL_LIGHT_MAX][3];
- memset(light_data,0,(VL_LIGHT_MAX)*3*sizeof(GLfloat));
+ memset(light_data, 0, (VL_LIGHT_MAX)*3 * sizeof(GLfloat));
- LightInstance *li=light_instances[p_light];
- Light *l=li->base;
+ LightInstance *li = light_instances[p_light];
+ Light *l = li->base;
- Color col_diffuse=_convert_color(l->colors[VS::LIGHT_COLOR_DIFFUSE]);
- Color col_specular=_convert_color(l->colors[VS::LIGHT_COLOR_SPECULAR]);
+ Color col_diffuse = _convert_color(l->colors[VS::LIGHT_COLOR_DIFFUSE]);
+ Color col_specular = _convert_color(l->colors[VS::LIGHT_COLOR_SPECULAR]);
- for(int j=0;j<3;j++) {
- light_data[VL_LIGHT_DIFFUSE][j]=col_diffuse[j];
- light_data[VL_LIGHT_SPECULAR][j]=col_specular[j];
+ for (int j = 0; j < 3; j++) {
+ light_data[VL_LIGHT_DIFFUSE][j] = col_diffuse[j];
+ light_data[VL_LIGHT_SPECULAR][j] = col_specular[j];
}
- if (l->type!=VS::LIGHT_OMNI) {
+ if (l->type != VS::LIGHT_OMNI) {
Vector3 dir = -li->transform.get_basis().get_axis(2);
dir = camera_transform_inverse.basis.xform(dir).normalized();
- for(int j=0;j<3;j++)
- light_data[VL_LIGHT_DIR][j]=dir[j];
+ for (int j = 0; j < 3; j++)
+ light_data[VL_LIGHT_DIR][j] = dir[j];
}
-
- if (l->type!=VS::LIGHT_DIRECTIONAL) {
+ if (l->type != VS::LIGHT_DIRECTIONAL) {
Vector3 pos = li->transform.get_origin();
pos = camera_transform_inverse.xform(pos);
- for(int j=0;j<3;j++)
- light_data[VL_LIGHT_POS][j]=pos[j];
+ for (int j = 0; j < 3; j++)
+ light_data[VL_LIGHT_POS][j] = pos[j];
}
if (li->near_shadow_buffer) {
- glActiveTexture(GL_TEXTURE0+max_texture_units-1);
- glBindTexture(GL_TEXTURE_2D,li->near_shadow_buffer->depth);
-
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX,li->shadow_projection[0]);
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_TEXEL_SIZE,Vector2(1.0,1.0)/li->near_shadow_buffer->size);
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_TEXTURE,max_texture_units-1);
- if (shadow_filter==SHADOW_FILTER_ESM)
- material_shader.set_uniform(MaterialShaderGLES2::ESM_MULTIPLIER,float(li->base->vars[VS::LIGHT_PARAM_SHADOW_ESM_MULTIPLIER]));
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 1);
+ glBindTexture(GL_TEXTURE_2D, li->near_shadow_buffer->depth);
- if (li->base->type==VS::LIGHT_DIRECTIONAL) {
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX, li->shadow_projection[0]);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_TEXEL_SIZE, Vector2(1.0, 1.0) / li->near_shadow_buffer->size);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_TEXTURE, max_texture_units - 1);
+ if (shadow_filter == SHADOW_FILTER_ESM)
+ material_shader.set_uniform(MaterialShaderGLES2::ESM_MULTIPLIER, float(li->base->vars[VS::LIGHT_PARAM_SHADOW_ESM_MULTIPLIER]));
- if (li->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
+ if (li->base->type == VS::LIGHT_DIRECTIONAL) {
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX2,li->shadow_projection[1]);
- material_shader.set_uniform(MaterialShaderGLES2::LIGHT_PSSM_SPLIT,Vector3(li->shadow_split[0],li->shadow_split[1],li->shadow_split[2]));
- } else if (li->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ if (li->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX2, li->shadow_projection[1]);
+ material_shader.set_uniform(MaterialShaderGLES2::LIGHT_PSSM_SPLIT, Vector3(li->shadow_split[0], li->shadow_split[1], li->shadow_split[2]));
+ } else if (li->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX2,li->shadow_projection[1]);
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX3,li->shadow_projection[2]);
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX4,li->shadow_projection[3]);
- material_shader.set_uniform(MaterialShaderGLES2::LIGHT_PSSM_SPLIT,Vector3(li->shadow_split[0],li->shadow_split[1],li->shadow_split[2]));
-
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX2, li->shadow_projection[1]);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX3, li->shadow_projection[2]);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_MATRIX4, li->shadow_projection[3]);
+ material_shader.set_uniform(MaterialShaderGLES2::LIGHT_PSSM_SPLIT, Vector3(li->shadow_split[0], li->shadow_split[1], li->shadow_split[2]));
}
//print_line("shadow split: "+rtos(li->shadow_split));
}
- material_shader.set_uniform(MaterialShaderGLES2::SHADOW_DARKENING,li->base->vars[VS::LIGHT_PARAM_SHADOW_DARKENING]);
+ material_shader.set_uniform(MaterialShaderGLES2::SHADOW_DARKENING, li->base->vars[VS::LIGHT_PARAM_SHADOW_DARKENING]);
//matrix
-
}
-
light_data[VL_LIGHT_ATTENUATION][0] = l->vars[VS::LIGHT_PARAM_ENERGY];
if (l->type == VS::LIGHT_DIRECTIONAL) {
light_data[VL_LIGHT_ATTENUATION][1] = l->directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_MAX_DISTANCE];
- }
- else{
+ } else {
light_data[VL_LIGHT_ATTENUATION][1] = l->vars[VS::LIGHT_PARAM_RADIUS];
}
light_data[VL_LIGHT_ATTENUATION][2] = l->vars[VS::LIGHT_PARAM_ATTENUATION];
- light_data[VL_LIGHT_SPOT_ATTENUATION][0]=Math::cos(Math::deg2rad(l->vars[VS::LIGHT_PARAM_SPOT_ANGLE]));
- light_data[VL_LIGHT_SPOT_ATTENUATION][1]=l->vars[VS::LIGHT_PARAM_SPOT_ATTENUATION];
-
+ light_data[VL_LIGHT_SPOT_ATTENUATION][0] = Math::cos(Math::deg2rad(l->vars[VS::LIGHT_PARAM_SPOT_ANGLE]));
+ light_data[VL_LIGHT_SPOT_ATTENUATION][1] = l->vars[VS::LIGHT_PARAM_SPOT_ATTENUATION];
//int uf = material_shader.get_uniform(MaterialShaderGLES2::LIGHT_PARAMS);
- for(int i=0;i<VL_LIGHT_MAX;i++) {
- glUniform3f( material_shader.get_uniform(light_uniforms[i]),light_data[i][0],light_data[i][1],light_data[i][2]);
+ for (int i = 0; i < VL_LIGHT_MAX; i++) {
+ glUniform3f(material_shader.get_uniform(light_uniforms[i]), light_data[i][0], light_data[i][1], light_data[i][2]);
}
-
}
-
-template<bool USE_NORMAL, bool USE_TANGENT,bool INPLACE>
-void RasterizerGLES2::_skeleton_xform(const uint8_t * p_src_array, int p_src_stride, uint8_t * p_dst_array, int p_dst_stride, int p_elements,const uint8_t *p_src_bones, const uint8_t *p_src_weights, const Skeleton::Bone *p_bone_xforms) {
+template <bool USE_NORMAL, bool USE_TANGENT, bool INPLACE>
+void RasterizerGLES2::_skeleton_xform(const uint8_t *p_src_array, int p_src_stride, uint8_t *p_dst_array, int p_dst_stride, int p_elements, const uint8_t *p_src_bones, const uint8_t *p_src_weights, const Skeleton::Bone *p_bone_xforms) {
uint32_t basesize = 3;
if (USE_NORMAL)
- basesize+=3;
+ basesize += 3;
if (USE_TANGENT)
- basesize+=4;
+ basesize += 4;
- uint32_t extra=(p_dst_stride-basesize*4);
- const int dstvec_size=3+(USE_NORMAL?3:0)+(USE_TANGENT?4:0);
+ uint32_t extra = (p_dst_stride - basesize * 4);
+ const int dstvec_size = 3 + (USE_NORMAL ? 3 : 0) + (USE_TANGENT ? 4 : 0);
float dstcopy[dstvec_size];
- for(int i=0;i<p_elements;i++) {
+ for (int i = 0; i < p_elements; i++) {
- uint32_t ss = p_src_stride*i;
- uint32_t ds = p_dst_stride*i;
- const uint16_t *bi = (const uint16_t*)&p_src_bones[ss];
+ uint32_t ss = p_src_stride * i;
+ uint32_t ds = p_dst_stride * i;
+ const uint16_t *bi = (const uint16_t *)&p_src_bones[ss];
const float *bw = (const float *)&p_src_weights[ss];
- const float *src_vec=(const float *)&p_src_array[ss];
+ const float *src_vec = (const float *)&p_src_array[ss];
float *dst_vec;
if (INPLACE)
- dst_vec=dstcopy;
+ dst_vec = dstcopy;
else
- dst_vec=(float*)&p_dst_array[ds];
+ dst_vec = (float *)&p_dst_array[ds];
- dst_vec[0]=0.0;
- dst_vec[1]=0.0;
- dst_vec[2]=0.0;
+ dst_vec[0] = 0.0;
+ dst_vec[1] = 0.0;
+ dst_vec[2] = 0.0;
//conditionals simply removed by optimizer
if (USE_NORMAL) {
- dst_vec[3]=0.0;
- dst_vec[4]=0.0;
- dst_vec[5]=0.0;
+ dst_vec[3] = 0.0;
+ dst_vec[4] = 0.0;
+ dst_vec[5] = 0.0;
if (USE_TANGENT) {
- dst_vec[6]=0.0;
- dst_vec[7]=0.0;
- dst_vec[8]=0.0;
- dst_vec[9]=src_vec[9];
+ dst_vec[6] = 0.0;
+ dst_vec[7] = 0.0;
+ dst_vec[8] = 0.0;
+ dst_vec[9] = src_vec[9];
}
} else {
if (USE_TANGENT) {
- dst_vec[3]=0.0;
- dst_vec[4]=0.0;
- dst_vec[5]=0.0;
- dst_vec[6]=src_vec[6];
+ dst_vec[3] = 0.0;
+ dst_vec[4] = 0.0;
+ dst_vec[5] = 0.0;
+ dst_vec[6] = src_vec[6];
}
}
-
-#define _XFORM_BONE(m_idx)\
- if (bw[m_idx]==0)\
- goto end;\
- p_bone_xforms[bi[m_idx]].transform_add_mul3(&src_vec[0],&dst_vec[0],bw[m_idx]);\
- if (USE_NORMAL) {\
- p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[3],&dst_vec[3],bw[m_idx]);\
- if (USE_TANGENT) {\
- p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[6],&dst_vec[6],bw[m_idx]);\
- }\
- } else {\
- if (USE_TANGENT) {\
- p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[3],&dst_vec[3],bw[m_idx]);\
- }\
- }
+#define _XFORM_BONE(m_idx) \
+ if (bw[m_idx] == 0) \
+ goto end; \
+ p_bone_xforms[bi[m_idx]].transform_add_mul3(&src_vec[0], &dst_vec[0], bw[m_idx]); \
+ if (USE_NORMAL) { \
+ p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[3], &dst_vec[3], bw[m_idx]); \
+ if (USE_TANGENT) { \
+ p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[6], &dst_vec[6], bw[m_idx]); \
+ } \
+ } else { \
+ if (USE_TANGENT) { \
+ p_bone_xforms[bi[m_idx]].transform3_add_mul3(&src_vec[3], &dst_vec[3], bw[m_idx]); \
+ } \
+ }
_XFORM_BONE(0);
_XFORM_BONE(1);
_XFORM_BONE(2);
_XFORM_BONE(3);
- end:
+ end:
if (INPLACE) {
- const uint8_t *esp =(const uint8_t*) dstcopy;
- uint8_t *edp =(uint8_t*)&p_dst_array[ds];
-
+ const uint8_t *esp = (const uint8_t *)dstcopy;
+ uint8_t *edp = (uint8_t *)&p_dst_array[ds];
- for(uint32_t j=0;j<dstvec_size*4;j++) {
+ for (uint32_t j = 0; j < dstvec_size * 4; j++) {
- edp[j]=esp[j];
+ edp[j] = esp[j];
}
} else {
//copy extra stuff
- const uint8_t *esp =(const uint8_t*) &src_vec[basesize];
- uint8_t *edp =(uint8_t*) &dst_vec[basesize];
+ const uint8_t *esp = (const uint8_t *)&src_vec[basesize];
+ uint8_t *edp = (uint8_t *)&dst_vec[basesize];
+ for (uint32_t j = 0; j < extra; j++) {
- for(uint32_t j=0;j<extra;j++) {
-
- edp[j]=esp[j];
+ edp[j] = esp[j];
}
}
}
}
+Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton, const float *p_morphs) {
-Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Material* p_material, const Skeleton *p_skeleton,const float *p_morphs) {
-
-
- switch(p_geometry->type) {
+ switch (p_geometry->type) {
case Geometry::GEOMETRY_MULTISURFACE:
case Geometry::GEOMETRY_SURFACE: {
- const Surface *surf=NULL;
- if (p_geometry->type==Geometry::GEOMETRY_SURFACE)
- surf=static_cast<const Surface*>(p_geometry);
- else if (p_geometry->type==Geometry::GEOMETRY_MULTISURFACE)
- surf=static_cast<const MultiMeshSurface*>(p_geometry)->surface;
-
+ const Surface *surf = NULL;
+ if (p_geometry->type == Geometry::GEOMETRY_SURFACE)
+ surf = static_cast<const Surface *>(p_geometry);
+ else if (p_geometry->type == Geometry::GEOMETRY_MULTISURFACE)
+ surf = static_cast<const MultiMeshSurface *>(p_geometry)->surface;
if (surf->format != surf->configured_format) {
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line("has format: "+itos(surf->format));
- print_line("configured format: "+itos(surf->configured_format));
+ print_line("has format: " + itos(surf->format));
+ print_line("configured format: " + itos(surf->configured_format));
}
ERR_EXPLAIN("Missing arrays (not set) in surface");
}
- ERR_FAIL_COND_V( surf->format != surf->configured_format, ERR_UNCONFIGURED );
- uint8_t *base=0;
- int stride=surf->stride;
- bool use_VBO = (surf->array_local==0);
- _setup_geometry_vinfo=surf->array_len;
+ ERR_FAIL_COND_V(surf->format != surf->configured_format, ERR_UNCONFIGURED);
+ uint8_t *base = 0;
+ int stride = surf->stride;
+ bool use_VBO = (surf->array_local == 0);
+ _setup_geometry_vinfo = surf->array_len;
- bool skeleton_valid = p_skeleton && (surf->format&VS::ARRAY_FORMAT_BONES) && (surf->format&VS::ARRAY_FORMAT_WEIGHTS) && !p_skeleton->bones.empty() && p_skeleton->bones.size() > surf->max_bone;
+ bool skeleton_valid = p_skeleton && (surf->format & VS::ARRAY_FORMAT_BONES) && (surf->format & VS::ARRAY_FORMAT_WEIGHTS) && !p_skeleton->bones.empty() && p_skeleton->bones.size() > surf->max_bone;
/*
if (surf->packed) {
float scales[4]={surf->vertex_scale,surf->uv_scale,surf->uv2_scale,0.0};
@@ -5627,174 +5254,163 @@ Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Materia
base = surf->array_local;
glBindBuffer(GL_ARRAY_BUFFER, 0);
- bool can_copy_to_local=surf->local_stride * surf->array_len <= skinned_buffer_size;
+ bool can_copy_to_local = surf->local_stride * surf->array_len <= skinned_buffer_size;
if (p_morphs && surf->stride * surf->array_len > skinned_buffer_size)
- can_copy_to_local=false;
-
+ can_copy_to_local = false;
if (!can_copy_to_local)
- skeleton_valid=false;
+ skeleton_valid = false;
/* compute morphs */
if (p_morphs && surf->morph_target_count && can_copy_to_local) {
-
-
base = skinned_buffer;
- stride=surf->local_stride;
+ stride = surf->local_stride;
//copy all first
- float coef=1.0;
-
- for(int i=0;i<surf->morph_target_count;i++) {
- if (surf->mesh->morph_target_mode==VS::MORPH_MODE_NORMALIZED)
- coef-=p_morphs[i];
- ERR_FAIL_COND_V( surf->morph_format != surf->morph_targets_local[i].configured_format, ERR_INVALID_DATA );
+ float coef = 1.0;
+ for (int i = 0; i < surf->morph_target_count; i++) {
+ if (surf->mesh->morph_target_mode == VS::MORPH_MODE_NORMALIZED)
+ coef -= p_morphs[i];
+ ERR_FAIL_COND_V(surf->morph_format != surf->morph_targets_local[i].configured_format, ERR_INVALID_DATA);
}
- int16_t coeffp = CLAMP(coef*255,0,255);
+ int16_t coeffp = CLAMP(coef * 255, 0, 255);
+ for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
- for(int i=0;i<VS::ARRAY_MAX-1;i++) {
-
- const Surface::ArrayData& ad=surf->array[i];
- if (ad.size==0)
+ const Surface::ArrayData &ad = surf->array[i];
+ if (ad.size == 0)
continue;
int ofs = ad.ofs;
- int src_stride=surf->stride;
- int dst_stride=skeleton_valid?surf->stride:surf->local_stride;
+ int src_stride = surf->stride;
+ int dst_stride = skeleton_valid ? surf->stride : surf->local_stride;
int count = surf->array_len;
- if (!skeleton_valid && i>=VS::ARRAY_MAX-3)
+ if (!skeleton_valid && i >= VS::ARRAY_MAX - 3)
break;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX:
case VS::ARRAY_NORMAL:
- case VS::ARRAY_TANGENT:
- {
+ case VS::ARRAY_TANGENT: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const float *src = (const float*)&surf->array_local[ofs+k*src_stride];
- float *dst = (float*)&base[ofs+k*dst_stride];
+ const float *src = (const float *)&surf->array_local[ofs + k * src_stride];
+ float *dst = (float *)&base[ofs + k * dst_stride];
- dst[0]= src[0]*coef;
- dst[1]= src[1]*coef;
- dst[2]= src[2]*coef;
+ dst[0] = src[0] * coef;
+ dst[1] = src[1] * coef;
+ dst[2] = src[2] * coef;
};
} break;
case VS::ARRAY_COLOR: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const uint8_t *src = (const uint8_t*)&surf->array_local[ofs+k*src_stride];
- uint8_t *dst = (uint8_t*)&base[ofs+k*dst_stride];
+ const uint8_t *src = (const uint8_t *)&surf->array_local[ofs + k * src_stride];
+ uint8_t *dst = (uint8_t *)&base[ofs + k * dst_stride];
- dst[0]= (src[0]*coeffp)>>8;
- dst[1]= (src[1]*coeffp)>>8;
- dst[2]= (src[2]*coeffp)>>8;
- dst[3]= (src[3]*coeffp)>>8;
+ dst[0] = (src[0] * coeffp) >> 8;
+ dst[1] = (src[1] * coeffp) >> 8;
+ dst[2] = (src[2] * coeffp) >> 8;
+ dst[3] = (src[3] * coeffp) >> 8;
}
} break;
case VS::ARRAY_TEX_UV:
case VS::ARRAY_TEX_UV2: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const float *src = (const float*)&surf->array_local[ofs+k*src_stride];
- float *dst = (float*)&base[ofs+k*dst_stride];
+ const float *src = (const float *)&surf->array_local[ofs + k * src_stride];
+ float *dst = (float *)&base[ofs + k * dst_stride];
- dst[0]= src[0]*coef;
- dst[1]= src[1]*coef;
+ dst[0] = src[0] * coef;
+ dst[1] = src[1] * coef;
}
} break;
case VS::ARRAY_BONES:
case VS::ARRAY_WEIGHTS: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const float *src = (const float*)&surf->array_local[ofs+k*src_stride];
- float *dst = (float*)&base[ofs+k*dst_stride];
+ const float *src = (const float *)&surf->array_local[ofs + k * src_stride];
+ float *dst = (float *)&base[ofs + k * dst_stride];
- dst[0]= src[0];
- dst[1]= src[1];
- dst[2]= src[2];
- dst[3]= src[3];
+ dst[0] = src[0];
+ dst[1] = src[1];
+ dst[2] = src[2];
+ dst[3] = src[3];
}
} break;
-
}
}
+ for (int j = 0; j < surf->morph_target_count; j++) {
- for(int j=0;j<surf->morph_target_count;j++) {
+ for (int i = 0; i < VS::ARRAY_MAX - 3; i++) {
- for(int i=0;i<VS::ARRAY_MAX-3;i++) {
-
- const Surface::ArrayData& ad=surf->array[i];
- if (ad.size==0)
+ const Surface::ArrayData &ad = surf->array[i];
+ if (ad.size == 0)
continue;
-
int ofs = ad.ofs;
- int src_stride=surf->local_stride;
- int dst_stride=skeleton_valid?surf->stride:surf->local_stride;
+ int src_stride = surf->local_stride;
+ int dst_stride = skeleton_valid ? surf->stride : surf->local_stride;
int count = surf->array_len;
- const uint8_t *morph=surf->morph_targets_local[j].array;
+ const uint8_t *morph = surf->morph_targets_local[j].array;
float w = p_morphs[j];
- int16_t wfp = CLAMP(w*255,0,255);
+ int16_t wfp = CLAMP(w * 255, 0, 255);
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX:
case VS::ARRAY_NORMAL:
- case VS::ARRAY_TANGENT:
- {
+ case VS::ARRAY_TANGENT: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const float *src_morph = (const float*)&morph[ofs+k*src_stride];
- float *dst = (float*)&base[ofs+k*dst_stride];
+ const float *src_morph = (const float *)&morph[ofs + k * src_stride];
+ float *dst = (float *)&base[ofs + k * dst_stride];
- dst[0]+= src_morph[0]*w;
- dst[1]+= src_morph[1]*w;
- dst[2]+= src_morph[2]*w;
+ dst[0] += src_morph[0] * w;
+ dst[1] += src_morph[1] * w;
+ dst[2] += src_morph[2] * w;
}
} break;
case VS::ARRAY_COLOR: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const uint8_t *src = (const uint8_t*)&morph[ofs+k*src_stride];
- uint8_t *dst = (uint8_t*)&base[ofs+k*dst_stride];
+ const uint8_t *src = (const uint8_t *)&morph[ofs + k * src_stride];
+ uint8_t *dst = (uint8_t *)&base[ofs + k * dst_stride];
- dst[0]= (src[0]*wfp)>>8;
- dst[1]= (src[1]*wfp)>>8;
- dst[2]= (src[2]*wfp)>>8;
- dst[3]= (src[3]*wfp)>>8;
+ dst[0] = (src[0] * wfp) >> 8;
+ dst[1] = (src[1] * wfp) >> 8;
+ dst[2] = (src[2] * wfp) >> 8;
+ dst[3] = (src[3] * wfp) >> 8;
}
} break;
case VS::ARRAY_TEX_UV:
case VS::ARRAY_TEX_UV2: {
- for(int k=0;k<count;k++) {
+ for (int k = 0; k < count; k++) {
- const float *src_morph = (const float*)&morph[ofs+k*src_stride];
- float *dst = (float*)&base[ofs+k*dst_stride];
+ const float *src_morph = (const float *)&morph[ofs + k * src_stride];
+ float *dst = (float *)&base[ofs + k * dst_stride];
- dst[0]+= src_morph[0]*w;
- dst[1]+= src_morph[1]*w;
+ dst[0] += src_morph[0] * w;
+ dst[1] += src_morph[1] * w;
}
} break;
@@ -5802,30 +5418,23 @@ Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Materia
}
}
-
-
if (skeleton_valid) {
-
-
- const uint8_t *src_weights=&surf->array_local[surf->array[VS::ARRAY_WEIGHTS].ofs];
- const uint8_t *src_bones=&surf->array_local[surf->array[VS::ARRAY_BONES].ofs];
+ const uint8_t *src_weights = &surf->array_local[surf->array[VS::ARRAY_WEIGHTS].ofs];
+ const uint8_t *src_bones = &surf->array_local[surf->array[VS::ARRAY_BONES].ofs];
const Skeleton::Bone *skeleton = &p_skeleton->bones[0];
-
- if (surf->format&VS::ARRAY_FORMAT_NORMAL && surf->format&VS::ARRAY_FORMAT_TANGENT)
- _skeleton_xform<true,true,true>(base,surf->stride,base,surf->stride,surf->array_len,src_bones,src_weights,skeleton);
- else if (surf->format&(VS::ARRAY_FORMAT_NORMAL))
- _skeleton_xform<true,false,true>(base,surf->stride,base,surf->stride,surf->array_len,src_bones,src_weights,skeleton);
- else if (surf->format&(VS::ARRAY_FORMAT_TANGENT))
- _skeleton_xform<false,true,true>(base,surf->stride,base,surf->stride,surf->array_len,src_bones,src_weights,skeleton);
+ if (surf->format & VS::ARRAY_FORMAT_NORMAL && surf->format & VS::ARRAY_FORMAT_TANGENT)
+ _skeleton_xform<true, true, true>(base, surf->stride, base, surf->stride, surf->array_len, src_bones, src_weights, skeleton);
+ else if (surf->format & (VS::ARRAY_FORMAT_NORMAL))
+ _skeleton_xform<true, false, true>(base, surf->stride, base, surf->stride, surf->array_len, src_bones, src_weights, skeleton);
+ else if (surf->format & (VS::ARRAY_FORMAT_TANGENT))
+ _skeleton_xform<false, true, true>(base, surf->stride, base, surf->stride, surf->array_len, src_bones, src_weights, skeleton);
else
- _skeleton_xform<false,false,true>(base,surf->stride,base,surf->stride,surf->array_len,src_bones,src_weights,skeleton);
-
+ _skeleton_xform<false, false, true>(base, surf->stride, base, surf->stride, surf->array_len, src_bones, src_weights, skeleton);
}
- stride=skeleton_valid?surf->stride:surf->local_stride;
-
+ stride = skeleton_valid ? surf->stride : surf->local_stride;
#if 0
{
@@ -5914,45 +5523,41 @@ Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Materia
base = skinned_buffer;
//copy stuff and get it ready for the skeleton
- int dst_stride = surf->stride - ( surf->array[VS::ARRAY_BONES].size + surf->array[VS::ARRAY_WEIGHTS].size );
- const uint8_t *src_weights=&surf->array_local[surf->array[VS::ARRAY_WEIGHTS].ofs];
- const uint8_t *src_bones=&surf->array_local[surf->array[VS::ARRAY_BONES].ofs];
+ int dst_stride = surf->stride - (surf->array[VS::ARRAY_BONES].size + surf->array[VS::ARRAY_WEIGHTS].size);
+ const uint8_t *src_weights = &surf->array_local[surf->array[VS::ARRAY_WEIGHTS].ofs];
+ const uint8_t *src_bones = &surf->array_local[surf->array[VS::ARRAY_BONES].ofs];
const Skeleton::Bone *skeleton = &p_skeleton->bones[0];
- if (surf->format&VS::ARRAY_FORMAT_NORMAL && surf->format&VS::ARRAY_FORMAT_TANGENT)
- _skeleton_xform<true,true,false>(surf->array_local,surf->stride,base,dst_stride,surf->array_len,src_bones,src_weights,skeleton);
- else if (surf->format&(VS::ARRAY_FORMAT_NORMAL))
- _skeleton_xform<true,false,false>(surf->array_local,surf->stride,base,dst_stride,surf->array_len,src_bones,src_weights,skeleton);
- else if (surf->format&(VS::ARRAY_FORMAT_TANGENT))
- _skeleton_xform<false,true,false>(surf->array_local,surf->stride,base,dst_stride,surf->array_len,src_bones,src_weights,skeleton);
+ if (surf->format & VS::ARRAY_FORMAT_NORMAL && surf->format & VS::ARRAY_FORMAT_TANGENT)
+ _skeleton_xform<true, true, false>(surf->array_local, surf->stride, base, dst_stride, surf->array_len, src_bones, src_weights, skeleton);
+ else if (surf->format & (VS::ARRAY_FORMAT_NORMAL))
+ _skeleton_xform<true, false, false>(surf->array_local, surf->stride, base, dst_stride, surf->array_len, src_bones, src_weights, skeleton);
+ else if (surf->format & (VS::ARRAY_FORMAT_TANGENT))
+ _skeleton_xform<false, true, false>(surf->array_local, surf->stride, base, dst_stride, surf->array_len, src_bones, src_weights, skeleton);
else
- _skeleton_xform<false,false,false>(surf->array_local,surf->stride,base,dst_stride,surf->array_len,src_bones,src_weights,skeleton);
-
+ _skeleton_xform<false, false, false>(surf->array_local, surf->stride, base, dst_stride, surf->array_len, src_bones, src_weights, skeleton);
- stride=dst_stride;
+ stride = dst_stride;
}
-
-
-
} else {
glBindBuffer(GL_ARRAY_BUFFER, surf->vertex_id);
};
- for (int i=0;i<(VS::ARRAY_MAX-1);i++) {
+ for (int i = 0; i < (VS::ARRAY_MAX - 1); i++) {
- const Surface::ArrayData& ad=surf->array[i];
+ const Surface::ArrayData &ad = surf->array[i];
/*
if (!gl_texcoord_shader[i])
continue;
*/
- if (ad.size==0 || ! ad.bind) {
+ if (ad.size == 0 || !ad.bind) {
glDisableVertexAttribArray(i);
if (i == VS::ARRAY_COLOR) {
- _set_color_attrib(Color(1, 1, 1,1));
+ _set_color_attrib(Color(1, 1, 1, 1));
};
//print_line("disable: "+itos(i));
continue; // this one is disabled.
@@ -5961,11 +5566,10 @@ Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Materia
glEnableVertexAttribArray(i);
//print_line("set: "+itos(i)+" - count: "+itos(ad.count)+" datatype: "+itos(ad.datatype)+" ofs: "+itos(ad.ofs)+" stride: "+itos(stride)+" total len: "+itos(surf->array_len));
glVertexAttribPointer(i, ad.count, ad.datatype, ad.normalize, stride, &base[ad.ofs]);
-
}
#ifdef GLEW_ENABLED
-//"desktop" opengl needs this.
- if (surf->primitive==VS::PRIMITIVE_POINTS) {
+ //"desktop" opengl needs this.
+ if (surf->primitive == VS::PRIMITIVE_POINTS) {
glEnable(GL_POINT_SPRITE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
@@ -5977,13 +5581,12 @@ Error RasterizerGLES2::_setup_geometry(const Geometry *p_geometry, const Materia
} break;
default: break;
-
};
return OK;
};
-static const GLenum gl_primitive[]={
+static const GLenum gl_primitive[] = {
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
@@ -5993,43 +5596,37 @@ static const GLenum gl_primitive[]={
GL_TRIANGLE_FAN
};
-
-
-void RasterizerGLES2::_render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton, const GeometryOwner *p_owner,const Transform& p_xform) {
-
+void RasterizerGLES2::_render(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton, const GeometryOwner *p_owner, const Transform &p_xform) {
_rinfo.object_count++;
- switch(p_geometry->type) {
+ switch (p_geometry->type) {
case Geometry::GEOMETRY_SURFACE: {
- Surface *s = (Surface*)p_geometry;
+ Surface *s = (Surface *)p_geometry;
- _rinfo.vertex_count+=s->array_len;
+ _rinfo.vertex_count += s->array_len;
- if (s->index_array_len>0) {
+ if (s->index_array_len > 0) {
if (s->index_array_local) {
//print_line("LOCAL F: "+itos(s->format)+" C: "+itos(s->index_array_len)+" VC: "+itos(s->array_len));
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
- glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len>(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT, s->index_array_local);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len > (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, s->index_array_local);
} else {
//print_line("indices: "+itos(s->index_array_local) );
-
//print_line("VBO F: "+itos(s->format)+" C: "+itos(s->index_array_len)+" VC: "+itos(s->array_len));
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len > (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
}
-
} else {
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
-
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
};
_rinfo.draw_calls++;
@@ -6038,145 +5635,136 @@ void RasterizerGLES2::_render(const Geometry *p_geometry,const Material *p_mater
case Geometry::GEOMETRY_MULTISURFACE: {
material_shader.bind_uniforms();
- Surface *s = static_cast<const MultiMeshSurface*>(p_geometry)->surface;
- const MultiMesh *mm = static_cast<const MultiMesh*>(p_owner);
- int element_count=mm->elements.size();
+ Surface *s = static_cast<const MultiMeshSurface *>(p_geometry)->surface;
+ const MultiMesh *mm = static_cast<const MultiMesh *>(p_owner);
+ int element_count = mm->elements.size();
- if (element_count==0)
+ if (element_count == 0)
return;
- if (mm->visible>=0) {
- element_count=MIN(element_count,mm->visible);
+ if (mm->visible >= 0) {
+ element_count = MIN(element_count, mm->visible);
}
- const MultiMesh::Element *elements=&mm->elements[0];
-
- _rinfo.vertex_count+=s->array_len*element_count;
+ const MultiMesh::Element *elements = &mm->elements[0];
- _rinfo.draw_calls+=element_count;
+ _rinfo.vertex_count += s->array_len * element_count;
+ _rinfo.draw_calls += element_count;
if (use_texture_instancing) {
//this is probably the fastest all around way if vertex texture fetch is supported
- float twd=(1.0/mm->tw)*4.0;
- float thd=1.0/mm->th;
- float parm[3]={0.0,01.0,(1.0f/mm->tw)};
- glActiveTexture(GL_TEXTURE0+max_texture_units-2);
+ float twd = (1.0 / mm->tw) * 4.0;
+ float thd = 1.0 / mm->th;
+ float parm[3] = { 0.0, 01.0, (1.0f / mm->tw) };
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 2);
glDisableVertexAttribArray(6);
- glBindTexture(GL_TEXTURE_2D,mm->tex_id);
- material_shader.set_uniform(MaterialShaderGLES2::INSTANCE_MATRICES,GL_TEXTURE0+max_texture_units-2);
-
- if (s->index_array_len>0) {
+ glBindTexture(GL_TEXTURE_2D, mm->tex_id);
+ material_shader.set_uniform(MaterialShaderGLES2::INSTANCE_MATRICES, GL_TEXTURE0 + max_texture_units - 2);
+ if (s->index_array_len > 0) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
- for(int i=0;i<element_count;i++) {
- parm[0]=(i%(mm->tw>>2))*twd;
- parm[1]=(i/(mm->tw>>2))*thd;
- glVertexAttrib3fv(6,parm);
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0);
-
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
+ for (int i = 0; i < element_count; i++) {
+ parm[0] = (i % (mm->tw >> 2)) * twd;
+ parm[1] = (i / (mm->tw >> 2)) * thd;
+ glVertexAttrib3fv(6, parm);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len > (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
}
-
} else {
- for(int i=0;i<element_count;i++) {
+ for (int i = 0; i < element_count; i++) {
//parm[0]=(i%(mm->tw>>2))*twd;
//parm[1]=(i/(mm->tw>>2))*thd;
- glVertexAttrib3fv(6,parm);
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
+ glVertexAttrib3fv(6, parm);
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
}
- };
+ };
} else if (use_attribute_instancing) {
//if not, using atributes instead of uniforms can be really fast in forward rendering architectures
- if (s->index_array_len>0) {
-
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
- for(int i=0;i<element_count;i++) {
- glVertexAttrib4fv(8,&elements[i].matrix[0]);
- glVertexAttrib4fv(9,&elements[i].matrix[4]);
- glVertexAttrib4fv(10,&elements[i].matrix[8]);
- glVertexAttrib4fv(11,&elements[i].matrix[12]);
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0);
+ if (s->index_array_len > 0) {
+
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
+ for (int i = 0; i < element_count; i++) {
+ glVertexAttrib4fv(8, &elements[i].matrix[0]);
+ glVertexAttrib4fv(9, &elements[i].matrix[4]);
+ glVertexAttrib4fv(10, &elements[i].matrix[8]);
+ glVertexAttrib4fv(11, &elements[i].matrix[12]);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len > (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
}
-
} else {
- for(int i=0;i<element_count;i++) {
- glVertexAttrib4fv(8,&elements[i].matrix[0]);
- glVertexAttrib4fv(9,&elements[i].matrix[4]);
- glVertexAttrib4fv(10,&elements[i].matrix[8]);
- glVertexAttrib4fv(11,&elements[i].matrix[12]);
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
+ for (int i = 0; i < element_count; i++) {
+ glVertexAttrib4fv(8, &elements[i].matrix[0]);
+ glVertexAttrib4fv(9, &elements[i].matrix[4]);
+ glVertexAttrib4fv(10, &elements[i].matrix[8]);
+ glVertexAttrib4fv(11, &elements[i].matrix[12]);
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
}
- };
-
+ };
} else {
//nothing to do, slow path (hope no hardware has to use it... but you never know)
- if (s->index_array_len>0) {
+ if (s->index_array_len > 0) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
- for(int i=0;i<element_count;i++) {
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
+ for (int i = 0; i < element_count; i++) {
glUniformMatrix4fv(material_shader.get_uniform_location(MaterialShaderGLES2::INSTANCE_TRANSFORM), 1, false, elements[i].matrix);
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len > (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
}
-
} else {
- for(int i=0;i<element_count;i++) {
+ for (int i = 0; i < element_count; i++) {
glUniformMatrix4fv(material_shader.get_uniform_location(MaterialShaderGLES2::INSTANCE_TRANSFORM), 1, false, elements[i].matrix);
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
}
- };
+ };
}
- } break;
+ } break;
case Geometry::GEOMETRY_IMMEDIATE: {
- bool restore_tex=false;
- const Immediate *im = static_cast<const Immediate*>( p_geometry );
+ bool restore_tex = false;
+ const Immediate *im = static_cast<const Immediate *>(p_geometry);
if (im->building) {
return;
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
- for(const List<Immediate::Chunk>::Element *E=im->chunks.front();E;E=E->next()) {
+ for (const List<Immediate::Chunk>::Element *E = im->chunks.front(); E; E = E->next()) {
- const Immediate::Chunk &c=E->get();
+ const Immediate::Chunk &c = E->get();
if (c.vertices.empty()) {
continue;
}
- for(int i=0;i<c.vertices.size();i++)
-
- if (c.texture.is_valid() && texture_owner.owns(c.texture)) {
+ for (int i = 0; i < c.vertices.size(); i++)
- const Texture *t = texture_owner.get(c.texture);
- glActiveTexture(GL_TEXTURE0+tc0_idx);
- glBindTexture(t->target,t->tex_id);
- restore_tex=true;
+ if (c.texture.is_valid() && texture_owner.owns(c.texture)) {
+ const Texture *t = texture_owner.get(c.texture);
+ glActiveTexture(GL_TEXTURE0 + tc0_idx);
+ glBindTexture(t->target, t->tex_id);
+ restore_tex = true;
- } else if (restore_tex) {
+ } else if (restore_tex) {
- glActiveTexture(GL_TEXTURE0+tc0_idx);
- glBindTexture(GL_TEXTURE_2D,tc0_id_cache);
- restore_tex=false;
- }
+ glActiveTexture(GL_TEXTURE0 + tc0_idx);
+ glBindTexture(GL_TEXTURE_2D, tc0_id_cache);
+ restore_tex = false;
+ }
if (!c.normals.empty()) {
glEnableVertexAttribArray(VS::ARRAY_NORMAL);
- glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false,sizeof(Vector3),c.normals.ptr());
+ glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false, sizeof(Vector3), c.normals.ptr());
} else {
@@ -6186,7 +5774,7 @@ void RasterizerGLES2::_render(const Geometry *p_geometry,const Material *p_mater
if (!c.tangents.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TANGENT);
- glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false,sizeof(Plane),c.tangents.ptr());
+ glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false, sizeof(Plane), c.tangents.ptr());
} else {
@@ -6196,19 +5784,18 @@ void RasterizerGLES2::_render(const Geometry *p_geometry,const Material *p_mater
if (!c.colors.empty()) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false,sizeof(Color),c.colors.ptr());
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), c.colors.ptr());
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
- _set_color_attrib(Color(1, 1, 1,1));
+ _set_color_attrib(Color(1, 1, 1, 1));
}
-
if (!c.uvs.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false,sizeof(Vector2),c.uvs.ptr());
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), c.uvs.ptr());
} else {
@@ -6218,101 +5805,91 @@ void RasterizerGLES2::_render(const Geometry *p_geometry,const Material *p_mater
if (!c.uvs2.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV2);
- glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false,sizeof(Vector2),c.uvs2.ptr());
+ glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false, sizeof(Vector2), c.uvs2.ptr());
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV2);
}
-
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false,sizeof(Vector3),c.vertices.ptr());
- glDrawArrays(gl_primitive[c.primitive],0,c.vertices.size());
-
-
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, sizeof(Vector3), c.vertices.ptr());
+ glDrawArrays(gl_primitive[c.primitive], 0, c.vertices.size());
}
-
if (restore_tex) {
- glActiveTexture(GL_TEXTURE0+tc0_idx);
- glBindTexture(GL_TEXTURE_2D,tc0_id_cache);
- restore_tex=false;
+ glActiveTexture(GL_TEXTURE0 + tc0_idx);
+ glBindTexture(GL_TEXTURE_2D, tc0_id_cache);
+ restore_tex = false;
}
-
} break;
case Geometry::GEOMETRY_PARTICLES: {
-
//print_line("particulinas");
- const Particles *particles = static_cast<const Particles*>( p_geometry );
+ const Particles *particles = static_cast<const Particles *>(p_geometry);
ERR_FAIL_COND(!p_owner);
- ParticlesInstance *particles_instance = (ParticlesInstance*)p_owner;
+ ParticlesInstance *particles_instance = (ParticlesInstance *)p_owner;
ParticleSystemProcessSW &pp = particles_instance->particles_process;
float td = time_delta; //MIN(time_delta,1.0/10.0);
- pp.process(&particles->data,particles_instance->transform,td);
+ pp.process(&particles->data, particles_instance->transform, td);
ERR_EXPLAIN("A parameter in the particle system is not correct.");
ERR_FAIL_COND(!pp.valid);
-
Transform camera;
if (shadow)
- camera=shadow->transform;
+ camera = shadow->transform;
else
- camera=camera_transform;
-
- particle_draw_info.prepare(&particles->data,&pp,particles_instance->transform,camera);
- _rinfo.draw_calls+=particles->data.amount;
+ camera = camera_transform;
+ particle_draw_info.prepare(&particles->data, &pp, particles_instance->transform, camera);
+ _rinfo.draw_calls += particles->data.amount;
- _rinfo.vertex_count+=4*particles->data.amount;
+ _rinfo.vertex_count += 4 * particles->data.amount;
{
- static const Vector3 points[4]={
- Vector3(-1.0,1.0,0),
- Vector3(1.0,1.0,0),
- Vector3(1.0,-1.0,0),
- Vector3(-1.0,-1.0,0)
+ static const Vector3 points[4] = {
+ Vector3(-1.0, 1.0, 0),
+ Vector3(1.0, 1.0, 0),
+ Vector3(1.0, -1.0, 0),
+ Vector3(-1.0, -1.0, 0)
};
- static const Vector3 uvs[4]={
- Vector3(0.0,0.0,0.0),
- Vector3(1.0,0.0,0.0),
- Vector3(1.0,1.0,0.0),
- Vector3(0,1.0,0.0)
+ static const Vector3 uvs[4] = {
+ Vector3(0.0, 0.0, 0.0),
+ Vector3(1.0, 0.0, 0.0),
+ Vector3(1.0, 1.0, 0.0),
+ Vector3(0, 1.0, 0.0)
};
- static const Vector3 normals[4]={
- Vector3(0,0,1),
- Vector3(0,0,1),
- Vector3(0,0,1),
- Vector3(0,0,1)
+ static const Vector3 normals[4] = {
+ Vector3(0, 0, 1),
+ Vector3(0, 0, 1),
+ Vector3(0, 0, 1),
+ Vector3(0, 0, 1)
};
- static const Plane tangents[4]={
- Plane(Vector3(1,0,0),0),
- Plane(Vector3(1,0,0),0),
- Plane(Vector3(1,0,0),0),
- Plane(Vector3(1,0,0),0)
+ static const Plane tangents[4] = {
+ Plane(Vector3(1, 0, 0), 0),
+ Plane(Vector3(1, 0, 0), 0),
+ Plane(Vector3(1, 0, 0), 0),
+ Plane(Vector3(1, 0, 0), 0)
};
- for(int i=0;i<particles->data.amount;i++) {
+ for (int i = 0; i < particles->data.amount; i++) {
- ParticleSystemDrawInfoSW::ParticleDrawInfo &pinfo=*particle_draw_info.draw_info_order[i];
+ ParticleSystemDrawInfoSW::ParticleDrawInfo &pinfo = *particle_draw_info.draw_info_order[i];
if (!pinfo.data->active)
continue;
material_shader.set_uniform(MaterialShaderGLES2::WORLD_TRANSFORM, pinfo.transform);
_set_color_attrib(pinfo.color);
- _draw_primitive(4,points,normals,NULL,uvs,tangents);
-
+ _draw_primitive(4, points, normals, NULL, uvs, tangents);
}
-
}
} break;
- default: break;
+ default: break;
};
};
@@ -6358,234 +5935,214 @@ void RasterizerGLES2::_setup_shader_params(const Material *p_material) {
}
#endif
-
}
void RasterizerGLES2::_setup_skeleton(const Skeleton *p_skeleton) {
- material_shader.set_conditional(MaterialShaderGLES2::USE_SKELETON,p_skeleton!=NULL);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SKELETON, p_skeleton != NULL);
if (p_skeleton && p_skeleton->tex_id) {
- glActiveTexture(GL_TEXTURE0+max_texture_units-2);
- glBindTexture(GL_TEXTURE_2D,p_skeleton->tex_id);
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 2);
+ glBindTexture(GL_TEXTURE_2D, p_skeleton->tex_id);
}
-
-
}
-
-void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Transform& p_view_transform, const Transform& p_view_transform_inverse,const CameraMatrix& p_projection,bool p_reverse_cull,bool p_fragment_light,bool p_alpha_pass) {
+void RasterizerGLES2::_render_list_forward(RenderList *p_render_list, const Transform &p_view_transform, const Transform &p_view_transform_inverse, const CameraMatrix &p_projection, bool p_reverse_cull, bool p_fragment_light, bool p_alpha_pass) {
if (current_rt && current_rt_vflip) {
//p_reverse_cull=!p_reverse_cull;
glFrontFace(GL_CCW);
-
}
- const Material *prev_material=NULL;
- uint16_t prev_light=0x777E;
- const Geometry *prev_geometry_cmp=NULL;
- uint8_t prev_light_type=0xEF;
- const Skeleton *prev_skeleton =NULL;
- uint8_t prev_sort_flags=0xFF;
- const BakedLightData *prev_baked_light=NULL;
+ const Material *prev_material = NULL;
+ uint16_t prev_light = 0x777E;
+ const Geometry *prev_geometry_cmp = NULL;
+ uint8_t prev_light_type = 0xEF;
+ const Skeleton *prev_skeleton = NULL;
+ uint8_t prev_sort_flags = 0xFF;
+ const BakedLightData *prev_baked_light = NULL;
RID prev_baked_light_texture;
- const float *prev_morph_values=NULL;
- int prev_receive_shadows_state=-1;
+ const float *prev_morph_values = NULL;
+ int prev_receive_shadows_state = -1;
- material_shader.set_conditional(MaterialShaderGLES2::USE_VERTEX_LIGHTING,!shadow && !p_fragment_light);
- material_shader.set_conditional(MaterialShaderGLES2::USE_FRAGMENT_LIGHTING,!shadow && p_fragment_light);
- material_shader.set_conditional(MaterialShaderGLES2::USE_SKELETON,false);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_VERTEX_LIGHTING, !shadow && !p_fragment_light);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_FRAGMENT_LIGHTING, !shadow && p_fragment_light);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_SKELETON, false);
if (shadow) {
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4,false);
- material_shader.set_conditional(MaterialShaderGLES2::SHADELESS,false);
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_OCTREE,false);
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP,false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4, false);
+ material_shader.set_conditional(MaterialShaderGLES2::SHADELESS, false);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_OCTREE, false);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP, false);
//material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_TEXTURE,false);
-
}
-
-
bool stores_glow = !shadow && (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) && !p_alpha_pass;
- float sampled_light_dp_multiplier=1.0;
+ float sampled_light_dp_multiplier = 1.0;
- bool prev_blend=false;
+ bool prev_blend = false;
glDisable(GL_BLEND);
- for (int i=0;i<p_render_list->element_count;i++) {
+ for (int i = 0; i < p_render_list->element_count; i++) {
RenderList::Element *e = p_render_list->elements[i];
const Material *material = e->material;
uint16_t light = e->light;
uint8_t light_type = e->light_type;
- uint8_t sort_flags= e->sort_flags;
+ uint8_t sort_flags = e->sort_flags;
const Skeleton *skeleton = e->skeleton;
const Geometry *geometry_cmp = e->geometry_cmp;
const BakedLightData *baked_light = e->instance->baked_light;
const float *morph_values = e->instance->morph_values.ptr();
int receive_shadows_state = e->instance->receive_shadows == true ? 1 : 0;
- bool rebind=false;
- bool bind_baked_light_octree=false;
- bool bind_baked_lightmap=false;
- bool additive=false;
- bool bind_dp_sampler=false;
-
+ bool rebind = false;
+ bool bind_baked_light_octree = false;
+ bool bind_baked_lightmap = false;
+ bool additive = false;
+ bool bind_dp_sampler = false;
if (!shadow) {
if (texscreen_used && !texscreen_copied && material->shader_cache && material->shader_cache->valid && material->shader_cache->has_texscreen) {
- texscreen_copied=true;
+ texscreen_copied = true;
_copy_to_texscreen();
//force reset state
- prev_material=NULL;
- prev_light=0x777E;
- prev_geometry_cmp=NULL;
- prev_light_type=0xEF;
- prev_skeleton =NULL;
- prev_sort_flags=0xFF;
- prev_morph_values=NULL;
- prev_receive_shadows_state=-1;
+ prev_material = NULL;
+ prev_light = 0x777E;
+ prev_geometry_cmp = NULL;
+ prev_light_type = 0xEF;
+ prev_skeleton = NULL;
+ prev_sort_flags = 0xFF;
+ prev_morph_values = NULL;
+ prev_receive_shadows_state = -1;
glEnable(GL_BLEND);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
-
}
- if (light_type!=prev_light_type || receive_shadows_state!=prev_receive_shadows_state) {
+ if (light_type != prev_light_type || receive_shadows_state != prev_receive_shadows_state) {
- if (material->flags[VS::MATERIAL_FLAG_UNSHADED] || current_debug==VS::SCENARIO_DEBUG_SHADELESS) {
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4,false);
- material_shader.set_conditional(MaterialShaderGLES2::SHADELESS,true);
+ if (material->flags[VS::MATERIAL_FLAG_UNSHADED] || current_debug == VS::SCENARIO_DEBUG_SHADELESS) {
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4, false);
+ material_shader.set_conditional(MaterialShaderGLES2::SHADELESS, true);
} else {
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL,(light_type&0x3)==VS::LIGHT_DIRECTIONAL);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI,(light_type&0x3)==VS::LIGHT_OMNI);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT,(light_type&0x3)==VS::LIGHT_SPOT);
- if (receive_shadows_state==1) {
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW,(light_type&0x8));
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM,(light_type&0x10));
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4,(light_type&0x20));
- }
- else {
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM,false);
- material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4,false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_DIRECTIONAL, (light_type & 0x3) == VS::LIGHT_DIRECTIONAL);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_OMNI, (light_type & 0x3) == VS::LIGHT_OMNI);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_TYPE_SPOT, (light_type & 0x3) == VS::LIGHT_SPOT);
+ if (receive_shadows_state == 1) {
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW, (light_type & 0x8));
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM, (light_type & 0x10));
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4, (light_type & 0x20));
+ } else {
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_SHADOW, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM, false);
+ material_shader.set_conditional(MaterialShaderGLES2::LIGHT_USE_PSSM4, false);
}
- material_shader.set_conditional(MaterialShaderGLES2::SHADELESS,false);
+ material_shader.set_conditional(MaterialShaderGLES2::SHADELESS, false);
}
- rebind=true;
+ rebind = true;
}
-
if (!*e->additive_ptr) {
- additive=false;
- *e->additive_ptr=true;
+ additive = false;
+ *e->additive_ptr = true;
} else {
- additive=true;
+ additive = true;
}
-
if (stores_glow)
- material_shader.set_conditional(MaterialShaderGLES2::USE_GLOW,!additive);
-
+ material_shader.set_conditional(MaterialShaderGLES2::USE_GLOW, !additive);
- bool desired_blend=false;
- VS::MaterialBlendMode desired_blend_mode=VS::MATERIAL_BLEND_MODE_MIX;
+ bool desired_blend = false;
+ VS::MaterialBlendMode desired_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
if (additive) {
- desired_blend=true;
- desired_blend_mode=VS::MATERIAL_BLEND_MODE_ADD;
+ desired_blend = true;
+ desired_blend_mode = VS::MATERIAL_BLEND_MODE_ADD;
} else {
- desired_blend=p_alpha_pass;
- desired_blend_mode=material->blend_mode;
+ desired_blend = p_alpha_pass;
+ desired_blend_mode = material->blend_mode;
}
- if (prev_blend!=desired_blend) {
+ if (prev_blend != desired_blend) {
if (desired_blend) {
glEnable(GL_BLEND);
if (!current_rt || !current_rt_transparent)
- glColorMask(1,1,1,0);
+ glColorMask(1, 1, 1, 0);
} else {
glDisable(GL_BLEND);
- glColorMask(1,1,1,1);
-
+ glColorMask(1, 1, 1, 1);
}
- prev_blend=desired_blend;
+ prev_blend = desired_blend;
}
- if (desired_blend && desired_blend_mode!=current_blend_mode) {
-
+ if (desired_blend && desired_blend_mode != current_blend_mode) {
- switch(desired_blend_mode) {
+ switch (desired_blend_mode) {
- case VS::MATERIAL_BLEND_MODE_MIX: {
+ case VS::MATERIAL_BLEND_MODE_MIX: {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- } break;
- case VS::MATERIAL_BLEND_MODE_ADD: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(p_alpha_pass?GL_SRC_ALPHA:GL_ONE,GL_ONE);
+ glBlendFunc(p_alpha_pass ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
- } break;
- case VS::MATERIAL_BLEND_MODE_SUB: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
- } break;
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ } break;
case VS::MATERIAL_BLEND_MODE_MUL: {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
} break;
-
}
- current_blend_mode=desired_blend_mode;
+ current_blend_mode = desired_blend_mode;
}
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_OCTREE,false);
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP,false);
- material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_DP_SAMPLER,false);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_OCTREE, false);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP, false);
+ material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_DP_SAMPLER, false);
material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_COLOR, false);
-
if (material->flags[VS::MATERIAL_FLAG_UNSHADED] == false && current_debug != VS::SCENARIO_DEBUG_SHADELESS) {
if (baked_light != NULL) {
if (baked_light->realtime_color_enabled) {
float realtime_energy = baked_light->realtime_energy;
material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_COLOR, true);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_COLOR, Vector3(baked_light->realtime_color.r*realtime_energy, baked_light->realtime_color.g*realtime_energy, baked_light->realtime_color.b*realtime_energy));
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_COLOR, Vector3(baked_light->realtime_color.r * realtime_energy, baked_light->realtime_color.g * realtime_energy, baked_light->realtime_color.b * realtime_energy));
}
}
@@ -6603,7 +6160,6 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
}
}
-
if (!additive && baked_light) {
if (baked_light->mode == VS::BAKED_LIGHT_OCTREE && baked_light->octree_texture.is_valid() && e->instance->baked_light_octree_xform) {
@@ -6623,26 +6179,20 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
glBindTexture(texl->target, texl->tex_id); //bind the light texture
}
}
-
}
- }
- else if (baked_light->mode == VS::BAKED_LIGHT_LIGHTMAPS) {
-
+ } else if (baked_light->mode == VS::BAKED_LIGHT_LIGHTMAPS) {
int lightmap_idx = e->instance->baked_lightmap_id;
material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP, false);
bind_baked_lightmap = false;
-
if (baked_light->lightmaps.has(lightmap_idx)) {
-
RID texid = baked_light->lightmaps[lightmap_idx];
if (prev_baked_light != baked_light || texid != prev_baked_light_texture) {
-
Texture *tex = texture_owner.get(texid);
if (tex) {
@@ -6657,7 +6207,6 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
material_shader.set_conditional(MaterialShaderGLES2::ENABLE_AMBIENT_LIGHTMAP, true);
bind_baked_lightmap = true;
}
-
}
}
}
@@ -6668,33 +6217,33 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
}
}
- if (sort_flags!=prev_sort_flags) {
+ if (sort_flags != prev_sort_flags) {
- if (sort_flags&RenderList::SORT_FLAG_INSTANCING) {
- material_shader.set_conditional(MaterialShaderGLES2::USE_UNIFORM_INSTANCING,!use_texture_instancing && !use_attribute_instancing);
- material_shader.set_conditional(MaterialShaderGLES2::USE_ATTRIBUTE_INSTANCING,use_attribute_instancing);
- material_shader.set_conditional(MaterialShaderGLES2::USE_TEXTURE_INSTANCING,use_texture_instancing);
+ if (sort_flags & RenderList::SORT_FLAG_INSTANCING) {
+ material_shader.set_conditional(MaterialShaderGLES2::USE_UNIFORM_INSTANCING, !use_texture_instancing && !use_attribute_instancing);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_ATTRIBUTE_INSTANCING, use_attribute_instancing);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_TEXTURE_INSTANCING, use_texture_instancing);
} else {
- material_shader.set_conditional(MaterialShaderGLES2::USE_UNIFORM_INSTANCING,false);
- material_shader.set_conditional(MaterialShaderGLES2::USE_ATTRIBUTE_INSTANCING,false);
- material_shader.set_conditional(MaterialShaderGLES2::USE_TEXTURE_INSTANCING,false);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_UNIFORM_INSTANCING, false);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_ATTRIBUTE_INSTANCING, false);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_TEXTURE_INSTANCING, false);
}
- rebind=true;
+ rebind = true;
}
- if (use_hw_skeleton_xform && (skeleton!=prev_skeleton||morph_values!=prev_morph_values)) {
+ if (use_hw_skeleton_xform && (skeleton != prev_skeleton || morph_values != prev_morph_values)) {
if (!prev_skeleton || !skeleton)
- rebind=true; //went from skeleton <-> no skeleton, needs rebind
+ rebind = true; //went from skeleton <-> no skeleton, needs rebind
- if (morph_values==NULL)
+ if (morph_values == NULL)
_setup_skeleton(skeleton);
else
_setup_skeleton(NULL);
}
- if (material!=prev_material || rebind) {
+ if (material != prev_material || rebind) {
- rebind = _setup_material(e->geometry,material,additive,!p_alpha_pass);
+ rebind = _setup_material(e->geometry, material, additive, !p_alpha_pass);
DEBUG_TEST_ERROR("Setup material");
_rinfo.mat_change_count++;
@@ -6702,74 +6251,68 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
//_setup_material_skeleton(material,skeleton);
} else {
- if (prev_skeleton!=skeleton) {
+ if (prev_skeleton != skeleton) {
//_setup_material_skeleton(material,skeleton);
};
}
+ if (geometry_cmp != prev_geometry_cmp || prev_skeleton != skeleton) {
- if (geometry_cmp!=prev_geometry_cmp || prev_skeleton!=skeleton) {
-
- _setup_geometry(e->geometry, material,e->skeleton,e->instance->morph_values.ptr());
+ _setup_geometry(e->geometry, material, e->skeleton, e->instance->morph_values.ptr());
_rinfo.surface_count++;
DEBUG_TEST_ERROR("Setup geometry");
};
- if (i==0 || light!=prev_light || rebind) {
- if (e->light!=0xFFFF) {
+ if (i == 0 || light != prev_light || rebind) {
+ if (e->light != 0xFFFF) {
_setup_light(e->light);
-
}
}
- if (bind_baked_light_octree && (baked_light!=prev_baked_light || rebind)) {
+ if (bind_baked_light_octree && (baked_light != prev_baked_light || rebind)) {
material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_INVERSE_TRANSFORM, *e->instance->baked_light_octree_xform);
material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LATTICE_SIZE, baked_light->octree_lattice_size);
material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LATTICE_DIVIDE, baked_light->octree_lattice_divide);
material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_STEPS, baked_light->octree_steps);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_TEX,max_texture_units-3);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_TEX, max_texture_units - 3);
if (baked_light->light_texture.is_valid()) {
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_TEX,max_texture_units-4);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_PIX_SIZE,baked_light->light_tex_pixel_size);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_TEX, max_texture_units - 4);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_PIX_SIZE, baked_light->light_tex_pixel_size);
} else {
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_TEX,max_texture_units-3);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_PIX_SIZE,baked_light->octree_tex_pixel_size);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_TEX, max_texture_units - 3);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_LIGHT_PIX_SIZE, baked_light->octree_tex_pixel_size);
}
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_MULTIPLIER,baked_light->texture_multiplier);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_PIX_SIZE,baked_light->octree_tex_pixel_size);
-
-
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_MULTIPLIER, baked_light->texture_multiplier);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_OCTREE_PIX_SIZE, baked_light->octree_tex_pixel_size);
}
- if (bind_baked_lightmap && (baked_light!=prev_baked_light || rebind)) {
+ if (bind_baked_lightmap && (baked_light != prev_baked_light || rebind)) {
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHTMAP, max_texture_units-3);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHTMAP, max_texture_units - 3);
material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHTMAP_MULTIPLIER, baked_light->lightmap_multiplier);
-
}
if (bind_dp_sampler) {
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_DP_SAMPLER_MULTIPLIER,sampled_light_dp_multiplier);
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_DP_SAMPLER,max_texture_units-3);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_DP_SAMPLER_MULTIPLIER, sampled_light_dp_multiplier);
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_DP_SAMPLER, max_texture_units - 3);
}
- _set_cull(e->mirror,p_reverse_cull);
-
+ _set_cull(e->mirror, p_reverse_cull);
- if (i==0 || rebind) {
+ if (i == 0 || rebind) {
material_shader.set_uniform(MaterialShaderGLES2::CAMERA_INVERSE_TRANSFORM, p_view_transform_inverse);
material_shader.set_uniform(MaterialShaderGLES2::PROJECTION_TRANSFORM, p_projection);
if (!shadow) {
if (!additive && current_env && current_env->fx_enabled[VS::ENV_FX_AMBIENT_LIGHT]) {
Color ambcolor = _convert_color(current_env->fx_param[VS::ENV_FX_PARAM_AMBIENT_LIGHT_COLOR]);
- float ambnrg = current_env->fx_param[VS::ENV_FX_PARAM_AMBIENT_LIGHT_ENERGY];
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHT,Vector3(ambcolor.r*ambnrg,ambcolor.g*ambnrg,ambcolor.b*ambnrg));
+ float ambnrg = current_env->fx_param[VS::ENV_FX_PARAM_AMBIENT_LIGHT_ENERGY];
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHT, Vector3(ambcolor.r * ambnrg, ambcolor.g * ambnrg, ambcolor.b * ambnrg));
} else {
- material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHT,Vector3());
+ material_shader.set_uniform(MaterialShaderGLES2::AMBIENT_LIGHT, Vector3());
}
}
@@ -6785,20 +6328,20 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
if (e->instance->billboard || e->instance->billboard_y || e->instance->depth_scale) {
- Transform xf=e->instance->transform;
+ Transform xf = e->instance->transform;
if (e->instance->depth_scale) {
if (p_projection.matrix[3][3]) {
//orthogonal matrix, try to do about the same
//with viewport size
//real_t w = Math::abs( 1.0/(2.0*(p_projection.matrix[0][0])) );
- real_t h = Math::abs( 1.0/(2.0*p_projection.matrix[1][1]) );
- float sc = (h*2.0); //consistent with Y-fov
- xf.basis.scale( Vector3(sc,sc,sc));
+ real_t h = Math::abs(1.0 / (2.0 * p_projection.matrix[1][1]));
+ float sc = (h * 2.0); //consistent with Y-fov
+ xf.basis.scale(Vector3(sc, sc, sc));
} else {
//just scale by depth
real_t sc = -camera_plane.distance_to(xf.origin);
- xf.basis.scale( Vector3(sc,sc,sc));
+ xf.basis.scale(Vector3(sc, sc, sc));
}
}
@@ -6814,18 +6357,18 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
xf.basis.scale(scale);
}
-
+
if (e->instance->billboard_y) {
-
+
Vector3 scale = xf.basis.get_scale();
- Vector3 look_at = p_view_transform.get_origin();
+ Vector3 look_at = p_view_transform.get_origin();
look_at.y = 0.0;
Vector3 look_at_norm = look_at.normalized();
-
+
if (current_rt && current_rt_vflip) {
- xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, -1.0, 0.0));
+ xf.set_look_at(xf.origin, xf.origin + look_at_norm, Vector3(0.0, -1.0, 0.0));
} else {
- xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, 1.0, 0.0));
+ xf.set_look_at(xf.origin, xf.origin + look_at_norm, Vector3(0.0, 1.0, 0.0));
}
xf.basis.scale(scale);
}
@@ -6835,34 +6378,30 @@ void RasterizerGLES2::_render_list_forward(RenderList *p_render_list,const Trans
material_shader.set_uniform(MaterialShaderGLES2::WORLD_TRANSFORM, e->instance->transform);
}
- material_shader.set_uniform(MaterialShaderGLES2::NORMAL_MULT, e->mirror?-1.0:1.0);
- material_shader.set_uniform(MaterialShaderGLES2::CONST_LIGHT_MULT,additive?0.0:1.0);
-
+ material_shader.set_uniform(MaterialShaderGLES2::NORMAL_MULT, e->mirror ? -1.0 : 1.0);
+ material_shader.set_uniform(MaterialShaderGLES2::CONST_LIGHT_MULT, additive ? 0.0 : 1.0);
- _render(e->geometry, material, skeleton,e->owner,e->instance->transform);
+ _render(e->geometry, material, skeleton, e->owner, e->instance->transform);
DEBUG_TEST_ERROR("Rendering");
- prev_material=material;
- prev_skeleton=skeleton;
- prev_geometry_cmp=geometry_cmp;
- prev_light=e->light;
- prev_light_type=e->light_type;
- prev_sort_flags=sort_flags;
- prev_baked_light=baked_light;
- prev_morph_values=morph_values;
- prev_receive_shadows_state=receive_shadows_state;
+ prev_material = material;
+ prev_skeleton = skeleton;
+ prev_geometry_cmp = geometry_cmp;
+ prev_light = e->light;
+ prev_light_type = e->light_type;
+ prev_sort_flags = sort_flags;
+ prev_baked_light = baked_light;
+ prev_morph_values = morph_values;
+ prev_receive_shadows_state = receive_shadows_state;
}
//print_line("shaderchanges: "+itos(p_alpha_pass)+": "+itos(_rinfo.shader_change_count));
-
if (current_rt && current_rt_vflip) {
glFrontFace(GL_CW);
}
-
};
-
void RasterizerGLES2::_copy_to_texscreen() {
//what am i missing?
@@ -6877,153 +6416,139 @@ void RasterizerGLES2::_copy_to_texscreen() {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
//glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
glDisableVertexAttribArray(i);
}
glActiveTexture(GL_TEXTURE0);
-
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.sample_fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D, framebuffer.color );
+ glBindTexture(GL_TEXTURE_2D, framebuffer.color);
copy_shader.bind();
_copy_screen_quad();
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.fbo);
-
-
}
void RasterizerGLES2::_copy_screen_quad() {
-
- Vector2 dst_pos[4]={
+ Vector2 dst_pos[4] = {
Vector2(-1, 1),
- Vector2( 1, 1),
- Vector2( 1,-1),
- Vector2(-1,-1)
+ Vector2(1, 1),
+ Vector2(1, -1),
+ Vector2(-1, -1)
};
Size2 uvscale(
(viewport.width / float(framebuffer.scale)) / framebuffer.width,
- (viewport.height / float(framebuffer.scale)) / framebuffer.height
- );
-
- Vector2 src_uv[4]={
- Vector2( 0, 1)*uvscale,
- Vector2( 1, 1)*uvscale,
- Vector2( 1, 0)*uvscale,
- Vector2( 0, 0)*uvscale
- };
+ (viewport.height / float(framebuffer.scale)) / framebuffer.height);
- Vector2 full_uv[4]={
- Vector2( 0, 1),
- Vector2( 1, 1),
- Vector2( 1, 0),
- Vector2( 0, 0)
+ Vector2 src_uv[4] = {
+ Vector2(0, 1) * uvscale,
+ Vector2(1, 1) * uvscale,
+ Vector2(1, 0) * uvscale,
+ Vector2(0, 0) * uvscale
};
- _draw_gui_primitive2(4,dst_pos,NULL,src_uv,full_uv);
+ Vector2 full_uv[4] = {
+ Vector2(0, 1),
+ Vector2(1, 1),
+ Vector2(1, 0),
+ Vector2(0, 0)
+ };
+ _draw_gui_primitive2(4, dst_pos, NULL, src_uv, full_uv);
}
void RasterizerGLES2::_process_glow_bloom() {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.blur[0].fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, framebuffer.color );
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_COPY,true);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.color);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_COPY, true);
if (current_vd && current_env->fx_enabled[VS::ENV_FX_HDR]) {
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,true);
-
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR, true);
}
copy_shader.bind();
- copy_shader.set_uniform(CopyShaderGLES2::BLOOM,float(current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM]));
- copy_shader.set_uniform(CopyShaderGLES2::BLOOM_TRESHOLD,float(current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM_TRESHOLD]));
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ copy_shader.set_uniform(CopyShaderGLES2::BLOOM, float(current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM]));
+ copy_shader.set_uniform(CopyShaderGLES2::BLOOM_TRESHOLD, float(current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM_TRESHOLD]));
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
if (current_vd && current_env->fx_enabled[VS::ENV_FX_HDR]) {
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D, current_vd->lum_color );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::HDR_SOURCE),2);
- copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_EXPOSURE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE]));
- copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_WHITE]));
+ glBindTexture(GL_TEXTURE_2D, current_vd->lum_color);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::HDR_SOURCE), 2);
+ copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_EXPOSURE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE]));
+ copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_WHITE]));
//copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE,1.0);
- copy_shader.set_uniform(CopyShaderGLES2::HDR_GLOW_TRESHOLD,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_GLOW_TRESHOLD]));
- copy_shader.set_uniform(CopyShaderGLES2::HDR_GLOW_SCALE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_GLOW_SCALE]));
+ copy_shader.set_uniform(CopyShaderGLES2::HDR_GLOW_TRESHOLD, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_GLOW_TRESHOLD]));
+ copy_shader.set_uniform(CopyShaderGLES2::HDR_GLOW_SCALE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_GLOW_SCALE]));
glActiveTexture(GL_TEXTURE0);
}
- glViewport( 0, 0, framebuffer.blur_size, framebuffer.blur_size );
+ glViewport(0, 0, framebuffer.blur_size, framebuffer.blur_size);
_copy_screen_quad();
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_COPY,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_COPY, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR, false);
int passes = current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_PASSES];
- Vector2 psize(1.0/framebuffer.blur_size,1.0/framebuffer.blur_size);
+ Vector2 psize(1.0 / framebuffer.blur_size, 1.0 / framebuffer.blur_size);
float pscale = current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_SCALE];
float pmag = current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_STRENGTH];
+ for (int i = 0; i < passes; i++) {
- for(int i=0;i<passes;i++) {
-
- static const Vector2 src_uv[4]={
- Vector2( 0, 1),
- Vector2( 1, 1),
- Vector2( 1, 0),
- Vector2( 0, 0)
+ static const Vector2 src_uv[4] = {
+ Vector2(0, 1),
+ Vector2(1, 1),
+ Vector2(1, 0),
+ Vector2(0, 0)
};
- static const Vector2 dst_pos[4]={
+ static const Vector2 dst_pos[4] = {
Vector2(-1, 1),
- Vector2( 1, 1),
- Vector2( 1,-1),
- Vector2(-1,-1)
+ Vector2(1, 1),
+ Vector2(1, -1),
+ Vector2(-1, -1)
};
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.blur[1].fbo);
- glBindTexture(GL_TEXTURE_2D, framebuffer.blur[0].color );
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS,true);
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS,false);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.blur[0].color);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS, true);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS, false);
copy_shader.bind();
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,psize);
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE,pscale);
- copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE,pmag);
-
- _draw_gui_primitive(4,dst_pos,NULL,src_uv);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, psize);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE, pscale);
+ copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE, pmag);
+ _draw_gui_primitive(4, dst_pos, NULL, src_uv);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.blur[0].fbo);
- glBindTexture(GL_TEXTURE_2D, framebuffer.blur[1].color );
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS,false);
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS,true);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.blur[1].color);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS, true);
copy_shader.bind();
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,psize);
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE,pscale);
- copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE,pmag);
-
- _draw_gui_primitive(4,dst_pos,NULL,src_uv);
-
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, psize);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE, pscale);
+ copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE, pmag);
+ _draw_gui_primitive(4, dst_pos, NULL, src_uv);
}
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS,false);
- copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,false);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_V_PASS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::BLUR_H_PASS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR, false);
//blur it
-
-
}
void RasterizerGLES2::_process_hdr() {
@@ -7034,92 +6559,83 @@ void RasterizerGLES2::_process_hdr() {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.luminance[0].fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, framebuffer.color );
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_COPY,true);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.color);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_COPY, true);
copy_shader.bind();
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
- glViewport( 0, 0, framebuffer.luminance[0].size, framebuffer.luminance[0].size );
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
+ glViewport(0, 0, framebuffer.luminance[0].size, framebuffer.luminance[0].size);
_copy_screen_quad();
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_COPY,false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_COPY, false);
//int passes = current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_PASSES];
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_REDUCE,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_REDUCE, true);
copy_shader.bind();
- for(int i=1;i<framebuffer.luminance.size();i++) {
+ for (int i = 1; i < framebuffer.luminance.size(); i++) {
-
- static const Vector2 src_uv[4]={
- Vector2( 0, 1),
- Vector2( 1, 1),
- Vector2( 1, 0),
- Vector2( 0, 0)
+ static const Vector2 src_uv[4] = {
+ Vector2(0, 1),
+ Vector2(1, 1),
+ Vector2(1, 0),
+ Vector2(0, 0)
};
- static const Vector2 dst_pos[4]={
+ static const Vector2 dst_pos[4] = {
Vector2(-1, 1),
- Vector2( 1, 1),
- Vector2( 1,-1),
- Vector2(-1,-1)
+ Vector2(1, 1),
+ Vector2(1, -1),
+ Vector2(-1, -1)
};
-
- Vector2 psize(1.0/framebuffer.luminance[i-1].size,1.0/framebuffer.luminance[i-1].size);
+ Vector2 psize(1.0 / framebuffer.luminance[i - 1].size, 1.0 / framebuffer.luminance[i - 1].size);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.luminance[i].fbo);
- glBindTexture(GL_TEXTURE_2D, framebuffer.luminance[i-1].color );
- glViewport( 0, 0, framebuffer.luminance[i].size, framebuffer.luminance[i].size );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.luminance[i - 1].color);
+ glViewport(0, 0, framebuffer.luminance[i].size, framebuffer.luminance[i].size);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
- if (framebuffer.luminance[i].size==1) {
+ if (framebuffer.luminance[i].size == 1) {
//last step
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_STORE,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_STORE, true);
copy_shader.bind();
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, current_vd->lum_color );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE_VD_LUM),1);
- copy_shader.set_uniform(CopyShaderGLES2::HDR_TIME_DELTA,time_delta);
- copy_shader.set_uniform(CopyShaderGLES2::HDR_EXP_ADJ_SPEED,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE_ADJUST_SPEED]));
- copy_shader.set_uniform(CopyShaderGLES2::MIN_LUMINANCE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_MIN_LUMINANCE]));
- copy_shader.set_uniform(CopyShaderGLES2::MAX_LUMINANCE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_MAX_LUMINANCE]));
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ glBindTexture(GL_TEXTURE_2D, current_vd->lum_color);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE_VD_LUM), 1);
+ copy_shader.set_uniform(CopyShaderGLES2::HDR_TIME_DELTA, time_delta);
+ copy_shader.set_uniform(CopyShaderGLES2::HDR_EXP_ADJ_SPEED, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE_ADJUST_SPEED]));
+ copy_shader.set_uniform(CopyShaderGLES2::MIN_LUMINANCE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_MIN_LUMINANCE]));
+ copy_shader.set_uniform(CopyShaderGLES2::MAX_LUMINANCE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_MAX_LUMINANCE]));
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
//swap them
- SWAP( current_vd->lum_color, framebuffer.luminance[i].color);
- SWAP( current_vd->lum_fbo, framebuffer.luminance[i].fbo);
-
+ SWAP(current_vd->lum_color, framebuffer.luminance[i].color);
+ SWAP(current_vd->lum_fbo, framebuffer.luminance[i].fbo);
}
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,psize);
-
- _draw_gui_primitive(4,dst_pos,NULL,src_uv);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, psize);
+ _draw_gui_primitive(4, dst_pos, NULL, src_uv);
}
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_REDUCE, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_STORE, false);
-
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_REDUCE,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR_STORE,false);
-
- draw_next_frame=true;
-
+ draw_next_frame = true;
}
-
void RasterizerGLES2::_draw_tex_bg() {
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
- glColorMask(1,1,1,1);
-
+ glColorMask(1, 1, 1, 1);
RID texture;
- if (current_env->bg_mode==VS::ENV_BG_TEXTURE) {
- texture=current_env->bg_param[VS::ENV_BG_PARAM_TEXTURE];
+ if (current_env->bg_mode == VS::ENV_BG_TEXTURE) {
+ texture = current_env->bg_param[VS::ENV_BG_PARAM_TEXTURE];
} else {
- texture=current_env->bg_param[VS::ENV_BG_PARAM_CUBEMAP];
+ texture = current_env->bg_param[VS::ENV_BG_PARAM_CUBEMAP];
}
if (!texture_owner.owns(texture)) {
@@ -7131,51 +6647,48 @@ void RasterizerGLES2::_draw_tex_bg() {
glActiveTexture(GL_TEXTURE0);
glBindTexture(t->target, t->tex_id);
- copy_shader.set_conditional(CopyShaderGLES2::USE_ENERGY,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_ENERGY, true);
- if (current_env->bg_mode==VS::ENV_BG_TEXTURE) {
- copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP,false);
+ if (current_env->bg_mode == VS::ENV_BG_TEXTURE) {
+ copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false);
} else {
- copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP, true);
}
-
- copy_shader.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA,true);
-
+ copy_shader.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, true);
copy_shader.bind();
- if (current_env->bg_mode==VS::ENV_BG_TEXTURE) {
- glUniform1i( copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ if (current_env->bg_mode == VS::ENV_BG_TEXTURE) {
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
} else {
- glUniform1i( copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE_CUBE),0);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE_CUBE), 0);
}
- float nrg =float(current_env->bg_param[VS::ENV_BG_PARAM_ENERGY]);
+ float nrg = float(current_env->bg_param[VS::ENV_BG_PARAM_ENERGY]);
if (current_env->fx_enabled[VS::ENV_FX_HDR] && !use_fp16_fb)
- nrg*=0.25; //go down a quarter for hdr
- copy_shader.set_uniform(CopyShaderGLES2::ENERGY,nrg);
- copy_shader.set_uniform(CopyShaderGLES2::CUSTOM_ALPHA,float(current_env->bg_param[VS::ENV_BG_PARAM_GLOW]));
+ nrg *= 0.25; //go down a quarter for hdr
+ copy_shader.set_uniform(CopyShaderGLES2::ENERGY, nrg);
+ copy_shader.set_uniform(CopyShaderGLES2::CUSTOM_ALPHA, float(current_env->bg_param[VS::ENV_BG_PARAM_GLOW]));
- float flip_sign = (current_env->bg_mode==VS::ENV_BG_TEXTURE && current_rt && current_rt_vflip)?-1:1;
+ float flip_sign = (current_env->bg_mode == VS::ENV_BG_TEXTURE && current_rt && current_rt_vflip) ? -1 : 1;
- Vector3 vertices[4]={
- Vector3(-1,-1*flip_sign,1),
- Vector3( 1,-1*flip_sign,1),
- Vector3( 1, 1*flip_sign,1),
- Vector3(-1, 1*flip_sign,1)
+ Vector3 vertices[4] = {
+ Vector3(-1, -1 * flip_sign, 1),
+ Vector3(1, -1 * flip_sign, 1),
+ Vector3(1, 1 * flip_sign, 1),
+ Vector3(-1, 1 * flip_sign, 1)
};
-
- Vector3 src_uv[4]={
- Vector3( 0, 1, 0),
- Vector3( 1, 1, 0),
- Vector3( 1, 0, 0),
- Vector3( 0, 0, 0)
+ Vector3 src_uv[4] = {
+ Vector3(0, 1, 0),
+ Vector3(1, 1, 0),
+ Vector3(1, 0, 0),
+ Vector3(0, 0, 0)
};
- if (current_env->bg_mode==VS::ENV_BG_TEXTURE) {
+ if (current_env->bg_mode == VS::ENV_BG_TEXTURE) {
//regular texture
//adjust aspect
@@ -7185,117 +6698,113 @@ void RasterizerGLES2::_draw_tex_bg() {
if (aspect_v > aspect_t) {
//wider than texture
- for(int i=0;i<4;i++) {
- src_uv[i].y=(src_uv[i].y-0.5)*(aspect_t/aspect_v)+0.5;
+ for (int i = 0; i < 4; i++) {
+ src_uv[i].y = (src_uv[i].y - 0.5) * (aspect_t / aspect_v) + 0.5;
}
} else {
//narrower than texture
- for(int i=0;i<4;i++) {
- src_uv[i].x=(src_uv[i].x-0.5)*(aspect_v/aspect_t)+0.5;
+ for (int i = 0; i < 4; i++) {
+ src_uv[i].x = (src_uv[i].x - 0.5) * (aspect_v / aspect_t) + 0.5;
}
}
- float scale=current_env->bg_param[VS::ENV_BG_PARAM_SCALE];
- for(int i=0;i<4;i++) {
+ float scale = current_env->bg_param[VS::ENV_BG_PARAM_SCALE];
+ for (int i = 0; i < 4; i++) {
- src_uv[i].x*=scale;
- src_uv[i].y*=scale;
+ src_uv[i].x *= scale;
+ src_uv[i].y *= scale;
}
} else {
//skybox uv vectors
- float vw,vh,zn;
- camera_projection.get_viewport_size(vw,vh);
- zn=camera_projection.get_z_near();
+ float vw, vh, zn;
+ camera_projection.get_viewport_size(vw, vh);
+ zn = camera_projection.get_z_near();
- float scale=current_env->bg_param[VS::ENV_BG_PARAM_SCALE];
+ float scale = current_env->bg_param[VS::ENV_BG_PARAM_SCALE];
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- Vector3 uv=src_uv[i];
- uv.x=(uv.x*2.0-1.0)*vw*scale;
- uv.y=-(uv.y*2.0-1.0)*vh*scale;
- uv.z=-zn;
+ Vector3 uv = src_uv[i];
+ uv.x = (uv.x * 2.0 - 1.0) * vw * scale;
+ uv.y = -(uv.y * 2.0 - 1.0) * vh * scale;
+ uv.z = -zn;
src_uv[i] = camera_transform.basis.xform(uv).normalized();
src_uv[i].z = -src_uv[i].z;
-
}
}
- _draw_primitive(4,vertices,NULL,NULL,src_uv);
+ _draw_primitive(4, vertices, NULL, NULL, src_uv);
- copy_shader.set_conditional(CopyShaderGLES2::USE_ENERGY,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_RGBE,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA,false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_ENERGY, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_RGBE, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_CUBEMAP, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_CUSTOM_ALPHA, false);
}
void RasterizerGLES2::end_scene() {
-
-
glEnable(GL_BLEND);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
- bool use_fb=false;
+ bool use_fb = false;
if (framebuffer.active) {
//detect when to use the framebuffer object
- if (using_canvas_bg || texscreen_used || framebuffer.scale!=1) {
- use_fb=true;
+ if (using_canvas_bg || texscreen_used || framebuffer.scale != 1) {
+ use_fb = true;
} else if (current_env) {
- use_fb=false;
- for(int i=0;i<VS::ENV_FX_MAX;i++) {
+ use_fb = false;
+ for (int i = 0; i < VS::ENV_FX_MAX; i++) {
- if (i==VS::ENV_FX_FOG) //does not need fb
+ if (i == VS::ENV_FX_FOG) //does not need fb
continue;
if (current_env->fx_enabled[i]) {
- use_fb=true;
+ use_fb = true;
break;
}
}
}
}
-
if (use_fb) {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.fbo);
- glViewport( 0,0,viewport.width / framebuffer.scale, viewport.height / framebuffer.scale );
- glScissor( 0,0,viewport.width / framebuffer.scale, viewport.height / framebuffer.scale );
+ glViewport(0, 0, viewport.width / framebuffer.scale, viewport.height / framebuffer.scale);
+ glScissor(0, 0, viewport.width / framebuffer.scale, viewport.height / framebuffer.scale);
- material_shader.set_conditional(MaterialShaderGLES2::USE_8BIT_HDR,!use_fp16_fb && current_env && current_env->fx_enabled[VS::ENV_FX_HDR]);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_8BIT_HDR, !use_fp16_fb && current_env && current_env->fx_enabled[VS::ENV_FX_HDR]);
} else {
if (current_rt) {
- glScissor( 0,0,viewport.width,viewport.height);
+ glScissor(0, 0, viewport.width, viewport.height);
} else {
- glScissor( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
+ glScissor(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height);
}
}
glEnable(GL_SCISSOR_TEST);
_glClearDepth(1.0);
- bool draw_tex_background=false;
+ bool draw_tex_background = false;
- if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) {
+ if (current_debug == VS::SCENARIO_DEBUG_OVERDRAW) {
- glClearColor(0,0,0,1);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ glClearColor(0, 0, 0, 1);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
} else if (current_rt && current_rt_transparent) {
- glClearColor(0,0,0,0);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ glClearColor(0, 0, 0, 0);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
} else if (current_env) {
- switch(current_env->bg_mode) {
+ switch (current_env->bg_mode) {
case VS::ENV_BG_CANVAS:
case VS::ENV_BG_KEEP: {
@@ -7306,36 +6815,33 @@ void RasterizerGLES2::end_scene() {
case VS::ENV_BG_COLOR: {
Color bgcolor;
- if (current_env->bg_mode==VS::ENV_BG_COLOR)
+ if (current_env->bg_mode == VS::ENV_BG_COLOR)
bgcolor = current_env->bg_param[VS::ENV_BG_PARAM_COLOR];
else
bgcolor = GlobalConfig::get_singleton()->get("render/default_clear_color");
bgcolor = _convert_color(bgcolor);
float a = use_fb ? float(current_env->bg_param[VS::ENV_BG_PARAM_GLOW]) : 1.0;
- glClearColor(bgcolor.r,bgcolor.g,bgcolor.b,a);
+ glClearColor(bgcolor.r, bgcolor.g, bgcolor.b, a);
_glClearDepth(1.0);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
} break;
case VS::ENV_BG_TEXTURE:
case VS::ENV_BG_CUBEMAP: {
-
glClear(GL_DEPTH_BUFFER_BIT);
- draw_tex_background=true;
+ draw_tex_background = true;
} break;
-
}
} else {
- Color c = _convert_color(Color(0.3,0.3,0.3));
- glClearColor(c.r,c.g,c.b,0.0);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ Color c = _convert_color(Color(0.3, 0.3, 0.3));
+ glClearColor(c.r, c.g, c.b, 0.0);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
glDisable(GL_SCISSOR_TEST);
-
//material_shader.set_uniform_camera(MaterialShaderGLES2::PROJECTION_MATRIX, camera_projection);
/*
@@ -7349,23 +6855,21 @@ void RasterizerGLES2::end_scene() {
*/
//material_shader.set_uniform_default(MaterialShaderGLES2::CAMERA_INVERSE, camera_transform_inverse);
-
- current_depth_test=true;
- current_depth_mask=true;
- texscreen_copied=false;
+ current_depth_test = true;
+ current_depth_mask = true;
+ texscreen_copied = false;
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
glDisable(GL_BLEND);
- current_blend_mode=VS::MATERIAL_BLEND_MODE_MIX;
+ current_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
//material_shader.set_conditional(MaterialShaderGLES2::USE_GLOW,current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]);
opaque_render_list.sort_mat_light_type_flags();
- _render_list_forward(&opaque_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting);
+ _render_list_forward(&opaque_render_list, camera_transform, camera_transform_inverse, camera_projection, false, fragment_lighting);
if (draw_tex_background) {
@@ -7378,38 +6882,35 @@ void RasterizerGLES2::end_scene() {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
glDisable(GL_BLEND);
- current_blend_mode=VS::MATERIAL_BLEND_MODE_MIX;
- material_shader.set_conditional(MaterialShaderGLES2::USE_GLOW,false);
+ current_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
+ material_shader.set_conditional(MaterialShaderGLES2::USE_GLOW, false);
if (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) {
- glColorMask(1,1,1,0); //don't touch alpha
+ glColorMask(1, 1, 1, 0); //don't touch alpha
}
alpha_render_list.sort_z();
- _render_list_forward(&alpha_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting,true);
- glColorMask(1,1,1,1);
+ _render_list_forward(&alpha_render_list, camera_transform, camera_transform_inverse, camera_projection, false, fragment_lighting, true);
+ glColorMask(1, 1, 1, 1);
//material_shader.set_conditional( MaterialShaderGLES2::USE_FOG,false);
DEBUG_TEST_ERROR("Drawing Scene");
#ifdef GLEW_ENABLED
- glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
if (use_fb) {
-
-
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
glDisableVertexAttribArray(i);
}
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
@@ -7419,57 +6920,55 @@ void RasterizerGLES2::end_scene() {
if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR]) {
int hdr_tm = current_env->fx_param[VS::ENV_FX_PARAM_HDR_TONEMAPPER];
- switch(hdr_tm) {
+ switch (hdr_tm) {
case VS::ENV_FX_HDR_TONE_MAPPER_LINEAR: {
-
} break;
case VS::ENV_FX_HDR_TONE_MAPPER_LOG: {
- copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER, true);
} break;
case VS::ENV_FX_HDR_TONE_MAPPER_REINHARDT: {
- copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER, true);
} break;
case VS::ENV_FX_HDR_TONE_MAPPER_REINHARDT_AUTOWHITE: {
- copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,true);
- copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE,true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER, true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE, true);
} break;
}
-
_process_hdr();
}
if (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) {
_process_glow_bloom();
- int glow_transfer_mode=current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_BLEND_MODE];
- if (glow_transfer_mode==1)
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN,true);
- if (glow_transfer_mode==2)
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT,true);
+ int glow_transfer_mode = current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_BLEND_MODE];
+ if (glow_transfer_mode == 1)
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN, true);
+ if (glow_transfer_mode == 2)
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT, true);
}
- glBindFramebuffer(GL_FRAMEBUFFER, current_rt?current_rt->fbo:base_framebuffer);
+ glBindFramebuffer(GL_FRAMEBUFFER, current_rt ? current_rt->fbo : base_framebuffer);
Size2 size;
if (current_rt) {
glBindFramebuffer(GL_FRAMEBUFFER, current_rt->fbo);
- glViewport( 0,0,viewport.width,viewport.height);
- size=Size2(viewport.width,viewport.height);
+ glViewport(0, 0, viewport.width, viewport.height);
+ size = Size2(viewport.width, viewport.height);
} else {
glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer);
- glViewport( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
- size=Size2(viewport.width,viewport.height);
+ glViewport(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height);
+ size = Size2(viewport.width, viewport.height);
}
//time to copy!!!
- copy_shader.set_conditional(CopyShaderGLES2::USE_BCS,current_env && current_env->fx_enabled[VS::ENV_FX_BCS]);
- copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB,current_env && current_env->fx_enabled[VS::ENV_FX_SRGB]);
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW,current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,current_env && current_env->fx_enabled[VS::ENV_FX_HDR]);
- copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA,true);
- copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA,current_env && current_env->fx_enabled[VS::ENV_FX_FXAA]);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_BCS, current_env && current_env->fx_enabled[VS::ENV_FX_BCS]);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB, current_env && current_env->fx_enabled[VS::ENV_FX_SRGB]);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW, current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR, current_env && current_env->fx_enabled[VS::ENV_FX_HDR]);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA, current_env && current_env->fx_enabled[VS::ENV_FX_FXAA]);
copy_shader.bind();
//copy_shader.set_uniform(CopyShaderGLES2::SOURCE,0);
@@ -7477,78 +6976,71 @@ void RasterizerGLES2::end_scene() {
if (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) {
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D, framebuffer.blur[0].color );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::GLOW_SOURCE),1);
-
+ glBindTexture(GL_TEXTURE_2D, framebuffer.blur[0].color);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::GLOW_SOURCE), 1);
}
if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR]) {
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D, current_vd->lum_color );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::HDR_SOURCE),2);
- copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_EXPOSURE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE]));
- copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_WHITE]));
-
+ glBindTexture(GL_TEXTURE_2D, current_vd->lum_color);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::HDR_SOURCE), 2);
+ copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_EXPOSURE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE]));
+ copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE, float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_WHITE]));
}
if (current_env && current_env->fx_enabled[VS::ENV_FX_FXAA])
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,Size2(1.0/size.x,1.0/size.y));
-
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, Size2(1.0 / size.x, 1.0 / size.y));
if (current_env && current_env->fx_enabled[VS::ENV_FX_BCS]) {
Vector3 bcs;
- bcs.x=current_env->fx_param[VS::ENV_FX_PARAM_BCS_BRIGHTNESS];
- bcs.y=current_env->fx_param[VS::ENV_FX_PARAM_BCS_CONTRAST];
- bcs.z=current_env->fx_param[VS::ENV_FX_PARAM_BCS_SATURATION];
- copy_shader.set_uniform(CopyShaderGLES2::BCS,bcs);
+ bcs.x = current_env->fx_param[VS::ENV_FX_PARAM_BCS_BRIGHTNESS];
+ bcs.y = current_env->fx_param[VS::ENV_FX_PARAM_BCS_CONTRAST];
+ bcs.z = current_env->fx_param[VS::ENV_FX_PARAM_BCS_SATURATION];
+ copy_shader.set_uniform(CopyShaderGLES2::BCS, bcs);
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D, framebuffer.color );
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.color);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
_copy_screen_quad();
- copy_shader.set_conditional(CopyShaderGLES2::USE_BCS,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER,false);
-
- material_shader.set_conditional(MaterialShaderGLES2::USE_8BIT_HDR,false);
-
-
- if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR] && GLOBAL_DEF("rasterizer/debug_hdr",false)) {
+ copy_shader.set_conditional(CopyShaderGLES2::USE_BCS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HDR, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER, false);
+
+ material_shader.set_conditional(MaterialShaderGLES2::USE_8BIT_HDR, false);
+
+ if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR] && GLOBAL_DEF("rasterizer/debug_hdr", false)) {
_debug_luminances();
}
}
- current_env=NULL;
- current_debug=VS::SCENARIO_DEBUG_DISABLED;
- if (GLOBAL_DEF("rasterizer/debug_shadow_maps",false)) {
+ current_env = NULL;
+ current_debug = VS::SCENARIO_DEBUG_DISABLED;
+ if (GLOBAL_DEF("rasterizer/debug_shadow_maps", false)) {
_debug_shadows();
}
//_debug_luminances();
//_debug_samplers();
if (using_canvas_bg) {
- using_canvas_bg=false;
- glColorMask(1,1,1,1); //don't touch alpha
+ using_canvas_bg = false;
+ glColorMask(1, 1, 1, 1); //don't touch alpha
}
-
}
void RasterizerGLES2::end_shadow_map() {
-
-
ERR_FAIL_COND(!shadow);
glDisable(GL_BLEND);
@@ -7557,7 +7049,6 @@ void RasterizerGLES2::end_shadow_map() {
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
-
ShadowBuffer *sb = shadow->near_shadow_buffer;
ERR_FAIL_COND(!sb);
@@ -7571,186 +7062,177 @@ void RasterizerGLES2::end_shadow_map() {
//glPolygonOffset( 8.0f, 16.0f);
CameraMatrix cm;
- float z_near,z_far;
+ float z_near, z_far;
Transform light_transform;
- float dp_direction=0.0;
- bool flip_facing=false;
+ float dp_direction = 0.0;
+ bool flip_facing = false;
Rect2 vp_rect;
- switch(shadow->base->type) {
+ switch (shadow->base->type) {
case VS::LIGHT_DIRECTIONAL: {
- if (shadow->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ if (shadow->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
cm = shadow->custom_projection[shadow_pass];
- light_transform=shadow->custom_transform[shadow_pass];
+ light_transform = shadow->custom_transform[shadow_pass];
- if (shadow_pass==0) {
+ if (shadow_pass == 0) {
- vp_rect=Rect2(0, sb->size/2, sb->size/2, sb->size/2);
- glViewport(0, sb->size/2, sb->size/2, sb->size/2);
- glScissor(0, sb->size/2, sb->size/2, sb->size/2);
- } else if (shadow_pass==1) {
+ vp_rect = Rect2(0, sb->size / 2, sb->size / 2, sb->size / 2);
+ glViewport(0, sb->size / 2, sb->size / 2, sb->size / 2);
+ glScissor(0, sb->size / 2, sb->size / 2, sb->size / 2);
+ } else if (shadow_pass == 1) {
- vp_rect=Rect2(0, 0, sb->size/2, sb->size/2);
- glViewport(0, 0, sb->size/2, sb->size/2);
- glScissor(0, 0, sb->size/2, sb->size/2);
+ vp_rect = Rect2(0, 0, sb->size / 2, sb->size / 2);
+ glViewport(0, 0, sb->size / 2, sb->size / 2);
+ glScissor(0, 0, sb->size / 2, sb->size / 2);
- } else if (shadow_pass==2) {
+ } else if (shadow_pass == 2) {
- vp_rect=Rect2(sb->size/2, sb->size/2, sb->size/2, sb->size/2);
- glViewport(sb->size/2, sb->size/2, sb->size/2, sb->size/2);
- glScissor(sb->size/2, sb->size/2, sb->size/2, sb->size/2);
- } else if (shadow_pass==3) {
-
- vp_rect=Rect2(sb->size/2, 0, sb->size/2, sb->size/2);
- glViewport(sb->size/2, 0, sb->size/2, sb->size/2);
- glScissor(sb->size/2, 0, sb->size/2, sb->size/2);
+ vp_rect = Rect2(sb->size / 2, sb->size / 2, sb->size / 2, sb->size / 2);
+ glViewport(sb->size / 2, sb->size / 2, sb->size / 2, sb->size / 2);
+ glScissor(sb->size / 2, sb->size / 2, sb->size / 2, sb->size / 2);
+ } else if (shadow_pass == 3) {
+ vp_rect = Rect2(sb->size / 2, 0, sb->size / 2, sb->size / 2);
+ glViewport(sb->size / 2, 0, sb->size / 2, sb->size / 2);
+ glScissor(sb->size / 2, 0, sb->size / 2, sb->size / 2);
}
-
-
glEnable(GL_SCISSOR_TEST);
- } else if (shadow->base->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
+ } else if (shadow->base->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
- if (shadow_pass==0) {
+ if (shadow_pass == 0) {
cm = shadow->custom_projection[0];
- light_transform=shadow->custom_transform[0];
- vp_rect=Rect2(0, sb->size/2, sb->size, sb->size/2);
- glViewport(0, sb->size/2, sb->size, sb->size/2);
- glScissor(0, sb->size/2, sb->size, sb->size/2);
+ light_transform = shadow->custom_transform[0];
+ vp_rect = Rect2(0, sb->size / 2, sb->size, sb->size / 2);
+ glViewport(0, sb->size / 2, sb->size, sb->size / 2);
+ glScissor(0, sb->size / 2, sb->size, sb->size / 2);
} else {
cm = shadow->custom_projection[1];
- light_transform=shadow->custom_transform[1];
- vp_rect=Rect2(0, 0, sb->size, sb->size/2);
- glViewport(0, 0, sb->size, sb->size/2);
- glScissor(0, 0, sb->size, sb->size/2);
-
+ light_transform = shadow->custom_transform[1];
+ vp_rect = Rect2(0, 0, sb->size, sb->size / 2);
+ glViewport(0, 0, sb->size, sb->size / 2);
+ glScissor(0, 0, sb->size, sb->size / 2);
}
glEnable(GL_SCISSOR_TEST);
} else {
cm = shadow->custom_projection[0];
- light_transform=shadow->custom_transform[0];
- vp_rect=Rect2(0, 0, sb->size, sb->size);
+ light_transform = shadow->custom_transform[0];
+ vp_rect = Rect2(0, 0, sb->size, sb->size);
glViewport(0, 0, sb->size, sb->size);
}
- z_near=cm.get_z_near();
- z_far=cm.get_z_far();
+ z_near = cm.get_z_near();
+ z_far = cm.get_z_far();
_glClearDepth(1.0f);
- glClearColor(1,1,1,1);
+ glClearColor(1, 1, 1, 1);
if (use_rgba_shadowmaps)
- glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
+ glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
else
glClear(GL_DEPTH_BUFFER_BIT);
-
glDisable(GL_SCISSOR_TEST);
} break;
case VS::LIGHT_OMNI: {
- material_shader.set_conditional(MaterialShaderGLES2::USE_DUAL_PARABOLOID,true);
- dp_direction = shadow_pass?1.0:-1.0;
+ material_shader.set_conditional(MaterialShaderGLES2::USE_DUAL_PARABOLOID, true);
+ dp_direction = shadow_pass ? 1.0 : -1.0;
flip_facing = (shadow_pass == 1);
- light_transform=shadow->transform;
- z_near=0;
- z_far=shadow->base->vars[ VS::LIGHT_PARAM_RADIUS ];
- shadow->dp.x=1.0/z_far;
- shadow->dp.y=dp_direction;
-
- if (shadow_pass==0) {
- vp_rect=Rect2(0, sb->size/2, sb->size, sb->size/2);
- glViewport(0, sb->size/2, sb->size, sb->size/2);
- glScissor(0, sb->size/2, sb->size, sb->size/2);
+ light_transform = shadow->transform;
+ z_near = 0;
+ z_far = shadow->base->vars[VS::LIGHT_PARAM_RADIUS];
+ shadow->dp.x = 1.0 / z_far;
+ shadow->dp.y = dp_direction;
+
+ if (shadow_pass == 0) {
+ vp_rect = Rect2(0, sb->size / 2, sb->size, sb->size / 2);
+ glViewport(0, sb->size / 2, sb->size, sb->size / 2);
+ glScissor(0, sb->size / 2, sb->size, sb->size / 2);
} else {
- vp_rect=Rect2(0, 0, sb->size, sb->size/2);
- glViewport(0, 0, sb->size, sb->size/2);
- glScissor(0, 0, sb->size, sb->size/2);
+ vp_rect = Rect2(0, 0, sb->size, sb->size / 2);
+ glViewport(0, 0, sb->size, sb->size / 2);
+ glScissor(0, 0, sb->size, sb->size / 2);
}
glEnable(GL_SCISSOR_TEST);
- shadow->projection=cm;
-
+ shadow->projection = cm;
- glClearColor(1,1,1,1);
+ glClearColor(1, 1, 1, 1);
_glClearDepth(1.0f);
if (use_rgba_shadowmaps)
- glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
+ glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
else
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
-
} break;
case VS::LIGHT_SPOT: {
- float far = shadow->base->vars[ VS::LIGHT_PARAM_RADIUS ];
- ERR_FAIL_COND( far<=0 );
- float near= far/200.0;
- if (near<0.05)
- near=0.05;
+ float far = shadow->base->vars[VS::LIGHT_PARAM_RADIUS];
+ ERR_FAIL_COND(far <= 0);
+ float near = far / 200.0;
+ if (near < 0.05)
+ near = 0.05;
- float angle = shadow->base->vars[ VS::LIGHT_PARAM_SPOT_ANGLE ];
+ float angle = shadow->base->vars[VS::LIGHT_PARAM_SPOT_ANGLE];
- cm.set_perspective( angle*2.0, 1.0, near, far );
+ cm.set_perspective(angle * 2.0, 1.0, near, far);
- shadow->projection=cm; // cache
- light_transform=shadow->transform;
- z_near=cm.get_z_near();
- z_far=cm.get_z_far();
+ shadow->projection = cm; // cache
+ light_transform = shadow->transform;
+ z_near = cm.get_z_near();
+ z_far = cm.get_z_far();
glViewport(0, 0, sb->size, sb->size);
- vp_rect=Rect2(0, 0, sb->size, sb->size);
+ vp_rect = Rect2(0, 0, sb->size, sb->size);
_glClearDepth(1.0f);
- glClearColor(1,1,1,1);
+ glClearColor(1, 1, 1, 1);
if (use_rgba_shadowmaps)
- glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
+ glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
else
glClear(GL_DEPTH_BUFFER_BIT);
-
} break;
}
Transform light_transform_inverse = light_transform.affine_inverse();
opaque_render_list.sort_mat_geom();
- _render_list_forward(&opaque_render_list,light_transform,light_transform_inverse,cm,flip_facing,false);
-
- material_shader.set_conditional(MaterialShaderGLES2::USE_DUAL_PARABOLOID,false);
+ _render_list_forward(&opaque_render_list, light_transform, light_transform_inverse, cm, flip_facing, false);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_DUAL_PARABOLOID, false);
//if (!use_rgba_shadowmaps)
- if (shadow_filter==SHADOW_FILTER_ESM) {
+ if (shadow_filter == SHADOW_FILTER_ESM) {
- copy_shader.set_conditional(CopyShaderGLES2::USE_RGBA_DEPTH,use_rgba_shadowmaps);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HIGHP_SOURCE,!use_rgba_shadowmaps);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_RGBA_DEPTH, use_rgba_shadowmaps);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HIGHP_SOURCE, !use_rgba_shadowmaps);
- Vector2 psize(1.0/sb->size,1.0/sb->size);
+ Vector2 psize(1.0 / sb->size, 1.0 / sb->size);
float pscale = 1.0;
- int passes=shadow->base->vars[VS::LIGHT_PARAM_SHADOW_BLUR_PASSES];
+ int passes = shadow->base->vars[VS::LIGHT_PARAM_SHADOW_BLUR_PASSES];
glDisable(GL_BLEND);
glDisable(GL_CULL_FACE);
#ifdef GLEW_ENABLED
- glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
glDisableVertexAttribArray(i);
}
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisable(GL_SCISSOR_TEST);
if (!use_rgba_shadowmaps) {
@@ -7761,16 +7243,15 @@ void RasterizerGLES2::end_shadow_map() {
glDisable(GL_DEPTH_TEST);
}
- for(int i=0;i<passes;i++) {
+ for (int i = 0; i < passes; i++) {
-
- Vector2 src_sb_uv[4]={
- (vp_rect.pos+Vector2(0,vp_rect.size.y))/sb->size,
- (vp_rect.pos+vp_rect.size)/sb->size,
- (vp_rect.pos+Vector2(vp_rect.size.x,0))/sb->size,
- (vp_rect.pos)/sb->size
+ Vector2 src_sb_uv[4] = {
+ (vp_rect.pos + Vector2(0, vp_rect.size.y)) / sb->size,
+ (vp_rect.pos + vp_rect.size) / sb->size,
+ (vp_rect.pos + Vector2(vp_rect.size.x, 0)) / sb->size,
+ (vp_rect.pos) / sb->size
};
-/*
+ /*
Vector2 src_uv[4]={
Vector2( 0, 1),
Vector2( 1, 1),
@@ -7778,39 +7259,37 @@ void RasterizerGLES2::end_shadow_map() {
Vector2( 0, 0)
};
*/
- static const Vector2 dst_pos[4]={
+ static const Vector2 dst_pos[4] = {
Vector2(-1, 1),
- Vector2( 1, 1),
- Vector2( 1,-1),
- Vector2(-1,-1)
+ Vector2(1, 1),
+ Vector2(1, -1),
+ Vector2(-1, -1)
};
glBindFramebuffer(GL_FRAMEBUFFER, blur_shadow_buffer.fbo);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, sb->depth);
#ifdef GLEW_ENABLED
- //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
+//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
#endif
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS,true);
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS,false);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS, true);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS, false);
copy_shader.bind();
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,psize);
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE,pscale);
- copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE,1);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, psize);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE, pscale);
+ copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE, 1);
//copy_shader.set_uniform(CopyShaderGLES2::SOURCE,0);
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
+ _draw_gui_primitive(4, dst_pos, NULL, src_sb_uv);
- _draw_gui_primitive(4,dst_pos,NULL,src_sb_uv);
-
-
- Vector2 src_bb_uv[4]={
- (vp_rect.pos+Vector2(0,vp_rect.size.y))/blur_shadow_buffer.size,
- (vp_rect.pos+vp_rect.size)/blur_shadow_buffer.size,
- (vp_rect.pos+Vector2(vp_rect.size.x,0))/blur_shadow_buffer.size,
- (vp_rect.pos)/blur_shadow_buffer.size,
+ Vector2 src_bb_uv[4] = {
+ (vp_rect.pos + Vector2(0, vp_rect.size.y)) / blur_shadow_buffer.size,
+ (vp_rect.pos + vp_rect.size) / blur_shadow_buffer.size,
+ (vp_rect.pos + Vector2(vp_rect.size.x, 0)) / blur_shadow_buffer.size,
+ (vp_rect.pos) / blur_shadow_buffer.size,
};
glBindFramebuffer(GL_FRAMEBUFFER, sb->fbo);
@@ -7818,161 +7297,141 @@ void RasterizerGLES2::end_shadow_map() {
glBindTexture(GL_TEXTURE_2D, blur_shadow_buffer.depth);
#ifdef GLEW_ENABLED
- //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
+//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
#endif
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS,false);
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS,true);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS, true);
copy_shader.bind();
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,psize);
- copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE,pscale);
- copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE,1);
- glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0);
-
- _draw_gui_primitive(4,dst_pos,NULL,src_bb_uv);
-
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE, psize);
+ copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SCALE, pscale);
+ copy_shader.set_uniform(CopyShaderGLES2::BLUR_MAGNITUDE, 1);
+ glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE), 0);
+ _draw_gui_primitive(4, dst_pos, NULL, src_bb_uv);
}
glDepthFunc(GL_LEQUAL);
- copy_shader.set_conditional(CopyShaderGLES2::USE_RGBA_DEPTH,false);
- copy_shader.set_conditional(CopyShaderGLES2::USE_HIGHP_SOURCE,false);
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS,false);
- copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS,false);
-
+ copy_shader.set_conditional(CopyShaderGLES2::USE_RGBA_DEPTH, false);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_HIGHP_SOURCE, false);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_V_PASS, false);
+ copy_shader.set_conditional(CopyShaderGLES2::SHADOW_BLUR_H_PASS, false);
}
DEBUG_TEST_ERROR("Drawing Shadow");
- shadow=NULL;
- glBindFramebuffer(GL_FRAMEBUFFER, current_rt?current_rt->fbo:base_framebuffer);
+ shadow = NULL;
+ glBindFramebuffer(GL_FRAMEBUFFER, current_rt ? current_rt->fbo : base_framebuffer);
glColorMask(1, 1, 1, 1);
//glDisable(GL_POLYGON_OFFSET_FILL);
-
}
-void RasterizerGLES2::_debug_draw_shadow(GLuint tex, const Rect2& p_rect) {
-
-
-
+void RasterizerGLES2::_debug_draw_shadow(GLuint tex, const Rect2 &p_rect) {
Transform2D modelview;
modelview.translate(p_rect.pos.x, p_rect.pos.y);
canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, modelview);
- glBindTexture(GL_TEXTURE_2D,tex);
-
- Vector3 coords[4]= {
- Vector3(p_rect.pos.x, p_rect.pos.y, 0 ),
- Vector3(p_rect.pos.x+p_rect.size.width,
- p_rect.pos.y, 0 ),
- Vector3(p_rect.pos.x+p_rect.size.width,
- p_rect.pos.y+p_rect.size.height, 0 ),
+ glBindTexture(GL_TEXTURE_2D, tex);
+
+ Vector3 coords[4] = {
+ Vector3(p_rect.pos.x, p_rect.pos.y, 0),
+ Vector3(p_rect.pos.x + p_rect.size.width,
+ p_rect.pos.y, 0),
+ Vector3(p_rect.pos.x + p_rect.size.width,
+ p_rect.pos.y + p_rect.size.height, 0),
Vector3(p_rect.pos.x,
- p_rect.pos.y+p_rect.size.height, 0 )
+ p_rect.pos.y + p_rect.size.height, 0)
};
- Vector3 texcoords[4]={
- Vector3( 0.0f,0.0f, 0),
- Vector3( 1.0f,0.0f, 0),
- Vector3( 1.0f, 1.0f, 0),
- Vector3( 0.0f, 1.0f, 0),
+ Vector3 texcoords[4] = {
+ Vector3(0.0f, 0.0f, 0),
+ Vector3(1.0f, 0.0f, 0),
+ Vector3(1.0f, 1.0f, 0),
+ Vector3(0.0f, 1.0f, 0),
};
- _draw_primitive(4,coords,0,0,texcoords);
+ _draw_primitive(4, coords, 0, 0, texcoords);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
-
}
-void RasterizerGLES2::_debug_draw_shadows_type(Vector<ShadowBuffer>& p_shadows,Point2& ofs) {
-
+void RasterizerGLES2::_debug_draw_shadows_type(Vector<ShadowBuffer> &p_shadows, Point2 &ofs) {
- Size2 debug_size(128,128);
+ Size2 debug_size(128, 128);
//Size2 debug_size(512,512);
+ int useblur = shadow_filter == SHADOW_FILTER_ESM ? 1 : 0;
+ for (int i = 0; i < p_shadows.size() + useblur; i++) {
- int useblur=shadow_filter==SHADOW_FILTER_ESM?1:0;
- for (int i=0;i<p_shadows.size()+useblur;i++) {
+ ShadowBuffer *sb = i == p_shadows.size() ? &blur_shadow_buffer : &p_shadows[i];
- ShadowBuffer *sb=i==p_shadows.size()?&blur_shadow_buffer:&p_shadows[i];
-
- if (!sb->owner && i!=p_shadows.size())
+ if (!sb->owner && i != p_shadows.size())
continue;
- _debug_draw_shadow(sb->depth, Rect2( ofs, debug_size ));
- ofs.x+=debug_size.x;
- if ( (ofs.x+debug_size.x) > viewport.width ) {
+ _debug_draw_shadow(sb->depth, Rect2(ofs, debug_size));
+ ofs.x += debug_size.x;
+ if ((ofs.x + debug_size.x) > viewport.width) {
- ofs.x=0;
- ofs.y+=debug_size.y;
+ ofs.x = 0;
+ ofs.y += debug_size.y;
}
}
-
}
-
void RasterizerGLES2::_debug_luminances() {
- canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32,!use_fp16_fb);
+ canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32, !use_fp16_fb);
canvas_begin();
glDisable(GL_BLEND);
canvas_shader.bind();
- Size2 debug_size(128,128);
+ Size2 debug_size(128, 128);
Size2 ofs;
+ for (int i = 0; i <= framebuffer.luminance.size(); i++) {
- for (int i=0;i<=framebuffer.luminance.size();i++) {
-
- if (i==framebuffer.luminance.size()) {
+ if (i == framebuffer.luminance.size()) {
if (!current_vd)
break;
- _debug_draw_shadow(current_vd->lum_color, Rect2( ofs, debug_size ));
+ _debug_draw_shadow(current_vd->lum_color, Rect2(ofs, debug_size));
} else {
- _debug_draw_shadow(framebuffer.luminance[i].color, Rect2( ofs, debug_size ));
+ _debug_draw_shadow(framebuffer.luminance[i].color, Rect2(ofs, debug_size));
}
- ofs.x+=debug_size.x/2;
- if ( (ofs.x+debug_size.x) > viewport.width ) {
+ ofs.x += debug_size.x / 2;
+ if ((ofs.x + debug_size.x) > viewport.width) {
- ofs.x=0;
- ofs.y+=debug_size.y;
+ ofs.x = 0;
+ ofs.y += debug_size.y;
}
}
- canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32,false);
-
+ canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32, false);
}
-
void RasterizerGLES2::_debug_samplers() {
- canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32,false);
+ canvas_shader.set_conditional(CanvasShaderGLES2::DEBUG_ENCODED_32, false);
canvas_begin();
glDisable(GL_BLEND);
- _set_color_attrib(Color(1,1,1,1));
+ _set_color_attrib(Color(1, 1, 1, 1));
canvas_shader.bind();
-
List<RID> samplers;
sampled_light_owner.get_owned_list(&samplers);
- Size2 debug_size(128,128);
+ Size2 debug_size(128, 128);
Size2 ofs;
+ for (List<RID>::Element *E = samplers.front(); E; E = E->next()) {
- for (List<RID>::Element *E=samplers.front();E;E=E->next()) {
-
- SampledLight *sl=sampled_light_owner.get(E->get());
+ SampledLight *sl = sampled_light_owner.get(E->get());
- _debug_draw_shadow(sl->texture, Rect2( ofs, debug_size ));
+ _debug_draw_shadow(sl->texture, Rect2(ofs, debug_size));
- ofs.x+=debug_size.x/2;
- if ( (ofs.x+debug_size.x) > viewport.width ) {
+ ofs.x += debug_size.x / 2;
+ if ((ofs.x + debug_size.x) > viewport.width) {
- ofs.x=0;
- ofs.y+=debug_size.y;
+ ofs.x = 0;
+ ofs.y += debug_size.y;
}
}
-
-
-
}
void RasterizerGLES2::_debug_shadows() {
@@ -7989,15 +7448,12 @@ void RasterizerGLES2::_debug_shadows() {
//glEnable(GL_TEXTURE_2D);
*/
-
- _debug_draw_shadows_type(near_shadow_buffers,ofs);
+ _debug_draw_shadows_type(near_shadow_buffers, ofs);
//_debug_draw_shadows_type(far_shadow_buffers,ofs);
-
}
void RasterizerGLES2::end_frame() {
-
//print_line("VTX: "+itos(_rinfo.vertex_count)+" OBJ: "+itos(_rinfo.object_count)+" MAT: "+itos(_rinfo.mat_change_count)+" SHD: "+itos(_rinfo.shader_change_count)+" CI: "+itos(_rinfo.ci_draw_commands));
//print_line("TOTAL VTX: "+itos(_rinfo.vertex_count));
@@ -8014,21 +7470,19 @@ void RasterizerGLES2::flush_frame() {
void RasterizerGLES2::begin_canvas_bg() {
if (framebuffer.active) {
- using_canvas_bg=true;
+ using_canvas_bg = true;
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.fbo);
- glViewport( 0,0,viewport.width , viewport.height );
+ glViewport(0, 0, viewport.width, viewport.height);
} else {
- using_canvas_bg=false;
+ using_canvas_bg = false;
}
-
}
void RasterizerGLES2::canvas_begin() {
-
if (using_canvas_bg) {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.fbo);
- glColorMask(1,1,1,0); //don't touch alpha
+ glColorMask(1, 1, 1, 0); //don't touch alpha
}
glDisable(GL_CULL_FACE);
@@ -8042,47 +7496,45 @@ void RasterizerGLES2::canvas_begin() {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
//glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glLineWidth(1.0);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
glDisableVertexAttribArray(i);
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D, white_tex );
- canvas_tex=RID();
+ glBindTexture(GL_TEXTURE_2D, white_tex);
+ canvas_tex = RID();
//material_shader.unbind();
canvas_shader.unbind();
canvas_shader.set_custom_shader(0);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,false);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE, false);
canvas_shader.bind();
canvas_shader.set_uniform(CanvasShaderGLES2::TEXTURE, 0);
- canvas_use_modulate=false;
- _set_color_attrib(Color(1,1,1));
- canvas_transform=Transform();
+ canvas_use_modulate = false;
+ _set_color_attrib(Color(1, 1, 1));
+ canvas_transform = Transform();
canvas_transform.translate(-(viewport.width / 2.0f), -(viewport.height / 2.0f), 0.0f);
float csy = 1.0;
if (current_rt && current_rt_vflip)
csy = -1.0;
- canvas_transform.scale( Vector3( 2.0f / viewport.width, csy * -2.0f / viewport.height, 1.0f ) );
- canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX,canvas_transform);
- canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,Transform2D());
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D());
-
- canvas_opacity=1.0;
- canvas_blend_mode=VS::MATERIAL_BLEND_MODE_MIX;
- canvas_texscreen_used=false;
- uses_texpixel_size=false;
+ canvas_transform.scale(Vector3(2.0f / viewport.width, csy * -2.0f / viewport.height, 1.0f));
+ canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX, canvas_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, Transform2D());
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D());
- canvas_last_material=NULL;
+ canvas_opacity = 1.0;
+ canvas_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
+ canvas_texscreen_used = false;
+ uses_texpixel_size = false;
+ canvas_last_material = NULL;
}
void RasterizerGLES2::canvas_disable_blending() {
@@ -8097,56 +7549,50 @@ void RasterizerGLES2::canvas_set_opacity(float p_opacity) {
void RasterizerGLES2::canvas_set_blend_mode(VS::MaterialBlendMode p_mode) {
- if (p_mode==canvas_blend_mode)
+ if (p_mode == canvas_blend_mode)
return;
- switch(p_mode) {
+ switch (p_mode) {
- case VS::MATERIAL_BLEND_MODE_MIX: {
+ case VS::MATERIAL_BLEND_MODE_MIX: {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- } break;
- case VS::MATERIAL_BLEND_MODE_ADD: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
- } break;
- case VS::MATERIAL_BLEND_MODE_SUB: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
- } break;
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ } break;
case VS::MATERIAL_BLEND_MODE_MUL: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_DST_COLOR,GL_ZERO);
+ glBlendFunc(GL_DST_COLOR, GL_ZERO);
} break;
case VS::MATERIAL_BLEND_MODE_PREMULT_ALPHA: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA);
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} break;
-
}
- canvas_blend_mode=p_mode;
-
+ canvas_blend_mode = p_mode;
}
+void RasterizerGLES2::canvas_begin_rect(const Transform2D &p_transform) {
-void RasterizerGLES2::canvas_begin_rect(const Transform2D& p_transform) {
-
-
- canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,p_transform);
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D());
-
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, p_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D());
}
-void RasterizerGLES2::canvas_set_clip(bool p_clip, const Rect2& p_rect) {
+void RasterizerGLES2::canvas_set_clip(bool p_clip, const Rect2 &p_rect) {
if (p_clip) {
@@ -8154,19 +7600,16 @@ void RasterizerGLES2::canvas_set_clip(bool p_clip, const Rect2& p_rect) {
//glScissor(viewport.x+p_rect.pos.x,viewport.y+ (viewport.height-(p_rect.pos.y+p_rect.size.height)),
int x = p_rect.pos.x;
- int y = window_size.height-(p_rect.pos.y+p_rect.size.y);
+ int y = window_size.height - (p_rect.pos.y + p_rect.size.y);
int w = p_rect.size.x;
int h = p_rect.size.y;
- glScissor(x,y,w,h);
-
+ glScissor(x, y, w, h);
} else {
glDisable(GL_SCISSOR_TEST);
}
-
-
}
void RasterizerGLES2::canvas_end_rect() {
@@ -8174,62 +7617,57 @@ void RasterizerGLES2::canvas_end_rect() {
//glPopMatrix();
}
+RasterizerGLES2::Texture *RasterizerGLES2::_bind_canvas_texture(const RID &p_texture) {
-RasterizerGLES2::Texture* RasterizerGLES2::_bind_canvas_texture(const RID& p_texture) {
-
- if (p_texture==canvas_tex && !rebind_texpixel_size) {
+ if (p_texture == canvas_tex && !rebind_texpixel_size) {
if (canvas_tex.is_valid()) {
- Texture*texture=texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
return texture;
}
return NULL;
}
- rebind_texpixel_size=false;
+ rebind_texpixel_size = false;
if (p_texture.is_valid()) {
-
- Texture*texture=texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
if (!texture) {
- canvas_tex=RID();
- glBindTexture(GL_TEXTURE_2D,white_tex);
+ canvas_tex = RID();
+ glBindTexture(GL_TEXTURE_2D, white_tex);
return NULL;
}
if (texture->render_target)
- texture->render_target->last_pass=frame;
+ texture->render_target->last_pass = frame;
- glBindTexture(GL_TEXTURE_2D,texture->tex_id);
- canvas_tex=p_texture;
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
+ canvas_tex = p_texture;
if (uses_texpixel_size) {
- canvas_shader.set_uniform(CanvasShaderGLES2::TEXPIXEL_SIZE,Size2(1.0/texture->width,1.0/texture->height));
+ canvas_shader.set_uniform(CanvasShaderGLES2::TEXPIXEL_SIZE, Size2(1.0 / texture->width, 1.0 / texture->height));
}
return texture;
-
} else {
-
- glBindTexture(GL_TEXTURE_2D,white_tex);
- canvas_tex=p_texture;
+ glBindTexture(GL_TEXTURE_2D, white_tex);
+ canvas_tex = p_texture;
}
-
return NULL;
}
-void RasterizerGLES2::canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) {
+void RasterizerGLES2::canvas_draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) {
_bind_canvas_texture(RID());
- Color c=p_color;
- c.a*=canvas_opacity;
+ Color c = p_color;
+ c.a *= canvas_opacity;
_set_color_attrib(c);
- Vector3 verts[2]={
- Vector3(p_from.x,p_from.y,0),
- Vector3(p_to.x,p_to.y,0)
+ Vector3 verts[2] = {
+ Vector3(p_from.x, p_from.y, 0),
+ Vector3(p_to.x, p_to.y, 0)
};
#ifdef GLEW_ENABLED
@@ -8237,7 +7675,7 @@ void RasterizerGLES2::canvas_draw_line(const Point2& p_from, const Point2& p_to,
glEnable(GL_LINE_SMOOTH);
#endif
glLineWidth(p_width);
- _draw_primitive(2,verts,0,0,0);
+ _draw_primitive(2, verts, 0, 0, 0);
#ifdef GLEW_ENABLED
if (p_antialiased)
@@ -8247,24 +7685,21 @@ void RasterizerGLES2::canvas_draw_line(const Point2& p_from, const Point2& p_to,
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs) {
-
-
-
- static const GLenum prim[5]={GL_POINTS,GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+void RasterizerGLES2::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs) {
+ static const GLenum prim[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN };
//#define GLES_USE_PRIMITIVE_BUFFER
#ifndef GLES_NO_CLIENT_ARRAYS
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(Vector2), p_vertices );
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), p_vertices);
if (p_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(Color), p_colors );
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), p_colors);
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
@@ -8272,74 +7707,71 @@ void RasterizerGLES2::_draw_gui_primitive(int p_points, const Vector2 *p_vertice
if (p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs );
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), p_uvs);
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
- glDrawArrays(prim[p_points],0,p_points);
+ glDrawArrays(prim[p_points], 0, p_points);
#else
- glBindBuffer(GL_ARRAY_BUFFER,gui_quad_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, gui_quad_buffer);
float b[32];
- int ofs=0;
+ int ofs = 0;
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_points;i++) {
- b[ofs++]=p_vertices[i].x;
- b[ofs++]=p_vertices[i].y;
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_points; i++) {
+ b[ofs++] = p_vertices[i].x;
+ b[ofs++] = p_vertices[i].y;
}
if (p_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(float)*4, ((float*)0)+ofs );
- for(int i=0;i<p_points;i++) {
- b[ofs++]=p_colors[i].r;
- b[ofs++]=p_colors[i].g;
- b[ofs++]=p_colors[i].b;
- b[ofs++]=p_colors[i].a;
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(float) * 4, ((float *)0) + ofs);
+ for (int i = 0; i < p_points; i++) {
+ b[ofs++] = p_colors[i].r;
+ b[ofs++] = p_colors[i].g;
+ b[ofs++] = p_colors[i].b;
+ b[ofs++] = p_colors[i].a;
}
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
-
if (p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_points;i++) {
- b[ofs++]=p_uvs[i].x;
- b[ofs++]=p_uvs[i].y;
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_points; i++) {
+ b[ofs++] = p_uvs[i].x;
+ b[ofs++] = p_uvs[i].y;
}
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
- glBufferSubData(GL_ARRAY_BUFFER,0,ofs*4,&b[0]);
- glDrawArrays(prim[p_points],0,p_points);
- glBindBuffer(GL_ARRAY_BUFFER,0);
-
+ glBufferSubData(GL_ARRAY_BUFFER, 0, ofs * 4, &b[0]);
+ glDrawArrays(prim[p_points], 0, p_points);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
#endif
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::_draw_gui_primitive2(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs, const Vector2 *p_uvs2) {
-
+void RasterizerGLES2::_draw_gui_primitive2(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs, const Vector2 *p_uvs2) {
- static const GLenum prim[5]={GL_POINTS,GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+ static const GLenum prim[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN };
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(Vector2), p_vertices );
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), p_vertices);
if (p_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(Color), p_colors );
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), p_colors);
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
@@ -8347,7 +7779,7 @@ void RasterizerGLES2::_draw_gui_primitive2(int p_points, const Vector2 *p_vertic
if (p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs );
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), p_uvs);
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
@@ -8355,220 +7787,212 @@ void RasterizerGLES2::_draw_gui_primitive2(int p_points, const Vector2 *p_vertic
if (p_uvs2) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV2);
- glVertexAttribPointer( VS::ARRAY_TEX_UV2, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs2 );
+ glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false, sizeof(Vector2), p_uvs2);
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV2);
}
- glDrawArrays(prim[p_points],0,p_points);
+ glDrawArrays(prim[p_points], 0, p_points);
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::_draw_textured_quad(const Rect2& p_rect, const Rect2& p_src_region, const Size2& p_tex_size,bool p_h_flip, bool p_v_flip, bool p_transpose ) {
+void RasterizerGLES2::_draw_textured_quad(const Rect2 &p_rect, const Rect2 &p_src_region, const Size2 &p_tex_size, bool p_h_flip, bool p_v_flip, bool p_transpose) {
- Vector2 texcoords[4]= {
- Vector2( p_src_region.pos.x/p_tex_size.width,
- p_src_region.pos.y/p_tex_size.height),
+ Vector2 texcoords[4] = {
+ Vector2(p_src_region.pos.x / p_tex_size.width,
+ p_src_region.pos.y / p_tex_size.height),
- Vector2((p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
- p_src_region.pos.y/p_tex_size.height),
+ Vector2((p_src_region.pos.x + p_src_region.size.width) / p_tex_size.width,
+ p_src_region.pos.y / p_tex_size.height),
- Vector2( (p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
- (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height),
+ Vector2((p_src_region.pos.x + p_src_region.size.width) / p_tex_size.width,
+ (p_src_region.pos.y + p_src_region.size.height) / p_tex_size.height),
- Vector2( p_src_region.pos.x/p_tex_size.width,
- (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height)
+ Vector2(p_src_region.pos.x / p_tex_size.width,
+ (p_src_region.pos.y + p_src_region.size.height) / p_tex_size.height)
};
if (p_transpose) {
- SWAP( texcoords[1], texcoords[3] );
+ SWAP(texcoords[1], texcoords[3]);
}
if (p_h_flip) {
- SWAP( texcoords[0], texcoords[1] );
- SWAP( texcoords[2], texcoords[3] );
+ SWAP(texcoords[0], texcoords[1]);
+ SWAP(texcoords[2], texcoords[3]);
}
if (p_v_flip) {
- SWAP( texcoords[1], texcoords[2] );
- SWAP( texcoords[0], texcoords[3] );
+ SWAP(texcoords[1], texcoords[2]);
+ SWAP(texcoords[0], texcoords[3]);
}
- Vector2 coords[4]= {
- Vector2( p_rect.pos.x, p_rect.pos.y ),
- Vector2( p_rect.pos.x+p_rect.size.width, p_rect.pos.y ),
- Vector2( p_rect.pos.x+p_rect.size.width, p_rect.pos.y+p_rect.size.height ),
- Vector2( p_rect.pos.x,p_rect.pos.y+p_rect.size.height )
+ Vector2 coords[4] = {
+ Vector2(p_rect.pos.x, p_rect.pos.y),
+ Vector2(p_rect.pos.x + p_rect.size.width, p_rect.pos.y),
+ Vector2(p_rect.pos.x + p_rect.size.width, p_rect.pos.y + p_rect.size.height),
+ Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.height)
};
- _draw_gui_primitive(4,coords,0,texcoords);
+ _draw_gui_primitive(4, coords, 0, texcoords);
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::_draw_quad(const Rect2& p_rect) {
+void RasterizerGLES2::_draw_quad(const Rect2 &p_rect) {
- Vector2 coords[4]= {
- Vector2( p_rect.pos.x,p_rect.pos.y ),
- Vector2( p_rect.pos.x+p_rect.size.width,p_rect.pos.y ),
- Vector2( p_rect.pos.x+p_rect.size.width,p_rect.pos.y+p_rect.size.height ),
- Vector2( p_rect.pos.x,p_rect.pos.y+p_rect.size.height )
+ Vector2 coords[4] = {
+ Vector2(p_rect.pos.x, p_rect.pos.y),
+ Vector2(p_rect.pos.x + p_rect.size.width, p_rect.pos.y),
+ Vector2(p_rect.pos.x + p_rect.size.width, p_rect.pos.y + p_rect.size.height),
+ Vector2(p_rect.pos.x, p_rect.pos.y + p_rect.size.height)
};
- _draw_gui_primitive(4,coords,0,0);
+ _draw_gui_primitive(4, coords, 0, 0);
_rinfo.ci_draw_commands++;
-
}
-void RasterizerGLES2::canvas_draw_rect(const Rect2& p_rect, int p_flags, const Rect2& p_source,RID p_texture,const Color& p_modulate) {
+void RasterizerGLES2::canvas_draw_rect(const Rect2 &p_rect, int p_flags, const Rect2 &p_source, RID p_texture, const Color &p_modulate) {
Color m = p_modulate;
- m.a*=canvas_opacity;
+ m.a *= canvas_opacity;
_set_color_attrib(m);
Texture *texture = _bind_canvas_texture(p_texture);
+ if (texture) {
- if ( texture ) {
-
- bool untile=false;
+ bool untile = false;
- if (p_flags&CANVAS_RECT_TILE && !(texture->flags&VS::TEXTURE_FLAG_REPEAT)) {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
- untile=true;
+ if (p_flags & CANVAS_RECT_TILE && !(texture->flags & VS::TEXTURE_FLAG_REPEAT)) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ untile = true;
}
- if (!(p_flags&CANVAS_RECT_REGION)) {
+ if (!(p_flags & CANVAS_RECT_REGION)) {
- Rect2 region = Rect2(0,0,texture->width,texture->height);
- _draw_textured_quad(p_rect,region,region.size,p_flags&CANVAS_RECT_FLIP_H,p_flags&CANVAS_RECT_FLIP_V,p_flags&CANVAS_RECT_TRANSPOSE);
+ Rect2 region = Rect2(0, 0, texture->width, texture->height);
+ _draw_textured_quad(p_rect, region, region.size, p_flags & CANVAS_RECT_FLIP_H, p_flags & CANVAS_RECT_FLIP_V, p_flags & CANVAS_RECT_TRANSPOSE);
} else {
- _draw_textured_quad(p_rect, p_source, Size2(texture->width,texture->height),p_flags&CANVAS_RECT_FLIP_H,p_flags&CANVAS_RECT_FLIP_V,p_flags&CANVAS_RECT_TRANSPOSE);
-
+ _draw_textured_quad(p_rect, p_source, Size2(texture->width, texture->height), p_flags & CANVAS_RECT_FLIP_H, p_flags & CANVAS_RECT_FLIP_V, p_flags & CANVAS_RECT_TRANSPOSE);
}
if (untile) {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
} else {
//glDisable(GL_TEXTURE_2D);
- _draw_quad( p_rect );
+ _draw_quad(p_rect);
//print_line("rect: "+p_rect);
-
}
_rinfo.ci_draw_commands++;
-
}
-void RasterizerGLES2::canvas_draw_style_box(const Rect2& p_rect, const Rect2& p_src_region, RID p_texture,const float *p_margin, bool p_draw_center,const Color& p_modulate) {
+void RasterizerGLES2::canvas_draw_style_box(const Rect2 &p_rect, const Rect2 &p_src_region, RID p_texture, const float *p_margin, bool p_draw_center, const Color &p_modulate) {
Color m = p_modulate;
- m.a*=canvas_opacity;
+ m.a *= canvas_opacity;
_set_color_attrib(m);
- Texture* texture=_bind_canvas_texture(p_texture);
+ Texture *texture = _bind_canvas_texture(p_texture);
ERR_FAIL_COND(!texture);
Rect2 region = p_src_region;
- if (region.size.width <= 0 )
- region.size.width = texture->width;
+ if (region.size.width <= 0)
+ region.size.width = texture->width;
if (region.size.height <= 0)
- region.size.height = texture->height;
+ region.size.height = texture->height;
/* CORNERS */
_draw_textured_quad( // top left
- Rect2( p_rect.pos, Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
- Rect2( region.pos, Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
+ Rect2(p_rect.pos, Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP])),
+ Rect2(region.pos, Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // top right
- Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
- Rect2( Point2(region.pos.x+region.size.width-p_margin[MARGIN_RIGHT], region.pos.y), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
-
+ Rect2(Point2(p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_TOP])),
+ Rect2(Point2(region.pos.x + region.size.width - p_margin[MARGIN_RIGHT], region.pos.y), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom left
- Rect2( Point2(p_rect.pos.x,p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(region.pos.x, region.pos.y+region.size.height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(p_rect.pos.x, p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(region.pos.x, region.pos.y + region.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom right
- Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(region.pos.x+region.size.width-p_margin[MARGIN_RIGHT], region.pos.y+region.size.height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
-
- Rect2 rect_center( p_rect.pos+Point2( p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2( p_rect.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], p_rect.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+ Rect2(Point2(p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(region.pos.x + region.size.width - p_margin[MARGIN_RIGHT], region.pos.y + region.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
- Rect2 src_center( Point2(region.pos.x+p_margin[MARGIN_LEFT], region.pos.y+p_margin[MARGIN_TOP]), Size2(region.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], region.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+ Rect2 rect_center(p_rect.pos + Point2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2(p_rect.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], p_rect.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM]));
+ Rect2 src_center(Point2(region.pos.x + p_margin[MARGIN_LEFT], region.pos.y + p_margin[MARGIN_TOP]), Size2(region.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], region.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM]));
_draw_textured_quad( // top
- Rect2( Point2(rect_center.pos.x,p_rect.pos.y),Size2(rect_center.size.width,p_margin[MARGIN_TOP])),
- Rect2( Point2(src_center.pos.x,region.pos.y), Size2(src_center.size.width,p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x, p_rect.pos.y), Size2(rect_center.size.width, p_margin[MARGIN_TOP])),
+ Rect2(Point2(src_center.pos.x, region.pos.y), Size2(src_center.size.width, p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom
- Rect2( Point2(rect_center.pos.x,rect_center.pos.y+rect_center.size.height),Size2(rect_center.size.width,p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(src_center.pos.x,src_center.pos.y+src_center.size.height), Size2(src_center.size.width,p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x, rect_center.pos.y + rect_center.size.height), Size2(rect_center.size.width, p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(src_center.pos.x, src_center.pos.y + src_center.size.height), Size2(src_center.size.width, p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // left
- Rect2( Point2(p_rect.pos.x,rect_center.pos.y),Size2(p_margin[MARGIN_LEFT],rect_center.size.height)),
- Rect2( Point2(region.pos.x,region.pos.y+p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_LEFT],src_center.size.height)),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(p_rect.pos.x, rect_center.pos.y), Size2(p_margin[MARGIN_LEFT], rect_center.size.height)),
+ Rect2(Point2(region.pos.x, region.pos.y + p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_LEFT], src_center.size.height)),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // right
- Rect2( Point2(rect_center.pos.x+rect_center.size.width,rect_center.pos.y),Size2(p_margin[MARGIN_RIGHT],rect_center.size.height)),
- Rect2( Point2(src_center.pos.x+src_center.size.width,region.pos.y+p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_RIGHT],src_center.size.height)),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x + rect_center.size.width, rect_center.pos.y), Size2(p_margin[MARGIN_RIGHT], rect_center.size.height)),
+ Rect2(Point2(src_center.pos.x + src_center.size.width, region.pos.y + p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_RIGHT], src_center.size.height)),
+ Size2(texture->width, texture->height));
if (p_draw_center) {
_draw_textured_quad(
- rect_center,
- src_center,
- Size2( texture->width, texture->height ));
+ rect_center,
+ src_center,
+ Size2(texture->width, texture->height));
}
-
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width) {
+void RasterizerGLES2::canvas_draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width) {
- ERR_FAIL_COND(p_points.size()<1);
- _set_color_attrib(Color(1,1,1,canvas_opacity));
+ ERR_FAIL_COND(p_points.size() < 1);
+ _set_color_attrib(Color(1, 1, 1, canvas_opacity));
_bind_canvas_texture(p_texture);
- _draw_gui_primitive(p_points.size(),p_points.ptr(),p_colors.ptr(),p_uvs.ptr());
+ _draw_gui_primitive(p_points.size(), p_points.ptr(), p_colors.ptr(), p_uvs.ptr());
_rinfo.ci_draw_commands++;
}
-void RasterizerGLES2::canvas_draw_polygon(int p_vertex_count, const int* p_indices, const Vector2* p_vertices, const Vector2* p_uvs, const Color* p_colors,const RID& p_texture,bool p_singlecolor) {
+void RasterizerGLES2::canvas_draw_polygon(int p_vertex_count, const int *p_indices, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, const RID &p_texture, bool p_singlecolor) {
- bool do_colors=false;
- Color m;
- if (p_singlecolor) {
- m = *p_colors;
- m.a*=canvas_opacity;
- _set_color_attrib(m);
- } else if (!p_colors) {
- m = Color(1, 1, 1, canvas_opacity);
- _set_color_attrib(m);
- } else
- do_colors=true;
+ bool do_colors = false;
+ Color m;
+ if (p_singlecolor) {
+ m = *p_colors;
+ m.a *= canvas_opacity;
+ _set_color_attrib(m);
+ } else if (!p_colors) {
+ m = Color(1, 1, 1, canvas_opacity);
+ _set_color_attrib(m);
+ } else
+ do_colors = true;
- Texture *texture = _bind_canvas_texture(p_texture);
+ Texture *texture = _bind_canvas_texture(p_texture);
#ifndef GLES_NO_CLIENT_ARRAYS
- glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(Vector2), p_vertices );
+ glEnableVertexAttribArray(VS::ARRAY_VERTEX);
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), p_vertices);
if (do_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(Color), p_colors );
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), p_colors);
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
@@ -8576,229 +8000,213 @@ void RasterizerGLES2::canvas_draw_polygon(int p_vertex_count, const int* p_indic
if (texture && p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs );
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), p_uvs);
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
if (p_indices) {
#ifdef GLEW_ENABLED
- glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_INT, p_indices );
+ glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_INT, p_indices);
#else
- static const int _max_draw_poly_indices = 16*1024; // change this size if needed!!!
+ static const int _max_draw_poly_indices = 16 * 1024; // change this size if needed!!!
ERR_FAIL_COND(p_vertex_count > _max_draw_poly_indices);
static uint16_t _draw_poly_indices[_max_draw_poly_indices];
- for (int i=0; i<p_vertex_count; i++) {
+ for (int i = 0; i < p_vertex_count; i++) {
_draw_poly_indices[i] = p_indices[i];
};
- glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_SHORT, _draw_poly_indices );
+ glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_SHORT, _draw_poly_indices);
#endif
} else {
- glDrawArrays(GL_TRIANGLES,0,p_vertex_count);
+ glDrawArrays(GL_TRIANGLES, 0, p_vertex_count);
}
-
#else //WebGL specific impl.
glBindBuffer(GL_ARRAY_BUFFER, gui_quad_buffer);
- float *b = GlobalVertexBuffer;
- int ofs = 0;
- if(p_vertex_count > MAX_POLYGON_VERTICES){
- print_line("Too many vertices to render");
- return;
- }
- glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_vertices[i].x;
- b[ofs++]=p_vertices[i].y;
- }
-
- if (p_colors && do_colors) {
-
- glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(float)*4, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_colors[i].r;
- b[ofs++]=p_colors[i].g;
- b[ofs++]=p_colors[i].b;
- b[ofs++]=p_colors[i].a;
- }
-
- } else {
- glDisableVertexAttribArray(VS::ARRAY_COLOR);
- }
-
-
- if (p_uvs) {
-
- glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_uvs[i].x;
- b[ofs++]=p_uvs[i].y;
- }
-
- } else {
- glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
- }
-
- glBufferSubData(GL_ARRAY_BUFFER,0,ofs*4,&b[0]);
-
- //bind the indices buffer.
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
-
- static const int _max_draw_poly_indices = 16*1024; // change this size if needed!!!
- ERR_FAIL_COND(p_vertex_count > _max_draw_poly_indices);
- static uint16_t _draw_poly_indices[_max_draw_poly_indices];
- for (int i=0; i<p_vertex_count; i++) {
- _draw_poly_indices[i] = p_indices[i];
- //OS::get_singleton()->print("ind: %d ", p_indices[i]);
- };
+ float *b = GlobalVertexBuffer;
+ int ofs = 0;
+ if (p_vertex_count > MAX_POLYGON_VERTICES) {
+ print_line("Too many vertices to render");
+ return;
+ }
+ glEnableVertexAttribArray(VS::ARRAY_VERTEX);
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_vertices[i].x;
+ b[ofs++] = p_vertices[i].y;
+ }
+
+ if (p_colors && do_colors) {
+
+ glEnableVertexAttribArray(VS::ARRAY_COLOR);
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(float) * 4, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_colors[i].r;
+ b[ofs++] = p_colors[i].g;
+ b[ofs++] = p_colors[i].b;
+ b[ofs++] = p_colors[i].a;
+ }
+
+ } else {
+ glDisableVertexAttribArray(VS::ARRAY_COLOR);
+ }
+
+ if (p_uvs) {
+
+ glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_uvs[i].x;
+ b[ofs++] = p_uvs[i].y;
+ }
+
+ } else {
+ glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
+ }
- //copy the data to GPU.
- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, p_vertex_count * sizeof(uint16_t), &_draw_poly_indices[0]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, ofs * 4, &b[0]);
- //draw the triangles.
- glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_SHORT, 0);
+ //bind the indices buffer.
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
- glBindBuffer(GL_ARRAY_BUFFER, 0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ static const int _max_draw_poly_indices = 16 * 1024; // change this size if needed!!!
+ ERR_FAIL_COND(p_vertex_count > _max_draw_poly_indices);
+ static uint16_t _draw_poly_indices[_max_draw_poly_indices];
+ for (int i = 0; i < p_vertex_count; i++) {
+ _draw_poly_indices[i] = p_indices[i];
+ //OS::get_singleton()->print("ind: %d ", p_indices[i]);
+ };
+
+ //copy the data to GPU.
+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, p_vertex_count * sizeof(uint16_t), &_draw_poly_indices[0]);
+
+ //draw the triangles.
+ glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_SHORT, 0);
+
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
#endif
_rinfo.ci_draw_commands++;
-
};
+void RasterizerGLES2::canvas_set_transform(const Transform2D &p_transform) {
-void RasterizerGLES2::canvas_set_transform(const Transform2D& p_transform) {
-
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,p_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, p_transform);
//canvas_transform = Variant(p_transform);
}
RID RasterizerGLES2::canvas_light_occluder_create() {
- CanvasOccluder *co = memnew( CanvasOccluder );
- co->index_id=0;
- co->vertex_id=0;
- co->len=0;
+ CanvasOccluder *co = memnew(CanvasOccluder);
+ co->index_id = 0;
+ co->vertex_id = 0;
+ co->len = 0;
return canvas_occluder_owner.make_rid(co);
}
-void RasterizerGLES2::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines) {
+void RasterizerGLES2::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines) {
CanvasOccluder *co = canvas_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!co);
- co->lines=p_lines;
+ co->lines = p_lines;
- if (p_lines.size()!=co->len) {
+ if (p_lines.size() != co->len) {
if (co->index_id)
- glDeleteBuffers(1,&co->index_id);
+ glDeleteBuffers(1, &co->index_id);
if (co->vertex_id)
- glDeleteBuffers(1,&co->vertex_id);
-
- co->index_id=0;
- co->vertex_id=0;
- co->len=0;
+ glDeleteBuffers(1, &co->vertex_id);
+ co->index_id = 0;
+ co->vertex_id = 0;
+ co->len = 0;
}
if (p_lines.size()) {
-
-
PoolVector<float> geometry;
PoolVector<uint16_t> indices;
int lc = p_lines.size();
- geometry.resize(lc*6);
- indices.resize(lc*3);
-
- PoolVector<float>::Write vw=geometry.write();
- PoolVector<uint16_t>::Write iw=indices.write();
+ geometry.resize(lc * 6);
+ indices.resize(lc * 3);
+ PoolVector<float>::Write vw = geometry.write();
+ PoolVector<uint16_t>::Write iw = indices.write();
- PoolVector<Vector2>::Read lr=p_lines.read();
+ PoolVector<Vector2>::Read lr = p_lines.read();
const int POLY_HEIGHT = 16384;
- for(int i=0;i<lc/2;i++) {
+ for (int i = 0; i < lc / 2; i++) {
- vw[i*12+0]=lr[i*2+0].x;
- vw[i*12+1]=lr[i*2+0].y;
- vw[i*12+2]=POLY_HEIGHT;
+ vw[i * 12 + 0] = lr[i * 2 + 0].x;
+ vw[i * 12 + 1] = lr[i * 2 + 0].y;
+ vw[i * 12 + 2] = POLY_HEIGHT;
- vw[i*12+3]=lr[i*2+1].x;
- vw[i*12+4]=lr[i*2+1].y;
- vw[i*12+5]=POLY_HEIGHT;
+ vw[i * 12 + 3] = lr[i * 2 + 1].x;
+ vw[i * 12 + 4] = lr[i * 2 + 1].y;
+ vw[i * 12 + 5] = POLY_HEIGHT;
- vw[i*12+6]=lr[i*2+1].x;
- vw[i*12+7]=lr[i*2+1].y;
- vw[i*12+8]=-POLY_HEIGHT;
+ vw[i * 12 + 6] = lr[i * 2 + 1].x;
+ vw[i * 12 + 7] = lr[i * 2 + 1].y;
+ vw[i * 12 + 8] = -POLY_HEIGHT;
- vw[i*12+9]=lr[i*2+0].x;
- vw[i*12+10]=lr[i*2+0].y;
- vw[i*12+11]=-POLY_HEIGHT;
+ vw[i * 12 + 9] = lr[i * 2 + 0].x;
+ vw[i * 12 + 10] = lr[i * 2 + 0].y;
+ vw[i * 12 + 11] = -POLY_HEIGHT;
- iw[i*6+0]=i*4+0;
- iw[i*6+1]=i*4+1;
- iw[i*6+2]=i*4+2;
-
- iw[i*6+3]=i*4+2;
- iw[i*6+4]=i*4+3;
- iw[i*6+5]=i*4+0;
+ iw[i * 6 + 0] = i * 4 + 0;
+ iw[i * 6 + 1] = i * 4 + 1;
+ iw[i * 6 + 2] = i * 4 + 2;
+ iw[i * 6 + 3] = i * 4 + 2;
+ iw[i * 6 + 4] = i * 4 + 3;
+ iw[i * 6 + 5] = i * 4 + 0;
}
//if same buffer len is being set, just use BufferSubData to avoid a pipeline flush
-
if (!co->vertex_id) {
- glGenBuffers(1,&co->vertex_id);
- glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id);
- glBufferData(GL_ARRAY_BUFFER,lc*6*sizeof(real_t),vw.ptr(),GL_STATIC_DRAW);
+ glGenBuffers(1, &co->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(real_t), vw.ptr(), GL_STATIC_DRAW);
} else {
- glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id);
- glBufferSubData(GL_ARRAY_BUFFER,0,lc*6*sizeof(real_t),vw.ptr());
-
+ glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, lc * 6 * sizeof(real_t), vw.ptr());
}
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
if (!co->index_id) {
- glGenBuffers(1,&co->index_id);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,lc*3*sizeof(uint16_t),iw.ptr(),GL_STATIC_DRAW);
+ glGenBuffers(1, &co->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, lc * 3 * sizeof(uint16_t), iw.ptr(), GL_STATIC_DRAW);
} else {
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id);
- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,lc*3*sizeof(uint16_t),iw.ptr());
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, lc * 3 * sizeof(uint16_t), iw.ptr());
}
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
-
- co->len=lc;
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
+ co->len = lc;
}
-
-
-
}
RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
- CanvasLightShadow *cls = memnew( CanvasLightShadow );
- if (p_width>max_texture_size)
- p_width=max_texture_size;
+ CanvasLightShadow *cls = memnew(CanvasLightShadow);
+ if (p_width > max_texture_size)
+ p_width = max_texture_size;
- cls->size=p_width;
+ cls->size = p_width;
glActiveTexture(GL_TEXTURE0);
glGenFramebuffers(1, &cls->fbo);
@@ -8818,14 +8226,14 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- cls->height=16;
+ cls->height = 16;
//print_line("ERROR? "+itos(glGetError()));
- if ( read_depth_supported ) {
+ if (read_depth_supported) {
// We'll use a depth texture to store the depths in the shadow map
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, cls->size, cls->height, 0,
- GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
#ifdef GLEW_ENABLED
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
@@ -8834,7 +8242,7 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
// Attach the depth texture to FBO depth attachment point
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, cls->depth, 0);
+ GL_TEXTURE_2D, cls->depth, 0);
#ifdef GLEW_ENABLED
glDrawBuffer(GL_NONE);
@@ -8848,7 +8256,7 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
// Attach the RGBA texture to FBO color attachment point
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, cls->depth, 0);
- cls->rgba=cls->depth;
+ cls->rgba = cls->depth;
// Allocate 16-bit depth buffer
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, cls->size, cls->height);
@@ -8856,12 +8264,10 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
// Attach the render buffer as depth buffer - will be ignored
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, cls->rbo);
-
-
}
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- //printf("errnum: %x\n",status);
+//printf("errnum: %x\n",status);
#ifdef GLEW_ENABLED
if (read_depth_supported) {
//glDrawBuffer(GL_BACK);
@@ -8869,7 +8275,7 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
#endif
glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer);
DEBUG_TEST_ERROR("2D Shadow Buffer Init");
- ERR_FAIL_COND_V( status != GL_FRAMEBUFFER_COMPLETE, RID() );
+ ERR_FAIL_COND_V(status != GL_FRAMEBUFFER_COMPLETE, RID());
#ifdef GLEW_ENABLED
if (read_depth_supported) {
@@ -8880,12 +8286,11 @@ RID RasterizerGLES2::canvas_light_shadow_buffer_create(int p_width) {
return canvas_light_shadow_owner.make_rid(cls);
}
-void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, CanvasLightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache) {
+void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, CanvasLightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) {
CanvasLightShadow *cls = canvas_light_shadow_owner.get(p_buffer);
ERR_FAIL_COND(!cls);
-
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_DITHER);
@@ -8902,71 +8307,70 @@ void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Tran
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
canvas_shadow_shader.bind();
- glViewport(0, 0, cls->size,cls->height);
+ glViewport(0, 0, cls->size, cls->height);
_glClearDepth(1.0f);
- glClearColor(1,1,1,1);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
-
- VS::CanvasOccluderPolygonCullMode cull=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
+ glClearColor(1, 1, 1, 1);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+ VS::CanvasOccluderPolygonCullMode cull = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
//make sure it remains orthogonal, makes easy to read angle later
Transform light;
- light.origin[0]=p_light_xform[2][0];
- light.origin[1]=p_light_xform[2][1];
- light.basis[0][0]=p_light_xform[0][0];
- light.basis[0][1]=p_light_xform[1][0];
- light.basis[1][0]=p_light_xform[0][1];
- light.basis[1][1]=p_light_xform[1][1];
+ light.origin[0] = p_light_xform[2][0];
+ light.origin[1] = p_light_xform[2][1];
+ light.basis[0][0] = p_light_xform[0][0];
+ light.basis[0][1] = p_light_xform[1][0];
+ light.basis[1][0] = p_light_xform[0][1];
+ light.basis[1][1] = p_light_xform[1][1];
//light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1));
- / //p_near=1;
- CameraMatrix projection;
+ / //p_near=1;
+ CameraMatrix projection;
{
- real_t fov = 90;
+ real_t fov = 90;
real_t near = p_near;
real_t far = p_far;
real_t aspect = 1.0;
- real_t ymax = near * Math::tan( Math::deg2rad( fov * 0.5 ) );
- real_t ymin = - ymax;
+ real_t ymax = near * Math::tan(Math::deg2rad(fov * 0.5));
+ real_t ymin = -ymax;
real_t xmin = ymin * aspect;
real_t xmax = ymax * aspect;
- projection.set_frustum( xmin, xmax, ymin, ymax, near, far );
+ projection.set_frustum(xmin, xmax, ymin, ymax, near, far);
}
- Vector3 cam_target=Matrix3(Vector3(0,0,Math_PI*2*(i/4.0))).xform(Vector3(0,1,0));
- projection = projection * CameraMatrix(Transform().looking_at(cam_target,Vector3(0,0,-1)).affine_inverse());
+ Vector3 cam_target = Matrix3(Vector3(0, 0, Math_PI * 2 * (i / 4.0))).xform(Vector3(0, 1, 0));
+ projection = projection * CameraMatrix(Transform().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
- canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::PROJECTION_MATRIX,projection);
- canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::LIGHT_MATRIX,light);
+ canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::PROJECTION_MATRIX, projection);
+ canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::LIGHT_MATRIX, light);
- if (i==0)
- *p_xform_cache=projection;
+ if (i == 0)
+ *p_xform_cache = projection;
- glViewport(0, (cls->height/4)*i, cls->size,cls->height/4);
+ glViewport(0, (cls->height / 4) * i, cls->size, cls->height / 4);
- CanvasLightOccluderInstance *instance=p_occluders;
+ CanvasLightOccluderInstance *instance = p_occluders;
- while(instance) {
+ while (instance) {
CanvasOccluder *cc = canvas_occluder_owner.get(instance->polygon_buffer);
- if (!cc || cc->len==0 || !(p_light_mask&instance->light_mask)) {
+ if (!cc || cc->len == 0 || !(p_light_mask & instance->light_mask)) {
- instance=instance->next;
+ instance = instance->next;
continue;
}
- canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::WORLD_MATRIX,instance->xform_cache);
- if (cull!=instance->cull_cache) {
+ canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES2::WORLD_MATRIX, instance->xform_cache);
+ if (cull != instance->cull_cache) {
- cull=instance->cull_cache;
- switch(cull) {
+ cull = instance->cull_cache;
+ switch (cull) {
case VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED: {
glDisable(GL_CULL_FACE);
@@ -8985,7 +8389,7 @@ void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Tran
} break;
}
}
-/*
+ /*
if (i==0) {
for(int i=0;i<cc->lines.size();i++) {
Vector2 p = instance->xform_cache.xform(cc->lines.get(i));
@@ -8998,24 +8402,21 @@ void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Tran
}
}
*/
- glBindBuffer(GL_ARRAY_BUFFER,cc->vertex_id);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,cc->index_id);
+ glBindBuffer(GL_ARRAY_BUFFER, cc->vertex_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cc->index_id);
glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, 0);
- glDrawElements(GL_TRIANGLES,cc->len*3,GL_UNSIGNED_SHORT,0);
+ glDrawElements(GL_TRIANGLES, cc->len * 3, GL_UNSIGNED_SHORT, 0);
-
- instance=instance->next;
+ instance = instance->next;
}
-
-
}
glDisableVertexAttribArray(VS::ARRAY_VERTEX);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- if (shadow_filter==SHADOW_FILTER_ESM) {
- //blur the buffer
+ if (shadow_filter == SHADOW_FILTER_ESM) {
+//blur the buffer
#if 0
//this is ignord, it did not make any difference..
if (read_depth_supported) {
@@ -9102,17 +8503,13 @@ void RasterizerGLES2::canvas_light_shadow_buffer_update(RID p_buffer, const Tran
#endif
}
- glBindFramebuffer(GL_FRAMEBUFFER, current_rt?current_rt->fbo:base_framebuffer);
+ glBindFramebuffer(GL_FRAMEBUFFER, current_rt ? current_rt->fbo : base_framebuffer);
glColorMask(1, 1, 1, 1);
-
-
-
}
+void RasterizerGLES2::canvas_debug_viewport_shadows(CanvasLight *p_lights_with_shadow) {
-void RasterizerGLES2::canvas_debug_viewport_shadows(CanvasLight* p_lights_with_shadow) {
-
- CanvasLight* light=p_lights_with_shadow;
+ CanvasLight *light = p_lights_with_shadow;
canvas_begin(); //reset
@@ -9121,60 +8518,56 @@ void RasterizerGLES2::canvas_debug_viewport_shadows(CanvasLight* p_lights_with_s
int ofs = h;
//print_line(" debug lights ");
- while(light) {
+ while (light) {
//print_line("debug light");
if (light->shadow_buffer.is_valid()) {
//print_line("sb is valid");
- CanvasLightShadow * sb = canvas_light_shadow_owner.get(light->shadow_buffer);
+ CanvasLightShadow *sb = canvas_light_shadow_owner.get(light->shadow_buffer);
if (sb) {
glActiveTexture(GL_TEXTURE0);
if (read_depth_supported)
- glBindTexture(GL_TEXTURE_2D,sb->depth);
+ glBindTexture(GL_TEXTURE_2D, sb->depth);
else
- glBindTexture(GL_TEXTURE_2D,sb->rgba);
- _draw_textured_quad(Rect2(h,ofs,w-h*2,h),Rect2(0,0,sb->size,10),Size2(sb->size,10),false,false);
- ofs+=h*2;
-
+ glBindTexture(GL_TEXTURE_2D, sb->rgba);
+ _draw_textured_quad(Rect2(h, ofs, w - h * 2, h), Rect2(0, 0, sb->size, 10), Size2(sb->size, 10), false, false);
+ ofs += h * 2;
}
}
- light=light->shadows_next_ptr;
+ light = light->shadows_next_ptr;
}
-
}
-void RasterizerGLES2::_canvas_normal_set_flip(const Vector2& p_flip) {
+void RasterizerGLES2::_canvas_normal_set_flip(const Vector2 &p_flip) {
- if (p_flip==normal_flip)
+ if (p_flip == normal_flip)
return;
- normal_flip=p_flip;
- canvas_shader.set_uniform(CanvasShaderGLES2::NORMAL_FLIP,normal_flip);
+ normal_flip = p_flip;
+ canvas_shader.set_uniform(CanvasShaderGLES2::NORMAL_FLIP, normal_flip);
}
+template <bool use_normalmap>
+void RasterizerGLES2::_canvas_item_render_commands(CanvasItem *p_item, CanvasItem *current_clip, bool &reclip) {
-template<bool use_normalmap>
-void RasterizerGLES2::_canvas_item_render_commands(CanvasItem *p_item,CanvasItem *current_clip,bool &reclip) {
-
- int cc=p_item->commands.size();
+ int cc = p_item->commands.size();
CanvasItem::Command **commands = p_item->commands.ptr();
+ for (int i = 0; i < cc; i++) {
- for(int i=0;i<cc;i++) {
-
- CanvasItem::Command *c=commands[i];
+ CanvasItem::Command *c = commands[i];
- switch(c->type) {
+ switch (c->type) {
case CanvasItem::Command::TYPE_LINE: {
- CanvasItem::CommandLine* line = static_cast<CanvasItem::CommandLine*>(c);
- canvas_draw_line(line->from,line->to,line->color,line->width,line->antialiased);
+ CanvasItem::CommandLine *line = static_cast<CanvasItem::CommandLine *>(c);
+ canvas_draw_line(line->from, line->to, line->color, line->width, line->antialiased);
} break;
case CanvasItem::Command::TYPE_RECT: {
- CanvasItem::CommandRect* rect = static_cast<CanvasItem::CommandRect*>(c);
- //canvas_draw_rect(rect->rect,rect->region,rect->source,rect->flags&CanvasItem::CommandRect::FLAG_TILE,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_H,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_V,rect->texture,rect->modulate);
+ CanvasItem::CommandRect *rect = static_cast<CanvasItem::CommandRect *>(c);
+//canvas_draw_rect(rect->rect,rect->region,rect->source,rect->flags&CanvasItem::CommandRect::FLAG_TILE,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_H,rect->flags&CanvasItem::CommandRect::FLAG_FLIP_V,rect->texture,rect->modulate);
#if 0
int flags=0;
@@ -9194,84 +8587,84 @@ void RasterizerGLES2::_canvas_item_render_commands(CanvasItem *p_item,CanvasItem
}
#else
- int flags=rect->flags;
+ int flags = rect->flags;
#endif
if (use_normalmap)
- _canvas_normal_set_flip(Vector2((flags&CANVAS_RECT_FLIP_H)?-1:1,(flags&CANVAS_RECT_FLIP_V)?-1:1));
- canvas_draw_rect(rect->rect,flags,rect->source,rect->texture,rect->modulate);
+ _canvas_normal_set_flip(Vector2((flags & CANVAS_RECT_FLIP_H) ? -1 : 1, (flags & CANVAS_RECT_FLIP_V) ? -1 : 1));
+ canvas_draw_rect(rect->rect, flags, rect->source, rect->texture, rect->modulate);
} break;
case CanvasItem::Command::TYPE_STYLE: {
- CanvasItem::CommandStyle* style = static_cast<CanvasItem::CommandStyle*>(c);
+ CanvasItem::CommandStyle *style = static_cast<CanvasItem::CommandStyle *>(c);
if (use_normalmap)
- _canvas_normal_set_flip(Vector2(1,1));
- canvas_draw_style_box(style->rect,style->source,style->texture,style->margin,style->draw_center,style->color);
+ _canvas_normal_set_flip(Vector2(1, 1));
+ canvas_draw_style_box(style->rect, style->source, style->texture, style->margin, style->draw_center, style->color);
} break;
case CanvasItem::Command::TYPE_PRIMITIVE: {
if (use_normalmap)
- _canvas_normal_set_flip(Vector2(1,1));
- CanvasItem::CommandPrimitive* primitive = static_cast<CanvasItem::CommandPrimitive*>(c);
- canvas_draw_primitive(primitive->points,primitive->colors,primitive->uvs,primitive->texture,primitive->width);
+ _canvas_normal_set_flip(Vector2(1, 1));
+ CanvasItem::CommandPrimitive *primitive = static_cast<CanvasItem::CommandPrimitive *>(c);
+ canvas_draw_primitive(primitive->points, primitive->colors, primitive->uvs, primitive->texture, primitive->width);
} break;
case CanvasItem::Command::TYPE_POLYGON: {
if (use_normalmap)
- _canvas_normal_set_flip(Vector2(1,1));
- CanvasItem::CommandPolygon* polygon = static_cast<CanvasItem::CommandPolygon*>(c);
- canvas_draw_polygon(polygon->count,polygon->indices.ptr(),polygon->points.ptr(),polygon->uvs.ptr(),polygon->colors.ptr(),polygon->texture,polygon->colors.size()==1);
+ _canvas_normal_set_flip(Vector2(1, 1));
+ CanvasItem::CommandPolygon *polygon = static_cast<CanvasItem::CommandPolygon *>(c);
+ canvas_draw_polygon(polygon->count, polygon->indices.ptr(), polygon->points.ptr(), polygon->uvs.ptr(), polygon->colors.ptr(), polygon->texture, polygon->colors.size() == 1);
} break;
case CanvasItem::Command::TYPE_POLYGON_PTR: {
if (use_normalmap)
- _canvas_normal_set_flip(Vector2(1,1));
- CanvasItem::CommandPolygonPtr* polygon = static_cast<CanvasItem::CommandPolygonPtr*>(c);
- canvas_draw_polygon(polygon->count,polygon->indices,polygon->points,polygon->uvs,polygon->colors,polygon->texture,false);
+ _canvas_normal_set_flip(Vector2(1, 1));
+ CanvasItem::CommandPolygonPtr *polygon = static_cast<CanvasItem::CommandPolygonPtr *>(c);
+ canvas_draw_polygon(polygon->count, polygon->indices, polygon->points, polygon->uvs, polygon->colors, polygon->texture, false);
} break;
case CanvasItem::Command::TYPE_CIRCLE: {
- CanvasItem::CommandCircle* circle = static_cast<CanvasItem::CommandCircle*>(c);
- static const int numpoints=32;
- Vector2 points[numpoints+1];
- points[numpoints]=circle->pos;
- int indices[numpoints*3];
+ CanvasItem::CommandCircle *circle = static_cast<CanvasItem::CommandCircle *>(c);
+ static const int numpoints = 32;
+ Vector2 points[numpoints + 1];
+ points[numpoints] = circle->pos;
+ int indices[numpoints * 3];
- for(int i=0;i<numpoints;i++) {
+ for (int i = 0; i < numpoints; i++) {
- points[i]=circle->pos+Vector2( Math::sin(i*Math_PI*2.0/numpoints),Math::cos(i*Math_PI*2.0/numpoints) )*circle->radius;
- indices[i*3+0]=i;
- indices[i*3+1]=(i+1)%numpoints;
- indices[i*3+2]=numpoints;
+ points[i] = circle->pos + Vector2(Math::sin(i * Math_PI * 2.0 / numpoints), Math::cos(i * Math_PI * 2.0 / numpoints)) * circle->radius;
+ indices[i * 3 + 0] = i;
+ indices[i * 3 + 1] = (i + 1) % numpoints;
+ indices[i * 3 + 2] = numpoints;
}
- canvas_draw_polygon(numpoints*3,indices,points,NULL,&circle->color,RID(),true);
+ canvas_draw_polygon(numpoints * 3, indices, points, NULL, &circle->color, RID(), true);
//canvas_draw_circle(circle->indices.size(),circle->indices.ptr(),circle->points.ptr(),circle->uvs.ptr(),circle->colors.ptr(),circle->texture,circle->colors.size()==1);
} break;
case CanvasItem::Command::TYPE_TRANSFORM: {
- CanvasItem::CommandTransform* transform = static_cast<CanvasItem::CommandTransform*>(c);
+ CanvasItem::CommandTransform *transform = static_cast<CanvasItem::CommandTransform *>(c);
canvas_set_transform(transform->xform);
} break;
case CanvasItem::Command::TYPE_BLEND_MODE: {
- CanvasItem::CommandBlendMode* bm = static_cast<CanvasItem::CommandBlendMode*>(c);
+ CanvasItem::CommandBlendMode *bm = static_cast<CanvasItem::CommandBlendMode *>(c);
canvas_set_blend_mode(bm->blend_mode);
} break;
case CanvasItem::Command::TYPE_CLIP_IGNORE: {
- CanvasItem::CommandClipIgnore* ci = static_cast<CanvasItem::CommandClipIgnore*>(c);
+ CanvasItem::CommandClipIgnore *ci = static_cast<CanvasItem::CommandClipIgnore *>(c);
if (current_clip) {
- if (ci->ignore!=reclip) {
+ if (ci->ignore != reclip) {
if (ci->ignore) {
glDisable(GL_SCISSOR_TEST);
- reclip=true;
- } else {
+ reclip = true;
+ } else {
glEnable(GL_SCISSOR_TEST);
//glScissor(viewport.x+current_clip->final_clip_rect.pos.x,viewport.y+ (viewport.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),
@@ -9287,51 +8680,46 @@ void RasterizerGLES2::_canvas_item_render_commands(CanvasItem *p_item,CanvasItem
y = current_clip->final_clip_rect.pos.y;
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
- }
- else {
+ } else {
x = current_clip->final_clip_rect.pos.x;
y = window_size.height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y);
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
}
- glScissor(x,y,w,h);
+ glScissor(x, y, w, h);
-
- reclip=false;
+ reclip = false;
}
}
}
-
-
} break;
}
}
-
}
-void RasterizerGLES2::_canvas_item_setup_shader_params(CanvasItemMaterial *material,Shader* shader) {
+void RasterizerGLES2::_canvas_item_setup_shader_params(CanvasItemMaterial *material, Shader *shader) {
if (canvas_shader.bind())
- rebind_texpixel_size=true;
+ rebind_texpixel_size = true;
- if (material->shader_version!=shader->version) {
+ if (material->shader_version != shader->version) {
//todo optimize uniforms
- material->shader_version=shader->version;
+ material->shader_version = shader->version;
}
if (shader->has_texscreen && framebuffer.active) {
int x = viewport.x;
- int y = window_size.height-(viewport.height+viewport.y);
-
- canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_MULT,Vector2(float(viewport.width)/framebuffer.width,float(viewport.height)/framebuffer.height));
- canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP,Color(float(x)/framebuffer.width,float(y)/framebuffer.height,float(x+viewport.width)/framebuffer.width,float(y+viewport.height)/framebuffer.height));
- canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_TEX,max_texture_units-1);
- glActiveTexture(GL_TEXTURE0+max_texture_units-1);
- glBindTexture(GL_TEXTURE_2D,framebuffer.sample_color);
- if (framebuffer.scale==1 && !canvas_texscreen_used) {
+ int y = window_size.height - (viewport.height + viewport.y);
+
+ canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_MULT, Vector2(float(viewport.width) / framebuffer.width, float(viewport.height) / framebuffer.height));
+ canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP, Color(float(x) / framebuffer.width, float(y) / framebuffer.height, float(x + viewport.width) / framebuffer.width, float(y + viewport.height) / framebuffer.height));
+ canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_TEX, max_texture_units - 1);
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 1);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.sample_color);
+ if (framebuffer.scale == 1 && !canvas_texscreen_used) {
#ifdef GLEW_ENABLED
if (current_rt) {
glReadBuffer(GL_COLOR_ATTACHMENT0);
@@ -9340,50 +8728,47 @@ void RasterizerGLES2::_canvas_item_setup_shader_params(CanvasItemMaterial *mater
}
#endif
if (current_rt) {
- glCopyTexSubImage2D(GL_TEXTURE_2D,0,viewport.x,viewport.y,viewport.x,viewport.y,viewport.width,viewport.height);
- canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP,Color(float(x)/framebuffer.width,float(viewport.y)/framebuffer.height,float(x+viewport.width)/framebuffer.width,float(y+viewport.height)/framebuffer.height));
+ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, viewport.x, viewport.y, viewport.x, viewport.y, viewport.width, viewport.height);
+ canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP, Color(float(x) / framebuffer.width, float(viewport.y) / framebuffer.height, float(x + viewport.width) / framebuffer.width, float(y + viewport.height) / framebuffer.height));
//window_size.height-(viewport.height+viewport.y)
} else {
- glCopyTexSubImage2D(GL_TEXTURE_2D,0,x,y,x,y,viewport.width,viewport.height);
+ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, x, y, viewport.width, viewport.height);
}
- canvas_texscreen_used=true;
+ canvas_texscreen_used = true;
}
glActiveTexture(GL_TEXTURE0);
-
}
if (shader->has_screen_uv) {
- canvas_shader.set_uniform(CanvasShaderGLES2::SCREEN_UV_MULT,Vector2(1.0/viewport.width,1.0/viewport.height));
+ canvas_shader.set_uniform(CanvasShaderGLES2::SCREEN_UV_MULT, Vector2(1.0 / viewport.width, 1.0 / viewport.height));
}
-
- uses_texpixel_size=shader->uses_texpixel_size;
-
+ uses_texpixel_size = shader->uses_texpixel_size;
}
-void RasterizerGLES2::_canvas_item_setup_shader_uniforms(CanvasItemMaterial *material,Shader* shader) {
+void RasterizerGLES2::_canvas_item_setup_shader_uniforms(CanvasItemMaterial *material, Shader *shader) {
//this can be optimized..
- int tex_id=1;
- int idx=0;
- for(Map<StringName,ShaderLanguage::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) {
+ int tex_id = 1;
+ int idx = 0;
+ for (Map<StringName, ShaderLanguage::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
- Map<StringName,Variant>::Element *F=material->shader_param.find(E->key());
+ Map<StringName, Variant>::Element *F = material->shader_param.find(E->key());
- if ((E->get().type==ShaderLanguage::TYPE_TEXTURE || E->get().type==ShaderLanguage::TYPE_CUBEMAP)) {
+ if ((E->get().type == ShaderLanguage::TYPE_TEXTURE || E->get().type == ShaderLanguage::TYPE_CUBEMAP)) {
RID rid;
if (F) {
- rid=F->get();
+ rid = F->get();
}
if (!rid.is_valid()) {
- Map<StringName,RID>::Element *DT=shader->default_textures.find(E->key());
+ Map<StringName, RID>::Element *DT = shader->default_textures.find(E->key());
if (DT) {
- rid=DT->get();
+ rid = DT->get();
}
}
@@ -9391,88 +8776,81 @@ void RasterizerGLES2::_canvas_item_setup_shader_uniforms(CanvasItemMaterial *mat
int loc = canvas_shader.get_custom_uniform_location(idx); //should be automatic..
- glActiveTexture(GL_TEXTURE0+tex_id);
- Texture *t=texture_owner.get(rid);
+ glActiveTexture(GL_TEXTURE0 + tex_id);
+ Texture *t = texture_owner.get(rid);
if (!t)
- glBindTexture(GL_TEXTURE_2D,white_tex);
+ glBindTexture(GL_TEXTURE_2D, white_tex);
else
- glBindTexture(t->target,t->tex_id);
+ glBindTexture(t->target, t->tex_id);
- glUniform1i(loc,tex_id);
+ glUniform1i(loc, tex_id);
tex_id++;
}
} else {
- Variant &v=F?F->get():E->get().default_value;
- canvas_shader.set_custom_uniform(idx,v);
+ Variant &v = F ? F->get() : E->get().default_value;
+ canvas_shader.set_custom_uniform(idx, v);
}
idx++;
}
- if (tex_id>1) {
+ if (tex_id > 1) {
glActiveTexture(GL_TEXTURE0);
}
if (shader->uses_time) {
- canvas_shader.set_uniform(CanvasShaderGLES2::TIME,Math::fmod(last_time,shader_time_rollback));
- draw_next_frame=true;
+ canvas_shader.set_uniform(CanvasShaderGLES2::TIME, Math::fmod(last_time, shader_time_rollback));
+ draw_next_frame = true;
}
- //if uses TIME - draw_next_frame=true
-
-
+ //if uses TIME - draw_next_frame=true
}
-void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const Color& p_modulate,CanvasLight *p_light) {
+void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list, int p_z, const Color &p_modulate, CanvasLight *p_light) {
+ CanvasItem *current_clip = NULL;
+ Shader *shader_cache = NULL;
- CanvasItem *current_clip=NULL;
- Shader *shader_cache=NULL;
+ bool rebind_shader = true;
- bool rebind_shader=true;
+ canvas_opacity = 1.0;
+ canvas_use_modulate = p_modulate != Color(1, 1, 1, 1);
+ canvas_modulate = p_modulate;
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE, canvas_use_modulate);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD, false);
- canvas_opacity=1.0;
- canvas_use_modulate=p_modulate!=Color(1,1,1,1);
- canvas_modulate=p_modulate;
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,canvas_use_modulate);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD,false);
+ bool reset_modulate = false;
+ bool prev_distance_field = false;
+ while (p_item_list) {
- bool reset_modulate=false;
- bool prev_distance_field=false;
-
- while(p_item_list) {
-
- CanvasItem *ci=p_item_list;
+ CanvasItem *ci = p_item_list;
if (ci->vp_render) {
if (draw_viewport_func) {
- draw_viewport_func(ci->vp_render->owner,ci->vp_render->udata,ci->vp_render->rect);
+ draw_viewport_func(ci->vp_render->owner, ci->vp_render->udata, ci->vp_render->rect);
}
memdelete(ci->vp_render);
- ci->vp_render=NULL;
- canvas_last_material=NULL;
- canvas_use_modulate=p_modulate!=Color(1,1,1,1);
- canvas_modulate=p_modulate;
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,canvas_use_modulate);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD,false);
- prev_distance_field=false;
- rebind_shader=true;
- reset_modulate=true;
-
-
+ ci->vp_render = NULL;
+ canvas_last_material = NULL;
+ canvas_use_modulate = p_modulate != Color(1, 1, 1, 1);
+ canvas_modulate = p_modulate;
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE, canvas_use_modulate);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD, false);
+ prev_distance_field = false;
+ rebind_shader = true;
+ reset_modulate = true;
}
- if (prev_distance_field!=ci->distance_field) {
+ if (prev_distance_field != ci->distance_field) {
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD,ci->distance_field);
- prev_distance_field=ci->distance_field;
- rebind_shader=true;
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_DISTANCE_FIELD, ci->distance_field);
+ prev_distance_field = ci->distance_field;
+ rebind_shader = true;
}
+ if (current_clip != ci->final_clip_owner) {
- if (current_clip!=ci->final_clip_owner) {
-
- current_clip=ci->final_clip_owner;
+ current_clip = ci->final_clip_owner;
//setup clip
if (current_clip) {
@@ -9481,7 +8859,7 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
//glScissor(viewport.x+current_clip->final_clip_rect.pos.x,viewport.y+ (viewport.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),
//current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height);
-/* int x = viewport.x+current_clip->final_clip_rect.pos.x;
+ /* int x = viewport.x+current_clip->final_clip_rect.pos.x;
int y = window_size.height-(viewport.y+current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.y);
int w = current_clip->final_clip_rect.size.x;
int h = current_clip->final_clip_rect.size.y;
@@ -9496,15 +8874,14 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
y = current_clip->final_clip_rect.pos.y;
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
- }
- else {
+ } else {
x = current_clip->final_clip_rect.pos.x;
y = window_size.height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y);
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
}
- glScissor(x,y,w,h);
+ glScissor(x, y, w, h);
} else {
@@ -9512,21 +8889,21 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
}
}
- if (ci->copy_back_buffer && framebuffer.active && framebuffer.scale==1) {
+ if (ci->copy_back_buffer && framebuffer.active && framebuffer.scale == 1) {
Rect2 rect;
- int x,y;
+ int x, y;
if (ci->copy_back_buffer->full) {
x = viewport.x;
- y = window_size.height-(viewport.height+viewport.y);
+ y = window_size.height - (viewport.height + viewport.y);
} else {
- x = viewport.x+ci->copy_back_buffer->screen_rect.pos.x;
- y = window_size.height-(viewport.y+ci->copy_back_buffer->screen_rect.pos.y+ci->copy_back_buffer->screen_rect.size.y);
+ x = viewport.x + ci->copy_back_buffer->screen_rect.pos.x;
+ y = window_size.height - (viewport.y + ci->copy_back_buffer->screen_rect.pos.y + ci->copy_back_buffer->screen_rect.size.y);
}
- glActiveTexture(GL_TEXTURE0+max_texture_units-1);
- glBindTexture(GL_TEXTURE_2D,framebuffer.sample_color);
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 1);
+ glBindTexture(GL_TEXTURE_2D, framebuffer.sample_color);
#ifdef GLEW_ENABLED
if (current_rt) {
@@ -9536,150 +8913,137 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
}
#endif
if (current_rt) {
- glCopyTexSubImage2D(GL_TEXTURE_2D,0,viewport.x,viewport.y,viewport.x,viewport.y,viewport.width,viewport.height);
+ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, viewport.x, viewport.y, viewport.x, viewport.y, viewport.width, viewport.height);
//window_size.height-(viewport.height+viewport.y)
} else {
- glCopyTexSubImage2D(GL_TEXTURE_2D,0,x,y,x,y,viewport.width,viewport.height);
+ glCopyTexSubImage2D(GL_TEXTURE_2D, 0, x, y, x, y, viewport.width, viewport.height);
}
- canvas_texscreen_used=true;
+ canvas_texscreen_used = true;
glActiveTexture(GL_TEXTURE0);
}
-
-
-
//begin rect
- CanvasItem *material_owner = ci->material_owner?ci->material_owner:ci;
+ CanvasItem *material_owner = ci->material_owner ? ci->material_owner : ci;
CanvasItemMaterial *material = material_owner->material;
- if (material!=canvas_last_material || rebind_shader) {
+ if (material != canvas_last_material || rebind_shader) {
Shader *shader = NULL;
if (material && material->shader.is_valid()) {
shader = shader_owner.get(material->shader);
if (shader && !shader->valid) {
- shader=NULL;
+ shader = NULL;
}
}
- shader_cache=shader;
+ shader_cache = shader;
if (shader) {
canvas_shader.set_custom_shader(shader->custom_code_id);
- _canvas_item_setup_shader_params(material,shader);
+ _canvas_item_setup_shader_params(material, shader);
} else {
- shader_cache=NULL;
+ shader_cache = NULL;
canvas_shader.set_custom_shader(0);
canvas_shader.bind();
- uses_texpixel_size=false;
-
+ uses_texpixel_size = false;
}
-
- canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX,canvas_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX, canvas_transform);
if (canvas_use_modulate)
- reset_modulate=true;
- canvas_last_material=material;
- rebind_shader=false;
+ reset_modulate = true;
+ canvas_last_material = material;
+ rebind_shader = false;
}
if (material && shader_cache) {
- _canvas_item_setup_shader_uniforms(material,shader_cache);
+ _canvas_item_setup_shader_uniforms(material, shader_cache);
}
- bool unshaded = (material && material->shading_mode==VS::CANVAS_ITEM_SHADING_UNSHADED) || ci->blend_mode!=VS::MATERIAL_BLEND_MODE_MIX;
+ bool unshaded = (material && material->shading_mode == VS::CANVAS_ITEM_SHADING_UNSHADED) || ci->blend_mode != VS::MATERIAL_BLEND_MODE_MIX;
if (unshaded) {
- canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE,Color(1,1,1,1));
- reset_modulate=true;
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE, Color(1, 1, 1, 1));
+ reset_modulate = true;
} else if (reset_modulate) {
- canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE,canvas_modulate);
- reset_modulate=false;
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE, canvas_modulate);
+ reset_modulate = false;
}
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, ci->final_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D());
+ bool reclip = false;
- canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,ci->final_transform);
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D());
-
-
- bool reclip=false;
-
- if (ci==p_item_list || ci->blend_mode!=canvas_blend_mode) {
+ if (ci == p_item_list || ci->blend_mode != canvas_blend_mode) {
- switch(ci->blend_mode) {
+ switch (ci->blend_mode) {
- case VS::MATERIAL_BLEND_MODE_MIX: {
+ case VS::MATERIAL_BLEND_MODE_MIX: {
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- } break;
- case VS::MATERIAL_BLEND_MODE_ADD: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
- } break;
- case VS::MATERIAL_BLEND_MODE_SUB: {
+ } break;
+ case VS::MATERIAL_BLEND_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
- } break;
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ } break;
case VS::MATERIAL_BLEND_MODE_MUL: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_DST_COLOR,GL_ZERO);
+ glBlendFunc(GL_DST_COLOR, GL_ZERO);
} break;
case VS::MATERIAL_BLEND_MODE_PREMULT_ALPHA: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA);
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} break;
-
}
- canvas_blend_mode=ci->blend_mode;
+ canvas_blend_mode = ci->blend_mode;
}
canvas_opacity = ci->final_opacity;
+ if (unshaded || (p_modulate.a > 0.001 && (!material || material->shading_mode != VS::CANVAS_ITEM_SHADING_ONLY_LIGHT) && !ci->light_masked))
+ _canvas_item_render_commands<false>(ci, current_clip, reclip);
- if (unshaded || (p_modulate.a>0.001 && (!material || material->shading_mode!=VS::CANVAS_ITEM_SHADING_ONLY_LIGHT) && !ci->light_masked ))
- _canvas_item_render_commands<false>(ci,current_clip,reclip);
-
- if (canvas_blend_mode==VS::MATERIAL_BLEND_MODE_MIX && p_light && !unshaded) {
+ if (canvas_blend_mode == VS::MATERIAL_BLEND_MODE_MIX && p_light && !unshaded) {
CanvasLight *light = p_light;
- bool light_used=false;
- VS::CanvasLightMode mode=VS::CANVAS_LIGHT_MODE_ADD;
+ bool light_used = false;
+ VS::CanvasLightMode mode = VS::CANVAS_LIGHT_MODE_ADD;
+ while (light) {
- while(light) {
-
-
- if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) {
+ if (ci->light_mask & light->item_mask && p_z >= light->z_min && p_z <= light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
//intersects this light
- if (!light_used || mode!=light->mode) {
+ if (!light_used || mode != light->mode) {
- mode=light->mode;
+ mode = light->mode;
- switch(mode) {
+ switch (mode) {
case VS::CANVAS_LIGHT_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
} break;
case VS::CANVAS_LIGHT_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
} break;
case VS::CANVAS_LIGHT_MODE_MIX:
case VS::CANVAS_LIGHT_MODE_MASK: {
@@ -9688,114 +9052,102 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
} break;
}
-
}
if (!light_used) {
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING,true);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,false);
- light_used=true;
- normal_flip=Vector2(1,1);
-
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, true);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE, false);
+ light_used = true;
+ normal_flip = Vector2(1, 1);
}
+ bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask & light->item_shadow_mask;
- bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask&light->item_shadow_mask;
-
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS,has_shadow);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, has_shadow);
bool light_rebind = canvas_shader.bind();
if (light_rebind) {
if (material && shader_cache) {
- _canvas_item_setup_shader_params(material,shader_cache);
- _canvas_item_setup_shader_uniforms(material,shader_cache);
+ _canvas_item_setup_shader_params(material, shader_cache);
+ _canvas_item_setup_shader_uniforms(material, shader_cache);
}
- canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,ci->final_transform);
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D());
- canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX,canvas_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, ci->final_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D());
+ canvas_shader.set_uniform(CanvasShaderGLES2::PROJECTION_MATRIX, canvas_transform);
if (canvas_use_modulate)
- canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE,canvas_modulate);
- canvas_shader.set_uniform(CanvasShaderGLES2::NORMAL_FLIP,Vector2(1,1));
- canvas_shader.set_uniform(CanvasShaderGLES2::SHADOWPIXEL_SIZE,1.0/light->shadow_buffer_size);
-
-
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE, canvas_modulate);
+ canvas_shader.set_uniform(CanvasShaderGLES2::NORMAL_FLIP, Vector2(1, 1));
+ canvas_shader.set_uniform(CanvasShaderGLES2::SHADOWPIXEL_SIZE, 1.0 / light->shadow_buffer_size);
}
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_MATRIX,light->light_shader_xform);
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_POS,light->light_shader_pos);
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_COLOR,Color(light->color.r*light->energy,light->color.g*light->energy,light->color.b*light->energy,light->color.a));
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_HEIGHT,light->height);
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_LOCAL_MATRIX,light->xform_cache.affine_inverse());
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_OUTSIDE_ALPHA,light->mode==VS::CANVAS_LIGHT_MODE_MASK?1.0:0.0);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_MATRIX, light->light_shader_xform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_POS, light->light_shader_pos);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_COLOR, Color(light->color.r * light->energy, light->color.g * light->energy, light->color.b * light->energy, light->color.a));
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_HEIGHT, light->height);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_LOCAL_MATRIX, light->xform_cache.affine_inverse());
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_OUTSIDE_ALPHA, light->mode == VS::CANVAS_LIGHT_MODE_MASK ? 1.0 : 0.0);
if (has_shadow) {
CanvasLightShadow *cls = canvas_light_shadow_owner.get(light->shadow_buffer);
- glActiveTexture(GL_TEXTURE0+max_texture_units-3);
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 3);
if (read_depth_supported)
- glBindTexture(GL_TEXTURE_2D,cls->depth);
+ glBindTexture(GL_TEXTURE_2D, cls->depth);
else
- glBindTexture(GL_TEXTURE_2D,cls->rgba);
-
- canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_TEXTURE,max_texture_units-3);
- canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_MATRIX,light->shadow_matrix_cache);
- canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_ESM_MULTIPLIER,light->shadow_esm_mult);
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_SHADOW_COLOR,light->shadow_color);
+ glBindTexture(GL_TEXTURE_2D, cls->rgba);
+ canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_TEXTURE, max_texture_units - 3);
+ canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_MATRIX, light->shadow_matrix_cache);
+ canvas_shader.set_uniform(CanvasShaderGLES2::SHADOW_ESM_MULTIPLIER, light->shadow_esm_mult);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_SHADOW_COLOR, light->shadow_color);
}
-
- glActiveTexture(GL_TEXTURE0+max_texture_units-2);
- canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_TEXTURE,max_texture_units-2);
+ glActiveTexture(GL_TEXTURE0 + max_texture_units - 2);
+ canvas_shader.set_uniform(CanvasShaderGLES2::LIGHT_TEXTURE, max_texture_units - 2);
Texture *t = texture_owner.get(light->texture);
if (!t) {
- glBindTexture(GL_TEXTURE_2D,white_tex);
+ glBindTexture(GL_TEXTURE_2D, white_tex);
} else {
- glBindTexture(t->target,t->tex_id);
+ glBindTexture(t->target, t->tex_id);
}
glActiveTexture(GL_TEXTURE0);
- _canvas_item_render_commands<true>(ci,current_clip,reclip); //redraw using light
-
+ _canvas_item_render_commands<true>(ci, current_clip, reclip); //redraw using light
}
- light=light->next_ptr;
+ light = light->next_ptr;
}
if (light_used) {
-
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING,false);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,canvas_use_modulate);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS,false);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_LIGHTING, false);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE, canvas_use_modulate);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_SHADOWS, false);
canvas_shader.bind();
if (material && shader_cache) {
- _canvas_item_setup_shader_params(material,shader_cache);
- _canvas_item_setup_shader_uniforms(material,shader_cache);
+ _canvas_item_setup_shader_params(material, shader_cache);
+ _canvas_item_setup_shader_uniforms(material, shader_cache);
}
- canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX,ci->final_transform);
- canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX,Transform2D());
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODELVIEW_MATRIX, ci->final_transform);
+ canvas_shader.set_uniform(CanvasShaderGLES2::EXTRA_MATRIX, Transform2D());
if (canvas_use_modulate)
- canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE,canvas_modulate);
+ canvas_shader.set_uniform(CanvasShaderGLES2::MODULATE, canvas_modulate);
glBlendEquation(GL_FUNC_ADD);
if (current_rt && current_rt_transparent) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
}
-
-
}
if (reclip) {
@@ -9814,116 +9166,104 @@ void RasterizerGLES2::canvas_render_items(CanvasItem *p_item_list,int p_z,const
y = current_clip->final_clip_rect.pos.y;
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
- }
- else {
+ } else {
x = current_clip->final_clip_rect.pos.x;
y = window_size.height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y);
w = current_clip->final_clip_rect.size.x;
h = current_clip->final_clip_rect.size.y;
}
- glScissor(x,y,w,h);
-
-
+ glScissor(x, y, w, h);
}
-
-
- p_item_list=p_item_list->next;
+ p_item_list = p_item_list->next;
}
if (current_clip) {
glDisable(GL_SCISSOR_TEST);
}
-
}
/* ENVIRONMENT */
RID RasterizerGLES2::environment_create() {
- Environment * env = memnew( Environment );
+ Environment *env = memnew(Environment);
return environment_owner.make_rid(env);
}
-void RasterizerGLES2::environment_set_background(RID p_env,VS::EnvironmentBG p_bg) {
+void RasterizerGLES2::environment_set_background(RID p_env, VS::EnvironmentBG p_bg) {
- ERR_FAIL_INDEX(p_bg,VS::ENV_BG_MAX);
- Environment * env = environment_owner.get(p_env);
+ ERR_FAIL_INDEX(p_bg, VS::ENV_BG_MAX);
+ Environment *env = environment_owner.get(p_env);
ERR_FAIL_COND(!env);
- env->bg_mode=p_bg;
+ env->bg_mode = p_bg;
}
-VS::EnvironmentBG RasterizerGLES2::environment_get_background(RID p_env) const{
+VS::EnvironmentBG RasterizerGLES2::environment_get_background(RID p_env) const {
- const Environment * env = environment_owner.get(p_env);
- ERR_FAIL_COND_V(!env,VS::ENV_BG_MAX);
+ const Environment *env = environment_owner.get(p_env);
+ ERR_FAIL_COND_V(!env, VS::ENV_BG_MAX);
return env->bg_mode;
}
-void RasterizerGLES2::environment_set_background_param(RID p_env,VS::EnvironmentBGParam p_param, const Variant& p_value){
+void RasterizerGLES2::environment_set_background_param(RID p_env, VS::EnvironmentBGParam p_param, const Variant &p_value) {
- ERR_FAIL_INDEX(p_param,VS::ENV_BG_PARAM_MAX);
- Environment * env = environment_owner.get(p_env);
+ ERR_FAIL_INDEX(p_param, VS::ENV_BG_PARAM_MAX);
+ Environment *env = environment_owner.get(p_env);
ERR_FAIL_COND(!env);
- env->bg_param[p_param]=p_value;
-
+ env->bg_param[p_param] = p_value;
}
-Variant RasterizerGLES2::environment_get_background_param(RID p_env,VS::EnvironmentBGParam p_param) const{
+Variant RasterizerGLES2::environment_get_background_param(RID p_env, VS::EnvironmentBGParam p_param) const {
- ERR_FAIL_INDEX_V(p_param,VS::ENV_BG_PARAM_MAX,Variant());
- const Environment * env = environment_owner.get(p_env);
- ERR_FAIL_COND_V(!env,Variant());
+ ERR_FAIL_INDEX_V(p_param, VS::ENV_BG_PARAM_MAX, Variant());
+ const Environment *env = environment_owner.get(p_env);
+ ERR_FAIL_COND_V(!env, Variant());
return env->bg_param[p_param];
-
}
-void RasterizerGLES2::environment_set_enable_fx(RID p_env,VS::EnvironmentFx p_effect,bool p_enabled){
+void RasterizerGLES2::environment_set_enable_fx(RID p_env, VS::EnvironmentFx p_effect, bool p_enabled) {
- ERR_FAIL_INDEX(p_effect,VS::ENV_FX_MAX);
- Environment * env = environment_owner.get(p_env);
+ ERR_FAIL_INDEX(p_effect, VS::ENV_FX_MAX);
+ Environment *env = environment_owner.get(p_env);
ERR_FAIL_COND(!env);
- env->fx_enabled[p_effect]=p_enabled;
+ env->fx_enabled[p_effect] = p_enabled;
}
-bool RasterizerGLES2::environment_is_fx_enabled(RID p_env,VS::EnvironmentFx p_effect) const{
+bool RasterizerGLES2::environment_is_fx_enabled(RID p_env, VS::EnvironmentFx p_effect) const {
- ERR_FAIL_INDEX_V(p_effect,VS::ENV_FX_MAX,false);
- const Environment * env = environment_owner.get(p_env);
- ERR_FAIL_COND_V(!env,false);
+ ERR_FAIL_INDEX_V(p_effect, VS::ENV_FX_MAX, false);
+ const Environment *env = environment_owner.get(p_env);
+ ERR_FAIL_COND_V(!env, false);
return env->fx_enabled[p_effect];
-
}
-void RasterizerGLES2::environment_fx_set_param(RID p_env,VS::EnvironmentFxParam p_param,const Variant& p_value){
+void RasterizerGLES2::environment_fx_set_param(RID p_env, VS::EnvironmentFxParam p_param, const Variant &p_value) {
- ERR_FAIL_INDEX(p_param,VS::ENV_FX_PARAM_MAX);
- Environment * env = environment_owner.get(p_env);
+ ERR_FAIL_INDEX(p_param, VS::ENV_FX_PARAM_MAX);
+ Environment *env = environment_owner.get(p_env);
ERR_FAIL_COND(!env);
- env->fx_param[p_param]=p_value;
+ env->fx_param[p_param] = p_value;
}
-Variant RasterizerGLES2::environment_fx_get_param(RID p_env,VS::EnvironmentFxParam p_param) const{
+Variant RasterizerGLES2::environment_fx_get_param(RID p_env, VS::EnvironmentFxParam p_param) const {
- ERR_FAIL_INDEX_V(p_param,VS::ENV_FX_PARAM_MAX,Variant());
- const Environment * env = environment_owner.get(p_env);
- ERR_FAIL_COND_V(!env,Variant());
+ ERR_FAIL_INDEX_V(p_param, VS::ENV_FX_PARAM_MAX, Variant());
+ const Environment *env = environment_owner.get(p_env);
+ ERR_FAIL_COND_V(!env, Variant());
return env->fx_param[p_param];
-
}
-
-
-RID RasterizerGLES2::sampled_light_dp_create(int p_width,int p_height) {
+RID RasterizerGLES2::sampled_light_dp_create(int p_width, int p_height) {
SampledLight *slight = memnew(SampledLight);
- slight->w=p_width;
- slight->h=p_height;
- slight->multiplier=1.0;
- slight->is_float=float_linear_supported;
+ slight->w = p_width;
+ slight->h = p_height;
+ slight->multiplier = 1.0;
+ slight->is_float = float_linear_supported;
glActiveTexture(GL_TEXTURE0);
- glGenTextures(1,&slight->texture);
+ glGenTextures(1, &slight->texture);
glBindTexture(GL_TEXTURE_2D, slight->texture);
-// for debug, but glitchy
+ // for debug, but glitchy
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
@@ -9933,17 +9273,15 @@ RID RasterizerGLES2::sampled_light_dp_create(int p_width,int p_height) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
if (slight->is_float) {
#ifdef GLEW_ENABLED
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_width, p_height, 0, GL_RGBA, GL_FLOAT,NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, p_width, p_height, 0, GL_RGBA, GL_FLOAT, NULL);
#else
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_width, p_height, 0, GL_RGBA, GL_FLOAT,NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_width, p_height, 0, GL_RGBA, GL_FLOAT, NULL);
#endif
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, p_width, p_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
-
}
return sampled_light_owner.make_rid(slight);
@@ -9960,47 +9298,46 @@ void RasterizerGLES2::sampled_light_dp_update(RID p_sampled_light, const Color *
if (slight->is_float) {
#ifdef GLEW_ENABLED
- glTexSubImage2D(GL_TEXTURE_2D, 0,0,0,slight->w, slight->h, GL_RGBA, GL_FLOAT,p_data);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, slight->w, slight->h, GL_RGBA, GL_FLOAT, p_data);
#else
- glTexSubImage2D(GL_TEXTURE_2D, 0,0,0,slight->w, slight->h, GL_RGBA, GL_FLOAT,p_data);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, slight->w, slight->h, GL_RGBA, GL_FLOAT, p_data);
#endif
} else {
//convert to bytes
- uint8_t *tex8 = (uint8_t*)alloca(slight->w*slight->h*4);
- const float* src=(const float*)p_data;
+ uint8_t *tex8 = (uint8_t *)alloca(slight->w * slight->h * 4);
+ const float *src = (const float *)p_data;
- for(int i=0;i<slight->w*slight->h*4;i++) {
+ for (int i = 0; i < slight->w * slight->h * 4; i++) {
- tex8[i]=Math::fast_ftoi(CLAMP(src[i]*255.0,0.0,255.0));
+ tex8[i] = Math::fast_ftoi(CLAMP(src[i] * 255.0, 0.0, 255.0));
}
- glTexSubImage2D(GL_TEXTURE_2D, 0,0,0,slight->w, slight->h, GL_RGBA, GL_UNSIGNED_BYTE,p_data);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, slight->w, slight->h, GL_RGBA, GL_UNSIGNED_BYTE, p_data);
}
- slight->multiplier=p_multiplier;
-
+ slight->multiplier = p_multiplier;
}
/*MISC*/
-bool RasterizerGLES2::is_texture(const RID& p_rid) const {
+bool RasterizerGLES2::is_texture(const RID &p_rid) const {
return texture_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_material(const RID& p_rid) const {
+bool RasterizerGLES2::is_material(const RID &p_rid) const {
return material_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_mesh(const RID& p_rid) const {
+bool RasterizerGLES2::is_mesh(const RID &p_rid) const {
return mesh_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_immediate(const RID& p_rid) const {
+bool RasterizerGLES2::is_immediate(const RID &p_rid) const {
return immediate_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_multimesh(const RID& p_rid) const {
+bool RasterizerGLES2::is_multimesh(const RID &p_rid) const {
return multimesh_owner.owns(p_rid);
}
@@ -10009,44 +9346,44 @@ bool RasterizerGLES2::is_particles(const RID &p_beam) const {
return particles_owner.owns(p_beam);
}
-bool RasterizerGLES2::is_light(const RID& p_rid) const {
+bool RasterizerGLES2::is_light(const RID &p_rid) const {
return light_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_light_instance(const RID& p_rid) const {
+bool RasterizerGLES2::is_light_instance(const RID &p_rid) const {
return light_instance_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_particles_instance(const RID& p_rid) const {
+bool RasterizerGLES2::is_particles_instance(const RID &p_rid) const {
return particles_instance_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_skeleton(const RID& p_rid) const {
+bool RasterizerGLES2::is_skeleton(const RID &p_rid) const {
return skeleton_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_environment(const RID& p_rid) const {
+bool RasterizerGLES2::is_environment(const RID &p_rid) const {
return environment_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_shader(const RID& p_rid) const {
+bool RasterizerGLES2::is_shader(const RID &p_rid) const {
return shader_owner.owns(p_rid);
}
-bool RasterizerGLES2::is_canvas_light_occluder(const RID& p_rid) const {
+bool RasterizerGLES2::is_canvas_light_occluder(const RID &p_rid) const {
return false;
}
-void RasterizerGLES2::free(const RID& p_rid) {
+void RasterizerGLES2::free(const RID &p_rid) {
if (texture_owner.owns(p_rid)) {
// delete the texture
Texture *texture = texture_owner.get(p_rid);
//glDeleteTextures( 1,&texture->tex_id );
- _rinfo.texture_mem-=texture->total_data_size;
+ _rinfo.texture_mem -= texture->total_data_size;
texture_owner.free(p_rid);
memdelete(texture);
@@ -10055,7 +9392,7 @@ void RasterizerGLES2::free(const RID& p_rid) {
// delete the texture
Shader *shader = shader_owner.get(p_rid);
- switch(shader->mode) {
+ switch (shader->mode) {
case VS::SHADER_MATERIAL: {
material_shader.free_custom_shader(shader->custom_code_id);
} break;
@@ -10073,7 +9410,7 @@ void RasterizerGLES2::free(const RID& p_rid) {
} else if (material_owner.owns(p_rid)) {
- Material *material = material_owner.get( p_rid );
+ Material *material = material_owner.get(p_rid);
ERR_FAIL_COND(!material);
_free_fixed_material(p_rid); //just in case
@@ -10084,7 +9421,7 @@ void RasterizerGLES2::free(const RID& p_rid) {
Mesh *mesh = mesh_owner.get(p_rid);
ERR_FAIL_COND(!mesh);
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
Surface *surface = mesh->surfaces[i];
if (surface->array_local != 0) {
@@ -10094,22 +9431,22 @@ void RasterizerGLES2::free(const RID& p_rid) {
memfree(surface->index_array_local);
};
- if (mesh->morph_target_count>0) {
+ if (mesh->morph_target_count > 0) {
- for(int i=0;i<mesh->morph_target_count;i++) {
+ for (int i = 0; i < mesh->morph_target_count; i++) {
memdelete_arr(surface->morph_targets_local[i].array);
}
memdelete_arr(surface->morph_targets_local);
- surface->morph_targets_local=NULL;
+ surface->morph_targets_local = NULL;
}
if (surface->vertex_id)
- glDeleteBuffers(1,&surface->vertex_id);
+ glDeleteBuffers(1, &surface->vertex_id);
if (surface->index_id)
- glDeleteBuffers(1,&surface->index_id);
+ glDeleteBuffers(1, &surface->index_id);
- memdelete( surface );
+ memdelete(surface);
};
mesh->surfaces.clear();
@@ -10119,15 +9456,15 @@ void RasterizerGLES2::free(const RID& p_rid) {
} else if (multimesh_owner.owns(p_rid)) {
- MultiMesh *multimesh = multimesh_owner.get(p_rid);
- ERR_FAIL_COND(!multimesh);
+ MultiMesh *multimesh = multimesh_owner.get(p_rid);
+ ERR_FAIL_COND(!multimesh);
if (multimesh->tex_id) {
- glDeleteTextures(1,&multimesh->tex_id);
+ glDeleteTextures(1, &multimesh->tex_id);
}
- multimesh_owner.free(p_rid);
- memdelete(multimesh);
+ multimesh_owner.free(p_rid);
+ memdelete(multimesh);
} else if (immediate_owner.owns(p_rid)) {
@@ -10153,20 +9490,20 @@ void RasterizerGLES2::free(const RID& p_rid) {
} else if (skeleton_owner.owns(p_rid)) {
- Skeleton *skeleton = skeleton_owner.get( p_rid );
+ Skeleton *skeleton = skeleton_owner.get(p_rid);
ERR_FAIL_COND(!skeleton);
if (skeleton->dirty_list.in_list())
_skeleton_dirty_list.remove(&skeleton->dirty_list);
if (skeleton->tex_id) {
- glDeleteTextures(1,&skeleton->tex_id);
+ glDeleteTextures(1, &skeleton->tex_id);
}
skeleton_owner.free(p_rid);
memdelete(skeleton);
} else if (light_owner.owns(p_rid)) {
- Light *light = light_owner.get( p_rid );
+ Light *light = light_owner.get(p_rid);
ERR_FAIL_COND(!light)
light_owner.free(p_rid);
@@ -10174,53 +9511,52 @@ void RasterizerGLES2::free(const RID& p_rid) {
} else if (light_instance_owner.owns(p_rid)) {
- LightInstance *light_instance = light_instance_owner.get( p_rid );
+ LightInstance *light_instance = light_instance_owner.get(p_rid);
ERR_FAIL_COND(!light_instance);
light_instance->clear_shadow_buffers();
light_instance_owner.free(p_rid);
- memdelete( light_instance );
+ memdelete(light_instance);
} else if (environment_owner.owns(p_rid)) {
- Environment *env = environment_owner.get( p_rid );
+ Environment *env = environment_owner.get(p_rid);
ERR_FAIL_COND(!env);
environment_owner.free(p_rid);
- memdelete( env );
+ memdelete(env);
} else if (viewport_data_owner.owns(p_rid)) {
- ViewportData *viewport_data = viewport_data_owner.get( p_rid );
+ ViewportData *viewport_data = viewport_data_owner.get(p_rid);
ERR_FAIL_COND(!viewport_data);
- glDeleteFramebuffers(1,&viewport_data->lum_fbo);
- glDeleteTextures(1,&viewport_data->lum_color);
+ glDeleteFramebuffers(1, &viewport_data->lum_fbo);
+ glDeleteTextures(1, &viewport_data->lum_color);
viewport_data_owner.free(p_rid);
- memdelete( viewport_data );
+ memdelete(viewport_data);
} else if (render_target_owner.owns(p_rid)) {
- RenderTarget *render_target = render_target_owner.get( p_rid );
+ RenderTarget *render_target = render_target_owner.get(p_rid);
ERR_FAIL_COND(!render_target);
- render_target_set_size(p_rid,0,0); //clears framebuffer
+ render_target_set_size(p_rid, 0, 0); //clears framebuffer
texture_owner.free(render_target->texture);
memdelete(render_target->texture_ptr);
render_target_owner.free(p_rid);
- memdelete( render_target );
+ memdelete(render_target);
} else if (sampled_light_owner.owns(p_rid)) {
- SampledLight *sampled_light = sampled_light_owner.get( p_rid );
+ SampledLight *sampled_light = sampled_light_owner.get(p_rid);
ERR_FAIL_COND(!sampled_light);
- glDeleteTextures(1,&sampled_light->texture);
+ glDeleteTextures(1, &sampled_light->texture);
sampled_light_owner.free(p_rid);
- memdelete( sampled_light );
+ memdelete(sampled_light);
} else if (canvas_occluder_owner.owns(p_rid)) {
-
CanvasOccluder *co = canvas_occluder_owner.get(p_rid);
if (co->index_id)
- glDeleteBuffers(1,&co->index_id);
+ glDeleteBuffers(1, &co->index_id);
if (co->vertex_id)
- glDeleteBuffers(1,&co->vertex_id);
+ glDeleteBuffers(1, &co->vertex_id);
canvas_occluder_owner.free(p_rid);
memdelete(co);
@@ -10228,9 +9564,9 @@ void RasterizerGLES2::free(const RID& p_rid) {
} else if (canvas_light_shadow_owner.owns(p_rid)) {
CanvasLightShadow *cls = canvas_light_shadow_owner.get(p_rid);
- glDeleteFramebuffers(1,&cls->fbo);
- glDeleteRenderbuffers(1,&cls->rbo);
- glDeleteTextures(1,&cls->depth);
+ glDeleteFramebuffers(1, &cls->fbo);
+ glDeleteRenderbuffers(1, &cls->rbo);
+ glDeleteTextures(1, &cls->depth);
/*
if (!read_depth_supported) {
glDeleteTextures(1,&cls->rgba);
@@ -10242,11 +9578,9 @@ void RasterizerGLES2::free(const RID& p_rid) {
};
}
+bool RasterizerGLES2::ShadowBuffer::init(int p_size, bool p_use_depth) {
-
-bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
-
- size=p_size;
+ size = p_size;
// Create a framebuffer object
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
@@ -10266,11 +9600,11 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//print_line("ERROR? "+itos(glGetError()));
- if ( p_use_depth ) {
+ if (p_use_depth) {
// We'll use a depth texture to store the depths in the shadow map
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, size, size, 0,
- GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
#ifdef GLEW_ENABLED
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
@@ -10279,7 +9613,7 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
// Attach the depth texture to FBO depth attachment point
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, depth, 0);
+ GL_TEXTURE_2D, depth, 0);
#ifdef GLEW_ENABLED
glDrawBuffer(GL_NONE);
@@ -10294,13 +9628,11 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
GL_TEXTURE_2D, depth, 0);
// Allocate 16-bit depth buffer
- glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, size,size);
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, size, size);
// Attach the render buffer as depth buffer - will be ignored
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, rbo);
-
-
}
#if 0
@@ -10351,7 +9683,7 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
#endif
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- //printf("errnum: %x\n",status);
+//printf("errnum: %x\n",status);
#ifdef GLEW_ENABLED
if (p_use_depth) {
//glDrawBuffer(GL_BACK);
@@ -10359,7 +9691,7 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
#endif
glBindFramebuffer(GL_FRAMEBUFFER, 0);
DEBUG_TEST_ERROR("Shadow Buffer Init");
- ERR_FAIL_COND_V( status != GL_FRAMEBUFFER_COMPLETE,false );
+ ERR_FAIL_COND_V(status != GL_FRAMEBUFFER_COMPLETE, false);
#ifdef GLEW_ENABLED
if (p_use_depth) {
@@ -10407,81 +9739,74 @@ bool RasterizerGLES2::ShadowBuffer::init(int p_size,bool p_use_depth) {
#endif
return true;
-
}
-
-
void RasterizerGLES2::_update_framebuffer() {
if (!use_framebuffers)
return;
- int scale = GLOBAL_DEF("rasterizer/framebuffer_shrink",1);
- if (scale<1)
- scale=1;
+ int scale = GLOBAL_DEF("rasterizer/framebuffer_shrink", 1);
+ if (scale < 1)
+ scale = 1;
- int dwidth = OS::get_singleton()->get_video_mode().width/scale;
- int dheight = OS::get_singleton()->get_video_mode().height/scale;
+ int dwidth = OS::get_singleton()->get_video_mode().width / scale;
+ int dheight = OS::get_singleton()->get_video_mode().height / scale;
- if (framebuffer.fbo && dwidth==framebuffer.width && dheight==framebuffer.height)
+ if (framebuffer.fbo && dwidth == framebuffer.width && dheight == framebuffer.height)
return;
+ bool use_fbo = true;
- bool use_fbo=true;
-
+ if (framebuffer.fbo != 0) {
- if (framebuffer.fbo!=0) {
-
- glDeleteFramebuffers(1,&framebuffer.fbo);
+ glDeleteFramebuffers(1, &framebuffer.fbo);
#if 0
glDeleteTextures(1,&framebuffer.depth);
#else
- glDeleteRenderbuffers(1,&framebuffer.depth);
+ glDeleteRenderbuffers(1, &framebuffer.depth);
#endif
- glDeleteTextures(1,&framebuffer.color);
-
- for(int i=0;i<framebuffer.luminance.size();i++) {
+ glDeleteTextures(1, &framebuffer.color);
- glDeleteTextures(1,&framebuffer.luminance[i].color);
- glDeleteFramebuffers(1,&framebuffer.luminance[i].fbo);
+ for (int i = 0; i < framebuffer.luminance.size(); i++) {
+ glDeleteTextures(1, &framebuffer.luminance[i].color);
+ glDeleteFramebuffers(1, &framebuffer.luminance[i].fbo);
}
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- glDeleteTextures(1,&framebuffer.blur[i].color);
- glDeleteFramebuffers(1,&framebuffer.blur[i].fbo);
+ glDeleteTextures(1, &framebuffer.blur[i].color);
+ glDeleteFramebuffers(1, &framebuffer.blur[i].fbo);
}
- glDeleteTextures(1,&framebuffer.sample_color);
- glDeleteFramebuffers(1,&framebuffer.sample_fbo);
+ glDeleteTextures(1, &framebuffer.sample_color);
+ glDeleteFramebuffers(1, &framebuffer.sample_fbo);
framebuffer.luminance.clear();
- framebuffer.blur_size=0;
- framebuffer.fbo=0;
+ framebuffer.blur_size = 0;
+ framebuffer.fbo = 0;
}
#ifdef TOOLS_ENABLED
- framebuffer.active=use_fbo;
+ framebuffer.active = use_fbo;
#else
- framebuffer.active=use_fbo && !low_memory_2d;
+ framebuffer.active = use_fbo && !low_memory_2d;
#endif
- framebuffer.width=dwidth;
- framebuffer.height=dheight;
- framebuffer.scale=scale;
+ framebuffer.width = dwidth;
+ framebuffer.height = dheight;
+ framebuffer.scale = scale;
if (!framebuffer.active)
return;
-
glGenFramebuffers(1, &framebuffer.fbo);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.fbo);
- //print_line("generating fbo, id: "+itos(framebuffer.fbo));
- //depth
+//print_line("generating fbo, id: "+itos(framebuffer.fbo));
+//depth
- // Create a render buffer
+// Create a render buffer
#if 0
glGenTextures(1, &framebuffer.depth);
@@ -10495,9 +9820,9 @@ void RasterizerGLES2::_update_framebuffer() {
#else
glGenRenderbuffers(1, &framebuffer.depth);
- glBindRenderbuffer(GL_RENDERBUFFER, framebuffer.depth );
+ glBindRenderbuffer(GL_RENDERBUFFER, framebuffer.depth);
- glRenderbufferStorage(GL_RENDERBUFFER, use_depth24?_DEPTH_COMPONENT24_OES:GL_DEPTH_COMPONENT16, framebuffer.width,framebuffer.height);
+ glRenderbufferStorage(GL_RENDERBUFFER, use_depth24 ? _DEPTH_COMPONENT24_OES : GL_DEPTH_COMPONENT16, framebuffer.width, framebuffer.height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, framebuffer.depth);
@@ -10506,28 +9831,25 @@ void RasterizerGLES2::_update_framebuffer() {
//GLuint format_rgba = use_fp16_fb?_GL_RGBA16F_EXT:GL_RGBA;
GLuint format_rgba = GL_RGBA;
- GLuint format_type = use_fp16_fb?_GL_HALF_FLOAT_OES:GL_UNSIGNED_BYTE;
- GLuint format_internal=GL_RGBA;
+ GLuint format_type = use_fp16_fb ? _GL_HALF_FLOAT_OES : GL_UNSIGNED_BYTE;
+ GLuint format_internal = GL_RGBA;
if (use_16bits_fbo) {
- format_type=GL_UNSIGNED_SHORT_5_6_5;
- format_rgba=GL_RGB;
- format_internal=GL_RGB;
+ format_type = GL_UNSIGNED_SHORT_5_6_5;
+ format_rgba = GL_RGB;
+ format_internal = GL_RGB;
}
/*GLuint format_luminance = use_fp16_fb?GL_RGB16F:GL_RGBA;
GLuint format_luminance_type = use_fp16_fb?(use_fu_GL_HALF_FLOAT_OES):GL_UNSIGNED_BYTE;
GLuint format_luminance_components = use_fp16_fb?GL_RGB:GL_RGBA;*/
- GLuint format_luminance = use_fp16_fb?_GL_RG_EXT:GL_RGBA;
- GLuint format_luminance_type = use_fp16_fb?(full_float_fb_supported?GL_FLOAT:_GL_HALF_FLOAT_OES):GL_UNSIGNED_BYTE;
- GLuint format_luminance_components = use_fp16_fb?_GL_RG_EXT:GL_RGBA;
-
-
-
+ GLuint format_luminance = use_fp16_fb ? _GL_RG_EXT : GL_RGBA;
+ GLuint format_luminance_type = use_fp16_fb ? (full_float_fb_supported ? GL_FLOAT : _GL_HALF_FLOAT_OES) : GL_UNSIGNED_BYTE;
+ GLuint format_luminance_components = use_fp16_fb ? _GL_RG_EXT : GL_RGBA;
glGenTextures(1, &framebuffer.color);
glBindTexture(GL_TEXTURE_2D, framebuffer.color);
- glTexImage2D(GL_TEXTURE_2D, 0, format_rgba, framebuffer.width, framebuffer.height, 0, format_internal, format_type, NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, format_rgba, framebuffer.width, framebuffer.height, 0, format_internal, format_type, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -10541,18 +9863,18 @@ void RasterizerGLES2::_update_framebuffer() {
if (status != GL_FRAMEBUFFER_COMPLETE) {
- glDeleteFramebuffers(1,&framebuffer.fbo);
+ glDeleteFramebuffers(1, &framebuffer.fbo);
#if 0
glDeleteTextures(1,&framebuffer.depth);
#else
- glDeleteRenderbuffers(1,&framebuffer.depth);
+ glDeleteRenderbuffers(1, &framebuffer.depth);
#endif
- glDeleteTextures(1,&framebuffer.color);
- framebuffer.fbo=0;
- framebuffer.active=false;
+ glDeleteTextures(1, &framebuffer.color);
+ framebuffer.fbo = 0;
+ framebuffer.active = false;
//print_line("**************** NO FAMEBUFFEEEERRRR????");
- WARN_PRINT(String("Could not create framebuffer!!, code: "+itos(status)).ascii().get_data());
+ WARN_PRINT(String("Could not create framebuffer!!, code: " + itos(status)).ascii().get_data());
}
//sample
@@ -10561,7 +9883,7 @@ void RasterizerGLES2::_update_framebuffer() {
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.sample_fbo);
glGenTextures(1, &framebuffer.sample_color);
glBindTexture(GL_TEXTURE_2D, framebuffer.sample_color);
- glTexImage2D(GL_TEXTURE_2D, 0, format_rgba, framebuffer.width, framebuffer.height, 0, format_internal, format_type, NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, format_rgba, framebuffer.width, framebuffer.height, 0, format_internal, format_type, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -10575,41 +9897,40 @@ void RasterizerGLES2::_update_framebuffer() {
if (status != GL_FRAMEBUFFER_COMPLETE) {
- glDeleteFramebuffers(1,&framebuffer.fbo);
+ glDeleteFramebuffers(1, &framebuffer.fbo);
#if 0
glDeleteTextures(1,&framebuffer.depth);
#else
- glDeleteRenderbuffers(1,&framebuffer.depth);
+ glDeleteRenderbuffers(1, &framebuffer.depth);
#endif
- glDeleteTextures(1,&framebuffer.color);
- glDeleteTextures(1,&framebuffer.sample_color);
- glDeleteFramebuffers(1,&framebuffer.sample_fbo);
- framebuffer.fbo=0;
- framebuffer.active=false;
+ glDeleteTextures(1, &framebuffer.color);
+ glDeleteTextures(1, &framebuffer.sample_color);
+ glDeleteFramebuffers(1, &framebuffer.sample_fbo);
+ framebuffer.fbo = 0;
+ framebuffer.active = false;
//print_line("**************** NO FAMEBUFFEEEERRRR????");
WARN_PRINT("Could not create framebuffer!!");
}
//blur
- int size = GLOBAL_DEF("rasterizer/blur_buffer_size",256);
+ int size = GLOBAL_DEF("rasterizer/blur_buffer_size", 256);
- if (size!=framebuffer.blur_size) {
+ if (size != framebuffer.blur_size) {
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
if (framebuffer.blur[i].fbo) {
- glDeleteFramebuffers(1,&framebuffer.blur[i].fbo);
- glDeleteTextures(1,&framebuffer.blur[i].color);
- framebuffer.blur[i].fbo=0;
- framebuffer.blur[i].color=0;
+ glDeleteFramebuffers(1, &framebuffer.blur[i].fbo);
+ glDeleteTextures(1, &framebuffer.blur[i].color);
+ framebuffer.blur[i].fbo = 0;
+ framebuffer.blur[i].color = 0;
}
}
- framebuffer.blur_size=size;
+ framebuffer.blur_size = size;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
glGenFramebuffers(1, &framebuffer.blur[i].fbo);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.blur[i].fbo);
@@ -10621,44 +9942,36 @@ void RasterizerGLES2::_update_framebuffer() {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, format_rgba, size, size, 0,
- format_internal, format_type, NULL);
+ format_internal, format_type, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, framebuffer.blur[i].color, 0);
-
+ GL_TEXTURE_2D, framebuffer.blur[i].color, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
DEBUG_TEST_ERROR("Shadow Buffer Init");
- ERR_CONTINUE( status != GL_FRAMEBUFFER_COMPLETE );
-
-
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
}
-
}
// luminance
- int base_size = GLOBAL_DEF("rasterizer/luminance_buffer_size",81);
-
- if (framebuffer.luminance.empty() || framebuffer.luminance[0].size!=base_size) {
+ int base_size = GLOBAL_DEF("rasterizer/luminance_buffer_size", 81);
+ if (framebuffer.luminance.empty() || framebuffer.luminance[0].size != base_size) {
- for(int i=0;i<framebuffer.luminance.size();i++) {
+ for (int i = 0; i < framebuffer.luminance.size(); i++) {
- glDeleteFramebuffers(1,&framebuffer.luminance[i].fbo);
- glDeleteTextures(1,&framebuffer.luminance[i].color);
+ glDeleteFramebuffers(1, &framebuffer.luminance[i].fbo);
+ glDeleteTextures(1, &framebuffer.luminance[i].color);
}
framebuffer.luminance.clear();
-
-
- while(base_size>0) {
+ while (base_size > 0) {
FrameBuffer::Luminance lb;
- lb.size=base_size;
-
+ lb.size = base_size;
glGenFramebuffers(1, &lb.fbo);
glBindFramebuffer(GL_FRAMEBUFFER, lb.fbo);
@@ -10670,32 +9983,27 @@ void RasterizerGLES2::_update_framebuffer() {
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, format_luminance, lb.size, lb.size, 0,
- format_luminance_components, format_luminance_type, NULL);
+ format_luminance_components, format_luminance_type, NULL);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, lb.color, 0);
-
+ GL_TEXTURE_2D, lb.color, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
- base_size/=3;
+ base_size /= 3;
DEBUG_TEST_ERROR("Shadow Buffer Init");
- ERR_CONTINUE( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
framebuffer.luminance.push_back(lb);
-
}
}
-
-
-
}
void RasterizerGLES2::set_base_framebuffer(GLuint p_id, Vector2 p_size) {
- base_framebuffer=p_id;
+ base_framebuffer = p_id;
if (p_size.x != 0) {
window_size = p_size;
@@ -10755,11 +10063,9 @@ void RasterizerGLES2::_update_blur_buffer() {
}
#endif
-
bool RasterizerGLES2::_test_depth_shadow_buffer() {
-
- int size=16;
+ int size = 16;
GLuint fbo;
GLuint rbo;
@@ -10784,11 +10090,9 @@ bool RasterizerGLES2::_test_depth_shadow_buffer() {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
-
// We'll use a depth texture to store the depths in the shadow map
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, size, size, 0,
- GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
#ifdef GLEW_ENABLED
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
@@ -10797,17 +10101,15 @@ bool RasterizerGLES2::_test_depth_shadow_buffer() {
// Attach the depth texture to FBO depth attachment point
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, depth, 0);
-
+ GL_TEXTURE_2D, depth, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- glDeleteFramebuffers(1,&fbo);
- glDeleteRenderbuffers(1,&rbo);
- glDeleteTextures(1,&depth);
+ glDeleteFramebuffers(1, &fbo);
+ glDeleteRenderbuffers(1, &rbo);
+ glDeleteTextures(1, &depth);
return status == GL_FRAMEBUFFER_COMPLETE;
-
}
void RasterizerGLES2::init() {
@@ -10818,9 +10120,9 @@ void RasterizerGLES2::init() {
#ifdef GLEW_ENABLED
GLuint res = glewInit();
- ERR_FAIL_COND(res!=GLEW_OK);
+ ERR_FAIL_COND(res != GLEW_OK);
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line(String("GLES2: Using GLEW ") + (const char*) glewGetString(GLEW_VERSION));
+ print_line(String("GLES2: Using GLEW ") + (const char *)glewGetString(GLEW_VERSION));
}
// Godot makes use of functions from ARB_framebuffer_object extension which is not implemented by all drivers.
@@ -10829,10 +10131,10 @@ void RasterizerGLES2::init() {
bool framebuffer_object_is_supported = glewIsSupported("GL_ARB_framebuffer_object");
- if ( !framebuffer_object_is_supported ) {
+ if (!framebuffer_object_is_supported) {
WARN_PRINT("GL_ARB_framebuffer_object not supported by your graphics card.");
- if ( glewIsSupported("GL_EXT_framebuffer_object") ) {
+ if (glewIsSupported("GL_EXT_framebuffer_object")) {
// falling-back to the older EXT function if present
WARN_PRINT("Falling-back to GL_EXT_framebuffer_object.");
@@ -10855,8 +10157,7 @@ void RasterizerGLES2::init() {
glGenerateMipmap = glGenerateMipmapEXT;
framebuffer_object_is_supported = true;
- }
- else {
+ } else {
ERR_PRINT("Framebuffer Object is not supported by your graphics card.");
}
}
@@ -10864,24 +10165,21 @@ void RasterizerGLES2::init() {
// Check for GL 2.1 compatibility, if not bail out
if (!(glewIsSupported("GL_VERSION_2_1") && framebuffer_object_is_supported)) {
ERR_PRINT("Your system's graphic drivers seem not to support OpenGL 2.1 / GLES 2.0, sorry :(\n"
- "Try a drivers update, buy a new GPU or try software rendering on Linux; Godot is now going to terminate.");
+ "Try a drivers update, buy a new GPU or try software rendering on Linux; Godot is now going to terminate.");
OS::get_singleton()->alert("Your system's graphic drivers seem not to support OpenGL 2.1 / GLES 2.0, sorry :(\n"
- "Godot Engine will self-destruct as soon as you acknowledge this error message.",
- "Fatal error: Insufficient OpenGL / GLES drivers");
+ "Godot Engine will self-destruct as soon as you acknowledge this error message.",
+ "Fatal error: Insufficient OpenGL / GLES drivers");
exit(1);
}
#endif
+ scene_pass = 1;
+ if (extensions.size() == 0) {
- scene_pass=1;
-
- if (extensions.size()==0) {
-
- set_extensions( (const char*)glGetString( GL_EXTENSIONS ));
+ set_extensions((const char *)glGetString(GL_EXTENSIONS));
}
-
GLint tmp = 0;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &tmp);
//print_line("GL_MAX_VERTEX_ATTRIBS "+itos(tmp));
@@ -10891,7 +10189,7 @@ void RasterizerGLES2::init() {
glFrontFace(GL_CW);
//glEnable(GL_TEXTURE_2D);
- default_material=create_default_material();
+ default_material = create_default_material();
material_shader.init();
canvas_shader.init();
@@ -10899,10 +10197,10 @@ void RasterizerGLES2::init() {
canvas_shadow_shader.init();
#ifdef GLEW_ENABLED
- material_shader.set_conditional(MaterialShaderGLES2::USE_GLES_OVER_GL,true);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_GLES_OVER_GL,true);
- canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES2::USE_GLES_OVER_GL,true);
- copy_shader.set_conditional(CopyShaderGLES2::USE_GLES_OVER_GL,true);
+ material_shader.set_conditional(MaterialShaderGLES2::USE_GLES_OVER_GL, true);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_GLES_OVER_GL, true);
+ canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES2::USE_GLES_OVER_GL, true);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_GLES_OVER_GL, true);
#endif
#ifdef ANGLE_ENABLED
@@ -10910,113 +10208,108 @@ void RasterizerGLES2::init() {
material_shader.set_conditional(MaterialShaderGLES2::DISABLE_FRONT_FACING, true);
#endif
+ shadow = NULL;
+ shadow_pass = 0;
- shadow=NULL;
- shadow_pass=0;
-
- framebuffer.fbo=0;
- framebuffer.width=0;
- framebuffer.height=0;
+ framebuffer.fbo = 0;
+ framebuffer.width = 0;
+ framebuffer.height = 0;
//framebuffer.buff16=false;
//framebuffer.blur[0].fbo=false;
//framebuffer.blur[1].fbo=false;
- framebuffer.active=false;
-
+ framebuffer.active = false;
//do a single initial clear
- glClearColor(0,0,0,1);
+ glClearColor(0, 0, 0, 1);
//glClearDepth(1.0);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGenTextures(1, &white_tex);
- unsigned char whitetexdata[8*8*3];
- for(int i=0;i<8*8*3;i++) {
- whitetexdata[i]=255;
+ unsigned char whitetexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i++) {
+ whitetexdata[i] = 255;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,white_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,whitetexdata);
+ glBindTexture(GL_TEXTURE_2D, white_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, 0);
#ifdef GLEW_ENABLED
-
- pvr_supported=false;
- etc_supported=false;
- use_depth24 =true;
+ pvr_supported = false;
+ etc_supported = false;
+ use_depth24 = true;
s3tc_supported = true;
atitc_supported = false;
//use_texture_instancing=false;
//use_attribute_instancing=true;
- use_texture_instancing=false;
- use_attribute_instancing=true;
- full_float_fb_supported=true;
- srgb_supported=true;
- latc_supported=true;
- s3tc_srgb_supported=true;
- use_anisotropic_filter=true;
- float_linear_supported=true;
+ use_texture_instancing = false;
+ use_attribute_instancing = true;
+ full_float_fb_supported = true;
+ srgb_supported = true;
+ latc_supported = true;
+ s3tc_srgb_supported = true;
+ use_anisotropic_filter = true;
+ float_linear_supported = true;
GLint vtf;
- glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,&vtf);
+ glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vtf);
float_supported = extensions.has("GL_OES_texture_float") || extensions.has("GL_ARB_texture_float");
- use_hw_skeleton_xform=vtf>0 && float_supported;
+ use_hw_skeleton_xform = vtf > 0 && float_supported;
- read_depth_supported=_test_depth_shadow_buffer();
- use_rgba_shadowmaps=!read_depth_supported;
+ read_depth_supported = _test_depth_shadow_buffer();
+ use_rgba_shadowmaps = !read_depth_supported;
//print_line("read depth support? "+itos(read_depth_supported));
- glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&anisotropic_level);
- anisotropic_level=MIN(anisotropic_level,float(GLOBAL_DEF("rasterizer/anisotropic_filter_level",4.0)));
+ glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropic_level);
+ anisotropic_level = MIN(anisotropic_level, float(GLOBAL_DEF("rasterizer/anisotropic_filter_level", 4.0)));
#ifdef OSX_ENABLED
- use_rgba_shadowmaps=true;
- use_fp16_fb=false;
+ use_rgba_shadowmaps = true;
+ use_fp16_fb = false;
#else
#endif
- use_half_float=true;
+ use_half_float = true;
#else
- for (Set<String>::Element *E=extensions.front();E;E=E->next()) {
+ for (Set<String>::Element *E = extensions.front(); E; E = E->next()) {
print_line(E->get());
}
- read_depth_supported=extensions.has("GL_OES_depth_texture");
- use_rgba_shadowmaps=!read_depth_supported;
- if (shadow_filter>=SHADOW_FILTER_ESM && !extensions.has("GL_EXT_frag_depth")) {
- use_rgba_shadowmaps=true; //no other way, go back to rgba
+ read_depth_supported = extensions.has("GL_OES_depth_texture");
+ use_rgba_shadowmaps = !read_depth_supported;
+ if (shadow_filter >= SHADOW_FILTER_ESM && !extensions.has("GL_EXT_frag_depth")) {
+ use_rgba_shadowmaps = true; //no other way, go back to rgba
}
- pvr_supported=extensions.has("GL_IMG_texture_compression_pvrtc");
- pvr_srgb_supported=extensions.has("GL_EXT_pvrtc_sRGB");
- etc_supported=extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
+ pvr_supported = extensions.has("GL_IMG_texture_compression_pvrtc");
+ pvr_srgb_supported = extensions.has("GL_EXT_pvrtc_sRGB");
+ etc_supported = extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
use_depth24 = extensions.has("GL_OES_depth24");
s3tc_supported = extensions.has("GL_EXT_texture_compression_dxt1") || extensions.has("GL_EXT_texture_compression_s3tc") || extensions.has("WEBGL_compressed_texture_s3tc");
use_half_float = extensions.has("GL_OES_vertex_half_float");
- atitc_supported=extensions.has("GL_AMD_compressed_ATC_texture");
-
+ atitc_supported = extensions.has("GL_AMD_compressed_ATC_texture");
- srgb_supported=extensions.has("GL_EXT_sRGB");
+ srgb_supported = extensions.has("GL_EXT_sRGB");
#ifndef ANGLE_ENABLED
- s3tc_srgb_supported = s3tc_supported && extensions.has("GL_EXT_texture_compression_s3tc");
+ s3tc_srgb_supported = s3tc_supported && extensions.has("GL_EXT_texture_compression_s3tc");
#else
s3tc_srgb_supported = s3tc_supported;
#endif
latc_supported = extensions.has("GL_EXT_texture_compression_latc");
- anisotropic_level=1.0;
- use_anisotropic_filter=extensions.has("GL_EXT_texture_filter_anisotropic");
+ anisotropic_level = 1.0;
+ use_anisotropic_filter = extensions.has("GL_EXT_texture_filter_anisotropic");
if (use_anisotropic_filter) {
- glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&anisotropic_level);
- anisotropic_level=MIN(anisotropic_level,float(GLOBAL_DEF("rasterizer/anisotropic_filter_level",4.0)));
+ glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropic_level);
+ anisotropic_level = MIN(anisotropic_level, float(GLOBAL_DEF("rasterizer/anisotropic_filter_level", 4.0)));
}
-
- print_line("S3TC: "+itos(s3tc_supported)+" ATITC: "+itos(atitc_supported));
+ print_line("S3TC: " + itos(s3tc_supported) + " ATITC: " + itos(atitc_supported));
GLint vtf;
- glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,&vtf);
+ glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vtf);
float_supported = extensions.has("GL_OES_texture_float") || extensions.has("GL_ARB_texture_float");
- use_hw_skeleton_xform=vtf>0 && float_supported;
+ use_hw_skeleton_xform = vtf > 0 && float_supported;
float_linear_supported = extensions.has("GL_OES_texture_float_linear");
/*
@@ -11024,41 +10317,36 @@ void RasterizerGLES2::init() {
use_hw_skeleton_xform=false;
*/
GLint mva;
- glGetIntegerv(GL_MAX_VERTEX_ATTRIBS,&mva);
- if (vtf==0 && mva>8) {
+ glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &mva);
+ if (vtf == 0 && mva > 8) {
//tegra 3, mali 400
- use_attribute_instancing=true;
- use_texture_instancing=false;
- } else if (vtf>0 && extensions.has("GL_OES_texture_float")){
+ use_attribute_instancing = true;
+ use_texture_instancing = false;
+ } else if (vtf > 0 && extensions.has("GL_OES_texture_float")) {
//use_texture_instancing=true;
- use_texture_instancing=false; // i don't get it, uniforms are faster.
- use_attribute_instancing=false;
-
-
+ use_texture_instancing = false; // i don't get it, uniforms are faster.
+ use_attribute_instancing = false;
} else {
- use_texture_instancing=false;
- use_attribute_instancing=false;
+ use_texture_instancing = false;
+ use_attribute_instancing = false;
}
if (use_fp16_fb) {
- use_fp16_fb=extensions.has("GL_OES_texture_half_float") && extensions.has("GL_EXT_color_buffer_half_float") && extensions.has("GL_EXT_texture_rg");
+ use_fp16_fb = extensions.has("GL_OES_texture_half_float") && extensions.has("GL_EXT_color_buffer_half_float") && extensions.has("GL_EXT_texture_rg");
}
- full_float_fb_supported=extensions.has("GL_EXT_color_buffer_float");
+ full_float_fb_supported = extensions.has("GL_EXT_color_buffer_float");
-
- //etc_supported=false;
+//etc_supported=false;
#endif
//use_rgba_shadowmaps=true;
-
-
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units);
- glGetIntegerv(GL_MAX_TEXTURE_SIZE,&max_texture_size);
+ glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
//read_depth_supported=false;
canvas_shadow_blur = canvas_light_shadow_buffer_create(max_texture_size);
@@ -11067,27 +10355,24 @@ void RasterizerGLES2::init() {
//shadowmaps
//don't use a shadowbuffer too big in GLES, this should be the maximum
- int max_shadow_size = GLOBAL_DEF("rasterizer/max_shadow_buffer_size",1024);
- int smsize=max_shadow_size;
- while(smsize>=16) {
+ int max_shadow_size = GLOBAL_DEF("rasterizer/max_shadow_buffer_size", 1024);
+ int smsize = max_shadow_size;
+ while (smsize >= 16) {
ShadowBuffer sb;
- bool s = sb.init(smsize,!use_rgba_shadowmaps);
+ bool s = sb.init(smsize, !use_rgba_shadowmaps);
if (s)
near_shadow_buffers.push_back(sb);
- smsize/=2;
+ smsize /= 2;
}
- blur_shadow_buffer.init(max_shadow_size,!use_rgba_shadowmaps);
-
+ blur_shadow_buffer.init(max_shadow_size, !use_rgba_shadowmaps);
//material_shader
- material_shader.set_conditional(MaterialShaderGLES2::USE_DEPTH_SHADOWS,!use_rgba_shadowmaps);
- canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES2::USE_DEPTH_SHADOWS,!use_rgba_shadowmaps);
-
+ material_shader.set_conditional(MaterialShaderGLES2::USE_DEPTH_SHADOWS, !use_rgba_shadowmaps);
+ canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES2::USE_DEPTH_SHADOWS, !use_rgba_shadowmaps);
}
-
shadow_material = material_create(); //empty with nothing
shadow_mat_ptr = material_owner.get(shadow_material);
@@ -11097,40 +10382,39 @@ void RasterizerGLES2::init() {
shadow_mat_double_sided_ptr->flags[VS::MATERIAL_FLAG_DOUBLE_SIDED] = true;
overdraw_material = create_overdraw_debug_material();
- copy_shader.set_conditional(CopyShaderGLES2::USE_8BIT_HDR,!use_fp16_fb);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_DEPTH_SHADOWS,read_depth_supported);
+ copy_shader.set_conditional(CopyShaderGLES2::USE_8BIT_HDR, !use_fp16_fb);
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_DEPTH_SHADOWS, read_depth_supported);
- canvas_shader.set_conditional(CanvasShaderGLES2::USE_PIXEL_SNAP,GLOBAL_DEF("display/use_2d_pixel_snap",false));
+ canvas_shader.set_conditional(CanvasShaderGLES2::USE_PIXEL_SNAP, GLOBAL_DEF("display/use_2d_pixel_snap", false));
- npo2_textures_available=true;
+ npo2_textures_available = true;
//fragment_lighting=false;
- _rinfo.texture_mem=0;
- current_env=NULL;
- current_rt=NULL;
- current_vd=NULL;
- current_debug=VS::SCENARIO_DEBUG_DISABLED;
- camera_ortho=false;
-
- glGenBuffers(1,&gui_quad_buffer);
- glBindBuffer(GL_ARRAY_BUFFER,gui_quad_buffer);
+ _rinfo.texture_mem = 0;
+ current_env = NULL;
+ current_rt = NULL;
+ current_vd = NULL;
+ current_debug = VS::SCENARIO_DEBUG_DISABLED;
+ camera_ortho = false;
+
+ glGenBuffers(1, &gui_quad_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, gui_quad_buffer);
#ifdef GLES_NO_CLIENT_ARRAYS //WebGL specific implementation.
- glBufferData(GL_ARRAY_BUFFER, 8 * MAX_POLYGON_VERTICES,NULL,GL_DYNAMIC_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, 8 * MAX_POLYGON_VERTICES, NULL, GL_DYNAMIC_DRAW);
#else
- glBufferData(GL_ARRAY_BUFFER,128,NULL,GL_DYNAMIC_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, 128, NULL, GL_DYNAMIC_DRAW);
#endif
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
-
-#ifdef GLES_NO_CLIENT_ARRAYS //webgl indices buffer
- glGenBuffers(1, &indices_buffer);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER, 16*1024, NULL, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);// unbind
+#ifdef GLES_NO_CLIENT_ARRAYS //webgl indices buffer
+ glGenBuffers(1, &indices_buffer);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, 16 * 1024, NULL, GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // unbind
#endif
- shader_time_rollback = GLOBAL_DEF("rasterizer/shader_time_rollback",300);
+ shader_time_rollback = GLOBAL_DEF("rasterizer/shader_time_rollback", 300);
- using_canvas_bg=false;
+ using_canvas_bg = false;
_update_framebuffer();
DEBUG_TEST_ERROR("Initializing");
}
@@ -11141,12 +10425,12 @@ void RasterizerGLES2::finish() {
free(shadow_material);
free(shadow_material_double_sided);
free(canvas_shadow_blur);
- free( overdraw_material );
+ free(overdraw_material);
}
int RasterizerGLES2::get_render_info(VS::RenderInfo p_info) {
- switch(p_info) {
+ switch (p_info) {
case VS::INFO_OBJECTS_IN_FRAME: {
@@ -11178,7 +10462,7 @@ int RasterizerGLES2::get_render_info(VS::RenderInfo p_info) {
} break;
case VS::INFO_VIDEO_MEM_USED: {
- return get_render_info(VS::INFO_TEXTURE_MEM_USED)+get_render_info(VS::INFO_VERTEX_MEM_USED);
+ return get_render_info(VS::INFO_TEXTURE_MEM_USED) + get_render_info(VS::INFO_VERTEX_MEM_USED);
} break;
case VS::INFO_TEXTURE_MEM_USED: {
@@ -11195,8 +10479,8 @@ int RasterizerGLES2::get_render_info(VS::RenderInfo p_info) {
void RasterizerGLES2::set_extensions(const char *p_strings) {
- Vector<String> strings = String(p_strings).split(" ",false);
- for(int i=0;i<strings.size();i++) {
+ Vector<String> strings = String(p_strings).split(" ", false);
+ for (int i = 0; i < strings.size(); i++) {
extensions.insert(strings[i]);
//print_line(strings[i]);
@@ -11210,96 +10494,88 @@ bool RasterizerGLES2::needs_to_draw_next_frame() const {
bool RasterizerGLES2::has_feature(VS::Features p_feature) const {
- switch( p_feature) {
+ switch (p_feature) {
case VS::FEATURE_SHADERS: return true;
case VS::FEATURE_NEEDS_RELOAD_HOOK: return use_reload_hooks;
default: return false;
}
}
-
void RasterizerGLES2::reload_vram() {
-
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glFrontFace(GL_CW);
-
-
//do a single initial clear
- glClearColor(0,0,0,1);
+ glClearColor(0, 0, 0, 1);
//glClearDepth(1.0);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
-
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGenTextures(1, &white_tex);
- unsigned char whitetexdata[8*8*3];
- for(int i=0;i<8*8*3;i++) {
- whitetexdata[i]=255;
+ unsigned char whitetexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i++) {
+ whitetexdata[i] = 255;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,white_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,whitetexdata);
+ glBindTexture(GL_TEXTURE_2D, white_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
-
-
+ glBindTexture(GL_TEXTURE_2D, 0);
List<RID> textures;
texture_owner.get_owned_list(&textures);
- keep_copies=false;
- for(List<RID>::Element *E=textures.front();E;E=E->next()) {
+ keep_copies = false;
+ for (List<RID>::Element *E = textures.front(); E; E = E->next()) {
RID tid = E->get();
- Texture *t=texture_owner.get(tid);
+ Texture *t = texture_owner.get(tid);
ERR_CONTINUE(!t);
- t->tex_id=0;
- t->data_size=0;
+ t->tex_id = 0;
+ t->data_size = 0;
glGenTextures(1, &t->tex_id);
- t->active=false;
+ t->active = false;
if (t->render_target)
continue;
- texture_allocate(tid,t->width,t->height,t->format,t->flags);
- bool had_image=false;
- for(int i=0;i<6;i++) {
+ texture_allocate(tid, t->width, t->height, t->format, t->flags);
+ bool had_image = false;
+ for (int i = 0; i < 6; i++) {
if (!t->image[i].empty()) {
- texture_set_data(tid,t->image[i],VS::CubeMapSide(i));
- had_image=true;
+ texture_set_data(tid, t->image[i], VS::CubeMapSide(i));
+ had_image = true;
}
}
if (!had_image && t->reloader) {
Object *rl = ObjectDB::get_instance(t->reloader);
if (rl)
- rl->call(t->reloader_func,tid);
+ rl->call(t->reloader_func, tid);
}
}
- keep_copies=true;
+ keep_copies = true;
List<RID> render_targets;
render_target_owner.get_owned_list(&render_targets);
- for(List<RID>::Element *E=render_targets.front();E;E=E->next()) {
+ for (List<RID>::Element *E = render_targets.front(); E; E = E->next()) {
RenderTarget *rt = render_target_owner.get(E->get());
int w = rt->width;
int h = rt->height;
- rt->width=0;
- rt->height=0;
- render_target_set_size(E->get(),w,h);
+ rt->width = 0;
+ rt->height = 0;
+ render_target_set_size(E->get(), w, h);
}
-
List<RID> meshes;
mesh_owner.get_owned_list(&meshes);
- for(List<RID>::Element *E=meshes.front();E;E=E->next()) {
+ for (List<RID>::Element *E = meshes.front(); E; E = E->next()) {
Mesh *mesh = mesh_owner.get(E->get());
- Vector<Surface*> surfaces =mesh->surfaces;
+ Vector<Surface *> surfaces = mesh->surfaces;
mesh->surfaces.clear();
- for(int i=0;i<surfaces.size();i++) {
- mesh_add_surface(E->get(),surfaces[i]->primitive,surfaces[i]->data,surfaces[i]->morph_data,surfaces[i]->alpha_sort);
- mesh_surface_set_material(E->get(),i,surfaces[i]->material);
+ for (int i = 0; i < surfaces.size(); i++) {
+ mesh_add_surface(E->get(), surfaces[i]->primitive, surfaces[i]->data, surfaces[i]->morph_data, surfaces[i]->alpha_sort);
+ mesh_surface_set_material(E->get(), i, surfaces[i]->material);
if (surfaces[i]->array_local != 0) {
memfree(surfaces[i]->array_local);
@@ -11308,14 +10584,13 @@ void RasterizerGLES2::reload_vram() {
memfree(surfaces[i]->index_array_local);
};
- memdelete( surfaces[i] );
+ memdelete(surfaces[i]);
}
-
}
List<RID> skeletons;
skeleton_owner.get_owned_list(&skeletons);
- for(List<RID>::Element *E=skeletons.front();E;E=E->next()) {
+ for (List<RID>::Element *E = skeletons.front(); E; E = E->next()) {
Skeleton *sk = skeleton_owner.get(E->get());
if (!sk->tex_id)
@@ -11323,15 +10598,15 @@ void RasterizerGLES2::reload_vram() {
Vector<Skeleton::Bone> bones = sk->bones;
sk->bones.clear();
- sk->tex_id=0;
- sk->pixel_size=1.0;
- skeleton_resize(E->get(),bones.size());
- sk->bones=bones;
+ sk->tex_id = 0;
+ sk->pixel_size = 1.0;
+ skeleton_resize(E->get(), bones.size());
+ sk->bones = bones;
}
List<RID> multimeshes;
multimesh_owner.get_owned_list(&multimeshes);
- for(List<RID>::Element *E=multimeshes.front();E;E=E->next()) {
+ for (List<RID>::Element *E = multimeshes.front(); E; E = E->next()) {
MultiMesh *mm = multimesh_owner.get(E->get());
if (!mm->tex_id)
@@ -11340,162 +10615,147 @@ void RasterizerGLES2::reload_vram() {
Vector<MultiMesh::Element> elements = mm->elements;
mm->elements.clear();
- mm->tw=1;
- mm->th=1;
- mm->tex_id=0;
- mm->last_pass=0;
+ mm->tw = 1;
+ mm->th = 1;
+ mm->tex_id = 0;
+ mm->last_pass = 0;
mm->visible = -1;
- multimesh_set_instance_count(E->get(),elements.size());
- mm->elements=elements;
-
+ multimesh_set_instance_count(E->get(), elements.size());
+ mm->elements = elements;
}
+ if (framebuffer.fbo != 0) {
+ framebuffer.fbo = 0;
+ framebuffer.depth = 0;
+ framebuffer.color = 0;
-
- if (framebuffer.fbo!=0) {
-
- framebuffer.fbo=0;
- framebuffer.depth=0;
- framebuffer.color=0;
-
- for(int i=0;i<3;i++) {
- framebuffer.blur[i].fbo=0;
- framebuffer.blur[i].color=0;
+ for (int i = 0; i < 3; i++) {
+ framebuffer.blur[i].fbo = 0;
+ framebuffer.blur[i].color = 0;
}
framebuffer.luminance.clear();
-
}
- for(int i=0;i<near_shadow_buffers.size();i++) {
- near_shadow_buffers[i].init(near_shadow_buffers[i].size,!use_rgba_shadowmaps);
+ for (int i = 0; i < near_shadow_buffers.size(); i++) {
+ near_shadow_buffers[i].init(near_shadow_buffers[i].size, !use_rgba_shadowmaps);
}
- blur_shadow_buffer.init(near_shadow_buffers[0].size,!use_rgba_shadowmaps);
-
-
+ blur_shadow_buffer.init(near_shadow_buffers[0].size, !use_rgba_shadowmaps);
canvas_shader.clear_caches();
material_shader.clear_caches();
blur_shader.clear_caches();
copy_shader.clear_caches();
-
List<RID> shaders;
shader_owner.get_owned_list(&shaders);
- for(List<RID>::Element *E=shaders.front();E;E=E->next()) {
+ for (List<RID>::Element *E = shaders.front(); E; E = E->next()) {
Shader *s = shader_owner.get(E->get());
- s->custom_code_id=0;
- s->version=1;
- s->valid=false;
- shader_set_mode(E->get(),s->mode);
-
+ s->custom_code_id = 0;
+ s->version = 1;
+ s->valid = false;
+ shader_set_mode(E->get(), s->mode);
}
List<RID> materials;
material_owner.get_owned_list(&materials);
- for(List<RID>::Element *E=materials.front();E;E=E->next()) {
-
+ for (List<RID>::Element *E = materials.front(); E; E = E->next()) {
Material *m = material_owner.get(E->get());
RID shader = m->shader;
- m->shader_version=0;
- material_set_shader(E->get(),shader);
-
+ m->shader_version = 0;
+ material_set_shader(E->get(), shader);
}
-
-
-
}
void RasterizerGLES2::set_use_framebuffers(bool p_use) {
- use_framebuffers=p_use;
+ use_framebuffers = p_use;
}
-RasterizerGLES2* RasterizerGLES2::get_singleton() {
+RasterizerGLES2 *RasterizerGLES2::get_singleton() {
return _singleton;
};
-int RasterizerGLES2::RenderList::max_elements=RenderList::DEFAULT_MAX_ELEMENTS;
+int RasterizerGLES2::RenderList::max_elements = RenderList::DEFAULT_MAX_ELEMENTS;
void RasterizerGLES2::set_force_16_bits_fbo(bool p_force) {
- use_16bits_fbo=p_force;
+ use_16bits_fbo = p_force;
}
-RasterizerGLES2::RasterizerGLES2(bool p_compress_arrays,bool p_keep_ram_copy,bool p_default_fragment_lighting,bool p_use_reload_hooks) {
+RasterizerGLES2::RasterizerGLES2(bool p_compress_arrays, bool p_keep_ram_copy, bool p_default_fragment_lighting, bool p_use_reload_hooks) {
_singleton = this;
- shrink_textures_x2=false;
- RenderList::max_elements=GLOBAL_DEF("rasterizer/max_render_elements",(int)RenderList::DEFAULT_MAX_ELEMENTS);
- if (RenderList::max_elements>64000)
- RenderList::max_elements=64000;
- if (RenderList::max_elements<1024)
- RenderList::max_elements=1024;
+ shrink_textures_x2 = false;
+ RenderList::max_elements = GLOBAL_DEF("rasterizer/max_render_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS);
+ if (RenderList::max_elements > 64000)
+ RenderList::max_elements = 64000;
+ if (RenderList::max_elements < 1024)
+ RenderList::max_elements = 1024;
opaque_render_list.init();
alpha_render_list.init();
- skinned_buffer_size = GLOBAL_DEF("rasterizer/skeleton_buffer_size_kb",DEFAULT_SKINNED_BUFFER_SIZE);
- if (skinned_buffer_size<256)
- skinned_buffer_size=256;
- if (skinned_buffer_size>16384)
- skinned_buffer_size=16384;
- skinned_buffer_size*=1024;
- skinned_buffer = memnew_arr( uint8_t, skinned_buffer_size );
-
- keep_copies=p_keep_ram_copy;
- use_reload_hooks=p_use_reload_hooks;
- pack_arrays=p_compress_arrays;
- p_default_fragment_lighting=false;
- fragment_lighting=GLOBAL_DEF("rasterizer/use_fragment_lighting",true);
- read_depth_supported=true; //todo check for extension
- shadow_filter=ShadowFilterTechnique((int)(GLOBAL_DEF("rasterizer/shadow_filter",SHADOW_FILTER_PCF5)));
- GlobalConfig::get_singleton()->set_custom_property_info("rasterizer/shadow_filter",PropertyInfo(Variant::INT,"rasterizer/shadow_filter",PROPERTY_HINT_ENUM,"None,PCF5,PCF13,ESM"));
- use_fp16_fb=bool(GLOBAL_DEF("rasterizer/fp16_framebuffer",true));
- use_shadow_mapping=true;
- use_fast_texture_filter=!bool(GLOBAL_DEF("rasterizer/trilinear_mipmap_filter",true));
- low_memory_2d=bool(GLOBAL_DEF("rasterizer/low_memory_2d_mode",false));
- skel_default.resize(1024*4);
- for(int i=0;i<1024/3;i++) {
-
- float * ptr = skel_default.ptr();
- ptr+=i*4*4;
- ptr[0]=1.0;
- ptr[1]=0.0;
- ptr[2]=0.0;
- ptr[3]=0.0;
-
- ptr[4]=0.0;
- ptr[5]=1.0;
- ptr[6]=0.0;
- ptr[7]=0.0;
-
- ptr[8]=0.0;
- ptr[9]=0.0;
- ptr[10]=1.0;
- ptr[12]=0.0;
- }
-
- base_framebuffer=0;
+ skinned_buffer_size = GLOBAL_DEF("rasterizer/skeleton_buffer_size_kb", DEFAULT_SKINNED_BUFFER_SIZE);
+ if (skinned_buffer_size < 256)
+ skinned_buffer_size = 256;
+ if (skinned_buffer_size > 16384)
+ skinned_buffer_size = 16384;
+ skinned_buffer_size *= 1024;
+ skinned_buffer = memnew_arr(uint8_t, skinned_buffer_size);
+
+ keep_copies = p_keep_ram_copy;
+ use_reload_hooks = p_use_reload_hooks;
+ pack_arrays = p_compress_arrays;
+ p_default_fragment_lighting = false;
+ fragment_lighting = GLOBAL_DEF("rasterizer/use_fragment_lighting", true);
+ read_depth_supported = true; //todo check for extension
+ shadow_filter = ShadowFilterTechnique((int)(GLOBAL_DEF("rasterizer/shadow_filter", SHADOW_FILTER_PCF5)));
+ GlobalConfig::get_singleton()->set_custom_property_info("rasterizer/shadow_filter", PropertyInfo(Variant::INT, "rasterizer/shadow_filter", PROPERTY_HINT_ENUM, "None,PCF5,PCF13,ESM"));
+ use_fp16_fb = bool(GLOBAL_DEF("rasterizer/fp16_framebuffer", true));
+ use_shadow_mapping = true;
+ use_fast_texture_filter = !bool(GLOBAL_DEF("rasterizer/trilinear_mipmap_filter", true));
+ low_memory_2d = bool(GLOBAL_DEF("rasterizer/low_memory_2d_mode", false));
+ skel_default.resize(1024 * 4);
+ for (int i = 0; i < 1024 / 3; i++) {
+
+ float *ptr = skel_default.ptr();
+ ptr += i * 4 * 4;
+ ptr[0] = 1.0;
+ ptr[1] = 0.0;
+ ptr[2] = 0.0;
+ ptr[3] = 0.0;
+
+ ptr[4] = 0.0;
+ ptr[5] = 1.0;
+ ptr[6] = 0.0;
+ ptr[7] = 0.0;
+
+ ptr[8] = 0.0;
+ ptr[9] = 0.0;
+ ptr[10] = 1.0;
+ ptr[12] = 0.0;
+ }
+
+ base_framebuffer = 0;
frame = 0;
- draw_next_frame=false;
- use_framebuffers=true;
- framebuffer.active=false;
- tc0_id_cache=0;
- tc0_idx=0;
- use_16bits_fbo=false;
+ draw_next_frame = false;
+ use_framebuffers = true;
+ framebuffer.active = false;
+ tc0_id_cache = 0;
+ tc0_idx = 0;
+ use_16bits_fbo = false;
};
void RasterizerGLES2::restore_framebuffer() {
glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer);
-
}
RasterizerGLES2::~RasterizerGLES2() {
@@ -11503,5 +10763,4 @@ RasterizerGLES2::~RasterizerGLES2() {
memdelete_arr(skinned_buffer);
};
-
#endif
diff --git a/drivers/gles2/rasterizer_gles2.h b/drivers/gles2/rasterizer_gles2.h
index ddcd97ec4a..81e137dffd 100644
--- a/drivers/gles2/rasterizer_gles2.h
+++ b/drivers/gles2/rasterizer_gles2.h
@@ -35,14 +35,14 @@
#ifdef GLES2_ENABLED
+#include "camera_matrix.h"
#include "image.h"
-#include "rid.h"
-#include "servers/visual_server.h"
#include "list.h"
#include "map.h"
-#include "camera_matrix.h"
-#include "sort.h"
+#include "rid.h"
#include "self_list.h"
+#include "servers/visual_server.h"
+#include "sort.h"
#include "platform_config.h"
#ifndef GLES2_INCLUDE_H
@@ -51,12 +51,12 @@
#include GLES2_INCLUDE_H
#endif
-#include "drivers/gles2/shaders/material.glsl.h"
+#include "drivers/gles2/shader_compiler_gles2.h"
+#include "drivers/gles2/shaders/blur.glsl.h"
#include "drivers/gles2/shaders/canvas.glsl.h"
#include "drivers/gles2/shaders/canvas_shadow.glsl.h"
-#include "drivers/gles2/shaders/blur.glsl.h"
#include "drivers/gles2/shaders/copy.glsl.h"
-#include "drivers/gles2/shader_compiler_gles2.h"
+#include "drivers/gles2/shaders/material.glsl.h"
#include "servers/visual/particle_system_sw.h"
/**
@@ -66,13 +66,12 @@ class RasterizerGLES2 : public Rasterizer {
enum {
- MAX_SCENE_LIGHTS=2048,
- LIGHT_SPOT_BIT=0x80,
+ MAX_SCENE_LIGHTS = 2048,
+ LIGHT_SPOT_BIT = 0x80,
DEFAULT_SKINNED_BUFFER_SIZE = 2048, // 10k vertices
MAX_HW_LIGHTS = 1,
};
-
uint8_t *skinned_buffer;
int skinned_buffer_size;
bool pvr_supported;
@@ -112,7 +111,7 @@ class RasterizerGLES2 : public Rasterizer {
Vector<float> skel_default;
- Image _get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,GLenum& r_gl_internal_format,int &r_gl_components,bool &r_has_alpha_cache,bool &r_compressed);
+ Image _get_gl_image_and_format(const Image &p_image, Image::Format p_format, uint32_t p_flags, GLenum &r_gl_format, GLenum &r_gl_internal_format, int &r_gl_components, bool &r_has_alpha_cache, bool &r_compressed);
struct RenderTarget;
@@ -120,7 +119,7 @@ class RasterizerGLES2 : public Rasterizer {
String path;
uint32_t flags;
- int width,height;
+ int width, height;
int alloc_width, alloc_height;
Image::Format format;
@@ -149,30 +148,30 @@ class RasterizerGLES2 : public Rasterizer {
Texture() {
- ignore_mipmaps=false;
- render_target=NULL;
- flags=width=height=0;
- tex_id=0;
- data_size=0;
- format=Image::FORMAT_L8;
- gl_components_cache=0;
- format_has_alpha=false;
- has_alpha=false;
- active=false;
- disallow_mipmaps=false;
- compressed=false;
- total_data_size=0;
- target=GL_TEXTURE_2D;
- mipmaps=0;
-
- reloader=0;
+ ignore_mipmaps = false;
+ render_target = NULL;
+ flags = width = height = 0;
+ tex_id = 0;
+ data_size = 0;
+ format = Image::FORMAT_L8;
+ gl_components_cache = 0;
+ format_has_alpha = false;
+ has_alpha = false;
+ active = false;
+ disallow_mipmaps = false;
+ compressed = false;
+ total_data_size = 0;
+ target = GL_TEXTURE_2D;
+ mipmaps = 0;
+
+ reloader = 0;
}
~Texture() {
- if (tex_id!=0) {
+ if (tex_id != 0) {
- glDeleteTextures(1,&tex_id);
+ glDeleteTextures(1, &tex_id);
}
}
};
@@ -192,7 +191,6 @@ class RasterizerGLES2 : public Rasterizer {
uint32_t custom_code_id;
uint32_t version;
-
bool valid;
bool has_alpha;
bool can_zpass;
@@ -204,38 +202,37 @@ class RasterizerGLES2 : public Rasterizer {
bool uses_normal;
bool uses_texpixel_size;
- Map<StringName,ShaderLanguage::Uniform> uniforms;
+ Map<StringName, ShaderLanguage::Uniform> uniforms;
StringName first_texture;
- Map<StringName,RID> default_textures;
+ Map<StringName, RID> default_textures;
SelfList<Shader> dirty_list;
- Shader() : dirty_list(this) {
-
- valid=false;
- custom_code_id=0;
- has_alpha=false;
- version=1;
- vertex_line=0;
- fragment_line=0;
- light_line=0;
- can_zpass=true;
- has_texscreen=false;
- has_screen_uv=false;
- writes_vertex=false;
- uses_discard=false;
- uses_time=false;
- uses_normal=false;
+ Shader()
+ : dirty_list(this) {
+
+ valid = false;
+ custom_code_id = 0;
+ has_alpha = false;
+ version = 1;
+ vertex_line = 0;
+ fragment_line = 0;
+ light_line = 0;
+ can_zpass = true;
+ has_texscreen = false;
+ has_screen_uv = false;
+ writes_vertex = false;
+ uses_discard = false;
+ uses_time = false;
+ uses_normal = false;
}
-
-
};
mutable RID_Owner<Shader> shader_owner;
mutable SelfList<Shader>::List _shader_dirty_list;
- _FORCE_INLINE_ void _shader_make_dirty(Shader* p_shader);
- void _update_shader( Shader* p_shader) const;
+ _FORCE_INLINE_ void _shader_make_dirty(Shader *p_shader);
+ void _update_shader(Shader *p_shader) const;
struct Material {
@@ -256,37 +253,33 @@ class RasterizerGLES2 : public Rasterizer {
bool inuse;
bool istexture;
- Variant value;
+ Variant value;
int index;
};
- mutable Map<StringName,UniformData> shader_params;
+ mutable Map<StringName, UniformData> shader_params;
uint64_t last_pass;
-
Material() {
- for(int i=0;i<VS::MATERIAL_FLAG_MAX;i++)
- flags[i]=false;
- flags[VS::MATERIAL_FLAG_VISIBLE]=true;
+ for (int i = 0; i < VS::MATERIAL_FLAG_MAX; i++)
+ flags[i] = false;
+ flags[VS::MATERIAL_FLAG_VISIBLE] = true;
- line_width=1;
- has_alpha=false;
- depth_draw_mode=VS::MATERIAL_DEPTH_DRAW_OPAQUE_ONLY;
- blend_mode=VS::MATERIAL_BLEND_MODE_MIX;
+ line_width = 1;
+ has_alpha = false;
+ depth_draw_mode = VS::MATERIAL_DEPTH_DRAW_OPAQUE_ONLY;
+ blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
last_pass = 0;
- shader_version=0;
- shader_cache=NULL;
-
+ shader_version = 0;
+ shader_cache = NULL;
}
};
_FORCE_INLINE_ void _update_material_shader_params(Material *p_material) const;
mutable RID_Owner<Material> material_owner;
-
-
struct Geometry {
enum Type {
@@ -302,8 +295,11 @@ class RasterizerGLES2 : public Rasterizer {
bool has_alpha;
bool material_owned;
- Geometry() { has_alpha=false; material_owned = false; }
- virtual ~Geometry() {};
+ Geometry() {
+ has_alpha = false;
+ material_owned = false;
+ }
+ virtual ~Geometry(){};
};
struct GeometryOwner {
@@ -317,11 +313,18 @@ class RasterizerGLES2 : public Rasterizer {
struct ArrayData {
- uint32_t ofs,size,datatype,count;
+ uint32_t ofs, size, datatype, count;
bool normalize;
bool bind;
- ArrayData() { ofs=0; size=0; count=0; datatype=0; normalize=0; bind=false;}
+ ArrayData() {
+ ofs = 0;
+ size = 0;
+ count = 0;
+ datatype = 0;
+ normalize = 0;
+ bind = false;
+ }
};
Mesh *mesh;
@@ -347,7 +350,7 @@ class RasterizerGLES2 : public Rasterizer {
uint8_t *array;
};
- MorphTarget* morph_targets_local;
+ MorphTarget *morph_targets_local;
int morph_target_count;
AABB aabb;
@@ -377,64 +380,60 @@ class RasterizerGLES2 : public Rasterizer {
Surface() {
+ array_len = 0;
+ local_stride = 0;
+ morph_format = 0;
+ type = GEOMETRY_SURFACE;
+ primitive = VS::PRIMITIVE_POINTS;
+ index_array_len = 0;
+ vertex_scale = 1.0;
+ uv_scale = 1.0;
+ uv2_scale = 1.0;
- array_len=0;
- local_stride=0;
- morph_format=0;
- type=GEOMETRY_SURFACE;
- primitive=VS::PRIMITIVE_POINTS;
- index_array_len=0;
- vertex_scale=1.0;
- uv_scale=1.0;
- uv2_scale=1.0;
+ alpha_sort = false;
- alpha_sort=false;
-
- format=0;
- stride=0;
- morph_targets_local=0;
- morph_target_count=0;
+ format = 0;
+ stride = 0;
+ morph_targets_local = 0;
+ morph_target_count = 0;
array_local = index_array_local = 0;
vertex_id = index_id = 0;
- active=false;
+ active = false;
//packed=false;
}
~Surface() {
-
}
};
-
struct Mesh {
bool active;
- Vector<Surface*> surfaces;
+ Vector<Surface *> surfaces;
int morph_target_count;
VS::MorphTargetMode morph_target_mode;
AABB custom_aabb;
mutable uint64_t last_pass;
Mesh() {
- morph_target_mode=VS::MORPH_MODE_NORMALIZED;
- morph_target_count=0;
- last_pass=0;
- active=false;
+ morph_target_mode = VS::MORPH_MODE_NORMALIZED;
+ morph_target_count = 0;
+ last_pass = 0;
+ active = false;
}
};
mutable RID_Owner<Mesh> mesh_owner;
- Error _surface_set_arrays(Surface *p_surface, uint8_t *p_mem,uint8_t *p_index_mem,const Array& p_arrays,bool p_main);
-
+ Error _surface_set_arrays(Surface *p_surface, uint8_t *p_mem, uint8_t *p_index_mem, const Array &p_arrays, bool p_main);
struct MultiMesh;
struct MultiMeshSurface : public Geometry {
Surface *surface;
- MultiMeshSurface() { type=GEOMETRY_MULTISURFACE; }
+ MultiMeshSurface() { type = GEOMETRY_MULTISURFACE; }
};
struct MultiMesh : public GeometryOwner {
@@ -444,28 +443,26 @@ class RasterizerGLES2 : public Rasterizer {
float matrix[16];
uint8_t color[4];
Element() {
- matrix[0]=1;
- matrix[1]=0;
- matrix[2]=0;
- matrix[3]=0;
-
- matrix[4]=0;
- matrix[5]=1;
- matrix[6]=0;
- matrix[7]=0;
-
- matrix[8]=0;
- matrix[9]=0;
- matrix[10]=1;
- matrix[11]=0;
-
- matrix[12]=0;
- matrix[13]=0;
- matrix[14]=0;
- matrix[15]=1;
+ matrix[0] = 1;
+ matrix[1] = 0;
+ matrix[2] = 0;
+ matrix[3] = 0;
+
+ matrix[4] = 0;
+ matrix[5] = 1;
+ matrix[6] = 0;
+ matrix[7] = 0;
+
+ matrix[8] = 0;
+ matrix[9] = 0;
+ matrix[10] = 1;
+ matrix[11] = 0;
+
+ matrix[12] = 0;
+ matrix[13] = 0;
+ matrix[14] = 0;
+ matrix[15] = 1;
};
-
-
};
AABB aabb;
@@ -482,12 +479,13 @@ class RasterizerGLES2 : public Rasterizer {
SelfList<MultiMesh> dirty_list;
- MultiMesh() : dirty_list(this) {
+ MultiMesh()
+ : dirty_list(this) {
- tw=1;
- th=1;
- tex_id=0;
- last_pass=0;
+ tw = 1;
+ th = 1;
+ tex_id = 0;
+ last_pass = 0;
visible = -1;
}
};
@@ -514,8 +512,10 @@ class RasterizerGLES2 : public Rasterizer {
int mask;
AABB aabb;
- Immediate() { type=GEOMETRY_IMMEDIATE; building=false;}
-
+ Immediate() {
+ type = GEOMETRY_IMMEDIATE;
+ building = false;
+ }
};
mutable RID_Owner<Immediate> immediate_owner;
@@ -525,8 +525,7 @@ class RasterizerGLES2 : public Rasterizer {
ParticleSystemSW data; // software particle system
Particles() {
- type=GEOMETRY_PARTICLES;
-
+ type = GEOMETRY_PARTICLES;
}
};
@@ -539,7 +538,7 @@ class RasterizerGLES2 : public Rasterizer {
ParticleSystemProcessSW particles_process;
Transform transform;
- ParticlesInstance() { }
+ ParticlesInstance() {}
};
mutable RID_Owner<ParticlesInstance> particles_instance_owner;
@@ -552,58 +551,52 @@ class RasterizerGLES2 : public Rasterizer {
float mtx[4][4]; //used
Bone() {
- for(int i=0;i<4;i++) {
- for(int j=0;j<4;j++) {
-
- mtx[i][j]=(i==j)?1:0;
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
+ mtx[i][j] = (i == j) ? 1 : 0;
}
}
-
}
- _ALWAYS_INLINE_ void transform_add_mul3(const float * p_src, float* r_dst, float p_weight) const {
+ _ALWAYS_INLINE_ void transform_add_mul3(const float *p_src, float *r_dst, float p_weight) const {
- r_dst[0]+=((mtx[0][0]*p_src[0] ) + ( mtx[1][0]*p_src[1] ) + ( mtx[2][0]*p_src[2] ) + mtx[3][0])*p_weight;
- r_dst[1]+=((mtx[0][1]*p_src[0] ) + ( mtx[1][1]*p_src[1] ) + ( mtx[2][1]*p_src[2] ) + mtx[3][1])*p_weight;
- r_dst[2]+=((mtx[0][2]*p_src[0] ) + ( mtx[1][2]*p_src[1] ) + ( mtx[2][2]*p_src[2] ) + mtx[3][2])*p_weight;
+ r_dst[0] += ((mtx[0][0] * p_src[0]) + (mtx[1][0] * p_src[1]) + (mtx[2][0] * p_src[2]) + mtx[3][0]) * p_weight;
+ r_dst[1] += ((mtx[0][1] * p_src[0]) + (mtx[1][1] * p_src[1]) + (mtx[2][1] * p_src[2]) + mtx[3][1]) * p_weight;
+ r_dst[2] += ((mtx[0][2] * p_src[0]) + (mtx[1][2] * p_src[1]) + (mtx[2][2] * p_src[2]) + mtx[3][2]) * p_weight;
}
- _ALWAYS_INLINE_ void transform3_add_mul3(const float * p_src, float* r_dst, float p_weight) const {
+ _ALWAYS_INLINE_ void transform3_add_mul3(const float *p_src, float *r_dst, float p_weight) const {
- r_dst[0]+=((mtx[0][0]*p_src[0] ) + ( mtx[1][0]*p_src[1] ) + ( mtx[2][0]*p_src[2] ) )*p_weight;
- r_dst[1]+=((mtx[0][1]*p_src[0] ) + ( mtx[1][1]*p_src[1] ) + ( mtx[2][1]*p_src[2] ) )*p_weight;
- r_dst[2]+=((mtx[0][2]*p_src[0] ) + ( mtx[1][2]*p_src[1] ) + ( mtx[2][2]*p_src[2] ) )*p_weight;
+ r_dst[0] += ((mtx[0][0] * p_src[0]) + (mtx[1][0] * p_src[1]) + (mtx[2][0] * p_src[2])) * p_weight;
+ r_dst[1] += ((mtx[0][1] * p_src[0]) + (mtx[1][1] * p_src[1]) + (mtx[2][1] * p_src[2])) * p_weight;
+ r_dst[2] += ((mtx[0][2] * p_src[0]) + (mtx[1][2] * p_src[1]) + (mtx[2][2] * p_src[2])) * p_weight;
}
- _ALWAYS_INLINE_ AABB transform_aabb(const AABB& p_aabb) const {
-
- float vertices[8][3]={
- {p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z},
- {p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z},
- {p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z},
- {p_aabb.pos.x+p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z},
- {p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z+p_aabb.size.z},
- {p_aabb.pos.x, p_aabb.pos.y+p_aabb.size.y, p_aabb.pos.z},
- {p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z+p_aabb.size.z},
- {p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z}
+ _ALWAYS_INLINE_ AABB transform_aabb(const AABB &p_aabb) const {
+
+ float vertices[8][3] = {
+ { p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z },
+ { p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z },
+ { p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z },
+ { p_aabb.pos.x + p_aabb.size.x, p_aabb.pos.y, p_aabb.pos.z },
+ { p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z + p_aabb.size.z },
+ { p_aabb.pos.x, p_aabb.pos.y + p_aabb.size.y, p_aabb.pos.z },
+ { p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z + p_aabb.size.z },
+ { p_aabb.pos.x, p_aabb.pos.y, p_aabb.pos.z }
};
-
AABB ret;
-
-
- for (int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
Vector3 xv(
- ((mtx[0][0]*vertices[i][0] ) + ( mtx[1][0]*vertices[i][1] ) + ( mtx[2][0]*vertices[i][2] ) + mtx[3][0] ),
- ((mtx[0][1]*vertices[i][0] ) + ( mtx[1][1]*vertices[i][1] ) + ( mtx[2][1]*vertices[i][2] ) + mtx[3][1] ),
- ((mtx[0][2]*vertices[i][0] ) + ( mtx[1][2]*vertices[i][1] ) + ( mtx[2][2]*vertices[i][2] ) + mtx[3][2] )
- );
+ ((mtx[0][0] * vertices[i][0]) + (mtx[1][0] * vertices[i][1]) + (mtx[2][0] * vertices[i][2]) + mtx[3][0]),
+ ((mtx[0][1] * vertices[i][0]) + (mtx[1][1] * vertices[i][1]) + (mtx[2][1] * vertices[i][2]) + mtx[3][1]),
+ ((mtx[0][2] * vertices[i][0]) + (mtx[1][2] * vertices[i][1]) + (mtx[2][2] * vertices[i][2]) + mtx[3][2]));
- if (i==0)
- ret.pos=xv;
+ if (i == 0)
+ ret.pos = xv;
else
ret.expand_to(xv);
}
@@ -618,16 +611,18 @@ class RasterizerGLES2 : public Rasterizer {
SelfList<Skeleton> dirty_list;
- Skeleton() : dirty_list(this) { tex_id=0; pixel_size=1.0; }
-
+ Skeleton()
+ : dirty_list(this) {
+ tex_id = 0;
+ pixel_size = 1.0;
+ }
};
mutable RID_Owner<Skeleton> skeleton_owner;
mutable SelfList<Skeleton>::List _skeleton_dirty_list;
-
- template<bool USE_NORMAL, bool USE_TANGENT,bool INPLACE>
- void _skeleton_xform(const uint8_t * p_src_array, int p_src_stride, uint8_t * p_dst_array, int p_dst_stride, int p_elements,const uint8_t *p_src_bones, const uint8_t *p_src_weights, const Skeleton::Bone *p_bone_xforms);
+ template <bool USE_NORMAL, bool USE_TANGENT, bool INPLACE>
+ void _skeleton_xform(const uint8_t *p_src_array, int p_src_stride, uint8_t *p_dst_array, int p_dst_stride, int p_elements, const uint8_t *p_src_bones, const uint8_t *p_src_weights, const Skeleton::Bone *p_bone_xforms);
struct Light {
@@ -642,36 +637,33 @@ class RasterizerGLES2 : public Rasterizer {
VS::LightDirectionalShadowMode directional_shadow_mode;
float directional_shadow_param[3];
-
Light() {
- vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]=1;
- vars[VS::LIGHT_PARAM_SPOT_ANGLE]=45;
- vars[VS::LIGHT_PARAM_ATTENUATION]=1.0;
- vars[VS::LIGHT_PARAM_ENERGY]=1.0;
- vars[VS::LIGHT_PARAM_RADIUS]=1.0;
- vars[VS::LIGHT_PARAM_SHADOW_DARKENING]=0.0;
- vars[VS::LIGHT_PARAM_SHADOW_Z_OFFSET]=0.2;
- vars[VS::LIGHT_PARAM_SHADOW_Z_SLOPE_SCALE]=1.4;
- vars[VS::LIGHT_PARAM_SHADOW_ESM_MULTIPLIER]=60.0;
- vars[VS::LIGHT_PARAM_SHADOW_BLUR_PASSES]=1;
- colors[VS::LIGHT_COLOR_DIFFUSE]=Color(1,1,1);
- colors[VS::LIGHT_COLOR_SPECULAR]=Color(1,1,1);
- shadow_enabled=false;
- volumetric_enabled=false;
-
- directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_SPLIT_WEIGHT]=0.5;
- directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_MAX_DISTANCE]=0;
- directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_ZOFFSET_SCALE]=2.0;
- omni_shadow_mode=VS::LIGHT_OMNI_SHADOW_DEFAULT;
- directional_shadow_mode=VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL;
+ vars[VS::LIGHT_PARAM_SPOT_ATTENUATION] = 1;
+ vars[VS::LIGHT_PARAM_SPOT_ANGLE] = 45;
+ vars[VS::LIGHT_PARAM_ATTENUATION] = 1.0;
+ vars[VS::LIGHT_PARAM_ENERGY] = 1.0;
+ vars[VS::LIGHT_PARAM_RADIUS] = 1.0;
+ vars[VS::LIGHT_PARAM_SHADOW_DARKENING] = 0.0;
+ vars[VS::LIGHT_PARAM_SHADOW_Z_OFFSET] = 0.2;
+ vars[VS::LIGHT_PARAM_SHADOW_Z_SLOPE_SCALE] = 1.4;
+ vars[VS::LIGHT_PARAM_SHADOW_ESM_MULTIPLIER] = 60.0;
+ vars[VS::LIGHT_PARAM_SHADOW_BLUR_PASSES] = 1;
+ colors[VS::LIGHT_COLOR_DIFFUSE] = Color(1, 1, 1);
+ colors[VS::LIGHT_COLOR_SPECULAR] = Color(1, 1, 1);
+ shadow_enabled = false;
+ volumetric_enabled = false;
+
+ directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_SPLIT_WEIGHT] = 0.5;
+ directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_MAX_DISTANCE] = 0;
+ directional_shadow_param[VS::LIGHT_DIRECTIONAL_SHADOW_PARAM_PSSM_ZOFFSET_SCALE] = 2.0;
+ omni_shadow_mode = VS::LIGHT_OMNI_SHADOW_DEFAULT;
+ directional_shadow_mode = VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL;
}
};
-
struct Environment {
-
VS::EnvironmentBG bg_mode;
Variant bg_param[VS::ENV_BG_PARAM_MAX];
bool fx_enabled[VS::ENV_FX_MAX];
@@ -679,54 +671,51 @@ class RasterizerGLES2 : public Rasterizer {
Environment() {
- bg_mode=VS::ENV_BG_DEFAULT_COLOR;
- bg_param[VS::ENV_BG_PARAM_COLOR]=Color(0,0,0);
- bg_param[VS::ENV_BG_PARAM_TEXTURE]=RID();
- bg_param[VS::ENV_BG_PARAM_CUBEMAP]=RID();
- bg_param[VS::ENV_BG_PARAM_ENERGY]=1.0;
- bg_param[VS::ENV_BG_PARAM_SCALE]=1.0;
- bg_param[VS::ENV_BG_PARAM_GLOW]=0.0;
- bg_param[VS::ENV_BG_PARAM_CANVAS_MAX_LAYER]=0;
-
- for(int i=0;i<VS::ENV_FX_MAX;i++)
- fx_enabled[i]=false;
-
- fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_PASSES]=1;
- fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_SCALE]=1.0;
- fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_STRENGTH]=1.0;
- fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_BLEND_MODE]=0;
- fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM]=0.0;
- fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM_TRESHOLD]=0.5;
- fx_param[VS::ENV_FX_PARAM_DOF_BLUR_PASSES]=1;
- fx_param[VS::ENV_FX_PARAM_DOF_BLUR_BEGIN]=100.0;
- fx_param[VS::ENV_FX_PARAM_DOF_BLUR_RANGE]=10.0;
- fx_param[VS::ENV_FX_PARAM_HDR_TONEMAPPER]=VS::ENV_FX_HDR_TONE_MAPPER_LINEAR;
- fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE]=0.4;
- fx_param[VS::ENV_FX_PARAM_HDR_WHITE]=1.0;
- fx_param[VS::ENV_FX_PARAM_HDR_GLOW_TRESHOLD]=0.95;
- fx_param[VS::ENV_FX_PARAM_HDR_GLOW_SCALE]=0.2;
- fx_param[VS::ENV_FX_PARAM_HDR_MIN_LUMINANCE]=0.4;
- fx_param[VS::ENV_FX_PARAM_HDR_MAX_LUMINANCE]=8.0;
- fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE_ADJUST_SPEED]=0.5;
- fx_param[VS::ENV_FX_PARAM_FOG_BEGIN]=100.0;
- fx_param[VS::ENV_FX_PARAM_FOG_ATTENUATION]=1.0;
- fx_param[VS::ENV_FX_PARAM_FOG_BEGIN_COLOR]=Color(0,0,0);
- fx_param[VS::ENV_FX_PARAM_FOG_END_COLOR]=Color(0,0,0);
- fx_param[VS::ENV_FX_PARAM_FOG_BG]=true;
- fx_param[VS::ENV_FX_PARAM_BCS_BRIGHTNESS]=1.0;
- fx_param[VS::ENV_FX_PARAM_BCS_CONTRAST]=1.0;
- fx_param[VS::ENV_FX_PARAM_BCS_SATURATION]=1.0;
-
+ bg_mode = VS::ENV_BG_DEFAULT_COLOR;
+ bg_param[VS::ENV_BG_PARAM_COLOR] = Color(0, 0, 0);
+ bg_param[VS::ENV_BG_PARAM_TEXTURE] = RID();
+ bg_param[VS::ENV_BG_PARAM_CUBEMAP] = RID();
+ bg_param[VS::ENV_BG_PARAM_ENERGY] = 1.0;
+ bg_param[VS::ENV_BG_PARAM_SCALE] = 1.0;
+ bg_param[VS::ENV_BG_PARAM_GLOW] = 0.0;
+ bg_param[VS::ENV_BG_PARAM_CANVAS_MAX_LAYER] = 0;
+
+ for (int i = 0; i < VS::ENV_FX_MAX; i++)
+ fx_enabled[i] = false;
+
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_PASSES] = 1;
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_SCALE] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_STRENGTH] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_BLEND_MODE] = 0;
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM] = 0.0;
+ fx_param[VS::ENV_FX_PARAM_GLOW_BLOOM_TRESHOLD] = 0.5;
+ fx_param[VS::ENV_FX_PARAM_DOF_BLUR_PASSES] = 1;
+ fx_param[VS::ENV_FX_PARAM_DOF_BLUR_BEGIN] = 100.0;
+ fx_param[VS::ENV_FX_PARAM_DOF_BLUR_RANGE] = 10.0;
+ fx_param[VS::ENV_FX_PARAM_HDR_TONEMAPPER] = VS::ENV_FX_HDR_TONE_MAPPER_LINEAR;
+ fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE] = 0.4;
+ fx_param[VS::ENV_FX_PARAM_HDR_WHITE] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_HDR_GLOW_TRESHOLD] = 0.95;
+ fx_param[VS::ENV_FX_PARAM_HDR_GLOW_SCALE] = 0.2;
+ fx_param[VS::ENV_FX_PARAM_HDR_MIN_LUMINANCE] = 0.4;
+ fx_param[VS::ENV_FX_PARAM_HDR_MAX_LUMINANCE] = 8.0;
+ fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE_ADJUST_SPEED] = 0.5;
+ fx_param[VS::ENV_FX_PARAM_FOG_BEGIN] = 100.0;
+ fx_param[VS::ENV_FX_PARAM_FOG_ATTENUATION] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_FOG_BEGIN_COLOR] = Color(0, 0, 0);
+ fx_param[VS::ENV_FX_PARAM_FOG_END_COLOR] = Color(0, 0, 0);
+ fx_param[VS::ENV_FX_PARAM_FOG_BG] = true;
+ fx_param[VS::ENV_FX_PARAM_BCS_BRIGHTNESS] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_BCS_CONTRAST] = 1.0;
+ fx_param[VS::ENV_FX_PARAM_BCS_SATURATION] = 1.0;
}
-
};
mutable RID_Owner<Environment> environment_owner;
-
struct SampledLight {
- int w,h;
+ int w, h;
GLuint texture;
float multiplier;
bool is_float;
@@ -734,14 +723,16 @@ class RasterizerGLES2 : public Rasterizer {
mutable RID_Owner<SampledLight> sampled_light_owner;
-
struct ViewportData {
//1x1 fbo+texture for storing previous HDR value
GLuint lum_fbo;
GLuint lum_color;
- ViewportData() { lum_fbo=0; lum_color=0; }
+ ViewportData() {
+ lum_fbo = 0;
+ lum_color = 0;
+ }
};
mutable RID_Owner<ViewportData> viewport_data_owner;
@@ -753,15 +744,12 @@ class RasterizerGLES2 : public Rasterizer {
GLuint fbo;
GLuint color;
GLuint depth;
- int width,height;
+ int width, height;
uint64_t last_pass;
-
};
mutable RID_Owner<RenderTarget> render_target_owner;
-
-
struct ShadowBuffer;
struct LightInstance {
@@ -795,9 +783,7 @@ class RasterizerGLES2 : public Rasterizer {
CameraMatrix shadow_projection[4];
float shadow_split[4];
-
-
- ShadowBuffer* near_shadow_buffer;
+ ShadowBuffer *near_shadow_buffer;
void clear_shadow_buffers() {
@@ -807,13 +793,17 @@ class RasterizerGLES2 : public Rasterizer {
void clear_near_shadow_buffers() {
if (near_shadow_buffer) {
- near_shadow_buffer->owner=NULL;
- near_shadow_buffer=NULL;
+ near_shadow_buffer->owner = NULL;
+ near_shadow_buffer = NULL;
}
}
- LightInstance() { shadow_pass=0; last_pass=0; sort_key=0; near_shadow_buffer=NULL;}
-
+ LightInstance() {
+ shadow_pass = 0;
+ last_pass = 0;
+ sort_key = 0;
+ near_shadow_buffer = NULL;
+ }
};
mutable RID_Owner<Light> light_owner;
mutable RID_Owner<LightInstance> light_instance_owner;
@@ -841,22 +831,19 @@ class RasterizerGLES2 : public Rasterizer {
GLuint gui_quad_buffer;
GLuint indices_buffer;
-
-
struct RenderList {
enum {
- DEFAULT_MAX_ELEMENTS=4096,
- MAX_LIGHTS=4,
- SORT_FLAG_SKELETON=1,
- SORT_FLAG_INSTANCING=2,
+ DEFAULT_MAX_ELEMENTS = 4096,
+ MAX_LIGHTS = 4,
+ SORT_FLAG_SKELETON = 1,
+ SORT_FLAG_INSTANCING = 2,
};
static int max_elements;
struct Element {
-
float depth;
const InstanceData *instance;
const Skeleton *skeleton;
@@ -885,19 +872,18 @@ class RasterizerGLES2 : public Rasterizer {
};
};
-
Element *_elements;
Element **elements;
int element_count;
void clear() {
- element_count=0;
+ element_count = 0;
}
struct SortZ {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
return A->depth > B->depth;
}
@@ -905,14 +891,13 @@ class RasterizerGLES2 : public Rasterizer {
void sort_z() {
- SortArray<Element*,SortZ> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortZ> sorter;
+ sorter.sort(elements, element_count);
}
-
struct SortMatGeom {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
// TODO move to a single uint64 (one comparison)
if (A->material->shader_cache == B->material->shader_cache) {
if (A->material == B->material) {
@@ -931,19 +916,19 @@ class RasterizerGLES2 : public Rasterizer {
void sort_mat_geom() {
- SortArray<Element*,SortMatGeom> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMatGeom> sorter;
+ sorter.sort(elements, element_count);
}
struct SortMatLight {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->geometry_cmp == B->geometry_cmp) {
if (A->material == B->material) {
- return A->light<B->light;
+ return A->light < B->light;
} else {
return (A->material < B->material);
@@ -957,13 +942,13 @@ class RasterizerGLES2 : public Rasterizer {
void sort_mat_light() {
- SortArray<Element*,SortMatLight> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMatLight> sorter;
+ sorter.sort(elements, element_count);
}
struct SortMatLightType {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->light_type == B->light_type) {
if (A->material->shader_cache == B->material->shader_cache) {
@@ -987,13 +972,13 @@ class RasterizerGLES2 : public Rasterizer {
void sort_mat_light_type() {
- SortArray<Element*,SortMatLightType> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMatLightType> sorter;
+ sorter.sort(elements, element_count);
}
struct SortMatLightTypeFlags {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->sort_key == B->sort_key) {
if (A->material->shader_cache == B->material->shader_cache) {
@@ -1017,29 +1002,27 @@ class RasterizerGLES2 : public Rasterizer {
void sort_mat_light_type_flags() {
- SortArray<Element*,SortMatLightTypeFlags> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMatLightTypeFlags> sorter;
+ sorter.sort(elements, element_count);
}
- _FORCE_INLINE_ Element* add_element() {
+ _FORCE_INLINE_ Element *add_element() {
- if (element_count>=max_elements)
+ if (element_count >= max_elements)
return NULL;
- elements[element_count]=&_elements[element_count];
+ elements[element_count] = &_elements[element_count];
return elements[element_count++];
}
void init() {
element_count = 0;
- elements=memnew_arr(Element*,max_elements);
- _elements=memnew_arr(Element,max_elements);
- for (int i=0;i<max_elements;i++)
- elements[i]=&_elements[i]; // assign elements
-
+ elements = memnew_arr(Element *, max_elements);
+ _elements = memnew_arr(Element, max_elements);
+ for (int i = 0; i < max_elements; i++)
+ elements[i] = &_elements[i]; // assign elements
}
RenderList() {
-
}
~RenderList() {
memdelete_arr(elements);
@@ -1047,14 +1030,11 @@ class RasterizerGLES2 : public Rasterizer {
}
};
-
-
RenderList opaque_render_list;
RenderList alpha_render_list;
RID default_material;
-
CameraMatrix camera_projection;
Transform camera_transform;
Transform camera_transform_inverse;
@@ -1066,12 +1046,10 @@ class RasterizerGLES2 : public Rasterizer {
bool texscreen_copied;
bool texscreen_used;
-
-
Plane camera_plane;
- void _add_geometry( const Geometry* p_geometry, const InstanceData *p_instance, const Geometry *p_geometry_cmp, const GeometryOwner *p_owner,int p_material=-1);
- void _render_list_forward(RenderList *p_render_list,const Transform& p_view_transform,const Transform& p_view_transform_inverse, const CameraMatrix& p_projection,bool p_reverse_cull=false,bool p_fragment_light=false,bool p_alpha_pass=false);
+ void _add_geometry(const Geometry *p_geometry, const InstanceData *p_instance, const Geometry *p_geometry_cmp, const GeometryOwner *p_owner, int p_material = -1);
+ void _render_list_forward(RenderList *p_render_list, const Transform &p_view_transform, const Transform &p_view_transform_inverse, const CameraMatrix &p_projection, bool p_reverse_cull = false, bool p_fragment_light = false, bool p_alpha_pass = false);
//void _setup_light(LightInstance* p_instance, int p_idx);
void _setup_light(uint16_t p_light);
@@ -1080,10 +1058,8 @@ class RasterizerGLES2 : public Rasterizer {
bool _setup_material(const Geometry *p_geometry, const Material *p_material, bool p_no_const_light, bool p_opaque_pass);
void _setup_skeleton(const Skeleton *p_skeleton);
-
- Error _setup_geometry(const Geometry *p_geometry, const Material* p_material,const Skeleton *p_skeleton, const float *p_morphs);
- void _render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton, const GeometryOwner *p_owner,const Transform& p_xform);
-
+ Error _setup_geometry(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton, const float *p_morphs);
+ void _render(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton, const GeometryOwner *p_owner, const Transform &p_xform);
/***********/
/* SHADOWS */
@@ -1103,8 +1079,12 @@ class RasterizerGLES2 : public Rasterizer {
#endif
LightInstance *owner;
- bool init(int p_size,bool p_use_depth);
- ShadowBuffer() { size=0; depth=0; owner=NULL; }
+ bool init(int p_size, bool p_use_depth);
+ ShadowBuffer() {
+ size = 0;
+ depth = 0;
+ owner = NULL;
+ }
};
Vector<ShadowBuffer> near_shadow_buffers;
@@ -1115,30 +1095,25 @@ class RasterizerGLES2 : public Rasterizer {
LightInstance *shadow;
int shadow_pass;
-
float shadow_near_far_split_size_ratio;
- bool _allocate_shadow_buffers(LightInstance *p_instance, Vector<ShadowBuffer>& p_buffers);
- void _debug_draw_shadow(GLuint tex, const Rect2& p_rect);
- void _debug_draw_shadows_type(Vector<ShadowBuffer>& p_shadows,Point2& ofs);
+ bool _allocate_shadow_buffers(LightInstance *p_instance, Vector<ShadowBuffer> &p_buffers);
+ void _debug_draw_shadow(GLuint tex, const Rect2 &p_rect);
+ void _debug_draw_shadows_type(Vector<ShadowBuffer> &p_shadows, Point2 &ofs);
void _debug_shadows();
void _debug_luminances();
void _debug_samplers();
-
-
/***********/
/* FBOs */
/***********/
-
struct FrameBuffer {
GLuint fbo;
GLuint color;
GLuint depth;
-
- int width,height;
+ int width, height;
int scale;
bool active;
@@ -1149,7 +1124,10 @@ class RasterizerGLES2 : public Rasterizer {
GLuint fbo;
GLuint color;
- Blur() { fbo=0; color=0; }
+ Blur() {
+ fbo = 0;
+ color = 0;
+ }
} blur[3];
struct Luminance {
@@ -1158,7 +1136,11 @@ class RasterizerGLES2 : public Rasterizer {
GLuint fbo;
GLuint color;
- Luminance() { fbo=0; color=0; size=0;}
+ Luminance() {
+ fbo = 0;
+ color = 0;
+ size = 0;
+ }
};
Vector<Luminance> luminance;
@@ -1167,7 +1149,7 @@ class RasterizerGLES2 : public Rasterizer {
GLuint sample_color;
FrameBuffer() {
- blur_size=0;
+ blur_size = 0;
}
} framebuffer;
@@ -1176,7 +1158,6 @@ class RasterizerGLES2 : public Rasterizer {
void _process_glow_and_bloom();
//void _update_blur_buffer();
-
/*********/
/* FRAME */
/*********/
@@ -1194,12 +1175,10 @@ class RasterizerGLES2 : public Rasterizer {
} _rinfo;
-
/*******************/
/* CANVAS OCCLUDER */
/*******************/
-
struct CanvasOccluder {
GLuint vertex_id; // 0 means, unconfigured
@@ -1214,7 +1193,6 @@ class RasterizerGLES2 : public Rasterizer {
/* CANVAS LIGHT SHADOW */
/***********************/
-
struct CanvasLightShadow {
int size;
@@ -1225,7 +1203,6 @@ class RasterizerGLES2 : public Rasterizer {
GLuint rgba; //for older devices
GLuint blur;
-
};
RID_Owner<CanvasLightShadow> canvas_light_shadow_owner;
@@ -1239,7 +1216,6 @@ class RasterizerGLES2 : public Rasterizer {
bool current_rt_vflip;
ViewportData *current_vd;
-
GLuint white_tex;
RID canvas_tex;
float canvas_opacity;
@@ -1251,13 +1227,11 @@ class RasterizerGLES2 : public Rasterizer {
CanvasItemMaterial *canvas_last_material;
bool canvas_texscreen_used;
Vector2 normal_flip;
- _FORCE_INLINE_ void _canvas_normal_set_flip(const Vector2& p_flip);
+ _FORCE_INLINE_ void _canvas_normal_set_flip(const Vector2 &p_flip);
-
- _FORCE_INLINE_ Texture* _bind_canvas_texture(const RID& p_texture);
+ _FORCE_INLINE_ Texture *_bind_canvas_texture(const RID &p_texture);
VS::MaterialBlendMode canvas_blend_mode;
-
int _setup_geometry_vinfo;
bool pack_arrays;
@@ -1265,8 +1239,8 @@ class RasterizerGLES2 : public Rasterizer {
bool use_reload_hooks;
bool cull_front;
bool lights_use_shadow;
- _FORCE_INLINE_ void _set_cull(bool p_front,bool p_reverse_cull=false);
- _FORCE_INLINE_ Color _convert_color(const Color& p_color);
+ _FORCE_INLINE_ void _set_cull(bool p_front, bool p_reverse_cull = false);
+ _FORCE_INLINE_ Color _convert_color(const Color &p_color);
void _process_glow_bloom();
void _process_hdr();
@@ -1285,7 +1259,6 @@ class RasterizerGLES2 : public Rasterizer {
RID overdraw_material;
float shader_time_rollback;
-
mutable MaterialShaderGLES2 material_shader;
mutable CanvasShaderGLES2 canvas_shader;
BlurShaderGLES2 blur_shader;
@@ -1294,11 +1267,11 @@ class RasterizerGLES2 : public Rasterizer {
mutable ShaderCompilerGLES2 shader_precompiler;
- void _draw_primitive(int p_points, const Vector3 *p_vertices, const Vector3 *p_normals, const Color* p_colors, const Vector3 *p_uvs,const Plane *p_tangents=NULL,int p_instanced=1);
- _FORCE_INLINE_ void _draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs);
- _FORCE_INLINE_ void _draw_gui_primitive2(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs, const Vector2 *p_uvs2);
- void _draw_textured_quad(const Rect2& p_rect, const Rect2& p_src_region, const Size2& p_tex_size,bool p_h_flip=false, bool p_v_flip=false, bool p_transpose=false );
- void _draw_quad(const Rect2& p_rect);
+ void _draw_primitive(int p_points, const Vector3 *p_vertices, const Vector3 *p_normals, const Color *p_colors, const Vector3 *p_uvs, const Plane *p_tangents = NULL, int p_instanced = 1);
+ _FORCE_INLINE_ void _draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs);
+ _FORCE_INLINE_ void _draw_gui_primitive2(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs, const Vector2 *p_uvs2);
+ void _draw_textured_quad(const Rect2 &p_rect, const Rect2 &p_src_region, const Size2 &p_tex_size, bool p_h_flip = false, bool p_v_flip = false, bool p_transpose = false);
+ void _draw_quad(const Rect2 &p_rect);
void _copy_screen_quad();
void _copy_to_texscreen();
@@ -1313,28 +1286,28 @@ class RasterizerGLES2 : public Rasterizer {
GLuint tc0_id_cache;
GLuint tc0_idx;
- template<bool use_normalmap>
- _FORCE_INLINE_ void _canvas_item_render_commands(CanvasItem *p_item,CanvasItem *current_clip,bool &reclip);
- _FORCE_INLINE_ void _canvas_item_setup_shader_params(CanvasItemMaterial *material,Shader* p_shader);
- _FORCE_INLINE_ void _canvas_item_setup_shader_uniforms(CanvasItemMaterial *material,Shader* p_shader);
-public:
+ template <bool use_normalmap>
+ _FORCE_INLINE_ void _canvas_item_render_commands(CanvasItem *p_item, CanvasItem *current_clip, bool &reclip);
+ _FORCE_INLINE_ void _canvas_item_setup_shader_params(CanvasItemMaterial *material, Shader *p_shader);
+ _FORCE_INLINE_ void _canvas_item_setup_shader_uniforms(CanvasItemMaterial *material, Shader *p_shader);
+public:
/* TEXTURE API */
virtual RID texture_create();
- virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT);
- virtual void texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT);
- virtual Image texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const;
- virtual void texture_set_flags(RID p_texture,uint32_t p_flags);
+ virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = VS::TEXTURE_FLAGS_DEFAULT);
+ virtual void texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT);
+ virtual Image texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) const;
+ virtual void texture_set_flags(RID p_texture, uint32_t p_flags);
virtual uint32_t texture_get_flags(RID p_texture) const;
virtual Image::Format texture_get_format(RID p_texture) const;
virtual uint32_t texture_get_width(RID p_texture) const;
virtual uint32_t texture_get_height(RID p_texture) const;
virtual bool texture_has_alpha(RID p_texture) const;
- virtual void texture_set_size_override(RID p_texture,int p_width, int p_height);
- virtual void texture_set_reload_hook(RID p_texture,ObjectID p_owner,const StringName& p_function) const;
+ virtual void texture_set_size_override(RID p_texture, int p_width, int p_height);
+ virtual void texture_set_reload_hook(RID p_texture, ObjectID p_owner, const StringName &p_function) const;
- virtual void texture_set_path(RID p_texture,const String& p_path);
+ virtual void texture_set_path(RID p_texture, const String &p_path);
virtual String texture_get_path(RID p_texture) const;
virtual void texture_debug_usage(List<VS::TextureInfo> *r_info);
@@ -1344,23 +1317,22 @@ public:
/* SHADER API */
- virtual RID shader_create(VS::ShaderMode p_mode=VS::SHADER_MATERIAL);
+ virtual RID shader_create(VS::ShaderMode p_mode = VS::SHADER_MATERIAL);
- virtual void shader_set_mode(RID p_shader,VS::ShaderMode p_mode);
+ virtual void shader_set_mode(RID p_shader, VS::ShaderMode p_mode);
virtual VS::ShaderMode shader_get_mode(RID p_shader) const;
- virtual void shader_set_code(RID p_shader, const String& p_vertex, const String& p_fragment,const String& p_light,int p_vertex_ofs=0,int p_fragment_ofs=0,int p_light_ofs=0);
+ virtual void shader_set_code(RID p_shader, const String &p_vertex, const String &p_fragment, const String &p_light, int p_vertex_ofs = 0, int p_fragment_ofs = 0, int p_light_ofs = 0);
virtual String shader_get_fragment_code(RID p_shader) const;
virtual String shader_get_vertex_code(RID p_shader) const;
virtual String shader_get_light_code(RID p_shader) const;
-
virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const;
- virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture);
- virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const;
+ virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture);
+ virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const;
- virtual Variant shader_get_default_param(RID p_shader, const StringName& p_name);
+ virtual Variant shader_get_default_param(RID p_shader, const StringName &p_name);
/* COMMON MATERIAL API */
@@ -1369,38 +1341,37 @@ public:
virtual void material_set_shader(RID p_shader_material, RID p_shader);
virtual RID material_get_shader(RID p_shader_material) const;
- virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value);
- virtual Variant material_get_param(RID p_material, const StringName& p_param) const;
+ virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value);
+ virtual Variant material_get_param(RID p_material, const StringName &p_param) const;
- virtual void material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled);
- virtual bool material_get_flag(RID p_material,VS::MaterialFlag p_flag) const;
+ virtual void material_set_flag(RID p_material, VS::MaterialFlag p_flag, bool p_enabled);
+ virtual bool material_get_flag(RID p_material, VS::MaterialFlag p_flag) const;
virtual void material_set_depth_draw_mode(RID p_material, VS::MaterialDepthDrawMode p_mode);
virtual VS::MaterialDepthDrawMode material_get_depth_draw_mode(RID p_material) const;
- virtual void material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode);
+ virtual void material_set_blend_mode(RID p_material, VS::MaterialBlendMode p_mode);
virtual VS::MaterialBlendMode material_get_blend_mode(RID p_material) const;
- virtual void material_set_line_width(RID p_material,float p_line_width);
+ virtual void material_set_line_width(RID p_material, float p_line_width);
virtual float material_get_line_width(RID p_material) const;
-
/* MESH API */
virtual RID mesh_create();
- virtual void mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes=Array(),bool p_alpha_sort=false);
- virtual Array mesh_get_surface_arrays(RID p_mesh,int p_surface) const;
- virtual Array mesh_get_surface_morph_arrays(RID p_mesh,int p_surface) const;
- virtual void mesh_add_custom_surface(RID p_mesh,const Variant& p_dat);
+ virtual void mesh_add_surface(RID p_mesh, VS::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), bool p_alpha_sort = false);
+ virtual Array mesh_get_surface_arrays(RID p_mesh, int p_surface) const;
+ virtual Array mesh_get_surface_morph_arrays(RID p_mesh, int p_surface) const;
+ virtual void mesh_add_custom_surface(RID p_mesh, const Variant &p_dat);
- virtual void mesh_set_morph_target_count(RID p_mesh,int p_amount);
+ virtual void mesh_set_morph_target_count(RID p_mesh, int p_amount);
virtual int mesh_get_morph_target_count(RID p_mesh) const;
- virtual void mesh_set_morph_target_mode(RID p_mesh,VS::MorphTargetMode p_mode);
+ virtual void mesh_set_morph_target_mode(RID p_mesh, VS::MorphTargetMode p_mode);
virtual VS::MorphTargetMode mesh_get_morph_target_mode(RID p_mesh) const;
- virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned=false);
+ virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material, bool p_owned = false);
virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const;
virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const;
@@ -1408,49 +1379,49 @@ public:
virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const;
virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const;
- virtual void mesh_remove_surface(RID p_mesh,int p_index);
+ virtual void mesh_remove_surface(RID p_mesh, int p_index);
virtual int mesh_get_surface_count(RID p_mesh) const;
- virtual AABB mesh_get_aabb(RID p_mesh,RID p_skeleton=RID()) const;
+ virtual AABB mesh_get_aabb(RID p_mesh, RID p_skeleton = RID()) const;
- virtual void mesh_set_custom_aabb(RID p_mesh,const AABB& p_aabb);
+ virtual void mesh_set_custom_aabb(RID p_mesh, const AABB &p_aabb);
virtual AABB mesh_get_custom_aabb(RID p_mesh) const;
/* MULTIMESH API */
virtual RID multimesh_create();
- virtual void multimesh_set_instance_count(RID p_multimesh,int p_count);
+ virtual void multimesh_set_instance_count(RID p_multimesh, int p_count);
virtual int multimesh_get_instance_count(RID p_multimesh) const;
- virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh);
- virtual void multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb);
- virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform);
- virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color);
+ virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh);
+ virtual void multimesh_set_aabb(RID p_multimesh, const AABB &p_aabb);
+ virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform);
+ virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color);
virtual RID multimesh_get_mesh(RID p_multimesh) const;
virtual AABB multimesh_get_aabb(RID p_multimesh) const;
- virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const;
- virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const;
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const;
+ virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const;
- virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible);
+ virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible);
virtual int multimesh_get_visible_instances(RID p_multimesh) const;
/* IMMEDIATE API */
virtual RID immediate_create();
- virtual void immediate_begin(RID p_immediate,VS::PrimitiveType p_rimitive,RID p_texture=RID());
- virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex);
- virtual void immediate_normal(RID p_immediate,const Vector3& p_normal);
- virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent);
- virtual void immediate_color(RID p_immediate,const Color& p_color);
- virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv);
- virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv);
+ virtual void immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture = RID());
+ virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex);
+ virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal);
+ virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent);
+ virtual void immediate_color(RID p_immediate, const Color &p_color);
+ virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv);
+ virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv);
virtual void immediate_end(RID p_immediate);
virtual void immediate_clear(RID p_immediate);
virtual AABB immediate_get_aabb(RID p_immediate) const;
- virtual void immediate_set_material(RID p_immediate,RID p_material);
+ virtual void immediate_set_material(RID p_immediate, RID p_material);
virtual RID immediate_get_material(RID p_immediate) const;
/* PARTICLES API */
@@ -1463,25 +1434,25 @@ public:
virtual void particles_set_emitting(RID p_particles, bool p_emitting);
virtual bool particles_is_emitting(RID p_particles) const;
- virtual void particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility);
+ virtual void particles_set_visibility_aabb(RID p_particles, const AABB &p_visibility);
virtual AABB particles_get_visibility_aabb(RID p_particles) const;
- virtual void particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents);
+ virtual void particles_set_emission_half_extents(RID p_particles, const Vector3 &p_half_extents);
virtual Vector3 particles_get_emission_half_extents(RID p_particles) const;
- virtual void particles_set_emission_base_velocity(RID p_particles, const Vector3& p_base_velocity);
+ virtual void particles_set_emission_base_velocity(RID p_particles, const Vector3 &p_base_velocity);
virtual Vector3 particles_get_emission_base_velocity(RID p_particles) const;
- virtual void particles_set_emission_points(RID p_particles, const DVector<Vector3>& p_points);
+ virtual void particles_set_emission_points(RID p_particles, const DVector<Vector3> &p_points);
virtual DVector<Vector3> particles_get_emission_points(RID p_particles) const;
- virtual void particles_set_gravity_normal(RID p_particles, const Vector3& p_normal);
+ virtual void particles_set_gravity_normal(RID p_particles, const Vector3 &p_normal);
virtual Vector3 particles_get_gravity_normal(RID p_particles) const;
- virtual void particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value);
+ virtual void particles_set_variable(RID p_particles, VS::ParticleVariable p_variable, float p_value);
virtual float particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const;
- virtual void particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness);
+ virtual void particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable, float p_randomness);
virtual float particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const;
virtual void particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos);
@@ -1490,19 +1461,19 @@ public:
virtual void particles_set_color_phases(RID p_particles, int p_phases);
virtual int particles_get_color_phases(RID p_particles) const;
- virtual void particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color);
+ virtual void particles_set_color_phase_color(RID p_particles, int p_phase, const Color &p_color);
virtual Color particles_get_color_phase_color(RID p_particles, int p_phase) const;
virtual void particles_set_attractors(RID p_particles, int p_attractors);
virtual int particles_get_attractors(RID p_particles) const;
- virtual void particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos);
- virtual Vector3 particles_get_attractor_pos(RID p_particles,int p_attractor) const;
+ virtual void particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3 &p_pos);
+ virtual Vector3 particles_get_attractor_pos(RID p_particles, int p_attractor) const;
virtual void particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force);
- virtual float particles_get_attractor_strength(RID p_particles,int p_attractor) const;
+ virtual float particles_get_attractor_strength(RID p_particles, int p_attractor) const;
- virtual void particles_set_material(RID p_particles, RID p_material,bool p_owned=false);
+ virtual void particles_set_material(RID p_particles, RID p_material, bool p_owned = false);
virtual RID particles_get_material(RID p_particles) const;
virtual AABB particles_get_aabb(RID p_particles) const;
@@ -1516,68 +1487,61 @@ public:
/* SKELETON API */
virtual RID skeleton_create();
- virtual void skeleton_resize(RID p_skeleton,int p_bones);
+ virtual void skeleton_resize(RID p_skeleton, int p_bones);
virtual int skeleton_get_bone_count(RID p_skeleton) const;
- virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform);
- virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone);
-
+ virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform);
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone);
/* LIGHT API */
virtual RID light_create(VS::LightType p_type);
virtual VS::LightType light_get_type(RID p_light) const;
- virtual void light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color);
- virtual Color light_get_color(RID p_light,VS::LightColor p_type) const;
+ virtual void light_set_color(RID p_light, VS::LightColor p_type, const Color &p_color);
+ virtual Color light_get_color(RID p_light, VS::LightColor p_type) const;
- virtual void light_set_shadow(RID p_light,bool p_enabled);
+ virtual void light_set_shadow(RID p_light, bool p_enabled);
virtual bool light_has_shadow(RID p_light) const;
- virtual void light_set_volumetric(RID p_light,bool p_enabled);
+ virtual void light_set_volumetric(RID p_light, bool p_enabled);
virtual bool light_is_volumetric(RID p_light) const;
- virtual void light_set_projector(RID p_light,RID p_texture);
+ virtual void light_set_projector(RID p_light, RID p_texture);
virtual RID light_get_projector(RID p_light) const;
virtual void light_set_var(RID p_light, VS::LightParam p_var, float p_value);
virtual float light_get_var(RID p_light, VS::LightParam p_var) const;
- virtual void light_set_operator(RID p_light,VS::LightOp p_op);
+ virtual void light_set_operator(RID p_light, VS::LightOp p_op);
virtual VS::LightOp light_get_operator(RID p_light) const;
- virtual void light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode);
+ virtual void light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode);
virtual VS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light) const;
- virtual void light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode);
+ virtual void light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode);
virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light) const;
- virtual void light_directional_set_shadow_param(RID p_light,VS::LightDirectionalShadowParam p_param, float p_value);
- virtual float light_directional_get_shadow_param(RID p_light,VS::LightDirectionalShadowParam p_param) const;
-
-
+ virtual void light_directional_set_shadow_param(RID p_light, VS::LightDirectionalShadowParam p_param, float p_value);
+ virtual float light_directional_get_shadow_param(RID p_light, VS::LightDirectionalShadowParam p_param) const;
virtual AABB light_get_aabb(RID p_poly) const;
-
virtual RID light_instance_create(RID p_light);
- virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform);
+ virtual void light_instance_set_transform(RID p_light_instance, const Transform &p_transform);
- virtual ShadowType light_instance_get_shadow_type(RID p_light_instance,bool p_far=false) const;
+ virtual ShadowType light_instance_get_shadow_type(RID p_light_instance, bool p_far = false) const;
virtual int light_instance_get_shadow_passes(RID p_light_instance) const;
virtual bool light_instance_get_pssm_shadow_overlap(RID p_light_instance) const;
- virtual void light_instance_set_shadow_transform(RID p_light_instance, int p_index, const CameraMatrix& p_camera, const Transform& p_transform, float p_split_near=0,float p_split_far=0);
- virtual int light_instance_get_shadow_size(RID p_light_instance, int p_index=0) const;
-
+ virtual void light_instance_set_shadow_transform(RID p_light_instance, int p_index, const CameraMatrix &p_camera, const Transform &p_transform, float p_split_near = 0, float p_split_far = 0);
+ virtual int light_instance_get_shadow_size(RID p_light_instance, int p_index = 0) const;
virtual void shadow_clear_near();
virtual bool shadow_allocate_near(RID p_light);
virtual bool shadow_allocate_far(RID p_light);
-
/* SHADOW */
virtual RID particles_instance_create(RID p_particles);
- virtual void particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform);
-
+ virtual void particles_instance_set_transform(RID p_particles_instance, const Transform &p_transform);
/* VIEWPORT */
@@ -1588,33 +1552,30 @@ public:
virtual RID render_target_get_texture(RID p_render_target) const;
virtual bool render_target_renedered_in_frame(RID p_render_target);
-
/* RENDER API */
/* all calls (inside begin/end shadow) are always warranted to be in the following order: */
virtual void begin_frame();
+ virtual void set_viewport(const VS::ViewportRect &p_viewport);
+ virtual void set_render_target(RID p_render_target, bool p_transparent_bg = false, bool p_vflip = false);
+ virtual void clear_viewport(const Color &p_color);
+ virtual void capture_viewport(Image *r_capture);
- virtual void set_viewport(const VS::ViewportRect& p_viewport);
- virtual void set_render_target(RID p_render_target,bool p_transparent_bg=false,bool p_vflip=false);
- virtual void clear_viewport(const Color& p_color);
- virtual void capture_viewport(Image* r_capture);
-
+ virtual void begin_scene(RID p_viewport_data, RID p_env, VS::ScenarioDebugMode p_debug);
- virtual void begin_scene(RID p_viewport_data,RID p_env,VS::ScenarioDebugMode p_debug);
+ virtual void begin_shadow_map(RID p_light_instance, int p_shadow_pass);
- virtual void begin_shadow_map( RID p_light_instance, int p_shadow_pass );
+ virtual void set_camera(const Transform &p_world, const CameraMatrix &p_projection, bool p_ortho_hint);
- virtual void set_camera(const Transform& p_world,const CameraMatrix& p_projection,bool p_ortho_hint);
+ virtual void add_light(RID p_light_instance); ///< all "add_light" calls happen before add_geometry calls
- virtual void add_light( RID p_light_instance ); ///< all "add_light" calls happen before add_geometry calls
+ typedef Map<StringName, Variant> ParamOverrideMap;
- typedef Map<StringName,Variant> ParamOverrideMap;
-
- virtual void add_mesh( const RID& p_mesh, const InstanceData *p_data);
- virtual void add_multimesh( const RID& p_multimesh, const InstanceData *p_data);
- virtual void add_immediate( const RID& p_immediate, const InstanceData *p_data);
- virtual void add_particles( const RID& p_particle_instance, const InstanceData *p_data);
+ virtual void add_mesh(const RID &p_mesh, const InstanceData *p_data);
+ virtual void add_multimesh(const RID &p_multimesh, const InstanceData *p_data);
+ virtual void add_immediate(const RID &p_immediate, const InstanceData *p_data);
+ virtual void add_particles(const RID &p_particle_instance, const InstanceData *p_data);
virtual void end_scene();
virtual void end_shadow_map();
@@ -1630,69 +1591,68 @@ public:
virtual void canvas_set_opacity(float p_opacity);
virtual void canvas_set_blend_mode(VS::MaterialBlendMode p_mode);
- virtual void canvas_begin_rect(const Transform2D& p_transform);
- virtual void canvas_set_clip(bool p_clip, const Rect2& p_rect);
+ virtual void canvas_begin_rect(const Transform2D &p_transform);
+ virtual void canvas_set_clip(bool p_clip, const Rect2 &p_rect);
virtual void canvas_end_rect();
- virtual void canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased);
- virtual void canvas_draw_rect(const Rect2& p_rect, int p_flags, const Rect2& p_source,RID p_texture,const Color& p_modulate);
- virtual void canvas_draw_style_box(const Rect2& p_rect, const Rect2& p_src_region, RID p_texture,const float *p_margins, bool p_draw_center=true,const Color& p_modulate=Color(1,1,1));
- virtual void canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width);
- virtual void canvas_draw_polygon(int p_vertex_count, const int* p_indices, const Vector2* p_vertices, const Vector2* p_uvs, const Color* p_colors,const RID& p_texture,bool p_singlecolor);
- virtual void canvas_set_transform(const Transform2D& p_transform);
+ virtual void canvas_draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased);
+ virtual void canvas_draw_rect(const Rect2 &p_rect, int p_flags, const Rect2 &p_source, RID p_texture, const Color &p_modulate);
+ virtual void canvas_draw_style_box(const Rect2 &p_rect, const Rect2 &p_src_region, RID p_texture, const float *p_margins, bool p_draw_center = true, const Color &p_modulate = Color(1, 1, 1));
+ virtual void canvas_draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width);
+ virtual void canvas_draw_polygon(int p_vertex_count, const int *p_indices, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, const RID &p_texture, bool p_singlecolor);
+ virtual void canvas_set_transform(const Transform2D &p_transform);
- virtual void canvas_render_items(CanvasItem *p_item_list,int p_z,const Color& p_modulate,CanvasLight *p_light);
- virtual void canvas_debug_viewport_shadows(CanvasLight* p_lights_with_shadow);
+ virtual void canvas_render_items(CanvasItem *p_item_list, int p_z, const Color &p_modulate, CanvasLight *p_light);
+ virtual void canvas_debug_viewport_shadows(CanvasLight *p_lights_with_shadow);
/* CANVAS LIGHT SHADOW */
//buffer
virtual RID canvas_light_shadow_buffer_create(int p_width);
- virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, CanvasLightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache);
+ virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, CanvasLightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache);
//occluder
virtual RID canvas_light_occluder_create();
- virtual void canvas_light_occluder_set_polylines(RID p_occluder, const DVector<Vector2>& p_lines);
+ virtual void canvas_light_occluder_set_polylines(RID p_occluder, const DVector<Vector2> &p_lines);
/* ENVIRONMENT */
-
virtual RID environment_create();
- virtual void environment_set_background(RID p_env,VS::EnvironmentBG p_bg);
+ virtual void environment_set_background(RID p_env, VS::EnvironmentBG p_bg);
virtual VS::EnvironmentBG environment_get_background(RID p_env) const;
- virtual void environment_set_background_param(RID p_env,VS::EnvironmentBGParam p_param, const Variant& p_value);
- virtual Variant environment_get_background_param(RID p_env,VS::EnvironmentBGParam p_param) const;
+ virtual void environment_set_background_param(RID p_env, VS::EnvironmentBGParam p_param, const Variant &p_value);
+ virtual Variant environment_get_background_param(RID p_env, VS::EnvironmentBGParam p_param) const;
- virtual void environment_set_enable_fx(RID p_env,VS::EnvironmentFx p_effect,bool p_enabled);
- virtual bool environment_is_fx_enabled(RID p_env,VS::EnvironmentFx p_effect) const;
+ virtual void environment_set_enable_fx(RID p_env, VS::EnvironmentFx p_effect, bool p_enabled);
+ virtual bool environment_is_fx_enabled(RID p_env, VS::EnvironmentFx p_effect) const;
- virtual void environment_fx_set_param(RID p_env,VS::EnvironmentFxParam p_param,const Variant& p_value);
- virtual Variant environment_fx_get_param(RID p_env,VS::EnvironmentFxParam p_param) const;
+ virtual void environment_fx_set_param(RID p_env, VS::EnvironmentFxParam p_param, const Variant &p_value);
+ virtual Variant environment_fx_get_param(RID p_env, VS::EnvironmentFxParam p_param) const;
/* SAMPLED LIGHT */
- virtual RID sampled_light_dp_create(int p_width,int p_height);
+ virtual RID sampled_light_dp_create(int p_width, int p_height);
virtual void sampled_light_dp_update(RID p_sampled_light, const Color *p_data, float p_multiplier);
/*MISC*/
- virtual bool is_texture(const RID& p_rid) const;
- virtual bool is_material(const RID& p_rid) const;
- virtual bool is_mesh(const RID& p_rid) const;
- virtual bool is_immediate(const RID& p_rid) const;
- virtual bool is_multimesh(const RID& p_rid) const;
+ virtual bool is_texture(const RID &p_rid) const;
+ virtual bool is_material(const RID &p_rid) const;
+ virtual bool is_mesh(const RID &p_rid) const;
+ virtual bool is_immediate(const RID &p_rid) const;
+ virtual bool is_multimesh(const RID &p_rid) const;
virtual bool is_particles(const RID &p_beam) const;
- virtual bool is_light(const RID& p_rid) const;
- virtual bool is_light_instance(const RID& p_rid) const;
- virtual bool is_particles_instance(const RID& p_rid) const;
- virtual bool is_skeleton(const RID& p_rid) const;
- virtual bool is_environment(const RID& p_rid) const;
- virtual bool is_shader(const RID& p_rid) const;
+ virtual bool is_light(const RID &p_rid) const;
+ virtual bool is_light_instance(const RID &p_rid) const;
+ virtual bool is_particles_instance(const RID &p_rid) const;
+ virtual bool is_skeleton(const RID &p_rid) const;
+ virtual bool is_environment(const RID &p_rid) const;
+ virtual bool is_shader(const RID &p_rid) const;
- virtual bool is_canvas_light_occluder(const RID& p_rid) const;
+ virtual bool is_canvas_light_occluder(const RID &p_rid) const;
- virtual void free(const RID& p_rid);
+ virtual void free(const RID &p_rid);
virtual void init();
virtual void finish();
@@ -1710,14 +1670,14 @@ public:
void reload_vram();
virtual bool has_feature(VS::Features p_feature) const;
-
+
virtual void restore_framebuffer();
- static RasterizerGLES2* get_singleton();
+ static RasterizerGLES2 *get_singleton();
virtual void set_force_16_bits_fbo(bool p_force);
- RasterizerGLES2(bool p_compress_arrays=false,bool p_keep_ram_copy=true,bool p_default_fragment_lighting=true,bool p_use_reload_hooks=false);
+ RasterizerGLES2(bool p_compress_arrays = false, bool p_keep_ram_copy = true, bool p_default_fragment_lighting = true, bool p_use_reload_hooks = false);
virtual ~RasterizerGLES2();
};
diff --git a/drivers/gles2/rasterizer_instance_gles2.cpp b/drivers/gles2/rasterizer_instance_gles2.cpp
index 647f526147..47bf6d11ff 100644
--- a/drivers/gles2/rasterizer_instance_gles2.cpp
+++ b/drivers/gles2/rasterizer_instance_gles2.cpp
@@ -33,8 +33,7 @@
Rasterizer *instance_RasterizerGLES2() {
- return memnew( RasterizerGLES2 );
+ return memnew(RasterizerGLES2);
}
-
#endif
diff --git a/drivers/gles2/rasterizer_instance_gles2.h b/drivers/gles2/rasterizer_instance_gles2.h
index 51754e0f8a..329e4e2739 100644
--- a/drivers/gles2/rasterizer_instance_gles2.h
+++ b/drivers/gles2/rasterizer_instance_gles2.h
@@ -33,7 +33,6 @@
#ifdef GLES2_ENABLED
-
Rasterizer *instance_RasterizerGLES2();
#endif
diff --git a/drivers/gles2/shader_compiler_gles2.cpp b/drivers/gles2/shader_compiler_gles2.cpp
index a5aa570e33..25decb37a2 100644
--- a/drivers/gles2/shader_compiler_gles2.cpp
+++ b/drivers/gles2/shader_compiler_gles2.cpp
@@ -38,14 +38,13 @@ typedef ShaderLanguage SL;
struct CodeGLSL2 {
String code;
-
};
static String _mktab(int p_level) {
String tb;
- for(int i=0;i<p_level;i++) {
- tb+="\t";
+ for (int i = 0; i < p_level; i++) {
+ tb += "\t";
}
return tb;
@@ -53,7 +52,7 @@ static String _mktab(int p_level) {
static String _typestr(SL::DataType p_type) {
- switch(p_type) {
+ switch (p_type) {
case SL::TYPE_VOID: return "void";
case SL::TYPE_BOOL: return "bool";
@@ -77,7 +76,7 @@ static String _mknum(float p_num) {
static String _opstr(SL::Operator p_op) {
- switch(p_op) {
+ switch (p_op) {
case SL::OP_ASSIGN: return "=";
case SL::OP_ADD: return "+";
case SL::OP_SUB: return "-";
@@ -103,7 +102,6 @@ static String _opstr(SL::Operator p_op) {
return "";
}
-
//#ifdef DEBUG_SHADER_ENABLED
#if 1
#define ENDL "\n"
@@ -111,275 +109,278 @@ static String _opstr(SL::Operator p_op) {
#define ENDL ""
#endif
-
-
-String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node,int p_level,bool p_assign_left) {
+String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node, int p_level, bool p_assign_left) {
String code;
- switch(p_node->type) {
+ switch (p_node->type) {
case SL::Node::TYPE_PROGRAM: {
- SL::ProgramNode *pnode=(SL::ProgramNode*)p_node;
+ SL::ProgramNode *pnode = (SL::ProgramNode *)p_node;
- code+=dump_node_code(pnode->body,p_level);
+ code += dump_node_code(pnode->body, p_level);
} break;
case SL::Node::TYPE_FUNCTION: {
} break;
case SL::Node::TYPE_BLOCK: {
- SL::BlockNode *bnode=(SL::BlockNode*)p_node;
+ SL::BlockNode *bnode = (SL::BlockNode *)p_node;
//variables
- code+="{" ENDL;
- for(Map<StringName,SL::DataType>::Element *E=bnode->variables.front();E;E=E->next()) {
+ code += "{" ENDL;
+ for (Map<StringName, SL::DataType>::Element *E = bnode->variables.front(); E; E = E->next()) {
- code+=_mktab(p_level)+_typestr(E->value())+" "+replace_string(E->key())+";" ENDL;
+ code += _mktab(p_level) + _typestr(E->value()) + " " + replace_string(E->key()) + ";" ENDL;
}
- for(int i=0;i<bnode->statements.size();i++) {
+ for (int i = 0; i < bnode->statements.size(); i++) {
- code+=_mktab(p_level)+dump_node_code(bnode->statements[i],p_level)+";" ENDL;
+ code += _mktab(p_level) + dump_node_code(bnode->statements[i], p_level) + ";" ENDL;
}
- code+="}" ENDL;
+ code += "}" ENDL;
} break;
case SL::Node::TYPE_VARIABLE: {
- SL::VariableNode *vnode=(SL::VariableNode*)p_node;
+ SL::VariableNode *vnode = (SL::VariableNode *)p_node;
- if (type==ShaderLanguage::SHADER_MATERIAL_VERTEX) {
+ if (type == ShaderLanguage::SHADER_MATERIAL_VERTEX) {
- if (vnode->name==vname_vertex && p_assign_left) {
- vertex_code_writes_vertex=true;
+ if (vnode->name == vname_vertex && p_assign_left) {
+ vertex_code_writes_vertex = true;
}
if (vnode->name == vname_position && p_assign_left) {
vertex_code_writes_position = true;
}
- if (vnode->name==vname_color_interp) {
- flags->use_color_interp=true;
+ if (vnode->name == vname_color_interp) {
+ flags->use_color_interp = true;
}
- if (vnode->name==vname_uv_interp) {
- flags->use_uv_interp=true;
+ if (vnode->name == vname_uv_interp) {
+ flags->use_uv_interp = true;
}
- if (vnode->name==vname_uv2_interp) {
- flags->use_uv2_interp=true;
+ if (vnode->name == vname_uv2_interp) {
+ flags->use_uv2_interp = true;
}
- if (vnode->name==vname_var1_interp) {
- flags->use_var1_interp=true;
+ if (vnode->name == vname_var1_interp) {
+ flags->use_var1_interp = true;
}
- if (vnode->name==vname_var2_interp) {
- flags->use_var2_interp=true;
+ if (vnode->name == vname_var2_interp) {
+ flags->use_var2_interp = true;
}
- if (vnode->name==vname_tangent_interp || vnode->name==vname_binormal_interp) {
- flags->use_tangent_interp=true;
+ if (vnode->name == vname_tangent_interp || vnode->name == vname_binormal_interp) {
+ flags->use_tangent_interp = true;
}
-
-
}
+ if (type == ShaderLanguage::SHADER_MATERIAL_FRAGMENT) {
-
- if (type==ShaderLanguage::SHADER_MATERIAL_FRAGMENT) {
-
- if (vnode->name==vname_discard) {
- uses_discard=true;
+ if (vnode->name == vname_discard) {
+ uses_discard = true;
}
- if (vnode->name==vname_normalmap) {
- uses_normalmap=true;
+ if (vnode->name == vname_normalmap) {
+ uses_normalmap = true;
}
- if (vnode->name==vname_screen_uv) {
- uses_screen_uv=true;
+ if (vnode->name == vname_screen_uv) {
+ uses_screen_uv = true;
}
- if (vnode->name==vname_diffuse_alpha && p_assign_left) {
- uses_alpha=true;
+ if (vnode->name == vname_diffuse_alpha && p_assign_left) {
+ uses_alpha = true;
}
- if (vnode->name==vname_color_interp) {
- flags->use_color_interp=true;
+ if (vnode->name == vname_color_interp) {
+ flags->use_color_interp = true;
}
- if (vnode->name==vname_uv_interp) {
- flags->use_uv_interp=true;
+ if (vnode->name == vname_uv_interp) {
+ flags->use_uv_interp = true;
}
- if (vnode->name==vname_uv2_interp) {
- flags->use_uv2_interp=true;
+ if (vnode->name == vname_uv2_interp) {
+ flags->use_uv2_interp = true;
}
- if (vnode->name==vname_var1_interp) {
- flags->use_var1_interp=true;
+ if (vnode->name == vname_var1_interp) {
+ flags->use_var1_interp = true;
}
- if (vnode->name==vname_var2_interp) {
- flags->use_var2_interp=true;
+ if (vnode->name == vname_var2_interp) {
+ flags->use_var2_interp = true;
}
- if (vnode->name==vname_tangent_interp || vnode->name==vname_binormal_interp) {
- flags->use_tangent_interp=true;
+ if (vnode->name == vname_tangent_interp || vnode->name == vname_binormal_interp) {
+ flags->use_tangent_interp = true;
}
-
}
- if (type==ShaderLanguage::SHADER_MATERIAL_LIGHT) {
+ if (type == ShaderLanguage::SHADER_MATERIAL_LIGHT) {
- if (vnode->name==vname_light) {
- uses_light=true;
+ if (vnode->name == vname_light) {
+ uses_light = true;
}
- if (vnode->name==vname_shadow) {
- uses_shadow_color=true;
+ if (vnode->name == vname_shadow) {
+ uses_shadow_color = true;
}
-
}
- if (type==ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX) {
+ if (type == ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX) {
- if (vnode->name==vname_var1_interp) {
- flags->use_var1_interp=true;
+ if (vnode->name == vname_var1_interp) {
+ flags->use_var1_interp = true;
}
- if (vnode->name==vname_var2_interp) {
- flags->use_var2_interp=true;
+ if (vnode->name == vname_var2_interp) {
+ flags->use_var2_interp = true;
}
- if (vnode->name==vname_world_vec) {
- uses_worldvec=true;
+ if (vnode->name == vname_world_vec) {
+ uses_worldvec = true;
}
-
}
+ if (type == ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT) {
- if (type==ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT) {
-
-
- if (vnode->name==vname_texpixel_size) {
- uses_texpixel_size=true;
+ if (vnode->name == vname_texpixel_size) {
+ uses_texpixel_size = true;
}
- if (vnode->name==vname_normal) {
- uses_normal=true;
+ if (vnode->name == vname_normal) {
+ uses_normal = true;
}
- if (vnode->name==vname_normalmap || vnode->name==vname_normalmap_depth) {
- uses_normalmap=true;
- uses_normal=true;
+ if (vnode->name == vname_normalmap || vnode->name == vname_normalmap_depth) {
+ uses_normalmap = true;
+ uses_normal = true;
}
- if (vnode->name==vname_screen_uv) {
- uses_screen_uv=true;
+ if (vnode->name == vname_screen_uv) {
+ uses_screen_uv = true;
}
- if (vnode->name==vname_var1_interp) {
- flags->use_var1_interp=true;
+ if (vnode->name == vname_var1_interp) {
+ flags->use_var1_interp = true;
}
- if (vnode->name==vname_var2_interp) {
- flags->use_var2_interp=true;
+ if (vnode->name == vname_var2_interp) {
+ flags->use_var2_interp = true;
}
}
- if (type==ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT) {
+ if (type == ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT) {
- if (vnode->name==vname_light) {
- uses_light=true;
+ if (vnode->name == vname_light) {
+ uses_light = true;
}
- if (vnode->name==vname_normal) {
- uses_normal=true;
+ if (vnode->name == vname_normal) {
+ uses_normal = true;
}
- if (vnode->name==vname_shadow) {
- uses_shadow_color=true;
+ if (vnode->name == vname_shadow) {
+ uses_shadow_color = true;
}
-
}
- if (vnode->name==vname_time) {
- uses_time=true;
+ if (vnode->name == vname_time) {
+ uses_time = true;
}
- code=replace_string(vnode->name);
+ code = replace_string(vnode->name);
} break;
case SL::Node::TYPE_CONSTANT: {
- SL::ConstantNode *cnode=(SL::ConstantNode*)p_node;
- switch(cnode->datatype) {
-
-
- case SL::TYPE_BOOL: code=cnode->value.operator bool()?"true":"false"; break;
- case SL::TYPE_FLOAT: code=_mknum(cnode->value); break; //force zeros, so GLSL doesn't confuse with integer.
- case SL::TYPE_VEC2: { Vector2 v = cnode->value; code="vec2("+_mknum(v.x)+", "+_mknum(v.y)+")"; } break;
- case SL::TYPE_VEC3: { Vector3 v = cnode->value; code="vec3("+_mknum(v.x)+", "+_mknum(v.y)+", "+_mknum(v.z)+")"; } break;
- case SL::TYPE_VEC4: { Plane v = cnode->value; code="vec4("+_mknum(v.normal.x)+", "+_mknum(v.normal.y)+", "+_mknum(v.normal.z)+", "+_mknum(v.d)+")"; } break;
- case SL::TYPE_MAT2: { Transform2D x = cnode->value; code="mat2( vec2("+_mknum(x[0][0])+", "+_mknum(x[0][1])+"), vec2("+_mknum(x[1][0])+", "+_mknum(x[1][1])+"))"; } break;
- case SL::TYPE_MAT3: { Basis x = cnode->value; code="mat3( vec3("+_mknum(x.get_axis(0).x)+", "+_mknum(x.get_axis(0).y)+", "+_mknum(x.get_axis(0).z)+"), vec3("+_mknum(x.get_axis(1).x)+", "+_mknum(x.get_axis(1).y)+", "+_mknum(x.get_axis(1).z)+"), vec3("+_mknum(x.get_axis(2).x)+", "+_mknum(x.get_axis(2).y)+", "+_mknum(x.get_axis(2).z)+"))"; } break;
- case SL::TYPE_MAT4: { Transform x = cnode->value; code="mat4( vec4("+_mknum(x.basis.get_axis(0).x)+", "+_mknum(x.basis.get_axis(0).y)+", "+_mknum(x.basis.get_axis(0).z)+",0.0), vec4("+_mknum(x.basis.get_axis(1).x)+", "+_mknum(x.basis.get_axis(1).y)+", "+_mknum(x.basis.get_axis(1).z)+",0.0), vec4("+_mknum(x.basis.get_axis(2).x)+", "+_mknum(x.basis.get_axis(2).y)+", "+_mknum(x.basis.get_axis(2).z)+",0.0), vec4("+_mknum(x.origin.x)+", "+_mknum(x.origin.y)+", "+_mknum(x.origin.z)+",1.0))"; } break;
- default: code="<error: "+Variant::get_type_name(cnode->value.get_type())+" ("+itos(cnode->datatype)+">";
+ SL::ConstantNode *cnode = (SL::ConstantNode *)p_node;
+ switch (cnode->datatype) {
+
+ case SL::TYPE_BOOL: code = cnode->value.operator bool() ? "true" : "false"; break;
+ case SL::TYPE_FLOAT:
+ code = _mknum(cnode->value);
+ break; //force zeros, so GLSL doesn't confuse with integer.
+ case SL::TYPE_VEC2: {
+ Vector2 v = cnode->value;
+ code = "vec2(" + _mknum(v.x) + ", " + _mknum(v.y) + ")";
+ } break;
+ case SL::TYPE_VEC3: {
+ Vector3 v = cnode->value;
+ code = "vec3(" + _mknum(v.x) + ", " + _mknum(v.y) + ", " + _mknum(v.z) + ")";
+ } break;
+ case SL::TYPE_VEC4: {
+ Plane v = cnode->value;
+ code = "vec4(" + _mknum(v.normal.x) + ", " + _mknum(v.normal.y) + ", " + _mknum(v.normal.z) + ", " + _mknum(v.d) + ")";
+ } break;
+ case SL::TYPE_MAT2: {
+ Transform2D x = cnode->value;
+ code = "mat2( vec2(" + _mknum(x[0][0]) + ", " + _mknum(x[0][1]) + "), vec2(" + _mknum(x[1][0]) + ", " + _mknum(x[1][1]) + "))";
+ } break;
+ case SL::TYPE_MAT3: {
+ Basis x = cnode->value;
+ code = "mat3( vec3(" + _mknum(x.get_axis(0).x) + ", " + _mknum(x.get_axis(0).y) + ", " + _mknum(x.get_axis(0).z) + "), vec3(" + _mknum(x.get_axis(1).x) + ", " + _mknum(x.get_axis(1).y) + ", " + _mknum(x.get_axis(1).z) + "), vec3(" + _mknum(x.get_axis(2).x) + ", " + _mknum(x.get_axis(2).y) + ", " + _mknum(x.get_axis(2).z) + "))";
+ } break;
+ case SL::TYPE_MAT4: {
+ Transform x = cnode->value;
+ code = "mat4( vec4(" + _mknum(x.basis.get_axis(0).x) + ", " + _mknum(x.basis.get_axis(0).y) + ", " + _mknum(x.basis.get_axis(0).z) + ",0.0), vec4(" + _mknum(x.basis.get_axis(1).x) + ", " + _mknum(x.basis.get_axis(1).y) + ", " + _mknum(x.basis.get_axis(1).z) + ",0.0), vec4(" + _mknum(x.basis.get_axis(2).x) + ", " + _mknum(x.basis.get_axis(2).y) + ", " + _mknum(x.basis.get_axis(2).z) + ",0.0), vec4(" + _mknum(x.origin.x) + ", " + _mknum(x.origin.y) + ", " + _mknum(x.origin.z) + ",1.0))";
+ } break;
+ default: code = "<error: " + Variant::get_type_name(cnode->value.get_type()) + " (" + itos(cnode->datatype) + ">";
}
} break;
case SL::Node::TYPE_OPERATOR: {
- SL::OperatorNode *onode=(SL::OperatorNode*)p_node;
+ SL::OperatorNode *onode = (SL::OperatorNode *)p_node;
-
- switch(onode->op) {
+ switch (onode->op) {
case SL::OP_ASSIGN_MUL: {
+ if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC3 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT4) {
- if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC3 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
-
- String mul_l=dump_node_code(onode->arguments[0],p_level,true);
- String mul_r=dump_node_code(onode->arguments[1],p_level);
- code=mul_l+"=(vec4("+mul_l+",1.0)*("+mul_r+")).xyz";
+ String mul_l = dump_node_code(onode->arguments[0], p_level, true);
+ String mul_r = dump_node_code(onode->arguments[1], p_level);
+ code = mul_l + "=(vec4(" + mul_l + ",1.0)*(" + mul_r + ")).xyz";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC3) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_MAT4 && onode->arguments[1]->get_datatype() == SL::TYPE_VEC3) {
- String mul_l=dump_node_code(onode->arguments[0],p_level,true);
- String mul_r=dump_node_code(onode->arguments[1],p_level);
- code=mul_l+"=(("+mul_l+")*vec4("+mul_r+",1.0)).xyz";
+ String mul_l = dump_node_code(onode->arguments[0], p_level, true);
+ String mul_r = dump_node_code(onode->arguments[1], p_level);
+ code = mul_l + "=((" + mul_l + ")*vec4(" + mul_r + ",1.0)).xyz";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC2 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT4) {
- String mul_l=dump_node_code(onode->arguments[0],p_level,true);
- String mul_r=dump_node_code(onode->arguments[1],p_level);
- code=mul_l+"=(vec4("+mul_l+",0.0,1.0)*("+mul_r+")).xy";
+ String mul_l = dump_node_code(onode->arguments[0], p_level, true);
+ String mul_r = dump_node_code(onode->arguments[1], p_level);
+ code = mul_l + "=(vec4(" + mul_l + ",0.0,1.0)*(" + mul_r + ")).xy";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_MAT4 && onode->arguments[1]->get_datatype() == SL::TYPE_VEC2) {
- String mul_l=dump_node_code(onode->arguments[0],p_level,true);
- String mul_r=dump_node_code(onode->arguments[1],p_level);
- code=mul_l+"=(("+mul_l+")*vec4("+mul_r+",0.0,1.0)).xy";
+ String mul_l = dump_node_code(onode->arguments[0], p_level, true);
+ String mul_r = dump_node_code(onode->arguments[1], p_level);
+ code = mul_l + "=((" + mul_l + ")*vec4(" + mul_r + ",0.0,1.0)).xy";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT3) {
- String mul_l=dump_node_code(onode->arguments[0],p_level,true);
- String mul_r=dump_node_code(onode->arguments[1],p_level);
- code=mul_l+"=(("+mul_l+")*vec3("+mul_r+",1.0)).xy";
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC2 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT3) {
+ String mul_l = dump_node_code(onode->arguments[0], p_level, true);
+ String mul_r = dump_node_code(onode->arguments[1], p_level);
+ code = mul_l + "=((" + mul_l + ")*vec3(" + mul_r + ",1.0)).xy";
break;
}
-
-
};
case SL::OP_ASSIGN:
case SL::OP_ASSIGN_ADD:
case SL::OP_ASSIGN_SUB:
case SL::OP_ASSIGN_DIV:
- code="("+dump_node_code(onode->arguments[0],p_level,true)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")";
+ code = "(" + dump_node_code(onode->arguments[0], p_level, true) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level) + ")";
break;
case SL::OP_MUL:
- if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC3) {
+ if (onode->arguments[0]->get_datatype() == SL::TYPE_MAT4 && onode->arguments[1]->get_datatype() == SL::TYPE_VEC3) {
- code="("+dump_node_code(onode->arguments[0],p_level)+"*vec4("+dump_node_code(onode->arguments[1],p_level)+",1.0)).xyz";
+ code = "(" + dump_node_code(onode->arguments[0], p_level) + "*vec4(" + dump_node_code(onode->arguments[1], p_level) + ",1.0)).xyz";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC3 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC3 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT4) {
- code="(vec4("+dump_node_code(onode->arguments[0],p_level)+",1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xyz";
+ code = "(vec4(" + dump_node_code(onode->arguments[0], p_level) + ",1.0)*" + dump_node_code(onode->arguments[1], p_level) + ").xyz";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT4 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_MAT4 && onode->arguments[1]->get_datatype() == SL::TYPE_VEC2) {
- code="("+dump_node_code(onode->arguments[0],p_level)+"*vec4("+dump_node_code(onode->arguments[1],p_level)+",0.0,1.0)).xy";
+ code = "(" + dump_node_code(onode->arguments[0], p_level) + "*vec4(" + dump_node_code(onode->arguments[1], p_level) + ",0.0,1.0)).xy";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT4) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC2 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT4) {
- code="(vec4("+dump_node_code(onode->arguments[0],p_level)+",0.0,1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xy";
+ code = "(vec4(" + dump_node_code(onode->arguments[0], p_level) + ",0.0,1.0)*" + dump_node_code(onode->arguments[1], p_level) + ").xy";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_MAT3 && onode->arguments[1]->get_datatype()==SL::TYPE_VEC2) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_MAT3 && onode->arguments[1]->get_datatype() == SL::TYPE_VEC2) {
- code="("+dump_node_code(onode->arguments[0],p_level)+"*vec3("+dump_node_code(onode->arguments[1],p_level)+",1.0)).xy";
+ code = "(" + dump_node_code(onode->arguments[0], p_level) + "*vec3(" + dump_node_code(onode->arguments[1], p_level) + ",1.0)).xy";
break;
- } else if (onode->arguments[0]->get_datatype()==SL::TYPE_VEC2 && onode->arguments[1]->get_datatype()==SL::TYPE_MAT3) {
+ } else if (onode->arguments[0]->get_datatype() == SL::TYPE_VEC2 && onode->arguments[1]->get_datatype() == SL::TYPE_MAT3) {
- code="(vec3("+dump_node_code(onode->arguments[0],p_level)+",1.0)*"+dump_node_code(onode->arguments[1],p_level)+").xy";
+ code = "(vec3(" + dump_node_code(onode->arguments[0], p_level) + ",1.0)*" + dump_node_code(onode->arguments[1], p_level) + ").xy";
break;
}
@@ -395,19 +396,18 @@ String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node,int p_level,bool p_a
case SL::OP_CMP_OR:
case SL::OP_CMP_AND:
//handle binary
- code="("+dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")";
+ code = "(" + dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level) + ")";
break;
case SL::OP_NEG:
case SL::OP_NOT:
//handle unary
- code=_opstr(onode->op)+dump_node_code(onode->arguments[0],p_level);
+ code = _opstr(onode->op) + dump_node_code(onode->arguments[0], p_level);
break;
case SL::OP_CONSTRUCT:
case SL::OP_CALL: {
- String callfunc=dump_node_code(onode->arguments[0],p_level);
-
+ String callfunc = dump_node_code(onode->arguments[0], p_level);
- code=callfunc+"(";
+ code = callfunc + "(";
/*if (callfunc=="mat4") {
//fix constructor for mat4
for(int i=1;i<onode->arguments.size();i++) {
@@ -417,78 +417,80 @@ String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node,int p_level,bool p_a
code+="vec4( "+dump_node_code(onode->arguments[i],p_level)+(i==4?",1.0)":",0.0)");
}
- } else*/ if (callfunc=="tex") {
+ } else*/ if (callfunc == "tex") {
- code="texture2D( "+dump_node_code(onode->arguments[1],p_level)+","+dump_node_code(onode->arguments[2],p_level)+")";
+ code = "texture2D( " + dump_node_code(onode->arguments[1], p_level) + "," + dump_node_code(onode->arguments[2], p_level) + ")";
break;
- } else if (callfunc=="texcube") {
+ } else if (callfunc == "texcube") {
- code="(textureCube( "+dump_node_code(onode->arguments[1],p_level)+",("+dump_node_code(onode->arguments[2],p_level)+")).xyz";
+ code = "(textureCube( " + dump_node_code(onode->arguments[1], p_level) + ",(" + dump_node_code(onode->arguments[2], p_level) + ")).xyz";
break;
- } else if (callfunc=="texscreen") {
+ } else if (callfunc == "texscreen") {
//create the call to sample the screen, and clamp it
- uses_texscreen=true;
- code="(texture2D( texscreen_tex, clamp(("+dump_node_code(onode->arguments[1],p_level)+").xy*texscreen_screen_mult,texscreen_screen_clamp.xy,texscreen_screen_clamp.zw))).rgb";
+ uses_texscreen = true;
+ code = "(texture2D( texscreen_tex, clamp((" + dump_node_code(onode->arguments[1], p_level) + ").xy*texscreen_screen_mult,texscreen_screen_clamp.xy,texscreen_screen_clamp.zw))).rgb";
//code="(texture2D( screen_texture, ("+dump_node_code(onode->arguments[1],p_level)+").xy).rgb";
break;
- } else if (callfunc=="texpos") {
+ } else if (callfunc == "texpos") {
//create the call to sample the screen, and clamp it
- uses_texpos=true;
- code="get_texpos("+dump_node_code(onode->arguments[1],p_level)+"";
+ uses_texpos = true;
+ code = "get_texpos(" + dump_node_code(onode->arguments[1], p_level) + "";
//code="get_texpos(gl_ProjectionMatrixInverse * texture2D( depth_texture, clamp(("+dump_node_code(onode->arguments[1],p_level)+").xy,vec2(0.0),vec2(1.0))*gl_LightSource[5].specular.zw+gl_LightSource[5].specular.xy)";
//code="(texture2D( screen_texture, ("+dump_node_code(onode->arguments[1],p_level)+").xy).rgb";
break;
- } else if (custom_h && callfunc=="cosh_custom") {
+ } else if (custom_h && callfunc == "cosh_custom") {
if (!cosh_used) {
- global_code=
- "float cosh_custom(float val)\n"\
- "{\n"\
- " float tmp = exp(val);\n"\
- " float cosH = (tmp + 1.0 / tmp) / 2.0;\n"\
- " return cosH;\n"\
- "}\n"+global_code;
- cosh_used=true;
+ global_code =
+ "float cosh_custom(float val)\n"
+ "{\n"
+ " float tmp = exp(val);\n"
+ " float cosH = (tmp + 1.0 / tmp) / 2.0;\n"
+ " return cosH;\n"
+ "}\n" +
+ global_code;
+ cosh_used = true;
}
- code="cosh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
- } else if (custom_h && callfunc=="sinh_custom") {
+ code = "cosh_custom(" + dump_node_code(onode->arguments[1], p_level) + "";
+ } else if (custom_h && callfunc == "sinh_custom") {
if (!sinh_used) {
- global_code=
- "float sinh_custom(float val)\n"\
- "{\n"\
- " float tmp = exp(val);\n"\
- " float sinH = (tmp - 1.0 / tmp) / 2.0;\n"\
- " return sinH;\n"\
- "}\n"+global_code;
- sinh_used=true;
+ global_code =
+ "float sinh_custom(float val)\n"
+ "{\n"
+ " float tmp = exp(val);\n"
+ " float sinH = (tmp - 1.0 / tmp) / 2.0;\n"
+ " return sinH;\n"
+ "}\n" +
+ global_code;
+ sinh_used = true;
}
- code="sinh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
- } else if (custom_h && callfunc=="tanh_custom") {
+ code = "sinh_custom(" + dump_node_code(onode->arguments[1], p_level) + "";
+ } else if (custom_h && callfunc == "tanh_custom") {
if (!tanh_used) {
- global_code=
- "float tanh_custom(float val)\n"\
- "{\n"\
- " float tmp = exp(val);\n"\
- " float tanH = (tmp - 1.0 / tmp) / (tmp + 1.0 / tmp);\n"\
- " return tanH;\n"\
- "}\n"+global_code;
- tanh_used=true;
+ global_code =
+ "float tanh_custom(float val)\n"
+ "{\n"
+ " float tmp = exp(val);\n"
+ " float tanH = (tmp - 1.0 / tmp) / (tmp + 1.0 / tmp);\n"
+ " return tanH;\n"
+ "}\n" +
+ global_code;
+ tanh_used = true;
}
- code="tanh_custom("+dump_node_code(onode->arguments[1],p_level)+"";
+ code = "tanh_custom(" + dump_node_code(onode->arguments[1], p_level) + "";
} else {
- for(int i=1;i<onode->arguments.size();i++) {
- if (i>1)
- code+=", ";
- //transform
- code+=dump_node_code(onode->arguments[i],p_level);
-
+ for (int i = 1; i < onode->arguments.size(); i++) {
+ if (i > 1)
+ code += ", ";
+ //transform
+ code += dump_node_code(onode->arguments[i], p_level);
}
}
- code+=")";
+ code += ")";
break;
} break;
default: {}
@@ -496,83 +498,81 @@ String ShaderCompilerGLES2::dump_node_code(SL::Node *p_node,int p_level,bool p_a
} break;
case SL::Node::TYPE_CONTROL_FLOW: {
- SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node;
- if (cfnode->flow_op==SL::FLOW_OP_IF) {
+ SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node;
+ if (cfnode->flow_op == SL::FLOW_OP_IF) {
- code+="if ("+dump_node_code(cfnode->statements[0],p_level)+") {" ENDL;
- code+=dump_node_code(cfnode->statements[1],p_level+1);
- if (cfnode->statements.size()==3) {
+ code += "if (" + dump_node_code(cfnode->statements[0], p_level) + ") {" ENDL;
+ code += dump_node_code(cfnode->statements[1], p_level + 1);
+ if (cfnode->statements.size() == 3) {
- code+="} else {" ENDL;
- code+=dump_node_code(cfnode->statements[2],p_level+1);
+ code += "} else {" ENDL;
+ code += dump_node_code(cfnode->statements[2], p_level + 1);
}
- code+="}" ENDL;
+ code += "}" ENDL;
- } else if (cfnode->flow_op==SL::FLOW_OP_RETURN) {
+ } else if (cfnode->flow_op == SL::FLOW_OP_RETURN) {
if (cfnode->statements.size()) {
- code="return "+dump_node_code(cfnode->statements[0],p_level);
+ code = "return " + dump_node_code(cfnode->statements[0], p_level);
} else {
- code="return";
+ code = "return";
}
}
} break;
case SL::Node::TYPE_MEMBER: {
- SL::MemberNode *mnode=(SL::MemberNode*)p_node;
+ SL::MemberNode *mnode = (SL::MemberNode *)p_node;
String m;
- if (mnode->basetype==SL::TYPE_MAT4) {
- if (mnode->name=="x")
- m="[0]";
- else if (mnode->name=="y")
- m="[1]";
- else if (mnode->name=="z")
- m="[2]";
- else if (mnode->name=="w")
- m="[3]";
- } else if (mnode->basetype==SL::TYPE_MAT2) {
- if (mnode->name=="x")
- m="[0]";
- else if (mnode->name=="y")
- m="[1]";
-
- } else if (mnode->basetype==SL::TYPE_MAT3) {
- if (mnode->name=="x")
- m="[0]";
- else if (mnode->name=="y")
- m="[1]";
- else if (mnode->name=="z")
- m="[2]";
+ if (mnode->basetype == SL::TYPE_MAT4) {
+ if (mnode->name == "x")
+ m = "[0]";
+ else if (mnode->name == "y")
+ m = "[1]";
+ else if (mnode->name == "z")
+ m = "[2]";
+ else if (mnode->name == "w")
+ m = "[3]";
+ } else if (mnode->basetype == SL::TYPE_MAT2) {
+ if (mnode->name == "x")
+ m = "[0]";
+ else if (mnode->name == "y")
+ m = "[1]";
+
+ } else if (mnode->basetype == SL::TYPE_MAT3) {
+ if (mnode->name == "x")
+ m = "[0]";
+ else if (mnode->name == "y")
+ m = "[1]";
+ else if (mnode->name == "z")
+ m = "[2]";
} else {
- m="."+mnode->name;
+ m = "." + mnode->name;
}
- code=dump_node_code(mnode->owner,p_level)+m;
+ code = dump_node_code(mnode->owner, p_level) + m;
} break;
}
return code;
-
}
-
Error ShaderCompilerGLES2::compile_node(SL::ProgramNode *p_program) {
// feed the local replace table and global code
- global_code="";
+ global_code = "";
// uniforms first!
- int ubase=0;
+ int ubase = 0;
if (uniforms)
- ubase=uniforms->size();
- for(Map<StringName,SL::Uniform>::Element *E=p_program->uniforms.front();E;E=E->next()) {
+ ubase = uniforms->size();
+ for (Map<StringName, SL::Uniform>::Element *E = p_program->uniforms.front(); E; E = E->next()) {
- String uline="uniform "+_typestr(E->get().type)+" _"+E->key().operator String()+";" ENDL;
+ String uline = "uniform " + _typestr(E->get().type) + " _" + E->key().operator String() + ";" ENDL;
- global_code+=uline;
+ global_code += uline;
if (uniforms) {
/*
if (uniforms->has(E->key())) {
@@ -582,138 +582,134 @@ Error ShaderCompilerGLES2::compile_node(SL::ProgramNode *p_program) {
}
*/
SL::Uniform u = E->get();
- u.order+=ubase;
- uniforms->insert(E->key(),u);
+ u.order += ubase;
+ uniforms->insert(E->key(), u);
}
}
- for(int i=0;i<p_program->functions.size();i++) {
-
+ for (int i = 0; i < p_program->functions.size(); i++) {
- SL::FunctionNode *fnode=p_program->functions[i].function;
+ SL::FunctionNode *fnode = p_program->functions[i].function;
- StringName funcname=fnode->name;
- String newfuncname=replace_string(funcname);
+ StringName funcname = fnode->name;
+ String newfuncname = replace_string(funcname);
String header;
- header=_typestr(fnode->return_type)+" "+newfuncname+"(";
- for(int i=0;i<fnode->arguments.size();i++) {
+ header = _typestr(fnode->return_type) + " " + newfuncname + "(";
+ for (int i = 0; i < fnode->arguments.size(); i++) {
- if (i>0)
- header+=", ";
- header+=_typestr(fnode->arguments[i].type)+" "+replace_string(fnode->arguments[i].name);
+ if (i > 0)
+ header += ", ";
+ header += _typestr(fnode->arguments[i].type) + " " + replace_string(fnode->arguments[i].name);
}
- header+=") {" ENDL;
- String fcode=header;
- fcode+=dump_node_code(fnode->body,1);
- fcode+="}" ENDL;
- global_code+=fcode;
-
+ header += ") {" ENDL;
+ String fcode = header;
+ fcode += dump_node_code(fnode->body, 1);
+ fcode += "}" ENDL;
+ global_code += fcode;
}
-/* for(Map<StringName,SL::DataType>::Element *E=p_program->preexisting_variables.front();E;E=E->next()) {
+ /* for(Map<StringName,SL::DataType>::Element *E=p_program->preexisting_variables.front();E;E=E->next()) {
StringName varname=E->key();
String newvarname=replace_string(varname);
global_code+="uniform "+_typestr(E->get())+" "+newvarname+";" ENDL;
}*/
- code=dump_node_code(p_program,0);
+ code = dump_node_code(p_program, 0);
#ifdef DEBUG_SHADER_ENABLED
print_line("GLOBAL CODE:\n\n");
print_line(global_code);
- global_code=global_code.replace("\n","");
+ global_code = global_code.replace("\n", "");
print_line("CODE:\n\n");
print_line(code);
- code=code.replace("\n","");
+ code = code.replace("\n", "");
#endif
return OK;
}
-Error ShaderCompilerGLES2::create_glsl_120_code(void *p_str,SL::ProgramNode *p_program) {
+Error ShaderCompilerGLES2::create_glsl_120_code(void *p_str, SL::ProgramNode *p_program) {
- ShaderCompilerGLES2 *compiler=(ShaderCompilerGLES2*)p_str;
+ ShaderCompilerGLES2 *compiler = (ShaderCompilerGLES2 *)p_str;
return compiler->compile_node(p_program);
}
+String ShaderCompilerGLES2::replace_string(const StringName &p_string) {
-String ShaderCompilerGLES2::replace_string(const StringName& p_string) {
-
- Map<StringName,StringName>::Element *E=NULL;
- E=replace_table.find(p_string);
+ Map<StringName, StringName>::Element *E = NULL;
+ E = replace_table.find(p_string);
if (E)
return E->get();
- E=mode_replace_table[type].find(p_string);
+ E = mode_replace_table[type].find(p_string);
if (E)
return E->get();
-
- return "_"+p_string.operator String();
+ return "_" + p_string.operator String();
}
-Error ShaderCompilerGLES2::compile(const String& p_code, ShaderLanguage::ShaderType p_type, String& r_code_line, String& r_globals_line, Flags& r_flags, Map<StringName,ShaderLanguage::Uniform> *r_uniforms) {
-
- uses_texscreen=false;
- uses_texpos=false;
- uses_alpha=false;
- uses_discard=false;
- uses_screen_uv=false;
- uses_light=false;
- uses_time=false;
- uses_normalmap=false;
- uses_normal=false;
- uses_texpixel_size=false;
- uses_worldvec=false;
- vertex_code_writes_vertex=false;
+Error ShaderCompilerGLES2::compile(const String &p_code, ShaderLanguage::ShaderType p_type, String &r_code_line, String &r_globals_line, Flags &r_flags, Map<StringName, ShaderLanguage::Uniform> *r_uniforms) {
+
+ uses_texscreen = false;
+ uses_texpos = false;
+ uses_alpha = false;
+ uses_discard = false;
+ uses_screen_uv = false;
+ uses_light = false;
+ uses_time = false;
+ uses_normalmap = false;
+ uses_normal = false;
+ uses_texpixel_size = false;
+ uses_worldvec = false;
+ vertex_code_writes_vertex = false;
vertex_code_writes_position = false;
- uses_shadow_color=false;
- uniforms=r_uniforms;
- flags=&r_flags;
- r_flags.use_color_interp=false;
- r_flags.use_uv_interp=false;
- r_flags.use_uv2_interp=false;
- r_flags.use_tangent_interp=false;
- r_flags.use_var1_interp=false;
- r_flags.use_var2_interp=false;
- r_flags.uses_normalmap=false;
- r_flags.uses_normal=false;
- sinh_used=false;
- tanh_used=false;
- cosh_used=false;
+ uses_shadow_color = false;
+ uniforms = r_uniforms;
+ flags = &r_flags;
+ r_flags.use_color_interp = false;
+ r_flags.use_uv_interp = false;
+ r_flags.use_uv2_interp = false;
+ r_flags.use_tangent_interp = false;
+ r_flags.use_var1_interp = false;
+ r_flags.use_var2_interp = false;
+ r_flags.uses_normalmap = false;
+ r_flags.uses_normal = false;
+ sinh_used = false;
+ tanh_used = false;
+ cosh_used = false;
String error;
- int errline,errcol;
+ int errline, errcol;
- type=p_type;
- Error err = SL::compile(p_code,p_type,create_glsl_120_code,this,&error,&errline,&errcol);
+ type = p_type;
+ Error err = SL::compile(p_code, p_type, create_glsl_120_code, this, &error, &errline, &errcol);
if (err) {
- print_line("***Error precompiling shader: "+error);
- print_line("error "+itos(errline)+":"+itos(errcol));
+ print_line("***Error precompiling shader: " + error);
+ print_line("error " + itos(errline) + ":" + itos(errcol));
return err;
}
- r_flags.uses_alpha=uses_alpha;
- r_flags.uses_texscreen=uses_texscreen;
- r_flags.uses_texpos=uses_texpos;
- r_flags.vertex_code_writes_vertex=vertex_code_writes_vertex;
- r_flags.vertex_code_writes_position=vertex_code_writes_position;
- r_flags.uses_discard=uses_discard;
- r_flags.uses_screen_uv=uses_screen_uv;
- r_flags.uses_light=uses_light;
- r_flags.uses_time=uses_time;
- r_flags.uses_normalmap=uses_normalmap;
- r_flags.uses_normal=uses_normal;
- r_flags.uses_texpixel_size=uses_texpixel_size;
- r_flags.uses_worldvec=uses_worldvec;
- r_flags.uses_shadow_color=uses_shadow_color;
- r_code_line=code;
- r_globals_line=global_code;
+ r_flags.uses_alpha = uses_alpha;
+ r_flags.uses_texscreen = uses_texscreen;
+ r_flags.uses_texpos = uses_texpos;
+ r_flags.vertex_code_writes_vertex = vertex_code_writes_vertex;
+ r_flags.vertex_code_writes_position = vertex_code_writes_position;
+ r_flags.uses_discard = uses_discard;
+ r_flags.uses_screen_uv = uses_screen_uv;
+ r_flags.uses_light = uses_light;
+ r_flags.uses_time = uses_time;
+ r_flags.uses_normalmap = uses_normalmap;
+ r_flags.uses_normal = uses_normal;
+ r_flags.uses_texpixel_size = uses_texpixel_size;
+ r_flags.uses_worldvec = uses_worldvec;
+ r_flags.uses_shadow_color = uses_shadow_color;
+ r_code_line = code;
+ r_globals_line = global_code;
return OK;
}
@@ -721,228 +717,222 @@ ShaderCompilerGLES2::ShaderCompilerGLES2() {
#ifdef GLEW_ENABLED
//use custom functions because they are not supported in GLSL120
- custom_h=true;
+ custom_h = true;
#else
- custom_h=false;
+ custom_h = false;
#endif
- replace_table["bool"]= "bool";
- replace_table["float" ]= "float";
- replace_table["vec2" ]= "vec2";
- replace_table["vec3" ]= "vec3";
- replace_table["vec4" ]= "vec4";
- replace_table["mat2" ]= "mat2";
- replace_table["mat3" ]= "mat3";
- replace_table["mat4" ]= "mat4";
- replace_table["texture" ]= "sampler2D";
- replace_table["cubemap" ]= "samplerCube";
-
- replace_table["sin"]= "sin";
- replace_table["cos" ]= "cos";
- replace_table["tan" ]= "tan";
- replace_table["asin" ]= "asin";
- replace_table["acos" ]= "acos";
- replace_table["atan" ]= "atan";
- replace_table["atan2"]= "atan";
+ replace_table["bool"] = "bool";
+ replace_table["float"] = "float";
+ replace_table["vec2"] = "vec2";
+ replace_table["vec3"] = "vec3";
+ replace_table["vec4"] = "vec4";
+ replace_table["mat2"] = "mat2";
+ replace_table["mat3"] = "mat3";
+ replace_table["mat4"] = "mat4";
+ replace_table["texture"] = "sampler2D";
+ replace_table["cubemap"] = "samplerCube";
+
+ replace_table["sin"] = "sin";
+ replace_table["cos"] = "cos";
+ replace_table["tan"] = "tan";
+ replace_table["asin"] = "asin";
+ replace_table["acos"] = "acos";
+ replace_table["atan"] = "atan";
+ replace_table["atan2"] = "atan";
if (custom_h) {
- replace_table["sinh" ]= "sinh_custom";
- replace_table["cosh" ]= "cosh_custom";
- replace_table["tanh" ]= "tanh_custom";
+ replace_table["sinh"] = "sinh_custom";
+ replace_table["cosh"] = "cosh_custom";
+ replace_table["tanh"] = "tanh_custom";
} else {
- replace_table["sinh" ]= "sinh";
- replace_table["cosh" ]= "cosh";
- replace_table["tanh" ]= "tanh";
+ replace_table["sinh"] = "sinh";
+ replace_table["cosh"] = "cosh";
+ replace_table["tanh"] = "tanh";
}
- replace_table["pow" ]= "pow";
- replace_table["exp" ]= "exp";
- replace_table["log" ]= "log";
- replace_table["sqrt"]= "sqrt";
- replace_table["abs" ]= "abs";
- replace_table["sign"]= "sign";
- replace_table["floor"]= "floor";
- replace_table["trunc"]= "trunc";
+ replace_table["pow"] = "pow";
+ replace_table["exp"] = "exp";
+ replace_table["log"] = "log";
+ replace_table["sqrt"] = "sqrt";
+ replace_table["abs"] = "abs";
+ replace_table["sign"] = "sign";
+ replace_table["floor"] = "floor";
+ replace_table["trunc"] = "trunc";
#ifdef GLEW_ENABLED
- replace_table["round"]= "roundfix";
+ replace_table["round"] = "roundfix";
#else
- replace_table["round"]= "round";
+ replace_table["round"] = "round";
#endif
- replace_table["ceil" ]= "ceil";
- replace_table["fract"]= "fract";
- replace_table["mod" ]= "mod";
- replace_table["min" ]= "min";
- replace_table["max"]= "max";
- replace_table["clamp"]= "clamp";
- replace_table["mix" ]= "mix";
- replace_table["step" ]= "step";
- replace_table["smoothstep" ]= "smoothstep";
- replace_table["length"]= "length";
- replace_table["distance"]= "distance";
- replace_table["dot" ]= "dot";
- replace_table["cross" ]="cross";
- replace_table["normalize"]= "normalize";
- replace_table["reflect"]= "reflect";
- replace_table["refract"]= "refract";
- replace_table["tex"]= "tex";
- replace_table["texa"]= "texa";
- replace_table["tex2"]= "tex2";
- replace_table["texcube"]= "textureCube";
- replace_table["texscreen"]= "texscreen";
- replace_table["texpos"]= "texpos";
-
-
+ replace_table["ceil"] = "ceil";
+ replace_table["fract"] = "fract";
+ replace_table["mod"] = "mod";
+ replace_table["min"] = "min";
+ replace_table["max"] = "max";
+ replace_table["clamp"] = "clamp";
+ replace_table["mix"] = "mix";
+ replace_table["step"] = "step";
+ replace_table["smoothstep"] = "smoothstep";
+ replace_table["length"] = "length";
+ replace_table["distance"] = "distance";
+ replace_table["dot"] = "dot";
+ replace_table["cross"] = "cross";
+ replace_table["normalize"] = "normalize";
+ replace_table["reflect"] = "reflect";
+ replace_table["refract"] = "refract";
+ replace_table["tex"] = "tex";
+ replace_table["texa"] = "texa";
+ replace_table["tex2"] = "tex2";
+ replace_table["texcube"] = "textureCube";
+ replace_table["texscreen"] = "texscreen";
+ replace_table["texpos"] = "texpos";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_VERTEX"] = "vertex_in.xyz";
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_NORMAL"] = "normal_in";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_TANGENT"]="tangent_in";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_BINORMALF"]="binormalf";
-
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_TANGENT"] = "tangent_in";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SRC_BINORMALF"] = "binormalf";
+
mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["POSITION"] = "gl_Position";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VERTEX"]="vertex_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["NORMAL"]="normal_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TANGENT"]="tangent_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["BINORMAL"]="binormal_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV"]="uv_interp.xy";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV2"]="uv_interp.zw";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["COLOR"]="color_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VERTEX"] = "vertex_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["NORMAL"] = "normal_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TANGENT"] = "tangent_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["BINORMAL"] = "binormal_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV"] = "uv_interp.xy";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["UV2"] = "uv_interp.zw";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["COLOR"] = "color_interp";
//@TODO convert to glsl stuff
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SPEC_EXP"]="vertex_specular_exp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["WORLD_MATRIX"]="world_transform";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INV_CAMERA_MATRIX"]="camera_inverse_transform";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["PROJECTION_MATRIX"]="projection_transform";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["MODELVIEW_MATRIX"]="modelview";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["POINT_SIZE"]="gl_PointSize";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR2"]="var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SPEC_EXP"] = "vertex_specular_exp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["WORLD_MATRIX"] = "world_transform";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INV_CAMERA_MATRIX"] = "camera_inverse_transform";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["PROJECTION_MATRIX"] = "projection_transform";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["MODELVIEW_MATRIX"] = "modelview";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["POINT_SIZE"] = "gl_PointSize";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["VAR2"] = "var2_interp";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SCREEN_POS"]="SCREEN_POS";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["SCREEN_SIZE"]="SCREEN_SIZE";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INSTANCE_ID"]="instance_id";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TIME"]="time";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["INSTANCE_ID"] = "instance_id";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_VERTEX]["TIME"] = "time";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VERTEX"]="vertex";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VERTEX"] = "vertex";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POSITION"]="IN_POSITION";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMAL"]="normal";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TANGENT"]="tangent";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POSITION"]="gl_Position";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["BINORMAL"]="binormal";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP"]="normalmap";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP_DEPTH"]="normaldepth";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"]="var2_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV"]="uv";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV2"]="uv2";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_UV"]="screen_uv";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"]="var2_interp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["COLOR"]="color";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE"]="diffuse.rgb";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE_ALPHA"]="diffuse";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPECULAR"]="specular";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["EMISSION"]="emission";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SHADE_PARAM"]="shade_param";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPEC_EXP"]="specular_exp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["GLOW"]="glow";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DISCARD"]="discard_";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POINT_COORD"]="gl_PointCoord";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["INV_CAMERA_MATRIX"]="camera_inverse_transform";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMAL"] = "normal";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TANGENT"] = "tangent";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POSITION"] = "gl_Position";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["BINORMAL"] = "binormal";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP"] = "normalmap";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["NORMALMAP_DEPTH"] = "normaldepth";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"] = "var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV"] = "uv";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["UV2"] = "uv2";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_UV"] = "screen_uv";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["VAR2"] = "var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["COLOR"] = "color";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE"] = "diffuse.rgb";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DIFFUSE_ALPHA"] = "diffuse";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPECULAR"] = "specular";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["EMISSION"] = "emission";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SHADE_PARAM"] = "shade_param";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SPEC_EXP"] = "specular_exp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["GLOW"] = "glow";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["DISCARD"] = "discard_";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["POINT_COORD"] = "gl_PointCoord";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["INV_CAMERA_MATRIX"] = "camera_inverse_transform";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_POS"]="SCREEN_POS";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["SCREEN_TEXEL_SIZE"]="SCREEN_TEXEL_SIZE";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TIME"]="time";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_FRAGMENT]["TIME"] = "time";
//////////////
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["NORMAL"]="normal";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["NORMAL"] = "normal";
//mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["POSITION"]="IN_POSITION";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIR"]="light_dir";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIFFUSE"]="light_diffuse";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_SPECULAR"]="light_specular";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["EYE_VEC"]="eye_vec";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["DIFFUSE"]="mdiffuse";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR"]="specular";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR_EXP"]="specular_exp";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SHADE_PARAM"]="shade_param";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT"]="light";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["POINT_COORD"]="gl_PointCoord";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["TIME"]="time";
- mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SHADOW"]="shadow_color";
-
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["SRC_VERTEX"]="src_vtx";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VERTEX"]="outvec.xy";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_VERTEX"]="outvec.xy";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["UV"]="uv_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["COLOR"]="color_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR2"]="var2_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["POINT_SIZE"]="gl_PointSize";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_MATRIX"]="modelview_matrix";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["PROJECTION_MATRIX"]="projection_matrix";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["EXTRA_MATRIX"]="extra_matrix";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["TIME"]="time";
-
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POSITION"]="gl_Position";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMAL"]="normal";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP"]="normal_map";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP_DEPTH"]="normal_depth";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["UV"]="uv_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SRC_COLOR"]="color_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["COLOR"]="color";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE"]="texture";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE_PIXEL_SIZE"]="texpixel_size";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR2"]="var2_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SCREEN_UV"]="screen_uv";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POINT_COORD"]="gl_PointCoord";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TIME"]="time";
-
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POSITION"]="gl_Position";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["NORMAL"]="normal";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["UV"]="uv_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["COLOR"]="color";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE"]="texture";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE_PIXEL_SIZE"]="texpixel_size";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR1"]="var1_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR2"]="var2_interp";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_VEC"]="light_vec";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_HEIGHT"]="light_height";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_COLOR"]="light";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_SHADOW"]="light_shadow_color";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_UV"]="light_uv";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT"]="light_out";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SHADOW"]="shadow_color";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SCREEN_UV"]="screen_uv";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POINT_COORD"]="gl_PointCoord";
- mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TIME"]="time";
-
-
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIR"] = "light_dir";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_DIFFUSE"] = "light_diffuse";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT_SPECULAR"] = "light_specular";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["EYE_VEC"] = "eye_vec";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["DIFFUSE"] = "mdiffuse";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR"] = "specular";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SPECULAR_EXP"] = "specular_exp";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SHADE_PARAM"] = "shade_param";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["LIGHT"] = "light";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["POINT_COORD"] = "gl_PointCoord";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["TIME"] = "time";
+ mode_replace_table[ShaderLanguage::SHADER_MATERIAL_LIGHT]["SHADOW"] = "shadow_color";
+
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["SRC_VERTEX"] = "src_vtx";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VERTEX"] = "outvec.xy";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_VERTEX"] = "outvec.xy";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["UV"] = "uv_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["COLOR"] = "color_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["VAR2"] = "var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["POINT_SIZE"] = "gl_PointSize";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["WORLD_MATRIX"] = "modelview_matrix";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["PROJECTION_MATRIX"] = "projection_matrix";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["EXTRA_MATRIX"] = "extra_matrix";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_VERTEX]["TIME"] = "time";
+
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POSITION"] = "gl_Position";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMAL"] = "normal";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP"] = "normal_map";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["NORMALMAP_DEPTH"] = "normal_depth";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["UV"] = "uv_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SRC_COLOR"] = "color_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["COLOR"] = "color";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE"] = "texture";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TEXTURE_PIXEL_SIZE"] = "texpixel_size";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["VAR2"] = "var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["SCREEN_UV"] = "screen_uv";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["POINT_COORD"] = "gl_PointCoord";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_FRAGMENT]["TIME"] = "time";
+
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POSITION"] = "gl_Position";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["NORMAL"] = "normal";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["UV"] = "uv_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["COLOR"] = "color";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE"] = "texture";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TEXTURE_PIXEL_SIZE"] = "texpixel_size";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR1"] = "var1_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["VAR2"] = "var2_interp";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_VEC"] = "light_vec";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_HEIGHT"] = "light_height";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_COLOR"] = "light";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_SHADOW"] = "light_shadow_color";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT_UV"] = "light_uv";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["LIGHT"] = "light_out";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SHADOW"] = "shadow_color";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["SCREEN_UV"] = "screen_uv";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["POINT_COORD"] = "gl_PointCoord";
+ mode_replace_table[ShaderLanguage::SHADER_CANVAS_ITEM_LIGHT]["TIME"] = "time";
//mode_replace_table[2]["SCREEN_POS"]="SCREEN_POS";
//mode_replace_table[2]["SCREEN_TEXEL_SIZE"]="SCREEN_TEXEL_SIZE";
-
- out_vertex_name="VERTEX";
-
- vname_discard="DISCARD";
- vname_screen_uv="SCREEN_UV";
- vname_diffuse_alpha="DIFFUSE_ALPHA";
- vname_color_interp="COLOR";
- vname_uv_interp="UV";
- vname_uv2_interp="UV2";
- vname_tangent_interp="TANGENT";
- vname_binormal_interp="BINORMAL";
- vname_var1_interp="VAR1";
- vname_var2_interp="VAR2";
- vname_vertex="VERTEX";
+ out_vertex_name = "VERTEX";
+
+ vname_discard = "DISCARD";
+ vname_screen_uv = "SCREEN_UV";
+ vname_diffuse_alpha = "DIFFUSE_ALPHA";
+ vname_color_interp = "COLOR";
+ vname_uv_interp = "UV";
+ vname_uv2_interp = "UV2";
+ vname_tangent_interp = "TANGENT";
+ vname_binormal_interp = "BINORMAL";
+ vname_var1_interp = "VAR1";
+ vname_var2_interp = "VAR2";
+ vname_vertex = "VERTEX";
vname_position = "POSITION";
- vname_light="LIGHT";
- vname_time="TIME";
- vname_normalmap="NORMALMAP";
- vname_normalmap_depth="NORMALMAP_DEPTH";
- vname_normal="NORMAL";
- vname_texpixel_size="TEXTURE_PIXEL_SIZE";
- vname_world_vec="WORLD_VERTEX";
- vname_shadow="SHADOW";
-
+ vname_light = "LIGHT";
+ vname_time = "TIME";
+ vname_normalmap = "NORMALMAP";
+ vname_normalmap_depth = "NORMALMAP_DEPTH";
+ vname_normal = "NORMAL";
+ vname_texpixel_size = "TEXTURE_PIXEL_SIZE";
+ vname_world_vec = "WORLD_VERTEX";
+ vname_shadow = "SHADOW";
}
diff --git a/drivers/gles2/shader_compiler_gles2.h b/drivers/gles2/shader_compiler_gles2.h
index 3c39e101ca..2565adcd5d 100644
--- a/drivers/gles2/shader_compiler_gles2.h
+++ b/drivers/gles2/shader_compiler_gles2.h
@@ -33,15 +33,15 @@
class ShaderCompilerGLES2 {
class Uniform;
+
public:
struct Flags;
-private:
+private:
ShaderLanguage::ProgramNode *program_node;
- String dump_node_code(ShaderLanguage::Node *p_node,int p_level,bool p_assign_left=false);
+ String dump_node_code(ShaderLanguage::Node *p_node, int p_level, bool p_assign_left = false);
Error compile_node(ShaderLanguage::ProgramNode *p_program);
- static Error create_glsl_120_code(void *p_str,ShaderLanguage::ProgramNode *p_program);
-
+ static Error create_glsl_120_code(void *p_str, ShaderLanguage::ProgramNode *p_program);
bool uses_light;
bool uses_texscreen;
@@ -87,7 +87,7 @@ private:
StringName vname_world_vec;
StringName vname_shadow;
- Map<StringName,ShaderLanguage::Uniform> *uniforms;
+ Map<StringName, ShaderLanguage::Uniform> *uniforms;
StringName out_vertex_name;
@@ -95,13 +95,12 @@ private:
String code;
ShaderLanguage::ShaderType type;
- String replace_string(const StringName& p_string);
+ String replace_string(const StringName &p_string);
- Map<StringName,StringName> mode_replace_table[9];
- Map<StringName,StringName> replace_table;
+ Map<StringName, StringName> mode_replace_table[9];
+ Map<StringName, StringName> replace_table;
public:
-
struct Flags {
bool uses_alpha;
@@ -126,10 +125,9 @@ public:
bool uses_shadow_color;
};
- Error compile(const String& p_code, ShaderLanguage::ShaderType p_type, String& r_code_line, String& r_globals_line, Flags& r_flags, Map<StringName,ShaderLanguage::Uniform> *r_uniforms=NULL);
+ Error compile(const String &p_code, ShaderLanguage::ShaderType p_type, String &r_code_line, String &r_globals_line, Flags &r_flags, Map<StringName, ShaderLanguage::Uniform> *r_uniforms = NULL);
ShaderCompilerGLES2();
-
};
#endif // SHADER_COMPILERL_GL_H
diff --git a/drivers/gles2/shader_gles2.cpp b/drivers/gles2/shader_gles2.cpp
index 97c31dfc1c..08b9c21d5b 100644
--- a/drivers/gles2/shader_gles2.cpp
+++ b/drivers/gles2/shader_gles2.cpp
@@ -35,22 +35,20 @@
#ifdef DEBUG_OPENGL
-#define DEBUG_TEST_ERROR(m_section)\
-{\
- uint32_t err = glGetError();\
- if (err) {\
- print_line("OpenGL Error #"+itos(err)+" at: "+m_section);\
- }\
-}
+#define DEBUG_TEST_ERROR(m_section) \
+ { \
+ uint32_t err = glGetError(); \
+ if (err) { \
+ print_line("OpenGL Error #" + itos(err) + " at: " + m_section); \
+ } \
+ }
#else
#define DEBUG_TEST_ERROR(m_section)
#endif
-ShaderGLES2 *ShaderGLES2::active=NULL;
-
-
+ShaderGLES2 *ShaderGLES2::active = NULL;
//#define DEBUG_SHADER
@@ -64,7 +62,6 @@ ShaderGLES2 *ShaderGLES2::active=NULL;
#endif
-
void ShaderGLES2::bind_uniforms() {
if (!uniforms_dirty) {
@@ -72,34 +69,33 @@ void ShaderGLES2::bind_uniforms() {
};
// upload default uniforms
- const Map<uint32_t,Variant>::Element *E =uniform_defaults.front();
+ const Map<uint32_t, Variant>::Element *E = uniform_defaults.front();
- while(E) {
- int idx=E->key();
- int location=version->uniform_location[idx];
+ while (E) {
+ int idx = E->key();
+ int location = version->uniform_location[idx];
- if (location<0) {
- E=E->next();
+ if (location < 0) {
+ E = E->next();
continue;
-
}
- const Variant &v=E->value();
+ const Variant &v = E->value();
_set_uniform_variant(location, v);
//print_line("uniform "+itos(location)+" value "+v+ " type "+Variant::get_type_name(v.get_type()));
- E=E->next();
+ E = E->next();
};
- const Map<uint32_t,CameraMatrix>::Element* C = uniform_cameras.front();
+ const Map<uint32_t, CameraMatrix>::Element *C = uniform_cameras.front();
while (C) {
int location = version->uniform_location[C->key()];
- if (location<0) {
- C=C->next();
+ if (location < 0) {
+ C = C->next();
continue;
}
- glUniformMatrix4fv(location,1,false,&(C->get().matrix[0][0]));
+ glUniformMatrix4fv(location, 1, false, &(C->get().matrix[0][0]));
C = C->next();
};
@@ -114,24 +110,24 @@ GLint ShaderGLES2::get_uniform_location(int p_idx) const {
};
bool ShaderGLES2::bind() {
-
- if (active!=this || !version || new_conditional_version.key!=conditional_version.key) {
- conditional_version=new_conditional_version;
+
+ if (active != this || !version || new_conditional_version.key != conditional_version.key) {
+ conditional_version = new_conditional_version;
version = get_current_version();
} else {
return false;
}
-
- ERR_FAIL_COND_V(!version,false);
- glUseProgram( version->id );
+ ERR_FAIL_COND_V(!version, false);
+
+ glUseProgram(version->id);
DEBUG_TEST_ERROR("Use Program");
- active=this;
+ active = this;
uniforms_dirty = true;
-/*
+ /*
* why on earth is this code here?
for (int i=0;i<texunit_pair_count;i++) {
@@ -145,184 +141,172 @@ bool ShaderGLES2::bind() {
void ShaderGLES2::unbind() {
- version=NULL;
+ version = NULL;
glUseProgram(0);
uniforms_dirty = true;
- active=NULL;
+ active = NULL;
}
+static String _fix_error_code_line(const String &p_error, int p_code_start, int p_offset) {
-static String _fix_error_code_line(const String& p_error,int p_code_start,int p_offset) {
-
- int last_find_pos=-1;
+ int last_find_pos = -1;
// NVIDIA
- String error=p_error;
- while((last_find_pos=p_error.find("(",last_find_pos+1))!=-1) {
+ String error = p_error;
+ while ((last_find_pos = p_error.find("(", last_find_pos + 1)) != -1) {
- int end_pos=last_find_pos+1;
+ int end_pos = last_find_pos + 1;
- while(true) {
+ while (true) {
- if (p_error[end_pos]>='0' && p_error[end_pos]<='9') {
+ if (p_error[end_pos] >= '0' && p_error[end_pos] <= '9') {
end_pos++;
continue;
- } else if (p_error[end_pos]==')') {
+ } else if (p_error[end_pos] == ')') {
break;
} else {
- end_pos=-1;
+ end_pos = -1;
break;
}
-
}
- if (end_pos==-1)
+ if (end_pos == -1)
continue;
- String numstr = error.substr(last_find_pos+1,(end_pos-last_find_pos)-1);
- String begin = error.substr(0,last_find_pos+1);
- String end = error.substr(end_pos,error.length());
- int num = numstr.to_int()+p_code_start-p_offset;
- error = begin+itos(num)+end;
+ String numstr = error.substr(last_find_pos + 1, (end_pos - last_find_pos) - 1);
+ String begin = error.substr(0, last_find_pos + 1);
+ String end = error.substr(end_pos, error.length());
+ int num = numstr.to_int() + p_code_start - p_offset;
+ error = begin + itos(num) + end;
}
- // ATI
- last_find_pos=-1;
- while((last_find_pos=p_error.find("ERROR: ",last_find_pos+1))!=-1) {
-
- last_find_pos+=6;
- int end_pos=last_find_pos+1;
+ // ATI
+ last_find_pos = -1;
+ while ((last_find_pos = p_error.find("ERROR: ", last_find_pos + 1)) != -1) {
- while(true) {
+ last_find_pos += 6;
+ int end_pos = last_find_pos + 1;
- if (p_error[end_pos]>='0' && p_error[end_pos]<='9') {
+ while (true) {
- end_pos++;
- continue;
- } else if (p_error[end_pos]==':') {
- break;
- } else {
+ if (p_error[end_pos] >= '0' && p_error[end_pos] <= '9') {
- end_pos=-1;
- break;
- }
+ end_pos++;
+ continue;
+ } else if (p_error[end_pos] == ':') {
+ break;
+ } else {
- }
+ end_pos = -1;
+ break;
+ }
+ }
continue;
- if (end_pos==-1)
- continue;
-
- String numstr = error.substr(last_find_pos+1,(end_pos-last_find_pos)-1);
- print_line("numstr: "+numstr);
- String begin = error.substr(0,last_find_pos+1);
- String end = error.substr(end_pos,error.length());
- int num = numstr.to_int()+p_code_start-p_offset;
- error = begin+itos(num)+end;
- }
+ if (end_pos == -1)
+ continue;
+
+ String numstr = error.substr(last_find_pos + 1, (end_pos - last_find_pos) - 1);
+ print_line("numstr: " + numstr);
+ String begin = error.substr(0, last_find_pos + 1);
+ String end = error.substr(end_pos, error.length());
+ int num = numstr.to_int() + p_code_start - p_offset;
+ error = begin + itos(num) + end;
+ }
return error;
}
-ShaderGLES2::Version* ShaderGLES2::get_current_version() {
+ShaderGLES2::Version *ShaderGLES2::get_current_version() {
- Version *_v=version_map.getptr(conditional_version);
+ Version *_v = version_map.getptr(conditional_version);
if (_v) {
- if (conditional_version.code_version!=0) {
- CustomCode *cc=custom_code_map.getptr(conditional_version.code_version);
- ERR_FAIL_COND_V(!cc,_v);
- if (cc->version==_v->code_version)
+ if (conditional_version.code_version != 0) {
+ CustomCode *cc = custom_code_map.getptr(conditional_version.code_version);
+ ERR_FAIL_COND_V(!cc, _v);
+ if (cc->version == _v->code_version)
return _v;
} else {
return _v;
}
-
}
-
-
if (!_v)
- version_map[conditional_version]=Version();
-
+ version_map[conditional_version] = Version();
Version &v = version_map[conditional_version];
if (!_v) {
- v.uniform_location = memnew_arr( GLint, uniform_count );
+ v.uniform_location = memnew_arr(GLint, uniform_count);
} else {
if (v.ok) {
//bye bye shaders
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- v.id=0;
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
}
- v.ok=false;
+ v.ok = false;
/* SETUP CONDITIONALS */
-
- Vector<const char*> strings;
+
+ Vector<const char *> strings;
#ifdef GLEW_ENABLED
strings.push_back("#version 120\n"); //ATI requieres this before anything
#endif
- int define_line_ofs=1;
+ int define_line_ofs = 1;
- for(int j=0;j<conditional_count;j++) {
-
- bool enable=((1<<j)&conditional_version.version);
- strings.push_back(enable?conditional_defines[j]:"");
+ for (int j = 0; j < conditional_count; j++) {
+
+ bool enable = ((1 << j) & conditional_version.version);
+ strings.push_back(enable ? conditional_defines[j] : "");
if (enable)
define_line_ofs++;
if (enable) {
DEBUG_PRINT(conditional_defines[j]);
}
-
}
-
+
//keep them around during the function
CharString code_string;
CharString code_string2;
CharString code_globals;
-
//print_line("code version? "+itos(conditional_version.code_version));
- CustomCode *cc=NULL;
+ CustomCode *cc = NULL;
- if ( conditional_version.code_version>0 ) {
+ if (conditional_version.code_version > 0) {
//do custom code related stuff
- ERR_FAIL_COND_V( !custom_code_map.has( conditional_version.code_version ), NULL );
- cc=&custom_code_map[conditional_version.code_version];
- v.code_version=cc->version;
- define_line_ofs+=2;
+ ERR_FAIL_COND_V(!custom_code_map.has(conditional_version.code_version), NULL);
+ cc = &custom_code_map[conditional_version.code_version];
+ v.code_version = cc->version;
+ define_line_ofs += 2;
}
-
/* CREATE PROGRAM */
-
+
v.id = glCreateProgram();
-
- ERR_FAIL_COND_V(v.id==0, NULL);
-
- /* VERTEX SHADER */
+ ERR_FAIL_COND_V(v.id == 0, NULL);
+
+ /* VERTEX SHADER */
if (cc) {
- for(int i=0;i<cc->custom_defines.size();i++) {
+ for (int i = 0; i < cc->custom_defines.size(); i++) {
strings.push_back(cc->custom_defines[i]);
- DEBUG_PRINT("CD #"+itos(i)+": "+String(cc->custom_defines[i]));
+ DEBUG_PRINT("CD #" + itos(i) + ": " + String(cc->custom_defines[i]));
}
}
- int strings_base_size=strings.size();
+ int strings_base_size = strings.size();
#if 0
if (cc) {
@@ -338,76 +322,72 @@ ShaderGLES2::Version* ShaderGLES2::get_current_version() {
}
#endif
-
strings.push_back(vertex_code0.get_data());
if (cc) {
- code_globals=cc->vertex_globals.ascii();
+ code_globals = cc->vertex_globals.ascii();
strings.push_back(code_globals.get_data());
}
strings.push_back(vertex_code1.get_data());
if (cc) {
- code_string=cc->vertex.ascii();
+ code_string = cc->vertex.ascii();
strings.push_back(code_string.get_data());
}
strings.push_back(vertex_code2.get_data());
#ifdef DEBUG_SHADER
- DEBUG_PRINT("\nVertex Code:\n\n"+String(code_string.get_data()));
- for(int i=0;i<strings.size();i++) {
+ DEBUG_PRINT("\nVertex Code:\n\n" + String(code_string.get_data()));
+ for (int i = 0; i < strings.size(); i++) {
//print_line("vert strings "+itos(i)+":"+String(strings[i]));
}
#endif
-
v.vert_id = glCreateShader(GL_VERTEX_SHADER);
- glShaderSource(v.vert_id,strings.size(),&strings[0],NULL);
+ glShaderSource(v.vert_id, strings.size(), &strings[0], NULL);
glCompileShader(v.vert_id);
-
+
GLint status;
-
- glGetShaderiv(v.vert_id,GL_COMPILE_STATUS,&status);
- if (status==GL_FALSE) {
- // error compiling
+
+ glGetShaderiv(v.vert_id, GL_COMPILE_STATUS, &status);
+ if (status == GL_FALSE) {
+ // error compiling
GLsizei iloglen;
- glGetShaderiv(v.vert_id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
-
+ glGetShaderiv(v.vert_id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
+
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
+
ERR_PRINT("NO LOG, WTF");
} else {
- if (iloglen==0) {
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
-
- char *ilogmem = (char*)Memory::alloc_static(iloglen+1);
- ilogmem[iloglen]=0;
- glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Vertex Program Compilation Failed:\n";
-
- err_string+=ilogmem;
- err_string=_fix_error_code_line(err_string,vertex_code_start,define_line_ofs);
+ char *ilogmem = (char *)Memory::alloc_static(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Vertex Program Compilation Failed:\n";
+
+ err_string += ilogmem;
+ err_string = _fix_error_code_line(err_string, vertex_code_start, define_line_ofs);
ERR_PRINT(err_string.ascii().get_data());
Memory::free_static(ilogmem);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
+
ERR_FAIL_V(NULL);
- }
-
+ }
+
/* FRAGMENT SHADER */
strings.resize(strings_base_size);
@@ -426,347 +406,330 @@ ShaderGLES2::Version* ShaderGLES2::get_current_version() {
}
#endif
-
strings.push_back(fragment_code0.get_data());
if (cc) {
- code_globals=cc->fragment_globals.ascii();
+ code_globals = cc->fragment_globals.ascii();
strings.push_back(code_globals.get_data());
}
strings.push_back(fragment_code1.get_data());
if (cc) {
- code_string=cc->fragment.ascii();
+ code_string = cc->fragment.ascii();
strings.push_back(code_string.get_data());
}
strings.push_back(fragment_code2.get_data());
if (cc) {
- code_string2=cc->light.ascii();
+ code_string2 = cc->light.ascii();
strings.push_back(code_string2.get_data());
}
strings.push_back(fragment_code3.get_data());
#ifdef DEBUG_SHADER
- DEBUG_PRINT("\nFragment Code:\n\n"+String(code_string.get_data()));
- for(int i=0;i<strings.size();i++) {
+ DEBUG_PRINT("\nFragment Code:\n\n" + String(code_string.get_data()));
+ for (int i = 0; i < strings.size(); i++) {
//print_line("frag strings "+itos(i)+":"+String(strings[i]));
}
#endif
v.frag_id = glCreateShader(GL_FRAGMENT_SHADER);
- glShaderSource(v.frag_id,strings.size(),&strings[0],NULL);
+ glShaderSource(v.frag_id, strings.size(), &strings[0], NULL);
glCompileShader(v.frag_id);
-
- glGetShaderiv(v.frag_id,GL_COMPILE_STATUS,&status);
- if (status==GL_FALSE) {
- // error compiling
+
+ glGetShaderiv(v.frag_id, GL_COMPILE_STATUS, &status);
+ if (status == GL_FALSE) {
+ // error compiling
GLsizei iloglen;
- glGetShaderiv(v.frag_id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
+ glGetShaderiv(v.frag_id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
+ glDeleteProgram(v.id);
+ v.id = 0;
ERR_PRINT("NO LOG, WTF");
} else {
-
- if (iloglen==0) {
+
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
- char *ilogmem = (char*)Memory::alloc_static(iloglen+1);
- ilogmem[iloglen]=0;
- glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Fragment Program Compilation Failed:\n";
-
- err_string+=ilogmem;
- err_string=_fix_error_code_line(err_string,fragment_code_start,define_line_ofs);
+ char *ilogmem = (char *)Memory::alloc_static(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Fragment Program Compilation Failed:\n";
+
+ err_string += ilogmem;
+ err_string = _fix_error_code_line(err_string, fragment_code_start, define_line_ofs);
ERR_PRINT(err_string.ascii().get_data());
Memory::free_static(ilogmem);
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
- ERR_FAIL_V( NULL );
- }
-
- glAttachShader(v.id,v.frag_id);
- glAttachShader(v.id,v.vert_id);
+
+ ERR_FAIL_V(NULL);
+ }
+
+ glAttachShader(v.id, v.frag_id);
+ glAttachShader(v.id, v.vert_id);
// bind attributes before linking
- for (int i=0;i<attribute_pair_count;i++) {
+ for (int i = 0; i < attribute_pair_count; i++) {
- glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name );
+ glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name);
}
glLinkProgram(v.id);
-
+
glGetProgramiv(v.id, GL_LINK_STATUS, &status);
-
- if (status==GL_FALSE) {
- // error linking
+
+ if (status == GL_FALSE) {
+ // error linking
GLsizei iloglen;
- glGetProgramiv(v.id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
-
+ glGetProgramiv(v.id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
+
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
- ERR_FAIL_COND_V(iloglen<=0, NULL);
+ glDeleteProgram(v.id);
+ v.id = 0;
+ ERR_FAIL_COND_V(iloglen <= 0, NULL);
}
- if (iloglen==0) {
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
-
- char *ilogmem = (char*)Memory::alloc_static(iloglen+1);
- ilogmem[iloglen]=0;
- glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Program LINK FAILED:\n";
-
- err_string+=ilogmem;
- err_string=_fix_error_code_line(err_string,fragment_code_start,define_line_ofs);
+ char *ilogmem = (char *)Memory::alloc_static(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Program LINK FAILED:\n";
+
+ err_string += ilogmem;
+ err_string = _fix_error_code_line(err_string, fragment_code_start, define_line_ofs);
ERR_PRINT(err_string.ascii().get_data());
Memory::free_static(ilogmem);
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
+
ERR_FAIL_V(NULL);
}
-
- /* UNIFORMS */
-
- glUseProgram(v.id);
+ /* UNIFORMS */
+
+ glUseProgram(v.id);
//print_line("uniforms: ");
- for(int j=0;j<uniform_count;j++) {
-
-
- v.uniform_location[j]=glGetUniformLocation(v.id,uniform_names[j]);
+ for (int j = 0; j < uniform_count; j++) {
+
+ v.uniform_location[j] = glGetUniformLocation(v.id, uniform_names[j]);
//print_line("uniform "+String(uniform_names[j])+" location "+itos(v.uniform_location[j]));
}
-
+
// set texture uniforms
- for (int i=0;i<texunit_pair_count;i++) {
+ for (int i = 0; i < texunit_pair_count; i++) {
- GLint loc = glGetUniformLocation(v.id,texunit_pairs[i].name);
- if (loc>=0)
- glUniform1i(loc,texunit_pairs[i].index);
+ GLint loc = glGetUniformLocation(v.id, texunit_pairs[i].name);
+ if (loc >= 0)
+ glUniform1i(loc, texunit_pairs[i].index);
}
- if ( cc ) {
+ if (cc) {
v.custom_uniform_locations.resize(cc->custom_uniforms.size());
- for(int i=0;i<cc->custom_uniforms.size();i++) {
+ for (int i = 0; i < cc->custom_uniforms.size(); i++) {
- v.custom_uniform_locations[i]=glGetUniformLocation(v.id,String(cc->custom_uniforms[i]).ascii().get_data());
+ v.custom_uniform_locations[i] = glGetUniformLocation(v.id, String(cc->custom_uniforms[i]).ascii().get_data());
}
}
glUseProgram(0);
-
- v.ok=true;
+ v.ok = true;
return &v;
}
-GLint ShaderGLES2::get_uniform_location(const String& p_name) const {
+GLint ShaderGLES2::get_uniform_location(const String &p_name) const {
- ERR_FAIL_COND_V(!version,-1);
- return glGetUniformLocation(version->id,p_name.ascii().get_data());
+ ERR_FAIL_COND_V(!version, -1);
+ return glGetUniformLocation(version->id, p_name.ascii().get_data());
}
-
-void ShaderGLES2::setup(const char** p_conditional_defines, int p_conditional_count,const char** p_uniform_names,int p_uniform_count, const AttributePair* p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count,const char*p_vertex_code, const char *p_fragment_code,int p_vertex_code_start,int p_fragment_code_start) {
+void ShaderGLES2::setup(const char **p_conditional_defines, int p_conditional_count, const char **p_uniform_names, int p_uniform_count, const AttributePair *p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const char *p_vertex_code, const char *p_fragment_code, int p_vertex_code_start, int p_fragment_code_start) {
ERR_FAIL_COND(version);
- conditional_version.key=0;
- new_conditional_version.key=0;
- uniform_count=p_uniform_count;
- conditional_count=p_conditional_count;
- conditional_defines=p_conditional_defines;
- uniform_names=p_uniform_names;
- vertex_code=p_vertex_code;
- fragment_code=p_fragment_code;
- texunit_pairs=p_texunit_pairs;
- texunit_pair_count=p_texunit_pair_count;
- vertex_code_start=p_vertex_code_start;
- fragment_code_start=p_fragment_code_start;
- attribute_pairs=p_attribute_pairs;
- attribute_pair_count=p_attribute_count;
+ conditional_version.key = 0;
+ new_conditional_version.key = 0;
+ uniform_count = p_uniform_count;
+ conditional_count = p_conditional_count;
+ conditional_defines = p_conditional_defines;
+ uniform_names = p_uniform_names;
+ vertex_code = p_vertex_code;
+ fragment_code = p_fragment_code;
+ texunit_pairs = p_texunit_pairs;
+ texunit_pair_count = p_texunit_pair_count;
+ vertex_code_start = p_vertex_code_start;
+ fragment_code_start = p_fragment_code_start;
+ attribute_pairs = p_attribute_pairs;
+ attribute_pair_count = p_attribute_count;
//split vertex and shader code (thank you, retarded shader compiler programmers from you know what company).
{
- String globals_tag="\nVERTEX_SHADER_GLOBALS";
- String code_tag="\nVERTEX_SHADER_CODE";
- String code = vertex_code;
+ String globals_tag = "\nVERTEX_SHADER_GLOBALS";
+ String code_tag = "\nVERTEX_SHADER_CODE";
+ String code = vertex_code;
int cpos = code.find(globals_tag);
- if (cpos==-1) {
- vertex_code0=code.ascii();
+ if (cpos == -1) {
+ vertex_code0 = code.ascii();
} else {
- vertex_code0=code.substr(0,cpos).ascii();
- code = code.substr(cpos+globals_tag.length(),code.length());
+ vertex_code0 = code.substr(0, cpos).ascii();
+ code = code.substr(cpos + globals_tag.length(), code.length());
cpos = code.find(code_tag);
- if (cpos==-1) {
- vertex_code1=code.ascii();
+ if (cpos == -1) {
+ vertex_code1 = code.ascii();
} else {
- vertex_code1=code.substr(0,cpos).ascii();
- vertex_code2=code.substr(cpos+code_tag.length(),code.length()).ascii();
+ vertex_code1 = code.substr(0, cpos).ascii();
+ vertex_code2 = code.substr(cpos + code_tag.length(), code.length()).ascii();
}
}
}
{
- String globals_tag="\nFRAGMENT_SHADER_GLOBALS";
- String code_tag="\nFRAGMENT_SHADER_CODE";
- String light_code_tag="\nLIGHT_SHADER_CODE";
- String code = fragment_code;
+ String globals_tag = "\nFRAGMENT_SHADER_GLOBALS";
+ String code_tag = "\nFRAGMENT_SHADER_CODE";
+ String light_code_tag = "\nLIGHT_SHADER_CODE";
+ String code = fragment_code;
int cpos = code.find(globals_tag);
- if (cpos==-1) {
- fragment_code0=code.ascii();
+ if (cpos == -1) {
+ fragment_code0 = code.ascii();
} else {
- fragment_code0=code.substr(0,cpos).ascii();
- code = code.substr(cpos+globals_tag.length(),code.length());
+ fragment_code0 = code.substr(0, cpos).ascii();
+ code = code.substr(cpos + globals_tag.length(), code.length());
cpos = code.find(code_tag);
- if (cpos==-1) {
- fragment_code1=code.ascii();
+ if (cpos == -1) {
+ fragment_code1 = code.ascii();
} else {
- fragment_code1=code.substr(0,cpos).ascii();
- String code2 = code.substr(cpos+code_tag.length(),code.length());
+ fragment_code1 = code.substr(0, cpos).ascii();
+ String code2 = code.substr(cpos + code_tag.length(), code.length());
cpos = code2.find(light_code_tag);
- if (cpos==-1) {
- fragment_code2=code2.ascii();
+ if (cpos == -1) {
+ fragment_code2 = code2.ascii();
} else {
- fragment_code2=code2.substr(0,cpos).ascii();
- fragment_code3 = code2.substr(cpos+light_code_tag.length(),code2.length()).ascii();
+ fragment_code2 = code2.substr(0, cpos).ascii();
+ fragment_code3 = code2.substr(cpos + light_code_tag.length(), code2.length()).ascii();
}
}
}
}
-
}
void ShaderGLES2::finish() {
-
- const VersionKey *V=NULL;
- while((V=version_map.next(V))) {
-
- Version &v=version_map[*V];
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- memdelete_arr( v.uniform_location );
+ const VersionKey *V = NULL;
+ while ((V = version_map.next(V))) {
+
+ Version &v = version_map[*V];
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ memdelete_arr(v.uniform_location);
}
-
}
-
void ShaderGLES2::clear_caches() {
- const VersionKey *V=NULL;
- while((V=version_map.next(V))) {
-
- Version &v=version_map[*V];
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- memdelete_arr( v.uniform_location );
+ const VersionKey *V = NULL;
+ while ((V = version_map.next(V))) {
+
+ Version &v = version_map[*V];
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ memdelete_arr(v.uniform_location);
}
version_map.clear();
custom_code_map.clear();
- version=NULL;
- last_custom_code=1;
+ version = NULL;
+ last_custom_code = 1;
uniforms_dirty = true;
-
}
uint32_t ShaderGLES2::create_custom_shader() {
- custom_code_map[last_custom_code]=CustomCode();
- custom_code_map[last_custom_code].version=1;
+ custom_code_map[last_custom_code] = CustomCode();
+ custom_code_map[last_custom_code].version = 1;
return last_custom_code++;
}
-void ShaderGLES2::set_custom_shader_code(uint32_t p_code_id, const String& p_vertex, const String& p_vertex_globals,const String& p_fragment,const String& p_light, const String& p_fragment_globals,const Vector<StringName>& p_uniforms,const Vector<const char*> &p_custom_defines) {
+void ShaderGLES2::set_custom_shader_code(uint32_t p_code_id, const String &p_vertex, const String &p_vertex_globals, const String &p_fragment, const String &p_light, const String &p_fragment_globals, const Vector<StringName> &p_uniforms, const Vector<const char *> &p_custom_defines) {
ERR_FAIL_COND(!custom_code_map.has(p_code_id));
- CustomCode *cc=&custom_code_map[p_code_id];
-
- cc->vertex=p_vertex;
- cc->vertex_globals=p_vertex_globals;
- cc->fragment=p_fragment;
- cc->fragment_globals=p_fragment_globals;
- cc->light=p_light;
- cc->custom_uniforms=p_uniforms;
- cc->custom_defines=p_custom_defines;
+ CustomCode *cc = &custom_code_map[p_code_id];
+
+ cc->vertex = p_vertex;
+ cc->vertex_globals = p_vertex_globals;
+ cc->fragment = p_fragment;
+ cc->fragment_globals = p_fragment_globals;
+ cc->light = p_light;
+ cc->custom_uniforms = p_uniforms;
+ cc->custom_defines = p_custom_defines;
cc->version++;
}
void ShaderGLES2::set_custom_shader(uint32_t p_code_id) {
- new_conditional_version.code_version=p_code_id;
+ new_conditional_version.code_version = p_code_id;
}
void ShaderGLES2::free_custom_shader(uint32_t p_code_id) {
- /* if (! custom_code_map.has( p_code_id )) {
+ /* if (! custom_code_map.has( p_code_id )) {
print_line("no code id "+itos(p_code_id));
} else {
print_line("freed code id "+itos(p_code_id));
}*/
- ERR_FAIL_COND(! custom_code_map.has( p_code_id ));
- if (conditional_version.code_version==p_code_id)
- conditional_version.code_version=0; //bye
+ ERR_FAIL_COND(!custom_code_map.has(p_code_id));
+ if (conditional_version.code_version == p_code_id)
+ conditional_version.code_version = 0; //bye
custom_code_map.erase(p_code_id);
-
}
-
-
ShaderGLES2::ShaderGLES2() {
- version=NULL;
- last_custom_code=1;
+ version = NULL;
+ last_custom_code = 1;
uniforms_dirty = true;
}
-
ShaderGLES2::~ShaderGLES2() {
-
+
finish();
}
-
#endif
diff --git a/drivers/gles2/shader_gles2.h b/drivers/gles2/shader_gles2.h
index 004d636c1e..a292fda7fe 100644
--- a/drivers/gles2/shader_gles2.h
+++ b/drivers/gles2/shader_gles2.h
@@ -38,19 +38,17 @@
#include GLES2_INCLUDE_H
#endif
+#include "camera_matrix.h"
#include "hash_map.h"
#include "map.h"
#include "variant.h"
-#include "camera_matrix.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class ShaderGLES2 {
-protected:
-
+protected:
struct Enum {
uint64_t mask;
@@ -71,7 +69,7 @@ protected:
};
struct UniformPair {
- const char* name;
+ const char *name;
Variant::Type type_hint;
};
@@ -82,8 +80,8 @@ protected:
};
bool uniforms_dirty;
-private:
+private:
//@TODO Optimize to a fixed set of shader pools and use a LRU
int uniform_count;
int texunit_pair_count;
@@ -101,23 +99,25 @@ private:
String light;
uint32_t version;
Vector<StringName> custom_uniforms;
- Vector<const char*> custom_defines;
-
+ Vector<const char *> custom_defines;
};
-
struct Version {
-
+
GLuint id;
GLuint vert_id;
- GLuint frag_id;
+ GLuint frag_id;
GLint *uniform_location;
Vector<GLint> custom_uniform_locations;
uint32_t code_version;
bool ok;
- Version() { code_version=0; ok=false; uniform_location=NULL; }
+ Version() {
+ code_version = 0;
+ ok = false;
+ uniform_location = NULL;
+ }
};
-
+
Version *version;
union VersionKey {
@@ -127,34 +127,32 @@ private:
uint32_t code_version;
};
uint64_t key;
- bool operator==(const VersionKey& p_key) const { return key==p_key.key; }
- bool operator<(const VersionKey& p_key) const { return key<p_key.key; }
-
+ bool operator==(const VersionKey &p_key) const { return key == p_key.key; }
+ bool operator<(const VersionKey &p_key) const { return key < p_key.key; }
};
struct VersionKeyHash {
- static _FORCE_INLINE_ uint32_t hash( const VersionKey& p_key) { return HashMapHasherDefault::hash(p_key.key); };
+ static _FORCE_INLINE_ uint32_t hash(const VersionKey &p_key) { return HashMapHasherDefault::hash(p_key.key); };
};
//this should use a way more cachefriendly version..
- HashMap<VersionKey,Version,VersionKeyHash> version_map;
+ HashMap<VersionKey, Version, VersionKeyHash> version_map;
- HashMap<uint32_t,CustomCode> custom_code_map;
+ HashMap<uint32_t, CustomCode> custom_code_map;
uint32_t last_custom_code;
-
-
+
VersionKey conditional_version;
VersionKey new_conditional_version;
-
- virtual String get_shader_name() const=0;
-
- const char** conditional_defines;
- const char** uniform_names;
+
+ virtual String get_shader_name() const = 0;
+
+ const char **conditional_defines;
+ const char **uniform_names;
const AttributePair *attribute_pairs;
const TexUnitPair *texunit_pairs;
- const char* vertex_code;
- const char* fragment_code;
+ const char *vertex_code;
+ const char *fragment_code;
CharString fragment_code0;
CharString fragment_code1;
CharString fragment_code2;
@@ -164,204 +162,196 @@ private:
CharString vertex_code1;
CharString vertex_code2;
- Version * get_current_version();
-
+ Version *get_current_version();
+
static ShaderGLES2 *active;
- _FORCE_INLINE_ void _set_uniform_variant(GLint p_uniform,const Variant& p_value) {
+ _FORCE_INLINE_ void _set_uniform_variant(GLint p_uniform, const Variant &p_value) {
- if (p_uniform<0)
+ if (p_uniform < 0)
return; // do none
- switch(p_value.get_type()) {
+ switch (p_value.get_type()) {
- case Variant::BOOL:
- case Variant::INT:/* {
+ case Variant::BOOL:
+ case Variant::INT: /* {
int val=p_value;
glUniform1i( p_uniform, val );
} break; */
- case Variant::REAL: {
-
- real_t val=p_value;
- glUniform1f( p_uniform, val );
- } break;
- case Variant::COLOR: {
-
- Color val=p_value;
- glUniform4f( p_uniform, val.r, val.g,val.b,val.a );
- } break;
- case Variant::VECTOR2: {
-
- Vector2 val=p_value;
- glUniform2f( p_uniform, val.x,val.y );
- } break;
- case Variant::VECTOR3: {
-
- Vector3 val=p_value;
- glUniform3f( p_uniform, val.x,val.y,val.z );
- } break;
- case Variant::PLANE: {
-
- Plane val=p_value;
- glUniform4f( p_uniform, val.normal.x,val.normal.y,val.normal.z,val.d );
- } break;
- case Variant::QUAT: {
-
- Quat val=p_value;
- glUniform4f( p_uniform, val.x,val.y,val.z,val.w );
- } break;
-
- case Variant::MATRIX32: {
-
- Transform2D tr=p_value;
- GLfloat matrix[16]={ /* build a 16x16 matrix */
- tr.elements[0][0],
- tr.elements[0][1],
- 0,
- 0,
- tr.elements[1][0],
- tr.elements[1][1],
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- tr.elements[2][0],
- tr.elements[2][1],
- 0,
- 1
- };
-
- glUniformMatrix4fv(p_uniform,1,false,matrix);
-
- } break;
- case Variant::MATRIX3:
- case Variant::TRANSFORM: {
-
- Transform tr=p_value;
- GLfloat matrix[16]={ /* build a 16x16 matrix */
- tr.basis.elements[0][0],
- tr.basis.elements[1][0],
- tr.basis.elements[2][0],
- 0,
- tr.basis.elements[0][1],
- tr.basis.elements[1][1],
- tr.basis.elements[2][1],
- 0,
- tr.basis.elements[0][2],
- tr.basis.elements[1][2],
- tr.basis.elements[2][2],
- 0,
- tr.origin.x,
- tr.origin.y,
- tr.origin.z,
- 1
- };
-
-
- glUniformMatrix4fv(p_uniform,1,false,matrix);
- } break;
- default: { ERR_FAIL(); } // do nothing
-
- }
+ case Variant::REAL: {
+
+ real_t val = p_value;
+ glUniform1f(p_uniform, val);
+ } break;
+ case Variant::COLOR: {
+
+ Color val = p_value;
+ glUniform4f(p_uniform, val.r, val.g, val.b, val.a);
+ } break;
+ case Variant::VECTOR2: {
+
+ Vector2 val = p_value;
+ glUniform2f(p_uniform, val.x, val.y);
+ } break;
+ case Variant::VECTOR3: {
+
+ Vector3 val = p_value;
+ glUniform3f(p_uniform, val.x, val.y, val.z);
+ } break;
+ case Variant::PLANE: {
+
+ Plane val = p_value;
+ glUniform4f(p_uniform, val.normal.x, val.normal.y, val.normal.z, val.d);
+ } break;
+ case Variant::QUAT: {
+
+ Quat val = p_value;
+ glUniform4f(p_uniform, val.x, val.y, val.z, val.w);
+ } break;
+
+ case Variant::MATRIX32: {
+
+ Transform2D tr = p_value;
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
+ tr.elements[0][0],
+ tr.elements[0][1],
+ 0,
+ 0,
+ tr.elements[1][0],
+ tr.elements[1][1],
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ tr.elements[2][0],
+ tr.elements[2][1],
+ 0,
+ 1
+ };
+
+ glUniformMatrix4fv(p_uniform, 1, false, matrix);
+
+ } break;
+ case Variant::MATRIX3:
+ case Variant::TRANSFORM: {
+
+ Transform tr = p_value;
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
+ tr.basis.elements[0][0],
+ tr.basis.elements[1][0],
+ tr.basis.elements[2][0],
+ 0,
+ tr.basis.elements[0][1],
+ tr.basis.elements[1][1],
+ tr.basis.elements[2][1],
+ 0,
+ tr.basis.elements[0][2],
+ tr.basis.elements[1][2],
+ tr.basis.elements[2][2],
+ 0,
+ tr.origin.x,
+ tr.origin.y,
+ tr.origin.z,
+ 1
+ };
+
+ glUniformMatrix4fv(p_uniform, 1, false, matrix);
+ } break;
+ default: { ERR_FAIL(); } // do nothing
+ }
}
- Map<uint32_t,Variant> uniform_defaults;
- Map<uint32_t,CameraMatrix> uniform_cameras;
-
-
-protected:
+ Map<uint32_t, Variant> uniform_defaults;
+ Map<uint32_t, CameraMatrix> uniform_cameras;
+protected:
_FORCE_INLINE_ int _get_uniform(int p_which) const;
_FORCE_INLINE_ void _set_conditional(int p_which, bool p_value);
-
- void setup(const char** p_conditional_defines, int p_conditional_count,const char** p_uniform_names,int p_uniform_count, const AttributePair* p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count,const char*p_vertex_code, const char *p_fragment_code,int p_vertex_code_start,int p_fragment_code_start);
-
+
+ void setup(const char **p_conditional_defines, int p_conditional_count, const char **p_uniform_names, int p_uniform_count, const AttributePair *p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const char *p_vertex_code, const char *p_fragment_code, int p_vertex_code_start, int p_fragment_code_start);
+
ShaderGLES2();
+
public:
-
enum {
- CUSTOM_SHADER_DISABLED=0
+ CUSTOM_SHADER_DISABLED = 0
};
- GLint get_uniform_location(const String& p_name) const;
+ GLint get_uniform_location(const String &p_name) const;
GLint get_uniform_location(int p_uniform) const;
-
+
static _FORCE_INLINE_ ShaderGLES2 *get_active() { return active; };
bool bind();
void unbind();
void bind_uniforms();
-
- inline GLuint get_program() const { return version?version->id:0; }
-
+ inline GLuint get_program() const { return version ? version->id : 0; }
+
void clear_caches();
uint32_t create_custom_shader();
- void set_custom_shader_code(uint32_t p_id,const String& p_vertex, const String& p_vertex_globals,const String& p_fragment,const String& p_p_light,const String& p_fragment_globals,const Vector<StringName>& p_uniforms,const Vector<const char*> &p_custom_defines);
+ void set_custom_shader_code(uint32_t p_id, const String &p_vertex, const String &p_vertex_globals, const String &p_fragment, const String &p_p_light, const String &p_fragment_globals, const Vector<StringName> &p_uniforms, const Vector<const char *> &p_custom_defines);
void set_custom_shader(uint32_t p_id);
void free_custom_shader(uint32_t p_id);
- void set_uniform_default(int p_idx, const Variant& p_value) {
+ void set_uniform_default(int p_idx, const Variant &p_value) {
- if (p_value.get_type()==Variant::NIL) {
+ if (p_value.get_type() == Variant::NIL) {
uniform_defaults.erase(p_idx);
} else {
- uniform_defaults[p_idx]=p_value;
+ uniform_defaults[p_idx] = p_value;
}
uniforms_dirty = true;
};
uint32_t get_version() const { return new_conditional_version.version; }
- void set_uniform_camera(int p_idx, const CameraMatrix& p_mat) {
+ void set_uniform_camera(int p_idx, const CameraMatrix &p_mat) {
uniform_cameras[p_idx] = p_mat;
uniforms_dirty = true;
};
- _FORCE_INLINE_ void set_custom_uniform(int p_idx, const Variant& p_value) {
+ _FORCE_INLINE_ void set_custom_uniform(int p_idx, const Variant &p_value) {
ERR_FAIL_COND(!version);
- ERR_FAIL_INDEX(p_idx,version->custom_uniform_locations.size());
- _set_uniform_variant( version->custom_uniform_locations[p_idx], p_value );
+ ERR_FAIL_INDEX(p_idx, version->custom_uniform_locations.size());
+ _set_uniform_variant(version->custom_uniform_locations[p_idx], p_value);
}
-
+
_FORCE_INLINE_ GLint get_custom_uniform_location(int p_idx) {
- ERR_FAIL_COND_V(!version,-1);
- ERR_FAIL_INDEX_V(p_idx,version->custom_uniform_locations.size(),-1);
+ ERR_FAIL_COND_V(!version, -1);
+ ERR_FAIL_INDEX_V(p_idx, version->custom_uniform_locations.size(), -1);
return version->custom_uniform_locations[p_idx];
}
- virtual void init()=0;
+ virtual void init() = 0;
void finish();
virtual ~ShaderGLES2();
-
};
-
-// called a lot, made inline
-
+// called a lot, made inline
int ShaderGLES2::_get_uniform(int p_which) const {
-
- ERR_FAIL_INDEX_V( p_which, uniform_count,-1 );
- ERR_FAIL_COND_V( !version, -1 );
+
+ ERR_FAIL_INDEX_V(p_which, uniform_count, -1);
+ ERR_FAIL_COND_V(!version, -1);
return version->uniform_location[p_which];
}
void ShaderGLES2::_set_conditional(int p_which, bool p_value) {
-
- ERR_FAIL_INDEX(p_which,conditional_count);
+
+ ERR_FAIL_INDEX(p_which, conditional_count);
if (p_value)
- new_conditional_version.version|=(1<<p_which);
+ new_conditional_version.version |= (1 << p_which);
else
- new_conditional_version.version&=~(1<<p_which);
+ new_conditional_version.version &= ~(1 << p_which);
}
#endif
diff --git a/drivers/gles3/rasterizer_canvas_gles3.cpp b/drivers/gles3/rasterizer_canvas_gles3.cpp
index 2526aad074..26d13bad89 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.cpp
+++ b/drivers/gles3/rasterizer_canvas_gles3.cpp
@@ -34,60 +34,58 @@
#define glClearDepth glClearDepthf
#endif
-static _FORCE_INLINE_ void store_transform2d(const Transform2D& p_mtx, float* p_array) {
-
- p_array[ 0]=p_mtx.elements[0][0];
- p_array[ 1]=p_mtx.elements[0][1];
- p_array[ 2]=0;
- p_array[ 3]=0;
- p_array[ 4]=p_mtx.elements[1][0];
- p_array[ 5]=p_mtx.elements[1][1];
- p_array[ 6]=0;
- p_array[ 7]=0;
- p_array[ 8]=0;
- p_array[ 9]=0;
- p_array[10]=1;
- p_array[11]=0;
- p_array[12]=p_mtx.elements[2][0];
- p_array[13]=p_mtx.elements[2][1];
- p_array[14]=0;
- p_array[15]=1;
+static _FORCE_INLINE_ void store_transform2d(const Transform2D &p_mtx, float *p_array) {
+
+ p_array[0] = p_mtx.elements[0][0];
+ p_array[1] = p_mtx.elements[0][1];
+ p_array[2] = 0;
+ p_array[3] = 0;
+ p_array[4] = p_mtx.elements[1][0];
+ p_array[5] = p_mtx.elements[1][1];
+ p_array[6] = 0;
+ p_array[7] = 0;
+ p_array[8] = 0;
+ p_array[9] = 0;
+ p_array[10] = 1;
+ p_array[11] = 0;
+ p_array[12] = p_mtx.elements[2][0];
+ p_array[13] = p_mtx.elements[2][1];
+ p_array[14] = 0;
+ p_array[15] = 1;
}
-
-static _FORCE_INLINE_ void store_transform(const Transform& p_mtx, float* p_array) {
- p_array[ 0]=p_mtx.basis.elements[0][0];
- p_array[ 1]=p_mtx.basis.elements[1][0];
- p_array[ 2]=p_mtx.basis.elements[2][0];
- p_array[ 3]=0;
- p_array[ 4]=p_mtx.basis.elements[0][1];
- p_array[ 5]=p_mtx.basis.elements[1][1];
- p_array[ 6]=p_mtx.basis.elements[2][1];
- p_array[ 7]=0;
- p_array[ 8]=p_mtx.basis.elements[0][2];
- p_array[ 9]=p_mtx.basis.elements[1][2];
- p_array[10]=p_mtx.basis.elements[2][2];
- p_array[11]=0;
- p_array[12]=p_mtx.origin.x;
- p_array[13]=p_mtx.origin.y;
- p_array[14]=p_mtx.origin.z;
- p_array[15]=1;
+static _FORCE_INLINE_ void store_transform(const Transform &p_mtx, float *p_array) {
+ p_array[0] = p_mtx.basis.elements[0][0];
+ p_array[1] = p_mtx.basis.elements[1][0];
+ p_array[2] = p_mtx.basis.elements[2][0];
+ p_array[3] = 0;
+ p_array[4] = p_mtx.basis.elements[0][1];
+ p_array[5] = p_mtx.basis.elements[1][1];
+ p_array[6] = p_mtx.basis.elements[2][1];
+ p_array[7] = 0;
+ p_array[8] = p_mtx.basis.elements[0][2];
+ p_array[9] = p_mtx.basis.elements[1][2];
+ p_array[10] = p_mtx.basis.elements[2][2];
+ p_array[11] = 0;
+ p_array[12] = p_mtx.origin.x;
+ p_array[13] = p_mtx.origin.y;
+ p_array[14] = p_mtx.origin.z;
+ p_array[15] = 1;
}
-static _FORCE_INLINE_ void store_camera(const CameraMatrix& p_mtx, float* p_array) {
+static _FORCE_INLINE_ void store_camera(const CameraMatrix &p_mtx, float *p_array) {
- for (int i=0;i<4;i++) {
- for (int j=0;j<4;j++) {
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
- p_array[i*4+j]=p_mtx.matrix[i][j];
+ p_array[i * 4 + j] = p_mtx.matrix[i][j];
}
}
}
-
RID RasterizerCanvasGLES3::light_internal_create() {
- LightInternal * li = memnew( LightInternal );
+ LightInternal *li = memnew(LightInternal);
glGenBuffers(1, &li->ubo);
glBindBuffer(GL_UNIFORM_BUFFER, li->ubo);
@@ -97,60 +95,56 @@ RID RasterizerCanvasGLES3::light_internal_create() {
return light_internal_owner.make_rid(li);
}
-void RasterizerCanvasGLES3::light_internal_update(RID p_rid, Light* p_light) {
+void RasterizerCanvasGLES3::light_internal_update(RID p_rid, Light *p_light) {
- LightInternal * li = light_internal_owner.getornull(p_rid);
+ LightInternal *li = light_internal_owner.getornull(p_rid);
ERR_FAIL_COND(!li);
- store_transform2d(p_light->light_shader_xform,li->ubo_data.light_matrix);
- store_transform2d(p_light->xform_cache.affine_inverse(),li->ubo_data.local_matrix);
- store_camera(p_light->shadow_matrix_cache,li->ubo_data.shadow_matrix);
+ store_transform2d(p_light->light_shader_xform, li->ubo_data.light_matrix);
+ store_transform2d(p_light->xform_cache.affine_inverse(), li->ubo_data.local_matrix);
+ store_camera(p_light->shadow_matrix_cache, li->ubo_data.shadow_matrix);
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- li->ubo_data.color[i]=p_light->color[i]*p_light->energy;
- li->ubo_data.shadow_color[i]=p_light->shadow_color[i];
+ li->ubo_data.color[i] = p_light->color[i] * p_light->energy;
+ li->ubo_data.shadow_color[i] = p_light->shadow_color[i];
}
- li->ubo_data.light_pos[0]=p_light->light_shader_pos.x;
- li->ubo_data.light_pos[1]=p_light->light_shader_pos.y;
- li->ubo_data.shadowpixel_size=1.0/p_light->shadow_buffer_size;
- li->ubo_data.light_outside_alpha=p_light->mode==VS::CANVAS_LIGHT_MODE_MASK?1.0:0.0;
- li->ubo_data.light_height=p_light->height;
- if (p_light->radius_cache==0)
- li->ubo_data.shadow_gradient=0;
+ li->ubo_data.light_pos[0] = p_light->light_shader_pos.x;
+ li->ubo_data.light_pos[1] = p_light->light_shader_pos.y;
+ li->ubo_data.shadowpixel_size = 1.0 / p_light->shadow_buffer_size;
+ li->ubo_data.light_outside_alpha = p_light->mode == VS::CANVAS_LIGHT_MODE_MASK ? 1.0 : 0.0;
+ li->ubo_data.light_height = p_light->height;
+ if (p_light->radius_cache == 0)
+ li->ubo_data.shadow_gradient = 0;
else
- li->ubo_data.shadow_gradient=p_light->shadow_gradient_length/(p_light->radius_cache*1.1);
-
- li->ubo_data.shadow_distance_mult=(p_light->radius_cache*1.1);
+ li->ubo_data.shadow_gradient = p_light->shadow_gradient_length / (p_light->radius_cache * 1.1);
+ li->ubo_data.shadow_distance_mult = (p_light->radius_cache * 1.1);
glBindBuffer(GL_UNIFORM_BUFFER, li->ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(LightInternal::UBOData), &li->ubo_data);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightInternal::UBOData), &li->ubo_data);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
}
void RasterizerCanvasGLES3::light_internal_free(RID p_rid) {
- LightInternal * li = light_internal_owner.getornull(p_rid);
+ LightInternal *li = light_internal_owner.getornull(p_rid);
ERR_FAIL_COND(!li);
- glDeleteBuffers(1,&li->ubo);
+ glDeleteBuffers(1, &li->ubo);
light_internal_owner.free(p_rid);
memdelete(li);
-
}
-void RasterizerCanvasGLES3::canvas_begin(){
+void RasterizerCanvasGLES3::canvas_begin() {
if (storage->frame.current_rt && storage->frame.clear_request) {
// a clear request may be pending, so do it
- glClearColor( storage->frame.clear_request_color.r, storage->frame.clear_request_color.g, storage->frame.clear_request_color.b, storage->frame.clear_request_color.a );
+ glClearColor(storage->frame.clear_request_color.r, storage->frame.clear_request_color.g, storage->frame.clear_request_color.b, storage->frame.clear_request_color.a);
glClear(GL_COLOR_BUFFER_BIT);
- storage->frame.clear_request=false;
-
+ storage->frame.clear_request = false;
}
/*canvas_shader.unbind();
@@ -162,138 +156,118 @@ void RasterizerCanvasGLES3::canvas_begin(){
reset_canvas();
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT,true);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,false);
-
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT, true);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD, false);
state.canvas_shader.set_custom_shader(0);
state.canvas_shader.bind();
- state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,Color(1,1,1,1));
- state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,Transform2D());
- state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform2D());
-
-
-
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, Color(1, 1, 1, 1));
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, Transform2D());
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, Transform2D());
//state.canvas_shader.set_uniform(CanvasShaderGLES3::PROJECTION_MATRIX,state.vp);
//state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,Transform());
//state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform());
- glBindBufferBase(GL_UNIFORM_BUFFER,0,state.canvas_item_ubo);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.canvas_item_ubo);
glBindVertexArray(data.canvas_quad_array);
- state.using_texture_rect=true;
-
-
+ state.using_texture_rect = true;
}
-
-void RasterizerCanvasGLES3::canvas_end(){
-
+void RasterizerCanvasGLES3::canvas_end() {
glBindVertexArray(0);
- glBindBufferBase(GL_UNIFORM_BUFFER,0,0);
-
- state.using_texture_rect=false;
+ glBindBufferBase(GL_UNIFORM_BUFFER, 0, 0);
+ state.using_texture_rect = false;
}
+RasterizerStorageGLES3::Texture *RasterizerCanvasGLES3::_bind_canvas_texture(const RID &p_texture) {
-
-RasterizerStorageGLES3::Texture* RasterizerCanvasGLES3::_bind_canvas_texture(const RID& p_texture) {
-
- if (p_texture==state.current_tex) {
+ if (p_texture == state.current_tex) {
return state.current_tex_ptr;
}
if (p_texture.is_valid()) {
-
- RasterizerStorageGLES3::Texture*texture=storage->texture_owner.getornull(p_texture);
+ RasterizerStorageGLES3::Texture *texture = storage->texture_owner.getornull(p_texture);
if (!texture) {
- state.current_tex=RID();
- state.current_tex_ptr=NULL;
- glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
+ state.current_tex = RID();
+ state.current_tex_ptr = NULL;
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
return NULL;
}
if (texture->render_target)
- texture->render_target->used_in_frame=true;
+ texture->render_target->used_in_frame = true;
- glBindTexture(GL_TEXTURE_2D,texture->tex_id);
- state.current_tex=p_texture;
- state.current_tex_ptr=texture;
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
+ state.current_tex = p_texture;
+ state.current_tex_ptr = texture;
return texture;
-
} else {
-
- glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
- state.current_tex=RID();
- state.current_tex_ptr=NULL;
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
+ state.current_tex = RID();
+ state.current_tex_ptr = NULL;
}
-
return NULL;
}
void RasterizerCanvasGLES3::_set_texture_rect_mode(bool p_enable) {
- if (state.using_texture_rect==p_enable)
+ if (state.using_texture_rect == p_enable)
return;
if (p_enable) {
glBindVertexArray(data.canvas_quad_array);
-
} else {
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
-
-
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT,p_enable);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT, p_enable);
state.canvas_shader.bind();
- state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix);
-
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, state.canvas_item_modulate);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, state.extra_matrix);
- state.using_texture_rect=p_enable;
+ state.using_texture_rect = p_enable;
}
+void RasterizerCanvasGLES3::_draw_polygon(int p_vertex_count, const int *p_indices, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, const RID &p_texture, bool p_singlecolor) {
-void RasterizerCanvasGLES3::_draw_polygon(int p_vertex_count, const int* p_indices, const Vector2* p_vertices, const Vector2* p_uvs, const Color* p_colors,const RID& p_texture,bool p_singlecolor) {
-
- bool do_colors=false;
+ bool do_colors = false;
Color m;
if (p_singlecolor) {
m = *p_colors;
- glVertexAttrib4f(VS::ARRAY_COLOR,m.r,m.g,m.b,m.a);
+ glVertexAttrib4f(VS::ARRAY_COLOR, m.r, m.g, m.b, m.a);
} else if (!p_colors) {
- glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1);
+ glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
} else
- do_colors=true;
+ do_colors = true;
RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(p_texture);
#ifndef GLES_NO_CLIENT_ARRAYS
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(Vector2), p_vertices );
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(Vector2), p_vertices);
if (do_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(Color), p_colors );
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), p_colors);
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
@@ -301,71 +275,69 @@ void RasterizerCanvasGLES3::_draw_polygon(int p_vertex_count, const int* p_indic
if (texture && p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs );
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), p_uvs);
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
if (p_indices) {
- glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_INT, p_indices );
+ glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_INT, p_indices);
} else {
- glDrawArrays(GL_TRIANGLES,0,p_vertex_count);
+ glDrawArrays(GL_TRIANGLES, 0, p_vertex_count);
}
-
#else //WebGL specific impl.
glBindBuffer(GL_ARRAY_BUFFER, gui_quad_buffer);
float *b = GlobalVertexBuffer;
int ofs = 0;
- if(p_vertex_count > MAX_POLYGON_VERTICES){
+ if (p_vertex_count > MAX_POLYGON_VERTICES) {
print_line("Too many vertices to render");
return;
}
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_vertices[i].x;
- b[ofs++]=p_vertices[i].y;
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_vertices[i].x;
+ b[ofs++] = p_vertices[i].y;
}
if (p_colors && do_colors) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(float)*4, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_colors[i].r;
- b[ofs++]=p_colors[i].g;
- b[ofs++]=p_colors[i].b;
- b[ofs++]=p_colors[i].a;
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(float) * 4, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_colors[i].r;
+ b[ofs++] = p_colors[i].g;
+ b[ofs++] = p_colors[i].b;
+ b[ofs++] = p_colors[i].a;
}
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
}
-
if (p_uvs) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs );
- for(int i=0;i<p_vertex_count;i++) {
- b[ofs++]=p_uvs[i].x;
- b[ofs++]=p_uvs[i].y;
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(float) * 2, ((float *)0) + ofs);
+ for (int i = 0; i < p_vertex_count; i++) {
+ b[ofs++] = p_uvs[i].x;
+ b[ofs++] = p_uvs[i].y;
}
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV);
}
- glBufferSubData(GL_ARRAY_BUFFER,0,ofs*4,&b[0]);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, ofs * 4, &b[0]);
//bind the indices buffer.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
- static const int _max_draw_poly_indices = 16*1024; // change this size if needed!!!
+ static const int _max_draw_poly_indices = 16 * 1024; // change this size if needed!!!
ERR_FAIL_COND(p_vertex_count > _max_draw_poly_indices);
static uint16_t _draw_poly_indices[_max_draw_poly_indices];
- for (int i=0; i<p_vertex_count; i++) {
+ for (int i = 0; i < p_vertex_count; i++) {
_draw_poly_indices[i] = p_indices[i];
//OS::get_singleton()->print("ind: %d ", p_indices[i]);
};
@@ -381,99 +353,88 @@ void RasterizerCanvasGLES3::_draw_polygon(int p_vertex_count, const int* p_indic
#endif
storage->frame.canvas_draw_commands++;
-
}
-void RasterizerCanvasGLES3::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs) {
-
-
-
- static const GLenum prim[5]={GL_POINTS,GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+void RasterizerCanvasGLES3::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs) {
+ static const GLenum prim[5] = { GL_POINTS, GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN };
//#define GLES_USE_PRIMITIVE_BUFFER
- int version=0;
- int color_ofs=0;
- int uv_ofs=0;
- int stride=2;
+ int version = 0;
+ int color_ofs = 0;
+ int uv_ofs = 0;
+ int stride = 2;
if (p_colors) { //color
- version|=1;
- color_ofs=stride;
- stride+=4;
+ version |= 1;
+ color_ofs = stride;
+ stride += 4;
}
if (p_uvs) { //uv
- version|=2;
- uv_ofs=stride;
- stride+=2;
+ version |= 2;
+ uv_ofs = stride;
+ stride += 2;
}
+ float b[(2 + 2 + 4) * 4];
- float b[(2+2+4)*4];
-
-
- for(int i=0;i<p_points;i++) {
- b[stride*i+0]=p_vertices[i].x;
- b[stride*i+1]=p_vertices[i].y;
+ for (int i = 0; i < p_points; i++) {
+ b[stride * i + 0] = p_vertices[i].x;
+ b[stride * i + 1] = p_vertices[i].y;
}
if (p_colors) {
- for(int i=0;i<p_points;i++) {
- b[stride*i+color_ofs+0]=p_colors[i].r;
- b[stride*i+color_ofs+1]=p_colors[i].g;
- b[stride*i+color_ofs+2]=p_colors[i].b;
- b[stride*i+color_ofs+3]=p_colors[i].a;
+ for (int i = 0; i < p_points; i++) {
+ b[stride * i + color_ofs + 0] = p_colors[i].r;
+ b[stride * i + color_ofs + 1] = p_colors[i].g;
+ b[stride * i + color_ofs + 2] = p_colors[i].b;
+ b[stride * i + color_ofs + 3] = p_colors[i].a;
}
-
}
if (p_uvs) {
- for(int i=0;i<p_points;i++) {
- b[stride*i+uv_ofs+0]=p_uvs[i].x;
- b[stride*i+uv_ofs+1]=p_uvs[i].y;
+ for (int i = 0; i < p_points; i++) {
+ b[stride * i + uv_ofs + 0] = p_uvs[i].x;
+ b[stride * i + uv_ofs + 1] = p_uvs[i].y;
}
-
}
- glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer);
- glBufferSubData(GL_ARRAY_BUFFER,0,p_points*stride*4,&b[0]);
+ glBindBuffer(GL_ARRAY_BUFFER, data.primitive_quad_buffer);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, p_points * stride * 4, &b[0]);
glBindVertexArray(data.primitive_quad_buffer_arrays[version]);
- glDrawArrays(prim[p_points],0,p_points);
+ glDrawArrays(prim[p_points], 0, p_points);
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
storage->frame.canvas_draw_commands++;
}
-void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *current_clip,bool &reclip) {
+void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item, Item *current_clip, bool &reclip) {
- int cc=p_item->commands.size();
+ int cc = p_item->commands.size();
Item::Command **commands = p_item->commands.ptr();
+ for (int i = 0; i < cc; i++) {
- for(int i=0;i<cc;i++) {
+ Item::Command *c = commands[i];
- Item::Command *c=commands[i];
-
- switch(c->type) {
+ switch (c->type) {
case Item::Command::TYPE_LINE: {
-
- Item::CommandLine* line = static_cast<Item::CommandLine*>(c);
+ Item::CommandLine *line = static_cast<Item::CommandLine *>(c);
_set_texture_rect_mode(false);
-
_bind_canvas_texture(RID());
- glVertexAttrib4f(VS::ARRAY_COLOR,line->color.r,line->color.g,line->color.b,line->color.a);
+ glVertexAttrib4f(VS::ARRAY_COLOR, line->color.r, line->color.g, line->color.b, line->color.a);
- Vector2 verts[2]={
- Vector2(line->from.x,line->from.y),
- Vector2(line->to.x,line->to.y)
+ Vector2 verts[2] = {
+ Vector2(line->from.x, line->from.y),
+ Vector2(line->to.x, line->to.y)
};
#ifdef GLES_OVER_GL
@@ -481,72 +442,66 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *curr
glEnable(GL_LINE_SMOOTH);
#endif
//glLineWidth(line->width);
- _draw_gui_primitive(2,verts,NULL,NULL);
+ _draw_gui_primitive(2, verts, NULL, NULL);
#ifdef GLES_OVER_GL
if (line->antialiased)
glDisable(GL_LINE_SMOOTH);
#endif
-
} break;
case Item::Command::TYPE_RECT: {
- Item::CommandRect* rect = static_cast<Item::CommandRect*>(c);
+ Item::CommandRect *rect = static_cast<Item::CommandRect *>(c);
_set_texture_rect_mode(true);
//set color
- glVertexAttrib4f(VS::ARRAY_COLOR,rect->modulate.r,rect->modulate.g,rect->modulate.b,rect->modulate.a);
+ glVertexAttrib4f(VS::ARRAY_COLOR, rect->modulate.r, rect->modulate.g, rect->modulate.b, rect->modulate.a);
- RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(rect->texture);
+ RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(rect->texture);
- if ( texture ) {
+ if (texture) {
- bool untile=false;
+ bool untile = false;
- if (rect->flags&CANVAS_RECT_TILE && !(texture->flags&VS::TEXTURE_FLAG_REPEAT)) {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
- untile=true;
+ if (rect->flags & CANVAS_RECT_TILE && !(texture->flags & VS::TEXTURE_FLAG_REPEAT)) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ untile = true;
}
- Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height );
- Rect2 src_rect = (rect->flags&CANVAS_RECT_REGION) ? Rect2( rect->source.pos * texpixel_size, rect->source.size * texpixel_size ) : Rect2(0,0,1,1);
+ Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
+ Rect2 src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.pos * texpixel_size, rect->source.size * texpixel_size) : Rect2(0, 0, 1, 1);
- if (rect->flags&CANVAS_RECT_FLIP_H) {
- src_rect.size.x*=-1;
+ if (rect->flags & CANVAS_RECT_FLIP_H) {
+ src_rect.size.x *= -1;
}
- if (rect->flags&CANVAS_RECT_FLIP_V) {
- src_rect.size.y*=-1;
+ if (rect->flags & CANVAS_RECT_FLIP_V) {
+ src_rect.size.y *= -1;
}
- if (rect->flags&CANVAS_RECT_TRANSPOSE) {
+ if (rect->flags & CANVAS_RECT_TRANSPOSE) {
//err..
}
- state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size);
-
-
- glVertexAttrib4f(1,rect->rect.pos.x,rect->rect.pos.y,rect->rect.size.x,rect->rect.size.y);
- glVertexAttrib4f(2,src_rect.pos.x,src_rect.pos.y,src_rect.size.x,src_rect.size.y);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
+ glVertexAttrib4f(1, rect->rect.pos.x, rect->rect.pos.y, rect->rect.size.x, rect->rect.size.y);
+ glVertexAttrib4f(2, src_rect.pos.x, src_rect.pos.y, src_rect.size.x, src_rect.size.y);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
if (untile) {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
} else {
-
- glVertexAttrib4f(1,rect->rect.pos.x,rect->rect.pos.y,rect->rect.size.x,rect->rect.size.y);
- glVertexAttrib4f(2,0,0,1,1);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
-
-
+ glVertexAttrib4f(1, rect->rect.pos.x, rect->rect.pos.y, rect->rect.size.x, rect->rect.size.y);
+ glVertexAttrib4f(2, 0, 0, 1, 1);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
storage->frame.canvas_draw_commands++;
@@ -555,80 +510,75 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *curr
case Item::Command::TYPE_NINEPATCH: {
- Item::CommandNinePatch* np = static_cast<Item::CommandNinePatch*>(c);
+ Item::CommandNinePatch *np = static_cast<Item::CommandNinePatch *>(c);
_set_texture_rect_mode(true);
- glVertexAttrib4f(VS::ARRAY_COLOR,np->color.r,np->color.g,np->color.b,np->color.a);
-
+ glVertexAttrib4f(VS::ARRAY_COLOR, np->color.r, np->color.g, np->color.b, np->color.a);
- RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(np->texture);
+ RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(np->texture);
- if ( !texture ) {
+ if (!texture) {
- glVertexAttrib4f(1,np->rect.pos.x,np->rect.pos.y,np->rect.size.x,np->rect.size.y);
- glVertexAttrib4f(2,0,0,1,1);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glVertexAttrib4f(1, np->rect.pos.x, np->rect.pos.y, np->rect.size.x, np->rect.size.y);
+ glVertexAttrib4f(2, 0, 0, 1, 1);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
continue;
}
+ Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
- Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height );
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size);
-
-#define DSTRECT(m_x,m_y,m_w,m_h) glVertexAttrib4f(1,m_x,m_y,m_w,m_h)
-#define SRCRECT(m_x,m_y,m_w,m_h) glVertexAttrib4f(2,(m_x)*texpixel_size.x,(m_y)*texpixel_size.y,(m_w)*texpixel_size.x,(m_h)*texpixel_size.y)
+#define DSTRECT(m_x, m_y, m_w, m_h) glVertexAttrib4f(1, m_x, m_y, m_w, m_h)
+#define SRCRECT(m_x, m_y, m_w, m_h) glVertexAttrib4f(2, (m_x)*texpixel_size.x, (m_y)*texpixel_size.y, (m_w)*texpixel_size.x, (m_h)*texpixel_size.y)
//top left
- DSTRECT(np->rect.pos.x,np->rect.pos.y,np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]);
- SRCRECT(0,0,np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x, np->rect.pos.y, np->margin[MARGIN_LEFT], np->margin[MARGIN_TOP]);
+ SRCRECT(0, 0, np->margin[MARGIN_LEFT], np->margin[MARGIN_TOP]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//top right
- DSTRECT(np->rect.pos.x+np->rect.size.x-np->margin[MARGIN_RIGHT],np->rect.pos.y,np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]);
- SRCRECT(texture->width-np->margin[MARGIN_RIGHT],0,np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x + np->rect.size.x - np->margin[MARGIN_RIGHT], np->rect.pos.y, np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP]);
+ SRCRECT(texture->width - np->margin[MARGIN_RIGHT], 0, np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//bottom right
- DSTRECT(np->rect.pos.x+np->rect.size.x-np->margin[MARGIN_RIGHT],np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_RIGHT],np->margin[MARGIN_BOTTOM]);
- SRCRECT(texture->width-np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_RIGHT],np->margin[MARGIN_BOTTOM]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x + np->rect.size.x - np->margin[MARGIN_RIGHT], np->rect.pos.y + np->rect.size.y - np->margin[MARGIN_BOTTOM], np->margin[MARGIN_RIGHT], np->margin[MARGIN_BOTTOM]);
+ SRCRECT(texture->width - np->margin[MARGIN_RIGHT], texture->height - np->margin[MARGIN_BOTTOM], np->margin[MARGIN_RIGHT], np->margin[MARGIN_BOTTOM]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//bottom left
- DSTRECT(np->rect.pos.x,np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_LEFT],np->margin[MARGIN_BOTTOM]);
- SRCRECT(0,texture->height-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_LEFT],np->margin[MARGIN_BOTTOM]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
-
+ DSTRECT(np->rect.pos.x, np->rect.pos.y + np->rect.size.y - np->margin[MARGIN_BOTTOM], np->margin[MARGIN_LEFT], np->margin[MARGIN_BOTTOM]);
+ SRCRECT(0, texture->height - np->margin[MARGIN_BOTTOM], np->margin[MARGIN_LEFT], np->margin[MARGIN_BOTTOM]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//top
- DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y,np->rect.size.width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]);
- SRCRECT(np->margin[MARGIN_LEFT],0,texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x + np->margin[MARGIN_LEFT], np->rect.pos.y, np->rect.size.width - np->margin[MARGIN_LEFT] - np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP]);
+ SRCRECT(np->margin[MARGIN_LEFT], 0, texture->width - np->margin[MARGIN_LEFT] - np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//bottom
- DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->rect.size.width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]);
- SRCRECT(np->margin[MARGIN_LEFT],texture->height-np->margin[MARGIN_BOTTOM],texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
-
+ DSTRECT(np->rect.pos.x + np->margin[MARGIN_LEFT], np->rect.pos.y + np->rect.size.y - np->margin[MARGIN_BOTTOM], np->rect.size.width - np->margin[MARGIN_LEFT] - np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP]);
+ SRCRECT(np->margin[MARGIN_LEFT], texture->height - np->margin[MARGIN_BOTTOM], texture->width - np->margin[MARGIN_LEFT] - np->margin[MARGIN_LEFT], np->margin[MARGIN_TOP]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//left
- DSTRECT(np->rect.pos.x,np->rect.pos.y+np->margin[MARGIN_TOP],np->margin[MARGIN_LEFT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- SRCRECT(0,np->margin[MARGIN_TOP],np->margin[MARGIN_LEFT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x, np->rect.pos.y + np->margin[MARGIN_TOP], np->margin[MARGIN_LEFT], np->rect.size.height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ SRCRECT(0, np->margin[MARGIN_TOP], np->margin[MARGIN_LEFT], texture->height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
//right
- DSTRECT(np->rect.pos.x+np->rect.size.width-np->margin[MARGIN_RIGHT],np->rect.pos.y+np->margin[MARGIN_TOP],np->margin[MARGIN_RIGHT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- SRCRECT(texture->width-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP],np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ DSTRECT(np->rect.pos.x + np->rect.size.width - np->margin[MARGIN_RIGHT], np->rect.pos.y + np->margin[MARGIN_TOP], np->margin[MARGIN_RIGHT], np->rect.size.height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ SRCRECT(texture->width - np->margin[MARGIN_RIGHT], np->margin[MARGIN_TOP], np->margin[MARGIN_RIGHT], texture->height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
if (np->draw_center) {
//center
- DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y+np->margin[MARGIN_TOP],np->rect.size.x-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- SRCRECT(np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP],texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
-
+ DSTRECT(np->rect.pos.x + np->margin[MARGIN_LEFT], np->rect.pos.y + np->margin[MARGIN_TOP], np->rect.size.x - np->margin[MARGIN_LEFT] - np->margin[MARGIN_RIGHT], np->rect.size.height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ SRCRECT(np->margin[MARGIN_LEFT], np->margin[MARGIN_TOP], texture->width - np->margin[MARGIN_LEFT] - np->margin[MARGIN_RIGHT], texture->height - np->margin[MARGIN_TOP] - np->margin[MARGIN_BOTTOM]);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
#undef SRCRECT
@@ -639,41 +589,39 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *curr
case Item::Command::TYPE_PRIMITIVE: {
- Item::CommandPrimitive* primitive = static_cast<Item::CommandPrimitive*>(c);
+ Item::CommandPrimitive *primitive = static_cast<Item::CommandPrimitive *>(c);
_set_texture_rect_mode(false);
- ERR_CONTINUE( primitive->points.size()<1);
+ ERR_CONTINUE(primitive->points.size() < 1);
- RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(primitive->texture);
-
- if (texture ) {
- Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height );
- state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size);
+ RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(primitive->texture);
+ if (texture) {
+ Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
}
- if (primitive->colors.size()==1 && primitive->points.size()>1) {
+ if (primitive->colors.size() == 1 && primitive->points.size() > 1) {
Color c = primitive->colors[0];
- glVertexAttrib4f(VS::ARRAY_COLOR,c.r,c.g,c.b,c.a);
+ glVertexAttrib4f(VS::ARRAY_COLOR, c.r, c.g, c.b, c.a);
} else if (primitive->colors.empty()) {
- glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1);
+ glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
}
- _draw_gui_primitive(primitive->points.size(),primitive->points.ptr(),primitive->colors.ptr(),primitive->uvs.ptr());
+ _draw_gui_primitive(primitive->points.size(), primitive->points.ptr(), primitive->colors.ptr(), primitive->uvs.ptr());
} break;
case Item::Command::TYPE_POLYGON: {
- Item::CommandPolygon* polygon = static_cast<Item::CommandPolygon*>(c);
+ Item::CommandPolygon *polygon = static_cast<Item::CommandPolygon *>(c);
_set_texture_rect_mode(false);
- RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(polygon->texture);
-
- if (texture ) {
- Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height );
- state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size);
+ RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(polygon->texture);
+ if (texture) {
+ Size2 texpixel_size(1.0 / texture->width, 1.0 / texture->height);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE, texpixel_size);
}
//_draw_polygon(polygon->count,polygon->indices.ptr(),polygon->points.ptr(),polygon->uvs.ptr(),polygon->colors.ptr(),polygon->texture,polygon->colors.size()==1);
@@ -682,59 +630,57 @@ void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *curr
_set_texture_rect_mode(false);
- Item::CommandCircle* circle = static_cast<Item::CommandCircle*>(c);
- static const int numpoints=32;
- Vector2 points[numpoints+1];
- points[numpoints]=circle->pos;
- int indices[numpoints*3];
+ Item::CommandCircle *circle = static_cast<Item::CommandCircle *>(c);
+ static const int numpoints = 32;
+ Vector2 points[numpoints + 1];
+ points[numpoints] = circle->pos;
+ int indices[numpoints * 3];
- for(int i=0;i<numpoints;i++) {
+ for (int i = 0; i < numpoints; i++) {
- points[i]=circle->pos+Vector2( Math::sin(i*Math_PI*2.0/numpoints),Math::cos(i*Math_PI*2.0/numpoints) )*circle->radius;
- indices[i*3+0]=i;
- indices[i*3+1]=(i+1)%numpoints;
- indices[i*3+2]=numpoints;
+ points[i] = circle->pos + Vector2(Math::sin(i * Math_PI * 2.0 / numpoints), Math::cos(i * Math_PI * 2.0 / numpoints)) * circle->radius;
+ indices[i * 3 + 0] = i;
+ indices[i * 3 + 1] = (i + 1) % numpoints;
+ indices[i * 3 + 2] = numpoints;
}
//_draw_polygon(numpoints*3,indices,points,NULL,&circle->color,RID(),true);
//canvas_draw_circle(circle->indices.size(),circle->indices.ptr(),circle->points.ptr(),circle->uvs.ptr(),circle->colors.ptr(),circle->texture,circle->colors.size()==1);
} break;
case Item::Command::TYPE_TRANSFORM: {
- Item::CommandTransform* transform = static_cast<Item::CommandTransform*>(c);
- state.extra_matrix=transform->xform;
- state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix);
+ Item::CommandTransform *transform = static_cast<Item::CommandTransform *>(c);
+ state.extra_matrix = transform->xform;
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, state.extra_matrix);
} break;
case Item::Command::TYPE_CLIP_IGNORE: {
- Item::CommandClipIgnore* ci = static_cast<Item::CommandClipIgnore*>(c);
+ Item::CommandClipIgnore *ci = static_cast<Item::CommandClipIgnore *>(c);
if (current_clip) {
- if (ci->ignore!=reclip) {
+ if (ci->ignore != reclip) {
if (ci->ignore) {
glDisable(GL_SCISSOR_TEST);
- reclip=true;
- } else {
+ reclip = true;
+ } else {
glEnable(GL_SCISSOR_TEST);
//glScissor(viewport.x+current_clip->final_clip_rect.pos.x,viewport.y+ (viewport.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),
//current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height);
int x = current_clip->final_clip_rect.pos.x;
- int y = storage->frame.current_rt->height - ( current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y );
+ int y = storage->frame.current_rt->height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y);
int w = current_clip->final_clip_rect.size.x;
int h = current_clip->final_clip_rect.size.y;
- glScissor(x,y,w,h);
+ glScissor(x, y, w, h);
- reclip=false;
+ reclip = false;
}
}
}
-
-
} break;
}
}
@@ -795,60 +741,52 @@ void RasterizerGLES2::_canvas_item_setup_shader_params(CanvasItemMaterial *mater
#endif
-void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const Color& p_modulate,Light *p_light) {
-
-
+void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light) {
+ Item *current_clip = NULL;
+ RasterizerStorageGLES3::Shader *shader_cache = NULL;
- Item *current_clip=NULL;
- RasterizerStorageGLES3::Shader *shader_cache=NULL;
+ bool rebind_shader = true;
- bool rebind_shader=true;
+ Size2 rt_size = Size2(storage->frame.current_rt->width, storage->frame.current_rt->height);
- Size2 rt_size = Size2(storage->frame.current_rt->width,storage->frame.current_rt->height);
-
-
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD, false);
glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo);
glBufferData(GL_UNIFORM_BUFFER, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
- state.current_tex=RID();
- state.current_tex_ptr=NULL;
+ state.current_tex = RID();
+ state.current_tex_ptr = NULL;
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
-
- int last_blend_mode=-1;
+ int last_blend_mode = -1;
RID canvas_last_material;
- bool prev_distance_field=false;
-
- while(p_item_list) {
+ bool prev_distance_field = false;
- Item *ci=p_item_list;
+ while (p_item_list) {
+ Item *ci = p_item_list;
- if (prev_distance_field!=ci->distance_field) {
+ if (prev_distance_field != ci->distance_field) {
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,ci->distance_field);
- prev_distance_field=ci->distance_field;
- rebind_shader=true;
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD, ci->distance_field);
+ prev_distance_field = ci->distance_field;
+ rebind_shader = true;
}
+ if (current_clip != ci->final_clip_owner) {
- if (current_clip!=ci->final_clip_owner) {
-
- current_clip=ci->final_clip_owner;
+ current_clip = ci->final_clip_owner;
//setup clip
if (current_clip) {
glEnable(GL_SCISSOR_TEST);
- glScissor(current_clip->final_clip_rect.pos.x,(rt_size.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height);
-
+ glScissor(current_clip->final_clip_rect.pos.x, (rt_size.height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height);
} else {
@@ -893,13 +831,12 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const
#endif
-
//begin rect
- Item *material_owner = ci->material_owner?ci->material_owner:ci;
+ Item *material_owner = ci->material_owner ? ci->material_owner : ci;
RID material = material_owner->material;
- if (material!=canvas_last_material || rebind_shader) {
+ if (material != canvas_last_material || rebind_shader) {
RasterizerStorageGLES3::Material *material_ptr = storage->material_owner.getornull(material);
RasterizerStorageGLES3::Shader *shader_ptr = NULL;
@@ -908,46 +845,44 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const
shader_ptr = material_ptr->shader;
- if (shader_ptr && shader_ptr->mode!=VS::SHADER_CANVAS_ITEM) {
- shader_ptr=NULL; //do not use non canvasitem shader
+ if (shader_ptr && shader_ptr->mode != VS::SHADER_CANVAS_ITEM) {
+ shader_ptr = NULL; //do not use non canvasitem shader
}
}
-
-
- if (shader_ptr && shader_ptr!=shader_cache) {
+ if (shader_ptr && shader_ptr != shader_cache) {
state.canvas_shader.set_custom_shader(shader_ptr->custom_code_id);
state.canvas_shader.bind();
if (material_ptr->ubo_id) {
- glBindBufferBase(GL_UNIFORM_BUFFER,2,material_ptr->ubo_id);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 2, material_ptr->ubo_id);
}
int tc = material_ptr->textures.size();
- RID* textures = material_ptr->textures.ptr();
- ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = shader_ptr->texture_hints.ptr();
+ RID *textures = material_ptr->textures.ptr();
+ ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = shader_ptr->texture_hints.ptr();
- for(int i=0;i<tc;i++) {
+ for (int i = 0; i < tc; i++) {
- glActiveTexture(GL_TEXTURE1+i);
+ glActiveTexture(GL_TEXTURE1 + i);
- RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull( textures[i] );
+ RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull(textures[i]);
if (!t) {
- switch(texture_hints[i]) {
+ switch (texture_hints[i]) {
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
- glBindTexture(GL_TEXTURE_2D,storage->resources.black_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.black_tex);
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: {
- glBindTexture(GL_TEXTURE_2D,storage->resources.aniso_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.aniso_tex);
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
- glBindTexture(GL_TEXTURE_2D,storage->resources.normal_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.normal_tex);
} break;
default: {
- glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
} break;
}
@@ -958,116 +893,108 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const
if (storage->config.srgb_decode_supported && t->using_srgb) {
//no srgb in 2D
- glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT);
- t->using_srgb=false;
+ glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
+ t->using_srgb = false;
}
- glBindTexture(t->target,t->tex_id);
+ glBindTexture(t->target, t->tex_id);
}
-
} else if (!shader_ptr) {
state.canvas_shader.set_custom_shader(0);
state.canvas_shader.bind();
-
}
- shader_cache=shader_ptr;
-
- canvas_last_material=material;
- rebind_shader=false;
+ shader_cache = shader_ptr;
+ canvas_last_material = material;
+ rebind_shader = false;
}
int blend_mode = shader_cache ? shader_cache->canvas_item.blend_mode : RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX;
- bool unshaded = shader_cache && (shader_cache->canvas_item.light_mode==RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_UNSHADED || blend_mode!=RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX);
- bool reclip=false;
+ bool unshaded = shader_cache && (shader_cache->canvas_item.light_mode == RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_UNSHADED || blend_mode != RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX);
+ bool reclip = false;
- if (last_blend_mode!=blend_mode) {
+ if (last_blend_mode != blend_mode) {
- switch(blend_mode) {
+ switch (blend_mode) {
- case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX: {
+ case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX: {
glBlendEquation(GL_FUNC_ADD);
if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- } break;
- case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_ADD: {
+ } break;
+ case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
- } break;
- case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_SUB: {
+ } break;
+ case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
- } break;
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ } break;
case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MUL: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_DST_COLOR,GL_ZERO);
+ glBlendFunc(GL_DST_COLOR, GL_ZERO);
} break;
case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA);
+ glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
} break;
-
}
- last_blend_mode=blend_mode;
+ last_blend_mode = blend_mode;
}
state.canvas_item_modulate = unshaded ? ci->final_modulate : Color(
- ci->final_modulate.r * p_modulate.r,
- ci->final_modulate.g * p_modulate.g,
- ci->final_modulate.b * p_modulate.b,
- ci->final_modulate.a * p_modulate.a );
+ ci->final_modulate.r * p_modulate.r,
+ ci->final_modulate.g * p_modulate.g,
+ ci->final_modulate.b * p_modulate.b,
+ ci->final_modulate.a * p_modulate.a);
state.final_transform = ci->final_transform;
- state.extra_matrix=Transform2D();
+ state.extra_matrix = Transform2D();
- state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, state.canvas_item_modulate);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, state.extra_matrix);
+ if (unshaded || (state.canvas_item_modulate.a > 0.001 && (!shader_cache || shader_cache->canvas_item.light_mode != RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY) && !ci->light_masked))
+ _canvas_item_render_commands(ci, current_clip, reclip);
- if (unshaded || (state.canvas_item_modulate.a>0.001 && (!shader_cache || shader_cache->canvas_item.light_mode!=RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY) && !ci->light_masked ))
- _canvas_item_render_commands(ci,current_clip,reclip);
-
- if ((blend_mode==RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX || blend_mode==RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA) && p_light && !unshaded) {
+ if ((blend_mode == RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX || blend_mode == RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA) && p_light && !unshaded) {
Light *light = p_light;
- bool light_used=false;
- VS::CanvasLightMode mode=VS::CANVAS_LIGHT_MODE_ADD;
- state.canvas_item_modulate=ci->final_modulate; // remove the canvas modulate
-
+ bool light_used = false;
+ VS::CanvasLightMode mode = VS::CANVAS_LIGHT_MODE_ADD;
+ state.canvas_item_modulate = ci->final_modulate; // remove the canvas modulate
- while(light) {
+ while (light) {
-
- if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) {
+ if (ci->light_mask & light->item_mask && p_z >= light->z_min && p_z <= light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
//intersects this light
- if (!light_used || mode!=light->mode) {
+ if (!light_used || mode != light->mode) {
- mode=light->mode;
+ mode = light->mode;
- switch(mode) {
+ switch (mode) {
case VS::CANVAS_LIGHT_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
} break;
case VS::CANVAS_LIGHT_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
} break;
case VS::CANVAS_LIGHT_MODE_MIX:
case VS::CANVAS_LIGHT_MODE_MASK: {
@@ -1076,90 +1003,80 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const
} break;
}
-
}
if (!light_used) {
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,true);
- light_used=true;
-
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING, true);
+ light_used = true;
}
+ bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask & light->item_shadow_mask;
- bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask&light->item_shadow_mask;
-
-
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,has_shadow);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS, has_shadow);
if (has_shadow) {
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_USE_GRADIENT,light->shadow_gradient_length>0);
- switch(light->shadow_filter) {
-
- case VS::CANVAS_LIGHT_FILTER_NONE: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,true); break;
- case VS::CANVAS_LIGHT_FILTER_PCF3: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3,true); break;
- case VS::CANVAS_LIGHT_FILTER_PCF5: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,true); break;
- case VS::CANVAS_LIGHT_FILTER_PCF9: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9,true); break;
- case VS::CANVAS_LIGHT_FILTER_PCF13: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,true); break;
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_USE_GRADIENT, light->shadow_gradient_length > 0);
+ switch (light->shadow_filter) {
+
+ case VS::CANVAS_LIGHT_FILTER_NONE: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST, true); break;
+ case VS::CANVAS_LIGHT_FILTER_PCF3: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3, true); break;
+ case VS::CANVAS_LIGHT_FILTER_PCF5: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5, true); break;
+ case VS::CANVAS_LIGHT_FILTER_PCF9: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9, true); break;
+ case VS::CANVAS_LIGHT_FILTER_PCF13: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13, true); break;
}
-
-
}
bool light_rebind = state.canvas_shader.bind();
if (light_rebind) {
- state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform);
- state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform2D());
-
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE, state.canvas_item_modulate);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX, state.final_transform);
+ state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX, Transform2D());
}
- glBindBufferBase(GL_UNIFORM_BUFFER,1,static_cast<LightInternal*>(light->light_internal.get_data())->ubo);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 1, static_cast<LightInternal *>(light->light_internal.get_data())->ubo);
if (has_shadow) {
RasterizerStorageGLES3::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(light->shadow_buffer);
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-2);
- glBindTexture(GL_TEXTURE_2D,cls->distance);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2);
+ glBindTexture(GL_TEXTURE_2D, cls->distance);
/*canvas_shader.set_uniform(CanvasShaderGLES3::SHADOW_MATRIX,light->shadow_matrix_cache);
canvas_shader.set_uniform(CanvasShaderGLES3::SHADOW_ESM_MULTIPLIER,light->shadow_esm_mult);
canvas_shader.set_uniform(CanvasShaderGLES3::LIGHT_SHADOW_COLOR,light->shadow_color);*/
-
}
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-1);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1);
RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull(light->texture);
if (!t) {
- glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
} else {
- glBindTexture(t->target,t->tex_id);
+ glBindTexture(t->target, t->tex_id);
}
glActiveTexture(GL_TEXTURE0);
- _canvas_item_render_commands(ci,current_clip,reclip); //redraw using light
-
+ _canvas_item_render_commands(ci, current_clip, reclip); //redraw using light
}
- light=light->next_ptr;
+ light = light->next_ptr;
}
if (light_used) {
-
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9,false);
- state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9, false);
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13, false);
state.canvas_shader.bind();
- last_blend_mode=-1;
+ last_blend_mode = -1;
/*
//this is set again, so it should not be needed anyway?
@@ -1185,69 +1102,58 @@ void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const
//@TODO RESET canvas_blend_mode
*/
}
-
-
}
if (reclip) {
glEnable(GL_SCISSOR_TEST);
- glScissor(current_clip->final_clip_rect.pos.x,(rt_size.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height);
-
-
+ glScissor(current_clip->final_clip_rect.pos.x, (rt_size.height - (current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.height)), current_clip->final_clip_rect.size.width, current_clip->final_clip_rect.size.height);
}
-
-
- p_item_list=p_item_list->next;
+ p_item_list = p_item_list->next;
}
if (current_clip) {
glDisable(GL_SCISSOR_TEST);
}
-
}
-void RasterizerCanvasGLES3::canvas_debug_viewport_shadows(Light* p_lights_with_shadow){
+void RasterizerCanvasGLES3::canvas_debug_viewport_shadows(Light *p_lights_with_shadow) {
- Light* light=p_lights_with_shadow;
+ Light *light = p_lights_with_shadow;
canvas_begin(); //reset
- glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1);
+ glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
int h = 10;
int w = storage->frame.current_rt->width;
int ofs = h;
glDisable(GL_BLEND);
//print_line(" debug lights ");
- while(light) {
-
+ while (light) {
//print_line("debug light");
if (light->shadow_buffer.is_valid()) {
//print_line("sb is valid");
- RasterizerStorageGLES3::CanvasLightShadow * sb = storage->canvas_light_shadow_owner.get(light->shadow_buffer);
+ RasterizerStorageGLES3::CanvasLightShadow *sb = storage->canvas_light_shadow_owner.get(light->shadow_buffer);
if (sb) {
- glBindTexture(GL_TEXTURE_2D,sb->distance);
+ glBindTexture(GL_TEXTURE_2D, sb->distance);
//glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex);
- draw_generic_textured_rect(Rect2(h,ofs,w-h*2,h),Rect2(0,0,1,1));
- ofs+=h*2;
-
+ draw_generic_textured_rect(Rect2(h, ofs, w - h * 2, h), Rect2(0, 0, 1, 1));
+ ofs += h * 2;
}
}
- light=light->shadows_next_ptr;
+ light = light->shadows_next_ptr;
}
}
-
-void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, LightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache) {
+void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) {
RasterizerStorageGLES3::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(p_buffer);
ERR_FAIL_COND(!cls);
-
glDisable(GL_BLEND);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_DITHER);
@@ -1261,73 +1167,71 @@ void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, cons
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
state.canvas_shadow_shader.bind();
- glViewport(0, 0, cls->size,cls->height);
+ glViewport(0, 0, cls->size, cls->height);
glClearDepth(1.0f);
- glClearColor(1,1,1,1);
- glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
+ glClearColor(1, 1, 1, 1);
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- VS::CanvasOccluderPolygonCullMode cull=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
+ VS::CanvasOccluderPolygonCullMode cull = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
-
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
//make sure it remains orthogonal, makes easy to read angle later
Transform light;
- light.origin[0]=p_light_xform[2][0];
- light.origin[1]=p_light_xform[2][1];
- light.basis[0][0]=p_light_xform[0][0];
- light.basis[0][1]=p_light_xform[1][0];
- light.basis[1][0]=p_light_xform[0][1];
- light.basis[1][1]=p_light_xform[1][1];
+ light.origin[0] = p_light_xform[2][0];
+ light.origin[1] = p_light_xform[2][1];
+ light.basis[0][0] = p_light_xform[0][0];
+ light.basis[0][1] = p_light_xform[1][0];
+ light.basis[1][0] = p_light_xform[0][1];
+ light.basis[1][1] = p_light_xform[1][1];
//light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1));
//p_near=1;
CameraMatrix projection;
{
- real_t fov = 90;
+ real_t fov = 90;
real_t nearp = p_near;
real_t farp = p_far;
real_t aspect = 1.0;
- real_t ymax = nearp * Math::tan( Math::deg2rad( fov * 0.5 ) );
- real_t ymin = - ymax;
+ real_t ymax = nearp * Math::tan(Math::deg2rad(fov * 0.5));
+ real_t ymin = -ymax;
real_t xmin = ymin * aspect;
real_t xmax = ymax * aspect;
- projection.set_frustum( xmin, xmax, ymin, ymax, nearp, farp );
+ projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
}
- Vector3 cam_target=Basis(Vector3(0,0,Math_PI*2*(i/4.0))).xform(Vector3(0,1,0));
- projection = projection * CameraMatrix(Transform().looking_at(cam_target,Vector3(0,0,-1)).affine_inverse());
-
- state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::PROJECTION_MATRIX,projection);
- state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::LIGHT_MATRIX,light);
- state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::DISTANCE_NORM,1.0/p_far);
+ Vector3 cam_target = Basis(Vector3(0, 0, Math_PI * 2 * (i / 4.0))).xform(Vector3(0, 1, 0));
+ projection = projection * CameraMatrix(Transform().looking_at(cam_target, Vector3(0, 0, -1)).affine_inverse());
+ state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::PROJECTION_MATRIX, projection);
+ state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::LIGHT_MATRIX, light);
+ state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::DISTANCE_NORM, 1.0 / p_far);
- if (i==0)
- *p_xform_cache=projection;
+ if (i == 0)
+ *p_xform_cache = projection;
- glViewport(0, (cls->height/4)*i, cls->size,cls->height/4);
+ glViewport(0, (cls->height / 4) * i, cls->size, cls->height / 4);
- LightOccluderInstance *instance=p_occluders;
+ LightOccluderInstance *instance = p_occluders;
- while(instance) {
+ while (instance) {
RasterizerStorageGLES3::CanvasOccluder *cc = storage->canvas_occluder_owner.get(instance->polygon_buffer);
- if (!cc || cc->len==0 || !(p_light_mask&instance->light_mask)) {
+ if (!cc || cc->len == 0 || !(p_light_mask & instance->light_mask)) {
- instance=instance->next;
+ instance = instance->next;
continue;
}
- state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::WORLD_MATRIX,instance->xform_cache);
- if (cull!=instance->cull_cache) {
+ state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::WORLD_MATRIX, instance->xform_cache);
+ if (cull != instance->cull_cache) {
- cull=instance->cull_cache;
- switch(cull) {
+ cull = instance->cull_cache;
+ switch (cull) {
case VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED: {
glDisable(GL_CULL_FACE);
@@ -1346,7 +1250,7 @@ void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, cons
} break;
}
}
-/*
+ /*
if (i==0) {
for(int i=0;i<cc->lines.size();i++) {
Vector2 p = instance->xform_cache.xform(cc->lines.get(i));
@@ -1359,31 +1263,26 @@ void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, cons
}
}
*/
- glBindBuffer(GL_ARRAY_BUFFER,cc->vertex_id);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,cc->index_id);
+ glBindBuffer(GL_ARRAY_BUFFER, cc->vertex_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cc->index_id);
glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, 0);
- glDrawElements(GL_TRIANGLES,cc->len*3,GL_UNSIGNED_SHORT,0);
+ glDrawElements(GL_TRIANGLES, cc->len * 3, GL_UNSIGNED_SHORT, 0);
-
- instance=instance->next;
+ instance = instance->next;
}
-
-
}
glDisableVertexAttribArray(VS::ARRAY_VERTEX);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void RasterizerCanvasGLES3::reset_canvas() {
-
if (storage->frame.current_rt) {
glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
- glColorMask(1,1,1,1); //don't touch alpha
+ glColorMask(1, 1, 1, 1); //don't touch alpha
}
-
glBindVertexArray(0);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
@@ -1392,23 +1291,21 @@ void RasterizerCanvasGLES3::reset_canvas() {
glBlendEquation(GL_FUNC_ADD);
if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
//glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
//glLineWidth(1.0);
- glBindBuffer(GL_ARRAY_BUFFER,0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
glDisableVertexAttribArray(i);
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D, storage->resources.white_tex );
-
+ glBindTexture(GL_TEXTURE_2D, storage->resources.white_tex);
- glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1);
+ glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
Transform canvas_transform;
@@ -1419,119 +1316,107 @@ void RasterizerCanvasGLES3::reset_canvas() {
csy = -1.0;
}
canvas_transform.translate(-(storage->frame.current_rt->width / 2.0f), -(storage->frame.current_rt->height / 2.0f), 0.0f);
- canvas_transform.scale( Vector3( 2.0f / storage->frame.current_rt->width, csy * -2.0f / storage->frame.current_rt->height, 1.0f ) );
+ canvas_transform.scale(Vector3(2.0f / storage->frame.current_rt->width, csy * -2.0f / storage->frame.current_rt->height, 1.0f));
} else {
Vector2 ssize = OS::get_singleton()->get_window_size();
canvas_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
- canvas_transform.scale( Vector3( 2.0f / ssize.width, -2.0f / ssize.height, 1.0f ) );
-
+ canvas_transform.scale(Vector3(2.0f / ssize.width, -2.0f / ssize.height, 1.0f));
}
- state.vp=canvas_transform;
+ state.vp = canvas_transform;
- store_transform(canvas_transform,state.canvas_item_ubo_data.projection_matrix);
- for(int i=0;i<4;i++) {
- state.canvas_item_ubo_data.time[i]=storage->frame.time[i];
+ store_transform(canvas_transform, state.canvas_item_ubo_data.projection_matrix);
+ for (int i = 0; i < 4; i++) {
+ state.canvas_item_ubo_data.time[i] = storage->frame.time[i];
}
glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
- state.canvas_texscreen_used=false;
-
-
+ state.canvas_texscreen_used = false;
}
+void RasterizerCanvasGLES3::draw_generic_textured_rect(const Rect2 &p_rect, const Rect2 &p_src) {
-void RasterizerCanvasGLES3::draw_generic_textured_rect(const Rect2& p_rect, const Rect2& p_src) {
-
-
- glVertexAttrib4f(1,p_rect.pos.x,p_rect.pos.y,p_rect.size.x,p_rect.size.y);
- glVertexAttrib4f(2,p_src.pos.x,p_src.pos.y,p_src.size.x,p_src.size.y);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glVertexAttrib4f(1, p_rect.pos.x, p_rect.pos.y, p_rect.size.x, p_rect.size.y);
+ glVertexAttrib4f(2, p_src.pos.x, p_src.pos.y, p_src.size.x, p_src.size.y);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
void RasterizerCanvasGLES3::initialize() {
-
{
//quad buffers
- glGenBuffers(1,&data.canvas_quad_vertices);
- glBindBuffer(GL_ARRAY_BUFFER,data.canvas_quad_vertices);
+ glGenBuffers(1, &data.canvas_quad_vertices);
+ glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
{
- const float qv[8]={
- 0,0,
- 0,1,
- 1,1,
- 1,0
+ const float qv[8] = {
+ 0, 0,
+ 0, 1,
+ 1, 1,
+ 1, 0
};
- glBufferData(GL_ARRAY_BUFFER,sizeof(float)*8,qv,GL_STATIC_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 8, qv, GL_STATIC_DRAW);
}
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
-
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
- glGenVertexArrays(1,&data.canvas_quad_array);
+ glGenVertexArrays(1, &data.canvas_quad_array);
glBindVertexArray(data.canvas_quad_array);
- glBindBuffer(GL_ARRAY_BUFFER,data.canvas_quad_vertices);
- glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(float)*2,0);
+ glBindBuffer(GL_ARRAY_BUFFER, data.canvas_quad_vertices);
+ glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
}
{
- glGenBuffers(1,&data.primitive_quad_buffer);
- glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer);
- glBufferData(GL_ARRAY_BUFFER,(2+2+4)*4*sizeof(float),NULL,GL_DYNAMIC_DRAW); //allocate max size
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glGenBuffers(1, &data.primitive_quad_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, data.primitive_quad_buffer);
+ glBufferData(GL_ARRAY_BUFFER, (2 + 2 + 4) * 4 * sizeof(float), NULL, GL_DYNAMIC_DRAW); //allocate max size
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
-
- for(int i=0;i<4;i++) {
- glGenVertexArrays(1,&data.primitive_quad_buffer_arrays[i]);
+ for (int i = 0; i < 4; i++) {
+ glGenVertexArrays(1, &data.primitive_quad_buffer_arrays[i]);
glBindVertexArray(data.primitive_quad_buffer_arrays[i]);
- glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, data.primitive_quad_buffer);
- int uv_ofs=0;
- int color_ofs=0;
- int stride=2*4;
+ int uv_ofs = 0;
+ int color_ofs = 0;
+ int stride = 2 * 4;
- if (i&1) { //color
- color_ofs=stride;
- stride+=4*4;
+ if (i & 1) { //color
+ color_ofs = stride;
+ stride += 4 * 4;
}
- if (i&2) { //uv
- uv_ofs=stride;
- stride+=2*4;
+ if (i & 2) { //uv
+ uv_ofs = stride;
+ stride += 2 * 4;
}
-
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer(VS::ARRAY_VERTEX,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+0);
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + 0);
- if (i&1) {
+ if (i & 1) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttribPointer(VS::ARRAY_COLOR,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+color_ofs);
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + color_ofs);
}
- if (i&2) {
+ if (i & 2) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glVertexAttribPointer(VS::ARRAY_TEX_UV,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+uv_ofs);
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + uv_ofs);
}
glBindVertexArray(0);
}
}
-
- store_transform(Transform(),state.canvas_item_ubo_data.projection_matrix);
-
+ store_transform(Transform(), state.canvas_item_ubo_data.projection_matrix);
glGenBuffers(1, &state.canvas_item_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo);
@@ -1542,20 +1427,15 @@ void RasterizerCanvasGLES3::initialize() {
state.canvas_shader.set_base_material_tex_index(1);
state.canvas_shadow_shader.init();
- state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_RGBA_SHADOWS,storage->config.use_rgba_2d_shadows);
- state.canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES3::USE_RGBA_SHADOWS,storage->config.use_rgba_2d_shadows);
-
-
+ state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows);
+ state.canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES3::USE_RGBA_SHADOWS, storage->config.use_rgba_2d_shadows);
}
-
void RasterizerCanvasGLES3::finalize() {
- glDeleteBuffers(1,&data.canvas_quad_vertices);
- glDeleteVertexArrays(1,&data.canvas_quad_array);
+ glDeleteBuffers(1, &data.canvas_quad_vertices);
+ glDeleteVertexArrays(1, &data.canvas_quad_array);
}
-RasterizerCanvasGLES3::RasterizerCanvasGLES3()
-{
-
+RasterizerCanvasGLES3::RasterizerCanvasGLES3() {
}
diff --git a/drivers/gles3/rasterizer_canvas_gles3.h b/drivers/gles3/rasterizer_canvas_gles3.h
index 1273e5f35d..c90dcc7d65 100644
--- a/drivers/gles3/rasterizer_canvas_gles3.h
+++ b/drivers/gles3/rasterizer_canvas_gles3.h
@@ -29,19 +29,16 @@
#ifndef RASTERIZERCANVASGLES3_H
#define RASTERIZERCANVASGLES3_H
-#include "servers/visual/rasterizer.h"
#include "rasterizer_storage_gles3.h"
+#include "servers/visual/rasterizer.h"
#include "shaders/canvas_shadow.glsl.h"
-
class RasterizerCanvasGLES3 : public RasterizerCanvas {
public:
-
struct CanvasItemUBO {
float projection_matrix[16];
float time[4];
-
};
struct Data {
@@ -63,7 +60,6 @@ public:
bool using_texture_rect;
-
RID current_tex;
RasterizerStorageGLES3::Texture *current_tex_ptr;
@@ -100,31 +96,27 @@ public:
RID_Owner<LightInternal> light_internal_owner;
virtual RID light_internal_create();
- virtual void light_internal_update(RID p_rid, Light* p_light);
+ virtual void light_internal_update(RID p_rid, Light *p_light);
virtual void light_internal_free(RID p_rid);
-
virtual void canvas_begin();
virtual void canvas_end();
_FORCE_INLINE_ void _set_texture_rect_mode(bool p_enable);
- _FORCE_INLINE_ RasterizerStorageGLES3::Texture* _bind_canvas_texture(const RID& p_texture);
-
- _FORCE_INLINE_ void _draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs);
- _FORCE_INLINE_ void _draw_polygon(int p_vertex_count, const int* p_indices, const Vector2* p_vertices, const Vector2* p_uvs, const Color* p_colors,const RID& p_texture,bool p_singlecolor);
- _FORCE_INLINE_ void _canvas_item_render_commands(Item *p_item,Item *current_clip,bool &reclip);
+ _FORCE_INLINE_ RasterizerStorageGLES3::Texture *_bind_canvas_texture(const RID &p_texture);
+ _FORCE_INLINE_ void _draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color *p_colors, const Vector2 *p_uvs);
+ _FORCE_INLINE_ void _draw_polygon(int p_vertex_count, const int *p_indices, const Vector2 *p_vertices, const Vector2 *p_uvs, const Color *p_colors, const RID &p_texture, bool p_singlecolor);
+ _FORCE_INLINE_ void _canvas_item_render_commands(Item *p_item, Item *current_clip, bool &reclip);
- virtual void canvas_render_items(Item *p_item_list,int p_z,const Color& p_modulate,Light *p_light);
- virtual void canvas_debug_viewport_shadows(Light* p_lights_with_shadow);
-
- virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, LightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache);
+ virtual void canvas_render_items(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light);
+ virtual void canvas_debug_viewport_shadows(Light *p_lights_with_shadow);
+ virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache);
virtual void reset_canvas();
- void draw_generic_textured_rect(const Rect2& p_rect, const Rect2& p_src);
-
+ void draw_generic_textured_rect(const Rect2 &p_rect, const Rect2 &p_src);
void initialize();
void finalize();
diff --git a/drivers/gles3/rasterizer_gles3.cpp b/drivers/gles3/rasterizer_gles3.cpp
index 05558a39ba..b6cb57d68a 100644
--- a/drivers/gles3/rasterizer_gles3.cpp
+++ b/drivers/gles3/rasterizer_gles3.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "rasterizer_gles3.h"
-#include "os/os.h"
-#include "global_config.h"
#include "gl_context/context_gl.h"
+#include "global_config.h"
+#include "os/os.h"
#include <string.h>
RasterizerStorage *RasterizerGLES3::get_storage() {
@@ -77,63 +77,60 @@ RasterizerScene *RasterizerGLES3::get_scene() {
#define GLAPIENTRY
#endif
-static void GLAPIENTRY _gl_debug_print(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const GLvoid *userParam)
-{
+static void GLAPIENTRY _gl_debug_print(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *userParam) {
- if (type==_EXT_DEBUG_TYPE_OTHER_ARB)
+ if (type == _EXT_DEBUG_TYPE_OTHER_ARB)
return;
print_line("mesege");
char debSource[256], debType[256], debSev[256];
- if(source == _EXT_DEBUG_SOURCE_API_ARB)
- strcpy(debSource, "OpenGL");
- else if(source == _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB)
- strcpy(debSource, "Windows");
- else if(source == _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB)
- strcpy(debSource, "Shader Compiler");
- else if(source == _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB)
- strcpy(debSource, "Third Party");
- else if(source == _EXT_DEBUG_SOURCE_APPLICATION_ARB)
- strcpy(debSource, "Application");
- else if(source == _EXT_DEBUG_SOURCE_OTHER_ARB)
- strcpy(debSource, "Other");
-
- if(type == _EXT_DEBUG_TYPE_ERROR_ARB)
- strcpy(debType, "Error");
- else if(type == _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB)
- strcpy(debType, "Deprecated behavior");
- else if(type == _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB)
- strcpy(debType, "Undefined behavior");
- else if(type == _EXT_DEBUG_TYPE_PORTABILITY_ARB)
- strcpy(debType, "Portability");
- else if(type == _EXT_DEBUG_TYPE_PERFORMANCE_ARB)
- strcpy(debType, "Performance");
- else if(type == _EXT_DEBUG_TYPE_OTHER_ARB)
- strcpy(debType, "Other");
-
- if(severity == _EXT_DEBUG_SEVERITY_HIGH_ARB)
- strcpy(debSev, "High");
- else if(severity == _EXT_DEBUG_SEVERITY_MEDIUM_ARB)
- strcpy(debSev, "Medium");
- else if(severity == _EXT_DEBUG_SEVERITY_LOW_ARB)
- strcpy(debSev, "Low");
-
- String output = String()+ "GL ERROR: Source: " + debSource + "\tType: " + debType + "\tID: " + itos(id) + "\tSeverity: " + debSev + "\tMessage: " + message;
+ if (source == _EXT_DEBUG_SOURCE_API_ARB)
+ strcpy(debSource, "OpenGL");
+ else if (source == _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB)
+ strcpy(debSource, "Windows");
+ else if (source == _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB)
+ strcpy(debSource, "Shader Compiler");
+ else if (source == _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB)
+ strcpy(debSource, "Third Party");
+ else if (source == _EXT_DEBUG_SOURCE_APPLICATION_ARB)
+ strcpy(debSource, "Application");
+ else if (source == _EXT_DEBUG_SOURCE_OTHER_ARB)
+ strcpy(debSource, "Other");
+
+ if (type == _EXT_DEBUG_TYPE_ERROR_ARB)
+ strcpy(debType, "Error");
+ else if (type == _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB)
+ strcpy(debType, "Deprecated behavior");
+ else if (type == _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB)
+ strcpy(debType, "Undefined behavior");
+ else if (type == _EXT_DEBUG_TYPE_PORTABILITY_ARB)
+ strcpy(debType, "Portability");
+ else if (type == _EXT_DEBUG_TYPE_PERFORMANCE_ARB)
+ strcpy(debType, "Performance");
+ else if (type == _EXT_DEBUG_TYPE_OTHER_ARB)
+ strcpy(debType, "Other");
+
+ if (severity == _EXT_DEBUG_SEVERITY_HIGH_ARB)
+ strcpy(debSev, "High");
+ else if (severity == _EXT_DEBUG_SEVERITY_MEDIUM_ARB)
+ strcpy(debSev, "Medium");
+ else if (severity == _EXT_DEBUG_SEVERITY_LOW_ARB)
+ strcpy(debSev, "Low");
+
+ String output = String() + "GL ERROR: Source: " + debSource + "\tType: " + debType + "\tID: " + itos(id) + "\tSeverity: " + debSev + "\tMessage: " + message;
ERR_PRINTS(output);
-
}
-
typedef void (*DEBUGPROCARB)(GLenum source,
- GLenum type,
- GLuint id,
- GLenum severity,
- GLsizei length,
- const char* message,
- const void* userParam);
+ GLenum type,
+ GLuint id,
+ GLenum severity,
+ GLsizei length,
+ const char *message,
+ const void *userParam);
-typedef void (* DebugMessageCallbackARB) (DEBUGPROCARB callback, const void *userParam);
+typedef void (*DebugMessageCallbackARB)(DEBUGPROCARB callback, const void *userParam);
void RasterizerGLES3::initialize() {
@@ -143,30 +140,30 @@ void RasterizerGLES3::initialize() {
#ifdef GLEW_ENABLED
GLuint res = glewInit();
- ERR_FAIL_COND(res!=GLEW_OK);
+ ERR_FAIL_COND(res != GLEW_OK);
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line(String("GLES2: Using GLEW ") + (const char*) glewGetString(GLEW_VERSION));
+ print_line(String("GLES2: Using GLEW ") + (const char *)glewGetString(GLEW_VERSION));
}
// Check for GL 2.1 compatibility, if not bail out
if (!glewIsSupported("GL_VERSION_3_0")) {
ERR_PRINT("Your system's graphic drivers seem not to support OpenGL 3.0+ / GLES 3.0, sorry :(\n"
- "Try a drivers update, buy a new GPU or try software rendering on Linux; Godot will now crash with a segmentation fault.");
+ "Try a drivers update, buy a new GPU or try software rendering on Linux; Godot will now crash with a segmentation fault.");
OS::get_singleton()->alert("Your system's graphic drivers seem not to support OpenGL 3.0+ / GLES 3.0, sorry :(\n"
- "Godot Engine will self-destruct as soon as you acknowledge this error message.",
- "Fatal error: Insufficient OpenGL / GLES drivers");
+ "Godot Engine will self-destruct as soon as you acknowledge this error message.",
+ "Fatal error: Insufficient OpenGL / GLES drivers");
// TODO: If it's even possible, we should stop the execution without segfault and memory leaks :)
}
#endif
#ifdef GLAD_ENABLED
- if(!gladLoadGL()) {
+ if (!gladLoadGL()) {
ERR_PRINT("Error initializing GLAD");
}
#ifdef __APPLE__
- // FIXME glDebugMessageCallbackARB does not seem to work on Mac OS X and opengl 3, this may be an issue with our opengl canvas..
+// FIXME glDebugMessageCallbackARB does not seem to work on Mac OS X and opengl 3, this may be an issue with our opengl canvas..
#else
glEnable(_EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
glDebugMessageCallbackARB(_gl_debug_print, NULL);
@@ -175,8 +172,7 @@ void RasterizerGLES3::initialize() {
#endif
-
-/* glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_ERROR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE);
+ /* glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_ERROR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE);
glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE);
glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE);
glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_PORTABILITY_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE);
@@ -194,114 +190,104 @@ void RasterizerGLES3::initialize() {
scene->initialize();
}
-void RasterizerGLES3::begin_frame(){
+void RasterizerGLES3::begin_frame() {
uint64_t tick = OS::get_singleton()->get_ticks_usec();
- double time_total = double(tick)/1000000.0;
+ double time_total = double(tick) / 1000000.0;
- storage->frame.time[0]=time_total;
- storage->frame.time[1]=Math::fmod(time_total,3600);
- storage->frame.time[2]=Math::fmod(time_total,900);
- storage->frame.time[3]=Math::fmod(time_total,60);
+ storage->frame.time[0] = time_total;
+ storage->frame.time[1] = Math::fmod(time_total, 3600);
+ storage->frame.time[2] = Math::fmod(time_total, 900);
+ storage->frame.time[3] = Math::fmod(time_total, 60);
storage->frame.count++;
- storage->frame.delta = double(tick-storage->frame.prev_tick)/1000000.0;
- if (storage->frame.prev_tick==0) {
+ storage->frame.delta = double(tick - storage->frame.prev_tick) / 1000000.0;
+ if (storage->frame.prev_tick == 0) {
//to avoid hiccups
- storage->frame.delta=0.001;
+ storage->frame.delta = 0.001;
}
- storage->frame.prev_tick=tick;
-
+ storage->frame.prev_tick = tick;
storage->update_dirty_resources();
-
- storage->info.render_object_count=0;
- storage->info.render_material_switch_count=0;
- storage->info.render_surface_switch_count=0;
- storage->info.render_shader_rebind_count=0;
- storage->info.render_vertices_count=0;
-
+ storage->info.render_object_count = 0;
+ storage->info.render_material_switch_count = 0;
+ storage->info.render_surface_switch_count = 0;
+ storage->info.render_shader_rebind_count = 0;
+ storage->info.render_vertices_count = 0;
scene->iteration();
-
-
-
-
}
-void RasterizerGLES3::set_current_render_target(RID p_render_target){
+void RasterizerGLES3::set_current_render_target(RID p_render_target) {
if (!p_render_target.is_valid() && storage->frame.current_rt && storage->frame.clear_request) {
//handle pending clear request, if the framebuffer was not cleared
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo);
- print_line("unbind clear of: "+storage->frame.clear_request_color);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
+ print_line("unbind clear of: " + storage->frame.clear_request_color);
glClearColor(
- storage->frame.clear_request_color.r,
- storage->frame.clear_request_color.g,
- storage->frame.clear_request_color.b,
- storage->frame.clear_request_color.a );
+ storage->frame.clear_request_color.r,
+ storage->frame.clear_request_color.g,
+ storage->frame.clear_request_color.b,
+ storage->frame.clear_request_color.a);
glClear(GL_COLOR_BUFFER_BIT);
-
}
if (p_render_target.is_valid()) {
- RasterizerStorageGLES3::RenderTarget * rt = storage->render_target_owner.getornull(p_render_target);
+ RasterizerStorageGLES3::RenderTarget *rt = storage->render_target_owner.getornull(p_render_target);
if (!rt) {
- storage->frame.current_rt=NULL;
+ storage->frame.current_rt = NULL;
}
ERR_FAIL_COND(!rt);
- storage->frame.current_rt=rt;
- storage->frame.clear_request=false;
+ storage->frame.current_rt = rt;
+ storage->frame.clear_request = false;
- glViewport(0,0,rt->width,rt->height);
+ glViewport(0, 0, rt->width, rt->height);
} else {
- storage->frame.current_rt=NULL;
- storage->frame.clear_request=false;
- glViewport(0,0,OS::get_singleton()->get_window_size().width,OS::get_singleton()->get_window_size().height);
- glBindFramebuffer(GL_FRAMEBUFFER,RasterizerStorageGLES3::system_fbo);
+ storage->frame.current_rt = NULL;
+ storage->frame.clear_request = false;
+ glViewport(0, 0, OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height);
+ glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
}
}
void RasterizerGLES3::restore_render_target() {
- ERR_FAIL_COND(storage->frame.current_rt==NULL);
- RasterizerStorageGLES3::RenderTarget * rt = storage->frame.current_rt;
- glBindFramebuffer(GL_FRAMEBUFFER,rt->fbo);
- glViewport(0,0,rt->width,rt->height);
-
+ ERR_FAIL_COND(storage->frame.current_rt == NULL);
+ RasterizerStorageGLES3::RenderTarget *rt = storage->frame.current_rt;
+ glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
+ glViewport(0, 0, rt->width, rt->height);
}
-void RasterizerGLES3::clear_render_target(const Color& p_color) {
+void RasterizerGLES3::clear_render_target(const Color &p_color) {
ERR_FAIL_COND(!storage->frame.current_rt);
- storage->frame.clear_request=true;
- storage->frame.clear_request_color=p_color;
-
+ storage->frame.clear_request = true;
+ storage->frame.clear_request_color = p_color;
}
-void RasterizerGLES3::blit_render_target_to_screen(RID p_render_target,const Rect2& p_screen_rect,int p_screen){
+void RasterizerGLES3::blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect, int p_screen) {
- ERR_FAIL_COND( storage->frame.current_rt );
+ ERR_FAIL_COND(storage->frame.current_rt);
RasterizerStorageGLES3::RenderTarget *rt = storage->render_target_owner.getornull(p_render_target);
ERR_FAIL_COND(!rt);
canvas->canvas_begin();
glDisable(GL_BLEND);
- glBindFramebuffer(GL_FRAMEBUFFER,RasterizerStorageGLES3::system_fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,rt->color);
- canvas->draw_generic_textured_rect(p_screen_rect,Rect2(0,0,1,-1));
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, rt->color);
+ canvas->draw_generic_textured_rect(p_screen_rect, Rect2(0, 0, 1, -1));
+ glBindTexture(GL_TEXTURE_2D, 0);
canvas->canvas_end();
}
-void RasterizerGLES3::end_frame(){
+void RasterizerGLES3::end_frame() {
#if 0
canvas->canvas_begin();
@@ -335,7 +321,7 @@ void RasterizerGLES3::end_frame(){
#endif
OS::get_singleton()->swap_buffers();
-/* print_line("objects: "+itos(storage->info.render_object_count));
+ /* print_line("objects: "+itos(storage->info.render_object_count));
print_line("material chages: "+itos(storage->info.render_material_switch_count));
print_line("surface changes: "+itos(storage->info.render_surface_switch_count));
print_line("shader changes: "+itos(storage->info.render_shader_rebind_count));
@@ -343,45 +329,38 @@ void RasterizerGLES3::end_frame(){
*/
}
-void RasterizerGLES3::finalize(){
+void RasterizerGLES3::finalize() {
storage->finalize();
canvas->finalize();
}
-
Rasterizer *RasterizerGLES3::_create_current() {
- return memnew( RasterizerGLES3 );
+ return memnew(RasterizerGLES3);
}
void RasterizerGLES3::make_current() {
- _create_func=_create_current;
+ _create_func = _create_current;
}
-
void RasterizerGLES3::register_config() {
- GLOBAL_DEF("rendering/gles3/render_architecture",0);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/render_architecture",PropertyInfo(Variant::INT,"",PROPERTY_HINT_ENUM,"Desktop,Mobile"));
- GLOBAL_DEF("rendering/quality/use_nearest_mipmap_filter",false);
- GLOBAL_DEF("rendering/quality/anisotropic_filter_level",4.0);
-
+ GLOBAL_DEF("rendering/gles3/render_architecture", 0);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/render_architecture", PropertyInfo(Variant::INT, "", PROPERTY_HINT_ENUM, "Desktop,Mobile"));
+ GLOBAL_DEF("rendering/quality/use_nearest_mipmap_filter", false);
+ GLOBAL_DEF("rendering/quality/anisotropic_filter_level", 4.0);
}
-RasterizerGLES3::RasterizerGLES3()
-{
-
- storage = memnew( RasterizerStorageGLES3 );
- canvas = memnew( RasterizerCanvasGLES3 );
- scene = memnew( RasterizerSceneGLES3 );
- canvas->storage=storage;
- storage->canvas=canvas;
- scene->storage=storage;
- storage->scene=scene;
-
-
+RasterizerGLES3::RasterizerGLES3() {
+ storage = memnew(RasterizerStorageGLES3);
+ canvas = memnew(RasterizerCanvasGLES3);
+ scene = memnew(RasterizerSceneGLES3);
+ canvas->storage = storage;
+ storage->canvas = canvas;
+ scene->storage = storage;
+ storage->scene = scene;
}
RasterizerGLES3::~RasterizerGLES3() {
diff --git a/drivers/gles3/rasterizer_gles3.h b/drivers/gles3/rasterizer_gles3.h
index 21e16b3bba..823f39ae8f 100644
--- a/drivers/gles3/rasterizer_gles3.h
+++ b/drivers/gles3/rasterizer_gles3.h
@@ -29,11 +29,10 @@
#ifndef RASTERIZERGLES3_H
#define RASTERIZERGLES3_H
-#include "servers/visual/rasterizer.h"
-#include "rasterizer_storage_gles3.h"
#include "rasterizer_canvas_gles3.h"
#include "rasterizer_scene_gles3.h"
-
+#include "rasterizer_storage_gles3.h"
+#include "servers/visual/rasterizer.h"
class RasterizerGLES3 : public Rasterizer {
@@ -44,7 +43,6 @@ class RasterizerGLES3 : public Rasterizer {
RasterizerSceneGLES3 *scene;
public:
-
virtual RasterizerStorage *get_storage();
virtual RasterizerCanvas *get_canvas();
virtual RasterizerScene *get_scene();
@@ -53,14 +51,13 @@ public:
virtual void begin_frame();
virtual void set_current_render_target(RID p_render_target);
virtual void restore_render_target();
- virtual void clear_render_target(const Color& p_color);
- virtual void blit_render_target_to_screen(RID p_render_target,const Rect2& p_screen_rect,int p_screen=0);
+ virtual void clear_render_target(const Color &p_color);
+ virtual void blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect, int p_screen = 0);
virtual void end_frame();
virtual void finalize();
static void make_current();
-
static void register_config();
RasterizerGLES3();
~RasterizerGLES3();
diff --git a/drivers/gles3/rasterizer_scene_gles3.cpp b/drivers/gles3/rasterizer_scene_gles3.cpp
index f09e6ce904..b5d58ee997 100644
--- a/drivers/gles3/rasterizer_scene_gles3.cpp
+++ b/drivers/gles3/rasterizer_scene_gles3.cpp
@@ -36,7 +36,7 @@
#define glClearDepth glClearDepthf
#endif
-static const GLenum _cube_side_enum[6]={
+static const GLenum _cube_side_enum[6] = {
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
@@ -47,53 +47,51 @@ static const GLenum _cube_side_enum[6]={
};
-
-static _FORCE_INLINE_ void store_transform2d(const Transform2D& p_mtx, float* p_array) {
-
- p_array[ 0]=p_mtx.elements[0][0];
- p_array[ 1]=p_mtx.elements[0][1];
- p_array[ 2]=0;
- p_array[ 3]=0;
- p_array[ 4]=p_mtx.elements[1][0];
- p_array[ 5]=p_mtx.elements[1][1];
- p_array[ 6]=0;
- p_array[ 7]=0;
- p_array[ 8]=0;
- p_array[ 9]=0;
- p_array[10]=1;
- p_array[11]=0;
- p_array[12]=p_mtx.elements[2][0];
- p_array[13]=p_mtx.elements[2][1];
- p_array[14]=0;
- p_array[15]=1;
+static _FORCE_INLINE_ void store_transform2d(const Transform2D &p_mtx, float *p_array) {
+
+ p_array[0] = p_mtx.elements[0][0];
+ p_array[1] = p_mtx.elements[0][1];
+ p_array[2] = 0;
+ p_array[3] = 0;
+ p_array[4] = p_mtx.elements[1][0];
+ p_array[5] = p_mtx.elements[1][1];
+ p_array[6] = 0;
+ p_array[7] = 0;
+ p_array[8] = 0;
+ p_array[9] = 0;
+ p_array[10] = 1;
+ p_array[11] = 0;
+ p_array[12] = p_mtx.elements[2][0];
+ p_array[13] = p_mtx.elements[2][1];
+ p_array[14] = 0;
+ p_array[15] = 1;
}
-
-static _FORCE_INLINE_ void store_transform(const Transform& p_mtx, float* p_array) {
- p_array[ 0]=p_mtx.basis.elements[0][0];
- p_array[ 1]=p_mtx.basis.elements[1][0];
- p_array[ 2]=p_mtx.basis.elements[2][0];
- p_array[ 3]=0;
- p_array[ 4]=p_mtx.basis.elements[0][1];
- p_array[ 5]=p_mtx.basis.elements[1][1];
- p_array[ 6]=p_mtx.basis.elements[2][1];
- p_array[ 7]=0;
- p_array[ 8]=p_mtx.basis.elements[0][2];
- p_array[ 9]=p_mtx.basis.elements[1][2];
- p_array[10]=p_mtx.basis.elements[2][2];
- p_array[11]=0;
- p_array[12]=p_mtx.origin.x;
- p_array[13]=p_mtx.origin.y;
- p_array[14]=p_mtx.origin.z;
- p_array[15]=1;
+static _FORCE_INLINE_ void store_transform(const Transform &p_mtx, float *p_array) {
+ p_array[0] = p_mtx.basis.elements[0][0];
+ p_array[1] = p_mtx.basis.elements[1][0];
+ p_array[2] = p_mtx.basis.elements[2][0];
+ p_array[3] = 0;
+ p_array[4] = p_mtx.basis.elements[0][1];
+ p_array[5] = p_mtx.basis.elements[1][1];
+ p_array[6] = p_mtx.basis.elements[2][1];
+ p_array[7] = 0;
+ p_array[8] = p_mtx.basis.elements[0][2];
+ p_array[9] = p_mtx.basis.elements[1][2];
+ p_array[10] = p_mtx.basis.elements[2][2];
+ p_array[11] = 0;
+ p_array[12] = p_mtx.origin.x;
+ p_array[13] = p_mtx.origin.y;
+ p_array[14] = p_mtx.origin.z;
+ p_array[15] = 1;
}
-static _FORCE_INLINE_ void store_camera(const CameraMatrix& p_mtx, float* p_array) {
+static _FORCE_INLINE_ void store_camera(const CameraMatrix &p_mtx, float *p_array) {
- for (int i=0;i<4;i++) {
- for (int j=0;j<4;j++) {
+ for (int i = 0; i < 4; i++) {
+ for (int j = 0; j < 4; j++) {
- p_array[i*4+j]=p_mtx.matrix[i][j];
+ p_array[i * 4 + j] = p_mtx.matrix[i][j];
}
}
}
@@ -102,48 +100,47 @@ static _FORCE_INLINE_ void store_camera(const CameraMatrix& p_mtx, float* p_arra
RID RasterizerSceneGLES3::shadow_atlas_create() {
- ShadowAtlas *shadow_atlas = memnew( ShadowAtlas );
- shadow_atlas->fbo=0;
- shadow_atlas->depth=0;
- shadow_atlas->size=0;
- shadow_atlas->smallest_subdiv=0;
+ ShadowAtlas *shadow_atlas = memnew(ShadowAtlas);
+ shadow_atlas->fbo = 0;
+ shadow_atlas->depth = 0;
+ shadow_atlas->size = 0;
+ shadow_atlas->smallest_subdiv = 0;
- for(int i=0;i<4;i++) {
- shadow_atlas->size_order[i]=i;
+ for (int i = 0; i < 4; i++) {
+ shadow_atlas->size_order[i] = i;
}
-
return shadow_atlas_owner.make_rid(shadow_atlas);
}
-void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas,int p_size){
+void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas, int p_size) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
ERR_FAIL_COND(!shadow_atlas);
- ERR_FAIL_COND(p_size<0);
+ ERR_FAIL_COND(p_size < 0);
p_size = nearest_power_of_2(p_size);
- if (p_size==shadow_atlas->size)
+ if (p_size == shadow_atlas->size)
return;
if (shadow_atlas->fbo) {
- glDeleteTextures(1,&shadow_atlas->depth);
- glDeleteFramebuffers(1,&shadow_atlas->fbo);
+ glDeleteTextures(1, &shadow_atlas->depth);
+ glDeleteFramebuffers(1, &shadow_atlas->fbo);
- shadow_atlas->depth=0;
- shadow_atlas->fbo=0;
+ shadow_atlas->depth = 0;
+ shadow_atlas->fbo = 0;
print_line("erasing atlas");
}
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
//clear subdivisions
shadow_atlas->quadrants[i].shadows.resize(0);
- shadow_atlas->quadrants[i].shadows.resize( 1<<shadow_atlas->quadrants[i].subdivision );
+ shadow_atlas->quadrants[i].shadows.resize(1 << shadow_atlas->quadrants[i].subdivision);
}
//erase shadow atlas reference from lights
- for (Map<RID,uint32_t>::Element *E=shadow_atlas->shadow_owners.front();E;E=E->next()) {
+ for (Map<RID, uint32_t>::Element *E = shadow_atlas->shadow_owners.front(); E; E = E->next()) {
LightInstance *li = light_instance_owner.getornull(E->key());
ERR_CONTINUE(!li);
li->shadow_atlases.erase(p_atlas);
@@ -152,9 +149,9 @@ void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas,int p_size){
//clear owners
shadow_atlas->shadow_owners.clear();
- shadow_atlas->size=p_size;
+ shadow_atlas->size = p_size;
- if (shadow_atlas->size) {
+ if (shadow_atlas->size) {
glGenFramebuffers(1, &shadow_atlas->fbo);
glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo);
@@ -163,7 +160,7 @@ void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas,int p_size){
glGenTextures(1, &shadow_atlas->depth);
glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadow_atlas->size, shadow_atlas->size, 0,
- GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -171,41 +168,37 @@ void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas,int p_size){
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, shadow_atlas->depth, 0);
+ GL_TEXTURE_2D, shadow_atlas->depth, 0);
- glViewport(0,0,shadow_atlas->size,shadow_atlas->size);
+ glViewport(0, 0, shadow_atlas->size, shadow_atlas->size);
glClearDepth(0.0f);
glClear(GL_DEPTH_BUFFER_BIT);
- glBindFramebuffer(GL_FRAMEBUFFER,0);
-
-
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
}
-
-void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas,int p_quadrant,int p_subdivision){
+void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
ERR_FAIL_COND(!shadow_atlas);
- ERR_FAIL_INDEX(p_quadrant,4);
- ERR_FAIL_INDEX(p_subdivision,16384);
-
+ ERR_FAIL_INDEX(p_quadrant, 4);
+ ERR_FAIL_INDEX(p_subdivision, 16384);
uint32_t subdiv = nearest_power_of_2(p_subdivision);
- if (subdiv&0xaaaaaaaa) { //sqrt(subdiv) must be integer
- subdiv<<=1;
+ if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
+ subdiv <<= 1;
}
- subdiv=int(Math::sqrt((float)subdiv));
+ subdiv = int(Math::sqrt((float)subdiv));
//obtain the number that will be x*x
- if (shadow_atlas->quadrants[p_quadrant].subdivision==subdiv)
+ if (shadow_atlas->quadrants[p_quadrant].subdivision == subdiv)
return;
//erase all data from quadrant
- for(int i=0;i<shadow_atlas->quadrants[p_quadrant].shadows.size();i++) {
+ for (int i = 0; i < shadow_atlas->quadrants[p_quadrant].shadows.size(); i++) {
if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) {
shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner);
@@ -216,51 +209,45 @@ void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas,int
}
shadow_atlas->quadrants[p_quadrant].shadows.resize(0);
- shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv*subdiv);
- shadow_atlas->quadrants[p_quadrant].subdivision=subdiv;
+ shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv * subdiv);
+ shadow_atlas->quadrants[p_quadrant].subdivision = subdiv;
//cache the smallest subdiv (for faster allocation in light update)
- shadow_atlas->smallest_subdiv=1<<30;
+ shadow_atlas->smallest_subdiv = 1 << 30;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
if (shadow_atlas->quadrants[i].subdivision) {
- shadow_atlas->smallest_subdiv=MIN(shadow_atlas->smallest_subdiv,shadow_atlas->quadrants[i].subdivision);
+ shadow_atlas->smallest_subdiv = MIN(shadow_atlas->smallest_subdiv, shadow_atlas->quadrants[i].subdivision);
}
}
- if (shadow_atlas->smallest_subdiv==1<<30) {
- shadow_atlas->smallest_subdiv=0;
+ if (shadow_atlas->smallest_subdiv == 1 << 30) {
+ shadow_atlas->smallest_subdiv = 0;
}
//resort the size orders, simple bublesort for 4 elements..
- int swaps=0;
+ int swaps = 0;
do {
- swaps=0;
+ swaps = 0;
- for(int i=0;i<3;i++) {
- if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i+1]].subdivision) {
- SWAP(shadow_atlas->size_order[i],shadow_atlas->size_order[i+1]);
+ for (int i = 0; i < 3; i++) {
+ if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i + 1]].subdivision) {
+ SWAP(shadow_atlas->size_order[i], shadow_atlas->size_order[i + 1]);
swaps++;
}
}
- } while(swaps>0);
-
-
-
-
-
+ } while (swaps > 0);
}
-bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas,int *p_in_quadrants,int p_quadrant_count,int p_current_subdiv,uint64_t p_tick,int &r_quadrant,int &r_shadow) {
-
+bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow) {
- for(int i=p_quadrant_count-1;i>=0;i--) {
+ for (int i = p_quadrant_count - 1; i >= 0; i--) {
int qidx = p_in_quadrants[i];
- if (shadow_atlas->quadrants[qidx].subdivision==p_current_subdiv) {
+ if (shadow_atlas->quadrants[qidx].subdivision == p_current_subdiv) {
return false;
}
@@ -268,120 +255,113 @@ bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas,i
int sc = shadow_atlas->quadrants[qidx].shadows.size();
ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptr();
- int found_free_idx=-1; //found a free one
- int found_used_idx=-1; //found existing one, must steal it
+ int found_free_idx = -1; //found a free one
+ int found_used_idx = -1; //found existing one, must steal it
uint64_t min_pass; // pass of the existing one, try to use the least recently used one (LRU fashion)
- for(int j=0;j<sc;j++) {
+ for (int j = 0; j < sc; j++) {
if (!sarr[j].owner.is_valid()) {
- found_free_idx=j;
+ found_free_idx = j;
break;
}
LightInstance *sli = light_instance_owner.getornull(sarr[j].owner);
ERR_CONTINUE(!sli);
- if (sli->last_scene_pass!=scene_pass) {
+ if (sli->last_scene_pass != scene_pass) {
//was just allocated, don't kill it so soon, wait a bit..
- if (p_tick-sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec)
+ if (p_tick - sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec)
continue;
- if (found_used_idx==-1 || sli->last_scene_pass<min_pass) {
- found_used_idx=j;
- min_pass=sli->last_scene_pass;
+ if (found_used_idx == -1 || sli->last_scene_pass < min_pass) {
+ found_used_idx = j;
+ min_pass = sli->last_scene_pass;
}
}
}
- if (found_free_idx==-1 && found_used_idx==-1)
+ if (found_free_idx == -1 && found_used_idx == -1)
continue; //nothing found
- if (found_free_idx==-1 && found_used_idx!=-1) {
- found_free_idx=found_used_idx;
+ if (found_free_idx == -1 && found_used_idx != -1) {
+ found_free_idx = found_used_idx;
}
- r_quadrant=qidx;
- r_shadow=found_free_idx;
+ r_quadrant = qidx;
+ r_shadow = found_free_idx;
return true;
}
return false;
-
}
-
-bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version){
-
+bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas);
- ERR_FAIL_COND_V(!shadow_atlas,false);
+ ERR_FAIL_COND_V(!shadow_atlas, false);
LightInstance *li = light_instance_owner.getornull(p_light_intance);
- ERR_FAIL_COND_V(!li,false);
+ ERR_FAIL_COND_V(!li, false);
- if (shadow_atlas->size==0 || shadow_atlas->smallest_subdiv==0) {
+ if (shadow_atlas->size == 0 || shadow_atlas->smallest_subdiv == 0) {
return false;
}
- uint32_t quad_size = shadow_atlas->size>>1;
- int desired_fit = MIN(quad_size/shadow_atlas->smallest_subdiv,nearest_power_of_2(quad_size*p_coverage));
-
+ uint32_t quad_size = shadow_atlas->size >> 1;
+ int desired_fit = MIN(quad_size / shadow_atlas->smallest_subdiv, nearest_power_of_2(quad_size * p_coverage));
int valid_quadrants[4];
- int valid_quadrant_count=0;
- int best_size=-1; //best size found
- int best_subdiv=-1; //subdiv for the best size
+ int valid_quadrant_count = 0;
+ int best_size = -1; //best size found
+ int best_subdiv = -1; //subdiv for the best size
//find the quadrants this fits into, and the best possible size it can fit into
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
int q = shadow_atlas->size_order[i];
int sd = shadow_atlas->quadrants[q].subdivision;
- if (sd==0)
+ if (sd == 0)
continue; //unused
int max_fit = quad_size / sd;
- if (best_size!=-1 && max_fit>best_size)
+ if (best_size != -1 && max_fit > best_size)
break; //too large
- valid_quadrants[valid_quadrant_count++]=q;
- best_subdiv=sd;
+ valid_quadrants[valid_quadrant_count++] = q;
+ best_subdiv = sd;
- if (max_fit>=desired_fit) {
- best_size=max_fit;
+ if (max_fit >= desired_fit) {
+ best_size = max_fit;
}
}
- ERR_FAIL_COND_V(valid_quadrant_count==0,false);
+ ERR_FAIL_COND_V(valid_quadrant_count == 0, false);
uint64_t tick = OS::get_singleton()->get_ticks_msec();
-
//see if it already exists
if (shadow_atlas->shadow_owners.has(p_light_intance)) {
//it does!
uint32_t key = shadow_atlas->shadow_owners[p_light_intance];
- uint32_t q = (key>>ShadowAtlas::QUADRANT_SHIFT)&0x3;
- uint32_t s = key&ShadowAtlas::SHADOW_INDEX_MASK;
-
- bool should_realloc=shadow_atlas->quadrants[q].subdivision!=best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick-tick > shadow_atlas_realloc_tolerance_msec);
- bool should_redraw=shadow_atlas->quadrants[q].shadows[s].version!=p_light_version;
-
+ uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
+ uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
+ bool should_realloc = shadow_atlas->quadrants[q].subdivision != best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick - tick > shadow_atlas_realloc_tolerance_msec);
+ bool should_redraw = shadow_atlas->quadrants[q].shadows[s].version != p_light_version;
if (!should_realloc) {
- shadow_atlas->quadrants[q].shadows[s].version=p_light_version;
+ shadow_atlas->quadrants[q].shadows[s].version = p_light_version;
//already existing, see if it should redraw or it's just OK
return should_redraw;
}
- int new_quadrant,new_shadow;
+ int new_quadrant, new_shadow;
//find a better place
- if (_shadow_atlas_find_shadow(shadow_atlas,valid_quadrants,valid_quadrant_count,shadow_atlas->quadrants[q].subdivision,tick,new_quadrant,new_shadow)) {
+ if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, shadow_atlas->quadrants[q].subdivision, tick, new_quadrant, new_shadow)) {
//found a better place!
ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows[new_shadow];
if (sh->owner.is_valid()) {
@@ -392,18 +372,18 @@ bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_in
}
//erase previous
- shadow_atlas->quadrants[q].shadows[s].version=0;
- shadow_atlas->quadrants[q].shadows[s].owner=RID();
+ shadow_atlas->quadrants[q].shadows[s].version = 0;
+ shadow_atlas->quadrants[q].shadows[s].owner = RID();
- sh->owner=p_light_intance;
- sh->alloc_tick=tick;
- sh->version=p_light_version;
+ sh->owner = p_light_intance;
+ sh->alloc_tick = tick;
+ sh->version = p_light_version;
//make new key
- key=new_quadrant<<ShadowAtlas::QUADRANT_SHIFT;
- key|=new_shadow;
+ key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
+ key |= new_shadow;
//update it in map
- shadow_atlas->shadow_owners[p_light_intance]=key;
+ shadow_atlas->shadow_owners[p_light_intance] = key;
//make it dirty, as it should redraw anyway
return true;
}
@@ -412,15 +392,15 @@ bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_in
//already existing, see if it should redraw or it's just OK
- shadow_atlas->quadrants[q].shadows[s].version=p_light_version;
+ shadow_atlas->quadrants[q].shadows[s].version = p_light_version;
return should_redraw;
}
- int new_quadrant,new_shadow;
+ int new_quadrant, new_shadow;
//find a better place
- if (_shadow_atlas_find_shadow(shadow_atlas,valid_quadrants,valid_quadrant_count,-1,tick,new_quadrant,new_shadow)) {
+ if (_shadow_atlas_find_shadow(shadow_atlas, valid_quadrants, valid_quadrant_count, -1, tick, new_quadrant, new_shadow)) {
//found a better place!
ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows[new_shadow];
if (sh->owner.is_valid()) {
@@ -430,15 +410,15 @@ bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_in
sli->shadow_atlases.erase(p_atlas);
}
- sh->owner=p_light_intance;
- sh->alloc_tick=tick;
- sh->version=p_light_version;
+ sh->owner = p_light_intance;
+ sh->alloc_tick = tick;
+ sh->version = p_light_version;
//make new key
- uint32_t key=new_quadrant<<ShadowAtlas::QUADRANT_SHIFT;
- key|=new_shadow;
+ uint32_t key = new_quadrant << ShadowAtlas::QUADRANT_SHIFT;
+ key |= new_shadow;
//update it in map
- shadow_atlas->shadow_owners[p_light_intance]=key;
+ shadow_atlas->shadow_owners[p_light_intance] = key;
//make it dirty, as it should redraw anyway
return true;
@@ -447,113 +427,106 @@ bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_in
//no place to allocate this light, apologies
return false;
-
-
-
-
}
void RasterizerSceneGLES3::set_directional_shadow_count(int p_count) {
- directional_shadow.light_count=p_count;
- directional_shadow.current_light=0;
+ directional_shadow.light_count = p_count;
+ directional_shadow.current_light = 0;
}
int RasterizerSceneGLES3::get_directional_light_shadow_size(RID p_light_intance) {
- ERR_FAIL_COND_V(directional_shadow.light_count==0,0);
+ ERR_FAIL_COND_V(directional_shadow.light_count == 0, 0);
int shadow_size;
- if (directional_shadow.light_count==1) {
+ if (directional_shadow.light_count == 1) {
shadow_size = directional_shadow.size;
} else {
- shadow_size = directional_shadow.size/2; //more than 4 not supported anyway
+ shadow_size = directional_shadow.size / 2; //more than 4 not supported anyway
}
LightInstance *light_instance = light_instance_owner.getornull(p_light_intance);
- ERR_FAIL_COND_V(!light_instance,0);
+ ERR_FAIL_COND_V(!light_instance, 0);
- switch(light_instance->light_ptr->directional_shadow_mode) {
- case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none
+ switch (light_instance->light_ptr->directional_shadow_mode) {
+ case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
+ break; //none
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
- case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: shadow_size/=2; break;
+ case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: shadow_size /= 2; break;
}
return shadow_size;
-
}
//////////////////////////////////////////////////////
RID RasterizerSceneGLES3::reflection_atlas_create() {
- ReflectionAtlas *reflection_atlas = memnew( ReflectionAtlas );
- reflection_atlas->subdiv=0;
- reflection_atlas->color=0;
- reflection_atlas->size=0;
- for(int i=0;i<6;i++) {
- reflection_atlas->fbo[i]=0;
+ ReflectionAtlas *reflection_atlas = memnew(ReflectionAtlas);
+ reflection_atlas->subdiv = 0;
+ reflection_atlas->color = 0;
+ reflection_atlas->size = 0;
+ for (int i = 0; i < 6; i++) {
+ reflection_atlas->fbo[i] = 0;
}
return reflection_atlas_owner.make_rid(reflection_atlas);
}
-void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas,int p_size) {
+void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas, int p_size) {
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas);
ERR_FAIL_COND(!reflection_atlas);
int size = nearest_power_of_2(p_size);
- if (size==reflection_atlas->size)
+ if (size == reflection_atlas->size)
return;
if (reflection_atlas->size) {
- for(int i=0;i<6;i++) {
- glDeleteFramebuffers(1,&reflection_atlas->fbo[i]);
- reflection_atlas->fbo[i]=0;
+ for (int i = 0; i < 6; i++) {
+ glDeleteFramebuffers(1, &reflection_atlas->fbo[i]);
+ reflection_atlas->fbo[i] = 0;
}
- glDeleteTextures(1,&reflection_atlas->color);
- reflection_atlas->color=0;
+ glDeleteTextures(1, &reflection_atlas->color);
+ reflection_atlas->color = 0;
}
- reflection_atlas->size=size;
+ reflection_atlas->size = size;
- for(int i=0;i<reflection_atlas->reflections.size();i++) {
+ for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
//erase probes reference to this
if (reflection_atlas->reflections[i].owner.is_valid()) {
ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner);
- reflection_atlas->reflections[i].owner=RID();
+ reflection_atlas->reflections[i].owner = RID();
ERR_CONTINUE(!reflection_probe_instance);
- reflection_probe_instance->reflection_atlas_index=-1;
- reflection_probe_instance->atlas=RID();
- reflection_probe_instance->render_step=-1;
+ reflection_probe_instance->reflection_atlas_index = -1;
+ reflection_probe_instance->atlas = RID();
+ reflection_probe_instance->render_step = -1;
}
}
-
if (reflection_atlas->size) {
- bool use_float=true;
-
+ bool use_float = true;
- GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2;
+ GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
GLenum format = GL_RGBA;
- GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV;
-
+ GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
// Create a texture for storing the color
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &reflection_atlas->color);
glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
- int mmsize=reflection_atlas->size;
+ int mmsize = reflection_atlas->size;
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glTexImage2D(GL_TEXTURE_2D, i, internal_format, mmsize, mmsize, 0,
- format, type, NULL);
+ format, type, NULL);
- mmsize>>=1;
+ mmsize >>= 1;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
@@ -564,194 +537,180 @@ void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas,int p_size)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 5);
- mmsize=reflection_atlas->size;
+ mmsize = reflection_atlas->size;
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glGenFramebuffers(1, &reflection_atlas->fbo[i]);
glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[i]);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflection_atlas->color, i);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflection_atlas->color, i);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
glDisable(GL_SCISSOR_TEST);
- glViewport(0,0,mmsize,mmsize);
- glClearColor(0,0,0,0);
+ glViewport(0, 0, mmsize, mmsize);
+ glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT); //it needs to be cleared, to avoid generating garbage
- mmsize>>=1;
-
+ mmsize >>= 1;
}
-
-
}
-
-
-
}
-
-void RasterizerSceneGLES3::reflection_atlas_set_subdivision(RID p_ref_atlas,int p_subdiv) {
+void RasterizerSceneGLES3::reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) {
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas);
ERR_FAIL_COND(!reflection_atlas);
uint32_t subdiv = nearest_power_of_2(p_subdiv);
- if (subdiv&0xaaaaaaaa) { //sqrt(subdiv) must be integer
- subdiv<<=1;
+ if (subdiv & 0xaaaaaaaa) { //sqrt(subdiv) must be integer
+ subdiv <<= 1;
}
- subdiv=int(Math::sqrt((float)subdiv));
+ subdiv = int(Math::sqrt((float)subdiv));
- if (reflection_atlas->subdiv==subdiv)
+ if (reflection_atlas->subdiv == subdiv)
return;
-
if (subdiv) {
- for(int i=0;i<reflection_atlas->reflections.size();i++) {
+ for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
//erase probes reference to this
if (reflection_atlas->reflections[i].owner.is_valid()) {
ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner);
- reflection_atlas->reflections[i].owner=RID();
+ reflection_atlas->reflections[i].owner = RID();
ERR_CONTINUE(!reflection_probe_instance);
- reflection_probe_instance->reflection_atlas_index=-1;
- reflection_probe_instance->atlas=RID();
- reflection_probe_instance->render_step=-1;
+ reflection_probe_instance->reflection_atlas_index = -1;
+ reflection_probe_instance->atlas = RID();
+ reflection_probe_instance->render_step = -1;
}
}
}
- reflection_atlas->subdiv=subdiv;
+ reflection_atlas->subdiv = subdiv;
- reflection_atlas->reflections.resize(subdiv*subdiv);
+ reflection_atlas->reflections.resize(subdiv * subdiv);
}
-
////////////////////////////////////////////////////
RID RasterizerSceneGLES3::reflection_probe_instance_create(RID p_probe) {
RasterizerStorageGLES3::ReflectionProbe *probe = storage->reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!probe,RID());
+ ERR_FAIL_COND_V(!probe, RID());
- ReflectionProbeInstance *rpi = memnew( ReflectionProbeInstance );
+ ReflectionProbeInstance *rpi = memnew(ReflectionProbeInstance);
- rpi->probe_ptr=probe;
- rpi->self=reflection_probe_instance_owner.make_rid(rpi);
- rpi->probe=p_probe;
- rpi->reflection_atlas_index=-1;
- rpi->render_step=-1;
- rpi->last_pass=0;
+ rpi->probe_ptr = probe;
+ rpi->self = reflection_probe_instance_owner.make_rid(rpi);
+ rpi->probe = p_probe;
+ rpi->reflection_atlas_index = -1;
+ rpi->render_step = -1;
+ rpi->last_pass = 0;
return rpi->self;
}
-void RasterizerSceneGLES3::reflection_probe_instance_set_transform(RID p_instance,const Transform& p_transform) {
+void RasterizerSceneGLES3::reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND(!rpi);
- rpi->transform=p_transform;
-
+ rpi->transform = p_transform;
}
void RasterizerSceneGLES3::reflection_probe_release_atlas_index(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
ERR_FAIL_COND(!rpi);
- if (rpi->reflection_atlas_index==-1)
+ if (rpi->reflection_atlas_index == -1)
return;
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas);
ERR_FAIL_COND(!reflection_atlas);
- ERR_FAIL_INDEX(rpi->reflection_atlas_index,reflection_atlas->reflections.size());
-
- ERR_FAIL_COND(reflection_atlas->reflections[rpi->reflection_atlas_index].owner!=rpi->self);
+ ERR_FAIL_INDEX(rpi->reflection_atlas_index, reflection_atlas->reflections.size());
- reflection_atlas->reflections[rpi->reflection_atlas_index].owner=RID();
+ ERR_FAIL_COND(reflection_atlas->reflections[rpi->reflection_atlas_index].owner != rpi->self);
- rpi->reflection_atlas_index=-1;
- rpi->atlas=RID();
- rpi->render_step=-1;
+ reflection_atlas->reflections[rpi->reflection_atlas_index].owner = RID();
+ rpi->reflection_atlas_index = -1;
+ rpi->atlas = RID();
+ rpi->render_step = -1;
}
bool RasterizerSceneGLES3::reflection_probe_instance_needs_redraw(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
- ERR_FAIL_COND_V(!rpi,false);
+ ERR_FAIL_COND_V(!rpi, false);
- return rpi->reflection_atlas_index==-1 || rpi->probe_ptr->update_mode==VS::REFLECTION_PROBE_UPDATE_ALWAYS;
+ return rpi->reflection_atlas_index == -1 || rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS;
}
-bool RasterizerSceneGLES3::reflection_probe_instance_has_reflection(RID p_instance){
+bool RasterizerSceneGLES3::reflection_probe_instance_has_reflection(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
- ERR_FAIL_COND_V(!rpi,false);
+ ERR_FAIL_COND_V(!rpi, false);
- return rpi->reflection_atlas_index!=-1;
+ return rpi->reflection_atlas_index != -1;
}
-bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance,RID p_reflection_atlas) {
+bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
- ERR_FAIL_COND_V(!rpi,false);
+ ERR_FAIL_COND_V(!rpi, false);
- rpi->render_step=0;
+ rpi->render_step = 0;
- if (rpi->reflection_atlas_index!=-1) {
+ if (rpi->reflection_atlas_index != -1) {
return true; //got one already
}
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
- ERR_FAIL_COND_V(!reflection_atlas,false);
-
+ ERR_FAIL_COND_V(!reflection_atlas, false);
- if (reflection_atlas->size==0 || reflection_atlas->subdiv==0) {
+ if (reflection_atlas->size == 0 || reflection_atlas->subdiv == 0) {
return false;
}
-
- int best_free=-1;
- int best_used=-1;
+ int best_free = -1;
+ int best_used = -1;
uint64_t best_used_frame;
- for(int i=0;i<reflection_atlas->reflections.size();i++) {
- if (reflection_atlas->reflections[i].owner==RID()) {
- best_free=i;
+ for (int i = 0; i < reflection_atlas->reflections.size(); i++) {
+ if (reflection_atlas->reflections[i].owner == RID()) {
+ best_free = i;
break;
}
- if (rpi->render_step<0 && reflection_atlas->reflections[i].last_frame<storage->frame.count &&
- (best_used==-1 || reflection_atlas->reflections[i].last_frame<best_used_frame)) {
- best_used=i;
- best_used_frame=reflection_atlas->reflections[i].last_frame;
+ if (rpi->render_step < 0 && reflection_atlas->reflections[i].last_frame < storage->frame.count &&
+ (best_used == -1 || reflection_atlas->reflections[i].last_frame < best_used_frame)) {
+ best_used = i;
+ best_used_frame = reflection_atlas->reflections[i].last_frame;
}
}
- if (best_free==-1 && best_used==-1) {
- return false ;// sorry, can not do. Try again next frame.
+ if (best_free == -1 && best_used == -1) {
+ return false; // sorry, can not do. Try again next frame.
}
- if (best_free==-1) {
+ if (best_free == -1) {
//find best from what is used
- best_free=best_used;
+ best_free = best_used;
ReflectionProbeInstance *victim_rpi = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[best_free].owner);
- ERR_FAIL_COND_V(!victim_rpi,false);
- victim_rpi->atlas=RID();
- victim_rpi->reflection_atlas_index=-1;
-
+ ERR_FAIL_COND_V(!victim_rpi, false);
+ victim_rpi->atlas = RID();
+ victim_rpi->reflection_atlas_index = -1;
}
- reflection_atlas->reflections[best_free].owner=p_instance;
- reflection_atlas->reflections[best_free].last_frame=storage->frame.count;
+ reflection_atlas->reflections[best_free].owner = p_instance;
+ reflection_atlas->reflections[best_free].last_frame = storage->frame.count;
- rpi->reflection_atlas_index=best_free;
- rpi->atlas=p_reflection_atlas;
- rpi->render_step=0;
+ rpi->reflection_atlas_index = best_free;
+ rpi->atlas = p_reflection_atlas;
+ rpi->render_step = 0;
return true;
}
@@ -759,303 +718,274 @@ bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance
bool RasterizerSceneGLES3::reflection_probe_instance_postprocess_step(RID p_instance) {
ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance);
- ERR_FAIL_COND_V(!rpi,true);
+ ERR_FAIL_COND_V(!rpi, true);
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas);
- ERR_FAIL_COND_V(!reflection_atlas,false);
+ ERR_FAIL_COND_V(!reflection_atlas, false);
- ERR_FAIL_COND_V(rpi->render_step>=6,true);
+ ERR_FAIL_COND_V(rpi->render_step >= 6, true);
- glBindFramebuffer(GL_FRAMEBUFFER,reflection_atlas->fbo[rpi->render_step]);
+ glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[rpi->render_step]);
state.cube_to_dp_shader.bind();
- int target_size=reflection_atlas->size/reflection_atlas->subdiv;
+ int target_size = reflection_atlas->size / reflection_atlas->subdiv;
- int cubemap_index=reflection_cubemaps.size()-1;
+ int cubemap_index = reflection_cubemaps.size() - 1;
- for(int i=reflection_cubemaps.size()-1;i>=0;i--) {
+ for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) {
//find appropriate cubemap to render to
- if (reflection_cubemaps[i].size>target_size*2)
+ if (reflection_cubemaps[i].size > target_size * 2)
break;
- cubemap_index=i;
+ cubemap_index = i;
}
glDisable(GL_BLEND);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_CUBE_MAP,reflection_cubemaps[cubemap_index].cubemap);
+ glBindTexture(GL_TEXTURE_CUBE_MAP, reflection_cubemaps[cubemap_index].cubemap);
glDisable(GL_CULL_FACE);
- storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,true);
+ storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
storage->shaders.cubemap_filter.bind();
int cell_size = reflection_atlas->size / reflection_atlas->subdiv;
- for(int i=0;i<rpi->render_step;i++) {
- cell_size>>=1; //mipmaps!
+ for (int i = 0; i < rpi->render_step; i++) {
+ cell_size >>= 1; //mipmaps!
}
int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size;
int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size;
- int width=cell_size;
- int height=cell_size;
+ int width = cell_size;
+ int height = cell_size;
- storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE,rpi->render_step==0);
- storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY,rpi->probe_ptr->update_mode==VS::REFLECTION_PROBE_UPDATE_ALWAYS);
- for(int i=0;i<2;i++) {
+ storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, rpi->render_step == 0);
+ storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, rpi->probe_ptr->update_mode == VS::REFLECTION_PROBE_UPDATE_ALWAYS);
+ for (int i = 0; i < 2; i++) {
- storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP,i>0);
- storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,rpi->render_step/5.0);
+ storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i > 0);
+ storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, rpi->render_step / 5.0);
- uint32_t local_width=width,local_height=height;
- uint32_t local_x=x,local_y=y;
+ uint32_t local_width = width, local_height = height;
+ uint32_t local_x = x, local_y = y;
- local_height/=2;
- local_y+=i*local_height;
+ local_height /= 2;
+ local_y += i * local_height;
- glViewport(local_x,local_y,local_width,local_height);
+ glViewport(local_x, local_y, local_width, local_height);
_copy_screen();
}
- storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE,false);
- storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY,false);
-
+ storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE, false);
+ storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY, false);
rpi->render_step++;
- return rpi->render_step==6;
+ return rpi->render_step == 6;
}
/* ENVIRONMENT API */
-RID RasterizerSceneGLES3::environment_create(){
+RID RasterizerSceneGLES3::environment_create() {
-
- Environment *env = memnew( Environment );
+ Environment *env = memnew(Environment);
return environment_owner.make_rid(env);
}
-void RasterizerSceneGLES3::environment_set_background(RID p_env,VS::EnvironmentBG p_bg){
+void RasterizerSceneGLES3::environment_set_background(RID p_env, VS::EnvironmentBG p_bg) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->bg_mode=p_bg;
+ env->bg_mode = p_bg;
}
-void RasterizerSceneGLES3::environment_set_skybox(RID p_env, RID p_skybox){
+void RasterizerSceneGLES3::environment_set_skybox(RID p_env, RID p_skybox) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->skybox=p_skybox;
-
+ env->skybox = p_skybox;
}
-void RasterizerSceneGLES3::environment_set_skybox_scale(RID p_env,float p_scale) {
+void RasterizerSceneGLES3::environment_set_skybox_scale(RID p_env, float p_scale) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->skybox_scale=p_scale;
-
+ env->skybox_scale = p_scale;
}
-void RasterizerSceneGLES3::environment_set_bg_color(RID p_env,const Color& p_color){
+void RasterizerSceneGLES3::environment_set_bg_color(RID p_env, const Color &p_color) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->bg_color=p_color;
-
+ env->bg_color = p_color;
}
-void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env,float p_energy) {
+void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env, float p_energy) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->bg_energy=p_energy;
-
+ env->bg_energy = p_energy;
}
-void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env,int p_max_layer){
+void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env, int p_max_layer) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->canvas_max_layer=p_max_layer;
-
+ env->canvas_max_layer = p_max_layer;
}
-void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color& p_color, float p_energy, float p_skybox_contribution){
+void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy, float p_skybox_contribution) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->ambient_color=p_color;
- env->ambient_energy=p_energy;
- env->ambient_skybox_contribution=p_skybox_contribution;
-
+ env->ambient_color = p_color;
+ env->ambient_energy = p_energy;
+ env->ambient_skybox_contribution = p_skybox_contribution;
}
+void RasterizerSceneGLES3::environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) {
-
-void RasterizerSceneGLES3::environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_amount,VS::EnvironmentDOFBlurQuality p_quality){
-
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->dof_blur_far_enabled=p_enable;
- env->dof_blur_far_distance=p_distance;
- env->dof_blur_far_transition=p_transition;
- env->dof_blur_far_amount=p_amount;
- env->dof_blur_far_quality=p_quality;
-
-
+ env->dof_blur_far_enabled = p_enable;
+ env->dof_blur_far_distance = p_distance;
+ env->dof_blur_far_transition = p_transition;
+ env->dof_blur_far_amount = p_amount;
+ env->dof_blur_far_quality = p_quality;
}
-void RasterizerSceneGLES3::environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_amount,VS::EnvironmentDOFBlurQuality p_quality){
+void RasterizerSceneGLES3::environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_amount, VS::EnvironmentDOFBlurQuality p_quality) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->dof_blur_near_enabled=p_enable;
- env->dof_blur_near_distance=p_distance;
- env->dof_blur_near_transition=p_transition;
- env->dof_blur_near_amount=p_amount;
- env->dof_blur_near_quality=p_quality;
-
-
+ env->dof_blur_near_enabled = p_enable;
+ env->dof_blur_near_distance = p_distance;
+ env->dof_blur_near_transition = p_transition;
+ env->dof_blur_near_amount = p_amount;
+ env->dof_blur_near_quality = p_quality;
}
void RasterizerSceneGLES3::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->glow_enabled=p_enable;
- env->glow_levels=p_level_flags;
- env->glow_intensity=p_intensity;
- env->glow_strength=p_strength;
- env->glow_bloom=p_bloom_treshold;
- env->glow_blend_mode=p_blend_mode;
- env->glow_hdr_bleed_treshold=p_hdr_bleed_treshold;
- env->glow_hdr_bleed_scale=p_hdr_bleed_scale;
- env->glow_bicubic_upscale=p_bicubic_upscale;
-
+ env->glow_enabled = p_enable;
+ env->glow_levels = p_level_flags;
+ env->glow_intensity = p_intensity;
+ env->glow_strength = p_strength;
+ env->glow_bloom = p_bloom_treshold;
+ env->glow_blend_mode = p_blend_mode;
+ env->glow_hdr_bleed_treshold = p_hdr_bleed_treshold;
+ env->glow_hdr_bleed_scale = p_hdr_bleed_scale;
+ env->glow_bicubic_upscale = p_bicubic_upscale;
}
-void RasterizerSceneGLES3::environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture){
-
+void RasterizerSceneGLES3::environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) {
}
-void RasterizerSceneGLES3::environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness) {
+void RasterizerSceneGLES3::environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->ssr_enabled=p_enable;
- env->ssr_max_steps=p_max_steps;
- env->ssr_accel=p_accel;
- env->ssr_fade=p_fade;
- env->ssr_depth_tolerance=p_depth_tolerance;
- env->ssr_smooth=p_smooth;
- env->ssr_roughness=p_roughness;
-
+ env->ssr_enabled = p_enable;
+ env->ssr_max_steps = p_max_steps;
+ env->ssr_accel = p_accel;
+ env->ssr_fade = p_fade;
+ env->ssr_depth_tolerance = p_depth_tolerance;
+ env->ssr_smooth = p_smooth;
+ env->ssr_roughness = p_roughness;
}
+void RasterizerSceneGLES3::environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, const Color &p_color, bool p_blur) {
-void RasterizerSceneGLES3::environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur) {
-
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
- env->ssao_enabled=p_enable;
- env->ssao_radius=p_radius;
- env->ssao_intensity=p_intensity;
- env->ssao_radius2=p_radius2;
- env->ssao_intensity2=p_intensity2;
- env->ssao_bias=p_bias;
- env->ssao_light_affect=p_light_affect;
- env->ssao_color=p_color;
- env->ssao_filter=p_blur;
-
+ env->ssao_enabled = p_enable;
+ env->ssao_radius = p_radius;
+ env->ssao_intensity = p_intensity;
+ env->ssao_radius2 = p_radius2;
+ env->ssao_intensity2 = p_intensity2;
+ env->ssao_bias = p_bias;
+ env->ssao_light_affect = p_light_affect;
+ env->ssao_color = p_color;
+ env->ssao_filter = p_blur;
}
-void RasterizerSceneGLES3::environment_set_tonemap(RID p_env,VS::EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_scale) {
+void RasterizerSceneGLES3::environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) {
- Environment *env=environment_owner.getornull(p_env);
+ Environment *env = environment_owner.getornull(p_env);
ERR_FAIL_COND(!env);
-
- env->tone_mapper=p_tone_mapper;
- env->tone_mapper_exposure=p_exposure;
- env->tone_mapper_exposure_white=p_white;
- env->auto_exposure=p_auto_exposure;
- env->auto_exposure_speed=p_auto_exp_speed;
- env->auto_exposure_min=p_min_luminance;
- env->auto_exposure_max=p_max_luminance;
- env->auto_exposure_grey=p_auto_exp_scale;
-
+ env->tone_mapper = p_tone_mapper;
+ env->tone_mapper_exposure = p_exposure;
+ env->tone_mapper_exposure_white = p_white;
+ env->auto_exposure = p_auto_exposure;
+ env->auto_exposure_speed = p_auto_exp_speed;
+ env->auto_exposure_min = p_min_luminance;
+ env->auto_exposure_max = p_max_luminance;
+ env->auto_exposure_grey = p_auto_exp_scale;
}
-
-void RasterizerSceneGLES3::environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp) {
-
-
+void RasterizerSceneGLES3::environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) {
}
-
RID RasterizerSceneGLES3::light_instance_create(RID p_light) {
+ LightInstance *light_instance = memnew(LightInstance);
- LightInstance *light_instance = memnew( LightInstance );
-
- light_instance->last_pass=0;
- light_instance->last_scene_pass=0;
- light_instance->last_scene_shadow_pass=0;
+ light_instance->last_pass = 0;
+ light_instance->last_scene_pass = 0;
+ light_instance->last_scene_shadow_pass = 0;
- light_instance->light=p_light;
- light_instance->light_ptr=storage->light_owner.getornull(p_light);
+ light_instance->light = p_light;
+ light_instance->light_ptr = storage->light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light_instance->light_ptr,RID());
+ ERR_FAIL_COND_V(!light_instance->light_ptr, RID());
- light_instance->self=light_instance_owner.make_rid(light_instance);
+ light_instance->self = light_instance_owner.make_rid(light_instance);
return light_instance->self;
}
-void RasterizerSceneGLES3::light_instance_set_transform(RID p_light_instance,const Transform& p_transform){
+void RasterizerSceneGLES3::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
- light_instance->transform=p_transform;
+ light_instance->transform = p_transform;
}
-void RasterizerSceneGLES3::light_instance_set_shadow_transform(RID p_light_instance,const CameraMatrix& p_projection,const Transform& p_transform,float p_far,float p_split,int p_pass) {
+void RasterizerSceneGLES3::light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
- if (light_instance->light_ptr->type!=VS::LIGHT_DIRECTIONAL) {
- p_pass=0;
+ if (light_instance->light_ptr->type != VS::LIGHT_DIRECTIONAL) {
+ p_pass = 0;
}
- ERR_FAIL_INDEX(p_pass,4);
-
- light_instance->shadow_transform[p_pass].camera=p_projection;
- light_instance->shadow_transform[p_pass].transform=p_transform;
- light_instance->shadow_transform[p_pass].farplane=p_far;
- light_instance->shadow_transform[p_pass].split=p_split;
+ ERR_FAIL_INDEX(p_pass, 4);
+ light_instance->shadow_transform[p_pass].camera = p_projection;
+ light_instance->shadow_transform[p_pass].transform = p_transform;
+ light_instance->shadow_transform[p_pass].farplane = p_far;
+ light_instance->shadow_transform[p_pass].split = p_split;
}
-
void RasterizerSceneGLES3::light_instance_mark_visible(RID p_light_instance) {
LightInstance *light_instance = light_instance_owner.getornull(p_light_instance);
ERR_FAIL_COND(!light_instance);
- light_instance->last_scene_pass=scene_pass;
+ light_instance->last_scene_pass = scene_pass;
}
-
//////////////////////
RID RasterizerSceneGLES3::gi_probe_instance_create() {
@@ -1069,66 +999,63 @@ void RasterizerSceneGLES3::gi_probe_instance_set_light_data(RID p_probe, RID p_b
GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND(!gipi);
- gipi->data=p_data;
- gipi->probe=storage->gi_probe_owner.getornull(p_base);
+ gipi->data = p_data;
+ gipi->probe = storage->gi_probe_owner.getornull(p_base);
if (p_data.is_valid()) {
RasterizerStorageGLES3::GIProbeData *gipd = storage->gi_probe_data_owner.getornull(p_data);
ERR_FAIL_COND(!gipd);
if (gipd) {
- gipi->tex_cache=gipd->tex_id;
- gipi->cell_size_cache.x=1.0/gipd->width;
- gipi->cell_size_cache.y=1.0/gipd->height;
- gipi->cell_size_cache.z=1.0/gipd->depth;
+ gipi->tex_cache = gipd->tex_id;
+ gipi->cell_size_cache.x = 1.0 / gipd->width;
+ gipi->cell_size_cache.y = 1.0 / gipd->height;
+ gipi->cell_size_cache.z = 1.0 / gipd->depth;
}
}
}
-void RasterizerSceneGLES3::gi_probe_instance_set_transform_to_data(RID p_probe,const Transform& p_xform) {
+void RasterizerSceneGLES3::gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) {
GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND(!gipi);
- gipi->transform_to_data=p_xform;
-
+ gipi->transform_to_data = p_xform;
}
-void RasterizerSceneGLES3::gi_probe_instance_set_bounds(RID p_probe,const Vector3& p_bounds) {
+void RasterizerSceneGLES3::gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) {
GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe);
ERR_FAIL_COND(!gipi);
- gipi->bounds=p_bounds;
-
+ gipi->bounds = p_bounds;
}
////////////////////////////
////////////////////////////
////////////////////////////
-bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_material,bool p_alpha_pass) {
+bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material *p_material, bool p_alpha_pass) {
- if (p_material->shader->spatial.cull_mode==RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) {
+ if (p_material->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) {
glDisable(GL_CULL_FACE);
} else {
glEnable(GL_CULL_FACE);
}
- if (state.current_line_width!=p_material->line_width) {
+ if (state.current_line_width != p_material->line_width) {
//glLineWidth(MAX(p_material->line_width,1.0));
- state.current_line_width=p_material->line_width;
+ state.current_line_width = p_material->line_width;
}
- if (state.current_depth_test!=(!p_material->shader->spatial.ontop)) {
+ if (state.current_depth_test != (!p_material->shader->spatial.ontop)) {
if (p_material->shader->spatial.ontop) {
glDisable(GL_DEPTH_TEST);
} else {
glEnable(GL_DEPTH_TEST);
-
}
- state.current_depth_test=!p_material->shader->spatial.ontop;
+ state.current_depth_test = !p_material->shader->spatial.ontop;
}
- if (state.current_depth_draw!=p_material->shader->spatial.depth_draw_mode) {
- switch(p_material->shader->spatial.depth_draw_mode) {
+ if (state.current_depth_draw != p_material->shader->spatial.depth_draw_mode) {
+ switch (p_material->shader->spatial.depth_draw_mode) {
case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS:
case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE: {
@@ -1142,12 +1069,12 @@ bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_m
} break;
}
- state.current_depth_draw=p_material->shader->spatial.depth_draw_mode;
+ state.current_depth_draw = p_material->shader->spatial.depth_draw_mode;
}
- //glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
+//glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
- /*
+/*
if (p_material->flags[VS::MATERIAL_FLAG_WIREFRAME])
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
else
@@ -1200,54 +1127,49 @@ bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_m
#endif
//material parameters
-
state.scene_shader.set_custom_shader(p_material->shader->custom_code_id);
bool rebind = state.scene_shader.bind();
-
if (p_material->ubo_id) {
- glBindBufferBase(GL_UNIFORM_BUFFER,1,p_material->ubo_id);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 1, p_material->ubo_id);
}
-
-
int tc = p_material->textures.size();
- RID* textures = p_material->textures.ptr();
- ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = p_material->shader->texture_hints.ptr();
+ RID *textures = p_material->textures.ptr();
+ ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = p_material->shader->texture_hints.ptr();
- state.current_main_tex=0;
+ state.current_main_tex = 0;
- for(int i=0;i<tc;i++) {
+ for (int i = 0; i < tc; i++) {
- glActiveTexture(GL_TEXTURE0+i);
+ glActiveTexture(GL_TEXTURE0 + i);
GLenum target;
GLuint tex;
- RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull( textures[i] );
+ RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull(textures[i]);
if (!t) {
//check hints
- target=GL_TEXTURE_2D;
+ target = GL_TEXTURE_2D;
- switch(texture_hints[i]) {
+ switch (texture_hints[i]) {
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
- tex=storage->resources.black_tex;
+ tex = storage->resources.black_tex;
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: {
- tex=storage->resources.aniso_tex;
+ tex = storage->resources.aniso_tex;
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
- tex=storage->resources.normal_tex;
+ tex = storage->resources.normal_tex;
} break;
default: {
- tex=storage->resources.white_tex;
+ tex = storage->resources.white_tex;
} break;
}
-
} else {
#ifdef TOOLS_ENABLED
@@ -1257,15 +1179,15 @@ bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_m
#endif
if (storage->config.srgb_decode_supported) {
//if SRGB decode extension is present, simply switch the texture to whathever is needed
- bool must_srgb=false;
+ bool must_srgb = false;
- if (t->srgb && (texture_hints[i]==ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || texture_hints[i]==ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO)) {
- must_srgb=true;
+ if (t->srgb && (texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || texture_hints[i] == ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO)) {
+ must_srgb = true;
}
- if (t->using_srgb!=must_srgb) {
+ if (t->using_srgb != must_srgb) {
if (must_srgb) {
- glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
+ glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
#ifdef TOOLS_ENABLED
if (t->detect_srgb) {
t->detect_srgb(t->detect_srgb_ud);
@@ -1273,41 +1195,37 @@ bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_m
#endif
} else {
- glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT);
+ glTexParameteri(t->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
}
- t->using_srgb=must_srgb;
+ t->using_srgb = must_srgb;
}
}
- target=t->target;
+ target = t->target;
tex = t->tex_id;
-
}
- glBindTexture(target,tex);
+ glBindTexture(target, tex);
- if (i==0) {
- state.current_main_tex=tex;
+ if (i == 0) {
+ state.current_main_tex = tex;
}
}
-
return rebind;
-
}
-
void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e) {
- switch(e->instance->base_type) {
+ switch (e->instance->base_type) {
case VS::INSTANCE_MESH: {
- RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry);
+ RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
if (s->blend_shapes.size() && e->instance->blend_values.size()) {
//blend shapes, use transform feedback
- storage->mesh_render_blend_shapes(s,e->instance->blend_values.ptr());
+ storage->mesh_render_blend_shapes(s, e->instance->blend_values.ptr());
//rebind shader
state.scene_shader.bind();
} else {
@@ -1319,57 +1237,56 @@ void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e) {
case VS::INSTANCE_MULTIMESH: {
- RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh*>(e->owner);
- RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry);
+ RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner);
+ RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
glBindVertexArray(s->instancing_array_id); // use the instancing array ID
- glBindBuffer(GL_ARRAY_BUFFER,multi_mesh->buffer); //modify the buffer
+ glBindBuffer(GL_ARRAY_BUFFER, multi_mesh->buffer); //modify the buffer
- int stride = (multi_mesh->xform_floats+multi_mesh->color_floats)*4;
+ int stride = (multi_mesh->xform_floats + multi_mesh->color_floats) * 4;
glEnableVertexAttribArray(8);
- glVertexAttribPointer(8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+0);
- glVertexAttribDivisor(8,1);
+ glVertexAttribPointer(8, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + 0);
+ glVertexAttribDivisor(8, 1);
glEnableVertexAttribArray(9);
- glVertexAttribPointer(9,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+4*4);
- glVertexAttribDivisor(9,1);
+ glVertexAttribPointer(9, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + 4 * 4);
+ glVertexAttribDivisor(9, 1);
int color_ofs;
- if (multi_mesh->transform_format==VS::MULTIMESH_TRANSFORM_3D) {
+ if (multi_mesh->transform_format == VS::MULTIMESH_TRANSFORM_3D) {
glEnableVertexAttribArray(10);
- glVertexAttribPointer(10,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+8*4);
- glVertexAttribDivisor(10,1);
- color_ofs=12*4;
+ glVertexAttribPointer(10, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + 8 * 4);
+ glVertexAttribDivisor(10, 1);
+ color_ofs = 12 * 4;
} else {
glDisableVertexAttribArray(10);
- glVertexAttrib4f(10,0,0,1,0);
- color_ofs=8*4;
+ glVertexAttrib4f(10, 0, 0, 1, 0);
+ color_ofs = 8 * 4;
}
- switch(multi_mesh->color_format) {
+ switch (multi_mesh->color_format) {
case VS::MULTIMESH_COLOR_NONE: {
glDisableVertexAttribArray(11);
- glVertexAttrib4f(11,1,1,1,1);
+ glVertexAttrib4f(11, 1, 1, 1, 1);
} break;
case VS::MULTIMESH_COLOR_8BIT: {
glEnableVertexAttribArray(11);
- glVertexAttribPointer(11,4,GL_UNSIGNED_BYTE,GL_TRUE,stride,((uint8_t*)NULL)+color_ofs);
- glVertexAttribDivisor(11,1);
+ glVertexAttribPointer(11, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, ((uint8_t *)NULL) + color_ofs);
+ glVertexAttribDivisor(11, 1);
} break;
case VS::MULTIMESH_COLOR_FLOAT: {
glEnableVertexAttribArray(11);
- glVertexAttribPointer(11,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+color_ofs);
- glVertexAttribDivisor(11,1);
+ glVertexAttribPointer(11, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)NULL) + color_ofs);
+ glVertexAttribDivisor(11, 1);
} break;
}
} break;
}
-
}
-static const GLenum gl_primitive[]={
+static const GLenum gl_primitive[] = {
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
@@ -1379,63 +1296,53 @@ static const GLenum gl_primitive[]={
GL_TRIANGLE_FAN
};
-
-
void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
- switch(e->instance->base_type) {
+ switch (e->instance->base_type) {
case VS::INSTANCE_MESH: {
- RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry);
-
- if (s->index_array_len>0) {
+ RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
+ if (s->index_array_len > 0) {
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>=(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0);
- storage->info.render_vertices_count+=s->index_array_len;
+ storage->info.render_vertices_count += s->index_array_len;
} else {
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
-
- storage->info.render_vertices_count+=s->array_len;
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
+ storage->info.render_vertices_count += s->array_len;
}
-
-
-
} break;
case VS::INSTANCE_MULTIMESH: {
- RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh*>(e->owner);
- RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry);
-
- int amount = MAX(multi_mesh->size,multi_mesh->visible_instances);
-
+ RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh *>(e->owner);
+ RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface *>(e->geometry);
+ int amount = MAX(multi_mesh->size, multi_mesh->visible_instances);
- if (s->index_array_len>0) {
+ if (s->index_array_len > 0) {
- glDrawElementsInstanced(gl_primitive[s->primitive],s->index_array_len, (s->array_len>=(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0,amount);
+ glDrawElementsInstanced(gl_primitive[s->primitive], s->index_array_len, (s->array_len >= (1 << 16)) ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT, 0, amount);
- storage->info.render_vertices_count+=s->index_array_len * amount;
+ storage->info.render_vertices_count += s->index_array_len * amount;
} else {
- glDrawArraysInstanced(gl_primitive[s->primitive],0,s->array_len,amount);
-
- storage->info.render_vertices_count+=s->array_len * amount;
+ glDrawArraysInstanced(gl_primitive[s->primitive], 0, s->array_len, amount);
+ storage->info.render_vertices_count += s->array_len * amount;
}
} break;
case VS::INSTANCE_IMMEDIATE: {
- bool restore_tex=false;
- const RasterizerStorageGLES3::Immediate *im = static_cast<const RasterizerStorageGLES3::Immediate*>( e->geometry );
+ bool restore_tex = false;
+ const RasterizerStorageGLES3::Immediate *im = static_cast<const RasterizerStorageGLES3::Immediate *>(e->geometry);
if (im->building) {
return;
@@ -1444,42 +1351,38 @@ void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer);
glBindVertexArray(state.immediate_array);
+ for (const List<RasterizerStorageGLES3::Immediate::Chunk>::Element *E = im->chunks.front(); E; E = E->next()) {
- for(const List< RasterizerStorageGLES3::Immediate::Chunk>::Element *E=im->chunks.front();E;E=E->next()) {
-
- const RasterizerStorageGLES3::Immediate::Chunk &c=E->get();
+ const RasterizerStorageGLES3::Immediate::Chunk &c = E->get();
if (c.vertices.empty()) {
continue;
}
int vertices = c.vertices.size();
- uint32_t buf_ofs=0;
+ uint32_t buf_ofs = 0;
- storage->info.render_vertices_count+=vertices;
+ storage->info.render_vertices_count += vertices;
if (c.texture.is_valid() && storage->texture_owner.owns(c.texture)) {
const RasterizerStorageGLES3::Texture *t = storage->texture_owner.get(c.texture);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(t->target,t->tex_id);
- restore_tex=true;
-
+ glBindTexture(t->target, t->tex_id);
+ restore_tex = true;
} else if (restore_tex) {
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,state.current_main_tex);
- restore_tex=false;
+ glBindTexture(GL_TEXTURE_2D, state.current_main_tex);
+ restore_tex = false;
}
-
-
if (!c.normals.empty()) {
glEnableVertexAttribArray(VS::ARRAY_NORMAL);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*vertices,c.normals.ptr());
- glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false,sizeof(Vector3)*vertices,((uint8_t*)NULL)+buf_ofs);
- buf_ofs+=sizeof(Vector3)*vertices;
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vector3) * vertices, c.normals.ptr());
+ glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false, sizeof(Vector3) * vertices, ((uint8_t *)NULL) + buf_ofs);
+ buf_ofs += sizeof(Vector3) * vertices;
} else {
@@ -1489,9 +1392,9 @@ void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
if (!c.tangents.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TANGENT);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Plane)*vertices,c.tangents.ptr());
- glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false,sizeof(Plane)*vertices,((uint8_t*)NULL)+buf_ofs);
- buf_ofs+=sizeof(Plane)*vertices;
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Plane) * vertices, c.tangents.ptr());
+ glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false, sizeof(Plane) * vertices, ((uint8_t *)NULL) + buf_ofs);
+ buf_ofs += sizeof(Plane) * vertices;
} else {
@@ -1501,23 +1404,22 @@ void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
if (!c.colors.empty()) {
glEnableVertexAttribArray(VS::ARRAY_COLOR);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Color)*vertices,c.colors.ptr());
- glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false,sizeof(Color),((uint8_t*)NULL)+buf_ofs);
- buf_ofs+=sizeof(Color)*vertices;
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Color) * vertices, c.colors.ptr());
+ glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false, sizeof(Color), ((uint8_t *)NULL) + buf_ofs);
+ buf_ofs += sizeof(Color) * vertices;
} else {
glDisableVertexAttribArray(VS::ARRAY_COLOR);
- glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1);
+ glVertexAttrib4f(VS::ARRAY_COLOR, 1, 1, 1, 1);
}
-
if (!c.uvs.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector2)*vertices,c.uvs.ptr());
- glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false,sizeof(Vector2),((uint8_t*)NULL)+buf_ofs);
- buf_ofs+=sizeof(Vector2)*vertices;
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vector2) * vertices, c.uvs.ptr());
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false, sizeof(Vector2), ((uint8_t *)NULL) + buf_ofs);
+ buf_ofs += sizeof(Vector2) * vertices;
} else {
@@ -1527,161 +1429,151 @@ void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) {
if (!c.uvs2.empty()) {
glEnableVertexAttribArray(VS::ARRAY_TEX_UV2);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector2)*vertices,c.uvs2.ptr());
- glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false,sizeof(Vector2),((uint8_t*)NULL)+buf_ofs);
- buf_ofs+=sizeof(Vector2)*vertices;
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vector2) * vertices, c.uvs2.ptr());
+ glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false, sizeof(Vector2), ((uint8_t *)NULL) + buf_ofs);
+ buf_ofs += sizeof(Vector2) * vertices;
} else {
glDisableVertexAttribArray(VS::ARRAY_TEX_UV2);
}
-
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*vertices,c.vertices.ptr());
- glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false,sizeof(Vector3),((uint8_t*)NULL)+buf_ofs);
- glDrawArrays(gl_primitive[c.primitive],0,c.vertices.size());
-
-
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vector3) * vertices, c.vertices.ptr());
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, sizeof(Vector3), ((uint8_t *)NULL) + buf_ofs);
+ glDrawArrays(gl_primitive[c.primitive], 0, c.vertices.size());
}
-
if (restore_tex) {
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,state.current_main_tex);
- restore_tex=false;
+ glBindTexture(GL_TEXTURE_2D, state.current_main_tex);
+ restore_tex = false;
}
} break;
-
}
-
}
-void RasterizerSceneGLES3::_setup_light(RenderList::Element *e,const Transform& p_view_transform) {
+void RasterizerSceneGLES3::_setup_light(RenderList::Element *e, const Transform &p_view_transform) {
int omni_indices[16];
- int omni_count=0;
+ int omni_count = 0;
int spot_indices[16];
- int spot_count=0;
+ int spot_count = 0;
int reflection_indices[16];
- int reflection_count=0;
+ int reflection_count = 0;
- int maxobj = MIN(16,state.max_forward_lights_per_object);
+ int maxobj = MIN(16, state.max_forward_lights_per_object);
- int lc = e->instance->light_instances.size();
+ int lc = e->instance->light_instances.size();
if (lc) {
- const RID* lights=e->instance->light_instances.ptr();
+ const RID *lights = e->instance->light_instances.ptr();
- for(int i=0;i<lc;i++) {
- LightInstance *li=light_instance_owner.getptr(lights[i]);
- if (li->last_pass!=render_pass) //not visible
+ for (int i = 0; i < lc; i++) {
+ LightInstance *li = light_instance_owner.getptr(lights[i]);
+ if (li->last_pass != render_pass) //not visible
continue;
- if (li->light_ptr->type==VS::LIGHT_OMNI) {
- if (omni_count<maxobj && e->instance->layer_mask&li->light_ptr->cull_mask) {
- omni_indices[omni_count++]=li->light_index;
+ if (li->light_ptr->type == VS::LIGHT_OMNI) {
+ if (omni_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) {
+ omni_indices[omni_count++] = li->light_index;
}
}
- if (li->light_ptr->type==VS::LIGHT_SPOT) {
- if (spot_count<maxobj && e->instance->layer_mask&li->light_ptr->cull_mask) {
- spot_indices[spot_count++]=li->light_index;
+ if (li->light_ptr->type == VS::LIGHT_SPOT) {
+ if (spot_count < maxobj && e->instance->layer_mask & li->light_ptr->cull_mask) {
+ spot_indices[spot_count++] = li->light_index;
}
}
}
}
- state.scene_shader.set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT,omni_count);
+ state.scene_shader.set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT, omni_count);
if (omni_count) {
- glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES),omni_count,omni_indices);
+ glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES), omni_count, omni_indices);
}
- state.scene_shader.set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT,spot_count);
+ state.scene_shader.set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT, spot_count);
if (spot_count) {
- glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES),spot_count,spot_indices);
+ glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES), spot_count, spot_indices);
}
-
int rc = e->instance->reflection_probe_instances.size();
-
if (rc) {
+ const RID *reflections = e->instance->reflection_probe_instances.ptr();
- const RID* reflections=e->instance->reflection_probe_instances.ptr();
-
- for(int i=0;i<rc;i++) {
- ReflectionProbeInstance *rpi=reflection_probe_instance_owner.getptr(reflections[i]);
- if (rpi->last_pass!=render_pass) //not visible
+ for (int i = 0; i < rc; i++) {
+ ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getptr(reflections[i]);
+ if (rpi->last_pass != render_pass) //not visible
continue;
- if (reflection_count<maxobj) {
- reflection_indices[reflection_count++]=rpi->reflection_index;
+ if (reflection_count < maxobj) {
+ reflection_indices[reflection_count++] = rpi->reflection_index;
}
}
}
- state.scene_shader.set_uniform(SceneShaderGLES3::REFLECTION_COUNT,reflection_count);
+ state.scene_shader.set_uniform(SceneShaderGLES3::REFLECTION_COUNT, reflection_count);
if (reflection_count) {
- glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::REFLECTION_INDICES),reflection_count,reflection_indices);
+ glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::REFLECTION_INDICES), reflection_count, reflection_indices);
}
int gi_probe_count = e->instance->gi_probe_instances.size();
if (gi_probe_count) {
- const RID * ridp = e->instance->gi_probe_instances.ptr();
+ const RID *ridp = e->instance->gi_probe_instances.ptr();
GIProbeInstance *gipi = gi_probe_instance_owner.getptr(ridp[0]);
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-6);
- glBindTexture(GL_TEXTURE_3D,gipi->tex_cache);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 6);
+ glBindTexture(GL_TEXTURE_3D, gipi->tex_cache);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM1, gipi->transform_to_data * p_view_transform);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS1, gipi->bounds);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER1, gipi->probe?gipi->probe->dynamic_range*gipi->probe->energy:0.0);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS1, gipi->probe?gipi->probe->bias:0.0);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT1, gipi->probe?!gipi->probe->interior:false);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER1, gipi->probe ? gipi->probe->dynamic_range * gipi->probe->energy : 0.0);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS1, gipi->probe ? gipi->probe->bias : 0.0);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT1, gipi->probe ? !gipi->probe->interior : false);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE1, gipi->cell_size_cache);
- if (gi_probe_count>1) {
+ if (gi_probe_count > 1) {
GIProbeInstance *gipi2 = gi_probe_instance_owner.getptr(ridp[1]);
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-7);
- glBindTexture(GL_TEXTURE_3D,gipi2->tex_cache);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 7);
+ glBindTexture(GL_TEXTURE_3D, gipi2->tex_cache);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM2, gipi2->transform_to_data * p_view_transform);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS2, gipi2->bounds);
state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE2, gipi2->cell_size_cache);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER2, gipi2->probe?gipi2->probe->dynamic_range*gipi2->probe->energy:0.0);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS2, gipi2->probe?gipi2->probe->bias:0.0);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT2, gipi2->probe?!gipi2->probe->interior:false);
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, true );
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER2, gipi2->probe ? gipi2->probe->dynamic_range * gipi2->probe->energy : 0.0);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BIAS2, gipi2->probe ? gipi2->probe->bias : 0.0);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT2, gipi2->probe ? !gipi2->probe->interior : false);
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, true);
} else {
- state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, false );
+ state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, false);
}
}
}
-
-void RasterizerSceneGLES3::_setup_transform(InstanceBase *p_instance,const Transform& p_view_transform,const CameraMatrix& p_projection) {
+void RasterizerSceneGLES3::_setup_transform(InstanceBase *p_instance, const Transform &p_view_transform, const CameraMatrix &p_projection) {
if (p_instance->billboard || p_instance->billboard_y || p_instance->depth_scale) {
- Transform xf=p_instance->transform;
+ Transform xf = p_instance->transform;
if (p_instance->depth_scale) {
if (p_projection.matrix[3][3]) {
//orthogonal matrix, try to do about the same
//with viewport size
//real_t w = Math::abs( 1.0/(2.0*(p_projection.matrix[0][0])) );
- real_t h = Math::abs( 1.0/(2.0*p_projection.matrix[1][1]) );
- float sc = (h*2.0); //consistent with Y-fov
- xf.basis.scale( Vector3(sc,sc,sc));
+ real_t h = Math::abs(1.0 / (2.0 * p_projection.matrix[1][1]));
+ float sc = (h * 2.0); //consistent with Y-fov
+ xf.basis.scale(Vector3(sc, sc, sc));
} else {
//just scale by depth
- real_t sc = Plane(p_view_transform.origin,-p_view_transform.get_basis().get_axis(2)).distance_to(xf.origin);
- xf.basis.scale( Vector3(sc,sc,sc));
+ real_t sc = Plane(p_view_transform.origin, -p_view_transform.get_basis().get_axis(2)).distance_to(xf.origin);
+ xf.basis.scale(Vector3(sc, sc, sc));
}
}
@@ -1701,14 +1593,14 @@ void RasterizerSceneGLES3::_setup_transform(InstanceBase *p_instance,const Trans
if (p_instance->billboard_y && storage->frame.current_rt) {
Vector3 scale = xf.basis.get_scale();
- Vector3 look_at = p_view_transform.get_origin();
+ Vector3 look_at = p_view_transform.get_origin();
look_at.y = 0.0;
Vector3 look_at_norm = look_at.normalized();
if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) {
- xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, -1.0, 0.0));
+ xf.set_look_at(xf.origin, xf.origin + look_at_norm, Vector3(0.0, -1.0, 0.0));
} else {
- xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, 1.0, 0.0));
+ xf.set_look_at(xf.origin, xf.origin + look_at_norm, Vector3(0.0, 1.0, 0.0));
}
xf.basis.scale(scale);
}
@@ -1719,22 +1611,20 @@ void RasterizerSceneGLES3::_setup_transform(InstanceBase *p_instance,const Trans
}
}
-void RasterizerSceneGLES3::_set_cull(bool p_front,bool p_reverse_cull) {
+void RasterizerSceneGLES3::_set_cull(bool p_front, bool p_reverse_cull) {
bool front = p_front;
if (p_reverse_cull)
- front=!front;
+ front = !front;
- if (front!=state.cull_front) {
+ if (front != state.cull_front) {
- glCullFace(front?GL_FRONT:GL_BACK);
- state.cull_front=front;
+ glCullFace(front ? GL_FRONT : GL_BACK);
+ state.cull_front = front;
}
}
-
-
-void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements,int p_element_count,const Transform& p_view_transform,const CameraMatrix& p_projection,GLuint p_base_env,bool p_reverse_cull,bool p_alpha_pass,bool p_shadow,bool p_directional_add,bool p_directional_shadows) {
+void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements, int p_element_count, const Transform &p_view_transform, const CameraMatrix &p_projection, GLuint p_base_env, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow, bool p_directional_add, bool p_directional_shadows) {
if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) {
//p_reverse_cull=!p_reverse_cull;
@@ -1743,287 +1633,257 @@ void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements,int p_e
glFrontFace(GL_CW);
}
- glBindBufferBase(GL_UNIFORM_BUFFER,0,state.scene_ubo); //bind globals ubo
-
+ glBindBufferBase(GL_UNIFORM_BUFFER, 0, state.scene_ubo); //bind globals ubo
if (!p_shadow && !p_directional_add) {
- glBindBufferBase(GL_UNIFORM_BUFFER,2,state.env_radiance_ubo); //bind environment radiance info
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-1);
- glBindTexture(GL_TEXTURE_2D,state.brdf_texture);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 2, state.env_radiance_ubo); //bind environment radiance info
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 1);
+ glBindTexture(GL_TEXTURE_2D, state.brdf_texture);
if (p_base_env) {
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-2);
- glBindTexture(GL_TEXTURE_2D,p_base_env);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,true);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 2);
+ glBindTexture(GL_TEXTURE_2D, p_base_env);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, true);
} else {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false);
-
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
}
} else {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
}
-
- state.cull_front=false;
+ state.cull_front = false;
glCullFace(GL_BACK);
- state.current_depth_test=true;
+ state.current_depth_test = true;
glEnable(GL_DEPTH_TEST);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false);
- state.current_blend_mode=-1;
- state.current_line_width=-1;
- state.current_depth_draw=-1;
+ state.current_blend_mode = -1;
+ state.current_line_width = -1;
+ state.current_depth_draw = -1;
- RasterizerStorageGLES3::Material* prev_material=NULL;
- RasterizerStorageGLES3::Geometry* prev_geometry=NULL;
- RasterizerStorageGLES3::GeometryOwner* prev_owner=NULL;
+ RasterizerStorageGLES3::Material *prev_material = NULL;
+ RasterizerStorageGLES3::Geometry *prev_geometry = NULL;
+ RasterizerStorageGLES3::GeometryOwner *prev_owner = NULL;
VS::InstanceType prev_base_type = VS::INSTANCE_MAX;
- int current_blend_mode=-1;
+ int current_blend_mode = -1;
- int prev_shading=-1;
+ int prev_shading = -1;
RID prev_skeleton;
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true); //by default unshaded (easier to set)
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true); //by default unshaded (easier to set)
- bool first=true;
+ bool first = true;
- storage->info.render_object_count+=p_element_count;
+ storage->info.render_object_count += p_element_count;
- for (int i=0;i<p_element_count;i++) {
+ for (int i = 0; i < p_element_count; i++) {
RenderList::Element *e = p_elements[i];
- RasterizerStorageGLES3::Material* material= e->material;
+ RasterizerStorageGLES3::Material *material = e->material;
RID skeleton = e->instance->skeleton;
+ bool rebind = first;
- bool rebind=first;
-
- int shading = (e->sort_key>>RenderList::SORT_KEY_SHADING_SHIFT)&RenderList::SORT_KEY_SHADING_MASK;
+ int shading = (e->sort_key >> RenderList::SORT_KEY_SHADING_SHIFT) & RenderList::SORT_KEY_SHADING_MASK;
if (!p_shadow) {
-
-
if (p_directional_add) {
- if (e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG || !(e->instance->layer_mask&directional_light->light_ptr->cull_mask)) {
+ if (e->sort_key & RenderList::SORT_KEY_UNSHADED_FLAG || !(e->instance->layer_mask & directional_light->light_ptr->cull_mask)) {
continue;
}
- shading&=~1; //ignore the ignore directional for base pass
+ shading &= ~1; //ignore the ignore directional for base pass
}
- if (shading!=prev_shading) {
-
- if (e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG) {
-
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,false);
+ if (shading != prev_shading) {
+ if (e->sort_key & RenderList::SORT_KEY_UNSHADED_FLAG) {
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, true);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false);
//state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true);
} else {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,e->instance->gi_probe_instances.size()>0);
-
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,!p_directional_add);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,shadow_filter_mode==SHADOW_FILTER_PCF5);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,shadow_filter_mode==SHADOW_FILTER_PCF13);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, e->instance->gi_probe_instances.size() > 0);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, !p_directional_add);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, shadow_filter_mode == SHADOW_FILTER_PCF5);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, shadow_filter_mode == SHADOW_FILTER_PCF13);
- if (p_directional_add || (directional_light && (e->sort_key&RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG)==0)) {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,true);
+ if (p_directional_add || (directional_light && (e->sort_key & RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG) == 0)) {
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, true);
if (p_directional_shadows && directional_light->light_ptr->shadow) {
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,true);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, true);
- switch(directional_light->light_ptr->directional_shadow_mode) {
- case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none
+ switch (directional_light->light_ptr->directional_shadow_mode) {
+ case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL:
+ break; //none
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS:
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,true);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,directional_light->light_ptr->directional_blend_splits);
- break;
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, true);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits);
+ break;
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS:
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,true);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,directional_light->light_ptr->directional_blend_splits);
- break;
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, true);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, directional_light->light_ptr->directional_blend_splits);
+ break;
}
}
-
}
-
}
-
-
- rebind=true;
+ rebind = true;
}
-
if (p_alpha_pass || p_directional_add) {
int desired_blend_mode;
if (p_directional_add) {
- desired_blend_mode=RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD;
+ desired_blend_mode = RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD;
} else {
- desired_blend_mode=material->shader->spatial.blend_mode;
+ desired_blend_mode = material->shader->spatial.blend_mode;
}
- if (desired_blend_mode!=current_blend_mode) {
-
+ if (desired_blend_mode != current_blend_mode) {
- switch(desired_blend_mode) {
+ switch (desired_blend_mode) {
- case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: {
+ case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: {
glBlendEquation(GL_FUNC_ADD);
if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
- } break;
- case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: {
+ } break;
+ case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: {
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(p_alpha_pass?GL_SRC_ALPHA:GL_ONE,GL_ONE);
+ glBlendFunc(p_alpha_pass ? GL_SRC_ALPHA : GL_ONE, GL_ONE);
- } break;
- case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: {
+ } break;
+ case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: {
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
- glBlendFunc(GL_SRC_ALPHA,GL_ONE);
- } break;
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+ } break;
case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: {
glBlendEquation(GL_FUNC_ADD);
if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) {
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
- }
- else {
+ } else {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
} break;
-
}
- current_blend_mode=desired_blend_mode;
+ current_blend_mode = desired_blend_mode;
}
-
}
-
-
}
- if (prev_skeleton!=skeleton) {
+ if (prev_skeleton != skeleton) {
if (prev_skeleton.is_valid() != skeleton.is_valid()) {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,skeleton.is_valid());
- rebind=true;
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, skeleton.is_valid());
+ rebind = true;
}
if (skeleton.is_valid()) {
RasterizerStorageGLES3::Skeleton *sk = storage->skeleton_owner.getornull(skeleton);
if (sk->size) {
- glBindBufferBase(GL_UNIFORM_BUFFER,7,sk->ubo);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 7, sk->ubo);
}
}
}
- if ((prev_base_type==VS::INSTANCE_MULTIMESH) != (e->instance->base_type==VS::INSTANCE_MULTIMESH)) {
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING,e->instance->base_type==VS::INSTANCE_MULTIMESH);
- rebind=true;
+ if ((prev_base_type == VS::INSTANCE_MULTIMESH) != (e->instance->base_type == VS::INSTANCE_MULTIMESH)) {
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, e->instance->base_type == VS::INSTANCE_MULTIMESH);
+ rebind = true;
}
- if (material!=prev_material || rebind) {
+ if (material != prev_material || rebind) {
storage->info.render_material_switch_count++;
- rebind = _setup_material(material,p_alpha_pass);
+ rebind = _setup_material(material, p_alpha_pass);
if (rebind) {
storage->info.render_shader_rebind_count++;
}
}
- if (!(e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG) && !p_directional_add && !p_shadow) {
- _setup_light(e,p_view_transform);
-
+ if (!(e->sort_key & RenderList::SORT_KEY_UNSHADED_FLAG) && !p_directional_add && !p_shadow) {
+ _setup_light(e, p_view_transform);
}
-
- if (e->owner != prev_owner || prev_base_type != e->instance->base_type || prev_geometry!=e->geometry) {
-
+ if (e->owner != prev_owner || prev_base_type != e->instance->base_type || prev_geometry != e->geometry) {
_setup_geometry(e);
storage->info.render_surface_switch_count++;
-
}
- _set_cull(e->sort_key&RenderList::SORT_KEY_MIRROR_FLAG,p_reverse_cull);
+ _set_cull(e->sort_key & RenderList::SORT_KEY_MIRROR_FLAG, p_reverse_cull);
- state.scene_shader.set_uniform(SceneShaderGLES3::NORMAL_MULT, e->instance->mirror?-1.0:1.0);
+ state.scene_shader.set_uniform(SceneShaderGLES3::NORMAL_MULT, e->instance->mirror ? -1.0 : 1.0);
- _setup_transform(e->instance,p_view_transform,p_projection);
+ _setup_transform(e->instance, p_view_transform, p_projection);
_render_geometry(e);
- prev_material=material;
- prev_base_type=e->instance->base_type;
- prev_geometry=e->geometry;
- prev_owner=e->owner;
- prev_shading=shading;
- prev_skeleton=skeleton;
- first=false;
-
+ prev_material = material;
+ prev_base_type = e->instance->base_type;
+ prev_geometry = e->geometry;
+ prev_owner = e->owner;
+ prev_shading = shading;
+ prev_skeleton = skeleton;
+ first = false;
}
-
-
glFrontFace(GL_CW);
glBindVertexArray(0);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,false);
-
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES, false);
}
+void RasterizerSceneGLES3::_add_geometry(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, int p_material, bool p_shadow) {
-void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner,int p_material,bool p_shadow) {
-
- RasterizerStorageGLES3::Material *m=NULL;
- RID m_src=p_instance->material_override.is_valid() ? p_instance->material_override :(p_material>=0?p_instance->materials[p_material]:p_geometry->material);
-
+ RasterizerStorageGLES3::Material *m = NULL;
+ RID m_src = p_instance->material_override.is_valid() ? p_instance->material_override : (p_material >= 0 ? p_instance->materials[p_material] : p_geometry->material);
-/*
+ /*
#ifdef DEBUG_ENABLED
if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) {
m_src=overdraw_material;
@@ -2033,42 +1893,40 @@ void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_g
*/
if (m_src.is_valid()) {
- m=storage->material_owner.getornull( m_src );
+ m = storage->material_owner.getornull(m_src);
if (!m->shader) {
- m=NULL;
+ m = NULL;
}
}
if (!m) {
- m=storage->material_owner.getptr( default_material );
+ m = storage->material_owner.getptr(default_material);
}
ERR_FAIL_COND(!m);
-
-
- bool has_base_alpha=(m->shader->spatial.uses_alpha);
- bool has_blend_alpha=m->shader->spatial.blend_mode!=RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX || m->shader->spatial.ontop;
+ bool has_base_alpha = (m->shader->spatial.uses_alpha);
+ bool has_blend_alpha = m->shader->spatial.blend_mode != RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX || m->shader->spatial.ontop;
bool has_alpha = has_base_alpha || has_blend_alpha;
bool shadow = false;
bool mirror = p_instance->mirror;
- if (m->shader->spatial.cull_mode==RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_FRONT) {
- mirror=!mirror;
+ if (m->shader->spatial.cull_mode == RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_FRONT) {
+ mirror = !mirror;
}
if (m->shader->spatial.uses_sss) {
- state.used_sss=true;
+ state.used_sss = true;
}
if (p_shadow) {
- if (has_blend_alpha || (has_base_alpha && m->shader->spatial.depth_draw_mode!=RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS))
+ if (has_blend_alpha || (has_base_alpha && m->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS))
return; //bye
- if (!m->shader->spatial.uses_vertex && !m->shader->spatial.uses_discard && m->shader->spatial.depth_draw_mode!=RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
+ if (!m->shader->spatial.uses_vertex && !m->shader->spatial.uses_discard && m->shader->spatial.depth_draw_mode != RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
//shader does not use discard and does not write a vertex position, use generic material
if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED)
m = storage->material_owner.getptr(default_material_twosided);
@@ -2076,47 +1934,43 @@ void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_g
m = storage->material_owner.getptr(default_material);
}
- has_alpha=false;
-
+ has_alpha = false;
}
-
-
RenderList::Element *e = has_alpha ? render_list.add_alpha_element() : render_list.add_element();
if (!e)
return;
- e->geometry=p_geometry;
- e->material=m;
- e->instance=p_instance;
- e->owner=p_owner;
- e->sort_key=0;
+ e->geometry = p_geometry;
+ e->material = m;
+ e->instance = p_instance;
+ e->owner = p_owner;
+ e->sort_key = 0;
- if (e->geometry->last_pass!=render_pass) {
- e->geometry->last_pass=render_pass;
- e->geometry->index=current_geometry_index++;
+ if (e->geometry->last_pass != render_pass) {
+ e->geometry->last_pass = render_pass;
+ e->geometry->index = current_geometry_index++;
}
- if (!p_shadow && directional_light && (directional_light->light_ptr->cull_mask&e->instance->layer_mask)==0) {
- e->sort_key|=RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG;
+ if (!p_shadow && directional_light && (directional_light->light_ptr->cull_mask & e->instance->layer_mask) == 0) {
+ e->sort_key |= RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG;
}
- e->sort_key|=uint64_t(e->geometry->index)<<RenderList::SORT_KEY_GEOMETRY_INDEX_SHIFT;
- e->sort_key|=uint64_t(e->instance->base_type)<<RenderList::SORT_KEY_GEOMETRY_TYPE_SHIFT;
+ e->sort_key |= uint64_t(e->geometry->index) << RenderList::SORT_KEY_GEOMETRY_INDEX_SHIFT;
+ e->sort_key |= uint64_t(e->instance->base_type) << RenderList::SORT_KEY_GEOMETRY_TYPE_SHIFT;
if (!p_shadow) {
-
- if (e->material->last_pass!=render_pass) {
- e->material->last_pass=render_pass;
- e->material->index=current_material_index++;
+ if (e->material->last_pass != render_pass) {
+ e->material->last_pass = render_pass;
+ e->material->index = current_material_index++;
}
- e->sort_key|=uint64_t(e->material->index)<<RenderList::SORT_KEY_MATERIAL_INDEX_SHIFT;
- e->sort_key|=uint64_t(e->instance->depth_layer)<<RenderList::SORT_KEY_DEPTH_LAYER_SHIFT;
+ e->sort_key |= uint64_t(e->material->index) << RenderList::SORT_KEY_MATERIAL_INDEX_SHIFT;
+ e->sort_key |= uint64_t(e->instance->depth_layer) << RenderList::SORT_KEY_DEPTH_LAYER_SHIFT;
- if (!has_blend_alpha && has_alpha && m->shader->spatial.depth_draw_mode==RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
+ if (!has_blend_alpha && has_alpha && m->shader->spatial.depth_draw_mode == RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) {
//if nothing exists, add this element as opaque too
RenderList::Element *oe = render_list.add_element();
@@ -2124,11 +1978,11 @@ void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_g
if (!oe)
return;
- copymem(oe,e,sizeof(RenderList::Element));
+ copymem(oe, e, sizeof(RenderList::Element));
}
if (e->instance->gi_probe_instances.size()) {
- e->sort_key|=RenderList::SORT_KEY_GI_PROBES_FLAG;
+ e->sort_key |= RenderList::SORT_KEY_GI_PROBES_FLAG;
}
}
@@ -2137,20 +1991,19 @@ void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_g
e->sort_flags|=RenderList::SORT_FLAG_INSTANCING;
*/
-
if (mirror) {
- e->sort_key|=RenderList::SORT_KEY_MIRROR_FLAG;
+ e->sort_key |= RenderList::SORT_KEY_MIRROR_FLAG;
}
//e->light_type=0xFF; // no lights!
if (shadow || m->shader->spatial.unshaded /*|| current_debug==VS::SCENARIO_DEBUG_SHADELESS*/) {
- e->sort_key|=RenderList::SORT_KEY_UNSHADED_FLAG;
+ e->sort_key |= RenderList::SORT_KEY_UNSHADED_FLAG;
}
}
-void RasterizerSceneGLES3::_draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox,const CameraMatrix& p_projection,const Transform& p_transform,bool p_vflip,float p_scale) {
+void RasterizerSceneGLES3::_draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox, const CameraMatrix &p_projection, const Transform &p_transform, bool p_vflip, float p_scale) {
if (!p_skybox)
return;
@@ -2159,16 +2012,15 @@ void RasterizerSceneGLES3::_draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox
ERR_FAIL_COND(!tex);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(tex->target,tex->tex_id);
-
+ glBindTexture(tex->target, tex->tex_id);
if (storage->config.srgb_decode_supported && tex->srgb && !tex->using_srgb) {
- glTexParameteri(tex->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
- tex->using_srgb=true;
+ glTexParameteri(tex->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
+ tex->using_srgb = true;
#ifdef TOOLS_ENABLED
- if (!(tex->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
- tex->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
+ if (!(tex->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ tex->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
//notify that texture must be set to linear beforehand, so it works in other platforms when exported
}
#endif
@@ -2179,400 +2031,366 @@ void RasterizerSceneGLES3::_draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);
- glColorMask(1,1,1,1);
+ glColorMask(1, 1, 1, 1);
- float flip_sign = p_vflip?-1:1;
+ float flip_sign = p_vflip ? -1 : 1;
- Vector3 vertices[8]={
- Vector3(-1,-1*flip_sign,1),
- Vector3( 0, 1, 0),
- Vector3( 1,-1*flip_sign,1),
- Vector3( 1, 1, 0),
- Vector3( 1, 1*flip_sign,1),
- Vector3( 1, 0, 0),
- Vector3(-1, 1*flip_sign,1),
- Vector3( 0, 0, 0)
+ Vector3 vertices[8] = {
+ Vector3(-1, -1 * flip_sign, 1),
+ Vector3(0, 1, 0),
+ Vector3(1, -1 * flip_sign, 1),
+ Vector3(1, 1, 0),
+ Vector3(1, 1 * flip_sign, 1),
+ Vector3(1, 0, 0),
+ Vector3(-1, 1 * flip_sign, 1),
+ Vector3(0, 0, 0)
};
-
-
//skybox uv vectors
- float vw,vh,zn;
- p_projection.get_viewport_size(vw,vh);
- zn=p_projection.get_z_near();
+ float vw, vh, zn;
+ p_projection.get_viewport_size(vw, vh);
+ zn = p_projection.get_z_near();
- float scale=p_scale;
+ float scale = p_scale;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- Vector3 uv=vertices[i*2+1];
- uv.x=(uv.x*2.0-1.0)*vw*scale;
- uv.y=-(uv.y*2.0-1.0)*vh*scale;
- uv.z=-zn;
- vertices[i*2+1] = p_transform.basis.xform(uv).normalized();
- vertices[i*2+1].z = -vertices[i*2+1].z;
+ Vector3 uv = vertices[i * 2 + 1];
+ uv.x = (uv.x * 2.0 - 1.0) * vw * scale;
+ uv.y = -(uv.y * 2.0 - 1.0) * vh * scale;
+ uv.z = -zn;
+ vertices[i * 2 + 1] = p_transform.basis.xform(uv).normalized();
+ vertices[i * 2 + 1].z = -vertices[i * 2 + 1].z;
}
- glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts);
- glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*8,vertices);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, state.skybox_verts);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(Vector3) * 8, vertices);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
glBindVertexArray(state.skybox_array);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP,true);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP, true);
storage->shaders.copy.bind();
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindVertexArray(0);
- glColorMask(1,1,1,1);
-
- storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP,false);
+ glColorMask(1, 1, 1, 1);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP, false);
}
-
-void RasterizerSceneGLES3::_setup_environment(Environment *env,const CameraMatrix& p_cam_projection,const Transform& p_cam_transform) {
-
+void RasterizerSceneGLES3::_setup_environment(Environment *env, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform) {
//store camera into ubo
- store_camera(p_cam_projection,state.ubo_data.projection_matrix);
- store_transform(p_cam_transform,state.ubo_data.camera_matrix);
- store_transform(p_cam_transform.affine_inverse(),state.ubo_data.camera_inverse_matrix);
+ store_camera(p_cam_projection, state.ubo_data.projection_matrix);
+ store_transform(p_cam_transform, state.ubo_data.camera_matrix);
+ store_transform(p_cam_transform.affine_inverse(), state.ubo_data.camera_inverse_matrix);
//time global variables
- for(int i=0;i<4;i++) {
- state.ubo_data.time[i]=storage->frame.time[i];
+ for (int i = 0; i < 4; i++) {
+ state.ubo_data.time[i] = storage->frame.time[i];
}
//bg and ambient
if (env) {
- state.ubo_data.bg_energy=env->bg_energy;
- state.ubo_data.ambient_energy=env->ambient_energy;
+ state.ubo_data.bg_energy = env->bg_energy;
+ state.ubo_data.ambient_energy = env->ambient_energy;
Color linear_ambient_color = env->ambient_color.to_linear();
- state.ubo_data.ambient_light_color[0]=linear_ambient_color.r;
- state.ubo_data.ambient_light_color[1]=linear_ambient_color.g;
- state.ubo_data.ambient_light_color[2]=linear_ambient_color.b;
- state.ubo_data.ambient_light_color[3]=linear_ambient_color.a;
+ state.ubo_data.ambient_light_color[0] = linear_ambient_color.r;
+ state.ubo_data.ambient_light_color[1] = linear_ambient_color.g;
+ state.ubo_data.ambient_light_color[2] = linear_ambient_color.b;
+ state.ubo_data.ambient_light_color[3] = linear_ambient_color.a;
Color bg_color;
- switch(env->bg_mode) {
+ switch (env->bg_mode) {
case VS::ENV_BG_CLEAR_COLOR: {
- bg_color=storage->frame.clear_request_color.to_linear();
+ bg_color = storage->frame.clear_request_color.to_linear();
} break;
case VS::ENV_BG_COLOR: {
- bg_color=env->bg_color.to_linear();
+ bg_color = env->bg_color.to_linear();
} break;
default: {
- bg_color=Color(0,0,0,1);
+ bg_color = Color(0, 0, 0, 1);
} break;
}
- state.ubo_data.bg_color[0]=bg_color.r;
- state.ubo_data.bg_color[1]=bg_color.g;
- state.ubo_data.bg_color[2]=bg_color.b;
- state.ubo_data.bg_color[3]=bg_color.a;
+ state.ubo_data.bg_color[0] = bg_color.r;
+ state.ubo_data.bg_color[1] = bg_color.g;
+ state.ubo_data.bg_color[2] = bg_color.b;
+ state.ubo_data.bg_color[3] = bg_color.a;
- state.env_radiance_data.ambient_contribution=env->ambient_skybox_contribution;
- state.ubo_data.ambient_occlusion_affect_light=env->ssao_light_affect;
+ state.env_radiance_data.ambient_contribution = env->ambient_skybox_contribution;
+ state.ubo_data.ambient_occlusion_affect_light = env->ssao_light_affect;
} else {
- state.ubo_data.bg_energy=1.0;
- state.ubo_data.ambient_energy=1.0;
+ state.ubo_data.bg_energy = 1.0;
+ state.ubo_data.ambient_energy = 1.0;
//use from clear color instead, since there is no ambient
Color linear_ambient_color = storage->frame.clear_request_color.to_linear();
- state.ubo_data.ambient_light_color[0]=linear_ambient_color.r;
- state.ubo_data.ambient_light_color[1]=linear_ambient_color.g;
- state.ubo_data.ambient_light_color[2]=linear_ambient_color.b;
- state.ubo_data.ambient_light_color[3]=linear_ambient_color.a;
-
- state.ubo_data.bg_color[0]=linear_ambient_color.r;
- state.ubo_data.bg_color[1]=linear_ambient_color.g;
- state.ubo_data.bg_color[2]=linear_ambient_color.b;
- state.ubo_data.bg_color[3]=linear_ambient_color.a;
-
- state.env_radiance_data.ambient_contribution=0;
- state.ubo_data.ambient_occlusion_affect_light=0;
-
+ state.ubo_data.ambient_light_color[0] = linear_ambient_color.r;
+ state.ubo_data.ambient_light_color[1] = linear_ambient_color.g;
+ state.ubo_data.ambient_light_color[2] = linear_ambient_color.b;
+ state.ubo_data.ambient_light_color[3] = linear_ambient_color.a;
+
+ state.ubo_data.bg_color[0] = linear_ambient_color.r;
+ state.ubo_data.bg_color[1] = linear_ambient_color.g;
+ state.ubo_data.bg_color[2] = linear_ambient_color.b;
+ state.ubo_data.bg_color[3] = linear_ambient_color.a;
+
+ state.env_radiance_data.ambient_contribution = 0;
+ state.ubo_data.ambient_occlusion_affect_light = 0;
}
{
//directional shadow
- state.ubo_data.shadow_directional_pixel_size[0]=1.0/directional_shadow.size;
- state.ubo_data.shadow_directional_pixel_size[1]=1.0/directional_shadow.size;
+ state.ubo_data.shadow_directional_pixel_size[0] = 1.0 / directional_shadow.size;
+ state.ubo_data.shadow_directional_pixel_size[1] = 1.0 / directional_shadow.size;
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-4);
- glBindTexture(GL_TEXTURE_2D,directional_shadow.depth);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 4);
+ glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
}
-
-
glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(State::SceneDataUBO), &state.ubo_data);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(State::SceneDataUBO), &state.ubo_data);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
//fill up environment
- store_transform(p_cam_transform,state.env_radiance_data.transform);
-
+ store_transform(p_cam_transform, state.env_radiance_data.transform);
glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_data);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_data);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
}
-void RasterizerSceneGLES3::_setup_directional_light(int p_index,const Transform& p_camera_inverse_transform,bool p_use_shadows) {
+void RasterizerSceneGLES3::_setup_directional_light(int p_index, const Transform &p_camera_inverse_transform, bool p_use_shadows) {
LightInstance *li = directional_lights[p_index];
LightDataUBO ubo_data; //used for filling
- float sign = li->light_ptr->negative?-1:1;
+ float sign = li->light_ptr->negative ? -1 : 1;
Color linear_col = li->light_ptr->color.to_linear();
- ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[3]=0;
+ ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[3] = 0;
//omni, keep at 0
- ubo_data.light_pos_inv_radius[0]=0.0;
- ubo_data.light_pos_inv_radius[1]=0.0;
- ubo_data.light_pos_inv_radius[2]=0.0;
- ubo_data.light_pos_inv_radius[3]=0.0;
-
- Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0,0,-1))).normalized();
- ubo_data.light_direction_attenuation[0]=direction.x;
- ubo_data.light_direction_attenuation[1]=direction.y;
- ubo_data.light_direction_attenuation[2]=direction.z;
- ubo_data.light_direction_attenuation[3]=1.0;
-
- ubo_data.light_params[0]=0;
- ubo_data.light_params[1]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
- ubo_data.light_params[2]=0;
- ubo_data.light_params[3]=0;
+ ubo_data.light_pos_inv_radius[0] = 0.0;
+ ubo_data.light_pos_inv_radius[1] = 0.0;
+ ubo_data.light_pos_inv_radius[2] = 0.0;
+ ubo_data.light_pos_inv_radius[3] = 0.0;
+
+ Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized();
+ ubo_data.light_direction_attenuation[0] = direction.x;
+ ubo_data.light_direction_attenuation[1] = direction.y;
+ ubo_data.light_direction_attenuation[2] = direction.z;
+ ubo_data.light_direction_attenuation[3] = 1.0;
+
+ ubo_data.light_params[0] = 0;
+ ubo_data.light_params[1] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
+ ubo_data.light_params[2] = 0;
+ ubo_data.light_params[3] = 0;
Color shadow_color = li->light_ptr->shadow_color.to_linear();
- ubo_data.light_shadow_color_contact[0]=shadow_color.r;
- ubo_data.light_shadow_color_contact[1]=shadow_color.g;
- ubo_data.light_shadow_color_contact[2]=shadow_color.b;
- ubo_data.light_shadow_color_contact[3]=li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
-
+ ubo_data.light_shadow_color_contact[0] = shadow_color.r;
+ ubo_data.light_shadow_color_contact[1] = shadow_color.g;
+ ubo_data.light_shadow_color_contact[2] = shadow_color.b;
+ ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
if (p_use_shadows && li->light_ptr->shadow) {
- int shadow_count=0;
+ int shadow_count = 0;
- switch(li->light_ptr->directional_shadow_mode) {
+ switch (li->light_ptr->directional_shadow_mode) {
case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: {
- shadow_count=1;
+ shadow_count = 1;
} break;
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: {
- shadow_count=2;
+ shadow_count = 2;
} break;
case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: {
- shadow_count=4;
+ shadow_count = 4;
} break;
-
}
- for(int j=0;j<shadow_count;j++) {
+ for (int j = 0; j < shadow_count; j++) {
+ uint32_t x = li->directional_rect.pos.x;
+ uint32_t y = li->directional_rect.pos.y;
+ uint32_t width = li->directional_rect.size.x;
+ uint32_t height = li->directional_rect.size.y;
- uint32_t x=li->directional_rect.pos.x;
- uint32_t y=li->directional_rect.pos.y;
- uint32_t width=li->directional_rect.size.x;
- uint32_t height=li->directional_rect.size.y;
+ if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ width /= 2;
+ height /= 2;
+ if (j == 0) {
- if (li->light_ptr->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
-
-
- width/=2;
- height/=2;
-
- if (j==0) {
-
- } else if (j==1) {
- x+=width;
- } else if (j==2) {
- y+=height;
- } else if (j==3) {
- x+=width;
- y+=height;
-
+ } else if (j == 1) {
+ x += width;
+ } else if (j == 2) {
+ y += height;
+ } else if (j == 3) {
+ x += width;
+ y += height;
}
+ } else if (li->light_ptr->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
+ height /= 2;
- } else if (li->light_ptr->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
-
- height/=2;
-
- if (j==0) {
+ if (j == 0) {
} else {
- y+=height;
+ y += height;
}
-
}
- ubo_data.shadow_split_offsets[j]=1.0/li->shadow_transform[j].split;
+ ubo_data.shadow_split_offsets[j] = 1.0 / li->shadow_transform[j].split;
Transform modelview = (p_camera_inverse_transform * li->shadow_transform[j].transform).inverse();
CameraMatrix bias;
bias.set_light_bias();
CameraMatrix rectm;
- Rect2 atlas_rect = Rect2(float(x)/directional_shadow.size,float(y)/directional_shadow.size,float(width)/directional_shadow.size,float(height)/directional_shadow.size);
+ Rect2 atlas_rect = Rect2(float(x) / directional_shadow.size, float(y) / directional_shadow.size, float(width) / directional_shadow.size, float(height) / directional_shadow.size);
rectm.set_light_atlas_rect(atlas_rect);
-
CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[j].camera * modelview;
- store_camera(shadow_mtx,&ubo_data.shadow_matrix1[16*j]);
-
- ubo_data.light_clamp[0]=atlas_rect.pos.x;
- ubo_data.light_clamp[1]=atlas_rect.pos.y;
- ubo_data.light_clamp[2]=atlas_rect.size.x;
- ubo_data.light_clamp[3]=atlas_rect.size.y;
+ store_camera(shadow_mtx, &ubo_data.shadow_matrix1[16 * j]);
+ ubo_data.light_clamp[0] = atlas_rect.pos.x;
+ ubo_data.light_clamp[1] = atlas_rect.pos.y;
+ ubo_data.light_clamp[2] = atlas_rect.size.x;
+ ubo_data.light_clamp[3] = atlas_rect.size.y;
}
-
}
glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo);
glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightDataUBO), &ubo_data);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
- directional_light=li;
-
- glBindBufferBase(GL_UNIFORM_BUFFER,3,state.directional_ubo);
+ directional_light = li;
+ glBindBufferBase(GL_UNIFORM_BUFFER, 3, state.directional_ubo);
}
-void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result,int p_light_cull_count,const Transform& p_camera_inverse_transform,const CameraMatrix& p_camera_projection,RID p_shadow_atlas) {
+void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_shadow_atlas) {
+ state.omni_light_count = 0;
+ state.spot_light_count = 0;
+ state.directional_light_count = 0;
- state.omni_light_count=0;
- state.spot_light_count=0;
- state.directional_light_count=0;
-
- directional_light=NULL;
+ directional_light = NULL;
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
+ for (int i = 0; i < p_light_cull_count; i++) {
- for(int i=0;i<p_light_cull_count;i++) {
-
- ERR_BREAK( i>=RenderList::MAX_LIGHTS );
+ ERR_BREAK(i >= RenderList::MAX_LIGHTS);
LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]);
LightDataUBO ubo_data; //used for filling
- switch(li->light_ptr->type) {
+ switch (li->light_ptr->type) {
case VS::LIGHT_DIRECTIONAL: {
- if (state.directional_light_count<RenderList::MAX_DIRECTIONAL_LIGHTS) {
- directional_lights[state.directional_light_count++]=li;
+ if (state.directional_light_count < RenderList::MAX_DIRECTIONAL_LIGHTS) {
+ directional_lights[state.directional_light_count++] = li;
}
-
} break;
case VS::LIGHT_OMNI: {
- float sign = li->light_ptr->negative?-1:1;
+ float sign = li->light_ptr->negative ? -1 : 1;
Color linear_col = li->light_ptr->color.to_linear();
- ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[3]=0;
-
+ ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[3] = 0;
Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin);
//directional, keep at 0
- ubo_data.light_pos_inv_radius[0]=pos.x;
- ubo_data.light_pos_inv_radius[1]=pos.y;
- ubo_data.light_pos_inv_radius[2]=pos.z;
- ubo_data.light_pos_inv_radius[3]=1.0/MAX(0.001,li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
+ ubo_data.light_pos_inv_radius[0] = pos.x;
+ ubo_data.light_pos_inv_radius[1] = pos.y;
+ ubo_data.light_pos_inv_radius[2] = pos.z;
+ ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
- ubo_data.light_direction_attenuation[0]=0;
- ubo_data.light_direction_attenuation[1]=0;
- ubo_data.light_direction_attenuation[2]=0;
- ubo_data.light_direction_attenuation[3]=li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
+ ubo_data.light_direction_attenuation[0] = 0;
+ ubo_data.light_direction_attenuation[1] = 0;
+ ubo_data.light_direction_attenuation[2] = 0;
+ ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
- ubo_data.light_params[0]=0;
- ubo_data.light_params[1]=0;
- ubo_data.light_params[2]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
- ubo_data.light_params[3]=0;
+ ubo_data.light_params[0] = 0;
+ ubo_data.light_params[1] = 0;
+ ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
+ ubo_data.light_params[3] = 0;
Color shadow_color = li->light_ptr->shadow_color.to_linear();
- ubo_data.light_shadow_color_contact[0]=shadow_color.r;
- ubo_data.light_shadow_color_contact[1]=shadow_color.g;
- ubo_data.light_shadow_color_contact[2]=shadow_color.b;
- ubo_data.light_shadow_color_contact[3]=li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
+ ubo_data.light_shadow_color_contact[0] = shadow_color.r;
+ ubo_data.light_shadow_color_contact[1] = shadow_color.g;
+ ubo_data.light_shadow_color_contact[2] = shadow_color.b;
+ ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) {
// fill in the shadow information
uint32_t key = shadow_atlas->shadow_owners[li->self];
- uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3;
+ uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
- ERR_CONTINUE(shadow>=shadow_atlas->quadrants[quadrant].shadows.size());
+ ERR_CONTINUE(shadow >= shadow_atlas->quadrants[quadrant].shadows.size());
uint32_t atlas_size = shadow_atlas->size;
- uint32_t quadrant_size = atlas_size>>1;
+ uint32_t quadrant_size = atlas_size >> 1;
- uint32_t x=(quadrant&1)*quadrant_size;
- uint32_t y=(quadrant>>1)*quadrant_size;
+ uint32_t x = (quadrant & 1) * quadrant_size;
+ uint32_t y = (quadrant >> 1) * quadrant_size;
uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
- x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
- y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
-
- uint32_t width=shadow_size;
- uint32_t height=shadow_size;
+ x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
+ y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
+ uint32_t width = shadow_size;
+ uint32_t height = shadow_size;
- if (li->light_ptr->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
+ if (li->light_ptr->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
- height/=2;
+ height /= 2;
} else {
- width/=2;
-
+ width /= 2;
}
Transform proj = (p_camera_inverse_transform * li->transform).inverse();
- store_transform(proj,ubo_data.shadow_matrix1);
-
- ubo_data.light_params[3]=1.0; //means it has shadow
- ubo_data.light_clamp[0]=float(x)/atlas_size;
- ubo_data.light_clamp[1]=float(y)/atlas_size;
- ubo_data.light_clamp[2]=float(width)/atlas_size;
- ubo_data.light_clamp[3]=float(height)/atlas_size;
+ store_transform(proj, ubo_data.shadow_matrix1);
+ ubo_data.light_params[3] = 1.0; //means it has shadow
+ ubo_data.light_clamp[0] = float(x) / atlas_size;
+ ubo_data.light_clamp[1] = float(y) / atlas_size;
+ ubo_data.light_clamp[2] = float(width) / atlas_size;
+ ubo_data.light_clamp[3] = float(height) / atlas_size;
}
-
- li->light_index=state.omni_light_count;
- copymem(&state.omni_array_tmp[li->light_index*state.ubo_light_size],&ubo_data,state.ubo_light_size);
+ li->light_index = state.omni_light_count;
+ copymem(&state.omni_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size);
state.omni_light_count++;
-
-
#if 0
if (li->light_ptr->shadow_enabled) {
li->shadow_projection[0] = Transform(camera_transform_inverse * li->transform).inverse();
@@ -2582,69 +2400,69 @@ void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result,int p_light_cu
} break;
case VS::LIGHT_SPOT: {
- float sign = li->light_ptr->negative?-1:1;
+ float sign = li->light_ptr->negative ? -1 : 1;
Color linear_col = li->light_ptr->color.to_linear();
- ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
- ubo_data.light_color_energy[3]=0;
+ ubo_data.light_color_energy[0] = linear_col.r * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[1] = linear_col.g * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[2] = linear_col.b * sign * li->light_ptr->param[VS::LIGHT_PARAM_ENERGY];
+ ubo_data.light_color_energy[3] = 0;
Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin);
//directional, keep at 0
- ubo_data.light_pos_inv_radius[0]=pos.x;
- ubo_data.light_pos_inv_radius[1]=pos.y;
- ubo_data.light_pos_inv_radius[2]=pos.z;
- ubo_data.light_pos_inv_radius[3]=1.0/MAX(0.001,li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
-
- Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0,0,-1))).normalized();
- ubo_data.light_direction_attenuation[0]=direction.x;
- ubo_data.light_direction_attenuation[1]=direction.y;
- ubo_data.light_direction_attenuation[2]=direction.z;
- ubo_data.light_direction_attenuation[3]=li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
-
- ubo_data.light_params[0]=li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION];
- ubo_data.light_params[1]=Math::cos(Math::deg2rad(li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE]));
- ubo_data.light_params[2]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
- ubo_data.light_params[3]=0;
+ ubo_data.light_pos_inv_radius[0] = pos.x;
+ ubo_data.light_pos_inv_radius[1] = pos.y;
+ ubo_data.light_pos_inv_radius[2] = pos.z;
+ ubo_data.light_pos_inv_radius[3] = 1.0 / MAX(0.001, li->light_ptr->param[VS::LIGHT_PARAM_RANGE]);
+
+ Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0, 0, -1))).normalized();
+ ubo_data.light_direction_attenuation[0] = direction.x;
+ ubo_data.light_direction_attenuation[1] = direction.y;
+ ubo_data.light_direction_attenuation[2] = direction.z;
+ ubo_data.light_direction_attenuation[3] = li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION];
+
+ ubo_data.light_params[0] = li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION];
+ ubo_data.light_params[1] = Math::cos(Math::deg2rad(li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE]));
+ ubo_data.light_params[2] = li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR];
+ ubo_data.light_params[3] = 0;
Color shadow_color = li->light_ptr->shadow_color.to_linear();
- ubo_data.light_shadow_color_contact[0]=shadow_color.r;
- ubo_data.light_shadow_color_contact[1]=shadow_color.g;
- ubo_data.light_shadow_color_contact[2]=shadow_color.b;
- ubo_data.light_shadow_color_contact[3]=li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
+ ubo_data.light_shadow_color_contact[0] = shadow_color.r;
+ ubo_data.light_shadow_color_contact[1] = shadow_color.g;
+ ubo_data.light_shadow_color_contact[2] = shadow_color.b;
+ ubo_data.light_shadow_color_contact[3] = li->light_ptr->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE];
if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) {
// fill in the shadow information
uint32_t key = shadow_atlas->shadow_owners[li->self];
- uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3;
+ uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
- ERR_CONTINUE(shadow>=shadow_atlas->quadrants[quadrant].shadows.size());
+ ERR_CONTINUE(shadow >= shadow_atlas->quadrants[quadrant].shadows.size());
uint32_t atlas_size = shadow_atlas->size;
- uint32_t quadrant_size = atlas_size>>1;
+ uint32_t quadrant_size = atlas_size >> 1;
- uint32_t x=(quadrant&1)*quadrant_size;
- uint32_t y=(quadrant>>1)*quadrant_size;
+ uint32_t x = (quadrant & 1) * quadrant_size;
+ uint32_t y = (quadrant >> 1) * quadrant_size;
uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
- x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
- y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
+ x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
+ y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
- uint32_t width=shadow_size;
- uint32_t height=shadow_size;
+ uint32_t width = shadow_size;
+ uint32_t height = shadow_size;
- Rect2 rect(float(x)/atlas_size,float(y)/atlas_size,float(width)/atlas_size,float(height)/atlas_size);
+ Rect2 rect(float(x) / atlas_size, float(y) / atlas_size, float(width) / atlas_size, float(height) / atlas_size);
- ubo_data.light_params[3]=1.0; //means it has shadow
- ubo_data.light_clamp[0]=rect.pos.x;
- ubo_data.light_clamp[1]=rect.pos.y;
- ubo_data.light_clamp[2]=rect.size.x;
- ubo_data.light_clamp[3]=rect.size.y;
+ ubo_data.light_params[3] = 1.0; //means it has shadow
+ ubo_data.light_clamp[0] = rect.pos.x;
+ ubo_data.light_clamp[1] = rect.pos.y;
+ ubo_data.light_clamp[2] = rect.size.x;
+ ubo_data.light_clamp[3] = rect.size.y;
Transform modelview = (p_camera_inverse_transform * li->transform).inverse();
@@ -2655,13 +2473,11 @@ void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result,int p_light_cu
CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[0].camera * modelview;
- store_camera(shadow_mtx,ubo_data.shadow_matrix1);
-
-
+ store_camera(shadow_mtx, ubo_data.shadow_matrix1);
}
- li->light_index=state.spot_light_count;
- copymem(&state.spot_array_tmp[li->light_index*state.ubo_light_size],&ubo_data,state.ubo_light_size);
+ li->light_index = state.spot_light_count;
+ copymem(&state.spot_array_tmp[li->light_index * state.ubo_light_size], &ubo_data, state.ubo_light_size);
state.spot_light_count++;
#if 0
@@ -2674,225 +2490,200 @@ void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result,int p_light_cu
}
#endif
} break;
-
}
-
- li->last_pass=render_pass;
+ li->last_pass = render_pass;
//update UBO for forward rendering, blit to texture for clustered
-
}
-
-
if (state.omni_light_count) {
glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0, state.omni_light_count*state.ubo_light_size, state.omni_array_tmp);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, state.omni_light_count * state.ubo_light_size, state.omni_array_tmp);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
- glBindBufferBase(GL_UNIFORM_BUFFER,4,state.omni_array_ubo);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 4, state.omni_array_ubo);
if (state.spot_light_count) {
glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0, state.spot_light_count*state.ubo_light_size, state.spot_array_tmp);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, state.spot_light_count * state.ubo_light_size, state.spot_array_tmp);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
}
- glBindBufferBase(GL_UNIFORM_BUFFER,5,state.spot_array_ubo);
-
-
+ glBindBufferBase(GL_UNIFORM_BUFFER, 5, state.spot_array_ubo);
}
-void RasterizerSceneGLES3::_setup_reflections(RID *p_reflection_probe_cull_result,int p_reflection_probe_cull_count,const Transform& p_camera_inverse_transform,const CameraMatrix& p_camera_projection,RID p_reflection_atlas,Environment *p_env) {
+void RasterizerSceneGLES3::_setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_reflection_atlas, Environment *p_env) {
- state.reflection_probe_count=0;
+ state.reflection_probe_count = 0;
- for(int i=0;i<p_reflection_probe_cull_count;i++) {
+ for (int i = 0; i < p_reflection_probe_cull_count; i++) {
- ReflectionProbeInstance *rpi=reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]);
+ ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]);
ERR_CONTINUE(!rpi);
- ReflectionAtlas *reflection_atlas=reflection_atlas_owner.getornull(p_reflection_atlas);
+ ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
ERR_CONTINUE(!reflection_atlas);
- ERR_CONTINUE(rpi->reflection_atlas_index<0);
-
+ ERR_CONTINUE(rpi->reflection_atlas_index < 0);
- if (state.reflection_probe_count>=state.max_ubo_reflections)
+ if (state.reflection_probe_count >= state.max_ubo_reflections)
break;
- rpi->last_pass=render_pass;
-
+ rpi->last_pass = render_pass;
ReflectionProbeDataUBO reflection_ubo;
- reflection_ubo.box_extents[0]=rpi->probe_ptr->extents.x;
- reflection_ubo.box_extents[1]=rpi->probe_ptr->extents.y;
- reflection_ubo.box_extents[2]=rpi->probe_ptr->extents.z;
- reflection_ubo.box_extents[3]=0;
+ reflection_ubo.box_extents[0] = rpi->probe_ptr->extents.x;
+ reflection_ubo.box_extents[1] = rpi->probe_ptr->extents.y;
+ reflection_ubo.box_extents[2] = rpi->probe_ptr->extents.z;
+ reflection_ubo.box_extents[3] = 0;
+ reflection_ubo.box_ofs[0] = rpi->probe_ptr->origin_offset.x;
+ reflection_ubo.box_ofs[1] = rpi->probe_ptr->origin_offset.y;
+ reflection_ubo.box_ofs[2] = rpi->probe_ptr->origin_offset.z;
+ reflection_ubo.box_ofs[3] = 0;
-
- reflection_ubo.box_ofs[0]=rpi->probe_ptr->origin_offset.x;
- reflection_ubo.box_ofs[1]=rpi->probe_ptr->origin_offset.y;
- reflection_ubo.box_ofs[2]=rpi->probe_ptr->origin_offset.z;
- reflection_ubo.box_ofs[3]=0;
-
- reflection_ubo.params[0]=rpi->probe_ptr->intensity;
- reflection_ubo.params[1]=0;
- reflection_ubo.params[2]=rpi->probe_ptr->interior?1.0:0.0;
- reflection_ubo.params[3]=rpi->probe_ptr->box_projection?1.0:0.0;
+ reflection_ubo.params[0] = rpi->probe_ptr->intensity;
+ reflection_ubo.params[1] = 0;
+ reflection_ubo.params[2] = rpi->probe_ptr->interior ? 1.0 : 0.0;
+ reflection_ubo.params[3] = rpi->probe_ptr->box_projection ? 1.0 : 0.0;
if (rpi->probe_ptr->interior) {
Color ambient_linear = rpi->probe_ptr->interior_ambient.to_linear();
- reflection_ubo.ambient[0]=ambient_linear.r*rpi->probe_ptr->interior_ambient_energy;
- reflection_ubo.ambient[1]=ambient_linear.g*rpi->probe_ptr->interior_ambient_energy;
- reflection_ubo.ambient[2]=ambient_linear.b*rpi->probe_ptr->interior_ambient_energy;
- reflection_ubo.ambient[3]=rpi->probe_ptr->interior_ambient_probe_contrib;
+ reflection_ubo.ambient[0] = ambient_linear.r * rpi->probe_ptr->interior_ambient_energy;
+ reflection_ubo.ambient[1] = ambient_linear.g * rpi->probe_ptr->interior_ambient_energy;
+ reflection_ubo.ambient[2] = ambient_linear.b * rpi->probe_ptr->interior_ambient_energy;
+ reflection_ubo.ambient[3] = rpi->probe_ptr->interior_ambient_probe_contrib;
} else {
Color ambient_linear;
- float contrib=0;
+ float contrib = 0;
if (p_env) {
- ambient_linear=p_env->ambient_color.to_linear();
- ambient_linear.r*=p_env->ambient_energy;
- ambient_linear.g*=p_env->ambient_energy;
- ambient_linear.b*=p_env->ambient_energy;
- contrib=p_env->ambient_skybox_contribution;
+ ambient_linear = p_env->ambient_color.to_linear();
+ ambient_linear.r *= p_env->ambient_energy;
+ ambient_linear.g *= p_env->ambient_energy;
+ ambient_linear.b *= p_env->ambient_energy;
+ contrib = p_env->ambient_skybox_contribution;
}
- reflection_ubo.ambient[0]=ambient_linear.r;
- reflection_ubo.ambient[1]=ambient_linear.g;
- reflection_ubo.ambient[2]=ambient_linear.b;
- reflection_ubo.ambient[3]=0;
+ reflection_ubo.ambient[0] = ambient_linear.r;
+ reflection_ubo.ambient[1] = ambient_linear.g;
+ reflection_ubo.ambient[2] = ambient_linear.b;
+ reflection_ubo.ambient[3] = 0;
}
int cell_size = reflection_atlas->size / reflection_atlas->subdiv;
int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size;
int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size;
- int width=cell_size;
- int height=cell_size;
+ int width = cell_size;
+ int height = cell_size;
- reflection_ubo.atlas_clamp[0]=float(x)/reflection_atlas->size;
- reflection_ubo.atlas_clamp[1]=float(y)/reflection_atlas->size;
- reflection_ubo.atlas_clamp[2]=float(width)/reflection_atlas->size;
- reflection_ubo.atlas_clamp[3]=float(height/2)/reflection_atlas->size;
+ reflection_ubo.atlas_clamp[0] = float(x) / reflection_atlas->size;
+ reflection_ubo.atlas_clamp[1] = float(y) / reflection_atlas->size;
+ reflection_ubo.atlas_clamp[2] = float(width) / reflection_atlas->size;
+ reflection_ubo.atlas_clamp[3] = float(height / 2) / reflection_atlas->size;
Transform proj = (p_camera_inverse_transform * rpi->transform).inverse();
- store_transform(proj,reflection_ubo.local_matrix);
+ store_transform(proj, reflection_ubo.local_matrix);
- rpi->reflection_index=state.reflection_probe_count;
- copymem(&state.reflection_array_tmp[rpi->reflection_index*sizeof(ReflectionProbeDataUBO)],&reflection_ubo,sizeof(ReflectionProbeDataUBO));
+ rpi->reflection_index = state.reflection_probe_count;
+ copymem(&state.reflection_array_tmp[rpi->reflection_index * sizeof(ReflectionProbeDataUBO)], &reflection_ubo, sizeof(ReflectionProbeDataUBO));
state.reflection_probe_count++;
-
}
-
if (state.reflection_probe_count) {
-
glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo);
- glBufferSubData(GL_UNIFORM_BUFFER, 0, state.reflection_probe_count*sizeof(ReflectionProbeDataUBO), state.reflection_array_tmp);
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, state.reflection_probe_count * sizeof(ReflectionProbeDataUBO), state.reflection_array_tmp);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
}
- glBindBufferBase(GL_UNIFORM_BUFFER,6,state.reflection_array_ubo);
-
+ glBindBufferBase(GL_UNIFORM_BUFFER, 6, state.reflection_array_ubo);
}
-
void RasterizerSceneGLES3::_copy_screen() {
- glBindVertexArray( storage->resources.quadie_array);
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glBindVertexArray(storage->resources.quadie_array);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindVertexArray(0);
-
}
void RasterizerSceneGLES3::_copy_to_front_buffer(Environment *env) {
//copy to front buffer
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);
- glColorMask(1,1,1,1);
+ glColorMask(1, 1, 1, 1);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.diffuse);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
if (!env) {
//no environment, simply convert from linear to srgb
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, true);
} else {
/* FIXME: Why are both statements equal? */
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true);
-
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, true);
}
storage->shaders.copy.bind();
_copy_screen();
-
//turn off everything used
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false);
-
-
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false);
}
void RasterizerSceneGLES3::_copy_texture_to_front_buffer(GLuint p_texture) {
//copy to front buffer
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);
- glColorMask(1,1,1,1);
+ glColorMask(1, 1, 1, 1);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,p_texture);
+ glBindTexture(GL_TEXTURE_2D, p_texture);
- glViewport(0,0,storage->frame.current_rt->width*0.5,storage->frame.current_rt->height*0.5);
+ glViewport(0, 0, storage->frame.current_rt->width * 0.5, storage->frame.current_rt->height * 0.5);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
storage->shaders.copy.bind();
_copy_screen();
//turn off everything used
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false);
-
-
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false);
}
-void RasterizerSceneGLES3::_fill_render_list(InstanceBase** p_cull_result,int p_cull_count,bool p_shadow){
+void RasterizerSceneGLES3::_fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_shadow) {
- current_geometry_index=0;
- current_material_index=0;
- state.used_sss=false;
+ current_geometry_index = 0;
+ current_material_index = 0;
+ state.used_sss = false;
//fill list
- for(int i=0;i<p_cull_count;i++) {
+ for (int i = 0; i < p_cull_count; i++) {
InstanceBase *inst = p_cull_result[i];
- switch(inst->base_type) {
+ switch (inst->base_type) {
case VS::INSTANCE_MESH: {
@@ -2901,11 +2692,11 @@ void RasterizerSceneGLES3::_fill_render_list(InstanceBase** p_cull_result,int p_
int ssize = mesh->surfaces.size();
- for (int i=0;i<ssize;i++) {
+ for (int i = 0; i < ssize; i++) {
int mat_idx = inst->materials[i].is_valid() ? i : -1;
RasterizerStorageGLES3::Surface *s = mesh->surfaces[i];
- _add_geometry(s,inst,NULL,mat_idx,p_shadow);
+ _add_geometry(s, inst, NULL, mat_idx, p_shadow);
}
//mesh->last_pass=frame;
@@ -2916,8 +2707,7 @@ void RasterizerSceneGLES3::_fill_render_list(InstanceBase** p_cull_result,int p_
RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getptr(inst->base);
ERR_CONTINUE(!multi_mesh);
-
- if (multi_mesh->size==0 || multi_mesh->visible_instances==0)
+ if (multi_mesh->size == 0 || multi_mesh->visible_instances == 0)
continue;
RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(multi_mesh->mesh);
@@ -2926,32 +2716,27 @@ void RasterizerSceneGLES3::_fill_render_list(InstanceBase** p_cull_result,int p_
int ssize = mesh->surfaces.size();
- for (int i=0;i<ssize;i++) {
+ for (int i = 0; i < ssize; i++) {
RasterizerStorageGLES3::Surface *s = mesh->surfaces[i];
- _add_geometry(s,inst,multi_mesh,-1,p_shadow);
+ _add_geometry(s, inst, multi_mesh, -1, p_shadow);
}
-
} break;
case VS::INSTANCE_IMMEDIATE: {
} break;
-
}
}
}
-
-void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_cam_projection) {
-
+void RasterizerSceneGLES3::_render_mrts(Environment *env, const CameraMatrix &p_cam_projection) {
glDepthMask(GL_FALSE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
-
if (env->ssao_enabled) {
//copy diffuse to front buffer
glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
@@ -2962,87 +2747,83 @@ void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_c
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
-
//copy from depth, convert to linear
GLint ss[2];
- ss[0]=storage->frame.current_rt->width;
- ss[1]=storage->frame.current_rt->height;
+ ss[0] = storage->frame.current_rt->width;
+ ss[1] = storage->frame.current_rt->height;
- for(int i=0;i<storage->frame.current_rt->effects.ssao.depth_mipmap_fbos.size();i++) {
+ for (int i = 0; i < storage->frame.current_rt->effects.ssao.depth_mipmap_fbos.size(); i++) {
- state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::MINIFY_START,i==0);
+ state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::MINIFY_START, i == 0);
state.ssao_minify_shader.bind();
- state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
- state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::SOURCE_MIPMAP,MAX(0,i-1));
- glUniform2iv(state.ssao_minify_shader.get_uniform(SsaoMinifyShaderGLES3::FROM_SIZE),1,ss);
- ss[0]>>=1;
- ss[1]>>=1;
+ state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
+ state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::SOURCE_MIPMAP, MAX(0, i - 1));
+ glUniform2iv(state.ssao_minify_shader.get_uniform(SsaoMinifyShaderGLES3::FROM_SIZE), 1, ss);
+ ss[0] >>= 1;
+ ss[1] >>= 1;
glActiveTexture(GL_TEXTURE0);
- if (i==0) {
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ if (i == 0) {
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
} else {
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.linear_depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth);
}
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.depth_mipmap_fbos[i]); //copy to front first
- glViewport(0,0,ss[0],ss[1]);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.depth_mipmap_fbos[i]); //copy to front first
+ glViewport(0, 0, ss[0], ss[1]);
_copy_screen();
-
}
- ss[0]=storage->frame.current_rt->width;
- ss[1]=storage->frame.current_rt->height;
-
- glViewport(0,0,ss[0],ss[1]);
+ ss[0] = storage->frame.current_rt->width;
+ ss[1] = storage->frame.current_rt->height;
+ glViewport(0, 0, ss[0], ss[1]);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_GREATER);
// do SSAO!
- state.ssao_shader.set_conditional(SsaoShaderGLES3::ENABLE_RADIUS2,env->ssao_radius2>0.001);
+ state.ssao_shader.set_conditional(SsaoShaderGLES3::ENABLE_RADIUS2, env->ssao_radius2 > 0.001);
state.ssao_shader.bind();
- state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
- state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- glUniform2iv(state.ssao_shader.get_uniform(SsaoShaderGLES3::SCREEN_SIZE),1,ss);
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ glUniform2iv(state.ssao_shader.get_uniform(SsaoShaderGLES3::SCREEN_SIZE), 1, ss);
float radius = env->ssao_radius;
- state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS,radius);
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS, radius);
float intensity = env->ssao_intensity;
- state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R6,intensity / pow(radius, 6.0f));
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R6, intensity / pow(radius, 6.0f));
- if (env->ssao_radius2>0.001) {
+ if (env->ssao_radius2 > 0.001) {
float radius2 = env->ssao_radius2;
- state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS2,radius2);
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS2, radius2);
float intensity2 = env->ssao_intensity2;
- state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R62,intensity2 / pow(radius2, 6.0f));
-
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R62, intensity2 / pow(radius2, 6.0f));
}
- float proj_info[4]={
- -2.0f / (ss[0]*p_cam_projection.matrix[0][0]),
- -2.0f / (ss[1]*p_cam_projection.matrix[1][1]),
- ( 1.0f - p_cam_projection.matrix[0][2]) / p_cam_projection.matrix[0][0],
- ( 1.0f + p_cam_projection.matrix[1][2]) / p_cam_projection.matrix[1][1]
+ float proj_info[4] = {
+ -2.0f / (ss[0] * p_cam_projection.matrix[0][0]),
+ -2.0f / (ss[1] * p_cam_projection.matrix[1][1]),
+ (1.0f - p_cam_projection.matrix[0][2]) / p_cam_projection.matrix[0][0],
+ (1.0f + p_cam_projection.matrix[1][2]) / p_cam_projection.matrix[1][1]
};
- glUniform4fv(state.ssao_shader.get_uniform(SsaoShaderGLES3::PROJ_INFO),1,proj_info);
+ glUniform4fv(state.ssao_shader.get_uniform(SsaoShaderGLES3::PROJ_INFO), 1, proj_info);
float pixels_per_meter = float(p_cam_projection.get_pixels_per_meter(ss[0]));
- state.ssao_shader.set_uniform(SsaoShaderGLES3::PROJ_SCALE,pixels_per_meter);
- state.ssao_shader.set_uniform(SsaoShaderGLES3::BIAS,env->ssao_bias);
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::PROJ_SCALE, pixels_per_meter);
+ state.ssao_shader.set_uniform(SsaoShaderGLES3::BIAS, env->ssao_bias);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.linear_depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.linear_depth);
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.blur_fbo[0]); //copy to front first
- Color white(1,1,1,1);
- glClearBufferfv(GL_COLOR,0,white.components); // specular
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[0]); //copy to front first
+ Color white(1, 1, 1, 1);
+ glClearBufferfv(GL_COLOR, 0, white.components); // specular
_copy_screen();
@@ -3051,22 +2832,21 @@ void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_c
state.ssao_blur_shader.bind();
if (env->ssao_filter) {
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
- state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- GLint axis[2]={i,1-i};
- glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::AXIS),1,axis);
+ state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
+ state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ GLint axis[2] = { i, 1 - i };
+ glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::AXIS), 1, axis);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.blur_red[i]);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[i]);
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.blur_fbo[1-i]);
- if (i==0) {
- glClearBufferfv(GL_COLOR,0,white.components); // specular
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.ssao.blur_fbo[1 - i]);
+ if (i == 0) {
+ glClearBufferfv(GL_COLOR, 0, white.components); // specular
}
_copy_screen();
-
}
}
@@ -3075,16 +2855,16 @@ void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_c
// just copy diffuse while applying SSAO
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::SSAO_COLOR,env->ssao_color);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::SSAO_COLOR, env->ssao_color);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); //previous level, since mipmaps[0] starts one level bigger
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color); //previous level, since mipmaps[0] starts one level bigger
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.blur_red[0]); //previous level, since mipmaps[0] starts one level bigger
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.ssao.blur_red[0]); //previous level, since mipmaps[0] starts one level bigger
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE, false);
} else {
@@ -3096,137 +2876,124 @@ void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_c
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
-
}
-
- if (state.used_sss) {//sss enabled
+ if (state.used_sss) { //sss enabled
//copy diffuse while performing sss
//copy normal and roughness to effect buffer
glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
glReadBuffer(GL_COLOR_ATTACHMENT3);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo);
- glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT , GL_NEAREST);
+ glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
- state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_11_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_LOW);
- state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_17_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_MEDIUM);
- state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_25_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_HIGH);
- state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_FOLLOW_SURFACE,subsurface_scatter_follow_surface);
+ state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_11_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_LOW);
+ state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_17_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_MEDIUM);
+ state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_25_SAMPLES, subsurface_scatter_quality == SSS_QUALITY_HIGH);
+ state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_FOLLOW_SURFACE, subsurface_scatter_follow_surface);
state.sss_shader.bind();
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::MAX_RADIUS,subsurface_scatter_size);
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::FOVY,p_cam_projection.get_fov());
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR,Vector2(1,0));
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::MAX_RADIUS, subsurface_scatter_size);
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::FOVY, p_cam_projection.get_fov());
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(1, 0));
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
_copy_screen();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color);
- state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR,Vector2(0,1));
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
+ state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR, Vector2(0, 1));
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
_copy_screen();
-
}
-
-
if (env->ssr_enabled) {
//copy normal and roughness to effect buffer
glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
glReadBuffer(GL_COLOR_ATTACHMENT2);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo);
- glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT , GL_NEAREST);
-
+ glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
//blur diffuse into effect mipmaps using separatable convolution
//storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
- for(int i=0;i<storage->frame.current_rt->effects.mip_maps[1].sizes.size();i++) {
-
+ for (int i = 0; i < storage->frame.current_rt->effects.mip_maps[1].sizes.size(); i++) {
int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width;
int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height;
- glViewport(0,0,vp_w,vp_h);
+ glViewport(0, 0, vp_w, vp_h);
//horizontal pass
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL, false);
//vertical pass
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[i+1].fbo); //next level, since mipmaps[0] starts one level bigger
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL, false);
}
-
//perform SSR
- state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::SMOOTH_ACCEL,env->ssr_accel>0 && env->ssr_smooth);
- state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::REFLECT_ROUGHNESS,env->ssr_accel>0 && env->ssr_roughness);
+ state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::SMOOTH_ACCEL, env->ssr_accel > 0 && env->ssr_smooth);
+ state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::REFLECT_ROUGHNESS, env->ssr_accel > 0 && env->ssr_roughness);
state.ssr_shader.bind();
int ssr_w = storage->frame.current_rt->effects.mip_maps[1].sizes[0].width;
int ssr_h = storage->frame.current_rt->effects.mip_maps[1].sizes[0].height;
-
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PIXEL_SIZE,Vector2(1.0/(ssr_w*0.5),1.0/(ssr_h*0.5)));
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PROJECTION,p_cam_projection);
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::INVERSE_PROJECTION,p_cam_projection.inverse());
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::VIEWPORT_SIZE,Size2(ssr_w,ssr_h));
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PIXEL_SIZE, Vector2(1.0 / (ssr_w * 0.5), 1.0 / (ssr_h * 0.5)));
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PROJECTION, p_cam_projection);
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::INVERSE_PROJECTION, p_cam_projection.inverse());
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::VIEWPORT_SIZE, Size2(ssr_w, ssr_h));
//state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FRAME_INDEX,int(render_pass));
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FILTER_MIPMAP_LEVELS,float(storage->frame.current_rt->effects.mip_maps[0].sizes.size()));
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::NUM_STEPS,env->ssr_max_steps);
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::ACCELERATION,env->ssr_accel);
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DEPTH_TOLERANCE,env->ssr_depth_tolerance);
- state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DISTANCE_FADE,env->ssr_fade);
-
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FILTER_MIPMAP_LEVELS, float(storage->frame.current_rt->effects.mip_maps[0].sizes.size()));
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::NUM_STEPS, env->ssr_max_steps);
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::ACCELERATION, env->ssr_accel);
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DEPTH_TOLERANCE, env->ssr_depth_tolerance);
+ state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DISTANCE_FADE, env->ssr_fade);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.effect);
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[0].fbo);
- glViewport(0,0,ssr_w,ssr_h);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[0].fbo);
+ glViewport(0, 0, ssr_w, ssr_h);
_copy_screen();
- glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height);
-
+ glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
}
-
-
glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
glReadBuffer(GL_COLOR_ATTACHMENT1);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo);
@@ -3238,46 +3005,43 @@ void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_c
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
//copy reflection over diffuse, resolving SSR if needed
- state.resolve_shader.set_conditional(ResolveShaderGLES3::USE_SSR,env->ssr_enabled);
+ state.resolve_shader.set_conditional(ResolveShaderGLES3::USE_SSR, env->ssr_enabled);
state.resolve_shader.bind();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
if (env->ssr_enabled) {
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
}
-
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
- glBlendFunc(GL_ONE,GL_ONE); //use additive to accumulate one over the other
+ glBlendFunc(GL_ONE, GL_ONE); //use additive to accumulate one over the other
_copy_screen();
glDisable(GL_BLEND); //end additive
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(0));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(0));
{
GLuint db = GL_COLOR_ATTACHMENT0;
- glDrawBuffers(1,&db);
+ glDrawBuffers(1, &db);
}
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY,false);
-
-
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY, false);
}
-void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_cam_projection){
+void RasterizerSceneGLES3::_post_process(Environment *env, const CameraMatrix &p_cam_projection) {
//copy to front buffer
@@ -3286,14 +3050,13 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
glDisable(GL_CULL_FACE);
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);
- glColorMask(1,1,1,1);
+ glColorMask(1, 1, 1, 1);
//turn off everything used
//copy specular to front buffer
//copy diffuse to effect buffer
-
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo);
@@ -3304,23 +3067,21 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
if (!env) {
//no environment, simply return and convert to SRGB
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, true);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, true);
storage->shaders.copy.bind();
_copy_screen();
- storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false);
- storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false); //compute luminance
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB, false);
+ storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA, false); //compute luminance
return;
-
}
-
//order of operation
//1) DOF Blur (first blur, then copy to buffer applying the blur)
//2) Motion Blur
@@ -3330,7 +3091,6 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
GLuint composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
-
if (env->dof_blur_far_enabled) {
//blur diffuse into effect mipmaps using separatable convolution
@@ -3339,54 +3099,51 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
int vp_h = storage->frame.current_rt->height;
int vp_w = storage->frame.current_rt->width;
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,true);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_LOW);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_HIGH);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_LOW);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_far_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH);
state.effect_blur_shader.bind();
- int qsteps[3]={4,10,20};
+ int qsteps[3] = { 4, 10, 20 };
- float radius = (env->dof_blur_far_amount*env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality];
+ float radius = (env->dof_blur_far_amount * env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality];
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_far_distance);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_far_distance+env->dof_blur_far_transition);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(1,0));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_far_distance);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_far_distance + env->dof_blur_far_transition);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,composite_from);
+ glBindTexture(GL_TEXTURE_2D, composite_from);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
_copy_screen();
-
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(0,1));
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1));
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,false);
-
-
- composite_from=storage->frame.current_rt->effects.mip_maps[0].color;
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false);
+ composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
}
if (env->dof_blur_near_enabled) {
@@ -3397,59 +3154,56 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
int vp_h = storage->frame.current_rt->height;
int vp_w = storage->frame.current_rt->width;
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR,true);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, true);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_LOW);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_HIGH);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_LOW);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_MEDIUM);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, env->dof_blur_near_quality == VS::ENV_DOF_BLUR_QUALITY_HIGH);
state.effect_blur_shader.bind();
- int qsteps[3]={4,10,20};
+ int qsteps[3] = { 4, 10, 20 };
- float radius = (env->dof_blur_near_amount*env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality];
+ float radius = (env->dof_blur_near_amount * env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality];
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_near_distance);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_near_distance-env->dof_blur_near_transition);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(1,0));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(1, 0));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,composite_from);
+ glBindTexture(GL_TEXTURE_2D, composite_from);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); //copy to front first
_copy_screen();
//manually do the blend if this is the first operation resolving from the diffuse buffer
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE,composite_from == storage->frame.current_rt->buffers.diffuse);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, composite_from == storage->frame.current_rt->buffers.diffuse);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false);
state.effect_blur_shader.bind();
-
-
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_near_distance);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_near_distance-env->dof_blur_near_transition);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(0,1));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near());
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far());
-
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN, env->dof_blur_near_distance);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END, env->dof_blur_near_distance - env->dof_blur_near_transition);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR, Vector2(0, 1));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS, radius);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR, p_cam_projection.get_z_near());
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR, p_cam_projection.get_z_far());
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->color);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level
if (composite_from != storage->frame.current_rt->buffers.diffuse) {
@@ -3459,8 +3213,7 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
} else {
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse);
-
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.diffuse);
}
_copy_screen();
@@ -3470,302 +3223,270 @@ void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_
glDisable(GL_BLEND);
}
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,false);
-
-
- composite_from=storage->frame.current_rt->effects.mip_maps[0].color;
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH, false);
+ composite_from = storage->frame.current_rt->effects.mip_maps[0].color;
}
- if ( env->auto_exposure) {
+ if (env->auto_exposure) {
//compute auto exposure
//first step, copy from image to luminance buffer
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN,true);
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, true);
state.exposure_shader.bind();
- int ss[2]={
+ int ss[2] = {
storage->frame.current_rt->width,
storage->frame.current_rt->height,
};
- int ds[2]={
+ int ds[2] = {
exposure_shrink_size,
exposure_shrink_size,
};
- glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::SOURCE_RENDER_SIZE),1,ss);
- glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::TARGET_SIZE),1,ds);
+ glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::SOURCE_RENDER_SIZE), 1, ss);
+ glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::TARGET_SIZE), 1, ds);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->buffers.diffuse);
-
- glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[0].fbo);
- glViewport(0,0,exposure_shrink_size,exposure_shrink_size);
+ glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[0].fbo);
+ glViewport(0, 0, exposure_shrink_size, exposure_shrink_size);
_copy_screen();
-
-
-
-
//second step, shrink to 2x2 pixels
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN,false);
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN, false);
state.exposure_shader.bind();
//shrink from second to previous to last level
- int s_size=exposure_shrink_size/3;
- for(int i=1;i<exposure_shrink.size()-1;i++) {
+ int s_size = exposure_shrink_size / 3;
+ for (int i = 1; i < exposure_shrink.size() - 1; i++) {
- glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[i].fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[i].fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,exposure_shrink[i-1].color);
+ glBindTexture(GL_TEXTURE_2D, exposure_shrink[i - 1].color);
_copy_screen();
- glViewport(0,0,s_size,s_size);
-
- s_size/=3;
+ glViewport(0, 0, s_size, s_size);
+ s_size /= 3;
}
//third step, shrink to 1x1 pixel taking in consideration the previous exposure
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END,true);
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, true);
uint64_t tick = OS::get_singleton()->get_ticks_usec();
- uint64_t tick_diff = storage->frame.current_rt->last_exposure_tick==0?0:tick-storage->frame.current_rt->last_exposure_tick;
- storage->frame.current_rt->last_exposure_tick=tick;
-
- if (tick_diff==0 || tick_diff>1000000) {
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET,true);
+ uint64_t tick_diff = storage->frame.current_rt->last_exposure_tick == 0 ? 0 : tick - storage->frame.current_rt->last_exposure_tick;
+ storage->frame.current_rt->last_exposure_tick = tick;
+ if (tick_diff == 0 || tick_diff > 1000000) {
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, true);
}
state.exposure_shader.bind();
- glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[exposure_shrink.size()-1].fbo);
- glViewport(0,0,1,1);
+ glBindFramebuffer(GL_FRAMEBUFFER, exposure_shrink[exposure_shrink.size() - 1].fbo);
+ glViewport(0, 0, 1, 1);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,exposure_shrink[exposure_shrink.size()-2].color);
+ glBindTexture(GL_TEXTURE_2D, exposure_shrink[exposure_shrink.size() - 2].color);
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); //read from previous
-
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color); //read from previous
- state.exposure_shader.set_uniform(ExposureShaderGLES3::EXPOSURE_ADJUST,env->auto_exposure_speed*(tick_diff/1000000.0));
- state.exposure_shader.set_uniform(ExposureShaderGLES3::MAX_LUMINANCE,env->auto_exposure_max);
- state.exposure_shader.set_uniform(ExposureShaderGLES3::MIN_LUMINANCE,env->auto_exposure_min);
+ state.exposure_shader.set_uniform(ExposureShaderGLES3::EXPOSURE_ADJUST, env->auto_exposure_speed * (tick_diff / 1000000.0));
+ state.exposure_shader.set_uniform(ExposureShaderGLES3::MAX_LUMINANCE, env->auto_exposure_max);
+ state.exposure_shader.set_uniform(ExposureShaderGLES3::MIN_LUMINANCE, env->auto_exposure_min);
_copy_screen();
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET,false);
- state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END,false);
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET, false);
+ state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END, false);
//last step, swap with the framebuffer exposure, so the right exposure is kept int he framebuffer
- SWAP(exposure_shrink[exposure_shrink.size()-1].fbo,storage->frame.current_rt->exposure.fbo);
- SWAP(exposure_shrink[exposure_shrink.size()-1].color,storage->frame.current_rt->exposure.color);
-
-
- glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height);
+ SWAP(exposure_shrink[exposure_shrink.size() - 1].fbo, storage->frame.current_rt->exposure.fbo);
+ SWAP(exposure_shrink[exposure_shrink.size() - 1].color, storage->frame.current_rt->exposure.color);
+ glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
}
-
- int max_glow_level=-1;
- int glow_mask=0;
-
+ int max_glow_level = -1;
+ int glow_mask = 0;
if (env->glow_enabled) {
+ for (int i = 0; i < VS::MAX_GLOW_LEVELS; i++) {
+ if (env->glow_levels & (1 << i)) {
- for(int i=0;i<VS::MAX_GLOW_LEVELS;i++) {
- if (env->glow_levels&(1<<i)) {
-
- if (i>=storage->frame.current_rt->effects.mip_maps[1].sizes.size()) {
- max_glow_level=storage->frame.current_rt->effects.mip_maps[1].sizes.size()-1;
- glow_mask|=1<<max_glow_level;
+ if (i >= storage->frame.current_rt->effects.mip_maps[1].sizes.size()) {
+ max_glow_level = storage->frame.current_rt->effects.mip_maps[1].sizes.size() - 1;
+ glow_mask |= 1 << max_glow_level;
} else {
- max_glow_level=i;
- glow_mask|=(1<<i);
+ max_glow_level = i;
+ glow_mask |= (1 << i);
}
-
}
}
-
//blur diffuse into effect mipmaps using separatable convolution
//storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true);
- for(int i=0;i<(max_glow_level+1);i++) {
-
+ for (int i = 0; i < (max_glow_level + 1); i++) {
int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width;
int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height;
- glViewport(0,0,vp_w,vp_h);
+ glViewport(0, 0, vp_w, vp_h);
//horizontal pass
- if (i==0) {
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS,true);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE,env->auto_exposure);
+ if (i == 0) {
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, env->auto_exposure);
}
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH,env->glow_strength);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength);
glActiveTexture(GL_TEXTURE0);
- if (i==0) {
- glBindTexture(GL_TEXTURE_2D,composite_from);
+ if (i == 0) {
+ glBindTexture(GL_TEXTURE_2D, composite_from);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::EXPOSURE,env->tone_mapper_exposure);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::EXPOSURE, env->tone_mapper_exposure);
if (env->auto_exposure) {
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::AUTO_EXPOSURE_GREY,env->auto_exposure_grey);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey);
}
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_BLOOM,env->glow_bloom);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_TRESHOLD,env->glow_hdr_bleed_treshold);
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_SCALE,env->glow_hdr_bleed_scale);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_BLOOM, env->glow_bloom);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_TRESHOLD, env->glow_hdr_bleed_treshold);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_SCALE, env->glow_hdr_bleed_scale);
} else {
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger
}
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo);
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS,false);
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS, false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE, false);
//vertical pass
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL,true);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, true);
state.effect_blur_shader.bind();
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i));
- state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH,env->glow_strength);
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE, Vector2(1.0 / vp_w, 1.0 / vp_h));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD, float(i));
+ state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH, env->glow_strength);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[i+1].fbo); //next level, since mipmaps[0] starts one level bigger
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[1].color);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[i + 1].fbo); //next level, since mipmaps[0] starts one level bigger
_copy_screen();
- state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL,false);
+ state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL, false);
}
- glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height);
-
+ glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
}
-
-
-
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,composite_from);
-
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_FILMIC);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_ACES);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_REINHARDT);
+ glBindTexture(GL_TEXTURE_2D, composite_from);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE,env->auto_exposure);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC,env->glow_bicubic_upscale);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_FILMIC);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_ACES);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER, env->tone_mapper == VS::ENV_TONE_MAPPER_REINHARDT);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, env->auto_exposure);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, env->glow_bicubic_upscale);
+ if (max_glow_level >= 0) {
- if (max_glow_level>=0) {
+ for (int i = 0; i < (max_glow_level + 1); i++) {
-
- for(int i=0;i<(max_glow_level+1);i++) {
-
- if (glow_mask&(1<<i)) {
- if (i==0) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1,true);
+ if (glow_mask & (1 << i)) {
+ if (i == 0) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, true);
}
- if (i==1) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2,true);
+ if (i == 1) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, true);
}
- if (i==2) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3,true);
+ if (i == 2) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, true);
}
- if (i==3) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4,true);
+ if (i == 3) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, true);
}
- if (i==4) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5,true);
+ if (i == 4) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, true);
}
- if (i==5) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6,true);
+ if (i == 5) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, true);
}
- if (i==6) {
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7,true);
+ if (i == 6) {
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, true);
}
}
}
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN,env->glow_blend_mode==VS::GLOW_BLEND_MODE_SCREEN);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT,env->glow_blend_mode==VS::GLOW_BLEND_MODE_SOFTLIGHT);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE,env->glow_blend_mode==VS::GLOW_BLEND_MODE_REPLACE);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SCREEN);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, env->glow_blend_mode == VS::GLOW_BLEND_MODE_SOFTLIGHT);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, env->glow_blend_mode == VS::GLOW_BLEND_MODE_REPLACE);
glActiveTexture(GL_TEXTURE2);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color);
-
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->effects.mip_maps[0].color);
}
state.tonemap_shader.bind();
- state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE,env->tone_mapper_exposure);
- state.tonemap_shader.set_uniform(TonemapShaderGLES3::WHITE,env->tone_mapper_exposure_white);
+ state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE, env->tone_mapper_exposure);
+ state.tonemap_shader.set_uniform(TonemapShaderGLES3::WHITE, env->tone_mapper_exposure_white);
- if (max_glow_level>=0) {
+ if (max_glow_level >= 0) {
- state.tonemap_shader.set_uniform(TonemapShaderGLES3::GLOW_INTENSITY,env->glow_intensity);
- int ss[2]={
+ state.tonemap_shader.set_uniform(TonemapShaderGLES3::GLOW_INTENSITY, env->glow_intensity);
+ int ss[2] = {
storage->frame.current_rt->width,
storage->frame.current_rt->height,
};
- glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES3::GLOW_TEXTURE_SIZE),1,ss);
-
+ glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES3::GLOW_TEXTURE_SIZE), 1, ss);
}
- if (env->auto_exposure) {
+ if (env->auto_exposure) {
glActiveTexture(GL_TEXTURE1);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color);
- state.tonemap_shader.set_uniform(TonemapShaderGLES3::AUTO_EXPOSURE_GREY,env->auto_exposure_grey);
-
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->exposure.color);
+ state.tonemap_shader.set_uniform(TonemapShaderGLES3::AUTO_EXPOSURE_GREY, env->auto_exposure_grey);
}
-
-
_copy_screen();
//turn off everything used
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT,false);
- state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC,false);
-
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT, false);
+ state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC, false);
}
-void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_ortogonal,InstanceBase** p_cull_result,int p_cull_count,RID* p_light_cull_result,int p_light_cull_count,RID* p_reflection_probe_cull_result,int p_reflection_probe_cull_count,RID p_environment,RID p_shadow_atlas,RID p_reflection_atlas,RID p_reflection_probe,int p_reflection_probe_pass){
+void RasterizerSceneGLES3::render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
//first of all, make a new render pass
render_pass++;
-
//fill up ubo
Environment *env = environment_owner.getornull(p_environment);
@@ -3773,73 +3494,69 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas);
if (shadow_atlas && shadow_atlas->size) {
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-3);
- glBindTexture(GL_TEXTURE_2D,shadow_atlas->depth);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 3);
+ glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
- state.ubo_data.shadow_atlas_pixel_size[0]=1.0/shadow_atlas->size;
- state.ubo_data.shadow_atlas_pixel_size[1]=1.0/shadow_atlas->size;
+ state.ubo_data.shadow_atlas_pixel_size[0] = 1.0 / shadow_atlas->size;
+ state.ubo_data.shadow_atlas_pixel_size[1] = 1.0 / shadow_atlas->size;
}
-
if (reflection_atlas && reflection_atlas->size) {
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-5);
- glBindTexture(GL_TEXTURE_2D,reflection_atlas->color);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 5);
+ glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
}
if (p_reflection_probe.is_valid()) {
- state.ubo_data.reflection_multiplier=0.0;
+ state.ubo_data.reflection_multiplier = 0.0;
} else {
- state.ubo_data.reflection_multiplier=1.0;
+ state.ubo_data.reflection_multiplier = 1.0;
}
- state.ubo_data.subsurface_scatter_width=subsurface_scatter_size;
+ state.ubo_data.subsurface_scatter_width = subsurface_scatter_size;
-
- state.ubo_data.shadow_z_offset=0;
- state.ubo_data.shadow_slope_scale=0;
- state.ubo_data.shadow_dual_paraboloid_render_side=0;
- state.ubo_data.shadow_dual_paraboloid_render_zfar=0;
+ state.ubo_data.shadow_z_offset = 0;
+ state.ubo_data.shadow_slope_scale = 0;
+ state.ubo_data.shadow_dual_paraboloid_render_side = 0;
+ state.ubo_data.shadow_dual_paraboloid_render_zfar = 0;
if (storage->frame.current_rt) {
- state.ubo_data.screen_pixel_size[0]=1.0/storage->frame.current_rt->width;
- state.ubo_data.screen_pixel_size[1]=1.0/storage->frame.current_rt->height;
+ state.ubo_data.screen_pixel_size[0] = 1.0 / storage->frame.current_rt->width;
+ state.ubo_data.screen_pixel_size[1] = 1.0 / storage->frame.current_rt->height;
}
- _setup_environment(env,p_cam_projection,p_cam_transform);
+ _setup_environment(env, p_cam_projection, p_cam_transform);
- bool fb_cleared=false;
+ bool fb_cleared = false;
glDepthFunc(GL_LEQUAL);
- state.used_contact_shadows=true;
+ state.used_contact_shadows = true;
- if ( storage->frame.current_rt && true) { //detect with state.used_contact_shadows too
+ if (storage->frame.current_rt && true) { //detect with state.used_contact_shadows too
//pre z pass
-
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo);
- glDrawBuffers(0,NULL);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
+ glDrawBuffers(0, NULL);
- glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height);
+ glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
- glColorMask(0,0,0,0);
+ glColorMask(0, 0, 0, 0);
glClearDepth(1.0f);
glClear(GL_DEPTH_BUFFER_BIT);
-
render_list.clear();
- _fill_render_list(p_cull_result,p_cull_count,true);
+ _fill_render_list(p_cull_result, p_cull_count, true);
render_list.sort_by_depth(false);
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,true);
- _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,0,false,false,true,false,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true);
+ _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, 0, false, false, true, false, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false);
- glColorMask(1,1,1,1);
+ glColorMask(1, 1, 1, 1);
if (state.used_contact_shadows) {
@@ -3850,28 +3567,24 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
//bind depth for read
- glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-8);
- glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth);
+ glActiveTexture(GL_TEXTURE0 + storage->config.max_texture_image_units - 8);
+ glBindTexture(GL_TEXTURE_2D, storage->frame.current_rt->depth);
}
- fb_cleared=true;
+ fb_cleared = true;
render_pass++;
}
-
- _setup_lights(p_light_cull_result,p_light_cull_count,p_cam_transform.affine_inverse(),p_cam_projection,p_shadow_atlas);
- _setup_reflections(p_reflection_probe_cull_result,p_reflection_probe_cull_count,p_cam_transform.affine_inverse(),p_cam_projection,p_reflection_atlas,env);
+ _setup_lights(p_light_cull_result, p_light_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_shadow_atlas);
+ _setup_reflections(p_reflection_probe_cull_result, p_reflection_probe_cull_count, p_cam_transform.affine_inverse(), p_cam_projection, p_reflection_atlas, env);
render_list.clear();
+ bool use_mrt = false;
- bool use_mrt=false;
-
-
- _fill_render_list(p_cull_result,p_cull_count,false);
+ _fill_render_list(p_cull_result, p_cull_count, false);
//
-
glEnable(GL_BLEND);
glDepthMask(GL_TRUE);
glEnable(GL_DEPTH_TEST);
@@ -3881,45 +3594,42 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
ReflectionProbeInstance *probe = reflection_probe_instance_owner.getornull(p_reflection_probe);
GLuint current_fbo;
-
-
if (probe) {
ReflectionAtlas *ref_atlas = reflection_atlas_owner.getptr(probe->atlas);
ERR_FAIL_COND(!ref_atlas);
- int target_size=ref_atlas->size/ref_atlas->subdiv;
+ int target_size = ref_atlas->size / ref_atlas->subdiv;
- int cubemap_index=reflection_cubemaps.size()-1;
+ int cubemap_index = reflection_cubemaps.size() - 1;
- for(int i=reflection_cubemaps.size()-1;i>=0;i--) {
+ for (int i = reflection_cubemaps.size() - 1; i >= 0; i--) {
//find appropriate cubemap to render to
- if (reflection_cubemaps[i].size>target_size*2)
+ if (reflection_cubemaps[i].size > target_size * 2)
break;
- cubemap_index=i;
+ cubemap_index = i;
}
- current_fbo=reflection_cubemaps[cubemap_index].fbo_id[p_reflection_probe_pass];
- use_mrt=false;
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false);
+ current_fbo = reflection_cubemaps[cubemap_index].fbo_id[p_reflection_probe_pass];
+ use_mrt = false;
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
- glViewport(0,0,reflection_cubemaps[cubemap_index].size,reflection_cubemaps[cubemap_index].size);
- glBindFramebuffer(GL_FRAMEBUFFER,current_fbo);
+ glViewport(0, 0, reflection_cubemaps[cubemap_index].size, reflection_cubemaps[cubemap_index].size);
+ glBindFramebuffer(GL_FRAMEBUFFER, current_fbo);
} else {
use_mrt = state.used_sss || (env && (env->ssao_enabled || env->ssr_enabled)); //only enable MRT rendering if any of these is enabled
- glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height);
+ glViewport(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height);
if (use_mrt) {
- current_fbo=storage->frame.current_rt->buffers.fbo;
-
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,true);
+ current_fbo = storage->frame.current_rt->buffers.fbo;
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, true);
Vector<GLenum> draw_buffers;
draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
@@ -3928,27 +3638,24 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
if (state.used_sss) {
draw_buffers.push_back(GL_COLOR_ATTACHMENT3);
}
- glDrawBuffers(draw_buffers.size(),draw_buffers.ptr());
+ glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
- Color black(0,0,0,0);
- glClearBufferfv(GL_COLOR,1,black.components); // specular
- glClearBufferfv(GL_COLOR,2,black.components); // normal metal rough
+ Color black(0, 0, 0, 0);
+ glClearBufferfv(GL_COLOR, 1, black.components); // specular
+ glClearBufferfv(GL_COLOR, 2, black.components); // normal metal rough
if (state.used_sss) {
- glClearBufferfv(GL_COLOR,3,black.components); // normal metal rough
+ glClearBufferfv(GL_COLOR, 3, black.components); // normal metal rough
}
} else {
-
-
current_fbo = storage->frame.current_rt->buffers.fbo;
- glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo);
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false);
+ glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
Vector<GLenum> draw_buffers;
draw_buffers.push_back(GL_COLOR_ATTACHMENT0);
- glDrawBuffers(draw_buffers.size(),draw_buffers.ptr());
-
+ glDrawBuffers(draw_buffers.size(), draw_buffers.ptr());
}
}
@@ -3957,41 +3664,39 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
glClear(GL_DEPTH_BUFFER_BIT);
}
- Color clear_color(0,0,0,0);
+ Color clear_color(0, 0, 0, 0);
- RasterizerStorageGLES3::SkyBox *skybox=NULL;
- GLuint env_radiance_tex=0;
+ RasterizerStorageGLES3::SkyBox *skybox = NULL;
+ GLuint env_radiance_tex = 0;
- if (!env || env->bg_mode==VS::ENV_BG_CLEAR_COLOR) {
+ if (!env || env->bg_mode == VS::ENV_BG_CLEAR_COLOR) {
if (storage->frame.clear_request) {
clear_color = storage->frame.clear_request_color.to_linear();
- storage->frame.clear_request=false;
-
+ storage->frame.clear_request = false;
}
- } else if (env->bg_mode==VS::ENV_BG_COLOR) {
+ } else if (env->bg_mode == VS::ENV_BG_COLOR) {
clear_color = env->bg_color.to_linear();
- storage->frame.clear_request=false;
- } else if (env->bg_mode==VS::ENV_BG_SKYBOX) {
+ storage->frame.clear_request = false;
+ } else if (env->bg_mode == VS::ENV_BG_SKYBOX) {
skybox = storage->skybox_owner.getornull(env->skybox);
if (skybox) {
- env_radiance_tex=skybox->radiance;
+ env_radiance_tex = skybox->radiance;
}
- storage->frame.clear_request=false;
+ storage->frame.clear_request = false;
} else {
- storage->frame.clear_request=false;
+ storage->frame.clear_request = false;
}
- glClearBufferfv(GL_COLOR,0,clear_color.components); // specular
-
+ glClearBufferfv(GL_COLOR, 0, clear_color.components); // specular
- state.texscreen_copied=false;
+ state.texscreen_copied = false;
glBlendEquation(GL_FUNC_ADD);
@@ -4011,53 +3716,44 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
-
-
- if (state.directional_light_count==0) {
- directional_light=NULL;
- _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,false,false,false,shadow_atlas!=NULL);
+ if (state.directional_light_count == 0) {
+ directional_light = NULL;
+ _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, false, false, false, shadow_atlas != NULL);
} else {
- for(int i=0;i<state.directional_light_count;i++) {
- directional_light=directional_lights[i];
- if (i>0) {
+ for (int i = 0; i < state.directional_light_count; i++) {
+ directional_light = directional_lights[i];
+ if (i > 0) {
glEnable(GL_BLEND);
}
- _setup_directional_light(i,p_cam_transform.affine_inverse(),shadow_atlas!=NULL);
- _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,false,false,i>0,shadow_atlas!=NULL);
-
+ _setup_directional_light(i, p_cam_transform.affine_inverse(), shadow_atlas != NULL);
+ _render_list(render_list.elements, render_list.element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, false, false, i > 0, shadow_atlas != NULL);
}
}
-
- state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS, false);
if (use_mrt) {
GLenum gldb = GL_COLOR_ATTACHMENT0;
- glDrawBuffers(1,&gldb);
+ glDrawBuffers(1, &gldb);
}
- if (env && env->bg_mode==VS::ENV_BG_SKYBOX) {
+ if (env && env->bg_mode == VS::ENV_BG_SKYBOX) {
/*
if (use_mrt) {
glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); //switch to alpha fbo for skybox, only diffuse/ambient matters
*/
- _draw_skybox(skybox,p_cam_projection,p_cam_transform,storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP],env->skybox_scale);
+ _draw_skybox(skybox, p_cam_projection, p_cam_transform, storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP], env->skybox_scale);
}
-
-
-
-
//_render_list_forward(&alpha_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting,true);
//glColorMask(1,1,1,1);
//state.scene_shader.set_conditional( SceneShaderGLES3::USE_FOG,false);
-
if (use_mrt) {
- _render_mrts(env,p_cam_projection);
+ _render_mrts(env, p_cam_projection);
}
glEnable(GL_BLEND);
@@ -4067,15 +3763,14 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
render_list.sort_by_depth(true);
- if (state.directional_light_count==0) {
- directional_light=NULL;
- _render_list(&render_list.elements[render_list.max_elements-render_list.alpha_element_count],render_list.alpha_element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,true,false,false,shadow_atlas!=NULL);
+ if (state.directional_light_count == 0) {
+ directional_light = NULL;
+ _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, true, false, false, shadow_atlas != NULL);
} else {
- for(int i=0;i<state.directional_light_count;i++) {
- directional_light=directional_lights[i];
- _setup_directional_light(i,p_cam_transform.affine_inverse(),shadow_atlas!=NULL);
- _render_list(&render_list.elements[render_list.max_elements-render_list.alpha_element_count],render_list.alpha_element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,true,false,i>0,shadow_atlas!=NULL);
-
+ for (int i = 0; i < state.directional_light_count; i++) {
+ directional_light = directional_lights[i];
+ _setup_directional_light(i, p_cam_transform.affine_inverse(), shadow_atlas != NULL);
+ _render_list(&render_list.elements[render_list.max_elements - render_list.alpha_element_count], render_list.alpha_element_count, p_cam_transform, p_cam_projection, env_radiance_tex, false, true, false, i > 0, shadow_atlas != NULL);
}
}
@@ -4084,19 +3779,16 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
return;
}
-
- _post_process(env,p_cam_projection);
-
+ _post_process(env, p_cam_projection);
if (false && shadow_atlas) {
//_copy_texture_to_front_buffer(shadow_atlas->depth);
storage->canvas->canvas_begin();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,shadow_atlas->depth);
+ glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
- storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1));
-
+ storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
}
if (false && storage->frame.current_rt) {
@@ -4104,10 +3796,9 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
//_copy_texture_to_front_buffer(shadow_atlas->depth);
storage->canvas->canvas_begin();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,exposure_shrink[4].color);
+ glBindTexture(GL_TEXTURE_2D, exposure_shrink[4].color);
//glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color);
- storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/16,storage->frame.current_rt->height/16),Rect2(0,0,1,1));
-
+ storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 16, storage->frame.current_rt->height / 16), Rect2(0, 0, 1, 1));
}
if (false && reflection_atlas && storage->frame.current_rt) {
@@ -4115,9 +3806,8 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
//_copy_texture_to_front_buffer(shadow_atlas->depth);
storage->canvas->canvas_begin();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,reflection_atlas->color);
- storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1));
-
+ glBindTexture(GL_TEXTURE_2D, reflection_atlas->color);
+ storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
}
if (false && directional_shadow.fbo) {
@@ -4125,10 +3815,9 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
//_copy_texture_to_front_buffer(shadow_atlas->depth);
storage->canvas->canvas_begin();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,directional_shadow.depth);
+ glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
- storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1));
-
+ storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
}
if (false && env_radiance_tex) {
@@ -4136,12 +3825,10 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
//_copy_texture_to_front_buffer(shadow_atlas->depth);
storage->canvas->canvas_begin();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,env_radiance_tex);
- storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1));
-
+ glBindTexture(GL_TEXTURE_2D, env_radiance_tex);
+ storage->canvas->draw_generic_textured_rect(Rect2(0, 0, storage->frame.current_rt->width / 2, storage->frame.current_rt->height / 2), Rect2(0, 0, 1, 1));
}
-
#if 0
if (use_fb) {
@@ -4288,106 +3975,97 @@ void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const C
#endif
}
-void RasterizerSceneGLES3::render_shadow(RID p_light,RID p_shadow_atlas,int p_pass,InstanceBase** p_cull_result,int p_cull_count) {
+void RasterizerSceneGLES3::render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) {
render_pass++;
- directional_light=NULL;
+ directional_light = NULL;
LightInstance *light_instance = light_instance_owner.getornull(p_light);
ERR_FAIL_COND(!light_instance);
RasterizerStorageGLES3::Light *light = storage->light_owner.getornull(light_instance->light);
ERR_FAIL_COND(!light);
- uint32_t x,y,width,height,vp_height;
-
+ uint32_t x, y, width, height, vp_height;
- float dp_direction=0.0;
- float zfar=0;
- bool flip_facing=false;
- int custom_vp_size=0;
+ float dp_direction = 0.0;
+ float zfar = 0;
+ bool flip_facing = false;
+ int custom_vp_size = 0;
GLuint fbo;
- int current_cubemap=-1;
- float bias=0;
- float normal_bias=0;
+ int current_cubemap = -1;
+ float bias = 0;
+ float normal_bias = 0;
CameraMatrix light_projection;
Transform light_transform;
-
- if (light->type==VS::LIGHT_DIRECTIONAL) {
+ if (light->type == VS::LIGHT_DIRECTIONAL) {
//set pssm stuff
- if (light_instance->last_scene_shadow_pass!=scene_pass) {
+ if (light_instance->last_scene_shadow_pass != scene_pass) {
//assign rect if unassigned
light_instance->light_directional_index = directional_shadow.current_light;
- light_instance->last_scene_shadow_pass=scene_pass;
+ light_instance->last_scene_shadow_pass = scene_pass;
directional_shadow.current_light++;
- if (directional_shadow.light_count==1) {
- light_instance->directional_rect=Rect2(0,0,directional_shadow.size,directional_shadow.size);
- } else if (directional_shadow.light_count==2) {
- light_instance->directional_rect=Rect2(0,0,directional_shadow.size,directional_shadow.size/2);
- if (light_instance->light_directional_index==1) {
- light_instance->directional_rect.pos.x+=light_instance->directional_rect.size.x;
+ if (directional_shadow.light_count == 1) {
+ light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size);
+ } else if (directional_shadow.light_count == 2) {
+ light_instance->directional_rect = Rect2(0, 0, directional_shadow.size, directional_shadow.size / 2);
+ if (light_instance->light_directional_index == 1) {
+ light_instance->directional_rect.pos.x += light_instance->directional_rect.size.x;
}
- } else { //3 and 4
- light_instance->directional_rect=Rect2(0,0,directional_shadow.size/2,directional_shadow.size/2);
- if (light_instance->light_directional_index&1) {
- light_instance->directional_rect.pos.x+=light_instance->directional_rect.size.x;
+ } else { //3 and 4
+ light_instance->directional_rect = Rect2(0, 0, directional_shadow.size / 2, directional_shadow.size / 2);
+ if (light_instance->light_directional_index & 1) {
+ light_instance->directional_rect.pos.x += light_instance->directional_rect.size.x;
}
- if (light_instance->light_directional_index/2) {
- light_instance->directional_rect.pos.y+=light_instance->directional_rect.size.y;
+ if (light_instance->light_directional_index / 2) {
+ light_instance->directional_rect.pos.y += light_instance->directional_rect.size.y;
}
}
}
- light_projection=light_instance->shadow_transform[p_pass].camera;
- light_transform=light_instance->shadow_transform[p_pass].transform;
-
- x=light_instance->directional_rect.pos.x;
- y=light_instance->directional_rect.pos.y;
- width=light_instance->directional_rect.size.x;
- height=light_instance->directional_rect.size.y;
-
+ light_projection = light_instance->shadow_transform[p_pass].camera;
+ light_transform = light_instance->shadow_transform[p_pass].transform;
+ x = light_instance->directional_rect.pos.x;
+ y = light_instance->directional_rect.pos.y;
+ width = light_instance->directional_rect.size.x;
+ height = light_instance->directional_rect.size.y;
- if (light->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) {
+ width /= 2;
+ height /= 2;
- width/=2;
- height/=2;
-
- if (p_pass==0) {
-
- } else if (p_pass==1) {
- x+=width;
- } else if (p_pass==2) {
- y+=height;
- } else if (p_pass==3) {
- x+=width;
- y+=height;
+ if (p_pass == 0) {
+ } else if (p_pass == 1) {
+ x += width;
+ } else if (p_pass == 2) {
+ y += height;
+ } else if (p_pass == 3) {
+ x += width;
+ y += height;
}
+ } else if (light->directional_shadow_mode == VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
+ height /= 2;
- } else if (light->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) {
-
- height/=2;
-
- if (p_pass==0) {
+ if (p_pass == 0) {
} else {
- y+=height;
+ y += height;
}
-
}
- zfar=light->param[VS::LIGHT_PARAM_RANGE];
- bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
- normal_bias=light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS];
- fbo=directional_shadow.fbo;
- vp_height=directional_shadow.size;
+ zfar = light->param[VS::LIGHT_PARAM_RANGE];
+ bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
+ normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS];
+ fbo = directional_shadow.fbo;
+ vp_height = directional_shadow.size;
} else {
//set from shadow atlas
@@ -4396,112 +4074,106 @@ void RasterizerSceneGLES3::render_shadow(RID p_light,RID p_shadow_atlas,int p_pa
ERR_FAIL_COND(!shadow_atlas);
ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light));
- fbo=shadow_atlas->fbo;
- vp_height=shadow_atlas->size;
+ fbo = shadow_atlas->fbo;
+ vp_height = shadow_atlas->size;
uint32_t key = shadow_atlas->shadow_owners[p_light];
- uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3;
+ uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK;
- ERR_FAIL_INDEX(shadow,shadow_atlas->quadrants[quadrant].shadows.size());
+ ERR_FAIL_INDEX(shadow, shadow_atlas->quadrants[quadrant].shadows.size());
- uint32_t quadrant_size = shadow_atlas->size>>1;
+ uint32_t quadrant_size = shadow_atlas->size >> 1;
- x=(quadrant&1)*quadrant_size;
- y=(quadrant>>1)*quadrant_size;
+ x = (quadrant & 1) * quadrant_size;
+ y = (quadrant >> 1) * quadrant_size;
uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision);
- x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
- y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
-
- width=shadow_size;
- height=shadow_size;
+ x += (shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
+ y += (shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size;
- if (light->type==VS::LIGHT_OMNI) {
+ width = shadow_size;
+ height = shadow_size;
+ if (light->type == VS::LIGHT_OMNI) {
- if (light->omni_shadow_mode==VS::LIGHT_OMNI_SHADOW_CUBE) {
+ if (light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE) {
- int cubemap_index=shadow_cubemaps.size()-1;
+ int cubemap_index = shadow_cubemaps.size() - 1;
- for(int i=shadow_cubemaps.size()-1;i>=0;i--) {
+ for (int i = shadow_cubemaps.size() - 1; i >= 0; i--) {
//find appropriate cubemap to render to
- if (shadow_cubemaps[i].size>shadow_size*2)
+ if (shadow_cubemaps[i].size > shadow_size * 2)
break;
- cubemap_index=i;
+ cubemap_index = i;
}
- fbo=shadow_cubemaps[cubemap_index].fbo_id[p_pass];
- light_projection=light_instance->shadow_transform[0].camera;
- light_transform=light_instance->shadow_transform[0].transform;
- custom_vp_size=shadow_cubemaps[cubemap_index].size;
- zfar=light->param[VS::LIGHT_PARAM_RANGE];
-
- current_cubemap=cubemap_index;
+ fbo = shadow_cubemaps[cubemap_index].fbo_id[p_pass];
+ light_projection = light_instance->shadow_transform[0].camera;
+ light_transform = light_instance->shadow_transform[0].transform;
+ custom_vp_size = shadow_cubemaps[cubemap_index].size;
+ zfar = light->param[VS::LIGHT_PARAM_RANGE];
+ current_cubemap = cubemap_index;
} else {
- light_projection=light_instance->shadow_transform[0].camera;
- light_transform=light_instance->shadow_transform[0].transform;
+ light_projection = light_instance->shadow_transform[0].camera;
+ light_transform = light_instance->shadow_transform[0].transform;
- if (light->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
+ if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
- height/=2;
- y+=p_pass*height;
+ height /= 2;
+ y += p_pass * height;
} else {
- width/=2;
- x+=p_pass*width;
-
+ width /= 2;
+ x += p_pass * width;
}
- dp_direction = p_pass==0?1.0:-1.0;
+ dp_direction = p_pass == 0 ? 1.0 : -1.0;
flip_facing = (p_pass == 1);
- zfar=light->param[VS::LIGHT_PARAM_RANGE];
- bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
+ zfar = light->param[VS::LIGHT_PARAM_RANGE];
+ bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID,true);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, true);
}
- } else if (light->type==VS::LIGHT_SPOT) {
+ } else if (light->type == VS::LIGHT_SPOT) {
- light_projection=light_instance->shadow_transform[0].camera;
- light_transform=light_instance->shadow_transform[0].transform;
+ light_projection = light_instance->shadow_transform[0].camera;
+ light_transform = light_instance->shadow_transform[0].transform;
dp_direction = 1.0;
flip_facing = false;
- zfar=light->param[VS::LIGHT_PARAM_RANGE];
- bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
- normal_bias=light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS];
+ zfar = light->param[VS::LIGHT_PARAM_RANGE];
+ bias = light->param[VS::LIGHT_PARAM_SHADOW_BIAS];
+ normal_bias = light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS];
}
-
}
//todo hacer que se redibuje cuando corresponde
-
render_list.clear();
- _fill_render_list(p_cull_result,p_cull_count,true);
+ _fill_render_list(p_cull_result, p_cull_count, true);
render_list.sort_by_depth(false); //shadow is front to back for performance
glDisable(GL_BLEND);
glDisable(GL_DITHER);
glEnable(GL_DEPTH_TEST);
- glBindFramebuffer(GL_FRAMEBUFFER,fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glDepthMask(true);
- glColorMask(0,0,0,0);
-
+ glColorMask(0, 0, 0, 0);
if (custom_vp_size) {
- glViewport(0,0,custom_vp_size,custom_vp_size);
- glScissor(0,0,custom_vp_size,custom_vp_size);
+ glViewport(0, 0, custom_vp_size, custom_vp_size);
+ glScissor(0, 0, custom_vp_size, custom_vp_size);
} else {
- glViewport(x,y,width,height);
- glScissor(x,y,width,height);
+ glViewport(x, y, width, height);
+ glScissor(x, y, width, height);
}
glEnable(GL_SCISSOR_TEST);
@@ -4509,54 +4181,53 @@ void RasterizerSceneGLES3::render_shadow(RID p_light,RID p_shadow_atlas,int p_pa
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_SCISSOR_TEST);
- state.ubo_data.shadow_z_offset=bias;
- state.ubo_data.shadow_slope_scale=normal_bias;
- state.ubo_data.shadow_dual_paraboloid_render_side=dp_direction;
- state.ubo_data.shadow_dual_paraboloid_render_zfar=zfar;
-
- _setup_environment(NULL,light_projection,light_transform);
+ state.ubo_data.shadow_z_offset = bias;
+ state.ubo_data.shadow_slope_scale = normal_bias;
+ state.ubo_data.shadow_dual_paraboloid_render_side = dp_direction;
+ state.ubo_data.shadow_dual_paraboloid_render_zfar = zfar;
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,true);
+ _setup_environment(NULL, light_projection, light_transform);
- _render_list(render_list.elements,render_list.element_count,light_transform,light_projection,0,flip_facing,false,true,false,false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, true);
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,false);
- state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID,false);
+ _render_list(render_list.elements, render_list.element_count, light_transform, light_projection, 0, flip_facing, false, true, false, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH, false);
+ state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID, false);
- if (light->type==VS::LIGHT_OMNI && light->omni_shadow_mode==VS::LIGHT_OMNI_SHADOW_CUBE && p_pass==5) {
+ if (light->type == VS::LIGHT_OMNI && light->omni_shadow_mode == VS::LIGHT_OMNI_SHADOW_CUBE && p_pass == 5) {
//convert the chosen cubemap to dual paraboloid!
ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas);
- glBindFramebuffer(GL_FRAMEBUFFER,shadow_atlas->fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo);
state.cube_to_dp_shader.bind();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_CUBE_MAP,shadow_cubemaps[current_cubemap].cubemap);
+ glBindTexture(GL_TEXTURE_CUBE_MAP, shadow_cubemaps[current_cubemap].cubemap);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glDisable(GL_CULL_FACE);
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FLIP,i==1);
- state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_NEAR,light_projection.get_z_near());
- state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FAR,light_projection.get_z_far());
- state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::BIAS,light->param[VS::LIGHT_PARAM_SHADOW_BIAS]);
+ state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FLIP, i == 1);
+ state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_NEAR, light_projection.get_z_near());
+ state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FAR, light_projection.get_z_far());
+ state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::BIAS, light->param[VS::LIGHT_PARAM_SHADOW_BIAS]);
- uint32_t local_width=width,local_height=height;
- uint32_t local_x=x,local_y=y;
- if (light->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
+ uint32_t local_width = width, local_height = height;
+ uint32_t local_x = x, local_y = y;
+ if (light->omni_shadow_detail == VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) {
- local_height/=2;
- local_y+=i*local_height;
+ local_height /= 2;
+ local_y += i * local_height;
} else {
- local_width/=2;
- local_x+=i*local_width;
+ local_width /= 2;
+ local_x += i * local_width;
}
- glViewport(local_x,local_y,local_width,local_height);
- glScissor(local_x,local_y,local_width,local_height);
+ glViewport(local_x, local_y, local_width, local_height);
+ glScissor(local_x, local_y, local_width, local_height);
glEnable(GL_SCISSOR_TEST);
glClearDepth(1.0f);
glClear(GL_DEPTH_BUFFER_BIT);
@@ -4565,53 +4236,47 @@ void RasterizerSceneGLES3::render_shadow(RID p_light,RID p_shadow_atlas,int p_pa
glDisable(GL_BLEND);
_copy_screen();
-
}
-
}
- glColorMask(1,1,1,1);
-
-
+ glColorMask(1, 1, 1, 1);
}
void RasterizerSceneGLES3::set_scene_pass(uint64_t p_pass) {
- scene_pass=p_pass;
+ scene_pass = p_pass;
}
bool RasterizerSceneGLES3::free(RID p_rid) {
if (light_instance_owner.owns(p_rid)) {
-
LightInstance *light_instance = light_instance_owner.getptr(p_rid);
//remove from shadow atlases..
- for(Set<RID>::Element *E=light_instance->shadow_atlases.front();E;E=E->next()) {
+ for (Set<RID>::Element *E = light_instance->shadow_atlases.front(); E; E = E->next()) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(E->get());
ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid));
uint32_t key = shadow_atlas->shadow_owners[p_rid];
- uint32_t q = (key>>ShadowAtlas::QUADRANT_SHIFT)&0x3;
- uint32_t s = key&ShadowAtlas::SHADOW_INDEX_MASK;
+ uint32_t q = (key >> ShadowAtlas::QUADRANT_SHIFT) & 0x3;
+ uint32_t s = key & ShadowAtlas::SHADOW_INDEX_MASK;
- shadow_atlas->quadrants[q].shadows[s].owner=RID();
+ shadow_atlas->quadrants[q].shadows[s].owner = RID();
shadow_atlas->shadow_owners.erase(p_rid);
}
-
light_instance_owner.free(p_rid);
memdelete(light_instance);
} else if (shadow_atlas_owner.owns(p_rid)) {
ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(p_rid);
- shadow_atlas_set_size(p_rid,0);
+ shadow_atlas_set_size(p_rid, 0);
shadow_atlas_owner.free(p_rid);
memdelete(shadow_atlas);
} else if (reflection_atlas_owner.owns(p_rid)) {
ReflectionAtlas *reflection_atlas = reflection_atlas_owner.get(p_rid);
- reflection_atlas_set_size(p_rid,0);
+ reflection_atlas_set_size(p_rid, 0);
reflection_atlas_owner.free(p_rid);
memdelete(reflection_atlas);
} else if (reflection_probe_instance_owner.owns(p_rid)) {
@@ -4626,46 +4291,44 @@ bool RasterizerSceneGLES3::free(RID p_rid) {
return false;
}
-
return true;
-
}
// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html
static _FORCE_INLINE_ float radicalInverse_VdC(uint32_t bits) {
- bits = (bits << 16u) | (bits >> 16u);
- bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
- bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
- bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
- bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
- return float(bits) * 2.3283064365386963e-10f; // / 0x100000000
+ bits = (bits << 16u) | (bits >> 16u);
+ bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
+ bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
+ bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
+ bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
+ return float(bits) * 2.3283064365386963e-10f; // / 0x100000000
}
static _FORCE_INLINE_ Vector2 Hammersley(uint32_t i, uint32_t N) {
- return Vector2(float(i) / float(N), radicalInverse_VdC(i));
+ return Vector2(float(i) / float(N), radicalInverse_VdC(i));
}
static _FORCE_INLINE_ Vector3 ImportanceSampleGGX(Vector2 Xi, float Roughness, Vector3 N) {
- float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph]
-
- // Compute distribution direction
- float Phi = 2.0f * Math_PI * Xi.x;
- float CosTheta = Math::sqrt((float)(1.0f - Xi.y) / (1.0f + (a*a - 1.0f) * Xi.y));
- float SinTheta = Math::sqrt((float)Math::abs(1.0f - CosTheta * CosTheta));
-
- // Convert to spherical direction
- Vector3 H;
- H.x = SinTheta * Math::cos(Phi);
- H.y = SinTheta * Math::sin(Phi);
- H.z = CosTheta;
-
- Vector3 UpVector = Math::abs(N.z) < 0.999 ? Vector3(0.0, 0.0, 1.0) : Vector3(1.0, 0.0, 0.0);
- Vector3 TangentX = UpVector.cross(N);
- TangentX.normalize();
- Vector3 TangentY = N.cross(TangentX);
-
- // Tangent to world space
- return TangentX * H.x + TangentY * H.y + N * H.z;
+ float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph]
+
+ // Compute distribution direction
+ float Phi = 2.0f * Math_PI * Xi.x;
+ float CosTheta = Math::sqrt((float)(1.0f - Xi.y) / (1.0f + (a * a - 1.0f) * Xi.y));
+ float SinTheta = Math::sqrt((float)Math::abs(1.0f - CosTheta * CosTheta));
+
+ // Convert to spherical direction
+ Vector3 H;
+ H.x = SinTheta * Math::cos(Phi);
+ H.y = SinTheta * Math::sin(Phi);
+ H.z = CosTheta;
+
+ Vector3 UpVector = Math::abs(N.z) < 0.999 ? Vector3(0.0, 0.0, 1.0) : Vector3(1.0, 0.0, 0.0);
+ Vector3 TangentX = UpVector.cross(N);
+ TangentX.normalize();
+ Vector3 TangentY = N.cross(TangentX);
+
+ // Tangent to world space
+ return TangentX * H.x + TangentY * H.y + N * H.z;
}
static _FORCE_INLINE_ float GGX(float NdotV, float a) {
@@ -4674,31 +4337,27 @@ static _FORCE_INLINE_ float GGX(float NdotV, float a) {
}
// http://graphicrants.blogspot.com.au/2013/08/specular-brdf-reference.html
-float _FORCE_INLINE_ G_Smith(float a, float nDotV, float nDotL)
-{
+float _FORCE_INLINE_ G_Smith(float a, float nDotV, float nDotL) {
return GGX(nDotL, a * a) * GGX(nDotV, a * a);
}
void RasterizerSceneGLES3::_generate_brdf() {
- int brdf_size=GLOBAL_DEF("rendering/gles3/brdf_texture_size",64);
-
-
+ int brdf_size = GLOBAL_DEF("rendering/gles3/brdf_texture_size", 64);
PoolVector<uint8_t> brdf;
- brdf.resize(brdf_size*brdf_size*2);
+ brdf.resize(brdf_size * brdf_size * 2);
PoolVector<uint8_t>::Write w = brdf.write();
+ for (int i = 0; i < brdf_size; i++) {
+ for (int j = 0; j < brdf_size; j++) {
- for(int i=0;i<brdf_size;i++) {
- for(int j=0;j<brdf_size;j++) {
-
- float Roughness = float(j)/(brdf_size-1);
- float NoV = float(i+1)/(brdf_size); //avoid storing nov0
+ float Roughness = float(j) / (brdf_size - 1);
+ float NoV = float(i + 1) / (brdf_size); //avoid storing nov0
Vector3 V;
- V.x = Math::sqrt( 1.0f - NoV * NoV );
+ V.x = Math::sqrt(1.0f - NoV * NoV);
V.y = 0.0;
V.z = NoV;
@@ -4707,69 +4366,63 @@ void RasterizerSceneGLES3::_generate_brdf() {
float A = 0;
float B = 0;
- for(int s=0;s<512;s++) {
+ for (int s = 0; s < 512; s++) {
+ Vector2 xi = Hammersley(s, 512);
+ Vector3 H = ImportanceSampleGGX(xi, Roughness, N);
+ Vector3 L = 2.0 * V.dot(H) * H - V;
- Vector2 xi = Hammersley(s,512);
- Vector3 H = ImportanceSampleGGX( xi, Roughness, N );
- Vector3 L = 2.0 * V.dot(H) * H - V;
+ float NoL = CLAMP(L.z, 0.0, 1.0);
+ float NoH = CLAMP(H.z, 0.0, 1.0);
+ float VoH = CLAMP(V.dot(H), 0.0, 1.0);
- float NoL = CLAMP( L.z, 0.0, 1.0 );
- float NoH = CLAMP( H.z, 0.0, 1.0 );
- float VoH = CLAMP( V.dot(H), 0.0, 1.0 );
-
- if ( NoL > 0.0 ) {
- float G = G_Smith( Roughness, NoV, NoL );
+ if (NoL > 0.0) {
+ float G = G_Smith(Roughness, NoV, NoL);
float G_Vis = G * VoH / (NoH * NoV);
- float Fc = pow(1.0 - VoH, 5.0);
+ float Fc = pow(1.0 - VoH, 5.0);
A += (1.0 - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
- A/=512.0;
- B/=512.0;
+ A /= 512.0;
+ B /= 512.0;
- int tofs = ((brdf_size-j-1)*brdf_size+i)*2;
- w[tofs+0]=CLAMP(A*255,0,255);
- w[tofs+1]=CLAMP(B*255,0,255);
+ int tofs = ((brdf_size - j - 1) * brdf_size + i) * 2;
+ w[tofs + 0] = CLAMP(A * 255, 0, 255);
+ w[tofs + 1] = CLAMP(B * 255, 0, 255);
}
}
-
//set up brdf texture
-
glGenTextures(1, &state.brdf_texture);
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,state.brdf_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, brdf_size, brdf_size, 0, GL_RG, GL_UNSIGNED_BYTE,w.ptr());
+ glBindTexture(GL_TEXTURE_2D, state.brdf_texture);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, brdf_size, brdf_size, 0, GL_RG, GL_UNSIGNED_BYTE, w.ptr());
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
- glBindTexture(GL_TEXTURE_2D,0);
-
+ glBindTexture(GL_TEXTURE_2D, 0);
}
void RasterizerSceneGLES3::initialize() {
-
- render_pass=0;
+ render_pass = 0;
state.scene_shader.init();
default_shader = storage->shader_create(VS::SHADER_SPATIAL);
default_material = storage->material_create();
- storage->material_set_shader(default_material,default_shader);
+ storage->material_set_shader(default_material, default_shader);
default_shader_twosided = storage->shader_create(VS::SHADER_SPATIAL);
default_material_twosided = storage->material_create();
- storage->shader_set_code(default_shader_twosided,"render_mode cull_disabled;\n");
- storage->material_set_shader(default_material_twosided,default_shader_twosided);
-
+ storage->shader_set_code(default_shader_twosided, "render_mode cull_disabled;\n");
+ storage->material_set_shader(default_material_twosided, default_shader_twosided);
glGenBuffers(1, &state.scene_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo);
@@ -4781,61 +4434,53 @@ void RasterizerSceneGLES3::initialize() {
glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_ubo, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
-
- render_list.max_elements=GLOBAL_DEF("rendering/gles3/max_renderable_elements",(int)RenderList::DEFAULT_MAX_ELEMENTS);
- if (render_list.max_elements>1000000)
- render_list.max_elements=1000000;
- if (render_list.max_elements<1024)
- render_list.max_elements=1024;
-
-
+ render_list.max_elements = GLOBAL_DEF("rendering/gles3/max_renderable_elements", (int)RenderList::DEFAULT_MAX_ELEMENTS);
+ if (render_list.max_elements > 1000000)
+ render_list.max_elements = 1000000;
+ if (render_list.max_elements < 1024)
+ render_list.max_elements = 1024;
{
//quad buffers
- glGenBuffers(1,&state.skybox_verts);
- glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts);
- glBufferData(GL_ARRAY_BUFFER,sizeof(Vector3)*8,NULL,GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &state.skybox_verts);
+ glBindBuffer(GL_ARRAY_BUFFER, state.skybox_verts);
+ glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, NULL, GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
-
- glGenVertexArrays(1,&state.skybox_array);
+ glGenVertexArrays(1, &state.skybox_array);
glBindVertexArray(state.skybox_array);
- glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts);
- glVertexAttribPointer(VS::ARRAY_VERTEX,3,GL_FLOAT,GL_FALSE,sizeof(Vector3)*2,0);
+ glBindBuffer(GL_ARRAY_BUFFER, state.skybox_verts);
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, 0);
glEnableVertexAttribArray(VS::ARRAY_VERTEX);
- glVertexAttribPointer(VS::ARRAY_TEX_UV,3,GL_FLOAT,GL_FALSE,sizeof(Vector3)*2,((uint8_t*)NULL)+sizeof(Vector3));
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3) * 2, ((uint8_t *)NULL) + sizeof(Vector3));
glEnableVertexAttribArray(VS::ARRAY_TEX_UV);
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
}
render_list.init();
state.cube_to_dp_shader.init();
_generate_brdf();
- shadow_atlas_realloc_tolerance_msec=500;
-
-
+ shadow_atlas_realloc_tolerance_msec = 500;
-
-
- int max_shadow_cubemap_sampler_size=512;
+ int max_shadow_cubemap_sampler_size = 512;
int cube_size = max_shadow_cubemap_sampler_size;
glActiveTexture(GL_TEXTURE0);
- while(cube_size>=32) {
+ while (cube_size >= 32) {
ShadowCubeMap cube;
- cube.size=cube_size;
+ cube.size = cube_size;
- glGenTextures(1,&cube.cubemap);
- glBindTexture(GL_TEXTURE_CUBE_MAP,cube.cubemap);
+ glGenTextures(1, &cube.cubemap);
+ glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap);
//gen cubemap first
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
- glTexImage2D(_cube_side_enum[i], 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ glTexImage2D(_cube_side_enum[i], 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
@@ -4846,38 +4491,38 @@ void RasterizerSceneGLES3::initialize() {
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
//gen renderbuffers second, because it needs a complete cubemap
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glGenFramebuffers(1, &cube.fbo_id[i]);
glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,_cube_side_enum[i], cube.cubemap, 0);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _cube_side_enum[i], cube.cubemap, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
}
shadow_cubemaps.push_back(cube);
- cube_size>>=1;
+ cube_size >>= 1;
}
{
//directional light shadow
- directional_shadow.light_count=0;
- directional_shadow.size=nearest_power_of_2(GLOBAL_DEF("rendering/shadows/directional_shadow_size",2048));
- glGenFramebuffers(1,&directional_shadow.fbo);
- glBindFramebuffer(GL_FRAMEBUFFER,directional_shadow.fbo);
- glGenTextures(1,&directional_shadow.depth);
- glBindTexture(GL_TEXTURE_2D,directional_shadow.depth);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ directional_shadow.light_count = 0;
+ directional_shadow.size = nearest_power_of_2(GLOBAL_DEF("rendering/shadows/directional_shadow_size", 2048));
+ glGenFramebuffers(1, &directional_shadow.fbo);
+ glBindFramebuffer(GL_FRAMEBUFFER, directional_shadow.fbo);
+ glGenTextures(1, &directional_shadow.depth);
+ glBindTexture(GL_TEXTURE_2D, directional_shadow.depth);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, directional_shadow.depth, 0);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, directional_shadow.depth, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- if (status!=GL_FRAMEBUFFER_COMPLETE) {
+ if (status != GL_FRAMEBUFFER_COMPLETE) {
ERR_PRINT("Directional shadow framebuffer status invalid");
}
}
@@ -4886,24 +4531,23 @@ void RasterizerSceneGLES3::initialize() {
//spot and omni ubos
int max_ubo_size;
- glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE,&max_ubo_size);
- const int ubo_light_size=160;
- state.ubo_light_size=ubo_light_size;
- state.max_ubo_lights=MIN(RenderList::MAX_LIGHTS,max_ubo_size/ubo_light_size);
- print_line("max ubo light: "+itos(state.max_ubo_lights));
-
- state.spot_array_tmp = (uint8_t*)memalloc(ubo_light_size*state.max_ubo_lights);
- state.omni_array_tmp = (uint8_t*)memalloc(ubo_light_size*state.max_ubo_lights);
+ glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &max_ubo_size);
+ const int ubo_light_size = 160;
+ state.ubo_light_size = ubo_light_size;
+ state.max_ubo_lights = MIN(RenderList::MAX_LIGHTS, max_ubo_size / ubo_light_size);
+ print_line("max ubo light: " + itos(state.max_ubo_lights));
+ state.spot_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights);
+ state.omni_array_tmp = (uint8_t *)memalloc(ubo_light_size * state.max_ubo_lights);
glGenBuffers(1, &state.spot_array_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo);
- glBufferData(GL_UNIFORM_BUFFER, ubo_light_size*state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
+ glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glGenBuffers(1, &state.omni_array_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo);
- glBufferData(GL_UNIFORM_BUFFER, ubo_light_size*state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
+ glBufferData(GL_UNIFORM_BUFFER, ubo_light_size * state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
glGenBuffers(1, &state.directional_ubo);
@@ -4911,67 +4555,63 @@ void RasterizerSceneGLES3::initialize() {
glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
- state.max_forward_lights_per_object=8;
+ state.max_forward_lights_per_object = 8;
+ state.scene_shader.add_custom_define("#define MAX_LIGHT_DATA_STRUCTS " + itos(state.max_ubo_lights) + "\n");
+ state.scene_shader.add_custom_define("#define MAX_FORWARD_LIGHTS " + itos(state.max_forward_lights_per_object) + "\n");
- state.scene_shader.add_custom_define("#define MAX_LIGHT_DATA_STRUCTS "+itos(state.max_ubo_lights)+"\n");
- state.scene_shader.add_custom_define("#define MAX_FORWARD_LIGHTS "+itos(state.max_forward_lights_per_object)+"\n");
+ state.max_ubo_reflections = MIN(RenderList::MAX_REFLECTIONS, max_ubo_size / sizeof(ReflectionProbeDataUBO));
+ print_line("max ubo reflections: " + itos(state.max_ubo_reflections) + " ubo size: " + itos(sizeof(ReflectionProbeDataUBO)));
- state.max_ubo_reflections=MIN(RenderList::MAX_REFLECTIONS,max_ubo_size/sizeof(ReflectionProbeDataUBO));
- print_line("max ubo reflections: "+itos(state.max_ubo_reflections)+" ubo size: "+itos(sizeof(ReflectionProbeDataUBO)));
-
- state.reflection_array_tmp = (uint8_t*)memalloc(sizeof(ReflectionProbeDataUBO)*state.max_ubo_reflections);
+ state.reflection_array_tmp = (uint8_t *)memalloc(sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections);
glGenBuffers(1, &state.reflection_array_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo);
- glBufferData(GL_UNIFORM_BUFFER, sizeof(ReflectionProbeDataUBO)*state.max_ubo_reflections, NULL, GL_DYNAMIC_DRAW);
+ glBufferData(GL_UNIFORM_BUFFER, sizeof(ReflectionProbeDataUBO) * state.max_ubo_reflections, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
- state.scene_shader.add_custom_define("#define MAX_REFLECTION_DATA_STRUCTS "+itos(state.max_ubo_reflections)+"\n");
-
- state.max_skeleton_bones=MIN(2048,max_ubo_size/(12*sizeof(float)));
- state.scene_shader.add_custom_define("#define MAX_SKELETON_BONES "+itos(state.max_skeleton_bones)+"\n");
-
+ state.scene_shader.add_custom_define("#define MAX_REFLECTION_DATA_STRUCTS " + itos(state.max_ubo_reflections) + "\n");
+ state.max_skeleton_bones = MIN(2048, max_ubo_size / (12 * sizeof(float)));
+ state.scene_shader.add_custom_define("#define MAX_SKELETON_BONES " + itos(state.max_skeleton_bones) + "\n");
}
- GLOBAL_DEF("rendering/gles3/shadow_filter_mode",1);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/shadow_filter_mode",PropertyInfo(Variant::INT,"rendering/gles3/shadow_filter_mode",PROPERTY_HINT_ENUM,"Disabled,PCF5,PCF13"));
- shadow_filter_mode=SHADOW_FILTER_NEAREST;
+ GLOBAL_DEF("rendering/gles3/shadow_filter_mode", 1);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/shadow_filter_mode", PropertyInfo(Variant::INT, "rendering/gles3/shadow_filter_mode", PROPERTY_HINT_ENUM, "Disabled,PCF5,PCF13"));
+ shadow_filter_mode = SHADOW_FILTER_NEAREST;
{ //reflection cubemaps
- int max_reflection_cubemap_sampler_size=512;
+ int max_reflection_cubemap_sampler_size = 512;
int cube_size = max_reflection_cubemap_sampler_size;
glActiveTexture(GL_TEXTURE0);
- bool use_float=true;
+ bool use_float = true;
- GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2;
+ GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
GLenum format = GL_RGBA;
- GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV;
+ GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
- while(cube_size>=32) {
+ while (cube_size >= 32) {
ReflectionCubeMap cube;
- cube.size=cube_size;
+ cube.size = cube_size;
- glGenTextures(1,&cube.depth);
- glBindTexture(GL_TEXTURE_2D,cube.depth);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ glGenTextures(1, &cube.depth);
+ glBindTexture(GL_TEXTURE_2D, cube.depth);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
- glGenTextures(1,&cube.cubemap);
- glBindTexture(GL_TEXTURE_CUBE_MAP,cube.cubemap);
+ glGenTextures(1, &cube.cubemap);
+ glBindTexture(GL_TEXTURE_CUBE_MAP, cube.cubemap);
//gen cubemap first
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
- glTexImage2D(_cube_side_enum[i], 0, internal_format, cube.size, cube.size, 0, format, type, NULL);
+ glTexImage2D(_cube_side_enum[i], 0, internal_format, cube.size, cube.size, 0, format, type, NULL);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
@@ -4982,41 +4622,37 @@ void RasterizerSceneGLES3::initialize() {
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
//gen renderbuffers second, because it needs a complete cubemap
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glGenFramebuffers(1, &cube.fbo_id[i]);
glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,_cube_side_enum[i], cube.cubemap, 0);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, cube.depth, 0);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], cube.cubemap, 0);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, cube.depth, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
}
reflection_cubemaps.push_back(cube);
- cube_size>>=1;
+ cube_size >>= 1;
}
}
{
-
- uint32_t immediate_buffer_size=GLOBAL_DEF("rendering/buffers/immediate_buffer_size_kb",2048);
+ uint32_t immediate_buffer_size = GLOBAL_DEF("rendering/buffers/immediate_buffer_size_kb", 2048);
glGenBuffers(1, &state.immediate_buffer);
glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer);
- glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size*1024, NULL, GL_DYNAMIC_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size * 1024, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
- glGenVertexArrays(1,&state.immediate_array);
-
-
-
+ glGenVertexArrays(1, &state.immediate_array);
}
#ifdef GLES_OVER_GL
-//"desktop" opengl needs this.
+ //"desktop" opengl needs this.
glEnable(GL_PROGRAM_POINT_SIZE);
#endif
@@ -5031,23 +4667,20 @@ void RasterizerSceneGLES3::initialize() {
state.exposure_shader.init();
state.tonemap_shader.init();
-
{
- GLOBAL_DEF("rendering/ssurf_scattering/quality",1);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/quality",PropertyInfo(Variant::INT,"rendering/ssurf_scattering/quality",PROPERTY_HINT_ENUM,"Low,Medium,High"));
- GLOBAL_DEF("rendering/ssurf_scattering/max_size",1.0);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/max_size",PropertyInfo(Variant::INT,"rendering/ssurf_scattering/max_size",PROPERTY_HINT_RANGE,"0.01,8,0.01"));
- GLOBAL_DEF("rendering/ssurf_scattering/follow_surface",false);
-
- GLOBAL_DEF("rendering/reflections/high_quality_vct_gi",true);
-
+ GLOBAL_DEF("rendering/ssurf_scattering/quality", 1);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/quality", PropertyInfo(Variant::INT, "rendering/ssurf_scattering/quality", PROPERTY_HINT_ENUM, "Low,Medium,High"));
+ GLOBAL_DEF("rendering/ssurf_scattering/max_size", 1.0);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/max_size", PropertyInfo(Variant::INT, "rendering/ssurf_scattering/max_size", PROPERTY_HINT_RANGE, "0.01,8,0.01"));
+ GLOBAL_DEF("rendering/ssurf_scattering/follow_surface", false);
+ GLOBAL_DEF("rendering/reflections/high_quality_vct_gi", true);
}
- exposure_shrink_size=243;
- int max_exposure_shrink_size=exposure_shrink_size;
+ exposure_shrink_size = 243;
+ int max_exposure_shrink_size = exposure_shrink_size;
- while(max_exposure_shrink_size>0) {
+ while (max_exposure_shrink_size > 0) {
RasterizerStorageGLES3::RenderTarget::Exposure e;
@@ -5056,41 +4689,33 @@ void RasterizerSceneGLES3::initialize() {
glGenTextures(1, &e.color);
glBindTexture(GL_TEXTURE_2D, e.color);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_FLOAT, NULL);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, e.color, 0);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_FLOAT, NULL);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, e.color, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
exposure_shrink.push_back(e);
- max_exposure_shrink_size/=3;
+ max_exposure_shrink_size /= 3;
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
-
-
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
}
-
}
void RasterizerSceneGLES3::iteration() {
- shadow_filter_mode=ShadowFilterMode(int(GlobalConfig::get_singleton()->get("rendering/gles3/shadow_filter_mode")));
- subsurface_scatter_follow_surface=GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/follow_surface");
- subsurface_scatter_quality=SubSurfaceScatterQuality(int(GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/quality")));
- subsurface_scatter_size=GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/max_size");
-
+ shadow_filter_mode = ShadowFilterMode(int(GlobalConfig::get_singleton()->get("rendering/gles3/shadow_filter_mode")));
+ subsurface_scatter_follow_surface = GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/follow_surface");
+ subsurface_scatter_quality = SubSurfaceScatterQuality(int(GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/quality")));
+ subsurface_scatter_size = GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/max_size");
- state.scene_shader.set_conditional(SceneShaderGLES3::VCT_QUALITY_HIGH,GlobalConfig::get_singleton()->get("rendering/reflections/high_quality_vct_gi"));
+ state.scene_shader.set_conditional(SceneShaderGLES3::VCT_QUALITY_HIGH, GlobalConfig::get_singleton()->get("rendering/reflections/high_quality_vct_gi"));
}
-void RasterizerSceneGLES3::finalize(){
-
-
+void RasterizerSceneGLES3::finalize() {
}
-
-RasterizerSceneGLES3::RasterizerSceneGLES3()
-{
+RasterizerSceneGLES3::RasterizerSceneGLES3() {
}
diff --git a/drivers/gles3/rasterizer_scene_gles3.h b/drivers/gles3/rasterizer_scene_gles3.h
index b21ef8317f..417a1d8500 100644
--- a/drivers/gles3/rasterizer_scene_gles3.h
+++ b/drivers/gles3/rasterizer_scene_gles3.h
@@ -29,29 +29,27 @@
#ifndef RASTERIZERSCENEGLES3_H
#define RASTERIZERSCENEGLES3_H
-#include "rasterizer_storage_gles3.h"
-#include "drivers/gles3/shaders/scene.glsl.h"
#include "drivers/gles3/shaders/cube_to_dp.glsl.h"
+#include "drivers/gles3/shaders/effect_blur.glsl.h"
+#include "drivers/gles3/shaders/exposure.glsl.h"
#include "drivers/gles3/shaders/resolve.glsl.h"
+#include "drivers/gles3/shaders/scene.glsl.h"
#include "drivers/gles3/shaders/screen_space_reflection.glsl.h"
-#include "drivers/gles3/shaders/effect_blur.glsl.h"
-#include "drivers/gles3/shaders/subsurf_scattering.glsl.h"
-#include "drivers/gles3/shaders/ssao_minify.glsl.h"
#include "drivers/gles3/shaders/ssao.glsl.h"
#include "drivers/gles3/shaders/ssao_blur.glsl.h"
-#include "drivers/gles3/shaders/exposure.glsl.h"
+#include "drivers/gles3/shaders/ssao_minify.glsl.h"
+#include "drivers/gles3/shaders/subsurf_scattering.glsl.h"
#include "drivers/gles3/shaders/tonemap.glsl.h"
+#include "rasterizer_storage_gles3.h"
class RasterizerSceneGLES3 : public RasterizerScene {
public:
-
enum ShadowFilterMode {
SHADOW_FILTER_NEAREST,
SHADOW_FILTER_PCF5,
SHADOW_FILTER_PCF13,
};
-
ShadowFilterMode shadow_filter_mode;
uint64_t shadow_atlas_realloc_tolerance_msec;
@@ -83,8 +81,6 @@ public:
struct State {
-
-
bool texscreen_copied;
int current_blend_mode;
float current_line_width;
@@ -104,7 +100,6 @@ public:
ExposureShaderGLES3 exposure_shader;
TonemapShaderGLES3 tonemap_shader;
-
struct SceneDataUBO {
float projection_matrix[16];
@@ -167,7 +162,6 @@ public:
bool used_contact_shadows;
-
int spot_light_count;
int omni_light_count;
int directional_light_count;
@@ -178,15 +172,14 @@ public:
} state;
-
/* SHADOW ATLAS API */
struct ShadowAtlas : public RID_Data {
enum {
- QUADRANT_SHIFT=27,
- SHADOW_INDEX_MASK=(1<<QUADRANT_SHIFT)-1,
- SHADOW_INVALID=0xFFFFFFFF
+ QUADRANT_SHIFT = 27,
+ SHADOW_INDEX_MASK = (1 << QUADRANT_SHIFT) - 1,
+ SHADOW_INVALID = 0xFFFFFFFF
};
struct Quadrant {
@@ -199,15 +192,15 @@ public:
uint64_t alloc_tick;
Shadow() {
- version=0;
- alloc_tick=0;
+ version = 0;
+ alloc_tick = 0;
}
};
Vector<Shadow> shadows;
Quadrant() {
- subdivision=0; //not in use
+ subdivision = 0; //not in use
}
} quadrants[4];
@@ -220,7 +213,7 @@ public:
GLuint fbo;
GLuint depth;
- Map<RID,uint32_t> shadow_owners;
+ Map<RID, uint32_t> shadow_owners;
};
struct ShadowCubeMap {
@@ -235,10 +228,10 @@ public:
RID_Owner<ShadowAtlas> shadow_atlas_owner;
RID shadow_atlas_create();
- void shadow_atlas_set_size(RID p_atlas,int p_size);
- void shadow_atlas_set_quadrant_subdivision(RID p_atlas,int p_quadrant,int p_subdivision);
+ void shadow_atlas_set_size(RID p_atlas, int p_size);
+ void shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision);
bool _shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas, int *p_in_quadrants, int p_quadrant_count, int p_current_subdiv, uint64_t p_tick, int &r_quadrant, int &r_shadow);
- bool shadow_atlas_update_light(RID p_atlas,RID p_light_intance,float p_coverage,uint64_t p_light_version);
+ bool shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version);
struct DirectionalShadow {
GLuint fbo;
@@ -272,8 +265,8 @@ public:
mutable RID_Owner<ReflectionAtlas> reflection_atlas_owner;
virtual RID reflection_atlas_create();
- virtual void reflection_atlas_set_size(RID p_ref_atlas,int p_size);
- virtual void reflection_atlas_set_subdivision(RID p_ref_atlas,int p_subdiv);
+ virtual void reflection_atlas_set_size(RID p_ref_atlas, int p_size);
+ virtual void reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv);
/* REFLECTION CUBEMAPS */
@@ -300,8 +293,6 @@ public:
int render_step;
-
-
uint64_t last_pass;
int reflection_index;
@@ -319,20 +310,16 @@ public:
//notes: for ambientblend, use distance to edge to blend between already existing global environment
};
-
mutable RID_Owner<ReflectionProbeInstance> reflection_probe_instance_owner;
virtual RID reflection_probe_instance_create(RID p_probe);
- virtual void reflection_probe_instance_set_transform(RID p_instance,const Transform& p_transform);
+ virtual void reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform);
virtual void reflection_probe_release_atlas_index(RID p_instance);
virtual bool reflection_probe_instance_needs_redraw(RID p_instance);
virtual bool reflection_probe_instance_has_reflection(RID p_instance);
virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas);
virtual bool reflection_probe_instance_postprocess_step(RID p_instance);
-
-
-
/* ENVIRONMENT API */
struct Environment : public RID_Data {
@@ -360,7 +347,6 @@ public:
bool ssr_smooth;
bool ssr_roughness;
-
bool ssao_enabled;
float ssao_intensity;
float ssao_radius;
@@ -403,62 +389,61 @@ public:
VS::EnvironmentDOFBlurQuality dof_blur_near_quality;
Environment() {
- bg_mode=VS::ENV_BG_CLEAR_COLOR;
- skybox_scale=1.0;
- bg_energy=1.0;
- skybox_ambient=0;
- ambient_energy=1.0;
- ambient_skybox_contribution=0.0;
- canvas_max_layer=0;
-
- ssr_enabled=false;
- ssr_max_steps=64;
- ssr_accel=0.04;
- ssr_fade=2.0;
- ssr_depth_tolerance=0.2;
- ssr_smooth=true;
- ssr_roughness=true;
-
- ssao_enabled=false;
- ssao_intensity=1.0;
- ssao_radius=1.0;
- ssao_intensity2=1.0;
- ssao_radius2=0.0;
- ssao_bias=0.01;
- ssao_light_affect=0;
- ssao_filter=true;
-
- tone_mapper=VS::ENV_TONE_MAPPER_LINEAR;
- tone_mapper_exposure=1.0;
- tone_mapper_exposure_white=1.0;
- auto_exposure=false;
- auto_exposure_speed=0.5;
- auto_exposure_min=0.05;
- auto_exposure_max=8;
- auto_exposure_grey=0.4;
-
- glow_enabled=false;
- glow_levels=(1<<2)|(1<<4);
- glow_intensity=0.8;
- glow_strength=1.0;
- glow_bloom=0.0;
- glow_blend_mode=VS::GLOW_BLEND_MODE_SOFTLIGHT;
- glow_hdr_bleed_treshold=1.0;
- glow_hdr_bleed_scale=2.0;
- glow_bicubic_upscale=false;
-
- dof_blur_far_enabled=false;
- dof_blur_far_distance=10;
- dof_blur_far_transition=5;
- dof_blur_far_amount=0.1;
- dof_blur_far_quality=VS::ENV_DOF_BLUR_QUALITY_MEDIUM;
-
- dof_blur_near_enabled=false;
- dof_blur_near_distance=2;
- dof_blur_near_transition=1;
- dof_blur_near_amount=0.1;
- dof_blur_near_quality=VS::ENV_DOF_BLUR_QUALITY_MEDIUM;
-
+ bg_mode = VS::ENV_BG_CLEAR_COLOR;
+ skybox_scale = 1.0;
+ bg_energy = 1.0;
+ skybox_ambient = 0;
+ ambient_energy = 1.0;
+ ambient_skybox_contribution = 0.0;
+ canvas_max_layer = 0;
+
+ ssr_enabled = false;
+ ssr_max_steps = 64;
+ ssr_accel = 0.04;
+ ssr_fade = 2.0;
+ ssr_depth_tolerance = 0.2;
+ ssr_smooth = true;
+ ssr_roughness = true;
+
+ ssao_enabled = false;
+ ssao_intensity = 1.0;
+ ssao_radius = 1.0;
+ ssao_intensity2 = 1.0;
+ ssao_radius2 = 0.0;
+ ssao_bias = 0.01;
+ ssao_light_affect = 0;
+ ssao_filter = true;
+
+ tone_mapper = VS::ENV_TONE_MAPPER_LINEAR;
+ tone_mapper_exposure = 1.0;
+ tone_mapper_exposure_white = 1.0;
+ auto_exposure = false;
+ auto_exposure_speed = 0.5;
+ auto_exposure_min = 0.05;
+ auto_exposure_max = 8;
+ auto_exposure_grey = 0.4;
+
+ glow_enabled = false;
+ glow_levels = (1 << 2) | (1 << 4);
+ glow_intensity = 0.8;
+ glow_strength = 1.0;
+ glow_bloom = 0.0;
+ glow_blend_mode = VS::GLOW_BLEND_MODE_SOFTLIGHT;
+ glow_hdr_bleed_treshold = 1.0;
+ glow_hdr_bleed_scale = 2.0;
+ glow_bicubic_upscale = false;
+
+ dof_blur_far_enabled = false;
+ dof_blur_far_distance = 10;
+ dof_blur_far_transition = 5;
+ dof_blur_far_amount = 0.1;
+ dof_blur_far_quality = VS::ENV_DOF_BLUR_QUALITY_MEDIUM;
+
+ dof_blur_near_enabled = false;
+ dof_blur_near_distance = 2;
+ dof_blur_near_transition = 1;
+ dof_blur_near_amount = 0.1;
+ dof_blur_near_quality = VS::ENV_DOF_BLUR_QUALITY_MEDIUM;
}
};
@@ -466,27 +451,25 @@ public:
virtual RID environment_create();
- virtual void environment_set_background(RID p_env,VS::EnvironmentBG p_bg);
- virtual void environment_set_skybox(RID p_env,RID p_skybox);
- virtual void environment_set_skybox_scale(RID p_env,float p_scale);
- virtual void environment_set_bg_color(RID p_env,const Color& p_color);
- virtual void environment_set_bg_energy(RID p_env,float p_energy);
- virtual void environment_set_canvas_max_layer(RID p_env,int p_max_layer);
- virtual void environment_set_ambient_light(RID p_env,const Color& p_color,float p_energy=1.0,float p_skybox_contribution=0.0);
+ virtual void environment_set_background(RID p_env, VS::EnvironmentBG p_bg);
+ virtual void environment_set_skybox(RID p_env, RID p_skybox);
+ virtual void environment_set_skybox_scale(RID p_env, float p_scale);
+ virtual void environment_set_bg_color(RID p_env, const Color &p_color);
+ virtual void environment_set_bg_energy(RID p_env, float p_energy);
+ virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer);
+ virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_skybox_contribution = 0.0);
- virtual void environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality);
- virtual void environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality);
- virtual void environment_set_glow(RID p_env,bool p_enable,int p_level_flags,float p_intensity,float p_strength,float p_bloom_treshold,VS::EnvironmentGlowBlendMode p_blend_mode,float p_hdr_bleed_treshold,float p_hdr_bleed_scale,bool p_bicubic_upscale);
- virtual void environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture);
+ virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality);
+ virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality);
+ virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale);
+ virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture);
- virtual void environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness);
- virtual void environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_radius2, float p_intensity2, float p_intensity, float p_bias, float p_light_affect,const Color &p_color,bool p_blur);
+ virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness);
+ virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_radius2, float p_intensity2, float p_intensity, float p_bias, float p_light_affect, const Color &p_color, bool p_blur);
+ virtual void environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale);
- virtual void environment_set_tonemap(RID p_env,VS::EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_scale);
-
- virtual void environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp);
-
+ virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp);
/* LIGHT INSTANCE */
@@ -503,7 +486,6 @@ public:
float shadow_matrix3[16];
float shadow_matrix4[16];
float shadow_split_offsets[4];
-
};
struct LightInstance : public RID_Data {
@@ -516,8 +498,6 @@ public:
float split;
};
-
-
ShadowTransform shadow_transform[4];
RID self;
@@ -542,18 +522,16 @@ public:
Rect2 directional_rect;
-
Set<RID> shadow_atlases; //shadow atlases where this light is registered
- LightInstance() { }
-
+ LightInstance() {}
};
mutable RID_Owner<LightInstance> light_instance_owner;
virtual RID light_instance_create(RID p_light);
- virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform);
- virtual void light_instance_set_shadow_transform(RID p_light_instance,const CameraMatrix& p_projection,const Transform& p_transform,float p_far,float p_split,int p_pass);
+ virtual void light_instance_set_transform(RID p_light_instance, const Transform &p_transform);
+ virtual void light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass);
virtual void light_instance_mark_visible(RID p_light_instance);
/* REFLECTION INSTANCE */
@@ -566,42 +544,42 @@ public:
Vector3 bounds;
Transform transform_to_data;
- GIProbeInstance() { probe=NULL; tex_cache=0; }
+ GIProbeInstance() {
+ probe = NULL;
+ tex_cache = 0;
+ }
};
-
-
mutable RID_Owner<GIProbeInstance> gi_probe_instance_owner;
virtual RID gi_probe_instance_create();
- virtual void gi_probe_instance_set_light_data(RID p_probe,RID p_base,RID p_data);
- virtual void gi_probe_instance_set_transform_to_data(RID p_probe,const Transform& p_xform);
- virtual void gi_probe_instance_set_bounds(RID p_probe,const Vector3& p_bounds);
+ virtual void gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data);
+ virtual void gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform);
+ virtual void gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds);
/* RENDER LIST */
struct RenderList {
enum {
- DEFAULT_MAX_ELEMENTS=65536,
- SORT_FLAG_SKELETON=1,
- SORT_FLAG_INSTANCING=2,
- MAX_DIRECTIONAL_LIGHTS=16,
- MAX_LIGHTS=4096,
- MAX_REFLECTIONS=1024,
-
-
- SORT_KEY_DEPTH_LAYER_SHIFT=60,
- SORT_KEY_UNSHADED_FLAG=uint64_t(1)<<59,
- SORT_KEY_NO_DIRECTIONAL_FLAG=uint64_t(1)<<58,
- SORT_KEY_GI_PROBES_FLAG=uint64_t(1)<<57,
- SORT_KEY_SHADING_SHIFT=57,
- SORT_KEY_SHADING_MASK=7,
- SORT_KEY_MATERIAL_INDEX_SHIFT=40,
- SORT_KEY_GEOMETRY_INDEX_SHIFT=20,
- SORT_KEY_GEOMETRY_TYPE_SHIFT=15,
- SORT_KEY_SKELETON_FLAG=2,
- SORT_KEY_MIRROR_FLAG=1
+ DEFAULT_MAX_ELEMENTS = 65536,
+ SORT_FLAG_SKELETON = 1,
+ SORT_FLAG_INSTANCING = 2,
+ MAX_DIRECTIONAL_LIGHTS = 16,
+ MAX_LIGHTS = 4096,
+ MAX_REFLECTIONS = 1024,
+
+ SORT_KEY_DEPTH_LAYER_SHIFT = 60,
+ SORT_KEY_UNSHADED_FLAG = uint64_t(1) << 59,
+ SORT_KEY_NO_DIRECTIONAL_FLAG = uint64_t(1) << 58,
+ SORT_KEY_GI_PROBES_FLAG = uint64_t(1) << 57,
+ SORT_KEY_SHADING_SHIFT = 57,
+ SORT_KEY_SHADING_MASK = 7,
+ SORT_KEY_MATERIAL_INDEX_SHIFT = 40,
+ SORT_KEY_GEOMETRY_INDEX_SHIFT = 20,
+ SORT_KEY_GEOMETRY_TYPE_SHIFT = 15,
+ SORT_KEY_SKELETON_FLAG = 2,
+ SORT_KEY_MIRROR_FLAG = 1
};
@@ -614,74 +592,70 @@ public:
RasterizerStorageGLES3::Material *material;
RasterizerStorageGLES3::GeometryOwner *owner;
uint64_t sort_key;
-
};
-
Element *_elements;
Element **elements;
int element_count;
int alpha_element_count;
-
void clear() {
- element_count=0;
- alpha_element_count=0;
+ element_count = 0;
+ alpha_element_count = 0;
}
//should eventually be replaced by radix
struct SortByKey {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
return A->sort_key < B->sort_key;
}
};
void sort_by_key(bool p_alpha) {
- SortArray<Element*,SortByKey> sorter;
+ SortArray<Element *, SortByKey> sorter;
if (p_alpha) {
- sorter.sort(&elements[max_elements-alpha_element_count],alpha_element_count);
+ sorter.sort(&elements[max_elements - alpha_element_count], alpha_element_count);
} else {
- sorter.sort(elements,element_count);
+ sorter.sort(elements, element_count);
}
}
struct SortByDepth {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
return A->instance->depth > B->instance->depth;
}
};
void sort_by_depth(bool p_alpha) {
- SortArray<Element*,SortByDepth> sorter;
+ SortArray<Element *, SortByDepth> sorter;
if (p_alpha) {
- sorter.sort(&elements[max_elements-alpha_element_count],alpha_element_count);
+ sorter.sort(&elements[max_elements - alpha_element_count], alpha_element_count);
} else {
- sorter.sort(elements,element_count);
+ sorter.sort(elements, element_count);
}
}
+ _FORCE_INLINE_ Element *add_element() {
- _FORCE_INLINE_ Element* add_element() {
-
- if (element_count+alpha_element_count>=max_elements)
+ if (element_count + alpha_element_count >= max_elements)
return NULL;
- elements[element_count]=&_elements[element_count];
+ elements[element_count] = &_elements[element_count];
return elements[element_count++];
}
- _FORCE_INLINE_ Element* add_alpha_element() {
+ _FORCE_INLINE_ Element *add_alpha_element() {
- if (element_count+alpha_element_count>=max_elements)
+ if (element_count + alpha_element_count >= max_elements)
return NULL;
- int idx = max_elements-alpha_element_count-1;
- elements[idx]=&_elements[idx];
+ int idx = max_elements - alpha_element_count - 1;
+ elements[idx] = &_elements[idx];
alpha_element_count++;
return elements[idx];
}
@@ -689,18 +663,16 @@ public:
void init() {
element_count = 0;
- alpha_element_count =0;
- elements=memnew_arr(Element*,max_elements);
- _elements=memnew_arr(Element,max_elements);
- for (int i=0;i<max_elements;i++)
- elements[i]=&_elements[i]; // assign elements
-
+ alpha_element_count = 0;
+ elements = memnew_arr(Element *, max_elements);
+ _elements = memnew_arr(Element, max_elements);
+ for (int i = 0; i < max_elements; i++)
+ elements[i] = &_elements[i]; // assign elements
}
-
RenderList() {
- max_elements=DEFAULT_MAX_ELEMENTS;
+ max_elements = DEFAULT_MAX_ELEMENTS;
}
~RenderList() {
@@ -709,45 +681,41 @@ public:
}
};
-
LightInstance *directional_light;
LightInstance *directional_lights[RenderList::MAX_DIRECTIONAL_LIGHTS];
-
-
RenderList render_list;
- _FORCE_INLINE_ void _set_cull(bool p_front,bool p_reverse_cull);
+ _FORCE_INLINE_ void _set_cull(bool p_front, bool p_reverse_cull);
- _FORCE_INLINE_ bool _setup_material(RasterizerStorageGLES3::Material* p_material,bool p_alpha_pass);
- _FORCE_INLINE_ void _setup_transform(InstanceBase *p_instance,const Transform& p_view_transform,const CameraMatrix& p_projection);
+ _FORCE_INLINE_ bool _setup_material(RasterizerStorageGLES3::Material *p_material, bool p_alpha_pass);
+ _FORCE_INLINE_ void _setup_transform(InstanceBase *p_instance, const Transform &p_view_transform, const CameraMatrix &p_projection);
_FORCE_INLINE_ void _setup_geometry(RenderList::Element *e);
_FORCE_INLINE_ void _render_geometry(RenderList::Element *e);
- _FORCE_INLINE_ void _setup_light(RenderList::Element *e,const Transform& p_view_transform);
-
- void _render_list(RenderList::Element **p_elements, int p_element_count, const Transform& p_view_transform, const CameraMatrix& p_projection, GLuint p_base_env, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow, bool p_directional_add, bool p_directional_shadows);
+ _FORCE_INLINE_ void _setup_light(RenderList::Element *e, const Transform &p_view_transform);
+ void _render_list(RenderList::Element **p_elements, int p_element_count, const Transform &p_view_transform, const CameraMatrix &p_projection, GLuint p_base_env, bool p_reverse_cull, bool p_alpha_pass, bool p_shadow, bool p_directional_add, bool p_directional_shadows);
- _FORCE_INLINE_ void _add_geometry( RasterizerStorageGLES3::Geometry* p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner,int p_material,bool p_shadow);
+ _FORCE_INLINE_ void _add_geometry(RasterizerStorageGLES3::Geometry *p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner, int p_material, bool p_shadow);
- void _draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox, const CameraMatrix& p_projection, const Transform& p_transform, bool p_vflip, float p_scale);
+ void _draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox, const CameraMatrix &p_projection, const Transform &p_transform, bool p_vflip, float p_scale);
- void _setup_environment(Environment *env, const CameraMatrix &p_cam_projection, const Transform& p_cam_transform);
+ void _setup_environment(Environment *env, const CameraMatrix &p_cam_projection, const Transform &p_cam_transform);
void _setup_directional_light(int p_index, const Transform &p_camera_inverse_transformm, bool p_use_shadows);
- void _setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix& p_camera_projection, RID p_shadow_atlas);
- void _setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform& p_camera_inverse_transform, const CameraMatrix& p_camera_projection, RID p_reflection_atlas, Environment *p_env);
+ void _setup_lights(RID *p_light_cull_result, int p_light_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_shadow_atlas);
+ void _setup_reflections(RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, const Transform &p_camera_inverse_transform, const CameraMatrix &p_camera_projection, RID p_reflection_atlas, Environment *p_env);
void _copy_screen();
void _copy_to_front_buffer(Environment *env);
void _copy_texture_to_front_buffer(GLuint p_texture); //used for debug
- void _fill_render_list(InstanceBase** p_cull_result,int p_cull_count,bool p_shadow);
+ void _fill_render_list(InstanceBase **p_cull_result, int p_cull_count, bool p_shadow);
void _render_mrts(Environment *env, const CameraMatrix &p_cam_projection);
void _post_process(Environment *env, const CameraMatrix &p_cam_projection);
- virtual void render_scene(const Transform& p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_ortogonal,InstanceBase** p_cull_result,int p_cull_count,RID* p_light_cull_result,int p_light_cull_count,RID* p_reflection_probe_cull_result,int p_reflection_probe_cull_count,RID p_environment,RID p_shadow_atlas,RID p_reflection_atlas,RID p_reflection_probe,int p_reflection_probe_pass);
- virtual void render_shadow(RID p_light,RID p_shadow_atlas,int p_pass,InstanceBase** p_cull_result,int p_cull_count);
+ virtual void render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass);
+ virtual void render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count);
virtual bool free(RID p_rid);
void _generate_brdf();
diff --git a/drivers/gles3/rasterizer_storage_gles3.cpp b/drivers/gles3/rasterizer_storage_gles3.cpp
index 4fea28ddb7..ed4be1cb3d 100644
--- a/drivers/gles3/rasterizer_storage_gles3.cpp
+++ b/drivers/gles3/rasterizer_storage_gles3.cpp
@@ -27,32 +27,30 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "rasterizer_storage_gles3.h"
+#include "global_config.h"
#include "rasterizer_canvas_gles3.h"
#include "rasterizer_scene_gles3.h"
-#include "global_config.h"
/* TEXTURE API */
-#define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
-#define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
-#define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
-#define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
-
-#define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
-#define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
-#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
-#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
+#define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
+#define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
+#define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
+#define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
+#define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54
+#define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55
+#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56
+#define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57
#define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
#define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
#define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
-#define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
-#define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
-#define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
-#define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
-
+#define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70
+#define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71
+#define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72
+#define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73
#define _EXT_COMPRESSED_RED_RGTC1_EXT 0x8DBB
#define _EXT_COMPRESSED_RED_RGTC1 0x8DBB
@@ -62,33 +60,27 @@
#define _EXT_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC
#define _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD
#define _EXT_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE
-#define _EXT_ETC1_RGB8_OES 0x8D64
-
-
-
-#define _EXT_SLUMINANCE_NV 0x8C46
-#define _EXT_SLUMINANCE_ALPHA_NV 0x8C44
-#define _EXT_SRGB8_NV 0x8C41
-#define _EXT_SLUMINANCE8_NV 0x8C47
-#define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45
+#define _EXT_ETC1_RGB8_OES 0x8D64
+#define _EXT_SLUMINANCE_NV 0x8C46
+#define _EXT_SLUMINANCE_ALPHA_NV 0x8C44
+#define _EXT_SRGB8_NV 0x8C41
+#define _EXT_SLUMINANCE8_NV 0x8C47
+#define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45
-#define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
-#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
+#define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E
+#define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F
+#define _EXT_ATC_RGB_AMD 0x8C92
+#define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
+#define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
+#define _EXT_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
-#define _EXT_ATC_RGB_AMD 0x8C92
-#define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
-#define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
-
-
-#define _EXT_TEXTURE_CUBE_MAP_SEAMLESS 0x884F
-
-#define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
-#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
+#define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
#define _EXT_COMPRESSED_R11_EAC 0x9270
#define _EXT_COMPRESSED_SIGNED_R11_EAC 0x9271
@@ -108,235 +100,221 @@
GLuint RasterizerStorageGLES3::system_fbo = 0;
-Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,GLenum& r_gl_internal_format,GLenum &r_gl_type,bool &r_compressed,bool &srgb) {
-
+Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image &p_image, Image::Format p_format, uint32_t p_flags, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_gl_type, bool &r_compressed, bool &srgb) {
- r_compressed=false;
- r_gl_format=0;
- Image image=p_image;
- srgb=false;
+ r_compressed = false;
+ r_gl_format = 0;
+ Image image = p_image;
+ srgb = false;
- bool need_decompress=false;
+ bool need_decompress = false;
- switch(p_format) {
+ switch (p_format) {
case Image::FORMAT_L8: {
#ifdef GLES_OVER_GL
- r_gl_internal_format=GL_R8;
- r_gl_format=GL_RED;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_R8;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_UNSIGNED_BYTE;
#else
- r_gl_internal_format=GL_LUMINANCE;
- r_gl_format=GL_LUMINANCE;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_LUMINANCE;
+ r_gl_format = GL_LUMINANCE;
+ r_gl_type = GL_UNSIGNED_BYTE;
#endif
} break;
case Image::FORMAT_LA8: {
#ifdef GLES_OVER_GL
- r_gl_internal_format=GL_RG8;
- r_gl_format=GL_RG;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_RG8;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_UNSIGNED_BYTE;
#else
- r_gl_internal_format=GL_LUMINANCE_ALPHA;
- r_gl_format=GL_LUMINANCE_ALPHA;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_LUMINANCE_ALPHA;
+ r_gl_format = GL_LUMINANCE_ALPHA;
+ r_gl_type = GL_UNSIGNED_BYTE;
#endif
} break;
case Image::FORMAT_R8: {
- r_gl_internal_format=GL_R8;
- r_gl_format=GL_RED;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_R8;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_UNSIGNED_BYTE;
} break;
case Image::FORMAT_RG8: {
- r_gl_internal_format=GL_RG8;
- r_gl_format=GL_RG;
- r_gl_type=GL_UNSIGNED_BYTE;
+ r_gl_internal_format = GL_RG8;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_UNSIGNED_BYTE;
} break;
case Image::FORMAT_RGB8: {
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8:GL_RGB8;
- r_gl_format=GL_RGB;
- r_gl_type=GL_UNSIGNED_BYTE;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? GL_SRGB8 : GL_RGB8;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ srgb = true;
} break;
case Image::FORMAT_RGBA8: {
- r_gl_format=GL_RGBA;
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8_ALPHA8:GL_RGBA8;
- r_gl_type=GL_UNSIGNED_BYTE;
- srgb=true;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? GL_SRGB8_ALPHA8 : GL_RGBA8;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ srgb = true;
} break;
case Image::FORMAT_RGB565: {
#ifndef GLES_OVER_GL
- r_gl_internal_format=GL_RGB565;
+ r_gl_internal_format = GL_RGB565;
#else
-//#warning TODO: Convert tod 555 if 565 is not supported (GLES3.3-)
- r_gl_internal_format=GL_RGB5;
+ //#warning TODO: Convert tod 555 if 565 is not supported (GLES3.3-)
+ r_gl_internal_format = GL_RGB5;
#endif
//r_gl_internal_format=GL_RGB565;
- r_gl_format=GL_RGB;
- r_gl_type=GL_UNSIGNED_SHORT_5_6_5;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_UNSIGNED_SHORT_5_6_5;
} break;
case Image::FORMAT_RGBA4444: {
- r_gl_internal_format=GL_RGBA4;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_SHORT_4_4_4_4;
+ r_gl_internal_format = GL_RGBA4;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_SHORT_4_4_4_4;
} break;
case Image::FORMAT_RGBA5551: {
- r_gl_internal_format=GL_RGB5_A1;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_SHORT_5_5_5_1;
-
+ r_gl_internal_format = GL_RGB5_A1;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_SHORT_5_5_5_1;
} break;
case Image::FORMAT_RF: {
-
- r_gl_internal_format=GL_R32F;
- r_gl_format=GL_RED;
- r_gl_type=GL_FLOAT;
+ r_gl_internal_format = GL_R32F;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_FLOAT;
} break;
case Image::FORMAT_RGF: {
- r_gl_internal_format=GL_RG32F;
- r_gl_format=GL_RG;
- r_gl_type=GL_FLOAT;
+ r_gl_internal_format = GL_RG32F;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_FLOAT;
} break;
case Image::FORMAT_RGBF: {
- r_gl_internal_format=GL_RGB32F;
- r_gl_format=GL_RGB;
- r_gl_type=GL_FLOAT;
+ r_gl_internal_format = GL_RGB32F;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_FLOAT;
} break;
case Image::FORMAT_RGBAF: {
- r_gl_internal_format=GL_RGBA32F;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_FLOAT;
+ r_gl_internal_format = GL_RGBA32F;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_FLOAT;
} break;
case Image::FORMAT_RH: {
- r_gl_internal_format=GL_R32F;
- r_gl_format=GL_RED;
- r_gl_type=GL_HALF_FLOAT;
+ r_gl_internal_format = GL_R32F;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_HALF_FLOAT;
} break;
case Image::FORMAT_RGH: {
- r_gl_internal_format=GL_RG32F;
- r_gl_format=GL_RG;
- r_gl_type=GL_HALF_FLOAT;
+ r_gl_internal_format = GL_RG32F;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_HALF_FLOAT;
} break;
case Image::FORMAT_RGBH: {
- r_gl_internal_format=GL_RGB32F;
- r_gl_format=GL_RGB;
- r_gl_type=GL_HALF_FLOAT;
+ r_gl_internal_format = GL_RGB32F;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_HALF_FLOAT;
} break;
case Image::FORMAT_RGBAH: {
- r_gl_internal_format=GL_RGBA32F;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_HALF_FLOAT;
+ r_gl_internal_format = GL_RGBA32F;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_HALF_FLOAT;
} break;
case Image::FORMAT_DXT1: {
if (config.s3tc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_S3TC_DXT1_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
} break;
case Image::FORMAT_DXT3: {
-
if (config.s3tc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
} break;
case Image::FORMAT_DXT5: {
if (config.s3tc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV : _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
} break;
case Image::FORMAT_ATI1: {
if (config.latc_supported) {
-
- r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_LATC1_EXT;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = _EXT_COMPRESSED_LUMINANCE_LATC1_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
-
} break;
case Image::FORMAT_ATI2: {
if (config.latc_supported) {
-
- r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
@@ -344,93 +322,86 @@ Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Ima
if (config.bptc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM:_EXT_COMPRESSED_RGBA_BPTC_UNORM;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM : _EXT_COMPRESSED_RGBA_BPTC_UNORM;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_BPTC_RGBF: {
if (config.bptc_supported) {
-
- r_gl_internal_format=_EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
- r_gl_format=GL_RGB;
- r_gl_type=GL_FLOAT;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_FLOAT;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_BPTC_RGBFU: {
if (config.bptc_supported) {
-
- r_gl_internal_format=_EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
- r_gl_format=GL_RGB;
- r_gl_type=GL_FLOAT;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_FLOAT;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_PVRTC2: {
if (config.pvrtc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_PVRTC2A: {
if (config.pvrtc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
} break;
case Image::FORMAT_PVRTC4: {
if (config.pvrtc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
@@ -438,32 +409,30 @@ Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Ima
if (config.pvrtc_supported) {
-
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT : _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
-
} break;
case Image::FORMAT_ETC: {
if (config.etc_supported) {
- r_gl_internal_format=_EXT_ETC1_RGB8_OES;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_ETC1_RGB8_OES;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
@@ -471,102 +440,99 @@ Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Ima
if (config.etc2_supported) {
- r_gl_internal_format=_EXT_COMPRESSED_R11_EAC;
- r_gl_format=GL_RED;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_R11_EAC;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_R11S: {
if (config.etc2_supported) {
- r_gl_internal_format=_EXT_COMPRESSED_SIGNED_R11_EAC;
- r_gl_format=GL_RED;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_SIGNED_R11_EAC;
+ r_gl_format = GL_RED;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_RG11: {
if (config.etc2_supported) {
- r_gl_internal_format=_EXT_COMPRESSED_RG11_EAC;
- r_gl_format=GL_RG;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_RG11_EAC;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_RG11S: {
if (config.etc2_supported) {
- r_gl_internal_format=_EXT_COMPRESSED_SIGNED_RG11_EAC;
- r_gl_format=GL_RG;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
+ r_gl_internal_format = _EXT_COMPRESSED_SIGNED_RG11_EAC;
+ r_gl_format = GL_RG;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_RGB8: {
if (config.etc2_supported) {
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_ETC2:_EXT_COMPRESSED_RGB8_ETC2;
- r_gl_format=GL_RGB;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
-
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB8_ETC2 : _EXT_COMPRESSED_RGB8_ETC2;
+ r_gl_format = GL_RGB;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_RGBA8: {
if (config.etc2_supported) {
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:_EXT_COMPRESSED_RGBA8_ETC2_EAC;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
-
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : _EXT_COMPRESSED_RGBA8_ETC2_EAC;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
case Image::FORMAT_ETC2_RGB8A1: {
if (config.etc2_supported) {
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:_EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
- r_gl_format=GL_RGBA;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=true;
- srgb=true;
-
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? _EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : _EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
+ r_gl_format = GL_RGBA;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = true;
+ srgb = true;
} else {
- need_decompress=true;
+ need_decompress = true;
}
} break;
default: {
@@ -579,26 +545,23 @@ Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Ima
if (!image.empty()) {
image.decompress();
- ERR_FAIL_COND_V(image.is_compressed(),image);
+ ERR_FAIL_COND_V(image.is_compressed(), image);
image.convert(Image::FORMAT_RGBA8);
}
-
- r_gl_format=GL_RGBA;
- r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8_ALPHA8:GL_RGBA8;
- r_gl_type=GL_UNSIGNED_BYTE;
- r_compressed=false;
- srgb=true;
+ r_gl_format = GL_RGBA;
+ r_gl_internal_format = (config.srgb_decode_supported || p_flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) ? GL_SRGB8_ALPHA8 : GL_RGBA8;
+ r_gl_type = GL_UNSIGNED_BYTE;
+ r_compressed = false;
+ srgb = true;
return image;
-
}
-
return image;
}
-static const GLenum _cube_side_enum[6]={
+static const GLenum _cube_side_enum[6] = {
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
@@ -612,16 +575,15 @@ static const GLenum _cube_side_enum[6]={
RID RasterizerStorageGLES3::texture_create() {
Texture *texture = memnew(Texture);
- ERR_FAIL_COND_V(!texture,RID());
+ ERR_FAIL_COND_V(!texture, RID());
glGenTextures(1, &texture->tex_id);
- texture->active=false;
- texture->total_data_size=0;
-
- return texture_owner.make_rid( texture );
+ texture->active = false;
+ texture->total_data_size = 0;
+ return texture_owner.make_rid(texture);
}
-void RasterizerStorageGLES3::texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags) {
+void RasterizerStorageGLES3::texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags) {
int components;
GLenum format;
@@ -631,56 +593,52 @@ void RasterizerStorageGLES3::texture_allocate(RID p_texture,int p_width, int p_h
bool compressed;
bool srgb;
- if (p_flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
- p_flags&=~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video
+ if (p_flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
+ p_flags &= ~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video
}
-
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->width=p_width;
- texture->height=p_height;
- texture->format=p_format;
- texture->flags=p_flags;
- texture->stored_cube_sides=0;
+ texture->width = p_width;
+ texture->height = p_height;
+ texture->format = p_format;
+ texture->flags = p_flags;
+ texture->stored_cube_sides = 0;
texture->target = (p_flags & VS::TEXTURE_FLAG_CUBEMAP) ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
- _get_gl_image_and_format(Image(),texture->format,texture->flags,format,internal_format,type,compressed,srgb);
+ _get_gl_image_and_format(Image(), texture->format, texture->flags, format, internal_format, type, compressed, srgb);
texture->alloc_width = texture->width;
texture->alloc_height = texture->height;
-
- texture->gl_format_cache=format;
- texture->gl_type_cache=type;
- texture->gl_internal_format_cache=internal_format;
- texture->compressed=compressed;
- texture->srgb=srgb;
- texture->data_size=0;
- texture->mipmaps=1;
-
+ texture->gl_format_cache = format;
+ texture->gl_type_cache = type;
+ texture->gl_internal_format_cache = internal_format;
+ texture->compressed = compressed;
+ texture->srgb = srgb;
+ texture->data_size = 0;
+ texture->mipmaps = 1;
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
-
- if (p_flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
+ if (p_flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
//prealloc if video
- glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, type,NULL);
+ glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, type, NULL);
}
- texture->active=true;
+ texture->active = true;
}
-void RasterizerStorageGLES3::texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side) {
+void RasterizerStorageGLES3::texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side) {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(!texture->active);
ERR_FAIL_COND(texture->render_target);
- ERR_FAIL_COND(texture->format != p_image.get_format() );
- ERR_FAIL_COND( p_image.empty() );
+ ERR_FAIL_COND(texture->format != p_image.get_format());
+ ERR_FAIL_COND(p_image.empty());
GLenum type;
GLenum format;
@@ -688,32 +646,29 @@ void RasterizerStorageGLES3::texture_set_data(RID p_texture,const Image& p_image
bool compressed;
bool srgb;
-
- if (config.keep_original_textures && !(texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
- texture->images[p_cube_side]=p_image;
+ if (config.keep_original_textures && !(texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
+ texture->images[p_cube_side] = p_image;
}
- Image img = _get_gl_image_and_format(p_image, p_image.get_format(),texture->flags,format,internal_format,type,compressed,srgb);
+ Image img = _get_gl_image_and_format(p_image, p_image.get_format(), texture->flags, format, internal_format, type, compressed, srgb);
- if (config.shrink_textures_x2 && (p_image.has_mipmaps() || !p_image.is_compressed()) && !(texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
+ if (config.shrink_textures_x2 && (p_image.has_mipmaps() || !p_image.is_compressed()) && !(texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING)) {
- texture->alloc_height = MAX(1,texture->alloc_height/2);
- texture->alloc_width = MAX(1,texture->alloc_width/2);
+ texture->alloc_height = MAX(1, texture->alloc_height / 2);
+ texture->alloc_width = MAX(1, texture->alloc_width / 2);
- if (texture->alloc_width == img.get_width()/2 && texture->alloc_height == img.get_height()/2) {
+ if (texture->alloc_width == img.get_width() / 2 && texture->alloc_height == img.get_height() / 2) {
img.shrink_x2();
} else if (img.get_format() <= Image::FORMAT_RGB565) {
img.resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR);
-
}
};
+ GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP) ? _cube_side_enum[p_cube_side] : GL_TEXTURE_2D;
- GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP)?_cube_side_enum[p_cube_side]:GL_TEXTURE_2D;
-
- texture->data_size=img.get_data().size();
+ texture->data_size = img.get_data().size();
PoolVector<uint8_t>::Read read = img.get_data().read();
glActiveTexture(GL_TEXTURE0);
@@ -721,87 +676,83 @@ void RasterizerStorageGLES3::texture_set_data(RID p_texture,const Image& p_image
texture->ignore_mipmaps = compressed && !img.has_mipmaps();
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps)
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,config.use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR);
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps)
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
else {
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
-
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
-
if (config.srgb_decode_supported && srgb) {
- if (texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ if (texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
- texture->using_srgb=true;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
+ texture->using_srgb = true;
} else {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT);
- texture->using_srgb=false;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
+ texture->using_srgb = false;
}
}
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
}
- if ((texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
+ if ((texture->flags & VS::TEXTURE_FLAG_REPEAT || texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
- if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
- }
- else{
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
+ } else {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
- //set swizle for older format compatibility
+//set swizle for older format compatibility
#ifdef GLES_OVER_GL
- switch(texture->format) {
+ switch (texture->format) {
case Image::FORMAT_L8: {
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_ONE);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ONE);
} break;
case Image::FORMAT_LA8: {
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_GREEN);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
} break;
default: {
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_GREEN);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_BLUE);
- glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_ALPHA);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_R, GL_RED);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
+ glTexParameteri(texture->target, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
} break;
-
}
#endif
if (config.use_anisotropic_filter) {
- if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level);
} else {
@@ -809,72 +760,66 @@ void RasterizerStorageGLES3::texture_set_data(RID p_texture,const Image& p_image
}
}
- int mipmaps= (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && img.has_mipmaps()) ? img.get_mipmap_count() +1: 1;
-
+ int mipmaps = (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && img.has_mipmaps()) ? img.get_mipmap_count() + 1 : 1;
- int w=img.get_width();
- int h=img.get_height();
+ int w = img.get_width();
+ int h = img.get_height();
- int tsize=0;
- for(int i=0;i<mipmaps;i++) {
+ int tsize = 0;
+ for (int i = 0; i < mipmaps; i++) {
- int size,ofs;
- img.get_mipmap_offset_and_size(i,ofs,size);
+ int size, ofs;
+ img.get_mipmap_offset_and_size(i, ofs, size);
//print_line("mipmap: "+itos(i)+" size: "+itos(size)+" w: "+itos(mm_w)+", h: "+itos(mm_h));
if (texture->compressed) {
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
- glCompressedTexImage2D( blit_target, i, internal_format,w,h,0,size,&read[ofs] );
+ glCompressedTexImage2D(blit_target, i, internal_format, w, h, 0, size, &read[ofs]);
} else {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- if (texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
- glTexSubImage2D( blit_target, i, 0,0,w, h,format,type,&read[ofs] );
+ if (texture->flags & VS::TEXTURE_FLAG_USED_FOR_STREAMING) {
+ glTexSubImage2D(blit_target, i, 0, 0, w, h, format, type, &read[ofs]);
} else {
- glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type,&read[ofs]);
+ glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type, &read[ofs]);
}
-
}
- tsize+=size;
-
- w = MAX(1,w>>1);
- h = MAX(1,h>>1);
+ tsize += size;
+ w = MAX(1, w >> 1);
+ h = MAX(1, h >> 1);
}
- info.texture_mem-=texture->total_data_size;
- texture->total_data_size=tsize;
- info.texture_mem+=texture->total_data_size;
+ info.texture_mem -= texture->total_data_size;
+ texture->total_data_size = tsize;
+ info.texture_mem += texture->total_data_size;
//printf("texture: %i x %i - size: %i - total: %i\n",texture->width,texture->height,tsize,_rinfo.texture_mem);
- texture->stored_cube_sides|=(1<<p_cube_side);
+ texture->stored_cube_sides |= (1 << p_cube_side);
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && mipmaps==1 && !texture->ignore_mipmaps && (!(texture->flags&VS::TEXTURE_FLAG_CUBEMAP) || texture->stored_cube_sides==(1<<6)-1)) {
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && mipmaps == 1 && !texture->ignore_mipmaps && (!(texture->flags & VS::TEXTURE_FLAG_CUBEMAP) || texture->stored_cube_sides == (1 << 6) - 1)) {
//generate mipmaps if they were requested and the image does not contain them
glGenerateMipmap(texture->target);
- } else if (mipmaps>1) {
+ } else if (mipmaps > 1) {
glTexParameteri(texture->target, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, mipmaps-1);
-
+ glTexParameteri(texture->target, GL_TEXTURE_MAX_LEVEL, mipmaps - 1);
}
- texture->mipmaps=mipmaps;
+ texture->mipmaps = mipmaps;
//texture_set_flags(p_texture,texture->flags);
-
-
}
-Image RasterizerStorageGLES3::texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side) const {
+Image RasterizerStorageGLES3::texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,Image());
- ERR_FAIL_COND_V(!texture->active,Image());
- ERR_FAIL_COND_V(texture->data_size==0,Image());
- ERR_FAIL_COND_V(texture->render_target,Image());
+ ERR_FAIL_COND_V(!texture, Image());
+ ERR_FAIL_COND_V(!texture->active, Image());
+ ERR_FAIL_COND_V(texture->data_size == 0, Image());
+ ERR_FAIL_COND_V(texture->render_target, Image());
if (!texture->images[p_cube_side].empty())
return texture->images[p_cube_side];
@@ -883,46 +828,44 @@ Image RasterizerStorageGLES3::texture_get_data(RID p_texture,VS::CubeMapSide p_c
PoolVector<uint8_t> data;
- int data_size = Image::get_image_data_size(texture->alloc_width,texture->alloc_height,texture->format,texture->mipmaps>1?-1:0);
+ int data_size = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, texture->format, texture->mipmaps > 1 ? -1 : 0);
- data.resize(data_size*2); //add some memory at the end, just in case for buggy drivers
+ data.resize(data_size * 2); //add some memory at the end, just in case for buggy drivers
PoolVector<uint8_t>::Write wb = data.write();
glActiveTexture(GL_TEXTURE0);
- glBindTexture(texture->target,texture->tex_id);
+ glBindTexture(texture->target, texture->tex_id);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
- print_line("GET FORMAT: "+Image::get_format_name(texture->format)+" mipmaps: "+itos(texture->mipmaps));
-
+ print_line("GET FORMAT: " + Image::get_format_name(texture->format) + " mipmaps: " + itos(texture->mipmaps));
- for(int i=0;i<texture->mipmaps;i++) {
+ for (int i = 0; i < texture->mipmaps; i++) {
- int ofs=0;
- if (i>0) {
- ofs=Image::get_image_data_size(texture->alloc_width,texture->alloc_height,texture->format,i-1);
+ int ofs = 0;
+ if (i > 0) {
+ ofs = Image::get_image_data_size(texture->alloc_width, texture->alloc_height, texture->format, i - 1);
}
if (texture->compressed) {
glPixelStorei(GL_PACK_ALIGNMENT, 4);
- glGetCompressedTexImage(texture->target,i,&wb[ofs]);
+ glGetCompressedTexImage(texture->target, i, &wb[ofs]);
} else {
glPixelStorei(GL_PACK_ALIGNMENT, 1);
- glGetTexImage(texture->target,i,texture->gl_format_cache,texture->gl_type_cache,&wb[ofs]);
+ glGetTexImage(texture->target, i, texture->gl_format_cache, texture->gl_type_cache, &wb[ofs]);
}
}
-
- wb=PoolVector<uint8_t>::Write();
+ wb = PoolVector<uint8_t>::Write();
data.resize(data_size);
- Image img(texture->alloc_width,texture->alloc_height,texture->mipmaps>1?true:false,texture->format,data);
+ Image img(texture->alloc_width, texture->alloc_height, texture->mipmaps > 1 ? true : false, texture->format, data);
return img;
#else
@@ -932,44 +875,40 @@ Image RasterizerStorageGLES3::texture_get_data(RID p_texture,VS::CubeMapSide p_c
#endif
}
-void RasterizerStorageGLES3::texture_set_flags(RID p_texture,uint32_t p_flags) {
+void RasterizerStorageGLES3::texture_set_flags(RID p_texture, uint32_t p_flags) {
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
if (texture->render_target) {
- p_flags&=VS::TEXTURE_FLAG_FILTER;//can change only filter
+ p_flags &= VS::TEXTURE_FLAG_FILTER; //can change only filter
}
- bool had_mipmaps = texture->flags&VS::TEXTURE_FLAG_MIPMAPS;
+ bool had_mipmaps = texture->flags & VS::TEXTURE_FLAG_MIPMAPS;
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
uint32_t cube = texture->flags & VS::TEXTURE_FLAG_CUBEMAP;
- texture->flags=p_flags|cube; // can't remove a cube from being a cube
+ texture->flags = p_flags | cube; // can't remove a cube from being a cube
+ if ((texture->flags & VS::TEXTURE_FLAG_REPEAT || texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
- if ((texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) {
-
- if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
- }
- else {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ if (texture->flags & VS::TEXTURE_FLAG_MIRRORED_REPEAT) {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
+ } else {
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
-
if (config.use_anisotropic_filter) {
- if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) {
glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level);
} else {
@@ -977,278 +916,256 @@ void RasterizerStorageGLES3::texture_set_flags(RID p_texture,uint32_t p_flags) {
}
}
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) {
- if (!had_mipmaps && texture->mipmaps==1) {
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) {
+ if (!had_mipmaps && texture->mipmaps == 1) {
glGenerateMipmap(texture->target);
}
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,config.use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR);
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, config.use_fast_texture_filter ? GL_LINEAR_MIPMAP_NEAREST : GL_LINEAR_MIPMAP_LINEAR);
- } else{
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
+ } else {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
-
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
-
if (config.srgb_decode_supported && texture->srgb) {
- if (texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
+ if (texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
- texture->using_srgb=true;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
+ texture->using_srgb = true;
} else {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT);
- texture->using_srgb=false;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _SKIP_DECODE_EXT);
+ texture->using_srgb = false;
}
}
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // raw Filtering
}
-
}
uint32_t RasterizerStorageGLES3::texture_get_flags(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->flags;
-
}
Image::Format RasterizerStorageGLES3::texture_get_format(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,Image::FORMAT_L8);
+ ERR_FAIL_COND_V(!texture, Image::FORMAT_L8);
return texture->format;
}
uint32_t RasterizerStorageGLES3::texture_get_width(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->width;
}
uint32_t RasterizerStorageGLES3::texture_get_height(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->height;
}
+void RasterizerStorageGLES3::texture_set_size_override(RID p_texture, int p_width, int p_height) {
-void RasterizerStorageGLES3::texture_set_size_override(RID p_texture,int p_width, int p_height) {
-
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(texture->render_target);
- ERR_FAIL_COND(p_width<=0 || p_width>16384);
- ERR_FAIL_COND(p_height<=0 || p_height>16384);
+ ERR_FAIL_COND(p_width <= 0 || p_width > 16384);
+ ERR_FAIL_COND(p_height <= 0 || p_height > 16384);
//real texture size is in alloc width and height
- texture->width=p_width;
- texture->height=p_height;
-
+ texture->width = p_width;
+ texture->height = p_height;
}
-void RasterizerStorageGLES3::texture_set_path(RID p_texture,const String& p_path) {
- Texture * texture = texture_owner.get(p_texture);
+void RasterizerStorageGLES3::texture_set_path(RID p_texture, const String &p_path) {
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->path=p_path;
-
+ texture->path = p_path;
}
-String RasterizerStorageGLES3::texture_get_path(RID p_texture) const{
+String RasterizerStorageGLES3::texture_get_path(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,String());
+ Texture *texture = texture_owner.get(p_texture);
+ ERR_FAIL_COND_V(!texture, String());
return texture->path;
}
-void RasterizerStorageGLES3::texture_debug_usage(List<VS::TextureInfo> *r_info){
+void RasterizerStorageGLES3::texture_debug_usage(List<VS::TextureInfo> *r_info) {
List<RID> textures;
texture_owner.get_owned_list(&textures);
- for (List<RID>::Element *E=textures.front();E;E=E->next()) {
+ for (List<RID>::Element *E = textures.front(); E; E = E->next()) {
Texture *t = texture_owner.get(E->get());
if (!t)
continue;
VS::TextureInfo tinfo;
- tinfo.path=t->path;
- tinfo.format=t->format;
- tinfo.size.x=t->alloc_width;
- tinfo.size.y=t->alloc_height;
- tinfo.bytes=t->total_data_size;
+ tinfo.path = t->path;
+ tinfo.format = t->format;
+ tinfo.size.x = t->alloc_width;
+ tinfo.size.y = t->alloc_height;
+ tinfo.bytes = t->total_data_size;
r_info->push_back(tinfo);
}
-
}
void RasterizerStorageGLES3::texture_set_shrink_all_x2_on_set_data(bool p_enable) {
- config.shrink_textures_x2=p_enable;
+ config.shrink_textures_x2 = p_enable;
}
void RasterizerStorageGLES3::textures_keep_original(bool p_enable) {
- config.keep_original_textures=p_enable;
+ config.keep_original_textures = p_enable;
}
-void RasterizerStorageGLES3::texture_set_detect_3d_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata) {
+void RasterizerStorageGLES3::texture_set_detect_3d_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->detect_3d=p_callback;
- texture->detect_3d_ud=p_userdata;
+ texture->detect_3d = p_callback;
+ texture->detect_3d_ud = p_userdata;
}
-void RasterizerStorageGLES3::texture_set_detect_srgb_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata){
- Texture * texture = texture_owner.get(p_texture);
+void RasterizerStorageGLES3::texture_set_detect_srgb_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) {
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->detect_srgb=p_callback;
- texture->detect_srgb_ud=p_userdata;
-
+ texture->detect_srgb = p_callback;
+ texture->detect_srgb_ud = p_userdata;
}
+RID RasterizerStorageGLES3::texture_create_radiance_cubemap(RID p_source, int p_resolution) const {
+ Texture *texture = texture_owner.get(p_source);
+ ERR_FAIL_COND_V(!texture, RID());
+ ERR_FAIL_COND_V(!(texture->flags & VS::TEXTURE_FLAG_CUBEMAP), RID());
-RID RasterizerStorageGLES3::texture_create_radiance_cubemap(RID p_source,int p_resolution) const {
-
- Texture * texture = texture_owner.get(p_source);
- ERR_FAIL_COND_V(!texture,RID());
- ERR_FAIL_COND_V(!(texture->flags&VS::TEXTURE_FLAG_CUBEMAP),RID());
-
- bool use_float=config.hdr_supported;
+ bool use_float = config.hdr_supported;
- if (p_resolution<0) {
- p_resolution=texture->width;
+ if (p_resolution < 0) {
+ p_resolution = texture->width;
}
-
glBindVertexArray(0);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_SCISSOR_TEST);
glDisable(GL_BLEND);
-
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
- texture->using_srgb=true;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
+ texture->using_srgb = true;
#ifdef TOOLS_ENABLED
- if (!(texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
- texture->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
+ if (!(texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ texture->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
//notify that texture must be set to linear beforehand, so it works in other platforms when exported
}
#endif
}
-
glActiveTexture(GL_TEXTURE1);
GLuint new_cubemap;
glGenTextures(1, &new_cubemap);
glBindTexture(GL_TEXTURE_CUBE_MAP, new_cubemap);
-
GLuint tmp_fb;
glGenFramebuffers(1, &tmp_fb);
glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
-
int size = p_resolution;
- int lod=0;
+ int lod = 0;
shaders.cubemap_filter.bind();
- int mipmaps=6;
+ int mipmaps = 6;
- int mm_level=mipmaps;
+ int mm_level = mipmaps;
- GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2;
+ GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
GLenum format = GL_RGBA;
- GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV;
+ GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
+ while (mm_level) {
- while(mm_level) {
-
- for(int i=0;i<6;i++) {
- glTexImage2D(_cube_side_enum[i], lod, internal_format, size, size, 0, format, type, NULL);
+ for (int i = 0; i < 6; i++) {
+ glTexImage2D(_cube_side_enum[i], lod, internal_format, size, size, 0, format, type, NULL);
}
lod++;
mm_level--;
- if (size>1)
- size>>=1;
+ if (size > 1)
+ size >>= 1;
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod-1);
+ glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod - 1);
- lod=0;
- mm_level=mipmaps;
+ lod = 0;
+ mm_level = mipmaps;
size = p_resolution;
- shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,false);
+ shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
- while(mm_level) {
+ while (mm_level) {
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], new_cubemap, lod);
- glViewport(0,0,size,size);
+ glViewport(0, 0, size, size);
glBindVertexArray(resources.quadie_array);
- shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::FACE_ID,i);
- shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,lod/float(mipmaps-1));
-
+ shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::FACE_ID, i);
+ shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, lod / float(mipmaps - 1));
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindVertexArray(0);
#ifdef DEBUG_ENABLED
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
#endif
}
-
-
- if (size>1)
- size>>=1;
+ if (size > 1)
+ size >>= 1;
lod++;
mm_level--;
-
}
-
//restore ranges
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod-1);
+ glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod - 1);
glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -1259,59 +1176,58 @@ RID RasterizerStorageGLES3::texture_create_radiance_cubemap(RID p_source,int p_r
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
glDeleteFramebuffers(1, &tmp_fb);
- Texture * ctex = memnew( Texture );
-
- ctex->flags=VS::TEXTURE_FLAG_CUBEMAP|VS::TEXTURE_FLAG_MIPMAPS|VS::TEXTURE_FLAG_FILTER;
- ctex->width=p_resolution;
- ctex->height=p_resolution;
- ctex->alloc_width=p_resolution;
- ctex->alloc_height=p_resolution;
- ctex->format=use_float?Image::FORMAT_RGBAH:Image::FORMAT_RGBA8;
- ctex->target=GL_TEXTURE_CUBE_MAP;
- ctex->gl_format_cache=format;
- ctex->gl_internal_format_cache=internal_format;
- ctex->gl_type_cache=type;
- ctex->data_size=0;
- ctex->compressed=false;
- ctex->srgb=false;
- ctex->total_data_size=0;
- ctex->ignore_mipmaps=false;
- ctex->mipmaps=mipmaps;
- ctex->active=true;
- ctex->tex_id=new_cubemap;
- ctex->stored_cube_sides=(1<<6)-1;
- ctex->render_target=NULL;
+ Texture *ctex = memnew(Texture);
+
+ ctex->flags = VS::TEXTURE_FLAG_CUBEMAP | VS::TEXTURE_FLAG_MIPMAPS | VS::TEXTURE_FLAG_FILTER;
+ ctex->width = p_resolution;
+ ctex->height = p_resolution;
+ ctex->alloc_width = p_resolution;
+ ctex->alloc_height = p_resolution;
+ ctex->format = use_float ? Image::FORMAT_RGBAH : Image::FORMAT_RGBA8;
+ ctex->target = GL_TEXTURE_CUBE_MAP;
+ ctex->gl_format_cache = format;
+ ctex->gl_internal_format_cache = internal_format;
+ ctex->gl_type_cache = type;
+ ctex->data_size = 0;
+ ctex->compressed = false;
+ ctex->srgb = false;
+ ctex->total_data_size = 0;
+ ctex->ignore_mipmaps = false;
+ ctex->mipmaps = mipmaps;
+ ctex->active = true;
+ ctex->tex_id = new_cubemap;
+ ctex->stored_cube_sides = (1 << 6) - 1;
+ ctex->render_target = NULL;
return texture_owner.make_rid(ctex);
}
-
RID RasterizerStorageGLES3::skybox_create() {
- SkyBox *skybox = memnew( SkyBox );
- skybox->radiance=0;
+ SkyBox *skybox = memnew(SkyBox);
+ skybox->radiance = 0;
return skybox_owner.make_rid(skybox);
}
-void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size){
+void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size) {
SkyBox *skybox = skybox_owner.getornull(p_skybox);
ERR_FAIL_COND(!skybox);
if (skybox->cubemap.is_valid()) {
- skybox->cubemap=RID();
- glDeleteTextures(1,&skybox->radiance);
- skybox->radiance=0;
+ skybox->cubemap = RID();
+ glDeleteTextures(1, &skybox->radiance);
+ skybox->radiance = 0;
}
- skybox->cubemap=p_cube_map;
+ skybox->cubemap = p_cube_map;
if (!skybox->cubemap.is_valid())
return; //cleared
Texture *texture = texture_owner.getornull(skybox->cubemap);
- if (!texture || !(texture->flags&VS::TEXTURE_FLAG_CUBEMAP)) {
- skybox->cubemap=RID();
- ERR_FAIL_COND(!texture || !(texture->flags&VS::TEXTURE_FLAG_CUBEMAP));
+ if (!texture || !(texture->flags & VS::TEXTURE_FLAG_CUBEMAP)) {
+ skybox->cubemap = RID();
+ ERR_FAIL_COND(!texture || !(texture->flags & VS::TEXTURE_FLAG_CUBEMAP));
}
glBindVertexArray(0);
@@ -1320,23 +1236,21 @@ void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, in
glDisable(GL_SCISSOR_TEST);
glDisable(GL_BLEND);
-
glActiveTexture(GL_TEXTURE0);
glBindTexture(texture->target, texture->tex_id);
if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) {
- glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT);
- texture->using_srgb=true;
+ glTexParameteri(texture->target, _TEXTURE_SRGB_DECODE_EXT, _DECODE_EXT);
+ texture->using_srgb = true;
#ifdef TOOLS_ENABLED
- if (!(texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
- texture->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
+ if (!(texture->flags & VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) {
+ texture->flags |= VS::TEXTURE_FLAG_CONVERT_TO_LINEAR;
//notify that texture must be set to linear beforehand, so it works in other platforms when exported
}
#endif
}
-
glActiveTexture(GL_TEXTURE1);
glGenTextures(1, &skybox->radiance);
glBindTexture(GL_TEXTURE_2D, skybox->radiance);
@@ -1346,75 +1260,70 @@ void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, in
glGenFramebuffers(1, &tmp_fb);
glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb);
-
int size = p_radiance_size;
- int lod=0;
-
+ int lod = 0;
- int mipmaps=6;
+ int mipmaps = 6;
- int mm_level=mipmaps;
+ int mm_level = mipmaps;
- bool use_float=config.hdr_supported;
+ bool use_float = config.hdr_supported;
- GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2;
+ GLenum internal_format = use_float ? GL_RGBA16F : GL_RGB10_A2;
GLenum format = GL_RGBA;
- GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV;
+ GLenum type = use_float ? GL_HALF_FLOAT : GL_UNSIGNED_INT_2_10_10_10_REV;
- while(mm_level) {
+ while (mm_level) {
- glTexImage2D(GL_TEXTURE_2D, lod, internal_format, size, size*2, 0, format, type, NULL);
+ glTexImage2D(GL_TEXTURE_2D, lod, internal_format, size, size * 2, 0, format, type, NULL);
lod++;
mm_level--;
- if (size>1)
- size>>=1;
+ if (size > 1)
+ size >>= 1;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod-1);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod - 1);
- lod=0;
- mm_level=mipmaps;
+ lod = 0;
+ mm_level = mipmaps;
size = p_radiance_size;
- shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,true);
+ shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, true);
shaders.cubemap_filter.bind();
- while(mm_level) {
+ while (mm_level) {
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, skybox->radiance, lod);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, skybox->radiance, lod);
#ifdef DEBUG_ENABLED
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
- ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE);
+ ERR_CONTINUE(status != GL_FRAMEBUFFER_COMPLETE);
#endif
- for(int i=0;i<2;i++) {
- glViewport(0,i*size,size,size);
+ for (int i = 0; i < 2; i++) {
+ glViewport(0, i * size, size, size);
glBindVertexArray(resources.quadie_array);
- shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP,i>0);
- shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,lod/float(mipmaps-1));
-
+ shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP, i > 0);
+ shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS, lod / float(mipmaps - 1));
- glDrawArrays(GL_TRIANGLE_FAN,0,4);
+ glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindVertexArray(0);
}
- if (size>1)
- size>>=1;
+ if (size > 1)
+ size >>= 1;
lod++;
mm_level--;
-
}
- shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,false);
-
+ shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID, false);
//restore ranges
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod-1);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod - 1);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
@@ -1423,26 +1332,23 @@ void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, in
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
glDeleteFramebuffers(1, &tmp_fb);
-
}
-
/* SHADER API */
+RID RasterizerStorageGLES3::shader_create(VS::ShaderMode p_mode) {
-RID RasterizerStorageGLES3::shader_create(VS::ShaderMode p_mode){
-
- Shader *shader = memnew( Shader );
- shader->mode=p_mode;
+ Shader *shader = memnew(Shader);
+ shader->mode = p_mode;
RID rid = shader_owner.make_rid(shader);
- shader_set_mode(rid,p_mode);
+ shader_set_mode(rid, p_mode);
_shader_make_dirty(shader);
- shader->self=rid;
+ shader->self = rid;
return rid;
}
-void RasterizerStorageGLES3::_shader_make_dirty(Shader* p_shader) {
+void RasterizerStorageGLES3::_shader_make_dirty(Shader *p_shader) {
if (p_shader->dirty_list.in_list())
return;
@@ -1450,217 +1356,212 @@ void RasterizerStorageGLES3::_shader_make_dirty(Shader* p_shader) {
_shader_dirty_list.add(&p_shader->dirty_list);
}
-void RasterizerStorageGLES3::shader_set_mode(RID p_shader,VS::ShaderMode p_mode){
+void RasterizerStorageGLES3::shader_set_mode(RID p_shader, VS::ShaderMode p_mode) {
- ERR_FAIL_INDEX(p_mode,VS::SHADER_MAX);
- Shader *shader=shader_owner.get(p_shader);
+ ERR_FAIL_INDEX(p_mode, VS::SHADER_MAX);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
- if (shader->custom_code_id && p_mode==shader->mode)
+ if (shader->custom_code_id && p_mode == shader->mode)
return;
-
if (shader->custom_code_id) {
shader->shader->free_custom_shader(shader->custom_code_id);
- shader->custom_code_id=0;
+ shader->custom_code_id = 0;
}
- shader->mode=p_mode;
+ shader->mode = p_mode;
- ShaderGLES3* shaders[VS::SHADER_MAX]={
+ ShaderGLES3 *shaders[VS::SHADER_MAX] = {
&scene->state.scene_shader,
&canvas->state.canvas_shader,
&this->shaders.particles,
};
- shader->shader=shaders[p_mode];
+ shader->shader = shaders[p_mode];
shader->custom_code_id = shader->shader->create_custom_shader();
_shader_make_dirty(shader);
-
}
VS::ShaderMode RasterizerStorageGLES3::shader_get_mode(RID p_shader) const {
- const Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,VS::SHADER_MAX);
+ const Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, VS::SHADER_MAX);
return shader->mode;
}
-void RasterizerStorageGLES3::shader_set_code(RID p_shader, const String& p_code){
+void RasterizerStorageGLES3::shader_set_code(RID p_shader, const String &p_code) {
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
- shader->code=p_code;
+ shader->code = p_code;
_shader_make_dirty(shader);
}
-String RasterizerStorageGLES3::shader_get_code(RID p_shader) const{
-
- const Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,String());
+String RasterizerStorageGLES3::shader_get_code(RID p_shader) const {
+ const Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, String());
return shader->code;
}
-void RasterizerStorageGLES3::_update_shader(Shader* p_shader) const {
-
+void RasterizerStorageGLES3::_update_shader(Shader *p_shader) const {
- _shader_dirty_list.remove( &p_shader->dirty_list );
+ _shader_dirty_list.remove(&p_shader->dirty_list);
- p_shader->valid=false;
+ p_shader->valid = false;
p_shader->uniforms.clear();
ShaderCompilerGLES3::GeneratedCode gen_code;
- ShaderCompilerGLES3::IdentifierActions *actions=NULL;
-
+ ShaderCompilerGLES3::IdentifierActions *actions = NULL;
-
- switch(p_shader->mode) {
+ switch (p_shader->mode) {
case VS::SHADER_CANVAS_ITEM: {
- p_shader->canvas_item.light_mode=Shader::CanvasItem::LIGHT_MODE_NORMAL;
- p_shader->canvas_item.blend_mode=Shader::CanvasItem::BLEND_MODE_MIX;
+ p_shader->canvas_item.light_mode = Shader::CanvasItem::LIGHT_MODE_NORMAL;
+ p_shader->canvas_item.blend_mode = Shader::CanvasItem::BLEND_MODE_MIX;
- shaders.actions_canvas.render_mode_values["blend_add"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_ADD);
- shaders.actions_canvas.render_mode_values["blend_mix"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_MIX);
- shaders.actions_canvas.render_mode_values["blend_sub"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_SUB);
- shaders.actions_canvas.render_mode_values["blend_mul"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_MUL);
- shaders.actions_canvas.render_mode_values["blend_premul_alpha"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_PMALPHA);
+ shaders.actions_canvas.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_ADD);
+ shaders.actions_canvas.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MIX);
+ shaders.actions_canvas.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_SUB);
+ shaders.actions_canvas.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_MUL);
+ shaders.actions_canvas.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&p_shader->canvas_item.blend_mode, Shader::CanvasItem::BLEND_MODE_PMALPHA);
- shaders.actions_canvas.render_mode_values["unshaded"]=Pair<int*,int>(&p_shader->canvas_item.light_mode,Shader::CanvasItem::LIGHT_MODE_UNSHADED);
- shaders.actions_canvas.render_mode_values["light_only"]=Pair<int*,int>(&p_shader->canvas_item.light_mode,Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY);
+ shaders.actions_canvas.render_mode_values["unshaded"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_UNSHADED);
+ shaders.actions_canvas.render_mode_values["light_only"] = Pair<int *, int>(&p_shader->canvas_item.light_mode, Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY);
- actions=&shaders.actions_canvas;
- actions->uniforms=&p_shader->uniforms;
+ actions = &shaders.actions_canvas;
+ actions->uniforms = &p_shader->uniforms;
} break;
case VS::SHADER_SPATIAL: {
- p_shader->spatial.blend_mode=Shader::Spatial::BLEND_MODE_MIX;
- p_shader->spatial.depth_draw_mode=Shader::Spatial::DEPTH_DRAW_OPAQUE;
- p_shader->spatial.cull_mode=Shader::Spatial::CULL_MODE_BACK;
- p_shader->spatial.uses_alpha=false;
- p_shader->spatial.uses_discard=false;
- p_shader->spatial.unshaded=false;
- p_shader->spatial.ontop=false;
- p_shader->spatial.uses_sss=false;
- p_shader->spatial.uses_vertex=false;
-
- shaders.actions_scene.render_mode_values["blend_add"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_ADD);
- shaders.actions_scene.render_mode_values["blend_mix"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_MIX);
- shaders.actions_scene.render_mode_values["blend_sub"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_SUB);
- shaders.actions_scene.render_mode_values["blend_mul"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_MUL);
+ p_shader->spatial.blend_mode = Shader::Spatial::BLEND_MODE_MIX;
+ p_shader->spatial.depth_draw_mode = Shader::Spatial::DEPTH_DRAW_OPAQUE;
+ p_shader->spatial.cull_mode = Shader::Spatial::CULL_MODE_BACK;
+ p_shader->spatial.uses_alpha = false;
+ p_shader->spatial.uses_discard = false;
+ p_shader->spatial.unshaded = false;
+ p_shader->spatial.ontop = false;
+ p_shader->spatial.uses_sss = false;
+ p_shader->spatial.uses_vertex = false;
- shaders.actions_scene.render_mode_values["depth_draw_opaque"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_OPAQUE);
- shaders.actions_scene.render_mode_values["depth_draw_always"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_ALWAYS);
- shaders.actions_scene.render_mode_values["depth_draw_never"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_NEVER);
- shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS);
+ shaders.actions_scene.render_mode_values["blend_add"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_ADD);
+ shaders.actions_scene.render_mode_values["blend_mix"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MIX);
+ shaders.actions_scene.render_mode_values["blend_sub"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_SUB);
+ shaders.actions_scene.render_mode_values["blend_mul"] = Pair<int *, int>(&p_shader->spatial.blend_mode, Shader::Spatial::BLEND_MODE_MUL);
- shaders.actions_scene.render_mode_values["cull_front"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_FRONT);
- shaders.actions_scene.render_mode_values["cull_back"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_BACK);
- shaders.actions_scene.render_mode_values["cull_disabled"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_DISABLED);
+ shaders.actions_scene.render_mode_values["depth_draw_opaque"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_OPAQUE);
+ shaders.actions_scene.render_mode_values["depth_draw_always"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALWAYS);
+ shaders.actions_scene.render_mode_values["depth_draw_never"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_NEVER);
+ shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"] = Pair<int *, int>(&p_shader->spatial.depth_draw_mode, Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS);
- shaders.actions_scene.render_mode_flags["unshaded"]=&p_shader->spatial.unshaded;
- shaders.actions_scene.render_mode_flags["ontop"]=&p_shader->spatial.ontop;
+ shaders.actions_scene.render_mode_values["cull_front"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_FRONT);
+ shaders.actions_scene.render_mode_values["cull_back"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_BACK);
+ shaders.actions_scene.render_mode_values["cull_disabled"] = Pair<int *, int>(&p_shader->spatial.cull_mode, Shader::Spatial::CULL_MODE_DISABLED);
- shaders.actions_scene.usage_flag_pointers["ALPHA"]=&p_shader->spatial.uses_alpha;
- shaders.actions_scene.usage_flag_pointers["VERTEX"]=&p_shader->spatial.uses_vertex;
+ shaders.actions_scene.render_mode_flags["unshaded"] = &p_shader->spatial.unshaded;
+ shaders.actions_scene.render_mode_flags["ontop"] = &p_shader->spatial.ontop;
- shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"]=&p_shader->spatial.uses_sss;
- shaders.actions_scene.usage_flag_pointers["DISCARD"]=&p_shader->spatial.uses_discard;
+ shaders.actions_scene.usage_flag_pointers["ALPHA"] = &p_shader->spatial.uses_alpha;
+ shaders.actions_scene.usage_flag_pointers["VERTEX"] = &p_shader->spatial.uses_vertex;
- actions=&shaders.actions_scene;
- actions->uniforms=&p_shader->uniforms;
+ shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"] = &p_shader->spatial.uses_sss;
+ shaders.actions_scene.usage_flag_pointers["DISCARD"] = &p_shader->spatial.uses_discard;
+ actions = &shaders.actions_scene;
+ actions->uniforms = &p_shader->uniforms;
} break;
case VS::SHADER_PARTICLES: {
- actions=&shaders.actions_particles;
- actions->uniforms=&p_shader->uniforms;
+ actions = &shaders.actions_particles;
+ actions->uniforms = &p_shader->uniforms;
} break;
-
}
+ Error err = shaders.compiler.compile(p_shader->mode, p_shader->code, actions, p_shader->path, gen_code);
- Error err = shaders.compiler.compile(p_shader->mode,p_shader->code,actions,p_shader->path,gen_code);
+ ERR_FAIL_COND(err != OK);
+ p_shader->shader->set_custom_shader_code(p_shader->custom_code_id, gen_code.vertex, gen_code.vertex_global, gen_code.fragment, gen_code.light, gen_code.fragment_global, gen_code.uniforms, gen_code.texture_uniforms, gen_code.defines);
- ERR_FAIL_COND(err!=OK);
+ p_shader->ubo_size = gen_code.uniform_total_size;
+ p_shader->ubo_offsets = gen_code.uniform_offsets;
+ p_shader->texture_count = gen_code.texture_uniforms.size();
+ p_shader->texture_hints = gen_code.texture_hints;
- p_shader->shader->set_custom_shader_code(p_shader->custom_code_id,gen_code.vertex,gen_code.vertex_global,gen_code.fragment,gen_code.light,gen_code.fragment_global,gen_code.uniforms,gen_code.texture_uniforms,gen_code.defines);
-
- p_shader->ubo_size=gen_code.uniform_total_size;
- p_shader->ubo_offsets=gen_code.uniform_offsets;
- p_shader->texture_count=gen_code.texture_uniforms.size();
- p_shader->texture_hints=gen_code.texture_hints;
-
- p_shader->uses_vertex_time=gen_code.uses_vertex_time;
- p_shader->uses_fragment_time=gen_code.uses_fragment_time;
+ p_shader->uses_vertex_time = gen_code.uses_vertex_time;
+ p_shader->uses_fragment_time = gen_code.uses_fragment_time;
//all materials using this shader will have to be invalidated, unfortunately
- for (SelfList<Material>* E = p_shader->materials.first();E;E=E->next() ) {
+ for (SelfList<Material> *E = p_shader->materials.first(); E; E = E->next()) {
_material_make_dirty(E->self());
}
- p_shader->valid=true;
+ p_shader->valid = true;
p_shader->version++;
-
-
}
void RasterizerStorageGLES3::update_dirty_shaders() {
- while( _shader_dirty_list.first() ) {
- _update_shader(_shader_dirty_list.first()->self() );
+ while (_shader_dirty_list.first()) {
+ _update_shader(_shader_dirty_list.first()->self());
}
}
-void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const{
+void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const {
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
-
if (shader->dirty_list.in_list())
_update_shader(shader); // ok should be not anymore dirty
+ Map<int, StringName> order;
- Map<int,StringName> order;
-
-
- for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
-
- order[E->get().order]=E->key();
+ order[E->get().order] = E->key();
}
-
- for(Map<int,StringName>::Element *E=order.front();E;E=E->next()) {
+ for (Map<int, StringName>::Element *E = order.front(); E; E = E->next()) {
PropertyInfo pi;
- ShaderLanguage::ShaderNode::Uniform &u=shader->uniforms[E->get()];
- pi.name=E->get();
- switch(u.type) {
- case ShaderLanguage::TYPE_VOID: pi.type=Variant::NIL; break;
- case ShaderLanguage::TYPE_BOOL: pi.type=Variant::BOOL; break;
- case ShaderLanguage::TYPE_BVEC2: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y"; break;
- case ShaderLanguage::TYPE_BVEC3: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y,z"; break;
- case ShaderLanguage::TYPE_BVEC4: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y,z,w"; break;
+ ShaderLanguage::ShaderNode::Uniform &u = shader->uniforms[E->get()];
+ pi.name = E->get();
+ switch (u.type) {
+ case ShaderLanguage::TYPE_VOID: pi.type = Variant::NIL; break;
+ case ShaderLanguage::TYPE_BOOL: pi.type = Variant::BOOL; break;
+ case ShaderLanguage::TYPE_BVEC2:
+ pi.type = Variant::INT;
+ pi.hint = PROPERTY_HINT_FLAGS;
+ pi.hint_string = "x,y";
+ break;
+ case ShaderLanguage::TYPE_BVEC3:
+ pi.type = Variant::INT;
+ pi.hint = PROPERTY_HINT_FLAGS;
+ pi.hint_string = "x,y,z";
+ break;
+ case ShaderLanguage::TYPE_BVEC4:
+ pi.type = Variant::INT;
+ pi.hint = PROPERTY_HINT_FLAGS;
+ pi.hint_string = "x,y,z,w";
+ break;
case ShaderLanguage::TYPE_UINT:
case ShaderLanguage::TYPE_INT: {
- pi.type=Variant::INT;
- if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
- pi.hint=PROPERTY_HINT_RANGE;
- pi.hint_string=rtos(u.hint_range[0])+","+rtos(u.hint_range[1]);
+ pi.type = Variant::INT;
+ if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
+ pi.hint = PROPERTY_HINT_RANGE;
+ pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]);
}
} break;
@@ -1671,77 +1572,75 @@ void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyIn
case ShaderLanguage::TYPE_UVEC3:
case ShaderLanguage::TYPE_UVEC4: {
- pi.type=Variant::POOL_INT_ARRAY;
+ pi.type = Variant::POOL_INT_ARRAY;
} break;
case ShaderLanguage::TYPE_FLOAT: {
- pi.type=Variant::REAL;
- if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
- pi.hint=PROPERTY_HINT_RANGE;
- pi.hint_string=rtos(u.hint_range[0])+","+rtos(u.hint_range[1])+","+rtos(u.hint_range[2]);
+ pi.type = Variant::REAL;
+ if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) {
+ pi.hint = PROPERTY_HINT_RANGE;
+ pi.hint_string = rtos(u.hint_range[0]) + "," + rtos(u.hint_range[1]) + "," + rtos(u.hint_range[2]);
}
} break;
- case ShaderLanguage::TYPE_VEC2: pi.type=Variant::VECTOR2; break;
- case ShaderLanguage::TYPE_VEC3: pi.type=Variant::VECTOR3; break;
+ case ShaderLanguage::TYPE_VEC2: pi.type = Variant::VECTOR2; break;
+ case ShaderLanguage::TYPE_VEC3: pi.type = Variant::VECTOR3; break;
case ShaderLanguage::TYPE_VEC4: {
- if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
- pi.type=Variant::COLOR;
+ if (u.hint == ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) {
+ pi.type = Variant::COLOR;
} else {
- pi.type=Variant::PLANE;
+ pi.type = Variant::PLANE;
}
} break;
- case ShaderLanguage::TYPE_MAT2: pi.type=Variant::TRANSFORM2D; break;
- case ShaderLanguage::TYPE_MAT3: pi.type=Variant::BASIS; break;
- case ShaderLanguage::TYPE_MAT4: pi.type=Variant::TRANSFORM; break;
+ case ShaderLanguage::TYPE_MAT2: pi.type = Variant::TRANSFORM2D; break;
+ case ShaderLanguage::TYPE_MAT3: pi.type = Variant::BASIS; break;
+ case ShaderLanguage::TYPE_MAT4: pi.type = Variant::TRANSFORM; break;
case ShaderLanguage::TYPE_SAMPLER2D:
case ShaderLanguage::TYPE_ISAMPLER2D:
case ShaderLanguage::TYPE_USAMPLER2D: {
- pi.type=Variant::OBJECT;
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string="Texture";
+ pi.type = Variant::OBJECT;
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = "Texture";
} break;
case ShaderLanguage::TYPE_SAMPLERCUBE: {
- pi.type=Variant::OBJECT;
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string="CubeMap";
+ pi.type = Variant::OBJECT;
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = "CubeMap";
} break;
};
p_param_list->push_back(pi);
-
}
}
-void RasterizerStorageGLES3::shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture){
+void RasterizerStorageGLES3::shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) {
- Shader *shader=shader_owner.get(p_shader);
+ Shader *shader = shader_owner.get(p_shader);
ERR_FAIL_COND(!shader);
ERR_FAIL_COND(p_texture.is_valid() && !texture_owner.owns(p_texture));
if (p_texture.is_valid())
- shader->default_textures[p_name]=p_texture;
+ shader->default_textures[p_name] = p_texture;
else
shader->default_textures.erase(p_name);
_shader_make_dirty(shader);
}
-RID RasterizerStorageGLES3::shader_get_default_texture_param(RID p_shader, const StringName& p_name) const{
+RID RasterizerStorageGLES3::shader_get_default_texture_param(RID p_shader, const StringName &p_name) const {
- const Shader *shader=shader_owner.get(p_shader);
- ERR_FAIL_COND_V(!shader,RID());
+ const Shader *shader = shader_owner.get(p_shader);
+ ERR_FAIL_COND_V(!shader, RID());
- const Map<StringName,RID>::Element *E=shader->default_textures.find(p_name);
+ const Map<StringName, RID>::Element *E = shader->default_textures.find(p_name);
if (!E)
return RID();
return E->get();
}
-
/* COMMON MATERIAL API */
-void RasterizerStorageGLES3::_material_make_dirty(Material* p_material) const {
+void RasterizerStorageGLES3::_material_make_dirty(Material *p_material) const {
if (p_material->dirty_list.in_list())
return;
@@ -1749,38 +1648,37 @@ void RasterizerStorageGLES3::_material_make_dirty(Material* p_material) const {
_material_dirty_list.add(&p_material->dirty_list);
}
-RID RasterizerStorageGLES3::material_create(){
+RID RasterizerStorageGLES3::material_create() {
- Material *material = memnew( Material );
+ Material *material = memnew(Material);
return material_owner.make_rid(material);
}
-void RasterizerStorageGLES3::material_set_shader(RID p_material, RID p_shader){
+void RasterizerStorageGLES3::material_set_shader(RID p_material, RID p_shader) {
- Material *material = material_owner.get( p_material );
+ Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- Shader *shader=shader_owner.getornull(p_shader);
+ Shader *shader = shader_owner.getornull(p_shader);
if (material->shader) {
//if shader, remove from previous shader material list
- material->shader->materials.remove( &material->list );
+ material->shader->materials.remove(&material->list);
}
- material->shader=shader;
+ material->shader = shader;
if (shader) {
shader->materials.add(&material->list);
}
_material_make_dirty(material);
-
}
-RID RasterizerStorageGLES3::material_get_shader(RID p_material) const{
+RID RasterizerStorageGLES3::material_get_shader(RID p_material) const {
- const Material *material = material_owner.get( p_material );
- ERR_FAIL_COND_V(!material,RID());
+ const Material *material = material_owner.get(p_material);
+ ERR_FAIL_COND_V(!material, RID());
if (material->shader)
return material->shader->self;
@@ -1788,23 +1686,22 @@ RID RasterizerStorageGLES3::material_get_shader(RID p_material) const{
return RID();
}
-void RasterizerStorageGLES3::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value){
+void RasterizerStorageGLES3::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
- Material *material = material_owner.get( p_material );
+ Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- if (p_value.get_type()==Variant::NIL)
+ if (p_value.get_type() == Variant::NIL)
material->params.erase(p_param);
else
- material->params[p_param]=p_value;
+ material->params[p_param] = p_value;
_material_make_dirty(material);
-
}
-Variant RasterizerStorageGLES3::material_get_param(RID p_material, const StringName& p_param) const{
+Variant RasterizerStorageGLES3::material_get_param(RID p_material, const StringName &p_param) const {
- const Material *material = material_owner.get( p_material );
- ERR_FAIL_COND_V(!material,RID());
+ const Material *material = material_owner.get(p_material);
+ ERR_FAIL_COND_V(!material, RID());
if (material->params.has(p_param))
return material->params[p_param];
@@ -1814,29 +1711,26 @@ Variant RasterizerStorageGLES3::material_get_param(RID p_material, const StringN
void RasterizerStorageGLES3::material_set_line_width(RID p_material, float p_width) {
- Material *material = material_owner.get( p_material );
+ Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- material->line_width=p_width;
-
-
+ material->line_width = p_width;
}
-bool RasterizerStorageGLES3::material_is_animated(RID p_material) {
+bool RasterizerStorageGLES3::material_is_animated(RID p_material) {
- Material *material = material_owner.get( p_material );
- ERR_FAIL_COND_V(!material,false);
+ Material *material = material_owner.get(p_material);
+ ERR_FAIL_COND_V(!material, false);
if (material->dirty_list.in_list()) {
_update_material(material);
}
return material->is_animated_cache;
-
}
-bool RasterizerStorageGLES3::material_casts_shadows(RID p_material) {
+bool RasterizerStorageGLES3::material_casts_shadows(RID p_material) {
- Material *material = material_owner.get( p_material );
- ERR_FAIL_COND_V(!material,false);
+ Material *material = material_owner.get(p_material);
+ ERR_FAIL_COND_V(!material, false);
if (material->dirty_list.in_list()) {
_update_material(material);
}
@@ -1846,90 +1740,87 @@ bool RasterizerStorageGLES3::material_casts_shadows(RID p_material) {
void RasterizerStorageGLES3::material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) {
- Material *material = material_owner.get( p_material );
+ Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.find(p_instance);
+ Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.find(p_instance);
if (E) {
E->get()++;
} else {
- material->instance_owners[p_instance]=1;
+ material->instance_owners[p_instance] = 1;
}
}
void RasterizerStorageGLES3::material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) {
- Material *material = material_owner.get( p_material );
+ Material *material = material_owner.get(p_material);
ERR_FAIL_COND(!material);
- Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.find(p_instance);
+ Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.find(p_instance);
ERR_FAIL_COND(!E);
E->get()--;
- if (E->get()==0) {
+ if (E->get() == 0) {
material->instance_owners.erase(E);
}
}
-
-
-_FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, const Variant& value, uint8_t *data,bool p_linear_color) {
- switch(type) {
+_FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, const Variant &value, uint8_t *data, bool p_linear_color) {
+ switch (type) {
case ShaderLanguage::TYPE_BOOL: {
bool v = value;
- GLuint *gui = (GLuint*)data;
+ GLuint *gui = (GLuint *)data;
*gui = v ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC2: {
int v = value;
- GLuint *gui = (GLuint*)data;
- gui[0]=v&1 ? GL_TRUE : GL_FALSE;
- gui[1]=v&2 ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = v & 1 ? GL_TRUE : GL_FALSE;
+ gui[1] = v & 2 ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC3: {
int v = value;
- GLuint *gui = (GLuint*)data;
- gui[0]=v&1 ? GL_TRUE : GL_FALSE;
- gui[1]=v&2 ? GL_TRUE : GL_FALSE;
- gui[2]=v&4 ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = v & 1 ? GL_TRUE : GL_FALSE;
+ gui[1] = v & 2 ? GL_TRUE : GL_FALSE;
+ gui[2] = v & 4 ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC4: {
int v = value;
- GLuint *gui = (GLuint*)data;
- gui[0]=v&1 ? GL_TRUE : GL_FALSE;
- gui[1]=v&2 ? GL_TRUE : GL_FALSE;
- gui[2]=v&4 ? GL_TRUE : GL_FALSE;
- gui[3]=v&8 ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = v & 1 ? GL_TRUE : GL_FALSE;
+ gui[1] = v & 2 ? GL_TRUE : GL_FALSE;
+ gui[2] = v & 4 ? GL_TRUE : GL_FALSE;
+ gui[3] = v & 8 ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_INT: {
int v = value;
- GLint *gui = (GLint*)data;
- gui[0]=v;
+ GLint *gui = (GLint *)data;
+ gui[0] = v;
} break;
case ShaderLanguage::TYPE_IVEC2: {
PoolVector<int> iv = value;
int s = iv.size();
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<2;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 2; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
-
+ gui[i] = 0;
}
} break;
@@ -1937,387 +1828,372 @@ _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataTy
PoolVector<int> iv = value;
int s = iv.size();
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<3;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 3; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
-
+ gui[i] = 0;
}
} break;
case ShaderLanguage::TYPE_IVEC4: {
-
PoolVector<int> iv = value;
int s = iv.size();
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<4;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 4; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
-
+ gui[i] = 0;
}
} break;
case ShaderLanguage::TYPE_UINT: {
int v = value;
- GLuint *gui = (GLuint*)data;
- gui[0]=v;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = v;
} break;
case ShaderLanguage::TYPE_UVEC2: {
PoolVector<int> iv = value;
int s = iv.size();
- GLuint *gui = (GLuint*)data;
+ GLuint *gui = (GLuint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<2;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 2; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
-
+ gui[i] = 0;
}
} break;
case ShaderLanguage::TYPE_UVEC3: {
PoolVector<int> iv = value;
int s = iv.size();
- GLuint *gui = (GLuint*)data;
+ GLuint *gui = (GLuint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<3;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 3; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
+ gui[i] = 0;
}
} break;
case ShaderLanguage::TYPE_UVEC4: {
PoolVector<int> iv = value;
int s = iv.size();
- GLuint *gui = (GLuint*)data;
+ GLuint *gui = (GLuint *)data;
PoolVector<int>::Read r = iv.read();
- for(int i=0;i<4;i++) {
- if (i<s)
- gui[i]=r[i];
+ for (int i = 0; i < 4; i++) {
+ if (i < s)
+ gui[i] = r[i];
else
- gui[i]=0;
+ gui[i] = 0;
}
} break;
case ShaderLanguage::TYPE_FLOAT: {
float v = value;
- GLfloat *gui = (GLfloat*)data;
- gui[0]=v;
+ GLfloat *gui = (GLfloat *)data;
+ gui[0] = v;
} break;
case ShaderLanguage::TYPE_VEC2: {
Vector2 v = value;
- GLfloat *gui = (GLfloat*)data;
- gui[0]=v.x;
- gui[1]=v.y;
+ GLfloat *gui = (GLfloat *)data;
+ gui[0] = v.x;
+ gui[1] = v.y;
} break;
case ShaderLanguage::TYPE_VEC3: {
Vector3 v = value;
- GLfloat *gui = (GLfloat*)data;
- gui[0]=v.x;
- gui[1]=v.y;
- gui[2]=v.z;
+ GLfloat *gui = (GLfloat *)data;
+ gui[0] = v.x;
+ gui[1] = v.y;
+ gui[2] = v.z;
} break;
case ShaderLanguage::TYPE_VEC4: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- if (value.get_type()==Variant::COLOR) {
- Color v=value;
+ if (value.get_type() == Variant::COLOR) {
+ Color v = value;
if (p_linear_color) {
- v=v.to_linear();
+ v = v.to_linear();
}
- gui[0]=v.r;
- gui[1]=v.g;
- gui[2]=v.b;
- gui[3]=v.a;
- } else if (value.get_type()==Variant::RECT2) {
- Rect2 v=value;
-
- gui[0]=v.pos.x;
- gui[1]=v.pos.y;
- gui[2]=v.size.x;
- gui[3]=v.size.y;
- } else if (value.get_type()==Variant::QUAT) {
- Quat v=value;
-
- gui[0]=v.x;
- gui[1]=v.y;
- gui[2]=v.z;
- gui[3]=v.w;
+ gui[0] = v.r;
+ gui[1] = v.g;
+ gui[2] = v.b;
+ gui[3] = v.a;
+ } else if (value.get_type() == Variant::RECT2) {
+ Rect2 v = value;
+
+ gui[0] = v.pos.x;
+ gui[1] = v.pos.y;
+ gui[2] = v.size.x;
+ gui[3] = v.size.y;
+ } else if (value.get_type() == Variant::QUAT) {
+ Quat v = value;
+
+ gui[0] = v.x;
+ gui[1] = v.y;
+ gui[2] = v.z;
+ gui[3] = v.w;
} else {
- Plane v=value;
-
- gui[0]=v.normal.x;
- gui[1]=v.normal.y;
- gui[2]=v.normal.x;
- gui[3]=v.d;
+ Plane v = value;
+ gui[0] = v.normal.x;
+ gui[1] = v.normal.y;
+ gui[2] = v.normal.x;
+ gui[3] = v.d;
}
} break;
case ShaderLanguage::TYPE_MAT2: {
Transform2D v = value;
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- gui[ 0]=v.elements[0][0];
- gui[ 1]=v.elements[0][1];
- gui[ 2]=v.elements[1][0];
- gui[ 3]=v.elements[1][1];
+ gui[0] = v.elements[0][0];
+ gui[1] = v.elements[0][1];
+ gui[2] = v.elements[1][0];
+ gui[3] = v.elements[1][1];
} break;
case ShaderLanguage::TYPE_MAT3: {
-
Basis v = value;
- GLfloat *gui = (GLfloat*)data;
-
- gui[ 0]=v.elements[0][0];
- gui[ 1]=v.elements[1][0];
- gui[ 2]=v.elements[2][0];
- gui[ 3]=0;
- gui[ 4]=v.elements[0][1];
- gui[ 5]=v.elements[1][1];
- gui[ 6]=v.elements[2][1];
- gui[ 7]=0;
- gui[ 8]=v.elements[0][2];
- gui[ 9]=v.elements[1][2];
- gui[10]=v.elements[2][2];
- gui[11]=0;
+ GLfloat *gui = (GLfloat *)data;
+
+ gui[0] = v.elements[0][0];
+ gui[1] = v.elements[1][0];
+ gui[2] = v.elements[2][0];
+ gui[3] = 0;
+ gui[4] = v.elements[0][1];
+ gui[5] = v.elements[1][1];
+ gui[6] = v.elements[2][1];
+ gui[7] = 0;
+ gui[8] = v.elements[0][2];
+ gui[9] = v.elements[1][2];
+ gui[10] = v.elements[2][2];
+ gui[11] = 0;
} break;
case ShaderLanguage::TYPE_MAT4: {
Transform v = value;
- GLfloat *gui = (GLfloat*)data;
-
- gui[ 0]=v.basis.elements[0][0];
- gui[ 1]=v.basis.elements[1][0];
- gui[ 2]=v.basis.elements[2][0];
- gui[ 3]=0;
- gui[ 4]=v.basis.elements[0][1];
- gui[ 5]=v.basis.elements[1][1];
- gui[ 6]=v.basis.elements[2][1];
- gui[ 7]=0;
- gui[ 8]=v.basis.elements[0][2];
- gui[ 9]=v.basis.elements[1][2];
- gui[10]=v.basis.elements[2][2];
- gui[11]=0;
- gui[12]=v.origin.x;
- gui[13]=v.origin.y;
- gui[14]=v.origin.z;
- gui[15]=1;
+ GLfloat *gui = (GLfloat *)data;
+
+ gui[0] = v.basis.elements[0][0];
+ gui[1] = v.basis.elements[1][0];
+ gui[2] = v.basis.elements[2][0];
+ gui[3] = 0;
+ gui[4] = v.basis.elements[0][1];
+ gui[5] = v.basis.elements[1][1];
+ gui[6] = v.basis.elements[2][1];
+ gui[7] = 0;
+ gui[8] = v.basis.elements[0][2];
+ gui[9] = v.basis.elements[1][2];
+ gui[10] = v.basis.elements[2][2];
+ gui[11] = 0;
+ gui[12] = v.origin.x;
+ gui[13] = v.origin.y;
+ gui[14] = v.origin.z;
+ gui[15] = 1;
} break;
default: {}
}
-
}
-_FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value>& value, uint8_t *data) {
+_FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value> &value, uint8_t *data) {
- switch(type) {
+ switch (type) {
case ShaderLanguage::TYPE_BOOL: {
- GLuint *gui = (GLuint*)data;
+ GLuint *gui = (GLuint *)data;
*gui = value[0].boolean ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC2: {
- GLuint *gui = (GLuint*)data;
- gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE;
- gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
+ gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC3: {
- GLuint *gui = (GLuint*)data;
- gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE;
- gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE;
- gui[2]=value[2].boolean ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
+ gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
+ gui[2] = value[2].boolean ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_BVEC4: {
- GLuint *gui = (GLuint*)data;
- gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE;
- gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE;
- gui[2]=value[2].boolean ? GL_TRUE : GL_FALSE;
- gui[3]=value[3].boolean ? GL_TRUE : GL_FALSE;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = value[0].boolean ? GL_TRUE : GL_FALSE;
+ gui[1] = value[1].boolean ? GL_TRUE : GL_FALSE;
+ gui[2] = value[2].boolean ? GL_TRUE : GL_FALSE;
+ gui[3] = value[3].boolean ? GL_TRUE : GL_FALSE;
} break;
case ShaderLanguage::TYPE_INT: {
- GLint *gui = (GLint*)data;
- gui[0]=value[0].sint;
+ GLint *gui = (GLint *)data;
+ gui[0] = value[0].sint;
} break;
case ShaderLanguage::TYPE_IVEC2: {
- GLint *gui = (GLint*)data;
-
- for(int i=0;i<2;i++) {
- gui[i]=value[i].sint;
+ GLint *gui = (GLint *)data;
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].sint;
}
} break;
case ShaderLanguage::TYPE_IVEC3: {
- GLint *gui = (GLint*)data;
-
- for(int i=0;i<3;i++) {
- gui[i]=value[i].sint;
+ GLint *gui = (GLint *)data;
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].sint;
}
} break;
case ShaderLanguage::TYPE_IVEC4: {
- GLint *gui = (GLint*)data;
-
- for(int i=0;i<4;i++) {
- gui[i]=value[i].sint;
+ GLint *gui = (GLint *)data;
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].sint;
}
} break;
case ShaderLanguage::TYPE_UINT: {
-
- GLuint *gui = (GLuint*)data;
- gui[0]=value[0].uint;
+ GLuint *gui = (GLuint *)data;
+ gui[0] = value[0].uint;
} break;
case ShaderLanguage::TYPE_UVEC2: {
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
- for(int i=0;i<2;i++) {
- gui[i]=value[i].uint;
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].uint;
}
} break;
case ShaderLanguage::TYPE_UVEC3: {
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
- for(int i=0;i<3;i++) {
- gui[i]=value[i].uint;
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].uint;
}
} break;
case ShaderLanguage::TYPE_UVEC4: {
- GLint *gui = (GLint*)data;
+ GLint *gui = (GLint *)data;
- for(int i=0;i<4;i++) {
- gui[i]=value[i].uint;
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].uint;
}
} break;
case ShaderLanguage::TYPE_FLOAT: {
- GLfloat *gui = (GLfloat*)data;
- gui[0]=value[0].real;
+ GLfloat *gui = (GLfloat *)data;
+ gui[0] = value[0].real;
} break;
case ShaderLanguage::TYPE_VEC2: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- for(int i=0;i<2;i++) {
- gui[i]=value[i].real;
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].real;
}
} break;
case ShaderLanguage::TYPE_VEC3: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- for(int i=0;i<3;i++) {
- gui[i]=value[i].real;
+ for (int i = 0; i < 3; i++) {
+ gui[i] = value[i].real;
}
} break;
case ShaderLanguage::TYPE_VEC4: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- for(int i=0;i<4;i++) {
- gui[i]=value[i].real;
+ for (int i = 0; i < 4; i++) {
+ gui[i] = value[i].real;
}
} break;
case ShaderLanguage::TYPE_MAT2: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- for(int i=0;i<2;i++) {
- gui[i]=value[i].real;
+ for (int i = 0; i < 2; i++) {
+ gui[i] = value[i].real;
}
} break;
case ShaderLanguage::TYPE_MAT3: {
-
-
- GLfloat *gui = (GLfloat*)data;
-
- gui[ 0]=value[0].real;
- gui[ 1]=value[1].real;
- gui[ 2]=value[2].real;
- gui[ 3]=0;
- gui[ 4]=value[3].real;
- gui[ 5]=value[4].real;
- gui[ 6]=value[5].real;
- gui[ 7]=0;
- gui[ 8]=value[6].real;
- gui[ 9]=value[7].real;
- gui[10]=value[8].real;
- gui[11]=0;
+ GLfloat *gui = (GLfloat *)data;
+
+ gui[0] = value[0].real;
+ gui[1] = value[1].real;
+ gui[2] = value[2].real;
+ gui[3] = 0;
+ gui[4] = value[3].real;
+ gui[5] = value[4].real;
+ gui[6] = value[5].real;
+ gui[7] = 0;
+ gui[8] = value[6].real;
+ gui[9] = value[7].real;
+ gui[10] = value[8].real;
+ gui[11] = 0;
} break;
case ShaderLanguage::TYPE_MAT4: {
- GLfloat *gui = (GLfloat*)data;
+ GLfloat *gui = (GLfloat *)data;
- for(int i=0;i<16;i++) {
- gui[i]=value[i].real;
+ for (int i = 0; i < 16; i++) {
+ gui[i] = value[i].real;
}
} break;
default: {}
}
-
}
-
_FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, uint8_t *data) {
- switch(type) {
+ switch (type) {
case ShaderLanguage::TYPE_BOOL:
case ShaderLanguage::TYPE_INT:
case ShaderLanguage::TYPE_UINT:
case ShaderLanguage::TYPE_FLOAT: {
- zeromem(data,4);
+ zeromem(data, 4);
} break;
case ShaderLanguage::TYPE_BVEC2:
case ShaderLanguage::TYPE_IVEC2:
case ShaderLanguage::TYPE_UVEC2:
case ShaderLanguage::TYPE_VEC2: {
- zeromem(data,8);
+ zeromem(data, 8);
} break;
case ShaderLanguage::TYPE_BVEC3:
case ShaderLanguage::TYPE_IVEC3:
@@ -2327,28 +2203,26 @@ _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type,
case ShaderLanguage::TYPE_IVEC4:
case ShaderLanguage::TYPE_UVEC4:
case ShaderLanguage::TYPE_VEC4:
- case ShaderLanguage::TYPE_MAT2:{
+ case ShaderLanguage::TYPE_MAT2: {
- zeromem(data,16);
+ zeromem(data, 16);
} break;
- case ShaderLanguage::TYPE_MAT3:{
+ case ShaderLanguage::TYPE_MAT3: {
- zeromem(data,48);
+ zeromem(data, 48);
} break;
- case ShaderLanguage::TYPE_MAT4:{
- zeromem(data,64);
+ case ShaderLanguage::TYPE_MAT4: {
+ zeromem(data, 64);
} break;
default: {}
}
-
}
-void RasterizerStorageGLES3::_update_material(Material* material) {
+void RasterizerStorageGLES3::_update_material(Material *material) {
if (material->dirty_list.in_list())
- _material_dirty_list.remove( &material->dirty_list );
-
+ _material_dirty_list.remove(&material->dirty_list);
if (material->shader && material->shader->dirty_list.in_list()) {
_update_shader(material->shader);
@@ -2359,90 +2233,85 @@ void RasterizerStorageGLES3::_update_material(Material* material) {
bool can_cast_shadow = false;
bool is_animated = false;
- if (material->shader && material->shader->mode==VS::SHADER_SPATIAL) {
+ if (material->shader && material->shader->mode == VS::SHADER_SPATIAL) {
- if (!material->shader->spatial.uses_alpha && material->shader->spatial.blend_mode==Shader::Spatial::BLEND_MODE_MIX) {
- can_cast_shadow=true;
+ if (!material->shader->spatial.uses_alpha && material->shader->spatial.blend_mode == Shader::Spatial::BLEND_MODE_MIX) {
+ can_cast_shadow = true;
}
if (material->shader->spatial.uses_discard && material->shader->uses_fragment_time) {
- is_animated=true;
+ is_animated = true;
}
if (material->shader->spatial.uses_vertex && material->shader->uses_vertex_time) {
- is_animated=true;
+ is_animated = true;
}
- if (can_cast_shadow!=material->can_cast_shadow_cache || is_animated!=material->is_animated_cache) {
- material->can_cast_shadow_cache=can_cast_shadow;
- material->is_animated_cache=is_animated;
+ if (can_cast_shadow != material->can_cast_shadow_cache || is_animated != material->is_animated_cache) {
+ material->can_cast_shadow_cache = can_cast_shadow;
+ material->is_animated_cache = is_animated;
- for(Map<Geometry*,int>::Element *E=material->geometry_owners.front();E;E=E->next()) {
+ for (Map<Geometry *, int>::Element *E = material->geometry_owners.front(); E; E = E->next()) {
E->key()->material_changed_notify();
}
- for(Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.front();E;E=E->next()) {
+ for (Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.front(); E; E = E->next()) {
E->key()->base_material_changed();
}
-
}
}
-
}
-
//clear ubo if it needs to be cleared
if (material->ubo_size) {
- if (!material->shader || material->shader->ubo_size!=material->ubo_size) {
+ if (!material->shader || material->shader->ubo_size != material->ubo_size) {
//by by ubo
- glDeleteBuffers(1,&material->ubo_id);
- material->ubo_id=0;
- material->ubo_size=0;
+ glDeleteBuffers(1, &material->ubo_id);
+ material->ubo_id = 0;
+ material->ubo_size = 0;
}
}
//create ubo if it needs to be created
- if (material->ubo_size==0 && material->shader && material->shader->ubo_size) {
+ if (material->ubo_size == 0 && material->shader && material->shader->ubo_size) {
glGenBuffers(1, &material->ubo_id);
glBindBuffer(GL_UNIFORM_BUFFER, material->ubo_id);
glBufferData(GL_UNIFORM_BUFFER, material->shader->ubo_size, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
- material->ubo_size=material->shader->ubo_size;
+ material->ubo_size = material->shader->ubo_size;
}
//fill up the UBO if it needs to be filled
if (material->shader && material->ubo_size) {
- uint8_t* local_ubo = (uint8_t*)alloca(material->ubo_size);
+ uint8_t *local_ubo = (uint8_t *)alloca(material->ubo_size);
- for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=material->shader->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = material->shader->uniforms.front(); E; E = E->next()) {
- if (E->get().order<0)
+ if (E->get().order < 0)
continue; // texture, does not go here
//regular uniform
- uint8_t *data = &local_ubo[ material->shader->ubo_offsets[E->get().order] ];
+ uint8_t *data = &local_ubo[material->shader->ubo_offsets[E->get().order]];
- Map<StringName,Variant>::Element *V = material->params.find(E->key());
+ Map<StringName, Variant>::Element *V = material->params.find(E->key());
if (V) {
- //user provided
- _fill_std140_variant_ubo_value(E->get().type,V->get(),data,material->shader->mode==VS::SHADER_SPATIAL);
+ //user provided
+ _fill_std140_variant_ubo_value(E->get().type, V->get(), data, material->shader->mode == VS::SHADER_SPATIAL);
- } else if (E->get().default_value.size()){
+ } else if (E->get().default_value.size()) {
//default value
- _fill_std140_ubo_value(E->get().type,E->get().default_value,data);
+ _fill_std140_ubo_value(E->get().type, E->get().default_value, data);
//value=E->get().default_value;
} else {
//zero because it was not provided
- _fill_std140_ubo_empty(E->get().type,data);
+ _fill_std140_ubo_empty(E->get().type, data);
}
-
-
}
- glBindBuffer(GL_UNIFORM_BUFFER,material->ubo_id);
+ glBindBuffer(GL_UNIFORM_BUFFER, material->ubo_id);
glBufferSubData(GL_UNIFORM_BUFFER, 0, material->ubo_size, local_ubo);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
@@ -2452,70 +2321,64 @@ void RasterizerStorageGLES3::_update_material(Material* material) {
material->textures.resize(material->shader->texture_count);
- for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=material->shader->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, ShaderLanguage::ShaderNode::Uniform>::Element *E = material->shader->uniforms.front(); E; E = E->next()) {
- if (E->get().texture_order<0)
+ if (E->get().texture_order < 0)
continue; // not a texture, does not go here
RID texture;
- Map<StringName,Variant>::Element *V = material->params.find(E->key());
+ Map<StringName, Variant>::Element *V = material->params.find(E->key());
if (V) {
- texture=V->get();
+ texture = V->get();
}
if (!texture.is_valid()) {
- Map<StringName,RID>::Element *W = material->shader->default_textures.find(E->key());
+ Map<StringName, RID>::Element *W = material->shader->default_textures.find(E->key());
if (W) {
- texture=W->get();
+ texture = W->get();
}
}
- material->textures[ E->get().texture_order ]=texture;
-
-
+ material->textures[E->get().texture_order] = texture;
}
-
} else {
material->textures.clear();
}
-
}
-void RasterizerStorageGLES3::_material_add_geometry(RID p_material,Geometry *p_geometry) {
+void RasterizerStorageGLES3::_material_add_geometry(RID p_material, Geometry *p_geometry) {
- Material * material = material_owner.getornull(p_material);
+ Material *material = material_owner.getornull(p_material);
ERR_FAIL_COND(!material);
- Map<Geometry*,int>::Element *I = material->geometry_owners.find(p_geometry);
+ Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
if (I) {
I->get()++;
} else {
- material->geometry_owners[p_geometry]=1;
+ material->geometry_owners[p_geometry] = 1;
}
-
}
-void RasterizerStorageGLES3::_material_remove_geometry(RID p_material,Geometry *p_geometry) {
+void RasterizerStorageGLES3::_material_remove_geometry(RID p_material, Geometry *p_geometry) {
- Material * material = material_owner.getornull(p_material);
+ Material *material = material_owner.getornull(p_material);
ERR_FAIL_COND(!material);
- Map<Geometry*,int>::Element *I = material->geometry_owners.find(p_geometry);
+ Map<Geometry *, int>::Element *I = material->geometry_owners.find(p_geometry);
ERR_FAIL_COND(!I);
I->get()--;
- if (I->get()==0) {
+ if (I->get() == 0) {
material->geometry_owners.erase(I);
}
}
-
void RasterizerStorageGLES3::update_dirty_materials() {
- while( _material_dirty_list.first() ) {
+ while (_material_dirty_list.first()) {
Material *material = _material_dirty_list.first()->self();
@@ -2525,389 +2388,366 @@ void RasterizerStorageGLES3::update_dirty_materials() {
/* MESH API */
-RID RasterizerStorageGLES3::mesh_create(){
+RID RasterizerStorageGLES3::mesh_create() {
- Mesh * mesh = memnew( Mesh );
+ Mesh *mesh = memnew(Mesh);
return mesh_owner.make_rid(mesh);
}
-
-void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh,uint32_t p_format,VS::PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes,const Vector<Rect3>& p_bone_aabbs){
-
+void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh, uint32_t p_format, VS::PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes, const Vector<Rect3> &p_bone_aabbs) {
PoolVector<uint8_t> array = p_array;
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_COND(!(p_format&VS::ARRAY_FORMAT_VERTEX));
+ ERR_FAIL_COND(!(p_format & VS::ARRAY_FORMAT_VERTEX));
//must have index and bones, both.
{
- uint32_t bones_weight = VS::ARRAY_FORMAT_BONES|VS::ARRAY_FORMAT_WEIGHTS;
+ uint32_t bones_weight = VS::ARRAY_FORMAT_BONES | VS::ARRAY_FORMAT_WEIGHTS;
ERR_EXPLAIN("Array must have both bones and weights in format or none.");
- ERR_FAIL_COND( (p_format&bones_weight) && (p_format&bones_weight)!=bones_weight );
+ ERR_FAIL_COND((p_format & bones_weight) && (p_format & bones_weight) != bones_weight);
}
-
//bool has_morph = p_blend_shapes.size();
Surface::Attrib attribs[VS::ARRAY_MAX];
- int stride=0;
+ int stride = 0;
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
- attribs[i].index=i;
+ attribs[i].index = i;
- if (! (p_format&(1<<i) ) ) {
- attribs[i].enabled=false;
- attribs[i].integer=false;
+ if (!(p_format & (1 << i))) {
+ attribs[i].enabled = false;
+ attribs[i].integer = false;
continue;
}
- attribs[i].enabled=true;
- attribs[i].offset=stride;
- attribs[i].integer=false;
+ attribs[i].enabled = true;
+ attribs[i].offset = stride;
+ attribs[i].integer = false;
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
- if (p_format&VS::ARRAY_FLAG_USE_2D_VERTICES) {
- attribs[i].size=2;
+ if (p_format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
+ attribs[i].size = 2;
} else {
- attribs[i].size=(p_format&VS::ARRAY_COMPRESS_VERTEX)?4:3;
+ attribs[i].size = (p_format & VS::ARRAY_COMPRESS_VERTEX) ? 4 : 3;
}
- if (p_format&VS::ARRAY_COMPRESS_VERTEX) {
- attribs[i].type=GL_HALF_FLOAT;
- stride+=attribs[i].size*2;
+ if (p_format & VS::ARRAY_COMPRESS_VERTEX) {
+ attribs[i].type = GL_HALF_FLOAT;
+ stride += attribs[i].size * 2;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=attribs[i].size*4;
+ attribs[i].type = GL_FLOAT;
+ stride += attribs[i].size * 4;
}
- attribs[i].normalized=GL_FALSE;
+ attribs[i].normalized = GL_FALSE;
} break;
case VS::ARRAY_NORMAL: {
- attribs[i].size=3;
+ attribs[i].size = 3;
- if (p_format&VS::ARRAY_COMPRESS_NORMAL) {
- attribs[i].type=GL_BYTE;
- stride+=4; //pad extra byte
- attribs[i].normalized=GL_TRUE;
+ if (p_format & VS::ARRAY_COMPRESS_NORMAL) {
+ attribs[i].type = GL_BYTE;
+ stride += 4; //pad extra byte
+ attribs[i].normalized = GL_TRUE;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=12;
- attribs[i].normalized=GL_FALSE;
+ attribs[i].type = GL_FLOAT;
+ stride += 12;
+ attribs[i].normalized = GL_FALSE;
}
-
-
} break;
case VS::ARRAY_TANGENT: {
- attribs[i].size=4;
+ attribs[i].size = 4;
- if (p_format&VS::ARRAY_COMPRESS_TANGENT) {
- attribs[i].type=GL_BYTE;
- stride+=4;
- attribs[i].normalized=GL_TRUE;
+ if (p_format & VS::ARRAY_COMPRESS_TANGENT) {
+ attribs[i].type = GL_BYTE;
+ stride += 4;
+ attribs[i].normalized = GL_TRUE;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=16;
- attribs[i].normalized=GL_FALSE;
+ attribs[i].type = GL_FLOAT;
+ stride += 16;
+ attribs[i].normalized = GL_FALSE;
}
-
} break;
case VS::ARRAY_COLOR: {
- attribs[i].size=4;
+ attribs[i].size = 4;
- if (p_format&VS::ARRAY_COMPRESS_COLOR) {
- attribs[i].type=GL_UNSIGNED_BYTE;
- stride+=4;
- attribs[i].normalized=GL_TRUE;
+ if (p_format & VS::ARRAY_COMPRESS_COLOR) {
+ attribs[i].type = GL_UNSIGNED_BYTE;
+ stride += 4;
+ attribs[i].normalized = GL_TRUE;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=16;
- attribs[i].normalized=GL_FALSE;
+ attribs[i].type = GL_FLOAT;
+ stride += 16;
+ attribs[i].normalized = GL_FALSE;
}
-
} break;
case VS::ARRAY_TEX_UV: {
- attribs[i].size=2;
+ attribs[i].size = 2;
- if (p_format&VS::ARRAY_COMPRESS_TEX_UV) {
- attribs[i].type=GL_HALF_FLOAT;
- stride+=4;
+ if (p_format & VS::ARRAY_COMPRESS_TEX_UV) {
+ attribs[i].type = GL_HALF_FLOAT;
+ stride += 4;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=8;
+ attribs[i].type = GL_FLOAT;
+ stride += 8;
}
- attribs[i].normalized=GL_FALSE;
-
+ attribs[i].normalized = GL_FALSE;
} break;
case VS::ARRAY_TEX_UV2: {
- attribs[i].size=2;
+ attribs[i].size = 2;
- if (p_format&VS::ARRAY_COMPRESS_TEX_UV2) {
- attribs[i].type=GL_HALF_FLOAT;
- stride+=4;
+ if (p_format & VS::ARRAY_COMPRESS_TEX_UV2) {
+ attribs[i].type = GL_HALF_FLOAT;
+ stride += 4;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=8;
+ attribs[i].type = GL_FLOAT;
+ stride += 8;
}
- attribs[i].normalized=GL_FALSE;
-
-
+ attribs[i].normalized = GL_FALSE;
} break;
case VS::ARRAY_BONES: {
- attribs[i].size=4;
+ attribs[i].size = 4;
- if (p_format&VS::ARRAY_FLAG_USE_16_BIT_BONES) {
- attribs[i].type=GL_UNSIGNED_SHORT;
- stride+=8;
+ if (p_format & VS::ARRAY_FLAG_USE_16_BIT_BONES) {
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ stride += 8;
} else {
- attribs[i].type=GL_UNSIGNED_BYTE;
- stride+=4;
+ attribs[i].type = GL_UNSIGNED_BYTE;
+ stride += 4;
}
- attribs[i].normalized=GL_FALSE;
- attribs[i].integer=true;
-
-
+ attribs[i].normalized = GL_FALSE;
+ attribs[i].integer = true;
} break;
case VS::ARRAY_WEIGHTS: {
- attribs[i].size=4;
+ attribs[i].size = 4;
- if (p_format&VS::ARRAY_COMPRESS_WEIGHTS) {
+ if (p_format & VS::ARRAY_COMPRESS_WEIGHTS) {
- attribs[i].type=GL_UNSIGNED_SHORT;
- stride+=8;
- attribs[i].normalized=GL_TRUE;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ stride += 8;
+ attribs[i].normalized = GL_TRUE;
} else {
- attribs[i].type=GL_FLOAT;
- stride+=16;
- attribs[i].normalized=GL_FALSE;
+ attribs[i].type = GL_FLOAT;
+ stride += 16;
+ attribs[i].normalized = GL_FALSE;
}
} break;
case VS::ARRAY_INDEX: {
- attribs[i].size=1;
+ attribs[i].size = 1;
- if (p_vertex_count>=(1<<16)) {
- attribs[i].type=GL_UNSIGNED_INT;
- attribs[i].stride=4;
+ if (p_vertex_count >= (1 << 16)) {
+ attribs[i].type = GL_UNSIGNED_INT;
+ attribs[i].stride = 4;
} else {
- attribs[i].type=GL_UNSIGNED_SHORT;
- attribs[i].stride=2;
+ attribs[i].type = GL_UNSIGNED_SHORT;
+ attribs[i].stride = 2;
}
- attribs[i].normalized=GL_FALSE;
+ attribs[i].normalized = GL_FALSE;
} break;
-
}
}
- for(int i=0;i<VS::ARRAY_MAX-1;i++) {
- attribs[i].stride=stride;
+ for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
+ attribs[i].stride = stride;
}
//validate sizes
int array_size = stride * p_vertex_count;
- int index_array_size=0;
- if (array.size()!=array_size && array.size()+p_vertex_count*2 == array_size) {
+ int index_array_size = 0;
+ if (array.size() != array_size && array.size() + p_vertex_count * 2 == array_size) {
//old format, convert
array = PoolVector<uint8_t>();
- array.resize( p_array.size()+p_vertex_count*2 );
+ array.resize(p_array.size() + p_vertex_count * 2);
PoolVector<uint8_t>::Write w = array.write();
PoolVector<uint8_t>::Read r = p_array.read();
- uint16_t *w16 = (uint16_t*)w.ptr();
- const uint16_t *r16 = (uint16_t*)r.ptr();
+ uint16_t *w16 = (uint16_t *)w.ptr();
+ const uint16_t *r16 = (uint16_t *)r.ptr();
uint16_t one = Math::make_half_float(1);
- for(int i=0;i<p_vertex_count;i++) {
+ for (int i = 0; i < p_vertex_count; i++) {
*w16++ = *r16++;
*w16++ = *r16++;
*w16++ = *r16++;
*w16++ = one;
- for(int j=0;j<(stride/2)-4;j++) {
+ for (int j = 0; j < (stride / 2) - 4; j++) {
*w16++ = *r16++;
}
}
-
}
- ERR_FAIL_COND(array.size()!=array_size);
+ ERR_FAIL_COND(array.size() != array_size);
- if (p_format&VS::ARRAY_FORMAT_INDEX) {
+ if (p_format & VS::ARRAY_FORMAT_INDEX) {
- index_array_size=attribs[VS::ARRAY_INDEX].stride*p_index_count;
+ index_array_size = attribs[VS::ARRAY_INDEX].stride * p_index_count;
}
+ ERR_FAIL_COND(p_index_array.size() != index_array_size);
- ERR_FAIL_COND(p_index_array.size()!=index_array_size);
-
- ERR_FAIL_COND(p_blend_shapes.size()!=mesh->blend_shape_count);
+ ERR_FAIL_COND(p_blend_shapes.size() != mesh->blend_shape_count);
- for(int i=0;i<p_blend_shapes.size();i++) {
- ERR_FAIL_COND(p_blend_shapes[i].size()!=array_size);
+ for (int i = 0; i < p_blend_shapes.size(); i++) {
+ ERR_FAIL_COND(p_blend_shapes[i].size() != array_size);
}
//ok all valid, create stuff
- Surface * surface = memnew( Surface );
-
- surface->active=true;
- surface->array_len=p_vertex_count;
- surface->index_array_len=p_index_count;
- surface->array_byte_size=array.size();
- surface->index_array_byte_size=p_index_array.size();
- surface->primitive=p_primitive;
- surface->mesh=mesh;
- surface->format=p_format;
- surface->skeleton_bone_aabb=p_bone_aabbs;
+ Surface *surface = memnew(Surface);
+
+ surface->active = true;
+ surface->array_len = p_vertex_count;
+ surface->index_array_len = p_index_count;
+ surface->array_byte_size = array.size();
+ surface->index_array_byte_size = p_index_array.size();
+ surface->primitive = p_primitive;
+ surface->mesh = mesh;
+ surface->format = p_format;
+ surface->skeleton_bone_aabb = p_bone_aabbs;
surface->skeleton_bone_used.resize(surface->skeleton_bone_aabb.size());
- surface->aabb=p_aabb;
- surface->max_bone=p_bone_aabbs.size();
+ surface->aabb = p_aabb;
+ surface->max_bone = p_bone_aabbs.size();
- for(int i=0;i<surface->skeleton_bone_used.size();i++) {
- if (surface->skeleton_bone_aabb[i].size.x<0 || surface->skeleton_bone_aabb[i].size.y<0 || surface->skeleton_bone_aabb[i].size.z<0) {
- surface->skeleton_bone_used[i]=false;
+ for (int i = 0; i < surface->skeleton_bone_used.size(); i++) {
+ if (surface->skeleton_bone_aabb[i].size.x < 0 || surface->skeleton_bone_aabb[i].size.y < 0 || surface->skeleton_bone_aabb[i].size.z < 0) {
+ surface->skeleton_bone_used[i] = false;
} else {
- surface->skeleton_bone_used[i]=true;
+ surface->skeleton_bone_used[i] = true;
}
}
- for(int i=0;i<VS::ARRAY_MAX;i++) {
- surface->attribs[i]=attribs[i];
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
+ surface->attribs[i] = attribs[i];
}
{
PoolVector<uint8_t>::Read vr = array.read();
- glGenBuffers(1,&surface->vertex_id);
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
- glBufferData(GL_ARRAY_BUFFER,array_size,vr.ptr(),GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, array_size, vr.ptr(), GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
-
- if (p_format&VS::ARRAY_FORMAT_INDEX) {
+ if (p_format & VS::ARRAY_FORMAT_INDEX) {
PoolVector<uint8_t>::Read ir = p_index_array.read();
- glGenBuffers(1,&surface->index_id);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,index_array_size,ir.ptr(),GL_STATIC_DRAW);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
-
-
+ glGenBuffers(1, &surface->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, index_array_size, ir.ptr(), GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
}
//generate arrays for faster state switching
- for(int ai=0;ai<2;ai++) {
+ for (int ai = 0; ai < 2; ai++) {
- if (ai==0) {
+ if (ai == 0) {
//for normal draw
- glGenVertexArrays(1,&surface->array_id);
+ glGenVertexArrays(1, &surface->array_id);
glBindVertexArray(surface->array_id);
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
- } else if (ai==1) {
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
+ } else if (ai == 1) {
//for instancing draw (can be changed and no one cares)
- glGenVertexArrays(1,&surface->instancing_array_id);
+ glGenVertexArrays(1, &surface->instancing_array_id);
glBindVertexArray(surface->instancing_array_id);
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
}
-
- for(int i=0;i<VS::ARRAY_MAX-1;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
if (!attribs[i].enabled)
continue;
if (attribs[i].integer) {
- glVertexAttribIPointer(attribs[i].index,attribs[i].size,attribs[i].type,attribs[i].stride,((uint8_t*)0)+attribs[i].offset);
+ glVertexAttribIPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].stride, ((uint8_t *)0) + attribs[i].offset);
} else {
- glVertexAttribPointer(attribs[i].index,attribs[i].size,attribs[i].type,attribs[i].normalized,attribs[i].stride,((uint8_t*)0)+attribs[i].offset);
+ glVertexAttribPointer(attribs[i].index, attribs[i].size, attribs[i].type, attribs[i].normalized, attribs[i].stride, ((uint8_t *)0) + attribs[i].offset);
}
glEnableVertexAttribArray(attribs[i].index);
-
}
if (surface->index_id) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
}
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
-
}
{
//blend shapes
- for(int i=0;i<p_blend_shapes.size();i++) {
+ for (int i = 0; i < p_blend_shapes.size(); i++) {
Surface::BlendShape mt;
PoolVector<uint8_t>::Read vr = p_blend_shapes[i].read();
- glGenBuffers(1,&mt.vertex_id);
- glBindBuffer(GL_ARRAY_BUFFER,mt.vertex_id);
- glBufferData(GL_ARRAY_BUFFER,array_size,vr.ptr(),GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &mt.vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, mt.vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, array_size, vr.ptr(), GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
- glGenVertexArrays(1,&mt.array_id);
+ glGenVertexArrays(1, &mt.array_id);
glBindVertexArray(mt.array_id);
- glBindBuffer(GL_ARRAY_BUFFER,mt.vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, mt.vertex_id);
- for(int j=0;j<VS::ARRAY_MAX-1;j++) {
+ for (int j = 0; j < VS::ARRAY_MAX - 1; j++) {
if (!attribs[j].enabled)
continue;
if (attribs[j].integer) {
- glVertexAttribIPointer(attribs[j].index,attribs[j].size,attribs[j].type,attribs[j].stride,((uint8_t*)0)+attribs[j].offset);
+ glVertexAttribIPointer(attribs[j].index, attribs[j].size, attribs[j].type, attribs[j].stride, ((uint8_t *)0) + attribs[j].offset);
} else {
- glVertexAttribPointer(attribs[j].index,attribs[j].size,attribs[j].type,attribs[j].normalized,attribs[j].stride,((uint8_t*)0)+attribs[j].offset);
+ glVertexAttribPointer(attribs[j].index, attribs[j].size, attribs[j].type, attribs[j].normalized, attribs[j].stride, ((uint8_t *)0) + attribs[j].offset);
}
glEnableVertexAttribArray(attribs[j].index);
-
}
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
surface->blend_shapes.push_back(mt);
-
}
}
@@ -2915,105 +2755,98 @@ void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh,uint32_t p_format,VS::P
mesh->instance_change_notify();
}
-void RasterizerStorageGLES3::mesh_set_blend_shape_count(RID p_mesh,int p_amount){
+void RasterizerStorageGLES3::mesh_set_blend_shape_count(RID p_mesh, int p_amount) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
+ ERR_FAIL_COND(mesh->surfaces.size() != 0);
+ ERR_FAIL_COND(p_amount < 0);
- ERR_FAIL_COND(mesh->surfaces.size()!=0);
- ERR_FAIL_COND(p_amount<0);
-
- mesh->blend_shape_count=p_amount;
-
+ mesh->blend_shape_count = p_amount;
}
-int RasterizerStorageGLES3::mesh_get_blend_shape_count(RID p_mesh) const{
+int RasterizerStorageGLES3::mesh_get_blend_shape_count(RID p_mesh) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,0);
+ ERR_FAIL_COND_V(!mesh, 0);
return mesh->blend_shape_count;
}
-
-void RasterizerStorageGLES3::mesh_set_blend_shape_mode(RID p_mesh,VS::BlendShapeMode p_mode){
+void RasterizerStorageGLES3::mesh_set_blend_shape_mode(RID p_mesh, VS::BlendShapeMode p_mode) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- mesh->blend_shape_mode=p_mode;
-
+ mesh->blend_shape_mode = p_mode;
}
-VS::BlendShapeMode RasterizerStorageGLES3::mesh_get_blend_shape_mode(RID p_mesh) const{
+VS::BlendShapeMode RasterizerStorageGLES3::mesh_get_blend_shape_mode(RID p_mesh) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,VS::BLEND_SHAPE_MODE_NORMALIZED);
+ ERR_FAIL_COND_V(!mesh, VS::BLEND_SHAPE_MODE_NORMALIZED);
return mesh->blend_shape_mode;
}
-void RasterizerStorageGLES3::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material){
+void RasterizerStorageGLES3::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_surface,mesh->surfaces.size());
+ ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
- if (mesh->surfaces[p_surface]->material==p_material)
+ if (mesh->surfaces[p_surface]->material == p_material)
return;
if (mesh->surfaces[p_surface]->material.is_valid()) {
- _material_remove_geometry(mesh->surfaces[p_surface]->material,mesh->surfaces[p_surface]);
+ _material_remove_geometry(mesh->surfaces[p_surface]->material, mesh->surfaces[p_surface]);
}
- mesh->surfaces[p_surface]->material=p_material;
+ mesh->surfaces[p_surface]->material = p_material;
if (mesh->surfaces[p_surface]->material.is_valid()) {
- _material_add_geometry(mesh->surfaces[p_surface]->material,mesh->surfaces[p_surface]);
+ _material_add_geometry(mesh->surfaces[p_surface]->material, mesh->surfaces[p_surface]);
}
mesh->instance_material_change_notify();
-
-
}
-RID RasterizerStorageGLES3::mesh_surface_get_material(RID p_mesh, int p_surface) const{
+RID RasterizerStorageGLES3::mesh_surface_get_material(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,RID());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),RID());
+ ERR_FAIL_COND_V(!mesh, RID());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID());
return mesh->surfaces[p_surface]->material;
}
-int RasterizerStorageGLES3::mesh_surface_get_array_len(RID p_mesh, int p_surface) const{
+int RasterizerStorageGLES3::mesh_surface_get_array_len(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,0);
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0);
+ ERR_FAIL_COND_V(!mesh, 0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
return mesh->surfaces[p_surface]->array_len;
-
}
-int RasterizerStorageGLES3::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const{
+int RasterizerStorageGLES3::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,0);
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0);
+ ERR_FAIL_COND_V(!mesh, 0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
return mesh->surfaces[p_surface]->index_array_len;
}
-PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, int p_surface) const{
+PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,PoolVector<uint8_t>());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!mesh, PoolVector<uint8_t>());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), PoolVector<uint8_t>());
Surface *surface = mesh->surfaces[p_surface];
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
- void * data = glMapBufferRange(GL_ARRAY_BUFFER,0,surface->array_byte_size,GL_MAP_READ_BIT);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
+ void *data = glMapBufferRange(GL_ARRAY_BUFFER, 0, surface->array_byte_size, GL_MAP_READ_BIT);
- ERR_FAIL_COND_V(!data,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!data, PoolVector<uint8_t>());
PoolVector<uint8_t> ret;
ret.resize(surface->array_byte_size);
@@ -3021,27 +2854,26 @@ PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, i
{
PoolVector<uint8_t>::Write w = ret.write();
- copymem(w.ptr(),data,surface->array_byte_size);
+ copymem(w.ptr(), data, surface->array_byte_size);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
-
return ret;
}
PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,PoolVector<uint8_t>());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!mesh, PoolVector<uint8_t>());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), PoolVector<uint8_t>());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V(surface->index_array_len==0,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(surface->index_array_len == 0, PoolVector<uint8_t>());
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
- void * data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER,0,surface->index_array_byte_size,GL_MAP_READ_BIT);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
+ void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, surface->index_array_byte_size, GL_MAP_READ_BIT);
- ERR_FAIL_COND_V(!data,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!data, PoolVector<uint8_t>());
PoolVector<uint8_t> ret;
ret.resize(surface->index_array_byte_size);
@@ -3049,7 +2881,7 @@ PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_m
{
PoolVector<uint8_t>::Write w = ret.write();
- copymem(w.ptr(),data,surface->index_array_byte_size);
+ copymem(w.ptr(), data, surface->index_array_byte_size);
}
glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
@@ -3057,23 +2889,21 @@ PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_m
return ret;
}
-
-uint32_t RasterizerStorageGLES3::mesh_surface_get_format(RID p_mesh, int p_surface) const{
+uint32_t RasterizerStorageGLES3::mesh_surface_get_format(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,0);
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0);
+ ERR_FAIL_COND_V(!mesh, 0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
return mesh->surfaces[p_surface]->format;
-
}
-VS::PrimitiveType RasterizerStorageGLES3::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const{
+VS::PrimitiveType RasterizerStorageGLES3::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,VS::PRIMITIVE_MAX);
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),VS::PRIMITIVE_MAX);
+ ERR_FAIL_COND_V(!mesh, VS::PRIMITIVE_MAX);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_MAX);
return mesh->surfaces[p_surface]->primitive;
}
@@ -3081,27 +2911,25 @@ VS::PrimitiveType RasterizerStorageGLES3::mesh_surface_get_primitive_type(RID p_
Rect3 RasterizerStorageGLES3::mesh_surface_get_aabb(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,Rect3());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Rect3());
+ ERR_FAIL_COND_V(!mesh, Rect3());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Rect3());
return mesh->surfaces[p_surface]->aabb;
-
-
}
-Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const{
+Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,Vector<PoolVector<uint8_t> >());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Vector<PoolVector<uint8_t> >());
+ ERR_FAIL_COND_V(!mesh, Vector<PoolVector<uint8_t> >());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Vector<PoolVector<uint8_t> >());
Vector<PoolVector<uint8_t> > bsarr;
- for(int i=0;i<mesh->surfaces[p_surface]->blend_shapes.size();i++) {
+ for (int i = 0; i < mesh->surfaces[p_surface]->blend_shapes.size(); i++) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh->surfaces[p_surface]->blend_shapes[i].vertex_id);
- void * data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER,0,mesh->surfaces[p_surface]->array_byte_size,GL_MAP_READ_BIT);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->surfaces[p_surface]->blend_shapes[i].vertex_id);
+ void *data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, mesh->surfaces[p_surface]->array_byte_size, GL_MAP_READ_BIT);
- ERR_FAIL_COND_V(!data,Vector<PoolVector<uint8_t> >());
+ ERR_FAIL_COND_V(!data, Vector<PoolVector<uint8_t> >());
PoolVector<uint8_t> ret;
ret.resize(mesh->surfaces[p_surface]->array_byte_size);
@@ -3109,7 +2937,7 @@ Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shap
{
PoolVector<uint8_t>::Write w = ret.write();
- copymem(w.ptr(),data,mesh->surfaces[p_surface]->array_byte_size);
+ copymem(w.ptr(), data, mesh->surfaces[p_surface]->array_byte_size);
}
bsarr.push_back(ret);
@@ -3118,42 +2946,39 @@ Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shap
}
return bsarr;
-
}
-Vector<Rect3> RasterizerStorageGLES3::mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const{
+Vector<Rect3> RasterizerStorageGLES3::mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,Vector<Rect3 >());
- ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Vector<Rect3 >());
+ ERR_FAIL_COND_V(!mesh, Vector<Rect3>());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), Vector<Rect3>());
return mesh->surfaces[p_surface]->skeleton_bone_aabb;
-
}
-
-void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface){
+void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_surface,mesh->surfaces.size());
+ ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
Surface *surface = mesh->surfaces[p_surface];
if (surface->material.is_valid()) {
- _material_remove_geometry(surface->material,mesh->surfaces[p_surface]);
+ _material_remove_geometry(surface->material, mesh->surfaces[p_surface]);
}
- glDeleteBuffers(1,&surface->vertex_id);
+ glDeleteBuffers(1, &surface->vertex_id);
if (surface->index_id) {
- glDeleteBuffers(1,&surface->index_id);
+ glDeleteBuffers(1, &surface->index_id);
}
- glDeleteVertexArrays(1,&surface->array_id);
+ glDeleteVertexArrays(1, &surface->array_id);
- for(int i=0;i<surface->blend_shapes.size();i++) {
+ for (int i = 0; i < surface->blend_shapes.size(); i++) {
- glDeleteBuffers(1,&surface->blend_shapes[i].vertex_id);
- glDeleteVertexArrays(1,&surface->blend_shapes[i].array_id);
+ glDeleteBuffers(1, &surface->blend_shapes[i].vertex_id);
+ glDeleteVertexArrays(1, &surface->blend_shapes[i].array_id);
}
mesh->instance_material_change_notify();
@@ -3164,115 +2989,109 @@ void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface){
mesh->instance_change_notify();
}
-int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const{
+int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,0);
+ ERR_FAIL_COND_V(!mesh, 0);
return mesh->surfaces.size();
-
}
-void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb){
+void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- mesh->custom_aabb=p_aabb;
+ mesh->custom_aabb = p_aabb;
}
-Rect3 RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const{
+Rect3 RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const {
const Mesh *mesh = mesh_owner.getornull(p_mesh);
- ERR_FAIL_COND_V(!mesh,Rect3());
+ ERR_FAIL_COND_V(!mesh, Rect3());
return mesh->custom_aabb;
-
}
-Rect3 RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh,RID p_skeleton) const{
+Rect3 RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh, RID p_skeleton) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,Rect3());
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, Rect3());
- if (mesh->custom_aabb!=Rect3())
+ if (mesh->custom_aabb != Rect3())
return mesh->custom_aabb;
- Skeleton *sk=NULL;
+ Skeleton *sk = NULL;
if (p_skeleton.is_valid())
- sk=skeleton_owner.get(p_skeleton);
+ sk = skeleton_owner.get(p_skeleton);
Rect3 aabb;
- if (sk && sk->size!=0) {
+ if (sk && sk->size != 0) {
-
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
Rect3 laabb;
- if (mesh->surfaces[i]->format&VS::ARRAY_FORMAT_BONES && mesh->surfaces[i]->skeleton_bone_aabb.size()) {
-
+ if (mesh->surfaces[i]->format & VS::ARRAY_FORMAT_BONES && mesh->surfaces[i]->skeleton_bone_aabb.size()) {
int bs = mesh->surfaces[i]->skeleton_bone_aabb.size();
const Rect3 *skbones = mesh->surfaces[i]->skeleton_bone_aabb.ptr();
const bool *skused = mesh->surfaces[i]->skeleton_bone_used.ptr();
int sbs = sk->size;
- ERR_CONTINUE(bs>sbs);
+ ERR_CONTINUE(bs > sbs);
float *skb = sk->bones.ptr();
-
-
- bool first=true;
+ bool first = true;
if (sk->use_2d) {
- for(int j=0;j<bs;j++) {
+ for (int j = 0; j < bs; j++) {
if (!skused[j])
continue;
- float *dataptr = &skb[8*j];
+ float *dataptr = &skb[8 * j];
Transform mtx;
- mtx.basis.elements[0][0]=dataptr[ 0];
- mtx.basis.elements[0][1]=dataptr[ 1];
- mtx.origin[0]=dataptr[ 3];
- mtx.basis.elements[1][0]=dataptr[ 4];
- mtx.basis.elements[1][1]=dataptr[ 5];
- mtx.origin[1]=dataptr[ 7];
+ mtx.basis.elements[0][0] = dataptr[0];
+ mtx.basis.elements[0][1] = dataptr[1];
+ mtx.origin[0] = dataptr[3];
+ mtx.basis.elements[1][0] = dataptr[4];
+ mtx.basis.elements[1][1] = dataptr[5];
+ mtx.origin[1] = dataptr[7];
- Rect3 baabb = mtx.xform( skbones[j] );
+ Rect3 baabb = mtx.xform(skbones[j]);
if (first) {
- laabb=baabb;
- first=false;
+ laabb = baabb;
+ first = false;
} else {
laabb.merge_with(baabb);
}
}
} else {
- for(int j=0;j<bs;j++) {
+ for (int j = 0; j < bs; j++) {
if (!skused[j])
continue;
- float *dataptr = &skb[12*j];
+ float *dataptr = &skb[12 * j];
Transform mtx;
- mtx.basis.elements[0][0]=dataptr[ 0];
- mtx.basis.elements[0][1]=dataptr[ 1];
- mtx.basis.elements[0][2]=dataptr[ 2];
- mtx.origin.x=dataptr[ 3];
- mtx.basis.elements[1][0]=dataptr[ 4];
- mtx.basis.elements[1][1]=dataptr[ 5];
- mtx.basis.elements[1][2]=dataptr[ 6];
- mtx.origin.y=dataptr[ 7];
- mtx.basis.elements[2][0]=dataptr[ 8];
- mtx.basis.elements[2][1]=dataptr[ 9];
- mtx.basis.elements[2][2]=dataptr[10];
- mtx.origin.z=dataptr[11];
-
- Rect3 baabb = mtx.xform ( skbones[j] );
+ mtx.basis.elements[0][0] = dataptr[0];
+ mtx.basis.elements[0][1] = dataptr[1];
+ mtx.basis.elements[0][2] = dataptr[2];
+ mtx.origin.x = dataptr[3];
+ mtx.basis.elements[1][0] = dataptr[4];
+ mtx.basis.elements[1][1] = dataptr[5];
+ mtx.basis.elements[1][2] = dataptr[6];
+ mtx.origin.y = dataptr[7];
+ mtx.basis.elements[2][0] = dataptr[8];
+ mtx.basis.elements[2][1] = dataptr[9];
+ mtx.basis.elements[2][2] = dataptr[10];
+ mtx.origin.z = dataptr[11];
+
+ Rect3 baabb = mtx.xform(skbones[j]);
if (first) {
- laabb=baabb;
- first=false;
+ laabb = baabb;
+ first = false;
} else {
laabb.merge_with(baabb);
}
@@ -3281,36 +3100,34 @@ Rect3 RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh,RID p_skeleton) const{
} else {
- laabb=mesh->surfaces[i]->aabb;
+ laabb = mesh->surfaces[i]->aabb;
}
- if (i==0)
- aabb=laabb;
+ if (i == 0)
+ aabb = laabb;
else
aabb.merge_with(laabb);
}
} else {
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
- if (i==0)
- aabb=mesh->surfaces[i]->aabb;
+ if (i == 0)
+ aabb = mesh->surfaces[i]->aabb;
else
aabb.merge_with(mesh->surfaces[i]->aabb);
}
-
}
return aabb;
-
}
-void RasterizerStorageGLES3::mesh_clear(RID p_mesh){
+void RasterizerStorageGLES3::mesh_clear(RID p_mesh) {
Mesh *mesh = mesh_owner.getornull(p_mesh);
ERR_FAIL_COND(!mesh);
- while(mesh->surfaces.size()) {
- mesh_remove_surface(p_mesh,0);
+ while (mesh->surfaces.size()) {
+ mesh_remove_surface(p_mesh, 0);
}
}
@@ -3318,7 +3135,7 @@ void RasterizerStorageGLES3::mesh_render_blend_shapes(Surface *s, float *p_weigh
glBindVertexArray(s->array_id);
- BlendShapeShaderGLES3::Conditionals cond[VS::ARRAY_MAX-1]={
+ BlendShapeShaderGLES3::Conditionals cond[VS::ARRAY_MAX - 1] = {
BlendShapeShaderGLES3::ENABLE_NORMAL, //will be ignored
BlendShapeShaderGLES3::ENABLE_NORMAL,
BlendShapeShaderGLES3::ENABLE_TANGENT,
@@ -3329,197 +3146,190 @@ void RasterizerStorageGLES3::mesh_render_blend_shapes(Surface *s, float *p_weigh
BlendShapeShaderGLES3::ENABLE_SKELETON,
};
- int stride=0;
+ int stride = 0;
- if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) {
- stride=2*4;
+ if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
+ stride = 2 * 4;
} else {
- stride=3*4;
- }
-
- static const int sizes[VS::ARRAY_MAX-1]={
- 3*4,
- 3*4,
- 4*4,
- 4*4,
- 2*4,
- 2*4,
- 4*4,
- 4*4
+ stride = 3 * 4;
+ }
+
+ static const int sizes[VS::ARRAY_MAX - 1] = {
+ 3 * 4,
+ 3 * 4,
+ 4 * 4,
+ 4 * 4,
+ 2 * 4,
+ 2 * 4,
+ 4 * 4,
+ 4 * 4
};
- for(int i=1;i<VS::ARRAY_MAX-1;i++) {
- shaders.blend_shapes.set_conditional(cond[i],s->format&(1<<i)); //enable conditional for format
- if (s->format&(1<<i)) {
- stride+=sizes[i];
+ for (int i = 1; i < VS::ARRAY_MAX - 1; i++) {
+ shaders.blend_shapes.set_conditional(cond[i], s->format & (1 << i)); //enable conditional for format
+ if (s->format & (1 << i)) {
+ stride += sizes[i];
}
}
-
//copy all first
- float base_weight=1.0;
+ float base_weight = 1.0;
int mtc = s->blend_shapes.size();
- if (s->mesh->blend_shape_mode==VS::BLEND_SHAPE_MODE_NORMALIZED) {
+ if (s->mesh->blend_shape_mode == VS::BLEND_SHAPE_MODE_NORMALIZED) {
- for(int i=0;i<mtc;i++) {
- base_weight-=p_weights[i];
+ for (int i = 0; i < mtc; i++) {
+ base_weight -= p_weights[i];
}
}
-
-
- shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND,false); //first pass does not blend
- shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::USE_2D_VERTEX,s->format&VS::ARRAY_FLAG_USE_2D_VERTICES); //use 2D vertices if needed
+ shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND, false); //first pass does not blend
+ shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::USE_2D_VERTEX, s->format & VS::ARRAY_FLAG_USE_2D_VERTICES); //use 2D vertices if needed
shaders.blend_shapes.bind();
- shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT,base_weight);
+ shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT, base_weight);
glEnable(GL_RASTERIZER_DISCARD);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[0]);
glBeginTransformFeedback(GL_POINTS);
- glDrawArrays(GL_POINTS,0,s->array_len);
+ glDrawArrays(GL_POINTS, 0, s->array_len);
glEndTransformFeedback();
-
- shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND,true); //first pass does not blend
+ shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND, true); //first pass does not blend
shaders.blend_shapes.bind();
- for(int ti=0;ti<mtc;ti++) {
+ for (int ti = 0; ti < mtc; ti++) {
float weight = p_weights[ti];
- if (weight<0.001) //not bother with this one
+ if (weight < 0.001) //not bother with this one
continue;
glBindVertexArray(s->blend_shapes[ti].array_id);
glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[1]);
- shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT,weight);
+ shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT, weight);
- int ofs=0;
- for(int i=0;i<VS::ARRAY_MAX-1;i++) {
+ int ofs = 0;
+ for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
- if (s->format&(1<<i)) {
- glEnableVertexAttribArray(i+8);
- switch(i) {
+ if (s->format & (1 << i)) {
+ glEnableVertexAttribArray(i + 8);
+ switch (i) {
case VS::ARRAY_VERTEX: {
- if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) {
- glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
+ glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} else {
- glVertexAttribPointer(i+8,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=3*4;
+ glVertexAttribPointer(i + 8, 3, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 3 * 4;
}
} break;
case VS::ARRAY_NORMAL: {
- glVertexAttribPointer(i+8,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=3*4;
+ glVertexAttribPointer(i + 8, 3, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 3 * 4;
} break;
case VS::ARRAY_TANGENT: {
- glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_COLOR: {
- glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_TEX_UV: {
- glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} break;
case VS::ARRAY_TEX_UV2: {
- glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ glVertexAttribPointer(i + 8, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} break;
case VS::ARRAY_BONES: {
- glVertexAttribIPointer(i+8,4,GL_UNSIGNED_INT,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribIPointer(i + 8, 4, GL_UNSIGNED_INT, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_WEIGHTS: {
- glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i + 8, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
}
} else {
- glDisableVertexAttribArray(i+8);
+ glDisableVertexAttribArray(i + 8);
}
}
glBeginTransformFeedback(GL_POINTS);
- glDrawArrays(GL_POINTS,0,s->array_len);
+ glDrawArrays(GL_POINTS, 0, s->array_len);
glEndTransformFeedback();
-
- SWAP(resources.transform_feedback_buffers[0],resources.transform_feedback_buffers[1]);
-
+ SWAP(resources.transform_feedback_buffers[0], resources.transform_feedback_buffers[1]);
}
glDisable(GL_RASTERIZER_DISCARD);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
-
glBindVertexArray(resources.transform_feedback_array);
glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]);
- int ofs=0;
- for(int i=0;i<VS::ARRAY_MAX-1;i++) {
+ int ofs = 0;
+ for (int i = 0; i < VS::ARRAY_MAX - 1; i++) {
- if (s->format&(1<<i)) {
+ if (s->format & (1 << i)) {
glEnableVertexAttribArray(i);
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
- if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) {
- glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ if (s->format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
+ glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} else {
- glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=3*4;
+ glVertexAttribPointer(i, 3, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 3 * 4;
}
} break;
case VS::ARRAY_NORMAL: {
- glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=3*4;
+ glVertexAttribPointer(i, 3, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 3 * 4;
} break;
case VS::ARRAY_TANGENT: {
- glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_COLOR: {
- glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_TEX_UV: {
- glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} break;
case VS::ARRAY_TEX_UV2: {
- glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=2*4;
+ glVertexAttribPointer(i, 2, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 2 * 4;
} break;
case VS::ARRAY_BONES: {
- glVertexAttribIPointer(i,4,GL_UNSIGNED_INT,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribIPointer(i, 4, GL_UNSIGNED_INT, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
case VS::ARRAY_WEIGHTS: {
- glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs);
- ofs+=4*4;
+ glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, stride, ((uint8_t *)0) + ofs);
+ ofs += 4 * 4;
} break;
}
@@ -3530,131 +3340,126 @@ void RasterizerStorageGLES3::mesh_render_blend_shapes(Surface *s, float *p_weigh
}
if (s->index_array_len) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
}
-
}
/* MULTIMESH API */
+RID RasterizerStorageGLES3::multimesh_create() {
-RID RasterizerStorageGLES3::multimesh_create(){
-
- MultiMesh *multimesh = memnew( MultiMesh );
+ MultiMesh *multimesh = memnew(MultiMesh);
return multimesh_owner.make_rid(multimesh);
}
-void RasterizerStorageGLES3::multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format){
+void RasterizerStorageGLES3::multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
- if (multimesh->size==p_instances && multimesh->transform_format==p_transform_format && multimesh->color_format==p_color_format)
+ if (multimesh->size == p_instances && multimesh->transform_format == p_transform_format && multimesh->color_format == p_color_format)
return;
if (multimesh->buffer) {
- glDeleteBuffers(1,&multimesh->buffer);
+ glDeleteBuffers(1, &multimesh->buffer);
multimesh->data.resize(0);
}
- multimesh->size=p_instances;
- multimesh->transform_format=p_transform_format;
- multimesh->color_format=p_color_format;
+ multimesh->size = p_instances;
+ multimesh->transform_format = p_transform_format;
+ multimesh->color_format = p_color_format;
if (multimesh->size) {
- if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) {
- multimesh->xform_floats=8;
+ if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
+ multimesh->xform_floats = 8;
} else {
- multimesh->xform_floats=12;
-
+ multimesh->xform_floats = 12;
}
- if (multimesh->color_format==VS::MULTIMESH_COLOR_NONE) {
- multimesh->color_floats=0;
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) {
- multimesh->color_floats=1;
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) {
- multimesh->color_floats=4;
+ if (multimesh->color_format == VS::MULTIMESH_COLOR_NONE) {
+ multimesh->color_floats = 0;
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
+ multimesh->color_floats = 1;
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
+ multimesh->color_floats = 4;
}
- int format_floats = multimesh->color_floats+multimesh->xform_floats;
- multimesh->data.resize(format_floats*p_instances);
- for(int i=0;i<p_instances;i+=format_floats) {
-
- int color_from=0;
-
- if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) {
- multimesh->data[i+0]=1.0;
- multimesh->data[i+1]=0.0;
- multimesh->data[i+2]=0.0;
- multimesh->data[i+3]=0.0;
- multimesh->data[i+4]=0.0;
- multimesh->data[i+5]=1.0;
- multimesh->data[i+6]=0.0;
- multimesh->data[i+7]=0.0;
- color_from=8;
+ int format_floats = multimesh->color_floats + multimesh->xform_floats;
+ multimesh->data.resize(format_floats * p_instances);
+ for (int i = 0; i < p_instances; i += format_floats) {
+
+ int color_from = 0;
+
+ if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
+ multimesh->data[i + 0] = 1.0;
+ multimesh->data[i + 1] = 0.0;
+ multimesh->data[i + 2] = 0.0;
+ multimesh->data[i + 3] = 0.0;
+ multimesh->data[i + 4] = 0.0;
+ multimesh->data[i + 5] = 1.0;
+ multimesh->data[i + 6] = 0.0;
+ multimesh->data[i + 7] = 0.0;
+ color_from = 8;
} else {
- multimesh->data[i+0]=1.0;
- multimesh->data[i+1]=0.0;
- multimesh->data[i+2]=0.0;
- multimesh->data[i+3]=0.0;
- multimesh->data[i+4]=0.0;
- multimesh->data[i+5]=1.0;
- multimesh->data[i+6]=0.0;
- multimesh->data[i+7]=0.0;
- multimesh->data[i+8]=0.0;
- multimesh->data[i+9]=0.0;
- multimesh->data[i+10]=1.0;
- multimesh->data[i+11]=0.0;
- color_from=12;
+ multimesh->data[i + 0] = 1.0;
+ multimesh->data[i + 1] = 0.0;
+ multimesh->data[i + 2] = 0.0;
+ multimesh->data[i + 3] = 0.0;
+ multimesh->data[i + 4] = 0.0;
+ multimesh->data[i + 5] = 1.0;
+ multimesh->data[i + 6] = 0.0;
+ multimesh->data[i + 7] = 0.0;
+ multimesh->data[i + 8] = 0.0;
+ multimesh->data[i + 9] = 0.0;
+ multimesh->data[i + 10] = 1.0;
+ multimesh->data[i + 11] = 0.0;
+ color_from = 12;
}
- if (multimesh->color_format==VS::MULTIMESH_COLOR_NONE) {
+ if (multimesh->color_format == VS::MULTIMESH_COLOR_NONE) {
//none
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) {
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
union {
uint32_t colu;
float colf;
} cu;
- cu.colu=0xFFFFFFFF;
- multimesh->data[i+color_from+0]=cu.colf;
+ cu.colu = 0xFFFFFFFF;
+ multimesh->data[i + color_from + 0] = cu.colf;
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) {
- multimesh->data[i+color_from+0]=1.0;
- multimesh->data[i+color_from+1]=1.0;
- multimesh->data[i+color_from+2]=1.0;
- multimesh->data[i+color_from+3]=1.0;
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
+ multimesh->data[i + color_from + 0] = 1.0;
+ multimesh->data[i + color_from + 1] = 1.0;
+ multimesh->data[i + color_from + 2] = 1.0;
+ multimesh->data[i + color_from + 3] = 1.0;
}
}
- glGenBuffers(1,&multimesh->buffer);
- glBindBuffer(GL_ARRAY_BUFFER,multimesh->buffer);
- glBufferData(GL_ARRAY_BUFFER,multimesh->data.size()*sizeof(float),NULL,GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0);
-
+ glGenBuffers(1, &multimesh->buffer);
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ glBufferData(GL_ARRAY_BUFFER, multimesh->data.size() * sizeof(float), NULL, GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
}
- multimesh->dirty_data=true;
- multimesh->dirty_aabb=true;
+ multimesh->dirty_data = true;
+ multimesh->dirty_aabb = true;
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
-
}
-int RasterizerStorageGLES3::multimesh_get_instance_count(RID p_multimesh) const{
+int RasterizerStorageGLES3::multimesh_get_instance_count(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,0);
+ ERR_FAIL_COND_V(!multimesh, 0);
return multimesh->size;
}
-void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh,RID p_mesh){
+void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
@@ -3666,8 +3471,7 @@ void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh,RID p_mesh){
}
}
- multimesh->mesh=p_mesh;
-
+ multimesh->mesh = p_mesh;
if (multimesh->mesh.is_valid()) {
Mesh *mesh = mesh_owner.getornull(multimesh->mesh);
@@ -3676,173 +3480,171 @@ void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh,RID p_mesh){
}
}
- multimesh->dirty_aabb=true;
+ multimesh->dirty_aabb = true;
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
}
-void RasterizerStorageGLES3::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform){
+void RasterizerStorageGLES3::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
- ERR_FAIL_INDEX(p_index,multimesh->size);
- ERR_FAIL_COND(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D);
-
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index];
-
- dataptr[ 0]=p_transform.basis.elements[0][0];
- dataptr[ 1]=p_transform.basis.elements[0][1];
- dataptr[ 2]=p_transform.basis.elements[0][2];
- dataptr[ 3]=p_transform.origin.x;
- dataptr[ 4]=p_transform.basis.elements[1][0];
- dataptr[ 5]=p_transform.basis.elements[1][1];
- dataptr[ 6]=p_transform.basis.elements[1][2];
- dataptr[ 7]=p_transform.origin.y;
- dataptr[ 8]=p_transform.basis.elements[2][0];
- dataptr[ 9]=p_transform.basis.elements[2][1];
- dataptr[10]=p_transform.basis.elements[2][2];
- dataptr[11]=p_transform.origin.z;
-
- multimesh->dirty_data=true;
- multimesh->dirty_aabb=true;
+ ERR_FAIL_INDEX(p_index, multimesh->size);
+ ERR_FAIL_COND(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D);
+
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index];
+
+ dataptr[0] = p_transform.basis.elements[0][0];
+ dataptr[1] = p_transform.basis.elements[0][1];
+ dataptr[2] = p_transform.basis.elements[0][2];
+ dataptr[3] = p_transform.origin.x;
+ dataptr[4] = p_transform.basis.elements[1][0];
+ dataptr[5] = p_transform.basis.elements[1][1];
+ dataptr[6] = p_transform.basis.elements[1][2];
+ dataptr[7] = p_transform.origin.y;
+ dataptr[8] = p_transform.basis.elements[2][0];
+ dataptr[9] = p_transform.basis.elements[2][1];
+ dataptr[10] = p_transform.basis.elements[2][2];
+ dataptr[11] = p_transform.origin.z;
+
+ multimesh->dirty_data = true;
+ multimesh->dirty_aabb = true;
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
}
-void RasterizerStorageGLES3::multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform){
+void RasterizerStorageGLES3::multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
- ERR_FAIL_INDEX(p_index,multimesh->size);
- ERR_FAIL_COND(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_3D);
+ ERR_FAIL_INDEX(p_index, multimesh->size);
+ ERR_FAIL_COND(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_3D);
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index];
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index];
- dataptr[ 0]=p_transform.elements[0][0];
- dataptr[ 1]=p_transform.elements[1][0];
- dataptr[ 2]=0;
- dataptr[ 3]=p_transform.elements[2][0];
- dataptr[ 4]=p_transform.elements[0][1];
- dataptr[ 5]=p_transform.elements[1][1];
- dataptr[ 6]=0;
- dataptr[ 7]=p_transform.elements[2][1];
+ dataptr[0] = p_transform.elements[0][0];
+ dataptr[1] = p_transform.elements[1][0];
+ dataptr[2] = 0;
+ dataptr[3] = p_transform.elements[2][0];
+ dataptr[4] = p_transform.elements[0][1];
+ dataptr[5] = p_transform.elements[1][1];
+ dataptr[6] = 0;
+ dataptr[7] = p_transform.elements[2][1];
- multimesh->dirty_data=true;
- multimesh->dirty_aabb=true;
+ multimesh->dirty_data = true;
+ multimesh->dirty_aabb = true;
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
}
-void RasterizerStorageGLES3::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color){
+void RasterizerStorageGLES3::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
- ERR_FAIL_INDEX(p_index,multimesh->size);
- ERR_FAIL_COND(multimesh->color_format==VS::MULTIMESH_COLOR_NONE);
+ ERR_FAIL_INDEX(p_index, multimesh->size);
+ ERR_FAIL_COND(multimesh->color_format == VS::MULTIMESH_COLOR_NONE);
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index+multimesh->xform_floats];
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index + multimesh->xform_floats];
- if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) {
+ if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
- uint8_t *data8=(uint8_t*)dataptr;
- data8[0]=CLAMP(p_color.r*255.0,0,255);
- data8[1]=CLAMP(p_color.g*255.0,0,255);
- data8[2]=CLAMP(p_color.b*255.0,0,255);
- data8[3]=CLAMP(p_color.a*255.0,0,255);
+ uint8_t *data8 = (uint8_t *)dataptr;
+ data8[0] = CLAMP(p_color.r * 255.0, 0, 255);
+ data8[1] = CLAMP(p_color.g * 255.0, 0, 255);
+ data8[2] = CLAMP(p_color.b * 255.0, 0, 255);
+ data8[3] = CLAMP(p_color.a * 255.0, 0, 255);
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) {
- dataptr[ 0]=p_color.r;
- dataptr[ 1]=p_color.g;
- dataptr[ 2]=p_color.b;
- dataptr[ 3]=p_color.a;
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
+ dataptr[0] = p_color.r;
+ dataptr[1] = p_color.g;
+ dataptr[2] = p_color.b;
+ dataptr[3] = p_color.a;
}
-
- multimesh->dirty_data=true;
- multimesh->dirty_aabb=true;
+ multimesh->dirty_data = true;
+ multimesh->dirty_aabb = true;
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
}
-RID RasterizerStorageGLES3::multimesh_get_mesh(RID p_multimesh) const{
+RID RasterizerStorageGLES3::multimesh_get_mesh(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,RID());
+ ERR_FAIL_COND_V(!multimesh, RID());
return multimesh->mesh;
}
-
-Transform RasterizerStorageGLES3::multimesh_instance_get_transform(RID p_multimesh,int p_index) const{
+Transform RasterizerStorageGLES3::multimesh_instance_get_transform(RID p_multimesh, int p_index) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Transform());
- ERR_FAIL_INDEX_V(p_index,multimesh->size,Transform());
- ERR_FAIL_COND_V(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D,Transform());
+ ERR_FAIL_COND_V(!multimesh, Transform());
+ ERR_FAIL_INDEX_V(p_index, multimesh->size, Transform());
+ ERR_FAIL_COND_V(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D, Transform());
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index];
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index];
Transform xform;
- xform.basis.elements[0][0]=dataptr[ 0];
- xform.basis.elements[0][1]=dataptr[ 1];
- xform.basis.elements[0][2]=dataptr[ 2];
- xform.origin.x=dataptr[ 3];
- xform.basis.elements[1][0]=dataptr[ 4];
- xform.basis.elements[1][1]=dataptr[ 5];
- xform.basis.elements[1][2]=dataptr[ 6];
- xform.origin.y=dataptr[ 7];
- xform.basis.elements[2][0]=dataptr[ 8];
- xform.basis.elements[2][1]=dataptr[ 9];
- xform.basis.elements[2][2]=dataptr[10];
- xform.origin.z=dataptr[11];
+ xform.basis.elements[0][0] = dataptr[0];
+ xform.basis.elements[0][1] = dataptr[1];
+ xform.basis.elements[0][2] = dataptr[2];
+ xform.origin.x = dataptr[3];
+ xform.basis.elements[1][0] = dataptr[4];
+ xform.basis.elements[1][1] = dataptr[5];
+ xform.basis.elements[1][2] = dataptr[6];
+ xform.origin.y = dataptr[7];
+ xform.basis.elements[2][0] = dataptr[8];
+ xform.basis.elements[2][1] = dataptr[9];
+ xform.basis.elements[2][2] = dataptr[10];
+ xform.origin.z = dataptr[11];
return xform;
}
-Transform2D RasterizerStorageGLES3::multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const{
+Transform2D RasterizerStorageGLES3::multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Transform2D());
- ERR_FAIL_INDEX_V(p_index,multimesh->size,Transform2D());
- ERR_FAIL_COND_V(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_3D,Transform2D());
+ ERR_FAIL_COND_V(!multimesh, Transform2D());
+ ERR_FAIL_INDEX_V(p_index, multimesh->size, Transform2D());
+ ERR_FAIL_COND_V(multimesh->transform_format == VS::MULTIMESH_TRANSFORM_3D, Transform2D());
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index];
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index];
Transform2D xform;
- xform.elements[0][0]=dataptr[ 0];
- xform.elements[1][0]=dataptr[ 1];
- xform.elements[2][0]=dataptr[ 3];
- xform.elements[0][1]=dataptr[ 4];
- xform.elements[1][1]=dataptr[ 5];
- xform.elements[2][1]=dataptr[ 7];
+ xform.elements[0][0] = dataptr[0];
+ xform.elements[1][0] = dataptr[1];
+ xform.elements[2][0] = dataptr[3];
+ xform.elements[0][1] = dataptr[4];
+ xform.elements[1][1] = dataptr[5];
+ xform.elements[2][1] = dataptr[7];
return xform;
}
-Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh,int p_index) const{
+Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh, int p_index) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Color());
- ERR_FAIL_INDEX_V(p_index,multimesh->size,Color());
- ERR_FAIL_COND_V(multimesh->color_format==VS::MULTIMESH_COLOR_NONE,Color());
+ ERR_FAIL_COND_V(!multimesh, Color());
+ ERR_FAIL_INDEX_V(p_index, multimesh->size, Color());
+ ERR_FAIL_COND_V(multimesh->color_format == VS::MULTIMESH_COLOR_NONE, Color());
- int stride = multimesh->color_floats+multimesh->xform_floats;
- float *dataptr=&multimesh->data[stride*p_index+multimesh->color_floats];
+ int stride = multimesh->color_floats + multimesh->xform_floats;
+ float *dataptr = &multimesh->data[stride * p_index + multimesh->color_floats];
- if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) {
+ if (multimesh->color_format == VS::MULTIMESH_COLOR_8BIT) {
union {
uint32_t colu;
float colf;
@@ -3850,130 +3652,124 @@ Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh,int p
return Color::hex(BSWAP32(cu.colu));
- } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) {
+ } else if (multimesh->color_format == VS::MULTIMESH_COLOR_FLOAT) {
Color c;
- c.r=dataptr[ 0];
- c.g=dataptr[ 1];
- c.b=dataptr[ 2];
- c.a=dataptr[ 3];
+ c.r = dataptr[0];
+ c.g = dataptr[1];
+ c.b = dataptr[2];
+ c.a = dataptr[3];
return c;
}
return Color();
-
}
-void RasterizerStorageGLES3::multimesh_set_visible_instances(RID p_multimesh,int p_visible){
+void RasterizerStorageGLES3::multimesh_set_visible_instances(RID p_multimesh, int p_visible) {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
ERR_FAIL_COND(!multimesh);
- multimesh->visible_instances=p_visible;
+ multimesh->visible_instances = p_visible;
}
-int RasterizerStorageGLES3::multimesh_get_visible_instances(RID p_multimesh) const{
+int RasterizerStorageGLES3::multimesh_get_visible_instances(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,-1);
+ ERR_FAIL_COND_V(!multimesh, -1);
return multimesh->visible_instances;
}
-Rect3 RasterizerStorageGLES3::multimesh_get_aabb(RID p_multimesh) const{
+Rect3 RasterizerStorageGLES3::multimesh_get_aabb(RID p_multimesh) const {
MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh);
- ERR_FAIL_COND_V(!multimesh,Rect3());
+ ERR_FAIL_COND_V(!multimesh, Rect3());
- const_cast<RasterizerStorageGLES3*>(this)->update_dirty_multimeshes(); //update pending AABBs
+ const_cast<RasterizerStorageGLES3 *>(this)->update_dirty_multimeshes(); //update pending AABBs
return multimesh->aabb;
}
void RasterizerStorageGLES3::update_dirty_multimeshes() {
- while(multimesh_update_list.first()) {
+ while (multimesh_update_list.first()) {
MultiMesh *multimesh = multimesh_update_list.first()->self();
if (multimesh->size && multimesh->dirty_data) {
-
- glBindBuffer(GL_ARRAY_BUFFER,multimesh->buffer);
- glBufferSubData(GL_ARRAY_BUFFER,0,multimesh->data.size()*sizeof(float),multimesh->data.ptr());
- glBindBuffer(GL_ARRAY_BUFFER,0);
-
-
+ glBindBuffer(GL_ARRAY_BUFFER, multimesh->buffer);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, multimesh->data.size() * sizeof(float), multimesh->data.ptr());
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
}
-
-
if (multimesh->size && multimesh->dirty_aabb) {
Rect3 mesh_aabb;
if (multimesh->mesh.is_valid()) {
- mesh_aabb=mesh_get_aabb(multimesh->mesh,RID());
+ mesh_aabb = mesh_get_aabb(multimesh->mesh, RID());
} else {
- mesh_aabb.size+=Vector3(0.001,0.001,0.001);
+ mesh_aabb.size += Vector3(0.001, 0.001, 0.001);
}
- int stride=multimesh->color_floats+multimesh->xform_floats;
+ int stride = multimesh->color_floats + multimesh->xform_floats;
int count = multimesh->data.size();
- float *data=multimesh->data.ptr();
+ float *data = multimesh->data.ptr();
Rect3 aabb;
- if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) {
+ if (multimesh->transform_format == VS::MULTIMESH_TRANSFORM_2D) {
- for(int i=0;i<count;i+=stride) {
+ for (int i = 0; i < count; i += stride) {
- float *dataptr=&data[i];
+ float *dataptr = &data[i];
Transform xform;
- xform.basis[0][0]=dataptr[ 0];
- xform.basis[0][1]=dataptr[ 1];
- xform.origin[0]=dataptr[ 3];
- xform.basis[1][0]=dataptr[ 4];
- xform.basis[1][1]=dataptr[ 5];
- xform.origin[1]=dataptr[ 7];
+ xform.basis[0][0] = dataptr[0];
+ xform.basis[0][1] = dataptr[1];
+ xform.origin[0] = dataptr[3];
+ xform.basis[1][0] = dataptr[4];
+ xform.basis[1][1] = dataptr[5];
+ xform.origin[1] = dataptr[7];
Rect3 laabb = xform.xform(mesh_aabb);
- if (i==0)
- aabb=laabb;
+ if (i == 0)
+ aabb = laabb;
else
aabb.merge_with(laabb);
}
} else {
- for(int i=0;i<count;i+=stride) {
+ for (int i = 0; i < count; i += stride) {
- float *dataptr=&data[i];
+ float *dataptr = &data[i];
Transform xform;
- xform.basis.elements[0][0]=dataptr[ 0];
- xform.basis.elements[0][1]=dataptr[ 1];
- xform.basis.elements[0][2]=dataptr[ 2];
- xform.origin.x=dataptr[ 3];
- xform.basis.elements[1][0]=dataptr[ 4];
- xform.basis.elements[1][1]=dataptr[ 5];
- xform.basis.elements[1][2]=dataptr[ 6];
- xform.origin.y=dataptr[ 7];
- xform.basis.elements[2][0]=dataptr[ 8];
- xform.basis.elements[2][1]=dataptr[ 9];
- xform.basis.elements[2][2]=dataptr[10];
- xform.origin.z=dataptr[11];
+ xform.basis.elements[0][0] = dataptr[0];
+ xform.basis.elements[0][1] = dataptr[1];
+ xform.basis.elements[0][2] = dataptr[2];
+ xform.origin.x = dataptr[3];
+ xform.basis.elements[1][0] = dataptr[4];
+ xform.basis.elements[1][1] = dataptr[5];
+ xform.basis.elements[1][2] = dataptr[6];
+ xform.origin.y = dataptr[7];
+ xform.basis.elements[2][0] = dataptr[8];
+ xform.basis.elements[2][1] = dataptr[9];
+ xform.basis.elements[2][2] = dataptr[10];
+ xform.origin.z = dataptr[11];
Rect3 laabb = xform.xform(mesh_aabb);
- if (i==0)
- aabb=laabb;
+ if (i == 0)
+ aabb = laabb;
else
aabb.merge_with(laabb);
}
}
- multimesh->aabb=aabb;
+ multimesh->aabb = aabb;
}
- multimesh->dirty_aabb=false;
- multimesh->dirty_data=false;
+ multimesh->dirty_aabb = false;
+ multimesh->dirty_data = false;
multimesh->instance_change_notify();
@@ -3983,30 +3779,26 @@ void RasterizerStorageGLES3::update_dirty_multimeshes() {
/* IMMEDIATE API */
-
RID RasterizerStorageGLES3::immediate_create() {
- Immediate *im = memnew( Immediate );
+ Immediate *im = memnew(Immediate);
return immediate_owner.make_rid(im);
-
}
-void RasterizerStorageGLES3::immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture){
+void RasterizerStorageGLES3::immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(im->building);
Immediate::Chunk ic;
- ic.texture=p_texture;
- ic.primitive=p_rimitive;
+ ic.texture = p_texture;
+ ic.primitive = p_rimitive;
im->chunks.push_back(ic);
- im->mask=0;
- im->building=true;
-
-
+ im->mask = 0;
+ im->building = true;
}
-void RasterizerStorageGLES3::immediate_vertex(RID p_immediate,const Vector3& p_vertex){
+void RasterizerStorageGLES3::immediate_vertex(RID p_immediate, const Vector3 &p_vertex) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
@@ -4014,92 +3806,83 @@ void RasterizerStorageGLES3::immediate_vertex(RID p_immediate,const Vector3& p_v
Immediate::Chunk *c = &im->chunks.back()->get();
+ if (c->vertices.empty() && im->chunks.size() == 1) {
- if (c->vertices.empty() && im->chunks.size()==1) {
-
- im->aabb.pos=p_vertex;
- im->aabb.size=Vector3();
+ im->aabb.pos = p_vertex;
+ im->aabb.size = Vector3();
} else {
im->aabb.expand_to(p_vertex);
}
- if (im->mask&VS::ARRAY_FORMAT_NORMAL)
+ if (im->mask & VS::ARRAY_FORMAT_NORMAL)
c->normals.push_back(chunk_normal);
- if (im->mask&VS::ARRAY_FORMAT_TANGENT)
+ if (im->mask & VS::ARRAY_FORMAT_TANGENT)
c->tangents.push_back(chunk_tangent);
- if (im->mask&VS::ARRAY_FORMAT_COLOR)
+ if (im->mask & VS::ARRAY_FORMAT_COLOR)
c->colors.push_back(chunk_color);
- if (im->mask&VS::ARRAY_FORMAT_TEX_UV)
+ if (im->mask & VS::ARRAY_FORMAT_TEX_UV)
c->uvs.push_back(chunk_uv);
- if (im->mask&VS::ARRAY_FORMAT_TEX_UV2)
+ if (im->mask & VS::ARRAY_FORMAT_TEX_UV2)
c->uvs2.push_back(chunk_uv2);
- im->mask|=VS::ARRAY_FORMAT_VERTEX;
+ im->mask |= VS::ARRAY_FORMAT_VERTEX;
c->vertices.push_back(p_vertex);
-
}
-
-void RasterizerStorageGLES3::immediate_normal(RID p_immediate,const Vector3& p_normal){
+void RasterizerStorageGLES3::immediate_normal(RID p_immediate, const Vector3 &p_normal) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_NORMAL;
- chunk_normal=p_normal;
-
+ im->mask |= VS::ARRAY_FORMAT_NORMAL;
+ chunk_normal = p_normal;
}
-void RasterizerStorageGLES3::immediate_tangent(RID p_immediate,const Plane& p_tangent){
+void RasterizerStorageGLES3::immediate_tangent(RID p_immediate, const Plane &p_tangent) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TANGENT;
- chunk_tangent=p_tangent;
-
+ im->mask |= VS::ARRAY_FORMAT_TANGENT;
+ chunk_tangent = p_tangent;
}
-void RasterizerStorageGLES3::immediate_color(RID p_immediate,const Color& p_color){
+void RasterizerStorageGLES3::immediate_color(RID p_immediate, const Color &p_color) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_COLOR;
- chunk_color=p_color;
-
+ im->mask |= VS::ARRAY_FORMAT_COLOR;
+ chunk_color = p_color;
}
-void RasterizerStorageGLES3::immediate_uv(RID p_immediate,const Vector2& tex_uv){
+void RasterizerStorageGLES3::immediate_uv(RID p_immediate, const Vector2 &tex_uv) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TEX_UV;
- chunk_uv=tex_uv;
-
+ im->mask |= VS::ARRAY_FORMAT_TEX_UV;
+ chunk_uv = tex_uv;
}
-void RasterizerStorageGLES3::immediate_uv2(RID p_immediate,const Vector2& tex_uv){
+void RasterizerStorageGLES3::immediate_uv2(RID p_immediate, const Vector2 &tex_uv) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->mask|=VS::ARRAY_FORMAT_TEX_UV2;
- chunk_uv2=tex_uv;
-
+ im->mask |= VS::ARRAY_FORMAT_TEX_UV2;
+ chunk_uv2 = tex_uv;
}
-void RasterizerStorageGLES3::immediate_end(RID p_immediate){
+void RasterizerStorageGLES3::immediate_end(RID p_immediate) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
ERR_FAIL_COND(!im->building);
- im->building=false;
+ im->building = false;
im->instance_change_notify();
-
}
void RasterizerStorageGLES3::immediate_clear(RID p_immediate) {
@@ -4109,279 +3892,264 @@ void RasterizerStorageGLES3::immediate_clear(RID p_immediate) {
im->chunks.clear();
im->instance_change_notify();
-
}
Rect3 RasterizerStorageGLES3::immediate_get_aabb(RID p_immediate) const {
Immediate *im = immediate_owner.get(p_immediate);
- ERR_FAIL_COND_V(!im,Rect3());
+ ERR_FAIL_COND_V(!im, Rect3());
return im->aabb;
}
-void RasterizerStorageGLES3::immediate_set_material(RID p_immediate,RID p_material) {
+void RasterizerStorageGLES3::immediate_set_material(RID p_immediate, RID p_material) {
Immediate *im = immediate_owner.get(p_immediate);
ERR_FAIL_COND(!im);
- im->material=p_material;
+ im->material = p_material;
im->instance_material_change_notify();
-
}
RID RasterizerStorageGLES3::immediate_get_material(RID p_immediate) const {
const Immediate *im = immediate_owner.get(p_immediate);
- ERR_FAIL_COND_V(!im,RID());
+ ERR_FAIL_COND_V(!im, RID());
return im->material;
-
}
/* SKELETON API */
-RID RasterizerStorageGLES3::skeleton_create(){
+RID RasterizerStorageGLES3::skeleton_create() {
- Skeleton *skeleton = memnew( Skeleton );
+ Skeleton *skeleton = memnew(Skeleton);
return skeleton_owner.make_rid(skeleton);
}
-void RasterizerStorageGLES3::skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton){
+void RasterizerStorageGLES3::skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton) {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
ERR_FAIL_COND(!skeleton);
- ERR_FAIL_COND(p_bones<0);
+ ERR_FAIL_COND(p_bones < 0);
- if (skeleton->size==p_bones && skeleton->use_2d==p_2d_skeleton)
+ if (skeleton->size == p_bones && skeleton->use_2d == p_2d_skeleton)
return;
if (skeleton->ubo) {
- glDeleteBuffers(1,&skeleton->ubo);
- skeleton->ubo=0;
+ glDeleteBuffers(1, &skeleton->ubo);
+ skeleton->ubo = 0;
}
- skeleton->size=p_bones;
+ skeleton->size = p_bones;
if (p_2d_skeleton) {
- skeleton->bones.resize(p_bones*8);
- for(int i=0;i<skeleton->bones.size();i+=8) {
- skeleton->bones[i+0]=1;
- skeleton->bones[i+1]=0;
- skeleton->bones[i+2]=0;
- skeleton->bones[i+3]=0;
- skeleton->bones[i+4]=0;
- skeleton->bones[i+5]=1;
- skeleton->bones[i+6]=0;
- skeleton->bones[i+7]=0;
+ skeleton->bones.resize(p_bones * 8);
+ for (int i = 0; i < skeleton->bones.size(); i += 8) {
+ skeleton->bones[i + 0] = 1;
+ skeleton->bones[i + 1] = 0;
+ skeleton->bones[i + 2] = 0;
+ skeleton->bones[i + 3] = 0;
+ skeleton->bones[i + 4] = 0;
+ skeleton->bones[i + 5] = 1;
+ skeleton->bones[i + 6] = 0;
+ skeleton->bones[i + 7] = 0;
}
} else {
- skeleton->bones.resize(p_bones*12);
- for(int i=0;i<skeleton->bones.size();i+=12) {
- skeleton->bones[i+0]=1;
- skeleton->bones[i+1]=0;
- skeleton->bones[i+2]=0;
- skeleton->bones[i+3]=0;
- skeleton->bones[i+4]=0;
- skeleton->bones[i+5]=1;
- skeleton->bones[i+6]=0;
- skeleton->bones[i+7]=0;
- skeleton->bones[i+8]=0;
- skeleton->bones[i+9]=0;
- skeleton->bones[i+10]=1;
- skeleton->bones[i+11]=0;
+ skeleton->bones.resize(p_bones * 12);
+ for (int i = 0; i < skeleton->bones.size(); i += 12) {
+ skeleton->bones[i + 0] = 1;
+ skeleton->bones[i + 1] = 0;
+ skeleton->bones[i + 2] = 0;
+ skeleton->bones[i + 3] = 0;
+ skeleton->bones[i + 4] = 0;
+ skeleton->bones[i + 5] = 1;
+ skeleton->bones[i + 6] = 0;
+ skeleton->bones[i + 7] = 0;
+ skeleton->bones[i + 8] = 0;
+ skeleton->bones[i + 9] = 0;
+ skeleton->bones[i + 10] = 1;
+ skeleton->bones[i + 11] = 0;
}
-
}
-
-
if (p_bones) {
glGenBuffers(1, &skeleton->ubo);
glBindBuffer(GL_UNIFORM_BUFFER, skeleton->ubo);
- glBufferData(GL_UNIFORM_BUFFER, skeleton->bones.size()*sizeof(float), NULL, GL_DYNAMIC_DRAW);
+ glBufferData(GL_UNIFORM_BUFFER, skeleton->bones.size() * sizeof(float), NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
if (!skeleton->update_list.in_list()) {
skeleton_update_list.add(&skeleton->update_list);
}
-
-
-
}
-int RasterizerStorageGLES3::skeleton_get_bone_count(RID p_skeleton) const{
+int RasterizerStorageGLES3::skeleton_get_bone_count(RID p_skeleton) const {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
- ERR_FAIL_COND_V(!skeleton,0);
+ ERR_FAIL_COND_V(!skeleton, 0);
return skeleton->size;
}
-void RasterizerStorageGLES3::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform){
+void RasterizerStorageGLES3::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
ERR_FAIL_COND(!skeleton);
- ERR_FAIL_INDEX(p_bone,skeleton->size);
+ ERR_FAIL_INDEX(p_bone, skeleton->size);
ERR_FAIL_COND(skeleton->use_2d);
- float * bones = skeleton->bones.ptr();
- bones[p_bone*12+ 0]=p_transform.basis.elements[0][0];
- bones[p_bone*12+ 1]=p_transform.basis.elements[0][1];
- bones[p_bone*12+ 2]=p_transform.basis.elements[0][2];
- bones[p_bone*12+ 3]=p_transform.origin.x;
- bones[p_bone*12+ 4]=p_transform.basis.elements[1][0];
- bones[p_bone*12+ 5]=p_transform.basis.elements[1][1];
- bones[p_bone*12+ 6]=p_transform.basis.elements[1][2];
- bones[p_bone*12+ 7]=p_transform.origin.y;
- bones[p_bone*12+ 8]=p_transform.basis.elements[2][0];
- bones[p_bone*12+ 9]=p_transform.basis.elements[2][1];
- bones[p_bone*12+10]=p_transform.basis.elements[2][2];
- bones[p_bone*12+11]=p_transform.origin.z;
+ float *bones = skeleton->bones.ptr();
+ bones[p_bone * 12 + 0] = p_transform.basis.elements[0][0];
+ bones[p_bone * 12 + 1] = p_transform.basis.elements[0][1];
+ bones[p_bone * 12 + 2] = p_transform.basis.elements[0][2];
+ bones[p_bone * 12 + 3] = p_transform.origin.x;
+ bones[p_bone * 12 + 4] = p_transform.basis.elements[1][0];
+ bones[p_bone * 12 + 5] = p_transform.basis.elements[1][1];
+ bones[p_bone * 12 + 6] = p_transform.basis.elements[1][2];
+ bones[p_bone * 12 + 7] = p_transform.origin.y;
+ bones[p_bone * 12 + 8] = p_transform.basis.elements[2][0];
+ bones[p_bone * 12 + 9] = p_transform.basis.elements[2][1];
+ bones[p_bone * 12 + 10] = p_transform.basis.elements[2][2];
+ bones[p_bone * 12 + 11] = p_transform.origin.z;
if (!skeleton->update_list.in_list()) {
skeleton_update_list.add(&skeleton->update_list);
}
-
}
-
-Transform RasterizerStorageGLES3::skeleton_bone_get_transform(RID p_skeleton,int p_bone) const{
+Transform RasterizerStorageGLES3::skeleton_bone_get_transform(RID p_skeleton, int p_bone) const {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
- ERR_FAIL_COND_V(!skeleton,Transform());
- ERR_FAIL_INDEX_V(p_bone,skeleton->size,Transform());
- ERR_FAIL_COND_V(skeleton->use_2d,Transform());
+ ERR_FAIL_COND_V(!skeleton, Transform());
+ ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform());
+ ERR_FAIL_COND_V(skeleton->use_2d, Transform());
- float * bones = skeleton->bones.ptr();
+ float *bones = skeleton->bones.ptr();
Transform mtx;
- mtx.basis.elements[0][0]=bones[p_bone*12+ 0];
- mtx.basis.elements[0][1]=bones[p_bone*12+ 1];
- mtx.basis.elements[0][2]=bones[p_bone*12+ 2];
- mtx.origin.x=bones[p_bone*12+ 3];
- mtx.basis.elements[1][0]=bones[p_bone*12+ 4];
- mtx.basis.elements[1][1]=bones[p_bone*12+ 5];
- mtx.basis.elements[1][2]=bones[p_bone*12+ 6];
- mtx.origin.y=bones[p_bone*12+ 7];
- mtx.basis.elements[2][0]=bones[p_bone*12+ 8];
- mtx.basis.elements[2][1]=bones[p_bone*12+ 9];
- mtx.basis.elements[2][2]=bones[p_bone*12+10];
- mtx.origin.z=bones[p_bone*12+11];
+ mtx.basis.elements[0][0] = bones[p_bone * 12 + 0];
+ mtx.basis.elements[0][1] = bones[p_bone * 12 + 1];
+ mtx.basis.elements[0][2] = bones[p_bone * 12 + 2];
+ mtx.origin.x = bones[p_bone * 12 + 3];
+ mtx.basis.elements[1][0] = bones[p_bone * 12 + 4];
+ mtx.basis.elements[1][1] = bones[p_bone * 12 + 5];
+ mtx.basis.elements[1][2] = bones[p_bone * 12 + 6];
+ mtx.origin.y = bones[p_bone * 12 + 7];
+ mtx.basis.elements[2][0] = bones[p_bone * 12 + 8];
+ mtx.basis.elements[2][1] = bones[p_bone * 12 + 9];
+ mtx.basis.elements[2][2] = bones[p_bone * 12 + 10];
+ mtx.origin.z = bones[p_bone * 12 + 11];
return mtx;
}
-void RasterizerStorageGLES3::skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform){
+void RasterizerStorageGLES3::skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
ERR_FAIL_COND(!skeleton);
- ERR_FAIL_INDEX(p_bone,skeleton->size);
+ ERR_FAIL_INDEX(p_bone, skeleton->size);
ERR_FAIL_COND(!skeleton->use_2d);
- float * bones = skeleton->bones.ptr();
- bones[p_bone*12+ 0]=p_transform.elements[0][0];
- bones[p_bone*12+ 1]=p_transform.elements[1][0];
- bones[p_bone*12+ 2]=0;
- bones[p_bone*12+ 3]=p_transform.elements[2][0];
- bones[p_bone*12+ 4]=p_transform.elements[0][1];
- bones[p_bone*12+ 5]=p_transform.elements[1][1];
- bones[p_bone*12+ 6]=0;
- bones[p_bone*12+ 7]=p_transform.elements[2][1];
+ float *bones = skeleton->bones.ptr();
+ bones[p_bone * 12 + 0] = p_transform.elements[0][0];
+ bones[p_bone * 12 + 1] = p_transform.elements[1][0];
+ bones[p_bone * 12 + 2] = 0;
+ bones[p_bone * 12 + 3] = p_transform.elements[2][0];
+ bones[p_bone * 12 + 4] = p_transform.elements[0][1];
+ bones[p_bone * 12 + 5] = p_transform.elements[1][1];
+ bones[p_bone * 12 + 6] = 0;
+ bones[p_bone * 12 + 7] = p_transform.elements[2][1];
if (!skeleton->update_list.in_list()) {
skeleton_update_list.add(&skeleton->update_list);
}
-
}
-Transform2D RasterizerStorageGLES3::skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone) const{
+Transform2D RasterizerStorageGLES3::skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
-
- ERR_FAIL_COND_V(!skeleton,Transform2D());
- ERR_FAIL_INDEX_V(p_bone,skeleton->size,Transform2D());
- ERR_FAIL_COND_V(!skeleton->use_2d,Transform2D());
+ ERR_FAIL_COND_V(!skeleton, Transform2D());
+ ERR_FAIL_INDEX_V(p_bone, skeleton->size, Transform2D());
+ ERR_FAIL_COND_V(!skeleton->use_2d, Transform2D());
Transform2D mtx;
- float * bones = skeleton->bones.ptr();
- mtx.elements[0][0]=bones[p_bone*12+ 0];
- mtx.elements[1][0]=bones[p_bone*12+ 1];
- mtx.elements[2][0]=bones[p_bone*12+ 3];
- mtx.elements[0][1]=bones[p_bone*12+ 4];
- mtx.elements[1][1]=bones[p_bone*12+ 5];
- mtx.elements[2][1]=bones[p_bone*12+ 7];
+ float *bones = skeleton->bones.ptr();
+ mtx.elements[0][0] = bones[p_bone * 12 + 0];
+ mtx.elements[1][0] = bones[p_bone * 12 + 1];
+ mtx.elements[2][0] = bones[p_bone * 12 + 3];
+ mtx.elements[0][1] = bones[p_bone * 12 + 4];
+ mtx.elements[1][1] = bones[p_bone * 12 + 5];
+ mtx.elements[2][1] = bones[p_bone * 12 + 7];
return mtx;
}
void RasterizerStorageGLES3::update_dirty_skeletons() {
- while(skeleton_update_list.first()) {
+ while (skeleton_update_list.first()) {
Skeleton *skeleton = skeleton_update_list.first()->self();
if (skeleton->size) {
glBindBuffer(GL_UNIFORM_BUFFER, skeleton->ubo);
- glBufferSubData(GL_UNIFORM_BUFFER,0,skeleton->bones.size()*sizeof(float),skeleton->bones.ptr());
+ glBufferSubData(GL_UNIFORM_BUFFER, 0, skeleton->bones.size() * sizeof(float), skeleton->bones.ptr());
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
- for (Set<RasterizerScene::InstanceBase*>::Element *E=skeleton->instances.front();E;E=E->next()) {
+ for (Set<RasterizerScene::InstanceBase *>::Element *E = skeleton->instances.front(); E; E = E->next()) {
E->get()->base_changed();
}
skeleton_update_list.remove(skeleton_update_list.first());
}
-
}
/* Light API */
-RID RasterizerStorageGLES3::light_create(VS::LightType p_type){
-
- Light *light = memnew( Light );
- light->type=p_type;
-
- light->param[VS::LIGHT_PARAM_ENERGY]=1.0;
- light->param[VS::LIGHT_PARAM_SPECULAR]=0.5;
- light->param[VS::LIGHT_PARAM_RANGE]=1.0;
- light->param[VS::LIGHT_PARAM_SPOT_ANGLE]=45;
- light->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE]=45;
- light->param[VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE]=0;
- light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET]=0.1;
- light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET]=0.3;
- light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET]=0.6;
- light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]=0.1;
- light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE]=0.1;
-
-
- light->color=Color(1,1,1,1);
- light->shadow=false;
- light->negative=false;
- light->cull_mask=0xFFFFFFFF;
- light->directional_shadow_mode=VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL;
- light->omni_shadow_mode=VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID;
- light->omni_shadow_detail=VS::LIGHT_OMNI_SHADOW_DETAIL_VERTICAL;
- light->directional_blend_splits=false;
-
- light->version=0;
+RID RasterizerStorageGLES3::light_create(VS::LightType p_type) {
+
+ Light *light = memnew(Light);
+ light->type = p_type;
+
+ light->param[VS::LIGHT_PARAM_ENERGY] = 1.0;
+ light->param[VS::LIGHT_PARAM_SPECULAR] = 0.5;
+ light->param[VS::LIGHT_PARAM_RANGE] = 1.0;
+ light->param[VS::LIGHT_PARAM_SPOT_ANGLE] = 45;
+ light->param[VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE] = 45;
+ light->param[VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE] = 0;
+ light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET] = 0.1;
+ light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET] = 0.3;
+ light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET] = 0.6;
+ light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS] = 0.1;
+ light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE] = 0.1;
+
+ light->color = Color(1, 1, 1, 1);
+ light->shadow = false;
+ light->negative = false;
+ light->cull_mask = 0xFFFFFFFF;
+ light->directional_shadow_mode = VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL;
+ light->omni_shadow_mode = VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID;
+ light->omni_shadow_detail = VS::LIGHT_OMNI_SHADOW_DETAIL_VERTICAL;
+ light->directional_blend_splits = false;
+
+ light->version = 0;
return light_owner.make_rid(light);
}
-void RasterizerStorageGLES3::light_set_color(RID p_light,const Color& p_color){
+void RasterizerStorageGLES3::light_set_color(RID p_light, const Color &p_color) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->color=p_color;
+ light->color = p_color;
}
-void RasterizerStorageGLES3::light_set_param(RID p_light,VS::LightParam p_param,float p_value){
+void RasterizerStorageGLES3::light_set_param(RID p_light, VS::LightParam p_param, float p_value) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- ERR_FAIL_INDEX(p_param,VS::LIGHT_PARAM_MAX);
+ ERR_FAIL_INDEX(p_param, VS::LIGHT_PARAM_MAX);
- switch(p_param) {
+ switch (p_param) {
case VS::LIGHT_PARAM_RANGE:
case VS::LIGHT_PARAM_SPOT_ANGLE:
case VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE:
@@ -4397,185 +4165,173 @@ void RasterizerStorageGLES3::light_set_param(RID p_light,VS::LightParam p_param,
} break;
}
- light->param[p_param]=p_value;
+ light->param[p_param] = p_value;
}
-void RasterizerStorageGLES3::light_set_shadow(RID p_light,bool p_enabled){
+void RasterizerStorageGLES3::light_set_shadow(RID p_light, bool p_enabled) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->shadow=p_enabled;
+ light->shadow = p_enabled;
light->version++;
light->instance_change_notify();
}
-void RasterizerStorageGLES3::light_set_shadow_color(RID p_light,const Color& p_color) {
+void RasterizerStorageGLES3::light_set_shadow_color(RID p_light, const Color &p_color) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->shadow_color=p_color;
-
+ light->shadow_color = p_color;
}
-void RasterizerStorageGLES3::light_set_projector(RID p_light,RID p_texture){
+void RasterizerStorageGLES3::light_set_projector(RID p_light, RID p_texture) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->projector=p_texture;
+ light->projector = p_texture;
}
-void RasterizerStorageGLES3::light_set_negative(RID p_light,bool p_enable){
+void RasterizerStorageGLES3::light_set_negative(RID p_light, bool p_enable) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->negative=p_enable;
+ light->negative = p_enable;
}
-void RasterizerStorageGLES3::light_set_cull_mask(RID p_light,uint32_t p_mask){
+void RasterizerStorageGLES3::light_set_cull_mask(RID p_light, uint32_t p_mask) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->cull_mask=p_mask;
+ light->cull_mask = p_mask;
light->version++;
light->instance_change_notify();
-
}
-void RasterizerStorageGLES3::light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode) {
+void RasterizerStorageGLES3::light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->omni_shadow_mode=p_mode;
+ light->omni_shadow_mode = p_mode;
light->version++;
light->instance_change_notify();
-
-
}
VS::LightOmniShadowMode RasterizerStorageGLES3::light_omni_get_shadow_mode(RID p_light) {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI_SHADOW_CUBE);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_OMNI_SHADOW_CUBE);
return light->omni_shadow_mode;
}
+void RasterizerStorageGLES3::light_omni_set_shadow_detail(RID p_light, VS::LightOmniShadowDetail p_detail) {
-void RasterizerStorageGLES3::light_omni_set_shadow_detail(RID p_light,VS::LightOmniShadowDetail p_detail) {
-
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->omni_shadow_detail=p_detail;
+ light->omni_shadow_detail = p_detail;
light->version++;
light->instance_change_notify();
}
+void RasterizerStorageGLES3::light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode) {
-void RasterizerStorageGLES3::light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode){
-
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->directional_shadow_mode=p_mode;
+ light->directional_shadow_mode = p_mode;
light->version++;
light->instance_change_notify();
-
}
-void RasterizerStorageGLES3::light_directional_set_blend_splits(RID p_light,bool p_enable) {
+void RasterizerStorageGLES3::light_directional_set_blend_splits(RID p_light, bool p_enable) {
- Light * light = light_owner.getornull(p_light);
+ Light *light = light_owner.getornull(p_light);
ERR_FAIL_COND(!light);
- light->directional_blend_splits=p_enable;
+ light->directional_blend_splits = p_enable;
light->version++;
light->instance_change_notify();
-
}
-
bool RasterizerStorageGLES3::light_directional_get_blend_splits(RID p_light) const {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,false);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, false);
return light->directional_blend_splits;
}
VS::LightDirectionalShadowMode RasterizerStorageGLES3::light_directional_get_shadow_mode(RID p_light) {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL);
return light->directional_shadow_mode;
}
-
VS::LightType RasterizerStorageGLES3::light_get_type(RID p_light) const {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
return light->type;
}
-float RasterizerStorageGLES3::light_get_param(RID p_light,VS::LightParam p_param) {
+float RasterizerStorageGLES3::light_get_param(RID p_light, VS::LightParam p_param) {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
return light->param[p_param];
}
Color RasterizerStorageGLES3::light_get_color(RID p_light) {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,Color());
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, Color());
return light->color;
-
}
bool RasterizerStorageGLES3::light_has_shadow(RID p_light) const {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_DIRECTIONAL);
return light->shadow;
}
uint64_t RasterizerStorageGLES3::light_get_version(RID p_light) const {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,0);
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, 0);
return light->version;
}
-
Rect3 RasterizerStorageGLES3::light_get_aabb(RID p_light) const {
- const Light * light = light_owner.getornull(p_light);
- ERR_FAIL_COND_V(!light,Rect3());
+ const Light *light = light_owner.getornull(p_light);
+ ERR_FAIL_COND_V(!light, Rect3());
- switch( light->type ) {
+ switch (light->type) {
case VS::LIGHT_SPOT: {
- float len=light->param[VS::LIGHT_PARAM_RANGE];
- float size=Math::tan(Math::deg2rad(light->param[VS::LIGHT_PARAM_SPOT_ANGLE]))*len;
- return Rect3( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) );
+ float len = light->param[VS::LIGHT_PARAM_RANGE];
+ float size = Math::tan(Math::deg2rad(light->param[VS::LIGHT_PARAM_SPOT_ANGLE])) * len;
+ return Rect3(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
} break;
case VS::LIGHT_OMNI: {
float r = light->param[VS::LIGHT_PARAM_RANGE];
- return Rect3( -Vector3(r,r,r), Vector3(r,r,r)*2 );
+ return Rect3(-Vector3(r, r, r), Vector3(r, r, r) * 2);
} break;
case VS::LIGHT_DIRECTIONAL: {
@@ -4584,27 +4340,27 @@ Rect3 RasterizerStorageGLES3::light_get_aabb(RID p_light) const {
default: {}
}
- ERR_FAIL_V( Rect3() );
+ ERR_FAIL_V(Rect3());
return Rect3();
}
/* PROBE API */
-RID RasterizerStorageGLES3::reflection_probe_create(){
+RID RasterizerStorageGLES3::reflection_probe_create() {
- ReflectionProbe *reflection_probe = memnew( ReflectionProbe );
+ ReflectionProbe *reflection_probe = memnew(ReflectionProbe);
- reflection_probe->intensity=1.0;
- reflection_probe->interior_ambient=Color();
- reflection_probe->interior_ambient_energy=1.0;
- reflection_probe->max_distance=0;
- reflection_probe->extents=Vector3(1,1,1);
- reflection_probe->origin_offset=Vector3(0,0,0);
- reflection_probe->interior=false;
- reflection_probe->box_projection=false;
- reflection_probe->enable_shadows=false;
- reflection_probe->cull_mask=(1<<20)-1;
- reflection_probe->update_mode=VS::REFLECTION_PROBE_UPDATE_ONCE;
+ reflection_probe->intensity = 1.0;
+ reflection_probe->interior_ambient = Color();
+ reflection_probe->interior_ambient_energy = 1.0;
+ reflection_probe->max_distance = 0;
+ reflection_probe->extents = Vector3(1, 1, 1);
+ reflection_probe->origin_offset = Vector3(0, 0, 0);
+ reflection_probe->interior = false;
+ reflection_probe->box_projection = false;
+ reflection_probe->enable_shadows = false;
+ reflection_probe->cull_mask = (1 << 20) - 1;
+ reflection_probe->update_mode = VS::REFLECTION_PROBE_UPDATE_ONCE;
return reflection_probe_owner.make_rid(reflection_probe);
}
@@ -4614,9 +4370,8 @@ void RasterizerStorageGLES3::reflection_probe_set_update_mode(RID p_probe, VS::R
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->update_mode=p_mode;
+ reflection_probe->update_mode = p_mode;
reflection_probe->instance_change_notify();
-
}
void RasterizerStorageGLES3::reflection_probe_set_intensity(RID p_probe, float p_intensity) {
@@ -4624,17 +4379,15 @@ void RasterizerStorageGLES3::reflection_probe_set_intensity(RID p_probe, float p
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->intensity=p_intensity;
-
+ reflection_probe->intensity = p_intensity;
}
-void RasterizerStorageGLES3::reflection_probe_set_interior_ambient(RID p_probe, const Color& p_ambient) {
+void RasterizerStorageGLES3::reflection_probe_set_interior_ambient(RID p_probe, const Color &p_ambient) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->interior_ambient=p_ambient;
-
+ reflection_probe->interior_ambient = p_ambient;
}
void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) {
@@ -4642,8 +4395,7 @@ void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_energy(RID p_
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->interior_ambient_energy=p_energy;
-
+ reflection_probe->interior_ambient_energy = p_energy;
}
void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) {
@@ -4651,91 +4403,80 @@ void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_probe_contrib
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->interior_ambient_probe_contrib=p_contrib;
-
+ reflection_probe->interior_ambient_probe_contrib = p_contrib;
}
-
-void RasterizerStorageGLES3::reflection_probe_set_max_distance(RID p_probe, float p_distance){
+void RasterizerStorageGLES3::reflection_probe_set_max_distance(RID p_probe, float p_distance) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->max_distance=p_distance;
+ reflection_probe->max_distance = p_distance;
reflection_probe->instance_change_notify();
-
}
-void RasterizerStorageGLES3::reflection_probe_set_extents(RID p_probe, const Vector3& p_extents){
+void RasterizerStorageGLES3::reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->extents=p_extents;
+ reflection_probe->extents = p_extents;
reflection_probe->instance_change_notify();
-
}
-void RasterizerStorageGLES3::reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset){
+void RasterizerStorageGLES3::reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->origin_offset=p_offset;
+ reflection_probe->origin_offset = p_offset;
reflection_probe->instance_change_notify();
-
}
-void RasterizerStorageGLES3::reflection_probe_set_as_interior(RID p_probe, bool p_enable){
+void RasterizerStorageGLES3::reflection_probe_set_as_interior(RID p_probe, bool p_enable) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->interior=p_enable;
-
+ reflection_probe->interior = p_enable;
}
-void RasterizerStorageGLES3::reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable){
+void RasterizerStorageGLES3::reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->box_projection=p_enable;
-
+ reflection_probe->box_projection = p_enable;
}
-void RasterizerStorageGLES3::reflection_probe_set_enable_shadows(RID p_probe, bool p_enable){
+void RasterizerStorageGLES3::reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->enable_shadows=p_enable;
+ reflection_probe->enable_shadows = p_enable;
reflection_probe->instance_change_notify();
-
}
-void RasterizerStorageGLES3::reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers){
+void RasterizerStorageGLES3::reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) {
ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!reflection_probe);
- reflection_probe->cull_mask=p_layers;
+ reflection_probe->cull_mask = p_layers;
reflection_probe->instance_change_notify();
-
}
Rect3 RasterizerStorageGLES3::reflection_probe_get_aabb(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,Rect3());
+ ERR_FAIL_COND_V(!reflection_probe, Rect3());
Rect3 aabb;
- aabb.pos=-reflection_probe->extents;
- aabb.size=reflection_probe->extents*2.0;
+ aabb.pos = -reflection_probe->extents;
+ aabb.size = reflection_probe->extents * 2.0;
return aabb;
-
-
}
-VS::ReflectionProbeUpdateMode RasterizerStorageGLES3::reflection_probe_get_update_mode(RID p_probe) const{
+VS::ReflectionProbeUpdateMode RasterizerStorageGLES3::reflection_probe_get_update_mode(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,VS::REFLECTION_PROBE_UPDATE_ALWAYS);
+ ERR_FAIL_COND_V(!reflection_probe, VS::REFLECTION_PROBE_UPDATE_ALWAYS);
return reflection_probe->update_mode;
}
@@ -4743,60 +4484,51 @@ VS::ReflectionProbeUpdateMode RasterizerStorageGLES3::reflection_probe_get_updat
uint32_t RasterizerStorageGLES3::reflection_probe_get_cull_mask(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,0);
+ ERR_FAIL_COND_V(!reflection_probe, 0);
return reflection_probe->cull_mask;
-
}
Vector3 RasterizerStorageGLES3::reflection_probe_get_extents(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,Vector3());
+ ERR_FAIL_COND_V(!reflection_probe, Vector3());
return reflection_probe->extents;
-
}
-Vector3 RasterizerStorageGLES3::reflection_probe_get_origin_offset(RID p_probe) const{
+Vector3 RasterizerStorageGLES3::reflection_probe_get_origin_offset(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,Vector3());
+ ERR_FAIL_COND_V(!reflection_probe, Vector3());
return reflection_probe->origin_offset;
-
}
bool RasterizerStorageGLES3::reflection_probe_renders_shadows(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,false);
+ ERR_FAIL_COND_V(!reflection_probe, false);
return reflection_probe->enable_shadows;
-
}
-float RasterizerStorageGLES3::reflection_probe_get_origin_max_distance(RID p_probe) const{
+float RasterizerStorageGLES3::reflection_probe_get_origin_max_distance(RID p_probe) const {
const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!reflection_probe,0);
+ ERR_FAIL_COND_V(!reflection_probe, 0);
return reflection_probe->max_distance;
-
}
/* ROOM API */
-RID RasterizerStorageGLES3::room_create(){
+RID RasterizerStorageGLES3::room_create() {
return RID();
}
-void RasterizerStorageGLES3::room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform){
-
-
+void RasterizerStorageGLES3::room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform) {
}
-void RasterizerStorageGLES3::room_clear_bounds(RID p_room){
-
-
+void RasterizerStorageGLES3::room_clear_bounds(RID p_room) {
}
/* PORTAL API */
@@ -4804,67 +4536,59 @@ void RasterizerStorageGLES3::room_clear_bounds(RID p_room){
// portals are only (x/y) points, forming a convex shape, which its clockwise
// order points outside. (z is 0);
-RID RasterizerStorageGLES3::portal_create(){
+RID RasterizerStorageGLES3::portal_create() {
return RID();
}
-void RasterizerStorageGLES3::portal_set_shape(RID p_portal, const Vector<Point2>& p_shape){
-
-
+void RasterizerStorageGLES3::portal_set_shape(RID p_portal, const Vector<Point2> &p_shape) {
}
-void RasterizerStorageGLES3::portal_set_enabled(RID p_portal, bool p_enabled){
-
-
+void RasterizerStorageGLES3::portal_set_enabled(RID p_portal, bool p_enabled) {
}
-void RasterizerStorageGLES3::portal_set_disable_distance(RID p_portal, float p_distance){
-
-
+void RasterizerStorageGLES3::portal_set_disable_distance(RID p_portal, float p_distance) {
}
-void RasterizerStorageGLES3::portal_set_disabled_color(RID p_portal, const Color& p_color){
-
-
+void RasterizerStorageGLES3::portal_set_disabled_color(RID p_portal, const Color &p_color) {
}
RID RasterizerStorageGLES3::gi_probe_create() {
- GIProbe *gip = memnew( GIProbe );
+ GIProbe *gip = memnew(GIProbe);
- gip->bounds=Rect3(Vector3(),Vector3(1,1,1));
- gip->dynamic_range=1.0;
- gip->energy=1.0;
- gip->propagation=1.0;
- gip->bias=0.4;
- gip->interior=false;
- gip->compress=false;
- gip->version=1;
- gip->cell_size=1.0;
+ gip->bounds = Rect3(Vector3(), Vector3(1, 1, 1));
+ gip->dynamic_range = 1.0;
+ gip->energy = 1.0;
+ gip->propagation = 1.0;
+ gip->bias = 0.4;
+ gip->interior = false;
+ gip->compress = false;
+ gip->version = 1;
+ gip->cell_size = 1.0;
return gi_probe_owner.make_rid(gip);
}
-void RasterizerStorageGLES3::gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds){
+void RasterizerStorageGLES3::gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->bounds=p_bounds;
+ gip->bounds = p_bounds;
gip->version++;
gip->instance_change_notify();
}
-Rect3 RasterizerStorageGLES3::gi_probe_get_bounds(RID p_probe) const{
+Rect3 RasterizerStorageGLES3::gi_probe_get_bounds(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,Rect3());
+ ERR_FAIL_COND_V(!gip, Rect3());
return gip->bounds;
}
-void RasterizerStorageGLES3::gi_probe_set_cell_size(RID p_probe,float p_size) {
+void RasterizerStorageGLES3::gi_probe_set_cell_size(RID p_probe, float p_size) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->cell_size=p_size;
+ gip->cell_size = p_size;
gip->version++;
gip->instance_change_notify();
}
@@ -4872,161 +4596,141 @@ void RasterizerStorageGLES3::gi_probe_set_cell_size(RID p_probe,float p_size) {
float RasterizerStorageGLES3::gi_probe_get_cell_size(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->cell_size;
-
}
-void RasterizerStorageGLES3::gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform) {
+void RasterizerStorageGLES3::gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->to_cell=p_xform;
+ gip->to_cell = p_xform;
}
Transform RasterizerStorageGLES3::gi_probe_get_to_cell_xform(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,Transform());
+ ERR_FAIL_COND_V(!gip, Transform());
return gip->to_cell;
-
}
-
-
-void RasterizerStorageGLES3::gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data){
+void RasterizerStorageGLES3::gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->dynamic_data=p_data;
+ gip->dynamic_data = p_data;
gip->version++;
gip->instance_change_notify();
-
}
-PoolVector<int> RasterizerStorageGLES3::gi_probe_get_dynamic_data(RID p_probe) const{
+PoolVector<int> RasterizerStorageGLES3::gi_probe_get_dynamic_data(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,PoolVector<int>());
+ ERR_FAIL_COND_V(!gip, PoolVector<int>());
return gip->dynamic_data;
}
-void RasterizerStorageGLES3::gi_probe_set_dynamic_range(RID p_probe,int p_range){
+void RasterizerStorageGLES3::gi_probe_set_dynamic_range(RID p_probe, int p_range) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->dynamic_range=p_range;
-
+ gip->dynamic_range = p_range;
}
-int RasterizerStorageGLES3::gi_probe_get_dynamic_range(RID p_probe) const{
+int RasterizerStorageGLES3::gi_probe_get_dynamic_range(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->dynamic_range;
}
-void RasterizerStorageGLES3::gi_probe_set_energy(RID p_probe,float p_range){
+void RasterizerStorageGLES3::gi_probe_set_energy(RID p_probe, float p_range) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->energy=p_range;
-
+ gip->energy = p_range;
}
-
-void RasterizerStorageGLES3::gi_probe_set_bias(RID p_probe,float p_range){
+void RasterizerStorageGLES3::gi_probe_set_bias(RID p_probe, float p_range) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->bias=p_range;
-
+ gip->bias = p_range;
}
-void RasterizerStorageGLES3::gi_probe_set_propagation(RID p_probe,float p_range){
+void RasterizerStorageGLES3::gi_probe_set_propagation(RID p_probe, float p_range) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->propagation=p_range;
-
+ gip->propagation = p_range;
}
-void RasterizerStorageGLES3::gi_probe_set_interior(RID p_probe,bool p_enable) {
+void RasterizerStorageGLES3::gi_probe_set_interior(RID p_probe, bool p_enable) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->interior=p_enable;
-
+ gip->interior = p_enable;
}
-bool RasterizerStorageGLES3::gi_probe_is_interior(RID p_probe) const{
+bool RasterizerStorageGLES3::gi_probe_is_interior(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,false);
+ ERR_FAIL_COND_V(!gip, false);
return gip->interior;
-
}
-
-void RasterizerStorageGLES3::gi_probe_set_compress(RID p_probe,bool p_enable) {
+void RasterizerStorageGLES3::gi_probe_set_compress(RID p_probe, bool p_enable) {
GIProbe *gip = gi_probe_owner.getornull(p_probe);
ERR_FAIL_COND(!gip);
- gip->compress=p_enable;
-
+ gip->compress = p_enable;
}
-bool RasterizerStorageGLES3::gi_probe_is_compressed(RID p_probe) const{
+bool RasterizerStorageGLES3::gi_probe_is_compressed(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,false);
+ ERR_FAIL_COND_V(!gip, false);
return gip->compress;
-
}
-float RasterizerStorageGLES3::gi_probe_get_energy(RID p_probe) const{
+float RasterizerStorageGLES3::gi_probe_get_energy(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->energy;
}
-float RasterizerStorageGLES3::gi_probe_get_bias(RID p_probe) const{
+float RasterizerStorageGLES3::gi_probe_get_bias(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->bias;
}
-
-float RasterizerStorageGLES3::gi_probe_get_propagation(RID p_probe) const{
+float RasterizerStorageGLES3::gi_probe_get_propagation(RID p_probe) const {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->propagation;
}
-
-
-
-
uint32_t RasterizerStorageGLES3::gi_probe_get_version(RID p_probe) {
const GIProbe *gip = gi_probe_owner.getornull(p_probe);
- ERR_FAIL_COND_V(!gip,0);
+ ERR_FAIL_COND_V(!gip, 0);
return gip->version;
}
@@ -5041,39 +4745,39 @@ RasterizerStorage::GIProbeCompression RasterizerStorageGLES3::gi_probe_get_dynam
RID RasterizerStorageGLES3::gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression) {
- GIProbeData *gipd = memnew( GIProbeData );
+ GIProbeData *gipd = memnew(GIProbeData);
- gipd->width=p_width;
- gipd->height=p_height;
- gipd->depth=p_depth;
- gipd->compression=p_compression;
+ gipd->width = p_width;
+ gipd->height = p_height;
+ gipd->depth = p_depth;
+ gipd->compression = p_compression;
glActiveTexture(GL_TEXTURE0);
- glGenTextures(1,&gipd->tex_id);
- glBindTexture(GL_TEXTURE_3D,gipd->tex_id);
+ glGenTextures(1, &gipd->tex_id);
+ glBindTexture(GL_TEXTURE_3D, gipd->tex_id);
- int level=0;
- int min_size=1;
+ int level = 0;
+ int min_size = 1;
- if (gipd->compression==GI_PROBE_S3TC) {
- min_size=4;
+ if (gipd->compression == GI_PROBE_S3TC) {
+ min_size = 4;
}
print_line("dyndata create");
- while(true) {
+ while (true) {
- if (gipd->compression==GI_PROBE_S3TC) {
+ if (gipd->compression == GI_PROBE_S3TC) {
int size = p_width * p_height * p_depth;
- glCompressedTexImage3D(GL_TEXTURE_3D,level,_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT,p_width,p_height,p_depth,0, size,NULL);
+ glCompressedTexImage3D(GL_TEXTURE_3D, level, _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT, p_width, p_height, p_depth, 0, size, NULL);
} else {
- glTexImage3D(GL_TEXTURE_3D,level,GL_RGBA8,p_width,p_height,p_depth,0,GL_RGBA,GL_UNSIGNED_BYTE,NULL);
+ glTexImage3D(GL_TEXTURE_3D, level, GL_RGBA8, p_width, p_height, p_depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
}
- if (p_width<=min_size || p_height<=min_size || p_depth<=min_size)
+ if (p_width <= min_size || p_height <= min_size || p_depth <= min_size)
break;
- p_width>>=1;
- p_height>>=1;
- p_depth>>=1;
+ p_width >>= 1;
+ p_height >>= 1;
+ p_depth >>= 1;
level++;
}
@@ -5085,7 +4789,7 @@ RID RasterizerStorageGLES3::gi_probe_dynamic_data_create(int p_width, int p_heig
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, level);
- gipd->levels=level+1;
+ gipd->levels = level + 1;
return gi_probe_data_owner.make_rid(gipd);
}
@@ -5094,7 +4798,7 @@ void RasterizerStorageGLES3::gi_probe_dynamic_data_update(RID p_gi_probe_data, i
GIProbeData *gipd = gi_probe_data_owner.getornull(p_gi_probe_data);
ERR_FAIL_COND(!gipd);
-/*
+ /*
Vector<uint8_t> data;
data.resize((gipd->width>>p_mipmap)*(gipd->height>>p_mipmap)*(gipd->depth>>p_mipmap)*4);
@@ -5113,120 +4817,109 @@ void RasterizerStorageGLES3::gi_probe_dynamic_data_update(RID p_gi_probe_data, i
}
*/
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_3D,gipd->tex_id);
- if (gipd->compression==GI_PROBE_S3TC) {
- int size = (gipd->width>>p_mipmap) * (gipd->height>>p_mipmap) * p_slice_count;
- glCompressedTexSubImage3D(GL_TEXTURE_3D,p_mipmap,0,0,p_depth_slice,gipd->width>>p_mipmap,gipd->height>>p_mipmap,p_slice_count,_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT,size, p_data);
+ glBindTexture(GL_TEXTURE_3D, gipd->tex_id);
+ if (gipd->compression == GI_PROBE_S3TC) {
+ int size = (gipd->width >> p_mipmap) * (gipd->height >> p_mipmap) * p_slice_count;
+ glCompressedTexSubImage3D(GL_TEXTURE_3D, p_mipmap, 0, 0, p_depth_slice, gipd->width >> p_mipmap, gipd->height >> p_mipmap, p_slice_count, _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT, size, p_data);
} else {
- glTexSubImage3D(GL_TEXTURE_3D,p_mipmap,0,0,p_depth_slice,gipd->width>>p_mipmap,gipd->height>>p_mipmap,p_slice_count,GL_RGBA,GL_UNSIGNED_BYTE,p_data);
+ glTexSubImage3D(GL_TEXTURE_3D, p_mipmap, 0, 0, p_depth_slice, gipd->width >> p_mipmap, gipd->height >> p_mipmap, p_slice_count, GL_RGBA, GL_UNSIGNED_BYTE, p_data);
}
//glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,p_data);
//glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,data.ptr());
-
}
///////
-
-
RID RasterizerStorageGLES3::particles_create() {
- Particles *particles = memnew( Particles );
-
+ Particles *particles = memnew(Particles);
return particles_owner.make_rid(particles);
}
-void RasterizerStorageGLES3::particles_set_emitting(RID p_particles,bool p_emitting) {
+void RasterizerStorageGLES3::particles_set_emitting(RID p_particles, bool p_emitting) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->emitting=p_emitting;
-
+ particles->emitting = p_emitting;
}
-void RasterizerStorageGLES3::particles_set_amount(RID p_particles,int p_amount) {
+void RasterizerStorageGLES3::particles_set_amount(RID p_particles, int p_amount) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- int floats = p_amount*24;
- float * data = memnew_arr(float,floats);
+ int floats = p_amount * 24;
+ float *data = memnew_arr(float, floats);
- for(int i=0;i<floats;i++) {
- data[i]=0;
+ for (int i = 0; i < floats; i++) {
+ data[i] = 0;
}
+ glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]);
+ glBufferData(GL_ARRAY_BUFFER, floats * sizeof(float), data, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[0]);
- glBufferData(GL_ARRAY_BUFFER,floats*sizeof(float),data,GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[1]);
+ glBufferData(GL_ARRAY_BUFFER, floats * sizeof(float), data, GL_DYNAMIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[1]);
- glBufferData(GL_ARRAY_BUFFER,floats*sizeof(float),data,GL_DYNAMIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
- glBindBuffer(GL_ARRAY_BUFFER,0);
-
- particles->prev_ticks=0;
- particles->phase=0;
- particles->prev_phase=0;
+ particles->prev_ticks = 0;
+ particles->phase = 0;
+ particles->prev_phase = 0;
memdelete_arr(data);
-
}
-void RasterizerStorageGLES3::particles_set_lifetime(RID p_particles,float p_lifetime){
+void RasterizerStorageGLES3::particles_set_lifetime(RID p_particles, float p_lifetime) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->lifetime=p_lifetime;
+ particles->lifetime = p_lifetime;
}
-void RasterizerStorageGLES3::particles_set_pre_process_time(RID p_particles,float p_time) {
+void RasterizerStorageGLES3::particles_set_pre_process_time(RID p_particles, float p_time) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->pre_process_time=p_time;
-
+ particles->pre_process_time = p_time;
}
-void RasterizerStorageGLES3::particles_set_explosiveness_ratio(RID p_particles,float p_ratio) {
+void RasterizerStorageGLES3::particles_set_explosiveness_ratio(RID p_particles, float p_ratio) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->explosiveness=p_ratio;
+ particles->explosiveness = p_ratio;
}
-void RasterizerStorageGLES3::particles_set_randomness_ratio(RID p_particles,float p_ratio) {
+void RasterizerStorageGLES3::particles_set_randomness_ratio(RID p_particles, float p_ratio) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->randomness=p_ratio;
-
+ particles->randomness = p_ratio;
}
-void RasterizerStorageGLES3::particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb) {
+void RasterizerStorageGLES3::particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->custom_aabb=p_aabb;
-
+ particles->custom_aabb = p_aabb;
}
-void RasterizerStorageGLES3::particles_set_gravity(RID p_particles,const Vector3& p_gravity) {
+void RasterizerStorageGLES3::particles_set_gravity(RID p_particles, const Vector3 &p_gravity) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->gravity=p_gravity;
-
+ particles->gravity = p_gravity;
}
-void RasterizerStorageGLES3::particles_set_use_local_coordinates(RID p_particles,bool p_enable) {
+void RasterizerStorageGLES3::particles_set_use_local_coordinates(RID p_particles, bool p_enable) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->use_local_coords=p_enable;
+ particles->use_local_coords = p_enable;
}
-void RasterizerStorageGLES3::particles_set_process_material(RID p_particles,RID p_material) {
+void RasterizerStorageGLES3::particles_set_process_material(RID p_particles, RID p_material) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->process_material=p_material;
+ particles->process_material = p_material;
}
void RasterizerStorageGLES3::particles_set_emission_shape(RID p_particles, VS::ParticlesEmissionShape p_shape) {
@@ -5234,67 +4927,64 @@ void RasterizerStorageGLES3::particles_set_emission_shape(RID p_particles, VS::P
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->emission_shape=p_shape;
+ particles->emission_shape = p_shape;
}
-void RasterizerStorageGLES3::particles_set_emission_sphere_radius(RID p_particles,float p_radius) {
+void RasterizerStorageGLES3::particles_set_emission_sphere_radius(RID p_particles, float p_radius) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->emission_sphere_radius=p_radius;
+ particles->emission_sphere_radius = p_radius;
}
-void RasterizerStorageGLES3::particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents) {
+void RasterizerStorageGLES3::particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->emission_box_extents=p_extents;
+ particles->emission_box_extents = p_extents;
}
-void RasterizerStorageGLES3::particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points) {
+void RasterizerStorageGLES3::particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->emission_points=p_points;
+ particles->emission_points = p_points;
}
-
-void RasterizerStorageGLES3::particles_set_draw_order(RID p_particles,VS::ParticlesDrawOrder p_order) {
+void RasterizerStorageGLES3::particles_set_draw_order(RID p_particles, VS::ParticlesDrawOrder p_order) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- particles->draw_order=p_order;
+ particles->draw_order = p_order;
}
-void RasterizerStorageGLES3::particles_set_draw_passes(RID p_particles,int p_count) {
+void RasterizerStorageGLES3::particles_set_draw_passes(RID p_particles, int p_count) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
particles->draw_passes.resize(p_count);
}
-void RasterizerStorageGLES3::particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material) {
+void RasterizerStorageGLES3::particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_INDEX(p_pass,particles->draw_passes.size());
- particles->draw_passes[p_pass].material=p_material;
-
+ ERR_FAIL_INDEX(p_pass, particles->draw_passes.size());
+ particles->draw_passes[p_pass].material = p_material;
}
-void RasterizerStorageGLES3::particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh) {
+void RasterizerStorageGLES3::particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) {
Particles *particles = particles_owner.getornull(p_particles);
ERR_FAIL_COND(!particles);
- ERR_FAIL_INDEX(p_pass,particles->draw_passes.size());
- particles->draw_passes[p_pass].mesh=p_mesh;
-
+ ERR_FAIL_INDEX(p_pass, particles->draw_passes.size());
+ particles->draw_passes[p_pass].mesh = p_mesh;
}
Rect3 RasterizerStorageGLES3::particles_get_current_aabb(RID p_particles) {
const Particles *particles = particles_owner.getornull(p_particles);
- ERR_FAIL_COND_V(!particles,Rect3());
+ ERR_FAIL_COND_V(!particles, Rect3());
return particles->computed_aabb;
}
@@ -5304,122 +4994,111 @@ void RasterizerStorageGLES3::update_particles() {
glEnable(GL_RASTERIZER_DISCARD);
glBindVertexArray(0);
-
while (particle_update_list.first()) {
//use transform feedback to process particles
Particles *particles = particle_update_list.first()->self();
-
Material *material = material_owner.getornull(particles->process_material);
- if (!material || !material->shader || material->shader->mode!=VS::SHADER_PARTICLES) {
+ if (!material || !material->shader || material->shader->mode != VS::SHADER_PARTICLES) {
shaders.particles.set_custom_shader(0);
} else {
- shaders.particles.set_custom_shader( material->shader->custom_code_id );
+ shaders.particles.set_custom_shader(material->shader->custom_code_id);
if (material->ubo_id) {
- glBindBufferBase(GL_UNIFORM_BUFFER,0,material->ubo_id);
+ glBindBufferBase(GL_UNIFORM_BUFFER, 0, material->ubo_id);
}
int tc = material->textures.size();
- RID* textures = material->textures.ptr();
- ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = material->shader->texture_hints.ptr();
+ RID *textures = material->textures.ptr();
+ ShaderLanguage::ShaderNode::Uniform::Hint *texture_hints = material->shader->texture_hints.ptr();
+ for (int i = 0; i < tc; i++) {
- for(int i=0;i<tc;i++) {
-
- glActiveTexture(GL_TEXTURE0+i);
+ glActiveTexture(GL_TEXTURE0 + i);
GLenum target;
GLuint tex;
- RasterizerStorageGLES3::Texture *t = texture_owner.getornull( textures[i] );
+ RasterizerStorageGLES3::Texture *t = texture_owner.getornull(textures[i]);
if (!t) {
//check hints
- target=GL_TEXTURE_2D;
+ target = GL_TEXTURE_2D;
- switch(texture_hints[i]) {
+ switch (texture_hints[i]) {
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO:
case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: {
- tex=resources.black_tex;
+ tex = resources.black_tex;
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: {
- tex=resources.aniso_tex;
+ tex = resources.aniso_tex;
} break;
case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: {
- tex=resources.normal_tex;
+ tex = resources.normal_tex;
} break;
default: {
- tex=resources.white_tex;
+ tex = resources.white_tex;
} break;
}
-
} else {
- target=t->target;
+ target = t->target;
tex = t->tex_id;
-
}
- glBindTexture(target,tex);
+ glBindTexture(target, tex);
}
-
}
shaders.particles.bind();
- shaders.particles.set_uniform(ParticlesShaderGLES3::ORIGIN,particles->origin);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::ORIGIN, particles->origin);
- float new_phase = Math::fmod((float)particles->phase+(frame.delta/particles->lifetime),(float)1.0);
+ float new_phase = Math::fmod((float)particles->phase + (frame.delta / particles->lifetime), (float)1.0);
- shaders.particles.set_uniform(ParticlesShaderGLES3::SYSTEM_PHASE,new_phase);
- shaders.particles.set_uniform(ParticlesShaderGLES3::PREV_SYSTEM_PHASE,particles->phase);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::SYSTEM_PHASE, new_phase);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::PREV_SYSTEM_PHASE, particles->phase);
particles->phase = new_phase;
- shaders.particles.set_uniform(ParticlesShaderGLES3::TOTAL_PARTICLES,particles->amount);
- shaders.particles.set_uniform(ParticlesShaderGLES3::TIME,0.0);
- shaders.particles.set_uniform(ParticlesShaderGLES3::EXPLOSIVENESS,particles->explosiveness);
- shaders.particles.set_uniform(ParticlesShaderGLES3::DELTA,frame.delta);
- shaders.particles.set_uniform(ParticlesShaderGLES3::GRAVITY,particles->gravity);
- shaders.particles.set_uniform(ParticlesShaderGLES3::ATTRACTOR_COUNT,0);
-
-
+ shaders.particles.set_uniform(ParticlesShaderGLES3::TOTAL_PARTICLES, particles->amount);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::TIME, 0.0);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::EXPLOSIVENESS, particles->explosiveness);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::DELTA, frame.delta);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::GRAVITY, particles->gravity);
+ shaders.particles.set_uniform(ParticlesShaderGLES3::ATTRACTOR_COUNT, 0);
-
- glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[0]);
+ glBindBuffer(GL_ARRAY_BUFFER, particles->particle_buffers[0]);
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, particles->particle_buffers[1]);
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glEnableVertexAttribArray(i);
- glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,sizeof(float)*4*6,((uint8_t*)0)+(i*16));
+ glVertexAttribPointer(i, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4 * 6, ((uint8_t *)0) + (i * 16));
}
-
glBeginTransformFeedback(GL_POINTS);
- glDrawArrays(GL_POINTS,0,particles->amount);
+ glDrawArrays(GL_POINTS, 0, particles->amount);
glEndTransformFeedback();
particle_update_list.remove(particle_update_list.first());
- SWAP(particles->particle_buffers[0],particles->particle_buffers[1]);
+ SWAP(particles->particle_buffers[0], particles->particle_buffers[1]);
}
glDisable(GL_RASTERIZER_DISCARD);
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
glDisableVertexAttribArray(i);
}
-
}
////////
-void RasterizerStorageGLES3::instance_add_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance) {
+void RasterizerStorageGLES3::instance_add_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
ERR_FAIL_COND(!skeleton);
@@ -5427,7 +5106,7 @@ void RasterizerStorageGLES3::instance_add_skeleton(RID p_skeleton,RasterizerScen
skeleton->instances.insert(p_instance);
}
-void RasterizerStorageGLES3::instance_remove_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance) {
+void RasterizerStorageGLES3::instance_remove_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) {
Skeleton *skeleton = skeleton_owner.getornull(p_skeleton);
ERR_FAIL_COND(!skeleton);
@@ -5435,11 +5114,10 @@ void RasterizerStorageGLES3::instance_remove_skeleton(RID p_skeleton,RasterizerS
skeleton->instances.erase(p_instance);
}
+void RasterizerStorageGLES3::instance_add_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) {
-void RasterizerStorageGLES3::instance_add_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance) {
-
- Instantiable *inst=NULL;
- switch(p_instance->base_type) {
+ Instantiable *inst = NULL;
+ switch (p_instance->base_type) {
case VS::INSTANCE_MESH: {
inst = mesh_owner.getornull(p_base);
ERR_FAIL_COND(!inst);
@@ -5471,14 +5149,14 @@ void RasterizerStorageGLES3::instance_add_dependency(RID p_base,RasterizerScene:
}
}
- inst->instance_list.add( &p_instance->dependency_item );
+ inst->instance_list.add(&p_instance->dependency_item);
}
-void RasterizerStorageGLES3::instance_remove_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance){
+void RasterizerStorageGLES3::instance_remove_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) {
- Instantiable *inst=NULL;
+ Instantiable *inst = NULL;
- switch(p_instance->base_type) {
+ switch (p_instance->base_type) {
case VS::INSTANCE_MESH: {
inst = mesh_owner.getornull(p_base);
ERR_FAIL_COND(!inst);
@@ -5513,85 +5191,76 @@ void RasterizerStorageGLES3::instance_remove_dependency(RID p_base,RasterizerSce
ERR_FAIL_COND(!inst);
- inst->instance_list.remove( &p_instance->dependency_item );
+ inst->instance_list.remove(&p_instance->dependency_item);
}
-
/* RENDER TARGET */
-
void RasterizerStorageGLES3::_render_target_clear(RenderTarget *rt) {
-
if (rt->fbo) {
- glDeleteFramebuffers(1,&rt->fbo);
- glDeleteTextures(1,&rt->color);
- rt->fbo=0;
+ glDeleteFramebuffers(1, &rt->fbo);
+ glDeleteTextures(1, &rt->color);
+ rt->fbo = 0;
}
-
if (rt->buffers.fbo) {
- glDeleteFramebuffers(1,&rt->buffers.fbo);
- glDeleteRenderbuffers(1,&rt->buffers.depth);
- glDeleteRenderbuffers(1,&rt->buffers.diffuse);
- glDeleteRenderbuffers(1,&rt->buffers.specular);
- glDeleteRenderbuffers(1,&rt->buffers.normal_rough);
- glDeleteRenderbuffers(1,&rt->buffers.motion_sss);
- glDeleteFramebuffers(1,&rt->buffers.effect_fbo);
- glDeleteTextures(1,&rt->buffers.effect);
+ glDeleteFramebuffers(1, &rt->buffers.fbo);
+ glDeleteRenderbuffers(1, &rt->buffers.depth);
+ glDeleteRenderbuffers(1, &rt->buffers.diffuse);
+ glDeleteRenderbuffers(1, &rt->buffers.specular);
+ glDeleteRenderbuffers(1, &rt->buffers.normal_rough);
+ glDeleteRenderbuffers(1, &rt->buffers.motion_sss);
+ glDeleteFramebuffers(1, &rt->buffers.effect_fbo);
+ glDeleteTextures(1, &rt->buffers.effect);
- rt->buffers.fbo=0;
+ rt->buffers.fbo = 0;
}
-
if (rt->depth) {
- glDeleteTextures(1,&rt->depth);
- rt->depth=0;
+ glDeleteTextures(1, &rt->depth);
+ rt->depth = 0;
}
-
if (rt->effects.ssao.blur_fbo[0]) {
- glDeleteFramebuffers(1,&rt->effects.ssao.blur_fbo[0]);
- glDeleteTextures(1,&rt->effects.ssao.blur_red[0]);
- glDeleteFramebuffers(1,&rt->effects.ssao.blur_fbo[1]);
- glDeleteTextures(1,&rt->effects.ssao.blur_red[1]);
- for(int i=0;i<rt->effects.ssao.depth_mipmap_fbos.size();i++) {
- glDeleteFramebuffers(1,&rt->effects.ssao.depth_mipmap_fbos[i]);
+ glDeleteFramebuffers(1, &rt->effects.ssao.blur_fbo[0]);
+ glDeleteTextures(1, &rt->effects.ssao.blur_red[0]);
+ glDeleteFramebuffers(1, &rt->effects.ssao.blur_fbo[1]);
+ glDeleteTextures(1, &rt->effects.ssao.blur_red[1]);
+ for (int i = 0; i < rt->effects.ssao.depth_mipmap_fbos.size(); i++) {
+ glDeleteFramebuffers(1, &rt->effects.ssao.depth_mipmap_fbos[i]);
}
rt->effects.ssao.depth_mipmap_fbos.clear();
- glDeleteTextures(1,&rt->effects.ssao.linear_depth);
+ glDeleteTextures(1, &rt->effects.ssao.linear_depth);
- rt->effects.ssao.blur_fbo[0]=0;
- rt->effects.ssao.blur_fbo[1]=0;
+ rt->effects.ssao.blur_fbo[0] = 0;
+ rt->effects.ssao.blur_fbo[1] = 0;
}
-
if (rt->exposure.fbo) {
- glDeleteFramebuffers(1,&rt->exposure.fbo);
- glDeleteTextures(1,&rt->exposure.color);
- rt->exposure.fbo=0;
+ glDeleteFramebuffers(1, &rt->exposure.fbo);
+ glDeleteTextures(1, &rt->exposure.color);
+ rt->exposure.fbo = 0;
}
Texture *tex = texture_owner.get(rt->texture);
- tex->alloc_height=0;
- tex->alloc_width=0;
- tex->width=0;
- tex->height=0;
-
-
- for(int i=0;i<2;i++) {
- for(int j=0;j<rt->effects.mip_maps[i].sizes.size();j++) {
- glDeleteFramebuffers(1,&rt->effects.mip_maps[i].sizes[j].fbo);
+ tex->alloc_height = 0;
+ tex->alloc_width = 0;
+ tex->width = 0;
+ tex->height = 0;
+
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < rt->effects.mip_maps[i].sizes.size(); j++) {
+ glDeleteFramebuffers(1, &rt->effects.mip_maps[i].sizes[j].fbo);
}
- glDeleteTextures(1,&rt->effects.mip_maps[i].color);
+ glDeleteTextures(1, &rt->effects.mip_maps[i].color);
rt->effects.mip_maps[i].sizes.clear();
- rt->effects.mip_maps[i].levels=0;
+ rt->effects.mip_maps[i].levels = 0;
}
-
-/*
+ /*
if (rt->effects.screen_space_depth) {
glDeleteTextures(1,&rt->effects.screen_space_depth);
rt->effects.screen_space_depth=0;
@@ -5600,9 +5269,9 @@ void RasterizerStorageGLES3::_render_target_clear(RenderTarget *rt) {
*/
}
-void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
+void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt) {
- if (rt->width<=0 || rt->height<=0)
+ if (rt->width <= 0 || rt->height <= 0)
return;
GLuint color_internal_format;
@@ -5611,22 +5280,21 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
Image::Format image_format;
bool hdr = rt->flags[RENDER_TARGET_HDR] && config.hdr_supported;
- hdr=false;
+ hdr = false;
if (!hdr || rt->flags[RENDER_TARGET_NO_3D]) {
- color_internal_format=GL_RGBA8;
- color_format=GL_RGBA;
- color_type=GL_UNSIGNED_BYTE;
- image_format=Image::FORMAT_RGBA8;
+ color_internal_format = GL_RGBA8;
+ color_format = GL_RGBA;
+ color_type = GL_UNSIGNED_BYTE;
+ image_format = Image::FORMAT_RGBA8;
} else {
- color_internal_format=GL_RGBA16F;
- color_format=GL_RGBA;
- color_type=GL_HALF_FLOAT;
- image_format=Image::FORMAT_RGBAH;
+ color_internal_format = GL_RGBA16F;
+ color_format = GL_RGBA;
+ color_type = GL_HALF_FLOAT;
+ image_format = Image::FORMAT_RGBAH;
}
-
{
/* FRONT FBO */
@@ -5635,23 +5303,22 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glGenFramebuffers(1, &rt->fbo);
glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo);
-
glGenTextures(1, &rt->depth);
glBindTexture(GL_TEXTURE_2D, rt->depth);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, rt->width, rt->height, 0,
- GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
+ GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, rt->depth, 0);
+ GL_TEXTURE_2D, rt->depth, 0);
glGenTextures(1, &rt->color);
glBindTexture(GL_TEXTURE_2D, rt->color);
- glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
@@ -5663,36 +5330,31 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- printf("framebuffer fail, status: %x\n",status);
+ printf("framebuffer fail, status: %x\n", status);
}
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
Texture *tex = texture_owner.get(rt->texture);
- tex->format=image_format;
- tex->gl_format_cache=color_format;
- tex->gl_type_cache=color_type;
- tex->gl_internal_format_cache=color_internal_format;
- tex->tex_id=rt->color;
- tex->width=rt->width;
- tex->alloc_width=rt->width;
- tex->height=rt->height;
- tex->alloc_height=rt->height;
-
-
- texture_set_flags(rt->texture,tex->flags);
+ tex->format = image_format;
+ tex->gl_format_cache = color_format;
+ tex->gl_type_cache = color_type;
+ tex->gl_internal_format_cache = color_internal_format;
+ tex->tex_id = rt->color;
+ tex->width = rt->width;
+ tex->alloc_width = rt->width;
+ tex->height = rt->height;
+ tex->alloc_height = rt->height;
+ texture_set_flags(rt->texture, tex->flags);
}
-
/* BACK FBO */
- if (config.render_arch==RENDER_ARCH_DESKTOP && !rt->flags[RENDER_TARGET_NO_3D]) {
-
-
+ if (config.render_arch == RENDER_ARCH_DESKTOP && !rt->flags[RENDER_TARGET_NO_3D]) {
- static const int msaa_value[]={0,2,4,8,16};
- int msaa=msaa_value[rt->msaa];
+ static const int msaa_value[] = { 0, 2, 4, 8, 16 };
+ int msaa = msaa_value[rt->msaa];
//regular fbo
glGenFramebuffers(1, &rt->buffers.fbo);
@@ -5700,66 +5362,63 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glGenRenderbuffers(1, &rt->buffers.depth);
glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.depth);
- if (msaa==0)
- glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH24_STENCIL8,rt->width,rt->height);
+ if (msaa == 0)
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, rt->width, rt->height);
else
- glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_DEPTH24_STENCIL8,rt->width,rt->height);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_DEPTH24_STENCIL8, rt->width, rt->height);
+
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rt->buffers.depth);
- glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,rt->buffers.depth);
-
glGenRenderbuffers(1, &rt->buffers.diffuse);
glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.diffuse);
- if (msaa==0)
- glRenderbufferStorage(GL_RENDERBUFFER,color_internal_format,rt->width,rt->height);
+ if (msaa == 0)
+ glRenderbufferStorage(GL_RENDERBUFFER, color_internal_format, rt->width, rt->height);
else
- glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,color_internal_format,rt->width,rt->height);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height);
- glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_RENDERBUFFER,rt->buffers.diffuse);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rt->buffers.diffuse);
glGenRenderbuffers(1, &rt->buffers.specular);
glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.specular);
- if (msaa==0)
- glRenderbufferStorage(GL_RENDERBUFFER,color_internal_format,rt->width,rt->height);
+ if (msaa == 0)
+ glRenderbufferStorage(GL_RENDERBUFFER, color_internal_format, rt->width, rt->height);
else
- glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,color_internal_format,rt->width,rt->height);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, color_internal_format, rt->width, rt->height);
- glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,GL_RENDERBUFFER,rt->buffers.specular);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_RENDERBUFFER, rt->buffers.specular);
glGenRenderbuffers(1, &rt->buffers.normal_rough);
glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.normal_rough);
- if (msaa==0)
- glRenderbufferStorage(GL_RENDERBUFFER,GL_RGBA8,rt->width,rt->height);
+ if (msaa == 0)
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, rt->width, rt->height);
else
- glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA8,rt->width,rt->height);
-
- glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT2,GL_RENDERBUFFER,rt->buffers.normal_rough);
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_RGBA8, rt->width, rt->height);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_RENDERBUFFER, rt->buffers.normal_rough);
glGenRenderbuffers(1, &rt->buffers.motion_sss);
glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.motion_sss);
- if (msaa==0)
- glRenderbufferStorage(GL_RENDERBUFFER,GL_RGBA8,rt->width,rt->height);
+ if (msaa == 0)
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, rt->width, rt->height);
else
- glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA8,rt->width,rt->height);
-
- glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT3,GL_RENDERBUFFER,rt->buffers.motion_sss);
-
+ glRenderbufferStorageMultisample(GL_RENDERBUFFER, msaa, GL_RGBA8, rt->width, rt->height);
+ glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_RENDERBUFFER, rt->buffers.motion_sss);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- printf("err status: %x\n",status);
+ printf("err status: %x\n", status);
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
- }
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
+ }
- glBindRenderbuffer(GL_RENDERBUFFER,0);
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
// effect resolver
@@ -5769,92 +5428,84 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glGenTextures(1, &rt->buffers.effect);
glBindTexture(GL_TEXTURE_2D, rt->buffers.effect);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, rt->width, rt->height, 0,
- GL_RGBA, GL_UNSIGNED_BYTE, NULL);
+ GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
- GL_TEXTURE_2D, rt->buffers.effect, 0);
-
+ GL_TEXTURE_2D, rt->buffers.effect, 0);
if (status != GL_FRAMEBUFFER_COMPLETE) {
- printf("err status: %x\n",status);
+ printf("err status: %x\n", status);
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
}
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE) {
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
}
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- ERR_FAIL_COND( rt->effects.mip_maps[i].sizes.size() );
- int w=rt->width;
- int h=rt->height;
+ ERR_FAIL_COND(rt->effects.mip_maps[i].sizes.size());
+ int w = rt->width;
+ int h = rt->height;
-
- if (i>0) {
- w>>=1;
- h>>=1;
+ if (i > 0) {
+ w >>= 1;
+ h >>= 1;
}
-
glGenTextures(1, &rt->effects.mip_maps[i].color);
glBindTexture(GL_TEXTURE_2D, rt->effects.mip_maps[i].color);
- int level=0;
+ int level = 0;
- while(true) {
+ while (true) {
RenderTarget::Effects::MipMaps::Size mm;
- glTexImage2D(GL_TEXTURE_2D, level, color_internal_format, w, h, 0, color_format, color_type, NULL);
- mm.width=w;
- mm.height=h;
+ glTexImage2D(GL_TEXTURE_2D, level, color_internal_format, w, h, 0, color_format, color_type, NULL);
+ mm.width = w;
+ mm.height = h;
rt->effects.mip_maps[i].sizes.push_back(mm);
- w>>=1;
- h>>=1;
+ w >>= 1;
+ h >>= 1;
- if (w<2 || h<2)
+ if (w < 2 || h < 2)
break;
level++;
-
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level);
+ for (int j = 0; j < rt->effects.mip_maps[i].sizes.size(); j++) {
- for(int j=0;j<rt->effects.mip_maps[i].sizes.size();j++) {
-
- RenderTarget::Effects::MipMaps::Size &mm=rt->effects.mip_maps[i].sizes[j];
+ RenderTarget::Effects::MipMaps::Size &mm = rt->effects.mip_maps[i].sizes[j];
glGenFramebuffers(1, &mm.fbo);
glBindFramebuffer(GL_FRAMEBUFFER, mm.fbo);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,rt->effects.mip_maps[i].color ,j);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.mip_maps[i].color, j);
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
}
-
- float zero[4]={1,0,1,0};
- glClearBufferfv(GL_COLOR,0,zero);
-
-
+ float zero[4] = { 1, 0, 1, 0 };
+ glClearBufferfv(GL_COLOR, 0, zero);
}
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
- rt->effects.mip_maps[i].levels=level;
+ rt->effects.mip_maps[i].levels = level;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
@@ -5862,23 +5513,21 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
-
-
}
///////////////// ssao
//AO strength textures
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
glGenFramebuffers(1, &rt->effects.ssao.blur_fbo[i]);
glBindFramebuffer(GL_FRAMEBUFFER, rt->effects.ssao.blur_fbo[i]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
- GL_TEXTURE_2D, rt->depth, 0);
+ GL_TEXTURE_2D, rt->depth, 0);
glGenTextures(1, &rt->effects.ssao.blur_red[i]);
glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.blur_red[i]);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, rt->width, rt->height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, rt->width, rt->height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@@ -5889,24 +5538,22 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
}
-
}
//5 mip levels for depth texture, but base is read separately
glGenTextures(1, &rt->effects.ssao.linear_depth);
glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.linear_depth);
- int ssao_w=rt->width/2;
- int ssao_h=rt->height/2;
+ int ssao_w = rt->width / 2;
+ int ssao_h = rt->height / 2;
+ for (int i = 0; i < 4; i++) { //5, but 4 mips, base is read directly to save bw
- for(int i=0;i<4;i++) { //5, but 4 mips, base is read directly to save bw
-
- glTexImage2D(GL_TEXTURE_2D, i, GL_R16UI, ssao_w, ssao_h, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, NULL);
- ssao_w>>=1;
- ssao_h>>=1;
+ glTexImage2D(GL_TEXTURE_2D, i, GL_R16UI, ssao_w, ssao_h, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, NULL);
+ ssao_w >>= 1;
+ ssao_h >>= 1;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
@@ -5916,7 +5563,7 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 3);
- for(int i=0;i<4;i++) { //5, but 4 mips, base is read directly to save bw
+ for (int i = 0; i < 4; i++) { //5, but 4 mips, base is read directly to save bw
GLuint fbo;
glGenFramebuffers(1, &fbo);
@@ -5925,7 +5572,6 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
rt->effects.ssao.depth_mipmap_fbos.push_back(fbo);
}
-
//////Exposure
glGenFramebuffers(1, &rt->exposure.fbo);
@@ -5933,82 +5579,77 @@ void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){
glGenTextures(1, &rt->exposure.color);
glBindTexture(GL_TEXTURE_2D, rt->exposure.color);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 1, 1, 0, GL_RED, GL_FLOAT, NULL);
- glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->exposure.color, 0);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 1, 1, 0, GL_RED, GL_FLOAT, NULL);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->exposure.color, 0);
status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
_render_target_clear(rt);
- ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE );
+ ERR_FAIL_COND(status != GL_FRAMEBUFFER_COMPLETE);
}
-
}
}
+RID RasterizerStorageGLES3::render_target_create() {
-RID RasterizerStorageGLES3::render_target_create(){
-
- RenderTarget *rt = memnew( RenderTarget );
+ RenderTarget *rt = memnew(RenderTarget);
- Texture * t = memnew( Texture );
+ Texture *t = memnew(Texture);
- t->flags=0;
- t->width=0;
- t->height=0;
- t->alloc_height=0;
- t->alloc_width=0;
- t->format=Image::FORMAT_R8;
- t->target=GL_TEXTURE_2D;
- t->gl_format_cache=0;
- t->gl_internal_format_cache=0;
- t->gl_type_cache=0;
- t->data_size=0;
- t->compressed=false;
- t->srgb=false;
- t->total_data_size=0;
- t->ignore_mipmaps=false;
- t->mipmaps=0;
- t->active=true;
- t->tex_id=0;
+ t->flags = 0;
+ t->width = 0;
+ t->height = 0;
+ t->alloc_height = 0;
+ t->alloc_width = 0;
+ t->format = Image::FORMAT_R8;
+ t->target = GL_TEXTURE_2D;
+ t->gl_format_cache = 0;
+ t->gl_internal_format_cache = 0;
+ t->gl_type_cache = 0;
+ t->data_size = 0;
+ t->compressed = false;
+ t->srgb = false;
+ t->total_data_size = 0;
+ t->ignore_mipmaps = false;
+ t->mipmaps = 0;
+ t->active = true;
+ t->tex_id = 0;
-
- rt->texture=texture_owner.make_rid(t);
+ rt->texture = texture_owner.make_rid(t);
return render_target_owner.make_rid(rt);
}
-void RasterizerStorageGLES3::render_target_set_size(RID p_render_target,int p_width, int p_height){
+void RasterizerStorageGLES3::render_target_set_size(RID p_render_target, int p_width, int p_height) {
RenderTarget *rt = render_target_owner.getornull(p_render_target);
ERR_FAIL_COND(!rt);
- if (rt->width==p_width && rt->height==p_height)
+ if (rt->width == p_width && rt->height == p_height)
return;
_render_target_clear(rt);
- rt->width=p_width;
- rt->height=p_height;
+ rt->width = p_width;
+ rt->height = p_height;
_render_target_allocate(rt);
-
}
-
-RID RasterizerStorageGLES3::render_target_get_texture(RID p_render_target) const{
+RID RasterizerStorageGLES3::render_target_get_texture(RID p_render_target) const {
RenderTarget *rt = render_target_owner.getornull(p_render_target);
- ERR_FAIL_COND_V(!rt,RID());
+ ERR_FAIL_COND_V(!rt, RID());
return rt->texture;
}
-void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target,RenderTargetFlags p_flag,bool p_value) {
+void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) {
RenderTarget *rt = render_target_owner.getornull(p_render_target);
ERR_FAIL_COND(!rt);
- rt->flags[p_flag]=p_value;
+ rt->flags[p_flag] = p_value;
- switch(p_flag) {
+ switch (p_flag) {
case RENDER_TARGET_NO_3D:
case RENDER_TARGET_TRANSPARENT: {
//must reset for these formats
@@ -6020,36 +5661,34 @@ void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target,RenderTa
}
}
-bool RasterizerStorageGLES3::render_target_renedered_in_frame(RID p_render_target){
+bool RasterizerStorageGLES3::render_target_renedered_in_frame(RID p_render_target) {
return false;
}
-void RasterizerStorageGLES3::render_target_set_msaa(RID p_render_target,VS::ViewportMSAA p_msaa) {
+void RasterizerStorageGLES3::render_target_set_msaa(RID p_render_target, VS::ViewportMSAA p_msaa) {
RenderTarget *rt = render_target_owner.getornull(p_render_target);
ERR_FAIL_COND(!rt);
- if (rt->msaa==p_msaa)
+ if (rt->msaa == p_msaa)
return;
_render_target_clear(rt);
- rt->msaa=p_msaa;
+ rt->msaa = p_msaa;
_render_target_allocate(rt);
-
}
/* CANVAS SHADOW */
-
RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) {
- CanvasLightShadow *cls = memnew( CanvasLightShadow );
- if (p_width>config.max_texture_size)
- p_width=config.max_texture_size;
+ CanvasLightShadow *cls = memnew(CanvasLightShadow);
+ if (p_width > config.max_texture_size)
+ p_width = config.max_texture_size;
- cls->size=p_width;
- cls->height=16;
+ cls->size = p_width;
+ cls->height = 16;
glActiveTexture(GL_TEXTURE0);
@@ -6057,12 +5696,12 @@ RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) {
glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo);
glGenRenderbuffers(1, &cls->depth);
- glBindRenderbuffer(GL_RENDERBUFFER, cls->depth );
- glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT24, cls->size, cls->height);
+ glBindRenderbuffer(GL_RENDERBUFFER, cls->depth);
+ glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, cls->size, cls->height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, cls->depth);
- glBindRenderbuffer(GL_RENDERBUFFER, 0 );
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
- glGenTextures(1,&cls->distance);
+ glGenTextures(1, &cls->distance);
glBindTexture(GL_TEXTURE_2D, cls->distance);
if (config.use_rgba_2d_shadows) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
@@ -6070,139 +5709,124 @@ RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, GL_RED, GL_FLOAT, NULL);
}
-
-
-
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cls->distance, 0);
-
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
//printf("errnum: %x\n",status);
glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo);
- ERR_FAIL_COND_V( status != GL_FRAMEBUFFER_COMPLETE, RID() );
+ ERR_FAIL_COND_V(status != GL_FRAMEBUFFER_COMPLETE, RID());
return canvas_light_shadow_owner.make_rid(cls);
}
/* LIGHT SHADOW MAPPING */
-
RID RasterizerStorageGLES3::canvas_light_occluder_create() {
- CanvasOccluder *co = memnew( CanvasOccluder );
- co->index_id=0;
- co->vertex_id=0;
- co->len=0;
+ CanvasOccluder *co = memnew(CanvasOccluder);
+ co->index_id = 0;
+ co->vertex_id = 0;
+ co->len = 0;
return canvas_occluder_owner.make_rid(co);
}
-void RasterizerStorageGLES3::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines) {
+void RasterizerStorageGLES3::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines) {
CanvasOccluder *co = canvas_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!co);
- co->lines=p_lines;
+ co->lines = p_lines;
- if (p_lines.size()!=co->len) {
+ if (p_lines.size() != co->len) {
if (co->index_id)
- glDeleteBuffers(1,&co->index_id);
+ glDeleteBuffers(1, &co->index_id);
if (co->vertex_id)
- glDeleteBuffers(1,&co->vertex_id);
-
- co->index_id=0;
- co->vertex_id=0;
- co->len=0;
+ glDeleteBuffers(1, &co->vertex_id);
+ co->index_id = 0;
+ co->vertex_id = 0;
+ co->len = 0;
}
if (p_lines.size()) {
-
-
PoolVector<float> geometry;
PoolVector<uint16_t> indices;
int lc = p_lines.size();
- geometry.resize(lc*6);
- indices.resize(lc*3);
+ geometry.resize(lc * 6);
+ indices.resize(lc * 3);
- PoolVector<float>::Write vw=geometry.write();
- PoolVector<uint16_t>::Write iw=indices.write();
+ PoolVector<float>::Write vw = geometry.write();
+ PoolVector<uint16_t>::Write iw = indices.write();
-
- PoolVector<Vector2>::Read lr=p_lines.read();
+ PoolVector<Vector2>::Read lr = p_lines.read();
const int POLY_HEIGHT = 16384;
- for(int i=0;i<lc/2;i++) {
-
- vw[i*12+0]=lr[i*2+0].x;
- vw[i*12+1]=lr[i*2+0].y;
- vw[i*12+2]=POLY_HEIGHT;
+ for (int i = 0; i < lc / 2; i++) {
- vw[i*12+3]=lr[i*2+1].x;
- vw[i*12+4]=lr[i*2+1].y;
- vw[i*12+5]=POLY_HEIGHT;
+ vw[i * 12 + 0] = lr[i * 2 + 0].x;
+ vw[i * 12 + 1] = lr[i * 2 + 0].y;
+ vw[i * 12 + 2] = POLY_HEIGHT;
- vw[i*12+6]=lr[i*2+1].x;
- vw[i*12+7]=lr[i*2+1].y;
- vw[i*12+8]=-POLY_HEIGHT;
+ vw[i * 12 + 3] = lr[i * 2 + 1].x;
+ vw[i * 12 + 4] = lr[i * 2 + 1].y;
+ vw[i * 12 + 5] = POLY_HEIGHT;
- vw[i*12+9]=lr[i*2+0].x;
- vw[i*12+10]=lr[i*2+0].y;
- vw[i*12+11]=-POLY_HEIGHT;
+ vw[i * 12 + 6] = lr[i * 2 + 1].x;
+ vw[i * 12 + 7] = lr[i * 2 + 1].y;
+ vw[i * 12 + 8] = -POLY_HEIGHT;
- iw[i*6+0]=i*4+0;
- iw[i*6+1]=i*4+1;
- iw[i*6+2]=i*4+2;
+ vw[i * 12 + 9] = lr[i * 2 + 0].x;
+ vw[i * 12 + 10] = lr[i * 2 + 0].y;
+ vw[i * 12 + 11] = -POLY_HEIGHT;
- iw[i*6+3]=i*4+2;
- iw[i*6+4]=i*4+3;
- iw[i*6+5]=i*4+0;
+ iw[i * 6 + 0] = i * 4 + 0;
+ iw[i * 6 + 1] = i * 4 + 1;
+ iw[i * 6 + 2] = i * 4 + 2;
+ iw[i * 6 + 3] = i * 4 + 2;
+ iw[i * 6 + 4] = i * 4 + 3;
+ iw[i * 6 + 5] = i * 4 + 0;
}
//if same buffer len is being set, just use BufferSubData to avoid a pipeline flush
-
if (!co->vertex_id) {
- glGenBuffers(1,&co->vertex_id);
- glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id);
- glBufferData(GL_ARRAY_BUFFER,lc*6*sizeof(real_t),vw.ptr(),GL_STATIC_DRAW);
+ glGenBuffers(1, &co->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, lc * 6 * sizeof(real_t), vw.ptr(), GL_STATIC_DRAW);
} else {
- glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id);
- glBufferSubData(GL_ARRAY_BUFFER,0,lc*6*sizeof(real_t),vw.ptr());
-
+ glBindBuffer(GL_ARRAY_BUFFER, co->vertex_id);
+ glBufferSubData(GL_ARRAY_BUFFER, 0, lc * 6 * sizeof(real_t), vw.ptr());
}
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
if (!co->index_id) {
- glGenBuffers(1,&co->index_id);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,lc*3*sizeof(uint16_t),iw.ptr(),GL_STATIC_DRAW);
+ glGenBuffers(1, &co->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, lc * 3 * sizeof(uint16_t), iw.ptr(), GL_STATIC_DRAW);
} else {
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id);
- glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,lc*3*sizeof(uint16_t),iw.ptr());
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, co->index_id);
+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, lc * 3 * sizeof(uint16_t), iw.ptr());
}
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
-
- co->len=lc;
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
+ co->len = lc;
}
-
}
VS::InstanceType RasterizerStorageGLES3::get_base_type(RID p_rid) const {
@@ -6234,13 +5858,13 @@ VS::InstanceType RasterizerStorageGLES3::get_base_type(RID p_rid) const {
return VS::INSTANCE_NONE;
}
-bool RasterizerStorageGLES3::free(RID p_rid){
+bool RasterizerStorageGLES3::free(RID p_rid) {
if (render_target_owner.owns(p_rid)) {
RenderTarget *rt = render_target_owner.getornull(p_rid);
_render_target_clear(rt);
- Texture *t=texture_owner.get(rt->texture);
+ Texture *t = texture_owner.get(rt->texture);
texture_owner.free(rt->texture);
memdelete(t);
render_target_owner.free(p_rid);
@@ -6249,14 +5873,14 @@ bool RasterizerStorageGLES3::free(RID p_rid){
} else if (texture_owner.owns(p_rid)) {
// delete the texture
Texture *texture = texture_owner.get(p_rid);
- ERR_FAIL_COND_V(texture->render_target,true); //cant free the render target texture, dude
- info.texture_mem-=texture->total_data_size;
+ ERR_FAIL_COND_V(texture->render_target, true); //cant free the render target texture, dude
+ info.texture_mem -= texture->total_data_size;
texture_owner.free(p_rid);
memdelete(texture);
} else if (skybox_owner.owns(p_rid)) {
// delete the skybox
SkyBox *skybox = skybox_owner.get(p_rid);
- skybox_set_texture(p_rid,RID(),256);
+ skybox_set_texture(p_rid, RID(), 256);
skybox_owner.free(p_rid);
memdelete(skybox);
@@ -6265,7 +5889,6 @@ bool RasterizerStorageGLES3::free(RID p_rid){
// delete the texture
Shader *shader = shader_owner.get(p_rid);
-
if (shader->shader)
shader->shader->free_custom_shader(shader->custom_code_id);
@@ -6276,10 +5899,10 @@ bool RasterizerStorageGLES3::free(RID p_rid){
Material *mat = shader->materials.first()->self();
- mat->shader=NULL;
+ mat->shader = NULL;
_material_make_dirty(mat);
- shader->materials.remove( shader->materials.first() );
+ shader->materials.remove(shader->materials.first());
}
//material_shader.free_custom_shader(shader->custom_code_id);
@@ -6292,31 +5915,30 @@ bool RasterizerStorageGLES3::free(RID p_rid){
Material *material = material_owner.get(p_rid);
if (material->shader) {
- material->shader->materials.remove( & material->list );
+ material->shader->materials.remove(&material->list);
}
if (material->ubo_id) {
- glDeleteBuffers(1,&material->ubo_id);
+ glDeleteBuffers(1, &material->ubo_id);
}
//remove from owners
- for (Map<Geometry*,int>::Element *E=material->geometry_owners.front();E;E=E->next()) {
+ for (Map<Geometry *, int>::Element *E = material->geometry_owners.front(); E; E = E->next()) {
Geometry *g = E->key();
- g->material=RID();
+ g->material = RID();
}
- for (Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.front();E;E=E->next()) {
- RasterizerScene::InstanceBase*ins=E->key();
- if (ins->material_override==p_rid) {
- ins->material_override=RID();
+ for (Map<RasterizerScene::InstanceBase *, int>::Element *E = material->instance_owners.front(); E; E = E->next()) {
+ RasterizerScene::InstanceBase *ins = E->key();
+ if (ins->material_override == p_rid) {
+ ins->material_override = RID();
}
- for(int i=0;i<ins->materials.size();i++) {
- if (ins->materials[i]==p_rid) {
- ins->materials[i]=RID();
+ for (int i = 0; i < ins->materials.size(); i++) {
+ if (ins->materials[i] == p_rid) {
+ ins->materials[i] = RID();
}
}
-
}
material_owner.free(p_rid);
@@ -6330,11 +5952,11 @@ bool RasterizerStorageGLES3::free(RID p_rid){
skeleton_update_list.remove(&skeleton->update_list);
}
- for (Set<RasterizerScene::InstanceBase*>::Element *E=skeleton->instances.front();E;E=E->next()) {
- E->get()->skeleton=RID();
+ for (Set<RasterizerScene::InstanceBase *>::Element *E = skeleton->instances.front(); E; E = E->next()) {
+ E->get()->skeleton = RID();
}
- skeleton_allocate(p_rid,0,false);
+ skeleton_allocate(p_rid, 0, false);
skeleton_owner.free(p_rid);
memdelete(skeleton);
@@ -6345,16 +5967,15 @@ bool RasterizerStorageGLES3::free(RID p_rid){
mesh->instance_remove_deps();
mesh_clear(p_rid);
- while(mesh->multimeshes.first()) {
+ while (mesh->multimeshes.first()) {
MultiMesh *multimesh = mesh->multimeshes.first()->self();
- multimesh->mesh=RID();
- multimesh->dirty_aabb=true;
+ multimesh->mesh = RID();
+ multimesh->dirty_aabb = true;
mesh->multimeshes.remove(mesh->multimeshes.first());
if (!multimesh->update_list.in_list()) {
multimesh_update_list.add(&multimesh->update_list);
}
-
}
mesh_owner.free(p_rid);
@@ -6373,10 +5994,9 @@ bool RasterizerStorageGLES3::free(RID p_rid){
}
}
- multimesh_allocate(p_rid,0,VS::MULTIMESH_TRANSFORM_2D,VS::MULTIMESH_COLOR_NONE); //frees multimesh
+ multimesh_allocate(p_rid, 0, VS::MULTIMESH_TRANSFORM_2D, VS::MULTIMESH_COLOR_NONE); //frees multimesh
update_dirty_multimeshes();
-
multimesh_owner.free(p_rid);
memdelete(multimesh);
} else if (immediate_owner.owns(p_rid)) {
@@ -6409,7 +6029,6 @@ bool RasterizerStorageGLES3::free(RID p_rid){
// delete the texture
GIProbe *gi_probe = gi_probe_owner.get(p_rid);
-
gi_probe_owner.free(p_rid);
memdelete(gi_probe);
} else if (gi_probe_data_owner.owns(p_rid)) {
@@ -6418,18 +6037,17 @@ bool RasterizerStorageGLES3::free(RID p_rid){
GIProbeData *gi_probe_data = gi_probe_data_owner.get(p_rid);
print_line("dyndata delete");
- glDeleteTextures(1,&gi_probe_data->tex_id);
+ glDeleteTextures(1, &gi_probe_data->tex_id);
gi_probe_owner.free(p_rid);
memdelete(gi_probe_data);
} else if (canvas_occluder_owner.owns(p_rid)) {
-
CanvasOccluder *co = canvas_occluder_owner.get(p_rid);
if (co->index_id)
- glDeleteBuffers(1,&co->index_id);
+ glDeleteBuffers(1, &co->index_id);
if (co->vertex_id)
- glDeleteBuffers(1,&co->vertex_id);
+ glDeleteBuffers(1, &co->vertex_id);
canvas_occluder_owner.free(p_rid);
memdelete(co);
@@ -6437,9 +6055,9 @@ bool RasterizerStorageGLES3::free(RID p_rid){
} else if (canvas_light_shadow_owner.owns(p_rid)) {
CanvasLightShadow *cls = canvas_light_shadow_owner.get(p_rid);
- glDeleteFramebuffers(1,&cls->fbo);
- glDeleteRenderbuffers(1,&cls->depth);
- glDeleteTextures(1,&cls->distance);
+ glDeleteFramebuffers(1, &cls->fbo);
+ glDeleteRenderbuffers(1, &cls->depth);
+ glDeleteTextures(1, &cls->distance);
canvas_light_shadow_owner.free(p_rid);
memdelete(cls);
} else {
@@ -6449,206 +6067,193 @@ bool RasterizerStorageGLES3::free(RID p_rid){
return true;
}
+bool RasterizerStorageGLES3::has_os_feature(const String &p_feature) const {
-bool RasterizerStorageGLES3::has_os_feature(const String& p_feature) const {
-
- if (p_feature=="s3tc")
+ if (p_feature == "s3tc")
return config.s3tc_supported;
- if (p_feature=="etc")
+ if (p_feature == "etc")
return config.etc_supported;
- if (p_feature=="etc2")
+ if (p_feature == "etc2")
return config.etc2_supported;
- if (p_feature=="pvrtc")
+ if (p_feature == "pvrtc")
return config.pvrtc_supported;
return false;
-
}
////////////////////////////////////////////
-
void RasterizerStorageGLES3::initialize() {
- config.render_arch=RENDER_ARCH_DESKTOP;
+ config.render_arch = RENDER_ARCH_DESKTOP;
//config.fbo_deferred=int(Globals::get_singleton()->get("rendering/gles3/lighting_technique"));
- RasterizerStorageGLES3::system_fbo=0;
-
+ RasterizerStorageGLES3::system_fbo = 0;
//// extensions config
///
{
- int max_extensions=0;
+ int max_extensions = 0;
print_line("getting extensions");
- glGetIntegerv(GL_NUM_EXTENSIONS,&max_extensions);
- print_line("total "+itos(max_extensions));
- for(int i=0;i<max_extensions;i++) {
- const GLubyte *s = glGetStringi( GL_EXTENSIONS,i );
+ glGetIntegerv(GL_NUM_EXTENSIONS, &max_extensions);
+ print_line("total " + itos(max_extensions));
+ for (int i = 0; i < max_extensions; i++) {
+ const GLubyte *s = glGetStringi(GL_EXTENSIONS, i);
if (!s)
break;
- config.extensions.insert((const char*)s);
+ config.extensions.insert((const char *)s);
}
}
- config.shrink_textures_x2=false;
- config.use_fast_texture_filter=int(GlobalConfig::get_singleton()->get("rendering/quality/use_nearest_mipmap_filter"));
+ config.shrink_textures_x2 = false;
+ config.use_fast_texture_filter = int(GlobalConfig::get_singleton()->get("rendering/quality/use_nearest_mipmap_filter"));
config.use_anisotropic_filter = config.extensions.has("GL_EXT_texture_filter_anisotropic");
- config.s3tc_supported=config.extensions.has("GL_EXT_texture_compression_dxt1") || config.extensions.has("GL_EXT_texture_compression_s3tc") || config.extensions.has("WEBGL_compressed_texture_s3tc");
- config.etc_supported=config.extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
- config.latc_supported=config.extensions.has("GL_EXT_texture_compression_latc");
- config.bptc_supported=config.extensions.has("GL_ARB_texture_compression_bptc");
+ config.s3tc_supported = config.extensions.has("GL_EXT_texture_compression_dxt1") || config.extensions.has("GL_EXT_texture_compression_s3tc") || config.extensions.has("WEBGL_compressed_texture_s3tc");
+ config.etc_supported = config.extensions.has("GL_OES_compressed_ETC1_RGB8_texture");
+ config.latc_supported = config.extensions.has("GL_EXT_texture_compression_latc");
+ config.bptc_supported = config.extensions.has("GL_ARB_texture_compression_bptc");
#ifdef GLES_OVER_GL
- config.hdr_supported=true;
- config.etc2_supported=false;
+ config.hdr_supported = true;
+ config.etc2_supported = false;
#else
- config.etc2_supported=true;
- config.hdr_supported=false;
+ config.etc2_supported = true;
+ config.hdr_supported = false;
#endif
- config.pvrtc_supported=config.extensions.has("GL_IMG_texture_compression_pvrtc");
- config.srgb_decode_supported=config.extensions.has("GL_EXT_texture_sRGB_decode");
-
+ config.pvrtc_supported = config.extensions.has("GL_IMG_texture_compression_pvrtc");
+ config.srgb_decode_supported = config.extensions.has("GL_EXT_texture_sRGB_decode");
-
- config.anisotropic_level=1.0;
- config.use_anisotropic_filter=config.extensions.has("GL_EXT_texture_filter_anisotropic");
+ config.anisotropic_level = 1.0;
+ config.use_anisotropic_filter = config.extensions.has("GL_EXT_texture_filter_anisotropic");
if (config.use_anisotropic_filter) {
- glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&config.anisotropic_level);
- config.anisotropic_level=MIN(int(GlobalConfig::get_singleton()->get("rendering/quality/anisotropic_filter_level")),config.anisotropic_level);
+ glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &config.anisotropic_level);
+ config.anisotropic_level = MIN(int(GlobalConfig::get_singleton()->get("rendering/quality/anisotropic_filter_level")), config.anisotropic_level);
}
-
- frame.clear_request=false;
+ frame.clear_request = false;
shaders.copy.init();
{
//default textures
-
glGenTextures(1, &resources.white_tex);
- unsigned char whitetexdata[8*8*3];
- for(int i=0;i<8*8*3;i++) {
- whitetexdata[i]=255;
+ unsigned char whitetexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i++) {
+ whitetexdata[i] = 255;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,resources.white_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,whitetexdata);
+ glBindTexture(GL_TEXTURE_2D, resources.white_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, whitetexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &resources.black_tex);
- unsigned char blacktexdata[8*8*3];
- for(int i=0;i<8*8*3;i++) {
- blacktexdata[i]=0;
+ unsigned char blacktexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i++) {
+ blacktexdata[i] = 0;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,resources.black_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,blacktexdata);
+ glBindTexture(GL_TEXTURE_2D, resources.black_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, blacktexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
+ glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &resources.normal_tex);
- unsigned char normaltexdata[8*8*3];
- for(int i=0;i<8*8*3;i+=3) {
- normaltexdata[i+0]=128;
- normaltexdata[i+1]=128;
- normaltexdata[i+2]=255;
+ unsigned char normaltexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i += 3) {
+ normaltexdata[i + 0] = 128;
+ normaltexdata[i + 1] = 128;
+ normaltexdata[i + 2] = 255;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,resources.normal_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,normaltexdata);
+ glBindTexture(GL_TEXTURE_2D, resources.normal_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, normaltexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
-
+ glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &resources.aniso_tex);
- unsigned char anisotexdata[8*8*3];
- for(int i=0;i<8*8*3;i+=3) {
- anisotexdata[i+0]=255;
- anisotexdata[i+1]=128;
- anisotexdata[i+2]=0;
+ unsigned char anisotexdata[8 * 8 * 3];
+ for (int i = 0; i < 8 * 8 * 3; i += 3) {
+ anisotexdata[i + 0] = 255;
+ anisotexdata[i + 1] = 128;
+ anisotexdata[i + 2] = 0;
}
glActiveTexture(GL_TEXTURE0);
- glBindTexture(GL_TEXTURE_2D,resources.aniso_tex);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,anisotexdata);
+ glBindTexture(GL_TEXTURE_2D, resources.aniso_tex);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, anisotexdata);
glGenerateMipmap(GL_TEXTURE_2D);
- glBindTexture(GL_TEXTURE_2D,0);
-
+ glBindTexture(GL_TEXTURE_2D, 0);
}
- glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,&config.max_texture_image_units);
- glGetIntegerv(GL_MAX_TEXTURE_SIZE,&config.max_texture_size);
+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &config.max_texture_image_units);
+ glGetIntegerv(GL_MAX_TEXTURE_SIZE, &config.max_texture_size);
#ifdef GLES_OVER_GL
- config.use_rgba_2d_shadows=false;
+ config.use_rgba_2d_shadows = false;
#else
- config.use_rgba_2d_shadows=true;
+ config.use_rgba_2d_shadows = true;
#endif
-
//generic quadie for copying
{
//quad buffers
- glGenBuffers(1,&resources.quadie);
- glBindBuffer(GL_ARRAY_BUFFER,resources.quadie);
+ glGenBuffers(1, &resources.quadie);
+ glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
{
- const float qv[16]={
- -1,-1,
- 0, 0,
+ const float qv[16] = {
+ -1, -1,
+ 0, 0,
-1, 1,
- 0, 1,
- 1, 1,
- 1, 1,
- 1,-1,
- 1, 0,
+ 0, 1,
+ 1, 1,
+ 1, 1,
+ 1, -1,
+ 1, 0,
};
- glBufferData(GL_ARRAY_BUFFER,sizeof(float)*16,qv,GL_STATIC_DRAW);
+ glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, qv, GL_STATIC_DRAW);
}
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
-
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
- glGenVertexArrays(1,&resources.quadie_array);
+ glGenVertexArrays(1, &resources.quadie_array);
glBindVertexArray(resources.quadie_array);
- glBindBuffer(GL_ARRAY_BUFFER,resources.quadie);
- glVertexAttribPointer(VS::ARRAY_VERTEX,2,GL_FLOAT,GL_FALSE,sizeof(float)*4,0);
+ glBindBuffer(GL_ARRAY_BUFFER, resources.quadie);
+ glVertexAttribPointer(VS::ARRAY_VERTEX, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, 0);
glEnableVertexAttribArray(0);
- glVertexAttribPointer(VS::ARRAY_TEX_UV,2,GL_FLOAT,GL_FALSE,sizeof(float)*4,((uint8_t*)NULL)+8);
+ glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 4, ((uint8_t *)NULL) + 8);
glEnableVertexAttribArray(4);
glBindVertexArray(0);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
}
//generic quadie for copying without touching skybox
{
//transform feedback buffers
- uint32_t xf_feedback_size = GLOBAL_DEF("rendering/buffers/blend_shape_max_buffer_size_kb",4096);
- for(int i=0;i<2;i++) {
+ uint32_t xf_feedback_size = GLOBAL_DEF("rendering/buffers/blend_shape_max_buffer_size_kb", 4096);
+ for (int i = 0; i < 2; i++) {
- glGenBuffers(1,&resources.transform_feedback_buffers[i]);
- glBindBuffer(GL_ARRAY_BUFFER,resources.transform_feedback_buffers[i]);
- glBufferData(GL_ARRAY_BUFFER,xf_feedback_size*1024,NULL,GL_STREAM_DRAW);
+ glGenBuffers(1, &resources.transform_feedback_buffers[i]);
+ glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[i]);
+ glBufferData(GL_ARRAY_BUFFER, xf_feedback_size * 1024, NULL, GL_STREAM_DRAW);
}
shaders.blend_shapes.init();
- glGenVertexArrays(1,&resources.transform_feedback_array);
-
+ glGenVertexArrays(1, &resources.transform_feedback_array);
}
shaders.cubemap_filter.init();
@@ -6656,10 +6261,10 @@ void RasterizerStorageGLES3::initialize() {
glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS);
- frame.count=0;
- frame.prev_tick=0;
- frame.delta=0;
- config.keep_original_textures=false;
+ frame.count = 0;
+ frame.prev_tick = 0;
+ frame.delta = 0;
+ config.keep_original_textures = false;
}
void RasterizerStorageGLES3::finalize() {
@@ -6667,7 +6272,6 @@ void RasterizerStorageGLES3::finalize() {
glDeleteTextures(1, &resources.white_tex);
glDeleteTextures(1, &resources.black_tex);
glDeleteTextures(1, &resources.normal_tex);
-
}
void RasterizerStorageGLES3::update_dirty_resources() {
@@ -6679,7 +6283,5 @@ void RasterizerStorageGLES3::update_dirty_resources() {
update_particles();
}
-RasterizerStorageGLES3::RasterizerStorageGLES3()
-{
-
+RasterizerStorageGLES3::RasterizerStorageGLES3() {
}
diff --git a/drivers/gles3/rasterizer_storage_gles3.h b/drivers/gles3/rasterizer_storage_gles3.h
index 1fa15538de..343cee2133 100644
--- a/drivers/gles3/rasterizer_storage_gles3.h
+++ b/drivers/gles3/rasterizer_storage_gles3.h
@@ -29,27 +29,26 @@
#ifndef RASTERIZERSTORAGEGLES3_H
#define RASTERIZERSTORAGEGLES3_H
+#include "self_list.h"
#include "servers/visual/rasterizer.h"
#include "servers/visual/shader_language.h"
+#include "shader_compiler_gles3.h"
#include "shader_gles3.h"
-#include "shaders/copy.glsl.h"
-#include "shaders/canvas.glsl.h"
#include "shaders/blend_shape.glsl.h"
+#include "shaders/canvas.glsl.h"
+#include "shaders/copy.glsl.h"
#include "shaders/cubemap_filter.glsl.h"
#include "shaders/particles.glsl.h"
-#include "self_list.h"
-#include "shader_compiler_gles3.h"
class RasterizerCanvasGLES3;
class RasterizerSceneGLES3;
-#define _TEXTURE_SRGB_DECODE_EXT 0x8A48
-#define _DECODE_EXT 0x8A49
-#define _SKIP_DECODE_EXT 0x8A4A
+#define _TEXTURE_SRGB_DECODE_EXT 0x8A48
+#define _DECODE_EXT 0x8A49
+#define _SKIP_DECODE_EXT 0x8A4A
class RasterizerStorageGLES3 : public RasterizerStorage {
public:
-
RasterizerCanvasGLES3 *canvas;
RasterizerSceneGLES3 *scene;
static GLuint system_fbo; //on some devices, such as apple, screen is rendered to yet another fbo.
@@ -134,18 +133,9 @@ public:
} info;
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////DATA///////////////////////////////////////////////////
-/////////////////////////////////////////////////////////////////////////////////////////
-
-
-
-
-
-
-
-
+ /////////////////////////////////////////////////////////////////////////////////////////
+ //////////////////////////////////DATA///////////////////////////////////////////////////
+ /////////////////////////////////////////////////////////////////////////////////////////
struct Instantiable : public RID_Data {
@@ -154,37 +144,35 @@ public:
_FORCE_INLINE_ void instance_change_notify() {
SelfList<RasterizerScene::InstanceBase> *instances = instance_list.first();
- while(instances) {
+ while (instances) {
instances->self()->base_changed();
- instances=instances->next();
+ instances = instances->next();
}
}
_FORCE_INLINE_ void instance_material_change_notify() {
SelfList<RasterizerScene::InstanceBase> *instances = instance_list.first();
- while(instances) {
+ while (instances) {
instances->self()->base_material_changed();
- instances=instances->next();
+ instances = instances->next();
}
}
_FORCE_INLINE_ void instance_remove_deps() {
SelfList<RasterizerScene::InstanceBase> *instances = instance_list.first();
- while(instances) {
+ while (instances) {
SelfList<RasterizerScene::InstanceBase> *next = instances->next();
instances->self()->base_removed();
- instances=next;
+ instances = next;
}
}
-
- Instantiable() { }
+ Instantiable() {}
virtual ~Instantiable() {
-
}
};
@@ -201,7 +189,6 @@ public:
GEOMETRY_MULTISURFACE,
};
-
Type type;
RID material;
uint64_t last_pass;
@@ -210,18 +197,14 @@ public:
virtual void material_changed_notify() {}
Geometry() {
- last_pass=0;
- index=0;
+ last_pass = 0;
+ index = 0;
}
-
};
-
-
-/////////////////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////API////////////////////////////////////////////////////
-/////////////////////////////////////////////////////////////////////////////////////////
-
+ /////////////////////////////////////////////////////////////////////////////////////////
+ //////////////////////////////////API////////////////////////////////////////////////////
+ /////////////////////////////////////////////////////////////////////////////////////////
/* TEXTURE API */
@@ -231,7 +214,7 @@ public:
String path;
uint32_t flags;
- int width,height;
+ int width, height;
int alloc_width, alloc_height;
Image::Format format;
@@ -266,64 +249,62 @@ public:
Texture() {
- using_srgb=false;
- stored_cube_sides=0;
- ignore_mipmaps=false;
- render_target=NULL;
- flags=width=height=0;
- tex_id=0;
- data_size=0;
- format=Image::FORMAT_L8;
- active=false;
- compressed=false;
- total_data_size=0;
- target=GL_TEXTURE_2D;
- mipmaps=0;
- detect_3d=NULL;
- detect_3d_ud=NULL;
- detect_srgb=NULL;
- detect_srgb_ud=NULL;
-
+ using_srgb = false;
+ stored_cube_sides = 0;
+ ignore_mipmaps = false;
+ render_target = NULL;
+ flags = width = height = 0;
+ tex_id = 0;
+ data_size = 0;
+ format = Image::FORMAT_L8;
+ active = false;
+ compressed = false;
+ total_data_size = 0;
+ target = GL_TEXTURE_2D;
+ mipmaps = 0;
+ detect_3d = NULL;
+ detect_3d_ud = NULL;
+ detect_srgb = NULL;
+ detect_srgb_ud = NULL;
}
~Texture() {
- if (tex_id!=0) {
+ if (tex_id != 0) {
- glDeleteTextures(1,&tex_id);
+ glDeleteTextures(1, &tex_id);
}
}
};
mutable RID_Owner<Texture> texture_owner;
- Image _get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags, GLenum& r_gl_format, GLenum& r_gl_internal_format, GLenum &r_type, bool &r_compressed, bool &srgb);
+ Image _get_gl_image_and_format(const Image &p_image, Image::Format p_format, uint32_t p_flags, GLenum &r_gl_format, GLenum &r_gl_internal_format, GLenum &r_type, bool &r_compressed, bool &srgb);
virtual RID texture_create();
- virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT);
- virtual void texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT);
- virtual Image texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const;
- virtual void texture_set_flags(RID p_texture,uint32_t p_flags);
+ virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = VS::TEXTURE_FLAGS_DEFAULT);
+ virtual void texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT);
+ virtual Image texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) const;
+ virtual void texture_set_flags(RID p_texture, uint32_t p_flags);
virtual uint32_t texture_get_flags(RID p_texture) const;
virtual Image::Format texture_get_format(RID p_texture) const;
virtual uint32_t texture_get_width(RID p_texture) const;
virtual uint32_t texture_get_height(RID p_texture) const;
- virtual void texture_set_size_override(RID p_texture,int p_width, int p_height);
+ virtual void texture_set_size_override(RID p_texture, int p_width, int p_height);
- virtual void texture_set_path(RID p_texture,const String& p_path);
+ virtual void texture_set_path(RID p_texture, const String &p_path);
virtual String texture_get_path(RID p_texture) const;
virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable);
virtual void texture_debug_usage(List<VS::TextureInfo> *r_info);
- virtual RID texture_create_radiance_cubemap(RID p_source,int p_resolution=-1) const;
+ virtual RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const;
virtual void textures_keep_original(bool p_enable);
- virtual void texture_set_detect_3d_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata);
- virtual void texture_set_detect_srgb_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata);
-
+ virtual void texture_set_detect_3d_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata);
+ virtual void texture_set_detect_srgb_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata);
/* SKYBOX API */
@@ -337,7 +318,7 @@ public:
mutable RID_Owner<SkyBox> skybox_owner;
virtual RID skybox_create();
- virtual void skybox_set_texture(RID p_skybox,RID p_cube_map,int p_radiance_size);
+ virtual void skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size);
/* SHADER API */
@@ -352,9 +333,7 @@ public:
String code;
SelfList<Material>::List materials;
-
-
- Map<StringName,ShaderLanguage::ShaderNode::Uniform> uniforms;
+ Map<StringName, ShaderLanguage::ShaderNode::Uniform> uniforms;
Vector<uint32_t> ubo_offsets;
uint32_t ubo_size;
@@ -365,7 +344,7 @@ public:
SelfList<Shader> dirty_list;
- Map<StringName,RID> default_textures;
+ Map<StringName, RID> default_textures;
Vector<ShaderLanguage::ShaderNode::Uniform::Hint> texture_hints;
@@ -434,45 +413,42 @@ public:
struct Particles {
-
} particles;
-
bool uses_vertex_time;
bool uses_fragment_time;
- Shader() : dirty_list(this) {
+ Shader()
+ : dirty_list(this) {
- shader=NULL;
- valid=false;
- custom_code_id=0;
- version=1;
+ shader = NULL;
+ valid = false;
+ custom_code_id = 0;
+ version = 1;
}
};
mutable SelfList<Shader>::List _shader_dirty_list;
- void _shader_make_dirty(Shader* p_shader);
+ void _shader_make_dirty(Shader *p_shader);
mutable RID_Owner<Shader> shader_owner;
- virtual RID shader_create(VS::ShaderMode p_mode=VS::SHADER_SPATIAL);
+ virtual RID shader_create(VS::ShaderMode p_mode = VS::SHADER_SPATIAL);
- virtual void shader_set_mode(RID p_shader,VS::ShaderMode p_mode);
+ virtual void shader_set_mode(RID p_shader, VS::ShaderMode p_mode);
virtual VS::ShaderMode shader_get_mode(RID p_shader) const;
- virtual void shader_set_code(RID p_shader, const String& p_code);
+ virtual void shader_set_code(RID p_shader, const String &p_code);
virtual String shader_get_code(RID p_shader) const;
virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const;
- virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture);
- virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const;
+ virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture);
+ virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const;
- void _update_shader(Shader* p_shader) const;
+ void _update_shader(Shader *p_shader) const;
void update_dirty_shaders();
-
-
/* COMMON MATERIAL API */
struct Material : public RID_Data {
@@ -480,7 +456,7 @@ public:
Shader *shader;
GLuint ubo_id;
uint32_t ubo_size;
- Map<StringName,Variant> params;
+ Map<StringName, Variant> params;
SelfList<Material> list;
SelfList<Material> dirty_list;
Vector<RID> textures;
@@ -489,30 +465,29 @@ public:
uint32_t index;
uint64_t last_pass;
- Map<Geometry*,int> geometry_owners;
- Map<RasterizerScene::InstanceBase*,int> instance_owners;
+ Map<Geometry *, int> geometry_owners;
+ Map<RasterizerScene::InstanceBase *, int> instance_owners;
bool can_cast_shadow_cache;
bool is_animated_cache;
- Material() : list(this), dirty_list(this) {
- can_cast_shadow_cache=false;
- is_animated_cache=false;
- shader=NULL;
- line_width=1.0;
- ubo_id=0;
- ubo_size=0;
- last_pass=0;
+ Material()
+ : list(this), dirty_list(this) {
+ can_cast_shadow_cache = false;
+ is_animated_cache = false;
+ shader = NULL;
+ line_width = 1.0;
+ ubo_id = 0;
+ ubo_size = 0;
+ last_pass = 0;
}
-
};
mutable SelfList<Material>::List _material_dirty_list;
void _material_make_dirty(Material *p_material) const;
- void _material_add_geometry(RID p_material,Geometry *p_instantiable);
+ void _material_add_geometry(RID p_material, Geometry *p_instantiable);
void _material_remove_geometry(RID p_material, Geometry *p_instantiable);
-
mutable RID_Owner<Material> material_owner;
virtual RID material_create();
@@ -520,8 +495,8 @@ public:
virtual void material_set_shader(RID p_material, RID p_shader);
virtual RID material_get_shader(RID p_material) const;
- virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value);
- virtual Variant material_get_param(RID p_material, const StringName& p_param) const;
+ virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value);
+ virtual Variant material_get_param(RID p_material, const StringName &p_param) const;
virtual void material_set_line_width(RID p_material, float p_width);
@@ -531,17 +506,12 @@ public:
virtual void material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance);
virtual void material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance);
- void _update_material(Material* material);
+ void _update_material(Material *material);
void update_dirty_materials();
/* MESH API */
-
-
-
-
-
struct Mesh;
struct Surface : public Geometry {
@@ -559,8 +529,6 @@ public:
Attrib attribs[VS::ARRAY_MAX];
-
-
Mesh *mesh;
uint32_t format;
@@ -590,7 +558,6 @@ public:
int array_byte_size;
int index_array_byte_size;
-
VS::PrimitiveType primitive;
bool active;
@@ -602,23 +569,21 @@ public:
Surface() {
- array_byte_size=0;
- index_array_byte_size=0;
- mesh=NULL;
- format=0;
- array_id=0;
- vertex_id=0;
- index_id=0;
- array_len=0;
- type=GEOMETRY_SURFACE;
- primitive=VS::PRIMITIVE_POINTS;
- index_array_len=0;
- active=false;
-
+ array_byte_size = 0;
+ index_array_byte_size = 0;
+ mesh = NULL;
+ format = 0;
+ array_id = 0;
+ vertex_id = 0;
+ index_id = 0;
+ array_len = 0;
+ type = GEOMETRY_SURFACE;
+ primitive = VS::PRIMITIVE_POINTS;
+ index_array_len = 0;
+ active = false;
}
~Surface() {
-
}
};
@@ -627,7 +592,7 @@ public:
struct Mesh : public GeometryOwner {
bool active;
- Vector<Surface*> surfaces;
+ Vector<Surface *> surfaces;
int blend_shape_count;
VS::BlendShapeMode blend_shape_mode;
Rect3 custom_aabb;
@@ -637,17 +602,17 @@ public:
_FORCE_INLINE_ void update_multimeshes() {
SelfList<MultiMesh> *mm = multimeshes.first();
- while(mm) {
+ while (mm) {
mm->self()->instance_material_change_notify();
- mm=mm->next();
+ mm = mm->next();
}
}
Mesh() {
- blend_shape_mode=VS::BLEND_SHAPE_MODE_NORMALIZED;
- blend_shape_count=0;
- last_pass=0;
- active=false;
+ blend_shape_mode = VS::BLEND_SHAPE_MODE_NORMALIZED;
+ blend_shape_count = 0;
+ last_pass = 0;
+ active = false;
}
};
@@ -655,13 +620,12 @@ public:
virtual RID mesh_create();
- virtual void mesh_add_surface(RID p_mesh,uint32_t p_format,VS::PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>());
+ virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, VS::PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>());
- virtual void mesh_set_blend_shape_count(RID p_mesh,int p_amount);
+ virtual void mesh_set_blend_shape_count(RID p_mesh, int p_amount);
virtual int mesh_get_blend_shape_count(RID p_mesh) const;
-
- virtual void mesh_set_blend_shape_mode(RID p_mesh,VS::BlendShapeMode p_mode);
+ virtual void mesh_set_blend_shape_mode(RID p_mesh, VS::BlendShapeMode p_mode);
virtual VS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const;
virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material);
@@ -673,7 +637,6 @@ public:
virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const;
virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const;
-
virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const;
virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const;
@@ -684,7 +647,7 @@ public:
virtual void mesh_remove_surface(RID p_mesh, int p_surface);
virtual int mesh_get_surface_count(RID p_mesh) const;
- virtual void mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb);
+ virtual void mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb);
virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const;
virtual Rect3 mesh_get_aabb(RID p_mesh, RID p_skeleton) const;
@@ -712,16 +675,17 @@ public:
bool dirty_aabb;
bool dirty_data;
- MultiMesh() : update_list(this), mesh_list(this) {
- dirty_aabb=true;
- dirty_data=true;
- xform_floats=0;
- color_floats=0;
- visible_instances=-1;
- size=0;
- buffer=0;
- transform_format=VS::MULTIMESH_TRANSFORM_2D;
- color_format=VS::MULTIMESH_COLOR_NONE;
+ MultiMesh()
+ : update_list(this), mesh_list(this) {
+ dirty_aabb = true;
+ dirty_data = true;
+ xform_floats = 0;
+ color_floats = 0;
+ visible_instances = -1;
+ size = 0;
+ buffer = 0;
+ transform_format = VS::MULTIMESH_TRANSFORM_2D;
+ color_format = VS::MULTIMESH_COLOR_NONE;
}
};
@@ -733,21 +697,21 @@ public:
virtual RID multimesh_create();
- virtual void multimesh_allocate(RID p_multimesh,int p_instances,VS::MultimeshTransformFormat p_transform_format,VS::MultimeshColorFormat p_color_format);
+ virtual void multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format);
virtual int multimesh_get_instance_count(RID p_multimesh) const;
- virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh);
- virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform);
- virtual void multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform);
- virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color);
+ virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh);
+ virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform);
+ virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform);
+ virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color);
virtual RID multimesh_get_mesh(RID p_multimesh) const;
- virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const;
- virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const;
- virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const;
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const;
+ virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const;
+ virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const;
- virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible);
+ virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible);
virtual int multimesh_get_visible_instances(RID p_multimesh) const;
virtual Rect3 multimesh_get_aabb(RID p_multimesh) const;
@@ -773,8 +737,10 @@ public:
int mask;
Rect3 aabb;
- Immediate() { type=GEOMETRY_IMMEDIATE; building=false;}
-
+ Immediate() {
+ type = GEOMETRY_IMMEDIATE;
+ building = false;
+ }
};
Vector3 chunk_vertex;
@@ -787,16 +753,16 @@ public:
mutable RID_Owner<Immediate> immediate_owner;
virtual RID immediate_create();
- virtual void immediate_begin(RID p_immediate,VS::PrimitiveType p_rimitive,RID p_texture=RID());
- virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex);
- virtual void immediate_normal(RID p_immediate,const Vector3& p_normal);
- virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent);
- virtual void immediate_color(RID p_immediate,const Color& p_color);
- virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv);
- virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv);
+ virtual void immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture = RID());
+ virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex);
+ virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal);
+ virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent);
+ virtual void immediate_color(RID p_immediate, const Color &p_color);
+ virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv);
+ virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv);
virtual void immediate_end(RID p_immediate);
virtual void immediate_clear(RID p_immediate);
- virtual void immediate_set_material(RID p_immediate,RID p_material);
+ virtual void immediate_set_material(RID p_immediate, RID p_material);
virtual RID immediate_get_material(RID p_immediate) const;
virtual Rect3 immediate_get_aabb(RID p_immediate) const;
@@ -808,12 +774,13 @@ public:
Vector<float> bones; //4x3 or 4x2 depending on what is needed
GLuint ubo;
SelfList<Skeleton> update_list;
- Set<RasterizerScene::InstanceBase*> instances; //instances using skeleton
+ Set<RasterizerScene::InstanceBase *> instances; //instances using skeleton
- Skeleton() : update_list(this) {
- size=0;
- use_2d=false;
- ubo=0;
+ Skeleton()
+ : update_list(this) {
+ size = 0;
+ use_2d = false;
+ ubo = 0;
}
};
@@ -824,16 +791,15 @@ public:
void update_dirty_skeletons();
virtual RID skeleton_create();
- virtual void skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton=false);
+ virtual void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false);
virtual int skeleton_get_bone_count(RID p_skeleton) const;
- virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform);
- virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone) const;
- virtual void skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform);
- virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone) const;
+ virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform);
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const;
+ virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform);
+ virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const;
/* Light API */
-
struct Light : Instantiable {
VS::LightType type;
@@ -855,20 +821,19 @@ public:
virtual RID light_create(VS::LightType p_type);
- virtual void light_set_color(RID p_light,const Color& p_color);
- virtual void light_set_param(RID p_light,VS::LightParam p_param,float p_value);
- virtual void light_set_shadow(RID p_light,bool p_enabled);
- virtual void light_set_shadow_color(RID p_light,const Color& p_color);
- virtual void light_set_projector(RID p_light,RID p_texture);
- virtual void light_set_negative(RID p_light,bool p_enable);
- virtual void light_set_cull_mask(RID p_light,uint32_t p_mask);
-
+ virtual void light_set_color(RID p_light, const Color &p_color);
+ virtual void light_set_param(RID p_light, VS::LightParam p_param, float p_value);
+ virtual void light_set_shadow(RID p_light, bool p_enabled);
+ virtual void light_set_shadow_color(RID p_light, const Color &p_color);
+ virtual void light_set_projector(RID p_light, RID p_texture);
+ virtual void light_set_negative(RID p_light, bool p_enable);
+ virtual void light_set_cull_mask(RID p_light, uint32_t p_mask);
- virtual void light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode);
- virtual void light_omni_set_shadow_detail(RID p_light,VS::LightOmniShadowDetail p_detail);
+ virtual void light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode);
+ virtual void light_omni_set_shadow_detail(RID p_light, VS::LightOmniShadowDetail p_detail);
- virtual void light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode);
- virtual void light_directional_set_blend_splits(RID p_light,bool p_enable);
+ virtual void light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode);
+ virtual void light_directional_set_blend_splits(RID p_light, bool p_enable);
virtual bool light_directional_get_blend_splits(RID p_light) const;
virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light);
@@ -877,7 +842,7 @@ public:
virtual bool light_has_shadow(RID p_light) const;
virtual VS::LightType light_get_type(RID p_light) const;
- virtual float light_get_param(RID p_light,VS::LightParam p_param);
+ virtual float light_get_param(RID p_light, VS::LightParam p_param);
virtual Color light_get_color(RID p_light);
virtual Rect3 light_get_aabb(RID p_light) const;
@@ -899,7 +864,6 @@ public:
bool box_projection;
bool enable_shadows;
uint32_t cull_mask;
-
};
mutable RID_Owner<ReflectionProbe> reflection_probe_owner;
@@ -908,12 +872,12 @@ public:
virtual void reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode);
virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity);
- virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color& p_ambient);
+ virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color &p_ambient);
virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy);
virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib);
virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance);
- virtual void reflection_probe_set_extents(RID p_probe, const Vector3& p_extents);
- virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset);
+ virtual void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents);
+ virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset);
virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable);
virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable);
virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable);
@@ -928,13 +892,10 @@ public:
virtual float reflection_probe_get_origin_max_distance(RID p_probe) const;
virtual bool reflection_probe_renders_shadows(RID p_probe) const;
-
-
-
/* ROOM API */
virtual RID room_create();
- virtual void room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform);
+ virtual void room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform);
virtual void room_clear_bounds(RID p_room);
/* PORTAL API */
@@ -943,22 +904,15 @@ public:
// order points outside. (z is 0);
virtual RID portal_create();
- virtual void portal_set_shape(RID p_portal, const Vector<Point2>& p_shape);
+ virtual void portal_set_shape(RID p_portal, const Vector<Point2> &p_shape);
virtual void portal_set_enabled(RID p_portal, bool p_enabled);
virtual void portal_set_disable_distance(RID p_portal, float p_distance);
- virtual void portal_set_disabled_color(RID p_portal, const Color& p_color);
-
-
-
-
-
-
+ virtual void portal_set_disabled_color(RID p_portal, const Color &p_color);
/* GI PROBE API */
struct GIProbe : public Instantiable {
-
Rect3 bounds;
Transform to_cell;
float cell_size;
@@ -973,42 +927,40 @@ public:
uint32_t version;
PoolVector<int> dynamic_data;
-
-
};
mutable RID_Owner<GIProbe> gi_probe_owner;
virtual RID gi_probe_create();
- virtual void gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds);
+ virtual void gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds);
virtual Rect3 gi_probe_get_bounds(RID p_probe) const;
virtual void gi_probe_set_cell_size(RID p_probe, float p_size);
virtual float gi_probe_get_cell_size(RID p_probe) const;
- virtual void gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform);
+ virtual void gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform);
virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const;
- virtual void gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data);
+ virtual void gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data);
virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const;
- virtual void gi_probe_set_dynamic_range(RID p_probe,int p_range);
+ virtual void gi_probe_set_dynamic_range(RID p_probe, int p_range);
virtual int gi_probe_get_dynamic_range(RID p_probe) const;
- virtual void gi_probe_set_energy(RID p_probe,float p_range);
+ virtual void gi_probe_set_energy(RID p_probe, float p_range);
virtual float gi_probe_get_energy(RID p_probe) const;
- virtual void gi_probe_set_bias(RID p_probe,float p_range);
+ virtual void gi_probe_set_bias(RID p_probe, float p_range);
virtual float gi_probe_get_bias(RID p_probe) const;
- virtual void gi_probe_set_propagation(RID p_probe,float p_range);
+ virtual void gi_probe_set_propagation(RID p_probe, float p_range);
virtual float gi_probe_get_propagation(RID p_probe) const;
- virtual void gi_probe_set_interior(RID p_probe,bool p_enable);
+ virtual void gi_probe_set_interior(RID p_probe, bool p_enable);
virtual bool gi_probe_is_interior(RID p_probe) const;
- virtual void gi_probe_set_compress(RID p_probe,bool p_enable);
+ virtual void gi_probe_set_compress(RID p_probe, bool p_enable);
virtual bool gi_probe_is_compressed(RID p_probe) const;
virtual uint32_t gi_probe_get_version(RID p_probe);
@@ -1029,8 +981,8 @@ public:
mutable RID_Owner<GIProbeData> gi_probe_data_owner;
virtual GIProbeCompression gi_probe_get_dynamic_data_get_preferred_compression() const;
- virtual RID gi_probe_dynamic_data_create(int p_width,int p_height,int p_depth,GIProbeCompression p_compression);
- virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data,int p_depth_slice,int p_slice_count,int p_mipmap,const void* p_data);
+ virtual RID gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression);
+ virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data, int p_depth_slice, int p_slice_count, int p_mipmap, const void *p_data);
/* PARTICLES */
@@ -1073,77 +1025,74 @@ public:
Transform origin;
- Particles() : particle_element(this) {
- emitting=false;
- amount=0;
- lifetime=1.0;
- pre_process_time=0.0;
- explosiveness=0.0;
- randomness=0.0;
- use_local_coords=true;
-
- draw_order=VS::PARTICLES_DRAW_ORDER_INDEX;
- emission_shape=VS::PARTICLES_EMSSION_POINT;
- emission_sphere_radius=1.0;
- emission_box_extents=Vector3(1,1,1);
- emission_point_texture=0;
- particle_buffers[0]=0;
- particle_buffers[1]=0;
-
- prev_ticks=0;
-
- glGenBuffers(2,particle_buffers);
+ Particles()
+ : particle_element(this) {
+ emitting = false;
+ amount = 0;
+ lifetime = 1.0;
+ pre_process_time = 0.0;
+ explosiveness = 0.0;
+ randomness = 0.0;
+ use_local_coords = true;
+
+ draw_order = VS::PARTICLES_DRAW_ORDER_INDEX;
+ emission_shape = VS::PARTICLES_EMSSION_POINT;
+ emission_sphere_radius = 1.0;
+ emission_box_extents = Vector3(1, 1, 1);
+ emission_point_texture = 0;
+ particle_buffers[0] = 0;
+ particle_buffers[1] = 0;
+
+ prev_ticks = 0;
+
+ glGenBuffers(2, particle_buffers);
}
~Particles() {
- glDeleteBuffers(2,particle_buffers);
+ glDeleteBuffers(2, particle_buffers);
}
-
-
};
SelfList<Particles>::List particle_update_list;
void update_particles();
-
mutable RID_Owner<Particles> particles_owner;
virtual RID particles_create();
- virtual void particles_set_emitting(RID p_particles,bool p_emitting);
- virtual void particles_set_amount(RID p_particles,int p_amount);
- virtual void particles_set_lifetime(RID p_particles,float p_lifetime);
- virtual void particles_set_pre_process_time(RID p_particles,float p_time);
- virtual void particles_set_explosiveness_ratio(RID p_particles,float p_ratio);
- virtual void particles_set_randomness_ratio(RID p_particles,float p_ratio);
- virtual void particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb);
- virtual void particles_set_gravity(RID p_particles,const Vector3& p_gravity);
- virtual void particles_set_use_local_coordinates(RID p_particles,bool p_enable);
- virtual void particles_set_process_material(RID p_particles,RID p_material);
+ virtual void particles_set_emitting(RID p_particles, bool p_emitting);
+ virtual void particles_set_amount(RID p_particles, int p_amount);
+ virtual void particles_set_lifetime(RID p_particles, float p_lifetime);
+ virtual void particles_set_pre_process_time(RID p_particles, float p_time);
+ virtual void particles_set_explosiveness_ratio(RID p_particles, float p_ratio);
+ virtual void particles_set_randomness_ratio(RID p_particles, float p_ratio);
+ virtual void particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb);
+ virtual void particles_set_gravity(RID p_particles, const Vector3 &p_gravity);
+ virtual void particles_set_use_local_coordinates(RID p_particles, bool p_enable);
+ virtual void particles_set_process_material(RID p_particles, RID p_material);
- virtual void particles_set_emission_shape(RID p_particles,VS::ParticlesEmissionShape p_shape);
- virtual void particles_set_emission_sphere_radius(RID p_particles,float p_radius);
- virtual void particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents);
- virtual void particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points);
+ virtual void particles_set_emission_shape(RID p_particles, VS::ParticlesEmissionShape p_shape);
+ virtual void particles_set_emission_sphere_radius(RID p_particles, float p_radius);
+ virtual void particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents);
+ virtual void particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points);
+ virtual void particles_set_draw_order(RID p_particles, VS::ParticlesDrawOrder p_order);
- virtual void particles_set_draw_order(RID p_particles,VS::ParticlesDrawOrder p_order);
-
- virtual void particles_set_draw_passes(RID p_particles,int p_count);
- virtual void particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material);
- virtual void particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh);
+ virtual void particles_set_draw_passes(RID p_particles, int p_count);
+ virtual void particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material);
+ virtual void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh);
virtual Rect3 particles_get_current_aabb(RID p_particles);
/* INSTANCE */
- virtual void instance_add_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance);
- virtual void instance_remove_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance);
+ virtual void instance_add_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance);
+ virtual void instance_remove_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance);
- virtual void instance_add_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance);
- virtual void instance_remove_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance);
+ virtual void instance_add_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance);
+ virtual void instance_remove_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance);
/* RENDER TARGET */
@@ -1180,7 +1129,10 @@ public:
GLuint color;
int levels;
- MipMaps() { color=0; levels=0;}
+ MipMaps() {
+ color = 0;
+ levels = 0;
+ }
};
MipMaps mip_maps[2]; //first mipmap chain starts from full-screen
@@ -1194,7 +1146,11 @@ public:
Vector<GLuint> depth_mipmap_fbos; //fbos for depth mipmapsla ver
- SSAO() { blur_fbo[0]=0; blur_fbo[1]=0; linear_depth=0; }
+ SSAO() {
+ blur_fbo[0] = 0;
+ blur_fbo[1] = 0;
+ linear_depth = 0;
+ }
} ssao;
Effects() {}
@@ -1205,12 +1161,12 @@ public:
GLuint fbo;
GLuint color;
- Exposure() { fbo=0; }
+ Exposure() { fbo = 0; }
} exposure;
uint64_t last_exposure_tick;
- int width,height;
+ int width, height;
bool flags[RENDER_TARGET_FLAG_MAX];
@@ -1221,23 +1177,22 @@ public:
RenderTarget() {
- msaa=VS::VIEWPORT_MSAA_DISABLED;
- width=0;
- height=0;
- depth=0;
- fbo=0;
- exposure.fbo=0;
- buffers.fbo=0;
- used_in_frame=false;
-
-
- flags[RENDER_TARGET_VFLIP]=false;
- flags[RENDER_TARGET_TRANSPARENT]=false;
- flags[RENDER_TARGET_NO_3D]=false;
- flags[RENDER_TARGET_HDR]=true;
- flags[RENDER_TARGET_NO_SAMPLING]=false;
-
- last_exposure_tick=0;
+ msaa = VS::VIEWPORT_MSAA_DISABLED;
+ width = 0;
+ height = 0;
+ depth = 0;
+ fbo = 0;
+ exposure.fbo = 0;
+ buffers.fbo = 0;
+ used_in_frame = false;
+
+ flags[RENDER_TARGET_VFLIP] = false;
+ flags[RENDER_TARGET_TRANSPARENT] = false;
+ flags[RENDER_TARGET_NO_3D] = false;
+ flags[RENDER_TARGET_HDR] = true;
+ flags[RENDER_TARGET_NO_SAMPLING] = false;
+
+ last_exposure_tick = 0;
}
};
@@ -1247,12 +1202,12 @@ public:
void _render_target_allocate(RenderTarget *rt);
virtual RID render_target_create();
- virtual void render_target_set_size(RID p_render_target,int p_width, int p_height);
+ virtual void render_target_set_size(RID p_render_target, int p_width, int p_height);
virtual RID render_target_get_texture(RID p_render_target) const;
- virtual void render_target_set_flag(RID p_render_target,RenderTargetFlags p_flag,bool p_value);
+ virtual void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value);
virtual bool render_target_renedered_in_frame(RID p_render_target);
- virtual void render_target_set_msaa(RID p_render_target,VS::ViewportMSAA p_msaa);
+ virtual void render_target_set_msaa(RID p_render_target, VS::ViewportMSAA p_msaa);
/* CANVAS SHADOW */
@@ -1282,13 +1237,12 @@ public:
RID_Owner<CanvasOccluder> canvas_occluder_owner;
virtual RID canvas_light_occluder_create();
- virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines);
+ virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines);
virtual VS::InstanceType get_base_type(RID p_rid) const;
virtual bool free(RID p_rid);
-
struct Frame {
RenderTarget *current_rt;
@@ -1305,12 +1259,11 @@ public:
void initialize();
void finalize();
- virtual bool has_os_feature(const String& p_feature) const;
+ virtual bool has_os_feature(const String &p_feature) const;
virtual void update_dirty_resources();
RasterizerStorageGLES3();
};
-
#endif // RASTERIZERSTORAGEGLES3_H
diff --git a/drivers/gles3/shader_compiler_gles3.cpp b/drivers/gles3/shader_compiler_gles3.cpp
index 260f1787c4..12934a82e7 100644
--- a/drivers/gles3/shader_compiler_gles3.cpp
+++ b/drivers/gles3/shader_compiler_gles3.cpp
@@ -35,8 +35,8 @@
static String _mktab(int p_level) {
String tb;
- for(int i=0;i<p_level;i++) {
- tb+="\t";
+ for (int i = 0; i < p_level; i++) {
+ tb += "\t";
}
return tb;
@@ -49,7 +49,7 @@ static String _typestr(SL::DataType p_type) {
static int _get_datatype_size(SL::DataType p_type) {
- switch(p_type) {
+ switch (p_type) {
case SL::TYPE_VOID: return 0;
case SL::TYPE_BOOL: return 4;
@@ -80,12 +80,9 @@ static int _get_datatype_size(SL::DataType p_type) {
ERR_FAIL_V(0);
}
-
-
static String _prestr(SL::DataPrecision p_pres) {
-
- switch(p_pres) {
+ switch (p_pres) {
case SL::PRECISION_LOWP: return "lowp ";
case SL::PRECISION_MEDIUMP: return "mediump ";
case SL::PRECISION_HIGHP: return "highp ";
@@ -94,89 +91,87 @@ static String _prestr(SL::DataPrecision p_pres) {
return "";
}
-
static String _opstr(SL::Operator p_op) {
return SL::get_operator_text(p_op);
}
-static String _mkid(const String& p_id) {
+static String _mkid(const String &p_id) {
- return "m_"+p_id;
+ return "m_" + p_id;
}
static String f2sp0(float p_float) {
- if (int(p_float)==p_float)
- return itos(p_float)+".0";
+ if (int(p_float) == p_float)
+ return itos(p_float) + ".0";
else
return rtoss(p_float);
}
-static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value>& p_values) {
+static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value> &p_values) {
- switch(p_type) {
- case SL::TYPE_BOOL: return p_values[0].boolean?"true":"false";
+ switch (p_type) {
+ case SL::TYPE_BOOL: return p_values[0].boolean ? "true" : "false";
case SL::TYPE_BVEC2:
case SL::TYPE_BVEC3:
case SL::TYPE_BVEC4: {
+ String text = "bvec" + itos(p_type - SL::TYPE_BOOL + 1) + "(";
+ for (int i = 0; i < p_values.size(); i++) {
+ if (i > 0)
+ text += ",";
- String text="bvec"+itos(p_type-SL::TYPE_BOOL+1)+"(";
- for(int i=0;i<p_values.size();i++) {
- if (i>0)
- text+=",";
-
- text+=p_values[i].boolean?"true":"false";
+ text += p_values[i].boolean ? "true" : "false";
}
- text+=")";
+ text += ")";
return text;
}
- case SL::TYPE_INT: return itos(p_values[0].sint);
+ case SL::TYPE_INT: return itos(p_values[0].sint);
case SL::TYPE_IVEC2:
case SL::TYPE_IVEC3:
case SL::TYPE_IVEC4: {
- String text="ivec"+itos(p_type-SL::TYPE_INT+1)+"(";
- for(int i=0;i<p_values.size();i++) {
- if (i>0)
- text+=",";
+ String text = "ivec" + itos(p_type - SL::TYPE_INT + 1) + "(";
+ for (int i = 0; i < p_values.size(); i++) {
+ if (i > 0)
+ text += ",";
- text+=itos(p_values[i].sint);
+ text += itos(p_values[i].sint);
}
- text+=")";
+ text += ")";
return text;
} break;
- case SL::TYPE_UINT: return itos(p_values[0].uint)+"u";
+ case SL::TYPE_UINT: return itos(p_values[0].uint) + "u";
case SL::TYPE_UVEC2:
case SL::TYPE_UVEC3:
- case SL::TYPE_UVEC4: {
+ case SL::TYPE_UVEC4: {
- String text="uvec"+itos(p_type-SL::TYPE_UINT+1)+"(";
- for(int i=0;i<p_values.size();i++) {
- if (i>0)
- text+=",";
+ String text = "uvec" + itos(p_type - SL::TYPE_UINT + 1) + "(";
+ for (int i = 0; i < p_values.size(); i++) {
+ if (i > 0)
+ text += ",";
- text+=itos(p_values[i].uint)+"u";
+ text += itos(p_values[i].uint) + "u";
}
- text+=")";
+ text += ")";
return text;
} break;
- case SL::TYPE_FLOAT: return f2sp0(p_values[0].real)+"f";
+ case SL::TYPE_FLOAT: return f2sp0(p_values[0].real) + "f";
case SL::TYPE_VEC2:
case SL::TYPE_VEC3:
- case SL::TYPE_VEC4: {
+ case SL::TYPE_VEC4: {
- String text="vec"+itos(p_type-SL::TYPE_FLOAT+1)+"(";
- for(int i=0;i<p_values.size();i++) {
- if (i>0)
- text+=",";
+ String text = "vec" + itos(p_type - SL::TYPE_FLOAT + 1) + "(";
+ for (int i = 0; i < p_values.size(); i++) {
+ if (i > 0)
+ text += ",";
- text+=f2sp0(p_values[i].real);
+ text += f2sp0(p_values[i].real);
}
- text+=")";
+ text += ")";
return text;
} break;
@@ -184,68 +179,68 @@ static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNo
}
}
-void ShaderCompilerGLES3::_dump_function_deps(SL::ShaderNode* p_node, const StringName& p_for_func, const Map<StringName,String>& p_func_code, String& r_to_add, Set<StringName> &added) {
+void ShaderCompilerGLES3::_dump_function_deps(SL::ShaderNode *p_node, const StringName &p_for_func, const Map<StringName, String> &p_func_code, String &r_to_add, Set<StringName> &added) {
- int fidx=-1;
+ int fidx = -1;
- for(int i=0;i<p_node->functions.size();i++) {
- if (p_node->functions[i].name==p_for_func) {
- fidx=i;
+ for (int i = 0; i < p_node->functions.size(); i++) {
+ if (p_node->functions[i].name == p_for_func) {
+ fidx = i;
break;
}
}
- ERR_FAIL_COND(fidx==-1);
+ ERR_FAIL_COND(fidx == -1);
- for (Set<StringName>::Element *E=p_node->functions[fidx].uses_function.front();E;E=E->next()) {
+ for (Set<StringName>::Element *E = p_node->functions[fidx].uses_function.front(); E; E = E->next()) {
if (added.has(E->get())) {
continue; //was added already
}
- _dump_function_deps(p_node,E->get(),p_func_code,r_to_add,added);
+ _dump_function_deps(p_node, E->get(), p_func_code, r_to_add, added);
- SL::FunctionNode *fnode=NULL;
+ SL::FunctionNode *fnode = NULL;
- for(int i=0;i<p_node->functions.size();i++) {
- if (p_node->functions[i].name==E->get()) {
- fnode=p_node->functions[i].function;
+ for (int i = 0; i < p_node->functions.size(); i++) {
+ if (p_node->functions[i].name == E->get()) {
+ fnode = p_node->functions[i].function;
break;
}
}
ERR_FAIL_COND(!fnode);
- r_to_add+="\n";
+ r_to_add += "\n";
String header;
- header=_typestr(fnode->return_type)+" "+_mkid(fnode->name)+"(";
- for(int i=0;i<fnode->arguments.size();i++) {
+ header = _typestr(fnode->return_type) + " " + _mkid(fnode->name) + "(";
+ for (int i = 0; i < fnode->arguments.size(); i++) {
- if (i>0)
- header+=", ";
- header+=_prestr(fnode->arguments[i].precision)+_typestr(fnode->arguments[i].type)+" "+_mkid(fnode->arguments[i].name);
+ if (i > 0)
+ header += ", ";
+ header += _prestr(fnode->arguments[i].precision) + _typestr(fnode->arguments[i].type) + " " + _mkid(fnode->arguments[i].name);
}
- header+=")\n";
- r_to_add+=header;
- r_to_add+=p_func_code[E->get()];
+ header += ")\n";
+ r_to_add += header;
+ r_to_add += p_func_code[E->get()];
added.insert(E->get());
}
}
-String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, GeneratedCode& r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions) {
+String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions) {
String code;
- switch(p_node->type) {
+ switch (p_node->type) {
case SL::Node::TYPE_SHADER: {
- SL::ShaderNode *pnode=(SL::ShaderNode*)p_node;
+ SL::ShaderNode *pnode = (SL::ShaderNode *)p_node;
- for(int i=0;i<pnode->render_modes.size();i++) {
+ for (int i = 0; i < pnode->render_modes.size(); i++) {
if (p_default_actions.render_mode_defines.has(pnode->render_modes[i]) && !used_rmode_defines.has(pnode->render_modes[i])) {
@@ -254,20 +249,19 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
}
if (p_actions.render_mode_flags.has(pnode->render_modes[i])) {
- *p_actions.render_mode_flags[pnode->render_modes[i]]=true;
+ *p_actions.render_mode_flags[pnode->render_modes[i]] = true;
}
if (p_actions.render_mode_values.has(pnode->render_modes[i])) {
- Pair<int*,int> &p = p_actions.render_mode_values[pnode->render_modes[i]];
- *p.first=p.second;
+ Pair<int *, int> &p = p_actions.render_mode_values[pnode->render_modes[i]];
+ *p.first = p.second;
}
}
+ int max_texture_uniforms = 0;
+ int max_uniforms = 0;
- int max_texture_uniforms=0;
- int max_uniforms=0;
-
- for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, SL::ShaderNode::Uniform>::Element *E = pnode->uniforms.front(); E; E = E->next()) {
if (SL::is_sampler_type(E->get().type))
max_texture_uniforms++;
else
@@ -284,66 +278,62 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
uniform_alignments.resize(max_uniforms);
uniform_defines.resize(max_uniforms);
- for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, SL::ShaderNode::Uniform>::Element *E = pnode->uniforms.front(); E; E = E->next()) {
String ucode;
if (SL::is_sampler_type(E->get().type)) {
- ucode="uniform ";
+ ucode = "uniform ";
}
- ucode+=_prestr(E->get().precission);
- ucode+=_typestr(E->get().type);
- ucode+=" "+_mkid(E->key());
- ucode+=";\n";
+ ucode += _prestr(E->get().precission);
+ ucode += _typestr(E->get().type);
+ ucode += " " + _mkid(E->key());
+ ucode += ";\n";
if (SL::is_sampler_type(E->get().type)) {
- r_gen_code.vertex_global+=ucode;
- r_gen_code.fragment_global+=ucode;
- r_gen_code.texture_uniforms[E->get().texture_order]=_mkid(E->key());
- r_gen_code.texture_hints[E->get().texture_order]=E->get().hint;
+ r_gen_code.vertex_global += ucode;
+ r_gen_code.fragment_global += ucode;
+ r_gen_code.texture_uniforms[E->get().texture_order] = _mkid(E->key());
+ r_gen_code.texture_hints[E->get().texture_order] = E->get().hint;
} else {
if (r_gen_code.uniforms.empty()) {
r_gen_code.defines.push_back(String("#define USE_MATERIAL\n").ascii());
}
- uniform_defines[E->get().order]=ucode;
- uniform_sizes[E->get().order]=_get_datatype_size(E->get().type);
- uniform_alignments[E->get().order]=MIN(16,_get_datatype_size(E->get().type));
+ uniform_defines[E->get().order] = ucode;
+ uniform_sizes[E->get().order] = _get_datatype_size(E->get().type);
+ uniform_alignments[E->get().order] = MIN(16, _get_datatype_size(E->get().type));
}
- p_actions.uniforms->insert(E->key(),E->get());
-
+ p_actions.uniforms->insert(E->key(), E->get());
}
- for(int i=0;i<max_uniforms;i++) {
- r_gen_code.uniforms+=uniform_defines[i];
+ for (int i = 0; i < max_uniforms; i++) {
+ r_gen_code.uniforms += uniform_defines[i];
}
// add up
- for(int i=0;i<uniform_sizes.size();i++) {
+ for (int i = 0; i < uniform_sizes.size(); i++) {
- if (i>0) {
+ if (i > 0) {
- int align = uniform_sizes[i-1] % uniform_alignments[i];
- if (align!=0) {
- uniform_sizes[i-1]+=uniform_alignments[i]-align;
+ int align = uniform_sizes[i - 1] % uniform_alignments[i];
+ if (align != 0) {
+ uniform_sizes[i - 1] += uniform_alignments[i] - align;
}
- uniform_sizes[i]=uniform_sizes[i]+uniform_sizes[i-1];
-
+ uniform_sizes[i] = uniform_sizes[i] + uniform_sizes[i - 1];
}
}
//offset
r_gen_code.uniform_offsets.resize(uniform_sizes.size());
- for(int i=0;i<uniform_sizes.size();i++) {
+ for (int i = 0; i < uniform_sizes.size(); i++) {
- if (i>0)
- r_gen_code.uniform_offsets[i]=uniform_sizes[i-1];
+ if (i > 0)
+ r_gen_code.uniform_offsets[i] = uniform_sizes[i - 1];
else
- r_gen_code.uniform_offsets[i]=0;
-
-
+ r_gen_code.uniform_offsets[i] = 0;
}
-/*
+ /*
for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) {
if (SL::is_sampler_type(E->get().type)) {
@@ -356,28 +346,28 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
*/
if (uniform_sizes.size()) {
- r_gen_code.uniform_total_size=uniform_sizes[ uniform_sizes.size() -1 ];
+ r_gen_code.uniform_total_size = uniform_sizes[uniform_sizes.size() - 1];
} else {
- r_gen_code.uniform_total_size=0;
+ r_gen_code.uniform_total_size = 0;
}
- for(Map<StringName,SL::ShaderNode::Varying>::Element *E=pnode->varyings.front();E;E=E->next()) {
+ for (Map<StringName, SL::ShaderNode::Varying>::Element *E = pnode->varyings.front(); E; E = E->next()) {
String vcode;
- vcode+=_prestr(E->get().precission);
- vcode+=_typestr(E->get().type);
- vcode+=" "+String(E->key());
- vcode+=";\n";
- r_gen_code.vertex_global+="out "+vcode;
- r_gen_code.fragment_global+="in "+vcode;
+ vcode += _prestr(E->get().precission);
+ vcode += _typestr(E->get().type);
+ vcode += " " + String(E->key());
+ vcode += ";\n";
+ r_gen_code.vertex_global += "out " + vcode;
+ r_gen_code.fragment_global += "in " + vcode;
}
- Map<StringName,String> function_code;
+ Map<StringName, String> function_code;
//code for functions
- for(int i=0;i<pnode->functions.size();i++) {
- SL::FunctionNode *fnode=pnode->functions[i].function;
- function_code[fnode->name]=_dump_node_code(fnode->body,p_level+1,r_gen_code,p_actions,p_default_actions);
+ for (int i = 0; i < pnode->functions.size(); i++) {
+ SL::FunctionNode *fnode = pnode->functions[i].function;
+ function_code[fnode->name] = _dump_node_code(fnode->body, p_level + 1, r_gen_code, p_actions, p_default_actions);
}
//place functions in actual code
@@ -385,28 +375,28 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
Set<StringName> added_vtx;
Set<StringName> added_fragment; //share for light
- for(int i=0;i<pnode->functions.size();i++) {
+ for (int i = 0; i < pnode->functions.size(); i++) {
- SL::FunctionNode *fnode=pnode->functions[i].function;
+ SL::FunctionNode *fnode = pnode->functions[i].function;
- current_func_name=fnode->name;
+ current_func_name = fnode->name;
- if (fnode->name=="vertex") {
+ if (fnode->name == "vertex") {
- _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.vertex_global,added_vtx);
- r_gen_code.vertex=function_code["vertex"];
+ _dump_function_deps(pnode, fnode->name, function_code, r_gen_code.vertex_global, added_vtx);
+ r_gen_code.vertex = function_code["vertex"];
}
- if (fnode->name=="fragment") {
+ if (fnode->name == "fragment") {
- _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.fragment_global,added_fragment);
- r_gen_code.fragment=function_code["fragment"];
+ _dump_function_deps(pnode, fnode->name, function_code, r_gen_code.fragment_global, added_fragment);
+ r_gen_code.fragment = function_code["fragment"];
}
- if (fnode->name=="light") {
+ if (fnode->name == "light") {
- _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.fragment_global,added_fragment);
- r_gen_code.light=function_code["light"];
+ _dump_function_deps(pnode, fnode->name, function_code, r_gen_code.fragment_global, added_fragment);
+ r_gen_code.light = function_code["light"];
}
}
@@ -416,72 +406,70 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
} break;
case SL::Node::TYPE_BLOCK: {
- SL::BlockNode *bnode=(SL::BlockNode*)p_node;
+ SL::BlockNode *bnode = (SL::BlockNode *)p_node;
//variables
- code+=_mktab(p_level-1)+"{\n";
- for(Map<StringName,SL::BlockNode::Variable>::Element *E=bnode->variables.front();E;E=E->next()) {
+ code += _mktab(p_level - 1) + "{\n";
+ for (Map<StringName, SL::BlockNode::Variable>::Element *E = bnode->variables.front(); E; E = E->next()) {
- code+=_mktab(p_level)+_prestr(E->get().precision)+_typestr(E->get().type)+" "+_mkid(E->key())+";\n";
+ code += _mktab(p_level) + _prestr(E->get().precision) + _typestr(E->get().type) + " " + _mkid(E->key()) + ";\n";
}
- for(int i=0;i<bnode->statements.size();i++) {
+ for (int i = 0; i < bnode->statements.size(); i++) {
- String scode = _dump_node_code(bnode->statements[i],p_level,r_gen_code,p_actions,p_default_actions);
+ String scode = _dump_node_code(bnode->statements[i], p_level, r_gen_code, p_actions, p_default_actions);
- if (bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW) {
+ if (bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW) {
// FIXME: if (A || A) ? I am hesitant to delete one of them, could be copy-paste error.
- code+=scode; //use directly
+ code += scode; //use directly
} else {
- code+=_mktab(p_level)+scode+";\n";
+ code += _mktab(p_level) + scode + ";\n";
}
}
- code+=_mktab(p_level-1)+"}\n";
-
+ code += _mktab(p_level - 1) + "}\n";
} break;
case SL::Node::TYPE_VARIABLE: {
- SL::VariableNode *vnode=(SL::VariableNode*)p_node;
+ SL::VariableNode *vnode = (SL::VariableNode *)p_node;
if (p_default_actions.usage_defines.has(vnode->name) && !used_name_defines.has(vnode->name)) {
String define = p_default_actions.usage_defines[vnode->name];
if (define.begins_with("@")) {
- define = p_default_actions.usage_defines[define.substr(1,define.length())];
+ define = p_default_actions.usage_defines[define.substr(1, define.length())];
}
r_gen_code.defines.push_back(define.utf8());
used_name_defines.insert(vnode->name);
}
if (p_actions.usage_flag_pointers.has(vnode->name) && !used_flag_pointers.has(vnode->name)) {
- *p_actions.usage_flag_pointers[vnode->name]=true;
+ *p_actions.usage_flag_pointers[vnode->name] = true;
used_flag_pointers.insert(vnode->name);
}
if (p_default_actions.renames.has(vnode->name))
- code=p_default_actions.renames[vnode->name];
+ code = p_default_actions.renames[vnode->name];
else
- code=_mkid(vnode->name);
+ code = _mkid(vnode->name);
- if (vnode->name==time_name) {
- if (current_func_name==vertex_name) {
- r_gen_code.uses_vertex_time=true;
+ if (vnode->name == time_name) {
+ if (current_func_name == vertex_name) {
+ r_gen_code.uses_vertex_time = true;
}
- if (current_func_name==fragment_name) {
- r_gen_code.uses_fragment_time=true;
+ if (current_func_name == fragment_name) {
+ r_gen_code.uses_fragment_time = true;
}
}
} break;
case SL::Node::TYPE_CONSTANT: {
- SL::ConstantNode *cnode=(SL::ConstantNode*)p_node;
- return get_constant_text(cnode->datatype,cnode->values);
+ SL::ConstantNode *cnode = (SL::ConstantNode *)p_node;
+ return get_constant_text(cnode->datatype, cnode->values);
} break;
case SL::Node::TYPE_OPERATOR: {
- SL::OperatorNode *onode=(SL::OperatorNode*)p_node;
+ SL::OperatorNode *onode = (SL::OperatorNode *)p_node;
-
- switch(onode->op) {
+ switch (onode->op) {
case SL::OP_ASSIGN:
case SL::OP_ASSIGN_ADD:
@@ -494,276 +482,259 @@ String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, Gener
case SL::OP_ASSIGN_BIT_AND:
case SL::OP_ASSIGN_BIT_OR:
case SL::OP_ASSIGN_BIT_XOR:
- code=_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op)+_dump_node_code(onode->arguments[1],p_level,r_gen_code,p_actions,p_default_actions);
+ code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions) + _opstr(onode->op) + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions);
break;
case SL::OP_BIT_INVERT:
case SL::OP_NEGATE:
case SL::OP_NOT:
case SL::OP_DECREMENT:
case SL::OP_INCREMENT:
- code=_opstr(onode->op)+_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions);
+ code = _opstr(onode->op) + _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions);
break;
case SL::OP_POST_DECREMENT:
case SL::OP_POST_INCREMENT:
- code=_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op);
+ code = _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions) + _opstr(onode->op);
break;
case SL::OP_CALL:
case SL::OP_CONSTRUCT: {
- ERR_FAIL_COND_V(onode->arguments[0]->type!=SL::Node::TYPE_VARIABLE,String());
+ ERR_FAIL_COND_V(onode->arguments[0]->type != SL::Node::TYPE_VARIABLE, String());
- SL::VariableNode *vnode=(SL::VariableNode*)onode->arguments[0];
+ SL::VariableNode *vnode = (SL::VariableNode *)onode->arguments[0];
- if (onode->op==SL::OP_CONSTRUCT) {
- code+=String(vnode->name);
+ if (onode->op == SL::OP_CONSTRUCT) {
+ code += String(vnode->name);
} else {
if (internal_functions.has(vnode->name)) {
- code+=vnode->name;
+ code += vnode->name;
} else if (p_default_actions.renames.has(vnode->name)) {
- code+=p_default_actions.renames[vnode->name];
+ code += p_default_actions.renames[vnode->name];
} else {
- code+=_mkid(vnode->name);
+ code += _mkid(vnode->name);
}
}
- code+="(";
+ code += "(";
- for(int i=1;i<onode->arguments.size();i++) {
- if (i>1)
- code+=", ";
- code+=_dump_node_code(onode->arguments[i],p_level,r_gen_code,p_actions,p_default_actions);
+ for (int i = 1; i < onode->arguments.size(); i++) {
+ if (i > 1)
+ code += ", ";
+ code += _dump_node_code(onode->arguments[i], p_level, r_gen_code, p_actions, p_default_actions);
}
- code+=")";
+ code += ")";
} break;
default: {
- code="("+_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op)+_dump_node_code(onode->arguments[1],p_level,r_gen_code,p_actions,p_default_actions)+")";
+ code = "(" + _dump_node_code(onode->arguments[0], p_level, r_gen_code, p_actions, p_default_actions) + _opstr(onode->op) + _dump_node_code(onode->arguments[1], p_level, r_gen_code, p_actions, p_default_actions) + ")";
break;
-
}
}
} break;
case SL::Node::TYPE_CONTROL_FLOW: {
- SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node;
- if (cfnode->flow_op==SL::FLOW_OP_IF) {
+ SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node;
+ if (cfnode->flow_op == SL::FLOW_OP_IF) {
- code+=_mktab(p_level)+"if ("+_dump_node_code(cfnode->expressions[0],p_level,r_gen_code,p_actions,p_default_actions)+")\n";
- code+=_dump_node_code(cfnode->blocks[0],p_level+1,r_gen_code,p_actions,p_default_actions);
- if (cfnode->blocks.size()==2) {
+ code += _mktab(p_level) + "if (" + _dump_node_code(cfnode->expressions[0], p_level, r_gen_code, p_actions, p_default_actions) + ")\n";
+ code += _dump_node_code(cfnode->blocks[0], p_level + 1, r_gen_code, p_actions, p_default_actions);
+ if (cfnode->blocks.size() == 2) {
- code+=_mktab(p_level)+"else\n";
- code+=_dump_node_code(cfnode->blocks[1],p_level+1,r_gen_code,p_actions,p_default_actions);
+ code += _mktab(p_level) + "else\n";
+ code += _dump_node_code(cfnode->blocks[1], p_level + 1, r_gen_code, p_actions, p_default_actions);
}
-
- } else if (cfnode->flow_op==SL::FLOW_OP_RETURN) {
+ } else if (cfnode->flow_op == SL::FLOW_OP_RETURN) {
if (cfnode->blocks.size()) {
- code="return "+_dump_node_code(cfnode->blocks[0],p_level,r_gen_code,p_actions,p_default_actions);
+ code = "return " + _dump_node_code(cfnode->blocks[0], p_level, r_gen_code, p_actions, p_default_actions);
} else {
- code="return";
+ code = "return";
}
}
} break;
case SL::Node::TYPE_MEMBER: {
- SL::MemberNode *mnode=(SL::MemberNode*)p_node;
- code=_dump_node_code(mnode->owner,p_level,r_gen_code,p_actions,p_default_actions)+"."+mnode->name;
+ SL::MemberNode *mnode = (SL::MemberNode *)p_node;
+ code = _dump_node_code(mnode->owner, p_level, r_gen_code, p_actions, p_default_actions) + "." + mnode->name;
} break;
}
return code;
-
}
+Error ShaderCompilerGLES3::compile(VS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code) {
-Error ShaderCompilerGLES3::compile(VS::ShaderMode p_mode, const String& p_code, IdentifierActions* p_actions, const String &p_path,GeneratedCode& r_gen_code) {
+ Error err = parser.compile(p_code, ShaderTypes::get_singleton()->get_functions(p_mode), ShaderTypes::get_singleton()->get_modes(p_mode));
-
-
- Error err = parser.compile(p_code,ShaderTypes::get_singleton()->get_functions(p_mode),ShaderTypes::get_singleton()->get_modes(p_mode));
-
- if (err!=OK) {
+ if (err != OK) {
#if 1
Vector<String> shader = p_code.split("\n");
- for(int i=0;i<shader.size();i++) {
- print_line(itos(i)+" "+shader[i]);
+ for (int i = 0; i < shader.size(); i++) {
+ print_line(itos(i) + " " + shader[i]);
}
#endif
- _err_print_error(NULL,p_path.utf8().get_data(),parser.get_error_line(),parser.get_error_text().utf8().get_data(),ERR_HANDLER_SHADER);
+ _err_print_error(NULL, p_path.utf8().get_data(), parser.get_error_line(), parser.get_error_text().utf8().get_data(), ERR_HANDLER_SHADER);
return err;
}
r_gen_code.defines.clear();
- r_gen_code.vertex=String();
- r_gen_code.vertex_global=String();
- r_gen_code.fragment=String();
- r_gen_code.fragment_global=String();
- r_gen_code.light=String();
- r_gen_code.uses_fragment_time=false;
- r_gen_code.uses_vertex_time=false;
-
-
+ r_gen_code.vertex = String();
+ r_gen_code.vertex_global = String();
+ r_gen_code.fragment = String();
+ r_gen_code.fragment_global = String();
+ r_gen_code.light = String();
+ r_gen_code.uses_fragment_time = false;
+ r_gen_code.uses_vertex_time = false;
used_name_defines.clear();
used_rmode_defines.clear();
used_flag_pointers.clear();
- _dump_node_code(parser.get_shader(),1,r_gen_code,*p_actions,actions[p_mode]);
+ _dump_node_code(parser.get_shader(), 1, r_gen_code, *p_actions, actions[p_mode]);
return OK;
-
}
-
ShaderCompilerGLES3::ShaderCompilerGLES3() {
/** CANVAS ITEM SHADER **/
- actions[VS::SHADER_CANVAS_ITEM].renames["SRC_VERTEX"]="vertex";
- actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX"]="outvec.xy";
- actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX_COLOR"]="vertex_color";
- actions[VS::SHADER_CANVAS_ITEM].renames["UV"]="uv_interp";
- actions[VS::SHADER_CANVAS_ITEM].renames["POINT_SIZE"]="gl_PointSize";
-
- actions[VS::SHADER_CANVAS_ITEM].renames["WORLD_MATRIX"]="modelview_matrix";
- actions[VS::SHADER_CANVAS_ITEM].renames["PROJECTION_MATRIX"]="projection_matrix";
- actions[VS::SHADER_CANVAS_ITEM].renames["EXTRA_MATRIX"]=="extra_matrix";
- actions[VS::SHADER_CANVAS_ITEM].renames["TIME"]="time";
-
- actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"]="color";
- actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL"]="normal";
- actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"]="normal_map";
- actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"]="normal_depth";
- actions[VS::SHADER_CANVAS_ITEM].renames["UV"]="uv_interp";
- actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"]="color";
- actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE"]="color_texture";
- actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"]="color_texpixel_size";
- actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_UV"]="screen_uv";
- actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_TEXTURE"]="screen_texture";
- actions[VS::SHADER_CANVAS_ITEM].renames["POINT_COORD"]="gl_PointCoord";
-
- actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_VEC"]="light_vec";
- actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_HEIGHT"]="light_height";
- actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_COLOR"]="light_color";
- actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_UV"]="light_uv";
+ actions[VS::SHADER_CANVAS_ITEM].renames["SRC_VERTEX"] = "vertex";
+ actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX"] = "outvec.xy";
+ actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX_COLOR"] = "vertex_color";
+ actions[VS::SHADER_CANVAS_ITEM].renames["UV"] = "uv_interp";
+ actions[VS::SHADER_CANVAS_ITEM].renames["POINT_SIZE"] = "gl_PointSize";
+
+ actions[VS::SHADER_CANVAS_ITEM].renames["WORLD_MATRIX"] = "modelview_matrix";
+ actions[VS::SHADER_CANVAS_ITEM].renames["PROJECTION_MATRIX"] = "projection_matrix";
+ actions[VS::SHADER_CANVAS_ITEM].renames["EXTRA_MATRIX"] == "extra_matrix";
+ actions[VS::SHADER_CANVAS_ITEM].renames["TIME"] = "time";
+
+ actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"] = "color";
+ actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL"] = "normal";
+ actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"] = "normal_map";
+ actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"] = "normal_depth";
+ actions[VS::SHADER_CANVAS_ITEM].renames["UV"] = "uv_interp";
+ actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"] = "color";
+ actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE"] = "color_texture";
+ actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"] = "color_texpixel_size";
+ actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_UV"] = "screen_uv";
+ actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_TEXTURE"] = "screen_texture";
+ actions[VS::SHADER_CANVAS_ITEM].renames["POINT_COORD"] = "gl_PointCoord";
+
+ actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_VEC"] = "light_vec";
+ actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_HEIGHT"] = "light_height";
+ actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_COLOR"] = "light_color";
+ actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_UV"] = "light_uv";
//actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_SHADOW_COLOR"]="light_shadow_color";
- actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT"]="light";
- actions[VS::SHADER_CANVAS_ITEM].renames["SHADOW_COLOR"]="shadow_color";
+ actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT"] = "light";
+ actions[VS::SHADER_CANVAS_ITEM].renames["SHADOW_COLOR"] = "shadow_color";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["COLOR"]="#define COLOR_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_TEXTURE"]="#define SCREEN_TEXTURE_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_UV"]="#define SCREEN_UV_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMAL"]="#define NORMAL_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMALMAP"]="#define NORMALMAP_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].usage_defines["SHADOW_COLOR"]="#define SHADOW_COLOR_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["COLOR"] = "#define COLOR_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_TEXTURE"] = "#define SCREEN_TEXTURE_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMAL"] = "#define NORMAL_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMALMAP"] = "#define NORMALMAP_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].usage_defines["SHADOW_COLOR"] = "#define SHADOW_COLOR_USED\n";
- actions[VS::SHADER_CANVAS_ITEM].render_mode_defines["skip_transform"]="#define SKIP_TRANSFORM_USED\n";
+ actions[VS::SHADER_CANVAS_ITEM].render_mode_defines["skip_transform"] = "#define SKIP_TRANSFORM_USED\n";
/** SPATIAL SHADER **/
-
- actions[VS::SHADER_SPATIAL].renames["WORLD_MATRIX"]="world_transform";
- actions[VS::SHADER_SPATIAL].renames["INV_CAMERA_MATRIX"]="camera_inverse_matrix";
- actions[VS::SHADER_SPATIAL].renames["PROJECTION_MATRIX"]="projection_matrix";
-
-
- actions[VS::SHADER_SPATIAL].renames["VERTEX"]="vertex.xyz";
- actions[VS::SHADER_SPATIAL].renames["NORMAL"]="normal";
- actions[VS::SHADER_SPATIAL].renames["TANGENT"]="tangent";
- actions[VS::SHADER_SPATIAL].renames["BINORMAL"]="binormal";
- actions[VS::SHADER_SPATIAL].renames["UV"]="uv_interp";
- actions[VS::SHADER_SPATIAL].renames["UV2"]="uv2_interp";
- actions[VS::SHADER_SPATIAL].renames["COLOR"]="color_interp";
- actions[VS::SHADER_SPATIAL].renames["POINT_SIZE"]="gl_PointSize";
+ actions[VS::SHADER_SPATIAL].renames["WORLD_MATRIX"] = "world_transform";
+ actions[VS::SHADER_SPATIAL].renames["INV_CAMERA_MATRIX"] = "camera_inverse_matrix";
+ actions[VS::SHADER_SPATIAL].renames["PROJECTION_MATRIX"] = "projection_matrix";
+
+ actions[VS::SHADER_SPATIAL].renames["VERTEX"] = "vertex.xyz";
+ actions[VS::SHADER_SPATIAL].renames["NORMAL"] = "normal";
+ actions[VS::SHADER_SPATIAL].renames["TANGENT"] = "tangent";
+ actions[VS::SHADER_SPATIAL].renames["BINORMAL"] = "binormal";
+ actions[VS::SHADER_SPATIAL].renames["UV"] = "uv_interp";
+ actions[VS::SHADER_SPATIAL].renames["UV2"] = "uv2_interp";
+ actions[VS::SHADER_SPATIAL].renames["COLOR"] = "color_interp";
+ actions[VS::SHADER_SPATIAL].renames["POINT_SIZE"] = "gl_PointSize";
//actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"]=ShaderLanguage::TYPE_INT;
//builtins
- actions[VS::SHADER_SPATIAL].renames["TIME"]="time";
+ actions[VS::SHADER_SPATIAL].renames["TIME"] = "time";
//actions[VS::SHADER_SPATIAL].renames["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2;
- actions[VS::SHADER_SPATIAL].renames["FRAGCOORD"]="gl_FragCoord";
- actions[VS::SHADER_SPATIAL].renames["FRONT_FACING"]="gl_FrotFacing";
- actions[VS::SHADER_SPATIAL].renames["NORMALMAP"]="normalmap";
- actions[VS::SHADER_SPATIAL].renames["NORMALMAP_DEPTH"]="normaldepth";
- actions[VS::SHADER_SPATIAL].renames["ALBEDO"]="albedo";
- actions[VS::SHADER_SPATIAL].renames["ALPHA"]="alpha";
- actions[VS::SHADER_SPATIAL].renames["SPECULAR"]="specular";
- actions[VS::SHADER_SPATIAL].renames["ROUGHNESS"]="roughness";
- actions[VS::SHADER_SPATIAL].renames["RIM"]="rim";
- actions[VS::SHADER_SPATIAL].renames["RIM_TINT"]="rim_tint";
- actions[VS::SHADER_SPATIAL].renames["CLEARCOAT"]="clearcoat";
- actions[VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"]="clearcoat_gloss";
- actions[VS::SHADER_SPATIAL].renames["ANISOTROPY"]="anisotropy";
- actions[VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"]="anisotropy_flow";
- actions[VS::SHADER_SPATIAL].renames["SSS_SPREAD"]="sss_spread";
- actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"]="sss_strength";
- actions[VS::SHADER_SPATIAL].renames["AO"]="ao";
- actions[VS::SHADER_SPATIAL].renames["EMISSION"]="emission";
- actions[VS::SHADER_SPATIAL].renames["DISCARD"]="_discard";
+ actions[VS::SHADER_SPATIAL].renames["FRAGCOORD"] = "gl_FragCoord";
+ actions[VS::SHADER_SPATIAL].renames["FRONT_FACING"] = "gl_FrotFacing";
+ actions[VS::SHADER_SPATIAL].renames["NORMALMAP"] = "normalmap";
+ actions[VS::SHADER_SPATIAL].renames["NORMALMAP_DEPTH"] = "normaldepth";
+ actions[VS::SHADER_SPATIAL].renames["ALBEDO"] = "albedo";
+ actions[VS::SHADER_SPATIAL].renames["ALPHA"] = "alpha";
+ actions[VS::SHADER_SPATIAL].renames["SPECULAR"] = "specular";
+ actions[VS::SHADER_SPATIAL].renames["ROUGHNESS"] = "roughness";
+ actions[VS::SHADER_SPATIAL].renames["RIM"] = "rim";
+ actions[VS::SHADER_SPATIAL].renames["RIM_TINT"] = "rim_tint";
+ actions[VS::SHADER_SPATIAL].renames["CLEARCOAT"] = "clearcoat";
+ actions[VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"] = "clearcoat_gloss";
+ actions[VS::SHADER_SPATIAL].renames["ANISOTROPY"] = "anisotropy";
+ actions[VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"] = "anisotropy_flow";
+ actions[VS::SHADER_SPATIAL].renames["SSS_SPREAD"] = "sss_spread";
+ actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength";
+ actions[VS::SHADER_SPATIAL].renames["AO"] = "ao";
+ actions[VS::SHADER_SPATIAL].renames["EMISSION"] = "emission";
+ actions[VS::SHADER_SPATIAL].renames["DISCARD"] = "_discard";
//actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2;
- actions[VS::SHADER_SPATIAL].renames["POINT_COORD"]="gl_PointCoord";
-
-
- actions[VS::SHADER_SPATIAL].usage_defines["TANGENT"]="#define ENABLE_TANGENT_INTERP\n";
- actions[VS::SHADER_SPATIAL].usage_defines["BINORMAL"]="@TANGENT";
- actions[VS::SHADER_SPATIAL].usage_defines["RIM"]="#define LIGHT_USE_RIM\n";
- actions[VS::SHADER_SPATIAL].usage_defines["RIM_TINT"]="@RIM";
- actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT"]="#define LIGHT_USE_CLEARCOAT\n";
- actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT_GLOSS"]="@CLEARCOAT";
- actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY"]="#define LIGHT_USE_ANISOTROPY\n";
- actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY_FLOW"]="@ANISOTROPY";
- actions[VS::SHADER_SPATIAL].usage_defines["AO"]="#define ENABLE_AO\n";
- actions[VS::SHADER_SPATIAL].usage_defines["UV"]="#define ENABLE_UV_INTERP\n";
- actions[VS::SHADER_SPATIAL].usage_defines["UV2"]="#define ENABLE_UV2_INTERP\n";
- actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP"]="#define ENABLE_NORMALMAP\n";
- actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP_DEPTH"]="@NORMALMAP";
- actions[VS::SHADER_SPATIAL].usage_defines["COLOR"]="#define ENABLE_COLOR_INTERP\n";
-
- actions[VS::SHADER_SPATIAL].usage_defines["SSS_STRENGTH"]="#define ENABLE_SSS_MOTION\n";
+ actions[VS::SHADER_SPATIAL].renames["POINT_COORD"] = "gl_PointCoord";
- actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"]="sss_strength";
+ actions[VS::SHADER_SPATIAL].usage_defines["TANGENT"] = "#define ENABLE_TANGENT_INTERP\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["BINORMAL"] = "@TANGENT";
+ actions[VS::SHADER_SPATIAL].usage_defines["RIM"] = "#define LIGHT_USE_RIM\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["RIM_TINT"] = "@RIM";
+ actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT"] = "#define LIGHT_USE_CLEARCOAT\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT_GLOSS"] = "@CLEARCOAT";
+ actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY"] = "#define LIGHT_USE_ANISOTROPY\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY_FLOW"] = "@ANISOTROPY";
+ actions[VS::SHADER_SPATIAL].usage_defines["AO"] = "#define ENABLE_AO\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["UV"] = "#define ENABLE_UV_INTERP\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["UV2"] = "#define ENABLE_UV2_INTERP\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP"] = "#define ENABLE_NORMALMAP\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP_DEPTH"] = "@NORMALMAP";
+ actions[VS::SHADER_SPATIAL].usage_defines["COLOR"] = "#define ENABLE_COLOR_INTERP\n";
+ actions[VS::SHADER_SPATIAL].usage_defines["SSS_STRENGTH"] = "#define ENABLE_SSS_MOTION\n";
- actions[VS::SHADER_SPATIAL].render_mode_defines["skip_transform"]="#define SKIP_TRANSFORM_USED\n";
+ actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"] = "sss_strength";
+ actions[VS::SHADER_SPATIAL].render_mode_defines["skip_transform"] = "#define SKIP_TRANSFORM_USED\n";
/* PARTICLES SHADER */
- actions[VS::SHADER_PARTICLES].renames["COLOR"]="color";
- actions[VS::SHADER_PARTICLES].renames["VELOCITY"]="out_velocity_active.xyz";
- actions[VS::SHADER_PARTICLES].renames["MASS"]="mass";
- actions[VS::SHADER_PARTICLES].renames["ACTIVE"]="active";
- actions[VS::SHADER_PARTICLES].renames["RESTART"]="restart";
- actions[VS::SHADER_PARTICLES].renames["CUSTOM"]="out_custom";
- actions[VS::SHADER_PARTICLES].renames["TRANSFORM"]="xform";
- actions[VS::SHADER_PARTICLES].renames["TIME"]="time";
- actions[VS::SHADER_PARTICLES].renames["LIFETIME"]="lifetime";
- actions[VS::SHADER_PARTICLES].renames["DELTA"]="delta";
- actions[VS::SHADER_PARTICLES].renames["SEED"]="seed";
- actions[VS::SHADER_PARTICLES].renames["ORIGIN"]="origin";
- actions[VS::SHADER_PARTICLES].renames["INDEX"]="index";
-
- actions[VS::SHADER_SPATIAL].render_mode_defines["disable_force"]="#define DISABLE_FORCE\n";
- actions[VS::SHADER_SPATIAL].render_mode_defines["disable_velocity"]="#define DISABLE_VELOCITY\n";
-
-
- vertex_name="vertex";
- fragment_name="fragment";
- time_name="TIME";
-
+ actions[VS::SHADER_PARTICLES].renames["COLOR"] = "color";
+ actions[VS::SHADER_PARTICLES].renames["VELOCITY"] = "out_velocity_active.xyz";
+ actions[VS::SHADER_PARTICLES].renames["MASS"] = "mass";
+ actions[VS::SHADER_PARTICLES].renames["ACTIVE"] = "active";
+ actions[VS::SHADER_PARTICLES].renames["RESTART"] = "restart";
+ actions[VS::SHADER_PARTICLES].renames["CUSTOM"] = "out_custom";
+ actions[VS::SHADER_PARTICLES].renames["TRANSFORM"] = "xform";
+ actions[VS::SHADER_PARTICLES].renames["TIME"] = "time";
+ actions[VS::SHADER_PARTICLES].renames["LIFETIME"] = "lifetime";
+ actions[VS::SHADER_PARTICLES].renames["DELTA"] = "delta";
+ actions[VS::SHADER_PARTICLES].renames["SEED"] = "seed";
+ actions[VS::SHADER_PARTICLES].renames["ORIGIN"] = "origin";
+ actions[VS::SHADER_PARTICLES].renames["INDEX"] = "index";
+
+ actions[VS::SHADER_SPATIAL].render_mode_defines["disable_force"] = "#define DISABLE_FORCE\n";
+ actions[VS::SHADER_SPATIAL].render_mode_defines["disable_velocity"] = "#define DISABLE_VELOCITY\n";
+
+ vertex_name = "vertex";
+ fragment_name = "fragment";
+ time_name = "TIME";
List<String> func_list;
ShaderLanguage::get_builtin_funcs(&func_list);
- for (List<String>::Element *E=func_list.front();E;E=E->next()) {
+ for (List<String>::Element *E = func_list.front(); E; E = E->next()) {
internal_functions.insert(E->get());
}
}
diff --git a/drivers/gles3/shader_compiler_gles3.h b/drivers/gles3/shader_compiler_gles3.h
index bbdfc7865f..44d6b3a349 100644
--- a/drivers/gles3/shader_compiler_gles3.h
+++ b/drivers/gles3/shader_compiler_gles3.h
@@ -29,20 +29,20 @@
#ifndef SHADERCOMPILERGLES3_H
#define SHADERCOMPILERGLES3_H
+#include "pair.h"
#include "servers/visual/shader_language.h"
#include "servers/visual/shader_types.h"
#include "servers/visual_server.h"
-#include "pair.h"
class ShaderCompilerGLES3 {
public:
struct IdentifierActions {
- Map<StringName,Pair<int*,int> > render_mode_values;
- Map<StringName,bool*> render_mode_flags;
- Map<StringName,bool*> usage_flag_pointers;
+ Map<StringName, Pair<int *, int> > render_mode_values;
+ Map<StringName, bool *> render_mode_flags;
+ Map<StringName, bool *> usage_flag_pointers;
- Map<StringName,ShaderLanguage::ShaderNode::Uniform> *uniforms;
+ Map<StringName, ShaderLanguage::ShaderNode::Uniform> *uniforms;
};
struct GeneratedCode {
@@ -62,23 +62,20 @@ public:
bool uses_fragment_time;
bool uses_vertex_time;
-
};
private:
-
ShaderLanguage parser;
struct DefaultIdentifierActions {
- Map<StringName,String> renames;
- Map<StringName,String> render_mode_defines;
- Map<StringName,String> usage_defines;
+ Map<StringName, String> renames;
+ Map<StringName, String> render_mode_defines;
+ Map<StringName, String> usage_defines;
};
- void _dump_function_deps(ShaderLanguage::ShaderNode *p_node, const StringName& p_for_func, const Map<StringName, String> &p_func_code, String& r_to_add,Set<StringName> &added);
- String _dump_node_code(ShaderLanguage::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions& p_actions, const DefaultIdentifierActions& p_default_actions);
-
+ void _dump_function_deps(ShaderLanguage::ShaderNode *p_node, const StringName &p_for_func, const Map<StringName, String> &p_func_code, String &r_to_add, Set<StringName> &added);
+ String _dump_node_code(ShaderLanguage::Node *p_node, int p_level, GeneratedCode &r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions);
StringName current_func_name;
StringName vertex_name;
@@ -90,14 +87,10 @@ private:
Set<StringName> used_rmode_defines;
Set<StringName> internal_functions;
-
DefaultIdentifierActions actions[VS::SHADER_MAX];
public:
-
-
- Error compile(VS::ShaderMode p_mode, const String& p_code, IdentifierActions* p_actions, const String& p_path, GeneratedCode& r_gen_code);
-
+ Error compile(VS::ShaderMode p_mode, const String &p_code, IdentifierActions *p_actions, const String &p_path, GeneratedCode &r_gen_code);
ShaderCompilerGLES3();
};
diff --git a/drivers/gles3/shader_gles3.cpp b/drivers/gles3/shader_gles3.cpp
index a148d68a91..3894f24295 100644
--- a/drivers/gles3/shader_gles3.cpp
+++ b/drivers/gles3/shader_gles3.cpp
@@ -28,29 +28,26 @@
/*************************************************************************/
#include "shader_gles3.h"
-
#include "print_string.h"
//#define DEBUG_OPENGL
#ifdef DEBUG_OPENGL
-#define DEBUG_TEST_ERROR(m_section)\
-{\
- uint32_t err = glGetError();\
- if (err) {\
- print_line("OpenGL Error #"+itos(err)+" at: "+m_section);\
- }\
-}
+#define DEBUG_TEST_ERROR(m_section) \
+ { \
+ uint32_t err = glGetError(); \
+ if (err) { \
+ print_line("OpenGL Error #" + itos(err) + " at: " + m_section); \
+ } \
+ }
#else
#define DEBUG_TEST_ERROR(m_section)
#endif
-ShaderGLES3 *ShaderGLES3::active=NULL;
-
-
+ShaderGLES3 *ShaderGLES3::active = NULL;
//#define DEBUG_SHADER
@@ -64,7 +61,6 @@ ShaderGLES3 *ShaderGLES3::active=NULL;
#endif
-
void ShaderGLES3::bind_uniforms() {
if (!uniforms_dirty) {
@@ -72,34 +68,33 @@ void ShaderGLES3::bind_uniforms() {
};
// upload default uniforms
- const Map<uint32_t,Variant>::Element *E =uniform_defaults.front();
+ const Map<uint32_t, Variant>::Element *E = uniform_defaults.front();
- while(E) {
- int idx=E->key();
- int location=version->uniform_location[idx];
+ while (E) {
+ int idx = E->key();
+ int location = version->uniform_location[idx];
- if (location<0) {
- E=E->next();
+ if (location < 0) {
+ E = E->next();
continue;
-
}
- const Variant &v=E->value();
+ const Variant &v = E->value();
_set_uniform_variant(location, v);
//print_line("uniform "+itos(location)+" value "+v+ " type "+Variant::get_type_name(v.get_type()));
- E=E->next();
+ E = E->next();
};
- const Map<uint32_t,CameraMatrix>::Element* C = uniform_cameras.front();
+ const Map<uint32_t, CameraMatrix>::Element *C = uniform_cameras.front();
while (C) {
int location = version->uniform_location[C->key()];
- if (location<0) {
- C=C->next();
+ if (location < 0) {
+ C = C->next();
continue;
}
- glUniformMatrix4fv(location,1,false,&(C->get().matrix[0][0]));
+ glUniformMatrix4fv(location, 1, false, &(C->get().matrix[0][0]));
C = C->next();
};
@@ -114,24 +109,24 @@ GLint ShaderGLES3::get_uniform_location(int p_idx) const {
};
bool ShaderGLES3::bind() {
-
- if (active!=this || !version || new_conditional_version.key!=conditional_version.key) {
- conditional_version=new_conditional_version;
+
+ if (active != this || !version || new_conditional_version.key != conditional_version.key) {
+ conditional_version = new_conditional_version;
version = get_current_version();
} else {
return false;
}
-
- ERR_FAIL_COND_V(!version,false);
- glUseProgram( version->id );
+ ERR_FAIL_COND_V(!version, false);
+
+ glUseProgram(version->id);
DEBUG_TEST_ERROR("Use Program");
- active=this;
+ active = this;
uniforms_dirty = true;
-/*
+ /*
* why on earth is this code here?
for (int i=0;i<texunit_pair_count;i++) {
@@ -145,152 +140,133 @@ bool ShaderGLES3::bind() {
void ShaderGLES3::unbind() {
- version=NULL;
+ version = NULL;
glUseProgram(0);
uniforms_dirty = true;
- active=NULL;
+ active = NULL;
}
+static void _display_error_with_code(const String &p_error, const Vector<const char *> &p_code) {
-static void _display_error_with_code(const String& p_error,const Vector<const char*>& p_code) {
-
-
- int line=1;
+ int line = 1;
String total_code;
- for(int i=0;i<p_code.size();i++) {
- total_code+=String(p_code[i]);
+ for (int i = 0; i < p_code.size(); i++) {
+ total_code += String(p_code[i]);
}
Vector<String> lines = String(total_code).split("\n");
- for(int j=0;j<lines.size();j++) {
+ for (int j = 0; j < lines.size(); j++) {
- print_line(itos(line)+": "+lines[j]);
+ print_line(itos(line) + ": " + lines[j]);
line++;
}
ERR_PRINTS(p_error);
-
}
-ShaderGLES3::Version* ShaderGLES3::get_current_version() {
+ShaderGLES3::Version *ShaderGLES3::get_current_version() {
- Version *_v=version_map.getptr(conditional_version);
+ Version *_v = version_map.getptr(conditional_version);
if (_v) {
- if (conditional_version.code_version!=0) {
- CustomCode *cc=custom_code_map.getptr(conditional_version.code_version);
- ERR_FAIL_COND_V(!cc,_v);
- if (cc->version==_v->code_version)
+ if (conditional_version.code_version != 0) {
+ CustomCode *cc = custom_code_map.getptr(conditional_version.code_version);
+ ERR_FAIL_COND_V(!cc, _v);
+ if (cc->version == _v->code_version)
return _v;
} else {
return _v;
}
-
}
-
-
if (!_v)
- version_map[conditional_version]=Version();
-
+ version_map[conditional_version] = Version();
Version &v = version_map[conditional_version];
if (!_v) {
- v.uniform_location = memnew_arr( GLint, uniform_count );
+ v.uniform_location = memnew_arr(GLint, uniform_count);
} else {
if (v.ok) {
//bye bye shaders
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- v.id=0;
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
}
-
-
- v.ok=false;
+ v.ok = false;
/* SETUP CONDITIONALS */
-
- Vector<const char*> strings;
+
+ Vector<const char *> strings;
#ifdef GLES_OVER_GL
strings.push_back("#version 330\n");
#else
strings.push_back("#version 300 es\n");
#endif
+ int define_line_ofs = 1;
-
- int define_line_ofs=1;
-
- for(int i=0;i<custom_defines.size();i++) {
+ for (int i = 0; i < custom_defines.size(); i++) {
strings.push_back(custom_defines[i].get_data());
define_line_ofs++;
}
- for(int j=0;j<conditional_count;j++) {
-
- bool enable=((1<<j)&conditional_version.version);
- strings.push_back(enable?conditional_defines[j]:"");
+ for (int j = 0; j < conditional_count; j++) {
+
+ bool enable = ((1 << j) & conditional_version.version);
+ strings.push_back(enable ? conditional_defines[j] : "");
if (enable)
define_line_ofs++;
if (enable) {
DEBUG_PRINT(conditional_defines[j]);
}
-
}
-
-
//keep them around during the function
CharString code_string;
CharString code_string2;
CharString code_globals;
CharString material_string;
-
//print_line("code version? "+itos(conditional_version.code_version));
- CustomCode *cc=NULL;
+ CustomCode *cc = NULL;
- if ( conditional_version.code_version>0 ) {
+ if (conditional_version.code_version > 0) {
//do custom code related stuff
- ERR_FAIL_COND_V( !custom_code_map.has( conditional_version.code_version ), NULL );
- cc=&custom_code_map[conditional_version.code_version];
- v.code_version=cc->version;
- define_line_ofs+=2;
-
+ ERR_FAIL_COND_V(!custom_code_map.has(conditional_version.code_version), NULL);
+ cc = &custom_code_map[conditional_version.code_version];
+ v.code_version = cc->version;
+ define_line_ofs += 2;
}
-
/* CREATE PROGRAM */
-
+
v.id = glCreateProgram();
-
- ERR_FAIL_COND_V(v.id==0, NULL);
-
- /* VERTEX SHADER */
+ ERR_FAIL_COND_V(v.id == 0, NULL);
+
+ /* VERTEX SHADER */
if (cc) {
- for(int i=0;i<cc->custom_defines.size();i++) {
+ for (int i = 0; i < cc->custom_defines.size(); i++) {
strings.push_back(cc->custom_defines[i].get_data());
- DEBUG_PRINT("CD #"+itos(i)+": "+String(cc->custom_defines[i]));
+ DEBUG_PRINT("CD #" + itos(i) + ": " + String(cc->custom_defines[i]));
}
}
- int strings_base_size=strings.size();
+ int strings_base_size = strings.size();
//vertex precision is high
strings.push_back("precision highp float;\n");
@@ -311,83 +287,78 @@ ShaderGLES3::Version* ShaderGLES3::get_current_version() {
}
#endif
-
strings.push_back(vertex_code0.get_data());
if (cc) {
- code_globals=cc->vertex_globals.ascii();
+ code_globals = cc->vertex_globals.ascii();
strings.push_back(code_globals.get_data());
}
strings.push_back(vertex_code1.get_data());
if (cc) {
- material_string=cc->uniforms.ascii();
+ material_string = cc->uniforms.ascii();
strings.push_back(material_string.get_data());
}
strings.push_back(vertex_code2.get_data());
if (cc) {
- code_string=cc->vertex.ascii();
+ code_string = cc->vertex.ascii();
strings.push_back(code_string.get_data());
}
strings.push_back(vertex_code3.get_data());
#ifdef DEBUG_SHADER
- DEBUG_PRINT("\nVertex Code:\n\n"+String(code_string.get_data()));
- for(int i=0;i<strings.size();i++) {
+ DEBUG_PRINT("\nVertex Code:\n\n" + String(code_string.get_data()));
+ for (int i = 0; i < strings.size(); i++) {
//print_line("vert strings "+itos(i)+":"+String(strings[i]));
}
#endif
-
v.vert_id = glCreateShader(GL_VERTEX_SHADER);
- glShaderSource(v.vert_id,strings.size(),&strings[0],NULL);
+ glShaderSource(v.vert_id, strings.size(), &strings[0], NULL);
glCompileShader(v.vert_id);
-
+
GLint status;
-
- glGetShaderiv(v.vert_id,GL_COMPILE_STATUS,&status);
- if (status==GL_FALSE) {
- // error compiling
+
+ glGetShaderiv(v.vert_id, GL_COMPILE_STATUS, &status);
+ if (status == GL_FALSE) {
+ // error compiling
GLsizei iloglen;
- glGetShaderiv(v.vert_id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
-
+ glGetShaderiv(v.vert_id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
+
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
+
ERR_PRINT("NO LOG, WTF");
} else {
- if (iloglen==0) {
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
-
- char *ilogmem = (char*)memalloc(iloglen+1);
- ilogmem[iloglen]=0;
- glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Vertex Program Compilation Failed:\n";
-
- err_string+=ilogmem;
- _display_error_with_code(err_string,strings);
+ char *ilogmem = (char *)memalloc(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Vertex Program Compilation Failed:\n";
+
+ err_string += ilogmem;
+ _display_error_with_code(err_string, strings);
memfree(ilogmem);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
- ERR_FAIL_V(NULL);
- }
+ ERR_FAIL_V(NULL);
+ }
/* FRAGMENT SHADER */
@@ -411,317 +382,308 @@ ShaderGLES3::Version* ShaderGLES3::get_current_version() {
}
#endif
-
strings.push_back(fragment_code0.get_data());
if (cc) {
- code_globals=cc->fragment_globals.ascii();
+ code_globals = cc->fragment_globals.ascii();
strings.push_back(code_globals.get_data());
}
strings.push_back(fragment_code1.get_data());
if (cc) {
- material_string=cc->uniforms.ascii();
+ material_string = cc->uniforms.ascii();
strings.push_back(material_string.get_data());
}
strings.push_back(fragment_code2.get_data());
if (cc) {
- code_string=cc->fragment.ascii();
+ code_string = cc->fragment.ascii();
strings.push_back(code_string.get_data());
}
strings.push_back(fragment_code3.get_data());
if (cc) {
- code_string2=cc->light.ascii();
+ code_string2 = cc->light.ascii();
strings.push_back(code_string2.get_data());
}
strings.push_back(fragment_code4.get_data());
#ifdef DEBUG_SHADER
- DEBUG_PRINT("\nFragment Code:\n\n"+String(code_string.get_data()));
- for(int i=0;i<strings.size();i++) {
+ DEBUG_PRINT("\nFragment Code:\n\n" + String(code_string.get_data()));
+ for (int i = 0; i < strings.size(); i++) {
//print_line("frag strings "+itos(i)+":"+String(strings[i]));
}
#endif
v.frag_id = glCreateShader(GL_FRAGMENT_SHADER);
- glShaderSource(v.frag_id,strings.size(),&strings[0],NULL);
+ glShaderSource(v.frag_id, strings.size(), &strings[0], NULL);
glCompileShader(v.frag_id);
-
- glGetShaderiv(v.frag_id,GL_COMPILE_STATUS,&status);
- if (status==GL_FALSE) {
- // error compiling
+
+ glGetShaderiv(v.frag_id, GL_COMPILE_STATUS, &status);
+ if (status == GL_FALSE) {
+ // error compiling
GLsizei iloglen;
- glGetShaderiv(v.frag_id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
+ glGetShaderiv(v.frag_id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
+ glDeleteProgram(v.id);
+ v.id = 0;
ERR_PRINT("NO LOG, WTF");
} else {
-
- if (iloglen==0) {
+
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
- char *ilogmem = (char*)memalloc(iloglen+1);
- ilogmem[iloglen]=0;
- glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Fragment Program Compilation Failed:\n";
-
- err_string+=ilogmem;
- _display_error_with_code(err_string,strings);
+ char *ilogmem = (char *)memalloc(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Fragment Program Compilation Failed:\n";
+
+ err_string += ilogmem;
+ _display_error_with_code(err_string, strings);
ERR_PRINT(err_string.ascii().get_data());
memfree(ilogmem);
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
}
-
- ERR_FAIL_V( NULL );
- }
- glAttachShader(v.id,v.frag_id);
- glAttachShader(v.id,v.vert_id);
+ ERR_FAIL_V(NULL);
+ }
+
+ glAttachShader(v.id, v.frag_id);
+ glAttachShader(v.id, v.vert_id);
// bind attributes before linking
- for (int i=0;i<attribute_pair_count;i++) {
+ for (int i = 0; i < attribute_pair_count; i++) {
- glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name );
+ glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name);
}
//if feedback exists, set it up
if (feedback_count) {
- Vector<const char*> feedback;
- for(int i=0;i<feedback_count;i++) {
+ Vector<const char *> feedback;
+ for (int i = 0; i < feedback_count; i++) {
- if (feedbacks[i].conditional==-1 || (1<<feedbacks[i].conditional)&conditional_version.version) {
+ if (feedbacks[i].conditional == -1 || (1 << feedbacks[i].conditional) & conditional_version.version) {
//conditional for this feedback is enabled
- print_line("tf varying: "+itos(feedback.size())+" "+String(feedbacks[i].name));
+ print_line("tf varying: " + itos(feedback.size()) + " " + String(feedbacks[i].name));
feedback.push_back(feedbacks[i].name);
}
}
if (feedback.size()) {
- glTransformFeedbackVaryings(v.id,feedback.size(),feedback.ptr(),GL_INTERLEAVED_ATTRIBS );
+ glTransformFeedbackVaryings(v.id, feedback.size(), feedback.ptr(), GL_INTERLEAVED_ATTRIBS);
}
-
}
glLinkProgram(v.id);
-
+
glGetProgramiv(v.id, GL_LINK_STATUS, &status);
-
- if (status==GL_FALSE) {
- // error linking
+
+ if (status == GL_FALSE) {
+ // error linking
GLsizei iloglen;
- glGetProgramiv(v.id,GL_INFO_LOG_LENGTH,&iloglen);
-
- if (iloglen<0) {
-
+ glGetProgramiv(v.id, GL_INFO_LOG_LENGTH, &iloglen);
+
+ if (iloglen < 0) {
+
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
- ERR_FAIL_COND_V(iloglen<=0, NULL);
+ glDeleteProgram(v.id);
+ v.id = 0;
+ ERR_FAIL_COND_V(iloglen <= 0, NULL);
}
- if (iloglen==0) {
+ if (iloglen == 0) {
iloglen = 4096; //buggy driver (Adreno 220+....)
}
-
- char *ilogmem = (char*)Memory::alloc_static(iloglen+1);
- ilogmem[iloglen]=0;
- glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem);
-
- String err_string=get_shader_name()+": Program LINK FAILED:\n";
-
- err_string+=ilogmem;
- _display_error_with_code(err_string,strings);
+ char *ilogmem = (char *)Memory::alloc_static(iloglen + 1);
+ ilogmem[iloglen] = 0;
+ glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem);
+
+ String err_string = get_shader_name() + ": Program LINK FAILED:\n";
+
+ err_string += ilogmem;
+ _display_error_with_code(err_string, strings);
ERR_PRINT(err_string.ascii().get_data());
Memory::free_static(ilogmem);
glDeleteShader(v.frag_id);
glDeleteShader(v.vert_id);
- glDeleteProgram( v.id );
- v.id=0;
-
+ glDeleteProgram(v.id);
+ v.id = 0;
+
ERR_FAIL_V(NULL);
}
-
- /* UNIFORMS */
-
- glUseProgram(v.id);
+ /* UNIFORMS */
+
+ glUseProgram(v.id);
//print_line("uniforms: ");
- for(int j=0;j<uniform_count;j++) {
-
-
- v.uniform_location[j]=glGetUniformLocation(v.id,uniform_names[j]);
+ for (int j = 0; j < uniform_count; j++) {
+
+ v.uniform_location[j] = glGetUniformLocation(v.id, uniform_names[j]);
//print_line("uniform "+String(uniform_names[j])+" location "+itos(v.uniform_location[j]));
}
-
+
// set texture uniforms
- for (int i=0;i<texunit_pair_count;i++) {
+ for (int i = 0; i < texunit_pair_count; i++) {
- GLint loc = glGetUniformLocation(v.id,texunit_pairs[i].name);
- if (loc>=0) {
- if (texunit_pairs[i].index<0) {
- glUniform1i(loc,max_image_units+texunit_pairs[i].index); //negative, goes down
+ GLint loc = glGetUniformLocation(v.id, texunit_pairs[i].name);
+ if (loc >= 0) {
+ if (texunit_pairs[i].index < 0) {
+ glUniform1i(loc, max_image_units + texunit_pairs[i].index); //negative, goes down
} else {
- glUniform1i(loc,texunit_pairs[i].index);
+ glUniform1i(loc, texunit_pairs[i].index);
}
}
}
// assign uniform block bind points
- for (int i=0;i<ubo_count;i++) {
+ for (int i = 0; i < ubo_count; i++) {
- GLint loc = glGetUniformBlockIndex(v.id,ubo_pairs[i].name);
- if (loc>=0)
- glUniformBlockBinding(v.id,loc,ubo_pairs[i].index);
+ GLint loc = glGetUniformBlockIndex(v.id, ubo_pairs[i].name);
+ if (loc >= 0)
+ glUniformBlockBinding(v.id, loc, ubo_pairs[i].index);
}
- if ( cc ) {
+ if (cc) {
v.texture_uniform_locations.resize(cc->texture_uniforms.size());
- for(int i=0;i<cc->texture_uniforms.size();i++) {
+ for (int i = 0; i < cc->texture_uniforms.size(); i++) {
- v.texture_uniform_locations[i]=glGetUniformLocation(v.id,String(cc->texture_uniforms[i]).ascii().get_data());
- glUniform1i(v.texture_uniform_locations[i],i+base_material_tex_index);
+ v.texture_uniform_locations[i] = glGetUniformLocation(v.id, String(cc->texture_uniforms[i]).ascii().get_data());
+ glUniform1i(v.texture_uniform_locations[i], i + base_material_tex_index);
}
}
glUseProgram(0);
-
- v.ok=true;
+ v.ok = true;
return &v;
}
-GLint ShaderGLES3::get_uniform_location(const String& p_name) const {
+GLint ShaderGLES3::get_uniform_location(const String &p_name) const {
- ERR_FAIL_COND_V(!version,-1);
- return glGetUniformLocation(version->id,p_name.ascii().get_data());
+ ERR_FAIL_COND_V(!version, -1);
+ return glGetUniformLocation(version->id, p_name.ascii().get_data());
}
-
-void ShaderGLES3::setup(const char** p_conditional_defines, int p_conditional_count,const char** p_uniform_names,int p_uniform_count, const AttributePair* p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const UBOPair *p_ubo_pairs, int p_ubo_pair_count, const Feedback* p_feedback, int p_feedback_count,const char*p_vertex_code, const char *p_fragment_code,int p_vertex_code_start,int p_fragment_code_start) {
+void ShaderGLES3::setup(const char **p_conditional_defines, int p_conditional_count, const char **p_uniform_names, int p_uniform_count, const AttributePair *p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const UBOPair *p_ubo_pairs, int p_ubo_pair_count, const Feedback *p_feedback, int p_feedback_count, const char *p_vertex_code, const char *p_fragment_code, int p_vertex_code_start, int p_fragment_code_start) {
ERR_FAIL_COND(version);
- conditional_version.key=0;
- new_conditional_version.key=0;
- uniform_count=p_uniform_count;
- conditional_count=p_conditional_count;
- conditional_defines=p_conditional_defines;
- uniform_names=p_uniform_names;
- vertex_code=p_vertex_code;
- fragment_code=p_fragment_code;
- texunit_pairs=p_texunit_pairs;
- texunit_pair_count=p_texunit_pair_count;
- vertex_code_start=p_vertex_code_start;
- fragment_code_start=p_fragment_code_start;
- attribute_pairs=p_attribute_pairs;
- attribute_pair_count=p_attribute_count;
- ubo_pairs=p_ubo_pairs;
- ubo_count=p_ubo_pair_count;
- feedbacks=p_feedback;
- feedback_count=p_feedback_count;
+ conditional_version.key = 0;
+ new_conditional_version.key = 0;
+ uniform_count = p_uniform_count;
+ conditional_count = p_conditional_count;
+ conditional_defines = p_conditional_defines;
+ uniform_names = p_uniform_names;
+ vertex_code = p_vertex_code;
+ fragment_code = p_fragment_code;
+ texunit_pairs = p_texunit_pairs;
+ texunit_pair_count = p_texunit_pair_count;
+ vertex_code_start = p_vertex_code_start;
+ fragment_code_start = p_fragment_code_start;
+ attribute_pairs = p_attribute_pairs;
+ attribute_pair_count = p_attribute_count;
+ ubo_pairs = p_ubo_pairs;
+ ubo_count = p_ubo_pair_count;
+ feedbacks = p_feedback;
+ feedback_count = p_feedback_count;
//split vertex and shader code (thank you, retarded shader compiler programmers from you know what company).
{
- String globals_tag="\nVERTEX_SHADER_GLOBALS";
- String material_tag="\nMATERIAL_UNIFORMS";
- String code_tag="\nVERTEX_SHADER_CODE";
- String code = vertex_code;
+ String globals_tag = "\nVERTEX_SHADER_GLOBALS";
+ String material_tag = "\nMATERIAL_UNIFORMS";
+ String code_tag = "\nVERTEX_SHADER_CODE";
+ String code = vertex_code;
int cpos = code.find(globals_tag);
- if (cpos==-1) {
- vertex_code0=code.ascii();
+ if (cpos == -1) {
+ vertex_code0 = code.ascii();
} else {
- vertex_code0=code.substr(0,cpos).ascii();
- code = code.substr(cpos+globals_tag.length(),code.length());
+ vertex_code0 = code.substr(0, cpos).ascii();
+ code = code.substr(cpos + globals_tag.length(), code.length());
cpos = code.find(material_tag);
- if (cpos==-1) {
- vertex_code1=code.ascii();
+ if (cpos == -1) {
+ vertex_code1 = code.ascii();
} else {
- vertex_code1=code.substr(0,cpos).ascii();
- String code2 = code.substr(cpos+material_tag.length(),code.length());
+ vertex_code1 = code.substr(0, cpos).ascii();
+ String code2 = code.substr(cpos + material_tag.length(), code.length());
cpos = code2.find(code_tag);
- if (cpos==-1) {
- vertex_code2=code2.ascii();
+ if (cpos == -1) {
+ vertex_code2 = code2.ascii();
} else {
- vertex_code2=code2.substr(0,cpos).ascii();
- vertex_code3 = code2.substr(cpos+code_tag.length(),code2.length()).ascii();
+ vertex_code2 = code2.substr(0, cpos).ascii();
+ vertex_code3 = code2.substr(cpos + code_tag.length(), code2.length()).ascii();
}
-
}
}
}
{
- String globals_tag="\nFRAGMENT_SHADER_GLOBALS";
- String material_tag="\nMATERIAL_UNIFORMS";
- String code_tag="\nFRAGMENT_SHADER_CODE";
- String light_code_tag="\nLIGHT_SHADER_CODE";
- String code = fragment_code;
+ String globals_tag = "\nFRAGMENT_SHADER_GLOBALS";
+ String material_tag = "\nMATERIAL_UNIFORMS";
+ String code_tag = "\nFRAGMENT_SHADER_CODE";
+ String light_code_tag = "\nLIGHT_SHADER_CODE";
+ String code = fragment_code;
int cpos = code.find(globals_tag);
- if (cpos==-1) {
- fragment_code0=code.ascii();
+ if (cpos == -1) {
+ fragment_code0 = code.ascii();
} else {
- fragment_code0=code.substr(0,cpos).ascii();
+ fragment_code0 = code.substr(0, cpos).ascii();
//print_line("CODE0:\n"+String(fragment_code0.get_data()));
- code = code.substr(cpos+globals_tag.length(),code.length());
+ code = code.substr(cpos + globals_tag.length(), code.length());
cpos = code.find(material_tag);
- if (cpos==-1) {
- fragment_code1=code.ascii();
+ if (cpos == -1) {
+ fragment_code1 = code.ascii();
} else {
- fragment_code1=code.substr(0,cpos).ascii();
+ fragment_code1 = code.substr(0, cpos).ascii();
//print_line("CODE1:\n"+String(fragment_code1.get_data()));
- String code2 = code.substr(cpos+material_tag.length(),code.length());
+ String code2 = code.substr(cpos + material_tag.length(), code.length());
cpos = code2.find(code_tag);
- if (cpos==-1) {
- fragment_code2=code2.ascii();
+ if (cpos == -1) {
+ fragment_code2 = code2.ascii();
} else {
- fragment_code2=code2.substr(0,cpos).ascii();
+ fragment_code2 = code2.substr(0, cpos).ascii();
//print_line("CODE2:\n"+String(fragment_code2.get_data()));
- String code3 = code2.substr(cpos+code_tag.length(),code2.length());
+ String code3 = code2.substr(cpos + code_tag.length(), code2.length());
cpos = code3.find(light_code_tag);
- if (cpos==-1) {
- fragment_code3=code3.ascii();
+ if (cpos == -1) {
+ fragment_code3 = code3.ascii();
} else {
- fragment_code3=code3.substr(0,cpos).ascii();
+ fragment_code3 = code3.substr(0, cpos).ascii();
//print_line("CODE3:\n"+String(fragment_code3.get_data()));
- fragment_code4 = code3.substr(cpos+light_code_tag.length(),code3.length()).ascii();
+ fragment_code4 = code3.substr(cpos + light_code_tag.length(), code3.length()).ascii();
//print_line("CODE4:\n"+String(fragment_code4.get_data()));
}
}
@@ -729,111 +691,99 @@ void ShaderGLES3::setup(const char** p_conditional_defines, int p_conditional_co
}
}
- glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,&max_image_units);
-
+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_image_units);
}
void ShaderGLES3::finish() {
-
- const VersionKey *V=NULL;
- while((V=version_map.next(V))) {
-
- Version &v=version_map[*V];
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- memdelete_arr( v.uniform_location );
-
- }
-
-}
+ const VersionKey *V = NULL;
+ while ((V = version_map.next(V))) {
+
+ Version &v = version_map[*V];
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ memdelete_arr(v.uniform_location);
+ }
+}
void ShaderGLES3::clear_caches() {
- const VersionKey *V=NULL;
- while((V=version_map.next(V))) {
-
- Version &v=version_map[*V];
- glDeleteShader( v.vert_id );
- glDeleteShader( v.frag_id );
- glDeleteProgram( v.id );
- memdelete_arr( v.uniform_location );
+ const VersionKey *V = NULL;
+ while ((V = version_map.next(V))) {
+
+ Version &v = version_map[*V];
+ glDeleteShader(v.vert_id);
+ glDeleteShader(v.frag_id);
+ glDeleteProgram(v.id);
+ memdelete_arr(v.uniform_location);
}
version_map.clear();
custom_code_map.clear();
- version=NULL;
- last_custom_code=1;
+ version = NULL;
+ last_custom_code = 1;
uniforms_dirty = true;
-
}
uint32_t ShaderGLES3::create_custom_shader() {
- custom_code_map[last_custom_code]=CustomCode();
- custom_code_map[last_custom_code].version=1;
+ custom_code_map[last_custom_code] = CustomCode();
+ custom_code_map[last_custom_code].version = 1;
return last_custom_code++;
}
-void ShaderGLES3::set_custom_shader_code(uint32_t p_code_id, const String& p_vertex, const String& p_vertex_globals, const String& p_fragment, const String& p_light, const String& p_fragment_globals, const String &p_uniforms, const Vector<StringName> &p_texture_uniforms, const Vector<CharString> &p_custom_defines) {
+void ShaderGLES3::set_custom_shader_code(uint32_t p_code_id, const String &p_vertex, const String &p_vertex_globals, const String &p_fragment, const String &p_light, const String &p_fragment_globals, const String &p_uniforms, const Vector<StringName> &p_texture_uniforms, const Vector<CharString> &p_custom_defines) {
ERR_FAIL_COND(!custom_code_map.has(p_code_id));
- CustomCode *cc=&custom_code_map[p_code_id];
-
-
- cc->vertex=p_vertex;
- cc->vertex_globals=p_vertex_globals;
- cc->fragment=p_fragment;
- cc->fragment_globals=p_fragment_globals;
- cc->light=p_light;
- cc->texture_uniforms=p_texture_uniforms;
- cc->uniforms=p_uniforms;
- cc->custom_defines=p_custom_defines;
+ CustomCode *cc = &custom_code_map[p_code_id];
+
+ cc->vertex = p_vertex;
+ cc->vertex_globals = p_vertex_globals;
+ cc->fragment = p_fragment;
+ cc->fragment_globals = p_fragment_globals;
+ cc->light = p_light;
+ cc->texture_uniforms = p_texture_uniforms;
+ cc->uniforms = p_uniforms;
+ cc->custom_defines = p_custom_defines;
cc->version++;
}
void ShaderGLES3::set_custom_shader(uint32_t p_code_id) {
- new_conditional_version.code_version=p_code_id;
+ new_conditional_version.code_version = p_code_id;
}
void ShaderGLES3::free_custom_shader(uint32_t p_code_id) {
- /* if (! custom_code_map.has( p_code_id )) {
+ /* if (! custom_code_map.has( p_code_id )) {
print_line("no code id "+itos(p_code_id));
} else {
print_line("freed code id "+itos(p_code_id));
}*/
- ERR_FAIL_COND(! custom_code_map.has( p_code_id ));
- if (conditional_version.code_version==p_code_id)
- conditional_version.code_version=0; //bye
+ ERR_FAIL_COND(!custom_code_map.has(p_code_id));
+ if (conditional_version.code_version == p_code_id)
+ conditional_version.code_version = 0; //bye
custom_code_map.erase(p_code_id);
-
}
void ShaderGLES3::set_base_material_tex_index(int p_idx) {
- base_material_tex_index=p_idx;
+ base_material_tex_index = p_idx;
}
ShaderGLES3::ShaderGLES3() {
- version=NULL;
- last_custom_code=1;
+ version = NULL;
+ last_custom_code = 1;
uniforms_dirty = true;
- base_material_tex_index=0;
-
+ base_material_tex_index = 0;
}
-
ShaderGLES3::~ShaderGLES3() {
-
+
finish();
}
-
-
-
diff --git a/drivers/gles3/shader_gles3.h b/drivers/gles3/shader_gles3.h
index 464f359d51..6f5ccc9126 100644
--- a/drivers/gles3/shader_gles3.h
+++ b/drivers/gles3/shader_gles3.h
@@ -38,19 +38,17 @@
#include GLES3_INCLUDE_H
#endif
+#include "camera_matrix.h"
#include "hash_map.h"
#include "map.h"
#include "variant.h"
-#include "camera_matrix.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class ShaderGLES3 {
-protected:
-
+protected:
struct Enum {
uint64_t mask;
@@ -71,7 +69,7 @@ protected:
};
struct UniformPair {
- const char* name;
+ const char *name;
Variant::Type type_hint;
};
@@ -94,8 +92,8 @@ protected:
};
bool uniforms_dirty;
-private:
+private:
//@TODO Optimize to a fixed set of shader pools and use a LRU
int uniform_count;
int texunit_pair_count;
@@ -117,22 +115,24 @@ private:
uint32_t version;
Vector<StringName> texture_uniforms;
Vector<CharString> custom_defines;
-
};
-
struct Version {
-
+
GLuint id;
GLuint vert_id;
- GLuint frag_id;
+ GLuint frag_id;
GLint *uniform_location;
Vector<GLint> texture_uniform_locations;
uint32_t code_version;
bool ok;
- Version() { code_version=0; ok=false; uniform_location=NULL; }
+ Version() {
+ code_version = 0;
+ ok = false;
+ uniform_location = NULL;
+ }
};
-
+
Version *version;
union VersionKey {
@@ -142,36 +142,34 @@ private:
uint32_t code_version;
};
uint64_t key;
- bool operator==(const VersionKey& p_key) const { return key==p_key.key; }
- bool operator<(const VersionKey& p_key) const { return key<p_key.key; }
-
+ bool operator==(const VersionKey &p_key) const { return key == p_key.key; }
+ bool operator<(const VersionKey &p_key) const { return key < p_key.key; }
};
struct VersionKeyHash {
- static _FORCE_INLINE_ uint32_t hash( const VersionKey& p_key) { return HashMapHasherDefault::hash(p_key.key); };
+ static _FORCE_INLINE_ uint32_t hash(const VersionKey &p_key) { return HashMapHasherDefault::hash(p_key.key); };
};
//this should use a way more cachefriendly version..
- HashMap<VersionKey,Version,VersionKeyHash> version_map;
+ HashMap<VersionKey, Version, VersionKeyHash> version_map;
- HashMap<uint32_t,CustomCode> custom_code_map;
+ HashMap<uint32_t, CustomCode> custom_code_map;
uint32_t last_custom_code;
-
-
+
VersionKey conditional_version;
VersionKey new_conditional_version;
-
- virtual String get_shader_name() const=0;
-
- const char** conditional_defines;
- const char** uniform_names;
+
+ virtual String get_shader_name() const = 0;
+
+ const char **conditional_defines;
+ const char **uniform_names;
const AttributePair *attribute_pairs;
const TexUnitPair *texunit_pairs;
const UBOPair *ubo_pairs;
const Feedback *feedbacks;
- const char* vertex_code;
- const char* fragment_code;
+ const char *vertex_code;
+ const char *fragment_code;
CharString fragment_code0;
CharString fragment_code1;
CharString fragment_code2;
@@ -187,213 +185,204 @@ private:
int base_material_tex_index;
- Version * get_current_version();
-
+ Version *get_current_version();
+
static ShaderGLES3 *active;
int max_image_units;
- _FORCE_INLINE_ void _set_uniform_variant(GLint p_uniform,const Variant& p_value) {
+ _FORCE_INLINE_ void _set_uniform_variant(GLint p_uniform, const Variant &p_value) {
- if (p_uniform<0)
+ if (p_uniform < 0)
return; // do none
- switch(p_value.get_type()) {
-
- case Variant::BOOL:
- case Variant::INT: {
-
- int val=p_value;
- glUniform1i( p_uniform, val );
- } break;
- case Variant::REAL: {
-
- real_t val=p_value;
- glUniform1f( p_uniform, val );
- } break;
- case Variant::COLOR: {
-
- Color val=p_value;
- glUniform4f( p_uniform, val.r, val.g,val.b,val.a );
- } break;
- case Variant::VECTOR2: {
-
- Vector2 val=p_value;
- glUniform2f( p_uniform, val.x,val.y );
- } break;
- case Variant::VECTOR3: {
-
- Vector3 val=p_value;
- glUniform3f( p_uniform, val.x,val.y,val.z );
- } break;
- case Variant::PLANE: {
-
- Plane val=p_value;
- glUniform4f( p_uniform, val.normal.x,val.normal.y,val.normal.z,val.d );
- } break;
- case Variant::QUAT: {
-
- Quat val=p_value;
- glUniform4f( p_uniform, val.x,val.y,val.z,val.w );
- } break;
-
- case Variant::TRANSFORM2D: {
-
- Transform2D tr=p_value;
- GLfloat matrix[16]={ /* build a 16x16 matrix */
- tr.elements[0][0],
- tr.elements[0][1],
- 0,
- 0,
- tr.elements[1][0],
- tr.elements[1][1],
- 0,
- 0,
- 0,
- 0,
- 1,
- 0,
- tr.elements[2][0],
- tr.elements[2][1],
- 0,
- 1
- };
-
- glUniformMatrix4fv(p_uniform,1,false,matrix);
-
- } break;
- case Variant::BASIS:
- case Variant::TRANSFORM: {
-
- Transform tr=p_value;
- GLfloat matrix[16]={ /* build a 16x16 matrix */
- tr.basis.elements[0][0],
- tr.basis.elements[1][0],
- tr.basis.elements[2][0],
- 0,
- tr.basis.elements[0][1],
- tr.basis.elements[1][1],
- tr.basis.elements[2][1],
- 0,
- tr.basis.elements[0][2],
- tr.basis.elements[1][2],
- tr.basis.elements[2][2],
- 0,
- tr.origin.x,
- tr.origin.y,
- tr.origin.z,
- 1
- };
-
-
- glUniformMatrix4fv(p_uniform,1,false,matrix);
- } break;
- default: { ERR_FAIL(); } // do nothing
-
- }
+ switch (p_value.get_type()) {
+
+ case Variant::BOOL:
+ case Variant::INT: {
+
+ int val = p_value;
+ glUniform1i(p_uniform, val);
+ } break;
+ case Variant::REAL: {
+
+ real_t val = p_value;
+ glUniform1f(p_uniform, val);
+ } break;
+ case Variant::COLOR: {
+
+ Color val = p_value;
+ glUniform4f(p_uniform, val.r, val.g, val.b, val.a);
+ } break;
+ case Variant::VECTOR2: {
+
+ Vector2 val = p_value;
+ glUniform2f(p_uniform, val.x, val.y);
+ } break;
+ case Variant::VECTOR3: {
+
+ Vector3 val = p_value;
+ glUniform3f(p_uniform, val.x, val.y, val.z);
+ } break;
+ case Variant::PLANE: {
+
+ Plane val = p_value;
+ glUniform4f(p_uniform, val.normal.x, val.normal.y, val.normal.z, val.d);
+ } break;
+ case Variant::QUAT: {
+
+ Quat val = p_value;
+ glUniform4f(p_uniform, val.x, val.y, val.z, val.w);
+ } break;
+
+ case Variant::TRANSFORM2D: {
+
+ Transform2D tr = p_value;
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
+ tr.elements[0][0],
+ tr.elements[0][1],
+ 0,
+ 0,
+ tr.elements[1][0],
+ tr.elements[1][1],
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ tr.elements[2][0],
+ tr.elements[2][1],
+ 0,
+ 1
+ };
+
+ glUniformMatrix4fv(p_uniform, 1, false, matrix);
+
+ } break;
+ case Variant::BASIS:
+ case Variant::TRANSFORM: {
+
+ Transform tr = p_value;
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
+ tr.basis.elements[0][0],
+ tr.basis.elements[1][0],
+ tr.basis.elements[2][0],
+ 0,
+ tr.basis.elements[0][1],
+ tr.basis.elements[1][1],
+ tr.basis.elements[2][1],
+ 0,
+ tr.basis.elements[0][2],
+ tr.basis.elements[1][2],
+ tr.basis.elements[2][2],
+ 0,
+ tr.origin.x,
+ tr.origin.y,
+ tr.origin.z,
+ 1
+ };
+
+ glUniformMatrix4fv(p_uniform, 1, false, matrix);
+ } break;
+ default: { ERR_FAIL(); } // do nothing
+ }
}
- Map<uint32_t,Variant> uniform_defaults;
- Map<uint32_t,CameraMatrix> uniform_cameras;
-
-
-protected:
+ Map<uint32_t, Variant> uniform_defaults;
+ Map<uint32_t, CameraMatrix> uniform_cameras;
+protected:
_FORCE_INLINE_ int _get_uniform(int p_which) const;
_FORCE_INLINE_ void _set_conditional(int p_which, bool p_value);
-
- void setup(const char** p_conditional_defines, int p_conditional_count,const char** p_uniform_names,int p_uniform_count, const AttributePair* p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const UBOPair *p_ubo_pairs,int p_ubo_pair_count, const Feedback* p_feedback, int p_feedback_count,const char*p_vertex_code, const char *p_fragment_code,int p_vertex_code_start,int p_fragment_code_start);
-
+
+ void setup(const char **p_conditional_defines, int p_conditional_count, const char **p_uniform_names, int p_uniform_count, const AttributePair *p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const UBOPair *p_ubo_pairs, int p_ubo_pair_count, const Feedback *p_feedback, int p_feedback_count, const char *p_vertex_code, const char *p_fragment_code, int p_vertex_code_start, int p_fragment_code_start);
+
ShaderGLES3();
+
public:
-
enum {
- CUSTOM_SHADER_DISABLED=0
+ CUSTOM_SHADER_DISABLED = 0
};
- GLint get_uniform_location(const String& p_name) const;
+ GLint get_uniform_location(const String &p_name) const;
GLint get_uniform_location(int p_uniform) const;
-
+
static _FORCE_INLINE_ ShaderGLES3 *get_active() { return active; };
bool bind();
void unbind();
void bind_uniforms();
-
- inline GLuint get_program() const { return version?version->id:0; }
-
+ inline GLuint get_program() const { return version ? version->id : 0; }
+
void clear_caches();
uint32_t create_custom_shader();
- void set_custom_shader_code(uint32_t p_id,const String& p_vertex, const String& p_vertex_globals,const String& p_fragment,const String& p_p_light,const String& p_fragment_globals,const String& p_uniforms,const Vector<StringName>& p_texture_uniforms,const Vector<CharString> &p_custom_defines);
+ void set_custom_shader_code(uint32_t p_id, const String &p_vertex, const String &p_vertex_globals, const String &p_fragment, const String &p_p_light, const String &p_fragment_globals, const String &p_uniforms, const Vector<StringName> &p_texture_uniforms, const Vector<CharString> &p_custom_defines);
void set_custom_shader(uint32_t p_id);
void free_custom_shader(uint32_t p_id);
- void set_uniform_default(int p_idx, const Variant& p_value) {
+ void set_uniform_default(int p_idx, const Variant &p_value) {
- if (p_value.get_type()==Variant::NIL) {
+ if (p_value.get_type() == Variant::NIL) {
uniform_defaults.erase(p_idx);
} else {
- uniform_defaults[p_idx]=p_value;
+ uniform_defaults[p_idx] = p_value;
}
uniforms_dirty = true;
}
uint32_t get_version() const { return new_conditional_version.version; }
- void set_uniform_camera(int p_idx, const CameraMatrix& p_mat) {
+ void set_uniform_camera(int p_idx, const CameraMatrix &p_mat) {
uniform_cameras[p_idx] = p_mat;
uniforms_dirty = true;
};
- _FORCE_INLINE_ void set_texture_uniform(int p_idx, const Variant& p_value) {
+ _FORCE_INLINE_ void set_texture_uniform(int p_idx, const Variant &p_value) {
ERR_FAIL_COND(!version);
- ERR_FAIL_INDEX(p_idx,version->texture_uniform_locations.size());
- _set_uniform_variant( version->texture_uniform_locations[p_idx], p_value );
+ ERR_FAIL_INDEX(p_idx, version->texture_uniform_locations.size());
+ _set_uniform_variant(version->texture_uniform_locations[p_idx], p_value);
}
-
+
_FORCE_INLINE_ GLint get_texture_uniform_location(int p_idx) {
- ERR_FAIL_COND_V(!version,-1);
- ERR_FAIL_INDEX_V(p_idx,version->texture_uniform_locations.size(),-1);
+ ERR_FAIL_COND_V(!version, -1);
+ ERR_FAIL_INDEX_V(p_idx, version->texture_uniform_locations.size(), -1);
return version->texture_uniform_locations[p_idx];
}
- virtual void init()=0;
+ virtual void init() = 0;
void finish();
void set_base_material_tex_index(int p_idx);
- void add_custom_define(const String& p_define) {
+ void add_custom_define(const String &p_define) {
custom_defines.push_back(p_define.utf8());
}
virtual ~ShaderGLES3();
-
};
-
-// called a lot, made inline
-
+// called a lot, made inline
int ShaderGLES3::_get_uniform(int p_which) const {
-
- ERR_FAIL_INDEX_V( p_which, uniform_count,-1 );
- ERR_FAIL_COND_V( !version, -1 );
+
+ ERR_FAIL_INDEX_V(p_which, uniform_count, -1);
+ ERR_FAIL_COND_V(!version, -1);
return version->uniform_location[p_which];
}
void ShaderGLES3::_set_conditional(int p_which, bool p_value) {
-
- ERR_FAIL_INDEX(p_which,conditional_count);
+
+ ERR_FAIL_INDEX(p_which, conditional_count);
if (p_value)
- new_conditional_version.version|=(1<<p_which);
+ new_conditional_version.version |= (1 << p_which);
else
- new_conditional_version.version&=~(1<<p_which);
+ new_conditional_version.version &= ~(1 << p_which);
}
#endif
-
diff --git a/drivers/png/image_loader_png.cpp b/drivers/png/image_loader_png.cpp
index 51429f3416..c524bee43c 100644
--- a/drivers/png/image_loader_png.cpp
+++ b/drivers/png/image_loader_png.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "image_loader_png.h"
-#include "print_string.h"
#include "os/os.h"
+#include "print_string.h"
#include <string.h>
+void ImageLoaderPNG::_read_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
-void ImageLoaderPNG::_read_png_data(png_structp png_ptr,png_bytep data, png_size_t p_length) {
-
- FileAccess *f = (FileAccess*)png_get_io_ptr(png_ptr);
- f->get_buffer( (uint8_t*)data, p_length );
+ FileAccess *f = (FileAccess *)png_get_io_ptr(png_ptr);
+ f->get_buffer((uint8_t *)data, p_length);
}
/*
@@ -51,7 +50,7 @@ static png_voidp _png_malloc_fn(png_structp png_ptr, png_size_t size) {
return memalloc(size);
}
-static void _png_free_fn(png_structp png_ptr, png_voidp ptr) {
+static void _png_free_fn(png_structp png_ptr, png_voidp ptr) {
memfree(ptr);
}
@@ -66,42 +65,39 @@ static void _png_warn_function(png_structp, png_const_charp text) {
WARN_PRINT(text);
}
-typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
-
-Error ImageLoaderPNG::_load_image(void *rf_up,png_rw_ptr p_func,Image *p_image) {
-
+typedef void(PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
+Error ImageLoaderPNG::_load_image(void *rf_up, png_rw_ptr p_func, Image *p_image) {
png_structp png;
png_infop info;
//png = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, NULL, NULL);
- png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,_png_error_function,_png_warn_function,(png_voidp)NULL,
- _png_malloc_fn,_png_free_fn );
+ png = png_create_read_struct_2(PNG_LIBPNG_VER_STRING, (png_voidp)NULL, _png_error_function, _png_warn_function, (png_voidp)NULL,
+ _png_malloc_fn, _png_free_fn);
ERR_FAIL_COND_V(!png, ERR_OUT_OF_MEMORY);
info = png_create_info_struct(png);
if (!info) {
- png_destroy_read_struct(&png,NULL,NULL);
+ png_destroy_read_struct(&png, NULL, NULL);
ERR_PRINT("Out of Memory");
return ERR_OUT_OF_MEMORY;
}
if (setjmp(png_jmpbuf(png))) {
- png_destroy_read_struct(&png,NULL,NULL);
- ERR_PRINT("PNG Corrupted");
- return ERR_FILE_CORRUPT;
+ png_destroy_read_struct(&png, NULL, NULL);
+ ERR_PRINT("PNG Corrupted");
+ return ERR_FILE_CORRUPT;
}
- png_set_read_fn(png,(void*)rf_up,p_func);
+ png_set_read_fn(png, (void *)rf_up, p_func);
png_uint_32 width, height;
int depth, color;
-
png_read_info(png, info);
png_get_IHDR(png, info, &width, &height, &depth, &color, NULL, NULL, NULL);
@@ -114,29 +110,28 @@ Error ImageLoaderPNG::_load_image(void *rf_up,png_rw_ptr p_func,Image *p_image)
printf("Color type:%i\n", color);
*/
- bool update_info=false;
+ bool update_info = false;
- if (depth<8) { //only bit dept 8 per channel is handled
+ if (depth < 8) { //only bit dept 8 per channel is handled
png_set_packing(png);
- update_info=true;
-
+ update_info = true;
};
- if (png_get_color_type(png,info)==PNG_COLOR_TYPE_PALETTE) {
+ if (png_get_color_type(png, info) == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png);
- update_info=true;
+ update_info = true;
}
if (depth > 8) {
png_set_strip_16(png);
- update_info=true;
+ update_info = true;
}
- if (png_get_valid(png,info,PNG_INFO_tRNS)) {
+ if (png_get_valid(png, info, PNG_INFO_tRNS)) {
//png_set_expand_gray_1_2_4_to_8(png);
png_set_tRNS_to_alpha(png);
- update_info=true;
+ update_info = true;
}
if (update_info) {
@@ -147,29 +142,28 @@ Error ImageLoaderPNG::_load_image(void *rf_up,png_rw_ptr p_func,Image *p_image)
int components = 0;
Image::Format fmt;
- switch(color) {
-
+ switch (color) {
case PNG_COLOR_TYPE_GRAY: {
- fmt=Image::FORMAT_L8;
- components=1;
+ fmt = Image::FORMAT_L8;
+ components = 1;
} break;
case PNG_COLOR_TYPE_GRAY_ALPHA: {
- fmt=Image::FORMAT_LA8;
- components=2;
+ fmt = Image::FORMAT_LA8;
+ components = 2;
} break;
case PNG_COLOR_TYPE_RGB: {
- fmt=Image::FORMAT_RGB8;
- components=3;
+ fmt = Image::FORMAT_RGB8;
+ components = 3;
} break;
case PNG_COLOR_TYPE_RGB_ALPHA: {
- fmt=Image::FORMAT_RGBA8;
- components=4;
- } break;
+ fmt = Image::FORMAT_RGBA8;
+ components = 4;
+ } break;
default: {
ERR_PRINT("INVALID PNG TYPE");
@@ -183,39 +177,35 @@ Error ImageLoaderPNG::_load_image(void *rf_up,png_rw_ptr p_func,Image *p_image)
PoolVector<uint8_t> dstbuff;
- dstbuff.resize( rowsize * height );
+ dstbuff.resize(rowsize * height);
PoolVector<uint8_t>::Write dstbuff_write = dstbuff.write();
- uint8_t* data = dstbuff_write.ptr();
+ uint8_t *data = dstbuff_write.ptr();
- uint8_t **row_p = memnew_arr( uint8_t*, height );
+ uint8_t **row_p = memnew_arr(uint8_t *, height);
for (unsigned int i = 0; i < height; i++) {
- row_p[i] = &data[components*width*i];
+ row_p[i] = &data[components * width * i];
}
- png_read_image(png, (png_bytep*)row_p);
-
+ png_read_image(png, (png_bytep *)row_p);
- memdelete_arr( row_p );
+ memdelete_arr(row_p);
- p_image->create( width, height, 0,fmt, dstbuff );
+ p_image->create(width, height, 0, fmt, dstbuff);
- png_destroy_read_struct(&png, &info, NULL );
+ png_destroy_read_struct(&png, &info, NULL);
return OK;
}
+Error ImageLoaderPNG::load_image(Image *p_image, FileAccess *f) {
-Error ImageLoaderPNG::load_image(Image *p_image,FileAccess *f) {
-
- Error err = _load_image(f,_read_png_data,p_image);
+ Error err = _load_image(f, _read_png_data, p_image);
f->close();
-
return err;
-
}
void ImageLoaderPNG::get_recognized_extensions(List<String> *p_extensions) const {
@@ -223,7 +213,6 @@ void ImageLoaderPNG::get_recognized_extensions(List<String> *p_extensions) const
p_extensions->push_back("png");
}
-
struct PNGReadStatus {
int offset;
@@ -231,84 +220,76 @@ struct PNGReadStatus {
const unsigned char *image;
};
-static void user_read_data(png_structp png_ptr,png_bytep data, png_size_t p_length) {
+static void user_read_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
PNGReadStatus *rstatus;
- rstatus=(PNGReadStatus*)png_get_io_ptr(png_ptr);
+ rstatus = (PNGReadStatus *)png_get_io_ptr(png_ptr);
- png_size_t to_read=p_length;
- if (rstatus->size>=0) {
- to_read = MIN( p_length, rstatus->size - rstatus->offset);
+ png_size_t to_read = p_length;
+ if (rstatus->size >= 0) {
+ to_read = MIN(p_length, rstatus->size - rstatus->offset);
}
- memcpy(data,&rstatus->image[rstatus->offset],to_read);
- rstatus->offset+=to_read;
+ memcpy(data, &rstatus->image[rstatus->offset], to_read);
+ rstatus->offset += to_read;
- if (to_read<p_length) {
- memset(&data[to_read],0,p_length-to_read);
+ if (to_read < p_length) {
+ memset(&data[to_read], 0, p_length - to_read);
}
}
-
-static Image _load_mem_png(const uint8_t* p_png,int p_size) {
-
+static Image _load_mem_png(const uint8_t *p_png, int p_size) {
PNGReadStatus prs;
- prs.image=p_png;
- prs.offset=0;
- prs.size=p_size;
+ prs.image = p_png;
+ prs.offset = 0;
+ prs.size = p_size;
Image img;
- Error err = ImageLoaderPNG::_load_image(&prs,user_read_data,&img);
- ERR_FAIL_COND_V(err,Image());
+ Error err = ImageLoaderPNG::_load_image(&prs, user_read_data, &img);
+ ERR_FAIL_COND_V(err, Image());
return img;
}
-
-static Image _lossless_unpack_png(const PoolVector<uint8_t>& p_data) {
+static Image _lossless_unpack_png(const PoolVector<uint8_t> &p_data) {
int len = p_data.size();
PoolVector<uint8_t>::Read r = p_data.read();
- ERR_FAIL_COND_V(r[0]!='P' || r[1]!='N' || r[2]!='G' || r[3]!=' ',Image());
- return _load_mem_png(&r[4],len-4);
-
+ ERR_FAIL_COND_V(r[0] != 'P' || r[1] != 'N' || r[2] != 'G' || r[3] != ' ', Image());
+ return _load_mem_png(&r[4], len - 4);
}
-static void _write_png_data(png_structp png_ptr,png_bytep data, png_size_t p_length) {
+static void _write_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
- PoolVector<uint8_t> &v = *(PoolVector<uint8_t>*)png_get_io_ptr(png_ptr);
+ PoolVector<uint8_t> &v = *(PoolVector<uint8_t> *)png_get_io_ptr(png_ptr);
int vs = v.size();
- v.resize(vs+p_length);
+ v.resize(vs + p_length);
PoolVector<uint8_t>::Write w = v.write();
- copymem(&w[vs],data,p_length);
+ copymem(&w[vs], data, p_length);
//print_line("png write: "+itos(p_length));
}
-
-static PoolVector<uint8_t> _lossless_pack_png(const Image& p_image) {
-
+static PoolVector<uint8_t> _lossless_pack_png(const Image &p_image) {
Image img = p_image;
if (img.is_compressed())
img.decompress();
-
ERR_FAIL_COND_V(img.is_compressed(), PoolVector<uint8_t>());
png_structp png_ptr;
png_infop info_ptr;
- png_bytep * row_pointers;
-
+ png_bytep *row_pointers;
/* initialize stuff */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- ERR_FAIL_COND_V(!png_ptr,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!png_ptr, PoolVector<uint8_t>());
info_ptr = png_create_info_struct(png_ptr);
- ERR_FAIL_COND_V(!info_ptr,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(!info_ptr, PoolVector<uint8_t>());
if (setjmp(png_jmpbuf(png_ptr))) {
ERR_FAIL_V(PoolVector<uint8_t>());
@@ -319,76 +300,73 @@ static PoolVector<uint8_t> _lossless_pack_png(const Image& p_image) {
ret.push_back('G');
ret.push_back(' ');
- png_set_write_fn(png_ptr,&ret,_write_png_data,NULL);
+ png_set_write_fn(png_ptr, &ret, _write_png_data, NULL);
/* write header */
if (setjmp(png_jmpbuf(png_ptr))) {
ERR_FAIL_V(PoolVector<uint8_t>());
}
- int pngf=0;
- int cs=0;
+ int pngf = 0;
+ int cs = 0;
- switch(img.get_format()) {
+ switch (img.get_format()) {
case Image::FORMAT_L8: {
- pngf=PNG_COLOR_TYPE_GRAY;
- cs=1;
+ pngf = PNG_COLOR_TYPE_GRAY;
+ cs = 1;
} break;
case Image::FORMAT_LA8: {
- pngf=PNG_COLOR_TYPE_GRAY_ALPHA;
- cs=2;
+ pngf = PNG_COLOR_TYPE_GRAY_ALPHA;
+ cs = 2;
} break;
case Image::FORMAT_RGB8: {
- pngf=PNG_COLOR_TYPE_RGB;
- cs=3;
+ pngf = PNG_COLOR_TYPE_RGB;
+ cs = 3;
} break;
case Image::FORMAT_RGBA8: {
- pngf=PNG_COLOR_TYPE_RGB_ALPHA;
- cs=4;
+ pngf = PNG_COLOR_TYPE_RGB_ALPHA;
+ cs = 4;
} break;
default: {
if (img.detect_alpha()) {
img.convert(Image::FORMAT_RGBA8);
- pngf=PNG_COLOR_TYPE_RGB_ALPHA;
- cs=4;
+ pngf = PNG_COLOR_TYPE_RGB_ALPHA;
+ cs = 4;
} else {
img.convert(Image::FORMAT_RGB8);
- pngf=PNG_COLOR_TYPE_RGB;
- cs=3;
+ pngf = PNG_COLOR_TYPE_RGB;
+ cs = 3;
}
-
}
}
int w = img.get_width();
int h = img.get_height();
- png_set_IHDR(png_ptr, info_ptr, w,h,
- 8, pngf, PNG_INTERLACE_NONE,
- PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+ png_set_IHDR(png_ptr, info_ptr, w, h,
+ 8, pngf, PNG_INTERLACE_NONE,
+ PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
-
/* write bytes */
if (setjmp(png_jmpbuf(png_ptr))) {
ERR_FAIL_V(PoolVector<uint8_t>());
}
-
PoolVector<uint8_t>::Read r = img.get_data().read();
- row_pointers = (png_bytep*)memalloc(sizeof(png_bytep)*h);
- for(int i=0;i<h;i++) {
+ row_pointers = (png_bytep *)memalloc(sizeof(png_bytep) * h);
+ for (int i = 0; i < h; i++) {
- row_pointers[i]=(png_bytep)&r[i*w*cs];
+ row_pointers[i] = (png_bytep)&r[i * w * cs];
}
png_write_image(png_ptr, row_pointers);
@@ -402,16 +380,12 @@ static PoolVector<uint8_t> _lossless_pack_png(const Image& p_image) {
png_write_end(png_ptr, NULL);
-
return ret;
}
ImageLoaderPNG::ImageLoaderPNG() {
-
- Image::_png_mem_loader_func=_load_mem_png;
- Image::lossless_unpacker=_lossless_unpack_png;
- Image::lossless_packer=_lossless_pack_png;
-
-
+ Image::_png_mem_loader_func = _load_mem_png;
+ Image::lossless_unpacker = _lossless_unpack_png;
+ Image::lossless_packer = _lossless_pack_png;
}
diff --git a/drivers/png/image_loader_png.h b/drivers/png/image_loader_png.h
index a98ad513db..00a64c5537 100644
--- a/drivers/png/image_loader_png.h
+++ b/drivers/png/image_loader_png.h
@@ -38,19 +38,13 @@
*/
class ImageLoaderPNG : public ImageFormatLoader {
- static void _read_png_data(png_structp png_ptr,png_bytep data, png_size_t p_length);
-
-
+ static void _read_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length);
public:
-
-
- static Error _load_image(void *rf_up,png_rw_ptr p_func,Image *p_image);
- virtual Error load_image(Image *p_image,FileAccess *f);
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
+ static Error _load_image(void *rf_up, png_rw_ptr p_func, Image *p_image);
+ virtual Error load_image(Image *p_image, FileAccess *f);
+ virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderPNG();
};
-
-
#endif
diff --git a/drivers/png/resource_saver_png.cpp b/drivers/png/resource_saver_png.cpp
index f55b089ded..ce1ffde1c8 100644
--- a/drivers/png/resource_saver_png.cpp
+++ b/drivers/png/resource_saver_png.cpp
@@ -35,20 +35,19 @@
#include <png.h>
-static void _write_png_data(png_structp png_ptr,png_bytep data, png_size_t p_length) {
+static void _write_png_data(png_structp png_ptr, png_bytep data, png_size_t p_length) {
- FileAccess *f = (FileAccess*)png_get_io_ptr(png_ptr);
- f->store_buffer( (const uint8_t*)data,p_length);
+ FileAccess *f = (FileAccess *)png_get_io_ptr(png_ptr);
+ f->store_buffer((const uint8_t *)data, p_length);
}
-Error ResourceSaverPNG::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
+Error ResourceSaverPNG::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
- Ref<ImageTexture> texture=p_resource;
+ Ref<ImageTexture> texture = p_resource;
- ERR_FAIL_COND_V(!texture.is_valid(),ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!texture.is_valid(), ERR_INVALID_PARAMETER);
ERR_EXPLAIN("Can't save empty texture as PNG");
- ERR_FAIL_COND_V(!texture->get_width() || !texture->get_height(),ERR_INVALID_PARAMETER);
-
+ ERR_FAIL_COND_V(!texture->get_width() || !texture->get_height(), ERR_INVALID_PARAMETER);
Image img = texture->get_data();
@@ -62,28 +61,28 @@ Error ResourceSaverPNG::save(const String &p_path,const RES& p_resource,uint32_t
String text;
- if (global_filter!=bool(texture->get_flags()&Texture::FLAG_FILTER)) {
- text+=bool(texture->get_flags()&Texture::FLAG_FILTER)?"filter=true\n":"filter=false\n";
+ if (global_filter != bool(texture->get_flags() & Texture::FLAG_FILTER)) {
+ text += bool(texture->get_flags() & Texture::FLAG_FILTER) ? "filter=true\n" : "filter=false\n";
}
- if (global_mipmaps!=bool(texture->get_flags()&Texture::FLAG_MIPMAPS)) {
- text+=bool(texture->get_flags()&Texture::FLAG_MIPMAPS)?"gen_mipmaps=true\n":"gen_mipmaps=false\n";
+ if (global_mipmaps != bool(texture->get_flags() & Texture::FLAG_MIPMAPS)) {
+ text += bool(texture->get_flags() & Texture::FLAG_MIPMAPS) ? "gen_mipmaps=true\n" : "gen_mipmaps=false\n";
}
- if (global_repeat!=bool(texture->get_flags()&Texture::FLAG_REPEAT)) {
- text+=bool(texture->get_flags()&Texture::FLAG_REPEAT)?"repeat=true\n":"repeat=false\n";
+ if (global_repeat != bool(texture->get_flags() & Texture::FLAG_REPEAT)) {
+ text += bool(texture->get_flags() & Texture::FLAG_REPEAT) ? "repeat=true\n" : "repeat=false\n";
}
- if (bool(texture->get_flags()&Texture::FLAG_ANISOTROPIC_FILTER)) {
- text+="anisotropic=true\n";
+ if (bool(texture->get_flags() & Texture::FLAG_ANISOTROPIC_FILTER)) {
+ text += "anisotropic=true\n";
}
- if (bool(texture->get_flags()&Texture::FLAG_CONVERT_TO_LINEAR)) {
- text+="tolinear=true\n";
+ if (bool(texture->get_flags() & Texture::FLAG_CONVERT_TO_LINEAR)) {
+ text += "tolinear=true\n";
}
- if (bool(texture->get_flags()&Texture::FLAG_MIRRORED_REPEAT)) {
- text+="mirroredrepeat=true\n";
+ if (bool(texture->get_flags() & Texture::FLAG_MIRRORED_REPEAT)) {
+ text += "mirroredrepeat=true\n";
}
- if (text!="" || FileAccess::exists(p_path+".flags")) {
+ if (text != "" || FileAccess::exists(p_path + ".flags")) {
- FileAccess* f = FileAccess::open(p_path+".flags",FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(p_path + ".flags", FileAccess::WRITE);
if (f) {
f->store_string(text);
@@ -92,7 +91,6 @@ Error ResourceSaverPNG::save(const String &p_path,const RES& p_resource,uint32_t
}
}
-
return err;
};
@@ -105,100 +103,95 @@ Error ResourceSaverPNG::save_image(const String &p_path, Image &p_img) {
png_structp png_ptr;
png_infop info_ptr;
- png_bytep * row_pointers;
-
+ png_bytep *row_pointers;
/* initialize stuff */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
- ERR_FAIL_COND_V(!png_ptr,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!png_ptr, ERR_CANT_CREATE);
info_ptr = png_create_info_struct(png_ptr);
- ERR_FAIL_COND_V(!info_ptr,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!info_ptr, ERR_CANT_CREATE);
if (setjmp(png_jmpbuf(png_ptr))) {
ERR_FAIL_V(ERR_CANT_OPEN);
}
//change this
Error err;
- FileAccess* f = FileAccess::open(p_path,FileAccess::WRITE,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
ERR_FAIL_V(err);
}
- png_set_write_fn(png_ptr,f,_write_png_data,NULL);
+ png_set_write_fn(png_ptr, f, _write_png_data, NULL);
/* write header */
if (setjmp(png_jmpbuf(png_ptr))) {
ERR_FAIL_V(ERR_CANT_OPEN);
}
- int pngf=0;
- int cs=0;
-
+ int pngf = 0;
+ int cs = 0;
- switch(p_img.get_format()) {
+ switch (p_img.get_format()) {
case Image::FORMAT_L8: {
- pngf=PNG_COLOR_TYPE_GRAY;
- cs=1;
+ pngf = PNG_COLOR_TYPE_GRAY;
+ cs = 1;
} break;
case Image::FORMAT_LA8: {
- pngf=PNG_COLOR_TYPE_GRAY_ALPHA;
- cs=2;
+ pngf = PNG_COLOR_TYPE_GRAY_ALPHA;
+ cs = 2;
} break;
case Image::FORMAT_RGB8: {
- pngf=PNG_COLOR_TYPE_RGB;
- cs=3;
+ pngf = PNG_COLOR_TYPE_RGB;
+ cs = 3;
} break;
case Image::FORMAT_RGBA8: {
- pngf=PNG_COLOR_TYPE_RGB_ALPHA;
- cs=4;
+ pngf = PNG_COLOR_TYPE_RGB_ALPHA;
+ cs = 4;
} break;
default: {
if (p_img.detect_alpha()) {
p_img.convert(Image::FORMAT_RGBA8);
- pngf=PNG_COLOR_TYPE_RGB_ALPHA;
- cs=4;
+ pngf = PNG_COLOR_TYPE_RGB_ALPHA;
+ cs = 4;
} else {
p_img.convert(Image::FORMAT_RGB8);
- pngf=PNG_COLOR_TYPE_RGB;
- cs=3;
+ pngf = PNG_COLOR_TYPE_RGB;
+ cs = 3;
}
-
}
}
int w = p_img.get_width();
int h = p_img.get_height();
- png_set_IHDR(png_ptr, info_ptr, w,h,
- 8, pngf, PNG_INTERLACE_NONE,
- PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
+ png_set_IHDR(png_ptr, info_ptr, w, h,
+ 8, pngf, PNG_INTERLACE_NONE,
+ PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
-
/* write bytes */
if (setjmp(png_jmpbuf(png_ptr))) {
memdelete(f);
ERR_FAIL_V(ERR_CANT_OPEN);
}
-
PoolVector<uint8_t>::Read r = p_img.get_data().read();
- row_pointers = (png_bytep*)memalloc(sizeof(png_bytep)*h);
- for(int i=0;i<h;i++) {
+ row_pointers = (png_bytep *)memalloc(sizeof(png_bytep) * h);
+ for (int i = 0; i < h; i++) {
- row_pointers[i]=(png_bytep)&r[i*w*cs];
+ row_pointers[i] = (png_bytep)&r[i * w * cs];
}
png_write_image(png_ptr, row_pointers);
@@ -220,16 +213,15 @@ Error ResourceSaverPNG::save_image(const String &p_path, Image &p_img) {
return OK;
}
-bool ResourceSaverPNG::recognize(const RES& p_resource) const {
+bool ResourceSaverPNG::recognize(const RES &p_resource) const {
return (p_resource.is_valid() && p_resource->is_class("ImageTexture"));
}
-void ResourceSaverPNG::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const{
+void ResourceSaverPNG::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
if (p_resource->cast_to<Texture>()) {
p_extensions->push_back("png");
}
-
}
ResourceSaverPNG::ResourceSaverPNG() {
diff --git a/drivers/png/resource_saver_png.h b/drivers/png/resource_saver_png.h
index c71877d728..ebc8d8e3ae 100644
--- a/drivers/png/resource_saver_png.h
+++ b/drivers/png/resource_saver_png.h
@@ -33,15 +33,13 @@
class ResourceSaverPNG : public ResourceFormatSaver {
public:
+ static Error save_image(const String &p_path, Image &p_img);
- static Error save_image(const String &p_path, Image& p_img);
-
- virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
- virtual bool recognize(const RES& p_resource) const;
- virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const;
+ virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
+ virtual bool recognize(const RES &p_resource) const;
+ virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
ResourceSaverPNG();
};
-
#endif // RESOURCE_SAVER_PNG_H
diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.cpp b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
index f5268f3ebd..d33ec3ce3a 100644
--- a/drivers/pulseaudio/audio_driver_pulseaudio.cpp
+++ b/drivers/pulseaudio/audio_driver_pulseaudio.cpp
@@ -43,7 +43,7 @@ Error AudioDriverPulseAudio::init() {
samples_in = NULL;
samples_out = NULL;
- mix_rate = GLOBAL_DEF("audio/mix_rate",44100);
+ mix_rate = GLOBAL_DEF("audio/mix_rate", 44100);
speaker_mode = SPEAKER_MODE_STEREO;
channels = 2;
@@ -64,23 +64,21 @@ Error AudioDriverPulseAudio::init() {
attr.minreq = (uint32_t)-1;
int error_code;
- pulse = pa_simple_new( NULL, // default server
- "Godot", // application name
- PA_STREAM_PLAYBACK,
- NULL, // default device
- "Sound", // stream description
- &spec,
- NULL, // use default channel map
- &attr, // use buffering attributes from above
- &error_code
- );
+ pulse = pa_simple_new(NULL, // default server
+ "Godot", // application name
+ PA_STREAM_PLAYBACK,
+ NULL, // default device
+ "Sound", // stream description
+ &spec,
+ NULL, // use default channel map
+ &attr, // use buffering attributes from above
+ &error_code);
if (pulse == NULL) {
- fprintf(stderr, "PulseAudio ERR: %s\n", pa_strerror(error_code));\
+ fprintf(stderr, "PulseAudio ERR: %s\n", pa_strerror(error_code));
ERR_FAIL_COND_V(pulse == NULL, ERR_CANT_OPEN);
}
-
samples_in = memnew_arr(int32_t, buffer_size * channels);
samples_out = memnew_arr(int16_t, buffer_size * channels);
@@ -92,23 +90,23 @@ Error AudioDriverPulseAudio::init() {
float AudioDriverPulseAudio::get_latency() {
- if (latency==0) { //only do this once since it's approximate anyway
+ if (latency == 0) { //only do this once since it's approximate anyway
int error_code;
- pa_usec_t palat = pa_simple_get_latency( pulse,&error_code);
- latency=double(palat)/1000000.0;
+ pa_usec_t palat = pa_simple_get_latency(pulse, &error_code);
+ latency = double(palat) / 1000000.0;
}
return latency;
}
-void AudioDriverPulseAudio::thread_func(void* p_udata) {
+void AudioDriverPulseAudio::thread_func(void *p_udata) {
print_line("thread");
- AudioDriverPulseAudio* ad = (AudioDriverPulseAudio*)p_udata;
+ AudioDriverPulseAudio *ad = (AudioDriverPulseAudio *)p_udata;
while (!ad->exit_thread) {
if (!ad->active) {
- for (unsigned int i=0; i < ad->buffer_size * ad->channels; i++) {
+ for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
ad->samples_out[i] = 0;
}
@@ -119,7 +117,7 @@ void AudioDriverPulseAudio::thread_func(void* p_udata) {
ad->unlock();
- for (unsigned int i=0; i < ad->buffer_size * ad->channels;i ++) {
+ for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
ad->samples_out[i] = ad->samples_in[i] >> 16;
}
}
@@ -199,11 +197,10 @@ AudioDriverPulseAudio::AudioDriverPulseAudio() {
mutex = NULL;
thread = NULL;
pulse = NULL;
- latency=0;
+ latency = 0;
}
AudioDriverPulseAudio::~AudioDriverPulseAudio() {
-
}
#endif
diff --git a/drivers/pulseaudio/audio_driver_pulseaudio.h b/drivers/pulseaudio/audio_driver_pulseaudio.h
index 36ae8c2e53..b6508434d4 100644
--- a/drivers/pulseaudio/audio_driver_pulseaudio.h
+++ b/drivers/pulseaudio/audio_driver_pulseaudio.h
@@ -30,27 +30,27 @@
#ifdef PULSEAUDIO_ENABLED
-#include "core/os/thread.h"
#include "core/os/mutex.h"
+#include "core/os/thread.h"
#include <pulse/simple.h>
-class AudioDriverPulseAudio : public AudioDriver{
+class AudioDriverPulseAudio : public AudioDriver {
- Thread* thread;
- Mutex* mutex;
+ Thread *thread;
+ Mutex *mutex;
- pa_simple* pulse;
+ pa_simple *pulse;
- int32_t* samples_in;
- int16_t* samples_out;
+ int32_t *samples_in;
+ int16_t *samples_out;
- static void thread_func(void* p_udata);
+ static void thread_func(void *p_udata);
unsigned int mix_rate;
SpeakerMode speaker_mode;
- unsigned int buffer_size;
+ unsigned int buffer_size;
int channels;
bool active;
@@ -61,9 +61,8 @@ class AudioDriverPulseAudio : public AudioDriver{
float latency;
public:
-
- const char* get_name() const {
- return "PulseAudio";
+ const char *get_name() const {
+ return "PulseAudio";
};
virtual Error init();
@@ -76,9 +75,8 @@ public:
virtual float get_latency();
-
- AudioDriverPulseAudio();
- ~AudioDriverPulseAudio();
+ AudioDriverPulseAudio();
+ ~AudioDriverPulseAudio();
};
#endif
diff --git a/drivers/register_driver_types.cpp b/drivers/register_driver_types.cpp
index d1d5f42944..9540a16089 100644
--- a/drivers/register_driver_types.cpp
+++ b/drivers/register_driver_types.cpp
@@ -40,32 +40,30 @@
#include "platform/windows/export/export.h"
#endif
-static ImageLoaderPNG *image_loader_png=NULL;
-static ResourceSaverPNG *resource_saver_png=NULL;
-
+static ImageLoaderPNG *image_loader_png = NULL;
+static ResourceSaverPNG *resource_saver_png = NULL;
void register_core_driver_types() {
- image_loader_png = memnew( ImageLoaderPNG );
- ImageLoader::add_image_format_loader( image_loader_png );
+ image_loader_png = memnew(ImageLoaderPNG);
+ ImageLoader::add_image_format_loader(image_loader_png);
- resource_saver_png = memnew( ResourceSaverPNG );
+ resource_saver_png = memnew(ResourceSaverPNG);
ResourceSaver::add_resource_format_saver(resource_saver_png);
}
void unregister_core_driver_types() {
if (image_loader_png)
- memdelete( image_loader_png );
+ memdelete(image_loader_png);
if (resource_saver_png)
- memdelete( resource_saver_png );
+ memdelete(resource_saver_png);
}
-
void register_driver_types() {
#ifdef TOOLS_ENABLED
- Geometry::_decompose_func=b2d_decompose;
+ Geometry::_decompose_func = b2d_decompose;
#endif
}
diff --git a/drivers/rtaudio/audio_driver_rtaudio.cpp b/drivers/rtaudio/audio_driver_rtaudio.cpp
index cc715545bd..5ecd4cbaec 100644
--- a/drivers/rtaudio/audio_driver_rtaudio.cpp
+++ b/drivers/rtaudio/audio_driver_rtaudio.cpp
@@ -33,7 +33,7 @@
#ifdef RTAUDIO_ENABLED
-const char* AudioDriverRtAudio::get_name() const {
+const char *AudioDriverRtAudio::get_name() const {
#ifdef OSX_ENABLED
return "RtAudio-OSX";
@@ -44,10 +44,9 @@ const char* AudioDriverRtAudio::get_name() const {
#else
return "RtAudio-None";
#endif
-
}
-int AudioDriverRtAudio::callback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ) {
+int AudioDriverRtAudio::callback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) {
if (status) {
if (status & RTAUDIO_INPUT_OVERFLOW) {
@@ -57,19 +56,19 @@ int AudioDriverRtAudio::callback( void *outputBuffer, void *inputBuffer, unsigne
WARN_PRINT("RtAudio output underflow!");
}
}
- int32_t *buffer = (int32_t *) outputBuffer;
+ int32_t *buffer = (int32_t *)outputBuffer;
- AudioDriverRtAudio *self = (AudioDriverRtAudio*)userData;
+ AudioDriverRtAudio *self = (AudioDriverRtAudio *)userData;
- if (self->mutex->try_lock()!=OK) {
+ if (self->mutex->try_lock() != OK) {
// what should i do..
- for(unsigned int i=0;i<nBufferFrames;i++)
- buffer[i]=0;
+ for (unsigned int i = 0; i < nBufferFrames; i++)
+ buffer[i] = 0;
return 0;
}
- self->audio_server_process(nBufferFrames,buffer);
+ self->audio_server_process(nBufferFrames, buffer);
self->mutex->unlock();
@@ -78,12 +77,12 @@ int AudioDriverRtAudio::callback( void *outputBuffer, void *inputBuffer, unsigne
Error AudioDriverRtAudio::init() {
- active=false;
- mutex=NULL;
- dac = memnew( RtAudio );
+ active = false;
+ mutex = NULL;
+ dac = memnew(RtAudio);
ERR_EXPLAIN("Cannot initialize RtAudio audio driver: No devices present.")
- ERR_FAIL_COND_V( dac->getDeviceCount() < 1, ERR_UNAVAILABLE );
+ ERR_FAIL_COND_V(dac->getDeviceCount() < 1, ERR_UNAVAILABLE);
// FIXME: Adapt to the OutputFormat -> SpeakerMode change
/*
@@ -114,60 +113,60 @@ Error AudioDriverRtAudio::init() {
//int priority; /*!< Scheduling priority of callback thread (only used with flag RTAUDIO_SCHEDULE_REALTIME). */
parameters.firstChannel = 0;
- mix_rate = GLOBAL_DEF("audio/mix_rate",44100);
+ mix_rate = GLOBAL_DEF("audio/mix_rate", 44100);
- int latency = GLOBAL_DEF("audio/output_latency",25);
+ int latency = GLOBAL_DEF("audio/output_latency", 25);
// calculate desired buffer_size, taking the desired numberOfBuffers into account (latency depends on numberOfBuffers*buffer_size)
- unsigned int buffer_size = nearest_power_of_2( latency * mix_rate / 1000 / target_number_of_buffers);
+ unsigned int buffer_size = nearest_power_of_2(latency * mix_rate / 1000 / target_number_of_buffers);
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line("audio buffer size: "+itos(buffer_size));
+ print_line("audio buffer size: " + itos(buffer_size));
}
short int tries = 2;
- while(true) {
- while( true) {
- switch(speaker_mode) {
+ while (true) {
+ while (true) {
+ switch (speaker_mode) {
case SPEAKER_MODE_STEREO: parameters.nChannels = 2; break;
case SPEAKER_SURROUND_51: parameters.nChannels = 6; break;
case SPEAKER_SURROUND_71: parameters.nChannels = 8; break;
};
try {
- dac->openStream( &parameters, NULL, RTAUDIO_SINT32, mix_rate, &buffer_size, &callback, this,&options );
+ dac->openStream(&parameters, NULL, RTAUDIO_SINT32, mix_rate, &buffer_size, &callback, this, &options);
mutex = Mutex::create(true);
- active=true;
+ active = true;
break;
- } catch ( RtAudioError& e ) {
+ } catch (RtAudioError &e) {
// try with less channels
ERR_PRINT("Unable to open audio, retrying with fewer channels..");
- switch(speaker_mode) {
- case SPEAKER_MODE_STEREO: speaker_mode=SPEAKER_MODE_STEREO; break;
- case SPEAKER_SURROUND_51: speaker_mode=SPEAKER_SURROUND_51; break;
- case SPEAKER_SURROUND_71: speaker_mode=SPEAKER_SURROUND_71; break;
+ switch (speaker_mode) {
+ case SPEAKER_MODE_STEREO: speaker_mode = SPEAKER_MODE_STEREO; break;
+ case SPEAKER_SURROUND_51: speaker_mode = SPEAKER_SURROUND_51; break;
+ case SPEAKER_SURROUND_71: speaker_mode = SPEAKER_SURROUND_71; break;
};
}
}
// compare actual numberOfBuffers with the desired one. If not equal, close and reopen the stream with adjusted buffer size, so the desired output_latency is still correct
- if(target_number_of_buffers != options.numberOfBuffers) {
- if(tries <= 0) {
+ if (target_number_of_buffers != options.numberOfBuffers) {
+ if (tries <= 0) {
ERR_EXPLAIN("RtAudio: Unable to set correct number of buffers.");
- ERR_FAIL_V( ERR_UNAVAILABLE );
+ ERR_FAIL_V(ERR_UNAVAILABLE);
break;
}
-
+
try {
dac->closeStream();
- } catch ( RtAudioError& e ) {
+ } catch (RtAudioError &e) {
ERR_PRINT(e.what());
- ERR_FAIL_V( ERR_UNAVAILABLE );
+ ERR_FAIL_V(ERR_UNAVAILABLE);
break;
}
- if (OS::get_singleton()->is_stdout_verbose())
+ if (OS::get_singleton()->is_stdout_verbose())
print_line("RtAudio: Desired number of buffers (" + itos(target_number_of_buffers) + ") not available. Using " + itos(options.numberOfBuffers) + " instead. Reopening stream with adjusted buffer_size.");
// new buffer size dependent on the ratio between set and actual numberOfBuffers
@@ -177,14 +176,11 @@ Error AudioDriverRtAudio::init() {
} else {
break;
}
-
-
}
return OK;
}
-
int AudioDriverRtAudio::get_mix_rate() const {
return mix_rate;
@@ -215,24 +211,19 @@ void AudioDriverRtAudio::unlock() {
void AudioDriverRtAudio::finish() {
- if ( active && dac->isStreamOpen() )
- dac->closeStream();
- if (mutex)
- memdelete(mutex);
- if (dac)
- memdelete(dac);
+ if (active && dac->isStreamOpen())
+ dac->closeStream();
+ if (mutex)
+ memdelete(mutex);
+ if (dac)
+ memdelete(dac);
}
+AudioDriverRtAudio::AudioDriverRtAudio() {
-
-AudioDriverRtAudio::AudioDriverRtAudio()
-{
-
- mutex=NULL;
- mix_rate=44100;
- speaker_mode=SPEAKER_MODE_STEREO;
+ mutex = NULL;
+ mix_rate = 44100;
+ speaker_mode = SPEAKER_MODE_STEREO;
}
-
-
#endif
diff --git a/drivers/rtaudio/audio_driver_rtaudio.h b/drivers/rtaudio/audio_driver_rtaudio.h
index 3f293db6a6..e7b480b7b2 100644
--- a/drivers/rtaudio/audio_driver_rtaudio.h
+++ b/drivers/rtaudio/audio_driver_rtaudio.h
@@ -37,29 +37,26 @@
class AudioDriverRtAudio : public AudioDriver {
-
- static int callback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
- double streamTime, RtAudioStreamStatus status, void *userData );
+ static int callback(void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames,
+ double streamTime, RtAudioStreamStatus status, void *userData);
SpeakerMode speaker_mode;
Mutex *mutex;
RtAudio *dac;
int mix_rate;
bool active;
-public:
-
- virtual const char* get_name() const;
+public:
+ virtual const char *get_name() const;
virtual Error init();
virtual void start();
- virtual int get_mix_rate() const ;
+ virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
virtual void lock();
virtual void unlock();
virtual void finish();
AudioDriverRtAudio();
-
};
#endif // AUDIO_DRIVER_RTAUDIO_H
diff --git a/drivers/unix/dir_access_unix.cpp b/drivers/unix/dir_access_unix.cpp
index a09cf80e6c..d3c7a42c70 100644
--- a/drivers/unix/dir_access_unix.cpp
+++ b/drivers/unix/dir_access_unix.cpp
@@ -34,20 +34,19 @@
#include <sys/statvfs.h>
#endif
-#include <stdio.h>
#include "os/memory.h"
#include "print_string.h"
#include <errno.h>
+#include <stdio.h>
DirAccess *DirAccessUnix::create_fs() {
- return memnew( DirAccessUnix );
+ return memnew(DirAccessUnix);
}
Error DirAccessUnix::list_dir_begin() {
-
+
list_dir_end(); //close any previous dir opening!
-
//char real_current_dir_name[2048]; //is this enough?!
//getcwd(real_current_dir_name,2048);
@@ -61,55 +60,51 @@ Error DirAccessUnix::list_dir_begin() {
}
bool DirAccessUnix::file_exists(String p_file) {
-
- GLOBAL_LOCK_FUNCTION
+ GLOBAL_LOCK_FUNCTION
if (p_file.is_rel_path())
- p_file=current_dir.plus_file(p_file);
+ p_file = current_dir.plus_file(p_file);
- p_file=fix_path(p_file);
+ p_file = fix_path(p_file);
struct stat flags;
- bool success = (stat(p_file.utf8().get_data(),&flags)==0);
+ bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success && S_ISDIR(flags.st_mode)) {
- success=false;
+ success = false;
}
return success;
-
}
bool DirAccessUnix::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
-
if (p_dir.is_rel_path())
- p_dir=get_current_dir().plus_file(p_dir);
+ p_dir = get_current_dir().plus_file(p_dir);
- p_dir=fix_path(p_dir);
+ p_dir = fix_path(p_dir);
struct stat flags;
- bool success = (stat(p_dir.utf8().get_data(),&flags)==0);
+ bool success = (stat(p_dir.utf8().get_data(), &flags) == 0);
if (success && S_ISDIR(flags.st_mode))
return true;
return false;
-
}
uint64_t DirAccessUnix::get_modified_time(String p_file) {
if (p_file.is_rel_path())
- p_file=current_dir.plus_file(p_file);
+ p_file = current_dir.plus_file(p_file);
- p_file=fix_path(p_file);
+ p_file = fix_path(p_file);
struct stat flags;
- bool success = (stat(p_file.utf8().get_data(),&flags)==0);
+ bool success = (stat(p_file.utf8().get_data(), &flags) == 0);
if (success) {
return flags.st_mtime;
@@ -120,16 +115,15 @@ uint64_t DirAccessUnix::get_modified_time(String p_file) {
return 0;
};
-
-String DirAccessUnix::get_next() {
+String DirAccessUnix::get_next() {
if (!dir_stream)
return "";
dirent *entry;
- entry=readdir(dir_stream);
+ entry = readdir(dir_stream);
- if (entry==NULL) {
+ if (entry == NULL) {
list_dir_end();
return "";
@@ -140,31 +134,27 @@ String DirAccessUnix::get_next() {
String fname = fix_unicode_name(entry->d_name);
- String f=current_dir.plus_file(fname);
+ String f = current_dir.plus_file(fname);
- if (stat(f.utf8().get_data(),&flags)==0) {
+ if (stat(f.utf8().get_data(), &flags) == 0) {
if (S_ISDIR(flags.st_mode)) {
- _cisdir=true;
+ _cisdir = true;
} else {
- _cisdir=false;
+ _cisdir = false;
}
} else {
- _cisdir=false;
-
+ _cisdir = false;
}
- _cishidden=(fname!="." && fname!=".." && fname.begins_with("."));
-
-
+ _cishidden = (fname != "." && fname != ".." && fname.begins_with("."));
return fname;
-
}
bool DirAccessUnix::current_is_dir() const {
@@ -177,13 +167,12 @@ bool DirAccessUnix::current_is_hidden() const {
return _cishidden;
}
-
void DirAccessUnix::list_dir_end() {
if (dir_stream)
closedir(dir_stream);
- dir_stream=0;
- _cisdir=false;
+ dir_stream = 0;
+ _cisdir = false;
}
int DirAccessUnix::get_drive_count() {
@@ -200,24 +189,21 @@ Error DirAccessUnix::make_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
- p_dir=get_current_dir().plus_file(p_dir);
-
-
- p_dir=fix_path(p_dir);
+ p_dir = get_current_dir().plus_file(p_dir);
+ p_dir = fix_path(p_dir);
#if 1
-
- bool success=(mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)==0);
+ bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
int err = errno;
#else
char real_current_dir_name[2048];
- getcwd(real_current_dir_name,2048);
+ getcwd(real_current_dir_name, 2048);
chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants
- bool success=(mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)==0);
+ bool success = (mkdir(p_dir.utf8().get_data(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0);
int err = errno;
chdir(real_current_dir_name);
@@ -233,91 +219,86 @@ Error DirAccessUnix::make_dir(String p_dir) {
return ERR_CANT_CREATE;
}
-
Error DirAccessUnix::change_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
- p_dir=fix_path(p_dir);
-
+ p_dir = fix_path(p_dir);
char real_current_dir_name[2048];
- getcwd(real_current_dir_name,2048);
+ getcwd(real_current_dir_name, 2048);
String prev_dir;
if (prev_dir.parse_utf8(real_current_dir_name))
- prev_dir=real_current_dir_name; //no utf8, maybe latin?
+ prev_dir = real_current_dir_name; //no utf8, maybe latin?
chdir(current_dir.utf8().get_data()); //ascii since this may be unicode or wathever the host os wants
- bool worked=(chdir(p_dir.utf8().get_data())==0); // we can only give this utf8
+ bool worked = (chdir(p_dir.utf8().get_data()) == 0); // we can only give this utf8
String base = _get_root_path();
- if (base!="") {
+ if (base != "") {
- getcwd(real_current_dir_name,2048);
+ getcwd(real_current_dir_name, 2048);
String new_dir;
new_dir.parse_utf8(real_current_dir_name);
if (!new_dir.begins_with(base))
- worked=false;
+ worked = false;
}
if (worked) {
- getcwd(real_current_dir_name,2048);
+ getcwd(real_current_dir_name, 2048);
if (current_dir.parse_utf8(real_current_dir_name))
- current_dir=real_current_dir_name; //no utf8, maybe latin?
+ current_dir = real_current_dir_name; //no utf8, maybe latin?
}
chdir(prev_dir.utf8().get_data());
- return worked?OK:ERR_INVALID_PARAMETER;
-
+ return worked ? OK : ERR_INVALID_PARAMETER;
}
String DirAccessUnix::get_current_dir() {
String base = _get_root_path();
- if (base!="") {
+ if (base != "") {
- String bd = current_dir.replace_first(base,"");
+ String bd = current_dir.replace_first(base, "");
if (bd.begins_with("/"))
- return _get_root_string()+bd.substr(1,bd.length());
+ return _get_root_string() + bd.substr(1, bd.length());
else
- return _get_root_string()+bd;
-
+ return _get_root_string() + bd;
}
return current_dir;
}
-Error DirAccessUnix::rename(String p_path,String p_new_path) {
+Error DirAccessUnix::rename(String p_path, String p_new_path) {
if (p_path.is_rel_path())
- p_path=get_current_dir().plus_file(p_path);
+ p_path = get_current_dir().plus_file(p_path);
- p_path=fix_path(p_path);
+ p_path = fix_path(p_path);
if (p_new_path.is_rel_path())
- p_new_path=get_current_dir().plus_file(p_new_path);
+ p_new_path = get_current_dir().plus_file(p_new_path);
- p_new_path=fix_path(p_new_path);
+ p_new_path = fix_path(p_new_path);
- return ::rename(p_path.utf8().get_data(),p_new_path.utf8().get_data())==0?OK:FAILED;
+ return ::rename(p_path.utf8().get_data(), p_new_path.utf8().get_data()) == 0 ? OK : FAILED;
}
-Error DirAccessUnix::remove(String p_path) {
+Error DirAccessUnix::remove(String p_path) {
if (p_path.is_rel_path())
- p_path=get_current_dir().plus_file(p_path);
+ p_path = get_current_dir().plus_file(p_path);
- p_path=fix_path(p_path);
+ p_path = fix_path(p_path);
struct stat flags;
- if ((stat(p_path.utf8().get_data(),&flags)!=0))
+ if ((stat(p_path.utf8().get_data(), &flags) != 0))
return FAILED;
if (S_ISDIR(flags.st_mode))
- return ::rmdir(p_path.utf8().get_data())==0?OK:FAILED;
+ return ::rmdir(p_path.utf8().get_data()) == 0 ? OK : FAILED;
else
- return ::unlink(p_path.utf8().get_data())==0?OK:FAILED;
+ return ::unlink(p_path.utf8().get_data()) == 0 ? OK : FAILED;
}
-
size_t DirAccessUnix::get_space_left() {
#ifndef NO_STATVFS
@@ -331,28 +312,23 @@ size_t DirAccessUnix::get_space_left() {
#else
#warning THIS IS BROKEN
return 0;
-#endif
+#endif
};
-
-
DirAccessUnix::DirAccessUnix() {
- dir_stream=0;
- current_dir=".";
- _cisdir=false;
+ dir_stream = 0;
+ current_dir = ".";
+ _cisdir = false;
/* determine drive count */
change_dir(current_dir);
-
}
-
DirAccessUnix::~DirAccessUnix() {
list_dir_end();
}
-
#endif //posix_enabled
diff --git a/drivers/unix/dir_access_unix.h b/drivers/unix/dir_access_unix.h
index f075c48268..0ec0e551d7 100644
--- a/drivers/unix/dir_access_unix.h
+++ b/drivers/unix/dir_access_unix.h
@@ -31,65 +31,57 @@
#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)
-#include <sys/types.h>
+#include <dirent.h>
#include <sys/stat.h>
+#include <sys/types.h>
#include <unistd.h>
-#include <dirent.h>
#include "os/dir_access.h"
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class DirAccessUnix : public DirAccess {
-
+
DIR *dir_stream;
-
+
static DirAccess *create_fs();
-
+
String current_dir;
bool _cisdir;
bool _cishidden;
-protected:
- virtual String fix_unicode_name(const char* p_name) const { return String::utf8(p_name); }
+protected:
+ virtual String fix_unicode_name(const char *p_name) const { return String::utf8(p_name); }
public:
-
virtual Error list_dir_begin(); ///< This starts dir listing
virtual String get_next();
virtual bool current_is_dir() const;
virtual bool current_is_hidden() const;
-
- virtual void list_dir_end(); ///<
-
+
+ virtual void list_dir_end(); ///<
+
virtual int get_drive_count();
virtual String get_drive(int p_drive);
-
+
virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success
virtual String get_current_dir(); ///< return current dir location
virtual Error make_dir(String p_dir);
-
+
virtual bool file_exists(String p_file);
virtual bool dir_exists(String p_dir);
virtual uint64_t get_modified_time(String p_file);
-
-
virtual Error rename(String p_from, String p_to);
virtual Error remove(String p_name);
virtual size_t get_space_left();
-
-
+
DirAccessUnix();
~DirAccessUnix();
-
};
-
-
#endif //UNIX ENABLED
#endif
diff --git a/drivers/unix/file_access_unix.cpp b/drivers/unix/file_access_unix.cpp
index ee51db6694..723bf3321a 100644
--- a/drivers/unix/file_access_unix.cpp
+++ b/drivers/unix/file_access_unix.cpp
@@ -30,20 +30,20 @@
#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)
-#include <sys/types.h>
-#include <sys/stat.h>
-#include "print_string.h"
#include "core/os/os.h"
+#include "print_string.h"
+#include <sys/stat.h>
+#include <sys/types.h>
#ifndef ANDROID_ENABLED
#include <sys/statvfs.h>
#endif
#ifdef MSVC
- #define S_ISREG(m) ((m)&_S_IFREG)
+#define S_ISREG(m) ((m)&_S_IFREG)
#endif
#ifndef S_ISREG
- #define S_ISREG(m) ((m) & S_IFREG)
+#define S_ISREG(m) ((m)&S_IFREG)
#endif
void FileAccessUnix::check_errors() const {
@@ -52,31 +52,30 @@ void FileAccessUnix::check_errors() const {
if (feof(f)) {
- last_error=ERR_FILE_EOF;
+ last_error = ERR_FILE_EOF;
}
-
}
-Error FileAccessUnix::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessUnix::_open(const String &p_path, int p_mode_flags) {
if (f)
fclose(f);
- f=NULL;
+ f = NULL;
- path=fix_path(p_path);
+ path = fix_path(p_path);
//printf("opening %ls, %i\n", path.c_str(), Memory::get_static_mem_usage());
- ERR_FAIL_COND_V(f,ERR_ALREADY_IN_USE);
- const char* mode_string;
-
- if (p_mode_flags==READ)
- mode_string="rb";
- else if (p_mode_flags==WRITE)
- mode_string="wb";
- else if (p_mode_flags==READ_WRITE)
- mode_string="rb+";
- else if (p_mode_flags==WRITE_READ)
- mode_string="wb+";
+ ERR_FAIL_COND_V(f, ERR_ALREADY_IN_USE);
+ const char *mode_string;
+
+ if (p_mode_flags == READ)
+ mode_string = "rb";
+ else if (p_mode_flags == WRITE)
+ mode_string = "wb";
+ else if (p_mode_flags == READ_WRITE)
+ mode_string = "rb+";
+ else if (p_mode_flags == WRITE_READ)
+ mode_string = "wb+";
else
return ERR_INVALID_PARAMETER;
@@ -85,30 +84,28 @@ Error FileAccessUnix::_open(const String& p_path, int p_mode_flags) {
//printf("opening %s as %s\n", p_path.utf8().get_data(), path.utf8().get_data());
struct stat st;
- if (stat(path.utf8().get_data(),&st) == 0) {
+ if (stat(path.utf8().get_data(), &st) == 0) {
if (!S_ISREG(st.st_mode))
return ERR_FILE_CANT_OPEN;
-
};
- if (is_backup_save_enabled() && p_mode_flags&WRITE && !(p_mode_flags&READ)) {
- save_path=path;
- path=path+".tmp";
+ if (is_backup_save_enabled() && p_mode_flags & WRITE && !(p_mode_flags & READ)) {
+ save_path = path;
+ path = path + ".tmp";
//print_line("saving instead to "+path);
}
- f=fopen(path.utf8().get_data(),mode_string);
+ f = fopen(path.utf8().get_data(), mode_string);
- if (f==NULL) {
- last_error=ERR_FILE_CANT_OPEN;
+ if (f == NULL) {
+ last_error = ERR_FILE_CANT_OPEN;
return ERR_FILE_CANT_OPEN;
} else {
- last_error=OK;
- flags=p_mode_flags;
+ last_error = OK;
+ flags = p_mode_flags;
return OK;
}
-
}
void FileAccessUnix::close() {
@@ -117,57 +114,53 @@ void FileAccessUnix::close() {
fclose(f);
f = NULL;
if (close_notification_func) {
- close_notification_func(path,flags);
+ close_notification_func(path, flags);
}
- if (save_path!="") {
+ if (save_path != "") {
//unlink(save_path.utf8().get_data());
//print_line("renaming..");
- int rename_error = rename((save_path+".tmp").utf8().get_data(),save_path.utf8().get_data());
+ int rename_error = rename((save_path + ".tmp").utf8().get_data(), save_path.utf8().get_data());
if (rename_error && close_fail_notify) {
close_fail_notify(save_path);
}
- save_path="";
- ERR_FAIL_COND( rename_error != 0);
+ save_path = "";
+ ERR_FAIL_COND(rename_error != 0);
}
-
-
}
-bool FileAccessUnix::is_open() const{
+bool FileAccessUnix::is_open() const {
- return (f!=NULL);
+ return (f != NULL);
}
void FileAccessUnix::seek(size_t p_position) {
ERR_FAIL_COND(!f);
- last_error=OK;
- if ( fseek(f,p_position,SEEK_SET) )
+ last_error = OK;
+ if (fseek(f, p_position, SEEK_SET))
check_errors();
}
-void FileAccessUnix::seek_end(int64_t p_position) {
+void FileAccessUnix::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
- if ( fseek(f,p_position,SEEK_END) )
+ if (fseek(f, p_position, SEEK_END))
check_errors();
}
-size_t FileAccessUnix::get_pos() const{
-
+size_t FileAccessUnix::get_pos() const {
- size_t aux_position=0;
- if ( !(aux_position = ftell(f)) ) {
+ size_t aux_position = 0;
+ if (!(aux_position = ftell(f))) {
check_errors();
};
return aux_position;
}
-size_t FileAccessUnix::get_len() const{
+size_t FileAccessUnix::get_len() const {
+ ERR_FAIL_COND_V(!f, 0);
- ERR_FAIL_COND_V(!f,0);
-
- FileAccessUnix *fau = const_cast<FileAccessUnix*>(this);
+ FileAccessUnix *fau = const_cast<FileAccessUnix *>(this);
int pos = fau->get_pos();
fau->seek_end();
int size = fau->get_pos();
@@ -176,16 +169,16 @@ size_t FileAccessUnix::get_len() const{
return size;
}
-bool FileAccessUnix::eof_reached() const{
+bool FileAccessUnix::eof_reached() const {
- return last_error==ERR_FILE_EOF;
+ return last_error == ERR_FILE_EOF;
}
-uint8_t FileAccessUnix::get_8() const{
+uint8_t FileAccessUnix::get_8() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
uint8_t b;
- if (fread(&b,1,1,f) == 0) {
+ if (fread(&b, 1, 1, f) == 0) {
check_errors();
};
@@ -194,13 +187,13 @@ uint8_t FileAccessUnix::get_8() const{
int FileAccessUnix::get_buffer(uint8_t *p_dst, int p_length) const {
- ERR_FAIL_COND_V(!f,-1);
+ ERR_FAIL_COND_V(!f, -1);
int read = fread(p_dst, 1, p_length, f);
check_errors();
return read;
};
-Error FileAccessUnix::get_error() const{
+Error FileAccessUnix::get_error() const {
return last_error;
}
@@ -208,18 +201,16 @@ Error FileAccessUnix::get_error() const{
void FileAccessUnix::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
- fwrite(&p_dest,1,1,f);
-
+ fwrite(&p_dest, 1, 1, f);
}
-
bool FileAccessUnix::file_exists(const String &p_path) {
FILE *g;
//printf("opening file %s\n", p_fname.c_str());
- String filename=fix_path(p_path);
- g=fopen(filename.utf8().get_data(),"rb");
- if (g==NULL) {
+ String filename = fix_path(p_path);
+ g = fopen(filename.utf8().get_data(), "rb");
+ if (g == NULL) {
return false;
} else {
@@ -231,38 +222,35 @@ bool FileAccessUnix::file_exists(const String &p_path) {
uint64_t FileAccessUnix::_get_modified_time(const String &p_file) {
- String file=fix_path(p_file);
+ String file = fix_path(p_file);
struct stat flags;
- bool success = (stat(file.utf8().get_data(),&flags)==0);
+ bool success = (stat(file.utf8().get_data(), &flags) == 0);
if (success) {
return flags.st_mtime;
} else {
- print_line("ERROR IN: "+p_file);
+ print_line("ERROR IN: " + p_file);
ERR_FAIL_V(0);
};
-
}
-FileAccess * FileAccessUnix::create_libc() {
+FileAccess *FileAccessUnix::create_libc() {
- return memnew( FileAccessUnix );
+ return memnew(FileAccessUnix);
}
-CloseNotificationFunc FileAccessUnix::close_notification_func=NULL;
+CloseNotificationFunc FileAccessUnix::close_notification_func = NULL;
FileAccessUnix::FileAccessUnix() {
- f=NULL;
- flags=0;
- last_error=OK;
-
+ f = NULL;
+ flags = 0;
+ last_error = OK;
}
FileAccessUnix::~FileAccessUnix() {
close();
-
}
#endif
diff --git a/drivers/unix/file_access_unix.h b/drivers/unix/file_access_unix.h
index 57b643dc26..4b5897e9a5 100644
--- a/drivers/unix/file_access_unix.h
+++ b/drivers/unix/file_access_unix.h
@@ -39,50 +39,47 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-typedef void (*CloseNotificationFunc)(const String& p_file,int p_flags);
+typedef void (*CloseNotificationFunc)(const String &p_file, int p_flags);
class FileAccessUnix : public FileAccess {
-
+
FILE *f;
int flags;
void check_errors() const;
mutable Error last_error;
String save_path;
String path;
-
- static FileAccess* create_libc();
+
+ static FileAccess *create_libc();
+
public:
-
static CloseNotificationFunc close_notification_func;
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
- virtual bool is_open() const; ///< true when file is open
+ virtual bool is_open() const; ///< true when file is open
- virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
- virtual size_t get_pos() const; ///< get position in the file
- virtual size_t get_len() const; ///< get size of the file
+ virtual void seek(size_t p_position); ///< seek to a given position
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
+ virtual size_t get_pos() const; ///< get position in the file
+ virtual size_t get_len() const; ///< get size of the file
- virtual bool eof_reached() const; ///< reading passed EOF
+ virtual bool eof_reached() const; ///< reading passed EOF
- virtual uint8_t get_8() const; ///< get a byte
+ virtual uint8_t get_8() const; ///< get a byte
virtual int get_buffer(uint8_t *p_dst, int p_length) const;
- virtual Error get_error() const; ///< get last error
+ virtual Error get_error() const; ///< get last error
- virtual void store_8(uint8_t p_dest); ///< store a byte
-
- virtual bool file_exists(const String& p_path); ///< return true if a file exists
+ virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual uint64_t _get_modified_time(const String& p_file);
+ virtual bool file_exists(const String &p_path); ///< return true if a file exists
+
+ virtual uint64_t _get_modified_time(const String &p_file);
FileAccessUnix();
virtual ~FileAccessUnix();
-
};
-
#endif
#endif
diff --git a/drivers/unix/ip_unix.cpp b/drivers/unix/ip_unix.cpp
index fc0b3faccc..d9dfd3c736 100644
--- a/drivers/unix/ip_unix.cpp
+++ b/drivers/unix/ip_unix.cpp
@@ -33,60 +33,60 @@
#include <string.h>
#ifdef WINDOWS_ENABLED
- #include <ws2tcpip.h>
- #include <winsock2.h>
- #include <windows.h>
- #include <stdio.h>
- #ifndef UWP_ENABLED
- #if defined(__MINGW32__ ) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
- // MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
- // some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
- // We don't use this Vista code for now, so working it around by disabling it.
- // MinGW-w64 >= 4.0 seems to be better judging by its headers.
- #undef _WIN32_WINNT
- #define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
- #include <iphlpapi.h>
- #undef _WIN32_WINNT
- #define _WIN32_WINNT 0x0600 // Reenable Vista API
- #else
- #include <iphlpapi.h>
- #endif // MINGW hack
- #endif
+#include <stdio.h>
+#include <windows.h>
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#ifndef UWP_ENABLED
+#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
+// MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
+// some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
+// We don't use this Vista code for now, so working it around by disabling it.
+// MinGW-w64 >= 4.0 seems to be better judging by its headers.
+#undef _WIN32_WINNT
+#define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
+#include <iphlpapi.h>
+#undef _WIN32_WINNT
+#define _WIN32_WINNT 0x0600 // Reenable Vista API
#else
- #include <netdb.h>
- #ifdef ANDROID_ENABLED
- #include "platform/android/ifaddrs_android.h"
- #else
- #ifdef __FreeBSD__
- #include <sys/types.h>
- #endif
- #include <ifaddrs.h>
- #endif
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #ifdef __FreeBSD__
- #include <netinet/in.h>
- #endif
+#include <iphlpapi.h>
+#endif // MINGW hack
+#endif
+#else
+#include <netdb.h>
+#ifdef ANDROID_ENABLED
+#include "platform/android/ifaddrs_android.h"
+#else
+#ifdef __FreeBSD__
+#include <sys/types.h>
+#endif
+#include <ifaddrs.h>
+#endif
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#ifdef __FreeBSD__
+#include <netinet/in.h>
+#endif
#endif
-static IP_Address _sockaddr2ip(struct sockaddr* p_addr) {
+static IP_Address _sockaddr2ip(struct sockaddr *p_addr) {
IP_Address ip;
if (p_addr->sa_family == AF_INET) {
- struct sockaddr_in* addr = (struct sockaddr_in*)p_addr;
+ struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
ip.set_ipv4((uint8_t *)&(addr->sin_addr));
} else {
- struct sockaddr_in6* addr6 = (struct sockaddr_in6*)p_addr;
+ struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
ip.set_ipv6(addr6->sin6_addr.s6_addr);
};
return ip;
};
-IP_Address IP_Unix::_resolve_hostname(const String& p_hostname, Type p_type) {
+IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) {
struct addrinfo hints;
- struct addrinfo* result;
+ struct addrinfo *result;
memset(&hints, 0, sizeof(struct addrinfo));
if (p_type == TYPE_IPV4) {
@@ -115,7 +115,6 @@ IP_Address IP_Unix::_resolve_hostname(const String& p_hostname, Type p_type) {
freeaddrinfo(result);
return ip;
-
}
#if defined(WINDOWS_ENABLED)
@@ -136,23 +135,22 @@ void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
r_addresses->push_back(IP_Address(String(hostnames->GetAt(i)->CanonicalName->Data())));
}
}
-
};
#else
void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
ULONG buf_size = 1024;
- IP_ADAPTER_ADDRESSES* addrs;
+ IP_ADAPTER_ADDRESSES *addrs;
while (true) {
- addrs = (IP_ADAPTER_ADDRESSES*)memalloc(buf_size);
+ addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size);
int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST |
- GAA_FLAG_SKIP_MULTICAST |
- GAA_FLAG_SKIP_DNS_SERVER |
- GAA_FLAG_SKIP_FRIENDLY_NAME,
- NULL, addrs, &buf_size);
+ GAA_FLAG_SKIP_MULTICAST |
+ GAA_FLAG_SKIP_DNS_SERVER |
+ GAA_FLAG_SKIP_FRIENDLY_NAME,
+ NULL, addrs, &buf_size);
if (err == NO_ERROR) {
break;
};
@@ -166,29 +164,27 @@ void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
return;
};
-
- IP_ADAPTER_ADDRESSES* adapter = addrs;
+ IP_ADAPTER_ADDRESSES *adapter = addrs;
while (adapter != NULL) {
- IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress;
+ IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress;
while (address != NULL) {
IP_Address ip;
if (address->Address.lpSockaddr->sa_family == AF_INET) {
- SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);
+ SOCKADDR_IN *ipv4 = reinterpret_cast<SOCKADDR_IN *>(address->Address.lpSockaddr);
ip.set_ipv4((uint8_t *)&(ipv4->sin_addr));
} else { // ipv6
- SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);
+ SOCKADDR_IN6 *ipv6 = reinterpret_cast<SOCKADDR_IN6 *>(address->Address.lpSockaddr);
ip.set_ipv6(ipv6->sin6_addr.s6_addr);
};
-
r_addresses->push_back(ip);
address = address->Next;
@@ -205,8 +201,8 @@ void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
- struct ifaddrs * ifAddrStruct=NULL;
- struct ifaddrs * ifa=NULL;
+ struct ifaddrs *ifAddrStruct = NULL;
+ struct ifaddrs *ifa = NULL;
getifaddrs(&ifAddrStruct);
@@ -218,19 +214,18 @@ void IP_Unix::get_local_addresses(List<IP_Address> *r_addresses) const {
r_addresses->push_back(ip);
}
- if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
-
+ if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
}
#endif
void IP_Unix::make_default() {
- _create=_create_unix;
+ _create = _create_unix;
}
-IP* IP_Unix::_create_unix() {
+IP *IP_Unix::_create_unix() {
- return memnew( IP_Unix );
+ return memnew(IP_Unix);
}
IP_Unix::IP_Unix() {
diff --git a/drivers/unix/ip_unix.h b/drivers/unix/ip_unix.h
index eb7ebf8bb0..c22fedfe1c 100644
--- a/drivers/unix/ip_unix.h
+++ b/drivers/unix/ip_unix.h
@@ -36,11 +36,11 @@
class IP_Unix : public IP {
GDCLASS(IP_Unix, IP);
- virtual IP_Address _resolve_hostname(const String& p_hostname, IP::Type p_type);
+ virtual IP_Address _resolve_hostname(const String &p_hostname, IP::Type p_type);
- static IP* _create_unix();
-public:
+ static IP *_create_unix();
+public:
virtual void get_local_addresses(List<IP_Address> *r_addresses) const;
static void make_default();
diff --git a/drivers/unix/mutex_posix.cpp b/drivers/unix/mutex_posix.cpp
index c9b5bdce75..9009da2065 100644
--- a/drivers/unix/mutex_posix.cpp
+++ b/drivers/unix/mutex_posix.cpp
@@ -34,7 +34,6 @@
void MutexPosix::lock() {
pthread_mutex_lock(&mutex);
-
}
void MutexPosix::unlock() {
@@ -42,32 +41,30 @@ void MutexPosix::unlock() {
}
Error MutexPosix::try_lock() {
- return (pthread_mutex_trylock(&mutex)==0)?OK:ERR_BUSY;
+ return (pthread_mutex_trylock(&mutex) == 0) ? OK : ERR_BUSY;
}
Mutex *MutexPosix::create_func_posix(bool p_recursive) {
- return memnew( MutexPosix(p_recursive) );
+ return memnew(MutexPosix(p_recursive));
}
void MutexPosix::make_default() {
- create_func=create_func_posix;
+ create_func = create_func_posix;
}
MutexPosix::MutexPosix(bool p_recursive) {
-
+
pthread_mutexattr_init(&attr);
if (p_recursive)
- pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
- pthread_mutex_init(&mutex,&attr);
+ pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+ pthread_mutex_init(&mutex, &attr);
}
-
MutexPosix::~MutexPosix() {
pthread_mutex_destroy(&mutex);
}
-
#endif
diff --git a/drivers/unix/mutex_posix.h b/drivers/unix/mutex_posix.h
index a71400924a..84fb32b844 100644
--- a/drivers/unix/mutex_posix.h
+++ b/drivers/unix/mutex_posix.h
@@ -31,29 +31,26 @@
#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)
-#include <pthread.h>
#include "os/mutex.h"
+#include <pthread.h>
class MutexPosix : public Mutex {
- pthread_mutexattr_t attr;
+ pthread_mutexattr_t attr;
pthread_mutex_t mutex;
-
+
static Mutex *create_func_posix(bool p_recursive);
-
-public:
- virtual void lock();
+public:
+ virtual void lock();
virtual void unlock();
- virtual Error try_lock();
-
+ virtual Error try_lock();
static void make_default();
MutexPosix(bool p_recursive);
-
- ~MutexPosix();
+ ~MutexPosix();
};
#endif
diff --git a/drivers/unix/os_unix.cpp b/drivers/unix/os_unix.cpp
index fe49501328..e2a544b676 100644
--- a/drivers/unix/os_unix.cpp
+++ b/drivers/unix/os_unix.cpp
@@ -32,18 +32,18 @@
#include "servers/visual_server.h"
-#include "thread_posix.h"
-#include "semaphore_posix.h"
+#include "core/os/thread_dummy.h"
#include "mutex_posix.h"
#include "rw_lock_posix.h"
-#include "core/os/thread_dummy.h"
+#include "semaphore_posix.h"
+#include "thread_posix.h"
//#include "core/io/file_access_buffered_fa.h"
-#include "file_access_unix.h"
#include "dir_access_unix.h"
-#include "tcp_server_posix.h"
-#include "stream_peer_tcp_posix.h"
+#include "file_access_unix.h"
#include "packet_peer_udp_posix.h"
+#include "stream_peer_tcp_posix.h"
+#include "tcp_server_posix.h"
#ifdef __APPLE__
#include <mach-o/dyld.h>
@@ -52,51 +52,50 @@
#ifdef __FreeBSD__
#include <sys/param.h>
#endif
+#include "global_config.h"
+#include <assert.h>
+#include <errno.h>
+#include <poll.h>
+#include <signal.h>
#include <stdarg.h>
-#include <sys/time.h>
-#include <sys/wait.h>
#include <stdlib.h>
-#include <signal.h>
#include <string.h>
-#include <poll.h>
-#include <errno.h>
-#include <assert.h>
-#include "global_config.h"
+#include <sys/time.h>
+#include <sys/wait.h>
extern bool _print_error_enabled;
-void OS_Unix::print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type) {
+void OS_Unix::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
if (!_print_error_enabled)
return;
- const char* err_details;
+ const char *err_details;
if (p_rationale && p_rationale[0])
- err_details=p_rationale;
+ err_details = p_rationale;
else
- err_details=p_code;
+ err_details = p_code;
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR:
- print("\E[1;31mERROR: %s: \E[0m\E[1m%s\n",p_function,err_details);
- print("\E[0;31m At: %s:%i.\E[0m\n",p_file,p_line);
+ print("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
+ print("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_WARNING:
- print("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n",p_function,err_details);
- print("\E[0;33m At: %s:%i.\E[0m\n",p_file,p_line);
+ print("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function, err_details);
+ print("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_SCRIPT:
- print("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n",p_function,err_details);
- print("\E[0;35m At: %s:%i.\E[0m\n",p_file,p_line);
+ print("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
+ print("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
break;
case ERR_SHADER:
- print("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n",p_function,err_details);
- print("\E[0;36m At: %s:%i.\E[0m\n",p_file,p_line);
+ print("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
+ print("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
break;
}
}
-
void OS_Unix::debug_break() {
assert(false);
@@ -105,26 +104,26 @@ void OS_Unix::debug_break() {
int OS_Unix::get_audio_driver_count() const {
return 1;
-
}
-const char * OS_Unix::get_audio_driver_name(int p_driver) const {
+const char *OS_Unix::get_audio_driver_name(int p_driver) const {
return "dummy";
}
-
+
int OS_Unix::unix_initialize_audio(int p_audio_driver) {
return 0;
}
-
+
// Very simple signal handler to reap processes where ::execute was called with
// !p_blocking
void handle_sigchld(int sig) {
int saved_errno = errno;
- while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {}
+ while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {
+ }
errno = saved_errno;
}
-
+
void OS_Unix::initialize_core() {
#ifdef NO_PTHREADS
@@ -132,9 +131,9 @@ void OS_Unix::initialize_core() {
SemaphoreDummy::make_default();
MutexDummy::make_default();
#else
- ThreadPosix::make_default();
+ ThreadPosix::make_default();
SemaphorePosix::make_default();
- MutexPosix::make_default();
+ MutexPosix::make_default();
RWLockPosix::make_default();
#endif
FileAccess::make_default<FileAccessUnix>(FileAccess::ACCESS_RESOURCES);
@@ -152,8 +151,8 @@ void OS_Unix::initialize_core() {
IP_Unix::make_default();
#endif
- ticks_start=0;
- ticks_start=get_ticks_usec();
+ ticks_start = 0;
+ ticks_start = get_ticks_usec();
struct sigaction sa;
sa.sa_handler = &handle_sigchld;
@@ -165,39 +164,34 @@ void OS_Unix::initialize_core() {
}
void OS_Unix::finalize_core() {
-
-
-
}
-
-void OS_Unix::vprint(const char* p_format, va_list p_list,bool p_stder) {
+void OS_Unix::vprint(const char *p_format, va_list p_list, bool p_stder) {
if (p_stder) {
- vfprintf(stderr,p_format,p_list);
+ vfprintf(stderr, p_format, p_list);
fflush(stderr);
} else {
- vprintf(p_format,p_list);
+ vprintf(p_format, p_list);
fflush(stdout);
}
}
-void OS_Unix::print(const char *p_format, ... ) {
+void OS_Unix::print(const char *p_format, ...) {
va_list argp;
va_start(argp, p_format);
- vprintf(p_format, argp );
+ vprintf(p_format, argp);
va_end(argp);
-
}
-void OS_Unix::alert(const String& p_alert,const String& p_title) {
+void OS_Unix::alert(const String &p_alert, const String &p_title) {
- fprintf(stderr,"ERROR: %s\n",p_alert.utf8().get_data());
+ fprintf(stderr, "ERROR: %s\n", p_alert.utf8().get_data());
}
-static int has_data(FILE* p_fd, int timeout_usec = 0) {
+static int has_data(FILE *p_fd, int timeout_usec = 0) {
fd_set readset;
int fd = fileno(p_fd);
@@ -206,17 +200,16 @@ static int has_data(FILE* p_fd, int timeout_usec = 0) {
timeval time;
time.tv_sec = 0;
time.tv_usec = timeout_usec;
- int res = 0;//select(fd + 1, &readset, NULL, NULL, &time);
+ int res = 0; //select(fd + 1, &readset, NULL, NULL, &time);
return res > 0;
};
-
String OS_Unix::get_stdin_string(bool p_block) {
String ret;
if (p_block) {
char buff[1024];
- ret = stdin_buf + fgets(buff,1024,stdin);
+ ret = stdin_buf + fgets(buff, 1024, stdin);
stdin_buf = "";
return ret;
};
@@ -243,7 +236,6 @@ String OS_Unix::get_name() {
return "Unix";
}
-
uint64_t OS_Unix::get_unix_time() const {
return time(NULL);
@@ -257,39 +249,38 @@ uint64_t OS_Unix::get_system_time_secs() const {
return uint64_t(tv_now.tv_sec);
}
-
OS::Date OS_Unix::get_date(bool utc) const {
- time_t t=time(NULL);
+ time_t t = time(NULL);
struct tm *lt;
if (utc)
- lt=gmtime(&t);
+ lt = gmtime(&t);
else
- lt=localtime(&t);
+ lt = localtime(&t);
Date ret;
- ret.year=1900+lt->tm_year;
+ ret.year = 1900 + lt->tm_year;
// Index starting at 1 to match OS_Unix::get_date
- // and Windows SYSTEMTIME and tm_mon follows the typical structure
+ // and Windows SYSTEMTIME and tm_mon follows the typical structure
// of 0-11, noted here: http://www.cplusplus.com/reference/ctime/tm/
- ret.month=(Month)(lt->tm_mon + 1);
- ret.day=lt->tm_mday;
- ret.weekday=(Weekday)lt->tm_wday;
- ret.dst=lt->tm_isdst;
-
+ ret.month = (Month)(lt->tm_mon + 1);
+ ret.day = lt->tm_mday;
+ ret.weekday = (Weekday)lt->tm_wday;
+ ret.dst = lt->tm_isdst;
+
return ret;
}
OS::Time OS_Unix::get_time(bool utc) const {
- time_t t=time(NULL);
+ time_t t = time(NULL);
struct tm *lt;
if (utc)
- lt=gmtime(&t);
+ lt = gmtime(&t);
else
- lt=localtime(&t);
+ lt = localtime(&t);
Time ret;
- ret.hour=lt->tm_hour;
- ret.min=lt->tm_min;
- ret.sec=lt->tm_sec;
+ ret.hour = lt->tm_hour;
+ ret.min = lt->tm_min;
+ ret.sec = lt->tm_sec;
get_time_zone_info();
return ret;
}
@@ -327,105 +318,99 @@ void OS_Unix::delay_usec(uint32_t p_usec) const {
uint64_t OS_Unix::get_ticks_usec() const {
struct timeval tv_now;
- gettimeofday(&tv_now,NULL);
-
- uint64_t longtime = (uint64_t)tv_now.tv_usec + (uint64_t)tv_now.tv_sec*1000000L;
- longtime-=ticks_start;
-
+ gettimeofday(&tv_now, NULL);
+
+ uint64_t longtime = (uint64_t)tv_now.tv_usec + (uint64_t)tv_now.tv_sec * 1000000L;
+ longtime -= ticks_start;
+
return longtime;
}
-Error OS_Unix::execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id,String* r_pipe,int *r_exitcode) {
-
+Error OS_Unix::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode) {
if (p_blocking && r_pipe) {
-
String argss;
- argss="\""+p_path+"\"";
+ argss = "\"" + p_path + "\"";
- for(int i=0;i<p_arguments.size();i++) {
+ for (int i = 0; i < p_arguments.size(); i++) {
- argss+=String(" \"")+p_arguments[i]+"\"";
+ argss += String(" \"") + p_arguments[i] + "\"";
}
- argss+=" 2>/dev/null"; //silence stderr
- FILE* f=popen(argss.utf8().get_data(),"r");
+ argss += " 2>/dev/null"; //silence stderr
+ FILE *f = popen(argss.utf8().get_data(), "r");
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
char buf[65535];
- while(fgets(buf,65535,f)) {
+ while (fgets(buf, 65535, f)) {
- (*r_pipe)+=buf;
+ (*r_pipe) += buf;
}
int rv = pclose(f);
if (r_exitcode)
- *r_exitcode=rv;
+ *r_exitcode = rv;
return OK;
}
-
pid_t pid = fork();
- ERR_FAIL_COND_V(pid<0,ERR_CANT_FORK);
-
+ ERR_FAIL_COND_V(pid < 0, ERR_CANT_FORK);
- if (pid==0) {
+ if (pid == 0) {
// is child
Vector<CharString> cs;
cs.push_back(p_path.utf8());
- for(int i=0;i<p_arguments.size();i++)
+ for (int i = 0; i < p_arguments.size(); i++)
cs.push_back(p_arguments[i].utf8());
- Vector<char*> args;
- for(int i=0;i<cs.size();i++)
- args.push_back((char*)cs[i].get_data());// shitty C cast
+ Vector<char *> args;
+ for (int i = 0; i < cs.size(); i++)
+ args.push_back((char *)cs[i].get_data()); // shitty C cast
args.push_back(0);
#ifdef __FreeBSD__
- if(p_path.find("/")) {
+ if (p_path.find("/")) {
// exec name contains path so use it
- execv(p_path.utf8().get_data(),&args[0]);
- }else{
+ execv(p_path.utf8().get_data(), &args[0]);
+ } else {
// use program name and search through PATH to find it
- execvp(getprogname(),&args[0]);
+ execvp(getprogname(), &args[0]);
}
#else
- execv(p_path.utf8().get_data(),&args[0]);
+ execv(p_path.utf8().get_data(), &args[0]);
#endif
// still alive? something failed..
- fprintf(stderr,"**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n",p_path.utf8().get_data());
+ fprintf(stderr, "**ERROR** OS_Unix::execute - Could not create child process while executing: %s\n", p_path.utf8().get_data());
abort();
}
if (p_blocking) {
int status;
- waitpid(pid,&status,0);
+ waitpid(pid, &status, 0);
if (r_exitcode)
- *r_exitcode=WEXITSTATUS(status);
+ *r_exitcode = WEXITSTATUS(status);
} else {
if (r_child_id)
- *r_child_id=pid;
+ *r_child_id = pid;
}
return OK;
-
}
-Error OS_Unix::kill(const ProcessID& p_pid) {
+Error OS_Unix::kill(const ProcessID &p_pid) {
- int ret = ::kill(p_pid,SIGKILL);
+ int ret = ::kill(p_pid, SIGKILL);
if (!ret) {
//avoid zombie process
int st;
- ::waitpid(p_pid,&st,0);
-
+ ::waitpid(p_pid, &st, 0);
}
- return ret?ERR_INVALID_PARAMETER:OK;
+ return ret ? ERR_INVALID_PARAMETER : OK;
}
int OS_Unix::get_process_ID() const {
@@ -433,10 +418,9 @@ int OS_Unix::get_process_ID() const {
return getpid();
};
+bool OS_Unix::has_environment(const String &p_var) const {
-bool OS_Unix::has_environment(const String& p_var) const {
-
- return getenv(p_var.utf8().get_data())!=NULL;
+ return getenv(p_var.utf8().get_data()) != NULL;
}
String OS_Unix::get_locale() const {
@@ -446,21 +430,20 @@ String OS_Unix::get_locale() const {
String locale = get_environment("LANG");
int tp = locale.find(".");
- if (tp!=-1)
- locale=locale.substr(0,tp);
+ if (tp != -1)
+ locale = locale.substr(0, tp);
return locale;
}
-Error OS_Unix::set_cwd(const String& p_cwd) {
+Error OS_Unix::set_cwd(const String &p_cwd) {
- if (chdir(p_cwd.utf8().get_data())!=0)
+ if (chdir(p_cwd.utf8().get_data()) != 0)
return ERR_CANT_OPEN;
return OK;
}
-
-String OS_Unix::get_environment(const String& p_var) const {
+String OS_Unix::get_environment(const String &p_var) const {
if (getenv(p_var.utf8().get_data()))
return getenv(p_var.utf8().get_data());
@@ -475,35 +458,30 @@ int OS_Unix::get_processor_count() const {
String OS_Unix::get_data_dir() const {
String an = get_safe_application_name();
- if (an!="") {
-
-
+ if (an != "") {
if (has_environment("HOME")) {
bool use_godot = GlobalConfig::get_singleton()->get("application/use_shared_user_dir");
if (use_godot)
- return get_environment("HOME")+"/.godot/app_userdata/"+an;
+ return get_environment("HOME") + "/.godot/app_userdata/" + an;
else
- return get_environment("HOME")+"/."+an;
+ return get_environment("HOME") + "/." + an;
}
}
return GlobalConfig::get_singleton()->get_resource_path();
-
}
-bool OS_Unix::check_feature_support(const String& p_feature) {
+bool OS_Unix::check_feature_support(const String &p_feature) {
return VisualServer::get_singleton()->has_os_feature(p_feature);
-
}
-
String OS_Unix::get_installed_templates_path() const {
- String p=get_global_settings_path();
- if (p!="")
- return p+"/templates/";
+ String p = get_global_settings_path();
+ if (p != "")
+ return p + "/templates/";
else
return "";
}
@@ -513,11 +491,11 @@ String OS_Unix::get_executable_path() const {
#ifdef __linux__
//fix for running from a symlink
char buf[256];
- memset(buf,0,256);
+ memset(buf, 0, 256);
readlink("/proc/self/exe", buf, sizeof(buf));
String b;
b.parse_utf8(buf);
- if (b=="") {
+ if (b == "") {
WARN_PRINT("Couldn't get executable path from /proc/self/exe, using argv[0]");
return OS::get_executable_path();
}
@@ -530,10 +508,10 @@ String OS_Unix::get_executable_path() const {
return String(resolved_path);
#elif defined(__APPLE__)
char temp_path[1];
- uint32_t buff_size=1;
+ uint32_t buff_size = 1;
_NSGetExecutablePath(temp_path, &buff_size);
- char* resolved_path = new char[buff_size + 1];
+ char *resolved_path = new char[buff_size + 1];
if (_NSGetExecutablePath(resolved_path, &buff_size) == 1)
WARN_PRINT("MAXPATHLEN is too small");
@@ -548,5 +526,4 @@ String OS_Unix::get_executable_path() const {
#endif
}
-
#endif
diff --git a/drivers/unix/os_unix.h b/drivers/unix/os_unix.h
index 220f818ff6..3ac4f46109 100644
--- a/drivers/unix/os_unix.h
+++ b/drivers/unix/os_unix.h
@@ -35,61 +35,57 @@
#ifdef UNIX_ENABLED
-
-#include "os/os.h"
#include "drivers/unix/ip_unix.h"
-
+#include "os/os.h"
class OS_Unix : public OS {
uint64_t ticks_start;
-protected:
+protected:
// UNIX only handles the core functions.
// inheriting platforms under unix (eg. X11) should handle the rest
-
+
//virtual int get_video_driver_count() const;
- //virtual const char * get_video_driver_name(int p_driver) const;
+ //virtual const char * get_video_driver_name(int p_driver) const;
//virtual VideoMode get_default_video_mode() const;
-
+
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
-
+ virtual const char *get_audio_driver_name(int p_driver) const;
+
virtual void initialize_core();
virtual int unix_initialize_audio(int p_audio_driver);
//virtual void initialize(int p_video_driver,int p_audio_driver);
-
+
//virtual void finalize();
virtual void finalize_core();
-
+
String stdin_buf;
String get_global_settings_path() const;
public:
+ virtual void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR);
-
- virtual void print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type=ERR_ERROR);
-
- virtual void print(const char *p_format, ... );
- virtual void vprint(const char* p_format, va_list p_list,bool p_stderr=false);
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
+ virtual void print(const char *p_format, ...);
+ virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false);
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
virtual String get_stdin_string(bool p_block);
//virtual void set_mouse_show(bool p_show);
//virtual void set_mouse_grab(bool p_grab);
//virtual bool is_mouse_grab_enabled() const = 0;
- //virtual void get_mouse_pos(int &x, int &y) const;
+ //virtual void get_mouse_pos(int &x, int &y) const;
//virtual void set_window_title(const String& p_title);
-
+
//virtual void set_video_mode(const VideoMode& p_video_mode);
//virtual VideoMode get_video_mode() const;
//virtual void get_fullscreen_mode_list(List<VideoMode> *p_list) const;
- virtual Error set_cwd(const String& p_cwd);
+ virtual Error set_cwd(const String &p_cwd);
virtual String get_name();
-
+
virtual Date get_date(bool utc) const;
virtual Time get_time(bool utc) const;
virtual TimeZoneInfo get_time_zone_info() const;
@@ -97,31 +93,28 @@ public:
virtual uint64_t get_unix_time() const;
virtual uint64_t get_system_time_secs() const;
- virtual void delay_usec(uint32_t p_usec) const;
+ virtual void delay_usec(uint32_t p_usec) const;
virtual uint64_t get_ticks_usec() const;
- virtual Error execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id=NULL,String* r_pipe=NULL,int *r_exitcode=NULL);
- virtual Error kill(const ProcessID& p_pid);
+ virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL);
+ virtual Error kill(const ProcessID &p_pid);
virtual int get_process_ID() const;
- virtual bool has_environment(const String& p_var) const;
- virtual String get_environment(const String& p_var) const;
+ virtual bool has_environment(const String &p_var) const;
+ virtual String get_environment(const String &p_var) const;
virtual String get_locale() const;
virtual int get_processor_count() const;
-
virtual void debug_break();
virtual String get_installed_templates_path() const;
virtual String get_executable_path() const;
virtual String get_data_dir() const;
- virtual bool check_feature_support(const String& p_feature);
+ virtual bool check_feature_support(const String &p_feature);
//virtual void run( MainLoop * p_main_loop );
-
-
};
#endif
diff --git a/drivers/unix/packet_peer_udp_posix.cpp b/drivers/unix/packet_peer_udp_posix.cpp
index 7696a5fcb5..98883f3267 100644
--- a/drivers/unix/packet_peer_udp_posix.cpp
+++ b/drivers/unix/packet_peer_udp_posix.cpp
@@ -30,22 +30,21 @@
#ifdef UNIX_ENABLED
-
#include <errno.h>
-#include <unistd.h>
#include <netdb.h>
-#include <sys/types.h>
#include <sys/socket.h>
+#include <sys/types.h>
+#include <unistd.h>
#include <netinet/in.h>
#include <stdio.h>
#ifndef NO_FCNTL
- #ifdef __HAIKU__
- #include <fcntl.h>
- #else
- #include <sys/fcntl.h>
- #endif
+#ifdef __HAIKU__
+#include <fcntl.h>
+#else
+#include <sys/fcntl.h>
+#endif
#else
#include <sys/ioctl.h>
#endif
@@ -58,19 +57,19 @@
int PacketPeerUDPPosix::get_available_packet_count() const {
- Error err = const_cast<PacketPeerUDPPosix*>(this)->_poll(false);
- if (err!=OK)
+ Error err = const_cast<PacketPeerUDPPosix *>(this)->_poll(false);
+ if (err != OK)
return 0;
return queue_count;
}
-Error PacketPeerUDPPosix::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const{
+Error PacketPeerUDPPosix::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const {
- Error err = const_cast<PacketPeerUDPPosix*>(this)->_poll(false);
- if (err!=OK)
+ Error err = const_cast<PacketPeerUDPPosix *>(this)->_poll(false);
+ if (err != OK)
return err;
- if (queue_count==0)
+ if (queue_count == 0)
return ERR_UNAVAILABLE;
uint32_t size;
@@ -78,38 +77,37 @@ Error PacketPeerUDPPosix::get_packet(const uint8_t **r_buffer,int &r_buffer_size
rb.read(&type, 1, true);
if (type == IP::TYPE_IPV4) {
uint8_t ip[4];
- rb.read(ip,4,true);
+ rb.read(ip, 4, true);
packet_ip.set_ipv4(ip);
} else {
uint8_t ipv6[16];
- rb.read(ipv6,16,true);
+ rb.read(ipv6, 16, true);
packet_ip.set_ipv6(ipv6);
};
- rb.read((uint8_t*)&packet_port,4,true);
- rb.read((uint8_t*)&size,4,true);
- rb.read(packet_buffer,size,true);
+ rb.read((uint8_t *)&packet_port, 4, true);
+ rb.read((uint8_t *)&size, 4, true);
+ rb.read(packet_buffer, size, true);
--queue_count;
- *r_buffer=packet_buffer;
- r_buffer_size=size;
+ *r_buffer = packet_buffer;
+ r_buffer_size = size;
return OK;
-
}
-Error PacketPeerUDPPosix::put_packet(const uint8_t *p_buffer,int p_buffer_size){
+Error PacketPeerUDPPosix::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
ERR_FAIL_COND_V(!peer_addr.is_valid(), ERR_UNCONFIGURED);
- if (sock_type==IP::TYPE_NONE)
+ if (sock_type == IP::TYPE_NONE)
sock_type = peer_addr.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
int sock = _get_socket();
- ERR_FAIL_COND_V( sock == -1, FAILED );
+ ERR_FAIL_COND_V(sock == -1, FAILED);
struct sockaddr_storage addr;
size_t addr_size = _set_sockaddr(&addr, peer_addr, peer_port, sock_type);
errno = 0;
int err;
- while ( (err = sendto(sock, p_buffer, p_buffer_size, 0, (struct sockaddr*)&addr, addr_size)) != p_buffer_size) {
+ while ((err = sendto(sock, p_buffer, p_buffer_size, 0, (struct sockaddr *)&addr, addr_size)) != p_buffer_size) {
if (errno != EAGAIN) {
return FAILED;
@@ -119,15 +117,15 @@ Error PacketPeerUDPPosix::put_packet(const uint8_t *p_buffer,int p_buffer_size){
return OK;
}
-int PacketPeerUDPPosix::get_max_packet_size() const{
+int PacketPeerUDPPosix::get_max_packet_size() const {
return 512; // uhm maybe not
}
Error PacketPeerUDPPosix::listen(int p_port, IP_Address p_bind_address, int p_recv_buffer_size) {
- ERR_FAIL_COND_V(sockfd!=-1,ERR_ALREADY_IN_USE);
- ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(),ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(sockfd != -1, ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER);
#ifdef __OpenBSD__
sock_type = IP::TYPE_IPV4; // OpenBSD does not support dual stacking, fallback to IPv4 only.
@@ -135,18 +133,18 @@ Error PacketPeerUDPPosix::listen(int p_port, IP_Address p_bind_address, int p_re
sock_type = IP::TYPE_ANY;
#endif
- if(p_bind_address.is_valid())
+ if (p_bind_address.is_valid())
sock_type = p_bind_address.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
int sock = _get_socket();
- if (sock == -1 )
+ if (sock == -1)
return ERR_CANT_CREATE;
- sockaddr_storage addr = {0};
+ sockaddr_storage addr = { 0 };
size_t addr_size = _set_listen_sockaddr(&addr, p_port, sock_type, IP_Address());
- if (bind(sock, (struct sockaddr*)&addr, addr_size) == -1 ) {
+ if (bind(sock, (struct sockaddr *)&addr, addr_size) == -1) {
close();
return ERR_UNAVAILABLE;
}
@@ -154,17 +152,16 @@ Error PacketPeerUDPPosix::listen(int p_port, IP_Address p_bind_address, int p_re
return OK;
}
-void PacketPeerUDPPosix::close(){
+void PacketPeerUDPPosix::close() {
if (sockfd != -1)
::close(sockfd);
- sockfd=-1;
+ sockfd = -1;
sock_type = IP::TYPE_NONE;
rb.resize(16);
- queue_count=0;
+ queue_count = 0;
}
-
Error PacketPeerUDPPosix::wait() {
return _poll(true);
@@ -172,22 +169,22 @@ Error PacketPeerUDPPosix::wait() {
Error PacketPeerUDPPosix::_poll(bool p_wait) {
- if (sockfd==-1) {
+ if (sockfd == -1) {
return FAILED;
}
- struct sockaddr_storage from = {0};
+ struct sockaddr_storage from = { 0 };
socklen_t len = sizeof(struct sockaddr_storage);
int ret;
- while ( (ret = recvfrom(sockfd, recv_buffer, MIN((int)sizeof(recv_buffer),MAX(rb.space_left()-24, 0)), p_wait?0:MSG_DONTWAIT, (struct sockaddr*)&from, &len)) > 0) {
+ while ((ret = recvfrom(sockfd, recv_buffer, MIN((int)sizeof(recv_buffer), MAX(rb.space_left() - 24, 0)), p_wait ? 0 : MSG_DONTWAIT, (struct sockaddr *)&from, &len)) > 0) {
uint32_t port = 0;
if (from.ss_family == AF_INET) {
uint8_t type = (uint8_t)IP::TYPE_IPV4;
rb.write(&type, 1);
- struct sockaddr_in* sin_from = (struct sockaddr_in*)&from;
- rb.write((uint8_t*)&sin_from->sin_addr, 4);
+ struct sockaddr_in *sin_from = (struct sockaddr_in *)&from;
+ rb.write((uint8_t *)&sin_from->sin_addr, 4);
port = ntohs(sin_from->sin_port);
} else if (from.ss_family == AF_INET6) {
@@ -195,8 +192,8 @@ Error PacketPeerUDPPosix::_poll(bool p_wait) {
uint8_t type = (uint8_t)IP::TYPE_IPV6;
rb.write(&type, 1);
- struct sockaddr_in6* s6_from = (struct sockaddr_in6*)&from;
- rb.write((uint8_t*)&s6_from->sin6_addr, 16);
+ struct sockaddr_in6 *s6_from = (struct sockaddr_in6 *)&from;
+ rb.write((uint8_t *)&s6_from->sin6_addr, 16);
port = ntohs(s6_from->sin6_port);
@@ -206,26 +203,25 @@ Error PacketPeerUDPPosix::_poll(bool p_wait) {
rb.write(&type, 1);
};
- rb.write((uint8_t*)&port, 4);
- rb.write((uint8_t*)&ret, 4);
+ rb.write((uint8_t *)&port, 4);
+ rb.write((uint8_t *)&ret, 4);
rb.write(recv_buffer, ret);
len = sizeof(struct sockaddr_storage);
++queue_count;
};
-
// TODO: Should ECONNRESET be handled here?
- if (ret == 0 || (ret == -1 && errno != EAGAIN) ) {
+ if (ret == 0 || (ret == -1 && errno != EAGAIN)) {
close();
return FAILED;
};
return OK;
}
-bool PacketPeerUDPPosix::is_listening() const{
+bool PacketPeerUDPPosix::is_listening() const {
- return sockfd!=-1;
+ return sockfd != -1;
}
IP_Address PacketPeerUDPPosix::get_packet_address() const {
@@ -233,14 +229,14 @@ IP_Address PacketPeerUDPPosix::get_packet_address() const {
return packet_ip;
}
-int PacketPeerUDPPosix::get_packet_port() const{
+int PacketPeerUDPPosix::get_packet_port() const {
return packet_port;
}
int PacketPeerUDPPosix::_get_socket() {
- ERR_FAIL_COND_V(sock_type==IP::TYPE_NONE, -1);
+ ERR_FAIL_COND_V(sock_type == IP::TYPE_NONE, -1);
if (sockfd != -1)
return sockfd;
@@ -250,14 +246,13 @@ int PacketPeerUDPPosix::_get_socket() {
return sockfd;
}
+void PacketPeerUDPPosix::set_dest_address(const IP_Address &p_address, int p_port) {
-void PacketPeerUDPPosix::set_dest_address(const IP_Address& p_address,int p_port) {
-
- peer_addr=p_address;
- peer_port=p_port;
+ peer_addr = p_address;
+ peer_port = p_port;
}
-PacketPeerUDP* PacketPeerUDPPosix::_create() {
+PacketPeerUDP *PacketPeerUDPPosix::_create() {
return memnew(PacketPeerUDPPosix);
};
@@ -267,13 +262,12 @@ void PacketPeerUDPPosix::make_default() {
PacketPeerUDP::_create = PacketPeerUDPPosix::_create;
};
-
PacketPeerUDPPosix::PacketPeerUDPPosix() {
- sockfd=-1;
- packet_port=0;
- queue_count=0;
- peer_port=0;
+ sockfd = -1;
+ packet_port = 0;
+ queue_count = 0;
+ peer_port = 0;
sock_type = IP::TYPE_NONE;
rb.resize(16);
}
diff --git a/drivers/unix/packet_peer_udp_posix.h b/drivers/unix/packet_peer_udp_posix.h
index ac68344d78..b44ef49f2c 100644
--- a/drivers/unix/packet_peer_udp_posix.h
+++ b/drivers/unix/packet_peer_udp_posix.h
@@ -36,9 +36,8 @@
class PacketPeerUDPPosix : public PacketPeerUDP {
-
enum {
- PACKET_BUFFER_SIZE=65536
+ PACKET_BUFFER_SIZE = 65536
};
mutable RingBuffer<uint8_t> rb;
@@ -55,18 +54,17 @@ class PacketPeerUDPPosix : public PacketPeerUDP {
_FORCE_INLINE_ int _get_socket();
- static PacketPeerUDP* _create();
+ static PacketPeerUDP *_create();
virtual Error _poll(bool p_block);
public:
-
virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const;
- virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size);
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
virtual int get_max_packet_size() const;
- virtual Error listen(int p_port, IP_Address p_bind_address=IP_Address("*"), int p_recv_buffer_size=65536);
+ virtual Error listen(int p_port, IP_Address p_bind_address = IP_Address("*"), int p_recv_buffer_size = 65536);
virtual void close();
virtual Error wait();
virtual bool is_listening() const;
@@ -74,7 +72,7 @@ public:
virtual IP_Address get_packet_address() const;
virtual int get_packet_port() const;
- virtual void set_dest_address(const IP_Address& p_address,int p_port);
+ virtual void set_dest_address(const IP_Address &p_address, int p_port);
static void make_default();
diff --git a/drivers/unix/rw_lock_posix.cpp b/drivers/unix/rw_lock_posix.cpp
index 455dde73b1..9c9ad26165 100644
--- a/drivers/unix/rw_lock_posix.cpp
+++ b/drivers/unix/rw_lock_posix.cpp
@@ -30,17 +30,17 @@
#include "rw_lock_posix.h"
-#include "os/memory.h"
#include "error_macros.h"
+#include "os/memory.h"
#include <stdio.h>
void RWLockPosix::read_lock() {
- int err =pthread_rwlock_rdlock(&rwlock);
- if (err!=0) {
+ int err = pthread_rwlock_rdlock(&rwlock);
+ if (err != 0) {
perror("wtf: ");
}
- ERR_FAIL_COND(err!=0);
+ ERR_FAIL_COND(err != 0);
}
void RWLockPosix::read_unlock() {
@@ -50,18 +50,17 @@ void RWLockPosix::read_unlock() {
Error RWLockPosix::read_try_lock() {
- if (pthread_rwlock_tryrdlock(&rwlock)!=0) {
+ if (pthread_rwlock_tryrdlock(&rwlock) != 0) {
return ERR_BUSY;
} else {
return OK;
}
-
}
void RWLockPosix::write_lock() {
int err = pthread_rwlock_wrlock(&rwlock);
- ERR_FAIL_COND(err!=0);
+ ERR_FAIL_COND(err != 0);
}
void RWLockPosix::write_unlock() {
@@ -70,36 +69,32 @@ void RWLockPosix::write_unlock() {
}
Error RWLockPosix::write_try_lock() {
- if (pthread_rwlock_trywrlock(&rwlock)!=0) {
+ if (pthread_rwlock_trywrlock(&rwlock) != 0) {
return ERR_BUSY;
} else {
return OK;
}
}
-
RWLock *RWLockPosix::create_func_posix() {
- return memnew( RWLockPosix );
+ return memnew(RWLockPosix);
}
void RWLockPosix::make_default() {
- create_func=create_func_posix;
+ create_func = create_func_posix;
}
-
RWLockPosix::RWLockPosix() {
//rwlock=PTHREAD_RWLOCK_INITIALIZER; fails on OSX
- pthread_rwlock_init(&rwlock,NULL);
+ pthread_rwlock_init(&rwlock, NULL);
}
-
RWLockPosix::~RWLockPosix() {
pthread_rwlock_destroy(&rwlock);
-
}
#endif
diff --git a/drivers/unix/rw_lock_posix.h b/drivers/unix/rw_lock_posix.h
index 35a686b15c..429b5c22d7 100644
--- a/drivers/unix/rw_lock_posix.h
+++ b/drivers/unix/rw_lock_posix.h
@@ -31,18 +31,16 @@
#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)
-#include <pthread.h>
#include "os/rw_lock.h"
+#include <pthread.h>
class RWLockPosix : public RWLock {
-
pthread_rwlock_t rwlock;
static RWLock *create_func_posix();
public:
-
virtual void read_lock();
virtual void read_unlock();
virtual Error read_try_lock();
@@ -56,10 +54,8 @@ public:
RWLockPosix();
~RWLockPosix();
-
};
#endif
-
#endif // RWLOCKPOSIX_H
diff --git a/drivers/unix/semaphore_posix.cpp b/drivers/unix/semaphore_posix.cpp
index 83b34a42dd..69f499bb52 100644
--- a/drivers/unix/semaphore_posix.cpp
+++ b/drivers/unix/semaphore_posix.cpp
@@ -36,10 +36,9 @@
Error SemaphorePosix::wait() {
-
- while(sem_wait(&sem)) {
- if (errno==EINTR) {
- errno=0;
+ while (sem_wait(&sem)) {
+ if (errno == EINTR) {
+ errno = 0;
continue;
} else {
perror("sem waiting");
@@ -51,39 +50,36 @@ Error SemaphorePosix::wait() {
Error SemaphorePosix::post() {
- return (sem_post(&sem)==0)?OK:ERR_BUSY;
+ return (sem_post(&sem) == 0) ? OK : ERR_BUSY;
}
int SemaphorePosix::get() const {
int val;
sem_getvalue(&sem, &val);
-
- return val;
-}
+ return val;
+}
Semaphore *SemaphorePosix::create_semaphore_posix() {
- return memnew( SemaphorePosix );
+ return memnew(SemaphorePosix);
}
void SemaphorePosix::make_default() {
- create_func=create_semaphore_posix;
+ create_func = create_semaphore_posix;
}
SemaphorePosix::SemaphorePosix() {
- int r = sem_init(&sem,0,0);
+ int r = sem_init(&sem, 0, 0);
if (r != 0)
perror("sem creating");
}
-
SemaphorePosix::~SemaphorePosix() {
sem_destroy(&sem);
}
-
#endif
diff --git a/drivers/unix/semaphore_posix.h b/drivers/unix/semaphore_posix.h
index 96d1ff5c06..66e10db3c3 100644
--- a/drivers/unix/semaphore_posix.h
+++ b/drivers/unix/semaphore_posix.h
@@ -29,8 +29,6 @@
#ifndef SEMAPHORE_POSIX_H
#define SEMAPHORE_POSIX_H
-
-
#include "os/semaphore.h"
#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)
@@ -46,16 +44,14 @@ class SemaphorePosix : public Semaphore {
static Semaphore *create_semaphore_posix();
public:
-
virtual Error wait();
- virtual Error post();
+ virtual Error post();
virtual int get() const;
static void make_default();
SemaphorePosix();
-
- ~SemaphorePosix();
+ ~SemaphorePosix();
};
#endif
diff --git a/drivers/unix/socket_helpers.h b/drivers/unix/socket_helpers.h
index fd5fa618ca..d27328a01e 100644
--- a/drivers/unix/socket_helpers.h
+++ b/drivers/unix/socket_helpers.h
@@ -31,28 +31,28 @@
#include <string.h>
-#if defined(__MINGW32__ ) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
- // Workaround for mingw-w64 < 4.0
- #ifndef IPV6_V6ONLY
- #define IPV6_V6ONLY 27
- #endif
+#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
+// Workaround for mingw-w64 < 4.0
+#ifndef IPV6_V6ONLY
+#define IPV6_V6ONLY 27
+#endif
#endif
// helpers for sockaddr -> IP_Address and back, should work for posix and winsock. All implementations should use this
-static size_t _set_sockaddr(struct sockaddr_storage* p_addr, const IP_Address& p_ip, int p_port, IP::Type p_sock_type = IP::TYPE_ANY) {
+static size_t _set_sockaddr(struct sockaddr_storage *p_addr, const IP_Address &p_ip, int p_port, IP::Type p_sock_type = IP::TYPE_ANY) {
memset(p_addr, 0, sizeof(struct sockaddr_storage));
- ERR_FAIL_COND_V(!p_ip.is_valid(),0);
+ ERR_FAIL_COND_V(!p_ip.is_valid(), 0);
// IPv6 socket
if (p_sock_type == IP::TYPE_IPV6 || p_sock_type == IP::TYPE_ANY) {
// IPv6 only socket with IPv4 address
- ERR_FAIL_COND_V(p_sock_type == IP::TYPE_IPV6 && p_ip.is_ipv4(),0);
+ ERR_FAIL_COND_V(p_sock_type == IP::TYPE_IPV6 && p_ip.is_ipv4(), 0);
- struct sockaddr_in6* addr6 = (struct sockaddr_in6*)p_addr;
+ struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(p_port);
copymem(&addr6->sin6_addr.s6_addr, p_ip.get_ipv6(), 16);
@@ -61,36 +61,36 @@ static size_t _set_sockaddr(struct sockaddr_storage* p_addr, const IP_Address& p
} else { // IPv4 socket
// IPv4 socket with IPv6 address
- ERR_FAIL_COND_V(!p_ip.is_ipv4(),0);
+ ERR_FAIL_COND_V(!p_ip.is_ipv4(), 0);
uint32_t ipv4 = *((uint32_t *)p_ip.get_ipv4());
- struct sockaddr_in* addr4 = (struct sockaddr_in*)p_addr;
+ struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
addr4->sin_family = AF_INET;
- addr4->sin_port = htons(p_port); // short, network byte order
+ addr4->sin_port = htons(p_port); // short, network byte order
copymem(&addr4->sin_addr.s_addr, p_ip.get_ipv4(), 16);
return sizeof(sockaddr_in);
};
};
-static size_t _set_listen_sockaddr(struct sockaddr_storage* p_addr, int p_port, IP::Type p_sock_type, const IP_Address p_bind_address) {
+static size_t _set_listen_sockaddr(struct sockaddr_storage *p_addr, int p_port, IP::Type p_sock_type, const IP_Address p_bind_address) {
memset(p_addr, 0, sizeof(struct sockaddr_storage));
if (p_sock_type == IP::TYPE_IPV4) {
- struct sockaddr_in* addr4 = (struct sockaddr_in*)p_addr;
+ struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
addr4->sin_family = AF_INET;
addr4->sin_port = htons(p_port);
- if(p_bind_address.is_valid()) {
+ if (p_bind_address.is_valid()) {
copymem(&addr4->sin_addr.s_addr, p_bind_address.get_ipv4(), 4);
} else {
addr4->sin_addr.s_addr = INADDR_ANY;
}
return sizeof(sockaddr_in);
} else {
- struct sockaddr_in6* addr6 = (struct sockaddr_in6*)p_addr;
+ struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(p_port);
- if(p_bind_address.is_valid()) {
+ if (p_bind_address.is_valid()) {
copymem(&addr6->sin6_addr.s6_addr, p_bind_address.get_ipv6(), 16);
} else {
addr6->sin6_addr = in6addr_any;
@@ -106,12 +106,12 @@ static int _socket_create(IP::Type p_type, int type, int protocol) {
int family = p_type == IP::TYPE_IPV4 ? AF_INET : AF_INET6;
int sockfd = socket(family, type, protocol);
- ERR_FAIL_COND_V( sockfd == -1, -1 );
+ ERR_FAIL_COND_V(sockfd == -1, -1);
- if(family == AF_INET6) {
+ if (family == AF_INET6) {
// Select IPv4 over IPv6 mapping
int opt = p_type != IP::TYPE_ANY;
- if(setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&opt, sizeof(opt)) != 0) {
+ if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&opt, sizeof(opt)) != 0) {
WARN_PRINT("Unable to set/unset IPv4 address mapping over IPv6");
}
}
@@ -119,24 +119,22 @@ static int _socket_create(IP::Type p_type, int type, int protocol) {
return sockfd;
}
-
-static void _set_ip_addr_port(IP_Address& r_ip, int& r_port, struct sockaddr_storage* p_addr) {
+static void _set_ip_addr_port(IP_Address &r_ip, int &r_port, struct sockaddr_storage *p_addr) {
if (p_addr->ss_family == AF_INET) {
- struct sockaddr_in* addr4 = (struct sockaddr_in*)p_addr;
+ struct sockaddr_in *addr4 = (struct sockaddr_in *)p_addr;
r_ip.set_ipv4((uint8_t *)&(addr4->sin_addr.s_addr));
r_port = ntohs(addr4->sin_port);
} else if (p_addr->ss_family == AF_INET6) {
- struct sockaddr_in6* addr6 = (struct sockaddr_in6*)p_addr;
+ struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
r_ip.set_ipv6(addr6->sin6_addr.s6_addr);
r_port = ntohs(addr6->sin6_port);
};
};
-
#endif
diff --git a/drivers/unix/stream_peer_tcp_posix.cpp b/drivers/unix/stream_peer_tcp_posix.cpp
index 08a2954617..fc4838f1e0 100644
--- a/drivers/unix/stream_peer_tcp_posix.cpp
+++ b/drivers/unix/stream_peer_tcp_posix.cpp
@@ -30,21 +30,21 @@
#include "stream_peer_tcp_posix.h"
+#include <errno.h>
+#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
#include <string.h>
-#include <netdb.h>
-#include <sys/types.h>
#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <unistd.h>
#ifndef NO_FCNTL
- #ifdef __HAIKU__
- #include <fcntl.h>
- #else
- #include <sys/fcntl.h>
- #endif
+#ifdef __HAIKU__
+#include <fcntl.h>
+#else
+#include <sys/fcntl.h>
+#endif
#else
#include <sys/ioctl.h>
#endif
@@ -58,12 +58,12 @@
#include <netinet/tcp.h>
#if defined(OSX_ENABLED) || defined(IPHONE_ENABLED)
- #define MSG_NOSIGNAL SO_NOSIGPIPE
+#define MSG_NOSIGNAL SO_NOSIGPIPE
#endif
#include "drivers/unix/socket_helpers.h"
-StreamPeerTCP* StreamPeerTCPPosix::_create() {
+StreamPeerTCP *StreamPeerTCPPosix::_create() {
return memnew(StreamPeerTCPPosix);
};
@@ -95,7 +95,7 @@ Error StreamPeerTCPPosix::_poll_connection() const {
struct sockaddr_storage their_addr;
size_t addr_size = _set_sockaddr(&their_addr, peer_host, peer_port, sock_type);
- if (::connect(sockfd, (struct sockaddr *)&their_addr,addr_size) == -1) {
+ if (::connect(sockfd, (struct sockaddr *)&their_addr, addr_size) == -1) {
if (errno == EISCONN) {
status = STATUS_CONNECTED;
@@ -134,9 +134,9 @@ void StreamPeerTCPPosix::set_socket(int p_sockfd, IP_Address p_host, int p_port,
peer_port = p_port;
};
-Error StreamPeerTCPPosix::connect_to_host(const IP_Address& p_host, uint16_t p_port) {
+Error StreamPeerTCPPosix::connect_to_host(const IP_Address &p_host, uint16_t p_port) {
- ERR_FAIL_COND_V( !p_host.is_valid(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!p_host.is_valid(), ERR_INVALID_PARAMETER);
sock_type = p_host.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
sockfd = _socket_create(sock_type, SOCK_STREAM, IPPROTO_TCP);
@@ -158,7 +158,7 @@ Error StreamPeerTCPPosix::connect_to_host(const IP_Address& p_host, uint16_t p_p
size_t addr_size = _set_sockaddr(&their_addr, p_host, p_port, sock_type);
errno = 0;
- if (::connect(sockfd, (struct sockaddr *)&their_addr,addr_size) == -1 && errno != EINPROGRESS) {
+ if (::connect(sockfd, (struct sockaddr *)&their_addr, addr_size) == -1 && errno != EINPROGRESS) {
ERR_PRINT("Connection to remote host failed!");
disconnect_from_host();
@@ -177,7 +177,7 @@ Error StreamPeerTCPPosix::connect_to_host(const IP_Address& p_host, uint16_t p_p
return OK;
};
-Error StreamPeerTCPPosix::write(const uint8_t* p_data,int p_bytes, int &r_sent, bool p_block) {
+Error StreamPeerTCPPosix::write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block) {
if (status == STATUS_NONE || status == STATUS_ERROR) {
@@ -237,7 +237,7 @@ Error StreamPeerTCPPosix::write(const uint8_t* p_data,int p_bytes, int &r_sent,
return OK;
};
-Error StreamPeerTCPPosix::read(uint8_t* p_buffer, int p_bytes,int &r_received, bool p_block) {
+Error StreamPeerTCPPosix::read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block) {
if (!is_connected_to_host()) {
@@ -282,9 +282,9 @@ Error StreamPeerTCPPosix::read(uint8_t* p_buffer, int p_bytes,int &r_received, b
};
_block(sockfd, true, false);
- } else if (read==0) {
+ } else if (read == 0) {
- sockfd=-1;
+ sockfd = -1;
status = STATUS_NONE;
peer_port = 0;
peer_host = IP_Address();
@@ -305,8 +305,8 @@ Error StreamPeerTCPPosix::read(uint8_t* p_buffer, int p_bytes,int &r_received, b
void StreamPeerTCPPosix::set_nodelay(bool p_enabled) {
ERR_FAIL_COND(!is_connected_to_host());
- int flag=p_enabled?1:0;
- setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
+ int flag = p_enabled ? 1 : 0;
+ setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
}
bool StreamPeerTCPPosix::is_connected_to_host() const {
@@ -319,7 +319,7 @@ bool StreamPeerTCPPosix::is_connected_to_host() const {
return true;
};
- return (sockfd!=-1);
+ return (sockfd != -1);
};
StreamPeerTCP::Status StreamPeerTCPPosix::get_status() const {
@@ -331,39 +331,37 @@ StreamPeerTCP::Status StreamPeerTCPPosix::get_status() const {
return status;
};
-
void StreamPeerTCPPosix::disconnect_from_host() {
if (sockfd != -1)
close(sockfd);
sock_type = IP::TYPE_NONE;
- sockfd=-1;
+ sockfd = -1;
status = STATUS_NONE;
peer_port = 0;
peer_host = IP_Address();
};
-
-Error StreamPeerTCPPosix::put_data(const uint8_t* p_data,int p_bytes) {
+Error StreamPeerTCPPosix::put_data(const uint8_t *p_data, int p_bytes) {
int total;
return write(p_data, p_bytes, total, true);
};
-Error StreamPeerTCPPosix::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent) {
+Error StreamPeerTCPPosix::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
return write(p_data, p_bytes, r_sent, false);
};
-Error StreamPeerTCPPosix::get_data(uint8_t* p_buffer, int p_bytes) {
+Error StreamPeerTCPPosix::get_data(uint8_t *p_buffer, int p_bytes) {
int total;
return read(p_buffer, p_bytes, total, true);
};
-Error StreamPeerTCPPosix::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received) {
+Error StreamPeerTCPPosix::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
return read(p_buffer, p_bytes, r_received, false);
};
@@ -371,10 +369,9 @@ Error StreamPeerTCPPosix::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r
int StreamPeerTCPPosix::get_available_bytes() const {
unsigned long len;
- int ret = ioctl(sockfd,FIONREAD,&len);
- ERR_FAIL_COND_V(ret==-1,0)
+ int ret = ioctl(sockfd, FIONREAD, &len);
+ ERR_FAIL_COND_V(ret == -1, 0)
return len;
-
}
IP_Address StreamPeerTCPPosix::get_connected_host() const {
diff --git a/drivers/unix/stream_peer_tcp_posix.h b/drivers/unix/stream_peer_tcp_posix.h
index 7f8d90a448..ef98f2ab83 100644
--- a/drivers/unix/stream_peer_tcp_posix.h
+++ b/drivers/unix/stream_peer_tcp_posix.h
@@ -38,7 +38,6 @@
class StreamPeerTCPPosix : public StreamPeerTCP {
protected:
-
mutable Status status;
IP::Type sock_type;
@@ -51,20 +50,19 @@ protected:
IP_Address peer_host;
int peer_port;
- Error write(const uint8_t* p_data,int p_bytes, int &r_sent, bool p_block);
- Error read(uint8_t* p_buffer, int p_bytes,int &r_received, bool p_block);
+ Error write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block);
+ Error read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block);
- static StreamPeerTCP* _create();
+ static StreamPeerTCP *_create();
public:
+ virtual Error connect_to_host(const IP_Address &p_host, uint16_t p_port);
- virtual Error connect_to_host(const IP_Address& p_host, uint16_t p_port);
-
- virtual Error put_data(const uint8_t* p_data,int p_bytes);
- virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent);
+ virtual Error put_data(const uint8_t *p_data, int p_bytes);
+ virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent);
- virtual Error get_data(uint8_t* p_buffer, int p_bytes);
- virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received);
+ virtual Error get_data(uint8_t *p_buffer, int p_bytes);
+ virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received);
virtual int get_available_bytes() const;
diff --git a/drivers/unix/tcp_server_posix.cpp b/drivers/unix/tcp_server_posix.cpp
index 7e9970453f..9049faebb8 100644
--- a/drivers/unix/tcp_server_posix.cpp
+++ b/drivers/unix/tcp_server_posix.cpp
@@ -33,32 +33,32 @@
#include <poll.h>
+#include <errno.h>
+#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
#include <string.h>
-#include <netdb.h>
#include <sys/types.h>
+#include <unistd.h>
#ifndef NO_FCNTL
- #ifdef __HAIKU__
- #include <fcntl.h>
- #else
- #include <sys/fcntl.h>
- #endif
+#ifdef __HAIKU__
+#include <fcntl.h>
+#else
+#include <sys/fcntl.h>
+#endif
#else
#include <sys/ioctl.h>
#endif
#ifdef JAVASCRIPT_ENABLED
#include <arpa/inet.h>
#endif
+#include <assert.h>
#include <netinet/in.h>
#include <sys/socket.h>
-#include <assert.h>
#include "drivers/unix/socket_helpers.h"
-TCP_Server* TCPServerPosix::_create() {
+TCP_Server *TCPServerPosix::_create() {
return memnew(TCPServerPosix);
};
@@ -68,9 +68,9 @@ void TCPServerPosix::make_default() {
TCP_Server::_create = TCPServerPosix::_create;
};
-Error TCPServerPosix::listen(uint16_t p_port,const IP_Address p_bind_address) {
+Error TCPServerPosix::listen(uint16_t p_port, const IP_Address p_bind_address) {
- ERR_FAIL_COND_V(listen_sockfd!=-1,ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(listen_sockfd != -1, ERR_ALREADY_IN_USE);
ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER);
int sockfd;
@@ -95,8 +95,8 @@ Error TCPServerPosix::listen(uint16_t p_port,const IP_Address p_bind_address) {
ioctl(sockfd, FIONBIO, &bval);
#endif
- int reuse=1;
- if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) {
+ int reuse = 1;
+ if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) {
WARN_PRINT("REUSEADDR failed!")
}
@@ -110,8 +110,7 @@ Error TCPServerPosix::listen(uint16_t p_port,const IP_Address p_bind_address) {
close(sockfd);
ERR_FAIL_V(FAILED);
};
- }
- else {
+ } else {
return ERR_ALREADY_IN_USE;
};
@@ -177,14 +176,13 @@ void TCPServerPosix::stop() {
if (listen_sockfd != -1) {
int ret = close(listen_sockfd);
- ERR_FAIL_COND(ret!=0);
+ ERR_FAIL_COND(ret != 0);
};
listen_sockfd = -1;
sock_type = IP::TYPE_NONE;
};
-
TCPServerPosix::TCPServerPosix() {
listen_sockfd = -1;
diff --git a/drivers/unix/tcp_server_posix.h b/drivers/unix/tcp_server_posix.h
index ea42d0fc0c..408179c197 100644
--- a/drivers/unix/tcp_server_posix.h
+++ b/drivers/unix/tcp_server_posix.h
@@ -37,11 +37,10 @@ class TCPServerPosix : public TCP_Server {
int listen_sockfd;
IP::Type sock_type;
- static TCP_Server* _create();
+ static TCP_Server *_create();
public:
-
- virtual Error listen(uint16_t p_port, IP_Address p_bind_address=IP_Address("*"));
+ virtual Error listen(uint16_t p_port, IP_Address p_bind_address = IP_Address("*"));
virtual bool is_connection_available() const;
virtual Ref<StreamPeerTCP> take_connection();
@@ -53,6 +52,5 @@ public:
~TCPServerPosix();
};
-
#endif // TCP_SERVER_POSIX_H
#endif
diff --git a/drivers/unix/thread_posix.cpp b/drivers/unix/thread_posix.cpp
index ecea67c37b..c33cc8cc5d 100644
--- a/drivers/unix/thread_posix.cpp
+++ b/drivers/unix/thread_posix.cpp
@@ -39,18 +39,18 @@
Thread::ID ThreadPosix::get_ID() const {
- return id;
+ return id;
}
-Thread* ThreadPosix::create_thread_posix() {
+Thread *ThreadPosix::create_thread_posix() {
- return memnew( ThreadPosix );
+ return memnew(ThreadPosix);
}
void *ThreadPosix::thread_callback(void *userdata) {
- ThreadPosix *t=reinterpret_cast<ThreadPosix*>(userdata);
- t->id=(ID)pthread_self();
+ ThreadPosix *t = reinterpret_cast<ThreadPosix *>(userdata);
+ t->id = (ID)pthread_self();
ScriptServer::thread_enter(); //scripts may need to attach a stack
@@ -61,80 +61,77 @@ void *ThreadPosix::thread_callback(void *userdata) {
return NULL;
}
-Thread* ThreadPosix::create_func_posix(ThreadCreateCallback p_callback,void *p_user,const Settings&) {
+Thread *ThreadPosix::create_func_posix(ThreadCreateCallback p_callback, void *p_user, const Settings &) {
- ThreadPosix *tr= memnew(ThreadPosix);
- tr->callback=p_callback;
- tr->user=p_user;
+ ThreadPosix *tr = memnew(ThreadPosix);
+ tr->callback = p_callback;
+ tr->user = p_user;
pthread_attr_init(&tr->pthread_attr);
pthread_attr_setdetachstate(&tr->pthread_attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setstacksize(&tr->pthread_attr, 256 * 1024);
-
+
pthread_create(&tr->pthread, &tr->pthread_attr, thread_callback, tr);
-
+
return tr;
}
Thread::ID ThreadPosix::get_thread_ID_func_posix() {
return (ID)pthread_self();
}
-void ThreadPosix::wait_to_finish_func_posix(Thread* p_thread) {
+void ThreadPosix::wait_to_finish_func_posix(Thread *p_thread) {
- ThreadPosix *tp=static_cast<ThreadPosix*>(p_thread);
+ ThreadPosix *tp = static_cast<ThreadPosix *>(p_thread);
ERR_FAIL_COND(!tp);
- ERR_FAIL_COND(tp->pthread==0);
-
- pthread_join(tp->pthread,NULL);
- tp->pthread=0;
+ ERR_FAIL_COND(tp->pthread == 0);
+
+ pthread_join(tp->pthread, NULL);
+ tp->pthread = 0;
}
-Error ThreadPosix::set_name_func_posix(const String& p_name) {
+Error ThreadPosix::set_name_func_posix(const String &p_name) {
pthread_t running_thread = pthread_self();
- #ifdef PTHREAD_NO_RENAME
+#ifdef PTHREAD_NO_RENAME
return ERR_UNAVAILABLE;
- #else
+#else
- #ifdef PTHREAD_RENAME_SELF
+#ifdef PTHREAD_RENAME_SELF
// check if thread is the same as caller
int err = pthread_setname_np(p_name.utf8().get_data());
-
- #else
- #ifdef PTHREAD_BSD_SET_NAME
+#else
+
+#ifdef PTHREAD_BSD_SET_NAME
pthread_set_name_np(running_thread, p_name.utf8().get_data());
int err = 0; // Open/FreeBSD ignore errors in this function
- #else
+#else
int err = pthread_setname_np(running_thread, p_name.utf8().get_data());
- #endif // PTHREAD_BSD_SET_NAME
+#endif // PTHREAD_BSD_SET_NAME
- #endif // PTHREAD_RENAME_SELF
+#endif // PTHREAD_RENAME_SELF
return err == 0 ? OK : ERR_INVALID_PARAMETER;
- #endif // PTHREAD_NO_RENAME
+#endif // PTHREAD_NO_RENAME
};
void ThreadPosix::make_default() {
- create_func=create_func_posix;
- get_thread_ID_func=get_thread_ID_func_posix;
- wait_to_finish_func=wait_to_finish_func_posix;
+ create_func = create_func_posix;
+ get_thread_ID_func = get_thread_ID_func_posix;
+ wait_to_finish_func = wait_to_finish_func_posix;
set_name_func = set_name_func_posix;
}
ThreadPosix::ThreadPosix() {
- pthread=0;
+ pthread = 0;
}
-
ThreadPosix::~ThreadPosix() {
-
}
-
#endif
diff --git a/drivers/unix/thread_posix.h b/drivers/unix/thread_posix.h
index cf360e164a..a756ed972c 100644
--- a/drivers/unix/thread_posix.h
+++ b/drivers/unix/thread_posix.h
@@ -35,9 +35,9 @@
#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)
-#include <sys/types.h>
-#include <pthread.h>
#include "os/thread.h"
+#include <pthread.h>
+#include <sys/types.h>
class ThreadPosix : public Thread {
@@ -47,31 +47,26 @@ class ThreadPosix : public Thread {
void *user;
ID id;
- static Thread* create_thread_posix();
-
-
+ static Thread *create_thread_posix();
+
static void *thread_callback(void *userdata);
-
- static Thread* create_func_posix(ThreadCreateCallback p_callback,void *,const Settings&);
+
+ static Thread *create_func_posix(ThreadCreateCallback p_callback, void *, const Settings &);
static ID get_thread_ID_func_posix();
- static void wait_to_finish_func_posix(Thread* p_thread);
+ static void wait_to_finish_func_posix(Thread *p_thread);
- static Error set_name_func_posix(const String& p_name);
+ static Error set_name_func_posix(const String &p_name);
+
+ ThreadPosix();
- ThreadPosix();
public:
-
-
virtual ID get_ID() const;
-
+
static void make_default();
-
-
- ~ThreadPosix();
+ ~ThreadPosix();
};
-
#endif
#endif
diff --git a/drivers/windows/dir_access_windows.cpp b/drivers/windows/dir_access_windows.cpp
index 14742aa420..bb5ab02d8c 100644
--- a/drivers/windows/dir_access_windows.cpp
+++ b/drivers/windows/dir_access_windows.cpp
@@ -32,10 +32,10 @@
#include "os/memory.h"
-#include <windows.h>
-#include <wchar.h>
-#include <stdio.h>
#include "print_string.h"
+#include <stdio.h>
+#include <wchar.h>
+#include <windows.h>
/*
@@ -61,36 +61,32 @@ struct DirAccessWindowsPrivate {
Error DirAccessWindows::list_dir_begin() {
- _cisdir=false;
- _cishidden=false;
+ _cisdir = false;
+ _cishidden = false;
list_dir_end();
- p->h = FindFirstFileExW((current_dir+"\\*").c_str(), FindExInfoStandard, &p->fu, FindExSearchNameMatch, NULL, 0);
-
- return (p->h==INVALID_HANDLE_VALUE) ? ERR_CANT_OPEN : OK;
+ p->h = FindFirstFileExW((current_dir + "\\*").c_str(), FindExInfoStandard, &p->fu, FindExSearchNameMatch, NULL, 0);
+ return (p->h == INVALID_HANDLE_VALUE) ? ERR_CANT_OPEN : OK;
}
-
String DirAccessWindows::get_next() {
- if (p->h==INVALID_HANDLE_VALUE)
+ if (p->h == INVALID_HANDLE_VALUE)
return "";
+ _cisdir = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
+ _cishidden = (p->fu.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
- _cisdir=(p->fu.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
- _cishidden=(p->fu.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN);
-
- String name=p->fu.cFileName;
+ String name = p->fu.cFileName;
if (FindNextFileW(p->h, &p->fu) == 0) {
FindClose(p->h);
- p->h=INVALID_HANDLE_VALUE;
+ p->h = INVALID_HANDLE_VALUE;
}
return name;
-
}
bool DirAccessWindows::current_is_dir() const {
@@ -105,65 +101,60 @@ bool DirAccessWindows::current_is_hidden() const {
void DirAccessWindows::list_dir_end() {
- if (p->h!=INVALID_HANDLE_VALUE) {
+ if (p->h != INVALID_HANDLE_VALUE) {
FindClose(p->h);
- p->h=INVALID_HANDLE_VALUE;
+ p->h = INVALID_HANDLE_VALUE;
}
-
}
int DirAccessWindows::get_drive_count() {
return drive_count;
-
}
String DirAccessWindows::get_drive(int p_drive) {
- if (p_drive<0 || p_drive>=drive_count)
+ if (p_drive < 0 || p_drive >= drive_count)
return "";
- return String::chr(drives[p_drive])+":";
+ return String::chr(drives[p_drive]) + ":";
}
Error DirAccessWindows::change_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
-
- p_dir=fix_path(p_dir);
-
+ p_dir = fix_path(p_dir);
wchar_t real_current_dir_name[2048];
- GetCurrentDirectoryW(2048,real_current_dir_name);
- String prev_dir=real_current_dir_name;
+ GetCurrentDirectoryW(2048, real_current_dir_name);
+ String prev_dir = real_current_dir_name;
SetCurrentDirectoryW(current_dir.c_str());
- bool worked=(SetCurrentDirectoryW(p_dir.c_str())!=0);
+ bool worked = (SetCurrentDirectoryW(p_dir.c_str()) != 0);
String base = _get_root_path();
- if (base!="") {
+ if (base != "") {
- GetCurrentDirectoryW(2048,real_current_dir_name);
+ GetCurrentDirectoryW(2048, real_current_dir_name);
String new_dir;
- new_dir = String(real_current_dir_name).replace("\\","/");
+ new_dir = String(real_current_dir_name).replace("\\", "/");
if (!new_dir.begins_with(base)) {
- worked=false;
+ worked = false;
}
}
if (worked) {
-
- GetCurrentDirectoryW(2048,real_current_dir_name);
- current_dir=real_current_dir_name; // TODO, utf8 parser
- current_dir=current_dir.replace("\\","/");
+ GetCurrentDirectoryW(2048, real_current_dir_name);
+ current_dir = real_current_dir_name; // TODO, utf8 parser
+ current_dir = current_dir.replace("\\", "/");
} //else {
- SetCurrentDirectoryW(prev_dir.c_str());
+ SetCurrentDirectoryW(prev_dir.c_str());
//}
- return worked?OK:ERR_INVALID_PARAMETER;
+ return worked ? OK : ERR_INVALID_PARAMETER;
}
Error DirAccessWindows::make_dir(String p_dir) {
@@ -171,18 +162,18 @@ Error DirAccessWindows::make_dir(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
- p_dir=get_current_dir().plus_file(p_dir);
+ p_dir = get_current_dir().plus_file(p_dir);
- p_dir=fix_path(p_dir);
- p_dir = p_dir.replace("/","\\");
+ p_dir = fix_path(p_dir);
+ p_dir = p_dir.replace("/", "\\");
bool success;
int err;
- p_dir="\\\\?\\"+p_dir; //done according to
-// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx
+ p_dir = "\\\\?\\" + p_dir; //done according to
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363855(v=vs.85).aspx
- success=CreateDirectoryW(p_dir.c_str(), NULL);
+ success = CreateDirectoryW(p_dir.c_str(), NULL);
err = GetLastError();
if (success) {
@@ -196,21 +187,18 @@ Error DirAccessWindows::make_dir(String p_dir) {
return ERR_CANT_CREATE;
}
-
String DirAccessWindows::get_current_dir() {
String base = _get_root_path();
- if (base!="") {
-
+ if (base != "") {
- String bd = current_dir.replace("\\","/").replace_first(base,"");
+ String bd = current_dir.replace("\\", "/").replace_first(base, "");
if (bd.begins_with("/"))
- return _get_root_string()+bd.substr(1,bd.length());
+ return _get_root_string() + bd.substr(1, bd.length());
else
- return _get_root_string()+bd;
+ return _get_root_string() + bd;
} else {
-
}
return current_dir;
@@ -221,9 +209,9 @@ bool DirAccessWindows::file_exists(String p_file) {
GLOBAL_LOCK_FUNCTION
if (!p_file.is_abs_path())
- p_file=get_current_dir().plus_file(p_file);
+ p_file = get_current_dir().plus_file(p_file);
- p_file=fix_path(p_file);
+ p_file = fix_path(p_file);
//p_file.replace("/","\\");
@@ -235,7 +223,7 @@ bool DirAccessWindows::file_exists(String p_file) {
if (INVALID_FILE_ATTRIBUTES == fileAttr)
return false;
- return !(fileAttr&FILE_ATTRIBUTE_DIRECTORY);
+ return !(fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
bool DirAccessWindows::dir_exists(String p_dir) {
@@ -243,34 +231,33 @@ bool DirAccessWindows::dir_exists(String p_dir) {
GLOBAL_LOCK_FUNCTION
if (p_dir.is_rel_path())
- p_dir=get_current_dir().plus_file(p_dir);
+ p_dir = get_current_dir().plus_file(p_dir);
- p_dir=fix_path(p_dir);
+ p_dir = fix_path(p_dir);
//p_dir.replace("/","\\");
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
-
DWORD fileAttr;
fileAttr = GetFileAttributesW(p_dir.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
- return false;
- return (fileAttr&FILE_ATTRIBUTE_DIRECTORY);
+ return false;
+ return (fileAttr & FILE_ATTRIBUTE_DIRECTORY);
}
-Error DirAccessWindows::rename(String p_path,String p_new_path) {
+Error DirAccessWindows::rename(String p_path, String p_new_path) {
if (p_path.is_rel_path())
- p_path=get_current_dir().plus_file(p_path);
+ p_path = get_current_dir().plus_file(p_path);
- p_path=fix_path(p_path);
+ p_path = fix_path(p_path);
if (p_new_path.is_rel_path())
- p_new_path=get_current_dir().plus_file(p_new_path);
+ p_new_path = get_current_dir().plus_file(p_new_path);
- p_new_path=fix_path(p_new_path);
+ p_new_path = fix_path(p_new_path);
if (file_exists(p_new_path)) {
if (remove(p_new_path) != OK) {
@@ -278,18 +265,17 @@ Error DirAccessWindows::rename(String p_path,String p_new_path) {
};
};
- return ::_wrename(p_path.c_str(),p_new_path.c_str())==0?OK:FAILED;
+ return ::_wrename(p_path.c_str(), p_new_path.c_str()) == 0 ? OK : FAILED;
}
-Error DirAccessWindows::remove(String p_path) {
+Error DirAccessWindows::remove(String p_path) {
if (p_path.is_rel_path())
- p_path=get_current_dir().plus_file(p_path);
+ p_path = get_current_dir().plus_file(p_path);
- p_path=fix_path(p_path);
+ p_path = fix_path(p_path);
-
- printf("erasing %s\n",p_path.utf8().get_data());
+ printf("erasing %s\n", p_path.utf8().get_data());
//WIN32_FILE_ATTRIBUTE_DATA fileInfo;
//DWORD fileAttr = GetFileAttributesExW(p_path.c_str(), GetFileExInfoStandard, &fileInfo);
@@ -297,11 +283,11 @@ Error DirAccessWindows::remove(String p_path) {
fileAttr = GetFileAttributesW(p_path.c_str());
if (INVALID_FILE_ATTRIBUTES == fileAttr)
- return FAILED;
- if ((fileAttr&FILE_ATTRIBUTE_DIRECTORY))
- return ::_wrmdir(p_path.c_str())==0?OK:FAILED;
+ return FAILED;
+ if ((fileAttr & FILE_ATTRIBUTE_DIRECTORY))
+ return ::_wrmdir(p_path.c_str()) == 0 ? OK : FAILED;
else
- return ::_wunlink(p_path.c_str())==0?OK:FAILED;
+ return ::_wunlink(p_path.c_str()) == 0 ? OK : FAILED;
}
/*
@@ -331,10 +317,10 @@ FileType DirAccessWindows::get_file_type(const String& p_file) const {
return (attr&FILE_ATTRIBUTE_DIRECTORY)?FILE_TYPE_
}
*/
-size_t DirAccessWindows::get_space_left() {
+size_t DirAccessWindows::get_space_left() {
uint64_t bytes = 0;
- if (!GetDiskFreeSpaceEx(NULL,(PULARGE_INTEGER)&bytes,NULL,NULL))
+ if (!GetDiskFreeSpaceEx(NULL, (PULARGE_INTEGER)&bytes, NULL, NULL))
return 0;
//this is either 0 or a value in bytes.
@@ -343,26 +329,25 @@ size_t DirAccessWindows::get_space_left() {
DirAccessWindows::DirAccessWindows() {
- p = memnew( DirAccessWindowsPrivate );
- p->h=INVALID_HANDLE_VALUE;
- current_dir=".";
+ p = memnew(DirAccessWindowsPrivate);
+ p->h = INVALID_HANDLE_VALUE;
+ current_dir = ".";
- drive_count=0;
+ drive_count = 0;
#ifdef UWP_ENABLED
- Windows::Storage::StorageFolder ^install_folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
+ Windows::Storage::StorageFolder ^ install_folder = Windows::ApplicationModel::Package::Current->InstalledLocation;
change_dir(install_folder->Path->Data());
#else
+ DWORD mask = GetLogicalDrives();
- DWORD mask=GetLogicalDrives();
-
- for (int i=0;i<MAX_DRIVES;i++) {
+ for (int i = 0; i < MAX_DRIVES; i++) {
- if (mask&(1<<i)) { //DRIVE EXISTS
+ if (mask & (1 << i)) { //DRIVE EXISTS
- drives[drive_count]='a'+i;
+ drives[drive_count] = 'a' + i;
drive_count++;
}
}
@@ -371,10 +356,9 @@ DirAccessWindows::DirAccessWindows() {
#endif
}
-
DirAccessWindows::~DirAccessWindows() {
- memdelete( p );
+ memdelete(p);
}
#endif //windows DirAccess support
diff --git a/drivers/windows/dir_access_windows.h b/drivers/windows/dir_access_windows.h
index f4105b7bc9..e0815f2c09 100644
--- a/drivers/windows/dir_access_windows.h
+++ b/drivers/windows/dir_access_windows.h
@@ -29,7 +29,6 @@
#ifndef DIR_ACCESS_WINDOWS_H
#define DIR_ACCESS_WINDOWS_H
-
#ifdef WINDOWS_ENABLED
#include "os/dir_access.h"
@@ -40,14 +39,12 @@
struct DirAccessWindowsPrivate;
-
class DirAccessWindows : public DirAccess {
enum {
- MAX_DRIVES=26
+ MAX_DRIVES = 26
};
-
DirAccessWindowsPrivate *p;
/* Windows stuff */
@@ -56,12 +53,10 @@ class DirAccessWindows : public DirAccess {
String current_dir;
-
bool _cisdir;
bool _cishidden;
public:
-
virtual Error list_dir_begin(); ///< This starts dir listing
virtual String get_next();
virtual bool current_is_dir() const;
@@ -74,7 +69,6 @@ public:
virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success
virtual String get_current_dir(); ///< return current dir location
-
virtual bool file_exists(String p_file);
virtual bool dir_exists(String p_dir);
@@ -88,7 +82,6 @@ public:
DirAccessWindows();
~DirAccessWindows();
-
};
#endif //WINDOWS_ENABLED
diff --git a/drivers/windows/file_access_windows.cpp b/drivers/windows/file_access_windows.cpp
index 894b49231b..0bb6c1d196 100644
--- a/drivers/windows/file_access_windows.cpp
+++ b/drivers/windows/file_access_windows.cpp
@@ -28,20 +28,18 @@
/*************************************************************************/
#ifdef WINDOWS_ENABLED
-#include <windows.h>
-#include "shlwapi.h"
#include "file_access_windows.h"
+#include "shlwapi.h"
+#include <windows.h>
-
-#include <sys/types.h>
+#include "print_string.h"
#include <sys/stat.h>
-#include <wchar.h>
+#include <sys/types.h>
#include <tchar.h>
-#include "print_string.h"
-
+#include <wchar.h>
#ifdef _MSC_VER
- #define S_ISREG(m) ((m)&_S_IFREG)
+#define S_ISREG(m) ((m)&_S_IFREG)
#endif
void FileAccessWindows::check_errors() const {
@@ -50,28 +48,26 @@ void FileAccessWindows::check_errors() const {
if (feof(f)) {
- last_error=ERR_FILE_EOF;
+ last_error = ERR_FILE_EOF;
}
-
}
-Error FileAccessWindows::_open(const String& p_filename, int p_mode_flags) {
+Error FileAccessWindows::_open(const String &p_filename, int p_mode_flags) {
- String filename=fix_path(p_filename);
+ String filename = fix_path(p_filename);
if (f)
close();
+ const wchar_t *mode_string;
- const wchar_t* mode_string;
-
- if (p_mode_flags==READ)
- mode_string=L"rb";
- else if (p_mode_flags==WRITE)
- mode_string=L"wb";
- else if (p_mode_flags==READ_WRITE)
- mode_string=L"rb+";
- else if (p_mode_flags==WRITE_READ)
- mode_string=L"wb+";
+ if (p_mode_flags == READ)
+ mode_string = L"rb";
+ else if (p_mode_flags == WRITE)
+ mode_string = L"wb";
+ else if (p_mode_flags == READ_WRITE)
+ mode_string = L"rb+";
+ else if (p_mode_flags == WRITE_READ)
+ mode_string = L"wb+";
else
return ERR_INVALID_PARAMETER;
@@ -83,27 +79,24 @@ Error FileAccessWindows::_open(const String& p_filename, int p_mode_flags) {
if (!S_ISREG(st.st_mode))
return ERR_FILE_CANT_OPEN;
-
};
- if (is_backup_save_enabled() && p_mode_flags&WRITE && !(p_mode_flags&READ)) {
- save_path=filename;
- filename=filename+".tmp";
+ if (is_backup_save_enabled() && p_mode_flags & WRITE && !(p_mode_flags & READ)) {
+ save_path = filename;
+ filename = filename + ".tmp";
//print_line("saving instead to "+path);
}
- f=_wfopen(filename.c_str(), mode_string);
+ f = _wfopen(filename.c_str(), mode_string);
-
- if (f==NULL) {
- last_error=ERR_FILE_CANT_OPEN;
+ if (f == NULL) {
+ last_error = ERR_FILE_CANT_OPEN;
return ERR_FILE_CANT_OPEN;
} else {
- last_error=OK;
- flags=p_mode_flags;
+ last_error = OK;
+ flags = p_mode_flags;
return OK;
}
-
}
void FileAccessWindows::close() {
@@ -113,14 +106,13 @@ void FileAccessWindows::close() {
fclose(f);
f = NULL;
- if (save_path!="") {
+ if (save_path != "") {
//unlink(save_path.utf8().get_data());
//print_line("renaming..");
//_wunlink(save_path.c_str()); //unlink if exists
//int rename_error = _wrename((save_path+".tmp").c_str(),save_path.c_str());
-
bool rename_error;
#ifdef UWP_ENABLED
@@ -133,53 +125,50 @@ void FileAccessWindows::close() {
if (!PathFileExistsW(save_path.c_str())) {
#endif
//creating new file
- rename_error = _wrename((save_path+".tmp").c_str(),save_path.c_str())!=0;
+ rename_error = _wrename((save_path + ".tmp").c_str(), save_path.c_str()) != 0;
} else {
//atomic replace for existing file
- rename_error = !ReplaceFileW(save_path.c_str(), (save_path+".tmp").c_str(), NULL, 2|4, NULL, NULL);
+ rename_error = !ReplaceFileW(save_path.c_str(), (save_path + ".tmp").c_str(), NULL, 2 | 4, NULL, NULL);
}
if (rename_error && close_fail_notify) {
close_fail_notify(save_path);
}
- save_path="";
- ERR_FAIL_COND( rename_error );
+ save_path = "";
+ ERR_FAIL_COND(rename_error);
}
-
}
bool FileAccessWindows::is_open() const {
- return (f!=NULL);
+ return (f != NULL);
}
void FileAccessWindows::seek(size_t p_position) {
ERR_FAIL_COND(!f);
- last_error=OK;
- if ( fseek(f,p_position,SEEK_SET) )
+ last_error = OK;
+ if (fseek(f, p_position, SEEK_SET))
check_errors();
}
void FileAccessWindows::seek_end(int64_t p_position) {
ERR_FAIL_COND(!f);
- if ( fseek(f,p_position,SEEK_END) )
+ if (fseek(f, p_position, SEEK_END))
check_errors();
}
size_t FileAccessWindows::get_pos() const {
-
- size_t aux_position=0;
- if ( !(aux_position = ftell(f)) ) {
+ size_t aux_position = 0;
+ if (!(aux_position = ftell(f))) {
check_errors();
};
return aux_position;
}
size_t FileAccessWindows::get_len() const {
-
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
size_t pos = get_pos();
- fseek(f,0,SEEK_END);
+ fseek(f, 0, SEEK_END);
int size = get_pos();
fseek(f, pos, SEEK_SET);
@@ -189,14 +178,14 @@ size_t FileAccessWindows::get_len() const {
bool FileAccessWindows::eof_reached() const {
check_errors();
- return last_error==ERR_FILE_EOF;
+ return last_error == ERR_FILE_EOF;
}
uint8_t FileAccessWindows::get_8() const {
- ERR_FAIL_COND_V(!f,0);
+ ERR_FAIL_COND_V(!f, 0);
uint8_t b;
- if (fread(&b,1,1,f) == 0) {
+ if (fread(&b, 1, 1, f) == 0) {
check_errors();
};
@@ -205,13 +194,12 @@ uint8_t FileAccessWindows::get_8() const {
int FileAccessWindows::get_buffer(uint8_t *p_dst, int p_length) const {
- ERR_FAIL_COND_V(!f,-1);
- int read = fread(p_dst, 1,p_length, f);
+ ERR_FAIL_COND_V(!f, -1);
+ int read = fread(p_dst, 1, p_length, f);
check_errors();
return read;
};
-
Error FileAccessWindows::get_error() const {
return last_error;
@@ -220,18 +208,16 @@ Error FileAccessWindows::get_error() const {
void FileAccessWindows::store_8(uint8_t p_dest) {
ERR_FAIL_COND(!f);
- fwrite(&p_dest,1,1,f);
-
+ fwrite(&p_dest, 1, 1, f);
}
-
-bool FileAccessWindows::file_exists(const String& p_name) {
+bool FileAccessWindows::file_exists(const String &p_name) {
FILE *g;
//printf("opening file %s\n", p_fname.c_str());
- String filename=fix_path(p_name);
- g=_wfopen(filename.c_str(),L"rb");
- if (g==NULL) {
+ String filename = fix_path(p_name);
+ g = _wfopen(filename.c_str(), L"rb");
+ if (g == NULL) {
return false;
} else {
@@ -241,11 +227,11 @@ bool FileAccessWindows::file_exists(const String& p_name) {
}
}
-uint64_t FileAccessWindows::_get_modified_time(const String& p_file) {
+uint64_t FileAccessWindows::_get_modified_time(const String &p_file) {
- String file=fix_path(p_file);
- if (file.ends_with("/") && file!="/")
- file=file.substr(0,file.length()-1);
+ String file = fix_path(p_file);
+ if (file.ends_with("/") && file != "/")
+ file = file.substr(0, file.length() - 1);
struct _stat st;
int rv = _wstat(file.c_str(), &st);
@@ -254,25 +240,21 @@ uint64_t FileAccessWindows::_get_modified_time(const String& p_file) {
return st.st_mtime;
} else {
- print_line("no access to "+file );
+ print_line("no access to " + file);
}
-
ERR_FAIL_V(0);
};
-
FileAccessWindows::FileAccessWindows() {
- f=NULL;
- flags=0;
- last_error=OK;
-
+ f = NULL;
+ flags = 0;
+ last_error = OK;
}
FileAccessWindows::~FileAccessWindows() {
close();
-
}
#endif
diff --git a/drivers/windows/file_access_windows.h b/drivers/windows/file_access_windows.h
index 9f06918b72..d64a4b98fc 100644
--- a/drivers/windows/file_access_windows.h
+++ b/drivers/windows/file_access_windows.h
@@ -47,12 +47,12 @@ class FileAccessWindows : public FileAccess {
String save_path;
public:
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -65,15 +65,13 @@ public:
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_name); ///< return true if a file exists
+ virtual bool file_exists(const String &p_name); ///< return true if a file exists
- uint64_t _get_modified_time(const String& p_file);
+ uint64_t _get_modified_time(const String &p_file);
FileAccessWindows();
virtual ~FileAccessWindows();
-
};
-
#endif
#endif
diff --git a/drivers/windows/mutex_windows.cpp b/drivers/windows/mutex_windows.cpp
index 6ae7e52124..bacf89efbb 100644
--- a/drivers/windows/mutex_windows.cpp
+++ b/drivers/windows/mutex_windows.cpp
@@ -31,76 +31,68 @@
#ifdef WINDOWS_ENABLED
-
-
void MutexWindows::lock() {
#ifdef WINDOWS_USE_MUTEX
- WaitForSingleObject(mutex,INFINITE);
+ WaitForSingleObject(mutex, INFINITE);
#else
- EnterCriticalSection( &mutex );
+ EnterCriticalSection(&mutex);
#endif
}
-
void MutexWindows::unlock() {
#ifdef WINDOWS_USE_MUTEX
ReleaseMutex(mutex);
#else
- LeaveCriticalSection( &mutex );
+ LeaveCriticalSection(&mutex);
#endif
}
Error MutexWindows::try_lock() {
#ifdef WINDOWS_USE_MUTEX
- return (WaitForSingleObject(mutex,0)==WAIT_TIMEOUT)?ERR_BUSY:OK;
+ return (WaitForSingleObject(mutex, 0) == WAIT_TIMEOUT) ? ERR_BUSY : OK;
#else
- if (TryEnterCriticalSection( &mutex ))
- return OK;
- else
- return ERR_BUSY;
+ if (TryEnterCriticalSection(&mutex))
+ return OK;
+ else
+ return ERR_BUSY;
#endif
-
}
Mutex *MutexWindows::create_func_windows(bool p_recursive) {
- return memnew( MutexWindows );
+ return memnew(MutexWindows);
}
void MutexWindows::make_default() {
- create_func=create_func_windows;
+ create_func = create_func_windows;
}
MutexWindows::MutexWindows() {
-
+
#ifdef WINDOWS_USE_MUTEX
- mutex = CreateMutex( NULL, FALSE, NULL );
+ mutex = CreateMutex(NULL, FALSE, NULL);
+#else
+#ifdef UWP_ENABLED
+ InitializeCriticalSectionEx(&mutex, 0, 0);
#else
- #ifdef UWP_ENABLED
- InitializeCriticalSectionEx( &mutex, 0, 0 );
- #else
- InitializeCriticalSection( &mutex );
- #endif
+ InitializeCriticalSection(&mutex);
+#endif
#endif
-
}
-
MutexWindows::~MutexWindows() {
#ifdef WINDOWS_USE_MUTEX
- CloseHandle(mutex);
+ CloseHandle(mutex);
#else
- DeleteCriticalSection(&mutex);
+ DeleteCriticalSection(&mutex);
#endif
-
}
-
#endif
diff --git a/drivers/windows/mutex_windows.h b/drivers/windows/mutex_windows.h
index 4202735f2b..0c6cbd472a 100644
--- a/drivers/windows/mutex_windows.h
+++ b/drivers/windows/mutex_windows.h
@@ -31,33 +31,30 @@
#ifdef WINDOWS_ENABLED
-#include <windows.h>
#include "os/mutex.h"
+#include <windows.h>
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class MutexWindows : public Mutex {
#ifdef WINDOWS_USE_MUTEX
- HANDLE mutex;
+ HANDLE mutex;
#else
- CRITICAL_SECTION mutex;
+ CRITICAL_SECTION mutex;
#endif
-
+
static Mutex *create_func_windows(bool p_recursive);
-
-public:
- virtual void lock();
+public:
+ virtual void lock();
virtual void unlock();
- virtual Error try_lock();
-
+ virtual Error try_lock();
static void make_default();
- MutexWindows();
+ MutexWindows();
~MutexWindows();
-
};
#endif
diff --git a/drivers/windows/rw_lock_windows.cpp b/drivers/windows/rw_lock_windows.cpp
index edbd7b6a0f..615bcd22aa 100644
--- a/drivers/windows/rw_lock_windows.cpp
+++ b/drivers/windows/rw_lock_windows.cpp
@@ -30,14 +30,13 @@
#include "rw_lock_windows.h"
-#include "os/memory.h"
#include "error_macros.h"
+#include "os/memory.h"
#include <stdio.h>
void RWLockWindows::read_lock() {
AcquireSRWLockShared(&lock);
-
}
void RWLockWindows::read_unlock() {
@@ -47,18 +46,16 @@ void RWLockWindows::read_unlock() {
Error RWLockWindows::read_try_lock() {
- if (TryAcquireSRWLockShared(&lock)==0) {
+ if (TryAcquireSRWLockShared(&lock) == 0) {
return ERR_BUSY;
} else {
return OK;
}
-
}
void RWLockWindows::write_lock() {
AcquireSRWLockExclusive(&lock);
-
}
void RWLockWindows::write_unlock() {
@@ -67,34 +64,29 @@ void RWLockWindows::write_unlock() {
}
Error RWLockWindows::write_try_lock() {
- if (TryAcquireSRWLockExclusive(&lock)==0) {
+ if (TryAcquireSRWLockExclusive(&lock) == 0) {
return ERR_BUSY;
} else {
return OK;
}
}
-
RWLock *RWLockWindows::create_func_windows() {
- return memnew( RWLockWindows );
+ return memnew(RWLockWindows);
}
void RWLockWindows::make_default() {
- create_func=create_func_windows;
+ create_func = create_func_windows;
}
-
RWLockWindows::RWLockWindows() {
InitializeSRWLock(&lock);
}
-
RWLockWindows::~RWLockWindows() {
-
-
}
#endif
diff --git a/drivers/windows/rw_lock_windows.h b/drivers/windows/rw_lock_windows.h
index 059704e5c7..e4b5367c2f 100644
--- a/drivers/windows/rw_lock_windows.h
+++ b/drivers/windows/rw_lock_windows.h
@@ -31,18 +31,16 @@
#if defined(WINDOWS_ENABLED)
-#include <windows.h>
#include "os/rw_lock.h"
+#include <windows.h>
class RWLockWindows : public RWLock {
-
SRWLOCK lock;
static RWLock *create_func_windows();
public:
-
virtual void read_lock();
virtual void read_unlock();
virtual Error read_try_lock();
@@ -56,10 +54,8 @@ public:
RWLockWindows();
~RWLockWindows();
-
};
#endif
-
#endif // RWLOCKWINDOWS_H
diff --git a/drivers/windows/semaphore_windows.cpp b/drivers/windows/semaphore_windows.cpp
index cdd1a7b888..b1c9ee0182 100644
--- a/drivers/windows/semaphore_windows.cpp
+++ b/drivers/windows/semaphore_windows.cpp
@@ -34,19 +34,19 @@
Error SemaphoreWindows::wait() {
- WaitForSingleObjectEx(semaphore,INFINITE, false);
+ WaitForSingleObjectEx(semaphore, INFINITE, false);
return OK;
}
Error SemaphoreWindows::post() {
- ReleaseSemaphore(semaphore,1,NULL);
+ ReleaseSemaphore(semaphore, 1, NULL);
return OK;
}
int SemaphoreWindows::get() const {
long previous;
switch (WaitForSingleObjectEx(semaphore, 0, false)) {
case WAIT_OBJECT_0: {
- ERR_FAIL_COND_V(!ReleaseSemaphore(semaphore, 1, &previous),-1);
+ ERR_FAIL_COND_V(!ReleaseSemaphore(semaphore, 1, &previous), -1);
return previous + 1;
} break;
case WAIT_TIMEOUT: {
@@ -58,41 +58,38 @@ int SemaphoreWindows::get() const {
ERR_FAIL_V(-1);
}
-
Semaphore *SemaphoreWindows::create_semaphore_windows() {
- return memnew( SemaphoreWindows );
+ return memnew(SemaphoreWindows);
}
void SemaphoreWindows::make_default() {
- create_func=create_semaphore_windows;
+ create_func = create_semaphore_windows;
}
SemaphoreWindows::SemaphoreWindows() {
#ifdef UWP_ENABLED
- semaphore=CreateSemaphoreEx(
- NULL,
- 0,
- 0xFFFFFFF, //wathever
- NULL,
- 0,
- SEMAPHORE_ALL_ACCESS);
+ semaphore = CreateSemaphoreEx(
+ NULL,
+ 0,
+ 0xFFFFFFF, //wathever
+ NULL,
+ 0,
+ SEMAPHORE_ALL_ACCESS);
#else
- semaphore=CreateSemaphore(
- NULL,
- 0,
- 0xFFFFFFF, //wathever
- NULL);
+ semaphore = CreateSemaphore(
+ NULL,
+ 0,
+ 0xFFFFFFF, //wathever
+ NULL);
#endif
}
-
SemaphoreWindows::~SemaphoreWindows() {
CloseHandle(semaphore);
}
-
#endif
diff --git a/drivers/windows/semaphore_windows.h b/drivers/windows/semaphore_windows.h
index 564087a691..5594cb0c58 100644
--- a/drivers/windows/semaphore_windows.h
+++ b/drivers/windows/semaphore_windows.h
@@ -29,8 +29,6 @@
#ifndef SEMAPHORE_WINDOWS_H
#define SEMAPHORE_WINDOWS_H
-
-
#include "os/semaphore.h"
#ifdef WINDOWS_ENABLED
@@ -41,21 +39,19 @@
*/
class SemaphoreWindows : public Semaphore {
- mutable HANDLE semaphore;
+ mutable HANDLE semaphore;
static Semaphore *create_semaphore_windows();
public:
-
virtual Error wait();
- virtual Error post();
+ virtual Error post();
virtual int get() const;
static void make_default();
SemaphoreWindows();
-
- ~SemaphoreWindows();
+ ~SemaphoreWindows();
};
#endif
diff --git a/drivers/windows/shell_windows.cpp b/drivers/windows/shell_windows.cpp
index a96bc6a7db..715d886ed2 100644
--- a/drivers/windows/shell_windows.cpp
+++ b/drivers/windows/shell_windows.cpp
@@ -52,17 +52,12 @@
void ShellWindows::execute(String p_path) {
ShellExecuteW(NULL, L"open", p_path.c_str(), NULL, NULL, SW_SHOWNORMAL);
-
}
-
-ShellWindows::ShellWindows()
-{
+ShellWindows::ShellWindows() {
}
-
-ShellWindows::~ShellWindows()
-{
+ShellWindows::~ShellWindows() {
}
#endif
diff --git a/drivers/windows/shell_windows.h b/drivers/windows/shell_windows.h
index 92203df98a..e0baf3e765 100644
--- a/drivers/windows/shell_windows.h
+++ b/drivers/windows/shell_windows.h
@@ -37,13 +37,11 @@
*/
class ShellWindows : public Shell {
public:
-
virtual void execute(String p_path);
ShellWindows();
-
- ~ShellWindows();
+ ~ShellWindows();
};
#endif
diff --git a/drivers/windows/thread_windows.cpp b/drivers/windows/thread_windows.cpp
index dbe2f93fd4..e6143b4af3 100644
--- a/drivers/windows/thread_windows.cpp
+++ b/drivers/windows/thread_windows.cpp
@@ -32,24 +32,23 @@
#include "os/memory.h"
-
Thread::ID ThreadWindows::get_ID() const {
- return id;
+ return id;
}
-Thread* ThreadWindows::create_thread_windows() {
+Thread *ThreadWindows::create_thread_windows() {
- return memnew( ThreadWindows );
+ return memnew(ThreadWindows);
}
-DWORD ThreadWindows::thread_callback( LPVOID userdata ) {
+DWORD ThreadWindows::thread_callback(LPVOID userdata) {
- ThreadWindows *t=reinterpret_cast<ThreadWindows*>(userdata);
+ ThreadWindows *t = reinterpret_cast<ThreadWindows *>(userdata);
ScriptServer::thread_enter(); //scripts may need to attach a stack
- t->id=(ID)GetCurrentThreadId(); // must implement
+ t->id = (ID)GetCurrentThreadId(); // must implement
t->callback(t->user);
ScriptServer::thread_exit();
@@ -57,53 +56,47 @@ DWORD ThreadWindows::thread_callback( LPVOID userdata ) {
return 0;
}
-Thread* ThreadWindows::create_func_windows(ThreadCreateCallback p_callback,void *p_user,const Settings&) {
-
- ThreadWindows *tr= memnew(ThreadWindows);
- tr->callback=p_callback;
- tr->user=p_user;
- tr->handle=CreateThread(
- NULL, // default security attributes
- 0, // use default stack size
- thread_callback, // thread function name
- tr, // argument to thread function
- 0, // use default creation flags
- NULL); // returns the thread identifier
-
+Thread *ThreadWindows::create_func_windows(ThreadCreateCallback p_callback, void *p_user, const Settings &) {
+
+ ThreadWindows *tr = memnew(ThreadWindows);
+ tr->callback = p_callback;
+ tr->user = p_user;
+ tr->handle = CreateThread(
+ NULL, // default security attributes
+ 0, // use default stack size
+ thread_callback, // thread function name
+ tr, // argument to thread function
+ 0, // use default creation flags
+ NULL); // returns the thread identifier
+
return tr;
}
Thread::ID ThreadWindows::get_thread_ID_func_windows() {
return (ID)GetCurrentThreadId(); //must implement
}
-void ThreadWindows::wait_to_finish_func_windows(Thread* p_thread) {
+void ThreadWindows::wait_to_finish_func_windows(Thread *p_thread) {
-
- ThreadWindows *tp=static_cast<ThreadWindows*>(p_thread);
+ ThreadWindows *tp = static_cast<ThreadWindows *>(p_thread);
ERR_FAIL_COND(!tp);
- WaitForSingleObject( tp->handle, INFINITE );
+ WaitForSingleObject(tp->handle, INFINITE);
CloseHandle(tp->handle);
- //`memdelete(tp);
+ //`memdelete(tp);
}
-
void ThreadWindows::make_default() {
- create_func=create_func_windows;
- get_thread_ID_func=get_thread_ID_func_windows;
- wait_to_finish_func=wait_to_finish_func_windows;
-
+ create_func = create_func_windows;
+ get_thread_ID_func = get_thread_ID_func_windows;
+ wait_to_finish_func = wait_to_finish_func_windows;
}
ThreadWindows::ThreadWindows() {
- handle=NULL;
+ handle = NULL;
}
-
ThreadWindows::~ThreadWindows() {
-
}
-
#endif
diff --git a/drivers/windows/thread_windows.h b/drivers/windows/thread_windows.h
index c8f395e062..5b2c076c7f 100644
--- a/drivers/windows/thread_windows.h
+++ b/drivers/windows/thread_windows.h
@@ -41,36 +41,29 @@
class ThreadWindows : public Thread {
-
ThreadCreateCallback callback;
void *user;
ID id;
HANDLE handle;
- static Thread* create_thread_windows();
-
-
-
- static DWORD WINAPI thread_callback( LPVOID userdata );
-
- static Thread* create_func_windows(ThreadCreateCallback p_callback,void *,const Settings&);
+ static Thread *create_thread_windows();
+
+ static DWORD WINAPI thread_callback(LPVOID userdata);
+
+ static Thread *create_func_windows(ThreadCreateCallback p_callback, void *, const Settings &);
static ID get_thread_ID_func_windows();
- static void wait_to_finish_func_windows(Thread* p_thread);
-
- ThreadWindows();
+ static void wait_to_finish_func_windows(Thread *p_thread);
+
+ ThreadWindows();
+
public:
-
-
virtual ID get_ID() const;
-
+
static void make_default();
-
-
- ~ThreadWindows();
+ ~ThreadWindows();
};
-
#endif
#endif
diff --git a/drivers/xaudio2/audio_driver_xaudio2.cpp b/drivers/xaudio2/audio_driver_xaudio2.cpp
index cd61fefd91..546bbff1ba 100644
--- a/drivers/xaudio2/audio_driver_xaudio2.cpp
+++ b/drivers/xaudio2/audio_driver_xaudio2.cpp
@@ -31,8 +31,7 @@
#include "global_config.h"
#include "os/os.h"
-const char * AudioDriverXAudio2::get_name() const
-{
+const char *AudioDriverXAudio2::get_name() const {
return "XAudio2";
}
@@ -44,7 +43,6 @@ Error AudioDriverXAudio2::init() {
pcm_open = false;
samples_in = NULL;
-
mix_rate = 48000;
// FIXME: speaker_mode seems unused in the Xaudio2 driver so far
speaker_mode = SPEAKER_MODE_STEREO;
@@ -53,11 +51,11 @@ Error AudioDriverXAudio2::init() {
int latency = GLOBAL_DEF("audio/output_latency", 25);
buffer_size = nearest_power_of_2(latency * mix_rate / 1000);
- samples_in = memnew_arr(int32_t, buffer_size*channels);
+ samples_in = memnew_arr(int32_t, buffer_size * channels);
for (int i = 0; i < AUDIO_BUFFERS; i++) {
- samples_out[i] = memnew_arr(int16_t, buffer_size*channels);
+ samples_out[i] = memnew_arr(int16_t, buffer_size * channels);
xaudio_buffer[i].AudioBytes = buffer_size * channels * sizeof(int16_t);
- xaudio_buffer[i].pAudioData = (const BYTE*)(samples_out[i]);
+ xaudio_buffer[i].pAudioData = (const BYTE *)(samples_out[i]);
xaudio_buffer[i].Flags = 0;
}
@@ -93,15 +91,14 @@ Error AudioDriverXAudio2::init() {
return OK;
};
-void AudioDriverXAudio2::thread_func(void* p_udata) {
+void AudioDriverXAudio2::thread_func(void *p_udata) {
- AudioDriverXAudio2* ad = (AudioDriverXAudio2*)p_udata;
+ AudioDriverXAudio2 *ad = (AudioDriverXAudio2 *)p_udata;
uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate)) * 1000000;
while (!ad->exit_thread) {
-
if (!ad->active) {
for (int i = 0; i < AUDIO_BUFFERS; i++) {
@@ -116,30 +113,27 @@ void AudioDriverXAudio2::thread_func(void* p_udata) {
ad->unlock();
- for (unsigned int i = 0;i < ad->buffer_size*ad->channels;i++) {
+ for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
ad->samples_out[ad->current_buffer][i] = ad->samples_in[i] >> 16;
}
ad->xaudio_buffer[ad->current_buffer].Flags = 0;
ad->xaudio_buffer[ad->current_buffer].AudioBytes = ad->buffer_size * ad->channels * sizeof(int16_t);
- ad->xaudio_buffer[ad->current_buffer].pAudioData = (const BYTE*)(ad->samples_out[ad->current_buffer]);
+ ad->xaudio_buffer[ad->current_buffer].pAudioData = (const BYTE *)(ad->samples_out[ad->current_buffer]);
ad->xaudio_buffer[ad->current_buffer].PlayBegin = 0;
ad->source_voice->SubmitSourceBuffer(&(ad->xaudio_buffer[ad->current_buffer]));
ad->current_buffer = (ad->current_buffer + 1) % AUDIO_BUFFERS;
XAUDIO2_VOICE_STATE state;
- while (ad->source_voice->GetState(&state), state.BuffersQueued > AUDIO_BUFFERS - 1)
- {
+ while (ad->source_voice->GetState(&state), state.BuffersQueued > AUDIO_BUFFERS - 1) {
WaitForSingleObject(ad->voice_callback.buffer_end_event, INFINITE);
}
}
-
};
ad->thread_exited = true;
-
};
void AudioDriverXAudio2::start() {
@@ -228,9 +222,6 @@ AudioDriverXAudio2::AudioDriverXAudio2() {
current_buffer = 0;
};
-AudioDriverXAudio2::~AudioDriverXAudio2() {
-
+AudioDriverXAudio2::~AudioDriverXAudio2(){
};
-
-
diff --git a/drivers/xaudio2/audio_driver_xaudio2.h b/drivers/xaudio2/audio_driver_xaudio2.h
index afafb84c23..9a37ba7a7b 100644
--- a/drivers/xaudio2/audio_driver_xaudio2.h
+++ b/drivers/xaudio2/audio_driver_xaudio2.h
@@ -29,15 +29,15 @@
#ifndef AUDIO_DRIVER_XAUDIO2_H
#define AUDIO_DRIVER_XAUDIO2_H
-#include "servers/audio_server.h"
-#include "core/os/thread.h"
#include "core/os/mutex.h"
+#include "core/os/thread.h"
+#include "servers/audio_server.h"
-#include <windows.h>
-#include <mmsystem.h>
#include <mmreg.h>
-#include <xaudio2.h>
+#include <mmsystem.h>
+#include <windows.h>
#include <wrl/client.h>
+#include <xaudio2.h>
class AudioDriverXAudio2 : public AudioDriver {
@@ -48,26 +48,28 @@ class AudioDriverXAudio2 : public AudioDriver {
struct XAudio2DriverVoiceCallback : public IXAudio2VoiceCallback {
HANDLE buffer_end_event;
- XAudio2DriverVoiceCallback() : buffer_end_event(CreateEvent(NULL, FALSE, FALSE, NULL)) {}
- void STDMETHODCALLTYPE OnBufferEnd(void* pBufferContext) { /*print_line("buffer ended");*/ SetEvent(buffer_end_event); }
+ XAudio2DriverVoiceCallback()
+ : buffer_end_event(CreateEvent(NULL, FALSE, FALSE, NULL)) {}
+ void STDMETHODCALLTYPE OnBufferEnd(void *pBufferContext) { /*print_line("buffer ended");*/
+ SetEvent(buffer_end_event);
+ }
//Unused methods are stubs
void STDMETHODCALLTYPE OnStreamEnd() {}
void STDMETHODCALLTYPE OnVoiceProcessingPassEnd() {}
void STDMETHODCALLTYPE OnVoiceProcessingPassStart(UINT32 SamplesRequired) {}
- void STDMETHODCALLTYPE OnBufferStart(void * pBufferContext) {}
- void STDMETHODCALLTYPE OnLoopEnd(void * pBufferContext) {}
- void STDMETHODCALLTYPE OnVoiceError(void * pBufferContext, HRESULT Error) {}
-
+ void STDMETHODCALLTYPE OnBufferStart(void *pBufferContext) {}
+ void STDMETHODCALLTYPE OnLoopEnd(void *pBufferContext) {}
+ void STDMETHODCALLTYPE OnVoiceError(void *pBufferContext, HRESULT Error) {}
};
- Thread* thread;
- Mutex* mutex;
+ Thread *thread;
+ Mutex *mutex;
- int32_t* samples_in;
- int16_t* samples_out[AUDIO_BUFFERS];
+ int32_t *samples_in;
+ int16_t *samples_out[AUDIO_BUFFERS];
- static void thread_func(void* p_udata);
+ static void thread_func(void *p_udata);
int buffer_size;
unsigned int mix_rate;
@@ -83,14 +85,13 @@ class AudioDriverXAudio2 : public AudioDriver {
WAVEFORMATEX wave_format;
Microsoft::WRL::ComPtr<IXAudio2> xaudio;
int current_buffer;
- IXAudio2MasteringVoice* mastering_voice;
+ IXAudio2MasteringVoice *mastering_voice;
XAUDIO2_BUFFER xaudio_buffer[AUDIO_BUFFERS];
- IXAudio2SourceVoice* source_voice;
+ IXAudio2SourceVoice *source_voice;
XAudio2DriverVoiceCallback voice_callback;
public:
-
- const char* get_name() const;
+ const char *get_name() const;
virtual Error init();
virtual void start();
diff --git a/editor/animation_editor.cpp b/editor/animation_editor.cpp
index d65f229fca..1a65014634 100644
--- a/editor/animation_editor.cpp
+++ b/editor/animation_editor.cpp
@@ -28,14 +28,14 @@
/*************************************************************************/
#include "animation_editor.h"
+#include "editor/plugins/animation_player_editor_plugin.h"
+#include "editor_node.h"
#include "editor_settings.h"
+#include "io/resource_saver.h"
#include "os/keyboard.h"
#include "os/os.h"
-#include "io/resource_saver.h"
#include "pair.h"
#include "scene/gui/separator.h"
-#include "editor_node.h"
-#include "editor/plugins/animation_player_editor_plugin.h"
#include "scene/main/viewport.h"
/* Missing to fix:
@@ -47,177 +47,174 @@
*when create track do undo/redo
*/
-
class AnimationCurveEdit : public Control {
- GDCLASS( AnimationCurveEdit, Control );
+ GDCLASS(AnimationCurveEdit, Control);
+
public:
enum Mode {
MODE_DISABLED,
MODE_SINGLE,
MODE_MULTIPLE
};
-private:
+private:
Set<float> multiples;
float transition;
Mode mode;
void _notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
-
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
Size2 s = get_size();
- Rect2 r(Point2(),s);
+ Rect2 r(Point2(), s);
//r=r.grow(3);
- Ref<StyleBox> sb = get_stylebox("normal","LineEdit");
- sb->draw(ci,r);
- r.size-=sb->get_minimum_size();
- r.pos+=sb->get_offset();
+ Ref<StyleBox> sb = get_stylebox("normal", "LineEdit");
+ sb->draw(ci, r);
+ r.size -= sb->get_minimum_size();
+ r.pos += sb->get_offset();
//VisualServer::get_singleton()->canvas_item_add
- Ref<Font> f = get_font("font","Label");
- r=r.grow(-2);
- Color color = get_color("font_color","Label");
+ Ref<Font> f = get_font("font", "Label");
+ r = r.grow(-2);
+ Color color = get_color("font_color", "Label");
int points = 48;
- if (mode==MODE_MULTIPLE) {
+ if (mode == MODE_MULTIPLE) {
- Color mcolor=color;
- mcolor.a*=0.3;
+ Color mcolor = color;
+ mcolor.a *= 0.3;
- Set<float>::Element *E=multiples.front();
- for(int j=0;j<16;j++) {
+ Set<float>::Element *E = multiples.front();
+ for (int j = 0; j < 16; j++) {
if (!E)
break;
- float prev=1.0;
- float exp=E->get();
- bool flip=false;//hint_text=="attenuation";
+ float prev = 1.0;
+ float exp = E->get();
+ bool flip = false; //hint_text=="attenuation";
+ for (int i = 1; i <= points; i++) {
- for(int i=1;i<=points;i++) {
+ float ifl = i / float(points);
+ float iflp = (i - 1) / float(points);
- float ifl = i/float(points);
- float iflp = (i-1)/float(points);
-
- float h = 1.0-Math::ease(ifl,exp);
+ float h = 1.0 - Math::ease(ifl, exp);
if (flip) {
- ifl=1.0-ifl;
- iflp=1.0-iflp;
+ ifl = 1.0 - ifl;
+ iflp = 1.0 - iflp;
}
- VisualServer::get_singleton()->canvas_item_add_line(ci,r.pos+Point2(iflp*r.size.width,prev*r.size.height),r.pos+Point2(ifl*r.size.width,h*r.size.height),mcolor);
- prev=h;
+ VisualServer::get_singleton()->canvas_item_add_line(ci, r.pos + Point2(iflp * r.size.width, prev * r.size.height), r.pos + Point2(ifl * r.size.width, h * r.size.height), mcolor);
+ prev = h;
}
- E=E->next();
+ E = E->next();
}
}
- float exp=transition;
- if (mode!=MODE_DISABLED) {
-
-
- float prev=1.0;
+ float exp = transition;
+ if (mode != MODE_DISABLED) {
- bool flip=false;//hint_text=="attenuation";
+ float prev = 1.0;
+ bool flip = false; //hint_text=="attenuation";
- for(int i=1;i<=points;i++) {
+ for (int i = 1; i <= points; i++) {
- float ifl = i/float(points);
- float iflp = (i-1)/float(points);
+ float ifl = i / float(points);
+ float iflp = (i - 1) / float(points);
- float h = 1.0-Math::ease(ifl,exp);
+ float h = 1.0 - Math::ease(ifl, exp);
if (flip) {
- ifl=1.0-ifl;
- iflp=1.0-iflp;
+ ifl = 1.0 - ifl;
+ iflp = 1.0 - iflp;
}
- VisualServer::get_singleton()->canvas_item_add_line(ci,r.pos+Point2(iflp*r.size.width,prev*r.size.height),r.pos+Point2(ifl*r.size.width,h*r.size.height),color);
- prev=h;
+ VisualServer::get_singleton()->canvas_item_add_line(ci, r.pos + Point2(iflp * r.size.width, prev * r.size.height), r.pos + Point2(ifl * r.size.width, h * r.size.height), color);
+ prev = h;
}
}
- String txt=String::num(exp,2);
- if (mode==MODE_DISABLED) {
- txt=TTR("Disabled");
- } else if (mode==MODE_MULTIPLE) {
- txt+=" - "+TTR("All Selection");
+ String txt = String::num(exp, 2);
+ if (mode == MODE_DISABLED) {
+ txt = TTR("Disabled");
+ } else if (mode == MODE_MULTIPLE) {
+ txt += " - " + TTR("All Selection");
}
- f->draw(ci,Point2(10,10+f->get_ascent()),txt,color);
-
+ f->draw(ci, Point2(10, 10 + f->get_ascent()), txt, color);
}
}
- void _gui_input(const InputEvent& p_ev) {
- if (p_ev.type==InputEvent::MOUSE_MOTION && p_ev.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
+ void _gui_input(const InputEvent &p_ev) {
+ if (p_ev.type == InputEvent::MOUSE_MOTION && p_ev.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
- if (mode==MODE_DISABLED)
+ if (mode == MODE_DISABLED)
return;
float rel = p_ev.mouse_motion.relative_x;
- if (rel==0)
- return;
+ if (rel == 0)
+ return;
- bool flip=false;
+ bool flip = false;
if (flip)
- rel=-rel;
+ rel = -rel;
float val = transition;
- if (val==0)
+ if (val == 0)
return;
bool sg = val < 0;
val = Math::absf(val);
- val = Math::log(val)/Math::log((float)2.0);
+ val = Math::log(val) / Math::log((float)2.0);
//logspace
- val+=rel*0.05;
+ val += rel * 0.05;
//
- val = Math::pow((float)2.0,val);
+ val = Math::pow((float)2.0, val);
if (sg)
- val=-val;
+ val = -val;
- transition=val;
+ transition = val;
update();
//emit_signal("variant_changed");
- emit_signal("transition_changed",transition);
+ emit_signal("transition_changed", transition);
}
}
public:
-
static void _bind_methods() {
//ClassDB::bind_method("_update_obj",&AnimationKeyEdit::_update_obj);
- ClassDB::bind_method("_gui_input",&AnimationCurveEdit::_gui_input);
+ ClassDB::bind_method("_gui_input", &AnimationCurveEdit::_gui_input);
ADD_SIGNAL(MethodInfo("transition_changed"));
}
void set_mode(Mode p_mode) {
- mode=p_mode;
+ mode = p_mode;
update();
}
- void clear_multiples() { multiples.clear(); update();}
+ void clear_multiples() {
+ multiples.clear();
+ update();
+ }
void set_multiple(float p_transition) {
multiples.insert(p_transition);
}
void set_transition(float p_transition) {
- transition=p_transition;
+ transition = p_transition;
update();
}
@@ -226,341 +223,318 @@ public:
}
void force_transition(float p_value) {
- if (mode==MODE_DISABLED)
+ if (mode == MODE_DISABLED)
return;
- transition=p_value;
- emit_signal("transition_changed",p_value);
+ transition = p_value;
+ emit_signal("transition_changed", p_value);
update();
}
AnimationCurveEdit() {
- transition=1.0;
+ transition = 1.0;
set_default_cursor_shape(CURSOR_HSPLIT);
- mode=MODE_DISABLED;
+ mode = MODE_DISABLED;
}
-
};
class AnimationKeyEdit : public Object {
- GDCLASS(AnimationKeyEdit,Object);
+ GDCLASS(AnimationKeyEdit, Object);
+
public:
bool setting;
bool hidden;
static void _bind_methods() {
- ClassDB::bind_method("_update_obj",&AnimationKeyEdit::_update_obj);
- ClassDB::bind_method("_key_ofs_changed",&AnimationKeyEdit::_key_ofs_changed);
+ ClassDB::bind_method("_update_obj", &AnimationKeyEdit::_update_obj);
+ ClassDB::bind_method("_key_ofs_changed", &AnimationKeyEdit::_key_ofs_changed);
}
//PopupDialog *ke_dialog;
void _fix_node_path(Variant &value) {
+ NodePath np = value;
- NodePath np=value;
-
- if (np==NodePath())
+ if (np == NodePath())
return;
- Node* root = EditorNode::get_singleton()->get_tree()->get_root();
+ Node *root = EditorNode::get_singleton()->get_tree()->get_root();
- Node* np_node = root->get_node(np);
+ Node *np_node = root->get_node(np);
ERR_FAIL_COND(!np_node);
- Node* edited_node = root->get_node(base);
+ Node *edited_node = root->get_node(base);
ERR_FAIL_COND(!edited_node);
-
-
value = edited_node->get_path_to(np_node);
}
-
void _update_obj(const Ref<Animation> &p_anim) {
if (setting)
return;
if (hidden)
return;
- if (!(animation==p_anim))
+ if (!(animation == p_anim))
return;
notify_change();
}
- void _key_ofs_changed(const Ref<Animation> &p_anim,float from, float to) {
+ void _key_ofs_changed(const Ref<Animation> &p_anim, float from, float to) {
if (hidden)
return;
- if (!(animation==p_anim))
+ if (!(animation == p_anim))
return;
- if (from!=key_ofs)
+ if (from != key_ofs)
return;
- key_ofs=to;
+ key_ofs = to;
if (setting)
return;
notify_change();
}
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
- int key = animation->track_find_key(track,key_ofs,true);
- ERR_FAIL_COND_V(key==-1,false);
+ int key = animation->track_find_key(track, key_ofs, true);
+ ERR_FAIL_COND_V(key == -1, false);
- String name=p_name;
- if (name=="time") {
+ String name = p_name;
+ if (name == "time") {
float new_time = p_value;
- if (new_time==key_ofs)
+ if (new_time == key_ofs)
return true;
- int existing = animation->track_find_key(track,new_time,true);
-
- setting=true;
- undo_redo->create_action(TTR("Move Add Key"),UndoRedo::MERGE_ENDS);
+ int existing = animation->track_find_key(track, new_time, true);
- Variant val = animation->track_get_key_value(track,key);
- float trans = animation->track_get_key_transition(track,key);
+ setting = true;
+ undo_redo->create_action(TTR("Move Add Key"), UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(animation.ptr(),"track_remove_key",track,key);
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",track,new_time,val,trans);
- undo_redo->add_do_method(this,"_key_ofs_changed",animation,key_ofs,new_time);
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",track,new_time);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",track,key_ofs,val,trans);
- undo_redo->add_undo_method(this,"_key_ofs_changed",animation,new_time,key_ofs);
+ Variant val = animation->track_get_key_value(track, key);
+ float trans = animation->track_get_key_transition(track, key);
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key", track, key);
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", track, new_time, val, trans);
+ undo_redo->add_do_method(this, "_key_ofs_changed", animation, key_ofs, new_time);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", track, new_time);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, key_ofs, val, trans);
+ undo_redo->add_undo_method(this, "_key_ofs_changed", animation, new_time, key_ofs);
- if (existing!=-1) {
- Variant v = animation->track_get_key_value(track,existing);
- float trans = animation->track_get_key_transition(track,existing);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",track,new_time,v,trans);
+ if (existing != -1) {
+ Variant v = animation->track_get_key_value(track, existing);
+ float trans = animation->track_get_key_transition(track, existing);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", track, new_time, v, trans);
}
undo_redo->commit_action();
- setting=false;
+ setting = false;
return true;
- } else if (name=="easing") {
+ } else if (name == "easing") {
float val = p_value;
- float prev_val = animation->track_get_key_transition(track,key);
- setting=true;
- undo_redo->create_action(TTR("Anim Change Transition"),UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(animation.ptr(),"track_set_key_transition",track,key,val);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_transition",track,key,prev_val);
- undo_redo->add_do_method(this,"_update_obj",animation);
- undo_redo->add_undo_method(this,"_update_obj",animation);
+ float prev_val = animation->track_get_key_transition(track, key);
+ setting = true;
+ undo_redo->create_action(TTR("Anim Change Transition"), UndoRedo::MERGE_ENDS);
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", track, key, val);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", track, key, prev_val);
+ undo_redo->add_do_method(this, "_update_obj", animation);
+ undo_redo->add_undo_method(this, "_update_obj", animation);
undo_redo->commit_action();
- setting=false;
+ setting = false;
return true;
}
-
-
- switch(animation->track_get_type(track)) {
-
+ switch (animation->track_get_type(track)) {
case Animation::TYPE_TRANSFORM: {
- Dictionary d_old = animation->track_get_key_value(track,key);
+ Dictionary d_old = animation->track_get_key_value(track, key);
Dictionary d_new = d_old;
- d_new[p_name]=p_value;
- setting=true;
+ d_new[p_name] = p_value;
+ setting = true;
undo_redo->create_action(TTR("Anim Change Transform"));
- undo_redo->add_do_method(animation.ptr(),"track_set_key_value",track,key,d_new);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_value",track,key,d_old);
- undo_redo->add_do_method(this,"_update_obj",animation);
- undo_redo->add_undo_method(this,"_update_obj",animation);
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old);
+ undo_redo->add_do_method(this, "_update_obj", animation);
+ undo_redo->add_undo_method(this, "_update_obj", animation);
undo_redo->commit_action();
- setting=false;
+ setting = false;
return true;
} break;
case Animation::TYPE_VALUE: {
- if (name=="value") {
+ if (name == "value") {
Variant value = p_value;
- if (value.get_type()==Variant::NODE_PATH) {
+ if (value.get_type() == Variant::NODE_PATH) {
_fix_node_path(value);
}
- setting=true;
- undo_redo->create_action(TTR("Anim Change Value"),UndoRedo::MERGE_ENDS);
- Variant prev = animation->track_get_key_value(track,key);
- undo_redo->add_do_method(animation.ptr(),"track_set_key_value",track,key,value);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_value",track,key,prev);
- undo_redo->add_do_method(this,"_update_obj",animation);
- undo_redo->add_undo_method(this,"_update_obj",animation);
+ setting = true;
+ undo_redo->create_action(TTR("Anim Change Value"), UndoRedo::MERGE_ENDS);
+ Variant prev = animation->track_get_key_value(track, key);
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, value);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, prev);
+ undo_redo->add_do_method(this, "_update_obj", animation);
+ undo_redo->add_undo_method(this, "_update_obj", animation);
undo_redo->commit_action();
- setting=false;
+ setting = false;
return true;
}
-
-
} break;
case Animation::TYPE_METHOD: {
- Dictionary d_old = animation->track_get_key_value(track,key);
+ Dictionary d_old = animation->track_get_key_value(track, key);
Dictionary d_new = d_old;
- bool change_notify_deserved=false;
- bool mergeable=false;
+ bool change_notify_deserved = false;
+ bool mergeable = false;
- if (name=="name") {
-
- d_new["method"]=p_value;
+ if (name == "name") {
+ d_new["method"] = p_value;
}
- if (name=="arg_count") {
+ if (name == "arg_count") {
Vector<Variant> args = d_old["args"];
args.resize(p_value);
- d_new["args"]=args;
- change_notify_deserved=true;
+ d_new["args"] = args;
+ change_notify_deserved = true;
}
if (name.begins_with("args/")) {
-
Vector<Variant> args = d_old["args"];
- int idx = name.get_slice("/",1).to_int();
- ERR_FAIL_INDEX_V(idx,args.size(),false);
+ int idx = name.get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, args.size(), false);
- String what = name.get_slice("/",2);
- if (what=="type") {
+ String what = name.get_slice("/", 2);
+ if (what == "type") {
Variant::Type t = Variant::Type(int(p_value));
- if (t!=args[idx].get_type()) {
+ if (t != args[idx].get_type()) {
Variant::CallError err;
- if (Variant::can_convert(args[idx].get_type(),t)) {
- Variant old=args[idx];
- Variant *ptrs[1]={&old};
- args[idx]=Variant::construct(t,(const Variant**)ptrs,1,err);
+ if (Variant::can_convert(args[idx].get_type(), t)) {
+ Variant old = args[idx];
+ Variant *ptrs[1] = { &old };
+ args[idx] = Variant::construct(t, (const Variant **)ptrs, 1, err);
} else {
- args[idx]=Variant::construct(t,NULL,0,err);
+ args[idx] = Variant::construct(t, NULL, 0, err);
}
- change_notify_deserved=true;
- d_new["args"]=args;
+ change_notify_deserved = true;
+ d_new["args"] = args;
}
-
}
- if (what=="value") {
+ if (what == "value") {
- Variant value=p_value;
- if (value.get_type()==Variant::NODE_PATH) {
+ Variant value = p_value;
+ if (value.get_type() == Variant::NODE_PATH) {
_fix_node_path(value);
}
- args[idx]=value;
- d_new["args"]=args;
- mergeable=true;
+ args[idx] = value;
+ d_new["args"] = args;
+ mergeable = true;
}
}
if (mergeable)
- undo_redo->create_action(TTR("Anim Change Call"),UndoRedo::MERGE_ENDS);
+ undo_redo->create_action(TTR("Anim Change Call"), UndoRedo::MERGE_ENDS);
else
undo_redo->create_action(TTR("Anim Change Call"));
- Variant prev = animation->track_get_key_value(track,key);
- setting=true;
- undo_redo->add_do_method(animation.ptr(),"track_set_key_value",track,key,d_new);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_value",track,key,d_old);
- undo_redo->add_do_method(this,"_update_obj",animation);
- undo_redo->add_undo_method(this,"_update_obj",animation);
+ Variant prev = animation->track_get_key_value(track, key);
+ setting = true;
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_value", track, key, d_new);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_value", track, key, d_old);
+ undo_redo->add_do_method(this, "_update_obj", animation);
+ undo_redo->add_undo_method(this, "_update_obj", animation);
undo_redo->commit_action();
- setting=false;
+ setting = false;
if (change_notify_deserved)
notify_change();
return true;
} break;
}
-
-
return false;
-
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ bool _get(const StringName &p_name, Variant &r_ret) const {
- int key = animation->track_find_key(track,key_ofs,true);
- ERR_FAIL_COND_V(key==-1,false);
+ int key = animation->track_find_key(track, key_ofs, true);
+ ERR_FAIL_COND_V(key == -1, false);
- String name=p_name;
- if (name=="time") {
+ String name = p_name;
+ if (name == "time") {
r_ret = key_ofs;
return true;
- } else if (name=="easing") {
- r_ret = animation->track_get_key_transition(track,key);
+ } else if (name == "easing") {
+ r_ret = animation->track_get_key_transition(track, key);
return true;
}
-
-
- switch(animation->track_get_type(track)) {
-
+ switch (animation->track_get_type(track)) {
case Animation::TYPE_TRANSFORM: {
- Dictionary d = animation->track_get_key_value(track,key);
- ERR_FAIL_COND_V(!d.has(name),false);
+ Dictionary d = animation->track_get_key_value(track, key);
+ ERR_FAIL_COND_V(!d.has(name), false);
r_ret = d[p_name];
return true;
} break;
case Animation::TYPE_VALUE: {
- if (name=="value") {
- r_ret = animation->track_get_key_value(track,key);
+ if (name == "value") {
+ r_ret = animation->track_get_key_value(track, key);
return true;
}
-
-
} break;
case Animation::TYPE_METHOD: {
- Dictionary d = animation->track_get_key_value(track,key);
+ Dictionary d = animation->track_get_key_value(track, key);
- if (name=="name") {
+ if (name == "name") {
- ERR_FAIL_COND_V(!d.has("method"),false);
- r_ret=d["method"];
+ ERR_FAIL_COND_V(!d.has("method"), false);
+ r_ret = d["method"];
return true;
}
- ERR_FAIL_COND_V(!d.has("args"),false);
+ ERR_FAIL_COND_V(!d.has("args"), false);
Vector<Variant> args = d["args"];
+ if (name == "arg_count") {
- if (name=="arg_count") {
-
- r_ret=args.size();
+ r_ret = args.size();
return true;
}
-
if (name.begins_with("args/")) {
- int idx = name.get_slice("/",1).to_int();
- ERR_FAIL_INDEX_V(idx,args.size(),false);
+ int idx = name.get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, args.size(), false);
- String what = name.get_slice("/",2);
- if (what=="type") {
- r_ret=args[idx].get_type();
+ String what = name.get_slice("/", 2);
+ if (what == "type") {
+ r_ret = args[idx].get_type();
return true;
}
- if (what=="value") {
- r_ret=args[idx];
+ if (what == "value") {
+ r_ret = args[idx];
return true;
}
}
@@ -570,79 +544,76 @@ public:
return false;
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ void _get_property_list(List<PropertyInfo> *p_list) const {
if (animation.is_null())
return;
- ERR_FAIL_INDEX(track,animation->get_track_count());
- int key = animation->track_find_key(track,key_ofs,true);
- ERR_FAIL_COND(key==-1);
+ ERR_FAIL_INDEX(track, animation->get_track_count());
+ int key = animation->track_find_key(track, key_ofs, true);
+ ERR_FAIL_COND(key == -1);
- p_list->push_back( PropertyInfo( Variant::REAL, "time", PROPERTY_HINT_RANGE,"0,"+rtos(animation->get_length())+",0.01") );
-
- switch(animation->track_get_type(track)) {
+ p_list->push_back(PropertyInfo(Variant::REAL, "time", PROPERTY_HINT_RANGE, "0," + rtos(animation->get_length()) + ",0.01"));
+ switch (animation->track_get_type(track)) {
case Animation::TYPE_TRANSFORM: {
- p_list->push_back( PropertyInfo( Variant::VECTOR3, "loc"));
- p_list->push_back( PropertyInfo( Variant::QUAT, "rot"));
- p_list->push_back( PropertyInfo( Variant::VECTOR3, "scale"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "loc"));
+ p_list->push_back(PropertyInfo(Variant::QUAT, "rot"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR3, "scale"));
} break;
case Animation::TYPE_VALUE: {
- Variant v = animation->track_get_key_value(track,key);
-
+ Variant v = animation->track_get_key_value(track, key);
+ if (hint.type != Variant::NIL) {
- if (hint.type!=Variant::NIL) {
-
- PropertyInfo pi=hint;
- pi.name="value";
- p_list->push_back( pi );
+ PropertyInfo pi = hint;
+ pi.name = "value";
+ p_list->push_back(pi);
} else {
- PropertyHint hint= PROPERTY_HINT_NONE;
+ PropertyHint hint = PROPERTY_HINT_NONE;
String hint_string;
- if (v.get_type()==Variant::OBJECT) {
+ if (v.get_type() == Variant::OBJECT) {
//could actually check the object property if exists..? yes i will!
Ref<Resource> res = v;
if (res.is_valid()) {
- hint=PROPERTY_HINT_RESOURCE_TYPE;
- hint_string=res->get_class();
+ hint = PROPERTY_HINT_RESOURCE_TYPE;
+ hint_string = res->get_class();
}
}
- if (v.get_type()!=Variant::NIL)
- p_list->push_back( PropertyInfo( v.get_type(), "value", hint,hint_string));
+ if (v.get_type() != Variant::NIL)
+ p_list->push_back(PropertyInfo(v.get_type(), "value", hint, hint_string));
}
} break;
case Animation::TYPE_METHOD: {
- p_list->push_back( PropertyInfo( Variant::STRING, "name"));
- p_list->push_back( PropertyInfo( Variant::INT, "arg_count",PROPERTY_HINT_RANGE,"0,5,1"));
+ p_list->push_back(PropertyInfo(Variant::STRING, "name"));
+ p_list->push_back(PropertyInfo(Variant::INT, "arg_count", PROPERTY_HINT_RANGE, "0,5,1"));
- Dictionary d = animation->track_get_key_value(track,key);
+ Dictionary d = animation->track_get_key_value(track, key);
ERR_FAIL_COND(!d.has("args"));
- Vector<Variant> args=d["args"];
+ Vector<Variant> args = d["args"];
String vtypes;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i>0)
- vtypes+=",";
- vtypes+=Variant::get_type_name( Variant::Type(i) );
+ if (i > 0)
+ vtypes += ",";
+ vtypes += Variant::get_type_name(Variant::Type(i));
}
- for(int i=0;i<args.size();i++) {
+ for (int i = 0; i < args.size(); i++) {
- p_list->push_back( PropertyInfo( Variant::INT, "args/"+itos(i)+"/type", PROPERTY_HINT_ENUM,vtypes));
- if (args[i].get_type()!=Variant::NIL)
- p_list->push_back( PropertyInfo( args[i].get_type(), "args/"+itos(i)+"/value"));
+ p_list->push_back(PropertyInfo(Variant::INT, "args/" + itos(i) + "/type", PROPERTY_HINT_ENUM, vtypes));
+ if (args[i].get_type() != Variant::NIL)
+ p_list->push_back(PropertyInfo(args[i].get_type(), "args/" + itos(i) + "/value"));
}
} break;
@@ -662,23 +633,24 @@ public:
PropertyInfo hint;
NodePath base;
-
void notify_change() {
_change_notify();
}
- AnimationKeyEdit() { hidden=true; key_ofs=0; track=-1; setting=false; }
-
+ AnimationKeyEdit() {
+ hidden = true;
+ key_ofs = 0;
+ track = -1;
+ setting = false;
+ }
};
-
void AnimationKeyEditor::_menu_add_track(int p_type) {
ERR_FAIL_COND(!animation.is_valid());
-
- switch(p_type) {
+ switch (p_type) {
case ADD_TRACK_MENU_ADD_CALL_TRACK: {
if (root) {
@@ -690,34 +662,32 @@ void AnimationKeyEditor::_menu_add_track(int p_type) {
case ADD_TRACK_MENU_ADD_TRANSFORM_TRACK: {
undo_redo->create_action(TTR("Anim Add Track"));
- undo_redo->add_do_method(animation.ptr(),"add_track",p_type);
- undo_redo->add_do_method(animation.ptr(),"track_set_path",animation->get_track_count(),".");
- undo_redo->add_undo_method(animation.ptr(),"remove_track",animation->get_track_count());
+ undo_redo->add_do_method(animation.ptr(), "add_track", p_type);
+ undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), ".");
+ undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count());
undo_redo->commit_action();
-
} break;
}
}
void AnimationKeyEditor::_anim_duplicate_keys(bool transpose) {
//duplicait!
- if (selection.size() && animation.is_valid() && selected_track>=0 && selected_track<animation->get_track_count()) {
+ if (selection.size() && animation.is_valid() && selected_track >= 0 && selected_track < animation->get_track_count()) {
- int top_track=0x7FFFFFFF;
+ int top_track = 0x7FFFFFFF;
float top_time = 1e10;
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
const SelectedKey &sk = E->key();
- float t = animation->track_get_key_time(sk.track,sk.key);
- if (t<top_time)
- top_time=t;
- if (sk.track<top_track)
- top_track=sk.track;
-
+ float t = animation->track_get_key_time(sk.track, sk.key);
+ if (t < top_time)
+ top_time = t;
+ if (sk.track < top_track)
+ top_track = sk.track;
}
- ERR_FAIL_COND( top_track == 0x7FFFFFFF || top_time==1e10 );
+ ERR_FAIL_COND(top_track == 0x7FFFFFFF || top_time == 1e10);
//
@@ -725,71 +695,66 @@ void AnimationKeyEditor::_anim_duplicate_keys(bool transpose) {
undo_redo->create_action(TTR("Anim Duplicate Keys"));
- List<Pair<int,float> > new_selection_values;
+ List<Pair<int, float> > new_selection_values;
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
const SelectedKey &sk = E->key();
- float t = animation->track_get_key_time(sk.track,sk.key);
+ float t = animation->track_get_key_time(sk.track, sk.key);
- float dst_time = t+(timeline_pos - top_time);
+ float dst_time = t + (timeline_pos - top_time);
int dst_track = sk.track + (start_track - top_track);
- if (dst_track < 0 || dst_track>= animation->get_track_count())
+ if (dst_track < 0 || dst_track >= animation->get_track_count())
continue;
if (animation->track_get_type(dst_track) != animation->track_get_type(sk.track))
continue;
- int existing_idx = animation->track_find_key(dst_track,dst_time,true);
-
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",dst_track,dst_time,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",dst_track,dst_time);
+ int existing_idx = animation->track_find_key(dst_track, dst_time, true);
- Pair<int,float> p;
- p.first=dst_track;
- p.second=dst_time;
- new_selection_values.push_back( p );
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", dst_track, dst_time);
- if (existing_idx!=-1) {
+ Pair<int, float> p;
+ p.first = dst_track;
+ p.second = dst_time;
+ new_selection_values.push_back(p);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",dst_track,dst_time,animation->track_get_key_value(dst_track,existing_idx),animation->track_get_key_transition(dst_track,existing_idx));
+ if (existing_idx != -1) {
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", dst_track, dst_time, animation->track_get_key_value(dst_track, existing_idx), animation->track_get_key_transition(dst_track, existing_idx));
}
-
}
undo_redo->commit_action();
//reselect duplicated
- Map<SelectedKey,KeyInfo> new_selection;
- for (List<Pair<int,float> >::Element *E=new_selection_values.front();E;E=E->next()) {
+ Map<SelectedKey, KeyInfo> new_selection;
+ for (List<Pair<int, float> >::Element *E = new_selection_values.front(); E; E = E->next()) {
- int track=E->get().first;
+ int track = E->get().first;
float time = E->get().second;
- int existing_idx = animation->track_find_key(track,time,true);
+ int existing_idx = animation->track_find_key(track, time, true);
- if (existing_idx==-1)
+ if (existing_idx == -1)
continue;
SelectedKey sk2;
- sk2.track=track;
- sk2.key=existing_idx;
+ sk2.track = track;
+ sk2.key = existing_idx;
KeyInfo ki;
- ki.pos=time;
-
- new_selection[sk2]=ki;
+ ki.pos = time;
+ new_selection[sk2] = ki;
}
-
- selection=new_selection;
+ selection = new_selection;
track_editor->update();
_edit_if_single_selection();
-
}
}
@@ -797,74 +762,70 @@ void AnimationKeyEditor::_menu_track(int p_type) {
ERR_FAIL_COND(!animation.is_valid());
- last_menu_track_opt=p_type;
- switch(p_type) {
+ last_menu_track_opt = p_type;
+ switch (p_type) {
case TRACK_MENU_SCALE:
case TRACK_MENU_SCALE_PIVOT: {
- scale_dialog->popup_centered(Size2(200,100));
+ scale_dialog->popup_centered(Size2(200, 100));
} break;
case TRACK_MENU_MOVE_UP: {
- int idx=selected_track;
- if (idx>0 && idx<animation->get_track_count()) {
+ int idx = selected_track;
+ if (idx > 0 && idx < animation->get_track_count()) {
undo_redo->create_action(TTR("Move Anim Track Up"));
- undo_redo->add_do_method(animation.ptr(),"track_move_down",idx);
- undo_redo->add_undo_method(animation.ptr(),"track_move_up",idx-1);
+ undo_redo->add_do_method(animation.ptr(), "track_move_down", idx);
+ undo_redo->add_undo_method(animation.ptr(), "track_move_up", idx - 1);
undo_redo->commit_action();
- selected_track=idx-1;
+ selected_track = idx - 1;
}
} break;
case TRACK_MENU_MOVE_DOWN: {
-
- int idx=selected_track;
- if (idx>=0 && idx<animation->get_track_count()-1) {
+ int idx = selected_track;
+ if (idx >= 0 && idx < animation->get_track_count() - 1) {
undo_redo->create_action(TTR("Move Anim Track Down"));
- undo_redo->add_do_method(animation.ptr(),"track_move_up",idx);
- undo_redo->add_undo_method(animation.ptr(),"track_move_down",idx+1);
+ undo_redo->add_do_method(animation.ptr(), "track_move_up", idx);
+ undo_redo->add_undo_method(animation.ptr(), "track_move_down", idx + 1);
undo_redo->commit_action();
- selected_track=idx+1;
+ selected_track = idx + 1;
}
} break;
case TRACK_MENU_REMOVE: {
- int idx=selected_track;
- if (idx>=0 && idx<animation->get_track_count()) {
+ int idx = selected_track;
+ if (idx >= 0 && idx < animation->get_track_count()) {
undo_redo->create_action(TTR("Remove Anim Track"));
- undo_redo->add_do_method(animation.ptr(),"remove_track",idx);
- undo_redo->add_undo_method(animation.ptr(),"add_track",animation->track_get_type(idx),idx);
- undo_redo->add_undo_method(animation.ptr(),"track_set_path",idx,animation->track_get_path(idx));
+ undo_redo->add_do_method(animation.ptr(), "remove_track", idx);
+ undo_redo->add_undo_method(animation.ptr(), "add_track", animation->track_get_type(idx), idx);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_path", idx, animation->track_get_path(idx));
//todo interpolation
- for(int i=0;i<animation->track_get_key_count(idx);i++) {
+ for (int i = 0; i < animation->track_get_key_count(idx); i++) {
- Variant v = animation->track_get_key_value(idx,i);
- float time = animation->track_get_key_time(idx,i);
- float trans = animation->track_get_key_transition(idx,i);
-
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",idx,time,v);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_transition",idx,i,trans);
+ Variant v = animation->track_get_key_value(idx, i);
+ float time = animation->track_get_key_time(idx, i);
+ float trans = animation->track_get_key_transition(idx, i);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, time, v);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", idx, i, trans);
}
- undo_redo->add_undo_method(animation.ptr(),"track_set_interpolation_type",idx,animation->track_get_interpolation_type(idx));
- if (animation->track_get_type(idx)==Animation::TYPE_VALUE) {
- undo_redo->add_undo_method(animation.ptr(),"value_track_set_update_mode",idx,animation->value_track_get_update_mode(idx));
-
+ undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", idx, animation->track_get_interpolation_type(idx));
+ if (animation->track_get_type(idx) == Animation::TYPE_VALUE) {
+ undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", idx, animation->value_track_get_update_mode(idx));
}
undo_redo->commit_action();
}
-
} break;
case TRACK_MENU_DUPLICATE:
case TRACK_MENU_DUPLICATE_TRANSPOSE: {
- _anim_duplicate_keys(p_type==TRACK_MENU_DUPLICATE_TRANSPOSE);
+ _anim_duplicate_keys(p_type == TRACK_MENU_DUPLICATE_TRANSPOSE);
} break;
case TRACK_MENU_SET_ALL_TRANS_LINEAR:
case TRACK_MENU_SET_ALL_TRANS_CONSTANT:
@@ -876,25 +837,24 @@ void AnimationKeyEditor::_menu_track(int p_type) {
if (!selection.size() || !animation.is_valid())
break;
- float t=0;
- switch(p_type) {
- case TRACK_MENU_SET_ALL_TRANS_LINEAR: t=1.0; break;
- case TRACK_MENU_SET_ALL_TRANS_CONSTANT: t=0.0; break;
- case TRACK_MENU_SET_ALL_TRANS_OUT: t=0.5; break;
- case TRACK_MENU_SET_ALL_TRANS_IN: t=2.0; break;
- case TRACK_MENU_SET_ALL_TRANS_INOUT: t=-0.5; break;
- case TRACK_MENU_SET_ALL_TRANS_OUTIN: t=-2.0; break;
+ float t = 0;
+ switch (p_type) {
+ case TRACK_MENU_SET_ALL_TRANS_LINEAR: t = 1.0; break;
+ case TRACK_MENU_SET_ALL_TRANS_CONSTANT: t = 0.0; break;
+ case TRACK_MENU_SET_ALL_TRANS_OUT: t = 0.5; break;
+ case TRACK_MENU_SET_ALL_TRANS_IN: t = 2.0; break;
+ case TRACK_MENU_SET_ALL_TRANS_INOUT: t = -0.5; break;
+ case TRACK_MENU_SET_ALL_TRANS_OUTIN: t = -2.0; break;
}
- undo_redo->create_action(TTR("Set Transitions to:")+" "+rtos(t));
+ undo_redo->create_action(TTR("Set Transitions to:") + " " + rtos(t));
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
const SelectedKey &sk = E->key();
- undo_redo->add_do_method(animation.ptr(),"track_set_key_transition",sk.track,sk.key,t);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_transition",sk.track,sk.key,animation->track_get_key_transition(sk.track,sk.key));
-
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", sk.track, sk.key, t);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", sk.track, sk.key, animation->track_get_key_transition(sk.track, sk.key));
}
undo_redo->commit_action();
@@ -905,56 +865,54 @@ void AnimationKeyEditor::_menu_track(int p_type) {
if (animation.is_null())
break;
float step = animation->get_step();
- if (step==0)
- step=1;
+ if (step == 0)
+ step = 1;
- float pos=timeline_pos;
+ float pos = timeline_pos;
- pos=Math::stepify(pos+step,step);
- if (pos>animation->get_length())
- pos=animation->get_length();
- timeline_pos=pos;
+ pos = Math::stepify(pos + step, step);
+ if (pos > animation->get_length())
+ pos = animation->get_length();
+ timeline_pos = pos;
track_pos->update();
- emit_signal("timeline_changed",pos,true);
+ emit_signal("timeline_changed", pos, true);
} break;
case TRACK_MENU_PREV_STEP: {
if (animation.is_null())
break;
float step = animation->get_step();
- if (step==0)
- step=1;
-
- float pos=timeline_pos;
- pos=Math::stepify(pos-step,step);
- if (pos<0)
- pos=0;
- timeline_pos=pos;
+ if (step == 0)
+ step = 1;
+
+ float pos = timeline_pos;
+ pos = Math::stepify(pos - step, step);
+ if (pos < 0)
+ pos = 0;
+ timeline_pos = pos;
track_pos->update();
- emit_signal("timeline_changed",pos,true);
-
+ emit_signal("timeline_changed", pos, true);
} break;
case TRACK_MENU_OPTIMIZE: {
- optimize_dialog->popup_centered(Size2(250,180));
+ optimize_dialog->popup_centered(Size2(250, 180));
} break;
case TRACK_MENU_CLEAN_UP: {
- cleanup_dialog->popup_centered_minsize(Size2(300,0));
+ cleanup_dialog->popup_centered_minsize(Size2(300, 0));
} break;
case TRACK_MENU_CLEAN_UP_CONFIRM: {
if (cleanup_all->is_pressed()) {
List<StringName> names;
AnimationPlayerEditor::singleton->get_player()->get_animation_list(&names);
- for (List<StringName>::Element *E=names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
_cleanup_animation(AnimationPlayerEditor::singleton->get_player()->get_animation(E->get()));
}
} else {
_cleanup_animation(animation);
-
}
} break;
case CURVE_SET_LINEAR: {
@@ -982,31 +940,28 @@ void AnimationKeyEditor::_menu_track(int p_type) {
curve_edit->force_transition(0);
} break;
-
}
-
}
void AnimationKeyEditor::_cleanup_animation(Ref<Animation> p_animation) {
+ for (int i = 0; i < p_animation->get_track_count(); i++) {
- for(int i=0;i<p_animation->get_track_count();i++) {
-
- bool prop_exists=false;
- Variant::Type valid_type=Variant::NIL;
- Object *obj=NULL;
+ bool prop_exists = false;
+ Variant::Type valid_type = Variant::NIL;
+ Object *obj = NULL;
RES res;
- Node *node = root->get_node_and_resource(p_animation->track_get_path(i),res);
+ Node *node = root->get_node_and_resource(p_animation->track_get_path(i), res);
if (res.is_valid()) {
- obj=res.ptr();
+ obj = res.ptr();
} else if (node) {
- obj=node;
+ obj = node;
}
- if (obj && p_animation->track_get_type(i)==Animation::TYPE_VALUE) {
- valid_type=obj->get_static_property_type(p_animation->track_get_path(i).get_property(),&prop_exists);
+ if (obj && p_animation->track_get_type(i) == Animation::TYPE_VALUE) {
+ valid_type = obj->get_static_property_type(p_animation->track_get_path(i).get_property(), &prop_exists);
}
if (!obj && cleanup_tracks->is_pressed()) {
@@ -1016,20 +971,20 @@ void AnimationKeyEditor::_cleanup_animation(Ref<Animation> p_animation) {
continue;
}
- if (!prop_exists || p_animation->track_get_type(i)!=Animation::TYPE_VALUE || cleanup_keys->is_pressed()==false)
+ if (!prop_exists || p_animation->track_get_type(i) != Animation::TYPE_VALUE || cleanup_keys->is_pressed() == false)
continue;
- for(int j=0;j<p_animation->track_get_key_count(i);j++) {
+ for (int j = 0; j < p_animation->track_get_key_count(i); j++) {
- Variant v = p_animation->track_get_key_value(i,j);
+ Variant v = p_animation->track_get_key_value(i, j);
- if (!Variant::can_convert(v.get_type(),valid_type)) {
- p_animation->track_remove_key(i,j);
+ if (!Variant::can_convert(v.get_type(), valid_type)) {
+ p_animation->track_remove_key(i, j);
j--;
}
}
- if (p_animation->track_get_key_count(i)==0 && cleanup_tracks->is_pressed()) {
+ if (p_animation->track_get_key_count(i) == 0 && cleanup_tracks->is_pressed()) {
p_animation->remove_track(i);
i--;
}
@@ -1039,25 +994,21 @@ void AnimationKeyEditor::_cleanup_animation(Ref<Animation> p_animation) {
_update_paths();
}
-void AnimationKeyEditor::_animation_optimize() {
-
+void AnimationKeyEditor::_animation_optimize() {
-
- animation->optimize(optimize_linear_error->get_value(),optimize_angular_error->get_value(),optimize_max_angle->get_value());
+ animation->optimize(optimize_linear_error->get_value(), optimize_angular_error->get_value(), optimize_max_angle->get_value());
track_editor->update();
undo_redo->clear_history();
-
}
-
float AnimationKeyEditor::_get_zoom_scale() const {
float zv = zoom->get_value();
- if (zv<1) {
- zv = 1.0-zv;
- return Math::pow(1.0f+zv,8.0f)*100;
+ if (zv < 1) {
+ zv = 1.0 - zv;
+ return Math::pow(1.0f + zv, 8.0f) * 100;
} else {
- return 1.0/Math::pow(zv,8.0f)*100;
+ return 1.0 / Math::pow(zv, 8.0f) * 100;
}
}
@@ -1067,47 +1018,42 @@ void AnimationKeyEditor::_track_pos_draw() {
return;
}
-
- Ref<StyleBox> style = get_stylebox("normal","TextEdit");
- Size2 size= track_editor->get_size() - style->get_minimum_size();
+ Ref<StyleBox> style = get_stylebox("normal", "TextEdit");
+ Size2 size = track_editor->get_size() - style->get_minimum_size();
Size2 ofs = style->get_offset();
int settings_limit = size.width - right_data_size_cache;
int name_limit = settings_limit * name_column_ratio;
- float keys_from= h_scroll->get_value();
+ float keys_from = h_scroll->get_value();
float zoom_scale = _get_zoom_scale();
- float keys_to=keys_from+(settings_limit-name_limit) / zoom_scale;
-
-
+ float keys_to = keys_from + (settings_limit - name_limit) / zoom_scale;
//will move to separate control! (for speedup)
- if (timeline_pos >= keys_from && timeline_pos<keys_to) {
+ if (timeline_pos >= keys_from && timeline_pos < keys_to) {
//draw position
int pixel = (timeline_pos - h_scroll->get_value()) * zoom_scale;
- pixel+=name_limit;
- track_pos->draw_line(ofs+Point2(pixel,0),ofs+Point2(pixel,size.height),Color(1,0.3,0.3,0.8));
-
+ pixel += name_limit;
+ track_pos->draw_line(ofs + Point2(pixel, 0), ofs + Point2(pixel, size.height), Color(1, 0.3, 0.3, 0.8));
}
}
void AnimationKeyEditor::_track_editor_draw() {
-
if (animation.is_valid() && animation->get_track_count()) {
if (selected_track < 0)
- selected_track=0;
- else if (selected_track>=animation->get_track_count())
- selected_track=animation->get_track_count()-1;
+ selected_track = 0;
+ else if (selected_track >= animation->get_track_count())
+ selected_track = animation->get_track_count() - 1;
}
track_pos->update();
- Control *te=track_editor;
- Ref<StyleBox> style = get_stylebox("normal","TextEdit");
- te->draw_style_box(style,Rect2(Point2(),track_editor->get_size()));
+ Control *te = track_editor;
+ Ref<StyleBox> style = get_stylebox("normal", "TextEdit");
+ te->draw_style_box(style, Rect2(Point2(), track_editor->get_size()));
if (te->has_focus()) {
- te->draw_style_box(get_stylebox("bg_focus","Tree"),Rect2(Point2(),track_editor->get_size()));
+ te->draw_style_box(get_stylebox("bg_focus", "Tree"), Rect2(Point2(), track_editor->get_size()));
}
if (!animation.is_valid()) {
@@ -1133,289 +1079,267 @@ void AnimationKeyEditor::_track_editor_draw() {
if (edit_button->is_pressed())
key_editor_tab->show();
- te_drawing=true;
+ te_drawing = true;
- Size2 size= te->get_size() - style->get_minimum_size();
+ Size2 size = te->get_size() - style->get_minimum_size();
Size2 ofs = style->get_offset();
- Ref<Font> font = te->get_font("font","Tree");
- int sep = get_constant("vseparation","Tree");
- int hsep = get_constant("hseparation","Tree");
- Color color = get_color("font_color","Tree");
- Color sepcolor = get_color("guide_color","Tree");
- Color timecolor = get_color("prop_subsection","Editor");
+ Ref<Font> font = te->get_font("font", "Tree");
+ int sep = get_constant("vseparation", "Tree");
+ int hsep = get_constant("hseparation", "Tree");
+ Color color = get_color("font_color", "Tree");
+ Color sepcolor = get_color("guide_color", "Tree");
+ Color timecolor = get_color("prop_subsection", "Editor");
timecolor = Color::html("ff4a414f");
- Color hover_color = Color(1,1,1,0.05);
- Color select_color = Color(1,1,1,0.1);
- Color invalid_path_color = Color(1,0.6,0.4,0.5);
- Color track_select_color =Color::html("ffbd8e8e");
-
- Ref<Texture> remove_icon = get_icon("Remove","EditorIcons");
- Ref<Texture> move_up_icon = get_icon("MoveUp","EditorIcons");
- Ref<Texture> move_down_icon = get_icon("MoveDown","EditorIcons");
- Ref<Texture> remove_icon_hl = get_icon("RemoveHl","EditorIcons");
- Ref<Texture> move_up_icon_hl = get_icon("MoveUpHl","EditorIcons");
- Ref<Texture> move_down_icon_hl = get_icon("MoveDownHl","EditorIcons");
- Ref<Texture> add_key_icon = get_icon("TrackAddKey","EditorIcons");
- Ref<Texture> add_key_icon_hl = get_icon("TrackAddKeyHl","EditorIcons");
- Ref<Texture> down_icon = get_icon("select_arrow","Tree");
-
- Ref<Texture> wrap_icon[2]={
- get_icon("InterpWrapClamp","EditorIcons"),
- get_icon("InterpWrapLoop","EditorIcons"),
+ Color hover_color = Color(1, 1, 1, 0.05);
+ Color select_color = Color(1, 1, 1, 0.1);
+ Color invalid_path_color = Color(1, 0.6, 0.4, 0.5);
+ Color track_select_color = Color::html("ffbd8e8e");
+
+ Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons");
+ Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons");
+ Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons");
+ Ref<Texture> remove_icon_hl = get_icon("RemoveHl", "EditorIcons");
+ Ref<Texture> move_up_icon_hl = get_icon("MoveUpHl", "EditorIcons");
+ Ref<Texture> move_down_icon_hl = get_icon("MoveDownHl", "EditorIcons");
+ Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons");
+ Ref<Texture> add_key_icon_hl = get_icon("TrackAddKeyHl", "EditorIcons");
+ Ref<Texture> down_icon = get_icon("select_arrow", "Tree");
+
+ Ref<Texture> wrap_icon[2] = {
+ get_icon("InterpWrapClamp", "EditorIcons"),
+ get_icon("InterpWrapLoop", "EditorIcons"),
};
- Ref<Texture> interp_icon[3]={
- get_icon("InterpRaw","EditorIcons"),
- get_icon("InterpLinear","EditorIcons"),
- get_icon("InterpCubic","EditorIcons")
+ Ref<Texture> interp_icon[3] = {
+ get_icon("InterpRaw", "EditorIcons"),
+ get_icon("InterpLinear", "EditorIcons"),
+ get_icon("InterpCubic", "EditorIcons")
};
- Ref<Texture> cont_icon[3]={
- get_icon("TrackContinuous","EditorIcons"),
- get_icon("TrackDiscrete","EditorIcons"),
- get_icon("TrackTrigger","EditorIcons")
+ Ref<Texture> cont_icon[3] = {
+ get_icon("TrackContinuous", "EditorIcons"),
+ get_icon("TrackDiscrete", "EditorIcons"),
+ get_icon("TrackTrigger", "EditorIcons")
};
- Ref<Texture> type_icon[3]={
- get_icon("KeyValue","EditorIcons"),
- get_icon("KeyXform","EditorIcons"),
- get_icon("KeyCall","EditorIcons")
+ Ref<Texture> type_icon[3] = {
+ get_icon("KeyValue", "EditorIcons"),
+ get_icon("KeyXform", "EditorIcons"),
+ get_icon("KeyCall", "EditorIcons")
};
- Ref<Texture> invalid_icon = get_icon("KeyInvalid","EditorIcons");
- Ref<Texture> invalid_icon_hover = get_icon("KeyInvalidHover","EditorIcons");
+ Ref<Texture> invalid_icon = get_icon("KeyInvalid", "EditorIcons");
+ Ref<Texture> invalid_icon_hover = get_icon("KeyInvalidHover", "EditorIcons");
- Ref<Texture> hsize_icon = get_icon("Hsize","EditorIcons");
+ Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons");
- Ref<Texture> type_hover=get_icon("KeyHover","EditorIcons");
- Ref<Texture> type_selected=get_icon("KeySelected","EditorIcons");
+ Ref<Texture> type_hover = get_icon("KeyHover", "EditorIcons");
+ Ref<Texture> type_selected = get_icon("KeySelected", "EditorIcons");
- int right_separator_ofs = down_icon->get_width() *3 + add_key_icon->get_width() + interp_icon[0]->get_width() + wrap_icon[0]->get_width() + cont_icon[0]->get_width() + hsep*9;
+ int right_separator_ofs = down_icon->get_width() * 3 + add_key_icon->get_width() + interp_icon[0]->get_width() + wrap_icon[0]->get_width() + cont_icon[0]->get_width() + hsep * 9;
- int h = font->get_height()+sep;
+ int h = font->get_height() + sep;
-
- int fit = (size.height / h)-1;
+ int fit = (size.height / h) - 1;
int total = animation->get_track_count();
if (total < fit) {
v_scroll->hide();
- v_scroll->set_max( total );
- v_scroll->set_page( fit );
+ v_scroll->set_max(total);
+ v_scroll->set_page(fit);
} else {
v_scroll->show();
- v_scroll->set_max( total );
- v_scroll->set_page( fit );
+ v_scroll->set_max(total);
+ v_scroll->set_page(fit);
}
-
int settings_limit = size.width - right_separator_ofs;
int name_limit = settings_limit * name_column_ratio;
- te->draw_line(ofs+Point2(name_limit,0),ofs+Point2(name_limit,size.height),color);
- te->draw_line(ofs+Point2(settings_limit,0),ofs+Point2(settings_limit,size.height),color);
- te->draw_texture(hsize_icon,ofs+Point2(name_limit-hsize_icon->get_width()-hsep,(h-hsize_icon->get_height())/2));
+ te->draw_line(ofs + Point2(name_limit, 0), ofs + Point2(name_limit, size.height), color);
+ te->draw_line(ofs + Point2(settings_limit, 0), ofs + Point2(settings_limit, size.height), color);
+ te->draw_texture(hsize_icon, ofs + Point2(name_limit - hsize_icon->get_width() - hsep, (h - hsize_icon->get_height()) / 2));
- te->draw_line(ofs+Point2(0,h),ofs+Point2(size.width,h),color);
+ te->draw_line(ofs + Point2(0, h), ofs + Point2(size.width, h), color);
// draw time
float keys_from;
float keys_to;
float zoom_scale;
-
{
- int zoomw = settings_limit-name_limit;
-
+ int zoomw = settings_limit - name_limit;
float scale = _get_zoom_scale();
- zoom_scale=scale;
-
+ zoom_scale = scale;
float l = animation->get_length();
- if (l<=0)
- l=0.001; //avoid crashor
+ if (l <= 0)
+ l = 0.001; //avoid crashor
int end_px = (l - h_scroll->get_value()) * scale;
int begin_px = -h_scroll->get_value() * scale;
Color notimecol;
- notimecol.r=timecolor.gray();
- notimecol.g=notimecol.r;
- notimecol.b=notimecol.r;
- notimecol.a=timecolor.a;
+ notimecol.r = timecolor.gray();
+ notimecol.g = notimecol.r;
+ notimecol.b = notimecol.r;
+ notimecol.a = timecolor.a;
{
- te->draw_rect(Rect2( ofs + Point2(name_limit,0), Point2(zoomw-1,h)), notimecol);
+ te->draw_rect(Rect2(ofs + Point2(name_limit, 0), Point2(zoomw - 1, h)), notimecol);
+ if (begin_px < zoomw && end_px > 0) {
- if (begin_px < zoomw && end_px >0) {
+ if (begin_px < 0)
+ begin_px = 0;
+ if (end_px > zoomw)
+ end_px = zoomw;
- if (begin_px<0)
- begin_px=0;
- if (end_px>zoomw)
- end_px=zoomw;
-
- te->draw_rect(Rect2( ofs + Point2(name_limit+begin_px,0), Point2(end_px-begin_px-1,h)), timecolor);
+ te->draw_rect(Rect2(ofs + Point2(name_limit + begin_px, 0), Point2(end_px - begin_px - 1, h)), timecolor);
}
-
}
-
-
- keys_from= h_scroll->get_value();
- keys_to=keys_from+zoomw / scale;
+ keys_from = h_scroll->get_value();
+ keys_to = keys_from + zoomw / scale;
{
- float time_min=0;
- float time_max=animation->get_length();
- for(int i=0;i<animation->get_track_count();i++) {
-
- if (animation->track_get_key_count(i)>0) {
-
- float beg = animation->track_get_key_time(i,0);
- if (beg<time_min)
- time_min=beg;
- float end = animation->track_get_key_time(i,animation->track_get_key_count(i)-1);
- if (end>time_max)
- time_max=end;
+ float time_min = 0;
+ float time_max = animation->get_length();
+ for (int i = 0; i < animation->get_track_count(); i++) {
+
+ if (animation->track_get_key_count(i) > 0) {
+
+ float beg = animation->track_get_key_time(i, 0);
+ if (beg < time_min)
+ time_min = beg;
+ float end = animation->track_get_key_time(i, animation->track_get_key_count(i) - 1);
+ if (end > time_max)
+ time_max = end;
}
}
+ float extra = (zoomw / scale) * 0.5;
-
-
-
- float extra = (zoomw / scale)*0.5;
-
- if (time_min<-0.001)
- time_min-=extra;
- time_max+=extra;
+ if (time_min < -0.001)
+ time_min -= extra;
+ time_max += extra;
h_scroll->set_min(time_min);
h_scroll->set_max(time_max);
- if (zoomw / scale < (time_max-time_min)) {
+ if (zoomw / scale < (time_max - time_min)) {
h_scroll->show();
} else {
h_scroll->hide();
}
-
-
}
h_scroll->set_page(zoomw / scale);
Color color_time_sec = color;
Color color_time_dec = color;
- color_time_dec.a*=0.5;
+ color_time_dec.a *= 0.5;
#define SC_ADJ 100
- int min=30;
- int dec=1;
- int step=1;
- int decimals=2;
- bool step_found=false;
+ int min = 30;
+ int dec = 1;
+ int step = 1;
+ int decimals = 2;
+ bool step_found = false;
- while(!step_found) {
+ while (!step_found) {
- static const int _multp[3]={1,2,5};
- for(int i=0;i<3;i++) {
+ static const int _multp[3] = { 1, 2, 5 };
+ for (int i = 0; i < 3; i++) {
step = (_multp[i] * dec);
- if (step*scale/SC_ADJ> min) {
- step_found=true;
+ if (step * scale / SC_ADJ > min) {
+ step_found = true;
break;
}
-
}
if (step_found)
break;
- dec*=10;
+ dec *= 10;
decimals--;
- if (decimals<0)
- decimals=0;
+ if (decimals < 0)
+ decimals = 0;
}
+ for (int i = 0; i < zoomw; i++) {
- for(int i=0;i<zoomw;i++) {
-
- float pos = h_scroll->get_value() + double(i)/scale;
- float prev = h_scroll->get_value() + (double(i)-1.0)/scale;
-
+ float pos = h_scroll->get_value() + double(i) / scale;
+ float prev = h_scroll->get_value() + (double(i) - 1.0) / scale;
- int sc = int(Math::floor(pos*SC_ADJ));
- int prev_sc = int(Math::floor(prev*SC_ADJ));
+ int sc = int(Math::floor(pos * SC_ADJ));
+ int prev_sc = int(Math::floor(prev * SC_ADJ));
bool sub = (sc % SC_ADJ);
- if ((sc/step)!=(prev_sc/step) || (prev_sc<0 && sc>=0)) {
+ if ((sc / step) != (prev_sc / step) || (prev_sc < 0 && sc >= 0)) {
int scd = sc < 0 ? prev_sc : sc;
- te->draw_line( ofs + Point2(name_limit+i,0), ofs+Point2(name_limit+i,h), color);
- te->draw_string( font,ofs + Point2(name_limit+i+3,(h-font->get_height())/2+font->get_ascent()).floor(),String::num((scd-(scd%step))/double(SC_ADJ),decimals),sub?color_time_dec:color_time_sec,zoomw-i);
+ te->draw_line(ofs + Point2(name_limit + i, 0), ofs + Point2(name_limit + i, h), color);
+ te->draw_string(font, ofs + Point2(name_limit + i + 3, (h - font->get_height()) / 2 + font->get_ascent()).floor(), String::num((scd - (scd % step)) / double(SC_ADJ), decimals), sub ? color_time_dec : color_time_sec, zoomw - i);
}
-
-
}
}
- color.a*=0.5;
+ color.a *= 0.5;
- for(int i=0;i<fit;i++) {
+ for (int i = 0; i < fit; i++) {
//this code sucks, i always forget how it works
int idx = v_scroll->get_value() + i;
- if (idx>=animation->get_track_count())
+ if (idx >= animation->get_track_count())
break;
- int y = h+i*h+sep;
+ int y = h + i * h + sep;
- bool prop_exists=false;
- Variant::Type valid_type=Variant::NIL;
- Object *obj=NULL;
+ bool prop_exists = false;
+ Variant::Type valid_type = Variant::NIL;
+ Object *obj = NULL;
RES res;
- Node *node = root->get_node_and_resource(animation->track_get_path(idx),res);
+ Node *node = root->get_node_and_resource(animation->track_get_path(idx), res);
if (res.is_valid()) {
- obj=res.ptr();
+ obj = res.ptr();
} else if (node) {
- obj=node;
+ obj = node;
}
- if (obj && animation->track_get_type(idx)==Animation::TYPE_VALUE) {
- valid_type=obj->get_static_property_type(animation->track_get_path(idx).get_property(),&prop_exists);
+ if (obj && animation->track_get_type(idx) == Animation::TYPE_VALUE) {
+ valid_type = obj->get_static_property_type(animation->track_get_path(idx).get_property(), &prop_exists);
}
-
- if (/*mouse_over.over!=MouseOver::OVER_NONE &&*/ idx==mouse_over.track) {
- Color sepc=hover_color;
- te->draw_rect(Rect2(ofs+Point2(0,y),Size2(size.width,h-1)),sepc);
+ if (/*mouse_over.over!=MouseOver::OVER_NONE &&*/ idx == mouse_over.track) {
+ Color sepc = hover_color;
+ te->draw_rect(Rect2(ofs + Point2(0, y), Size2(size.width, h - 1)), sepc);
}
- if (selected_track==idx) {
+ if (selected_track == idx) {
Color tc = select_color;
//tc.a*=0.7;
- te->draw_rect(Rect2(ofs+Point2(0,y),Size2(size.width-1,h-1)),tc);
+ te->draw_rect(Rect2(ofs + Point2(0, y), Size2(size.width - 1, h - 1)), tc);
}
- te->draw_texture(type_icon[animation->track_get_type(idx)],ofs+Point2(0,y+(h-type_icon[0]->get_height())/2).floor());
+ te->draw_texture(type_icon[animation->track_get_type(idx)], ofs + Point2(0, y + (h - type_icon[0]->get_height()) / 2).floor());
NodePath np = animation->track_get_path(idx);
Node *n = root->get_node(np);
Color ncol = color;
if (n && editor_selection->is_selected(n))
- ncol=track_select_color;
- te->draw_string(font,Point2(ofs+Point2(type_icon[0]->get_width()+sep,y+font->get_ascent()+(sep/2))).floor(),np,ncol,name_limit-(type_icon[0]->get_width()+sep)-5);
+ ncol = track_select_color;
+ te->draw_string(font, Point2(ofs + Point2(type_icon[0]->get_width() + sep, y + font->get_ascent() + (sep / 2))).floor(), np, ncol, name_limit - (type_icon[0]->get_width() + sep) - 5);
if (!obj)
- te->draw_line(ofs+Point2(0,y+h/2),ofs+Point2(name_limit,y+h/2),invalid_path_color);
+ te->draw_line(ofs + Point2(0, y + h / 2), ofs + Point2(name_limit, y + h / 2), invalid_path_color);
- te->draw_line(ofs+Point2(0,y+h),ofs+Point2(size.width,y+h),sepcolor);
+ te->draw_line(ofs + Point2(0, y + h), ofs + Point2(size.width, y + h), sepcolor);
- Point2 icon_ofs = ofs + Point2( size.width, y + (h - remove_icon->get_height() )/2).floor();
- icon_ofs.y+=4;
+ Point2 icon_ofs = ofs + Point2(size.width, y + (h - remove_icon->get_height()) / 2).floor();
+ icon_ofs.y += 4;
-
-/* icon_ofs.x-=remove_icon->get_width();
+ /* icon_ofs.x-=remove_icon->get_width();
te->draw_texture((mouse_over.over==MouseOver::OVER_REMOVE && mouse_over.track==idx)?remove_icon_hl:remove_icon,icon_ofs);
icon_ofs.x-=hsep;
@@ -1429,246 +1353,235 @@ void AnimationKeyEditor::_track_editor_draw() {
icon_ofs.x-=hsep;
*/
- track_ofs[0]=size.width-icon_ofs.x;
- icon_ofs.x-=down_icon->get_width();
- te->draw_texture(down_icon,icon_ofs);
+ track_ofs[0] = size.width - icon_ofs.x;
+ icon_ofs.x -= down_icon->get_width();
+ te->draw_texture(down_icon, icon_ofs);
- int wrap_type = animation->track_get_interpolation_loop_wrap(idx)?1:0;
- icon_ofs.x-=hsep;
- icon_ofs.x-=wrap_icon[wrap_type]->get_width();
- te->draw_texture(wrap_icon[wrap_type],icon_ofs);
+ int wrap_type = animation->track_get_interpolation_loop_wrap(idx) ? 1 : 0;
+ icon_ofs.x -= hsep;
+ icon_ofs.x -= wrap_icon[wrap_type]->get_width();
+ te->draw_texture(wrap_icon[wrap_type], icon_ofs);
- icon_ofs.x-=hsep;
- te->draw_line(Point2(icon_ofs.x,ofs.y+y),Point2(icon_ofs.x,ofs.y+y+h),sepcolor);
+ icon_ofs.x -= hsep;
+ te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor);
- track_ofs[1]=size.width-icon_ofs.x;
+ track_ofs[1] = size.width - icon_ofs.x;
- icon_ofs.x-=down_icon->get_width();
- te->draw_texture(down_icon,icon_ofs);
+ icon_ofs.x -= down_icon->get_width();
+ te->draw_texture(down_icon, icon_ofs);
int interp_type = animation->track_get_interpolation_type(idx);
- ERR_CONTINUE(interp_type<0 || interp_type>=3);
- icon_ofs.x-=hsep;
- icon_ofs.x-=interp_icon[interp_type]->get_width();
- te->draw_texture(interp_icon[interp_type],icon_ofs);
-
- icon_ofs.x-=hsep;
- te->draw_line(Point2(icon_ofs.x,ofs.y+y),Point2(icon_ofs.x,ofs.y+y+h),sepcolor);
+ ERR_CONTINUE(interp_type < 0 || interp_type >= 3);
+ icon_ofs.x -= hsep;
+ icon_ofs.x -= interp_icon[interp_type]->get_width();
+ te->draw_texture(interp_icon[interp_type], icon_ofs);
- track_ofs[2]=size.width-icon_ofs.x;
+ icon_ofs.x -= hsep;
+ te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor);
- if (animation->track_get_type(idx)==Animation::TYPE_VALUE) {
+ track_ofs[2] = size.width - icon_ofs.x;
+ if (animation->track_get_type(idx) == Animation::TYPE_VALUE) {
int umode = animation->value_track_get_update_mode(idx);
- icon_ofs.x-=hsep;
- icon_ofs.x-=down_icon->get_width();
- te->draw_texture(down_icon,icon_ofs);
+ icon_ofs.x -= hsep;
+ icon_ofs.x -= down_icon->get_width();
+ te->draw_texture(down_icon, icon_ofs);
- icon_ofs.x-=hsep;
- icon_ofs.x-=cont_icon[umode]->get_width();
- te->draw_texture(cont_icon[umode],icon_ofs);
+ icon_ofs.x -= hsep;
+ icon_ofs.x -= cont_icon[umode]->get_width();
+ te->draw_texture(cont_icon[umode], icon_ofs);
} else {
- icon_ofs.x -= hsep*2 + cont_icon[0]->get_width() + down_icon->get_width();
+ icon_ofs.x -= hsep * 2 + cont_icon[0]->get_width() + down_icon->get_width();
}
- icon_ofs.x-=hsep;
- te->draw_line(Point2(icon_ofs.x,ofs.y+y),Point2(icon_ofs.x,ofs.y+y+h),sepcolor);
+ icon_ofs.x -= hsep;
+ te->draw_line(Point2(icon_ofs.x, ofs.y + y), Point2(icon_ofs.x, ofs.y + y + h), sepcolor);
- track_ofs[3]=size.width-icon_ofs.x;
+ track_ofs[3] = size.width - icon_ofs.x;
- icon_ofs.x-=hsep;
- icon_ofs.x-=add_key_icon->get_width();
- te->draw_texture((mouse_over.over==MouseOver::OVER_ADD_KEY && mouse_over.track==idx)?add_key_icon_hl:add_key_icon,icon_ofs);
+ icon_ofs.x -= hsep;
+ icon_ofs.x -= add_key_icon->get_width();
+ te->draw_texture((mouse_over.over == MouseOver::OVER_ADD_KEY && mouse_over.track == idx) ? add_key_icon_hl : add_key_icon, icon_ofs);
- track_ofs[4]=size.width-icon_ofs.x;
+ track_ofs[4] = size.width - icon_ofs.x;
//draw the keys;
int tt = animation->track_get_type(idx);
- float key_vofs = Math::floor((float)(h - type_icon[tt]->get_height())/2);
- float key_hofs = -Math::floor((float)type_icon[tt]->get_height()/2);
-
- int kc=animation->track_get_key_count(idx);
- bool first=true;
+ float key_vofs = Math::floor((float)(h - type_icon[tt]->get_height()) / 2);
+ float key_hofs = -Math::floor((float)type_icon[tt]->get_height() / 2);
+ int kc = animation->track_get_key_count(idx);
+ bool first = true;
+ for (int i = 0; i < kc; i++) {
- for(int i=0;i<kc;i++) {
-
-
- float time = animation->track_get_key_time(idx,i);
- if (time<keys_from)
+ float time = animation->track_get_key_time(idx, i);
+ if (time < keys_from)
continue;
- if (time>keys_to) {
+ if (time > keys_to) {
- if (first && i>0 && animation->track_get_key_value(idx,i)==animation->track_get_key_value(idx,i-1)) {
+ if (first && i > 0 && animation->track_get_key_value(idx, i) == animation->track_get_key_value(idx, i - 1)) {
//draw whole line
- te->draw_line(ofs+Vector2(name_limit,y+h/2),ofs+Point2(settings_limit,y+h/2),color);
+ te->draw_line(ofs + Vector2(name_limit, y + h / 2), ofs + Point2(settings_limit, y + h / 2), color);
}
break;
}
- float x = key_hofs + name_limit + (time-keys_from)*zoom_scale;
+ float x = key_hofs + name_limit + (time - keys_from) * zoom_scale;
Ref<Texture> tex = type_icon[tt];
SelectedKey sk;
- sk.key=i;
- sk.track=idx;
+ sk.key = i;
+ sk.track = idx;
if (selection.has(sk)) {
- if (click.click==ClickOver::CLICK_MOVE_KEYS)
+ if (click.click == ClickOver::CLICK_MOVE_KEYS)
continue;
- tex=type_selected;
+ tex = type_selected;
}
- if (mouse_over.over==MouseOver::OVER_KEY && mouse_over.track==idx && mouse_over.over_key==i)
- tex=type_hover;
+ if (mouse_over.over == MouseOver::OVER_KEY && mouse_over.track == idx && mouse_over.over_key == i)
+ tex = type_hover;
- Variant value = animation->track_get_key_value(idx,i);
- if (first && i>0 && value==animation->track_get_key_value(idx,i-1)) {
+ Variant value = animation->track_get_key_value(idx, i);
+ if (first && i > 0 && value == animation->track_get_key_value(idx, i - 1)) {
- te->draw_line(ofs+Vector2(name_limit,y+h/2),ofs+Point2(x,y+h/2),color);
+ te->draw_line(ofs + Vector2(name_limit, y + h / 2), ofs + Point2(x, y + h / 2), color);
}
- if (i<kc-1 && value==animation->track_get_key_value(idx,i+1)) {
- float x_n = key_hofs + name_limit + (animation->track_get_key_time(idx,i+1)-keys_from)*zoom_scale;
-
- x_n = MIN( x_n, settings_limit);
- te->draw_line(ofs+Point2(x_n,y+h/2),ofs+Point2(x,y+h/2),color);
+ if (i < kc - 1 && value == animation->track_get_key_value(idx, i + 1)) {
+ float x_n = key_hofs + name_limit + (animation->track_get_key_time(idx, i + 1) - keys_from) * zoom_scale;
+ x_n = MIN(x_n, settings_limit);
+ te->draw_line(ofs + Point2(x_n, y + h / 2), ofs + Point2(x, y + h / 2), color);
}
- if (prop_exists && !Variant::can_convert(value.get_type(),valid_type)) {
- te->draw_texture(invalid_icon,ofs+Point2(x,y+key_vofs).floor());
+ if (prop_exists && !Variant::can_convert(value.get_type(), valid_type)) {
+ te->draw_texture(invalid_icon, ofs + Point2(x, y + key_vofs).floor());
}
- if (prop_exists && !Variant::can_convert(value.get_type(),valid_type)) {
- if (tex==type_hover)
- te->draw_texture(invalid_icon_hover,ofs+Point2(x,y+key_vofs).floor());
+ if (prop_exists && !Variant::can_convert(value.get_type(), valid_type)) {
+ if (tex == type_hover)
+ te->draw_texture(invalid_icon_hover, ofs + Point2(x, y + key_vofs).floor());
else
- te->draw_texture(invalid_icon,ofs+Point2(x,y+key_vofs).floor());
+ te->draw_texture(invalid_icon, ofs + Point2(x, y + key_vofs).floor());
} else {
- te->draw_texture(tex,ofs+Point2(x,y+key_vofs).floor());
+ te->draw_texture(tex, ofs + Point2(x, y + key_vofs).floor());
}
-
- first=false;
+ first = false;
}
-
}
- switch(click.click) {
+ switch (click.click) {
case ClickOver::CLICK_SELECT_KEYS: {
- te->draw_rect(Rect2(click.at,click.to-click.at),Color(0.7,0.7,1.0,0.5));
+ te->draw_rect(Rect2(click.at, click.to - click.at), Color(0.7, 0.7, 1.0, 0.5));
} break;
case ClickOver::CLICK_MOVE_KEYS: {
float from_t = 1e20;
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
- float t = animation->track_get_key_time(E->key().track,E->key().key);
- if (t<from_t)
- from_t=t;
-
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
+ float t = animation->track_get_key_time(E->key().track, E->key().key);
+ if (t < from_t)
+ from_t = t;
}
- float motion = from_t+(click.to.x - click.at.x)/zoom_scale;
+ float motion = from_t + (click.to.x - click.at.x) / zoom_scale;
if (step->get_value())
- motion = Math::stepify(motion,step->get_value());
-
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
+ motion = Math::stepify(motion, step->get_value());
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
int idx = E->key().track;
- int i = idx-v_scroll->get_value();
- if (i<0 || i>=fit)
+ int i = idx - v_scroll->get_value();
+ if (i < 0 || i >= fit)
continue;
- int y = h+i*h+sep;
+ int y = h + i * h + sep;
- float key_vofs = Math::floor((float)(h - type_selected->get_height())/2);
- float key_hofs = -Math::floor((float)type_selected->get_height()/2);
+ float key_vofs = Math::floor((float)(h - type_selected->get_height()) / 2);
+ float key_hofs = -Math::floor((float)type_selected->get_height() / 2);
- float time = animation->track_get_key_time(idx,E->key().key);
- float diff = time-from_t;
+ float time = animation->track_get_key_time(idx, E->key().key);
+ float diff = time - from_t;
float t = motion + diff;
- float x = (t-keys_from)*zoom_scale;
+ float x = (t - keys_from) * zoom_scale;
//x+=click.to.x - click.at.x;
- if (x<0 || x>=(settings_limit-name_limit))
+ if (x < 0 || x >= (settings_limit - name_limit))
continue;
- x+=name_limit;
-
- te->draw_texture(type_selected,ofs+Point2(x+key_hofs,y+key_vofs).floor());
+ x += name_limit;
+ te->draw_texture(type_selected, ofs + Point2(x + key_hofs, y + key_vofs).floor());
}
} break;
default: {};
}
-
- te_drawing=false;
+ te_drawing = false;
}
-void AnimationKeyEditor::_track_name_changed(const String& p_name) {
+void AnimationKeyEditor::_track_name_changed(const String &p_name) {
ERR_FAIL_COND(!animation.is_valid());
undo_redo->create_action(TTR("Anim Track Rename"));
- undo_redo->add_do_method(animation.ptr(),"track_set_path",track_name_editing,p_name);
- undo_redo->add_undo_method(animation.ptr(),"track_set_path",track_name_editing,animation->track_get_path(track_name_editing));
+ undo_redo->add_do_method(animation.ptr(), "track_set_path", track_name_editing, p_name);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_path", track_name_editing, animation->track_get_path(track_name_editing));
undo_redo->commit_action();
track_name->hide();
-
}
void AnimationKeyEditor::_track_menu_selected(int p_idx) {
-
ERR_FAIL_COND(!animation.is_valid());
- if (interp_editing!=-1) {
+ if (interp_editing != -1) {
- ERR_FAIL_INDEX(interp_editing,animation->get_track_count());
+ ERR_FAIL_INDEX(interp_editing, animation->get_track_count());
undo_redo->create_action(TTR("Anim Track Change Interpolation"));
- undo_redo->add_do_method(animation.ptr(),"track_set_interpolation_type",interp_editing,p_idx);
- undo_redo->add_undo_method(animation.ptr(),"track_set_interpolation_type",interp_editing,animation->track_get_interpolation_type(interp_editing));
+ undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_type", interp_editing, p_idx);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_type", interp_editing, animation->track_get_interpolation_type(interp_editing));
undo_redo->commit_action();
- } else if (cont_editing!=-1) {
+ } else if (cont_editing != -1) {
- ERR_FAIL_INDEX(cont_editing,animation->get_track_count());
+ ERR_FAIL_INDEX(cont_editing, animation->get_track_count());
undo_redo->create_action(TTR("Anim Track Change Value Mode"));
- undo_redo->add_do_method(animation.ptr(),"value_track_set_update_mode",cont_editing,p_idx);
- undo_redo->add_undo_method(animation.ptr(),"value_track_set_update_mode",cont_editing,animation->value_track_get_update_mode(cont_editing));
+ undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", cont_editing, p_idx);
+ undo_redo->add_undo_method(animation.ptr(), "value_track_set_update_mode", cont_editing, animation->value_track_get_update_mode(cont_editing));
undo_redo->commit_action();
- } else if (wrap_editing!=-1) {
+ } else if (wrap_editing != -1) {
- ERR_FAIL_INDEX(wrap_editing,animation->get_track_count());
+ ERR_FAIL_INDEX(wrap_editing, animation->get_track_count());
undo_redo->create_action(TTR("Anim Track Change Wrap Mode"));
- undo_redo->add_do_method(animation.ptr(),"track_set_interpolation_loop_wrap",wrap_editing,p_idx?true:false);
- undo_redo->add_undo_method(animation.ptr(),"track_set_interpolation_loop_wrap",wrap_editing,animation->track_get_interpolation_loop_wrap(wrap_editing));
+ undo_redo->add_do_method(animation.ptr(), "track_set_interpolation_loop_wrap", wrap_editing, p_idx ? true : false);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_interpolation_loop_wrap", wrap_editing, animation->track_get_interpolation_loop_wrap(wrap_editing));
undo_redo->commit_action();
} else {
switch (p_idx) {
case RIGHT_MENU_DUPLICATE:
- _anim_duplicate_keys(); break;
+ _anim_duplicate_keys();
+ break;
case RIGHT_MENU_DUPLICATE_TRANSPOSE:
- _anim_duplicate_keys(true); break;
+ _anim_duplicate_keys(true);
+ break;
case RIGHT_MENU_REMOVE:
- _anim_delete_keys(); break;
+ _anim_delete_keys();
+ break;
}
}
-
}
struct _AnimMoveRestore {
@@ -1679,59 +1592,54 @@ struct _AnimMoveRestore {
float transition;
};
-void AnimationKeyEditor::_clear_selection_for_anim(const Ref<Animation>& p_anim) {
+void AnimationKeyEditor::_clear_selection_for_anim(const Ref<Animation> &p_anim) {
- if (!(animation==p_anim))
+ if (!(animation == p_anim))
return;
//selection.clear();
_clear_selection();
-
}
-void AnimationKeyEditor::_select_at_anim(const Ref<Animation>& p_anim,int p_track,float p_pos){
+void AnimationKeyEditor::_select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos) {
- if (!(animation==p_anim))
+ if (!(animation == p_anim))
return;
- int idx = animation->track_find_key(p_track,p_pos,true);
- ERR_FAIL_COND(idx<0);
+ int idx = animation->track_find_key(p_track, p_pos, true);
+ ERR_FAIL_COND(idx < 0);
SelectedKey sk;
- sk.track=p_track;
- sk.key=idx;
+ sk.track = p_track;
+ sk.key = idx;
KeyInfo ki;
- ki.pos=p_pos;
-
- selection.insert(sk,ki);
+ ki.pos = p_pos;
+ selection.insert(sk, ki);
}
+PropertyInfo AnimationKeyEditor::_find_hint_for_track(int p_idx, NodePath &r_base_path) {
-PropertyInfo AnimationKeyEditor::_find_hint_for_track(int p_idx,NodePath& r_base_path) {
-
- r_base_path=NodePath();
- ERR_FAIL_COND_V(!animation.is_valid(),PropertyInfo());
- ERR_FAIL_INDEX_V(p_idx,animation->get_track_count(),PropertyInfo());
+ r_base_path = NodePath();
+ ERR_FAIL_COND_V(!animation.is_valid(), PropertyInfo());
+ ERR_FAIL_INDEX_V(p_idx, animation->get_track_count(), PropertyInfo());
if (!root)
return PropertyInfo();
NodePath path = animation->track_get_path(p_idx);
-
if (!root->has_node_and_resource(path))
return PropertyInfo();
RES res;
- Node *node = root->get_node_and_resource(path,res);
-
+ Node *node = root->get_node_and_resource(path, res);
if (node) {
- r_base_path=node->get_path();
+ r_base_path = node->get_path();
}
String property = path.get_property();
- if (property=="")
+ if (property == "")
return PropertyInfo();
List<PropertyInfo> pinfo;
@@ -1740,36 +1648,34 @@ PropertyInfo AnimationKeyEditor::_find_hint_for_track(int p_idx,NodePath& r_base
else
node->get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().name==property)
+ if (E->get().name == property)
return E->get();
}
return PropertyInfo();
}
-
void AnimationKeyEditor::_curve_transition_changed(float p_what) {
- if (selection.size()==0)
+ if (selection.size() == 0)
return;
- if (selection.size()==1)
- undo_redo->create_action(TTR("Edit Node Curve"),UndoRedo::MERGE_ENDS);
+ if (selection.size() == 1)
+ undo_redo->create_action(TTR("Edit Node Curve"), UndoRedo::MERGE_ENDS);
else
- undo_redo->create_action(TTR("Edit Selection Curve"),UndoRedo::MERGE_ENDS);
+ undo_redo->create_action(TTR("Edit Selection Curve"), UndoRedo::MERGE_ENDS);
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
int track = E->key().track;
int key = E->key().key;
- float prev_val = animation->track_get_key_transition(track,key);
- undo_redo->add_do_method(animation.ptr(),"track_set_key_transition",track,key,p_what);
- undo_redo->add_undo_method(animation.ptr(),"track_set_key_transition",track,key,prev_val);
+ float prev_val = animation->track_get_key_transition(track, key);
+ undo_redo->add_do_method(animation.ptr(), "track_set_key_transition", track, key, p_what);
+ undo_redo->add_undo_method(animation.ptr(), "track_set_key_transition", track, key, prev_val);
}
undo_redo->commit_action();
-
}
void AnimationKeyEditor::_toggle_edit_curves() {
@@ -1780,12 +1686,11 @@ void AnimationKeyEditor::_toggle_edit_curves() {
key_editor_tab->hide();
}
-
bool AnimationKeyEditor::_edit_if_single_selection() {
- if (selection.size()!=1) {
+ if (selection.size() != 1) {
- if (selection.size()==0) {
+ if (selection.size() == 0) {
curve_edit->set_mode(AnimationCurveEdit::MODE_DISABLED);
//print_line("disable");
} else {
@@ -1794,12 +1699,11 @@ bool AnimationKeyEditor::_edit_if_single_selection() {
curve_edit->set_transition(1.0);
curve_edit->clear_multiples();
//add all
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
- curve_edit->set_multiple(animation->track_get_key_transition(E->key().track,E->key().key));
+ curve_edit->set_multiple(animation->track_get_key_transition(E->key().track, E->key().key));
}
//print_line("multiple");
-
}
return false;
}
@@ -1810,36 +1714,33 @@ bool AnimationKeyEditor::_edit_if_single_selection() {
int key = selection.front()->key().key;
{
- key_edit->animation=animation;
- key_edit->track=idx;
- key_edit->key_ofs=animation->track_get_key_time(idx,key);
- key_edit->hint=_find_hint_for_track(idx,key_edit->base);
+ key_edit->animation = animation;
+ key_edit->track = idx;
+ key_edit->key_ofs = animation->track_get_key_time(idx, key);
+ key_edit->hint = _find_hint_for_track(idx, key_edit->base);
key_edit->notify_change();
- curve_edit->set_transition(animation->track_get_key_transition(idx,key));
+ curve_edit->set_transition(animation->track_get_key_transition(idx, key));
/*key_edit_dialog->set_size( Size2( 200,200) );
key_edit_dialog->set_pos( track_editor->get_global_pos() + ofs + mpos +Point2(-100,20));
key_edit_dialog->popup();*/
-
}
return true;
-
}
void AnimationKeyEditor::_anim_delete_keys() {
if (selection.size()) {
undo_redo->create_action(TTR("Anim Delete Keys"));
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- undo_redo->add_do_method(animation.ptr(),"track_remove_key",E->key().track,E->key().key);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",E->key().track,E->get().pos,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
}
- undo_redo->add_do_method(this,"_clear_selection_for_anim",animation);
- undo_redo->add_undo_method(this,"_clear_selection_for_anim",animation);
+ undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
+ undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
undo_redo->commit_action();
//selection.clear();
accept_event();
@@ -1847,70 +1748,69 @@ void AnimationKeyEditor::_anim_delete_keys() {
}
}
-void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
+void AnimationKeyEditor::_track_editor_gui_input(const InputEvent &p_input) {
- Control *te=track_editor;
- Ref<StyleBox> style = get_stylebox("normal","TextEdit");
+ Control *te = track_editor;
+ Ref<StyleBox> style = get_stylebox("normal", "TextEdit");
if (!animation.is_valid()) {
return;
}
- Size2 size= te->get_size() - style->get_minimum_size();
+ Size2 size = te->get_size() - style->get_minimum_size();
Size2 ofs = style->get_offset();
- Ref<Font> font = te->get_font("font","Tree");
- int sep = get_constant("vseparation","Tree");
- int hsep = get_constant("hseparation","Tree");
- Ref<Texture> remove_icon = get_icon("Remove","EditorIcons");
- Ref<Texture> move_up_icon = get_icon("MoveUp","EditorIcons");
- Ref<Texture> move_down_icon = get_icon("MoveDown","EditorIcons");
- Ref<Texture> down_icon = get_icon("select_arrow","Tree");
- Ref<Texture> hsize_icon = get_icon("Hsize","EditorIcons");
- Ref<Texture> add_key_icon = get_icon("TrackAddKey","EditorIcons");
-
- Ref<Texture> wrap_icon[2]={
- get_icon("InterpWrapClamp","EditorIcons"),
- get_icon("InterpWrapLoop","EditorIcons"),
+ Ref<Font> font = te->get_font("font", "Tree");
+ int sep = get_constant("vseparation", "Tree");
+ int hsep = get_constant("hseparation", "Tree");
+ Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons");
+ Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons");
+ Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons");
+ Ref<Texture> down_icon = get_icon("select_arrow", "Tree");
+ Ref<Texture> hsize_icon = get_icon("Hsize", "EditorIcons");
+ Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons");
+
+ Ref<Texture> wrap_icon[2] = {
+ get_icon("InterpWrapClamp", "EditorIcons"),
+ get_icon("InterpWrapLoop", "EditorIcons"),
};
- Ref<Texture> interp_icon[3]={
- get_icon("InterpRaw","EditorIcons"),
- get_icon("InterpLinear","EditorIcons"),
- get_icon("InterpCubic","EditorIcons")
+ Ref<Texture> interp_icon[3] = {
+ get_icon("InterpRaw", "EditorIcons"),
+ get_icon("InterpLinear", "EditorIcons"),
+ get_icon("InterpCubic", "EditorIcons")
};
- Ref<Texture> cont_icon[3]={
- get_icon("TrackContinuous","EditorIcons"),
- get_icon("TrackDiscrete","EditorIcons"),
- get_icon("TrackTrigger","EditorIcons")
+ Ref<Texture> cont_icon[3] = {
+ get_icon("TrackContinuous", "EditorIcons"),
+ get_icon("TrackDiscrete", "EditorIcons"),
+ get_icon("TrackTrigger", "EditorIcons")
};
- Ref<Texture> type_icon[3]={
- get_icon("KeyValue","EditorIcons"),
- get_icon("KeyXform","EditorIcons"),
- get_icon("KeyCall","EditorIcons")
+ Ref<Texture> type_icon[3] = {
+ get_icon("KeyValue", "EditorIcons"),
+ get_icon("KeyXform", "EditorIcons"),
+ get_icon("KeyCall", "EditorIcons")
};
- int right_separator_ofs = down_icon->get_width() *3 + add_key_icon->get_width() + interp_icon[0]->get_width() + wrap_icon[0]->get_width() + cont_icon[0]->get_width() + hsep*9;
+ int right_separator_ofs = down_icon->get_width() * 3 + add_key_icon->get_width() + interp_icon[0]->get_width() + wrap_icon[0]->get_width() + cont_icon[0]->get_width() + hsep * 9;
- int h = font->get_height()+sep;
+ int h = font->get_height() + sep;
- int fit = (size.height / h)-1;
+ int fit = (size.height / h) - 1;
int total = animation->get_track_count();
if (total < fit) {
v_scroll->hide();
} else {
v_scroll->show();
- v_scroll->set_max( total );
- v_scroll->set_page( fit );
+ v_scroll->set_max(total);
+ v_scroll->set_page(fit);
}
int settings_limit = size.width - right_separator_ofs;
int name_limit = settings_limit * name_column_ratio;
-
- switch(p_input.type) {
+ switch (p_input.type) {
case InputEvent::KEY: {
- if (p_input.key.scancode==KEY_D && p_input.key.pressed && p_input.key.mod.command) {
+ if (p_input.key.scancode == KEY_D && p_input.key.pressed && p_input.key.mod.command) {
if (p_input.key.mod.shift)
_menu_track(TRACK_MENU_DUPLICATE_TRANSPOSE);
@@ -1919,10 +1819,10 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
accept_event();
- } else if (p_input.key.scancode==KEY_DELETE && p_input.key.pressed && click.click==ClickOver::CLICK_NONE) {
+ } else if (p_input.key.scancode == KEY_DELETE && p_input.key.pressed && click.click == ClickOver::CLICK_NONE) {
_anim_delete_keys();
- } else if (animation.is_valid() && animation->get_track_count()>0) {
+ } else if (animation.is_valid() && animation->get_track_count() > 0) {
if (p_input.is_pressed() && (p_input.is_action("ui_up") || p_input.is_action("ui_page_up"))) {
@@ -1931,19 +1831,16 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (v_scroll->is_visible_in_tree() && p_input.is_action("ui_page_up"))
selected_track--;
- if (selected_track<0)
- selected_track=0;
-
+ if (selected_track < 0)
+ selected_track = 0;
if (v_scroll->is_visible_in_tree()) {
if (v_scroll->get_value() > selected_track)
v_scroll->set_value(selected_track);
-
}
track_editor->update();
accept_event();
-
}
if (p_input.is_pressed() && (p_input.is_action("ui_down") || p_input.is_action("ui_page_down"))) {
@@ -1951,13 +1848,13 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (p_input.is_action("ui_down"))
selected_track++;
else if (v_scroll->is_visible_in_tree() && p_input.is_action("ui_page_down"))
- selected_track+=v_scroll->get_page();
+ selected_track += v_scroll->get_page();
if (selected_track >= animation->get_track_count())
- selected_track=animation->get_track_count()-1;
+ selected_track = animation->get_track_count() - 1;
- if (v_scroll->is_visible_in_tree() && v_scroll->get_page()+v_scroll->get_value() < selected_track+1) {
- v_scroll->set_value(selected_track-v_scroll->get_page()+1);
+ if (v_scroll->is_visible_in_tree() && v_scroll->get_page() + v_scroll->get_value() < selected_track + 1) {
+ v_scroll->set_value(selected_track - v_scroll->get_page() + 1);
}
track_editor->update();
@@ -1965,114 +1862,109 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
}
}
-
} break;
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &mb = p_input.mouse_button;
- if (mb.button_index==BUTTON_WHEEL_UP && mb.pressed) {
+ if (mb.button_index == BUTTON_WHEEL_UP && mb.pressed) {
if (mb.mod.command) {
zoom->set_value(zoom->get_value() + zoom->get_step());
} else {
- v_scroll->set_value( v_scroll->get_value() - v_scroll->get_page() / 8 );
+ v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / 8);
}
}
- if (mb.button_index==BUTTON_WHEEL_DOWN && mb.pressed) {
+ if (mb.button_index == BUTTON_WHEEL_DOWN && mb.pressed) {
if (mb.mod.command) {
zoom->set_value(zoom->get_value() - zoom->get_step());
} else {
- v_scroll->set_value( v_scroll->get_value() + v_scroll->get_page() / 8 );
+ v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / 8);
}
}
- if (mb.button_index==BUTTON_RIGHT && mb.pressed) {
+ if (mb.button_index == BUTTON_RIGHT && mb.pressed) {
- Point2 mpos = Point2(mb.x,mb.y)-ofs;
+ Point2 mpos = Point2(mb.x, mb.y) - ofs;
if (selection.size() == 0) {
// Auto-select on right-click if nothing is selected
// Note: This code is pretty much duplicated from the left click code,
// both codes could be moved into a function to avoid the duplicated code.
- Point2 mpos = Point2(mb.x,mb.y)-ofs;
+ Point2 mpos = Point2(mb.x, mb.y) - ofs;
- if (mpos.y < h ) {
+ if (mpos.y < h) {
return;
}
mpos.y -= h;
int idx = mpos.y / h;
- idx+=v_scroll->get_value();
- if (idx <0 || idx>=animation->get_track_count())
+ idx += v_scroll->get_value();
+ if (idx < 0 || idx >= animation->get_track_count())
break;
if (mpos.x < name_limit) {
} else if (mpos.x < settings_limit) {
float pos = mpos.x - name_limit;
- pos/=_get_zoom_scale();
- pos+=h_scroll->get_value();
- float w_time = (type_icon[0]->get_width() / _get_zoom_scale())/2.0;
+ pos /= _get_zoom_scale();
+ pos += h_scroll->get_value();
+ float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0;
- int kidx = animation->track_find_key(idx,pos);
- int kidx_n = kidx+1;
- int key=-1;
+ int kidx = animation->track_find_key(idx, pos);
+ int kidx_n = kidx + 1;
+ int key = -1;
- if (kidx>=0 && kidx<animation->track_get_key_count(idx)) {
+ if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx);
+ if (ABS(pos - kpos) <= w_time) {
- key=kidx;
+ key = kidx;
}
}
- if (key==-1 && kidx_n>=0 && kidx_n<animation->track_get_key_count(idx)) {
+ if (key == -1 && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx_n);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx_n);
+ if (ABS(pos - kpos) <= w_time) {
- key=kidx_n;
+ key = kidx_n;
}
}
- if (key==-1) {
+ if (key == -1) {
- click.click=ClickOver::CLICK_SELECT_KEYS;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
- click.shift=mb.mod.shift;
- selected_track=idx;
+ click.click = ClickOver::CLICK_SELECT_KEYS;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
+ click.shift = mb.mod.shift;
+ selected_track = idx;
track_editor->update();
//drag select region
return;
-
}
-
-
SelectedKey sk;
- sk.track=idx;
- sk.key=key;
+ sk.track = idx;
+ sk.key = key;
KeyInfo ki;
- ki.pos= animation->track_get_key_time(idx,key);
- click.shift=mb.mod.shift;
- click.selk=sk;
-
+ ki.pos = animation->track_get_key_time(idx, key);
+ click.shift = mb.mod.shift;
+ click.selk = sk;
if (!mb.mod.shift && !selection.has(sk))
_clear_selection();
- selection.insert(sk,ki);
+ selection.insert(sk, ki);
- click.click=ClickOver::CLICK_MOVE_KEYS;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
+ click.click = ClickOver::CLICK_MOVE_KEYS;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
update();
- selected_track=idx;
+ selected_track = idx;
track_editor->update();
if (_edit_if_single_selection() && mb.mod.command) {
@@ -2085,59 +1977,54 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (selection.size()) {
// User has right clicked and we have a selection, show a popup menu with options
track_menu->clear();
- track_menu->set_size(Point2(1,1));
+ track_menu->set_size(Point2(1, 1));
track_menu->add_item(TTR("Duplicate Selection"), RIGHT_MENU_DUPLICATE);
track_menu->add_item(TTR("Duplicate Transposed"), RIGHT_MENU_DUPLICATE_TRANSPOSE);
track_menu->add_item(TTR("Remove Selection"), RIGHT_MENU_REMOVE);
- track_menu->set_pos(te->get_global_pos()+mpos);
+ track_menu->set_pos(te->get_global_pos() + mpos);
- interp_editing=-1;
- cont_editing=-1;
- wrap_editing=-1;
+ interp_editing = -1;
+ cont_editing = -1;
+ wrap_editing = -1;
track_menu->popup();
}
}
- if (mb.button_index==BUTTON_LEFT && !(mb.button_mask&~BUTTON_MASK_LEFT)) {
-
+ if (mb.button_index == BUTTON_LEFT && !(mb.button_mask & ~BUTTON_MASK_LEFT)) {
if (mb.pressed) {
- Point2 mpos = Point2(mb.x,mb.y)-ofs;
-
- if (mpos.y < h ) {
-
+ Point2 mpos = Point2(mb.x, mb.y) - ofs;
- if (mpos.x<name_limit && mpos.x > (name_limit - hsep - hsize_icon->get_width())) {
+ if (mpos.y < h) {
+ if (mpos.x < name_limit && mpos.x > (name_limit - hsep - hsize_icon->get_width())) {
- click.click=ClickOver::CLICK_RESIZE_NAMES;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
- click.at.y=name_limit;
-
+ click.click = ClickOver::CLICK_RESIZE_NAMES;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
+ click.at.y = name_limit;
}
- if (mpos.x>=name_limit && mpos.x<settings_limit) {
+ if (mpos.x >= name_limit && mpos.x < settings_limit) {
//seek
//int zoomw = settings_limit-name_limit;
float scale = _get_zoom_scale();
- float pos = h_scroll->get_value() + (mpos.x-name_limit) / scale;
+ float pos = h_scroll->get_value() + (mpos.x - name_limit) / scale;
if (animation->get_step())
- pos=Math::stepify(pos,animation->get_step());
-
- if (pos<0 )
- pos=0;
- if (pos>=animation->get_length())
- pos=animation->get_length();
- timeline_pos=pos;
- click.click=ClickOver::CLICK_DRAG_TIMELINE;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
- emit_signal("timeline_changed",pos,false);
-
+ pos = Math::stepify(pos, animation->get_step());
+
+ if (pos < 0)
+ pos = 0;
+ if (pos >= animation->get_length())
+ pos = animation->get_length();
+ timeline_pos = pos;
+ click.click = ClickOver::CLICK_DRAG_TIMELINE;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
+ emit_signal("timeline_changed", pos, false);
}
return;
@@ -2146,17 +2033,17 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
mpos.y -= h;
int idx = mpos.y / h;
- idx+=v_scroll->get_value();
- if (idx <0)
+ idx += v_scroll->get_value();
+ if (idx < 0)
break;
- if (idx>=animation->get_track_count()) {
+ if (idx >= animation->get_track_count()) {
- if (mpos.x >= name_limit && mpos.x<settings_limit) {
+ if (mpos.x >= name_limit && mpos.x < settings_limit) {
- click.click=ClickOver::CLICK_SELECT_KEYS;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
+ click.click = ClickOver::CLICK_SELECT_KEYS;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
//drag select region
}
@@ -2167,85 +2054,81 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
//name column
// area
- if (idx!=selected_track) {
+ if (idx != selected_track) {
- selected_track=idx;
+ selected_track = idx;
track_editor->update();
break;
}
- Rect2 area(ofs.x,ofs.y+((int(mpos.y)/h)+1)*h,name_limit, h );
+ Rect2 area(ofs.x, ofs.y + ((int(mpos.y) / h) + 1) * h, name_limit, h);
track_name->set_text(animation->track_get_path(idx));
- track_name->set_pos( te->get_global_pos() + area.pos);
+ track_name->set_pos(te->get_global_pos() + area.pos);
track_name->set_size(area.size);
track_name->show_modal();
track_name->grab_focus();
track_name->select_all();
- track_name_editing=idx;
+ track_name_editing = idx;
} else if (mpos.x < settings_limit) {
float pos = mpos.x - name_limit;
- pos/=_get_zoom_scale();
- pos+=h_scroll->get_value();
- float w_time = (type_icon[0]->get_width() / _get_zoom_scale())/2.0;
+ pos /= _get_zoom_scale();
+ pos += h_scroll->get_value();
+ float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0;
- int kidx = animation->track_find_key(idx,pos);
- int kidx_n = kidx+1;
- int key=-1;
+ int kidx = animation->track_find_key(idx, pos);
+ int kidx_n = kidx + 1;
+ int key = -1;
- if (kidx>=0 && kidx<animation->track_get_key_count(idx)) {
+ if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx);
+ if (ABS(pos - kpos) <= w_time) {
- key=kidx;
+ key = kidx;
}
}
- if (key==-1 && kidx_n>=0 && kidx_n<animation->track_get_key_count(idx)) {
+ if (key == -1 && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx_n);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx_n);
+ if (ABS(pos - kpos) <= w_time) {
- key=kidx_n;
+ key = kidx_n;
}
}
- if (key==-1) {
+ if (key == -1) {
- click.click=ClickOver::CLICK_SELECT_KEYS;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
- click.shift=mb.mod.shift;
- selected_track=idx;
+ click.click = ClickOver::CLICK_SELECT_KEYS;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
+ click.shift = mb.mod.shift;
+ selected_track = idx;
track_editor->update();
//drag select region
return;
-
}
-
-
SelectedKey sk;
- sk.track=idx;
- sk.key=key;
+ sk.track = idx;
+ sk.key = key;
KeyInfo ki;
- ki.pos= animation->track_get_key_time(idx,key);
- click.shift=mb.mod.shift;
- click.selk=sk;
-
+ ki.pos = animation->track_get_key_time(idx, key);
+ click.shift = mb.mod.shift;
+ click.selk = sk;
if (!mb.mod.shift && !selection.has(sk))
_clear_selection();
- selection.insert(sk,ki);
+ selection.insert(sk, ki);
- click.click=ClickOver::CLICK_MOVE_KEYS;
- click.at=Point2(mb.x,mb.y);
- click.to=click.at;
+ click.click = ClickOver::CLICK_MOVE_KEYS;
+ click.at = Point2(mb.x, mb.y);
+ click.to = click.at;
update();
- selected_track=idx;
+ selected_track = idx;
track_editor->update();
if (_edit_if_single_selection() && mb.mod.command) {
@@ -2257,7 +2140,7 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
int ofsx = size.width - mpos.x;
if (ofsx < 0)
break;
-/*
+ /*
if (ofsx < remove_icon->get_width()) {
undo_redo->create_action("Remove Anim Track");
@@ -2318,50 +2201,46 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
ofsx-=hsep*3+move_up_icon->get_width();
*/
-
if (ofsx < track_ofs[1]) {
track_menu->clear();
- track_menu->set_size(Point2(1,1));
- static const char *interp_name[2]={"Clamp Loop Interp","Wrap Loop Interp"};
- for(int i=0;i<2;i++) {
- track_menu->add_icon_item(wrap_icon[i],interp_name[i]);
+ track_menu->set_size(Point2(1, 1));
+ static const char *interp_name[2] = { "Clamp Loop Interp", "Wrap Loop Interp" };
+ for (int i = 0; i < 2; i++) {
+ track_menu->add_icon_item(wrap_icon[i], interp_name[i]);
}
- int popup_y = ofs.y+((int(mpos.y)/h)+2)*h;
- int popup_x = size.width-track_ofs[1];
+ int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h;
+ int popup_x = size.width - track_ofs[1];
- track_menu->set_pos(te->get_global_pos()+Point2(popup_x,popup_y));
+ track_menu->set_pos(te->get_global_pos() + Point2(popup_x, popup_y));
-
- wrap_editing=idx;
- interp_editing=-1;
- cont_editing=-1;
+ wrap_editing = idx;
+ interp_editing = -1;
+ cont_editing = -1;
track_menu->popup();
return;
}
-
if (ofsx < track_ofs[2]) {
track_menu->clear();
- track_menu->set_size(Point2(1,1));
- static const char *interp_name[3]={"Nearest","Linear","Cubic"};
- for(int i=0;i<3;i++) {
- track_menu->add_icon_item(interp_icon[i],interp_name[i]);
+ track_menu->set_size(Point2(1, 1));
+ static const char *interp_name[3] = { "Nearest", "Linear", "Cubic" };
+ for (int i = 0; i < 3; i++) {
+ track_menu->add_icon_item(interp_icon[i], interp_name[i]);
}
- int popup_y = ofs.y+((int(mpos.y)/h)+2)*h;
- int popup_x = size.width-track_ofs[2];
+ int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h;
+ int popup_x = size.width - track_ofs[2];
- track_menu->set_pos(te->get_global_pos()+Point2(popup_x,popup_y));
+ track_menu->set_pos(te->get_global_pos() + Point2(popup_x, popup_y));
-
- interp_editing=idx;
- cont_editing=-1;
- wrap_editing=-1;
+ interp_editing = idx;
+ cont_editing = -1;
+ wrap_editing = -1;
track_menu->popup();
@@ -2371,21 +2250,20 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (ofsx < track_ofs[3]) {
track_menu->clear();
- track_menu->set_size(Point2(1,1));
- String cont_name[3]={TTR("Continuous"),TTR("Discrete"),TTR("Trigger")};
- for(int i=0;i<3;i++) {
- track_menu->add_icon_item(cont_icon[i],cont_name[i]);
+ track_menu->set_size(Point2(1, 1));
+ String cont_name[3] = { TTR("Continuous"), TTR("Discrete"), TTR("Trigger") };
+ for (int i = 0; i < 3; i++) {
+ track_menu->add_icon_item(cont_icon[i], cont_name[i]);
}
+ int popup_y = ofs.y + ((int(mpos.y) / h) + 2) * h;
+ int popup_x = size.width - track_ofs[3];
- int popup_y = ofs.y+((int(mpos.y)/h)+2)*h;
- int popup_x = size.width-track_ofs[3];
-
- track_menu->set_pos(te->get_global_pos()+Point2(popup_x,popup_y));
+ track_menu->set_pos(te->get_global_pos() + Point2(popup_x, popup_y));
- interp_editing=-1;
- wrap_editing=-1;
- cont_editing=idx;
+ interp_editing = -1;
+ wrap_editing = -1;
+ cont_editing = idx;
track_menu->popup();
@@ -2397,85 +2275,76 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
Animation::TrackType tt = animation->track_get_type(idx);
float pos = timeline_pos;
- int existing = animation->track_find_key(idx,pos,true);
-
-
+ int existing = animation->track_find_key(idx, pos, true);
Variant newval;
- if (tt==Animation::TYPE_TRANSFORM) {
+ if (tt == Animation::TYPE_TRANSFORM) {
Dictionary d;
- d["loc"]=Vector3();
- d["rot"]=Quat();
- d["scale"]=Vector3();
- newval=d;
+ d["loc"] = Vector3();
+ d["rot"] = Quat();
+ d["scale"] = Vector3();
+ newval = d;
- } else if (tt==Animation::TYPE_METHOD) {
+ } else if (tt == Animation::TYPE_METHOD) {
Dictionary d;
- d["method"]="";
- d["args"]=Vector<Variant>();
-
+ d["method"] = "";
+ d["args"] = Vector<Variant>();
- newval=d;
- } else if (tt==Animation::TYPE_VALUE) {
+ newval = d;
+ } else if (tt == Animation::TYPE_VALUE) {
NodePath np;
- PropertyInfo inf = _find_hint_for_track(idx,np);
- if (inf.type!=Variant::NIL) {
+ PropertyInfo inf = _find_hint_for_track(idx, np);
+ if (inf.type != Variant::NIL) {
Variant::CallError err;
- newval=Variant::construct(inf.type,NULL,0,err);
-
+ newval = Variant::construct(inf.type, NULL, 0, err);
}
- if (newval.get_type()==Variant::NIL) {
+ if (newval.get_type() == Variant::NIL) {
//popup a new type
- cvi_track=idx;
- cvi_pos=pos;
+ cvi_track = idx;
+ cvi_pos = pos;
- type_menu->set_pos( get_global_pos() + mpos +ofs );
+ type_menu->set_pos(get_global_pos() + mpos + ofs);
type_menu->popup();
return;
}
-
}
undo_redo->create_action(TTR("Anim Add Key"));
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",idx,pos,newval,1);
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",idx,pos);
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", idx, pos, newval, 1);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", idx, pos);
- if (existing!=-1) {
- Variant v = animation->track_get_key_value(idx,existing);
- float trans = animation->track_get_key_transition(idx,existing);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",idx,pos,v,trans);
+ if (existing != -1) {
+ Variant v = animation->track_get_key_value(idx, existing);
+ float trans = animation->track_get_key_transition(idx, existing);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", idx, pos, v, trans);
}
undo_redo->commit_action();
-
return;
}
-
}
} else {
- switch(click.click) {
+ switch (click.click) {
case ClickOver::CLICK_SELECT_KEYS: {
-
- float zoom_scale=_get_zoom_scale();
+ float zoom_scale = _get_zoom_scale();
float keys_from = h_scroll->get_value();
- float keys_to = keys_from + (settings_limit-name_limit) / zoom_scale;
-
- float from_time = keys_from + ( click.at.x - (name_limit+ofs.x)) / zoom_scale;
- float to_time = keys_from + (click.to.x - (name_limit+ofs.x)) / zoom_scale;
+ float keys_to = keys_from + (settings_limit - name_limit) / zoom_scale;
+ float from_time = keys_from + (click.at.x - (name_limit + ofs.x)) / zoom_scale;
+ float to_time = keys_from + (click.to.x - (name_limit + ofs.x)) / zoom_scale;
if (to_time < from_time)
- SWAP(from_time,to_time);
+ SWAP(from_time, to_time);
if (from_time > keys_to || to_time < keys_from)
break;
@@ -2486,30 +2355,26 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (to_time >= keys_to)
to_time = keys_to;
-
- int from_track = int(click.at.y-ofs.y-h-sep) / h + v_scroll->get_value();
- int to_track = int(click.to.y-ofs.y-h-sep) / h + v_scroll->get_value();
- int from_mod = int(click.at.y-ofs.y-sep) % h;
- int to_mod = int(click.to.y-ofs.y-sep) % h;
+ int from_track = int(click.at.y - ofs.y - h - sep) / h + v_scroll->get_value();
+ int to_track = int(click.to.y - ofs.y - h - sep) / h + v_scroll->get_value();
+ int from_mod = int(click.at.y - ofs.y - sep) % h;
+ int to_mod = int(click.to.y - ofs.y - sep) % h;
if (to_track < from_track) {
- SWAP(from_track,to_track);
- SWAP(from_mod,to_mod);
+ SWAP(from_track, to_track);
+ SWAP(from_mod, to_mod);
}
-
-
-
- if ((from_mod > (h/2)) && ((click.at.y-ofs.y)>=(h+sep))) {
+ if ((from_mod > (h / 2)) && ((click.at.y - ofs.y) >= (h + sep))) {
from_track++;
}
- if (to_mod < h/2) {
+ if (to_mod < h / 2) {
to_track--;
}
- if (from_track>to_track) {
+ if (from_track > to_track) {
if (!click.shift)
_clear_selection();
_edit_if_single_selection();
@@ -2517,18 +2382,18 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
}
int tracks_from = v_scroll->get_value();
- int tracks_to = v_scroll->get_value()+fit-1;
- if (tracks_to>=animation->get_track_count())
- tracks_to=animation->get_track_count()-1;
+ int tracks_to = v_scroll->get_value() + fit - 1;
+ if (tracks_to >= animation->get_track_count())
+ tracks_to = animation->get_track_count() - 1;
- tracks_from=0;
- tracks_to=animation->get_track_count()-1;
- if (to_track >tracks_to)
+ tracks_from = 0;
+ tracks_to = animation->get_track_count() - 1;
+ if (to_track > tracks_to)
to_track = tracks_to;
- if (from_track<tracks_from)
- from_track=tracks_from;
+ if (from_track < tracks_from)
+ from_track = tracks_from;
- if (from_track > tracks_to || to_track < tracks_from) {
+ if (from_track > tracks_to || to_track < tracks_from) {
if (!click.shift)
_clear_selection();
_edit_if_single_selection();
@@ -2538,52 +2403,49 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
if (!click.shift)
_clear_selection();
+ int higher_track = 0x7FFFFFFF;
+ for (int i = from_track; i <= to_track; i++) {
- int higher_track=0x7FFFFFFF;
- for(int i=from_track;i<=to_track;i++) {
-
- int kc=animation->track_get_key_count(i);
- for(int j=0;j<kc;j++) {
+ int kc = animation->track_get_key_count(i);
+ for (int j = 0; j < kc; j++) {
- float t = animation->track_get_key_time(i,j);
- if (t<from_time)
+ float t = animation->track_get_key_time(i, j);
+ if (t < from_time)
continue;
- if (t>to_time)
+ if (t > to_time)
break;
- if (i<higher_track)
- higher_track=i;
+ if (i < higher_track)
+ higher_track = i;
SelectedKey sk;
- sk.track=i;
- sk.key=j;
+ sk.track = i;
+ sk.key = j;
KeyInfo ki;
- ki.pos=t;
- selection[sk]=ki;
+ ki.pos = t;
+ selection[sk] = ki;
}
}
- if (higher_track!=0x7FFFFFFF) {
- selected_track=higher_track;
+ if (higher_track != 0x7FFFFFFF) {
+ selected_track = higher_track;
track_editor->update();
}
-
_edit_if_single_selection();
-
} break;
case ClickOver::CLICK_MOVE_KEYS: {
if (selection.empty())
break;
- if (click.at==click.to) {
+ if (click.at == click.to) {
if (!click.shift) {
- KeyInfo ki=selection[click.selk];
+ KeyInfo ki = selection[click.selk];
_clear_selection();
- selection[click.selk]=ki;
+ selection[click.selk] = ki;
_edit_if_single_selection();
}
@@ -2592,114 +2454,103 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
float from_t = 1e20;
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
- float t = animation->track_get_key_time(E->key().track,E->key().key);
- if (t<from_t)
- from_t=t;
-
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
+ float t = animation->track_get_key_time(E->key().track, E->key().key);
+ if (t < from_t)
+ from_t = t;
}
- float motion = from_t+(click.to.x - click.at.x)/_get_zoom_scale();
+ float motion = from_t + (click.to.x - click.at.x) / _get_zoom_scale();
if (step->get_value())
- motion = Math::stepify(motion,step->get_value());
-
-
-
+ motion = Math::stepify(motion, step->get_value());
undo_redo->create_action(TTR("Anim Move Keys"));
List<_AnimMoveRestore> to_restore;
// 1-remove the keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- undo_redo->add_do_method(animation.ptr(),"track_remove_key",E->key().track,E->key().key);
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key);
}
// 2- remove overlapped keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- float newtime = E->get().pos-from_t+motion;
- int idx = animation->track_find_key(E->key().track,newtime,true);
- if (idx==-1)
+ float newtime = E->get().pos - from_t + motion;
+ int idx = animation->track_find_key(E->key().track, newtime, true);
+ if (idx == -1)
continue;
SelectedKey sk;
- sk.key=idx;
- sk.track=E->key().track;
+ sk.key = idx;
+ sk.track = E->key().track;
if (selection.has(sk))
continue; //already in selection, don't save
- undo_redo->add_do_method(animation.ptr(),"track_remove_key_at_pos",E->key().track,newtime);
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_pos", E->key().track, newtime);
_AnimMoveRestore amr;
- amr.key=animation->track_get_key_value(E->key().track,idx);
- amr.track=E->key().track;
- amr.time=newtime;
- amr.transition=animation->track_get_key_transition(E->key().track,idx);
+ amr.key = animation->track_get_key_value(E->key().track, idx);
+ amr.track = E->key().track;
+ amr.time = newtime;
+ amr.transition = animation->track_get_key_transition(E->key().track, idx);
to_restore.push_back(amr);
-
}
// 3-move the keys (re insert them)
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- float newpos=E->get().pos-from_t+motion;
+ float newpos = E->get().pos - from_t + motion;
/*
if (newpos<0)
continue; //no add at the begining
*/
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",E->key().track,newpos,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
-
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
}
// 4-(undo) remove inserted keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- float newpos=E->get().pos+-from_t+motion;
+ float newpos = E->get().pos + -from_t + motion;
/*
if (newpos<0)
continue; //no remove what no inserted
*/
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",E->key().track,newpos);
-
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", E->key().track, newpos);
}
// 5-(undo) reinsert keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",E->key().track,E->get().pos,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
}
// 6-(undo) reinsert overlapped keys
- for(List<_AnimMoveRestore>::Element *E=to_restore.front();E;E=E->next()) {
+ for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) {
_AnimMoveRestore &amr = E->get();
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",amr.track,amr.time,amr.key,amr.transition);
-
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition);
}
// 6-(undo) reinsert overlapped keys
- for(List<_AnimMoveRestore>::Element *E=to_restore.front();E;E=E->next()) {
+ for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) {
_AnimMoveRestore &amr = E->get();
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",amr.track,amr.time,amr.key,amr.transition);
-
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition);
}
- undo_redo->add_do_method(this,"_clear_selection_for_anim",animation);
- undo_redo->add_undo_method(this,"_clear_selection_for_anim",animation);
+ undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
+ undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7-reselect
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- float oldpos=E->get().pos;
- float newpos=oldpos-from_t+motion;
+ float oldpos = E->get().pos;
+ float newpos = oldpos - from_t + motion;
//if (newpos>=0)
- undo_redo->add_do_method(this,"_select_at_anim",animation,E->key().track,newpos);
- undo_redo->add_undo_method(this,"_select_at_anim",animation,E->key().track,oldpos);
-
+ undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos);
+ undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos);
}
undo_redo->commit_action();
@@ -2710,10 +2561,8 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
}
//button released
- click.click=ClickOver::CLICK_NONE;
+ click.click = ClickOver::CLICK_NONE;
track_editor->update();
-
-
}
}
@@ -2723,41 +2572,38 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
const InputEventMouseMotion &mb = p_input.mouse_motion;
- mouse_over.over=MouseOver::OVER_NONE;
- mouse_over.track=-1;
+ mouse_over.over = MouseOver::OVER_NONE;
+ mouse_over.track = -1;
te->update();
track_editor->set_tooltip("");
- if (!track_editor->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
+ if (!track_editor->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
track_editor->call_deferred("grab_focus");
+ if (click.click != ClickOver::CLICK_NONE) {
- if (click.click!=ClickOver::CLICK_NONE) {
-
- switch(click.click) {
+ switch (click.click) {
case ClickOver::CLICK_RESIZE_NAMES: {
-
float base = click.at.y;
- float clickp = click.at.x-ofs.x;
+ float clickp = click.at.x - ofs.x;
float dif = base - clickp;
- float target = mb.x+dif-ofs.x;
+ float target = mb.x + dif - ofs.x;
float ratio = target / settings_limit;
- if (ratio>0.9)
- ratio=0.9;
- else if (ratio<0.2)
- ratio=0.2;
-
- name_column_ratio=ratio;
+ if (ratio > 0.9)
+ ratio = 0.9;
+ else if (ratio < 0.2)
+ ratio = 0.2;
+ name_column_ratio = ratio;
} break;
case ClickOver::CLICK_DRAG_TIMELINE: {
- Point2 mpos = Point2(mb.x,mb.y)-ofs;
+ Point2 mpos = Point2(mb.x, mb.y) - ofs;
/*
if (mpos.x<name_limit)
mpos.x=name_limit;
@@ -2765,73 +2611,66 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
mpos.x=settings_limit;
*/
-
//int zoomw = settings_limit-name_limit;
float scale = _get_zoom_scale();
- float pos = h_scroll->get_value() + (mpos.x-name_limit) / scale;
+ float pos = h_scroll->get_value() + (mpos.x - name_limit) / scale;
if (animation->get_step()) {
- pos=Math::stepify(pos,animation->get_step());
-
+ pos = Math::stepify(pos, animation->get_step());
}
- if (pos<0)
- pos=0;
- if (pos>=animation->get_length())
- pos=animation->get_length();
+ if (pos < 0)
+ pos = 0;
+ if (pos >= animation->get_length())
+ pos = animation->get_length();
if (pos < h_scroll->get_value()) {
h_scroll->set_value(pos);
} else if (pos > h_scroll->get_value() + (settings_limit - name_limit) / scale) {
- h_scroll->set_value( pos - (settings_limit - name_limit) / scale );
+ h_scroll->set_value(pos - (settings_limit - name_limit) / scale);
}
- timeline_pos=pos;
- emit_signal("timeline_changed",pos,true);
-
-
+ timeline_pos = pos;
+ emit_signal("timeline_changed", pos, true);
} break;
case ClickOver::CLICK_SELECT_KEYS: {
- click.to=Point2(mb.x,mb.y);
- if (click.to.y<h && click.at.y>h && mb.relative_y<0) {
+ click.to = Point2(mb.x, mb.y);
+ if (click.to.y < h && click.at.y > h && mb.relative_y < 0) {
float prev = v_scroll->get_value();
- v_scroll->set_value( v_scroll->get_value() -1 );
- if (prev!=v_scroll->get_value())
- click.at.y+=h;
-
-
+ v_scroll->set_value(v_scroll->get_value() - 1);
+ if (prev != v_scroll->get_value())
+ click.at.y += h;
}
- if (click.to.y>size.height && click.at.y<size.height && mb.relative_y>0) {
+ if (click.to.y > size.height && click.at.y < size.height && mb.relative_y > 0) {
float prev = v_scroll->get_value();
- v_scroll->set_value( v_scroll->get_value() +1 );
- if (prev!=v_scroll->get_value())
- click.at.y-=h;
+ v_scroll->set_value(v_scroll->get_value() + 1);
+ if (prev != v_scroll->get_value())
+ click.at.y -= h;
}
} break;
case ClickOver::CLICK_MOVE_KEYS: {
- click.to=Point2(mb.x,mb.y);
+ click.to = Point2(mb.x, mb.y);
} break;
default: {}
}
return;
- } else if (mb.button_mask&BUTTON_MASK_MIDDLE) {
+ } else if (mb.button_mask & BUTTON_MASK_MIDDLE) {
int rel = mb.relative_x;
float relf = rel / _get_zoom_scale();
- h_scroll->set_value( h_scroll->get_value() - relf );
+ h_scroll->set_value(h_scroll->get_value() - relf);
}
- if (mb.button_mask==0) {
-
+ if (mb.button_mask == 0) {
- Point2 mpos = Point2(mb.x,mb.y)-ofs;
+ Point2 mpos = Point2(mb.x, mb.y) - ofs;
- if (mpos.y < h ) {
+ if (mpos.y < h) {
#if 0
//seek
//int zoomw = settings_limit-name_limit;
@@ -2849,130 +2688,123 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
mpos.y -= h;
int idx = mpos.y / h;
- idx+=v_scroll->get_value();
- if (idx <0 || idx>=animation->get_track_count())
+ idx += v_scroll->get_value();
+ if (idx < 0 || idx >= animation->get_track_count())
break;
- mouse_over.track=idx;
+ mouse_over.track = idx;
if (mpos.x < name_limit) {
//name column
-
- mouse_over.over=MouseOver::OVER_NAME;
+ mouse_over.over = MouseOver::OVER_NAME;
} else if (mpos.x < settings_limit) {
float pos = mpos.x - name_limit;
- pos/=_get_zoom_scale();
- pos+=h_scroll->get_value();
- float w_time = (type_icon[0]->get_width() / _get_zoom_scale())/2.0;
+ pos /= _get_zoom_scale();
+ pos += h_scroll->get_value();
+ float w_time = (type_icon[0]->get_width() / _get_zoom_scale()) / 2.0;
- int kidx = animation->track_find_key(idx,pos);
- int kidx_n = kidx+1;
+ int kidx = animation->track_find_key(idx, pos);
+ int kidx_n = kidx + 1;
bool found = false;
- if (kidx>=0 && kidx<animation->track_get_key_count(idx)) {
+ if (kidx >= 0 && kidx < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx);
+ if (ABS(pos - kpos) <= w_time) {
- mouse_over.over=MouseOver::OVER_KEY;
- mouse_over.track=idx;
- mouse_over.over_key=kidx;
- found=true;
+ mouse_over.over = MouseOver::OVER_KEY;
+ mouse_over.track = idx;
+ mouse_over.over_key = kidx;
+ found = true;
}
}
- if (!found && kidx_n>=0 && kidx_n<animation->track_get_key_count(idx)) {
+ if (!found && kidx_n >= 0 && kidx_n < animation->track_get_key_count(idx)) {
- float kpos = animation->track_get_key_time(idx,kidx_n);
- if (ABS(pos-kpos)<=w_time) {
+ float kpos = animation->track_get_key_time(idx, kidx_n);
+ if (ABS(pos - kpos) <= w_time) {
- mouse_over.over=MouseOver::OVER_KEY;
- mouse_over.track=idx;
- mouse_over.over_key=kidx_n;
- found=true;
+ mouse_over.over = MouseOver::OVER_KEY;
+ mouse_over.track = idx;
+ mouse_over.over_key = kidx_n;
+ found = true;
}
}
-
if (found) {
String text;
- text="time: "+rtos(animation->track_get_key_time(idx,mouse_over.over_key))+"\n";
-
+ text = "time: " + rtos(animation->track_get_key_time(idx, mouse_over.over_key)) + "\n";
- switch(animation->track_get_type(idx)) {
+ switch (animation->track_get_type(idx)) {
case Animation::TYPE_TRANSFORM: {
- Dictionary d = animation->track_get_key_value(idx,mouse_over.over_key);
+ Dictionary d = animation->track_get_key_value(idx, mouse_over.over_key);
if (d.has("loc"))
- text+="loc: "+String(d["loc"])+"\n";
+ text += "loc: " + String(d["loc"]) + "\n";
if (d.has("rot"))
- text+="rot: "+String(d["rot"])+"\n";
+ text += "rot: " + String(d["rot"]) + "\n";
if (d.has("scale"))
- text+="scale: "+String(d["scale"])+"\n";
+ text += "scale: " + String(d["scale"]) + "\n";
} break;
case Animation::TYPE_VALUE: {
- Variant v = animation->track_get_key_value(idx,mouse_over.over_key);
+ Variant v = animation->track_get_key_value(idx, mouse_over.over_key);
//text+="value: "+String(v)+"\n";
- bool prop_exists=false;
- Variant::Type valid_type=Variant::NIL;
- Object *obj=NULL;
+ bool prop_exists = false;
+ Variant::Type valid_type = Variant::NIL;
+ Object *obj = NULL;
RES res;
- Node *node = root->get_node_and_resource(animation->track_get_path(idx),res);
+ Node *node = root->get_node_and_resource(animation->track_get_path(idx), res);
if (res.is_valid()) {
- obj=res.ptr();
+ obj = res.ptr();
} else if (node) {
- obj=node;
+ obj = node;
}
if (obj) {
- valid_type=obj->get_static_property_type(animation->track_get_path(idx).get_property(),&prop_exists);
+ valid_type = obj->get_static_property_type(animation->track_get_path(idx).get_property(), &prop_exists);
}
- text+="type: "+Variant::get_type_name(v.get_type())+"\n";
- if (prop_exists && !Variant::can_convert(v.get_type(),valid_type)) {
- text+="value: "+String(v)+" (Invalid, expected type: "+Variant::get_type_name(valid_type)+")\n";
+ text += "type: " + Variant::get_type_name(v.get_type()) + "\n";
+ if (prop_exists && !Variant::can_convert(v.get_type(), valid_type)) {
+ text += "value: " + String(v) + " (Invalid, expected type: " + Variant::get_type_name(valid_type) + ")\n";
} else {
- text+="value: "+String(v)+"\n";
+ text += "value: " + String(v) + "\n";
}
} break;
case Animation::TYPE_METHOD: {
-
- Dictionary d = animation->track_get_key_value(idx,mouse_over.over_key);
+ Dictionary d = animation->track_get_key_value(idx, mouse_over.over_key);
if (d.has("method"))
- text+=String(d["method"]);
- text+="(";
+ text += String(d["method"]);
+ text += "(";
Vector<Variant> args;
if (d.has("args"))
- args=d["args"];
- for(int i=0;i<args.size();i++) {
+ args = d["args"];
+ for (int i = 0; i < args.size(); i++) {
- if (i>0)
- text+=", ";
- text+=String(args[i]);
+ if (i > 0)
+ text += ", ";
+ text += String(args[i]);
}
- text+=")\n";
+ text += ")\n";
} break;
}
- text+="easing: "+rtos(animation->track_get_key_transition(idx,mouse_over.over_key));
-
-
+ text += "easing: " + rtos(animation->track_get_key_transition(idx, mouse_over.over_key));
track_editor->set_tooltip(text);
return;
-
}
} else {
@@ -2980,7 +2812,7 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
int ofsx = size.width - mpos.x;
if (ofsx < 0)
break;
-/*
+ /*
if (ofsx < remove_icon->get_width()) {
mouse_over.over=MouseOver::OVER_REMOVE;
@@ -3008,51 +2840,45 @@ void AnimationKeyEditor::_track_editor_gui_input(const InputEvent& p_input) {
*/
- if (ofsx < down_icon->get_width() + wrap_icon[0]->get_width() + hsep*3) {
+ if (ofsx < down_icon->get_width() + wrap_icon[0]->get_width() + hsep * 3) {
- mouse_over.over=MouseOver::OVER_WRAP;
+ mouse_over.over = MouseOver::OVER_WRAP;
return;
}
- ofsx-=hsep*3+wrap_icon[0]->get_width() + down_icon->get_width();
+ ofsx -= hsep * 3 + wrap_icon[0]->get_width() + down_icon->get_width();
- if (ofsx < down_icon->get_width() + interp_icon[0]->get_width() + hsep*3) {
+ if (ofsx < down_icon->get_width() + interp_icon[0]->get_width() + hsep * 3) {
- mouse_over.over=MouseOver::OVER_INTERP;
+ mouse_over.over = MouseOver::OVER_INTERP;
return;
}
+ ofsx -= hsep * 2 + interp_icon[0]->get_width() + down_icon->get_width();
- ofsx-=hsep*2+interp_icon[0]->get_width() + down_icon->get_width();
-
- if (ofsx < down_icon->get_width() + cont_icon[0]->get_width() +hsep*3) {
+ if (ofsx < down_icon->get_width() + cont_icon[0]->get_width() + hsep * 3) {
- mouse_over.over=MouseOver::OVER_VALUE;
+ mouse_over.over = MouseOver::OVER_VALUE;
return;
}
- ofsx-=hsep*3+cont_icon[0]->get_width() + down_icon->get_width();
+ ofsx -= hsep * 3 + cont_icon[0]->get_width() + down_icon->get_width();
if (ofsx < add_key_icon->get_width()) {
- mouse_over.over=MouseOver::OVER_ADD_KEY;
+ mouse_over.over = MouseOver::OVER_ADD_KEY;
return;
}
-
-
}
-
}
} break;
-
}
}
void AnimationKeyEditor::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_VISIBILITY_CHANGED: {
EditorNode::get_singleton()->update_keying();
@@ -3061,102 +2887,99 @@ void AnimationKeyEditor::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE: {
- key_editor->edit(key_edit);
-
- zoomicon->set_texture( get_icon("Zoom","EditorIcons") );
-
- menu_add_track->set_icon(get_icon("AddTrack","EditorIcons"));
- menu_add_track->get_popup()->add_icon_item(get_icon("KeyValue","EditorIcons"),"Add Normal Track",ADD_TRACK_MENU_ADD_VALUE_TRACK);
- menu_add_track->get_popup()->add_icon_item(get_icon("KeyXform","EditorIcons"),"Add Transform Track",ADD_TRACK_MENU_ADD_TRANSFORM_TRACK);
- menu_add_track->get_popup()->add_icon_item(get_icon("KeyCall","EditorIcons"),"Add Call Func Track",ADD_TRACK_MENU_ADD_CALL_TRACK);
-
- menu_track->set_icon(get_icon("Tools","EditorIcons"));
- menu_track->get_popup()->add_item(TTR("Scale Selection"),TRACK_MENU_SCALE);
- menu_track->get_popup()->add_item(TTR("Scale From Cursor"),TRACK_MENU_SCALE_PIVOT);
- menu_track->get_popup()->add_separator();
- menu_track->get_popup()->add_item(TTR("Duplicate Selection"),TRACK_MENU_DUPLICATE);
- menu_track->get_popup()->add_item(TTR("Duplicate Transposed"),TRACK_MENU_DUPLICATE_TRANSPOSE);
- menu_track->get_popup()->add_separator();
- menu_track->get_popup()->add_item(TTR("Goto Next Step"),TRACK_MENU_NEXT_STEP,KEY_MASK_CMD|KEY_RIGHT);
- menu_track->get_popup()->add_item(TTR("Goto Prev Step"),TRACK_MENU_PREV_STEP,KEY_MASK_CMD|KEY_LEFT);
- menu_track->get_popup()->add_separator();
- PopupMenu *tpp = memnew( PopupMenu );
- tpp->add_item(TTR("Linear"),TRACK_MENU_SET_ALL_TRANS_LINEAR);
- tpp->add_item(TTR("Constant"),TRACK_MENU_SET_ALL_TRANS_CONSTANT);
- tpp->add_item(TTR("In"),TRACK_MENU_SET_ALL_TRANS_IN);
- tpp->add_item(TTR("Out"),TRACK_MENU_SET_ALL_TRANS_OUT);
- tpp->add_item(TTR("In-Out"),TRACK_MENU_SET_ALL_TRANS_INOUT);
- tpp->add_item(TTR("Out-In"),TRACK_MENU_SET_ALL_TRANS_OUTIN);
- tpp->set_name(TTR("Transitions"));
- tpp->connect("id_pressed",this,"_menu_track");
- optimize_dialog->connect("confirmed",this,"_animation_optimize");
-
- menu_track->get_popup()->add_child(tpp);
- //menu_track->get_popup()->add_submenu_item("Set Transitions..","Transitions");
- //menu_track->get_popup()->add_separator();
- menu_track->get_popup()->add_item(TTR("Optimize Animation"),TRACK_MENU_OPTIMIZE);
- menu_track->get_popup()->add_item(TTR("Clean-Up Animation"),TRACK_MENU_CLEAN_UP);
-
- curve_linear->set_icon(get_icon("CurveLinear","EditorIcons"));
- curve_in->set_icon(get_icon("CurveIn","EditorIcons"));
- curve_out->set_icon(get_icon("CurveOut","EditorIcons"));
- curve_inout->set_icon(get_icon("CurveInOut","EditorIcons"));
- curve_outin->set_icon(get_icon("CurveOutIn","EditorIcons"));
- curve_constant->set_icon(get_icon("CurveConstant","EditorIcons"));
-
- curve_linear->connect("pressed",this,"_menu_track",varray(CURVE_SET_LINEAR));
- curve_in->connect("pressed",this,"_menu_track",varray(CURVE_SET_IN));
- curve_out->connect("pressed",this,"_menu_track",varray(CURVE_SET_OUT));
- curve_inout->connect("pressed",this,"_menu_track",varray(CURVE_SET_INOUT));
- curve_outin->connect("pressed",this,"_menu_track",varray(CURVE_SET_OUTIN));
- curve_constant->connect("pressed",this,"_menu_track",varray(CURVE_SET_CONSTANT));
-
-
- move_up_button->set_icon(get_icon("MoveUp","EditorIcons"));
- move_down_button->set_icon(get_icon("MoveDown","EditorIcons"));
- remove_button->set_icon(get_icon("Remove","EditorIcons"));
- edit_button->set_icon(get_icon("EditKey","EditorIcons"));
- edit_button->connect("pressed",this,"_toggle_edit_curves");
-
- loop->set_icon(get_icon("Loop","EditorIcons"));
- curve_edit->connect("transition_changed",this,"_curve_transition_changed");
-
- //edit_button->add_color_override("font_color",get_color("font_color","Tree"));
- //edit_button->add_color_override("font_color_hover",get_color("font_color","Tree"));
-
- {
-
- right_data_size_cache=0;
- int hsep = get_constant("hseparation","Tree");
- Ref<Texture> remove_icon = get_icon("Remove","EditorIcons");
- Ref<Texture> move_up_icon = get_icon("MoveUp","EditorIcons");
- Ref<Texture> move_down_icon = get_icon("MoveDown","EditorIcons");
- Ref<Texture> down_icon = get_icon("select_arrow","Tree");
- Ref<Texture> add_key_icon = get_icon("TrackAddKey","EditorIcons");
- Ref<Texture> interp_icon[3]={
- get_icon("InterpRaw","EditorIcons"),
- get_icon("InterpLinear","EditorIcons"),
- get_icon("InterpCubic","EditorIcons")
- };
- Ref<Texture> cont_icon[3]={
- get_icon("TrackContinuous","EditorIcons"),
- get_icon("TrackDiscrete","EditorIcons"),
- get_icon("TrackTrigger","EditorIcons")
- };
-
- Ref<Texture> wrap_icon[2]={
- get_icon("InterpWrapClamp","EditorIcons"),
- get_icon("InterpWrapLoop","EditorIcons"),
- };
-
- //right_data_size_cache = remove_icon->get_width() + move_up_icon->get_width() + move_down_icon->get_width() + down_icon->get_width() *2 + interp_icon[0]->get_width() + cont_icon[0]->get_width() + add_key_icon->get_width() + hsep*11;
- right_data_size_cache = down_icon->get_width() *3 + add_key_icon->get_width() + interp_icon[0]->get_width() + cont_icon[0]->get_width() + wrap_icon[0]->get_width() + hsep*8;
+ key_editor->edit(key_edit);
+
+ zoomicon->set_texture(get_icon("Zoom", "EditorIcons"));
+
+ menu_add_track->set_icon(get_icon("AddTrack", "EditorIcons"));
+ menu_add_track->get_popup()->add_icon_item(get_icon("KeyValue", "EditorIcons"), "Add Normal Track", ADD_TRACK_MENU_ADD_VALUE_TRACK);
+ menu_add_track->get_popup()->add_icon_item(get_icon("KeyXform", "EditorIcons"), "Add Transform Track", ADD_TRACK_MENU_ADD_TRANSFORM_TRACK);
+ menu_add_track->get_popup()->add_icon_item(get_icon("KeyCall", "EditorIcons"), "Add Call Func Track", ADD_TRACK_MENU_ADD_CALL_TRACK);
+
+ menu_track->set_icon(get_icon("Tools", "EditorIcons"));
+ menu_track->get_popup()->add_item(TTR("Scale Selection"), TRACK_MENU_SCALE);
+ menu_track->get_popup()->add_item(TTR("Scale From Cursor"), TRACK_MENU_SCALE_PIVOT);
+ menu_track->get_popup()->add_separator();
+ menu_track->get_popup()->add_item(TTR("Duplicate Selection"), TRACK_MENU_DUPLICATE);
+ menu_track->get_popup()->add_item(TTR("Duplicate Transposed"), TRACK_MENU_DUPLICATE_TRANSPOSE);
+ menu_track->get_popup()->add_separator();
+ menu_track->get_popup()->add_item(TTR("Goto Next Step"), TRACK_MENU_NEXT_STEP, KEY_MASK_CMD | KEY_RIGHT);
+ menu_track->get_popup()->add_item(TTR("Goto Prev Step"), TRACK_MENU_PREV_STEP, KEY_MASK_CMD | KEY_LEFT);
+ menu_track->get_popup()->add_separator();
+ PopupMenu *tpp = memnew(PopupMenu);
+ tpp->add_item(TTR("Linear"), TRACK_MENU_SET_ALL_TRANS_LINEAR);
+ tpp->add_item(TTR("Constant"), TRACK_MENU_SET_ALL_TRANS_CONSTANT);
+ tpp->add_item(TTR("In"), TRACK_MENU_SET_ALL_TRANS_IN);
+ tpp->add_item(TTR("Out"), TRACK_MENU_SET_ALL_TRANS_OUT);
+ tpp->add_item(TTR("In-Out"), TRACK_MENU_SET_ALL_TRANS_INOUT);
+ tpp->add_item(TTR("Out-In"), TRACK_MENU_SET_ALL_TRANS_OUTIN);
+ tpp->set_name(TTR("Transitions"));
+ tpp->connect("id_pressed", this, "_menu_track");
+ optimize_dialog->connect("confirmed", this, "_animation_optimize");
+
+ menu_track->get_popup()->add_child(tpp);
+ //menu_track->get_popup()->add_submenu_item("Set Transitions..","Transitions");
+ //menu_track->get_popup()->add_separator();
+ menu_track->get_popup()->add_item(TTR("Optimize Animation"), TRACK_MENU_OPTIMIZE);
+ menu_track->get_popup()->add_item(TTR("Clean-Up Animation"), TRACK_MENU_CLEAN_UP);
+
+ curve_linear->set_icon(get_icon("CurveLinear", "EditorIcons"));
+ curve_in->set_icon(get_icon("CurveIn", "EditorIcons"));
+ curve_out->set_icon(get_icon("CurveOut", "EditorIcons"));
+ curve_inout->set_icon(get_icon("CurveInOut", "EditorIcons"));
+ curve_outin->set_icon(get_icon("CurveOutIn", "EditorIcons"));
+ curve_constant->set_icon(get_icon("CurveConstant", "EditorIcons"));
+
+ curve_linear->connect("pressed", this, "_menu_track", varray(CURVE_SET_LINEAR));
+ curve_in->connect("pressed", this, "_menu_track", varray(CURVE_SET_IN));
+ curve_out->connect("pressed", this, "_menu_track", varray(CURVE_SET_OUT));
+ curve_inout->connect("pressed", this, "_menu_track", varray(CURVE_SET_INOUT));
+ curve_outin->connect("pressed", this, "_menu_track", varray(CURVE_SET_OUTIN));
+ curve_constant->connect("pressed", this, "_menu_track", varray(CURVE_SET_CONSTANT));
+
+ move_up_button->set_icon(get_icon("MoveUp", "EditorIcons"));
+ move_down_button->set_icon(get_icon("MoveDown", "EditorIcons"));
+ remove_button->set_icon(get_icon("Remove", "EditorIcons"));
+ edit_button->set_icon(get_icon("EditKey", "EditorIcons"));
+ edit_button->connect("pressed", this, "_toggle_edit_curves");
+
+ loop->set_icon(get_icon("Loop", "EditorIcons"));
+ curve_edit->connect("transition_changed", this, "_curve_transition_changed");
+
+ //edit_button->add_color_override("font_color",get_color("font_color","Tree"));
+ //edit_button->add_color_override("font_color_hover",get_color("font_color","Tree"));
+ {
- }
- call_select->connect("selected",this,"_add_call_track");
- //rename_anim->set_icon( get_icon("Rename","EditorIcons") );
-/*
+ right_data_size_cache = 0;
+ int hsep = get_constant("hseparation", "Tree");
+ Ref<Texture> remove_icon = get_icon("Remove", "EditorIcons");
+ Ref<Texture> move_up_icon = get_icon("MoveUp", "EditorIcons");
+ Ref<Texture> move_down_icon = get_icon("MoveDown", "EditorIcons");
+ Ref<Texture> down_icon = get_icon("select_arrow", "Tree");
+ Ref<Texture> add_key_icon = get_icon("TrackAddKey", "EditorIcons");
+ Ref<Texture> interp_icon[3] = {
+ get_icon("InterpRaw", "EditorIcons"),
+ get_icon("InterpLinear", "EditorIcons"),
+ get_icon("InterpCubic", "EditorIcons")
+ };
+ Ref<Texture> cont_icon[3] = {
+ get_icon("TrackContinuous", "EditorIcons"),
+ get_icon("TrackDiscrete", "EditorIcons"),
+ get_icon("TrackTrigger", "EditorIcons")
+ };
+
+ Ref<Texture> wrap_icon[2] = {
+ get_icon("InterpWrapClamp", "EditorIcons"),
+ get_icon("InterpWrapLoop", "EditorIcons"),
+ };
+
+ //right_data_size_cache = remove_icon->get_width() + move_up_icon->get_width() + move_down_icon->get_width() + down_icon->get_width() *2 + interp_icon[0]->get_width() + cont_icon[0]->get_width() + add_key_icon->get_width() + hsep*11;
+ right_data_size_cache = down_icon->get_width() * 3 + add_key_icon->get_width() + interp_icon[0]->get_width() + cont_icon[0]->get_width() + wrap_icon[0]->get_width() + hsep * 8;
+ }
+ call_select->connect("selected", this, "_add_call_track");
+ //rename_anim->set_icon( get_icon("Rename","EditorIcons") );
+ /*
edit_anim->set_icon( get_icon("Edit","EditorIcons") );
blend_anim->set_icon( get_icon("Blend","EditorIcons") );
play->set_icon( get_icon("Play","EditorIcons") );
@@ -3169,14 +2992,9 @@ void AnimationKeyEditor::_notification(int p_what) {
_update_menu();
} break;
-
-
}
-
}
-
-
void AnimationKeyEditor::_scroll_changed(double) {
if (te_drawing)
@@ -3185,8 +3003,6 @@ void AnimationKeyEditor::_scroll_changed(double) {
track_editor->update();
}
-
-
void AnimationKeyEditor::_update_paths() {
if (animation.is_valid()) {
@@ -3198,16 +3014,14 @@ void AnimationKeyEditor::_update_paths() {
}
}
-
void AnimationKeyEditor::_root_removed() {
- root=NULL;
+ root = NULL;
}
void AnimationKeyEditor::_update_menu() {
-
- updating=true;
+ updating = true;
if (animation.is_valid()) {
@@ -3217,36 +3031,33 @@ void AnimationKeyEditor::_update_menu() {
}
track_editor->update();
- updating=false;
-
+ updating = false;
}
void AnimationKeyEditor::_clear_selection() {
selection.clear();
- key_edit->animation=Ref<Animation>();
- key_edit->track=0;
- key_edit->key_ofs=0;
- key_edit->hint=PropertyInfo();
- key_edit->base=NodePath();
+ key_edit->animation = Ref<Animation>();
+ key_edit->track = 0;
+ key_edit->key_ofs = 0;
+ key_edit->hint = PropertyInfo();
+ key_edit->base = NodePath();
key_edit->notify_change();
-
}
-
-void AnimationKeyEditor::set_animation(const Ref<Animation>& p_anim) {
+void AnimationKeyEditor::set_animation(const Ref<Animation> &p_anim) {
if (animation.is_valid())
- animation->disconnect("changed",this,"_update_paths");
- animation=p_anim;
+ animation->disconnect("changed", this, "_update_paths");
+ animation = p_anim;
if (animation.is_valid())
- animation->connect("changed",this,"_update_paths");
+ animation->connect("changed", this, "_update_paths");
- timeline_pos=0;
+ timeline_pos = 0;
_clear_selection();
_update_paths();
_update_menu();
- selected_track=-1;
+ selected_track = -1;
_edit_if_single_selection();
EditorNode::get_singleton()->update_keying();
@@ -3255,14 +3066,12 @@ void AnimationKeyEditor::set_animation(const Ref<Animation>& p_anim) {
void AnimationKeyEditor::set_root(Node *p_root) {
if (root)
- root->disconnect("tree_exited",this,"_root_removed");
+ root->disconnect("tree_exited", this, "_root_removed");
- root=p_root;
+ root = p_root;
if (root)
- root->connect("tree_exited",this,"_root_removed",make_binds(),CONNECT_ONESHOT);
-
-
+ root->connect("tree_exited", this, "_root_removed", make_binds(), CONNECT_ONESHOT);
}
Node *AnimationKeyEditor::get_root() const {
@@ -3270,22 +3079,16 @@ Node *AnimationKeyEditor::get_root() const {
return root;
}
-
-
-
-
-
void AnimationKeyEditor::update_keying() {
- bool keying_enabled=is_visible_in_tree() && animation.is_valid();
+ bool keying_enabled = is_visible_in_tree() && animation.is_valid();
- if (keying_enabled==keying)
+ if (keying_enabled == keying)
return;
- keying=keying_enabled;
+ keying = keying_enabled;
_update_menu();
emit_signal("keying_changed");
-
}
bool AnimationKeyEditor::has_keying() const {
@@ -3293,98 +3096,93 @@ bool AnimationKeyEditor::has_keying() const {
return keying;
}
-void AnimationKeyEditor::_query_insert(const InsertData& p_id) {
-
+void AnimationKeyEditor::_query_insert(const InsertData &p_id) {
- if (insert_frame!=Engine::get_singleton()->get_frames_drawn()) {
+ if (insert_frame != Engine::get_singleton()->get_frames_drawn()) {
//clear insert list for the frame if frame changed
if (insert_confirm->is_visible_in_tree())
return; //do nothing
insert_data.clear();
- insert_query=false;
+ insert_query = false;
}
- insert_frame=Engine::get_singleton()->get_frames_drawn();
+ insert_frame = Engine::get_singleton()->get_frames_drawn();
- for (List<InsertData>::Element *E=insert_data.front();E;E=E->next()) {
+ for (List<InsertData>::Element *E = insert_data.front(); E; E = E->next()) {
//prevent insertion of multiple tracks
- if (E->get().path==p_id.path)
+ if (E->get().path == p_id.path)
return; //already inserted a track for this on this frame
}
insert_data.push_back(p_id);
- if (p_id.track_idx==-1) {
- if (bool(EDITOR_DEF("editors/animation/confirm_insert_track",true))) {
+ if (p_id.track_idx == -1) {
+ if (bool(EDITOR_DEF("editors/animation/confirm_insert_track", true))) {
//potential new key, does not exist
- if (insert_data.size()==1)
- insert_confirm->set_text(vformat(TTR("Create NEW track for %s and insert key?"),p_id.query));
+ if (insert_data.size() == 1)
+ insert_confirm->set_text(vformat(TTR("Create NEW track for %s and insert key?"), p_id.query));
else
- insert_confirm->set_text(vformat(TTR("Create %d NEW tracks and insert keys?"),insert_data.size()));
+ insert_confirm->set_text(vformat(TTR("Create %d NEW tracks and insert keys?"), insert_data.size()));
insert_confirm->get_ok()->set_text(TTR("Create"));
insert_confirm->popup_centered_minsize();
- insert_query=true;
+ insert_query = true;
} else {
call_deferred("_insert_delay");
- insert_queue=true;
+ insert_queue = true;
}
} else {
if (!insert_query && !insert_queue) {
call_deferred("_insert_delay");
- insert_queue=true;
+ insert_queue = true;
}
}
-
}
-void AnimationKeyEditor::insert_transform_key(Spatial *p_node,const String& p_sub,const Transform& p_xform) {
+void AnimationKeyEditor::insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform) {
if (!keying)
return;
if (!animation.is_valid())
return;
-
ERR_FAIL_COND(!root);
//let's build a node path
String path = root->get_path_to(p_node);
- if (p_sub!="")
- path+=":"+p_sub;
+ if (p_sub != "")
+ path += ":" + p_sub;
- NodePath np=path;
+ NodePath np = path;
- int track_idx=-1;
+ int track_idx = -1;
- for(int i=0;i<animation->get_track_count();i++) {
+ for (int i = 0; i < animation->get_track_count(); i++) {
- if (animation->track_get_type(i)!=Animation::TYPE_TRANSFORM)
+ if (animation->track_get_type(i) != Animation::TYPE_TRANSFORM)
continue;
- if (animation->track_get_path(i)!=np)
+ if (animation->track_get_path(i) != np)
continue;
- track_idx=i;
+ track_idx = i;
break;
}
InsertData id;
Dictionary val;
- id.path=np;
- id.track_idx=track_idx;
- id.value=p_xform;
- id.type=Animation::TYPE_TRANSFORM;
- id.query="node '"+p_node->get_name()+"'";
- id.advance=false;
+ id.path = np;
+ id.track_idx = track_idx;
+ id.value = p_xform;
+ id.type = Animation::TYPE_TRANSFORM;
+ id.query = "node '" + p_node->get_name() + "'";
+ id.advance = false;
//dialog insert
_query_insert(id);
-
}
-
-void AnimationKeyEditor::insert_node_value_key(Node* p_node, const String& p_property,const Variant& p_value,bool p_only_if_exists) {
+void AnimationKeyEditor::insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists) {
ERR_FAIL_COND(!root);
//let's build a node path
@@ -3393,54 +3191,50 @@ void AnimationKeyEditor::insert_node_value_key(Node* p_node, const String& p_pro
String path = root->get_path_to(node);
- for(int i=1;i<history->get_path_size();i++) {
+ for (int i = 1; i < history->get_path_size(); i++) {
String prop = history->get_path_property(i);
- ERR_FAIL_COND(prop=="");
- path+=":"+prop;
+ ERR_FAIL_COND(prop == "");
+ path += ":" + prop;
}
-
- path+=":"+p_property;
+ path += ":" + p_property;
NodePath np = path;
//locate track
- int track_idx=-1;
+ int track_idx = -1;
- for(int i=0;i<animation->get_track_count();i++) {
+ for (int i = 0; i < animation->get_track_count(); i++) {
- if (animation->track_get_type(i)!=Animation::TYPE_VALUE)
+ if (animation->track_get_type(i) != Animation::TYPE_VALUE)
continue;
- if (animation->track_get_path(i)!=np)
+ if (animation->track_get_path(i) != np)
continue;
- track_idx=i;
+ track_idx = i;
break;
}
- if (p_only_if_exists && track_idx==-1)
+ if (p_only_if_exists && track_idx == -1)
return;
InsertData id;
- id.path=np;
- id.track_idx=track_idx;
- id.value=p_value;
- id.type=Animation::TYPE_VALUE;
- id.query="property '"+p_property+"'";
- id.advance=false;
+ id.path = np;
+ id.track_idx = track_idx;
+ id.value = p_value;
+ id.type = Animation::TYPE_VALUE;
+ id.query = "property '" + p_property + "'";
+ id.advance = false;
//dialog insert
_query_insert(id);
-
-
-
}
-void AnimationKeyEditor::insert_value_key(const String& p_property,const Variant& p_value,bool p_advance) {
+void AnimationKeyEditor::insert_value_key(const String &p_property, const Variant &p_value, bool p_advance) {
ERR_FAIL_COND(!root);
//let's build a node path
- ERR_FAIL_COND(history->get_path_size()==0);
+ ERR_FAIL_COND(history->get_path_size() == 0);
Object *obj = ObjectDB::get_instance(history->get_path_object(0));
ERR_FAIL_COND(!obj || !obj->cast_to<Node>());
@@ -3448,110 +3242,104 @@ void AnimationKeyEditor::insert_value_key(const String& p_property,const Variant
String path = root->get_path_to(node);
- for(int i=1;i<history->get_path_size();i++) {
+ for (int i = 1; i < history->get_path_size(); i++) {
String prop = history->get_path_property(i);
- ERR_FAIL_COND(prop=="");
- path+=":"+prop;
+ ERR_FAIL_COND(prop == "");
+ path += ":" + prop;
}
-
-
- path+=":"+p_property;
+ path += ":" + p_property;
NodePath np = path;
//locate track
- int track_idx=-1;
+ int track_idx = -1;
- for(int i=0;i<animation->get_track_count();i++) {
+ for (int i = 0; i < animation->get_track_count(); i++) {
- if (animation->track_get_type(i)!=Animation::TYPE_VALUE)
+ if (animation->track_get_type(i) != Animation::TYPE_VALUE)
continue;
- if (animation->track_get_path(i)!=np)
+ if (animation->track_get_path(i) != np)
continue;
- track_idx=i;
+ track_idx = i;
break;
}
InsertData id;
- id.path=np;
- id.track_idx=track_idx;
- id.value=p_value;
- id.type=Animation::TYPE_VALUE;
- id.query="property '"+p_property+"'";
- id.advance=p_advance;
+ id.path = np;
+ id.track_idx = track_idx;
+ id.value = p_value;
+ id.type = Animation::TYPE_VALUE;
+ id.query = "property '" + p_property + "'";
+ id.advance = p_advance;
//dialog insert
_query_insert(id);
-
-
-
}
void AnimationKeyEditor::_confirm_insert_list() {
-
undo_redo->create_action(TTR("Anim Create & Insert"));
int last_track = animation->get_track_count();
- while(insert_data.size()) {
+ while (insert_data.size()) {
- last_track=_confirm_insert(insert_data.front()->get(),last_track);
+ last_track = _confirm_insert(insert_data.front()->get(), last_track);
insert_data.pop_front();
}
undo_redo->commit_action();
}
-int AnimationKeyEditor::_confirm_insert(InsertData p_id,int p_last_track) {
+int AnimationKeyEditor::_confirm_insert(InsertData p_id, int p_last_track) {
- if (p_last_track==-1)
- p_last_track=animation->get_track_count();
+ if (p_last_track == -1)
+ p_last_track = animation->get_track_count();
- bool created=false;
- if (p_id.track_idx<0) {
+ bool created = false;
+ if (p_id.track_idx < 0) {
- created=true;
+ created = true;
undo_redo->create_action(TTR("Anim Insert Track & Key"));
- Animation::UpdateMode update_mode=Animation::UPDATE_DISCRETE;
+ Animation::UpdateMode update_mode = Animation::UPDATE_DISCRETE;
- if (p_id.type==Animation::TYPE_VALUE) {
+ if (p_id.type == Animation::TYPE_VALUE) {
//wants a new tack
{
//shitty hack
NodePath np;
animation->add_track(p_id.type);
- animation->track_set_path(animation->get_track_count()-1,p_id.path);
- PropertyInfo h = _find_hint_for_track(animation->get_track_count()-1,np);
- animation->remove_track(animation->get_track_count()-1); //hack
-
- if ( h.type==Variant::REAL ||
- h.type==Variant::VECTOR2 ||
- h.type==Variant::RECT2 ||
- h.type==Variant::VECTOR3 ||
- h.type==Variant::RECT3 ||
- h.type==Variant::QUAT ||
- h.type==Variant::COLOR ||
- h.type==Variant::TRANSFORM ) {
-
- update_mode=Animation::UPDATE_CONTINUOUS;
+ animation->track_set_path(animation->get_track_count() - 1, p_id.path);
+ PropertyInfo h = _find_hint_for_track(animation->get_track_count() - 1, np);
+ animation->remove_track(animation->get_track_count() - 1); //hack
+
+ if (h.type == Variant::REAL ||
+ h.type == Variant::VECTOR2 ||
+ h.type == Variant::RECT2 ||
+ h.type == Variant::VECTOR3 ||
+ h.type == Variant::RECT3 ||
+ h.type == Variant::QUAT ||
+ h.type == Variant::COLOR ||
+ h.type == Variant::TRANSFORM) {
+
+ update_mode = Animation::UPDATE_CONTINUOUS;
}
- if (h.usage&PROPERTY_USAGE_ANIMATE_AS_TRIGGER) {
- update_mode=Animation::UPDATE_TRIGGER;
+ if (h.usage & PROPERTY_USAGE_ANIMATE_AS_TRIGGER) {
+ update_mode = Animation::UPDATE_TRIGGER;
}
}
}
- p_id.track_idx=p_last_track;
+ p_id.track_idx = p_last_track;
- undo_redo->add_do_method(animation.ptr(),"add_track",p_id.type);
- undo_redo->add_do_method(animation.ptr(),"track_set_path",p_id.track_idx,p_id.path);
- if (p_id.type==Animation::TYPE_VALUE)
- undo_redo->add_do_method(animation.ptr(),"value_track_set_update_mode",p_id.track_idx,update_mode);
+ undo_redo->add_do_method(animation.ptr(), "add_track", p_id.type);
+ undo_redo->add_do_method(animation.ptr(), "track_set_path", p_id.track_idx, p_id.path);
+ if (p_id.type == Animation::TYPE_VALUE)
+ undo_redo->add_do_method(animation.ptr(), "value_track_set_update_mode", p_id.track_idx, update_mode);
} else {
undo_redo->create_action(TTR("Anim Insert Key"));
@@ -3560,64 +3348,55 @@ int AnimationKeyEditor::_confirm_insert(InsertData p_id,int p_last_track) {
float time = timeline_pos;
Variant value;
-
- switch(p_id.type) {
+ switch (p_id.type) {
case Animation::TYPE_VALUE: {
value = p_id.value;
-
} break;
case Animation::TYPE_TRANSFORM: {
-
Transform tr = p_id.value;
Dictionary d;
- d["loc"]=tr.origin;
- d["scale"]=tr.basis.get_scale();
- d["rot"]=Quat(tr.basis);//.orthonormalized();
- value=d;
+ d["loc"] = tr.origin;
+ d["scale"] = tr.basis.get_scale();
+ d["rot"] = Quat(tr.basis); //.orthonormalized();
+ value = d;
} break;
- default:{}
+ default: {}
}
-
-
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",p_id.track_idx,time,value);
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, value);
if (created) {
//just remove the track
- undo_redo->add_undo_method(animation.ptr(),"remove_track",p_last_track);
+ undo_redo->add_undo_method(animation.ptr(), "remove_track", p_last_track);
p_last_track++;
} else {
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",p_id.track_idx,time);
- int existing = animation->track_find_key(p_id.track_idx,time,true);
- if (existing!=-1) {
- Variant v = animation->track_get_key_value(p_id.track_idx,existing);
- float trans = animation->track_get_key_transition(p_id.track_idx,existing);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",p_id.track_idx,time,v,trans);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", p_id.track_idx, time);
+ int existing = animation->track_find_key(p_id.track_idx, time, true);
+ if (existing != -1) {
+ Variant v = animation->track_get_key_value(p_id.track_idx, existing);
+ float trans = animation->track_get_key_transition(p_id.track_idx, existing);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", p_id.track_idx, time, v, trans);
}
}
- undo_redo->add_do_method(this,"update");
- undo_redo->add_undo_method(this,"update");
- undo_redo->add_do_method(track_editor,"update");
- undo_redo->add_undo_method(track_editor,"update");
- undo_redo->add_do_method(track_pos,"update");
- undo_redo->add_undo_method(track_pos,"update");
+ undo_redo->add_do_method(this, "update");
+ undo_redo->add_undo_method(this, "update");
+ undo_redo->add_do_method(track_editor, "update");
+ undo_redo->add_undo_method(track_editor, "update");
+ undo_redo->add_do_method(track_pos, "update");
+ undo_redo->add_undo_method(track_pos, "update");
undo_redo->commit_action();
return p_last_track;
-
}
-
-
-
Ref<Animation> AnimationKeyEditor::get_current_animation() const {
return animation;
@@ -3625,32 +3404,30 @@ Ref<Animation> AnimationKeyEditor::get_current_animation() const {
void AnimationKeyEditor::_animation_len_changed(float p_len) {
-
if (updating)
return;
if (!animation.is_null()) {
undo_redo->create_action(TTR("Change Anim Len"));
- undo_redo->add_do_method(animation.ptr(),"set_length",p_len);
- undo_redo->add_undo_method(animation.ptr(),"set_length",animation->get_length());
- undo_redo->add_do_method(this,"_animation_len_update");
- undo_redo->add_undo_method(this,"_animation_len_update");
+ undo_redo->add_do_method(animation.ptr(), "set_length", p_len);
+ undo_redo->add_undo_method(animation.ptr(), "set_length", animation->get_length());
+ undo_redo->add_do_method(this, "_animation_len_update");
+ undo_redo->add_undo_method(this, "_animation_len_update");
undo_redo->commit_action();
}
}
void AnimationKeyEditor::_animation_len_update() {
- if (!animation.is_null())
- emit_signal(alc,animation->get_length());
+ if (!animation.is_null())
+ emit_signal(alc, animation->get_length());
}
void AnimationKeyEditor::_animation_changed() {
if (updating)
return;
_update_menu();
-
}
void AnimationKeyEditor::_animation_loop_changed() {
@@ -3661,73 +3438,68 @@ void AnimationKeyEditor::_animation_loop_changed() {
if (!animation.is_null()) {
undo_redo->create_action(TTR("Change Anim Loop"));
- undo_redo->add_do_method(animation.ptr(),"set_loop",loop->is_pressed());
- undo_redo->add_undo_method(animation.ptr(),"set_loop",!loop->is_pressed());
+ undo_redo->add_do_method(animation.ptr(), "set_loop", loop->is_pressed());
+ undo_redo->add_undo_method(animation.ptr(), "set_loop", !loop->is_pressed());
undo_redo->commit_action();
}
-
}
-
void AnimationKeyEditor::_create_value_item(int p_type) {
undo_redo->create_action(TTR("Anim Create Typed Value Key"));
Variant::CallError ce;
- Variant v = Variant::construct(Variant::Type(p_type),NULL,0,ce);
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",cvi_track,cvi_pos,v);
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",cvi_track,cvi_pos);
+ Variant v = Variant::construct(Variant::Type(p_type), NULL, 0, ce);
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", cvi_track, cvi_pos, v);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", cvi_track, cvi_pos);
- int existing = animation->track_find_key(cvi_track,cvi_pos,true);
+ int existing = animation->track_find_key(cvi_track, cvi_pos, true);
- if (existing!=-1) {
- Variant v = animation->track_get_key_value(cvi_track,existing);
- float trans = animation->track_get_key_transition(cvi_track,existing);
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",cvi_track,cvi_pos,v,trans);
+ if (existing != -1) {
+ Variant v = animation->track_get_key_value(cvi_track, existing);
+ float trans = animation->track_get_key_transition(cvi_track, existing);
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", cvi_track, cvi_pos, v, trans);
}
undo_redo->commit_action();
-
}
-
void AnimationKeyEditor::set_anim_pos(float p_pos) {
if (animation.is_null())
return;
- timeline_pos=p_pos;
+ timeline_pos = p_pos;
update();
track_pos->update();
track_editor->update();
}
-void AnimationKeyEditor::_pane_drag(const Point2& p_delta) {
+void AnimationKeyEditor::_pane_drag(const Point2 &p_delta) {
Size2 ecs = ec->get_custom_minimum_size();
- ecs.y-=p_delta.y;
- if (ecs.y<100)
- ecs.y=100;
+ ecs.y -= p_delta.y;
+ if (ecs.y < 100)
+ ecs.y = 100;
ec->set_custom_minimum_size(ecs);
-
}
void AnimationKeyEditor::_insert_delay() {
if (insert_query) {
//discard since it's entered into query mode
- insert_queue=false;
+ insert_queue = false;
return;
}
undo_redo->create_action(TTR("Anim Insert"));
int last_track = animation->get_track_count();
- bool advance=false;
- while(insert_data.size()) {
+ bool advance = false;
+ while (insert_data.size()) {
if (insert_data.front()->get().advance)
- advance=true;
- last_track=_confirm_insert(insert_data.front()->get(),last_track);
+ advance = true;
+ last_track = _confirm_insert(insert_data.front()->get(), last_track);
insert_data.pop_front();
}
@@ -3735,170 +3507,154 @@ void AnimationKeyEditor::_insert_delay() {
if (advance) {
float step = animation->get_step();
- if (step==0)
- step=1;
+ if (step == 0)
+ step = 1;
- float pos=timeline_pos;
+ float pos = timeline_pos;
- pos=Math::stepify(pos+step,step);
- if (pos>animation->get_length())
- pos=animation->get_length();
- timeline_pos=pos;
+ pos = Math::stepify(pos + step, step);
+ if (pos > animation->get_length())
+ pos = animation->get_length();
+ timeline_pos = pos;
track_pos->update();
- emit_signal("timeline_changed",pos,true);
+ emit_signal("timeline_changed", pos, true);
}
- insert_queue=false;
+ insert_queue = false;
}
void AnimationKeyEditor::_step_changed(float p_len) {
- updating=true;
+ updating = true;
if (!animation.is_null()) {
animation->set_step(p_len);
- emit_signal("animation_step_changed",animation->get_step());
+ emit_signal("animation_step_changed", animation->get_step());
}
- updating=false;
+ updating = false;
}
void AnimationKeyEditor::_scale() {
-
if (selection.empty())
return;
-
float from_t = 1e20;
float to_t = -1e20;
float len = -1e20;
- float pivot=0;
-
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.front();E;E=E->next()) {
- float t = animation->track_get_key_time(E->key().track,E->key().key);
- if (t<from_t)
- from_t=t;
- if (t>to_t)
- to_t=t;
+ float pivot = 0;
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.front(); E; E = E->next()) {
+ float t = animation->track_get_key_time(E->key().track, E->key().key);
+ if (t < from_t)
+ from_t = t;
+ if (t > to_t)
+ to_t = t;
}
- len=to_t-from_t;
- if (last_menu_track_opt==TRACK_MENU_SCALE_PIVOT) {
+ len = to_t - from_t;
+ if (last_menu_track_opt == TRACK_MENU_SCALE_PIVOT) {
pivot = timeline_pos;
} else {
- pivot=from_t;
-
+ pivot = from_t;
}
float s = scale->get_value();
- if (s==0) {
+ if (s == 0) {
ERR_PRINT("Can't scale to 0");
}
-
-
undo_redo->create_action(TTR("Anim Scale Keys"));
List<_AnimMoveRestore> to_restore;
// 1-remove the keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- undo_redo->add_do_method(animation.ptr(),"track_remove_key",E->key().track,E->key().key);
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key", E->key().track, E->key().key);
}
// 2- remove overlapped keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
- float newtime = (E->get().pos-from_t)*s+from_t;
- int idx = animation->track_find_key(E->key().track,newtime,true);
- if (idx==-1)
+ float newtime = (E->get().pos - from_t) * s + from_t;
+ int idx = animation->track_find_key(E->key().track, newtime, true);
+ if (idx == -1)
continue;
SelectedKey sk;
- sk.key=idx;
- sk.track=E->key().track;
+ sk.key = idx;
+ sk.track = E->key().track;
if (selection.has(sk))
continue; //already in selection, don't save
- undo_redo->add_do_method(animation.ptr(),"track_remove_key_at_pos",E->key().track,newtime);
+ undo_redo->add_do_method(animation.ptr(), "track_remove_key_at_pos", E->key().track, newtime);
_AnimMoveRestore amr;
- amr.key=animation->track_get_key_value(E->key().track,idx);
- amr.track=E->key().track;
- amr.time=newtime;
- amr.transition=animation->track_get_key_transition(E->key().track,idx);
+ amr.key = animation->track_get_key_value(E->key().track, idx);
+ amr.track = E->key().track;
+ amr.time = newtime;
+ amr.transition = animation->track_get_key_transition(E->key().track, idx);
to_restore.push_back(amr);
-
}
-#define _NEW_POS(m_ofs) (((s>0)?m_ofs:from_t+(len-(m_ofs-from_t)))-pivot)*ABS(s)+from_t
+#define _NEW_POS(m_ofs) (((s > 0) ? m_ofs : from_t + (len - (m_ofs - from_t))) - pivot) * ABS(s) + from_t
// 3-move the keys (re insert them)
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- float newpos=_NEW_POS(E->get().pos);
- undo_redo->add_do_method(animation.ptr(),"track_insert_key",E->key().track,newpos,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ float newpos = _NEW_POS(E->get().pos);
+ undo_redo->add_do_method(animation.ptr(), "track_insert_key", E->key().track, newpos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
}
// 4-(undo) remove inserted keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- float newpos=_NEW_POS(E->get().pos);
- undo_redo->add_undo_method(animation.ptr(),"track_remove_key_at_pos",E->key().track,newpos);
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ float newpos = _NEW_POS(E->get().pos);
+ undo_redo->add_undo_method(animation.ptr(), "track_remove_key_at_pos", E->key().track, newpos);
}
// 5-(undo) reinsert keys
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",E->key().track,E->get().pos,animation->track_get_key_value(E->key().track,E->key().key),animation->track_get_key_transition(E->key().track,E->key().key));
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", E->key().track, E->get().pos, animation->track_get_key_value(E->key().track, E->key().key), animation->track_get_key_transition(E->key().track, E->key().key));
}
// 6-(undo) reinsert overlapped keys
- for(List<_AnimMoveRestore>::Element *E=to_restore.front();E;E=E->next()) {
+ for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) {
_AnimMoveRestore &amr = E->get();
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",amr.track,amr.time,amr.key,amr.transition);
-
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition);
}
// 6-(undo) reinsert overlapped keys
- for(List<_AnimMoveRestore>::Element *E=to_restore.front();E;E=E->next()) {
+ for (List<_AnimMoveRestore>::Element *E = to_restore.front(); E; E = E->next()) {
_AnimMoveRestore &amr = E->get();
- undo_redo->add_undo_method(animation.ptr(),"track_insert_key",amr.track,amr.time,amr.key,amr.transition);
-
+ undo_redo->add_undo_method(animation.ptr(), "track_insert_key", amr.track, amr.time, amr.key, amr.transition);
}
- undo_redo->add_do_method(this,"_clear_selection_for_anim",animation);
- undo_redo->add_undo_method(this,"_clear_selection_for_anim",animation);
+ undo_redo->add_do_method(this, "_clear_selection_for_anim", animation);
+ undo_redo->add_undo_method(this, "_clear_selection_for_anim", animation);
// 7-reselect
- for(Map<SelectedKey,KeyInfo>::Element *E=selection.back();E;E=E->prev()) {
-
- float oldpos=E->get().pos;
- float newpos=_NEW_POS(oldpos);
- if (newpos>=0)
- undo_redo->add_do_method(this,"_select_at_anim",animation,E->key().track,newpos);
- undo_redo->add_undo_method(this,"_select_at_anim",animation,E->key().track,oldpos);
+ for (Map<SelectedKey, KeyInfo>::Element *E = selection.back(); E; E = E->prev()) {
+ float oldpos = E->get().pos;
+ float newpos = _NEW_POS(oldpos);
+ if (newpos >= 0)
+ undo_redo->add_do_method(this, "_select_at_anim", animation, E->key().track, newpos);
+ undo_redo->add_undo_method(this, "_select_at_anim", animation, E->key().track, oldpos);
}
#undef _NEW_POS
undo_redo->commit_action();
-
}
+void AnimationKeyEditor::_add_call_track(const NodePath &p_base) {
-void AnimationKeyEditor::_add_call_track(const NodePath& p_base) {
-
-
- Node* base = EditorNode::get_singleton()->get_edited_scene();
+ Node *base = EditorNode::get_singleton()->get_edited_scene();
if (!base)
return;
- Node* from=base->get_node(p_base);
+ Node *from = base->get_node(p_base);
if (!from || !root)
return;
@@ -3908,11 +3664,10 @@ void AnimationKeyEditor::_add_call_track(const NodePath& p_base) {
//print_line("path: "+String(path));
undo_redo->create_action(TTR("Anim Add Call Track"));
- undo_redo->add_do_method(animation.ptr(),"add_track",Animation::TYPE_METHOD);
- undo_redo->add_do_method(animation.ptr(),"track_set_path",animation->get_track_count(),path);
- undo_redo->add_undo_method(animation.ptr(),"remove_track",animation->get_track_count());
+ undo_redo->add_do_method(animation.ptr(), "add_track", Animation::TYPE_METHOD);
+ undo_redo->add_do_method(animation.ptr(), "track_set_path", animation->get_track_count(), path);
+ undo_redo->add_undo_method(animation.ptr(), "remove_track", animation->get_track_count());
undo_redo->commit_action();
-
}
void AnimationKeyEditor::cleanup() {
@@ -3922,97 +3677,85 @@ void AnimationKeyEditor::cleanup() {
void AnimationKeyEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_root_removed"),&AnimationKeyEditor::_root_removed);
- ClassDB::bind_method(D_METHOD("_scale"),&AnimationKeyEditor::_scale);
- ClassDB::bind_method(D_METHOD("set_root"),&AnimationKeyEditor::set_root);
-
+ ClassDB::bind_method(D_METHOD("_root_removed"), &AnimationKeyEditor::_root_removed);
+ ClassDB::bind_method(D_METHOD("_scale"), &AnimationKeyEditor::_scale);
+ ClassDB::bind_method(D_METHOD("set_root"), &AnimationKeyEditor::set_root);
//ClassDB::bind_method(D_METHOD("_confirm_insert"),&AnimationKeyEditor::_confirm_insert);
- ClassDB::bind_method(D_METHOD("_confirm_insert_list"),&AnimationKeyEditor::_confirm_insert_list);
-
-
-
- ClassDB::bind_method(D_METHOD("_update_paths"),&AnimationKeyEditor::_update_paths);
- ClassDB::bind_method(D_METHOD("_track_editor_draw"),&AnimationKeyEditor::_track_editor_draw);
-
-
-
-
- ClassDB::bind_method(D_METHOD("_animation_changed"),&AnimationKeyEditor::_animation_changed);
- ClassDB::bind_method(D_METHOD("_scroll_changed"),&AnimationKeyEditor::_scroll_changed);
- ClassDB::bind_method(D_METHOD("_track_editor_gui_input"),&AnimationKeyEditor::_track_editor_gui_input);
- ClassDB::bind_method(D_METHOD("_track_name_changed"),&AnimationKeyEditor::_track_name_changed);
- ClassDB::bind_method(D_METHOD("_track_menu_selected"),&AnimationKeyEditor::_track_menu_selected);
- ClassDB::bind_method(D_METHOD("_menu_add_track"),&AnimationKeyEditor::_menu_add_track);
- ClassDB::bind_method(D_METHOD("_menu_track"),&AnimationKeyEditor::_menu_track);
- ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"),&AnimationKeyEditor::_clear_selection_for_anim);
- ClassDB::bind_method(D_METHOD("_select_at_anim"),&AnimationKeyEditor::_select_at_anim);
- ClassDB::bind_method(D_METHOD("_track_pos_draw"),&AnimationKeyEditor::_track_pos_draw);
- ClassDB::bind_method(D_METHOD("_insert_delay"),&AnimationKeyEditor::_insert_delay);
- ClassDB::bind_method(D_METHOD("_step_changed"),&AnimationKeyEditor::_step_changed);
-
-
- ClassDB::bind_method(D_METHOD("_animation_loop_changed"),&AnimationKeyEditor::_animation_loop_changed);
- ClassDB::bind_method(D_METHOD("_animation_len_changed"),&AnimationKeyEditor::_animation_len_changed);
- ClassDB::bind_method(D_METHOD("_create_value_item"),&AnimationKeyEditor::_create_value_item);
- ClassDB::bind_method(D_METHOD("_pane_drag"),&AnimationKeyEditor::_pane_drag);
-
- ClassDB::bind_method(D_METHOD("_animation_len_update"),&AnimationKeyEditor::_animation_len_update);
-
- ClassDB::bind_method(D_METHOD("set_animation"),&AnimationKeyEditor::set_animation);
- ClassDB::bind_method(D_METHOD("_animation_optimize"),&AnimationKeyEditor::_animation_optimize);
- ClassDB::bind_method(D_METHOD("_curve_transition_changed"),&AnimationKeyEditor::_curve_transition_changed);
- ClassDB::bind_method(D_METHOD("_toggle_edit_curves"),&AnimationKeyEditor::_toggle_edit_curves);
- ClassDB::bind_method(D_METHOD("_add_call_track"),&AnimationKeyEditor::_add_call_track);
-
-
- ADD_SIGNAL( MethodInfo("resource_selected", PropertyInfo( Variant::OBJECT, "res"),PropertyInfo( Variant::STRING, "prop") ) );
- ADD_SIGNAL( MethodInfo("keying_changed" ) );
- ADD_SIGNAL( MethodInfo("timeline_changed", PropertyInfo(Variant::REAL,"pos"), PropertyInfo(Variant::BOOL,"drag") ) );
- ADD_SIGNAL( MethodInfo("animation_len_changed", PropertyInfo(Variant::REAL,"len") ) );
- ADD_SIGNAL( MethodInfo("animation_step_changed", PropertyInfo(Variant::REAL,"step") ) );
- ADD_SIGNAL( MethodInfo("key_edited", PropertyInfo(Variant::INT,"track"), PropertyInfo(Variant::INT,"key") ) );
-
+ ClassDB::bind_method(D_METHOD("_confirm_insert_list"), &AnimationKeyEditor::_confirm_insert_list);
+
+ ClassDB::bind_method(D_METHOD("_update_paths"), &AnimationKeyEditor::_update_paths);
+ ClassDB::bind_method(D_METHOD("_track_editor_draw"), &AnimationKeyEditor::_track_editor_draw);
+
+ ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationKeyEditor::_animation_changed);
+ ClassDB::bind_method(D_METHOD("_scroll_changed"), &AnimationKeyEditor::_scroll_changed);
+ ClassDB::bind_method(D_METHOD("_track_editor_gui_input"), &AnimationKeyEditor::_track_editor_gui_input);
+ ClassDB::bind_method(D_METHOD("_track_name_changed"), &AnimationKeyEditor::_track_name_changed);
+ ClassDB::bind_method(D_METHOD("_track_menu_selected"), &AnimationKeyEditor::_track_menu_selected);
+ ClassDB::bind_method(D_METHOD("_menu_add_track"), &AnimationKeyEditor::_menu_add_track);
+ ClassDB::bind_method(D_METHOD("_menu_track"), &AnimationKeyEditor::_menu_track);
+ ClassDB::bind_method(D_METHOD("_clear_selection_for_anim"), &AnimationKeyEditor::_clear_selection_for_anim);
+ ClassDB::bind_method(D_METHOD("_select_at_anim"), &AnimationKeyEditor::_select_at_anim);
+ ClassDB::bind_method(D_METHOD("_track_pos_draw"), &AnimationKeyEditor::_track_pos_draw);
+ ClassDB::bind_method(D_METHOD("_insert_delay"), &AnimationKeyEditor::_insert_delay);
+ ClassDB::bind_method(D_METHOD("_step_changed"), &AnimationKeyEditor::_step_changed);
+
+ ClassDB::bind_method(D_METHOD("_animation_loop_changed"), &AnimationKeyEditor::_animation_loop_changed);
+ ClassDB::bind_method(D_METHOD("_animation_len_changed"), &AnimationKeyEditor::_animation_len_changed);
+ ClassDB::bind_method(D_METHOD("_create_value_item"), &AnimationKeyEditor::_create_value_item);
+ ClassDB::bind_method(D_METHOD("_pane_drag"), &AnimationKeyEditor::_pane_drag);
+
+ ClassDB::bind_method(D_METHOD("_animation_len_update"), &AnimationKeyEditor::_animation_len_update);
+
+ ClassDB::bind_method(D_METHOD("set_animation"), &AnimationKeyEditor::set_animation);
+ ClassDB::bind_method(D_METHOD("_animation_optimize"), &AnimationKeyEditor::_animation_optimize);
+ ClassDB::bind_method(D_METHOD("_curve_transition_changed"), &AnimationKeyEditor::_curve_transition_changed);
+ ClassDB::bind_method(D_METHOD("_toggle_edit_curves"), &AnimationKeyEditor::_toggle_edit_curves);
+ ClassDB::bind_method(D_METHOD("_add_call_track"), &AnimationKeyEditor::_add_call_track);
+
+ ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "res"), PropertyInfo(Variant::STRING, "prop")));
+ ADD_SIGNAL(MethodInfo("keying_changed"));
+ ADD_SIGNAL(MethodInfo("timeline_changed", PropertyInfo(Variant::REAL, "pos"), PropertyInfo(Variant::BOOL, "drag")));
+ ADD_SIGNAL(MethodInfo("animation_len_changed", PropertyInfo(Variant::REAL, "len")));
+ ADD_SIGNAL(MethodInfo("animation_step_changed", PropertyInfo(Variant::REAL, "step")));
+ ADD_SIGNAL(MethodInfo("key_edited", PropertyInfo(Variant::INT, "track"), PropertyInfo(Variant::INT, "key")));
}
-
AnimationKeyEditor::AnimationKeyEditor() {
- alc="animation_len_changed";
- editor_selection=EditorNode::get_singleton()->get_editor_selection();
+ alc = "animation_len_changed";
+ editor_selection = EditorNode::get_singleton()->get_editor_selection();
- selected_track=-1;
- updating=false;
- te_drawing=false;
- undo_redo=EditorNode::get_singleton()->get_undo_redo();
- history=EditorNode::get_singleton()->get_editor_history();
+ selected_track = -1;
+ updating = false;
+ te_drawing = false;
+ undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ history = EditorNode::get_singleton()->get_editor_history();
- ec = memnew (Control);
- ec->set_custom_minimum_size(Size2(0,150));
+ ec = memnew(Control);
+ ec->set_custom_minimum_size(Size2(0, 150));
add_child(ec);
ec->set_v_size_flags(SIZE_EXPAND_FILL);
- h_scroll = memnew( HScrollBar );
- h_scroll->connect("value_changed",this,"_scroll_changed");
+ h_scroll = memnew(HScrollBar);
+ h_scroll->connect("value_changed", this, "_scroll_changed");
add_child(h_scroll);
h_scroll->set_value(0);
-
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
-
- root=NULL;
+ root = NULL;
//menu = memnew( MenuButton );
//menu->set_flat(true);
//menu->set_pos(Point2());
//add_child(menu);
- zoomicon = memnew( TextureRect );
+ zoomicon = memnew(TextureRect);
hb->add_child(zoomicon);
zoomicon->set_tooltip(TTR("Animation zoom."));
- zoom = memnew( HSlider );
+ zoom = memnew(HSlider);
//hb->add_child(zoom);
zoom->set_step(0.01);
zoom->set_min(0.0);
@@ -4021,16 +3764,16 @@ AnimationKeyEditor::AnimationKeyEditor() {
zoom->set_h_size_flags(SIZE_EXPAND_FILL);
zoom->set_stretch_ratio(2);
hb->add_child(zoom);
- zoom->connect("value_changed",this,"_scroll_changed");
+ zoom->connect("value_changed", this, "_scroll_changed");
zoom->set_tooltip(TTR("Animation zoom."));
- hb->add_child( memnew( VSeparator ) );
+ hb->add_child(memnew(VSeparator));
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
l->set_text(TTR("Length (s):"));
hb->add_child(l);
- length = memnew( SpinBox );
+ length = memnew(SpinBox);
length->set_min(0.01);
length->set_max(10000);
length->set_step(0.01);
@@ -4039,13 +3782,13 @@ AnimationKeyEditor::AnimationKeyEditor() {
length->set_tooltip(TTR("Animation length (in seconds)."));
hb->add_child(length);
- length->connect("value_changed",this,"_animation_len_changed");
+ length->connect("value_changed", this, "_animation_len_changed");
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Step (s):"));
hb->add_child(l);
- step = memnew( SpinBox );
+ step = memnew(SpinBox);
step->set_min(0.00);
step->set_max(128);
step->set_step(0.01);
@@ -4055,50 +3798,50 @@ AnimationKeyEditor::AnimationKeyEditor() {
step->set_tooltip(TTR("Cursor step snap (in seconds)."));
hb->add_child(step);
- step->connect("value_changed",this,"_step_changed");
+ step->connect("value_changed", this, "_step_changed");
- loop = memnew( ToolButton );
+ loop = memnew(ToolButton);
loop->set_toggle_mode(true);
- loop->connect("pressed",this,"_animation_loop_changed");
+ loop->connect("pressed", this, "_animation_loop_changed");
hb->add_child(loop);
loop->set_tooltip(TTR("Enable/Disable looping in animation."));
- hb->add_child( memnew( VSeparator ) );
+ hb->add_child(memnew(VSeparator));
- menu_add_track = memnew( MenuButton );
+ menu_add_track = memnew(MenuButton);
hb->add_child(menu_add_track);
- menu_add_track->get_popup()->connect("id_pressed",this,"_menu_add_track");
+ menu_add_track->get_popup()->connect("id_pressed", this, "_menu_add_track");
menu_add_track->set_tooltip(TTR("Add new tracks."));
- move_up_button = memnew( ToolButton );
+ move_up_button = memnew(ToolButton);
hb->add_child(move_up_button);
- move_up_button->connect("pressed",this,"_menu_track",make_binds(TRACK_MENU_MOVE_UP));
+ move_up_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_MOVE_UP));
move_up_button->set_focus_mode(FOCUS_NONE);
move_up_button->set_disabled(true);
move_up_button->set_tooltip(TTR("Move current track up."));
- move_down_button = memnew( ToolButton );
+ move_down_button = memnew(ToolButton);
hb->add_child(move_down_button);
- move_down_button->connect("pressed",this,"_menu_track",make_binds(TRACK_MENU_MOVE_DOWN));
+ move_down_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_MOVE_DOWN));
move_down_button->set_focus_mode(FOCUS_NONE);
move_down_button->set_disabled(true);
move_down_button->set_tooltip(TTR("Move current track down."));
- remove_button = memnew( ToolButton );
+ remove_button = memnew(ToolButton);
hb->add_child(remove_button);
- remove_button->connect("pressed",this,"_menu_track",make_binds(TRACK_MENU_REMOVE));
+ remove_button->connect("pressed", this, "_menu_track", make_binds(TRACK_MENU_REMOVE));
remove_button->set_focus_mode(FOCUS_NONE);
remove_button->set_disabled(true);
remove_button->set_tooltip(TTR("Remove selected track."));
- hb->add_child(memnew( VSeparator ));
+ hb->add_child(memnew(VSeparator));
- menu_track = memnew( MenuButton );
+ menu_track = memnew(MenuButton);
hb->add_child(menu_track);
- menu_track->get_popup()->connect("id_pressed",this,"_menu_track");
+ menu_track->get_popup()->connect("id_pressed", this, "_menu_track");
menu_track->set_tooltip(TTR("Track tools"));
- edit_button = memnew( ToolButton );
+ edit_button = memnew(ToolButton);
edit_button->set_toggle_mode(true);
edit_button->set_focus_mode(FOCUS_NONE);
edit_button->set_disabled(true);
@@ -4106,27 +3849,27 @@ AnimationKeyEditor::AnimationKeyEditor() {
hb->add_child(edit_button);
edit_button->set_tooltip(TTR("Enable editing of individual keys by clicking them."));
- optimize_dialog = memnew( ConfirmationDialog );
+ optimize_dialog = memnew(ConfirmationDialog);
add_child(optimize_dialog);
optimize_dialog->set_title(TTR("Anim. Optimizer"));
- VBoxContainer *optimize_vb = memnew( VBoxContainer );
+ VBoxContainer *optimize_vb = memnew(VBoxContainer);
optimize_dialog->add_child(optimize_vb);
- optimize_linear_error = memnew( SpinBox );
+ optimize_linear_error = memnew(SpinBox);
optimize_linear_error->set_max(1.0);
optimize_linear_error->set_min(0.001);
optimize_linear_error->set_step(0.001);
optimize_linear_error->set_value(0.05);
- optimize_vb->add_margin_child(TTR("Max. Linear Error:"),optimize_linear_error);
- optimize_angular_error = memnew( SpinBox );
+ optimize_vb->add_margin_child(TTR("Max. Linear Error:"), optimize_linear_error);
+ optimize_angular_error = memnew(SpinBox);
optimize_angular_error->set_max(1.0);
optimize_angular_error->set_min(0.001);
optimize_angular_error->set_step(0.001);
optimize_angular_error->set_value(0.01);
- optimize_vb->add_margin_child(TTR("Max. Angular Error:"),optimize_angular_error);
- optimize_max_angle = memnew( SpinBox );
- optimize_vb->add_margin_child(TTR("Max Optimizable Angle:"),optimize_max_angle);
+ optimize_vb->add_margin_child(TTR("Max. Angular Error:"), optimize_angular_error);
+ optimize_max_angle = memnew(SpinBox);
+ optimize_vb->add_margin_child(TTR("Max Optimizable Angle:"), optimize_max_angle);
optimize_max_angle->set_max(360.0);
optimize_max_angle->set_min(0.0);
optimize_max_angle->set_step(0.1);
@@ -4134,8 +3877,6 @@ AnimationKeyEditor::AnimationKeyEditor() {
optimize_dialog->get_ok()->set_text(TTR("Optimize"));
-
-
/*keying = memnew( Button );
keying->set_toggle_mode(true);
//keying->set_text("Keys");
@@ -4147,35 +3888,32 @@ AnimationKeyEditor::AnimationKeyEditor() {
keying->connect("pressed",this,"_keying_toggled");
*/
-/* l = memnew( Label );
+ /* l = memnew( Label );
l->set_text("Base: ");
l->set_pos(Point2(0,3));
//dr_panel->add_child(l);*/
//menu->get_popup()->connect("id_pressed",this,"_menu_callback");
-
- hb = memnew( HBoxContainer);
+ hb = memnew(HBoxContainer);
hb->set_area_as_parent_rect();
ec->add_child(hb);
hb->set_v_size_flags(SIZE_EXPAND_FILL);
- track_editor = memnew( Control );
- track_editor->connect("draw",this,"_track_editor_draw");
+ track_editor = memnew(Control);
+ track_editor->connect("draw", this, "_track_editor_draw");
hb->add_child(track_editor);
- track_editor->connect("gui_input",this,"_track_editor_gui_input");
+ track_editor->connect("gui_input", this, "_track_editor_gui_input");
track_editor->set_focus_mode(Control::FOCUS_ALL);
track_editor->set_h_size_flags(SIZE_EXPAND_FILL);
-
-
- track_pos = memnew( Control );
+ track_pos = memnew(Control);
track_pos->set_area_as_parent_rect();
track_pos->set_mouse_filter(MOUSE_FILTER_IGNORE);
track_editor->add_child(track_pos);
- track_pos->connect("draw",this,"_track_pos_draw");
+ track_pos->connect("draw", this, "_track_pos_draw");
- select_anim_warning = memnew( Label );
+ select_anim_warning = memnew(Label);
track_editor->add_child(select_anim_warning);
select_anim_warning->set_area_as_parent_rect();
select_anim_warning->set_text(TTR("Select an AnimationPlayer from the Scene Tree to edit animations."));
@@ -4183,149 +3921,137 @@ AnimationKeyEditor::AnimationKeyEditor() {
select_anim_warning->set_align(Label::ALIGN_CENTER);
select_anim_warning->set_valign(Label::VALIGN_CENTER);
-
-
- v_scroll = memnew( VScrollBar );
+ v_scroll = memnew(VScrollBar);
hb->add_child(v_scroll);
- v_scroll->connect("value_changed",this,"_scroll_changed");
+ v_scroll->connect("value_changed", this, "_scroll_changed");
v_scroll->set_value(0);
key_editor_tab = memnew(TabContainer);
hb->add_child(key_editor_tab);
- key_editor_tab->set_custom_minimum_size(Size2(200,0));
+ key_editor_tab->set_custom_minimum_size(Size2(200, 0));
- key_editor = memnew( PropertyEditor );
+ key_editor = memnew(PropertyEditor);
key_editor->set_area_as_parent_rect();
key_editor->hide_top_label();
key_editor->set_name(TTR("Key"));
key_editor_tab->add_child(key_editor);
- key_edit = memnew( AnimationKeyEdit );
- key_edit->undo_redo=undo_redo;
+ key_edit = memnew(AnimationKeyEdit);
+ key_edit->undo_redo = undo_redo;
//key_edit->ke_dialog=key_edit_dialog;
- type_menu = memnew( PopupMenu );
+ type_menu = memnew(PopupMenu);
add_child(type_menu);
- for(int i=0;i<Variant::VARIANT_MAX;i++)
- type_menu->add_item(Variant::get_type_name(Variant::Type(i)),i);
- type_menu->connect("id_pressed",this,"_create_value_item");
+ for (int i = 0; i < Variant::VARIANT_MAX; i++)
+ type_menu->add_item(Variant::get_type_name(Variant::Type(i)), i);
+ type_menu->connect("id_pressed", this, "_create_value_item");
- VBoxContainer *curve_vb = memnew( VBoxContainer );
+ VBoxContainer *curve_vb = memnew(VBoxContainer);
curve_vb->set_name(TTR("Transition"));
- HBoxContainer *curve_hb = memnew( HBoxContainer );
+ HBoxContainer *curve_hb = memnew(HBoxContainer);
curve_vb->add_child(curve_hb);
- curve_linear = memnew( ToolButton );
+ curve_linear = memnew(ToolButton);
curve_linear->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_linear);
- curve_in = memnew( ToolButton );
+ curve_in = memnew(ToolButton);
curve_in->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_in);
- curve_out = memnew( ToolButton );
+ curve_out = memnew(ToolButton);
curve_out->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_out);
- curve_inout = memnew( ToolButton );
+ curve_inout = memnew(ToolButton);
curve_inout->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_inout);
- curve_outin = memnew( ToolButton );
+ curve_outin = memnew(ToolButton);
curve_outin->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_outin);
- curve_constant = memnew( ToolButton );
+ curve_constant = memnew(ToolButton);
curve_constant->set_focus_mode(FOCUS_NONE);
curve_hb->add_child(curve_constant);
-
- curve_edit = memnew( AnimationCurveEdit );
+ curve_edit = memnew(AnimationCurveEdit);
curve_vb->add_child(curve_edit);
curve_edit->set_v_size_flags(SIZE_EXPAND_FILL);
key_editor_tab->add_child(curve_vb);
- track_name = memnew( LineEdit );
+ track_name = memnew(LineEdit);
track_name->set_as_toplevel(true);
track_name->hide();
add_child(track_name);
- track_name->connect("text_entered",this,"_track_name_changed");
- track_menu = memnew( PopupMenu );
+ track_name->connect("text_entered", this, "_track_name_changed");
+ track_menu = memnew(PopupMenu);
add_child(track_menu);
- track_menu->connect("id_pressed",this,"_track_menu_selected");
+ track_menu->connect("id_pressed", this, "_track_menu_selected");
key_editor_tab->hide();
- last_idx =1;
+ last_idx = 1;
_update_menu();
-
-
- insert_confirm = memnew( ConfirmationDialog );
+ insert_confirm = memnew(ConfirmationDialog);
add_child(insert_confirm);
- insert_confirm->connect("confirmed",this,"_confirm_insert_list");
-
- click.click=ClickOver::CLICK_NONE;
-
+ insert_confirm->connect("confirmed", this, "_confirm_insert_list");
- name_column_ratio=0.3;
- timeline_pos=0;
+ click.click = ClickOver::CLICK_NONE;
+ name_column_ratio = 0.3;
+ timeline_pos = 0;
- keying=false;
- insert_frame=0;
- insert_query=false;
- insert_queue=false;
+ keying = false;
+ insert_frame = 0;
+ insert_query = false;
+ insert_queue = false;
- editor_selection->connect("selection_changed",track_editor,"update");
+ editor_selection->connect("selection_changed", track_editor, "update");
-
- scale_dialog = memnew( ConfirmationDialog );
- VBoxContainer *vbc = memnew( VBoxContainer );
+ scale_dialog = memnew(ConfirmationDialog);
+ VBoxContainer *vbc = memnew(VBoxContainer);
scale_dialog->add_child(vbc);
- scale = memnew( SpinBox );
+ scale = memnew(SpinBox);
scale->set_min(-99999);
scale->set_max(99999);
scale->set_step(0.001);
- vbc->add_margin_child(TTR("Scale Ratio:"),scale);
- scale_dialog->connect("confirmed",this,"_scale");
+ vbc->add_margin_child(TTR("Scale Ratio:"), scale);
+ scale_dialog->connect("confirmed", this, "_scale");
add_child(scale_dialog);
- call_select = memnew( SceneTreeDialog );
+ call_select = memnew(SceneTreeDialog);
add_child(call_select);
call_select->set_title(TTR("Call Functions in Which Node?"));
- cleanup_dialog = memnew( ConfirmationDialog );
+ cleanup_dialog = memnew(ConfirmationDialog);
add_child(cleanup_dialog);
- VBoxContainer *cleanup_vb = memnew( VBoxContainer );
+ VBoxContainer *cleanup_vb = memnew(VBoxContainer);
cleanup_dialog->add_child(cleanup_vb);
- cleanup_keys = memnew( CheckButton );
+ cleanup_keys = memnew(CheckButton);
cleanup_keys->set_text(TTR("Remove invalid keys"));
cleanup_keys->set_pressed(true);
cleanup_vb->add_child(cleanup_keys);
- cleanup_tracks = memnew( CheckButton );
+ cleanup_tracks = memnew(CheckButton);
cleanup_tracks->set_text(TTR("Remove unresolved and empty tracks"));
cleanup_tracks->set_pressed(true);
cleanup_vb->add_child(cleanup_tracks);
- cleanup_all = memnew( CheckButton );
+ cleanup_all = memnew(CheckButton);
cleanup_all->set_text(TTR("Clean-up all animations"));
cleanup_vb->add_child(cleanup_all);
cleanup_dialog->set_title(TTR("Clean-Up Animation(s) (NO UNDO!)"));
cleanup_dialog->get_ok()->set_text(TTR("Clean-Up"));
- cleanup_dialog->connect("confirmed",this,"_menu_track",varray(TRACK_MENU_CLEAN_UP_CONFIRM));
+ cleanup_dialog->connect("confirmed", this, "_menu_track", varray(TRACK_MENU_CLEAN_UP_CONFIRM));
- add_constant_override("separation",get_constant("separation","VBoxContainer"));
+ add_constant_override("separation", get_constant("separation", "VBoxContainer"));
track_editor->set_clip_contents(true);
-
}
AnimationKeyEditor::~AnimationKeyEditor() {
-
-
- memdelete( key_edit );
-
+ memdelete(key_edit);
}
diff --git a/editor/animation_editor.h b/editor/animation_editor.h
index c4539cd763..a775ad160b 100644
--- a/editor/animation_editor.h
+++ b/editor/animation_editor.h
@@ -30,30 +30,30 @@
#define ANIMATION_EDITOR_H
#include "scene/gui/control.h"
-#include "scene/gui/slider.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/menu_button.h"
+#include "scene/gui/scroll_bar.h"
+#include "scene/gui/slider.h"
#include "scene/gui/spin_box.h"
+#include "scene/gui/tab_container.h"
#include "scene/gui/texture_rect.h"
-#include "scene/gui/scroll_bar.h"
#include "scene/gui/tool_button.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/tab_container.h"
-#include "scene/resources/animation.h"
-#include "scene/animation/animation_cache.h"
-#include "scene_tree_editor.h"
#include "editor_data.h"
#include "property_editor.h"
+#include "scene/animation/animation_cache.h"
+#include "scene/resources/animation.h"
+#include "scene_tree_editor.h"
#include "scene_tree_editor.h"
class AnimationKeyEdit;
class AnimationCurveEdit;
-class AnimationKeyEditor : public VBoxContainer {
+class AnimationKeyEditor : public VBoxContainer {
- GDCLASS( AnimationKeyEditor, VBoxContainer );
+ GDCLASS(AnimationKeyEditor, VBoxContainer);
-/*
+ /*
enum {
MENU_NEW_ANIMATION,
@@ -130,7 +130,7 @@ class AnimationKeyEditor : public VBoxContainer {
int track;
int key;
- bool operator<(const SelectedKey& p_key) const { return track==p_key.track ? key < p_key.key : track < p_key.track; };
+ bool operator<(const SelectedKey &p_key) const { return track == p_key.track ? key < p_key.key : track < p_key.track; };
};
struct KeyInfo {
@@ -138,7 +138,7 @@ class AnimationKeyEditor : public VBoxContainer {
float pos;
};
- Map<SelectedKey,KeyInfo> selection;
+ Map<SelectedKey, KeyInfo> selection;
struct ClickOver {
@@ -159,7 +159,6 @@ class AnimationKeyEditor : public VBoxContainer {
Point2 to;
} click;
-
float timeline_pos;
float name_column_ratio;
@@ -195,7 +194,6 @@ class AnimationKeyEditor : public VBoxContainer {
ToolButton *curve_outin;
ToolButton *curve_constant;
-
ConfirmationDialog *optimize_dialog;
SpinBox *optimize_linear_error;
SpinBox *optimize_angular_error;
@@ -233,10 +231,9 @@ class AnimationKeyEditor : public VBoxContainer {
Node *root;
UndoRedo *undo_redo;
- EditorHistory* history;
+ EditorHistory *history;
ConfirmationDialog *insert_confirm;
-
AnimationKeyEdit *key_edit;
AnimationCurveEdit *curve_edit;
@@ -257,7 +254,7 @@ class AnimationKeyEditor : public VBoxContainer {
Variant value;
String query;
bool advance;
- };/* insert_data;*/
+ }; /* insert_data;*/
bool insert_query;
List<InsertData> insert_data;
@@ -266,37 +263,32 @@ class AnimationKeyEditor : public VBoxContainer {
int cvi_track;
float cvi_pos;
-
int right_data_size_cache;
EditorSelection *editor_selection;
Label *select_anim_warning;
-
float _get_zoom_scale() const;
void _track_editor_draw();
- void _track_editor_gui_input(const InputEvent& p_input);
+ void _track_editor_gui_input(const InputEvent &p_input);
void _track_pos_draw();
-
- void _track_name_changed(const String& p_name);
+ void _track_name_changed(const String &p_name);
void _track_menu_selected(int p_idx);
void _confirm_insert_list();
- int _confirm_insert(InsertData p_id,int p_at_track=-1);
- void _query_insert(const InsertData& p_id);
+ int _confirm_insert(InsertData p_id, int p_at_track = -1);
+ void _query_insert(const InsertData &p_id);
void _update_menu();
bool insert_queue;
void _insert_delay();
void _scale();
-
void _clear_selection();
//void _browse_path();
-
StringName alc;
void _animation_changed();
@@ -308,32 +300,32 @@ class AnimationKeyEditor : public VBoxContainer {
void _menu_add_track(int p_type);
void _menu_track(int p_type);
- void _clear_selection_for_anim(const Ref<Animation>& p_anim);
- void _select_at_anim(const Ref<Animation>& p_anim,int p_track,float p_pos);
+ void _clear_selection_for_anim(const Ref<Animation> &p_anim);
+ void _select_at_anim(const Ref<Animation> &p_anim, int p_track, float p_pos);
void _curve_transition_changed(float p_what);
PropertyInfo _find_hint_for_track(int p_idx, NodePath &r_base_path);
void _create_value_item(int p_type);
- void _pane_drag(const Point2& p_delta);
+ void _pane_drag(const Point2 &p_delta);
bool _edit_if_single_selection();
void _toggle_edit_curves();
void _animation_len_update();
- void _add_call_track(const NodePath& p_base);
+ void _add_call_track(const NodePath &p_base);
void _anim_duplicate_keys(bool transpose = false);
void _anim_delete_keys();
void _root_removed();
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_animation(const Ref<Animation>& p_anim);
+public:
+ void set_animation(const Ref<Animation> &p_anim);
Ref<Animation> get_current_animation() const;
void set_root(Node *p_root);
Node *get_root() const;
@@ -343,9 +335,9 @@ public:
void cleanup();
void set_anim_pos(float p_pos);
- void insert_node_value_key(Node* p_node, const String& p_property,const Variant& p_value,bool p_only_if_exists=false);
- void insert_value_key(const String& p_property, const Variant& p_value, bool p_advance);
- void insert_transform_key(Spatial *p_node,const String& p_sub,const Transform& p_xform);
+ void insert_node_value_key(Node *p_node, const String &p_property, const Variant &p_value, bool p_only_if_exists = false);
+ void insert_value_key(const String &p_property, const Variant &p_value, bool p_advance);
+ void insert_transform_key(Spatial *p_node, const String &p_sub, const Transform &p_xform);
void show_select_node_warning(bool p_show) { select_anim_warning->set_visible(p_show); }
AnimationKeyEditor();
diff --git a/editor/array_property_edit.cpp b/editor/array_property_edit.cpp
index 7304d8dddf..62415f4993 100644
--- a/editor/array_property_edit.cpp
+++ b/editor/array_property_edit.cpp
@@ -32,15 +32,15 @@
#define ITEMS_PER_PAGE 100
-Variant ArrayPropertyEdit::get_array() const{
+Variant ArrayPropertyEdit::get_array() const {
- Object*o = ObjectDB::get_instance(obj);
+ Object *o = ObjectDB::get_instance(obj);
if (!o)
return Array();
- Variant arr=o->get(property);
+ Variant arr = o->get(property);
if (!arr.is_array()) {
Variant::CallError ce;
- arr=Variant::construct(default_type,NULL,0,ce);
+ arr = Variant::construct(default_type, NULL, 0, ce);
}
return arr;
}
@@ -48,7 +48,7 @@ Variant ArrayPropertyEdit::get_array() const{
void ArrayPropertyEdit::_notif_change() {
_change_notify();
}
-void ArrayPropertyEdit::_notif_changev(const String& p_v) {
+void ArrayPropertyEdit::_notif_changev(const String &p_v) {
_change_notify(p_v.utf8().get_data());
}
@@ -56,115 +56,111 @@ void ArrayPropertyEdit::_notif_changev(const String& p_v) {
void ArrayPropertyEdit::_set_size(int p_size) {
Variant arr = get_array();
- arr.call("resize",p_size);
- Object*o = ObjectDB::get_instance(obj);
+ arr.call("resize", p_size);
+ Object *o = ObjectDB::get_instance(obj);
if (!o)
return;
- o->set(property,arr);
-
+ o->set(property, arr);
}
-void ArrayPropertyEdit::_set_value(int p_idx,const Variant& p_value) {
+void ArrayPropertyEdit::_set_value(int p_idx, const Variant &p_value) {
Variant arr = get_array();
- arr.set(p_idx,p_value);
- Object*o = ObjectDB::get_instance(obj);
+ arr.set(p_idx, p_value);
+ Object *o = ObjectDB::get_instance(obj);
if (!o)
return;
- o->set(property,arr);
+ o->set(property, arr);
}
-bool ArrayPropertyEdit::_set(const StringName& p_name, const Variant& p_value){
+bool ArrayPropertyEdit::_set(const StringName &p_name, const Variant &p_value) {
- String pn=p_name;
+ String pn = p_name;
if (pn.begins_with("array/")) {
- if (pn=="array/size") {
+ if (pn == "array/size") {
Variant arr = get_array();
int size = arr.call("size");
- int newsize=p_value;
- if (newsize==size)
+ int newsize = p_value;
+ if (newsize == size)
return true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Resize Array"));
- ur->add_do_method(this,"_set_size",newsize);
- ur->add_undo_method(this,"_set_size",size);
- if (newsize<size) {
- for(int i=newsize;i<size;i++) {
- ur->add_undo_method(this,"_set_value",i,arr.get(i));
-
+ ur->add_do_method(this, "_set_size", newsize);
+ ur->add_undo_method(this, "_set_size", size);
+ if (newsize < size) {
+ for (int i = newsize; i < size; i++) {
+ ur->add_undo_method(this, "_set_value", i, arr.get(i));
}
- } else if (newsize>size) {
+ } else if (newsize > size) {
Variant init;
Variant::CallError ce;
Variant::Type new_type = subtype;
- if(new_type==Variant::NIL && size) {
- new_type = arr.get(size-1).get_type();
+ if (new_type == Variant::NIL && size) {
+ new_type = arr.get(size - 1).get_type();
}
- if(new_type!=Variant::NIL) {
- init = Variant::construct(new_type,NULL,0,ce);
- for(int i=size;i<newsize;i++) {
- ur->add_do_method(this,"_set_value",i,init);
+ if (new_type != Variant::NIL) {
+ init = Variant::construct(new_type, NULL, 0, ce);
+ for (int i = size; i < newsize; i++) {
+ ur->add_do_method(this, "_set_value", i, init);
}
}
-
}
- ur->add_do_method(this,"_notif_change");
- ur->add_undo_method(this,"_notif_change");
+ ur->add_do_method(this, "_notif_change");
+ ur->add_undo_method(this, "_notif_change");
ur->commit_action();
return true;
}
- if (pn=="array/page") {
- page=p_value;
+ if (pn == "array/page") {
+ page = p_value;
_change_notify();
return true;
}
} else if (pn.begins_with("indices")) {
- if (pn.find("_")!=-1) {
+ if (pn.find("_") != -1) {
//type
- int idx=pn.get_slicec('/',1).get_slicec('_',0).to_int();
+ int idx = pn.get_slicec('/', 1).get_slicec('_', 0).to_int();
int type = p_value;
Variant arr = get_array();
Variant value = arr.get(idx);
- if (value.get_type()!=type && type>=0 && type<Variant::VARIANT_MAX) {
+ if (value.get_type() != type && type >= 0 && type < Variant::VARIANT_MAX) {
Variant::CallError ce;
- Variant new_value=Variant::construct(Variant::Type(type),NULL,0,ce);
+ Variant new_value = Variant::construct(Variant::Type(type), NULL, 0, ce);
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Array Value Type"));
- ur->add_do_method(this,"_set_value",idx,new_value);
- ur->add_undo_method(this,"_set_value",idx,value);
- ur->add_do_method(this,"_notif_change");
- ur->add_undo_method(this,"_notif_change");
+ ur->add_do_method(this, "_set_value", idx, new_value);
+ ur->add_undo_method(this, "_set_value", idx, value);
+ ur->add_do_method(this, "_notif_change");
+ ur->add_undo_method(this, "_notif_change");
ur->commit_action();
-
}
return true;
} else {
- int idx=pn.get_slicec('/',1).to_int();
+ int idx = pn.get_slicec('/', 1).to_int();
Variant arr = get_array();
Variant value = arr.get(idx);
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Array Value"));
- ur->add_do_method(this,"_set_value",idx,p_value);
- ur->add_undo_method(this,"_set_value",idx,value);
- ur->add_do_method(this,"_notif_changev",p_name);
- ur->add_undo_method(this,"_notif_changev",p_name);
+ ur->add_do_method(this, "_set_value", idx, p_value);
+ ur->add_undo_method(this, "_set_value", idx, value);
+ ur->add_do_method(this, "_notif_changev", p_name);
+ ur->add_undo_method(this, "_notif_changev", p_name);
ur->commit_action();
return true;
}
@@ -173,37 +169,37 @@ bool ArrayPropertyEdit::_set(const StringName& p_name, const Variant& p_value){
return false;
}
-bool ArrayPropertyEdit::_get(const StringName& p_name,Variant &r_ret) const {
+bool ArrayPropertyEdit::_get(const StringName &p_name, Variant &r_ret) const {
Variant arr = get_array();
//int size = arr.call("size");
- String pn=p_name;
+ String pn = p_name;
if (pn.begins_with("array/")) {
- if (pn=="array/size") {
- r_ret=arr.call("size");
+ if (pn == "array/size") {
+ r_ret = arr.call("size");
return true;
}
- if (pn=="array/page") {
- r_ret=page;
+ if (pn == "array/page") {
+ r_ret = page;
return true;
}
} else if (pn.begins_with("indices")) {
- if (pn.find("_")!=-1) {
+ if (pn.find("_") != -1) {
//type
- int idx=pn.get_slicec('/',1).get_slicec('_',0).to_int();
+ int idx = pn.get_slicec('/', 1).get_slicec('_', 0).to_int();
bool valid;
- r_ret=arr.get(idx,&valid);
+ r_ret = arr.get(idx, &valid);
if (valid)
- r_ret=r_ret.get_type();
+ r_ret = r_ret.get_type();
return valid;
} else {
- int idx=pn.get_slicec('/',1).to_int();
+ int idx = pn.get_slicec('/', 1).to_int();
bool valid;
- r_ret=arr.get(idx,&valid);
+ r_ret = arr.get(idx, &valid);
return valid;
}
}
@@ -211,70 +207,67 @@ bool ArrayPropertyEdit::_get(const StringName& p_name,Variant &r_ret) const {
return false;
}
-void ArrayPropertyEdit::_get_property_list( List<PropertyInfo> *p_list) const{
+void ArrayPropertyEdit::_get_property_list(List<PropertyInfo> *p_list) const {
Variant arr = get_array();
int size = arr.call("size");
- p_list->push_back( PropertyInfo(Variant::INT,"array/size",PROPERTY_HINT_RANGE,"0,100000,1") );
- int pages = size/ITEMS_PER_PAGE;
- if (pages>0)
- p_list->push_back( PropertyInfo(Variant::INT,"array/page",PROPERTY_HINT_RANGE,"0,"+itos(pages)+",1") );
+ p_list->push_back(PropertyInfo(Variant::INT, "array/size", PROPERTY_HINT_RANGE, "0,100000,1"));
+ int pages = size / ITEMS_PER_PAGE;
+ if (pages > 0)
+ p_list->push_back(PropertyInfo(Variant::INT, "array/page", PROPERTY_HINT_RANGE, "0," + itos(pages) + ",1"));
- int offset=page*ITEMS_PER_PAGE;
+ int offset = page * ITEMS_PER_PAGE;
- int items=MIN(size-offset,ITEMS_PER_PAGE);
+ int items = MIN(size - offset, ITEMS_PER_PAGE);
+ for (int i = 0; i < items; i++) {
- for(int i=0;i<items;i++) {
+ Variant v = arr.get(i + offset);
+ bool is_typed = arr.get_type() != Variant::ARRAY || subtype != Variant::NIL;
- Variant v=arr.get(i+offset);
- bool is_typed = arr.get_type()!=Variant::ARRAY || subtype!=Variant::NIL;
-
if (!is_typed) {
- p_list->push_back(PropertyInfo(Variant::INT,"indices/"+itos(i+offset)+"_type",PROPERTY_HINT_ENUM,vtypes));
+ p_list->push_back(PropertyInfo(Variant::INT, "indices/" + itos(i + offset) + "_type", PROPERTY_HINT_ENUM, vtypes));
}
-
- if (is_typed || v.get_type()!=Variant::NIL ) {
- PropertyInfo pi(v.get_type(),"indices/"+itos(i+offset));
- if(subtype!=Variant::NIL) {
+
+ if (is_typed || v.get_type() != Variant::NIL) {
+ PropertyInfo pi(v.get_type(), "indices/" + itos(i + offset));
+ if (subtype != Variant::NIL) {
pi.type = Variant::Type(subtype);
pi.hint = PropertyHint(subtype_hint);
pi.hint_string = subtype_hint_string;
- } else if (v.get_type()==Variant::OBJECT) {
- pi.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pi.hint_string="Resource";
+ } else if (v.get_type() == Variant::OBJECT) {
+ pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pi.hint_string = "Resource";
}
-
+
p_list->push_back(pi);
}
}
-
}
-void ArrayPropertyEdit::edit(Object* p_obj,const StringName& p_prop,const String& p_hint_string,Variant::Type p_deftype) {
+void ArrayPropertyEdit::edit(Object *p_obj, const StringName &p_prop, const String &p_hint_string, Variant::Type p_deftype) {
- page=0;
- property=p_prop;
- obj=p_obj->get_instance_ID();
- default_type=p_deftype;
+ page = 0;
+ property = p_prop;
+ obj = p_obj->get_instance_ID();
+ default_type = p_deftype;
- if(!p_hint_string.empty()) {
+ if (!p_hint_string.empty()) {
int hint_subtype_seperator = p_hint_string.find(":");
- if(hint_subtype_seperator >= 0) {
- String subtype_string = p_hint_string.substr(0,hint_subtype_seperator);
-
+ if (hint_subtype_seperator >= 0) {
+ String subtype_string = p_hint_string.substr(0, hint_subtype_seperator);
+
int slash_pos = subtype_string.find("/");
- if(slash_pos >= 0) {
- subtype_hint = PropertyHint(subtype_string.substr(slash_pos+1, subtype_string.size()-slash_pos-1).to_int());
- subtype_string = subtype_string.substr(0,slash_pos);
+ if (slash_pos >= 0) {
+ subtype_hint = PropertyHint(subtype_string.substr(slash_pos + 1, subtype_string.size() - slash_pos - 1).to_int());
+ subtype_string = subtype_string.substr(0, slash_pos);
}
-
- subtype_hint_string = p_hint_string.substr(hint_subtype_seperator+1, p_hint_string.size() - hint_subtype_seperator-1);
- subtype=Variant::Type(subtype_string.to_int());
+
+ subtype_hint_string = p_hint_string.substr(hint_subtype_seperator + 1, p_hint_string.size() - hint_subtype_seperator - 1);
+ subtype = Variant::Type(subtype_string.to_int());
}
}
-
}
Node *ArrayPropertyEdit::get_node() {
@@ -288,23 +281,22 @@ Node *ArrayPropertyEdit::get_node() {
void ArrayPropertyEdit::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_set_size"),&ArrayPropertyEdit::_set_size);
- ClassDB::bind_method(D_METHOD("_set_value"),&ArrayPropertyEdit::_set_value);
- ClassDB::bind_method(D_METHOD("_notif_change"),&ArrayPropertyEdit::_notif_change);
- ClassDB::bind_method(D_METHOD("_notif_changev"),&ArrayPropertyEdit::_notif_changev);
+ ClassDB::bind_method(D_METHOD("_set_size"), &ArrayPropertyEdit::_set_size);
+ ClassDB::bind_method(D_METHOD("_set_value"), &ArrayPropertyEdit::_set_value);
+ ClassDB::bind_method(D_METHOD("_notif_change"), &ArrayPropertyEdit::_notif_change);
+ ClassDB::bind_method(D_METHOD("_notif_changev"), &ArrayPropertyEdit::_notif_changev);
}
-ArrayPropertyEdit::ArrayPropertyEdit()
-{
- page=0;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ArrayPropertyEdit::ArrayPropertyEdit() {
+ page = 0;
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i>0)
- vtypes+=",";
- vtypes+=Variant::get_type_name( Variant::Type(i) );
+ if (i > 0)
+ vtypes += ",";
+ vtypes += Variant::get_type_name(Variant::Type(i));
}
- default_type=Variant::NIL;
- subtype=Variant::NIL;
- subtype_hint=PROPERTY_HINT_NONE;
- subtype_hint_string="";
+ default_type = Variant::NIL;
+ subtype = Variant::NIL;
+ subtype_hint = PROPERTY_HINT_NONE;
+ subtype_hint_string = "";
}
diff --git a/editor/array_property_edit.h b/editor/array_property_edit.h
index 6ca700bf80..1461aa52a3 100644
--- a/editor/array_property_edit.h
+++ b/editor/array_property_edit.h
@@ -33,7 +33,7 @@
class ArrayPropertyEdit : public Reference {
- GDCLASS(ArrayPropertyEdit,Reference);
+ GDCLASS(ArrayPropertyEdit, Reference);
int page;
ObjectID obj;
@@ -46,20 +46,18 @@ class ArrayPropertyEdit : public Reference {
Variant::Type default_type;
void _notif_change();
- void _notif_changev(const String& p_v);
+ void _notif_changev(const String &p_v);
void _set_size(int p_size);
- void _set_value(int p_idx,const Variant& p_value);
+ void _set_value(int p_idx, const Variant &p_value);
protected:
-
static void _bind_methods();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
- void edit(Object* p_obj, const StringName& p_prop, const String& p_hint_string, Variant::Type p_deftype);
+ void edit(Object *p_obj, const StringName &p_prop, const String &p_hint_string, Variant::Type p_deftype);
Node *get_node();
diff --git a/editor/asset_library_editor_plugin.cpp b/editor/asset_library_editor_plugin.cpp
index 1c1b6c91e3..7bfe52d1b4 100644
--- a/editor/asset_library_editor_plugin.cpp
+++ b/editor/asset_library_editor_plugin.cpp
@@ -32,72 +32,65 @@
#include "editor_settings.h"
#include "io/json.h"
-
-void EditorAssetLibraryItem::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost) {
+void EditorAssetLibraryItem::configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, int p_rating, const String &p_cost) {
title->set_text(p_title);
- asset_id=p_asset_id;
+ asset_id = p_asset_id;
category->set_text(p_category);
- category_id=p_category_id;
+ category_id = p_category_id;
author->set_text(p_author);
- author_id=p_author_id;
+ author_id = p_author_id;
price->set_text(p_cost);
- for(int i=0;i<5;i++) {
- if (i<p_rating)
- stars[i]->set_texture(get_icon("RatingStar","EditorIcons"));
+ for (int i = 0; i < 5; i++) {
+ if (i < p_rating)
+ stars[i]->set_texture(get_icon("RatingStar", "EditorIcons"));
else
- stars[i]->set_texture(get_icon("RatingNoStar","EditorIcons"));
+ stars[i]->set_texture(get_icon("RatingNoStar", "EditorIcons"));
}
-
-
}
-void EditorAssetLibraryItem::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
+void EditorAssetLibraryItem::set_image(int p_type, int p_index, const Ref<Texture> &p_image) {
- ERR_FAIL_COND(p_type!=EditorAssetLibrary::IMAGE_QUEUE_ICON);
- ERR_FAIL_COND(p_index!=0);
+ ERR_FAIL_COND(p_type != EditorAssetLibrary::IMAGE_QUEUE_ICON);
+ ERR_FAIL_COND(p_index != 0);
icon->set_normal_texture(p_image);
}
void EditorAssetLibraryItem::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
- icon->set_normal_texture(get_icon("GodotAssetDefault","EditorIcons"));
- category->add_color_override("font_color", Color(0.5,0.5,0.5) );
- author->add_color_override("font_color", Color(0.5,0.5,0.5) );
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ icon->set_normal_texture(get_icon("GodotAssetDefault", "EditorIcons"));
+ category->add_color_override("font_color", Color(0.5, 0.5, 0.5));
+ author->add_color_override("font_color", Color(0.5, 0.5, 0.5));
}
}
void EditorAssetLibraryItem::_asset_clicked() {
- emit_signal("asset_selected",asset_id);
+ emit_signal("asset_selected", asset_id);
}
-void EditorAssetLibraryItem::_category_clicked(){
+void EditorAssetLibraryItem::_category_clicked() {
- emit_signal("category_selected",category_id);
+ emit_signal("category_selected", category_id);
}
-void EditorAssetLibraryItem::_author_clicked(){
-
- emit_signal("author_selected",author_id);
+void EditorAssetLibraryItem::_author_clicked() {
+ emit_signal("author_selected", author_id);
}
void EditorAssetLibraryItem::_bind_methods() {
- ClassDB::bind_method("set_image",&EditorAssetLibraryItem::set_image);
- ClassDB::bind_method("_asset_clicked",&EditorAssetLibraryItem::_asset_clicked);
- ClassDB::bind_method("_category_clicked",&EditorAssetLibraryItem::_category_clicked);
- ClassDB::bind_method("_author_clicked",&EditorAssetLibraryItem::_author_clicked);
- ADD_SIGNAL( MethodInfo("asset_selected"));
- ADD_SIGNAL( MethodInfo("category_selected"));
- ADD_SIGNAL( MethodInfo("author_selected"));
-
-
+ ClassDB::bind_method("set_image", &EditorAssetLibraryItem::set_image);
+ ClassDB::bind_method("_asset_clicked", &EditorAssetLibraryItem::_asset_clicked);
+ ClassDB::bind_method("_category_clicked", &EditorAssetLibraryItem::_category_clicked);
+ ClassDB::bind_method("_author_clicked", &EditorAssetLibraryItem::_author_clicked);
+ ADD_SIGNAL(MethodInfo("asset_selected"));
+ ADD_SIGNAL(MethodInfo("category_selected"));
+ ADD_SIGNAL(MethodInfo("author_selected"));
}
EditorAssetLibraryItem::EditorAssetLibraryItem() {
@@ -108,53 +101,52 @@ EditorAssetLibraryItem::EditorAssetLibraryItem() {
border->set_default_margin(MARGIN_RIGHT,5);
border->set_default_margin(MARGIN_BOTTOM,5);
border->set_default_margin(MARGIN_TOP,5);*/
- add_style_override("panel",border);
+ add_style_override("panel", border);
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
- icon = memnew( TextureButton );
+ icon = memnew(TextureButton);
icon->set_default_cursor_shape(CURSOR_POINTING_HAND);
- icon->connect("pressed",this,"_asset_clicked");
+ icon->connect("pressed", this, "_asset_clicked");
hb->add_child(icon);
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
hb->add_child(vb);
vb->set_h_size_flags(SIZE_EXPAND_FILL);
- title = memnew( LinkButton );
+ title = memnew(LinkButton);
title->set_text("My Awesome Addon");
title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- title->connect("pressed",this,"_asset_clicked");
+ title->connect("pressed", this, "_asset_clicked");
vb->add_child(title);
-
- category = memnew( LinkButton );
+ category = memnew(LinkButton);
category->set_text("Editor Tools");
category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- category->connect("pressed",this,"_category_clicked");
+ category->connect("pressed", this, "_category_clicked");
vb->add_child(category);
- author = memnew( LinkButton );
+ author = memnew(LinkButton);
author->set_text("Johny Tolengo");
author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- author->connect("pressed",this,"_author_clicked");
+ author->connect("pressed", this, "_author_clicked");
vb->add_child(author);
- HBoxContainer *rating_hb = memnew( HBoxContainer );
+ HBoxContainer *rating_hb = memnew(HBoxContainer);
vb->add_child(rating_hb);
- for(int i=0;i<5;i++) {
- stars[i]=memnew(TextureRect);
+ for (int i = 0; i < 5; i++) {
+ stars[i] = memnew(TextureRect);
rating_hb->add_child(stars[i]);
}
- price = memnew( Label );
+ price = memnew(Label);
price->set_text("Free");
vb->add_child(price);
- set_custom_minimum_size(Size2(250,100));
+ set_custom_minimum_size(Size2(250, 100));
set_h_size_flags(SIZE_EXPAND_FILL);
set_mouse_filter(MOUSE_FILTER_PASS);
@@ -162,20 +154,19 @@ EditorAssetLibraryItem::EditorAssetLibraryItem() {
//////////////////////////////////////////////////////////////////////////////
+void EditorAssetLibraryItemDescription::set_image(int p_type, int p_index, const Ref<Texture> &p_image) {
-void EditorAssetLibraryItemDescription::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
-
- switch(p_type) {
+ switch (p_type) {
case EditorAssetLibrary::IMAGE_QUEUE_ICON: {
- item->call("set_image",p_type,p_index,p_image);
- icon=p_image;
+ item->call("set_image", p_type, p_index, p_image);
+ icon = p_image;
} break;
case EditorAssetLibrary::IMAGE_QUEUE_THUMBNAIL: {
- for(int i=0;i<preview_images.size();i++) {
- if (preview_images[i].id==p_index) {
+ for (int i = 0; i < preview_images.size(); i++) {
+ if (preview_images[i].id == p_index) {
preview_images[i].button->set_icon(p_image);
break;
}
@@ -184,10 +175,10 @@ void EditorAssetLibraryItemDescription::set_image(int p_type,int p_index,const R
} break;
case EditorAssetLibrary::IMAGE_QUEUE_SCREENSHOT: {
- for(int i=0;i<preview_images.size();i++) {
- if (preview_images[i].id==p_index) {
+ for (int i = 0; i < preview_images.size(); i++) {
+ if (preview_images[i].id == p_index) {
preview_images[i].image = p_image;
- if(preview_images[i].button->is_pressed()) {
+ if (preview_images[i].button->is_pressed()) {
_preview_click(p_index);
}
break;
@@ -199,23 +190,22 @@ void EditorAssetLibraryItemDescription::set_image(int p_type,int p_index,const R
}
void EditorAssetLibraryItemDescription::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_image"),&EditorAssetLibraryItemDescription::set_image);
- ClassDB::bind_method(D_METHOD("_link_click"),&EditorAssetLibraryItemDescription::_link_click);
- ClassDB::bind_method(D_METHOD("_preview_click"),&EditorAssetLibraryItemDescription::_preview_click);
-
+ ClassDB::bind_method(D_METHOD("set_image"), &EditorAssetLibraryItemDescription::set_image);
+ ClassDB::bind_method(D_METHOD("_link_click"), &EditorAssetLibraryItemDescription::_link_click);
+ ClassDB::bind_method(D_METHOD("_preview_click"), &EditorAssetLibraryItemDescription::_preview_click);
}
-void EditorAssetLibraryItemDescription::_link_click(const String& p_url) {
+void EditorAssetLibraryItemDescription::_link_click(const String &p_url) {
ERR_FAIL_COND(!p_url.begins_with("http"));
OS::get_singleton()->shell_open(p_url);
}
void EditorAssetLibraryItemDescription::_preview_click(int p_id) {
- for(int i=0;i<preview_images.size();i++) {
- if(preview_images[i].id==p_id) {
+ for (int i = 0; i < preview_images.size(); i++) {
+ if (preview_images[i].id == p_id) {
preview_images[i].button->set_pressed(true);
- if(!preview_images[i].is_video) {
- if(preview_images[i].image.is_valid()) {
+ if (!preview_images[i].is_video) {
+ if (preview_images[i].image.is_valid()) {
preview->set_texture(preview_images[i].image);
}
} else {
@@ -227,40 +217,40 @@ void EditorAssetLibraryItemDescription::_preview_click(int p_id) {
}
}
-void EditorAssetLibraryItemDescription::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost,int p_version,const String& p_version_string,const String& p_description,const String& p_download_url,const String& p_browse_url,const String& p_sha256_hash) {
+void EditorAssetLibraryItemDescription::configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, int p_rating, const String &p_cost, int p_version, const String &p_version_string, const String &p_description, const String &p_download_url, const String &p_browse_url, const String &p_sha256_hash) {
- asset_id=p_asset_id;
- title=p_title;
- download_url=p_download_url;
- sha256=p_sha256_hash;
- item->configure(p_title,p_asset_id,p_category,p_category_id,p_author,p_author_id,p_rating,p_cost);
+ asset_id = p_asset_id;
+ title = p_title;
+ download_url = p_download_url;
+ sha256 = p_sha256_hash;
+ item->configure(p_title, p_asset_id, p_category, p_category_id, p_author, p_author_id, p_rating, p_cost);
description->clear();
- description->add_text("Version: "+p_version_string+"\n");
+ description->add_text("Version: " + p_version_string + "\n");
description->add_text("Contents: ");
description->push_meta(p_browse_url);
description->add_text("View Files");
description->pop();
description->add_text("\nDescription:\n\n");
- description->append_bbcode(p_description);
+ description->append_bbcode(p_description);
set_title(p_title);
}
-void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video,const String& p_url){
+void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video, const String &p_url) {
Preview preview;
- preview.id=p_id;
- preview.video_link=p_url;
- preview.is_video=p_video;
- preview.button = memnew( Button );
+ preview.id = p_id;
+ preview.video_link = p_url;
+ preview.is_video = p_video;
+ preview.button = memnew(Button);
preview.button->set_flat(true);
- preview.button->set_icon(get_icon("ThumbnailWait","EditorIcons"));
+ preview.button->set_icon(get_icon("ThumbnailWait", "EditorIcons"));
preview.button->set_toggle_mode(true);
preview.button->connect("pressed", this, "_preview_click", varray(p_id));
preview_hb->add_child(preview.button);
- if(!p_video) {
- preview.image=get_icon("ThumbnailWait","EditorIcons");
+ if (!p_video) {
+ preview.image = get_icon("ThumbnailWait", "EditorIcons");
}
- if(preview_images.size()==0 && !p_video) {
+ if (preview_images.size() == 0 && !p_video) {
_preview_click(p_id);
}
preview_images.push_back(preview);
@@ -268,158 +258,147 @@ void EditorAssetLibraryItemDescription::add_preview(int p_id, bool p_video,const
EditorAssetLibraryItemDescription::EditorAssetLibraryItemDescription() {
- VBoxContainer *vbox = memnew( VBoxContainer );
+ VBoxContainer *vbox = memnew(VBoxContainer);
add_child(vbox);
-
-
- HBoxContainer *hbox = memnew( HBoxContainer);
+ HBoxContainer *hbox = memnew(HBoxContainer);
vbox->add_child(hbox);
- vbox->add_constant_override("separation",15);
- VBoxContainer *desc_vbox = memnew( VBoxContainer );
+ vbox->add_constant_override("separation", 15);
+ VBoxContainer *desc_vbox = memnew(VBoxContainer);
hbox->add_child(desc_vbox);
- hbox->add_constant_override("separation",15);
+ hbox->add_constant_override("separation", 15);
- item = memnew( EditorAssetLibraryItem );
+ item = memnew(EditorAssetLibraryItem);
desc_vbox->add_child(item);
- desc_vbox->set_custom_minimum_size(Size2(300,0));
+ desc_vbox->set_custom_minimum_size(Size2(300, 0));
-
- PanelContainer * desc_bg = memnew( PanelContainer );
+ PanelContainer *desc_bg = memnew(PanelContainer);
desc_vbox->add_child(desc_bg);
desc_bg->set_v_size_flags(SIZE_EXPAND_FILL);
- description = memnew( RichTextLabel );
- description->connect("meta_clicked",this,"_link_click");
+ description = memnew(RichTextLabel);
+ description->connect("meta_clicked", this, "_link_click");
//desc_vbox->add_child(description);
desc_bg->add_child(description);
- desc_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
+ desc_bg->add_style_override("panel", get_stylebox("normal", "TextEdit"));
- preview = memnew( TextureRect );
- preview->set_custom_minimum_size(Size2(640,345));
+ preview = memnew(TextureRect);
+ preview->set_custom_minimum_size(Size2(640, 345));
hbox->add_child(preview);
- PanelContainer * previews_bg = memnew( PanelContainer );
+ PanelContainer *previews_bg = memnew(PanelContainer);
vbox->add_child(previews_bg);
- previews_bg->set_custom_minimum_size(Size2(0,85));
- previews_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
+ previews_bg->set_custom_minimum_size(Size2(0, 85));
+ previews_bg->add_style_override("panel", get_stylebox("normal", "TextEdit"));
- previews = memnew( ScrollContainer );
+ previews = memnew(ScrollContainer);
previews_bg->add_child(previews);
previews->set_enable_v_scroll(false);
previews->set_enable_h_scroll(true);
- preview_hb = memnew( HBoxContainer );
+ preview_hb = memnew(HBoxContainer);
preview_hb->set_v_size_flags(SIZE_EXPAND_FILL);
previews->add_child(preview_hb);
get_ok()->set_text("Install");
get_cancel()->set_text("Close");
-
-
-
}
///////////////////////////////////////////////////////////////////////////////////
-void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data) {
-
+void EditorAssetLibraryItemDownload::_http_download_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data) {
String error_text;
- print_line("COMPLETED: "+itos(p_status)+" code: "+itos(p_code)+" data size: "+itos(p_data.size()));
+ print_line("COMPLETED: " + itos(p_status) + " code: " + itos(p_code) + " data size: " + itos(p_data.size()));
- switch(p_status) {
+ switch (p_status) {
case HTTPRequest::RESULT_CANT_RESOLVE: {
- error_text=("Can't resolve hostname: "+host);
+ error_text = ("Can't resolve hostname: " + host);
status->set_text("Can't resolve.");
} break;
case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
case HTTPRequest::RESULT_CONNECTION_ERROR:
case HTTPRequest::RESULT_CHUNKED_BODY_SIZE_MISMATCH: {
- error_text=("Connection error, please try again.");
+ error_text = ("Connection error, please try again.");
status->set_text("Can't connect.");
} break;
case HTTPRequest::RESULT_SSL_HANDSHAKE_ERROR:
case HTTPRequest::RESULT_CANT_CONNECT: {
- error_text=("Can't connect to host: "+host);
+ error_text = ("Can't connect to host: " + host);
status->set_text("Can't connect.");
} break;
case HTTPRequest::RESULT_NO_RESPONSE: {
- error_text=("No response from host: "+host);
+ error_text = ("No response from host: " + host);
status->set_text("No response.");
} break;
case HTTPRequest::RESULT_REQUEST_FAILED: {
- error_text=("Request failed, return code: "+itos(p_code));
+ error_text = ("Request failed, return code: " + itos(p_code));
status->set_text("Req. Failed.");
} break;
case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
- error_text=("Request failed, too many redirects");
+ error_text = ("Request failed, too many redirects");
status->set_text("Redirect Loop.");
} break;
default: {
- if (p_code!=200) {
- error_text=("Request failed, return code: "+itos(p_code));
- status->set_text("Failed: "+itos(p_code));
- } else if(sha256 != "") {
+ if (p_code != 200) {
+ error_text = ("Request failed, return code: " + itos(p_code));
+ status->set_text("Failed: " + itos(p_code));
+ } else if (sha256 != "") {
String download_sha256 = FileAccess::get_sha256(download->get_download_file());
- if(sha256 != download_sha256) {
- error_text="Bad download hash, assuming file has been tampered with.\nExpected: " + sha256 + "\nGot: " + download_sha256;
+ if (sha256 != download_sha256) {
+ error_text = "Bad download hash, assuming file has been tampered with.\nExpected: " + sha256 + "\nGot: " + download_sha256;
status->set_text("Failed sha256 hash check");
}
}
} break;
-
}
- if (error_text!=String()) {
- download_error->set_text("Asset Download Error:\n"+error_text);
+ if (error_text != String()) {
+ download_error->set_text("Asset Download Error:\n" + error_text);
download_error->popup_centered_minsize();
return;
-
}
- progress->set_max( download->get_body_size() );
+ progress->set_max(download->get_body_size());
progress->set_value(download->get_downloaded_bytes());
- print_line("max: "+itos(download->get_body_size())+" bytes: "+itos(download->get_downloaded_bytes()));
+ print_line("max: " + itos(download->get_body_size()) + " bytes: " + itos(download->get_downloaded_bytes()));
install->set_disabled(false);
progress->set_value(download->get_downloaded_bytes());
- status->set_text("Success! ("+String::humanize_size(download->get_downloaded_bytes())+")");
+ status->set_text("Success! (" + String::humanize_size(download->get_downloaded_bytes()) + ")");
set_process(false);
}
-
-void EditorAssetLibraryItemDownload::configure(const String& p_title,int p_asset_id,const Ref<Texture>& p_preview, const String& p_download_url, const String& p_sha256_hash) {
+void EditorAssetLibraryItemDownload::configure(const String &p_title, int p_asset_id, const Ref<Texture> &p_preview, const String &p_download_url, const String &p_sha256_hash) {
title->set_text(p_title);
icon->set_texture(p_preview);
- asset_id=p_asset_id;
+ asset_id = p_asset_id;
if (!p_preview.is_valid())
- icon->set_texture(get_icon("GodotAssetDefault","EditorIcons"));
- host=p_download_url;
- sha256=p_sha256_hash;
- asset_installer->connect("confirmed",this,"_close");
- dismiss->set_normal_texture( get_icon("Close","EditorIcons"));
+ icon->set_texture(get_icon("GodotAssetDefault", "EditorIcons"));
+ host = p_download_url;
+ sha256 = p_sha256_hash;
+ asset_installer->connect("confirmed", this, "_close");
+ dismiss->set_normal_texture(get_icon("Close", "EditorIcons"));
_make_request();
}
-
void EditorAssetLibraryItemDownload::_notification(int p_what) {
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
- progress->set_max( download->get_body_size() );
+ progress->set_max(download->get_body_size());
progress->set_value(download->get_downloaded_bytes());
int cstatus = download->get_http_client_status();
- if (cstatus==HTTPClient::STATUS_BODY)
- status->set_text("Fetching: "+String::humanize_size(download->get_downloaded_bytes()));
+ if (cstatus == HTTPClient::STATUS_BODY)
+ status->set_text("Fetching: " + String::humanize_size(download->get_downloaded_bytes()));
- if (cstatus!=prev_status) {
- switch(cstatus) {
+ if (cstatus != prev_status) {
+ switch (cstatus) {
case HTTPClient::STATUS_RESOLVING: {
status->set_text("Resolving..");
@@ -432,9 +411,8 @@ void EditorAssetLibraryItemDownload::_notification(int p_what) {
} break;
default: {}
}
- prev_status=cstatus;
+ prev_status = cstatus;
}
-
}
}
void EditorAssetLibraryItemDownload::_close() {
@@ -450,20 +428,19 @@ void EditorAssetLibraryItemDownload::_install() {
String file = download->get_download_file();
if (external_install) {
- emit_signal("install_asset",file,title->get_text());
+ emit_signal("install_asset", file, title->get_text());
return;
}
-
- asset_installer->open(file,1);
+ asset_installer->open(file, 1);
}
void EditorAssetLibraryItemDownload::_make_request() {
download->cancel_request();
- download->set_download_file(EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("tmp_asset_"+itos(asset_id))+".zip");
+ download->set_download_file(EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("tmp_asset_" + itos(asset_id)) + ".zip");
Error err = download->request(host);
- if(err!=OK) {
+ if (err != OK) {
status->set_text("Error making request");
} else {
set_process(true);
@@ -472,114 +449,107 @@ void EditorAssetLibraryItemDownload::_make_request() {
void EditorAssetLibraryItemDownload::_bind_methods() {
- ClassDB::bind_method("_http_download_completed",&EditorAssetLibraryItemDownload::_http_download_completed);
- ClassDB::bind_method("_install",&EditorAssetLibraryItemDownload::_install);
- ClassDB::bind_method("_close",&EditorAssetLibraryItemDownload::_close);
- ClassDB::bind_method("_make_request",&EditorAssetLibraryItemDownload::_make_request);
-
- ADD_SIGNAL(MethodInfo("install_asset",PropertyInfo(Variant::STRING,"zip_path"),PropertyInfo(Variant::STRING,"name")));
+ ClassDB::bind_method("_http_download_completed", &EditorAssetLibraryItemDownload::_http_download_completed);
+ ClassDB::bind_method("_install", &EditorAssetLibraryItemDownload::_install);
+ ClassDB::bind_method("_close", &EditorAssetLibraryItemDownload::_close);
+ ClassDB::bind_method("_make_request", &EditorAssetLibraryItemDownload::_make_request);
+ ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
}
EditorAssetLibraryItemDownload::EditorAssetLibraryItemDownload() {
- HBoxContainer *hb = memnew( HBoxContainer);
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
- icon = memnew( TextureRect );
+ icon = memnew(TextureRect);
hb->add_child(icon);
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
hb->add_child(vb);
vb->set_h_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *title_hb = memnew( HBoxContainer);
+ HBoxContainer *title_hb = memnew(HBoxContainer);
vb->add_child(title_hb);
- title = memnew( Label );
+ title = memnew(Label);
title_hb->add_child(title);
title->set_h_size_flags(SIZE_EXPAND_FILL);
- dismiss = memnew( TextureButton );
- dismiss->connect("pressed",this,"_close");
+ dismiss = memnew(TextureButton);
+ dismiss->connect("pressed", this, "_close");
title_hb->add_child(dismiss);
title->set_clip_text(true);
vb->add_spacer();
- status = memnew (Label("Idle"));
+ status = memnew(Label("Idle"));
vb->add_child(status);
- status->add_color_override("font_color", Color(0.5,0.5,0.5) );
- progress = memnew( ProgressBar );
+ status->add_color_override("font_color", Color(0.5, 0.5, 0.5));
+ progress = memnew(ProgressBar);
vb->add_child(progress);
-
-
- HBoxContainer *hb2 = memnew( HBoxContainer );
+ HBoxContainer *hb2 = memnew(HBoxContainer);
vb->add_child(hb2);
hb2->add_spacer();
- install = memnew( Button );
+ install = memnew(Button);
install->set_text("Install");
install->set_disabled(true);
- install->connect("pressed",this,"_install");
+ install->connect("pressed", this, "_install");
- retry = memnew( Button );
+ retry = memnew(Button);
retry->set_text("Retry");
- retry->connect("pressed",this,"_make_request");
+ retry->connect("pressed", this, "_make_request");
hb2->add_child(retry);
hb2->add_child(install);
- set_custom_minimum_size(Size2(250,0));
+ set_custom_minimum_size(Size2(250, 0));
- download = memnew( HTTPRequest );
+ download = memnew(HTTPRequest);
add_child(download);
- download->connect("request_completed",this,"_http_download_completed");
+ download->connect("request_completed", this, "_http_download_completed");
- download_error = memnew( AcceptDialog );
+ download_error = memnew(AcceptDialog);
add_child(download_error);
download_error->set_title("Download Error");
- asset_installer = memnew( EditorAssetInstaller );
+ asset_installer = memnew(EditorAssetInstaller);
add_child(asset_installer);
- prev_status=-1;
-
- external_install=false;
-
+ prev_status = -1;
+ external_install = false;
}
-
-
////////////////////////////////////////////////////////////////////////////////
void EditorAssetLibrary::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
TextureRect *tf = memnew(TextureRect);
- tf->set_texture(get_icon("Error","EditorIcons"));
- reverse->set_icon(get_icon("Updown","EditorIcons"));
+ tf->set_texture(get_icon("Error", "EditorIcons"));
+ reverse->set_icon(get_icon("Updown", "EditorIcons"));
error_hb->add_child(tf);
error_label->raise();
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
- if(is_visible()) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
+ if (is_visible()) {
_repository_changed(0); // Update when shown for the first time
}
}
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
HTTPClient::Status s = request->get_http_client_status();
- bool visible = s!=HTTPClient::STATUS_DISCONNECTED;
+ bool visible = s != HTTPClient::STATUS_DISCONNECTED;
if (visible != load_status->is_visible()) {
load_status->set_visible(visible);
}
if (visible) {
- switch(s) {
+ switch (s) {
case HTTPClient::STATUS_RESOLVING: {
load_status->set_value(0.1);
@@ -594,26 +564,23 @@ void EditorAssetLibrary::_notification(int p_what) {
load_status->set_value(0.4);
} break;
default: {}
-
}
}
- bool no_downloads = downloads_hb->get_child_count()==0;
+ bool no_downloads = downloads_hb->get_child_count() == 0;
if (no_downloads == downloads_scroll->is_visible()) {
downloads_scroll->set_visible(!no_downloads);
}
}
-
}
-
void EditorAssetLibrary::_install_asset() {
ERR_FAIL_COND(!description);
- for(int i=0;i<downloads_hb->get_child_count();i++) {
+ for (int i = 0; i < downloads_hb->get_child_count(); i++) {
- EditorAssetLibraryItemDownload *d = downloads_hb->get_child(i)->cast_to<EditorAssetLibraryItemDownload>();
+ EditorAssetLibraryItemDownload *d = downloads_hb->get_child(i)->cast_to<EditorAssetLibraryItemDownload>();
if (d && d->get_asset_id() == description->get_asset_id()) {
if (EditorNode::get_singleton() != NULL)
@@ -622,19 +589,17 @@ void EditorAssetLibrary::_install_asset() {
}
}
-
- EditorAssetLibraryItemDownload * download = memnew( EditorAssetLibraryItemDownload );
+ EditorAssetLibraryItemDownload *download = memnew(EditorAssetLibraryItemDownload);
downloads_hb->add_child(download);
- download->configure(description->get_title(),description->get_asset_id(),description->get_preview_icon(),description->get_download_url(),description->get_sha256());
+ download->configure(description->get_title(), description->get_asset_id(), description->get_preview_icon(), description->get_download_url(), description->get_sha256());
if (templates_only) {
download->set_external_install(true);
- download->connect("install_asset",this,"_install_external_asset");
+ download->connect("install_asset", this, "_install_external_asset");
}
-
}
-const char* EditorAssetLibrary::sort_key[SORT_MAX]={
+const char *EditorAssetLibrary::sort_key[SORT_MAX] = {
"rating",
"downloads",
"name",
@@ -642,7 +607,7 @@ const char* EditorAssetLibrary::sort_key[SORT_MAX]={
"updated"
};
-const char* EditorAssetLibrary::sort_text[SORT_MAX]={
+const char *EditorAssetLibrary::sort_text[SORT_MAX] = {
"Rating",
"Downloads",
"Name",
@@ -650,35 +615,34 @@ const char* EditorAssetLibrary::sort_text[SORT_MAX]={
"Updated"
};
-const char* EditorAssetLibrary::support_key[SUPPORT_MAX]={
+const char *EditorAssetLibrary::support_key[SUPPORT_MAX] = {
"official",
"community",
"testing"
};
-
void EditorAssetLibrary::_select_author(int p_id) {
//opemn author window
}
-void EditorAssetLibrary::_select_category(int p_id){
+void EditorAssetLibrary::_select_category(int p_id) {
- for(int i=0;i<categories->get_item_count();i++) {
+ for (int i = 0; i < categories->get_item_count(); i++) {
- if (i==0)
+ if (i == 0)
continue;
int id = categories->get_item_metadata(i);
- if (id==p_id) {
+ if (id == p_id) {
categories->select(i);
_search();
break;
}
}
}
-void EditorAssetLibrary::_select_asset(int p_id){
+void EditorAssetLibrary::_select_asset(int p_id) {
- _api_request("asset/"+itos(p_id), REQUESTING_ASSET);
+ _api_request("asset/" + itos(p_id), REQUESTING_ASSET);
/*
if (description) {
@@ -691,43 +655,43 @@ void EditorAssetLibrary::_select_asset(int p_id){
description->popup_centered_minsize();*/
}
-void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PoolByteArray& p_data, int p_queue_id) {
+void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PoolByteArray &p_data, int p_queue_id) {
Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
if (obj) {
bool image_set = false;
PoolByteArray image_data = p_data;
-
- if(use_cache) {
- String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_"+image_queue[p_queue_id].image_url.md5_text());
-
- FileAccess* file = FileAccess::open(cache_filename_base+".data", FileAccess::READ);
-
- if(file) {
+
+ if (use_cache) {
+ String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
+
+ FileAccess *file = FileAccess::open(cache_filename_base + ".data", FileAccess::READ);
+
+ if (file) {
PoolByteArray cached_data;
- int len=file->get_32();
+ int len = file->get_32();
cached_data.resize(len);
-
- PoolByteArray::Write w=cached_data.write();
+
+ PoolByteArray::Write w = cached_data.write();
file->get_buffer(w.ptr(), len);
-
+
image_data = cached_data;
file->close();
}
}
-
- int len=image_data.size();
- PoolByteArray::Read r=image_data.read();
- Image image(r.ptr(),len);
+
+ int len = image_data.size();
+ PoolByteArray::Read r = image_data.read();
+ Image image(r.ptr(), len);
if (!image.empty()) {
float max_height = 10000;
- switch(image_queue[p_queue_id].image_type) {
- case IMAGE_QUEUE_ICON: max_height=80; break;
- case IMAGE_QUEUE_THUMBNAIL: max_height=80; break;
- case IMAGE_QUEUE_SCREENSHOT: max_height=345; break;
+ switch (image_queue[p_queue_id].image_type) {
+ case IMAGE_QUEUE_ICON: max_height = 80; break;
+ case IMAGE_QUEUE_THUMBNAIL: max_height = 80; break;
+ case IMAGE_QUEUE_SCREENSHOT: max_height = 345; break;
}
float scale_ratio = max_height / image.get_height();
- if(scale_ratio < 1) {
+ if (scale_ratio < 1) {
image.resize(image.get_width() * scale_ratio, image.get_height() * scale_ratio, Image::INTERPOLATE_CUBIC);
}
@@ -735,57 +699,57 @@ void EditorAssetLibrary::_image_update(bool use_cache, bool final, const PoolByt
tex.instance();
tex->create_from_image(image);
- obj->call("set_image",image_queue[p_queue_id].image_type,image_queue[p_queue_id].image_index,tex);
+ obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, tex);
image_set = true;
}
-
- if(!image_set && final) {
- obj->call("set_image",image_queue[p_queue_id].image_type,image_queue[p_queue_id].image_index,get_icon("ErrorSign","EditorIcons"));
+
+ if (!image_set && final) {
+ obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("ErrorSign", "EditorIcons"));
}
}
}
-void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data,int p_queue_id) {
+void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data, int p_queue_id) {
+
+ ERR_FAIL_COND(!image_queue.has(p_queue_id));
- ERR_FAIL_COND( !image_queue.has(p_queue_id) );
+ if (p_status == HTTPRequest::RESULT_SUCCESS) {
- if (p_status==HTTPRequest::RESULT_SUCCESS) {
-
print_line("GOT IMAGE YAY!");
-
- if(p_code != HTTPClient::RESPONSE_NOT_MODIFIED) {
- for(int i=0;i<headers.size();i++) {
- if (headers[i].findn("ETag:")==0) { // Save etag
- String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_"+image_queue[p_queue_id].image_url.md5_text());
- String new_etag = headers[i].substr(headers[i].find(":")+1,headers[i].length()).strip_edges();
- FileAccess* file;
-
- file = FileAccess::open(cache_filename_base+".etag", FileAccess::WRITE);
- if(file) {
+
+ if (p_code != HTTPClient::RESPONSE_NOT_MODIFIED) {
+ for (int i = 0; i < headers.size(); i++) {
+ if (headers[i].findn("ETag:") == 0) { // Save etag
+ String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_" + image_queue[p_queue_id].image_url.md5_text());
+ String new_etag = headers[i].substr(headers[i].find(":") + 1, headers[i].length()).strip_edges();
+ FileAccess *file;
+
+ file = FileAccess::open(cache_filename_base + ".etag", FileAccess::WRITE);
+ if (file) {
file->store_line(new_etag);
file->close();
}
-
- int len=p_data.size();
- PoolByteArray::Read r=p_data.read();
- file = FileAccess::open(cache_filename_base+".data", FileAccess::WRITE);
- if(file) {
+
+ int len = p_data.size();
+ PoolByteArray::Read r = p_data.read();
+ file = FileAccess::open(cache_filename_base + ".data", FileAccess::WRITE);
+ if (file) {
file->store_32(len);
- file->store_buffer(r.ptr(),len);
+ file->store_buffer(r.ptr(), len);
file->close();
}
-
+
break;
}
}
}
_image_update(p_code == HTTPClient::RESPONSE_NOT_MODIFIED, true, p_data, p_queue_id);
-
+
} else {
- WARN_PRINTS("Error getting PNG file for asset id "+itos(image_queue[p_queue_id].asset_id));
+ WARN_PRINTS("Error getting PNG file for asset id " + itos(image_queue[p_queue_id].asset_id));
Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
if (obj) {
- obj->call("set_image",image_queue[p_queue_id].image_type,image_queue[p_queue_id].image_index,get_icon("ErrorSign","EditorIcons"));
+ obj->call("set_image", image_queue[p_queue_id].image_type, image_queue[p_queue_id].image_index, get_icon("ErrorSign", "EditorIcons"));
}
}
@@ -793,35 +757,34 @@ void EditorAssetLibrary::_image_request_completed(int p_status, int p_code, cons
image_queue.erase(p_queue_id);
_update_image_queue();
-
}
void EditorAssetLibrary::_update_image_queue() {
- int max_images=2;
- int current_images=0;
+ int max_images = 2;
+ int current_images = 0;
List<int> to_delete;
- for (Map<int,ImageQueue>::Element *E=image_queue.front();E;E=E->next()) {
- if (!E->get().active && current_images<max_images) {
-
- String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_"+E->get().image_url.md5_text());
+ for (Map<int, ImageQueue>::Element *E = image_queue.front(); E; E = E->next()) {
+ if (!E->get().active && current_images < max_images) {
+
+ String cache_filename_base = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp").plus_file("assetimage_" + E->get().image_url.md5_text());
Vector<String> headers;
-
- if(FileAccess::exists(cache_filename_base+".etag") && FileAccess::exists(cache_filename_base+".data")) {
- FileAccess* file = FileAccess::open(cache_filename_base+".etag", FileAccess::READ);
+
+ if (FileAccess::exists(cache_filename_base + ".etag") && FileAccess::exists(cache_filename_base + ".data")) {
+ FileAccess *file = FileAccess::open(cache_filename_base + ".etag", FileAccess::READ);
if (file) {
headers.push_back("If-None-Match: " + file->get_line());
file->close();
}
}
- print_line("REQUEST ICON FOR: "+itos(E->get().asset_id));
+ print_line("REQUEST ICON FOR: " + itos(E->get().asset_id));
Error err = E->get().request->request(E->get().image_url, headers);
- if (err!=OK) {
+ if (err != OK) {
to_delete.push_back(E->key());
} else {
- E->get().active=true;
+ E->get().active = true;
}
current_images++;
} else if (E->get().active) {
@@ -829,42 +792,39 @@ void EditorAssetLibrary::_update_image_queue() {
}
}
- while(to_delete.size()) {
+ while (to_delete.size()) {
image_queue[to_delete.front()->get()].request->queue_delete();
image_queue.erase(to_delete.front()->get());
to_delete.pop_front();
}
}
-void EditorAssetLibrary::_request_image(ObjectID p_for,String p_image_url,ImageType p_type,int p_image_index) {
-
+void EditorAssetLibrary::_request_image(ObjectID p_for, String p_image_url, ImageType p_type, int p_image_index) {
ImageQueue iq;
- iq.image_url=p_image_url;
- iq.image_index=p_image_index;
- iq.image_type=p_type;
- iq.request = memnew( HTTPRequest );
+ iq.image_url = p_image_url;
+ iq.image_index = p_image_index;
+ iq.image_type = p_type;
+ iq.request = memnew(HTTPRequest);
- iq.target=p_for;
- iq.queue_id=++last_queue_id;
- iq.active=false;
+ iq.target = p_for;
+ iq.queue_id = ++last_queue_id;
+ iq.active = false;
- iq.request->connect("request_completed",this,"_image_request_completed",varray(iq.queue_id));
+ iq.request->connect("request_completed", this, "_image_request_completed", varray(iq.queue_id));
- image_queue[iq.queue_id]=iq;
+ image_queue[iq.queue_id] = iq;
add_child(iq.request);
_image_update(true, false, PoolByteArray(), iq.queue_id);
_update_image_queue();
-
-
}
void EditorAssetLibrary::_repository_changed(int p_repository_id) {
- host=repository->get_item_metadata(p_repository_id);
+ host = repository->get_item_metadata(p_repository_id);
print_line(".." + host);
- if(templates_only) {
+ if (templates_only) {
_api_request("configure", REQUESTING_CONFIG, "?type=project");
} else {
_api_request("configure", REQUESTING_CONFIG);
@@ -884,121 +844,119 @@ void EditorAssetLibrary::_search(int p_page) {
String args;
- if(templates_only) {
+ if (templates_only) {
args += "?type=project&";
} else {
args += "?";
}
- args+=String()+"sort="+sort_key[sort->get_selected()];
+ args += String() + "sort=" + sort_key[sort->get_selected()];
-
String support_list;
- for(int i = 0; i < SUPPORT_MAX; i++) {
- if(support->get_popup()->is_item_checked(i)) {
+ for (int i = 0; i < SUPPORT_MAX; i++) {
+ if (support->get_popup()->is_item_checked(i)) {
support_list += String(support_key[i]) + "+";
}
}
- if(support_list != String()) {
+ if (support_list != String()) {
args += "&support=" + support_list.substr(0, support_list.length() - 1);
}
- if (categories->get_selected()>0) {
+ if (categories->get_selected() > 0) {
- args+="&category="+itos(categories->get_item_metadata(categories->get_selected()));
+ args += "&category=" + itos(categories->get_item_metadata(categories->get_selected()));
}
-
+
if (reverse->is_pressed()) {
- args+="&reverse=true";
+ args += "&reverse=true";
}
-
- if (filter->get_text()!=String()) {
- args+="&filter="+filter->get_text().http_escape();
+
+ if (filter->get_text() != String()) {
+ args += "&filter=" + filter->get_text().http_escape();
}
- if (p_page>0) {
- args+="&page="+itos(p_page);
+ if (p_page > 0) {
+ args += "&page=" + itos(p_page);
}
- _api_request("asset",REQUESTING_SEARCH,args);
+ _api_request("asset", REQUESTING_SEARCH, args);
}
-HBoxContainer* EditorAssetLibrary::_make_pages(int p_page,int p_page_count,int p_page_len,int p_total_items,int p_current_items) {
+HBoxContainer *EditorAssetLibrary::_make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items) {
- HBoxContainer * hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
//do the mario
- int from = p_page-5;
- if (from<0)
- from=0;
- int to = from+10;
- if (to>p_page_count)
- to=p_page_count;
+ int from = p_page - 5;
+ if (from < 0)
+ from = 0;
+ int to = from + 10;
+ if (to > p_page_count)
+ to = p_page_count;
- Color gray = Color(0.65,0.65,0.65);
+ Color gray = Color(0.65, 0.65, 0.65);
hbc->add_spacer();
- hbc->add_constant_override("separation",10);
+ hbc->add_constant_override("separation", 10);
- if(p_page != 0) {
- LinkButton *first = memnew( LinkButton );
+ if (p_page != 0) {
+ LinkButton *first = memnew(LinkButton);
first->set_text("first");
- first->add_color_override("font_color", gray );
+ first->add_color_override("font_color", gray);
first->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- first->connect("pressed",this,"_search",varray(0));
+ first->connect("pressed", this, "_search", varray(0));
hbc->add_child(first);
}
- if (p_page>0) {
- LinkButton *prev = memnew( LinkButton );
+ if (p_page > 0) {
+ LinkButton *prev = memnew(LinkButton);
prev->set_text("prev");
- prev->add_color_override("font_color", gray );
+ prev->add_color_override("font_color", gray);
prev->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- prev->connect("pressed",this,"_search",varray(p_page-1));
+ prev->connect("pressed", this, "_search", varray(p_page - 1));
hbc->add_child(prev);
}
- for(int i=from;i<to;i++) {
+ for (int i = from; i < to; i++) {
- if (i==p_page) {
+ if (i == p_page) {
Label *current = memnew(Label);
- current->set_text(itos(i+1));
+ current->set_text(itos(i + 1));
hbc->add_child(current);
} else {
- LinkButton *current = memnew( LinkButton );
- current->add_color_override("font_color", gray );
+ LinkButton *current = memnew(LinkButton);
+ current->add_color_override("font_color", gray);
current->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- current->set_text(itos(i+1));
- current->connect("pressed",this,"_search",varray(i));
+ current->set_text(itos(i + 1));
+ current->connect("pressed", this, "_search", varray(i));
hbc->add_child(current);
-
}
}
- if (p_page<p_page_count-1) {
- LinkButton *next = memnew( LinkButton );
+ if (p_page < p_page_count - 1) {
+ LinkButton *next = memnew(LinkButton);
next->set_text("next");
- next->add_color_override("font_color", gray );
+ next->add_color_override("font_color", gray);
next->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
- next->connect("pressed",this,"_search",varray(p_page+1));
+ next->connect("pressed", this, "_search", varray(p_page + 1));
hbc->add_child(next);
}
- if(p_page != p_page_count-1) {
- LinkButton *last = memnew( LinkButton );
+ if (p_page != p_page_count - 1) {
+ LinkButton *last = memnew(LinkButton);
last->set_text("last");
- last->add_color_override("font_color", gray );
+ last->add_color_override("font_color", gray);
last->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
hbc->add_child(last);
- last->connect("pressed",this,"_search",varray(p_page_count-1));
+ last->connect("pressed", this, "_search", varray(p_page_count - 1));
}
- Label *totals = memnew( Label );
- totals->set_text("( "+itos(from*p_page_len)+" - "+itos(from*p_page_len+p_current_items-1)+" / "+itos(p_total_items)+" )");
+ Label *totals = memnew(Label);
+ totals->set_text("( " + itos(from * p_page_len) + " - " + itos(from * p_page_len + p_current_items - 1) + " / " + itos(p_total_items) + " )");
hbc->add_child(totals);
hbc->add_spacer();
@@ -1006,38 +964,34 @@ HBoxContainer* EditorAssetLibrary::_make_pages(int p_page,int p_page_count,int p
return hbc;
}
+void EditorAssetLibrary::_api_request(const String &p_request, RequestType p_request_type, const String &p_arguments) {
-void EditorAssetLibrary::_api_request(const String& p_request, RequestType p_request_type, const String& p_arguments) {
-
- if (requesting!=REQUESTING_NONE) {
+ if (requesting != REQUESTING_NONE) {
request->cancel_request();
}
- requesting=p_request_type;
+ requesting = p_request_type;
error_hb->hide();
- request->request(host+"/"+p_request+p_arguments);
+ request->request(host + "/" + p_request + p_arguments);
}
-
-
-void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data) {
-
+void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data) {
String str;
{
- int datalen=p_data.size();
+ int datalen = p_data.size();
PoolByteArray::Read r = p_data.read();
- str.parse_utf8((const char*)r.ptr(),datalen);
+ str.parse_utf8((const char *)r.ptr(), datalen);
}
- bool error_abort=true;
+ bool error_abort = true;
- switch(p_status) {
+ switch (p_status) {
case HTTPRequest::RESULT_CANT_RESOLVE: {
- error_label->set_text("Can't resolve hostname: "+host);
+ error_label->set_text("Can't resolve hostname: " + host);
} break;
case HTTPRequest::RESULT_BODY_SIZE_LIMIT_EXCEEDED:
case HTTPRequest::RESULT_CONNECTION_ERROR:
@@ -1046,68 +1000,65 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const
} break;
case HTTPRequest::RESULT_SSL_HANDSHAKE_ERROR:
case HTTPRequest::RESULT_CANT_CONNECT: {
- error_label->set_text("Can't connect to host: "+host);
+ error_label->set_text("Can't connect to host: " + host);
} break;
case HTTPRequest::RESULT_NO_RESPONSE: {
- error_label->set_text("No response from host: "+host);
+ error_label->set_text("No response from host: " + host);
} break;
case HTTPRequest::RESULT_REQUEST_FAILED: {
- error_label->set_text("Request failed, return code: "+itos(p_code));
+ error_label->set_text("Request failed, return code: " + itos(p_code));
} break;
case HTTPRequest::RESULT_REDIRECT_LIMIT_REACHED: {
error_label->set_text("Request failed, too many redirects");
} break;
default: {
- if (p_code!=200) {
- error_label->set_text("Request failed, return code: "+itos(p_code));
+ if (p_code != 200) {
+ error_label->set_text("Request failed, return code: " + itos(p_code));
} else {
- error_abort=false;
+ error_abort = false;
}
} break;
-
}
-
if (error_abort) {
error_hb->show();
return;
}
- print_line("response: "+itos(p_status)+" code: "+itos(p_code));
+ print_line("response: " + itos(p_status) + " code: " + itos(p_code));
Dictionary d;
{
Variant js;
String errs;
int errl;
- JSON::parse(str,js,errs,errl);
- d=js;
+ JSON::parse(str, js, errs, errl);
+ d = js;
}
-
print_line(Variant(d).get_construct_string());
RequestType requested = requesting;
- requesting=REQUESTING_NONE;
+ requesting = REQUESTING_NONE;
- switch(requested) {
+ switch (requested) {
case REQUESTING_CONFIG: {
categories->clear();
categories->add_item("All");
- categories->set_item_metadata(0,0);
+ categories->set_item_metadata(0, 0);
if (d.has("categories")) {
Array clist = d["categories"];
- for(int i=0;i<clist.size();i++) {
+ for (int i = 0; i < clist.size(); i++) {
Dictionary cat = clist[i];
if (!cat.has("name") || !cat.has("id"))
continue;
- String name=cat["name"];
- int id=cat["id"];
+ String name = cat["name"];
+ int id = cat["id"];
categories->add_item(name);
- categories->set_item_metadata( categories->get_item_count() -1, id);
+ categories->set_item_metadata(categories->get_item_count() - 1, id);
category_map[cat["id"]] = name;
}
}
@@ -1127,43 +1078,42 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const
memdelete(asset_bottom_page);
}
- int page=0;
- int pages=1;
- int page_len=10;
- int total_items=1;
+ int page = 0;
+ int pages = 1;
+ int page_len = 10;
+ int total_items = 1;
Array result;
-
if (d.has("page")) {
- page=d["page"];
+ page = d["page"];
}
if (d.has("pages")) {
- pages=d["pages"];
+ pages = d["pages"];
}
if (d.has("page_length")) {
- page_len=d["page_length"];
+ page_len = d["page_length"];
}
if (d.has("total")) {
- total_items=d["total"];
+ total_items = d["total"];
}
if (d.has("result")) {
- result=d["result"];
+ result = d["result"];
}
- asset_top_page = _make_pages(page,pages,page_len,total_items,result.size());
+ asset_top_page = _make_pages(page, pages, page_len, total_items, result.size());
library_vb->add_child(asset_top_page);
- asset_items = memnew( GridContainer );
+ asset_items = memnew(GridContainer);
asset_items->set_columns(2);
- asset_items->add_constant_override("hseparation",10);
- asset_items->add_constant_override("vseparation",10);
+ asset_items->add_constant_override("hseparation", 10);
+ asset_items->add_constant_override("vseparation", 10);
library_vb->add_child(asset_items);
- asset_bottom_page = _make_pages(page,pages,page_len,total_items,result.size());
+ asset_bottom_page = _make_pages(page, pages, page_len, total_items, result.size());
library_vb->add_child(asset_bottom_page);
- for(int i=0;i<result.size();i++) {
+ for (int i = 0; i < result.size(); i++) {
Dictionary r = result[i];
@@ -1176,16 +1126,15 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const
ERR_CONTINUE(!r.has("rating"));
ERR_CONTINUE(!r.has("cost"));
-
- EditorAssetLibraryItem *item = memnew( EditorAssetLibraryItem );
+ EditorAssetLibraryItem *item = memnew(EditorAssetLibraryItem);
asset_items->add_child(item);
- item->configure(r["title"],r["asset_id"],category_map[r["category_id"]],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"]);
- item->connect("asset_selected",this,"_select_asset");
- item->connect("author_selected",this,"_select_author");
- item->connect("category_selected",this,"_select_category");
+ item->configure(r["title"], r["asset_id"], category_map[r["category_id"]], r["category_id"], r["author"], r["author_id"], r["rating"], r["cost"]);
+ item->connect("asset_selected", this, "_select_asset");
+ item->connect("author_selected", this, "_select_author");
+ item->connect("category_selected", this, "_select_category");
- if(r.has("icon_url") && r["icon_url"] != "") {
- _request_image(item->get_instance_ID(),r["icon_url"],IMAGE_QUEUE_ICON,0);
+ if (r.has("icon_url") && r["icon_url"] != "") {
+ _request_image(item->get_instance_ID(), r["icon_url"], IMAGE_QUEUE_ICON, 0);
}
}
} break;
@@ -1211,69 +1160,63 @@ void EditorAssetLibrary::_http_request_completed(int p_status, int p_code, const
memdelete(description);
}
- description = memnew( EditorAssetLibraryItemDescription );
+ description = memnew(EditorAssetLibraryItemDescription);
add_child(description);
description->popup_centered_minsize();
- description->connect("confirmed",this,"_install_asset");
+ description->connect("confirmed", this, "_install_asset");
- description->configure(r["title"],r["asset_id"],category_map[r["category_id"]],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"],r["version"],r["version_string"],r["description"],r["download_url"],r["browse_url"], r["download_hash"]);
+ description->configure(r["title"], r["asset_id"], category_map[r["category_id"]], r["category_id"], r["author"], r["author_id"], r["rating"], r["cost"], r["version"], r["version_string"], r["description"], r["download_url"], r["browse_url"], r["download_hash"]);
/*item->connect("asset_selected",this,"_select_asset");
item->connect("author_selected",this,"_select_author");
item->connect("category_selected",this,"_category_selected");*/
- if(r.has("icon_url") && r["icon_url"] != "") {
- _request_image(description->get_instance_ID(),r["icon_url"],IMAGE_QUEUE_ICON,0);
+ if (r.has("icon_url") && r["icon_url"] != "") {
+ _request_image(description->get_instance_ID(), r["icon_url"], IMAGE_QUEUE_ICON, 0);
}
if (d.has("previews")) {
Array previews = d["previews"];
- for(int i=0;i<previews.size();i++) {
+ for (int i = 0; i < previews.size(); i++) {
-
- Dictionary p=previews[i];
+ Dictionary p = previews[i];
ERR_CONTINUE(!p.has("type"));
ERR_CONTINUE(!p.has("link"));
- bool is_video=p.has("type") && String(p["type"])=="video";
+ bool is_video = p.has("type") && String(p["type"]) == "video";
String video_url;
if (is_video && p.has("link")) {
- video_url=p["link"];
+ video_url = p["link"];
}
- description->add_preview(i,is_video,video_url);
+ description->add_preview(i, is_video, video_url);
- if(p.has("thumbnail")) {
- _request_image(description->get_instance_ID(),p["thumbnail"],IMAGE_QUEUE_THUMBNAIL,i);
+ if (p.has("thumbnail")) {
+ _request_image(description->get_instance_ID(), p["thumbnail"], IMAGE_QUEUE_THUMBNAIL, i);
}
- if(is_video) {
+ if (is_video) {
//_request_image(description->get_instance_ID(),p["link"],IMAGE_QUEUE_SCREENSHOT,i);
} else {
- _request_image(description->get_instance_ID(),p["link"],IMAGE_QUEUE_SCREENSHOT,i);
+ _request_image(description->get_instance_ID(), p["link"], IMAGE_QUEUE_SCREENSHOT, i);
}
-
}
}
} break;
default: break;
}
-
}
-
-void EditorAssetLibrary::_asset_file_selected(const String& p_file) {
+void EditorAssetLibrary::_asset_file_selected(const String &p_file) {
if (asset_installer) {
- memdelete( asset_installer );
- asset_installer=NULL;
+ memdelete(asset_installer);
+ asset_installer = NULL;
}
- asset_installer = memnew( EditorAssetInstaller );
+ asset_installer = memnew(EditorAssetInstaller);
add_child(asset_installer);
asset_installer->open(p_file);
-
-
}
void EditorAssetLibrary::_asset_open() {
@@ -1287,94 +1230,86 @@ void EditorAssetLibrary::_manage_plugins() {
ProjectSettings::get_singleton()->set_plugins_page();
}
+void EditorAssetLibrary::_install_external_asset(String p_zip_path, String p_title) {
-
-void EditorAssetLibrary::_install_external_asset(String p_zip_path,String p_title) {
-
- emit_signal("install_asset",p_zip_path,p_title);
+ emit_signal("install_asset", p_zip_path, p_title);
}
void EditorAssetLibrary::_bind_methods() {
- ClassDB::bind_method("_http_request_completed",&EditorAssetLibrary::_http_request_completed);
- ClassDB::bind_method("_select_asset",&EditorAssetLibrary::_select_asset);
- ClassDB::bind_method("_select_author",&EditorAssetLibrary::_select_author);
- ClassDB::bind_method("_select_category",&EditorAssetLibrary::_select_category);
- ClassDB::bind_method("_image_request_completed",&EditorAssetLibrary::_image_request_completed);
- ClassDB::bind_method("_search",&EditorAssetLibrary::_search,DEFVAL(0));
- ClassDB::bind_method("_install_asset",&EditorAssetLibrary::_install_asset);
- ClassDB::bind_method("_manage_plugins",&EditorAssetLibrary::_manage_plugins);
- ClassDB::bind_method("_asset_open",&EditorAssetLibrary::_asset_open);
- ClassDB::bind_method("_asset_file_selected",&EditorAssetLibrary::_asset_file_selected);
- ClassDB::bind_method("_repository_changed",&EditorAssetLibrary::_repository_changed);
- ClassDB::bind_method("_support_toggled",&EditorAssetLibrary::_support_toggled);
- ClassDB::bind_method("_rerun_search",&EditorAssetLibrary::_rerun_search);
- ClassDB::bind_method("_install_external_asset",&EditorAssetLibrary::_install_external_asset);
-
-
-
- ADD_SIGNAL(MethodInfo("install_asset",PropertyInfo(Variant::STRING,"zip_path"),PropertyInfo(Variant::STRING,"name")));
-
+ ClassDB::bind_method("_http_request_completed", &EditorAssetLibrary::_http_request_completed);
+ ClassDB::bind_method("_select_asset", &EditorAssetLibrary::_select_asset);
+ ClassDB::bind_method("_select_author", &EditorAssetLibrary::_select_author);
+ ClassDB::bind_method("_select_category", &EditorAssetLibrary::_select_category);
+ ClassDB::bind_method("_image_request_completed", &EditorAssetLibrary::_image_request_completed);
+ ClassDB::bind_method("_search", &EditorAssetLibrary::_search, DEFVAL(0));
+ ClassDB::bind_method("_install_asset", &EditorAssetLibrary::_install_asset);
+ ClassDB::bind_method("_manage_plugins", &EditorAssetLibrary::_manage_plugins);
+ ClassDB::bind_method("_asset_open", &EditorAssetLibrary::_asset_open);
+ ClassDB::bind_method("_asset_file_selected", &EditorAssetLibrary::_asset_file_selected);
+ ClassDB::bind_method("_repository_changed", &EditorAssetLibrary::_repository_changed);
+ ClassDB::bind_method("_support_toggled", &EditorAssetLibrary::_support_toggled);
+ ClassDB::bind_method("_rerun_search", &EditorAssetLibrary::_rerun_search);
+ ClassDB::bind_method("_install_external_asset", &EditorAssetLibrary::_install_external_asset);
+
+ ADD_SIGNAL(MethodInfo("install_asset", PropertyInfo(Variant::STRING, "zip_path"), PropertyInfo(Variant::STRING, "name")));
}
EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
- templates_only=p_templates_only;
+ templates_only = p_templates_only;
Ref<StyleBoxEmpty> border;
border.instance();
- border->set_default_margin(MARGIN_LEFT,15);
- border->set_default_margin(MARGIN_RIGHT,15);
- border->set_default_margin(MARGIN_BOTTOM,5);
- border->set_default_margin(MARGIN_TOP,5);
+ border->set_default_margin(MARGIN_LEFT, 15);
+ border->set_default_margin(MARGIN_RIGHT, 15);
+ border->set_default_margin(MARGIN_BOTTOM, 5);
+ border->set_default_margin(MARGIN_TOP, 5);
- add_style_override("panel",border);
+ add_style_override("panel", border);
- VBoxContainer *library_main = memnew( VBoxContainer );
+ VBoxContainer *library_main = memnew(VBoxContainer);
add_child(library_main);
- HBoxContainer *search_hb = memnew( HBoxContainer );
+ HBoxContainer *search_hb = memnew(HBoxContainer);
library_main->add_child(search_hb);
- library_main->add_constant_override("separation",10);
-
-
+ library_main->add_constant_override("separation", 10);
- search_hb->add_child( memnew( Label(TTR("Search:")+" ")));
- filter =memnew( LineEdit );
+ search_hb->add_child(memnew(Label(TTR("Search:") + " ")));
+ filter = memnew(LineEdit);
search_hb->add_child(filter);
filter->set_h_size_flags(SIZE_EXPAND_FILL);
- filter->connect("text_entered",this,"_search");
- search = memnew( Button("Search"));
- search->connect("pressed",this,"_search");
+ filter->connect("text_entered", this, "_search");
+ search = memnew(Button("Search"));
+ search->connect("pressed", this, "_search");
search_hb->add_child(search);
if (!p_templates_only)
- search_hb->add_child(memnew( VSeparator ));
+ search_hb->add_child(memnew(VSeparator));
- Button * open_asset = memnew( Button );
+ Button *open_asset = memnew(Button);
open_asset->set_text("Import");
search_hb->add_child(open_asset);
- open_asset->connect("pressed",this,"_asset_open");
+ open_asset->connect("pressed", this, "_asset_open");
- Button * plugins = memnew( Button );
+ Button *plugins = memnew(Button);
plugins->set_text("Plugins");
search_hb->add_child(plugins);
- plugins->connect("pressed",this,"_manage_plugins");
+ plugins->connect("pressed", this, "_manage_plugins");
if (p_templates_only) {
open_asset->hide();
plugins->hide();
}
-
- HBoxContainer *search_hb2 = memnew( HBoxContainer );
+ HBoxContainer *search_hb2 = memnew(HBoxContainer);
library_main->add_child(search_hb2);
- search_hb2->add_child( memnew( Label(TTR("Sort:")+" ")));
- sort = memnew( OptionButton );
- for(int i=0;i<SORT_MAX;i++) {
+ search_hb2->add_child(memnew(Label(TTR("Sort:") + " ")));
+ sort = memnew(OptionButton);
+ for (int i = 0; i < SORT_MAX; i++) {
sort->add_item(sort_text[i]);
}
@@ -1383,7 +1318,7 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
sort->set_h_size_flags(SIZE_EXPAND_FILL);
sort->connect("item_selected", this, "_rerun_search");
- reverse = memnew( ToolButton );
+ reverse = memnew(ToolButton);
reverse->set_toggle_mode(true);
reverse->connect("toggled", this, "_rerun_search");
//reverse->set_text(TTR("Reverse"));
@@ -1393,8 +1328,8 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
//search_hb2->add_spacer();
- search_hb2->add_child( memnew( Label(TTR("Category:")+" ")));
- categories = memnew( OptionButton );
+ search_hb2->add_child(memnew(Label(TTR("Category:") + " ")));
+ categories = memnew(OptionButton);
categories->add_item(TTR("All"));
search_hb2->add_child(categories);
categories->set_h_size_flags(SIZE_EXPAND_FILL);
@@ -1403,128 +1338,120 @@ EditorAssetLibrary::EditorAssetLibrary(bool p_templates_only) {
search_hb2->add_child(memnew(VSeparator));
- search_hb2->add_child( memnew( Label(TTR("Site:")+" ")));
- repository = memnew( OptionButton );
+ search_hb2->add_child(memnew(Label(TTR("Site:") + " ")));
+ repository = memnew(OptionButton);
repository->add_item("Godot");
repository->set_item_metadata(0, "https://godotengine.org/asset-library/api");
repository->add_item("Localhost"); // TODO: Maybe remove?
repository->set_item_metadata(1, "http://127.0.0.1/asset-library/api");
- repository->connect("item_selected",this,"_repository_changed");
+ repository->connect("item_selected", this, "_repository_changed");
search_hb2->add_child(repository);
repository->set_h_size_flags(SIZE_EXPAND_FILL);
-
search_hb2->add_child(memnew(VSeparator));
- support = memnew( MenuButton );
+ support = memnew(MenuButton);
search_hb2->add_child(support);
support->set_text(TTR("Support.."));
- support->get_popup()->add_check_item(TTR("Official"),SUPPORT_OFFICIAL);
- support->get_popup()->add_check_item(TTR("Community"),SUPPORT_COMMUNITY);
- support->get_popup()->add_check_item(TTR("Testing"),SUPPORT_TESTING);
- support->get_popup()->set_item_checked(SUPPORT_OFFICIAL,true);
- support->get_popup()->set_item_checked(SUPPORT_COMMUNITY,true);
- support->get_popup()->connect("id_pressed",this,"_support_toggled");
+ support->get_popup()->add_check_item(TTR("Official"), SUPPORT_OFFICIAL);
+ support->get_popup()->add_check_item(TTR("Community"), SUPPORT_COMMUNITY);
+ support->get_popup()->add_check_item(TTR("Testing"), SUPPORT_TESTING);
+ support->get_popup()->set_item_checked(SUPPORT_OFFICIAL, true);
+ support->get_popup()->set_item_checked(SUPPORT_COMMUNITY, true);
+ support->get_popup()->connect("id_pressed", this, "_support_toggled");
/////////
- PanelContainer * library_scroll_bg = memnew( PanelContainer );
+ PanelContainer *library_scroll_bg = memnew(PanelContainer);
library_main->add_child(library_scroll_bg);
- library_scroll_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
+ library_scroll_bg->add_style_override("panel", get_stylebox("normal", "TextEdit"));
library_scroll_bg->set_v_size_flags(SIZE_EXPAND_FILL);
- library_scroll = memnew( ScrollContainer );
+ library_scroll = memnew(ScrollContainer);
library_scroll->set_enable_v_scroll(true);
library_scroll->set_enable_h_scroll(false);
library_scroll_bg->add_child(library_scroll);
-
Ref<StyleBoxEmpty> border2;
border2.instance();
- border2->set_default_margin(MARGIN_LEFT,15);
- border2->set_default_margin(MARGIN_RIGHT,35);
- border2->set_default_margin(MARGIN_BOTTOM,15);
- border2->set_default_margin(MARGIN_TOP,15);
+ border2->set_default_margin(MARGIN_LEFT, 15);
+ border2->set_default_margin(MARGIN_RIGHT, 35);
+ border2->set_default_margin(MARGIN_BOTTOM, 15);
+ border2->set_default_margin(MARGIN_TOP, 15);
-
- PanelContainer * library_vb_border = memnew( PanelContainer );
+ PanelContainer *library_vb_border = memnew(PanelContainer);
library_scroll->add_child(library_vb_border);
- library_vb_border->add_style_override("panel",border2);
+ library_vb_border->add_style_override("panel", border2);
library_vb_border->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->set_mouse_filter(MOUSE_FILTER_PASS);
-
-
- library_vb = memnew( VBoxContainer );
+ library_vb = memnew(VBoxContainer);
library_vb->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->add_child(library_vb);
//margin_panel->set_stop_mouse(false);
- asset_top_page = memnew( HBoxContainer );
+ asset_top_page = memnew(HBoxContainer);
library_vb->add_child(asset_top_page);
- asset_items = memnew( GridContainer );
+ asset_items = memnew(GridContainer);
asset_items->set_columns(2);
- asset_items->add_constant_override("hseparation",10);
- asset_items->add_constant_override("vseparation",10);
+ asset_items->add_constant_override("hseparation", 10);
+ asset_items->add_constant_override("vseparation", 10);
library_vb->add_child(asset_items);
- asset_bottom_page = memnew( HBoxContainer );
+ asset_bottom_page = memnew(HBoxContainer);
library_vb->add_child(asset_bottom_page);
- request = memnew( HTTPRequest );
+ request = memnew(HTTPRequest);
add_child(request);
- request->set_use_threads(EDITOR_DEF("asset_library/use_threads",true));
- request->connect("request_completed",this,"_http_request_completed");
+ request->set_use_threads(EDITOR_DEF("asset_library/use_threads", true));
+ request->connect("request_completed", this, "_http_request_completed");
- last_queue_id=0;
+ last_queue_id = 0;
- library_vb->add_constant_override("separation",20);
+ library_vb->add_constant_override("separation", 20);
- load_status = memnew( ProgressBar );
+ load_status = memnew(ProgressBar);
load_status->set_min(0);
load_status->set_max(1);
load_status->set_step(0.001);
library_main->add_child(load_status);
- error_hb = memnew( HBoxContainer );
+ error_hb = memnew(HBoxContainer);
library_main->add_child(error_hb);
- error_label = memnew( Label );
- error_label->add_color_override("color",Color(1,0.4,0.3));
+ error_label = memnew(Label);
+ error_label->add_color_override("color", Color(1, 0.4, 0.3));
error_hb->add_child(error_label);
description = NULL;
set_process(true);
- downloads_scroll = memnew( ScrollContainer );
+ downloads_scroll = memnew(ScrollContainer);
downloads_scroll->set_enable_h_scroll(true);
downloads_scroll->set_enable_v_scroll(false);
library_main->add_child(downloads_scroll);
- downloads_hb = memnew( HBoxContainer );
+ downloads_hb = memnew(HBoxContainer);
downloads_scroll->add_child(downloads_hb);
- asset_open = memnew( EditorFileDialog );
+ asset_open = memnew(EditorFileDialog);
asset_open->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
- asset_open->add_filter("*.zip ; "+TTR("Assets ZIP File"));
+ asset_open->add_filter("*.zip ; " + TTR("Assets ZIP File"));
asset_open->set_mode(EditorFileDialog::MODE_OPEN_FILE);
add_child(asset_open);
- asset_open->connect("file_selected",this,"_asset_file_selected");
-
- asset_installer=NULL;
+ asset_open->connect("file_selected", this, "_asset_file_selected");
+ asset_installer = NULL;
}
-
///////
-
void AssetLibraryEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
@@ -1534,20 +1461,17 @@ void AssetLibraryEditorPlugin::make_visible(bool p_visible) {
addon_library->hide();
}
-
}
AssetLibraryEditorPlugin::AssetLibraryEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- addon_library = memnew( EditorAssetLibrary );
+ editor = p_node;
+ addon_library = memnew(EditorAssetLibrary);
addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL);
editor->get_viewport()->add_child(addon_library);
addon_library->set_area_as_parent_rect();
addon_library->hide();
-
}
AssetLibraryEditorPlugin::~AssetLibraryEditorPlugin() {
-
}
diff --git a/editor/asset_library_editor_plugin.h b/editor/asset_library_editor_plugin.h
index 0598ea90ea..bdfd52cf4f 100644
--- a/editor/asset_library_editor_plugin.h
+++ b/editor/asset_library_editor_plugin.h
@@ -29,63 +29,57 @@
#ifndef ASSET_LIBRARY_EDITOR_PLUGIN_H
#define ASSET_LIBRARY_EDITOR_PLUGIN_H
-
#include "editor_plugin.h"
#include "scene/gui/box_container.h"
+#include "scene/gui/check_box.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/link_button.h"
#include "scene/gui/option_button.h"
-#include "scene/gui/tab_container.h"
#include "scene/gui/panel_container.h"
-#include "scene/gui/link_button.h"
-#include "scene/gui/check_box.h"
#include "scene/gui/progress_bar.h"
#include "scene/gui/separator.h"
+#include "scene/gui/tab_container.h"
+#include "editor_plugin_settings.h"
#include "scene/gui/grid_container.h"
+#include "scene/gui/rich_text_label.h"
#include "scene/gui/scroll_container.h"
#include "scene/gui/texture_button.h"
-#include "scene/gui/rich_text_label.h"
-#include "editor_plugin_settings.h"
-#include "scene/main/http_request.h"
#include "editor_asset_installer.h"
+#include "scene/main/http_request.h"
class EditorAssetLibraryItem : public PanelContainer {
- GDCLASS( EditorAssetLibraryItem, PanelContainer );
+ GDCLASS(EditorAssetLibraryItem, PanelContainer);
TextureButton *icon;
- LinkButton* title;
- LinkButton* category;
- LinkButton* author;
+ LinkButton *title;
+ LinkButton *category;
+ LinkButton *author;
TextureRect *stars[5];
- Label* price;
+ Label *price;
int asset_id;
int category_id;
int author_id;
-
void _asset_clicked();
void _category_clicked();
void _author_clicked();
-
- void set_image(int p_type,int p_index,const Ref<Texture>& p_image);
+ void set_image(int p_type, int p_index, const Ref<Texture> &p_image);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
- void configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost);
+public:
+ void configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, int p_rating, const String &p_cost);
EditorAssetLibraryItem();
};
-
class EditorAssetLibraryItemDescription : public ConfirmationDialog {
GDCLASS(EditorAssetLibraryItemDescription, ConfirmationDialog);
@@ -106,7 +100,7 @@ class EditorAssetLibraryItemDescription : public ConfirmationDialog {
Vector<Preview> preview_images;
TextureRect *preview;
- void set_image(int p_type,int p_index,const Ref<Texture>& p_image);
+ void set_image(int p_type, int p_index, const Ref<Texture> &p_image);
int asset_id;
String download_url;
@@ -114,15 +108,15 @@ class EditorAssetLibraryItemDescription : public ConfirmationDialog {
String sha256;
Ref<Texture> icon;
- void _link_click(const String& p_url);
+ void _link_click(const String &p_url);
void _preview_click(int p_index);
-protected:
+protected:
static void _bind_methods();
-public:
- void configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost,int p_version,const String& p_version_string,const String& p_description,const String& p_download_url,const String& p_browse_url,const String& p_sha256_hash);
- void add_preview(int p_id, bool p_video,const String& p_url);
+public:
+ void configure(const String &p_title, int p_asset_id, const String &p_category, int p_category_id, const String &p_author, int p_author_id, int p_rating, const String &p_cost, int p_version, const String &p_version_string, const String &p_description, const String &p_download_url, const String &p_browse_url, const String &p_sha256_hash);
+ void add_preview(int p_id, bool p_video, const String &p_url);
String get_title() { return title; }
Ref<Texture> get_preview_icon() { return icon; }
@@ -130,16 +124,14 @@ public:
int get_asset_id() { return asset_id; }
String get_sha256() { return sha256; }
EditorAssetLibraryItemDescription();
-
};
class EditorAssetLibraryItemDownload : public PanelContainer {
GDCLASS(EditorAssetLibraryItemDownload, PanelContainer);
-
TextureRect *icon;
- Label* title;
+ Label *title;
ProgressBar *progress;
Button *install;
Button *retry;
@@ -162,33 +154,29 @@ class EditorAssetLibraryItemDownload : public PanelContainer {
void _close();
void _install();
void _make_request();
- void _http_download_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data);
+ void _http_download_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_external_install(bool p_enable) { external_install=p_enable; }
+public:
+ void set_external_install(bool p_enable) { external_install = p_enable; }
int get_asset_id() { return asset_id; }
- void configure(const String& p_title,int p_asset_id,const Ref<Texture>& p_preview, const String& p_download_url, const String& p_sha256_hash);
+ void configure(const String &p_title, int p_asset_id, const Ref<Texture> &p_preview, const String &p_download_url, const String &p_sha256_hash);
EditorAssetLibraryItemDownload();
-
};
class EditorAssetLibrary : public PanelContainer {
- GDCLASS(EditorAssetLibrary,PanelContainer);
+ GDCLASS(EditorAssetLibrary, PanelContainer);
String host;
EditorFileDialog *asset_open;
EditorAssetInstaller *asset_installer;
-
void _asset_open();
- void _asset_file_selected(const String& p_file);
-
+ void _asset_file_selected(const String &p_file);
ScrollContainer *library_scroll;
VBoxContainer *library_vb;
@@ -229,11 +217,9 @@ class EditorAssetLibrary : public PanelContainer {
SORT_MAX
};
-
- static const char* sort_key[SORT_MAX];
- static const char* sort_text[SORT_MAX];
- static const char* support_key[SUPPORT_MAX];
-
+ static const char *sort_key[SORT_MAX];
+ static const char *sort_text[SORT_MAX];
+ static const char *support_key[SUPPORT_MAX];
///MainListing
@@ -257,14 +243,14 @@ class EditorAssetLibrary : public PanelContainer {
};
int last_queue_id;
- Map<int,ImageQueue> image_queue;
+ Map<int, ImageQueue> image_queue;
- void _image_update(bool use_cache, bool final, const PoolByteArray& p_data, int p_queue_id);
- void _image_request_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data, int p_queue_id);
- void _request_image(ObjectID p_for,String p_image_url,ImageType p_type,int p_image_index);
+ void _image_update(bool use_cache, bool final, const PoolByteArray &p_data, int p_queue_id);
+ void _image_request_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data, int p_queue_id);
+ void _request_image(ObjectID p_for, String p_image_url, ImageType p_type, int p_image_index);
void _update_image_queue();
- HBoxContainer* _make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items);
+ HBoxContainer *_make_pages(int p_page, int p_page_count, int p_page_len, int p_total_items, int p_current_items);
//
EditorAssetLibraryItemDescription *description;
@@ -277,16 +263,12 @@ class EditorAssetLibrary : public PanelContainer {
REQUESTING_ASSET,
};
-
RequestType requesting;
Dictionary category_map;
-
ScrollContainer *downloads_scroll;
HBoxContainer *downloads_hb;
-
-
void _install_asset();
void _select_author(int p_id);
@@ -295,36 +277,36 @@ class EditorAssetLibrary : public PanelContainer {
void _manage_plugins();
- void _search(int p_page=0);
+ void _search(int p_page = 0);
void _rerun_search(int p_ignore);
- void _api_request(const String& p_request, RequestType p_request_type, const String &p_arguments="");
- void _http_request_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data);
- void _http_download_completed(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data);
+ void _api_request(const String &p_request, RequestType p_request_type, const String &p_arguments = "");
+ void _http_request_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data);
+ void _http_download_completed(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data);
void _repository_changed(int p_repository_id);
void _support_toggled(int p_support);
- void _install_external_asset(String p_zip_path,String p_title);
+ void _install_external_asset(String p_zip_path, String p_title);
-friend class EditorAssetLibraryItemDescription;
-friend class EditorAssetLibraryItem;
-protected:
+ friend class EditorAssetLibraryItemDescription;
+ friend class EditorAssetLibraryItem;
+protected:
static void _bind_methods();
void _notification(int p_what);
+
public:
- EditorAssetLibrary(bool p_templates_only=false);
+ EditorAssetLibrary(bool p_templates_only = false);
};
class AssetLibraryEditorPlugin : public EditorPlugin {
- GDCLASS( AssetLibraryEditorPlugin, EditorPlugin );
+ GDCLASS(AssetLibraryEditorPlugin, EditorPlugin);
EditorAssetLibrary *addon_library;
EditorNode *editor;
public:
-
virtual String get_name() const { return "AssetLib"; }
bool has_main_screen() const { return true; }
virtual void edit(Object *p_object) {}
@@ -336,7 +318,6 @@ public:
AssetLibraryEditorPlugin(EditorNode *p_node);
~AssetLibraryEditorPlugin();
-
};
#endif // EDITORASSETLIBRARY_H
diff --git a/editor/call_dialog.cpp b/editor/call_dialog.cpp
index 6dfeb87dfd..7a8290c58d 100644
--- a/editor/call_dialog.cpp
+++ b/editor/call_dialog.cpp
@@ -29,9 +29,9 @@
#include "call_dialog.h"
#if 0
-#include "scene/gui/label.h"
#include "class_db.h"
#include "print_string.h"
+#include "scene/gui/label.h"
class CallDialogParams : public Object {
diff --git a/editor/call_dialog.h b/editor/call_dialog.h
index 56fc07c3df..f3dbe6458b 100644
--- a/editor/call_dialog.h
+++ b/editor/call_dialog.h
@@ -29,12 +29,12 @@
#ifndef CALL_DIALOG_H
#define CALL_DIALOG_H
-#include "scene/gui/popup.h"
+#include "editor/property_editor.h"
#include "scene/gui/button.h"
-#include "scene/gui/tree.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
-#include "editor/property_editor.h"
+#include "scene/gui/popup.h"
+#include "scene/gui/tree.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
diff --git a/editor/code_editor.cpp b/editor/code_editor.cpp
index 8e9925a0d3..c71c2cc608 100644
--- a/editor/code_editor.cpp
+++ b/editor/code_editor.cpp
@@ -28,35 +28,33 @@
/*************************************************************************/
#include "code_editor.h"
+#include "editor/editor_scale.h"
#include "editor_settings.h"
+#include "os/keyboard.h"
#include "scene/gui/margin_container.h"
#include "scene/gui/separator.h"
#include "scene/resources/dynamic_font.h"
-#include "os/keyboard.h"
-#include "editor/editor_scale.h"
void GotoLineDialog::popup_find_line(TextEdit *p_edit) {
- text_editor=p_edit;
+ text_editor = p_edit;
line->set_text(itos(text_editor->cursor_get_line()));
line->select_all();
- popup_centered(Size2(180,80));
+ popup_centered(Size2(180, 80));
line->grab_focus();
}
-
int GotoLineDialog::get_line() const {
return line->get_text().to_int();
}
-
void GotoLineDialog::ok_pressed() {
- if (get_line()<1 || get_line()>text_editor->get_line_count())
+ if (get_line() < 1 || get_line() > text_editor->get_line_count())
return;
- text_editor->cursor_set_line(get_line()-1);
+ text_editor->cursor_set_line(get_line() - 1);
hide();
}
@@ -65,30 +63,29 @@ GotoLineDialog::GotoLineDialog() {
set_title(TTR("Go to Line"));
Label *l = memnew(Label);
l->set_text(TTR("Line Number:"));
- l->set_pos(Point2(5,5));
+ l->set_pos(Point2(5, 5));
add_child(l);
- line = memnew( LineEdit );
- line->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- line->set_begin( Point2(15,22) );
- line->set_end( Point2(15,35) );
+ line = memnew(LineEdit);
+ line->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ line->set_begin(Point2(15, 22));
+ line->set_end(Point2(15, 35));
add_child(line);
register_text_enter(line);
- text_editor=NULL;
+ text_editor = NULL;
set_hide_on_ok(false);
}
-
void FindReplaceBar::_notification(int p_what) {
if (p_what == NOTIFICATION_READY) {
find_prev->set_icon(get_icon("MoveUp", "EditorIcons"));
find_next->set_icon(get_icon("MoveDown", "EditorIcons"));
- hide_button->set_normal_texture(get_icon("Close","EditorIcons"));
- hide_button->set_hover_texture(get_icon("CloseHover","EditorIcons"));
- hide_button->set_pressed_texture(get_icon("Close","EditorIcons"));
+ hide_button->set_normal_texture(get_icon("Close", "EditorIcons"));
+ hide_button->set_hover_texture(get_icon("CloseHover", "EditorIcons"));
+ hide_button->set_pressed_texture(get_icon("Close", "EditorIcons"));
} else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
@@ -100,7 +97,7 @@ void FindReplaceBar::_unhandled_input(const InputEvent &p_event) {
if (p_event.type == InputEvent::KEY) {
- const InputEventKey& k = p_event.key;
+ const InputEventKey &k = p_event.key;
if (k.pressed && (text_edit->has_focus() || text_vbc->is_a_parent_of(get_focus_owner()))) {
@@ -128,30 +125,30 @@ void FindReplaceBar::_unhandled_input(const InputEvent &p_event) {
bool FindReplaceBar::_search(uint32_t p_flags, int p_from_line, int p_from_col) {
int line, col;
- String text=get_search_text();
+ String text = get_search_text();
- bool found=text_edit->search(text,p_flags,p_from_line,p_from_col,line,col);
+ bool found = text_edit->search(text, p_flags, p_from_line, p_from_col, line, col);
if (found) {
if (!preserve_cursor) {
text_edit->cursor_set_line(line, false);
- text_edit->cursor_set_column(col+text.length(), false);
+ text_edit->cursor_set_column(col + text.length(), false);
text_edit->center_viewport_to_cursor();
}
text_edit->set_search_text(text);
text_edit->set_search_flags(p_flags);
- text_edit->set_current_search_result(line,col);
+ text_edit->set_current_search_result(line, col);
- result_line=line;
- result_col=col;
+ result_line = line;
+ result_col = col;
set_error("");
} else {
- result_line=-1;
- result_col=-1;
+ result_line = -1;
+ result_col = -1;
text_edit->set_search_text("");
- set_error(text.empty()?"":TTR("No Matches"));
+ set_error(text.empty() ? "" : TTR("No Matches"));
}
return found;
@@ -159,10 +156,10 @@ bool FindReplaceBar::_search(uint32_t p_flags, int p_from_line, int p_from_col)
void FindReplaceBar::_replace() {
- if (result_line!=-1 && result_col!=-1) {
+ if (result_line != -1 && result_col != -1) {
text_edit->begin_complex_operation();
- text_edit->select(result_line,result_col,result_line,result_col+get_search_text().length());
+ text_edit->select(result_line, result_col, result_line, result_col + get_search_text().length());
text_edit->insert_text_at_cursor(get_replace_text());
text_edit->end_complex_operation();
@@ -174,14 +171,14 @@ void FindReplaceBar::_replace() {
void FindReplaceBar::_replace_all() {
// line as x so it gets priority in comparison, column as y
- Point2i orig_cursor(text_edit->cursor_get_line(),text_edit->cursor_get_column());
- Point2i prev_match=Point2(-1,-1);
+ Point2i orig_cursor(text_edit->cursor_get_line(), text_edit->cursor_get_column());
+ Point2i prev_match = Point2(-1, -1);
bool selection_enabled = text_edit->is_selection_active();
- Point2i selection_begin,selection_end;
+ Point2i selection_begin, selection_end;
if (selection_enabled) {
- selection_begin=Point2i(text_edit->get_selection_from_line(),text_edit->get_selection_from_column());
- selection_end=Point2i(text_edit->get_selection_to_line(),text_edit->get_selection_to_column());
+ selection_begin = Point2i(text_edit->get_selection_from_line(), text_edit->get_selection_from_column());
+ selection_end = Point2i(text_edit->get_selection_to_line(), text_edit->get_selection_to_column());
}
int vsval = text_edit->get_v_scroll();
@@ -189,10 +186,10 @@ void FindReplaceBar::_replace_all() {
text_edit->cursor_set_line(0);
text_edit->cursor_set_column(0);
- String replace_text=get_replace_text();
- int search_text_len=get_search_text().length();
+ String replace_text = get_replace_text();
+ int search_text_len = get_search_text().length();
- int rc=0;
+ int rc = 0;
replace_all_mode = true;
@@ -201,25 +198,25 @@ void FindReplaceBar::_replace_all() {
while (search_next()) {
// replace area
- Point2i match_from(result_line,result_col);
- Point2i match_to(result_line,result_col+search_text_len);
+ Point2i match_from(result_line, result_col);
+ Point2i match_to(result_line, result_col + search_text_len);
if (match_from < prev_match)
break; // done
- prev_match=Point2i(result_line,result_col+replace_text.length());
+ prev_match = Point2i(result_line, result_col + replace_text.length());
- text_edit->select(result_line,result_col,result_line,match_to.y);
+ text_edit->select(result_line, result_col, result_line, match_to.y);
if (selection_enabled && is_selection_only()) {
- if (match_from<selection_begin || match_to>selection_end)
+ if (match_from < selection_begin || match_to > selection_end)
continue;
// replace but adjust selection bounds
text_edit->insert_text_at_cursor(replace_text);
- if (match_to.x==selection_end.x)
- selection_end.y+=replace_text.length()-search_text_len;
+ if (match_to.x == selection_end.x)
+ selection_end.y += replace_text.length() - search_text_len;
} else {
// just replace
text_edit->insert_text_at_cursor(replace_text);
@@ -238,7 +235,7 @@ void FindReplaceBar::_replace_all() {
if (selection_enabled && is_selection_only()) {
// reselect
- text_edit->select(selection_begin.x,selection_begin.y,selection_end.x,selection_end.y);
+ text_edit->select(selection_begin.x, selection_begin.y, selection_end.x, selection_end.y);
} else {
text_edit->deselect();
}
@@ -247,96 +244,96 @@ void FindReplaceBar::_replace_all() {
set_error(vformat(TTR("Replaced %d Ocurrence(s)."), rc));
}
-void FindReplaceBar::_get_search_from(int& r_line, int& r_col) {
+void FindReplaceBar::_get_search_from(int &r_line, int &r_col) {
- r_line=text_edit->cursor_get_line();
- r_col=text_edit->cursor_get_column();
+ r_line = text_edit->cursor_get_line();
+ r_col = text_edit->cursor_get_column();
if (text_edit->is_selection_active() && !replace_all_mode) {
- int selection_line=text_edit->get_selection_from_line();
+ int selection_line = text_edit->get_selection_from_line();
- if (text_edit->get_selection_text()==get_search_text() && r_line==selection_line) {
+ if (text_edit->get_selection_text() == get_search_text() && r_line == selection_line) {
- int selection_from_col=text_edit->get_selection_from_column();
+ int selection_from_col = text_edit->get_selection_from_column();
- if (r_col>=selection_from_col && r_col<=text_edit->get_selection_to_column()) {
- r_col=selection_line;
- r_col=selection_from_col;
+ if (r_col >= selection_from_col && r_col <= text_edit->get_selection_to_column()) {
+ r_col = selection_line;
+ r_col = selection_from_col;
}
}
}
- if (r_line==result_line && r_col>=result_col && r_col<=result_col+get_search_text().length()) {
- r_col=result_col;
+ if (r_line == result_line && r_col >= result_col && r_col <= result_col + get_search_text().length()) {
+ r_col = result_col;
}
}
bool FindReplaceBar::search_current() {
- uint32_t flags=0;
+ uint32_t flags = 0;
if (is_whole_words())
- flags|=TextEdit::SEARCH_WHOLE_WORDS;
+ flags |= TextEdit::SEARCH_WHOLE_WORDS;
if (is_case_sensitive())
- flags|=TextEdit::SEARCH_MATCH_CASE;
+ flags |= TextEdit::SEARCH_MATCH_CASE;
int line, col;
_get_search_from(line, col);
- return _search(flags,line,col);
+ return _search(flags, line, col);
}
bool FindReplaceBar::search_prev() {
- uint32_t flags=0;
+ uint32_t flags = 0;
String text = get_search_text();
if (is_whole_words())
- flags|=TextEdit::SEARCH_WHOLE_WORDS;
+ flags |= TextEdit::SEARCH_WHOLE_WORDS;
if (is_case_sensitive())
- flags|=TextEdit::SEARCH_MATCH_CASE;
+ flags |= TextEdit::SEARCH_MATCH_CASE;
- flags|=TextEdit::SEARCH_BACKWARDS;
+ flags |= TextEdit::SEARCH_BACKWARDS;
int line, col;
_get_search_from(line, col);
- col-=text.length();
- if (col<0) {
- line-=1;
- if (line<0)
- line=text_edit->get_line_count()-1;
- col=text_edit->get_line(line).length();
+ col -= text.length();
+ if (col < 0) {
+ line -= 1;
+ if (line < 0)
+ line = text_edit->get_line_count() - 1;
+ col = text_edit->get_line(line).length();
}
- return _search(flags,line,col);
+ return _search(flags, line, col);
}
bool FindReplaceBar::search_next() {
- uint32_t flags=0;
+ uint32_t flags = 0;
String text = get_search_text();
if (is_whole_words())
- flags|=TextEdit::SEARCH_WHOLE_WORDS;
+ flags |= TextEdit::SEARCH_WHOLE_WORDS;
if (is_case_sensitive())
- flags|=TextEdit::SEARCH_MATCH_CASE;
+ flags |= TextEdit::SEARCH_MATCH_CASE;
int line, col;
_get_search_from(line, col);
- if (line==result_line && col==result_col) {
- col+=text.length();
- if (col>text_edit->get_line(line).length()) {
- line+=1;
- if (line>=text_edit->get_line_count())
- line=0;
- col=0;
+ if (line == result_line && col == result_col) {
+ col += text.length();
+ if (col > text_edit->get_line(line).length()) {
+ line += 1;
+ if (line >= text_edit->get_line_count())
+ line = 0;
+ col = 0;
}
}
- return _search(flags,line,col);
+ return _search(flags, line, col);
}
void FindReplaceBar::_hide_bar() {
@@ -377,15 +374,13 @@ void FindReplaceBar::popup_search() {
void FindReplaceBar::popup_replace() {
-
if (!replace_hbc->is_visible_in_tree() || !replace_options_hbc->is_visible_in_tree()) {
replace_text->clear();
replace_hbc->show();
replace_options_hbc->show();
-
}
- selection_only->set_pressed( (text_edit->is_selection_active() && text_edit->get_selection_from_line() < text_edit->get_selection_to_line()) );
+ selection_only->set_pressed((text_edit->is_selection_active() && text_edit->get_selection_from_line() < text_edit->get_selection_to_line()));
_show_search();
}
@@ -398,23 +393,23 @@ void FindReplaceBar::_search_options_changed(bool p_pressed) {
void FindReplaceBar::_editor_text_changed() {
if (is_visible_in_tree()) {
- preserve_cursor=true;
+ preserve_cursor = true;
search_current();
- preserve_cursor=false;
+ preserve_cursor = false;
}
}
-void FindReplaceBar::_search_text_changed(const String& p_text) {
+void FindReplaceBar::_search_text_changed(const String &p_text) {
search_current();
}
-void FindReplaceBar::_search_text_entered(const String& p_text) {
+void FindReplaceBar::_search_text_entered(const String &p_text) {
search_next();
}
-void FindReplaceBar::_replace_text_entered(const String& p_text) {
+void FindReplaceBar::_replace_text_entered(const String &p_text) {
if (selection_only->is_pressed() && text_edit->is_selection_active()) {
_replace_all();
@@ -455,32 +450,32 @@ void FindReplaceBar::set_error(const String &p_label) {
void FindReplaceBar::set_text_edit(TextEdit *p_text_edit) {
text_edit = p_text_edit;
- text_edit->connect("text_changed",this,"_editor_text_changed");
+ text_edit->connect("text_changed", this, "_editor_text_changed");
}
void FindReplaceBar::_bind_methods() {
- ClassDB::bind_method("_unhandled_input",&FindReplaceBar::_unhandled_input);
+ ClassDB::bind_method("_unhandled_input", &FindReplaceBar::_unhandled_input);
- ClassDB::bind_method("_editor_text_changed",&FindReplaceBar::_editor_text_changed);
- ClassDB::bind_method("_search_text_changed",&FindReplaceBar::_search_text_changed);
- ClassDB::bind_method("_search_text_entered",&FindReplaceBar::_search_text_entered);
- ClassDB::bind_method("_replace_text_entered",&FindReplaceBar::_replace_text_entered);
- ClassDB::bind_method("_search_current",&FindReplaceBar::search_current);
- ClassDB::bind_method("_search_next",&FindReplaceBar::search_next);
- ClassDB::bind_method("_search_prev",&FindReplaceBar::search_prev);
- ClassDB::bind_method("_replace_pressed",&FindReplaceBar::_replace);
- ClassDB::bind_method("_replace_all_pressed",&FindReplaceBar::_replace_all);
- ClassDB::bind_method("_search_options_changed",&FindReplaceBar::_search_options_changed);
- ClassDB::bind_method("_hide_pressed",&FindReplaceBar::_hide_bar);
+ ClassDB::bind_method("_editor_text_changed", &FindReplaceBar::_editor_text_changed);
+ ClassDB::bind_method("_search_text_changed", &FindReplaceBar::_search_text_changed);
+ ClassDB::bind_method("_search_text_entered", &FindReplaceBar::_search_text_entered);
+ ClassDB::bind_method("_replace_text_entered", &FindReplaceBar::_replace_text_entered);
+ ClassDB::bind_method("_search_current", &FindReplaceBar::search_current);
+ ClassDB::bind_method("_search_next", &FindReplaceBar::search_next);
+ ClassDB::bind_method("_search_prev", &FindReplaceBar::search_prev);
+ ClassDB::bind_method("_replace_pressed", &FindReplaceBar::_replace);
+ ClassDB::bind_method("_replace_all_pressed", &FindReplaceBar::_replace_all);
+ ClassDB::bind_method("_search_options_changed", &FindReplaceBar::_search_options_changed);
+ ClassDB::bind_method("_hide_pressed", &FindReplaceBar::_hide_bar);
ADD_SIGNAL(MethodInfo("search"));
}
FindReplaceBar::FindReplaceBar() {
- replace_all_mode=false;
- preserve_cursor=false;
+ replace_all_mode = false;
+ preserve_cursor = false;
text_vbc = memnew(VBoxContainer);
add_child(text_vbc);
@@ -491,18 +486,18 @@ FindReplaceBar::FindReplaceBar() {
search_text = memnew(LineEdit);
search_hbc->add_child(search_text);
search_text->set_custom_minimum_size(Size2(200, 0));
- search_text->connect("text_changed",this,"_search_text_changed");
- search_text->connect("text_entered",this,"_search_text_entered");
+ search_text->connect("text_changed", this, "_search_text_changed");
+ search_text->connect("text_entered", this, "_search_text_entered");
find_prev = memnew(ToolButton);
search_hbc->add_child(find_prev);
find_prev->set_focus_mode(FOCUS_NONE);
- find_prev->connect("pressed",this,"_search_prev");
+ find_prev->connect("pressed", this, "_search_prev");
find_next = memnew(ToolButton);
search_hbc->add_child(find_next);
find_next->set_focus_mode(FOCUS_NONE);
- find_next->connect("pressed",this,"_search_next");
+ find_next->connect("pressed", this, "_search_next");
replace_hbc = memnew(HBoxContainer);
text_vbc->add_child(replace_hbc);
@@ -511,22 +506,21 @@ FindReplaceBar::FindReplaceBar() {
replace_text = memnew(LineEdit);
replace_hbc->add_child(replace_text);
replace_text->set_custom_minimum_size(Size2(200, 0));
- replace_text->connect("text_entered",this,"_replace_text_entered");
-
+ replace_text->connect("text_entered", this, "_replace_text_entered");
replace = memnew(Button);
replace_hbc->add_child(replace);
replace->set_text(TTR("Replace"));
//replace->set_focus_mode(FOCUS_NONE);
- replace->connect("pressed",this,"_replace_pressed");
+ replace->connect("pressed", this, "_replace_pressed");
replace_all = memnew(Button);
replace_hbc->add_child(replace_all);
replace_all->set_text(TTR("Replace All"));
//replace_all->set_focus_mode(FOCUS_NONE);
- replace_all->connect("pressed",this,"_replace_all_pressed");
+ replace_all->connect("pressed", this, "_replace_all_pressed");
- Control *spacer_split = memnew( Control );
+ Control *spacer_split = memnew(Control);
spacer_split->set_custom_minimum_size(Size2(0, 1));
text_vbc->add_child(spacer_split);
@@ -541,18 +535,18 @@ FindReplaceBar::FindReplaceBar() {
search_options->add_child(case_sensitive);
case_sensitive->set_text(TTR("Match Case"));
case_sensitive->set_focus_mode(FOCUS_NONE);
- case_sensitive->connect("toggled",this,"_search_options_changed");
+ case_sensitive->connect("toggled", this, "_search_options_changed");
whole_words = memnew(CheckBox);
search_options->add_child(whole_words);
whole_words->set_text(TTR("Whole Words"));
whole_words->set_focus_mode(FOCUS_NONE);
- whole_words->connect("toggled",this,"_search_options_changed");
+ whole_words->connect("toggled", this, "_search_options_changed");
error_label = memnew(Label);
search_options->add_child(error_label);
- error_label->add_color_override("font_color", Color(1,1,0,1));
- error_label->add_color_override("font_color_shadow", Color(0,0,0,1));
+ error_label->add_color_override("font_color", Color(1, 1, 0, 1));
+ error_label->add_color_override("font_color_shadow", Color(0, 0, 0, 1));
error_label->add_constant_override("shadow_as_outline", 1);
search_options->add_spacer();
@@ -560,7 +554,7 @@ FindReplaceBar::FindReplaceBar() {
hide_button = memnew(TextureButton);
search_options->add_child(hide_button);
hide_button->set_focus_mode(FOCUS_NONE);
- hide_button->connect("pressed",this,"_hide_pressed");
+ hide_button->connect("pressed", this, "_hide_pressed");
replace_options_hbc = memnew(HBoxContainer);
options_vbc->add_child(replace_options_hbc);
@@ -570,10 +564,9 @@ FindReplaceBar::FindReplaceBar() {
replace_options_hbc->add_child(selection_only);
selection_only->set_text(TTR("Selection Only"));
selection_only->set_focus_mode(FOCUS_NONE);
- selection_only->connect("toggled",this,"_search_options_changed");
+ selection_only->connect("toggled", this, "_search_options_changed");
}
-
void FindReplaceDialog::popup_search() {
set_title(TTR("Search"));
@@ -581,24 +574,22 @@ void FindReplaceDialog::popup_search() {
replace_label->hide();
replace_vb->hide();
skip->hide();
- popup_centered(Point2(300,190));
+ popup_centered(Point2(300, 190));
get_ok()->set_text(TTR("Find"));
search_text->grab_focus();
- if (text_edit->is_selection_active() && ( text_edit->get_selection_from_line() == text_edit->get_selection_to_line())) {
+ if (text_edit->is_selection_active() && (text_edit->get_selection_from_line() == text_edit->get_selection_to_line())) {
- search_text->set_text( text_edit->get_selection_text() );
+ search_text->set_text(text_edit->get_selection_text());
}
search_text->select_all();
error_label->set_text("");
-
}
void FindReplaceDialog::popup_replace() {
-
set_title(TTR("Replace"));
- bool do_selection=(text_edit->is_selection_active() && text_edit->get_selection_from_line() < text_edit->get_selection_to_line());
+ bool do_selection = (text_edit->is_selection_active() && text_edit->get_selection_from_line() < text_edit->get_selection_to_line());
set_replace_selection_only(do_selection);
@@ -609,9 +600,9 @@ void FindReplaceDialog::popup_replace() {
replace_mc->show();
replace_label->show();
replace_vb->show();
- popup_centered(Point2(300,300));
- if (search_text->get_text()!="" && replace_text->get_text()=="") {
- search_text->select(0,0);
+ popup_centered(Point2(300, 300));
+ if (search_text->get_text() != "" && replace_text->get_text() == "") {
+ search_text->select(0, 0);
replace_text->grab_focus();
} else {
search_text->grab_focus();
@@ -629,7 +620,6 @@ void FindReplaceDialog::popup_replace() {
get_ok()->set_text(TTR("Replace"));
selection_only->set_disabled(false);
}
-
}
void FindReplaceDialog::_search_callback() {
@@ -638,7 +628,6 @@ void FindReplaceDialog::_search_callback() {
_replace();
else
_search();
-
}
void FindReplaceDialog::_replace_skip_callback() {
@@ -652,15 +641,14 @@ void FindReplaceDialog::_replace() {
if (is_replace_all_mode()) {
//line as x so it gets priority in comparison, column as y
- Point2i orig_cursor(text_edit->cursor_get_line(),text_edit->cursor_get_column());
- Point2i prev_match=Point2(-1,-1);
-
+ Point2i orig_cursor(text_edit->cursor_get_line(), text_edit->cursor_get_column());
+ Point2i prev_match = Point2(-1, -1);
bool selection_enabled = text_edit->is_selection_active();
- Point2i selection_begin,selection_end;
+ Point2i selection_begin, selection_end;
if (selection_enabled) {
- selection_begin=Point2i(text_edit->get_selection_from_line(),text_edit->get_selection_from_column());
- selection_end=Point2i(text_edit->get_selection_to_line(),text_edit->get_selection_to_column());
+ selection_begin = Point2i(text_edit->get_selection_from_line(), text_edit->get_selection_from_column());
+ selection_end = Point2i(text_edit->get_selection_to_line(), text_edit->get_selection_to_column());
}
int vsval = text_edit->get_v_scroll();
//int hsval = text_edit->get_h_scroll();
@@ -668,9 +656,9 @@ void FindReplaceDialog::_replace() {
text_edit->cursor_set_line(0);
text_edit->cursor_set_column(0);
- int rc=0;
+ int rc = 0;
- while(_search()) {
+ while (_search()) {
if (!text_edit->is_selection_active()) {
//search selects
@@ -678,30 +666,29 @@ void FindReplaceDialog::_replace() {
}
//replace area
- Point2i match_from(text_edit->get_selection_from_line(),text_edit->get_selection_from_column());
- Point2i match_to(text_edit->get_selection_to_line(),text_edit->get_selection_to_column());
+ Point2i match_from(text_edit->get_selection_from_line(), text_edit->get_selection_from_column());
+ Point2i match_to(text_edit->get_selection_to_line(), text_edit->get_selection_to_column());
if (match_from < prev_match)
break; //done
- prev_match=match_to;
+ prev_match = match_to;
if (selection_enabled && is_replace_selection_only()) {
- if (match_from<selection_begin || match_to>selection_end)
+ if (match_from < selection_begin || match_to > selection_end)
continue;
//replace but adjust selection bounds
text_edit->insert_text_at_cursor(get_replace_text());
- if (match_to.x==selection_end.x)
- selection_end.y+=get_replace_text().length() - get_search_text().length();
+ if (match_to.x == selection_end.x)
+ selection_end.y += get_replace_text().length() - get_search_text().length();
} else {
//just replace
text_edit->insert_text_at_cursor(get_replace_text());
}
rc++;
-
}
//restore editor state (selection, cursor, scroll)
text_edit->cursor_set_line(orig_cursor.x);
@@ -709,20 +696,19 @@ void FindReplaceDialog::_replace() {
if (selection_enabled && is_replace_selection_only()) {
//reselect
- text_edit->select(selection_begin.x,selection_begin.y,selection_end.x,selection_end.y);
+ text_edit->select(selection_begin.x, selection_begin.y, selection_end.x, selection_end.y);
} else {
text_edit->deselect();
}
text_edit->set_v_scroll(vsval);
//text_edit->set_h_scroll(hsval);
- error_label->set_text(vformat(TTR("Replaced %d ocurrence(s)."),rc));
-
+ error_label->set_text(vformat(TTR("Replaced %d ocurrence(s)."), rc));
//hide();
} else {
- if (text_edit->get_selection_text()==get_search_text()) {
+ if (text_edit->get_selection_text() == get_search_text()) {
text_edit->insert_text_at_cursor(get_replace_text());
}
@@ -732,35 +718,31 @@ void FindReplaceDialog::_replace() {
text_edit->end_complex_operation();
}
-
-
bool FindReplaceDialog::_search() {
-
- String text=get_search_text();
- uint32_t flags=0;
+ String text = get_search_text();
+ uint32_t flags = 0;
if (is_whole_words())
- flags|=TextEdit::SEARCH_WHOLE_WORDS;
+ flags |= TextEdit::SEARCH_WHOLE_WORDS;
if (is_case_sensitive())
- flags|=TextEdit::SEARCH_MATCH_CASE;
+ flags |= TextEdit::SEARCH_MATCH_CASE;
if (is_backwards())
- flags|=TextEdit::SEARCH_BACKWARDS;
+ flags |= TextEdit::SEARCH_BACKWARDS;
- int line=text_edit->cursor_get_line(),col=text_edit->cursor_get_column();
+ int line = text_edit->cursor_get_line(), col = text_edit->cursor_get_column();
if (is_backwards()) {
- col-=1;
- if (col<0) {
- line-=1;
- if (line<0) {
- line=text_edit->get_line_count()-1;
+ col -= 1;
+ if (col < 0) {
+ line -= 1;
+ if (line < 0) {
+ line = text_edit->get_line_count() - 1;
}
- col=text_edit->get_line(line).length();
+ col = text_edit->get_line(line).length();
}
}
- bool found = text_edit->search(text,flags,line,col,line,col);
-
+ bool found = text_edit->search(text, flags, line, col, line, col);
if (found) {
// print_line("found");
@@ -768,8 +750,8 @@ bool FindReplaceDialog::_search() {
if (is_backwards())
text_edit->cursor_set_column(col);
else
- text_edit->cursor_set_column(col+text.length());
- text_edit->select(line,col,line,col+text.length());
+ text_edit->cursor_set_column(col + text.length());
+ text_edit->select(line, col, line, col + text.length());
set_error("");
return true;
} else {
@@ -777,7 +759,6 @@ bool FindReplaceDialog::_search() {
set_error(TTR("Not found!"));
return false;
}
-
}
void FindReplaceDialog::_prompt_changed() {
@@ -794,7 +775,6 @@ void FindReplaceDialog::_prompt_changed() {
}
}
-
void FindReplaceDialog::_skip_pressed() {
_replace_skip_callback();
@@ -812,39 +792,35 @@ bool FindReplaceDialog::is_replace_all_mode() const {
bool FindReplaceDialog::is_replace_selection_only() const {
- return selection_only->is_pressed();
+ return selection_only->is_pressed();
}
-void FindReplaceDialog::set_replace_selection_only(bool p_enable){
+void FindReplaceDialog::set_replace_selection_only(bool p_enable) {
selection_only->set_pressed(p_enable);
}
-
void FindReplaceDialog::ok_pressed() {
_search_callback();
}
-void FindReplaceDialog::_search_text_entered(const String& p_text) {
+void FindReplaceDialog::_search_text_entered(const String &p_text) {
if (replace_text->is_visible_in_tree())
return;
emit_signal("search");
_search();
-
}
-void FindReplaceDialog::_replace_text_entered(const String& p_text) {
+void FindReplaceDialog::_replace_text_entered(const String &p_text) {
if (!replace_text->is_visible_in_tree())
return;
emit_signal("search");
_replace();
-
}
-
String FindReplaceDialog::get_search_text() const {
return search_text->get_text();
@@ -860,157 +836,141 @@ bool FindReplaceDialog::is_whole_words() const {
bool FindReplaceDialog::is_case_sensitive() const {
return case_sensitive->is_pressed();
-
}
bool FindReplaceDialog::is_backwards() const {
return backwards->is_pressed();
-
}
-void FindReplaceDialog::set_error(const String& p_error) {
+void FindReplaceDialog::set_error(const String &p_error) {
error_label->set_text(p_error);
}
void FindReplaceDialog::set_text_edit(TextEdit *p_text_edit) {
- text_edit=p_text_edit;
+ text_edit = p_text_edit;
}
void FindReplaceDialog::search_next() {
_search();
}
-
void FindReplaceDialog::_bind_methods() {
- ClassDB::bind_method("_search_text_entered",&FindReplaceDialog::_search_text_entered);
- ClassDB::bind_method("_replace_text_entered",&FindReplaceDialog::_replace_text_entered);
- ClassDB::bind_method("_prompt_changed",&FindReplaceDialog::_prompt_changed);
- ClassDB::bind_method("_skip_pressed",&FindReplaceDialog::_skip_pressed);
+ ClassDB::bind_method("_search_text_entered", &FindReplaceDialog::_search_text_entered);
+ ClassDB::bind_method("_replace_text_entered", &FindReplaceDialog::_replace_text_entered);
+ ClassDB::bind_method("_prompt_changed", &FindReplaceDialog::_prompt_changed);
+ ClassDB::bind_method("_skip_pressed", &FindReplaceDialog::_skip_pressed);
ADD_SIGNAL(MethodInfo("search"));
ADD_SIGNAL(MethodInfo("skip"));
-
}
FindReplaceDialog::FindReplaceDialog() {
- set_self_modulate(Color(1,1,1,0.8));
+ set_self_modulate(Color(1, 1, 1, 0.8));
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
-
-
- search_text = memnew( LineEdit );
- vb->add_margin_child(TTR("Search"),search_text);
- search_text->connect("text_entered", this,"_search_text_entered");
+ search_text = memnew(LineEdit);
+ vb->add_margin_child(TTR("Search"), search_text);
+ search_text->connect("text_entered", this, "_search_text_entered");
//search_text->set_self_opacity(0.7);
-
-
- replace_label = memnew( Label);
+ replace_label = memnew(Label);
replace_label->set_text(TTR("Replace By"));
vb->add_child(replace_label);
- replace_mc= memnew( MarginContainer);
+ replace_mc = memnew(MarginContainer);
vb->add_child(replace_mc);
- replace_text = memnew( LineEdit );
- replace_text->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- replace_text->set_begin( Point2(15,132) );
- replace_text->set_end( Point2(15,135) );
+ replace_text = memnew(LineEdit);
+ replace_text->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ replace_text->set_begin(Point2(15, 132));
+ replace_text->set_end(Point2(15, 135));
//replace_text->set_self_opacity(0.7);
replace_mc->add_child(replace_text);
+ replace_text->connect("text_entered", this, "_replace_text_entered");
- replace_text->connect("text_entered", this,"_replace_text_entered");
-
-
-
- MarginContainer *opt_mg = memnew( MarginContainer );
+ MarginContainer *opt_mg = memnew(MarginContainer);
vb->add_child(opt_mg);
- VBoxContainer *svb = memnew( VBoxContainer);
+ VBoxContainer *svb = memnew(VBoxContainer);
opt_mg->add_child(svb);
- svb ->add_child(memnew(Label));
+ svb->add_child(memnew(Label));
- whole_words = memnew( CheckButton );
+ whole_words = memnew(CheckButton);
whole_words->set_text(TTR("Whole Words"));
svb->add_child(whole_words);
- case_sensitive = memnew( CheckButton );
+ case_sensitive = memnew(CheckButton);
case_sensitive->set_text(TTR("Case Sensitive"));
svb->add_child(case_sensitive);
- backwards = memnew( CheckButton );
+ backwards = memnew(CheckButton);
backwards->set_text(TTR("Backwards"));
svb->add_child(backwards);
- opt_mg = memnew( MarginContainer );
+ opt_mg = memnew(MarginContainer);
vb->add_child(opt_mg);
- VBoxContainer *rvb = memnew( VBoxContainer);
+ VBoxContainer *rvb = memnew(VBoxContainer);
opt_mg->add_child(rvb);
- replace_vb=rvb;
+ replace_vb = rvb;
//rvb ->add_child(memnew(HSeparator));
- rvb ->add_child(memnew(Label));
+ rvb->add_child(memnew(Label));
- prompt = memnew( CheckButton );
+ prompt = memnew(CheckButton);
prompt->set_text(TTR("Prompt On Replace"));
rvb->add_child(prompt);
- prompt->connect("pressed", this,"_prompt_changed");
+ prompt->connect("pressed", this, "_prompt_changed");
- selection_only = memnew( CheckButton );
+ selection_only = memnew(CheckButton);
selection_only->set_text(TTR("Selection Only"));
rvb->add_child(selection_only);
+ int margin = get_constant("margin", "Dialogs");
+ int button_margin = get_constant("button_margin", "Dialogs");
- int margin = get_constant("margin","Dialogs");
- int button_margin = get_constant("button_margin","Dialogs");
-
- skip = memnew( Button );
- skip->set_anchor( MARGIN_LEFT, ANCHOR_END );
- skip->set_anchor( MARGIN_TOP, ANCHOR_END );
- skip->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- skip->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
- skip->set_begin( Point2( 70, button_margin ) );
- skip->set_end( Point2( 10, margin ) );
+ skip = memnew(Button);
+ skip->set_anchor(MARGIN_LEFT, ANCHOR_END);
+ skip->set_anchor(MARGIN_TOP, ANCHOR_END);
+ skip->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ skip->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
+ skip->set_begin(Point2(70, button_margin));
+ skip->set_end(Point2(10, margin));
skip->set_text(TTR("Skip"));
add_child(skip);
- skip->connect("pressed", this,"_skip_pressed");
-
+ skip->connect("pressed", this, "_skip_pressed");
- error_label = memnew( Label );
+ error_label = memnew(Label);
error_label->set_align(Label::ALIGN_CENTER);
- error_label->add_color_override("font_color",Color(1,0.4,0.3));
- error_label->add_color_override("font_color_shadow",Color(0,0,0,0.2));
- error_label->add_constant_override("shadow_as_outline",1);
+ error_label->add_color_override("font_color", Color(1, 0.4, 0.3));
+ error_label->add_color_override("font_color_shadow", Color(0, 0, 0, 0.2));
+ error_label->add_constant_override("shadow_as_outline", 1);
vb->add_child(error_label);
-
set_hide_on_ok(false);
-
}
-
/*** CODE EDITOR ****/
-void CodeTextEditor::_text_editor_gui_input(const InputEvent& p_event) {
+void CodeTextEditor::_text_editor_gui_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::MOUSE_BUTTON) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON) {
- const InputEventMouseButton& mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
if (mb.pressed && mb.mod.command) {
- if (mb.button_index==BUTTON_WHEEL_UP) {
+ if (mb.button_index == BUTTON_WHEEL_UP) {
_zoom_in();
- } else if (mb.button_index==BUTTON_WHEEL_DOWN) {
+ } else if (mb.button_index == BUTTON_WHEEL_DOWN) {
_zoom_out();
}
}
- } else if (p_event.type==InputEvent::KEY) {
+ } else if (p_event.type == InputEvent::KEY) {
if (p_event.key.pressed) {
if (ED_IS_SHORTCUT("script_editor/zoom_in", p_event)) {
@@ -1027,16 +987,16 @@ void CodeTextEditor::_text_editor_gui_input(const InputEvent& p_event) {
}
void CodeTextEditor::_zoom_in() {
- font_resize_val+=1;
+ font_resize_val += 1;
- if (font_resize_timer->get_time_left()==0)
+ if (font_resize_timer->get_time_left() == 0)
font_resize_timer->start();
}
void CodeTextEditor::_zoom_out() {
- font_resize_val-=1;
+ font_resize_val -= 1;
- if (font_resize_timer->get_time_left()==0)
+ if (font_resize_timer->get_time_left() == 0)
font_resize_timer->start();
}
@@ -1044,7 +1004,7 @@ void CodeTextEditor::_reset_zoom() {
Ref<DynamicFont> font = text_editor->get_font("font"); // reset source font size to default
if (font.is_valid()) {
- EditorSettings::get_singleton()->set("interface/source_font_size",14);
+ EditorSettings::get_singleton()->set("interface/source_font_size", 14);
font->set_size(14);
}
}
@@ -1072,19 +1032,19 @@ void CodeTextEditor::_complete_request() {
List<String> entries;
String ctext = text_editor->get_text_for_completion();
- _code_complete_script(ctext,&entries);
+ _code_complete_script(ctext, &entries);
if (code_complete_func) {
- code_complete_func(code_complete_ud,ctext,&entries);
+ code_complete_func(code_complete_ud, ctext, &entries);
}
// print_line("COMPLETE: "+p_request);
- if (entries.size()==0)
+ if (entries.size() == 0)
return;
Vector<String> strs;
strs.resize(entries.size());
- int i=0;
- for(List<String>::Element *E=entries.front();E;E=E->next()) {
+ int i = 0;
+ for (List<String>::Element *E = entries.front(); E; E = E->next()) {
- strs[i++]=E->get();
+ strs[i++] = E->get();
}
text_editor->code_complete(strs);
@@ -1095,14 +1055,14 @@ void CodeTextEditor::_font_resize_timeout() {
Ref<DynamicFont> font = text_editor->get_font("font");
if (font.is_valid()) {
- int size=font->get_size()+font_resize_val;
+ int size = font->get_size() + font_resize_val;
- if (size>=8 && size<=96) {
- EditorSettings::get_singleton()->set("interface/source_font_size",size);
+ if (size >= 8 && size <= 96) {
+ EditorSettings::get_singleton()->set("interface/source_font_size", size);
font->set_size(size);
}
- font_resize_val=0;
+ font_resize_val = 0;
}
}
@@ -1124,15 +1084,14 @@ void CodeTextEditor::update_editor_settings() {
text_editor->cursor_set_block_mode(EditorSettings::get_singleton()->get("text_editor/cursor/block_caret"));
}
-void CodeTextEditor::set_error(const String& p_error) {
+void CodeTextEditor::set_error(const String &p_error) {
- if (p_error!="") {
+ if (p_error != "") {
error->set_text(p_error);
error->show();
} else {
error->hide();
}
-
}
void CodeTextEditor::_update_font() {
@@ -1140,16 +1099,16 @@ void CodeTextEditor::_update_font() {
// FONTS
String editor_font = EDITOR_DEF("text_editor/theme/font", "");
bool font_overridden = false;
- if (editor_font!="") {
+ if (editor_font != "") {
Ref<Font> fnt = ResourceLoader::load(editor_font);
if (fnt.is_valid()) {
- text_editor->add_font_override("font",fnt);
+ text_editor->add_font_override("font", fnt);
font_overridden = true;
}
}
- if(!font_overridden) {
+ if (!font_overridden) {
- text_editor->add_font_override("font",get_font("source","EditorFonts"));
+ text_editor->add_font_override("font", get_font("source", "EditorFonts"));
}
}
@@ -1159,76 +1118,69 @@ void CodeTextEditor::_on_settings_change() {
// AUTO BRACE COMPLETION
text_editor->set_auto_brace_completion(
- EDITOR_DEF("text_editor/completion/auto_brace_complete", true)
- );
+ EDITOR_DEF("text_editor/completion/auto_brace_complete", true));
code_complete_timer->set_wait_time(
- EDITOR_DEF("text_editor/completion/code_complete_delay",.3f)
- );
+ EDITOR_DEF("text_editor/completion/code_complete_delay", .3f));
- enable_complete_timer = EDITOR_DEF("text_editor/completion/enable_code_completion_delay",true);
+ enable_complete_timer = EDITOR_DEF("text_editor/completion/enable_code_completion_delay", true);
// call hint settings
text_editor->set_callhint_settings(
- EDITOR_DEF("text_editor/completion/put_callhint_tooltip_below_current_line", true),
- EDITOR_DEF("text_editor/completion/callhint_tooltip_offset", Vector2())
- );
+ EDITOR_DEF("text_editor/completion/put_callhint_tooltip_below_current_line", true),
+ EDITOR_DEF("text_editor/completion/callhint_tooltip_offset", Vector2()));
}
void CodeTextEditor::_text_changed_idle_timeout() {
-
_validate_script();
emit_signal("validate_script");
}
void CodeTextEditor::_notification(int p_what) {
-
- if (p_what==EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
+ if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
_load_theme_settings();
emit_signal("load_theme_settings");
}
- if (p_what==NOTIFICATION_THEME_CHANGED) {
+ if (p_what == NOTIFICATION_THEME_CHANGED) {
_update_font();
}
}
void CodeTextEditor::_bind_methods() {
- ClassDB::bind_method("_text_editor_gui_input",&CodeTextEditor::_text_editor_gui_input);
- ClassDB::bind_method("_line_col_changed",&CodeTextEditor::_line_col_changed);
- ClassDB::bind_method("_text_changed",&CodeTextEditor::_text_changed);
- ClassDB::bind_method("_on_settings_change",&CodeTextEditor::_on_settings_change);
- ClassDB::bind_method("_text_changed_idle_timeout",&CodeTextEditor::_text_changed_idle_timeout);
- ClassDB::bind_method("_code_complete_timer_timeout",&CodeTextEditor::_code_complete_timer_timeout);
- ClassDB::bind_method("_complete_request",&CodeTextEditor::_complete_request);
- ClassDB::bind_method("_font_resize_timeout",&CodeTextEditor::_font_resize_timeout);
+ ClassDB::bind_method("_text_editor_gui_input", &CodeTextEditor::_text_editor_gui_input);
+ ClassDB::bind_method("_line_col_changed", &CodeTextEditor::_line_col_changed);
+ ClassDB::bind_method("_text_changed", &CodeTextEditor::_text_changed);
+ ClassDB::bind_method("_on_settings_change", &CodeTextEditor::_on_settings_change);
+ ClassDB::bind_method("_text_changed_idle_timeout", &CodeTextEditor::_text_changed_idle_timeout);
+ ClassDB::bind_method("_code_complete_timer_timeout", &CodeTextEditor::_code_complete_timer_timeout);
+ ClassDB::bind_method("_complete_request", &CodeTextEditor::_complete_request);
+ ClassDB::bind_method("_font_resize_timeout", &CodeTextEditor::_font_resize_timeout);
ADD_SIGNAL(MethodInfo("validate_script"));
ADD_SIGNAL(MethodInfo("load_theme_settings"));
-
}
-void CodeTextEditor::set_code_complete_func(CodeTextEditorCodeCompleteFunc p_code_complete_func,void * p_ud) {
- code_complete_func=p_code_complete_func;
- code_complete_ud=p_ud;
+void CodeTextEditor::set_code_complete_func(CodeTextEditorCodeCompleteFunc p_code_complete_func, void *p_ud) {
+ code_complete_func = p_code_complete_func;
+ code_complete_ud = p_ud;
}
-
CodeTextEditor::CodeTextEditor() {
- code_complete_func=NULL;
- ED_SHORTCUT("script_editor/zoom_in", TTR("Zoom In"), KEY_MASK_CMD|KEY_EQUAL);
- ED_SHORTCUT("script_editor/zoom_out", TTR("Zoom Out"), KEY_MASK_CMD|KEY_MINUS);
- ED_SHORTCUT("script_editor/reset_zoom", TTR("Reset Zoom"), KEY_MASK_CMD|KEY_0);
+ code_complete_func = NULL;
+ ED_SHORTCUT("script_editor/zoom_in", TTR("Zoom In"), KEY_MASK_CMD | KEY_EQUAL);
+ ED_SHORTCUT("script_editor/zoom_out", TTR("Zoom Out"), KEY_MASK_CMD | KEY_MINUS);
+ ED_SHORTCUT("script_editor/reset_zoom", TTR("Reset Zoom"), KEY_MASK_CMD | KEY_0);
- find_replace_bar = memnew( FindReplaceBar );
+ find_replace_bar = memnew(FindReplaceBar);
add_child(find_replace_bar);
find_replace_bar->set_h_size_flags(SIZE_EXPAND_FILL);
find_replace_bar->hide();
- text_editor = memnew( TextEdit );
+ text_editor = memnew(TextEdit);
add_child(text_editor);
text_editor->set_v_size_flags(SIZE_EXPAND_FILL);
@@ -1238,86 +1190,86 @@ CodeTextEditor::CodeTextEditor() {
text_editor->set_brace_matching(true);
text_editor->set_auto_indent(true);
- MarginContainer *status_mc = memnew( MarginContainer );
+ MarginContainer *status_mc = memnew(MarginContainer);
add_child(status_mc);
status_mc->set("custom_constants/margin_left", 2);
status_mc->set("custom_constants/margin_top", 5);
status_mc->set("custom_constants/margin_right", 2);
status_mc->set("custom_constants/margin_bottom", 1);
- HBoxContainer *status_bar = memnew( HBoxContainer );
+ HBoxContainer *status_bar = memnew(HBoxContainer);
status_mc->add_child(status_bar);
status_bar->set_h_size_flags(SIZE_EXPAND_FILL);
- status_bar->add_child( memnew( Label ) ); //to keep the height if the other labels are not visible
+ status_bar->add_child(memnew(Label)); //to keep the height if the other labels are not visible
- idle = memnew( Timer );
+ idle = memnew(Timer);
add_child(idle);
idle->set_one_shot(true);
- idle->set_wait_time(EDITOR_DEF("text_editor/completion/idle_parse_delay",2));
+ idle->set_wait_time(EDITOR_DEF("text_editor/completion/idle_parse_delay", 2));
code_complete_timer = memnew(Timer);
add_child(code_complete_timer);
code_complete_timer->set_one_shot(true);
- enable_complete_timer = EDITOR_DEF("text_editor/completion/enable_code_completion_delay",true);
+ enable_complete_timer = EDITOR_DEF("text_editor/completion/enable_code_completion_delay", true);
- code_complete_timer->set_wait_time(EDITOR_DEF("text_editor/completion/code_complete_delay",.3f));
+ code_complete_timer->set_wait_time(EDITOR_DEF("text_editor/completion/code_complete_delay", .3f));
- error = memnew( Label );
+ error = memnew(Label);
status_bar->add_child(error);
error->hide();
error->set_valign(Label::VALIGN_CENTER);
- error->add_color_override("font_color",Color(1,0.7,0.6,0.9));
+ error->add_color_override("font_color", Color(1, 0.7, 0.6, 0.9));
status_bar->add_spacer();
- Label *line_txt = memnew( Label );
+ Label *line_txt = memnew(Label);
status_bar->add_child(line_txt);
line_txt->set_align(Label::ALIGN_RIGHT);
line_txt->set_valign(Label::VALIGN_CENTER);
line_txt->set_v_size_flags(SIZE_FILL);
line_txt->set_text(TTR("Line:"));
- line_nb = memnew( Label );
+ line_nb = memnew(Label);
status_bar->add_child(line_nb);
line_nb->set_valign(Label::VALIGN_CENTER);
line_nb->set_v_size_flags(SIZE_FILL);
line_nb->set_autowrap(true); // workaround to prevent resizing the label on each change
- line_nb->set_custom_minimum_size(Size2(40,1)*EDSCALE);
+ line_nb->set_custom_minimum_size(Size2(40, 1) * EDSCALE);
- Label *col_txt = memnew( Label );
+ Label *col_txt = memnew(Label);
status_bar->add_child(col_txt);
col_txt->set_align(Label::ALIGN_RIGHT);
col_txt->set_valign(Label::VALIGN_CENTER);
col_txt->set_v_size_flags(SIZE_FILL);
col_txt->set_text(TTR("Col:"));
- col_nb = memnew( Label );
+ col_nb = memnew(Label);
status_bar->add_child(col_nb);
col_nb->set_valign(Label::VALIGN_CENTER);
col_nb->set_v_size_flags(SIZE_FILL);
col_nb->set_autowrap(true); // workaround to prevent resizing the label on each change
- col_nb->set_custom_minimum_size(Size2(40,1)*EDSCALE);
+ col_nb->set_custom_minimum_size(Size2(40, 1) * EDSCALE);
- text_editor->connect("gui_input", this,"_text_editor_gui_input");
- text_editor->connect("cursor_changed", this,"_line_col_changed");
- text_editor->connect("text_changed", this,"_text_changed");
- text_editor->connect("request_completion", this,"_complete_request");
+ text_editor->connect("gui_input", this, "_text_editor_gui_input");
+ text_editor->connect("cursor_changed", this, "_line_col_changed");
+ text_editor->connect("text_changed", this, "_text_changed");
+ text_editor->connect("request_completion", this, "_complete_request");
Vector<String> cs;
cs.push_back(".");
cs.push_back(",");
cs.push_back("(");
cs.push_back("$");
- text_editor->set_completion(true,cs);
- idle->connect("timeout", this,"_text_changed_idle_timeout");
+ text_editor->set_completion(true, cs);
+ idle->connect("timeout", this, "_text_changed_idle_timeout");
- code_complete_timer->connect("timeout", this,"_code_complete_timer_timeout");
+ code_complete_timer->connect("timeout", this, "_code_complete_timer_timeout");
- font_resize_val=0;
+ font_resize_val = 0;
font_resize_timer = memnew(Timer);
add_child(font_resize_timer);
font_resize_timer->set_one_shot(true);
font_resize_timer->set_wait_time(0.07);
font_resize_timer->connect("timeout", this, "_font_resize_timeout");
- EditorSettings::get_singleton()->connect("settings_changed",this,"_on_settings_change");
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_on_settings_change");
}
diff --git a/editor/code_editor.h b/editor/code_editor.h
index 7582985d4c..8fa52b03f7 100644
--- a/editor/code_editor.h
+++ b/editor/code_editor.h
@@ -30,19 +30,17 @@
#define CODE_EDITOR_H
#include "editor/editor_plugin.h"
-#include "scene/gui/text_edit.h"
-#include "scene/gui/dialogs.h"
-#include "scene/main/timer.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/check_button.h"
#include "scene/gui/check_box.h"
+#include "scene/gui/check_button.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/line_edit.h"
-
-
+#include "scene/gui/text_edit.h"
+#include "scene/gui/tool_button.h"
+#include "scene/main/timer.h"
class GotoLineDialog : public ConfirmationDialog {
- GDCLASS(GotoLineDialog,ConfirmationDialog);
+ GDCLASS(GotoLineDialog, ConfirmationDialog);
Label *line_label;
LineEdit *line;
@@ -50,19 +48,18 @@ class GotoLineDialog : public ConfirmationDialog {
TextEdit *text_editor;
virtual void ok_pressed();
-public:
+public:
void popup_find_line(TextEdit *p_edit);
int get_line() const;
-
void set_text_editor(TextEdit *p_text_editor);
GotoLineDialog();
};
class FindReplaceBar : public HBoxContainer {
- GDCLASS(FindReplaceBar,HBoxContainer);
+ GDCLASS(FindReplaceBar, HBoxContainer);
LineEdit *search_text;
ToolButton *find_prev;
@@ -89,16 +86,16 @@ class FindReplaceBar : public HBoxContainer {
bool replace_all_mode;
bool preserve_cursor;
- void _get_search_from(int& r_line, int& r_col);
+ void _get_search_from(int &r_line, int &r_col);
void _show_search();
void _hide_bar();
void _editor_text_changed();
void _search_options_changed(bool p_pressed);
- void _search_text_changed(const String& p_text);
- void _search_text_entered(const String& p_text);
- void _replace_text_entered(const String& p_text);
+ void _search_text_changed(const String &p_text);
+ void _search_text_entered(const String &p_text);
+ void _replace_text_entered(const String &p_text);
protected:
void _notification(int p_what);
@@ -118,7 +115,7 @@ public:
bool is_case_sensitive() const;
bool is_whole_words() const;
bool is_selection_only() const;
- void set_error(const String& p_label);
+ void set_error(const String &p_label);
void set_text_edit(TextEdit *p_text_edit);
@@ -134,7 +131,7 @@ public:
class FindReplaceDialog : public ConfirmationDialog {
- GDCLASS(FindReplaceDialog,ConfirmationDialog);
+ GDCLASS(FindReplaceDialog, ConfirmationDialog);
LineEdit *search_text;
LineEdit *replace_text;
@@ -149,15 +146,14 @@ class FindReplaceDialog : public ConfirmationDialog {
Label *replace_label;
VBoxContainer *replace_vb;
- void _search_text_entered(const String& p_text);
- void _replace_text_entered(const String& p_text);
+ void _search_text_entered(const String &p_text);
+ void _replace_text_entered(const String &p_text);
void _prompt_changed();
void _skip_pressed();
-
TextEdit *text_edit;
-protected:
+protected:
void _search_callback();
void _replace_skip_callback();
@@ -166,8 +162,8 @@ protected:
virtual void ok_pressed();
static void _bind_methods();
-public:
+public:
String get_search_text() const;
String get_replace_text() const;
bool is_whole_words() const;
@@ -178,7 +174,7 @@ public:
bool is_replace_selection_only() const;
void set_replace_selection_only(bool p_enable);
- void set_error(const String& p_error);
+ void set_error(const String &p_error);
void popup_search();
void popup_replace();
@@ -189,12 +185,11 @@ public:
FindReplaceDialog();
};
-
-typedef void (*CodeTextEditorCodeCompleteFunc)(void* p_ud,const String& p_code, List<String>* r_options);
+typedef void (*CodeTextEditorCodeCompleteFunc)(void *p_ud, const String &p_code, List<String> *r_options);
class CodeTextEditor : public VBoxContainer {
- GDCLASS(CodeTextEditor,VBoxContainer);
+ GDCLASS(CodeTextEditor, VBoxContainer);
TextEdit *text_editor;
FindReplaceBar *find_replace_bar;
@@ -217,21 +212,18 @@ class CodeTextEditor : public VBoxContainer {
void _complete_request();
void _font_resize_timeout();
- void _text_editor_gui_input(const InputEvent& p_event);
+ void _text_editor_gui_input(const InputEvent &p_event);
void _zoom_in();
void _zoom_out();
void _reset_zoom();
-
CodeTextEditorCodeCompleteFunc code_complete_func;
void *code_complete_ud;
protected:
-
-
virtual void _load_theme_settings() {}
virtual void _validate_script() {}
- virtual void _code_complete_script(const String& p_code, List<String>* r_options) {}
+ virtual void _code_complete_script(const String &p_code, List<String> *r_options) {}
void _text_changed_idle_timeout();
void _code_complete_timer_timeout();
@@ -241,21 +233,16 @@ protected:
static void _bind_methods();
public:
-
void update_editor_settings();
- void set_error(const String& p_error);
+ void set_error(const String &p_error);
void update_line_and_column() { _line_col_changed(); }
TextEdit *get_text_edit() { return text_editor; }
FindReplaceBar *get_find_replace_bar() { return find_replace_bar; }
virtual void apply_code() {}
-
- void set_code_complete_func(CodeTextEditorCodeCompleteFunc p_code_complete_func, void * p_ud);
-
+ void set_code_complete_func(CodeTextEditorCodeCompleteFunc p_code_complete_func, void *p_ud);
CodeTextEditor();
};
-
-
#endif // CODE_EDITOR_H
diff --git a/editor/collada/collada.cpp b/editor/collada/collada.cpp
index 2ba4f648a3..d96f1f4b6e 100644
--- a/editor/collada/collada.cpp
+++ b/editor/collada/collada.cpp
@@ -44,12 +44,10 @@
/* HELPERS */
+String Collada::Effect::get_texture_path(const String &p_source, Collada &state) const {
-
-String Collada::Effect::get_texture_path(const String& p_source,Collada& state) const {
-
- String image=p_source;
- ERR_FAIL_COND_V(!state.state.image_map.has(image),"");
+ String image = p_source;
+ ERR_FAIL_COND_V(!state.state.image_map.has(image), "");
return state.state.image_map[image].path;
}
@@ -57,50 +55,47 @@ Transform Collada::get_root_transform() const {
Transform unit_scale_transform;
#ifndef COLLADA_IMPORT_SCALE_SCENE
- unit_scale_transform.scale(Vector3(state.unit_scale,state.unit_scale,state.unit_scale));
+ unit_scale_transform.scale(Vector3(state.unit_scale, state.unit_scale, state.unit_scale));
#endif
return unit_scale_transform;
}
-
-
void Collada::Vertex::fix_unit_scale(Collada &state) {
#ifdef COLLADA_IMPORT_SCALE_SCENE
- vertex*=state.state.unit_scale;
+ vertex *= state.state.unit_scale;
#endif
}
-static String _uri_to_id(const String& p_uri) {
+static String _uri_to_id(const String &p_uri) {
if (p_uri.begins_with("#"))
- return p_uri.substr(1,p_uri.size()-1);
+ return p_uri.substr(1, p_uri.size() - 1);
else
return p_uri;
-
}
/** HELPER FUNCTIONS **/
-Transform Collada::fix_transform(const Transform& p_transform) {
+Transform Collada::fix_transform(const Transform &p_transform) {
- Transform tr=p_transform;
+ Transform tr = p_transform;
#ifndef NO_UP_AXIS_SWAP
- if (state.up_axis!=Vector3::AXIS_Y) {
+ if (state.up_axis != Vector3::AXIS_Y) {
- for(int i=0;i<3;i++)
- SWAP(tr.basis[1][i],tr.basis[state.up_axis][i]);
- for(int i=0;i<3;i++)
- SWAP(tr.basis[i][1],tr.basis[i][state.up_axis]);
+ for (int i = 0; i < 3; i++)
+ SWAP(tr.basis[1][i], tr.basis[state.up_axis][i]);
+ for (int i = 0; i < 3; i++)
+ SWAP(tr.basis[i][1], tr.basis[i][state.up_axis]);
- SWAP(tr.origin[1],tr.origin[state.up_axis]);
+ SWAP(tr.origin[1], tr.origin[state.up_axis]);
- tr.basis[state.up_axis][0]=-tr.basis[state.up_axis][0];
- tr.basis[state.up_axis][1]=-tr.basis[state.up_axis][1];
- tr.basis[0][state.up_axis]=-tr.basis[0][state.up_axis];
- tr.basis[1][state.up_axis]=-tr.basis[1][state.up_axis];
- tr.origin[state.up_axis]=-tr.origin[state.up_axis];
+ tr.basis[state.up_axis][0] = -tr.basis[state.up_axis][0];
+ tr.basis[state.up_axis][1] = -tr.basis[state.up_axis][1];
+ tr.basis[0][state.up_axis] = -tr.basis[0][state.up_axis];
+ tr.basis[1][state.up_axis] = -tr.basis[1][state.up_axis];
+ tr.origin[state.up_axis] = -tr.origin[state.up_axis];
}
#endif
@@ -109,25 +104,23 @@ Transform Collada::fix_transform(const Transform& p_transform) {
//return state.matrix_fix * p_transform;
}
-
-static Transform _read_transform_from_array(const Vector<float>& array, int ofs=0) {
+static Transform _read_transform_from_array(const Vector<float> &array, int ofs = 0) {
Transform tr;
// i wonder why collada matrices are transposed, given that's opposed to opengl..
- tr.basis.elements[0][0]=array[0+ofs];
- tr.basis.elements[0][1]=array[1+ofs];
- tr.basis.elements[0][2]=array[2+ofs];
- tr.basis.elements[1][0]=array[4+ofs];
- tr.basis.elements[1][1]=array[5+ofs];
- tr.basis.elements[1][2]=array[6+ofs];
- tr.basis.elements[2][0]=array[8+ofs];
- tr.basis.elements[2][1]=array[9+ofs];
- tr.basis.elements[2][2]=array[10+ofs];
- tr.origin.x=array[3+ofs];
- tr.origin.y=array[7+ofs];
- tr.origin.z=array[11+ofs];
+ tr.basis.elements[0][0] = array[0 + ofs];
+ tr.basis.elements[0][1] = array[1 + ofs];
+ tr.basis.elements[0][2] = array[2 + ofs];
+ tr.basis.elements[1][0] = array[4 + ofs];
+ tr.basis.elements[1][1] = array[5 + ofs];
+ tr.basis.elements[1][2] = array[6 + ofs];
+ tr.basis.elements[2][0] = array[8 + ofs];
+ tr.basis.elements[2][1] = array[9 + ofs];
+ tr.basis.elements[2][2] = array[10 + ofs];
+ tr.origin.x = array[3 + ofs];
+ tr.origin.y = array[7 + ofs];
+ tr.origin.z = array[11 + ofs];
return tr;
-
}
/* STRUCTURES */
@@ -136,50 +129,49 @@ Transform Collada::Node::compute_transform(Collada &state) const {
Transform xform;
- for(int i=0;i<xform_list.size();i++) {
+ for (int i = 0; i < xform_list.size(); i++) {
Transform xform_step;
- const XForm& xf = xform_list[i];
- switch(xf.op) {
+ const XForm &xf = xform_list[i];
+ switch (xf.op) {
case XForm::OP_ROTATE: {
- if (xf.data.size()>=4) {
+ if (xf.data.size() >= 4) {
- xform_step.rotate(Vector3(xf.data[0],xf.data[1],xf.data[2]),Math::deg2rad(xf.data[3]));
+ xform_step.rotate(Vector3(xf.data[0], xf.data[1], xf.data[2]), Math::deg2rad(xf.data[3]));
}
} break;
case XForm::OP_SCALE: {
- if (xf.data.size()>=3) {
+ if (xf.data.size() >= 3) {
- xform_step.scale(Vector3(xf.data[0],xf.data[1],xf.data[2]));
+ xform_step.scale(Vector3(xf.data[0], xf.data[1], xf.data[2]));
}
} break;
case XForm::OP_TRANSLATE: {
- if (xf.data.size()>=3) {
+ if (xf.data.size() >= 3) {
- xform_step.origin=Vector3(xf.data[0],xf.data[1],xf.data[2]);
+ xform_step.origin = Vector3(xf.data[0], xf.data[1], xf.data[2]);
}
} break;
case XForm::OP_MATRIX: {
- if (xf.data.size()>=16) {
- xform_step = _read_transform_from_array(xf.data,0);
+ if (xf.data.size() >= 16) {
+ xform_step = _read_transform_from_array(xf.data, 0);
}
} break;
default: {}
-
}
xform = xform * xform_step;
}
#ifdef COLLADA_IMPORT_SCALE_SCENE
- xform.origin*=state.state.unit_scale;
+ xform.origin *= state.state.unit_scale;
#endif
return xform;
}
@@ -195,69 +187,67 @@ Transform Collada::Node::get_global_transform() const {
return parent->get_global_transform() * default_transform;
else
return default_transform;
-
}
Vector<float> Collada::AnimationTrack::get_value_at_time(float p_time) {
- ERR_FAIL_COND_V(keys.size()==0,Vector<float>());
- int i=0;
+ ERR_FAIL_COND_V(keys.size() == 0, Vector<float>());
+ int i = 0;
- for(i=0;i<keys.size();i++) {
+ for (i = 0; i < keys.size(); i++) {
- if (keys[i].time>p_time)
+ if (keys[i].time > p_time)
break;
}
- if (i==0)
+ if (i == 0)
return keys[0].data;
- if (i==keys.size())
- return keys[keys.size()-1].data;
+ if (i == keys.size())
+ return keys[keys.size() - 1].data;
- switch(keys[i].interp_type) {
+ switch (keys[i].interp_type) {
case INTERP_BEZIER: //wait for bezier
case INTERP_LINEAR: {
- float c = (p_time-keys[i-1].time)/(keys[i].time-keys[i-1].time);
+ float c = (p_time - keys[i - 1].time) / (keys[i].time - keys[i - 1].time);
- if (keys[i].data.size()==16) {
+ if (keys[i].data.size() == 16) {
//interpolate a matrix
- Transform src = _read_transform_from_array(keys[i-1].data);
+ Transform src = _read_transform_from_array(keys[i - 1].data);
Transform dst = _read_transform_from_array(keys[i].data);
-
- Transform interp = c<0.001 ? src : src.interpolate_with(dst,c);
+ Transform interp = c < 0.001 ? src : src.interpolate_with(dst, c);
Vector<float> ret;
ret.resize(16);
Transform tr;
// i wonder why collada matrices are transposed, given that's opposed to opengl..
- ret[0]=interp.basis.elements[0][0];
- ret[1]=interp.basis.elements[0][1];
- ret[2]=interp.basis.elements[0][2];
- ret[4]=interp.basis.elements[1][0];
- ret[5]=interp.basis.elements[1][1];
- ret[6]=interp.basis.elements[1][2];
- ret[8]=interp.basis.elements[2][0];
- ret[9]=interp.basis.elements[2][1];
- ret[10]=interp.basis.elements[2][2];
- ret[3]=interp.origin.x;
- ret[7]=interp.origin.y;
- ret[11]=interp.origin.z;
- ret[12]=0;
- ret[13]=0;
- ret[14]=0;
- ret[15]=1;
+ ret[0] = interp.basis.elements[0][0];
+ ret[1] = interp.basis.elements[0][1];
+ ret[2] = interp.basis.elements[0][2];
+ ret[4] = interp.basis.elements[1][0];
+ ret[5] = interp.basis.elements[1][1];
+ ret[6] = interp.basis.elements[1][2];
+ ret[8] = interp.basis.elements[2][0];
+ ret[9] = interp.basis.elements[2][1];
+ ret[10] = interp.basis.elements[2][2];
+ ret[3] = interp.origin.x;
+ ret[7] = interp.origin.y;
+ ret[11] = interp.origin.z;
+ ret[12] = 0;
+ ret[13] = 0;
+ ret[14] = 0;
+ ret[15] = 1;
return ret;
} else {
Vector<float> dest;
dest.resize(keys[i].data.size());
- for(int j=0;j<dest.size();j++) {
+ for (int j = 0; j < dest.size(); j++) {
- dest[j]=keys[i].data[j]*c+keys[i-1].data[j]*(1.0-c);
+ dest[j] = keys[i].data[j] * c + keys[i - 1].data[j] * (1.0 - c);
}
return dest;
//interpolate one by one
@@ -268,140 +258,128 @@ Vector<float> Collada::AnimationTrack::get_value_at_time(float p_time) {
ERR_FAIL_V(Vector<float>());
}
+void Collada::_parse_asset(XMLParser &parser) {
+ while (parser.read() == OK) {
-
-void Collada::_parse_asset(XMLParser& parser) {
-
- while(parser.read()==OK) {
-
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="up_axis") {
+ if (name == "up_axis") {
parser.read();
- if (parser.get_node_data()=="X_UP")
- state.up_axis=Vector3::AXIS_X;
- if (parser.get_node_data()=="Y_UP")
- state.up_axis=Vector3::AXIS_Y;
- if (parser.get_node_data()=="Z_UP")
- state.up_axis=Vector3::AXIS_Z;
+ if (parser.get_node_data() == "X_UP")
+ state.up_axis = Vector3::AXIS_X;
+ if (parser.get_node_data() == "Y_UP")
+ state.up_axis = Vector3::AXIS_Y;
+ if (parser.get_node_data() == "Z_UP")
+ state.up_axis = Vector3::AXIS_Z;
- COLLADA_PRINT("up axis: "+parser.get_node_data());
- } else if (name=="unit") {
+ COLLADA_PRINT("up axis: " + parser.get_node_data());
+ } else if (name == "unit") {
state.unit_scale = parser.get_attribute_value("meter").to_double();
- COLLADA_PRINT("unit scale: "+rtos(state.unit_scale));
+ COLLADA_PRINT("unit scale: " + rtos(state.unit_scale));
}
-
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="asset")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "asset")
break; //end of <asset>
}
}
+void Collada::_parse_image(XMLParser &parser) {
-void Collada::_parse_image(XMLParser& parser) {
-
- String id=parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
-
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
-
Image image;
-
- if (state.version<State::Version(1,4,0)) {
+ if (state.version < State::Version(1, 4, 0)) {
/* <1.4 */
String path = parser.get_attribute_value("source").strip_edges();
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- image.path=GlobalConfig::get_singleton()->localize_path(state.local_path.get_base_dir()+"/"+path.percent_decode());
-
+ image.path = GlobalConfig::get_singleton()->localize_path(state.local_path.get_base_dir() + "/" + path.percent_decode());
}
} else {
+ while (parser.read() == OK) {
- while(parser.read()==OK) {
-
-
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="init_from") {
+ if (name == "init_from") {
parser.read();
String path = parser.get_node_data().strip_edges().percent_decode();
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(state.local_path.get_base_dir()+"/"+path);
+ path = GlobalConfig::get_singleton()->localize_path(state.local_path.get_base_dir() + "/" + path);
- } else if (path.find("file:///")==0) {
- path=path.replace_first("file:///","");
- path=GlobalConfig::get_singleton()->localize_path(path);
+ } else if (path.find("file:///") == 0) {
+ path = path.replace_first("file:///", "");
+ path = GlobalConfig::get_singleton()->localize_path(path);
}
- image.path=path;
+ image.path = path;
- } else if (name=="data") {
+ } else if (name == "data") {
ERR_PRINT("COLLADA Embedded image data not supported!");
- } else if (name=="extra" && !parser.is_empty())
+ } else if (name == "extra" && !parser.is_empty())
parser.skip_section();
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="image")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "image")
break; //end of <asset>
-
}
}
- state.image_map[id]=image;
+ state.image_map[id] = image;
}
-void Collada::_parse_material(XMLParser& parser) {
+void Collada::_parse_material(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
Material material;
- String id=parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
if (parser.has_attribute("name"))
- material.name=parser.get_attribute_value("name");
+ material.name = parser.get_attribute_value("name");
- if (state.version<State::Version(1,4,0)) {
+ if (state.version < State::Version(1, 4, 0)) {
/* <1.4 */
ERR_PRINT("Collada Materials < 1.4 are not supported (yet)");
} else {
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT && parser.get_node_name()=="instance_effect") {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT && parser.get_node_name() == "instance_effect") {
- material.instance_effect=_uri_to_id(parser.get_attribute_value("url"));
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="material")
+ material.instance_effect = _uri_to_id(parser.get_attribute_value("url"));
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "material")
break; //end of <asset>
}
}
- state.material_map[id]=material;
+ state.material_map[id] = material;
}
//! reads floats from inside of xml element until end of xml element
-Vector<float> Collada::_read_float_array(XMLParser& parser) {
+Vector<float> Collada::_read_float_array(XMLParser &parser) {
if (parser.is_empty())
return Vector<float>();
@@ -413,103 +391,93 @@ Vector<float> Collada::_read_float_array(XMLParser& parser) {
splitters.push_back("\t");
Vector<float> array;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
// TODO: check for comments inside the element
// and ignore them.
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
// parse float data
String str = parser.get_node_data();
- array=str.split_floats_mk(splitters,false);
+ array = str.split_floats_mk(splitters, false);
//array=str.split_floats(" ",false);
- }
- else
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
break; // end parsing text
}
return array;
}
-Vector<String> Collada::_read_string_array(XMLParser& parser) {
+Vector<String> Collada::_read_string_array(XMLParser &parser) {
if (parser.is_empty())
return Vector<String>();
Vector<String> array;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
// TODO: check for comments inside the element
// and ignore them.
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
// parse String data
String str = parser.get_node_data();
- array=str.split_spaces();
+ array = str.split_spaces();
/*
for(int i=0;i<array.size();i++) {
print_line(itos(i)+": "+array[i]);
}
*/
- }
- else
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
break; // end parsing text
}
return array;
}
-
-
-Transform Collada::_read_transform(XMLParser& parser) {
+Transform Collada::_read_transform(XMLParser &parser) {
if (parser.is_empty())
return Transform();
Vector<String> array;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
// TODO: check for comments inside the element
// and ignore them.
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
// parse float data
String str = parser.get_node_data();
- array=str.split_spaces();
- }
- else
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
+ array = str.split_spaces();
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
break; // end parsing text
}
- ERR_FAIL_COND_V(array.size()!=16,Transform());
+ ERR_FAIL_COND_V(array.size() != 16, Transform());
Vector<float> farr;
farr.resize(16);
- for(int i=0;i<16;i++) {
- farr[i]=array[i].to_double();
+ for (int i = 0; i < 16; i++) {
+ farr[i] = array[i].to_double();
}
return _read_transform_from_array(farr);
}
-String Collada::_read_empty_draw_type(XMLParser& parser) {
+String Collada::_read_empty_draw_type(XMLParser &parser) {
String empty_draw_type = "";
-
+
if (parser.is_empty())
return empty_draw_type;
-
- while (parser.read()==OK) {
+
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
empty_draw_type = parser.get_node_data();
- }
- else
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END)
break; // end parsing text
}
return empty_draw_type;
}
-Variant Collada::_parse_param(XMLParser& parser) {
+Variant Collada::_parse_param(XMLParser &parser) {
if (parser.is_empty())
return Variant();
@@ -517,197 +485,182 @@ Variant Collada::_parse_param(XMLParser& parser) {
String from = parser.get_node_name();
Variant data;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
if (parser.get_node_name() == "float") {
parser.read();
- if (parser.get_node_type()==XMLParser::NODE_TEXT) {
+ if (parser.get_node_type() == XMLParser::NODE_TEXT) {
- data=parser.get_node_data().to_double();
+ data = parser.get_node_data().to_double();
}
} else if (parser.get_node_name() == "float2") {
Vector<float> v2 = _read_float_array(parser);
- if (v2.size()>=2) {
+ if (v2.size() >= 2) {
- data=Vector2(v2[0],v2[1]);
+ data = Vector2(v2[0], v2[1]);
}
} else if (parser.get_node_name() == "float3") {
Vector<float> v3 = _read_float_array(parser);
- if (v3.size()>=3) {
+ if (v3.size() >= 3) {
- data=Vector3(v3[0],v3[1],v3[2]);
+ data = Vector3(v3[0], v3[1], v3[2]);
}
} else if (parser.get_node_name() == "float4") {
Vector<float> v4 = _read_float_array(parser);
- if (v4.size()>=4) {
+ if (v4.size() >= 4) {
- data=Color(v4[0],v4[1],v4[2],v4[3]);
+ data = Color(v4[0], v4[1], v4[2], v4[3]);
}
} else if (parser.get_node_name() == "sampler2D") {
- while(parser.read()==OK) {
-
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="source") {
+ if (parser.get_node_name() == "source") {
parser.read();
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
- data=parser.get_node_data();
+ data = parser.get_node_data();
}
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="sampler2D")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "sampler2D")
break;
-
}
} else if (parser.get_node_name() == "surface") {
- while(parser.read()==OK) {
-
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="init_from") {
+ if (parser.get_node_name() == "init_from") {
parser.read();
if (parser.get_node_type() == XMLParser::NODE_TEXT) {
- data=parser.get_node_data();
+ data = parser.get_node_data();
}
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="surface")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "surface")
break;
-
}
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==from)
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == from)
+ break;
}
- COLLADA_PRINT("newparam ending "+parser.get_node_name());
+ COLLADA_PRINT("newparam ending " + parser.get_node_name());
return data;
-
}
+void Collada::_parse_effect_material(XMLParser &parser, Effect &effect, String &id) {
-
-void Collada::_parse_effect_material(XMLParser& parser,Effect &effect,String &id) {
-
-
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
// first come the tags we descend, but ignore the top-levels
- COLLADA_PRINT("node name: "+parser.get_node_name());
+ COLLADA_PRINT("node name: " + parser.get_node_name());
if (!parser.is_empty() && (parser.get_node_name() == "profile_COMMON" || parser.get_node_name() == "technique" || parser.get_node_name() == "extra")) {
- _parse_effect_material(parser,effect,id); // try again
+ _parse_effect_material(parser, effect, id); // try again
} else if (parser.get_node_name() == "newparam") {
String name = parser.get_attribute_value("sid");
Variant value = _parse_param(parser);
- effect.params[name]=value;
- COLLADA_PRINT("param: "+name+" value:"+String(value));
+ effect.params[name] = value;
+ COLLADA_PRINT("param: " + name + " value:" + String(value));
} else if (parser.get_node_name() == "constant" ||
- parser.get_node_name() == "lambert" ||
- parser.get_node_name() == "phong" ||
- parser.get_node_name() == "blinn" )
- {
-
- COLLADA_PRINT("shade model: "+parser.get_node_name());
- while(parser.read()==OK) {
+ parser.get_node_name() == "lambert" ||
+ parser.get_node_name() == "phong" ||
+ parser.get_node_name() == "blinn") {
+ COLLADA_PRINT("shade model: " + parser.get_node_name());
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String what = parser.get_node_name();
- if ( what=="emission" ||
- what=="diffuse" ||
- what=="specular" ||
- what=="reflective") {
-
-
+ if (what == "emission" ||
+ what == "diffuse" ||
+ what == "specular" ||
+ what == "reflective") {
// color or texture types
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="color") {
+ if (parser.get_node_name() == "color") {
Vector<float> colorarr = _read_float_array(parser);
- COLLADA_PRINT("colorarr size: "+rtos(colorarr.size()));
+ COLLADA_PRINT("colorarr size: " + rtos(colorarr.size()));
- if (colorarr.size()>=3) {
+ if (colorarr.size() >= 3) {
// alpha strangely not allright? maybe it needs to be multiplied by value as a channel intensity
- Color color(colorarr[0],colorarr[1],colorarr[2],1.0);
- if (what=="diffuse")
- effect.diffuse.color=color;
- if (what=="specular")
- effect.specular.color=color;
- if (what=="emission")
- effect.emission.color=color;
-
- COLLADA_PRINT(what+" color: "+color);
-
+ Color color(colorarr[0], colorarr[1], colorarr[2], 1.0);
+ if (what == "diffuse")
+ effect.diffuse.color = color;
+ if (what == "specular")
+ effect.specular.color = color;
+ if (what == "emission")
+ effect.emission.color = color;
+
+ COLLADA_PRINT(what + " color: " + color);
}
- } else if (parser.get_node_name()=="texture") {
+ } else if (parser.get_node_name() == "texture") {
String sampler = parser.get_attribute_value("texture");
if (!effect.params.has(sampler)) {
- ERR_PRINT(String("Couldn't find sampler: "+sampler+" in material:"+id).utf8().get_data());
+ ERR_PRINT(String("Couldn't find sampler: " + sampler + " in material:" + id).utf8().get_data());
} else {
String surface = effect.params[sampler];
if (!effect.params.has(surface)) {
- ERR_PRINT(String("Couldn't find surface: "+surface+" in material:"+id).utf8().get_data());
+ ERR_PRINT(String("Couldn't find surface: " + surface + " in material:" + id).utf8().get_data());
} else {
String uri = effect.params[surface];
-
- if (what=="diffuse") {
- effect.diffuse.texture=uri;
- } else if (what=="specular") {
- effect.specular.texture=uri;
- } else if (what=="emission") {
- effect.emission.texture=uri;
- } else if (what=="bump") {
- if (parser.has_attribute("bumptype") && parser.get_attribute_value("bumptype")!="NORMALMAP") {
+ if (what == "diffuse") {
+ effect.diffuse.texture = uri;
+ } else if (what == "specular") {
+ effect.specular.texture = uri;
+ } else if (what == "emission") {
+ effect.emission.texture = uri;
+ } else if (what == "bump") {
+ if (parser.has_attribute("bumptype") && parser.get_attribute_value("bumptype") != "NORMALMAP") {
WARN_PRINT("'bump' texture type is not NORMALMAP, only NORMALMAP is supported.")
}
- effect.bump.texture=uri;
+ effect.bump.texture = uri;
}
- COLLADA_PRINT(what+" texture: "+uri);
+ COLLADA_PRINT(what + " texture: " + uri);
}
-
}
} else if (!parser.is_empty())
parser.skip_section();
@@ -716,63 +669,60 @@ void Collada::_parse_effect_material(XMLParser& parser,Effect &effect,String &id
break;
}
- } else if (what=="shininess") {
+ } else if (what == "shininess") {
#if 1
- effect.shininess=_parse_param(parser);
+ effect.shininess = _parse_param(parser);
#else
parser.read();
float shininess = parser.get_node_data().to_double();
- effect.shininess=shininess;
- COLLADA_PRINT("shininess: "+rtos(shininess));
+ effect.shininess = shininess;
+ COLLADA_PRINT("shininess: " + rtos(shininess));
#endif
-
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && (
- parser.get_node_name()=="constant" ||
- parser.get_node_name()=="lambert" ||
- parser.get_node_name()=="phong" ||
- parser.get_node_name()=="blinn"))
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && (parser.get_node_name() == "constant" ||
+ parser.get_node_name() == "lambert" ||
+ parser.get_node_name() == "phong" ||
+ parser.get_node_name() == "blinn"))
break;
}
- } else if (parser.get_node_name()=="double_sided" || parser.get_node_name()=="show_double_sided") { // colladamax / google earth
+ } else if (parser.get_node_name() == "double_sided" || parser.get_node_name() == "show_double_sided") { // colladamax / google earth
// 3DS Max / Google Earth double sided extension
parser.read();
- effect.found_double_sided=true;
- effect.double_sided=parser.get_node_data().to_int();
- COLLADA_PRINT("double sided: "+itos(parser.get_node_data().to_int()));
- } else if (parser.get_node_name()=="unshaded") {
+ effect.found_double_sided = true;
+ effect.double_sided = parser.get_node_data().to_int();
+ COLLADA_PRINT("double sided: " + itos(parser.get_node_data().to_int()));
+ } else if (parser.get_node_name() == "unshaded") {
parser.read();
- effect.unshaded=parser.get_node_data().to_int();
- } else if (parser.get_node_name()=="bump") {
+ effect.unshaded = parser.get_node_data().to_int();
+ } else if (parser.get_node_name() == "bump") {
// color or texture types
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="texture") {
+ if (parser.get_node_name() == "texture") {
String sampler = parser.get_attribute_value("texture");
if (!effect.params.has(sampler)) {
- ERR_PRINT(String("Couldn't find sampler: "+sampler+" in material:"+id).utf8().get_data());
+ ERR_PRINT(String("Couldn't find sampler: " + sampler + " in material:" + id).utf8().get_data());
} else {
String surface = effect.params[sampler];
if (!effect.params.has(surface)) {
- ERR_PRINT(String("Couldn't find surface: "+surface+" in material:"+id).utf8().get_data());
+ ERR_PRINT(String("Couldn't find surface: " + surface + " in material:" + id).utf8().get_data());
} else {
String uri = effect.params[surface];
- if (parser.has_attribute("bumptype") && parser.get_attribute_value("bumptype")!="NORMALMAP") {
+ if (parser.has_attribute("bumptype") && parser.get_attribute_value("bumptype") != "NORMALMAP") {
WARN_PRINT("'bump' texture type is not NORMALMAP, only NORMALMAP is supported.")
}
- effect.bump.texture=uri;
- COLLADA_PRINT(" bump: "+uri);
+ effect.bump.texture = uri;
+ COLLADA_PRINT(" bump: " + uri);
}
-
}
} else if (!parser.is_empty())
parser.skip_section();
@@ -784,204 +734,189 @@ void Collada::_parse_effect_material(XMLParser& parser,Effect &effect,String &id
} else if (!parser.is_empty())
parser.skip_section();
} else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END &&
- (parser.get_node_name() == "effect" ||
- parser.get_node_name() == "profile_COMMON" ||
- parser.get_node_name() == "technique" ||
- parser.get_node_name() == "extra"))
+ (parser.get_node_name() == "effect" ||
+ parser.get_node_name() == "profile_COMMON" ||
+ parser.get_node_name() == "technique" ||
+ parser.get_node_name() == "extra"))
break;
}
-
}
-void Collada::_parse_effect(XMLParser& parser) {
+void Collada::_parse_effect(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
- String id=parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
Effect effect;
if (parser.has_attribute("name"))
- effect.name=parser.get_attribute_value("name");
- _parse_effect_material(parser,effect,id);
-
-
+ effect.name = parser.get_attribute_value("name");
+ _parse_effect_material(parser, effect, id);
- state.effect_map[id]=effect;
-
- COLLADA_PRINT("Effect ID:"+id);
+ state.effect_map[id] = effect;
+ COLLADA_PRINT("Effect ID:" + id);
}
-void Collada::_parse_camera(XMLParser& parser) {
+void Collada::_parse_camera(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
- String id=parser.get_attribute_value("id");
-
-
- state.camera_data_map[id]=CameraData();
- CameraData &camera=state.camera_data_map[id];
+ String id = parser.get_attribute_value("id");
+ state.camera_data_map[id] = CameraData();
+ CameraData &camera = state.camera_data_map[id];
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
-
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="perspective") {
+ if (name == "perspective") {
- camera.mode=CameraData::MODE_PERSPECTIVE;
- } else if (name=="orthographic") {
+ camera.mode = CameraData::MODE_PERSPECTIVE;
+ } else if (name == "orthographic") {
- camera.mode=CameraData::MODE_ORTHOGONAL;
- } else if (name=="xfov") {
+ camera.mode = CameraData::MODE_ORTHOGONAL;
+ } else if (name == "xfov") {
parser.read();
camera.perspective.x_fov = parser.get_node_data().to_double();
- } else if (name=="yfov") {
+ } else if (name == "yfov") {
parser.read();
camera.perspective.y_fov = parser.get_node_data().to_double();
- } else if (name=="xmag") {
+ } else if (name == "xmag") {
parser.read();
camera.orthogonal.x_mag = parser.get_node_data().to_double();
- } else if (name=="ymag") {
+ } else if (name == "ymag") {
parser.read();
camera.orthogonal.y_mag = parser.get_node_data().to_double();
- } else if (name=="aspect_ratio") {
+ } else if (name == "aspect_ratio") {
parser.read();
camera.aspect = parser.get_node_data().to_double();
- } else if (name=="znear") {
+ } else if (name == "znear") {
parser.read();
camera.z_near = parser.get_node_data().to_double();
- } else if (name=="zfar") {
+ } else if (name == "zfar") {
parser.read();
camera.z_far = parser.get_node_data().to_double();
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="camera")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "camera")
break; //end of <asset>
}
- COLLADA_PRINT("Camera ID:"+id);
-
+ COLLADA_PRINT("Camera ID:" + id);
}
-void Collada::_parse_light(XMLParser& parser) {
+void Collada::_parse_light(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
- String id=parser.get_attribute_value("id");
-
+ String id = parser.get_attribute_value("id");
- state.light_data_map[id]=LightData();
- LightData &light=state.light_data_map[id];
+ state.light_data_map[id] = LightData();
+ LightData &light = state.light_data_map[id];
+ while (parser.read() == OK) {
- while(parser.read()==OK) {
-
-
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="ambient") {
+ if (name == "ambient") {
- light.mode=LightData::MODE_AMBIENT;
- } else if (name=="directional") {
+ light.mode = LightData::MODE_AMBIENT;
+ } else if (name == "directional") {
- light.mode=LightData::MODE_DIRECTIONAL;
- } else if (name=="point") {
+ light.mode = LightData::MODE_DIRECTIONAL;
+ } else if (name == "point") {
- light.mode=LightData::MODE_OMNI;
- } else if (name=="spot") {
+ light.mode = LightData::MODE_OMNI;
+ } else if (name == "spot") {
- light.mode=LightData::MODE_SPOT;
- } else if (name=="color") {
+ light.mode = LightData::MODE_SPOT;
+ } else if (name == "color") {
parser.read();
Vector<float> colorarr = _read_float_array(parser);
- COLLADA_PRINT("colorarr size: "+rtos(colorarr.size()));
+ COLLADA_PRINT("colorarr size: " + rtos(colorarr.size()));
- if (colorarr.size()>=4) {
+ if (colorarr.size() >= 4) {
// alpha strangely not allright? maybe it needs to be multiplied by value as a channel intensity
- Color color(colorarr[0],colorarr[1],colorarr[2],1.0);
- light.color=color;
+ Color color(colorarr[0], colorarr[1], colorarr[2], 1.0);
+ light.color = color;
}
- } else if (name=="constant_attenuation") {
+ } else if (name == "constant_attenuation") {
parser.read();
- light.constant_att=parser.get_node_data().to_double();
- } else if (name=="linear_attenuation") {
+ light.constant_att = parser.get_node_data().to_double();
+ } else if (name == "linear_attenuation") {
parser.read();
- light.linear_att=parser.get_node_data().to_double();
- } else if (name=="quadratic_attenuation") {
+ light.linear_att = parser.get_node_data().to_double();
+ } else if (name == "quadratic_attenuation") {
parser.read();
- light.quad_att=parser.get_node_data().to_double();
- } else if (name=="falloff_angle") {
+ light.quad_att = parser.get_node_data().to_double();
+ } else if (name == "falloff_angle") {
parser.read();
- light.spot_angle= parser.get_node_data().to_double();
+ light.spot_angle = parser.get_node_data().to_double();
- } else if (name=="falloff_exponent") {
+ } else if (name == "falloff_exponent") {
parser.read();
- light.spot_exp= parser.get_node_data().to_double();
+ light.spot_exp = parser.get_node_data().to_double();
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="light")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "light")
break; //end of <asset>
}
- COLLADA_PRINT("Light ID:"+id);
-
+ COLLADA_PRINT("Light ID:" + id);
}
+void Collada::_parse_curve_geometry(XMLParser &parser, String p_id, String p_name) {
-void Collada::_parse_curve_geometry(XMLParser& parser,String p_id,String p_name) {
-
-
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
//load everything into a pre dictionary
- state.curve_data_map[p_id]=CurveData();
+ state.curve_data_map[p_id] = CurveData();
CurveData &curvedata = state.curve_data_map[p_id];
- curvedata.name=p_name;
-
- COLLADA_PRINT("curve name: "+p_name);
+ curvedata.name = p_name;
+ COLLADA_PRINT("curve name: " + p_name);
String current_source;
// handles geometry node and the curve childs in this loop
@@ -990,32 +925,32 @@ void Collada::_parse_curve_geometry(XMLParser& parser,String p_id,String p_name)
return;
}
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
if (section == "source") {
- String id=parser.get_attribute_value("id");
- curvedata.sources[id]=CurveData::Source();
- current_source=id;
- COLLADA_PRINT("source data: "+id);
+ String id = parser.get_attribute_value("id");
+ curvedata.sources[id] = CurveData::Source();
+ current_source = id;
+ COLLADA_PRINT("source data: " + id);
- } else if (section=="float_array" || section=="array") {
+ } else if (section == "float_array" || section == "array") {
// create a new array and read it.
if (curvedata.sources.has(current_source)) {
curvedata.sources[current_source].array = _read_float_array(parser);
- COLLADA_PRINT("section: "+current_source+" read "+itos(curvedata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(curvedata.sources[current_source].array.size()) + " values.");
}
- } else if (section=="Name_array") {
+ } else if (section == "Name_array") {
// create a new array and read it.
if (curvedata.sources.has(current_source)) {
curvedata.sources[current_source].sarray = _read_string_array(parser);
- COLLADA_PRINT("section: "+current_source+" read "+itos(curvedata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(curvedata.sources[current_source].array.size()) + " values.");
}
} else if (section == "technique_common") {
@@ -1023,61 +958,53 @@ void Collada::_parse_curve_geometry(XMLParser& parser,String p_id,String p_name)
} else if (section == "accessor") { // child of source (below a technique tag)
if (curvedata.sources.has(current_source)) {
- curvedata.sources[current_source].stride=parser.get_attribute_value("stride").to_int();
- COLLADA_PRINT("section: "+current_source+" stride "+itos(curvedata.sources[current_source].stride));
+ curvedata.sources[current_source].stride = parser.get_attribute_value("stride").to_int();
+ COLLADA_PRINT("section: " + current_source + " stride " + itos(curvedata.sources[current_source].stride));
}
} else if (section == "control_vertices") {
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
-
- curvedata.control_vertices[semantic]=source;
+ String source = _uri_to_id(parser.get_attribute_value("source"));
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source);
+ curvedata.control_vertices[semantic] = source;
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
}
- } else if (!parser.is_empty()){
+ } else if (!parser.is_empty()) {
parser.skip_section();
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="spline")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "spline")
+ break;
}
-
-
-
}
+void Collada::_parse_mesh_geometry(XMLParser &parser, String p_id, String p_name) {
-
-void Collada::_parse_mesh_geometry(XMLParser& parser,String p_id,String p_name) {
-
-
- if (!(state.import_flags&IMPORT_FLAG_SCENE)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_SCENE)) {
+ if (!parser.is_empty())
parser.skip_section();
return;
}
//load everything into a pre dictionary
- state.mesh_data_map[p_id]=MeshData();
+ state.mesh_data_map[p_id] = MeshData();
MeshData &meshdata = state.mesh_data_map[p_id];
- meshdata.name=p_name;
-
- COLLADA_PRINT("mesh name: "+p_name);
+ meshdata.name = p_name;
+ COLLADA_PRINT("mesh name: " + p_name);
String current_source;
// handles geometry node and the mesh childs in this loop
@@ -1086,130 +1013,124 @@ void Collada::_parse_mesh_geometry(XMLParser& parser,String p_id,String p_name)
return;
}
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
-
- String section = parser.get_node_name();
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ String section = parser.get_node_name();
if (section == "source") {
- String id=parser.get_attribute_value("id");
- meshdata.sources[id]=MeshData::Source();
- current_source=id;
- COLLADA_PRINT("source data: "+id);
+ String id = parser.get_attribute_value("id");
+ meshdata.sources[id] = MeshData::Source();
+ current_source = id;
+ COLLADA_PRINT("source data: " + id);
- } else if (section=="float_array" || section=="array") {
+ } else if (section == "float_array" || section == "array") {
// create a new array and read it.
if (meshdata.sources.has(current_source)) {
meshdata.sources[current_source].array = _read_float_array(parser);
- COLLADA_PRINT("section: "+current_source+" read "+itos(meshdata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(meshdata.sources[current_source].array.size()) + " values.");
}
} else if (section == "technique_common") {
//skip it
} else if (section == "accessor") { // child of source (below a technique tag)
if (meshdata.sources.has(current_source)) {
- meshdata.sources[current_source].stride=parser.get_attribute_value("stride").to_int();
- COLLADA_PRINT("section: "+current_source+" stride "+itos(meshdata.sources[current_source].stride));
+ meshdata.sources[current_source].stride = parser.get_attribute_value("stride").to_int();
+ COLLADA_PRINT("section: " + current_source + " stride " + itos(meshdata.sources[current_source].stride));
}
} else if (section == "vertices") {
MeshData::Vertices vert;
- String id = parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
-
- vert.sources[semantic]=source;
+ String source = _uri_to_id(parser.get_attribute_value("source"));
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source);
+ vert.sources[semantic] = source;
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
}
- meshdata.vertices[id]=vert;
+ meshdata.vertices[id] = vert;
- } else if (section =="triangles" || section=="polylist" || section=="polygons") {
+ } else if (section == "triangles" || section == "polylist" || section == "polygons") {
- bool polygons=(section=="polygons");
+ bool polygons = (section == "polygons");
if (polygons) {
WARN_PRINT("Primitive type \"polygons\" is not well supported (concave shapes may fail). To ensure that the geometry is properly imported, please re-export using \"triangles\" or \"polylist\".");
}
MeshData::Primitives prim;
if (parser.has_attribute("material"))
- prim.material=parser.get_attribute_value("material");
- prim.count=parser.get_attribute_value("count").to_int();
- prim.vertex_size=0;
- int last_ref=0;
+ prim.material = parser.get_attribute_value("material");
+ prim.count = parser.get_attribute_value("count").to_int();
+ prim.vertex_size = 0;
+ int last_ref = 0;
-
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
+ String source = _uri_to_id(parser.get_attribute_value("source"));
- if (semantic=="TEXCOORD") {
+ if (semantic == "TEXCOORD") {
/*
if (parser.has_attribute("set"))// a texcoord
semantic+=parser.get_attribute_value("set");
else
semantic="TEXCOORD0";*/
- semantic="TEXCOORD"+itos(last_ref++);
+ semantic = "TEXCOORD" + itos(last_ref++);
}
int offset = parser.get_attribute_value("offset").to_int();
-
MeshData::Primitives::SourceRef sref;
- sref.source=source;
- sref.offset=offset;
- prim.sources[semantic]=sref;
- prim.vertex_size=MAX(prim.vertex_size,offset+1);
+ sref.source = source;
+ sref.offset = offset;
+ prim.sources[semantic] = sref;
+ prim.vertex_size = MAX(prim.vertex_size, offset + 1);
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source+" offset: "+itos(offset));
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source + " offset: " + itos(offset));
-
- } else if (parser.get_node_name()=="p") { //indices
+ } else if (parser.get_node_name() == "p") { //indices
Vector<float> values = _read_float_array(parser);
if (polygons) {
- prim.polygons.push_back(values.size()/prim.vertex_size);
+ prim.polygons.push_back(values.size() / prim.vertex_size);
int from = prim.indices.size();
- prim.indices.resize(from+values.size());
- for(int i=0;i<values.size();i++)
- prim.indices[from+i]=values[i];
+ prim.indices.resize(from + values.size());
+ for (int i = 0; i < values.size(); i++)
+ prim.indices[from + i] = values[i];
- } else if (prim.vertex_size>0){
- prim.indices=values;
+ } else if (prim.vertex_size > 0) {
+ prim.indices = values;
}
- COLLADA_PRINT("read "+itos(values.size())+" index values");
+ COLLADA_PRINT("read " + itos(values.size()) + " index values");
- } else if (parser.get_node_name()=="vcount") { // primitive
+ } else if (parser.get_node_name() == "vcount") { // primitive
Vector<float> values = _read_float_array(parser);
- prim.polygons=values;
- COLLADA_PRINT("read "+itos(values.size())+" polygon values");
+ prim.polygons = values;
+ COLLADA_PRINT("read " + itos(values.size()) + " polygon values");
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
-
}
meshdata.primitives.push_back(prim);
@@ -1217,76 +1138,72 @@ void Collada::_parse_mesh_geometry(XMLParser& parser,String p_id,String p_name)
} else if (parser.get_node_name() == "double_sided") {
parser.read();
- meshdata.found_double_sided=true;
- meshdata.double_sided=parser.get_node_data().to_int();
+ meshdata.found_double_sided = true;
+ meshdata.double_sided = parser.get_node_data().to_int();
} else if (parser.get_node_name() == "polygons") {
ERR_PRINT("Primitive type \"polygons\" not supported, re-export using \"polylist\" or \"triangles\".");
- } else if (!parser.is_empty()){
+ } else if (!parser.is_empty()) {
parser.skip_section();
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="mesh")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "mesh")
+ break;
}
-
-
-
}
-void Collada::_parse_skin_controller(XMLParser& parser,String p_id) {
+void Collada::_parse_skin_controller(XMLParser &parser, String p_id) {
- state.skin_controller_data_map[p_id]=SkinControllerData();
+ state.skin_controller_data_map[p_id] = SkinControllerData();
SkinControllerData &skindata = state.skin_controller_data_map[p_id];
- skindata.base=_uri_to_id(parser.get_attribute_value("source"));
+ skindata.base = _uri_to_id(parser.get_attribute_value("source"));
String current_source;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT){
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
- if (section=="bind_shape_matrix") {
+ if (section == "bind_shape_matrix") {
- skindata.bind_shape=_read_transform(parser);
+ skindata.bind_shape = _read_transform(parser);
#ifdef COLLADA_IMPORT_SCALE_SCENE
skindata.bind_shape.origin *= state.unit_scale;
#endif
- COLLADA_PRINT("skeleton bind shape transform: "+skindata.bind_shape);
-
+ COLLADA_PRINT("skeleton bind shape transform: " + skindata.bind_shape);
} else if (section == "source") {
- String id=parser.get_attribute_value("id");
- skindata.sources[id]=SkinControllerData::Source();
- current_source=id;
- COLLADA_PRINT("source data: "+id);
+ String id = parser.get_attribute_value("id");
+ skindata.sources[id] = SkinControllerData::Source();
+ current_source = id;
+ COLLADA_PRINT("source data: " + id);
- } else if (section=="float_array" || section=="array") {
+ } else if (section == "float_array" || section == "array") {
// create a new array and read it.
if (skindata.sources.has(current_source)) {
skindata.sources[current_source].array = _read_float_array(parser);
- COLLADA_PRINT("section: "+current_source+" read "+itos(skindata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(skindata.sources[current_source].array.size()) + " values.");
}
- } else if (section=="Name_array" || section=="IDREF_array") {
+ } else if (section == "Name_array" || section == "IDREF_array") {
// create a new array and read it.
- if (section=="IDREF_array")
- skindata.use_idrefs=true;
+ if (section == "IDREF_array")
+ skindata.use_idrefs = true;
if (skindata.sources.has(current_source)) {
skindata.sources[current_source].sarray = _read_string_array(parser);
- if (section=="IDREF_array") {
+ if (section == "IDREF_array") {
Vector<String> sa = skindata.sources[current_source].sarray;
- for(int i=0;i<sa.size();i++)
+ for (int i = 0; i < sa.size(); i++)
state.idref_joints.insert(sa[i]);
}
- COLLADA_PRINT("section: "+current_source+" read "+itos(skindata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(skindata.sources[current_source].array.size()) + " values.");
}
} else if (section == "technique_common") {
//skip it
@@ -1294,90 +1211,86 @@ void Collada::_parse_skin_controller(XMLParser& parser,String p_id) {
if (skindata.sources.has(current_source)) {
- int stride=1;
+ int stride = 1;
if (parser.has_attribute("stride"))
- stride=parser.get_attribute_value("stride").to_int();
+ stride = parser.get_attribute_value("stride").to_int();
- skindata.sources[current_source].stride=stride;
- COLLADA_PRINT("section: "+current_source+" stride "+itos(skindata.sources[current_source].stride));
+ skindata.sources[current_source].stride = stride;
+ COLLADA_PRINT("section: " + current_source + " stride " + itos(skindata.sources[current_source].stride));
}
} else if (section == "joints") {
SkinControllerData::Joints joint;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
-
- joint.sources[semantic]=source;
+ String source = _uri_to_id(parser.get_attribute_value("source"));
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source);
+ joint.sources[semantic] = source;
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
}
- skindata.joints=joint;
+ skindata.joints = joint;
- } else if (section=="vertex_weights") {
+ } else if (section == "vertex_weights") {
SkinControllerData::Weights weights;
- weights.count=parser.get_attribute_value("count").to_int();
+ weights.count = parser.get_attribute_value("count").to_int();
-
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
+ String source = _uri_to_id(parser.get_attribute_value("source"));
int offset = parser.get_attribute_value("offset").to_int();
SkinControllerData::Weights::SourceRef sref;
- sref.source=source;
- sref.offset=offset;
- weights.sources[semantic]=sref;
+ sref.source = source;
+ sref.offset = offset;
+ weights.sources[semantic] = sref;
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source+" offset: "+itos(offset));
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source + " offset: " + itos(offset));
- } else if (parser.get_node_name()=="v") { //indices
+ } else if (parser.get_node_name() == "v") { //indices
Vector<float> values = _read_float_array(parser);
- weights.indices=values;
- COLLADA_PRINT("read "+itos(values.size())+" index values");
+ weights.indices = values;
+ COLLADA_PRINT("read " + itos(values.size()) + " index values");
- } else if (parser.get_node_name()=="vcount") { // weightsitive
+ } else if (parser.get_node_name() == "vcount") { // weightsitive
Vector<float> values = _read_float_array(parser);
- weights.sets=values;
- COLLADA_PRINT("read "+itos(values.size())+" polygon values");
+ weights.sets = values;
+ COLLADA_PRINT("read " + itos(values.size()) + " polygon values");
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
-
}
- skindata.weights=weights;
-
+ skindata.weights = weights;
}
/*
else if (!parser.is_empty())
parser.skip_section();
*/
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="skin")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "skin")
+ break;
}
/* STORE REST MATRICES */
@@ -1395,57 +1308,53 @@ void Collada::_parse_skin_controller(XMLParser& parser,String p_id) {
SkinControllerData::Source &joint_source = skindata.sources[joint_arr];
SkinControllerData::Source &ibm_source = skindata.sources[ibm];
+ ERR_FAIL_COND(joint_source.sarray.size() != ibm_source.array.size() / 16);
-
- ERR_FAIL_COND(joint_source.sarray.size() != ibm_source.array.size()/16);
-
- for(int i=0;i<joint_source.sarray.size();i++) {
+ for (int i = 0; i < joint_source.sarray.size(); i++) {
String name = joint_source.sarray[i];
- Transform xform = _read_transform_from_array(ibm_source.array,i*16); //<- this is a mistake, it must be applied to vertices
+ Transform xform = _read_transform_from_array(ibm_source.array, i * 16); //<- this is a mistake, it must be applied to vertices
xform.affine_invert(); // inverse for rest, because it's an inverse
#ifdef COLLADA_IMPORT_SCALE_SCENE
- xform.origin*=state.unit_scale;
+ xform.origin *= state.unit_scale;
#endif
- skindata.bone_rest_map[name]=xform;
+ skindata.bone_rest_map[name] = xform;
}
-
-
}
-void Collada::_parse_morph_controller(XMLParser& parser, String p_id) {
+void Collada::_parse_morph_controller(XMLParser &parser, String p_id) {
- state.morph_controller_data_map[p_id]=MorphControllerData();
+ state.morph_controller_data_map[p_id] = MorphControllerData();
MorphControllerData &morphdata = state.morph_controller_data_map[p_id];
- print_line("morph source: "+parser.get_attribute_value("source")+" id: "+p_id);
- morphdata.mesh=_uri_to_id(parser.get_attribute_value("source"));
- print_line("morph source2: "+morphdata.mesh);
- morphdata.mode=parser.get_attribute_value("method");
- printf("JJmorph: %p\n",&morphdata);
+ print_line("morph source: " + parser.get_attribute_value("source") + " id: " + p_id);
+ morphdata.mesh = _uri_to_id(parser.get_attribute_value("source"));
+ print_line("morph source2: " + morphdata.mesh);
+ morphdata.mode = parser.get_attribute_value("method");
+ printf("JJmorph: %p\n", &morphdata);
String current_source;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT){
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
if (section == "source") {
- String id=parser.get_attribute_value("id");
- morphdata.sources[id]=MorphControllerData::Source();
- current_source=id;
- COLLADA_PRINT("source data: "+id);
+ String id = parser.get_attribute_value("id");
+ morphdata.sources[id] = MorphControllerData::Source();
+ current_source = id;
+ COLLADA_PRINT("source data: " + id);
- } else if (section=="float_array" || section=="array") {
+ } else if (section == "float_array" || section == "array") {
// create a new array and read it.
if (morphdata.sources.has(current_source)) {
morphdata.sources[current_source].array = _read_float_array(parser);
- COLLADA_PRINT("section: "+current_source+" read "+itos(morphdata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(morphdata.sources[current_source].array.size()) + " values.");
}
- } else if (section=="Name_array" || section=="IDREF_array") {
+ } else if (section == "Name_array" || section == "IDREF_array") {
// create a new array and read it.
/*
@@ -1461,7 +1370,7 @@ void Collada::_parse_morph_controller(XMLParser& parser, String p_id) {
for(int i=0;i<sa.size();i++)
state.idref_joints.insert(sa[i]);
}*/
- COLLADA_PRINT("section: "+current_source+" read "+itos(morphdata.sources[current_source].array.size())+" values.");
+ COLLADA_PRINT("section: " + current_source + " read " + itos(morphdata.sources[current_source].array.size()) + " values.");
}
} else if (section == "technique_common") {
//skip it
@@ -1469,119 +1378,106 @@ void Collada::_parse_morph_controller(XMLParser& parser, String p_id) {
if (morphdata.sources.has(current_source)) {
- int stride=1;
+ int stride = 1;
if (parser.has_attribute("stride"))
- stride=parser.get_attribute_value("stride").to_int();
+ stride = parser.get_attribute_value("stride").to_int();
- morphdata.sources[current_source].stride=stride;
- COLLADA_PRINT("section: "+current_source+" stride "+itos(morphdata.sources[current_source].stride));
+ morphdata.sources[current_source].stride = stride;
+ COLLADA_PRINT("section: " + current_source + " stride " + itos(morphdata.sources[current_source].stride));
}
} else if (section == "targets") {
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="input") {
+ if (parser.get_node_name() == "input") {
String semantic = parser.get_attribute_value("semantic");
- String source =_uri_to_id( parser.get_attribute_value("source") );
-
- morphdata.targets[semantic]=source;
+ String source = _uri_to_id(parser.get_attribute_value("source"));
- COLLADA_PRINT(section+" input semantic: "+semantic+" source: "+source);
+ morphdata.targets[semantic] = source;
+ COLLADA_PRINT(section + " input semantic: " + semantic + " source: " + source);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==section)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == section)
break;
}
-
-
}
/*
else if (!parser.is_empty())
parser.skip_section();
*/
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="morph")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "morph")
+ break;
}
-
if (morphdata.targets.has("MORPH_WEIGHT")) {
- state.morph_name_map[ morphdata.targets["MORPH_WEIGHT"] ] = p_id;
+ state.morph_name_map[morphdata.targets["MORPH_WEIGHT"]] = p_id;
}
-
}
-void Collada::_parse_controller(XMLParser& parser) {
+void Collada::_parse_controller(XMLParser &parser) {
- String id=parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
if (parser.is_empty()) {
return;
}
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT){
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
- if (section=="skin") {
- _parse_skin_controller(parser,id);
+ if (section == "skin") {
+ _parse_skin_controller(parser, id);
} else if (section == "morph") {
- _parse_morph_controller(parser,id);
+ _parse_morph_controller(parser, id);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="controller")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "controller")
+ break;
}
-
-
}
-
-Collada::Node* Collada::_parse_visual_instance_geometry(XMLParser& parser) {
+Collada::Node *Collada::_parse_visual_instance_geometry(XMLParser &parser) {
String type = parser.get_node_name();
- NodeGeometry *geom=memnew( NodeGeometry );
- geom->controller=type=="instance_controller";
+ NodeGeometry *geom = memnew(NodeGeometry);
+ geom->controller = type == "instance_controller";
geom->source = _uri_to_id(parser.get_attribute_value_safe("url"));
-
-
if (parser.is_empty()) //nothing else to parse...
return geom;
// try to find also many materials and skeletons!
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="instance_material") {
+ if (parser.get_node_name() == "instance_material") {
- String symbol=parser.get_attribute_value("symbol");
- String target=_uri_to_id(parser.get_attribute_value("target"));
+ String symbol = parser.get_attribute_value("symbol");
+ String target = _uri_to_id(parser.get_attribute_value("target"));
NodeGeometry::Material mat;
- mat.target=target;
- geom->material_map[symbol]=mat;
- COLLADA_PRINT("uses material: '"+target+"' on primitive'"+symbol+"'");
- } else if (parser.get_node_name()=="skeleton") {
+ mat.target = target;
+ geom->material_map[symbol] = mat;
+ COLLADA_PRINT("uses material: '" + target + "' on primitive'" + symbol + "'");
+ } else if (parser.get_node_name() == "skeleton") {
parser.read();
String uri = _uri_to_id(parser.get_node_data());
- if (uri!="") {
+ if (uri != "") {
geom->skeletons.push_back(uri);
}
-
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==type)
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == type)
break;
-
-
}
if (geom->controller) {
@@ -1592,223 +1488,214 @@ Collada::Node* Collada::_parse_visual_instance_geometry(XMLParser& parser) {
if (state.skin_controller_data_map.has(geom->source)) {
SkinControllerData *skin = &state.skin_controller_data_map[geom->source];
//case where skeletons reference bones with IDREF (XSI)
- ERR_FAIL_COND_V(!skin->joints.sources.has("JOINT"),geom);
+ ERR_FAIL_COND_V(!skin->joints.sources.has("JOINT"), geom);
String joint_arr = skin->joints.sources["JOINT"];
- ERR_FAIL_COND_V(!skin->sources.has(joint_arr),geom);
+ ERR_FAIL_COND_V(!skin->sources.has(joint_arr), geom);
Collada::SkinControllerData::Source &joint_source = skin->sources[joint_arr];
- geom->skeletons=joint_source.sarray; //quite crazy, but should work.
+ geom->skeletons = joint_source.sarray; //quite crazy, but should work.
}
-
}
-
}
return geom;
}
-
-Collada::Node* Collada::_parse_visual_instance_camera(XMLParser& parser) {
+Collada::Node *Collada::_parse_visual_instance_camera(XMLParser &parser) {
String type = parser.get_node_name();
- NodeCamera *cam=memnew( NodeCamera );
- cam->camera= _uri_to_id(parser.get_attribute_value_safe("url"));
+ NodeCamera *cam = memnew(NodeCamera);
+ cam->camera = _uri_to_id(parser.get_attribute_value_safe("url"));
- if (state.up_axis==Vector3::AXIS_Z) //collada weirdness
- cam->post_transform.basis.rotate(Vector3(1,0,0),-Math_PI*0.5);
+ if (state.up_axis == Vector3::AXIS_Z) //collada weirdness
+ cam->post_transform.basis.rotate(Vector3(1, 0, 0), -Math_PI * 0.5);
if (parser.is_empty()) //nothing else to parse...
return cam;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="instance_camera")
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "instance_camera")
break;
}
return cam;
}
-Collada::Node* Collada::_parse_visual_instance_light(XMLParser& parser) {
+Collada::Node *Collada::_parse_visual_instance_light(XMLParser &parser) {
String type = parser.get_node_name();
- NodeLight *cam=memnew( NodeLight );
- cam->light= _uri_to_id(parser.get_attribute_value_safe("url"));
+ NodeLight *cam = memnew(NodeLight);
+ cam->light = _uri_to_id(parser.get_attribute_value_safe("url"));
- if (state.up_axis==Vector3::AXIS_Z) //collada weirdness
- cam->post_transform.basis.rotate(Vector3(1,0,0),-Math_PI*0.5);
+ if (state.up_axis == Vector3::AXIS_Z) //collada weirdness
+ cam->post_transform.basis.rotate(Vector3(1, 0, 0), -Math_PI * 0.5);
if (parser.is_empty()) //nothing else to parse...
return cam;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="instance_light")
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "instance_light")
break;
}
return cam;
}
-
-Collada::Node* Collada::_parse_visual_node_instance_data(XMLParser& parser) {
+Collada::Node *Collada::_parse_visual_node_instance_data(XMLParser &parser) {
String instance_type = parser.get_node_name();
-
- if (instance_type=="instance_geometry" || instance_type=="instance_controller") {
+ if (instance_type == "instance_geometry" || instance_type == "instance_controller") {
return _parse_visual_instance_geometry(parser);
- } else if (instance_type=="instance_camera") {
+ } else if (instance_type == "instance_camera") {
return _parse_visual_instance_camera(parser);
- } else if (instance_type=="instance_light") {
+ } else if (instance_type == "instance_light") {
return _parse_visual_instance_light(parser);
}
-
if (parser.is_empty()) //nothing else to parse...
return NULL;
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()==instance_type)
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == instance_type)
break;
}
return NULL;
}
-Collada::Node* Collada::_parse_visual_scene_node(XMLParser& parser) {
+Collada::Node *Collada::_parse_visual_scene_node(XMLParser &parser) {
String name;
String id = parser.get_attribute_value_safe("id");
- bool found_name=false;
+ bool found_name = false;
- if (id=="") {
+ if (id == "") {
- id="%NODEID%"+itos(Math::rand());
+ id = "%NODEID%" + itos(Math::rand());
} else {
- found_name=true;
+ found_name = true;
}
Vector<Node::XForm> xform_list;
- Vector<Node*> children;
-
- String empty_draw_type="";
+ Vector<Node *> children;
+
+ String empty_draw_type = "";
- Node *node=NULL;
+ Node *node = NULL;
- name=parser.has_attribute("name")?parser.get_attribute_value_safe("name"):parser.get_attribute_value_safe("id");
- if (name=="") {
+ name = parser.has_attribute("name") ? parser.get_attribute_value_safe("name") : parser.get_attribute_value_safe("id");
+ if (name == "") {
- name=id;
+ name = id;
} else {
- found_name=true;
+ found_name = true;
}
- if ((parser.has_attribute("type") && parser.get_attribute_value("type")=="JOINT") || state.idref_joints.has(name)) {
+ if ((parser.has_attribute("type") && parser.get_attribute_value("type") == "JOINT") || state.idref_joints.has(name)) {
// handle a bone
- NodeJoint *joint = memnew( NodeJoint );
+ NodeJoint *joint = memnew(NodeJoint);
- if ( parser.has_attribute("sid") ) { //bones may not have sid
- joint->sid=parser.get_attribute_value("sid");
+ if (parser.has_attribute("sid")) { //bones may not have sid
+ joint->sid = parser.get_attribute_value("sid");
//state.bone_map[joint->sid]=joint;
} else if (state.idref_joints.has(name)) {
- joint->sid=name; //kind of a cheat but..
+ joint->sid = name; //kind of a cheat but..
} else if (parser.has_attribute("name")) {
- joint->sid=parser.get_attribute_value_safe("name");
+ joint->sid = parser.get_attribute_value_safe("name");
}
-
- if (joint->sid!="") {
- state.sid_to_node_map[joint->sid]=id;
+ if (joint->sid != "") {
+ state.sid_to_node_map[joint->sid] = id;
}
- node=joint;
-
-
+ node = joint;
}
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
- if (section=="translate") {
+ if (section == "translate") {
Node::XForm xf;
if (parser.has_attribute("sid")) {
- xf.id=parser.get_attribute_value("sid");
+ xf.id = parser.get_attribute_value("sid");
}
- xf.op=Node::XForm::OP_TRANSLATE;
+ xf.op = Node::XForm::OP_TRANSLATE;
Vector<float> xlt = _read_float_array(parser);
- xf.data=xlt;
+ xf.data = xlt;
xform_list.push_back(xf);
- } else if (section=="rotate") {
+ } else if (section == "rotate") {
Node::XForm xf;
if (parser.has_attribute("sid")) {
- xf.id=parser.get_attribute_value("sid");
+ xf.id = parser.get_attribute_value("sid");
}
- xf.op=Node::XForm::OP_ROTATE;
+ xf.op = Node::XForm::OP_ROTATE;
Vector<float> rot = _read_float_array(parser);
- xf.data=rot;
+ xf.data = rot;
xform_list.push_back(xf);
- } else if (section=="scale") {
+ } else if (section == "scale") {
Node::XForm xf;
if (parser.has_attribute("sid")) {
- xf.id=parser.get_attribute_value("sid");
+ xf.id = parser.get_attribute_value("sid");
}
- xf.op=Node::XForm::OP_SCALE;
+ xf.op = Node::XForm::OP_SCALE;
Vector<float> scale = _read_float_array(parser);
- xf.data=scale;
+ xf.data = scale;
xform_list.push_back(xf);
- } else if (section=="matrix") {
+ } else if (section == "matrix") {
Node::XForm xf;
if (parser.has_attribute("sid")) {
- xf.id=parser.get_attribute_value("sid");
+ xf.id = parser.get_attribute_value("sid");
}
- xf.op=Node::XForm::OP_MATRIX;
+ xf.op = Node::XForm::OP_MATRIX;
Vector<float> matrix = _read_float_array(parser);
- xf.data=matrix;
+ xf.data = matrix;
String mtx;
- for(int i=0;i<matrix.size();i++)
- mtx+=" "+rtos(matrix[i]);
+ for (int i = 0; i < matrix.size(); i++)
+ mtx += " " + rtos(matrix[i]);
xform_list.push_back(xf);
- } else if (section=="visibility") {
- Node::XForm xf;
- if (parser.has_attribute("sid")) {
- xf.id=parser.get_attribute_value("sid");
- }
- xf.op=Node::XForm::OP_VISIBILITY;
+ } else if (section == "visibility") {
+ Node::XForm xf;
+ if (parser.has_attribute("sid")) {
+ xf.id = parser.get_attribute_value("sid");
+ }
+ xf.op = Node::XForm::OP_VISIBILITY;
- Vector<float> visible = _read_float_array(parser);
+ Vector<float> visible = _read_float_array(parser);
- xf.data=visible;
+ xf.data = visible;
- xform_list.push_back(xf);
+ xform_list.push_back(xf);
- } else if (section=="empty_draw_type") {
+ } else if (section == "empty_draw_type") {
empty_draw_type = _read_empty_draw_type(parser);
- } else if (section == "technique" || section=="extra") {
+ } else if (section == "technique" || section == "extra") {
- } else if (section!="node") {
+ } else if (section != "node") {
//usually what defines the type of node
//print_line(" dont know what to do with "+section);
if (section.begins_with("instance_")) {
@@ -1820,149 +1707,137 @@ Collada::Node* Collada::_parse_visual_scene_node(XMLParser& parser) {
} else {
ERR_PRINT("Multiple instance_* not supported.");
}
-
}
- } else if (section=="node") {
+ } else if (section == "node") {
/* Found a child node!! what to do..*/
Node *child = _parse_visual_scene_node(parser);
children.push_back(child);
-
-
-
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="node")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "node")
+ break;
}
if (!node) {
- node = memnew( Node ); //generic node, nothing of relevance found
+ node = memnew(Node); //generic node, nothing of relevance found
}
- node->noname=!found_name;
- node->xform_list=xform_list;
- node->children=children;
- for(int i=0;i<children.size();i++) {
- node->children[i]->parent=node;
+ node->noname = !found_name;
+ node->xform_list = xform_list;
+ node->children = children;
+ for (int i = 0; i < children.size(); i++) {
+ node->children[i]->parent = node;
}
- node->name=name;
- node->id=id;
- node->empty_draw_type=empty_draw_type;
+ node->name = name;
+ node->id = id;
+ node->empty_draw_type = empty_draw_type;
- if (node->children.size()==1) {
+ if (node->children.size() == 1) {
if (node->children[0]->noname && !node->noname) {
- node->children[0]->name=node->name;
- node->name=node->name+"-base";
+ node->children[0]->name = node->name;
+ node->name = node->name + "-base";
}
}
-
-
node->default_transform = node->compute_transform(*this);
- state.scene_map[id]=node;
-
+ state.scene_map[id] = node;
return node;
}
-void Collada::_parse_visual_scene(XMLParser& parser) {
+void Collada::_parse_visual_scene(XMLParser &parser) {
- String id=parser.get_attribute_value("id");
+ String id = parser.get_attribute_value("id");
if (parser.is_empty()) {
return;
}
- state.visual_scene_map[id]=VisualScene();
+ state.visual_scene_map[id] = VisualScene();
VisualScene &vscene = state.visual_scene_map[id];
if (parser.has_attribute("name"))
- vscene.name=parser.get_attribute_value("name");
+ vscene.name = parser.get_attribute_value("name");
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- String section = parser.get_node_name();
+ String section = parser.get_node_name();
- if (section=="node") {
+ if (section == "node") {
vscene.root_nodes.push_back(_parse_visual_scene_node(parser));
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="visual_scene")
- break;
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "visual_scene")
+ break;
}
-
- COLLADA_PRINT("Scene ID:"+id);
-
-
+ COLLADA_PRINT("Scene ID:" + id);
}
-void Collada::_parse_animation(XMLParser& parser) {
+void Collada::_parse_animation(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_ANIMATION)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_ANIMATION)) {
+ if (!parser.is_empty())
parser.skip_section();
-
return;
}
- Map<String,Vector<float> > float_sources;
- Map<String,Vector<String> > string_sources;
- Map<String,int > source_strides;
- Map<String, Map<String,String> > samplers;
- Map<String,Vector<String> > source_param_names;
- Map<String,Vector<String> > source_param_types;
+ Map<String, Vector<float> > float_sources;
+ Map<String, Vector<String> > string_sources;
+ Map<String, int> source_strides;
+ Map<String, Map<String, String> > samplers;
+ Map<String, Vector<String> > source_param_names;
+ Map<String, Vector<String> > source_param_types;
- String id="";
+ String id = "";
if (parser.has_attribute("id"))
- id=parser.get_attribute_value("id");
+ id = parser.get_attribute_value("id");
String current_source;
String current_sampler;
Vector<String> channel_sources;
Vector<String> channel_targets;
- while(parser.read()==OK) {
-
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="source") {
+ if (name == "source") {
- current_source=parser.get_attribute_value("id");
- source_param_names[current_source]=Vector<String>();
- source_param_types[current_source]=Vector<String>();
+ current_source = parser.get_attribute_value("id");
+ source_param_names[current_source] = Vector<String>();
+ source_param_types[current_source] = Vector<String>();
- } else if (name=="float_array") {
+ } else if (name == "float_array") {
- if (current_source!="") {
- float_sources[current_source]=_read_float_array(parser);
+ if (current_source != "") {
+ float_sources[current_source] = _read_float_array(parser);
}
- } else if (name=="Name_array") {
+ } else if (name == "Name_array") {
- if (current_source!="") {
- string_sources[current_source]=_read_string_array(parser);
+ if (current_source != "") {
+ string_sources[current_source] = _read_string_array(parser);
}
- } else if (name=="accessor") {
+ } else if (name == "accessor") {
- if (current_source!="" && parser.has_attribute("stride")) {
- source_strides[current_source]=parser.get_attribute_value("stride").to_int();
+ if (current_source != "" && parser.has_attribute("stride")) {
+ source_strides[current_source] = parser.get_attribute_value("stride").to_int();
}
- } else if (name=="sampler") {
+ } else if (name == "sampler") {
- current_sampler=parser.get_attribute_value("id");
- samplers[current_sampler]=Map<String,String>();
- } else if (name=="param") {
+ current_sampler = parser.get_attribute_value("id");
+ samplers[current_sampler] = Map<String, String>();
+ } else if (name == "param") {
if (parser.has_attribute("name"))
source_param_names[current_source].push_back(parser.get_attribute_value("name"));
@@ -1974,294 +1849,276 @@ void Collada::_parse_animation(XMLParser& parser) {
else
source_param_types[current_source].push_back("");
- } else if (name=="input") {
+ } else if (name == "input") {
- if (current_sampler!="") {
+ if (current_sampler != "") {
- samplers[current_sampler][parser.get_attribute_value("semantic")]=parser.get_attribute_value("source");
+ samplers[current_sampler][parser.get_attribute_value("semantic")] = parser.get_attribute_value("source");
}
- } else if (name=="channel") {
+ } else if (name == "channel") {
channel_sources.push_back(parser.get_attribute_value("source"));
channel_targets.push_back(parser.get_attribute_value("target"));
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="animation")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "animation")
break; //end of <asset>
-
-
}
+ for (int i = 0; i < channel_sources.size(); i++) {
- for(int i=0;i<channel_sources.size();i++) {
-
- String source=_uri_to_id(channel_sources[i]);
- String target=channel_targets[i];
+ String source = _uri_to_id(channel_sources[i]);
+ String target = channel_targets[i];
if (!samplers.has(source)) {
- print_line("channel lacks source: "+source);
+ print_line("channel lacks source: " + source);
}
ERR_CONTINUE(!samplers.has(source));
- Map<String,String>& sampler=samplers[source];
+ Map<String, String> &sampler = samplers[source];
ERR_CONTINUE(!sampler.has("INPUT")); //no input semantic? wtf?
- String input_id=_uri_to_id(sampler["INPUT"]);
- COLLADA_PRINT("input id is "+input_id);
+ String input_id = _uri_to_id(sampler["INPUT"]);
+ COLLADA_PRINT("input id is " + input_id);
ERR_CONTINUE(!float_sources.has(input_id));
ERR_CONTINUE(!sampler.has("OUTPUT"));
- String output_id=_uri_to_id(sampler["OUTPUT"]);
+ String output_id = _uri_to_id(sampler["OUTPUT"]);
ERR_CONTINUE(!float_sources.has(output_id));
ERR_CONTINUE(!source_param_names.has(output_id));
Vector<String> &names = source_param_names[output_id];
- for(int l=0;l<names.size();l++) {
+ for (int l = 0; l < names.size(); l++) {
String name = names[l];
- Vector<float> &time_keys=float_sources[input_id];
+ Vector<float> &time_keys = float_sources[input_id];
int key_count = time_keys.size();
AnimationTrack track; //begin crating track
- track.id=id;
+ track.id = id;
track.keys.resize(key_count);
- for(int j=0;j<key_count;j++) {
- track.keys[j].time=time_keys[j];
- state.animation_length = MAX(state.animation_length,time_keys[j] );
+ for (int j = 0; j < key_count; j++) {
+ track.keys[j].time = time_keys[j];
+ state.animation_length = MAX(state.animation_length, time_keys[j]);
}
//now read actual values
- int stride=1;
+ int stride = 1;
if (source_strides.has(output_id))
- stride=source_strides[output_id];
- int output_len=stride / names.size();
+ stride = source_strides[output_id];
+ int output_len = stride / names.size();
- ERR_CONTINUE(output_len==0);
+ ERR_CONTINUE(output_len == 0);
ERR_CONTINUE(!float_sources.has(output_id));
Vector<float> &output = float_sources[output_id];
ERR_EXPLAIN("Wrong number of keys in output");
- ERR_CONTINUE( (output.size()/stride) != key_count );
+ ERR_CONTINUE((output.size() / stride) != key_count);
- for(int j=0;j<key_count;j++) {
+ for (int j = 0; j < key_count; j++) {
track.keys[j].data.resize(output_len);
- for(int k=0;k<output_len;k++)
- track.keys[j].data[k]=output[l+j*stride+k]; //super weird but should work
+ for (int k = 0; k < output_len; k++)
+ track.keys[j].data[k] = output[l + j * stride + k]; //super weird but should work
}
- if(sampler.has("INTERPOLATION")) {
+ if (sampler.has("INTERPOLATION")) {
- String interp_id=_uri_to_id(sampler["INTERPOLATION"]);
+ String interp_id = _uri_to_id(sampler["INTERPOLATION"]);
ERR_CONTINUE(!string_sources.has(interp_id));
- Vector<String> &interps=string_sources[interp_id];
- ERR_CONTINUE(interps.size()!=key_count);
+ Vector<String> &interps = string_sources[interp_id];
+ ERR_CONTINUE(interps.size() != key_count);
- for(int j=0;j<key_count;j++) {
- if (interps[j]=="BEZIER")
- track.keys[j].interp_type=AnimationTrack::INTERP_BEZIER;
+ for (int j = 0; j < key_count; j++) {
+ if (interps[j] == "BEZIER")
+ track.keys[j].interp_type = AnimationTrack::INTERP_BEZIER;
else
- track.keys[j].interp_type=AnimationTrack::INTERP_LINEAR;
+ track.keys[j].interp_type = AnimationTrack::INTERP_LINEAR;
}
}
if (sampler.has("IN_TANGENT") && sampler.has("OUT_TANGENT")) {
//bezier control points..
- String intangent_id=_uri_to_id(sampler["IN_TANGENT"]);
+ String intangent_id = _uri_to_id(sampler["IN_TANGENT"]);
ERR_CONTINUE(!float_sources.has(intangent_id));
- Vector<float> &intangents=float_sources[intangent_id];
-
+ Vector<float> &intangents = float_sources[intangent_id];
+ ERR_CONTINUE(intangents.size() != key_count * 2 * names.size());
-
- ERR_CONTINUE(intangents.size()!=key_count*2*names.size());
-
- String outangent_id=_uri_to_id(sampler["OUT_TANGENT"]);
+ String outangent_id = _uri_to_id(sampler["OUT_TANGENT"]);
ERR_CONTINUE(!float_sources.has(outangent_id));
- Vector<float> &outangents=float_sources[outangent_id];
- ERR_CONTINUE(outangents.size()!=key_count*2*names.size());
+ Vector<float> &outangents = float_sources[outangent_id];
+ ERR_CONTINUE(outangents.size() != key_count * 2 * names.size());
- for(int j=0;j<key_count;j++) {
- track.keys[j].in_tangent=Vector2( intangents[j*2*names.size()+0+l*2],intangents[j*2*names.size()+1+l*2] );
- track.keys[j].out_tangent=Vector2( outangents[j*2*names.size()+0+l*2],outangents[j*2*names.size()+1+l*2] );
+ for (int j = 0; j < key_count; j++) {
+ track.keys[j].in_tangent = Vector2(intangents[j * 2 * names.size() + 0 + l * 2], intangents[j * 2 * names.size() + 1 + l * 2]);
+ track.keys[j].out_tangent = Vector2(outangents[j * 2 * names.size() + 0 + l * 2], outangents[j * 2 * names.size() + 1 + l * 2]);
}
}
- if (target.find("/")!=-1) { //transform component
- track.target=target.get_slicec('/',0);
- track.param=target.get_slicec('/',1);
- if (track.param.find(".")!=-1)
- track.component=track.param.get_slice(".",1).to_upper();
- track.param=track.param.get_slice(".",0);
- if (names.size()>1 && track.component=="") {
+ if (target.find("/") != -1) { //transform component
+ track.target = target.get_slicec('/', 0);
+ track.param = target.get_slicec('/', 1);
+ if (track.param.find(".") != -1)
+ track.component = track.param.get_slice(".", 1).to_upper();
+ track.param = track.param.get_slice(".", 0);
+ if (names.size() > 1 && track.component == "") {
//this is a guess because the collada spec is ambiguous here...
//i suppose if you have many names (outputs) you can't use a component and i should abide to that.
- track.component=name;
-
+ track.component = name;
}
} else {
- track.target=target;
+ track.target = target;
}
- print_line("TARGET: "+track.target);
+ print_line("TARGET: " + track.target);
state.animation_tracks.push_back(track);
if (!state.referenced_tracks.has(target))
- state.referenced_tracks[target]=Vector<int>();
+ state.referenced_tracks[target] = Vector<int>();
- state.referenced_tracks[target].push_back(state.animation_tracks.size()-1);
+ state.referenced_tracks[target].push_back(state.animation_tracks.size() - 1);
- if (id!="") {
+ if (id != "") {
if (!state.by_id_tracks.has(id))
- state.by_id_tracks[id]=Vector<int>();
+ state.by_id_tracks[id] = Vector<int>();
- state.by_id_tracks[id].push_back(state.animation_tracks.size()-1);
+ state.by_id_tracks[id].push_back(state.animation_tracks.size() - 1);
}
- COLLADA_PRINT("loaded animation with "+itos(key_count)+" keys");
+ COLLADA_PRINT("loaded animation with " + itos(key_count) + " keys");
}
-
}
}
-void Collada::_parse_animation_clip(XMLParser& parser) {
+void Collada::_parse_animation_clip(XMLParser &parser) {
- if (!(state.import_flags&IMPORT_FLAG_ANIMATION)) {
- if (!parser.is_empty())
+ if (!(state.import_flags & IMPORT_FLAG_ANIMATION)) {
+ if (!parser.is_empty())
parser.skip_section();
-
return;
}
-
AnimationClip clip;
if (parser.has_attribute("name"))
- clip.name=parser.get_attribute_value("name");
+ clip.name = parser.get_attribute_value("name");
else if (parser.has_attribute("id"))
- clip.name=parser.get_attribute_value("id");
+ clip.name = parser.get_attribute_value("id");
if (parser.has_attribute("start"))
- clip.begin=parser.get_attribute_value("start").to_double();
+ clip.begin = parser.get_attribute_value("start").to_double();
if (parser.has_attribute("end"))
- clip.end=parser.get_attribute_value("end").to_double();
-
+ clip.end = parser.get_attribute_value("end").to_double();
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
-
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="instance_animation") {
+ if (name == "instance_animation") {
String url = _uri_to_id(parser.get_attribute_value("url"));
clip.tracks.push_back(url);
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="animation_clip")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "animation_clip")
break; //end of <asset>
-
}
state.animation_clips.push_back(clip);
- print_line("found anim clip: "+clip.name);
-
+ print_line("found anim clip: " + clip.name);
}
-void Collada::_parse_scene(XMLParser& parser) {
+void Collada::_parse_scene(XMLParser &parser) {
if (parser.is_empty()) {
return;
}
- while(parser.read()==OK) {
-
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- if (name=="instance_visual_scene") {
-
- state.root_visual_scene=_uri_to_id(parser.get_attribute_value("url"));
- print_line("***ROOT VISUAL SCENE: "+state.root_visual_scene);
- } else if (name=="instance_physics_scene") {
+ if (name == "instance_visual_scene") {
- state.root_physics_scene=_uri_to_id(parser.get_attribute_value("url"));
+ state.root_visual_scene = _uri_to_id(parser.get_attribute_value("url"));
+ print_line("***ROOT VISUAL SCENE: " + state.root_visual_scene);
+ } else if (name == "instance_physics_scene") {
+ state.root_physics_scene = _uri_to_id(parser.get_attribute_value("url"));
}
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="scene")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "scene")
break; //end of <asset>
}
}
-void Collada::_parse_library(XMLParser& parser) {
-
+void Collada::_parse_library(XMLParser &parser) {
if (parser.is_empty()) {
return;
}
- while(parser.read()==OK) {
-
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser.get_node_name();
- COLLADA_PRINT("library name is: "+name);
- if (name=="image") {
+ COLLADA_PRINT("library name is: " + name);
+ if (name == "image") {
_parse_image(parser);
- } else if (name=="material") {
+ } else if (name == "material") {
_parse_material(parser);
- } else if (name=="effect") {
+ } else if (name == "effect") {
_parse_effect(parser);
- } else if (name=="camera") {
+ } else if (name == "camera") {
_parse_camera(parser);
- } else if (name=="light") {
+ } else if (name == "light") {
_parse_light(parser);
- } else if (name=="geometry") {
+ } else if (name == "geometry") {
String id = parser.get_attribute_value("id");
String name = parser.get_attribute_value_safe("name");
- while(parser.read()==OK) {
+ while (parser.read() == OK) {
- if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser.get_node_name()=="mesh") {
- state.mesh_name_map[id]=(name!="")?name:id;
- _parse_mesh_geometry(parser,id,name);
- } else if (parser.get_node_name()=="spline") {
- state.mesh_name_map[id]=(name!="")?name:id;
- _parse_curve_geometry(parser,id,name);
+ if (parser.get_node_name() == "mesh") {
+ state.mesh_name_map[id] = (name != "") ? name : id;
+ _parse_mesh_geometry(parser, id, name);
+ } else if (parser.get_node_name() == "spline") {
+ state.mesh_name_map[id] = (name != "") ? name : id;
+ _parse_curve_geometry(parser, id, name);
} else if (!parser.is_empty())
parser.skip_section();
- } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name()=="geometry")
+ } else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name() == "geometry")
break;
}
- } else if (name=="controller") {
+ } else if (name == "controller") {
_parse_controller(parser);
- } else if (name=="animation") {
+ } else if (name == "animation") {
_parse_animation(parser);
- } else if (name=="animation_clip") {
+ } else if (name == "animation_clip") {
_parse_animation_clip(parser);
- } else if (name=="visual_scene") {
+ } else if (name == "visual_scene") {
COLLADA_PRINT("visual scene");
_parse_visual_scene(parser);
@@ -2270,158 +2127,144 @@ void Collada::_parse_library(XMLParser& parser) {
} else if (parser.get_node_type() == XMLParser::NODE_ELEMENT_END && parser.get_node_name().begins_with("library_"))
break; //end of <asset>
-
-
}
-
}
void Collada::_joint_set_owner(Collada::Node *p_node, NodeSkeleton *p_owner) {
- if (p_node->type==Node::TYPE_JOINT) {
+ if (p_node->type == Node::TYPE_JOINT) {
- NodeJoint *nj = static_cast<NodeJoint*>(p_node);
- nj->owner=p_owner;
+ NodeJoint *nj = static_cast<NodeJoint *>(p_node);
+ nj->owner = p_owner;
- for(int i=0;i<nj->children.size();i++) {
+ for (int i = 0; i < nj->children.size(); i++) {
- _joint_set_owner(nj->children[i],p_owner);
+ _joint_set_owner(nj->children[i], p_owner);
}
}
}
-void Collada::_create_skeletons(Collada::Node **p_node,NodeSkeleton *p_skeleton) {
-
+void Collada::_create_skeletons(Collada::Node **p_node, NodeSkeleton *p_skeleton) {
Node *node = *p_node;
- if (node->type==Node::TYPE_JOINT) {
+ if (node->type == Node::TYPE_JOINT) {
if (!p_skeleton) {
// ohohohoohoo it's a joint node, time to work!
- NodeSkeleton *sk = memnew( NodeSkeleton );
- *p_node=sk;
+ NodeSkeleton *sk = memnew(NodeSkeleton);
+ *p_node = sk;
sk->children.push_back(node);
- sk->parent=node->parent;
- node->parent=sk;
- p_skeleton=sk;
+ sk->parent = node->parent;
+ node->parent = sk;
+ p_skeleton = sk;
}
- NodeJoint *nj = static_cast<NodeJoint*>(node);
- nj->owner=p_skeleton;
+ NodeJoint *nj = static_cast<NodeJoint *>(node);
+ nj->owner = p_skeleton;
} else {
- p_skeleton=NULL;
+ p_skeleton = NULL;
}
-
- for(int i=0;i<node->children.size();i++) {
- _create_skeletons(&node->children[i],p_skeleton);
+ for (int i = 0; i < node->children.size(); i++) {
+ _create_skeletons(&node->children[i], p_skeleton);
}
-
}
-bool Collada::_remove_node(Node *p_parent,Node *p_node) {
+bool Collada::_remove_node(Node *p_parent, Node *p_node) {
- for(int i=0;i<p_parent->children.size();i++) {
+ for (int i = 0; i < p_parent->children.size(); i++) {
- if (p_parent->children[i]==p_node) {
+ if (p_parent->children[i] == p_node) {
p_parent->children.remove(i);
return true;
}
- if (_remove_node(p_parent->children[i],p_node))
+ if (_remove_node(p_parent->children[i], p_node))
return true;
}
return false;
}
-void Collada::_remove_node(VisualScene *p_vscene,Node *p_node) {
+void Collada::_remove_node(VisualScene *p_vscene, Node *p_node) {
- for(int i=0;i<p_vscene->root_nodes.size();i++) {
- if (p_vscene->root_nodes[i]==p_node) {
+ for (int i = 0; i < p_vscene->root_nodes.size(); i++) {
+ if (p_vscene->root_nodes[i] == p_node) {
p_vscene->root_nodes.remove(i);
return;
}
- if (_remove_node(p_vscene->root_nodes[i],p_node))
+ if (_remove_node(p_vscene->root_nodes[i], p_node))
return;
}
ERR_PRINT("ERROR: Not found node to remove?");
-
}
+void Collada::_merge_skeletons(VisualScene *p_vscene, Node *p_node) {
-void Collada::_merge_skeletons(VisualScene *p_vscene,Node *p_node) {
-
- if (p_node->type==Node::TYPE_GEOMETRY) {
+ if (p_node->type == Node::TYPE_GEOMETRY) {
- NodeGeometry *gnode = static_cast<NodeGeometry*>(p_node);
+ NodeGeometry *gnode = static_cast<NodeGeometry *>(p_node);
if (gnode->controller) {
// recount skeletons used
- Set<NodeSkeleton*> skeletons;
+ Set<NodeSkeleton *> skeletons;
- for(int i=0;i<gnode->skeletons.size();i++) {
+ for (int i = 0; i < gnode->skeletons.size(); i++) {
String nodeid = gnode->skeletons[i];
- ERR_CONTINUE( !state.scene_map.has( nodeid )); //weird, it should have it...
+ ERR_CONTINUE(!state.scene_map.has(nodeid)); //weird, it should have it...
-
- NodeJoint *nj = SAFE_CAST<NodeJoint*>(state.scene_map[nodeid]);
+ NodeJoint *nj = SAFE_CAST<NodeJoint *>(state.scene_map[nodeid]);
if (!nj->owner) {
- print_line("no owner for: "+String(nodeid));
+ print_line("no owner for: " + String(nodeid));
}
- ERR_CONTINUE( !nj->owner ); //weird, node should have a skeleton owner
+ ERR_CONTINUE(!nj->owner); //weird, node should have a skeleton owner
skeletons.insert(nj->owner);
}
- if (skeletons.size()>1) {
+ if (skeletons.size() > 1) {
//do the merger!!
- Set<NodeSkeleton*>::Element *E=skeletons.front();
+ Set<NodeSkeleton *>::Element *E = skeletons.front();
NodeSkeleton *base = E->get();
- for(E=E->next();E;E=E->next() ) {
+ for (E = E->next(); E; E = E->next()) {
NodeSkeleton *merged = E->get();
- _remove_node(p_vscene,merged);
- for(int i=0;i<merged->children.size();i++) {
-
- _joint_set_owner(merged->children[i],base);
- base->children.push_back( merged->children[i] );
- merged->children[i]->parent=base;
-
+ _remove_node(p_vscene, merged);
+ for (int i = 0; i < merged->children.size(); i++) {
+ _joint_set_owner(merged->children[i], base);
+ base->children.push_back(merged->children[i]);
+ merged->children[i]->parent = base;
}
merged->children.clear(); //take children from it
- memdelete( merged );
+ memdelete(merged);
}
-
}
}
}
- for(int i=0;i<p_node->children.size();i++) {
- _merge_skeletons(p_vscene,p_node->children[i]);
+ for (int i = 0; i < p_node->children.size(); i++) {
+ _merge_skeletons(p_vscene, p_node->children[i]);
}
-
}
-
void Collada::_merge_skeletons2(VisualScene *p_vscene) {
- for (Map<String,SkinControllerData>::Element *E=state.skin_controller_data_map.front();E;E=E->next()) {
+ for (Map<String, SkinControllerData>::Element *E = state.skin_controller_data_map.front(); E; E = E->next()) {
- SkinControllerData &cd=E->get();
+ SkinControllerData &cd = E->get();
- NodeSkeleton *skeleton=NULL;
+ NodeSkeleton *skeleton = NULL;
- for (Map<String,Transform>::Element *F=cd.bone_rest_map.front();F;F=F->next()) {
+ for (Map<String, Transform>::Element *F = cd.bone_rest_map.front(); F; F = F->next()) {
String name;
@@ -2432,84 +2275,79 @@ void Collada::_merge_skeletons2(VisualScene *p_vscene) {
name = state.sid_to_node_map[F->key()];
if (!state.scene_map.has(name)) {
- print_line("no foundie node for: "+name);
+ print_line("no foundie node for: " + name);
}
- ERR_CONTINUE( !state.scene_map.has(name) );
+ ERR_CONTINUE(!state.scene_map.has(name));
- Node *node=state.scene_map[name];
- ERR_CONTINUE( node->type!=Node::TYPE_JOINT );
- if (node->type!=Node::TYPE_JOINT)
+ Node *node = state.scene_map[name];
+ ERR_CONTINUE(node->type != Node::TYPE_JOINT);
+ if (node->type != Node::TYPE_JOINT)
continue;
- NodeSkeleton *sk=NULL;
+ NodeSkeleton *sk = NULL;
- while(node && !sk) {
+ while (node && !sk) {
- if (node->type==Node::TYPE_SKELETON) {
- sk=static_cast<NodeSkeleton*>(node);
+ if (node->type == Node::TYPE_SKELETON) {
+ sk = static_cast<NodeSkeleton *>(node);
}
- node=node->parent;
+ node = node->parent;
}
- ERR_CONTINUE( !sk );
+ ERR_CONTINUE(!sk);
if (!sk)
continue; //bleh
if (!skeleton) {
- skeleton=sk;
+ skeleton = sk;
continue;
}
- if (skeleton!=sk) {
+ if (skeleton != sk) {
//whoa.. wtf, merge.
print_line("MERGED BONES!!");
//NodeSkeleton *merged = E->get();
- _remove_node(p_vscene,sk);
- for(int i=0;i<sk->children.size();i++) {
-
- _joint_set_owner(sk->children[i],skeleton);
- skeleton->children.push_back( sk->children[i] );
- sk->children[i]->parent=skeleton;
-
+ _remove_node(p_vscene, sk);
+ for (int i = 0; i < sk->children.size(); i++) {
+ _joint_set_owner(sk->children[i], skeleton);
+ skeleton->children.push_back(sk->children[i]);
+ sk->children[i]->parent = skeleton;
}
sk->children.clear(); //take children from it
- memdelete( sk );
+ memdelete(sk);
}
}
}
-
-
-
}
-bool Collada::_optimize_skeletons(VisualScene *p_vscene,Node *p_node) {
+bool Collada::_optimize_skeletons(VisualScene *p_vscene, Node *p_node) {
- Node *node=p_node;
+ Node *node = p_node;
- if (node->type==Node::TYPE_SKELETON && node->parent && node->parent->type==Node::TYPE_NODE && node->parent->children.size()==1) {
+ if (node->type == Node::TYPE_SKELETON && node->parent && node->parent->type == Node::TYPE_NODE && node->parent->children.size() == 1) {
//replace parent by this...
Node *parent = node->parent;
//i wonder if this is allright.. i think it is since created skeleton (first joint) is already animated by bone..
- node->id=parent->id;
- node->name=parent->name;
- node->xform_list=parent->xform_list;
- node->default_transform=parent->default_transform;
+ node->id = parent->id;
+ node->name = parent->name;
+ node->xform_list = parent->xform_list;
+ node->default_transform = parent->default_transform;
- state.scene_map[node->id]=node;
- node->parent=parent->parent;
+ state.scene_map[node->id] = node;
+ node->parent = parent->parent;
if (parent->parent) {
Node *gp = parent->parent;
- bool found=false;
- for(int i=0;i<gp->children.size();i++) {
+ bool found = false;
+ for (int i = 0; i < gp->children.size(); i++) {
- if (gp->children[i]==parent) {
- gp->children[i]=node;
- found=true;
+ if (gp->children[i] == parent) {
+ gp->children[i] = node;
+ found = true;
break;
}
}
@@ -2518,21 +2356,20 @@ bool Collada::_optimize_skeletons(VisualScene *p_vscene,Node *p_node) {
}
} else {
- bool found=false;
+ bool found = false;
- for(int i=0;i<p_vscene->root_nodes.size();i++) {
+ for (int i = 0; i < p_vscene->root_nodes.size(); i++) {
- if (p_vscene->root_nodes[i]==parent) {
+ if (p_vscene->root_nodes[i] == parent) {
- p_vscene->root_nodes[i]=node;
- found=true;
+ p_vscene->root_nodes[i] = node;
+ found = true;
break;
}
}
if (!found) {
ERR_PRINT("BUG");
}
-
}
parent->children.clear();
@@ -2540,26 +2377,24 @@ bool Collada::_optimize_skeletons(VisualScene *p_vscene,Node *p_node) {
return true;
}
- for(int i=0;i<node->children.size();i++) {
+ for (int i = 0; i < node->children.size(); i++) {
- if (_optimize_skeletons(p_vscene,node->children[i]))
+ if (_optimize_skeletons(p_vscene, node->children[i]))
return false; //stop processing, go up
}
return false;
-
}
-
-bool Collada::_move_geometry_to_skeletons(VisualScene *p_vscene,Node *p_node,List<Node*> *p_mgeom) {
+bool Collada::_move_geometry_to_skeletons(VisualScene *p_vscene, Node *p_node, List<Node *> *p_mgeom) {
// bind shape matrix escala los huesos y los hace gigantes, asi la matriz despues achica
// al modelo?
// solucion: aplicarle la bind shape matrix a los VERTICES, y si el objeto viene con escala, se la dejo me parece!
- if (p_node->type==Node::TYPE_GEOMETRY) {
+ if (p_node->type == Node::TYPE_GEOMETRY) {
- NodeGeometry *ng = static_cast<NodeGeometry*>(p_node);
+ NodeGeometry *ng = static_cast<NodeGeometry *>(p_node);
if (ng->ignore_anim)
return false; //already made child of skeleton and processeg
@@ -2567,59 +2402,57 @@ bool Collada::_move_geometry_to_skeletons(VisualScene *p_vscene,Node *p_node,Lis
String nodeid = ng->skeletons[0];
- ERR_FAIL_COND_V( !state.scene_map.has( nodeid ), false); //weird, it should have it...
- NodeJoint *nj = SAFE_CAST<NodeJoint*>(state.scene_map[nodeid]);
- ERR_FAIL_COND_V(!nj,false);
+ ERR_FAIL_COND_V(!state.scene_map.has(nodeid), false); //weird, it should have it...
+ NodeJoint *nj = SAFE_CAST<NodeJoint *>(state.scene_map[nodeid]);
+ ERR_FAIL_COND_V(!nj, false);
if (!nj->owner) {
- print_line("Has no owner: "+nj->name);
+ print_line("Has no owner: " + nj->name);
}
- ERR_FAIL_COND_V( !nj->owner,false ); //weird, node should have a skeleton owner
+ ERR_FAIL_COND_V(!nj->owner, false); //weird, node should have a skeleton owner
NodeSkeleton *sk = nj->owner;
- Node *p =sk->parent;
- bool node_is_parent_of_skeleton=false;
+ Node *p = sk->parent;
+ bool node_is_parent_of_skeleton = false;
while (p) {
- if (p==p_node) {
- node_is_parent_of_skeleton=true;
+ if (p == p_node) {
+ node_is_parent_of_skeleton = true;
break;
}
- p=p->parent; // try again
+ p = p->parent; // try again
}
- ERR_FAIL_COND_V( node_is_parent_of_skeleton, false);
+ ERR_FAIL_COND_V(node_is_parent_of_skeleton, false);
//this should be correct
- ERR_FAIL_COND_V( !state.skin_controller_data_map.has(ng->source), false);
- SkinControllerData &skin=state.skin_controller_data_map[ng->source];
+ ERR_FAIL_COND_V(!state.skin_controller_data_map.has(ng->source), false);
+ SkinControllerData &skin = state.skin_controller_data_map[ng->source];
Transform skel_inv = sk->get_global_transform().affine_inverse();
- p_node->default_transform = skel_inv * (skin.bind_shape /* p_node->get_global_transform()*/); // i honestly have no idea what to do with a previous model xform.. most exporters ignore it
+ p_node->default_transform = skel_inv * (skin.bind_shape /* p_node->get_global_transform()*/); // i honestly have no idea what to do with a previous model xform.. most exporters ignore it
//make rests relative to the skeleton (they seem to be always relative to world)
- for(Map<String,Transform>::Element *E=skin.bone_rest_map.front();E;E=E->next()) {
+ for (Map<String, Transform>::Element *E = skin.bone_rest_map.front(); E; E = E->next()) {
E->get() = skel_inv * E->get(); //make the bone rest local to the skeleton
- state.bone_rest_map[E->key()]=E->get(); // make it remember where the bone is globally, now that it's relative
+ state.bone_rest_map[E->key()] = E->get(); // make it remember where the bone is globally, now that it's relative
}
//but most exporters seem to work only if i do this..
//p_node->default_transform = p_node->get_global_transform();
-
-
//p_node->default_transform=Transform(); //this seems to be correct, because bind shape makes the object local to the skeleton
- p_node->ignore_anim=true; // collada may animate this later, if it does, then this is not supported (redo your original asset and don't animate the base mesh)
- p_node->parent=sk;
+ p_node->ignore_anim = true; // collada may animate this later, if it does, then this is not supported (redo your original asset and don't animate the base mesh)
+ p_node->parent = sk;
//sk->children.push_back(0,p_node); //avoid INFINIT loop
p_mgeom->push_back(p_node);
return true;
}
}
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
- if (_move_geometry_to_skeletons(p_vscene,p_node->children[i],p_mgeom)) {
+ if (_move_geometry_to_skeletons(p_vscene, p_node->children[i], p_mgeom)) {
p_node->children.remove(i);
i--;
}
@@ -2628,139 +2461,129 @@ bool Collada::_move_geometry_to_skeletons(VisualScene *p_vscene,Node *p_node,Lis
return false;
}
-void Collada::_find_morph_nodes(VisualScene *p_vscene,Node *p_node) {
+void Collada::_find_morph_nodes(VisualScene *p_vscene, Node *p_node) {
- if (p_node->type==Node::TYPE_GEOMETRY) {
+ if (p_node->type == Node::TYPE_GEOMETRY) {
- NodeGeometry *nj = static_cast<NodeGeometry*>(p_node);
+ NodeGeometry *nj = static_cast<NodeGeometry *>(p_node);
if (nj->controller) {
String base = nj->source;
- while(base!="" && !state.mesh_data_map.has(base)) {
+ while (base != "" && !state.mesh_data_map.has(base)) {
if (state.skin_controller_data_map.has(base)) {
SkinControllerData &sk = state.skin_controller_data_map[base];
- base=sk.base;
+ base = sk.base;
} else if (state.morph_controller_data_map.has(base)) {
- state.morph_ownership_map[base]=nj->id;
+ state.morph_ownership_map[base] = nj->id;
break;
} else {
ERR_EXPLAIN("Invalid scene");
ERR_FAIL();
}
}
-
}
}
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
- _find_morph_nodes(p_vscene,p_node->children[i]);
+ _find_morph_nodes(p_vscene, p_node->children[i]);
}
-
}
void Collada::_optimize() {
-
- for(Map<String,VisualScene>::Element *E=state.visual_scene_map.front();E;E=E->next()) {
+ for (Map<String, VisualScene>::Element *E = state.visual_scene_map.front(); E; E = E->next()) {
VisualScene &vs = E->get();
- for(int i=0;i<vs.root_nodes.size();i++) {
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
_create_skeletons(&vs.root_nodes[i]);
-
}
#if 1
- for(int i=0;i<vs.root_nodes.size();i++) {
- _merge_skeletons(&vs,vs.root_nodes[i]);
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
+ _merge_skeletons(&vs, vs.root_nodes[i]);
}
_merge_skeletons2(&vs);
-
- for(int i=0;i<vs.root_nodes.size();i++) {
- _optimize_skeletons(&vs,vs.root_nodes[i]);
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
+ _optimize_skeletons(&vs, vs.root_nodes[i]);
}
- for(int i=0;i<vs.root_nodes.size();i++) {
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
- List<Node*> mgeom;
- if (_move_geometry_to_skeletons(&vs,vs.root_nodes[i],&mgeom)) {
+ List<Node *> mgeom;
+ if (_move_geometry_to_skeletons(&vs, vs.root_nodes[i], &mgeom)) {
vs.root_nodes.remove(i);
i--;
}
- while(!mgeom.empty()) {
+ while (!mgeom.empty()) {
- Node * n= mgeom.front()->get();
+ Node *n = mgeom.front()->get();
n->parent->children.push_back(n);
mgeom.pop_front();
}
-
}
#endif
- for(int i=0;i<vs.root_nodes.size();i++) {
- _find_morph_nodes(&vs,vs.root_nodes[i]);
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
+ _find_morph_nodes(&vs, vs.root_nodes[i]);
}
-
}
}
-
int Collada::get_uv_channel(String p_name) {
if (!channel_map.has(p_name)) {
- ERR_FAIL_COND_V(channel_map.size()==2,0);
+ ERR_FAIL_COND_V(channel_map.size() == 2, 0);
- channel_map[p_name]=channel_map.size();
+ channel_map[p_name] = channel_map.size();
}
return channel_map[p_name];
}
-Error Collada::load(const String& p_path, int p_flags) {
+Error Collada::load(const String &p_path, int p_flags) {
- Ref<XMLParser> parserr = memnew( XMLParser );
+ Ref<XMLParser> parserr = memnew(XMLParser);
XMLParser &parser = *parserr.ptr();
Error err = parser.open(p_path);
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
state.local_path = GlobalConfig::get_singleton()->localize_path(p_path);
- state.import_flags=p_flags;
+ state.import_flags = p_flags;
/* Skip headers */
- err=OK;
- while((err=parser.read())==OK) {
+ err = OK;
+ while ((err = parser.read()) == OK) {
if (parser.get_node_type() == XMLParser::NODE_ELEMENT) {
if (parser.get_node_name() == "COLLADA") {
break;
} else if (!parser.is_empty())
- parser.skip_section();// unknown section, likely headers
+ parser.skip_section(); // unknown section, likely headers
}
}
- ERR_FAIL_COND_V(err!=OK, ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(err != OK, ERR_FILE_CORRUPT);
/* Start loading Collada */
{
//version
String version = parser.get_attribute_value("version");
- state.version.major=version.get_slice(".",0).to_int();
- state.version.minor=version.get_slice(".",1).to_int();
- state.version.rev=version.get_slice(".",2).to_int();
- COLLADA_PRINT("Collada VERSION: "+version);
+ state.version.major = version.get_slice(".", 0).to_int();
+ state.version.minor = version.get_slice(".", 1).to_int();
+ state.version.rev = version.get_slice(".", 2).to_int();
+ COLLADA_PRINT("Collada VERSION: " + version);
}
-
-
- while((err=parser.read())==OK) {
+ while ((err = parser.read()) == OK) {
/* Read all the main sections.. */
@@ -2769,33 +2592,27 @@ Error Collada::load(const String& p_path, int p_flags) {
String section = parser.get_node_name();
- COLLADA_PRINT("section: "+section);
+ COLLADA_PRINT("section: " + section);
- if (section=="asset") {
+ if (section == "asset") {
_parse_asset(parser);
} else if (section.begins_with("library_")) {
_parse_library(parser);
- } else if (section=="scene") {
+ } else if (section == "scene") {
_parse_scene(parser);
} else if (!parser.is_empty()) {
parser.skip_section(); // unknown section, likely headers
}
-
}
_optimize();
return OK;
}
-
-
-
Collada::Collada() {
-
-
}
#endif
diff --git a/editor/collada/collada.h b/editor/collada/collada.h
index 2de2d22935..23b3aef670 100644
--- a/editor/collada/collada.h
+++ b/editor/collada/collada.h
@@ -31,21 +31,18 @@
#ifndef COLLADA_H
#define COLLADA_H
-
-#include "scene/resources/material.h"
#include "global_config.h"
#include "io/xml_parser.h"
#include "map.h"
+#include "scene/resources/material.h"
class Collada {
public:
-
enum ImportFlags {
- IMPORT_FLAG_SCENE=1,
- IMPORT_FLAG_ANIMATION=2
+ IMPORT_FLAG_SCENE = 1,
+ IMPORT_FLAG_ANIMATION = 2
};
-
struct Image {
String path;
@@ -57,7 +54,6 @@ public:
String instance_effect;
};
-
struct Effect {
String name;
@@ -68,23 +64,23 @@ public:
int uv_idx;
String texture;
Color color;
- Channel() { uv_idx=0; }
+ Channel() { uv_idx = 0; }
};
- Channel diffuse,specular,emission,bump;
+ Channel diffuse, specular, emission, bump;
float shininess;
bool found_double_sided;
bool double_sided;
bool unshaded;
- String get_texture_path(const String& p_source,Collada& state) const;
+ String get_texture_path(const String &p_source, Collada &state) const;
Effect() {
- diffuse.color=Color(1,1,1,1);
- double_sided=true;
- found_double_sided=false;
- shininess=40;
- unshaded=false;
+ diffuse.color = Color(1, 1, 1, 1);
+ double_sided = true;
+ found_double_sided = false;
+ shininess = 40;
+ unshaded = false;
}
};
@@ -114,12 +110,12 @@ public:
CameraData() {
- mode=MODE_PERSPECTIVE;
- perspective.y_fov=0;
- perspective.x_fov=0;
- aspect=1;
- z_near=0.1;
- z_far=100;
+ mode = MODE_PERSPECTIVE;
+ perspective.y_fov = 0;
+ perspective.x_fov = 0;
+ aspect = 1;
+ z_near = 0.1;
+ z_far = 100;
}
};
@@ -145,37 +141,34 @@ public:
LightData() {
- mode=MODE_AMBIENT;
- color=Color(1,1,1,1);
- constant_att=0;
- linear_att=0;
- quad_att=0;
+ mode = MODE_AMBIENT;
+ color = Color(1, 1, 1, 1);
+ constant_att = 0;
+ linear_att = 0;
+ quad_att = 0;
- spot_angle=45;
- spot_exp=1;
+ spot_angle = 45;
+ spot_exp = 1;
}
};
-
struct MeshData {
-
String name;
struct Source {
Vector<float> array;
int stride;
-
};
- Map<String,Source> sources;
+ Map<String, Source> sources;
struct Vertices {
- Map<String,String> sources;
+ Map<String, String> sources;
};
- Map<String,Vertices> vertices;
+ Map<String, Vertices> vertices;
struct Primitives {
@@ -183,12 +176,10 @@ public:
String source;
int offset;
-
-
};
String material;
- Map<String,SourceRef> sources;
+ Map<String, SourceRef> sources;
Vector<float> polygons;
Vector<float> indices;
int count;
@@ -200,12 +191,14 @@ public:
bool found_double_sided;
bool double_sided;
- MeshData() { found_double_sided=false; double_sided=true; }
+ MeshData() {
+ found_double_sided = false;
+ double_sided = true;
+ }
};
struct CurveData {
-
String name;
bool closed;
@@ -216,16 +209,14 @@ public:
int stride;
};
- Map<String,Source> sources;
-
+ Map<String, Source> sources;
- Map<String,String> control_vertices;
+ Map<String, String> control_vertices;
CurveData() {
- closed=false;
+ closed = false;
}
-
};
struct SkinControllerData {
@@ -240,15 +231,15 @@ public:
Vector<float> array;
int stride;
Source() {
- stride=1;
+ stride = 1;
}
};
- Map<String,Source> sources;
+ Map<String, Source> sources;
struct Joints {
- Map<String,String> sources;
+ Map<String, String> sources;
} joints;
struct Weights {
@@ -257,23 +248,20 @@ public:
String source;
int offset;
-
-
};
String material;
- Map<String,SourceRef> sources;
+ Map<String, SourceRef> sources;
Vector<float> sets;
Vector<float> indices;
int count;
} weights;
- Map<String,Transform> bone_rest_map;
+ Map<String, Transform> bone_rest_map;
- SkinControllerData() { use_idrefs=false; }
+ SkinControllerData() { use_idrefs = false; }
};
-
struct MorphControllerData {
String mesh;
@@ -284,21 +272,20 @@ public:
int stride;
Vector<String> sarray; //maybe for names
Vector<float> array;
- Source() { stride=1; }
+ Source() { stride = 1; }
};
- Map<String,Source> sources;
+ Map<String, Source> sources;
- Map<String,String> targets;
- MorphControllerData() { }
+ Map<String, String> targets;
+ MorphControllerData() {}
};
-
struct Vertex {
int idx;
Vector3 vertex;
- Vector3 normal;
+ Vector3 normal;
Vector3 uv;
Vector3 uv2;
Plane tangent;
@@ -307,8 +294,7 @@ public:
struct Weight {
int bone_idx;
float weight;
- bool operator<(const Weight w) const { return weight>w.weight; } //heaviest first
-
+ bool operator<(const Weight w) const { return weight > w.weight; } //heaviest first
};
Vector<Weight> weights;
@@ -316,61 +302,61 @@ public:
void fix_weights() {
weights.sort();
- if (weights.size()>4) {
+ if (weights.size() > 4) {
//cap to 4 and make weights add up 1
weights.resize(4);
- float total=0;
- for(int i=0;i<4;i++)
- total+=weights[i].weight;
+ float total = 0;
+ for (int i = 0; i < 4; i++)
+ total += weights[i].weight;
if (total)
- for(int i=0;i<4;i++)
- weights[i].weight/=total;
-
+ for (int i = 0; i < 4; i++)
+ weights[i].weight /= total;
}
}
void fix_unit_scale(Collada &state);
- bool operator<(const Vertex& p_vert) const {
+ bool operator<(const Vertex &p_vert) const {
- if (uid==p_vert.uid) {
- if (vertex==p_vert.vertex) {
- if(normal==p_vert.normal) {
- if(uv==p_vert.uv) {
- if(uv2==p_vert.uv2) {
+ if (uid == p_vert.uid) {
+ if (vertex == p_vert.vertex) {
+ if (normal == p_vert.normal) {
+ if (uv == p_vert.uv) {
+ if (uv2 == p_vert.uv2) {
if (!weights.empty() || !p_vert.weights.empty()) {
- if (weights.size()==p_vert.weights.size()) {
+ if (weights.size() == p_vert.weights.size()) {
- for(int i=0;i<weights.size();i++) {
- if (weights[i].bone_idx!=p_vert.weights[i].bone_idx)
- return weights[i].bone_idx<p_vert.weights[i].bone_idx;
+ for (int i = 0; i < weights.size(); i++) {
+ if (weights[i].bone_idx != p_vert.weights[i].bone_idx)
+ return weights[i].bone_idx < p_vert.weights[i].bone_idx;
- if (weights[i].weight!=p_vert.weights[i].weight)
- return weights[i].weight<p_vert.weights[i].weight;
+ if (weights[i].weight != p_vert.weights[i].weight)
+ return weights[i].weight < p_vert.weights[i].weight;
}
- } else {
+ } else {
return weights.size() < p_vert.weights.size();
}
-
}
- return (color<p_vert.color);
+ return (color < p_vert.color);
} else
- return (uv2<p_vert.uv2);
+ return (uv2 < p_vert.uv2);
} else
- return (uv<p_vert.uv);
+ return (uv < p_vert.uv);
} else
- return (normal<p_vert.normal);
+ return (normal < p_vert.normal);
} else
- return vertex<p_vert.vertex;
+ return vertex < p_vert.vertex;
} else
return uid < p_vert.uid;
-
}
- Vertex() { uid=0; idx=0; }
+ Vertex() {
+ uid = 0;
+ idx = 0;
+ }
};
struct Node {
@@ -384,7 +370,6 @@ public:
TYPE_GEOMETRY
};
-
struct XForm {
enum Op {
@@ -409,9 +394,9 @@ public:
Vector<XForm> xform_list;
Transform default_transform;
Transform post_transform;
- Vector<Node*> children;
+ Vector<Node *> children;
- Node* parent;
+ Node *parent;
Transform compute_transform(Collada &state) const;
Transform get_global_transform() const;
@@ -419,26 +404,33 @@ public:
bool ignore_anim;
-
- Node() {noname=false; type=TYPE_NODE; parent=NULL; ignore_anim=false; }
- virtual ~Node() { for(int i=0;i<children.size();i++) memdelete( children[i] ); };
-
+ Node() {
+ noname = false;
+ type = TYPE_NODE;
+ parent = NULL;
+ ignore_anim = false;
+ }
+ virtual ~Node() {
+ for (int i = 0; i < children.size(); i++)
+ memdelete(children[i]);
+ };
};
struct NodeSkeleton : public Node {
-
- NodeSkeleton() { type=TYPE_SKELETON; }
+ NodeSkeleton() { type = TYPE_SKELETON; }
};
struct NodeJoint : public Node {
NodeSkeleton *owner;
String sid;
- NodeJoint() { type=TYPE_JOINT; owner=NULL; }
+ NodeJoint() {
+ type = TYPE_JOINT;
+ owner = NULL;
+ }
};
-
struct NodeGeometry : public Node {
bool controller;
@@ -448,36 +440,37 @@ public:
String target;
};
- Map<String,Material> material_map;
+ Map<String, Material> material_map;
Vector<String> skeletons;
- NodeGeometry() { type=TYPE_GEOMETRY; }
+ NodeGeometry() { type = TYPE_GEOMETRY; }
};
struct NodeCamera : public Node {
String camera;
- NodeCamera() { type=TYPE_CAMERA; }
+ NodeCamera() { type = TYPE_CAMERA; }
};
struct NodeLight : public Node {
String light;
- NodeLight() { type=TYPE_LIGHT; }
+ NodeLight() { type = TYPE_LIGHT; }
};
-
struct VisualScene {
String name;
- Vector<Node*> root_nodes;
+ Vector<Node *> root_nodes;
- ~VisualScene() { for(int i=0;i<root_nodes.size();i++) memdelete( root_nodes[i] ); }
+ ~VisualScene() {
+ for (int i = 0; i < root_nodes.size(); i++)
+ memdelete(root_nodes[i]);
+ }
};
-
struct AnimationClip {
String name;
@@ -485,7 +478,10 @@ public:
float end;
Vector<String> tracks;
- AnimationClip() { begin=0; end=1; }
+ AnimationClip() {
+ begin = 0;
+ end = 1;
+ }
};
struct AnimationTrack {
@@ -514,26 +510,22 @@ public:
Point2 out_tangent;
InterpolationType interp_type;
- Key() { interp_type=INTERP_LINEAR; }
+ Key() { interp_type = INTERP_LINEAR; }
};
-
Vector<float> get_value_at_time(float p_time);
Vector<Key> keys;
- AnimationTrack() { property=false; }
+ AnimationTrack() { property = false; }
};
-
/****************/
/* IMPORT STATE */
/****************/
-
struct State {
-
int import_flags;
float unit_scale;
@@ -542,38 +534,38 @@ public:
struct Version {
- int major,minor,rev;
+ int major, minor, rev;
- bool operator<(const Version& p_ver) const { return (major==p_ver.major)?((minor==p_ver.minor)?(rev<p_ver.rev):minor<p_ver.minor):major<p_ver.major; }
- Version(int p_major=0,int p_minor=0,int p_rev=0) { major=p_major; minor=p_minor; rev=p_rev; }
+ bool operator<(const Version &p_ver) const { return (major == p_ver.major) ? ((minor == p_ver.minor) ? (rev < p_ver.rev) : minor < p_ver.minor) : major < p_ver.major; }
+ Version(int p_major = 0, int p_minor = 0, int p_rev = 0) {
+ major = p_major;
+ minor = p_minor;
+ rev = p_rev;
+ }
} version;
+ Map<String, CameraData> camera_data_map;
+ Map<String, MeshData> mesh_data_map;
+ Map<String, LightData> light_data_map;
+ Map<String, CurveData> curve_data_map;
- Map<String,CameraData> camera_data_map;
- Map<String,MeshData> mesh_data_map;
- Map<String,LightData> light_data_map;
- Map<String,CurveData> curve_data_map;
-
-
- Map<String,String> mesh_name_map;
- Map<String,String> morph_name_map;
- Map<String,String> morph_ownership_map;
- Map<String,SkinControllerData> skin_controller_data_map;
- Map<String,MorphControllerData> morph_controller_data_map;
+ Map<String, String> mesh_name_map;
+ Map<String, String> morph_name_map;
+ Map<String, String> morph_ownership_map;
+ Map<String, SkinControllerData> skin_controller_data_map;
+ Map<String, MorphControllerData> morph_controller_data_map;
+ Map<String, Image> image_map;
+ Map<String, Material> material_map;
+ Map<String, Effect> effect_map;
-
- Map<String,Image > image_map;
- Map<String,Material> material_map;
- Map<String,Effect> effect_map;
-
- Map<String,VisualScene> visual_scene_map;
- Map<String,Node*> scene_map;
+ Map<String, VisualScene> visual_scene_map;
+ Map<String, Node *> scene_map;
Set<String> idref_joints;
- Map<String,String> sid_to_node_map;
+ Map<String, String> sid_to_node_map;
//Map<String,NodeJoint*> bone_map;
- Map<String,Transform> bone_rest_map;
+ Map<String, Transform> bone_rest_map;
String local_path;
String root_visual_scene;
@@ -581,81 +573,78 @@ public:
Vector<AnimationClip> animation_clips;
Vector<AnimationTrack> animation_tracks;
- Map<String,Vector<int> > referenced_tracks;
- Map<String,Vector<int> > by_id_tracks;
+ Map<String, Vector<int> > referenced_tracks;
+ Map<String, Vector<int> > by_id_tracks;
float animation_length;
- State() { unit_scale=1.0; up_axis=Vector3::AXIS_Y; import_flags=0; animation_length=0; }
+ State() {
+ unit_scale = 1.0;
+ up_axis = Vector3::AXIS_Y;
+ import_flags = 0;
+ animation_length = 0;
+ }
} state;
-
- Error load(const String& p_path, int p_flags=0);
+ Error load(const String &p_path, int p_flags = 0);
Collada();
- Transform fix_transform(const Transform& p_transform);
+ Transform fix_transform(const Transform &p_transform);
Transform get_root_transform() const;
int get_uv_channel(String p_name);
private: // private stuff
-
- Map<String,int> channel_map;
-
- void _parse_asset(XMLParser& parser);
- void _parse_image(XMLParser& parser);
- void _parse_material(XMLParser& parser);
- void _parse_effect_material(XMLParser& parser,Effect &effect,String &id);
- void _parse_effect(XMLParser& parser);
- void _parse_camera(XMLParser& parser);
- void _parse_light(XMLParser& parser);
- void _parse_animation_clip(XMLParser& parser);
-
- void _parse_mesh_geometry(XMLParser& parser,String p_id,String p_name);
- void _parse_curve_geometry(XMLParser& parser,String p_id,String p_name);
-
- void _parse_skin_controller(XMLParser& parser,String p_id);
- void _parse_morph_controller(XMLParser& parser, String id);
- void _parse_controller(XMLParser& parser);
-
- Node* _parse_visual_instance_geometry(XMLParser& parser);
- Node* _parse_visual_instance_camera(XMLParser& parser);
- Node* _parse_visual_instance_light(XMLParser& parser);
-
- Node* _parse_visual_node_instance_data(XMLParser& parser);
- Node* _parse_visual_scene_node(XMLParser& parser);
- void _parse_visual_scene(XMLParser& parser);
-
- void _parse_animation(XMLParser& parser);
- void _parse_scene(XMLParser& parser);
- void _parse_library(XMLParser& parser);
-
-
- Variant _parse_param(XMLParser& parser);
- Vector<float> _read_float_array(XMLParser& parser);
- Vector<String> _read_string_array(XMLParser& parser);
- Transform _read_transform(XMLParser& parser);
- String _read_empty_draw_type(XMLParser& parser);
+ Map<String, int> channel_map;
+
+ void _parse_asset(XMLParser &parser);
+ void _parse_image(XMLParser &parser);
+ void _parse_material(XMLParser &parser);
+ void _parse_effect_material(XMLParser &parser, Effect &effect, String &id);
+ void _parse_effect(XMLParser &parser);
+ void _parse_camera(XMLParser &parser);
+ void _parse_light(XMLParser &parser);
+ void _parse_animation_clip(XMLParser &parser);
+
+ void _parse_mesh_geometry(XMLParser &parser, String p_id, String p_name);
+ void _parse_curve_geometry(XMLParser &parser, String p_id, String p_name);
+
+ void _parse_skin_controller(XMLParser &parser, String p_id);
+ void _parse_morph_controller(XMLParser &parser, String id);
+ void _parse_controller(XMLParser &parser);
+
+ Node *_parse_visual_instance_geometry(XMLParser &parser);
+ Node *_parse_visual_instance_camera(XMLParser &parser);
+ Node *_parse_visual_instance_light(XMLParser &parser);
+
+ Node *_parse_visual_node_instance_data(XMLParser &parser);
+ Node *_parse_visual_scene_node(XMLParser &parser);
+ void _parse_visual_scene(XMLParser &parser);
+
+ void _parse_animation(XMLParser &parser);
+ void _parse_scene(XMLParser &parser);
+ void _parse_library(XMLParser &parser);
+
+ Variant _parse_param(XMLParser &parser);
+ Vector<float> _read_float_array(XMLParser &parser);
+ Vector<String> _read_string_array(XMLParser &parser);
+ Transform _read_transform(XMLParser &parser);
+ String _read_empty_draw_type(XMLParser &parser);
void _joint_set_owner(Collada::Node *p_node, NodeSkeleton *p_owner);
- void _create_skeletons(Collada::Node **p_node, NodeSkeleton *p_skeleton=NULL);
- void _find_morph_nodes(VisualScene *p_vscene,Node *p_node);
- bool _remove_node(Node *p_parent,Node *p_node);
- void _remove_node(VisualScene *p_vscene,Node *p_node);
+ void _create_skeletons(Collada::Node **p_node, NodeSkeleton *p_skeleton = NULL);
+ void _find_morph_nodes(VisualScene *p_vscene, Node *p_node);
+ bool _remove_node(Node *p_parent, Node *p_node);
+ void _remove_node(VisualScene *p_vscene, Node *p_node);
void _merge_skeletons2(VisualScene *p_vscene);
- void _merge_skeletons(VisualScene *p_vscene,Node *p_node);
- bool _optimize_skeletons(VisualScene *p_vscene,Node *p_node);
-
-
- bool _move_geometry_to_skeletons(VisualScene *p_vscene,Node *p_node,List<Node*> *p_mgeom);
-
+ void _merge_skeletons(VisualScene *p_vscene, Node *p_node);
+ bool _optimize_skeletons(VisualScene *p_vscene, Node *p_node);
+ bool _move_geometry_to_skeletons(VisualScene *p_vscene, Node *p_node, List<Node *> *p_mgeom);
void _optimize();
-
-
};
#endif // COLLADA_H
diff --git a/editor/connections_dialog.cpp b/editor/connections_dialog.cpp
index 91ba419c97..03f77dbe94 100644
--- a/editor/connections_dialog.cpp
+++ b/editor/connections_dialog.cpp
@@ -28,41 +28,40 @@
/*************************************************************************/
#include "connections_dialog.h"
-#include "scene/gui/label.h"
-#include "print_string.h"
-#include "editor_settings.h"
#include "editor_node.h"
+#include "editor_settings.h"
#include "plugins/script_editor_plugin.h"
+#include "print_string.h"
+#include "scene/gui/label.h"
class ConnectDialogBinds : public Object {
- GDCLASS( ConnectDialogBinds, Object );
-public:
+ GDCLASS(ConnectDialogBinds, Object);
+public:
Vector<Variant> params;
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
- String name=p_name;
+ String name = p_name;
if (name.begins_with("bind/")) {
- int which = name.get_slice("/",1).to_int()-1;
- ERR_FAIL_INDEX_V(which,params.size(),false);
- params[which]=p_value;
+ int which = name.get_slice("/", 1).to_int() - 1;
+ ERR_FAIL_INDEX_V(which, params.size(), false);
+ params[which] = p_value;
} else
return false;
return true;
}
+ bool _get(const StringName &p_name, Variant &r_ret) const {
- bool _get(const StringName& p_name,Variant &r_ret) const {
-
- String name=p_name;
+ String name = p_name;
if (name.begins_with("bind/")) {
- int which = name.get_slice("/",1).to_int()-1;
- ERR_FAIL_INDEX_V(which,params.size(),false);
+ int which = name.get_slice("/", 1).to_int() - 1;
+ ERR_FAIL_INDEX_V(which, params.size(), false);
r_ret = params[which];
} else
return false;
@@ -72,8 +71,8 @@ public:
void _get_property_list(List<PropertyInfo> *p_list) const {
- for(int i=0;i<params.size();i++) {
- p_list->push_back( PropertyInfo( params[i].get_type(), "bind/"+itos(i+1)) );
+ for (int i = 0; i < params.size(); i++) {
+ p_list->push_back(PropertyInfo(params[i].get_type(), "bind/" + itos(i + 1)));
}
}
@@ -83,20 +82,18 @@ public:
}
ConnectDialogBinds() {
-
-
}
};
void ConnectDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
bind_editor->edit(cdbinds);
}
}
@@ -104,14 +101,13 @@ void ConnectDialog::_notification(int p_what) {
void ConnectDialog::_tree_node_selected() {
//dst_method_list->get_popup()->clear();
- Node *current=tree->get_selected();
+ Node *current = tree->get_selected();
if (!current) {
make_callback->hide();
return;
}
-
if (current->get_script().is_null())
make_callback->hide();
else
@@ -144,8 +140,6 @@ void ConnectDialog::_tree_node_selected() {
}
#endif
dst_path->set_text(node->get_path_to(current));
-
-
}
void ConnectDialog::_dst_method_list_selected(int p_idx) {
@@ -155,13 +149,12 @@ void ConnectDialog::_dst_method_list_selected(int p_idx) {
void ConnectDialog::edit(Node *p_node) {
- node=p_node;
+ node = p_node;
//dst_method_list->get_popup()->clear();
-
tree->set_selected(NULL);
- tree->set_marked(node,true);
+ tree->set_marked(node, true);
dst_path->set_text("");
dst_method->set_text("");
deferred->set_pressed(false);
@@ -172,13 +165,13 @@ void ConnectDialog::edit(Node *p_node) {
void ConnectDialog::ok_pressed() {
- if (dst_method->get_text()=="") {
+ if (dst_method->get_text() == "") {
error->set_text(TTR("Method in target Node must be specified!"));
error->popup_centered_minsize();
return;
}
- Node* target = tree->get_selected();
+ Node *target = tree->get_selected();
if (target->get_script().is_null()) {
if (!target->has_method(dst_method->get_text())) {
error->set_text(TTR("Target method not found! Specify a valid method or attach a script to target Node."));
@@ -188,20 +181,17 @@ void ConnectDialog::ok_pressed() {
}
emit_signal("connected");
hide();
-
}
void ConnectDialog::_cancel_pressed() {
hide();
}
-
NodePath ConnectDialog::get_dst_path() const {
return dst_path->get_text();
}
-
bool ConnectDialog::get_deferred() const {
return deferred->is_pressed();
@@ -214,16 +204,14 @@ bool ConnectDialog::get_oneshot() const {
StringName ConnectDialog::get_dst_method() const {
- String txt=dst_method->get_text();
- if (txt.find("(")!=-1)
- txt=txt.left( txt.find("(")).strip_edges();
+ String txt = dst_method->get_text();
+ if (txt.find("(") != -1)
+ txt = txt.left(txt.find("(")).strip_edges();
return txt;
}
-
Vector<Variant> ConnectDialog::get_binds() const {
-
return cdbinds->params;
}
@@ -235,9 +223,9 @@ void ConnectDialog::_add_bind() {
Variant value;
- switch(vt) {
+ switch (vt) {
- case Variant::BOOL: value = false ; break;
+ case Variant::BOOL: value = false; break;
case Variant::INT: value = 0; break;
case Variant::REAL: value = 0.0; break;
case Variant::STRING: value = ""; break;
@@ -255,32 +243,30 @@ void ConnectDialog::_add_bind() {
default: { ERR_FAIL(); } break;
}
- ERR_FAIL_COND(value.get_type()==Variant::NIL);
+ ERR_FAIL_COND(value.get_type() == Variant::NIL);
cdbinds->params.push_back(value);
cdbinds->notify_changed();
-
}
void ConnectDialog::_remove_bind() {
String st = bind_editor->get_selected_path();
- if (st=="")
+ if (st == "")
return;
- int idx = st.get_slice("/",1).to_int()-1;
+ int idx = st.get_slice("/", 1).to_int() - 1;
- ERR_FAIL_INDEX(idx,cdbinds->params.size());
+ ERR_FAIL_INDEX(idx, cdbinds->params.size());
cdbinds->params.remove(idx);
cdbinds->notify_changed();
-
}
-void ConnectDialog::set_dst_node(Node* p_node) {
+void ConnectDialog::set_dst_node(Node *p_node) {
tree->set_selected(p_node);
}
-void ConnectDialog::set_dst_method(const StringName& p_method) {
+void ConnectDialog::set_dst_method(const StringName &p_method) {
dst_method->set_text(p_method);
}
@@ -288,92 +274,84 @@ void ConnectDialog::set_dst_method(const StringName& p_method) {
void ConnectDialog::_bind_methods() {
//ClassDB::bind_method("_ok",&ConnectDialog::_ok_pressed);
- ClassDB::bind_method("_cancel",&ConnectDialog::_cancel_pressed);
+ ClassDB::bind_method("_cancel", &ConnectDialog::_cancel_pressed);
//ClassDB::bind_method("_dst_method_list_selected",&ConnectDialog::_dst_method_list_selected);
- ClassDB::bind_method("_tree_node_selected",&ConnectDialog::_tree_node_selected);
+ ClassDB::bind_method("_tree_node_selected", &ConnectDialog::_tree_node_selected);
- ClassDB::bind_method("_add_bind",&ConnectDialog::_add_bind);
- ClassDB::bind_method("_remove_bind",&ConnectDialog::_remove_bind);
+ ClassDB::bind_method("_add_bind", &ConnectDialog::_add_bind);
+ ClassDB::bind_method("_remove_bind", &ConnectDialog::_remove_bind);
- ADD_SIGNAL( MethodInfo("connected") );
+ ADD_SIGNAL(MethodInfo("connected"));
}
ConnectDialog::ConnectDialog() {
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
-
- HBoxContainer *main_hb = memnew( HBoxContainer );
+ HBoxContainer *main_hb = memnew(HBoxContainer);
vbc->add_child(main_hb);
main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
- VBoxContainer *vbc_left = memnew( VBoxContainer );
+ VBoxContainer *vbc_left = memnew(VBoxContainer);
main_hb->add_child(vbc_left);
vbc_left->set_h_size_flags(SIZE_EXPAND_FILL);
-
tree = memnew(SceneTreeEditor(false));
- tree->get_scene_tree()->connect("item_activated",this,"_ok");
- vbc_left->add_margin_child(TTR("Connect To Node:"),tree,true);
-
+ tree->get_scene_tree()->connect("item_activated", this, "_ok");
+ vbc_left->add_margin_child(TTR("Connect To Node:"), tree, true);
-
- VBoxContainer *vbc_right = memnew( VBoxContainer );
+ VBoxContainer *vbc_right = memnew(VBoxContainer);
main_hb->add_child(vbc_right);
vbc_right->set_h_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *add_bind_hb = memnew( HBoxContainer );
+ HBoxContainer *add_bind_hb = memnew(HBoxContainer);
- type_list = memnew( OptionButton );
+ type_list = memnew(OptionButton);
type_list->set_h_size_flags(SIZE_EXPAND_FILL);
add_bind_hb->add_child(type_list);
-
- type_list->add_item("bool",Variant::BOOL);
- type_list->add_item("int",Variant::INT);
- type_list->add_item("real",Variant::REAL);
- type_list->add_item("string",Variant::STRING);
+ type_list->add_item("bool", Variant::BOOL);
+ type_list->add_item("int", Variant::INT);
+ type_list->add_item("real", Variant::REAL);
+ type_list->add_item("string", Variant::STRING);
//type_list->add_separator();
- type_list->add_item("Vector2",Variant::VECTOR2);
- type_list->add_item("Rect2",Variant::RECT2);
- type_list->add_item("Vector3",Variant::VECTOR3);
- type_list->add_item("Plane",Variant::PLANE);
- type_list->add_item("Quat",Variant::QUAT);
- type_list->add_item("Rect3",Variant::RECT3);
- type_list->add_item("Basis",Variant::BASIS);
- type_list->add_item("Transform",Variant::TRANSFORM);
+ type_list->add_item("Vector2", Variant::VECTOR2);
+ type_list->add_item("Rect2", Variant::RECT2);
+ type_list->add_item("Vector3", Variant::VECTOR3);
+ type_list->add_item("Plane", Variant::PLANE);
+ type_list->add_item("Quat", Variant::QUAT);
+ type_list->add_item("Rect3", Variant::RECT3);
+ type_list->add_item("Basis", Variant::BASIS);
+ type_list->add_item("Transform", Variant::TRANSFORM);
//type_list->add_separator();
- type_list->add_item("Color",Variant::COLOR);
- type_list->add_item("Image",Variant::IMAGE);
+ type_list->add_item("Color", Variant::COLOR);
+ type_list->add_item("Image", Variant::IMAGE);
type_list->select(0);
- Button *add_bind = memnew( Button );
+ Button *add_bind = memnew(Button);
add_bind->set_text(TTR("Add"));
add_bind_hb->add_child(add_bind);
- add_bind->connect("pressed",this,"_add_bind");
+ add_bind->connect("pressed", this, "_add_bind");
- Button *del_bind = memnew( Button );
+ Button *del_bind = memnew(Button);
del_bind->set_text(TTR("Remove"));
add_bind_hb->add_child(del_bind);
- del_bind->connect("pressed",this,"_remove_bind");
+ del_bind->connect("pressed", this, "_remove_bind");
- vbc_right->add_margin_child(TTR("Add Extra Call Argument:"),add_bind_hb);
+ vbc_right->add_margin_child(TTR("Add Extra Call Argument:"), add_bind_hb);
- bind_editor = memnew( PropertyEditor );
+ bind_editor = memnew(PropertyEditor);
bind_editor->hide_top_label();
- vbc_right->add_margin_child(TTR("Extra Call Arguments:"),bind_editor,true);
-
-
+ vbc_right->add_margin_child(TTR("Extra Call Arguments:"), bind_editor, true);
dst_path = memnew(LineEdit);
- vbc->add_margin_child(TTR("Path to Node:"),dst_path);
+ vbc->add_margin_child(TTR("Path to Node:"), dst_path);
-
- HBoxContainer *dstm_hb = memnew( HBoxContainer );
- vbc->add_margin_child("Method In Node:",dstm_hb);
+ HBoxContainer *dstm_hb = memnew(HBoxContainer);
+ vbc->add_margin_child("Method In Node:", dstm_hb);
dst_method = memnew(LineEdit);
dst_method->set_h_size_flags(SIZE_EXPAND_FILL);
@@ -390,21 +368,21 @@ ConnectDialog::ConnectDialog() {
*/
//add_child(dst_method_list);
- make_callback = memnew( CheckButton );
+ make_callback = memnew(CheckButton);
make_callback->set_toggle_mode(true);
- make_callback->set_pressed( EDITOR_DEF("text_editor/tools/create_signal_callbacks",true));
+ make_callback->set_pressed(EDITOR_DEF("text_editor/tools/create_signal_callbacks", true));
make_callback->set_text(TTR("Make Function"));
dstm_hb->add_child(make_callback);
- deferred = memnew( CheckButton );
+ deferred = memnew(CheckButton);
deferred->set_text(TTR("Deferred"));
dstm_hb->add_child(deferred);
- oneshot = memnew( CheckButton );
+ oneshot = memnew(CheckButton);
oneshot->set_text(TTR("Oneshot"));
dstm_hb->add_child(oneshot);
-/*
+ /*
realtime = memnew( CheckButton );
realtime->set_anchor( MARGIN_TOP, ANCHOR_END );
realtime->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
@@ -415,38 +393,27 @@ ConnectDialog::ConnectDialog() {
add_child(realtime);
*/
-
-
-
//dst_method_list->get_popup()->connect("id_pressed", this,"_dst_method_list_selected");
- tree->connect("node_selected", this,"_tree_node_selected");
+ tree->connect("node_selected", this, "_tree_node_selected");
set_as_toplevel(true);
- cdbinds = memnew( ConnectDialogBinds );
+ cdbinds = memnew(ConnectDialogBinds);
- error = memnew( ConfirmationDialog );
+ error = memnew(ConfirmationDialog);
add_child(error);
error->get_ok()->set_text(TTR("Close"));
get_ok()->set_text(TTR("Connect"));
//error->get_cancel()->set_text("Close");
-
-
-
-
}
-
-ConnectDialog::~ConnectDialog()
-{
- memdelete( cdbinds );
+ConnectDialog::~ConnectDialog() {
+ memdelete(cdbinds);
}
-
-
void ConnectionsDock::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
@@ -462,94 +429,88 @@ void ConnectionsDock::_connect() {
TreeItem *it = tree->get_selected();
ERR_FAIL_COND(!it);
- String signal=it->get_metadata(0).operator Dictionary()["name"];
+ String signal = it->get_metadata(0).operator Dictionary()["name"];
- NodePath dst_path=connect_dialog->get_dst_path();
+ NodePath dst_path = connect_dialog->get_dst_path();
Node *target = node->get_node(dst_path);
ERR_FAIL_COND(!target);
- StringName dst_method=connect_dialog->get_dst_method();
- bool defer=connect_dialog->get_deferred();
- bool oshot=connect_dialog->get_oneshot();
+ StringName dst_method = connect_dialog->get_dst_method();
+ bool defer = connect_dialog->get_deferred();
+ bool oshot = connect_dialog->get_oneshot();
Vector<Variant> binds = connect_dialog->get_binds();
- PoolStringArray args = it->get_metadata(0).operator Dictionary()["args"];
- int flags = CONNECT_PERSIST | (defer?CONNECT_DEFERRED:0) | (oshot?CONNECT_ONESHOT:0);
+ PoolStringArray args = it->get_metadata(0).operator Dictionary()["args"];
+ int flags = CONNECT_PERSIST | (defer ? CONNECT_DEFERRED : 0) | (oshot ? CONNECT_ONESHOT : 0);
- undo_redo->create_action(vformat(TTR("Connect '%s' to '%s'"),signal,String(dst_method)));
- undo_redo->add_do_method(node,"connect",signal,target,dst_method,binds,flags);
- undo_redo->add_undo_method(node,"disconnect",signal,target,dst_method);
- undo_redo->add_do_method(this,"update_tree");
- undo_redo->add_undo_method(this,"update_tree");
- undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
- undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
+ undo_redo->create_action(vformat(TTR("Connect '%s' to '%s'"), signal, String(dst_method)));
+ undo_redo->add_do_method(node, "connect", signal, target, dst_method, binds, flags);
+ undo_redo->add_undo_method(node, "disconnect", signal, target, dst_method);
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(this, "update_tree");
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
-
if (connect_dialog->get_make_callback()) {
print_line("request connect");
- editor->emit_signal("script_add_function_request",target,dst_method,args);
+ editor->emit_signal("script_add_function_request", target, dst_method, args);
hide();
}
update_tree();
-
}
-
-
-
void ConnectionsDock::_connect_pressed() {
-
TreeItem *item = tree->get_selected();
if (!item) {
//no idea how this happened, but disable
connect_button->set_disabled(true);
return;
}
- if (item->get_parent()==tree->get_root() || item->get_parent()->get_parent()==tree->get_root()) {
+ if (item->get_parent() == tree->get_root() || item->get_parent()->get_parent() == tree->get_root()) {
//a signal - connect
- String signal=item->get_metadata(0).operator Dictionary()["name"];
- String signalname=signal;
- String midname=node->get_name();
- for(int i=0;i<midname.length();i++) {
+ String signal = item->get_metadata(0).operator Dictionary()["name"];
+ String signalname = signal;
+ String midname = node->get_name();
+ for (int i = 0; i < midname.length(); i++) {
CharType c = midname[i];
- if ((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_') {
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') {
//all good
- } else if (c==' ') {
- c='_';
+ } else if (c == ' ') {
+ c = '_';
} else {
midname.remove(i);
i--;
continue;
}
- midname[i]=c;
+ midname[i] = c;
}
connect_dialog->edit(node);
connect_dialog->popup_centered_ratio();
- connect_dialog->set_title(TTR("Connecting Signal:")+" "+signalname);
- connect_dialog->set_dst_method("_on_"+midname+"_"+signal);
- connect_dialog->set_dst_node(node->get_owner()?node->get_owner():node);
+ connect_dialog->set_title(TTR("Connecting Signal:") + " " + signalname);
+ connect_dialog->set_dst_method("_on_" + midname + "_" + signal);
+ connect_dialog->set_dst_node(node->get_owner() ? node->get_owner() : node);
} else {
//a slot- disconnect
- Connection c=item->get_metadata(0);
- ERR_FAIL_COND(c.source!=node); //shouldn't happen but...bugcheck
+ Connection c = item->get_metadata(0);
+ ERR_FAIL_COND(c.source != node); //shouldn't happen but...bugcheck
undo_redo->create_action(TTR("Create Subscription"));
- undo_redo->add_do_method(node,"disconnect",c.signal,c.target,c.method);
- undo_redo->add_undo_method(node,"connect",c.signal,c.target,c.method,Vector<Variant>(),c.flags);
- undo_redo->add_do_method(this,"update_tree");
- undo_redo->add_undo_method(this,"update_tree");
- undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
- undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
+ undo_redo->add_do_method(node, "disconnect", c.signal, c.target, c.method);
+ undo_redo->add_undo_method(node, "connect", c.signal, c.target, c.method, Vector<Variant>(), c.flags);
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(this, "update_tree");
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
- c.source->disconnect(c.signal,c.target,c.method);
+ c.source->disconnect(c.signal, c.target, c.method);
update_tree();
}
}
@@ -592,30 +553,29 @@ void ConnectionsDock::_remove_confirm() {
struct _ConnectionsDockMethodInfoSort {
- _FORCE_INLINE_ bool operator()(const MethodInfo& a, const MethodInfo& b) const {
+ _FORCE_INLINE_ bool operator()(const MethodInfo &a, const MethodInfo &b) const {
return a.name < b.name;
}
};
void ConnectionsDock::update_tree() {
- tree->clear();
+ tree->clear();
if (!node)
return;
-
- TreeItem *root=tree->create_item();
+ TreeItem *root = tree->create_item();
List<MethodInfo> node_signals;
node->get_signal_list(&node_signals);
//node_signals.sort_custom<_ConnectionsDockMethodInfoSort>();
- bool did_script=false;
+ bool did_script = false;
StringName base = node->get_class();
- while(base) {
+ while (base) {
List<MethodInfo> node_signals;
Ref<Texture> icon;
@@ -627,128 +587,122 @@ void ConnectionsDock::update_tree() {
if (scr.is_valid()) {
scr->get_script_signal_list(&node_signals);
if (scr->get_path().is_resource_file())
- name=scr->get_path().get_file();
+ name = scr->get_path().get_file();
else
- name=scr->get_class();
+ name = scr->get_class();
- if (has_icon(scr->get_class(),"EditorIcons")) {
- icon=get_icon(scr->get_class(),"EditorIcons");
+ if (has_icon(scr->get_class(), "EditorIcons")) {
+ icon = get_icon(scr->get_class(), "EditorIcons");
}
}
} else {
- ClassDB::get_signal_list(base,&node_signals,true);
- if (has_icon(base,"EditorIcons")) {
- icon=get_icon(base,"EditorIcons");
+ ClassDB::get_signal_list(base, &node_signals, true);
+ if (has_icon(base, "EditorIcons")) {
+ icon = get_icon(base, "EditorIcons");
}
- name=base;
+ name = base;
}
-
TreeItem *pitem = NULL;
if (node_signals.size()) {
- pitem=tree->create_item(root);
- pitem->set_text(0,name);
- pitem->set_icon(0,icon);
- pitem->set_selectable(0,false);
- pitem->set_editable(0,false);
- pitem->set_custom_bg_color(0,get_color("prop_subsection","Editor"));
+ pitem = tree->create_item(root);
+ pitem->set_text(0, name);
+ pitem->set_icon(0, icon);
+ pitem->set_selectable(0, false);
+ pitem->set_editable(0, false);
+ pitem->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
node_signals.sort();
}
- for(List<MethodInfo>::Element *E=node_signals.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = node_signals.front(); E; E = E->next()) {
-
- MethodInfo &mi =E->get();
+ MethodInfo &mi = E->get();
String signaldesc;
- signaldesc=mi.name+"(";
+ signaldesc = mi.name + "(";
PoolStringArray argnames;
if (mi.arguments.size()) {
- signaldesc+=" ";
- for(int i=0;i<mi.arguments.size();i++) {
+ signaldesc += " ";
+ for (int i = 0; i < mi.arguments.size(); i++) {
PropertyInfo &pi = mi.arguments[i];
- if (i>0)
- signaldesc+=", ";
- String tname="var";
- if (pi.type!=Variant::NIL) {
- tname=Variant::get_type_name(pi.type);
+ if (i > 0)
+ signaldesc += ", ";
+ String tname = "var";
+ if (pi.type != Variant::NIL) {
+ tname = Variant::get_type_name(pi.type);
}
- signaldesc+=tname+" "+(pi.name==""?String("arg "+itos(i)):pi.name);
- argnames.push_back(pi.name+":"+tname);
-
+ signaldesc += tname + " " + (pi.name == "" ? String("arg " + itos(i)) : pi.name);
+ argnames.push_back(pi.name + ":" + tname);
}
- signaldesc+=" ";
+ signaldesc += " ";
}
- signaldesc+=")";
+ signaldesc += ")";
- TreeItem *item=tree->create_item(pitem);
- item->set_text(0,signaldesc);
+ TreeItem *item = tree->create_item(pitem);
+ item->set_text(0, signaldesc);
Dictionary sinfo;
- sinfo["name"]=mi.name;
- sinfo["args"]=argnames;
- item->set_metadata(0,sinfo);
- item->set_icon(0,get_icon("Signal","EditorIcons"));
+ sinfo["name"] = mi.name;
+ sinfo["args"] = argnames;
+ item->set_metadata(0, sinfo);
+ item->set_icon(0, get_icon("Signal", "EditorIcons"));
List<Object::Connection> connections;
- node->get_signal_connection_list(mi.name,&connections);
+ node->get_signal_connection_list(mi.name, &connections);
- for(List<Object::Connection>::Element *F=connections.front();F;F=F->next()) {
+ for (List<Object::Connection>::Element *F = connections.front(); F; F = F->next()) {
- Object::Connection&c = F->get();
- if (!(c.flags&CONNECT_PERSIST))
+ Object::Connection &c = F->get();
+ if (!(c.flags & CONNECT_PERSIST))
continue;
Node *target = c.target->cast_to<Node>();
if (!target)
continue;
- String path = String(node->get_path_to(target))+" :: "+c.method+"()";
- if (c.flags&CONNECT_DEFERRED)
- path+=" (deferred)";
- if (c.flags&CONNECT_ONESHOT)
- path+=" (oneshot)";
+ String path = String(node->get_path_to(target)) + " :: " + c.method + "()";
+ if (c.flags & CONNECT_DEFERRED)
+ path += " (deferred)";
+ if (c.flags & CONNECT_ONESHOT)
+ path += " (oneshot)";
if (c.binds.size()) {
- path+=" binds( ";
- for(int i=0;i<c.binds.size();i++) {
+ path += " binds( ";
+ for (int i = 0; i < c.binds.size(); i++) {
- if (i>0)
- path+=", ";
- path+=c.binds[i].operator String();
+ if (i > 0)
+ path += ", ";
+ path += c.binds[i].operator String();
}
- path+=" )";
+ path += " )";
}
- TreeItem *item2=tree->create_item(item);
- item2->set_text(0,path);
- item2->set_metadata(0,c);
- item2->set_icon(0,get_icon("Slot","EditorIcons"));
-
-
+ TreeItem *item2 = tree->create_item(item);
+ item2->set_text(0, path);
+ item2->set_metadata(0, c);
+ item2->set_icon(0, get_icon("Slot", "EditorIcons"));
}
}
if (!did_script) {
- did_script=true;
+ did_script = true;
} else {
- base=ClassDB::get_parent_class(base);
+ base = ClassDB::get_parent_class(base);
}
}
connect_button->set_text(TTR("Connect"));
connect_button->set_disabled(true);
-
}
-void ConnectionsDock::set_node(Node* p_node) {
+void ConnectionsDock::set_node(Node *p_node) {
- node=p_node;
+ node = p_node;
update_tree();
}
@@ -760,7 +714,7 @@ void ConnectionsDock::_something_selected() {
connect_button->set_text(TTR("Connect.."));
connect_button->set_disabled(true);
- } else if (item->get_parent()==tree->get_root() || item->get_parent()->get_parent()==tree->get_root()) {
+ } else if (item->get_parent() == tree->get_root() || item->get_parent()->get_parent() == tree->get_root()) {
//a signal - connect
connect_button->set_text(TTR("Connect.."));
connect_button->set_disabled(false);
@@ -770,7 +724,6 @@ void ConnectionsDock::_something_selected() {
connect_button->set_text(TTR("Disconnect"));
connect_button->set_disabled(false);
}
-
}
void ConnectionsDock::_something_activated() {
@@ -780,87 +733,83 @@ void ConnectionsDock::_something_activated() {
if (!item)
return;
- if (item->get_parent()==tree->get_root() || item->get_parent()->get_parent()==tree->get_root()) {
+ if (item->get_parent() == tree->get_root() || item->get_parent()->get_parent() == tree->get_root()) {
// a signal - connect
- String signal=item->get_metadata(0).operator Dictionary()["name"];
- String midname=node->get_name();
- for(int i=0;i<midname.length();i++) {
+ String signal = item->get_metadata(0).operator Dictionary()["name"];
+ String midname = node->get_name();
+ for (int i = 0; i < midname.length(); i++) {
CharType c = midname[i];
- if ((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_') {
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') {
//all good
- } else if (c==' ') {
- c='_';
+ } else if (c == ' ') {
+ c = '_';
} else {
midname.remove(i);
i--;
continue;
}
- midname[i]=c;
+ midname[i] = c;
}
connect_dialog->edit(node);
connect_dialog->popup_centered_ratio();
- connect_dialog->set_dst_method("_on_"+midname+"_"+signal);
- connect_dialog->set_dst_node(node->get_owner()?node->get_owner():node);
+ connect_dialog->set_dst_method("_on_" + midname + "_" + signal);
+ connect_dialog->set_dst_node(node->get_owner() ? node->get_owner() : node);
} else {
// a slot - go to target method
- Connection c=item->get_metadata(0);
- ERR_FAIL_COND(c.source!=node); //shouldn't happen but...bugcheck
+ Connection c = item->get_metadata(0);
+ ERR_FAIL_COND(c.source != node); //shouldn't happen but...bugcheck
if (!c.target)
return;
Ref<Script> script = c.target->get_script();
- if (script.is_valid() && ScriptEditor::get_singleton()->script_go_to_method(script,c.method)) {
- editor->call("_editor_select",EditorNode::EDITOR_SCRIPT);
+ if (script.is_valid() && ScriptEditor::get_singleton()->script_go_to_method(script, c.method)) {
+ editor->call("_editor_select", EditorNode::EDITOR_SCRIPT);
}
}
}
void ConnectionsDock::_bind_methods() {
-
- ClassDB::bind_method("_connect",&ConnectionsDock::_connect);
- ClassDB::bind_method("_something_selected",&ConnectionsDock::_something_selected);
- ClassDB::bind_method("_something_activated",&ConnectionsDock::_something_activated);
- ClassDB::bind_method("_close",&ConnectionsDock::_close);
- ClassDB::bind_method("_connect_pressed",&ConnectionsDock::_connect_pressed);
- ClassDB::bind_method("update_tree",&ConnectionsDock::update_tree);
-
-
+ ClassDB::bind_method("_connect", &ConnectionsDock::_connect);
+ ClassDB::bind_method("_something_selected", &ConnectionsDock::_something_selected);
+ ClassDB::bind_method("_something_activated", &ConnectionsDock::_something_activated);
+ ClassDB::bind_method("_close", &ConnectionsDock::_close);
+ ClassDB::bind_method("_connect_pressed", &ConnectionsDock::_connect_pressed);
+ ClassDB::bind_method("update_tree", &ConnectionsDock::update_tree);
}
ConnectionsDock::ConnectionsDock(EditorNode *p_editor) {
- editor=p_editor;
+ editor = p_editor;
set_name(TTR("Signals"));
-
VBoxContainer *vbc = this;
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_columns(1);
tree->set_select_mode(Tree::SELECT_ROW);
tree->set_hide_root(true);
vbc->add_child(tree);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
- connect_button = memnew( Button );
+ connect_button = memnew(Button);
connect_button->set_text("Connect");
- HBoxContainer *hb = memnew( HBoxContainer);
+ HBoxContainer *hb = memnew(HBoxContainer);
vbc->add_child(hb);
hb->add_spacer();
hb->add_child(connect_button);
- connect_button->connect("pressed",this,"_connect_pressed");
+ connect_button->connect("pressed", this, "_connect_pressed");
//add_child(tree);
- connect_dialog = memnew( ConnectDialog );
+ connect_dialog = memnew(ConnectDialog);
connect_dialog->set_as_toplevel(true);
add_child(connect_dialog);
- remove_confirm = memnew( ConfirmationDialog );
+ remove_confirm = memnew(ConfirmationDialog);
remove_confirm->set_as_toplevel(true);
add_child(remove_confirm);
@@ -873,18 +822,13 @@ ConnectionsDock::ConnectionsDock(EditorNode *p_editor) {
node_only->set_end( Point2( 10,44) );
*/
+ remove_confirm->connect("confirmed", this, "_remove_confirm");
+ connect_dialog->connect("connected", this, "_connect");
+ tree->connect("item_selected", this, "_something_selected");
+ tree->connect("item_activated", this, "_something_activated");
- remove_confirm->connect("confirmed", this,"_remove_confirm");
- connect_dialog->connect("connected", this,"_connect");
- tree->connect("item_selected", this,"_something_selected");
- tree->connect("item_activated", this,"_something_activated");
-
- add_constant_override("separation",3*EDSCALE);
+ add_constant_override("separation", 3 * EDSCALE);
}
-
-ConnectionsDock::~ConnectionsDock()
-{
+ConnectionsDock::~ConnectionsDock() {
}
-
-
diff --git a/editor/connections_dialog.h b/editor/connections_dialog.h
index 6407b83f6e..240e3655ed 100644
--- a/editor/connections_dialog.h
+++ b/editor/connections_dialog.h
@@ -29,15 +29,15 @@
#ifndef CONNECTIONS_DIALOG_H
#define CONNECTIONS_DIALOG_H
-#include "scene/gui/popup.h"
+#include "editor/property_editor.h"
+#include "editor/scene_tree_editor.h"
#include "scene/gui/button.h"
#include "scene/gui/check_button.h"
-#include "scene/gui/tree.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/menu_button.h"
#include "scene/gui/line_edit.h"
-#include "editor/scene_tree_editor.h"
-#include "editor/property_editor.h"
+#include "scene/gui/menu_button.h"
+#include "scene/gui/popup.h"
+#include "scene/gui/tree.h"
#include "undo_redo.h"
/**
@@ -48,8 +48,7 @@ class ConnectDialogBinds;
class ConnectDialog : public ConfirmationDialog {
- GDCLASS( ConnectDialog, ConfirmationDialog );
-
+ GDCLASS(ConnectDialog, ConfirmationDialog);
ConfirmationDialog *error;
LineEdit *dst_path;
@@ -71,20 +70,18 @@ class ConnectDialog : public ConfirmationDialog {
void _remove_bind();
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
+public:
bool get_make_callback() { return make_callback->is_visible() && make_callback->is_pressed(); }
NodePath get_dst_path() const;
StringName get_dst_method() const;
bool get_deferred() const;
bool get_oneshot() const;
Vector<Variant> get_binds() const;
- void set_dst_method(const StringName& p_method);
- void set_dst_node(Node* p_node);
+ void set_dst_method(const StringName &p_method);
+ void set_dst_node(Node *p_node);
//Button *get_ok() { return ok; }
//Button *get_cancel() { return cancel; }
@@ -92,12 +89,11 @@ public:
ConnectDialog();
~ConnectDialog();
-
};
class ConnectionsDock : public VBoxContainer {
- GDCLASS( ConnectionsDock , VBoxContainer );
+ GDCLASS(ConnectionsDock, VBoxContainer);
Button *connect_button;
EditorNode *editor;
@@ -115,20 +111,18 @@ class ConnectionsDock : public VBoxContainer {
UndoRedo *undo_redo;
protected:
-
void _connect_pressed();
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_undoredo(UndoRedo *p_undo_redo) { undo_redo=p_undo_redo; }
+public:
+ void set_undoredo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
- void set_node(Node* p_node);
+ void set_node(Node *p_node);
String get_selected_type();
- ConnectionsDock(EditorNode *p_editor=NULL);
+ ConnectionsDock(EditorNode *p_editor = NULL);
~ConnectionsDock();
-
};
#endif
diff --git a/editor/create_dialog.cpp b/editor/create_dialog.cpp
index 58bb148ce1..af62a2293b 100644
--- a/editor/create_dialog.cpp
+++ b/editor/create_dialog.cpp
@@ -29,39 +29,38 @@
#include "create_dialog.h"
#include "class_db.h"
+#include "editor_node.h"
#include "print_string.h"
#include "scene/gui/box_container.h"
-#include "editor_node.h"
#if 1
-#include "os/keyboard.h"
-#include "editor_settings.h"
#include "editor_help.h"
-
+#include "editor_settings.h"
+#include "os/keyboard.h"
void CreateDialog::popup(bool p_dontclear) {
recent->clear();
- FileAccess *f = FileAccess::open( EditorSettings::get_singleton()->get_project_settings_path().plus_file("create_recent."+base_type), FileAccess::READ );
+ FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_path().plus_file("create_recent." + base_type), FileAccess::READ);
if (f) {
TreeItem *root = recent->create_item();
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
- if (l!=String()) {
+ if (l != String()) {
TreeItem *ti = recent->create_item(root);
- ti->set_text(0,l);
- if (has_icon(l,"EditorIcons")) {
+ ti->set_text(0, l);
+ if (has_icon(l, "EditorIcons")) {
- ti->set_icon(0,get_icon(l,"EditorIcons"));
+ ti->set_icon(0, get_icon(l, "EditorIcons"));
} else {
- ti->set_icon(0,get_icon("Object","EditorIcons"));
+ ti->set_icon(0, get_icon("Object", "EditorIcons"));
}
}
}
@@ -71,17 +70,16 @@ void CreateDialog::popup(bool p_dontclear) {
favorites->clear();
- f = FileAccess::open( EditorSettings::get_singleton()->get_project_settings_path().plus_file("favorites."+base_type), FileAccess::READ );
+ f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_path().plus_file("favorites." + base_type), FileAccess::READ);
favorite_list.clear();
if (f) {
-
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
- if (l!=String()) {
+ if (l != String()) {
favorite_list.push_back(l);
}
}
@@ -123,64 +121,57 @@ void CreateDialog::popup(bool p_dontclear) {
search_box->grab_focus();
_update_search();
-
-
}
-
-void CreateDialog::_text_changed(const String& p_newtext) {
+void CreateDialog::_text_changed(const String &p_newtext) {
_update_search();
}
-void CreateDialog::_sbox_input(const InputEvent& p_ie) {
+void CreateDialog::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY && (
- p_ie.key.scancode == KEY_UP ||
- p_ie.key.scancode == KEY_DOWN ||
- p_ie.key.scancode == KEY_PAGEUP ||
- p_ie.key.scancode == KEY_PAGEDOWN ) ) {
+ if (p_ie.type == InputEvent::KEY && (p_ie.key.scancode == KEY_UP ||
+ p_ie.key.scancode == KEY_DOWN ||
+ p_ie.key.scancode == KEY_PAGEUP ||
+ p_ie.key.scancode == KEY_PAGEDOWN)) {
- search_options->call("_gui_input",p_ie);
+ search_options->call("_gui_input", p_ie);
search_box->accept_event();
}
-
}
-void CreateDialog::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root,TreeItem **to_select) {
+void CreateDialog::add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem *p_root, TreeItem **to_select) {
if (p_types.has(p_type))
return;
- if (!ClassDB::is_parent_class(p_type,base_type) || p_type==base_type)
+ if (!ClassDB::is_parent_class(p_type, base_type) || p_type == base_type)
return;
- String inherits=ClassDB::get_parent_class(p_type);
-
- TreeItem *parent=p_root;
+ String inherits = ClassDB::get_parent_class(p_type);
+ TreeItem *parent = p_root;
if (inherits.length()) {
if (!p_types.has(inherits)) {
- add_type(inherits,p_types,p_root,to_select);
+ add_type(inherits, p_types, p_root, to_select);
}
- if (p_types.has(inherits) )
- parent=p_types[inherits];
+ if (p_types.has(inherits))
+ parent = p_types[inherits];
}
TreeItem *item = search_options->create_item(parent);
- item->set_text(0,p_type);
+ item->set_text(0, p_type);
if (!ClassDB::can_instance(p_type)) {
- item->set_custom_color(0, Color(0.5,0.5,0.5) );
- item->set_selectable(0,false);
+ item->set_custom_color(0, Color(0.5, 0.5, 0.5));
+ item->set_selectable(0, false);
} else {
- if ((!*to_select && (search_box->get_text().is_subsequence_ofi(p_type))) || search_box->get_text()==p_type) {
- *to_select=item;
+ if ((!*to_select && (search_box->get_text().is_subsequence_ofi(p_type))) || search_box->get_text() == p_type) {
+ *to_select = item;
}
-
}
if (bool(EditorSettings::get_singleton()->get("docks/scene_tree/start_create_dialog_fully_expanded"))) {
@@ -195,23 +186,19 @@ void CreateDialog::add_type(const String& p_type,HashMap<String,TreeItem*>& p_ty
item->set_collapsed(collapse);
}
- const String& description = EditorHelp::get_doc_data()->class_list[p_type].brief_description;
- item->set_tooltip(0,description);
-
+ const String &description = EditorHelp::get_doc_data()->class_list[p_type].brief_description;
+ item->set_tooltip(0, description);
- if (has_icon(p_type,"EditorIcons")) {
+ if (has_icon(p_type, "EditorIcons")) {
- item->set_icon(0, get_icon(p_type,"EditorIcons"));
+ item->set_icon(0, get_icon(p_type, "EditorIcons"));
}
-
-
- p_types[p_type]=item;
+ p_types[p_type] = item;
}
void CreateDialog::_update_search() {
-
search_options->clear();
favorite->set_disabled(true);
@@ -224,58 +211,54 @@ void CreateDialog::_update_search() {
List<StringName> type_list;
ClassDB::get_class_list(&type_list);
- HashMap<String,TreeItem*> types;
+ HashMap<String, TreeItem *> types;
TreeItem *root = search_options->create_item();
- root->set_text(0,base_type);
- if (has_icon(base_type,"EditorIcons")) {
- root->set_icon(0,get_icon(base_type,"EditorIcons"));
+ root->set_text(0, base_type);
+ if (has_icon(base_type, "EditorIcons")) {
+ root->set_icon(0, get_icon(base_type, "EditorIcons"));
}
- List<StringName>::Element *I=type_list.front();
- TreeItem *to_select=NULL;
-
- for(;I;I=I->next()) {
-
+ List<StringName>::Element *I = type_list.front();
+ TreeItem *to_select = NULL;
+ for (; I; I = I->next()) {
- String type=I->get();
+ String type = I->get();
- if (base_type=="Node" && type.begins_with("Editor"))
+ if (base_type == "Node" && type.begins_with("Editor"))
continue; // do not show editor nodes
if (!ClassDB::can_instance(type))
continue; // cant create what can't be instanced
- if (search_box->get_text()=="") {
- add_type(type,types,root,&to_select);
+ if (search_box->get_text() == "") {
+ add_type(type, types, root, &to_select);
} else {
- bool found=false;
- String type=I->get();
- while(type!="" && ClassDB::is_parent_class(type,base_type) && type!=base_type) {
+ bool found = false;
+ String type = I->get();
+ while (type != "" && ClassDB::is_parent_class(type, base_type) && type != base_type) {
if (search_box->get_text().is_subsequence_ofi(type)) {
- found=true;
+ found = true;
break;
}
- type=ClassDB::get_parent_class(type);
+ type = ClassDB::get_parent_class(type);
}
-
if (found)
- add_type(I->get(),types,root,&to_select);
+ add_type(I->get(), types, root, &to_select);
}
if (EditorNode::get_editor_data().get_custom_types().has(type) && ClassDB::is_parent_class(type, base_type)) {
//there are custom types based on this... cool.
//print_line("there are custom types");
-
const Vector<EditorData::CustomType> &ct = EditorNode::get_editor_data().get_custom_types()[type];
- for(int i=0;i<ct.size();i++) {
+ for (int i = 0; i < ct.size(); i++) {
bool show = search_box->get_text().is_subsequence_ofi(ct[i].name);
@@ -283,40 +266,35 @@ void CreateDialog::_update_search() {
continue;
if (!types.has(type))
- add_type(type,types,root,&to_select);
+ add_type(type, types, root, &to_select);
TreeItem *ti;
- if (types.has(type) )
- ti=types[type];
+ if (types.has(type))
+ ti = types[type];
else
- ti=search_options->get_root();
-
+ ti = search_options->get_root();
TreeItem *item = search_options->create_item(ti);
- item->set_metadata(0,type);
- item->set_text(0,ct[i].name);
+ item->set_metadata(0, type);
+ item->set_text(0, ct[i].name);
if (ct[i].icon.is_valid()) {
- item->set_icon(0,ct[i].icon);
-
+ item->set_icon(0, ct[i].icon);
}
- if (!to_select || ct[i].name==search_box->get_text()) {
- to_select=item;
+ if (!to_select || ct[i].name == search_box->get_text()) {
+ to_select = item;
}
-
}
-
}
}
if (to_select) {
to_select->select(0);
favorite->set_disabled(false);
- favorite->set_pressed(favorite_list.find(to_select->get_text(0))!=-1);
+ favorite->set_pressed(favorite_list.find(to_select->get_text(0)) != -1);
}
- get_ok()->set_disabled(root->get_children()==NULL);
-
+ get_ok()->set_disabled(root->get_children() == NULL);
}
void CreateDialog::_confirmed() {
@@ -325,25 +303,25 @@ void CreateDialog::_confirmed() {
if (!ti)
return;
- FileAccess *f = FileAccess::open( EditorSettings::get_singleton()->get_project_settings_path().plus_file("create_recent."+base_type), FileAccess::WRITE );
+ FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_path().plus_file("create_recent." + base_type), FileAccess::WRITE);
if (f) {
f->store_line(get_selected_type());
TreeItem *t = recent->get_root();
if (t)
- t=t->get_children();
- int count=0;
- while(t) {
- if (t->get_text(0)!=get_selected_type()) {
+ t = t->get_children();
+ int count = 0;
+ while (t) {
+ if (t->get_text(0) != get_selected_type()) {
f->store_line(t->get_text(0));
}
- if (count>32) {
+ if (count > 32) {
//limit it to 32 entries..
break;
}
- t=t->get_next();
+ t = t->get_next();
count++;
}
@@ -356,18 +334,17 @@ void CreateDialog::_confirmed() {
void CreateDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- connect("confirmed",this,"_confirmed");
- favorite->set_icon(get_icon("Favorites","EditorIcons"));
+ connect("confirmed", this, "_confirmed");
+ favorite->set_icon(get_icon("Favorites", "EditorIcons"));
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
- disconnect("confirmed",this,"_confirmed");
+ if (p_what == NOTIFICATION_EXIT_TREE) {
+ disconnect("confirmed", this, "_confirmed");
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (is_visible_in_tree()) {
@@ -375,13 +352,12 @@ void CreateDialog::_notification(int p_what) {
search_box->select_all();
}
}
-
}
-void CreateDialog::set_base_type(const String& p_base) {
+void CreateDialog::set_base_type(const String &p_base) {
- base_type=p_base;
- set_title(TTR("Create New")+" "+p_base);
+ base_type = p_base;
+ set_title(TTR("Create New") + " " + p_base);
_update_search();
}
@@ -403,42 +379,38 @@ Object *CreateDialog::instance_selected() {
Variant md = selected->get_metadata(0);
String custom;
- if (md.get_type()!=Variant::NIL)
- custom=md;
+ if (md.get_type() != Variant::NIL)
+ custom = md;
- if (custom!=String()) {
+ if (custom != String()) {
if (EditorNode::get_editor_data().get_custom_types().has(custom)) {
- for(int i=0;i<EditorNode::get_editor_data().get_custom_types()[custom].size();i++) {
- if (EditorNode::get_editor_data().get_custom_types()[custom][i].name==selected->get_text(0)) {
+ for (int i = 0; i < EditorNode::get_editor_data().get_custom_types()[custom].size(); i++) {
+ if (EditorNode::get_editor_data().get_custom_types()[custom][i].name == selected->get_text(0)) {
Ref<Texture> icon = EditorNode::get_editor_data().get_custom_types()[custom][i].icon;
Ref<Script> script = EditorNode::get_editor_data().get_custom_types()[custom][i].script;
String name = selected->get_text(0);
Object *ob = ClassDB::instance(custom);
- ERR_FAIL_COND_V(!ob,NULL);
+ ERR_FAIL_COND_V(!ob, NULL);
if (ob->is_class("Node")) {
- ob->call("set_name",name);
+ ob->call("set_name", name);
}
ob->set_script(script.get_ref_ptr());
if (icon.is_valid())
- ob->set_meta("_editor_icon",icon);
+ ob->set_meta("_editor_icon", icon);
return ob;
-
}
}
-
}
} else {
return ClassDB::instance(selected->get_text(0));
}
}
-
return NULL;
}
-
String CreateDialog::get_base_type() const {
return base_type;
@@ -453,16 +425,14 @@ void CreateDialog::_item_selected() {
String name = item->get_text(0);
favorite->set_disabled(false);
- favorite->set_pressed(favorite_list.find(name)!=-1);
+ favorite->set_pressed(favorite_list.find(name) != -1);
if (!EditorHelp::get_doc_data()->class_list.has(name))
return;
help_bit->set_text(EditorHelp::get_doc_data()->class_list[name].brief_description);
-
}
-
void CreateDialog::_favorite_toggled() {
TreeItem *item = search_options->get_selected();
@@ -471,7 +441,7 @@ void CreateDialog::_favorite_toggled() {
String name = item->get_text(0);
- if (favorite_list.find(name)==-1) {
+ if (favorite_list.find(name) == -1) {
favorite_list.push_back(name);
favorite->set_pressed(true);
} else {
@@ -485,11 +455,11 @@ void CreateDialog::_favorite_toggled() {
void CreateDialog::_save_favorite_list() {
- FileAccess *f = FileAccess::open( EditorSettings::get_singleton()->get_project_settings_path().plus_file("favorites."+base_type), FileAccess::WRITE );
+ FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_path().plus_file("favorites." + base_type), FileAccess::WRITE);
if (f) {
- for(int i=0;i<favorite_list.size();i++) {
+ for (int i = 0; i < favorite_list.size(); i++) {
f->store_line(favorite_list[i]);
}
@@ -501,21 +471,20 @@ void CreateDialog::_update_favorite_list() {
favorites->clear();
TreeItem *root = favorites->create_item();
- for(int i=0;i<favorite_list.size();i++) {
+ for (int i = 0; i < favorite_list.size(); i++) {
TreeItem *ti = favorites->create_item(root);
String l = favorite_list[i];
- ti->set_text(0,l);
+ ti->set_text(0, l);
- if (has_icon(l,"EditorIcons")) {
+ if (has_icon(l, "EditorIcons")) {
- ti->set_icon(0,get_icon(l,"EditorIcons"));
+ ti->set_icon(0, get_icon(l, "EditorIcons"));
} else {
- ti->set_icon(0,get_icon("Object","EditorIcons"));
+ ti->set_icon(0, get_icon("Object", "EditorIcons"));
}
}
}
-
void CreateDialog::_history_selected() {
TreeItem *item = recent->get_selected();
@@ -524,10 +493,9 @@ void CreateDialog::_history_selected() {
search_box->set_text(item->get_text(0));
_update_search();
-
}
-void CreateDialog::_favorite_selected(){
+void CreateDialog::_favorite_selected() {
TreeItem *item = favorites->get_selected();
if (!item)
@@ -535,7 +503,6 @@ void CreateDialog::_favorite_selected(){
search_box->set_text(item->get_text(0));
_update_search();
-
}
void CreateDialog::_history_activated() {
@@ -543,20 +510,20 @@ void CreateDialog::_history_activated() {
_confirmed();
}
-void CreateDialog::_favorite_activated(){
+void CreateDialog::_favorite_activated() {
_confirmed();
}
-Variant CreateDialog::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant CreateDialog::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
TreeItem *ti = favorites->get_item_at_pos(p_point);
if (ti) {
Dictionary d;
- d["type"]="create_favorite_drag";
- d["class"]=ti->get_text(0);
+ d["type"] = "create_favorite_drag";
+ d["class"] = ti->get_text(0);
- ToolButton *tb = memnew( ToolButton );
+ ToolButton *tb = memnew(ToolButton);
tb->set_icon(ti->get_icon(0));
tb->set_text(ti->get_text(0));
set_drag_preview(tb);
@@ -567,17 +534,17 @@ Variant CreateDialog::get_drag_data_fw(const Point2& p_point,Control* p_from) {
return Variant();
}
-bool CreateDialog::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool CreateDialog::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
- if (d.has("type") && String(d["type"])=="create_favorite_drag") {
+ if (d.has("type") && String(d["type"]) == "create_favorite_drag") {
favorites->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN);
return true;
}
return false;
}
-void CreateDialog::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void CreateDialog::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
Dictionary d = p_data;
@@ -589,139 +556,128 @@ void CreateDialog::drop_data_fw(const Point2& p_point,const Variant& p_data,Cont
int ds = favorites->get_drop_section_at_pos(p_point);
int drop_idx = favorite_list.find(drop_at);
- if (drop_idx<0)
+ if (drop_idx < 0)
return;
String type = d["class"];
int from_idx = favorite_list.find(type);
- if (from_idx<0)
+ if (from_idx < 0)
return;
- if (drop_idx==from_idx) {
- ds=-1; //cause it will be gone
- } else if (drop_idx>from_idx) {
+ if (drop_idx == from_idx) {
+ ds = -1; //cause it will be gone
+ } else if (drop_idx > from_idx) {
drop_idx--;
}
favorite_list.remove(from_idx);
- if (ds<0) {
- favorite_list.insert(drop_idx,type);
+ if (ds < 0) {
+ favorite_list.insert(drop_idx, type);
} else {
- if (drop_idx>=favorite_list.size()-1) {
+ if (drop_idx >= favorite_list.size() - 1) {
favorite_list.push_back(type);
} else {
- favorite_list.insert(drop_idx+1,type);
+ favorite_list.insert(drop_idx + 1, type);
}
}
_save_favorite_list();
_update_favorite_list();
-
-
}
void CreateDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_changed"),&CreateDialog::_text_changed);
- ClassDB::bind_method(D_METHOD("_confirmed"),&CreateDialog::_confirmed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&CreateDialog::_sbox_input);
- ClassDB::bind_method(D_METHOD("_item_selected"),&CreateDialog::_item_selected);
- ClassDB::bind_method(D_METHOD("_favorite_toggled"),&CreateDialog::_favorite_toggled);
- ClassDB::bind_method(D_METHOD("_history_selected"),&CreateDialog::_history_selected);
- ClassDB::bind_method(D_METHOD("_favorite_selected"),&CreateDialog::_favorite_selected);
- ClassDB::bind_method(D_METHOD("_history_activated"),&CreateDialog::_history_activated);
- ClassDB::bind_method(D_METHOD("_favorite_activated"),&CreateDialog::_favorite_activated);
+ ClassDB::bind_method(D_METHOD("_text_changed"), &CreateDialog::_text_changed);
+ ClassDB::bind_method(D_METHOD("_confirmed"), &CreateDialog::_confirmed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &CreateDialog::_sbox_input);
+ ClassDB::bind_method(D_METHOD("_item_selected"), &CreateDialog::_item_selected);
+ ClassDB::bind_method(D_METHOD("_favorite_toggled"), &CreateDialog::_favorite_toggled);
+ ClassDB::bind_method(D_METHOD("_history_selected"), &CreateDialog::_history_selected);
+ ClassDB::bind_method(D_METHOD("_favorite_selected"), &CreateDialog::_favorite_selected);
+ ClassDB::bind_method(D_METHOD("_history_activated"), &CreateDialog::_history_activated);
+ ClassDB::bind_method(D_METHOD("_favorite_activated"), &CreateDialog::_favorite_activated);
-
- ClassDB::bind_method("get_drag_data_fw",&CreateDialog::get_drag_data_fw);
- ClassDB::bind_method("can_drop_data_fw",&CreateDialog::can_drop_data_fw);
- ClassDB::bind_method("drop_data_fw",&CreateDialog::drop_data_fw);
+ ClassDB::bind_method("get_drag_data_fw", &CreateDialog::get_drag_data_fw);
+ ClassDB::bind_method("can_drop_data_fw", &CreateDialog::can_drop_data_fw);
+ ClassDB::bind_method("drop_data_fw", &CreateDialog::drop_data_fw);
ADD_SIGNAL(MethodInfo("create"));
-
}
-
CreateDialog::CreateDialog() {
- HSplitContainer *hbc = memnew( HSplitContainer );
+ HSplitContainer *hbc = memnew(HSplitContainer);
add_child(hbc);
-
- VBoxContainer *lvbc = memnew( VBoxContainer);
+ VBoxContainer *lvbc = memnew(VBoxContainer);
hbc->add_child(lvbc);
- lvbc->set_custom_minimum_size(Size2(150,0)*EDSCALE);
+ lvbc->set_custom_minimum_size(Size2(150, 0) * EDSCALE);
- favorites = memnew (Tree );
- lvbc->add_margin_child(TTR("Favorites:"),favorites,true);
+ favorites = memnew(Tree);
+ lvbc->add_margin_child(TTR("Favorites:"), favorites, true);
favorites->set_hide_root(true);
favorites->set_hide_folding(true);
- favorites->connect("cell_selected",this,"_favorite_selected");
- favorites->connect("item_activated",this,"_favorite_activated");
+ favorites->connect("cell_selected", this, "_favorite_selected");
+ favorites->connect("item_activated", this, "_favorite_activated");
favorites->set_drag_forwarding(this);
-
- recent = memnew (Tree );
- lvbc->add_margin_child(TTR("Recent:"),recent,true);
+ recent = memnew(Tree);
+ lvbc->add_margin_child(TTR("Recent:"), recent, true);
recent->set_hide_root(true);
recent->set_hide_folding(true);
- recent->connect("cell_selected",this,"_history_selected");
- recent->connect("item_activated",this,"_history_activated");
+ recent->connect("cell_selected", this, "_history_selected");
+ recent->connect("item_activated", this, "_history_activated");
-
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
hbc->add_child(vbc);
vbc->set_h_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *search_hb = memnew( HBoxContainer );
- search_box = memnew( LineEdit );
+ HBoxContainer *search_hb = memnew(HBoxContainer);
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
search_hb->add_child(search_box);
- favorite = memnew( Button );
+ favorite = memnew(Button);
favorite->set_toggle_mode(true);
search_hb->add_child(favorite);
- favorite->connect("pressed",this,"_favorite_toggled");
- vbc->add_margin_child(TTR("Search:"),search_hb);
- search_box->connect("text_changed",this,"_text_changed");
- search_box->connect("gui_input",this,"_sbox_input");
- search_options = memnew( Tree );
- vbc->add_margin_child(TTR("Matches:"),search_options,true);
+ favorite->connect("pressed", this, "_favorite_toggled");
+ vbc->add_margin_child(TTR("Search:"), search_hb);
+ search_box->connect("text_changed", this, "_text_changed");
+ search_box->connect("gui_input", this, "_sbox_input");
+ search_options = memnew(Tree);
+ vbc->add_margin_child(TTR("Matches:"), search_options, true);
get_ok()->set_text(TTR("Create"));
get_ok()->set_disabled(true);
register_text_enter(search_box);
set_hide_on_ok(false);
- search_options->connect("item_activated",this,"_confirmed");
- search_options->connect("cell_selected",this,"_item_selected");
+ search_options->connect("item_activated", this, "_confirmed");
+ search_options->connect("cell_selected", this, "_item_selected");
//search_options->set_hide_root(true);
- base_type="Object";
-
- help_bit = memnew( EditorHelpBit );
- vbc->add_margin_child(TTR("Description:"),help_bit);
- help_bit->connect("request_hide",this,"_closed");
+ base_type = "Object";
+ help_bit = memnew(EditorHelpBit);
+ vbc->add_margin_child(TTR("Description:"), help_bit);
+ help_bit->connect("request_hide", this, "_closed");
}
-
#else
//old create dialog, disabled
void CreateDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
- connect("confirmed",this,"_create");
+ if (p_what == NOTIFICATION_READY) {
+ connect("confirmed", this, "_create");
update_tree();
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
}
}
-
void CreateDialog::_create() {
if (tree->get_selected())
@@ -739,45 +695,41 @@ void CreateDialog::_text_changed(String p_text) {
update_tree();
}
-void CreateDialog::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root) {
+void CreateDialog::add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem *p_root) {
if (p_types.has(p_type))
return;
- if (!ClassDB::is_type(p_type,base) || p_type==base)
+ if (!ClassDB::is_type(p_type, base) || p_type == base)
return;
- String inherits=ClassDB::type_inherits_from(p_type);
-
- TreeItem *parent=p_root;
+ String inherits = ClassDB::type_inherits_from(p_type);
+ TreeItem *parent = p_root;
if (inherits.length()) {
if (!p_types.has(inherits)) {
- add_type(inherits,p_types,p_root);
+ add_type(inherits, p_types, p_root);
}
- if (p_types.has(inherits) )
- parent=p_types[inherits];
+ if (p_types.has(inherits))
+ parent = p_types[inherits];
}
TreeItem *item = tree->create_item(parent);
- item->set_text(0,p_type);
+ item->set_text(0, p_type);
if (!ClassDB::can_instance(p_type)) {
- item->set_custom_color(0, Color(0.5,0.5,0.5) );
- item->set_selectable(0,false);
+ item->set_custom_color(0, Color(0.5, 0.5, 0.5));
+ item->set_selectable(0, false);
}
+ if (has_icon(p_type, "EditorIcons")) {
- if (has_icon(p_type,"EditorIcons")) {
-
- item->set_icon(0, get_icon(p_type,"EditorIcons"));
+ item->set_icon(0, get_icon(p_type, "EditorIcons"));
}
-
-
- p_types[p_type]=item;
+ p_types[p_type] = item;
}
void CreateDialog::update_tree() {
@@ -787,137 +739,117 @@ void CreateDialog::update_tree() {
List<String> type_list;
ClassDB::get_type_list(&type_list);
- HashMap<String,TreeItem*> types;
+ HashMap<String, TreeItem *> types;
TreeItem *root = tree->create_item();
- root->set_text(0,base);
-
- List<String>::Element *I=type_list.front();
-
- for(;I;I=I->next()) {
+ root->set_text(0, base);
+ List<String>::Element *I = type_list.front();
- String type=I->get();
+ for (; I; I = I->next()) {
+ String type = I->get();
if (!ClassDB::can_instance(type))
continue; // cant create what can't be instanced
- if (filter->get_text()=="")
- add_type(type,types,root);
+ if (filter->get_text() == "")
+ add_type(type, types, root);
else {
- bool found=false;
- String type=I->get();
- while(type!="" && ClassDB::is_type(type,base) && type!=base) {
- if (type.findn(filter->get_text())!=-1) {
+ bool found = false;
+ String type = I->get();
+ while (type != "" && ClassDB::is_type(type, base) && type != base) {
+ if (type.findn(filter->get_text()) != -1) {
- found=true;
+ found = true;
break;
}
- type=ClassDB::type_inherits_from(type);
+ type = ClassDB::type_inherits_from(type);
}
-
if (found)
- add_type(I->get(),types,root);
+ add_type(I->get(), types, root);
}
if (EditorNode::get_editor_data().get_custom_types().has(type)) {
//there are custom types based on this... cool.
-
const Vector<EditorData::CustomType> &ct = EditorNode::get_editor_data().get_custom_types()[type];
- for(int i=0;i<ct.size();i++) {
+ for (int i = 0; i < ct.size(); i++) {
- bool show = filter->get_text()=="" || ct[i].name.findn(filter->get_text())!=-1;
+ bool show = filter->get_text() == "" || ct[i].name.findn(filter->get_text()) != -1;
if (!show)
continue;
if (!types.has(type))
- add_type(type,types,root);
+ add_type(type, types, root);
TreeItem *ti;
- if (types.has(type) )
- ti=types[type];
+ if (types.has(type))
+ ti = types[type];
else
- ti=tree->get_root();
-
+ ti = tree->get_root();
TreeItem *item = tree->create_item(ti);
- item->set_metadata(0,type);
- item->set_text(0,ct[i].name);
+ item->set_metadata(0, type);
+ item->set_text(0, ct[i].name);
if (ct[i].icon.is_valid()) {
- item->set_icon(0,ct[i].icon);
-
+ item->set_icon(0, ct[i].icon);
}
}
-
}
}
-
-
}
-
Object *CreateDialog::instance_selected() {
if (!tree->get_selected())
return NULL;
String base = String(tree->get_selected()->get_metadata(0));
- if (base!="") {
-
+ if (base != "") {
String name = tree->get_selected()->get_text(0);
if (EditorNode::get_editor_data().get_custom_types().has(base)) {
const Vector<EditorData::CustomType> &ct = EditorNode::get_editor_data().get_custom_types()[base];
- for(int i=0;i<ct.size();i++) {
+ for (int i = 0; i < ct.size(); i++) {
- if (ct[i].name==name) {
+ if (ct[i].name == name) {
- Object* obj = ClassDB::instance(base);
- ERR_FAIL_COND_V(!obj,NULL);
+ Object *obj = ClassDB::instance(base);
+ ERR_FAIL_COND_V(!obj, NULL);
obj->set_script(ct[i].script.get_ref_ptr());
if (ct[i].icon.is_valid())
- obj->set_meta("_editor_icon",ct[i].icon);
+ obj->set_meta("_editor_icon", ct[i].icon);
return obj;
-
-
}
}
}
ERR_FAIL_V(NULL);
-
}
return ClassDB::instance(tree->get_selected()->get_text(0));
-
}
-
void CreateDialog::_bind_methods() {
- ClassDB::bind_method("_create",&CreateDialog::_create);
- ClassDB::bind_method("_cancel",&CreateDialog::_cancel);
+ ClassDB::bind_method("_create", &CreateDialog::_create);
+ ClassDB::bind_method("_cancel", &CreateDialog::_cancel);
ClassDB::bind_method("_text_changed", &CreateDialog::_text_changed);
- ADD_SIGNAL( MethodInfo("create"));
-
+ ADD_SIGNAL(MethodInfo("create"));
}
+void CreateDialog::set_base_type(const String &p_base) {
+ set_title(vformat("Create %s Type", p_base));
-
-void CreateDialog::set_base_type(const String& p_base) {
-
- set_title(vformat("Create %s Type",p_base));
-
- if (base==p_base)
+ if (base == p_base)
return;
- base=p_base;
+ base = p_base;
if (is_inside_scene())
update_tree();
}
@@ -929,33 +861,26 @@ String CreateDialog::get_base_type() const {
CreateDialog::CreateDialog() {
-
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
-
get_ok()->set_text("Create");
- tree = memnew( Tree );
- vbc->add_margin_child("Type:",tree,true);
+ tree = memnew(Tree);
+ vbc->add_margin_child("Type:", tree, true);
//tree->set_hide_root(true);
- filter = memnew( LineEdit );
- vbc->add_margin_child("Filter:",filter);
+ filter = memnew(LineEdit);
+ vbc->add_margin_child("Filter:", filter);
- base="Node";
+ base = "Node";
set_as_toplevel(true);
-
tree->connect("item_activated", this, "_create");
- filter->connect("text_changed", this,"_text_changed");
-
+ filter->connect("text_changed", this, "_text_changed");
}
-
-CreateDialog::~CreateDialog()
-{
+CreateDialog::~CreateDialog() {
}
-
#endif
diff --git a/editor/create_dialog.h b/editor/create_dialog.h
index 5ecb4db2c3..aff6b9c62b 100644
--- a/editor/create_dialog.h
+++ b/editor/create_dialog.h
@@ -29,24 +29,22 @@
#ifndef CREATE_DIALOG_H
#define CREATE_DIALOG_H
-#include "scene/gui/dialogs.h"
+#include "editor_help.h"
#include "scene/gui/button.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/item_list.h"
-#include "scene/gui/line_edit.h"
#include "scene/gui/label.h"
-#include "editor_help.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/tree.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
#if 1
-
class CreateDialog : public ConfirmationDialog {
- GDCLASS(CreateDialog,ConfirmationDialog )
-
+ GDCLASS(CreateDialog, ConfirmationDialog)
Vector<String> favorite_list;
Tree *favorites;
@@ -72,74 +70,67 @@ class CreateDialog : public ConfirmationDialog {
void _history_activated();
void _favorite_activated();
- void _sbox_input(const InputEvent& p_ie);
+ void _sbox_input(const InputEvent &p_ie);
void _confirmed();
- void _text_changed(const String& p_newtext);
+ void _text_changed(const String &p_newtext);
- void add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root,TreeItem **to_select);
+ void add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem *p_root, TreeItem **to_select);
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
Object *instance_selected();
String get_selected_type();
- void set_base_type(const String& p_base);
+ void set_base_type(const String &p_base);
String get_base_type() const;
void popup(bool p_dontclear);
-
CreateDialog();
};
-
#else
//old create dialog, disabled
class CreateDialog : public ConfirmationDialog {
- GDCLASS( CreateDialog, ConfirmationDialog );
+ GDCLASS(CreateDialog, ConfirmationDialog);
Tree *tree;
Button *create;
Button *cancel;
LineEdit *filter;
-
void update_tree();
void _create();
void _cancel();
- void add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem
- *p_root);
+ void add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem
+ *p_root);
String base;
void _text_changed(String p_text);
- virtual void _post_popup() { tree->grab_focus();}
+ virtual void _post_popup() { tree->grab_focus(); }
protected:
static void _bind_methods();
void _notification(int p_what);
-public:
-
-
+public:
Object *instance_selected();
- void set_base_type(const String& p_base);
+ void set_base_type(const String &p_base);
String get_base_type() const;
CreateDialog();
~CreateDialog();
-
};
#endif
diff --git a/editor/dependency_editor.cpp b/editor/dependency_editor.cpp
index d7e04db86e..64c3cc1c00 100644
--- a/editor/dependency_editor.cpp
+++ b/editor/dependency_editor.cpp
@@ -28,53 +28,49 @@
/*************************************************************************/
#include "dependency_editor.h"
+#include "editor_node.h"
+#include "io/resource_loader.h"
#include "os/file_access.h"
#include "scene/gui/margin_container.h"
-#include "io/resource_loader.h"
-#include "editor_node.h"
-
-void DependencyEditor::_notification(int p_what){
-
+void DependencyEditor::_notification(int p_what) {
}
-void DependencyEditor::_searched(const String& p_path) {
+void DependencyEditor::_searched(const String &p_path) {
- Map<String,String> dep_rename;
- dep_rename[replacing]=p_path;
+ Map<String, String> dep_rename;
+ dep_rename[replacing] = p_path;
-
- ResourceLoader::rename_dependencies(editing,dep_rename);
+ ResourceLoader::rename_dependencies(editing, dep_rename);
_update_list();
_update_file();
}
-void DependencyEditor::_load_pressed(Object* p_item,int p_cell,int p_button){
+void DependencyEditor::_load_pressed(Object *p_item, int p_cell, int p_button) {
- TreeItem *ti=p_item->cast_to<TreeItem>();
+ TreeItem *ti = p_item->cast_to<TreeItem>();
String fname = ti->get_text(0);
replacing = ti->get_text(1);
- search->set_title(TTR("Search Replacement For:")+" "+replacing.get_file());
+ search->set_title(TTR("Search Replacement For:") + " " + replacing.get_file());
search->clear_filters();
List<String> ext;
- ResourceLoader::get_recognized_extensions_for_type(ti->get_metadata(0),&ext);
- for (List<String>::Element *E=ext.front();E;E=E->next()) {
- search->add_filter("*"+E->get());
+ ResourceLoader::get_recognized_extensions_for_type(ti->get_metadata(0), &ext);
+ for (List<String>::Element *E = ext.front(); E; E = E->next()) {
+ search->add_filter("*" + E->get());
}
search->popup_centered_ratio();
-
}
-void DependencyEditor::_fix_and_find(EditorFileSystemDirectory *efsd, Map<String,Map<String,String> >& candidates){
+void DependencyEditor::_fix_and_find(EditorFileSystemDirectory *efsd, Map<String, Map<String, String> > &candidates) {
- for(int i=0;i<efsd->get_subdir_count();i++) {
- _fix_and_find(efsd->get_subdir(i),candidates);
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
+ _fix_and_find(efsd->get_subdir(i), candidates);
}
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
String file = efsd->get_file(i);
if (!candidates.has(file))
@@ -82,34 +78,34 @@ void DependencyEditor::_fix_and_find(EditorFileSystemDirectory *efsd, Map<String
String path = efsd->get_file_path(i);
- for(Map<String,String>::Element *E=candidates[file].front();E;E=E->next()) {
+ for (Map<String, String>::Element *E = candidates[file].front(); E; E = E->next()) {
- if (E->get()==String()) {
- E->get()=path;
+ if (E->get() == String()) {
+ E->get() = path;
continue;
}
//must match the best, using subdirs
- String existing=E->get().replace_first("res://","");
- String current=path.replace_first("res://","");
- String lost=E->key().replace_first("res://","");
+ String existing = E->get().replace_first("res://", "");
+ String current = path.replace_first("res://", "");
+ String lost = E->key().replace_first("res://", "");
- Vector<String> existingv=existing.split("/");
+ Vector<String> existingv = existing.split("/");
existingv.invert();
- Vector<String> currentv=current.split("/");
+ Vector<String> currentv = current.split("/");
currentv.invert();
- Vector<String> lostv=lost.split("/");
+ Vector<String> lostv = lost.split("/");
lostv.invert();
- int existing_score=0;
- int current_score=0;
+ int existing_score = 0;
+ int current_score = 0;
- for(int j=0;j<lostv.size();j++) {
+ for (int j = 0; j < lostv.size(); j++) {
- if (j<existingv.size() && lostv[j]==existingv[j]) {
+ if (j < existingv.size() && lostv[j] == existingv[j]) {
existing_score++;
}
- if (j<currentv.size() && lostv[j]==currentv[j]) {
+ if (j < currentv.size() && lostv[j] == currentv[j]) {
current_score++;
}
}
@@ -118,51 +114,46 @@ void DependencyEditor::_fix_and_find(EditorFileSystemDirectory *efsd, Map<String
//if it was the same, could track distance to new path but..
- E->get()=path; //replace by more accurate
+ E->get() = path; //replace by more accurate
}
-
}
-
}
-
}
-
-void DependencyEditor::_fix_all(){
+void DependencyEditor::_fix_all() {
if (!EditorFileSystem::get_singleton()->get_filesystem())
return;
- Map<String,Map<String,String> > candidates;
+ Map<String, Map<String, String> > candidates;
- for (List<String>::Element *E=missing.front();E;E=E->next()) {
+ for (List<String>::Element *E = missing.front(); E; E = E->next()) {
String base = E->get().get_file();
if (!candidates.has(base)) {
- candidates[base]=Map<String,String>();
+ candidates[base] = Map<String, String>();
}
- candidates[base][E->get()]="";
+ candidates[base][E->get()] = "";
}
- _fix_and_find(EditorFileSystem::get_singleton()->get_filesystem(),candidates);
+ _fix_and_find(EditorFileSystem::get_singleton()->get_filesystem(), candidates);
- Map<String,String> remaps;
+ Map<String, String> remaps;
- for (Map<String,Map<String,String> >::Element *E=candidates.front();E;E=E->next()) {
+ for (Map<String, Map<String, String> >::Element *E = candidates.front(); E; E = E->next()) {
- for (Map<String,String>::Element *F=E->get().front();F;F=F->next()) {
+ for (Map<String, String>::Element *F = E->get().front(); F; F = F->next()) {
- if (F->get()!=String()) {
- remaps[F->key()]=F->get();
+ if (F->get() != String()) {
+ remaps[F->key()] = F->get();
}
}
-
}
if (remaps.size()) {
- ResourceLoader::rename_dependencies(editing,remaps);
+ ResourceLoader::rename_dependencies(editing, remaps);
_update_list();
_update_file();
@@ -172,24 +163,23 @@ void DependencyEditor::_fix_all(){
void DependencyEditor::_update_file() {
EditorFileSystem::get_singleton()->update_file(editing);
-
}
void DependencyEditor::_update_list() {
List<String> deps;
- ResourceLoader::get_dependencies(editing,&deps,true);
+ ResourceLoader::get_dependencies(editing, &deps, true);
tree->clear();
missing.clear();
TreeItem *root = tree->create_item();
- Ref<Texture> folder = get_icon("folder","FileDialog");
+ Ref<Texture> folder = get_icon("folder", "FileDialog");
- bool broken=false;
+ bool broken = false;
- for(List<String>::Element *E=deps.front();E;E=E->next()) {
+ for (List<String>::Element *E = deps.front(); E; E = E->next()) {
TreeItem *item = tree->create_item(root);
@@ -197,129 +187,119 @@ void DependencyEditor::_update_list() {
String path;
String type;
- if (n.find("::")!=-1) {
- path = n.get_slice("::",0);
- type = n.get_slice("::",1);
+ if (n.find("::") != -1) {
+ path = n.get_slice("::", 0);
+ type = n.get_slice("::", 1);
} else {
- path=n;
- type="Resource";
+ path = n;
+ type = "Resource";
}
String name = path.get_file();
Ref<Texture> icon;
- if (has_icon(type,"EditorIcons")) {
- icon=get_icon(type,"EditorIcons");
+ if (has_icon(type, "EditorIcons")) {
+ icon = get_icon(type, "EditorIcons");
} else {
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
}
- item->set_text(0,name);
- item->set_icon(0,icon);
- item->set_metadata(0,type);
- item->set_text(1,path);
+ item->set_text(0, name);
+ item->set_icon(0, icon);
+ item->set_metadata(0, type);
+ item->set_text(1, path);
if (!FileAccess::exists(path)) {
- item->set_custom_color(1,Color(1,0.4,0.3));
+ item->set_custom_color(1, Color(1, 0.4, 0.3));
missing.push_back(path);
- broken=true;
+ broken = true;
}
- item->add_button(1,folder,0);
+ item->add_button(1, folder, 0);
}
fixdeps->set_disabled(!broken);
-
}
+void DependencyEditor::edit(const String &p_path) {
-
-void DependencyEditor::edit(const String& p_path) {
-
-
- editing=p_path;
- set_title(TTR("Dependencies For:")+" "+p_path.get_file());
+ editing = p_path;
+ set_title(TTR("Dependencies For:") + " " + p_path.get_file());
_update_list();
popup_centered_ratio();
if (EditorNode::get_singleton()->is_scene_open(p_path)) {
- EditorNode::get_singleton()->show_warning(vformat(TTR("Scene '%s' is currently being edited.\nChanges will not take effect unless reloaded."),p_path.get_file()));
+ EditorNode::get_singleton()->show_warning(vformat(TTR("Scene '%s' is currently being edited.\nChanges will not take effect unless reloaded."), p_path.get_file()));
} else if (ResourceCache::has(p_path)) {
- EditorNode::get_singleton()->show_warning(vformat(TTR("Resource '%s' is in use.\nChanges will take effect when reloaded."),p_path.get_file()));
+ EditorNode::get_singleton()->show_warning(vformat(TTR("Resource '%s' is in use.\nChanges will take effect when reloaded."), p_path.get_file()));
}
}
-
void DependencyEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_searched"),&DependencyEditor::_searched);
- ClassDB::bind_method(D_METHOD("_load_pressed"),&DependencyEditor::_load_pressed);
- ClassDB::bind_method(D_METHOD("_fix_all"),&DependencyEditor::_fix_all);
-
+ ClassDB::bind_method(D_METHOD("_searched"), &DependencyEditor::_searched);
+ ClassDB::bind_method(D_METHOD("_load_pressed"), &DependencyEditor::_load_pressed);
+ ClassDB::bind_method(D_METHOD("_fix_all"), &DependencyEditor::_fix_all);
}
DependencyEditor::DependencyEditor() {
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
vb->set_name(TTR("Dependencies"));
add_child(vb);
-
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_columns(2);
tree->set_column_titles_visible(true);
- tree->set_column_title(0,TTR("Resource"));
- tree->set_column_title(1,TTR("Path"));
+ tree->set_column_title(0, TTR("Resource"));
+ tree->set_column_title(1, TTR("Path"));
tree->set_hide_root(true);
- tree->connect("button_pressed",this,"_load_pressed");
+ tree->connect("button_pressed", this, "_load_pressed");
- HBoxContainer *hbc = memnew( HBoxContainer );
- Label *label = memnew( Label(TTR("Dependencies:")));
+ HBoxContainer *hbc = memnew(HBoxContainer);
+ Label *label = memnew(Label(TTR("Dependencies:")));
hbc->add_child(label);
hbc->add_spacer();
- fixdeps = memnew( Button(TTR("Fix Broken")));
+ fixdeps = memnew(Button(TTR("Fix Broken")));
hbc->add_child(fixdeps);
- fixdeps->connect("pressed",this,"_fix_all");
+ fixdeps->connect("pressed", this, "_fix_all");
vb->add_child(hbc);
- MarginContainer *mc = memnew( MarginContainer );
+ MarginContainer *mc = memnew(MarginContainer);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
mc->add_child(tree);
vb->add_child(mc);
set_title(TTR("Dependency Editor"));
- search = memnew( EditorFileDialog );
- search->connect("file_selected",this,"_searched");
+ search = memnew(EditorFileDialog);
+ search->connect("file_selected", this, "_searched");
search->set_mode(EditorFileDialog::MODE_OPEN_FILE);
search->set_title(TTR("Search Replacement Resource:"));
add_child(search);
-
}
/////////////////////////////////////
-
-
void DependencyEditorOwners::_fill_owners(EditorFileSystemDirectory *efsd) {
if (!efsd)
return;
- for(int i=0;i<efsd->get_subdir_count();i++) {
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
_fill_owners(efsd->get_subdir(i));
}
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
Vector<String> deps = efsd->get_file_deps(i);
//print_line(":::"+efsd->get_file_path(i));
- bool found=false;
- for(int j=0;j<deps.size();j++) {
+ bool found = false;
+ for (int j = 0; j < deps.size(); j++) {
//print_line("\t"+deps[j]+" vs "+editing);
- if (deps[j]==editing) {
+ if (deps[j] == editing) {
//print_line("found");
- found=true;
+ found = true;
break;
}
}
@@ -327,57 +307,50 @@ void DependencyEditorOwners::_fill_owners(EditorFileSystemDirectory *efsd) {
continue;
Ref<Texture> icon;
- String type=efsd->get_file_type(i);
- if (!has_icon(type,"EditorIcons")) {
- icon=get_icon("Object","EditorIcons");
+ String type = efsd->get_file_type(i);
+ if (!has_icon(type, "EditorIcons")) {
+ icon = get_icon("Object", "EditorIcons");
} else {
- icon=get_icon(type,"EditorIcons");
+ icon = get_icon(type, "EditorIcons");
}
- owners->add_item(efsd->get_file_path(i),icon);
+ owners->add_item(efsd->get_file_path(i), icon);
}
-
}
-void DependencyEditorOwners::show(const String& p_path) {
+void DependencyEditorOwners::show(const String &p_path) {
- editing=p_path;
+ editing = p_path;
owners->clear();
_fill_owners(EditorFileSystem::get_singleton()->get_filesystem());
popup_centered_ratio();
- set_title(TTR("Owners Of:")+" "+p_path.get_file());
-
+ set_title(TTR("Owners Of:") + " " + p_path.get_file());
}
DependencyEditorOwners::DependencyEditorOwners() {
-
- owners = memnew( ItemList );
+ owners = memnew(ItemList);
add_child(owners);
-
-
-
}
///////////////////////
-
void DependencyRemoveDialog::_fill_owners(EditorFileSystemDirectory *efsd) {
if (!efsd)
return;
- for(int i=0;i<efsd->get_subdir_count();i++) {
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
_fill_owners(efsd->get_subdir(i));
}
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
Vector<String> deps = efsd->get_file_deps(i);
//print_line(":::"+efsd->get_file_path(i));
Set<String> met;
- for(int j=0;j<deps.size();j++) {
+ for (int j = 0; j < deps.size(); j++) {
if (files.has(deps[j])) {
met.insert(deps[j]);
}
@@ -385,65 +358,58 @@ void DependencyRemoveDialog::_fill_owners(EditorFileSystemDirectory *efsd) {
if (!met.size())
continue;
- exist=true;
+ exist = true;
Ref<Texture> icon;
- String type=efsd->get_file_type(i);
- if (!has_icon(type,"EditorIcons")) {
- icon=get_icon("Object","EditorIcons");
+ String type = efsd->get_file_type(i);
+ if (!has_icon(type, "EditorIcons")) {
+ icon = get_icon("Object", "EditorIcons");
} else {
- icon=get_icon(type,"EditorIcons");
+ icon = get_icon(type, "EditorIcons");
}
-
- for(Set<String>::Element *E=met.front();E;E=E->next()) {
+ for (Set<String>::Element *E = met.front(); E; E = E->next()) {
String which = E->get();
if (!files[which]) {
- TreeItem *ti=owners->create_item(owners->get_root());
- ti->set_text(0,which.get_file());
- files[which]=ti;
-
+ TreeItem *ti = owners->create_item(owners->get_root());
+ ti->set_text(0, which.get_file());
+ files[which] = ti;
}
- TreeItem *ti=owners->create_item(files[which]);
- ti->set_text(0,efsd->get_file_path(i));
- ti->set_icon(0,icon);
+ TreeItem *ti = owners->create_item(files[which]);
+ ti->set_text(0, efsd->get_file_path(i));
+ ti->set_icon(0, icon);
}
-
}
-
}
void DependencyRemoveDialog::show(const Vector<String> &to_erase) {
- exist=false;
+ exist = false;
owners->clear();
files.clear();
owners->create_item(); // root
- for(int i=0;i<to_erase.size();i++) {
- files[to_erase[i]]=NULL;
+ for (int i = 0; i < to_erase.size(); i++) {
+ files[to_erase[i]] = NULL;
}
_fill_owners(EditorFileSystem::get_singleton()->get_filesystem());
-
if (exist) {
owners->show();
text->set_text(TTR("The files being removed are required by other resources in order for them to work.\nRemove them anyway? (no undo)"));
- popup_centered_minsize(Size2(500,220));
+ popup_centered_minsize(Size2(500, 220));
} else {
owners->hide();
text->set_text(TTR("Remove selected files from the project? (no undo)"));
- popup_centered_minsize(Size2(400,100));
+ popup_centered_minsize(Size2(400, 100));
}
-
}
void DependencyRemoveDialog::ok_pressed() {
-
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- for (Map<String,TreeItem*>::Element *E=files.front();E;E=E->next()) {
+ for (Map<String, TreeItem *>::Element *E = files.front(); E; E = E->next()) {
if (ResourceCache::has(E->key())) {
Resource *res = ResourceCache::get(E->key());
@@ -453,225 +419,202 @@ void DependencyRemoveDialog::ok_pressed() {
EditorFileSystem::get_singleton()->update_file(E->key());
}
memdelete(da);
-
}
DependencyRemoveDialog::DependencyRemoveDialog() {
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
-
- text = memnew( Label );
+ text = memnew(Label);
vb->add_child(text);
- owners = memnew( Tree );
+ owners = memnew(Tree);
owners->set_hide_root(true);
vb->add_child(owners);
owners->set_v_size_flags(SIZE_EXPAND_FILL);
get_ok()->set_text(TTR("Remove"));
}
-
//////////////
+void DependencyErrorDialog::show(const String &p_for_file, const Vector<String> &report) {
-void DependencyErrorDialog::show(const String& p_for_file,const Vector<String> &report) {
-
-
- for_file=p_for_file;
- set_title(TTR("Error loading:")+" "+p_for_file.get_file());
+ for_file = p_for_file;
+ set_title(TTR("Error loading:") + " " + p_for_file.get_file());
files->clear();
TreeItem *root = files->create_item(NULL);
- for(int i=0;i<report.size();i++) {
+ for (int i = 0; i < report.size(); i++) {
String dep;
- String type="Object";
- dep=report[i].get_slice("::",0);
- if (report[i].get_slice_count("::")>0)
- type=report[i].get_slice("::",1);
+ String type = "Object";
+ dep = report[i].get_slice("::", 0);
+ if (report[i].get_slice_count("::") > 0)
+ type = report[i].get_slice("::", 1);
Ref<Texture> icon;
- if (!has_icon(type,"EditorIcons")) {
- icon=get_icon("Object","EditorIcons");
+ if (!has_icon(type, "EditorIcons")) {
+ icon = get_icon("Object", "EditorIcons");
} else {
- icon=get_icon(type,"EditorIcons");
+ icon = get_icon(type, "EditorIcons");
}
- TreeItem *ti=files->create_item(root);
- ti->set_text(0,dep);
- ti->set_icon(0,icon);
-
+ TreeItem *ti = files->create_item(root);
+ ti->set_text(0, dep);
+ ti->set_icon(0, icon);
}
- popup_centered_minsize(Size2(500,220));
-
+ popup_centered_minsize(Size2(500, 220));
}
void DependencyErrorDialog::ok_pressed() {
- EditorNode::get_singleton()->load_scene(for_file,true);
+ EditorNode::get_singleton()->load_scene(for_file, true);
}
-void DependencyErrorDialog::custom_action(const String&) {
+void DependencyErrorDialog::custom_action(const String &) {
EditorNode::get_singleton()->fix_dependencies(for_file);
}
DependencyErrorDialog::DependencyErrorDialog() {
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
-
-
- files = memnew( Tree );
+ files = memnew(Tree);
files->set_hide_root(true);
- vb->add_margin_child(TTR("Scene failed to load due to missing dependencies:"),files,true);
+ vb->add_margin_child(TTR("Scene failed to load due to missing dependencies:"), files, true);
files->set_v_size_flags(SIZE_EXPAND_FILL);
get_ok()->set_text(TTR("Open Anyway"));
- text = memnew( Label );
+ text = memnew(Label);
vb->add_child(text);
text->set_text(TTR("Which action should be taken?"));
-
- fdep=add_button(TTR("Fix Dependencies"),true,"fixdeps");
+ fdep = add_button(TTR("Fix Dependencies"), true, "fixdeps");
set_title(TTR("Errors loading!"));
-
}
//////////////////////////////////////////////////////////////////////
-
-
void OrphanResourcesDialog::ok_pressed() {
paths.clear();
- _find_to_delete(files->get_root(),paths);
+ _find_to_delete(files->get_root(), paths);
if (paths.empty())
return;
- delete_confirm->set_text(vformat(TTR("Permanently delete %d item(s)? (No undo!)"),paths.size()));
+ delete_confirm->set_text(vformat(TTR("Permanently delete %d item(s)? (No undo!)"), paths.size()));
delete_confirm->popup_centered_minsize();
}
-bool OrphanResourcesDialog::_fill_owners(EditorFileSystemDirectory *efsd,HashMap<String,int>& refs,TreeItem* p_parent){
-
+bool OrphanResourcesDialog::_fill_owners(EditorFileSystemDirectory *efsd, HashMap<String, int> &refs, TreeItem *p_parent) {
if (!efsd)
return false;
- bool has_childs=false;
+ bool has_childs = false;
- for(int i=0;i<efsd->get_subdir_count();i++) {
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
- TreeItem *dir_item=NULL;
+ TreeItem *dir_item = NULL;
if (p_parent) {
dir_item = files->create_item(p_parent);
- dir_item->set_text(0,efsd->get_subdir(i)->get_name());
- dir_item->set_icon(0,get_icon("folder","FileDialog"));
-
+ dir_item->set_text(0, efsd->get_subdir(i)->get_name());
+ dir_item->set_icon(0, get_icon("folder", "FileDialog"));
}
- bool children = _fill_owners(efsd->get_subdir(i),refs,dir_item);
+ bool children = _fill_owners(efsd->get_subdir(i), refs, dir_item);
if (p_parent) {
if (!children) {
memdelete(dir_item);
} else {
- has_childs=true;
+ has_childs = true;
}
}
-
}
-
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
if (!p_parent) {
Vector<String> deps = efsd->get_file_deps(i);
//print_line(":::"+efsd->get_file_path(i));
- for(int j=0;j<deps.size();j++) {
+ for (int j = 0; j < deps.size(); j++) {
if (!refs.has(deps[j])) {
- refs[deps[j]]=1;
+ refs[deps[j]] = 1;
}
}
} else {
String path = efsd->get_file_path(i);
if (!refs.has(path)) {
- TreeItem *ti=files->create_item(p_parent);
- ti->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- ti->set_text(0,efsd->get_file(i));
- ti->set_editable(0,true);
+ TreeItem *ti = files->create_item(p_parent);
+ ti->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ ti->set_text(0, efsd->get_file(i));
+ ti->set_editable(0, true);
- String type=efsd->get_file_type(i);
+ String type = efsd->get_file_type(i);
Ref<Texture> icon;
- if (has_icon(type,"EditorIcons")) {
- icon=get_icon(type,"EditorIcons");
+ if (has_icon(type, "EditorIcons")) {
+ icon = get_icon(type, "EditorIcons");
} else {
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
}
- ti->set_icon(0,icon);
+ ti->set_icon(0, icon);
int ds = efsd->get_file_deps(i).size();
- ti->set_text(1,itos(ds));
+ ti->set_text(1, itos(ds));
if (ds) {
- ti->add_button(1,get_icon("Visible","EditorIcons"));
+ ti->add_button(1, get_icon("Visible", "EditorIcons"));
}
- ti->set_metadata(0,path);
- has_childs=true;
+ ti->set_metadata(0, path);
+ has_childs = true;
}
}
-
}
return has_childs;
}
-
void OrphanResourcesDialog::refresh() {
- HashMap<String,int> refs;
- _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(),refs,NULL);
+ HashMap<String, int> refs;
+ _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(), refs, NULL);
files->clear();
- TreeItem *root=files->create_item();
- _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(),refs,root);
+ TreeItem *root = files->create_item();
+ _fill_owners(EditorFileSystem::get_singleton()->get_filesystem(), refs, root);
}
-
-void OrphanResourcesDialog::show(){
+void OrphanResourcesDialog::show() {
refresh();
popup_centered_ratio();
}
+void OrphanResourcesDialog::_find_to_delete(TreeItem *p_item, List<String> &paths) {
-void OrphanResourcesDialog::_find_to_delete(TreeItem* p_item,List<String>& paths) {
+ while (p_item) {
- while(p_item) {
-
- if (p_item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK && p_item->is_checked(0)) {
+ if (p_item->get_cell_mode(0) == TreeItem::CELL_MODE_CHECK && p_item->is_checked(0)) {
paths.push_back(p_item->get_metadata(0));
}
if (p_item->get_children()) {
- _find_to_delete(p_item->get_children(),paths);
+ _find_to_delete(p_item->get_children(), paths);
}
- p_item=p_item->get_next();
+ p_item = p_item->get_next();
}
-
-
}
void OrphanResourcesDialog::_delete_confirm() {
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- for (List<String>::Element *E=paths.front();E;E=E->next()) {
+ for (List<String>::Element *E = paths.front(); E; E = E->next()) {
da->remove(E->get());
EditorFileSystem::get_singleton()->update_file(E->get());
@@ -680,46 +623,43 @@ void OrphanResourcesDialog::_delete_confirm() {
refresh();
}
-void OrphanResourcesDialog::_button_pressed(Object *p_item,int p_column, int p_id) {
+void OrphanResourcesDialog::_button_pressed(Object *p_item, int p_column, int p_id) {
- TreeItem *ti=p_item->cast_to<TreeItem>();
+ TreeItem *ti = p_item->cast_to<TreeItem>();
String path = ti->get_metadata(0);
dep_edit->edit(path);
-
}
void OrphanResourcesDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_delete_confirm"),&OrphanResourcesDialog::_delete_confirm);
- ClassDB::bind_method(D_METHOD("_button_pressed"),&OrphanResourcesDialog::_button_pressed);
-
+ ClassDB::bind_method(D_METHOD("_delete_confirm"), &OrphanResourcesDialog::_delete_confirm);
+ ClassDB::bind_method(D_METHOD("_button_pressed"), &OrphanResourcesDialog::_button_pressed);
}
-OrphanResourcesDialog::OrphanResourcesDialog(){
+OrphanResourcesDialog::OrphanResourcesDialog() {
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
- files = memnew( Tree );
+ files = memnew(Tree);
files->set_columns(2);
files->set_column_titles_visible(true);
- files->set_column_min_width(1,100);
- files->set_column_expand(0,true);
- files->set_column_expand(1,false);
- files->set_column_title(0,TTR("Resource"));
- files->set_column_title(1,TTR("Owns"));
+ files->set_column_min_width(1, 100);
+ files->set_column_expand(0, true);
+ files->set_column_expand(1, false);
+ files->set_column_title(0, TTR("Resource"));
+ files->set_column_title(1, TTR("Owns"));
files->set_hide_root(true);
- vbc->add_margin_child(TTR("Resources Without Explicit Ownership:"),files,true);
+ vbc->add_margin_child(TTR("Resources Without Explicit Ownership:"), files, true);
set_title(TTR("Orphan Resource Explorer"));
- delete_confirm = memnew( ConfirmationDialog );
+ delete_confirm = memnew(ConfirmationDialog);
delete_confirm->set_text(TTR("Delete selected files?"));
get_ok()->set_text(TTR("Delete"));
add_child(delete_confirm);
- dep_edit = memnew( DependencyEditor );
+ dep_edit = memnew(DependencyEditor);
add_child(dep_edit);
- files->connect("button_pressed",this,"_button_pressed");
- delete_confirm->connect("confirmed",this,"_delete_confirm");
+ files->connect("button_pressed", this, "_button_pressed");
+ delete_confirm->connect("confirmed", this, "_delete_confirm");
set_hide_on_ok(false);
-
}
diff --git a/editor/dependency_editor.h b/editor/dependency_editor.h
index a96ffe5fcf..bd0e1f8b07 100644
--- a/editor/dependency_editor.h
+++ b/editor/dependency_editor.h
@@ -29,16 +29,15 @@
#ifndef DEPENDENCY_EDITOR_H
#define DEPENDENCY_EDITOR_H
+#include "editor_file_dialog.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
#include "scene/gui/tab_container.h"
-#include "editor_file_dialog.h"
+#include "scene/gui/tree.h"
class EditorFileSystemDirectory;
class DependencyEditor : public AcceptDialog {
- GDCLASS(DependencyEditor,AcceptDialog);
-
+ GDCLASS(DependencyEditor, AcceptDialog);
Tree *tree;
Button *fixdeps;
@@ -49,97 +48,86 @@ class DependencyEditor : public AcceptDialog {
String editing;
List<String> missing;
+ void _fix_and_find(EditorFileSystemDirectory *efsd, Map<String, Map<String, String> > &candidates);
- void _fix_and_find(EditorFileSystemDirectory *efsd, Map<String,Map<String,String> >& candidates);
-
- void _searched(const String& p_path);
- void _load_pressed(Object* p_item,int p_cell,int p_button);
+ void _searched(const String &p_path);
+ void _load_pressed(Object *p_item, int p_cell, int p_button);
void _fix_all();
void _update_list();
void _update_file();
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
-
- void edit(const String& p_path);
+public:
+ void edit(const String &p_path);
DependencyEditor();
};
class DependencyEditorOwners : public AcceptDialog {
- GDCLASS(DependencyEditorOwners,AcceptDialog);
+ GDCLASS(DependencyEditorOwners, AcceptDialog);
ItemList *owners;
String editing;
void _fill_owners(EditorFileSystemDirectory *efsd);
public:
-
- void show(const String& p_path);
+ void show(const String &p_path);
DependencyEditorOwners();
};
class DependencyRemoveDialog : public ConfirmationDialog {
- GDCLASS(DependencyRemoveDialog,ConfirmationDialog);
-
+ GDCLASS(DependencyRemoveDialog, ConfirmationDialog);
Label *text;
Tree *owners;
bool exist;
- Map<String,TreeItem*> files;
+ Map<String, TreeItem *> files;
void _fill_owners(EditorFileSystemDirectory *efsd);
void ok_pressed();
public:
-
void show(const Vector<String> &to_erase);
DependencyRemoveDialog();
};
-
class DependencyErrorDialog : public ConfirmationDialog {
- GDCLASS(DependencyErrorDialog,ConfirmationDialog);
-
+ GDCLASS(DependencyErrorDialog, ConfirmationDialog);
String for_file;
Button *fdep;
Label *text;
Tree *files;
void ok_pressed();
- void custom_action(const String&);
+ void custom_action(const String &);
public:
-
- void show(const String& p_for,const Vector<String> &report);
+ void show(const String &p_for, const Vector<String> &report);
DependencyErrorDialog();
};
-
-
class OrphanResourcesDialog : public ConfirmationDialog {
- GDCLASS(OrphanResourcesDialog,ConfirmationDialog);
+ GDCLASS(OrphanResourcesDialog, ConfirmationDialog);
DependencyEditor *dep_edit;
Tree *files;
ConfirmationDialog *delete_confirm;
void ok_pressed();
- bool _fill_owners(EditorFileSystemDirectory *efsd, HashMap<String,int>& refs, TreeItem *p_parent);
+ bool _fill_owners(EditorFileSystemDirectory *efsd, HashMap<String, int> &refs, TreeItem *p_parent);
List<String> paths;
- void _find_to_delete(TreeItem* p_item,List<String>& paths);
+ void _find_to_delete(TreeItem *p_item, List<String> &paths);
void _delete_confirm();
- void _button_pressed(Object *p_item,int p_column, int p_id);
+ void _button_pressed(Object *p_item, int p_column, int p_id);
void refresh();
static void _bind_methods();
-public:
+public:
void show();
OrphanResourcesDialog();
};
diff --git a/editor/doc/doc_data.cpp b/editor/doc/doc_data.cpp
index 47b8edfa04..4f1b85f236 100644
--- a/editor/doc/doc_data.cpp
+++ b/editor/doc/doc_data.cpp
@@ -28,18 +28,17 @@
/*************************************************************************/
#include "doc_data.h"
-#include "version.h"
-#include "global_constants.h"
#include "global_config.h"
-#include "script_language.h"
-#include "io/marshalls.h"
+#include "global_constants.h"
#include "io/compression.h"
+#include "io/marshalls.h"
#include "scene/resources/theme.h"
+#include "script_language.h"
+#include "version.h"
-void DocData::merge_from(const DocData& p_data) {
-
- for( Map<String,ClassDoc>::Element *E=class_list.front();E;E=E->next()) {
+void DocData::merge_from(const DocData &p_data) {
+ for (Map<String, ClassDoc>::Element *E = class_list.front(); E; E = E->next()) {
ClassDoc &c = E->get();
@@ -48,25 +47,26 @@ void DocData::merge_from(const DocData& p_data) {
const ClassDoc &cf = p_data.class_list[c.name];
- c.description=cf.description;
- c.brief_description=cf.brief_description;
+ c.description = cf.description;
+ c.brief_description = cf.brief_description;
- for(int i=0;i<c.methods.size();i++) {
+ for (int i = 0; i < c.methods.size(); i++) {
MethodDoc &m = c.methods[i];
- for(int j=0;j<cf.methods.size();j++) {
+ for (int j = 0; j < cf.methods.size(); j++) {
- if (cf.methods[j].name!=m.name)
+ if (cf.methods[j].name != m.name)
continue;
- if (cf.methods[j].arguments.size()!=m.arguments.size())
+ if (cf.methods[j].arguments.size() != m.arguments.size())
continue;
// since polymorphic functions are allowed we need to check the type of
// the arguments so we make sure they are different.
int arg_count = cf.methods[j].arguments.size();
Vector<bool> arg_used;
arg_used.resize(arg_count);
- for (int l = 0; l < arg_count; ++l) arg_used[l] = false;
+ for (int l = 0; l < arg_count; ++l)
+ arg_used[l] = false;
// also there is no guarantee that argument ordering will match, so we
// have to check one by one so we make sure we have an exact match
for (int k = 0; k < arg_count; ++k) {
@@ -85,234 +85,225 @@ void DocData::merge_from(const DocData& p_data) {
const MethodDoc &mf = cf.methods[j];
- m.description=mf.description;
+ m.description = mf.description;
break;
}
}
-
- for(int i=0;i<c.signals.size();i++) {
+ for (int i = 0; i < c.signals.size(); i++) {
MethodDoc &m = c.signals[i];
- for(int j=0;j<cf.signals.size();j++) {
+ for (int j = 0; j < cf.signals.size(); j++) {
- if (cf.signals[j].name!=m.name)
+ if (cf.signals[j].name != m.name)
continue;
const MethodDoc &mf = cf.signals[j];
- m.description=mf.description;
+ m.description = mf.description;
break;
}
}
- for(int i=0;i<c.constants.size();i++) {
+ for (int i = 0; i < c.constants.size(); i++) {
ConstantDoc &m = c.constants[i];
- for(int j=0;j<cf.constants.size();j++) {
+ for (int j = 0; j < cf.constants.size(); j++) {
- if (cf.constants[j].name!=m.name)
+ if (cf.constants[j].name != m.name)
continue;
const ConstantDoc &mf = cf.constants[j];
- m.description=mf.description;
+ m.description = mf.description;
break;
}
}
- for(int i=0;i<c.properties.size();i++) {
+ for (int i = 0; i < c.properties.size(); i++) {
PropertyDoc &p = c.properties[i];
- for(int j=0;j<cf.properties.size();j++) {
+ for (int j = 0; j < cf.properties.size(); j++) {
- if (cf.properties[j].name!=p.name)
+ if (cf.properties[j].name != p.name)
continue;
const PropertyDoc &pf = cf.properties[j];
- p.description=pf.description;
- p.setter=pf.setter;
- p.getter=pf.getter;
+ p.description = pf.description;
+ p.setter = pf.setter;
+ p.getter = pf.getter;
break;
}
}
- for(int i=0;i<c.theme_properties.size();i++) {
+ for (int i = 0; i < c.theme_properties.size(); i++) {
PropertyDoc &p = c.theme_properties[i];
- for(int j=0;j<cf.theme_properties.size();j++) {
+ for (int j = 0; j < cf.theme_properties.size(); j++) {
- if (cf.theme_properties[j].name!=p.name)
+ if (cf.theme_properties[j].name != p.name)
continue;
const PropertyDoc &pf = cf.theme_properties[j];
- p.description=pf.description;
+ p.description = pf.description;
break;
}
}
-
}
-
}
void DocData::remove_from(const DocData &p_data) {
- for(Map<String,ClassDoc>::Element* E=p_data.class_list.front(); E; E=E->next()) {
- if(class_list.has(E->key()))
+ for (Map<String, ClassDoc>::Element *E = p_data.class_list.front(); E; E = E->next()) {
+ if (class_list.has(E->key()))
class_list.erase(E->key());
}
}
void DocData::generate(bool p_basic_types) {
-
List<StringName> classes;
ClassDB::get_class_list(&classes);
classes.sort_custom<StringName::AlphCompare>();
- while(classes.size()) {
+ while (classes.size()) {
- String name=classes.front()->get();
- String cname=name;
+ String name = classes.front()->get();
+ String cname = name;
if (cname.begins_with("_")) //proxy class
- cname=cname.substr(1,name.length());
-
- class_list[cname]=ClassDoc();
- ClassDoc& c = class_list[cname];
- c.name=cname;
- c.inherits=ClassDB::get_parent_class(name);
- c.category=ClassDB::get_category(name);
+ cname = cname.substr(1, name.length());
+ class_list[cname] = ClassDoc();
+ ClassDoc &c = class_list[cname];
+ c.name = cname;
+ c.inherits = ClassDB::get_parent_class(name);
+ c.category = ClassDB::get_category(name);
List<PropertyInfo> properties;
- ClassDB::get_property_list(name,&properties,true);
+ ClassDB::get_property_list(name, &properties, true);
- for(List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
- if (E->get().usage& PROPERTY_USAGE_GROUP || E->get().usage& PROPERTY_USAGE_CATEGORY)
+ for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
+ if (E->get().usage & PROPERTY_USAGE_GROUP || E->get().usage & PROPERTY_USAGE_CATEGORY)
continue;
PropertyDoc prop;
- StringName setter = ClassDB::get_property_setter(name,E->get().name);
- StringName getter = ClassDB::get_property_getter(name,E->get().name);
-
- prop.name=E->get().name;
- prop.setter=setter;
- prop.getter=getter;
- if (E->get().type==Variant::OBJECT && E->get().hint==PROPERTY_HINT_RESOURCE_TYPE)
- prop.type=E->get().hint_string;
+ StringName setter = ClassDB::get_property_setter(name, E->get().name);
+ StringName getter = ClassDB::get_property_getter(name, E->get().name);
+
+ prop.name = E->get().name;
+ prop.setter = setter;
+ prop.getter = getter;
+ if (E->get().type == Variant::OBJECT && E->get().hint == PROPERTY_HINT_RESOURCE_TYPE)
+ prop.type = E->get().hint_string;
else
- prop.type=Variant::get_type_name(E->get().type);
+ prop.type = Variant::get_type_name(E->get().type);
c.properties.push_back(prop);
}
-
List<MethodInfo> method_list;
- ClassDB::get_method_list(name,&method_list,true);
+ ClassDB::get_method_list(name, &method_list, true);
method_list.sort();
+ for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
- for(List<MethodInfo>::Element *E=method_list.front();E;E=E->next()) {
-
- if (E->get().name=="" || (E->get().name[0]=='_' && !(E->get().flags&METHOD_FLAG_VIRTUAL)))
+ if (E->get().name == "" || (E->get().name[0] == '_' && !(E->get().flags & METHOD_FLAG_VIRTUAL)))
continue; //hiden, dont count
MethodDoc method;
- method.name=E->get().name;
-
- MethodBind *m = ClassDB::get_method(name,E->get().name);
+ method.name = E->get().name;
+ MethodBind *m = ClassDB::get_method(name, E->get().name);
- if (E->get().flags&METHOD_FLAG_VIRTUAL)
- method.qualifiers="virtual";
- if (E->get().flags&METHOD_FLAG_CONST) {
- if (method.qualifiers!="")
- method.qualifiers+=" ";
- method.qualifiers+="const";
+ if (E->get().flags & METHOD_FLAG_VIRTUAL)
+ method.qualifiers = "virtual";
+ if (E->get().flags & METHOD_FLAG_CONST) {
+ if (method.qualifiers != "")
+ method.qualifiers += " ";
+ method.qualifiers += "const";
- } else if (E->get().flags&METHOD_FLAG_VARARG) {
- if (method.qualifiers!="")
- method.qualifiers+=" ";
- method.qualifiers+="vararg";
+ } else if (E->get().flags & METHOD_FLAG_VARARG) {
+ if (method.qualifiers != "")
+ method.qualifiers += " ";
+ method.qualifiers += "vararg";
}
- for(int i=-1;i<E->get().arguments.size();i++) {
+ for (int i = -1; i < E->get().arguments.size(); i++) {
PropertyInfo arginfo;
- if (i==-1) {
+ if (i == -1) {
-
- arginfo=E->get().return_val;
+ arginfo = E->get().return_val;
#ifdef DEBUG_METHODS_ENABLED
- if (m && m->get_return_type()!=StringName())
- method.return_type=m->get_return_type();
- else if (method.name.find(":")!=-1) {
- method.return_type=method.name.get_slice(":",1);
- method.name=method.name.get_slice(":",0);
+ if (m && m->get_return_type() != StringName())
+ method.return_type = m->get_return_type();
+ else if (method.name.find(":") != -1) {
+ method.return_type = method.name.get_slice(":", 1);
+ method.name = method.name.get_slice(":", 0);
- } else if (arginfo.type!=Variant::NIL) // {
+ } else if (arginfo.type != Variant::NIL) // {
#endif
- method.return_type=(arginfo.hint==PROPERTY_HINT_RESOURCE_TYPE)?arginfo.hint_string:Variant::get_type_name(arginfo.type);
+ method.return_type = (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) ? arginfo.hint_string : Variant::get_type_name(arginfo.type);
//}
} else {
ArgumentDoc argument;
- arginfo=E->get().arguments[i];
+ arginfo = E->get().arguments[i];
String type_name;
- if (arginfo.name.find(":")!=-1) {
- type_name=arginfo.name.get_slice(":",1);
- arginfo.name=arginfo.name.get_slice(":",0);
+ if (arginfo.name.find(":") != -1) {
+ type_name = arginfo.name.get_slice(":", 1);
+ arginfo.name = arginfo.name.get_slice(":", 0);
- } else if (arginfo.hint==PROPERTY_HINT_RESOURCE_TYPE) {
- type_name=arginfo.hint_string;
- } else if (arginfo.type==Variant::NIL)
- type_name="Variant";
+ } else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ type_name = arginfo.hint_string;
+ } else if (arginfo.type == Variant::NIL)
+ type_name = "Variant";
else
- type_name=Variant::get_type_name(arginfo.type);
+ type_name = Variant::get_type_name(arginfo.type);
- if (arginfo.type==Variant::OBJECT) {
+ if (arginfo.type == Variant::OBJECT) {
//print_line("validate: "+cname+"::"+method.name);
}
if (m && m->has_default_argument(i)) {
- Variant default_arg=m->get_default_argument(i);
- String default_arg_text=m->get_default_argument(i);
+ Variant default_arg = m->get_default_argument(i);
+ String default_arg_text = m->get_default_argument(i);
- switch(default_arg.get_type()) {
+ switch (default_arg.get_type()) {
case Variant::NIL:
- default_arg_text="NULL";
+ default_arg_text = "NULL";
break;
// atomic types
case Variant::BOOL:
if (bool(default_arg))
- default_arg_text="true";
+ default_arg_text = "true";
else
- default_arg_text="false";
+ default_arg_text = "false";
break;
case Variant::INT:
case Variant::REAL:
//keep it
break;
- case Variant::STRING: // 15
- case Variant::NODE_PATH: // 15
- default_arg_text="\""+default_arg_text+"\"";
+ case Variant::STRING: // 15
+ case Variant::NODE_PATH: // 15
+ default_arg_text = "\"" + default_arg_text + "\"";
break;
case Variant::TRANSFORM:
- if (default_arg.operator Transform()==Transform()) {
- default_arg_text="";
+ if (default_arg.operator Transform() == Transform()) {
+ default_arg_text = "";
}
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"("+default_arg_text+")";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
break;
case Variant::RECT3: //sorry naming convention fail :( not like it's used often // 10
@@ -321,48 +312,46 @@ void DocData::generate(bool p_basic_types) {
case Variant::POOL_BYTE_ARRAY:
case Variant::POOL_INT_ARRAY:
case Variant::POOL_REAL_ARRAY:
- case Variant::POOL_STRING_ARRAY: //25
+ case Variant::POOL_STRING_ARRAY: //25
case Variant::POOL_VECTOR2_ARRAY:
case Variant::POOL_VECTOR3_ARRAY:
case Variant::POOL_COLOR_ARRAY:
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"("+default_arg_text+")";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
break;
- case Variant::VECTOR2: // 5
+ case Variant::VECTOR2: // 5
case Variant::RECT2:
case Variant::VECTOR3:
case Variant::QUAT:
case Variant::BASIS:
- default_arg_text=Variant::get_type_name(default_arg.get_type())+default_arg_text;
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + default_arg_text;
break;
case Variant::OBJECT:
if (default_arg.is_zero()) {
- default_arg_text="NULL";
+ default_arg_text = "NULL";
break;
}
case Variant::INPUT_EVENT:
- case Variant::DICTIONARY: // 20
+ case Variant::DICTIONARY: // 20
case Variant::ARRAY:
case Variant::_RID:
case Variant::IMAGE:
- //case Variant::RESOURCE:
+ //case Variant::RESOURCE:
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"()";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "()";
break;
default: {}
-
}
-
- argument.type=type_name;
- argument.name=arginfo.name;
- argument.default_value=default_arg_text;
+ argument.type = type_name;
+ argument.name = arginfo.name;
+ argument.default_value = default_arg_text;
} else {
- argument.type=type_name;
- argument.name=arginfo.name;
+ argument.type = type_name;
+ argument.name = arginfo.name;
}
- if (arginfo.type==Variant::OBJECT) {
+ if (arginfo.type == Variant::OBJECT) {
//print_line("validate: "+cname+"::"+method.name);
}
@@ -370,7 +359,7 @@ void DocData::generate(bool p_basic_types) {
method.arguments.push_back(argument);
}
-/*
+ /*
String hint;
switch(arginfo.hint) {
case PROPERTY_HINT_DIR: hint="A directory."; break;
@@ -384,46 +373,41 @@ void DocData::generate(bool p_basic_types) {
if (hint!="")
_write_string(f,4,hint);
*/
-
-
}
c.methods.push_back(method);
}
List<MethodInfo> signal_list;
- ClassDB::get_signal_list(name,&signal_list,true);
+ ClassDB::get_signal_list(name, &signal_list, true);
if (signal_list.size()) {
-
- for(List<MethodInfo>::Element *EV=signal_list.front();EV;EV=EV->next()) {
+ for (List<MethodInfo>::Element *EV = signal_list.front(); EV; EV = EV->next()) {
MethodDoc signal;
- signal.name=EV->get().name;
- for(int i=0;i<EV->get().arguments.size();i++) {
+ signal.name = EV->get().name;
+ for (int i = 0; i < EV->get().arguments.size(); i++) {
- PropertyInfo arginfo=EV->get().arguments[i];
+ PropertyInfo arginfo = EV->get().arguments[i];
ArgumentDoc argument;
- argument.name=arginfo.name;
- argument.type=Variant::get_type_name(arginfo.type);
+ argument.name = arginfo.name;
+ argument.type = Variant::get_type_name(arginfo.type);
signal.arguments.push_back(argument);
}
c.signals.push_back(signal);
}
-
-
}
List<String> constant_list;
ClassDB::get_integer_constant_list(name, &constant_list, true);
- for(List<String>::Element *E=constant_list.front();E;E=E->next()) {
+ for (List<String>::Element *E = constant_list.front(); E; E = E->next()) {
ConstantDoc constant;
- constant.name=E->get();
- constant.value=itos(ClassDB::get_integer_constant(name, E->get()));
+ constant.name = E->get();
+ constant.value = itos(ClassDB::get_integer_constant(name, E->get()));
c.constants.push_back(constant);
}
@@ -431,187 +415,179 @@ void DocData::generate(bool p_basic_types) {
{
List<StringName> l;
- Theme::get_default()->get_constant_list(cname,&l);
- for (List<StringName>::Element*E=l.front();E;E=E->next()) {
+ Theme::get_default()->get_constant_list(cname, &l);
+ for (List<StringName>::Element *E = l.front(); E; E = E->next()) {
PropertyDoc pd;
- pd.name=E->get();
- pd.type="int";
+ pd.name = E->get();
+ pd.type = "int";
c.theme_properties.push_back(pd);
}
l.clear();
- Theme::get_default()->get_color_list(cname,&l);
- for (List<StringName>::Element*E=l.front();E;E=E->next()) {
+ Theme::get_default()->get_color_list(cname, &l);
+ for (List<StringName>::Element *E = l.front(); E; E = E->next()) {
PropertyDoc pd;
- pd.name=E->get();
- pd.type="Color";
+ pd.name = E->get();
+ pd.type = "Color";
c.theme_properties.push_back(pd);
}
l.clear();
- Theme::get_default()->get_icon_list(cname,&l);
- for (List<StringName>::Element*E=l.front();E;E=E->next()) {
+ Theme::get_default()->get_icon_list(cname, &l);
+ for (List<StringName>::Element *E = l.front(); E; E = E->next()) {
PropertyDoc pd;
- pd.name=E->get();
- pd.type="Texture";
+ pd.name = E->get();
+ pd.type = "Texture";
c.theme_properties.push_back(pd);
}
l.clear();
- Theme::get_default()->get_font_list(cname,&l);
- for (List<StringName>::Element*E=l.front();E;E=E->next()) {
+ Theme::get_default()->get_font_list(cname, &l);
+ for (List<StringName>::Element *E = l.front(); E; E = E->next()) {
PropertyDoc pd;
- pd.name=E->get();
- pd.type="Font";
+ pd.name = E->get();
+ pd.type = "Font";
c.theme_properties.push_back(pd);
}
l.clear();
- Theme::get_default()->get_stylebox_list(cname,&l);
- for (List<StringName>::Element*E=l.front();E;E=E->next()) {
+ Theme::get_default()->get_stylebox_list(cname, &l);
+ for (List<StringName>::Element *E = l.front(); E; E = E->next()) {
PropertyDoc pd;
- pd.name=E->get();
- pd.type="StyleBox";
+ pd.name = E->get();
+ pd.type = "StyleBox";
c.theme_properties.push_back(pd);
}
-
}
-
classes.pop_front();
}
-
{
//so it can be documented that it does not exist
- class_list["Variant"]=ClassDoc();
- class_list["Variant"].name="Variant";
+ class_list["Variant"] = ClassDoc();
+ class_list["Variant"].name = "Variant";
}
if (!p_basic_types)
return;
- for (int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (i==Variant::OBJECT)
+ if (i == Variant::OBJECT)
continue; //use the core type instead
- int loops=1;
+ int loops = 1;
- if (i==Variant::INPUT_EVENT)
- loops=InputEvent::TYPE_MAX;
+ if (i == Variant::INPUT_EVENT)
+ loops = InputEvent::TYPE_MAX;
- for(int j=0;j<loops;j++) {
+ for (int j = 0; j < loops; j++) {
- String cname=Variant::get_type_name(Variant::Type(i));
+ String cname = Variant::get_type_name(Variant::Type(i));
- if (i==Variant::INPUT_EVENT) {
- static const char* ie_type[InputEvent::TYPE_MAX]={
- "","Key","MouseMotion","MouseButton","JoypadMotion","JoypadButton","ScreenTouch","ScreenDrag","Action"
+ if (i == Variant::INPUT_EVENT) {
+ static const char *ie_type[InputEvent::TYPE_MAX] = {
+ "", "Key", "MouseMotion", "MouseButton", "JoypadMotion", "JoypadButton", "ScreenTouch", "ScreenDrag", "Action"
};
- cname+=ie_type[j];
+ cname += ie_type[j];
}
-
- class_list[cname]=ClassDoc();
- ClassDoc& c = class_list[cname];
- c.name=cname;
- c.category="Built-In Types";
+ class_list[cname] = ClassDoc();
+ ClassDoc &c = class_list[cname];
+ c.name = cname;
+ c.category = "Built-In Types";
Variant::CallError cerror;
- Variant v=Variant::construct(Variant::Type(i),NULL,0,cerror);
+ Variant v = Variant::construct(Variant::Type(i), NULL, 0, cerror);
- if (i==Variant::INPUT_EVENT) {
- v.set("type",j);
+ if (i == Variant::INPUT_EVENT) {
+ v.set("type", j);
}
List<MethodInfo> method_list;
v.get_method_list(&method_list);
method_list.sort();
- Variant::get_constructor_list(Variant::Type(i),&method_list);
+ Variant::get_constructor_list(Variant::Type(i), &method_list);
+ for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
- for(List<MethodInfo>::Element *E=method_list.front();E;E=E->next()) {
-
- MethodInfo &mi=E->get();
+ MethodInfo &mi = E->get();
MethodDoc method;
- method.name=mi.name;
+ method.name = mi.name;
- for(int i=0;i<mi.arguments.size();i++) {
+ for (int i = 0; i < mi.arguments.size(); i++) {
ArgumentDoc arg;
- PropertyInfo pi=mi.arguments[i];
+ PropertyInfo pi = mi.arguments[i];
- arg.name=pi.name;
+ arg.name = pi.name;
//print_line("arg name: "+arg.name);
- if (pi.type==Variant::NIL)
- arg.type="var";
+ if (pi.type == Variant::NIL)
+ arg.type = "var";
else
- arg.type=Variant::get_type_name(pi.type);
+ arg.type = Variant::get_type_name(pi.type);
int defarg = mi.default_arguments.size() - mi.arguments.size() + i;
- if (defarg >=0)
- arg.default_value=mi.default_arguments[defarg];
+ if (defarg >= 0)
+ arg.default_value = mi.default_arguments[defarg];
method.arguments.push_back(arg);
}
- if (mi.return_val.type==Variant::NIL) {
- if (mi.return_val.name!="")
- method.return_type="var";
+ if (mi.return_val.type == Variant::NIL) {
+ if (mi.return_val.name != "")
+ method.return_type = "var";
} else {
- method.return_type=Variant::get_type_name(mi.return_val.type);
+ method.return_type = Variant::get_type_name(mi.return_val.type);
}
c.methods.push_back(method);
}
-
List<PropertyInfo> properties;
v.get_property_list(&properties);
- for(List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
- PropertyInfo pi=E->get();
+ PropertyInfo pi = E->get();
PropertyDoc property;
- property.name=pi.name;
- property.type=Variant::get_type_name(pi.type);
+ property.name = pi.name;
+ property.type = Variant::get_type_name(pi.type);
c.properties.push_back(property);
}
List<StringName> constants;
- Variant::get_numeric_constants_for_type(Variant::Type(i),&constants);
+ Variant::get_numeric_constants_for_type(Variant::Type(i), &constants);
- for(List<StringName>::Element *E=constants.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = constants.front(); E; E = E->next()) {
ConstantDoc constant;
- constant.name=E->get();
- constant.value=itos(Variant::get_numeric_constant_value(Variant::Type(i),E->get()));
+ constant.name = E->get();
+ constant.value = itos(Variant::get_numeric_constant_value(Variant::Type(i), E->get()));
c.constants.push_back(constant);
}
}
-
}
//built in constants and functions
{
- String cname="@Global Scope";
- class_list[cname]=ClassDoc();
- ClassDoc& c = class_list[cname];
- c.name=cname;
-
+ String cname = "@Global Scope";
+ class_list[cname] = ClassDoc();
+ ClassDoc &c = class_list[cname];
+ c.name = cname;
- for(int i=0;i<GlobalConstants::get_global_constant_count();i++) {
+ for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
ConstantDoc cd;
- cd.name=GlobalConstants::get_global_constant_name(i);
- cd.value=itos(GlobalConstants::get_global_constant_value(i));
+ cd.name = GlobalConstants::get_global_constant_name(i);
+ cd.value = itos(GlobalConstants::get_global_constant_value(i));
c.constants.push_back(cd);
}
@@ -619,524 +595,495 @@ void DocData::generate(bool p_basic_types) {
GlobalConfig::get_singleton()->get_singletons(&singletons);
//servers (this is kind of hackish)
- for(List<GlobalConfig::Singleton>::Element *E=singletons.front();E;E=E->next()) {
+ for (List<GlobalConfig::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
PropertyDoc pd;
- GlobalConfig::Singleton &s=E->get();
- pd.name=s.name;
- pd.type=s.ptr->get_class();
- while (String(ClassDB::get_parent_class(pd.type))!="Object")
- pd.type=ClassDB::get_parent_class(pd.type);
+ GlobalConfig::Singleton &s = E->get();
+ pd.name = s.name;
+ pd.type = s.ptr->get_class();
+ while (String(ClassDB::get_parent_class(pd.type)) != "Object")
+ pd.type = ClassDB::get_parent_class(pd.type);
if (pd.type.begins_with("_"))
- pd.type=pd.type.substr(1,pd.type.length());
+ pd.type = pd.type.substr(1, pd.type.length());
c.properties.push_back(pd);
-
}
-
}
//built in script reference
{
-
- for(int i=0;i<ScriptServer::get_language_count();i++) {
-
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptLanguage *lang = ScriptServer::get_language(i);
- String cname="@"+lang->get_name();
- class_list[cname]=ClassDoc();
- ClassDoc& c = class_list[cname];
- c.name=cname;
+ String cname = "@" + lang->get_name();
+ class_list[cname] = ClassDoc();
+ ClassDoc &c = class_list[cname];
+ c.name = cname;
List<MethodInfo> minfo;
lang->get_public_functions(&minfo);
+ for (List<MethodInfo>::Element *E = minfo.front(); E; E = E->next()) {
- for(List<MethodInfo>::Element *E=minfo.front();E;E=E->next()) {
-
- MethodInfo &mi=E->get();
+ MethodInfo &mi = E->get();
MethodDoc md;
- md.name=mi.name;
- if (mi.return_val.name!="")
- md.return_type=mi.return_val.name;
- else if (mi.name.find(":")!=-1) {
- md.return_type=mi.name.get_slice(":",1);
- md.name=mi.name.get_slice(":",0);
+ md.name = mi.name;
+ if (mi.return_val.name != "")
+ md.return_type = mi.return_val.name;
+ else if (mi.name.find(":") != -1) {
+ md.return_type = mi.name.get_slice(":", 1);
+ md.name = mi.name.get_slice(":", 0);
} else
- md.return_type=Variant::get_type_name(mi.return_val.type);
+ md.return_type = Variant::get_type_name(mi.return_val.type);
- for(int i=0;i<mi.arguments.size();i++) {
+ for (int i = 0; i < mi.arguments.size(); i++) {
- PropertyInfo &pi=mi.arguments[i];
+ PropertyInfo &pi = mi.arguments[i];
ArgumentDoc ad;
- ad.name=pi.name;
+ ad.name = pi.name;
-
- if (pi.type==Variant::NIL)
- ad.type="Variant";
+ if (pi.type == Variant::NIL)
+ ad.type = "Variant";
else
- ad.type=Variant::get_type_name( pi.type );
+ ad.type = Variant::get_type_name(pi.type);
md.arguments.push_back(ad);
}
c.methods.push_back(md);
-
}
- List<Pair<String,Variant> > cinfo;
+ List<Pair<String, Variant> > cinfo;
lang->get_public_constants(&cinfo);
-
- for(List<Pair<String,Variant> >::Element *E=cinfo.front();E;E=E->next()) {
+ for (List<Pair<String, Variant> >::Element *E = cinfo.front(); E; E = E->next()) {
ConstantDoc cd;
- cd.name=E->get().first;
- cd.value=E->get().second;
+ cd.name = E->get().first;
+ cd.value = E->get().second;
c.constants.push_back(cd);
}
}
}
-
-
}
+static Error _parse_methods(Ref<XMLParser> &parser, Vector<DocData::MethodDoc> &methods) {
-static Error _parse_methods(Ref<XMLParser>& parser,Vector<DocData::MethodDoc>& methods) {
-
- String section=parser->get_node_name();
- String element=section.substr(0,section.length()-1);
+ String section = parser->get_node_name();
+ String element = section.substr(0, section.length() - 1);
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
- if (parser->get_node_name()==element) {
+ if (parser->get_node_name() == element) {
DocData::MethodDoc method;
- ERR_FAIL_COND_V(!parser->has_attribute("name"),ERR_FILE_CORRUPT);
- method.name=parser->get_attribute_value("name");
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ method.name = parser->get_attribute_value("name");
if (parser->has_attribute("qualifiers"))
- method.qualifiers=parser->get_attribute_value("qualifiers");
-
+ method.qualifiers = parser->get_attribute_value("qualifiers");
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
- String name=parser->get_node_name();
- if (name=="return") {
+ String name = parser->get_node_name();
+ if (name == "return") {
- ERR_FAIL_COND_V(!parser->has_attribute("type"),ERR_FILE_CORRUPT);
- method.return_type=parser->get_attribute_value("type");
- } else if (name=="argument") {
+ ERR_FAIL_COND_V(!parser->has_attribute("type"), ERR_FILE_CORRUPT);
+ method.return_type = parser->get_attribute_value("type");
+ } else if (name == "argument") {
DocData::ArgumentDoc argument;
- ERR_FAIL_COND_V(!parser->has_attribute("name"),ERR_FILE_CORRUPT);
- argument.name=parser->get_attribute_value("name");
- ERR_FAIL_COND_V(!parser->has_attribute("type"),ERR_FILE_CORRUPT);
- argument.type=parser->get_attribute_value("type");
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ argument.name = parser->get_attribute_value("name");
+ ERR_FAIL_COND_V(!parser->has_attribute("type"), ERR_FILE_CORRUPT);
+ argument.type = parser->get_attribute_value("type");
method.arguments.push_back(argument);
- } else if (name=="description") {
+ } else if (name == "description") {
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- method.description=parser->get_node_data().strip_edges();
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ method.description = parser->get_node_data().strip_edges();
}
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()==element)
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == element)
break;
}
methods.push_back(method);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: "+parser->get_node_name());
+ ERR_EXPLAIN("Invalid tag in doc file: " + parser->get_node_name());
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()==section)
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == section)
break;
}
return OK;
}
-Error DocData::load(const String& p_path) {
+Error DocData::load(const String &p_path) {
- Ref<XMLParser> parser=memnew(XMLParser);
+ Ref<XMLParser> parser = memnew(XMLParser);
Error err = parser->open(p_path);
if (err)
return err;
return _load(parser);
-
}
Error DocData::_load(Ref<XMLParser> parser) {
- Error err=OK;
+ Error err = OK;
- while((err=parser->read())==OK) {
+ while ((err = parser->read()) == OK) {
if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
if (parser->get_node_name() == "doc") {
break;
} else if (!parser->is_empty())
- parser->skip_section();// unknown section, likely headers
+ parser->skip_section(); // unknown section, likely headers
}
}
if (parser->has_attribute("version"))
- version=parser->get_attribute_value("version");
-
-
- while((err=parser->read())==OK) {
+ version = parser->get_attribute_value("version");
+ while ((err = parser->read()) == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()=="doc")
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "doc")
break; //end of <doc>
if (parser->get_node_type() != XMLParser::NODE_ELEMENT)
continue; //no idea what this may be, but skipping anyway
- ERR_FAIL_COND_V( parser->get_node_name()!="class", ERR_FILE_CORRUPT );
+ ERR_FAIL_COND_V(parser->get_node_name() != "class", ERR_FILE_CORRUPT);
- ERR_FAIL_COND_V( !parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
String name = parser->get_attribute_value("name");
- class_list[name]=ClassDoc();
- ClassDoc& c = class_list[name];
+ class_list[name] = ClassDoc();
+ ClassDoc &c = class_list[name];
//print_line("class: "+name);
- c.name=name;
+ c.name = name;
if (parser->has_attribute("inherits"))
c.inherits = parser->get_attribute_value("inherits");
if (parser->has_attribute("category"))
c.category = parser->get_attribute_value("category");
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser->get_node_name();
- if (name=="brief_description") {
+ if (name == "brief_description") {
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- c.brief_description=parser->get_node_data().strip_edges();
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ c.brief_description = parser->get_node_data().strip_edges();
- } else if (name=="description") {
+ } else if (name == "description") {
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- c.description=parser->get_node_data().strip_edges();
- } else if (name=="methods") {
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ c.description = parser->get_node_data().strip_edges();
+ } else if (name == "methods") {
- Error err = _parse_methods(parser,c.methods);
- ERR_FAIL_COND_V(err,err);
+ Error err = _parse_methods(parser, c.methods);
+ ERR_FAIL_COND_V(err, err);
- } else if (name=="signals") {
+ } else if (name == "signals") {
- Error err = _parse_methods(parser,c.signals);
- ERR_FAIL_COND_V(err,err);
- } else if (name=="members") {
+ Error err = _parse_methods(parser, c.signals);
+ ERR_FAIL_COND_V(err, err);
+ } else if (name == "members") {
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser->get_node_name();
- if (name=="member") {
+ if (name == "member") {
PropertyDoc prop;
- ERR_FAIL_COND_V(!parser->has_attribute("name"),ERR_FILE_CORRUPT);
- prop.name=parser->get_attribute_value("name");
- ERR_FAIL_COND_V(!parser->has_attribute("type"),ERR_FILE_CORRUPT);
- prop.type=parser->get_attribute_value("type");
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ prop.name = parser->get_attribute_value("name");
+ ERR_FAIL_COND_V(!parser->has_attribute("type"), ERR_FILE_CORRUPT);
+ prop.type = parser->get_attribute_value("type");
if (parser->has_attribute("setter"))
- prop.setter=parser->get_attribute_value("setter");
+ prop.setter = parser->get_attribute_value("setter");
if (parser->has_attribute("getter"))
- prop.getter=parser->get_attribute_value("getter");
+ prop.getter = parser->get_attribute_value("getter");
if (parser->has_attribute("brief"))
- prop.brief_description=parser->get_attribute_value("brief").xml_unescape();
+ prop.brief_description = parser->get_attribute_value("brief").xml_unescape();
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- prop.description=parser->get_node_data().strip_edges();
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ prop.description = parser->get_node_data().strip_edges();
c.properties.push_back(prop);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: "+name);
+ ERR_EXPLAIN("Invalid tag in doc file: " + name);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()=="members")
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "members")
break; //end of <constants>
}
- } else if (name=="theme_items") {
+ } else if (name == "theme_items") {
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
String name = parser->get_node_name();
- if (name=="theme_item") {
+ if (name == "theme_item") {
PropertyDoc prop;
- ERR_FAIL_COND_V(!parser->has_attribute("name"),ERR_FILE_CORRUPT);
- prop.name=parser->get_attribute_value("name");
- ERR_FAIL_COND_V(!parser->has_attribute("type"),ERR_FILE_CORRUPT);
- prop.type=parser->get_attribute_value("type");
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ prop.name = parser->get_attribute_value("name");
+ ERR_FAIL_COND_V(!parser->has_attribute("type"), ERR_FILE_CORRUPT);
+ prop.type = parser->get_attribute_value("type");
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- prop.description=parser->get_node_data().strip_edges();
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ prop.description = parser->get_node_data().strip_edges();
c.theme_properties.push_back(prop);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: "+name);
+ ERR_EXPLAIN("Invalid tag in doc file: " + name);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()=="theme_items")
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "theme_items")
break; //end of <constants>
}
- } else if (name=="constants") {
+ } else if (name == "constants") {
- while(parser->read()==OK) {
+ while (parser->read() == OK) {
- if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
+ if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
- String name=parser->get_node_name();
+ String name = parser->get_node_name();
- if (name=="constant") {
+ if (name == "constant") {
ConstantDoc constant;
- ERR_FAIL_COND_V(!parser->has_attribute("name"),ERR_FILE_CORRUPT);
- constant.name=parser->get_attribute_value("name");
- ERR_FAIL_COND_V(!parser->has_attribute("value"),ERR_FILE_CORRUPT);
- constant.value=parser->get_attribute_value("value");
+ ERR_FAIL_COND_V(!parser->has_attribute("name"), ERR_FILE_CORRUPT);
+ constant.name = parser->get_attribute_value("name");
+ ERR_FAIL_COND_V(!parser->has_attribute("value"), ERR_FILE_CORRUPT);
+ constant.value = parser->get_attribute_value("value");
parser->read();
- if (parser->get_node_type()==XMLParser::NODE_TEXT)
- constant.description=parser->get_node_data().strip_edges();
+ if (parser->get_node_type() == XMLParser::NODE_TEXT)
+ constant.description = parser->get_node_data().strip_edges();
c.constants.push_back(constant);
} else {
- ERR_EXPLAIN("Invalid tag in doc file: "+name);
+ ERR_EXPLAIN("Invalid tag in doc file: " + name);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()=="constants")
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "constants")
break; //end of <constants>
}
} else {
- ERR_EXPLAIN("Invalid tag in doc file: "+name);
+ ERR_EXPLAIN("Invalid tag in doc file: " + name);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
-
- } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name()=="class")
+ } else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name() == "class")
break; //end of <asset>
}
-
-
}
return OK;
}
-
-static void _write_string(FileAccess *f,int p_tablevel,const String& p_string) {
+static void _write_string(FileAccess *f, int p_tablevel, const String &p_string) {
String tab;
- for(int i=0;i<p_tablevel;i++) tab+="\t";
- f->store_string(tab+p_string+"\n");
+ for (int i = 0; i < p_tablevel; i++)
+ tab += "\t";
+ f->store_string(tab + p_string + "\n");
}
-Error DocData::save(const String& p_path) {
+Error DocData::save(const String &p_path) {
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::WRITE,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
- ERR_EXPLAIN("Can't write doc file: "+p_path);
+ ERR_EXPLAIN("Can't write doc file: " + p_path);
ERR_FAIL_V(err);
-
}
- _write_string(f,0,"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
- _write_string(f,0,"<doc version=\""+String(VERSION_MKSTRING)+"\" name=\"Engine Types\">");
-
- for( Map<String,ClassDoc>::Element *E=class_list.front();E;E=E->next()) {
-
- ClassDoc &c=E->get();
-
- String header="<class name=\""+c.name+"\"";
- if (c.inherits!="")
- header+=" inherits=\""+c.inherits+"\"";
-
- String category=c.category;
- if (c.category=="")
- category="Core";
- header+=" category=\""+category+"\"";
- header+=">";
- _write_string(f,0,header);
- _write_string(f,1,"<brief_description>");
- if (c.brief_description!="")
- _write_string(f,2,c.brief_description.xml_escape());
- _write_string(f,1,"</brief_description>");
- _write_string(f,1,"<description>");
- if (c.description!="")
- _write_string(f,2,c.description.xml_escape());
- _write_string(f,1,"</description>");
- _write_string(f,1,"<methods>");
+ _write_string(f, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ _write_string(f, 0, "<doc version=\"" + String(VERSION_MKSTRING) + "\" name=\"Engine Types\">");
+
+ for (Map<String, ClassDoc>::Element *E = class_list.front(); E; E = E->next()) {
+
+ ClassDoc &c = E->get();
+
+ String header = "<class name=\"" + c.name + "\"";
+ if (c.inherits != "")
+ header += " inherits=\"" + c.inherits + "\"";
+
+ String category = c.category;
+ if (c.category == "")
+ category = "Core";
+ header += " category=\"" + category + "\"";
+ header += ">";
+ _write_string(f, 0, header);
+ _write_string(f, 1, "<brief_description>");
+ if (c.brief_description != "")
+ _write_string(f, 2, c.brief_description.xml_escape());
+ _write_string(f, 1, "</brief_description>");
+ _write_string(f, 1, "<description>");
+ if (c.description != "")
+ _write_string(f, 2, c.description.xml_escape());
+ _write_string(f, 1, "</description>");
+ _write_string(f, 1, "<methods>");
c.methods.sort();
- for(int i=0;i<c.methods.size();i++) {
+ for (int i = 0; i < c.methods.size(); i++) {
- MethodDoc &m=c.methods[i];
+ MethodDoc &m = c.methods[i];
String qualifiers;
- if (m.qualifiers!="")
- qualifiers+=" qualifiers=\""+m.qualifiers.xml_escape()+"\"";
+ if (m.qualifiers != "")
+ qualifiers += " qualifiers=\"" + m.qualifiers.xml_escape() + "\"";
- _write_string(f,2,"<method name=\""+m.name+"\""+qualifiers+">");
+ _write_string(f, 2, "<method name=\"" + m.name + "\"" + qualifiers + ">");
- if (m.return_type!="") {
+ if (m.return_type != "") {
- _write_string(f,3,"<return type=\""+m.return_type+"\">");
- _write_string(f,3,"</return>");
+ _write_string(f, 3, "<return type=\"" + m.return_type + "\">");
+ _write_string(f, 3, "</return>");
}
- for(int j=0;j<m.arguments.size();j++) {
+ for (int j = 0; j < m.arguments.size(); j++) {
ArgumentDoc &a = m.arguments[j];
- if (a.default_value!="")
- _write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\" default=\""+a.default_value.xml_escape(true)+"\">");
+ if (a.default_value != "")
+ _write_string(f, 3, "<argument index=\"" + itos(j) + "\" name=\"" + a.name.xml_escape() + "\" type=\"" + a.type.xml_escape() + "\" default=\"" + a.default_value.xml_escape(true) + "\">");
else
- _write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\">");
-
- _write_string(f,3,"</argument>");
+ _write_string(f, 3, "<argument index=\"" + itos(j) + "\" name=\"" + a.name.xml_escape() + "\" type=\"" + a.type.xml_escape() + "\">");
+ _write_string(f, 3, "</argument>");
}
- _write_string(f,3,"<description>");
- if (m.description!="")
- _write_string(f,4,m.description.xml_escape());
- _write_string(f,3,"</description>");
-
- _write_string(f,2,"</method>");
+ _write_string(f, 3, "<description>");
+ if (m.description != "")
+ _write_string(f, 4, m.description.xml_escape());
+ _write_string(f, 3, "</description>");
+ _write_string(f, 2, "</method>");
}
- _write_string(f,1,"</methods>");
+ _write_string(f, 1, "</methods>");
if (c.properties.size()) {
- _write_string(f,1,"<members>");
+ _write_string(f, 1, "<members>");
c.properties.sort();
- for(int i=0;i<c.properties.size();i++) {
-
-
- PropertyDoc &p=c.properties[i];
- _write_string(f,2,"<member name=\""+p.name+"\" type=\""+p.type+"\" setter=\""+p.setter+"\" getter=\""+p.getter+"\" brief=\""+p.brief_description.xml_escape(true)+"\">");
- if (p.description!="")
- _write_string(f,3,p.description.xml_escape());
- _write_string(f,2,"</member>");
+ for (int i = 0; i < c.properties.size(); i++) {
+ PropertyDoc &p = c.properties[i];
+ _write_string(f, 2, "<member name=\"" + p.name + "\" type=\"" + p.type + "\" setter=\"" + p.setter + "\" getter=\"" + p.getter + "\" brief=\"" + p.brief_description.xml_escape(true) + "\">");
+ if (p.description != "")
+ _write_string(f, 3, p.description.xml_escape());
+ _write_string(f, 2, "</member>");
}
- _write_string(f,1,"</members>");
+ _write_string(f, 1, "</members>");
}
if (c.signals.size()) {
c.signals.sort();
- _write_string(f,1,"<signals>");
- for(int i=0;i<c.signals.size();i++) {
+ _write_string(f, 1, "<signals>");
+ for (int i = 0; i < c.signals.size(); i++) {
- MethodDoc &m=c.signals[i];
- _write_string(f,2,"<signal name=\""+m.name+"\">");
- for(int j=0;j<m.arguments.size();j++) {
+ MethodDoc &m = c.signals[i];
+ _write_string(f, 2, "<signal name=\"" + m.name + "\">");
+ for (int j = 0; j < m.arguments.size(); j++) {
ArgumentDoc &a = m.arguments[j];
- _write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\">");
- _write_string(f,3,"</argument>");
-
+ _write_string(f, 3, "<argument index=\"" + itos(j) + "\" name=\"" + a.name.xml_escape() + "\" type=\"" + a.type.xml_escape() + "\">");
+ _write_string(f, 3, "</argument>");
}
- _write_string(f,3,"<description>");
- if (m.description!="")
- _write_string(f,4,m.description.xml_escape());
- _write_string(f,3,"</description>");
+ _write_string(f, 3, "<description>");
+ if (m.description != "")
+ _write_string(f, 4, m.description.xml_escape());
+ _write_string(f, 3, "</description>");
- _write_string(f,2,"</signal>");
+ _write_string(f, 2, "</signal>");
}
- _write_string(f,1,"</signals>");
+ _write_string(f, 1, "</signals>");
}
- _write_string(f,1,"<constants>");
+ _write_string(f, 1, "<constants>");
+ for (int i = 0; i < c.constants.size(); i++) {
- for(int i=0;i<c.constants.size();i++) {
-
- ConstantDoc &k=c.constants[i];
- _write_string(f,2,"<constant name=\""+k.name+"\" value=\""+k.value+"\">");
- if (k.description!="")
- _write_string(f,3,k.description.xml_escape());
- _write_string(f,2,"</constant>");
+ ConstantDoc &k = c.constants[i];
+ _write_string(f, 2, "<constant name=\"" + k.name + "\" value=\"" + k.value + "\">");
+ if (k.description != "")
+ _write_string(f, 3, k.description.xml_escape());
+ _write_string(f, 2, "</constant>");
}
- _write_string(f,1,"</constants>");
+ _write_string(f, 1, "</constants>");
if (c.theme_properties.size()) {
c.theme_properties.sort();
- _write_string(f,1,"<theme_items>");
- for(int i=0;i<c.theme_properties.size();i++) {
-
-
- PropertyDoc &p=c.theme_properties[i];
- _write_string(f,2,"<theme_item name=\""+p.name+"\" type=\""+p.type+"\">");
- _write_string(f,2,"</theme_item>");
+ _write_string(f, 1, "<theme_items>");
+ for (int i = 0; i < c.theme_properties.size(); i++) {
+ PropertyDoc &p = c.theme_properties[i];
+ _write_string(f, 2, "<theme_item name=\"" + p.name + "\" type=\"" + p.type + "\">");
+ _write_string(f, 2, "</theme_item>");
}
- _write_string(f,1,"</theme_items>");
+ _write_string(f, 1, "</theme_items>");
}
- _write_string(f,0,"</class>");
-
+ _write_string(f, 0, "</class>");
}
- _write_string(f,0,"</doc>");
+ _write_string(f, 0, "</doc>");
f->close();
memdelete(f);
return OK;
}
-
Error DocData::load_compressed(const uint8_t *p_data, int p_compressed_size, int p_uncompressed_size) {
Vector<uint8_t> data;
data.resize(p_uncompressed_size);
- Compression::decompress(data.ptr(),p_uncompressed_size,p_data,p_compressed_size,Compression::MODE_DEFLATE);
+ Compression::decompress(data.ptr(), p_uncompressed_size, p_data, p_compressed_size, Compression::MODE_DEFLATE);
class_list.clear();
- Ref<XMLParser> parser = memnew( XMLParser );
+ Ref<XMLParser> parser = memnew(XMLParser);
Error err = parser->open_buffer(data);
if (err)
return err;
@@ -1144,5 +1091,4 @@ Error DocData::load_compressed(const uint8_t *p_data, int p_compressed_size, int
_load(parser);
return OK;
-
}
diff --git a/editor/doc/doc_data.h b/editor/doc/doc_data.h
index 7601013979..b4bd63e6ee 100644
--- a/editor/doc/doc_data.h
+++ b/editor/doc/doc_data.h
@@ -29,12 +29,11 @@
#ifndef DOC_DATA_H
#define DOC_DATA_H
-
-#include "variant.h"
-#include "map.h"
#include "io/xml_parser.h"
+#include "map.h"
+#include "variant.h"
-class DocData {
+class DocData {
public:
struct ArgumentDoc {
@@ -50,8 +49,8 @@ public:
String qualifiers;
String description;
Vector<ArgumentDoc> arguments;
- bool operator<(const MethodDoc& p_md) const {
- return name<p_md.name;
+ bool operator<(const MethodDoc &p_md) const {
+ return name < p_md.name;
}
};
@@ -68,13 +67,13 @@ public:
String type;
String brief_description;
String description;
- String setter,getter;
- bool operator<(const PropertyDoc& p_prop) const {
- return name<p_prop.name;
+ String setter, getter;
+ bool operator<(const PropertyDoc &p_prop) const {
+ return name < p_prop.name;
}
};
- struct ClassDoc {
+ struct ClassDoc {
String name;
String inherits;
@@ -86,26 +85,21 @@ public:
Vector<ConstantDoc> constants;
Vector<PropertyDoc> properties;
Vector<PropertyDoc> theme_properties;
-
};
String version;
- Map<String,ClassDoc> class_list;
+ Map<String, ClassDoc> class_list;
Error _load(Ref<XMLParser> parser);
-
public:
-
- void merge_from(const DocData& p_data);
- void remove_from(const DocData& p_data);
- void generate(bool p_basic_types=false);
- Error load(const String& p_path);
- Error save(const String& p_path);
+ void merge_from(const DocData &p_data);
+ void remove_from(const DocData &p_data);
+ void generate(bool p_basic_types = false);
+ Error load(const String &p_path);
+ Error save(const String &p_path);
Error load_compressed(const uint8_t *p_data, int p_compressed_size, int p_uncompressed_size);
-
-
};
#endif // DOC_DATA_H
diff --git a/editor/doc/doc_dump.cpp b/editor/doc/doc_dump.cpp
index 5ebba596e9..38b61d706d 100644
--- a/editor/doc/doc_dump.cpp
+++ b/editor/doc/doc_dump.cpp
@@ -28,162 +28,155 @@
/*************************************************************************/
#include "doc_dump.h"
-#include "version.h"
#include "os/file_access.h"
#include "scene/main/node.h"
+#include "version.h"
-
-static void _write_string(FileAccess *f,int p_tablevel,const String& p_string) {
+static void _write_string(FileAccess *f, int p_tablevel, const String &p_string) {
String tab;
- for(int i=0;i<p_tablevel;i++) tab+="\t";
- f->store_string(tab+p_string+"\n");
+ for (int i = 0; i < p_tablevel; i++)
+ tab += "\t";
+ f->store_string(tab + p_string + "\n");
}
struct _ConstantSort {
String name;
int value;
- bool operator<(const _ConstantSort& p_c) const {
+ bool operator<(const _ConstantSort &p_c) const {
- String left_a=name.find("_")==-1?name:name.substr(0,name.find("_"));
- String left_b=p_c.name.find("_")==-1?p_c.name:p_c.name.substr(0,p_c.name.find("_"));
- if(left_a==left_b)
- return value<p_c.value;
+ String left_a = name.find("_") == -1 ? name : name.substr(0, name.find("_"));
+ String left_b = p_c.name.find("_") == -1 ? p_c.name : p_c.name.substr(0, p_c.name.find("_"));
+ if (left_a == left_b)
+ return value < p_c.value;
else
- return left_a<left_b;
-
+ return left_a < left_b;
}
-
};
+static String _escape_string(const String &p_str) {
-static String _escape_string(const String& p_str) {
-
- String ret=p_str;
- ret=ret.replace("&","&amp;");
- ret=ret.replace("<","&gt;");
- ret=ret.replace(">","&lt;");
- ret=ret.replace("'","&apos;");
- ret=ret.replace("\"","&quot;");
- for (char i=1;i<32;i++) {
+ String ret = p_str;
+ ret = ret.replace("&", "&amp;");
+ ret = ret.replace("<", "&gt;");
+ ret = ret.replace(">", "&lt;");
+ ret = ret.replace("'", "&apos;");
+ ret = ret.replace("\"", "&quot;");
+ for (char i = 1; i < 32; i++) {
- char chr[2]={i,0};
- ret=ret.replace(chr,"&#"+String::num(i)+";");
+ char chr[2] = { i, 0 };
+ ret = ret.replace(chr, "&#" + String::num(i) + ";");
}
- ret=ret.utf8();
+ ret = ret.utf8();
return ret;
}
-void DocDump::dump(const String& p_file) {
-
+void DocDump::dump(const String &p_file) {
List<StringName> class_list;
ClassDB::get_class_list(&class_list);
class_list.sort_custom<StringName::AlphCompare>();
+ FileAccess *f = FileAccess::open(p_file, FileAccess::WRITE);
- FileAccess *f = FileAccess::open(p_file,FileAccess::WRITE);
-
- _write_string(f,0,"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ _write_string(f, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
- _write_string(f,0,"<doc version=\""+String(VERSION_MKSTRING)+"\" name=\"Engine Types\">");
- while(class_list.size()) {
+ _write_string(f, 0, "<doc version=\"" + String(VERSION_MKSTRING) + "\" name=\"Engine Types\">");
+ while (class_list.size()) {
- String name=class_list.front()->get();
+ String name = class_list.front()->get();
- String header="<class name=\""+name+"\"";
- String inherits=ClassDB::get_parent_class(name);
- if (inherits!="")
- header+=" inherits=\""+inherits+"\"";
- String category=ClassDB::get_category(name);
- if (category=="")
- category="Core";
- header+=" category=\""+category+"\"";
- header+=">";
- _write_string(f,0,header);
- _write_string(f,1,"<brief_description>");
- _write_string(f,1,"</brief_description>");
- _write_string(f,1,"<description>");
- _write_string(f,1,"</description>");
- _write_string(f,1,"<methods>");
+ String header = "<class name=\"" + name + "\"";
+ String inherits = ClassDB::get_parent_class(name);
+ if (inherits != "")
+ header += " inherits=\"" + inherits + "\"";
+ String category = ClassDB::get_category(name);
+ if (category == "")
+ category = "Core";
+ header += " category=\"" + category + "\"";
+ header += ">";
+ _write_string(f, 0, header);
+ _write_string(f, 1, "<brief_description>");
+ _write_string(f, 1, "</brief_description>");
+ _write_string(f, 1, "<description>");
+ _write_string(f, 1, "</description>");
+ _write_string(f, 1, "<methods>");
List<MethodInfo> method_list;
- ClassDB::get_method_list(name,&method_list,true);
+ ClassDB::get_method_list(name, &method_list, true);
method_list.sort();
-
- for(List<MethodInfo>::Element *E=method_list.front();E;E=E->next()) {
- if (E->get().name=="" || E->get().name[0]=='_')
+ for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
+ if (E->get().name == "" || E->get().name[0] == '_')
continue; //hiden
- MethodBind *m = ClassDB::get_method(name,E->get().name);
+ MethodBind *m = ClassDB::get_method(name, E->get().name);
String qualifiers;
- if (E->get().flags&METHOD_FLAG_CONST)
- qualifiers+="qualifiers=\"const\"";
+ if (E->get().flags & METHOD_FLAG_CONST)
+ qualifiers += "qualifiers=\"const\"";
- _write_string(f,2,"<method name=\""+_escape_string(E->get().name)+"\" "+qualifiers+" >");
+ _write_string(f, 2, "<method name=\"" + _escape_string(E->get().name) + "\" " + qualifiers + " >");
- for(int i=-1;i<E->get().arguments.size();i++) {
+ for (int i = -1; i < E->get().arguments.size(); i++) {
PropertyInfo arginfo;
- if (i==-1) {
+ if (i == -1) {
- arginfo=E->get().return_val;
- String type_name=(arginfo.hint==PROPERTY_HINT_RESOURCE_TYPE)?arginfo.hint_string:Variant::get_type_name(arginfo.type);
+ arginfo = E->get().return_val;
+ String type_name = (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) ? arginfo.hint_string : Variant::get_type_name(arginfo.type);
- if (arginfo.type==Variant::NIL)
+ if (arginfo.type == Variant::NIL)
continue;
- _write_string(f,3,"<return type=\""+type_name+"\">");
+ _write_string(f, 3, "<return type=\"" + type_name + "\">");
} else {
-
- arginfo=E->get().arguments[i];
+ arginfo = E->get().arguments[i];
String type_name;
- if (arginfo.hint==PROPERTY_HINT_RESOURCE_TYPE)
- type_name=arginfo.hint_string;
- else if (arginfo.type==Variant::NIL)
- type_name="var";
+ if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE)
+ type_name = arginfo.hint_string;
+ else if (arginfo.type == Variant::NIL)
+ type_name = "var";
else
- type_name=Variant::get_type_name(arginfo.type);
+ type_name = Variant::get_type_name(arginfo.type);
if (m && m->has_default_argument(i)) {
- Variant default_arg=m->get_default_argument(i);
- String default_arg_text=String(_escape_string(m->get_default_argument(i)));
+ Variant default_arg = m->get_default_argument(i);
+ String default_arg_text = String(_escape_string(m->get_default_argument(i)));
- switch(default_arg.get_type()) {
+ switch (default_arg.get_type()) {
case Variant::NIL:
- default_arg_text="NULL";
+ default_arg_text = "NULL";
break;
// atomic types
case Variant::BOOL:
if (bool(default_arg))
- default_arg_text="true";
+ default_arg_text = "true";
else
- default_arg_text="false";
+ default_arg_text = "false";
break;
case Variant::INT:
case Variant::REAL:
//keep it
break;
- case Variant::STRING: // 15
- case Variant::NODE_PATH: // 15
- default_arg_text="\""+default_arg_text+"\"";
+ case Variant::STRING: // 15
+ case Variant::NODE_PATH: // 15
+ default_arg_text = "\"" + default_arg_text + "\"";
break;
case Variant::TRANSFORM:
- if (default_arg.operator Transform()==Transform()) {
- default_arg_text="";
+ if (default_arg.operator Transform() == Transform()) {
+ default_arg_text = "";
}
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"("+default_arg_text+")";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
break;
- case Variant::VECTOR2: // 5
+ case Variant::VECTOR2: // 5
case Variant::RECT2:
case Variant::VECTOR3:
case Variant::PLANE:
@@ -194,89 +187,90 @@ void DocDump::dump(const String& p_file) {
case Variant::POOL_BYTE_ARRAY:
case Variant::POOL_INT_ARRAY:
case Variant::POOL_REAL_ARRAY:
- case Variant::POOL_STRING_ARRAY: //25
+ case Variant::POOL_STRING_ARRAY: //25
case Variant::POOL_VECTOR3_ARRAY:
case Variant::POOL_COLOR_ARRAY:
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"("+default_arg_text+")";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
break;
case Variant::OBJECT:
case Variant::INPUT_EVENT:
- case Variant::DICTIONARY: // 20
+ case Variant::DICTIONARY: // 20
case Variant::ARRAY:
case Variant::_RID:
case Variant::IMAGE:
- //case Variant::RESOURCE:
+ //case Variant::RESOURCE:
- default_arg_text=Variant::get_type_name(default_arg.get_type())+"()";
+ default_arg_text = Variant::get_type_name(default_arg.get_type()) + "()";
break;
default: {}
-
}
-
-
-
- _write_string(f,3,"<argument index=\""+itos(i)+"\" name=\""+_escape_string(arginfo.name)+"\" type=\""+type_name+"\" default=\""+_escape_string(default_arg_text)+"\">");
+ _write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + _escape_string(arginfo.name) + "\" type=\"" + type_name + "\" default=\"" + _escape_string(default_arg_text) + "\">");
} else
- _write_string(f,3,"<argument index=\""+itos(i)+"\" name=\""+arginfo.name+"\" type=\""+type_name+"\">");
+ _write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + arginfo.name + "\" type=\"" + type_name + "\">");
}
-
String hint;
- switch(arginfo.hint) {
- case PROPERTY_HINT_DIR: hint="A directory."; break;
- case PROPERTY_HINT_RANGE: hint="Range - min: "+arginfo.hint_string.get_slice(",",0)+" max: "+arginfo.hint_string.get_slice(",",1)+" step: "+arginfo.hint_string.get_slice(",",2); break;
- case PROPERTY_HINT_ENUM: hint="Values: "; for(int j=0;j<arginfo.hint_string.get_slice_count(",");j++) { if (j>0) hint+=", "; hint+=arginfo.hint_string.get_slice(",",j)+"="+itos(j); } break;
- case PROPERTY_HINT_LENGTH: hint="Length: "+arginfo.hint_string; break;
- case PROPERTY_HINT_FLAGS: hint="Values: "; for(int j=0;j<arginfo.hint_string.get_slice_count(",");j++) { if (j>0) hint+=", "; hint+=arginfo.hint_string.get_slice(",",j)+"="+itos(1<<j); } break;
- case PROPERTY_HINT_FILE: hint="A file:"; break;
+ switch (arginfo.hint) {
+ case PROPERTY_HINT_DIR: hint = "A directory."; break;
+ case PROPERTY_HINT_RANGE: hint = "Range - min: " + arginfo.hint_string.get_slice(",", 0) + " max: " + arginfo.hint_string.get_slice(",", 1) + " step: " + arginfo.hint_string.get_slice(",", 2); break;
+ case PROPERTY_HINT_ENUM:
+ hint = "Values: ";
+ for (int j = 0; j < arginfo.hint_string.get_slice_count(","); j++) {
+ if (j > 0) hint += ", ";
+ hint += arginfo.hint_string.get_slice(",", j) + "=" + itos(j);
+ }
+ break;
+ case PROPERTY_HINT_LENGTH: hint = "Length: " + arginfo.hint_string; break;
+ case PROPERTY_HINT_FLAGS:
+ hint = "Values: ";
+ for (int j = 0; j < arginfo.hint_string.get_slice_count(","); j++) {
+ if (j > 0) hint += ", ";
+ hint += arginfo.hint_string.get_slice(",", j) + "=" + itos(1 << j);
+ }
+ break;
+ case PROPERTY_HINT_FILE: hint = "A file:"; break;
default: {}
- //case PROPERTY_HINT_RESOURCE_TYPE: hint="Type: "+arginfo.hint_string; break;
+ //case PROPERTY_HINT_RESOURCE_TYPE: hint="Type: "+arginfo.hint_string; break;
};
- if (hint!="")
- _write_string(f,4,hint);
-
- _write_string(f,3,(i==-1)?"</return>":"</argument>");
-
+ if (hint != "")
+ _write_string(f, 4, hint);
+ _write_string(f, 3, (i == -1) ? "</return>" : "</argument>");
}
- _write_string(f,3,"<description>");
- _write_string(f,3,"</description>");
-
- _write_string(f,2,"</method>");
+ _write_string(f, 3, "<description>");
+ _write_string(f, 3, "</description>");
+ _write_string(f, 2, "</method>");
}
-
- _write_string(f,1,"</methods>");
+ _write_string(f, 1, "</methods>");
List<MethodInfo> signal_list;
- ClassDB::get_signal_list(name,&signal_list,true);
+ ClassDB::get_signal_list(name, &signal_list, true);
if (signal_list.size()) {
- _write_string(f,1,"<signals>");
- for(List<MethodInfo>::Element *EV=signal_list.front();EV;EV=EV->next()) {
+ _write_string(f, 1, "<signals>");
+ for (List<MethodInfo>::Element *EV = signal_list.front(); EV; EV = EV->next()) {
- _write_string(f,2,"<signal name=\""+EV->get().name+"\">");
- for(int i=0;i<EV->get().arguments.size();i++) {
- PropertyInfo arginfo=EV->get().arguments[i];
- _write_string(f,3,"<argument index=\""+itos(i)+"\" name=\""+arginfo.name+"\" type=\""+Variant::get_type_name(arginfo.type)+"\">");
- _write_string(f,3,"</argument>");
+ _write_string(f, 2, "<signal name=\"" + EV->get().name + "\">");
+ for (int i = 0; i < EV->get().arguments.size(); i++) {
+ PropertyInfo arginfo = EV->get().arguments[i];
+ _write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + arginfo.name + "\" type=\"" + Variant::get_type_name(arginfo.type) + "\">");
+ _write_string(f, 3, "</argument>");
}
- _write_string(f,3,"<description>");
- _write_string(f,3,"</description>");
+ _write_string(f, 3, "<description>");
+ _write_string(f, 3, "</description>");
- _write_string(f,2,"</signal>");
+ _write_string(f, 2, "</signal>");
}
- _write_string(f,1,"</signals>");
+ _write_string(f, 1, "</signals>");
}
-
- _write_string(f,1,"<constants>");
-
+ _write_string(f, 1, "<constants>");
List<String> constant_list;
ClassDB::get_integer_constant_list(name, &constant_list, true);
@@ -285,29 +279,28 @@ void DocDump::dump(const String& p_file) {
List<_ConstantSort> constant_sort;
- for(List<String>::Element *E=constant_list.front();E;E=E->next()) {
+ for (List<String>::Element *E = constant_list.front(); E; E = E->next()) {
_ConstantSort cs;
- cs.name=E->get();
- cs.value=ClassDB::get_integer_constant(name, E->get());
+ cs.name = E->get();
+ cs.value = ClassDB::get_integer_constant(name, E->get());
constant_sort.push_back(cs);
}
constant_sort.sort();
- for(List<_ConstantSort>::Element *E=constant_sort.front();E;E=E->next()) {
+ for (List<_ConstantSort>::Element *E = constant_sort.front(); E; E = E->next()) {
- _write_string(f,2,"<constant name=\""+E->get().name+"\" value=\""+itos(E->get().value)+"\">");
- _write_string(f,2,"</constant>");
+ _write_string(f, 2, "<constant name=\"" + E->get().name + "\" value=\"" + itos(E->get().value) + "\">");
+ _write_string(f, 2, "</constant>");
}
- _write_string(f,1,"</constants>");
- _write_string(f,0,"</class>");
+ _write_string(f, 1, "</constants>");
+ _write_string(f, 0, "</class>");
class_list.erase(name);
}
- _write_string(f,0,"</doc>");
+ _write_string(f, 0, "</doc>");
f->close();
memdelete(f);
-
}
diff --git a/editor/doc/doc_dump.h b/editor/doc/doc_dump.h
index 84629b89c8..6d6782788f 100644
--- a/editor/doc/doc_dump.h
+++ b/editor/doc/doc_dump.h
@@ -33,9 +33,7 @@
class DocDump {
public:
-
- static void dump(const String& p_file);
-
+ static void dump(const String &p_file);
};
#endif // DOC_DUMP_H
diff --git a/editor/doc_code_font.h b/editor/doc_code_font.h
index 55f335ab78..e3874214f5 100644
--- a/editor/doc_code_font.h
+++ b/editor/doc_code_font.h
@@ -26,7 +26,7 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-static const int _bi_font_doc_code_font_height=19;
-static const int _bi_font_doc_code_font_ascent=15;
-static const int _bi_font_doc_code_font_charcount=193;
-static const int _bi_font_doc_code_font_characters[]={0, 253, 53, 2, 2, -1, 14, 0, 13, 253, 56, 2, 2, -1, 14, 0, 32, 253, 59, 2, 2, -1, 14, 4, 33, 221, 29, 3, 12, 1, 3, 5, 34, 144, 77, 6, 5, 0, 3, 7, 35, 180, 55, 9, 11, -1, 4, 8, 36, 215, 0, 8, 15, 0, 2, 8, 37, 28, 45, 12, 11, -1, 4, 12, 38, 199, 16, 11, 12, 0, 3, 11, 39, 157, 77, 3, 5, 0, 3, 4, 40, 36, 16, 4, 15, 0, 3, 5, 41, 31, 16, 4, 15, 0, 3, 5, 42, 93, 79, 9, 7, -1, 3, 8, 43, 110, 68, 9, 9, -1, 5, 8, 44, 121, 78, 4, 6, -1, 12, 4, 45, 204, 76, 5, 3, -1, 9, 5, 46, 216, 75, 4, 3, 0, 12, 4, 47, 233, 0, 8, 15, -1, 2, 7, 48, 246, 29, 9, 11, -1, 4, 8, 49, 208, 54, 8, 11, 0, 4, 8, 50, 219, 42, 9, 11, -1, 4, 8, 51, 229, 41, 9, 11, -1, 4, 8, 52, 239, 41, 9, 11, -1, 4, 8, 53, 0, 57, 9, 11, -1, 4, 8, 54, 160, 55, 9, 11, -1, 4, 8, 55, 10, 57, 9, 11, -1, 4, 8, 56, 20, 57, 9, 11, -1, 4, 8, 57, 40, 57, 9, 11, -1, 4, 8, 58, 78, 80, 3, 8, 0, 7, 4, 59, 72, 68, 4, 11, -1, 7, 4, 60, 18, 69, 8, 11, 0, 4, 8, 61, 112, 78, 8, 7, 0, 6, 8, 62, 0, 69, 8, 11, 0, 4, 8, 63, 184, 30, 7, 12, 0, 3, 7, 64, 148, 16, 13, 13, 0, 4, 14, 65, 117, 44, 11, 11, -1, 4, 10, 66, 50, 57, 9, 11, 0, 4, 9, 67, 197, 42, 10, 11, -1, 4, 8, 68, 153, 43, 10, 11, 0, 4, 10, 69, 244, 53, 8, 11, 0, 4, 8, 70, 43, 69, 7, 11, 0, 4, 7, 71, 93, 44, 11, 11, -1, 4, 10, 72, 60, 56, 9, 11, 0, 4, 10, 73, 77, 68, 4, 11, 0, 4, 4, 74, 249, 41, 6, 11, -1, 4, 5, 75, 70, 56, 9, 11, 0, 4, 9, 76, 27, 69, 7, 11, 0, 4, 7, 77, 14, 45, 13, 11, 0, 4, 14, 78, 208, 42, 10, 11, 0, 4, 11, 79, 41, 45, 12, 11, -1, 4, 11, 80, 199, 54, 8, 11, 0, 4, 9, 81, 162, 16, 13, 13, -1, 4, 11, 82, 80, 56, 9, 11, 0, 4, 9, 83, 90, 56, 9, 11, -1, 4, 8, 84, 100, 56, 9, 11, -1, 4, 8, 85, 164, 43, 10, 11, 0, 4, 10, 86, 129, 44, 11, 11, -1, 4, 9, 87, 229, 29, 16, 11, -1, 4, 15, 88, 175, 43, 10, 11, -1, 4, 9, 89, 186, 43, 10, 11, -1, 4, 8, 90, 110, 56, 9, 11, -1, 4, 8, 91, 26, 16, 4, 15, 0, 3, 5, 92, 123, 0, 10, 15, -2, 2, 7, 93, 251, 0, 4, 15, 0, 3, 5, 94, 82, 79, 10, 7, -2, 4, 8, 95, 180, 76, 9, 3, -1, 15, 8, 96, 161, 77, 6, 4, -1, 3, 5, 97, 27, 81, 8, 8, -1, 7, 8, 98, 68, 31, 8, 12, 0, 3, 9, 99, 18, 81, 8, 8, -1, 7, 7, 100, 211, 16, 9, 12, -1, 3, 9, 101, 228, 66, 9, 8, -1, 7, 8, 102, 176, 30, 7, 12, -1, 3, 5, 103, 120, 56, 9, 11, -1, 7, 8, 104, 59, 31, 8, 12, 0, 3, 9, 105, 66, 68, 5, 11, -1, 4, 4, 106, 141, 16, 6, 14, -2, 4, 4, 107, 104, 31, 8, 12, 0, 3, 8, 108, 251, 16, 3, 12, 0, 3, 4, 109, 144, 68, 13, 8, 0, 7, 13, 110, 9, 81, 8, 8, 0, 7, 9, 111, 208, 66, 9, 8, -1, 7, 9, 112, 217, 54, 8, 11, 0, 7, 9, 113, 140, 56, 9, 11, -1, 7, 9, 114, 53, 81, 6, 8, 0, 7, 6, 115, 45, 81, 7, 8, -1, 7, 6, 116, 102, 68, 7, 10, -1, 5, 6, 117, 36, 81, 8, 8, 0, 7, 9, 118, 238, 65, 9, 8, -1, 7, 8, 119, 158, 68, 13, 8, -1, 7, 12, 120, 218, 66, 9, 8, -1, 7, 7, 121, 150, 56, 9, 11, -1, 7, 8, 122, 248, 65, 7, 8, -1, 7, 6, 123, 14, 16, 5, 15, 0, 3, 6, 124, 41, 16, 3, 15, 2, 3, 8, 125, 20, 16, 5, 15, 0, 3, 6, 126, 135, 78, 8, 5, -1, 4, 8, 160, 253, 62, 2, 2, -1, 14, 4, 161, 225, 29, 3, 12, 0, 5, 5, 162, 35, 69, 7, 11, 0, 4, 8, 163, 190, 55, 8, 11, 0, 4, 8, 164, 82, 68, 9, 10, -1, 5, 8, 165, 105, 44, 11, 11, -2, 4, 8, 166, 45, 16, 3, 15, 2, 3, 8, 167, 125, 16, 8, 14, 0, 3, 8, 168, 197, 76, 6, 3, 0, 4, 7, 169, 186, 16, 12, 12, 0, 3, 13, 170, 137, 68, 6, 9, 0, 4, 7, 171, 197, 67, 10, 8, -1, 6, 9, 172, 126, 78, 8, 5, -1, 8, 8, 173, 210, 75, 5, 3, -1, 9, 5, 174, 103, 79, 8, 7, 0, 3, 8, 175, 190, 76, 6, 3, 0, 4, 6, 176, 151, 77, 5, 5, 0, 3, 5, 177, 221, 16, 9, 12, -1, 3, 8, 178, 60, 81, 6, 8, -1, 2, 5, 179, 67, 80, 5, 8, -1, 2, 5, 180, 168, 77, 6, 4, -1, 3, 5, 181, 170, 55, 9, 11, 0, 7, 9, 182, 176, 16, 9, 13, 0, 4, 10, 183, 221, 75, 3, 3, 0, 9, 4, 184, 175, 76, 4, 4, 0, 14, 5, 185, 73, 80, 4, 8, 0, 2, 4, 186, 129, 68, 7, 9, 0, 4, 7, 187, 185, 67, 11, 8, -1, 6, 9, 188, 54, 44, 12, 11, -2, 4, 11, 189, 67, 44, 12, 11, -2, 4, 11, 190, 80, 44, 12, 11, -1, 4, 11, 191, 192, 29, 7, 12, -1, 5, 7, 192, 88, 0, 11, 15, -1, 0, 10, 193, 64, 0, 11, 15, -1, 0, 10, 194, 76, 0, 11, 15, -1, 0, 10, 195, 100, 0, 11, 15, -1, 0, 10, 196, 74, 16, 11, 14, -1, 1, 10, 197, 62, 16, 11, 14, -1, 1, 10, 198, 0, 45, 13, 11, -1, 4, 12, 199, 107, 16, 8, 14, 0, 4, 8, 200, 188, 0, 8, 15, 0, 0, 8, 201, 206, 0, 8, 15, 0, 0, 8, 202, 224, 0, 8, 15, 0, 0, 8, 203, 116, 16, 8, 14, 0, 1, 8, 204, 0, 16, 6, 15, -2, 0, 4, 205, 7, 16, 6, 15, -1, 0, 4, 206, 242, 0, 8, 15, -2, 0, 4, 207, 134, 16, 6, 14, -1, 1, 4, 208, 141, 44, 11, 11, -1, 4, 10, 209, 145, 0, 10, 15, 0, 0, 11, 210, 0, 0, 12, 15, -1, 0, 11, 211, 39, 0, 12, 15, -1, 0, 11, 212, 26, 0, 12, 15, -1, 0, 11, 213, 13, 0, 12, 15, -1, 0, 11, 214, 49, 16, 12, 14, -1, 1, 11, 215, 0, 81, 8, 8, 0, 6, 8, 216, 52, 0, 11, 15, 0, 2, 11, 217, 167, 0, 10, 15, 0, 0, 10, 218, 134, 0, 10, 15, 0, 0, 10, 219, 156, 0, 10, 15, 0, 0, 10, 220, 86, 16, 10, 14, 0, 1, 10, 221, 112, 0, 10, 15, -1, 0, 8, 222, 226, 54, 8, 11, 0, 4, 9, 223, 77, 31, 8, 12, 0, 3, 9, 224, 113, 31, 8, 12, -1, 3, 8, 225, 122, 31, 8, 12, -1, 3, 8, 226, 131, 31, 8, 12, -1, 3, 8, 227, 167, 30, 8, 12, -1, 3, 8, 228, 235, 53, 8, 11, -1, 4, 8, 229, 50, 31, 8, 12, -1, 3, 8, 230, 172, 67, 12, 8, 0, 7, 12, 231, 51, 69, 7, 11, 0, 7, 7, 232, 40, 32, 9, 12, -1, 3, 8, 233, 231, 16, 9, 12, -1, 3, 8, 234, 241, 16, 9, 12, -1, 3, 8, 235, 30, 57, 9, 11, -1, 4, 8, 236, 200, 29, 6, 12, -2, 3, 4, 237, 214, 29, 6, 12, -1, 3, 4, 238, 207, 29, 6, 12, -1, 3, 4, 239, 59, 69, 6, 11, -1, 4, 4, 240, 86, 31, 8, 12, 0, 3, 9, 241, 95, 31, 8, 12, 0, 3, 9, 242, 0, 32, 9, 12, -1, 3, 9, 243, 10, 32, 9, 12, -1, 3, 9, 244, 20, 32, 9, 12, -1, 3, 9, 245, 30, 32, 9, 12, -1, 3, 9, 246, 130, 56, 9, 11, -1, 4, 9, 247, 120, 68, 8, 9, -1, 5, 8, 248, 92, 68, 9, 10, 0, 6, 9, 249, 140, 31, 8, 12, 0, 3, 9, 250, 149, 30, 8, 12, 0, 3, 9, 251, 158, 30, 8, 12, 0, 3, 9, 252, 9, 69, 8, 11, 0, 4, 9, 253, 178, 0, 9, 15, -1, 3, 8, 254, 197, 0, 8, 15, 0, 3, 9, 255, 97, 16, 9, 14, -1, 4, 8};
+static const int _bi_font_doc_code_font_height = 19;
+static const int _bi_font_doc_code_font_ascent = 15;
+static const int _bi_font_doc_code_font_charcount = 193;
+static const int _bi_font_doc_code_font_characters[] = { 0, 253, 53, 2, 2, -1, 14, 0, 13, 253, 56, 2, 2, -1, 14, 0, 32, 253, 59, 2, 2, -1, 14, 4, 33, 221, 29, 3, 12, 1, 3, 5, 34, 144, 77, 6, 5, 0, 3, 7, 35, 180, 55, 9, 11, -1, 4, 8, 36, 215, 0, 8, 15, 0, 2, 8, 37, 28, 45, 12, 11, -1, 4, 12, 38, 199, 16, 11, 12, 0, 3, 11, 39, 157, 77, 3, 5, 0, 3, 4, 40, 36, 16, 4, 15, 0, 3, 5, 41, 31, 16, 4, 15, 0, 3, 5, 42, 93, 79, 9, 7, -1, 3, 8, 43, 110, 68, 9, 9, -1, 5, 8, 44, 121, 78, 4, 6, -1, 12, 4, 45, 204, 76, 5, 3, -1, 9, 5, 46, 216, 75, 4, 3, 0, 12, 4, 47, 233, 0, 8, 15, -1, 2, 7, 48, 246, 29, 9, 11, -1, 4, 8, 49, 208, 54, 8, 11, 0, 4, 8, 50, 219, 42, 9, 11, -1, 4, 8, 51, 229, 41, 9, 11, -1, 4, 8, 52, 239, 41, 9, 11, -1, 4, 8, 53, 0, 57, 9, 11, -1, 4, 8, 54, 160, 55, 9, 11, -1, 4, 8, 55, 10, 57, 9, 11, -1, 4, 8, 56, 20, 57, 9, 11, -1, 4, 8, 57, 40, 57, 9, 11, -1, 4, 8, 58, 78, 80, 3, 8, 0, 7, 4, 59, 72, 68, 4, 11, -1, 7, 4, 60, 18, 69, 8, 11, 0, 4, 8, 61, 112, 78, 8, 7, 0, 6, 8, 62, 0, 69, 8, 11, 0, 4, 8, 63, 184, 30, 7, 12, 0, 3, 7, 64, 148, 16, 13, 13, 0, 4, 14, 65, 117, 44, 11, 11, -1, 4, 10, 66, 50, 57, 9, 11, 0, 4, 9, 67, 197, 42, 10, 11, -1, 4, 8, 68, 153, 43, 10, 11, 0, 4, 10, 69, 244, 53, 8, 11, 0, 4, 8, 70, 43, 69, 7, 11, 0, 4, 7, 71, 93, 44, 11, 11, -1, 4, 10, 72, 60, 56, 9, 11, 0, 4, 10, 73, 77, 68, 4, 11, 0, 4, 4, 74, 249, 41, 6, 11, -1, 4, 5, 75, 70, 56, 9, 11, 0, 4, 9, 76, 27, 69, 7, 11, 0, 4, 7, 77, 14, 45, 13, 11, 0, 4, 14, 78, 208, 42, 10, 11, 0, 4, 11, 79, 41, 45, 12, 11, -1, 4, 11, 80, 199, 54, 8, 11, 0, 4, 9, 81, 162, 16, 13, 13, -1, 4, 11, 82, 80, 56, 9, 11, 0, 4, 9, 83, 90, 56, 9, 11, -1, 4, 8, 84, 100, 56, 9, 11, -1, 4, 8, 85, 164, 43, 10, 11, 0, 4, 10, 86, 129, 44, 11, 11, -1, 4, 9, 87, 229, 29, 16, 11, -1, 4, 15, 88, 175, 43, 10, 11, -1, 4, 9, 89, 186, 43, 10, 11, -1, 4, 8, 90, 110, 56, 9, 11, -1, 4, 8, 91, 26, 16, 4, 15, 0, 3, 5, 92, 123, 0, 10, 15, -2, 2, 7, 93, 251, 0, 4, 15, 0, 3, 5, 94, 82, 79, 10, 7, -2, 4, 8, 95, 180, 76, 9, 3, -1, 15, 8, 96, 161, 77, 6, 4, -1, 3, 5, 97, 27, 81, 8, 8, -1, 7, 8, 98, 68, 31, 8, 12, 0, 3, 9, 99, 18, 81, 8, 8, -1, 7, 7, 100, 211, 16, 9, 12, -1, 3, 9, 101, 228, 66, 9, 8, -1, 7, 8, 102, 176, 30, 7, 12, -1, 3, 5, 103, 120, 56, 9, 11, -1, 7, 8, 104, 59, 31, 8, 12, 0, 3, 9, 105, 66, 68, 5, 11, -1, 4, 4, 106, 141, 16, 6, 14, -2, 4, 4, 107, 104, 31, 8, 12, 0, 3, 8, 108, 251, 16, 3, 12, 0, 3, 4, 109, 144, 68, 13, 8, 0, 7, 13, 110, 9, 81, 8, 8, 0, 7, 9, 111, 208, 66, 9, 8, -1, 7, 9, 112, 217, 54, 8, 11, 0, 7, 9, 113, 140, 56, 9, 11, -1, 7, 9, 114, 53, 81, 6, 8, 0, 7, 6, 115, 45, 81, 7, 8, -1, 7, 6, 116, 102, 68, 7, 10, -1, 5, 6, 117, 36, 81, 8, 8, 0, 7, 9, 118, 238, 65, 9, 8, -1, 7, 8, 119, 158, 68, 13, 8, -1, 7, 12, 120, 218, 66, 9, 8, -1, 7, 7, 121, 150, 56, 9, 11, -1, 7, 8, 122, 248, 65, 7, 8, -1, 7, 6, 123, 14, 16, 5, 15, 0, 3, 6, 124, 41, 16, 3, 15, 2, 3, 8, 125, 20, 16, 5, 15, 0, 3, 6, 126, 135, 78, 8, 5, -1, 4, 8, 160, 253, 62, 2, 2, -1, 14, 4, 161, 225, 29, 3, 12, 0, 5, 5, 162, 35, 69, 7, 11, 0, 4, 8, 163, 190, 55, 8, 11, 0, 4, 8, 164, 82, 68, 9, 10, -1, 5, 8, 165, 105, 44, 11, 11, -2, 4, 8, 166, 45, 16, 3, 15, 2, 3, 8, 167, 125, 16, 8, 14, 0, 3, 8, 168, 197, 76, 6, 3, 0, 4, 7, 169, 186, 16, 12, 12, 0, 3, 13, 170, 137, 68, 6, 9, 0, 4, 7, 171, 197, 67, 10, 8, -1, 6, 9, 172, 126, 78, 8, 5, -1, 8, 8, 173, 210, 75, 5, 3, -1, 9, 5, 174, 103, 79, 8, 7, 0, 3, 8, 175, 190, 76, 6, 3, 0, 4, 6, 176, 151, 77, 5, 5, 0, 3, 5, 177, 221, 16, 9, 12, -1, 3, 8, 178, 60, 81, 6, 8, -1, 2, 5, 179, 67, 80, 5, 8, -1, 2, 5, 180, 168, 77, 6, 4, -1, 3, 5, 181, 170, 55, 9, 11, 0, 7, 9, 182, 176, 16, 9, 13, 0, 4, 10, 183, 221, 75, 3, 3, 0, 9, 4, 184, 175, 76, 4, 4, 0, 14, 5, 185, 73, 80, 4, 8, 0, 2, 4, 186, 129, 68, 7, 9, 0, 4, 7, 187, 185, 67, 11, 8, -1, 6, 9, 188, 54, 44, 12, 11, -2, 4, 11, 189, 67, 44, 12, 11, -2, 4, 11, 190, 80, 44, 12, 11, -1, 4, 11, 191, 192, 29, 7, 12, -1, 5, 7, 192, 88, 0, 11, 15, -1, 0, 10, 193, 64, 0, 11, 15, -1, 0, 10, 194, 76, 0, 11, 15, -1, 0, 10, 195, 100, 0, 11, 15, -1, 0, 10, 196, 74, 16, 11, 14, -1, 1, 10, 197, 62, 16, 11, 14, -1, 1, 10, 198, 0, 45, 13, 11, -1, 4, 12, 199, 107, 16, 8, 14, 0, 4, 8, 200, 188, 0, 8, 15, 0, 0, 8, 201, 206, 0, 8, 15, 0, 0, 8, 202, 224, 0, 8, 15, 0, 0, 8, 203, 116, 16, 8, 14, 0, 1, 8, 204, 0, 16, 6, 15, -2, 0, 4, 205, 7, 16, 6, 15, -1, 0, 4, 206, 242, 0, 8, 15, -2, 0, 4, 207, 134, 16, 6, 14, -1, 1, 4, 208, 141, 44, 11, 11, -1, 4, 10, 209, 145, 0, 10, 15, 0, 0, 11, 210, 0, 0, 12, 15, -1, 0, 11, 211, 39, 0, 12, 15, -1, 0, 11, 212, 26, 0, 12, 15, -1, 0, 11, 213, 13, 0, 12, 15, -1, 0, 11, 214, 49, 16, 12, 14, -1, 1, 11, 215, 0, 81, 8, 8, 0, 6, 8, 216, 52, 0, 11, 15, 0, 2, 11, 217, 167, 0, 10, 15, 0, 0, 10, 218, 134, 0, 10, 15, 0, 0, 10, 219, 156, 0, 10, 15, 0, 0, 10, 220, 86, 16, 10, 14, 0, 1, 10, 221, 112, 0, 10, 15, -1, 0, 8, 222, 226, 54, 8, 11, 0, 4, 9, 223, 77, 31, 8, 12, 0, 3, 9, 224, 113, 31, 8, 12, -1, 3, 8, 225, 122, 31, 8, 12, -1, 3, 8, 226, 131, 31, 8, 12, -1, 3, 8, 227, 167, 30, 8, 12, -1, 3, 8, 228, 235, 53, 8, 11, -1, 4, 8, 229, 50, 31, 8, 12, -1, 3, 8, 230, 172, 67, 12, 8, 0, 7, 12, 231, 51, 69, 7, 11, 0, 7, 7, 232, 40, 32, 9, 12, -1, 3, 8, 233, 231, 16, 9, 12, -1, 3, 8, 234, 241, 16, 9, 12, -1, 3, 8, 235, 30, 57, 9, 11, -1, 4, 8, 236, 200, 29, 6, 12, -2, 3, 4, 237, 214, 29, 6, 12, -1, 3, 4, 238, 207, 29, 6, 12, -1, 3, 4, 239, 59, 69, 6, 11, -1, 4, 4, 240, 86, 31, 8, 12, 0, 3, 9, 241, 95, 31, 8, 12, 0, 3, 9, 242, 0, 32, 9, 12, -1, 3, 9, 243, 10, 32, 9, 12, -1, 3, 9, 244, 20, 32, 9, 12, -1, 3, 9, 245, 30, 32, 9, 12, -1, 3, 9, 246, 130, 56, 9, 11, -1, 4, 9, 247, 120, 68, 8, 9, -1, 5, 8, 248, 92, 68, 9, 10, 0, 6, 9, 249, 140, 31, 8, 12, 0, 3, 9, 250, 149, 30, 8, 12, 0, 3, 9, 251, 158, 30, 8, 12, 0, 3, 9, 252, 9, 69, 8, 11, 0, 4, 9, 253, 178, 0, 9, 15, -1, 3, 8, 254, 197, 0, 8, 15, 0, 3, 9, 255, 97, 16, 9, 14, -1, 4, 8 };
diff --git a/editor/doc_font.h b/editor/doc_font.h
index b598ee26f8..c146f04cd8 100644
--- a/editor/doc_font.h
+++ b/editor/doc_font.h
@@ -26,7 +26,7 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-static const int _bi_font_doc_font_height=18;
-static const int _bi_font_doc_font_ascent=14;
-static const int _bi_font_doc_font_charcount=193;
-static const int _bi_font_doc_font_characters[]={0, 253, 3, 2, 2, -1, 13, 0, 13, 253, 9, 2, 2, -1, 13, 0, 32, 253, 0, 2, 2, -1, 13, 3, 33, 220, 26, 3, 11, 1, 3, 5, 34, 187, 59, 5, 5, 0, 3, 6, 35, 88, 40, 9, 10, -1, 4, 7, 36, 50, 0, 8, 14, -1, 2, 7, 37, 175, 14, 11, 11, -1, 3, 11, 38, 187, 14, 11, 11, -1, 3, 10, 39, 198, 58, 3, 5, 0, 3, 3, 40, 98, 0, 4, 14, 0, 3, 5, 41, 103, 0, 4, 14, 0, 3, 5, 42, 146, 61, 7, 6, 0, 3, 7, 43, 246, 48, 8, 8, -1, 5, 7, 44, 193, 58, 4, 5, -1, 11, 4, 45, 13, 73, 5, 2, 0, 9, 5, 46, 241, 57, 3, 3, 0, 11, 4, 47, 84, 0, 7, 14, -1, 2, 6, 48, 246, 37, 8, 10, -1, 4, 7, 49, 33, 52, 7, 10, 0, 4, 7, 50, 237, 37, 8, 10, -1, 4, 7, 51, 219, 38, 8, 10, -1, 4, 7, 52, 128, 39, 9, 10, -1, 4, 7, 53, 41, 52, 7, 10, -1, 4, 7, 54, 9, 53, 7, 10, 0, 4, 7, 55, 228, 38, 8, 10, -1, 4, 7, 56, 57, 52, 7, 10, 0, 4, 7, 57, 65, 51, 7, 10, 0, 4, 7, 58, 98, 62, 4, 8, 0, 6, 4, 59, 162, 50, 5, 10, -1, 6, 4, 60, 174, 49, 8, 9, -1, 4, 7, 61, 179, 59, 7, 5, 0, 7, 7, 62, 228, 49, 8, 8, -1, 5, 7, 63, 89, 28, 7, 11, 0, 3, 7, 64, 54, 15, 12, 12, 0, 4, 13, 65, 36, 41, 10, 10, -1, 4, 9, 66, 97, 51, 7, 10, 0, 4, 8, 67, 174, 38, 8, 10, 0, 4, 8, 68, 156, 39, 8, 10, 0, 4, 9, 69, 105, 51, 7, 10, 0, 4, 7, 70, 121, 51, 6, 10, 0, 4, 7, 71, 0, 53, 8, 10, 0, 4, 9, 72, 192, 38, 8, 10, 0, 4, 9, 73, 251, 26, 3, 10, 0, 4, 4, 74, 156, 50, 5, 10, -1, 4, 5, 75, 147, 39, 8, 10, 0, 4, 8, 76, 135, 50, 6, 10, 0, 4, 6, 77, 13, 41, 11, 10, 0, 4, 12, 78, 210, 38, 8, 10, 0, 4, 10, 79, 68, 40, 9, 10, 0, 4, 10, 80, 113, 51, 7, 10, 0, 4, 8, 81, 199, 14, 10, 11, 0, 4, 10, 82, 183, 38, 8, 10, 0, 4, 8, 83, 128, 50, 6, 10, 0, 4, 7, 84, 108, 40, 9, 10, -1, 4, 7, 85, 165, 39, 8, 10, 0, 4, 9, 86, 25, 41, 10, 10, -1, 4, 9, 87, 236, 26, 14, 10, -1, 4, 13, 88, 98, 40, 9, 10, -1, 4, 8, 89, 118, 40, 9, 10, -1, 4, 7, 90, 138, 39, 8, 10, -1, 4, 7, 91, 49, 15, 4, 13, 0, 3, 5, 92, 76, 0, 7, 14, -1, 2, 6, 93, 43, 15, 5, 13, -1, 3, 5, 94, 137, 61, 8, 6, -1, 4, 7, 95, 245, 57, 9, 2, -1, 15, 7, 96, 230, 58, 5, 3, -1, 3, 4, 97, 57, 63, 7, 8, 0, 6, 7, 98, 81, 28, 7, 11, 0, 3, 8, 99, 79, 62, 6, 8, 0, 6, 6, 100, 33, 29, 7, 11, 0, 3, 8, 101, 9, 64, 7, 8, 0, 6, 8, 102, 200, 26, 6, 11, -1, 3, 5, 103, 153, 27, 7, 11, 0, 6, 7, 104, 121, 27, 7, 11, 0, 3, 8, 105, 224, 26, 3, 11, 0, 3, 4, 106, 92, 0, 5, 14, -2, 3, 4, 107, 25, 29, 7, 11, 0, 3, 7, 108, 228, 26, 3, 11, 0, 3, 4, 109, 204, 49, 11, 8, 0, 6, 12, 110, 17, 63, 7, 8, 0, 6, 8, 111, 33, 63, 7, 8, 0, 6, 8, 112, 17, 29, 7, 11, 0, 6, 8, 113, 9, 29, 7, 11, 0, 6, 8, 114, 86, 62, 5, 8, 0, 6, 5, 115, 92, 62, 5, 8, 0, 6, 6, 116, 168, 50, 5, 10, -1, 4, 5, 117, 49, 63, 7, 8, 0, 6, 8, 118, 0, 64, 8, 8, -1, 6, 7, 119, 216, 49, 11, 8, -1, 6, 10, 120, 41, 63, 7, 8, -1, 6, 7, 121, 0, 30, 8, 11, -1, 6, 7, 122, 72, 62, 6, 8, 0, 6, 6, 123, 8, 15, 6, 13, -1, 3, 5, 124, 0, 0, 3, 15, 1, 2, 7, 125, 15, 15, 6, 13, -1, 3, 5, 126, 202, 58, 8, 4, -1, 4, 7, 160, 253, 6, 2, 2, -1, 13, 3, 161, 232, 26, 3, 11, 0, 4, 5, 162, 149, 50, 6, 10, 0, 4, 7, 163, 17, 52, 7, 10, 0, 4, 7, 164, 183, 49, 8, 9, -1, 5, 7, 165, 47, 41, 10, 10, -2, 4, 7, 166, 4, 0, 3, 15, 2, 2, 7, 167, 122, 14, 7, 12, 0, 3, 7, 168, 0, 73, 6, 2, -1, 4, 6, 169, 162, 14, 12, 11, 0, 3, 13, 170, 65, 62, 6, 8, -1, 4, 6, 171, 112, 62, 8, 7, -1, 6, 8, 172, 211, 58, 7, 4, -1, 8, 7, 173, 19, 72, 5, 2, 0, 9, 5, 174, 103, 62, 8, 7, -1, 3, 8, 175, 7, 73, 5, 2, 0, 3, 6, 176, 171, 61, 7, 5, -1, 3, 5, 177, 58, 40, 9, 10, -1, 4, 7, 178, 154, 61, 5, 6, 0, 2, 5, 179, 160, 61, 5, 6, -1, 2, 5, 180, 224, 58, 5, 3, -1, 3, 4, 181, 241, 14, 8, 11, 0, 6, 8, 182, 97, 15, 8, 12, 0, 4, 9, 183, 236, 58, 4, 3, 0, 8, 4, 184, 219, 58, 4, 4, 0, 13, 5, 185, 166, 61, 4, 6, 0, 2, 4, 186, 25, 63, 7, 8, -1, 4, 6, 187, 129, 61, 7, 7, 0, 6, 8, 188, 221, 14, 9, 11, 0, 3, 10, 189, 231, 14, 9, 11, 0, 3, 10, 190, 210, 14, 10, 11, -1, 3, 10, 191, 41, 29, 7, 11, -1, 4, 7, 192, 141, 0, 10, 13, -1, 1, 9, 193, 130, 0, 10, 13, -1, 1, 9, 194, 119, 0, 10, 13, -1, 1, 9, 195, 20, 0, 10, 14, -1, 0, 9, 196, 67, 15, 10, 12, -1, 2, 9, 197, 108, 0, 10, 13, -1, 1, 9, 198, 0, 42, 12, 10, -1, 4, 11, 199, 228, 0, 8, 13, 0, 4, 8, 200, 245, 0, 7, 13, 0, 1, 7, 201, 237, 0, 7, 13, 0, 1, 7, 202, 0, 16, 7, 13, 0, 1, 7, 203, 130, 14, 7, 12, 0, 2, 7, 204, 36, 15, 6, 13, -2, 1, 4, 205, 22, 15, 6, 13, -1, 1, 4, 206, 29, 15, 6, 13, -1, 1, 4, 207, 154, 14, 7, 12, -2, 2, 4, 208, 78, 40, 9, 10, -1, 4, 9, 209, 59, 0, 8, 14, 0, 0, 10, 210, 172, 0, 9, 13, 0, 1, 10, 211, 152, 0, 9, 13, 0, 1, 10, 212, 182, 0, 9, 13, 0, 1, 10, 213, 31, 0, 9, 14, 0, 0, 10, 214, 78, 15, 9, 12, 0, 2, 10, 215, 121, 62, 7, 7, 0, 6, 7, 216, 8, 0, 11, 14, -1, 2, 10, 217, 192, 0, 8, 13, 0, 1, 9, 218, 210, 0, 8, 13, 0, 1, 9, 219, 201, 0, 8, 13, 0, 1, 9, 220, 88, 15, 8, 12, 0, 2, 9, 221, 162, 0, 9, 13, -1, 1, 7, 222, 81, 51, 7, 10, 0, 4, 8, 223, 49, 29, 7, 11, 0, 3, 8, 224, 57, 28, 7, 11, 0, 3, 7, 225, 65, 28, 7, 11, 0, 3, 7, 226, 73, 28, 7, 11, 0, 3, 7, 227, 138, 14, 7, 12, 0, 2, 7, 228, 25, 52, 7, 10, 0, 4, 7, 229, 146, 14, 7, 12, 0, 2, 7, 230, 192, 49, 11, 8, 0, 6, 12, 231, 207, 26, 6, 11, 0, 6, 6, 232, 97, 28, 7, 11, 0, 3, 8, 233, 105, 28, 7, 11, 0, 3, 8, 234, 113, 28, 7, 11, 0, 3, 8, 235, 73, 51, 7, 10, 0, 4, 8, 236, 214, 26, 5, 11, -2, 3, 3, 237, 250, 14, 5, 11, -1, 3, 3, 238, 193, 26, 6, 11, -2, 3, 3, 239, 142, 50, 6, 10, -2, 4, 3, 240, 185, 26, 7, 11, 0, 3, 8, 241, 106, 15, 7, 12, 0, 2, 8, 242, 129, 27, 7, 11, 0, 3, 8, 243, 137, 27, 7, 11, 0, 3, 8, 244, 145, 27, 7, 11, 0, 3, 8, 245, 114, 14, 7, 12, 0, 2, 8, 246, 49, 52, 7, 10, 0, 4, 8, 247, 237, 48, 8, 8, -1, 5, 7, 248, 201, 38, 8, 10, 0, 5, 8, 249, 161, 27, 7, 11, 0, 3, 8, 250, 169, 26, 7, 11, 0, 3, 8, 251, 177, 26, 7, 11, 0, 3, 8, 252, 89, 51, 7, 10, 0, 4, 8, 253, 41, 0, 8, 14, -1, 3, 7, 254, 68, 0, 7, 14, 0, 3, 8, 255, 219, 0, 8, 13, -1, 4, 7};
+static const int _bi_font_doc_font_height = 18;
+static const int _bi_font_doc_font_ascent = 14;
+static const int _bi_font_doc_font_charcount = 193;
+static const int _bi_font_doc_font_characters[] = { 0, 253, 3, 2, 2, -1, 13, 0, 13, 253, 9, 2, 2, -1, 13, 0, 32, 253, 0, 2, 2, -1, 13, 3, 33, 220, 26, 3, 11, 1, 3, 5, 34, 187, 59, 5, 5, 0, 3, 6, 35, 88, 40, 9, 10, -1, 4, 7, 36, 50, 0, 8, 14, -1, 2, 7, 37, 175, 14, 11, 11, -1, 3, 11, 38, 187, 14, 11, 11, -1, 3, 10, 39, 198, 58, 3, 5, 0, 3, 3, 40, 98, 0, 4, 14, 0, 3, 5, 41, 103, 0, 4, 14, 0, 3, 5, 42, 146, 61, 7, 6, 0, 3, 7, 43, 246, 48, 8, 8, -1, 5, 7, 44, 193, 58, 4, 5, -1, 11, 4, 45, 13, 73, 5, 2, 0, 9, 5, 46, 241, 57, 3, 3, 0, 11, 4, 47, 84, 0, 7, 14, -1, 2, 6, 48, 246, 37, 8, 10, -1, 4, 7, 49, 33, 52, 7, 10, 0, 4, 7, 50, 237, 37, 8, 10, -1, 4, 7, 51, 219, 38, 8, 10, -1, 4, 7, 52, 128, 39, 9, 10, -1, 4, 7, 53, 41, 52, 7, 10, -1, 4, 7, 54, 9, 53, 7, 10, 0, 4, 7, 55, 228, 38, 8, 10, -1, 4, 7, 56, 57, 52, 7, 10, 0, 4, 7, 57, 65, 51, 7, 10, 0, 4, 7, 58, 98, 62, 4, 8, 0, 6, 4, 59, 162, 50, 5, 10, -1, 6, 4, 60, 174, 49, 8, 9, -1, 4, 7, 61, 179, 59, 7, 5, 0, 7, 7, 62, 228, 49, 8, 8, -1, 5, 7, 63, 89, 28, 7, 11, 0, 3, 7, 64, 54, 15, 12, 12, 0, 4, 13, 65, 36, 41, 10, 10, -1, 4, 9, 66, 97, 51, 7, 10, 0, 4, 8, 67, 174, 38, 8, 10, 0, 4, 8, 68, 156, 39, 8, 10, 0, 4, 9, 69, 105, 51, 7, 10, 0, 4, 7, 70, 121, 51, 6, 10, 0, 4, 7, 71, 0, 53, 8, 10, 0, 4, 9, 72, 192, 38, 8, 10, 0, 4, 9, 73, 251, 26, 3, 10, 0, 4, 4, 74, 156, 50, 5, 10, -1, 4, 5, 75, 147, 39, 8, 10, 0, 4, 8, 76, 135, 50, 6, 10, 0, 4, 6, 77, 13, 41, 11, 10, 0, 4, 12, 78, 210, 38, 8, 10, 0, 4, 10, 79, 68, 40, 9, 10, 0, 4, 10, 80, 113, 51, 7, 10, 0, 4, 8, 81, 199, 14, 10, 11, 0, 4, 10, 82, 183, 38, 8, 10, 0, 4, 8, 83, 128, 50, 6, 10, 0, 4, 7, 84, 108, 40, 9, 10, -1, 4, 7, 85, 165, 39, 8, 10, 0, 4, 9, 86, 25, 41, 10, 10, -1, 4, 9, 87, 236, 26, 14, 10, -1, 4, 13, 88, 98, 40, 9, 10, -1, 4, 8, 89, 118, 40, 9, 10, -1, 4, 7, 90, 138, 39, 8, 10, -1, 4, 7, 91, 49, 15, 4, 13, 0, 3, 5, 92, 76, 0, 7, 14, -1, 2, 6, 93, 43, 15, 5, 13, -1, 3, 5, 94, 137, 61, 8, 6, -1, 4, 7, 95, 245, 57, 9, 2, -1, 15, 7, 96, 230, 58, 5, 3, -1, 3, 4, 97, 57, 63, 7, 8, 0, 6, 7, 98, 81, 28, 7, 11, 0, 3, 8, 99, 79, 62, 6, 8, 0, 6, 6, 100, 33, 29, 7, 11, 0, 3, 8, 101, 9, 64, 7, 8, 0, 6, 8, 102, 200, 26, 6, 11, -1, 3, 5, 103, 153, 27, 7, 11, 0, 6, 7, 104, 121, 27, 7, 11, 0, 3, 8, 105, 224, 26, 3, 11, 0, 3, 4, 106, 92, 0, 5, 14, -2, 3, 4, 107, 25, 29, 7, 11, 0, 3, 7, 108, 228, 26, 3, 11, 0, 3, 4, 109, 204, 49, 11, 8, 0, 6, 12, 110, 17, 63, 7, 8, 0, 6, 8, 111, 33, 63, 7, 8, 0, 6, 8, 112, 17, 29, 7, 11, 0, 6, 8, 113, 9, 29, 7, 11, 0, 6, 8, 114, 86, 62, 5, 8, 0, 6, 5, 115, 92, 62, 5, 8, 0, 6, 6, 116, 168, 50, 5, 10, -1, 4, 5, 117, 49, 63, 7, 8, 0, 6, 8, 118, 0, 64, 8, 8, -1, 6, 7, 119, 216, 49, 11, 8, -1, 6, 10, 120, 41, 63, 7, 8, -1, 6, 7, 121, 0, 30, 8, 11, -1, 6, 7, 122, 72, 62, 6, 8, 0, 6, 6, 123, 8, 15, 6, 13, -1, 3, 5, 124, 0, 0, 3, 15, 1, 2, 7, 125, 15, 15, 6, 13, -1, 3, 5, 126, 202, 58, 8, 4, -1, 4, 7, 160, 253, 6, 2, 2, -1, 13, 3, 161, 232, 26, 3, 11, 0, 4, 5, 162, 149, 50, 6, 10, 0, 4, 7, 163, 17, 52, 7, 10, 0, 4, 7, 164, 183, 49, 8, 9, -1, 5, 7, 165, 47, 41, 10, 10, -2, 4, 7, 166, 4, 0, 3, 15, 2, 2, 7, 167, 122, 14, 7, 12, 0, 3, 7, 168, 0, 73, 6, 2, -1, 4, 6, 169, 162, 14, 12, 11, 0, 3, 13, 170, 65, 62, 6, 8, -1, 4, 6, 171, 112, 62, 8, 7, -1, 6, 8, 172, 211, 58, 7, 4, -1, 8, 7, 173, 19, 72, 5, 2, 0, 9, 5, 174, 103, 62, 8, 7, -1, 3, 8, 175, 7, 73, 5, 2, 0, 3, 6, 176, 171, 61, 7, 5, -1, 3, 5, 177, 58, 40, 9, 10, -1, 4, 7, 178, 154, 61, 5, 6, 0, 2, 5, 179, 160, 61, 5, 6, -1, 2, 5, 180, 224, 58, 5, 3, -1, 3, 4, 181, 241, 14, 8, 11, 0, 6, 8, 182, 97, 15, 8, 12, 0, 4, 9, 183, 236, 58, 4, 3, 0, 8, 4, 184, 219, 58, 4, 4, 0, 13, 5, 185, 166, 61, 4, 6, 0, 2, 4, 186, 25, 63, 7, 8, -1, 4, 6, 187, 129, 61, 7, 7, 0, 6, 8, 188, 221, 14, 9, 11, 0, 3, 10, 189, 231, 14, 9, 11, 0, 3, 10, 190, 210, 14, 10, 11, -1, 3, 10, 191, 41, 29, 7, 11, -1, 4, 7, 192, 141, 0, 10, 13, -1, 1, 9, 193, 130, 0, 10, 13, -1, 1, 9, 194, 119, 0, 10, 13, -1, 1, 9, 195, 20, 0, 10, 14, -1, 0, 9, 196, 67, 15, 10, 12, -1, 2, 9, 197, 108, 0, 10, 13, -1, 1, 9, 198, 0, 42, 12, 10, -1, 4, 11, 199, 228, 0, 8, 13, 0, 4, 8, 200, 245, 0, 7, 13, 0, 1, 7, 201, 237, 0, 7, 13, 0, 1, 7, 202, 0, 16, 7, 13, 0, 1, 7, 203, 130, 14, 7, 12, 0, 2, 7, 204, 36, 15, 6, 13, -2, 1, 4, 205, 22, 15, 6, 13, -1, 1, 4, 206, 29, 15, 6, 13, -1, 1, 4, 207, 154, 14, 7, 12, -2, 2, 4, 208, 78, 40, 9, 10, -1, 4, 9, 209, 59, 0, 8, 14, 0, 0, 10, 210, 172, 0, 9, 13, 0, 1, 10, 211, 152, 0, 9, 13, 0, 1, 10, 212, 182, 0, 9, 13, 0, 1, 10, 213, 31, 0, 9, 14, 0, 0, 10, 214, 78, 15, 9, 12, 0, 2, 10, 215, 121, 62, 7, 7, 0, 6, 7, 216, 8, 0, 11, 14, -1, 2, 10, 217, 192, 0, 8, 13, 0, 1, 9, 218, 210, 0, 8, 13, 0, 1, 9, 219, 201, 0, 8, 13, 0, 1, 9, 220, 88, 15, 8, 12, 0, 2, 9, 221, 162, 0, 9, 13, -1, 1, 7, 222, 81, 51, 7, 10, 0, 4, 8, 223, 49, 29, 7, 11, 0, 3, 8, 224, 57, 28, 7, 11, 0, 3, 7, 225, 65, 28, 7, 11, 0, 3, 7, 226, 73, 28, 7, 11, 0, 3, 7, 227, 138, 14, 7, 12, 0, 2, 7, 228, 25, 52, 7, 10, 0, 4, 7, 229, 146, 14, 7, 12, 0, 2, 7, 230, 192, 49, 11, 8, 0, 6, 12, 231, 207, 26, 6, 11, 0, 6, 6, 232, 97, 28, 7, 11, 0, 3, 8, 233, 105, 28, 7, 11, 0, 3, 8, 234, 113, 28, 7, 11, 0, 3, 8, 235, 73, 51, 7, 10, 0, 4, 8, 236, 214, 26, 5, 11, -2, 3, 3, 237, 250, 14, 5, 11, -1, 3, 3, 238, 193, 26, 6, 11, -2, 3, 3, 239, 142, 50, 6, 10, -2, 4, 3, 240, 185, 26, 7, 11, 0, 3, 8, 241, 106, 15, 7, 12, 0, 2, 8, 242, 129, 27, 7, 11, 0, 3, 8, 243, 137, 27, 7, 11, 0, 3, 8, 244, 145, 27, 7, 11, 0, 3, 8, 245, 114, 14, 7, 12, 0, 2, 8, 246, 49, 52, 7, 10, 0, 4, 8, 247, 237, 48, 8, 8, -1, 5, 7, 248, 201, 38, 8, 10, 0, 5, 8, 249, 161, 27, 7, 11, 0, 3, 8, 250, 169, 26, 7, 11, 0, 3, 8, 251, 177, 26, 7, 11, 0, 3, 8, 252, 89, 51, 7, 10, 0, 4, 8, 253, 41, 0, 8, 14, -1, 3, 7, 254, 68, 0, 7, 14, 0, 3, 8, 255, 219, 0, 8, 13, -1, 4, 7 };
diff --git a/editor/doc_title_font.h b/editor/doc_title_font.h
index afa0f61eda..bb8a394807 100644
--- a/editor/doc_title_font.h
+++ b/editor/doc_title_font.h
@@ -26,7 +26,7 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-static const int _bi_font_doc_title_font_height=22;
-static const int _bi_font_doc_title_font_ascent=17;
-static const int _bi_font_doc_title_font_charcount=193;
-static const int _bi_font_doc_title_font_characters[]={0, 108, 97, 2, 2, -1, 16, 0, 13, 111, 97, 2, 2, -1, 16, 0, 32, 252, 55, 2, 2, -1, 16, 4, 33, 84, 48, 3, 13, 1, 4, 6, 34, 9, 99, 6, 6, 0, 4, 8, 35, 52, 76, 9, 12, -1, 5, 9, 36, 31, 18, 9, 16, 0, 3, 9, 37, 28, 35, 13, 13, -1, 4, 13, 38, 56, 35, 12, 13, 0, 4, 13, 39, 16, 99, 3, 6, 0, 4, 4, 40, 48, 0, 5, 17, 0, 3, 6, 41, 54, 0, 5, 17, 0, 3, 6, 42, 207, 84, 9, 8, 0, 3, 9, 43, 121, 86, 9, 9, 0, 7, 9, 44, 251, 71, 4, 6, -1, 13, 5, 45, 102, 97, 5, 3, 0, 10, 6, 46, 66, 99, 4, 4, 0, 13, 5, 47, 24, 0, 9, 17, -2, 3, 8, 48, 11, 76, 10, 12, -1, 5, 9, 49, 102, 74, 9, 12, 0, 5, 9, 50, 48, 63, 10, 12, -1, 5, 9, 51, 59, 63, 10, 12, -1, 5, 9, 52, 70, 63, 10, 12, -1, 5, 9, 53, 81, 62, 10, 12, -1, 5, 9, 54, 235, 59, 10, 12, -1, 5, 9, 55, 103, 61, 10, 12, -1, 5, 9, 56, 114, 60, 10, 12, -1, 5, 9, 57, 125, 60, 10, 12, -1, 5, 9, 58, 252, 45, 3, 9, 0, 8, 5, 59, 246, 71, 4, 11, -1, 8, 5, 60, 148, 73, 8, 12, 0, 5, 9, 61, 0, 100, 8, 7, 0, 8, 9, 62, 139, 73, 8, 12, 0, 5, 9, 63, 40, 49, 8, 13, 0, 4, 8, 64, 184, 17, 15, 14, 0, 5, 16, 65, 178, 47, 12, 12, -1, 5, 11, 66, 136, 60, 10, 12, 0, 5, 10, 67, 240, 45, 11, 12, -1, 5, 10, 68, 0, 63, 11, 12, 0, 5, 11, 69, 130, 73, 8, 12, 0, 5, 9, 70, 112, 74, 8, 12, 0, 5, 8, 71, 191, 46, 12, 12, -1, 5, 11, 72, 24, 63, 11, 12, 0, 5, 11, 73, 193, 72, 4, 12, 0, 5, 5, 74, 173, 73, 6, 12, -1, 5, 6, 75, 147, 60, 10, 12, 0, 5, 10, 76, 121, 73, 8, 12, 0, 5, 8, 77, 122, 47, 15, 12, 0, 5, 16, 78, 12, 63, 11, 12, 0, 5, 12, 79, 138, 47, 13, 12, -1, 5, 12, 80, 62, 76, 9, 12, 0, 5, 10, 81, 200, 17, 14, 14, -1, 5, 12, 82, 158, 60, 10, 12, 0, 5, 10, 83, 32, 76, 9, 12, -1, 5, 9, 84, 169, 60, 10, 12, -1, 5, 9, 85, 204, 46, 11, 12, 0, 5, 12, 86, 165, 47, 12, 12, -1, 5, 11, 87, 88, 48, 17, 12, -1, 5, 16, 88, 216, 46, 11, 12, -1, 5, 10, 89, 228, 46, 11, 12, -1, 5, 9, 90, 180, 60, 10, 12, -1, 5, 9, 91, 249, 0, 5, 16, 0, 4, 6, 92, 13, 0, 10, 17, -2, 3, 8, 93, 85, 17, 5, 16, 0, 4, 6, 94, 196, 85, 10, 8, -1, 5, 9, 95, 71, 99, 10, 3, -1, 17, 9, 96, 46, 99, 6, 4, -1, 4, 5, 97, 111, 87, 9, 9, -1, 8, 9, 98, 207, 32, 9, 13, 0, 4, 10, 99, 161, 86, 8, 9, -1, 8, 8, 100, 69, 34, 10, 13, -1, 4, 10, 101, 89, 88, 10, 9, -1, 8, 9, 102, 58, 49, 7, 13, -1, 4, 6, 103, 191, 59, 10, 12, -1, 8, 9, 104, 177, 33, 9, 13, 0, 4, 10, 105, 187, 73, 5, 12, -1, 5, 4, 106, 177, 17, 6, 15, -2, 5, 5, 107, 217, 32, 9, 13, 0, 4, 9, 108, 250, 17, 4, 13, 0, 4, 4, 109, 24, 89, 14, 9, 0, 8, 15, 110, 151, 86, 9, 9, 0, 8, 10, 111, 100, 87, 10, 9, -1, 8, 10, 112, 42, 76, 9, 12, 0, 8, 10, 113, 213, 59, 10, 12, -1, 8, 10, 114, 188, 86, 7, 9, 0, 8, 6, 115, 170, 86, 8, 9, -1, 8, 7, 116, 230, 72, 7, 11, -1, 6, 6, 117, 141, 86, 9, 9, 0, 8, 10, 118, 78, 89, 10, 9, -1, 8, 9, 119, 8, 89, 15, 9, -1, 8, 13, 120, 131, 86, 9, 9, -1, 8, 8, 121, 224, 59, 10, 12, -1, 8, 9, 122, 179, 86, 8, 9, -1, 8, 7, 123, 34, 0, 6, 17, -1, 3, 6, 124, 64, 0, 3, 17, 2, 3, 9, 125, 41, 0, 6, 17, 0, 3, 6, 126, 30, 99, 9, 5, 0, 5, 9, 160, 114, 97, 2, 2, -1, 16, 4, 161, 80, 48, 3, 13, 1, 6, 6, 162, 165, 73, 7, 12, 0, 5, 9, 163, 92, 74, 9, 12, 0, 5, 9, 164, 209, 72, 10, 11, -1, 6, 9, 165, 36, 63, 11, 12, -2, 5, 9, 166, 60, 0, 3, 17, 2, 3, 9, 167, 151, 17, 8, 15, 0, 4, 9, 168, 82, 99, 6, 3, 0, 5, 7, 169, 236, 17, 13, 13, 0, 4, 15, 170, 238, 72, 7, 11, 0, 5, 7, 171, 54, 89, 11, 9, -1, 7, 10, 172, 20, 99, 9, 5, -1, 10, 9, 173, 96, 98, 5, 3, 0, 10, 6, 174, 226, 84, 8, 8, 0, 4, 9, 175, 89, 98, 6, 3, 0, 4, 7, 176, 40, 99, 5, 5, 0, 4, 6, 177, 22, 76, 9, 12, 0, 5, 9, 178, 235, 84, 6, 8, 0, 3, 6, 179, 242, 84, 6, 8, 0, 3, 6, 180, 53, 99, 6, 4, -1, 4, 5, 181, 0, 76, 10, 12, 0, 8, 10, 182, 215, 17, 10, 14, 0, 5, 11, 183, 251, 78, 3, 4, 0, 9, 5, 184, 60, 99, 5, 4, 0, 16, 5, 185, 249, 83, 5, 8, -1, 3, 5, 186, 0, 89, 7, 10, 0, 5, 8, 187, 66, 89, 11, 9, -1, 7, 10, 188, 42, 35, 13, 13, -1, 4, 12, 189, 0, 35, 13, 13, -1, 4, 12, 190, 14, 35, 13, 13, -1, 4, 13, 191, 49, 49, 8, 13, -1, 6, 8, 192, 150, 0, 12, 16, -1, 1, 11, 193, 176, 0, 12, 16, -1, 1, 11, 194, 163, 0, 12, 16, -1, 1, 11, 195, 124, 0, 12, 16, -1, 1, 11, 196, 105, 17, 12, 15, -1, 2, 11, 197, 0, 0, 12, 17, -1, 0, 11, 198, 106, 47, 15, 12, -1, 5, 14, 199, 141, 17, 9, 15, 0, 5, 10, 200, 60, 18, 8, 16, 0, 1, 9, 201, 41, 18, 9, 16, 0, 1, 9, 202, 21, 18, 9, 16, 0, 1, 9, 203, 160, 17, 8, 15, 0, 2, 9, 204, 69, 17, 7, 16, -2, 1, 5, 205, 77, 17, 7, 16, -1, 1, 5, 206, 51, 18, 8, 16, -2, 1, 5, 207, 169, 17, 7, 15, -2, 2, 5, 208, 152, 47, 12, 12, -1, 5, 12, 209, 237, 0, 11, 16, 0, 1, 12, 210, 82, 0, 13, 16, -1, 1, 12, 211, 68, 0, 13, 16, -1, 1, 12, 212, 110, 0, 13, 16, -1, 1, 12, 213, 96, 0, 13, 16, -1, 1, 12, 214, 91, 17, 13, 15, -1, 2, 12, 215, 217, 84, 8, 8, 0, 8, 9, 216, 137, 0, 12, 16, 0, 3, 12, 217, 225, 0, 11, 16, 0, 1, 12, 218, 189, 0, 11, 16, 0, 1, 12, 219, 213, 0, 11, 16, 0, 1, 12, 220, 118, 17, 11, 15, 0, 2, 12, 221, 201, 0, 11, 16, -1, 1, 9, 222, 72, 76, 9, 12, 0, 5, 10, 223, 167, 33, 9, 13, 0, 4, 10, 224, 157, 33, 9, 13, -1, 4, 9, 225, 30, 49, 9, 13, -1, 4, 9, 226, 227, 32, 9, 13, -1, 4, 9, 227, 237, 31, 9, 13, -1, 4, 9, 228, 82, 75, 9, 12, -1, 5, 9, 229, 226, 17, 9, 14, -1, 3, 9, 230, 39, 89, 14, 9, 0, 8, 14, 231, 157, 73, 7, 12, 0, 8, 8, 232, 146, 33, 10, 13, -1, 4, 9, 233, 80, 34, 10, 13, -1, 4, 9, 234, 91, 33, 10, 13, -1, 4, 9, 235, 92, 61, 10, 12, -1, 5, 9, 236, 66, 49, 6, 13, -2, 4, 4, 237, 73, 48, 6, 13, -1, 4, 4, 238, 247, 31, 8, 13, -2, 4, 4, 239, 180, 73, 6, 12, -1, 5, 4, 240, 187, 32, 9, 13, 0, 4, 10, 241, 197, 32, 9, 13, 0, 4, 10, 242, 102, 33, 10, 13, -1, 4, 10, 243, 113, 33, 10, 13, -1, 4, 10, 244, 124, 33, 10, 13, -1, 4, 10, 245, 135, 33, 10, 13, -1, 4, 10, 246, 202, 59, 10, 12, -1, 5, 10, 247, 220, 72, 9, 11, -1, 6, 9, 248, 198, 72, 10, 11, 0, 7, 10, 249, 0, 49, 9, 13, 0, 4, 10, 250, 10, 49, 9, 13, 0, 4, 10, 251, 20, 49, 9, 13, 0, 4, 10, 252, 246, 58, 9, 12, 0, 5, 10, 253, 0, 18, 10, 16, -1, 4, 9, 254, 11, 18, 9, 16, 0, 4, 10, 255, 130, 17, 10, 15, -1, 5, 9};
+static const int _bi_font_doc_title_font_height = 22;
+static const int _bi_font_doc_title_font_ascent = 17;
+static const int _bi_font_doc_title_font_charcount = 193;
+static const int _bi_font_doc_title_font_characters[] = { 0, 108, 97, 2, 2, -1, 16, 0, 13, 111, 97, 2, 2, -1, 16, 0, 32, 252, 55, 2, 2, -1, 16, 4, 33, 84, 48, 3, 13, 1, 4, 6, 34, 9, 99, 6, 6, 0, 4, 8, 35, 52, 76, 9, 12, -1, 5, 9, 36, 31, 18, 9, 16, 0, 3, 9, 37, 28, 35, 13, 13, -1, 4, 13, 38, 56, 35, 12, 13, 0, 4, 13, 39, 16, 99, 3, 6, 0, 4, 4, 40, 48, 0, 5, 17, 0, 3, 6, 41, 54, 0, 5, 17, 0, 3, 6, 42, 207, 84, 9, 8, 0, 3, 9, 43, 121, 86, 9, 9, 0, 7, 9, 44, 251, 71, 4, 6, -1, 13, 5, 45, 102, 97, 5, 3, 0, 10, 6, 46, 66, 99, 4, 4, 0, 13, 5, 47, 24, 0, 9, 17, -2, 3, 8, 48, 11, 76, 10, 12, -1, 5, 9, 49, 102, 74, 9, 12, 0, 5, 9, 50, 48, 63, 10, 12, -1, 5, 9, 51, 59, 63, 10, 12, -1, 5, 9, 52, 70, 63, 10, 12, -1, 5, 9, 53, 81, 62, 10, 12, -1, 5, 9, 54, 235, 59, 10, 12, -1, 5, 9, 55, 103, 61, 10, 12, -1, 5, 9, 56, 114, 60, 10, 12, -1, 5, 9, 57, 125, 60, 10, 12, -1, 5, 9, 58, 252, 45, 3, 9, 0, 8, 5, 59, 246, 71, 4, 11, -1, 8, 5, 60, 148, 73, 8, 12, 0, 5, 9, 61, 0, 100, 8, 7, 0, 8, 9, 62, 139, 73, 8, 12, 0, 5, 9, 63, 40, 49, 8, 13, 0, 4, 8, 64, 184, 17, 15, 14, 0, 5, 16, 65, 178, 47, 12, 12, -1, 5, 11, 66, 136, 60, 10, 12, 0, 5, 10, 67, 240, 45, 11, 12, -1, 5, 10, 68, 0, 63, 11, 12, 0, 5, 11, 69, 130, 73, 8, 12, 0, 5, 9, 70, 112, 74, 8, 12, 0, 5, 8, 71, 191, 46, 12, 12, -1, 5, 11, 72, 24, 63, 11, 12, 0, 5, 11, 73, 193, 72, 4, 12, 0, 5, 5, 74, 173, 73, 6, 12, -1, 5, 6, 75, 147, 60, 10, 12, 0, 5, 10, 76, 121, 73, 8, 12, 0, 5, 8, 77, 122, 47, 15, 12, 0, 5, 16, 78, 12, 63, 11, 12, 0, 5, 12, 79, 138, 47, 13, 12, -1, 5, 12, 80, 62, 76, 9, 12, 0, 5, 10, 81, 200, 17, 14, 14, -1, 5, 12, 82, 158, 60, 10, 12, 0, 5, 10, 83, 32, 76, 9, 12, -1, 5, 9, 84, 169, 60, 10, 12, -1, 5, 9, 85, 204, 46, 11, 12, 0, 5, 12, 86, 165, 47, 12, 12, -1, 5, 11, 87, 88, 48, 17, 12, -1, 5, 16, 88, 216, 46, 11, 12, -1, 5, 10, 89, 228, 46, 11, 12, -1, 5, 9, 90, 180, 60, 10, 12, -1, 5, 9, 91, 249, 0, 5, 16, 0, 4, 6, 92, 13, 0, 10, 17, -2, 3, 8, 93, 85, 17, 5, 16, 0, 4, 6, 94, 196, 85, 10, 8, -1, 5, 9, 95, 71, 99, 10, 3, -1, 17, 9, 96, 46, 99, 6, 4, -1, 4, 5, 97, 111, 87, 9, 9, -1, 8, 9, 98, 207, 32, 9, 13, 0, 4, 10, 99, 161, 86, 8, 9, -1, 8, 8, 100, 69, 34, 10, 13, -1, 4, 10, 101, 89, 88, 10, 9, -1, 8, 9, 102, 58, 49, 7, 13, -1, 4, 6, 103, 191, 59, 10, 12, -1, 8, 9, 104, 177, 33, 9, 13, 0, 4, 10, 105, 187, 73, 5, 12, -1, 5, 4, 106, 177, 17, 6, 15, -2, 5, 5, 107, 217, 32, 9, 13, 0, 4, 9, 108, 250, 17, 4, 13, 0, 4, 4, 109, 24, 89, 14, 9, 0, 8, 15, 110, 151, 86, 9, 9, 0, 8, 10, 111, 100, 87, 10, 9, -1, 8, 10, 112, 42, 76, 9, 12, 0, 8, 10, 113, 213, 59, 10, 12, -1, 8, 10, 114, 188, 86, 7, 9, 0, 8, 6, 115, 170, 86, 8, 9, -1, 8, 7, 116, 230, 72, 7, 11, -1, 6, 6, 117, 141, 86, 9, 9, 0, 8, 10, 118, 78, 89, 10, 9, -1, 8, 9, 119, 8, 89, 15, 9, -1, 8, 13, 120, 131, 86, 9, 9, -1, 8, 8, 121, 224, 59, 10, 12, -1, 8, 9, 122, 179, 86, 8, 9, -1, 8, 7, 123, 34, 0, 6, 17, -1, 3, 6, 124, 64, 0, 3, 17, 2, 3, 9, 125, 41, 0, 6, 17, 0, 3, 6, 126, 30, 99, 9, 5, 0, 5, 9, 160, 114, 97, 2, 2, -1, 16, 4, 161, 80, 48, 3, 13, 1, 6, 6, 162, 165, 73, 7, 12, 0, 5, 9, 163, 92, 74, 9, 12, 0, 5, 9, 164, 209, 72, 10, 11, -1, 6, 9, 165, 36, 63, 11, 12, -2, 5, 9, 166, 60, 0, 3, 17, 2, 3, 9, 167, 151, 17, 8, 15, 0, 4, 9, 168, 82, 99, 6, 3, 0, 5, 7, 169, 236, 17, 13, 13, 0, 4, 15, 170, 238, 72, 7, 11, 0, 5, 7, 171, 54, 89, 11, 9, -1, 7, 10, 172, 20, 99, 9, 5, -1, 10, 9, 173, 96, 98, 5, 3, 0, 10, 6, 174, 226, 84, 8, 8, 0, 4, 9, 175, 89, 98, 6, 3, 0, 4, 7, 176, 40, 99, 5, 5, 0, 4, 6, 177, 22, 76, 9, 12, 0, 5, 9, 178, 235, 84, 6, 8, 0, 3, 6, 179, 242, 84, 6, 8, 0, 3, 6, 180, 53, 99, 6, 4, -1, 4, 5, 181, 0, 76, 10, 12, 0, 8, 10, 182, 215, 17, 10, 14, 0, 5, 11, 183, 251, 78, 3, 4, 0, 9, 5, 184, 60, 99, 5, 4, 0, 16, 5, 185, 249, 83, 5, 8, -1, 3, 5, 186, 0, 89, 7, 10, 0, 5, 8, 187, 66, 89, 11, 9, -1, 7, 10, 188, 42, 35, 13, 13, -1, 4, 12, 189, 0, 35, 13, 13, -1, 4, 12, 190, 14, 35, 13, 13, -1, 4, 13, 191, 49, 49, 8, 13, -1, 6, 8, 192, 150, 0, 12, 16, -1, 1, 11, 193, 176, 0, 12, 16, -1, 1, 11, 194, 163, 0, 12, 16, -1, 1, 11, 195, 124, 0, 12, 16, -1, 1, 11, 196, 105, 17, 12, 15, -1, 2, 11, 197, 0, 0, 12, 17, -1, 0, 11, 198, 106, 47, 15, 12, -1, 5, 14, 199, 141, 17, 9, 15, 0, 5, 10, 200, 60, 18, 8, 16, 0, 1, 9, 201, 41, 18, 9, 16, 0, 1, 9, 202, 21, 18, 9, 16, 0, 1, 9, 203, 160, 17, 8, 15, 0, 2, 9, 204, 69, 17, 7, 16, -2, 1, 5, 205, 77, 17, 7, 16, -1, 1, 5, 206, 51, 18, 8, 16, -2, 1, 5, 207, 169, 17, 7, 15, -2, 2, 5, 208, 152, 47, 12, 12, -1, 5, 12, 209, 237, 0, 11, 16, 0, 1, 12, 210, 82, 0, 13, 16, -1, 1, 12, 211, 68, 0, 13, 16, -1, 1, 12, 212, 110, 0, 13, 16, -1, 1, 12, 213, 96, 0, 13, 16, -1, 1, 12, 214, 91, 17, 13, 15, -1, 2, 12, 215, 217, 84, 8, 8, 0, 8, 9, 216, 137, 0, 12, 16, 0, 3, 12, 217, 225, 0, 11, 16, 0, 1, 12, 218, 189, 0, 11, 16, 0, 1, 12, 219, 213, 0, 11, 16, 0, 1, 12, 220, 118, 17, 11, 15, 0, 2, 12, 221, 201, 0, 11, 16, -1, 1, 9, 222, 72, 76, 9, 12, 0, 5, 10, 223, 167, 33, 9, 13, 0, 4, 10, 224, 157, 33, 9, 13, -1, 4, 9, 225, 30, 49, 9, 13, -1, 4, 9, 226, 227, 32, 9, 13, -1, 4, 9, 227, 237, 31, 9, 13, -1, 4, 9, 228, 82, 75, 9, 12, -1, 5, 9, 229, 226, 17, 9, 14, -1, 3, 9, 230, 39, 89, 14, 9, 0, 8, 14, 231, 157, 73, 7, 12, 0, 8, 8, 232, 146, 33, 10, 13, -1, 4, 9, 233, 80, 34, 10, 13, -1, 4, 9, 234, 91, 33, 10, 13, -1, 4, 9, 235, 92, 61, 10, 12, -1, 5, 9, 236, 66, 49, 6, 13, -2, 4, 4, 237, 73, 48, 6, 13, -1, 4, 4, 238, 247, 31, 8, 13, -2, 4, 4, 239, 180, 73, 6, 12, -1, 5, 4, 240, 187, 32, 9, 13, 0, 4, 10, 241, 197, 32, 9, 13, 0, 4, 10, 242, 102, 33, 10, 13, -1, 4, 10, 243, 113, 33, 10, 13, -1, 4, 10, 244, 124, 33, 10, 13, -1, 4, 10, 245, 135, 33, 10, 13, -1, 4, 10, 246, 202, 59, 10, 12, -1, 5, 10, 247, 220, 72, 9, 11, -1, 6, 9, 248, 198, 72, 10, 11, 0, 7, 10, 249, 0, 49, 9, 13, 0, 4, 10, 250, 10, 49, 9, 13, 0, 4, 10, 251, 20, 49, 9, 13, 0, 4, 10, 252, 246, 58, 9, 12, 0, 5, 10, 253, 0, 18, 10, 16, -1, 4, 9, 254, 11, 18, 9, 16, 0, 4, 10, 255, 130, 17, 10, 15, -1, 5, 9 };
diff --git a/editor/editor_asset_installer.cpp b/editor/editor_asset_installer.cpp
index 8af01012a4..dfe63aacc2 100644
--- a/editor/editor_asset_installer.cpp
+++ b/editor/editor_asset_installer.cpp
@@ -28,36 +28,32 @@
/*************************************************************************/
#include "editor_asset_installer.h"
+#include "editor_node.h"
#include "io/zip_io.h"
#include "os/dir_access.h"
#include "os/file_access.h"
-#include "editor_node.h"
-
-void EditorAssetInstaller::_update_subitems(TreeItem* p_item,bool p_check,bool p_first) {
+void EditorAssetInstaller::_update_subitems(TreeItem *p_item, bool p_check, bool p_first) {
if (p_check) {
- if (p_item->get_custom_color(0)==Color()) {
- p_item->set_checked(0,true);
+ if (p_item->get_custom_color(0) == Color()) {
+ p_item->set_checked(0, true);
}
} else {
- p_item->set_checked(0,false);
-
+ p_item->set_checked(0, false);
}
if (p_item->get_children()) {
- _update_subitems(p_item->get_children(),p_check);
+ _update_subitems(p_item->get_children(), p_check);
}
if (!p_first && p_item->get_next()) {
- _update_subitems(p_item->get_next(),p_check);
+ _update_subitems(p_item->get_next(), p_check);
}
-
}
void EditorAssetInstaller::_item_edited() {
-
if (updating)
return;
@@ -65,32 +61,28 @@ void EditorAssetInstaller::_item_edited() {
if (!item)
return;
+ String path = item->get_metadata(0);
- String path=item->get_metadata(0);
-
- updating=true;
- if (path==String()) { //a dir
- _update_subitems(item,item->is_checked(0),true);
+ updating = true;
+ if (path == String()) { //a dir
+ _update_subitems(item, item->is_checked(0), true);
}
if (item->is_checked(0)) {
- while(item) {
- item->set_checked(0,true);
- item=item->get_parent();
+ while (item) {
+ item->set_checked(0, true);
+ item = item->get_parent();
}
-
}
- updating=false;
-
+ updating = false;
}
-void EditorAssetInstaller::open(const String& p_path,int p_depth) {
-
+void EditorAssetInstaller::open(const String &p_path, int p_depth) {
- package_path=p_path;
+ package_path = p_path;
Set<String> files_sorted;
- FileAccess *src_f=NULL;
+ FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(p_path.utf8().get_data(), &io);
@@ -102,138 +94,126 @@ void EditorAssetInstaller::open(const String& p_path,int p_depth) {
int ret = unzGoToFirstFile(pkg);
-
- while(ret==UNZ_OK) {
+ while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
- ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);
+ ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
- String name=fname;
+ String name = fname;
files_sorted.insert(name);
ret = unzGoToNextFile(pkg);
}
-
- Map<String,Ref<Texture> > extension_guess;
+ Map<String, Ref<Texture> > extension_guess;
{
- extension_guess["png"]=get_icon("Texture","EditorIcons");
- extension_guess["jpg"]=get_icon("Texture","EditorIcons");
- extension_guess["tex"]=get_icon("Texture","EditorIcons");
- extension_guess["atex"]=get_icon("Texture","EditorIcons");
- extension_guess["dds"]=get_icon("Texture","EditorIcons");
- extension_guess["scn"]=get_icon("PackedScene","EditorIcons");
- extension_guess["tscn"]=get_icon("PackedScene","EditorIcons");
- extension_guess["xml"]=get_icon("PackedScene","EditorIcons");
- extension_guess["xscn"]=get_icon("PackedScene","EditorIcons");
- extension_guess["mtl"]=get_icon("Material","EditorIcons");
- extension_guess["shd"]=get_icon("Shader","EditorIcons");
- extension_guess["gd"]=get_icon("GDScript","EditorIcons");
+ extension_guess["png"] = get_icon("Texture", "EditorIcons");
+ extension_guess["jpg"] = get_icon("Texture", "EditorIcons");
+ extension_guess["tex"] = get_icon("Texture", "EditorIcons");
+ extension_guess["atex"] = get_icon("Texture", "EditorIcons");
+ extension_guess["dds"] = get_icon("Texture", "EditorIcons");
+ extension_guess["scn"] = get_icon("PackedScene", "EditorIcons");
+ extension_guess["tscn"] = get_icon("PackedScene", "EditorIcons");
+ extension_guess["xml"] = get_icon("PackedScene", "EditorIcons");
+ extension_guess["xscn"] = get_icon("PackedScene", "EditorIcons");
+ extension_guess["mtl"] = get_icon("Material", "EditorIcons");
+ extension_guess["shd"] = get_icon("Shader", "EditorIcons");
+ extension_guess["gd"] = get_icon("GDScript", "EditorIcons");
}
- Ref<Texture> generic_extension = get_icon("Object","EditorIcons");
-
+ Ref<Texture> generic_extension = get_icon("Object", "EditorIcons");
unzClose(pkg);
- updating=true;
+ updating = true;
tree->clear();
- TreeItem *root=tree->create_item();
- root->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- root->set_checked(0,true);
- root->set_icon(0,get_icon("folder","FileDialog"));
- root->set_text(0,"res://");
- root->set_editable(0,true);
- Map<String,TreeItem*> dir_map;
+ TreeItem *root = tree->create_item();
+ root->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ root->set_checked(0, true);
+ root->set_icon(0, get_icon("folder", "FileDialog"));
+ root->set_text(0, "res://");
+ root->set_editable(0, true);
+ Map<String, TreeItem *> dir_map;
- for(Set<String>::Element *E=files_sorted.front();E;E=E->next()) {
+ for (Set<String>::Element *E = files_sorted.front(); E; E = E->next()) {
String path = E->get();
- int depth=p_depth;
- bool skip=false;
- while(depth>0) {
+ int depth = p_depth;
+ bool skip = false;
+ while (depth > 0) {
int pp = path.find("/");
- if (pp==-1) {
- skip=true;
+ if (pp == -1) {
+ skip = true;
break;
}
- path=path.substr(pp+1,path.length());
+ path = path.substr(pp + 1, path.length());
depth--;
}
- if (skip || path==String())
+ if (skip || path == String())
continue;
- bool isdir=false;
+ bool isdir = false;
if (path.ends_with("/")) {
//a directory
- path=path.substr(0,path.length()-1);
- isdir=true;
+ path = path.substr(0, path.length() - 1);
+ isdir = true;
}
int pp = path.find_last("/");
-
TreeItem *parent;
- if (pp==-1) {
- parent=root;
+ if (pp == -1) {
+ parent = root;
} else {
- String ppath=path.substr(0,pp);
- print_line("PPATH IS: "+ppath);
+ String ppath = path.substr(0, pp);
+ print_line("PPATH IS: " + ppath);
ERR_CONTINUE(!dir_map.has(ppath));
- parent=dir_map[ppath];
-
+ parent = dir_map[ppath];
}
TreeItem *ti = tree->create_item(parent);
- ti->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- ti->set_checked(0,true);
- ti->set_editable(0,true);
+ ti->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ ti->set_checked(0, true);
+ ti->set_editable(0, true);
if (isdir) {
- dir_map[path]=ti;
- ti->set_text(0,path.get_file()+"/");
- ti->set_icon(0,get_icon("folder","FileDialog"));
+ dir_map[path] = ti;
+ ti->set_text(0, path.get_file() + "/");
+ ti->set_icon(0, get_icon("folder", "FileDialog"));
} else {
String file = path.get_file();
String extension = file.get_extension().to_lower();
if (extension_guess.has(extension)) {
- ti->set_icon(0,extension_guess[extension]);
+ ti->set_icon(0, extension_guess[extension]);
} else {
- ti->set_icon(0,generic_extension);
+ ti->set_icon(0, generic_extension);
}
- ti->set_text(0,file);
+ ti->set_text(0, file);
-
- String res_path = "res://"+path;
+ String res_path = "res://" + path;
if (FileAccess::exists(res_path)) {
- ti->set_custom_color(0,Color(1,0.3,0.2));
- ti->set_tooltip(0,res_path+" (Already Exists)");
- ti->set_checked(0,false);
+ ti->set_custom_color(0, Color(1, 0.3, 0.2));
+ ti->set_tooltip(0, res_path + " (Already Exists)");
+ ti->set_checked(0, false);
} else {
- ti->set_tooltip(0,res_path);
-
+ ti->set_tooltip(0, res_path);
}
- ti->set_metadata(0,res_path);
-
+ ti->set_metadata(0, res_path);
}
- status_map[E->get()]=ti;
-
-
-
+ status_map[E->get()] = ti;
}
popup_centered_ratio();
- updating=false;
-
+ updating = false;
}
void EditorAssetInstaller::ok_pressed() {
- FileAccess *src_f=NULL;
+ FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(package_path.utf8().get_data(), &io);
@@ -247,32 +227,32 @@ void EditorAssetInstaller::ok_pressed() {
Vector<String> failed_files;
- ProgressDialog::get_singleton()->add_task("uncompress","Uncompressing Assets",status_map.size());
+ ProgressDialog::get_singleton()->add_task("uncompress", "Uncompressing Assets", status_map.size());
- int idx=0;
- while(ret==UNZ_OK) {
+ int idx = 0;
+ while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
- ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);
+ ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
- String name=fname;
+ String name = fname;
if (status_map.has(name) && status_map[name]->is_checked(0)) {
String path = status_map[name]->get_metadata(0);
- if (path==String()) { // a dir
+ if (path == String()) { // a dir
String dirpath;
TreeItem *t = status_map[name];
- while(t) {
- dirpath=t->get_text(0)+dirpath;
- t=t->get_parent();
+ while (t) {
+ dirpath = t->get_text(0) + dirpath;
+ t = t->get_parent();
}
if (dirpath.ends_with("/")) {
- dirpath=dirpath.substr(0,dirpath.length()-1);
+ dirpath = dirpath.substr(0, dirpath.length() - 1);
}
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
@@ -286,20 +266,19 @@ void EditorAssetInstaller::ok_pressed() {
//read
unzOpenCurrentFile(pkg);
- unzReadCurrentFile(pkg,data.ptr(),data.size());
+ unzReadCurrentFile(pkg, data.ptr(), data.size());
unzCloseCurrentFile(pkg);
- FileAccess *f=FileAccess::open(path,FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(path, FileAccess::WRITE);
if (f) {
- f->store_buffer(data.ptr(),data.size());
+ f->store_buffer(data.ptr(), data.size());
memdelete(f);
} else {
failed_files.push_back(path);
}
- ProgressDialog::get_singleton()->task_step("uncompress",path,idx);
+ ProgressDialog::get_singleton()->task_step("uncompress", path, idx);
}
-
}
idx++;
@@ -310,50 +289,43 @@ void EditorAssetInstaller::ok_pressed() {
unzClose(pkg);
if (failed_files.size()) {
- String msg="The following files failed extraction from package:\n\n";
- for(int i=0;i<failed_files.size();i++) {
+ String msg = "The following files failed extraction from package:\n\n";
+ for (int i = 0; i < failed_files.size(); i++) {
- if (i>15) {
- msg+="\nAnd "+itos(failed_files.size()-i)+" more files.";
+ if (i > 15) {
+ msg += "\nAnd " + itos(failed_files.size() - i) + " more files.";
break;
}
- msg+=failed_files[i];
+ msg += failed_files[i];
}
if (EditorNode::get_singleton() != NULL)
EditorNode::get_singleton()->show_warning(msg);
} else {
if (EditorNode::get_singleton() != NULL)
- EditorNode::get_singleton()->show_warning("Package Installed Successfully!","Success!");
+ EditorNode::get_singleton()->show_warning("Package Installed Successfully!", "Success!");
}
-
-
-
-
}
void EditorAssetInstaller::_bind_methods() {
- ClassDB::bind_method("_item_edited",&EditorAssetInstaller::_item_edited);
-
+ ClassDB::bind_method("_item_edited", &EditorAssetInstaller::_item_edited);
}
EditorAssetInstaller::EditorAssetInstaller() {
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
+ tree = memnew(Tree);
+ vb->add_margin_child("Package Contents:", tree, true);
+ tree->connect("item_edited", this, "_item_edited");
- tree = memnew( Tree );
- vb->add_margin_child("Package Contents:",tree,true);
- tree->connect("item_edited",this,"_item_edited");
-
- error = memnew( AcceptDialog) ;
+ error = memnew(AcceptDialog);
add_child(error);
get_ok()->set_text("Install");
set_title("Package Installer");
- updating=false;
+ updating = false;
set_hide_on_ok(true);
}
-
diff --git a/editor/editor_asset_installer.h b/editor/editor_asset_installer.h
index 2d0486a6f6..046387520e 100644
--- a/editor/editor_asset_installer.h
+++ b/editor/editor_asset_installer.h
@@ -29,27 +29,26 @@
#ifndef EDITORASSETINSTALLER_H
#define EDITORASSETINSTALLER_H
-
#include "scene/gui/dialogs.h"
#include "scene/gui/tree.h"
class EditorAssetInstaller : public ConfirmationDialog {
- GDCLASS( EditorAssetInstaller, ConfirmationDialog );
+ GDCLASS(EditorAssetInstaller, ConfirmationDialog);
Tree *tree;
String package_path;
AcceptDialog *error;
- Map<String,TreeItem*> status_map;
+ Map<String, TreeItem *> status_map;
bool updating;
- void _update_subitems(TreeItem* p_item,bool p_check,bool p_first=false);
+ void _update_subitems(TreeItem *p_item, bool p_check, bool p_first = false);
void _item_edited();
virtual void ok_pressed();
-protected:
+protected:
static void _bind_methods();
-public:
- void open(const String& p_path,int p_depth=0);
+public:
+ void open(const String &p_path, int p_depth = 0);
EditorAssetInstaller();
};
diff --git a/editor/editor_audio_buses.cpp b/editor/editor_audio_buses.cpp
index 8643644950..36cb95a373 100644
--- a/editor/editor_audio_buses.cpp
+++ b/editor/editor_audio_buses.cpp
@@ -29,114 +29,109 @@
#include "editor_audio_buses.h"
#include "editor_node.h"
-#include "servers/audio_server.h"
-#include "os/keyboard.h"
-#include "io/resource_saver.h"
#include "filesystem_dock.h"
+#include "io/resource_saver.h"
+#include "os/keyboard.h"
+#include "servers/audio_server.h"
void EditorAudioBus::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
- vu_l->set_under_texture(get_icon("BusVuEmpty","EditorIcons"));
- vu_l->set_progress_texture(get_icon("BusVuFull","EditorIcons"));
- vu_r->set_under_texture(get_icon("BusVuEmpty","EditorIcons"));
- vu_r->set_progress_texture(get_icon("BusVuFull","EditorIcons"));
- scale->set_texture( get_icon("BusVuDb","EditorIcons"));
+ vu_l->set_under_texture(get_icon("BusVuEmpty", "EditorIcons"));
+ vu_l->set_progress_texture(get_icon("BusVuFull", "EditorIcons"));
+ vu_r->set_under_texture(get_icon("BusVuEmpty", "EditorIcons"));
+ vu_r->set_progress_texture(get_icon("BusVuFull", "EditorIcons"));
+ scale->set_texture(get_icon("BusVuDb", "EditorIcons"));
- disabled_vu = get_icon("BusVuFrozen","EditorIcons");
+ disabled_vu = get_icon("BusVuFrozen", "EditorIcons");
- prev_active=true;
+ prev_active = true;
update_bus();
set_process(true);
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (has_focus()) {
- draw_style_box(get_stylebox("focus","Button"),Rect2(Vector2(),get_size()));
+ draw_style_box(get_stylebox("focus", "Button"), Rect2(Vector2(), get_size()));
}
}
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
- float real_peak[2]={-100,-100};
- bool activity_found=false;
+ float real_peak[2] = { -100, -100 };
+ bool activity_found = false;
int cc;
- switch(AudioServer::get_singleton()->get_speaker_mode()) {
+ switch (AudioServer::get_singleton()->get_speaker_mode()) {
case AudioServer::SPEAKER_MODE_STEREO: cc = 1; break;
case AudioServer::SPEAKER_SURROUND_51: cc = 4; break;
case AudioServer::SPEAKER_SURROUND_71: cc = 5; break;
}
- for(int i=0;i<cc;i++) {
- if (AudioServer::get_singleton()->is_bus_channel_active(get_index(),i)) {
- activity_found=true;
- real_peak[0]=MAX(real_peak[0],AudioServer::get_singleton()->get_bus_peak_volume_left_db(get_index(),i));
- real_peak[1]=MAX(real_peak[1],AudioServer::get_singleton()->get_bus_peak_volume_right_db(get_index(),i));
+ for (int i = 0; i < cc; i++) {
+ if (AudioServer::get_singleton()->is_bus_channel_active(get_index(), i)) {
+ activity_found = true;
+ real_peak[0] = MAX(real_peak[0], AudioServer::get_singleton()->get_bus_peak_volume_left_db(get_index(), i));
+ real_peak[1] = MAX(real_peak[1], AudioServer::get_singleton()->get_bus_peak_volume_right_db(get_index(), i));
}
}
-
- if (real_peak[0]>peak_l) {
+ if (real_peak[0] > peak_l) {
peak_l = real_peak[0];
} else {
- peak_l-=get_process_delta_time()*60.0;
+ peak_l -= get_process_delta_time() * 60.0;
}
- if (real_peak[1]>peak_r) {
+ if (real_peak[1] > peak_r) {
peak_r = real_peak[1];
} else {
- peak_r-=get_process_delta_time()*60.0;
-
+ peak_r -= get_process_delta_time() * 60.0;
}
vu_l->set_value(peak_l);
vu_r->set_value(peak_r);
- if (activity_found!=prev_active) {
+ if (activity_found != prev_active) {
if (activity_found) {
vu_l->set_over_texture(Ref<Texture>());
vu_r->set_over_texture(Ref<Texture>());
} else {
vu_l->set_over_texture(disabled_vu);
vu_r->set_over_texture(disabled_vu);
-
}
- prev_active=activity_found;
+ prev_active = activity_found;
}
-
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- peak_l=-100;
- peak_r=-100;
- prev_active=true;
+ peak_l = -100;
+ peak_r = -100;
+ prev_active = true;
set_process(is_visible_in_tree());
}
-
}
void EditorAudioBus::update_send() {
send->clear();
- if (get_index()==0) {
+ if (get_index() == 0) {
send->set_disabled(true);
send->set_text("Speakers");
} else {
send->set_disabled(false);
StringName current_send = AudioServer::get_singleton()->get_bus_send(get_index());
- int current_send_index=0; //by default to master
+ int current_send_index = 0; //by default to master
- for(int i=0;i<get_index();i++) {
+ for (int i = 0; i < get_index(); i++) {
StringName send_name = AudioServer::get_singleton()->get_bus_name(i);
send->add_item(send_name);
- if (send_name==current_send) {
- current_send_index=i;
+ if (send_name == current_send) {
+ current_send_index = i;
}
}
@@ -149,63 +144,60 @@ void EditorAudioBus::update_bus() {
if (updating_bus)
return;
- updating_bus=true;
+ updating_bus = true;
int index = get_index();
slider->set_value(AudioServer::get_singleton()->get_bus_volume_db(index));
track_name->set_text(AudioServer::get_singleton()->get_bus_name(index));
- if (get_index()==0)
+ if (get_index() == 0)
track_name->set_editable(false);
- solo->set_pressed( AudioServer::get_singleton()->is_bus_solo(index));
- mute->set_pressed( AudioServer::get_singleton()->is_bus_mute(index));
- bypass->set_pressed( AudioServer::get_singleton()->is_bus_bypassing_effects(index));
+ solo->set_pressed(AudioServer::get_singleton()->is_bus_solo(index));
+ mute->set_pressed(AudioServer::get_singleton()->is_bus_mute(index));
+ bypass->set_pressed(AudioServer::get_singleton()->is_bus_bypassing_effects(index));
// effects..
effects->clear();
TreeItem *root = effects->create_item();
- for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(index);i++) {
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_effect_count(index); i++) {
- Ref<AudioEffect> afx = AudioServer::get_singleton()->get_bus_effect(index,i);
+ Ref<AudioEffect> afx = AudioServer::get_singleton()->get_bus_effect(index, i);
TreeItem *fx = effects->create_item(root);
- fx->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- fx->set_editable(0,true);
- fx->set_checked(0,AudioServer::get_singleton()->is_bus_effect_enabled(index,i));
- fx->set_text(0,afx->get_name());
- fx->set_metadata(0,i);
-
+ fx->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ fx->set_editable(0, true);
+ fx->set_checked(0, AudioServer::get_singleton()->is_bus_effect_enabled(index, i));
+ fx->set_text(0, afx->get_name());
+ fx->set_metadata(0, i);
}
TreeItem *add = effects->create_item(root);
- add->set_cell_mode(0,TreeItem::CELL_MODE_CUSTOM);
- add->set_editable(0,true);
- add->set_selectable(0,false);
- add->set_text(0,"Add Effect");
+ add->set_cell_mode(0, TreeItem::CELL_MODE_CUSTOM);
+ add->set_editable(0, true);
+ add->set_selectable(0, false);
+ add->set_text(0, "Add Effect");
update_send();
- updating_bus=false;
-
+ updating_bus = false;
}
+void EditorAudioBus::_name_changed(const String &p_new_name) {
-void EditorAudioBus::_name_changed(const String& p_new_name) {
-
- if (p_new_name==AudioServer::get_singleton()->get_bus_name(get_index()))
+ if (p_new_name == AudioServer::get_singleton()->get_bus_name(get_index()))
return;
- String attempt=p_new_name;
- int attempts=1;
+ String attempt = p_new_name;
+ int attempts = 1;
- while(true) {
+ while (true) {
- bool name_free=true;
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
+ bool name_free = true;
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
- if (AudioServer::get_singleton()->get_bus_name(i)==attempt) {
- name_free=false;
+ if (AudioServer::get_singleton()->get_bus_name(i) == attempt) {
+ name_free = false;
break;
}
}
@@ -215,115 +207,107 @@ void EditorAudioBus::_name_changed(const String& p_new_name) {
}
attempts++;
- attempt=p_new_name+" "+itos(attempts);
+ attempt = p_new_name + " " + itos(attempts);
}
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
StringName current = AudioServer::get_singleton()->get_bus_name(get_index());
ur->create_action("Rename Audio Bus");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_name",get_index(),attempt);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_name",get_index(),current);
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_name", get_index(), attempt);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_name", get_index(), current);
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
- if (AudioServer::get_singleton()->get_bus_send(i)==current) {
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",i,attempt);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",i,current);
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
+ if (AudioServer::get_singleton()->get_bus_send(i) == current) {
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_send", i, attempt);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_send", i, current);
}
}
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
-
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
- ur->add_do_method(buses,"_update_sends");
- ur->add_undo_method(buses,"_update_sends");
+ ur->add_do_method(buses, "_update_sends");
+ ur->add_undo_method(buses, "_update_sends");
ur->commit_action();
- updating_bus=false;
-
+ updating_bus = false;
}
-void EditorAudioBus::_volume_db_changed(float p_db){
+void EditorAudioBus::_volume_db_changed(float p_db) {
if (updating_bus)
return;
- updating_bus=true;
-
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- ur->create_action("Change Audio Bus Volume",UndoRedo::MERGE_ENDS);
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),p_db);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),AudioServer::get_singleton()->get_bus_volume_db(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->create_action("Change Audio Bus Volume", UndoRedo::MERGE_ENDS);
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_volume_db", get_index(), p_db);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_volume_db", get_index(), AudioServer::get_singleton()->get_bus_volume_db(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
-
+ updating_bus = false;
}
-void EditorAudioBus::_solo_toggled(){
+void EditorAudioBus::_solo_toggled() {
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Toggle Audio Bus Solo");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),solo->is_pressed());
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),AudioServer::get_singleton()->is_bus_solo(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_solo", get_index(), solo->is_pressed());
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_solo", get_index(), AudioServer::get_singleton()->is_bus_solo(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
-
+ updating_bus = false;
}
-void EditorAudioBus::_mute_toggled(){
+void EditorAudioBus::_mute_toggled() {
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Toggle Audio Bus Mute");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),mute->is_pressed());
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),AudioServer::get_singleton()->is_bus_mute(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_mute", get_index(), mute->is_pressed());
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_mute", get_index(), AudioServer::get_singleton()->is_bus_mute(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
-
+ updating_bus = false;
}
-void EditorAudioBus::_bypass_toggled(){
+void EditorAudioBus::_bypass_toggled() {
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Toggle Audio Bus Bypass Effects");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),bypass->is_pressed());
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),AudioServer::get_singleton()->is_bus_bypassing_effects(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_bypass_effects", get_index(), bypass->is_pressed());
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_bypass_effects", get_index(), AudioServer::get_singleton()->is_bus_bypassing_effects(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
-
-
+ updating_bus = false;
}
void EditorAudioBus::_send_selected(int p_which) {
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Select Audio Bus Send");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",get_index(),send->get_item_text(p_which));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",get_index(),AudioServer::get_singleton()->get_bus_send(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_send", get_index(), send->get_item_text(p_which));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_send", get_index(), AudioServer::get_singleton()->get_bus_send(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
+ updating_bus = false;
}
void EditorAudioBus::_effect_selected() {
@@ -331,19 +315,18 @@ void EditorAudioBus::_effect_selected() {
TreeItem *effect = effects->get_selected();
if (!effect)
return;
- updating_bus=true;
+ updating_bus = true;
- if (effect->get_metadata(0)!=Variant()) {
+ if (effect->get_metadata(0) != Variant()) {
int index = effect->get_metadata(0);
- Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(get_index(),index);
+ Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(get_index(), index);
if (effect.is_valid()) {
EditorNode::get_singleton()->push_item(effect.ptr());
}
}
- updating_bus=false;
-
+ updating_bus = false;
}
void EditorAudioBus::_effect_edited() {
@@ -355,28 +338,26 @@ void EditorAudioBus::_effect_edited() {
if (!effect)
return;
- if (effect->get_metadata(0)==Variant()) {
+ if (effect->get_metadata(0) == Variant()) {
Rect2 area = effects->get_item_rect(effect);
- effect_options->set_pos(effects->get_global_pos()+area.pos+Vector2(0,area.size.y));
+ effect_options->set_pos(effects->get_global_pos() + area.pos + Vector2(0, area.size.y));
effect_options->popup();
//add effect
- } else {
+ } else {
int index = effect->get_metadata(0);
- updating_bus=true;
+ updating_bus = true;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Select Audio Bus Send");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,effect->is_checked(0));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,AudioServer::get_singleton()->is_bus_effect_enabled(get_index(),index));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), index, effect->is_checked(0));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), index, AudioServer::get_singleton()->is_bus_effect_enabled(get_index(), index));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
- updating_bus=false;
-
+ updating_bus = false;
}
-
}
void EditorAudioBus::_effect_add(int p_which) {
@@ -396,78 +377,75 @@ void EditorAudioBus::_effect_add(int p_which) {
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Add Audio Bus Effect");
- ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),afxr,-1);
- ur->add_undo_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect_count(get_index()));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), afxr, -1);
+ ur->add_undo_method(AudioServer::get_singleton(), "remove_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect_count(get_index()));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
}
-void EditorAudioBus::_gui_input(const InputEvent& p_event) {
+void EditorAudioBus::_gui_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && p_event.key.pressed && p_event.key.scancode==KEY_DELETE && !p_event.key.echo) {
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed && p_event.key.scancode == KEY_DELETE && !p_event.key.echo) {
accept_event();
emit_signal("delete_request");
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==2 && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 2 && p_event.mouse_button.pressed) {
- Vector2 pos = Vector2(p_event.mouse_button.x,p_event.mouse_button.y);
- delete_popup->set_pos(get_global_pos()+pos);
+ Vector2 pos = Vector2(p_event.mouse_button.x, p_event.mouse_button.y);
+ delete_popup->set_pos(get_global_pos() + pos);
delete_popup->popup();
}
}
void EditorAudioBus::_delete_pressed(int p_option) {
- if (p_option==1) {
+ if (p_option == 1) {
emit_signal("delete_request");
- } else if (p_option==0) {
+ } else if (p_option == 0) {
//duplicate
- emit_signal("duplicate_request",get_index());
+ emit_signal("duplicate_request", get_index());
}
-
}
+Variant EditorAudioBus::get_drag_data(const Point2 &p_point) {
-Variant EditorAudioBus::get_drag_data(const Point2& p_point) {
-
- if (get_index()==0) {
+ if (get_index() == 0) {
return Variant();
}
Control *c = memnew(Control);
- Panel *p = memnew( Panel );
+ Panel *p = memnew(Panel);
c->add_child(p);
- p->add_style_override("panel",get_stylebox("focus","Button"));
+ p->add_style_override("panel", get_stylebox("focus", "Button"));
p->set_size(get_size());
p->set_pos(-p_point);
set_drag_preview(c);
Dictionary d;
- d["type"]="move_audio_bus";
- d["index"]=get_index();
+ d["type"] = "move_audio_bus";
+ d["index"] = get_index();
emit_signal("drop_end_request");
return d;
}
-bool EditorAudioBus::can_drop_data(const Point2& p_point,const Variant& p_data) const {
+bool EditorAudioBus::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
- if (get_index()==0)
+ if (get_index() == 0)
return false;
- Dictionary d=p_data;
- if (d.has("type") && String(d["type"])=="move_audio_bus") {
+ Dictionary d = p_data;
+ if (d.has("type") && String(d["type"]) == "move_audio_bus") {
return true;
}
return false;
}
-void EditorAudioBus::drop_data(const Point2& p_point,const Variant& p_data) {
-
- Dictionary d=p_data;
- emit_signal("dropped",d["index"],get_index());
+void EditorAudioBus::drop_data(const Point2 &p_point, const Variant &p_data) {
+ Dictionary d = p_data;
+ emit_signal("dropped", d["index"], get_index());
}
-Variant EditorAudioBus::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant EditorAudioBus::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
print_line("drag fw");
TreeItem *item = effects->get_item_at_pos(p_point);
@@ -478,13 +456,13 @@ Variant EditorAudioBus::get_drag_data_fw(const Point2& p_point,Control* p_from)
Variant md = item->get_metadata(0);
- if (md.get_type()==Variant::INT) {
+ if (md.get_type() == Variant::INT) {
Dictionary fxd;
- fxd["type"]="audio_bus_effect";
- fxd["bus"]=get_index();
- fxd["effect"]=md;
+ fxd["type"] = "audio_bus_effect";
+ fxd["bus"] = get_index();
+ fxd["effect"] = md;
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
l->set_text(item->get_text(0));
effects->set_drag_preview(l);
@@ -492,13 +470,12 @@ Variant EditorAudioBus::get_drag_data_fw(const Point2& p_point,Control* p_from)
}
return Variant();
-
}
-bool EditorAudioBus::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool EditorAudioBus::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
- if (!d.has("type") || String(d["type"])!="audio_bus_effect")
+ if (!d.has("type") || String(d["type"]) != "audio_bus_effect")
return false;
TreeItem *item = effects->get_item_at_pos(p_point);
@@ -510,98 +487,92 @@ bool EditorAudioBus::can_drop_data_fw(const Point2& p_point,const Variant& p_dat
return true;
}
-void EditorAudioBus::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void EditorAudioBus::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
Dictionary d = p_data;
TreeItem *item = effects->get_item_at_pos(p_point);
if (!item)
return;
- int pos=effects->get_drop_section_at_pos(p_point);
+ int pos = effects->get_drop_section_at_pos(p_point);
Variant md = item->get_metadata(0);
int paste_at;
int bus = d["bus"];
int effect = d["effect"];
- if (md.get_type()==Variant::INT) {
- paste_at=md;
- if (pos>0)
+ if (md.get_type() == Variant::INT) {
+ paste_at = md;
+ if (pos > 0)
paste_at++;
- if (bus==get_index() && paste_at >effect) {
+ if (bus == get_index() && paste_at > effect) {
paste_at--;
}
} else {
- paste_at=-1;
+ paste_at = -1;
}
-
- bool enabled = AudioServer::get_singleton()->is_bus_effect_enabled(bus,effect);
+ bool enabled = AudioServer::get_singleton()->is_bus_effect_enabled(bus, effect);
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Move Bus Effect");
- ur->add_do_method(AudioServer::get_singleton(),"remove_bus_effect",bus,effect);
- ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect(bus,effect),paste_at);
+ ur->add_do_method(AudioServer::get_singleton(), "remove_bus_effect", bus, effect);
+ ur->add_do_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect(bus, effect), paste_at);
- if (paste_at==-1) {
+ if (paste_at == -1) {
paste_at = AudioServer::get_singleton()->get_bus_effect_count(get_index());
- if (bus==get_index()) {
+ if (bus == get_index()) {
paste_at--;
}
}
if (!enabled) {
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),paste_at,false);
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), paste_at, false);
}
- ur->add_undo_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),paste_at);
- ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",bus,AudioServer::get_singleton()->get_bus_effect(bus,effect),effect);
+ ur->add_undo_method(AudioServer::get_singleton(), "remove_bus_effect", get_index(), paste_at);
+ ur->add_undo_method(AudioServer::get_singleton(), "add_bus_effect", bus, AudioServer::get_singleton()->get_bus_effect(bus, effect), effect);
if (!enabled) {
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",bus,effect,false);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_effect_enabled", bus, effect, false);
}
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
- if (get_index()!=bus) {
- ur->add_do_method(buses,"_update_bus",bus);
- ur->add_undo_method(buses,"_update_bus",bus);
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
+ if (get_index() != bus) {
+ ur->add_do_method(buses, "_update_bus", bus);
+ ur->add_undo_method(buses, "_update_bus", bus);
}
ur->commit_action();
-
-
-
}
void EditorAudioBus::_delete_effect_pressed(int p_option) {
- TreeItem * item = effects->get_selected();
+ TreeItem *item = effects->get_selected();
if (!item)
return;
- if (item->get_metadata(0).get_type()!=Variant::INT)
+ if (item->get_metadata(0).get_type() != Variant::INT)
return;
int index = item->get_metadata(0);
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Delete Bus Effect");
- ur->add_do_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),index);
- ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect(get_index(),index),index);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,AudioServer::get_singleton()->is_bus_effect_enabled(get_index(),index));
- ur->add_do_method(buses,"_update_bus",get_index());
- ur->add_undo_method(buses,"_update_bus",get_index());
+ ur->add_do_method(AudioServer::get_singleton(), "remove_bus_effect", get_index(), index);
+ ur->add_undo_method(AudioServer::get_singleton(), "add_bus_effect", get_index(), AudioServer::get_singleton()->get_bus_effect(get_index(), index), index);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_effect_enabled", get_index(), index, AudioServer::get_singleton()->is_bus_effect_enabled(get_index(), index));
+ ur->add_do_method(buses, "_update_bus", get_index());
+ ur->add_undo_method(buses, "_update_bus", get_index());
ur->commit_action();
-
-
}
-void EditorAudioBus::_effect_rmb(const Vector2& p_pos) {
+void EditorAudioBus::_effect_rmb(const Vector2 &p_pos) {
- TreeItem * item = effects->get_selected();
+ TreeItem *item = effects->get_selected();
if (!item)
return;
- if (item->get_metadata(0).get_type()!=Variant::INT)
+ if (item->get_metadata(0).get_type() != Variant::INT)
return;
delete_effect_popup->set_pos(get_global_mouse_pos());
@@ -610,172 +581,165 @@ void EditorAudioBus::_effect_rmb(const Vector2& p_pos) {
void EditorAudioBus::_bind_methods() {
- ClassDB::bind_method("update_bus",&EditorAudioBus::update_bus);
- ClassDB::bind_method("update_send",&EditorAudioBus::update_send);
- ClassDB::bind_method("_name_changed",&EditorAudioBus::_name_changed);
- ClassDB::bind_method("_volume_db_changed",&EditorAudioBus::_volume_db_changed);
- ClassDB::bind_method("_solo_toggled",&EditorAudioBus::_solo_toggled);
- ClassDB::bind_method("_mute_toggled",&EditorAudioBus::_mute_toggled);
- ClassDB::bind_method("_bypass_toggled",&EditorAudioBus::_bypass_toggled);
- ClassDB::bind_method("_name_focus_exit",&EditorAudioBus::_name_focus_exit);
- ClassDB::bind_method("_send_selected",&EditorAudioBus::_send_selected);
- ClassDB::bind_method("_effect_edited",&EditorAudioBus::_effect_edited);
- ClassDB::bind_method("_effect_selected",&EditorAudioBus::_effect_selected);
- ClassDB::bind_method("_effect_add",&EditorAudioBus::_effect_add);
- ClassDB::bind_method("_gui_input",&EditorAudioBus::_gui_input);
- ClassDB::bind_method("_delete_pressed",&EditorAudioBus::_delete_pressed);
- ClassDB::bind_method("get_drag_data_fw",&EditorAudioBus::get_drag_data_fw);
- ClassDB::bind_method("can_drop_data_fw",&EditorAudioBus::can_drop_data_fw);
- ClassDB::bind_method("drop_data_fw",&EditorAudioBus::drop_data_fw);
- ClassDB::bind_method("_delete_effect_pressed",&EditorAudioBus::_delete_effect_pressed);
- ClassDB::bind_method("_effect_rmb",&EditorAudioBus::_effect_rmb);
-
-
+ ClassDB::bind_method("update_bus", &EditorAudioBus::update_bus);
+ ClassDB::bind_method("update_send", &EditorAudioBus::update_send);
+ ClassDB::bind_method("_name_changed", &EditorAudioBus::_name_changed);
+ ClassDB::bind_method("_volume_db_changed", &EditorAudioBus::_volume_db_changed);
+ ClassDB::bind_method("_solo_toggled", &EditorAudioBus::_solo_toggled);
+ ClassDB::bind_method("_mute_toggled", &EditorAudioBus::_mute_toggled);
+ ClassDB::bind_method("_bypass_toggled", &EditorAudioBus::_bypass_toggled);
+ ClassDB::bind_method("_name_focus_exit", &EditorAudioBus::_name_focus_exit);
+ ClassDB::bind_method("_send_selected", &EditorAudioBus::_send_selected);
+ ClassDB::bind_method("_effect_edited", &EditorAudioBus::_effect_edited);
+ ClassDB::bind_method("_effect_selected", &EditorAudioBus::_effect_selected);
+ ClassDB::bind_method("_effect_add", &EditorAudioBus::_effect_add);
+ ClassDB::bind_method("_gui_input", &EditorAudioBus::_gui_input);
+ ClassDB::bind_method("_delete_pressed", &EditorAudioBus::_delete_pressed);
+ ClassDB::bind_method("get_drag_data_fw", &EditorAudioBus::get_drag_data_fw);
+ ClassDB::bind_method("can_drop_data_fw", &EditorAudioBus::can_drop_data_fw);
+ ClassDB::bind_method("drop_data_fw", &EditorAudioBus::drop_data_fw);
+ ClassDB::bind_method("_delete_effect_pressed", &EditorAudioBus::_delete_effect_pressed);
+ ClassDB::bind_method("_effect_rmb", &EditorAudioBus::_effect_rmb);
ADD_SIGNAL(MethodInfo("duplicate_request"));
ADD_SIGNAL(MethodInfo("delete_request"));
ADD_SIGNAL(MethodInfo("drop_end_request"));
ADD_SIGNAL(MethodInfo("dropped"));
-
}
EditorAudioBus::EditorAudioBus(EditorAudioBuses *p_buses) {
- buses=p_buses;
- updating_bus=false;
+ buses = p_buses;
+ updating_bus = false;
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
set_v_size_flags(SIZE_EXPAND_FILL);
- track_name = memnew( LineEdit );
+ track_name = memnew(LineEdit);
vb->add_child(track_name);
- track_name->connect("text_entered",this,"_name_changed");
- track_name->connect("focus_exited",this,"_name_focus_exit");
+ track_name->connect("text_entered", this, "_name_changed");
+ track_name->connect("focus_exited", this, "_name_focus_exit");
- HBoxContainer *hbc = memnew( HBoxContainer);
+ HBoxContainer *hbc = memnew(HBoxContainer);
vb->add_child(hbc);
hbc->add_spacer();
- solo = memnew( ToolButton );
+ solo = memnew(ToolButton);
solo->set_text("S");
solo->set_toggle_mode(true);
- solo->set_modulate(Color(0.8,1.2,0.8));
+ solo->set_modulate(Color(0.8, 1.2, 0.8));
solo->set_focus_mode(FOCUS_NONE);
- solo->connect("pressed",this,"_solo_toggled");
+ solo->connect("pressed", this, "_solo_toggled");
hbc->add_child(solo);
- mute = memnew( ToolButton );
+ mute = memnew(ToolButton);
mute->set_text("M");
mute->set_toggle_mode(true);
- mute->set_modulate(Color(1.2,0.8,0.8));
+ mute->set_modulate(Color(1.2, 0.8, 0.8));
mute->set_focus_mode(FOCUS_NONE);
- mute->connect("pressed",this,"_mute_toggled");
+ mute->connect("pressed", this, "_mute_toggled");
hbc->add_child(mute);
- bypass = memnew( ToolButton );
+ bypass = memnew(ToolButton);
bypass->set_text("B");
bypass->set_toggle_mode(true);
- bypass->set_modulate(Color(1.1,1.1,0.8));
+ bypass->set_modulate(Color(1.1, 1.1, 0.8));
bypass->set_focus_mode(FOCUS_NONE);
- bypass->connect("pressed",this,"_bypass_toggled");
+ bypass->connect("pressed", this, "_bypass_toggled");
hbc->add_child(bypass);
hbc->add_spacer();
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
vb->add_child(hb);
- slider = memnew( VSlider );
+ slider = memnew(VSlider);
slider->set_min(-80);
slider->set_max(24);
slider->set_step(0.1);
- slider->connect("value_changed",this,"_volume_db_changed");
+ slider->connect("value_changed", this, "_volume_db_changed");
hb->add_child(slider);
- vu_l = memnew( TextureProgress );
+ vu_l = memnew(TextureProgress);
vu_l->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP);
hb->add_child(vu_l);
vu_l->set_min(-80);
vu_l->set_max(24);
vu_l->set_step(0.1);
- vu_r = memnew( TextureProgress );
+ vu_r = memnew(TextureProgress);
vu_r->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP);
hb->add_child(vu_r);
vu_r->set_min(-80);
vu_r->set_max(24);
vu_r->set_step(0.1);
- scale = memnew( TextureRect );
+ scale = memnew(TextureRect);
hb->add_child(scale);
//add_child(hb);
- effects = memnew( Tree );
+ effects = memnew(Tree);
effects->set_hide_root(true);
- effects->set_custom_minimum_size(Size2(0,90)*EDSCALE);
+ effects->set_custom_minimum_size(Size2(0, 90) * EDSCALE);
effects->set_hide_folding(true);
vb->add_child(effects);
- effects->connect("item_edited",this,"_effect_edited");
- effects->connect("cell_selected",this,"_effect_selected");
+ effects->connect("item_edited", this, "_effect_edited");
+ effects->connect("cell_selected", this, "_effect_selected");
effects->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
effects->set_drag_forwarding(this);
- effects->connect("item_rmb_selected",this,"_effect_rmb");
+ effects->connect("item_rmb_selected", this, "_effect_rmb");
effects->set_allow_rmb_select(true);
- send = memnew( OptionButton );
+ send = memnew(OptionButton);
send->set_clip_text(true);
- send->connect("item_selected",this,"_send_selected");
+ send->connect("item_selected", this, "_send_selected");
vb->add_child(send);
set_focus_mode(FOCUS_CLICK);
- effect_options = memnew( PopupMenu );
- effect_options->connect("index_pressed",this,"_effect_add");
+ effect_options = memnew(PopupMenu);
+ effect_options->connect("index_pressed", this, "_effect_add");
add_child(effect_options);
List<StringName> effects;
- ClassDB::get_inheriters_from_class("AudioEffect",&effects);
+ ClassDB::get_inheriters_from_class("AudioEffect", &effects);
effects.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *E=effects.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = effects.front(); E; E = E->next()) {
if (!ClassDB::can_instance(E->get()))
continue;
Ref<Texture> icon;
- if (has_icon(E->get(),"EditorIcons")) {
- icon = get_icon(E->get(),"EditorIcons");
+ if (has_icon(E->get(), "EditorIcons")) {
+ icon = get_icon(E->get(), "EditorIcons");
}
- String name = E->get().operator String().replace("AudioEffect","");
+ String name = E->get().operator String().replace("AudioEffect", "");
effect_options->add_item(name);
- effect_options->set_item_metadata(effect_options->get_item_count()-1,E->get());
- effect_options->set_item_icon(effect_options->get_item_count()-1,icon);
+ effect_options->set_item_metadata(effect_options->get_item_count() - 1, E->get());
+ effect_options->set_item_icon(effect_options->get_item_count() - 1, icon);
}
- delete_popup = memnew( PopupMenu );
+ delete_popup = memnew(PopupMenu);
delete_popup->add_item("Duplicate");
delete_popup->add_item("Delete");
add_child(delete_popup);
- delete_popup->connect("index_pressed",this,"_delete_pressed");
+ delete_popup->connect("index_pressed", this, "_delete_pressed");
- delete_effect_popup = memnew( PopupMenu );
+ delete_effect_popup = memnew(PopupMenu);
delete_effect_popup->add_item("Delete Effect");
add_child(delete_effect_popup);
- delete_effect_popup->connect("index_pressed",this,"_delete_effect_pressed");
-
+ delete_effect_popup->connect("index_pressed", this, "_delete_effect_pressed");
}
+bool EditorAudioBusDrop::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
-
-bool EditorAudioBusDrop::can_drop_data(const Point2& p_point,const Variant& p_data) const {
-
- Dictionary d=p_data;
- if (d.has("type") && String(d["type"])=="move_audio_bus") {
+ Dictionary d = p_data;
+ if (d.has("type") && String(d["type"]) == "move_audio_bus") {
return true;
}
return false;
}
-void EditorAudioBusDrop::drop_data(const Point2& p_point,const Variant& p_data){
-
- Dictionary d=p_data;
- emit_signal("dropped",d["index"],-1);
+void EditorAudioBusDrop::drop_data(const Point2 &p_point, const Variant &p_data) {
+ Dictionary d = p_data;
+ emit_signal("dropped", d["index"], -1);
}
void EditorAudioBusDrop::_bind_methods() {
@@ -784,65 +748,59 @@ void EditorAudioBusDrop::_bind_methods() {
}
EditorAudioBusDrop::EditorAudioBusDrop() {
-
-
}
-
void EditorAudioBuses::_update_buses() {
- while(bus_hb->get_child_count()>0) {
+ while (bus_hb->get_child_count() > 0) {
memdelete(bus_hb->get_child(0));
}
- drop_end=NULL;
+ drop_end = NULL;
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
- EditorAudioBus *audio_bus = memnew( EditorAudioBus(this) );
- if (i==0) {
- audio_bus->set_self_modulate(Color(1,0.9,0.9));
+ EditorAudioBus *audio_bus = memnew(EditorAudioBus(this));
+ if (i == 0) {
+ audio_bus->set_self_modulate(Color(1, 0.9, 0.9));
}
bus_hb->add_child(audio_bus);
- audio_bus->connect("delete_request",this,"_delete_bus",varray(audio_bus),CONNECT_DEFERRED);
- audio_bus->connect("duplicate_request",this,"_duplicate_bus",varray(),CONNECT_DEFERRED);
- audio_bus->connect("drop_end_request",this,"_request_drop_end");
- audio_bus->connect("dropped",this,"_drop_at_index",varray(),CONNECT_DEFERRED);
-
-
-
+ audio_bus->connect("delete_request", this, "_delete_bus", varray(audio_bus), CONNECT_DEFERRED);
+ audio_bus->connect("duplicate_request", this, "_duplicate_bus", varray(), CONNECT_DEFERRED);
+ audio_bus->connect("drop_end_request", this, "_request_drop_end");
+ audio_bus->connect("dropped", this, "_drop_at_index", varray(), CONNECT_DEFERRED);
}
}
EditorAudioBuses *EditorAudioBuses::register_editor() {
- EditorAudioBuses * audio_buses = memnew( EditorAudioBuses );
- EditorNode::get_singleton()->add_bottom_panel_item("Audio",audio_buses);
+ EditorAudioBuses *audio_buses = memnew(EditorAudioBuses);
+ EditorNode::get_singleton()->add_bottom_panel_item("Audio", audio_buses);
return audio_buses;
}
void EditorAudioBuses::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
_update_buses();
}
- if (p_what==NOTIFICATION_DRAG_END) {
+ if (p_what == NOTIFICATION_DRAG_END) {
if (drop_end) {
drop_end->queue_delete();
- drop_end=NULL;
+ drop_end = NULL;
}
}
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
//check if anything was edited
bool edited = AudioServer::get_singleton()->is_edited();
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
- for(int j=0;j<AudioServer::get_singleton()->get_bus_effect_count(i);j++) {
- Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(i,j);
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
+ for (int j = 0; j < AudioServer::get_singleton()->get_bus_effect_count(i); j++) {
+ Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(i, j);
if (effect->is_edited()) {
- edited=true;
+ edited = true;
effect->set_edited(false);
}
}
@@ -855,27 +813,24 @@ void EditorAudioBuses::_notification(int p_what) {
save_timer->start();
}
}
-
}
-
void EditorAudioBuses::_add_bus() {
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
//need to simulate new name, so we can undi :(
ur->create_action("Add Audio Bus");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count()+1);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count());
- ur->add_do_method(this,"_update_buses");
- ur->add_undo_method(this,"_update_buses");
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_count", AudioServer::get_singleton()->get_bus_count() + 1);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_count", AudioServer::get_singleton()->get_bus_count());
+ ur->add_do_method(this, "_update_buses");
+ ur->add_undo_method(this, "_update_buses");
ur->commit_action();
-
}
void EditorAudioBuses::_update_bus(int p_index) {
- if (p_index>=bus_hb->get_child_count())
+ if (p_index >= bus_hb->get_child_count())
return;
bus_hb->get_child(p_index)->call("update_bus");
@@ -883,109 +838,103 @@ void EditorAudioBuses::_update_bus(int p_index) {
void EditorAudioBuses::_update_sends() {
- for(int i=0;i<bus_hb->get_child_count();i++) {
+ for (int i = 0; i < bus_hb->get_child_count(); i++) {
bus_hb->get_child(i)->call("update_send");
}
}
-void EditorAudioBuses::_delete_bus(Object* p_which) {
+void EditorAudioBuses::_delete_bus(Object *p_which) {
EditorAudioBus *bus = p_which->cast_to<EditorAudioBus>();
int index = bus->get_index();
- if (index==0) {
+ if (index == 0) {
EditorNode::get_singleton()->show_warning("Master bus can't be deleted!");
return;
}
-
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Delete Audio Bus");
- ur->add_do_method(AudioServer::get_singleton(),"remove_bus",index);
- ur->add_undo_method(AudioServer::get_singleton(),"add_bus",index);
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_name",index,AudioServer::get_singleton()->get_bus_name(index));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_volume_db",index,AudioServer::get_singleton()->get_bus_volume_db(index));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",index,AudioServer::get_singleton()->get_bus_send(index));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_solo",index,AudioServer::get_singleton()->is_bus_solo(index));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_mute",index,AudioServer::get_singleton()->is_bus_mute(index));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_bypass_effects",index,AudioServer::get_singleton()->is_bus_bypassing_effects(index));
- for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(index);i++) {
-
- ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",index,AudioServer::get_singleton()->get_bus_effect(index,i));
- ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",index,i,AudioServer::get_singleton()->is_bus_effect_enabled(index,i));
+ ur->add_do_method(AudioServer::get_singleton(), "remove_bus", index);
+ ur->add_undo_method(AudioServer::get_singleton(), "add_bus", index);
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_name", index, AudioServer::get_singleton()->get_bus_name(index));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_volume_db", index, AudioServer::get_singleton()->get_bus_volume_db(index));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_send", index, AudioServer::get_singleton()->get_bus_send(index));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_solo", index, AudioServer::get_singleton()->is_bus_solo(index));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_mute", index, AudioServer::get_singleton()->is_bus_mute(index));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_bypass_effects", index, AudioServer::get_singleton()->is_bus_bypassing_effects(index));
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_effect_count(index); i++) {
+
+ ur->add_undo_method(AudioServer::get_singleton(), "add_bus_effect", index, AudioServer::get_singleton()->get_bus_effect(index, i));
+ ur->add_undo_method(AudioServer::get_singleton(), "set_bus_effect_enabled", index, i, AudioServer::get_singleton()->is_bus_effect_enabled(index, i));
}
- ur->add_do_method(this,"_update_buses");
- ur->add_undo_method(this,"_update_buses");
+ ur->add_do_method(this, "_update_buses");
+ ur->add_undo_method(this, "_update_buses");
ur->commit_action();
-
}
-
void EditorAudioBuses::_duplicate_bus(int p_which) {
- int add_at_pos = p_which+1;
+ int add_at_pos = p_which + 1;
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Duplicate Audio Bus");
- ur->add_do_method(AudioServer::get_singleton(),"add_bus",add_at_pos);
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_name",add_at_pos,AudioServer::get_singleton()->get_bus_name(p_which)+" Copy");
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_volume_db",add_at_pos,AudioServer::get_singleton()->get_bus_volume_db(p_which));
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",add_at_pos,AudioServer::get_singleton()->get_bus_send(p_which));
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_solo",add_at_pos,AudioServer::get_singleton()->is_bus_solo(p_which));
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_mute",add_at_pos,AudioServer::get_singleton()->is_bus_mute(p_which));
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_bypass_effects",add_at_pos,AudioServer::get_singleton()->is_bus_bypassing_effects(p_which));
- for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(p_which);i++) {
-
- ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",add_at_pos,AudioServer::get_singleton()->get_bus_effect(p_which,i));
- ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",add_at_pos,i,AudioServer::get_singleton()->is_bus_effect_enabled(p_which,i));
+ ur->add_do_method(AudioServer::get_singleton(), "add_bus", add_at_pos);
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_name", add_at_pos, AudioServer::get_singleton()->get_bus_name(p_which) + " Copy");
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_volume_db", add_at_pos, AudioServer::get_singleton()->get_bus_volume_db(p_which));
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_send", add_at_pos, AudioServer::get_singleton()->get_bus_send(p_which));
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_solo", add_at_pos, AudioServer::get_singleton()->is_bus_solo(p_which));
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_mute", add_at_pos, AudioServer::get_singleton()->is_bus_mute(p_which));
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_bypass_effects", add_at_pos, AudioServer::get_singleton()->is_bus_bypassing_effects(p_which));
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_effect_count(p_which); i++) {
+
+ ur->add_do_method(AudioServer::get_singleton(), "add_bus_effect", add_at_pos, AudioServer::get_singleton()->get_bus_effect(p_which, i));
+ ur->add_do_method(AudioServer::get_singleton(), "set_bus_effect_enabled", add_at_pos, i, AudioServer::get_singleton()->is_bus_effect_enabled(p_which, i));
}
- ur->add_undo_method(AudioServer::get_singleton(),"remove_bus",add_at_pos);
- ur->add_do_method(this,"_update_buses");
- ur->add_undo_method(this,"_update_buses");
+ ur->add_undo_method(AudioServer::get_singleton(), "remove_bus", add_at_pos);
+ ur->add_do_method(this, "_update_buses");
+ ur->add_undo_method(this, "_update_buses");
ur->commit_action();
-
}
void EditorAudioBuses::_request_drop_end() {
if (!drop_end && bus_hb->get_child_count()) {
- drop_end = memnew( EditorAudioBusDrop );
+ drop_end = memnew(EditorAudioBusDrop);
bus_hb->add_child(drop_end);
drop_end->set_custom_minimum_size(bus_hb->get_child(0)->cast_to<Control>()->get_size());
- drop_end->connect("dropped",this,"_drop_at_index",varray(),CONNECT_DEFERRED);
+ drop_end->connect("dropped", this, "_drop_at_index", varray(), CONNECT_DEFERRED);
}
}
-void EditorAudioBuses::_drop_at_index(int p_bus,int p_index) {
-
+void EditorAudioBuses::_drop_at_index(int p_bus, int p_index) {
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
//need to simulate new name, so we can undi :(
ur->create_action("Move Audio Bus");
- ur->add_do_method(AudioServer::get_singleton(),"move_bus",p_bus,p_index);
+ ur->add_do_method(AudioServer::get_singleton(), "move_bus", p_bus, p_index);
int final_pos;
- if (p_index==p_bus) {
- final_pos=p_bus;
- } else if (p_index==-1) {
- final_pos = AudioServer::get_singleton()->get_bus_count()-1;
- } else if (p_index<p_bus) {
+ if (p_index == p_bus) {
+ final_pos = p_bus;
+ } else if (p_index == -1) {
+ final_pos = AudioServer::get_singleton()->get_bus_count() - 1;
+ } else if (p_index < p_bus) {
final_pos = p_index;
} else {
- final_pos = p_index -1;
+ final_pos = p_index - 1;
}
- ur->add_undo_method(AudioServer::get_singleton(),"move_bus",final_pos,p_bus);
+ ur->add_undo_method(AudioServer::get_singleton(), "move_bus", final_pos, p_bus);
- ur->add_do_method(this,"_update_buses");
- ur->add_undo_method(this,"_update_buses");
+ ur->add_do_method(this, "_update_buses");
+ ur->add_undo_method(this, "_update_buses");
ur->commit_action();
}
void EditorAudioBuses::_server_save() {
Ref<AudioBusLayout> state = AudioServer::get_singleton()->generate_bus_layout();
- ResourceSaver::save(edited_path,state);
-
+ ResourceSaver::save(edited_path, state);
}
void EditorAudioBuses::_select_layout() {
@@ -999,17 +948,16 @@ void EditorAudioBuses::_save_as_layout() {
file_dialog->set_title(TTR("Save Audio Bus Layout As.."));
file_dialog->set_current_path(edited_path);
file_dialog->popup_centered_ratio();
- new_layout=false;
+ new_layout = false;
}
-
void EditorAudioBuses::_new_layout() {
file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
file_dialog->set_title(TTR("Location for New Layout.."));
file_dialog->set_current_path(edited_path);
file_dialog->popup_centered_ratio();
- new_layout=true;
+ new_layout = true;
}
void EditorAudioBuses::_load_layout() {
@@ -1018,20 +966,18 @@ void EditorAudioBuses::_load_layout() {
file_dialog->set_title(TTR("Open Audio Bus Layout"));
file_dialog->set_current_path(edited_path);
file_dialog->popup_centered_ratio();
- new_layout=false;
+ new_layout = false;
}
-
void EditorAudioBuses::_load_default_layout() {
-
Ref<AudioBusLayout> state = ResourceLoader::load("res://default_bus_layout.tres");
if (state.is_null()) {
EditorNode::get_singleton()->show_warning("There is no 'res://default_bus_layout.tres' file.");
return;
}
- edited_path="res://default_bus_layout.tres";
+ edited_path = "res://default_bus_layout.tres";
file->set_text(edited_path.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
@@ -1039,23 +985,23 @@ void EditorAudioBuses::_load_default_layout() {
call_deferred("_select_layout");
}
-void EditorAudioBuses::_file_dialog_callback(const String& p_string) {
+void EditorAudioBuses::_file_dialog_callback(const String &p_string) {
- if (file_dialog->get_mode()==EditorFileDialog::MODE_OPEN_FILE) {
+ if (file_dialog->get_mode() == EditorFileDialog::MODE_OPEN_FILE) {
Ref<AudioBusLayout> state = ResourceLoader::load(p_string);
if (state.is_null()) {
EditorNode::get_singleton()->show_warning("Invalid file, not an audio bus layout.");
return;
}
- edited_path=p_string;
+ edited_path = p_string;
file->set_text(p_string.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
EditorNode::get_singleton()->get_undo_redo()->clear_history();
call_deferred("_select_layout");
- } else if (file_dialog->get_mode()==EditorFileDialog::MODE_SAVE_FILE) {
+ } else if (file_dialog->get_mode() == EditorFileDialog::MODE_SAVE_FILE) {
if (new_layout) {
Ref<AudioBusLayout> empty_state;
@@ -1063,116 +1009,111 @@ void EditorAudioBuses::_file_dialog_callback(const String& p_string) {
AudioServer::get_singleton()->set_bus_layout(empty_state);
}
- Error err = ResourceSaver::save(p_string,AudioServer::get_singleton()->generate_bus_layout());
+ Error err = ResourceSaver::save(p_string, AudioServer::get_singleton()->generate_bus_layout());
- if (err!=OK) {
- EditorNode::get_singleton()->show_warning("Error saving file: "+p_string);
+ if (err != OK) {
+ EditorNode::get_singleton()->show_warning("Error saving file: " + p_string);
return;
}
- edited_path=p_string;
+ edited_path = p_string;
file->set_text(p_string.get_file());
_update_buses();
EditorNode::get_singleton()->get_undo_redo()->clear_history();
call_deferred("_select_layout");
}
-
}
void EditorAudioBuses::_bind_methods() {
- ClassDB::bind_method("_add_bus",&EditorAudioBuses::_add_bus);
- ClassDB::bind_method("_update_buses",&EditorAudioBuses::_update_buses);
- ClassDB::bind_method("_update_bus",&EditorAudioBuses::_update_bus);
- ClassDB::bind_method("_update_sends",&EditorAudioBuses::_update_sends);
- ClassDB::bind_method("_delete_bus",&EditorAudioBuses::_delete_bus);
- ClassDB::bind_method("_request_drop_end",&EditorAudioBuses::_request_drop_end);
- ClassDB::bind_method("_drop_at_index",&EditorAudioBuses::_drop_at_index);
- ClassDB::bind_method("_server_save",&EditorAudioBuses::_server_save);
- ClassDB::bind_method("_select_layout",&EditorAudioBuses::_select_layout);
- ClassDB::bind_method("_save_as_layout",&EditorAudioBuses::_save_as_layout);
- ClassDB::bind_method("_load_layout",&EditorAudioBuses::_load_layout);
- ClassDB::bind_method("_load_default_layout",&EditorAudioBuses::_load_default_layout);
- ClassDB::bind_method("_new_layout",&EditorAudioBuses::_new_layout);
- ClassDB::bind_method("_duplicate_bus",&EditorAudioBuses::_duplicate_bus);
-
- ClassDB::bind_method("_file_dialog_callback",&EditorAudioBuses::_file_dialog_callback);
+ ClassDB::bind_method("_add_bus", &EditorAudioBuses::_add_bus);
+ ClassDB::bind_method("_update_buses", &EditorAudioBuses::_update_buses);
+ ClassDB::bind_method("_update_bus", &EditorAudioBuses::_update_bus);
+ ClassDB::bind_method("_update_sends", &EditorAudioBuses::_update_sends);
+ ClassDB::bind_method("_delete_bus", &EditorAudioBuses::_delete_bus);
+ ClassDB::bind_method("_request_drop_end", &EditorAudioBuses::_request_drop_end);
+ ClassDB::bind_method("_drop_at_index", &EditorAudioBuses::_drop_at_index);
+ ClassDB::bind_method("_server_save", &EditorAudioBuses::_server_save);
+ ClassDB::bind_method("_select_layout", &EditorAudioBuses::_select_layout);
+ ClassDB::bind_method("_save_as_layout", &EditorAudioBuses::_save_as_layout);
+ ClassDB::bind_method("_load_layout", &EditorAudioBuses::_load_layout);
+ ClassDB::bind_method("_load_default_layout", &EditorAudioBuses::_load_default_layout);
+ ClassDB::bind_method("_new_layout", &EditorAudioBuses::_new_layout);
+ ClassDB::bind_method("_duplicate_bus", &EditorAudioBuses::_duplicate_bus);
+
+ ClassDB::bind_method("_file_dialog_callback", &EditorAudioBuses::_file_dialog_callback);
}
-EditorAudioBuses::EditorAudioBuses()
-{
+EditorAudioBuses::EditorAudioBuses() {
drop_end = NULL;
- top_hb = memnew( HBoxContainer );
+ top_hb = memnew(HBoxContainer);
add_child(top_hb);
- add = memnew( Button );
- top_hb->add_child(add);;
+ add = memnew(Button);
+ top_hb->add_child(add);
+ ;
add->set_text(TTR("Add Bus"));
- add->connect("pressed",this,"_add_bus");
-
-
+ add->connect("pressed", this, "_add_bus");
top_hb->add_spacer();
- file = memnew( ToolButton );
+ file = memnew(ToolButton);
file->set_text("default_bus_layout.tres");
top_hb->add_child(file);
- file->connect("pressed",this,"_select_layout");
+ file->connect("pressed", this, "_select_layout");
- load = memnew( Button );
+ load = memnew(Button);
load->set_text(TTR("Load"));
top_hb->add_child(load);
- load->connect("pressed",this,"_load_layout");
+ load->connect("pressed", this, "_load_layout");
- save_as = memnew( Button );
+ save_as = memnew(Button);
save_as->set_text(TTR("Save As"));
top_hb->add_child(save_as);
- save_as->connect("pressed",this,"_save_as_layout");
+ save_as->connect("pressed", this, "_save_as_layout");
- _default = memnew( Button );
+ _default = memnew(Button);
_default->set_text(TTR("Default"));
top_hb->add_child(_default);
- _default->connect("pressed",this,"_load_default_layout");
+ _default->connect("pressed", this, "_load_default_layout");
- _new = memnew( Button );
+ _new = memnew(Button);
_new->set_text(TTR("Create"));
top_hb->add_child(_new);
- _new->connect("pressed",this,"_new_layout");
+ _new->connect("pressed", this, "_new_layout");
- bus_scroll = memnew( ScrollContainer );
+ bus_scroll = memnew(ScrollContainer);
bus_scroll->set_v_size_flags(SIZE_EXPAND_FILL);
bus_scroll->set_enable_h_scroll(true);
bus_scroll->set_enable_v_scroll(false);
add_child(bus_scroll);
- bus_hb = memnew( HBoxContainer );
+ bus_hb = memnew(HBoxContainer);
bus_scroll->add_child(bus_hb);
- save_timer=memnew(Timer);
+ save_timer = memnew(Timer);
save_timer->set_wait_time(0.8);
save_timer->set_one_shot(true);
add_child(save_timer);
- save_timer->connect("timeout",this,"_server_save");
+ save_timer->connect("timeout", this, "_server_save");
set_v_size_flags(SIZE_EXPAND_FILL);
-
edited_path = "res://default_bus_layout.tres";
- file_dialog = memnew( EditorFileDialog );
+ file_dialog = memnew(EditorFileDialog);
List<String> ext;
- ResourceLoader::get_recognized_extensions_for_type("AudioServerState",&ext);
- for (List<String>::Element *E=ext.front();E;E=E->next()) {
- file_dialog->add_filter("*."+E->get()+"; Audio Bus State");
+ ResourceLoader::get_recognized_extensions_for_type("AudioServerState", &ext);
+ for (List<String>::Element *E = ext.front(); E; E = E->next()) {
+ file_dialog->add_filter("*." + E->get() + "; Audio Bus State");
}
add_child(file_dialog);
- file_dialog->connect("file_selected",this,"_file_dialog_callback");
+ file_dialog->connect("file_selected", this, "_file_dialog_callback");
set_process(true);
-
}
-void EditorAudioBuses::open_layout(const String& p_path) {
+void EditorAudioBuses::open_layout(const String &p_path) {
EditorNode::get_singleton()->make_bottom_panel_item_visible(this);
@@ -1182,7 +1123,7 @@ void EditorAudioBuses::open_layout(const String& p_path) {
return;
}
- edited_path=p_path;
+ edited_path = p_path;
file->set_text(p_path.get_file());
AudioServer::get_singleton()->set_bus_layout(state);
_update_buses();
@@ -1203,19 +1144,16 @@ void AudioBusesEditorPlugin::edit(Object *p_node) {
bool AudioBusesEditorPlugin::handles(Object *p_node) const {
- return (p_node->cast_to<AudioBusLayout>()!=NULL);
+ return (p_node->cast_to<AudioBusLayout>() != NULL);
}
-void AudioBusesEditorPlugin::make_visible(bool p_visible){
-
-
+void AudioBusesEditorPlugin::make_visible(bool p_visible) {
}
AudioBusesEditorPlugin::AudioBusesEditorPlugin(EditorAudioBuses *p_node) {
- audio_bus_editor=p_node;
+ audio_bus_editor = p_node;
}
AudioBusesEditorPlugin::~AudioBusesEditorPlugin() {
-
}
diff --git a/editor/editor_audio_buses.h b/editor/editor_audio_buses.h
index 8f9e327368..06a9c01bf0 100644
--- a/editor/editor_audio_buses.h
+++ b/editor/editor_audio_buses.h
@@ -29,27 +29,26 @@
#ifndef EDITORAUDIOBUSES_H
#define EDITORAUDIOBUSES_H
-
+#include "editor/editor_file_dialog.h"
+#include "editor_plugin.h"
#include "scene/gui/box_container.h"
#include "scene/gui/button.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/scroll_container.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/option_button.h"
+#include "scene/gui/panel.h"
#include "scene/gui/panel_container.h"
+#include "scene/gui/scroll_container.h"
#include "scene/gui/slider.h"
#include "scene/gui/texture_progress.h"
#include "scene/gui/texture_rect.h"
-#include "scene/gui/line_edit.h"
+#include "scene/gui/tool_button.h"
#include "scene/gui/tree.h"
-#include "scene/gui/option_button.h"
-#include "scene/gui/panel.h"
-#include "editor/editor_file_dialog.h"
-#include "editor_plugin.h"
class EditorAudioBuses;
class EditorAudioBus : public PanelContainer {
- GDCLASS( EditorAudioBus, PanelContainer )
+ GDCLASS(EditorAudioBus, PanelContainer)
bool prev_active;
float peak_l;
@@ -75,10 +74,10 @@ class EditorAudioBus : public PanelContainer {
bool updating_bus;
- void _gui_input(const InputEvent& p_event);
+ void _gui_input(const InputEvent &p_event);
void _delete_pressed(int p_option);
- void _name_changed(const String& p_new_name);
+ void _name_changed(const String &p_new_name);
void _name_focus_exit() { _name_changed(track_name->get_text()); }
void _volume_db_changed(float p_db);
void _solo_toggled();
@@ -89,52 +88,48 @@ class EditorAudioBus : public PanelContainer {
void _effect_add(int p_which);
void _effect_selected();
void _delete_effect_pressed(int p_option);
- void _effect_rmb(const Vector2& p_pos);
-
-
- virtual Variant get_drag_data(const Point2& p_point);
- virtual bool can_drop_data(const Point2& p_point,const Variant& p_data) const;
- virtual void drop_data(const Point2& p_point,const Variant& p_data);
+ void _effect_rmb(const Vector2 &p_pos);
+ virtual Variant get_drag_data(const Point2 &p_point);
+ virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
+ virtual void drop_data(const Point2 &p_point, const Variant &p_data);
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
-friend class EditorAudioBuses;
+ friend class EditorAudioBuses;
EditorAudioBuses *buses;
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
+public:
void update_bus();
void update_send();
- EditorAudioBus(EditorAudioBuses *p_buses=NULL);
+ EditorAudioBus(EditorAudioBuses *p_buses = NULL);
};
-
class EditorAudioBusDrop : public Panel {
- GDCLASS(EditorAudioBusDrop,Panel);
+ GDCLASS(EditorAudioBusDrop, Panel);
- virtual bool can_drop_data(const Point2& p_point,const Variant& p_data) const;
- virtual void drop_data(const Point2& p_point,const Variant& p_data);
-protected:
+ virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
+ virtual void drop_data(const Point2 &p_point, const Variant &p_data);
+protected:
static void _bind_methods();
-public:
+public:
EditorAudioBusDrop();
};
-class EditorAudioBuses : public VBoxContainer {
+class EditorAudioBuses : public VBoxContainer {
- GDCLASS(EditorAudioBuses,VBoxContainer)
+ GDCLASS(EditorAudioBuses, VBoxContainer)
HBoxContainer *top_hb;
@@ -158,12 +153,11 @@ class EditorAudioBuses : public VBoxContainer {
void _update_bus(int p_index);
void _update_sends();
- void _delete_bus(Object* p_which);
+ void _delete_bus(Object *p_which);
void _duplicate_bus(int p_which);
-
void _request_drop_end();
- void _drop_at_index(int p_bus,int p_index);
+ void _drop_at_index(int p_bus, int p_index);
void _server_save();
@@ -176,30 +170,27 @@ class EditorAudioBuses : public VBoxContainer {
EditorFileDialog *file_dialog;
bool new_layout;
- void _file_dialog_callback(const String& p_string);
+ void _file_dialog_callback(const String &p_string);
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
- void open_layout(const String& p_path);
+public:
+ void open_layout(const String &p_path);
- static EditorAudioBuses* register_editor();
+ static EditorAudioBuses *register_editor();
EditorAudioBuses();
};
-
-
class AudioBusesEditorPlugin : public EditorPlugin {
- GDCLASS( AudioBusesEditorPlugin, EditorPlugin );
+ GDCLASS(AudioBusesEditorPlugin, EditorPlugin);
EditorAudioBuses *audio_bus_editor;
-public:
+public:
virtual String get_name() const { return "SampleLibrary"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -208,7 +199,6 @@ public:
AudioBusesEditorPlugin(EditorAudioBuses *p_node);
~AudioBusesEditorPlugin();
-
};
#endif // EDITORAUDIOBUSES_H
diff --git a/editor/editor_autoload_settings.cpp b/editor/editor_autoload_settings.cpp
index 3e3362f515..67e8c63e51 100644
--- a/editor/editor_autoload_settings.cpp
+++ b/editor/editor_autoload_settings.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "editor_autoload_settings.h"
+#include "editor_node.h"
#include "global_config.h"
#include "global_constants.h"
-#include "editor_node.h"
#define PREVIEW_LIST_MAX_SIZE 10
@@ -51,11 +51,11 @@ void EditorAutoloadSettings::_notification(int p_what) {
}
}
-bool EditorAutoloadSettings::_autoload_name_is_valid(const String& p_name, String* r_error) {
+bool EditorAutoloadSettings::_autoload_name_is_valid(const String &p_name, String *r_error) {
if (!p_name.is_valid_identifier()) {
if (r_error)
- *r_error = TTR("Invalid name.") + "\n" + TTR("Valid characters:")+" a-z, A-Z, 0-9 or _";
+ *r_error = TTR("Invalid name.") + "\n" + TTR("Valid characters:") + " a-z, A-Z, 0-9 or _";
return false;
}
@@ -68,7 +68,7 @@ bool EditorAutoloadSettings::_autoload_name_is_valid(const String& p_name, Strin
}
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (Variant::get_type_name( Variant::Type(i) ) == p_name) {
+ if (Variant::get_type_name(Variant::Type(i)) == p_name) {
if (r_error)
*r_error = TTR("Invalid name. Must not collide with an existing buit-in type name.");
@@ -105,13 +105,13 @@ void EditorAutoloadSettings::_autoload_add() {
}
if (!path.begins_with("res://")) {
- EditorNode::get_singleton()->show_warning(TTR("Invalid Path.") + "\n"+ TTR("Not in resource path."));
+ EditorNode::get_singleton()->show_warning(TTR("Invalid Path.") + "\n" + TTR("Not in resource path."));
return;
}
name = "autoload/" + name;
- UndoRedo* undo_redo = EditorNode::get_singleton()->get_undo_redo();
+ UndoRedo *undo_redo = EditorNode::get_singleton()->get_undo_redo();
undo_redo->create_action(TTR("Add AutoLoad"));
undo_redo->add_do_property(GlobalConfig::get_singleton(), name, "*" + path);
@@ -220,8 +220,8 @@ void EditorAutoloadSettings::_autoload_edited() {
undo_redo->add_do_property(GlobalConfig::get_singleton(), base, path);
undo_redo->add_undo_property(GlobalConfig::get_singleton(), base, GlobalConfig::get_singleton()->get(base));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set_order", base, order);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set_order", base, order);
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set_order", base, order);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set_order", base, order);
undo_redo->add_do_method(this, "update_autoload");
undo_redo->add_undo_method(this, "update_autoload");
@@ -245,7 +245,7 @@ void EditorAutoloadSettings::_autoload_button_pressed(Object *p_item, int p_colu
switch (p_button) {
- case BUTTON_MOVE_UP:
+ case BUTTON_MOVE_UP:
case BUTTON_MOVE_DOWN: {
TreeItem *swap = NULL;
@@ -303,7 +303,7 @@ void EditorAutoloadSettings::_autoload_button_pressed(Object *p_item, int p_colu
}
}
-void EditorAutoloadSettings::_autoload_file_callback(const String& p_path) {
+void EditorAutoloadSettings::_autoload_file_callback(const String &p_path) {
autoload_add_name->set_text(p_path.get_file().get_basename());
}
@@ -361,16 +361,16 @@ void EditorAutoloadSettings::update_autoload() {
item->set_text(2, TTR("Enable"));
item->set_checked(2, global);
- item->add_button(3, get_icon("MoveUp","EditorIcons"), BUTTON_MOVE_UP);
- item->add_button(3, get_icon("MoveDown","EditorIcons"), BUTTON_MOVE_DOWN);
- item->add_button(3, get_icon("Del","EditorIcons"), BUTTON_DELETE);
+ item->add_button(3, get_icon("MoveUp", "EditorIcons"), BUTTON_MOVE_UP);
+ item->add_button(3, get_icon("MoveDown", "EditorIcons"), BUTTON_MOVE_DOWN);
+ item->add_button(3, get_icon("Del", "EditorIcons"), BUTTON_DELETE);
item->set_selectable(3, false);
}
updating_autoload = false;
}
-Variant EditorAutoloadSettings::get_drag_data_fw(const Point2& p_point, Control *p_control) {
+Variant EditorAutoloadSettings::get_drag_data_fw(const Point2 &p_point, Control *p_control) {
if (autoload_cache.size() <= 1)
return false;
@@ -387,13 +387,13 @@ Variant EditorAutoloadSettings::get_drag_data_fw(const Point2& p_point, Control
if (autoloads.size() == 0 || autoloads.size() == autoload_cache.size())
return Variant();
- VBoxContainer *preview = memnew( VBoxContainer );
+ VBoxContainer *preview = memnew(VBoxContainer);
int max_size = MIN(PREVIEW_LIST_MAX_SIZE, autoloads.size());
for (int i = 0; i < max_size; i++) {
- Label *label = memnew( Label(autoloads[i]) );
- label->set_self_modulate(Color(1,1,1,Math::lerp(1, 0, float(i)/PREVIEW_LIST_MAX_SIZE)));
+ Label *label = memnew(Label(autoloads[i]));
+ label->set_self_modulate(Color(1, 1, 1, Math::lerp(1, 0, float(i) / PREVIEW_LIST_MAX_SIZE)));
preview->add_child(label);
}
@@ -408,7 +408,7 @@ Variant EditorAutoloadSettings::get_drag_data_fw(const Point2& p_point, Control
return drop_data;
}
-bool EditorAutoloadSettings::can_drop_data_fw(const Point2& p_point, const Variant& p_data, Control *p_control) const {
+bool EditorAutoloadSettings::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_control) const {
if (updating_autoload)
return false;
@@ -434,7 +434,7 @@ bool EditorAutoloadSettings::can_drop_data_fw(const Point2& p_point, const Varia
return false;
}
-void EditorAutoloadSettings::drop_data_fw(const Point2& p_point, const Variant& p_data, Control *p_control) {
+void EditorAutoloadSettings::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_control) {
TreeItem *ti = tree->get_item_at_pos(p_point);
@@ -544,13 +544,13 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
updating_autoload = false;
selected_autoload = "";
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
add_child(hbc);
- VBoxContainer *vbc_path = memnew( VBoxContainer );
+ VBoxContainer *vbc_path = memnew(VBoxContainer);
vbc_path->set_h_size_flags(SIZE_EXPAND_FILL);
- autoload_add_path = memnew( EditorLineEditFileChooser );
+ autoload_add_path = memnew(EditorLineEditFileChooser);
autoload_add_path->set_h_size_flags(SIZE_EXPAND_FILL);
autoload_add_path->get_file_dialog()->set_mode(EditorFileDialog::MODE_OPEN_FILE);
@@ -559,16 +559,16 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
vbc_path->add_margin_child(TTR("Path:"), autoload_add_path);
hbc->add_child(vbc_path);
- VBoxContainer *vbc_name = memnew( VBoxContainer );
+ VBoxContainer *vbc_name = memnew(VBoxContainer);
vbc_name->set_h_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *hbc_name = memnew( HBoxContainer );
+ HBoxContainer *hbc_name = memnew(HBoxContainer);
- autoload_add_name = memnew( LineEdit );
+ autoload_add_name = memnew(LineEdit);
autoload_add_name->set_h_size_flags(SIZE_EXPAND_FILL);
hbc_name->add_child(autoload_add_name);
- Button *add_autoload = memnew( Button );
+ Button *add_autoload = memnew(Button);
add_autoload->set_text(TTR("Add"));
hbc_name->add_child(add_autoload);
add_autoload->connect("pressed", this, "_autoload_add");
@@ -576,7 +576,7 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
vbc_name->add_margin_child(TTR("Node Name:"), hbc_name);
hbc->add_child(vbc_name);
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_hide_root(true);
tree->set_select_mode(Tree::SELECT_MULTI);
tree->set_single_select_cell_editing_only_when_already_selected(true);
@@ -586,20 +586,20 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
tree->set_columns(4);
tree->set_column_titles_visible(true);
- tree->set_column_title(0,TTR("Name"));
- tree->set_column_expand(0,true);
- tree->set_column_min_width(0,100);
+ tree->set_column_title(0, TTR("Name"));
+ tree->set_column_expand(0, true);
+ tree->set_column_min_width(0, 100);
- tree->set_column_title(1,TTR("Path"));
- tree->set_column_expand(1,true);
- tree->set_column_min_width(1,100);
+ tree->set_column_title(1, TTR("Path"));
+ tree->set_column_expand(1, true);
+ tree->set_column_min_width(1, 100);
- tree->set_column_title(2,TTR("Singleton"));
- tree->set_column_expand(2,false);
- tree->set_column_min_width(2,80);
+ tree->set_column_title(2, TTR("Singleton"));
+ tree->set_column_expand(2, false);
+ tree->set_column_min_width(2, 80);
- tree->set_column_expand(3,false);
- tree->set_column_min_width(3,80);
+ tree->set_column_expand(3, false);
+ tree->set_column_min_width(3, 80);
tree->connect("cell_selected", this, "_autoload_selected");
tree->connect("item_edited", this, "_autoload_edited");
@@ -607,4 +607,3 @@ EditorAutoloadSettings::EditorAutoloadSettings() {
add_margin_child(TTR("List:"), tree, true);
}
-
diff --git a/editor/editor_autoload_settings.h b/editor/editor_autoload_settings.h
index 2afe239000..8eb6140180 100644
--- a/editor/editor_autoload_settings.h
+++ b/editor/editor_autoload_settings.h
@@ -36,7 +36,7 @@
class EditorAutoloadSettings : public VBoxContainer {
- GDCLASS( EditorAutoloadSettings, VBoxContainer );
+ GDCLASS(EditorAutoloadSettings, VBoxContainer);
enum {
BUTTON_MOVE_UP,
@@ -50,7 +50,7 @@ class EditorAutoloadSettings : public VBoxContainer {
String name;
int order;
- bool operator==(const AutoLoadInfo& p_info) {
+ bool operator==(const AutoLoadInfo &p_info) {
return order == p_info.order;
}
};
@@ -65,30 +65,26 @@ class EditorAutoloadSettings : public VBoxContainer {
EditorLineEditFileChooser *autoload_add_path;
LineEdit *autoload_add_name;
- bool _autoload_name_is_valid(const String& p_string, String *r_error = NULL);
+ bool _autoload_name_is_valid(const String &p_string, String *r_error = NULL);
void _autoload_add();
void _autoload_selected();
void _autoload_edited();
void _autoload_button_pressed(Object *p_item, int p_column, int p_button);
- void _autoload_file_callback(const String& p_path);
+ void _autoload_file_callback(const String &p_path);
- Variant get_drag_data_fw(const Point2& p_point, Control *p_from);
- bool can_drop_data_fw(const Point2& p_point, const Variant& p_data, Control *p_from) const;
- void drop_data_fw(const Point2& p_point, const Variant& p_data, Control *p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
void update_autoload();
EditorAutoloadSettings();
-
};
#endif
-
diff --git a/editor/editor_data.cpp b/editor/editor_data.cpp
index d2fa40e08c..d92a348df9 100644
--- a/editor/editor_data.cpp
+++ b/editor/editor_data.cpp
@@ -28,30 +28,30 @@
/*************************************************************************/
#include "editor_data.h"
-#include "global_config.h"
+#include "editor_node.h"
#include "editor_settings.h"
-#include "os/dir_access.h"
+#include "global_config.h"
#include "io/resource_loader.h"
-#include "scene/resources/packed_scene.h"
+#include "os/dir_access.h"
#include "os/file_access.h"
-#include "editor_node.h"
+#include "scene/resources/packed_scene.h"
void EditorHistory::_cleanup_history() {
- for(int i=0;i<history.size();i++) {
+ for (int i = 0; i < history.size(); i++) {
- bool fail=false;
+ bool fail = false;
- for(int j=0;j<history[i].path.size();j++) {
+ for (int j = 0; j < history[i].path.size(); j++) {
if (!history[i].path[j].ref.is_null())
continue;
if (ObjectDB::get_instance(history[i].path[j].object))
continue; //has isntance, try next
- if (j<=history[i].level) {
+ if (j <= history[i].level) {
//before or equal level, complete fail
- fail=true;
+ fail = true;
} else {
//after level, clip
history[i].path.resize(j);
@@ -66,46 +66,46 @@ void EditorHistory::_cleanup_history() {
}
}
- if (current>=history.size())
- current=history.size()-1;
+ if (current >= history.size())
+ current = history.size() - 1;
}
-void EditorHistory::_add_object(ObjectID p_object,const String& p_property,int p_level_change) {
+void EditorHistory::_add_object(ObjectID p_object, const String &p_property, int p_level_change) {
Object *obj = ObjectDB::get_instance(p_object);
ERR_FAIL_COND(!obj);
Reference *r = obj->cast_to<Reference>();
Obj o;
if (r)
- o.ref=REF(r);
- o.object=p_object;
- o.property=p_property;
+ o.ref = REF(r);
+ o.object = p_object;
+ o.property = p_property;
History h;
- bool has_prev = current>=0 && current<history.size();
+ bool has_prev = current >= 0 && current < history.size();
if (has_prev) {
- history.resize(current+1); //clip history to next
+ history.resize(current + 1); //clip history to next
}
- if (p_property!="" && has_prev) {
+ if (p_property != "" && has_prev) {
//add a sub property
History &pr = history[current];
- h=pr;
- h.path.resize(h.level+1);
+ h = pr;
+ h.path.resize(h.level + 1);
h.path.push_back(o);
h.level++;
- } else if (p_level_change!=-1 && has_prev) {
+ } else if (p_level_change != -1 && has_prev) {
//add a sub property
History &pr = history[current];
- h=pr;
- ERR_FAIL_INDEX(p_level_change,h.path.size());
- h.level=p_level_change;
+ h = pr;
+ ERR_FAIL_INDEX(p_level_change, h.path.size());
+ h.level = p_level_change;
} else {
//add a new node
h.path.push_back(o);
- h.level=0;
+ h.level = 0;
}
history.push_back(h);
@@ -114,17 +114,17 @@ void EditorHistory::_add_object(ObjectID p_object,const String& p_property,int p
void EditorHistory::add_object(ObjectID p_object) {
- _add_object(p_object,"",-1);
+ _add_object(p_object, "", -1);
}
-void EditorHistory::add_object(ObjectID p_object,const String& p_subprop) {
+void EditorHistory::add_object(ObjectID p_object, const String &p_subprop) {
- _add_object(p_object,p_subprop,-1);
+ _add_object(p_object, p_subprop, -1);
}
-void EditorHistory::add_object(ObjectID p_object,int p_relevel){
+void EditorHistory::add_object(ObjectID p_object, int p_relevel) {
- _add_object(p_object,"",p_relevel);
+ _add_object(p_object, "", p_relevel);
}
int EditorHistory::get_history_len() {
@@ -135,26 +135,24 @@ int EditorHistory::get_history_pos() {
}
ObjectID EditorHistory::get_history_obj(int p_obj) const {
- ERR_FAIL_INDEX_V(p_obj,history.size(),0);
- ERR_FAIL_INDEX_V(history[p_obj].level,history[p_obj].path.size(),0);
+ ERR_FAIL_INDEX_V(p_obj, history.size(), 0);
+ ERR_FAIL_INDEX_V(history[p_obj].level, history[p_obj].path.size(), 0);
return history[p_obj].path[history[p_obj].level].object;
}
bool EditorHistory::is_at_begining() const {
- return current<=0;
+ return current <= 0;
}
bool EditorHistory::is_at_end() const {
- return ((current+1)>=history.size());
+ return ((current + 1) >= history.size());
}
-
bool EditorHistory::next() {
-
_cleanup_history();
- if ((current+1)<history.size())
+ if ((current + 1) < history.size())
current++;
else
return false;
@@ -164,10 +162,9 @@ bool EditorHistory::next() {
bool EditorHistory::previous() {
-
_cleanup_history();
- if (current>0)
+ if (current > 0)
current--;
else
return false;
@@ -177,11 +174,10 @@ bool EditorHistory::previous() {
ObjectID EditorHistory::get_current() {
-
- if (current<0 || current >=history.size())
+ if (current < 0 || current >= history.size())
return 0;
- History &h=history[current];
+ History &h = history[current];
Object *obj = ObjectDB::get_instance(h.path[h.level].object);
if (!obj)
return 0;
@@ -191,22 +187,21 @@ ObjectID EditorHistory::get_current() {
int EditorHistory::get_path_size() const {
- if (current<0 || current >=history.size())
+ if (current < 0 || current >= history.size())
return 0;
- const History &h=history[current];
+ const History &h = history[current];
return h.path.size();
-
}
ObjectID EditorHistory::get_path_object(int p_index) const {
- if (current<0 || current >=history.size())
+ if (current < 0 || current >= history.size())
return 0;
- const History &h=history[current];
+ const History &h = history[current];
- ERR_FAIL_INDEX_V(p_index,h.path.size(),0);
+ ERR_FAIL_INDEX_V(p_index, h.path.size(), 0);
Object *obj = ObjectDB::get_instance(h.path[p_index].object);
if (!obj)
@@ -217,31 +212,30 @@ ObjectID EditorHistory::get_path_object(int p_index) const {
String EditorHistory::get_path_property(int p_index) const {
- if (current<0 || current >=history.size())
+ if (current < 0 || current >= history.size())
return "";
- const History &h=history[current];
+ const History &h = history[current];
- ERR_FAIL_INDEX_V(p_index,h.path.size(),"");
+ ERR_FAIL_INDEX_V(p_index, h.path.size(), "");
return h.path[p_index].property;
-
}
void EditorHistory::clear() {
history.clear();
- current=-1;
+ current = -1;
}
EditorHistory::EditorHistory() {
- current=-1;
+ current = -1;
}
-EditorPlugin* EditorData::get_editor(Object *p_object) {
+EditorPlugin *EditorData::get_editor(Object *p_object) {
- for (int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
if (editor_plugins[i]->has_main_screen() && editor_plugins[i]->handles(p_object))
return editor_plugins[i];
@@ -250,9 +244,9 @@ EditorPlugin* EditorData::get_editor(Object *p_object) {
return NULL;
}
-EditorPlugin* EditorData::get_subeditor(Object *p_object) {
+EditorPlugin *EditorData::get_subeditor(Object *p_object) {
- for (int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
if (!editor_plugins[i]->has_main_screen() && editor_plugins[i]->handles(p_object))
return editor_plugins[i];
@@ -261,8 +255,8 @@ EditorPlugin* EditorData::get_subeditor(Object *p_object) {
return NULL;
}
-Vector<EditorPlugin*> EditorData::get_subeditors(Object* p_object) {
- Vector<EditorPlugin*> sub_plugins;
+Vector<EditorPlugin *> EditorData::get_subeditors(Object *p_object) {
+ Vector<EditorPlugin *> sub_plugins;
for (int i = 0; i < editor_plugins.size(); i++) {
if (!editor_plugins[i]->has_main_screen() && editor_plugins[i]->handles(p_object)) {
sub_plugins.push_back(editor_plugins[i]);
@@ -271,11 +265,11 @@ Vector<EditorPlugin*> EditorData::get_subeditors(Object* p_object) {
return sub_plugins;
}
-EditorPlugin* EditorData::get_editor(String p_name) {
+EditorPlugin *EditorData::get_editor(String p_name) {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
- if (editor_plugins[i]->get_name()==p_name)
+ if (editor_plugins[i]->get_name() == p_name)
return editor_plugins[i];
}
@@ -289,79 +283,73 @@ void EditorData::copy_object_params(Object *p_object) {
List<PropertyInfo> pinfo;
p_object->get_property_list(&pinfo);
- for( List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_EDITOR))
+ if (!(E->get().usage & PROPERTY_USAGE_EDITOR))
continue;
PropertyData pd;
- pd.name=E->get().name;
- pd.value=p_object->get(pd.name);
+ pd.name = E->get().name;
+ pd.value = p_object->get(pd.name);
clipboard.push_back(pd);
}
}
void EditorData::get_editor_breakpoints(List<String> *p_breakpoints) {
-
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->get_breakpoints(p_breakpoints);
}
-
-
}
Dictionary EditorData::get_editor_states() const {
Dictionary metadata;
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
- Dictionary state=editor_plugins[i]->get_state();
+ Dictionary state = editor_plugins[i]->get_state();
if (state.empty())
continue;
- metadata[editor_plugins[i]->get_name()]=state;
+ metadata[editor_plugins[i]->get_name()] = state;
}
return metadata;
-
}
-Dictionary EditorData::get_scene_editor_states(int p_idx) const
-{
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),Dictionary());
+Dictionary EditorData::get_scene_editor_states(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), Dictionary());
EditedScene es = edited_scene[p_idx];
return es.editor_states;
}
-void EditorData::set_editor_states(const Dictionary& p_states) {
+void EditorData::set_editor_states(const Dictionary &p_states) {
List<Variant> keys;
p_states.get_key_list(&keys);
- List<Variant>::Element *E=keys.front();
- for(;E;E=E->next()) {
+ List<Variant>::Element *E = keys.front();
+ for (; E; E = E->next()) {
String name = E->get();
- int idx=-1;
- for(int i=0;i<editor_plugins.size();i++) {
+ int idx = -1;
+ for (int i = 0; i < editor_plugins.size(); i++) {
- if (editor_plugins[i]->get_name()==name) {
- idx=i;
+ if (editor_plugins[i]->get_name() == name) {
+ idx = i;
break;
}
}
- if (idx==-1)
+ if (idx == -1)
continue;
editor_plugins[idx]->set_state(p_states[name]);
}
-
}
void EditorData::notify_edited_scene_changed() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->edited_scene_changed();
}
@@ -369,16 +357,15 @@ void EditorData::notify_edited_scene_changed() {
void EditorData::clear_editor_states() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->clear();
}
-
}
void EditorData::save_editor_external_data() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->save_external_data();
}
@@ -386,42 +373,36 @@ void EditorData::save_editor_external_data() {
void EditorData::apply_changes_in_editors() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->apply_changes();
}
-
}
void EditorData::save_editor_global_states() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->save_global_state();
}
}
-void EditorData::restore_editor_global_states(){
+void EditorData::restore_editor_global_states() {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->restore_global_state();
}
-
}
-
void EditorData::paste_object_params(Object *p_object) {
+ for (List<PropertyData>::Element *E = clipboard.front(); E; E = E->next()) {
- for( List<PropertyData>::Element *E=clipboard.front();E;E=E->next()) {
-
- p_object->set( E->get().name, E->get().value);
+ p_object->set(E->get().name, E->get().value);
}
-
}
-
UndoRedo &EditorData::get_undo_redo() {
return undo_redo;
@@ -429,14 +410,13 @@ UndoRedo &EditorData::get_undo_redo() {
void EditorData::remove_editor_plugin(EditorPlugin *p_plugin) {
- p_plugin->undo_redo=NULL;
+ p_plugin->undo_redo = NULL;
editor_plugins.erase(p_plugin);
-
}
void EditorData::add_editor_plugin(EditorPlugin *p_plugin) {
- p_plugin->undo_redo=&undo_redo;
+ p_plugin->undo_redo = &undo_redo;
editor_plugins.push_back(p_plugin);
}
@@ -445,32 +425,30 @@ int EditorData::get_editor_plugin_count() const {
}
EditorPlugin *EditorData::get_editor_plugin(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,editor_plugins.size(),NULL);
+ ERR_FAIL_INDEX_V(p_idx, editor_plugins.size(), NULL);
return editor_plugins[p_idx];
}
-
-void EditorData::add_custom_type(const String& p_type, const String& p_inherits,const Ref<Script>& p_script,const Ref<Texture>& p_icon ) {
+void EditorData::add_custom_type(const String &p_type, const String &p_inherits, const Ref<Script> &p_script, const Ref<Texture> &p_icon) {
ERR_FAIL_COND(p_script.is_null());
CustomType ct;
- ct.name=p_type;
- ct.icon=p_icon;
- ct.script=p_script;
+ ct.name = p_type;
+ ct.icon = p_icon;
+ ct.script = p_script;
if (!custom_types.has(p_inherits)) {
- custom_types[p_inherits]=Vector<CustomType>();
+ custom_types[p_inherits] = Vector<CustomType>();
}
custom_types[p_inherits].push_back(ct);
}
-void EditorData::remove_custom_type(const String& p_type){
-
+void EditorData::remove_custom_type(const String &p_type) {
- for (Map<String,Vector<CustomType> >::Element *E=custom_types.front();E;E=E->next()) {
+ for (Map<String, Vector<CustomType> >::Element *E = custom_types.front(); E; E = E->next()) {
- for(int i=0;i<E->get().size();i++) {
- if (E->get()[i].name==p_type) {
+ for (int i = 0; i < E->get().size(); i++) {
+ if (E->get()[i].name == p_type) {
E->get().remove(i);
if (E->get().empty()) {
custom_types.erase(E->key());
@@ -479,51 +457,49 @@ void EditorData::remove_custom_type(const String& p_type){
}
}
}
-
}
int EditorData::add_edited_scene(int p_at_pos) {
- if (p_at_pos<0)
- p_at_pos=edited_scene.size();
+ if (p_at_pos < 0)
+ p_at_pos = edited_scene.size();
EditedScene es;
- es.root=NULL;
- es.history_current=-1;
- es.version=0;
- es.live_edit_root=NodePath(String("/root"));
+ es.root = NULL;
+ es.history_current = -1;
+ es.version = 0;
+ es.live_edit_root = NodePath(String("/root"));
- if (p_at_pos==edited_scene.size())
+ if (p_at_pos == edited_scene.size())
edited_scene.push_back(es);
else
- edited_scene.insert(p_at_pos,es);
+ edited_scene.insert(p_at_pos, es);
- if (current_edited_scene<0)
- current_edited_scene=0;
+ if (current_edited_scene < 0)
+ current_edited_scene = 0;
return p_at_pos;
}
-void EditorData::move_edited_scene_index(int p_idx,int p_to_idx){
+void EditorData::move_edited_scene_index(int p_idx, int p_to_idx) {
- ERR_FAIL_INDEX(p_idx,edited_scene.size());
- ERR_FAIL_INDEX(p_to_idx,edited_scene.size());
- SWAP(edited_scene[p_idx],edited_scene[p_to_idx]);
+ ERR_FAIL_INDEX(p_idx, edited_scene.size());
+ ERR_FAIL_INDEX(p_to_idx, edited_scene.size());
+ SWAP(edited_scene[p_idx], edited_scene[p_to_idx]);
}
-void EditorData::remove_scene(int p_idx){
- ERR_FAIL_INDEX(p_idx,edited_scene.size());
+void EditorData::remove_scene(int p_idx) {
+ ERR_FAIL_INDEX(p_idx, edited_scene.size());
if (edited_scene[p_idx].root)
memdelete(edited_scene[p_idx].root);
- if (current_edited_scene>p_idx)
+ if (current_edited_scene > p_idx)
current_edited_scene--;
- else if (current_edited_scene==p_idx && current_edited_scene>0) {
+ else if (current_edited_scene == p_idx && current_edited_scene > 0) {
current_edited_scene--;
}
edited_scene.remove(p_idx);
-
}
-bool EditorData::_find_updated_instances(Node* p_root,Node *p_node,Set<String> &checked_paths) {
+bool EditorData::_find_updated_instances(Node *p_root, Node *p_node, Set<String> &checked_paths) {
/*
if (p_root!=p_node && p_node->get_owner()!=p_root && !p_root->is_editable_instance(p_node->get_owner()))
@@ -532,10 +508,10 @@ bool EditorData::_find_updated_instances(Node* p_root,Node *p_node,Set<String> &
Ref<SceneState> ss;
- if (p_node==p_root) {
- ss=p_node->get_scene_inherited_state();
- } else if (p_node->get_filename()!=String()){
- ss=p_node->get_scene_instance_state();
+ if (p_node == p_root) {
+ ss = p_node->get_scene_inherited_state();
+ } else if (p_node->get_filename() != String()) {
+ ss = p_node->get_scene_instance_state();
}
if (ss.is_valid()) {
@@ -544,18 +520,17 @@ bool EditorData::_find_updated_instances(Node* p_root,Node *p_node,Set<String> &
if (!checked_paths.has(path)) {
uint64_t modified_time = FileAccess::get_modified_time(path);
- if (modified_time!=ss->get_last_modified_time()) {
+ if (modified_time != ss->get_last_modified_time()) {
return true; //external scene changed
}
checked_paths.insert(path);
}
-
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- bool found = _find_updated_instances(p_root,p_node->get_child(i),checked_paths);
+ bool found = _find_updated_instances(p_root, p_node->get_child(i), checked_paths);
if (found)
return true;
}
@@ -563,79 +538,75 @@ bool EditorData::_find_updated_instances(Node* p_root,Node *p_node,Set<String> &
return false;
}
-
bool EditorData::check_and_update_scene(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), false);
if (!edited_scene[p_idx].root)
return false;
Set<String> checked_scenes;
+ bool must_reload = _find_updated_instances(edited_scene[p_idx].root, edited_scene[p_idx].root, checked_scenes);
- bool must_reload = _find_updated_instances(edited_scene[p_idx].root,edited_scene[p_idx].root,checked_scenes);
-
- print_line("MUST RELOAD? "+itos(must_reload));
+ print_line("MUST RELOAD? " + itos(must_reload));
if (must_reload) {
Ref<PackedScene> pscene;
pscene.instance();
- EditorProgress ep("update_scene",TTR("Updating Scene"),2);
- ep.step(TTR("Storing local changes.."),0);
+ EditorProgress ep("update_scene", TTR("Updating Scene"), 2);
+ ep.step(TTR("Storing local changes.."), 0);
//pack first, so it stores diffs to previous version of saved scene
Error err = pscene->pack(edited_scene[p_idx].root);
- ERR_FAIL_COND_V(err!=OK,false);
- ep.step(TTR("Updating scene.."),1);
+ ERR_FAIL_COND_V(err != OK, false);
+ ep.step(TTR("Updating scene.."), 1);
Node *new_scene = pscene->instance(PackedScene::GEN_EDIT_STATE_MAIN);
- ERR_FAIL_COND_V(!new_scene,false);
+ ERR_FAIL_COND_V(!new_scene, false);
//transfer selection
- List<Node*> new_selection;
- for (List<Node*>::Element *E=edited_scene[p_idx].selection.front();E;E=E->next()) {
+ List<Node *> new_selection;
+ for (List<Node *>::Element *E = edited_scene[p_idx].selection.front(); E; E = E->next()) {
NodePath p = edited_scene[p_idx].root->get_path_to(E->get());
Node *new_node = new_scene->get_node(p);
if (new_node)
new_selection.push_back(new_node);
}
- new_scene->set_filename( edited_scene[p_idx].root->get_filename() );
+ new_scene->set_filename(edited_scene[p_idx].root->get_filename());
memdelete(edited_scene[p_idx].root);
- edited_scene[p_idx].root=new_scene;
- edited_scene[p_idx].selection=new_selection;
+ edited_scene[p_idx].root = new_scene;
+ edited_scene[p_idx].selection = new_selection;
return true;
-
}
return false;
-
}
int EditorData::get_edited_scene() const {
return current_edited_scene;
}
-void EditorData::set_edited_scene(int p_idx){
+void EditorData::set_edited_scene(int p_idx) {
- ERR_FAIL_INDEX(p_idx,edited_scene.size());
- current_edited_scene=p_idx;
+ ERR_FAIL_INDEX(p_idx, edited_scene.size());
+ current_edited_scene = p_idx;
//swap
}
-Node* EditorData::get_edited_scene_root(int p_idx){
+Node *EditorData::get_edited_scene_root(int p_idx) {
if (p_idx < 0) {
- ERR_FAIL_INDEX_V(current_edited_scene,edited_scene.size(),NULL);
+ ERR_FAIL_INDEX_V(current_edited_scene, edited_scene.size(), NULL);
return edited_scene[current_edited_scene].root;
} else {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),NULL);
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), NULL);
return edited_scene[p_idx].root;
}
}
-void EditorData::set_edited_scene_root(Node* p_root) {
+void EditorData::set_edited_scene_root(Node *p_root) {
- ERR_FAIL_INDEX(current_edited_scene,edited_scene.size());
- edited_scene[current_edited_scene].root=p_root;
+ ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
+ edited_scene[current_edited_scene].root = p_root;
}
int EditorData::get_edited_scene_count() const {
@@ -644,123 +615,111 @@ int EditorData::get_edited_scene_count() const {
}
void EditorData::set_edited_scene_version(uint64_t version, int scene_idx) {
- ERR_FAIL_INDEX(current_edited_scene,edited_scene.size());
+ ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
if (scene_idx < 0) {
- edited_scene[current_edited_scene].version=version;
+ edited_scene[current_edited_scene].version = version;
} else {
- ERR_FAIL_INDEX(scene_idx,edited_scene.size());
- edited_scene[scene_idx].version=version;
+ ERR_FAIL_INDEX(scene_idx, edited_scene.size());
+ edited_scene[scene_idx].version = version;
}
-
}
-uint64_t EditorData::get_edited_scene_version() const{
+uint64_t EditorData::get_edited_scene_version() const {
- ERR_FAIL_INDEX_V(current_edited_scene,edited_scene.size(),0);
+ ERR_FAIL_INDEX_V(current_edited_scene, edited_scene.size(), 0);
return edited_scene[current_edited_scene].version;
-
}
-uint64_t EditorData::get_scene_version(int p_idx) const{
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),false);
+uint64_t EditorData::get_scene_version(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), false);
return edited_scene[p_idx].version;
}
String EditorData::get_scene_type(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), String());
if (!edited_scene[p_idx].root)
return "";
return edited_scene[p_idx].root->get_class();
-
}
void EditorData::move_edited_scene_to_index(int p_idx) {
- ERR_FAIL_INDEX(current_edited_scene,edited_scene.size());
- ERR_FAIL_INDEX(p_idx,edited_scene.size());
+ ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
+ ERR_FAIL_INDEX(p_idx, edited_scene.size());
- EditedScene es=edited_scene[current_edited_scene];
+ EditedScene es = edited_scene[current_edited_scene];
edited_scene.remove(current_edited_scene);
- edited_scene.insert(p_idx,es);
- current_edited_scene=p_idx;
+ edited_scene.insert(p_idx, es);
+ current_edited_scene = p_idx;
}
Ref<Script> EditorData::get_scene_root_script(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),Ref<Script>());
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), Ref<Script>());
if (!edited_scene[p_idx].root)
return Ref<Script>();
- Ref<Script> s=edited_scene[p_idx].root->get_script();
+ Ref<Script> s = edited_scene[p_idx].root->get_script();
if (!s.is_valid() && edited_scene[p_idx].root->get_child_count()) {
Node *n = edited_scene[p_idx].root->get_child(0);
- while(!s.is_valid() && n && n->get_filename()==String()) {
- s=n->get_script();
- n=n->get_parent();
+ while (!s.is_valid() && n && n->get_filename() == String()) {
+ s = n->get_script();
+ n = n->get_parent();
}
}
return s;
}
String EditorData::get_scene_title(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), String());
if (!edited_scene[p_idx].root)
return "[empty]";
- if (edited_scene[p_idx].root->get_filename()=="")
+ if (edited_scene[p_idx].root->get_filename() == "")
return "[unsaved]";
return edited_scene[p_idx].root->get_filename().get_file();
}
-
String EditorData::get_scene_path(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,edited_scene.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, edited_scene.size(), String());
if (!edited_scene[p_idx].root)
return "";
return edited_scene[p_idx].root->get_filename();
-
}
-void EditorData::set_edited_scene_live_edit_root(const NodePath& p_root) {
- ERR_FAIL_INDEX(current_edited_scene,edited_scene.size());
-
- edited_scene[current_edited_scene].live_edit_root=p_root;
+void EditorData::set_edited_scene_live_edit_root(const NodePath &p_root) {
+ ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
+ edited_scene[current_edited_scene].live_edit_root = p_root;
}
NodePath EditorData::get_edited_scene_live_edit_root() {
- ERR_FAIL_INDEX_V(current_edited_scene,edited_scene.size(),String());
+ ERR_FAIL_INDEX_V(current_edited_scene, edited_scene.size(), String());
return edited_scene[current_edited_scene].live_edit_root;
-
-
-
}
+void EditorData::save_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history, const Dictionary &p_custom) {
-void EditorData::save_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history, const Dictionary& p_custom) {
-
- ERR_FAIL_INDEX(current_edited_scene,edited_scene.size());
+ ERR_FAIL_INDEX(current_edited_scene, edited_scene.size());
- EditedScene &es=edited_scene[current_edited_scene];
+ EditedScene &es = edited_scene[current_edited_scene];
es.selection = p_selection->get_selected_node_list();
- es.history_current=p_history->current;
- es.history_stored=p_history->history;
- es.editor_states=get_editor_states();
- es.custom_state=p_custom;
-
+ es.history_current = p_history->current;
+ es.history_stored = p_history->history;
+ es.editor_states = get_editor_states();
+ es.custom_state = p_custom;
}
Dictionary EditorData::restore_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history) {
- ERR_FAIL_INDEX_V(current_edited_scene,edited_scene.size(),Dictionary());
-
- EditedScene &es=edited_scene[current_edited_scene];
+ ERR_FAIL_INDEX_V(current_edited_scene, edited_scene.size(), Dictionary());
- p_history->current=es.history_current;
- p_history->history=es.history_stored;
+ EditedScene &es = edited_scene[current_edited_scene];
+ p_history->current = es.history_current;
+ p_history->history = es.history_stored;
p_selection->clear();
- for(List<Node*>::Element *E=es.selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = es.selection.front(); E; E = E->next()) {
p_selection->add_node(E->get());
}
set_editor_states(es.editor_states);
@@ -768,34 +727,31 @@ Dictionary EditorData::restore_edited_scene_state(EditorSelection *p_selection,
return es.custom_state;
}
-
void EditorData::clear_edited_scenes() {
- for(int i=0;i<edited_scene.size();i++) {
+ for (int i = 0; i < edited_scene.size(); i++) {
if (edited_scene[i].root) {
- memdelete( edited_scene[i].root );
+ memdelete(edited_scene[i].root);
}
}
edited_scene.clear();
}
-
-
void EditorData::set_plugin_window_layout(Ref<ConfigFile> p_layout) {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->set_window_layout(p_layout);
}
}
void EditorData::get_plugin_window_layout(Ref<ConfigFile> p_layout) {
- for(int i=0;i<editor_plugins.size();i++) {
+ for (int i = 0; i < editor_plugins.size(); i++) {
editor_plugins[i]->get_window_layout(p_layout);
}
}
EditorData::EditorData() {
- current_edited_scene=-1;
+ current_edited_scene = -1;
//load_imported_scenes_from_globals();
}
@@ -810,8 +766,8 @@ void EditorSelection::_node_removed(Node *p_node) {
if (meta)
memdelete(meta);
selection.erase(p_node);
- changed=true;
- nl_changed=true;
+ changed = true;
+ nl_changed = true;
}
void EditorSelection::add_node(Node *p_node) {
@@ -821,20 +777,19 @@ void EditorSelection::add_node(Node *p_node) {
if (selection.has(p_node))
return;
- changed=true;
- nl_changed=true;
- Object *meta=NULL;
- for(List<Object*>::Element *E=editor_plugins.front();E;E=E->next()) {
+ changed = true;
+ nl_changed = true;
+ Object *meta = NULL;
+ for (List<Object *>::Element *E = editor_plugins.front(); E; E = E->next()) {
- meta = E->get()->call("_get_editor_data",p_node);
+ meta = E->get()->call("_get_editor_data", p_node);
if (meta) {
break;
}
-
}
- selection[p_node]=meta;
+ selection[p_node] = meta;
- p_node->connect("tree_exited",this,"_node_removed",varray(p_node),CONNECT_ONESHOT);
+ p_node->connect("tree_exited", this, "_node_removed", varray(p_node), CONNECT_ONESHOT);
//emit_signal("selection_changed");
}
@@ -846,16 +801,16 @@ void EditorSelection::remove_node(Node *p_node) {
if (!selection.has(p_node))
return;
- changed=true;
- nl_changed=true;
+ changed = true;
+ nl_changed = true;
Object *meta = selection[p_node];
if (meta)
memdelete(meta);
selection.erase(p_node);
- p_node->disconnect("tree_exited",this,"_node_removed");
+ p_node->disconnect("tree_exited", this, "_node_removed");
//emit_signal("selection_changed");
}
-bool EditorSelection::is_selected(Node * p_node) const {
+bool EditorSelection::is_selected(Node *p_node) const {
return selection.has(p_node);
}
@@ -864,7 +819,7 @@ Array EditorSelection::_get_transformable_selected_nodes() {
Array ret;
- for (List<Node*>::Element *E=selected_node_list.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selected_node_list.front(); E; E = E->next()) {
ret.push_back(E->get());
}
@@ -876,7 +831,7 @@ Array EditorSelection::_get_selected_nodes() {
Array ret;
- for (Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
ret.push_back(E->key());
}
@@ -886,14 +841,13 @@ Array EditorSelection::_get_selected_nodes() {
void EditorSelection::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_node_removed"),&EditorSelection::_node_removed);
- ClassDB::bind_method(D_METHOD("clear"),&EditorSelection::clear);
- ClassDB::bind_method(D_METHOD("add_node","node:Node"),&EditorSelection::add_node);
- ClassDB::bind_method(D_METHOD("remove_node","node:Node"),&EditorSelection::remove_node);
- ClassDB::bind_method(D_METHOD("get_selected_nodes"),&EditorSelection::_get_selected_nodes);
- ClassDB::bind_method(D_METHOD("get_transformable_selected_nodes"),&EditorSelection::_get_transformable_selected_nodes);
- ADD_SIGNAL( MethodInfo("selection_changed") );
-
+ ClassDB::bind_method(D_METHOD("_node_removed"), &EditorSelection::_node_removed);
+ ClassDB::bind_method(D_METHOD("clear"), &EditorSelection::clear);
+ ClassDB::bind_method(D_METHOD("add_node", "node:Node"), &EditorSelection::add_node);
+ ClassDB::bind_method(D_METHOD("remove_node", "node:Node"), &EditorSelection::remove_node);
+ ClassDB::bind_method(D_METHOD("get_selected_nodes"), &EditorSelection::_get_selected_nodes);
+ ClassDB::bind_method(D_METHOD("get_transformable_selected_nodes"), &EditorSelection::_get_transformable_selected_nodes);
+ ADD_SIGNAL(MethodInfo("selection_changed"));
}
void EditorSelection::add_editor_plugin(Object *p_object) {
@@ -908,18 +862,17 @@ void EditorSelection::_update_nl() {
selected_node_list.clear();
- for (Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
-
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Node *parent = E->key();
- parent=parent->get_parent();
- bool skip=false;
+ parent = parent->get_parent();
+ bool skip = false;
while (parent) {
if (selection.has(parent)) {
- skip=true;
+ skip = true;
break;
}
- parent=parent->get_parent();
+ parent = parent->get_parent();
}
if (skip)
@@ -927,7 +880,7 @@ void EditorSelection::_update_nl() {
selected_node_list.push_back(E->key());
}
- nl_changed=true;
+ nl_changed = true;
}
void EditorSelection::update() {
@@ -937,12 +890,10 @@ void EditorSelection::update() {
if (!changed)
return;
emit_signal("selection_changed");
- changed=false;
-
-
+ changed = false;
}
-List<Node*>& EditorSelection::get_selected_node_list() {
+List<Node *> &EditorSelection::get_selected_node_list() {
if (changed)
update();
@@ -951,26 +902,20 @@ List<Node*>& EditorSelection::get_selected_node_list() {
return selected_node_list;
}
-
-
-
void EditorSelection::clear() {
- while( !selection.empty() ) {
+ while (!selection.empty()) {
remove_node(selection.front()->key());
}
-
- changed=true;
- nl_changed=true;
-
+ changed = true;
+ nl_changed = true;
}
EditorSelection::EditorSelection() {
- changed=false;
- nl_changed=false;
-
+ changed = false;
+ nl_changed = false;
}
EditorSelection::~EditorSelection() {
diff --git a/editor/editor_data.h b/editor/editor_data.h
index 4622791653..598cde2318 100644
--- a/editor/editor_data.h
+++ b/editor/editor_data.h
@@ -30,16 +30,16 @@
#define EDITOR_DATA_H
#include "editor/editor_plugin.h"
-#include "scene/resources/texture.h"
#include "list.h"
-#include "undo_redo.h"
#include "pair.h"
+#include "scene/resources/texture.h"
+#include "undo_redo.h"
class EditorHistory {
enum {
- HISTORY_MAX=64
+ HISTORY_MAX = 64
};
struct Obj {
@@ -54,7 +54,7 @@ class EditorHistory {
Vector<Obj> path;
int level;
};
-friend class EditorData;
+ friend class EditorData;
Vector<History> history;
int current;
@@ -67,19 +67,17 @@ friend class EditorData;
Variant value;
};
-
void _cleanup_history();
- void _add_object(ObjectID p_object,const String& p_property,int p_level_change);
+ void _add_object(ObjectID p_object, const String &p_property, int p_level_change);
public:
-
bool is_at_begining() const;
bool is_at_end() const;
void add_object(ObjectID p_object);
- void add_object(ObjectID p_object,const String& p_subprop);
- void add_object(ObjectID p_object,int p_relevel);
+ void add_object(ObjectID p_object, const String &p_subprop);
+ void add_object(ObjectID p_object, int p_relevel);
int get_history_len();
int get_history_pos();
@@ -109,54 +107,50 @@ public:
Ref<Script> script;
Ref<Texture> icon;
};
-private:
- Vector<EditorPlugin*> editor_plugins;
+private:
+ Vector<EditorPlugin *> editor_plugins;
struct PropertyData {
String name;
Variant value;
};
- Map<String,Vector<CustomType> > custom_types;
+ Map<String, Vector<CustomType> > custom_types;
List<PropertyData> clipboard;
UndoRedo undo_redo;
-
void _cleanup_history();
struct EditedScene {
- Node* root;
+ Node *root;
Dictionary editor_states;
- List<Node*> selection;
+ List<Node *> selection;
Vector<EditorHistory::History> history_stored;
int history_current;
Dictionary custom_state;
uint64_t version;
NodePath live_edit_root;
-
-
};
Vector<EditedScene> edited_scene;
int current_edited_scene;
- bool _find_updated_instances(Node* p_root,Node *p_node,Set<String> &checked_paths);
+ bool _find_updated_instances(Node *p_root, Node *p_node, Set<String> &checked_paths);
public:
-
- EditorPlugin* get_editor(Object *p_object);
- EditorPlugin* get_subeditor(Object *p_object);
- Vector<EditorPlugin*> get_subeditors(Object *p_object);
- EditorPlugin* get_editor(String p_name);
+ EditorPlugin *get_editor(Object *p_object);
+ EditorPlugin *get_subeditor(Object *p_object);
+ Vector<EditorPlugin *> get_subeditors(Object *p_object);
+ EditorPlugin *get_editor(String p_name);
void copy_object_params(Object *p_object);
void paste_object_params(Object *p_object);
Dictionary get_editor_states() const;
Dictionary get_scene_editor_states(int p_idx) const;
- void set_editor_states(const Dictionary& p_states);
+ void set_editor_states(const Dictionary &p_states);
void get_editor_breakpoints(List<String> *p_breakpoints);
void clear_editor_states();
void save_editor_external_data();
@@ -173,18 +167,17 @@ public:
void save_editor_global_states();
void restore_editor_global_states();
- void add_custom_type(const String& p_type, const String& p_inherits,const Ref<Script>& p_script,const Ref<Texture>& p_icon );
- void remove_custom_type(const String& p_type);
- const Map<String,Vector<CustomType> >& get_custom_types() const { return custom_types; }
-
+ void add_custom_type(const String &p_type, const String &p_inherits, const Ref<Script> &p_script, const Ref<Texture> &p_icon);
+ void remove_custom_type(const String &p_type);
+ const Map<String, Vector<CustomType> > &get_custom_types() const { return custom_types; }
int add_edited_scene(int p_at_pos);
- void move_edited_scene_index(int p_idx,int p_to_idx);
+ void move_edited_scene_index(int p_idx, int p_to_idx);
void remove_scene(int p_idx);
void set_edited_scene(int p_idx);
- void set_edited_scene_root(Node* p_root);
+ void set_edited_scene_root(Node *p_root);
int get_edited_scene() const;
- Node* get_edited_scene_root(int p_idx = -1);
+ Node *get_edited_scene_root(int p_idx = -1);
int get_edited_scene_count() const;
String get_scene_title(int p_idx) const;
String get_scene_path(int p_idx) const;
@@ -194,55 +187,50 @@ public:
uint64_t get_edited_scene_version() const;
uint64_t get_scene_version(int p_idx) const;
void clear_edited_scenes();
- void set_edited_scene_live_edit_root(const NodePath& p_root);
+ void set_edited_scene_live_edit_root(const NodePath &p_root);
NodePath get_edited_scene_live_edit_root();
bool check_and_update_scene(int p_idx);
void move_edited_scene_to_index(int p_idx);
-
void set_plugin_window_layout(Ref<ConfigFile> p_layout);
void get_plugin_window_layout(Ref<ConfigFile> p_layout);
- void save_edited_scene_state(EditorSelection *p_selection,EditorHistory *p_history,const Dictionary& p_custom);
+ void save_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history, const Dictionary &p_custom);
Dictionary restore_edited_scene_state(EditorSelection *p_selection, EditorHistory *p_history);
void notify_edited_scene_changed();
-
EditorData();
};
-
-
class EditorSelection : public Object {
- GDCLASS(EditorSelection,Object);
-public:
+ GDCLASS(EditorSelection, Object);
- Map<Node*,Object*> selection;
+public:
+ Map<Node *, Object *> selection;
bool changed;
bool nl_changed;
void _node_removed(Node *p_node);
- List<Object*> editor_plugins;
- List<Node*> selected_node_list;
+ List<Object *> editor_plugins;
+ List<Node *> selected_node_list;
void _update_nl();
Array _get_selected_nodes();
Array _get_transformable_selected_nodes();
protected:
-
static void _bind_methods();
-public:
+public:
void add_node(Node *p_node);
void remove_node(Node *p_node);
bool is_selected(Node *) const;
- template<class T>
- T* get_node_editor_data(Node *p_node) {
+ template <class T>
+ T *get_node_editor_data(Node *p_node) {
if (!selection.has(p_node))
return NULL;
Object *obj = selection[p_node];
@@ -256,14 +244,11 @@ public:
void update();
void clear();
-
- List<Node*>& get_selected_node_list();
- Map<Node*,Object*>& get_selection() { return selection; }
-
+ List<Node *> &get_selected_node_list();
+ Map<Node *, Object *> &get_selection() { return selection; }
EditorSelection();
~EditorSelection();
};
-
#endif // EDITOR_DATA_H
diff --git a/editor/editor_dir_dialog.cpp b/editor/editor_dir_dialog.cpp
index 235d1f06ba..5cd277e218 100644
--- a/editor/editor_dir_dialog.cpp
+++ b/editor/editor_dir_dialog.cpp
@@ -28,28 +28,27 @@
/*************************************************************************/
#include "editor_dir_dialog.h"
-#include "os/os.h"
-#include "os/keyboard.h"
-#include "editor/editor_settings.h"
#include "editor/editor_file_system.h"
+#include "editor/editor_settings.h"
+#include "os/keyboard.h"
+#include "os/os.h"
+void EditorDirDialog::_update_dir(TreeItem *p_item) {
-void EditorDirDialog::_update_dir(TreeItem* p_item) {
-
- updating=true;
+ updating = true;
p_item->clear_children();
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
String cdir = p_item->get_metadata(0);
da->change_dir(cdir);
da->list_dir_begin();
- String p=da->get_next();
+ String p = da->get_next();
List<String> dirs;
bool ishidden;
bool show_hidden = EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files");
- while(p!="") {
+ while (p != "") {
ishidden = da->current_is_hidden();
@@ -58,153 +57,144 @@ void EditorDirDialog::_update_dir(TreeItem* p_item) {
dirs.push_back(p);
}
}
- p=da->get_next();
+ p = da->get_next();
}
dirs.sort();
- for(List<String>::Element *E=dirs.front();E;E=E->next()) {
+ for (List<String>::Element *E = dirs.front(); E; E = E->next()) {
TreeItem *ti = tree->create_item(p_item);
- ti->set_text(0,E->get());
- ti->set_icon(0,get_icon("Folder","EditorIcons"));
+ ti->set_text(0, E->get());
+ ti->set_icon(0, get_icon("Folder", "EditorIcons"));
ti->set_collapsed(true);
-
}
memdelete(da);
- updating=false;
-
+ updating = false;
}
-
void EditorDirDialog::reload() {
if (!is_visible_in_tree()) {
- must_reload=true;
+ must_reload = true;
return;
}
tree->clear();
TreeItem *root = tree->create_item();
- root->set_metadata(0,"res://");
- root->set_icon(0,get_icon("Folder","EditorIcons"));
- root->set_text(0,"/");
+ root->set_metadata(0, "res://");
+ root->set_icon(0, get_icon("Folder", "EditorIcons"));
+ root->set_text(0, "/");
_update_dir(root);
_item_collapsed(root);
- must_reload=false;
-
+ must_reload = false;
}
-
void EditorDirDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
reload();
- if (!tree->is_connected("item_collapsed",this,"_item_collapsed")) {
- tree->connect("item_collapsed",this,"_item_collapsed",varray(),CONNECT_DEFERRED);
+ if (!tree->is_connected("item_collapsed", this, "_item_collapsed")) {
+ tree->connect("item_collapsed", this, "_item_collapsed", varray(), CONNECT_DEFERRED);
}
- if (!EditorFileSystem::get_singleton()->is_connected("filesystem_changed",this,"reload")) {
- EditorFileSystem::get_singleton()->connect("filesystem_changed",this,"reload");
+ if (!EditorFileSystem::get_singleton()->is_connected("filesystem_changed", this, "reload")) {
+ EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "reload");
}
-
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (must_reload && is_visible_in_tree()) {
reload();
}
}
}
-void EditorDirDialog::_item_collapsed(Object* _p_item){
+void EditorDirDialog::_item_collapsed(Object *_p_item) {
- TreeItem *p_item=_p_item->cast_to<TreeItem>();
+ TreeItem *p_item = _p_item->cast_to<TreeItem>();
if (updating || p_item->is_collapsed())
return;
TreeItem *ci = p_item->get_children();
- while(ci) {
+ while (ci) {
- String p =ci->get_metadata(0);
- if (p=="") {
+ String p = ci->get_metadata(0);
+ if (p == "") {
String pp = p_item->get_metadata(0);
- ci->set_metadata(0,pp.plus_file(ci->get_text(0)));
+ ci->set_metadata(0, pp.plus_file(ci->get_text(0)));
_update_dir(ci);
}
- ci=ci->get_next();
+ ci = ci->get_next();
}
-
}
-void EditorDirDialog::set_current_path(const String& p_path) {
+void EditorDirDialog::set_current_path(const String &p_path) {
reload();
String p = p_path;
if (p.begins_with("res://"))
- p = p.replace_first("res://","");
+ p = p.replace_first("res://", "");
- Vector<String> dirs = p.split("/",false);
+ Vector<String> dirs = p.split("/", false);
- TreeItem *r=tree->get_root();
- for(int i=0;i<dirs.size();i++) {
+ TreeItem *r = tree->get_root();
+ for (int i = 0; i < dirs.size(); i++) {
String d = dirs[i];
TreeItem *p = r->get_children();
- while(p) {
+ while (p) {
- if (p->get_text(0)==d)
+ if (p->get_text(0) == d)
break;
- p=p->get_next();
+ p = p->get_next();
}
ERR_FAIL_COND(!p);
String pp = p->get_metadata(0);
- if (pp=="") {
- p->set_metadata(0,String(r->get_metadata(0)).plus_file(d));
+ if (pp == "") {
+ p->set_metadata(0, String(r->get_metadata(0)).plus_file(d));
_update_dir(p);
}
- updating=true;
+ updating = true;
p->set_collapsed(false);
- updating=false;
+ updating = false;
_item_collapsed(p);
- r=p;
+ r = p;
}
r->select(0);
-
}
void EditorDirDialog::ok_pressed() {
- TreeItem *ti=tree->get_selected();
+ TreeItem *ti = tree->get_selected();
if (!ti)
return;
String dir = ti->get_metadata(0);
- emit_signal("dir_selected",dir);
+ emit_signal("dir_selected", dir);
hide();
}
-
void EditorDirDialog::_make_dir() {
- TreeItem *ti=tree->get_selected();
+ TreeItem *ti = tree->get_selected();
if (!ti) {
mkdirerr->set_text("Please select a base directory first");
mkdirerr->popup_centered_minsize();
return;
}
- makedialog->popup_centered_minsize(Size2(250,80));
+ makedialog->popup_centered_minsize(Size2(250, 80));
makedirname->grab_focus();
}
void EditorDirDialog::_make_dir_confirm() {
- TreeItem *ti=tree->get_selected();
+ TreeItem *ti = tree->get_selected();
if (!ti)
return;
@@ -214,63 +204,57 @@ void EditorDirDialog::_make_dir_confirm() {
ERR_FAIL_COND(!d);
Error err = d->make_dir(makedirname->get_text());
- if (err!=OK) {
- mkdirerr->popup_centered_minsize(Size2(250,80));
+ if (err != OK) {
+ mkdirerr->popup_centered_minsize(Size2(250, 80));
} else {
set_current_path(dir.plus_file(makedirname->get_text()));
}
makedirname->set_text(""); // reset label
}
-
void EditorDirDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_item_collapsed"),&EditorDirDialog::_item_collapsed);
- ClassDB::bind_method(D_METHOD("_make_dir"),&EditorDirDialog::_make_dir);
- ClassDB::bind_method(D_METHOD("_make_dir_confirm"),&EditorDirDialog::_make_dir_confirm);
- ClassDB::bind_method(D_METHOD("reload"),&EditorDirDialog::reload);
+ ClassDB::bind_method(D_METHOD("_item_collapsed"), &EditorDirDialog::_item_collapsed);
+ ClassDB::bind_method(D_METHOD("_make_dir"), &EditorDirDialog::_make_dir);
+ ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &EditorDirDialog::_make_dir_confirm);
+ ClassDB::bind_method(D_METHOD("reload"), &EditorDirDialog::reload);
- ADD_SIGNAL(MethodInfo("dir_selected",PropertyInfo(Variant::STRING,"dir")));
+ ADD_SIGNAL(MethodInfo("dir_selected", PropertyInfo(Variant::STRING, "dir")));
}
-
-
EditorDirDialog::EditorDirDialog() {
- updating=false;
+ updating = false;
set_title(TTR("Choose a Directory"));
set_hide_on_ok(false);
- tree = memnew( Tree );
+ tree = memnew(Tree);
add_child(tree);
- tree->connect("item_activated",this,"_ok");
+ tree->connect("item_activated", this, "_ok");
- makedir = add_button(TTR("Create Folder"),OS::get_singleton()->get_swap_ok_cancel()?true:false,"makedir");
- makedir->connect("pressed",this,"_make_dir");
+ makedir = add_button(TTR("Create Folder"), OS::get_singleton()->get_swap_ok_cancel() ? true : false, "makedir");
+ makedir->connect("pressed", this, "_make_dir");
- makedialog = memnew( ConfirmationDialog );
+ makedialog = memnew(ConfirmationDialog);
makedialog->set_title(TTR("Create Folder"));
add_child(makedialog);
- VBoxContainer *makevb= memnew( VBoxContainer );
+ VBoxContainer *makevb = memnew(VBoxContainer);
makedialog->add_child(makevb);
//makedialog->set_child_rect(makevb);
- makedirname = memnew( LineEdit );
- makevb->add_margin_child(TTR("Name:"),makedirname);
+ makedirname = memnew(LineEdit);
+ makevb->add_margin_child(TTR("Name:"), makedirname);
makedialog->register_text_enter(makedirname);
- makedialog->connect("confirmed",this,"_make_dir_confirm");
+ makedialog->connect("confirmed", this, "_make_dir_confirm");
- mkdirerr = memnew( AcceptDialog );
+ mkdirerr = memnew(AcceptDialog);
mkdirerr->set_text(TTR("Could not create folder."));
add_child(mkdirerr);
get_ok()->set_text(TTR("Choose"));
- must_reload=false;
-
-
-
+ must_reload = false;
}
diff --git a/editor/editor_dir_dialog.h b/editor/editor_dir_dialog.h
index 0577ff0442..2f2385e971 100644
--- a/editor/editor_dir_dialog.h
+++ b/editor/editor_dir_dialog.h
@@ -34,8 +34,7 @@
#include "scene/gui/tree.h"
class EditorDirDialog : public ConfirmationDialog {
- GDCLASS(EditorDirDialog,ConfirmationDialog);
-
+ GDCLASS(EditorDirDialog, ConfirmationDialog);
ConfirmationDialog *makedialog;
LineEdit *makedirname;
@@ -46,8 +45,8 @@ class EditorDirDialog : public ConfirmationDialog {
Tree *tree;
bool updating;
- void _item_collapsed(Object* p_item);
- void _update_dir(TreeItem* p_item);
+ void _item_collapsed(Object *p_item);
+ void _update_dir(TreeItem *p_item);
void _make_dir();
void _make_dir_confirm();
@@ -56,14 +55,12 @@ class EditorDirDialog : public ConfirmationDialog {
bool must_reload;
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_current_path(const String& p_path);
+public:
+ void set_current_path(const String &p_path);
void reload();
EditorDirDialog();
};
diff --git a/editor/editor_export.cpp b/editor/editor_export.cpp
index f5840d00fb..7ac299974c 100644
--- a/editor/editor_export.cpp
+++ b/editor/editor_export.cpp
@@ -27,20 +27,20 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "editor_export.h"
-#include "version.h"
-#include "script_language.h"
-#include "global_config.h"
-#include "os/file_access.h"
-#include "os/dir_access.h"
#include "editor/editor_file_system.h"
-#include "io/resource_loader.h"
+#include "editor/plugins/script_editor_plugin.h"
#include "editor_node.h"
#include "editor_settings.h"
+#include "global_config.h"
#include "io/config_file.h"
-#include "io/resource_saver.h"
#include "io/md5.h"
-#include "editor/plugins/script_editor_plugin.h"
+#include "io/resource_loader.h"
+#include "io/resource_saver.h"
#include "io/zip_io.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
+#include "script_language.h"
+#include "version.h"
static int _get_pad(int p_alignment, int p_n) {
@@ -55,10 +55,10 @@ static int _get_pad(int p_alignment, int p_n) {
#define PCK_PADDING 16
-bool EditorExportPreset::_set(const StringName& p_name, const Variant& p_value) {
+bool EditorExportPreset::_set(const StringName &p_name, const Variant &p_value) {
- if (values.has(p_name)) {
- values[p_name]=p_value;
+ if (values.has(p_name)) {
+ values[p_name] = p_value;
EditorExport::singleton->save_presets();
return true;
}
@@ -66,18 +66,18 @@ bool EditorExportPreset::_set(const StringName& p_name, const Variant& p_value)
return false;
}
-bool EditorExportPreset::_get(const StringName& p_name,Variant &r_ret) const{
+bool EditorExportPreset::_get(const StringName &p_name, Variant &r_ret) const {
if (values.has(p_name)) {
- r_ret=values[p_name];
+ r_ret = values[p_name];
return true;
}
return false;
}
-void EditorExportPreset::_get_property_list( List<PropertyInfo> *p_list) const{
+void EditorExportPreset::_get_property_list(List<PropertyInfo> *p_list) const {
- for (const List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
+ for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
@@ -91,26 +91,24 @@ Ref<EditorExportPlatform> EditorExportPreset::get_platform() const {
Vector<String> EditorExportPreset::get_files_to_export() const {
Vector<String> files;
- for(Set<String>::Element *E=selected_files.front();E;E=E->next()) {
+ for (Set<String>::Element *E = selected_files.front(); E; E = E->next()) {
files.push_back(E->get());
}
return files;
}
-void EditorExportPreset::set_name(const String& p_name) {
- name=p_name;
+void EditorExportPreset::set_name(const String &p_name) {
+ name = p_name;
EditorExport::singleton->save_presets();
-
}
String EditorExportPreset::get_name() const {
return name;
-
}
void EditorExportPreset::set_runnable(bool p_enable) {
- runnable=p_enable;
+ runnable = p_enable;
EditorExport::singleton->save_presets();
}
@@ -121,20 +119,18 @@ bool EditorExportPreset::is_runnable() const {
void EditorExportPreset::set_export_filter(ExportFilter p_filter) {
- export_filter=p_filter;
+ export_filter = p_filter;
EditorExport::singleton->save_presets();
-
}
EditorExportPreset::ExportFilter EditorExportPreset::get_export_filter() const {
return export_filter;
}
-void EditorExportPreset::set_include_filter(const String& p_include) {
+void EditorExportPreset::set_include_filter(const String &p_include) {
- include_filter=p_include;
+ include_filter = p_include;
EditorExport::singleton->save_presets();
-
}
String EditorExportPreset::get_include_filter() const {
@@ -142,9 +138,9 @@ String EditorExportPreset::get_include_filter() const {
return include_filter;
}
-void EditorExportPreset::set_exclude_filter(const String& p_exclude) {
+void EditorExportPreset::set_exclude_filter(const String &p_exclude) {
- exclude_filter=p_exclude;
+ exclude_filter = p_exclude;
EditorExport::singleton->save_presets();
}
@@ -153,28 +149,28 @@ String EditorExportPreset::get_exclude_filter() const {
return exclude_filter;
}
-void EditorExportPreset::add_export_file(const String& p_path) {
+void EditorExportPreset::add_export_file(const String &p_path) {
selected_files.insert(p_path);
EditorExport::singleton->save_presets();
}
-void EditorExportPreset::remove_export_file(const String& p_path) {
+void EditorExportPreset::remove_export_file(const String &p_path) {
selected_files.erase(p_path);
EditorExport::singleton->save_presets();
}
-bool EditorExportPreset::has_export_file(const String& p_path) {
+bool EditorExportPreset::has_export_file(const String &p_path) {
return selected_files.has(p_path);
}
-void EditorExportPreset::add_patch(const String& p_path,int p_at_pos) {
+void EditorExportPreset::add_patch(const String &p_path, int p_at_pos) {
- if (p_at_pos<0)
+ if (p_at_pos < 0)
patches.push_back(p_path);
else
- patches.insert(p_at_pos,p_path);
+ patches.insert(p_at_pos, p_path);
EditorExport::singleton->save_presets();
}
@@ -183,14 +179,14 @@ void EditorExportPreset::remove_patch(int p_idx) {
EditorExport::singleton->save_presets();
}
-void EditorExportPreset::set_patch(int p_index,const String& p_path) {
- ERR_FAIL_INDEX(p_index,patches.size());
- patches[p_index]=p_path;
+void EditorExportPreset::set_patch(int p_index, const String &p_path) {
+ ERR_FAIL_INDEX(p_index, patches.size());
+ patches[p_index] = p_path;
EditorExport::singleton->save_presets();
}
String EditorExportPreset::get_patch(int p_index) {
- ERR_FAIL_INDEX_V(p_index,patches.size(),String());
+ ERR_FAIL_INDEX_V(p_index, patches.size(), String());
return patches[p_index];
}
@@ -200,136 +196,131 @@ Vector<String> EditorExportPreset::get_patches() const {
EditorExportPreset::EditorExportPreset() {
- export_filter=EXPORT_ALL_RESOURCES;
- runnable=false;
+ export_filter = EXPORT_ALL_RESOURCES;
+ runnable = false;
}
-
///////////////////////////////////
void EditorExportPlatform::gen_debug_flags(Vector<String> &r_flags, int p_flags) {
String host = EditorSettings::get_singleton()->get("network/debug_host");
- if (p_flags&DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST)
- host="localhost";
+ if (p_flags & DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST)
+ host = "localhost";
- if (p_flags&DEBUG_FLAG_DUMB_CLIENT) {
+ if (p_flags & DEBUG_FLAG_DUMB_CLIENT) {
int port = EditorSettings::get_singleton()->get("filesystem/file_server/port");
String passwd = EditorSettings::get_singleton()->get("filesystem/file_server/password");
r_flags.push_back("-rfs");
- r_flags.push_back(host+":"+itos(port));
- if (passwd!="") {
+ r_flags.push_back(host + ":" + itos(port));
+ if (passwd != "") {
r_flags.push_back("-rfs_pass");
r_flags.push_back(passwd);
}
}
- if (p_flags&DEBUG_FLAG_REMOTE_DEBUG) {
+ if (p_flags & DEBUG_FLAG_REMOTE_DEBUG) {
r_flags.push_back("-rdebug");
- r_flags.push_back(host+":"+String::num(GLOBAL_DEF("network/debug/remote_port", 6007)));
+ r_flags.push_back(host + ":" + String::num(GLOBAL_DEF("network/debug/remote_port", 6007)));
List<String> breakpoints;
ScriptEditor::get_singleton()->get_breakpoints(&breakpoints);
-
if (breakpoints.size()) {
r_flags.push_back("-bp");
String bpoints;
- for(const List<String>::Element *E=breakpoints.front();E;E=E->next()) {
+ for (const List<String>::Element *E = breakpoints.front(); E; E = E->next()) {
- bpoints+=E->get().replace(" ","%20");
+ bpoints += E->get().replace(" ", "%20");
if (E->next())
- bpoints+=",";
+ bpoints += ",";
}
r_flags.push_back(bpoints);
}
-
}
- if (p_flags&DEBUG_FLAG_VIEW_COLLISONS) {
+ if (p_flags & DEBUG_FLAG_VIEW_COLLISONS) {
r_flags.push_back("-debugcol");
}
- if (p_flags&DEBUG_FLAG_VIEW_NAVIGATION) {
+ if (p_flags & DEBUG_FLAG_VIEW_NAVIGATION) {
r_flags.push_back("-debugnav");
}
}
-Error EditorExportPlatform::_save_pack_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total) {
+Error EditorExportPlatform::_save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
- PackData *pd = (PackData*)p_userdata;
+ PackData *pd = (PackData *)p_userdata;
SavedData sd;
- sd.path_utf8=p_path.utf8();
+ sd.path_utf8 = p_path.utf8();
sd.ofs = pd->f->get_pos();
sd.size = p_data.size();
- pd->f->store_buffer(p_data.ptr(),p_data.size());
- int pad = _get_pad(PCK_PADDING,sd.size);
- for(int i=0;i<pad;i++) {
+ pd->f->store_buffer(p_data.ptr(), p_data.size());
+ int pad = _get_pad(PCK_PADDING, sd.size);
+ for (int i = 0; i < pad; i++) {
pd->f->store_8(0);
}
{
MD5_CTX ctx;
MD5Init(&ctx);
- MD5Update(&ctx,(unsigned char*)p_data.ptr(),p_data.size());
+ MD5Update(&ctx, (unsigned char *)p_data.ptr(), p_data.size());
MD5Final(&ctx);
sd.md5.resize(16);
- for(int i=0;i<16;i++) {
- sd.md5[i]=ctx.digest[i];
+ for (int i = 0; i < 16; i++) {
+ sd.md5[i] = ctx.digest[i];
}
}
pd->file_ofs.push_back(sd);
- pd->ep->step(TTR("Storing File:")+" "+p_path,2+p_file*100/p_total,false);
+ pd->ep->step(TTR("Storing File:") + " " + p_path, 2 + p_file * 100 / p_total, false);
return OK;
}
-Error EditorExportPlatform::_save_zip_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total) {
-
+Error EditorExportPlatform::_save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total) {
- String path=p_path.replace_first("res://","");
+ String path = p_path.replace_first("res://", "");
- ZipData *zd = (ZipData*)p_userdata;
+ ZipData *zd = (ZipData *)p_userdata;
- zipFile zip=(zipFile)zd->zip;
+ zipFile zip = (zipFile)zd->zip;
zipOpenNewFileInZip(zip,
- path.utf8().get_data(),
- NULL,
- NULL,
- 0,
- NULL,
- 0,
- NULL,
- Z_DEFLATED,
- Z_DEFAULT_COMPRESSION);
-
- zipWriteInFileInZip(zip,p_data.ptr(),p_data.size());
+ path.utf8().get_data(),
+ NULL,
+ NULL,
+ 0,
+ NULL,
+ 0,
+ NULL,
+ Z_DEFLATED,
+ Z_DEFAULT_COMPRESSION);
+
+ zipWriteInFileInZip(zip, p_data.ptr(), p_data.size());
zipCloseFileInZip(zip);
- zd->ep->step(TTR("Storing File:")+" "+p_path,2+p_file*100/p_total,false);
+ zd->ep->step(TTR("Storing File:") + " " + p_path, 2 + p_file * 100 / p_total, false);
return OK;
}
String EditorExportPlatform::find_export_template(String template_file_name, String *err) const {
- String user_file = EditorSettings::get_singleton()->get_settings_path()
- +"/templates/"+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"."+_MKSTR(VERSION_STATUS)+"/"+template_file_name;
- String system_file=OS::get_singleton()->get_installed_templates_path();
- bool has_system_path=(system_file!="");
- system_file+=template_file_name;
+ String user_file = EditorSettings::get_singleton()->get_settings_path() + "/templates/" + itos(VERSION_MAJOR) + "." + itos(VERSION_MINOR) + "." + _MKSTR(VERSION_STATUS) + "/" + template_file_name;
+ String system_file = OS::get_singleton()->get_installed_templates_path();
+ bool has_system_path = (system_file != "");
+ system_file += template_file_name;
// Prefer user file
if (FileAccess::exists(user_file)) {
@@ -345,11 +336,11 @@ String EditorExportPlatform::find_export_template(String template_file_name, Str
// Not found
if (err) {
- *err+="No export template found at \""+user_file+"\"";
+ *err += "No export template found at \"" + user_file + "\"";
if (has_system_path)
- *err+="\n or \""+system_file+"\".";
+ *err += "\n or \"" + system_file + "\".";
else
- *err+=".";
+ *err += ".";
}
return "";
}
@@ -358,34 +349,32 @@ Ref<EditorExportPreset> EditorExportPlatform::create_preset() {
Ref<EditorExportPreset> preset;
preset.instance();
- preset->platform=Ref<EditorExportPlatform>(this);
+ preset->platform = Ref<EditorExportPlatform>(this);
List<ExportOption> options;
get_export_options(&options);
- for (List<ExportOption>::Element *E=options.front();E;E=E->next()) {
+ for (List<ExportOption>::Element *E = options.front(); E; E = E->next()) {
preset->properties.push_back(E->get().option);
- preset->values[E->get().option.name]=E->get().default_value;
+ preset->values[E->get().option.name] = E->get().default_value;
}
return preset;
-
}
-void EditorExportPlatform::_export_find_resources(EditorFileSystemDirectory *p_dir,Set<String>& p_paths) {
+void EditorExportPlatform::_export_find_resources(EditorFileSystemDirectory *p_dir, Set<String> &p_paths) {
- for(int i=0;i<p_dir->get_subdir_count();i++) {
- _export_find_resources(p_dir->get_subdir(i),p_paths);
+ for (int i = 0; i < p_dir->get_subdir_count(); i++) {
+ _export_find_resources(p_dir->get_subdir(i), p_paths);
}
- for(int i=0;i<p_dir->get_file_count();i++) {
+ for (int i = 0; i < p_dir->get_file_count(); i++) {
p_paths.insert(p_dir->get_file_path(i));
}
}
-
-void EditorExportPlatform::_export_find_dependencies(const String& p_path,Set<String>& p_paths) {
+void EditorExportPlatform::_export_find_dependencies(const String &p_path, Set<String> &p_paths) {
if (p_paths.has(p_path))
return;
@@ -394,94 +383,93 @@ void EditorExportPlatform::_export_find_dependencies(const String& p_path,Set<St
EditorFileSystemDirectory *dir;
int file_idx;
- dir = EditorFileSystem::get_singleton()->find_file(p_path,&file_idx);
+ dir = EditorFileSystem::get_singleton()->find_file(p_path, &file_idx);
if (!dir)
return;
Vector<String> deps = dir->get_file_deps(file_idx);
- for(int i=0;i<deps.size();i++) {
+ for (int i = 0; i < deps.size(); i++) {
- _export_find_dependencies(deps[i],p_paths);
+ _export_find_dependencies(deps[i], p_paths);
}
}
-
-Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset>& p_preset,EditorExportSaveFunction p_func, void* p_udata) {
+Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset> &p_preset, EditorExportSaveFunction p_func, void *p_udata) {
Ref<EditorExportPlatform> platform = p_preset->get_platform();
List<String> feature_list;
- platform->get_preset_features(p_preset,&feature_list);
+ platform->get_preset_features(p_preset, &feature_list);
//figure out features
Set<String> features;
- for (List<String>::Element *E=feature_list.front();E;E=E->next()) {
+ for (List<String>::Element *E = feature_list.front(); E; E = E->next()) {
features.insert(E->get());
}
//figure out paths of files that will be exported
Set<String> paths;
- if (p_preset->get_export_filter()==EditorExportPreset::EXPORT_ALL_RESOURCES) {
+ if (p_preset->get_export_filter() == EditorExportPreset::EXPORT_ALL_RESOURCES) {
//find stuff
- _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(),paths);
+ _export_find_resources(EditorFileSystem::get_singleton()->get_filesystem(), paths);
} else {
- bool scenes_only = p_preset->get_export_filter()==EditorExportPreset::EXPORT_SELECTED_SCENES;
+ bool scenes_only = p_preset->get_export_filter() == EditorExportPreset::EXPORT_SELECTED_SCENES;
Vector<String> files = p_preset->get_files_to_export();
- for(int i=0;i<files.size();i++) {
- if (scenes_only && ResourceLoader::get_resource_type(files[i])!="PackedScene")
+ for (int i = 0; i < files.size(); i++) {
+ if (scenes_only && ResourceLoader::get_resource_type(files[i]) != "PackedScene")
continue;
- _export_find_dependencies(files[i],paths);
+ _export_find_dependencies(files[i], paths);
}
}
//store everything in the export medium
int idx = 0;
- int total=paths.size();
+ int total = paths.size();
- for(Set<String>::Element *E=paths.front();E;E=E->next()) {
+ for (Set<String>::Element *E = paths.front(); E; E = E->next()) {
String path = E->get();
- if (FileAccess::exists(path+".import")) {
+ if (FileAccess::exists(path + ".import")) {
//file is imported, replace by what it imports
Ref<ConfigFile> config;
config.instance();
- Error err = config->load(path+".import");
- if (err!=OK) {
- ERR_PRINTS("Could not parse: '"+path+"', not exported.");
+ Error err = config->load(path + ".import");
+ if (err != OK) {
+ ERR_PRINTS("Could not parse: '" + path + "', not exported.");
continue;
}
List<String> remaps;
- config->get_section_keys("remap",&remaps);
+ config->get_section_keys("remap", &remaps);
- for(List<String>::Element *F=remaps.front();F;F=F->next()) {
+ for (List<String>::Element *F = remaps.front(); F; F = F->next()) {
- String remap=F->get();
- if (remap=="path") {
- String remapped_path=config->get_value("remap",remap);
+ String remap = F->get();
+ if (remap == "path") {
+ String remapped_path = config->get_value("remap", remap);
Vector<uint8_t> array = FileAccess::get_file_as_array(remapped_path);
- p_func(p_udata,remapped_path,array,idx,total);
+ p_func(p_udata, remapped_path, array, idx, total);
} else if (remap.begins_with("path.")) {
- String feature = remap.get_slice(".",1);
+ String feature = remap.get_slice(".", 1);
if (features.has(feature)) {
- String remapped_path=config->get_value("remap",remap);
+ String remapped_path = config->get_value("remap", remap);
Vector<uint8_t> array = FileAccess::get_file_as_array(remapped_path);
- p_func(p_udata,remapped_path,array,idx,total);
+ p_func(p_udata, remapped_path, array, idx, total);
}
}
}
//also save the .import file
- Vector<uint8_t> array = FileAccess::get_file_as_array(path+".import");
- p_func(p_udata,path+".import",array,idx,total);
+ Vector<uint8_t> array = FileAccess::get_file_as_array(path + ".import");
+ p_func(p_udata, path + ".import", array, idx, total);
} else {
//just store it as it comes
Vector<uint8_t> array = FileAccess::get_file_as_array(path);
- p_func(p_udata,path,array,idx,total);
+ p_func(p_udata, path, array, idx, total);
}
idx++;
@@ -489,29 +477,29 @@ Error EditorExportPlatform::export_project_files(const Ref<EditorExportPreset>&
//save config!
- String config_file="godot.cfb";
- String engine_cfb =EditorSettings::get_singleton()->get_settings_path()+"/tmp/tmp"+config_file;
+ String config_file = "godot.cfb";
+ String engine_cfb = EditorSettings::get_singleton()->get_settings_path() + "/tmp/tmp" + config_file;
GlobalConfig::get_singleton()->save_custom(engine_cfb);
Vector<uint8_t> data = FileAccess::get_file_as_array(engine_cfb);
- p_func(p_udata,"res://"+config_file,data,idx,total);
+ p_func(p_udata, "res://" + config_file, data, idx, total);
return OK;
}
-Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset>& p_preset,const String& p_path) {
+Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
- EditorProgress ep("savepack",TTR("Packing"),102);
+ EditorProgress ep("savepack", TTR("Packing"), 102);
- String tmppath = EditorSettings::get_singleton()->get_settings_path()+"/tmp/packtmp";
- FileAccess *ftmp = FileAccess::open(tmppath,FileAccess::WRITE);
- ERR_FAIL_COND_V(!ftmp,ERR_CANT_CREATE)
+ String tmppath = EditorSettings::get_singleton()->get_settings_path() + "/tmp/packtmp";
+ FileAccess *ftmp = FileAccess::open(tmppath, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!ftmp, ERR_CANT_CREATE)
PackData pd;
- pd.ep=&ep;
- pd.f=ftmp;
+ pd.ep = &ep;
+ pd.f = ftmp;
- Error err = export_project_files(p_preset,_save_pack_file,&pd);
+ Error err = export_project_files(p_preset, _save_pack_file, &pd);
memdelete(ftmp); //close tmp file
@@ -520,15 +508,14 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset>& p_preset,co
pd.file_ofs.sort(); //do sort, so we can do binary search later
-
- FileAccess *f = FileAccess::open(p_path,FileAccess::WRITE);
- ERR_FAIL_COND_V(!f,ERR_CANT_CREATE)
+ FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
+ ERR_FAIL_COND_V(!f, ERR_CANT_CREATE)
f->store_32(0x43504447); //GDPK
f->store_32(1); //pack version
f->store_32(VERSION_MAJOR);
f->store_32(VERSION_MINOR);
f->store_32(0); //hmph
- for(int i=0;i<16;i++) {
+ for (int i = 0; i < 16; i++) {
//reserved
f->store_32(0);
}
@@ -539,55 +526,54 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset>& p_preset,co
//precalculate header size
- for(int i=0;i<pd.file_ofs.size();i++) {
+ for (int i = 0; i < pd.file_ofs.size(); i++) {
header_size += 4; // size of path string (32 bits is enough)
uint32_t string_len = pd.file_ofs[i].path_utf8.length();
- header_size += string_len + _get_pad(4,string_len); ///size of path string
+ header_size += string_len + _get_pad(4, string_len); ///size of path string
header_size += 8; // offset to file _with_ header size included
header_size += 8; // size of file
- header_size +=16; // md5
-
+ header_size += 16; // md5
}
- size_t header_padding = _get_pad(PCK_PADDING,header_size);
+ size_t header_padding = _get_pad(PCK_PADDING, header_size);
-
- for(int i=0;i<pd.file_ofs.size();i++) {
+ for (int i = 0; i < pd.file_ofs.size(); i++) {
uint32_t string_len = pd.file_ofs[i].path_utf8.length();
- uint32_t pad = _get_pad(4,string_len);;
- f->store_32(string_len+pad);
- f->store_buffer((const uint8_t*)pd.file_ofs[i].path_utf8.get_data(),string_len);
- for(uint32_t j=0;j<pad;j++) {
+ uint32_t pad = _get_pad(4, string_len);
+ ;
+ f->store_32(string_len + pad);
+ f->store_buffer((const uint8_t *)pd.file_ofs[i].path_utf8.get_data(), string_len);
+ for (uint32_t j = 0; j < pad; j++) {
f->store_8(0);
}
f->store_64(pd.file_ofs[i].ofs + header_padding + header_size);
f->store_64(pd.file_ofs[i].size); // pay attention here, this is where file is
- f->store_buffer(pd.file_ofs[i].md5.ptr(),16); //also save md5 for file
+ f->store_buffer(pd.file_ofs[i].md5.ptr(), 16); //also save md5 for file
}
- for(uint32_t j=0;j<header_padding;j++) {
+ for (uint32_t j = 0; j < header_padding; j++) {
f->store_8(0);
}
//save the rest of the data
- ftmp = FileAccess::open(tmppath,FileAccess::READ);
+ ftmp = FileAccess::open(tmppath, FileAccess::READ);
if (!ftmp) {
memdelete(f);
- ERR_FAIL_COND_V(!ftmp,ERR_CANT_CREATE)
+ ERR_FAIL_COND_V(!ftmp, ERR_CANT_CREATE)
}
- const int bufsize=16384;
+ const int bufsize = 16384;
uint8_t buf[bufsize];
- while(true) {
+ while (true) {
- int got = ftmp->get_buffer(buf,bufsize);
- if (got<=0)
+ int got = ftmp->get_buffer(buf, bufsize);
+ if (got <= 0)
break;
- f->store_buffer(buf,got);
+ f->store_buffer(buf, got);
}
memdelete(ftmp);
@@ -598,91 +584,81 @@ Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset>& p_preset,co
return OK;
}
-Error EditorExportPlatform::save_zip(const Ref<EditorExportPreset>& p_preset,const String& p_path) {
+Error EditorExportPlatform::save_zip(const Ref<EditorExportPreset> &p_preset, const String &p_path) {
- EditorProgress ep("savezip",TTR("Packing"),102);
+ EditorProgress ep("savezip", TTR("Packing"), 102);
//FileAccess *tmp = FileAccess::open(tmppath,FileAccess::WRITE);
FileAccess *src_f;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
- zipFile zip=zipOpen2(p_path.utf8().get_data(),APPEND_STATUS_CREATE,NULL,&io);
+ zipFile zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io);
ZipData zd;
- zd.ep=&ep;
- zd.zip=zip;
-
+ zd.ep = &ep;
+ zd.zip = zip;
- Error err = export_project_files(p_preset,_save_zip_file,&zd);
+ Error err = export_project_files(p_preset, _save_zip_file, &zd);
- zipClose(zip,NULL);
+ zipClose(zip, NULL);
return OK;
}
EditorExportPlatform::EditorExportPlatform() {
-
-
}
-
////
-EditorExport *EditorExport::singleton=NULL;
-
+EditorExport *EditorExport::singleton = NULL;
void EditorExport::_save() {
-
Ref<ConfigFile> config;
config.instance();
- for(int i=0;i<export_presets.size();i++) {
+ for (int i = 0; i < export_presets.size(); i++) {
Ref<EditorExportPreset> preset = export_presets[i];
- String section="preset."+itos(i);
+ String section = "preset." + itos(i);
- config->set_value(section,"name",preset->get_name());
- config->set_value(section,"platform",preset->get_platform()->get_name());
- config->set_value(section,"runnable",preset->is_runnable());
- bool save_files=false;
- switch(preset->get_export_filter()) {
+ config->set_value(section, "name", preset->get_name());
+ config->set_value(section, "platform", preset->get_platform()->get_name());
+ config->set_value(section, "runnable", preset->is_runnable());
+ bool save_files = false;
+ switch (preset->get_export_filter()) {
case EditorExportPreset::EXPORT_ALL_RESOURCES: {
- config->set_value(section,"export_filter","all_resources");
+ config->set_value(section, "export_filter", "all_resources");
} break;
case EditorExportPreset::EXPORT_SELECTED_SCENES: {
- config->set_value(section,"export_filter","scenes");
- save_files=true;
+ config->set_value(section, "export_filter", "scenes");
+ save_files = true;
} break;
case EditorExportPreset::EXPORT_SELECTED_RESOURCES: {
- config->set_value(section,"export_filter","resources");
- save_files=true;
+ config->set_value(section, "export_filter", "resources");
+ save_files = true;
} break;
-
-
}
if (save_files) {
Vector<String> export_files = preset->get_files_to_export();
- config->set_value(section,"export_files",export_files);
+ config->set_value(section, "export_files", export_files);
}
- config->set_value(section,"include_filter",preset->get_include_filter());
- config->set_value(section,"exclude_filter",preset->get_exclude_filter());
- config->set_value(section,"patch_list",preset->get_patches());
+ config->set_value(section, "include_filter", preset->get_include_filter());
+ config->set_value(section, "exclude_filter", preset->get_exclude_filter());
+ config->set_value(section, "patch_list", preset->get_patches());
- String option_section="preset."+itos(i)+".options";
+ String option_section = "preset." + itos(i) + ".options";
- for (const List<PropertyInfo>::Element *E=preset->get_properties().front();E;E=E->next()) {
- config->set_value(option_section,E->get().name,preset->get(E->get().name));
+ for (const List<PropertyInfo>::Element *E = preset->get_properties().front(); E; E = E->next()) {
+ config->set_value(option_section, E->get().name, preset->get(E->get().name));
}
}
config->save("res://export_presets.cfg");
print_line("saved ok");
-
}
-
void EditorExport::save_presets() {
print_line("save presets");
@@ -693,10 +669,10 @@ void EditorExport::save_presets() {
void EditorExport::_bind_methods() {
- ClassDB::bind_method("_save",&EditorExport::_save);
+ ClassDB::bind_method("_save", &EditorExport::_save);
}
-void EditorExport::add_export_platform(const Ref<EditorExportPlatform>& p_platform) {
+void EditorExport::add_export_platform(const Ref<EditorExportPlatform> &p_platform) {
export_platforms.push_back(p_platform);
}
@@ -708,20 +684,17 @@ int EditorExport::get_export_platform_count() {
Ref<EditorExportPlatform> EditorExport::get_export_platform(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,export_platforms.size(),Ref<EditorExportPlatform>());
+ ERR_FAIL_INDEX_V(p_idx, export_platforms.size(), Ref<EditorExportPlatform>());
return export_platforms[p_idx];
}
+void EditorExport::add_export_preset(const Ref<EditorExportPreset> &p_preset, int p_at_pos) {
-void EditorExport::add_export_preset(const Ref<EditorExportPreset>& p_preset,int p_at_pos) {
-
- if (p_at_pos<0)
+ if (p_at_pos < 0)
export_presets.push_back(p_preset);
else
- export_presets.insert(p_at_pos,p_preset);
-
-
+ export_presets.insert(p_at_pos, p_preset);
}
int EditorExport::get_export_preset_count() const {
@@ -731,7 +704,7 @@ int EditorExport::get_export_preset_count() const {
Ref<EditorExportPreset> EditorExport::get_export_preset(int p_idx) {
- ERR_FAIL_INDEX_V( p_idx, export_presets.size(),Ref<EditorExportPreset>() );
+ ERR_FAIL_INDEX_V(p_idx, export_presets.size(), Ref<EditorExportPreset>());
return export_presets[p_idx];
}
@@ -742,7 +715,7 @@ void EditorExport::remove_export_preset(int p_idx) {
void EditorExport::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
load_config();
}
}
@@ -752,24 +725,24 @@ void EditorExport::load_config() {
Ref<ConfigFile> config;
config.instance();
Error err = config->load("res://export_presets.cfg");
- if (err!=OK)
+ if (err != OK)
return;
- block_save=true;
+ block_save = true;
- int index=0;
- while(true) {
+ int index = 0;
+ while (true) {
- String section = "preset."+itos(index);
+ String section = "preset." + itos(index);
if (!config->has_section(section))
break;
- String platform=config->get_value(section,"platform");
+ String platform = config->get_value(section, "platform");
Ref<EditorExportPreset> preset;
- for(int i=0;i<export_platforms.size();i++) {
- if (export_platforms[i]->get_name()==platform) {
+ for (int i = 0; i < export_platforms.size(); i++) {
+ if (export_platforms[i]->get_name() == platform) {
preset = export_platforms[i]->create_preset();
break;
}
@@ -780,86 +753,79 @@ void EditorExport::load_config() {
ERR_CONTINUE(!preset.is_valid());
}
- preset->set_name( config->get_value(section,"name") );
- preset->set_runnable( config->get_value(section,"runnable") );
+ preset->set_name(config->get_value(section, "name"));
+ preset->set_runnable(config->get_value(section, "runnable"));
- String export_filter = config->get_value(section,"export_filter");
+ String export_filter = config->get_value(section, "export_filter");
- bool get_files=false;
+ bool get_files = false;
- if (export_filter=="all_resources") {
+ if (export_filter == "all_resources") {
preset->set_export_filter(EditorExportPreset::EXPORT_ALL_RESOURCES);
- } else if (export_filter=="scenes") {
+ } else if (export_filter == "scenes") {
preset->set_export_filter(EditorExportPreset::EXPORT_SELECTED_SCENES);
- get_files=true;
- } else if (export_filter=="resources") {
+ get_files = true;
+ } else if (export_filter == "resources") {
preset->set_export_filter(EditorExportPreset::EXPORT_SELECTED_RESOURCES);
- get_files=true;
+ get_files = true;
}
if (get_files) {
- Vector<String> files = config->get_value(section,"export_files");
+ Vector<String> files = config->get_value(section, "export_files");
- for(int i=0;i<files.size();i++) {
+ for (int i = 0; i < files.size(); i++) {
preset->add_export_file(files[i]);
}
}
- preset->set_include_filter( config->get_value(section,"include_filter") );
- preset->set_exclude_filter( config->get_value(section,"exclude_filter") );
+ preset->set_include_filter(config->get_value(section, "include_filter"));
+ preset->set_exclude_filter(config->get_value(section, "exclude_filter"));
+ Vector<String> patch_list = config->get_value(section, "patch_list");
- Vector<String> patch_list = config->get_value(section,"patch_list");
-
- for(int i=0;i<patch_list.size();i++) {
+ for (int i = 0; i < patch_list.size(); i++) {
preset->add_patch(patch_list[i]);
}
- String option_section="preset."+itos(index)+".options";
+ String option_section = "preset." + itos(index) + ".options";
List<String> options;
- config->get_section_keys(option_section,&options);
+ config->get_section_keys(option_section, &options);
- for (List<String>::Element *E=options.front();E;E=E->next()) {
+ for (List<String>::Element *E = options.front(); E; E = E->next()) {
- Variant value = config->get_value(option_section,E->get());
+ Variant value = config->get_value(option_section, E->get());
- preset->set(E->get(),value);
+ preset->set(E->get(), value);
}
add_export_preset(preset);
index++;
}
- block_save=false;
-
+ block_save = false;
}
-
-
EditorExport::EditorExport() {
- save_timer = memnew( Timer );
+ save_timer = memnew(Timer);
add_child(save_timer);
save_timer->set_wait_time(0.8);
save_timer->set_one_shot(true);
- save_timer->connect("timeout",this,"_save");
- block_save=false;
+ save_timer->connect("timeout", this, "_save");
+ block_save = false;
- singleton=this;
+ singleton = this;
}
EditorExport::~EditorExport() {
-
-
}
-
//////////
-void EditorExportPlatformPC::get_preset_features(const Ref<EditorExportPreset>& p_preset,List<String>* r_features) {
+void EditorExportPlatformPC::get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) {
if (p_preset->get("texture_format/s3tc")) {
r_features->push_back("s3tc");
@@ -874,35 +840,35 @@ void EditorExportPlatformPC::get_preset_features(const Ref<EditorExportPreset>&
void EditorExportPlatformPC::get_export_options(List<ExportOption> *r_options) {
- r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL,"texture_format/s3tc"),true));
- r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL,"texture_format/etc"),false));
- r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL,"texture_format/etc2"),false));
- r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL,"binary_format/64_bits"),true));
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING,"custom_template/release",PROPERTY_HINT_GLOBAL_FILE),""));
- r_options->push_back(ExportOption(PropertyInfo(Variant::STRING,"custom_template/debug",PROPERTY_HINT_GLOBAL_FILE),""));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/s3tc"), true));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc"), false));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "texture_format/etc2"), false));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::BOOL, "binary_format/64_bits"), true));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/release", PROPERTY_HINT_GLOBAL_FILE), ""));
+ r_options->push_back(ExportOption(PropertyInfo(Variant::STRING, "custom_template/debug", PROPERTY_HINT_GLOBAL_FILE), ""));
}
String EditorExportPlatformPC::get_name() const {
return name;
}
-Ref<Texture> EditorExportPlatformPC::get_logo() const {
+Ref<Texture> EditorExportPlatformPC::get_logo() const {
return logo;
}
-bool EditorExportPlatformPC::can_export(const Ref<EditorExportPreset>& p_preset,String &r_error, bool &r_missing_templates) const {
+bool EditorExportPlatformPC::can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const {
- r_missing_templates=false;
+ r_missing_templates = false;
- if (find_export_template(release_file_32)==String()) {
- r_missing_templates=true;
- } else if (find_export_template(debug_file_32)==String()) {
- r_missing_templates=true;
- } else if (find_export_template(release_file_64)==String()) {
- r_missing_templates=true;
- } else if (find_export_template(debug_file_64)==String()) {
- r_missing_templates=true;
+ if (find_export_template(release_file_32) == String()) {
+ r_missing_templates = true;
+ } else if (find_export_template(debug_file_32) == String()) {
+ r_missing_templates = true;
+ } else if (find_export_template(release_file_64) == String()) {
+ r_missing_templates = true;
+ } else if (find_export_template(debug_file_64) == String()) {
+ r_missing_templates = true;
}
return !r_missing_templates;
}
@@ -911,64 +877,62 @@ String EditorExportPlatformPC::get_binary_extension() const {
return extension;
}
-Error EditorExportPlatformPC::export_project(const Ref<EditorExportPreset>& p_preset, bool p_debug, const String& p_path, int p_flags) {
+Error EditorExportPlatformPC::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {
return OK;
}
-void EditorExportPlatformPC::set_extension(const String& p_extension) {
- extension=p_extension;
+void EditorExportPlatformPC::set_extension(const String &p_extension) {
+ extension = p_extension;
}
-void EditorExportPlatformPC::set_name(const String& p_name) {
- name=p_name;
+void EditorExportPlatformPC::set_name(const String &p_name) {
+ name = p_name;
}
-void EditorExportPlatformPC::set_logo(const Ref<Texture>& p_logo) {
- logo=p_logo;
+void EditorExportPlatformPC::set_logo(const Ref<Texture> &p_logo) {
+ logo = p_logo;
}
-void EditorExportPlatformPC::set_release_64(const String& p_file) {
+void EditorExportPlatformPC::set_release_64(const String &p_file) {
- release_file_64=p_file;
+ release_file_64 = p_file;
}
-void EditorExportPlatformPC::set_release_32(const String& p_file){
+void EditorExportPlatformPC::set_release_32(const String &p_file) {
- release_file_32=p_file;
+ release_file_32 = p_file;
}
-void EditorExportPlatformPC::set_debug_64(const String& p_file){
+void EditorExportPlatformPC::set_debug_64(const String &p_file) {
- debug_file_64=p_file;
+ debug_file_64 = p_file;
}
-void EditorExportPlatformPC::set_debug_32(const String& p_file){
-
- debug_file_32=p_file;
+void EditorExportPlatformPC::set_debug_32(const String &p_file) {
+ debug_file_32 = p_file;
}
EditorExportPlatformPC::EditorExportPlatformPC() {
-
}
////////
#if 0
-#include "version.h"
-#include "script_language.h"
-#include "global_config.h"
-#include "os/file_access.h"
-#include "os/dir_access.h"
#include "editor/editor_file_system.h"
-#include "io/resource_loader.h"
+#include "editor/plugins/script_editor_plugin.h"
#include "editor_node.h"
#include "editor_settings.h"
+#include "global_config.h"
#include "io/config_file.h"
-#include "io/resource_saver.h"
#include "io/md5.h"
-#include "io_plugins/editor_texture_import_plugin.h"
-#include "editor/plugins/script_editor_plugin.h"
+#include "io/resource_loader.h"
+#include "io/resource_saver.h"
#include "io/zip_io.h"
+#include "io_plugins/editor_texture_import_plugin.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
+#include "script_language.h"
+#include "version.h"
String EditorImportPlugin::validate_source_path(const String& p_path) {
diff --git a/editor/editor_export.h b/editor/editor_export.h
index 8a9dc965e5..fe3c3df7d4 100644
--- a/editor/editor_export.h
+++ b/editor/editor_export.h
@@ -29,12 +29,10 @@
#ifndef EDITOR_EXPORT_H
#define EDITOR_EXPORT_H
-
-
#include "resource.h"
#include "scene/main/node.h"
-#include "scene/resources/texture.h"
#include "scene/main/timer.h"
+#include "scene/resources/texture.h"
class EditorProgress;
class FileAccess;
@@ -43,7 +41,7 @@ class EditorFileSystemDirectory;
class EditorExportPreset : public Reference {
- GDCLASS( EditorExportPreset,Reference )
+ GDCLASS(EditorExportPreset, Reference)
public:
enum ExportFilter {
EXPORT_ALL_RESOURCES,
@@ -52,7 +50,6 @@ public:
};
private:
-
Ref<EditorExportPlatform> platform;
ExportFilter export_filter;
String include_filter;
@@ -64,31 +61,30 @@ private:
Vector<String> patches;
-
-friend class EditorExport;
-friend class EditorExportPlatform;
+ friend class EditorExport;
+ friend class EditorExportPlatform;
List<PropertyInfo> properties;
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
String name;
+
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
Ref<EditorExportPlatform> get_platform() const;
- bool has(const StringName& p_property) const { return values.has(p_property); }
+ bool has(const StringName &p_property) const { return values.has(p_property); }
Vector<String> get_files_to_export() const;
- void add_export_file(const String& p_path);
- void remove_export_file(const String& p_path);
- bool has_export_file(const String& p_path);
+ void add_export_file(const String &p_path);
+ void remove_export_file(const String &p_path);
+ bool has_export_file(const String &p_path);
- void set_name(const String& p_name);
+ void set_name(const String &p_name);
String get_name() const;
void set_runnable(bool p_enable);
@@ -97,34 +93,31 @@ public:
void set_export_filter(ExportFilter p_filter);
ExportFilter get_export_filter() const;
- void set_include_filter(const String& p_include);
+ void set_include_filter(const String &p_include);
String get_include_filter() const;
- void set_exclude_filter(const String& p_exclude);
+ void set_exclude_filter(const String &p_exclude);
String get_exclude_filter() const;
- void add_patch(const String& p_path,int p_at_pos=-1);
- void set_patch(int p_index,const String& p_path);
+ void add_patch(const String &p_path, int p_at_pos = -1);
+ void set_patch(int p_index, const String &p_path);
String get_patch(int p_index);
void remove_patch(int p_idx);
Vector<String> get_patches() const;
- const List<PropertyInfo>& get_properties() const { return properties; }
+ const List<PropertyInfo> &get_properties() const { return properties; }
EditorExportPreset();
};
-
class EditorExportPlatform : public Reference {
- GDCLASS( EditorExportPlatform,Reference )
+ GDCLASS(EditorExportPlatform, Reference)
public:
-
- typedef Error (*EditorExportSaveFunction)(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total);
+ typedef Error (*EditorExportSaveFunction)(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
private:
-
struct SavedData {
uint64_t ofs;
@@ -132,7 +125,7 @@ private:
Vector<uint8_t> md5;
CharString path_utf8;
- bool operator<(const SavedData& p_data) const {
+ bool operator<(const SavedData &p_data) const {
return path_utf8 < p_data.path_utf8;
}
};
@@ -146,47 +139,43 @@ private:
struct ZipData {
- void* zip;
+ void *zip;
EditorProgress *ep;
-
};
- void _export_find_resources(EditorFileSystemDirectory *p_dir,Set<String>& p_paths);
- void _export_find_dependencies(const String& p_path,Set<String>& p_paths);
+ void _export_find_resources(EditorFileSystemDirectory *p_dir, Set<String> &p_paths);
+ void _export_find_dependencies(const String &p_path, Set<String> &p_paths);
void gen_debug_flags(Vector<String> &r_flags, int p_flags);
- static Error _save_pack_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total);
- static Error _save_zip_file(void *p_userdata,const String& p_path, const Vector<uint8_t>& p_data,int p_file,int p_total);
-
+ static Error _save_pack_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
+ static Error _save_zip_file(void *p_userdata, const String &p_path, const Vector<uint8_t> &p_data, int p_file, int p_total);
protected:
-
- virtual void get_preset_features(const Ref<EditorExportPreset>& p_preset,List<String> *r_features)=0;
- String find_export_template(String template_file_name, String *err=NULL) const;
+ virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features) = 0;
+ String find_export_template(String template_file_name, String *err = NULL) const;
public:
-
-
struct ExportOption {
PropertyInfo option;
Variant default_value;
- ExportOption(const PropertyInfo& p_info,const Variant& p_default) { option=p_info; default_value=p_default; }
+ ExportOption(const PropertyInfo &p_info, const Variant &p_default) {
+ option = p_info;
+ default_value = p_default;
+ }
ExportOption() {}
};
virtual Ref<EditorExportPreset> create_preset();
- virtual void get_export_options(List<ExportOption> *r_options)=0;
- virtual String get_name() const =0;
- virtual Ref<Texture> get_logo() const =0;
-
-
- Error export_project_files(const Ref<EditorExportPreset>& p_preset,EditorExportSaveFunction p_func, void* p_udata);
+ virtual void get_export_options(List<ExportOption> *r_options) = 0;
+ virtual String get_name() const = 0;
+ virtual Ref<Texture> get_logo() const = 0;
- Error save_pack(const Ref<EditorExportPreset>& p_preset,const String& p_path);
- Error save_zip(const Ref<EditorExportPreset>& p_preset,const String& p_path);
+ Error export_project_files(const Ref<EditorExportPreset> &p_preset, EditorExportSaveFunction p_func, void *p_udata);
+ Error save_pack(const Ref<EditorExportPreset> &p_preset, const String &p_path);
+ Error save_zip(const Ref<EditorExportPreset> &p_preset, const String &p_path);
virtual bool poll_devices() { return false; }
virtual int get_device_count() const { return 0; }
@@ -194,26 +183,25 @@ public:
virtual String get_device_info(int p_device) const { return ""; }
enum DebugFlags {
- DEBUG_FLAG_DUMB_CLIENT=1,
- DEBUG_FLAG_REMOTE_DEBUG=2,
- DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST=4,
- DEBUG_FLAG_VIEW_COLLISONS=8,
- DEBUG_FLAG_VIEW_NAVIGATION=16,
+ DEBUG_FLAG_DUMB_CLIENT = 1,
+ DEBUG_FLAG_REMOTE_DEBUG = 2,
+ DEBUG_FLAG_REMOTE_DEBUG_LOCALHOST = 4,
+ DEBUG_FLAG_VIEW_COLLISONS = 8,
+ DEBUG_FLAG_VIEW_NAVIGATION = 16,
};
- virtual Error run(int p_device,int p_debug_flags) { return OK; }
+ virtual Error run(int p_device, int p_debug_flags) { return OK; }
- virtual bool can_export(const Ref<EditorExportPreset>& p_preset,String &r_error,bool &r_missing_templates) const=0;
+ virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const = 0;
- virtual String get_binary_extension() const=0;
- virtual Error export_project(const Ref<EditorExportPreset>& p_preset,bool p_debug,const String& p_path,int p_flags=0)=0;
+ virtual String get_binary_extension() const = 0;
+ virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0) = 0;
EditorExportPlatform();
};
-
class EditorExport : public Node {
- GDCLASS(EditorExport,Node);
+ GDCLASS(EditorExport, Node);
Vector<Ref<EditorExportPlatform> > export_platforms;
Vector<Ref<EditorExportPreset> > export_presets;
@@ -224,23 +212,22 @@ class EditorExport : public Node {
static EditorExport *singleton;
void _save();
-protected:
-friend class EditorExportPreset;
+protected:
+ friend class EditorExportPreset;
void save_presets();
void _notification(int p_what);
static void _bind_methods();
-public:
- static EditorExport * get_singleton() { return singleton; }
+public:
+ static EditorExport *get_singleton() { return singleton; }
- void add_export_platform(const Ref<EditorExportPlatform>& p_platform);
+ void add_export_platform(const Ref<EditorExportPlatform> &p_platform);
int get_export_platform_count();
Ref<EditorExportPlatform> get_export_platform(int p_idx);
-
- void add_export_preset(const Ref<EditorExportPreset>& p_preset,int p_at_pos=-1);
+ void add_export_preset(const Ref<EditorExportPreset> &p_preset, int p_at_pos = -1);
int get_export_preset_count() const;
Ref<EditorExportPreset> get_export_preset(int p_idx);
void remove_export_preset(int p_idx);
@@ -251,12 +238,9 @@ public:
~EditorExport();
};
-
-
-
class EditorExportPlatformPC : public EditorExportPlatform {
- GDCLASS( EditorExportPlatformPC,EditorExportPlatform )
+ GDCLASS(EditorExportPlatformPC, EditorExportPlatform)
Ref<ImageTexture> logo;
String name;
@@ -268,30 +252,28 @@ class EditorExportPlatformPC : public EditorExportPlatform {
String debug_file_64;
public:
-
- virtual void get_preset_features(const Ref<EditorExportPreset>& p_preset,List<String>* r_features);
+ virtual void get_preset_features(const Ref<EditorExportPreset> &p_preset, List<String> *r_features);
virtual void get_export_options(List<ExportOption> *r_options);
virtual String get_name() const;
virtual Ref<Texture> get_logo() const;
- virtual bool can_export(const Ref<EditorExportPreset>& p_preset,String &r_error,bool &r_missing_templates) const;
+ virtual bool can_export(const Ref<EditorExportPreset> &p_preset, String &r_error, bool &r_missing_templates) const;
virtual String get_binary_extension() const;
- virtual Error export_project(const Ref<EditorExportPreset>& p_preset,bool p_debug,const String& p_path,int p_flags=0);
+ virtual Error export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags = 0);
- void set_extension(const String& p_extension);
- void set_name(const String& p_name);
+ void set_extension(const String &p_extension);
+ void set_name(const String &p_name);
- void set_logo(const Ref<Texture>& p_loco);
+ void set_logo(const Ref<Texture> &p_loco);
- void set_release_64(const String& p_file);
- void set_release_32(const String& p_file);
- void set_debug_64(const String& p_file);
- void set_debug_32(const String& p_file);
+ void set_release_64(const String &p_file);
+ void set_release_32(const String &p_file);
+ void set_debug_64(const String &p_file);
+ void set_debug_32(const String &p_file);
EditorExportPlatformPC();
};
-
#endif // EDITOR_IMPORT_EXPORT_H
diff --git a/editor/editor_file_dialog.cpp b/editor/editor_file_dialog.cpp
index bfaf1906d8..bde0fd90cf 100644
--- a/editor/editor_file_dialog.cpp
+++ b/editor/editor_file_dialog.cpp
@@ -28,107 +28,105 @@
/*************************************************************************/
#include "editor_file_dialog.h"
-#include "scene/gui/label.h"
-#include "scene/gui/center_container.h"
-#include "print_string.h"
-#include "os/keyboard.h"
#include "editor_resource_preview.h"
+#include "editor_scale.h"
#include "editor_settings.h"
-#include "scene/gui/margin_container.h"
#include "os/file_access.h"
-#include "editor_scale.h"
-
-EditorFileDialog::GetIconFunc EditorFileDialog::get_icon_func=NULL;
-EditorFileDialog::GetIconFunc EditorFileDialog::get_large_icon_func=NULL;
+#include "os/keyboard.h"
+#include "print_string.h"
+#include "scene/gui/center_container.h"
+#include "scene/gui/label.h"
+#include "scene/gui/margin_container.h"
-EditorFileDialog::RegisterFunc EditorFileDialog::register_func=NULL;
-EditorFileDialog::RegisterFunc EditorFileDialog::unregister_func=NULL;
+EditorFileDialog::GetIconFunc EditorFileDialog::get_icon_func = NULL;
+EditorFileDialog::GetIconFunc EditorFileDialog::get_large_icon_func = NULL;
+EditorFileDialog::RegisterFunc EditorFileDialog::register_func = NULL;
+EditorFileDialog::RegisterFunc EditorFileDialog::unregister_func = NULL;
VBoxContainer *EditorFileDialog::get_vbox() {
return vbox;
-
}
void EditorFileDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- mode_thumbnails->set_icon(get_icon("FileThumbnail","EditorIcons"));
- mode_list->set_icon(get_icon("FileList","EditorIcons"));
- dir_prev->set_icon(get_icon("ArrowLeft","EditorIcons"));
- dir_next->set_icon(get_icon("ArrowRight","EditorIcons"));
- dir_up->set_icon(get_icon("ArrowUp","EditorIcons"));
- refresh->set_icon(get_icon("Reload","EditorIcons"));
- favorite->set_icon(get_icon("Favorites","EditorIcons"));
+ mode_thumbnails->set_icon(get_icon("FileThumbnail", "EditorIcons"));
+ mode_list->set_icon(get_icon("FileList", "EditorIcons"));
+ dir_prev->set_icon(get_icon("ArrowLeft", "EditorIcons"));
+ dir_next->set_icon(get_icon("ArrowRight", "EditorIcons"));
+ dir_up->set_icon(get_icon("ArrowUp", "EditorIcons"));
+ refresh->set_icon(get_icon("Reload", "EditorIcons"));
+ favorite->set_icon(get_icon("Favorites", "EditorIcons"));
- fav_up->set_icon(get_icon("MoveUp","EditorIcons"));
- fav_down->set_icon(get_icon("MoveDown","EditorIcons"));
- fav_rm->set_icon(get_icon("RemoveSmall","EditorIcons"));
+ fav_up->set_icon(get_icon("MoveUp", "EditorIcons"));
+ fav_down->set_icon(get_icon("MoveDown", "EditorIcons"));
+ fav_rm->set_icon(get_icon("RemoveSmall", "EditorIcons"));
- } else if (p_what==NOTIFICATION_PROCESS) {
+ } else if (p_what == NOTIFICATION_PROCESS) {
if (preview_waiting) {
- preview_wheel_timeout-=get_process_delta_time();
- if (preview_wheel_timeout<=0) {
+ preview_wheel_timeout -= get_process_delta_time();
+ if (preview_wheel_timeout <= 0) {
preview_wheel_index++;
- if (preview_wheel_index>=8)
- preview_wheel_index=0;
- Ref<Texture> frame = get_icon("WaitPreview"+itos(preview_wheel_index+1),"EditorIcons");
+ if (preview_wheel_index >= 8)
+ preview_wheel_index = 0;
+ Ref<Texture> frame = get_icon("WaitPreview" + itos(preview_wheel_index + 1), "EditorIcons");
preview->set_texture(frame);
- preview_wheel_timeout=0.1;
+ preview_wheel_timeout = 0.1;
}
}
- } else if (p_what==NOTIFICATION_DRAW) {
+ } else if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
- } else if (p_what==NOTIFICATION_POPUP_HIDE) {
+ } else if (p_what == NOTIFICATION_POPUP_HIDE) {
set_process_unhandled_input(false);
- } else if (p_what==EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
+ } else if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
- bool show_hidden=EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files");
- if (show_hidden_files!=show_hidden)
+ bool show_hidden = EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files");
+ if (show_hidden_files != show_hidden)
set_show_hidden_files(show_hidden);
set_display_mode((DisplayMode)EditorSettings::get_singleton()->get("filesystem/file_dialog/display_mode").operator int());
}
}
-void EditorFileDialog::_unhandled_input(const InputEvent& p_event) {
+void EditorFileDialog::_unhandled_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && is_window_modal_on_top()) {
+ if (p_event.type == InputEvent::KEY && is_window_modal_on_top()) {
if (p_event.key.pressed) {
- bool handled=false;
+ bool handled = false;
if (ED_IS_SHORTCUT("file_dialog/go_back", p_event)) {
_go_back();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/go_forward", p_event)) {
_go_forward();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/go_up", p_event)) {
_go_up();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/refresh", p_event)) {
invalidate();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/toggle_hidden_files", p_event)) {
- bool show=!show_hidden_files;
+ bool show = !show_hidden_files;
set_show_hidden_files(show);
- EditorSettings::get_singleton()->set("filesystem/file_dialog/show_hidden_files",show);
- handled=true;
+ EditorSettings::get_singleton()->set("filesystem/file_dialog/show_hidden_files", show);
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/toggle_favorite", p_event)) {
_favorite_toggled(favorite->is_pressed());
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/toggle_mode", p_event)) {
if (mode_thumbnails->is_pressed()) {
@@ -136,23 +134,23 @@ void EditorFileDialog::_unhandled_input(const InputEvent& p_event) {
} else {
set_display_mode(DISPLAY_THUMBNAILS);
}
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/create_folder", p_event)) {
_make_dir();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/focus_path", p_event)) {
dir->grab_focus();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/move_favorite_up", p_event)) {
_favorite_move_up();
- handled=true;
+ handled = true;
}
if (ED_IS_SHORTCUT("file_dialog/move_favorite_down", p_event)) {
_favorite_move_down();
- handled=true;
+ handled = true;
}
if (handled) {
@@ -164,19 +162,17 @@ void EditorFileDialog::_unhandled_input(const InputEvent& p_event) {
void EditorFileDialog::set_enable_multiple_selection(bool p_enable) {
- item_list->set_select_mode(p_enable?ItemList::SELECT_MULTI:ItemList::SELECT_SINGLE);
-
+ item_list->set_select_mode(p_enable ? ItemList::SELECT_MULTI : ItemList::SELECT_SINGLE);
};
Vector<String> EditorFileDialog::get_selected_files() const {
Vector<String> list;
- for(int i=0;i<item_list->get_item_count();i++) {
+ for (int i = 0; i < item_list->get_item_count(); i++) {
if (item_list->is_selected(i))
list.push_back(item_list->get_item_text(i));
}
return list;
-
};
void EditorFileDialog::update_dir() {
@@ -186,25 +182,22 @@ void EditorFileDialog::update_dir() {
void EditorFileDialog::_dir_entered(String p_dir) {
-
dir_access->change_dir(p_dir);
file->set_text("");
invalidate();
update_dir();
_push_history();
-
-
}
-void EditorFileDialog::_file_entered(const String& p_file) {
+void EditorFileDialog::_file_entered(const String &p_file) {
_action_pressed();
}
void EditorFileDialog::_save_confirm_pressed() {
- String f=dir_access->get_current_dir().plus_file(file->get_text());
+ String f = dir_access->get_current_dir().plus_file(file->get_text());
_save_to_recent();
- emit_signal("file_selected",f);
+ emit_signal("file_selected", f);
hide();
}
@@ -213,75 +206,72 @@ void EditorFileDialog::_post_popup() {
ConfirmationDialog::_post_popup();
if (invalidated) {
update_file_list();
- invalidated=false;
+ invalidated = false;
}
- if (mode==MODE_SAVE_FILE)
+ if (mode == MODE_SAVE_FILE)
file->grab_focus();
else
item_list->grab_focus();
- if (is_visible_in_tree() && get_current_file()!="")
+ if (is_visible_in_tree() && get_current_file() != "")
_request_single_thumbnail(get_current_dir().plus_file(get_current_file()));
if (is_visible_in_tree()) {
- Ref<Texture> folder = get_icon("folder","FileDialog");
+ Ref<Texture> folder = get_icon("folder", "FileDialog");
recent->clear();
-
- bool res = access==ACCESS_RESOURCES;
+ bool res = access == ACCESS_RESOURCES;
Vector<String> recentd = EditorSettings::get_singleton()->get_recent_dirs();
- for(int i=0;i<recentd.size();i++) {
+ for (int i = 0; i < recentd.size(); i++) {
bool cres = recentd[i].begins_with("res://");
- if (cres!=res)
+ if (cres != res)
continue;
String name = recentd[i];
- if (res && name=="res://") {
- name="/";
+ if (res && name == "res://") {
+ name = "/";
} else {
- name=name.get_file()+"/";
+ name = name.get_file() + "/";
}
//print_line("file: "+name);
- recent->add_item(name,folder);
- recent->set_item_metadata( recent->get_item_count()-1,recentd[i]);
+ recent->add_item(name, folder);
+ recent->set_item_metadata(recent->get_item_count() - 1, recentd[i]);
}
local_history.clear();
- local_history_pos=-1;
+ local_history_pos = -1;
_push_history();
_update_favorites();
}
set_process_unhandled_input(true);
-
}
-void EditorFileDialog::_thumbnail_result(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata) {
+void EditorFileDialog::_thumbnail_result(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata) {
- if (display_mode==DISPLAY_LIST || p_preview.is_null())
+ if (display_mode == DISPLAY_LIST || p_preview.is_null())
return;
- for(int i=0;i<item_list->get_item_count();i++) {
+ for (int i = 0; i < item_list->get_item_count(); i++) {
Dictionary d = item_list->get_item_metadata(i);
String pname = d["path"];
- if (pname==p_path) {
- item_list->set_item_icon(i,p_preview);
- item_list->set_item_tag_icon(i,Ref<Texture>());
+ if (pname == p_path) {
+ item_list->set_item_icon(i, p_preview);
+ item_list->set_item_tag_icon(i, Ref<Texture>());
}
}
}
-void EditorFileDialog::_thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata) {
+void EditorFileDialog::_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata) {
set_process(false);
- preview_waiting=false;
-
- if (p_preview.is_valid() && get_current_path()==p_path) {
+ preview_waiting = false;
+ if (p_preview.is_valid() && get_current_path() == p_path) {
preview->set_texture(p_preview);
- if (display_mode==DISPLAY_THUMBNAILS) {
+ if (display_mode == DISPLAY_THUMBNAILS) {
preview_vb->hide();
} else {
preview_vb->show();
@@ -290,63 +280,59 @@ void EditorFileDialog::_thumbnail_done(const String& p_path,const Ref<Texture>&
} else {
preview_vb->hide();
preview->set_texture(Ref<Texture>());
-
}
-
}
-void EditorFileDialog::_request_single_thumbnail(const String& p_path) {
+void EditorFileDialog::_request_single_thumbnail(const String &p_path) {
if (!FileAccess::exists(p_path))
return;
- EditorResourcePreview::get_singleton()->queue_resource_preview(p_path,this,"_thumbnail_done",p_path);
+ EditorResourcePreview::get_singleton()->queue_resource_preview(p_path, this, "_thumbnail_done", p_path);
//print_line("want file "+p_path);
set_process(true);
- preview_waiting=true;
- preview_wheel_timeout=0;
-
+ preview_waiting = true;
+ preview_wheel_timeout = 0;
}
void EditorFileDialog::_action_pressed() {
- if (mode==MODE_OPEN_FILES) {
-
+ if (mode == MODE_OPEN_FILES) {
- String fbase=dir_access->get_current_dir();
+ String fbase = dir_access->get_current_dir();
PoolVector<String> files;
- for(int i=0;i<item_list->get_item_count();i++) {
+ for (int i = 0; i < item_list->get_item_count(); i++) {
if (item_list->is_selected(i))
- files.push_back( fbase.plus_file(item_list->get_item_text(i) ));
+ files.push_back(fbase.plus_file(item_list->get_item_text(i)));
}
if (files.size()) {
_save_to_recent();
- emit_signal("files_selected",files);
+ emit_signal("files_selected", files);
hide();
}
return;
}
- String f=dir_access->get_current_dir().plus_file(file->get_text());
+ String f = dir_access->get_current_dir().plus_file(file->get_text());
- if ((mode==MODE_OPEN_ANY || mode==MODE_OPEN_FILE) && dir_access->file_exists(f)) {
+ if ((mode == MODE_OPEN_ANY || mode == MODE_OPEN_FILE) && dir_access->file_exists(f)) {
_save_to_recent();
- emit_signal("file_selected",f);
+ emit_signal("file_selected", f);
hide();
- }else if (mode==MODE_OPEN_ANY || mode==MODE_OPEN_DIR) {
+ } else if (mode == MODE_OPEN_ANY || mode == MODE_OPEN_DIR) {
- String path=dir_access->get_current_dir();
+ String path = dir_access->get_current_dir();
- path=path.replace("\\","/");
+ path = path.replace("\\", "/");
- for(int i=0;i<item_list->get_item_count();i++) {
+ for (int i = 0; i < item_list->get_item_count(); i++) {
if (item_list->is_selected(i)) {
- Dictionary d=item_list->get_item_metadata(i);
+ Dictionary d = item_list->get_item_metadata(i);
if (d["dir"]) {
- path=path.plus_file(d["name"]);
+ path = path.plus_file(d["name"]);
break;
}
@@ -354,26 +340,26 @@ void EditorFileDialog::_action_pressed() {
}
_save_to_recent();
- emit_signal("dir_selected",path);
+ emit_signal("dir_selected", path);
hide();
}
- if (mode==MODE_SAVE_FILE) {
+ if (mode == MODE_SAVE_FILE) {
- bool valid=false;
+ bool valid = false;
- if (filter->get_selected()==filter->get_item_count()-1) {
- valid=true; //match none
- } else if (filters.size()>1 && filter->get_selected()==0) {
+ if (filter->get_selected() == filter->get_item_count() - 1) {
+ valid = true; //match none
+ } else if (filters.size() > 1 && filter->get_selected() == 0) {
// match all filters
- for (int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String flt=filters[i].get_slice(";",0);
- for (int j=0;j<flt.get_slice_count(",");j++) {
+ String flt = filters[i].get_slice(";", 0);
+ for (int j = 0; j < flt.get_slice_count(","); j++) {
- String str = flt.get_slice(",",j).strip_edges();
+ String str = flt.get_slice(",", j).strip_edges();
if (f.match(str)) {
- valid=true;
+ valid = true;
break;
}
}
@@ -381,49 +367,47 @@ void EditorFileDialog::_action_pressed() {
break;
}
} else {
- int idx=filter->get_selected();
- if (filters.size()>1)
+ int idx = filter->get_selected();
+ if (filters.size() > 1)
idx--;
- if (idx>=0 && idx<filters.size()) {
+ if (idx >= 0 && idx < filters.size()) {
- String flt=filters[idx].get_slice(";",0);
- int filterSliceCount=flt.get_slice_count(",");
- for (int j=0;j<filterSliceCount;j++) {
+ String flt = filters[idx].get_slice(";", 0);
+ int filterSliceCount = flt.get_slice_count(",");
+ for (int j = 0; j < filterSliceCount; j++) {
- String str = (flt.get_slice(",",j).strip_edges());
+ String str = (flt.get_slice(",", j).strip_edges());
if (f.match(str)) {
- valid=true;
+ valid = true;
break;
}
}
- if (!valid && filterSliceCount>0) {
- String str = (flt.get_slice(",",0).strip_edges());
- f+=str.substr(1, str.length()-1);
+ if (!valid && filterSliceCount > 0) {
+ String str = (flt.get_slice(",", 0).strip_edges());
+ f += str.substr(1, str.length() - 1);
_request_single_thumbnail(get_current_dir().plus_file(f.get_file()));
file->set_text(f.get_file());
- valid=true;
+ valid = true;
}
} else {
- valid=true;
+ valid = true;
}
}
-
if (!valid) {
- exterr->popup_centered_minsize(Size2(250,80)*EDSCALE);
+ exterr->popup_centered_minsize(Size2(250, 80) * EDSCALE);
return;
-
}
if (dir_access->file_exists(f) && !disable_overwrite_warning) {
confirm_save->set_text(TTR("File Exists, Overwrite?"));
- confirm_save->popup_centered(Size2(200,80));
+ confirm_save->popup_centered(Size2(200, 80));
} else {
_save_to_recent();
- emit_signal("file_selected",f);
+ emit_signal("file_selected", f);
hide();
}
}
@@ -439,10 +423,10 @@ void EditorFileDialog::_cancel_pressed() {
void EditorFileDialog::_item_selected(int p_item) {
int current = p_item;
- if (current<0 || current>=item_list->get_item_count())
+ if (current < 0 || current >= item_list->get_item_count())
return;
- Dictionary d=item_list->get_item_metadata(current);
+ Dictionary d = item_list->get_item_metadata(current);
if (!d["dir"]) {
@@ -453,24 +437,22 @@ void EditorFileDialog::_item_selected(int p_item) {
void EditorFileDialog::_push_history() {
- local_history.resize(local_history_pos+1);
+ local_history.resize(local_history_pos + 1);
String new_path = dir_access->get_current_dir();
- if (local_history.size()==0 || new_path!=local_history[local_history_pos]) {
+ if (local_history.size() == 0 || new_path != local_history[local_history_pos]) {
local_history.push_back(new_path);
local_history_pos++;
- dir_prev->set_disabled(local_history_pos==0);
+ dir_prev->set_disabled(local_history_pos == 0);
dir_next->set_disabled(true);
}
-
}
void EditorFileDialog::_item_dc_selected(int p_item) {
-
int current = p_item;
- if (current<0 || current>=item_list->get_item_count())
+ if (current < 0 || current >= item_list->get_item_count())
return;
- Dictionary d=item_list->get_item_metadata(current);
+ Dictionary d = item_list->get_item_metadata(current);
if (d["dir"]) {
@@ -480,54 +462,50 @@ void EditorFileDialog::_item_dc_selected(int p_item) {
_push_history();
-
} else {
_action_pressed();
}
}
-
-
void EditorFileDialog::update_file_list() {
-
int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
- thumbnail_size*=EDSCALE;
+ thumbnail_size *= EDSCALE;
Ref<Texture> folder_thumbnail;
Ref<Texture> file_thumbnail;
item_list->clear();
- if (display_mode==DISPLAY_THUMBNAILS) {
+ if (display_mode == DISPLAY_THUMBNAILS) {
item_list->set_max_columns(0);
item_list->set_icon_mode(ItemList::ICON_MODE_TOP);
- item_list->set_fixed_column_width(thumbnail_size*3/2);
+ item_list->set_fixed_column_width(thumbnail_size * 3 / 2);
item_list->set_max_text_lines(2);
- item_list->set_fixed_icon_size(Size2(thumbnail_size,thumbnail_size));
+ item_list->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size));
- if (!has_icon("ResizedFolder","EditorIcons")) {
- Ref<ImageTexture> folder = get_icon("FolderBig","EditorIcons");
+ if (!has_icon("ResizedFolder", "EditorIcons")) {
+ Ref<ImageTexture> folder = get_icon("FolderBig", "EditorIcons");
Image img = folder->get_data();
- img.resize(thumbnail_size,thumbnail_size);
- Ref<ImageTexture> resized_folder = Ref<ImageTexture>( memnew( ImageTexture));
- resized_folder->create_from_image(img,0);
- Theme::get_default()->set_icon("ResizedFolder","EditorIcons",resized_folder);
+ img.resize(thumbnail_size, thumbnail_size);
+ Ref<ImageTexture> resized_folder = Ref<ImageTexture>(memnew(ImageTexture));
+ resized_folder->create_from_image(img, 0);
+ Theme::get_default()->set_icon("ResizedFolder", "EditorIcons", resized_folder);
}
- folder_thumbnail = get_icon("ResizedFolder","EditorIcons");
+ folder_thumbnail = get_icon("ResizedFolder", "EditorIcons");
- if (!has_icon("ResizedFile","EditorIcons")) {
- Ref<ImageTexture> file = get_icon("FileBig","EditorIcons");
+ if (!has_icon("ResizedFile", "EditorIcons")) {
+ Ref<ImageTexture> file = get_icon("FileBig", "EditorIcons");
Image img = file->get_data();
- img.resize(thumbnail_size,thumbnail_size);
- Ref<ImageTexture> resized_file = Ref<ImageTexture>( memnew( ImageTexture));
- resized_file->create_from_image(img,0);
- Theme::get_default()->set_icon("ResizedFile","EditorIcons",resized_file);
+ img.resize(thumbnail_size, thumbnail_size);
+ Ref<ImageTexture> resized_file = Ref<ImageTexture>(memnew(ImageTexture));
+ resized_file->create_from_image(img, 0);
+ Theme::get_default()->set_icon("ResizedFile", "EditorIcons", resized_file);
}
- file_thumbnail = get_icon("ResizedFile","EditorIcons");
+ file_thumbnail = get_icon("ResizedFile", "EditorIcons");
preview_vb->hide();
@@ -540,16 +518,14 @@ void EditorFileDialog::update_file_list() {
item_list->set_fixed_icon_size(Size2());
if (preview->get_texture().is_valid())
preview_vb->show();
-
}
String cdir = dir_access->get_current_dir();
- bool skip_pp = access==ACCESS_RESOURCES && cdir=="res://";
+ bool skip_pp = access == ACCESS_RESOURCES && cdir == "res://";
dir_access->list_dir_begin();
-
- Ref<Texture> folder = get_icon("folder","FileDialog");
+ Ref<Texture> folder = get_icon("folder", "FileDialog");
List<String> files;
List<String> dirs;
@@ -558,19 +534,19 @@ void EditorFileDialog::update_file_list() {
bool show_hidden = show_hidden_files;
String item;
- while ((item=dir_access->get_next(&isdir))!="") {
+ while ((item = dir_access->get_next(&isdir)) != "") {
ishidden = dir_access->current_is_hidden();
if (show_hidden || !ishidden) {
if (!isdir)
files.push_back(item);
- else if (item!=".." || !skip_pp)
+ else if (item != ".." || !skip_pp)
dirs.push_back(item);
}
}
- if (dirs.find("..")==NULL) {
+ if (dirs.find("..") == NULL) {
//may happen if lacking permissions
dirs.push_back("..");
}
@@ -578,25 +554,25 @@ void EditorFileDialog::update_file_list() {
dirs.sort_custom<NoCaseComparator>();
files.sort_custom<NoCaseComparator>();
- while(!dirs.empty()) {
- const String& dir_name=dirs.front()->get();
+ while (!dirs.empty()) {
+ const String &dir_name = dirs.front()->get();
- item_list->add_item(dir_name+"/");
+ item_list->add_item(dir_name + "/");
- if (display_mode==DISPLAY_THUMBNAILS) {
+ if (display_mode == DISPLAY_THUMBNAILS) {
- item_list->set_item_icon(item_list->get_item_count()-1,folder_thumbnail);
+ item_list->set_item_icon(item_list->get_item_count() - 1, folder_thumbnail);
} else {
- item_list->set_item_icon(item_list->get_item_count()-1,folder);
+ item_list->set_item_icon(item_list->get_item_count() - 1, folder);
}
Dictionary d;
- d["name"]=dir_name;
- d["path"]=String();
- d["dir"]=true;
+ d["name"] = dir_name;
+ d["path"] = String();
+ d["dir"] = true;
- item_list->set_item_metadata( item_list->get_item_count() -1, d);
+ item_list->set_item_metadata(item_list->get_item_count() - 1, d);
dirs.pop_front();
}
@@ -605,47 +581,45 @@ void EditorFileDialog::update_file_list() {
List<String> patterns;
// build filter
- if (filter->get_selected()==filter->get_item_count()-1) {
+ if (filter->get_selected() == filter->get_item_count() - 1) {
// match all
- } else if (filters.size()>1 && filter->get_selected()==0) {
+ } else if (filters.size() > 1 && filter->get_selected() == 0) {
// match all filters
- for (int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String f=filters[i].get_slice(";",0);
- for (int j=0;j<f.get_slice_count(",");j++) {
+ String f = filters[i].get_slice(";", 0);
+ for (int j = 0; j < f.get_slice_count(","); j++) {
- patterns.push_back(f.get_slice(",",j).strip_edges());
+ patterns.push_back(f.get_slice(",", j).strip_edges());
}
}
} else {
- int idx=filter->get_selected();
- if (filters.size()>1)
+ int idx = filter->get_selected();
+ if (filters.size() > 1)
idx--;
- if (idx>=0 && idx<filters.size()) {
+ if (idx >= 0 && idx < filters.size()) {
- String f=filters[idx].get_slice(";",0);
- for (int j=0;j<f.get_slice_count(",");j++) {
+ String f = filters[idx].get_slice(";", 0);
+ for (int j = 0; j < f.get_slice_count(","); j++) {
- patterns.push_back(f.get_slice(",",j).strip_edges());
+ patterns.push_back(f.get_slice(",", j).strip_edges());
}
}
}
-
String base_dir = dir_access->get_current_dir();
+ while (!files.empty()) {
- while(!files.empty()) {
-
- bool match=patterns.empty();
+ bool match = patterns.empty();
- for(List<String>::Element *E=patterns.front();E;E=E->next()) {
+ for (List<String>::Element *E = patterns.front(); E; E = E->next()) {
if (files.front()->get().matchn(E->get())) {
- match=true;
+ match = true;
break;
}
}
@@ -657,62 +631,60 @@ void EditorFileDialog::update_file_list() {
if (get_icon_func) {
-
Ref<Texture> icon = get_icon_func(base_dir.plus_file(files.front()->get()));
//ti->set_icon(0,icon);
- if (display_mode==DISPLAY_THUMBNAILS) {
+ if (display_mode == DISPLAY_THUMBNAILS) {
- item_list->set_item_icon(item_list->get_item_count()-1,file_thumbnail);
- item_list->set_item_tag_icon(item_list->get_item_count()-1,icon);
+ item_list->set_item_icon(item_list->get_item_count() - 1, file_thumbnail);
+ item_list->set_item_tag_icon(item_list->get_item_count() - 1, icon);
} else {
- item_list->set_item_icon(item_list->get_item_count()-1,icon);
+ item_list->set_item_icon(item_list->get_item_count() - 1, icon);
}
}
- if (mode==MODE_OPEN_DIR) {
+ if (mode == MODE_OPEN_DIR) {
//disabled mode?
//ti->set_custom_color(0,get_color("files_disabled"));
//ti->set_selectable(0,false);
}
Dictionary d;
- d["name"]=files.front()->get();
- d["dir"]=false;
+ d["name"] = files.front()->get();
+ d["dir"] = false;
String fullpath = base_dir.plus_file(files.front()->get());
- if (display_mode==DISPLAY_THUMBNAILS) {
- EditorResourcePreview::get_singleton()->queue_resource_preview(fullpath,this,"_thumbnail_result",fullpath);
+ if (display_mode == DISPLAY_THUMBNAILS) {
+ EditorResourcePreview::get_singleton()->queue_resource_preview(fullpath, this, "_thumbnail_result", fullpath);
}
- d["path"]=base_dir.plus_file(files.front()->get());
+ d["path"] = base_dir.plus_file(files.front()->get());
//ti->set_metadata(0,d);
- item_list->set_item_metadata(item_list->get_item_count()-1,d);
+ item_list->set_item_metadata(item_list->get_item_count() - 1, d);
- if (file->get_text()==files.front()->get())
- item_list->set_current(item_list->get_item_count()-1);
+ if (file->get_text() == files.front()->get())
+ item_list->set_current(item_list->get_item_count() - 1);
}
files.pop_front();
}
- if (favorites->get_current()>=0) {
+ if (favorites->get_current() >= 0) {
favorites->unselect(favorites->get_current());
}
favorite->set_pressed(false);
fav_up->set_disabled(true);
fav_down->set_disabled(true);
- for(int i=0;i<favorites->get_item_count();i++) {
- if (favorites->get_item_metadata(i)==base_dir) {
+ for (int i = 0; i < favorites->get_item_count(); i++) {
+ if (favorites->get_item_metadata(i) == base_dir) {
favorites->select(i);
favorite->set_pressed(true);
- if (i>0) {
+ if (i > 0) {
fav_up->set_disabled(false);
}
- if (i<favorites->get_item_count()-1) {
+ if (i < favorites->get_item_count() - 1) {
fav_down->set_disabled(false);
}
break;
}
-
}
// ??
/*
@@ -721,7 +693,6 @@ void EditorFileDialog::update_file_list() {
*/
files.clear();
-
}
void EditorFileDialog::_filter_selected(int) {
@@ -733,35 +704,34 @@ void EditorFileDialog::update_filters() {
filter->clear();
- if (filters.size()>1) {
+ if (filters.size() > 1) {
String all_filters;
- const int max_filters=5;
+ const int max_filters = 5;
- for(int i=0;i<MIN( max_filters, filters.size()) ;i++) {
- String flt=filters[i].get_slice(";",0);
- if (i>0)
- all_filters+=",";
- all_filters+=flt;
+ for (int i = 0; i < MIN(max_filters, filters.size()); i++) {
+ String flt = filters[i].get_slice(";", 0);
+ if (i > 0)
+ all_filters += ",";
+ all_filters += flt;
}
- if (max_filters<filters.size())
- all_filters+=", ...";
+ if (max_filters < filters.size())
+ all_filters += ", ...";
- filter->add_item(TTR("All Recognized")+" ( "+all_filters+" )");
+ filter->add_item(TTR("All Recognized") + " ( " + all_filters + " )");
}
- for(int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String flt=filters[i].get_slice(";",0).strip_edges();
- String desc=filters[i].get_slice(";",1).strip_edges();
+ String flt = filters[i].get_slice(";", 0).strip_edges();
+ String desc = filters[i].get_slice(";", 1).strip_edges();
if (desc.length())
- filter->add_item(desc+" ( "+flt+" )");
+ filter->add_item(desc + " ( " + flt + " )");
else
- filter->add_item("( "+flt+" )");
+ filter->add_item("( " + flt + " )");
}
filter->add_item(TTR("All Files (*)"));
-
}
void EditorFileDialog::clear_filters() {
@@ -770,12 +740,11 @@ void EditorFileDialog::clear_filters() {
update_filters();
invalidate();
}
-void EditorFileDialog::add_filter(const String& p_filter) {
+void EditorFileDialog::add_filter(const String &p_filter) {
filters.push_back(p_filter);
update_filters();
invalidate();
-
}
String EditorFileDialog::get_current_dir() const {
@@ -790,62 +759,77 @@ String EditorFileDialog::get_current_path() const {
return dir->get_text().plus_file(file->get_text());
}
-void EditorFileDialog::set_current_dir(const String& p_dir) {
+void EditorFileDialog::set_current_dir(const String &p_dir) {
dir_access->change_dir(p_dir);
update_dir();
invalidate();
//_push_history();
-
-
}
-void EditorFileDialog::set_current_file(const String& p_file) {
+void EditorFileDialog::set_current_file(const String &p_file) {
file->set_text(p_file);
update_dir();
invalidate();
int lp = p_file.find_last(".");
- if (lp!=-1) {
- file->select(0,lp);
+ if (lp != -1) {
+ file->select(0, lp);
file->grab_focus();
}
if (is_visible_in_tree())
_request_single_thumbnail(get_current_dir().plus_file(get_current_file()));
-
-
}
-void EditorFileDialog::set_current_path(const String& p_path) {
+void EditorFileDialog::set_current_path(const String &p_path) {
if (!p_path.size())
return;
- int pos=MAX( p_path.find_last("/"), p_path.find_last("\\") );
- if (pos==-1) {
+ int pos = MAX(p_path.find_last("/"), p_path.find_last("\\"));
+ if (pos == -1) {
set_current_file(p_path);
} else {
- String dir=p_path.substr(0,pos);
- String file=p_path.substr(pos+1,p_path.length());
+ String dir = p_path.substr(0, pos);
+ String file = p_path.substr(pos + 1, p_path.length());
set_current_dir(dir);
set_current_file(file);
}
}
-
void EditorFileDialog::set_mode(Mode p_mode) {
- mode=p_mode;
- switch(mode) {
+ mode = p_mode;
+ switch (mode) {
- case MODE_OPEN_FILE: get_ok()->set_text(TTR("Open")); set_title("Open a File"); makedir->hide(); break;
- case MODE_OPEN_FILES: get_ok()->set_text(TTR("Open")); set_title("Open File(s)"); makedir->hide(); break;
- case MODE_OPEN_DIR: get_ok()->set_text(TTR("Open")); set_title("Open a Directory"); makedir->show(); break;
- case MODE_OPEN_ANY: get_ok()->set_text(TTR("Open")); set_title("Open a File or Directory"); makedir->show(); break;
- case MODE_SAVE_FILE: get_ok()->set_text(TTR("Save")); set_title("Save a File"); makedir->show(); break;
+ case MODE_OPEN_FILE:
+ get_ok()->set_text(TTR("Open"));
+ set_title("Open a File");
+ makedir->hide();
+ break;
+ case MODE_OPEN_FILES:
+ get_ok()->set_text(TTR("Open"));
+ set_title("Open File(s)");
+ makedir->hide();
+ break;
+ case MODE_OPEN_DIR:
+ get_ok()->set_text(TTR("Open"));
+ set_title("Open a Directory");
+ makedir->show();
+ break;
+ case MODE_OPEN_ANY:
+ get_ok()->set_text(TTR("Open"));
+ set_title("Open a File or Directory");
+ makedir->show();
+ break;
+ case MODE_SAVE_FILE:
+ get_ok()->set_text(TTR("Save"));
+ set_title("Save a File");
+ makedir->show();
+ break;
}
- if (mode==MODE_OPEN_FILES) {
+ if (mode == MODE_OPEN_FILES) {
item_list->set_select_mode(ItemList::SELECT_MULTI);
} else {
item_list->set_select_mode(ItemList::SELECT_SINGLE);
@@ -859,11 +843,11 @@ EditorFileDialog::Mode EditorFileDialog::get_mode() const {
void EditorFileDialog::set_access(Access p_access) {
- ERR_FAIL_INDEX(p_access,3);
- if (access==p_access)
+ ERR_FAIL_INDEX(p_access, 3);
+ if (access == p_access)
return;
- memdelete( dir_access );
- switch(p_access) {
+ memdelete(dir_access);
+ switch (p_access) {
case ACCESS_FILESYSTEM: {
dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -877,7 +861,7 @@ void EditorFileDialog::set_access(Access p_access) {
dir_access = DirAccess::create(DirAccess::ACCESS_USERDATA);
} break;
}
- access=p_access;
+ access = p_access;
_update_drives();
invalidate();
update_filters();
@@ -888,22 +872,21 @@ void EditorFileDialog::invalidate() {
if (is_visible_in_tree()) {
update_file_list();
- invalidated=false;
+ invalidated = false;
} else {
- invalidated=true;
+ invalidated = true;
}
-
}
-EditorFileDialog::Access EditorFileDialog::get_access() const{
+EditorFileDialog::Access EditorFileDialog::get_access() const {
return access;
}
void EditorFileDialog::_make_dir_confirm() {
- Error err = dir_access->make_dir( makedirname->get_text() );
- if (err==OK) {
+ Error err = dir_access->make_dir(makedirname->get_text());
+ if (err == OK) {
dir_access->change_dir(makedirname->get_text());
invalidate();
update_filters();
@@ -911,17 +894,15 @@ void EditorFileDialog::_make_dir_confirm() {
_push_history();
} else {
- mkdirerr->popup_centered_minsize(Size2(250,50)*EDSCALE);
+ mkdirerr->popup_centered_minsize(Size2(250, 50) * EDSCALE);
}
makedirname->set_text(""); // reset label
}
-
void EditorFileDialog::_make_dir() {
- makedialog->popup_centered_minsize(Size2(250,80)*EDSCALE);
+ makedialog->popup_centered_minsize(Size2(250, 80) * EDSCALE);
makedirname->grab_focus();
-
}
void EditorFileDialog::_select_drive(int p_idx) {
@@ -932,35 +913,30 @@ void EditorFileDialog::_select_drive(int p_idx) {
invalidate();
update_dir();
_push_history();
-
-
}
void EditorFileDialog::_update_drives() {
-
int dc = dir_access->get_drive_count();
- if (dc==0 || access!=ACCESS_FILESYSTEM) {
+ if (dc == 0 || access != ACCESS_FILESYSTEM) {
drives->hide();
} else {
drives->clear();
drives->show();
- for(int i=0;i<dir_access->get_drive_count();i++) {
+ for (int i = 0; i < dir_access->get_drive_count(); i++) {
String d = dir_access->get_drive(i);
drives->add_item(dir_access->get_drive(i));
}
drives->select(dir_access->get_current_drive());
-
}
}
-
void EditorFileDialog::_favorite_selected(int p_idx) {
Vector<String> favorited = EditorSettings::get_singleton()->get_favorite_dirs();
- ERR_FAIL_INDEX(p_idx,favorited.size());
+ ERR_FAIL_INDEX(p_idx, favorited.size());
dir_access->change_dir(favorited[p_idx]);
file->set_text("");
@@ -969,105 +945,98 @@ void EditorFileDialog::_favorite_selected(int p_idx) {
_push_history();
}
-void EditorFileDialog::_favorite_move_up(){
+void EditorFileDialog::_favorite_move_up() {
int current = favorites->get_current();
- if (current>0 && current<favorites->get_item_count()) {
+ if (current > 0 && current < favorites->get_item_count()) {
Vector<String> favorited = EditorSettings::get_singleton()->get_favorite_dirs();
- int a_idx=favorited.find(String(favorites->get_item_metadata(current-1)));
- int b_idx=favorited.find(String(favorites->get_item_metadata(current)));
+ int a_idx = favorited.find(String(favorites->get_item_metadata(current - 1)));
+ int b_idx = favorited.find(String(favorites->get_item_metadata(current)));
- if (a_idx==-1 || b_idx==-1)
+ if (a_idx == -1 || b_idx == -1)
return;
- SWAP(favorited[a_idx],favorited[b_idx]);
+ SWAP(favorited[a_idx], favorited[b_idx]);
EditorSettings::get_singleton()->set_favorite_dirs(favorited);
_update_favorites();
update_file_list();
-
}
}
-void EditorFileDialog::_favorite_move_down(){
+void EditorFileDialog::_favorite_move_down() {
int current = favorites->get_current();
- if (current>=0 && current<favorites->get_item_count()-1) {
+ if (current >= 0 && current < favorites->get_item_count() - 1) {
Vector<String> favorited = EditorSettings::get_singleton()->get_favorite_dirs();
- int a_idx=favorited.find(String(favorites->get_item_metadata(current+1)));
- int b_idx=favorited.find(String(favorites->get_item_metadata(current)));
+ int a_idx = favorited.find(String(favorites->get_item_metadata(current + 1)));
+ int b_idx = favorited.find(String(favorites->get_item_metadata(current)));
- if (a_idx==-1 || b_idx==-1)
+ if (a_idx == -1 || b_idx == -1)
return;
- SWAP(favorited[a_idx],favorited[b_idx]);
+ SWAP(favorited[a_idx], favorited[b_idx]);
EditorSettings::get_singleton()->set_favorite_dirs(favorited);
_update_favorites();
update_file_list();
-
}
}
-
void EditorFileDialog::_update_favorites() {
- bool res = access==ACCESS_RESOURCES;
+ bool res = access == ACCESS_RESOURCES;
String current = get_current_dir();
- Ref<Texture> star = get_icon("Favorites","EditorIcons");
+ Ref<Texture> star = get_icon("Favorites", "EditorIcons");
favorites->clear();
favorite->set_pressed(false);
-
Vector<String> favorited = EditorSettings::get_singleton()->get_favorite_dirs();
- for(int i=0;i<favorited.size();i++) {
+ for (int i = 0; i < favorited.size(); i++) {
bool cres = favorited[i].begins_with("res://");
- if (cres!=res)
+ if (cres != res)
continue;
String name = favorited[i];
- bool setthis = name==current;
+ bool setthis = name == current;
- if (res && name=="res://") {
- name="/";
+ if (res && name == "res://") {
+ name = "/";
} else {
- name=name.get_file()+"/";
+ name = name.get_file() + "/";
}
-
//print_line("file: "+name);
- favorites->add_item(name,star);
- favorites->set_item_metadata( favorites->get_item_count()-1,favorited[i]);
+ favorites->add_item(name, star);
+ favorites->set_item_metadata(favorites->get_item_count() - 1, favorited[i]);
if (setthis) {
favorite->set_pressed(true);
- favorites->set_current(favorites->get_item_count()-1);
+ favorites->set_current(favorites->get_item_count() - 1);
}
}
-
-
}
void EditorFileDialog::_favorite_toggled(bool p_toggle) {
- bool res = access==ACCESS_RESOURCES;
+ bool res = access == ACCESS_RESOURCES;
String cd = get_current_dir();
Vector<String> favorited = EditorSettings::get_singleton()->get_favorite_dirs();
bool found = false;
- for(int i=0;i<favorited.size();i++) {
+ for (int i = 0; i < favorited.size(); i++) {
bool cres = favorited[i].begins_with("res://");
- if (cres!=res)
+ if (cres != res)
continue;
- if (favorited[i]==cd) {
- found=true;
+ if (favorited[i] == cd) {
+ found = true;
break;
}
}
@@ -1083,13 +1052,12 @@ void EditorFileDialog::_favorite_toggled(bool p_toggle) {
EditorSettings::get_singleton()->set_favorite_dirs(favorited);
_update_favorites();
-
}
void EditorFileDialog::_recent_selected(int p_idx) {
Vector<String> recentd = EditorSettings::get_singleton()->get_recent_dirs();
- ERR_FAIL_INDEX(p_idx,recentd.size());
+ ERR_FAIL_INDEX(p_idx, recentd.size());
dir_access->change_dir(recent->get_item_metadata(p_idx));
update_file_list();
@@ -1103,12 +1071,11 @@ void EditorFileDialog::_go_up() {
update_file_list();
update_dir();
_push_history();
-
}
-void EditorFileDialog::_go_back(){
+void EditorFileDialog::_go_back() {
- if (local_history_pos<=0) {
+ if (local_history_pos <= 0) {
return;
}
@@ -1117,12 +1084,12 @@ void EditorFileDialog::_go_back(){
update_file_list();
update_dir();
- dir_prev->set_disabled(local_history_pos==0);
- dir_next->set_disabled(local_history_pos==local_history.size()-1);
+ dir_prev->set_disabled(local_history_pos == 0);
+ dir_next->set_disabled(local_history_pos == local_history.size() - 1);
}
-void EditorFileDialog::_go_forward(){
+void EditorFileDialog::_go_forward() {
- if (local_history_pos==local_history.size()-1) {
+ if (local_history_pos == local_history.size() - 1) {
return;
}
@@ -1131,108 +1098,103 @@ void EditorFileDialog::_go_forward(){
update_file_list();
update_dir();
- dir_prev->set_disabled(local_history_pos==0);
- dir_next->set_disabled(local_history_pos==local_history.size()-1);
-
+ dir_prev->set_disabled(local_history_pos == 0);
+ dir_next->set_disabled(local_history_pos == local_history.size() - 1);
}
-bool EditorFileDialog::default_show_hidden_files=false;
+bool EditorFileDialog::default_show_hidden_files = false;
-EditorFileDialog::DisplayMode EditorFileDialog::default_display_mode=DISPLAY_THUMBNAILS;
+EditorFileDialog::DisplayMode EditorFileDialog::default_display_mode = DISPLAY_THUMBNAILS;
void EditorFileDialog::set_display_mode(DisplayMode p_mode) {
- if (display_mode==p_mode)
+ if (display_mode == p_mode)
return;
- if (p_mode==DISPLAY_THUMBNAILS) {
+ if (p_mode == DISPLAY_THUMBNAILS) {
mode_list->set_pressed(false);
mode_thumbnails->set_pressed(true);
} else {
mode_thumbnails->set_pressed(false);
mode_list->set_pressed(true);
}
- display_mode=p_mode;
+ display_mode = p_mode;
invalidate();
}
-EditorFileDialog::DisplayMode EditorFileDialog::get_display_mode() const{
+EditorFileDialog::DisplayMode EditorFileDialog::get_display_mode() const {
return display_mode;
}
-
-
void EditorFileDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_unhandled_input"),&EditorFileDialog::_unhandled_input);
-
- ClassDB::bind_method(D_METHOD("_item_selected"),&EditorFileDialog::_item_selected);
- ClassDB::bind_method(D_METHOD("_item_db_selected"),&EditorFileDialog::_item_dc_selected);
- ClassDB::bind_method(D_METHOD("_dir_entered"),&EditorFileDialog::_dir_entered);
- ClassDB::bind_method(D_METHOD("_file_entered"),&EditorFileDialog::_file_entered);
- ClassDB::bind_method(D_METHOD("_action_pressed"),&EditorFileDialog::_action_pressed);
- ClassDB::bind_method(D_METHOD("_cancel_pressed"),&EditorFileDialog::_cancel_pressed);
- ClassDB::bind_method(D_METHOD("_filter_selected"),&EditorFileDialog::_filter_selected);
- ClassDB::bind_method(D_METHOD("_save_confirm_pressed"),&EditorFileDialog::_save_confirm_pressed);
-
- ClassDB::bind_method(D_METHOD("clear_filters"),&EditorFileDialog::clear_filters);
- ClassDB::bind_method(D_METHOD("add_filter","filter"),&EditorFileDialog::add_filter);
- ClassDB::bind_method(D_METHOD("get_current_dir"),&EditorFileDialog::get_current_dir);
- ClassDB::bind_method(D_METHOD("get_current_file"),&EditorFileDialog::get_current_file);
- ClassDB::bind_method(D_METHOD("get_current_path"),&EditorFileDialog::get_current_path);
- ClassDB::bind_method(D_METHOD("set_current_dir","dir"),&EditorFileDialog::set_current_dir);
- ClassDB::bind_method(D_METHOD("set_current_file","file"),&EditorFileDialog::set_current_file);
- ClassDB::bind_method(D_METHOD("set_current_path","path"),&EditorFileDialog::set_current_path);
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&EditorFileDialog::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&EditorFileDialog::get_mode);
- ClassDB::bind_method(D_METHOD("get_vbox:VBoxContainer"),&EditorFileDialog::get_vbox);
- ClassDB::bind_method(D_METHOD("set_access","access"),&EditorFileDialog::set_access);
- ClassDB::bind_method(D_METHOD("get_access"),&EditorFileDialog::get_access);
- ClassDB::bind_method(D_METHOD("set_show_hidden_files","show"),&EditorFileDialog::set_show_hidden_files);
- ClassDB::bind_method(D_METHOD("is_showing_hidden_files"),&EditorFileDialog::is_showing_hidden_files);
- ClassDB::bind_method(D_METHOD("_select_drive"),&EditorFileDialog::_select_drive);
- ClassDB::bind_method(D_METHOD("_make_dir"),&EditorFileDialog::_make_dir);
- ClassDB::bind_method(D_METHOD("_make_dir_confirm"),&EditorFileDialog::_make_dir_confirm);
- ClassDB::bind_method(D_METHOD("_update_file_list"),&EditorFileDialog::update_file_list);
- ClassDB::bind_method(D_METHOD("_update_dir"),&EditorFileDialog::update_dir);
- ClassDB::bind_method(D_METHOD("_thumbnail_done"),&EditorFileDialog::_thumbnail_done);
- ClassDB::bind_method(D_METHOD("set_display_mode","mode"),&EditorFileDialog::set_display_mode);
- ClassDB::bind_method(D_METHOD("get_display_mode"),&EditorFileDialog::get_display_mode);
- ClassDB::bind_method(D_METHOD("_thumbnail_result"),&EditorFileDialog::_thumbnail_result);
- ClassDB::bind_method(D_METHOD("set_disable_overwrite_warning","disable"),&EditorFileDialog::set_disable_overwrite_warning);
- ClassDB::bind_method(D_METHOD("is_overwrite_warning_disabled"),&EditorFileDialog::is_overwrite_warning_disabled);
-
- ClassDB::bind_method(D_METHOD("_recent_selected"),&EditorFileDialog::_recent_selected);
- ClassDB::bind_method(D_METHOD("_go_back"),&EditorFileDialog::_go_back);
- ClassDB::bind_method(D_METHOD("_go_forward"),&EditorFileDialog::_go_forward);
- ClassDB::bind_method(D_METHOD("_go_up"),&EditorFileDialog::_go_up);
-
- ClassDB::bind_method(D_METHOD("_favorite_toggled"),&EditorFileDialog::_favorite_toggled);
- ClassDB::bind_method(D_METHOD("_favorite_selected"),&EditorFileDialog::_favorite_selected);
- ClassDB::bind_method(D_METHOD("_favorite_move_up"),&EditorFileDialog::_favorite_move_up);
- ClassDB::bind_method(D_METHOD("_favorite_move_down"),&EditorFileDialog::_favorite_move_down);
-
- ClassDB::bind_method(D_METHOD("invalidate"),&EditorFileDialog::invalidate);
-
- ADD_SIGNAL(MethodInfo("file_selected",PropertyInfo( Variant::STRING,"path")));
- ADD_SIGNAL(MethodInfo("files_selected",PropertyInfo( Variant::POOL_STRING_ARRAY,"paths")));
- ADD_SIGNAL(MethodInfo("dir_selected",PropertyInfo( Variant::STRING,"dir")));
-
- BIND_CONSTANT( MODE_OPEN_FILE );
- BIND_CONSTANT( MODE_OPEN_FILES );
- BIND_CONSTANT( MODE_OPEN_DIR );
- BIND_CONSTANT( MODE_OPEN_ANY );
- BIND_CONSTANT( MODE_SAVE_FILE );
-
- BIND_CONSTANT( ACCESS_RESOURCES );
- BIND_CONSTANT( ACCESS_USERDATA );
- BIND_CONSTANT( ACCESS_FILESYSTEM );
-
+ ClassDB::bind_method(D_METHOD("_unhandled_input"), &EditorFileDialog::_unhandled_input);
+
+ ClassDB::bind_method(D_METHOD("_item_selected"), &EditorFileDialog::_item_selected);
+ ClassDB::bind_method(D_METHOD("_item_db_selected"), &EditorFileDialog::_item_dc_selected);
+ ClassDB::bind_method(D_METHOD("_dir_entered"), &EditorFileDialog::_dir_entered);
+ ClassDB::bind_method(D_METHOD("_file_entered"), &EditorFileDialog::_file_entered);
+ ClassDB::bind_method(D_METHOD("_action_pressed"), &EditorFileDialog::_action_pressed);
+ ClassDB::bind_method(D_METHOD("_cancel_pressed"), &EditorFileDialog::_cancel_pressed);
+ ClassDB::bind_method(D_METHOD("_filter_selected"), &EditorFileDialog::_filter_selected);
+ ClassDB::bind_method(D_METHOD("_save_confirm_pressed"), &EditorFileDialog::_save_confirm_pressed);
+
+ ClassDB::bind_method(D_METHOD("clear_filters"), &EditorFileDialog::clear_filters);
+ ClassDB::bind_method(D_METHOD("add_filter", "filter"), &EditorFileDialog::add_filter);
+ ClassDB::bind_method(D_METHOD("get_current_dir"), &EditorFileDialog::get_current_dir);
+ ClassDB::bind_method(D_METHOD("get_current_file"), &EditorFileDialog::get_current_file);
+ ClassDB::bind_method(D_METHOD("get_current_path"), &EditorFileDialog::get_current_path);
+ ClassDB::bind_method(D_METHOD("set_current_dir", "dir"), &EditorFileDialog::set_current_dir);
+ ClassDB::bind_method(D_METHOD("set_current_file", "file"), &EditorFileDialog::set_current_file);
+ ClassDB::bind_method(D_METHOD("set_current_path", "path"), &EditorFileDialog::set_current_path);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &EditorFileDialog::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &EditorFileDialog::get_mode);
+ ClassDB::bind_method(D_METHOD("get_vbox:VBoxContainer"), &EditorFileDialog::get_vbox);
+ ClassDB::bind_method(D_METHOD("set_access", "access"), &EditorFileDialog::set_access);
+ ClassDB::bind_method(D_METHOD("get_access"), &EditorFileDialog::get_access);
+ ClassDB::bind_method(D_METHOD("set_show_hidden_files", "show"), &EditorFileDialog::set_show_hidden_files);
+ ClassDB::bind_method(D_METHOD("is_showing_hidden_files"), &EditorFileDialog::is_showing_hidden_files);
+ ClassDB::bind_method(D_METHOD("_select_drive"), &EditorFileDialog::_select_drive);
+ ClassDB::bind_method(D_METHOD("_make_dir"), &EditorFileDialog::_make_dir);
+ ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &EditorFileDialog::_make_dir_confirm);
+ ClassDB::bind_method(D_METHOD("_update_file_list"), &EditorFileDialog::update_file_list);
+ ClassDB::bind_method(D_METHOD("_update_dir"), &EditorFileDialog::update_dir);
+ ClassDB::bind_method(D_METHOD("_thumbnail_done"), &EditorFileDialog::_thumbnail_done);
+ ClassDB::bind_method(D_METHOD("set_display_mode", "mode"), &EditorFileDialog::set_display_mode);
+ ClassDB::bind_method(D_METHOD("get_display_mode"), &EditorFileDialog::get_display_mode);
+ ClassDB::bind_method(D_METHOD("_thumbnail_result"), &EditorFileDialog::_thumbnail_result);
+ ClassDB::bind_method(D_METHOD("set_disable_overwrite_warning", "disable"), &EditorFileDialog::set_disable_overwrite_warning);
+ ClassDB::bind_method(D_METHOD("is_overwrite_warning_disabled"), &EditorFileDialog::is_overwrite_warning_disabled);
+
+ ClassDB::bind_method(D_METHOD("_recent_selected"), &EditorFileDialog::_recent_selected);
+ ClassDB::bind_method(D_METHOD("_go_back"), &EditorFileDialog::_go_back);
+ ClassDB::bind_method(D_METHOD("_go_forward"), &EditorFileDialog::_go_forward);
+ ClassDB::bind_method(D_METHOD("_go_up"), &EditorFileDialog::_go_up);
+
+ ClassDB::bind_method(D_METHOD("_favorite_toggled"), &EditorFileDialog::_favorite_toggled);
+ ClassDB::bind_method(D_METHOD("_favorite_selected"), &EditorFileDialog::_favorite_selected);
+ ClassDB::bind_method(D_METHOD("_favorite_move_up"), &EditorFileDialog::_favorite_move_up);
+ ClassDB::bind_method(D_METHOD("_favorite_move_down"), &EditorFileDialog::_favorite_move_down);
+
+ ClassDB::bind_method(D_METHOD("invalidate"), &EditorFileDialog::invalidate);
+
+ ADD_SIGNAL(MethodInfo("file_selected", PropertyInfo(Variant::STRING, "path")));
+ ADD_SIGNAL(MethodInfo("files_selected", PropertyInfo(Variant::POOL_STRING_ARRAY, "paths")));
+ ADD_SIGNAL(MethodInfo("dir_selected", PropertyInfo(Variant::STRING, "dir")));
+
+ BIND_CONSTANT(MODE_OPEN_FILE);
+ BIND_CONSTANT(MODE_OPEN_FILES);
+ BIND_CONSTANT(MODE_OPEN_DIR);
+ BIND_CONSTANT(MODE_OPEN_ANY);
+ BIND_CONSTANT(MODE_SAVE_FILE);
+
+ BIND_CONSTANT(ACCESS_RESOURCES);
+ BIND_CONSTANT(ACCESS_USERDATA);
+ BIND_CONSTANT(ACCESS_FILESYSTEM);
}
-
void EditorFileDialog::set_show_hidden_files(bool p_show) {
- show_hidden_files=p_show;
+ show_hidden_files = p_show;
invalidate();
}
@@ -1241,11 +1203,11 @@ bool EditorFileDialog::is_showing_hidden_files() const {
}
void EditorFileDialog::set_default_show_hidden_files(bool p_show) {
- default_show_hidden_files=p_show;
+ default_show_hidden_files = p_show;
}
void EditorFileDialog::set_default_display_mode(DisplayMode p_mode) {
- default_display_mode=p_mode;
+ default_display_mode = p_mode;
}
void EditorFileDialog::_save_to_recent() {
@@ -1253,13 +1215,13 @@ void EditorFileDialog::_save_to_recent() {
String dir = get_current_dir();
Vector<String> recent = EditorSettings::get_singleton()->get_recent_dirs();
- const int max=20;
- int count=0;
- bool res=dir.begins_with("res://");
+ const int max = 20;
+ int count = 0;
+ bool res = dir.begins_with("res://");
- for(int i=0;i<recent.size();i++) {
- bool cres=recent[i].begins_with("res://");
- if (recent[i]==dir || (res==cres && count>max)) {
+ for (int i = 0; i < recent.size(); i++) {
+ bool cres = recent[i].begins_with("res://");
+ if (recent[i] == dir || (res == cres && count > max)) {
recent.remove(i);
i--;
} else {
@@ -1267,222 +1229,210 @@ void EditorFileDialog::_save_to_recent() {
}
}
- recent.insert(0,dir);
+ recent.insert(0, dir);
EditorSettings::get_singleton()->set_recent_dirs(recent);
-
-
}
void EditorFileDialog::set_disable_overwrite_warning(bool p_disable) {
- disable_overwrite_warning=p_disable;
+ disable_overwrite_warning = p_disable;
}
-bool EditorFileDialog::is_overwrite_warning_disabled() const{
+bool EditorFileDialog::is_overwrite_warning_disabled() const {
return disable_overwrite_warning;
}
-
EditorFileDialog::EditorFileDialog() {
- show_hidden_files=default_show_hidden_files;
- display_mode=default_display_mode;
- local_history_pos=0;
- disable_overwrite_warning=false;
- VBoxContainer *vbc = memnew( VBoxContainer );
+ show_hidden_files = default_show_hidden_files;
+ display_mode = default_display_mode;
+ local_history_pos = 0;
+ disable_overwrite_warning = false;
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
- mode=MODE_SAVE_FILE;
+ mode = MODE_SAVE_FILE;
set_title(TTR("Save a File"));
- ED_SHORTCUT("file_dialog/go_back", TTR("Go Back"), KEY_MASK_ALT|KEY_LEFT);
- ED_SHORTCUT("file_dialog/go_forward", TTR("Go Forward"), KEY_MASK_ALT|KEY_RIGHT);
- ED_SHORTCUT("file_dialog/go_up", TTR("Go Up"), KEY_MASK_ALT|KEY_UP);
+ ED_SHORTCUT("file_dialog/go_back", TTR("Go Back"), KEY_MASK_ALT | KEY_LEFT);
+ ED_SHORTCUT("file_dialog/go_forward", TTR("Go Forward"), KEY_MASK_ALT | KEY_RIGHT);
+ ED_SHORTCUT("file_dialog/go_up", TTR("Go Up"), KEY_MASK_ALT | KEY_UP);
ED_SHORTCUT("file_dialog/refresh", TTR("Refresh"), KEY_F5);
- ED_SHORTCUT("file_dialog/toggle_hidden_files", TTR("Toggle Hidden Files"), KEY_MASK_CMD|KEY_H);
- ED_SHORTCUT("file_dialog/toggle_favorite", TTR("Toggle Favorite"), KEY_MASK_ALT|KEY_F);
- ED_SHORTCUT("file_dialog/toggle_mode", TTR("Toggle Mode"), KEY_MASK_ALT|KEY_V);
- ED_SHORTCUT("file_dialog/create_folder", TTR("Create Folder"), KEY_MASK_CMD|KEY_N);
- ED_SHORTCUT("file_dialog/focus_path", TTR("Focus Path"), KEY_MASK_CMD|KEY_D);
- ED_SHORTCUT("file_dialog/move_favorite_up", TTR("Move Favorite Up"), KEY_MASK_CMD|KEY_UP);
- ED_SHORTCUT("file_dialog/move_favorite_down", TTR("Move Favorite Down"), KEY_MASK_CMD|KEY_DOWN);
+ ED_SHORTCUT("file_dialog/toggle_hidden_files", TTR("Toggle Hidden Files"), KEY_MASK_CMD | KEY_H);
+ ED_SHORTCUT("file_dialog/toggle_favorite", TTR("Toggle Favorite"), KEY_MASK_ALT | KEY_F);
+ ED_SHORTCUT("file_dialog/toggle_mode", TTR("Toggle Mode"), KEY_MASK_ALT | KEY_V);
+ ED_SHORTCUT("file_dialog/create_folder", TTR("Create Folder"), KEY_MASK_CMD | KEY_N);
+ ED_SHORTCUT("file_dialog/focus_path", TTR("Focus Path"), KEY_MASK_CMD | KEY_D);
+ ED_SHORTCUT("file_dialog/move_favorite_up", TTR("Move Favorite Up"), KEY_MASK_CMD | KEY_UP);
+ ED_SHORTCUT("file_dialog/move_favorite_down", TTR("Move Favorite Down"), KEY_MASK_CMD | KEY_DOWN);
- HBoxContainer *pathhb = memnew( HBoxContainer );
+ HBoxContainer *pathhb = memnew(HBoxContainer);
- dir_prev = memnew( ToolButton );
- dir_next = memnew( ToolButton );
- dir_up = memnew( ToolButton );
+ dir_prev = memnew(ToolButton);
+ dir_next = memnew(ToolButton);
+ dir_up = memnew(ToolButton);
pathhb->add_child(dir_prev);
pathhb->add_child(dir_next);
pathhb->add_child(dir_up);
- dir_prev->connect("pressed",this,"_go_back");
- dir_next->connect("pressed",this,"_go_forward");
- dir_up->connect("pressed",this,"_go_up");
+ dir_prev->connect("pressed", this, "_go_back");
+ dir_next->connect("pressed", this, "_go_forward");
+ dir_up->connect("pressed", this, "_go_up");
dir = memnew(LineEdit);
pathhb->add_child(dir);
dir->set_h_size_flags(SIZE_EXPAND_FILL);
- refresh = memnew( ToolButton );
- refresh->connect("pressed",this,"_update_file_list");
+ refresh = memnew(ToolButton);
+ refresh->connect("pressed", this, "_update_file_list");
pathhb->add_child(refresh);
- favorite = memnew( ToolButton );
+ favorite = memnew(ToolButton);
favorite->set_toggle_mode(true);
- favorite->connect("toggled",this,"_favorite_toggled");
+ favorite->connect("toggled", this, "_favorite_toggled");
pathhb->add_child(favorite);
- mode_thumbnails = memnew( ToolButton );
- mode_thumbnails->connect("pressed",this,"set_display_mode",varray(DISPLAY_THUMBNAILS));
+ mode_thumbnails = memnew(ToolButton);
+ mode_thumbnails->connect("pressed", this, "set_display_mode", varray(DISPLAY_THUMBNAILS));
mode_thumbnails->set_toggle_mode(true);
- mode_thumbnails->set_pressed(display_mode==DISPLAY_THUMBNAILS);
+ mode_thumbnails->set_pressed(display_mode == DISPLAY_THUMBNAILS);
pathhb->add_child(mode_thumbnails);
- mode_list = memnew( ToolButton );
- mode_list->connect("pressed",this,"set_display_mode",varray(DISPLAY_LIST));
+ mode_list = memnew(ToolButton);
+ mode_list->connect("pressed", this, "set_display_mode", varray(DISPLAY_LIST));
mode_list->set_toggle_mode(true);
- mode_list->set_pressed(display_mode==DISPLAY_LIST);
+ mode_list->set_pressed(display_mode == DISPLAY_LIST);
pathhb->add_child(mode_list);
- drives = memnew( OptionButton );
+ drives = memnew(OptionButton);
pathhb->add_child(drives);
- drives->connect("item_selected",this,"_select_drive");
+ drives->connect("item_selected", this, "_select_drive");
- makedir = memnew( Button );
+ makedir = memnew(Button);
makedir->set_text(TTR("Create Folder"));
- makedir->connect("pressed",this,"_make_dir");
+ makedir->connect("pressed", this, "_make_dir");
pathhb->add_child(makedir);
- list_hb = memnew( HBoxContainer );
+ list_hb = memnew(HBoxContainer);
- vbc->add_margin_child(TTR("Path:"),pathhb);
+ vbc->add_margin_child(TTR("Path:"), pathhb);
vbc->add_child(list_hb);
list_hb->set_v_size_flags(SIZE_EXPAND_FILL);
- VBoxContainer *fav_vb = memnew( VBoxContainer );
+ VBoxContainer *fav_vb = memnew(VBoxContainer);
list_hb->add_child(fav_vb);
- HBoxContainer *fav_hb = memnew( HBoxContainer );
+ HBoxContainer *fav_hb = memnew(HBoxContainer);
fav_vb->add_child(fav_hb);
fav_hb->add_child(memnew(Label(TTR("Favorites:"))));
fav_hb->add_spacer();
- fav_up = memnew( ToolButton );
+ fav_up = memnew(ToolButton);
fav_hb->add_child(fav_up);
- fav_up->connect("pressed",this,"_favorite_move_up");
- fav_down = memnew( ToolButton );
+ fav_up->connect("pressed", this, "_favorite_move_up");
+ fav_down = memnew(ToolButton);
fav_hb->add_child(fav_down);
- fav_down->connect("pressed",this,"_favorite_move_down");
- fav_rm = memnew( ToolButton );
+ fav_down->connect("pressed", this, "_favorite_move_down");
+ fav_rm = memnew(ToolButton);
fav_hb->add_child(fav_rm);
fav_rm->hide(); // redundant
- MarginContainer *fav_mv = memnew( MarginContainer );
+ MarginContainer *fav_mv = memnew(MarginContainer);
fav_vb->add_child(fav_mv);
fav_mv->set_v_size_flags(SIZE_EXPAND_FILL);
- favorites = memnew( ItemList );
+ favorites = memnew(ItemList);
fav_mv->add_child(favorites);
- favorites->connect("item_selected",this,"_favorite_selected");
+ favorites->connect("item_selected", this, "_favorite_selected");
- recent = memnew( ItemList );
- fav_vb->add_margin_child(TTR("Recent:"),recent,true);
- recent->connect("item_selected",this,"_recent_selected");
+ recent = memnew(ItemList);
+ fav_vb->add_margin_child(TTR("Recent:"), recent, true);
+ recent->connect("item_selected", this, "_recent_selected");
- VBoxContainer *item_vb = memnew( VBoxContainer );
+ VBoxContainer *item_vb = memnew(VBoxContainer);
list_hb->add_child(item_vb);
item_vb->set_h_size_flags(SIZE_EXPAND_FILL);
- item_list = memnew( ItemList );
+ item_list = memnew(ItemList);
item_list->set_v_size_flags(SIZE_EXPAND_FILL);
- item_vb->add_margin_child(TTR("Directories & Files:"),item_list,true);
+ item_vb->add_margin_child(TTR("Directories & Files:"), item_list, true);
- HBoxContainer* filter_hb = memnew( HBoxContainer );
+ HBoxContainer *filter_hb = memnew(HBoxContainer);
item_vb->add_child(filter_hb);
- VBoxContainer *filter_vb = memnew( VBoxContainer );
+ VBoxContainer *filter_vb = memnew(VBoxContainer);
filter_hb->add_child(filter_vb);
filter_vb->set_h_size_flags(SIZE_EXPAND_FILL);
- preview_vb = memnew( VBoxContainer );
+ preview_vb = memnew(VBoxContainer);
filter_hb->add_child(preview_vb);
- CenterContainer *prev_cc = memnew( CenterContainer );
- preview_vb->add_margin_child(TTR("Preview:"),prev_cc);
- preview = memnew( TextureRect );
+ CenterContainer *prev_cc = memnew(CenterContainer);
+ preview_vb->add_margin_child(TTR("Preview:"), prev_cc);
+ preview = memnew(TextureRect);
prev_cc->add_child(preview);
preview_vb->hide();
-
file = memnew(LineEdit);
//add_child(file);
- filter_vb->add_margin_child(TTR("File:"),file);
-
+ filter_vb->add_margin_child(TTR("File:"), file);
- filter = memnew( OptionButton );
+ filter = memnew(OptionButton);
//add_child(filter);
- filter_vb->add_margin_child(TTR("Filter:"),filter);
- filter->set_clip_text(true);//too many extensions overflow it
+ filter_vb->add_margin_child(TTR("Filter:"), filter);
+ filter->set_clip_text(true); //too many extensions overflow it
dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- access=ACCESS_RESOURCES;
+ access = ACCESS_RESOURCES;
_update_drives();
-
- connect("confirmed", this,"_action_pressed");
+ connect("confirmed", this, "_action_pressed");
//cancel->connect("pressed", this,"_cancel_pressed");
- item_list->connect("item_selected", this,"_item_selected",varray(),CONNECT_DEFERRED);
- item_list->connect("item_activated", this,"_item_db_selected",varray());
- dir->connect("text_entered", this,"_dir_entered");
- file->connect("text_entered", this,"_file_entered");
- filter->connect("item_selected", this,"_filter_selected");
-
+ item_list->connect("item_selected", this, "_item_selected", varray(), CONNECT_DEFERRED);
+ item_list->connect("item_activated", this, "_item_db_selected", varray());
+ dir->connect("text_entered", this, "_dir_entered");
+ file->connect("text_entered", this, "_file_entered");
+ filter->connect("item_selected", this, "_filter_selected");
- confirm_save = memnew( ConfirmationDialog );
+ confirm_save = memnew(ConfirmationDialog);
confirm_save->set_as_toplevel(true);
add_child(confirm_save);
+ confirm_save->connect("confirmed", this, "_save_confirm_pressed");
- confirm_save->connect("confirmed", this,"_save_confirm_pressed");
-
- makedialog = memnew( ConfirmationDialog );
+ makedialog = memnew(ConfirmationDialog);
makedialog->set_title(TTR("Create Folder"));
- VBoxContainer *makevb= memnew( VBoxContainer );
+ VBoxContainer *makevb = memnew(VBoxContainer);
makedialog->add_child(makevb);
- makedirname = memnew( LineEdit );
- makevb->add_margin_child(TTR("Name:"),makedirname);
+ makedirname = memnew(LineEdit);
+ makevb->add_margin_child(TTR("Name:"), makedirname);
add_child(makedialog);
makedialog->register_text_enter(makedirname);
- makedialog->connect("confirmed",this,"_make_dir_confirm");
- mkdirerr = memnew( AcceptDialog );
+ makedialog->connect("confirmed", this, "_make_dir_confirm");
+ mkdirerr = memnew(AcceptDialog);
mkdirerr->set_text(TTR("Could not create folder."));
add_child(mkdirerr);
- exterr = memnew( AcceptDialog );
+ exterr = memnew(AcceptDialog);
exterr->set_text(TTR("Must use a valid extension."));
add_child(exterr);
-
//update_file_list();
update_filters();
update_dir();
set_hide_on_ok(false);
- vbox=vbc;
-
+ vbox = vbc;
- invalidated=true;
+ invalidated = true;
if (register_func)
register_func(this);
- preview_wheel_timeout=0;
- preview_wheel_index=0;
- preview_waiting=false;
-
+ preview_wheel_timeout = 0;
+ preview_wheel_index = 0;
+ preview_waiting = false;
}
-
EditorFileDialog::~EditorFileDialog() {
if (unregister_func)
@@ -1490,21 +1440,19 @@ EditorFileDialog::~EditorFileDialog() {
memdelete(dir_access);
}
-
void EditorLineEditFileChooser::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_browse"),&EditorLineEditFileChooser::_browse);
- ClassDB::bind_method(D_METHOD("_chosen"),&EditorLineEditFileChooser::_chosen);
- ClassDB::bind_method(D_METHOD("get_button:Button"),&EditorLineEditFileChooser::get_button);
- ClassDB::bind_method(D_METHOD("get_line_edit:LineEdit"),&EditorLineEditFileChooser::get_line_edit);
- ClassDB::bind_method(D_METHOD("get_file_dialog:EditorFileDialog"),&EditorLineEditFileChooser::get_file_dialog);
-
+ ClassDB::bind_method(D_METHOD("_browse"), &EditorLineEditFileChooser::_browse);
+ ClassDB::bind_method(D_METHOD("_chosen"), &EditorLineEditFileChooser::_chosen);
+ ClassDB::bind_method(D_METHOD("get_button:Button"), &EditorLineEditFileChooser::get_button);
+ ClassDB::bind_method(D_METHOD("get_line_edit:LineEdit"), &EditorLineEditFileChooser::get_line_edit);
+ ClassDB::bind_method(D_METHOD("get_file_dialog:EditorFileDialog"), &EditorLineEditFileChooser::get_file_dialog);
}
-void EditorLineEditFileChooser::_chosen(const String& p_text){
+void EditorLineEditFileChooser::_chosen(const String &p_text) {
line_edit->set_text(p_text);
- line_edit->emit_signal("text_entered",p_text);
+ line_edit->emit_signal("text_entered", p_text);
}
void EditorLineEditFileChooser::_browse() {
@@ -1514,18 +1462,16 @@ void EditorLineEditFileChooser::_browse() {
EditorLineEditFileChooser::EditorLineEditFileChooser() {
- line_edit = memnew( LineEdit );
+ line_edit = memnew(LineEdit);
add_child(line_edit);
line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
- button = memnew( Button );
+ button = memnew(Button);
button->set_text(" .. ");
add_child(button);
- button->connect("pressed",this,"_browse");
- dialog = memnew( EditorFileDialog);
+ button->connect("pressed", this, "_browse");
+ dialog = memnew(EditorFileDialog);
add_child(dialog);
- dialog->connect("file_selected",this,"_chosen");
- dialog->connect("dir_selected",this,"_chosen");
- dialog->connect("files_selected",this,"_chosen");
-
-
+ dialog->connect("file_selected", this, "_chosen");
+ dialog->connect("dir_selected", this, "_chosen");
+ dialog->connect("files_selected", this, "_chosen");
}
diff --git a/editor/editor_file_dialog.h b/editor/editor_file_dialog.h
index 193cbc513c..6c1bf08a40 100644
--- a/editor/editor_file_dialog.h
+++ b/editor/editor_file_dialog.h
@@ -29,12 +29,12 @@
#ifndef EDITORFILEDIALOG_H
#define EDITORFILEDIALOG_H
+#include "os/dir_access.h"
+#include "scene/gui/box_container.h"
#include "scene/gui/dialogs.h"
#include "scene/gui/item_list.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/option_button.h"
-#include "os/dir_access.h"
-#include "scene/gui/box_container.h"
#include "scene/gui/texture_rect.h"
#include "scene/gui/tool_button.h"
/**
@@ -42,23 +42,20 @@
*/
class EditorFileDialog : public ConfirmationDialog {
- GDCLASS( EditorFileDialog, ConfirmationDialog );
+ GDCLASS(EditorFileDialog, ConfirmationDialog);
public:
-
enum DisplayMode {
DISPLAY_THUMBNAILS,
DISPLAY_LIST
};
-
enum Access {
ACCESS_RESOURCES,
ACCESS_USERDATA,
ACCESS_FILESYSTEM
};
-
enum Mode {
MODE_OPEN_FILE,
MODE_OPEN_FILES,
@@ -67,8 +64,8 @@ public:
MODE_SAVE_FILE
};
- typedef Ref<Texture> (*GetIconFunc)(const String&);
- typedef void (*RegisterFunc)(EditorFileDialog*);
+ typedef Ref<Texture> (*GetIconFunc)(const String &);
+ typedef void (*RegisterFunc)(EditorFileDialog *);
static GetIconFunc get_icon_func;
static GetIconFunc get_large_icon_func;
@@ -76,7 +73,6 @@ public:
static RegisterFunc unregister_func;
private:
-
ConfirmationDialog *makedialog;
LineEdit *makedirname;
@@ -105,7 +101,6 @@ private:
ToolButton *mode_thumbnails;
ToolButton *mode_list;
-
ToolButton *refresh;
ToolButton *favorite;
@@ -143,8 +138,6 @@ private:
void _favorite_move_up();
void _favorite_move_down();
-
-
void _recent_selected(int p_idx);
void _item_selected(int p_item);
@@ -152,7 +145,7 @@ private:
void _select_drive(int p_idx);
void _dir_entered(String p_dir);
- void _file_entered(const String& p_file);
+ void _file_entered(const String &p_file);
void _action_pressed();
void _save_confirm_pressed();
void _cancel_pressed();
@@ -171,21 +164,19 @@ private:
void _save_to_recent();
//callback funtion is callback(String p_path,Ref<Texture> preview,Variant udata) preview null if could not load
- void _thumbnail_result(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata);
- void _thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata);
- void _request_single_thumbnail(const String& p_path);
+ void _thumbnail_result(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata);
+ void _thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata);
+ void _request_single_thumbnail(const String &p_path);
- void _unhandled_input(const InputEvent& p_event);
+ void _unhandled_input(const InputEvent &p_event);
protected:
-
void _notification(int p_what);
static void _bind_methods();
//bind helpers
public:
-
void clear_filters();
- void add_filter(const String& p_filter);
+ void add_filter(const String &p_filter);
void set_enable_multiple_selection(bool p_enable);
Vector<String> get_selected_files() const;
@@ -193,9 +184,9 @@ public:
String get_current_dir() const;
String get_current_file() const;
String get_current_path() const;
- void set_current_dir(const String& p_dir);
- void set_current_file(const String& p_file);
- void set_current_path(const String& p_path);
+ void set_current_dir(const String &p_dir);
+ void set_current_file(const String &p_file);
+ void set_current_path(const String &p_path);
void set_display_mode(DisplayMode p_mode);
DisplayMode get_display_mode() const;
@@ -222,22 +213,22 @@ public:
EditorFileDialog();
~EditorFileDialog();
-
};
class EditorLineEditFileChooser : public HBoxContainer {
- GDCLASS( EditorLineEditFileChooser, HBoxContainer );
+ GDCLASS(EditorLineEditFileChooser, HBoxContainer);
Button *button;
LineEdit *line_edit;
EditorFileDialog *dialog;
- void _chosen(const String& p_text);
+ void _chosen(const String &p_text);
void _browse();
+
protected:
static void _bind_methods();
-public:
+public:
Button *get_button() { return button; }
LineEdit *get_line_edit() { return line_edit; }
EditorFileDialog *get_file_dialog() { return dialog; }
@@ -245,8 +236,8 @@ public:
EditorLineEditFileChooser();
};
-VARIANT_ENUM_CAST( EditorFileDialog::Mode );
-VARIANT_ENUM_CAST( EditorFileDialog::Access );
-VARIANT_ENUM_CAST( EditorFileDialog::DisplayMode );
+VARIANT_ENUM_CAST(EditorFileDialog::Mode);
+VARIANT_ENUM_CAST(EditorFileDialog::Access);
+VARIANT_ENUM_CAST(EditorFileDialog::DisplayMode);
#endif // EDITORFILEDIALOG_H
diff --git a/editor/editor_file_system.cpp b/editor/editor_file_system.cpp
index cd151cd90b..b188a5760b 100644
--- a/editor/editor_file_system.cpp
+++ b/editor/editor_file_system.cpp
@@ -28,65 +28,61 @@
/*************************************************************************/
#include "editor_file_system.h"
+#include "editor_node.h"
+#include "editor_resource_preview.h"
+#include "editor_settings.h"
#include "global_config.h"
+#include "io/resource_import.h"
#include "io/resource_loader.h"
-#include "os/os.h"
-#include "os/file_access.h"
-#include "editor_node.h"
#include "io/resource_saver.h"
-#include "io/resource_import.h"
-#include "editor_settings.h"
-#include "editor_resource_preview.h"
+#include "os/file_access.h"
+#include "os/os.h"
#include "variant_parser.h"
-EditorFileSystem *EditorFileSystem::singleton=NULL;
+EditorFileSystem *EditorFileSystem::singleton = NULL;
void EditorFileSystemDirectory::sort_files() {
files.sort_custom<FileInfoSort>();
}
-int EditorFileSystemDirectory::find_file_index(const String& p_file) const {
+int EditorFileSystemDirectory::find_file_index(const String &p_file) const {
- for(int i=0;i<files.size();i++) {
- if (files[i]->file==p_file)
+ for (int i = 0; i < files.size(); i++) {
+ if (files[i]->file == p_file)
return i;
}
return -1;
-
}
-int EditorFileSystemDirectory::find_dir_index(const String& p_dir) const{
+int EditorFileSystemDirectory::find_dir_index(const String &p_dir) const {
-
- for(int i=0;i<subdirs.size();i++) {
- if (subdirs[i]->name==p_dir)
+ for (int i = 0; i < subdirs.size(); i++) {
+ if (subdirs[i]->name == p_dir)
return i;
}
return -1;
}
-
int EditorFileSystemDirectory::get_subdir_count() const {
return subdirs.size();
}
-EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx){
+EditorFileSystemDirectory *EditorFileSystemDirectory::get_subdir(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,subdirs.size(),NULL);
+ ERR_FAIL_INDEX_V(p_idx, subdirs.size(), NULL);
return subdirs[p_idx];
-
}
-int EditorFileSystemDirectory::get_file_count() const{
+int EditorFileSystemDirectory::get_file_count() const {
return files.size();
}
-String EditorFileSystemDirectory::get_file(int p_idx) const{
+String EditorFileSystemDirectory::get_file(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,files.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->file;
}
@@ -94,41 +90,36 @@ String EditorFileSystemDirectory::get_file(int p_idx) const{
String EditorFileSystemDirectory::get_path() const {
String p;
- const EditorFileSystemDirectory *d=this;
- while(d->parent) {
- p=d->name+"/"+p;
- d=d->parent;
+ const EditorFileSystemDirectory *d = this;
+ while (d->parent) {
+ p = d->name + "/" + p;
+ d = d->parent;
}
- return "res://"+p;
-
+ return "res://" + p;
}
-
String EditorFileSystemDirectory::get_file_path(int p_idx) const {
String file = get_file(p_idx);
- const EditorFileSystemDirectory *d=this;
- while(d->parent) {
- file=d->name+"/"+file;
- d=d->parent;
+ const EditorFileSystemDirectory *d = this;
+ while (d->parent) {
+ file = d->name + "/" + file;
+ d = d->parent;
}
- return "res://"+file;
+ return "res://" + file;
}
-
Vector<String> EditorFileSystemDirectory::get_file_deps(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,files.size(),Vector<String>());
+ ERR_FAIL_INDEX_V(p_idx, files.size(), Vector<String>());
return files[p_idx]->deps;
-
}
-
StringName EditorFileSystemDirectory::get_file_type(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,files.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, files.size(), "");
return files[p_idx]->type;
}
@@ -144,45 +135,38 @@ EditorFileSystemDirectory *EditorFileSystemDirectory::get_parent() {
void EditorFileSystemDirectory::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_subdir_count"),&EditorFileSystemDirectory::get_subdir_count);
- ClassDB::bind_method(D_METHOD("get_subdir","idx"),&EditorFileSystemDirectory::get_subdir);
- ClassDB::bind_method(D_METHOD("get_file_count"),&EditorFileSystemDirectory::get_file_count);
- ClassDB::bind_method(D_METHOD("get_file","idx"),&EditorFileSystemDirectory::get_file);
- ClassDB::bind_method(D_METHOD("get_file_path","idx"),&EditorFileSystemDirectory::get_file_path);
- ClassDB::bind_method(D_METHOD("get_file_type","idx"),&EditorFileSystemDirectory::get_file_type);
- ClassDB::bind_method(D_METHOD("get_name"),&EditorFileSystemDirectory::get_name);
- ClassDB::bind_method(D_METHOD("get_path"),&EditorFileSystemDirectory::get_path);
- ClassDB::bind_method(D_METHOD("get_parent:EditorFileSystemDirectory"),&EditorFileSystemDirectory::get_parent);
- ClassDB::bind_method(D_METHOD("find_file_index","name"),&EditorFileSystemDirectory::find_file_index);
- ClassDB::bind_method(D_METHOD("find_dir_index","name"),&EditorFileSystemDirectory::find_dir_index);
-
-
+ ClassDB::bind_method(D_METHOD("get_subdir_count"), &EditorFileSystemDirectory::get_subdir_count);
+ ClassDB::bind_method(D_METHOD("get_subdir", "idx"), &EditorFileSystemDirectory::get_subdir);
+ ClassDB::bind_method(D_METHOD("get_file_count"), &EditorFileSystemDirectory::get_file_count);
+ ClassDB::bind_method(D_METHOD("get_file", "idx"), &EditorFileSystemDirectory::get_file);
+ ClassDB::bind_method(D_METHOD("get_file_path", "idx"), &EditorFileSystemDirectory::get_file_path);
+ ClassDB::bind_method(D_METHOD("get_file_type", "idx"), &EditorFileSystemDirectory::get_file_type);
+ ClassDB::bind_method(D_METHOD("get_name"), &EditorFileSystemDirectory::get_name);
+ ClassDB::bind_method(D_METHOD("get_path"), &EditorFileSystemDirectory::get_path);
+ ClassDB::bind_method(D_METHOD("get_parent:EditorFileSystemDirectory"), &EditorFileSystemDirectory::get_parent);
+ ClassDB::bind_method(D_METHOD("find_file_index", "name"), &EditorFileSystemDirectory::find_file_index);
+ ClassDB::bind_method(D_METHOD("find_dir_index", "name"), &EditorFileSystemDirectory::find_dir_index);
}
-
EditorFileSystemDirectory::EditorFileSystemDirectory() {
- modified_time=0;
- parent=NULL;
+ modified_time = 0;
+ parent = NULL;
}
EditorFileSystemDirectory::~EditorFileSystemDirectory() {
- for(int i=0;i<files.size();i++) {
+ for (int i = 0; i < files.size(); i++) {
memdelete(files[i]);
}
- for(int i=0;i<subdirs.size();i++) {
+ for (int i = 0; i < subdirs.size(); i++) {
memdelete(subdirs[i]);
}
}
-
-
-
-
void EditorFileSystem::_scan_filesystem() {
ERR_FAIL_COND(!scanning || new_filesystem);
@@ -193,335 +177,316 @@ void EditorFileSystem::_scan_filesystem() {
sources_changed.clear();
file_cache.clear();
- String project=GlobalConfig::get_singleton()->get_resource_path();
+ String project = GlobalConfig::get_singleton()->get_resource_path();
String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache2");
- FileAccess *f =FileAccess::open(fscache,FileAccess::READ);
+ FileAccess *f = FileAccess::open(fscache, FileAccess::READ);
if (f) {
//read the disk cache
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
- if (l==String())
+ if (l == String())
continue;
if (l.begins_with("::")) {
Vector<String> split = l.split("::");
- ERR_CONTINUE( split.size() != 3);
+ ERR_CONTINUE(split.size() != 3);
String name = split[1];
- cpath=name;
+ cpath = name;
} else {
Vector<String> split = l.split("::");
- ERR_CONTINUE( split.size() != 5);
+ ERR_CONTINUE(split.size() != 5);
String name = split[0];
String file;
- file=name;
- name=cpath.plus_file(name);
+ file = name;
+ name = cpath.plus_file(name);
FileCache fc;
- fc.type=split[1];
- fc.modification_time=split[2].to_int64();
+ fc.type = split[1];
+ fc.modification_time = split[2].to_int64();
fc.import_modification_time = split[3].to_int64();
String deps = split[4].strip_edges();
if (deps.length()) {
Vector<String> dp = deps.split("<>");
- for(int i=0;i<dp.size();i++) {
- String path=dp[i];
+ for (int i = 0; i < dp.size(); i++) {
+ String path = dp[i];
fc.deps.push_back(path);
}
}
- file_cache[name]=fc;
-
+ file_cache[name] = fc;
}
-
}
f->close();
memdelete(f);
}
-
-
- EditorProgressBG scan_progress("efs","ScanFS",1000);
+ EditorProgressBG scan_progress("efs", "ScanFS", 1000);
ScanProgress sp;
- sp.low=0;
- sp.hi=1;
- sp.progress=&scan_progress;
-
+ sp.low = 0;
+ sp.hi = 1;
+ sp.progress = &scan_progress;
- new_filesystem = memnew( EditorFileSystemDirectory );
- new_filesystem->parent=NULL;
+ new_filesystem = memnew(EditorFileSystemDirectory);
+ new_filesystem->parent = NULL;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir("res://");
- _scan_new_dir(new_filesystem,d,sp);
+ _scan_new_dir(new_filesystem, d, sp);
file_cache.clear(); //clear caches, no longer needed
memdelete(d);
-
//save back the findings
//String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("file_cache");
- f=FileAccess::open(fscache,FileAccess::WRITE);
- _save_filesystem_cache(new_filesystem,f);
+ f = FileAccess::open(fscache, FileAccess::WRITE);
+ _save_filesystem_cache(new_filesystem, f);
f->close();
memdelete(f);
- scanning=false;
-
+ scanning = false;
}
void EditorFileSystem::_save_filesystem_cache() {
String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache2");
- FileAccess *f=FileAccess::open(fscache,FileAccess::WRITE);
- _save_filesystem_cache(filesystem,f);
+ FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE);
+ _save_filesystem_cache(filesystem, f);
f->close();
memdelete(f);
}
void EditorFileSystem::_thread_func(void *_userdata) {
- EditorFileSystem *sd = (EditorFileSystem*)_userdata;
+ EditorFileSystem *sd = (EditorFileSystem *)_userdata;
sd->_scan_filesystem();
-
}
bool EditorFileSystem::_update_scan_actions() {
sources_changed.clear();
- bool fs_changed=false;
+ bool fs_changed = false;
Vector<String> reimports;
- for (List<ItemAction>::Element *E=scan_actions.front();E;E=E->next()) {
+ for (List<ItemAction>::Element *E = scan_actions.front(); E; E = E->next()) {
- ItemAction&ia = E->get();
+ ItemAction &ia = E->get();
- switch(ia.action) {
+ switch (ia.action) {
case ItemAction::ACTION_NONE: {
} break;
case ItemAction::ACTION_DIR_ADD: {
//print_line("*ACTION ADD DIR: "+ia.new_dir->get_name());
- int idx=0;
- for(int i=0;i<ia.dir->subdirs.size();i++) {
+ int idx = 0;
+ for (int i = 0; i < ia.dir->subdirs.size(); i++) {
- if (ia.new_dir->name<ia.dir->subdirs[i]->name)
+ if (ia.new_dir->name < ia.dir->subdirs[i]->name)
break;
idx++;
}
- if (idx==ia.dir->subdirs.size()) {
+ if (idx == ia.dir->subdirs.size()) {
ia.dir->subdirs.push_back(ia.new_dir);
} else {
- ia.dir->subdirs.insert(idx,ia.new_dir);
+ ia.dir->subdirs.insert(idx, ia.new_dir);
}
- fs_changed=true;
+ fs_changed = true;
} break;
case ItemAction::ACTION_DIR_REMOVE: {
ERR_CONTINUE(!ia.dir->parent);
//print_line("*ACTION REMOVE DIR: "+ia.dir->get_name());
ia.dir->parent->subdirs.erase(ia.dir);
- memdelete( ia.dir );
- fs_changed=true;
+ memdelete(ia.dir);
+ fs_changed = true;
} break;
case ItemAction::ACTION_FILE_ADD: {
- int idx=0;
- for(int i=0;i<ia.dir->files.size();i++) {
+ int idx = 0;
+ for (int i = 0; i < ia.dir->files.size(); i++) {
- if (ia.new_file->file<ia.dir->files[i]->file)
+ if (ia.new_file->file < ia.dir->files[i]->file)
break;
idx++;
}
- if (idx==ia.dir->files.size()) {
+ if (idx == ia.dir->files.size()) {
ia.dir->files.push_back(ia.new_file);
} else {
- ia.dir->files.insert(idx,ia.new_file);
+ ia.dir->files.insert(idx, ia.new_file);
}
- fs_changed=true;
+ fs_changed = true;
//print_line("*ACTION ADD FILE: "+ia.new_file->file);
} break;
case ItemAction::ACTION_FILE_REMOVE: {
int idx = ia.dir->find_file_index(ia.file);
- ERR_CONTINUE(idx==-1);
- memdelete( ia.dir->files[idx] );
+ ERR_CONTINUE(idx == -1);
+ memdelete(ia.dir->files[idx]);
ia.dir->files.remove(idx);
- fs_changed=true;
+ fs_changed = true;
//print_line("*ACTION REMOVE FILE: "+ia.file);
} break;
case ItemAction::ACTION_FILE_REIMPORT: {
-
int idx = ia.dir->find_file_index(ia.file);
- ERR_CONTINUE(idx==-1);
+ ERR_CONTINUE(idx == -1);
String full_path = ia.dir->get_file_path(idx);
reimports.push_back(full_path);
- fs_changed=true;
+ fs_changed = true;
} break;
-
}
}
-
if (reimports.size()) {
reimport_files(reimports);
-
}
scan_actions.clear();
return fs_changed;
-
}
void EditorFileSystem::scan() {
- if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/)
- return;
+ if (false /*&& bool(Globals::get_singleton()->get("debug/disable_scan"))*/)
+ return;
- if (scanning || scanning_changes|| thread)
+ if (scanning || scanning_changes || thread)
return;
_update_extensions();
- abort_scan=false;
+ abort_scan = false;
if (!use_threads) {
- scanning=true;
- scan_total=0;
+ scanning = true;
+ scan_total = 0;
_scan_filesystem();
if (filesystem)
memdelete(filesystem);
//file_type_cache.clear();
- filesystem=new_filesystem;
- new_filesystem=NULL;
+ filesystem = new_filesystem;
+ new_filesystem = NULL;
_update_scan_actions();
- scanning=false;
+ scanning = false;
emit_signal("filesystem_changed");
- emit_signal("sources_changed",sources_changed.size()>0);
+ emit_signal("sources_changed", sources_changed.size() > 0);
} else {
ERR_FAIL_COND(thread);
set_process(true);
Thread::Settings s;
- scanning=true;
- scan_total=0;
- s.priority=Thread::PRIORITY_LOW;
- thread = Thread::create(_thread_func,this,s);
+ scanning = true;
+ scan_total = 0;
+ s.priority = Thread::PRIORITY_LOW;
+ thread = Thread::create(_thread_func, this, s);
//tree->hide();
//progress->show();
-
}
-
-
-
}
-void EditorFileSystem::ScanProgress::update(int p_current,int p_total) const {
+void EditorFileSystem::ScanProgress::update(int p_current, int p_total) const {
- float ratio = low + ((hi-low)/p_total)*p_current;
- progress->step(ratio*1000);
- EditorFileSystem::singleton->scan_total=ratio;
+ float ratio = low + ((hi - low) / p_total) * p_current;
+ progress->step(ratio * 1000);
+ EditorFileSystem::singleton->scan_total = ratio;
}
-EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current,int p_total) const{
+EditorFileSystem::ScanProgress EditorFileSystem::ScanProgress::get_sub(int p_current, int p_total) const {
- ScanProgress sp=*this;
- float slice = (sp.hi-sp.low)/p_total;
- sp.low+=slice*p_current;
- sp.hi=slice;
+ ScanProgress sp = *this;
+ float slice = (sp.hi - sp.low) / p_total;
+ sp.low += slice * p_current;
+ sp.hi = slice;
return sp;
-
}
-bool EditorFileSystem::_check_missing_imported_files(const String& p_path) {
+bool EditorFileSystem::_check_missing_imported_files(const String &p_path) {
if (!reimport_on_missing_imported_files)
return true;
Error err;
- FileAccess *f= FileAccess::open(p_path+".import",FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path + ".import", FileAccess::READ, &err);
if (!f) {
- print_line("could not open import for "+p_path);
+ print_line("could not open import for " + p_path);
return false;
}
VariantParser::StreamFile stream;
- stream.f=f;
+ stream.f = f;
String assign;
Variant value;
VariantParser::Tag next_tag;
- int lines=0;
+ int lines = 0;
String error_text;
List<String> to_check;
- while(true) {
+ while (true) {
- assign=Variant();
+ assign = Variant();
next_tag.fields.clear();
- next_tag.name=String();
+ next_tag.name = String();
- err = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,NULL,true);
- if (err==ERR_FILE_EOF) {
+ err = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, NULL, true);
+ if (err == ERR_FILE_EOF) {
memdelete(f);
return OK;
- }
- else if (err!=OK) {
- ERR_PRINTS("ResourceFormatImporter::load - "+p_path+".import:"+itos(lines)+" error: "+error_text);
+ } else if (err != OK) {
+ ERR_PRINTS("ResourceFormatImporter::load - " + p_path + ".import:" + itos(lines) + " error: " + error_text);
memdelete(f);
return false;
}
- if (assign!=String()) {
+ if (assign != String()) {
if (assign.begins_with("path")) {
to_check.push_back(value);
- } else if (assign=="files") {
+ } else if (assign == "files") {
Array fa = value;
- for(int i=0;i<fa.size();i++) {
+ for (int i = 0; i < fa.size(); i++) {
to_check.push_back(fa[i]);
}
}
- } else if (next_tag.name!="remap" && next_tag.name!="deps") {
+ } else if (next_tag.name != "remap" && next_tag.name != "deps") {
break;
}
}
memdelete(f);
- for (List<String>::Element *E=to_check.front();E;E=E->next()) {
+ for (List<String>::Element *E = to_check.front(); E; E = E->next()) {
if (!FileAccess::exists(E->get())) {
- print_line("missing "+E->get()+", reimport" );
+ print_line("missing " + E->get() + ", reimport");
return false;
}
}
return true;
}
-void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess *da,const ScanProgress& p_progress) {
+void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress) {
List<String> dirs;
List<String> files;
@@ -530,13 +495,12 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess
p_dir->modified_time = FileAccess::get_modified_time(cd);
-
da->list_dir_begin();
while (true) {
bool isdir;
String f = da->get_next(&isdir);
- if (f=="")
+ if (f == "")
break;
if (isdir) {
@@ -553,7 +517,6 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess
files.push_back(f);
}
-
}
da->list_dir_end();
@@ -561,61 +524,57 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess
dirs.sort();
files.sort();
- int total = dirs.size()+files.size();
- int idx=0;
-
+ int total = dirs.size() + files.size();
+ int idx = 0;
- for (List<String>::Element *E=dirs.front();E;E=E->next(),idx++) {
+ for (List<String>::Element *E = dirs.front(); E; E = E->next(), idx++) {
- if (da->change_dir(E->get())==OK) {
+ if (da->change_dir(E->get()) == OK) {
String d = da->get_current_dir();
- if (d==cd || !d.begins_with(cd)) {
+ if (d == cd || !d.begins_with(cd)) {
da->change_dir(cd); //avoid recursion
} else {
+ EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
- EditorFileSystemDirectory *efd = memnew( EditorFileSystemDirectory );
+ efd->parent = p_dir;
+ efd->name = E->get();
- efd->parent=p_dir;
- efd->name=E->get();
+ _scan_new_dir(efd, da, p_progress.get_sub(idx, total));
- _scan_new_dir(efd,da,p_progress.get_sub(idx,total));
+ int idx = 0;
+ for (int i = 0; i < p_dir->subdirs.size(); i++) {
- int idx=0;
- for(int i=0;i<p_dir->subdirs.size();i++) {
-
- if (efd->name<p_dir->subdirs[i]->name)
+ if (efd->name < p_dir->subdirs[i]->name)
break;
idx++;
}
- if (idx==p_dir->subdirs.size()) {
+ if (idx == p_dir->subdirs.size()) {
p_dir->subdirs.push_back(efd);
} else {
- p_dir->subdirs.insert(idx,efd);
+ p_dir->subdirs.insert(idx, efd);
}
da->change_dir("..");
}
} else {
- ERR_PRINTS("Cannot go into subdir: "+E->get());
+ ERR_PRINTS("Cannot go into subdir: " + E->get());
}
- p_progress.update(idx,total);
-
+ p_progress.update(idx, total);
}
- for (List<String>::Element*E=files.front();E;E=E->next(),idx++) {
-
+ for (List<String>::Element *E = files.front(); E; E = E->next(), idx++) {
String ext = E->get().get_extension().to_lower();
if (!valid_extensions.has(ext)) {
continue; //invalid
}
- EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo );
- fi->file=E->get();
+ EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
+ fi->file = E->get();
String path = cd.plus_file(fi->file);
@@ -624,92 +583,87 @@ void EditorFileSystem::_scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess
if (import_extensions.has(ext)) {
- //is imported
- uint64_t import_mt=0;
- if (FileAccess::exists(path+".import")) {
- import_mt=FileAccess::get_modified_time(path+".import");
+ //is imported
+ uint64_t import_mt = 0;
+ if (FileAccess::exists(path + ".import")) {
+ import_mt = FileAccess::get_modified_time(path + ".import");
}
+ if (fc && fc->modification_time == mt && fc->import_modification_time == import_mt && _check_missing_imported_files(path)) {
- if (fc && fc->modification_time==mt && fc->import_modification_time==import_mt && _check_missing_imported_files(path)) {
-
- fi->type=fc->type;
- fi->modified_time=fc->modification_time;
- fi->import_modified_time=fc->import_modification_time;
+ fi->type = fc->type;
+ fi->modified_time = fc->modification_time;
+ fi->import_modified_time = fc->import_modification_time;
} else {
if (!fc) {
print_line("REIMPORT BECAUSE: not previously found");
- } else if (fc->modification_time!=mt) {
- print_line("REIMPORT BECAUSE: modified resource time "+itos(fc->modification_time)+" vs "+itos(mt));
+ } else if (fc->modification_time != mt) {
+ print_line("REIMPORT BECAUSE: modified resource time " + itos(fc->modification_time) + " vs " + itos(mt));
- } else if (fc->import_modification_time!=import_mt) {
- print_line("REIMPORT BECAUSE: modified .import time"+itos(fc->import_modification_time)+" vs "+itos(import_mt));
+ } else if (fc->import_modification_time != import_mt) {
+ print_line("REIMPORT BECAUSE: modified .import time" + itos(fc->import_modification_time) + " vs " + itos(import_mt));
} else {
print_line("REIMPORT BECAUSE: missing imported files");
}
-
- fi->type=ResourceFormatImporter::get_singleton()->get_resource_type(path);
- fi->modified_time=0;
- fi->import_modified_time=0;
+ fi->type = ResourceFormatImporter::get_singleton()->get_resource_type(path);
+ fi->modified_time = 0;
+ fi->import_modified_time = 0;
ItemAction ia;
- ia.action=ItemAction::ACTION_FILE_REIMPORT;
- ia.dir=p_dir;
- ia.file=E->get();
+ ia.action = ItemAction::ACTION_FILE_REIMPORT;
+ ia.dir = p_dir;
+ ia.file = E->get();
scan_actions.push_back(ia);
}
} else {
//not imported, so just update type if changed
if (fc && fc->modification_time == mt) {
- fi->type=fc->type;
- fi->modified_time=fc->modification_time;
- fi->import_modified_time=0;
+ fi->type = fc->type;
+ fi->modified_time = fc->modification_time;
+ fi->import_modified_time = 0;
} else {
- fi->type=ResourceLoader::get_resource_type(path);
- fi->modified_time=mt;
- fi->import_modified_time=0;
+ fi->type = ResourceLoader::get_resource_type(path);
+ fi->modified_time = mt;
+ fi->import_modified_time = 0;
}
}
p_dir->files.push_back(fi);
- p_progress.update(idx,total);
+ p_progress.update(idx, total);
}
-
}
-
-
-void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const ScanProgress& p_progress) {
+void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress) {
uint64_t current_mtime = FileAccess::get_modified_time(p_dir->get_path());
- bool updated_dir=false;
+ bool updated_dir = false;
String cd = p_dir->get_path();
//print_line("dir: "+p_dir->get_path()+" MODTIME: "+itos(p_dir->modified_time)+" CTIME: "+itos(current_mtime));
- if (current_mtime!=p_dir->modified_time) {
+ if (current_mtime != p_dir->modified_time) {
- updated_dir=true;
- p_dir->modified_time=current_mtime;
+ updated_dir = true;
+ p_dir->modified_time = current_mtime;
//ooooops, dir changed, see what's going on
//first mark everything as veryfied
- for(int i=0;i<p_dir->files.size();i++) {
+ for (int i = 0; i < p_dir->files.size(); i++) {
- p_dir->files[i]->verified=false;
+ p_dir->files[i]->verified = false;
}
- for(int i=0;i<p_dir->subdirs.size();i++) {
+ for (int i = 0; i < p_dir->subdirs.size(); i++) {
- p_dir->get_subdir(i)->verified=false;
+ p_dir->get_subdir(i)->verified = false;
}
//then scan files and directories and check what's different
@@ -722,7 +676,7 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const S
bool isdir;
String f = da->get_next(&isdir);
- if (f=="")
+ if (f == "")
break;
if (isdir) {
@@ -731,32 +685,30 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const S
continue;
int idx = p_dir->find_dir_index(f);
- if (idx==-1) {
+ if (idx == -1) {
if (FileAccess::exists(cd.plus_file(f).plus_file("godot.cfg"))) // skip if another project inside this
continue;
- EditorFileSystemDirectory *efd = memnew( EditorFileSystemDirectory );
+ EditorFileSystemDirectory *efd = memnew(EditorFileSystemDirectory);
- efd->parent=p_dir;
- efd->name=f;
+ efd->parent = p_dir;
+ efd->name = f;
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
d->change_dir(cd.plus_file(f));
- _scan_new_dir(efd,d,p_progress.get_sub(1,1));
+ _scan_new_dir(efd, d, p_progress.get_sub(1, 1));
memdelete(d);
-
ItemAction ia;
- ia.action=ItemAction::ACTION_DIR_ADD;
- ia.dir=p_dir;
- ia.file=f;
- ia.new_dir=efd;
+ ia.action = ItemAction::ACTION_DIR_ADD;
+ ia.dir = p_dir;
+ ia.file = f;
+ ia.new_dir = efd;
scan_actions.push_back(ia);
} else {
- p_dir->subdirs[idx]->verified=true;
+ p_dir->subdirs[idx]->verified = true;
}
-
} else {
String ext = f.get_extension().to_lower();
if (!valid_extensions.has(ext))
@@ -764,66 +716,59 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const S
int idx = p_dir->find_file_index(f);
- if (idx==-1) {
+ if (idx == -1) {
//never seen this file, add actition to add it
- EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo );
- fi->file=f;
+ EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
+ fi->file = f;
String path = cd.plus_file(fi->file);
- fi->modified_time=FileAccess::get_modified_time(path);
- fi->import_modified_time=0;
- fi->type=ResourceLoader::get_resource_type(path);
+ fi->modified_time = FileAccess::get_modified_time(path);
+ fi->import_modified_time = 0;
+ fi->type = ResourceLoader::get_resource_type(path);
{
ItemAction ia;
- ia.action=ItemAction::ACTION_FILE_ADD;
- ia.dir=p_dir;
- ia.file=f;
- ia.new_file=fi;
+ ia.action = ItemAction::ACTION_FILE_ADD;
+ ia.dir = p_dir;
+ ia.file = f;
+ ia.new_file = fi;
scan_actions.push_back(ia);
-
-
}
if (import_extensions.has(ext)) {
//if it can be imported, and it was added, it needs to be reimported
print_line("REIMPORT: file was not found before, reimport");
- print_line("at dir: "+p_dir->get_path()+" file: "+f);
- for(int i=0;i<p_dir->files.size();i++) {
- print_line(itos(i)+": "+p_dir->files[i]->file);
+ print_line("at dir: " + p_dir->get_path() + " file: " + f);
+ for (int i = 0; i < p_dir->files.size(); i++) {
+ print_line(itos(i) + ": " + p_dir->files[i]->file);
}
ItemAction ia;
- ia.action=ItemAction::ACTION_FILE_REIMPORT;
- ia.dir=p_dir;
- ia.file=f;
+ ia.action = ItemAction::ACTION_FILE_REIMPORT;
+ ia.dir = p_dir;
+ ia.file = f;
scan_actions.push_back(ia);
}
} else {
- p_dir->files[idx]->verified=true;
+ p_dir->files[idx]->verified = true;
}
-
-
}
-
}
da->list_dir_end();
memdelete(da);
-
}
- for(int i=0;i<p_dir->files.size();i++) {
+ for (int i = 0; i < p_dir->files.size(); i++) {
if (updated_dir && !p_dir->files[i]->verified) {
//this file was removed, add action to remove it
ItemAction ia;
- ia.action=ItemAction::ACTION_FILE_REMOVE;
- ia.dir=p_dir;
- ia.file=p_dir->files[i]->file;
+ ia.action = ItemAction::ACTION_FILE_REMOVE;
+ ia.dir = p_dir;
+ ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
continue;
-
}
if (import_extensions.has(p_dir->files[i]->file.get_extension().to_lower())) {
@@ -833,150 +778,142 @@ void EditorFileSystem::_scan_fs_changes(EditorFileSystemDirectory *p_dir,const S
uint64_t mt = FileAccess::get_modified_time(path);
- bool reimport=false;
+ bool reimport = false;
- if (mt!=p_dir->files[i]->modified_time) {
+ if (mt != p_dir->files[i]->modified_time) {
print_line("REIMPORT: modified time changed, reimport");
- reimport=true; //it was modified, must be reimported.
- } else if (!FileAccess::exists(path+".import")) {
+ reimport = true; //it was modified, must be reimported.
+ } else if (!FileAccess::exists(path + ".import")) {
print_line("REIMPORT: no .import exists, reimport");
- reimport=true; //no .import file, obviously reimport
+ reimport = true; //no .import file, obviously reimport
} else {
- uint64_t import_mt=FileAccess::get_modified_time(path+".import");
- print_line(itos(import_mt)+" vs "+itos(p_dir->files[i]->import_modified_time));
- if (import_mt!=p_dir->files[i]->import_modified_time) {
+ uint64_t import_mt = FileAccess::get_modified_time(path + ".import");
+ print_line(itos(import_mt) + " vs " + itos(p_dir->files[i]->import_modified_time));
+ if (import_mt != p_dir->files[i]->import_modified_time) {
print_line("REIMPORT: import modified changed, reimport");
- reimport=true;
+ reimport = true;
} else if (!_check_missing_imported_files(path)) {
print_line("REIMPORT: imported files removed");
- reimport=true;
+ reimport = true;
}
}
if (reimport) {
ItemAction ia;
- ia.action=ItemAction::ACTION_FILE_REIMPORT;
- ia.dir=p_dir;
- ia.file=p_dir->files[i]->file;
+ ia.action = ItemAction::ACTION_FILE_REIMPORT;
+ ia.dir = p_dir;
+ ia.file = p_dir->files[i]->file;
scan_actions.push_back(ia);
}
-
}
EditorResourcePreview::get_singleton()->check_for_invalidation(p_dir->get_file_path(i));
}
- for(int i=0;i<p_dir->subdirs.size();i++) {
+ for (int i = 0; i < p_dir->subdirs.size(); i++) {
if (updated_dir && !p_dir->subdirs[i]->verified) {
//this directory was removed, add action to remove it
ItemAction ia;
- ia.action=ItemAction::ACTION_DIR_REMOVE;
- ia.dir=p_dir->subdirs[i];
+ ia.action = ItemAction::ACTION_DIR_REMOVE;
+ ia.dir = p_dir->subdirs[i];
scan_actions.push_back(ia);
continue;
-
}
- _scan_fs_changes(p_dir->get_subdir(i),p_progress);
+ _scan_fs_changes(p_dir->get_subdir(i), p_progress);
}
-
}
void EditorFileSystem::_thread_func_sources(void *_userdata) {
- EditorFileSystem *efs = (EditorFileSystem*)_userdata;
+ EditorFileSystem *efs = (EditorFileSystem *)_userdata;
if (efs->filesystem) {
- EditorProgressBG pr("sources",TTR("ScanSources"),1000);
+ EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
- sp.progress=&pr;
- sp.hi=1;
- sp.low=0;
- efs->_scan_fs_changes(efs->filesystem,sp);
+ sp.progress = &pr;
+ sp.hi = 1;
+ sp.low = 0;
+ efs->_scan_fs_changes(efs->filesystem, sp);
}
- efs->scanning_changes_done=true;
+ efs->scanning_changes_done = true;
}
void EditorFileSystem::get_changed_sources(List<String> *r_changed) {
- *r_changed=sources_changed;
+ *r_changed = sources_changed;
}
void EditorFileSystem::scan_changes() {
- if (scanning || scanning_changes|| thread)
+ if (scanning || scanning_changes || thread)
return;
_update_extensions();
sources_changed.clear();
- scanning_changes=true;
- scanning_changes_done=false;
+ scanning_changes = true;
+ scanning_changes_done = false;
- abort_scan=false;
+ abort_scan = false;
if (!use_threads) {
if (filesystem) {
- EditorProgressBG pr("sources",TTR("ScanSources"),1000);
+ EditorProgressBG pr("sources", TTR("ScanSources"), 1000);
ScanProgress sp;
- sp.progress=&pr;
- sp.hi=1;
- sp.low=0;
- scan_total=0;
- _scan_fs_changes(filesystem,sp);
+ sp.progress = &pr;
+ sp.hi = 1;
+ sp.low = 0;
+ scan_total = 0;
+ _scan_fs_changes(filesystem, sp);
if (_update_scan_actions())
emit_signal("filesystem_changed");
}
- scanning_changes=false;
- scanning_changes_done=true;
- emit_signal("sources_changed",sources_changed.size()>0);
+ scanning_changes = false;
+ scanning_changes_done = true;
+ emit_signal("sources_changed", sources_changed.size() > 0);
} else {
ERR_FAIL_COND(thread_sources);
set_process(true);
- scan_total=0;
+ scan_total = 0;
Thread::Settings s;
- s.priority=Thread::PRIORITY_LOW;
- thread_sources = Thread::create(_thread_func_sources,this,s);
+ s.priority = Thread::PRIORITY_LOW;
+ thread_sources = Thread::create(_thread_func_sources, this, s);
//tree->hide();
//print_line("SCAN BEGIN!");
//progress->show();
}
-
-
-
}
void EditorFileSystem::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
-
- scan();
+ scan();
} break;
case NOTIFICATION_EXIT_TREE: {
if (use_threads && thread) {
//abort thread if in progress
- abort_scan=true;
- while(scanning) {
+ abort_scan = true;
+ while (scanning) {
OS::get_singleton()->delay_usec(1000);
}
Thread::wait_to_finish(thread);
memdelete(thread);
- thread=NULL;
+ thread = NULL;
WARN_PRINTS("Scan thread aborted...");
set_process(false);
-
}
if (filesystem)
memdelete(filesystem);
if (new_filesystem)
memdelete(new_filesystem);
- filesystem=NULL;
- new_filesystem=NULL;
+ filesystem = NULL;
+ new_filesystem = NULL;
} break;
case NOTIFICATION_PROCESS: {
@@ -987,17 +924,17 @@ void EditorFileSystem::_notification(int p_what) {
if (scanning_changes_done) {
- scanning_changes=false;
+ scanning_changes = false;
set_process(false);
Thread::wait_to_finish(thread_sources);
memdelete(thread_sources);
- thread_sources=NULL;
+ thread_sources = NULL;
if (_update_scan_actions())
emit_signal("filesystem_changed");
//print_line("sources changed: "+itos(sources_changed.size()));
- emit_signal("sources_changed",sources_changed.size()>0);
+ emit_signal("sources_changed", sources_changed.size() > 0);
}
} else if (!scanning) {
@@ -1005,25 +942,22 @@ void EditorFileSystem::_notification(int p_what) {
if (filesystem)
memdelete(filesystem);
- filesystem=new_filesystem;
- new_filesystem=NULL;
+ filesystem = new_filesystem;
+ new_filesystem = NULL;
Thread::wait_to_finish(thread);
memdelete(thread);
- thread=NULL;
+ thread = NULL;
_update_scan_actions();
emit_signal("filesystem_changed");
- emit_signal("sources_changed",sources_changed.size()>0);
+ emit_signal("sources_changed", sources_changed.size() > 0);
//print_line("initial sources changed: "+itos(sources_changed.size()));
-
-
} else {
//progress->set_text("Scanning...\n"+itos(total*100)+"%");
}
}
} break;
}
-
}
bool EditorFileSystem::is_scanning() const {
@@ -1040,311 +974,283 @@ EditorFileSystemDirectory *EditorFileSystem::get_filesystem() {
return filesystem;
}
-void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory*p_dir,FileAccess *p_file) {
-
+void EditorFileSystem::_save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file) {
if (!p_dir)
return; //none
- p_file->store_line("::"+p_dir->get_path()+"::"+String::num(p_dir->modified_time));
+ p_file->store_line("::" + p_dir->get_path() + "::" + String::num(p_dir->modified_time));
- for(int i=0;i<p_dir->files.size();i++) {
+ for (int i = 0; i < p_dir->files.size(); i++) {
- String s=p_dir->files[i]->file+"::"+p_dir->files[i]->type+"::"+itos(p_dir->files[i]->modified_time)+"::"+itos(p_dir->files[i]->import_modified_time);
- s+="::";
- for(int j=0;j<p_dir->files[i]->deps.size();j++) {
+ String s = p_dir->files[i]->file + "::" + p_dir->files[i]->type + "::" + itos(p_dir->files[i]->modified_time) + "::" + itos(p_dir->files[i]->import_modified_time);
+ s += "::";
+ for (int j = 0; j < p_dir->files[i]->deps.size(); j++) {
- if (j>0)
- s+="<>";
- s+=p_dir->files[i]->deps[j];
+ if (j > 0)
+ s += "<>";
+ s += p_dir->files[i]->deps[j];
}
p_file->store_line(s);
}
- for(int i=0;i<p_dir->subdirs.size();i++) {
+ for (int i = 0; i < p_dir->subdirs.size(); i++) {
- _save_filesystem_cache(p_dir->subdirs[i],p_file);
+ _save_filesystem_cache(p_dir->subdirs[i], p_file);
}
-
}
-
-
-
-
-
-bool EditorFileSystem::_find_file(const String& p_file,EditorFileSystemDirectory ** r_d, int &r_file_pos) const {
+bool EditorFileSystem::_find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const {
//todo make faster
if (!filesystem || scanning)
return false;
-
String f = GlobalConfig::get_singleton()->localize_path(p_file);
if (!f.begins_with("res://"))
return false;
- f=f.substr(6,f.length());
- f=f.replace("\\","/");
+ f = f.substr(6, f.length());
+ f = f.replace("\\", "/");
Vector<String> path = f.split("/");
- if (path.size()==0)
+ if (path.size() == 0)
return false;
- String file=path[path.size()-1];
- path.resize(path.size()-1);
+ String file = path[path.size() - 1];
+ path.resize(path.size() - 1);
- EditorFileSystemDirectory *fs=filesystem;
+ EditorFileSystemDirectory *fs = filesystem;
- for(int i=0;i<path.size();i++) {
+ for (int i = 0; i < path.size(); i++) {
if (path[i].begins_with("."))
return false;
- int idx=-1;
- for(int j=0;j<fs->get_subdir_count();j++) {
+ int idx = -1;
+ for (int j = 0; j < fs->get_subdir_count(); j++) {
- if (fs->get_subdir(j)->get_name()==path[i]) {
- idx=j;
+ if (fs->get_subdir(j)->get_name() == path[i]) {
+ idx = j;
break;
}
}
- if (idx==-1) {
+ if (idx == -1) {
//does not exist, create i guess?
- EditorFileSystemDirectory *efsd = memnew( EditorFileSystemDirectory );
- efsd->name=path[i];
- int idx2=0;
- for(int j=0;j<fs->get_subdir_count();j++) {
+ EditorFileSystemDirectory *efsd = memnew(EditorFileSystemDirectory);
+ efsd->name = path[i];
+ int idx2 = 0;
+ for (int j = 0; j < fs->get_subdir_count(); j++) {
- if (efsd->name<fs->get_subdir(j)->get_name())
+ if (efsd->name < fs->get_subdir(j)->get_name())
break;
idx2++;
}
- if (idx2==fs->get_subdir_count())
+ if (idx2 == fs->get_subdir_count())
fs->subdirs.push_back(efsd);
else
- fs->subdirs.insert(idx2,efsd);
- fs=efsd;
+ fs->subdirs.insert(idx2, efsd);
+ fs = efsd;
} else {
- fs=fs->get_subdir(idx);
+ fs = fs->get_subdir(idx);
}
}
+ int cpos = -1;
+ for (int i = 0; i < fs->files.size(); i++) {
- int cpos=-1;
- for(int i=0;i<fs->files.size();i++) {
-
- if (fs->files[i]->file==file) {
- cpos=i;
+ if (fs->files[i]->file == file) {
+ cpos = i;
break;
}
}
- r_file_pos=cpos;
- *r_d=fs;
+ r_file_pos = cpos;
+ *r_d = fs;
- if (cpos!=-1) {
+ if (cpos != -1) {
return true;
- } else {
+ } else {
return false;
}
-
-
}
-String EditorFileSystem::get_file_type(const String& p_file) const {
-
- EditorFileSystemDirectory *fs=NULL;
- int cpos=-1;
+String EditorFileSystem::get_file_type(const String &p_file) const {
- if (!_find_file(p_file,&fs,cpos)) {
+ EditorFileSystemDirectory *fs = NULL;
+ int cpos = -1;
- return "";
- }
+ if (!_find_file(p_file, &fs, cpos)) {
+ return "";
+ }
- return fs->files[cpos]->type;
-
+ return fs->files[cpos]->type;
}
-EditorFileSystemDirectory* EditorFileSystem::find_file(const String& p_file,int* r_index) const {
+EditorFileSystemDirectory *EditorFileSystem::find_file(const String &p_file, int *r_index) const {
if (!filesystem || scanning)
- return NULL;
+ return NULL;
- EditorFileSystemDirectory *fs=NULL;
- int cpos=-1;
- if (!_find_file(p_file,&fs,cpos)) {
+ EditorFileSystemDirectory *fs = NULL;
+ int cpos = -1;
+ if (!_find_file(p_file, &fs, cpos)) {
- return NULL;
+ return NULL;
}
-
if (r_index)
- *r_index=cpos;
+ *r_index = cpos;
return fs;
}
+EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String &p_path) {
-EditorFileSystemDirectory *EditorFileSystem::get_filesystem_path(const String& p_path) {
-
- if (!filesystem || scanning)
- return NULL;
-
-
- String f = GlobalConfig::get_singleton()->localize_path(p_path);
-
- if (!f.begins_with("res://"))
- return NULL;
+ if (!filesystem || scanning)
+ return NULL;
+ String f = GlobalConfig::get_singleton()->localize_path(p_path);
- f=f.substr(6,f.length());
- f=f.replace("\\","/");
- if (f==String())
- return filesystem;
+ if (!f.begins_with("res://"))
+ return NULL;
- if (f.ends_with("/"))
- f=f.substr(0,f.length()-1);
+ f = f.substr(6, f.length());
+ f = f.replace("\\", "/");
+ if (f == String())
+ return filesystem;
- Vector<String> path = f.split("/");
+ if (f.ends_with("/"))
+ f = f.substr(0, f.length() - 1);
- if (path.size()==0)
- return NULL;
+ Vector<String> path = f.split("/");
- EditorFileSystemDirectory *fs=filesystem;
+ if (path.size() == 0)
+ return NULL;
- for(int i=0;i<path.size();i++) {
+ EditorFileSystemDirectory *fs = filesystem;
+ for (int i = 0; i < path.size(); i++) {
- int idx=-1;
- for(int j=0;j<fs->get_subdir_count();j++) {
+ int idx = -1;
+ for (int j = 0; j < fs->get_subdir_count(); j++) {
- if (fs->get_subdir(j)->get_name()==path[i]) {
- idx=j;
- break;
- }
- }
+ if (fs->get_subdir(j)->get_name() == path[i]) {
+ idx = j;
+ break;
+ }
+ }
- if (idx==-1) {
- return NULL;
- } else {
+ if (idx == -1) {
+ return NULL;
+ } else {
- fs=fs->get_subdir(idx);
+ fs = fs->get_subdir(idx);
+ }
}
- }
- return fs;
+ return fs;
}
-void EditorFileSystem::_resource_saved(const String& p_path){
-
+void EditorFileSystem::_resource_saved(const String &p_path) {
//print_line("resource saved: "+p_path);
EditorFileSystem::get_singleton()->update_file(p_path);
-
}
+void EditorFileSystem::update_file(const String &p_file) {
+ EditorFileSystemDirectory *fs = NULL;
+ int cpos = -1;
+ if (!_find_file(p_file, &fs, cpos)) {
-void EditorFileSystem::update_file(const String& p_file) {
-
- EditorFileSystemDirectory *fs=NULL;
- int cpos=-1;
-
- if (!_find_file(p_file,&fs,cpos)) {
+ if (!fs)
+ return;
+ }
- if (!fs)
+ if (!FileAccess::exists(p_file)) {
+ //was removed
+ memdelete(fs->files[cpos]);
+ fs->files.remove(cpos);
+ call_deferred("emit_signal", "filesystem_changed"); //update later
return;
- }
-
- if (!FileAccess::exists(p_file)) {
- //was removed
- memdelete( fs->files[cpos] );
- fs->files.remove(cpos);
- call_deferred("emit_signal","filesystem_changed"); //update later
- return;
-
- }
-
- String type = ResourceLoader::get_resource_type(p_file);
-
- if (cpos==-1) {
+ }
- int idx=0;
+ String type = ResourceLoader::get_resource_type(p_file);
- for(int i=0;i<fs->files.size();i++) {
- if (p_file<fs->files[i]->file)
- break;
- idx++;
- }
+ if (cpos == -1) {
- EditorFileSystemDirectory::FileInfo *fi = memnew( EditorFileSystemDirectory::FileInfo );
- fi->file=p_file.get_file();
- fi->import_modified_time=0;
+ int idx = 0;
- if (idx==fs->files.size()) {
- fs->files.push_back(fi);
- } else {
+ for (int i = 0; i < fs->files.size(); i++) {
+ if (p_file < fs->files[i]->file)
+ break;
+ idx++;
+ }
- fs->files.insert(idx,fi);
- }
- cpos=idx;
+ EditorFileSystemDirectory::FileInfo *fi = memnew(EditorFileSystemDirectory::FileInfo);
+ fi->file = p_file.get_file();
+ fi->import_modified_time = 0;
+ if (idx == fs->files.size()) {
+ fs->files.push_back(fi);
+ } else {
- }
+ fs->files.insert(idx, fi);
+ }
+ cpos = idx;
+ }
//print_line("UPDATING: "+p_file);
- fs->files[cpos]->type=type;
- fs->files[cpos]->modified_time=FileAccess::get_modified_time(p_file);
+ fs->files[cpos]->type = type;
+ fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
//if (FileAccess::exists(p_file+".import")) {
// fs->files[cpos]->import_modified_time=FileAccess::get_modified_time(p_file+".import");
//}
- EditorResourcePreview::get_singleton()->call_deferred("check_for_invalidation",p_file);
- call_deferred("emit_signal","filesystem_changed"); //update later
-
+ EditorResourcePreview::get_singleton()->call_deferred("check_for_invalidation", p_file);
+ call_deferred("emit_signal", "filesystem_changed"); //update later
}
+void EditorFileSystem::_reimport_file(const String &p_file) {
-void EditorFileSystem::_reimport_file(const String& p_file) {
-
- print_line("REIMPORTING: "+p_file);
+ print_line("REIMPORTING: " + p_file);
- EditorFileSystemDirectory *fs=NULL;
- int cpos=-1;
- bool found = _find_file(p_file,&fs,cpos);
+ EditorFileSystemDirectory *fs = NULL;
+ int cpos = -1;
+ bool found = _find_file(p_file, &fs, cpos);
ERR_FAIL_COND(!found);
//try to obtain existing params
- Map<StringName,Variant> params;
+ Map<StringName, Variant> params;
String importer_name;
- if (FileAccess::exists(p_file+".import")) {
+ if (FileAccess::exists(p_file + ".import")) {
Ref<ConfigFile> cf;
cf.instance();
- Error err = cf->load(p_file+".import");
- if (err==OK) {
+ Error err = cf->load(p_file + ".import");
+ if (err == OK) {
List<String> sk;
- cf->get_section_keys("params",&sk);
- for(List<String>::Element *E=sk.front();E;E=E->next()) {
- params[E->get()]=cf->get_value("params",E->get());
+ cf->get_section_keys("params", &sk);
+ for (List<String>::Element *E = sk.front(); E; E = E->next()) {
+ params[E->get()] = cf->get_value("params", E->get());
}
- importer_name = cf->get_value("remap","importer");
+ importer_name = cf->get_value("remap", "importer");
}
}
Ref<ResourceImporter> importer;
//find the importer
- if (importer_name!="") {
+ if (importer_name != "") {
importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
}
@@ -1354,7 +1260,6 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
if (importer.is_null()) {
ERR_PRINT("BUG: File queued for import, but can't be imported!");
ERR_FAIL();
-
}
}
@@ -1362,9 +1267,9 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
List<ResourceImporter::ImportOption> opts;
importer->get_import_options(&opts);
- for (List<ResourceImporter::ImportOption>::Element *E=opts.front();E;E=E->next()) {
+ for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
if (!params.has(E->get().option.name)) { //this one is not present
- params[E->get().option.name]=E->get().default_value;
+ params[E->get().option.name] = E->get().default_value;
}
}
@@ -1374,72 +1279,65 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
List<String> import_variants;
List<String> gen_files;
- Error err = importer->import(p_file,base_path,params,&import_variants,&gen_files);
+ Error err = importer->import(p_file, base_path, params, &import_variants, &gen_files);
- if (err!=OK) {
- ERR_PRINTS("Error importing: "+p_file);
+ if (err != OK) {
+ ERR_PRINTS("Error importing: " + p_file);
}
//as import is complete, save the .import file
- FileAccess *f = FileAccess::open(p_file+".import",FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE);
ERR_FAIL_COND(!f);
//write manually, as order matters ([remap] has to go first for performance).
f->store_line("[remap]");
f->store_line("");
- f->store_line("importer=\""+importer->get_importer_name()+"\"");
- if (importer->get_resource_type()!="") {
- f->store_line("type=\""+importer->get_resource_type()+"\"");
+ f->store_line("importer=\"" + importer->get_importer_name() + "\"");
+ if (importer->get_resource_type() != "") {
+ f->store_line("type=\"" + importer->get_resource_type() + "\"");
}
-
- if (importer->get_save_extension()=="") {
+ if (importer->get_save_extension() == "") {
//no path
} else if (import_variants.size()) {
//import with variants
- for(List<String>::Element *E=import_variants.front();E;E=E->next()) {
-
-
- String path = base_path.c_escape()+"."+E->get()+"."+importer->get_save_extension();
+ for (List<String>::Element *E = import_variants.front(); E; E = E->next()) {
- f->store_line("path."+E->get()+"=\""+path+"\"");
+ String path = base_path.c_escape() + "." + E->get() + "." + importer->get_save_extension();
+ f->store_line("path." + E->get() + "=\"" + path + "\"");
}
} else {
- f->store_line("path=\""+base_path+"."+importer->get_save_extension()+"\"");
+ f->store_line("path=\"" + base_path + "." + importer->get_save_extension() + "\"");
}
f->store_line("");
if (gen_files.size()) {
f->store_line("[gen]");
Array genf;
- for (List<String>::Element *E=gen_files.front();E;E=E->next()) {
+ for (List<String>::Element *E = gen_files.front(); E; E = E->next()) {
genf.push_back(E->get());
}
String value;
- VariantWriter::write_to_string(genf,value);
- f->store_line("files="+value);
+ VariantWriter::write_to_string(genf, value);
+ f->store_line("files=" + value);
f->store_line("");
}
-
f->store_line("[params]");
f->store_line("");
//store options in provided order, to avoid file changing
-
- for (List<ResourceImporter::ImportOption>::Element *E=opts.front();E;E=E->next()) {
+ for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
String base = E->get().option.name;
String value;
- VariantWriter::write_to_string(params[base],value);
- f->store_line(base+"="+value);
-
-
+ VariantWriter::write_to_string(params[base], value);
+ f->store_line(base + "=" + value);
}
f->close();
@@ -1447,7 +1345,7 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
//update modified times, to avoid reimport
fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
- fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file+".import");
+ fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
//to reload properly
@@ -1455,7 +1353,7 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
Resource *r = ResourceCache::get(p_file);
- if (r->get_import_path()!=String()) {
+ if (r->get_import_path() != String()) {
String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file);
r->set_import_path(dst_path);
@@ -1464,18 +1362,18 @@ void EditorFileSystem::_reimport_file(const String& p_file) {
}
}
-void EditorFileSystem::reimport_files(const Vector<String>& p_files) {
+void EditorFileSystem::reimport_files(const Vector<String> &p_files) {
- importing=true;
- EditorProgress pr("reimport",TTR("(Re)Importing Assets"),p_files.size());
- for(int i=0;i<p_files.size();i++) {
- pr.step(p_files[i].get_file(),i);
+ importing = true;
+ EditorProgress pr("reimport", TTR("(Re)Importing Assets"), p_files.size());
+ for (int i = 0; i < p_files.size(); i++) {
+ pr.step(p_files[i].get_file(), i);
_reimport_file(p_files[i]);
}
_save_filesystem_cache();
- importing=false;
+ importing = false;
if (!is_scanning()) {
emit_signal("filesystem_changed");
}
@@ -1483,19 +1381,17 @@ void EditorFileSystem::reimport_files(const Vector<String>& p_files) {
void EditorFileSystem::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("get_filesystem:EditorFileSystemDirectory"),&EditorFileSystem::get_filesystem);
- ClassDB::bind_method(D_METHOD("is_scanning"),&EditorFileSystem::is_scanning);
- ClassDB::bind_method(D_METHOD("get_scanning_progress"),&EditorFileSystem::get_scanning_progress);
- ClassDB::bind_method(D_METHOD("scan"),&EditorFileSystem::scan);
- ClassDB::bind_method(D_METHOD("scan_sources"),&EditorFileSystem::scan_changes);
- ClassDB::bind_method(D_METHOD("update_file","path"),&EditorFileSystem::update_file);
- ClassDB::bind_method(D_METHOD("get_filesystem_path:EditorFileSystemDirectory","path"),&EditorFileSystem::get_filesystem_path);
- ClassDB::bind_method(D_METHOD("get_file_type","path"),&EditorFileSystem::get_file_type);
-
- ADD_SIGNAL( MethodInfo("filesystem_changed") );
- ADD_SIGNAL( MethodInfo("sources_changed",PropertyInfo(Variant::BOOL,"exist")) );
-
+ ClassDB::bind_method(D_METHOD("get_filesystem:EditorFileSystemDirectory"), &EditorFileSystem::get_filesystem);
+ ClassDB::bind_method(D_METHOD("is_scanning"), &EditorFileSystem::is_scanning);
+ ClassDB::bind_method(D_METHOD("get_scanning_progress"), &EditorFileSystem::get_scanning_progress);
+ ClassDB::bind_method(D_METHOD("scan"), &EditorFileSystem::scan);
+ ClassDB::bind_method(D_METHOD("scan_sources"), &EditorFileSystem::scan_changes);
+ ClassDB::bind_method(D_METHOD("update_file", "path"), &EditorFileSystem::update_file);
+ ClassDB::bind_method(D_METHOD("get_filesystem_path:EditorFileSystemDirectory", "path"), &EditorFileSystem::get_filesystem_path);
+ ClassDB::bind_method(D_METHOD("get_file_type", "path"), &EditorFileSystem::get_file_type);
+
+ ADD_SIGNAL(MethodInfo("filesystem_changed"));
+ ADD_SIGNAL(MethodInfo("sources_changed", PropertyInfo(Variant::BOOL, "exist")));
}
void EditorFileSystem::_update_extensions() {
@@ -1504,15 +1400,15 @@ void EditorFileSystem::_update_extensions() {
import_extensions.clear();
List<String> extensionsl;
- ResourceLoader::get_recognized_extensions_for_type("",&extensionsl);
- for(List<String>::Element *E = extensionsl.front();E;E=E->next()) {
+ ResourceLoader::get_recognized_extensions_for_type("", &extensionsl);
+ for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
valid_extensions.insert(E->get());
}
extensionsl.clear();
ResourceFormatImporter::get_singleton()->get_recognized_extensions(&extensionsl);
- for(List<String>::Element *E = extensionsl.front();E;E=E->next()) {
+ for (List<String>::Element *E = extensionsl.front(); E; E = E->next()) {
import_extensions.insert(E->get());
}
@@ -1520,31 +1416,29 @@ void EditorFileSystem::_update_extensions() {
EditorFileSystem::EditorFileSystem() {
- reimport_on_missing_imported_files = GLOBAL_DEF("editor/reimport_missing_imported_files",true);
+ reimport_on_missing_imported_files = GLOBAL_DEF("editor/reimport_missing_imported_files", true);
- singleton=this;
- filesystem=memnew( EditorFileSystemDirectory ); //like, empty
+ singleton = this;
+ filesystem = memnew(EditorFileSystemDirectory); //like, empty
thread = NULL;
- scanning=false;
- importing=false;
- use_threads=true;
- thread_sources=NULL;
- new_filesystem=NULL;
+ scanning = false;
+ importing = false;
+ use_threads = true;
+ thread_sources = NULL;
+ new_filesystem = NULL;
- scanning_changes=false;
+ scanning_changes = false;
ResourceSaver::set_save_callback(_resource_saved);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- if (da->change_dir("res://.import")!=OK) {
+ if (da->change_dir("res://.import") != OK) {
da->make_dir("res://.import");
}
memdelete(da);
- scan_total=0;
+ scan_total = 0;
}
EditorFileSystem::~EditorFileSystem() {
-
-
}
diff --git a/editor/editor_file_system.h b/editor/editor_file_system.h
index 10d9b919fc..da78ba9cfb 100644
--- a/editor/editor_file_system.h
+++ b/editor/editor_file_system.h
@@ -29,25 +29,24 @@
#ifndef EDITOR_FILE_SYSTEM_H
#define EDITOR_FILE_SYSTEM_H
-#include "scene/main/node.h"
-#include "os/thread.h"
#include "os/dir_access.h"
-#include "set.h"
+#include "os/thread.h"
#include "os/thread_safe.h"
+#include "scene/main/node.h"
+#include "set.h"
class FileAccess;
struct EditorProgressBG;
class EditorFileSystemDirectory : public Object {
- GDCLASS( EditorFileSystemDirectory,Object );
+ GDCLASS(EditorFileSystemDirectory, Object);
String name;
uint64_t modified_time;
bool verified; //used for checking changes
EditorFileSystemDirectory *parent;
- Vector<EditorFileSystemDirectory*> subdirs;
-
+ Vector<EditorFileSystemDirectory *> subdirs;
struct FileInfo {
String file;
@@ -56,25 +55,23 @@ class EditorFileSystemDirectory : public Object {
uint64_t import_modified_time;
Vector<String> deps;
bool verified; //used for checking changes
-
};
struct FileInfoSort {
- bool operator()(const FileInfo *p_a,const FileInfo *p_b) const {
- return p_a->file<p_b->file;
+ bool operator()(const FileInfo *p_a, const FileInfo *p_b) const {
+ return p_a->file < p_b->file;
}
};
void sort_files();
- Vector<FileInfo*> files;
+ Vector<FileInfo *> files;
static void _bind_methods();
+ friend class EditorFileSystem;
-friend class EditorFileSystem;
public:
-
String get_name();
String get_path() const;
@@ -88,9 +85,8 @@ public:
EditorFileSystemDirectory *get_parent();
- int find_file_index(const String& p_file) const;
- int find_dir_index(const String& p_dir) const;
-
+ int find_file_index(const String &p_file) const;
+ int find_dir_index(const String &p_dir) const;
EditorFileSystemDirectory();
~EditorFileSystemDirectory();
@@ -98,12 +94,10 @@ public:
class EditorFileSystem : public Node {
- GDCLASS( EditorFileSystem, Node );
+ GDCLASS(EditorFileSystem, Node);
_THREAD_SAFE_CLASS_
-
-
struct ItemAction {
enum Action {
@@ -121,8 +115,12 @@ class EditorFileSystem : public Node {
EditorFileSystemDirectory *new_dir;
EditorFileSystemDirectory::FileInfo *new_file;
- ItemAction() { action=ACTION_NONE; dir=NULL; new_dir=NULL; new_file=NULL; }
-
+ ItemAction() {
+ action = ACTION_NONE;
+ dir = NULL;
+ new_dir = NULL;
+ new_file = NULL;
+ }
};
bool use_threads;
@@ -136,7 +134,6 @@ class EditorFileSystem : public Node {
bool importing;
float scan_total;
-
void _scan_filesystem();
EditorFileSystemDirectory *filesystem;
@@ -152,32 +149,30 @@ class EditorFileSystem : public Node {
Vector<String> deps;
};
- HashMap<String,FileCache> file_cache;
+ HashMap<String, FileCache> file_cache;
struct ScanProgress {
float low;
float hi;
mutable EditorProgressBG *progress;
- void update(int p_current,int p_total) const;
- ScanProgress get_sub(int p_current,int p_total) const;
+ void update(int p_current, int p_total) const;
+ ScanProgress get_sub(int p_current, int p_total) const;
};
-
void _save_filesystem_cache();
- void _save_filesystem_cache(EditorFileSystemDirectory *p_dir,FileAccess *p_file);
+ void _save_filesystem_cache(EditorFileSystemDirectory *p_dir, FileAccess *p_file);
- bool _find_file(const String& p_file,EditorFileSystemDirectory ** r_d, int &r_file_pos) const;
+ bool _find_file(const String &p_file, EditorFileSystemDirectory **r_d, int &r_file_pos) const;
void _scan_fs_changes(EditorFileSystemDirectory *p_dir, const ScanProgress &p_progress);
-
int md_count;
Set<String> valid_extensions;
Set<String> import_extensions;
- void _scan_new_dir(EditorFileSystemDirectory *p_dir,DirAccess *da,const ScanProgress& p_progress);
+ void _scan_new_dir(EditorFileSystemDirectory *p_dir, DirAccess *da, const ScanProgress &p_progress);
Thread *thread_sources;
bool scanning_changes;
@@ -190,24 +185,22 @@ class EditorFileSystem : public Node {
bool _update_scan_actions();
- static void _resource_saved(const String& p_path);
+ static void _resource_saved(const String &p_path);
void _update_extensions();
void _reimport_file(const String &p_file);
- bool _check_missing_imported_files(const String& p_path);
+ bool _check_missing_imported_files(const String &p_path);
bool reimport_on_missing_imported_files;
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
- static EditorFileSystem* get_singleton() { return singleton; }
+public:
+ static EditorFileSystem *get_singleton() { return singleton; }
EditorFileSystemDirectory *get_filesystem();
bool is_scanning() const;
@@ -216,13 +209,13 @@ public:
void scan();
void scan_changes();
void get_changed_sources(List<String> *r_changed);
- void update_file(const String& p_file);
+ void update_file(const String &p_file);
- EditorFileSystemDirectory *get_filesystem_path(const String& p_path);
- String get_file_type(const String& p_file) const;
- EditorFileSystemDirectory* find_file(const String& p_file,int* r_index) const;
+ EditorFileSystemDirectory *get_filesystem_path(const String &p_path);
+ String get_file_type(const String &p_file) const;
+ EditorFileSystemDirectory *find_file(const String &p_file, int *r_index) const;
- void reimport_files(const Vector<String>& p_files);
+ void reimport_files(const Vector<String> &p_files);
EditorFileSystem();
~EditorFileSystem();
diff --git a/editor/editor_fonts.cpp b/editor/editor_fonts.cpp
index 3652a59978..8bfacb4a26 100644
--- a/editor/editor_fonts.cpp
+++ b/editor/editor_fonts.cpp
@@ -28,103 +28,97 @@
/*************************************************************************/
#include "editor_fonts.h"
+#include "builtin_fonts.h"
+#include "doc_code_font.h"
#include "doc_font.h"
#include "doc_title_font.h"
-#include "doc_code_font.h"
-#include "builtin_fonts.h"
-#include "editor_settings.h"
-#include "scene/resources/dynamic_font.h"
#include "editor_scale.h"
+#include "editor_settings.h"
#include "scene/resources/default_theme/default_theme.h"
+#include "scene/resources/dynamic_font.h"
-static Ref<BitmapFont> make_font(int p_height,int p_ascent, int p_valign, int p_charcount, const int *p_chars,const Ref<Texture> &p_texture) {
-
+static Ref<BitmapFont> make_font(int p_height, int p_ascent, int p_valign, int p_charcount, const int *p_chars, const Ref<Texture> &p_texture) {
- Ref<BitmapFont> font( memnew( BitmapFont ) );
- font->add_texture( p_texture );
+ Ref<BitmapFont> font(memnew(BitmapFont));
+ font->add_texture(p_texture);
- for (int i=0;i<p_charcount;i++) {
+ for (int i = 0; i < p_charcount; i++) {
- const int *c = &p_chars[i*8];
+ const int *c = &p_chars[i * 8];
- int chr=c[0];
+ int chr = c[0];
Rect2 frect;
- frect.pos.x=c[1];
- frect.pos.y=c[2];
- frect.size.x=c[3];
- frect.size.y=c[4];
- Point2 align( c[5], c[6]+p_valign);
- int advance=c[7];
-
-
- font->add_char( chr, 0, frect, align,advance );
-
+ frect.pos.x = c[1];
+ frect.pos.y = c[2];
+ frect.size.x = c[3];
+ frect.size.y = c[4];
+ Point2 align(c[5], c[6] + p_valign);
+ int advance = c[7];
+
+ font->add_char(chr, 0, frect, align, advance);
}
- font->set_height( p_height );
- font->set_ascent( p_ascent );
+ font->set_height(p_height);
+ font->set_ascent(p_ascent);
return font;
}
-#define MAKE_FALLBACKS(m_name)\
- m_name->add_fallback(DroidSansFallback);\
- m_name->add_fallback(DroidSansJapanese);\
- m_name->add_fallback(DroidSansArabic);\
- m_name->add_fallback(DroidSansHebrew);\
+#define MAKE_FALLBACKS(m_name) \
+ m_name->add_fallback(DroidSansFallback); \
+ m_name->add_fallback(DroidSansJapanese); \
+ m_name->add_fallback(DroidSansArabic); \
+ m_name->add_fallback(DroidSansHebrew); \
m_name->add_fallback(DroidSansThai);
-#define MAKE_DROID_SANS(m_name,m_size) \
- Ref<DynamicFont> m_name;\
- m_name.instance();\
- m_name->set_size(m_size);\
- m_name->set_font_data(DroidSans);\
+#define MAKE_DROID_SANS(m_name, m_size) \
+ Ref<DynamicFont> m_name; \
+ m_name.instance(); \
+ m_name->set_size(m_size); \
+ m_name->set_font_data(DroidSans); \
MAKE_FALLBACKS(m_name);
-
void editor_register_fonts(Ref<Theme> p_theme) {
/* Droid Sans */
Ref<DynamicFontData> DroidSans;
DroidSans.instance();
- DroidSans->set_font_ptr(_font_DroidSans,_font_DroidSans_size);
+ DroidSans->set_font_ptr(_font_DroidSans, _font_DroidSans_size);
DroidSans->set_force_autohinter(true); //just looks better..i think?
Ref<DynamicFontData> DroidSansFallback;
DroidSansFallback.instance();
- DroidSansFallback->set_font_ptr(_font_DroidSansFallback,_font_DroidSansFallback_size);
+ DroidSansFallback->set_font_ptr(_font_DroidSansFallback, _font_DroidSansFallback_size);
DroidSansFallback->set_force_autohinter(true); //just looks better..i think?
Ref<DynamicFontData> DroidSansJapanese;
DroidSansJapanese.instance();
- DroidSansJapanese->set_font_ptr(_font_DroidSansJapanese,_font_DroidSansJapanese_size);
+ DroidSansJapanese->set_font_ptr(_font_DroidSansJapanese, _font_DroidSansJapanese_size);
DroidSansJapanese->set_force_autohinter(true); //just looks better..i think?
Ref<DynamicFontData> DroidSansArabic;
DroidSansArabic.instance();
- DroidSansArabic->set_font_ptr(_font_DroidSansArabic,_font_DroidSansArabic_size);
+ DroidSansArabic->set_font_ptr(_font_DroidSansArabic, _font_DroidSansArabic_size);
DroidSansArabic->set_force_autohinter(true); //just looks better..i think?
Ref<DynamicFontData> DroidSansHebrew;
DroidSansHebrew.instance();
- DroidSansHebrew->set_font_ptr(_font_DroidSansHebrew,_font_DroidSansHebrew_size);
+ DroidSansHebrew->set_font_ptr(_font_DroidSansHebrew, _font_DroidSansHebrew_size);
DroidSansHebrew->set_force_autohinter(true); //just looks better..i think?
Ref<DynamicFontData> DroidSansThai;
DroidSansThai.instance();
- DroidSansThai->set_font_ptr(_font_DroidSansThai,_font_DroidSansThai_size);
+ DroidSansThai->set_font_ptr(_font_DroidSansThai, _font_DroidSansThai_size);
DroidSansThai->set_force_autohinter(true); //just looks better..i think?
/* Source Code Pro */
-
Ref<DynamicFontData> dfmono;
dfmono.instance();
- dfmono->set_font_ptr(_font_source_code_pro,_font_source_code_pro_size);
+ dfmono->set_font_ptr(_font_source_code_pro, _font_source_code_pro_size);
//dfd->set_force_autohinter(true); //just looks better..i think?
- MAKE_DROID_SANS(df,int(EditorSettings::get_singleton()->get("interface/font_size"))*EDSCALE);
-
+ MAKE_DROID_SANS(df, int(EditorSettings::get_singleton()->get("interface/font_size")) * EDSCALE);
p_theme->set_default_theme_font(df);
@@ -132,37 +126,31 @@ void editor_register_fonts(Ref<Theme> p_theme) {
//Ref<BitmapFont> doc_title_font = make_font(_bi_font_doc_title_font_height,_bi_font_doc_title_font_ascent,0,_bi_font_doc_title_font_charcount,_bi_font_doc_title_font_characters,p_theme->get_icon("DocTitleFont","EditorIcons"));
//Ref<BitmapFont> doc_code_font = make_font(_bi_font_doc_code_font_height,_bi_font_doc_code_font_ascent,0,_bi_font_doc_code_font_charcount,_bi_font_doc_code_font_characters,p_theme->get_icon("DocCodeFont","EditorIcons"));
- MAKE_DROID_SANS(df_title,int(EDITOR_DEF("text_editor/help/help_title_font_size",18))*EDSCALE);
-
- MAKE_DROID_SANS(df_doc,int(EDITOR_DEF("text_editor/help/help_font_size",16))*EDSCALE);
+ MAKE_DROID_SANS(df_title, int(EDITOR_DEF("text_editor/help/help_title_font_size", 18)) * EDSCALE);
+ MAKE_DROID_SANS(df_doc, int(EDITOR_DEF("text_editor/help/help_font_size", 16)) * EDSCALE);
- p_theme->set_font("doc","EditorFonts",df_doc);
- p_theme->set_font("doc_title","EditorFonts",df_title);
-
+ p_theme->set_font("doc", "EditorFonts", df_doc);
+ p_theme->set_font("doc_title", "EditorFonts", df_title);
Ref<DynamicFont> df_code;
df_code.instance();
- df_code->set_size(int(EditorSettings::get_singleton()->get("interface/source_font_size"))*EDSCALE);
+ df_code->set_size(int(EditorSettings::get_singleton()->get("interface/source_font_size")) * EDSCALE);
df_code->set_font_data(dfmono);
MAKE_FALLBACKS(df_code);
- p_theme->set_font("source","EditorFonts",df_code);
+ p_theme->set_font("source", "EditorFonts", df_code);
Ref<DynamicFont> df_doc_code;
df_doc_code.instance();
- df_doc_code->set_size(int(EDITOR_DEF("text_editor/help/help_source_font_size",14))*EDSCALE);
+ df_doc_code->set_size(int(EDITOR_DEF("text_editor/help/help_source_font_size", 14)) * EDSCALE);
df_doc_code->set_font_data(dfmono);
MAKE_FALLBACKS(df_doc_code);
-
- p_theme->set_font("doc_source","EditorFonts",df_doc_code);
-
+ p_theme->set_font("doc_source", "EditorFonts", df_doc_code);
//replace default theme
Ref<Texture> di;
Ref<StyleBox> ds;
- fill_default_theme(p_theme,df,df_doc,di,ds,EDSCALE);
-
-
+ fill_default_theme(p_theme, df, df_doc, di, ds, EDSCALE);
}
diff --git a/editor/editor_help.cpp b/editor/editor_help.cpp
index 7ef7658132..161326ebab 100644
--- a/editor/editor_help.cpp
+++ b/editor/editor_help.cpp
@@ -28,25 +28,25 @@
/*************************************************************************/
#include "editor_help.h"
+#include "doc_data_compressed.h"
+#include "editor/plugins/script_editor_plugin.h"
#include "editor_node.h"
#include "editor_settings.h"
#include "os/keyboard.h"
-#include "doc_data_compressed.h"
-#include "editor/plugins/script_editor_plugin.h"
void EditorHelpSearch::popup() {
popup_centered_ratio(0.6);
- if (search_box->get_text()!="") {
+ if (search_box->get_text() != "") {
search_box->select_all();
_update_search();
}
search_box->grab_focus();
}
-void EditorHelpSearch::popup(const String& p_term) {
+void EditorHelpSearch::popup(const String &p_term) {
popup_centered_ratio(0.6);
- if (p_term!="") {
+ if (p_term != "") {
search_box->set_text(p_term);
search_box->select_all();
_update_search();
@@ -55,24 +55,21 @@ void EditorHelpSearch::popup(const String& p_term) {
search_box->grab_focus();
}
-
-void EditorHelpSearch::_text_changed(const String& p_newtext) {
+void EditorHelpSearch::_text_changed(const String &p_newtext) {
_update_search();
}
-void EditorHelpSearch::_sbox_input(const InputEvent& p_ie) {
+void EditorHelpSearch::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY && (
- p_ie.key.scancode == KEY_UP ||
- p_ie.key.scancode == KEY_DOWN ||
- p_ie.key.scancode == KEY_PAGEUP ||
- p_ie.key.scancode == KEY_PAGEDOWN ) ) {
+ if (p_ie.type == InputEvent::KEY && (p_ie.key.scancode == KEY_UP ||
+ p_ie.key.scancode == KEY_DOWN ||
+ p_ie.key.scancode == KEY_PAGEUP ||
+ p_ie.key.scancode == KEY_PAGEDOWN)) {
- search_options->call("_gui_input",p_ie);
+ search_options->call("_gui_input", p_ie);
search_box->accept_event();
}
-
}
void EditorHelpSearch::_update_search() {
@@ -88,178 +85,161 @@ void EditorHelpSearch::_update_search() {
List<StringName> type_list;
ClassDB::get_class_list(&type_list);
- DocData *doc=EditorHelp::get_doc_data();
+ DocData *doc = EditorHelp::get_doc_data();
String term = search_box->get_text();
- if (term.length()<2)
+ if (term.length() < 2)
return;
TreeItem *root = search_options->create_item();
-
-
- Ref<Texture> def_icon = get_icon("Node","EditorIcons");
+ Ref<Texture> def_icon = get_icon("Node", "EditorIcons");
//classes first
- for (Map<String,DocData::ClassDoc>::Element *E=doc->class_list.front();E;E=E->next()) {
+ for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
- if (E->key().findn(term)!=-1) {
+ if (E->key().findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_name:"+E->key());
- item->set_text(0,E->key()+" (Class)");
- if (has_icon(E->key(),"EditorIcons"))
- item->set_icon(0,get_icon(E->key(),"EditorIcons"));
+ item->set_metadata(0, "class_name:" + E->key());
+ item->set_text(0, E->key() + " (Class)");
+ if (has_icon(E->key(), "EditorIcons"))
+ item->set_icon(0, get_icon(E->key(), "EditorIcons"));
else
- item->set_icon(0,def_icon);
-
-
+ item->set_icon(0, def_icon);
}
-
}
//class methods, etc second
- for (Map<String,DocData::ClassDoc>::Element *E=doc->class_list.front();E;E=E->next()) {
+ for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
-
- DocData::ClassDoc & c = E->get();
+ DocData::ClassDoc &c = E->get();
Ref<Texture> cicon;
- if (has_icon(E->key(),"EditorIcons"))
- cicon=get_icon(E->key(),"EditorIcons");
+ if (has_icon(E->key(), "EditorIcons"))
+ cicon = get_icon(E->key(), "EditorIcons");
else
- cicon=def_icon;
-
+ cicon = def_icon;
- for(int i=0;i<c.methods.size();i++) {
- if( (term.begins_with(".") && c.methods[i].name.begins_with(term.right(1)))
- || (term.ends_with("(") && c.methods[i].name.ends_with(term.left(term.length()-1).strip_edges()))
- || (term.begins_with(".") && term.ends_with("(") && c.methods[i].name==term.substr(1,term.length()-2).strip_edges())
- || c.methods[i].name.findn(term)!=-1) {
+ for (int i = 0; i < c.methods.size(); i++) {
+ if ((term.begins_with(".") && c.methods[i].name.begins_with(term.right(1))) || (term.ends_with("(") && c.methods[i].name.ends_with(term.left(term.length() - 1).strip_edges())) || (term.begins_with(".") && term.ends_with("(") && c.methods[i].name == term.substr(1, term.length() - 2).strip_edges()) || c.methods[i].name.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_method:"+E->key()+":"+c.methods[i].name);
- item->set_text(0,E->key()+"."+c.methods[i].name+" (Method)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_method:" + E->key() + ":" + c.methods[i].name);
+ item->set_text(0, E->key() + "." + c.methods[i].name + " (Method)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.signals.size();i++) {
+ for (int i = 0; i < c.signals.size(); i++) {
- if (c.signals[i].name.findn(term)!=-1) {
+ if (c.signals[i].name.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_signal:"+E->key()+":"+c.signals[i].name);
- item->set_text(0,E->key()+"."+c.signals[i].name+" (Signal)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_signal:" + E->key() + ":" + c.signals[i].name);
+ item->set_text(0, E->key() + "." + c.signals[i].name + " (Signal)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.constants.size();i++) {
+ for (int i = 0; i < c.constants.size(); i++) {
- if (c.constants[i].name.findn(term)!=-1) {
+ if (c.constants[i].name.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_constant:"+E->key()+":"+c.constants[i].name);
- item->set_text(0,E->key()+"."+c.constants[i].name+" (Constant)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_constant:" + E->key() + ":" + c.constants[i].name);
+ item->set_text(0, E->key() + "." + c.constants[i].name + " (Constant)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.properties.size();i++) {
+ for (int i = 0; i < c.properties.size(); i++) {
- if (c.properties[i].name.findn(term)!=-1) {
+ if (c.properties[i].name.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_property:"+E->key()+":"+c.properties[i].name);
- item->set_text(0,E->key()+"."+c.properties[i].name+" (Property)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_property:" + E->key() + ":" + c.properties[i].name);
+ item->set_text(0, E->key() + "." + c.properties[i].name + " (Property)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.theme_properties.size();i++) {
+ for (int i = 0; i < c.theme_properties.size(); i++) {
- if (c.theme_properties[i].name.findn(term)!=-1) {
+ if (c.theme_properties[i].name.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_theme_item:"+E->key()+":"+c.theme_properties[i].name);
- item->set_text(0,E->key()+"."+c.theme_properties[i].name+" (Theme Item)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_theme_item:" + E->key() + ":" + c.theme_properties[i].name);
+ item->set_text(0, E->key() + "." + c.theme_properties[i].name + " (Theme Item)");
+ item->set_icon(0, cicon);
}
}
-
-
}
//same but descriptions
- for (Map<String,DocData::ClassDoc>::Element *E=doc->class_list.front();E;E=E->next()) {
+ for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
-
- DocData::ClassDoc & c = E->get();
+ DocData::ClassDoc &c = E->get();
Ref<Texture> cicon;
- if (has_icon(E->key(),"EditorIcons"))
- cicon=get_icon(E->key(),"EditorIcons");
+ if (has_icon(E->key(), "EditorIcons"))
+ cicon = get_icon(E->key(), "EditorIcons");
else
- cicon=def_icon;
-
- if (c.description.findn(term)!=-1) {
+ cicon = def_icon;
+ if (c.description.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_desc:"+E->key());
- item->set_text(0,E->key()+" (Class Description)");
- item->set_icon(0,cicon);
-
+ item->set_metadata(0, "class_desc:" + E->key());
+ item->set_text(0, E->key() + " (Class Description)");
+ item->set_icon(0, cicon);
}
- for(int i=0;i<c.methods.size();i++) {
+ for (int i = 0; i < c.methods.size(); i++) {
- if (c.methods[i].description.findn(term)!=-1) {
+ if (c.methods[i].description.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_method_desc:"+E->key()+":"+c.methods[i].name);
- item->set_text(0,E->key()+"."+c.methods[i].name+" (Method Description)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_method_desc:" + E->key() + ":" + c.methods[i].name);
+ item->set_text(0, E->key() + "." + c.methods[i].name + " (Method Description)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.signals.size();i++) {
+ for (int i = 0; i < c.signals.size(); i++) {
- if (c.signals[i].description.findn(term)!=-1) {
+ if (c.signals[i].description.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_signal:"+E->key()+":"+c.signals[i].name);
- item->set_text(0,E->key()+"."+c.signals[i].name+" (Signal Description)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_signal:" + E->key() + ":" + c.signals[i].name);
+ item->set_text(0, E->key() + "." + c.signals[i].name + " (Signal Description)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.constants.size();i++) {
+ for (int i = 0; i < c.constants.size(); i++) {
- if (c.constants[i].description.findn(term)!=-1) {
+ if (c.constants[i].description.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_constant:"+E->key()+":"+c.constants[i].name);
- item->set_text(0,E->key()+"."+c.constants[i].name+" (Constant Description)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_constant:" + E->key() + ":" + c.constants[i].name);
+ item->set_text(0, E->key() + "." + c.constants[i].name + " (Constant Description)");
+ item->set_icon(0, cicon);
}
}
- for(int i=0;i<c.properties.size();i++) {
+ for (int i = 0; i < c.properties.size(); i++) {
- if (c.properties[i].description.findn(term)!=-1) {
+ if (c.properties[i].description.findn(term) != -1) {
TreeItem *item = search_options->create_item(root);
- item->set_metadata(0,"class_property_desc:"+E->key()+":"+c.properties[i].name);
- item->set_text(0,E->key()+"."+c.properties[i].name+" (Property Description)");
- item->set_icon(0,cicon);
+ item->set_metadata(0, "class_property_desc:" + E->key() + ":" + c.properties[i].name);
+ item->set_text(0, E->key() + "." + c.properties[i].name + " (Property Description)");
+ item->set_icon(0, cicon);
}
}
-
}
- get_ok()->set_disabled(root->get_children()==NULL);
-
+ get_ok()->set_disabled(root->get_children() == NULL);
}
void EditorHelpSearch::_confirmed() {
@@ -268,22 +248,22 @@ void EditorHelpSearch::_confirmed() {
if (!ti)
return;
- String mdata=ti->get_metadata(0);
- emit_signal("go_to_help",mdata);
- editor->call("_editor_select",EditorNode::EDITOR_SCRIPT); // in case EditorHelpSearch beeen invoked on top of other editor window
+ String mdata = ti->get_metadata(0);
+ emit_signal("go_to_help", mdata);
+ editor->call("_editor_select", EditorNode::EDITOR_SCRIPT); // in case EditorHelpSearch beeen invoked on top of other editor window
// go to that
hide();
}
void EditorHelpSearch::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- connect("confirmed",this,"_confirmed");
+ connect("confirmed", this, "_confirmed");
_update_search();
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (is_visible_in_tree()) {
@@ -291,49 +271,44 @@ void EditorHelpSearch::_notification(int p_what) {
search_box->select_all();
}
}
-
}
-
void EditorHelpSearch::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_changed"),&EditorHelpSearch::_text_changed);
- ClassDB::bind_method(D_METHOD("_confirmed"),&EditorHelpSearch::_confirmed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&EditorHelpSearch::_sbox_input);
- ClassDB::bind_method(D_METHOD("_update_search"),&EditorHelpSearch::_update_search);
+ ClassDB::bind_method(D_METHOD("_text_changed"), &EditorHelpSearch::_text_changed);
+ ClassDB::bind_method(D_METHOD("_confirmed"), &EditorHelpSearch::_confirmed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &EditorHelpSearch::_sbox_input);
+ ClassDB::bind_method(D_METHOD("_update_search"), &EditorHelpSearch::_update_search);
ADD_SIGNAL(MethodInfo("go_to_help"));
-
}
-
EditorHelpSearch::EditorHelpSearch() {
- editor=EditorNode::get_singleton();
- VBoxContainer *vbc = memnew( VBoxContainer );
+ editor = EditorNode::get_singleton();
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
- HBoxContainer *sb_hb = memnew( HBoxContainer);
- search_box = memnew( LineEdit );
+ HBoxContainer *sb_hb = memnew(HBoxContainer);
+ search_box = memnew(LineEdit);
sb_hb->add_child(search_box);
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
- Button *sb = memnew( Button(TTR("Search")));
- sb->connect("pressed",this,"_update_search");
+ Button *sb = memnew(Button(TTR("Search")));
+ sb->connect("pressed", this, "_update_search");
sb_hb->add_child(sb);
- vbc->add_margin_child(TTR("Search:"),sb_hb);
- search_box->connect("text_changed",this,"_text_changed");
- search_box->connect("gui_input",this,"_sbox_input");
- search_options = memnew( Tree );
- vbc->add_margin_child(TTR("Matches:"),search_options,true);
+ vbc->add_margin_child(TTR("Search:"), sb_hb);
+ search_box->connect("text_changed", this, "_text_changed");
+ search_box->connect("gui_input", this, "_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);
register_text_enter(search_box);
set_hide_on_ok(false);
- search_options->connect("item_activated",this,"_confirmed");
+ search_options->connect("item_activated", this, "_confirmed");
set_title(TTR("Search Help"));
//search_options->set_hide_root(true);
-
}
/////////////////////////////////
@@ -341,9 +316,7 @@ EditorHelpSearch::EditorHelpSearch() {
////////////////////////////////////
/// /////////////////////////////////
-
-
-void EditorHelpIndex::add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root) {
+void EditorHelpIndex::add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem *p_root) {
if (p_types.has(p_type))
return;
@@ -352,53 +325,48 @@ void EditorHelpIndex::add_type(const String& p_type,HashMap<String,TreeItem*>& p
return;
*/
- String inherits=EditorHelp::get_doc_data()->class_list[p_type].inherits;
-
- TreeItem *parent=p_root;
+ String inherits = EditorHelp::get_doc_data()->class_list[p_type].inherits;
+ TreeItem *parent = p_root;
if (inherits.length()) {
if (!p_types.has(inherits)) {
- add_type(inherits,p_types,p_root);
+ add_type(inherits, p_types, p_root);
}
- if (p_types.has(inherits) )
- parent=p_types[inherits];
+ if (p_types.has(inherits))
+ parent = p_types[inherits];
}
TreeItem *item = class_list->create_item(parent);
- item->set_metadata(0,p_type);
- item->set_tooltip(0,EditorHelp::get_doc_data()->class_list[p_type].brief_description);
- item->set_text(0,p_type);
-
+ item->set_metadata(0, p_type);
+ item->set_tooltip(0, EditorHelp::get_doc_data()->class_list[p_type].brief_description);
+ item->set_text(0, p_type);
- if (has_icon(p_type,"EditorIcons")) {
+ if (has_icon(p_type, "EditorIcons")) {
- item->set_icon(0, get_icon(p_type,"EditorIcons"));
+ item->set_icon(0, get_icon(p_type, "EditorIcons"));
}
- p_types[p_type]=item;
+ p_types[p_type] = item;
}
-
void EditorHelpIndex::_tree_item_selected() {
-
- TreeItem *s=class_list->get_selected();
+ TreeItem *s = class_list->get_selected();
if (!s)
return;
- emit_signal("open_class",s->get_text(0));
+ emit_signal("open_class", s->get_text(0));
hide();
//_goto_desc(s->get_text(0));
-
}
-void EditorHelpIndex::select_class(const String& p_class) {
+void EditorHelpIndex::select_class(const String &p_class) {
if (!tree_item_map.has(p_class))
return;
@@ -416,19 +384,19 @@ void EditorHelpIndex::popup() {
void EditorHelpIndex::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
_update_class_list();
- connect("confirmed",this,"_tree_item_selected");
+ connect("confirmed", this, "_tree_item_selected");
- } else if (p_what==NOTIFICATION_POST_POPUP) {
+ } else if (p_what == NOTIFICATION_POST_POPUP) {
search_box->call_deferred("grab_focus");
}
}
-void EditorHelpIndex::_text_changed(const String& p_text) {
+void EditorHelpIndex::_text_changed(const String &p_text) {
_update_class_list();
}
@@ -443,23 +411,23 @@ void EditorHelpIndex::_update_class_list() {
String filter = search_box->get_text().strip_edges();
String to_select = "";
- for(Map<String,DocData::ClassDoc>::Element *E=EditorHelp::get_doc_data()->class_list.front();E;E=E->next()) {
+ for (Map<String, DocData::ClassDoc>::Element *E = EditorHelp::get_doc_data()->class_list.front(); E; E = E->next()) {
if (filter == "") {
- add_type(E->key(),tree_item_map,root);
+ add_type(E->key(), tree_item_map, root);
} else {
bool found = false;
String type = E->key();
- while(type != "") {
+ while (type != "") {
if (filter.is_subsequence_ofi(type)) {
if (to_select.empty()) {
to_select = type;
}
- found=true;
+ found = true;
break;
}
@@ -467,7 +435,7 @@ void EditorHelpIndex::_update_class_list() {
}
if (found) {
- add_type(E->key(),tree_item_map,root);
+ add_type(E->key(), tree_item_map, root);
}
}
}
@@ -479,37 +447,33 @@ void EditorHelpIndex::_update_class_list() {
}
}
+void EditorHelpIndex::_sbox_input(const InputEvent &p_ie) {
-void EditorHelpIndex::_sbox_input(const InputEvent& p_ie) {
+ if (p_ie.type == InputEvent::KEY && (p_ie.key.scancode == KEY_UP ||
+ p_ie.key.scancode == KEY_DOWN ||
+ p_ie.key.scancode == KEY_PAGEUP ||
+ p_ie.key.scancode == KEY_PAGEDOWN)) {
- if (p_ie.type==InputEvent::KEY && (
- p_ie.key.scancode == KEY_UP ||
- p_ie.key.scancode == KEY_DOWN ||
- p_ie.key.scancode == KEY_PAGEUP ||
- p_ie.key.scancode == KEY_PAGEDOWN ) ) {
-
- class_list->call("_gui_input",p_ie);
+ class_list->call("_gui_input", p_ie);
search_box->accept_event();
}
}
void EditorHelpIndex::_bind_methods() {
- ClassDB::bind_method("_tree_item_selected",&EditorHelpIndex::_tree_item_selected);
- ClassDB::bind_method("_text_changed",&EditorHelpIndex::_text_changed);
- ClassDB::bind_method("_sbox_input",&EditorHelpIndex::_sbox_input);
- ClassDB::bind_method("select_class",&EditorHelpIndex::select_class);
- ADD_SIGNAL( MethodInfo("open_class"));
+ ClassDB::bind_method("_tree_item_selected", &EditorHelpIndex::_tree_item_selected);
+ ClassDB::bind_method("_text_changed", &EditorHelpIndex::_text_changed);
+ ClassDB::bind_method("_sbox_input", &EditorHelpIndex::_sbox_input);
+ ClassDB::bind_method("select_class", &EditorHelpIndex::select_class);
+ ADD_SIGNAL(MethodInfo("open_class"));
}
-
-
EditorHelpIndex::EditorHelpIndex() {
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
vbc->add_margin_child(TTR("Search:"), search_box);
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
@@ -518,52 +482,47 @@ EditorHelpIndex::EditorHelpIndex() {
search_box->connect("text_changed", this, "_text_changed");
search_box->connect("gui_input", this, "_sbox_input");
- class_list = memnew( Tree );
- vbc->add_margin_child(TTR("Class List:")+" ", class_list, true);
+ class_list = memnew(Tree);
+ vbc->add_margin_child(TTR("Class List:") + " ", class_list, true);
class_list->set_v_size_flags(SIZE_EXPAND_FILL);
- class_list->connect("item_activated",this,"_tree_item_selected");
+ class_list->connect("item_activated", this, "_tree_item_selected");
get_ok()->set_text(TTR("Open"));
set_title(TTR("Search Classes"));
}
-
-
/////////////////////////////////
////////////////////////////////////
/// /////////////////////////////////
-DocData *EditorHelp::doc=NULL;
+DocData *EditorHelp::doc = NULL;
-void EditorHelp::_unhandled_key_input(const InputEvent& p_ev) {
+void EditorHelp::_unhandled_key_input(const InputEvent &p_ev) {
if (!is_visible_in_tree())
return;
- if ( p_ev.key.mod.control && p_ev.key.scancode==KEY_F) {
+ if (p_ev.key.mod.control && p_ev.key.scancode == KEY_F) {
search->grab_focus();
search->select_all();
}
}
-void EditorHelp::_search(const String&) {
+void EditorHelp::_search(const String &) {
- if (search->get_text()=="")
+ if (search->get_text() == "")
return;
-
- String stext=search->get_text();
- bool keep = prev_search==stext;
+ String stext = search->get_text();
+ bool keep = prev_search == stext;
bool ret = class_desc->search(stext, keep);
if (!ret) {
class_desc->search(stext, false);
}
- prev_search=stext;
-
-
+ prev_search = stext;
}
#if 0
@@ -607,66 +566,59 @@ void EditorHelp::_button_pressed(int p_idx) {
}
}
-
#endif
-void EditorHelp::_class_list_select(const String& p_select) {
+void EditorHelp::_class_list_select(const String &p_select) {
_goto_desc(p_select);
}
-void EditorHelp::_class_desc_select(const String& p_select) {
-
-
+void EditorHelp::_class_desc_select(const String &p_select) {
//print_line("LINK: "+p_select);
if (p_select.begins_with("#")) {
//_goto_desc(p_select.substr(1,p_select.length()));
- emit_signal("go_to_help","class_name:"+p_select.substr(1,p_select.length()));
+ emit_signal("go_to_help", "class_name:" + p_select.substr(1, p_select.length()));
return;
} else if (p_select.begins_with("@")) {
- String m = p_select.substr(1,p_select.length());
+ String m = p_select.substr(1, p_select.length());
- if (m.find(".")!=-1) {
+ if (m.find(".") != -1) {
//must go somewhere else
- emit_signal("go_to_help","class_method:"+m.get_slice(".",0)+":"+m.get_slice(".",0));
+ emit_signal("go_to_help", "class_method:" + m.get_slice(".", 0) + ":" + m.get_slice(".", 0));
} else {
if (!method_line.has(m))
return;
class_desc->scroll_to_line(method_line[m]);
}
-
}
-
-
}
-void EditorHelp::_class_desc_input(const InputEvent& p_input) {
- if (p_input.type==InputEvent::MOUSE_BUTTON && p_input.mouse_button.pressed && p_input.mouse_button.button_index==1) {
+void EditorHelp::_class_desc_input(const InputEvent &p_input) {
+ if (p_input.type == InputEvent::MOUSE_BUTTON && p_input.mouse_button.pressed && p_input.mouse_button.button_index == 1) {
class_desc->set_selection_enabled(false);
class_desc->set_selection_enabled(true);
}
set_focused();
}
-void EditorHelp::_add_type(const String& p_type) {
+void EditorHelp::_add_type(const String &p_type) {
String t = p_type;
- if (t=="")
- t="void";
- bool can_ref = (t!="int" && t!="real" && t!="bool" && t!="void");
+ if (t == "")
+ t = "void";
+ bool can_ref = (t != "int" && t != "real" && t != "bool" && t != "void");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/base_type_color"));
if (can_ref)
- class_desc->push_meta("#"+t); //class
+ class_desc->push_meta("#" + t); //class
class_desc->add_text(t);
if (can_ref)
class_desc->pop();
class_desc->pop();
-
}
void EditorHelp::_scroll_changed(double p_scroll) {
@@ -675,51 +627,48 @@ void EditorHelp::_scroll_changed(double p_scroll) {
return;
if (!class_desc->get_v_scroll()->is_visible())
- p_scroll=0;
+ p_scroll = 0;
//history[p].scroll=p_scroll;
}
-Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
+Error EditorHelp::_goto_desc(const String &p_class, int p_vscr) {
//ERR_FAIL_COND(!doc->class_list.has(p_class));
if (!doc->class_list.has(p_class))
return ERR_DOES_NOT_EXIST;
-
//if (tree_item_map.has(p_class)) {
- select_locked = true;
+ select_locked = true;
//}
class_desc->show();
//tabs->set_current_tab(PAGE_CLASS_DESC);
- description_line=0;
+ description_line = 0;
- if (p_class==edited_class)
+ if (p_class == edited_class)
return OK; //already there
- scroll_locked=true;
+ scroll_locked = true;
class_desc->clear();
method_line.clear();
- edited_class=p_class;
+ edited_class = p_class;
//edited_class->show();
-
- DocData::ClassDoc cd=doc->class_list[p_class]; //make a copy, so we can sort without worrying
+ DocData::ClassDoc cd = doc->class_list[p_class]; //make a copy, so we can sort without worrying
Color h_color;
- Ref<Font> doc_font = get_font("doc","EditorFonts");
- Ref<Font> doc_title_font = get_font("doc_title","EditorFonts");
- Ref<Font> doc_code_font = get_font("doc_source","EditorFonts");
-
+ Ref<Font> doc_font = get_font("doc", "EditorFonts");
+ Ref<Font> doc_title_font = get_font("doc_title", "EditorFonts");
+ Ref<Font> doc_code_font = get_font("doc_source", "EditorFonts");
- h_color=Color(1,1,1,1);
+ h_color = Color(1, 1, 1, 1);
class_desc->push_font(doc_title_font);
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
- class_desc->add_text(TTR("Class:")+" ");
+ class_desc->add_text(TTR("Class:") + " ");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/base_type_color"));
_add_text(p_class);
class_desc->pop();
@@ -727,11 +676,11 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->add_newline();
- if (cd.inherits!="") {
+ if (cd.inherits != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
- class_desc->add_text(TTR("Inherits:")+" ");
+ class_desc->add_text(TTR("Inherits:") + " ");
class_desc->pop();
class_desc->pop();
@@ -758,14 +707,14 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
bool found = false;
bool prev = false;
- for (Map<String,DocData::ClassDoc>::Element *E=doc->class_list.front();E;E=E->next()) {
+ for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
if (E->get().inherits == cd.name) {
if (!found) {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
- class_desc->add_text(TTR("Inherited by:")+" ");
+ class_desc->add_text(TTR("Inherited by:") + " ");
class_desc->pop();
class_desc->pop();
@@ -792,7 +741,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
- if (cd.brief_description!="") {
+ if (cd.brief_description != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
@@ -803,7 +752,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
//class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(cd.brief_description);
class_desc->pop();
@@ -814,11 +763,10 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
}
Set<String> skip_methods;
- bool property_descr=false;
+ bool property_descr = false;
if (cd.properties.size()) {
-
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Members:"));
@@ -828,10 +776,10 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->push_indent(1);
class_desc->push_table(2);
- class_desc->set_table_column_expand(1,1);
+ class_desc->set_table_column_expand(1, 1);
- for(int i=0;i<cd.properties.size();i++) {
- property_line[cd.properties[i].name]=class_desc->get_line_count()-2; //gets overriden if description
+ for (int i = 0; i < cd.properties.size(); i++) {
+ property_line[cd.properties[i].name] = class_desc->get_line_count() - 2; //gets overriden if description
class_desc->push_cell();
class_desc->push_align(RichTextLabel::ALIGN_RIGHT);
@@ -842,25 +790,23 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->pop();
- bool describe=false;
+ bool describe = false;
- if (cd.properties[i].setter!="") {
+ if (cd.properties[i].setter != "") {
skip_methods.insert(cd.properties[i].setter);
- describe=true;
-
+ describe = true;
}
- if (cd.properties[i].getter!="") {
+ if (cd.properties[i].getter != "") {
skip_methods.insert(cd.properties[i].getter);
- describe=true;
+ describe = true;
}
- if (cd.properties[i].description!="") {
- describe=true;
-
+ if (cd.properties[i].description != "") {
+ describe = true;
}
class_desc->push_cell();
if (describe) {
- class_desc->push_meta("@"+cd.properties[i].name);
+ class_desc->push_meta("@" + cd.properties[i].name);
}
class_desc->push_font(doc_code_font);
@@ -871,42 +817,36 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
}
-
- if (cd.properties[i].brief_description!="") {
+ if (cd.properties[i].brief_description != "") {
class_desc->push_font(doc_font);
class_desc->add_text(" ");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/comment_color"));
_add_text(cd.properties[i].description);
class_desc->pop();
class_desc->pop();
-
}
if (describe) {
- property_descr=true;
+ property_descr = true;
}
-
class_desc->pop();
class_desc->pop();
class_desc->pop();
-
}
-
class_desc->pop(); //table
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
}
-
- bool method_descr=false;
+ bool method_descr = false;
bool sort_methods = EditorSettings::get_singleton()->get("text_editor/help/sort_functions_alphabetically");
Vector<DocData::MethodDoc> methods;
- for(int i=0;i<cd.methods.size();i++) {
+ for (int i = 0; i < cd.methods.size(); i++) {
if (skip_methods.has(cd.methods[i].name))
continue;
methods.push_back(cd.methods[i]);
@@ -928,14 +868,13 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->push_indent(1);
class_desc->push_table(2);
- class_desc->set_table_column_expand(1,1);
+ class_desc->set_table_column_expand(1, 1);
- for(int i=0;i<methods.size();i++) {
+ for (int i = 0; i < methods.size(); i++) {
class_desc->push_cell();
-
- method_line[methods[i].name]=class_desc->get_line_count()-2; //gets overriden if description
+ method_line[methods[i].name] = class_desc->get_line_count() - 2; //gets overriden if description
class_desc->push_align(RichTextLabel::ALIGN_RIGHT);
class_desc->push_font(doc_code_font);
_add_type(methods[i].return_type);
@@ -946,26 +885,26 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->push_cell();
class_desc->push_font(doc_code_font);
- if (methods[i].description!="") {
- method_descr=true;
- class_desc->push_meta("@"+methods[i].name);
+ if (methods[i].description != "") {
+ method_descr = true;
+ class_desc->push_meta("@" + methods[i].name);
}
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
_add_text(methods[i].name);
class_desc->pop();
- if (methods[i].description!="")
+ if (methods[i].description != "")
class_desc->pop();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(methods[i].arguments.size()?"( ":"(");
+ class_desc->add_text(methods[i].arguments.size() ? "( " : "(");
class_desc->pop();
- for(int j=0;j<methods[i].arguments.size();j++) {
+ for (int j = 0; j < methods[i].arguments.size(); j++) {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- if (j>0)
+ if (j > 0)
class_desc->add_text(", ");
_add_type(methods[i].arguments[j].type);
class_desc->add_text(" ");
_add_text(methods[i].arguments[j].name);
- if (methods[i].arguments[j].default_value!="") {
+ if (methods[i].arguments[j].default_value != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
class_desc->add_text("=");
@@ -976,7 +915,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
}
- if (methods[i].qualifiers.find("vararg")!=-1) {
+ if (methods[i].qualifiers.find("vararg") != -1) {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
class_desc->add_text(",");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
@@ -986,32 +925,27 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
}
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(methods[i].arguments.size()?" )":")");
+ class_desc->add_text(methods[i].arguments.size() ? " )" : ")");
class_desc->pop();
- if (methods[i].qualifiers!="") {
+ if (methods[i].qualifiers != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->add_text(" ");
_add_text(methods[i].qualifiers);
class_desc->pop();
-
}
- class_desc->pop();//monofont
+ class_desc->pop(); //monofont
//class_desc->add_newline();
class_desc->pop(); //cell
-
}
class_desc->pop(); //table
class_desc->pop();
class_desc->add_newline();
class_desc->add_newline();
-
}
-
if (cd.theme_properties.size()) {
-
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("GUI Theme Items:"));
@@ -1023,9 +957,9 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
//class_desc->add_newline();
- for(int i=0;i<cd.theme_properties.size();i++) {
+ for (int i = 0; i < cd.theme_properties.size(); i++) {
- theme_property_line[cd.theme_properties[i].name]=class_desc->get_line_count()-2; //gets overriden if description
+ theme_property_line[cd.theme_properties[i].name] = class_desc->get_line_count() - 2; //gets overriden if description
class_desc->push_font(doc_code_font);
_add_type(cd.theme_properties[i].type);
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
@@ -1034,14 +968,13 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->pop();
- if (cd.theme_properties[i].description!="") {
+ if (cd.theme_properties[i].description != "") {
class_desc->push_font(doc_font);
class_desc->add_text(" ");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/comment_color"));
_add_text(cd.theme_properties[i].description);
class_desc->pop();
class_desc->pop();
-
}
class_desc->add_newline();
@@ -1067,26 +1000,26 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->push_indent(1);
- for(int i=0;i<cd.signals.size();i++) {
+ for (int i = 0; i < cd.signals.size(); i++) {
- signal_line[cd.signals[i].name]=class_desc->get_line_count()-2; //gets overriden if description
- class_desc->push_font(doc_code_font); // monofont
+ signal_line[cd.signals[i].name] = class_desc->get_line_count() - 2; //gets overriden if description
+ class_desc->push_font(doc_code_font); // monofont
//_add_type("void");
//class_desc->add_text(" ");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
_add_text(cd.signals[i].name);
class_desc->pop();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(cd.signals[i].arguments.size()?"( ":"(");
+ class_desc->add_text(cd.signals[i].arguments.size() ? "( " : "(");
class_desc->pop();
- for(int j=0;j<cd.signals[i].arguments.size();j++) {
+ for (int j = 0; j < cd.signals[i].arguments.size(); j++) {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- if (j>0)
+ if (j > 0)
class_desc->add_text(", ");
_add_type(cd.signals[i].arguments[j].type);
class_desc->add_text(" ");
_add_text(cd.signals[i].arguments[j].name);
- if (cd.signals[i].arguments[j].default_value!="") {
+ if (cd.signals[i].arguments[j].default_value != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
class_desc->add_text("=");
@@ -1098,29 +1031,25 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
}
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(cd.signals[i].arguments.size()?" )":")");
+ class_desc->add_text(cd.signals[i].arguments.size() ? " )" : ")");
class_desc->pop();
class_desc->pop(); // end monofont
- if (cd.signals[i].description!="") {
+ if (cd.signals[i].description != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/comment_color"));
class_desc->add_text(" ");
_add_text(cd.signals[i].description);
class_desc->pop();
-
}
class_desc->add_newline();
-
}
class_desc->pop();
class_desc->add_newline();
-
}
if (cd.constants.size()) {
-
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Constants:"));
@@ -1131,9 +1060,9 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
//class_desc->add_newline();
- for(int i=0;i<cd.constants.size();i++) {
+ for (int i = 0; i < cd.constants.size(); i++) {
- constant_line[cd.constants[i].name]=class_desc->get_line_count()-2;
+ constant_line[cd.constants[i].name] = class_desc->get_line_count() - 2;
class_desc->push_font(doc_code_font);
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/base_type_color"));
_add_text(cd.constants[i].name);
@@ -1145,7 +1074,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
_add_text(cd.constants[i].value);
class_desc->pop();
class_desc->pop();
- if (cd.constants[i].description!="") {
+ if (cd.constants[i].description != "") {
class_desc->push_font(doc_font);
class_desc->add_text(" ");
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/comment_color"));
@@ -1159,13 +1088,11 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->add_newline();
-
-
}
- if (cd.description!="") {
+ if (cd.description != "") {
- description_line=class_desc->get_line_count()-2;
+ description_line = class_desc->get_line_count() - 2;
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->push_font(doc_title_font);
class_desc->add_text(TTR("Description:"));
@@ -1175,7 +1102,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
class_desc->add_newline();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(cd.description);
class_desc->pop();
@@ -1196,10 +1123,9 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
class_desc->add_newline();
+ for (int i = 0; i < cd.properties.size(); i++) {
- for(int i=0;i<cd.properties.size();i++) {
-
- method_line[cd.properties[i].name]=class_desc->get_line_count()-2;
+ method_line[cd.properties[i].name] = class_desc->get_line_count() - 2;
class_desc->push_font(doc_code_font);
_add_type(cd.properties[i].type);
@@ -1213,9 +1139,9 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop(); //font
- if (cd.properties[i].setter!="") {
+ if (cd.properties[i].setter != "") {
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(2);
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
@@ -1223,18 +1149,17 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->add_text(cd.properties[i].setter+"(value)");
+ class_desc->add_text(cd.properties[i].setter + "(value)");
class_desc->pop(); //color
class_desc->pop(); //indent
class_desc->pop(); //font
-
}
- if (cd.properties[i].getter!="") {
+ if (cd.properties[i].getter != "") {
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(2);
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
@@ -1242,19 +1167,18 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->pop();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->add_text(cd.properties[i].getter+"()");
+ class_desc->add_text(cd.properties[i].getter + "()");
class_desc->pop(); //color
class_desc->pop(); //indent
class_desc->pop(); //font
-
}
class_desc->add_newline();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(cd.properties[i].description);
class_desc->pop();
@@ -1263,9 +1187,7 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
-
}
-
}
if (method_descr) {
@@ -1279,10 +1201,9 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
class_desc->add_newline();
+ for (int i = 0; i < methods.size(); i++) {
- for(int i=0;i<methods.size();i++) {
-
- method_line[methods[i].name]=class_desc->get_line_count()-2;
+ method_line[methods[i].name] = class_desc->get_line_count() - 2;
class_desc->push_font(doc_code_font);
_add_type(methods[i].return_type);
@@ -1292,16 +1213,16 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
_add_text(methods[i].name);
class_desc->pop();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(methods[i].arguments.size()?"( ":"(");
+ class_desc->add_text(methods[i].arguments.size() ? "( " : "(");
class_desc->pop();
- for(int j=0;j<methods[i].arguments.size();j++) {
+ for (int j = 0; j < methods[i].arguments.size(); j++) {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- if (j>0)
+ if (j > 0)
class_desc->add_text(", ");
_add_type(methods[i].arguments[j].type);
class_desc->add_text(" ");
_add_text(methods[i].arguments[j].name);
- if (methods[i].arguments[j].default_value!="") {
+ if (methods[i].arguments[j].default_value != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
class_desc->add_text("=");
@@ -1313,22 +1234,21 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
}
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/symbol_color"));
- class_desc->add_text(methods[i].arguments.size()?" )":")");
+ class_desc->add_text(methods[i].arguments.size() ? " )" : ")");
class_desc->pop();
- if (methods[i].qualifiers!="") {
+ if (methods[i].qualifiers != "") {
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
class_desc->add_text(" ");
_add_text(methods[i].qualifiers);
class_desc->pop();
-
}
class_desc->pop();
class_desc->add_newline();
class_desc->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/text_color"));
- class_desc->push_font( doc_font );
+ class_desc->push_font(doc_font);
class_desc->push_indent(1);
_add_text(methods[i].description);
class_desc->pop();
@@ -1337,72 +1257,60 @@ Error EditorHelp::_goto_desc(const String& p_class,int p_vscr) {
class_desc->add_newline();
class_desc->add_newline();
class_desc->add_newline();
-
}
-
-
-
-
-
}
-
-
- scroll_locked=false;
+ scroll_locked = false;
return OK;
}
-void EditorHelp::_request_help(const String& p_string) {
+void EditorHelp::_request_help(const String &p_string) {
Error err = _goto_desc(p_string);
- if (err==OK) {
- editor->call("_editor_select",EditorNode::EDITOR_SCRIPT);
+ if (err == OK) {
+ editor->call("_editor_select", EditorNode::EDITOR_SCRIPT);
}
//100 palabras
}
+void EditorHelp::_help_callback(const String &p_topic) {
-void EditorHelp::_help_callback(const String& p_topic) {
-
- String what = p_topic.get_slice(":",0);
- String clss = p_topic.get_slice(":",1);
+ String what = p_topic.get_slice(":", 0);
+ String clss = p_topic.get_slice(":", 1);
String name;
- if (p_topic.get_slice_count(":")==3)
- name=p_topic.get_slice(":",2);
+ if (p_topic.get_slice_count(":") == 3)
+ name = p_topic.get_slice(":", 2);
_request_help(clss); //first go to class
- int line=0;
+ int line = 0;
- if (what=="class_desc") {
- line=description_line;
- } else if (what=="class_signal") {
+ if (what == "class_desc") {
+ line = description_line;
+ } else if (what == "class_signal") {
if (signal_line.has(name))
- line=signal_line[name];
- } else if (what=="class_method" || what=="class_method_desc") {
+ line = signal_line[name];
+ } else if (what == "class_method" || what == "class_method_desc") {
if (method_line.has(name))
- line=method_line[name];
- } else if (what=="class_property") {
+ line = method_line[name];
+ } else if (what == "class_property") {
if (property_line.has(name))
- line=property_line[name];
- } else if (what=="class_theme_item") {
+ line = property_line[name];
+ } else if (what == "class_theme_item") {
if (theme_property_line.has(name))
- line=theme_property_line[name];
- } else if (what=="class_constant") {
+ line = theme_property_line[name];
+ } else if (what == "class_constant") {
if (constant_line.has(name))
- line=constant_line[name];
+ line = constant_line[name];
}
class_desc->call_deferred("scroll_to_line", line);
-
}
-
-
-static void _add_text_to_rt(const String& p_bbcode,RichTextLabel *p_rt) {
+static void _add_text_to_rt(const String &p_bbcode, RichTextLabel *p_rt) {
DocData *doc = EditorHelp::get_doc_data();
String base_path;
@@ -1412,34 +1320,34 @@ static void _add_text_to_rt(const String& p_bbcode,RichTextLabel *p_rt) {
p_rt->push_indent(1);*/
int pos = 0;
- Ref<Font> doc_font = p_rt->get_font("doc","EditorFonts");
- Ref<Font> doc_code_font = p_rt->get_font("doc_source","EditorFonts");
+ Ref<Font> doc_font = p_rt->get_font("doc", "EditorFonts");
+ Ref<Font> doc_code_font = p_rt->get_font("doc_source", "EditorFonts");
- String bbcode=p_bbcode.replace("\t"," ").replace("\r"," ").strip_edges();
+ String bbcode = p_bbcode.replace("\t", " ").replace("\r", " ").strip_edges();
//change newlines for double newlines
- for(int i=0;i<bbcode.length();i++) {
+ for (int i = 0; i < bbcode.length(); i++) {
//find valid newlines (double)
- if (bbcode[i]=='\n') {
- bool dnl=false;
- int j=i+1;
- for(;j<p_bbcode.length();j++) {
- if (bbcode[j]==' ')
+ if (bbcode[i] == '\n') {
+ bool dnl = false;
+ int j = i + 1;
+ for (; j < p_bbcode.length(); j++) {
+ if (bbcode[j] == ' ')
continue;
- if (bbcode[j]=='\n') {
- dnl=true;
+ if (bbcode[j] == '\n') {
+ dnl = true;
break;
}
break;
}
if (dnl) {
- bbcode[i]=0xFFFF;
+ bbcode[i] = 0xFFFF;
//keep
- i=j;
+ i = j;
} else {
- bbcode=bbcode.insert(i,"\n");
+ bbcode = bbcode.insert(i, "\n");
i++;
//bbcode[i]=' ';
//i=j-1;
@@ -1448,12 +1356,12 @@ static void _add_text_to_rt(const String& p_bbcode,RichTextLabel *p_rt) {
}
//remove double spaces or spaces after newlines
- for(int i=0;i<bbcode.length();i++) {
+ for (int i = 0; i < bbcode.length(); i++) {
- if (bbcode[i]==' ' || bbcode[i]=='\n' || bbcode[i]==0xFFFF) {
+ if (bbcode[i] == ' ' || bbcode[i] == '\n' || bbcode[i] == 0xFFFF) {
- for(int j=i+1;j<p_bbcode.length();j++) {
- if (bbcode[j]==' ') {
+ for (int j = i + 1; j < p_bbcode.length(); j++) {
+ if (bbcode[j] == ' ') {
bbcode.remove(j);
j--;
continue;
@@ -1466,47 +1374,39 @@ static void _add_text_to_rt(const String& p_bbcode,RichTextLabel *p_rt) {
//change newlines to double newlines
- CharType dnls[2]={0xFFFF,0};
- bbcode=bbcode.replace(dnls,"\n");
-
+ CharType dnls[2] = { 0xFFFF, 0 };
+ bbcode = bbcode.replace(dnls, "\n");
List<String> tag_stack;
- while(pos < bbcode.length()) {
+ while (pos < bbcode.length()) {
+ int brk_pos = bbcode.find("[", pos);
- int brk_pos = bbcode.find("[",pos);
-
- if (brk_pos<0)
- brk_pos=bbcode.length();
+ if (brk_pos < 0)
+ brk_pos = bbcode.length();
if (brk_pos > pos) {
- p_rt->add_text(bbcode.substr(pos,brk_pos-pos));
-
+ p_rt->add_text(bbcode.substr(pos, brk_pos - pos));
}
- if (brk_pos==bbcode.length())
+ if (brk_pos == bbcode.length())
break; //nothing else o add
- int brk_end = bbcode.find("]",brk_pos+1);
+ int brk_end = bbcode.find("]", brk_pos + 1);
- if (brk_end==-1) {
+ if (brk_end == -1) {
//no close, add the rest
- p_rt->add_text(bbcode.substr(brk_pos,bbcode.length()-brk_pos));
+ p_rt->add_text(bbcode.substr(brk_pos, bbcode.length() - brk_pos));
break;
}
-
- String tag = bbcode.substr(brk_pos+1,brk_end-brk_pos-1);
-
+ String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
if (tag.begins_with("/")) {
- bool tag_ok = tag_stack.size() && tag_stack.front()->get()==tag.substr(1,tag.length());
+ bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
if (tag_stack.size()) {
-
-
-
}
if (!tag_ok) {
@@ -1516,224 +1416,203 @@ static void _add_text_to_rt(const String& p_bbcode,RichTextLabel *p_rt) {
}
tag_stack.pop_front();
- pos=brk_end+1;
- if (tag!="/img")
+ pos = brk_end + 1;
+ if (tag != "/img")
p_rt->pop();
} else if (tag.begins_with("method ")) {
- String m = tag.substr(7,tag.length());
+ String m = tag.substr(7, tag.length());
p_rt->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
- p_rt->push_meta("@"+m);
- p_rt->add_text(m+"()");
+ p_rt->push_meta("@" + m);
+ p_rt->add_text(m + "()");
p_rt->pop();
p_rt->pop();
- pos=brk_end+1;
+ pos = brk_end + 1;
} else if (doc->class_list.has(tag)) {
-
p_rt->push_color(EditorSettings::get_singleton()->get("text_editor/highlighting/keyword_color"));
- p_rt->push_meta("#"+tag);
+ p_rt->push_meta("#" + tag);
p_rt->add_text(tag);
p_rt->pop();
p_rt->pop();
- pos=brk_end+1;
+ pos = brk_end + 1;
- } else if (tag=="b") {
+ } else if (tag == "b") {
//use bold font
p_rt->push_font(doc_code_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="i") {
+ } else if (tag == "i") {
//use italics font
Color text_color = EditorSettings::get_singleton()->get("text_editor/highlighting/text_color");
//no italics so emphasize with color
- text_color.r*=1.1;
- text_color.g*=1.1;
- text_color.b*=1.1;
+ text_color.r *= 1.1;
+ text_color.g *= 1.1;
+ text_color.b *= 1.1;
p_rt->push_color(text_color);
//p_rt->push_font(get_font("italic","Fonts"));
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="code" || tag=="codeblock") {
+ } else if (tag == "code" || tag == "codeblock") {
//use monospace font
p_rt->push_font(doc_code_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="center") {
+ } else if (tag == "center") {
//use monospace font
p_rt->push_align(RichTextLabel::ALIGN_CENTER);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="br") {
+ } else if (tag == "br") {
//use monospace font
p_rt->add_newline();
- pos=brk_end+1;
- } else if (tag=="u") {
+ pos = brk_end + 1;
+ } else if (tag == "u") {
//use underline
p_rt->push_underline();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="s") {
+ } else if (tag == "s") {
//use strikethrough (not supported underline instead)
p_rt->push_underline();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="url") {
+ } else if (tag == "url") {
//use strikethrough (not supported underline instead)
- int end=bbcode.find("[",brk_end);
- if (end==-1)
- end=bbcode.length();
- String url = bbcode.substr(brk_end+1,end-brk_end-1);
+ int end = bbcode.find("[", brk_end);
+ if (end == -1)
+ end = bbcode.length();
+ String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
p_rt->push_meta(url);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("url=")) {
- String url = tag.substr(4,tag.length());
+ String url = tag.substr(4, tag.length());
p_rt->push_meta(url);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("url");
- } else if (tag=="img") {
+ } else if (tag == "img") {
//use strikethrough (not supported underline instead)
- int end=bbcode.find("[",brk_end);
- if (end==-1)
- end=bbcode.length();
- String image = bbcode.substr(brk_end+1,end-brk_end-1);
+ int end = bbcode.find("[", brk_end);
+ if (end == -1)
+ end = bbcode.length();
+ String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
- Ref<Texture> texture = ResourceLoader::load(base_path+"/"+image,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(base_path + "/" + image, "Texture");
if (texture.is_valid())
p_rt->add_image(texture);
- pos=end;
+ pos = end;
tag_stack.push_front(tag);
} else if (tag.begins_with("color=")) {
- String col = tag.substr(6,tag.length());
+ String col = tag.substr(6, tag.length());
Color color;
if (col.begins_with("#"))
- color=Color::html(col);
- else if (col=="aqua")
- color=Color::html("#00FFFF");
- else if (col=="black")
- color=Color::html("#000000");
- else if (col=="blue")
- color=Color::html("#0000FF");
- else if (col=="fuchsia")
- color=Color::html("#FF00FF");
- else if (col=="gray" || col=="grey")
- color=Color::html("#808080");
- else if (col=="green")
- color=Color::html("#008000");
- else if (col=="lime")
- color=Color::html("#00FF00");
- else if (col=="maroon")
- color=Color::html("#800000");
- else if (col=="navy")
- color=Color::html("#000080");
- else if (col=="olive")
- color=Color::html("#808000");
- else if (col=="purple")
- color=Color::html("#800080");
- else if (col=="red")
- color=Color::html("#FF0000");
- else if (col=="silver")
- color=Color::html("#C0C0C0");
- else if (col=="teal")
- color=Color::html("#008008");
- else if (col=="white")
- color=Color::html("#FFFFFF");
- else if (col=="yellow")
- color=Color::html("#FFFF00");
+ color = Color::html(col);
+ else if (col == "aqua")
+ color = Color::html("#00FFFF");
+ else if (col == "black")
+ color = Color::html("#000000");
+ else if (col == "blue")
+ color = Color::html("#0000FF");
+ else if (col == "fuchsia")
+ color = Color::html("#FF00FF");
+ else if (col == "gray" || col == "grey")
+ color = Color::html("#808080");
+ else if (col == "green")
+ color = Color::html("#008000");
+ else if (col == "lime")
+ color = Color::html("#00FF00");
+ else if (col == "maroon")
+ color = Color::html("#800000");
+ else if (col == "navy")
+ color = Color::html("#000080");
+ else if (col == "olive")
+ color = Color::html("#808000");
+ else if (col == "purple")
+ color = Color::html("#800080");
+ else if (col == "red")
+ color = Color::html("#FF0000");
+ else if (col == "silver")
+ color = Color::html("#C0C0C0");
+ else if (col == "teal")
+ color = Color::html("#008008");
+ else if (col == "white")
+ color = Color::html("#FFFFFF");
+ else if (col == "yellow")
+ color = Color::html("#FFFF00");
else
- color=Color(0,0,0,1); //base_color;
-
-
+ color = Color(0, 0, 0, 1); //base_color;
p_rt->push_color(color);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("color");
} else if (tag.begins_with("font=")) {
- String fnt = tag.substr(5,tag.length());
-
+ String fnt = tag.substr(5, tag.length());
- Ref<Font> font = ResourceLoader::load(base_path+"/"+fnt,"Font");
+ Ref<Font> font = ResourceLoader::load(base_path + "/" + fnt, "Font");
if (font.is_valid())
p_rt->push_font(font);
else {
p_rt->push_font(doc_font);
}
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("font");
-
} else {
p_rt->add_text("["); //ignore
- pos=brk_pos+1;
-
+ pos = brk_pos + 1;
}
}
/*p_rt->pop();
p_rt->pop();
p_rt->pop();*/
-
}
+void EditorHelp::_add_text(const String &p_bbcode) {
-void EditorHelp::_add_text(const String& p_bbcode) {
-
-
- _add_text_to_rt(p_bbcode,class_desc);
-
+ _add_text_to_rt(p_bbcode, class_desc);
}
-
-
-
void EditorHelp::_update_doc() {
-
-
-
}
-
void EditorHelp::generate_doc() {
- doc = memnew( DocData );
+ doc = memnew(DocData);
doc->generate(true);
DocData compdoc;
- compdoc.load_compressed(_doc_data_compressed,_doc_data_compressed_size,_doc_data_uncompressed_size);
+ compdoc.load_compressed(_doc_data_compressed, _doc_data_compressed_size, _doc_data_uncompressed_size);
doc->merge_from(compdoc); //ensure all is up to date
-
-
}
void EditorHelp::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
-
//forward->set_icon(get_icon("Forward","EditorIcons"));
//back->set_icon(get_icon("Back","EditorIcons"));
_update_doc();
@@ -1742,20 +1621,19 @@ void EditorHelp::_notification(int p_what) {
}
}
-void EditorHelp::go_to_help(const String& p_help) {
+void EditorHelp::go_to_help(const String &p_help) {
_help_callback(p_help);
}
-void EditorHelp::go_to_class(const String& p_class,int p_scroll) {
+void EditorHelp::go_to_class(const String &p_class, int p_scroll) {
- _goto_desc(p_class,p_scroll);
+ _goto_desc(p_class, p_scroll);
}
void EditorHelp::popup_search() {
-
- search_dialog->popup_centered(Size2(250,80));
+ search_dialog->popup_centered(Size2(250, 80));
search->grab_focus();
}
@@ -1779,74 +1657,70 @@ int EditorHelp::get_scroll() const {
}
void EditorHelp::set_scroll(int p_scroll) {
-
class_desc->get_v_scroll()->set_value(p_scroll);
-
}
void EditorHelp::_bind_methods() {
- ClassDB::bind_method("_class_list_select",&EditorHelp::_class_list_select);
- ClassDB::bind_method("_class_desc_select",&EditorHelp::_class_desc_select);
- ClassDB::bind_method("_class_desc_input",&EditorHelp::_class_desc_input);
+ ClassDB::bind_method("_class_list_select", &EditorHelp::_class_list_select);
+ ClassDB::bind_method("_class_desc_select", &EditorHelp::_class_desc_select);
+ ClassDB::bind_method("_class_desc_input", &EditorHelp::_class_desc_input);
//ClassDB::bind_method("_button_pressed",&EditorHelp::_button_pressed);
- ClassDB::bind_method("_scroll_changed",&EditorHelp::_scroll_changed);
- ClassDB::bind_method("_request_help",&EditorHelp::_request_help);
- ClassDB::bind_method("_unhandled_key_input",&EditorHelp::_unhandled_key_input);
- ClassDB::bind_method("_search",&EditorHelp::_search);
- ClassDB::bind_method("_search_cbk",&EditorHelp::_search_cbk);
- ClassDB::bind_method("_help_callback",&EditorHelp::_help_callback);
+ ClassDB::bind_method("_scroll_changed", &EditorHelp::_scroll_changed);
+ ClassDB::bind_method("_request_help", &EditorHelp::_request_help);
+ ClassDB::bind_method("_unhandled_key_input", &EditorHelp::_unhandled_key_input);
+ ClassDB::bind_method("_search", &EditorHelp::_search);
+ ClassDB::bind_method("_search_cbk", &EditorHelp::_search_cbk);
+ ClassDB::bind_method("_help_callback", &EditorHelp::_help_callback);
ADD_SIGNAL(MethodInfo("go_to_help"));
-
}
EditorHelp::EditorHelp() {
- editor=EditorNode::get_singleton();
+ editor = EditorNode::get_singleton();
VBoxContainer *vbc = this;
- EDITOR_DEF("text_editor/help/sort_functions_alphabetically",true);
+ EDITOR_DEF("text_editor/help/sort_functions_alphabetically", true);
//class_list->connect("meta_clicked",this,"_class_list_select");
//class_list->set_selection_enabled(true);
{
- Panel *pc = memnew( Panel );
- Ref<StyleBoxFlat> style( memnew( StyleBoxFlat ) );
- style->set_bg_color( EditorSettings::get_singleton()->get("text_editor/highlighting/background_color") );
+ Panel *pc = memnew(Panel);
+ Ref<StyleBoxFlat> style(memnew(StyleBoxFlat));
+ style->set_bg_color(EditorSettings::get_singleton()->get("text_editor/highlighting/background_color"));
pc->set_v_size_flags(SIZE_EXPAND_FILL);
pc->add_style_override("panel", style); //get_stylebox("normal","TextEdit"));
vbc->add_child(pc);
- class_desc = memnew( RichTextLabel );
+ class_desc = memnew(RichTextLabel);
pc->add_child(class_desc);
class_desc->set_area_as_parent_rect(8);
- class_desc->connect("meta_clicked",this,"_class_desc_select");
- class_desc->connect("gui_input",this,"_class_desc_input");
+ class_desc->connect("meta_clicked", this, "_class_desc_select");
+ class_desc->connect("gui_input", this, "_class_desc_input");
}
- class_desc->get_v_scroll()->connect("value_changed",this,"_scroll_changed");
+ class_desc->get_v_scroll()->connect("value_changed", this, "_scroll_changed");
class_desc->set_selection_enabled(true);
- scroll_locked=false;
- select_locked=false;
+ scroll_locked = false;
+ select_locked = false;
set_process_unhandled_key_input(true);
class_desc->hide();
- search_dialog = memnew( ConfirmationDialog );
+ search_dialog = memnew(ConfirmationDialog);
add_child(search_dialog);
- VBoxContainer *search_vb = memnew( VBoxContainer );
+ VBoxContainer *search_vb = memnew(VBoxContainer);
search_dialog->add_child(search_vb);
- search = memnew( LineEdit );
+ search = memnew(LineEdit);
search_dialog->register_text_enter(search);
- search_vb->add_margin_child(TTR("Search Text"),search);
+ search_vb->add_margin_child(TTR("Search Text"), search);
search_dialog->get_ok()->set_text(TTR("Find"));
- search_dialog->connect("confirmed",this,"_search_cbk");
+ search_dialog->connect("confirmed", this, "_search_cbk");
search_dialog->set_hide_on_ok(false);
- search_dialog->set_self_modulate(Color(1,1,1,0.8));
-
+ search_dialog->set_self_modulate(Color(1, 1, 1, 0.8));
/*class_search = memnew( EditorHelpSearch(editor) );
editor->get_gui_base()->add_child(class_search);
@@ -1856,13 +1730,10 @@ EditorHelp::EditorHelp() {
}
EditorHelp::~EditorHelp() {
-
}
/////////////
-
-
void EditorHelpBit::_go_to_help(String p_what) {
EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT);
@@ -1875,16 +1746,16 @@ void EditorHelpBit::_meta_clicked(String p_select) {
//print_line("LINK: "+p_select);
if (p_select.begins_with("#")) {
//_goto_desc(p_select.substr(1,p_select.length()));
- _go_to_help("class_name:"+p_select.substr(1,p_select.length()));
+ _go_to_help("class_name:" + p_select.substr(1, p_select.length()));
return;
} else if (p_select.begins_with("@")) {
- String m = p_select.substr(1,p_select.length());
+ String m = p_select.substr(1, p_select.length());
- if (m.find(".")!=-1) {
+ if (m.find(".") != -1) {
//must go somewhere else
- _go_to_help("class_method:"+m.get_slice(".",0)+":"+m.get_slice(".",0));
+ _go_to_help("class_method:" + m.get_slice(".", 0) + ":" + m.get_slice(".", 0));
} else {
/*
if (!method_line.has(m))
@@ -1892,38 +1763,33 @@ void EditorHelpBit::_meta_clicked(String p_select) {
class_desc->scroll_to_line(method_line[m]);
*/
}
-
}
-
-
}
void EditorHelpBit::_bind_methods() {
- ClassDB::bind_method("_meta_clicked",&EditorHelpBit::_meta_clicked);
+ ClassDB::bind_method("_meta_clicked", &EditorHelpBit::_meta_clicked);
ADD_SIGNAL(MethodInfo("request_hide"));
}
-void EditorHelpBit::_notification(int p_what){
+void EditorHelpBit::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- add_style_override("panel",get_stylebox("normal","TextEdit"));
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ add_style_override("panel", get_stylebox("normal", "TextEdit"));
}
}
-
-void EditorHelpBit::set_text(const String& p_text) {
+void EditorHelpBit::set_text(const String &p_text) {
rich_text->clear();
- _add_text_to_rt(p_text,rich_text);
+ _add_text_to_rt(p_text, rich_text);
}
EditorHelpBit::EditorHelpBit() {
- rich_text = memnew( RichTextLabel );
+ rich_text = memnew(RichTextLabel);
add_child(rich_text);
- rich_text->set_area_as_parent_rect(8*EDSCALE);
- rich_text->connect("meta_clicked",this,"_meta_clicked");
- set_custom_minimum_size(Size2(0,70*EDSCALE));
-
+ rich_text->set_area_as_parent_rect(8 * EDSCALE);
+ rich_text->connect("meta_clicked", this, "_meta_clicked");
+ set_custom_minimum_size(Size2(0, 70 * EDSCALE));
}
diff --git a/editor/editor_help.h b/editor/editor_help.h
index 909226f403..06b64edf78 100644
--- a/editor/editor_help.h
+++ b/editor/editor_help.h
@@ -30,24 +30,23 @@
#define EDITOR_HELP_H
#include "editor/editor_plugin.h"
-#include "scene/gui/tab_container.h"
-#include "scene/gui/text_edit.h"
-#include "scene/gui/split_container.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/rich_text_label.h"
#include "scene/gui/panel_container.h"
+#include "scene/gui/rich_text_label.h"
+#include "scene/gui/split_container.h"
+#include "scene/gui/tab_container.h"
+#include "scene/gui/text_edit.h"
#include "scene/gui/tree.h"
-#include "scene/main/timer.h"
#include "editor/code_editor.h"
#include "editor/doc/doc_data.h"
-
+#include "scene/main/timer.h"
class EditorNode;
class EditorHelpSearch : public ConfirmationDialog {
- GDCLASS(EditorHelpSearch,ConfirmationDialog )
+ GDCLASS(EditorHelpSearch, ConfirmationDialog)
EditorNode *editor;
LineEdit *search_box;
@@ -56,56 +55,51 @@ class EditorHelpSearch : public ConfirmationDialog {
void _update_search();
- void _sbox_input(const InputEvent& p_ie);
+ void _sbox_input(const InputEvent &p_ie);
void _confirmed();
- void _text_changed(const String& p_newtext);
-
+ void _text_changed(const String &p_newtext);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void popup();
- void popup(const String& p_term);
+ void popup(const String &p_term);
EditorHelpSearch();
};
class EditorHelpIndex : public ConfirmationDialog {
- GDCLASS( EditorHelpIndex, ConfirmationDialog );
+ GDCLASS(EditorHelpIndex, ConfirmationDialog);
LineEdit *search_box;
Tree *class_list;
- HashMap<String,TreeItem*> tree_item_map;
+ HashMap<String, TreeItem *> tree_item_map;
void _tree_item_selected();
- void _text_changed(const String& p_text);
- void _sbox_input(const InputEvent& p_ie);
+ void _text_changed(const String &p_text);
+ void _sbox_input(const InputEvent &p_ie);
void _update_class_list();
- void add_type(const String& p_type,HashMap<String,TreeItem*>& p_types,TreeItem *p_root);
-protected:
+ void add_type(const String &p_type, HashMap<String, TreeItem *> &p_types, TreeItem *p_root);
+protected:
void _notification(int p_what);
static void _bind_methods();
public:
-
- void select_class(const String& p_class);
+ void select_class(const String &p_class);
void popup();
EditorHelpIndex();
};
-
class EditorHelp : public VBoxContainer {
- GDCLASS( EditorHelp, VBoxContainer );
-
+ GDCLASS(EditorHelp, VBoxContainer);
enum Page {
@@ -118,7 +112,6 @@ class EditorHelp : public VBoxContainer {
};
-
bool select_locked;
String prev_search;
@@ -126,63 +119,55 @@ class EditorHelp : public VBoxContainer {
String edited_class;
EditorNode *editor;
- Map<String,int> method_line;
- Map<String,int> signal_line;
- Map<String,int> property_line;
- Map<String,int> theme_property_line;
- Map<String,int> constant_line;
+ Map<String, int> method_line;
+ Map<String, int> signal_line;
+ Map<String, int> property_line;
+ Map<String, int> theme_property_line;
+ Map<String, int> constant_line;
int description_line;
-
RichTextLabel *class_desc;
HSplitContainer *h_split;
static DocData *doc;
-
ConfirmationDialog *search_dialog;
LineEdit *search;
-
String base_path;
+ void _help_callback(const String &p_topic);
- void _help_callback(const String& p_topic);
-
- void _add_text(const String& p_text);
+ void _add_text(const String &p_text);
bool scroll_locked;
//void _button_pressed(int p_idx);
- void _add_type(const String& p_type);
+ void _add_type(const String &p_type);
void _scroll_changed(double p_scroll);
- void _class_list_select(const String& p_select);
- void _class_desc_select(const String& p_select);
- void _class_desc_input(const InputEvent& p_input);
+ void _class_list_select(const String &p_select);
+ void _class_desc_select(const String &p_select);
+ void _class_desc_input(const InputEvent &p_input);
- Error _goto_desc(const String& p_class, int p_vscr=-1);
+ Error _goto_desc(const String &p_class, int p_vscr = -1);
//void _update_history_buttons();
void _update_doc();
- void _request_help(const String& p_string);
- void _search(const String& p_str);
+ void _request_help(const String &p_string);
+ void _search(const String &p_str);
void _search_cbk();
- void _unhandled_key_input(const InputEvent& p_ev);
-
-
+ void _unhandled_key_input(const InputEvent &p_ev);
protected:
-
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
static void generate_doc();
static DocData *get_doc_data() { return doc; }
- void go_to_help(const String& p_help);
- void go_to_class(const String& p_class,int p_scroll=0);
+ void go_to_help(const String &p_help);
+ void go_to_class(const String &p_class, int p_scroll = 0);
void popup_search();
void search_again();
@@ -198,24 +183,20 @@ public:
~EditorHelp();
};
-
-
class EditorHelpBit : public Panel {
- GDCLASS( EditorHelpBit, Panel);
+ GDCLASS(EditorHelpBit, Panel);
RichTextLabel *rich_text;
void _go_to_help(String p_what);
void _meta_clicked(String p_what);
-
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
- void set_text(const String& p_text);
+public:
+ void set_text(const String &p_text);
EditorHelpBit();
};
diff --git a/editor/editor_initialize_ssl.cpp b/editor/editor_initialize_ssl.cpp
index c08dcc6656..7801b312b3 100644
--- a/editor/editor_initialize_ssl.cpp
+++ b/editor/editor_initialize_ssl.cpp
@@ -29,23 +29,18 @@
#include "editor_initialize_ssl.h"
#include "certs_compressed.h"
-#include "io/stream_peer_ssl.h"
#include "io/compression.h"
+#include "io/stream_peer_ssl.h"
void editor_initialize_certificates() {
-
PoolByteArray data;
- data.resize(_certs_uncompressed_size+1);
+ data.resize(_certs_uncompressed_size + 1);
{
PoolByteArray::Write w = data.write();
- Compression::decompress(w.ptr(),_certs_uncompressed_size,_certs_compressed,_certs_compressed_size,Compression::MODE_DEFLATE);
- w[_certs_uncompressed_size]=0; //make sure it ends at zero
+ Compression::decompress(w.ptr(), _certs_uncompressed_size, _certs_compressed, _certs_compressed_size, Compression::MODE_DEFLATE);
+ w[_certs_uncompressed_size] = 0; //make sure it ends at zero
}
StreamPeerSSL::load_certs_from_memory(data);
-
-
}
-
-
diff --git a/editor/editor_log.cpp b/editor/editor_log.cpp
index 850d9273f8..60837d900e 100644
--- a/editor/editor_log.cpp
+++ b/editor/editor_log.cpp
@@ -28,21 +28,21 @@
/*************************************************************************/
#include "editor_log.h"
-#include "version.h"
-#include "scene/gui/center_container.h"
#include "editor_node.h"
+#include "scene/gui/center_container.h"
+#include "version.h"
-void EditorLog::_error_handler(void *p_self, const char*p_func, const char*p_file,int p_line, const char*p_error,const char*p_errorexp,ErrorHandlerType p_type ) {
+void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type) {
- EditorLog *self=(EditorLog *)p_self;
- if (self->current!=Thread::get_caller_ID())
+ EditorLog *self = (EditorLog *)p_self;
+ if (self->current != Thread::get_caller_ID())
return;
String err_str;
if (p_errorexp && p_errorexp[0]) {
- err_str=p_errorexp;
+ err_str = p_errorexp;
} else {
- err_str=String(p_file)+":"+itos(p_line)+" - "+String(p_error);
+ err_str = String(p_file) + ":" + itos(p_line) + " - " + String(p_error);
}
/*
@@ -50,44 +50,41 @@ void EditorLog::_error_handler(void *p_self, const char*p_func, const char*p_fil
self->emit_signal("show_request");
*/
- err_str=" "+err_str;
+ err_str = " " + err_str;
self->log->add_newline();
Ref<Texture> icon;
- switch(p_type) {
+ switch (p_type) {
case ERR_HANDLER_ERROR: {
- icon = self->get_icon("Error","EditorIcons");
+ icon = self->get_icon("Error", "EditorIcons");
return; // these are confusing
} break;
case ERR_HANDLER_WARNING: {
- icon = self->get_icon("Error","EditorIcons");
+ icon = self->get_icon("Error", "EditorIcons");
} break;
case ERR_HANDLER_SCRIPT: {
- icon = self->get_icon("ScriptError","EditorIcons");
+ icon = self->get_icon("ScriptError", "EditorIcons");
} break;
case ERR_HANDLER_SHADER: {
- icon = self->get_icon("Shader","EditorIcons");
+ icon = self->get_icon("Shader", "EditorIcons");
} break;
-
}
- self->add_message(err_str,true);
-
+ self->add_message(err_str, true);
}
void EditorLog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- log->add_color_override("default_color",get_color("font_color","Tree"));
+ log->add_color_override("default_color", get_color("font_color", "Tree"));
//button->set_icon(get_icon("Console","EditorIcons"));
-
}
/*if (p_what==NOTIFICATION_DRAW) {
@@ -102,42 +99,32 @@ void EditorLog::_notification(int p_what) {
}*/
}
-
-
-
void EditorLog::_clear_request() {
log->clear();
-
}
void EditorLog::clear() {
_clear_request();
}
-
-void EditorLog::add_message(const String& p_msg,bool p_error) {
-
+void EditorLog::add_message(const String &p_msg, bool p_error) {
if (p_error) {
- Ref<Texture> icon = get_icon("Error","EditorIcons");
- log->add_image( icon );
+ Ref<Texture> icon = get_icon("Error", "EditorIcons");
+ log->add_image(icon);
//button->set_icon(icon);
- log->push_color(get_color("fg_error","Editor"));
+ log->push_color(get_color("fg_error", "Editor"));
} else {
//button->set_icon(Ref<Texture>());
-
}
-
log->add_newline();
log->add_text(p_msg);
//button->set_text(p_msg);
if (p_error)
log->pop();
-
-
}
/*
@@ -155,32 +142,28 @@ void EditorLog::_dragged(const Point2& p_ofs) {
}
*/
+void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) {
-
-
-void EditorLog::_undo_redo_cbk(void *p_self,const String& p_name) {
-
- EditorLog *self=(EditorLog *)p_self;
+ EditorLog *self = (EditorLog *)p_self;
self->add_message(p_name);
-
}
void EditorLog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_clear_request"),&EditorLog::_clear_request );
- ClassDB::bind_method("_override_logger_styles",&EditorLog::_override_logger_styles );
+ ClassDB::bind_method(D_METHOD("_clear_request"), &EditorLog::_clear_request);
+ ClassDB::bind_method("_override_logger_styles", &EditorLog::_override_logger_styles);
//ClassDB::bind_method(D_METHOD("_dragged"),&EditorLog::_dragged );
- ADD_SIGNAL( MethodInfo("clear_request"));
+ ADD_SIGNAL(MethodInfo("clear_request"));
}
EditorLog::EditorLog() {
VBoxContainer *vb = this;
- add_constant_override("separation",get_constant("separation","VBoxContainer"));
+ add_constant_override("separation", get_constant("separation", "VBoxContainer"));
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
vb->add_child(hb);
- title = memnew( Label );
+ title = memnew(Label);
title->set_text(TTR(" Output:"));
title->set_h_size_flags(SIZE_EXPAND_FILL);
hb->add_child(title);
@@ -190,53 +173,47 @@ EditorLog::EditorLog() {
//pd->connect("dragged",this,"_dragged");
//pd->set_default_cursor_shape(Control::CURSOR_MOVE);
- clearbutton = memnew( Button );
+ clearbutton = memnew(Button);
hb->add_child(clearbutton);
clearbutton->set_text(TTR("Clear"));
- clearbutton->connect("pressed", this,"_clear_request");
+ clearbutton->connect("pressed", this, "_clear_request");
- ec = memnew( Control);
+ ec = memnew(Control);
vb->add_child(ec);
- ec->set_custom_minimum_size(Size2(0,180));
+ ec->set_custom_minimum_size(Size2(0, 180));
ec->set_v_size_flags(SIZE_EXPAND_FILL);
- pc = memnew( PanelContainer );
+ pc = memnew(PanelContainer);
ec->add_child(pc);
pc->set_area_as_parent_rect();
pc->connect("tree_entered", this, "_override_logger_styles");
- log = memnew( RichTextLabel );
+ log = memnew(RichTextLabel);
log->set_scroll_follow(true);
log->set_selection_enabled(true);
log->set_focus_mode(FOCUS_CLICK);
pc->add_child(log);
- add_message(VERSION_FULL_NAME" (c) 2008-2017 Juan Linietsky, Ariel Manzur.");
+ add_message(VERSION_FULL_NAME " (c) 2008-2017 Juan Linietsky, Ariel Manzur.");
//log->add_text("Initialization Complete.\n"); //because it looks cool.
- eh.errfunc=_error_handler;
- eh.userdata=this;
+ eh.errfunc = _error_handler;
+ eh.userdata = this;
add_error_handler(&eh);
- current=Thread::get_caller_ID();
-
- EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk,this);
-
+ current = Thread::get_caller_ID();
+ EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk, this);
}
void EditorLog::deinit() {
remove_error_handler(&eh);
-
}
void EditorLog::_override_logger_styles() {
- pc->add_style_override("panel",get_stylebox("normal","TextEdit"));
-
+ pc->add_style_override("panel", get_stylebox("normal", "TextEdit"));
}
EditorLog::~EditorLog() {
-
-
}
diff --git a/editor/editor_log.h b/editor/editor_log.h
index 965d8d6420..3debbfecd4 100644
--- a/editor/editor_log.h
+++ b/editor/editor_log.h
@@ -34,15 +34,15 @@
#include "scene/gui/rich_text_label.h"
#include "scene/gui/texture_button.h"
//#include "scene/gui/empty_control.h"
+#include "os/thread.h"
+#include "pane_drag.h"
#include "scene/gui/box_container.h"
#include "scene/gui/panel_container.h"
#include "scene/gui/texture_rect.h"
#include "scene/gui/tool_button.h"
-#include "pane_drag.h"
-#include "os/thread.h"
class EditorLog : public VBoxContainer {
- GDCLASS( EditorLog, VBoxContainer );
+ GDCLASS(EditorLog, VBoxContainer);
Button *clearbutton;
Label *title;
@@ -52,7 +52,7 @@ class EditorLog : public VBoxContainer {
Control *ec;
PanelContainer *pc;
- static void _error_handler(void *p_self, const char*p_func, const char*p_file,int p_line, const char*p_error,const char*p_errorexp,ErrorHandlerType p_type);
+ static void _error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type);
ErrorHandlerList eh;
@@ -60,18 +60,17 @@ class EditorLog : public VBoxContainer {
//void _dragged(const Point2& p_ofs);
void _clear_request();
- static void _undo_redo_cbk(void *p_self,const String& p_name);
-protected:
+ static void _undo_redo_cbk(void *p_self, const String &p_name);
+protected:
static void _bind_methods();
void _notification(int p_what);
void _override_logger_styles();
-public:
- void add_message(const String& p_msg, bool p_error=false);
+public:
+ void add_message(const String &p_msg, bool p_error = false);
void deinit();
-
void clear();
EditorLog();
~EditorLog();
diff --git a/editor/editor_name_dialog.cpp b/editor/editor_name_dialog.cpp
index da9f25f1e3..b8fa534ddb 100644
--- a/editor/editor_name_dialog.cpp
+++ b/editor/editor_name_dialog.cpp
@@ -31,7 +31,7 @@
#include "class_db.h"
#include "os/keyboard.h"
-void EditorNameDialog::_line_gui_input(const InputEvent& p_event) {
+void EditorNameDialog::_line_gui_input(const InputEvent &p_event) {
if (p_event.type == InputEvent::KEY) {
@@ -65,25 +65,24 @@ void EditorNameDialog::_post_popup() {
void EditorNameDialog::ok_pressed() {
- if (name->get_text()!="") {
+ if (name->get_text() != "") {
emit_signal("name_confirmed", name->get_text());
}
}
void EditorNameDialog::_bind_methods() {
- ClassDB::bind_method("_line_gui_input",&EditorNameDialog::_line_gui_input);
+ ClassDB::bind_method("_line_gui_input", &EditorNameDialog::_line_gui_input);
- ADD_SIGNAL(MethodInfo("name_confirmed",PropertyInfo( Variant::STRING,"name")));
+ ADD_SIGNAL(MethodInfo("name_confirmed", PropertyInfo(Variant::STRING, "name")));
}
-EditorNameDialog::EditorNameDialog()
-{
- name = memnew( LineEdit );
+EditorNameDialog::EditorNameDialog() {
+ name = memnew(LineEdit);
add_child(name);
- move_child(name, get_label()->get_index()+1);
- name->set_margin(MARGIN_TOP,5);
- name->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,5);
- name->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,5);
+ move_child(name, get_label()->get_index() + 1);
+ name->set_margin(MARGIN_TOP, 5);
+ name->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 5);
+ name->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 5);
name->connect("gui_input", this, "_line_gui_input");
}
diff --git a/editor/editor_name_dialog.h b/editor/editor_name_dialog.h
index d6bc7eca94..5b65abef84 100644
--- a/editor/editor_name_dialog.h
+++ b/editor/editor_name_dialog.h
@@ -35,21 +35,19 @@
class EditorNameDialog : public ConfirmationDialog {
- GDCLASS( EditorNameDialog, ConfirmationDialog );
+ GDCLASS(EditorNameDialog, ConfirmationDialog);
LineEdit *name;
- void _line_gui_input(const InputEvent& p_event);
+ void _line_gui_input(const InputEvent &p_event);
protected:
-
static void _bind_methods();
virtual void ok_pressed();
virtual void _post_popup();
public:
-
- LineEdit* get_line_edit() { return name; }
+ LineEdit *get_line_edit() { return name; }
EditorNameDialog();
};
diff --git a/editor/editor_node.cpp b/editor/editor_node.cpp
index 7a85941b0d..00df0f337d 100644
--- a/editor/editor_node.cpp
+++ b/editor/editor_node.cpp
@@ -28,162 +28,154 @@
/*************************************************************************/
#include "editor_node.h"
-#include "version.h"
-#include "print_string.h"
-#include "editor_themes.h"
-#include "editor_help.h"
-#include "core/io/resource_saver.h"
+#include "animation_editor.h"
+#include "bind/core_bind.h"
+#include "class_db.h"
#include "core/io/resource_loader.h"
-#include "servers/physics_2d_server.h"
-#include "scene/resources/packed_scene.h"
+#include "core/io/resource_saver.h"
+#include "editor_file_system.h"
+#include "editor_help.h"
#include "editor_settings.h"
+#include "editor_themes.h"
#include "global_config.h"
-#include <stdio.h>
-#include "class_db.h"
+#include "io/config_file.h"
+#include "io/stream_peer_ssl.h"
+#include "io/zip_io.h"
+#include "main/input_default.h"
+#include "message_queue.h"
+#include "os/file_access.h"
+#include "os/input.h"
#include "os/keyboard.h"
#include "os/os.h"
-#include "os/file_access.h"
-#include "message_queue.h"
#include "path_remap.h"
-#include "translation.h"
+#include "print_string.h"
#include "pvrtc_compress.h"
-#include "editor_file_system.h"
#include "register_exporters.h"
-#include "bind/core_bind.h"
-#include "io/zip_io.h"
-#include "io/config_file.h"
-#include "animation_editor.h"
-#include "io/stream_peer_ssl.h"
-#include "main/input_default.h"
-#include "os/input.h"
+#include "scene/resources/packed_scene.h"
+#include "servers/physics_2d_server.h"
+#include "translation.h"
+#include "version.h"
+#include <stdio.h>
// plugins
-#include "plugins/sprite_frames_editor_plugin.h"
-#include "plugins/texture_region_editor_plugin.h"
-#include "plugins/canvas_item_editor_plugin.h"
#include "asset_library_editor_plugin.h"
-#include "plugins/spatial_editor_plugin.h"
-#include "plugins/sample_editor_plugin.h"
-#include "plugins/texture_editor_plugin.h"
-#include "plugins/material_editor_plugin.h"
-#include "plugins/sample_library_editor_plugin.h"
-#include "plugins/sample_player_editor_plugin.h"
+#include "import/resource_importer_csv_translation.h"
+#include "import/resource_importer_obj.h"
+#include "import/resource_importer_scene.h"
+#include "import/resource_importer_texture.h"
+#include "import/resource_importer_wav.h"
+#include "plugins/animation_player_editor_plugin.h"
+#include "plugins/animation_tree_editor_plugin.h"
+#include "plugins/baked_light_editor_plugin.h"
#include "plugins/camera_editor_plugin.h"
-#include "plugins/style_box_editor_plugin.h"
-#include "plugins/resource_preloader_editor_plugin.h"
+#include "plugins/canvas_item_editor_plugin.h"
+#include "plugins/collision_polygon_2d_editor_plugin.h"
+#include "plugins/collision_polygon_editor_plugin.h"
+#include "plugins/collision_shape_2d_editor_plugin.h"
+#include "plugins/color_ramp_editor_plugin.h"
+#include "plugins/cube_grid_theme_editor_plugin.h"
+#include "plugins/gi_probe_editor_plugin.h"
#include "plugins/item_list_editor_plugin.h"
-#include "plugins/stream_editor_plugin.h"
-#include "plugins/multimesh_editor_plugin.h"
-#include "plugins/mesh_instance_editor_plugin.h"
+#include "plugins/light_occluder_2d_editor_plugin.h"
+#include "plugins/line_2d_editor_plugin.h"
+#include "plugins/material_editor_plugin.h"
#include "plugins/mesh_editor_plugin.h"
-#include "plugins/theme_editor_plugin.h"
-#include "plugins/tile_map_editor_plugin.h"
-#include "plugins/cube_grid_theme_editor_plugin.h"
-#include "plugins/shader_editor_plugin.h"
-#include "plugins/shader_graph_editor_plugin.h"
+#include "plugins/mesh_instance_editor_plugin.h"
+#include "plugins/multimesh_editor_plugin.h"
+#include "plugins/navigation_polygon_editor_plugin.h"
+#include "plugins/particles_2d_editor_plugin.h"
+#include "plugins/particles_editor_plugin.h"
+#include "plugins/path_2d_editor_plugin.h"
#include "plugins/path_editor_plugin.h"
+#include "plugins/polygon_2d_editor_plugin.h"
+#include "plugins/resource_preloader_editor_plugin.h"
#include "plugins/rich_text_editor_plugin.h"
-#include "plugins/collision_polygon_editor_plugin.h"
-#include "plugins/collision_polygon_2d_editor_plugin.h"
+#include "plugins/sample_editor_plugin.h"
+#include "plugins/sample_library_editor_plugin.h"
+#include "plugins/sample_player_editor_plugin.h"
#include "plugins/script_editor_plugin.h"
#include "plugins/script_text_editor.h"
-#include "plugins/path_2d_editor_plugin.h"
-#include "plugins/line_2d_editor_plugin.h"
-#include "plugins/particles_editor_plugin.h"
-#include "plugins/particles_2d_editor_plugin.h"
-#include "plugins/animation_tree_editor_plugin.h"
+#include "plugins/shader_editor_plugin.h"
+#include "plugins/shader_graph_editor_plugin.h"
+#include "plugins/spatial_editor_plugin.h"
+#include "plugins/sprite_frames_editor_plugin.h"
+#include "plugins/stream_editor_plugin.h"
+#include "plugins/style_box_editor_plugin.h"
+#include "plugins/texture_editor_plugin.h"
+#include "plugins/texture_region_editor_plugin.h"
+#include "plugins/theme_editor_plugin.h"
+#include "plugins/tile_map_editor_plugin.h"
#include "plugins/tile_set_editor_plugin.h"
-#include "plugins/animation_player_editor_plugin.h"
-#include "plugins/baked_light_editor_plugin.h"
-#include "plugins/polygon_2d_editor_plugin.h"
-#include "plugins/navigation_polygon_editor_plugin.h"
-#include "plugins/light_occluder_2d_editor_plugin.h"
-#include "plugins/color_ramp_editor_plugin.h"
-#include "plugins/collision_shape_2d_editor_plugin.h"
-#include "plugins/gi_probe_editor_plugin.h"
-#include "import/resource_importer_texture.h"
-#include "import/resource_importer_csv_translation.h"
-#include "import/resource_importer_wav.h"
-#include "import/resource_importer_obj.h"
-#include "import/resource_importer_scene.h"
// end
#include "editor_settings.h"
-#include "io_plugins/editor_texture_import_plugin.h"
-#include "io_plugins/editor_scene_import_plugin.h"
-#include "io_plugins/editor_font_import_plugin.h"
-#include "io_plugins/editor_sample_import_plugin.h"
-#include "io_plugins/editor_translation_import_plugin.h"
+#include "import/editor_import_collada.h"
#include "io_plugins/editor_bitmask_import_plugin.h"
-#include "io_plugins/editor_mesh_import_plugin.h"
#include "io_plugins/editor_export_scene.h"
-#include "import/editor_import_collada.h"
+#include "io_plugins/editor_font_import_plugin.h"
+#include "io_plugins/editor_mesh_import_plugin.h"
+#include "io_plugins/editor_sample_import_plugin.h"
+#include "io_plugins/editor_scene_import_plugin.h"
#include "io_plugins/editor_scene_importer_fbxconv.h"
+#include "io_plugins/editor_texture_import_plugin.h"
+#include "io_plugins/editor_translation_import_plugin.h"
-#include "plugins/editor_preview_plugins.h"
-#include "editor_initialize_ssl.h"
#include "editor_audio_buses.h"
+#include "editor_initialize_ssl.h"
+#include "plugins/editor_preview_plugins.h"
#include "script_editor_debugger.h"
-EditorNode *EditorNode::singleton=NULL;
+EditorNode *EditorNode::singleton = NULL;
void EditorNode::_update_scene_tabs() {
bool show_rb = EditorSettings::get_singleton()->get("interface/show_script_in_scene_tabs");
scene_tabs->clear_tabs();
- Ref<Texture> script_icon = gui_base->get_icon("Script","EditorIcons");
- for(int i=0;i<editor_data.get_edited_scene_count();i++) {
+ Ref<Texture> script_icon = gui_base->get_icon("Script", "EditorIcons");
+ for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
- String type=editor_data.get_scene_type(i);
+ String type = editor_data.get_scene_type(i);
Ref<Texture> icon;
- if (type!=String()) {
+ if (type != String()) {
- if (!gui_base->has_icon(type,"EditorIcons")) {
- type="Node";
+ if (!gui_base->has_icon(type, "EditorIcons")) {
+ type = "Node";
}
- icon=gui_base->get_icon(type,"EditorIcons");
-
+ icon = gui_base->get_icon(type, "EditorIcons");
}
-
-
int current = editor_data.get_edited_scene();
- bool unsaved = (i==current)?saved_version!=editor_data.get_undo_redo().get_version():editor_data.get_scene_version(i)!=0;
- scene_tabs->add_tab(editor_data.get_scene_title(i)+(unsaved?"(*)":""),icon);
+ bool unsaved = (i == current) ? saved_version != editor_data.get_undo_redo().get_version() : editor_data.get_scene_version(i) != 0;
+ scene_tabs->add_tab(editor_data.get_scene_title(i) + (unsaved ? "(*)" : ""), icon);
if (show_rb && editor_data.get_scene_root_script(i).is_valid()) {
- scene_tabs->set_tab_right_button(i,script_icon);
+ scene_tabs->set_tab_right_button(i, script_icon);
}
-
}
scene_tabs->set_current_tab(editor_data.get_edited_scene());
scene_tabs->ensure_tab_visible(editor_data.get_edited_scene());
-
}
void EditorNode::_update_title() {
String appname = GlobalConfig::get_singleton()->get("application/name");
- String title = appname.empty()?String(VERSION_FULL_NAME):String(_MKSTR(VERSION_NAME) + String(" - ") + appname);
- String edited = editor_data.get_edited_scene_root()?editor_data.get_edited_scene_root()->get_filename():String();
+ String title = appname.empty() ? String(VERSION_FULL_NAME) : String(_MKSTR(VERSION_NAME) + String(" - ") + appname);
+ String edited = editor_data.get_edited_scene_root() ? editor_data.get_edited_scene_root()->get_filename() : String();
if (!edited.empty())
- title+=" - " + String(edited.get_file());
+ title += " - " + String(edited.get_file());
if (unsaved_cache)
- title+=" (*)";
+ title += " (*)";
OS::get_singleton()->set_window_title(title);
-
}
-void EditorNode::_unhandled_input(const InputEvent& p_event) {
+void EditorNode::_unhandled_input(const InputEvent &p_event) {
if (Node::get_viewport()->get_modal_stack_top())
return; //ignore because of modal window
-
- if (p_event.type==InputEvent::KEY && p_event.key.pressed && !p_event.key.echo && !gui_base->get_viewport()->gui_has_modal_stack()) {
-
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed && !p_event.key.echo && !gui_base->get_viewport()->gui_has_modal_stack()) {
if (ED_IS_SHORTCUT("editor/next_tab", p_event)) {
int next_tab = editor_data.get_edited_scene() + 1;
@@ -199,7 +191,7 @@ void EditorNode::_unhandled_input(const InputEvent& p_event) {
filesystem_dock->focus_on_filter();
}
- switch(p_event.key.scancode) {
+ switch (p_event.key.scancode) {
/*case KEY_F1:
if (!p_event.key.mod.shift && !p_event.key.mod.command)
@@ -208,38 +200,34 @@ void EditorNode::_unhandled_input(const InputEvent& p_event) {
case KEY_F1:
if (!p_event.key.mod.shift && !p_event.key.mod.command)
_editor_select(EDITOR_2D);
- break;
+ break;
case KEY_F2:
if (!p_event.key.mod.shift && !p_event.key.mod.command)
_editor_select(EDITOR_3D);
- break;
+ break;
case KEY_F3:
if (!p_event.key.mod.shift && !p_event.key.mod.command)
_editor_select(EDITOR_SCRIPT);
- break;
- /* case KEY_F5: _menu_option_confirm((p_event.key.mod.control&&p_event.key.mod.shift)?RUN_PLAY_CUSTOM_SCENE:RUN_PLAY,true); break;
+ break;
+ /* case KEY_F5: _menu_option_confirm((p_event.key.mod.control&&p_event.key.mod.shift)?RUN_PLAY_CUSTOM_SCENE:RUN_PLAY,true); break;
case KEY_F6: _menu_option_confirm(RUN_PLAY_SCENE,true); break;
//case KEY_F7: _menu_option_confirm(RUN_PAUSE,true); break;
case KEY_F8: _menu_option_confirm(RUN_STOP,true); break;*/
-
}
-
}
}
-
-
void EditorNode::_notification(int p_what) {
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
editor_data.save_editor_external_data();
FileAccess::set_file_close_fail_notify_callback(NULL);
log->deinit(); // do not get messages anymore
}
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
- //force the whole tree viewport
+//force the whole tree viewport
#if 0
{
Rect2 grect = scene_root_base->get_global_rect();
@@ -252,17 +240,17 @@ void EditorNode::_notification(int p_what) {
#endif
if (opening_prev && !confirmation->is_visible())
- opening_prev=false;
+ opening_prev = false;
- if (unsaved_cache != (saved_version!=editor_data.get_undo_redo().get_version())) {
+ if (unsaved_cache != (saved_version != editor_data.get_undo_redo().get_version())) {
- unsaved_cache = (saved_version!=editor_data.get_undo_redo().get_version());
+ unsaved_cache = (saved_version != editor_data.get_undo_redo().get_version());
_update_title();
}
- if (last_checked_version!=editor_data.get_undo_redo().get_version()) {
+ if (last_checked_version != editor_data.get_undo_redo().get_version()) {
_update_scene_tabs();
- last_checked_version=editor_data.get_undo_redo().get_version();
+ last_checked_version = editor_data.get_undo_redo().get_version();
}
//get_root_node()->set_rect(viewport->get_global_rect());
@@ -271,48 +259,46 @@ void EditorNode::_notification(int p_what) {
uint64_t frame = Engine::get_singleton()->get_frames_drawn();
uint32_t tick = OS::get_singleton()->get_ticks_msec();
- if (frame!=circle_step_frame && (tick-circle_step_msec)>(1000/8)) {
+ if (frame != circle_step_frame && (tick - circle_step_msec) > (1000 / 8)) {
circle_step++;
- if (circle_step>=8)
- circle_step=0;
+ if (circle_step >= 8)
+ circle_step = 0;
- circle_step_msec=tick;
- circle_step_frame=frame+1;
+ circle_step_msec = tick;
+ circle_step_frame = frame + 1;
// update the circle itself only when its enabled
- if (!update_menu->get_popup()->is_item_checked(3)){
- update_menu->set_icon(gui_base->get_icon("Progress"+itos(circle_step+1),"EditorIcons"));
+ if (!update_menu->get_popup()->is_item_checked(3)) {
+ update_menu->set_icon(gui_base->get_icon("Progress" + itos(circle_step + 1), "EditorIcons"));
}
}
editor_selection->update();
{
- uint32_t p32 = 0;//AudioServer::get_singleton()->read_output_peak()>>8;
+ uint32_t p32 = 0; //AudioServer::get_singleton()->read_output_peak()>>8;
- float peak = p32==0? -80 : Math::linear2db(p32 / 65535.0);
+ float peak = p32 == 0 ? -80 : Math::linear2db(p32 / 65535.0);
- if (peak<-80)
- peak=-80;
+ if (peak < -80)
+ peak = -80;
float vu = audio_vu->get_value();
if (peak > vu) {
audio_vu->set_value(peak);
} else {
- float new_vu = vu - get_process_delta_time()*70.0;
- if (new_vu<-80)
- new_vu=-80;
- if (new_vu !=-80 && vu !=-80)
+ float new_vu = vu - get_process_delta_time() * 70.0;
+ if (new_vu < -80)
+ new_vu = -80;
+ if (new_vu != -80 && vu != -80)
audio_vu->set_value(new_vu);
}
-
}
ResourceImporterTexture::get_singleton()->update_imports();
-
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
get_tree()->get_root()->set_disable_3d(true);
//MessageQueue::get_singleton()->push_call(this,"_get_scene_metadata");
@@ -320,28 +306,26 @@ void EditorNode::_notification(int p_what) {
get_tree()->get_root()->set_as_audio_listener(false);
get_tree()->get_root()->set_as_audio_listener_2d(false);
get_tree()->set_auto_accept_quit(false);
- get_tree()->connect("files_dropped",this,"_dropped_files");
- //VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport(),false);
+ get_tree()->connect("files_dropped", this, "_dropped_files");
+ //VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport(),false);
//import_monitor->scan_changes();
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
+ if (p_what == NOTIFICATION_EXIT_TREE) {
editor_data.clear_edited_scenes();
-
}
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
- VisualServer::get_singleton()->viewport_set_hide_scenario(get_scene_root()->get_viewport_rid(),true);
- VisualServer::get_singleton()->viewport_set_hide_canvas(get_scene_root()->get_viewport_rid(),true);
- VisualServer::get_singleton()->viewport_set_disable_environment(get_viewport()->get_viewport_rid(),true);
+ VisualServer::get_singleton()->viewport_set_hide_scenario(get_scene_root()->get_viewport_rid(), true);
+ VisualServer::get_singleton()->viewport_set_hide_canvas(get_scene_root()->get_viewport_rid(), true);
+ VisualServer::get_singleton()->viewport_set_disable_environment(get_viewport()->get_viewport_rid(), true);
_editor_select(EDITOR_3D);
_update_debug_options();
-/*
+ /*
if (defer_optimize!="") {
Error ok = save_optimized_copy(defer_optimize,defer_optimize_preset);
defer_optimize_preset="";
@@ -372,27 +356,26 @@ void EditorNode::_notification(int p_what) {
};
if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) {
- scene_tabs->set_tab_close_display_policy( (bool(EDITOR_DEF("interface/always_show_close_button_in_scene_tabs", false)) ? Tabs::CLOSE_BUTTON_SHOW_ALWAYS : Tabs::CLOSE_BUTTON_SHOW_ACTIVE_ONLY) );
+ scene_tabs->set_tab_close_display_policy((bool(EDITOR_DEF("interface/always_show_close_button_in_scene_tabs", false)) ? Tabs::CLOSE_BUTTON_SHOW_ALWAYS : Tabs::CLOSE_BUTTON_SHOW_ACTIVE_ONLY));
}
-
}
void EditorNode::_fs_changed() {
- for(Set<FileDialog*>::Element *E=file_dialogs.front();E;E=E->next()) {
+ for (Set<FileDialog *>::Element *E = file_dialogs.front(); E; E = E->next()) {
E->get()->invalidate();
}
- for(Set<EditorFileDialog*>::Element *E=editor_file_dialogs.front();E;E=E->next()) {
+ for (Set<EditorFileDialog *>::Element *E = editor_file_dialogs.front(); E; E = E->next()) {
E->get()->invalidate();
}
- if (export_defer.platform!="") {
+ if (export_defer.platform != "") {
//project_export_settings->export_platform(export_defer.platform,export_defer.path,export_defer.debug,export_defer.password,true);
- export_defer.platform="";
+ export_defer.platform = "";
}
{
@@ -403,7 +386,7 @@ void EditorNode::_fs_changed() {
List<Ref<Resource> > cached;
ResourceCache::get_cached_resources(&cached);
//this should probably be done in a thread..
- for(List<Ref<Resource> >::Element *E=cached.front();E;E=E->next()) {
+ for (List<Ref<Resource> >::Element *E = cached.front(); E; E = E->next()) {
if (!E->get()->editor_can_reload_from_file())
continue;
@@ -412,12 +395,12 @@ void EditorNode::_fs_changed() {
if (!FileAccess::exists(E->get()->get_path()))
continue;
- if (E->get()->get_import_path()!=String()) {
+ if (E->get()->get_import_path() != String()) {
//imported resource
uint64_t mt = FileAccess::get_modified_time(E->get()->get_import_path());
- print_line("testing modified: "+E->get()->get_import_path()+" "+itos(mt)+" vs "+itos(E->get()->get_import_last_modified_time()));
+ print_line("testing modified: " + E->get()->get_import_path() + " " + itos(mt) + " vs " + itos(E->get()->get_import_last_modified_time()));
- if (mt!=E->get()->get_import_last_modified_time()) {
+ if (mt != E->get()->get_import_last_modified_time()) {
print_line("success");
changed.push_back(E->get());
}
@@ -425,7 +408,7 @@ void EditorNode::_fs_changed() {
} else {
uint64_t mt = FileAccess::get_modified_time(E->get()->get_path());
- if (mt!=E->get()->get_last_modified_time()) {
+ if (mt != E->get()->get_last_modified_time()) {
changed.push_back(E->get());
}
}
@@ -433,47 +416,39 @@ void EditorNode::_fs_changed() {
if (changed.size()) {
//EditorProgress ep("reload_res","Reload Modified Resources",changed.size());
- int idx=0;
- for(List<Ref<Resource> >::Element *E=changed.front();E;E=E->next()) {
+ int idx = 0;
+ for (List<Ref<Resource> >::Element *E = changed.front(); E; E = E->next()) {
//ep.step(E->get()->get_path(),idx++);
E->get()->reload_from_file();
}
}
-
-
}
}
-
void EditorNode::_sources_changed(bool p_exist) {
if (waiting_for_first_scan) {
- if (defer_load_scene!="") {
+ if (defer_load_scene != "") {
print_line("loading scene DEFERED");
load_scene(defer_load_scene);
- defer_load_scene="";
+ defer_load_scene = "";
}
- waiting_for_first_scan=false;
+ waiting_for_first_scan = false;
}
-
-
}
void EditorNode::_vp_resized() {
-
-
}
-void EditorNode::_rebuild_import_menu()
-{
- PopupMenu* p = import_menu->get_popup();
+void EditorNode::_rebuild_import_menu() {
+ PopupMenu *p = import_menu->get_popup();
p->clear();
- //p->add_item(TTR("Node From Scene"), FILE_IMPORT_SUBSCENE);
- //p->add_separator();
+//p->add_item(TTR("Node From Scene"), FILE_IMPORT_SUBSCENE);
+//p->add_separator();
#if 0
for (int i = 0; i < editor_import_export->get_import_plugin_count(); i++) {
p->add_item(editor_import_export->get_import_plugin(i)->get_visible_name(), IMPORT_PLUGIN_BASE + i);
@@ -487,21 +462,19 @@ void EditorNode::_node_renamed() {
property_editor->update_tree();
}
-
-Error EditorNode::load_resource(const String& p_scene) {
+Error EditorNode::load_resource(const String &p_scene) {
RES res = ResourceLoader::load(p_scene);
- ERR_FAIL_COND_V(!res.is_valid(),ERR_CANT_OPEN);
+ ERR_FAIL_COND_V(!res.is_valid(), ERR_CANT_OPEN);
edit_resource(res);
return OK;
}
+void EditorNode::edit_resource(const Ref<Resource> &p_resource) {
-void EditorNode::edit_resource(const Ref<Resource>& p_resource) {
-
- _resource_selected(p_resource,"");
+ _resource_selected(p_resource, "");
}
void EditorNode::edit_node(Node *p_node) {
@@ -509,213 +482,202 @@ void EditorNode::edit_node(Node *p_node) {
push_item(p_node);
}
-void EditorNode::open_resource(const String& p_type) {
-
+void EditorNode::open_resource(const String &p_type) {
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type(p_type,&extensions);
+ ResourceLoader::get_recognized_extensions_for_type(p_type, &extensions);
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
//file->set_current_path(current_path);
file->popup_centered_ratio();
- current_option=RESOURCE_LOAD;
+ current_option = RESOURCE_LOAD;
}
-
-void EditorNode::save_resource_in_path(const Ref<Resource>& p_resource,const String& p_path) {
+void EditorNode::save_resource_in_path(const Ref<Resource> &p_resource, const String &p_path) {
editor_data.apply_changes_in_editors();
- int flg=0;
+ int flg = 0;
if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources"))
- flg|=ResourceSaver::FLAG_COMPRESS;
+ flg |= ResourceSaver::FLAG_COMPRESS;
/*
if (EditorSettings::get_singleton()->get("filesystem/on_save/save_paths_as_relative"))
flg|=ResourceSaver::FLAG_RELATIVE_PATHS;
*/
String path = GlobalConfig::get_singleton()->localize_path(p_path);
- Error err = ResourceSaver::save(path,p_resource,flg|ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
+ Error err = ResourceSaver::save(path, p_resource, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
- if (err!=OK) {
+ if (err != OK) {
accept->set_text(TTR("Error saving resource!"));
accept->popup_centered_minsize();
- return;
+ return;
}
//EditorFileSystem::get_singleton()->update_file(path,p_resource->get_type());
- ((Resource*)p_resource.ptr())->set_path(path);
- emit_signal("resource_saved",p_resource);
-
+ ((Resource *)p_resource.ptr())->set_path(path);
+ emit_signal("resource_saved", p_resource);
}
-void EditorNode::save_resource(const Ref<Resource>& p_resource) {
+void EditorNode::save_resource(const Ref<Resource> &p_resource) {
if (p_resource->get_path().is_resource_file()) {
- save_resource_in_path(p_resource,p_resource->get_path());
+ save_resource_in_path(p_resource, p_resource->get_path());
} else {
save_resource_as(p_resource);
}
}
-void EditorNode::save_resource_as(const Ref<Resource>& p_resource,const String& p_at_path) {
+void EditorNode::save_resource_as(const Ref<Resource> &p_resource, const String &p_at_path) {
file->set_mode(EditorFileDialog::MODE_SAVE_FILE);
- current_option=RESOURCE_SAVE_AS;
+ current_option = RESOURCE_SAVE_AS;
List<String> extensions;
- Ref<PackedScene> sd = memnew( PackedScene );
- ResourceSaver::get_recognized_extensions(p_resource,&extensions);
+ Ref<PackedScene> sd = memnew(PackedScene);
+ ResourceSaver::get_recognized_extensions(p_resource, &extensions);
file->clear_filters();
List<String> preferred;
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- if (p_resource->is_class("Script") && (extensions[i]=="tres" || extensions[i]=="res" || extensions[i]=="xml")) {
+ if (p_resource->is_class("Script") && (extensions[i] == "tres" || extensions[i] == "res" || extensions[i] == "xml")) {
//this serves no purpose and confused people
continue;
}
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
preferred.push_back(extensions[i]);
}
//file->set_current_path(current_path);
- if (p_at_path!=String()) {
+ if (p_at_path != String()) {
file->set_current_dir(p_at_path);
if (p_resource->get_path().is_resource_file()) {
file->set_current_file(p_resource->get_path().get_file());
} else {
- if (extensions.size()) {
- file->set_current_file("new_"+p_resource->get_class().to_lower()+"."+preferred.front()->get().to_lower());
+ if (extensions.size()) {
+ file->set_current_file("new_" + p_resource->get_class().to_lower() + "." + preferred.front()->get().to_lower());
} else {
file->set_current_file(String());
}
}
- } else if (p_resource->get_path()!="") {
+ } else if (p_resource->get_path() != "") {
file->set_current_path(p_resource->get_path());
if (extensions.size()) {
- String ext=p_resource->get_path().get_extension().to_lower();
- if (extensions.find(ext)==NULL) {
- file->set_current_path(p_resource->get_path().replacen("."+ext,"."+extensions.front()->get()));
+ String ext = p_resource->get_path().get_extension().to_lower();
+ if (extensions.find(ext) == NULL) {
+ file->set_current_path(p_resource->get_path().replacen("." + ext, "." + extensions.front()->get()));
}
}
} else if (preferred.size()) {
String existing;
if (extensions.size()) {
- existing="new_"+p_resource->get_class().to_lower()+"."+preferred.front()->get().to_lower();
+ existing = "new_" + p_resource->get_class().to_lower() + "." + preferred.front()->get().to_lower();
}
file->set_current_path(existing);
-
}
file->popup_centered_ratio();
file->set_title(TTR("Save Resource As.."));
}
-
void EditorNode::_menu_option(int p_option) {
- _menu_option_confirm(p_option,false);
+ _menu_option_confirm(p_option, false);
}
void EditorNode::_menu_confirm_current() {
- _menu_option_confirm(current_option,true);
+ _menu_option_confirm(current_option, true);
}
-
-void EditorNode::_dialog_display_file_error(String p_file,Error p_error) {
-
+void EditorNode::_dialog_display_file_error(String p_file, Error p_error) {
if (p_error) {
- current_option=-1;
+ current_option = -1;
//accept->"()->hide();
accept->get_ok()->set_text(TTR("I see.."));
- switch(p_error) {
+ switch (p_error) {
case ERR_FILE_CANT_WRITE: {
- accept->set_text(TTR("Can't open file for writing:")+" "+p_file.get_extension());
+ accept->set_text(TTR("Can't open file for writing:") + " " + p_file.get_extension());
} break;
case ERR_FILE_UNRECOGNIZED: {
- accept->set_text(TTR("Requested file format unknown:")+" "+p_file.get_extension());
+ accept->set_text(TTR("Requested file format unknown:") + " " + p_file.get_extension());
} break;
default: {
accept->set_text(TTR("Error while saving."));
- }break;
+ } break;
}
accept->popup_centered_minsize();
}
-
}
-void EditorNode::_get_scene_metadata(const String& p_file) {
+void EditorNode::_get_scene_metadata(const String &p_file) {
Node *scene = editor_data.get_edited_scene_root();
if (!scene)
return;
- String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file()+"-editstate-"+p_file.md5_text()+".cfg");
+ String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file() + "-editstate-" + p_file.md5_text() + ".cfg");
Ref<ConfigFile> cf;
cf.instance();
Error err = cf->load(path);
- if (err!=OK || !cf->has_section("editor_states"))
+ if (err != OK || !cf->has_section("editor_states"))
return; //must not exist
List<String> esl;
- cf->get_section_keys("editor_states",&esl);
+ cf->get_section_keys("editor_states", &esl);
Dictionary md;
- for (List<String>::Element *E=esl.front();E;E=E->next()) {
+ for (List<String>::Element *E = esl.front(); E; E = E->next()) {
- Variant st=cf->get_value("editor_states",E->get());
+ Variant st = cf->get_value("editor_states", E->get());
if (st.get_type()) {
- md[E->get()]=st;
+ md[E->get()] = st;
}
}
-
-
editor_data.set_editor_states(md);
-
}
-void EditorNode::_set_scene_metadata(const String& p_file, int p_idx) {
+void EditorNode::_set_scene_metadata(const String &p_file, int p_idx) {
Node *scene = editor_data.get_edited_scene_root(p_idx);
if (!scene)
return;
- scene->set_meta("__editor_run_settings__",Variant()); //clear it (no point in keeping it)
- scene->set_meta("__editor_plugin_states__",Variant());
+ scene->set_meta("__editor_run_settings__", Variant()); //clear it (no point in keeping it)
+ scene->set_meta("__editor_plugin_states__", Variant());
- String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file()+"-editstate-"+p_file.md5_text()+".cfg");
+ String path = EditorSettings::get_singleton()->get_project_settings_path().plus_file(p_file.get_file() + "-editstate-" + p_file.md5_text() + ".cfg");
Ref<ConfigFile> cf;
cf.instance();
Dictionary md;
- if (p_idx<0 || editor_data.get_edited_scene()==p_idx) {
+ if (p_idx < 0 || editor_data.get_edited_scene() == p_idx) {
md = editor_data.get_editor_states();
} else {
md = editor_data.get_scene_editor_states(p_idx);
@@ -724,83 +686,76 @@ void EditorNode::_set_scene_metadata(const String& p_file, int p_idx) {
List<Variant> keys;
md.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
- cf->set_value("editor_states",E->get(),md[E->get()]);
+ cf->set_value("editor_states", E->get(), md[E->get()]);
}
Error err = cf->save(path);
- ERR_FAIL_COND(err!=OK);
-
+ ERR_FAIL_COND(err != OK);
}
-
-bool EditorNode::_find_and_save_resource(RES res,Map<RES,bool>& processed,int32_t flags) {
+bool EditorNode::_find_and_save_resource(RES res, Map<RES, bool> &processed, int32_t flags) {
if (res.is_null())
return false;
- if (processed.has(res)) {
-
- return processed[res];
- }
+ if (processed.has(res)) {
+ return processed[res];
+ }
bool changed = res->is_edited();
res->set_edited(false);
- bool subchanged = _find_and_save_edited_subresources(res.ptr(),processed,flags);
+ bool subchanged = _find_and_save_edited_subresources(res.ptr(), processed, flags);
//print_line("checking if edited: "+res->get_type()+" :: "+res->get_name()+" :: "+res->get_path()+" :: "+itos(changed)+" :: SR "+itos(subchanged));
if (res->get_path().is_resource_file()) {
if (changed || subchanged) {
//save
- print_line("Also saving modified external resource: "+res->get_path());
- ResourceSaver::save(res->get_path(),res,flags);
-
+ print_line("Also saving modified external resource: " + res->get_path());
+ ResourceSaver::save(res->get_path(), res, flags);
}
- processed[res]=false; //because it's a file
+ processed[res] = false; //because it's a file
return false;
} else {
-
- processed[res]=changed;
+ processed[res] = changed;
return changed;
}
}
-bool EditorNode::_find_and_save_edited_subresources(Object *obj,Map<RES,bool>& processed,int32_t flags) {
+bool EditorNode::_find_and_save_edited_subresources(Object *obj, Map<RES, bool> &processed, int32_t flags) {
- bool ret_changed=false;
+ bool ret_changed = false;
List<PropertyInfo> pi;
obj->get_property_list(&pi);
- for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
-
-
- switch(E->get().type) {
+ switch (E->get().type) {
case Variant::OBJECT: {
RES res = obj->get(E->get().name);
- if (_find_and_save_resource(res,processed,flags))
- ret_changed=true;
+ if (_find_and_save_resource(res, processed, flags))
+ ret_changed = true;
} break;
case Variant::ARRAY: {
- Array varray= obj->get(E->get().name);
- int len=varray.size();
- for(int i=0;i<len;i++) {
+ Array varray = obj->get(E->get().name);
+ int len = varray.size();
+ for (int i = 0; i < len; i++) {
- Variant v=varray.get(i);
- RES res=v;
- if (_find_and_save_resource(res,processed,flags))
- ret_changed=true;
+ Variant v = varray.get(i);
+ RES res = v;
+ if (_find_and_save_resource(res, processed, flags))
+ ret_changed = true;
//_find_resources(v);
}
@@ -808,44 +763,40 @@ bool EditorNode::_find_and_save_edited_subresources(Object *obj,Map<RES,bool>& p
} break;
case Variant::DICTIONARY: {
-
- Dictionary d=obj->get(E->get().name);
+ Dictionary d = obj->get(E->get().name);
List<Variant> keys;
d.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
Variant v = d[E->get()];
- RES res=v;
- if (_find_and_save_resource(res,processed,flags))
- ret_changed=true;
+ RES res = v;
+ if (_find_and_save_resource(res, processed, flags))
+ ret_changed = true;
}
} break;
default: {}
}
-
}
return ret_changed;
-
}
-void EditorNode::_save_edited_subresources(Node* scene,Map<RES,bool>& processed,int32_t flags) {
+void EditorNode::_save_edited_subresources(Node *scene, Map<RES, bool> &processed, int32_t flags) {
- _find_and_save_edited_subresources(scene,processed,flags);
+ _find_and_save_edited_subresources(scene, processed, flags);
- for(int i=0;i<scene->get_child_count();i++) {
+ for (int i = 0; i < scene->get_child_count(); i++) {
Node *n = scene->get_child(i);
- if (n->get_owner()!=editor_data.get_edited_scene_root())
+ if (n->get_owner() != editor_data.get_edited_scene_root())
continue;
- _save_edited_subresources(n,processed,flags);
+ _save_edited_subresources(n, processed, flags);
}
-
}
-void EditorNode::_find_node_types(Node* p_node, int&count_2d, int&count_3d) {
+void EditorNode::_find_node_types(Node *p_node, int &count_2d, int &count_3d) {
- if (p_node->is_class("Viewport") || (p_node!=editor_data.get_edited_scene_root() && p_node->get_owner()!=editor_data.get_edited_scene_root()))
+ if (p_node->is_class("Viewport") || (p_node != editor_data.get_edited_scene_root() && p_node->get_owner() != editor_data.get_edited_scene_root()))
return;
if (p_node->is_class("CanvasItem"))
@@ -853,46 +804,42 @@ void EditorNode::_find_node_types(Node* p_node, int&count_2d, int&count_3d) {
else if (p_node->is_class("Spatial"))
count_3d++;
- for(int i=0;i<p_node->get_child_count();i++)
- _find_node_types(p_node->get_child(i),count_2d,count_3d);
-
+ for (int i = 0; i < p_node->get_child_count(); i++)
+ _find_node_types(p_node->get_child(i), count_2d, count_3d);
}
-
void EditorNode::_save_scene_with_preview(String p_file) {
- int c2d=0;
- int c3d=0;
+ int c2d = 0;
+ int c3d = 0;
- EditorProgress save("save",TTR("Saving Scene"),4);
- save.step(TTR("Analyzing"),0);
- _find_node_types(editor_data.get_edited_scene_root(),c2d,c3d);
+ EditorProgress save("save", TTR("Saving Scene"), 4);
+ save.step(TTR("Analyzing"), 0);
+ _find_node_types(editor_data.get_edited_scene_root(), c2d, c3d);
RID viewport;
bool is2d;
- if (c3d<c2d) {
- viewport=scene_root->get_viewport_rid();
- is2d=true;
+ if (c3d < c2d) {
+ viewport = scene_root->get_viewport_rid();
+ is2d = true;
} else {
- viewport=SpatialEditor::get_singleton()->get_editor_viewport(0)->get_viewport_node()->get_viewport_rid();
- is2d=false;
-
+ viewport = SpatialEditor::get_singleton()->get_editor_viewport(0)->get_viewport_node()->get_viewport_rid();
+ is2d = false;
}
- save.step(TTR("Creating Thumbnail"),1);
+ save.step(TTR("Creating Thumbnail"), 1);
//current view?
- int screen =-1;
- for(int i=0;i<editor_table.size();i++) {
- if (editor_plugin_screen==editor_table[i]) {
- screen=i;
+ int screen = -1;
+ for (int i = 0; i < editor_table.size(); i++) {
+ if (editor_plugin_screen == editor_table[i]) {
+ screen = i;
break;
}
}
- _editor_select(is2d?EDITOR_2D:EDITOR_3D);
-
+ _editor_select(is2d ? EDITOR_2D : EDITOR_3D);
- save.step(TTR("Creating Thumbnail"),2);
- save.step(TTR("Creating Thumbnail"),3);
+ save.step(TTR("Creating Thumbnail"), 2);
+ save.step(TTR("Creating Thumbnail"), 3);
#if 0
Image img = VS::get_singleton()->viewport_texture(scree_capture(viewport);
int preview_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
@@ -926,22 +873,20 @@ void EditorNode::_save_scene_with_preview(String p_file) {
editor_data.get_edited_scene_import_metadata()->set_option("thumbnail",imgdata);
#endif
//tamanio tel thumbnail
- if (screen!=-1) {
+ if (screen != -1) {
_editor_select(screen);
}
- save.step(TTR("Saving Scene"),4);
+ save.step(TTR("Saving Scene"), 4);
_save_scene(p_file);
-
}
-
void EditorNode::_save_scene(String p_file, int idx) {
Node *scene = editor_data.get_edited_scene_root(idx);
if (!scene) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text("This operation can't be done without a tree root.");
@@ -951,8 +896,7 @@ void EditorNode::_save_scene(String p_file, int idx) {
editor_data.apply_changes_in_editors();
- _set_scene_metadata(p_file,idx);
-
+ _set_scene_metadata(p_file, idx);
Ref<PackedScene> sdata;
@@ -961,7 +905,7 @@ void EditorNode::_save_scene(String p_file, int idx) {
// we must update it, but also let the previous scene state go, as
// old version still work for referencing changes in instanced or inherited scenes
- sdata = Ref<PackedScene>( ResourceCache::get(p_file)->cast_to<PackedScene>() );
+ sdata = Ref<PackedScene>(ResourceCache::get(p_file)->cast_to<PackedScene>());
if (sdata.is_valid())
sdata->recreate_state();
else
@@ -971,10 +915,9 @@ void EditorNode::_save_scene(String p_file, int idx) {
}
Error err = sdata->pack(scene);
+ if (err != OK) {
- if (err!=OK) {
-
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Couldn't save scene. Likely dependencies (instances) couldn't be satisfied."));
@@ -982,41 +925,35 @@ void EditorNode::_save_scene(String p_file, int idx) {
return;
}
- int flg=0;
+ int flg = 0;
if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources"))
- flg|=ResourceSaver::FLAG_COMPRESS;
+ flg |= ResourceSaver::FLAG_COMPRESS;
/*
if (EditorSettings::get_singleton()->get("filesystem/on_save/save_paths_as_relative"))
flg|=ResourceSaver::FLAG_RELATIVE_PATHS;
*/
- flg|=ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
-
+ flg |= ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
- err = ResourceSaver::save(p_file,sdata,flg);
- Map<RES,bool> processed;
- _save_edited_subresources(scene,processed,flg);
+ err = ResourceSaver::save(p_file, sdata, flg);
+ Map<RES, bool> processed;
+ _save_edited_subresources(scene, processed, flg);
editor_data.save_editor_external_data();
- if (err==OK) {
- scene->set_filename( GlobalConfig::get_singleton()->localize_path(p_file) );
+ if (err == OK) {
+ scene->set_filename(GlobalConfig::get_singleton()->localize_path(p_file));
//EditorFileSystem::get_singleton()->update_file(p_file,sdata->get_type());
if (idx < 0 || idx == editor_data.get_edited_scene())
set_current_version(editor_data.get_undo_redo().get_version());
else
- editor_data.set_edited_scene_version(0,idx);
+ editor_data.set_edited_scene_version(0, idx);
_update_title();
_update_scene_tabs();
} else {
- _dialog_display_file_error(p_file,err);
+ _dialog_display_file_error(p_file, err);
}
-
-
};
-
-
-
-void EditorNode::_import_action(const String& p_action) {
+void EditorNode::_import_action(const String &p_action) {
#if 0
import_confirmation->hide();
@@ -1113,65 +1050,58 @@ void EditorNode::_import(const String &p_file) {
saved_version=editor_data.get_undo_redo().get_version();
_update_title();
-
#endif
}
void EditorNode::_dialog_action(String p_file) {
-
- switch(current_option) {
+ switch (current_option) {
case RESOURCE_LOAD: {
RES res = ResourceLoader::load(p_file);
if (res.is_null()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text("ok :(");
accept->set_text(TTR("Failed to load resource."));
return;
};
-
- push_item(res.operator->() );
+ push_item(res.operator->());
} break;
case FILE_NEW_INHERITED_SCENE: {
-
- load_scene(p_file,false,true);
+ load_scene(p_file, false, true);
} break;
case FILE_OPEN_SCENE: {
-
load_scene(p_file);
} break;
case SETTINGS_PICK_MAIN_SCENE: {
- GlobalConfig::get_singleton()->set("application/main_scene",p_file);
+ GlobalConfig::get_singleton()->set("application/main_scene", p_file);
GlobalConfig::get_singleton()->save();
//would be nice to show the project manager opened with the hilighted field..
} break;
case FILE_SAVE_OPTIMIZED: {
-
-
} break;
case FILE_RUN_SCRIPT: {
- Ref<Script> scr = ResourceLoader::load(p_file,"Script",true);
+ Ref<Script> scr = ResourceLoader::load(p_file, "Script", true);
if (scr.is_null()) {
- add_io_error("Script Failed to Load:\n"+p_file);
+ add_io_error("Script Failed to Load:\n" + p_file);
return;
}
if (!scr->is_tool()) {
- add_io_error("Script is not tool, will not be able to run:\n"+p_file);
+ add_io_error("Script is not tool, will not be able to run:\n" + p_file);
return;
}
- Ref<EditorScript> es = memnew( EditorScript );
+ Ref<EditorScript> es = memnew(EditorScript);
es->set_script(scr.get_ref_ptr());
es->set_editor(this);
es->_run();
@@ -1181,17 +1111,16 @@ void EditorNode::_dialog_action(String p_file) {
case FILE_SAVE_SCENE:
case FILE_SAVE_AS_SCENE: {
- if (file->get_mode()==EditorFileDialog::MODE_SAVE_FILE) {
+ if (file->get_mode() == EditorFileDialog::MODE_SAVE_FILE) {
//_save_scene(p_file);
_save_scene_with_preview(p_file);
-
}
} break;
case FILE_SAVE_AND_RUN: {
- if (file->get_mode()==EditorFileDialog::MODE_SAVE_FILE) {
+ if (file->get_mode() == EditorFileDialog::MODE_SAVE_FILE) {
//_save_scene(p_file);
_save_scene_with_preview(p_file);
@@ -1204,26 +1133,25 @@ void EditorNode::_dialog_action(String p_file) {
Ref<MeshLibrary> ml;
if (file_export_lib_merge->is_pressed() && FileAccess::exists(p_file)) {
- ml=ResourceLoader::load(p_file,"MeshLibrary");
+ ml = ResourceLoader::load(p_file, "MeshLibrary");
if (ml.is_null()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Can't load MeshLibrary for merging!"));
accept->popup_centered_minsize();
return;
}
-
}
if (ml.is_null()) {
- ml = Ref<MeshLibrary>( memnew( MeshLibrary ));
+ ml = Ref<MeshLibrary>(memnew(MeshLibrary));
}
//MeshLibraryEditor::update_library_file(editor_data.get_edited_scene_root(),ml,true);
- Error err = ResourceSaver::save(p_file,ml);
+ Error err = ResourceSaver::save(p_file, ml);
if (err) {
accept->get_ok()->set_text(TTR("I see.."));
@@ -1232,17 +1160,16 @@ void EditorNode::_dialog_action(String p_file) {
return;
}
-
} break;
case FILE_EXPORT_TILESET: {
Ref<TileSet> ml;
if (FileAccess::exists(p_file)) {
- ml=ResourceLoader::load(p_file,"TileSet");
+ ml = ResourceLoader::load(p_file, "TileSet");
if (ml.is_null()) {
if (file_export_lib_merge->is_pressed()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Can't load TileSet for merging!"));
@@ -1254,12 +1181,12 @@ void EditorNode::_dialog_action(String p_file) {
}
} else {
- ml = Ref<TileSet>( memnew( TileSet ));
+ ml = Ref<TileSet>(memnew(TileSet));
}
- TileSetEditor::update_library_file(editor_data.get_edited_scene_root(),ml,true);
+ TileSetEditor::update_library_file(editor_data.get_edited_scene_root(), ml, true);
- Error err = ResourceSaver::save(p_file,ml);
+ Error err = ResourceSaver::save(p_file, ml);
if (err) {
accept->get_ok()->set_text(TTR("I see.."));
@@ -1271,52 +1198,49 @@ void EditorNode::_dialog_action(String p_file) {
case SETTINGS_LOAD_EXPORT_TEMPLATES: {
- FileAccess *fa=NULL;
+ FileAccess *fa = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&fa);
unzFile pkg = unzOpen2(p_file.utf8().get_data(), &io);
if (!pkg) {
- current_option=-1;
+ current_option = -1;
//confirmation->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Can't open export templates zip."));
accept->popup_centered_minsize();
return;
-
}
int ret = unzGoToFirstFile(pkg);
- int fc=0; //count them
+ int fc = 0; //count them
- while(ret==UNZ_OK) {
+ while (ret == UNZ_OK) {
fc++;
ret = unzGoToNextFile(pkg);
-
}
ret = unzGoToFirstFile(pkg);
- EditorProgress p("ltask",TTR("Loading Export Templates"),fc);
+ EditorProgress p("ltask", TTR("Loading Export Templates"), fc);
- fc=0;
+ fc = 0;
- while(ret==UNZ_OK) {
+ while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
- ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);
-
+ ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
- String file=fname;
+ String file = fname;
Vector<uint8_t> data;
data.resize(info.uncompressed_size);
//read
ret = unzOpenCurrentFile(pkg);
- ret = unzReadCurrentFile(pkg,data.ptr(),data.size());
+ ret = unzReadCurrentFile(pkg, data.ptr(), data.size());
unzCloseCurrentFile(pkg);
print_line(fname);
@@ -1326,14 +1250,14 @@ void EditorNode::_dialog_action(String p_file) {
}
*/
- file=file.get_file();
+ file = file.get_file();
- p.step(TTR("Importing:")+" "+file,fc);
+ p.step(TTR("Importing:") + " " + file, fc);
- FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_settings_path()+"/templates/"+file,FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_settings_path() + "/templates/" + file, FileAccess::WRITE);
ERR_CONTINUE(!f);
- f->store_buffer(data.ptr(),data.size());
+ f->store_buffer(data.ptr(), data.size());
memdelete(f);
@@ -1348,15 +1272,14 @@ void EditorNode::_dialog_action(String p_file) {
case RESOURCE_SAVE:
case RESOURCE_SAVE_AS: {
-
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
ERR_FAIL_COND(!current_obj->cast_to<Resource>())
RES current_res = RES(current_obj->cast_to<Resource>());
- save_resource_in_path(current_res,p_file);
+ save_resource_in_path(current_res, p_file);
} break;
case SETTINGS_LAYOUT_SAVE: {
@@ -1368,9 +1291,9 @@ void EditorNode::_dialog_action(String p_file) {
config.instance();
Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg"));
- if (err==ERR_CANT_OPEN) {
+ if (err == ERR_CANT_OPEN) {
config.instance(); // new config
- } else if (err!=OK) {
+ } else if (err != OK) {
show_warning(TTR("Error trying to save layout!"));
return;
}
@@ -1382,7 +1305,7 @@ void EditorNode::_dialog_action(String p_file) {
layout_dialog->hide();
_update_layouts_menu();
- if (p_file=="Default") {
+ if (p_file == "Default") {
show_warning(TTR("Default editor layout overridden."));
}
@@ -1396,7 +1319,7 @@ void EditorNode::_dialog_action(String p_file) {
config.instance();
Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg"));
- if (err!=OK || !config->has_section(p_file)) {
+ if (err != OK || !config->has_section(p_file)) {
show_warning(TTR("Layout name not found!"));
return;
}
@@ -1404,7 +1327,7 @@ void EditorNode::_dialog_action(String p_file) {
// erase
List<String> keys;
config->get_section_keys(p_file, &keys);
- for (List<String>::Element *E=keys.front();E;E=E->next()) {
+ for (List<String>::Element *E = keys.front(); E; E = E->next()) {
config->set_value(p_file, E->get(), Variant());
}
@@ -1413,14 +1336,14 @@ void EditorNode::_dialog_action(String p_file) {
layout_dialog->hide();
_update_layouts_menu();
- if (p_file=="Default") {
+ if (p_file == "Default") {
show_warning(TTR("Restored default layout to base settings."));
}
} break;
default: { //save scene?
- if (file->get_mode()==EditorFileDialog::MODE_SAVE_FILE) {
+ if (file->get_mode() == EditorFileDialog::MODE_SAVE_FILE) {
//_save_scene(p_file);
_save_scene_with_preview(p_file);
@@ -1430,10 +1353,7 @@ void EditorNode::_dialog_action(String p_file) {
}
}
-
-
-void EditorNode::push_item(Object *p_object,const String& p_property) {
-
+void EditorNode::push_item(Object *p_object, const String &p_property) {
if (!p_object) {
property_editor->edit(NULL);
@@ -1443,23 +1363,22 @@ void EditorNode::push_item(Object *p_object,const String& p_property) {
}
uint32_t id = p_object->get_instance_ID();
- if (id!=editor_history.get_current()) {
+ if (id != editor_history.get_current()) {
- if (p_property=="")
+ if (p_property == "")
editor_history.add_object(id);
else
- editor_history.add_object(id,p_property);
+ editor_history.add_object(id, p_property);
}
_edit_current();
-
}
void EditorNode::_select_history(int p_idx) {
//push it to the top, it is not correct, but it's more useful
- ObjectID id=editor_history.get_history_obj(p_idx);
- Object* obj=ObjectDB::get_instance(id);
+ ObjectID id = editor_history.get_history_obj(p_idx);
+ Object *obj = ObjectDB::get_instance(id);
if (!obj)
return;
push_item(obj);
@@ -1467,19 +1386,18 @@ void EditorNode::_select_history(int p_idx) {
void EditorNode::_prepare_history() {
- int history_to = MAX(0,editor_history.get_history_len()-25);
+ int history_to = MAX(0, editor_history.get_history_len() - 25);
editor_history_menu->get_popup()->clear();
- Ref<Texture> base_icon = gui_base->get_icon("Object","EditorIcons");
+ Ref<Texture> base_icon = gui_base->get_icon("Object", "EditorIcons");
Set<ObjectID> already;
- for(int i=editor_history.get_history_len()-1;i>=history_to;i--) {
+ for (int i = editor_history.get_history_len() - 1; i >= history_to; i--) {
-
- ObjectID id=editor_history.get_history_obj(i);
- Object* obj=ObjectDB::get_instance(id);
+ ObjectID id = editor_history.get_history_obj(i);
+ Object *obj = ObjectDB::get_instance(id);
if (!obj || already.has(id)) {
- if (history_to>0) {
+ if (history_to > 0) {
history_to--;
}
continue;
@@ -1487,32 +1405,32 @@ void EditorNode::_prepare_history() {
already.insert(id);
- Ref<Texture> icon = gui_base->get_icon("Object","EditorIcons");
- if (gui_base->has_icon(obj->get_class(),"EditorIcons"))
- icon=gui_base->get_icon(obj->get_class(),"EditorIcons");
+ Ref<Texture> icon = gui_base->get_icon("Object", "EditorIcons");
+ if (gui_base->has_icon(obj->get_class(), "EditorIcons"))
+ icon = gui_base->get_icon(obj->get_class(), "EditorIcons");
else
- icon=base_icon;
+ icon = base_icon;
String text;
if (obj->cast_to<Resource>()) {
- Resource *r=obj->cast_to<Resource>();
+ Resource *r = obj->cast_to<Resource>();
if (r->get_path().is_resource_file())
- text=r->get_path().get_file();
- else if (r->get_name()!=String()) {
- text=r->get_name();
+ text = r->get_path().get_file();
+ else if (r->get_name() != String()) {
+ text = r->get_name();
} else {
- text=r->get_class();
+ text = r->get_class();
}
} else if (obj->cast_to<Node>()) {
- text=obj->cast_to<Node>()->get_name();
+ text = obj->cast_to<Node>()->get_name();
} else {
- text=obj->get_class();
+ text = obj->get_class();
}
- if (i==editor_history.get_history_pos()) {
- text="["+text+"]";
+ if (i == editor_history.get_history_pos()) {
+ text = "[" + text + "]";
}
- editor_history_menu->get_popup()->add_icon_item(icon,text,i);
+ editor_history_menu->get_popup()->add_icon_item(icon, text, i);
}
}
@@ -1520,19 +1438,16 @@ void EditorNode::_property_editor_forward() {
if (editor_history.next())
_edit_current();
-
}
void EditorNode::_property_editor_back() {
if (editor_history.previous())
_edit_current();
-
}
-
void EditorNode::_imported(Node *p_node) {
-/*
+ /*
Node *scene = editor_data.get_edited_scene_root();
add_edited_scene(p_node);
@@ -1542,11 +1457,8 @@ void EditorNode::_imported(Node *p_node) {
memdelete(scene);
}
*/
-
-
}
-
void EditorNode::_hide_top_editors() {
_display_top_editors(false);
@@ -1558,32 +1470,29 @@ void EditorNode::_display_top_editors(bool p_display) {
editor_plugins_over->make_visible(p_display);
}
-void EditorNode::_set_top_editors(Vector<EditorPlugin*> p_editor_plugins_over) {
+void EditorNode::_set_top_editors(Vector<EditorPlugin *> p_editor_plugins_over) {
editor_plugins_over->set_plugins_list(p_editor_plugins_over);
}
-void EditorNode::_set_editing_top_editors(Object* p_current_object) {
+void EditorNode::_set_editing_top_editors(Object *p_current_object) {
editor_plugins_over->edit(p_current_object);
}
-
-
void EditorNode::_edit_current() {
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
- property_back->set_disabled( editor_history.is_at_begining() );
- property_forward->set_disabled( editor_history.is_at_end() );
+ property_back->set_disabled(editor_history.is_at_begining());
+ property_forward->set_disabled(editor_history.is_at_end());
- this->current=current_obj;
+ this->current = current_obj;
editor_path->update_path();
-
if (!current_obj) {
scene_tree_dock->set_selected(NULL);
- property_editor->edit( NULL );
+ property_editor->edit(NULL);
node_dock->set_node(NULL);
object_menu->set_disabled(true);
@@ -1600,29 +1509,24 @@ void EditorNode::_edit_current() {
if (is_resource) {
-
Resource *current_res = current_obj->cast_to<Resource>();
ERR_FAIL_COND(!current_res);
scene_tree_dock->set_selected(NULL);
- property_editor->edit( current_res );
+ property_editor->edit(current_res);
node_dock->set_node(NULL);
object_menu->set_disabled(false);
//resources_dock->add_resource(Ref<Resource>(current_res));
-
//top_pallete->set_current_tab(1);
} else if (is_node) {
- Node * current_node = current_obj->cast_to<Node>();
+ Node *current_node = current_obj->cast_to<Node>();
ERR_FAIL_COND(!current_node);
ERR_FAIL_COND(!current_node->is_inside_tree());
-
-
-
- property_editor->edit( current_node );
- node_dock->set_node( current_node );
+ property_editor->edit(current_node);
+ node_dock->set_node(current_node);
scene_tree_dock->set_selected(current_node);
object_menu->get_popup()->clear();
@@ -1630,40 +1534,37 @@ void EditorNode::_edit_current() {
} else {
- property_editor->edit( current_obj );
+ property_editor->edit(current_obj);
node_dock->set_node(NULL);
//scene_tree_dock->set_selected(current_node);
//object_menu->get_popup()->clear();
-
}
/* Take care of PLUGIN EDITOR */
-
EditorPlugin *main_plugin = editor_data.get_editor(current_obj);
if (main_plugin) {
// special case if use of external editor is true
- if (main_plugin->get_name() == "Script" && bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor"))){
+ if (main_plugin->get_name() == "Script" && bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor"))) {
main_plugin->edit(current_obj);
}
- else if (main_plugin!=editor_plugin_screen && (!ScriptEditor::get_singleton() || !ScriptEditor::get_singleton()->is_visible_in_tree() || ScriptEditor::get_singleton()->can_take_away_focus())) {
+ else if (main_plugin != editor_plugin_screen && (!ScriptEditor::get_singleton() || !ScriptEditor::get_singleton()->is_visible_in_tree() || ScriptEditor::get_singleton()->can_take_away_focus())) {
// update screen main_plugin
if (!changing_scene) {
if (editor_plugin_screen)
editor_plugin_screen->make_visible(false);
- editor_plugin_screen=main_plugin;
+ editor_plugin_screen = main_plugin;
editor_plugin_screen->edit(current_obj);
editor_plugin_screen->make_visible(true);
+ for (int i = 0; i < editor_table.size(); i++) {
- for(int i=0;i<editor_table.size();i++) {
-
- main_editor_buttons[i]->set_pressed(editor_table[i]==main_plugin);
+ main_editor_buttons[i]->set_pressed(editor_table[i] == main_plugin);
}
}
@@ -1671,10 +1572,9 @@ void EditorNode::_edit_current() {
editor_plugin_screen->edit(current_obj);
}
-
}
- Vector<EditorPlugin*> sub_plugins = editor_data.get_subeditors(current_obj);
+ Vector<EditorPlugin *> sub_plugins = editor_data.get_subeditors(current_obj);
if (!sub_plugins.empty()) {
_display_top_editors(false);
@@ -1686,9 +1586,8 @@ void EditorNode::_edit_current() {
} else if (!editor_plugins_over->get_plugins_list().empty()) {
_hide_top_editors();
-
}
-/*
+ /*
if (!plugin || plugin->has_main_screen()) {
// remove the OVER plugin if exists
if (editor_plugin_over)
@@ -1700,52 +1599,50 @@ void EditorNode::_edit_current() {
object_menu->set_disabled(false);
- PopupMenu *p=object_menu->get_popup();
+ PopupMenu *p = object_menu->get_popup();
p->clear();
- p->add_shortcut(ED_SHORTCUT("property_editor/copy_params",TTR("Copy Params")),OBJECT_COPY_PARAMS);
- p->add_shortcut(ED_SHORTCUT("property_editor/paste_params",TTR("Paste Params")),OBJECT_PASTE_PARAMS);
+ p->add_shortcut(ED_SHORTCUT("property_editor/copy_params", TTR("Copy Params")), OBJECT_COPY_PARAMS);
+ p->add_shortcut(ED_SHORTCUT("property_editor/paste_params", TTR("Paste Params")), OBJECT_PASTE_PARAMS);
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("property_editor/paste_resource",TTR("Paste Resource")),RESOURCE_PASTE);
+ p->add_shortcut(ED_SHORTCUT("property_editor/paste_resource", TTR("Paste Resource")), RESOURCE_PASTE);
if (is_resource) {
- p->add_shortcut(ED_SHORTCUT("property_editor/copy_resource",TTR("Copy Resource")),RESOURCE_COPY);
- p->add_shortcut(ED_SHORTCUT("property_editor/unref_resource",TTR("Make Built-In")),RESOURCE_UNREF);
+ p->add_shortcut(ED_SHORTCUT("property_editor/copy_resource", TTR("Copy Resource")), RESOURCE_COPY);
+ p->add_shortcut(ED_SHORTCUT("property_editor/unref_resource", TTR("Make Built-In")), RESOURCE_UNREF);
}
if (is_resource || is_node) {
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("property_editor/make_subresources_unique",TTR("Make Sub-Resources Unique")),OBJECT_UNIQUE_RESOURCES);
+ p->add_shortcut(ED_SHORTCUT("property_editor/make_subresources_unique", TTR("Make Sub-Resources Unique")), OBJECT_UNIQUE_RESOURCES);
p->add_separator();
- p->add_icon_shortcut(gui_base->get_icon("Help","EditorIcons"),ED_SHORTCUT("property_editor/open_help",TTR("Open in Help")),OBJECT_REQUEST_HELP);
+ p->add_icon_shortcut(gui_base->get_icon("Help", "EditorIcons"), ED_SHORTCUT("property_editor/open_help", TTR("Open in Help")), OBJECT_REQUEST_HELP);
}
List<MethodInfo> methods;
current_obj->get_method_list(&methods);
-
if (!methods.empty()) {
- bool found=false;
- List<MethodInfo>::Element *I=methods.front();
- int i=0;
- while(I) {
+ bool found = false;
+ List<MethodInfo>::Element *I = methods.front();
+ int i = 0;
+ while (I) {
- if (I->get().flags&METHOD_FLAG_EDITOR) {
+ if (I->get().flags & METHOD_FLAG_EDITOR) {
if (!found) {
p->add_separator();
- found=true;
+ found = true;
}
- p->add_item(I->get().name.capitalize(),OBJECT_METHOD_BASE+i);
+ p->add_item(I->get().name.capitalize(), OBJECT_METHOD_BASE + i);
}
i++;
- I=I->next();
+ I = I->next();
}
}
//p->add_separator();
//p->add_item("All Methods",OBJECT_CALL_METHOD);
-
update_keying();
}
@@ -1757,27 +1654,23 @@ void EditorNode::_resource_created() {
Resource *r = c->cast_to<Resource>();
ERR_FAIL_COND(!r);
- REF res( r );
+ REF res(r);
push_item(c);
-
}
-void EditorNode::_resource_selected(const RES& p_res,const String& p_property) {
-
+void EditorNode::_resource_selected(const RES &p_res, const String &p_property) {
if (p_res.is_null())
return;
- RES r=p_res;
- push_item(r.operator->(),p_property);
-
+ RES r = p_res;
+ push_item(r.operator->(), p_property);
}
+void EditorNode::_run(bool p_current, const String &p_custom) {
-void EditorNode::_run(bool p_current,const String& p_custom) {
-
- if (editor_run.get_status()==EditorRun::STATUS_PLAY) {
+ if (editor_run.get_status() == EditorRun::STATUS_PLAY) {
play_button->set_pressed(!_playing_edited);
play_scene_button->set_pressed(_playing_edited);
@@ -1785,24 +1678,23 @@ void EditorNode::_run(bool p_current,const String& p_custom) {
}
play_button->set_pressed(false);
- play_button->set_icon(gui_base->get_icon("MainPlay","EditorIcons"));
+ play_button->set_icon(gui_base->get_icon("MainPlay", "EditorIcons"));
//pause_button->set_pressed(false);
play_scene_button->set_pressed(false);
- play_scene_button->set_icon(gui_base->get_icon("PlayScene","EditorIcons"));
+ play_scene_button->set_icon(gui_base->get_icon("PlayScene", "EditorIcons"));
play_custom_scene_button->set_pressed(false);
- play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom","EditorIcons"));
+ play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom", "EditorIcons"));
String main_scene;
String run_filename;
String args;
-
- if (p_current || (editor_data.get_edited_scene_root() && p_custom==editor_data.get_edited_scene_root()->get_filename())) {
+ if (p_current || (editor_data.get_edited_scene_root() && p_custom == editor_data.get_edited_scene_root()->get_filename())) {
Node *scene = editor_data.get_edited_scene_root();
if (!scene) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("There is no defined scene to run."));
@@ -1810,27 +1702,26 @@ void EditorNode::_run(bool p_current,const String& p_custom) {
return;
}
- if (scene->get_filename()=="") {
- current_option=-1;
+ if (scene->get_filename() == "") {
+ current_option = -1;
//accept->get_cancel()->hide();
/**/
_menu_option_confirm(FILE_SAVE_BEFORE_RUN, false);
return;
-
}
- run_filename=scene->get_filename();
- } else if (p_custom!="") {
+ run_filename = scene->get_filename();
+ } else if (p_custom != "") {
run_filename = p_custom;
}
- if (run_filename=="") {
+ if (run_filename == "") {
//evidently, run the scene
- main_scene=GLOBAL_DEF("application/main_scene","");
- if (main_scene=="") {
+ main_scene = GLOBAL_DEF("application/main_scene", "");
+ if (main_scene == "") {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
pick_main_scene->set_text(TTR("No main scene has ever been defined, select one?\nYou can change it later in later in \"Project Settings\" under the 'application' category."));
pick_main_scene->popup_centered_minsize();
@@ -1839,28 +1730,24 @@ void EditorNode::_run(bool p_current,const String& p_custom) {
if (!FileAccess::exists(main_scene)) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
pick_main_scene->set_text(vformat(TTR("Selected scene '%s' does not exist, select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
pick_main_scene->popup_centered_minsize();
return;
-
}
- if (ResourceLoader::get_resource_type(main_scene)!="PackedScene") {
+ if (ResourceLoader::get_resource_type(main_scene) != "PackedScene") {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
pick_main_scene->set_text(vformat(TTR("Selected scene '%s' is not a scene file, select a valid one?\nYou can change it later in \"Project Settings\" under the 'application' category."), main_scene));
pick_main_scene->popup_centered_minsize();
return;
-
}
-
}
-
- if (bool(EDITOR_DEF("run/auto_save/save_before_running",true))) {
+ if (bool(EDITOR_DEF("run/auto_save/save_before_running", true))) {
if (unsaved_cache) {
@@ -1868,9 +1755,9 @@ void EditorNode::_run(bool p_current,const String& p_custom) {
if (scene) { //only autosave if there is a scene obviously
- if (scene->get_filename()=="") {
+ if (scene->get_filename() == "") {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Current scene was never saved, please save it prior to running."));
@@ -1899,34 +1786,32 @@ void EditorNode::_run(bool p_current,const String& p_custom) {
args = GlobalConfig::get_singleton()->get("editor/main_run_args");
- Error error = editor_run.run(run_filename,args,breakpoints);
+ Error error = editor_run.run(run_filename, args, breakpoints);
- if (error!=OK) {
+ if (error != OK) {
- current_option=-1;
+ current_option = -1;
//confirmation->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Could not start subprocess!"));
accept->popup_centered_minsize();
return;
-
}
emit_signal("play_pressed");
if (p_current) {
play_scene_button->set_pressed(true);
- play_scene_button->set_icon(gui_base->get_icon("Reload","EditorIcons"));
- } else if (p_custom!="") {
- run_custom_filename=p_custom;
+ play_scene_button->set_icon(gui_base->get_icon("Reload", "EditorIcons"));
+ } else if (p_custom != "") {
+ run_custom_filename = p_custom;
play_custom_scene_button->set_pressed(true);
- play_custom_scene_button->set_icon(gui_base->get_icon("Reload","EditorIcons"));
+ play_custom_scene_button->set_icon(gui_base->get_icon("Reload", "EditorIcons"));
} else {
play_button->set_pressed(true);
- play_button->set_icon(gui_base->get_icon("Reload","EditorIcons"));
+ play_button->set_icon(gui_base->get_icon("Reload", "EditorIcons"));
}
- _playing_edited=p_current;
-
+ _playing_edited = p_current;
}
void EditorNode::_cleanup_scene() {
@@ -1970,14 +1855,13 @@ void EditorNode::_cleanup_scene() {
#endif
}
-void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
+void EditorNode::_menu_option_confirm(int p_option, bool p_confirmed) {
//print_line("option "+itos(p_option)+" confirm "+itos(p_confirmed));
if (!p_confirmed) //this may be a hack..
- current_option=(MenuOptions)p_option;
+ current_option = (MenuOptions)p_option;
-
- switch( p_option ) {
+ switch (p_option) {
case FILE_NEW_SCENE: {
// TODO: Drop such obsolete commented code
@@ -1990,37 +1874,33 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
break;
}*/
-
int idx = editor_data.add_edited_scene(-1);
_scene_tab_changed(idx);
editor_data.clear_editor_states();
//_cleanup_scene();
-
} break;
case FILE_NEW_INHERITED_SCENE:
case FILE_OPEN_SCENE: {
-
//print_tree();
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
//not for now?
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("PackedScene",&extensions);
+ ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
-
//file->set_current_path(current_path);
Node *scene = editor_data.get_edited_scene_root();
if (scene) {
file->set_current_path(scene->get_filename());
};
- file->set_title(p_option==FILE_OPEN_SCENE?TTR("Open Scene"):TTR("Open Base Scene"));
+ file->set_title(p_option == FILE_OPEN_SCENE ? TTR("Open Scene") : TTR("Open Base Scene"));
file->popup_centered_ratio();
} break;
@@ -2032,7 +1912,6 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case FILE_QUICK_OPEN_SCRIPT: {
-
quick_open->popup("Script", true);
quick_open->set_title(TTR("Quick Open Script.."));
@@ -2045,7 +1924,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (previous_scenes.empty())
break;
- opening_prev=true;
+ opening_prev = true;
open_request(previous_scenes.back()->get());
} break;
@@ -2061,8 +1940,6 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
_remove_edited_scene();
-
-
} break;
case SCENE_TAB_CLOSE: {
_remove_scene(tab_closing);
@@ -2071,9 +1948,8 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case FILE_SAVE_SCENE: {
-
Node *scene = editor_data.get_edited_scene_root();
- if (scene && scene->get_filename()!="") {
+ if (scene && scene->get_filename() != "") {
// save in background if in the script editor
if (_get_current_main_editor() == EDITOR_SCRIPT) {
@@ -2091,7 +1967,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (!scene) {
- current_option=-1;
+ current_option = -1;
//confirmation->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text("This operation can't be done without a tree root.");
@@ -2101,23 +1977,22 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
file->set_mode(EditorFileDialog::MODE_SAVE_FILE);
-
List<String> extensions;
- Ref<PackedScene> sd = memnew( PackedScene );
- ResourceSaver::get_recognized_extensions(sd,&extensions);
+ Ref<PackedScene> sd = memnew(PackedScene);
+ ResourceSaver::get_recognized_extensions(sd, &extensions);
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
//file->set_current_path(current_path);
- if (scene->get_filename()!="") {
+ if (scene->get_filename() != "") {
file->set_current_path(scene->get_filename());
if (extensions.size()) {
- String ext=scene->get_filename().get_extension().to_lower();
- if (extensions.find(ext)==NULL) {
- file->set_current_path(scene->get_filename().replacen("."+ext,"."+extensions.front()->get()));
+ String ext = scene->get_filename().get_extension().to_lower();
+ if (extensions.find(ext) == NULL) {
+ file->set_current_path(scene->get_filename().replacen("." + ext, "." + extensions.front()->get()));
}
}
} else {
@@ -2125,10 +2000,9 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
String existing;
if (extensions.size()) {
String root_name(get_edited_scene()->get_name());
- existing=root_name+"."+extensions.front()->get().to_lower();
+ existing = root_name + "." + extensions.front()->get().to_lower();
}
file->set_current_path(existing);
-
}
file->popup_centered_ratio();
file->set_title(TTR("Save Scene As.."));
@@ -2138,14 +2012,14 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case FILE_SAVE_ALL_SCENES: {
for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
Node *scene = editor_data.get_edited_scene_root(i);
- if (scene && scene->get_filename()!="") {
+ if (scene && scene->get_filename() != "") {
// save in background if in the script editor
if (i != editor_data.get_edited_scene() || _get_current_main_editor() == EDITOR_SCRIPT) {
_save_scene(scene->get_filename(), i);
} else {
_save_scene_with_preview(scene->get_filename());
}
- }// else: ignore new scenes
+ } // else: ignore new scenes
}
} break;
case FILE_SAVE_BEFORE_RUN: {
@@ -2207,7 +2081,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (!editor_data.get_edited_scene_root()) {
- current_option=-1;
+ current_option = -1;
//confirmation->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text("This operation can't be done without a scene.");
@@ -2216,11 +2090,11 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
}
List<String> extensions;
- Ref<MeshLibrary> ml( memnew( MeshLibrary) );
- ResourceSaver::get_recognized_extensions(ml,&extensions);
+ Ref<MeshLibrary> ml(memnew(MeshLibrary));
+ ResourceSaver::get_recognized_extensions(ml, &extensions);
file_export_lib->clear_filters();
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- file_export_lib->add_filter("*."+E->get());
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file_export_lib->add_filter("*." + E->get());
}
file_export_lib->popup_centered_ratio();
@@ -2230,11 +2104,11 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case FILE_EXPORT_TILESET: {
List<String> extensions;
- Ref<TileSet> ml( memnew( TileSet) );
- ResourceSaver::get_recognized_extensions(ml,&extensions);
+ Ref<TileSet> ml(memnew(TileSet));
+ ResourceSaver::get_recognized_extensions(ml, &extensions);
file_export_lib->clear_filters();
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- file_export_lib->add_filter("*."+E->get());
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file_export_lib->add_filter("*." + E->get());
}
file_export_lib->popup_centered_ratio();
@@ -2252,7 +2126,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (!editor_data.get_edited_scene_root()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text("This operation can't be done without a selected node.");
@@ -2266,19 +2140,17 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case FILE_QUIT: {
-
if (!p_confirmed) {
confirmation->get_ok()->set_text(TTR("Quit"));
//confirmation->get_cancel()->show();
confirmation->set_text(TTR("Exit the editor?"));
- confirmation->popup_centered(Size2(180,70)*EDSCALE);
+ confirmation->popup_centered(Size2(180, 70) * EDSCALE);
break;
}
-
- _menu_option_confirm(RUN_STOP,true);
- exiting=true;
+ _menu_option_confirm(RUN_STOP, true);
+ exiting = true;
get_tree()->quit();
} break;
@@ -2291,42 +2163,39 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
confirmation->set_text(TTR("Current scene not saved. Open anyway?"));
confirmation->popup_centered_minsize();
break;
-
}
- bool oprev=opening_prev;
+ bool oprev = opening_prev;
Error err = load_scene(external_file);
if (err == OK && oprev) {
previous_scenes.pop_back();
- opening_prev=false;
+ opening_prev = false;
}
} break;
case EDIT_UNDO: {
-
-
- if (Input::get_singleton()->get_mouse_button_mask()&0x7) {
+ if (Input::get_singleton()->get_mouse_button_mask() & 0x7) {
print_line("no because state");
break; // can't undo while mouse buttons are pressed
}
- String action = editor_data.get_undo_redo().get_current_action_name();
- if (action!="")
- log->add_message("UNDO: "+action);
+ String action = editor_data.get_undo_redo().get_current_action_name();
+ if (action != "")
+ log->add_message("UNDO: " + action);
editor_data.get_undo_redo().undo();
} break;
case EDIT_REDO: {
- if (Input::get_singleton()->get_mouse_button_mask()&0x7)
+ if (Input::get_singleton()->get_mouse_button_mask() & 0x7)
break; // can't redo while mouse buttons are pressed
editor_data.get_undo_redo().redo();
- String action = editor_data.get_undo_redo().get_current_action_name();
- if (action!="")
- log->add_message("REDO: "+action);
+ String action = editor_data.get_undo_redo().get_current_action_name();
+ if (action != "")
+ log->add_message("REDO: " + action);
} break;
case TOOLS_ORPHAN_RESOURCES: {
@@ -2343,7 +2212,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
String filename = scene->get_filename();
- if (filename==String()) {
+ if (filename == String()) {
show_warning(TTR("Can't reload a scene that was never saved."));
break;
}
@@ -2355,7 +2224,6 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
break;
}
-
int cur_idx = editor_data.get_edited_scene();
_remove_edited_scene();
Error err = load_scene(filename);
@@ -2429,9 +2297,8 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case RESOURCE_SAVE: {
-
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
ERR_FAIL_COND(!current_obj->cast_to<Resource>())
@@ -2443,7 +2310,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case RESOURCE_SAVE_AS: {
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
ERR_FAIL_COND(!current_obj->cast_to<Resource>())
@@ -2455,7 +2322,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case RESOURCE_UNREF: {
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
ERR_FAIL_COND(!current_obj->cast_to<Resource>())
@@ -2466,7 +2333,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
case RESOURCE_COPY: {
uint32_t current = editor_history.get_current();
- Object *current_obj = current>0 ? ObjectDB::get_instance(current) : NULL;
+ Object *current_obj = current > 0 ? ObjectDB::get_instance(current) : NULL;
ERR_FAIL_COND(!current_obj->cast_to<Resource>())
@@ -2479,7 +2346,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
RES r = EditorSettings::get_singleton()->get_resource_clipboard();
if (r.is_valid()) {
- push_item(EditorSettings::get_singleton()->get_resource_clipboard().ptr(),String());
+ push_item(EditorSettings::get_singleton()->get_resource_clipboard().ptr(), String());
}
} break;
@@ -2487,10 +2354,9 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (current) {
_editor_select(EDITOR_SCRIPT);
- emit_signal("request_help",current->get_class());
+ emit_signal("request_help", current->get_class());
}
-
} break;
case OBJECT_COPY_PARAMS: {
@@ -2511,10 +2377,10 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (current) {
List<PropertyInfo> props;
current->get_property_list(&props);
- Map<RES,RES> duplicates;
- for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ Map<RES, RES> duplicates;
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
Variant v = current->get(E->get().name);
@@ -2526,16 +2392,14 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
if (res.is_valid()) {
if (!duplicates.has(res)) {
- duplicates[res]=res->duplicate();
+ duplicates[res] = res->duplicate();
}
- res=duplicates[res];
+ res = duplicates[res];
- current->set(E->get().name,res);
+ current->set(E->get().name, res);
}
-
}
}
-
}
}
@@ -2546,42 +2410,42 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case RUN_PLAY: {
- _menu_option_confirm(RUN_STOP,true);
+ _menu_option_confirm(RUN_STOP, true);
_call_build();
_run(false);
} break;
case RUN_PLAY_CUSTOM_SCENE: {
- if (run_custom_filename.empty() || editor_run.get_status()==EditorRun::STATUS_STOP) {
- _menu_option_confirm(RUN_STOP,true);
- quick_run->popup("PackedScene",true);
+ if (run_custom_filename.empty() || editor_run.get_status() == EditorRun::STATUS_STOP) {
+ _menu_option_confirm(RUN_STOP, true);
+ quick_run->popup("PackedScene", true);
quick_run->set_title(TTR("Quick Run Scene.."));
play_custom_scene_button->set_pressed(false);
} else {
- String last_custom_scene=run_custom_filename;
- _menu_option_confirm(RUN_STOP,true);
- _run(false,last_custom_scene);
+ String last_custom_scene = run_custom_filename;
+ _menu_option_confirm(RUN_STOP, true);
+ _run(false, last_custom_scene);
}
} break;
case RUN_STOP: {
- if (editor_run.get_status()==EditorRun::STATUS_STOP)
+ if (editor_run.get_status() == EditorRun::STATUS_STOP)
break;
editor_run.stop();
run_custom_filename.clear();
play_button->set_pressed(false);
- play_button->set_icon(gui_base->get_icon("MainPlay","EditorIcons"));
+ play_button->set_icon(gui_base->get_icon("MainPlay", "EditorIcons"));
play_scene_button->set_pressed(false);
- play_scene_button->set_icon(gui_base->get_icon("PlayScene","EditorIcons"));
+ play_scene_button->set_icon(gui_base->get_icon("PlayScene", "EditorIcons"));
play_custom_scene_button->set_pressed(false);
- play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom","EditorIcons"));
+ play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom", "EditorIcons"));
//pause_button->set_pressed(false);
if (bool(EDITOR_DEF("run/output/always_close_output_on_stop", true))) {
- for(int i=0;i<bottom_panel_items.size();i++) {
- if (bottom_panel_items[i].control==log) {
- _bottom_panel_switch(false,i);
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
+ if (bottom_panel_items[i].control == log) {
+ _bottom_panel_switch(false, i);
break;
}
}
@@ -2590,19 +2454,19 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case RUN_PLAY_SCENE: {
- _menu_option_confirm(RUN_STOP,true);
+ _menu_option_confirm(RUN_STOP, true);
_call_build();
_run(true);
} break;
case RUN_PLAY_NATIVE: {
- bool autosave = EDITOR_DEF("run/auto_save/save_before_running",true);
+ bool autosave = EDITOR_DEF("run/auto_save/save_before_running", true);
if (autosave) {
_menu_option_confirm(FILE_SAVE_ALL_SCENES, false);
}
- if (run_native->is_deploy_debug_remote_enabled()){
- _menu_option_confirm(RUN_STOP,true);
+ if (run_native->is_deploy_debug_remote_enabled()) {
+ _menu_option_confirm(RUN_STOP, true);
_call_build();
emit_signal("play_pressed");
editor_run.run_native_notify();
@@ -2625,8 +2489,8 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
break;
}
- _menu_option_confirm(RUN_STOP,true);
- exiting=true;
+ _menu_option_confirm(RUN_STOP, true);
+ exiting = true;
get_tree()->quit();
String exec = OS::get_singleton()->get_executable_path();
@@ -2635,14 +2499,14 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
args.push_back(exec.get_base_dir());
args.push_back("-pm");
- OS::ProcessID pid=0;
- Error err = OS::get_singleton()->execute(exec,args,false,&pid);
+ OS::ProcessID pid = 0;
+ Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
} break;
case RUN_FILE_SERVER: {
//file_server
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_FILE_SERVER));
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_FILE_SERVER));
if (ischecked) {
file_server->stop();
@@ -2656,14 +2520,14 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
//debug_button->get_popup()->set_item_text( debug_button->get_popup()->get_item_index(RUN_FILE_SERVER),"Disable File Server");
}
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_FILE_SERVER),!ischecked);
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_FILE_SERVER), !ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_file_server", !ischecked);
} break;
case RUN_LIVE_DEBUG: {
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_LIVE_DEBUG));
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_LIVE_DEBUG));
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_LIVE_DEBUG),!ischecked);
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_LIVE_DEBUG), !ischecked);
ScriptEditor::get_singleton()->get_debugger()->set_live_debugging(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_live_debug", !ischecked);
@@ -2678,16 +2542,16 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;*/
case RUN_DEPLOY_REMOTE_DEBUG: {
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG));
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG),!ischecked);
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG));
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_DEPLOY_REMOTE_DEBUG), !ischecked);
run_native->set_deploy_debug_remote(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_deploy_remote_debug", !ischecked);
} break;
case RUN_DEBUG_COLLISONS: {
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_DEBUG_COLLISONS));
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_DEBUG_COLLISONS),!ischecked);
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_DEBUG_COLLISONS));
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_DEBUG_COLLISONS), !ischecked);
run_native->set_debug_collisions(!ischecked);
editor_run.set_debug_collisions(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_debug_collisons", !ischecked);
@@ -2695,8 +2559,8 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case RUN_DEBUG_NAVIGATION: {
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION));
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION),!ischecked);
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION));
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_DEBUG_NAVIGATION), !ischecked);
run_native->set_debug_navigation(!ischecked);
editor_run.set_debug_navigation(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_debug_navigation", !ischecked);
@@ -2704,9 +2568,8 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case RUN_RELOAD_SCRIPTS: {
-
- bool ischecked = debug_button->get_popup()->is_item_checked( debug_button->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS));
- debug_button->get_popup()->set_item_checked( debug_button->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS),!ischecked);
+ bool ischecked = debug_button->get_popup()->is_item_checked(debug_button->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS));
+ debug_button->get_popup()->set_item_checked(debug_button->get_popup()->get_item_index(RUN_RELOAD_SCRIPTS), !ischecked);
ScriptEditor::get_singleton()->set_live_auto_reload_running_scripts(!ischecked);
EditorSettings::get_singleton()->set_project_metadata("debug_options", "run_reload_scripts", !ischecked);
@@ -2714,20 +2577,20 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case SETTINGS_UPDATE_ALWAYS: {
- update_menu->get_popup()->set_item_checked(0,true);
- update_menu->get_popup()->set_item_checked(1,false);
+ update_menu->get_popup()->set_item_checked(0, true);
+ update_menu->get_popup()->set_item_checked(1, false);
OS::get_singleton()->set_low_processor_usage_mode(false);
} break;
case SETTINGS_UPDATE_CHANGES: {
- update_menu->get_popup()->set_item_checked(0,false);
- update_menu->get_popup()->set_item_checked(1,true);
+ update_menu->get_popup()->set_item_checked(0, false);
+ update_menu->get_popup()->set_item_checked(1, true);
OS::get_singleton()->set_low_processor_usage_mode(true);
} break;
- case SETTINGS_UPDATE_SPINNER_HIDE: {
- update_menu->set_icon(gui_base->get_icon("Collapse","EditorIcons"));
- update_menu->get_popup()->toggle_item_checked(3);
- } break;
+ case SETTINGS_UPDATE_SPINNER_HIDE: {
+ update_menu->set_icon(gui_base->get_icon("Collapse", "EditorIcons"));
+ update_menu->get_popup()->toggle_item_checked(3);
+ } break;
case SETTINGS_PREFERENCES: {
settings_config_dialog->popup_edit_settings();
@@ -2738,31 +2601,27 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case SETTINGS_LOAD_EXPORT_TEMPLATES: {
-
file_templates->popup_centered_ratio();
} break;
case SETTINGS_TOGGLE_FULLSCREN: {
- OS::get_singleton()->set_window_fullscreen( !OS::get_singleton()->is_window_fullscreen() );
-
+ OS::get_singleton()->set_window_fullscreen(!OS::get_singleton()->is_window_fullscreen());
} break;
case SETTINGS_PICK_MAIN_SCENE: {
-
//print_tree();
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
//not for now?
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("PackedScene",&extensions);
+ ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
-
//file->set_current_path(current_path);
Node *scene = editor_data.get_edited_scene_root();
if (scene) {
@@ -2774,7 +2633,7 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case SETTINGS_ABOUT: {
- about->popup_centered_minsize(Size2(500,130)*EDSCALE);
+ about->popup_centered_minsize(Size2(500, 130) * EDSCALE);
} break;
case SOURCES_REIMPORT: {
@@ -2782,12 +2641,10 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
} break;
case DEPENDENCY_LOAD_CHANGED_IMAGES: {
-
-
} break;
case DEPENDENCY_UPDATE_IMPORTED: {
-/*
+ /*
bool editing_changed = _find_editing_changed_scene(get_edited_scene());
import_reload_fn="";
@@ -2829,28 +2686,25 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
*/
-
} break;
default: {
- if (p_option>=OBJECT_METHOD_BASE) {
+ if (p_option >= OBJECT_METHOD_BASE) {
ERR_FAIL_COND(!current);
- int idx=p_option-OBJECT_METHOD_BASE;
+ int idx = p_option - OBJECT_METHOD_BASE;
List<MethodInfo> methods;
current->get_method_list(&methods);
- ERR_FAIL_INDEX( idx, methods.size() );
- String name=methods[idx].name;
+ ERR_FAIL_INDEX(idx, methods.size());
+ String name = methods[idx].name;
if (current)
current->call(name);
- } else if (p_option>=IMPORT_PLUGIN_BASE) {
-
-
+ } else if (p_option >= IMPORT_PLUGIN_BASE) {
}
}
}
@@ -2858,72 +2712,64 @@ void EditorNode::_menu_option_confirm(int p_option,bool p_confirmed) {
void EditorNode::_update_debug_options() {
- bool check_deploy_remote = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_deploy_remote_debug", false);
- bool check_file_server = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_file_server", false);
- bool check_debug_collisons = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false);
+ bool check_deploy_remote = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_deploy_remote_debug", false);
+ bool check_file_server = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_file_server", false);
+ bool check_debug_collisons = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_collisons", false);
bool check_debug_navigation = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_debug_navigation", false);
- bool check_live_debug = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_live_debug", false);
- bool check_reload_scripts = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_reload_scripts", false);
+ bool check_live_debug = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_live_debug", false);
+ bool check_reload_scripts = EditorSettings::get_singleton()->get_project_metadata("debug_options", "run_reload_scripts", false);
- if (check_deploy_remote) _menu_option_confirm(RUN_DEPLOY_REMOTE_DEBUG, true);
- if (check_file_server) _menu_option_confirm(RUN_FILE_SERVER, true);
- if (check_debug_collisons) _menu_option_confirm(RUN_DEBUG_COLLISONS, true);
+ if (check_deploy_remote) _menu_option_confirm(RUN_DEPLOY_REMOTE_DEBUG, true);
+ if (check_file_server) _menu_option_confirm(RUN_FILE_SERVER, true);
+ if (check_debug_collisons) _menu_option_confirm(RUN_DEBUG_COLLISONS, true);
if (check_debug_navigation) _menu_option_confirm(RUN_DEBUG_NAVIGATION, true);
- if (check_live_debug) _menu_option_confirm(RUN_LIVE_DEBUG, true);
- if (check_reload_scripts) _menu_option_confirm(RUN_RELOAD_SCRIPTS, true);
-
+ if (check_live_debug) _menu_option_confirm(RUN_LIVE_DEBUG, true);
+ if (check_reload_scripts) _menu_option_confirm(RUN_RELOAD_SCRIPTS, true);
}
-Control* EditorNode::get_viewport() {
+Control *EditorNode::get_viewport() {
return viewport;
}
-
-
void EditorNode::_editor_select(int p_which) {
- static bool selecting=false;
+ static bool selecting = false;
if (selecting || changing_scene)
return;
- selecting=true;
+ selecting = true;
+ ERR_FAIL_INDEX(p_which, editor_table.size());
- ERR_FAIL_INDEX(p_which,editor_table.size());
-
- for(int i=0;i<main_editor_buttons.size();i++) {
- main_editor_buttons[i]->set_pressed(i==p_which);
+ for (int i = 0; i < main_editor_buttons.size(); i++) {
+ main_editor_buttons[i]->set_pressed(i == p_which);
}
- selecting=false;
-
+ selecting = false;
EditorPlugin *new_editor = editor_table[p_which];
ERR_FAIL_COND(!new_editor);
- if (editor_plugin_screen==new_editor)
+ if (editor_plugin_screen == new_editor)
return;
if (editor_plugin_screen) {
editor_plugin_screen->make_visible(false);
}
- editor_plugin_screen=new_editor;
+ editor_plugin_screen = new_editor;
editor_plugin_screen->make_visible(true);
editor_plugin_screen->selected_notify();
-
-
}
void EditorNode::add_editor_plugin(EditorPlugin *p_editor) {
-
if (p_editor->has_main_screen()) {
- ToolButton *tb = memnew( ToolButton );
+ ToolButton *tb = memnew(ToolButton);
tb->set_toggle_mode(true);
- tb->connect("pressed",singleton,"_editor_select",varray(singleton->main_editor_buttons.size()));
+ tb->connect("pressed", singleton, "_editor_select", varray(singleton->main_editor_buttons.size()));
tb->set_text(p_editor->get_name());
singleton->main_editor_buttons.push_back(tb);
singleton->main_editor_button_vb->add_child(tb);
@@ -2931,24 +2777,23 @@ void EditorNode::add_editor_plugin(EditorPlugin *p_editor) {
singleton->distraction_free->raise();
}
- singleton->editor_data.add_editor_plugin( p_editor );
+ singleton->editor_data.add_editor_plugin(p_editor);
singleton->add_child(p_editor);
}
-
void EditorNode::remove_editor_plugin(EditorPlugin *p_editor) {
if (p_editor->has_main_screen()) {
- for(int i=0;i<singleton->main_editor_buttons.size();i++) {
+ for (int i = 0; i < singleton->main_editor_buttons.size(); i++) {
- if (p_editor->get_name()==singleton->main_editor_buttons[i]->get_text()) {
+ if (p_editor->get_name() == singleton->main_editor_buttons[i]->get_text()) {
if (singleton->main_editor_buttons[i]->is_pressed()) {
singleton->_editor_select(EDITOR_SCRIPT);
}
- memdelete( singleton->main_editor_buttons[i] );
+ memdelete(singleton->main_editor_buttons[i]);
singleton->main_editor_buttons.remove(i);
break;
@@ -2962,12 +2807,9 @@ void EditorNode::remove_editor_plugin(EditorPlugin *p_editor) {
p_editor->clear();
singleton->editor_plugins_over->get_plugins_list().erase(p_editor);
singleton->remove_child(p_editor);
- singleton->editor_data.remove_editor_plugin( p_editor );
-
+ singleton->editor_data.remove_editor_plugin(p_editor);
}
-
-
void EditorNode::_update_addon_config() {
if (_initializing_addons)
@@ -2975,21 +2817,20 @@ void EditorNode::_update_addon_config() {
Vector<String> enabled_addons;
- for(Map<String,EditorPlugin*>::Element *E=plugin_addons.front();E;E=E->next()) {
+ for (Map<String, EditorPlugin *>::Element *E = plugin_addons.front(); E; E = E->next()) {
enabled_addons.push_back(E->key());
}
- if (enabled_addons.size()==0) {
- GlobalConfig::get_singleton()->set("editor_plugins/enabled",Variant());
+ if (enabled_addons.size() == 0) {
+ GlobalConfig::get_singleton()->set("editor_plugins/enabled", Variant());
} else {
- GlobalConfig::get_singleton()->set("editor_plugins/enabled",enabled_addons);
+ GlobalConfig::get_singleton()->set("editor_plugins/enabled", enabled_addons);
}
project_settings->queue_save();
-
}
-void EditorNode::set_addon_plugin_enabled(const String& p_addon,bool p_enabled) {
+void EditorNode::set_addon_plugin_enabled(const String &p_addon, bool p_enabled) {
ERR_FAIL_COND(p_enabled && plugin_addons.has(p_addon));
ERR_FAIL_COND(!p_enabled && !plugin_addons.has(p_addon));
@@ -3004,75 +2845,68 @@ void EditorNode::set_addon_plugin_enabled(const String& p_addon,bool p_enabled)
return;
}
-
Ref<ConfigFile> cf;
cf.instance();
- String addon_path = "res://addons/"+p_addon+"/plugin.cfg";
+ String addon_path = "res://addons/" + p_addon + "/plugin.cfg";
Error err = cf->load(addon_path);
- if (err!=OK) {
- show_warning("Unable to enable addon plugin at: '"+addon_path+"' parsing of config failed.");
+ if (err != OK) {
+ show_warning("Unable to enable addon plugin at: '" + addon_path + "' parsing of config failed.");
return;
}
- if (!cf->has_section_key("plugin","script")) {
- show_warning("Unable to find script field for addon plugin at: 'res://addons/"+p_addon+"''.");
+ if (!cf->has_section_key("plugin", "script")) {
+ show_warning("Unable to find script field for addon plugin at: 'res://addons/" + p_addon + "''.");
return;
}
- String path = cf->get_value("plugin","script");
- path="res://addons/"+p_addon+"/"+path;
+ String path = cf->get_value("plugin", "script");
+ path = "res://addons/" + p_addon + "/" + path;
Ref<Script> script = ResourceLoader::load(path);
-
if (script.is_null()) {
- show_warning("Unable to load addon script from path: '"+path+"'.");
+ show_warning("Unable to load addon script from path: '" + path + "'.");
return;
}
//could check inheritance..
- if (String(script->get_instance_base_type())!="EditorPlugin") {
- show_warning("Unable to load addon script from path: '"+path+"' Base type is not EditorPlugin.");
+ if (String(script->get_instance_base_type()) != "EditorPlugin") {
+ show_warning("Unable to load addon script from path: '" + path + "' Base type is not EditorPlugin.");
return;
}
if (!script->is_tool()) {
- show_warning("Unable to load addon script from path: '"+path+"' Script is does not support tool mode.");
+ show_warning("Unable to load addon script from path: '" + path + "' Script is does not support tool mode.");
return;
}
- EditorPlugin *ep = memnew( EditorPlugin );
+ EditorPlugin *ep = memnew(EditorPlugin);
ep->set_script(script.get_ref_ptr());
- plugin_addons[p_addon]=ep;
+ plugin_addons[p_addon] = ep;
add_editor_plugin(ep);
_update_addon_config();
-
-
}
-bool EditorNode::is_addon_plugin_enabled(const String& p_addon) const {
+bool EditorNode::is_addon_plugin_enabled(const String &p_addon) const {
return plugin_addons.has(p_addon);
}
-
void EditorNode::_remove_edited_scene() {
int new_index = editor_data.get_edited_scene();
- int old_index=new_index;
+ int old_index = new_index;
- if (new_index>0) {
- new_index=new_index-1;
- } else if (editor_data.get_edited_scene_count()>1) {
- new_index=1;
+ if (new_index > 0) {
+ new_index = new_index - 1;
+ } else if (editor_data.get_edited_scene_count() > 1) {
+ new_index = 1;
} else {
editor_data.add_edited_scene(-1);
- new_index=1;
+ new_index = 1;
}
-
-
- if (editor_data.get_scene_path(old_index)!=String()) {
+ if (editor_data.get_scene_path(old_index) != String()) {
ScriptEditor::get_singleton()->close_builtin_scripts_from_scene(editor_data.get_scene_path(old_index));
}
_scene_tab_changed(new_index);
@@ -3096,8 +2930,7 @@ void EditorNode::_remove_scene(int index) {
if (editor_data.get_edited_scene() == index) {
//Scene to remove is current scene
_remove_edited_scene();
- }
- else {
+ } else {
// Scene to remove is not active scene
editor_data.remove_scene(index);
}
@@ -3106,9 +2939,8 @@ void EditorNode::_remove_scene(int index) {
void EditorNode::set_edited_scene(Node *p_scene) {
if (get_editor_data().get_edited_scene_root()) {
- if (get_editor_data().get_edited_scene_root()->get_parent()==scene_root)
+ if (get_editor_data().get_edited_scene_root()->get_parent() == scene_root)
scene_root->remove_child(get_editor_data().get_edited_scene_root());
-
}
get_editor_data().set_edited_scene_root(p_scene);
@@ -3119,19 +2951,15 @@ void EditorNode::set_edited_scene(Node *p_scene) {
get_tree()->set_edited_scene_root(p_scene);
if (p_scene) {
- if (p_scene->get_parent()!=scene_root)
+ if (p_scene->get_parent() != scene_root)
scene_root->add_child(p_scene);
-
}
}
-
-
-
int EditorNode::_get_current_main_editor() {
- for(int i=0;i<editor_table.size();i++) {
- if (editor_table[i]==editor_plugin_screen)
+ for (int i = 0; i < editor_table.size(); i++) {
+ if (editor_table[i] == editor_plugin_screen)
return i;
}
@@ -3141,22 +2969,22 @@ int EditorNode::_get_current_main_editor() {
Dictionary EditorNode::_get_main_scene_state() {
Dictionary state;
- state["main_tab"]=_get_current_main_editor();
- state["scene_tree_offset"]=scene_tree_dock->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
- state["property_edit_offset"]=get_property_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
- state["saved_version"]=saved_version;
- state["node_filter"]=scene_tree_dock->get_filter();
+ state["main_tab"] = _get_current_main_editor();
+ state["scene_tree_offset"] = scene_tree_dock->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
+ state["property_edit_offset"] = get_property_editor()->get_scene_tree()->get_vscroll_bar()->get_value();
+ state["saved_version"] = saved_version;
+ state["node_filter"] = scene_tree_dock->get_filter();
//print_line(" getting main tab: "+itos(state["main_tab"]));
return state;
}
-void EditorNode::_set_main_scene_state(Dictionary p_state,Node* p_for_scene) {
+void EditorNode::_set_main_scene_state(Dictionary p_state, Node *p_for_scene) {
- if (get_edited_scene()!=p_for_scene && p_for_scene!=NULL)
+ if (get_edited_scene() != p_for_scene && p_for_scene != NULL)
return; //not for this scene
//print_line("set current 7 ");
- changing_scene=false;
+ changing_scene = false;
#if 0
if (p_state.has("main_tab")) {
@@ -3183,31 +3011,28 @@ void EditorNode::_set_main_scene_state(Dictionary p_state,Node* p_for_scene) {
if (get_edited_scene()) {
- int current=-1;
- for(int i=0;i<editor_table.size();i++) {
- if (editor_plugin_screen==editor_table[i]) {
- current=i;
+ int current = -1;
+ for (int i = 0; i < editor_table.size(); i++) {
+ if (editor_plugin_screen == editor_table[i]) {
+ current = i;
break;
}
}
- if (current<2) {
+ if (current < 2) {
//use heuristic instead
- int n2d=0,n3d=0;
- _find_node_types(get_edited_scene(),n2d,n3d);
- if (n2d>n3d) {
+ int n2d = 0, n3d = 0;
+ _find_node_types(get_edited_scene(), n2d, n3d);
+ if (n2d > n3d) {
_editor_select(EDITOR_2D);
- } else if (n3d>n2d) {
+ } else if (n3d > n2d) {
_editor_select(EDITOR_3D);
-
}
}
-
}
#endif
-
if (p_state.has("scene_tree_offset"))
scene_tree_dock->get_tree_editor()->get_scene_tree()->get_vscroll_bar()->set_value(p_state["scene_tree_offset"]);
if (p_state.has("property_edit_offset"))
@@ -3221,16 +3046,15 @@ void EditorNode::_set_main_scene_state(Dictionary p_state,Node* p_for_scene) {
//changing_scene=true; //avoid script change from opening editor
ScriptEditor::get_singleton()->get_debugger()->update_live_edit_root();
- ScriptEditor::get_singleton()->set_scene_root_script( editor_data.get_scene_root_script(editor_data.get_edited_scene()) );
+ ScriptEditor::get_singleton()->set_scene_root_script(editor_data.get_scene_root_script(editor_data.get_edited_scene()));
editor_data.notify_edited_scene_changed();
//changing_scene=false;
-
}
void EditorNode::set_current_version(uint64_t p_version) {
- saved_version=p_version;
+ saved_version = p_version;
editor_data.set_edited_scene_version(p_version);
}
@@ -3249,13 +3073,12 @@ void EditorNode::set_current_scene(int p_idx) {
call_deferred("_clear_undo_history");
}
- changing_scene=true;
- editor_data.save_edited_scene_state(editor_selection,&editor_history,_get_main_scene_state());
+ changing_scene = true;
+ editor_data.save_edited_scene_state(editor_selection, &editor_history, _get_main_scene_state());
if (get_editor_data().get_edited_scene_root()) {
- if (get_editor_data().get_edited_scene_root()->get_parent()==scene_root)
+ if (get_editor_data().get_edited_scene_root()->get_parent() == scene_root)
scene_root->remove_child(get_editor_data().get_edited_scene_root());
-
}
//print_line("set current 2 ");
@@ -3263,7 +3086,7 @@ void EditorNode::set_current_scene(int p_idx) {
editor_selection->clear();
editor_data.set_edited_scene(p_idx);
- Node* new_scene = editor_data.get_edited_scene_root();
+ Node *new_scene = editor_data.get_edited_scene_root();
if (new_scene && new_scene->cast_to<Popup>())
new_scene->cast_to<Popup>()->show(); //show popups
@@ -3275,14 +3098,12 @@ void EditorNode::set_current_scene(int p_idx) {
get_tree()->set_edited_scene_root(new_scene);
if (new_scene) {
- if (new_scene->get_parent()!=scene_root)
+ if (new_scene->get_parent() != scene_root)
scene_root->add_child(new_scene);
-
}
//print_line("set current 4 ");
-
- Dictionary state = editor_data.restore_edited_scene_state(editor_selection,&editor_history);
+ Dictionary state = editor_data.restore_edited_scene_state(editor_selection, &editor_history);
_edit_current();
/*if (!unsaved) {
@@ -3297,60 +3118,50 @@ void EditorNode::set_current_scene(int p_idx) {
}*/
//_set_main_scene_state(state);
- call_deferred("_set_main_scene_state",state,get_edited_scene()); //do after everything else is done setting up
+ call_deferred("_set_main_scene_state", state, get_edited_scene()); //do after everything else is done setting up
//print_line("set current 6 ");
-
-
}
-bool EditorNode::is_scene_open(const String& p_path) {
+bool EditorNode::is_scene_open(const String &p_path) {
- for(int i=0;i<editor_data.get_edited_scene_count();i++) {
- if (editor_data.get_scene_path(i)==p_path)
+ for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
+ if (editor_data.get_scene_path(i) == p_path)
return true;
}
return false;
}
-void EditorNode::fix_dependencies(const String& p_for_file) {
+void EditorNode::fix_dependencies(const String &p_for_file) {
dependency_fixer->edit(p_for_file);
}
-
-
-
-Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_clear_errors, bool p_force_open_imported) {
+Error EditorNode::load_scene(const String &p_scene, bool p_ignore_broken_deps, bool p_set_inherited, bool p_clear_errors, bool p_force_open_imported) {
if (!is_inside_tree()) {
defer_load_scene = p_scene;
return OK;
}
+ if (!p_set_inherited) {
- if(!p_set_inherited) {
-
+ for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
- for(int i=0;i<editor_data.get_edited_scene_count();i++) {
-
- if (editor_data.get_scene_path(i)==p_scene) {
+ if (editor_data.get_scene_path(i) == p_scene) {
_scene_tab_changed(i);
return OK;
}
}
- if (!p_force_open_imported && FileAccess::exists(p_scene+".import")) {
- open_imported->set_text(vformat(TTR("Scene '%s' was automatically imported, so it can't be modified.\nTo make changes to it, a new inherited scene can be created."),p_scene.get_file()));
+ if (!p_force_open_imported && FileAccess::exists(p_scene + ".import")) {
+ open_imported->set_text(vformat(TTR("Scene '%s' was automatically imported, so it can't be modified.\nTo make changes to it, a new inherited scene can be created."), p_scene.get_file()));
open_imported->popup_centered_minsize();
new_inherited_button->grab_focus();
- open_import_request=p_scene;
+ open_import_request = p_scene;
return OK;
}
-
}
-
-
if (p_clear_errors)
load_errors->clear();
@@ -3358,12 +3169,12 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
if (!lpath.begins_with("res://")) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("Ugh"));
accept->set_text(TTR("Error loading scene, it must be inside the project path. Use 'Import' to open the scene, then save it inside the project path."));
accept->popup_centered_minsize();
- opening_prev=false;
+ opening_prev = false;
return ERR_FILE_NOT_FOUND;
}
@@ -3372,29 +3183,27 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
//print_line("load scene callback");
//set_current_scene(idx);
- if (!editor_data.get_edited_scene_root() && editor_data.get_edited_scene_count()==2) {
+ if (!editor_data.get_edited_scene_root() && editor_data.get_edited_scene_count() == 2) {
_remove_edited_scene();
} else {
_scene_tab_changed(idx);
}
-
-
//_cleanup_scene(); // i'm sorry but this MUST happen to avoid modified resources to not be reloaded.
dependency_errors.clear();
- Ref<PackedScene> sdata = ResourceLoader::load(lpath,"",true);
+ Ref<PackedScene> sdata = ResourceLoader::load(lpath, "", true);
if (!sdata.is_valid()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("Ugh"));
accept->set_text(TTR("Error loading scene."));
accept->popup_centered_minsize();
- opening_prev=false;
+ opening_prev = false;
- if (prev!=-1) {
+ if (prev != -1) {
set_current_scene(prev);
editor_data.remove_scene(idx);
}
@@ -3403,16 +3212,16 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
if (!p_ignore_broken_deps && dependency_errors.has(lpath)) {
- current_option=-1;
+ current_option = -1;
Vector<String> errors;
- for(Set<String>::Element *E=dependency_errors[lpath].front();E;E=E->next()) {
+ for (Set<String>::Element *E = dependency_errors[lpath].front(); E; E = E->next()) {
errors.push_back(E->get());
}
- dependency_error->show(lpath,errors);
- opening_prev=false;
+ dependency_error->show(lpath, errors);
+ opening_prev = false;
- if (prev!=-1) {
+ if (prev != -1) {
set_current_scene(prev);
editor_data.remove_scene(idx);
}
@@ -3421,40 +3230,40 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
dependency_errors.erase(lpath); //at least not self path
- for (Map<String,Set<String> >::Element *E=dependency_errors.front();E;E=E->next()) {
+ for (Map<String, Set<String> >::Element *E = dependency_errors.front(); E; E = E->next()) {
- String txt=vformat(TTR("Scene '%s' has broken dependencies:"),E->key())+"\n";
- for(Set<String>::Element *F=E->get().front();F;F=F->next()) {
- txt+="\t"+F->get()+"\n";
+ String txt = vformat(TTR("Scene '%s' has broken dependencies:"), E->key()) + "\n";
+ for (Set<String>::Element *F = E->get().front(); F; F = F->next()) {
+ txt += "\t" + F->get() + "\n";
}
add_io_error(txt);
}
if (ResourceCache::has(lpath)) {
//used from somewhere else? no problem! update state and replace sdata
- Ref<PackedScene> ps = Ref<PackedScene>( ResourceCache::get(lpath)->cast_to<PackedScene>() );
+ Ref<PackedScene> ps = Ref<PackedScene>(ResourceCache::get(lpath)->cast_to<PackedScene>());
if (ps.is_valid()) {
- ps->replace_state( sdata->get_state() );
- ps->set_last_modified_time( sdata->get_last_modified_time() );
- sdata=ps;
+ ps->replace_state(sdata->get_state());
+ ps->set_last_modified_time(sdata->get_last_modified_time());
+ sdata = ps;
}
} else {
- sdata->set_path(lpath,true); //take over path
+ sdata->set_path(lpath, true); //take over path
}
- Node*new_scene=sdata->instance(PackedScene::GEN_EDIT_STATE_MAIN);
+ Node *new_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_MAIN);
if (!new_scene) {
sdata.unref();
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("Ugh"));
accept->set_text(TTR("Error loading scene."));
accept->popup_centered_minsize();
- opening_prev=false;
- if (prev!=-1) {
+ opening_prev = false;
+ if (prev != -1) {
set_current_scene(prev);
editor_data.remove_scene(idx);
}
@@ -3501,13 +3310,13 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
*/
//editor_data.get_undo_redo().clear_history();
- saved_version=editor_data.get_undo_redo().get_version();
+ saved_version = editor_data.get_undo_redo().get_version();
_update_title();
_update_scene_tabs();
_add_to_recent_scenes(lpath);
- prev_scene->set_disabled(previous_scenes.size()==0);
- opening_prev=false;
+ prev_scene->set_disabled(previous_scenes.size() == 0);
+ opening_prev = false;
ScriptEditor::get_singleton()->get_debugger()->update_live_edit_root();
@@ -3518,9 +3327,7 @@ Error EditorNode::load_scene(const String& p_scene, bool p_ignore_broken_deps, b
return OK;
}
-
-
-void EditorNode::open_request(const String& p_path) {
+void EditorNode::open_request(const String &p_path) {
load_scene(p_path); // as it will be opened in separate tab
//external_file=p_path;
@@ -3530,10 +3337,9 @@ void EditorNode::open_request(const String& p_path) {
void EditorNode::request_instance_scene(const String &p_path) {
scene_tree_dock->instance(p_path);
-
}
-void EditorNode::request_instance_scenes(const Vector<String>& p_files) {
+void EditorNode::request_instance_scenes(const Vector<String> &p_files) {
scene_tree_dock->instance_scenes(p_files);
}
@@ -3551,41 +3357,40 @@ SceneTreeDock *EditorNode::get_scene_tree_dock() {
return scene_tree_dock;
}
-void EditorNode::_instance_request(const Vector<String>& p_files) {
+void EditorNode::_instance_request(const Vector<String> &p_files) {
request_instance_scenes(p_files);
}
-void EditorNode::_property_keyed(const String& p_keyed,const Variant& p_value,bool p_advance) {
+void EditorNode::_property_keyed(const String &p_keyed, const Variant &p_value, bool p_advance) {
- AnimationPlayerEditor::singleton->get_key_editor()->insert_value_key(p_keyed,p_value,p_advance);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_value_key(p_keyed, p_value, p_advance);
}
-void EditorNode::_transform_keyed(Object *sp,const String& p_sub,const Transform& p_key) {
+void EditorNode::_transform_keyed(Object *sp, const String &p_sub, const Transform &p_key) {
- Spatial *s=sp->cast_to<Spatial>();
+ Spatial *s = sp->cast_to<Spatial>();
if (!s)
return;
- AnimationPlayerEditor::singleton->get_key_editor()->insert_transform_key(s,p_sub,p_key);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_transform_key(s, p_sub, p_key);
}
void EditorNode::update_keying() {
//print_line("KR: "+itos(p_enabled));
- bool valid=false;
+ bool valid = false;
if (AnimationPlayerEditor::singleton->get_key_editor()->has_keying()) {
- if (editor_history.get_path_size()>=1) {
+ if (editor_history.get_path_size() >= 1) {
Object *obj = ObjectDB::get_instance(editor_history.get_path_object(0));
if (obj && obj->cast_to<Node>()) {
- valid=true;
+ valid = true;
}
}
-
}
property_editor->set_keying(valid);
@@ -3593,7 +3398,6 @@ void EditorNode::update_keying() {
AnimationPlayerEditor::singleton->get_key_editor()->update_keying();
}
-
void EditorNode::_close_messages() {
//left_split->set_dragger_visible(false);
@@ -3607,7 +3411,6 @@ void EditorNode::_show_messages() {
//left_split->set_dragger_visible(true);
center_split->set_split_offset(old_split_ofs);
//scene_root_parent->set_anchor_and_margin(MARGIN_BOTTOM,Control::ANCHOR_END,log->get_margin(MARGIN_TOP));
-
}
#if 0
@@ -3648,33 +3451,31 @@ void EditorNode::animation_editor_make_visible(bool p_visible) {
}
#endif
-void EditorNode::_add_to_recent_scenes(const String& p_scene) {
+void EditorNode::_add_to_recent_scenes(const String &p_scene) {
- String base="_"+GlobalConfig::get_singleton()->get_resource_path().replace("\\","::").replace("/","::");
- Vector<String> rc = EDITOR_DEF(base+"/_recent_scenes",Array());
+ String base = "_" + GlobalConfig::get_singleton()->get_resource_path().replace("\\", "::").replace("/", "::");
+ Vector<String> rc = EDITOR_DEF(base + "/_recent_scenes", Array());
String name = p_scene;
- name=name.replace("res://","");
- if (rc.find(name)!=-1)
+ name = name.replace("res://", "");
+ if (rc.find(name) != -1)
rc.erase(name);
- rc.insert(0,name);
- if (rc.size()>10)
+ rc.insert(0, name);
+ if (rc.size() > 10)
rc.resize(10);
- EditorSettings::get_singleton()->set(base+"/_recent_scenes",rc);
+ EditorSettings::get_singleton()->set(base + "/_recent_scenes", rc);
EditorSettings::get_singleton()->save();
_update_recent_scenes();
-
}
void EditorNode::_open_recent_scene(int p_idx) {
- String base="_"+GlobalConfig::get_singleton()->get_resource_path().replace("\\","::").replace("/","::");
- Vector<String> rc = EDITOR_DEF(base+"/_recent_scenes",Array());
-
- ERR_FAIL_INDEX(p_idx,rc.size());
+ String base = "_" + GlobalConfig::get_singleton()->get_resource_path().replace("\\", "::").replace("/", "::");
+ Vector<String> rc = EDITOR_DEF(base + "/_recent_scenes", Array());
- String path = "res://"+rc[p_idx];
+ ERR_FAIL_INDEX(p_idx, rc.size());
+ String path = "res://" + rc[p_idx];
/*if (unsaved_cache) {
_recent_scene=rc[p_idx];
@@ -3685,14 +3486,11 @@ void EditorNode::_open_recent_scene(int p_idx) {
}*/
load_scene(path);
-
-
}
void EditorNode::_save_optimized() {
-
- //save_optimized_copy(optimized_save->get_optimized_scene(),optimized_save->get_preset());
+//save_optimized_copy(optimized_save->get_optimized_scene(),optimized_save->get_preset());
#if 0
String path = optimized_save->get_optimized_scene();
@@ -3730,25 +3528,23 @@ void EditorNode::_save_optimized() {
void EditorNode::_update_recent_scenes() {
- String base="_"+GlobalConfig::get_singleton()->get_resource_path().replace("\\","::").replace("/","::");
- Vector<String> rc = EDITOR_DEF(base+"/_recent_scenes",Array());
+ String base = "_" + GlobalConfig::get_singleton()->get_resource_path().replace("\\", "::").replace("/", "::");
+ Vector<String> rc = EDITOR_DEF(base + "/_recent_scenes", Array());
recent_scenes->clear();
- for(int i=0;i<rc.size();i++) {
+ for (int i = 0; i < rc.size(); i++) {
- recent_scenes->add_item(rc[i],i);
+ recent_scenes->add_item(rc[i], i);
}
-
}
void EditorNode::_quick_opened() {
-
Vector<String> files = quick_open->get_selected_files();
for (int i = 0; i < files.size(); i++) {
String res_path = files[i];
- if (quick_open->get_base_type()=="PackedScene") {
+ if (quick_open->get_base_type() == "PackedScene") {
open_request(res_path);
} else {
load_resource(res_path);
@@ -3759,21 +3555,18 @@ void EditorNode::_quick_opened() {
void EditorNode::_quick_run() {
_call_build();
- _run(false,quick_run->get_selected());
+ _run(false, quick_run->get_selected());
}
-
void EditorNode::notify_child_process_exited() {
- _menu_option_confirm(RUN_STOP,false);
+ _menu_option_confirm(RUN_STOP, false);
stop_button->set_pressed(false);
editor_run.stop();
-
}
-
bool EditorNode::_find_editing_changed_scene(Node *p_from) {
-/*
+ /*
if (!p_from)
return false;
@@ -3796,35 +3589,29 @@ bool EditorNode::_find_editing_changed_scene(Node *p_from) {
return false;
}
-
-
-
-void EditorNode::add_io_error(const String& p_error) {
+void EditorNode::add_io_error(const String &p_error) {
//CharString err_ut = p_error.utf8();
//ERR_PRINT(!err_ut.get_data());
- _load_error_notify(singleton,p_error);
+ _load_error_notify(singleton, p_error);
}
-void EditorNode::_load_error_notify(void* p_ud,const String& p_text) {
-
+void EditorNode::_load_error_notify(void *p_ud, const String &p_text) {
- EditorNode*en=(EditorNode*)p_ud;
- en->load_errors->add_image(en->gui_base->get_icon("Error","EditorIcons"));
- en->load_errors->add_text(p_text+"\n");
+ EditorNode *en = (EditorNode *)p_ud;
+ en->load_errors->add_image(en->gui_base->get_icon("Error", "EditorIcons"));
+ en->load_errors->add_text(p_text + "\n");
en->load_error_dialog->popup_centered_ratio(0.5);
-
}
+bool EditorNode::_find_scene_in_use(Node *p_node, const String &p_path) const {
-bool EditorNode::_find_scene_in_use(Node* p_node,const String& p_path) const {
-
- if (p_node->get_filename()==p_path) {
+ if (p_node->get_filename() == p_path) {
return true;
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- if (_find_scene_in_use(p_node->get_child(i),p_path)) {
+ if (_find_scene_in_use(p_node->get_child(i), p_path)) {
return true;
}
}
@@ -3832,22 +3619,20 @@ bool EditorNode::_find_scene_in_use(Node* p_node,const String& p_path) const {
return false;
}
-
-bool EditorNode::is_scene_in_use(const String& p_path) {
+bool EditorNode::is_scene_in_use(const String &p_path) {
Node *es = get_edited_scene();
if (es)
- return _find_scene_in_use(es,p_path);
+ return _find_scene_in_use(es, p_path);
return false;
-
}
void EditorNode::register_editor_types() {
ClassDB::register_class<EditorPlugin>();
-// ClassDB::register_class<EditorImportPlugin>();
-// ClassDB::register_class<EditorExportPlugin>();
-// ClassDB::register_class<EditorScenePostImport>();
+ // ClassDB::register_class<EditorImportPlugin>();
+ // ClassDB::register_class<EditorExportPlugin>();
+ // ClassDB::register_class<EditorScenePostImport>();
ClassDB::register_class<EditorScript>();
ClassDB::register_class<EditorSelection>();
ClassDB::register_class<EditorFileDialog>();
@@ -3859,8 +3644,6 @@ void EditorNode::register_editor_types() {
ClassDB::register_class<EditorFileSystem>();
ClassDB::register_class<EditorFileSystemDirectory>();
-
-
//ClassDB::register_type<EditorImporter>();
//ClassDB::register_type<EditorPostImport>();
}
@@ -3870,62 +3653,49 @@ void EditorNode::unregister_editor_types() {
_init_callbacks.clear();
}
-
void EditorNode::stop_child_process() {
- _menu_option_confirm(RUN_STOP,false);
+ _menu_option_confirm(RUN_STOP, false);
}
+void EditorNode::progress_add_task(const String &p_task, const String &p_label, int p_steps) {
-
-
-
-void EditorNode::progress_add_task(const String& p_task,const String& p_label, int p_steps) {
-
- singleton->progress_dialog->add_task(p_task,p_label,p_steps);
+ singleton->progress_dialog->add_task(p_task, p_label, p_steps);
}
-void EditorNode::progress_task_step(const String& p_task, const String& p_state, int p_step,bool p_force_redraw) {
-
- singleton->progress_dialog->task_step(p_task,p_state,p_step,p_force_redraw);
+void EditorNode::progress_task_step(const String &p_task, const String &p_state, int p_step, bool p_force_redraw) {
+ singleton->progress_dialog->task_step(p_task, p_state, p_step, p_force_redraw);
}
-void EditorNode::progress_end_task(const String& p_task) {
+void EditorNode::progress_end_task(const String &p_task) {
singleton->progress_dialog->end_task(p_task);
-
}
+void EditorNode::progress_add_task_bg(const String &p_task, const String &p_label, int p_steps) {
-void EditorNode::progress_add_task_bg(const String& p_task,const String& p_label, int p_steps) {
-
- singleton->progress_hb->add_task(p_task,p_label,p_steps);
+ singleton->progress_hb->add_task(p_task, p_label, p_steps);
}
-void EditorNode::progress_task_step_bg(const String& p_task, int p_step) {
-
- singleton->progress_hb->task_step(p_task,p_step);
+void EditorNode::progress_task_step_bg(const String &p_task, int p_step) {
+ singleton->progress_hb->task_step(p_task, p_step);
}
-void EditorNode::progress_end_task_bg(const String& p_task) {
+void EditorNode::progress_end_task_bg(const String &p_task) {
singleton->progress_hb->end_task(p_task);
-
}
-
-
-Ref<Texture> EditorNode::_file_dialog_get_icon(const String& p_path) {
-
+Ref<Texture> EditorNode::_file_dialog_get_icon(const String &p_path) {
EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem_path(p_path.get_base_dir());
if (efsd) {
String file = p_path.get_file();
- for(int i=0;i<efsd->get_file_count();i++) {
- if (efsd->get_file(i)==file) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
+ if (efsd->get_file(i) == file) {
String type = efsd->get_file_type(i);
@@ -3934,7 +3704,6 @@ Ref<Texture> EditorNode::_file_dialog_get_icon(const String& p_path) {
} else {
return singleton->icon_type_cache["Object"];
}
-
}
}
}
@@ -3947,7 +3716,7 @@ void EditorNode::_file_dialog_register(FileDialog *p_dialog) {
singleton->file_dialogs.insert(p_dialog);
}
-void EditorNode::_file_dialog_unregister(FileDialog *p_dialog){
+void EditorNode::_file_dialog_unregister(FileDialog *p_dialog) {
singleton->file_dialogs.erase(p_dialog);
}
@@ -3957,83 +3726,80 @@ void EditorNode::_editor_file_dialog_register(EditorFileDialog *p_dialog) {
singleton->editor_file_dialogs.insert(p_dialog);
}
-void EditorNode::_editor_file_dialog_unregister(EditorFileDialog *p_dialog){
+void EditorNode::_editor_file_dialog_unregister(EditorFileDialog *p_dialog) {
singleton->editor_file_dialogs.erase(p_dialog);
}
Vector<EditorNodeInitCallback> EditorNode::_init_callbacks;
-Error EditorNode::export_platform(const String& p_platform, const String& p_path, bool p_debug,const String& p_password,bool p_quit_after) {
+Error EditorNode::export_platform(const String &p_platform, const String &p_path, bool p_debug, const String &p_password, bool p_quit_after) {
- export_defer.platform=p_platform;
- export_defer.path=p_path;
- export_defer.debug=p_debug;
- export_defer.password=p_password;
+ export_defer.platform = p_platform;
+ export_defer.path = p_path;
+ export_defer.debug = p_debug;
+ export_defer.password = p_password;
return OK;
}
-void EditorNode::show_warning(const String& p_text, const String &p_title) {
+void EditorNode::show_warning(const String &p_text, const String &p_title) {
warning->set_text(p_text);
warning->set_title(p_title);
warning->popup_centered_minsize();
}
-void EditorNode::_dock_select_input(const InputEvent& p_input) {
+void EditorNode::_dock_select_input(const InputEvent &p_input) {
- if (p_input.type==InputEvent::MOUSE_BUTTON || p_input.type==InputEvent::MOUSE_MOTION) {
+ if (p_input.type == InputEvent::MOUSE_BUTTON || p_input.type == InputEvent::MOUSE_MOTION) {
- Vector2 point(p_input.mouse_motion.x,p_input.mouse_motion.y);
+ Vector2 point(p_input.mouse_motion.x, p_input.mouse_motion.y);
int nrect = -1;
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
if (dock_select_rect[i].has_point(point)) {
- nrect=i;
+ nrect = i;
break;
}
}
-
- if (nrect!=dock_select_rect_over) {
+ if (nrect != dock_select_rect_over) {
dock_select->update();
- dock_select_rect_over=nrect;
-
+ dock_select_rect_over = nrect;
}
-
- if (nrect==-1)
+ if (nrect == -1)
return;
- if (p_input.type==InputEvent::MOUSE_BUTTON && p_input.mouse_button.button_index==1 && p_input.mouse_button.pressed && dock_popup_selected!=nrect) {
+ if (p_input.type == InputEvent::MOUSE_BUTTON && p_input.mouse_button.button_index == 1 && p_input.mouse_button.pressed && dock_popup_selected != nrect) {
Control *dock = dock_slot[dock_popup_selected]->get_current_tab_control();
if (dock) {
dock_slot[dock_popup_selected]->remove_child(dock);
}
- if (dock_slot[dock_popup_selected]->get_tab_count()==0) {
+ if (dock_slot[dock_popup_selected]->get_tab_count() == 0) {
dock_slot[dock_popup_selected]->hide();
- } else {
+ } else {
dock_slot[dock_popup_selected]->set_current_tab(0);
}
dock_slot[nrect]->add_child(dock);
- dock_popup_selected=nrect;
- dock_slot[nrect]->set_current_tab(dock_slot[nrect]->get_tab_count()-1);
+ dock_popup_selected = nrect;
+ dock_slot[nrect]->set_current_tab(dock_slot[nrect]->get_tab_count() - 1);
dock_slot[nrect]->show();
dock_select->update();
- VSplitContainer*splits[DOCK_SLOT_MAX/2]={
+ VSplitContainer *splits[DOCK_SLOT_MAX / 2] = {
left_l_vsplit,
left_r_vsplit,
right_l_vsplit,
right_r_vsplit,
};
- for(int i=0;i<4;i++) {
- bool in_use = dock_slot[i*2+0]->get_tab_count() || dock_slot[i*2+1]->get_tab_count();
+ for (int i = 0; i < 4; i++) {
+ bool in_use = dock_slot[i * 2 + 0]->get_tab_count() || dock_slot[i * 2 + 1]->get_tab_count();
if (in_use)
splits[i]->show();
else
@@ -4047,132 +3813,127 @@ void EditorNode::_dock_select_input(const InputEvent& p_input) {
void EditorNode::_dock_popup_exit() {
- dock_select_rect_over=-1;
+ dock_select_rect_over = -1;
dock_select->update();
}
void EditorNode::_dock_pre_popup(int p_which) {
-
- dock_popup_selected=p_which;
+ dock_popup_selected = p_which;
}
void EditorNode::_dock_move_left() {
- if (dock_popup_selected<0 || dock_popup_selected>=DOCK_SLOT_MAX)
+ if (dock_popup_selected < 0 || dock_popup_selected >= DOCK_SLOT_MAX)
return;
- Control *current = dock_slot[dock_popup_selected]->get_tab_control( dock_slot[dock_popup_selected]->get_current_tab() );
- Control *prev = dock_slot[dock_popup_selected]->get_tab_control( dock_slot[dock_popup_selected]->get_current_tab()-1 );
+ Control *current = dock_slot[dock_popup_selected]->get_tab_control(dock_slot[dock_popup_selected]->get_current_tab());
+ Control *prev = dock_slot[dock_popup_selected]->get_tab_control(dock_slot[dock_popup_selected]->get_current_tab() - 1);
if (!current || !prev)
return;
- dock_slot[dock_popup_selected]->move_child(current,prev->get_index());
- dock_slot[dock_popup_selected]->set_current_tab( dock_slot[dock_popup_selected]->get_current_tab()-1 );
+ dock_slot[dock_popup_selected]->move_child(current, prev->get_index());
+ dock_slot[dock_popup_selected]->set_current_tab(dock_slot[dock_popup_selected]->get_current_tab() - 1);
dock_select->update();
_save_docks();
-
-
}
void EditorNode::_dock_move_right() {
- Control *current = dock_slot[dock_popup_selected]->get_tab_control( dock_slot[dock_popup_selected]->get_current_tab() );
- Control *next = dock_slot[dock_popup_selected]->get_tab_control( dock_slot[dock_popup_selected]->get_current_tab()+1 );
+ Control *current = dock_slot[dock_popup_selected]->get_tab_control(dock_slot[dock_popup_selected]->get_current_tab());
+ Control *next = dock_slot[dock_popup_selected]->get_tab_control(dock_slot[dock_popup_selected]->get_current_tab() + 1);
if (!current || !next)
return;
- dock_slot[dock_popup_selected]->move_child(next,current->get_index());
- dock_slot[dock_popup_selected]->set_current_tab( dock_slot[dock_popup_selected]->get_current_tab()+1 );
+ dock_slot[dock_popup_selected]->move_child(next, current->get_index());
+ dock_slot[dock_popup_selected]->set_current_tab(dock_slot[dock_popup_selected]->get_current_tab() + 1);
dock_select->update();
_save_docks();
}
-void EditorNode::_dock_select_draw(){
+void EditorNode::_dock_select_draw() {
Size2 s = dock_select->get_size();
- s.y/=2.0;
- s.x/=6.0;
+ s.y /= 2.0;
+ s.x /= 6.0;
- Color used=Color(0.6,0.6,0.6,0.8);
- Color used_selected=Color(0.8,0.8,0.8,0.8);
- Color tab_selected=Color(1,1,1,1);
- Color unused=used;
- unused.a=0.4;
- Color unusable=unused;
- unusable.a=0.1;
+ Color used = Color(0.6, 0.6, 0.6, 0.8);
+ Color used_selected = Color(0.8, 0.8, 0.8, 0.8);
+ Color tab_selected = Color(1, 1, 1, 1);
+ Color unused = used;
+ unused.a = 0.4;
+ Color unusable = unused;
+ unusable.a = 0.1;
- Rect2 unr(s.x*2,0,s.x*2,s.y*2);
- unr.pos+=Vector2(2,5);
- unr.size-=Vector2(4,7);
+ Rect2 unr(s.x * 2, 0, s.x * 2, s.y * 2);
+ unr.pos += Vector2(2, 5);
+ unr.size -= Vector2(4, 7);
- dock_select->draw_rect(unr,unusable);
+ dock_select->draw_rect(unr, unusable);
dock_tab_move_left->set_disabled(true);
dock_tab_move_right->set_disabled(true);
- if (dock_popup_selected!=-1 && dock_slot[dock_popup_selected]->get_tab_count()) {
+ if (dock_popup_selected != -1 && dock_slot[dock_popup_selected]->get_tab_count()) {
- dock_tab_move_left->set_disabled(dock_slot[dock_popup_selected]->get_current_tab()==0);
- dock_tab_move_right->set_disabled(dock_slot[dock_popup_selected]->get_current_tab()>=dock_slot[dock_popup_selected]->get_tab_count()-1);
+ dock_tab_move_left->set_disabled(dock_slot[dock_popup_selected]->get_current_tab() == 0);
+ dock_tab_move_right->set_disabled(dock_slot[dock_popup_selected]->get_current_tab() >= dock_slot[dock_popup_selected]->get_tab_count() - 1);
}
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
Vector2 ofs;
- switch(i) {
+ switch (i) {
case DOCK_SLOT_LEFT_UL: {
} break;
case DOCK_SLOT_LEFT_BL: {
- ofs.y+=s.y;
+ ofs.y += s.y;
} break;
case DOCK_SLOT_LEFT_UR: {
- ofs.x+=s.x;
+ ofs.x += s.x;
} break;
case DOCK_SLOT_LEFT_BR: {
- ofs+=s;
+ ofs += s;
} break;
case DOCK_SLOT_RIGHT_UL: {
- ofs.x+=s.x*4;
+ ofs.x += s.x * 4;
} break;
case DOCK_SLOT_RIGHT_BL: {
- ofs.x+=s.x*4;
- ofs.y+=s.y;
+ ofs.x += s.x * 4;
+ ofs.y += s.y;
} break;
case DOCK_SLOT_RIGHT_UR: {
- ofs.x+=s.x*4;
- ofs.x+=s.x;
+ ofs.x += s.x * 4;
+ ofs.x += s.x;
} break;
case DOCK_SLOT_RIGHT_BR: {
- ofs.x+=s.x*4;
- ofs+=s;
+ ofs.x += s.x * 4;
+ ofs += s;
} break;
}
- Rect2 r(ofs,s);
- dock_select_rect[i]=r;
- r.pos+=Vector2(2,5);
- r.size-=Vector2(4,7);
+ Rect2 r(ofs, s);
+ dock_select_rect[i] = r;
+ r.pos += Vector2(2, 5);
+ r.size -= Vector2(4, 7);
-
- if (i==dock_select_rect_over) {
- dock_select->draw_rect(r,used_selected);
- } else if (dock_slot[i]->get_child_count()==0) {
- dock_select->draw_rect(r,unused);
+ if (i == dock_select_rect_over) {
+ dock_select->draw_rect(r, used_selected);
+ } else if (dock_slot[i]->get_child_count() == 0) {
+ dock_select->draw_rect(r, unused);
} else {
- dock_select->draw_rect(r,used);
+ dock_select->draw_rect(r, used);
}
- for(int j=0;j<MIN(3,dock_slot[i]->get_child_count());j++) {
- int xofs = (r.size.width/3)*j;
+ for (int j = 0; j < MIN(3, dock_slot[i]->get_child_count()); j++) {
+ int xofs = (r.size.width / 3) * j;
Color c = used;
- if (i==dock_popup_selected && (dock_slot[i]->get_current_tab()>3 || dock_slot[i]->get_current_tab()==j))
- c=tab_selected;
- dock_select->draw_rect(Rect2(2+ofs.x+xofs,ofs.y,r.size.width/3-1,3),c);
+ if (i == dock_popup_selected && (dock_slot[i]->get_current_tab() > 3 || dock_slot[i]->get_current_tab() == j))
+ c = tab_selected;
+ dock_select->draw_rect(Rect2(2 + ofs.x + xofs, ofs.y, r.size.width / 3 - 1, 3), c);
}
-
}
}
@@ -4185,54 +3946,51 @@ void EditorNode::_save_docks() {
editor_data.get_plugin_window_layout(config);
config->save(EditorSettings::get_singleton()->get_project_settings_path().plus_file("editor_layout.cfg"));
-
}
-void EditorNode::_save_docks_to_config(Ref<ConfigFile> p_layout, const String& p_section) {
+void EditorNode::_save_docks_to_config(Ref<ConfigFile> p_layout, const String &p_section) {
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
String names;
- for(int j=0;j<dock_slot[i]->get_tab_count();j++) {
+ for (int j = 0; j < dock_slot[i]->get_tab_count(); j++) {
String name = dock_slot[i]->get_tab_control(j)->get_name();
- if (names!="")
- names+=",";
- names+=name;
+ if (names != "")
+ names += ",";
+ names += name;
}
- if (names!="") {
- p_layout->set_value(p_section,"dock_"+itos(i+1),names);
+ if (names != "") {
+ p_layout->set_value(p_section, "dock_" + itos(i + 1), names);
}
}
- p_layout->set_value(p_section,"dock_filesystem_split",filesystem_dock->get_split_offset());
+ p_layout->set_value(p_section, "dock_filesystem_split", filesystem_dock->get_split_offset());
- VSplitContainer*splits[DOCK_SLOT_MAX/2]={
+ VSplitContainer *splits[DOCK_SLOT_MAX / 2] = {
left_l_vsplit,
left_r_vsplit,
right_l_vsplit,
right_r_vsplit,
};
- for(int i=0;i<DOCK_SLOT_MAX/2;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++) {
if (splits[i]->is_visible_in_tree()) {
- p_layout->set_value(p_section,"dock_split_"+itos(i+1),splits[i]->get_split_offset());
+ p_layout->set_value(p_section, "dock_split_" + itos(i + 1), splits[i]->get_split_offset());
}
}
-
- HSplitContainer *h_splits[4]={
+ HSplitContainer *h_splits[4] = {
left_l_hsplit,
left_r_hsplit,
main_hsplit,
right_hsplit,
};
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- p_layout->set_value(p_section,"dock_hsplit_"+itos(i+1),h_splits[i]->get_split_offset());
+ p_layout->set_value(p_section, "dock_hsplit_" + itos(i + 1), h_splits[i]->get_split_offset());
}
-
}
void EditorNode::save_layout() {
@@ -4250,9 +4008,9 @@ void EditorNode::_load_docks() {
Ref<ConfigFile> config;
config.instance();
Error err = config->load(EditorSettings::get_singleton()->get_project_settings_path().plus_file("editor_layout.cfg"));
- if (err!=OK) {
+ if (err != OK) {
//no config
- if (overridden_default_layout>=0) {
+ if (overridden_default_layout >= 0) {
_layout_menu_option(overridden_default_layout);
}
return;
@@ -4260,21 +4018,18 @@ void EditorNode::_load_docks() {
_load_docks_from_config(config, "docks");
editor_data.set_plugin_window_layout(config);
-
}
-
void EditorNode::_update_dock_slots_visibility() {
- VSplitContainer*splits[DOCK_SLOT_MAX/2]={
+ VSplitContainer *splits[DOCK_SLOT_MAX / 2] = {
left_l_vsplit,
left_r_vsplit,
right_l_vsplit,
right_r_vsplit,
};
-
- HSplitContainer*h_splits[4]={
+ HSplitContainer *h_splits[4] = {
left_l_hsplit,
left_r_hsplit,
main_hsplit,
@@ -4283,36 +4038,34 @@ void EditorNode::_update_dock_slots_visibility() {
if (!docks_visible) {
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
dock_slot[i]->hide();
}
- for(int i=0;i<DOCK_SLOT_MAX/2;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++) {
splits[i]->hide();
}
right_hsplit->hide();
bottom_panel->hide();
} else {
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
if (dock_slot[i]->get_tab_count())
dock_slot[i]->show();
else
dock_slot[i]->hide();
-
}
-
- for(int i=0;i<DOCK_SLOT_MAX/2;i++) {
- bool in_use = dock_slot[i*2+0]->get_tab_count() || dock_slot[i*2+1]->get_tab_count();
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++) {
+ bool in_use = dock_slot[i * 2 + 0]->get_tab_count() || dock_slot[i * 2 + 1]->get_tab_count();
if (in_use)
splits[i]->show();
else
splits[i]->hide();
}
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
if (dock_slot[i]->is_visible() && dock_slot[i]->get_tab_count()) {
dock_slot[i]->set_current_tab(0);
@@ -4338,44 +4091,42 @@ void EditorNode::_update_top_menu_visibility() {
}*/
}
-void EditorNode::_load_docks_from_config(Ref<ConfigFile> p_layout, const String& p_section) {
+void EditorNode::_load_docks_from_config(Ref<ConfigFile> p_layout, const String &p_section) {
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
- if (!p_layout->has_section_key(p_section,"dock_"+itos(i+1)))
+ if (!p_layout->has_section_key(p_section, "dock_" + itos(i + 1)))
continue;
- Vector<String> names = String(p_layout->get_value(p_section,"dock_"+itos(i+1))).split(",");
+ Vector<String> names = String(p_layout->get_value(p_section, "dock_" + itos(i + 1))).split(",");
- for(int j=0;j<names.size();j++) {
+ for (int j = 0; j < names.size(); j++) {
- String name=names[j];
+ String name = names[j];
//find it, in a horribly inefficient way
- int atidx=-1;
- Control *node=NULL;
- for(int k=0;k<DOCK_SLOT_MAX;k++) {
+ int atidx = -1;
+ Control *node = NULL;
+ for (int k = 0; k < DOCK_SLOT_MAX; k++) {
if (!dock_slot[k]->has_node(name))
continue;
- node=dock_slot[k]->get_node(name)->cast_to<Control>();
+ node = dock_slot[k]->get_node(name)->cast_to<Control>();
if (!node)
continue;
- atidx=k;
+ atidx = k;
break;
}
- if (atidx==-1) //well, it's not anywhere
+ if (atidx == -1) //well, it's not anywhere
continue;
- if (atidx==i) {
+ if (atidx == i) {
node->raise();
continue;
}
-
dock_slot[atidx]->remove_child(node);
- if (dock_slot[atidx]->get_tab_count()==0) {
+ if (dock_slot[atidx]->get_tab_count() == 0) {
dock_slot[atidx]->hide();
-
}
dock_slot[i]->add_child(node);
dock_slot[i]->show();
@@ -4383,50 +4134,50 @@ void EditorNode::_load_docks_from_config(Ref<ConfigFile> p_layout, const String&
}
int fs_split_ofs = 0;
- if (p_layout->has_section_key(p_section,"dock_filesystem_split")) {
- fs_split_ofs = p_layout->get_value(p_section,"dock_filesystem_split");
+ if (p_layout->has_section_key(p_section, "dock_filesystem_split")) {
+ fs_split_ofs = p_layout->get_value(p_section, "dock_filesystem_split");
}
filesystem_dock->set_split_offset(fs_split_ofs);
- VSplitContainer*splits[DOCK_SLOT_MAX/2]={
+ VSplitContainer *splits[DOCK_SLOT_MAX / 2] = {
left_l_vsplit,
left_r_vsplit,
right_l_vsplit,
right_r_vsplit,
};
- for(int i=0;i<DOCK_SLOT_MAX/2;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++) {
- if (!p_layout->has_section_key(p_section,"dock_split_"+itos(i+1)))
+ if (!p_layout->has_section_key(p_section, "dock_split_" + itos(i + 1)))
continue;
- int ofs = p_layout->get_value(p_section,"dock_split_"+itos(i+1));
+ int ofs = p_layout->get_value(p_section, "dock_split_" + itos(i + 1));
splits[i]->set_split_offset(ofs);
}
- HSplitContainer*h_splits[4]={
+ HSplitContainer *h_splits[4] = {
left_l_hsplit,
left_r_hsplit,
main_hsplit,
right_hsplit,
};
- for(int i=0;i<4;i++) {
- if (!p_layout->has_section_key(p_section,"dock_hsplit_"+itos(i+1)))
+ for (int i = 0; i < 4; i++) {
+ if (!p_layout->has_section_key(p_section, "dock_hsplit_" + itos(i + 1)))
continue;
- int ofs = p_layout->get_value(p_section,"dock_hsplit_"+itos(i+1));
+ int ofs = p_layout->get_value(p_section, "dock_hsplit_" + itos(i + 1));
h_splits[i]->set_split_offset(ofs);
}
- for(int i=0;i<DOCK_SLOT_MAX/2;i++) {
- bool in_use = dock_slot[i*2+0]->get_tab_count() || dock_slot[i*2+1]->get_tab_count();
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++) {
+ bool in_use = dock_slot[i * 2 + 0]->get_tab_count() || dock_slot[i * 2 + 1]->get_tab_count();
if (in_use)
splits[i]->show();
else
splits[i]->hide();
}
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
if (dock_slot[i]->is_visible() && dock_slot[i]->get_tab_count()) {
dock_slot[i]->set_current_tab(0);
@@ -4434,40 +4185,38 @@ void EditorNode::_load_docks_from_config(Ref<ConfigFile> p_layout, const String&
}
}
-
void EditorNode::_update_layouts_menu() {
editor_layouts->clear();
- overridden_default_layout=-1;
+ overridden_default_layout = -1;
editor_layouts->set_size(Vector2());
- editor_layouts->add_shortcut(ED_SHORTCUT("layout/save",TTR("Save Layout")), SETTINGS_LAYOUT_SAVE);
- editor_layouts->add_shortcut(ED_SHORTCUT("layout/delete",TTR("Delete Layout")), SETTINGS_LAYOUT_DELETE);
+ editor_layouts->add_shortcut(ED_SHORTCUT("layout/save", TTR("Save Layout")), SETTINGS_LAYOUT_SAVE);
+ editor_layouts->add_shortcut(ED_SHORTCUT("layout/delete", TTR("Delete Layout")), SETTINGS_LAYOUT_DELETE);
editor_layouts->add_separator();
- editor_layouts->add_shortcut(ED_SHORTCUT("layout/default",TTR("Default")), SETTINGS_LAYOUT_DEFAULT);
+ editor_layouts->add_shortcut(ED_SHORTCUT("layout/default", TTR("Default")), SETTINGS_LAYOUT_DEFAULT);
Ref<ConfigFile> config;
config.instance();
Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg"));
- if (err!=OK) {
+ if (err != OK) {
return; //no config
}
List<String> layouts;
config.ptr()->get_sections(&layouts);
- for (List<String>::Element *E=layouts.front();E;E=E->next()) {
+ for (List<String>::Element *E = layouts.front(); E; E = E->next()) {
- String layout=E->get();
+ String layout = E->get();
- if (layout==TTR("Default")) {
+ if (layout == TTR("Default")) {
editor_layouts->remove_item(editor_layouts->get_item_index(SETTINGS_LAYOUT_DEFAULT));
- overridden_default_layout=editor_layouts->get_item_count();
+ overridden_default_layout = editor_layouts->get_item_count();
}
editor_layouts->add_item(layout);
}
-
}
void EditorNode::_layout_menu_option(int p_id) {
@@ -4476,14 +4225,14 @@ void EditorNode::_layout_menu_option(int p_id) {
case SETTINGS_LAYOUT_SAVE: {
- current_option=p_id;
+ current_option = p_id;
layout_dialog->set_title(TTR("Save Layout"));
layout_dialog->get_ok()->set_text(TTR("Save"));
layout_dialog->popup_centered();
} break;
case SETTINGS_LAYOUT_DELETE: {
- current_option=p_id;
+ current_option = p_id;
layout_dialog->set_title(TTR("Delete Layout"));
layout_dialog->get_ok()->set_text(TTR("Delete"));
layout_dialog->popup_centered();
@@ -4498,7 +4247,7 @@ void EditorNode::_layout_menu_option(int p_id) {
Ref<ConfigFile> config;
config.instance();
Error err = config->load(EditorSettings::get_singleton()->get_settings_path().plus_file("editor_layouts.cfg"));
- if (err!=OK) {
+ if (err != OK) {
return; //no config
}
@@ -4506,13 +4255,11 @@ void EditorNode::_layout_menu_option(int p_id) {
_save_docks();
}
}
-
}
-
void EditorNode::_scene_tab_script_edited(int p_tab) {
- Ref<Script> script = editor_data.get_scene_root_script(p_tab);
+ Ref<Script> script = editor_data.get_scene_root_script(p_tab);
if (script.is_valid())
edit_resource(script);
}
@@ -4521,53 +4268,46 @@ void EditorNode::_scene_tab_closed(int p_tab) {
current_option = SCENE_TAB_CLOSE;
tab_closing = p_tab;
- bool unsaved = (p_tab==editor_data.get_edited_scene()) ?
- saved_version!=editor_data.get_undo_redo().get_version() :
- editor_data.get_scene_version(p_tab)!=0;
+ bool unsaved = (p_tab == editor_data.get_edited_scene()) ?
+ saved_version != editor_data.get_undo_redo().get_version() :
+ editor_data.get_scene_version(p_tab) != 0;
if (unsaved) {
confirmation->get_ok()->set_text(TTR("Yes"));
//confirmation->get_cancel()->show();
confirmation->set_text(TTR("Close scene? (Unsaved changes will be lost)"));
confirmation->popup_centered_minsize();
- }
- else {
+ } else {
_remove_scene(p_tab);
_update_scene_tabs();
}
-
}
-
void EditorNode::_scene_tab_changed(int p_tab) {
-
//print_line("set current 1 ");
- bool unsaved = (saved_version!=editor_data.get_undo_redo().get_version());
+ bool unsaved = (saved_version != editor_data.get_undo_redo().get_version());
//print_line("version: "+itos(editor_data.get_undo_redo().get_version())+", saved "+itos(saved_version));
- if (p_tab==editor_data.get_edited_scene())
+ if (p_tab == editor_data.get_edited_scene())
return; //pointless
uint64_t next_scene_version = editor_data.get_scene_version(p_tab);
-
-
//print_line("scene tab changed???");
editor_data.get_undo_redo().create_action(TTR("Switch Scene Tab"));
- editor_data.get_undo_redo().add_do_method(this,"set_current_version",unsaved?saved_version:0);
- editor_data.get_undo_redo().add_do_method(this,"set_current_scene",p_tab);
+ editor_data.get_undo_redo().add_do_method(this, "set_current_version", unsaved ? saved_version : 0);
+ editor_data.get_undo_redo().add_do_method(this, "set_current_scene", p_tab);
//editor_data.get_undo_redo().add_do_method(scene_tabs,"set_current_tab",p_tab);
//editor_data.get_undo_redo().add_do_method(scene_tabs,"ensure_tab_visible",p_tab);
- editor_data.get_undo_redo().add_do_method(this,"set_current_version",next_scene_version==0?editor_data.get_undo_redo().get_version()+1:next_scene_version);
+ editor_data.get_undo_redo().add_do_method(this, "set_current_version", next_scene_version == 0 ? editor_data.get_undo_redo().get_version() + 1 : next_scene_version);
- editor_data.get_undo_redo().add_undo_method(this,"set_current_version",next_scene_version);
- editor_data.get_undo_redo().add_undo_method(this,"set_current_scene",editor_data.get_edited_scene());
+ editor_data.get_undo_redo().add_undo_method(this, "set_current_version", next_scene_version);
+ editor_data.get_undo_redo().add_undo_method(this, "set_current_scene", editor_data.get_edited_scene());
//editor_data.get_undo_redo().add_undo_method(scene_tabs,"set_current_tab",editor_data.get_edited_scene());
//editor_data.get_undo_redo().add_undo_method(scene_tabs,"ensure_tab_visible",p_tab,editor_data.get_edited_scene());
- editor_data.get_undo_redo().add_undo_method(this,"set_current_version",saved_version);
+ editor_data.get_undo_redo().add_undo_method(this, "set_current_version", saved_version);
editor_data.get_undo_redo().commit_action();
-
}
void EditorNode::_toggle_search_bar(bool p_pressed) {
@@ -4587,17 +4327,17 @@ void EditorNode::_toggle_search_bar(bool p_pressed) {
void EditorNode::_clear_search_box() {
- if (search_box->get_text()=="")
+ if (search_box->get_text() == "")
return;
search_box->clear();
property_editor->update_tree();
}
-ToolButton *EditorNode::add_bottom_panel_item(String p_text,Control *p_item) {
+ToolButton *EditorNode::add_bottom_panel_item(String p_text, Control *p_item) {
- ToolButton *tb = memnew( ToolButton );
- tb->connect("toggled",this,"_bottom_panel_switch",varray(bottom_panel_items.size()));
+ ToolButton *tb = memnew(ToolButton);
+ tb->connect("toggled", this, "_bottom_panel_switch", varray(bottom_panel_items.size()));
tb->set_text(p_text);
tb->set_toggle_mode(true);
tb->set_focus_mode(Control::FOCUS_NONE);
@@ -4607,18 +4347,17 @@ ToolButton *EditorNode::add_bottom_panel_item(String p_text,Control *p_item) {
p_item->set_v_size_flags(Control::SIZE_EXPAND_FILL);
p_item->hide();
BottomPanelItem bpi;
- bpi.button=tb;
- bpi.control=p_item;
- bpi.name=p_text;
+ bpi.button = tb;
+ bpi.control = p_item;
+ bpi.name = p_text;
bottom_panel_items.push_back(bpi);
return tb;
-
}
bool EditorNode::are_bottom_panels_hidden() const {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
if (bottom_panel_items[i].button->is_pressed())
return false;
}
@@ -4628,16 +4367,15 @@ bool EditorNode::are_bottom_panels_hidden() const {
void EditorNode::hide_bottom_panel() {
- _bottom_panel_switch(false,0);
-
+ _bottom_panel_switch(false, 0);
}
void EditorNode::make_bottom_panel_item_visible(Control *p_item) {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
- if (bottom_panel_items[i].control==p_item) {
- _bottom_panel_switch(true,i);
+ if (bottom_panel_items[i].control == p_item) {
+ _bottom_panel_switch(true, i);
break;
}
}
@@ -4645,60 +4383,57 @@ void EditorNode::make_bottom_panel_item_visible(Control *p_item) {
void EditorNode::raise_bottom_panel_item(Control *p_item) {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
- if (bottom_panel_items[i].control==p_item) {
+ if (bottom_panel_items[i].control == p_item) {
bottom_panel_items[i].button->raise();
- SWAP( bottom_panel_items[i], bottom_panel_items[bottom_panel_items.size()-1]);
+ SWAP(bottom_panel_items[i], bottom_panel_items[bottom_panel_items.size() - 1]);
break;
}
}
- for(int i=0;i<bottom_panel_items.size();i++) {
- bottom_panel_items[i].button->disconnect("toggled",this,"_bottom_panel_switch");
- bottom_panel_items[i].button->connect("toggled",this,"_bottom_panel_switch",varray(i));
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
+ bottom_panel_items[i].button->disconnect("toggled", this, "_bottom_panel_switch");
+ bottom_panel_items[i].button->connect("toggled", this, "_bottom_panel_switch", varray(i));
}
-
}
void EditorNode::remove_bottom_panel_item(Control *p_item) {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
- if (bottom_panel_items[i].control==p_item) {
+ if (bottom_panel_items[i].control == p_item) {
if (p_item->is_visible_in_tree()) {
- _bottom_panel_switch(false,0);
+ _bottom_panel_switch(false, 0);
}
bottom_panel_vb->remove_child(bottom_panel_items[i].control);
bottom_panel_hb->remove_child(bottom_panel_items[i].button);
- memdelete( bottom_panel_items[i].button );
+ memdelete(bottom_panel_items[i].button);
bottom_panel_items.remove(i);
break;
}
}
- for(int i=0;i<bottom_panel_items.size();i++) {
- bottom_panel_items[i].button->disconnect("toggled",this,"_bottom_panel_switch");
- bottom_panel_items[i].button->connect("toggled",this,"_bottom_panel_switch",varray(i));
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
+ bottom_panel_items[i].button->disconnect("toggled", this, "_bottom_panel_switch");
+ bottom_panel_items[i].button->connect("toggled", this, "_bottom_panel_switch", varray(i));
}
}
-void EditorNode::_bottom_panel_switch(bool p_enable,int p_idx) {
-
- ERR_FAIL_INDEX(p_idx,bottom_panel_items.size());
-
+void EditorNode::_bottom_panel_switch(bool p_enable, int p_idx) {
+ ERR_FAIL_INDEX(p_idx, bottom_panel_items.size());
if (p_enable) {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
- bottom_panel_items[i].button->set_pressed(i==p_idx);
- bottom_panel_items[i].control->set_visible(i==p_idx);
+ bottom_panel_items[i].button->set_pressed(i == p_idx);
+ bottom_panel_items[i].control->set_visible(i == p_idx);
}
center_split->set_dragger_visibility(SplitContainer::DRAGGER_VISIBLE);
center_split->set_collapsed(false);
} else {
- for(int i=0;i<bottom_panel_items.size();i++) {
+ for (int i = 0; i < bottom_panel_items.size(); i++) {
bottom_panel_items[i].button->set_pressed(false);
bottom_panel_items[i].control->set_visible(false);
@@ -4719,7 +4454,7 @@ bool EditorNode::get_docks_visible() const {
void EditorNode::_toggle_distraction_free_mode() {
- set_distraction_free_mode( distraction_free->is_pressed() );
+ set_distraction_free_mode(distraction_free->is_pressed());
}
void EditorNode::set_distraction_free_mode(bool p_enter) {
@@ -4740,19 +4475,18 @@ bool EditorNode::get_distraction_free_mode() const {
return distraction_free->is_pressed();
}
-void EditorNode::add_control_to_dock(DockSlot p_slot,Control* p_control) {
- ERR_FAIL_INDEX(p_slot,DOCK_SLOT_MAX);
+void EditorNode::add_control_to_dock(DockSlot p_slot, Control *p_control) {
+ ERR_FAIL_INDEX(p_slot, DOCK_SLOT_MAX);
dock_slot[p_slot]->add_child(p_control);
_update_dock_slots_visibility();
-
}
-void EditorNode::remove_control_from_dock(Control* p_control) {
+void EditorNode::remove_control_from_dock(Control *p_control) {
- Control *dock=NULL;
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
- if (p_control->get_parent()==dock_slot[i]) {
- dock=dock_slot[i];
+ Control *dock = NULL;
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
+ if (p_control->get_parent() == dock_slot[i]) {
+ dock = dock_slot[i];
break;
}
}
@@ -4764,139 +4498,128 @@ void EditorNode::remove_control_from_dock(Control* p_control) {
_update_dock_slots_visibility();
}
-Variant EditorNode::drag_resource(const Ref<Resource>& p_res,Control* p_from) {
-
+Variant EditorNode::drag_resource(const Ref<Resource> &p_res, Control *p_from) {
- Control *drag_control = memnew( Control );
- TextureRect *drag_preview = memnew( TextureRect );
- Label* label=memnew( Label );
+ Control *drag_control = memnew(Control);
+ TextureRect *drag_preview = memnew(TextureRect);
+ Label *label = memnew(Label);
Ref<Texture> preview;
{
//todo make proper previews
- Ref<ImageTexture> pic = gui_base->get_icon("FileBig","EditorIcons");
+ Ref<ImageTexture> pic = gui_base->get_icon("FileBig", "EditorIcons");
Image img = pic->get_data();
- img.resize(48,48); //meh
- Ref<ImageTexture> resized_pic = Ref<ImageTexture>( memnew( ImageTexture) );
+ img.resize(48, 48); //meh
+ Ref<ImageTexture> resized_pic = Ref<ImageTexture>(memnew(ImageTexture));
resized_pic->create_from_image(img);
- preview=resized_pic;
+ preview = resized_pic;
}
drag_preview->set_texture(preview);
drag_control->add_child(drag_preview);
if (p_res->get_path().is_resource_file()) {
label->set_text(p_res->get_path().get_file());
- } else if (p_res->get_name()!="") {
+ } else if (p_res->get_name() != "") {
label->set_text(p_res->get_name());
} else {
label->set_text(p_res->get_class());
-
}
drag_control->add_child(label);
p_from->set_drag_preview(drag_control); //wait until it enters scene
- label->set_pos( Point2((preview->get_width()-label->get_minimum_size().width)/2,preview->get_height()) );
+ label->set_pos(Point2((preview->get_width() - label->get_minimum_size().width) / 2, preview->get_height()));
Dictionary drag_data;
- drag_data["type"]="resource";
- drag_data["resource"]=p_res;
- drag_data["from"]=p_from;
-
+ drag_data["type"] = "resource";
+ drag_data["resource"] = p_res;
+ drag_data["from"] = p_from;
return drag_data;
-
}
-Variant EditorNode::drag_files(const Vector<String>& p_files, Control *p_from){
+Variant EditorNode::drag_files(const Vector<String> &p_files, Control *p_from) {
- VBoxContainer *files = memnew( VBoxContainer );
+ VBoxContainer *files = memnew(VBoxContainer);
- int max_files=6;
+ int max_files = 6;
- for(int i=0;i<MIN(max_files,p_files.size());i++) {
+ for (int i = 0; i < MIN(max_files, p_files.size()); i++) {
- Label* label=memnew( Label );
+ Label *label = memnew(Label);
label->set_text(p_files[i].get_file());
files->add_child(label);
}
- if (p_files.size()>max_files) {
+ if (p_files.size() > max_files) {
- Label* label=memnew( Label );
- label->set_text(vformat(TTR("%d more file(s)"), p_files.size()-max_files));
+ Label *label = memnew(Label);
+ label->set_text(vformat(TTR("%d more file(s)"), p_files.size() - max_files));
files->add_child(label);
-
}
Dictionary drag_data;
- drag_data["type"]="files";
- drag_data["files"]=p_files;
- drag_data["from"]=p_from;
+ drag_data["type"] = "files";
+ drag_data["files"] = p_files;
+ drag_data["from"] = p_from;
p_from->set_drag_preview(files); //wait until it enters scene
return drag_data;
-
}
-Variant EditorNode::drag_files_and_dirs(const Vector<String>& p_files, Control *p_from){
+Variant EditorNode::drag_files_and_dirs(const Vector<String> &p_files, Control *p_from) {
- VBoxContainer *files = memnew( VBoxContainer );
+ VBoxContainer *files = memnew(VBoxContainer);
- int max_files=6;
+ int max_files = 6;
- for(int i=0;i<MIN(max_files,p_files.size());i++) {
+ for (int i = 0; i < MIN(max_files, p_files.size()); i++) {
- Label* label=memnew( Label );
+ Label *label = memnew(Label);
label->set_text(p_files[i].get_file());
files->add_child(label);
}
- if (p_files.size()>max_files) {
+ if (p_files.size() > max_files) {
- Label* label=memnew( Label );
- label->set_text(vformat(TTR("%d more file(s) or folder(s)"), p_files.size()-max_files));
+ Label *label = memnew(Label);
+ label->set_text(vformat(TTR("%d more file(s) or folder(s)"), p_files.size() - max_files));
files->add_child(label);
-
}
Dictionary drag_data;
- drag_data["type"]="files_and_dirs";
- drag_data["files"]=p_files;
- drag_data["from"]=p_from;
+ drag_data["type"] = "files_and_dirs";
+ drag_data["files"] = p_files;
+ drag_data["from"] = p_from;
p_from->set_drag_preview(files); //wait until it enters scene
return drag_data;
-
}
-
-void EditorNode::_dropped_files(const Vector<String>& p_files,int p_screen) {
+void EditorNode::_dropped_files(const Vector<String> &p_files, int p_screen) {
String cur_path = filesystem_dock->get_current_path();
-// for(int i=0;i<EditorImportExport::get_singleton()->get_import_plugin_count();i++) {
-// EditorImportExport::get_singleton()->get_import_plugin(i)->import_from_drop(p_files,cur_path);
-// }
+ // for(int i=0;i<EditorImportExport::get_singleton()->get_import_plugin_count();i++) {
+ // EditorImportExport::get_singleton()->get_import_plugin(i)->import_from_drop(p_files,cur_path);
+ // }
}
-void EditorNode::_file_access_close_error_notify(const String& p_str) {
+void EditorNode::_file_access_close_error_notify(const String &p_str) {
- add_io_error("Unable to write to file '"+p_str+"', file in use, locked or lacking permissions.");
+ add_io_error("Unable to write to file '" + p_str + "', file in use, locked or lacking permissions.");
}
-
-void EditorNode::reload_scene(const String& p_path) {
-
+void EditorNode::reload_scene(const String &p_path) {
//first of all, reload textures as they might have changed on disk
List<Ref<Resource> > cached;
ResourceCache::get_cached_resources(&cached);
List<Ref<Resource> > to_clear; //clear internal resources from previous scene from being used
- for(List<Ref<Resource> >::Element *E=cached.front();E;E=E->next()) {
+ for (List<Ref<Resource> >::Element *E = cached.front(); E; E = E->next()) {
- if (E->get()->get_path().begins_with(p_path+"::")) //subresources of existing scene
+ if (E->get()->get_path().begins_with(p_path + "::")) //subresources of existing scene
to_clear.push_back(E->get());
if (!E->get()->cast_to<Texture>())
@@ -4906,30 +4629,29 @@ void EditorNode::reload_scene(const String& p_path) {
if (!FileAccess::exists(E->get()->get_path()))
continue;
uint64_t mt = FileAccess::get_modified_time(E->get()->get_path());
- if (mt!=E->get()->get_last_modified_time()) {
+ if (mt != E->get()->get_last_modified_time()) {
E->get()->reload_from_file();
}
}
//so reload reloads everything, clear subresources of previous scene
- while(to_clear.front()) {
+ while (to_clear.front()) {
to_clear.front()->get()->set_path("");
to_clear.pop_front();
}
- int scene_idx=-1;
- for(int i=0;i<editor_data.get_edited_scene_count();i++) {
+ int scene_idx = -1;
+ for (int i = 0; i < editor_data.get_edited_scene_count(); i++) {
- if (editor_data.get_scene_path(i)==p_path) {
- scene_idx=i;
+ if (editor_data.get_scene_path(i) == p_path) {
+ scene_idx = i;
break;
}
}
int current_tab = editor_data.get_edited_scene();
-
- if (scene_idx==-1) {
+ if (scene_idx == -1) {
if (get_edited_scene()) {
//scene is not open, so at it might be instanced, just refresh, set tab to itself and it will reload
set_current_scene(current_tab);
@@ -4938,11 +4660,9 @@ void EditorNode::reload_scene(const String& p_path) {
return;
}
-
- if (current_tab==scene_idx) {
+ if (current_tab == scene_idx) {
editor_data.apply_changes_in_editors();
_set_scene_metadata(p_path);
-
}
//remove scene
_remove_scene(scene_idx);
@@ -4956,122 +4676,116 @@ void EditorNode::reload_scene(const String& p_path) {
_scene_tab_changed(current_tab);
}
-int EditorNode::plugin_init_callback_count=0;
+int EditorNode::plugin_init_callback_count = 0;
void EditorNode::add_plugin_init_callback(EditorPluginInitializeCallback p_callback) {
- ERR_FAIL_COND(plugin_init_callback_count==MAX_INIT_CALLBACKS);
+ ERR_FAIL_COND(plugin_init_callback_count == MAX_INIT_CALLBACKS);
- plugin_init_callbacks[plugin_init_callback_count++]=p_callback;
+ plugin_init_callbacks[plugin_init_callback_count++] = p_callback;
}
EditorPluginInitializeCallback EditorNode::plugin_init_callbacks[EditorNode::MAX_INIT_CALLBACKS];
-
-int EditorNode::build_callback_count=0;
+int EditorNode::build_callback_count = 0;
void EditorNode::add_build_callback(EditorBuildCallback p_callback) {
- ERR_FAIL_COND(build_callback_count==MAX_INIT_CALLBACKS);
+ ERR_FAIL_COND(build_callback_count == MAX_INIT_CALLBACKS);
- build_callbacks[build_callback_count++]=p_callback;
+ build_callbacks[build_callback_count++] = p_callback;
}
EditorPluginInitializeCallback EditorNode::build_callbacks[EditorNode::MAX_BUILD_CALLBACKS];
void EditorNode::_call_build() {
- for(int i=0;i<build_callback_count;i++) {
+ for (int i = 0; i < build_callback_count; i++) {
build_callbacks[i]();
}
}
-
-void EditorNode::_inherit_imported(const String& p_action) {
+void EditorNode::_inherit_imported(const String &p_action) {
open_imported->hide();
- load_scene(open_import_request,true,true);
-
+ load_scene(open_import_request, true, true);
}
void EditorNode::_open_imported() {
- load_scene(open_import_request,true,false,true,true);
+ load_scene(open_import_request, true, false, true, true);
}
void EditorNode::_bind_methods() {
-
- ClassDB::bind_method("_menu_option",&EditorNode::_menu_option);
- ClassDB::bind_method("_menu_confirm_current",&EditorNode::_menu_confirm_current);
- ClassDB::bind_method("_dialog_action",&EditorNode::_dialog_action);
- ClassDB::bind_method("_resource_selected",&EditorNode::_resource_selected,DEFVAL(""));
- ClassDB::bind_method("_property_editor_forward",&EditorNode::_property_editor_forward);
- ClassDB::bind_method("_property_editor_back",&EditorNode::_property_editor_back);
- ClassDB::bind_method("_editor_select",&EditorNode::_editor_select);
- ClassDB::bind_method("_node_renamed",&EditorNode::_node_renamed);
- ClassDB::bind_method("edit_node",&EditorNode::edit_node);
- ClassDB::bind_method("_imported",&EditorNode::_imported);
- ClassDB::bind_method("_unhandled_input",&EditorNode::_unhandled_input);
-
- ClassDB::bind_method("_get_scene_metadata",&EditorNode::_get_scene_metadata);
- ClassDB::bind_method("set_edited_scene",&EditorNode::set_edited_scene);
- ClassDB::bind_method("open_request",&EditorNode::open_request);
- ClassDB::bind_method("_instance_request",&EditorNode::_instance_request);
- ClassDB::bind_method("update_keying",&EditorNode::update_keying);
- ClassDB::bind_method("_property_keyed",&EditorNode::_property_keyed);
- ClassDB::bind_method("_transform_keyed",&EditorNode::_transform_keyed);
- ClassDB::bind_method("_close_messages",&EditorNode::_close_messages);
- ClassDB::bind_method("_show_messages",&EditorNode::_show_messages);
- ClassDB::bind_method("_vp_resized",&EditorNode::_vp_resized);
- ClassDB::bind_method("_quick_opened",&EditorNode::_quick_opened);
- ClassDB::bind_method("_quick_run",&EditorNode::_quick_run);
-
- ClassDB::bind_method("_resource_created",&EditorNode::_resource_created);
-
- ClassDB::bind_method("_import_action",&EditorNode::_import_action);
+ ClassDB::bind_method("_menu_option", &EditorNode::_menu_option);
+ ClassDB::bind_method("_menu_confirm_current", &EditorNode::_menu_confirm_current);
+ ClassDB::bind_method("_dialog_action", &EditorNode::_dialog_action);
+ ClassDB::bind_method("_resource_selected", &EditorNode::_resource_selected, DEFVAL(""));
+ ClassDB::bind_method("_property_editor_forward", &EditorNode::_property_editor_forward);
+ ClassDB::bind_method("_property_editor_back", &EditorNode::_property_editor_back);
+ ClassDB::bind_method("_editor_select", &EditorNode::_editor_select);
+ ClassDB::bind_method("_node_renamed", &EditorNode::_node_renamed);
+ ClassDB::bind_method("edit_node", &EditorNode::edit_node);
+ ClassDB::bind_method("_imported", &EditorNode::_imported);
+ ClassDB::bind_method("_unhandled_input", &EditorNode::_unhandled_input);
+
+ ClassDB::bind_method("_get_scene_metadata", &EditorNode::_get_scene_metadata);
+ ClassDB::bind_method("set_edited_scene", &EditorNode::set_edited_scene);
+ ClassDB::bind_method("open_request", &EditorNode::open_request);
+ ClassDB::bind_method("_instance_request", &EditorNode::_instance_request);
+ ClassDB::bind_method("update_keying", &EditorNode::update_keying);
+ ClassDB::bind_method("_property_keyed", &EditorNode::_property_keyed);
+ ClassDB::bind_method("_transform_keyed", &EditorNode::_transform_keyed);
+ ClassDB::bind_method("_close_messages", &EditorNode::_close_messages);
+ ClassDB::bind_method("_show_messages", &EditorNode::_show_messages);
+ ClassDB::bind_method("_vp_resized", &EditorNode::_vp_resized);
+ ClassDB::bind_method("_quick_opened", &EditorNode::_quick_opened);
+ ClassDB::bind_method("_quick_run", &EditorNode::_quick_run);
+
+ ClassDB::bind_method("_resource_created", &EditorNode::_resource_created);
+
+ ClassDB::bind_method("_import_action", &EditorNode::_import_action);
//ClassDB::bind_method("_import",&EditorNode::_import);
//ClassDB::bind_method("_import_conflicts_solved",&EditorNode::_import_conflicts_solved);
- ClassDB::bind_method("_open_recent_scene",&EditorNode::_open_recent_scene);
+ ClassDB::bind_method("_open_recent_scene", &EditorNode::_open_recent_scene);
//ClassDB::bind_method("_open_recent_scene_confirm",&EditorNode::_open_recent_scene_confirm);
- ClassDB::bind_method("_save_optimized",&EditorNode::_save_optimized);
-
- ClassDB::bind_method("stop_child_process",&EditorNode::stop_child_process);
-
- ClassDB::bind_method("_sources_changed",&EditorNode::_sources_changed);
- ClassDB::bind_method("_fs_changed",&EditorNode::_fs_changed);
- ClassDB::bind_method("_dock_select_draw",&EditorNode::_dock_select_draw);
- ClassDB::bind_method("_dock_select_input",&EditorNode::_dock_select_input);
- ClassDB::bind_method("_dock_pre_popup",&EditorNode::_dock_pre_popup);
- ClassDB::bind_method("_dock_split_dragged",&EditorNode::_dock_split_dragged);
- ClassDB::bind_method("_save_docks",&EditorNode::_save_docks);
- ClassDB::bind_method("_dock_popup_exit",&EditorNode::_dock_popup_exit);
- ClassDB::bind_method("_dock_move_left",&EditorNode::_dock_move_left);
- ClassDB::bind_method("_dock_move_right",&EditorNode::_dock_move_right);
-
- ClassDB::bind_method("_layout_menu_option",&EditorNode::_layout_menu_option);
-
- ClassDB::bind_method("set_current_scene",&EditorNode::set_current_scene);
- ClassDB::bind_method("set_current_version",&EditorNode::set_current_version);
- ClassDB::bind_method("_scene_tab_changed",&EditorNode::_scene_tab_changed);
- ClassDB::bind_method("_scene_tab_closed",&EditorNode::_scene_tab_closed);
- ClassDB::bind_method("_scene_tab_script_edited",&EditorNode::_scene_tab_script_edited);
- ClassDB::bind_method("_set_main_scene_state",&EditorNode::_set_main_scene_state);
- ClassDB::bind_method("_update_scene_tabs",&EditorNode::_update_scene_tabs);
-
- ClassDB::bind_method("_prepare_history",&EditorNode::_prepare_history);
- ClassDB::bind_method("_select_history",&EditorNode::_select_history);
-
- ClassDB::bind_method("_toggle_search_bar",&EditorNode::_toggle_search_bar);
- ClassDB::bind_method("_clear_search_box",&EditorNode::_clear_search_box);
- ClassDB::bind_method("_clear_undo_history",&EditorNode::_clear_undo_history);
- ClassDB::bind_method("_dropped_files",&EditorNode::_dropped_files);
- ClassDB::bind_method("_toggle_distraction_free_mode",&EditorNode::_toggle_distraction_free_mode);
-
-
-
-// ClassDB::bind_method(D_METHOD("add_editor_import_plugin", "plugin"), &EditorNode::add_editor_import_plugin);
+ ClassDB::bind_method("_save_optimized", &EditorNode::_save_optimized);
+
+ ClassDB::bind_method("stop_child_process", &EditorNode::stop_child_process);
+
+ ClassDB::bind_method("_sources_changed", &EditorNode::_sources_changed);
+ ClassDB::bind_method("_fs_changed", &EditorNode::_fs_changed);
+ ClassDB::bind_method("_dock_select_draw", &EditorNode::_dock_select_draw);
+ ClassDB::bind_method("_dock_select_input", &EditorNode::_dock_select_input);
+ ClassDB::bind_method("_dock_pre_popup", &EditorNode::_dock_pre_popup);
+ ClassDB::bind_method("_dock_split_dragged", &EditorNode::_dock_split_dragged);
+ ClassDB::bind_method("_save_docks", &EditorNode::_save_docks);
+ ClassDB::bind_method("_dock_popup_exit", &EditorNode::_dock_popup_exit);
+ ClassDB::bind_method("_dock_move_left", &EditorNode::_dock_move_left);
+ ClassDB::bind_method("_dock_move_right", &EditorNode::_dock_move_right);
+
+ ClassDB::bind_method("_layout_menu_option", &EditorNode::_layout_menu_option);
+
+ ClassDB::bind_method("set_current_scene", &EditorNode::set_current_scene);
+ ClassDB::bind_method("set_current_version", &EditorNode::set_current_version);
+ ClassDB::bind_method("_scene_tab_changed", &EditorNode::_scene_tab_changed);
+ ClassDB::bind_method("_scene_tab_closed", &EditorNode::_scene_tab_closed);
+ ClassDB::bind_method("_scene_tab_script_edited", &EditorNode::_scene_tab_script_edited);
+ ClassDB::bind_method("_set_main_scene_state", &EditorNode::_set_main_scene_state);
+ ClassDB::bind_method("_update_scene_tabs", &EditorNode::_update_scene_tabs);
+
+ ClassDB::bind_method("_prepare_history", &EditorNode::_prepare_history);
+ ClassDB::bind_method("_select_history", &EditorNode::_select_history);
+
+ ClassDB::bind_method("_toggle_search_bar", &EditorNode::_toggle_search_bar);
+ ClassDB::bind_method("_clear_search_box", &EditorNode::_clear_search_box);
+ ClassDB::bind_method("_clear_undo_history", &EditorNode::_clear_undo_history);
+ ClassDB::bind_method("_dropped_files", &EditorNode::_dropped_files);
+ ClassDB::bind_method("_toggle_distraction_free_mode", &EditorNode::_toggle_distraction_free_mode);
+
+ // ClassDB::bind_method(D_METHOD("add_editor_import_plugin", "plugin"), &EditorNode::add_editor_import_plugin);
//ClassDB::bind_method(D_METHOD("remove_editor_import_plugin", "plugin"), &EditorNode::remove_editor_import_plugin);
ClassDB::bind_method(D_METHOD("get_gui_base"), &EditorNode::get_gui_base);
ClassDB::bind_method(D_METHOD("_bottom_panel_switch"), &EditorNode::_bottom_panel_switch);
@@ -5079,25 +4793,22 @@ void EditorNode::_bind_methods() {
ClassDB::bind_method(D_METHOD("_open_imported"), &EditorNode::_open_imported);
ClassDB::bind_method(D_METHOD("_inherit_imported"), &EditorNode::_inherit_imported);
- ADD_SIGNAL( MethodInfo("play_pressed") );
- ADD_SIGNAL( MethodInfo("pause_pressed") );
- ADD_SIGNAL( MethodInfo("stop_pressed") );
- ADD_SIGNAL( MethodInfo("request_help") );
- ADD_SIGNAL( MethodInfo("script_add_function_request",PropertyInfo(Variant::OBJECT,"obj"),PropertyInfo(Variant::STRING,"function"),PropertyInfo(Variant::POOL_STRING_ARRAY,"args")) );
- ADD_SIGNAL( MethodInfo("resource_saved",PropertyInfo(Variant::OBJECT,"obj")) );
-
-
-
+ ADD_SIGNAL(MethodInfo("play_pressed"));
+ ADD_SIGNAL(MethodInfo("pause_pressed"));
+ ADD_SIGNAL(MethodInfo("stop_pressed"));
+ ADD_SIGNAL(MethodInfo("request_help"));
+ ADD_SIGNAL(MethodInfo("script_add_function_request", PropertyInfo(Variant::OBJECT, "obj"), PropertyInfo(Variant::STRING, "function"), PropertyInfo(Variant::POOL_STRING_ARRAY, "args")));
+ ADD_SIGNAL(MethodInfo("resource_saved", PropertyInfo(Variant::OBJECT, "obj")));
}
-static Node* _resource_get_edited_scene() {
+static Node *_resource_get_edited_scene() {
return EditorNode::get_singleton()->get_edited_scene();
}
EditorNode::EditorNode() {
- Resource::_get_local_scene_func=_resource_get_edited_scene;
+ Resource::_get_local_scene_func = _resource_get_edited_scene;
VisualServer::get_singleton()->textures_keep_original(true);
@@ -5116,15 +4827,13 @@ EditorNode::EditorNode() {
id->set_custom_mouse_cursor(RES());
}
-
- singleton=this;
- exiting=false;
- last_checked_version=0;
- changing_scene=false;
- _initializing_addons=false;
+ singleton = this;
+ exiting = false;
+ last_checked_version = 0;
+ changing_scene = false;
+ _initializing_addons = false;
docks_visible = true;
-
FileAccess::set_backup_save(true);
TranslationServer::get_singleton()->set_enabled(false);
@@ -5135,35 +4844,33 @@ EditorNode::EditorNode() {
bool use_single_dock_column = false;
{
int dpi_mode = EditorSettings::get_singleton()->get("interface/hidpi_mode");
- if (dpi_mode==0) {
- editor_set_scale( OS::get_singleton()->get_screen_dpi(0) > 150 && OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x>2000 ? 2.0 : 1.0 );
+ if (dpi_mode == 0) {
+ editor_set_scale(OS::get_singleton()->get_screen_dpi(0) > 150 && OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x > 2000 ? 2.0 : 1.0);
- use_single_dock_column = OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x<1200;
+ use_single_dock_column = OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x < 1200;
- } else if (dpi_mode==1) {
+ } else if (dpi_mode == 1) {
editor_set_scale(0.75);
- } else if (dpi_mode==2) {
+ } else if (dpi_mode == 2) {
editor_set_scale(1.0);
- } else if (dpi_mode==3) {
+ } else if (dpi_mode == 3) {
editor_set_scale(1.5);
- } else if (dpi_mode==4) {
+ } else if (dpi_mode == 4) {
editor_set_scale(2.0);
}
}
-
ResourceLoader::set_abort_on_missing_resources(false);
FileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
EditorFileDialog::set_default_show_hidden_files(EditorSettings::get_singleton()->get("filesystem/file_dialog/show_hidden_files"));
EditorFileDialog::set_default_display_mode((EditorFileDialog::DisplayMode)EditorSettings::get_singleton()->get("filesystem/file_dialog/display_mode").operator int());
- ResourceLoader::set_error_notify_func(this,_load_error_notify);
- ResourceLoader::set_dependency_error_notify_func(this,_dependency_error_report);
+ ResourceLoader::set_error_notify_func(this, _load_error_notify);
+ ResourceLoader::set_dependency_error_notify_func(this, _dependency_error_report);
ResourceLoader::set_timestamp_on_load(true);
ResourceSaver::set_timestamp_on_save(true);
-
- { //register importers at the begining, so dialogs are created with the right extensions
+ { //register importers at the begining, so dialogs are created with the right extensions
Ref<ResourceImporterTexture> import_texture;
import_texture.instance();
ResourceFormatImporter::get_singleton()->add_importer(import_texture);
@@ -5176,7 +4883,6 @@ EditorNode::EditorNode() {
import_wav.instance();
ResourceFormatImporter::get_singleton()->add_importer(import_wav);
-
Ref<ResourceImporterOBJ> import_obj;
import_obj.instance();
ResourceFormatImporter::get_singleton()->add_importer(import_obj);
@@ -5190,60 +4896,58 @@ EditorNode::EditorNode() {
import_collada.instance();
import_scene->add_importer(import_collada);
}
-
}
_pvrtc_register_compressors();
- editor_selection = memnew( EditorSelection );
+ editor_selection = memnew(EditorSelection);
- EditorFileSystem *efs = memnew( EditorFileSystem );
+ EditorFileSystem *efs = memnew(EditorFileSystem);
add_child(efs);
//used for previews
- FileDialog::get_icon_func=_file_dialog_get_icon;
- FileDialog::register_func=_file_dialog_register;
- FileDialog::unregister_func=_file_dialog_unregister;
+ FileDialog::get_icon_func = _file_dialog_get_icon;
+ FileDialog::register_func = _file_dialog_register;
+ FileDialog::unregister_func = _file_dialog_unregister;
- EditorFileDialog::get_icon_func=_file_dialog_get_icon;
- EditorFileDialog::register_func=_editor_file_dialog_register;
- EditorFileDialog::unregister_func=_editor_file_dialog_unregister;
+ EditorFileDialog::get_icon_func = _file_dialog_get_icon;
+ EditorFileDialog::register_func = _editor_file_dialog_register;
+ EditorFileDialog::unregister_func = _editor_file_dialog_unregister;
- editor_export = memnew( EditorExport );
+ editor_export = memnew(EditorExport);
add_child(editor_export);
-
register_exporters();
- GLOBAL_DEF("editor/main_run_args","");
+ GLOBAL_DEF("editor/main_run_args", "");
- ClassDB::set_class_enabled("CollisionShape",true);
- ClassDB::set_class_enabled("CollisionShape2D",true);
- ClassDB::set_class_enabled("CollisionPolygon2D",true);
+ ClassDB::set_class_enabled("CollisionShape", true);
+ ClassDB::set_class_enabled("CollisionShape2D", true);
+ ClassDB::set_class_enabled("CollisionPolygon2D", true);
- Control *theme_base = memnew( Control );
+ Control *theme_base = memnew(Control);
add_child(theme_base);
theme_base->set_area_as_parent_rect();
- gui_base = memnew( Panel );
+ gui_base = memnew(Panel);
theme_base->add_child(gui_base);
gui_base->set_area_as_parent_rect();
Ref<Theme> theme = create_editor_theme();
- theme_base->set_theme( theme );
+ theme_base->set_theme(theme);
gui_base->set_theme(create_custom_theme());
- resource_preview = memnew( EditorResourcePreview );
+ resource_preview = memnew(EditorResourcePreview);
add_child(resource_preview);
- progress_dialog = memnew( ProgressDialog );
+ progress_dialog = memnew(ProgressDialog);
gui_base->add_child(progress_dialog);
// take up all screen
- gui_base->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
- gui_base->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
- gui_base->set_end( Point2(0,0) );
+ gui_base->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
+ gui_base->set_anchor(MARGIN_BOTTOM, Control::ANCHOR_END);
+ gui_base->set_end(Point2(0, 0));
- main_vbox = memnew( VBoxContainer );
+ main_vbox = memnew(VBoxContainer);
gui_base->add_child(main_vbox);
main_vbox->set_area_as_parent_rect(8);
@@ -5265,175 +4969,164 @@ EditorNode::EditorNode() {
top_dark_panel->add_child(top_dark_vb);
#endif
-
-
- menu_hb = memnew( HBoxContainer );
+ menu_hb = memnew(HBoxContainer);
main_vbox->add_child(menu_hb);
//top_dark_vb->add_child(scene_tabs);
//left
- left_l_hsplit = memnew( HSplitContainer );
+ left_l_hsplit = memnew(HSplitContainer);
main_vbox->add_child(left_l_hsplit);
left_l_hsplit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- left_l_vsplit = memnew( VSplitContainer );
+ left_l_vsplit = memnew(VSplitContainer);
left_l_hsplit->add_child(left_l_vsplit);
- dock_slot[DOCK_SLOT_LEFT_UL]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_LEFT_UL] = memnew(TabContainer);
left_l_vsplit->add_child(dock_slot[DOCK_SLOT_LEFT_UL]);
- dock_slot[DOCK_SLOT_LEFT_BL]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_LEFT_BL] = memnew(TabContainer);
left_l_vsplit->add_child(dock_slot[DOCK_SLOT_LEFT_BL]);
left_l_vsplit->hide();
dock_slot[DOCK_SLOT_LEFT_UL]->hide();
dock_slot[DOCK_SLOT_LEFT_BL]->hide();
- left_r_hsplit = memnew( HSplitContainer );
+ left_r_hsplit = memnew(HSplitContainer);
left_l_hsplit->add_child(left_r_hsplit);
- left_r_vsplit = memnew( VSplitContainer );
+ left_r_vsplit = memnew(VSplitContainer);
left_r_hsplit->add_child(left_r_vsplit);
- dock_slot[DOCK_SLOT_LEFT_UR]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_LEFT_UR] = memnew(TabContainer);
left_r_vsplit->add_child(dock_slot[DOCK_SLOT_LEFT_UR]);
- dock_slot[DOCK_SLOT_LEFT_BR]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_LEFT_BR] = memnew(TabContainer);
left_r_vsplit->add_child(dock_slot[DOCK_SLOT_LEFT_BR]);
//left_r_vsplit->hide();
//dock_slot[DOCK_SLOT_LEFT_UR]->hide();
//dock_slot[DOCK_SLOT_LEFT_BR]->hide();
-
- main_hsplit = memnew( HSplitContainer );
+ main_hsplit = memnew(HSplitContainer);
left_r_hsplit->add_child(main_hsplit);
//main_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- VBoxContainer * center_vb = memnew( VBoxContainer);
+ VBoxContainer *center_vb = memnew(VBoxContainer);
main_hsplit->add_child(center_vb);
center_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
- center_split = memnew( VSplitContainer );
+ center_split = memnew(VSplitContainer);
//main_hsplit->add_child(center_split);
center_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
center_split->set_collapsed(false);
center_vb->add_child(center_split);
- right_hsplit = memnew( HSplitContainer );
+ right_hsplit = memnew(HSplitContainer);
main_hsplit->add_child(right_hsplit);
- right_l_vsplit = memnew( VSplitContainer );
+ right_l_vsplit = memnew(VSplitContainer);
right_hsplit->add_child(right_l_vsplit);
- dock_slot[DOCK_SLOT_RIGHT_UL]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_RIGHT_UL] = memnew(TabContainer);
right_l_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_UL]);
- dock_slot[DOCK_SLOT_RIGHT_BL]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_RIGHT_BL] = memnew(TabContainer);
right_l_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_BL]);
//right_l_vsplit->hide();
//dock_slot[DOCK_SLOT_RIGHT_UL]->hide();
//dock_slot[DOCK_SLOT_RIGHT_BL]->hide();
- right_r_vsplit = memnew( VSplitContainer );
+ right_r_vsplit = memnew(VSplitContainer);
right_hsplit->add_child(right_r_vsplit);
- dock_slot[DOCK_SLOT_RIGHT_UR]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_RIGHT_UR] = memnew(TabContainer);
right_r_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_UR]);
- dock_slot[DOCK_SLOT_RIGHT_BR]=memnew( TabContainer );
+ dock_slot[DOCK_SLOT_RIGHT_BR] = memnew(TabContainer);
right_r_vsplit->add_child(dock_slot[DOCK_SLOT_RIGHT_BR]);
right_r_vsplit->hide();
dock_slot[DOCK_SLOT_RIGHT_UR]->hide();
dock_slot[DOCK_SLOT_RIGHT_BR]->hide();
- left_l_vsplit->connect("dragged",this,"_dock_split_dragged");
- left_r_vsplit->connect("dragged",this,"_dock_split_dragged");
- right_l_vsplit->connect("dragged",this,"_dock_split_dragged");
- right_r_vsplit->connect("dragged",this,"_dock_split_dragged");
-
- left_l_hsplit->connect("dragged",this,"_dock_split_dragged");
- left_r_hsplit->connect("dragged",this,"_dock_split_dragged");
- main_hsplit->connect("dragged",this,"_dock_split_dragged");
- right_hsplit->connect("dragged",this,"_dock_split_dragged");
-
+ left_l_vsplit->connect("dragged", this, "_dock_split_dragged");
+ left_r_vsplit->connect("dragged", this, "_dock_split_dragged");
+ right_l_vsplit->connect("dragged", this, "_dock_split_dragged");
+ right_r_vsplit->connect("dragged", this, "_dock_split_dragged");
+ left_l_hsplit->connect("dragged", this, "_dock_split_dragged");
+ left_r_hsplit->connect("dragged", this, "_dock_split_dragged");
+ main_hsplit->connect("dragged", this, "_dock_split_dragged");
+ right_hsplit->connect("dragged", this, "_dock_split_dragged");
- dock_select_popoup = memnew( PopupPanel );
+ dock_select_popoup = memnew(PopupPanel);
gui_base->add_child(dock_select_popoup);
- VBoxContainer *dock_vb = memnew( VBoxContainer );
+ VBoxContainer *dock_vb = memnew(VBoxContainer);
dock_select_popoup->add_child(dock_vb);
- HBoxContainer *dock_hb = memnew( HBoxContainer);
- dock_tab_move_left = memnew( ToolButton );
- dock_tab_move_left->set_icon(theme->get_icon("Back","EditorIcons"));
+ HBoxContainer *dock_hb = memnew(HBoxContainer);
+ dock_tab_move_left = memnew(ToolButton);
+ dock_tab_move_left->set_icon(theme->get_icon("Back", "EditorIcons"));
dock_tab_move_left->set_focus_mode(Control::FOCUS_NONE);
- dock_tab_move_left->connect("pressed",this,"_dock_move_left");
+ dock_tab_move_left->connect("pressed", this, "_dock_move_left");
//dock_tab_move_left->set_h_size_flags(Control::SIZE_EXPAND_FILL);
dock_hb->add_child(dock_tab_move_left);
dock_hb->add_spacer();
- dock_tab_move_right = memnew( ToolButton );
- dock_tab_move_right->set_icon(theme->get_icon("Forward","EditorIcons"));
+ dock_tab_move_right = memnew(ToolButton);
+ dock_tab_move_right->set_icon(theme->get_icon("Forward", "EditorIcons"));
dock_tab_move_right->set_focus_mode(Control::FOCUS_NONE);
- dock_tab_move_right->connect("pressed",this,"_dock_move_right");
+ dock_tab_move_right->connect("pressed", this, "_dock_move_right");
//dock_tab_move_right->set_h_size_flags(Control::SIZE_EXPAND_FILL);
dock_hb->add_child(dock_tab_move_right);
dock_vb->add_child(dock_hb);
- dock_select = memnew( Control );
- dock_select->set_custom_minimum_size(Size2(128,64)*EDSCALE);
- dock_select->connect("gui_input",this,"_dock_select_input");
- dock_select->connect("draw",this,"_dock_select_draw");
- dock_select->connect("mouse_exited",this,"_dock_popup_exit");
+ dock_select = memnew(Control);
+ dock_select->set_custom_minimum_size(Size2(128, 64) * EDSCALE);
+ dock_select->connect("gui_input", this, "_dock_select_input");
+ dock_select->connect("draw", this, "_dock_select_draw");
+ dock_select->connect("mouse_exited", this, "_dock_popup_exit");
dock_select->set_v_size_flags(Control::SIZE_EXPAND_FILL);
dock_vb->add_child(dock_select);
-
-
dock_select_popoup->set_as_minsize();
- dock_select_rect_over=-1;
- dock_popup_selected=-1;
+ dock_select_rect_over = -1;
+ dock_popup_selected = -1;
//dock_select_popoup->set_(Size2(20,20));
- for(int i=0;i<DOCK_SLOT_MAX;i++) {
- dock_slot[i]->set_custom_minimum_size(Size2(230,220)*EDSCALE);
+ for (int i = 0; i < DOCK_SLOT_MAX; i++) {
+ dock_slot[i]->set_custom_minimum_size(Size2(230, 220) * EDSCALE);
dock_slot[i]->set_v_size_flags(Control::SIZE_EXPAND_FILL);
dock_slot[i]->set_popup(dock_select_popoup);
- dock_slot[i]->connect("pre_popup_pressed",this,"_dock_pre_popup",varray(i));
+ dock_slot[i]->connect("pre_popup_pressed", this, "_dock_pre_popup", varray(i));
//dock_slot[i]->set_tab_align(TabContainer::ALIGN_LEFT);
}
- dock_drag_timer = memnew( Timer );
+ dock_drag_timer = memnew(Timer);
add_child(dock_drag_timer);
dock_drag_timer->set_wait_time(0.5);
dock_drag_timer->set_one_shot(true);
- dock_drag_timer->connect("timeout",this,"_save_docks");
+ dock_drag_timer->connect("timeout", this, "_save_docks");
- top_split = memnew( VSplitContainer );
+ top_split = memnew(VSplitContainer);
center_split->add_child(top_split);
top_split->set_v_size_flags(Control::SIZE_EXPAND_FILL);
top_split->set_collapsed(true);
- VBoxContainer *srt = memnew( VBoxContainer );
+ VBoxContainer *srt = memnew(VBoxContainer);
srt->set_v_size_flags(Control::SIZE_EXPAND_FILL);
top_split->add_child(srt);
- srt->add_constant_override("separation",0);
+ srt->add_constant_override("separation", 0);
-
-/* main_editor_tabs = memnew( Tabs );
+ /* main_editor_tabs = memnew( Tabs );
main_editor_tabs->connect("tab_changed",this,"_editor_select");
main_editor_tabs->set_tab_close_display_policy(Tabs::SHOW_NEVER);
*/
- scene_tabs=memnew( Tabs );
+ scene_tabs = memnew(Tabs);
scene_tabs->add_tab("unsaved");
scene_tabs->set_tab_align(Tabs::ALIGN_CENTER);
- scene_tabs->set_tab_close_display_policy( (bool(EDITOR_DEF("interface/always_show_close_button_in_scene_tabs", false)) ? Tabs::CLOSE_BUTTON_SHOW_ALWAYS : Tabs::CLOSE_BUTTON_SHOW_ACTIVE_ONLY) );
- scene_tabs->connect("tab_changed",this,"_scene_tab_changed");
- scene_tabs->connect("right_button_pressed",this,"_scene_tab_script_edited");
+ scene_tabs->set_tab_close_display_policy((bool(EDITOR_DEF("interface/always_show_close_button_in_scene_tabs", false)) ? Tabs::CLOSE_BUTTON_SHOW_ALWAYS : Tabs::CLOSE_BUTTON_SHOW_ACTIVE_ONLY));
+ scene_tabs->connect("tab_changed", this, "_scene_tab_changed");
+ scene_tabs->connect("right_button_pressed", this, "_scene_tab_script_edited");
scene_tabs->connect("tab_close", this, "_scene_tab_closed");
srt->add_child(scene_tabs);
- scene_root_parent = memnew( PanelContainer );
- scene_root_parent->set_custom_minimum_size(Size2(0,80)*EDSCALE);
-
-
+ scene_root_parent = memnew(PanelContainer);
+ scene_root_parent->set_custom_minimum_size(Size2(0, 80) * EDSCALE);
//Ref<StyleBox> sp = scene_root_parent->get_stylebox("panel","TabContainer");
//scene_root_parent->add_style_override("panel",sp);
-
/*scene_root_parent->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
scene_root_parent->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
scene_root_parent->set_begin( Point2( 0, 0) );
@@ -5441,133 +5134,122 @@ EditorNode::EditorNode() {
srt->add_child(scene_root_parent);
scene_root_parent->set_v_size_flags(Control::SIZE_EXPAND_FILL);
-
- scene_root = memnew( Viewport );
+ scene_root = memnew(Viewport);
scene_root->set_disable_3d(true);
-
-
//scene_root_base->add_child(scene_root);
//scene_root->set_meta("_editor_disable_input",true);
- VisualServer::get_singleton()->viewport_set_hide_scenario(scene_root->get_viewport_rid(),true);
+ VisualServer::get_singleton()->viewport_set_hide_scenario(scene_root->get_viewport_rid(), true);
scene_root->set_disable_input(true);
scene_root->set_as_audio_listener_2d(true);
//scene_root->set_size_override(true,Size2(GlobalConfig::get_singleton()->get("display/width"),GlobalConfig::get_singleton()->get("display/height")));
//scene_root->set_world_2d( Ref<World2D>( memnew( World2D )) );
-
- viewport = memnew( VBoxContainer );
+ viewport = memnew(VBoxContainer);
viewport->set_v_size_flags(Control::SIZE_EXPAND_FILL);
/*for(int i=0;i<4;i++) {
viewport->set_margin(Margin(i),sp->get_margin(Margin(i)));
}*/
scene_root_parent->add_child(viewport);
-
-
- PanelContainer *top_region = memnew( PanelContainer );
- top_region->add_style_override("panel",gui_base->get_stylebox("hover","Button"));
- HBoxContainer *left_menu_hb = memnew( HBoxContainer );
+ PanelContainer *top_region = memnew(PanelContainer);
+ top_region->add_style_override("panel", gui_base->get_stylebox("hover", "Button"));
+ HBoxContainer *left_menu_hb = memnew(HBoxContainer);
top_region->add_child(left_menu_hb);
menu_hb->add_child(top_region);
PopupMenu *p;
-
-
- file_menu = memnew( MenuButton );
+ file_menu = memnew(MenuButton);
file_menu->set_text(TTR("Scene"));
//file_menu->set_icon(gui_base->get_icon("Save","EditorIcons"));
- left_menu_hb->add_child( file_menu );
+ left_menu_hb->add_child(file_menu);
- prev_scene = memnew( ToolButton );
- prev_scene->set_icon(gui_base->get_icon("PrevScene","EditorIcons"));
+ prev_scene = memnew(ToolButton);
+ prev_scene->set_icon(gui_base->get_icon("PrevScene", "EditorIcons"));
prev_scene->set_tooltip(TTR("Go to previously opened scene."));
prev_scene->set_disabled(true);
//left_menu_hb->add_child( prev_scene );
- prev_scene->connect("pressed",this,"_menu_option",make_binds(FILE_OPEN_PREV));
+ prev_scene->connect("pressed", this, "_menu_option", make_binds(FILE_OPEN_PREV));
gui_base->add_child(prev_scene);
- prev_scene->set_pos(Point2(3,24));
+ prev_scene->set_pos(Point2(3, 24));
prev_scene->hide();
-
-
- ED_SHORTCUT("editor/next_tab", TTR("Next tab"), KEY_MASK_CMD+KEY_TAB);
- ED_SHORTCUT("editor/prev_tab", TTR("Previous tab"), KEY_MASK_CMD+KEY_MASK_SHIFT+KEY_TAB);
- ED_SHORTCUT("editor/filter_files", TTR("Filter Files.."), KEY_MASK_ALT+KEY_MASK_CMD+KEY_P);
-
+ ED_SHORTCUT("editor/next_tab", TTR("Next tab"), KEY_MASK_CMD + KEY_TAB);
+ ED_SHORTCUT("editor/prev_tab", TTR("Previous tab"), KEY_MASK_CMD + KEY_MASK_SHIFT + KEY_TAB);
+ ED_SHORTCUT("editor/filter_files", TTR("Filter Files.."), KEY_MASK_ALT + KEY_MASK_CMD + KEY_P);
file_menu->set_tooltip(TTR("Operations with scene files."));
- p=file_menu->get_popup();
- p->add_shortcut(ED_SHORTCUT("editor/new_scene",TTR("New Scene")),FILE_NEW_SCENE);
- p->add_shortcut(ED_SHORTCUT("editor/new_inherited_scene",TTR("New Inherited Scene..")),FILE_NEW_INHERITED_SCENE);
- p->add_shortcut(ED_SHORTCUT("editor/open_scene",TTR("Open Scene.."),KEY_MASK_CMD+KEY_O),FILE_OPEN_SCENE);
+ p = file_menu->get_popup();
+ p->add_shortcut(ED_SHORTCUT("editor/new_scene", TTR("New Scene")), FILE_NEW_SCENE);
+ p->add_shortcut(ED_SHORTCUT("editor/new_inherited_scene", TTR("New Inherited Scene..")), FILE_NEW_INHERITED_SCENE);
+ p->add_shortcut(ED_SHORTCUT("editor/open_scene", TTR("Open Scene.."), KEY_MASK_CMD + KEY_O), FILE_OPEN_SCENE);
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("editor/save_scene",TTR("Save Scene"),KEY_MASK_CMD+KEY_S),FILE_SAVE_SCENE);
- p->add_shortcut(ED_SHORTCUT("editor/save_scene_as",TTR("Save Scene As.."),KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_S),FILE_SAVE_AS_SCENE);
- p->add_shortcut(ED_SHORTCUT("editor/save_all_scenes",TTR("Save all Scenes"),KEY_MASK_ALT+KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_S),FILE_SAVE_ALL_SCENES);
+ p->add_shortcut(ED_SHORTCUT("editor/save_scene", TTR("Save Scene"), KEY_MASK_CMD + KEY_S), FILE_SAVE_SCENE);
+ p->add_shortcut(ED_SHORTCUT("editor/save_scene_as", TTR("Save Scene As.."), KEY_MASK_SHIFT + KEY_MASK_CMD + KEY_S), FILE_SAVE_AS_SCENE);
+ p->add_shortcut(ED_SHORTCUT("editor/save_all_scenes", TTR("Save all Scenes"), KEY_MASK_ALT + KEY_MASK_SHIFT + KEY_MASK_CMD + KEY_S), FILE_SAVE_ALL_SCENES);
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("editor/close_scene",TTR("Close Scene"),KEY_MASK_SHIFT+KEY_MASK_CTRL+KEY_W),FILE_CLOSE);
+ p->add_shortcut(ED_SHORTCUT("editor/close_scene", TTR("Close Scene"), KEY_MASK_SHIFT + KEY_MASK_CTRL + KEY_W), FILE_CLOSE);
p->add_separator();
//p->add_shortcut(ED_SHORTCUT("editor/save_scene",TTR("Close Goto Prev. Scene")),FILE_OPEN_PREV,KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_P);
- p->add_submenu_item(TTR("Open Recent"),"RecentScenes",FILE_OPEN_RECENT);
+ p->add_submenu_item(TTR("Open Recent"), "RecentScenes", FILE_OPEN_RECENT);
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("editor/quick_open_scene",TTR("Quick Open Scene.."),KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_O),FILE_QUICK_OPEN_SCENE);
- p->add_shortcut(ED_SHORTCUT("editor/quick_open_script",TTR("Quick Open Script.."),KEY_MASK_ALT+KEY_MASK_CMD+KEY_O),FILE_QUICK_OPEN_SCRIPT);
+ p->add_shortcut(ED_SHORTCUT("editor/quick_open_scene", TTR("Quick Open Scene.."), KEY_MASK_SHIFT + KEY_MASK_CMD + KEY_O), FILE_QUICK_OPEN_SCENE);
+ p->add_shortcut(ED_SHORTCUT("editor/quick_open_script", TTR("Quick Open Script.."), KEY_MASK_ALT + KEY_MASK_CMD + KEY_O), FILE_QUICK_OPEN_SCRIPT);
p->add_separator();
- PopupMenu *pm_export = memnew(PopupMenu );
+ PopupMenu *pm_export = memnew(PopupMenu);
pm_export->set_name("Export");
p->add_child(pm_export);
- p->add_submenu_item(TTR("Convert To.."),"Export");
+ p->add_submenu_item(TTR("Convert To.."), "Export");
pm_export->add_separator();
pm_export->add_shortcut(ED_SHORTCUT("editor/convert_to_MeshLibrary", TTR("MeshLibrary..")), FILE_EXPORT_MESH_LIBRARY);
pm_export->add_shortcut(ED_SHORTCUT("editor/convert_to_TileSet", TTR("TileSet..")), FILE_EXPORT_TILESET);
- pm_export->connect("id_pressed",this,"_menu_option");
+ pm_export->connect("id_pressed", this, "_menu_option");
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("editor/undo", TTR("Undo"),KEY_MASK_CMD+KEY_Z),EDIT_UNDO,true);
- p->add_shortcut(ED_SHORTCUT("editor/redo", TTR("Redo"),KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_Z),EDIT_REDO,true);
+ p->add_shortcut(ED_SHORTCUT("editor/undo", TTR("Undo"), KEY_MASK_CMD + KEY_Z), EDIT_UNDO, true);
+ p->add_shortcut(ED_SHORTCUT("editor/redo", TTR("Redo"), KEY_MASK_SHIFT + KEY_MASK_CMD + KEY_Z), EDIT_REDO, true);
p->add_separator();
- p->add_item(TTR("Run Script"),FILE_RUN_SCRIPT,KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_R);
+ p->add_item(TTR("Run Script"), FILE_RUN_SCRIPT, KEY_MASK_SHIFT + KEY_MASK_CMD + KEY_R);
p->add_separator();
- p->add_item(TTR("Project Settings"),RUN_SETTINGS);
+ p->add_item(TTR("Project Settings"), RUN_SETTINGS);
p->add_separator();
- p->add_item(TTR("Revert Scene"),EDIT_REVERT);
+ p->add_item(TTR("Revert Scene"), EDIT_REVERT);
p->add_separator();
#ifdef OSX_ENABLED
- p->add_item(TTR("Quit to Project List"),RUN_PROJECT_MANAGER,KEY_MASK_SHIFT+KEY_MASK_ALT+KEY_Q);
+ p->add_item(TTR("Quit to Project List"), RUN_PROJECT_MANAGER, KEY_MASK_SHIFT + KEY_MASK_ALT + KEY_Q);
#else
- p->add_item(TTR("Quit to Project List"),RUN_PROJECT_MANAGER,KEY_MASK_SHIFT+KEY_MASK_CTRL+KEY_Q);
+ p->add_item(TTR("Quit to Project List"), RUN_PROJECT_MANAGER, KEY_MASK_SHIFT + KEY_MASK_CTRL + KEY_Q);
#endif
- p->add_item(TTR("Quit"),FILE_QUIT,KEY_MASK_CMD+KEY_Q);
+ p->add_item(TTR("Quit"), FILE_QUIT, KEY_MASK_CMD + KEY_Q);
- recent_scenes = memnew( PopupMenu );
+ recent_scenes = memnew(PopupMenu);
recent_scenes->set_name("RecentScenes");
p->add_child(recent_scenes);
- recent_scenes->connect("id_pressed",this,"_open_recent_scene");
+ recent_scenes->connect("id_pressed", this, "_open_recent_scene");
{
- Control *sp = memnew( Control );
- sp->set_custom_minimum_size(Size2(30,0)*EDSCALE);
+ Control *sp = memnew(Control);
+ sp->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
menu_hb->add_child(sp);
}
- PanelContainer *editor_region = memnew( PanelContainer );
- editor_region->add_style_override("panel",gui_base->get_stylebox("hover","Button"));
- main_editor_button_vb = memnew( HBoxContainer );
+ PanelContainer *editor_region = memnew(PanelContainer);
+ editor_region->add_style_override("panel", gui_base->get_stylebox("hover", "Button"));
+ main_editor_button_vb = memnew(HBoxContainer);
editor_region->add_child(main_editor_button_vb);
menu_hb->add_child(editor_region);
- distraction_free = memnew( ToolButton );
+ distraction_free = memnew(ToolButton);
main_editor_button_vb->add_child(distraction_free);
- distraction_free->set_shortcut( ED_SHORTCUT("editor/distraction_free_mode",TTR("Distraction Free Mode"),KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_F11) );
- distraction_free->connect("pressed",this,"_toggle_distraction_free_mode");
- distraction_free->set_icon(gui_base->get_icon("DistractionFree","EditorIcons"));
+ distraction_free->set_shortcut(ED_SHORTCUT("editor/distraction_free_mode", TTR("Distraction Free Mode"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_F11));
+ distraction_free->connect("pressed", this, "_toggle_distraction_free_mode");
+ distraction_free->set_icon(gui_base->get_icon("DistractionFree", "EditorIcons"));
distraction_free->set_toggle_mode(true);
- //menu_hb->add_spacer();
+//menu_hb->add_spacer();
#if 0
node_menu = memnew( MenuButton );
node_menu->set_text("Node");
@@ -5596,30 +5278,30 @@ EditorNode::EditorNode() {
menu_panel->add_child( resource_menu );
#endif
- import_menu = memnew( MenuButton );
+ import_menu = memnew(MenuButton);
import_menu->set_tooltip(TTR("Import assets to the project."));
import_menu->set_text(TTR("Import"));
//import_menu->set_icon(gui_base->get_icon("Save","EditorIcons"));
- left_menu_hb->add_child( import_menu );
+ left_menu_hb->add_child(import_menu);
- p=import_menu->get_popup();
- p->connect("id_pressed",this,"_menu_option");
+ p = import_menu->get_popup();
+ p->connect("id_pressed", this, "_menu_option");
- tool_menu = memnew( MenuButton );
+ tool_menu = memnew(MenuButton);
tool_menu->set_tooltip(TTR("Miscellaneous project or scene-wide tools."));
tool_menu->set_text(TTR("Tools"));
//tool_menu->set_icon(gui_base->get_icon("Save","EditorIcons"));
- left_menu_hb->add_child( tool_menu );
+ left_menu_hb->add_child(tool_menu);
- p=tool_menu->get_popup();
- p->connect("id_pressed",this,"_menu_option");
- p->add_item(TTR("Orphan Resource Explorer"),TOOLS_ORPHAN_RESOURCES);
+ p = tool_menu->get_popup();
+ p->connect("id_pressed", this, "_menu_option");
+ p->add_item(TTR("Orphan Resource Explorer"), TOOLS_ORPHAN_RESOURCES);
- export_button = memnew( ToolButton );
+ export_button = memnew(ToolButton);
export_button->set_tooltip(TTR("Export the project to many platforms."));
export_button->set_text(TTR("Export"));
- export_button->connect("pressed",this,"_menu_option",varray(FILE_EXPORT_PROJECT));
+ export_button->connect("pressed", this, "_menu_option", varray(FILE_EXPORT_PROJECT));
export_button->set_focus_mode(Control::FOCUS_NONE);
left_menu_hb->add_child(export_button);
@@ -5630,109 +5312,105 @@ EditorNode::EditorNode() {
//s1->set_pos(Point2(210,4));
//s1->set_size(Point2(10,15));
-
- play_cc = memnew( CenterContainer );
+ play_cc = memnew(CenterContainer);
play_cc->set_mouse_filter(Control::MOUSE_FILTER_IGNORE);
- gui_base->add_child( play_cc );
+ gui_base->add_child(play_cc);
play_cc->set_area_as_parent_rect();
- play_cc->set_anchor_and_margin(MARGIN_BOTTOM,Control::ANCHOR_BEGIN,10);
- play_cc->set_margin(MARGIN_TOP,5);
+ play_cc->set_anchor_and_margin(MARGIN_BOTTOM, Control::ANCHOR_BEGIN, 10);
+ play_cc->set_margin(MARGIN_TOP, 5);
- top_region = memnew( PanelContainer );
- top_region->add_style_override("panel",gui_base->get_stylebox("hover","Button"));
+ top_region = memnew(PanelContainer);
+ top_region->add_style_override("panel", gui_base->get_stylebox("hover", "Button"));
play_cc->add_child(top_region);
- HBoxContainer *play_hb = memnew( HBoxContainer );
+ HBoxContainer *play_hb = memnew(HBoxContainer);
top_region->add_child(play_hb);
- play_button = memnew( ToolButton );
+ play_button = memnew(ToolButton);
play_hb->add_child(play_button);
play_button->set_toggle_mode(true);
- play_button->set_icon(gui_base->get_icon("MainPlay","EditorIcons"));
+ play_button->set_icon(gui_base->get_icon("MainPlay", "EditorIcons"));
play_button->set_focus_mode(Control::FOCUS_NONE);
- play_button->connect("pressed", this,"_menu_option",make_binds(RUN_PLAY));
+ play_button->connect("pressed", this, "_menu_option", make_binds(RUN_PLAY));
play_button->set_tooltip(TTR("Play the project."));
- play_button->set_shortcut(ED_SHORTCUT("editor/play",TTR("Play"),KEY_F5));
-
+ play_button->set_shortcut(ED_SHORTCUT("editor/play", TTR("Play"), KEY_F5));
-
- pause_button = memnew( ToolButton );
+ pause_button = memnew(ToolButton);
//menu_panel->add_child(pause_button); - not needed for now?
pause_button->set_toggle_mode(true);
- pause_button->set_icon(gui_base->get_icon("Pause","EditorIcons"));
+ pause_button->set_icon(gui_base->get_icon("Pause", "EditorIcons"));
pause_button->set_focus_mode(Control::FOCUS_NONE);
//pause_button->connect("pressed", this,"_menu_option",make_binds(RUN_PAUSE));
pause_button->set_tooltip(TTR("Pause the scene"));
pause_button->set_disabled(true);
play_hb->add_child(pause_button);
- pause_button->set_shortcut(ED_SHORTCUT("editor/pause_scene",TTR("Pause Scene"),KEY_F7));
-
+ pause_button->set_shortcut(ED_SHORTCUT("editor/pause_scene", TTR("Pause Scene"), KEY_F7));
- stop_button = memnew( ToolButton );
+ stop_button = memnew(ToolButton);
play_hb->add_child(stop_button);
//stop_button->set_toggle_mode(true);
stop_button->set_focus_mode(Control::FOCUS_NONE);
- stop_button->set_icon(gui_base->get_icon("MainStop","EditorIcons"));
- stop_button->connect("pressed", this,"_menu_option",make_binds(RUN_STOP));
+ stop_button->set_icon(gui_base->get_icon("MainStop", "EditorIcons"));
+ stop_button->connect("pressed", this, "_menu_option", make_binds(RUN_STOP));
stop_button->set_tooltip(TTR("Stop the scene."));
- stop_button->set_shortcut(ED_SHORTCUT("editor/stop",TTR("Stop"),KEY_F8));
+ stop_button->set_shortcut(ED_SHORTCUT("editor/stop", TTR("Stop"), KEY_F8));
- run_native = memnew( EditorRunNative);
+ run_native = memnew(EditorRunNative);
play_hb->add_child(run_native);
- native_play_button = memnew( MenuButton );
+ native_play_button = memnew(MenuButton);
native_play_button->set_text("NTV");
menu_hb->add_child(native_play_button);
native_play_button->hide();
- native_play_button->get_popup()->connect("id_pressed",this,"_run_in_device");
- run_native->connect("native_run",this,"_menu_option",varray(RUN_PLAY_NATIVE));
+ native_play_button->get_popup()->connect("id_pressed", this, "_run_in_device");
+ run_native->connect("native_run", this, "_menu_option", varray(RUN_PLAY_NATIVE));
//VSeparator *s1 = memnew( VSeparator );
//play_hb->add_child(s1);
- play_scene_button = memnew( ToolButton );
+ play_scene_button = memnew(ToolButton);
play_hb->add_child(play_scene_button);
play_scene_button->set_toggle_mode(true);
play_scene_button->set_focus_mode(Control::FOCUS_NONE);
- play_scene_button->set_icon(gui_base->get_icon("PlayScene","EditorIcons"));
- play_scene_button->connect("pressed", this,"_menu_option",make_binds(RUN_PLAY_SCENE));
+ play_scene_button->set_icon(gui_base->get_icon("PlayScene", "EditorIcons"));
+ play_scene_button->connect("pressed", this, "_menu_option", make_binds(RUN_PLAY_SCENE));
play_scene_button->set_tooltip(TTR("Play the edited scene."));
- play_scene_button->set_shortcut(ED_SHORTCUT("editor/play_scene",TTR("Play Scene"),KEY_F6));
+ play_scene_button->set_shortcut(ED_SHORTCUT("editor/play_scene", TTR("Play Scene"), KEY_F6));
- play_custom_scene_button = memnew( ToolButton );
+ play_custom_scene_button = memnew(ToolButton);
play_hb->add_child(play_custom_scene_button);
play_custom_scene_button->set_toggle_mode(true);
play_custom_scene_button->set_focus_mode(Control::FOCUS_NONE);
- play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom","EditorIcons"));
- play_custom_scene_button->connect("pressed", this,"_menu_option",make_binds(RUN_PLAY_CUSTOM_SCENE));
+ play_custom_scene_button->set_icon(gui_base->get_icon("PlayCustom", "EditorIcons"));
+ play_custom_scene_button->connect("pressed", this, "_menu_option", make_binds(RUN_PLAY_CUSTOM_SCENE));
play_custom_scene_button->set_tooltip(TTR("Play custom scene"));
- play_custom_scene_button->set_shortcut(ED_SHORTCUT("editor/play_custom_scene",TTR("Play Custom Scene"),KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_F5));
+ play_custom_scene_button->set_shortcut(ED_SHORTCUT("editor/play_custom_scene", TTR("Play Custom Scene"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_F5));
- debug_button = memnew( MenuButton );
+ debug_button = memnew(MenuButton);
debug_button->set_flat(true);
play_hb->add_child(debug_button);
//debug_button->set_toggle_mode(true);
debug_button->set_focus_mode(Control::FOCUS_NONE);
- debug_button->set_icon(gui_base->get_icon("Remote","EditorIcons"));
+ debug_button->set_icon(gui_base->get_icon("Remote", "EditorIcons"));
//debug_button->connect("pressed", this,"_menu_option",make_binds(RUN_LIVE_DEBUG));
debug_button->set_tooltip(TTR("Debug options"));
- p=debug_button->get_popup();
+ p = debug_button->get_popup();
p->set_hide_on_item_selection(false);
- p->add_check_item(TTR("Deploy with Remote Debug"),RUN_DEPLOY_REMOTE_DEBUG);
- p->set_item_tooltip(p->get_item_count()-1,TTR("When exporting or deploying, the resulting executable will attempt to connect to the IP of this computer in order to be debugged."));
- p->add_check_item(TTR("Small Deploy with Network FS"),RUN_FILE_SERVER);
- p->set_item_tooltip(p->get_item_count()-1,TTR("When this option is enabled, export or deploy will produce a minimal executable.\nThe filesystem will be provided from the project by the editor over the network.\nOn Android, deploy will use the USB cable for faster performance. This option speeds up testing for games with a large footprint."));
+ p->add_check_item(TTR("Deploy with Remote Debug"), RUN_DEPLOY_REMOTE_DEBUG);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("When exporting or deploying, the resulting executable will attempt to connect to the IP of this computer in order to be debugged."));
+ p->add_check_item(TTR("Small Deploy with Network FS"), RUN_FILE_SERVER);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is enabled, export or deploy will produce a minimal executable.\nThe filesystem will be provided from the project by the editor over the network.\nOn Android, deploy will use the USB cable for faster performance. This option speeds up testing for games with a large footprint."));
p->add_separator();
- p->add_check_item(TTR("Visible Collision Shapes"),RUN_DEBUG_COLLISONS);
- p->set_item_tooltip(p->get_item_count()-1,TTR("Collision shapes and raycast nodes (for 2D and 3D) will be visible on the running game if this option is turned on."));
- p->add_check_item(TTR("Visible Navigation"),RUN_DEBUG_NAVIGATION);
- p->set_item_tooltip(p->get_item_count()-1,TTR("Navigation meshes and polygons will be visible on the running game if this option is turned on."));
+ p->add_check_item(TTR("Visible Collision Shapes"), RUN_DEBUG_COLLISONS);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("Collision shapes and raycast nodes (for 2D and 3D) will be visible on the running game if this option is turned on."));
+ p->add_check_item(TTR("Visible Navigation"), RUN_DEBUG_NAVIGATION);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("Navigation meshes and polygons will be visible on the running game if this option is turned on."));
p->add_separator();
- p->add_check_item(TTR("Sync Scene Changes"),RUN_LIVE_DEBUG);
- p->set_item_tooltip(p->get_item_count()-1,TTR("When this option is turned on, any changes made to the scene in the editor will be replicated in the running game.\nWhen used remotely on a device, this is more efficient with network filesystem."));
- p->add_check_item(TTR("Sync Script Changes"),RUN_RELOAD_SCRIPTS);
- p->set_item_tooltip(p->get_item_count()-1,TTR("When this option is turned on, any script that is saved will be reloaded on the running game.\nWhen used remotely on a device, this is more efficient with network filesystem."));
- p->connect("id_pressed",this,"_menu_option");
+ p->add_check_item(TTR("Sync Scene Changes"), RUN_LIVE_DEBUG);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is turned on, any changes made to the scene in the editor will be replicated in the running game.\nWhen used remotely on a device, this is more efficient with network filesystem."));
+ p->add_check_item(TTR("Sync Script Changes"), RUN_RELOAD_SCRIPTS);
+ p->set_item_tooltip(p->get_item_count() - 1, TTR("When this option is turned on, any script that is saved will be reloaded on the running game.\nWhen used remotely on a device, this is more efficient with network filesystem."));
+ p->connect("id_pressed", this, "_menu_option");
/*
run_settings_button = memnew( ToolButton );
@@ -5752,104 +5430,97 @@ EditorNode::EditorNode() {
run_settings_button->connect("pressed", this,"_menu_option",make_binds(RUN_SETTINGS));
*/
-
- progress_hb = memnew( BackgroundProgress );
+ progress_hb = memnew(BackgroundProgress);
menu_hb->add_child(progress_hb);
{
- Control *sp = memnew( Control );
- sp->set_custom_minimum_size(Size2(30,0)*EDSCALE);
+ Control *sp = memnew(Control);
+ sp->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
menu_hb->add_child(sp);
}
-
- PanelContainer *vu_cont = memnew( PanelContainer );
- vu_cont->add_style_override("panel",gui_base->get_stylebox("hover","Button"));
+ PanelContainer *vu_cont = memnew(PanelContainer);
+ vu_cont->add_style_override("panel", gui_base->get_stylebox("hover", "Button"));
menu_hb->add_child(vu_cont);
- audio_vu = memnew( TextureProgress );
- CenterContainer *vu_cc = memnew( CenterContainer );
+ audio_vu = memnew(TextureProgress);
+ CenterContainer *vu_cc = memnew(CenterContainer);
vu_cc->add_child(audio_vu);
vu_cont->add_child(vu_cc);
- audio_vu->set_under_texture(gui_base->get_icon("VuEmpty","EditorIcons"));
- audio_vu->set_progress_texture(gui_base->get_icon("VuFull","EditorIcons"));
+ audio_vu->set_under_texture(gui_base->get_icon("VuEmpty", "EditorIcons"));
+ audio_vu->set_progress_texture(gui_base->get_icon("VuFull", "EditorIcons"));
audio_vu->set_max(24);
audio_vu->set_min(-80);
audio_vu->set_step(0.01);
audio_vu->set_value(0);
{
- Control *sp = memnew( Control );
- sp->set_custom_minimum_size(Size2(30,0)*EDSCALE);
+ Control *sp = memnew(Control);
+ sp->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
menu_hb->add_child(sp);
}
-
-
- top_region = memnew( PanelContainer );
- top_region->add_style_override("panel",gui_base->get_stylebox("hover","Button"));
- HBoxContainer *right_menu_hb = memnew( HBoxContainer );
+ top_region = memnew(PanelContainer);
+ top_region->add_style_override("panel", gui_base->get_stylebox("hover", "Button"));
+ HBoxContainer *right_menu_hb = memnew(HBoxContainer);
top_region->add_child(right_menu_hb);
menu_hb->add_child(top_region);
-
- settings_menu = memnew( MenuButton );
+ settings_menu = memnew(MenuButton);
settings_menu->set_text(TTR("Settings"));
//settings_menu->set_anchor(MARGIN_RIGHT,ANCHOR_END);
- right_menu_hb->add_child( settings_menu );
- p=settings_menu->get_popup();
+ right_menu_hb->add_child(settings_menu);
+ p = settings_menu->get_popup();
//p->add_item("Export Settings",SETTINGS_EXPORT_PREFERENCES);
- p->add_item(TTR("Editor Settings"),SETTINGS_PREFERENCES);
+ p->add_item(TTR("Editor Settings"), SETTINGS_PREFERENCES);
//p->add_item("Optimization Presets",SETTINGS_OPTIMIZED_PRESETS);
p->add_separator();
- editor_layouts = memnew( PopupMenu );
+ editor_layouts = memnew(PopupMenu);
editor_layouts->set_name("Layouts");
p->add_child(editor_layouts);
- editor_layouts->connect("id_pressed",this,"_layout_menu_option");
+ editor_layouts->connect("id_pressed", this, "_layout_menu_option");
p->add_submenu_item(TTR("Editor Layout"), "Layouts");
- p->add_shortcut(ED_SHORTCUT("editor/fullscreen_mode",TTR("Toggle Fullscreen"),KEY_MASK_SHIFT|KEY_F11),SETTINGS_TOGGLE_FULLSCREN);
+ p->add_shortcut(ED_SHORTCUT("editor/fullscreen_mode", TTR("Toggle Fullscreen"), KEY_MASK_SHIFT | KEY_F11), SETTINGS_TOGGLE_FULLSCREN);
p->add_separator();
- p->add_item(TTR("Install Export Templates"),SETTINGS_LOAD_EXPORT_TEMPLATES);
+ p->add_item(TTR("Install Export Templates"), SETTINGS_LOAD_EXPORT_TEMPLATES);
p->add_separator();
- p->add_item(TTR("About"),SETTINGS_ABOUT);
+ p->add_item(TTR("About"), SETTINGS_ABOUT);
- layout_dialog = memnew( EditorNameDialog );
+ layout_dialog = memnew(EditorNameDialog);
gui_base->add_child(layout_dialog);
layout_dialog->set_hide_on_ok(false);
- layout_dialog->set_size(Size2(175, 70)*EDSCALE);
- layout_dialog->connect("name_confirmed", this,"_dialog_action");
+ layout_dialog->set_size(Size2(175, 70) * EDSCALE);
+ layout_dialog->connect("name_confirmed", this, "_dialog_action");
- sources_button = memnew( ToolButton );
+ sources_button = memnew(ToolButton);
right_menu_hb->add_child(sources_button);
- sources_button->set_icon(gui_base->get_icon("DependencyOk","EditorIcons"));
- sources_button->connect("pressed",this,"_menu_option",varray(SOURCES_REIMPORT));
+ sources_button->set_icon(gui_base->get_icon("DependencyOk", "EditorIcons"));
+ sources_button->connect("pressed", this, "_menu_option", varray(SOURCES_REIMPORT));
sources_button->set_tooltip(TTR("Alerts when an external resource has changed."));
- update_menu = memnew( MenuButton );
+ update_menu = memnew(MenuButton);
update_menu->set_tooltip(TTR("Spins when the editor window repaints!"));
right_menu_hb->add_child(update_menu);
- update_menu->set_icon(gui_base->get_icon("Progress1","EditorIcons"));
- p=update_menu->get_popup();
- p->add_check_item(TTR("Update Always"),SETTINGS_UPDATE_ALWAYS);
- p->add_check_item(TTR("Update Changes"),SETTINGS_UPDATE_CHANGES);
- p->add_separator();
- p->add_check_item(TTR("Disable Update Spinner"),SETTINGS_UPDATE_SPINNER_HIDE);
- p->set_item_checked(1,true);
+ update_menu->set_icon(gui_base->get_icon("Progress1", "EditorIcons"));
+ p = update_menu->get_popup();
+ p->add_check_item(TTR("Update Always"), SETTINGS_UPDATE_ALWAYS);
+ p->add_check_item(TTR("Update Changes"), SETTINGS_UPDATE_CHANGES);
+ p->add_separator();
+ p->add_check_item(TTR("Disable Update Spinner"), SETTINGS_UPDATE_SPINNER_HIDE);
+ p->set_item_checked(1, true);
//sources_button->connect();
-/*
+ /*
Separator *s2 = memnew( VSeparator );
menu_panel->add_child(s2);
s2->set_pos(Point2(338,4));
s2->set_size(Point2(10,15));
*/
-
-
//editor_hsplit = memnew( HSplitContainer );
//main_split->add_child(editor_hsplit);
//editor_hsplit->set_v_size_flags(Control::SIZE_EXPAND_FILL);
@@ -5858,7 +5529,7 @@ EditorNode::EditorNode() {
//editor_hsplit->add_child(editor_vsplit);
//top_pallete = memnew( TabContainer );
- scene_tree_dock = memnew( SceneTreeDock(this,scene_root,editor_selection,editor_data) );
+ scene_tree_dock = memnew(SceneTreeDock(this, scene_root, editor_selection, editor_data));
scene_tree_dock->set_name(TTR("Scene"));
//top_pallete->add_child(scene_tree_dock);
dock_slot[DOCK_SLOT_RIGHT_UL]->add_child(scene_tree_dock);
@@ -5877,7 +5548,6 @@ EditorNode::EditorNode() {
editor_spacer->add_child( top_pallete );
top_pallete->set_area_as_parent_rect();*/
-
//prop_pallete = memnew( TabContainer );
//prop_pallete->set_v_size_flags(Control::SIZE_EXPAND_FILL);
@@ -5889,108 +5559,106 @@ EditorNode::EditorNode() {
editor_spacer->add_child( prop_pallete );
prop_pallete->set_area_as_parent_rect();*/
- VBoxContainer *prop_editor_base = memnew( VBoxContainer );
+ VBoxContainer *prop_editor_base = memnew(VBoxContainer);
prop_editor_base->set_name(TTR("Inspector")); // Properties?
dock_slot[DOCK_SLOT_RIGHT_BL]->add_child(prop_editor_base);
- HBoxContainer *prop_editor_hb = memnew( HBoxContainer );
+ HBoxContainer *prop_editor_hb = memnew(HBoxContainer);
prop_editor_base->add_child(prop_editor_hb);
- prop_editor_vb=prop_editor_base;
+ prop_editor_vb = prop_editor_base;
- resource_new_button = memnew( ToolButton );
+ resource_new_button = memnew(ToolButton);
resource_new_button->set_tooltip(TTR("Create a new resource in memory and edit it."));
- resource_new_button->set_icon(gui_base->get_icon("New","EditorIcons"));
+ resource_new_button->set_icon(gui_base->get_icon("New", "EditorIcons"));
prop_editor_hb->add_child(resource_new_button);
- resource_new_button->connect("pressed",this,"_menu_option",varray(RESOURCE_NEW));
+ resource_new_button->connect("pressed", this, "_menu_option", varray(RESOURCE_NEW));
resource_new_button->set_focus_mode(Control::FOCUS_NONE);
- resource_load_button = memnew( ToolButton );
+ resource_load_button = memnew(ToolButton);
resource_load_button->set_tooltip(TTR("Load an existing resource from disk and edit it."));
- resource_load_button->set_icon(gui_base->get_icon("Load","EditorIcons"));
+ resource_load_button->set_icon(gui_base->get_icon("Load", "EditorIcons"));
prop_editor_hb->add_child(resource_load_button);
- resource_load_button->connect("pressed",this,"_menu_option",varray(RESOURCE_LOAD));
+ resource_load_button->connect("pressed", this, "_menu_option", varray(RESOURCE_LOAD));
resource_load_button->set_focus_mode(Control::FOCUS_NONE);
- resource_save_button = memnew( MenuButton );
+ resource_save_button = memnew(MenuButton);
resource_save_button->set_tooltip(TTR("Save the currently edited resource."));
- resource_save_button->set_icon(gui_base->get_icon("Save","EditorIcons"));
+ resource_save_button->set_icon(gui_base->get_icon("Save", "EditorIcons"));
prop_editor_hb->add_child(resource_save_button);
- resource_save_button->get_popup()->add_item(TTR("Save"),RESOURCE_SAVE);
- resource_save_button->get_popup()->add_item(TTR("Save As.."),RESOURCE_SAVE_AS);
- resource_save_button->get_popup()->connect("id_pressed",this,"_menu_option");
+ resource_save_button->get_popup()->add_item(TTR("Save"), RESOURCE_SAVE);
+ resource_save_button->get_popup()->add_item(TTR("Save As.."), RESOURCE_SAVE_AS);
+ resource_save_button->get_popup()->connect("id_pressed", this, "_menu_option");
resource_save_button->set_focus_mode(Control::FOCUS_NONE);
resource_save_button->set_disabled(true);
prop_editor_hb->add_spacer();
- property_back = memnew( ToolButton );
- property_back->set_icon( gui_base->get_icon("Back","EditorIcons") );
+ property_back = memnew(ToolButton);
+ property_back->set_icon(gui_base->get_icon("Back", "EditorIcons"));
property_back->set_flat(true);
property_back->set_tooltip(TTR("Go to the previous edited object in history."));
property_back->set_disabled(true);
- prop_editor_hb->add_child( property_back );
+ prop_editor_hb->add_child(property_back);
- property_forward = memnew( ToolButton );
- property_forward->set_icon( gui_base->get_icon("Forward","EditorIcons") );
+ property_forward = memnew(ToolButton);
+ property_forward->set_icon(gui_base->get_icon("Forward", "EditorIcons"));
property_forward->set_flat(true);
property_forward->set_tooltip(TTR("Go to the next edited object in history."));
property_forward->set_disabled(true);
- prop_editor_hb->add_child( property_forward );
-
+ prop_editor_hb->add_child(property_forward);
- editor_history_menu = memnew( MenuButton );
+ editor_history_menu = memnew(MenuButton);
editor_history_menu->set_tooltip(TTR("History of recently edited objects."));
- editor_history_menu->set_icon( gui_base->get_icon("History","EditorIcons"));
+ editor_history_menu->set_icon(gui_base->get_icon("History", "EditorIcons"));
prop_editor_hb->add_child(editor_history_menu);
- editor_history_menu->connect("about_to_show",this,"_prepare_history");
- editor_history_menu->get_popup()->connect("id_pressed",this,"_select_history");
+ editor_history_menu->connect("about_to_show", this, "_prepare_history");
+ editor_history_menu->get_popup()->connect("id_pressed", this, "_select_history");
-
- prop_editor_hb = memnew( HBoxContainer ); //again...
+ prop_editor_hb = memnew(HBoxContainer); //again...
prop_editor_base->add_child(prop_editor_hb);
- editor_path = memnew( EditorPath(&editor_history) );
+ editor_path = memnew(EditorPath(&editor_history));
editor_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);
prop_editor_hb->add_child(editor_path);
- search_button = memnew( ToolButton );
+ search_button = memnew(ToolButton);
search_button->set_toggle_mode(true);
search_button->set_pressed(false);
- search_button->set_icon(gui_base->get_icon("Zoom","EditorIcons"));
+ search_button->set_icon(gui_base->get_icon("Zoom", "EditorIcons"));
prop_editor_hb->add_child(search_button);
- search_button->connect("toggled",this,"_toggle_search_bar");
+ search_button->connect("toggled", this, "_toggle_search_bar");
- object_menu = memnew( MenuButton );
- object_menu->set_icon(gui_base->get_icon("Tools","EditorIcons"));
- prop_editor_hb->add_child( object_menu );
+ object_menu = memnew(MenuButton);
+ object_menu->set_icon(gui_base->get_icon("Tools", "EditorIcons"));
+ prop_editor_hb->add_child(object_menu);
object_menu->set_tooltip(TTR("Object properties."));
- create_dialog = memnew( CreateDialog );
+ create_dialog = memnew(CreateDialog);
gui_base->add_child(create_dialog);
create_dialog->set_base_type("Resource");
- create_dialog->connect("create",this,"_resource_created");
+ create_dialog->connect("create", this, "_resource_created");
- search_bar = memnew( HBoxContainer );
+ search_bar = memnew(HBoxContainer);
search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL);
prop_editor_base->add_child(search_bar);
search_bar->hide();
- Label *l = memnew( Label(TTR("Search:")+" ") );
+ Label *l = memnew(Label(TTR("Search:") + " "));
search_bar->add_child(l);
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
search_bar->add_child(search_box);
- ToolButton *clear_button = memnew( ToolButton );
- clear_button->set_icon(gui_base->get_icon("Close","EditorIcons"));
+ ToolButton *clear_button = memnew(ToolButton);
+ clear_button->set_icon(gui_base->get_icon("Close", "EditorIcons"));
search_bar->add_child(clear_button);
- clear_button->connect("pressed",this,"_clear_search_box");
+ clear_button->connect("pressed", this, "_clear_search_box");
- property_editor = memnew( PropertyEditor );
+ property_editor = memnew(PropertyEditor);
property_editor->set_autoclear(true);
property_editor->set_show_categories(true);
property_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
@@ -5999,16 +5667,14 @@ EditorNode::EditorNode() {
property_editor->hide_top_label();
property_editor->register_text_enter(search_box);
- prop_editor_base->add_child( property_editor );
+ prop_editor_base->add_child(property_editor);
property_editor->set_undo_redo(&editor_data.get_undo_redo());
-
- import_dock = memnew( ImportDock );
+ import_dock = memnew(ImportDock);
dock_slot[DOCK_SLOT_RIGHT_UL]->add_child(import_dock);
import_dock->set_name(TTR("Import"));
-
- node_dock = memnew( NodeDock );
+ node_dock = memnew(NodeDock);
//node_dock->set_undoredo(&editor_data.get_undo_redo());
if (use_single_dock_column) {
dock_slot[DOCK_SLOT_RIGHT_UL]->add_child(node_dock);
@@ -6016,7 +5682,7 @@ EditorNode::EditorNode() {
dock_slot[DOCK_SLOT_RIGHT_BL]->add_child(node_dock);
}
- filesystem_dock = memnew( FileSystemDock(this) );
+ filesystem_dock = memnew(FileSystemDock(this));
filesystem_dock->set_name(TTR("FileSystem"));
filesystem_dock->set_display_mode(int(EditorSettings::get_singleton()->get("docks/filesystem/display_mode")));
@@ -6029,64 +5695,56 @@ EditorNode::EditorNode() {
dock_slot[DOCK_SLOT_LEFT_UR]->add_child(filesystem_dock);
}
//prop_pallete->add_child(filesystem_dock);
- filesystem_dock->connect("open",this,"open_request");
- filesystem_dock->connect("instance",this,"_instance_request");
+ filesystem_dock->connect("open", this, "open_request");
+ filesystem_dock->connect("instance", this, "_instance_request");
const String docks_section = "docks";
- overridden_default_layout=-1;
+ overridden_default_layout = -1;
default_layout.instance();
default_layout->set_value(docks_section, "dock_3", TTR("FileSystem"));
default_layout->set_value(docks_section, "dock_5", TTR("Scene"));
- default_layout->set_value(docks_section, "dock_6", TTR("Inspector")+","+TTR("Node"));
+ default_layout->set_value(docks_section, "dock_6", TTR("Inspector") + "," + TTR("Node"));
- for(int i=0;i<DOCK_SLOT_MAX/2;i++)
- default_layout->set_value(docks_section, "dock_hsplit_"+itos(i+1), 0);
- for(int i=0;i<DOCK_SLOT_MAX/2;i++)
- default_layout->set_value(docks_section, "dock_split_"+itos(i+1), 0);
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++)
+ default_layout->set_value(docks_section, "dock_hsplit_" + itos(i + 1), 0);
+ for (int i = 0; i < DOCK_SLOT_MAX / 2; i++)
+ default_layout->set_value(docks_section, "dock_split_" + itos(i + 1), 0);
_update_layouts_menu();
- bottom_panel = memnew( PanelContainer );
- bottom_panel->add_style_override("panel",gui_base->get_stylebox("panelf","Panel"));
+ bottom_panel = memnew(PanelContainer);
+ bottom_panel->add_style_override("panel", gui_base->get_stylebox("panelf", "Panel"));
center_split->add_child(bottom_panel);
center_split->set_dragger_visibility(SplitContainer::DRAGGER_HIDDEN);
- bottom_panel_vb = memnew( VBoxContainer );
+ bottom_panel_vb = memnew(VBoxContainer);
bottom_panel->add_child(bottom_panel_vb);
//bottom_panel_vb->set_v_size_flags(Control::SIZE_EXPAND_FILL);
- bottom_panel_hb = memnew( HBoxContainer );
+ bottom_panel_hb = memnew(HBoxContainer);
bottom_panel_vb->add_child(bottom_panel_hb);
+ log = memnew(EditorLog);
-
- log = memnew( EditorLog );
-
- add_bottom_panel_item(TTR("Output"),log);
+ add_bottom_panel_item(TTR("Output"), log);
//left_split->set_dragger_visible(false);
+ old_split_ofs = 0;
- old_split_ofs=0;
-
- center_split->connect("resized",this,"_vp_resized");
-
+ center_split->connect("resized", this, "_vp_resized");
/*PanelContainer *bottom_pc = memnew( PanelContainer );
srt->add_child(bottom_pc);
bottom_hb = memnew( HBoxContainer );
bottom_pc->add_child(bottom_hb);*/
-
//center_vb->add_child( log->get_button() );
//log->get_button()->set_h_size_flags(Control::SIZE_EXPAND_FILL);
-
//progress_hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
-
-
/*
animation_menu = memnew( ToolButton );
animation_menu->set_pos(Point2(500,0));
@@ -6098,41 +5756,22 @@ EditorNode::EditorNode() {
animation_menu->connect("pressed",this,"_animation_visibility_toggle");
*/
-
-
-
-
-
-
-
-
-
-
-
- orphan_resources = memnew( OrphanResourcesDialog );
+ orphan_resources = memnew(OrphanResourcesDialog);
gui_base->add_child(orphan_resources);
-
-
-
-
- confirmation = memnew( ConfirmationDialog );
+ confirmation = memnew(ConfirmationDialog);
gui_base->add_child(confirmation);
- confirmation->connect("confirmed", this,"_menu_confirm_current");
+ confirmation->connect("confirmed", this, "_menu_confirm_current");
- accept = memnew( AcceptDialog );
+ accept = memnew(AcceptDialog);
gui_base->add_child(accept);
- accept->connect("confirmed", this,"_menu_confirm_current");
-
-
-
-
+ accept->connect("confirmed", this, "_menu_confirm_current");
//optimized_save = memnew( OptimizedSaveDialog(&editor_data) );
//gui_base->add_child(optimized_save);
//optimized_save->connect("confirmed",this,"_save_optimized");
- project_export = memnew( ProjectExportDialog );
+ project_export = memnew(ProjectExportDialog);
gui_base->add_child(project_export);
//project_export_settings = memnew( ProjectExportDialog(this) );
@@ -6142,213 +5781,187 @@ EditorNode::EditorNode() {
//gui_base->add_child(optimized_presets);
//optimized_presets->connect("confirmed",this,"_presets_optimized");
-
-
//import_subscene = memnew( EditorSubScene );
//gui_base->add_child(import_subscene);
-
-
- dependency_error = memnew( DependencyErrorDialog );
+ dependency_error = memnew(DependencyErrorDialog);
gui_base->add_child(dependency_error);
- dependency_fixer = memnew( DependencyEditor );
- gui_base->add_child( dependency_fixer );
+ dependency_fixer = memnew(DependencyEditor);
+ gui_base->add_child(dependency_fixer);
- settings_config_dialog = memnew( EditorSettingsDialog );
+ settings_config_dialog = memnew(EditorSettingsDialog);
gui_base->add_child(settings_config_dialog);
- project_settings = memnew( ProjectSettings(&editor_data) );
+ project_settings = memnew(ProjectSettings(&editor_data));
gui_base->add_child(project_settings);
- import_confirmation = memnew( ConfirmationDialog );
+ import_confirmation = memnew(ConfirmationDialog);
import_confirmation->get_ok()->set_text(TTR("Re-Import"));
- import_confirmation->add_button(TTR("Update"),!OS::get_singleton()->get_swap_ok_cancel(),"update");
+ import_confirmation->add_button(TTR("Update"), !OS::get_singleton()->get_swap_ok_cancel(), "update");
import_confirmation->get_label()->set_align(Label::ALIGN_CENTER);
- import_confirmation->connect("confirmed",this,"_import_action",make_binds("re-import"));
- import_confirmation->connect("custom_action",this,"_import_action");
+ import_confirmation->connect("confirmed", this, "_import_action", make_binds("re-import"));
+ import_confirmation->connect("custom_action", this, "_import_action");
gui_base->add_child(import_confirmation);
- open_recent_confirmation = memnew( ConfirmationDialog );
+ open_recent_confirmation = memnew(ConfirmationDialog);
add_child(open_recent_confirmation);
- open_recent_confirmation->connect("confirmed",this,"_open_recent_scene_confirm");
-
-
- run_settings_dialog = memnew( RunSettingsDialog );
- gui_base->add_child( run_settings_dialog );
+ open_recent_confirmation->connect("confirmed", this, "_open_recent_scene_confirm");
+ run_settings_dialog = memnew(RunSettingsDialog);
+ gui_base->add_child(run_settings_dialog);
-
- about = memnew( AcceptDialog );
+ about = memnew(AcceptDialog);
about->set_title(TTR("Thanks from the Godot community!"));
//about->get_cancel()->hide();
about->get_ok()->set_text(TTR("Thanks!"));
about->set_hide_on_ok(true);
- Label *about_text = memnew( Label );
- about_text->set_text(VERSION_FULL_NAME"\n(c) 2008-2017 Juan Linietsky, Ariel Manzur.\n");
- about_text->set_pos(Point2(gui_base->get_icon("Logo","EditorIcons")->get_size().width+30,20));
+ Label *about_text = memnew(Label);
+ about_text->set_text(VERSION_FULL_NAME "\n(c) 2008-2017 Juan Linietsky, Ariel Manzur.\n");
+ about_text->set_pos(Point2(gui_base->get_icon("Logo", "EditorIcons")->get_size().width + 30, 20));
gui_base->add_child(about);
about->add_child(about_text);
- TextureRect *logo = memnew( TextureRect );
+ TextureRect *logo = memnew(TextureRect);
about->add_child(logo);
- logo->set_pos(Point2(20,20));
- logo->set_texture(gui_base->get_icon("Logo","EditorIcons") );
+ logo->set_pos(Point2(20, 20));
+ logo->set_texture(gui_base->get_icon("Logo", "EditorIcons"));
- warning = memnew( AcceptDialog );
+ warning = memnew(AcceptDialog);
gui_base->add_child(warning);
-
-
- file_templates = memnew( FileDialog );
+ file_templates = memnew(FileDialog);
file_templates->set_title(TTR("Import Templates From ZIP File"));
- gui_base->add_child( file_templates );
+ gui_base->add_child(file_templates);
file_templates->set_mode(FileDialog::MODE_OPEN_FILE);
file_templates->set_access(FileDialog::ACCESS_FILESYSTEM);
file_templates->clear_filters();
file_templates->add_filter("*.tpz ; Template Package");
-
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
gui_base->add_child(file);
file->set_current_dir("res://");
- file_export = memnew( FileDialog );
+ file_export = memnew(FileDialog);
file_export->set_access(FileDialog::ACCESS_FILESYSTEM);
gui_base->add_child(file_export);
file_export->set_title(TTR("Export Project"));
- file_export->connect("file_selected", this,"_dialog_action");
+ file_export->connect("file_selected", this, "_dialog_action");
- file_export_lib = memnew( FileDialog );
+ file_export_lib = memnew(FileDialog);
file_export_lib->set_title(TTR("Export Library"));
file_export_lib->set_mode(FileDialog::MODE_SAVE_FILE);
- file_export_lib->connect("file_selected", this,"_dialog_action");
- file_export_lib_merge = memnew( CheckButton );
+ file_export_lib->connect("file_selected", this, "_dialog_action");
+ file_export_lib_merge = memnew(CheckButton);
file_export_lib_merge->set_text(TTR("Merge With Existing"));
file_export_lib_merge->set_pressed(true);
file_export_lib->get_vbox()->add_child(file_export_lib_merge);
gui_base->add_child(file_export_lib);
-
-
-
- file_export_password = memnew( LineEdit );
+ file_export_password = memnew(LineEdit);
file_export_password->set_secret(true);
file_export_password->set_editable(false);
- file_export->get_vbox()->add_margin_child(TTR("Password:"),file_export_password);
+ file_export->get_vbox()->add_margin_child(TTR("Password:"), file_export_password);
-
- file_script = memnew( FileDialog );
+ file_script = memnew(FileDialog);
file_script->set_title(TTR("Open & Run a Script"));
file_script->set_access(FileDialog::ACCESS_FILESYSTEM);
file_script->set_mode(FileDialog::MODE_OPEN_FILE);
List<String> sexts;
- ResourceLoader::get_recognized_extensions_for_type("Script",&sexts);
- for (List<String>::Element*E=sexts.front();E;E=E->next()) {
- file_script->add_filter("*."+E->get());
+ ResourceLoader::get_recognized_extensions_for_type("Script", &sexts);
+ for (List<String>::Element *E = sexts.front(); E; E = E->next()) {
+ file_script->add_filter("*." + E->get());
}
gui_base->add_child(file_script);
- file_script->connect("file_selected",this,"_dialog_action");
+ file_script->connect("file_selected", this, "_dialog_action");
//reimport_dialog = memnew( EditorReImportDialog );
//gui_base->add_child(reimport_dialog);
+ property_forward->connect("pressed", this, "_property_editor_forward");
+ property_back->connect("pressed", this, "_property_editor_back");
+ file_menu->get_popup()->connect("id_pressed", this, "_menu_option");
+ object_menu->get_popup()->connect("id_pressed", this, "_menu_option");
- property_forward->connect("pressed", this,"_property_editor_forward");
- property_back->connect("pressed", this,"_property_editor_back");
-
+ update_menu->get_popup()->connect("id_pressed", this, "_menu_option");
+ settings_menu->get_popup()->connect("id_pressed", this, "_menu_option");
-
- file_menu->get_popup()->connect("id_pressed", this,"_menu_option");
- object_menu->get_popup()->connect("id_pressed", this,"_menu_option");
-
- update_menu->get_popup()->connect("id_pressed", this,"_menu_option");
- settings_menu->get_popup()->connect("id_pressed", this,"_menu_option");
-
-
- file->connect("file_selected", this,"_dialog_action");
- file_templates->connect("file_selected", this,"_dialog_action");
- property_editor->connect("resource_selected", this,"_resource_selected");
- property_editor->connect("property_keyed", this,"_property_keyed");
+ file->connect("file_selected", this, "_dialog_action");
+ file_templates->connect("file_selected", this, "_dialog_action");
+ property_editor->connect("resource_selected", this, "_resource_selected");
+ property_editor->connect("property_keyed", this, "_property_keyed");
//plugin stuff
- file_server = memnew( EditorFileServer );
-
-
-
-
- add_editor_plugin( memnew( AnimationPlayerEditorPlugin(this) ) );
- add_editor_plugin( memnew( CanvasItemEditorPlugin(this) ) );
- add_editor_plugin( memnew( SpatialEditorPlugin(this) ) );
- add_editor_plugin( memnew( ScriptEditorPlugin(this) ) );
+ file_server = memnew(EditorFileServer);
+ add_editor_plugin(memnew(AnimationPlayerEditorPlugin(this)));
+ add_editor_plugin(memnew(CanvasItemEditorPlugin(this)));
+ add_editor_plugin(memnew(SpatialEditorPlugin(this)));
+ add_editor_plugin(memnew(ScriptEditorPlugin(this)));
EditorAudioBuses *audio_bus_editor = EditorAudioBuses::register_editor();
ScriptTextEditor::register_editor(); //register one for text scripts
if (StreamPeerSSL::is_available()) {
- add_editor_plugin( memnew( AssetLibraryEditorPlugin(this) ) );
+ add_editor_plugin(memnew(AssetLibraryEditorPlugin(this)));
} else {
WARN_PRINT("Asset Library not available, as it requires SSL to work.");
}
//more visually meaningful to have this later
raise_bottom_panel_item(AnimationPlayerEditor::singleton);
- add_editor_plugin( memnew( ShaderEditorPlugin(this) ) );
-/* add_editor_plugin( memnew( ShaderGraphEditorPlugin(this,true) ) );
+ add_editor_plugin(memnew(ShaderEditorPlugin(this)));
+ /* add_editor_plugin( memnew( ShaderGraphEditorPlugin(this,true) ) );
add_editor_plugin( memnew( ShaderGraphEditorPlugin(this,false) ) );
add_editor_plugin( memnew( ShaderEditorPlugin(this,false) ) );*/
- add_editor_plugin( memnew( CameraEditorPlugin(this) ) );
-// add_editor_plugin( memnew( SampleEditorPlugin(this) ) );
-// add_editor_plugin( memnew( SampleLibraryEditorPlugin(this) ) );
- add_editor_plugin( memnew( ThemeEditorPlugin(this) ) );
- add_editor_plugin( memnew( MultiMeshEditorPlugin(this) ) );
- add_editor_plugin( memnew( MeshInstanceEditorPlugin(this) ) );
- add_editor_plugin( memnew( AnimationTreeEditorPlugin(this) ) );
+ add_editor_plugin(memnew(CameraEditorPlugin(this)));
+ // add_editor_plugin( memnew( SampleEditorPlugin(this) ) );
+ // add_editor_plugin( memnew( SampleLibraryEditorPlugin(this) ) );
+ add_editor_plugin(memnew(ThemeEditorPlugin(this)));
+ add_editor_plugin(memnew(MultiMeshEditorPlugin(this)));
+ add_editor_plugin(memnew(MeshInstanceEditorPlugin(this)));
+ add_editor_plugin(memnew(AnimationTreeEditorPlugin(this)));
//add_editor_plugin( memnew( SamplePlayerEditorPlugin(this) ) ); - this is kind of useless at this point
//add_editor_plugin( memnew( MeshLibraryEditorPlugin(this) ) );
//add_editor_plugin( memnew( StreamEditorPlugin(this) ) );
- add_editor_plugin( memnew( StyleBoxEditorPlugin(this) ) );
+ add_editor_plugin(memnew(StyleBoxEditorPlugin(this)));
//add_editor_plugin( memnew( ParticlesEditorPlugin(this) ) );
- add_editor_plugin( memnew( ResourcePreloaderEditorPlugin(this) ) );
- add_editor_plugin( memnew( ItemListEditorPlugin(this) ) );
+ add_editor_plugin(memnew(ResourcePreloaderEditorPlugin(this)));
+ add_editor_plugin(memnew(ItemListEditorPlugin(this)));
//add_editor_plugin( memnew( RichTextEditorPlugin(this) ) );
//add_editor_plugin( memnew( CollisionPolygonEditorPlugin(this) ) );
- add_editor_plugin( memnew( CollisionPolygon2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( TileSetEditorPlugin(this) ) );
- add_editor_plugin( memnew( TileMapEditorPlugin(this) ) );
- add_editor_plugin( memnew( SpriteFramesEditorPlugin(this) ) );
- add_editor_plugin( memnew( TextureRegionEditorPlugin(this) ) );
- add_editor_plugin( memnew( Particles2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( GIProbeEditorPlugin(this) ) );
- add_editor_plugin( memnew( Path2DEditorPlugin(this) ) );
+ add_editor_plugin(memnew(CollisionPolygon2DEditorPlugin(this)));
+ add_editor_plugin(memnew(TileSetEditorPlugin(this)));
+ add_editor_plugin(memnew(TileMapEditorPlugin(this)));
+ add_editor_plugin(memnew(SpriteFramesEditorPlugin(this)));
+ add_editor_plugin(memnew(TextureRegionEditorPlugin(this)));
+ add_editor_plugin(memnew(Particles2DEditorPlugin(this)));
+ add_editor_plugin(memnew(GIProbeEditorPlugin(this)));
+ add_editor_plugin(memnew(Path2DEditorPlugin(this)));
//add_editor_plugin( memnew( PathEditorPlugin(this) ) );
//add_editor_plugin( memnew( BakedLightEditorPlugin(this) ) );
- add_editor_plugin( memnew( Line2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( Polygon2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( LightOccluder2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( NavigationPolygonEditorPlugin(this) ) );
- add_editor_plugin( memnew( ColorRampEditorPlugin(this) ) );
- add_editor_plugin( memnew( CollisionShape2DEditorPlugin(this) ) );
- add_editor_plugin( memnew( TextureEditorPlugin(this) ) );
- add_editor_plugin( memnew( AudioBusesEditorPlugin(audio_bus_editor) ) );
+ add_editor_plugin(memnew(Line2DEditorPlugin(this)));
+ add_editor_plugin(memnew(Polygon2DEditorPlugin(this)));
+ add_editor_plugin(memnew(LightOccluder2DEditorPlugin(this)));
+ add_editor_plugin(memnew(NavigationPolygonEditorPlugin(this)));
+ add_editor_plugin(memnew(ColorRampEditorPlugin(this)));
+ add_editor_plugin(memnew(CollisionShape2DEditorPlugin(this)));
+ add_editor_plugin(memnew(TextureEditorPlugin(this)));
+ add_editor_plugin(memnew(AudioBusesEditorPlugin(audio_bus_editor)));
//add_editor_plugin( memnew( MaterialEditorPlugin(this) ) );
//add_editor_plugin( memnew( MeshEditorPlugin(this) ) );
- for(int i=0;i<EditorPlugins::get_plugin_count();i++)
- add_editor_plugin( EditorPlugins::create(i,this) );
+ for (int i = 0; i < EditorPlugins::get_plugin_count(); i++)
+ add_editor_plugin(EditorPlugins::create(i, this));
- for(int i=0;i<plugin_init_callback_count;i++) {
+ for (int i = 0; i < plugin_init_callback_count; i++) {
plugin_init_callbacks[i]();
}
-
-
-
/*resource_preview->add_preview_generator( Ref<EditorTexturePreviewPlugin>( memnew(EditorTexturePreviewPlugin )));
resource_preview->add_preview_generator( Ref<EditorPackedScenePreviewPlugin>( memnew(EditorPackedScenePreviewPlugin )));
resource_preview->add_preview_generator( Ref<EditorMaterialPreviewPlugin>( memnew(EditorMaterialPreviewPlugin )));
@@ -6358,128 +5971,115 @@ EditorNode::EditorNode() {
resource_preview->add_preview_generator( Ref<EditorBitmapPreviewPlugin>( memnew(EditorBitmapPreviewPlugin )));
*/
-
- circle_step_msec=OS::get_singleton()->get_ticks_msec();
- circle_step_frame=Engine::get_singleton()->get_frames_drawn();
- circle_step=0;
+ circle_step_msec = OS::get_singleton()->get_ticks_msec();
+ circle_step_frame = Engine::get_singleton()->get_frames_drawn();
+ circle_step = 0;
_rebuild_import_menu();
- editor_plugin_screen=NULL;
+ editor_plugin_screen = NULL;
editor_plugins_over = memnew(EditorPluginList);
//force_top_viewport(true);
_edit_current();
- current=NULL;
+ current = NULL;
PhysicsServer::get_singleton()->set_active(false); // no physics by default if editor
Physics2DServer::get_singleton()->set_active(false); // no physics by default if editor
ScriptServer::set_scripting_enabled(false); // no scripting by default if editor
-
//GlobalConfig::get_singleton()->set("render/room_cull_enabled",false);
- reference_resource_mem=true;
- save_external_resources_mem=true;
+ reference_resource_mem = true;
+ save_external_resources_mem = true;
set_process(true);
OS::get_singleton()->set_low_processor_usage_mode(true);
-
if (0) { //not sure if i want this to happen after all
//store project name in ssettings
String project_name;
//figure it out from path
- project_name=GlobalConfig::get_singleton()->get_resource_path().replace("\\","/");
- print_line("path: "+project_name);
- if (project_name.length() && project_name[project_name.length()-1]=='/')
- project_name=project_name.substr(0,project_name.length()-1);
+ project_name = GlobalConfig::get_singleton()->get_resource_path().replace("\\", "/");
+ print_line("path: " + project_name);
+ if (project_name.length() && project_name[project_name.length() - 1] == '/')
+ project_name = project_name.substr(0, project_name.length() - 1);
- project_name=project_name.replace("/","::");
+ project_name = project_name.replace("/", "::");
- if (project_name!="") {
- EditorSettings::get_singleton()->set("projects/"+project_name,GlobalConfig::get_singleton()->get_resource_path());
- EditorSettings::get_singleton()->raise_order("projects/"+project_name);
+ if (project_name != "") {
+ EditorSettings::get_singleton()->set("projects/" + project_name, GlobalConfig::get_singleton()->get_resource_path());
+ EditorSettings::get_singleton()->raise_order("projects/" + project_name);
EditorSettings::get_singleton()->save();
}
}
- open_imported = memnew( ConfirmationDialog );
+ open_imported = memnew(ConfirmationDialog);
open_imported->get_ok()->set_text(TTR("Open Anyway"));
- new_inherited_button=open_imported->add_button("New Inherited",!OS::get_singleton()->get_swap_ok_cancel(),"inherit");
- open_imported->connect("confirmed",this,"_open_imported");
- open_imported->connect("custom_action",this,"_inherit_imported");
+ new_inherited_button = open_imported->add_button("New Inherited", !OS::get_singleton()->get_swap_ok_cancel(), "inherit");
+ open_imported->connect("confirmed", this, "_open_imported");
+ open_imported->connect("custom_action", this, "_inherit_imported");
gui_base->add_child(open_imported);
-
-
//edited_scene=NULL;
- saved_version=1;
- unsaved_cache=true;
- _last_instanced_scene=NULL;
-
+ saved_version = 1;
+ unsaved_cache = true;
+ _last_instanced_scene = NULL;
- quick_open = memnew( EditorQuickOpen );
+ quick_open = memnew(EditorQuickOpen);
gui_base->add_child(quick_open);
- quick_open->connect("quick_open",this,"_quick_opened");
+ quick_open->connect("quick_open", this, "_quick_opened");
- quick_run = memnew( EditorQuickOpen );
+ quick_run = memnew(EditorQuickOpen);
gui_base->add_child(quick_run);
- quick_run->connect("quick_open",this,"_quick_run");
-
+ quick_run->connect("quick_open", this, "_quick_run");
_update_recent_scenes();
-
editor_data.restore_editor_global_states();
- convert_old=false;
- opening_prev=false;
+ convert_old = false;
+ opening_prev = false;
set_process_unhandled_input(true);
- _playing_edited=false;
+ _playing_edited = false;
//Panel *errors = memnew( Panel );
- load_errors = memnew( RichTextLabel );
+ load_errors = memnew(RichTextLabel);
//load_errors->set_readonly(true);
- load_error_dialog = memnew( AcceptDialog );
+ load_error_dialog = memnew(AcceptDialog);
load_error_dialog->add_child(load_errors);
load_error_dialog->set_title(TTR("Load Errors"));
//load_error_dialog->set_child_rect(load_errors);
gui_base->add_child(load_error_dialog);
-
//EditorImport::add_importer( Ref<EditorImporterCollada>( memnew(EditorImporterCollada )));
- EditorFileSystem::get_singleton()->connect("sources_changed",this,"_sources_changed");
- EditorFileSystem::get_singleton()->connect("filesystem_changed",this,"_fs_changed");
-
+ EditorFileSystem::get_singleton()->connect("sources_changed", this, "_sources_changed");
+ EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_fs_changed");
{
List<StringName> tl;
StringName ei = "EditorIcons";
- theme_base->get_theme()->get_icon_list(ei,&tl);
- for(List<StringName>::Element *E=tl.front();E;E=E->next()) {
+ theme_base->get_theme()->get_icon_list(ei, &tl);
+ for (List<StringName>::Element *E = tl.front(); E; E = E->next()) {
if (!ClassDB::class_exists(E->get()))
continue;
- icon_type_cache[E->get()]=theme_base->get_theme()->get_icon(E->get(),ei);
+ icon_type_cache[E->get()] = theme_base->get_theme()->get_icon(E->get(), ei);
}
}
-
-
Node::set_human_readable_collision_renaming(true);
-
- pick_main_scene = memnew( ConfirmationDialog );
+ pick_main_scene = memnew(ConfirmationDialog);
gui_base->add_child(pick_main_scene);
pick_main_scene->get_ok()->set_text("Select");
- pick_main_scene->connect("confirmed",this,"_menu_option",varray(SETTINGS_PICK_MAIN_SCENE));
+ pick_main_scene->connect("confirmed", this, "_menu_option", varray(SETTINGS_PICK_MAIN_SCENE));
//Ref<ImageTexture> it = gui_base->get_icon("logo","Icons");
//OS::get_singleton()->set_icon( it->get_data() );
- for(int i=0;i<_init_callbacks.size();i++)
+ for (int i = 0; i < _init_callbacks.size(); i++)
_init_callbacks[i]();
editor_data.add_edited_scene(-1);
@@ -6488,30 +6088,25 @@ EditorNode::EditorNode() {
{
- _initializing_addons=true;
+ _initializing_addons = true;
Vector<String> addons = GlobalConfig::get_singleton()->get("editor_plugins/enabled");
- for(int i=0;i<addons.size();i++) {
- set_addon_plugin_enabled(addons[i],true);
+ for (int i = 0; i < addons.size(); i++) {
+ set_addon_plugin_enabled(addons[i], true);
}
- _initializing_addons=false;
+ _initializing_addons = false;
}
-
-
_load_docks();
FileAccess::set_file_close_fail_notify_callback(_file_access_close_error_notify);
- waiting_for_first_scan=true;
-
+ waiting_for_first_scan = true;
}
-
EditorNode::~EditorNode() {
-
- memdelete( EditorHelp::get_doc_data() );
+ memdelete(EditorHelp::get_doc_data());
memdelete(editor_selection);
memdelete(editor_plugins_over);
memdelete(file_server);
@@ -6522,29 +6117,26 @@ EditorNode::~EditorNode() {
* EDITOR PLUGIN LIST
*/
-
void EditorPluginList::make_visible(bool p_visible) {
for (int i = 0; i < plugins_list.size(); i++) {
plugins_list[i]->make_visible(p_visible);
}
-
}
-void EditorPluginList::edit(Object* p_object) {
+void EditorPluginList::edit(Object *p_object) {
for (int i = 0; i < plugins_list.size(); i++) {
plugins_list[i]->edit(p_object);
}
-
}
-bool EditorPluginList::forward_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) {
+bool EditorPluginList::forward_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) {
bool discard = false;
for (int i = 0; i < plugins_list.size(); i++) {
- if (plugins_list[i]->forward_canvas_gui_input(p_canvas_xform,p_event)) {
+ if (plugins_list[i]->forward_canvas_gui_input(p_canvas_xform, p_event)) {
discard = true;
}
}
@@ -6552,7 +6144,7 @@ bool EditorPluginList::forward_gui_input(const Transform2D& p_canvas_xform,const
return discard;
}
-bool EditorPluginList::forward_spatial_gui_input(Camera* p_camera, const InputEvent& p_event) {
+bool EditorPluginList::forward_spatial_gui_input(Camera *p_camera, const InputEvent &p_event) {
bool discard = false;
for (int i = 0; i < plugins_list.size(); i++) {
@@ -6564,12 +6156,11 @@ bool EditorPluginList::forward_spatial_gui_input(Camera* p_camera, const InputEv
return discard;
}
-void EditorPluginList::forward_draw_over_canvas(const Transform2D& p_canvas_xform,Control* p_canvas) {
+void EditorPluginList::forward_draw_over_canvas(const Transform2D &p_canvas_xform, Control *p_canvas) {
for (int i = 0; i < plugins_list.size(); i++) {
- plugins_list[i]->forward_draw_over_canvas(p_canvas_xform,p_canvas);
+ plugins_list[i]->forward_draw_over_canvas(p_canvas_xform, p_canvas);
}
-
}
bool EditorPluginList::empty() {
diff --git a/editor/editor_node.h b/editor/editor_node.h
index fb0b5c4c25..cb165bdf21 100644
--- a/editor/editor_node.h
+++ b/editor/editor_node.h
@@ -29,60 +29,59 @@
#ifndef EDITOR_NODE_H
#define EDITOR_NODE_H
-#include "scene/gui/control.h"
-#include "scene/gui/panel.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/menu_button.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/dialogs.h"
-#include "scene/gui/separator.h"
-#include "scene/gui/tab_container.h"
-#include "scene/gui/panel_container.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/split_container.h"
-#include "scene/gui/center_container.h"
-#include "scene/gui/texture_progress.h"
-#include "editor/filesystem_dock.h"
-#include "editor/scene_tree_editor.h"
-#include "editor/property_editor.h"
-#include "editor/create_dialog.h"
#include "editor/call_dialog.h"
-#include "editor/reparent_dialog.h"
#include "editor/connections_dialog.h"
-#include "editor/node_dock.h"
-#include "editor/import_dock.h"
-#include "editor/settings_config_dialog.h"
-#include "editor/groups_editor.h"
+#include "editor/create_dialog.h"
#include "editor/editor_data.h"
#include "editor/editor_path.h"
#include "editor/editor_run.h"
+#include "editor/filesystem_dock.h"
+#include "editor/groups_editor.h"
+#include "editor/import_dock.h"
+#include "editor/node_dock.h"
+#include "editor/property_editor.h"
+#include "editor/reparent_dialog.h"
+#include "editor/scene_tree_editor.h"
+#include "editor/settings_config_dialog.h"
+#include "scene/gui/center_container.h"
+#include "scene/gui/control.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
+#include "scene/gui/menu_button.h"
+#include "scene/gui/panel.h"
+#include "scene/gui/panel_container.h"
+#include "scene/gui/separator.h"
+#include "scene/gui/split_container.h"
+#include "scene/gui/tab_container.h"
+#include "scene/gui/texture_progress.h"
+#include "scene/gui/tool_button.h"
+#include "scene/gui/tree.h"
#include "editor/pane_drag.h"
-#include "editor/script_create_dialog.h"
-#include "editor/run_settings_dialog.h"
-#include "editor/project_settings.h"
-#include "editor/project_export.h"
#include "editor/editor_log.h"
-#include "editor/scene_tree_dock.h"
-#include "editor/resources_dock.h"
#include "editor/editor_run_script.h"
+#include "editor/project_export.h"
+#include "editor/project_settings.h"
+#include "editor/resources_dock.h"
+#include "editor/run_settings_dialog.h"
+#include "editor/scene_tree_dock.h"
+#include "editor/script_create_dialog.h"
+#include "editor/editor_name_dialog.h"
+#include "editor/editor_plugin.h"
#include "editor/editor_run_native.h"
-#include "scene/gui/tabs.h"
-#include "editor/quick_open.h"
-#include "editor/project_export.h"
#include "editor/editor_sub_scene.h"
+#include "editor/project_export.h"
+#include "editor/quick_open.h"
#include "editor_export.h"
#include "editor_reimport_dialog.h"
-#include "editor/editor_plugin.h"
-#include "editor/editor_name_dialog.h"
+#include "scene/gui/tabs.h"
-#include "fileserver/editor_file_server.h"
#include "editor_resource_preview.h"
+#include "fileserver/editor_file_server.h"
#include "scene/gui/viewport_container.h"
-
#include "progress_dialog.h"
#include "editor_scale.h"
@@ -90,10 +89,6 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
-
-
typedef void (*EditorNodeInitCallback)();
typedef void (*EditorPluginInitializeCallback)();
typedef void (*EditorBuildCallback)();
@@ -102,7 +97,7 @@ class EditorPluginList;
class EditorNode : public Node {
- GDCLASS( EditorNode, Node );
+ GDCLASS(EditorNode, Node);
public:
enum DockSlot {
@@ -116,9 +111,10 @@ public:
DOCK_SLOT_RIGHT_BR,
DOCK_SLOT_MAX
};
+
private:
enum {
- HISTORY_SIZE=64
+ HISTORY_SIZE = 64
};
enum MenuOptions {
@@ -194,21 +190,19 @@ private:
DEPENDENCY_UPDATE_IMPORTED,
SCENE_TAB_CLOSE,
- IMPORT_PLUGIN_BASE=100,
+ IMPORT_PLUGIN_BASE = 100,
- OBJECT_METHOD_BASE=500,
+ OBJECT_METHOD_BASE = 500,
- TOOL_MENU_BASE=1000
+ TOOL_MENU_BASE = 1000
};
-
-
//Node *edited_scene; //scene being edited
Viewport *scene_root; //root of the scene being edited
//Ref<ResourceImportMetadata> scene_import_metadata;
- PanelContainer* scene_root_parent;
+ PanelContainer *scene_root_parent;
Control *gui_base;
VBoxContainer *main_vbox;
@@ -240,7 +234,6 @@ private:
//PaneDrag *pd_anim;
Panel *menu_panel;
-
//HSplitContainer *editor_hsplit;
//VSplitContainer *editor_vsplit;
CenterContainer *play_cc;
@@ -335,10 +328,10 @@ private:
EditorQuickOpen *quick_run;
HBoxContainer *main_editor_button_vb;
- Vector<ToolButton*> main_editor_buttons;
- Vector<EditorPlugin*> editor_table;
+ Vector<ToolButton *> main_editor_buttons;
+ Vector<EditorPlugin *> editor_table;
-// EditorReImportDialog *reimport_dialog;
+ // EditorReImportDialog *reimport_dialog;
ProgressDialog *progress_dialog;
BackgroundProgress *progress_hb;
@@ -350,7 +343,6 @@ private:
Button *new_inherited_button;
String open_import_request;
-
TabContainer *dock_slot[DOCK_SLOT_MAX];
Rect2 dock_select_rect[DOCK_SLOT_MAX];
int dock_select_rect_over;
@@ -386,7 +378,7 @@ private:
uint64_t circle_step_frame;
int circle_step;
- Vector<EditorPlugin*> editor_plugins;
+ Vector<EditorPlugin *> editor_plugins;
EditorPlugin *editor_plugin_screen;
EditorPluginList *editor_plugins_over;
@@ -394,13 +386,12 @@ private:
EditorData editor_data;
EditorRun editor_run;
EditorSelection *editor_selection;
-// ProjectExport *project_export;
+ // ProjectExport *project_export;
ProjectExportDialog *project_export;
EditorResourcePreview *resource_preview;
EditorFileServer *file_server;
-
struct BottomPanelItem {
String name;
Control *control;
@@ -421,17 +412,16 @@ private:
void _dialog_action(String p_file);
-
void _edit_current();
- void _dialog_display_file_error(String p_file,Error p_error);
+ void _dialog_display_file_error(String p_file, Error p_error);
int current_option;
//void _animation_visibility_toggle();
void _resource_created();
- void _resource_selected(const RES& p_res,const String& p_property="");
+ void _resource_selected(const RES &p_res, const String &p_property = "");
void _menu_option(int p_option);
void _menu_confirm_current();
- void _menu_option_confirm(int p_option,bool p_confirmed);
+ void _menu_option_confirm(int p_option, bool p_confirmed);
void _update_debug_options();
void _property_editor_forward();
@@ -440,15 +430,14 @@ private:
void _select_history(int p_idx);
void _prepare_history();
-
void _fs_changed();
void _sources_changed(bool p_exist);
void _imported(Node *p_node);
void _node_renamed();
void _editor_select(int p_which);
- void _set_scene_metadata(const String &p_file, int p_idx=-1);
- void _get_scene_metadata(const String& p_file);
+ void _set_scene_metadata(const String &p_file, int p_idx = -1);
+ void _get_scene_metadata(const String &p_file);
void _update_title();
void _update_scene_tabs();
void _close_messages();
@@ -459,37 +448,36 @@ private:
void _save_scene(String p_file, int idx = -1);
+ void _instance_request(const Vector<String> &p_files);
- void _instance_request(const Vector<String>& p_files);
-
- void _property_keyed(const String& p_keyed, const Variant& p_value, bool p_advance);
- void _transform_keyed(Object *sp,const String& p_sub,const Transform& p_key);
+ void _property_keyed(const String &p_keyed, const Variant &p_value, bool p_advance);
+ void _transform_keyed(Object *sp, const String &p_sub, const Transform &p_key);
void _hide_top_editors();
void _display_top_editors(bool p_display);
- void _set_top_editors(Vector<EditorPlugin*> p_editor_plugins_over);
- void _set_editing_top_editors(Object * p_current_object);
+ void _set_top_editors(Vector<EditorPlugin *> p_editor_plugins_over);
+ void _set_editing_top_editors(Object *p_current_object);
void _quick_opened();
void _quick_run();
- void _run(bool p_current=false, const String &p_custom="");
+ void _run(bool p_current = false, const String &p_custom = "");
void _save_optimized();
- void _import_action(const String& p_action);
+ void _import_action(const String &p_action);
void _import(const String &p_file);
- void _add_to_recent_scenes(const String& p_scene);
+ void _add_to_recent_scenes(const String &p_scene);
void _update_recent_scenes();
void _open_recent_scene(int p_idx);
- void _dropped_files(const Vector<String>& p_files,int p_screen);
+ void _dropped_files(const Vector<String> &p_files, int p_screen);
//void _open_recent_scene_confirm();
String _recent_scene;
bool convert_old;
- void _unhandled_input(const InputEvent& p_event);
+ void _unhandled_input(const InputEvent &p_event);
- static void _load_error_notify(void* p_ud,const String& p_text);
+ static void _load_error_notify(void *p_ud, const String &p_text);
bool has_main_screen() const { return true; }
@@ -497,41 +485,37 @@ private:
String import_reload_fn;
- Set<FileDialog*> file_dialogs;
- Set<EditorFileDialog*> editor_file_dialogs;
+ Set<FileDialog *> file_dialogs;
+ Set<EditorFileDialog *> editor_file_dialogs;
- Map<String,Ref<Texture> > icon_type_cache;
+ Map<String, Ref<Texture> > icon_type_cache;
bool _initializing_addons;
- Map<String,EditorPlugin*> plugin_addons;
+ Map<String, EditorPlugin *> plugin_addons;
-
- static Ref<Texture> _file_dialog_get_icon(const String& p_path);
+ static Ref<Texture> _file_dialog_get_icon(const String &p_path);
static void _file_dialog_register(FileDialog *p_dialog);
static void _file_dialog_unregister(FileDialog *p_dialog);
static void _editor_file_dialog_register(EditorFileDialog *p_dialog);
static void _editor_file_dialog_unregister(EditorFileDialog *p_dialog);
-
void _cleanup_scene();
void _remove_edited_scene();
void _remove_scene(int index);
- bool _find_and_save_resource(RES p_res,Map<RES,bool>& processed,int32_t flags);
- bool _find_and_save_edited_subresources(Object *obj,Map<RES,bool>& processed,int32_t flags);
- void _save_edited_subresources(Node* scene,Map<RES,bool>& processed,int32_t flags);
+ bool _find_and_save_resource(RES p_res, Map<RES, bool> &processed, int32_t flags);
+ bool _find_and_save_edited_subresources(Object *obj, Map<RES, bool> &processed, int32_t flags);
+ void _save_edited_subresources(Node *scene, Map<RES, bool> &processed, int32_t flags);
- void _find_node_types(Node* p_node, int&count_2d, int&count_3d);
+ void _find_node_types(Node *p_node, int &count_2d, int &count_3d);
void _save_scene_with_preview(String p_file);
+ Map<String, Set<String> > dependency_errors;
- Map<String,Set<String> > dependency_errors;
-
- static void _dependency_error_report(void *ud,const String& p_path,const String& p_dep,const String& p_type) {
- EditorNode*en=(EditorNode*)ud;
+ static void _dependency_error_report(void *ud, const String &p_path, const String &p_dep, const String &p_type) {
+ EditorNode *en = (EditorNode *)ud;
if (!en->dependency_errors.has(p_path))
- en->dependency_errors[p_path]=Set<String>();
- en->dependency_errors[p_path].insert(p_dep+"::"+p_type);
-
+ en->dependency_errors[p_path] = Set<String>();
+ en->dependency_errors[p_path].insert(p_dep + "::" + p_type);
}
struct ExportDefer {
@@ -546,9 +530,9 @@ private:
static Vector<EditorNodeInitCallback> _init_callbacks;
- bool _find_scene_in_use(Node* p_node,const String& p_path) const;
+ bool _find_scene_in_use(Node *p_node, const String &p_path) const;
- void _dock_select_input(const InputEvent& p_input);
+ void _dock_select_input(const InputEvent &p_input);
void _dock_move_left();
void _dock_move_right();
void _dock_select_draw();
@@ -560,14 +544,14 @@ private:
void _scene_tab_script_edited(int p_tab);
Dictionary _get_main_scene_state();
- void _set_main_scene_state(Dictionary p_state,Node* p_for_scene);
+ void _set_main_scene_state(Dictionary p_state, Node *p_for_scene);
int _get_current_main_editor();
void _save_docks();
void _load_docks();
- void _save_docks_to_config(Ref<ConfigFile> p_layout, const String& p_section);
- void _load_docks_from_config(Ref<ConfigFile> p_layout, const String& p_section);
+ void _save_docks_to_config(Ref<ConfigFile> p_layout, const String &p_section);
+ void _load_docks_from_config(Ref<ConfigFile> p_layout, const String &p_section);
void _update_dock_slots_visibility();
void _update_top_menu_visibility();
@@ -580,19 +564,18 @@ private:
void _update_addon_config();
- static void _file_access_close_error_notify(const String& p_str);
+ static void _file_access_close_error_notify(const String &p_str);
void _toggle_distraction_free_mode();
enum {
- MAX_INIT_CALLBACKS=128,
- MAX_BUILD_CALLBACKS=128
+ MAX_INIT_CALLBACKS = 128,
+ MAX_BUILD_CALLBACKS = 128
};
void _inherit_imported(const String &p_action);
void _open_imported();
-
static int plugin_init_callback_count;
static EditorPluginInitializeCallback plugin_init_callbacks[MAX_INIT_CALLBACKS];
@@ -612,14 +595,14 @@ private:
Vector<ToolMenuItem> tool_menu_items;
- void _tool_menu_insert_item(const ToolMenuItem& p_item);
+ void _tool_menu_insert_item(const ToolMenuItem &p_item);
void _rebuild_tool_menu() const;
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
static void add_plugin_init_callback(EditorPluginInitializeCallback p_callback);
enum EditorTable {
@@ -629,8 +612,7 @@ public:
};
void set_visible_editor(EditorTable p_table) { _editor_select(p_table); }
- static EditorNode* get_singleton() { return singleton; }
-
+ static EditorNode *get_singleton() { return singleton; }
EditorPlugin *get_editor_plugin_screen() { return editor_plugin_screen; }
EditorPluginList *get_editor_plugins_over() { return editor_plugins_over; }
@@ -640,8 +622,7 @@ public:
static void add_editor_plugin(EditorPlugin *p_editor);
static void remove_editor_plugin(EditorPlugin *p_editor);
- void new_inherited_scene() { _menu_option_confirm(FILE_NEW_INHERITED_SCENE,false); }
-
+ void new_inherited_scene() { _menu_option_confirm(FILE_NEW_INHERITED_SCENE, false); }
void set_docks_visible(bool p_show);
bool get_docks_visible() const;
@@ -649,35 +630,34 @@ public:
void set_distraction_free_mode(bool p_enter);
bool get_distraction_free_mode() const;
- void add_control_to_dock(DockSlot p_slot,Control* p_control);
- void remove_control_from_dock(Control* p_control);
+ void add_control_to_dock(DockSlot p_slot, Control *p_control);
+ void remove_control_from_dock(Control *p_control);
- void set_addon_plugin_enabled(const String& p_addon,bool p_enabled);
+ void set_addon_plugin_enabled(const String &p_addon, bool p_enabled);
bool is_addon_plugin_enabled(const String &p_addon) const;
void edit_node(Node *p_node);
- void edit_resource(const Ref<Resource>& p_resource);
- void open_resource(const String& p_type="");
+ void edit_resource(const Ref<Resource> &p_resource);
+ void open_resource(const String &p_type = "");
- void save_resource_in_path(const Ref<Resource>& p_resource,const String& p_path);
- void save_resource(const Ref<Resource>& p_resource);
- void save_resource_as(const Ref<Resource>& p_resource, const String &p_at_path=String());
+ void save_resource_in_path(const Ref<Resource> &p_resource, const String &p_path);
+ void save_resource(const Ref<Resource> &p_resource);
+ void save_resource_as(const Ref<Resource> &p_resource, const String &p_at_path = String());
- void merge_from_scene() { _menu_option_confirm(FILE_IMPORT_SUBSCENE,false); }
+ void merge_from_scene() { _menu_option_confirm(FILE_IMPORT_SUBSCENE, false); }
static bool has_unsaved_changes() { return singleton->unsaved_cache; }
static HBoxContainer *get_menu_hb() { return singleton->menu_hb; }
- void push_item(Object *p_object,const String& p_property="");
+ void push_item(Object *p_object, const String &p_property = "");
- void open_request(const String& p_path);
+ void open_request(const String &p_path);
bool is_changing_scene() const;
-
static EditorLog *get_log() { return singleton->log; }
- Control* get_viewport();
+ Control *get_viewport();
//void animation_editor_make_visible(bool p_visible);
//void hide_animation_player_editors();
@@ -689,31 +669,31 @@ public:
Viewport *get_scene_root() { return scene_root; } //root of the scene being edited
- void fix_dependencies(const String& p_for_file);
+ void fix_dependencies(const String &p_for_file);
void clear_scene() { _cleanup_scene(); }
- Error load_scene(const String& p_scene, bool p_ignore_broken_deps=false, bool p_set_inherited=false, bool p_clear_errors=true,bool p_force_open_imported=false);
- Error load_resource(const String& p_scene);
+ Error load_scene(const String &p_scene, bool p_ignore_broken_deps = false, bool p_set_inherited = false, bool p_clear_errors = true, bool p_force_open_imported = false);
+ Error load_resource(const String &p_scene);
- bool is_scene_open(const String& p_path);
+ bool is_scene_open(const String &p_path);
void set_current_version(uint64_t p_version);
void set_current_scene(int p_idx);
- static EditorData& get_editor_data() { return singleton->editor_data; }
- EditorHistory * get_editor_history() { return &editor_history; }
+ static EditorData &get_editor_data() { return singleton->editor_data; }
+ EditorHistory *get_editor_history() { return &editor_history; }
static VSplitContainer *get_top_split() { return singleton->top_split; }
void request_instance_scene(const String &p_path);
- void request_instance_scenes(const Vector<String>& p_files);
+ void request_instance_scenes(const Vector<String> &p_files);
FileSystemDock *get_filesystem_dock();
ImportDock *get_import_dock();
SceneTreeDock *get_scene_tree_dock();
- static UndoRedo* get_undo_redo() { return &singleton->editor_data.get_undo_redo(); }
+ static UndoRedo *get_undo_redo() { return &singleton->editor_data.get_undo_redo(); }
EditorSelection *get_editor_selection() { return editor_selection; }
- void set_convert_old_scene(bool p_old) { convert_old=p_old; }
+ void set_convert_old_scene(bool p_old) { convert_old = p_old; }
void notify_child_process_exited();
@@ -722,11 +702,9 @@ public:
Ref<Theme> get_editor_theme() const { return theme; }
+ void show_warning(const String &p_text, const String &p_title = "Warning!");
- void show_warning(const String& p_text,const String& p_title="Warning!");
-
-
- Error export_platform(const String& p_platform, const String& p_path, bool p_debug,const String& p_password,bool p_quit_after=false);
+ Error export_platform(const String &p_platform, const String &p_path, bool p_debug, const String &p_password, bool p_quit_after = false);
static void register_editor_types();
static void unregister_editor_types();
@@ -734,19 +712,19 @@ public:
Control *get_gui_base() { return gui_base; }
Control *get_theme_base() { return gui_base->get_parent_control(); }
- static void add_io_error(const String& p_error);
+ static void add_io_error(const String &p_error);
- static void progress_add_task(const String& p_task,const String& p_label, int p_steps);
- static void progress_task_step(const String& p_task,const String& p_state, int p_step=-1,bool p_force_refresh=true);
- static void progress_end_task(const String& p_task);
+ static void progress_add_task(const String &p_task, const String &p_label, int p_steps);
+ static void progress_task_step(const String &p_task, const String &p_state, int p_step = -1, bool p_force_refresh = true);
+ static void progress_end_task(const String &p_task);
- static void progress_add_task_bg(const String& p_task,const String& p_label, int p_steps);
- static void progress_task_step_bg(const String& p_task,int p_step=-1);
- static void progress_end_task_bg(const String& p_task);
+ static void progress_add_task_bg(const String &p_task, const String &p_label, int p_steps);
+ static void progress_task_step_bg(const String &p_task, int p_step = -1);
+ static void progress_end_task_bg(const String &p_task);
void save_scene(String p_file) { _save_scene(p_file); }
- bool is_scene_in_use(const String& p_path);
+ bool is_scene_in_use(const String &p_path);
void scan_import_changes();
@@ -754,79 +732,79 @@ public:
void update_keying();
- void reload_scene(const String& p_path);
+ void reload_scene(const String &p_path);
bool is_exiting() const { return exiting; }
ToolButton *get_pause_button() { return pause_button; }
-
- ToolButton* add_bottom_panel_item(String p_text,Control *p_item);
+ ToolButton *add_bottom_panel_item(String p_text, Control *p_item);
bool are_bottom_panels_hidden() const;
void make_bottom_panel_item_visible(Control *p_item);
void raise_bottom_panel_item(Control *p_item);
void hide_bottom_panel();
void remove_bottom_panel_item(Control *p_item);
- Variant drag_resource(const Ref<Resource>& p_res,Control* p_from);
- Variant drag_files(const Vector<String>& p_files,Control* p_from);
- Variant drag_files_and_dirs(const Vector<String>& p_files,Control* p_from);
+ Variant drag_resource(const Ref<Resource> &p_res, Control *p_from);
+ Variant drag_files(const Vector<String> &p_files, Control *p_from);
+ Variant drag_files_and_dirs(const Vector<String> &p_files, Control *p_from);
- void add_tool_menu_item(const String& p_name, Object *p_handler, const String& p_callback, const Variant& p_ud = Variant());
- void add_tool_submenu_item(const String& p_name, PopupMenu *p_submenu);
- void remove_tool_menu_item(const String& p_name);
+ void add_tool_menu_item(const String &p_name, Object *p_handler, const String &p_callback, const Variant &p_ud = Variant());
+ void add_tool_submenu_item(const String &p_name, PopupMenu *p_submenu);
+ void remove_tool_menu_item(const String &p_name);
EditorNode();
~EditorNode();
- void get_singleton(const char* arg1, bool arg2);
+ void get_singleton(const char *arg1, bool arg2);
static void add_init_callback(EditorNodeInitCallback p_callback) { _init_callbacks.push_back(p_callback); }
static void add_build_callback(EditorBuildCallback p_callback);
-
-
-
};
struct EditorProgress {
String task;
- void step(const String& p_state, int p_step=-1,bool p_force_refresh=true) { EditorNode::progress_task_step(task,p_state,p_step,p_force_refresh); }
- EditorProgress(const String& p_task,const String& p_label,int p_amount) { EditorNode::progress_add_task(p_task,p_label,p_amount); task=p_task; }
+ void step(const String &p_state, int p_step = -1, bool p_force_refresh = true) { EditorNode::progress_task_step(task, p_state, p_step, p_force_refresh); }
+ EditorProgress(const String &p_task, const String &p_label, int p_amount) {
+ EditorNode::progress_add_task(p_task, p_label, p_amount);
+ task = p_task;
+ }
~EditorProgress() { EditorNode::progress_end_task(task); }
};
class EditorPluginList : public Object {
private:
- Vector<EditorPlugin*> plugins_list;
+ Vector<EditorPlugin *> plugins_list;
public:
-
- void set_plugins_list(Vector<EditorPlugin*> p_plugins_list) {
+ void set_plugins_list(Vector<EditorPlugin *> p_plugins_list) {
plugins_list = p_plugins_list;
}
- Vector<EditorPlugin*>& get_plugins_list() {
+ Vector<EditorPlugin *> &get_plugins_list() {
return plugins_list;
}
void make_visible(bool p_visible);
void edit(Object *p_object);
- bool forward_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event);
- bool forward_spatial_gui_input(Camera* p_camera, const InputEvent& p_event);
- void forward_draw_over_canvas(const Transform2D& p_canvas_xform,Control* p_canvas);
+ bool forward_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event);
+ bool forward_spatial_gui_input(Camera *p_camera, const InputEvent &p_event);
+ void forward_draw_over_canvas(const Transform2D &p_canvas_xform, Control *p_canvas);
void clear();
bool empty();
EditorPluginList();
~EditorPluginList();
-
-} ;
+};
struct EditorProgressBG {
String task;
- void step(int p_step=-1) { EditorNode::progress_task_step_bg(task,p_step); }
- EditorProgressBG(const String& p_task,const String& p_label,int p_amount) { EditorNode::progress_add_task_bg(p_task,p_label,p_amount); task=p_task; }
+ void step(int p_step = -1) { EditorNode::progress_task_step_bg(task, p_step); }
+ EditorProgressBG(const String &p_task, const String &p_label, int p_amount) {
+ EditorNode::progress_add_task_bg(p_task, p_label, p_amount);
+ task = p_task;
+ }
~EditorProgressBG() { EditorNode::progress_end_task_bg(task); }
};
diff --git a/editor/editor_path.cpp b/editor/editor_path.cpp
index 8cd31c4bcc..0200278dc0 100644
--- a/editor/editor_path.cpp
+++ b/editor/editor_path.cpp
@@ -28,25 +28,25 @@
/*************************************************************************/
#include "editor_path.h"
-#include "editor_scale.h"
#include "editor_node.h"
+#include "editor_scale.h"
-void EditorPath::_add_children_to_popup(Object* p_obj,int p_depth) {
+void EditorPath::_add_children_to_popup(Object *p_obj, int p_depth) {
- if (p_depth>8)
+ if (p_depth > 8)
return;
List<PropertyInfo> pinfo;
p_obj->get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_EDITOR))
+ if (!(E->get().usage & PROPERTY_USAGE_EDITOR))
continue;
- if (E->get().hint!=PROPERTY_HINT_RESOURCE_TYPE)
+ if (E->get().hint != PROPERTY_HINT_RESOURCE_TYPE)
continue;
Variant value = p_obj->get(E->get().name);
- if (value.get_type()!=Variant::OBJECT)
+ if (value.get_type() != Variant::OBJECT)
continue;
Object *obj = value;
if (!obj)
@@ -54,69 +54,64 @@ void EditorPath::_add_children_to_popup(Object* p_obj,int p_depth) {
Ref<Texture> icon;
- if (has_icon(obj->get_class(),"EditorIcons"))
- icon=get_icon(obj->get_class(),"EditorIcons");
+ if (has_icon(obj->get_class(), "EditorIcons"))
+ icon = get_icon(obj->get_class(), "EditorIcons");
else
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
int index = popup->get_item_count();
- popup->add_icon_item(icon,E->get().name.capitalize(),objects.size());
- popup->set_item_h_offset(index,p_depth*10*EDSCALE);
+ popup->add_icon_item(icon, E->get().name.capitalize(), objects.size());
+ popup->set_item_h_offset(index, p_depth * 10 * EDSCALE);
objects.push_back(obj->get_instance_ID());
- _add_children_to_popup(obj,p_depth+1);
+ _add_children_to_popup(obj, p_depth + 1);
}
}
-void EditorPath::_gui_input(const InputEvent& p_event) {
+void EditorPath::_gui_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==BUTTON_LEFT && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == BUTTON_LEFT && p_event.mouse_button.pressed) {
-
- Object *obj = ObjectDB::get_instance(history->get_path_object( history->get_path_size()-1));
+ Object *obj = ObjectDB::get_instance(history->get_path_object(history->get_path_size() - 1));
if (!obj)
return;
-
-
objects.clear();
popup->clear();
_add_children_to_popup(obj);
- popup->set_pos( get_global_pos() + Vector2(0,get_size().height));
- popup->set_size( Size2(get_size().width,1));
+ popup->set_pos(get_global_pos() + Vector2(0, get_size().height));
+ popup->set_size(Size2(get_size().width, 1));
popup->popup();
}
}
void EditorPath::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_MOUSE_ENTER: {
- mouse_over=true;
+ mouse_over = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
- mouse_over=false;
+ mouse_over = false;
update();
} break;
case NOTIFICATION_DRAW: {
- RID ci=get_canvas_item();
- Ref<Font> label_font = get_font("font","Label");
+ RID ci = get_canvas_item();
+ Ref<Font> label_font = get_font("font", "Label");
Size2i size = get_size();
- Ref<Texture> sn = get_icon("SmallNext","EditorIcons");
- Ref<StyleBox> sb = get_stylebox("pressed","Button");
-
+ Ref<Texture> sn = get_icon("SmallNext", "EditorIcons");
+ Ref<StyleBox> sb = get_stylebox("pressed", "Button");
- int ofs=sb->get_margin(MARGIN_LEFT);
+ int ofs = sb->get_margin(MARGIN_LEFT);
if (mouse_over) {
- draw_style_box(sb,Rect2(Point2(),get_size()));
+ draw_style_box(sb, Rect2(Point2(), get_size()));
}
- for(int i=0;i<history->get_path_size();i++) {
+ for (int i = 0; i < history->get_path_size(); i++) {
Object *obj = ObjectDB::get_instance(history->get_path_object(i));
if (!obj)
@@ -126,53 +121,50 @@ void EditorPath::_notification(int p_what) {
Ref<Texture> icon;
- if (has_icon(obj->get_class(),"EditorIcons"))
- icon=get_icon(obj->get_class(),"EditorIcons");
+ if (has_icon(obj->get_class(), "EditorIcons"))
+ icon = get_icon(obj->get_class(), "EditorIcons");
else
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
+ icon->draw(ci, Point2i(ofs, (size.height - icon->get_height()) / 2));
- icon->draw(ci,Point2i(ofs,(size.height-icon->get_height())/2));
+ ofs += icon->get_width();
- ofs+=icon->get_width();
-
- if (i==history->get_path_size()-1) {
+ if (i == history->get_path_size() - 1) {
//add name
- ofs+=4;
+ ofs += 4;
int left = size.width - ofs;
- if (left<0)
+ if (left < 0)
continue;
String name;
if (obj->cast_to<Resource>()) {
Resource *r = obj->cast_to<Resource>();
if (r->get_path().is_resource_file())
- name=r->get_path().get_file();
+ name = r->get_path().get_file();
else
- name=r->get_name();
+ name = r->get_name();
- if (name=="")
- name=r->get_class();
+ if (name == "")
+ name = r->get_class();
} else if (obj->cast_to<Node>()) {
- name=obj->cast_to<Node>()->get_name();
- } else if (obj->cast_to<Resource>() && obj->cast_to<Resource>()->get_name()!="") {
- name=obj->cast_to<Resource>()->get_name();
+ name = obj->cast_to<Node>()->get_name();
+ } else if (obj->cast_to<Resource>() && obj->cast_to<Resource>()->get_name() != "") {
+ name = obj->cast_to<Resource>()->get_name();
} else {
- name=obj->get_class();
+ name = obj->get_class();
}
set_tooltip(obj->get_class());
-
- label_font->draw(ci,Point2i(ofs,(size.height-label_font->get_height())/2+label_font->get_ascent()),name,Color(1,1,1),left);
+ label_font->draw(ci, Point2i(ofs, (size.height - label_font->get_height()) / 2 + label_font->get_ascent()), name, Color(1, 1, 1), left);
} else {
//add arrow
//sn->draw(ci,Point2i(ofs,(size.height-sn->get_height())/2));
//ofs+=sn->get_width();
- ofs+=5; //just looks better! somehow
-
+ ofs += 5; //just looks better! somehow
}
}
@@ -182,15 +174,14 @@ void EditorPath::_notification(int p_what) {
void EditorPath::update_path() {
-
update();
}
void EditorPath::_popup_select(int p_idx) {
- ERR_FAIL_INDEX(p_idx,objects.size());
+ ERR_FAIL_INDEX(p_idx, objects.size());
- Object* obj = ObjectDB::get_instance(objects[p_idx]);
+ Object *obj = ObjectDB::get_instance(objects[p_idx]);
if (!obj)
return;
@@ -199,17 +190,15 @@ void EditorPath::_popup_select(int p_idx) {
void EditorPath::_bind_methods() {
- ClassDB::bind_method("_gui_input",&EditorPath::_gui_input);
- ClassDB::bind_method("_popup_select",&EditorPath::_popup_select);
+ ClassDB::bind_method("_gui_input", &EditorPath::_gui_input);
+ ClassDB::bind_method("_popup_select", &EditorPath::_popup_select);
}
EditorPath::EditorPath(EditorHistory *p_history) {
- history=p_history;
- mouse_over=false;
- popup = memnew( PopupMenu );
- popup->connect("id_pressed",this,"_popup_select");
+ history = p_history;
+ mouse_over = false;
+ popup = memnew(PopupMenu);
+ popup->connect("id_pressed", this, "_popup_select");
add_child(popup);
-
-
}
diff --git a/editor/editor_path.h b/editor/editor_path.h
index fd5b469d07..d781f6609a 100644
--- a/editor/editor_path.h
+++ b/editor/editor_path.h
@@ -29,32 +29,30 @@
#ifndef EDITOR_PATH_H
#define EDITOR_PATH_H
+#include "editor_data.h"
#include "scene/gui/control.h"
#include "scene/gui/popup_menu.h"
-#include "editor_data.h"
class EditorPath : public Control {
- GDCLASS(EditorPath,Control);
+ GDCLASS(EditorPath, Control);
EditorHistory *history;
-
Vector<ObjectID> objects;
PopupMenu *popup;
bool mouse_over;
EditorPath();
void _popup_select(int p_idx);
- void _gui_input(const InputEvent& p_event);
- void _add_children_to_popup(Object* p_obj,int p_depth=0);
-protected:
+ void _gui_input(const InputEvent &p_event);
+ void _add_children_to_popup(Object *p_obj, int p_depth = 0);
+protected:
static void _bind_methods();
void _notification(int p_what);
public:
-
void update_path();
EditorPath(EditorHistory *p_history);
diff --git a/editor/editor_plugin.cpp b/editor/editor_plugin.cpp
index 85ef96fcc3..2579871d78 100644
--- a/editor/editor_plugin.cpp
+++ b/editor/editor_plugin.cpp
@@ -28,64 +28,60 @@
/*************************************************************************/
#include "editor_plugin.h"
-#include "scene/gui/popup_menu.h"
-#include "scene/3d/camera.h"
-#include "plugins/canvas_item_editor_plugin.h"
-#include "plugins/spatial_editor_plugin.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
#include "editor_resource_preview.h"
+#include "plugins/canvas_item_editor_plugin.h"
+#include "plugins/spatial_editor_plugin.h"
+#include "scene/3d/camera.h"
+#include "scene/gui/popup_menu.h"
-void EditorPlugin::add_custom_type(const String& p_type, const String& p_base,const Ref<Script>& p_script, const Ref<Texture>& p_icon) {
+void EditorPlugin::add_custom_type(const String &p_type, const String &p_base, const Ref<Script> &p_script, const Ref<Texture> &p_icon) {
- EditorNode::get_editor_data().add_custom_type(p_type,p_base,p_script,p_icon);
+ EditorNode::get_editor_data().add_custom_type(p_type, p_base, p_script, p_icon);
}
-void EditorPlugin::remove_custom_type(const String& p_type){
+void EditorPlugin::remove_custom_type(const String &p_type) {
EditorNode::get_editor_data().remove_custom_type(p_type);
}
+ToolButton *EditorPlugin::add_control_to_bottom_panel(Control *p_control, const String &p_title) {
-ToolButton * EditorPlugin::add_control_to_bottom_panel(Control *p_control, const String &p_title) {
-
- return EditorNode::get_singleton()->add_bottom_panel_item(p_title,p_control);
+ return EditorNode::get_singleton()->add_bottom_panel_item(p_title, p_control);
}
-void EditorPlugin::add_control_to_dock(DockSlot p_slot,Control *p_control) {
+void EditorPlugin::add_control_to_dock(DockSlot p_slot, Control *p_control) {
ERR_FAIL_NULL(p_control);
- EditorNode::get_singleton()->add_control_to_dock(EditorNode::DockSlot(p_slot),p_control);
-
+ EditorNode::get_singleton()->add_control_to_dock(EditorNode::DockSlot(p_slot), p_control);
}
void EditorPlugin::remove_control_from_docks(Control *p_control) {
ERR_FAIL_NULL(p_control);
EditorNode::get_singleton()->remove_control_from_dock(p_control);
-
}
void EditorPlugin::remove_control_from_bottom_panel(Control *p_control) {
ERR_FAIL_NULL(p_control);
EditorNode::get_singleton()->remove_bottom_panel_item(p_control);
-
}
-Control * EditorPlugin::get_editor_viewport() {
+Control *EditorPlugin::get_editor_viewport() {
return EditorNode::get_singleton()->get_viewport();
}
-void EditorPlugin::edit_resource(const Ref<Resource>& p_resource){
+void EditorPlugin::edit_resource(const Ref<Resource> &p_resource) {
EditorNode::get_singleton()->edit_resource(p_resource);
}
-void EditorPlugin::add_control_to_container(CustomControlContainer p_location,Control *p_control) {
+void EditorPlugin::add_control_to_container(CustomControlContainer p_location, Control *p_control) {
- switch(p_location) {
+ switch (p_location) {
case CONTAINER_TOOLBAR: {
@@ -100,7 +96,7 @@ void EditorPlugin::add_control_to_container(CustomControlContainer p_location,Co
case CONTAINER_SPATIAL_EDITOR_SIDE: {
SpatialEditor::get_singleton()->get_palette_split()->add_child(p_control);
- SpatialEditor::get_singleton()->get_palette_split()->move_child(p_control,0);
+ SpatialEditor::get_singleton()->get_palette_split()->move_child(p_control, 0);
} break;
case CONTAINER_SPATIAL_EDITOR_BOTTOM: {
@@ -116,7 +112,7 @@ void EditorPlugin::add_control_to_container(CustomControlContainer p_location,Co
case CONTAINER_CANVAS_EDITOR_SIDE: {
CanvasItemEditor::get_singleton()->get_palette_split()->add_child(p_control);
- CanvasItemEditor::get_singleton()->get_palette_split()->move_child(p_control,0);
+ CanvasItemEditor::get_singleton()->get_palette_split()->move_child(p_control, 0);
} break;
case CONTAINER_CANVAS_EDITOR_BOTTOM: {
@@ -129,17 +125,15 @@ void EditorPlugin::add_control_to_container(CustomControlContainer p_location,Co
EditorNode::get_singleton()->get_property_editor_vb()->add_child(p_control);
} break;
-
-
}
}
-void EditorPlugin::add_tool_menu_item(const String& p_name, Object *p_handler, const String& p_callback, const Variant& p_ud) {
+void EditorPlugin::add_tool_menu_item(const String &p_name, Object *p_handler, const String &p_callback, const Variant &p_ud) {
//EditorNode::get_singleton()->add_tool_menu_item(p_name, p_handler, p_callback, p_ud);
}
-void EditorPlugin::add_tool_submenu_item(const String& p_name, Object *p_submenu) {
+void EditorPlugin::add_tool_submenu_item(const String &p_name, Object *p_submenu) {
ERR_FAIL_NULL(p_submenu);
PopupMenu *submenu = p_submenu->cast_to<PopupMenu>();
@@ -147,32 +141,32 @@ void EditorPlugin::add_tool_submenu_item(const String& p_name, Object *p_submenu
//EditorNode::get_singleton()->add_tool_submenu_item(p_name, submenu);
}
-void EditorPlugin::remove_tool_menu_item(const String& p_name) {
+void EditorPlugin::remove_tool_menu_item(const String &p_name) {
//EditorNode::get_singleton()->remove_tool_menu_item(p_name);
}
-Ref<SpatialEditorGizmo> EditorPlugin::create_spatial_gizmo(Spatial* p_spatial) {
+Ref<SpatialEditorGizmo> EditorPlugin::create_spatial_gizmo(Spatial *p_spatial) {
//??
if (get_script_instance() && get_script_instance()->has_method("create_spatial_gizmo")) {
- return get_script_instance()->call("create_spatial_gizmo",p_spatial);
+ return get_script_instance()->call("create_spatial_gizmo", p_spatial);
}
return Ref<SpatialEditorGizmo>();
}
-bool EditorPlugin::forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) {
+bool EditorPlugin::forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) {
if (get_script_instance() && get_script_instance()->has_method("forward_canvas_gui_input")) {
- return get_script_instance()->call("forward_canvas_gui_input",p_canvas_xform,p_event);
+ return get_script_instance()->call("forward_canvas_gui_input", p_canvas_xform, p_event);
}
return false;
}
-void EditorPlugin::forward_draw_over_canvas(const Transform2D& p_canvas_xform,Control *p_canvas) {
+void EditorPlugin::forward_draw_over_canvas(const Transform2D &p_canvas_xform, Control *p_canvas) {
if (get_script_instance() && get_script_instance()->has_method("forward_draw_over_canvas")) {
- get_script_instance()->call("forward_draw_over_canvas",p_canvas_xform,p_canvas);
+ get_script_instance()->call("forward_draw_over_canvas", p_canvas_xform, p_canvas);
}
}
@@ -180,10 +174,10 @@ void EditorPlugin::update_canvas() {
CanvasItemEditor::get_singleton()->get_viewport_control()->update();
}
-bool EditorPlugin::forward_spatial_gui_input(Camera* p_camera,const InputEvent& p_event) {
+bool EditorPlugin::forward_spatial_gui_input(Camera *p_camera, const InputEvent &p_event) {
if (get_script_instance() && get_script_instance()->has_method("forward_spatial_gui_input")) {
- return get_script_instance()->call("forward_spatial_gui_input",p_camera,p_event);
+ return get_script_instance()->call("forward_spatial_gui_input", p_camera, p_event);
}
return false;
@@ -195,7 +189,6 @@ String EditorPlugin::get_name() const {
}
return String();
-
}
bool EditorPlugin::has_main_screen() const {
@@ -204,28 +197,25 @@ bool EditorPlugin::has_main_screen() const {
}
return false;
-
}
void EditorPlugin::make_visible(bool p_visible) {
if (get_script_instance() && get_script_instance()->has_method("make_visible")) {
- get_script_instance()->call("make_visible",p_visible);
+ get_script_instance()->call("make_visible", p_visible);
}
}
-
void EditorPlugin::edit(Object *p_object) {
if (get_script_instance() && get_script_instance()->has_method("edit")) {
- get_script_instance()->call("edit",p_object);
+ get_script_instance()->call("edit", p_object);
}
-
}
bool EditorPlugin::handles(Object *p_object) const {
if (get_script_instance() && get_script_instance()->has_method("handles")) {
- return get_script_instance()->call("handles",p_object);
+ return get_script_instance()->call("handles", p_object);
}
return false;
@@ -239,10 +229,10 @@ Dictionary EditorPlugin::get_state() const {
return Dictionary();
}
-void EditorPlugin::set_state(const Dictionary& p_state) {
+void EditorPlugin::set_state(const Dictionary &p_state) {
if (get_script_instance() && get_script_instance()->has_method("set_state")) {
- get_script_instance()->call("set_state",p_state);
+ get_script_instance()->call("set_state", p_state);
}
}
@@ -251,7 +241,6 @@ void EditorPlugin::clear() {
if (get_script_instance() && get_script_instance()->has_method("clear")) {
get_script_instance()->call("clear");
}
-
}
// if editor references external resources/scenes, save them
@@ -274,12 +263,11 @@ void EditorPlugin::get_breakpoints(List<String> *p_breakpoints) {
if (get_script_instance() && get_script_instance()->has_method("get_breakpoints")) {
PoolStringArray arr = get_script_instance()->call("get_breakpoints");
- for(int i=0;i<arr.size();i++)
+ for (int i = 0; i < arr.size(); i++)
p_breakpoints->push_back(arr[i]);
}
-
}
-bool EditorPlugin::get_remove_list(List<Node*> *p_list) {
+bool EditorPlugin::get_remove_list(List<Node *> *p_list) {
return false;
}
@@ -294,7 +282,7 @@ void EditorPlugin::set_window_layout(Ref<ConfigFile> p_layout) {
}
}
-void EditorPlugin::get_window_layout(Ref<ConfigFile> p_layout){
+void EditorPlugin::get_window_layout(Ref<ConfigFile> p_layout) {
if (get_script_instance() && get_script_instance()->has_method("get_window_layout")) {
get_script_instance()->call("get_window_layout", p_layout);
@@ -306,11 +294,10 @@ void EditorPlugin::queue_save_layout() const {
EditorNode::get_singleton()->save_layout();
}
-EditorSelection* EditorPlugin::get_selection() {
+EditorSelection *EditorPlugin::get_selection() {
return EditorNode::get_singleton()->get_editor_selection();
}
-
EditorSettings *EditorPlugin::get_editor_settings() {
return EditorSettings::get_singleton();
}
@@ -324,7 +311,7 @@ Control *EditorPlugin::get_base_control() {
return EditorNode::get_singleton()->get_gui_base();
}
-void EditorPlugin::make_bottom_panel_item_visible(Control * p_item) {
+void EditorPlugin::make_bottom_panel_item_visible(Control *p_item) {
EditorNode::get_singleton()->make_bottom_panel_item_visible(p_item);
}
@@ -334,9 +321,9 @@ void EditorPlugin::hide_bottom_panel() {
EditorNode::get_singleton()->hide_bottom_panel();
}
-void EditorPlugin::inspect_object(Object *p_obj,const String& p_for_property) {
+void EditorPlugin::inspect_object(Object *p_obj, const String &p_for_property) {
- EditorNode::get_singleton()->push_item(p_obj,p_for_property);
+ EditorNode::get_singleton()->push_item(p_obj, p_for_property);
}
EditorFileSystem *EditorPlugin::get_resource_file_system() {
@@ -345,88 +332,81 @@ EditorFileSystem *EditorPlugin::get_resource_file_system() {
void EditorPlugin::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_control_to_container","container","control:Control"),&EditorPlugin::add_control_to_container);
- ClassDB::bind_method(D_METHOD("add_control_to_bottom_panel:ToolButton","control:Control","title"),&EditorPlugin::add_control_to_bottom_panel);
- ClassDB::bind_method(D_METHOD("add_control_to_dock","slot","control:Control"),&EditorPlugin::add_control_to_dock);
- ClassDB::bind_method(D_METHOD("remove_control_from_docks","control:Control"),&EditorPlugin::remove_control_from_docks);
- ClassDB::bind_method(D_METHOD("remove_control_from_bottom_panel","control:Control"),&EditorPlugin::remove_control_from_bottom_panel);
+ ClassDB::bind_method(D_METHOD("add_control_to_container", "container", "control:Control"), &EditorPlugin::add_control_to_container);
+ ClassDB::bind_method(D_METHOD("add_control_to_bottom_panel:ToolButton", "control:Control", "title"), &EditorPlugin::add_control_to_bottom_panel);
+ ClassDB::bind_method(D_METHOD("add_control_to_dock", "slot", "control:Control"), &EditorPlugin::add_control_to_dock);
+ ClassDB::bind_method(D_METHOD("remove_control_from_docks", "control:Control"), &EditorPlugin::remove_control_from_docks);
+ ClassDB::bind_method(D_METHOD("remove_control_from_bottom_panel", "control:Control"), &EditorPlugin::remove_control_from_bottom_panel);
//ClassDB::bind_method(D_METHOD("add_tool_menu_item", "name", "handler", "callback", "ud"),&EditorPlugin::add_tool_menu_item,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("add_tool_submenu_item", "name", "submenu:PopupMenu"),&EditorPlugin::add_tool_submenu_item);
+ ClassDB::bind_method(D_METHOD("add_tool_submenu_item", "name", "submenu:PopupMenu"), &EditorPlugin::add_tool_submenu_item);
//ClassDB::bind_method(D_METHOD("remove_tool_menu_item", "name"),&EditorPlugin::remove_tool_menu_item);
- ClassDB::bind_method(D_METHOD("add_custom_type","type","base","script:Script","icon:Texture"),&EditorPlugin::add_custom_type);
- ClassDB::bind_method(D_METHOD("remove_custom_type","type"),&EditorPlugin::remove_custom_type);
+ ClassDB::bind_method(D_METHOD("add_custom_type", "type", "base", "script:Script", "icon:Texture"), &EditorPlugin::add_custom_type);
+ ClassDB::bind_method(D_METHOD("remove_custom_type", "type"), &EditorPlugin::remove_custom_type);
ClassDB::bind_method(D_METHOD("get_editor_viewport:Control"), &EditorPlugin::get_editor_viewport);
- ClassDB::bind_method(D_METHOD("get_resource_previewer:EditorResourcePreview"),&EditorPlugin::get_resource_previewer);
- ClassDB::bind_method(D_METHOD("get_resource_filesystem:EditorFileSystem"),&EditorPlugin::get_resource_file_system);
+ ClassDB::bind_method(D_METHOD("get_resource_previewer:EditorResourcePreview"), &EditorPlugin::get_resource_previewer);
+ ClassDB::bind_method(D_METHOD("get_resource_filesystem:EditorFileSystem"), &EditorPlugin::get_resource_file_system);
- ClassDB::bind_method(D_METHOD("inspect_object","object","for_property"),&EditorPlugin::inspect_object,DEFVAL(String()));
- ClassDB::bind_method(D_METHOD("update_canvas"),&EditorPlugin::update_canvas);
+ ClassDB::bind_method(D_METHOD("inspect_object", "object", "for_property"), &EditorPlugin::inspect_object, DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("update_canvas"), &EditorPlugin::update_canvas);
- ClassDB::bind_method(D_METHOD("make_bottom_panel_item_visible","item:Control"), &EditorPlugin::make_bottom_panel_item_visible);
+ ClassDB::bind_method(D_METHOD("make_bottom_panel_item_visible", "item:Control"), &EditorPlugin::make_bottom_panel_item_visible);
ClassDB::bind_method(D_METHOD("hide_bottom_panel"), &EditorPlugin::hide_bottom_panel);
- ClassDB::bind_method(D_METHOD("get_base_control:Control"),&EditorPlugin::get_base_control);
- ClassDB::bind_method(D_METHOD("get_undo_redo:UndoRedo"),&EditorPlugin::_get_undo_redo);
- ClassDB::bind_method(D_METHOD("get_selection:EditorSelection"),&EditorPlugin::get_selection);
- ClassDB::bind_method(D_METHOD("get_editor_settings:EditorSettings"),&EditorPlugin::get_editor_settings);
- ClassDB::bind_method(D_METHOD("queue_save_layout"),&EditorPlugin::queue_save_layout);
- ClassDB::bind_method(D_METHOD("edit_resource"),&EditorPlugin::edit_resource);
-
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::BOOL,"forward_canvas_gui_input",PropertyInfo(Variant::TRANSFORM2D,"canvas_xform"),PropertyInfo(Variant::INPUT_EVENT,"event")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("forward_draw_over_canvas",PropertyInfo(Variant::TRANSFORM2D,"canvas_xform"),PropertyInfo(Variant::OBJECT,"canvas:Control")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::BOOL,"forward_spatial_gui_input",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera"),PropertyInfo(Variant::INPUT_EVENT,"event")));
- MethodInfo gizmo = MethodInfo(Variant::OBJECT,"create_spatial_gizmo",PropertyInfo(Variant::OBJECT,"for_spatial:Spatial"));
- gizmo.return_val.hint=PROPERTY_HINT_RESOURCE_TYPE;
- gizmo.return_val.hint_string="EditorSpatialGizmo";
- ClassDB::add_virtual_method(get_class_static(),gizmo);
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::STRING,"get_name"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::BOOL,"has_main_screen"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("make_visible",PropertyInfo(Variant::BOOL,"visible")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("edit",PropertyInfo(Variant::OBJECT,"object")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::BOOL,"handles",PropertyInfo(Variant::OBJECT,"object")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::DICTIONARY,"get_state"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("set_state",PropertyInfo(Variant::DICTIONARY,"state")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("clear"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("save_external_data"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("apply_changes"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::POOL_STRING_ARRAY,"get_breakpoints"));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("set_window_layout",PropertyInfo(Variant::OBJECT,"layout",PROPERTY_HINT_RESOURCE_TYPE,"ConfigFile")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo("get_window_layout",PropertyInfo(Variant::OBJECT,"layout",PROPERTY_HINT_RESOURCE_TYPE,"ConfigFile")));
-
- BIND_CONSTANT( CONTAINER_TOOLBAR );
- BIND_CONSTANT( CONTAINER_SPATIAL_EDITOR_MENU );
- BIND_CONSTANT( CONTAINER_SPATIAL_EDITOR_SIDE );
- BIND_CONSTANT( CONTAINER_SPATIAL_EDITOR_BOTTOM );
- BIND_CONSTANT( CONTAINER_CANVAS_EDITOR_MENU );
- BIND_CONSTANT( CONTAINER_CANVAS_EDITOR_SIDE );
- BIND_CONSTANT( CONTAINER_PROPERTY_EDITOR_BOTTOM );
-
-
- BIND_CONSTANT( DOCK_SLOT_LEFT_UL );
- BIND_CONSTANT( DOCK_SLOT_LEFT_BL );
- BIND_CONSTANT( DOCK_SLOT_LEFT_UR );
- BIND_CONSTANT( DOCK_SLOT_LEFT_BR );
- BIND_CONSTANT( DOCK_SLOT_RIGHT_UL );
- BIND_CONSTANT( DOCK_SLOT_RIGHT_BL );
- BIND_CONSTANT( DOCK_SLOT_RIGHT_UR );
- BIND_CONSTANT( DOCK_SLOT_RIGHT_BR );
- BIND_CONSTANT( DOCK_SLOT_MAX );
-
-}
-
-EditorPlugin::EditorPlugin()
-{
- undo_redo=NULL;
-}
-
-
-EditorPlugin::~EditorPlugin()
-{
+ ClassDB::bind_method(D_METHOD("get_base_control:Control"), &EditorPlugin::get_base_control);
+ ClassDB::bind_method(D_METHOD("get_undo_redo:UndoRedo"), &EditorPlugin::_get_undo_redo);
+ ClassDB::bind_method(D_METHOD("get_selection:EditorSelection"), &EditorPlugin::get_selection);
+ ClassDB::bind_method(D_METHOD("get_editor_settings:EditorSettings"), &EditorPlugin::get_editor_settings);
+ ClassDB::bind_method(D_METHOD("queue_save_layout"), &EditorPlugin::queue_save_layout);
+ ClassDB::bind_method(D_METHOD("edit_resource"), &EditorPlugin::edit_resource);
+
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "forward_canvas_gui_input", PropertyInfo(Variant::TRANSFORM2D, "canvas_xform"), PropertyInfo(Variant::INPUT_EVENT, "event")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("forward_draw_over_canvas", PropertyInfo(Variant::TRANSFORM2D, "canvas_xform"), PropertyInfo(Variant::OBJECT, "canvas:Control")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "forward_spatial_gui_input", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera"), PropertyInfo(Variant::INPUT_EVENT, "event")));
+ MethodInfo gizmo = MethodInfo(Variant::OBJECT, "create_spatial_gizmo", PropertyInfo(Variant::OBJECT, "for_spatial:Spatial"));
+ gizmo.return_val.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ gizmo.return_val.hint_string = "EditorSpatialGizmo";
+ ClassDB::add_virtual_method(get_class_static(), gizmo);
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::STRING, "get_name"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "has_main_screen"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("make_visible", PropertyInfo(Variant::BOOL, "visible")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("edit", PropertyInfo(Variant::OBJECT, "object")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles", PropertyInfo(Variant::OBJECT, "object")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::DICTIONARY, "get_state"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("set_state", PropertyInfo(Variant::DICTIONARY, "state")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("clear"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("save_external_data"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("apply_changes"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::POOL_STRING_ARRAY, "get_breakpoints"));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("set_window_layout", PropertyInfo(Variant::OBJECT, "layout", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo("get_window_layout", PropertyInfo(Variant::OBJECT, "layout", PROPERTY_HINT_RESOURCE_TYPE, "ConfigFile")));
+
+ BIND_CONSTANT(CONTAINER_TOOLBAR);
+ BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_MENU);
+ BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_SIDE);
+ BIND_CONSTANT(CONTAINER_SPATIAL_EDITOR_BOTTOM);
+ BIND_CONSTANT(CONTAINER_CANVAS_EDITOR_MENU);
+ BIND_CONSTANT(CONTAINER_CANVAS_EDITOR_SIDE);
+ BIND_CONSTANT(CONTAINER_PROPERTY_EDITOR_BOTTOM);
+
+ BIND_CONSTANT(DOCK_SLOT_LEFT_UL);
+ BIND_CONSTANT(DOCK_SLOT_LEFT_BL);
+ BIND_CONSTANT(DOCK_SLOT_LEFT_UR);
+ BIND_CONSTANT(DOCK_SLOT_LEFT_BR);
+ BIND_CONSTANT(DOCK_SLOT_RIGHT_UL);
+ BIND_CONSTANT(DOCK_SLOT_RIGHT_BL);
+ BIND_CONSTANT(DOCK_SLOT_RIGHT_UR);
+ BIND_CONSTANT(DOCK_SLOT_RIGHT_BR);
+ BIND_CONSTANT(DOCK_SLOT_MAX);
+}
+
+EditorPlugin::EditorPlugin() {
+ undo_redo = NULL;
+}
+
+EditorPlugin::~EditorPlugin() {
}
-
-
EditorPluginCreateFunc EditorPlugins::creation_funcs[MAX_CREATE_FUNCS];
-int EditorPlugins::creation_func_count=0;
+int EditorPlugins::creation_func_count = 0;
diff --git a/editor/editor_plugin.h b/editor/editor_plugin.h
index 13d8ab0343..611ef72945 100644
--- a/editor/editor_plugin.h
+++ b/editor/editor_plugin.h
@@ -29,11 +29,11 @@
#ifndef EDITOR_PLUGIN_H
#define EDITOR_PLUGIN_H
+#include "io/config_file.h"
#include "scene/gui/tool_button.h"
#include "scene/main/node.h"
#include "scene/resources/texture.h"
#include "undo_redo.h"
-#include "io/config_file.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -53,23 +53,20 @@ class EditorFileSystem;
class EditorPlugin : public Node {
- GDCLASS( EditorPlugin, Node );
-friend class EditorData;
+ GDCLASS(EditorPlugin, Node);
+ friend class EditorData;
UndoRedo *undo_redo;
- UndoRedo* _get_undo_redo() { return undo_redo; }
+ UndoRedo *_get_undo_redo() { return undo_redo; }
protected:
-
static void _bind_methods();
- UndoRedo& get_undo_redo() { return *undo_redo; }
-
- void add_custom_type(const String& p_type, const String& p_base,const Ref<Script>& p_script, const Ref<Texture>& p_icon);
- void remove_custom_type(const String& p_type);
+ UndoRedo &get_undo_redo() { return *undo_redo; }
+ void add_custom_type(const String &p_type, const String &p_base, const Ref<Script> &p_script, const Ref<Texture> &p_icon);
+ void remove_custom_type(const String &p_type);
public:
-
enum CustomControlContainer {
CONTAINER_TOOLBAR,
CONTAINER_SPATIAL_EDITOR_MENU,
@@ -97,40 +94,40 @@ public:
void add_control_to_container(CustomControlContainer p_location, Control *p_control);
ToolButton *add_control_to_bottom_panel(Control *p_control, const String &p_title);
- void add_control_to_dock(DockSlot p_slot,Control *p_control);
+ void add_control_to_dock(DockSlot p_slot, Control *p_control);
void remove_control_from_docks(Control *p_control);
void remove_control_from_bottom_panel(Control *p_control);
- Control* get_editor_viewport();
- void edit_resource(const Ref<Resource>& p_resource);
+ Control *get_editor_viewport();
+ void edit_resource(const Ref<Resource> &p_resource);
- void add_tool_menu_item(const String& p_name, Object *p_handler, const String& p_callback, const Variant& p_ud = Variant());
- void add_tool_submenu_item(const String& p_name, Object *p_submenu);
- void remove_tool_menu_item(const String& p_name);
+ void add_tool_menu_item(const String &p_name, Object *p_handler, const String &p_callback, const Variant &p_ud = Variant());
+ void add_tool_submenu_item(const String &p_name, Object *p_submenu);
+ void remove_tool_menu_item(const String &p_name);
- virtual Ref<SpatialEditorGizmo> create_spatial_gizmo(Spatial* p_spatial);
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform, const InputEvent& p_event);
- virtual void forward_draw_over_canvas(const Transform2D& p_canvas_xform,Control *p_canvas);
- virtual bool forward_spatial_gui_input(Camera* p_camera,const InputEvent& p_event);
+ virtual Ref<SpatialEditorGizmo> create_spatial_gizmo(Spatial *p_spatial);
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event);
+ virtual void forward_draw_over_canvas(const Transform2D &p_canvas_xform, Control *p_canvas);
+ virtual bool forward_spatial_gui_input(Camera *p_camera, const InputEvent &p_event);
virtual String get_name() const;
virtual bool has_main_screen() const;
virtual void make_visible(bool p_visible);
- virtual void selected_notify() {}//notify that it was raised by the user, not the editor
+ virtual void selected_notify() {} //notify that it was raised by the user, not the editor
virtual void edit(Object *p_object);
virtual bool handles(Object *p_node) const;
virtual Dictionary get_state() const; //save editor state so it can't be reloaded when reloading scene
- virtual void set_state(const Dictionary& p_state) ; //restore editor state (likely was saved with the scene)
- virtual void clear() ; // clear any temporary data in te editor, reset it (likely new scene or load another scene)
- virtual void save_external_data() ; // if editor references external resources/scenes, save them
- virtual void apply_changes() ; // if changes are pending in editor, apply them
+ virtual void set_state(const Dictionary &p_state); //restore editor state (likely was saved with the scene)
+ virtual void clear(); // clear any temporary data in te editor, reset it (likely new scene or load another scene)
+ virtual void save_external_data(); // if editor references external resources/scenes, save them
+ virtual void apply_changes(); // if changes are pending in editor, apply them
virtual void get_breakpoints(List<String> *p_breakpoints);
- virtual bool get_remove_list(List<Node*> *p_list);
+ virtual bool get_remove_list(List<Node *> *p_list);
virtual void set_window_layout(Ref<ConfigFile> p_layout);
virtual void get_window_layout(Ref<ConfigFile> p_layout);
- virtual void edited_scene_changed(){} // if changes are pending in editor, apply them
+ virtual void edited_scene_changed() {} // if changes are pending in editor, apply them
void update_canvas();
- virtual void inspect_object(Object *p_obj,const String& p_for_property=String());
+ virtual void inspect_object(Object *p_obj, const String &p_for_property = String());
void queue_save_layout() const;
@@ -139,7 +136,7 @@ public:
void make_bottom_panel_item_visible(Control *p_item);
void hide_bottom_panel();
- EditorSelection* get_selection();
+ EditorSelection *get_selection();
//EditorImportExport *get_import_export();
EditorSettings *get_editor_settings();
EditorResourcePreview *get_resource_previewer();
@@ -150,52 +147,44 @@ public:
EditorPlugin();
virtual ~EditorPlugin();
-
};
-VARIANT_ENUM_CAST( EditorPlugin::CustomControlContainer );
-VARIANT_ENUM_CAST( EditorPlugin::DockSlot );
-
+VARIANT_ENUM_CAST(EditorPlugin::CustomControlContainer);
+VARIANT_ENUM_CAST(EditorPlugin::DockSlot);
-typedef EditorPlugin* (*EditorPluginCreateFunc)(EditorNode *);
+typedef EditorPlugin *(*EditorPluginCreateFunc)(EditorNode *);
class EditorPlugins {
enum {
- MAX_CREATE_FUNCS=64
+ MAX_CREATE_FUNCS = 64
};
static EditorPluginCreateFunc creation_funcs[MAX_CREATE_FUNCS];
static int creation_func_count;
- template<class T>
+ template <class T>
static EditorPlugin *creator(EditorNode *p_node) {
- return memnew( T(p_node) );
+ return memnew(T(p_node));
}
public:
-
static int get_plugin_count() { return creation_func_count; }
- static EditorPlugin* create(int p_idx,EditorNode* p_editor) { ERR_FAIL_INDEX_V(p_idx,creation_func_count,NULL); return creation_funcs[p_idx](p_editor); }
+ static EditorPlugin *create(int p_idx, EditorNode *p_editor) {
+ ERR_FAIL_INDEX_V(p_idx, creation_func_count, NULL);
+ return creation_funcs[p_idx](p_editor);
+ }
- template<class T>
+ template <class T>
static void add_by_type() {
add_create_func(creator<T>);
}
static void add_create_func(EditorPluginCreateFunc p_func) {
- ERR_FAIL_COND(creation_func_count>=MAX_CREATE_FUNCS);
- creation_funcs[creation_func_count++]=p_func;
+ ERR_FAIL_COND(creation_func_count >= MAX_CREATE_FUNCS);
+ creation_funcs[creation_func_count++] = p_func;
}
-
};
-
-
-
-
-
-
-
#endif
diff --git a/editor/editor_plugin_settings.cpp b/editor/editor_plugin_settings.cpp
index 2d879e38cf..3e7b225a8d 100644
--- a/editor/editor_plugin_settings.cpp
+++ b/editor/editor_plugin_settings.cpp
@@ -28,33 +28,32 @@
/*************************************************************************/
#include "editor_plugin_settings.h"
-#include "scene/gui/margin_container.h"
+#include "editor_node.h"
+#include "global_config.h"
#include "io/config_file.h"
#include "os/file_access.h"
#include "os/main_loop.h"
-#include "global_config.h"
-#include "editor_node.h"
+#include "scene/gui/margin_container.h"
void EditorPluginSettings::_notification(int p_what) {
- if (p_what==MainLoop::NOTIFICATION_WM_FOCUS_IN) {
+ if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {
update_plugins();
}
}
void EditorPluginSettings::update_plugins() {
-
plugin_list->clear();
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
Error err = da->change_dir("res://addons");
- if (err!=OK) {
+ if (err != OK) {
memdelete(da);
return;
}
- updating=true;
+ updating = true;
TreeItem *root = plugin_list->create_item();
@@ -64,10 +63,10 @@ void EditorPluginSettings::update_plugins() {
Vector<String> plugins;
- while(d!=String()) {
+ while (d != String()) {
bool dir = da->current_is_dir();
- String path = "res://addons/"+d+"/plugin.cfg";
+ String path = "res://addons/" + d + "/plugin.cfg";
if (dir && FileAccess::exists(path)) {
@@ -84,133 +83,126 @@ void EditorPluginSettings::update_plugins() {
Vector<String> active_plugins = GlobalConfig::get_singleton()->get("plugins/active");
- for(int i=0;i<plugins.size();i++) {
+ for (int i = 0; i < plugins.size(); i++) {
Ref<ConfigFile> cf;
cf.instance();
- String path = "res://addons/"+plugins[i]+"/plugin.cfg";
+ String path = "res://addons/" + plugins[i] + "/plugin.cfg";
Error err = cf->load(path);
- if (err!=OK) {
- WARN_PRINTS("Can't load plugin config: "+path);
- } else if (!cf->has_section_key("plugin","name")) {
- WARN_PRINTS("Plugin misses plugin/name: "+path);
- } else if (!cf->has_section_key("plugin","author")) {
- WARN_PRINTS("Plugin misses plugin/author: "+path);
- } else if (!cf->has_section_key("plugin","version")) {
- WARN_PRINTS("Plugin misses plugin/version: "+path);
- } else if (!cf->has_section_key("plugin","description")) {
- WARN_PRINTS("Plugin misses plugin/description: "+path);
- } else if (!cf->has_section_key("plugin","script")) {
- WARN_PRINTS("Plugin misses plugin/script: "+path);
+ if (err != OK) {
+ WARN_PRINTS("Can't load plugin config: " + path);
+ } else if (!cf->has_section_key("plugin", "name")) {
+ WARN_PRINTS("Plugin misses plugin/name: " + path);
+ } else if (!cf->has_section_key("plugin", "author")) {
+ WARN_PRINTS("Plugin misses plugin/author: " + path);
+ } else if (!cf->has_section_key("plugin", "version")) {
+ WARN_PRINTS("Plugin misses plugin/version: " + path);
+ } else if (!cf->has_section_key("plugin", "description")) {
+ WARN_PRINTS("Plugin misses plugin/description: " + path);
+ } else if (!cf->has_section_key("plugin", "script")) {
+ WARN_PRINTS("Plugin misses plugin/script: " + path);
} else {
String d = plugins[i];
- String name = cf->get_value("plugin","name");
- String author = cf->get_value("plugin","author");
- String version = cf->get_value("plugin","version");
- String description = cf->get_value("plugin","description");
- String script = cf->get_value("plugin","script");
+ String name = cf->get_value("plugin", "name");
+ String author = cf->get_value("plugin", "author");
+ String version = cf->get_value("plugin", "version");
+ String description = cf->get_value("plugin", "description");
+ String script = cf->get_value("plugin", "script");
TreeItem *item = plugin_list->create_item(root);
- item->set_text(0,name);
- item->set_tooltip(0,"Name: "+name+"\nPath: "+path+"\nMain Script: "+script);
- item->set_metadata(0,d);
- item->set_text(1,version);
- item->set_metadata(1,script);
- item->set_text(2,author);
- item->set_metadata(2,description);
- item->set_cell_mode(3,TreeItem::CELL_MODE_RANGE);
- item->set_range_config(3,0,1,1);
- item->set_text(3,"Inactive,Active");
- item->set_editable(3,true);
+ item->set_text(0, name);
+ item->set_tooltip(0, "Name: " + name + "\nPath: " + path + "\nMain Script: " + script);
+ item->set_metadata(0, d);
+ item->set_text(1, version);
+ item->set_metadata(1, script);
+ item->set_text(2, author);
+ item->set_metadata(2, description);
+ item->set_cell_mode(3, TreeItem::CELL_MODE_RANGE);
+ item->set_range_config(3, 0, 1, 1);
+ item->set_text(3, "Inactive,Active");
+ item->set_editable(3, true);
if (EditorNode::get_singleton()->is_addon_plugin_enabled(d)) {
- item->set_custom_color(3,Color(0.2,1,0.2));
- item->set_range(3,1);
+ item->set_custom_color(3, Color(0.2, 1, 0.2));
+ item->set_range(3, 1);
} else {
- item->set_custom_color(3,Color(1,0.2,0.2));
- item->set_range(3,0);
+ item->set_custom_color(3, Color(1, 0.2, 0.2));
+ item->set_range(3, 0);
}
}
-
}
- updating=false;
-
+ updating = false;
}
-
void EditorPluginSettings::_plugin_activity_changed() {
if (updating)
return;
- TreeItem *ti=plugin_list->get_edited();
+ TreeItem *ti = plugin_list->get_edited();
ERR_FAIL_COND(!ti);
bool active = ti->get_range(3);
String name = ti->get_metadata(0);
- EditorNode::get_singleton()->set_addon_plugin_enabled(name,active);
+ EditorNode::get_singleton()->set_addon_plugin_enabled(name, active);
bool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);
- if (is_active!=active) {
- updating=true;
- ti->set_range(3,is_active?1:0);
- updating=false;
+ if (is_active != active) {
+ updating = true;
+ ti->set_range(3, is_active ? 1 : 0);
+ updating = false;
}
if (is_active)
- ti->set_custom_color(3,Color(0.2,1,0.2));
+ ti->set_custom_color(3, Color(0.2, 1, 0.2));
else
- ti->set_custom_color(3,Color(1,0.2,0.2));
-
-
+ ti->set_custom_color(3, Color(1, 0.2, 0.2));
}
void EditorPluginSettings::_bind_methods() {
- ClassDB::bind_method("update_plugins",&EditorPluginSettings::update_plugins);
- ClassDB::bind_method("_plugin_activity_changed",&EditorPluginSettings::_plugin_activity_changed);
+ ClassDB::bind_method("update_plugins", &EditorPluginSettings::update_plugins);
+ ClassDB::bind_method("_plugin_activity_changed", &EditorPluginSettings::_plugin_activity_changed);
}
EditorPluginSettings::EditorPluginSettings() {
- HBoxContainer *title_hb = memnew( HBoxContainer );
- title_hb->add_child(memnew( Label(TTR("Installed Plugins:"))));
+ HBoxContainer *title_hb = memnew(HBoxContainer);
+ title_hb->add_child(memnew(Label(TTR("Installed Plugins:"))));
title_hb->add_spacer();
- update_list = memnew( Button(TTR("Update")) );
- update_list->connect("pressed",this,"update_plugins");
+ update_list = memnew(Button(TTR("Update")));
+ update_list->connect("pressed", this, "update_plugins");
title_hb->add_child(update_list);
add_child(title_hb);
- plugin_list = memnew( Tree );
+ plugin_list = memnew(Tree);
plugin_list->set_v_size_flags(SIZE_EXPAND_FILL);
plugin_list->set_columns(4);
plugin_list->set_column_titles_visible(true);
- plugin_list->set_column_title(0,TTR("Name:"));
- plugin_list->set_column_title(1,TTR("Version:"));
- plugin_list->set_column_title(2,TTR("Author:"));
- plugin_list->set_column_title(3,TTR("Status:"));
- plugin_list->set_column_expand(0,true);
- plugin_list->set_column_expand(1,false);
- plugin_list->set_column_expand(2,false);
- plugin_list->set_column_expand(3,false);
- plugin_list->set_column_min_width(1,100);
- plugin_list->set_column_min_width(2,250);
- plugin_list->set_column_min_width(3,80);
+ plugin_list->set_column_title(0, TTR("Name:"));
+ plugin_list->set_column_title(1, TTR("Version:"));
+ plugin_list->set_column_title(2, TTR("Author:"));
+ plugin_list->set_column_title(3, TTR("Status:"));
+ plugin_list->set_column_expand(0, true);
+ plugin_list->set_column_expand(1, false);
+ plugin_list->set_column_expand(2, false);
+ plugin_list->set_column_expand(3, false);
+ plugin_list->set_column_min_width(1, 100);
+ plugin_list->set_column_min_width(2, 250);
+ plugin_list->set_column_min_width(3, 80);
plugin_list->set_hide_root(true);
- plugin_list->connect("item_edited",this,"_plugin_activity_changed");
-
+ plugin_list->connect("item_edited", this, "_plugin_activity_changed");
- MarginContainer *mc = memnew( MarginContainer );
+ MarginContainer *mc = memnew(MarginContainer);
mc->add_child(plugin_list);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
add_child(mc);
- updating=false;
-
+ updating = false;
}
diff --git a/editor/editor_plugin_settings.h b/editor/editor_plugin_settings.h
index e24880a21d..faad933130 100644
--- a/editor/editor_plugin_settings.h
+++ b/editor/editor_plugin_settings.h
@@ -29,31 +29,27 @@
#ifndef EDITORPLUGINSETTINGS_H
#define EDITORPLUGINSETTINGS_H
-
-#include "scene/gui/dialogs.h"
+#include "editor_data.h"
#include "property_editor.h"
+#include "scene/gui/dialogs.h"
#include "undo_redo.h"
-#include "editor_data.h"
class EditorPluginSettings : public VBoxContainer {
- GDCLASS(EditorPluginSettings,VBoxContainer);
+ GDCLASS(EditorPluginSettings, VBoxContainer);
- Button* update_list;
+ Button *update_list;
Tree *plugin_list;
bool updating;
-
void _plugin_activity_changed();
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-
public:
-
void update_plugins();
EditorPluginSettings();
diff --git a/editor/editor_profiler.cpp b/editor/editor_profiler.cpp
index d9a4174246..1199779cb8 100644
--- a/editor/editor_profiler.cpp
+++ b/editor/editor_profiler.cpp
@@ -31,46 +31,43 @@
#include "editor_settings.h"
#include "os/os.h"
-void EditorProfiler::_make_metric_ptrs(Metric& m) {
+void EditorProfiler::_make_metric_ptrs(Metric &m) {
- for(int i=0;i<m.categories.size();i++) {
- m.category_ptrs[m.categories[i].signature]=&m.categories[i];
- for(int j=0;j<m.categories[i].items.size();j++) {
- m.item_ptrs[m.categories[i].items[j].signature]=&m.categories[i].items[j];
+ for (int i = 0; i < m.categories.size(); i++) {
+ m.category_ptrs[m.categories[i].signature] = &m.categories[i];
+ for (int j = 0; j < m.categories[i].items.size(); j++) {
+ m.item_ptrs[m.categories[i].items[j].signature] = &m.categories[i].items[j];
}
}
}
-void EditorProfiler::add_frame_metric(const Metric& p_metric,bool p_final) {
+void EditorProfiler::add_frame_metric(const Metric &p_metric, bool p_final) {
++last_metric;
- if (last_metric>=frame_metrics.size())
- last_metric=0;
+ if (last_metric >= frame_metrics.size())
+ last_metric = 0;
-
- frame_metrics[last_metric]=p_metric;
+ frame_metrics[last_metric] = p_metric;
_make_metric_ptrs(frame_metrics[last_metric]);
- updating_frame=true;
+ updating_frame = true;
cursor_metric_edit->set_max(frame_metrics[last_metric].frame_number);
- cursor_metric_edit->set_min(MAX(frame_metrics[last_metric].frame_number-frame_metrics.size(),0));
-
+ cursor_metric_edit->set_min(MAX(frame_metrics[last_metric].frame_number - frame_metrics.size(), 0));
if (!seeking) {
cursor_metric_edit->set_value(frame_metrics[last_metric].frame_number);
- if (hover_metric!=-1) {
+ if (hover_metric != -1) {
hover_metric++;
- if (hover_metric>=frame_metrics.size()) {
- hover_metric=0;
+ if (hover_metric >= frame_metrics.size()) {
+ hover_metric = 0;
}
}
-
}
- updating_frame=false;
+ updating_frame = false;
if (!frame_delay->is_processing()) {
- frame_delay->set_wait_time(p_final?0.1:1);
+ frame_delay->set_wait_time(p_final ? 0.1 : 1);
frame_delay->start();
}
@@ -78,69 +75,63 @@ void EditorProfiler::add_frame_metric(const Metric& p_metric,bool p_final) {
plot_delay->set_wait_time(0.1);
plot_delay->start();
}
-
}
-
-
void EditorProfiler::clear() {
- int metric_size=EditorSettings::get_singleton()->get("debugger/profiler_frame_history_size");
- metric_size = CLAMP(metric_size,60,1024);
+ int metric_size = EditorSettings::get_singleton()->get("debugger/profiler_frame_history_size");
+ metric_size = CLAMP(metric_size, 60, 1024);
frame_metrics.clear();
frame_metrics.resize(metric_size);
- last_metric=-1;
+ last_metric = -1;
variables->clear();
//activate->set_pressed(false);
plot_sigs.clear();
plot_sigs.insert("fixed_frame_time");
plot_sigs.insert("category_frame_time");
- updating_frame=true;
+ updating_frame = true;
cursor_metric_edit->set_min(0);
cursor_metric_edit->set_max(0);
cursor_metric_edit->set_value(0);
- updating_frame=false;
- hover_metric=-1;
- seeking=false;
+ updating_frame = false;
+ hover_metric = -1;
+ seeking = false;
}
-static String _get_percent_txt(float p_value,float p_total) {
- if (p_total==0)
- p_total=0.00001;
- return String::num((p_value/p_total)*100,1)+"%";
+static String _get_percent_txt(float p_value, float p_total) {
+ if (p_total == 0)
+ p_total = 0.00001;
+ return String::num((p_value / p_total) * 100, 1) + "%";
}
-
-String EditorProfiler::_get_time_as_text(Metric &m,float p_time,int p_calls) {
+String EditorProfiler::_get_time_as_text(Metric &m, float p_time, int p_calls) {
int dmode = display_mode->get_selected();
-
- if (dmode==DISPLAY_FRAME_TIME) {
+ if (dmode == DISPLAY_FRAME_TIME) {
return rtos(p_time);
- } else if (dmode==DISPLAY_AVERAGE_TIME) {
- if (p_calls==0)
+ } else if (dmode == DISPLAY_AVERAGE_TIME) {
+ if (p_calls == 0)
return "0";
else
- return rtos(p_time/p_calls);
- } else if (dmode==DISPLAY_FRAME_PERCENT) {
- return _get_percent_txt(p_time,m.frame_time);
- } else if (dmode==DISPLAY_FIXED_FRAME_PERCENT) {
+ return rtos(p_time / p_calls);
+ } else if (dmode == DISPLAY_FRAME_PERCENT) {
+ return _get_percent_txt(p_time, m.frame_time);
+ } else if (dmode == DISPLAY_FIXED_FRAME_PERCENT) {
- return _get_percent_txt(p_time,m.fixed_frame_time);
+ return _get_percent_txt(p_time, m.fixed_frame_time);
}
return "err";
}
-Color EditorProfiler::_get_color_from_signature(const StringName& p_signature) const {
+Color EditorProfiler::_get_color_from_signature(const StringName &p_signature) const {
- double rot = ABS(double(p_signature.hash())/double(0x7FFFFFFF));
+ double rot = ABS(double(p_signature.hash()) / double(0x7FFFFFFF));
Color c;
- c.set_hsv(rot,1,1);
+ c.set_hsv(rot, 1, 1);
return c;
-
}
void EditorProfiler::_item_edited() {
@@ -148,12 +139,11 @@ void EditorProfiler::_item_edited() {
if (updating_frame)
return;
- TreeItem *item=variables->get_edited();
+ TreeItem *item = variables->get_edited();
if (!item)
return;
- StringName signature=item->get_metadata(0);
- bool checked=item->is_checked(0);
-
+ StringName signature = item->get_metadata(0);
+ bool checked = item->is_checked(0);
if (checked)
plot_sigs.insert(signature);
@@ -173,424 +163,381 @@ void EditorProfiler::_update_plot() {
int w = graph->get_size().width;
int h = graph->get_size().height;
- bool reset_texture=false;
+ bool reset_texture = false;
int desired_len = w * h * 4;
- if (graph_image.size()!=desired_len) {
- reset_texture=true;
+ if (graph_image.size() != desired_len) {
+ reset_texture = true;
graph_image.resize(desired_len);
}
-
PoolVector<uint8_t>::Write wr = graph_image.write();
-
-
//clear
- for(int i=0;i<desired_len;i+=4) {
- wr[i+0]=0;
- wr[i+1]=0;
- wr[i+2]=0;
- wr[i+3]=255;
+ for (int i = 0; i < desired_len; i += 4) {
+ wr[i + 0] = 0;
+ wr[i + 1] = 0;
+ wr[i + 2] = 0;
+ wr[i + 3] = 255;
}
-
//find highest value
- bool use_self = display_time->get_selected()==DISPLAY_SELF_TIME;
- float highest=0;
+ bool use_self = display_time->get_selected() == DISPLAY_SELF_TIME;
+ float highest = 0;
- for(int i=0;i<frame_metrics.size();i++) {
+ for (int i = 0; i < frame_metrics.size(); i++) {
Metric &m = frame_metrics[i];
if (!m.valid)
continue;
- for (Set<StringName>::Element *E=plot_sigs.front();E;E=E->next()) {
+ for (Set<StringName>::Element *E = plot_sigs.front(); E; E = E->next()) {
- Map<StringName,Metric::Category*>::Element *F=m.category_ptrs.find(E->get());
+ Map<StringName, Metric::Category *>::Element *F = m.category_ptrs.find(E->get());
if (F) {
- highest=MAX(F->get()->total_time,highest);
+ highest = MAX(F->get()->total_time, highest);
}
- Map<StringName,Metric::Category::Item*>::Element *G=m.item_ptrs.find(E->get());
+ Map<StringName, Metric::Category::Item *>::Element *G = m.item_ptrs.find(E->get());
if (G) {
if (use_self) {
- highest=MAX(G->get()->self,highest);
+ highest = MAX(G->get()->self, highest);
} else {
- highest=MAX(G->get()->total,highest);
+ highest = MAX(G->get()->total, highest);
}
}
}
}
- if (highest>0) {
+ if (highest > 0) {
//means some data exists..
- highest*=1.2; //leave some upper room
- graph_height=highest;
+ highest *= 1.2; //leave some upper room
+ graph_height = highest;
Vector<int> columnv;
- columnv.resize(h*4);
+ columnv.resize(h * 4);
int *column = columnv.ptr();
- Map<StringName,int> plot_prev;
+ Map<StringName, int> plot_prev;
//Map<StringName,int> plot_max;
uint64_t time = OS::get_singleton()->get_ticks_usec();
- for(int i=0;i<w;i++) {
+ for (int i = 0; i < w; i++) {
-
- for(int j=0;j<h*4;j++) {
- column[j]=0;
+ for (int j = 0; j < h * 4; j++) {
+ column[j] = 0;
}
- int current = i*frame_metrics.size()/w;
- int next = (i+1)*frame_metrics.size()/w;
- if (next>frame_metrics.size()) {
- next=frame_metrics.size();
+ int current = i * frame_metrics.size() / w;
+ int next = (i + 1) * frame_metrics.size() / w;
+ if (next > frame_metrics.size()) {
+ next = frame_metrics.size();
}
- if (next==current)
- next=current+1; //just because for loop must work
+ if (next == current)
+ next = current + 1; //just because for loop must work
- for (Set<StringName>::Element *E=plot_sigs.front();E;E=E->next()) {
+ for (Set<StringName>::Element *E = plot_sigs.front(); E; E = E->next()) {
- int plot_pos=-1;
+ int plot_pos = -1;
- for(int j=current;j<next;j++) {
+ for (int j = current; j < next; j++) {
//wrap
- int idx = last_metric+1+j;
- while( idx >= frame_metrics.size() ) {
- idx-=frame_metrics.size();
+ int idx = last_metric + 1 + j;
+ while (idx >= frame_metrics.size()) {
+ idx -= frame_metrics.size();
}
//get
Metric &m = frame_metrics[idx];
- if (m.valid==false)
+ if (m.valid == false)
continue; //skip because invalid
+ float value = 0;
- float value=0;
-
- Map<StringName,Metric::Category*>::Element *F=m.category_ptrs.find(E->get());
+ Map<StringName, Metric::Category *>::Element *F = m.category_ptrs.find(E->get());
if (F) {
- value=F->get()->total_time;
+ value = F->get()->total_time;
}
- Map<StringName,Metric::Category::Item*>::Element *G=m.item_ptrs.find(E->get());
+ Map<StringName, Metric::Category::Item *>::Element *G = m.item_ptrs.find(E->get());
if (G) {
if (use_self) {
- value=G->get()->self;
+ value = G->get()->self;
} else {
- value=G->get()->total;
+ value = G->get()->total;
}
}
-
- plot_pos = MAX( CLAMP(int(value*h/highest),0,h-1), plot_pos );
-
-
+ plot_pos = MAX(CLAMP(int(value * h / highest), 0, h - 1), plot_pos);
}
- int prev_plot=plot_pos;
- Map<StringName,int>::Element *H=plot_prev.find(E->get());
+ int prev_plot = plot_pos;
+ Map<StringName, int>::Element *H = plot_prev.find(E->get());
if (H) {
- prev_plot=H->get();
- H->get()=plot_pos;
+ prev_plot = H->get();
+ H->get() = plot_pos;
} else {
- plot_prev[E->get()]=plot_pos;
+ plot_prev[E->get()] = plot_pos;
}
- if (plot_pos==-1 && prev_plot==-1) {
+ if (plot_pos == -1 && prev_plot == -1) {
//don't bother drawing
continue;
}
- if (prev_plot!=-1 && plot_pos==-1) {
+ if (prev_plot != -1 && plot_pos == -1) {
- plot_pos=prev_plot;
+ plot_pos = prev_plot;
}
- if (prev_plot==-1 && plot_pos!=-1) {
- prev_plot=plot_pos;
+ if (prev_plot == -1 && plot_pos != -1) {
+ prev_plot = plot_pos;
}
- plot_pos = h- plot_pos -1;
- prev_plot = h- prev_plot -1;
+ plot_pos = h - plot_pos - 1;
+ prev_plot = h - prev_plot - 1;
if (prev_plot > plot_pos) {
- SWAP(prev_plot,plot_pos);
+ SWAP(prev_plot, plot_pos);
}
Color col = _get_color_from_signature(E->get());
- for(int j=prev_plot;j<=plot_pos;j++) {
-
- column[j*4+0]+=Math::fast_ftoi(CLAMP(col.r*255,0,255));
- column[j*4+1]+=Math::fast_ftoi(CLAMP(col.g*255,0,255));
- column[j*4+2]+=Math::fast_ftoi(CLAMP(col.b*255,0,255));
- column[j*4+3]+=1;
+ for (int j = prev_plot; j <= plot_pos; j++) {
+ column[j * 4 + 0] += Math::fast_ftoi(CLAMP(col.r * 255, 0, 255));
+ column[j * 4 + 1] += Math::fast_ftoi(CLAMP(col.g * 255, 0, 255));
+ column[j * 4 + 2] += Math::fast_ftoi(CLAMP(col.b * 255, 0, 255));
+ column[j * 4 + 3] += 1;
}
}
+ for (int j = 0; j < h * 4; j += 4) {
- for(int j=0;j<h*4;j+=4) {
-
- int a = column[j+3];
- if (a>0) {
- column[j+0]/=a;
- column[j+1]/=a;
- column[j+2]/=a;
-
+ int a = column[j + 3];
+ if (a > 0) {
+ column[j + 0] /= a;
+ column[j + 1] /= a;
+ column[j + 2] /= a;
}
- uint8_t r = uint8_t(column[j+0]);
- uint8_t g = uint8_t(column[j+1]);
- uint8_t b = uint8_t(column[j+2]);
+ uint8_t r = uint8_t(column[j + 0]);
+ uint8_t g = uint8_t(column[j + 1]);
+ uint8_t b = uint8_t(column[j + 2]);
- int widx = ((j>>2)*w+i)*4;
- wr[widx+0]=r;
- wr[widx+1]=g;
- wr[widx+2]=b;
- wr[widx+3]=255;
+ int widx = ((j >> 2) * w + i) * 4;
+ wr[widx + 0] = r;
+ wr[widx + 1] = g;
+ wr[widx + 2] = b;
+ wr[widx + 3] = 255;
}
}
time = OS::get_singleton()->get_ticks_usec() - time;
//print_line("Taken: "+rtos(USEC_TO_SEC(time)));
-
}
-
wr = PoolVector<uint8_t>::Write();
- Image img(w,h,0,Image::FORMAT_RGBA8,graph_image);
+ Image img(w, h, 0, Image::FORMAT_RGBA8, graph_image);
if (reset_texture) {
if (graph_texture.is_null()) {
graph_texture.instance();
}
- graph_texture->create(img.get_width(),img.get_height(),img.get_format(),Texture::FLAG_VIDEO_SURFACE);
-
+ graph_texture->create(img.get_width(), img.get_height(), img.get_format(), Texture::FLAG_VIDEO_SURFACE);
}
graph_texture->set_data(img);
-
graph->set_texture(graph_texture);
graph->update();
-
}
void EditorProfiler::_update_frame() {
int cursor_metric = _get_cursor_index();
+ ERR_FAIL_INDEX(cursor_metric, frame_metrics.size());
- ERR_FAIL_INDEX(cursor_metric,frame_metrics.size());
-
- updating_frame=true;
+ updating_frame = true;
variables->clear();
- TreeItem* root = variables->create_item();
+ TreeItem *root = variables->create_item();
Metric &m = frame_metrics[cursor_metric];
-
int dtime = display_time->get_selected();
-
- for(int i=0;i<m.categories.size();i++) {
+ for (int i = 0; i < m.categories.size(); i++) {
TreeItem *category = variables->create_item(root);
- category->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- category->set_editable(0,true);
- category->set_metadata(0,m.categories[i].signature);
- category->set_text(0,String(m.categories[i].name));
- category->set_text(1,_get_time_as_text(m,m.categories[i].total_time,1));
+ category->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ category->set_editable(0, true);
+ category->set_metadata(0, m.categories[i].signature);
+ category->set_text(0, String(m.categories[i].name));
+ category->set_text(1, _get_time_as_text(m, m.categories[i].total_time, 1));
if (plot_sigs.has(m.categories[i].signature)) {
- category->set_checked(0,true);
- category->set_custom_bg_color(0,Color(0,0,0));
- category->set_custom_color(0,_get_color_from_signature(m.categories[i].signature));
+ category->set_checked(0, true);
+ category->set_custom_bg_color(0, Color(0, 0, 0));
+ category->set_custom_color(0, _get_color_from_signature(m.categories[i].signature));
}
-
- for(int j=0;j<m.categories[i].items.size();j++) {
+ for (int j = 0; j < m.categories[i].items.size(); j++) {
Metric::Category::Item &it = m.categories[i].items[j];
TreeItem *item = variables->create_item(category);
- item->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- item->set_editable(0,true);
- item->set_text(0,it.name);
- item->set_metadata(0,it.signature);
- item->set_metadata(1,it.script);
- item->set_metadata(2,it.line);
- item->set_tooltip(0,it.script+":"+itos(it.line));
+ item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ item->set_editable(0, true);
+ item->set_text(0, it.name);
+ item->set_metadata(0, it.signature);
+ item->set_metadata(1, it.script);
+ item->set_metadata(2, it.line);
+ item->set_tooltip(0, it.script + ":" + itos(it.line));
float time = dtime == DISPLAY_SELF_TIME ? it.self : it.total;
- item->set_text(1,_get_time_as_text(m,time,it.calls));
+ item->set_text(1, _get_time_as_text(m, time, it.calls));
- item->set_text(2,itos(it.calls));
+ item->set_text(2, itos(it.calls));
if (plot_sigs.has(it.signature)) {
- item->set_checked(0,true);
- item->set_custom_bg_color(0,Color(0,0,0));
- item->set_custom_color(0,_get_color_from_signature(it.signature));
+ item->set_checked(0, true);
+ item->set_custom_bg_color(0, Color(0, 0, 0));
+ item->set_custom_color(0, _get_color_from_signature(it.signature));
}
-
}
}
- updating_frame=false;
-
+ updating_frame = false;
}
-
void EditorProfiler::_activate_pressed() {
if (activate->is_pressed()) {
clear();
- activate->set_icon(get_icon("Stop","EditorIcons"));
+ activate->set_icon(get_icon("Stop", "EditorIcons"));
activate->set_text(TTR("Stop Profiling"));
} else {
- activate->set_icon(get_icon("Play","EditorIcons"));
+ activate->set_icon(get_icon("Play", "EditorIcons"));
activate->set_text(TTR("Start Profiling"));
-
-
}
- emit_signal("enable_profiling",activate->is_pressed());
-
+ emit_signal("enable_profiling", activate->is_pressed());
}
-
void EditorProfiler::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- activate->set_icon(get_icon("Play","EditorIcons"));
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ activate->set_icon(get_icon("Play", "EditorIcons"));
}
}
void EditorProfiler::_graph_tex_draw() {
- if (last_metric<0)
+ if (last_metric < 0)
return;
if (seeking) {
int max_frames = frame_metrics.size();
- int frame = cursor_metric_edit->get_value() - (frame_metrics[last_metric].frame_number-max_frames+1);
- if (frame<0)
- frame=0;
+ int frame = cursor_metric_edit->get_value() - (frame_metrics[last_metric].frame_number - max_frames + 1);
+ if (frame < 0)
+ frame = 0;
int cur_x = frame * graph->get_size().x / max_frames;
-
- graph->draw_line(Vector2(cur_x,0),Vector2(cur_x,graph->get_size().y),Color(1,1,1,0.8));
+ graph->draw_line(Vector2(cur_x, 0), Vector2(cur_x, graph->get_size().y), Color(1, 1, 1, 0.8));
}
-
- if (hover_metric!=-1 && frame_metrics[hover_metric].valid) {
-
-
+ if (hover_metric != -1 && frame_metrics[hover_metric].valid) {
int max_frames = frame_metrics.size();
- int frame = frame_metrics[hover_metric].frame_number - (frame_metrics[last_metric].frame_number-max_frames+1);
- if (frame<0)
- frame=0;
+ int frame = frame_metrics[hover_metric].frame_number - (frame_metrics[last_metric].frame_number - max_frames + 1);
+ if (frame < 0)
+ frame = 0;
int cur_x = frame * graph->get_size().x / max_frames;
- graph->draw_line(Vector2(cur_x,0),Vector2(cur_x,graph->get_size().y),Color(1,1,1,0.4));
-
-
+ graph->draw_line(Vector2(cur_x, 0), Vector2(cur_x, graph->get_size().y), Color(1, 1, 1, 0.4));
}
-
}
void EditorProfiler::_graph_tex_mouse_exit() {
- hover_metric=-1;
+ hover_metric = -1;
graph->update();
}
-
void EditorProfiler::_cursor_metric_changed(double) {
if (updating_frame)
return;
-
graph->update();
_update_frame();
-
}
-void EditorProfiler::_graph_tex_input(const InputEvent& p_ev){
+void EditorProfiler::_graph_tex_input(const InputEvent &p_ev) {
- if (last_metric<0)
+ if (last_metric < 0)
return;
if (
- (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index==BUTTON_LEFT && p_ev.mouse_button.pressed) ||
- (p_ev.type==InputEvent::MOUSE_MOTION) ) {
+ (p_ev.type == InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index == BUTTON_LEFT && p_ev.mouse_button.pressed) ||
+ (p_ev.type == InputEvent::MOUSE_MOTION)) {
int x = p_ev.mouse_button.x;
- x=x*frame_metrics.size()/graph->get_size().width;
+ x = x * frame_metrics.size() / graph->get_size().width;
- bool show_hover = x>=0 && x<frame_metrics.size();
+ bool show_hover = x >= 0 && x < frame_metrics.size();
- if (x<0) {
- x=0;
+ if (x < 0) {
+ x = 0;
}
- if (x>=frame_metrics.size()) {
- x=frame_metrics.size()-1;
+ if (x >= frame_metrics.size()) {
+ x = frame_metrics.size() - 1;
}
-
-
- int metric=frame_metrics.size()-x-1;
- metric = last_metric-metric;
- while(metric<0) {
- metric+=frame_metrics.size();
+ int metric = frame_metrics.size() - x - 1;
+ metric = last_metric - metric;
+ while (metric < 0) {
+ metric += frame_metrics.size();
}
-
-
if (show_hover) {
- hover_metric=metric;
+ hover_metric = metric;
} else {
- hover_metric=-1;
+ hover_metric = -1;
}
-
- if (p_ev.type==InputEvent::MOUSE_BUTTON || p_ev.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON || p_ev.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
//cursor_metric=x;
- updating_frame=true;
+ updating_frame = true;
//metric may be invalid, so look for closest metric that is valid, this makes snap feel better
- bool valid=false;
- for(int i=0;i<frame_metrics.size();i++) {
+ bool valid = false;
+ for (int i = 0; i < frame_metrics.size(); i++) {
if (frame_metrics[metric].valid) {
- valid=true;
+ valid = true;
break;
}
metric++;
- if (metric>=frame_metrics.size())
- metric=0;
+ if (metric >= frame_metrics.size())
+ metric = 0;
}
if (valid)
cursor_metric_edit->set_value(frame_metrics[metric].frame_number);
- updating_frame=false;
+ updating_frame = false;
if (activate->is_pressed()) {
if (!seeking) {
@@ -598,7 +545,7 @@ void EditorProfiler::_graph_tex_input(const InputEvent& p_ev){
}
}
- seeking=true;
+ seeking = true;
if (!frame_delay->is_processing()) {
frame_delay->set_wait_time(0.1);
@@ -607,35 +554,30 @@ void EditorProfiler::_graph_tex_input(const InputEvent& p_ev){
}
graph->update();
-
}
-
}
int EditorProfiler::_get_cursor_index() const {
- if (last_metric<0)
+ if (last_metric < 0)
return 0;
if (!frame_metrics[last_metric].valid)
return 0;
- int diff = (frame_metrics[last_metric].frame_number-cursor_metric_edit->get_value());
+ int diff = (frame_metrics[last_metric].frame_number - cursor_metric_edit->get_value());
int idx = last_metric - diff;
- while (idx<0) {
- idx+=frame_metrics.size();
+ while (idx < 0) {
+ idx += frame_metrics.size();
}
-
return idx;
-
}
void EditorProfiler::disable_seeking() {
- seeking=false;
+ seeking = false;
graph->update();
-
}
void EditorProfiler::_combo_changed(int) {
@@ -646,19 +588,18 @@ void EditorProfiler::_combo_changed(int) {
void EditorProfiler::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_update_frame"),&EditorProfiler::_update_frame);
- ClassDB::bind_method(D_METHOD("_update_plot"),&EditorProfiler::_update_plot);
- ClassDB::bind_method(D_METHOD("_activate_pressed"),&EditorProfiler::_activate_pressed);
- ClassDB::bind_method(D_METHOD("_graph_tex_draw"),&EditorProfiler::_graph_tex_draw);
- ClassDB::bind_method(D_METHOD("_graph_tex_input"),&EditorProfiler::_graph_tex_input);
- ClassDB::bind_method(D_METHOD("_graph_tex_mouse_exit"),&EditorProfiler::_graph_tex_mouse_exit);
- ClassDB::bind_method(D_METHOD("_cursor_metric_changed"),&EditorProfiler::_cursor_metric_changed);
- ClassDB::bind_method(D_METHOD("_combo_changed"),&EditorProfiler::_combo_changed);
-
- ClassDB::bind_method(D_METHOD("_item_edited"),&EditorProfiler::_item_edited);
- ADD_SIGNAL( MethodInfo("enable_profiling",PropertyInfo(Variant::BOOL,"enable")));
- ADD_SIGNAL( MethodInfo("break_request"));
-
+ ClassDB::bind_method(D_METHOD("_update_frame"), &EditorProfiler::_update_frame);
+ ClassDB::bind_method(D_METHOD("_update_plot"), &EditorProfiler::_update_plot);
+ ClassDB::bind_method(D_METHOD("_activate_pressed"), &EditorProfiler::_activate_pressed);
+ ClassDB::bind_method(D_METHOD("_graph_tex_draw"), &EditorProfiler::_graph_tex_draw);
+ ClassDB::bind_method(D_METHOD("_graph_tex_input"), &EditorProfiler::_graph_tex_input);
+ ClassDB::bind_method(D_METHOD("_graph_tex_mouse_exit"), &EditorProfiler::_graph_tex_mouse_exit);
+ ClassDB::bind_method(D_METHOD("_cursor_metric_changed"), &EditorProfiler::_cursor_metric_changed);
+ ClassDB::bind_method(D_METHOD("_combo_changed"), &EditorProfiler::_combo_changed);
+
+ ClassDB::bind_method(D_METHOD("_item_edited"), &EditorProfiler::_item_edited);
+ ADD_SIGNAL(MethodInfo("enable_profiling", PropertyInfo(Variant::BOOL, "enable")));
+ ADD_SIGNAL(MethodInfo("break_request"));
}
void EditorProfiler::set_enabled(bool p_enable) {
@@ -670,115 +611,109 @@ bool EditorProfiler::is_profiling() {
return activate->is_pressed();
}
-EditorProfiler::EditorProfiler()
-{
+EditorProfiler::EditorProfiler() {
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
- activate = memnew( Button );
+ activate = memnew(Button);
activate->set_toggle_mode(true);
activate->set_text(TTR("Start Profiling"));
- activate->connect("pressed",this,"_activate_pressed");
+ activate->connect("pressed", this, "_activate_pressed");
hb->add_child(activate);
- hb->add_child( memnew( Label(TTR("Measure:") ) ) );
+ hb->add_child(memnew(Label(TTR("Measure:"))));
- display_mode = memnew( OptionButton );
+ display_mode = memnew(OptionButton);
display_mode->add_item(TTR("Frame Time (sec)"));
display_mode->add_item(TTR("Average Time (sec)"));
display_mode->add_item(TTR("Frame %"));
display_mode->add_item(TTR("Fixed Frame %"));
- display_mode->connect("item_selected",this,"_combo_changed");
+ display_mode->connect("item_selected", this, "_combo_changed");
- hb->add_child( display_mode );
+ hb->add_child(display_mode);
- hb->add_child( memnew( Label(TTR("Time:") ) ) );
+ hb->add_child(memnew(Label(TTR("Time:"))));
- display_time = memnew( OptionButton );
+ display_time = memnew(OptionButton);
display_time->add_item(TTR("Inclusive"));
display_time->add_item(TTR("Self"));
- display_time->connect("item_selected",this,"_combo_changed");
+ display_time->connect("item_selected", this, "_combo_changed");
hb->add_child(display_time);
hb->add_spacer();
- hb->add_child( memnew( Label(TTR("Frame #:") ) ) );
+ hb->add_child(memnew(Label(TTR("Frame #:"))));
- cursor_metric_edit = memnew( SpinBox );
+ cursor_metric_edit = memnew(SpinBox);
cursor_metric_edit->set_h_size_flags(SIZE_FILL);
hb->add_child(cursor_metric_edit);
- cursor_metric_edit->connect("value_changed",this,"_cursor_metric_changed");
+ cursor_metric_edit->connect("value_changed", this, "_cursor_metric_changed");
- hb->add_constant_override("separation",8);
+ hb->add_constant_override("separation", 8);
-
-
- h_split = memnew( HSplitContainer );
+ h_split = memnew(HSplitContainer);
add_child(h_split);
h_split->set_v_size_flags(SIZE_EXPAND_FILL);
- variables = memnew( Tree );
- variables->set_custom_minimum_size(Size2(300,0));
+ variables = memnew(Tree);
+ variables->set_custom_minimum_size(Size2(300, 0));
variables->set_hide_folding(true);
h_split->add_child(variables);
variables->set_hide_root(true);
variables->set_columns(3);
variables->set_column_titles_visible(true);
- variables->set_column_title(0,"Name");
- variables->set_column_expand(0,true);
- variables->set_column_min_width(0,60);
- variables->set_column_title(1,"Time");
- variables->set_column_expand(1,false);
- variables->set_column_min_width(1,60);
- variables->set_column_title(2,"Calls");
- variables->set_column_expand(2,false);
- variables->set_column_min_width(2,60);
- variables->connect("item_edited",this,"_item_edited");
-
-
- graph = memnew( TextureRect );
+ variables->set_column_title(0, "Name");
+ variables->set_column_expand(0, true);
+ variables->set_column_min_width(0, 60);
+ variables->set_column_title(1, "Time");
+ variables->set_column_expand(1, false);
+ variables->set_column_min_width(1, 60);
+ variables->set_column_title(2, "Calls");
+ variables->set_column_expand(2, false);
+ variables->set_column_min_width(2, 60);
+ variables->connect("item_edited", this, "_item_edited");
+
+ graph = memnew(TextureRect);
graph->set_expand(true);
graph->set_mouse_filter(MOUSE_FILTER_STOP);
//graph->set_ignore_mouse(false);
- graph->connect("draw",this,"_graph_tex_draw");
- graph->connect("gui_input",this,"_graph_tex_input");
- graph->connect("mouse_exited",this,"_graph_tex_mouse_exit");
+ graph->connect("draw", this, "_graph_tex_draw");
+ graph->connect("gui_input", this, "_graph_tex_input");
+ graph->connect("mouse_exited", this, "_graph_tex_mouse_exit");
h_split->add_child(graph);
graph->set_h_size_flags(SIZE_EXPAND_FILL);
- add_constant_override("separation",3);
+ add_constant_override("separation", 3);
- int metric_size=CLAMP(int(EDITOR_DEF("debugger/profiler_frame_history_size",600)),60,1024);
+ int metric_size = CLAMP(int(EDITOR_DEF("debugger/profiler_frame_history_size", 600)), 60, 1024);
frame_metrics.resize(metric_size);
- last_metric=-1;
+ last_metric = -1;
//cursor_metric=-1;
- hover_metric=-1;
+ hover_metric = -1;
-
- EDITOR_DEF("debugger/profiler_frame_max_functions",64);
+ EDITOR_DEF("debugger/profiler_frame_max_functions", 64);
//display_mode=DISPLAY_FRAME_TIME;
- frame_delay = memnew( Timer );
+ frame_delay = memnew(Timer);
frame_delay->set_wait_time(0.1);
frame_delay->set_one_shot(true);
add_child(frame_delay);
- frame_delay->connect("timeout",this,"_update_frame");
+ frame_delay->connect("timeout", this, "_update_frame");
- plot_delay = memnew( Timer );
+ plot_delay = memnew(Timer);
plot_delay->set_wait_time(0.1);
plot_delay->set_one_shot(true);
add_child(plot_delay);
- plot_delay->connect("timeout",this,"_update_plot");
+ plot_delay->connect("timeout", this, "_update_plot");
plot_sigs.insert("fixed_frame_time");
plot_sigs.insert("category_frame_time");
- seeking=false;
- graph_height=1;
+ seeking = false;
+ graph_height = 1;
//activate->set_disabled(true);
-
}
diff --git a/editor/editor_profiler.h b/editor/editor_profiler.h
index bf89e3939c..c084859942 100644
--- a/editor/editor_profiler.h
+++ b/editor/editor_profiler.h
@@ -29,23 +29,20 @@
#ifndef EDITORPROFILER_H
#define EDITORPROFILER_H
-
#include "scene/gui/box_container.h"
-#include "scene/gui/texture_rect.h"
#include "scene/gui/button.h"
#include "scene/gui/label.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/split_container.h"
#include "scene/gui/option_button.h"
#include "scene/gui/spin_box.h"
-
+#include "scene/gui/split_container.h"
+#include "scene/gui/texture_rect.h"
+#include "scene/gui/tree.h"
class EditorProfiler : public VBoxContainer {
- GDCLASS(EditorProfiler,VBoxContainer)
+ GDCLASS(EditorProfiler, VBoxContainer)
public:
-
struct Metric {
bool valid;
@@ -78,11 +75,13 @@ public:
Vector<Category> categories;
- Map<StringName,Category*> category_ptrs;
- Map<StringName,Category::Item*> item_ptrs;
-
+ Map<StringName, Category *> category_ptrs;
+ Map<StringName, Category::Item *> item_ptrs;
- Metric() { valid=false; frame_number=0; }
+ Metric() {
+ valid = false;
+ frame_number = 0;
+ }
};
enum DisplayMode {
@@ -110,7 +109,7 @@ private:
OptionButton *display_mode;
OptionButton *display_time;
- SpinBox * cursor_metric_edit;
+ SpinBox *cursor_metric_edit;
Vector<Metric> frame_metrics;
int last_metric;
@@ -133,9 +132,9 @@ private:
void _activate_pressed();
- String _get_time_as_text(Metric &m,float p_time,int p_calls);
+ String _get_time_as_text(Metric &m, float p_time, int p_calls);
- void _make_metric_ptrs(Metric& m);
+ void _make_metric_ptrs(Metric &m);
void _item_edited();
void _update_plot();
@@ -143,23 +142,22 @@ private:
void _graph_tex_mouse_exit();
void _graph_tex_draw();
- void _graph_tex_input(const InputEvent& p_ev);
+ void _graph_tex_input(const InputEvent &p_ev);
int _get_cursor_index() const;
- Color _get_color_from_signature(const StringName& p_signature) const;
+ Color _get_color_from_signature(const StringName &p_signature) const;
void _cursor_metric_changed(double);
void _combo_changed(int);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void add_frame_metric(const Metric& p_metric, bool p_final=false);
+public:
+ void add_frame_metric(const Metric &p_metric, bool p_final = false);
void set_enabled(bool p_enable);
bool is_profiling();
bool is_seeking() { return seeking; }
diff --git a/editor/editor_resource_preview.cpp b/editor/editor_resource_preview.cpp
index ab2226e79a..9eb6758cc2 100644
--- a/editor/editor_resource_preview.cpp
+++ b/editor/editor_resource_preview.cpp
@@ -28,37 +28,35 @@
/*************************************************************************/
#include "editor_resource_preview.h"
+#include "editor_scale.h"
#include "editor_settings.h"
-#include "os/file_access.h"
+#include "global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
-#include "global_config.h"
-#include "editor_scale.h"
#include "message_queue.h"
+#include "os/file_access.h"
-bool EditorResourcePreviewGenerator::handles(const String& p_type) const {
+bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
if (get_script_instance() && get_script_instance()->has_method("handles")) {
- return get_script_instance()->call("handles",p_type);
+ return get_script_instance()->call("handles", p_type);
}
ERR_EXPLAIN("EditorResourcePreviewGenerator::handles needs to be overriden");
ERR_FAIL_V(false);
}
-Ref<Texture> EditorResourcePreviewGenerator::generate(const RES& p_from){
+Ref<Texture> EditorResourcePreviewGenerator::generate(const RES &p_from) {
if (get_script_instance() && get_script_instance()->has_method("generate")) {
- return get_script_instance()->call("generate",p_from);
+ return get_script_instance()->call("generate", p_from);
}
ERR_EXPLAIN("EditorResourcePreviewGenerator::generate needs to be overriden");
ERR_FAIL_V(Ref<Texture>());
-
}
-
-Ref<Texture> EditorResourcePreviewGenerator::generate_from_path(const String& p_path) {
+Ref<Texture> EditorResourcePreviewGenerator::generate_from_path(const String &p_path) {
if (get_script_instance() && get_script_instance()->has_method("generate_from_path")) {
- return get_script_instance()->call("generate_from_path",p_path);
+ return get_script_instance()->call("generate_from_path", p_path);
}
RES res = ResourceLoader::load(p_path);
@@ -67,78 +65,69 @@ Ref<Texture> EditorResourcePreviewGenerator::generate_from_path(const String& p_
return generate(res);
}
-
void EditorResourcePreviewGenerator::_bind_methods() {
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::BOOL,"handles",PropertyInfo(Variant::STRING,"type")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::OBJECT,"generate:Texture",PropertyInfo(Variant::OBJECT,"from",PROPERTY_HINT_RESOURCE_TYPE,"Resource")));
- ClassDB::add_virtual_method(get_class_static(),MethodInfo(Variant::OBJECT,"generate_from_path:Texture",PropertyInfo(Variant::STRING,"path",PROPERTY_HINT_FILE)));
-
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::BOOL, "handles", PropertyInfo(Variant::STRING, "type")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::OBJECT, "generate:Texture", PropertyInfo(Variant::OBJECT, "from", PROPERTY_HINT_RESOURCE_TYPE, "Resource")));
+ ClassDB::add_virtual_method(get_class_static(), MethodInfo(Variant::OBJECT, "generate_from_path:Texture", PropertyInfo(Variant::STRING, "path", PROPERTY_HINT_FILE)));
}
EditorResourcePreviewGenerator::EditorResourcePreviewGenerator() {
-
-
}
-
-EditorResourcePreview* EditorResourcePreview::singleton=NULL;
-
+EditorResourcePreview *EditorResourcePreview::singleton = NULL;
void EditorResourcePreview::_thread_func(void *ud) {
- EditorResourcePreview *erp=(EditorResourcePreview*)ud;
+ EditorResourcePreview *erp = (EditorResourcePreview *)ud;
erp->_thread();
-
}
-
-void EditorResourcePreview::_preview_ready(const String& p_str,const Ref<Texture>& p_texture,ObjectID id,const StringName& p_func,const Variant& p_ud) {
+void EditorResourcePreview::_preview_ready(const String &p_str, const Ref<Texture> &p_texture, ObjectID id, const StringName &p_func, const Variant &p_ud) {
//print_line("preview is ready");
preview_mutex->lock();
String path = p_str;
- uint32_t hash=0;
- uint64_t modified_time=0;
+ uint32_t hash = 0;
+ uint64_t modified_time = 0;
if (p_str.begins_with("ID:")) {
- hash=p_str.get_slicec(':',2).to_int();
- path="ID:"+p_str.get_slicec(':',1);
+ hash = p_str.get_slicec(':', 2).to_int();
+ path = "ID:" + p_str.get_slicec(':', 1);
} else {
modified_time = FileAccess::get_modified_time(path);
}
Item item;
- item.order=order++;
- item.preview=p_texture;
- item.last_hash=hash;
- item.modified_time=modified_time;
+ item.order = order++;
+ item.preview = p_texture;
+ item.last_hash = hash;
+ item.modified_time = modified_time;
- cache[path]=item;
+ cache[path] = item;
preview_mutex->unlock();
- MessageQueue::get_singleton()->push_call(id,p_func,path,p_texture,p_ud);
-
+ MessageQueue::get_singleton()->push_call(id, p_func, path, p_texture, p_ud);
}
-Ref<Texture> EditorResourcePreview::_generate_preview(const QueueItem& p_item,const String& cache_base) {
+Ref<Texture> EditorResourcePreview::_generate_preview(const QueueItem &p_item, const String &cache_base) {
String type;
if (p_item.resource.is_valid())
- type=p_item.resource->get_class();
+ type = p_item.resource->get_class();
else
- type=ResourceLoader::get_resource_type(p_item.path);
+ type = ResourceLoader::get_resource_type(p_item.path);
//print_line("resource type is: "+type);
- if (type=="")
+ if (type == "")
return Ref<Texture>(); //could not guess type
Ref<Texture> generated;
- for(int i=0;i<preview_generators.size();i++) {
+ for (int i = 0; i < preview_generators.size(); i++) {
if (!preview_generators[i]->handles(type))
continue;
@@ -156,17 +145,16 @@ Ref<Texture> EditorResourcePreview::_generate_preview(const QueueItem& p_item,co
if (generated.is_valid()) {
//print_line("was generated");
int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
- thumbnail_size*=EDSCALE;
+ thumbnail_size *= EDSCALE;
//wow it generated a preview... save cache
- ResourceSaver::save(cache_base+".png",generated);
- FileAccess *f=FileAccess::open(cache_base+".txt",FileAccess::WRITE);
+ ResourceSaver::save(cache_base + ".png", generated);
+ FileAccess *f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
f->store_line(itos(thumbnail_size));
f->store_line(itos(FileAccess::get_modified_time(p_item.path)));
f->store_line(FileAccess::get_md5(p_item.path));
memdelete(f);
} else {
//print_line("was not generated");
-
}
}
@@ -176,7 +164,7 @@ Ref<Texture> EditorResourcePreview::_generate_preview(const QueueItem& p_item,co
void EditorResourcePreview::_thread() {
//print_line("begin thread");
- while(!exit) {
+ while (!exit) {
//print_line("wait for semaphore");
preview_sem->wait();
@@ -186,56 +174,51 @@ void EditorResourcePreview::_thread() {
if (queue.size()) {
-
-
QueueItem item = queue.front()->get();
queue.pop_front();
if (cache.has(item.path)) {
//already has it because someone loaded it, just let it know it's ready
if (item.resource.is_valid()) {
- item.path+=":"+itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
+ item.path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
}
- _preview_ready(item.path,cache[item.path].preview,item.id,item.function,item.userdata);
+ _preview_ready(item.path, cache[item.path].preview, item.id, item.function, item.userdata);
preview_mutex->unlock();
} else {
preview_mutex->unlock();
-
Ref<Texture> texture;
//print_line("pop from queue "+item.path);
int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
- thumbnail_size*=EDSCALE;
+ thumbnail_size *= EDSCALE;
+ if (item.resource.is_valid()) {
- if (item.resource.is_valid()){
-
- texture=_generate_preview(item,String());
+ texture = _generate_preview(item, String());
//adding hash to the end of path (should be ID:<objid>:<hash>) because of 5 argument limit to call_deferred
- _preview_ready(item.path+":"+itos(item.resource->hash_edited_version()),texture,item.id,item.function,item.userdata);
+ _preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, item.id, item.function, item.userdata);
} else {
-
- String temp_path=EditorSettings::get_singleton()->get_settings_path().plus_file("tmp");
+ String temp_path = EditorSettings::get_singleton()->get_settings_path().plus_file("tmp");
String cache_base = GlobalConfig::get_singleton()->globalize_path(item.path).md5_text();
- cache_base = temp_path.plus_file("resthumb-"+cache_base);
+ cache_base = temp_path.plus_file("resthumb-" + cache_base);
//does not have it, try to load a cached thumbnail
- String file = cache_base+".txt";
+ String file = cache_base + ".txt";
//print_line("cachetxt at "+file);
- FileAccess *f=FileAccess::open(file,FileAccess::READ);
+ FileAccess *f = FileAccess::open(file, FileAccess::READ);
if (!f) {
//print_line("generate because not cached");
//generate
- texture=_generate_preview(item,cache_base);
+ texture = _generate_preview(item, cache_base);
} else {
uint64_t modtime = FileAccess::get_modified_time(item.path);
@@ -244,22 +227,22 @@ void EditorResourcePreview::_thread() {
bool cache_valid = true;
- if (tsize!=thumbnail_size) {
- cache_valid=false;
+ if (tsize != thumbnail_size) {
+ cache_valid = false;
memdelete(f);
- } else if (last_modtime!=modtime) {
+ } else if (last_modtime != modtime) {
String last_md5 = f->get_line();
String md5 = FileAccess::get_md5(item.path);
memdelete(f);
- if (last_md5!=md5) {
+ if (last_md5 != md5) {
- cache_valid=false;
+ cache_valid = false;
} else {
//update modified time
- f=FileAccess::open(file,FileAccess::WRITE);
+ f = FileAccess::open(file, FileAccess::WRITE);
f->store_line(itos(modtime));
f->store_line(md5);
memdelete(f);
@@ -268,172 +251,154 @@ void EditorResourcePreview::_thread() {
memdelete(f);
}
- cache_valid=false;
+ cache_valid = false;
if (cache_valid) {
- texture = ResourceLoader::load(cache_base+".png","ImageTexture",true);
+ texture = ResourceLoader::load(cache_base + ".png", "ImageTexture", true);
if (!texture.is_valid()) {
//well fuck
- cache_valid=false;
+ cache_valid = false;
}
}
if (!cache_valid) {
- texture=_generate_preview(item,cache_base);
+ texture = _generate_preview(item, cache_base);
}
-
}
//print_line("notify of preview ready");
- _preview_ready(item.path,texture,item.id,item.function,item.userdata);
-
+ _preview_ready(item.path, texture, item.id, item.function, item.userdata);
}
}
-
} else {
preview_mutex->unlock();
}
-
}
}
-
-
-void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource>& p_res, Object* p_receiver, const StringName& p_receiver_func, const Variant& p_userdata) {
+void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
ERR_FAIL_NULL(p_receiver);
ERR_FAIL_COND(!p_res.is_valid());
preview_mutex->lock();
- String path_id = "ID:"+itos(p_res->get_instance_ID());
-
+ String path_id = "ID:" + itos(p_res->get_instance_ID());
- if (cache.has(path_id) && cache[path_id].last_hash==p_res->hash_edited_version()) {
+ if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version()) {
- cache[path_id].order=order++;
- p_receiver->call_deferred(p_receiver_func,path_id,cache[path_id].preview,p_userdata);
+ cache[path_id].order = order++;
+ p_receiver->call_deferred(p_receiver_func, path_id, cache[path_id].preview, p_userdata);
preview_mutex->unlock();
return;
-
}
cache.erase(path_id); //erase if exists, since it will be regen
//print_line("send to thread "+p_path);
QueueItem item;
- item.function=p_receiver_func;
- item.id=p_receiver->get_instance_ID();
- item.resource=p_res;
- item.path=path_id;
- item.userdata=p_userdata;
+ item.function = p_receiver_func;
+ item.id = p_receiver->get_instance_ID();
+ item.resource = p_res;
+ item.path = path_id;
+ item.userdata = p_userdata;
queue.push_back(item);
preview_mutex->unlock();
preview_sem->post();
}
-void EditorResourcePreview::queue_resource_preview(const String& p_path, Object* p_receiver, const StringName& p_receiver_func, const Variant& p_userdata) {
+void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
ERR_FAIL_NULL(p_receiver);
preview_mutex->lock();
if (cache.has(p_path)) {
- cache[p_path].order=order++;
- p_receiver->call_deferred(p_receiver_func,p_path,cache[p_path].preview,p_userdata);
+ cache[p_path].order = order++;
+ p_receiver->call_deferred(p_receiver_func, p_path, cache[p_path].preview, p_userdata);
preview_mutex->unlock();
return;
}
//print_line("send to thread "+p_path);
QueueItem item;
- item.function=p_receiver_func;
- item.id=p_receiver->get_instance_ID();
- item.path=p_path;
- item.userdata=p_userdata;
+ item.function = p_receiver_func;
+ item.id = p_receiver->get_instance_ID();
+ item.path = p_path;
+ item.userdata = p_userdata;
queue.push_back(item);
preview_mutex->unlock();
preview_sem->post();
-
}
-void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator>& p_generator) {
+void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
preview_generators.push_back(p_generator);
}
-void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator>& p_generator) {
+void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
preview_generators.erase(p_generator);
}
-EditorResourcePreview* EditorResourcePreview::get_singleton() {
+EditorResourcePreview *EditorResourcePreview::get_singleton() {
return singleton;
}
void EditorResourcePreview::_bind_methods() {
- ClassDB::bind_method("_preview_ready",&EditorResourcePreview::_preview_ready);
-
- ClassDB::bind_method(D_METHOD("queue_resource_preview","path","receiver","receiver_func","userdata:Variant"),&EditorResourcePreview::queue_resource_preview);
- ClassDB::bind_method(D_METHOD("queue_edited_resource_preview","resource:Resource","receiver","receiver_func","userdata:Variant"),&EditorResourcePreview::queue_edited_resource_preview);
- ClassDB::bind_method(D_METHOD("add_preview_generator","generator:EditorResourcePreviewGenerator"),&EditorResourcePreview::add_preview_generator);
- ClassDB::bind_method(D_METHOD("remove_preview_generator","generator:EditorResourcePreviewGenerator"),&EditorResourcePreview::remove_preview_generator);
- ClassDB::bind_method(D_METHOD("check_for_invalidation","path"),&EditorResourcePreview::check_for_invalidation);
+ ClassDB::bind_method("_preview_ready", &EditorResourcePreview::_preview_ready);
+ ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata:Variant"), &EditorResourcePreview::queue_resource_preview);
+ ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource:Resource", "receiver", "receiver_func", "userdata:Variant"), &EditorResourcePreview::queue_edited_resource_preview);
+ ClassDB::bind_method(D_METHOD("add_preview_generator", "generator:EditorResourcePreviewGenerator"), &EditorResourcePreview::add_preview_generator);
+ ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator:EditorResourcePreviewGenerator"), &EditorResourcePreview::remove_preview_generator);
+ ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
- ADD_SIGNAL(MethodInfo("preview_invalidated",PropertyInfo(Variant::STRING,"path")));
+ ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
}
-void EditorResourcePreview::check_for_invalidation(const String& p_path) {
+void EditorResourcePreview::check_for_invalidation(const String &p_path) {
preview_mutex->lock();
- bool call_invalidated=false;
+ bool call_invalidated = false;
if (cache.has(p_path)) {
uint64_t modified_time = FileAccess::get_modified_time(p_path);
- if (modified_time!=cache[p_path].modified_time) {
+ if (modified_time != cache[p_path].modified_time) {
cache.erase(p_path);
- call_invalidated=true;
+ call_invalidated = true;
}
}
preview_mutex->unlock();
- if (call_invalidated) {//do outside mutex
- call_deferred("emit_signal","preview_invalidated",p_path);
+ if (call_invalidated) { //do outside mutex
+ call_deferred("emit_signal", "preview_invalidated", p_path);
}
-
-
-
}
EditorResourcePreview::EditorResourcePreview() {
- singleton=this;
+ singleton = this;
preview_mutex = Mutex::create();
- preview_sem = Semaphore::create();
- order=0;
- exit=false;
+ preview_sem = Semaphore::create();
+ order = 0;
+ exit = false;
- thread = Thread::create(_thread_func,this);
+ thread = Thread::create(_thread_func, this);
}
+EditorResourcePreview::~EditorResourcePreview() {
-EditorResourcePreview::~EditorResourcePreview()
-{
-
- exit=true;
+ exit = true;
preview_sem->post();
Thread::wait_to_finish(thread);
memdelete(thread);
memdelete(preview_mutex);
memdelete(preview_sem);
-
-
}
-
diff --git a/editor/editor_resource_preview.h b/editor/editor_resource_preview.h
index e4a593330d..ad7f0946e5 100644
--- a/editor/editor_resource_preview.h
+++ b/editor/editor_resource_preview.h
@@ -29,9 +29,9 @@
#ifndef EDITORRESOURCEPREVIEW_H
#define EDITORRESOURCEPREVIEW_H
-#include "scene/main/node.h"
#include "os/semaphore.h"
#include "os/thread.h"
+#include "scene/main/node.h"
#include "scene/resources/texture.h"
/* make previews for:
@@ -52,30 +52,26 @@
-curve and curve2D
*/
-
class EditorResourcePreviewGenerator : public Reference {
- GDCLASS(EditorResourcePreviewGenerator,Reference );
+ GDCLASS(EditorResourcePreviewGenerator, Reference);
protected:
-
static void _bind_methods();
-public:
- virtual bool handles(const String& p_type) const;
- virtual Ref<Texture> generate(const RES& p_from);
- virtual Ref<Texture> generate_from_path(const String& p_path);
+public:
+ virtual bool handles(const String &p_type) const;
+ virtual Ref<Texture> generate(const RES &p_from);
+ virtual Ref<Texture> generate_from_path(const String &p_path);
EditorResourcePreviewGenerator();
};
-
class EditorResourcePreview : public Node {
- GDCLASS(EditorResourcePreview,Node);
-
+ GDCLASS(EditorResourcePreview, Node);
- static EditorResourcePreview* singleton;
+ static EditorResourcePreview *singleton;
struct QueueItem {
Ref<Resource> resource;
@@ -101,31 +97,29 @@ class EditorResourcePreview : public Node {
int order;
- Map<String,Item> cache;
+ Map<String, Item> cache;
- void _preview_ready(const String& p_str,const Ref<Texture>& p_texture, ObjectID id, const StringName &p_func, const Variant &p_ud);
- Ref<Texture> _generate_preview(const QueueItem& p_item, const String &cache_base);
+ void _preview_ready(const String &p_str, const Ref<Texture> &p_texture, ObjectID id, const StringName &p_func, const Variant &p_ud);
+ Ref<Texture> _generate_preview(const QueueItem &p_item, const String &cache_base);
static void _thread_func(void *ud);
void _thread();
Vector<Ref<EditorResourcePreviewGenerator> > preview_generators;
-
protected:
-
static void _bind_methods();
-public:
- static EditorResourcePreview* get_singleton();
+public:
+ static EditorResourcePreview *get_singleton();
//callback funtion is callback(String p_path,Ref<Texture> preview,Variant udata) preview null if could not load
- void queue_resource_preview(const String& p_res, Object* p_receiver, const StringName& p_receiver_func, const Variant& p_userdata);
- void queue_edited_resource_preview(const Ref<Resource>& p_path, Object* p_receiver, const StringName& p_receiver_func, const Variant& p_userdata);
+ void queue_resource_preview(const String &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata);
+ void queue_edited_resource_preview(const Ref<Resource> &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata);
- void add_preview_generator(const Ref<EditorResourcePreviewGenerator>& p_generator);
- void remove_preview_generator(const Ref<EditorResourcePreviewGenerator>& p_generator);
- void check_for_invalidation(const String& p_path);
+ void add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator);
+ void remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator);
+ void check_for_invalidation(const String &p_path);
EditorResourcePreview();
~EditorResourcePreview();
diff --git a/editor/editor_run.cpp b/editor/editor_run.cpp
index 46e400ae7f..99d32ea958 100644
--- a/editor/editor_run.cpp
+++ b/editor/editor_run.cpp
@@ -28,29 +28,27 @@
/*************************************************************************/
#include "editor_run.h"
-#include "global_config.h"
#include "editor_settings.h"
+#include "global_config.h"
EditorRun::Status EditorRun::get_status() const {
return status;
}
-Error EditorRun::run(const String& p_scene,const String p_custom_args,const List<String>& p_breakpoints) {
+Error EditorRun::run(const String &p_scene, const String p_custom_args, const List<String> &p_breakpoints) {
List<String> args;
-
String resource_path = GlobalConfig::get_singleton()->get_resource_path();
- if (resource_path!="") {
+ if (resource_path != "") {
args.push_back("-path");
- args.push_back(resource_path.replace(" ","%20"));
-
+ args.push_back(resource_path.replace(" ", "%20"));
}
if (true) {
args.push_back("-rdebug");
- args.push_back("localhost:"+String::num(GLOBAL_GET("network/debug/remote_port")));
+ args.push_back("localhost:" + String::num(GLOBAL_GET("network/debug/remote_port")));
}
args.push_back("-epid");
@@ -66,105 +64,101 @@ Error EditorRun::run(const String& p_scene,const String p_custom_args,const List
int screen = EditorSettings::get_singleton()->get("run/window_placement/screen");
- if (screen==0) {
- screen=OS::get_singleton()->get_current_screen();
+ if (screen == 0) {
+ screen = OS::get_singleton()->get_current_screen();
} else {
screen--;
}
Rect2 screen_rect;
- screen_rect.pos=OS::get_singleton()->get_screen_position(screen);
- screen_rect.size=OS::get_singleton()->get_screen_size(screen);
-
+ screen_rect.pos = OS::get_singleton()->get_screen_position(screen);
+ screen_rect.size = OS::get_singleton()->get_screen_size(screen);
Size2 desired_size;
- desired_size.x=GlobalConfig::get_singleton()->get("display/width");
- desired_size.y=GlobalConfig::get_singleton()->get("display/height");
+ desired_size.x = GlobalConfig::get_singleton()->get("display/width");
+ desired_size.y = GlobalConfig::get_singleton()->get("display/height");
Size2 test_size;
- test_size.x=GlobalConfig::get_singleton()->get("display/test_width");
- test_size.y=GlobalConfig::get_singleton()->get("display/test_height");
- if (test_size.x>0 && test_size.y>0) {
+ test_size.x = GlobalConfig::get_singleton()->get("display/test_width");
+ test_size.y = GlobalConfig::get_singleton()->get("display/test_height");
+ if (test_size.x > 0 && test_size.y > 0) {
- desired_size=test_size;
+ desired_size = test_size;
}
+ int window_placement = EditorSettings::get_singleton()->get("run/window_placement/rect");
- int window_placement=EditorSettings::get_singleton()->get("run/window_placement/rect");
-
- switch(window_placement) {
+ switch (window_placement) {
case 0: { // default
args.push_back("-p");
- args.push_back(itos(screen_rect.pos.x)+"x"+itos(screen_rect.pos.y));
+ args.push_back(itos(screen_rect.pos.x) + "x" + itos(screen_rect.pos.y));
} break;
case 1: { // centered
- Vector2 pos=screen_rect.pos+((screen_rect.size-desired_size)/2).floor();
+ Vector2 pos = screen_rect.pos + ((screen_rect.size - desired_size) / 2).floor();
args.push_back("-p");
- args.push_back(itos(pos.x)+"x"+itos(pos.y));
+ args.push_back(itos(pos.x) + "x" + itos(pos.y));
} break;
case 2: { // custom pos
Vector2 pos = EditorSettings::get_singleton()->get("run/window_placement/rect_custom_position");
- pos+=screen_rect.pos;
+ pos += screen_rect.pos;
args.push_back("-p");
- args.push_back(itos(pos.x)+"x"+itos(pos.y));
+ args.push_back(itos(pos.x) + "x" + itos(pos.y));
} break;
case 3: { // force maximized
- Vector2 pos=screen_rect.pos;
+ Vector2 pos = screen_rect.pos;
args.push_back("-p");
- args.push_back(itos(pos.x)+"x"+itos(pos.y));
+ args.push_back(itos(pos.x) + "x" + itos(pos.y));
args.push_back("-mx");
} break;
case 4: { // force fullscreen
- Vector2 pos=screen_rect.pos;
+ Vector2 pos = screen_rect.pos;
args.push_back("-p");
- args.push_back(itos(pos.x)+"x"+itos(pos.y));
+ args.push_back(itos(pos.x) + "x" + itos(pos.y));
args.push_back("-f");
} break;
}
-
-
if (p_breakpoints.size()) {
args.push_back("-bp");
String bpoints;
- for(const List<String>::Element *E=p_breakpoints.front();E;E=E->next()) {
+ for (const List<String>::Element *E = p_breakpoints.front(); E; E = E->next()) {
- bpoints+=E->get().replace(" ","%20");
+ bpoints += E->get().replace(" ", "%20");
if (E->next())
- bpoints+=",";
+ bpoints += ",";
}
args.push_back(bpoints);
}
-
- if (p_scene!="") {
+
+ if (p_scene != "") {
args.push_back(p_scene);
}
- if (p_custom_args!="") {
- Vector<String> cargs=p_custom_args.split(" ",false);
- for(int i=0;i<cargs.size();i++) {
- args.push_back(cargs[i].replace(" ","%20"));
+ if (p_custom_args != "") {
+ Vector<String> cargs = p_custom_args.split(" ", false);
+ for (int i = 0; i < cargs.size(); i++) {
+ args.push_back(cargs[i].replace(" ", "%20"));
}
}
String exec = OS::get_singleton()->get_executable_path();
printf("running: %ls", exec.c_str());
- for (List<String>::Element* E = args.front(); E ; E = E->next()) {
+ for (List<String>::Element *E = args.front(); E; E = E->next()) {
printf(" %ls", E->get().c_str());
};
printf("\n");
- pid=0;
- Error err = OS::get_singleton()->execute(exec,args,false,&pid);
- ERR_FAIL_COND_V(err,err);
+ pid = 0;
+ Error err = OS::get_singleton()->execute(exec, args, false, &pid);
+ ERR_FAIL_COND_V(err, err);
status = STATUS_PLAY;
@@ -173,39 +167,37 @@ Error EditorRun::run(const String& p_scene,const String p_custom_args,const List
void EditorRun::stop() {
- if (status!=STATUS_STOP && pid!=0) {
+ if (status != STATUS_STOP && pid != 0) {
OS::get_singleton()->kill(pid);
}
- status=STATUS_STOP;
+ status = STATUS_STOP;
}
void EditorRun::set_debug_collisions(bool p_debug) {
- debug_collisions=p_debug;
+ debug_collisions = p_debug;
}
-bool EditorRun::get_debug_collisions() const{
+bool EditorRun::get_debug_collisions() const {
return debug_collisions;
}
void EditorRun::set_debug_navigation(bool p_debug) {
- debug_navigation=p_debug;
+ debug_navigation = p_debug;
}
-bool EditorRun::get_debug_navigation() const{
+bool EditorRun::get_debug_navigation() const {
return debug_navigation;
}
-
EditorRun::EditorRun() {
- status=STATUS_STOP;
- debug_collisions=false;
- debug_navigation=false;
-
+ status = STATUS_STOP;
+ debug_collisions = false;
+ debug_navigation = false;
}
diff --git a/editor/editor_run.h b/editor/editor_run.h
index 46c5dc7521..796ff8fa3e 100644
--- a/editor/editor_run.h
+++ b/editor/editor_run.h
@@ -29,8 +29,8 @@
#ifndef EDITOR_RUN_H
#define EDITOR_RUN_H
-#include "scene/main/node.h"
#include "os/os.h"
+#include "scene/main/node.h"
class EditorRun {
public:
enum Status {
@@ -41,16 +41,16 @@ public:
};
OS::ProcessID pid;
-private:
+private:
bool debug_collisions;
bool debug_navigation;
Status status;
-public:
+public:
Status get_status() const;
- Error run(const String& p_scene,const String p_custom_args,const List<String>& p_breakpoints);
- void run_native_notify() { status=STATUS_PLAY; }
+ Error run(const String &p_scene, const String p_custom_args, const List<String> &p_breakpoints);
+ void run_native_notify() { status = STATUS_PLAY; }
void stop();
OS::ProcessID get_pid() const { return pid; }
diff --git a/editor/editor_run_native.cpp b/editor/editor_run_native.cpp
index 60a9f53b94..5e27598307 100644
--- a/editor/editor_run_native.cpp
+++ b/editor/editor_run_native.cpp
@@ -100,7 +100,7 @@ void EditorRunNative::_notification(int p_what) {
#endif
}
-void EditorRunNative::_run_native(int p_idx,const String& p_platform) {
+void EditorRunNative::_run_native(int p_idx, const String &p_platform) {
#if 0
Ref<EditorExportPlatform> eep = EditorImportExport::get_singleton()->get_export_platform(p_platform);
@@ -132,58 +132,56 @@ void EditorRunNative::_run_native(int p_idx,const String& p_platform) {
void EditorRunNative::_bind_methods() {
- ClassDB::bind_method("_run_native",&EditorRunNative::_run_native);
+ ClassDB::bind_method("_run_native", &EditorRunNative::_run_native);
ADD_SIGNAL(MethodInfo("native_run"));
}
void EditorRunNative::set_deploy_dumb(bool p_enabled) {
- deploy_dumb=p_enabled;
+ deploy_dumb = p_enabled;
}
-bool EditorRunNative::is_deploy_dumb_enabled() const{
+bool EditorRunNative::is_deploy_dumb_enabled() const {
return deploy_dumb;
}
void EditorRunNative::set_deploy_debug_remote(bool p_enabled) {
- deploy_debug_remote=p_enabled;
+ deploy_debug_remote = p_enabled;
}
-bool EditorRunNative::is_deploy_debug_remote_enabled() const{
+bool EditorRunNative::is_deploy_debug_remote_enabled() const {
return deploy_debug_remote;
}
void EditorRunNative::set_debug_collisions(bool p_debug) {
- debug_collisions=p_debug;
+ debug_collisions = p_debug;
}
-bool EditorRunNative::get_debug_collisions() const{
+bool EditorRunNative::get_debug_collisions() const {
return debug_collisions;
}
void EditorRunNative::set_debug_navigation(bool p_debug) {
- debug_navigation=p_debug;
+ debug_navigation = p_debug;
}
-bool EditorRunNative::get_debug_navigation() const{
+bool EditorRunNative::get_debug_navigation() const {
return debug_navigation;
}
-EditorRunNative::EditorRunNative()
-{
+EditorRunNative::EditorRunNative() {
set_process(true);
- first=true;
- deploy_dumb=false;
- deploy_debug_remote=false;
- debug_collisions=false;
- debug_navigation=false;
-
+ first = true;
+ deploy_dumb = false;
+ deploy_debug_remote = false;
+ debug_collisions = false;
+ debug_navigation = false;
}
diff --git a/editor/editor_run_native.h b/editor/editor_run_native.h
index c62021148b..92eaa8516b 100644
--- a/editor/editor_run_native.h
+++ b/editor/editor_run_native.h
@@ -34,23 +34,22 @@
class EditorRunNative : public HBoxContainer {
- GDCLASS(EditorRunNative,BoxContainer);
+ GDCLASS(EditorRunNative, BoxContainer);
- Map<StringName,MenuButton*> menus;
+ Map<StringName, MenuButton *> menus;
bool first;
bool deploy_dumb;
bool deploy_debug_remote;
bool debug_collisions;
bool debug_navigation;
- void _run_native(int p_idx,const String& p_platform);
+ void _run_native(int p_idx, const String &p_platform);
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
+public:
void set_deploy_dumb(bool p_enabled);
bool is_deploy_dumb_enabled() const;
diff --git a/editor/editor_run_script.cpp b/editor/editor_run_script.cpp
index 77dc7bd4bf..21c97b4587 100644
--- a/editor/editor_run_script.cpp
+++ b/editor/editor_run_script.cpp
@@ -30,16 +30,15 @@
#include "editor_node.h"
-
void EditorScript::add_root_node(Node *p_node) {
if (!editor) {
- EditorNode::add_io_error("EditorScript::add_root_node: "+TTR("Write your logic in the _run() method."));
+ EditorNode::add_io_error("EditorScript::add_root_node: " + TTR("Write your logic in the _run() method."));
return;
}
if (editor->get_edited_scene()) {
- EditorNode::add_io_error("EditorScript::add_root_node: "+TTR("There is an edited scene already."));
+ EditorNode::add_io_error("EditorScript::add_root_node: " + TTR("There is an edited scene already."));
return;
}
@@ -49,7 +48,7 @@ void EditorScript::add_root_node(Node *p_node) {
Node *EditorScript::get_scene() {
if (!editor) {
- EditorNode::add_io_error("EditorScript::get_scene: "+TTR("Write your logic in the _run() method."));
+ EditorNode::add_io_error("EditorScript::get_scene: " + TTR("Write your logic in the _run() method."));
return NULL;
}
@@ -61,37 +60,32 @@ void EditorScript::_run() {
Ref<Script> s = get_script();
ERR_FAIL_COND(!s.is_valid());
if (!get_script_instance()) {
- EditorNode::add_io_error(TTR("Couldn't instance script:")+"\n "+s->get_path()+"\n"+TTR("Did you forget the 'tool' keyword?"));
+ EditorNode::add_io_error(TTR("Couldn't instance script:") + "\n " + s->get_path() + "\n" + TTR("Did you forget the 'tool' keyword?"));
return;
-
}
Variant::CallError ce;
- ce.error=Variant::CallError::CALL_OK;
- get_script_instance()->call("_run",NULL,0,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
+ ce.error = Variant::CallError::CALL_OK;
+ get_script_instance()->call("_run", NULL, 0, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
- EditorNode::add_io_error(TTR("Couldn't run script:")+"\n "+s->get_path()+"\n"+TTR("Did you forget the '_run' method?"));
+ EditorNode::add_io_error(TTR("Couldn't run script:") + "\n " + s->get_path() + "\n" + TTR("Did you forget the '_run' method?"));
}
}
void EditorScript::set_editor(EditorNode *p_editor) {
- editor=p_editor;
+ editor = p_editor;
}
-
void EditorScript::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_root_node","node"),&EditorScript::add_root_node);
- ClassDB::bind_method(D_METHOD("get_scene"),&EditorScript::get_scene);
- BIND_VMETHOD( MethodInfo("_run") );
-
-
+ ClassDB::bind_method(D_METHOD("add_root_node", "node"), &EditorScript::add_root_node);
+ ClassDB::bind_method(D_METHOD("get_scene"), &EditorScript::get_scene);
+ BIND_VMETHOD(MethodInfo("_run"));
}
EditorScript::EditorScript() {
- editor=NULL;
+ editor = NULL;
}
-
diff --git a/editor/editor_run_script.h b/editor/editor_run_script.h
index 3ab8525cc6..270600db69 100644
--- a/editor/editor_run_script.h
+++ b/editor/editor_run_script.h
@@ -31,18 +31,17 @@
#include "reference.h"
-
class EditorNode;
class EditorScript : public Reference {
- GDCLASS( EditorScript, Reference );
+ GDCLASS(EditorScript, Reference);
EditorNode *editor;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void add_root_node(Node *p_node);
Node *get_scene();
diff --git a/editor/editor_scale.cpp b/editor/editor_scale.cpp
index 5687f97b22..027f1edc28 100644
--- a/editor/editor_scale.cpp
+++ b/editor/editor_scale.cpp
@@ -34,7 +34,7 @@ static float scale = 1.0;
void editor_set_scale(float p_scale) {
- scale=p_scale;
+ scale = p_scale;
}
float editor_get_scale() {
diff --git a/editor/editor_settings.cpp b/editor/editor_settings.cpp
index f977a40243..8794a34f62 100644
--- a/editor/editor_settings.cpp
+++ b/editor/editor_settings.cpp
@@ -28,84 +28,80 @@
/*************************************************************************/
#include "editor_settings.h"
-#include "os/os.h"
-#include "os/dir_access.h"
-#include "os/file_access.h"
-#include "version.h"
-#include "scene/main/scene_main_loop.h"
-#include "scene/main/node.h"
-#include "io/resource_loader.h"
-#include "io/resource_saver.h"
-#include "scene/main/viewport.h"
-#include "io/config_file.h"
#include "editor_node.h"
#include "global_config.h"
-#include "translations.h"
+#include "io/compression.h"
+#include "io/config_file.h"
#include "io/file_access_memory.h"
+#include "io/resource_loader.h"
+#include "io/resource_saver.h"
#include "io/translation_loader_po.h"
-#include "io/compression.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
#include "os/keyboard.h"
+#include "os/os.h"
+#include "scene/main/node.h"
+#include "scene/main/scene_main_loop.h"
+#include "scene/main/viewport.h"
+#include "translations.h"
+#include "version.h"
-
-
-
-Ref<EditorSettings> EditorSettings::singleton=NULL;
+Ref<EditorSettings> EditorSettings::singleton = NULL;
EditorSettings *EditorSettings::get_singleton() {
return singleton.ptr();
}
-
-bool EditorSettings::_set(const StringName& p_name, const Variant& p_value) {
+bool EditorSettings::_set(const StringName &p_name, const Variant &p_value) {
_THREAD_SAFE_METHOD_
- if (p_name.operator String()=="shortcuts") {
+ if (p_name.operator String() == "shortcuts") {
- Array arr=p_value;
- ERR_FAIL_COND_V(arr.size() && arr.size()&1,true);
- for(int i=0;i<arr.size();i+=2) {
+ Array arr = p_value;
+ ERR_FAIL_COND_V(arr.size() && arr.size() & 1, true);
+ for (int i = 0; i < arr.size(); i += 2) {
String name = arr[i];
- InputEvent shortcut = arr[i+1];
+ InputEvent shortcut = arr[i + 1];
Ref<ShortCut> sc;
sc.instance();
sc->set_shortcut(shortcut);
- add_shortcut(name,sc);
+ add_shortcut(name, sc);
}
return true;
}
- if (p_value.get_type()==Variant::NIL)
+ if (p_value.get_type() == Variant::NIL)
props.erase(p_name);
else {
if (props.has(p_name))
- props[p_name].variant=p_value;
+ props[p_name].variant = p_value;
else
- props[p_name]=VariantContainer(p_value,last_order++);
+ props[p_name] = VariantContainer(p_value, last_order++);
if (save_changed_setting) {
- props[p_name].save=true;
+ props[p_name].save = true;
}
}
emit_signal("settings_changed");
return true;
}
-bool EditorSettings::_get(const StringName& p_name,Variant &r_ret) const {
+bool EditorSettings::_get(const StringName &p_name, Variant &r_ret) const {
_THREAD_SAFE_METHOD_
- if (p_name.operator String()=="shortcuts") {
+ if (p_name.operator String() == "shortcuts") {
Array arr;
- for (const Map<String,Ref<ShortCut> >::Element *E=shortcuts.front();E;E=E->next()) {
+ for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) {
- Ref<ShortCut> sc=E->get();
+ Ref<ShortCut> sc = E->get();
if (optimize_save) {
if (!sc->has_meta("original")) {
@@ -113,20 +109,20 @@ bool EditorSettings::_get(const StringName& p_name,Variant &r_ret) const {
}
InputEvent original = sc->get_meta("original");
- if (sc->is_shortcut(original) || (original.type==InputEvent::NONE && sc->get_shortcut().type==InputEvent::NONE))
+ if (sc->is_shortcut(original) || (original.type == InputEvent::NONE && sc->get_shortcut().type == InputEvent::NONE))
continue; //not changed from default, don't save
}
arr.push_back(E->key());
arr.push_back(sc->get_shortcut());
}
- r_ret=arr;
+ r_ret = arr;
return true;
}
- const VariantContainer *v=props.getptr(p_name);
+ const VariantContainer *v = props.getptr(p_name);
if (!v) {
- print_line("EditorSettings::_get - Warning, not found: "+String(p_name));
+ print_line("EditorSettings::_get - Warning, not found: " + String(p_name));
return false;
}
r_ret = v->variant;
@@ -140,56 +136,54 @@ struct _EVCSort {
int order;
bool save;
- bool operator<(const _EVCSort& p_vcs) const{ return order< p_vcs.order; }
+ bool operator<(const _EVCSort &p_vcs) const { return order < p_vcs.order; }
};
void EditorSettings::_get_property_list(List<PropertyInfo> *p_list) const {
_THREAD_SAFE_METHOD_
- const String *k=NULL;
+ const String *k = NULL;
Set<_EVCSort> vclist;
- while ((k=props.next(k))) {
+ while ((k = props.next(k))) {
- const VariantContainer *v=props.getptr(*k);
+ const VariantContainer *v = props.getptr(*k);
if (v->hide_from_editor)
continue;
_EVCSort vc;
- vc.name=*k;
- vc.order=v->order;
- vc.type=v->variant.get_type();
- vc.save=v->save;
-
+ vc.name = *k;
+ vc.order = v->order;
+ vc.type = v->variant.get_type();
+ vc.save = v->save;
vclist.insert(vc);
}
- for(Set<_EVCSort>::Element *E=vclist.front();E;E=E->next()) {
+ for (Set<_EVCSort>::Element *E = vclist.front(); E; E = E->next()) {
int pinfo = 0;
if (E->get().save || !optimize_save) {
- pinfo|=PROPERTY_USAGE_STORAGE;
+ pinfo |= PROPERTY_USAGE_STORAGE;
}
if (!E->get().name.begins_with("_") && !E->get().name.begins_with("projects/")) {
- pinfo|=PROPERTY_USAGE_EDITOR;
+ pinfo |= PROPERTY_USAGE_EDITOR;
} else {
- pinfo|=PROPERTY_USAGE_STORAGE; //hiddens must always be saved
+ pinfo |= PROPERTY_USAGE_STORAGE; //hiddens must always be saved
}
PropertyInfo pi(E->get().type, E->get().name);
- pi.usage=pinfo;
+ pi.usage = pinfo;
if (hints.has(E->get().name))
- pi=hints[E->get().name];
+ pi = hints[E->get().name];
-
- p_list->push_back( pi );
+ p_list->push_back(pi);
}
- p_list->push_back(PropertyInfo(Variant::ARRAY,"shortcuts",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); //do not edit
+ p_list->push_back(PropertyInfo(Variant::ARRAY, "shortcuts", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); //do not edit
}
bool EditorSettings::has(String p_var) const {
@@ -206,33 +200,27 @@ void EditorSettings::erase(String p_var) {
props.erase(p_var);
}
-void EditorSettings::raise_order(const String& p_name) {
+void EditorSettings::raise_order(const String &p_name) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(!props.has(p_name));
- props[p_name].order=++last_order;
-
-
+ props[p_name].order = ++last_order;
}
-
-Variant _EDITOR_DEF( const String& p_var, const Variant& p_default) {
+Variant _EDITOR_DEF(const String &p_var, const Variant &p_default) {
if (EditorSettings::get_singleton()->has(p_var))
return EditorSettings::get_singleton()->get(p_var);
- EditorSettings::get_singleton()->set(p_var,p_default);
+ EditorSettings::get_singleton()->set(p_var, p_default);
return p_default;
-
}
-
void EditorSettings::create() {
-
if (singleton.ptr())
return; //pointless
- DirAccess *dir=NULL;
+ DirAccess *dir = NULL;
Variant meta;
String config_path;
@@ -241,7 +229,7 @@ void EditorSettings::create() {
Ref<ConfigFile> extra_config = memnew(ConfigFile);
String exe_path = OS::get_singleton()->get_executable_path().get_base_dir();
- DirAccess* d = DirAccess::create_for_path(exe_path);
+ DirAccess *d = DirAccess::create_for_path(exe_path);
bool self_contained = false;
if (d->file_exists(exe_path + "/._sc_")) {
@@ -260,57 +248,57 @@ void EditorSettings::create() {
if (OS::get_singleton()->has_environment("APPDATA")) {
// Most likely under windows, save here
- config_path=OS::get_singleton()->get_environment("APPDATA");
- config_dir=String(_MKSTR(VERSION_SHORT_NAME)).capitalize();
+ config_path = OS::get_singleton()->get_environment("APPDATA");
+ config_dir = String(_MKSTR(VERSION_SHORT_NAME)).capitalize();
} else if (OS::get_singleton()->has_environment("HOME")) {
- config_path=OS::get_singleton()->get_environment("HOME");
- config_dir="."+String(_MKSTR(VERSION_SHORT_NAME)).to_lower();
+ config_path = OS::get_singleton()->get_environment("HOME");
+ config_dir = "." + String(_MKSTR(VERSION_SHORT_NAME)).to_lower();
}
};
ClassDB::register_class<EditorSettings>(); //otherwise it can't be unserialized
String config_file_path;
- if (config_path!=""){
+ if (config_path != "") {
dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- if (dir->change_dir(config_path)!=OK) {
+ if (dir->change_dir(config_path) != OK) {
ERR_PRINT("Cannot find path for config directory!");
memdelete(dir);
goto fail;
}
- if (dir->change_dir(config_dir)!=OK) {
+ if (dir->change_dir(config_dir) != OK) {
dir->make_dir(config_dir);
- if (dir->change_dir(config_dir)!=OK) {
+ if (dir->change_dir(config_dir) != OK) {
ERR_PRINT("Cannot create config directory!");
memdelete(dir);
goto fail;
}
}
- if (dir->change_dir("templates")!=OK) {
+ if (dir->change_dir("templates") != OK) {
dir->make_dir("templates");
} else {
dir->change_dir("..");
}
- if (dir->change_dir("text_editor_themes")!=OK) {
+ if (dir->change_dir("text_editor_themes") != OK) {
dir->make_dir("text_editor_themes");
} else {
dir->change_dir("..");
}
- if (dir->change_dir("tmp")!=OK) {
+ if (dir->change_dir("tmp") != OK) {
dir->make_dir("tmp");
} else {
dir->change_dir("..");
}
- if (dir->change_dir("config")!=OK) {
+ if (dir->change_dir("config") != OK) {
dir->make_dir("config");
} else {
@@ -319,10 +307,10 @@ void EditorSettings::create() {
dir->change_dir("config");
- String pcp=GlobalConfig::get_singleton()->get_resource_path();
+ String pcp = GlobalConfig::get_singleton()->get_resource_path();
if (pcp.ends_with("/"))
- pcp=config_path.substr(0,pcp.size()-1);
- pcp=pcp.get_file()+"-"+pcp.md5_text();
+ pcp = config_path.substr(0, pcp.size() - 1);
+ pcp = pcp.get_file() + "-" + pcp.md5_text();
if (dir->change_dir(pcp)) {
dir->make_dir(pcp);
@@ -346,17 +334,17 @@ void EditorSettings::create() {
memdelete(dir);
- singleton = ResourceLoader::load(open_path,"EditorSettings");
+ singleton = ResourceLoader::load(open_path, "EditorSettings");
if (singleton.is_null()) {
WARN_PRINT("Could not open config file.");
goto fail;
}
- singleton->save_changed_setting=true;
- singleton->config_file_path=config_file_path;
- singleton->project_config_path=pcp;
- singleton->settings_path=config_path+"/"+config_dir;
+ singleton->save_changed_setting = true;
+ singleton->config_file_path = config_file_path;
+ singleton->project_config_path = pcp;
+ singleton->settings_path = config_path + "/" + config_dir;
if (OS::get_singleton()->is_stdout_verbose()) {
@@ -369,33 +357,28 @@ void EditorSettings::create() {
singleton->list_text_editor_themes();
return;
-
}
-
-
- fail:
+fail:
// patch init projects
if (extra_config->has_section("init_projects")) {
Vector<String> list = extra_config->get_value("init_projects", "list");
- for (int i=0; i<list.size(); i++) {
+ for (int i = 0; i < list.size(); i++) {
list[i] = exe_path + "/" + list[i];
};
extra_config->set_value("init_projects", "list", list);
};
- singleton = Ref<EditorSettings>( memnew( EditorSettings ) );
- singleton->save_changed_setting=true;
- singleton->config_file_path=config_file_path;
- singleton->settings_path=config_path+"/"+config_dir;
+ singleton = Ref<EditorSettings>(memnew(EditorSettings));
+ singleton->save_changed_setting = true;
+ singleton->config_file_path = config_file_path;
+ singleton->settings_path = config_path + "/" + config_dir;
singleton->_load_defaults(extra_config);
singleton->setup_language();
singleton->setup_network();
singleton->list_text_editor_themes();
-
-
}
String EditorSettings::get_settings_path() const {
@@ -403,16 +386,14 @@ String EditorSettings::get_settings_path() const {
return settings_path;
}
-
-
void EditorSettings::setup_language() {
String lang = get("interface/editor_language");
- if (lang=="en")
- return;//none to do
+ if (lang == "en")
+ return; //none to do
- for(int i=0;i<translations.size();i++) {
- if (translations[i]->get_locale()==lang) {
+ for (int i = 0; i < translations.size(); i++) {
+ if (translations[i]->get_locale() == lang) {
TranslationServer::get_singleton()->set_tool_translation(translations[i]);
break;
}
@@ -425,30 +406,27 @@ void EditorSettings::setup_network() {
IP::get_singleton()->get_local_addresses(&local_ip);
String lip;
String hint;
- String current=get("network/debug_host");
+ String current = get("network/debug_host");
- for(List<IP_Address>::Element *E=local_ip.front();E;E=E->next()) {
+ for (List<IP_Address>::Element *E = local_ip.front(); E; E = E->next()) {
String ip = E->get();
- if (ip=="127.0.0.1")
+ if (ip == "127.0.0.1")
continue;
- if (lip=="")
- lip=ip;
- if (ip==current)
- lip=current; //so it saves
- if (hint!="")
- hint+=",";
- hint+=ip;
-
+ if (lip == "")
+ lip = ip;
+ if (ip == current)
+ lip = current; //so it saves
+ if (hint != "")
+ hint += ",";
+ hint += ip;
}
- set("network/debug_host",lip);
- add_property_hint(PropertyInfo(Variant::STRING,"network/debug_host",PROPERTY_HINT_ENUM,hint));
-
+ set("network/debug_host", lip);
+ add_property_hint(PropertyInfo(Variant::STRING, "network/debug_host", PROPERTY_HINT_ENUM, hint));
}
-
void EditorSettings::save() {
//_THREAD_SAFE_METHOD_
@@ -456,14 +434,14 @@ void EditorSettings::save() {
if (!singleton.ptr())
return;
- if (singleton->config_file_path=="") {
+ if (singleton->config_file_path == "") {
ERR_PRINT("Cannot save EditorSettings config, no valid path");
return;
}
- Error err = ResourceSaver::save(singleton->config_file_path,singleton);
+ Error err = ResourceSaver::save(singleton->config_file_path, singleton);
- if (err!=OK) {
+ if (err != OK) {
ERR_PRINT("Can't Save!");
return;
}
@@ -471,7 +449,6 @@ void EditorSettings::save() {
if (OS::get_singleton()->is_stdout_verbose()) {
print_line("EditorSettings Save OK!");
}
-
}
void EditorSettings::destroy() {
@@ -479,69 +456,65 @@ void EditorSettings::destroy() {
if (!singleton.ptr())
return;
save();
- singleton=Ref<EditorSettings>();
+ singleton = Ref<EditorSettings>();
}
void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
_THREAD_SAFE_METHOD_
-
{
- String lang_hint="en";
+ String lang_hint = "en";
String host_lang = OS::get_singleton()->get_locale();
String best;
- for(int i=0;i<translations.size();i++) {
+ for (int i = 0; i < translations.size(); i++) {
String locale = translations[i]->get_locale();
- lang_hint+=",";
- lang_hint+=locale;
+ lang_hint += ",";
+ lang_hint += locale;
- if (host_lang==locale) {
- best=locale;
+ if (host_lang == locale) {
+ best = locale;
}
- if (best==String() && host_lang.begins_with(locale)) {
- best=locale;
+ if (best == String() && host_lang.begins_with(locale)) {
+ best = locale;
}
}
- if (best==String()) {
- best="en";
+ if (best == String()) {
+ best = "en";
}
- set("interface/editor_language",best);
- hints["interface/editor_language"]=PropertyInfo(Variant::STRING,"interface/editor_language",PROPERTY_HINT_ENUM,lang_hint,PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
+ set("interface/editor_language", best);
+ hints["interface/editor_language"] = PropertyInfo(Variant::STRING, "interface/editor_language", PROPERTY_HINT_ENUM, lang_hint, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
}
- set("interface/hidpi_mode",0);
- hints["interface/hidpi_mode"]=PropertyInfo(Variant::INT,"interface/hidpi_mode",PROPERTY_HINT_ENUM,"Auto,VeryLoDPI,LoDPI,MidDPI,HiDPI",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
- set("interface/show_script_in_scene_tabs",false);
- set("interface/font_size",14);
- hints["interface/font_size"]=PropertyInfo(Variant::INT,"interface/font_size",PROPERTY_HINT_RANGE,"10,40,1",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
- set("interface/source_font_size",14);
- hints["interface/source_font_size"]=PropertyInfo(Variant::INT,"interface/source_font_size",PROPERTY_HINT_RANGE,"8,96,1",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
- set("interface/custom_font","");
- hints["interface/custom_font"]=PropertyInfo(Variant::STRING,"interface/custom_font",PROPERTY_HINT_GLOBAL_FILE,"*.fnt",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
- set("interface/custom_theme","");
- hints["interface/custom_theme"]=PropertyInfo(Variant::STRING,"interface/custom_theme",PROPERTY_HINT_GLOBAL_FILE,"*.res,*.tres,*.theme",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
-
-
- set("filesystem/directories/autoscan_project_path","");
- hints["filesystem/directories/autoscan_project_path"]=PropertyInfo(Variant::STRING,"filesystem/directories/autoscan_project_path",PROPERTY_HINT_GLOBAL_DIR);
- set("filesystem/directories/default_project_path","");
- hints["filesystem/directories/default_project_path"]=PropertyInfo(Variant::STRING,"filesystem/directories/default_project_path",PROPERTY_HINT_GLOBAL_DIR);
- set("filesystem/directories/default_project_export_path","");
- hints["global/default_project_export_path"]=PropertyInfo(Variant::STRING,"global/default_project_export_path",PROPERTY_HINT_GLOBAL_DIR);
- set("interface/show_script_in_scene_tabs",false);
-
-
- set("text_editor/theme/color_theme","Default");
- hints["text_editor/theme/color_theme"]=PropertyInfo(Variant::STRING,"text_editor/theme/color_theme",PROPERTY_HINT_ENUM,"Default");
-
- set("text_editor/theme/line_spacing",4);
-
+ set("interface/hidpi_mode", 0);
+ hints["interface/hidpi_mode"] = PropertyInfo(Variant::INT, "interface/hidpi_mode", PROPERTY_HINT_ENUM, "Auto,VeryLoDPI,LoDPI,MidDPI,HiDPI", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ set("interface/show_script_in_scene_tabs", false);
+ set("interface/font_size", 14);
+ hints["interface/font_size"] = PropertyInfo(Variant::INT, "interface/font_size", PROPERTY_HINT_RANGE, "10,40,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ set("interface/source_font_size", 14);
+ hints["interface/source_font_size"] = PropertyInfo(Variant::INT, "interface/source_font_size", PROPERTY_HINT_RANGE, "8,96,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ set("interface/custom_font", "");
+ hints["interface/custom_font"] = PropertyInfo(Variant::STRING, "interface/custom_font", PROPERTY_HINT_GLOBAL_FILE, "*.fnt", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+ set("interface/custom_theme", "");
+ hints["interface/custom_theme"] = PropertyInfo(Variant::STRING, "interface/custom_theme", PROPERTY_HINT_GLOBAL_FILE, "*.res,*.tres,*.theme", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+
+ set("filesystem/directories/autoscan_project_path", "");
+ hints["filesystem/directories/autoscan_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/autoscan_project_path", PROPERTY_HINT_GLOBAL_DIR);
+ set("filesystem/directories/default_project_path", "");
+ hints["filesystem/directories/default_project_path"] = PropertyInfo(Variant::STRING, "filesystem/directories/default_project_path", PROPERTY_HINT_GLOBAL_DIR);
+ set("filesystem/directories/default_project_export_path", "");
+ hints["global/default_project_export_path"] = PropertyInfo(Variant::STRING, "global/default_project_export_path", PROPERTY_HINT_GLOBAL_DIR);
+ set("interface/show_script_in_scene_tabs", false);
+
+ set("text_editor/theme/color_theme", "Default");
+ hints["text_editor/theme/color_theme"] = PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, "Default");
+
+ set("text_editor/theme/line_spacing", 4);
_load_default_text_editor_theme();
@@ -551,7 +524,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
set("text_editor/cursor/scroll_past_end_of_file", false);
set("text_editor/indent/tab_size", 4);
- hints["text_editor/indent/tab_size"]=PropertyInfo(Variant::INT,"text_editor/indent/tab_size",PROPERTY_HINT_RANGE,"1, 64, 1"); // size of 0 crashes.
+ hints["text_editor/indent/tab_size"] = PropertyInfo(Variant::INT, "text_editor/indent/tab_size", PROPERTY_HINT_RANGE, "1, 64, 1"); // size of 0 crashes.
set("text_editor/indent/draw_tabs", true);
set("text_editor/line_numbers/show_line_numbers", true);
@@ -559,124 +532,122 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
set("text_editor/line_numbers/show_breakpoint_gutter", true);
set("text_editor/line_numbers/show_line_length_guideline", false);
set("text_editor/line_numbers/line_length_guideline_column", 80);
- hints["text_editor/line_numbers/line_length_guideline_column"]=PropertyInfo(Variant::INT,"text_editor/line_numbers/line_length_guideline_column",PROPERTY_HINT_RANGE,"20, 160, 10");
+ hints["text_editor/line_numbers/line_length_guideline_column"] = PropertyInfo(Variant::INT, "text_editor/line_numbers/line_length_guideline_column", PROPERTY_HINT_RANGE, "20, 160, 10");
set("text_editor/files/trim_trailing_whitespace_on_save", false);
- set("text_editor/completion/idle_parse_delay",2);
- set("text_editor/tools/create_signal_callbacks",true);
- set("text_editor/files/autosave_interval_secs",0);
+ set("text_editor/completion/idle_parse_delay", 2);
+ set("text_editor/tools/create_signal_callbacks", true);
+ set("text_editor/files/autosave_interval_secs", 0);
set("text_editor/cursor/block_caret", false);
set("text_editor/cursor/caret_blink", false);
set("text_editor/cursor/caret_blink_speed", 0.65);
- hints["text_editor/cursor/caret_blink_speed"]=PropertyInfo(Variant::REAL,"text_editor/cursor/caret_blink_speed",PROPERTY_HINT_RANGE,"0.1, 10, 0.1");
+ hints["text_editor/cursor/caret_blink_speed"] = PropertyInfo(Variant::REAL, "text_editor/cursor/caret_blink_speed", PROPERTY_HINT_RANGE, "0.1, 10, 0.1");
- set("text_editor/theme/font","");
- hints["text_editor/theme/font"]=PropertyInfo(Variant::STRING,"text_editor/theme/font",PROPERTY_HINT_GLOBAL_FILE,"*.fnt");
+ set("text_editor/theme/font", "");
+ hints["text_editor/theme/font"] = PropertyInfo(Variant::STRING, "text_editor/theme/font", PROPERTY_HINT_GLOBAL_FILE, "*.fnt");
set("text_editor/completion/auto_brace_complete", false);
- set("text_editor/files/restore_scripts_on_load",true);
-
+ set("text_editor/files/restore_scripts_on_load", true);
//set("docks/scene_tree/display_old_action_buttons",false);
- set("docks/scene_tree/start_create_dialog_fully_expanded",false);
- set("docks/scene_tree/draw_relationship_lines",false);
- set("docks/scene_tree/relationship_line_color",Color::html("464646"));
+ set("docks/scene_tree/start_create_dialog_fully_expanded", false);
+ set("docks/scene_tree/draw_relationship_lines", false);
+ set("docks/scene_tree/relationship_line_color", Color::html("464646"));
set("editors/grid_map/pick_distance", 5000.0);
- set("editors/3d/grid_color",Color(0,1,0,0.2));
- hints["editors/3d/grid_color"]=PropertyInfo(Variant::COLOR,"editors/3d/grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED);
-
- set("editors/3d/default_fov",45.0);
- set("editors/3d/default_z_near",0.1);
- set("editors/3d/default_z_far",500.0);
-
- set("editors/3d/navigation_scheme",0);
- hints["editors/3d/navigation_scheme"]=PropertyInfo(Variant::INT,"editors/3d/navigation_scheme",PROPERTY_HINT_ENUM,"Godot,Maya,Modo");
- set("editors/3d/zoom_style",0);
- hints["editors/3d/zoom_style"]=PropertyInfo(Variant::INT,"editors/3d/zoom_style",PROPERTY_HINT_ENUM,"Vertical, Horizontal");
- set("editors/3d/orbit_modifier",0);
- hints["editors/3d/orbit_modifier"]=PropertyInfo(Variant::INT,"editors/3d/orbit_modifier",PROPERTY_HINT_ENUM,"None,Shift,Alt,Meta,Ctrl");
- set("editors/3d/pan_modifier",1);
- hints["editors/3d/pan_modifier"]=PropertyInfo(Variant::INT,"editors/3d/pan_modifier",PROPERTY_HINT_ENUM,"None,Shift,Alt,Meta,Ctrl");
- set("editors/3d/zoom_modifier",4);
- hints["editors/3d/zoom_modifier"]=PropertyInfo(Variant::INT,"editors/3d/zoom_modifier",PROPERTY_HINT_ENUM,"None,Shift,Alt,Meta,Ctrl");
- set("editors/3d/emulate_numpad",false);
+ set("editors/3d/grid_color", Color(0, 1, 0, 0.2));
+ hints["editors/3d/grid_color"] = PropertyInfo(Variant::COLOR, "editors/3d/grid_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED);
+
+ set("editors/3d/default_fov", 45.0);
+ set("editors/3d/default_z_near", 0.1);
+ set("editors/3d/default_z_far", 500.0);
+
+ set("editors/3d/navigation_scheme", 0);
+ hints["editors/3d/navigation_scheme"] = PropertyInfo(Variant::INT, "editors/3d/navigation_scheme", PROPERTY_HINT_ENUM, "Godot,Maya,Modo");
+ set("editors/3d/zoom_style", 0);
+ hints["editors/3d/zoom_style"] = PropertyInfo(Variant::INT, "editors/3d/zoom_style", PROPERTY_HINT_ENUM, "Vertical, Horizontal");
+ set("editors/3d/orbit_modifier", 0);
+ hints["editors/3d/orbit_modifier"] = PropertyInfo(Variant::INT, "editors/3d/orbit_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl");
+ set("editors/3d/pan_modifier", 1);
+ hints["editors/3d/pan_modifier"] = PropertyInfo(Variant::INT, "editors/3d/pan_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl");
+ set("editors/3d/zoom_modifier", 4);
+ hints["editors/3d/zoom_modifier"] = PropertyInfo(Variant::INT, "editors/3d/zoom_modifier", PROPERTY_HINT_ENUM, "None,Shift,Alt,Meta,Ctrl");
+ set("editors/3d/emulate_numpad", false);
set("editors/3d/emulate_3_button_mouse", false);
- set("editors/2d/bone_width",5);
- set("editors/2d/bone_color1",Color(1.0,1.0,1.0,0.9));
- set("editors/2d/bone_color2",Color(0.75,0.75,0.75,0.9));
- set("editors/2d/bone_selected_color",Color(0.9,0.45,0.45,0.9));
- set("editors/2d/bone_ik_color",Color(0.9,0.9,0.45,0.9));
+ set("editors/2d/bone_width", 5);
+ set("editors/2d/bone_color1", Color(1.0, 1.0, 1.0, 0.9));
+ set("editors/2d/bone_color2", Color(0.75, 0.75, 0.75, 0.9));
+ set("editors/2d/bone_selected_color", Color(0.9, 0.45, 0.45, 0.9));
+ set("editors/2d/bone_ik_color", Color(0.9, 0.9, 0.45, 0.9));
set("editors/2d/keep_margins_when_changing_anchors", false);
- set("run/window_placement/rect",0);
- hints["run/window_placement/rect"]=PropertyInfo(Variant::INT,"run/window_placement/rect",PROPERTY_HINT_ENUM,"Default,Centered,Custom Position,Force Maximized,Force Full Screen");
- String screen_hints=TTR("Default (Same as Editor)");
- for(int i=0;i<OS::get_singleton()->get_screen_count();i++) {
- screen_hints+=",Monitor "+itos(i+1);
+ set("run/window_placement/rect", 0);
+ hints["run/window_placement/rect"] = PropertyInfo(Variant::INT, "run/window_placement/rect", PROPERTY_HINT_ENUM, "Default,Centered,Custom Position,Force Maximized,Force Full Screen");
+ String screen_hints = TTR("Default (Same as Editor)");
+ for (int i = 0; i < OS::get_singleton()->get_screen_count(); i++) {
+ screen_hints += ",Monitor " + itos(i + 1);
}
- set("run/window_placement/rect_custom_position",Vector2());
- set("run/window_placement/screen",0);
- hints["run/window_placement/screen"]=PropertyInfo(Variant::INT,"run/window_placement/screen",PROPERTY_HINT_ENUM,screen_hints);
+ set("run/window_placement/rect_custom_position", Vector2());
+ set("run/window_placement/screen", 0);
+ hints["run/window_placement/screen"] = PropertyInfo(Variant::INT, "run/window_placement/screen", PROPERTY_HINT_ENUM, screen_hints);
- set("filesystem/on_save/compress_binary_resources",true);
- set("filesystem/on_save/save_modified_external_resources",true);
+ set("filesystem/on_save/compress_binary_resources", true);
+ set("filesystem/on_save/save_modified_external_resources", true);
//set("filesystem/on_save/save_paths_as_relative",false);
//set("filesystem/on_save/save_paths_without_extension",false);
- set("text_editor/tools/create_signal_callbacks",true);
+ set("text_editor/tools/create_signal_callbacks", true);
set("filesystem/file_dialog/show_hidden_files", false);
set("filesystem/file_dialog/display_mode", 0);
- hints["filesystem/file_dialog/display_mode"]=PropertyInfo(Variant::INT,"filesystem/file_dialog/display_mode",PROPERTY_HINT_ENUM,"Thumbnails,List");
+ hints["filesystem/file_dialog/display_mode"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List");
set("filesystem/file_dialog/thumbnail_size", 64);
- hints["filesystem/file_dialog/thumbnail_size"]=PropertyInfo(Variant::INT,"filesystem/file_dialog/thumbnail_size",PROPERTY_HINT_RANGE,"32,128,16");
+ hints["filesystem/file_dialog/thumbnail_size"] = PropertyInfo(Variant::INT, "filesystem/file_dialog/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16");
set("docks/filesystem/display_mode", 0);
- hints["docks/filesystem/display_mode"]=PropertyInfo(Variant::INT,"docks/filesystem/display_mode",PROPERTY_HINT_ENUM,"Thumbnails,List");
+ hints["docks/filesystem/display_mode"] = PropertyInfo(Variant::INT, "docks/filesystem/display_mode", PROPERTY_HINT_ENUM, "Thumbnails,List");
set("docks/filesystem/thumbnail_size", 64);
- hints["docks/filesystem/thumbnail_size"]=PropertyInfo(Variant::INT,"docks/filesystem/thumbnail_size",PROPERTY_HINT_RANGE,"32,128,16");
+ hints["docks/filesystem/thumbnail_size"] = PropertyInfo(Variant::INT, "docks/filesystem/thumbnail_size", PROPERTY_HINT_RANGE, "32,128,16");
- set("editors/animation/autorename_animation_tracks",true);
- set("editors/animation/confirm_insert_track",true);
+ set("editors/animation/autorename_animation_tracks", true);
+ set("editors/animation/confirm_insert_track", true);
- set("docks/property_editor/texture_preview_width",48);
- set("docks/property_editor/auto_refresh_interval",0.3);
- set("text_editor/help/doc_path","");
+ set("docks/property_editor/texture_preview_width", 48);
+ set("docks/property_editor/auto_refresh_interval", 0.3);
+ set("text_editor/help/doc_path", "");
- set("filesystem/import/ask_save_before_reimport",false);
+ set("filesystem/import/ask_save_before_reimport", false);
- set("filesystem/import/pvrtc_texture_tool","");
+ set("filesystem/import/pvrtc_texture_tool", "");
#ifdef WINDOWS_ENABLED
- hints["filesystem/import/pvrtc_texture_tool"]=PropertyInfo(Variant::STRING,"import/pvrtc_texture_tool",PROPERTY_HINT_GLOBAL_FILE,"*.exe");
+ hints["filesystem/import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, "*.exe");
#else
- hints["import/pvrtc_texture_tool"]=PropertyInfo(Variant::STRING,"import/pvrtc_texture_tool",PROPERTY_HINT_GLOBAL_FILE,"");
+ hints["import/pvrtc_texture_tool"] = PropertyInfo(Variant::STRING, "import/pvrtc_texture_tool", PROPERTY_HINT_GLOBAL_FILE, "");
#endif
// TODO: Rename to "filesystem/import/pvrtc_fast_conversion" to match other names?
- set("filesystem/import/pvrtc_fast_conversion",false);
-
+ set("filesystem/import/pvrtc_fast_conversion", false);
- set("run/auto_save/save_before_running",true);
- set("run/output/always_clear_output_on_play",true);
- set("run/output/always_open_output_on_play",true);
- set("run/output/always_close_output_on_stop",false);
- set("filesystem/resources/save_compressed_resources",true);
- set("filesystem/resources/auto_reload_modified_images",true);
+ set("run/auto_save/save_before_running", true);
+ set("run/output/always_clear_output_on_play", true);
+ set("run/output/always_open_output_on_play", true);
+ set("run/output/always_close_output_on_stop", false);
+ set("filesystem/resources/save_compressed_resources", true);
+ set("filesystem/resources/auto_reload_modified_images", true);
- set("filesystem/import/automatic_reimport_on_sources_changed",true);
+ set("filesystem/import/automatic_reimport_on_sources_changed", true);
if (p_extra_config.is_valid()) {
if (p_extra_config->has_section("init_projects") && p_extra_config->has_section_key("init_projects", "list")) {
Vector<String> list = p_extra_config->get_value("init_projects", "list");
- for (int i=0; i<list.size(); i++) {
+ for (int i = 0; i < list.size(); i++) {
String name = list[i].replace("/", "::");
- set("projects/"+name, list[i]);
+ set("projects/" + name, list[i]);
};
};
@@ -685,7 +656,7 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
List<String> keys;
p_extra_config->get_section_keys("presets", &keys);
- for (List<String>::Element *E=keys.front();E;E=E->next()) {
+ for (List<String>::Element *E = keys.front(); E; E = E->next()) {
String key = E->get();
Variant val = p_extra_config->get_value("presets", key);
@@ -693,49 +664,45 @@ void EditorSettings::_load_defaults(Ref<ConfigFile> p_extra_config) {
};
};
};
-
-
-
-
}
void EditorSettings::_load_default_text_editor_theme() {
- set("text_editor/highlighting/background_color",Color::html("3b000000"));
+ set("text_editor/highlighting/background_color", Color::html("3b000000"));
set("text_editor/highlighting/completion_background_color", Color::html("2C2A32"));
set("text_editor/highlighting/completion_selected_color", Color::html("434244"));
set("text_editor/highlighting/completion_existing_color", Color::html("21dfdfdf"));
set("text_editor/highlighting/completion_scroll_color", Color::html("ffffff"));
set("text_editor/highlighting/completion_font_color", Color::html("aaaaaa"));
- set("text_editor/highlighting/caret_color",Color::html("aaaaaa"));
+ set("text_editor/highlighting/caret_color", Color::html("aaaaaa"));
set("text_editor/highlighting/caret_background_color", Color::html("000000"));
- set("text_editor/highlighting/line_number_color",Color::html("66aaaaaa"));
- set("text_editor/highlighting/text_color",Color::html("aaaaaa"));
- set("text_editor/highlighting/text_selected_color",Color::html("000000"));
- set("text_editor/highlighting/keyword_color",Color::html("ffffb3"));
- set("text_editor/highlighting/base_type_color",Color::html("a4ffd4"));
- set("text_editor/highlighting/engine_type_color",Color::html("83d3ff"));
- set("text_editor/highlighting/function_color",Color::html("66a2ce"));
- set("text_editor/highlighting/member_variable_color",Color::html("e64e59"));
- set("text_editor/highlighting/comment_color",Color::html("676767"));
- set("text_editor/highlighting/string_color",Color::html("ef6ebe"));
- set("text_editor/highlighting/number_color",Color::html("EB9532"));
- set("text_editor/highlighting/symbol_color",Color::html("badfff"));
- set("text_editor/highlighting/selection_color",Color::html("7b5dbe"));
- set("text_editor/highlighting/brace_mismatch_color",Color(1,0.2,0.2));
- set("text_editor/highlighting/current_line_color",Color(0.3,0.5,0.8,0.15));
- set("text_editor/highlighting/line_length_guideline_color",Color(0.3,0.5,0.8,0.1));
- set("text_editor/highlighting/mark_color", Color(1.0,0.4,0.4,0.4));
- set("text_editor/highlighting/breakpoint_color", Color(0.8,0.8,0.4,0.2));
- set("text_editor/highlighting/word_highlighted_color",Color(0.8,0.9,0.9,0.15));
- set("text_editor/highlighting/search_result_color",Color(0.05,0.25,0.05,1));
- set("text_editor/highlighting/search_result_border_color",Color(0.1,0.45,0.1,1));
+ set("text_editor/highlighting/line_number_color", Color::html("66aaaaaa"));
+ set("text_editor/highlighting/text_color", Color::html("aaaaaa"));
+ set("text_editor/highlighting/text_selected_color", Color::html("000000"));
+ set("text_editor/highlighting/keyword_color", Color::html("ffffb3"));
+ set("text_editor/highlighting/base_type_color", Color::html("a4ffd4"));
+ set("text_editor/highlighting/engine_type_color", Color::html("83d3ff"));
+ set("text_editor/highlighting/function_color", Color::html("66a2ce"));
+ set("text_editor/highlighting/member_variable_color", Color::html("e64e59"));
+ set("text_editor/highlighting/comment_color", Color::html("676767"));
+ set("text_editor/highlighting/string_color", Color::html("ef6ebe"));
+ set("text_editor/highlighting/number_color", Color::html("EB9532"));
+ set("text_editor/highlighting/symbol_color", Color::html("badfff"));
+ set("text_editor/highlighting/selection_color", Color::html("7b5dbe"));
+ set("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2));
+ set("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15));
+ set("text_editor/highlighting/line_length_guideline_color", Color(0.3, 0.5, 0.8, 0.1));
+ set("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4));
+ set("text_editor/highlighting/breakpoint_color", Color(0.8, 0.8, 0.4, 0.2));
+ set("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15));
+ set("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1));
+ set("text_editor/highlighting/search_result_border_color", Color(0.1, 0.45, 0.1, 1));
}
void EditorSettings::notify_changes() {
_THREAD_SAFE_METHOD_
- SceneTree *sml=NULL;
+ SceneTree *sml = NULL;
if (OS::get_singleton()->get_main_loop())
sml = OS::get_singleton()->get_main_loop()->cast_to<SceneTree>();
@@ -750,10 +717,9 @@ void EditorSettings::notify_changes() {
return;
}
root->propagate_notification(NOTIFICATION_EDITOR_SETTINGS_CHANGED);
-
}
-void EditorSettings::_add_property_info_bind(const Dictionary& p_info) {
+void EditorSettings::_add_property_info_bind(const Dictionary &p_info) {
ERR_FAIL_COND(!p_info.has("name"));
ERR_FAIL_COND(!p_info.has("type"));
@@ -772,28 +738,22 @@ void EditorSettings::_add_property_info_bind(const Dictionary& p_info) {
add_property_hint(pinfo);
}
-void EditorSettings::add_property_hint(const PropertyInfo& p_hint) {
+void EditorSettings::add_property_hint(const PropertyInfo &p_hint) {
_THREAD_SAFE_METHOD_
- hints[p_hint.name]=p_hint;
+ hints[p_hint.name] = p_hint;
}
+void EditorSettings::set_favorite_dirs(const Vector<String> &p_favorites) {
-
-
-
-
-void EditorSettings::set_favorite_dirs(const Vector<String>& p_favorites) {
-
- favorite_dirs=p_favorites;
- FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("favorite_dirs"),FileAccess::WRITE);
+ favorite_dirs = p_favorites;
+ FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("favorite_dirs"), FileAccess::WRITE);
if (f) {
- for(int i=0;i<favorite_dirs.size();i++)
+ for (int i = 0; i < favorite_dirs.size(); i++)
f->store_line(favorite_dirs[i]);
memdelete(f);
}
-
}
Vector<String> EditorSettings::get_favorite_dirs() const {
@@ -801,13 +761,12 @@ Vector<String> EditorSettings::get_favorite_dirs() const {
return favorite_dirs;
}
+void EditorSettings::set_recent_dirs(const Vector<String> &p_recent) {
-void EditorSettings::set_recent_dirs(const Vector<String>& p_recent) {
-
- recent_dirs=p_recent;
- FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("recent_dirs"),FileAccess::WRITE);
+ recent_dirs = p_recent;
+ FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("recent_dirs"), FileAccess::WRITE);
if (f) {
- for(int i=0;i<recent_dirs.size();i++)
+ for (int i = 0; i < recent_dirs.size(); i++)
f->store_line(recent_dirs[i]);
memdelete(f);
}
@@ -820,42 +779,39 @@ Vector<String> EditorSettings::get_recent_dirs() const {
String EditorSettings::get_project_settings_path() const {
-
return get_settings_path().plus_file("config").plus_file(project_config_path);
}
-
void EditorSettings::load_favorites() {
- FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("favorite_dirs"),FileAccess::READ);
+ FileAccess *f = FileAccess::open(get_project_settings_path().plus_file("favorite_dirs"), FileAccess::READ);
if (f) {
String line = f->get_line().strip_edges();
- while(line!="") {
+ while (line != "") {
favorite_dirs.push_back(line);
line = f->get_line().strip_edges();
}
memdelete(f);
}
- f = FileAccess::open(get_project_settings_path().plus_file("recent_dirs"),FileAccess::READ);
+ f = FileAccess::open(get_project_settings_path().plus_file("recent_dirs"), FileAccess::READ);
if (f) {
String line = f->get_line().strip_edges();
- while(line!="") {
+ while (line != "") {
recent_dirs.push_back(line);
line = f->get_line().strip_edges();
}
memdelete(f);
}
-
}
void EditorSettings::list_text_editor_themes() {
- String themes="Default";
+ String themes = "Default";
DirAccess *d = DirAccess::open(settings_path + "/text_editor_themes");
if (d) {
d->list_dir_begin();
String file = d->get_next();
- while(file != String()) {
+ while (file != String()) {
if (file.get_extension() == "tet" && file.get_basename().to_lower() != "default") {
themes += "," + file.get_basename();
}
@@ -864,18 +820,18 @@ void EditorSettings::list_text_editor_themes() {
d->list_dir_end();
memdelete(d);
}
- add_property_hint(PropertyInfo(Variant::STRING,"text_editor/theme/color_theme",PROPERTY_HINT_ENUM,themes));
+ add_property_hint(PropertyInfo(Variant::STRING, "text_editor/theme/color_theme", PROPERTY_HINT_ENUM, themes));
}
void EditorSettings::load_text_editor_theme() {
if (get("text_editor/theme/color_theme") == "Default") {
- _load_default_text_editor_theme(); // sorry for "Settings changed" console spam
+ _load_default_text_editor_theme(); // sorry for "Settings changed" console spam
return;
}
String theme_path = get_settings_path() + "/text_editor_themes/" + get("text_editor/theme/color_theme") + ".tet";
- Ref<ConfigFile> cf = memnew( ConfigFile );
+ Ref<ConfigFile> cf = memnew(ConfigFile);
Error err = cf->load(theme_path);
if (err != OK) {
@@ -885,7 +841,7 @@ void EditorSettings::load_text_editor_theme() {
List<String> keys;
cf->get_section_keys("color_theme", &keys);
- for(List<String>::Element *E=keys.front();E;E=E->next()) {
+ for (List<String>::Element *E = keys.front(); E; E = E->next()) {
String key = E->get();
String val = cf->get_value("color_theme", key);
@@ -894,7 +850,7 @@ void EditorSettings::load_text_editor_theme() {
// make sure it is actually a color
if (val.is_valid_html_color() && key.find("color") >= 0) {
- props["text_editor/highlighting/"+key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam
+ props["text_editor/highlighting/" + key].variant = Color::html(val); // change manually to prevent "Settings changed" console spam
}
}
}
@@ -940,7 +896,7 @@ bool EditorSettings::save_text_editor_theme_as(String p_file) {
if (p_file.get_file().to_lower() == "default.tet") {
return false;
}
- if(_save_text_editor_theme(p_file)) {
+ if (_save_text_editor_theme(p_file)) {
// switch to theme is saved in the theme directory
list_text_editor_themes();
@@ -957,7 +913,7 @@ bool EditorSettings::save_text_editor_theme_as(String p_file) {
bool EditorSettings::_save_text_editor_theme(String p_file) {
String theme_section = "color_theme";
- Ref<ConfigFile> cf = memnew( ConfigFile ); // hex is better?
+ Ref<ConfigFile> cf = memnew(ConfigFile); // hex is better?
cf->set_value(theme_section, "background_color", ((Color)get("text_editor/highlighting/background_color")).to_html());
cf->set_value(theme_section, "completion_background_color", ((Color)get("text_editor/highlighting/completion_background_color")).to_html());
cf->set_value(theme_section, "completion_selected_color", ((Color)get("text_editor/highlighting/completion_selected_color")).to_html());
@@ -988,7 +944,6 @@ bool EditorSettings::_save_text_editor_theme(String p_file) {
cf->set_value(theme_section, "search_result_color", ((Color)get("text_editor/highlighting/search_result_color")).to_html());
cf->set_value(theme_section, "search_result_border_color", ((Color)get("text_editor/highlighting/search_result_border_color")).to_html());
-
Error err = cf->save(p_file);
if (err == OK) {
@@ -997,27 +952,25 @@ bool EditorSettings::_save_text_editor_theme(String p_file) {
return false;
}
+void EditorSettings::add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcut) {
-void EditorSettings::add_shortcut(const String& p_name, Ref<ShortCut> &p_shortcut) {
-
- shortcuts[p_name]=p_shortcut;
+ shortcuts[p_name] = p_shortcut;
}
-bool EditorSettings::is_shortcut(const String&p_name, const InputEvent &p_event) const{
+bool EditorSettings::is_shortcut(const String &p_name, const InputEvent &p_event) const {
- const Map<String,Ref<ShortCut> >::Element *E=shortcuts.find(p_name);
+ const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name);
if (!E) {
- ERR_EXPLAIN("Unknown Shortcut: "+p_name);
+ ERR_EXPLAIN("Unknown Shortcut: " + p_name);
ERR_FAIL_V(false);
}
return E->get()->is_shortcut(p_event);
-
}
-Ref<ShortCut> EditorSettings::get_shortcut(const String&p_name) const{
+Ref<ShortCut> EditorSettings::get_shortcut(const String &p_name) const {
- const Map<String,Ref<ShortCut> >::Element *E=shortcuts.find(p_name);
+ const Map<String, Ref<ShortCut> >::Element *E = shortcuts.find(p_name);
if (!E)
return Ref<ShortCut>();
@@ -1026,7 +979,7 @@ Ref<ShortCut> EditorSettings::get_shortcut(const String&p_name) const{
void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) {
- for (const Map<String,Ref<ShortCut> >::Element*E=shortcuts.front();E;E=E->next()) {
+ for (const Map<String, Ref<ShortCut> >::Element *E = shortcuts.front(); E; E = E->next()) {
r_shortcuts->push_back(E->key());
}
@@ -1034,11 +987,11 @@ void EditorSettings::get_shortcut_list(List<String> *r_shortcuts) {
void EditorSettings::set_optimize_save(bool p_optimize) {
- optimize_save=p_optimize;
+ optimize_save = p_optimize;
}
-Variant EditorSettings::get_project_metadata(const String& p_section, const String& p_key, Variant p_default) {
- Ref<ConfigFile> cf = memnew( ConfigFile );
+Variant EditorSettings::get_project_metadata(const String &p_section, const String &p_key, Variant p_default) {
+ Ref<ConfigFile> cf = memnew(ConfigFile);
String path = get_project_settings_path().plus_file("project_metadata.cfg");
Error err = cf->load(path);
if (err != OK) {
@@ -1047,9 +1000,8 @@ Variant EditorSettings::get_project_metadata(const String& p_section, const Stri
return cf->get_value(p_section, p_key, p_default);
}
-void EditorSettings::set_project_metadata(const String& p_section, const String& p_key, Variant p_data)
-{
- Ref<ConfigFile> cf = memnew( ConfigFile );
+void EditorSettings::set_project_metadata(const String &p_section, const String &p_key, Variant p_data) {
+ Ref<ConfigFile> cf = memnew(ConfigFile);
String path = get_project_settings_path().plus_file("project_metadata.cfg");
cf->load(path);
cf->set_value(p_section, p_key, p_data);
@@ -1058,42 +1010,40 @@ void EditorSettings::set_project_metadata(const String& p_section, const String&
void EditorSettings::_bind_methods() {
- ClassDB::bind_method(D_METHOD("erase","property"),&EditorSettings::erase);
- ClassDB::bind_method(D_METHOD("get_settings_path"),&EditorSettings::get_settings_path);
- ClassDB::bind_method(D_METHOD("get_project_settings_path"),&EditorSettings::get_project_settings_path);
+ ClassDB::bind_method(D_METHOD("erase", "property"), &EditorSettings::erase);
+ ClassDB::bind_method(D_METHOD("get_settings_path"), &EditorSettings::get_settings_path);
+ ClassDB::bind_method(D_METHOD("get_project_settings_path"), &EditorSettings::get_project_settings_path);
- ClassDB::bind_method(D_METHOD("add_property_info", "info"),&EditorSettings::_add_property_info_bind);
+ ClassDB::bind_method(D_METHOD("add_property_info", "info"), &EditorSettings::_add_property_info_bind);
- ClassDB::bind_method(D_METHOD("set_favorite_dirs","dirs"),&EditorSettings::set_favorite_dirs);
- ClassDB::bind_method(D_METHOD("get_favorite_dirs"),&EditorSettings::get_favorite_dirs);
+ ClassDB::bind_method(D_METHOD("set_favorite_dirs", "dirs"), &EditorSettings::set_favorite_dirs);
+ ClassDB::bind_method(D_METHOD("get_favorite_dirs"), &EditorSettings::get_favorite_dirs);
- ClassDB::bind_method(D_METHOD("set_recent_dirs","dirs"),&EditorSettings::set_recent_dirs);
- ClassDB::bind_method(D_METHOD("get_recent_dirs"),&EditorSettings::get_recent_dirs);
+ ClassDB::bind_method(D_METHOD("set_recent_dirs", "dirs"), &EditorSettings::set_recent_dirs);
+ ClassDB::bind_method(D_METHOD("get_recent_dirs"), &EditorSettings::get_recent_dirs);
ADD_SIGNAL(MethodInfo("settings_changed"));
-
}
EditorSettings::EditorSettings() {
-
//singleton=this;
- last_order=0;
- optimize_save=true;
- save_changed_setting=true;
+ last_order = 0;
+ optimize_save = true;
+ save_changed_setting = true;
- EditorTranslationList *etl=_editor_translations;
+ EditorTranslationList *etl = _editor_translations;
- while(etl->data) {
+ while (etl->data) {
Vector<uint8_t> data;
data.resize(etl->uncomp_size);
- Compression::decompress(data.ptr(),etl->uncomp_size,etl->data,etl->comp_size,Compression::MODE_DEFLATE);
+ Compression::decompress(data.ptr(), etl->uncomp_size, etl->data, etl->comp_size, Compression::MODE_DEFLATE);
- FileAccessMemory *fa = memnew (FileAccessMemory);
- fa->open_custom(data.ptr(),data.size());
+ FileAccessMemory *fa = memnew(FileAccessMemory);
+ fa->open_custom(data.ptr(), data.size());
- Ref<Translation> tr = TranslationLoaderPO::load_translation(fa,NULL,"translation_"+String(etl->lang));
+ Ref<Translation> tr = TranslationLoaderPO::load_translation(fa, NULL, "translation_" + String(etl->lang));
if (tr.is_valid()) {
tr->set_locale(etl->lang);
@@ -1101,58 +1051,53 @@ EditorSettings::EditorSettings() {
}
etl++;
-
}
_load_defaults();
-
-
}
-
EditorSettings::~EditorSettings() {
//singleton=NULL;
}
-Ref<ShortCut> ED_GET_SHORTCUT(const String& p_path) {
+Ref<ShortCut> ED_GET_SHORTCUT(const String &p_path) {
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path);
if (!sc.is_valid()) {
- ERR_EXPLAIN("Used ED_GET_SHORTCUT with invalid shortcut: "+p_path);
- ERR_FAIL_COND_V(!sc.is_valid(),sc);
+ ERR_EXPLAIN("Used ED_GET_SHORTCUT with invalid shortcut: " + p_path);
+ ERR_FAIL_COND_V(!sc.is_valid(), sc);
}
return sc;
}
-Ref<ShortCut> ED_SHORTCUT(const String& p_path,const String& p_name,uint32_t p_keycode) {
+Ref<ShortCut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode) {
InputEvent ie;
if (p_keycode) {
- ie.type=InputEvent::KEY;
- ie.key.unicode=p_keycode&KEY_CODE_MASK;
- ie.key.scancode=p_keycode&KEY_CODE_MASK;
- ie.key.mod.shift=bool(p_keycode&KEY_MASK_SHIFT);
- ie.key.mod.alt=bool(p_keycode&KEY_MASK_ALT);
- ie.key.mod.control=bool(p_keycode&KEY_MASK_CTRL);
- ie.key.mod.meta=bool(p_keycode&KEY_MASK_META);
-
+ ie.type = InputEvent::KEY;
+ ie.key.unicode = p_keycode & KEY_CODE_MASK;
+ ie.key.scancode = p_keycode & KEY_CODE_MASK;
+ ie.key.mod.shift = bool(p_keycode & KEY_MASK_SHIFT);
+ ie.key.mod.alt = bool(p_keycode & KEY_MASK_ALT);
+ ie.key.mod.control = bool(p_keycode & KEY_MASK_CTRL);
+ ie.key.mod.meta = bool(p_keycode & KEY_MASK_META);
}
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(p_path);
if (sc.is_valid()) {
sc->set_name(p_name); //keep name (the ones that come from disk have no name)
- sc->set_meta("original",ie); //to compare against changes
+ sc->set_meta("original", ie); //to compare against changes
return sc;
}
sc.instance();
sc->set_name(p_name);
sc->set_shortcut(ie);
- sc->set_meta("original",ie); //to compare against changes
- EditorSettings::get_singleton()->add_shortcut(p_path,sc);
+ sc->set_meta("original", ie); //to compare against changes
+ EditorSettings::get_singleton()->add_shortcut(p_path, sc);
return sc;
}
diff --git a/editor/editor_settings.h b/editor/editor_settings.h
index 809389eb40..4e084e5291 100644
--- a/editor/editor_settings.h
+++ b/editor/editor_settings.h
@@ -31,17 +31,18 @@
#include "object.h"
-#include "resource.h"
-#include "os/thread_safe.h"
#include "core/io/config_file.h"
-#include "translation.h"
+#include "os/thread_safe.h"
+#include "resource.h"
#include "scene/gui/input_action.h"
+#include "translation.h"
class EditorPlugin;
class EditorSettings : public Resource {
- GDCLASS( EditorSettings, Resource );
+ GDCLASS(EditorSettings, Resource);
+
private:
_THREAD_SAFE_CLASS_
@@ -58,24 +59,32 @@ public:
String script;
Vector<String> install_files;
};
-private:
+private:
struct VariantContainer {
int order;
Variant variant;
bool hide_from_editor;
bool save;
- VariantContainer(){ order=0; hide_from_editor=false; save=false;}
- VariantContainer(const Variant& p_variant, int p_order) { variant=p_variant; order=p_order; hide_from_editor=false; }
+ VariantContainer() {
+ order = 0;
+ hide_from_editor = false;
+ save = false;
+ }
+ VariantContainer(const Variant &p_variant, int p_order) {
+ variant = p_variant;
+ order = p_order;
+ hide_from_editor = false;
+ }
};
- HashMap<String,PropertyInfo> hints;
+ HashMap<String, PropertyInfo> hints;
int last_order;
- HashMap<String,VariantContainer> props;
+ HashMap<String, VariantContainer> props;
String resource_path;
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
static Ref<EditorSettings> singleton;
@@ -85,7 +94,6 @@ private:
Ref<Resource> clipboard;
-
bool save_changed_setting;
bool optimize_save; //do not save stuff that came from config but was not set from engine
@@ -102,20 +110,18 @@ private:
Vector<Ref<Translation> > translations;
- Map<String,Ref<ShortCut> > shortcuts;
+ Map<String, Ref<ShortCut> > shortcuts;
- void _add_property_info_bind(const Dictionary& p_info);
+ void _add_property_info_bind(const Dictionary &p_info);
protected:
-
static void _bind_methods();
-public:
+public:
enum {
- NOTIFICATION_EDITOR_SETTINGS_CHANGED=10000
+ NOTIFICATION_EDITOR_SETTINGS_CHANGED = 10000
};
-
bool has(String p_var) const;
static EditorSettings *get_singleton();
void erase(String p_var);
@@ -123,26 +129,25 @@ public:
//String get_global_settings_path() const;
String get_project_settings_path() const;
-
void setup_language();
void setup_network();
- void raise_order(const String& p_name);
+ void raise_order(const String &p_name);
static void create();
static void save();
static void destroy();
void notify_changes();
- void set_resource_clipboard(const Ref<Resource>& p_resource) { clipboard=p_resource; }
+ void set_resource_clipboard(const Ref<Resource> &p_resource) { clipboard = p_resource; }
Ref<Resource> get_resource_clipboard() const { return clipboard; }
- void add_property_hint(const PropertyInfo& p_hint);
+ void add_property_hint(const PropertyInfo &p_hint);
- void set_favorite_dirs(const Vector<String>& p_favorite_dirs);
+ void set_favorite_dirs(const Vector<String> &p_favorite_dirs);
Vector<String> get_favorite_dirs() const;
- void set_recent_dirs(const Vector<String>& p_recent_dirs);
+ void set_recent_dirs(const Vector<String> &p_recent_dirs);
Vector<String> get_recent_dirs() const;
void load_favorites();
@@ -153,28 +158,27 @@ public:
bool save_text_editor_theme();
bool save_text_editor_theme_as(String p_file);
- void add_shortcut(const String& p_name,Ref<ShortCut>& p_shortcut);
- bool is_shortcut(const String&p_name,const InputEvent& p_event) const;
- Ref<ShortCut> get_shortcut(const String&p_name) const;
+ void add_shortcut(const String &p_name, Ref<ShortCut> &p_shortcut);
+ bool is_shortcut(const String &p_name, const InputEvent &p_event) const;
+ Ref<ShortCut> get_shortcut(const String &p_name) const;
void get_shortcut_list(List<String> *r_shortcuts);
void set_optimize_save(bool p_optimize);
- Variant get_project_metadata(const String& p_section, const String& p_key, Variant p_default);
- void set_project_metadata(const String& p_section, const String& p_key, Variant p_data);
+ Variant get_project_metadata(const String &p_section, const String &p_key, Variant p_default);
+ void set_project_metadata(const String &p_section, const String &p_key, Variant p_data);
EditorSettings();
~EditorSettings();
-
};
//not a macro any longer
-#define EDITOR_DEF(m_var,m_val) _EDITOR_DEF(m_var,Variant(m_val))
-Variant _EDITOR_DEF( const String& p_var, const Variant& p_default);
+#define EDITOR_DEF(m_var, m_val) _EDITOR_DEF(m_var, Variant(m_val))
+Variant _EDITOR_DEF(const String &p_var, const Variant &p_default);
-#define ED_IS_SHORTCUT(p_name,p_ev) (EditorSettings::get_singleton()->is_shortcut(p_name,p_ev))
-Ref<ShortCut> ED_SHORTCUT(const String& p_path,const String& p_name,uint32_t p_keycode=0);
-Ref<ShortCut> ED_GET_SHORTCUT(const String& p_path);
+#define ED_IS_SHORTCUT(p_name, p_ev) (EditorSettings::get_singleton()->is_shortcut(p_name, p_ev))
+Ref<ShortCut> ED_SHORTCUT(const String &p_path, const String &p_name, uint32_t p_keycode = 0);
+Ref<ShortCut> ED_GET_SHORTCUT(const String &p_path);
#endif // EDITOR_SETTINGS_H
diff --git a/editor/editor_sub_scene.cpp b/editor/editor_sub_scene.cpp
index 917560b540..01c08bb231 100644
--- a/editor/editor_sub_scene.cpp
+++ b/editor/editor_sub_scene.cpp
@@ -31,27 +31,25 @@
#include "scene/gui/margin_container.h"
#include "scene/resources/packed_scene.h"
-void EditorSubScene::_path_selected(const String& p_path) {
+void EditorSubScene::_path_selected(const String &p_path) {
path->set_text(p_path);
_path_changed(p_path);
-
}
-void EditorSubScene::_path_changed(const String& p_path) {
+void EditorSubScene::_path_changed(const String &p_path) {
tree->clear();
-
if (scene) {
memdelete(scene);
- scene=NULL;
+ scene = NULL;
}
- if (p_path=="")
+ if (p_path == "")
return;
- Ref<PackedScene> ps = ResourceLoader::load(p_path,"PackedScene");
+ Ref<PackedScene> ps = ResourceLoader::load(p_path, "PackedScene");
if (ps.is_null())
return;
@@ -60,10 +58,7 @@ void EditorSubScene::_path_changed(const String& p_path) {
if (!scene)
return;
- _fill_tree(scene,NULL);
-
-
-
+ _fill_tree(scene, NULL);
}
void EditorSubScene::_path_browse() {
@@ -71,45 +66,37 @@ void EditorSubScene::_path_browse() {
file_dialog->popup_centered_ratio();
}
-
void EditorSubScene::_notification(int p_what) {
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (!is_visible_in_tree()) {
-
-
}
}
}
-
-void EditorSubScene::_fill_tree(Node* p_node,TreeItem *p_parent) {
+void EditorSubScene::_fill_tree(Node *p_node, TreeItem *p_parent) {
TreeItem *it = tree->create_item(p_parent);
- it->set_metadata(0,p_node);
- it->set_text(0,p_node->get_name());
- it->set_editable(0,false);
- it->set_selectable(0,true);
- if (has_icon(p_node->get_class(),"EditorIcons")) {
- it->set_icon(0,get_icon(p_node->get_class(),"EditorIcons"));
-
+ it->set_metadata(0, p_node);
+ it->set_text(0, p_node->get_name());
+ it->set_editable(0, false);
+ it->set_selectable(0, true);
+ if (has_icon(p_node->get_class(), "EditorIcons")) {
+ it->set_icon(0, get_icon(p_node->get_class(), "EditorIcons"));
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
Node *c = p_node->get_child(i);
- if (c->get_owner()!=scene)
+ if (c->get_owner() != scene)
continue;
- _fill_tree(c,it);
+ _fill_tree(c, it);
}
-
}
-
void EditorSubScene::ok_pressed() {
-
TreeItem *s = tree->get_selected();
if (!s)
return;
@@ -119,29 +106,26 @@ void EditorSubScene::ok_pressed() {
emit_signal("subscene_selected");
hide();
clear();
-
-
}
+void EditorSubScene::_reown(Node *p_node, List<Node *> *p_to_reown) {
-void EditorSubScene::_reown(Node* p_node,List<Node*> *p_to_reown) {
-
- if (p_node==scene) {
+ if (p_node == scene) {
scene->set_filename("");
p_to_reown->push_back(p_node);
- } else if (p_node->get_owner()==scene){
+ } else if (p_node->get_owner() == scene) {
p_to_reown->push_back(p_node);
}
- for(int i=0;i<p_node->get_child_count();i++) {
- Node *c=p_node->get_child(i);
- _reown(c,p_to_reown);
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ Node *c = p_node->get_child(i);
+ _reown(c, p_to_reown);
}
}
-void EditorSubScene::move(Node* p_new_parent, Node* p_new_owner) {
+void EditorSubScene::move(Node *p_new_parent, Node *p_new_owner) {
if (!scene) {
return;
@@ -156,27 +140,24 @@ void EditorSubScene::move(Node* p_new_parent, Node* p_new_owner) {
return;
}
- List<Node*> to_reown;
- _reown(selnode,&to_reown);
+ List<Node *> to_reown;
+ _reown(selnode, &to_reown);
- if (selnode!=scene) {
+ if (selnode != scene) {
selnode->get_parent()->remove_child(selnode);
}
p_new_parent->add_child(selnode);
- for (List<Node*>::Element *E=to_reown.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = to_reown.front(); E; E = E->next()) {
E->get()->set_owner(p_new_owner);
}
- if (selnode!=scene) {
+ if (selnode != scene) {
memdelete(scene);
}
- scene=NULL;
-
+ scene = NULL;
//return selnode;
-
-
}
void EditorSubScene::clear() {
@@ -187,52 +168,49 @@ void EditorSubScene::clear() {
void EditorSubScene::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_path_selected"),&EditorSubScene::_path_selected);
- ClassDB::bind_method(D_METHOD("_path_changed"),&EditorSubScene::_path_changed);
- ClassDB::bind_method(D_METHOD("_path_browse"),&EditorSubScene::_path_browse);
- ADD_SIGNAL( MethodInfo("subscene_selected"));
-
+ ClassDB::bind_method(D_METHOD("_path_selected"), &EditorSubScene::_path_selected);
+ ClassDB::bind_method(D_METHOD("_path_changed"), &EditorSubScene::_path_changed);
+ ClassDB::bind_method(D_METHOD("_path_browse"), &EditorSubScene::_path_browse);
+ ADD_SIGNAL(MethodInfo("subscene_selected"));
}
-
EditorSubScene::EditorSubScene() {
- scene=NULL;
+ scene = NULL;
set_title(TTR("Select Node(s) to Import"));
set_hide_on_ok(false);
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
//set_child_rect(vb);
- HBoxContainer *hb = memnew( HBoxContainer );
- path = memnew( LineEdit );
- path->connect("text_entered",this,"_path_changed");
+ HBoxContainer *hb = memnew(HBoxContainer);
+ path = memnew(LineEdit);
+ path->connect("text_entered", this, "_path_changed");
hb->add_child(path);
path->set_h_size_flags(SIZE_EXPAND_FILL);
- Button *b = memnew( Button );
+ Button *b = memnew(Button);
b->set_text(" .. ");
hb->add_child(b);
- b->connect("pressed",this,"_path_browse");
- vb->add_margin_child(TTR("Scene Path:"),hb);
+ b->connect("pressed", this, "_path_browse");
+ vb->add_margin_child(TTR("Scene Path:"), hb);
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
- vb->add_margin_child(TTR("Import From Node:"),tree,true);
- tree->connect("item_activated",this,"_ok",make_binds(),CONNECT_DEFERRED);
+ vb->add_margin_child(TTR("Import From Node:"), tree, true);
+ tree->connect("item_activated", this, "_ok", make_binds(), CONNECT_DEFERRED);
- file_dialog = memnew( EditorFileDialog );
+ file_dialog = memnew(EditorFileDialog);
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("PackedScene",&extensions);
+ ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
- for(List<String>::Element *E = extensions.front();E;E=E->next() ) {
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
- file_dialog->add_filter("*."+E->get());
+ file_dialog->add_filter("*." + E->get());
}
file_dialog->set_mode(EditorFileDialog::MODE_OPEN_FILE);
add_child(file_dialog);
- file_dialog->connect("file_selected",this,"_path_selected");
-
+ file_dialog->connect("file_selected", this, "_path_selected");
}
diff --git a/editor/editor_sub_scene.h b/editor/editor_sub_scene.h
index 46cdceafa5..9739f49a45 100644
--- a/editor/editor_sub_scene.h
+++ b/editor/editor_sub_scene.h
@@ -29,14 +29,13 @@
#ifndef EDITOR_SUB_SCENE_H
#define EDITOR_SUB_SCENE_H
+#include "editor/editor_file_dialog.h"
#include "scene/gui/dialogs.h"
#include "scene/gui/tree.h"
-#include "editor/editor_file_dialog.h"
class EditorSubScene : public ConfirmationDialog {
- GDCLASS(EditorSubScene,ConfirmationDialog);
-
+ GDCLASS(EditorSubScene, ConfirmationDialog);
LineEdit *path;
Tree *tree;
@@ -44,24 +43,20 @@ class EditorSubScene : public ConfirmationDialog {
EditorFileDialog *file_dialog;
- void _fill_tree(Node* p_node,TreeItem *p_parent);
- void _reown(Node* p_node,List<Node*> *p_to_reown);
+ void _fill_tree(Node *p_node, TreeItem *p_parent);
+ void _reown(Node *p_node, List<Node *> *p_to_reown);
void ok_pressed();
-
protected:
-
-
void _notification(int p_what);
static void _bind_methods();
void _path_browse();
- void _path_selected(const String& p_path);
- void _path_changed(const String& p_path);
+ void _path_selected(const String &p_path);
+ void _path_changed(const String &p_path);
public:
-
- void move(Node* p_new_parent, Node* p_new_owner);
+ void move(Node *p_new_parent, Node *p_new_owner);
void clear();
EditorSubScene();
};
diff --git a/editor/editor_themes.cpp b/editor/editor_themes.cpp
index 7657996b81..adb4c8162e 100644
--- a/editor/editor_themes.cpp
+++ b/editor/editor_themes.cpp
@@ -28,47 +28,45 @@
/*************************************************************************/
#include "editor_themes.h"
-#include "editor_icons.h"
-#include "editor_fonts.h"
-#include "editor_settings.h"
#include "core/io/resource_loader.h"
+#include "editor_fonts.h"
+#include "editor_icons.h"
#include "editor_scale.h"
+#include "editor_settings.h"
-Ref<Theme> create_editor_theme()
-{
- Ref<Theme> theme = Ref<Theme>( memnew( Theme ) );
+Ref<Theme> create_editor_theme() {
+ Ref<Theme> theme = Ref<Theme>(memnew(Theme));
editor_register_fonts(theme);
editor_register_icons(theme);
- Ref<StyleBoxTexture> focus_sbt=memnew( StyleBoxTexture );
- focus_sbt->set_texture(theme->get_icon("EditorFocus","EditorIcons"));
- for(int i=0;i<4;i++) {
- focus_sbt->set_margin_size(Margin(i),16*EDSCALE);
- focus_sbt->set_default_margin(Margin(i),16*EDSCALE);
+ Ref<StyleBoxTexture> focus_sbt = memnew(StyleBoxTexture);
+ focus_sbt->set_texture(theme->get_icon("EditorFocus", "EditorIcons"));
+ for (int i = 0; i < 4; i++) {
+ focus_sbt->set_margin_size(Margin(i), 16 * EDSCALE);
+ focus_sbt->set_default_margin(Margin(i), 16 * EDSCALE);
}
focus_sbt->set_draw_center(false);
- theme->set_stylebox("EditorFocus","EditorStyles",focus_sbt);
- theme->set_color("prop_category","Editor",Color::hex(0x3f3a44ff));
- theme->set_color("prop_section","Editor",Color::hex(0x35313aff));
- theme->set_color("prop_subsection","Editor",Color::hex(0x312e37ff));
- theme->set_color("fg_selected","Editor",Color::html("ffbd8e8e"));
- theme->set_color("fg_error","Editor",Color::html("ffbd8e8e"));
+ theme->set_stylebox("EditorFocus", "EditorStyles", focus_sbt);
+ theme->set_color("prop_category", "Editor", Color::hex(0x3f3a44ff));
+ theme->set_color("prop_section", "Editor", Color::hex(0x35313aff));
+ theme->set_color("prop_subsection", "Editor", Color::hex(0x312e37ff));
+ theme->set_color("fg_selected", "Editor", Color::html("ffbd8e8e"));
+ theme->set_color("fg_error", "Editor", Color::html("ffbd8e8e"));
return theme;
}
-Ref<Theme> create_custom_theme()
-{
+Ref<Theme> create_custom_theme() {
Ref<Theme> theme;
String custom_theme = EditorSettings::get_singleton()->get("interface/custom_theme");
- if (custom_theme!="") {
+ if (custom_theme != "") {
theme = ResourceLoader::load(custom_theme);
}
String global_font = EditorSettings::get_singleton()->get("interface/custom_font");
- if (global_font!="") {
+ if (global_font != "") {
Ref<Font> fnt = ResourceLoader::load(global_font);
if (fnt.is_valid()) {
if (!theme.is_valid()) {
diff --git a/editor/file_type_cache.cpp b/editor/file_type_cache.cpp
index 891669db13..7db0182a37 100644
--- a/editor/file_type_cache.cpp
+++ b/editor/file_type_cache.cpp
@@ -31,32 +31,31 @@
#include "global_config.h"
#include "os/file_access.h"
-FileTypeCache* FileTypeCache::singleton=NULL;
+FileTypeCache *FileTypeCache::singleton = NULL;
-bool FileTypeCache::has_file(const String& p_path) const {
+bool FileTypeCache::has_file(const String &p_path) const {
GLOBAL_LOCK_FUNCTION
return file_type_map.has(p_path);
}
-String FileTypeCache::get_file_type(const String& p_path) const{
+String FileTypeCache::get_file_type(const String &p_path) const {
GLOBAL_LOCK_FUNCTION
- ERR_FAIL_COND_V(!file_type_map.has(p_path),"");
+ ERR_FAIL_COND_V(!file_type_map.has(p_path), "");
return file_type_map[p_path];
-
}
-void FileTypeCache::set_file_type(const String& p_path,const String& p_type){
+void FileTypeCache::set_file_type(const String &p_path, const String &p_type) {
GLOBAL_LOCK_FUNCTION
- file_type_map[p_path]=p_type;
+ file_type_map[p_path] = p_type;
}
void FileTypeCache::load() {
GLOBAL_LOCK_FUNCTION
- String project=GlobalConfig::get_singleton()->get_resource_path();
- FileAccess *f =FileAccess::open(project+"/file_type_cache.cch",FileAccess::READ);
+ String project = GlobalConfig::get_singleton()->get_resource_path();
+ FileAccess *f = FileAccess::open(project + "/file_type_cache.cch", FileAccess::READ);
if (!f) {
@@ -65,44 +64,42 @@ void FileTypeCache::load() {
}
file_type_map.clear();
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
- String path=f->get_line();
+ String path = f->get_line();
if (f->eof_reached())
break;
- String type=f->get_line();
- set_file_type(path,type);
+ String type = f->get_line();
+ set_file_type(path, type);
}
memdelete(f);
-
}
void FileTypeCache::save() {
GLOBAL_LOCK_FUNCTION
- String project=GlobalConfig::get_singleton()->get_resource_path();
- FileAccess *f =FileAccess::open(project+"/file_type_cache.cch",FileAccess::WRITE);
+ String project = GlobalConfig::get_singleton()->get_resource_path();
+ FileAccess *f = FileAccess::open(project + "/file_type_cache.cch", FileAccess::WRITE);
if (!f) {
ERR_EXPLAIN(TTR("Can't open file_type_cache.cch for writing, not saving file type cache!"));
ERR_FAIL();
}
- const String *K=NULL;
+ const String *K = NULL;
- while((K=file_type_map.next(K))) {
+ while ((K = file_type_map.next(K))) {
f->store_line(*K);
f->store_line(file_type_map[*K]);
}
memdelete(f);
-
}
FileTypeCache::FileTypeCache() {
ERR_FAIL_COND(singleton);
- singleton=this;
+ singleton = this;
}
diff --git a/editor/file_type_cache.h b/editor/file_type_cache.h
index 25755f168c..fa2c7b46af 100644
--- a/editor/file_type_cache.h
+++ b/editor/file_type_cache.h
@@ -33,19 +33,18 @@
class FileTypeCache : Object {
- GDCLASS(FileTypeCache,Object);
+ GDCLASS(FileTypeCache, Object);
- HashMap<String,String> file_type_map;
+ HashMap<String, String> file_type_map;
+ static FileTypeCache *singleton;
- static FileTypeCache* singleton;
public:
+ static FileTypeCache *get_singleton() { return singleton; }
- static FileTypeCache* get_singleton() { return singleton; }
-
- bool has_file(const String& p_path) const;
- String get_file_type(const String& p_path) const;
- void set_file_type(const String& p_path,const String& p_type);
+ bool has_file(const String &p_path) const;
+ String get_file_type(const String &p_path) const;
+ void set_file_type(const String &p_path, const String &p_type);
void load();
void save();
@@ -53,6 +52,4 @@ public:
FileTypeCache();
};
-
-
#endif // FILE_TYPE_CACHE_H
diff --git a/editor/fileserver/editor_file_server.cpp b/editor/fileserver/editor_file_server.cpp
index 2e5dbf6248..20a4809e36 100644
--- a/editor/fileserver/editor_file_server.cpp
+++ b/editor/fileserver/editor_file_server.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "editor_file_server.h"
+#include "../editor_settings.h"
#include "io/marshalls.h"
#include "io/marshalls.h"
-#include "../editor_settings.h"
//#define DEBUG_PRINT(m_p) print_line(m_p)
-#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n",m_what,OS::get_singleton()->get_ticks_usec());
+#define DEBUG_TIME(m_what) printf("MS: %s - %lli\n", m_what, OS::get_singleton()->get_ticks_usec());
//#define DEBUG_TIME(m_what)
@@ -43,59 +43,55 @@ void EditorFileServer::_close_client(ClientData *cd) {
cd->efs->wait_mutex->lock();
cd->efs->to_wait.insert(cd->thread);
cd->efs->wait_mutex->unlock();
- while(cd->files.size()) {
+ while (cd->files.size()) {
memdelete(cd->files.front()->get());
cd->files.erase(cd->files.front());
}
memdelete(cd);
-
}
-void EditorFileServer::_subthread_start(void*s) {
-
- ClientData *cd = (ClientData*)s;
+void EditorFileServer::_subthread_start(void *s) {
+ ClientData *cd = (ClientData *)s;
cd->connection->set_nodelay(true);
uint8_t buf4[8];
- Error err = cd->connection->get_data(buf4,4);
- if (err!=OK) {
+ Error err = cd->connection->get_data(buf4, 4);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
+ int passlen = decode_uint32(buf4);
-
- int passlen=decode_uint32(buf4);
-
- if (passlen>512) {
+ if (passlen > 512) {
_close_client(cd);
- ERR_FAIL_COND(passlen>512);
- } else if (passlen>0) {
+ ERR_FAIL_COND(passlen > 512);
+ } else if (passlen > 0) {
Vector<char> passutf8;
- passutf8.resize(passlen+1);
- err = cd->connection->get_data((uint8_t*)passutf8.ptr(),passlen);
- if (err!=OK) {
+ passutf8.resize(passlen + 1);
+ err = cd->connection->get_data((uint8_t *)passutf8.ptr(), passlen);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- passutf8[passlen]=0;
+ passutf8[passlen] = 0;
String s;
s.parse_utf8(passutf8.ptr());
- if (s!=cd->efs->password) {
- encode_uint32(ERR_INVALID_DATA,buf4);
- cd->connection->put_data(buf4,4);
+ if (s != cd->efs->password) {
+ encode_uint32(ERR_INVALID_DATA, buf4);
+ cd->connection->put_data(buf4, 4);
OS::get_singleton()->delay_usec(1000000);
_close_client(cd);
ERR_PRINT("CLIENT PASSWORD MISMATCH");
ERR_FAIL();
}
} else {
- if (cd->efs->password!="") {
- encode_uint32(ERR_INVALID_DATA,buf4);
- cd->connection->put_data(buf4,4);
+ if (cd->efs->password != "") {
+ encode_uint32(ERR_INVALID_DATA, buf4);
+ cd->connection->put_data(buf4, 4);
OS::get_singleton()->delay_usec(1000000);
_close_client(cd);
ERR_PRINT("CLIENT PASSWORD MISMATCH (should be empty!)");
@@ -103,163 +99,161 @@ void EditorFileServer::_subthread_start(void*s) {
}
}
- encode_uint32(OK,buf4);
- cd->connection->put_data(buf4,4);
+ encode_uint32(OK, buf4);
+ cd->connection->put_data(buf4, 4);
- while(!cd->quit) {
+ while (!cd->quit) {
//wait for ID
- err = cd->connection->get_data(buf4,4);
+ err = cd->connection->get_data(buf4, 4);
//#define DEBUG_PRINT(m_p) print_line(m_p)
DEBUG_TIME("get_data")
- if (err!=OK) {
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- int id=decode_uint32(buf4);
+ int id = decode_uint32(buf4);
//wait for command
- err = cd->connection->get_data(buf4,4);
- if (err!=OK) {
+ err = cd->connection->get_data(buf4, 4);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- int cmd=decode_uint32(buf4);
+ int cmd = decode_uint32(buf4);
- switch(cmd) {
+ switch (cmd) {
case FileAccessNetwork::COMMAND_FILE_EXISTS:
case FileAccessNetwork::COMMAND_GET_MODTIME:
case FileAccessNetwork::COMMAND_OPEN_FILE: {
DEBUG_TIME("open_file")
- err = cd->connection->get_data(buf4,4);
- if (err!=OK) {
+ err = cd->connection->get_data(buf4, 4);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- int namelen=decode_uint32(buf4);
+ int namelen = decode_uint32(buf4);
Vector<char> fileutf8;
- fileutf8.resize(namelen+1);
- err = cd->connection->get_data((uint8_t*)fileutf8.ptr(),namelen);
- if (err!=OK) {
+ fileutf8.resize(namelen + 1);
+ err = cd->connection->get_data((uint8_t *)fileutf8.ptr(), namelen);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- fileutf8[namelen]=0;
+ fileutf8[namelen] = 0;
String s;
s.parse_utf8(fileutf8.ptr());
- if (cmd==FileAccessNetwork::COMMAND_FILE_EXISTS) {
- print_line("FILE EXISTS: "+s);
+ if (cmd == FileAccessNetwork::COMMAND_FILE_EXISTS) {
+ print_line("FILE EXISTS: " + s);
}
- if (cmd==FileAccessNetwork::COMMAND_GET_MODTIME) {
- print_line("MOD TIME: "+s);
+ if (cmd == FileAccessNetwork::COMMAND_GET_MODTIME) {
+ print_line("MOD TIME: " + s);
}
- if (cmd==FileAccessNetwork::COMMAND_OPEN_FILE) {
- print_line("OPEN: "+s);
+ if (cmd == FileAccessNetwork::COMMAND_OPEN_FILE) {
+ print_line("OPEN: " + s);
}
- if ( !s.begins_with("res://")) {
+ if (!s.begins_with("res://")) {
_close_client(cd);
ERR_FAIL_COND(!s.begins_with("res://"));
}
ERR_CONTINUE(cd->files.has(id));
- if (cmd==FileAccessNetwork::COMMAND_FILE_EXISTS) {
+ if (cmd == FileAccessNetwork::COMMAND_FILE_EXISTS) {
- encode_uint32(id,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccessNetwork::RESPONSE_FILE_EXISTS,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccess::exists(s),buf4);
- cd->connection->put_data(buf4,4);
+ encode_uint32(id, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccessNetwork::RESPONSE_FILE_EXISTS, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccess::exists(s), buf4);
+ cd->connection->put_data(buf4, 4);
DEBUG_TIME("open_file_end")
break;
}
- if (cmd==FileAccessNetwork::COMMAND_GET_MODTIME) {
+ if (cmd == FileAccessNetwork::COMMAND_GET_MODTIME) {
- encode_uint32(id,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccessNetwork::RESPONSE_GET_MODTIME,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint64(FileAccess::get_modified_time(s),buf4);
- cd->connection->put_data(buf4,8);
+ encode_uint32(id, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccessNetwork::RESPONSE_GET_MODTIME, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint64(FileAccess::get_modified_time(s), buf4);
+ cd->connection->put_data(buf4, 8);
DEBUG_TIME("open_file_end")
break;
}
- FileAccess *fa = FileAccess::open(s,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(s, FileAccess::READ);
if (!fa) {
//not found, continue
- encode_uint32(id,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccessNetwork::RESPONSE_OPEN,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(ERR_FILE_NOT_FOUND,buf4);
- cd->connection->put_data(buf4,4);
+ encode_uint32(id, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccessNetwork::RESPONSE_OPEN, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(ERR_FILE_NOT_FOUND, buf4);
+ cd->connection->put_data(buf4, 4);
DEBUG_TIME("open_file_end")
break;
-
}
- encode_uint32(id,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccessNetwork::RESPONSE_OPEN,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(OK,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint64(fa->get_len(),buf4);
- cd->connection->put_data(buf4,8);
+ encode_uint32(id, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccessNetwork::RESPONSE_OPEN, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(OK, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint64(fa->get_len(), buf4);
+ cd->connection->put_data(buf4, 8);
- cd->files[id]=fa;
+ cd->files[id] = fa;
DEBUG_TIME("open_file_end")
} break;
case FileAccessNetwork::COMMAND_READ_BLOCK: {
- err = cd->connection->get_data(buf4,8);
- if (err!=OK) {
+ err = cd->connection->get_data(buf4, 8);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
ERR_CONTINUE(!cd->files.has(id));
uint64_t offset = decode_uint64(buf4);
- err = cd->connection->get_data(buf4,4);
- if (err!=OK) {
+ err = cd->connection->get_data(buf4, 4);
+ if (err != OK) {
_close_client(cd);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
- int blocklen=decode_uint32(buf4);
- ERR_CONTINUE(blocklen > (16*1024*1024));
+ int blocklen = decode_uint32(buf4);
+ ERR_CONTINUE(blocklen > (16 * 1024 * 1024));
cd->files[id]->seek(offset);
Vector<uint8_t> buf;
buf.resize(blocklen);
- int read = cd->files[id]->get_buffer(buf.ptr(),blocklen);
- ERR_CONTINUE(read<0);
+ int read = cd->files[id]->get_buffer(buf.ptr(), blocklen);
+ ERR_CONTINUE(read < 0);
- print_line("GET BLOCK - offset: "+itos(offset)+", blocklen: "+itos(blocklen));
+ print_line("GET BLOCK - offset: " + itos(offset) + ", blocklen: " + itos(blocklen));
//not found, continue
- encode_uint32(id,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint32(FileAccessNetwork::RESPONSE_DATA,buf4);
- cd->connection->put_data(buf4,4);
- encode_uint64(offset,buf4);
- cd->connection->put_data(buf4,8);
- encode_uint32(read,buf4);
- cd->connection->put_data(buf4,4);
- cd->connection->put_data(buf.ptr(),read);
-
+ encode_uint32(id, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint32(FileAccessNetwork::RESPONSE_DATA, buf4);
+ cd->connection->put_data(buf4, 4);
+ encode_uint64(offset, buf4);
+ cd->connection->put_data(buf4, 8);
+ encode_uint32(read, buf4);
+ cd->connection->put_data(buf4, 4);
+ cd->connection->put_data(buf.ptr(), read);
} break;
case FileAccessNetwork::COMMAND_CLOSE: {
@@ -273,31 +267,30 @@ void EditorFileServer::_subthread_start(void*s) {
}
_close_client(cd);
-
}
-void EditorFileServer::_thread_start(void*s) {
+void EditorFileServer::_thread_start(void *s) {
- EditorFileServer *self=(EditorFileServer*)s;
- while(!self->quit) {
+ EditorFileServer *self = (EditorFileServer *)s;
+ while (!self->quit) {
- if (self->cmd==CMD_ACTIVATE) {
+ if (self->cmd == CMD_ACTIVATE) {
self->server->listen(self->port);
- self->active=true;
- self->cmd=CMD_NONE;
- } else if (self->cmd==CMD_STOP) {
+ self->active = true;
+ self->cmd = CMD_NONE;
+ } else if (self->cmd == CMD_STOP) {
self->server->stop();
- self->active=false;
- self->cmd=CMD_NONE;
+ self->active = false;
+ self->cmd = CMD_NONE;
}
if (self->active) {
if (self->server->is_connection_available()) {
- ClientData *cd = memnew( ClientData);
- cd->connection=self->server->take_connection();
- cd->efs=self;
- cd->quit=false;
- cd->thread=Thread::create(_subthread_start,cd);
+ ClientData *cd = memnew(ClientData);
+ cd->connection = self->server->take_connection();
+ cd->efs = self;
+ cd->quit = false;
+ cd->thread = Thread::create(_subthread_start, cd);
}
}
@@ -314,18 +307,14 @@ void EditorFileServer::_thread_start(void*s) {
OS::get_singleton()->delay_usec(100000);
}
-
-
}
void EditorFileServer::start() {
-
stop();
- port=EDITOR_DEF("filesystem/file_server/port",6010);
- password=EDITOR_DEF("filesystem/file_server/password","");
- cmd=CMD_ACTIVATE;
-
+ port = EDITOR_DEF("filesystem/file_server/port", 6010);
+ password = EDITOR_DEF("filesystem/file_server/password", "");
+ cmd = CMD_ACTIVATE;
}
bool EditorFileServer::is_active() const {
@@ -333,28 +322,27 @@ bool EditorFileServer::is_active() const {
return active;
}
-void EditorFileServer::stop(){
+void EditorFileServer::stop() {
- cmd=CMD_STOP;
+ cmd = CMD_STOP;
}
EditorFileServer::EditorFileServer() {
server = TCP_Server::create_ref();
wait_mutex = Mutex::create();
- quit=false;
- active=false;
- cmd=CMD_NONE;
- thread=Thread::create(_thread_start,this);
+ quit = false;
+ active = false;
+ cmd = CMD_NONE;
+ thread = Thread::create(_thread_start, this);
- EDITOR_DEF("filesystem/file_server/port",6010);
- EDITOR_DEF("filesystem/file_server/password","");
+ EDITOR_DEF("filesystem/file_server/port", 6010);
+ EDITOR_DEF("filesystem/file_server/password", "");
}
EditorFileServer::~EditorFileServer() {
-
- quit=true;
+ quit = true;
Thread::wait_to_finish(thread);
memdelete(thread);
memdelete(wait_mutex);
diff --git a/editor/fileserver/editor_file_server.h b/editor/fileserver/editor_file_server.h
index 31f8ae84b8..cf97f685f7 100644
--- a/editor/fileserver/editor_file_server.h
+++ b/editor/fileserver/editor_file_server.h
@@ -29,15 +29,15 @@
#ifndef EDITOR_FILE_SERVER_H
#define EDITOR_FILE_SERVER_H
+#include "io/file_access_network.h"
+#include "io/packet_peer.h"
+#include "io/tcp_server.h"
#include "object.h"
#include "os/thread.h"
-#include "io/tcp_server.h"
-#include "io/packet_peer.h"
-#include "io/file_access_network.h"
class EditorFileServer : public Object {
- GDCLASS(EditorFileServer,Object);
+ GDCLASS(EditorFileServer, Object);
enum Command {
CMD_NONE,
@@ -45,26 +45,24 @@ class EditorFileServer : public Object {
CMD_STOP,
};
-
struct ClientData {
Thread *thread;
Ref<StreamPeerTCP> connection;
- Map<int,FileAccess*> files;
+ Map<int, FileAccess *> files;
EditorFileServer *efs;
bool quit;
-
};
Ref<TCP_Server> server;
- Set<Thread*> to_wait;
+ Set<Thread *> to_wait;
static void _close_client(ClientData *cd);
- static void _subthread_start(void*s);
+ static void _subthread_start(void *s);
Mutex *wait_mutex;
Thread *thread;
- static void _thread_start(void*);
+ static void _thread_start(void *);
bool quit;
Command cmd;
@@ -72,9 +70,7 @@ class EditorFileServer : public Object {
int port;
bool active;
-
public:
-
void start();
void stop();
diff --git a/editor/filesystem_dock.cpp b/editor/filesystem_dock.cpp
index bce0e9148a..fe1f984f39 100644
--- a/editor/filesystem_dock.cpp
+++ b/editor/filesystem_dock.cpp
@@ -28,101 +28,97 @@
/*************************************************************************/
#include "filesystem_dock.h"
-#include "os/dir_access.h"
-#include "os/file_access.h"
+#include "editor_node.h"
+#include "editor_settings.h"
#include "global_config.h"
#include "io/resource_loader.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
#include "os/os.h"
-#include "editor_node.h"
-#include "editor_settings.h"
#include "scene/main/viewport.h"
-bool FileSystemDock::_create_tree(TreeItem *p_parent,EditorFileSystemDirectory *p_dir) {
+bool FileSystemDock::_create_tree(TreeItem *p_parent, EditorFileSystemDirectory *p_dir) {
TreeItem *item = tree->create_item(p_parent);
- String dname=p_dir->get_name();
- if (dname=="")
- dname="res://";
+ String dname = p_dir->get_name();
+ if (dname == "")
+ dname = "res://";
else {
// collapse every tree item but the root folder
item->set_collapsed(true);
}
- item->set_text(0,dname);
- item->set_icon(0,get_icon("Folder","EditorIcons"));
- item->set_selectable(0,true);
+ item->set_text(0, dname);
+ item->set_icon(0, get_icon("Folder", "EditorIcons"));
+ item->set_selectable(0, true);
String lpath = p_dir->get_path();
- if (lpath!="res://" && lpath.ends_with("/")) {
- lpath=lpath.substr(0,lpath.length()-1);
+ if (lpath != "res://" && lpath.ends_with("/")) {
+ lpath = lpath.substr(0, lpath.length() - 1);
}
- item->set_metadata(0,lpath);
- if (lpath==path) {
+ item->set_metadata(0, lpath);
+ if (lpath == path) {
item->select(0);
}
- for(int i=0;i<p_dir->get_subdir_count();i++)
- _create_tree(item,p_dir->get_subdir(i));
+ for (int i = 0; i < p_dir->get_subdir_count(); i++)
+ _create_tree(item, p_dir->get_subdir(i));
return true;
}
-
void FileSystemDock::_update_tree() {
tree->clear();
- updating_tree=true;
+ updating_tree = true;
TreeItem *root = tree->create_item();
TreeItem *favorites = tree->create_item(root);
- favorites->set_icon(0, get_icon("Favorites","EditorIcons") );
- favorites->set_text(0,TTR("Favorites:"));
- favorites->set_selectable(0,false);
- Vector<String> faves = EditorSettings::get_singleton()->get_favorite_dirs();
- for(int i=0;i<faves.size();i++) {
+ favorites->set_icon(0, get_icon("Favorites", "EditorIcons"));
+ favorites->set_text(0, TTR("Favorites:"));
+ favorites->set_selectable(0, false);
+ Vector<String> faves = EditorSettings::get_singleton()->get_favorite_dirs();
+ for (int i = 0; i < faves.size(); i++) {
if (!faves[i].begins_with("res://"))
continue;
TreeItem *ti = tree->create_item(favorites);
String fv = faves[i];
- if (fv=="res://")
- ti->set_text(0,"/");
+ if (fv == "res://")
+ ti->set_text(0, "/");
else
- ti->set_text(0,faves[i].get_file());
- ti->set_icon(0,get_icon("Folder","EditorIcons"));
- ti->set_selectable(0,true);
- ti->set_metadata(0,faves[i]);
+ ti->set_text(0, faves[i].get_file());
+ ti->set_icon(0, get_icon("Folder", "EditorIcons"));
+ ti->set_selectable(0, true);
+ ti->set_metadata(0, faves[i]);
}
- _create_tree(root,EditorFileSystem::get_singleton()->get_filesystem());
- updating_tree=false;
-
+ _create_tree(root, EditorFileSystem::get_singleton()->get_filesystem());
+ updating_tree = false;
}
-
void FileSystemDock::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_RESIZED: {
+ bool new_mode = get_size().height < get_viewport_rect().size.height * 3 / 4;
- bool new_mode = get_size().height < get_viewport_rect().size.height*3/4;
-
- if (new_mode != split_mode ) {
+ if (new_mode != split_mode) {
- split_mode=new_mode;
+ split_mode = new_mode;
//print_line("SPLIT MODE? "+itos(split_mode));
if (split_mode) {
file_list_vb->hide();
- tree->set_custom_minimum_size(Size2(0,0));
+ tree->set_custom_minimum_size(Size2(0, 0));
tree->set_v_size_flags(SIZE_EXPAND_FILL);
button_back->show();
} else {
tree->show();
file_list_vb->show();
- tree->set_custom_minimum_size(Size2(0,200)*EDSCALE);
+ tree->set_custom_minimum_size(Size2(0, 200) * EDSCALE);
tree->set_v_size_flags(SIZE_FILL);
button_back->hide();
if (!EditorFileSystem::get_singleton()->is_scanning()) {
@@ -131,42 +127,40 @@ void FileSystemDock::_notification(int p_what) {
}
}
-
} break;
case NOTIFICATION_ENTER_TREE: {
if (initialized)
return;
- initialized=true;
+ initialized = true;
- EditorFileSystem::get_singleton()->connect("filesystem_changed",this,"_fs_changed");
- EditorResourcePreview::get_singleton()->connect("preview_invalidated",this,"_preview_invalidated");
+ EditorFileSystem::get_singleton()->connect("filesystem_changed", this, "_fs_changed");
+ EditorResourcePreview::get_singleton()->connect("preview_invalidated", this, "_preview_invalidated");
- button_reload->set_icon( get_icon("Reload","EditorIcons"));
- button_favorite->set_icon( get_icon("Favorites","EditorIcons"));
+ button_reload->set_icon(get_icon("Reload", "EditorIcons"));
+ button_favorite->set_icon(get_icon("Favorites", "EditorIcons"));
//button_instance->set_icon( get_icon("Add","EditorIcons"));
//button_open->set_icon( get_icon("Folder","EditorIcons"));
- button_back->set_icon( get_icon("Filesystem","EditorIcons"));
+ button_back->set_icon(get_icon("Filesystem", "EditorIcons"));
if (display_mode == DISPLAY_THUMBNAILS) {
- button_display_mode->set_icon(get_icon("FileList","EditorIcons"));
+ button_display_mode->set_icon(get_icon("FileList", "EditorIcons"));
} else {
- button_display_mode->set_icon(get_icon("FileThumbnail","EditorIcons"));
+ button_display_mode->set_icon(get_icon("FileThumbnail", "EditorIcons"));
}
- button_display_mode->connect("pressed",this,"_change_file_display");
+ button_display_mode->connect("pressed", this, "_change_file_display");
//file_options->set_icon( get_icon("Tools","EditorIcons"));
- files->connect("item_activated",this,"_select_file");
- button_hist_next->connect("pressed",this,"_fw_history");
- button_hist_prev->connect("pressed",this,"_bw_history");
- search_icon->set_texture( get_icon("Zoom","EditorIcons"));
-
- button_hist_next->set_icon( get_icon("Forward","EditorIcons"));
- button_hist_prev->set_icon( get_icon("Back","EditorIcons"));
- file_options->connect("id_pressed",this,"_file_option");
- folder_options->connect("id_pressed",this,"_folder_option");
-
-
- button_back->connect("pressed",this,"_go_to_tree",varray(),CONNECT_DEFERRED);
- current_path->connect("text_entered",this,"_go_to_dir");
+ files->connect("item_activated", this, "_select_file");
+ button_hist_next->connect("pressed", this, "_fw_history");
+ button_hist_prev->connect("pressed", this, "_bw_history");
+ search_icon->set_texture(get_icon("Zoom", "EditorIcons"));
+
+ button_hist_next->set_icon(get_icon("Forward", "EditorIcons"));
+ button_hist_prev->set_icon(get_icon("Back", "EditorIcons"));
+ file_options->connect("id_pressed", this, "_file_option");
+ folder_options->connect("id_pressed", this, "_folder_option");
+
+ button_back->connect("pressed", this, "_go_to_tree", varray(), CONNECT_DEFERRED);
+ current_path->connect("text_entered", this, "_go_to_dir");
_update_tree(); //maybe it finished already
if (EditorFileSystem::get_singleton()->is_scanning()) {
@@ -176,7 +170,7 @@ void FileSystemDock::_notification(int p_what) {
} break;
case NOTIFICATION_PROCESS: {
if (EditorFileSystem::get_singleton()->is_scanning()) {
- scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress()*100);
+ scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100);
}
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -185,16 +179,15 @@ void FileSystemDock::_notification(int p_what) {
case NOTIFICATION_DRAG_BEGIN: {
Dictionary dd = get_viewport()->gui_get_drag_data();
- if (tree->is_visible_in_tree() && dd.has("type") ) {
- if ( (String(dd["type"])=="files") || (String(dd["type"])=="files_and_dirs") || (String(dd["type"])=="resource")) {
+ if (tree->is_visible_in_tree() && dd.has("type")) {
+ if ((String(dd["type"]) == "files") || (String(dd["type"]) == "files_and_dirs") || (String(dd["type"]) == "resource")) {
tree->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM);
}
- if ( (String(dd["type"])=="favorite") ) {
+ if ((String(dd["type"]) == "favorite")) {
tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN);
}
}
-
} break;
case NOTIFICATION_DRAG_END: {
@@ -212,65 +205,57 @@ void FileSystemDock::_notification(int p_what) {
}
} break;
}
-
}
-
-
-
void FileSystemDock::_dir_selected() {
TreeItem *ti = tree->get_selected();
if (!ti)
return;
String dir = ti->get_metadata(0);
- bool found=false;
+ bool found = false;
Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs();
- for(int i=0;i<favorites.size();i++) {
+ for (int i = 0; i < favorites.size(); i++) {
- if (favorites[i]==dir) {
- found=true;
+ if (favorites[i] == dir) {
+ found = true;
break;
}
}
-
button_favorite->set_pressed(found);
if (!split_mode) {
_open_pressed(); //go directly to dir
}
-
}
-
void FileSystemDock::_favorites_pressed() {
TreeItem *sel = tree->get_selected();
if (!sel)
- return ;
+ return;
String dir = sel->get_metadata(0);
int idx = -1;
Vector<String> favorites = EditorSettings::get_singleton()->get_favorite_dirs();
- for(int i=0;i<favorites.size();i++) {
+ for (int i = 0; i < favorites.size(); i++) {
- if (favorites[i]==dir) {
- idx=i;
+ if (favorites[i] == dir) {
+ idx = i;
break;
}
}
- if (button_favorite->is_pressed() && idx==-1) {
+ if (button_favorite->is_pressed() && idx == -1) {
favorites.push_back(dir);
EditorSettings::get_singleton()->set_favorite_dirs(favorites);
_update_tree();
- } else if (!button_favorite->is_pressed() && idx!=-1) {
+ } else if (!button_favorite->is_pressed() && idx != -1) {
favorites.remove(idx);
EditorSettings::get_singleton()->set_favorite_dirs(favorites);
_update_tree();
}
-
}
String FileSystemDock::get_selected_path() const {
@@ -279,7 +264,7 @@ String FileSystemDock::get_selected_path() const {
if (!sel)
return "";
String path = sel->get_metadata(0);
- return "res://"+path;
+ return "res://" + path;
}
String FileSystemDock::get_current_path() const {
@@ -287,22 +272,22 @@ String FileSystemDock::get_current_path() const {
return path;
}
-void FileSystemDock::navigate_to_path(const String& p_path) {
+void FileSystemDock::navigate_to_path(const String &p_path) {
// If the path is a file, do not only go to the directory in the tree, also select the file in the file list.
- String dir_path="";
- String file_name="";
- DirAccess* dirAccess=DirAccess::open("res://");
+ String dir_path = "";
+ String file_name = "";
+ DirAccess *dirAccess = DirAccess::open("res://");
if (dirAccess->file_exists(p_path)) {
- dir_path=p_path.get_base_dir();
- file_name=p_path.get_file();
+ dir_path = p_path.get_base_dir();
+ file_name = p_path.get_file();
} else if (dirAccess->dir_exists(p_path)) {
- dir_path=p_path;
+ dir_path = p_path;
} else {
ERR_EXPLAIN(TTR("Cannot navigate to '" + p_path + "' as it has not been found in the file system!"));
ERR_FAIL();
}
- path=dir_path;
+ path = dir_path;
_update_tree();
tree->ensure_cursor_is_visible();
@@ -310,9 +295,9 @@ void FileSystemDock::navigate_to_path(const String& p_path) {
_open_pressed(); // Seems to be the only way to get into the file view. This also pushes to history.
// Focus the given file.
- for (int i=0; i<files->get_item_count(); i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (files->get_item_text(i) == file_name) {
- files->select(i,true);
+ files->select(i, true);
files->ensure_current_is_visible();
break;
}
@@ -320,42 +305,40 @@ void FileSystemDock::navigate_to_path(const String& p_path) {
}
}
-void FileSystemDock::_thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata) {
+void FileSystemDock::_thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata) {
- bool valid=false;
+ bool valid = false;
if (search_box->is_visible()) {
- valid=true;
+ valid = true;
} else {
- valid=(path==p_path.get_base_dir());
+ valid = (path == p_path.get_base_dir());
}
if (p_preview.is_valid() && valid) {
- Array uarr=p_udata;
- int idx=uarr[0];
- String file=uarr[1];
- if (idx>=files->get_item_count())
+ Array uarr = p_udata;
+ int idx = uarr[0];
+ String file = uarr[1];
+ if (idx >= files->get_item_count())
return;
- if (files->get_item_text(idx)!=file)
+ if (files->get_item_text(idx) != file)
return;
String fpath = files->get_item_metadata(idx);
- if (fpath!=p_path)
+ if (fpath != p_path)
return;
- files->set_item_icon(idx,p_preview);
-
+ files->set_item_icon(idx, p_preview);
}
-
}
void FileSystemDock::_change_file_display() {
if (button_display_mode->is_pressed()) {
display_mode = DISPLAY_LIST;
- button_display_mode->set_icon( get_icon("FileThumbnail","EditorIcons"));
+ button_display_mode->set_icon(get_icon("FileThumbnail", "EditorIcons"));
} else {
display_mode = DISPLAY_THUMBNAILS;
- button_display_mode->set_icon( get_icon("FileList","EditorIcons"));
+ button_display_mode->set_icon(get_icon("FileList", "EditorIcons"));
}
EditorSettings::get_singleton()->set("docks/filesystem/display_mode", display_mode);
@@ -363,32 +346,30 @@ void FileSystemDock::_change_file_display() {
_update_files(true);
}
-void FileSystemDock::_search(EditorFileSystemDirectory *p_path,List<FileInfo>* matches,int p_max_items) {
+void FileSystemDock::_search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items) {
- if (matches->size()>p_max_items)
+ if (matches->size() > p_max_items)
return;
- for(int i=0;i<p_path->get_subdir_count();i++) {
- _search(p_path->get_subdir(i),matches,p_max_items);
-
+ for (int i = 0; i < p_path->get_subdir_count(); i++) {
+ _search(p_path->get_subdir(i), matches, p_max_items);
}
String match = search_box->get_text();
- for(int i=0;i<p_path->get_file_count();i++) {
+ for (int i = 0; i < p_path->get_file_count(); i++) {
String file = p_path->get_file(i);
- if (file.find(match)!=-1) {
+ if (file.find(match) != -1) {
FileInfo fi;
- fi.name=file;
- fi.type=p_path->get_file_type(i);
- fi.path=p_path->get_file_path(i);
- fi.import_status=0;
-
+ fi.name = file;
+ fi.type = p_path->get_file_type(i);
+ fi.path = p_path->get_file_path(i);
+ fi.import_status = 0;
matches->push_back(fi);
- if (matches->size()>p_max_items)
+ if (matches->size() > p_max_items)
return;
}
}
@@ -400,7 +381,7 @@ void FileSystemDock::_update_files(bool p_keep_selection) {
if (p_keep_selection) {
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (files->is_selected(i))
cselection.insert(files->get_item_text(i));
@@ -411,48 +392,47 @@ void FileSystemDock::_update_files(bool p_keep_selection) {
current_path->set_text(path);
-
EditorFileSystemDirectory *efd = EditorFileSystem::get_singleton()->get_filesystem_path(path);
if (!efd)
return;
int thumbnail_size = EditorSettings::get_singleton()->get("docks/filesystem/thumbnail_size");
- thumbnail_size*=EDSCALE;
+ thumbnail_size *= EDSCALE;
Ref<Texture> folder_thumbnail;
Ref<Texture> file_thumbnail;
bool use_thumbnails = (display_mode == DISPLAY_THUMBNAILS);
- bool use_folders = search_box->get_text().length()==0 && split_mode;
+ bool use_folders = search_box->get_text().length() == 0 && split_mode;
if (use_thumbnails) { //thumbnails
files->set_max_columns(0);
files->set_icon_mode(ItemList::ICON_MODE_TOP);
- files->set_fixed_column_width(thumbnail_size*3/2);
+ files->set_fixed_column_width(thumbnail_size * 3 / 2);
files->set_max_text_lines(2);
- files->set_fixed_icon_size(Size2(thumbnail_size,thumbnail_size));
+ files->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size));
- if (!has_icon("ResizedFolder","EditorIcons")) {
- Ref<ImageTexture> folder = get_icon("FolderBig","EditorIcons");
+ if (!has_icon("ResizedFolder", "EditorIcons")) {
+ Ref<ImageTexture> folder = get_icon("FolderBig", "EditorIcons");
Image img = folder->get_data();
- img.resize(thumbnail_size,thumbnail_size);
- Ref<ImageTexture> resized_folder = Ref<ImageTexture>( memnew( ImageTexture));
- resized_folder->create_from_image(img,0);
- Theme::get_default()->set_icon("ResizedFolder","EditorIcons",resized_folder);
+ img.resize(thumbnail_size, thumbnail_size);
+ Ref<ImageTexture> resized_folder = Ref<ImageTexture>(memnew(ImageTexture));
+ resized_folder->create_from_image(img, 0);
+ Theme::get_default()->set_icon("ResizedFolder", "EditorIcons", resized_folder);
}
- folder_thumbnail = get_icon("ResizedFolder","EditorIcons");
+ folder_thumbnail = get_icon("ResizedFolder", "EditorIcons");
- if (!has_icon("ResizedFile","EditorIcons")) {
- Ref<ImageTexture> file = get_icon("FileBig","EditorIcons");
+ if (!has_icon("ResizedFile", "EditorIcons")) {
+ Ref<ImageTexture> file = get_icon("FileBig", "EditorIcons");
Image img = file->get_data();
- img.resize(thumbnail_size,thumbnail_size);
- Ref<ImageTexture> resized_file = Ref<ImageTexture>( memnew( ImageTexture));
- resized_file->create_from_image(img,0);
- Theme::get_default()->set_icon("ResizedFile","EditorIcons",resized_file);
+ img.resize(thumbnail_size, thumbnail_size);
+ Ref<ImageTexture> resized_file = Ref<ImageTexture>(memnew(ImageTexture));
+ resized_file->create_from_image(img, 0);
+ Theme::get_default()->set_icon("ResizedFile", "EditorIcons", resized_file);
}
- file_thumbnail = get_icon("ResizedFile","EditorIcons");
+ file_thumbnail = get_icon("ResizedFile", "EditorIcons");
} else {
@@ -461,137 +441,124 @@ void FileSystemDock::_update_files(bool p_keep_selection) {
files->set_max_text_lines(1);
files->set_fixed_column_width(0);
files->set_fixed_icon_size(Size2());
-
}
if (use_folders) {
- if (path!="res://") {
+ if (path != "res://") {
if (use_thumbnails) {
- files->add_item("..",folder_thumbnail,true);
+ files->add_item("..", folder_thumbnail, true);
} else {
- files->add_item("..",get_icon("folder","FileDialog"),true);
+ files->add_item("..", get_icon("folder", "FileDialog"), true);
}
String bd = path.get_base_dir();
- if (bd!="res://" && !bd.ends_with("/"))
- bd+="/";
+ if (bd != "res://" && !bd.ends_with("/"))
+ bd += "/";
- files->set_item_metadata(files->get_item_count()-1,bd);
+ files->set_item_metadata(files->get_item_count() - 1, bd);
}
- for(int i=0;i<efd->get_subdir_count();i++) {
-
- String dname=efd->get_subdir(i)->get_name();
+ for (int i = 0; i < efd->get_subdir_count(); i++) {
+ String dname = efd->get_subdir(i)->get_name();
if (use_thumbnails) {
- files->add_item(dname,folder_thumbnail,true);
+ files->add_item(dname, folder_thumbnail, true);
} else {
- files->add_item(dname,get_icon("folder","FileDialog"),true);
+ files->add_item(dname, get_icon("folder", "FileDialog"), true);
}
- files->set_item_metadata(files->get_item_count()-1,path.plus_file(dname)+"/");
+ files->set_item_metadata(files->get_item_count() - 1, path.plus_file(dname) + "/");
if (cselection.has(dname))
- files->select(files->get_item_count()-1,false);
+ files->select(files->get_item_count() - 1, false);
}
}
-
List<FileInfo> filelist;
if (search_box->get_text().length()) {
- if (search_box->get_text().length()>1) {
- _search(EditorFileSystem::get_singleton()->get_filesystem(),&filelist,128);
+ if (search_box->get_text().length() > 1) {
+ _search(EditorFileSystem::get_singleton()->get_filesystem(), &filelist, 128);
}
filelist.sort();
} else {
- for(int i=0;i<efd->get_file_count();i++) {
+ for (int i = 0; i < efd->get_file_count(); i++) {
FileInfo fi;
- fi.name=efd->get_file(i);
- fi.path=path.plus_file(fi.name);
- fi.type=efd->get_file_type(i);
- fi.import_status=0;
-
-
+ fi.name = efd->get_file(i);
+ fi.path = path.plus_file(fi.name);
+ fi.type = efd->get_file_type(i);
+ fi.import_status = 0;
filelist.push_back(fi);
}
}
- StringName ei="EditorIcons"; //make it faster..
- StringName oi="Object";
-
+ StringName ei = "EditorIcons"; //make it faster..
+ StringName oi = "Object";
- for(List<FileInfo>::Element *E=filelist.front();E;E=E->next()) {
- String fname=E->get().name;
+ for (List<FileInfo>::Element *E = filelist.front(); E; E = E->next()) {
+ String fname = E->get().name;
String fp = E->get().path;
StringName type = E->get().type;
Ref<Texture> type_icon;
- String tooltip=fname;
+ String tooltip = fname;
- if (E->get().import_status==0) {
+ if (E->get().import_status == 0) {
- if (has_icon(type,ei)) {
- type_icon=get_icon(type,ei);
+ if (has_icon(type, ei)) {
+ type_icon = get_icon(type, ei);
} else {
- type_icon=get_icon(oi,ei);
+ type_icon = get_icon(oi, ei);
}
- } else if (E->get().import_status==1) {
- type_icon=get_icon("DependencyOk","EditorIcons");
- } else if (E->get().import_status==2) {
- type_icon=get_icon("DependencyChanged","EditorIcons");
- tooltip+"\nStatus: Needs Re-Import";
- } else if (E->get().import_status==3) {
- type_icon=get_icon("ImportFail","EditorIcons");
- tooltip+"\nStatus: Missing Dependencies";
+ } else if (E->get().import_status == 1) {
+ type_icon = get_icon("DependencyOk", "EditorIcons");
+ } else if (E->get().import_status == 2) {
+ type_icon = get_icon("DependencyChanged", "EditorIcons");
+ tooltip + "\nStatus: Needs Re-Import";
+ } else if (E->get().import_status == 3) {
+ type_icon = get_icon("ImportFail", "EditorIcons");
+ tooltip + "\nStatus: Missing Dependencies";
}
if (E->get().sources.size()) {
- for(int i=0;i<E->get().sources.size();i++) {
- tooltip+="\nSource: "+E->get().sources[i];
+ for (int i = 0; i < E->get().sources.size(); i++) {
+ tooltip += "\nSource: " + E->get().sources[i];
}
}
-
-
if (use_thumbnails) {
- files->add_item(fname,file_thumbnail,true);
- files->set_item_metadata(files->get_item_count()-1,fp);
- files->set_item_tag_icon(files->get_item_count()-1,type_icon);
+ files->add_item(fname, file_thumbnail, true);
+ files->set_item_metadata(files->get_item_count() - 1, fp);
+ files->set_item_tag_icon(files->get_item_count() - 1, type_icon);
Array udata;
udata.resize(2);
- udata[0]=files->get_item_count()-1;
- udata[1]=fname;
- EditorResourcePreview::get_singleton()->queue_resource_preview(fp,this,"_thumbnail_done",udata);
+ udata[0] = files->get_item_count() - 1;
+ udata[1] = fname;
+ EditorResourcePreview::get_singleton()->queue_resource_preview(fp, this, "_thumbnail_done", udata);
} else {
- files->add_item(fname,type_icon,true);
- files->set_item_metadata(files->get_item_count()-1,fp);
-
+ files->add_item(fname, type_icon, true);
+ files->set_item_metadata(files->get_item_count() - 1, fp);
}
if (cselection.has(fname))
- files->select(files->get_item_count()-1,false);
-
- files->set_item_tooltip(files->get_item_count()-1,tooltip);
-
+ files->select(files->get_item_count() - 1, false);
+ files->set_item_tooltip(files->get_item_count() - 1, tooltip);
}
-
-
}
void FileSystemDock::_select_file(int p_idx) {
- files->select(p_idx,true);
+ files->select(p_idx, true);
_file_option(FILE_OPEN);
}
@@ -607,33 +574,30 @@ void FileSystemDock::_go_to_tree() {
//file_options->hide();
}
-void FileSystemDock::_go_to_dir(const String& p_dir){
+void FileSystemDock::_go_to_dir(const String &p_dir) {
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- if (da->change_dir(p_dir)==OK) {
- path=da->get_current_dir();
+ if (da->change_dir(p_dir) == OK) {
+ path = da->get_current_dir();
_update_files(false);
}
current_path->set_text(path);
memdelete(da);
-
-
}
-void FileSystemDock::_preview_invalidated(const String& p_path) {
+void FileSystemDock::_preview_invalidated(const String &p_path) {
- if (p_path.get_base_dir()==path && search_box->get_text()==String() && file_list_vb->is_visible_in_tree()) {
+ if (p_path.get_base_dir() == path && search_box->get_text() == String() && file_list_vb->is_visible_in_tree()) {
+ for (int i = 0; i < files->get_item_count(); i++) {
- for(int i=0;i<files->get_item_count();i++) {
-
- if (files->get_item_metadata(i)==p_path) {
+ if (files->get_item_metadata(i) == p_path) {
//re-request preview
Array udata;
udata.resize(2);
- udata[0]=i;
- udata[1]=files->get_item_text(i);
- EditorResourcePreview::get_singleton()->queue_resource_preview(p_path,this,"_thumbnail_done",udata);
+ udata[0] = i;
+ udata[1] = files->get_item_text(i);
+ EditorResourcePreview::get_singleton()->queue_resource_preview(p_path, this, "_thumbnail_done", udata);
break;
}
}
@@ -642,15 +606,14 @@ void FileSystemDock::_preview_invalidated(const String& p_path) {
void FileSystemDock::_fs_changed() {
- button_hist_prev->set_disabled(history_pos==0);
- button_hist_next->set_disabled(history_pos+1==history.size());
+ button_hist_prev->set_disabled(history_pos == 0);
+ button_hist_next->set_disabled(history_pos + 1 == history.size());
scanning_vb->hide();
split_box->show();
if (tree->is_visible()) {
button_favorite->show();
_update_tree();
-
}
if (file_list_vb->is_visible()) {
@@ -669,25 +632,23 @@ void FileSystemDock::_set_scanning_mode() {
scanning_vb->show();
set_process(true);
if (EditorFileSystem::get_singleton()->is_scanning()) {
- scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress()*100);
+ scanning_progress->set_value(EditorFileSystem::get_singleton()->get_scanning_progress() * 100);
} else {
scanning_progress->set_value(0);
}
-
}
void FileSystemDock::_fw_history() {
- if (history_pos<history.size()-1)
+ if (history_pos < history.size() - 1)
history_pos++;
- path=history[history_pos];
+ path = history[history_pos];
if (tree->is_visible()) {
_update_tree();
tree->grab_focus();
tree->ensure_cursor_is_visible();
-
}
if (file_list_vb->is_visible()) {
@@ -695,18 +656,16 @@ void FileSystemDock::_fw_history() {
current_path->set_text(path);
}
- button_hist_prev->set_disabled(history_pos==0);
- button_hist_next->set_disabled(history_pos+1==history.size());
-
+ button_hist_prev->set_disabled(history_pos == 0);
+ button_hist_next->set_disabled(history_pos + 1 == history.size());
}
void FileSystemDock::_bw_history() {
- if (history_pos>0)
+ if (history_pos > 0)
history_pos--;
- path=history[history_pos];
-
+ path = history[history_pos];
if (tree->is_visible()) {
_update_tree();
@@ -719,44 +678,40 @@ void FileSystemDock::_bw_history() {
current_path->set_text(path);
}
- button_hist_prev->set_disabled(history_pos==0);
- button_hist_next->set_disabled(history_pos+1==history.size());
-
+ button_hist_prev->set_disabled(history_pos == 0);
+ button_hist_next->set_disabled(history_pos + 1 == history.size());
}
void FileSystemDock::_push_to_history() {
- history.resize(history_pos+1);
- if (history[history_pos]!=path) {
+ history.resize(history_pos + 1);
+ if (history[history_pos] != path) {
history.push_back(path);
history_pos++;
}
- button_hist_prev->set_disabled(history_pos==0);
- button_hist_next->set_disabled(history_pos+1==history.size());
-
+ button_hist_prev->set_disabled(history_pos == 0);
+ button_hist_next->set_disabled(history_pos + 1 == history.size());
}
+void FileSystemDock::_find_inside_move_files(EditorFileSystemDirectory *efsd, Vector<String> &files) {
-void FileSystemDock::_find_inside_move_files(EditorFileSystemDirectory *efsd,Vector<String>& files) {
-
- for(int i=0;i<efsd->get_subdir_count();i++) {
- _find_inside_move_files(efsd->get_subdir(i),files);
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
+ _find_inside_move_files(efsd->get_subdir(i), files);
}
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
files.push_back(efsd->get_file_path(i));
}
-
}
-void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd,Map<String,String> &renames,List<String>& to_remaps) {
+void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd, Map<String, String> &renames, List<String> &to_remaps) {
- for(int i=0;i<efsd->get_subdir_count();i++) {
- _find_remaps(efsd->get_subdir(i),renames,to_remaps);
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
+ _find_remaps(efsd->get_subdir(i), renames, to_remaps);
}
- for(int i=0;i<efsd->get_file_count();i++) {
- Vector<String> deps=efsd->get_file_deps(i);
- for(int j=0;j<deps.size();j++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
+ Vector<String> deps = efsd->get_file_deps(i);
+ for (int j = 0; j < deps.size(); j++) {
if (renames.has(deps[j])) {
to_remaps.push_back(efsd->get_file_path(i));
break;
@@ -765,10 +720,9 @@ void FileSystemDock::_find_remaps(EditorFileSystemDirectory *efsd,Map<String,Str
}
}
+void FileSystemDock::_rename_operation(const String &p_to_path) {
-void FileSystemDock::_rename_operation(const String& p_to_path) {
-
- if (move_files[0]==p_to_path) {
+ if (move_files[0] == p_to_path) {
EditorNode::get_singleton()->show_warning(TTR("Same source and destination files, doing nothing."));
return;
}
@@ -777,33 +731,33 @@ void FileSystemDock::_rename_operation(const String& p_to_path) {
return;
}
- Map<String,String> renames;
- renames[move_files[0]]=p_to_path;
+ Map<String, String> renames;
+ renames[move_files[0]] = p_to_path;
List<String> remap;
- _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(),renames,remap);
- print_line("found files to remap: "+itos(remap.size()));
+ _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(), renames, remap);
+ print_line("found files to remap: " + itos(remap.size()));
//perform remaps
- for(List<String>::Element *E=remap.front();E;E=E->next()) {
+ for (List<String>::Element *E = remap.front(); E; E = E->next()) {
- Error err = ResourceLoader::rename_dependencies(E->get(),renames);
- print_line("remapping: "+E->get());
+ Error err = ResourceLoader::rename_dependencies(E->get(), renames);
+ print_line("remapping: " + E->get());
- if (err!=OK) {
- EditorNode::get_singleton()->add_io_error("Can't rename deps for:\n"+E->get()+"\n");
+ if (err != OK) {
+ EditorNode::get_singleton()->add_io_error("Can't rename deps for:\n" + E->get() + "\n");
}
}
//finally, perform moves
- DirAccess *da=DirAccess::create(DirAccess::ACCESS_RESOURCES);
+ DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- Error err = da->rename(move_files[0],p_to_path);
- print_line("moving file "+move_files[0]+" to "+p_to_path);
- if (err!=OK) {
- EditorNode::get_singleton()->add_io_error("Error moving file:\n"+move_files[0]+"\n");
+ Error err = da->rename(move_files[0], p_to_path);
+ print_line("moving file " + move_files[0] + " to " + p_to_path);
+ if (err != OK) {
+ EditorNode::get_singleton()->add_io_error("Error moving file:\n" + move_files[0] + "\n");
}
//rescan everything
@@ -812,10 +766,9 @@ void FileSystemDock::_rename_operation(const String& p_to_path) {
_rescan();
}
+void FileSystemDock::_move_operation(const String &p_to_path) {
-void FileSystemDock::_move_operation(const String& p_to_path) {
-
- if (p_to_path==path) {
+ if (p_to_path == path) {
EditorNode::get_singleton()->show_warning(TTR("Same source and destination paths, doing nothing."));
return;
}
@@ -824,78 +777,78 @@ void FileSystemDock::_move_operation(const String& p_to_path) {
Vector<String> inside_files;
- for(int i=0;i<move_dirs.size();i++) {
+ for (int i = 0; i < move_dirs.size(); i++) {
if (p_to_path.begins_with(move_dirs[i])) {
EditorNode::get_singleton()->show_warning(TTR("Can't move directories to within themselves."));
return;
}
- EditorFileSystemDirectory *efsd=EditorFileSystem::get_singleton()->get_filesystem_path(move_dirs[i]);
+ EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem_path(move_dirs[i]);
if (!efsd)
continue;
- _find_inside_move_files(efsd,inside_files);
+ _find_inside_move_files(efsd, inside_files);
}
//make list of remaps
- Map<String,String> renames;
- String repfrom=path=="res://"?path:String(path+"/");
- String repto=p_to_path=="res://"?p_to_path:String(p_to_path+"/");
+ Map<String, String> renames;
+ String repfrom = path == "res://" ? path : String(path + "/");
+ String repto = p_to_path == "res://" ? p_to_path : String(p_to_path + "/");
- for(int i=0;i<move_files.size();i++) {
- renames[move_files[i]]=move_files[i].replace_first(repfrom,repto);
- print_line("move file "+move_files[i]+" -> "+renames[move_files[i]]);
+ for (int i = 0; i < move_files.size(); i++) {
+ renames[move_files[i]] = move_files[i].replace_first(repfrom, repto);
+ print_line("move file " + move_files[i] + " -> " + renames[move_files[i]]);
}
- for(int i=0;i<inside_files.size();i++) {
- renames[inside_files[i]]=inside_files[i].replace_first(repfrom,repto);
- print_line("inside file "+inside_files[i]+" -> "+renames[inside_files[i]]);
+ for (int i = 0; i < inside_files.size(); i++) {
+ renames[inside_files[i]] = inside_files[i].replace_first(repfrom, repto);
+ print_line("inside file " + inside_files[i] + " -> " + renames[inside_files[i]]);
}
//make list of files that will be run the remapping
List<String> remap;
- _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(),renames,remap);
- print_line("found files to remap: "+itos(remap.size()));
+ _find_remaps(EditorFileSystem::get_singleton()->get_filesystem(), renames, remap);
+ print_line("found files to remap: " + itos(remap.size()));
//perform remaps
- for(List<String>::Element *E=remap.front();E;E=E->next()) {
+ for (List<String>::Element *E = remap.front(); E; E = E->next()) {
- Error err = ResourceLoader::rename_dependencies(E->get(),renames);
- print_line("remapping: "+E->get());
+ Error err = ResourceLoader::rename_dependencies(E->get(), renames);
+ print_line("remapping: " + E->get());
- if (err!=OK) {
- EditorNode::get_singleton()->add_io_error("Can't rename deps for:\n"+E->get()+"\n");
+ if (err != OK) {
+ EditorNode::get_singleton()->add_io_error("Can't rename deps for:\n" + E->get() + "\n");
}
}
//finally, perform moves
- DirAccess *da=DirAccess::create(DirAccess::ACCESS_RESOURCES);
+ DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- for(int i=0;i<move_files.size();i++) {
+ for (int i = 0; i < move_files.size(); i++) {
- String to = move_files[i].replace_first(repfrom,repto);
- Error err = da->rename(move_files[i],to);
- print_line("moving file "+move_files[i]+" to "+to);
- if (err!=OK) {
- EditorNode::get_singleton()->add_io_error("Error moving file:\n"+move_files[i]+"\n");
+ String to = move_files[i].replace_first(repfrom, repto);
+ Error err = da->rename(move_files[i], to);
+ print_line("moving file " + move_files[i] + " to " + to);
+ if (err != OK) {
+ EditorNode::get_singleton()->add_io_error("Error moving file:\n" + move_files[i] + "\n");
}
}
- for(int i=0;i<move_dirs.size();i++) {
+ for (int i = 0; i < move_dirs.size(); i++) {
String mdir = move_dirs[i];
- if (mdir=="res://")
+ if (mdir == "res://")
continue;
if (mdir.ends_with("/")) {
- mdir=mdir.substr(0,mdir.length()-1);
+ mdir = mdir.substr(0, mdir.length() - 1);
}
String to = p_to_path.plus_file(mdir.get_file());
- Error err = da->rename(mdir,to);
- print_line("moving dir "+mdir+" to "+to);
- if (err!=OK) {
- EditorNode::get_singleton()->add_io_error("Error moving dir:\n"+move_dirs[i]+"\n");
+ Error err = da->rename(mdir, to);
+ print_line("moving dir " + mdir + " to " + to);
+ if (err != OK) {
+ EditorNode::get_singleton()->add_io_error("Error moving dir:\n" + move_dirs[i] + "\n");
}
}
@@ -903,48 +856,44 @@ void FileSystemDock::_move_operation(const String& p_to_path) {
//rescan everything
print_line("call rescan!");
_rescan();
-
}
void FileSystemDock::_file_option(int p_option) {
- switch(p_option) {
-
+ switch (p_option) {
case FILE_SHOW_IN_EXPLORER:
case FILE_OPEN: {
- int idx=-1;
- for(int i=0;i<files->get_item_count();i++) {
+ int idx = -1;
+ for (int i = 0; i < files->get_item_count(); i++) {
if (files->is_selected(i)) {
- idx=i;
+ idx = i;
break;
}
}
- if (idx<0)
+ if (idx < 0)
return;
-
-
String path = files->get_item_metadata(idx);
if (p_option == FILE_SHOW_IN_EXPLORER) {
String dir = GlobalConfig::get_singleton()->globalize_path(path);
dir = dir.substr(0, dir.find_last("/"));
- OS::get_singleton()->shell_open(String("file://")+dir);
+ OS::get_singleton()->shell_open(String("file://") + dir);
return;
}
if (path.ends_with("/")) {
- if (path!="res://") {
- path=path.substr(0,path.length()-1);
+ if (path != "res://") {
+ path = path.substr(0, path.length() - 1);
}
- this->path=path;
+ this->path = path;
_update_files(false);
current_path->set_text(path);
_push_to_history();
} else {
- if (ResourceLoader::get_resource_type(path)=="PackedScene") {
+ if (ResourceLoader::get_resource_type(path) == "PackedScene") {
editor->open_request(path);
} else {
@@ -957,11 +906,11 @@ void FileSystemDock::_file_option(int p_option) {
Vector<String> paths;
- for (int i = 0; i<files->get_item_count(); i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
continue;
- String path =files->get_item_metadata(i);
- if (EditorFileSystem::get_singleton()->get_file_type(path)=="PackedScene") {
+ String path = files->get_item_metadata(i);
+ if (EditorFileSystem::get_singleton()->get_file_type(path) == "PackedScene") {
paths.push_back(path);
}
}
@@ -973,7 +922,7 @@ void FileSystemDock::_file_option(int p_option) {
case FILE_DEPENDENCIES: {
int idx = files->get_current();
- if (idx<0 || idx>=files->get_item_count())
+ if (idx < 0 || idx >= files->get_item_count())
break;
String path = files->get_item_metadata(idx);
deps_editor->edit(path);
@@ -981,7 +930,7 @@ void FileSystemDock::_file_option(int p_option) {
case FILE_OWNERS: {
int idx = files->get_current();
- if (idx<0 || idx>=files->get_item_count())
+ if (idx < 0 || idx >= files->get_item_count())
break;
String path = files->get_item_metadata(idx);
owners_editor->show(path);
@@ -991,53 +940,49 @@ void FileSystemDock::_file_option(int p_option) {
move_dirs.clear();
move_files.clear();
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
String path = files->get_item_metadata(i);
if (!files->is_selected(i))
continue;
- if (files->get_item_text(i)=="..") {
- EditorNode::get_singleton()->show_warning(TTR("Can't operate on '..'"));
- return;
- }
+ if (files->get_item_text(i) == "..") {
+ EditorNode::get_singleton()->show_warning(TTR("Can't operate on '..'"));
+ return;
+ }
if (path.ends_with("/")) {
- move_dirs.push_back(path.substr(0,path.length()-1));
+ move_dirs.push_back(path.substr(0, path.length() - 1));
} else {
move_files.push_back(path);
}
}
-
- if (move_dirs.empty() && move_files.size()==1) {
+ if (move_dirs.empty() && move_files.size() == 1) {
rename_dialog->clear_filters();
- rename_dialog->add_filter("*."+move_files[0].get_extension());
+ rename_dialog->add_filter("*." + move_files[0].get_extension());
rename_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
rename_dialog->set_current_path(move_files[0]);
rename_dialog->popup_centered_ratio();
- rename_dialog->set_title(TTR("Pick New Name and Location For:")+" "+move_files[0].get_file());
-
+ rename_dialog->set_title(TTR("Pick New Name and Location For:") + " " + move_files[0].get_file());
} else {
//just move
move_dialog->popup_centered_ratio();
}
-
} break;
case FILE_REMOVE: {
Vector<String> torem;
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
String path = files->get_item_metadata(i);
if (path.ends_with("/") || !files->is_selected(i))
continue;
torem.push_back(path);
-
}
if (torem.empty()) {
@@ -1055,9 +1000,8 @@ void FileSystemDock::_file_option(int p_option) {
} break;
case FILE_REIMPORT: {
-
Vector<String> reimport;
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
continue;
@@ -1066,8 +1010,8 @@ void FileSystemDock::_file_option(int p_option) {
reimport.push_back(path);
}
- ERR_FAIL_COND(reimport.size()==0);
-/*
+ ERR_FAIL_COND(reimport.size() == 0);
+ /*
Ref<ResourceImportMetadata> rimd = ResourceLoader::load_import_metadata(reimport[0]);
ERR_FAIL_COND(!rimd.is_valid());
String editor=rimd->get_editor();
@@ -1091,7 +1035,7 @@ void FileSystemDock::_file_option(int p_option) {
case FILE_COPY_PATH:
int idx = files->get_current();
- if (idx<0 || idx>=files->get_item_count())
+ if (idx < 0 || idx >= files->get_item_count())
break;
String path = files->get_item_metadata(idx);
OS::get_singleton()->set_clipboard(path);
@@ -1103,18 +1047,18 @@ void FileSystemDock::_folder_option(int p_option) {
TreeItem *item = tree->get_selected();
TreeItem *child = item->get_children();
- switch(p_option) {
-
+ switch (p_option) {
+
case FOLDER_EXPAND_ALL:
item->set_collapsed(false);
- while(child) {
+ while (child) {
child->set_collapsed(false);
child = child->get_next();
}
break;
case FOLDER_COLLAPSE_ALL:
- while(child) {
+ while (child) {
child->set_collapsed(true);
child = child->get_next();
}
@@ -1122,8 +1066,7 @@ void FileSystemDock::_folder_option(int p_option) {
}
}
-void FileSystemDock::_open_pressed(){
-
+void FileSystemDock::_open_pressed() {
TreeItem *sel = tree->get_selected();
if (!sel) {
@@ -1149,22 +1092,20 @@ void FileSystemDock::_open_pressed(){
_push_to_history();
//emit_signal("open",path);
-
}
-void FileSystemDock::_dir_rmb_pressed(const Vector2& p_pos) {
+void FileSystemDock::_dir_rmb_pressed(const Vector2 &p_pos) {
folder_options->clear();
- folder_options->set_size(Size2(1,1));
+ folder_options->set_size(Size2(1, 1));
- folder_options->add_item(TTR("Expand all"),FOLDER_EXPAND_ALL);
- folder_options->add_item(TTR("Collapse all"),FOLDER_COLLAPSE_ALL);
+ folder_options->add_item(TTR("Expand all"), FOLDER_EXPAND_ALL);
+ folder_options->add_item(TTR("Collapse all"), FOLDER_COLLAPSE_ALL);
folder_options->set_pos(files->get_global_pos() + p_pos);
folder_options->popup();
}
-
-void FileSystemDock::_search_changed(const String& p_text) {
+void FileSystemDock::_search_changed(const String &p_text) {
if (!search_box->is_visible_in_tree())
return; //wtf
@@ -1176,14 +1117,12 @@ void FileSystemDock::_rescan() {
_set_scanning_mode();
EditorFileSystem::get_singleton()->scan();
-
}
-void FileSystemDock::fix_dependencies(const String& p_for_file) {
+void FileSystemDock::fix_dependencies(const String &p_for_file) {
deps_editor->edit(p_for_file);
}
-
void FileSystemDock::focus_on_filter() {
if (!search_box->is_visible_in_tree()) {
@@ -1205,39 +1144,37 @@ void FileSystemDock::set_display_mode(int p_mode) {
_change_file_display();
}
+Variant FileSystemDock::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
-Variant FileSystemDock::get_drag_data_fw(const Point2& p_point,Control* p_from) {
-
- if (p_from==tree) {
+ if (p_from == tree) {
TreeItem *selected = tree->get_selected();
if (!selected)
return Variant();
String path = selected->get_metadata(0);
- if (path==String())
+ if (path == String())
return Variant();
if (!path.ends_with("/"))
- path=path+"/";
+ path = path + "/";
Vector<String> paths;
paths.push_back(path);
- Dictionary d = EditorNode::get_singleton()->drag_files(paths,p_from);
+ Dictionary d = EditorNode::get_singleton()->drag_files(paths, p_from);
- if (selected->get_parent() && tree->get_root()->get_children()==selected->get_parent()) {
+ if (selected->get_parent() && tree->get_root()->get_children() == selected->get_parent()) {
//a favorite.. treat as such
- d["type"]="favorite";
+ d["type"] = "favorite";
}
return d;
-
}
- if (p_from==files) {
+ if (p_from == files) {
List<int> seldirs;
List<int> selfiles;
- for (int i = 0; i<files->get_item_count(); i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (files->is_selected(i)) {
String path = files->get_item_metadata(i);
if (path.ends_with("/"))
@@ -1261,35 +1198,34 @@ Variant FileSystemDock::get_drag_data_fw(const Point2& p_point,Control* p_from)
}
}*/
- if (selfiles.size()>0 && seldirs.size()==0) {
+ if (selfiles.size() > 0 && seldirs.size() == 0) {
Vector<String> fnames;
- for(List<int>::Element *E=selfiles.front();E;E=E->next()) {
+ for (List<int>::Element *E = selfiles.front(); E; E = E->next()) {
fnames.push_back(files->get_item_metadata(E->get()));
}
- return EditorNode::get_singleton()->drag_files(fnames,p_from);
+ return EditorNode::get_singleton()->drag_files(fnames, p_from);
}
- if (selfiles.size()>0 || seldirs.size()>0) {
+ if (selfiles.size() > 0 || seldirs.size() > 0) {
Vector<String> fnames;
- for(List<int>::Element *E=selfiles.front();E;E=E->next()) {
+ for (List<int>::Element *E = selfiles.front(); E; E = E->next()) {
fnames.push_back(files->get_item_metadata(E->get()));
}
- for(List<int>::Element *E=seldirs.front();E;E=E->next()) {
+ for (List<int>::Element *E = seldirs.front(); E; E = E->next()) {
fnames.push_back(files->get_item_metadata(E->get()));
}
- return EditorNode::get_singleton()->drag_files_and_dirs(fnames,p_from);
+ return EditorNode::get_singleton()->drag_files_and_dirs(fnames, p_from);
}
-
}
return Variant();
}
-bool FileSystemDock::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool FileSystemDock::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary drag_data = p_data;
- if (drag_data.has("type") && String(drag_data["type"])=="favorite") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "favorite") {
//moving favorite around
TreeItem *ti = tree->get_item_at_pos(p_point);
@@ -1298,34 +1234,32 @@ bool FileSystemDock::can_drop_data_fw(const Point2& p_point,const Variant& p_dat
int what = tree->get_drop_section_at_pos(p_point);
- if (ti==tree->get_root()->get_children()) {
- return (what==1); //the parent, first fav
+ if (ti == tree->get_root()->get_children()) {
+ return (what == 1); //the parent, first fav
}
- if (ti->get_parent() && tree->get_root()->get_children()==ti->get_parent()) {
+ if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) {
return true; // a favorite
}
- if (ti==tree->get_root()->get_children()->get_next()) {
- return (what==-1); //the tree, last fav
+ if (ti == tree->get_root()->get_children()->get_next()) {
+ return (what == -1); //the tree, last fav
}
return false;
-
}
-
- if (drag_data.has("type") && String(drag_data["type"])=="resource") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
return true;
}
- if (drag_data.has("type") && ( String(drag_data["type"])=="files" || String(drag_data["type"])=="files_and_dirs")) {
+ if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) {
Vector<String> fnames = drag_data["files"];
- if (p_from==files) {
+ if (p_from == files) {
int at_pos = files->get_item_at_pos(p_point);
- if (at_pos!=-1) {
+ if (at_pos != -1) {
String dir = files->get_item_metadata(at_pos);
if (dir.ends_with("/"))
@@ -1333,31 +1267,30 @@ bool FileSystemDock::can_drop_data_fw(const Point2& p_point,const Variant& p_dat
}
}
- if (p_from==tree) {
+ if (p_from == tree) {
TreeItem *ti = tree->get_item_at_pos(p_point);
if (!ti)
return false;
String path = ti->get_metadata(0);
- if (path==String())
+ if (path == String())
return false;
return true;
}
-
}
return false;
}
-void FileSystemDock::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void FileSystemDock::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (!can_drop_data_fw(p_point,p_data,p_from))
+ if (!can_drop_data_fw(p_point, p_data, p_from))
return;
Dictionary drag_data = p_data;
- if (drag_data.has("type") && String(drag_data["type"])=="favorite") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "favorite") {
//moving favorite around
TreeItem *ti = tree->get_item_at_pos(p_point);
@@ -1366,131 +1299,126 @@ void FileSystemDock::drop_data_fw(const Point2& p_point,const Variant& p_data,Co
Vector<String> files = drag_data["files"];
- ERR_FAIL_COND(files.size()!=1);
+ ERR_FAIL_COND(files.size() != 1);
String swap = files[0];
- if (swap!="res://" && swap.ends_with("/")) {
- swap=swap.substr(0,swap.length()-1);
+ if (swap != "res://" && swap.ends_with("/")) {
+ swap = swap.substr(0, swap.length() - 1);
}
int what = tree->get_drop_section_at_pos(p_point);
- TreeItem *swap_item=NULL;
+ TreeItem *swap_item = NULL;
- if (ti==tree->get_root()->get_children()) {
- swap_item=tree->get_root()->get_children()->get_children();
+ if (ti == tree->get_root()->get_children()) {
+ swap_item = tree->get_root()->get_children()->get_children();
- } else if (ti->get_parent() && tree->get_root()->get_children()==ti->get_parent()) {
- if (what==-1) {
- swap_item=ti;
+ } else if (ti->get_parent() && tree->get_root()->get_children() == ti->get_parent()) {
+ if (what == -1) {
+ swap_item = ti;
} else {
- swap_item=ti->get_next();
+ swap_item = ti->get_next();
}
}
String swap_with;
if (swap_item) {
- swap_with=swap_item->get_metadata(0);
- if (swap_with!="res://" && swap_with.ends_with("/")) {
- swap_with=swap_with.substr(0,swap_with.length()-1);
+ swap_with = swap_item->get_metadata(0);
+ if (swap_with != "res://" && swap_with.ends_with("/")) {
+ swap_with = swap_with.substr(0, swap_with.length() - 1);
}
}
- if (swap==swap_with)
+ if (swap == swap_with)
return;
Vector<String> dirs = EditorSettings::get_singleton()->get_favorite_dirs();
- ERR_FAIL_COND(dirs.find(swap)==-1);
- ERR_FAIL_COND(swap_with!=String() && dirs.find(swap_with)==-1);
+ ERR_FAIL_COND(dirs.find(swap) == -1);
+ ERR_FAIL_COND(swap_with != String() && dirs.find(swap_with) == -1);
dirs.erase(swap);
- if (swap_with==String()) {
+ if (swap_with == String()) {
dirs.push_back(swap);
} else {
int idx = dirs.find(swap_with);
- dirs.insert(idx,swap);
+ dirs.insert(idx, swap);
}
EditorSettings::get_singleton()->set_favorite_dirs(dirs);
_update_tree();
return;
-
}
- if (drag_data.has("type") && String(drag_data["type"])=="resource") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
Ref<Resource> res = drag_data["resource"];
if (!res.is_valid()) {
return;
}
-
- if (p_from==tree) {
+ if (p_from == tree) {
TreeItem *ti = tree->get_item_at_pos(p_point);
if (!ti)
return;
String path = ti->get_metadata(0);
- if (path==String())
+ if (path == String())
return;
- EditorNode::get_singleton()->save_resource_as(res,path);
+ EditorNode::get_singleton()->save_resource_as(res, path);
return;
-
}
- if (p_from==files) {
- String save_path=path;
+ if (p_from == files) {
+ String save_path = path;
int at_pos = files->get_item_at_pos(p_point);
- if (at_pos!=-1) {
+ if (at_pos != -1) {
String to_dir = files->get_item_metadata(at_pos);
if (to_dir.ends_with("/")) {
- save_path=to_dir;
- if (save_path!="res://")
- save_path=save_path.substr(0,save_path.length()-1);
+ save_path = to_dir;
+ if (save_path != "res://")
+ save_path = save_path.substr(0, save_path.length() - 1);
}
-
}
- EditorNode::get_singleton()->save_resource_as(res,save_path);
+ EditorNode::get_singleton()->save_resource_as(res, save_path);
return;
}
}
- if (drag_data.has("type") && ( String(drag_data["type"])=="files" || String(drag_data["type"])=="files_and_dirs")) {
+ if (drag_data.has("type") && (String(drag_data["type"]) == "files" || String(drag_data["type"]) == "files_and_dirs")) {
- if (p_from==files || p_from==tree) {
+ if (p_from == files || p_from == tree) {
String to_dir;
- if (p_from==files) {
+ if (p_from == files) {
int at_pos = files->get_item_at_pos(p_point);
- ERR_FAIL_COND(at_pos==-1);
+ ERR_FAIL_COND(at_pos == -1);
to_dir = files->get_item_metadata(at_pos);
- } else {
+ } else {
TreeItem *ti = tree->get_item_at_pos(p_point);
if (!ti)
return;
to_dir = ti->get_metadata(0);
- ERR_FAIL_COND(to_dir==String());
-
+ ERR_FAIL_COND(to_dir == String());
}
- if (to_dir!="res://" && to_dir.ends_with("/")) {
- to_dir=to_dir.substr(0,to_dir.length()-1);
+ if (to_dir != "res://" && to_dir.ends_with("/")) {
+ to_dir = to_dir.substr(0, to_dir.length() - 1);
}
Vector<String> fnames = drag_data["files"];
move_files.clear();
move_dirs.clear();
- for(int i=0;i<fnames.size();i++) {
+ for (int i = 0; i < fnames.size(); i++) {
if (fnames[i].ends_with("/"))
move_dirs.push_back(fnames[i]);
else
@@ -1500,27 +1428,26 @@ void FileSystemDock::drop_data_fw(const Point2& p_point,const Variant& p_data,Co
_move_operation(to_dir);
}
}
-
}
-void FileSystemDock::_files_list_rmb_select(int p_item,const Vector2& p_pos) {
+void FileSystemDock::_files_list_rmb_select(int p_item, const Vector2 &p_pos) {
Vector<String> filenames;
- bool all_scenes=true;
- bool all_can_reimport=true;
+ bool all_scenes = true;
+ bool all_can_reimport = true;
Set<String> types;
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
continue;
String path = files->get_item_metadata(i);
- if (files->get_item_text(i)=="..") {
+ if (files->get_item_text(i) == "..") {
// no operate on ..
- return;
+ return;
}
if (path.ends_with("/")) {
@@ -1528,63 +1455,58 @@ void FileSystemDock::_files_list_rmb_select(int p_item,const Vector2& p_pos) {
return;
}
-
- EditorFileSystemDirectory *efsd=NULL;
+ EditorFileSystemDirectory *efsd = NULL;
int pos;
- efsd = EditorFileSystem::get_singleton()->find_file(path,&pos);
+ efsd = EditorFileSystem::get_singleton()->find_file(path, &pos);
if (efsd) {
-
} else {
- all_can_reimport=false;
-
+ all_can_reimport = false;
}
filenames.push_back(path);
- if (EditorFileSystem::get_singleton()->get_file_type(path)!="PackedScene")
- all_scenes=false;
+ if (EditorFileSystem::get_singleton()->get_file_type(path) != "PackedScene")
+ all_scenes = false;
}
-
- if (filenames.size()==0)
+ if (filenames.size() == 0)
return;
file_options->clear();
- file_options->set_size(Size2(1,1));
+ file_options->set_size(Size2(1, 1));
- file_options->add_item(TTR("Open"),FILE_OPEN);
+ file_options->add_item(TTR("Open"), FILE_OPEN);
if (all_scenes) {
- file_options->add_item(TTR("Instance"),FILE_INSTANCE);
+ file_options->add_item(TTR("Instance"), FILE_INSTANCE);
}
file_options->add_separator();
- if (filenames.size()==1) {
- file_options->add_item(TTR("Edit Dependencies.."),FILE_DEPENDENCIES);
- file_options->add_item(TTR("View Owners.."),FILE_OWNERS);
+ if (filenames.size() == 1) {
+ file_options->add_item(TTR("Edit Dependencies.."), FILE_DEPENDENCIES);
+ file_options->add_item(TTR("View Owners.."), FILE_OWNERS);
file_options->add_separator();
}
- if (filenames.size()==1) {
+ if (filenames.size() == 1) {
file_options->add_item(TTR("Copy Path"), FILE_COPY_PATH);
- file_options->add_item(TTR("Rename or Move.."),FILE_MOVE);
+ file_options->add_item(TTR("Rename or Move.."), FILE_MOVE);
} else {
- file_options->add_item(TTR("Move To.."),FILE_MOVE);
+ file_options->add_item(TTR("Move To.."), FILE_MOVE);
}
-
- file_options->add_item(TTR("Delete"),FILE_REMOVE);
+ file_options->add_item(TTR("Delete"), FILE_REMOVE);
//file_options->add_item(TTR("Info"),FILE_INFO);
file_options->add_separator();
- file_options->add_item(TTR("Show In File Manager"),FILE_SHOW_IN_EXPLORER);
+ file_options->add_item(TTR("Show In File Manager"), FILE_SHOW_IN_EXPLORER);
- if (all_can_reimport && types.size()==1) { //all can reimport and are of the same type
+ if (all_can_reimport && types.size() == 1) { //all can reimport and are of the same type
-/*
+ /*
bool valid=true;
Ref<EditorImportPlugin> rimp = EditorImportExport::get_singleton()->get_import_plugin_by_name(types.front()->get());
if (rimp.is_valid()) {
@@ -1605,24 +1527,21 @@ void FileSystemDock::_files_list_rmb_select(int p_item,const Vector2& p_pos) {
file_options->set_pos(files->get_global_pos() + p_pos);
file_options->popup();
-
}
-void FileSystemDock::select_file(const String& p_file) {
+void FileSystemDock::select_file(const String &p_file) {
_go_to_dir(p_file.get_base_dir());
- for(int i=0;i<files->get_item_count();i++) {
- if (files->get_item_metadata(i)==p_file) {
+ for (int i = 0; i < files->get_item_count(); i++) {
+ if (files->get_item_metadata(i) == p_file) {
files->select(i);
files->ensure_current_is_visible();
break;
}
}
-
}
-void FileSystemDock::_file_multi_selected(int p_index,bool p_selected) {
-
+void FileSystemDock::_file_multi_selected(int p_index, bool p_selected) {
_file_selected();
}
@@ -1633,27 +1552,27 @@ void FileSystemDock::_file_selected() {
Vector<String> imports;
String import_type;
- for(int i=0;i<files->get_item_count();i++) {
+ for (int i = 0; i < files->get_item_count(); i++) {
if (!files->is_selected(i))
continue;
String p = files->get_item_metadata(i);
- if (!FileAccess::exists(p+".import")) {
+ if (!FileAccess::exists(p + ".import")) {
imports.clear();
break;
}
Ref<ConfigFile> cf;
cf.instance();
- Error err = cf->load(p+".import");
- if (err!=OK) {
+ Error err = cf->load(p + ".import");
+ if (err != OK) {
imports.clear();
break;
}
- String type = cf->get_value("remap","type");
- if (import_type=="") {
- import_type=type;
- } else if (import_type!=type) {
+ String type = cf->get_value("remap", "type");
+ if (import_type == "") {
+ import_type = type;
+ } else if (import_type != type) {
//all should be the same type
imports.clear();
break;
@@ -1661,27 +1580,25 @@ void FileSystemDock::_file_selected() {
imports.push_back(p);
}
-
- if (imports.size()==0) {
+ if (imports.size() == 0) {
EditorNode::get_singleton()->get_import_dock()->clear();
- } else if (imports.size()==1) {
+ } else if (imports.size() == 1) {
EditorNode::get_singleton()->get_import_dock()->set_edit_path(imports[0]);
} else {
EditorNode::get_singleton()->get_import_dock()->set_edit_multiple_paths(imports);
}
}
-
void FileSystemDock::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_update_tree"),&FileSystemDock::_update_tree);
- ClassDB::bind_method(D_METHOD("_rescan"),&FileSystemDock::_rescan);
- ClassDB::bind_method(D_METHOD("_favorites_pressed"),&FileSystemDock::_favorites_pressed);
+ ClassDB::bind_method(D_METHOD("_update_tree"), &FileSystemDock::_update_tree);
+ ClassDB::bind_method(D_METHOD("_rescan"), &FileSystemDock::_rescan);
+ ClassDB::bind_method(D_METHOD("_favorites_pressed"), &FileSystemDock::_favorites_pressed);
//ClassDB::bind_method(D_METHOD("_instance_pressed"),&ScenesDock::_instance_pressed);
- ClassDB::bind_method(D_METHOD("_open_pressed"),&FileSystemDock::_open_pressed);
- ClassDB::bind_method(D_METHOD("_dir_rmb_pressed"),&FileSystemDock::_dir_rmb_pressed);
+ ClassDB::bind_method(D_METHOD("_open_pressed"), &FileSystemDock::_open_pressed);
+ ClassDB::bind_method(D_METHOD("_dir_rmb_pressed"), &FileSystemDock::_dir_rmb_pressed);
- ClassDB::bind_method(D_METHOD("_thumbnail_done"),&FileSystemDock::_thumbnail_done);
+ ClassDB::bind_method(D_METHOD("_thumbnail_done"), &FileSystemDock::_thumbnail_done);
ClassDB::bind_method(D_METHOD("_select_file"), &FileSystemDock::_select_file);
ClassDB::bind_method(D_METHOD("_go_to_tree"), &FileSystemDock::_go_to_tree);
ClassDB::bind_method(D_METHOD("_go_to_dir"), &FileSystemDock::_go_to_dir);
@@ -1700,46 +1617,42 @@ void FileSystemDock::_bind_methods() {
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &FileSystemDock::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &FileSystemDock::can_drop_data_fw);
ClassDB::bind_method(D_METHOD("drop_data_fw"), &FileSystemDock::drop_data_fw);
- ClassDB::bind_method(D_METHOD("_files_list_rmb_select"),&FileSystemDock::_files_list_rmb_select);
-
- ClassDB::bind_method(D_METHOD("_preview_invalidated"),&FileSystemDock::_preview_invalidated);
- ClassDB::bind_method(D_METHOD("_file_selected"),&FileSystemDock::_file_selected);
- ClassDB::bind_method(D_METHOD("_file_multi_selected"),&FileSystemDock::_file_multi_selected);
+ ClassDB::bind_method(D_METHOD("_files_list_rmb_select"), &FileSystemDock::_files_list_rmb_select);
+ ClassDB::bind_method(D_METHOD("_preview_invalidated"), &FileSystemDock::_preview_invalidated);
+ ClassDB::bind_method(D_METHOD("_file_selected"), &FileSystemDock::_file_selected);
+ ClassDB::bind_method(D_METHOD("_file_multi_selected"), &FileSystemDock::_file_multi_selected);
ADD_SIGNAL(MethodInfo("instance", PropertyInfo(Variant::POOL_STRING_ARRAY, "files")));
ADD_SIGNAL(MethodInfo("open"));
-
}
FileSystemDock::FileSystemDock(EditorNode *p_editor) {
- editor=p_editor;
-
+ editor = p_editor;
- HBoxContainer *toolbar_hbc = memnew( HBoxContainer );
+ HBoxContainer *toolbar_hbc = memnew(HBoxContainer);
add_child(toolbar_hbc);
- button_hist_prev = memnew( ToolButton );
+ button_hist_prev = memnew(ToolButton);
toolbar_hbc->add_child(button_hist_prev);
button_hist_prev->set_disabled(true);
button_hist_prev->set_tooltip(TTR("Previous Directory"));
- button_hist_next = memnew( ToolButton );
+ button_hist_next = memnew(ToolButton);
toolbar_hbc->add_child(button_hist_next);
button_hist_next->set_disabled(true);
button_hist_prev->set_focus_mode(FOCUS_NONE);
button_hist_next->set_focus_mode(FOCUS_NONE);
button_hist_next->set_tooltip(TTR("Next Directory"));
- current_path=memnew( LineEdit );
+ current_path = memnew(LineEdit);
current_path->set_h_size_flags(SIZE_EXPAND_FILL);
toolbar_hbc->add_child(current_path);
-
- button_reload = memnew( Button );
+ button_reload = memnew(Button);
button_reload->set_flat(true);
- button_reload->connect("pressed",this,"_rescan");
+ button_reload->connect("pressed", this, "_rescan");
toolbar_hbc->add_child(button_reload);
button_reload->set_focus_mode(FOCUS_NONE);
button_reload->set_tooltip(TTR("Re-Scan Filesystem"));
@@ -1747,11 +1660,10 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
//toolbar_hbc->add_spacer();
-
- button_favorite = memnew( Button );
+ button_favorite = memnew(Button);
button_favorite->set_flat(true);
button_favorite->set_toggle_mode(true);
- button_favorite->connect("pressed",this,"_favorites_pressed");
+ button_favorite->connect("pressed", this, "_favorites_pressed");
toolbar_hbc->add_child(button_favorite);
button_favorite->set_tooltip(TTR("Toggle folder status as Favorite"));
@@ -1759,9 +1671,7 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
//Control *spacer = memnew( Control);
-
-
-/*
+ /*
button_open = memnew( Button );
button_open->set_flat(true);
button_open->connect("pressed",this,"_open_pressed");
@@ -1780,112 +1690,106 @@ FileSystemDock::FileSystemDock(EditorNode *p_editor) {
button_instance->set_tooltip(TTR("Instance the selected scene(s) as child of the selected node."));
*/
- file_options = memnew( PopupMenu );
+ file_options = memnew(PopupMenu);
add_child(file_options);
- folder_options = memnew ( PopupMenu );
+ folder_options = memnew(PopupMenu);
add_child(folder_options);
- split_box = memnew( VSplitContainer );
+ split_box = memnew(VSplitContainer);
add_child(split_box);
split_box->set_v_size_flags(SIZE_EXPAND_FILL);
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_hide_root(true);
split_box->add_child(tree);
tree->set_drag_forwarding(this);
tree->set_allow_rmb_select(true);
-
//tree->set_v_size_flags(SIZE_EXPAND_FILL);
- tree->connect("item_edited",this,"_favorite_toggled");
- tree->connect("item_activated",this,"_open_pressed");
- tree->connect("cell_selected",this,"_dir_selected");
- tree->connect("item_rmb_selected",this,"_dir_rmb_pressed");
+ tree->connect("item_edited", this, "_favorite_toggled");
+ tree->connect("item_activated", this, "_open_pressed");
+ tree->connect("cell_selected", this, "_dir_selected");
+ tree->connect("item_rmb_selected", this, "_dir_rmb_pressed");
- files = memnew( ItemList );
+ files = memnew(ItemList);
files->set_v_size_flags(SIZE_EXPAND_FILL);
files->set_select_mode(ItemList::SELECT_MULTI);
files->set_drag_forwarding(this);
- files->connect("item_rmb_selected",this,"_files_list_rmb_select");
- files->connect("item_selected",this,"_file_selected");
- files->connect("multi_selected",this,"_file_multi_selected");
+ files->connect("item_rmb_selected", this, "_files_list_rmb_select");
+ files->connect("item_selected", this, "_file_selected");
+ files->connect("multi_selected", this, "_file_multi_selected");
files->set_allow_rmb_select(true);
- file_list_vb = memnew( VBoxContainer );
+ file_list_vb = memnew(VBoxContainer);
split_box->add_child(file_list_vb);
file_list_vb->set_v_size_flags(SIZE_EXPAND_FILL);
- path_hb = memnew( HBoxContainer );
+ path_hb = memnew(HBoxContainer);
file_list_vb->add_child(path_hb);
- button_back = memnew( ToolButton );
+ button_back = memnew(ToolButton);
path_hb->add_child(button_back);
button_back->hide();
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
path_hb->add_child(search_box);
- search_box->connect("text_changed",this,"_search_changed");
+ search_box->connect("text_changed", this, "_search_changed");
- search_icon = memnew( TextureRect );
+ search_icon = memnew(TextureRect);
search_icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
path_hb->add_child(search_icon);
- button_display_mode = memnew( ToolButton );
+ button_display_mode = memnew(ToolButton);
path_hb->add_child(button_display_mode);
button_display_mode->set_toggle_mode(true);
file_list_vb->add_child(files);
-
- scanning_vb = memnew( VBoxContainer );
- Label *slabel = memnew( Label );
+ scanning_vb = memnew(VBoxContainer);
+ Label *slabel = memnew(Label);
slabel->set_text("Scanning Files,\nPlease Wait..");
slabel->set_align(Label::ALIGN_CENTER);
scanning_vb->add_child(slabel);
- scanning_progress = memnew( ProgressBar );
+ scanning_progress = memnew(ProgressBar);
scanning_vb->add_child(scanning_progress);
add_child(scanning_vb);
scanning_vb->hide();
-
-
- deps_editor = memnew( DependencyEditor );
+ deps_editor = memnew(DependencyEditor);
add_child(deps_editor);
- owners_editor = memnew( DependencyEditorOwners);
+ owners_editor = memnew(DependencyEditorOwners);
add_child(owners_editor);
- remove_dialog = memnew( DependencyRemoveDialog);
+ remove_dialog = memnew(DependencyRemoveDialog);
add_child(remove_dialog);
- move_dialog = memnew( EditorDirDialog );
+ move_dialog = memnew(EditorDirDialog);
add_child(move_dialog);
- move_dialog->connect("dir_selected",this,"_move_operation");
+ move_dialog->connect("dir_selected", this, "_move_operation");
move_dialog->get_ok()->set_text(TTR("Move"));
- rename_dialog = memnew( EditorFileDialog );
+ rename_dialog = memnew(EditorFileDialog);
rename_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
- rename_dialog->connect("file_selected",this,"_rename_operation");
+ rename_dialog->connect("file_selected", this, "_rename_operation");
add_child(rename_dialog);
- updating_tree=false;
- initialized=false;
+ updating_tree = false;
+ initialized = false;
history.push_back("res://");
- history_pos=0;
+ history_pos = 0;
- split_mode=false;
+ split_mode = false;
display_mode = DISPLAY_THUMBNAILS;
- path="res://";
-
+ path = "res://";
- add_constant_override("separation",3);
+ add_constant_override("separation", 3);
}
FileSystemDock::~FileSystemDock() {
-
}
diff --git a/editor/filesystem_dock.h b/editor/filesystem_dock.h
index 916321d8fd..1a4b5ae977 100644
--- a/editor/filesystem_dock.h
+++ b/editor/filesystem_dock.h
@@ -29,36 +29,36 @@
#ifndef FILESYSTEM_DOCK_H
#define FILESYSTEM_DOCK_H
-#include "scene/main/timer.h"
+#include "scene/gui/box_container.h"
#include "scene/gui/control.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/item_list.h"
#include "scene/gui/label.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/option_button.h"
-#include "scene/gui/box_container.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/item_list.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/progress_bar.h"
#include "scene/gui/split_container.h"
+#include "scene/gui/tool_button.h"
+#include "scene/gui/tree.h"
+#include "scene/main/timer.h"
#include "os/dir_access.h"
#include "os/thread.h"
-#include "editor_file_system.h"
-#include "editor_dir_dialog.h"
#include "dependency_editor.h"
+#include "editor_dir_dialog.h"
+#include "editor_file_system.h"
class EditorNode;
-
class FileSystemDock : public VBoxContainer {
- GDCLASS( FileSystemDock, VBoxContainer );
+ GDCLASS(FileSystemDock, VBoxContainer);
public:
enum DisplayMode {
DISPLAY_THUMBNAILS,
DISPLAY_LIST
};
+
private:
enum FileMenu {
FILE_OPEN,
@@ -78,7 +78,6 @@ private:
FOLDER_COLLAPSE_ALL
};
-
VBoxContainer *scanning_vb;
ProgressBar *scanning_progress;
VSplitContainer *split_box;
@@ -114,7 +113,6 @@ private:
Vector<String> move_dirs;
Vector<String> move_files;
-
Vector<String> history;
int history_pos;
@@ -123,26 +121,23 @@ private:
bool initialized;
bool updating_tree;
- Tree * tree; //directories
+ Tree *tree; //directories
ItemList *files;
-
void _file_multi_selected(int p_index, bool p_selected);
void _file_selected();
-
void _go_to_tree();
- void _go_to_dir(const String& p_dir);
+ void _go_to_dir(const String &p_dir);
void _select_file(int p_idx);
- bool _create_tree(TreeItem *p_parent,EditorFileSystemDirectory *p_dir);
- void _thumbnail_done(const String& p_path,const Ref<Texture>& p_preview, const Variant& p_udata);
- void _find_inside_move_files(EditorFileSystemDirectory *efsd,Vector<String>& files);
- void _find_remaps(EditorFileSystemDirectory *efsd,Map<String,String> &renames,List<String>& to_remaps);
-
- void _rename_operation(const String& p_to_path);
- void _move_operation(const String& p_to_path);
+ bool _create_tree(TreeItem *p_parent, EditorFileSystemDirectory *p_dir);
+ void _thumbnail_done(const String &p_path, const Ref<Texture> &p_preview, const Variant &p_udata);
+ void _find_inside_move_files(EditorFileSystemDirectory *efsd, Vector<String> &files);
+ void _find_remaps(EditorFileSystemDirectory *efsd, Map<String, String> &renames, List<String> &to_remaps);
+ void _rename_operation(const String &p_to_path);
+ void _move_operation(const String &p_to_path);
void _file_option(int p_option);
void _folder_option(int p_option);
@@ -154,21 +149,17 @@ private:
void _bw_history();
void _push_to_history();
-
void _dir_selected();
void _update_tree();
void _rescan();
void _set_scanning_mode();
-
void _favorites_pressed();
void _open_pressed();
- void _dir_rmb_pressed(const Vector2& local_mouse_pos);
- void _search_changed(const String& p_text);
-
-
- void _files_list_rmb_select(int p_item,const Vector2& p_pos);
+ void _dir_rmb_pressed(const Vector2 &local_mouse_pos);
+ void _search_changed(const String &p_text);
+ void _files_list_rmb_select(int p_item, const Vector2 &p_pos);
struct FileInfo {
String name;
@@ -177,41 +168,40 @@ private:
int import_status; //0 not imported, 1 - ok, 2- must reimport, 3- broken
Vector<String> sources;
- bool operator<(const FileInfo& fi) const {
+ bool operator<(const FileInfo &fi) const {
return name < fi.name;
}
};
- void _search(EditorFileSystemDirectory *p_path, List<FileInfo>* matches, int p_max_items);
+ void _search(EditorFileSystemDirectory *p_path, List<FileInfo> *matches, int p_max_items);
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
- void _preview_invalidated(const String& p_path);
+ void _preview_invalidated(const String &p_path);
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
String get_selected_path() const;
String get_current_path() const;
- void navigate_to_path(const String& p_path);
+ void navigate_to_path(const String &p_path);
void focus_on_filter();
- void fix_dependencies(const String& p_for_file);
+ void fix_dependencies(const String &p_for_file);
void set_display_mode(int p_mode);
int get_split_offset() { return split_box->get_split_offset(); }
void set_split_offset(int p_offset) { split_box->set_split_offset(p_offset); }
- void select_file(const String& p_file);
+ void select_file(const String &p_file);
FileSystemDock(EditorNode *p_editor);
~FileSystemDock();
};
-
#endif // SCENES_DOCK_H
diff --git a/editor/groups_editor.cpp b/editor/groups_editor.cpp
index 90f0bab6dd..c9e9acd7f2 100644
--- a/editor/groups_editor.cpp
+++ b/editor/groups_editor.cpp
@@ -28,18 +28,18 @@
/*************************************************************************/
#include "groups_editor.h"
+#include "editor_node.h"
#include "scene/gui/box_container.h"
#include "scene/gui/label.h"
-#include "editor_node.h"
#include "scene/resources/packed_scene.h"
-void GroupsEditor::_add_group(const String& p_group) {
+void GroupsEditor::_add_group(const String &p_group) {
if (!node)
return;
String name = group_name->get_text();
- if (name.strip_edges()=="")
+ if (name.strip_edges() == "")
return;
if (node->is_in_group(name))
@@ -47,12 +47,12 @@ void GroupsEditor::_add_group(const String& p_group) {
undo_redo->create_action(TTR("Add to Group"));
- undo_redo->add_do_method(node,"add_to_group",name,true);
- undo_redo->add_do_method(this,"update_tree");
- undo_redo->add_undo_method(node,"remove_from_group",name);
- undo_redo->add_undo_method(this,"update_tree");
- undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
- undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
+ undo_redo->add_do_method(node, "add_to_group", name, true);
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(node, "remove_from_group", name);
+ undo_redo->add_undo_method(this, "update_tree");
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
@@ -72,19 +72,19 @@ void GroupsEditor::_remove_group(Object *p_item, int p_column, int p_id) {
undo_redo->create_action(TTR("Remove from Group"));
- undo_redo->add_do_method(node,"remove_from_group",name);
- undo_redo->add_do_method(this,"update_tree");
- undo_redo->add_undo_method(node,"add_to_group",name,true);
- undo_redo->add_undo_method(this,"update_tree");
- undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
- undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(),"update_tree"); //to force redraw of scene tree
+ undo_redo->add_do_method(node, "remove_from_group", name);
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(node, "add_to_group", name, true);
+ undo_redo->add_undo_method(this, "update_tree");
+ undo_redo->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
+ undo_redo->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock()->get_tree_editor(), "update_tree"); //to force redraw of scene tree
undo_redo->commit_action();
}
struct _GroupInfoComparator {
- bool operator()(const Node::GroupInfo& p_a, const Node::GroupInfo& p_b) const {
+ bool operator()(const Node::GroupInfo &p_a, const Node::GroupInfo &p_b) const {
return p_a.name.operator String() < p_b.name.operator String();
}
};
@@ -100,89 +100,83 @@ void GroupsEditor::update_tree() {
node->get_groups(&groups);
groups.sort_custom<_GroupInfoComparator>();
- TreeItem *root=tree->create_item();
+ TreeItem *root = tree->create_item();
- for(List<GroupInfo>::Element *E=groups.front();E;E=E->next()) {
+ for (List<GroupInfo>::Element *E = groups.front(); E; E = E->next()) {
Node::GroupInfo gi = E->get();
if (!gi.persistent)
continue;
Node *n = node;
- bool can_be_deleted=true;
+ bool can_be_deleted = true;
- while(n) {
+ while (n) {
- Ref<SceneState> ss = (n==EditorNode::get_singleton()->get_edited_scene()) ? n->get_scene_inherited_state() : n->get_scene_instance_state();
+ Ref<SceneState> ss = (n == EditorNode::get_singleton()->get_edited_scene()) ? n->get_scene_inherited_state() : n->get_scene_instance_state();
if (ss.is_valid()) {
int path = ss->find_node_by_path(n->get_path_to(node));
- if (path!=-1) {
- if (ss->is_node_in_group(path,gi.name)) {
- can_be_deleted=false;
+ if (path != -1) {
+ if (ss->is_node_in_group(path, gi.name)) {
+ can_be_deleted = false;
}
}
}
- n=n->get_owner();
+ n = n->get_owner();
}
-
- TreeItem *item=tree->create_item(root);
+ TreeItem *item = tree->create_item(root);
item->set_text(0, gi.name);
if (can_be_deleted) {
item->add_button(0, get_icon("Remove", "EditorIcons"), 0);
} else {
- item->set_selectable(0,false);
+ item->set_selectable(0, false);
}
-
}
}
-void GroupsEditor::set_current(Node* p_node) {
+void GroupsEditor::set_current(Node *p_node) {
- node=p_node;
+ node = p_node;
update_tree();
}
void GroupsEditor::_bind_methods() {
- ClassDB::bind_method("_add_group",&GroupsEditor::_add_group);
- ClassDB::bind_method("_remove_group",&GroupsEditor::_remove_group);
- ClassDB::bind_method("update_tree",&GroupsEditor::update_tree);
+ ClassDB::bind_method("_add_group", &GroupsEditor::_add_group);
+ ClassDB::bind_method("_remove_group", &GroupsEditor::_remove_group);
+ ClassDB::bind_method("update_tree", &GroupsEditor::update_tree);
}
GroupsEditor::GroupsEditor() {
- node=NULL;
+ node = NULL;
VBoxContainer *vbc = this;
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
- group_name = memnew( LineEdit );
+ group_name = memnew(LineEdit);
group_name->set_h_size_flags(SIZE_EXPAND_FILL);
hbc->add_child(group_name);
- group_name->connect("text_entered",this,"_add_group");
+ group_name->connect("text_entered", this, "_add_group");
- add = memnew( Button );
+ add = memnew(Button);
add->set_text(TTR("Add"));
hbc->add_child(add);
- add->connect("pressed", this,"_add_group", varray(String()));
+ add->connect("pressed", this, "_add_group", varray(String()));
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_hide_root(true);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(tree);
- tree->connect("button_pressed",this,"_remove_group");
- add_constant_override("separation",3*EDSCALE);
+ tree->connect("button_pressed", this, "_remove_group");
+ add_constant_override("separation", 3 * EDSCALE);
}
-GroupsEditor::~GroupsEditor()
-{
+GroupsEditor::~GroupsEditor() {
}
-
-
-
diff --git a/editor/groups_editor.h b/editor/groups_editor.h
index 9ab75c6cfd..2b27a3a70c 100644
--- a/editor/groups_editor.h
+++ b/editor/groups_editor.h
@@ -29,10 +29,10 @@
#ifndef GROUPS_EDITOR_H
#define GROUPS_EDITOR_H
-#include "scene/gui/dialogs.h"
#include "scene/gui/button.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/tree.h"
#include "undo_redo.h"
/**
@@ -41,7 +41,7 @@
class GroupsEditor : public VBoxContainer {
- GDCLASS(GroupsEditor,VBoxContainer);
+ GDCLASS(GroupsEditor, VBoxContainer);
Node *node;
@@ -52,16 +52,16 @@ class GroupsEditor : public VBoxContainer {
UndoRedo *undo_redo;
void update_tree();
- void _add_group(const String& p_group="");
+ void _add_group(const String &p_group = "");
void _remove_group(Object *p_item, int p_column, int p_id);
void _close();
-protected:
+protected:
static void _bind_methods();
-public:
- void set_undo_redo(UndoRedo *p_undoredo) { undo_redo=p_undoredo; }
- void set_current(Node* p_node);
+public:
+ void set_undo_redo(UndoRedo *p_undoredo) { undo_redo = p_undoredo; }
+ void set_current(Node *p_node);
GroupsEditor();
~GroupsEditor();
diff --git a/editor/import/editor_import_collada.cpp b/editor/import/editor_import_collada.cpp
index 7098e8812b..b4ce666e0c 100644
--- a/editor/import/editor_import_collada.cpp
+++ b/editor/import/editor_import_collada.cpp
@@ -28,22 +28,20 @@
/*************************************************************************/
#include "editor_import_collada.h"
-
-#include "scene/3d/spatial.h"
-#include "scene/3d/skeleton.h"
-#include "scene/3d/path.h"
+#include "editor/collada/collada.h"
+#include "editor/editor_node.h"
+#include "os/os.h"
#include "scene/3d/camera.h"
#include "scene/3d/light.h"
-#include "scene/animation/animation_player.h"
#include "scene/3d/mesh_instance.h"
+#include "scene/3d/path.h"
+#include "scene/3d/skeleton.h"
+#include "scene/3d/spatial.h"
+#include "scene/animation/animation_player.h"
#include "scene/resources/animation.h"
#include "scene/resources/packed_scene.h"
-#include "os/os.h"
-#include "editor/collada/collada.h"
-#include "editor/editor_node.h"
#include <iostream>
-
struct ColladaImport {
Collada collada;
@@ -57,7 +55,10 @@ struct ColladaImport {
int bone;
List<int> anim_tracks;
- NodeMap() { node=NULL; bone=-1; }
+ NodeMap() {
+ node = NULL;
+ bone = -1;
+ }
};
bool found_ambient;
@@ -68,30 +69,28 @@ struct ColladaImport {
bool use_mesh_builtin_materials;
float bake_fps;
-
-
- Map<String,NodeMap> node_map; //map from collada node to engine node
- Map<String,String> node_name_map; //map from collada node to engine node
+ Map<String, NodeMap> node_map; //map from collada node to engine node
+ Map<String, String> node_name_map; //map from collada node to engine node
Map<String, Ref<Mesh> > mesh_cache;
Map<String, Ref<Curve3D> > curve_cache;
Map<String, Ref<Material> > material_cache;
- Map<Collada::Node*,Skeleton*> skeleton_map;
+ Map<Collada::Node *, Skeleton *> skeleton_map;
- Map< Skeleton*, Map< String, int> > skeleton_bone_map;
+ Map<Skeleton *, Map<String, int> > skeleton_bone_map;
Set<String> valid_animated_nodes;
Vector<int> valid_animated_properties;
- Map<String,bool> bones_with_animation;
+ Map<String, bool> bones_with_animation;
- Error _populate_skeleton(Skeleton *p_skeleton,Collada::Node *p_node, int &r_bone, int p_parent);
+ Error _populate_skeleton(Skeleton *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent);
Error _create_scene_skeletons(Collada::Node *p_node);
Error _create_scene(Collada::Node *p_node, Spatial *p_parent);
Error _create_resources(Collada::Node *p_node);
- Error _create_material(const String& p_material);
- Error _create_mesh_surfaces(bool p_optimize, Ref<Mesh>& p_mesh, const Map<String,Collada::NodeGeometry::Material>& p_material_map, const Collada::MeshData &meshdata, const Transform& p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_data, const Collada::MorphControllerData *p_morph_data, Vector<Ref<Mesh> > p_morph_meshes=Vector<Ref<Mesh> >(), bool p_for_morph=false, bool p_use_mesh_material=false);
- Error load(const String& p_path, int p_flags, bool p_force_make_tangents=false);
+ Error _create_material(const String &p_material);
+ Error _create_mesh_surfaces(bool p_optimize, Ref<Mesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_data, const Collada::MorphControllerData *p_morph_data, Vector<Ref<Mesh> > p_morph_meshes = Vector<Ref<Mesh> >(), bool p_for_morph = false, bool p_use_mesh_material = false);
+ Error load(const String &p_path, int p_flags, bool p_force_make_tangents = false);
void _fix_param_animation_tracks();
- void create_animation(int p_clip,bool p_make_tracks_in_all_bones, bool p_import_value_tracks);
+ void create_animation(int p_clip, bool p_make_tracks_in_all_bones, bool p_import_value_tracks);
void create_animations(bool p_make_tracks_in_all_bones, bool p_import_value_tracks);
Set<String> tracks_in_clips;
@@ -101,51 +100,47 @@ struct ColladaImport {
ColladaImport() {
- found_ambient=false;
- found_directional=false;
- force_make_tangents=false;
- apply_mesh_xform_to_vertices=true;
- bake_fps=15;
-
+ found_ambient = false;
+ found_directional = false;
+ force_make_tangents = false;
+ apply_mesh_xform_to_vertices = true;
+ bake_fps = 15;
}
};
+Error ColladaImport::_populate_skeleton(Skeleton *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent) {
-Error ColladaImport::_populate_skeleton(Skeleton *p_skeleton,Collada::Node *p_node, int &r_bone, int p_parent) {
-
-
- if (p_node->type!=Collada::Node::TYPE_JOINT)
+ if (p_node->type != Collada::Node::TYPE_JOINT)
return OK;
- Collada::NodeJoint *joint = static_cast<Collada::NodeJoint*>(p_node);
+ Collada::NodeJoint *joint = static_cast<Collada::NodeJoint *>(p_node);
- print_line("populating joint "+joint->name);
+ print_line("populating joint " + joint->name);
p_skeleton->add_bone(p_node->name);
- if (p_parent>=0)
- p_skeleton->set_bone_parent(r_bone,p_parent);
+ if (p_parent >= 0)
+ p_skeleton->set_bone_parent(r_bone, p_parent);
NodeMap nm;
- nm.node=p_skeleton;
+ nm.node = p_skeleton;
nm.bone = r_bone;
- node_map[p_node->id]=nm;
- node_name_map[p_node->name]=p_node->id;
+ node_map[p_node->id] = nm;
+ node_name_map[p_node->name] = p_node->id;
- skeleton_bone_map[p_skeleton][joint->sid]=r_bone;
+ skeleton_bone_map[p_skeleton][joint->sid] = r_bone;
if (collada.state.bone_rest_map.has(joint->sid)) {
- p_skeleton->set_bone_rest(r_bone,collada.fix_transform(collada.state.bone_rest_map[joint->sid]));
+ p_skeleton->set_bone_rest(r_bone, collada.fix_transform(collada.state.bone_rest_map[joint->sid]));
//should map this bone to something for animation?
} else {
- print_line("no rest: "+joint->sid);
+ print_line("no rest: " + joint->sid);
WARN_PRINT("Joint has no rest..");
}
-
int id = r_bone++;
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
- Error err = _populate_skeleton(p_skeleton,p_node->children[i],r_bone,id);
+ Error err = _populate_skeleton(p_skeleton, p_node->children[i], r_bone, id);
if (err)
return err;
}
@@ -153,70 +148,61 @@ Error ColladaImport::_populate_skeleton(Skeleton *p_skeleton,Collada::Node *p_no
return OK;
}
-
void ColladaImport::_pre_process_lights(Collada::Node *p_node) {
+ if (p_node->type == Collada::Node::TYPE_LIGHT) {
- if (p_node->type==Collada::Node::TYPE_LIGHT) {
-
-
- Collada::NodeLight *light=static_cast<Collada::NodeLight*>(p_node);
+ Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
if (collada.state.light_data_map.has(light->light)) {
Collada::LightData &ld = collada.state.light_data_map[light->light];
- if (ld.mode==Collada::LightData::MODE_AMBIENT) {
- found_ambient=true;
- ambient=ld.color;
+ if (ld.mode == Collada::LightData::MODE_AMBIENT) {
+ found_ambient = true;
+ ambient = ld.color;
}
- if (ld.mode==Collada::LightData::MODE_DIRECTIONAL) {
- found_directional=true;
+ if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
+ found_directional = true;
}
}
-
}
-
- for(int i=0;i<p_node->children.size();i++)
+ for (int i = 0; i < p_node->children.size(); i++)
_pre_process_lights(p_node->children[i]);
}
Error ColladaImport::_create_scene_skeletons(Collada::Node *p_node) {
+ if (p_node->type == Collada::Node::TYPE_SKELETON) {
- if (p_node->type==Collada::Node::TYPE_SKELETON) {
-
- Skeleton *sk = memnew( Skeleton );
+ Skeleton *sk = memnew(Skeleton);
int bone = 0;
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
- _populate_skeleton(sk,p_node->children[i],bone,-1);
+ _populate_skeleton(sk, p_node->children[i], bone, -1);
}
sk->localize_rests(); //after creating skeleton, rests must be localized...!
- skeleton_map[p_node]=sk;
+ skeleton_map[p_node] = sk;
}
-
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
Error err = _create_scene_skeletons(p_node->children[i]);
if (err)
return err;
}
return OK;
-
}
-
Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
- Spatial * node=NULL;
+ Spatial *node = NULL;
- switch(p_node->type) {
+ switch (p_node->type) {
case Collada::Node::TYPE_NODE: {
- node = memnew( Spatial );
+ node = memnew(Spatial);
} break;
case Collada::Node::TYPE_JOINT: {
@@ -225,29 +211,29 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
case Collada::Node::TYPE_LIGHT: {
//node = memnew( Light)
- Collada::NodeLight *light = static_cast<Collada::NodeLight*>(p_node);
+ Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
if (collada.state.light_data_map.has(light->light)) {
Collada::LightData &ld = collada.state.light_data_map[light->light];
- if (ld.mode==Collada::LightData::MODE_AMBIENT) {
+ if (ld.mode == Collada::LightData::MODE_AMBIENT) {
if (found_directional)
return OK; //do nothing not needed
- if (!bool(GLOBAL_DEF("collada/use_ambient",false)))
+ if (!bool(GLOBAL_DEF("collada/use_ambient", false)))
return OK;
//well, it's an ambient light..
- Light *l = memnew( DirectionalLight );
+ Light *l = memnew(DirectionalLight);
//l->set_color(Light::COLOR_AMBIENT,ld.color);
//l->set_color(Light::COLOR_DIFFUSE,Color(0,0,0));
//l->set_color(Light::COLOR_SPECULAR,Color(0,0,0));
node = l;
- } else if (ld.mode==Collada::LightData::MODE_DIRECTIONAL) {
+ } else if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
//well, it's an ambient light..
- Light *l = memnew( DirectionalLight );
+ Light *l = memnew(DirectionalLight);
/*
if (found_ambient) //use it here
l->set_color(Light::COLOR_AMBIENT,ambient);
@@ -260,10 +246,10 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
Light *l;
- if (ld.mode==Collada::LightData::MODE_OMNI)
- l=memnew( OmniLight );
+ if (ld.mode == Collada::LightData::MODE_OMNI)
+ l = memnew(OmniLight);
else {
- l=memnew( SpotLight );
+ l = memnew(SpotLight);
//l->set_parameter(Light::PARAM_SPOT_ANGLE,ld.spot_angle);
//l->set_parameter(Light::PARAM_SPOT_ATTENUATION,ld.spot_exp);
}
@@ -272,37 +258,36 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
//l->set_color(Light::COLOR_DIFFUSE,ld.color);
//l->set_color(Light::COLOR_SPECULAR,Color(1,1,1));
//l->approximate_opengl_attenuation(ld.constant_att,ld.linear_att,ld.quad_att);
- node=l;
+ node = l;
}
} else {
- node = memnew( Spatial );
+ node = memnew(Spatial);
}
} break;
case Collada::Node::TYPE_CAMERA: {
- Collada::NodeCamera *cam = static_cast<Collada::NodeCamera*>(p_node);
- Camera *camera = memnew( Camera );
+ Collada::NodeCamera *cam = static_cast<Collada::NodeCamera *>(p_node);
+ Camera *camera = memnew(Camera);
if (collada.state.camera_data_map.has(cam->camera)) {
const Collada::CameraData &cd = collada.state.camera_data_map[cam->camera];
- switch(cd.mode) {
+ switch (cd.mode) {
case Collada::CameraData::MODE_ORTHOGONAL: {
if (cd.orthogonal.y_mag) {
camera->set_keep_aspect_mode(Camera::KEEP_HEIGHT);
- camera->set_orthogonal(cd.orthogonal.y_mag*2.0 ,cd.z_near,cd.z_far);
+ camera->set_orthogonal(cd.orthogonal.y_mag * 2.0, cd.z_near, cd.z_far);
} else if (!cd.orthogonal.y_mag && cd.orthogonal.x_mag) {
-
camera->set_keep_aspect_mode(Camera::KEEP_WIDTH);
- camera->set_orthogonal(cd.orthogonal.x_mag*2.0,cd.z_near,cd.z_far);
+ camera->set_orthogonal(cd.orthogonal.x_mag * 2.0, cd.z_near, cd.z_far);
}
} break;
@@ -310,97 +295,94 @@ Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
if (cd.perspective.y_fov) {
- camera->set_perspective(cd.perspective.y_fov,cd.z_near,cd.z_far);
+ camera->set_perspective(cd.perspective.y_fov, cd.z_near, cd.z_far);
} else if (!cd.perspective.y_fov && cd.perspective.x_fov) {
- camera->set_perspective(cd.perspective.x_fov / cd.aspect,cd.z_near,cd.z_far);
+ camera->set_perspective(cd.perspective.x_fov / cd.aspect, cd.z_near, cd.z_far);
}
} break;
}
-
}
- node=camera;
+ node = camera;
} break;
case Collada::Node::TYPE_GEOMETRY: {
- Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry*>(p_node);
+ Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
if (collada.state.curve_data_map.has(ng->source)) {
- node = memnew( Path );
+ node = memnew(Path);
} else {
//mesh since nothing else
- node = memnew( MeshInstance );
- node->cast_to<MeshInstance>()->set_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT,true);
+ node = memnew(MeshInstance);
+ node->cast_to<MeshInstance>()->set_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT, true);
}
} break;
case Collada::Node::TYPE_SKELETON: {
- ERR_FAIL_COND_V(!skeleton_map.has(p_node),ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!skeleton_map.has(p_node), ERR_CANT_CREATE);
Skeleton *sk = skeleton_map[p_node];
- node=sk;
+ node = sk;
} break;
-
}
- if (p_node->name!="")
+ if (p_node->name != "")
node->set_name(p_node->name);
NodeMap nm;
- nm.node=node;
- node_map[p_node->id]=nm;
- node_name_map[p_node->name]=p_node->id;
+ nm.node = node;
+ node_map[p_node->id] = nm;
+ node_name_map[p_node->name] = p_node->id;
Transform xf = p_node->default_transform;
- xf = collada.fix_transform( xf ) * p_node->post_transform;
+ xf = collada.fix_transform(xf) * p_node->post_transform;
node->set_transform(xf);
p_parent->add_child(node);
node->set_owner(scene);
- if (p_node->empty_draw_type!="") {
+ if (p_node->empty_draw_type != "") {
node->set_meta("empty_draw_type", Variant(p_node->empty_draw_type));
}
-
- for(int i=0;i<p_node->children.size();i++) {
- Error err = _create_scene(p_node->children[i],node);
+ for (int i = 0; i < p_node->children.size(); i++) {
+
+ Error err = _create_scene(p_node->children[i], node);
if (err)
return err;
}
return OK;
}
+Error ColladaImport::_create_material(const String &p_target) {
-Error ColladaImport::_create_material(const String& p_target) {
+ ERR_FAIL_COND_V(material_cache.has(p_target), ERR_ALREADY_EXISTS);
+ ERR_FAIL_COND_V(!collada.state.material_map.has(p_target), ERR_INVALID_PARAMETER);
+ Collada::Material &src_mat = collada.state.material_map[p_target];
+ ERR_FAIL_COND_V(!collada.state.effect_map.has(src_mat.instance_effect), ERR_INVALID_PARAMETER);
+ Collada::Effect &effect = collada.state.effect_map[src_mat.instance_effect];
- ERR_FAIL_COND_V(material_cache.has(p_target),ERR_ALREADY_EXISTS);
- ERR_FAIL_COND_V(!collada.state.material_map.has(p_target),ERR_INVALID_PARAMETER);
- Collada::Material &src_mat=collada.state.material_map[p_target];
- ERR_FAIL_COND_V(!collada.state.effect_map.has(src_mat.instance_effect),ERR_INVALID_PARAMETER);
- Collada::Effect &effect=collada.state.effect_map[src_mat.instance_effect];
+ Ref<FixedSpatialMaterial> material = memnew(FixedSpatialMaterial);
- Ref<FixedSpatialMaterial> material= memnew( FixedSpatialMaterial );
-
- if (src_mat.name!="")
+ if (src_mat.name != "")
material->set_name(src_mat.name);
- else if (effect.name!="")
+ else if (effect.name != "")
material->set_name(effect.name);
// DIFFUSE
- if (effect.diffuse.texture!="") {
+ if (effect.diffuse.texture != "") {
- String texfile = effect.get_texture_path(effect.diffuse.texture,collada);
- if (texfile!="") {
+ String texfile = effect.get_texture_path(effect.diffuse.texture, collada);
+ if (texfile != "") {
- Ref<Texture> texture = ResourceLoader::load(texfile,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
if (texture.is_valid()) {
- material->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,texture);
- material->set_albedo(Color(1,1,1,1));
+ material->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, texture);
+ material->set_albedo(Color(1, 1, 1, 1));
//material->set_parameter(FixedSpatialMaterial::PARAM_DIFFUSE,Color(1,1,1,1));
} else {
missing_textures.push_back(texfile.get_file());
@@ -412,154 +394,140 @@ Error ColladaImport::_create_material(const String& p_target) {
// SPECULAR
- if (effect.specular.texture!="") {
+ if (effect.specular.texture != "") {
- String texfile = effect.get_texture_path(effect.specular.texture,collada);
- if (texfile!="") {
+ String texfile = effect.get_texture_path(effect.specular.texture, collada);
+ if (texfile != "") {
- Ref<Texture> texture = ResourceLoader::load(texfile,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
if (texture.is_valid()) {
- material->set_texture(FixedSpatialMaterial::TEXTURE_SPECULAR,texture);
- material->set_specular(Color(1,1,1,1));
+ material->set_texture(FixedSpatialMaterial::TEXTURE_SPECULAR, texture);
+ material->set_specular(Color(1, 1, 1, 1));
//material->set_texture(FixedSpatialMaterial::PARAM_SPECULAR,texture);
//material->set_parameter(FixedSpatialMaterial::PARAM_SPECULAR,Color(1,1,1,1));
} else {
missing_textures.push_back(texfile.get_file());
}
-
}
} else {
material->set_metalness(effect.specular.color.get_v());
}
-
// EMISSION
- if (effect.emission.texture!="") {
+ if (effect.emission.texture != "") {
- String texfile = effect.get_texture_path(effect.emission.texture,collada);
- if (texfile!="") {
+ String texfile = effect.get_texture_path(effect.emission.texture, collada);
+ if (texfile != "") {
- Ref<Texture> texture = ResourceLoader::load(texfile,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
if (texture.is_valid()) {
- material->set_feature(FixedSpatialMaterial::FEATURE_EMISSION,true);
- material->set_texture(FixedSpatialMaterial::TEXTURE_EMISSION,texture);
- material->set_emission(Color(1,1,1,1));
+ material->set_feature(FixedSpatialMaterial::FEATURE_EMISSION, true);
+ material->set_texture(FixedSpatialMaterial::TEXTURE_EMISSION, texture);
+ material->set_emission(Color(1, 1, 1, 1));
//material->set_parameter(FixedSpatialMaterial::PARAM_EMISSION,Color(1,1,1,1));
- }else {
+ } else {
missing_textures.push_back(texfile.get_file());
}
-
}
} else {
- if (effect.emission.color!=Color()) {
- material->set_feature(FixedSpatialMaterial::FEATURE_EMISSION,true);
+ if (effect.emission.color != Color()) {
+ material->set_feature(FixedSpatialMaterial::FEATURE_EMISSION, true);
material->set_emission(effect.emission.color);
}
}
// NORMAL
- if (effect.bump.texture!="") {
+ if (effect.bump.texture != "") {
- String texfile = effect.get_texture_path(effect.bump.texture,collada);
- if (texfile!="") {
+ String texfile = effect.get_texture_path(effect.bump.texture, collada);
+ if (texfile != "") {
- Ref<Texture> texture = ResourceLoader::load(texfile,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
if (texture.is_valid()) {
- material->set_feature(FixedSpatialMaterial::FEATURE_NORMAL_MAPPING,true);
- material->set_texture(FixedSpatialMaterial::TEXTURE_NORMAL,texture);
+ material->set_feature(FixedSpatialMaterial::FEATURE_NORMAL_MAPPING, true);
+ material->set_texture(FixedSpatialMaterial::TEXTURE_NORMAL, texture);
//material->set_emission(Color(1,1,1,1));
//material->set_texture(FixedSpatialMaterial::PARAM_NORMAL,texture);
- }else {
+ } else {
//missing_textures.push_back(texfile.get_file());
}
-
}
}
-
- float roughness = Math::sqrt(1.0-((Math::log(effect.shininess)/Math::log(2.0))/8.0)); //not very right..
+ float roughness = Math::sqrt(1.0 - ((Math::log(effect.shininess) / Math::log(2.0)) / 8.0)); //not very right..
material->set_roughness(roughness);
if (effect.double_sided) {
material->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
}
- material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,effect.unshaded);
-
+ material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, effect.unshaded);
-
- material_cache[p_target]=material;
+ material_cache[p_target] = material;
return OK;
}
-
-static void _generate_normals(const PoolVector<int>& p_indices,const PoolVector<Vector3>& p_vertices,PoolVector<Vector3>&r_normals) {
-
+static void _generate_normals(const PoolVector<int> &p_indices, const PoolVector<Vector3> &p_vertices, PoolVector<Vector3> &r_normals) {
r_normals.resize(p_vertices.size());
PoolVector<Vector3>::Write narrayw = r_normals.write();
- int iacount=p_indices.size()/3;
+ int iacount = p_indices.size() / 3;
PoolVector<int>::Read index_arrayr = p_indices.read();
PoolVector<Vector3>::Read vertex_arrayr = p_vertices.read();
- for(int idx=0;idx<iacount;idx++) {
+ for (int idx = 0; idx < iacount; idx++) {
- Vector3 v[3]={
- vertex_arrayr[index_arrayr[idx*3+0]],
- vertex_arrayr[index_arrayr[idx*3+1]],
- vertex_arrayr[index_arrayr[idx*3+2]]
+ Vector3 v[3] = {
+ vertex_arrayr[index_arrayr[idx * 3 + 0]],
+ vertex_arrayr[index_arrayr[idx * 3 + 1]],
+ vertex_arrayr[index_arrayr[idx * 3 + 2]]
};
- Vector3 normal = Plane(v[0],v[1],v[2]).normal;
+ Vector3 normal = Plane(v[0], v[1], v[2]).normal;
- narrayw[index_arrayr[idx*3+0]]+=normal;
- narrayw[index_arrayr[idx*3+1]]+=normal;
- narrayw[index_arrayr[idx*3+2]]+=normal;
+ narrayw[index_arrayr[idx * 3 + 0]] += normal;
+ narrayw[index_arrayr[idx * 3 + 1]] += normal;
+ narrayw[index_arrayr[idx * 3 + 2]] += normal;
}
- int vlen=p_vertices.size();
+ int vlen = p_vertices.size();
- for(int idx=0;idx<vlen;idx++) {
+ for (int idx = 0; idx < vlen; idx++) {
narrayw[idx].normalize();
}
-
}
+static void _generate_tangents_and_binormals(const PoolVector<int> &p_indices, const PoolVector<Vector3> &p_vertices, const PoolVector<Vector3> &p_uvs, const PoolVector<Vector3> &p_normals, PoolVector<real_t> &r_tangents) {
-static void _generate_tangents_and_binormals(const PoolVector<int>& p_indices,const PoolVector<Vector3>& p_vertices,const PoolVector<Vector3>& p_uvs,const PoolVector<Vector3>& p_normals,PoolVector<real_t>&r_tangents) {
-
- int vlen=p_vertices.size();
+ int vlen = p_vertices.size();
Vector<Vector3> tangents;
tangents.resize(vlen);
Vector<Vector3> binormals;
binormals.resize(vlen);
-
- int iacount=p_indices.size()/3;
+ int iacount = p_indices.size() / 3;
PoolVector<int>::Read index_arrayr = p_indices.read();
PoolVector<Vector3>::Read vertex_arrayr = p_vertices.read();
PoolVector<Vector3>::Read narrayr = p_normals.read();
PoolVector<Vector3>::Read uvarrayr = p_uvs.read();
+ for (int idx = 0; idx < iacount; idx++) {
- for(int idx=0;idx<iacount;idx++) {
+ Vector3 v1 = vertex_arrayr[index_arrayr[idx * 3 + 0]];
+ Vector3 v2 = vertex_arrayr[index_arrayr[idx * 3 + 1]];
+ Vector3 v3 = vertex_arrayr[index_arrayr[idx * 3 + 2]];
-
- Vector3 v1 = vertex_arrayr[ index_arrayr[idx*3+0] ];
- Vector3 v2 = vertex_arrayr[ index_arrayr[idx*3+1] ];
- Vector3 v3 = vertex_arrayr[ index_arrayr[idx*3+2] ];
-
- Vector3 w1 = uvarrayr[ index_arrayr[idx*3+0] ];
- Vector3 w2 = uvarrayr[ index_arrayr[idx*3+1] ];
- Vector3 w3 = uvarrayr[ index_arrayr[idx*3+2] ];
+ Vector3 w1 = uvarrayr[index_arrayr[idx * 3 + 0]];
+ Vector3 w2 = uvarrayr[index_arrayr[idx * 3 + 1]];
+ Vector3 w3 = uvarrayr[index_arrayr[idx * 3 + 2]];
real_t x1 = v2.x - v1.x;
real_t x2 = v3.x - v1.x;
@@ -573,169 +541,165 @@ static void _generate_tangents_and_binormals(const PoolVector<int>& p_indices,co
real_t t1 = w2.y - w1.y;
real_t t2 = w3.y - w1.y;
- real_t r = (s1 * t2 - s2 * t1);
+ real_t r = (s1 * t2 - s2 * t1);
Vector3 tangent;
Vector3 binormal;
- if (r==0) {
+ if (r == 0) {
- binormal=Vector3();
- tangent=Vector3();
+ binormal = Vector3();
+ tangent = Vector3();
} else {
tangent = Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
- (t2 * z1 - t1 * z2) * r).normalized();
+ (t2 * z1 - t1 * z2) * r)
+ .normalized();
binormal = Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
- (s1 * z2 - s2 * z1) * r).normalized();
+ (s1 * z2 - s2 * z1) * r)
+ .normalized();
}
- tangents[ index_arrayr[idx*3+0] ]+=tangent;
- binormals[ index_arrayr[idx*3+0] ]+=binormal;
- tangents[ index_arrayr[idx*3+1] ]+=tangent;
- binormals[ index_arrayr[idx*3+1] ]+=binormal;
- tangents[ index_arrayr[idx*3+2] ]+=tangent;
- binormals[ index_arrayr[idx*3+2] ]+=binormal;
+ tangents[index_arrayr[idx * 3 + 0]] += tangent;
+ binormals[index_arrayr[idx * 3 + 0]] += binormal;
+ tangents[index_arrayr[idx * 3 + 1]] += tangent;
+ binormals[index_arrayr[idx * 3 + 1]] += binormal;
+ tangents[index_arrayr[idx * 3 + 2]] += tangent;
+ binormals[index_arrayr[idx * 3 + 2]] += binormal;
//print_line(itos(idx)+" tangent: "+tangent);
//print_line(itos(idx)+" binormal: "+binormal);
}
- r_tangents.resize(vlen*4);
+ r_tangents.resize(vlen * 4);
PoolVector<real_t>::Write tarrayw = r_tangents.write();
- for(int idx=0;idx<vlen;idx++) {
+ for (int idx = 0; idx < vlen; idx++) {
Vector3 tangent = tangents[idx];
Vector3 bingen = narrayr[idx].cross(tangent);
float dir;
- if (bingen.dot(binormals[idx]) < 0 )
- dir=-1.0;
+ if (bingen.dot(binormals[idx]) < 0)
+ dir = -1.0;
else
- dir=+1.0;
+ dir = +1.0;
- tarrayw[idx*4+0]=tangent.x;
- tarrayw[idx*4+1]=tangent.y;
- tarrayw[idx*4+2]=tangent.z;
- tarrayw[idx*4+3]=dir;
+ tarrayw[idx * 4 + 0] = tangent.x;
+ tarrayw[idx * 4 + 1] = tangent.y;
+ tarrayw[idx * 4 + 2] = tangent.z;
+ tarrayw[idx * 4 + 3] = dir;
}
}
-Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,const Map<String,Collada::NodeGeometry::Material>& p_material_map,const Collada::MeshData &meshdata,const Transform& p_local_xform,const Vector<int> &bone_remap, const Collada::SkinControllerData *skin_controller, const Collada::MorphControllerData *p_morph_data,Vector<Ref<Mesh> > p_morph_meshes,bool p_for_morph,bool p_use_mesh_material) {
-
+Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<Mesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<Mesh> > p_morph_meshes, bool p_for_morph, bool p_use_mesh_material) {
- bool local_xform_mirror=p_local_xform.basis.determinant() < 0;
+ bool local_xform_mirror = p_local_xform.basis.determinant() < 0;
if (p_morph_data) {
//add morphie target
- ERR_FAIL_COND_V( !p_morph_data->targets.has("MORPH_TARGET"), ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!p_morph_data->targets.has("MORPH_TARGET"), ERR_INVALID_DATA);
String mt = p_morph_data->targets["MORPH_TARGET"];
- ERR_FAIL_COND_V( !p_morph_data->sources.has(mt), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!p_morph_data->sources.has(mt), ERR_INVALID_DATA);
int morph_targets = p_morph_data->sources[mt].sarray.size();
- for(int i=0;i<morph_targets;i++) {
+ for (int i = 0; i < morph_targets; i++) {
String target = p_morph_data->sources[mt].sarray[i];
- ERR_FAIL_COND_V( !collada.state.mesh_data_map.has(target), ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(target), ERR_INVALID_DATA);
String name = collada.state.mesh_data_map[target].name;
p_mesh->add_blend_shape(name);
}
- if (p_morph_data->mode=="RELATIVE")
+ if (p_morph_data->mode == "RELATIVE")
p_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_RELATIVE);
- else if (p_morph_data->mode=="NORMALIZED")
+ else if (p_morph_data->mode == "NORMALIZED")
p_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
}
+ int surface = 0;
+ for (int p_i = 0; p_i < meshdata.primitives.size(); p_i++) {
- int surface=0;
- for(int p_i = 0; p_i < meshdata.primitives.size(); p_i ++ ) {
-
-
-
- const Collada::MeshData::Primitives& p = meshdata.primitives[p_i];
+ const Collada::MeshData::Primitives &p = meshdata.primitives[p_i];
/* VERTEX SOURCE */
- ERR_FAIL_COND_V(!p.sources.has("VERTEX"),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!p.sources.has("VERTEX"), ERR_INVALID_DATA);
String vertex_src_id = p.sources["VERTEX"].source;
- int vertex_ofs=p.sources["VERTEX"].offset;
+ int vertex_ofs = p.sources["VERTEX"].offset;
- ERR_FAIL_COND_V(!meshdata.vertices.has(vertex_src_id),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!meshdata.vertices.has(vertex_src_id), ERR_INVALID_DATA);
- ERR_FAIL_COND_V(!meshdata.vertices[vertex_src_id].sources.has("POSITION"),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!meshdata.vertices[vertex_src_id].sources.has("POSITION"), ERR_INVALID_DATA);
String position_src_id = meshdata.vertices[vertex_src_id].sources["POSITION"];
- ERR_FAIL_COND_V(!meshdata.sources.has(position_src_id),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!meshdata.sources.has(position_src_id), ERR_INVALID_DATA);
- const Collada::MeshData::Source *vertex_src=&meshdata.sources[position_src_id];
+ const Collada::MeshData::Source *vertex_src = &meshdata.sources[position_src_id];
/* NORMAL SOURCE */
- const Collada::MeshData::Source *normal_src=NULL;
- int normal_ofs=0;
+ const Collada::MeshData::Source *normal_src = NULL;
+ int normal_ofs = 0;
if (p.sources.has("NORMAL")) {
String normal_source_id = p.sources["NORMAL"].source;
normal_ofs = p.sources["NORMAL"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(normal_source_id),ERR_INVALID_DATA);
- normal_src=&meshdata.sources[normal_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(normal_source_id), ERR_INVALID_DATA);
+ normal_src = &meshdata.sources[normal_source_id];
}
- const Collada::MeshData::Source *binormal_src=NULL;
- int binormal_ofs=0;
+ const Collada::MeshData::Source *binormal_src = NULL;
+ int binormal_ofs = 0;
if (p.sources.has("TEXBINORMAL")) {
String binormal_source_id = p.sources["TEXBINORMAL"].source;
binormal_ofs = p.sources["TEXBINORMAL"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(binormal_source_id),ERR_INVALID_DATA);
- binormal_src=&meshdata.sources[binormal_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(binormal_source_id), ERR_INVALID_DATA);
+ binormal_src = &meshdata.sources[binormal_source_id];
}
- const Collada::MeshData::Source *tangent_src=NULL;
- int tangent_ofs=0;
+ const Collada::MeshData::Source *tangent_src = NULL;
+ int tangent_ofs = 0;
if (p.sources.has("TEXTANGENT")) {
String tangent_source_id = p.sources["TEXTANGENT"].source;
tangent_ofs = p.sources["TEXTANGENT"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(tangent_source_id),ERR_INVALID_DATA);
- tangent_src=&meshdata.sources[tangent_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(tangent_source_id), ERR_INVALID_DATA);
+ tangent_src = &meshdata.sources[tangent_source_id];
}
-
- const Collada::MeshData::Source *uv_src=NULL;
- int uv_ofs=0;
+ const Collada::MeshData::Source *uv_src = NULL;
+ int uv_ofs = 0;
if (p.sources.has("TEXCOORD0")) {
String uv_source_id = p.sources["TEXCOORD0"].source;
uv_ofs = p.sources["TEXCOORD0"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(uv_source_id),ERR_INVALID_DATA);
- uv_src=&meshdata.sources[uv_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(uv_source_id), ERR_INVALID_DATA);
+ uv_src = &meshdata.sources[uv_source_id];
}
- const Collada::MeshData::Source *uv2_src=NULL;
- int uv2_ofs=0;
+ const Collada::MeshData::Source *uv2_src = NULL;
+ int uv2_ofs = 0;
if (p.sources.has("TEXCOORD1")) {
String uv2_source_id = p.sources["TEXCOORD1"].source;
uv2_ofs = p.sources["TEXCOORD1"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(uv2_source_id),ERR_INVALID_DATA);
- uv2_src=&meshdata.sources[uv2_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(uv2_source_id), ERR_INVALID_DATA);
+ uv2_src = &meshdata.sources[uv2_source_id];
}
-
- const Collada::MeshData::Source *color_src=NULL;
- int color_ofs=0;
+ const Collada::MeshData::Source *color_src = NULL;
+ int color_ofs = 0;
if (p.sources.has("COLOR")) {
String color_source_id = p.sources["COLOR"].source;
color_ofs = p.sources["COLOR"].offset;
- ERR_FAIL_COND_V( !meshdata.sources.has(color_source_id), ERR_INVALID_DATA );
- color_src=&meshdata.sources[color_source_id];
+ ERR_FAIL_COND_V(!meshdata.sources.has(color_source_id), ERR_INVALID_DATA);
+ color_src = &meshdata.sources[color_source_id];
}
//find largest source..
@@ -744,14 +708,14 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
/* ADD WEIGHTS IF EXIST */
/************************/
- Map<int,Vector<Collada::Vertex::Weight> > pre_weights;
+ Map<int, Vector<Collada::Vertex::Weight> > pre_weights;
- bool has_weights=false;
+ bool has_weights = false;
if (skin_controller) {
- const Collada::SkinControllerData::Source *weight_src=NULL;
- int weight_ofs=0;
+ const Collada::SkinControllerData::Source *weight_src = NULL;
+ int weight_ofs = 0;
if (skin_controller->weights.sources.has("WEIGHT")) {
@@ -760,11 +724,10 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
if (skin_controller->sources.has(weight_id)) {
weight_src = &skin_controller->sources[weight_id];
-
}
}
- int joint_ofs=0;
+ int joint_ofs = 0;
if (skin_controller->weights.sources.has("JOINT")) {
@@ -773,67 +736,62 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
//should be OK, given this was pre-checked.
- int index_ofs=0;
+ int index_ofs = 0;
int wstride = skin_controller->weights.sources.size();
- for(int w_i=0;w_i<skin_controller->weights.sets.size();w_i++) {
+ for (int w_i = 0; w_i < skin_controller->weights.sets.size(); w_i++) {
int amount = skin_controller->weights.sets[w_i];
Vector<Collada::Vertex::Weight> weights;
- for (int a_i=0;a_i<amount;a_i++) {
+ for (int a_i = 0; a_i < amount; a_i++) {
Collada::Vertex::Weight w;
- int read_from = index_ofs+a_i*wstride;
- ERR_FAIL_INDEX_V(read_from+wstride-1,skin_controller->weights.indices.size(),ERR_INVALID_DATA);
- int weight_index = skin_controller->weights.indices[read_from+weight_ofs];
- ERR_FAIL_INDEX_V(weight_index,weight_src->array.size(),ERR_INVALID_DATA);
+ int read_from = index_ofs + a_i * wstride;
+ ERR_FAIL_INDEX_V(read_from + wstride - 1, skin_controller->weights.indices.size(), ERR_INVALID_DATA);
+ int weight_index = skin_controller->weights.indices[read_from + weight_ofs];
+ ERR_FAIL_INDEX_V(weight_index, weight_src->array.size(), ERR_INVALID_DATA);
w.weight = weight_src->array[weight_index];
- int bone_index = skin_controller->weights.indices[read_from+joint_ofs];
- if (bone_index==-1)
+ int bone_index = skin_controller->weights.indices[read_from + joint_ofs];
+ if (bone_index == -1)
continue; //ignore this weight (refers to bind shape)
- ERR_FAIL_INDEX_V(bone_index,bone_remap.size(),ERR_INVALID_DATA);
-
- w.bone_idx=bone_remap[bone_index];
+ ERR_FAIL_INDEX_V(bone_index, bone_remap.size(), ERR_INVALID_DATA);
+ w.bone_idx = bone_remap[bone_index];
weights.push_back(w);
}
/* FIX WEIGHTS */
-
-
weights.sort();
- if (weights.size()>4) {
+ if (weights.size() > 4) {
//cap to 4 and make weights add up 1
weights.resize(4);
-
}
//make sure weights allways add up to 1
- float total=0;
- for(int i=0;i<weights.size();i++)
- total+=weights[i].weight;
+ float total = 0;
+ for (int i = 0; i < weights.size(); i++)
+ total += weights[i].weight;
if (total)
- for(int i=0;i<weights.size();i++)
- weights[i].weight/=total;
+ for (int i = 0; i < weights.size(); i++)
+ weights[i].weight /= total;
- if (weights.size()==0 || total==0) { //if nothing, add a weight to bone 0
+ if (weights.size() == 0 || total == 0) { //if nothing, add a weight to bone 0
//no weights assigned
Collada::Vertex::Weight w;
- w.bone_idx=0;
- w.weight=1.0;
+ w.bone_idx = 0;
+ w.weight = 1.0;
weights.clear();
weights.push_back(w);
-
}
- pre_weights[w_i]=weights;
+ pre_weights[w_i] = weights;
/*
for(Set<int>::Element *E=vertex_map[w_i].front();E;E=E->next()) {
@@ -845,16 +803,11 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
}*/
-
-
-
- index_ofs+=wstride*amount;
-
+ index_ofs += wstride * amount;
}
//vertices need to be localized
- has_weights=true;
-
+ has_weights = true;
}
Set<Collada::Vertex> vertex_set; //vertex set will be the vertices
@@ -870,131 +823,121 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
// This is, however, more incompatible with standard video cards, so arrays must be converted.
// Must convert to GL/DX format.
- int _prim_ofs=0;
- int vertidx=0;
- for(int p_i=0;p_i<p.count;p_i++) {
-
+ int _prim_ofs = 0;
+ int vertidx = 0;
+ for (int p_i = 0; p_i < p.count; p_i++) {
int amount;
if (p.polygons.size()) {
- ERR_FAIL_INDEX_V(p_i,p.polygons.size(),ERR_INVALID_DATA);
- amount=p.polygons[p_i];
+ ERR_FAIL_INDEX_V(p_i, p.polygons.size(), ERR_INVALID_DATA);
+ amount = p.polygons[p_i];
} else {
- amount=3; //triangles;
+ amount = 3; //triangles;
}
//COLLADA_PRINT("amount: "+itos(amount));
- int prev2[2]={0,0};
+ int prev2[2] = { 0, 0 };
- for(int j=0;j<amount;j++) {
+ for (int j = 0; j < amount; j++) {
- int src=_prim_ofs;
+ int src = _prim_ofs;
//_prim_ofs+=p.sources.size()
- ERR_FAIL_INDEX_V(src,p.indices.size(),ERR_INVALID_DATA);
+ ERR_FAIL_INDEX_V(src, p.indices.size(), ERR_INVALID_DATA);
Collada::Vertex vertex;
if (!p_optimize)
- vertex.uid=vertidx++;
-
+ vertex.uid = vertidx++;
-
- int vertex_index=p.indices[src+vertex_ofs]; //used for index field (later used by controllers)
- int vertex_pos = (vertex_src->stride?vertex_src->stride:3) * vertex_index;
- ERR_FAIL_INDEX_V(vertex_pos,vertex_src->array.size(),ERR_INVALID_DATA);
- vertex.vertex=Vector3(vertex_src->array[vertex_pos+0],vertex_src->array[vertex_pos+1],vertex_src->array[vertex_pos+2]);
+ int vertex_index = p.indices[src + vertex_ofs]; //used for index field (later used by controllers)
+ int vertex_pos = (vertex_src->stride ? vertex_src->stride : 3) * vertex_index;
+ ERR_FAIL_INDEX_V(vertex_pos, vertex_src->array.size(), ERR_INVALID_DATA);
+ vertex.vertex = Vector3(vertex_src->array[vertex_pos + 0], vertex_src->array[vertex_pos + 1], vertex_src->array[vertex_pos + 2]);
if (pre_weights.has(vertex_index)) {
- vertex.weights=pre_weights[vertex_index];
+ vertex.weights = pre_weights[vertex_index];
}
if (normal_src) {
-
-
- int normal_pos = (normal_src->stride?normal_src->stride:3) * p.indices[src+normal_ofs];
- ERR_FAIL_INDEX_V(normal_pos,normal_src->array.size(),ERR_INVALID_DATA);
- vertex.normal=Vector3(normal_src->array[normal_pos+0],normal_src->array[normal_pos+1],normal_src->array[normal_pos+2]);
- vertex.normal=vertex.normal.snapped(0.001);
-
+ int normal_pos = (normal_src->stride ? normal_src->stride : 3) * p.indices[src + normal_ofs];
+ ERR_FAIL_INDEX_V(normal_pos, normal_src->array.size(), ERR_INVALID_DATA);
+ vertex.normal = Vector3(normal_src->array[normal_pos + 0], normal_src->array[normal_pos + 1], normal_src->array[normal_pos + 2]);
+ vertex.normal = vertex.normal.snapped(0.001);
if (tangent_src && binormal_src) {
- int binormal_pos = (binormal_src->stride?binormal_src->stride:3) * p.indices[src+binormal_ofs];
- ERR_FAIL_INDEX_V(binormal_pos,binormal_src->array.size(),ERR_INVALID_DATA);
- Vector3 binormal =Vector3(binormal_src->array[binormal_pos+0],binormal_src->array[binormal_pos+1],binormal_src->array[binormal_pos+2]);
+ int binormal_pos = (binormal_src->stride ? binormal_src->stride : 3) * p.indices[src + binormal_ofs];
+ ERR_FAIL_INDEX_V(binormal_pos, binormal_src->array.size(), ERR_INVALID_DATA);
+ Vector3 binormal = Vector3(binormal_src->array[binormal_pos + 0], binormal_src->array[binormal_pos + 1], binormal_src->array[binormal_pos + 2]);
- int tangent_pos = (tangent_src->stride?tangent_src->stride:3) * p.indices[src+tangent_ofs];
- ERR_FAIL_INDEX_V(tangent_pos,tangent_src->array.size(),ERR_INVALID_DATA);
- Vector3 tangent =Vector3(tangent_src->array[tangent_pos+0],tangent_src->array[tangent_pos+1],tangent_src->array[tangent_pos+2]);
+ int tangent_pos = (tangent_src->stride ? tangent_src->stride : 3) * p.indices[src + tangent_ofs];
+ ERR_FAIL_INDEX_V(tangent_pos, tangent_src->array.size(), ERR_INVALID_DATA);
+ Vector3 tangent = Vector3(tangent_src->array[tangent_pos + 0], tangent_src->array[tangent_pos + 1], tangent_src->array[tangent_pos + 2]);
- vertex.tangent.normal=tangent;
- vertex.tangent.d= vertex.normal.cross(tangent).dot(binormal) > 0 ? 1 : -1;
+ vertex.tangent.normal = tangent;
+ vertex.tangent.d = vertex.normal.cross(tangent).dot(binormal) > 0 ? 1 : -1;
}
-
}
-
if (uv_src) {
- int uv_pos = (uv_src->stride?uv_src->stride:2) * p.indices[src+uv_ofs];
- ERR_FAIL_INDEX_V(uv_pos,uv_src->array.size(),ERR_INVALID_DATA);
- vertex.uv=Vector3(uv_src->array[uv_pos+0],1.0-uv_src->array[uv_pos+1],0);
+ int uv_pos = (uv_src->stride ? uv_src->stride : 2) * p.indices[src + uv_ofs];
+ ERR_FAIL_INDEX_V(uv_pos, uv_src->array.size(), ERR_INVALID_DATA);
+ vertex.uv = Vector3(uv_src->array[uv_pos + 0], 1.0 - uv_src->array[uv_pos + 1], 0);
}
if (uv2_src) {
- int uv2_pos = (uv2_src->stride?uv2_src->stride:2) * p.indices[src+uv2_ofs];
- ERR_FAIL_INDEX_V(uv2_pos,uv2_src->array.size(),ERR_INVALID_DATA);
- vertex.uv2=Vector3(uv2_src->array[uv2_pos+0],1.0-uv2_src->array[uv2_pos+1],0);
+ int uv2_pos = (uv2_src->stride ? uv2_src->stride : 2) * p.indices[src + uv2_ofs];
+ ERR_FAIL_INDEX_V(uv2_pos, uv2_src->array.size(), ERR_INVALID_DATA);
+ vertex.uv2 = Vector3(uv2_src->array[uv2_pos + 0], 1.0 - uv2_src->array[uv2_pos + 1], 0);
}
if (color_src) {
- int color_pos = (color_src->stride?color_src->stride:3) * p.indices[src+color_ofs]; // colors are RGB in collada..
- ERR_FAIL_INDEX_V(color_pos,color_src->array.size(),ERR_INVALID_DATA);
- vertex.color=Color(color_src->array[color_pos+0],color_src->array[color_pos+1],color_src->array[color_pos+2],(color_src->stride>3)?color_src->array[color_pos+3]:1.0);
-
+ int color_pos = (color_src->stride ? color_src->stride : 3) * p.indices[src + color_ofs]; // colors are RGB in collada..
+ ERR_FAIL_INDEX_V(color_pos, color_src->array.size(), ERR_INVALID_DATA);
+ vertex.color = Color(color_src->array[color_pos + 0], color_src->array[color_pos + 1], color_src->array[color_pos + 2], (color_src->stride > 3) ? color_src->array[color_pos + 3] : 1.0);
}
#ifndef NO_UP_AXIS_SWAP
- if (collada.state.up_axis==Vector3::AXIS_Z) {
+ if (collada.state.up_axis == Vector3::AXIS_Z) {
- SWAP( vertex.vertex.z, vertex.vertex.y );
+ SWAP(vertex.vertex.z, vertex.vertex.y);
vertex.vertex.z = -vertex.vertex.z;
- SWAP( vertex.normal.z, vertex.normal.y );
+ SWAP(vertex.normal.z, vertex.normal.y);
vertex.normal.z = -vertex.normal.z;
- SWAP( vertex.tangent.normal.z, vertex.tangent.normal.y );
+ SWAP(vertex.tangent.normal.z, vertex.tangent.normal.y);
vertex.tangent.normal.z = -vertex.tangent.normal.z;
-
}
#endif
vertex.fix_unit_scale(collada);
- int index=0;
+ int index = 0;
//COLLADA_PRINT("vertex: "+vertex.vertex);
if (vertex_set.has(vertex)) {
- index=vertex_set.find(vertex)->get().idx;
+ index = vertex_set.find(vertex)->get().idx;
} else {
- index=vertex_set.size();
- vertex.idx=index;
+ index = vertex_set.size();
+ vertex.idx = index;
vertex_set.insert(vertex);
}
- /* if (!vertex_map.has(vertex_index))
+ /* if (!vertex_map.has(vertex_index))
vertex_map[vertex_index]=Set<int>();
vertex_map[vertex_index].insert(index); //should be outside..*/
//build triangles if needed
- if (j==0)
- prev2[0]=index;
+ if (j == 0)
+ prev2[0] = index;
- if (j>=2) {
+ if (j >= 2) {
//insert indices in reverse order (collada uses CCW as frontface)
if (local_xform_mirror) {
@@ -1009,32 +952,28 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
}
}
- prev2[1]=index;
- _prim_ofs+=p.vertex_size;
+ prev2[1] = index;
+ _prim_ofs += p.vertex_size;
}
-
}
-
-
Vector<Collada::Vertex> vertex_array; //there we go, vertex array
vertex_array.resize(vertex_set.size());
- for(Set<Collada::Vertex>::Element *F=vertex_set.front();F;F=F->next()) {
+ for (Set<Collada::Vertex>::Element *F = vertex_set.front(); F; F = F->next()) {
- vertex_array[F->get().idx]=F->get();
+ vertex_array[F->get().idx] = F->get();
}
-
if (has_weights) {
//if skeleton, localize
Transform local_xform = p_local_xform;
- for(int i=0;i<vertex_array.size();i++) {
+ for (int i = 0; i < vertex_array.size(); i++) {
- vertex_array[i].vertex=local_xform.xform(vertex_array[i].vertex);
- vertex_array[i].normal=local_xform.basis.xform(vertex_array[i].normal).normalized();
- vertex_array[i].tangent.normal=local_xform.basis.xform(vertex_array[i].tangent.normal).normalized();
+ vertex_array[i].vertex = local_xform.xform(vertex_array[i].vertex);
+ vertex_array[i].normal = local_xform.basis.xform(vertex_array[i].normal).normalized();
+ vertex_array[i].tangent.normal = local_xform.basis.xform(vertex_array[i].tangent.normal).normalized();
if (local_xform_mirror) {
//i shouldn't do this? wtf?
//vertex_array[i].normal*=-1.0;
@@ -1043,51 +982,46 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
}
}
-
PoolVector<int> index_array;
index_array.resize(indices_list.size());
PoolVector<int>::Write index_arrayw = index_array.write();
- int iidx=0;
- for(List<int>::Element *F=indices_list.front();F;F=F->next()) {
+ int iidx = 0;
+ for (List<int>::Element *F = indices_list.front(); F; F = F->next()) {
- index_arrayw[iidx++]=F->get();
+ index_arrayw[iidx++] = F->get();
}
- index_arrayw=PoolVector<int>::Write();
-
+ index_arrayw = PoolVector<int>::Write();
/*****************/
/* MAKE SURFACES */
/*****************/
-
{
Ref<FixedSpatialMaterial> material;
//find material
- Mesh::PrimitiveType primitive=Mesh::PRIMITIVE_TRIANGLES;
+ Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
{
if (p_material_map.has(p.material)) {
- String target=p_material_map[p.material].target;
+ String target = p_material_map[p.material].target;
if (!material_cache.has(target)) {
Error err = _create_material(target);
if (!err)
- material=material_cache[target];
+ material = material_cache[target];
} else
- material=material_cache[target];
+ material = material_cache[target];
- } else if (p.material!=""){
- print_line("Warning, unreferenced material in geometry instance: "+p.material);
+ } else if (p.material != "") {
+ print_line("Warning, unreferenced material in geometry instance: " + p.material);
}
}
-
-
PoolVector<Vector3> final_vertex_array;
PoolVector<Vector3> final_normal_array;
PoolVector<float> final_tangent_array;
@@ -1097,34 +1031,30 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
PoolVector<int> final_bone_array;
PoolVector<float> final_weight_array;
- uint32_t final_format=0;
+ uint32_t final_format = 0;
//create format
- final_format=Mesh::ARRAY_FORMAT_VERTEX|Mesh::ARRAY_FORMAT_INDEX;
+ final_format = Mesh::ARRAY_FORMAT_VERTEX | Mesh::ARRAY_FORMAT_INDEX;
if (normal_src) {
- final_format|=Mesh::ARRAY_FORMAT_NORMAL;
+ final_format |= Mesh::ARRAY_FORMAT_NORMAL;
if (uv_src && binormal_src && tangent_src) {
- final_format|=Mesh::ARRAY_FORMAT_TANGENT;
+ final_format |= Mesh::ARRAY_FORMAT_TANGENT;
}
-
}
-
-
if (color_src)
- final_format|=Mesh::ARRAY_FORMAT_COLOR;
+ final_format |= Mesh::ARRAY_FORMAT_COLOR;
if (uv_src)
- final_format|=Mesh::ARRAY_FORMAT_TEX_UV;
+ final_format |= Mesh::ARRAY_FORMAT_TEX_UV;
if (uv2_src)
- final_format|=Mesh::ARRAY_FORMAT_TEX_UV2;
+ final_format |= Mesh::ARRAY_FORMAT_TEX_UV2;
if (has_weights) {
- final_format|=Mesh::ARRAY_FORMAT_WEIGHTS;
- final_format|=Mesh::ARRAY_FORMAT_BONES;
+ final_format |= Mesh::ARRAY_FORMAT_WEIGHTS;
+ final_format |= Mesh::ARRAY_FORMAT_BONES;
}
-
//set arrays
int vlen = vertex_array.size();
@@ -1135,27 +1065,24 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
PoolVector<Vector3>::Write varrayw = varray.write();
- for(int k=0;k<vlen;k++)
- varrayw[k]=vertex_array[k].vertex;
+ for (int k = 0; k < vlen; k++)
+ varrayw[k] = vertex_array[k].vertex;
varrayw = PoolVector<Vector3>::Write();
- final_vertex_array=varray;
-
+ final_vertex_array = varray;
}
-
if (uv_src) { //compute uv first, may be needed for computing tangent/bionrmal
PoolVector<Vector3> uvarray;
uvarray.resize(vertex_array.size());
PoolVector<Vector3>::Write uvarrayw = uvarray.write();
- for(int k=0;k<vlen;k++) {
- uvarrayw[k]=vertex_array[k].uv;
+ for (int k = 0; k < vlen; k++) {
+ uvarrayw[k] = vertex_array[k].uv;
}
uvarrayw = PoolVector<Vector3>::Write();
- final_uv_array=uvarray;
-
+ final_uv_array = uvarray;
}
if (uv2_src) { //compute uv first, may be needed for computing tangent/bionrmal
@@ -1163,13 +1090,12 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
uv2array.resize(vertex_array.size());
PoolVector<Vector3>::Write uv2arrayw = uv2array.write();
- for(int k=0;k<vlen;k++) {
- uv2arrayw[k]=vertex_array[k].uv2;
+ for (int k = 0; k < vlen; k++) {
+ uv2arrayw[k] = vertex_array[k].uv2;
}
uv2arrayw = PoolVector<Vector3>::Write();
- final_uv2_array=uv2array;
-
+ final_uv2_array = uv2array;
}
if (normal_src) {
@@ -1177,12 +1103,12 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
narray.resize(vertex_array.size());
PoolVector<Vector3>::Write narrayw = narray.write();
- for(int k=0;k<vlen;k++) {
- narrayw[k]=vertex_array[k].normal;
+ for (int k = 0; k < vlen; k++) {
+ narrayw[k] = vertex_array[k].normal;
}
narrayw = PoolVector<Vector3>::Write();
- final_normal_array=narray;
+ final_normal_array = narray;
/*
PoolVector<Vector3> altnaray;
@@ -1192,91 +1118,82 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
print_line(rtos(altnaray[i].dot(final_normal_array[i])));
*/
- } else if (primitive==Mesh::PRIMITIVE_TRIANGLES) {
+ } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
//generate normals (even if unused later)
- _generate_normals(index_array,final_vertex_array,final_normal_array);
+ _generate_normals(index_array, final_vertex_array, final_normal_array);
if (OS::get_singleton()->is_stdout_verbose())
print_line("Collada: Triangle mesh lacks normals, so normals were generated.");
- final_format|=Mesh::ARRAY_FORMAT_NORMAL;
-
+ final_format |= Mesh::ARRAY_FORMAT_NORMAL;
}
if (final_normal_array.size() && uv_src && binormal_src && tangent_src && !force_make_tangents) {
PoolVector<real_t> tarray;
- tarray.resize(vertex_array.size()*4);
+ tarray.resize(vertex_array.size() * 4);
PoolVector<real_t>::Write tarrayw = tarray.write();
-
- for(int k=0;k<vlen;k++) {
- tarrayw[k*4+0]=vertex_array[k].tangent.normal.x;
- tarrayw[k*4+1]=vertex_array[k].tangent.normal.y;
- tarrayw[k*4+2]=vertex_array[k].tangent.normal.z;
- tarrayw[k*4+3]=vertex_array[k].tangent.d;
-
+ for (int k = 0; k < vlen; k++) {
+ tarrayw[k * 4 + 0] = vertex_array[k].tangent.normal.x;
+ tarrayw[k * 4 + 1] = vertex_array[k].tangent.normal.y;
+ tarrayw[k * 4 + 2] = vertex_array[k].tangent.normal.z;
+ tarrayw[k * 4 + 3] = vertex_array[k].tangent.d;
}
tarrayw = PoolVector<real_t>::Write();
- final_tangent_array=tarray;
- } else if (final_normal_array.size() && primitive==Mesh::PRIMITIVE_TRIANGLES && final_uv_array.size() && (force_make_tangents || (material.is_valid()))){
+ final_tangent_array = tarray;
+ } else if (final_normal_array.size() && primitive == Mesh::PRIMITIVE_TRIANGLES && final_uv_array.size() && (force_make_tangents || (material.is_valid()))) {
//if this uses triangles, there are uvs and the material is using a normalmap, generate tangents and binormals, because they WILL be needed
//generate binormals/tangents
- _generate_tangents_and_binormals(index_array,final_vertex_array,final_uv_array,final_normal_array,final_tangent_array);
- final_format|=Mesh::ARRAY_FORMAT_TANGENT;
+ _generate_tangents_and_binormals(index_array, final_vertex_array, final_uv_array, final_normal_array, final_tangent_array);
+ final_format |= Mesh::ARRAY_FORMAT_TANGENT;
if (OS::get_singleton()->is_stdout_verbose())
print_line("Collada: Triangle mesh lacks tangents (And normalmap was used), so tangents were generated.");
-
}
-
if (color_src) {
PoolVector<Color> colorarray;
colorarray.resize(vertex_array.size());
PoolVector<Color>::Write colorarrayw = colorarray.write();
- for(int k=0;k<vlen;k++) {
- colorarrayw[k]=vertex_array[k].color;
+ for (int k = 0; k < vlen; k++) {
+ colorarrayw[k] = vertex_array[k].color;
}
colorarrayw = PoolVector<Color>::Write();
- final_color_array=colorarray;
+ final_color_array = colorarray;
}
if (has_weights) {
PoolVector<float> weightarray;
PoolVector<int> bonearray;
- weightarray.resize(vertex_array.size()*4);
+ weightarray.resize(vertex_array.size() * 4);
PoolVector<float>::Write weightarrayw = weightarray.write();
- bonearray.resize(vertex_array.size()*4);
+ bonearray.resize(vertex_array.size() * 4);
PoolVector<int>::Write bonearrayw = bonearray.write();
- for(int k=0;k<vlen;k++) {
- float sum=0;
+ for (int k = 0; k < vlen; k++) {
+ float sum = 0;
- for(int l=0;l<VS::ARRAY_WEIGHTS_SIZE;l++) {
- if (l<vertex_array[k].weights.size()) {
- weightarrayw[k*VS::ARRAY_WEIGHTS_SIZE+l]=vertex_array[k].weights[l].weight;
- sum+=weightarrayw[k*VS::ARRAY_WEIGHTS_SIZE+l];
- bonearrayw[k*VS::ARRAY_WEIGHTS_SIZE+l]=int(vertex_array[k].weights[l].bone_idx);
+ for (int l = 0; l < VS::ARRAY_WEIGHTS_SIZE; l++) {
+ if (l < vertex_array[k].weights.size()) {
+ weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = vertex_array[k].weights[l].weight;
+ sum += weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l];
+ bonearrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = int(vertex_array[k].weights[l].bone_idx);
//COLLADA_PRINT(itos(k)+": "+rtos(bonearrayw[k*VS::ARRAY_WEIGHTS_SIZE+l])+":"+rtos(weightarray[k*VS::ARRAY_WEIGHTS_SIZE+l]));
} else {
- weightarrayw[k*VS::ARRAY_WEIGHTS_SIZE+l]=0;
- bonearrayw[k*VS::ARRAY_WEIGHTS_SIZE+l]=0;
-
+ weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = 0;
+ bonearrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = 0;
}
-
-
}
/*
if (sum<0.8)
COLLADA_PRINT("ERROR SUMMING INDEX "+itos(k)+" had weights: "+itos(vertex_array[k].weights.size()));
*/
-
}
weightarrayw = PoolVector<float>::Write();
@@ -1286,8 +1203,6 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
final_bone_array = bonearray;
}
-
-
////////////////////////////
// FINALLY CREATE SUFRACE //
////////////////////////////
@@ -1295,30 +1210,29 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
Array d;
d.resize(VS::ARRAY_MAX);
- d[Mesh::ARRAY_INDEX]=index_array;
- d[Mesh::ARRAY_VERTEX]=final_vertex_array;
+ d[Mesh::ARRAY_INDEX] = index_array;
+ d[Mesh::ARRAY_VERTEX] = final_vertex_array;
if (final_normal_array.size())
- d[Mesh::ARRAY_NORMAL]=final_normal_array;
+ d[Mesh::ARRAY_NORMAL] = final_normal_array;
if (final_tangent_array.size())
- d[Mesh::ARRAY_TANGENT]=final_tangent_array;
+ d[Mesh::ARRAY_TANGENT] = final_tangent_array;
if (final_uv_array.size())
- d[Mesh::ARRAY_TEX_UV]=final_uv_array;
+ d[Mesh::ARRAY_TEX_UV] = final_uv_array;
if (final_uv2_array.size())
- d[Mesh::ARRAY_TEX_UV2]=final_uv2_array;
+ d[Mesh::ARRAY_TEX_UV2] = final_uv2_array;
if (final_color_array.size())
- d[Mesh::ARRAY_COLOR]=final_color_array;
+ d[Mesh::ARRAY_COLOR] = final_color_array;
if (final_weight_array.size())
- d[Mesh::ARRAY_WEIGHTS]=final_weight_array;
+ d[Mesh::ARRAY_WEIGHTS] = final_weight_array;
if (final_bone_array.size())
- d[Mesh::ARRAY_BONES]=final_bone_array;
-
+ d[Mesh::ARRAY_BONES] = final_bone_array;
Array mr;
- ////////////////////////////
- // THEN THE MORPH TARGETS //
- ////////////////////////////
+////////////////////////////
+// THEN THE MORPH TARGETS //
+////////////////////////////
#if 0
if (p_morph_data) {
@@ -1426,14 +1340,14 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
int pos = m_i*stride;
Vector3 vtx( m->array[pos+0], m->array[pos+1], m->array[pos+2] );
- #ifndef NO_UP_AXIS_SWAP
+#ifndef NO_UP_AXIS_SWAP
if (collada.state.up_axis==Vector3::AXIS_Z) {
SWAP( vtx.z, vtx.y );
vtx.z = -vtx.z;
}
- #endif
+#endif
Collada::Vertex vertex;
vertex.vertex=vtx;
@@ -1483,24 +1397,23 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
}
#endif
- for(int mi=0;mi<p_morph_meshes.size();mi++) {
+ for (int mi = 0; mi < p_morph_meshes.size(); mi++) {
//print_line("want surface "+itos(mi)+" has "+itos(p_morph_meshes[mi]->get_surface_count()));
Array a = p_morph_meshes[mi]->surface_get_arrays(surface);
//add valid weight and bone arrays if they exist, TODO check if they are unique to shape (generally not)
if (final_weight_array.size())
- a[Mesh::ARRAY_WEIGHTS]=final_weight_array;
+ a[Mesh::ARRAY_WEIGHTS] = final_weight_array;
if (final_bone_array.size())
- a[Mesh::ARRAY_BONES]=final_bone_array;
+ a[Mesh::ARRAY_BONES] = final_bone_array;
- a[Mesh::ARRAY_INDEX]=Variant();
+ a[Mesh::ARRAY_INDEX] = Variant();
//a.resize(Mesh::ARRAY_MAX); //no need for index
mr.push_back(a);
}
-
- p_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,d,mr,p_for_morph?0:Mesh::ARRAY_COMPRESS_DEFAULT);
+ p_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, d, mr, p_for_morph ? 0 : Mesh::ARRAY_COMPRESS_DEFAULT);
if (material.is_valid()) {
if (p_use_mesh_material) {
@@ -1517,21 +1430,15 @@ Error ColladaImport::_create_mesh_surfaces(bool p_optimize,Ref<Mesh>& p_mesh,con
surface++;
}
-
return OK;
-
}
-
Error ColladaImport::_create_resources(Collada::Node *p_node) {
+ if (p_node->type == Collada::Node::TYPE_GEOMETRY && node_map.has(p_node->id)) {
- if (p_node->type==Collada::Node::TYPE_GEOMETRY && node_map.has(p_node->id)) {
-
-
- Spatial * node=node_map[p_node->id].node;
- Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry*>(p_node);
-
+ Spatial *node = node_map[p_node->id].node;
+ Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
if (node->cast_to<Path>()) {
@@ -1544,96 +1451,86 @@ Error ColladaImport::_create_resources(Collada::Node *p_node) {
path->set_curve(curve_cache[ng->source]);
} else {
- Ref<Curve3D> c = memnew( Curve3D );
+ Ref<Curve3D> c = memnew(Curve3D);
const Collada::CurveData &cd = collada.state.curve_data_map[ng->source];
- ERR_FAIL_COND_V( !cd.control_vertices.has("POSITION") , ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.control_vertices.has("IN_TANGENT") , ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.control_vertices.has("OUT_TANGENT") , ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.control_vertices.has("INTERPOLATION") , ERR_INVALID_DATA);
-
+ ERR_FAIL_COND_V(!cd.control_vertices.has("POSITION"), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!cd.control_vertices.has("IN_TANGENT"), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!cd.control_vertices.has("OUT_TANGENT"), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!cd.control_vertices.has("INTERPOLATION"), ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.sources.has(cd.control_vertices["POSITION"] ) , ERR_INVALID_DATA);
- const Collada::CurveData::Source &vertices = cd.sources[ cd.control_vertices["POSITION"] ];
- ERR_FAIL_COND_V( vertices.stride!=3, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["POSITION"]), ERR_INVALID_DATA);
+ const Collada::CurveData::Source &vertices = cd.sources[cd.control_vertices["POSITION"]];
+ ERR_FAIL_COND_V(vertices.stride != 3, ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.sources.has(cd.control_vertices["IN_TANGENT"] ) , ERR_INVALID_DATA);
- const Collada::CurveData::Source &in_tangents = cd.sources[ cd.control_vertices["IN_TANGENT"] ];
- ERR_FAIL_COND_V( in_tangents.stride!=3 , ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["IN_TANGENT"]), ERR_INVALID_DATA);
+ const Collada::CurveData::Source &in_tangents = cd.sources[cd.control_vertices["IN_TANGENT"]];
+ ERR_FAIL_COND_V(in_tangents.stride != 3, ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.sources.has(cd.control_vertices["OUT_TANGENT"] ), ERR_INVALID_DATA );
- const Collada::CurveData::Source &out_tangents = cd.sources[ cd.control_vertices["OUT_TANGENT"] ];
- ERR_FAIL_COND_V( out_tangents.stride!=3, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["OUT_TANGENT"]), ERR_INVALID_DATA);
+ const Collada::CurveData::Source &out_tangents = cd.sources[cd.control_vertices["OUT_TANGENT"]];
+ ERR_FAIL_COND_V(out_tangents.stride != 3, ERR_INVALID_DATA);
- ERR_FAIL_COND_V( !cd.sources.has(cd.control_vertices["INTERPOLATION"] ), ERR_INVALID_DATA );
- const Collada::CurveData::Source &interps = cd.sources[ cd.control_vertices["INTERPOLATION"] ];
- ERR_FAIL_COND_V( interps.stride!=1, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["INTERPOLATION"]), ERR_INVALID_DATA);
+ const Collada::CurveData::Source &interps = cd.sources[cd.control_vertices["INTERPOLATION"]];
+ ERR_FAIL_COND_V(interps.stride != 1, ERR_INVALID_DATA);
- const Collada::CurveData::Source *tilts=NULL;
+ const Collada::CurveData::Source *tilts = NULL;
if (cd.control_vertices.has("TILT") && cd.sources.has(cd.control_vertices["TILT"]))
- tilts=&cd.sources[ cd.control_vertices["TILT"] ];
-
+ tilts = &cd.sources[cd.control_vertices["TILT"]];
if (tilts) {
print_line("FOUND TILTS!!!");
}
- int pc = vertices.array.size()/3;
- for(int i=0;i<pc;i++) {
+ int pc = vertices.array.size() / 3;
+ for (int i = 0; i < pc; i++) {
- Vector3 pos( vertices.array[i*3+0], vertices.array[i*3+1], vertices.array[i*3+2] );
- Vector3 in( in_tangents.array[i*3+0], in_tangents.array[i*3+1], in_tangents.array[i*3+2] );
- Vector3 out( out_tangents.array[i*3+0], out_tangents.array[i*3+1], out_tangents.array[i*3+2] );
+ Vector3 pos(vertices.array[i * 3 + 0], vertices.array[i * 3 + 1], vertices.array[i * 3 + 2]);
+ Vector3 in(in_tangents.array[i * 3 + 0], in_tangents.array[i * 3 + 1], in_tangents.array[i * 3 + 2]);
+ Vector3 out(out_tangents.array[i * 3 + 0], out_tangents.array[i * 3 + 1], out_tangents.array[i * 3 + 2]);
#ifndef NO_UP_AXIS_SWAP
- if (collada.state.up_axis==Vector3::AXIS_Z) {
-
- SWAP(pos.y,pos.z);
- pos.z=-pos.z;
- SWAP(in.y,in.z);
- in.z=-in.z;
- SWAP(out.y,out.z);
- out.z=-out.z;
+ if (collada.state.up_axis == Vector3::AXIS_Z) {
+
+ SWAP(pos.y, pos.z);
+ pos.z = -pos.z;
+ SWAP(in.y, in.z);
+ in.z = -in.z;
+ SWAP(out.y, out.z);
+ out.z = -out.z;
}
#endif
- pos*=collada.state.unit_scale;
- in*=collada.state.unit_scale;
- out*=collada.state.unit_scale;
+ pos *= collada.state.unit_scale;
+ in *= collada.state.unit_scale;
+ out *= collada.state.unit_scale;
- c->add_point(pos,in-pos,out-pos);
+ c->add_point(pos, in - pos, out - pos);
if (tilts)
- c->set_point_tilt(i,tilts->array[i]);
-
+ c->set_point_tilt(i, tilts->array[i]);
}
- curve_cache[ng->source]=c;
+ curve_cache[ng->source] = c;
path->set_curve(c);
-
}
-
-
}
-
if (node->cast_to<MeshInstance>()) {
-
- Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry*>(p_node);
+ Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
MeshInstance *mi = node->cast_to<MeshInstance>();
+ ERR_FAIL_COND_V(!mi, ERR_BUG);
- ERR_FAIL_COND_V(!mi,ERR_BUG);
-
-
- Collada::SkinControllerData *skin=NULL;
- Collada::MorphControllerData *morph=NULL;
+ Collada::SkinControllerData *skin = NULL;
+ Collada::MorphControllerData *morph = NULL;
String meshid;
Transform apply_xform;
Vector<int> bone_remap;
Vector<Ref<Mesh> > morphs;
- print_line("mesh: "+String(mi->get_name()));
+ print_line("mesh: " + String(mi->get_name()));
if (ng->controller) {
@@ -1643,95 +1540,93 @@ Error ColladaImport::_create_resources(Collada::Node *p_node) {
if (collada.state.skin_controller_data_map.has(ngsource)) {
-
- ERR_FAIL_COND_V(!collada.state.skin_controller_data_map.has(ngsource),ERR_INVALID_DATA);
- skin=&collada.state.skin_controller_data_map[ngsource];
+ ERR_FAIL_COND_V(!collada.state.skin_controller_data_map.has(ngsource), ERR_INVALID_DATA);
+ skin = &collada.state.skin_controller_data_map[ngsource];
Vector<String> skeletons = ng->skeletons;
- ERR_FAIL_COND_V( skeletons.empty(), ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(skeletons.empty(), ERR_INVALID_DATA);
String skname = skeletons[0];
if (!node_map.has(skname)) {
- print_line("no node for skeleton "+skname);
+ print_line("no node for skeleton " + skname);
}
- ERR_FAIL_COND_V( !node_map.has(skname), ERR_INVALID_DATA );
+ ERR_FAIL_COND_V(!node_map.has(skname), ERR_INVALID_DATA);
NodeMap nmsk = node_map[skname];
Skeleton *sk = nmsk.node->cast_to<Skeleton>();
- ERR_FAIL_COND_V( !sk, ERR_INVALID_DATA );
- ERR_FAIL_COND_V( !skeleton_bone_map.has(sk), ERR_INVALID_DATA );
- Map<String, int> &bone_remap_map=skeleton_bone_map[sk];
+ ERR_FAIL_COND_V(!sk, ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!skeleton_bone_map.has(sk), ERR_INVALID_DATA);
+ Map<String, int> &bone_remap_map = skeleton_bone_map[sk];
-
- meshid=skin->base;
+ meshid = skin->base;
if (collada.state.morph_controller_data_map.has(meshid)) {
//it's a morph!!
morph = &collada.state.morph_controller_data_map[meshid];
- ngsource=meshid;
- meshid=morph->mesh;
+ ngsource = meshid;
+ meshid = morph->mesh;
} else {
- ngsource="";
+ ngsource = "";
}
if (apply_mesh_xform_to_vertices) {
- apply_xform=collada.fix_transform(p_node->default_transform);
+ apply_xform = collada.fix_transform(p_node->default_transform);
node->set_transform(Transform());
} else {
- apply_xform=Transform();
+ apply_xform = Transform();
}
- Collada::SkinControllerData::Source *joint_src=NULL;
+ Collada::SkinControllerData::Source *joint_src = NULL;
- ERR_FAIL_COND_V(!skin->weights.sources.has("JOINT"),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!skin->weights.sources.has("JOINT"), ERR_INVALID_DATA);
String joint_id = skin->weights.sources["JOINT"].source;
- ERR_FAIL_COND_V(!skin->sources.has(joint_id),ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!skin->sources.has(joint_id), ERR_INVALID_DATA);
joint_src = &skin->sources[joint_id];
bone_remap.resize(joint_src->sarray.size());
- for(int i=0;i<bone_remap.size();i++) {
+ for (int i = 0; i < bone_remap.size(); i++) {
String str = joint_src->sarray[i];
if (!bone_remap_map.has(str)) {
- print_line("bone not found for remap: "+str);
- print_line("in skeleton: "+skname);
+ print_line("bone not found for remap: " + str);
+ print_line("in skeleton: " + skname);
}
- ERR_FAIL_COND_V( !bone_remap_map.has(str), ERR_INVALID_DATA );
- bone_remap[i]=bone_remap_map[str];
+ ERR_FAIL_COND_V(!bone_remap_map.has(str), ERR_INVALID_DATA);
+ bone_remap[i] = bone_remap_map[str];
}
}
if (collada.state.morph_controller_data_map.has(ngsource)) {
- print_line("is morph "+ngsource);
+ print_line("is morph " + ngsource);
//it's a morph!!
morph = &collada.state.morph_controller_data_map[ngsource];
- meshid=morph->mesh;
- printf("KKmorph: %p\n",morph);
- print_line("morph mshid: "+meshid);
+ meshid = morph->mesh;
+ printf("KKmorph: %p\n", morph);
+ print_line("morph mshid: " + meshid);
Vector<String> targets;
morph->targets.has("MORPH_TARGET");
String target = morph->targets["MORPH_TARGET"];
- bool valid=false;
+ bool valid = false;
if (morph->sources.has(target)) {
- valid=true;
+ valid = true;
Vector<String> names = morph->sources[target].sarray;
- for(int i=0;i<names.size();i++) {
+ for (int i = 0; i < names.size(); i++) {
- String meshid=names[i];
+ String meshid = names[i];
if (collada.state.mesh_data_map.has(meshid)) {
- Ref<Mesh> mesh=Ref<Mesh>(memnew( Mesh ));
+ Ref<Mesh> mesh = Ref<Mesh>(memnew(Mesh));
const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
- Error err = _create_mesh_surfaces(false,mesh,ng->material_map,meshdata,apply_xform,bone_remap,skin,NULL,Vector<Ref<Mesh> >(),true);
- ERR_FAIL_COND_V(err,err);
+ Error err = _create_mesh_surfaces(false, mesh, ng->material_map, meshdata, apply_xform, bone_remap, skin, NULL, Vector<Ref<Mesh> >(), true);
+ ERR_FAIL_COND_V(err, err);
morphs.push_back(mesh);
} else {
- valid=false;
+ valid = false;
}
}
}
@@ -1739,38 +1634,36 @@ Error ColladaImport::_create_resources(Collada::Node *p_node) {
if (!valid)
morphs.clear();
- ngsource="";
+ ngsource = "";
}
- if (ngsource!=""){
- ERR_EXPLAIN("Controller Instance Source '"+ngsource+"' is neither skin or morph!");
- ERR_FAIL_V( ERR_INVALID_DATA );
+ if (ngsource != "") {
+ ERR_EXPLAIN("Controller Instance Source '" + ngsource + "' is neither skin or morph!");
+ ERR_FAIL_V(ERR_INVALID_DATA);
}
-
-
} else {
- meshid=ng->source;
+ meshid = ng->source;
}
Ref<Mesh> mesh;
if (mesh_cache.has(meshid)) {
- mesh=mesh_cache[meshid];
+ mesh = mesh_cache[meshid];
} else {
if (collada.state.mesh_data_map.has(meshid)) {
//bleh, must ignore invalid
- ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(meshid),ERR_INVALID_DATA);
- mesh=Ref<Mesh>(memnew( Mesh ));
+ ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(meshid), ERR_INVALID_DATA);
+ mesh = Ref<Mesh>(memnew(Mesh));
const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
- mesh->set_name( meshdata.name );
- Error err = _create_mesh_surfaces(morphs.size()==0,mesh,ng->material_map,meshdata,apply_xform,bone_remap,skin,morph,morphs,false,use_mesh_builtin_materials);
- ERR_FAIL_COND_V(err,err);
+ mesh->set_name(meshdata.name);
+ Error err = _create_mesh_surfaces(morphs.size() == 0, mesh, ng->material_map, meshdata, apply_xform, bone_remap, skin, morph, morphs, false, use_mesh_builtin_materials);
+ ERR_FAIL_COND_V(err, err);
- mesh_cache[meshid]=mesh;
+ mesh_cache[meshid] = mesh;
} else {
- print_line("Warning, will not import geometry: "+meshid);
+ print_line("Warning, will not import geometry: " + meshid);
}
}
@@ -1780,33 +1673,32 @@ Error ColladaImport::_create_resources(Collada::Node *p_node) {
if (!use_mesh_builtin_materials) {
const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
- for(int i=0;i<meshdata.primitives.size();i++) {
+ for (int i = 0; i < meshdata.primitives.size(); i++) {
- String matname=meshdata.primitives[i].material;
+ String matname = meshdata.primitives[i].material;
if (ng->material_map.has(matname)) {
- String target=ng->material_map[matname].target;
+ String target = ng->material_map[matname].target;
Ref<Material> material;
if (!material_cache.has(target)) {
Error err = _create_material(target);
if (!err)
- material=material_cache[target];
+ material = material_cache[target];
} else
- material=material_cache[target];
+ material = material_cache[target];
- mi->set_surface_material(i,material);
- } else if (matname!=""){
- print_line("Warning, unreferenced material in geometry instance: "+matname);
+ mi->set_surface_material(i, material);
+ } else if (matname != "") {
+ print_line("Warning, unreferenced material in geometry instance: " + matname);
}
-
}
}
}
}
}
- for(int i=0;i<p_node->children.size();i++) {
+ for (int i = 0; i < p_node->children.size(); i++) {
Error err = _create_resources(p_node->children[i]);
if (err)
@@ -1815,64 +1707,60 @@ Error ColladaImport::_create_resources(Collada::Node *p_node) {
return OK;
}
+Error ColladaImport::load(const String &p_path, int p_flags, bool p_force_make_tangents) {
-Error ColladaImport::load(const String& p_path,int p_flags,bool p_force_make_tangents) {
-
- Error err = collada.load(p_path,p_flags);
- ERR_FAIL_COND_V(err,err);
+ Error err = collada.load(p_path, p_flags);
+ ERR_FAIL_COND_V(err, err);
- force_make_tangents=p_force_make_tangents;
- ERR_FAIL_COND_V( !collada.state.visual_scene_map.has( collada.state.root_visual_scene ), ERR_INVALID_DATA );
- Collada::VisualScene &vs = collada.state.visual_scene_map[ collada.state.root_visual_scene ];
+ force_make_tangents = p_force_make_tangents;
+ ERR_FAIL_COND_V(!collada.state.visual_scene_map.has(collada.state.root_visual_scene), ERR_INVALID_DATA);
+ Collada::VisualScene &vs = collada.state.visual_scene_map[collada.state.root_visual_scene];
- scene = memnew( Spatial ); // root
+ scene = memnew(Spatial); // root
//determine what's going on with the lights
- for(int i=0;i<vs.root_nodes.size();i++) {
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
_pre_process_lights(vs.root_nodes[i]);
-
}
//import scene
- for(int i=0;i<vs.root_nodes.size();i++) {
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
Error err = _create_scene_skeletons(vs.root_nodes[i]);
- if (err!=OK) {
+ if (err != OK) {
memdelete(scene);
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
}
}
- for(int i=0;i<vs.root_nodes.size();i++) {
+ for (int i = 0; i < vs.root_nodes.size(); i++) {
- Error err = _create_scene(vs.root_nodes[i],scene);
- if (err!=OK) {
+ Error err = _create_scene(vs.root_nodes[i], scene);
+ if (err != OK) {
memdelete(scene);
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
}
Error err2 = _create_resources(vs.root_nodes[i]);
- if (err2!=OK) {
+ if (err2 != OK) {
memdelete(scene);
- ERR_FAIL_COND_V(err2,err2);
+ ERR_FAIL_COND_V(err2, err2);
}
}
//optatively, set unit scale in the root
scene->set_transform(collada.get_root_transform());
-
return OK;
-
}
void ColladaImport::_fix_param_animation_tracks() {
- for (Map<String,Collada::Node*>::Element *E=collada.state.scene_map.front();E;E=E->next()) {
+ for (Map<String, Collada::Node *>::Element *E = collada.state.scene_map.front(); E; E = E->next()) {
Collada::Node *n = E->get();
- switch(n->type) {
+ switch (n->type) {
case Collada::Node::TYPE_NODE: {
// ? do nothing
@@ -1891,86 +1779,77 @@ void ColladaImport::_fix_param_animation_tracks() {
} break;
case Collada::Node::TYPE_GEOMETRY: {
- Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry*>(n);
+ Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(n);
// test source(s)
String source = ng->source;
- while (source!="") {
+ while (source != "") {
if (collada.state.skin_controller_data_map.has(source)) {
- const Collada::SkinControllerData& skin = collada.state.skin_controller_data_map[source];
+ const Collada::SkinControllerData &skin = collada.state.skin_controller_data_map[source];
//nothing to animate here i think
- source=skin.base;
+ source = skin.base;
} else if (collada.state.morph_controller_data_map.has(source)) {
-
- const Collada::MorphControllerData& morph = collada.state.morph_controller_data_map[source];
+ const Collada::MorphControllerData &morph = collada.state.morph_controller_data_map[source];
if (morph.targets.has("MORPH_WEIGHT") && morph.targets.has("MORPH_TARGET")) {
-
String weights = morph.targets["MORPH_WEIGHT"];
String targets = morph.targets["MORPH_TARGET"];
//fails here
if (morph.sources.has(targets) && morph.sources.has(weights)) {
- const Collada::MorphControllerData::Source &weight_src=morph.sources[weights];
- const Collada::MorphControllerData::Source &target_src=morph.sources[targets];
-
+ const Collada::MorphControllerData::Source &weight_src = morph.sources[weights];
+ const Collada::MorphControllerData::Source &target_src = morph.sources[targets];
ERR_FAIL_COND(weight_src.array.size() != target_src.sarray.size());
- for(int i=0;i<weight_src.array.size();i++) {
+ for (int i = 0; i < weight_src.array.size(); i++) {
- String track_name = weights+"("+itos(i)+")";
+ String track_name = weights + "(" + itos(i) + ")";
String mesh_name = target_src.sarray[i];
if (collada.state.mesh_name_map.has(mesh_name) && collada.state.referenced_tracks.has(track_name)) {
+ const Vector<int> &rt = collada.state.referenced_tracks[track_name];
- const Vector<int>&rt = collada.state.referenced_tracks[track_name];
-
- for(int rti=0;rti<rt.size();rti++) {
+ for (int rti = 0; rti < rt.size(); rti++) {
Collada::AnimationTrack *at = &collada.state.animation_tracks[rt[rti]];
- at->target=E->key();
- at->param="morph/"+collada.state.mesh_name_map[mesh_name];
- at->property=true;
+ at->target = E->key();
+ at->param = "morph/" + collada.state.mesh_name_map[mesh_name];
+ at->property = true;
//at->param
}
}
}
}
}
- source=morph.mesh;
+ source = morph.mesh;
} else {
- source=""; // for now nothing else supported
+ source = ""; // for now nothing else supported
}
}
} break;
-
}
}
-
}
void ColladaImport::create_animations(bool p_make_tracks_in_all_bones, bool p_import_value_tracks) {
-
_fix_param_animation_tracks();
- for(int i=0;i<collada.state.animation_clips.size();i++) {
+ for (int i = 0; i < collada.state.animation_clips.size(); i++) {
- for(int j=0;j<collada.state.animation_clips[i].tracks.size();j++)
+ for (int j = 0; j < collada.state.animation_clips[i].tracks.size(); j++)
tracks_in_clips.insert(collada.state.animation_clips[i].tracks[j]);
}
-
-
- for(int i=0;i<collada.state.animation_tracks.size();i++) {
+ for (int i = 0; i < collada.state.animation_tracks.size(); i++) {
Collada::AnimationTrack &at = collada.state.animation_tracks[i];
//print_line("CHANNEL: "+at.target+" PARAM: "+at.param);
@@ -1981,16 +1860,15 @@ void ColladaImport::create_animations(bool p_make_tracks_in_all_bones, bool p_im
if (node_name_map.has(at.target)) {
- node=node_name_map[at.target];
+ node = node_name_map[at.target];
} else {
- print_line("Coudlnt find node: "+at.target);
+ print_line("Coudlnt find node: " + at.target);
continue;
}
} else {
- node=at.target;
+ node = at.target;
}
-
if (at.property) {
valid_animated_properties.push_back(i);
@@ -2000,22 +1878,19 @@ void ColladaImport::create_animations(bool p_make_tracks_in_all_bones, bool p_im
node_map[node].anim_tracks.push_back(i);
valid_animated_nodes.insert(node);
}
-
}
- create_animation(-1,p_make_tracks_in_all_bones, p_import_value_tracks);
+ create_animation(-1, p_make_tracks_in_all_bones, p_import_value_tracks);
//print_line("clipcount: "+itos(collada.state.animation_clips.size()));
- for(int i=0;i<collada.state.animation_clips.size();i++)
+ for (int i = 0; i < collada.state.animation_clips.size(); i++)
create_animation(i, p_make_tracks_in_all_bones, p_import_value_tracks);
-
}
void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones, bool p_import_value_tracks) {
- Ref<Animation> animation = Ref<Animation>( memnew( Animation ));
-
+ Ref<Animation> animation = Ref<Animation>(memnew(Animation));
- if (p_clip==-1) {
+ if (p_clip == -1) {
//print_line("default");
animation->set_name("default");
@@ -2024,33 +1899,32 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
animation->set_name(collada.state.animation_clips[p_clip].name);
}
- for(Map<String,NodeMap>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<String, NodeMap>::Element *E = node_map.front(); E; E = E->next()) {
- if (E->get().bone<0)
+ if (E->get().bone < 0)
continue;
- bones_with_animation[E->key()]=false;
+ bones_with_animation[E->key()] = false;
}
//store and validate tracks
- if (p_clip==-1) {
+ if (p_clip == -1) {
//main anim
}
Set<int> track_filter;
+ if (p_clip == -1) {
- if (p_clip==-1) {
-
- for(int i=0;i<collada.state.animation_clips.size();i++) {
+ for (int i = 0; i < collada.state.animation_clips.size(); i++) {
int tc = collada.state.animation_clips[i].tracks.size();
- for(int j=0;j<tc;j++) {
+ for (int j = 0; j < tc; j++) {
String n = collada.state.animation_clips[i].tracks[j];
if (collada.state.by_id_tracks.has(n)) {
- const Vector<int>&ti = collada.state.by_id_tracks[n];
- for(int k=0;k<ti.size();k++) {
+ const Vector<int> &ti = collada.state.by_id_tracks[n];
+ for (int k = 0; k < ti.size(); k++) {
track_filter.insert(ti[k]);
}
}
@@ -2059,18 +1933,17 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
} else {
int tc = collada.state.animation_clips[p_clip].tracks.size();
- for(int j=0;j<tc;j++) {
+ for (int j = 0; j < tc; j++) {
String n = collada.state.animation_clips[p_clip].tracks[j];
if (collada.state.by_id_tracks.has(n)) {
- const Vector<int>&ti = collada.state.by_id_tracks[n];
- for(int k=0;k<ti.size();k++) {
+ const Vector<int> &ti = collada.state.by_id_tracks[n];
+ for (int k = 0; k < ti.size(); k++) {
track_filter.insert(ti[k]);
}
}
}
-
}
//animation->set_loop(true);
@@ -2078,37 +1951,33 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
Vector<float> base_snapshots;
- float f=0;
- float snapshot_interval = 1.0/bake_fps; //should be customizable somewhere...
+ float f = 0;
+ float snapshot_interval = 1.0 / bake_fps; //should be customizable somewhere...
- float anim_length=collada.state.animation_length;
- if (p_clip>=0 && collada.state.animation_clips[p_clip].end)
- anim_length=collada.state.animation_clips[p_clip].end;
+ float anim_length = collada.state.animation_length;
+ if (p_clip >= 0 && collada.state.animation_clips[p_clip].end)
+ anim_length = collada.state.animation_clips[p_clip].end;
- while(f<anim_length) {
+ while (f < anim_length) {
base_snapshots.push_back(f);
- f+=snapshot_interval;
+ f += snapshot_interval;
- if (f>=anim_length) {
+ if (f >= anim_length) {
base_snapshots.push_back(anim_length);
-
}
}
//print_line("anim len: "+rtos(anim_length));
animation->set_length(anim_length);
- bool tracks_found=false;
-
-
+ bool tracks_found = false;
- for(Set<String>::Element* E=valid_animated_nodes.front();E;E=E->next()) {
+ for (Set<String>::Element *E = valid_animated_nodes.front(); E; E = E->next()) {
// take snapshots
-
if (!collada.state.scene_map.has(E->get())) {
continue;
@@ -2117,14 +1986,13 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
NodeMap &nm = node_map[E->get()];
String path = scene->get_path_to(nm.node);
- if (nm.bone>=0) {
- Skeleton *sk = static_cast<Skeleton*>(nm.node);
+ if (nm.bone >= 0) {
+ Skeleton *sk = static_cast<Skeleton *>(nm.node);
String name = sk->get_bone_name(nm.bone);
- path=path+":"+name;
+ path = path + ":" + name;
}
- bool found_anim=false;
-
+ bool found_anim = false;
Collada::Node *cn = collada.state.scene_map[E->get()];
if (cn->ignore_anim) {
@@ -2132,34 +2000,27 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
continue;
}
-
-
animation->add_track(Animation::TYPE_TRANSFORM);
- int track = animation->get_track_count() -1;
- animation->track_set_path( track , path );
- animation->track_set_imported( track , true ); //helps merging later
+ int track = animation->get_track_count() - 1;
+ animation->track_set_path(track, path);
+ animation->track_set_imported(track, true); //helps merging later
Vector<float> snapshots = base_snapshots;
- if (nm.anim_tracks.size()==1) {
+ if (nm.anim_tracks.size() == 1) {
//use snapshot keys from anim track instead, because this was most likely exported baked
Collada::AnimationTrack &at = collada.state.animation_tracks[nm.anim_tracks.front()->get()];
snapshots.clear();
- for(int i=0;i<at.keys.size();i++)
+ for (int i = 0; i < at.keys.size(); i++)
snapshots.push_back(at.keys[i].time);
-
-
}
+ for (int i = 0; i < snapshots.size(); i++) {
- for(int i=0;i<snapshots.size();i++) {
-
-
- for(List<int>::Element *ET=nm.anim_tracks.front();ET;ET=ET->next()) {
+ for (List<int>::Element *ET = nm.anim_tracks.front(); ET; ET = ET->next()) {
//apply tracks
-
- if (p_clip==-1) {
+ if (p_clip == -1) {
if (track_filter.has(ET->get())) {
@@ -2169,66 +2030,61 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
if (!track_filter.has(ET->get()))
continue;
-
}
- found_anim=true;
+ found_anim = true;
Collada::AnimationTrack &at = collada.state.animation_tracks[ET->get()];
- int xform_idx=-1;
- for(int j=0;j<cn->xform_list.size();j++) {
+ int xform_idx = -1;
+ for (int j = 0; j < cn->xform_list.size(); j++) {
+ if (cn->xform_list[j].id == at.param) {
- if (cn->xform_list[j].id==at.param) {
-
- xform_idx=j;
+ xform_idx = j;
break;
}
}
- if (xform_idx==-1) {
- print_line("couldnt find matching node "+at.target+" xform for track "+at.param);
- continue;
+ if (xform_idx == -1) {
+ print_line("couldnt find matching node " + at.target + " xform for track " + at.param);
+ continue;
}
- ERR_CONTINUE(xform_idx==-1);
+ ERR_CONTINUE(xform_idx == -1);
Vector<float> data = at.get_value_at_time(snapshots[i]);
ERR_CONTINUE(data.empty());
-
Collada::Node::XForm &xf = cn->xform_list[xform_idx];
- if (at.component=="ANGLE") {
- ERR_CONTINUE(data.size()!=1);
- ERR_CONTINUE(xf.op!=Collada::Node::XForm::OP_ROTATE);
- ERR_CONTINUE(xf.data.size()<4);
- xf.data[3]=data[0];
- } else if (at.component=="X" || at.component=="Y" || at.component=="Z") {
- int cn=at.component[0]-'X';
- ERR_CONTINUE(cn>=xf.data.size());
- ERR_CONTINUE(data.size()>1);
- xf.data[cn]=data[0];
- } else if (data.size()==xf.data.size()) {
-
- xf.data=data;
+ if (at.component == "ANGLE") {
+ ERR_CONTINUE(data.size() != 1);
+ ERR_CONTINUE(xf.op != Collada::Node::XForm::OP_ROTATE);
+ ERR_CONTINUE(xf.data.size() < 4);
+ xf.data[3] = data[0];
+ } else if (at.component == "X" || at.component == "Y" || at.component == "Z") {
+ int cn = at.component[0] - 'X';
+ ERR_CONTINUE(cn >= xf.data.size());
+ ERR_CONTINUE(data.size() > 1);
+ xf.data[cn] = data[0];
+ } else if (data.size() == xf.data.size()) {
+
+ xf.data = data;
} else {
-
- if ( data.size()!=xf.data.size() ) {
- print_line("component "+at.component+" datasize "+itos(data.size())+" xfdatasize "+itos(xf.data.size()));
+ if (data.size() != xf.data.size()) {
+ print_line("component " + at.component + " datasize " + itos(data.size()) + " xfdatasize " + itos(xf.data.size()));
}
- ERR_CONTINUE( data.size()!=xf.data.size() );
+ ERR_CONTINUE(data.size() != xf.data.size());
}
}
Transform xform = cn->compute_transform(collada);
xform = collada.fix_transform(xform) * cn->post_transform;
-
- if (nm.bone>=0) {
+ if (nm.bone >= 0) {
//make bone transform relative to rest (in case of skeleton)
Skeleton *sk = nm.node->cast_to<Skeleton>();
if (sk) {
@@ -2245,29 +2101,25 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
Vector3 s = xform.basis.get_scale();
Vector3 l = xform.origin;
- animation->transform_track_insert_key(track,snapshots[i],l,q,s);
-
+ animation->transform_track_insert_key(track, snapshots[i], l, q, s);
}
-
-
- if (nm.bone>=0) {
+ if (nm.bone >= 0) {
if (found_anim)
- bones_with_animation[E->get()]=true;
+ bones_with_animation[E->get()] = true;
}
if (found_anim)
- tracks_found=true;
+ tracks_found = true;
else {
- animation->remove_track( track );
+ animation->remove_track(track);
}
-
}
if (p_make_tracks_in_all_bones) {
//some bones may lack animation, but since we don't store pose as a property, we must add keyframes!
- for(Map<String,bool>::Element *E=bones_with_animation.front();E;E=E->next()) {
+ for (Map<String, bool>::Element *E = bones_with_animation.front(); E; E = E->next()) {
if (E->get())
continue;
@@ -2276,22 +2128,21 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
NodeMap &nm = node_map[E->key()];
String path = scene->get_path_to(nm.node);
- ERR_CONTINUE( nm.bone <0 );
- Skeleton *sk = static_cast<Skeleton*>(nm.node);
+ ERR_CONTINUE(nm.bone < 0);
+ Skeleton *sk = static_cast<Skeleton *>(nm.node);
String name = sk->get_bone_name(nm.bone);
- path=path+":"+name;
+ path = path + ":" + name;
Collada::Node *cn = collada.state.scene_map[E->key()];
if (cn->ignore_anim) {
- print_line("warning, ignoring animation on node: "+path);
+ print_line("warning, ignoring animation on node: " + path);
continue;
}
animation->add_track(Animation::TYPE_TRANSFORM);
- int track = animation->get_track_count() -1;
- animation->track_set_path( track , path );
- animation->track_set_imported( track , true ); //helps merging later
-
+ int track = animation->get_track_count() - 1;
+ animation->track_set_path(track, path);
+ animation->track_set_imported(track, true); //helps merging later
Transform xform = cn->compute_transform(collada);
xform = collada.fix_transform(xform) * cn->post_transform;
@@ -2303,33 +2154,27 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
Vector3 s = xform.basis.get_scale();
Vector3 l = xform.origin;
- animation->transform_track_insert_key(track,0,l,q,s);
+ animation->transform_track_insert_key(track, 0, l, q, s);
- tracks_found=true;
+ tracks_found = true;
}
}
-
-
if (p_import_value_tracks) {
for (int i = 0; i < valid_animated_properties.size(); i++) {
-
int ti = valid_animated_properties[i];
if (p_clip == -1) {
if (track_filter.has(ti))
continue;
- }
- else {
+ } else {
if (!track_filter.has(ti))
continue;
-
}
-
Collada::AnimationTrack &at = collada.state.animation_tracks[ti];
// take snapshots
@@ -2346,7 +2191,6 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
animation->track_set_path(track, path);
animation->track_set_imported(track, true); //helps merging later
-
for (int i = 0; i < at.keys.size(); i++) {
float time = at.keys[i].time;
@@ -2356,12 +2200,10 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
//push a float
value = data[0];
- }
- else if (data.size() == 16) {
+ } else if (data.size() == 16) {
//matrix
print_line("value keys for matrices not supported");
- }
- else {
+ } else {
print_line("don't know what to do with this amount of value keys: " + itos(data.size()));
}
@@ -2369,55 +2211,43 @@ void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones
animation->track_insert_key(track, time, value);
}
-
tracks_found = true;
-
}
}
-
-
if (tracks_found) {
animations.push_back(animation);
}
-
-
-
}
-
/*********************************************************************************/
/*************************************** SCENE ***********************************/
/*********************************************************************************/
-
#define DEBUG_ANIMATION
-
uint32_t EditorSceneImporterCollada::get_import_flags() const {
- return IMPORT_SCENE|IMPORT_ANIMATION;
-
+ return IMPORT_SCENE | IMPORT_ANIMATION;
}
void EditorSceneImporterCollada::get_extensions(List<String> *r_extensions) const {
-
r_extensions->push_back("dae");
}
-Node* EditorSceneImporterCollada::import_scene(const String& p_path, uint32_t p_flags,int p_bake_fps, List<String> *r_missing_deps, Error* r_err) {
+Node *EditorSceneImporterCollada::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
ColladaImport state;
- uint32_t flags=Collada::IMPORT_FLAG_SCENE;
- if (p_flags&IMPORT_ANIMATION)
- flags|=Collada::IMPORT_FLAG_ANIMATION;
+ uint32_t flags = Collada::IMPORT_FLAG_SCENE;
+ if (p_flags & IMPORT_ANIMATION)
+ flags |= Collada::IMPORT_FLAG_ANIMATION;
- state.use_mesh_builtin_materials=!(p_flags&IMPORT_MATERIALS_IN_INSTANCES);
- state.bake_fps=p_bake_fps;
+ state.use_mesh_builtin_materials = !(p_flags & IMPORT_MATERIALS_IN_INSTANCES);
+ state.bake_fps = p_bake_fps;
- Error err = state.load(p_path,flags,p_flags&EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
+ Error err = state.load(p_path, flags, p_flags & EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
- ERR_FAIL_COND_V(err!=OK,NULL);
+ ERR_FAIL_COND_V(err != OK, NULL);
if (state.missing_textures.size()) {
@@ -2427,82 +2257,70 @@ Node* EditorSceneImporterCollada::import_scene(const String& p_path, uint32_t p_
}
*/
-
if (r_missing_deps) {
- for(int i=0;i<state.missing_textures.size();i++) {
+ for (int i = 0; i < state.missing_textures.size(); i++) {
//EditorNode::add_io_error("Texture Not Found: "+state.missing_textures[i]);
r_missing_deps->push_back(state.missing_textures[i]);
}
-
}
}
- if (p_flags&IMPORT_ANIMATION) {
+ if (p_flags & IMPORT_ANIMATION) {
- state.create_animations(p_flags&IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS,p_flags&EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
- AnimationPlayer *ap = memnew( AnimationPlayer );
- for(int i=0;i<state.animations.size();i++) {
+ state.create_animations(p_flags & IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS, p_flags & EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
+ AnimationPlayer *ap = memnew(AnimationPlayer);
+ for (int i = 0; i < state.animations.size(); i++) {
String name;
- if (state.animations[i]->get_name()=="")
- name="default";
+ if (state.animations[i]->get_name() == "")
+ name = "default";
else
- name=state.animations[i]->get_name();
+ name = state.animations[i]->get_name();
- if (p_flags&IMPORT_ANIMATION_DETECT_LOOP) {
+ if (p_flags & IMPORT_ANIMATION_DETECT_LOOP) {
if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
state.animations[i]->set_loop(true);
}
}
- ap->add_animation(name,state.animations[i]);
+ ap->add_animation(name, state.animations[i]);
}
state.scene->add_child(ap);
ap->set_owner(state.scene);
-
}
return state.scene;
-
}
-Ref<Animation> EditorSceneImporterCollada::import_animation(const String& p_path,uint32_t p_flags) {
-
+Ref<Animation> EditorSceneImporterCollada::import_animation(const String &p_path, uint32_t p_flags) {
ColladaImport state;
+ state.use_mesh_builtin_materials = false;
- state.use_mesh_builtin_materials=false;
-
- Error err = state.load(p_path,Collada::IMPORT_FLAG_ANIMATION,p_flags&EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
- ERR_FAIL_COND_V(err!=OK,RES());
+ Error err = state.load(p_path, Collada::IMPORT_FLAG_ANIMATION, p_flags & EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
+ ERR_FAIL_COND_V(err != OK, RES());
-
- state.create_animations(p_flags&EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS,p_flags&EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
+ state.create_animations(p_flags & EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS, p_flags & EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
if (state.scene)
memdelete(state.scene);
- if (state.animations.size()==0)
+ if (state.animations.size() == 0)
return Ref<Animation>();
- Ref<Animation> anim=state.animations[0];
- anim=state.animations[0];
+ Ref<Animation> anim = state.animations[0];
+ anim = state.animations[0];
print_line("Anim Load OK");
String base = p_path.get_basename().to_lower();
- if (p_flags&IMPORT_ANIMATION_DETECT_LOOP) {
+ if (p_flags & IMPORT_ANIMATION_DETECT_LOOP) {
if (base.begins_with("loop") || base.ends_with("loop") || base.begins_with("cycle") || base.ends_with("cycle")) {
anim->set_loop(true);
}
}
-
return anim;
}
-
EditorSceneImporterCollada::EditorSceneImporterCollada() {
-
-
}
-
diff --git a/editor/import/editor_import_collada.h b/editor/import/editor_import_collada.h
index 5c7624bd33..f9e9c10980 100644
--- a/editor/import/editor_import_collada.h
+++ b/editor/import/editor_import_collada.h
@@ -31,21 +31,17 @@
#include "editor/import/resource_importer_scene.h"
-
-
class EditorSceneImporterCollada : public EditorSceneImporter {
- GDCLASS(EditorSceneImporterCollada,EditorSceneImporter );
-public:
+ GDCLASS(EditorSceneImporterCollada, EditorSceneImporter);
+public:
virtual uint32_t get_import_flags() const;
virtual void get_extensions(List<String> *r_extensions) const;
- 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);
- virtual Ref<Animation> import_animation(const String& p_path,uint32_t p_flags);
+ 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);
+ virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags);
EditorSceneImporterCollada();
};
-
#endif
-
diff --git a/editor/import/resource_importer_csv_translation.cpp b/editor/import/resource_importer_csv_translation.cpp
index faf62d2839..3be89920fb 100644
--- a/editor/import/resource_importer_csv_translation.cpp
+++ b/editor/import/resource_importer_csv_translation.cpp
@@ -28,21 +28,21 @@
/*************************************************************************/
#include "resource_importer_csv_translation.h"
+#include "compressed_translation.h"
+#include "io/resource_saver.h"
#include "os/file_access.h"
#include "translation.h"
-#include "io/resource_saver.h"
-#include "compressed_translation.h"
String ResourceImporterCSVTranslation::get_importer_name() const {
return "csv_translation";
}
-String ResourceImporterCSVTranslation::get_visible_name() const{
+String ResourceImporterCSVTranslation::get_visible_name() const {
return "CSV Translation";
}
-void ResourceImporterCSVTranslation::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceImporterCSVTranslation::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("csv");
}
@@ -51,12 +51,12 @@ String ResourceImporterCSVTranslation::get_save_extension() const {
return ""; //does not save a single resoure
}
-String ResourceImporterCSVTranslation::get_resource_type() const{
+String ResourceImporterCSVTranslation::get_resource_type() const {
return "StreamCSVTranslation";
}
-bool ResourceImporterCSVTranslation::get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const {
+bool ResourceImporterCSVTranslation::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
return true;
}
@@ -69,33 +69,27 @@ String ResourceImporterCSVTranslation::get_preset_name(int p_idx) const {
return "";
}
+void ResourceImporterCSVTranslation::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-void ResourceImporterCSVTranslation::get_import_options(List<ImportOption> *r_options,int p_preset) const {
-
-
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"compress"),true));
-
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress"), true));
}
-
-
-Error ResourceImporterCSVTranslation::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) {
-
+Error ResourceImporterCSVTranslation::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) {
bool compress = p_options["compress"];
- FileAccessRef f = FileAccess::open(p_source_file,FileAccess::READ);
+ FileAccessRef f = FileAccess::open(p_source_file, FileAccess::READ);
- ERR_FAIL_COND_V( !f, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(!f, ERR_INVALID_PARAMETER);
Vector<String> line = f->get_csv_line();
- if (line.size()<=1) {
+ if (line.size() <= 1) {
return ERR_PARSE_ERROR;
}
Vector<String> locales;
Vector<Ref<Translation> > translations;
- for(int i=1;i<line.size();i++) {
+ for (int i = 1; i < line.size(); i++) {
String locale = line[i];
if (!TranslationServer::is_locale_valid(locale)) {
@@ -111,44 +105,38 @@ Error ResourceImporterCSVTranslation::import(const String& p_source_file, const
line = f->get_csv_line();
- while(line.size()==locales.size()+1) {
+ while (line.size() == locales.size() + 1) {
String key = line[0];
- if (key!="") {
+ if (key != "") {
- for(int i=1;i<line.size();i++) {
- translations[i-1]->add_message(key,line[i]);
+ for (int i = 1; i < line.size(); i++) {
+ translations[i - 1]->add_message(key, line[i]);
}
}
line = f->get_csv_line();
}
-
- for(int i=0;i<translations.size();i++) {
+ for (int i = 0; i < translations.size(); i++) {
Ref<Translation> xlt = translations[i];
if (compress) {
- Ref<PHashTranslation> cxl = memnew( PHashTranslation );
- cxl->generate( xlt );
- xlt=cxl;
+ Ref<PHashTranslation> cxl = memnew(PHashTranslation);
+ cxl->generate(xlt);
+ xlt = cxl;
}
- String save_path = p_source_file.get_basename()+"."+translations[i]->get_locale()+".xl";
+ String save_path = p_source_file.get_basename() + "." + translations[i]->get_locale() + ".xl";
- ResourceSaver::save(save_path,xlt);
+ ResourceSaver::save(save_path, xlt);
if (r_gen_files) {
r_gen_files->push_back(save_path);
}
}
-
-
return OK;
-
}
-ResourceImporterCSVTranslation::ResourceImporterCSVTranslation()
-{
-
+ResourceImporterCSVTranslation::ResourceImporterCSVTranslation() {
}
diff --git a/editor/import/resource_importer_csv_translation.h b/editor/import/resource_importer_csv_translation.h
index a25e6a0fa8..8b1e1b5827 100644
--- a/editor/import/resource_importer_csv_translation.h
+++ b/editor/import/resource_importer_csv_translation.h
@@ -31,9 +31,8 @@
#include "io/resource_import.h"
-
class ResourceImporterCSVTranslation : public ResourceImporter {
- GDCLASS(ResourceImporterCSVTranslation,ResourceImporter)
+ GDCLASS(ResourceImporterCSVTranslation, ResourceImporter)
public:
virtual String get_importer_name() const;
virtual String get_visible_name() const;
@@ -44,10 +43,10 @@ public:
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
- 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=NULL);
+ 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 = NULL);
ResourceImporterCSVTranslation();
};
diff --git a/editor/import/resource_importer_obj.cpp b/editor/import/resource_importer_obj.cpp
index 3b3e0e3a00..145071d4cb 100644
--- a/editor/import/resource_importer_obj.cpp
+++ b/editor/import/resource_importer_obj.cpp
@@ -29,21 +29,21 @@
#include "resource_importer_obj.h"
#include "io/resource_saver.h"
+#include "os/file_access.h"
#include "scene/resources/mesh.h"
#include "scene/resources/surface_tool.h"
#include "scene/resources/surface_tool.h"
-#include "os/file_access.h"
String ResourceImporterOBJ::get_importer_name() const {
return "obj_mesh";
}
-String ResourceImporterOBJ::get_visible_name() const{
+String ResourceImporterOBJ::get_visible_name() const {
return "OBJ As Mesh";
}
-void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("obj");
}
@@ -51,12 +51,12 @@ String ResourceImporterOBJ::get_save_extension() const {
return "msh";
}
-String ResourceImporterOBJ::get_resource_type() const{
+String ResourceImporterOBJ::get_resource_type() const {
return "Mesh";
}
-bool ResourceImporterOBJ::get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const {
+bool ResourceImporterOBJ::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
return true;
}
@@ -69,138 +69,129 @@ String ResourceImporterOBJ::get_preset_name(int p_idx) const {
return String();
}
+void ResourceImporterOBJ::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-void ResourceImporterOBJ::get_import_options(List<ImportOption> *r_options,int p_preset) const {
-
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"generate/tangents"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"generate/normals"),true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate/tangents"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate/normals"), true));
//not for nowp
//r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"import/materials")));
//r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"import/textures")));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/flip_faces"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/smooth_shading"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/weld_vertices"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"force/weld_tolerance",PROPERTY_HINT_RANGE,"0.00001,16,0.00001"),0.0001));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/flip_faces"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/smooth_shading"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/weld_vertices"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "force/weld_tolerance", PROPERTY_HINT_RANGE, "0.00001,16,0.00001"), 0.0001));
//r_options->push_back(PropertyInfo(Variant::INT,"compress/bitrate",PROPERTY_HINT_ENUM,"64,96,128,192"));
-
}
+Error ResourceImporterOBJ::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) {
+ FileAccessRef f = FileAccess::open(p_source_file, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
-Error ResourceImporterOBJ::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) {
-
- FileAccessRef f = FileAccess::open(p_source_file,FileAccess::READ);
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
-
- Ref<Mesh> mesh = Ref<Mesh>( memnew( Mesh ) );
- Map<String,Ref<Material> > name_map;
-
+ Ref<Mesh> mesh = Ref<Mesh>(memnew(Mesh));
+ Map<String, Ref<Material> > name_map;
-
- bool generate_normals=p_options["generate/normals"];
- bool generate_tangents=p_options["generate/tangents"];
- bool flip_faces=p_options["force/flip_faces"];
- bool force_smooth=p_options["force/smooth_shading"];
- bool weld_vertices=p_options["force/weld_vertices"];
- float weld_tolerance=p_options["force/weld_tolerance"];
+ bool generate_normals = p_options["generate/normals"];
+ bool generate_tangents = p_options["generate/tangents"];
+ bool flip_faces = p_options["force/flip_faces"];
+ bool force_smooth = p_options["force/smooth_shading"];
+ bool weld_vertices = p_options["force/weld_vertices"];
+ float weld_tolerance = p_options["force/weld_tolerance"];
Vector<Vector3> vertices;
Vector<Vector3> normals;
Vector<Vector2> uvs;
String name;
- Ref<SurfaceTool> surf_tool = memnew( SurfaceTool) ;
+ Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
if (force_smooth)
surf_tool->add_smooth_group(true);
- int has_index_data=false;
-
- while(true) {
+ int has_index_data = false;
+ while (true) {
String l = f->get_line().strip_edges();
if (l.begins_with("v ")) {
//vertex
- Vector<String> v = l.split(" ",false);
- ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);
+ Vector<String> v = l.split(" ", false);
+ ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
Vector3 vtx;
- vtx.x=v[1].to_float();
- vtx.y=v[2].to_float();
- vtx.z=v[3].to_float();
+ vtx.x = v[1].to_float();
+ vtx.y = v[2].to_float();
+ vtx.z = v[3].to_float();
vertices.push_back(vtx);
- } else if (l.begins_with("vt ")) {
+ } else if (l.begins_with("vt ")) {
//uv
- Vector<String> v = l.split(" ",false);
- ERR_FAIL_COND_V(v.size()<3,ERR_INVALID_DATA);
+ Vector<String> v = l.split(" ", false);
+ ERR_FAIL_COND_V(v.size() < 3, ERR_INVALID_DATA);
Vector2 uv;
- uv.x=v[1].to_float();
- uv.y=1.0-v[2].to_float();
+ uv.x = v[1].to_float();
+ uv.y = 1.0 - v[2].to_float();
uvs.push_back(uv);
} else if (l.begins_with("vn ")) {
//normal
- Vector<String> v = l.split(" ",false);
- ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);
+ Vector<String> v = l.split(" ", false);
+ ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
Vector3 nrm;
- nrm.x=v[1].to_float();
- nrm.y=v[2].to_float();
- nrm.z=v[3].to_float();
+ nrm.x = v[1].to_float();
+ nrm.y = v[2].to_float();
+ nrm.z = v[3].to_float();
normals.push_back(nrm);
} else if (l.begins_with("f ")) {
- //vertex
+ //vertex
- has_index_data=true;
- Vector<String> v = l.split(" ",false);
- ERR_FAIL_COND_V(v.size()<4,ERR_INVALID_DATA);
+ has_index_data = true;
+ Vector<String> v = l.split(" ", false);
+ ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
//not very fast, could be sped up
-
Vector<String> face[3];
face[0] = v[1].split("/");
face[1] = v[2].split("/");
- ERR_FAIL_COND_V(face[0].size()==0,ERR_PARSE_ERROR);
- ERR_FAIL_COND_V(face[0].size()!=face[1].size(),ERR_PARSE_ERROR);
- for(int i=2;i<v.size()-1;i++) {
+ ERR_FAIL_COND_V(face[0].size() == 0, ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_PARSE_ERROR);
+ for (int i = 2; i < v.size() - 1; i++) {
- face[2] = v[i+1].split("/");
- ERR_FAIL_COND_V(face[0].size()!=face[2].size(),ERR_PARSE_ERROR);
- for(int j=0;j<3;j++) {
+ face[2] = v[i + 1].split("/");
+ ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_PARSE_ERROR);
+ for (int j = 0; j < 3; j++) {
- int idx=j;
+ int idx = j;
- if (!flip_faces && idx<2) {
- idx=1^idx;
+ if (!flip_faces && idx < 2) {
+ idx = 1 ^ idx;
}
-
- if (face[idx].size()==3) {
- int norm = face[idx][2].to_int()-1;
- ERR_FAIL_INDEX_V(norm,normals.size(),ERR_PARSE_ERROR);
+ if (face[idx].size() == 3) {
+ int norm = face[idx][2].to_int() - 1;
+ ERR_FAIL_INDEX_V(norm, normals.size(), ERR_PARSE_ERROR);
surf_tool->add_normal(normals[norm]);
}
- if (face[idx].size()>=2 && face[idx][1]!=String()) {
+ if (face[idx].size() >= 2 && face[idx][1] != String()) {
- int uv = face[idx][1].to_int()-1;
- ERR_FAIL_INDEX_V(uv,uvs.size(),ERR_PARSE_ERROR);
+ int uv = face[idx][1].to_int() - 1;
+ ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_PARSE_ERROR);
surf_tool->add_uv(uvs[uv]);
}
- int vtx = face[idx][0].to_int()-1;
- ERR_FAIL_INDEX_V(vtx,vertices.size(),ERR_PARSE_ERROR);
+ int vtx = face[idx][0].to_int() - 1;
+ ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_PARSE_ERROR);
Vector3 vertex = vertices[vtx];
if (weld_vertices)
- vertex=vertex.snapped(weld_tolerance);
+ vertex = vertex.snapped(weld_tolerance);
surf_tool->add_vertex(vertex);
}
- face[1]=face[2];
+ face[1] = face[2];
}
} else if (l.begins_with("s ") && !force_smooth) { //smoothing
- String what = l.substr(2,l.length()).strip_edges();
- if (what=="off")
+ String what = l.substr(2, l.length()).strip_edges();
+ if (what == "off")
surf_tool->add_smooth_group(false);
else
surf_tool->add_smooth_group(true);
@@ -216,27 +207,27 @@ Error ResourceImporterOBJ::import(const String& p_source_file, const String& p_s
surf_tool->index();
mesh = surf_tool->commit(mesh);
- if (name=="")
- name=vformat(TTR("Surface %d"),mesh->get_surface_count()-1);
- mesh->surface_set_name(mesh->get_surface_count()-1,name);
- name="";
+ if (name == "")
+ name = vformat(TTR("Surface %d"), mesh->get_surface_count() - 1);
+ mesh->surface_set_name(mesh->get_surface_count() - 1, name);
+ name = "";
surf_tool->clear();
surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
if (force_smooth)
surf_tool->add_smooth_group(true);
- has_index_data=false;
+ has_index_data = false;
if (f->eof_reached())
break;
}
if (l.begins_with("o ")) //name
- name=l.substr(2,l.length()).strip_edges();
+ name = l.substr(2, l.length()).strip_edges();
}
}
-/*
+ /*
TODO, check existing materials and merge?
//re-apply materials if exist
for(int i=0;i<mesh->get_surface_count();i++) {
@@ -247,13 +238,10 @@ Error ResourceImporterOBJ::import(const String& p_source_file, const String& p_s
}
*/
- Error err = ResourceSaver::save(p_save_path+".msh",mesh);
+ Error err = ResourceSaver::save(p_save_path + ".msh", mesh);
return err;
-
}
-ResourceImporterOBJ::ResourceImporterOBJ()
-{
-
+ResourceImporterOBJ::ResourceImporterOBJ() {
}
diff --git a/editor/import/resource_importer_obj.h b/editor/import/resource_importer_obj.h
index e4e426f9e8..de2f2eceda 100644
--- a/editor/import/resource_importer_obj.h
+++ b/editor/import/resource_importer_obj.h
@@ -29,11 +29,10 @@
#ifndef RESOURCEIMPORTEROBJ_H
#define RESOURCEIMPORTEROBJ_H
-
#include "io/resource_import.h"
class ResourceImporterOBJ : public ResourceImporter {
- GDCLASS(ResourceImporterOBJ,ResourceImporter)
+ GDCLASS(ResourceImporterOBJ, ResourceImporter)
public:
virtual String get_importer_name() const;
virtual String get_visible_name() const;
@@ -44,13 +43,12 @@ public:
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
- 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=NULL);
+ 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 = NULL);
ResourceImporterOBJ();
};
-
#endif // RESOURCEIMPORTEROBJ_H
diff --git a/editor/import/resource_importer_scene.cpp b/editor/import/resource_importer_scene.cpp
index 3f81b30bf6..8a78376f13 100644
--- a/editor/import/resource_importer_scene.cpp
+++ b/editor/import/resource_importer_scene.cpp
@@ -28,56 +28,51 @@
/*************************************************************************/
#include "resource_importer_scene.h"
-#include "scene/resources/packed_scene.h"
-#include "io/resource_saver.h"
#include "editor/editor_node.h"
+#include "io/resource_saver.h"
+#include "scene/resources/packed_scene.h"
+#include "scene/3d/body_shape.h"
#include "scene/3d/mesh_instance.h"
#include "scene/3d/navigation.h"
-#include "scene/3d/room_instance.h"
-#include "scene/3d/body_shape.h"
#include "scene/3d/physics_body.h"
#include "scene/3d/portal.h"
+#include "scene/3d/room_instance.h"
#include "scene/3d/vehicle_body.h"
-#include "scene/resources/sphere_shape.h"
#include "scene/resources/box_shape.h"
-#include "scene/resources/ray_shape.h"
#include "scene/resources/plane_shape.h"
-
+#include "scene/resources/ray_shape.h"
+#include "scene/resources/sphere_shape.h"
void EditorScenePostImport::_bind_methods() {
- BIND_VMETHOD( MethodInfo("post_import",PropertyInfo(Variant::OBJECT,"scene")) );
-
+ BIND_VMETHOD(MethodInfo("post_import", PropertyInfo(Variant::OBJECT, "scene")));
}
-Node *EditorScenePostImport::post_import(Node* p_scene) {
+Node *EditorScenePostImport::post_import(Node *p_scene) {
if (get_script_instance())
- return get_script_instance()->call("post_import",p_scene);
+ return get_script_instance()->call("post_import", p_scene);
return p_scene;
}
EditorScenePostImport::EditorScenePostImport() {
-
-
}
-
String ResourceImporterScene::get_importer_name() const {
return "scene";
}
-String ResourceImporterScene::get_visible_name() const{
+String ResourceImporterScene::get_visible_name() const {
return "Scene";
}
-void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceImporterScene::get_recognized_extensions(List<String> *p_extensions) const {
- for (Set< Ref<EditorSceneImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
E->get()->get_extensions(p_extensions);
}
}
@@ -86,30 +81,29 @@ String ResourceImporterScene::get_save_extension() const {
return "scn";
}
-String ResourceImporterScene::get_resource_type() const{
+String ResourceImporterScene::get_resource_type() const {
return "PackedScene";
}
-bool ResourceImporterScene::get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const {
+bool ResourceImporterScene::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
if (p_option.begins_with("animation/")) {
- if (p_option!="animation/import" && !bool(p_options["animation/import"]))
+ if (p_option != "animation/import" && !bool(p_options["animation/import"]))
return false;
- if (p_option.begins_with("animation/optimizer/") && p_option!="animation/optimizer/enabled" && !bool(p_options["animation/optimizer/enabled"]))
+ if (p_option.begins_with("animation/optimizer/") && p_option != "animation/optimizer/enabled" && !bool(p_options["animation/optimizer/enabled"]))
return false;
if (p_option.begins_with("animation/clip_")) {
int max_clip = p_options["animation/clips/amount"];
- int clip = p_option.get_slice("/",1).get_slice("_",1).to_int()-1;
- if (clip>=max_clip)
+ int clip = p_option.get_slice("/", 1).get_slice("_", 1).to_int() - 1;
+ if (clip >= max_clip)
return false;
}
}
return true;
-
}
int ResourceImporterScene::get_preset_count() const {
@@ -120,37 +114,34 @@ String ResourceImporterScene::get_preset_name(int p_idx) const {
return "";
}
+static bool _teststr(const String &p_what, const String &p_str) {
-static bool _teststr(const String& p_what,const String& p_str) {
-
- if (p_what.findn("$"+p_str)!=-1) //blender and other stuff
+ if (p_what.findn("$" + p_str) != -1) //blender and other stuff
return true;
- if (p_what.to_lower().ends_with("-"+p_str)) //collada only supports "_" and "-" besides letters
+ if (p_what.to_lower().ends_with("-" + p_str)) //collada only supports "_" and "-" besides letters
return true;
- if (p_what.to_lower().ends_with("_"+p_str)) //collada only supports "_" and "-" besides letters
+ if (p_what.to_lower().ends_with("_" + p_str)) //collada only supports "_" and "-" besides letters
return true;
return false;
}
-static String _fixstr(const String& p_what,const String& p_str) {
+static String _fixstr(const String &p_what, const String &p_str) {
- if (p_what.findn("$"+p_str)!=-1) //blender and other stuff
- return p_what.replace("$"+p_str,"");
- if (p_what.to_lower().ends_with("-"+p_str)) //collada only supports "_" and "-" besides letters
- return p_what.substr(0,p_what.length()-(p_str.length()+1));
- if (p_what.to_lower().ends_with("_"+p_str)) //collada only supports "_" and "-" besides letters
- return p_what.substr(0,p_what.length()-(p_str.length()+1));
+ if (p_what.findn("$" + p_str) != -1) //blender and other stuff
+ return p_what.replace("$" + p_str, "");
+ if (p_what.to_lower().ends_with("-" + p_str)) //collada only supports "_" and "-" besides letters
+ return p_what.substr(0, p_what.length() - (p_str.length() + 1));
+ if (p_what.to_lower().ends_with("_" + p_str)) //collada only supports "_" and "-" besides letters
+ return p_what.substr(0, p_what.length() - (p_str.length() + 1));
return p_what;
}
-
-Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,Ref<Shape> > &collision_map) {
+Node *ResourceImporterScene::_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, Ref<Shape> > &collision_map) {
// children first..
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
-
- Node *r = _fix_node(p_node->get_child(i),p_root,collision_map);
+ Node *r = _fix_node(p_node->get_child(i), p_root, collision_map);
if (!r) {
print_line("was erased..");
i--; //was erased
@@ -159,35 +150,32 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
String name = p_node->get_name();
- bool isroot = p_node==p_root;
-
+ bool isroot = p_node == p_root;
- if (!isroot && _teststr(name,"noimp")) {
+ if (!isroot && _teststr(name, "noimp")) {
memdelete(p_node);
return NULL;
}
-
if (p_node->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
- bool bb=false;
-
- if ((_teststr(name,"bb"))) {
- bb=true;
- } else if (mi->get_mesh().is_valid() && (_teststr(mi->get_mesh()->get_name(),"bb"))) {
- bb=true;
+ bool bb = false;
+ if ((_teststr(name, "bb"))) {
+ bb = true;
+ } else if (mi->get_mesh().is_valid() && (_teststr(mi->get_mesh()->get_name(), "bb"))) {
+ bb = true;
}
if (bb) {
- mi->set_flag(GeometryInstance::FLAG_BILLBOARD,true);
+ mi->set_flag(GeometryInstance::FLAG_BILLBOARD, true);
if (mi->get_mesh().is_valid()) {
Ref<Mesh> m = mi->get_mesh();
- for(int i=0;i<m->get_surface_count();i++) {
+ for (int i = 0; i < m->get_surface_count(); i++) {
Ref<FixedSpatialMaterial> fm = m->surface_get_material(i);
if (fm.is_valid()) {
@@ -201,7 +189,6 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
}
}
-
if (p_node->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
@@ -210,24 +197,23 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
if (m.is_valid()) {
- for(int i=0;i<m->get_surface_count();i++) {
+ for (int i = 0; i < m->get_surface_count(); i++) {
Ref<FixedSpatialMaterial> mat = m->surface_get_material(i);
if (!mat.is_valid())
continue;
- if (_teststr(mat->get_name(),"alpha")) {
+ if (_teststr(mat->get_name(), "alpha")) {
- mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
- mat->set_name(_fixstr(mat->get_name(),"alpha"));
+ mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_name(_fixstr(mat->get_name(), "alpha"));
}
- if (_teststr(mat->get_name(),"vcol")) {
+ if (_teststr(mat->get_name(), "vcol")) {
- mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
- mat->set_name(_fixstr(mat->get_name(),"vcol"));
+ mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
+ mat->set_name(_fixstr(mat->get_name(), "vcol"));
}
-
}
}
}
@@ -238,52 +224,48 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
List<StringName> anims;
ap->get_animation_list(&anims);
- for(List<StringName>::Element *E=anims.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
- Ref<Animation> anim=ap->get_animation(E->get());
+ Ref<Animation> anim = ap->get_animation(E->get());
ERR_CONTINUE(anim.is_null());
- for(int i=0;i<anim->get_track_count();i++) {
+ for (int i = 0; i < anim->get_track_count(); i++) {
NodePath path = anim->track_get_path(i);
- for(int j=0;j<path.get_name_count();j++) {
+ for (int j = 0; j < path.get_name_count(); j++) {
String node = path.get_name(j);
- if (_teststr(node,"noimp")) {
+ if (_teststr(node, "noimp")) {
anim->remove_track(i);
i--;
break;
}
}
}
-
}
}
-
if (p_node->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
String str;
- if ((_teststr(name,"imp"))) {
- str=name;
- } else if (mi->get_mesh().is_valid() && (_teststr(mi->get_mesh()->get_name(),"imp"))) {
- str=mi->get_mesh()->get_name();
-
+ if ((_teststr(name, "imp"))) {
+ str = name;
+ } else if (mi->get_mesh().is_valid() && (_teststr(mi->get_mesh()->get_name(), "imp"))) {
+ str = mi->get_mesh()->get_name();
}
-
if (p_node->get_parent() && p_node->get_parent()->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
MeshInstance *mip = p_node->get_parent()->cast_to<MeshInstance>();
- String d=str.substr(str.find("imp")+3,str.length());
- if (d!="") {
- if ((d[0]<'0' || d[0]>'9'))
- d=d.substr(1,d.length());
- if (d.length() && d[0]>='0' && d[0]<='9') {
+ String d = str.substr(str.find("imp") + 3, str.length());
+ if (d != "") {
+ if ((d[0] < '0' || d[0] > '9'))
+ d = d.substr(1, d.length());
+ if (d.length() && d[0] >= '0' && d[0] <= '9') {
float dist = d.to_double();
- mi->set_flag(GeometryInstance::FLAG_BILLBOARD,true);
- mi->set_flag(GeometryInstance::FLAG_BILLBOARD_FIX_Y,true);
+ mi->set_flag(GeometryInstance::FLAG_BILLBOARD, true);
+ mi->set_flag(GeometryInstance::FLAG_BILLBOARD_FIX_Y, true);
//mi->set_draw_range_begin(dist);
//mi->set_draw_range_end(100000);
@@ -293,7 +275,7 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
if (mi->get_mesh().is_valid()) {
Ref<Mesh> m = mi->get_mesh();
- for(int i=0;i<m->get_surface_count();i++) {
+ for (int i = 0; i < m->get_surface_count(); i++) {
Ref<FixedSpatialMaterial> fm = m->surface_get_material(i);
if (fm.is_valid()) {
@@ -367,24 +349,24 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
//mi->set_baked_light_texture_id(layer);
}
#endif
- if (_teststr(name,"colonly")) {
+ if (_teststr(name, "colonly")) {
if (isroot)
return p_node;
if (p_node->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
- Node * col = mi->create_trimesh_collision_node();
- ERR_FAIL_COND_V(!col,NULL);
+ Node *col = mi->create_trimesh_collision_node();
+ ERR_FAIL_COND_V(!col, NULL);
- col->set_name(_fixstr(name,"colonly"));
+ col->set_name(_fixstr(name, "colonly"));
col->cast_to<Spatial>()->set_transform(mi->get_transform());
p_node->replace_by(col);
memdelete(p_node);
- p_node=col;
+ p_node = col;
StaticBody *sb = col->cast_to<StaticBody>();
- CollisionShape *colshape = memnew( CollisionShape);
+ CollisionShape *colshape = memnew(CollisionShape);
colshape->set_shape(sb->get_shape(0));
colshape->set_name("shape");
sb->add_child(colshape);
@@ -392,29 +374,29 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
} else if (p_node->has_meta("empty_draw_type")) {
String empty_draw_type = String(p_node->get_meta("empty_draw_type"));
print_line(empty_draw_type);
- StaticBody *sb = memnew( StaticBody);
- sb->set_name(_fixstr(name,"colonly"));
+ StaticBody *sb = memnew(StaticBody);
+ sb->set_name(_fixstr(name, "colonly"));
sb->cast_to<Spatial>()->set_transform(p_node->cast_to<Spatial>()->get_transform());
p_node->replace_by(sb);
memdelete(p_node);
- CollisionShape *colshape = memnew( CollisionShape);
+ CollisionShape *colshape = memnew(CollisionShape);
if (empty_draw_type == "CUBE") {
- BoxShape *boxShape = memnew( BoxShape);
+ BoxShape *boxShape = memnew(BoxShape);
boxShape->set_extents(Vector3(1, 1, 1));
colshape->set_shape(boxShape);
colshape->set_name("BoxShape");
} else if (empty_draw_type == "SINGLE_ARROW") {
- RayShape *rayShape = memnew( RayShape);
+ RayShape *rayShape = memnew(RayShape);
rayShape->set_length(1);
colshape->set_shape(rayShape);
colshape->set_name("RayShape");
sb->cast_to<Spatial>()->rotate_x(Math_PI / 2);
} else if (empty_draw_type == "IMAGE") {
- PlaneShape *planeShape = memnew( PlaneShape);
+ PlaneShape *planeShape = memnew(PlaneShape);
colshape->set_shape(planeShape);
colshape->set_name("PlaneShape");
} else {
- SphereShape *sphereShape = memnew( SphereShape);
+ SphereShape *sphereShape = memnew(SphereShape);
sphereShape->set_radius(1);
colshape->set_shape(sphereShape);
colshape->set_name("SphereShape");
@@ -423,7 +405,7 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
colshape->set_owner(sb->get_owner());
}
- } else if (_teststr(name,"rigid") && p_node->cast_to<MeshInstance>()) {
+ } else if (_teststr(name, "rigid") && p_node->cast_to<MeshInstance>()) {
if (isroot)
return p_node;
@@ -433,17 +415,17 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
Rect3 aabb = mi->get_aabb();
// create a new rigid body collision node
- RigidBody * rigid_body = memnew( RigidBody );
- Node * col = rigid_body;
- ERR_FAIL_COND_V(!col,NULL);
+ RigidBody *rigid_body = memnew(RigidBody);
+ Node *col = rigid_body;
+ ERR_FAIL_COND_V(!col, NULL);
// remove node name postfix
- col->set_name(_fixstr(name,"rigid"));
+ col->set_name(_fixstr(name, "rigid"));
// get mesh instance xform matrix to the rigid body collision node
col->cast_to<Spatial>()->set_transform(mi->get_transform());
// save original node by duplicating it into a new instance and correcting the name
- Node * mesh = p_node->duplicate();
- mesh->set_name(_fixstr(name,"rigid"));
+ Node *mesh = p_node->duplicate();
+ mesh->set_name(_fixstr(name, "rigid"));
// reset the xform matrix of the duplicated node so it can inherit parent node xform
mesh->cast_to<Spatial>()->set_transform(Transform(Basis()));
// reparent the new mesh node to the rigid body collision node
@@ -452,69 +434,67 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
// replace the original node with the rigid body collision node
p_node->replace_by(col);
memdelete(p_node);
- p_node=col;
+ p_node = col;
// create an alias for the rigid body collision node
RigidBody *rb = col->cast_to<RigidBody>();
// create a new Box collision shape and set the right extents
- Ref<BoxShape> shape = memnew( BoxShape );
+ Ref<BoxShape> shape = memnew(BoxShape);
shape->set_extents(aabb.get_size() * 0.5);
- CollisionShape *colshape = memnew( CollisionShape);
+ CollisionShape *colshape = memnew(CollisionShape);
colshape->set_name("shape");
colshape->set_shape(shape);
// reparent the new collision shape to the rigid body collision node
rb->add_child(colshape);
colshape->set_owner(p_node->get_owner());
- } else if (_teststr(name,"col") && p_node->cast_to<MeshInstance>()) {
-
+ } else if (_teststr(name, "col") && p_node->cast_to<MeshInstance>()) {
MeshInstance *mi = p_node->cast_to<MeshInstance>();
- mi->set_name(_fixstr(name,"col"));
- Node *col= mi->create_trimesh_collision_node();
- ERR_FAIL_COND_V(!col,NULL);
+ mi->set_name(_fixstr(name, "col"));
+ Node *col = mi->create_trimesh_collision_node();
+ ERR_FAIL_COND_V(!col, NULL);
col->set_name("col");
p_node->add_child(col);
- StaticBody *sb=col->cast_to<StaticBody>();
- CollisionShape *colshape = memnew( CollisionShape);
+ StaticBody *sb = col->cast_to<StaticBody>();
+ CollisionShape *colshape = memnew(CollisionShape);
colshape->set_shape(sb->get_shape(0));
colshape->set_name("shape");
col->add_child(colshape);
colshape->set_owner(p_node->get_owner());
sb->set_owner(p_node->get_owner());
- } else if (_teststr(name,"navmesh") && p_node->cast_to<MeshInstance>()) {
+ } else if (_teststr(name, "navmesh") && p_node->cast_to<MeshInstance>()) {
if (isroot)
return p_node;
MeshInstance *mi = p_node->cast_to<MeshInstance>();
- Ref<Mesh> mesh=mi->get_mesh();
- ERR_FAIL_COND_V(mesh.is_null(),NULL);
- NavigationMeshInstance *nmi = memnew( NavigationMeshInstance );
-
+ Ref<Mesh> mesh = mi->get_mesh();
+ ERR_FAIL_COND_V(mesh.is_null(), NULL);
+ NavigationMeshInstance *nmi = memnew(NavigationMeshInstance);
- nmi->set_name(_fixstr(name,"navmesh"));
- Ref<NavigationMesh> nmesh = memnew( NavigationMesh);
+ nmi->set_name(_fixstr(name, "navmesh"));
+ Ref<NavigationMesh> nmesh = memnew(NavigationMesh);
nmesh->create_from_mesh(mesh);
nmi->set_navigation_mesh(nmesh);
nmi->cast_to<Spatial>()->set_transform(mi->get_transform());
p_node->replace_by(nmi);
memdelete(p_node);
- p_node=nmi;
- } else if (_teststr(name,"vehicle")) {
+ p_node = nmi;
+ } else if (_teststr(name, "vehicle")) {
if (isroot)
return p_node;
Node *owner = p_node->get_owner();
Spatial *s = p_node->cast_to<Spatial>();
- VehicleBody *bv = memnew( VehicleBody );
- String n = _fixstr(p_node->get_name(),"vehicle");
+ VehicleBody *bv = memnew(VehicleBody);
+ String n = _fixstr(p_node->get_name(), "vehicle");
bv->set_name(n);
p_node->replace_by(bv);
p_node->set_name(n);
@@ -524,18 +504,17 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
bv->set_transform(s->get_transform());
s->set_transform(Transform());
- p_node=bv;
-
+ p_node = bv;
- } else if (_teststr(name,"wheel")) {
+ } else if (_teststr(name, "wheel")) {
if (isroot)
return p_node;
Node *owner = p_node->get_owner();
Spatial *s = p_node->cast_to<Spatial>();
- VehicleWheel *bv = memnew( VehicleWheel );
- String n = _fixstr(p_node->get_name(),"wheel");
+ VehicleWheel *bv = memnew(VehicleWheel);
+ String n = _fixstr(p_node->get_name(), "wheel");
bv->set_name(n);
p_node->replace_by(bv);
p_node->set_name(n);
@@ -545,10 +524,9 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
bv->set_transform(s->get_transform());
s->set_transform(Transform());
- p_node=bv;
-
- } else if (_teststr(name,"room") && p_node->cast_to<MeshInstance>()) {
+ p_node = bv;
+ } else if (_teststr(name, "room") && p_node->cast_to<MeshInstance>()) {
if (isroot)
return p_node;
@@ -556,42 +534,40 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
MeshInstance *mi = p_node->cast_to<MeshInstance>();
PoolVector<Face3> faces = mi->get_faces(VisualInstance::FACES_SOLID);
-
BSP_Tree bsptree(faces);
- Ref<RoomBounds> area = memnew( RoomBounds );
+ Ref<RoomBounds> area = memnew(RoomBounds);
//area->set_bounds(faces);
//area->set_geometry_hint(faces);
-
- Room * room = memnew( Room );
- room->set_name(_fixstr(name,"room"));
+ Room *room = memnew(Room);
+ room->set_name(_fixstr(name, "room"));
room->set_transform(mi->get_transform());
room->set_room(area);
p_node->replace_by(room);
memdelete(p_node);
- p_node=room;
+ p_node = room;
- } else if (_teststr(name,"room")) {
+ } else if (_teststr(name, "room")) {
if (isroot)
return p_node;
Spatial *dummy = p_node->cast_to<Spatial>();
- ERR_FAIL_COND_V(!dummy,NULL);
+ ERR_FAIL_COND_V(!dummy, NULL);
- Room * room = memnew( Room );
- room->set_name(_fixstr(name,"room"));
+ Room *room = memnew(Room);
+ room->set_name(_fixstr(name, "room"));
room->set_transform(dummy->get_transform());
p_node->replace_by(room);
memdelete(p_node);
- p_node=room;
+ p_node = room;
//room->compute_room_from_subtree();
- } else if (_teststr(name,"portal") && p_node->cast_to<MeshInstance>()) {
+ } else if (_teststr(name, "portal") && p_node->cast_to<MeshInstance>()) {
if (isroot)
return p_node;
@@ -599,78 +575,76 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
MeshInstance *mi = p_node->cast_to<MeshInstance>();
PoolVector<Face3> faces = mi->get_faces(VisualInstance::FACES_SOLID);
- ERR_FAIL_COND_V(faces.size()==0,NULL);
+ ERR_FAIL_COND_V(faces.size() == 0, NULL);
//step 1 compute the plane
Set<Vector3> points;
Plane plane;
Vector3 center;
- for(int i=0;i<faces.size();i++) {
+ for (int i = 0; i < faces.size(); i++) {
Face3 f = faces.get(i);
Plane p = f.get_plane();
- plane.normal+=p.normal;
- plane.d+=p.d;
+ plane.normal += p.normal;
+ plane.d += p.d;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 v = f.vertex[i].snapped(0.01);
if (!points.has(v)) {
points.insert(v);
- center+=v;
+ center += v;
}
}
}
plane.normal.normalize();
- plane.d/=faces.size();
- center/=points.size();
+ plane.d /= faces.size();
+ center /= points.size();
//step 2, create points
Transform t;
t.basis.from_z(plane.normal);
t.basis.transpose();
- t.origin=center;
+ t.origin = center;
Vector<Point2> portal_points;
- for(Set<Vector3>::Element *E=points.front();E;E=E->next()) {
+ for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
Vector3 local = t.xform_inv(E->get());
- portal_points.push_back(Point2(local.x,local.y));
+ portal_points.push_back(Point2(local.x, local.y));
}
// step 3 bubbly sort points
- int swaps=0;
+ int swaps = 0;
do {
- swaps=0;
+ swaps = 0;
- for(int i=0;i<portal_points.size()-1;i++) {
+ for (int i = 0; i < portal_points.size() - 1; i++) {
float a = portal_points[i].angle();
- float b = portal_points[i+1].angle();
+ float b = portal_points[i + 1].angle();
- if (a>b) {
- SWAP( portal_points[i], portal_points[i+1] );
+ if (a > b) {
+ SWAP(portal_points[i], portal_points[i + 1]);
swaps++;
}
-
}
- } while(swaps);
+ } while (swaps);
-
- Portal *portal = memnew( Portal );
+ Portal *portal = memnew(Portal);
portal->set_shape(portal_points);
- portal->set_transform( mi->get_transform() * t);
+ portal->set_transform(mi->get_transform() * t);
p_node->replace_by(portal);
memdelete(p_node);
- p_node=portal;
+ p_node = portal;
} else if (p_node->cast_to<MeshInstance>()) {
@@ -681,9 +655,9 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
Ref<Mesh> mesh = mi->get_mesh();
if (!mesh.is_null()) {
- if (_teststr(mesh->get_name(),"col")) {
+ if (_teststr(mesh->get_name(), "col")) {
- mesh->set_name( _fixstr(mesh->get_name(),"col") );
+ mesh->set_name(_fixstr(mesh->get_name(), "col"));
Ref<Shape> shape;
if (collision_map.has(mesh)) {
@@ -693,9 +667,7 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
shape = mesh->create_trimesh_shape();
if (!shape.is_null())
- collision_map[mesh]=shape;
-
-
+ collision_map[mesh] = shape;
}
if (!shape.is_null()) {
@@ -711,15 +683,14 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
static_body->set_owner( mi->get_owner() );
#endif
}
-
}
- for(int i=0;i<mesh->get_surface_count();i++) {
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
Ref<FixedSpatialMaterial> fm = mesh->surface_get_material(i);
if (fm.is_valid()) {
String name = fm->get_name();
- /* if (_teststr(name,"alpha")) {
+ /* if (_teststr(name,"alpha")) {
fm->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_ALPHA,true);
name=_fixstr(name,"alpha");
}
@@ -731,22 +702,18 @@ Node* ResourceImporterScene::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,R
fm->set_name(name);
}
}
-
}
-
}
-
return p_node;
}
-
-void ResourceImporterScene::_create_clips(Node *scene, const Array& p_clips,bool p_bake_all) {
+void ResourceImporterScene::_create_clips(Node *scene, const Array &p_clips, bool p_bake_all) {
if (!scene->has_node(String("AnimationPlayer")))
return;
- Node* n = scene->get_node(String("AnimationPlayer"));
+ Node *n = scene->get_node(String("AnimationPlayer"));
ERR_FAIL_COND(!n);
AnimationPlayer *anim = n->cast_to<AnimationPlayer>();
ERR_FAIL_COND(!anim);
@@ -754,185 +721,173 @@ void ResourceImporterScene::_create_clips(Node *scene, const Array& p_clips,bool
if (!anim->has_animation("default"))
return;
-
Ref<Animation> default_anim = anim->get_animation("default");
- for(int i=0;i<p_clips.size();i+=4) {
+ for (int i = 0; i < p_clips.size(); i += 4) {
String name = p_clips[i];
- float from=p_clips[i+1];
- float to=p_clips[i+2];
- bool loop=p_clips[i+3];
- if (from>=to)
+ float from = p_clips[i + 1];
+ float to = p_clips[i + 2];
+ bool loop = p_clips[i + 3];
+ if (from >= to)
continue;
- Ref<Animation> new_anim = memnew( Animation );
-
- for(int j=0;j<default_anim->get_track_count();j++) {
+ Ref<Animation> new_anim = memnew(Animation);
+ for (int j = 0; j < default_anim->get_track_count(); j++) {
List<float> keys;
int kc = default_anim->track_get_key_count(j);
- int dtrack=-1;
- for(int k=0;k<kc;k++) {
+ int dtrack = -1;
+ for (int k = 0; k < kc; k++) {
- float kt = default_anim->track_get_key_time(j,k);
- if (kt>=from && kt<to) {
+ float kt = default_anim->track_get_key_time(j, k);
+ if (kt >= from && kt < to) {
//found a key within range, so create track
- if (dtrack==-1) {
+ if (dtrack == -1) {
new_anim->add_track(default_anim->track_get_type(j));
- dtrack = new_anim->get_track_count()-1;
- new_anim->track_set_path(dtrack,default_anim->track_get_path(j));
+ dtrack = new_anim->get_track_count() - 1;
+ new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
- if (kt>(from+0.01) && k>0) {
+ if (kt > (from + 0.01) && k > 0) {
- if (default_anim->track_get_type(j)==Animation::TYPE_TRANSFORM) {
+ if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
Quat q;
Vector3 p;
Vector3 s;
- default_anim->transform_track_interpolate(j,from,&p,&q,&s);
- new_anim->transform_track_insert_key(dtrack,0,p,q,s);
+ default_anim->transform_track_interpolate(j, from, &p, &q, &s);
+ new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
}
}
-
}
- if (default_anim->track_get_type(j)==Animation::TYPE_TRANSFORM) {
+ if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
Quat q;
Vector3 p;
Vector3 s;
- default_anim->transform_track_get_key(j,k,&p,&q,&s);
- new_anim->transform_track_insert_key(dtrack,kt-from,p,q,s);
+ default_anim->transform_track_get_key(j, k, &p, &q, &s);
+ new_anim->transform_track_insert_key(dtrack, kt - from, p, q, s);
}
-
}
- if (dtrack!=-1 && kt>=to) {
+ if (dtrack != -1 && kt >= to) {
- if (default_anim->track_get_type(j)==Animation::TYPE_TRANSFORM) {
+ if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
Quat q;
Vector3 p;
Vector3 s;
- default_anim->transform_track_interpolate(j,to,&p,&q,&s);
- new_anim->transform_track_insert_key(dtrack,to-from,p,q,s);
+ default_anim->transform_track_interpolate(j, to, &p, &q, &s);
+ new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
}
}
-
}
- if (dtrack==-1 && p_bake_all) {
+ if (dtrack == -1 && p_bake_all) {
new_anim->add_track(default_anim->track_get_type(j));
- dtrack = new_anim->get_track_count()-1;
- new_anim->track_set_path(dtrack,default_anim->track_get_path(j));
- if (default_anim->track_get_type(j)==Animation::TYPE_TRANSFORM) {
-
+ dtrack = new_anim->get_track_count() - 1;
+ new_anim->track_set_path(dtrack, default_anim->track_get_path(j));
+ if (default_anim->track_get_type(j) == Animation::TYPE_TRANSFORM) {
Quat q;
Vector3 p;
Vector3 s;
- default_anim->transform_track_interpolate(j,from,&p,&q,&s);
- new_anim->transform_track_insert_key(dtrack,0,p,q,s);
- default_anim->transform_track_interpolate(j,to,&p,&q,&s);
- new_anim->transform_track_insert_key(dtrack,to-from,p,q,s);
+ default_anim->transform_track_interpolate(j, from, &p, &q, &s);
+ new_anim->transform_track_insert_key(dtrack, 0, p, q, s);
+ default_anim->transform_track_interpolate(j, to, &p, &q, &s);
+ new_anim->transform_track_insert_key(dtrack, to - from, p, q, s);
}
-
}
}
-
new_anim->set_loop(loop);
- new_anim->set_length(to-from);
- anim->add_animation(name,new_anim);
+ new_anim->set_length(to - from);
+ anim->add_animation(name, new_anim);
}
anim->remove_animation("default"); //remove default (no longer needed)
}
-void ResourceImporterScene::_filter_anim_tracks(Ref<Animation> anim,Set<String> &keep) {
+void ResourceImporterScene::_filter_anim_tracks(Ref<Animation> anim, Set<String> &keep) {
Ref<Animation> a = anim;
ERR_FAIL_COND(!a.is_valid());
- print_line("From Anim "+anim->get_name()+":");
+ print_line("From Anim " + anim->get_name() + ":");
- for(int j=0;j<a->get_track_count();j++) {
+ for (int j = 0; j < a->get_track_count(); j++) {
String path = a->track_get_path(j);
if (!keep.has(path)) {
- print_line("Remove: "+path);
+ print_line("Remove: " + path);
a->remove_track(j);
j--;
}
-
}
}
-
-void ResourceImporterScene::_filter_tracks(Node *scene, const String& p_text) {
+void ResourceImporterScene::_filter_tracks(Node *scene, const String &p_text) {
if (!scene->has_node(String("AnimationPlayer")))
return;
- Node* n = scene->get_node(String("AnimationPlayer"));
+ Node *n = scene->get_node(String("AnimationPlayer"));
ERR_FAIL_COND(!n);
AnimationPlayer *anim = n->cast_to<AnimationPlayer>();
ERR_FAIL_COND(!anim);
Vector<String> strings = p_text.split("\n");
- for(int i=0;i<strings.size();i++) {
+ for (int i = 0; i < strings.size(); i++) {
- strings[i]=strings[i].strip_edges();
+ strings[i] = strings[i].strip_edges();
}
List<StringName> anim_names;
anim->get_animation_list(&anim_names);
- for(List<StringName>::Element *E=anim_names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
String name = E->get();
- bool valid_for_this=false;
- bool valid=false;
+ bool valid_for_this = false;
+ bool valid = false;
Set<String> keep;
Set<String> keep_local;
-
- for(int i=0;i<strings.size();i++) {
-
+ for (int i = 0; i < strings.size(); i++) {
if (strings[i].begins_with("@")) {
- valid_for_this=false;
- for(Set<String>::Element *F=keep_local.front();F;F=F->next()) {
+ valid_for_this = false;
+ for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
keep.insert(F->get());
}
keep_local.clear();
- Vector<String> filters=strings[i].substr(1,strings[i].length()).split(",");
- for(int j=0;j<filters.size();j++) {
+ Vector<String> filters = strings[i].substr(1, strings[i].length()).split(",");
+ for (int j = 0; j < filters.size(); j++) {
String fname = filters[j].strip_edges();
- if (fname=="")
+ if (fname == "")
continue;
int fc = fname[0];
bool plus;
- if (fc=='+')
- plus=true;
- else if (fc=='-')
- plus=false;
+ if (fc == '+')
+ plus = true;
+ else if (fc == '-')
+ plus = false;
else
continue;
- String filter=fname.substr(1,fname.length()).strip_edges();
+ String filter = fname.substr(1, fname.length()).strip_edges();
if (!name.matchn(filter))
continue;
- valid_for_this=plus;
+ valid_for_this = plus;
}
if (valid_for_this)
- valid=true;
+ valid = true;
} else if (valid_for_this) {
@@ -940,23 +895,23 @@ void ResourceImporterScene::_filter_tracks(Node *scene, const String& p_text) {
if (!a.is_valid())
continue;
- for(int j=0;j<a->get_track_count();j++) {
+ for (int j = 0; j < a->get_track_count(); j++) {
String path = a->track_get_path(j);
String tname = strings[i];
- if (tname=="")
+ if (tname == "")
continue;
int fc = tname[0];
bool plus;
- if (fc=='+')
- plus=true;
- else if (fc=='-')
- plus=false;
+ if (fc == '+')
+ plus = true;
+ else if (fc == '-')
+ plus = false;
else
continue;
- String filter=tname.substr(1,tname.length()).strip_edges();
+ String filter = tname.substr(1, tname.length()).strip_edges();
if (!path.matchn(filter))
continue;
@@ -967,93 +922,83 @@ void ResourceImporterScene::_filter_tracks(Node *scene, const String& p_text) {
keep_local.erase(path);
}
}
-
}
-
}
if (valid) {
- for(Set<String>::Element *F=keep_local.front();F;F=F->next()) {
+ for (Set<String>::Element *F = keep_local.front(); F; F = F->next()) {
keep.insert(F->get());
}
- _filter_anim_tracks(anim->get_animation(name),keep);
+ _filter_anim_tracks(anim->get_animation(name), keep);
} else {
-
}
-
}
-
-
-
}
-void ResourceImporterScene::_optimize_animations(Node *scene, float p_max_lin_error,float p_max_ang_error,float p_max_angle) {
+void ResourceImporterScene::_optimize_animations(Node *scene, float p_max_lin_error, float p_max_ang_error, float p_max_angle) {
if (!scene->has_node(String("AnimationPlayer")))
return;
- Node* n = scene->get_node(String("AnimationPlayer"));
+ Node *n = scene->get_node(String("AnimationPlayer"));
ERR_FAIL_COND(!n);
AnimationPlayer *anim = n->cast_to<AnimationPlayer>();
ERR_FAIL_COND(!anim);
-
List<StringName> anim_names;
anim->get_animation_list(&anim_names);
- for(List<StringName>::Element *E=anim_names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
Ref<Animation> a = anim->get_animation(E->get());
- a->optimize(p_max_lin_error,p_max_ang_error,Math::deg2rad(p_max_angle));
+ a->optimize(p_max_lin_error, p_max_ang_error, Math::deg2rad(p_max_angle));
}
}
+static String _make_extname(const String &p_str) {
-static String _make_extname(const String& p_str) {
-
- String ext_name=p_str.replace(".","_");
- ext_name=ext_name.replace(":","_");
- ext_name=ext_name.replace("\"","_");
- ext_name=ext_name.replace("<","_");
- ext_name=ext_name.replace(">","_");
- ext_name=ext_name.replace("/","_");
- ext_name=ext_name.replace("|","_");
- ext_name=ext_name.replace("\\","_");
- ext_name=ext_name.replace("?","_");
- ext_name=ext_name.replace("*","_");
+ String ext_name = p_str.replace(".", "_");
+ ext_name = ext_name.replace(":", "_");
+ ext_name = ext_name.replace("\"", "_");
+ ext_name = ext_name.replace("<", "_");
+ ext_name = ext_name.replace(">", "_");
+ ext_name = ext_name.replace("/", "_");
+ ext_name = ext_name.replace("|", "_");
+ ext_name = ext_name.replace("\\", "_");
+ ext_name = ext_name.replace("?", "_");
+ ext_name = ext_name.replace("*", "_");
return ext_name;
}
-void ResourceImporterScene::_make_external_resources(Node* p_node,const String& p_base_path, bool p_make_materials, bool p_make_meshes, Map<Ref<Material>,Ref<Material> >& p_materials, Map<Ref<Mesh>,Ref<Mesh> >& p_meshes) {
+void ResourceImporterScene::_make_external_resources(Node *p_node, const String &p_base_path, bool p_make_materials, bool p_make_meshes, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<Mesh>, Ref<Mesh> > &p_meshes) {
List<PropertyInfo> pi;
p_node->get_property_list(&pi);
- for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
- if (E->get().type==Variant::OBJECT) {
+ if (E->get().type == Variant::OBJECT) {
Ref<Material> mat = p_node->get(E->get().name);
- if (p_make_materials && mat.is_valid() && mat->get_name()!="") {
-
+ if (p_make_materials && mat.is_valid() && mat->get_name() != "") {
if (!p_materials.has(mat)) {
- String ext_name = p_base_path+"."+_make_extname(mat->get_name())+".mtl";
+ String ext_name = p_base_path + "." + _make_extname(mat->get_name()) + ".mtl";
if (FileAccess::exists(ext_name)) {
//if exists, use it
Ref<Material> existing = ResourceLoader::load(ext_name);
- p_materials[mat]=existing;
+ p_materials[mat] = existing;
} else {
- ResourceSaver::save(ext_name,mat,ResourceSaver::FLAG_CHANGE_PATH);
- p_materials[mat]=mat;
+ ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
+ p_materials[mat] = mat;
}
}
- if (p_materials[mat]!=mat) {
+ if (p_materials[mat] != mat) {
- p_node->set(E->get().name,p_materials[mat]);
+ p_node->set(E->get().name, p_materials[mat]);
}
} else {
@@ -1061,62 +1006,57 @@ void ResourceImporterScene::_make_external_resources(Node* p_node,const String&
if (mesh.is_valid()) {
- bool mesh_just_added=false;
+ bool mesh_just_added = false;
if (p_make_meshes) {
if (!p_meshes.has(mesh)) {
- String ext_name = p_base_path+"."+_make_extname(mesh->get_name())+".msh";
+ String ext_name = p_base_path + "." + _make_extname(mesh->get_name()) + ".msh";
if (FileAccess::exists(ext_name)) {
//if exists, use it
Ref<Mesh> existing = ResourceLoader::load(ext_name);
- p_meshes[mesh]=existing;
+ p_meshes[mesh] = existing;
} else {
- ResourceSaver::save(ext_name,mesh,ResourceSaver::FLAG_CHANGE_PATH);
- p_meshes[mesh]=mesh;
- mesh_just_added=true;
+ ResourceSaver::save(ext_name, mesh, ResourceSaver::FLAG_CHANGE_PATH);
+ p_meshes[mesh] = mesh;
+ mesh_just_added = true;
}
-
-
}
}
-
- if (p_make_materials){
+ if (p_make_materials) {
if (mesh_just_added || !p_meshes.has(mesh)) {
-
- for(int i=0;i<mesh->get_surface_count();i++) {
- mat=mesh->surface_get_material(i);
- if (!mat.is_valid() || mat->get_name()=="")
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
+ mat = mesh->surface_get_material(i);
+ if (!mat.is_valid() || mat->get_name() == "")
continue;
if (!p_materials.has(mat)) {
- String ext_name = p_base_path+"."+_make_extname(mat->get_name())+".mtl";
+ String ext_name = p_base_path + "." + _make_extname(mat->get_name()) + ".mtl";
if (FileAccess::exists(ext_name)) {
//if exists, use it
Ref<Material> existing = ResourceLoader::load(ext_name);
- p_materials[mat]=existing;
+ p_materials[mat] = existing;
} else {
- ResourceSaver::save(ext_name,mat,ResourceSaver::FLAG_CHANGE_PATH);
- p_materials[mat]=mat;
+ ResourceSaver::save(ext_name, mat, ResourceSaver::FLAG_CHANGE_PATH);
+ p_materials[mat] = mat;
}
}
- if (p_materials[mat]!=mat) {
+ if (p_materials[mat] != mat) {
- mesh->surface_set_material(i,p_materials[mat]);
+ mesh->surface_set_material(i, p_materials[mat]);
}
-
}
- if(!p_make_meshes) {
- p_meshes[mesh]=Ref<Mesh>(); //save it anyway, so it won't be checked again
+ if (!p_make_meshes) {
+ p_meshes[mesh] = Ref<Mesh>(); //save it anyway, so it won't be checked again
}
}
}
@@ -1125,72 +1065,69 @@ void ResourceImporterScene::_make_external_resources(Node* p_node,const String&
}
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- _make_external_resources(p_node->get_child(i),p_base_path,p_make_materials,p_make_meshes,p_materials,p_meshes);
+ _make_external_resources(p_node->get_child(i), p_base_path, p_make_materials, p_make_meshes, p_materials, p_meshes);
}
}
+void ResourceImporterScene::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-void ResourceImporterScene::get_import_options(List<ImportOption> *r_options,int p_preset) const {
-
-
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING,"nodes/root_type",PROPERTY_HINT_TYPE_STRING,"Node"),"Spatial"));
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING,"nodes/root_name"),"Scene Root"));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_type", PROPERTY_HINT_TYPE_STRING, "Node"), "Spatial"));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/root_name"), "Scene Root"));
List<String> script_extentions;
- ResourceLoader::get_recognized_extensions_for_type("Script",&script_extentions);
+ ResourceLoader::get_recognized_extensions_for_type("Script", &script_extentions);
String script_ext_hint;
- for(List<String>::Element *E=script_extentions.front();E;E=E->next()) {
- if (script_ext_hint!="")
- script_ext_hint+=",";
- script_ext_hint+="*."+E->get();
+ for (List<String>::Element *E = script_extentions.front(); E; E = E->next()) {
+ if (script_ext_hint != "")
+ script_ext_hint += ",";
+ script_ext_hint += "*." + E->get();
}
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING,"nodes/custom_script",PROPERTY_HINT_FILE,script_ext_hint),""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"materials/location",PROPERTY_HINT_ENUM,"Node,Mesh"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"materials/storage",PROPERTY_HINT_ENUM,"Bult-In,Files"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"geometry/compress"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"geometry/ensure_tangents"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"geometry/storage",PROPERTY_HINT_ENUM,"Built-In,Files"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"animation/import",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"animation/fps",PROPERTY_HINT_RANGE,"1,120,1"),15));
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING,"animation/filter_script",PROPERTY_HINT_MULTILINE_TEXT),""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"animation/optimizer/enabled",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"animation/optimizer/max_linear_error"),0.05));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"animation/optimizer/max_angular_error"),0.01));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"animation/optimizer/max_angle"),22));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"animation/optimizer/remove_unused_tracks"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"animation/clips/amount",PROPERTY_HINT_RANGE,"0,256,1",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED),0));
- for(int i=0;i<256;i++) {
- r_options->push_back(ImportOption(PropertyInfo(Variant::STRING,"animation/clip_"+itos(i+1)+"/name"),""));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"animation/clip_"+itos(i+1)+"/start_frame"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"animation/clip_"+itos(i+1)+"/end_frame"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"animation/clip_"+itos(i+1)+"/loops"),false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "nodes/custom_script", PROPERTY_HINT_FILE, script_ext_hint), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/location", PROPERTY_HINT_ENUM, "Node,Mesh"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "materials/storage", PROPERTY_HINT_ENUM, "Bult-In,Files"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "geometry/compress"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "geometry/ensure_tangents"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "geometry/storage", PROPERTY_HINT_ENUM, "Built-In,Files"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/import", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/fps", PROPERTY_HINT_RANGE, "1,120,1"), 15));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/filter_script", PROPERTY_HINT_MULTILINE_TEXT), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_linear_error"), 0.05));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angular_error"), 0.01));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "animation/optimizer/max_angle"), 22));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/optimizer/remove_unused_tracks"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clips/amount", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
+ for (int i = 0; i < 256; i++) {
+ r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "animation/clip_" + itos(i + 1) + "/name"), ""));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/start_frame"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "animation/clip_" + itos(i + 1) + "/end_frame"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "animation/clip_" + itos(i + 1) + "/loops"), false));
}
}
-Error ResourceImporterScene::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) {
+Error ResourceImporterScene::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) {
- String src_path=p_source_file;
+ String src_path = p_source_file;
Ref<EditorSceneImporter> importer;
- String ext=src_path.get_extension().to_lower();
-
+ String ext = src_path.get_extension().to_lower();
- EditorProgress progress("import",TTR("Import Scene"),104);
- progress.step(TTR("Importing Scene.."),0);
+ EditorProgress progress("import", TTR("Import Scene"), 104);
+ progress.step(TTR("Importing Scene.."), 0);
- for(Set< Ref<EditorSceneImporter> >::Element *E=importers.front();E;E=E->next()) {
+ for (Set<Ref<EditorSceneImporter> >::Element *E = importers.front(); E; E = E->next()) {
List<String> extensions;
E->get()->get_extensions(&extensions);
- for(List<String>::Element *F=extensions.front();F;F=F->next()) {
+ for (List<String>::Element *F = extensions.front(); F; F = F->next()) {
- if (F->get().to_lower()==ext) {
+ if (F->get().to_lower() == ext) {
importer = E->get();
break;
@@ -1201,145 +1138,135 @@ Error ResourceImporterScene::import(const String& p_source_file, const String& p
break;
}
- ERR_FAIL_COND_V(!importer.is_valid(),ERR_FILE_UNRECOGNIZED);
+ ERR_FAIL_COND_V(!importer.is_valid(), ERR_FILE_UNRECOGNIZED);
- float fps=p_options["animation/fps"];
+ float fps = p_options["animation/fps"];
-
-
- int import_flags=EditorSceneImporter::IMPORT_ANIMATION_DETECT_LOOP;
+ int import_flags = EditorSceneImporter::IMPORT_ANIMATION_DETECT_LOOP;
if (!bool(p_options["animation/optimizer/remove_unused_tracks"]))
- import_flags|=EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS;
+ import_flags |= EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS;
if (bool(p_options["animation/import"]))
- import_flags|=EditorSceneImporter::IMPORT_ANIMATION;
+ import_flags |= EditorSceneImporter::IMPORT_ANIMATION;
if (bool(p_options["geometry/ensure_tangents"]))
- import_flags|=EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS;
-
- if (int(p_options["materials/location"])==0)
- import_flags|=EditorSceneImporter::IMPORT_MATERIALS_IN_INSTANCES;
+ import_flags |= EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS;
+ if (int(p_options["materials/location"]) == 0)
+ import_flags |= EditorSceneImporter::IMPORT_MATERIALS_IN_INSTANCES;
- Error err=OK;
+ Error err = OK;
List<String> missing_deps; // for now, not much will be done with this
- Node *scene = importer->import_scene(src_path,import_flags,fps,&missing_deps,&err);
- if (!scene || err!=OK) {
+ Node *scene = importer->import_scene(src_path, import_flags, fps, &missing_deps, &err);
+ if (!scene || err != OK) {
return err;
}
String root_type = p_options["nodes/root_type"];
- if (scene->get_class()!=root_type) {
+ if (scene->get_class() != root_type) {
Object *base = ClassDB::instance(root_type);
Node *base_node = NULL;
if (base)
- base_node=base->cast_to<Node>();
+ base_node = base->cast_to<Node>();
if (base_node) {
scene->replace_by(base_node);
memdelete(scene);
- scene=base_node;
+ scene = base_node;
}
}
scene->set_name(p_options["nodes/root_name"]);
-
- err=OK;
+ err = OK;
String animation_filter = String(p_options["animation/filter_script"]).strip_edges();
bool use_optimizer = p_options["animation/optimizer/enabled"];
- float anim_optimizer_linerr=p_options["animation/optimizer/max_linear_error"];
- float anim_optimizer_angerr=p_options["animation/optimizer/max_angular_error"];
- float anim_optimizer_maxang=p_options["animation/optimizer/max_angle"];
+ float anim_optimizer_linerr = p_options["animation/optimizer/max_linear_error"];
+ float anim_optimizer_angerr = p_options["animation/optimizer/max_angular_error"];
+ float anim_optimizer_maxang = p_options["animation/optimizer/max_angle"];
- Map<Ref<Mesh>,Ref<Shape> > collision_map;
+ Map<Ref<Mesh>, Ref<Shape> > collision_map;
- scene=_fix_node(scene,scene,collision_map);
+ scene = _fix_node(scene, scene, collision_map);
if (use_optimizer) {
- _optimize_animations(scene,anim_optimizer_linerr,anim_optimizer_angerr,anim_optimizer_maxang);
+ _optimize_animations(scene, anim_optimizer_linerr, anim_optimizer_angerr, anim_optimizer_maxang);
}
Array animation_clips;
{
-
int clip_count = p_options["animation/clips/amount"];
- for(int i=0;i<clip_count;i++) {
- String name = p_options["animation/clip_"+itos(i+1)+"/name"];
- int from_frame = p_options["animation/clip_"+itos(i+1)+"/start_frame"];
- int end_frame = p_options["animation/clip_"+itos(i+1)+"/end_frame"];
- bool loop = p_options["animation/clip_"+itos(i+1)+"/loops"];
+ for (int i = 0; i < clip_count; i++) {
+ String name = p_options["animation/clip_" + itos(i + 1) + "/name"];
+ int from_frame = p_options["animation/clip_" + itos(i + 1) + "/start_frame"];
+ int end_frame = p_options["animation/clip_" + itos(i + 1) + "/end_frame"];
+ bool loop = p_options["animation/clip_" + itos(i + 1) + "/loops"];
animation_clips.push_back(name);
- animation_clips.push_back(from_frame/fps);
- animation_clips.push_back(end_frame/fps);
+ animation_clips.push_back(from_frame / fps);
+ animation_clips.push_back(end_frame / fps);
animation_clips.push_back(loop);
}
-
}
if (animation_clips.size()) {
- _create_clips(scene,animation_clips,!bool(p_options["animation/optimizer/remove_unused_tracks"]));
+ _create_clips(scene, animation_clips, !bool(p_options["animation/optimizer/remove_unused_tracks"]));
}
- if (animation_filter!="") {
- _filter_tracks(scene,animation_filter);
+ if (animation_filter != "") {
+ _filter_tracks(scene, animation_filter);
}
-
bool external_materials = p_options["materials/storage"];
bool external_meshes = p_options["geometry/storage"];
if (external_materials || external_meshes) {
Map<Ref<Material>, Ref<Material> > mat_map;
Map<Ref<Mesh>, Ref<Mesh> > mesh_map;
- _make_external_resources(scene,p_source_file.get_basename(),external_materials,external_meshes,mat_map,mesh_map);
+ _make_external_resources(scene, p_source_file.get_basename(), external_materials, external_meshes, mat_map, mesh_map);
}
- progress.step(TTR("Running Custom Script.."),2);
+ progress.step(TTR("Running Custom Script.."), 2);
String post_import_script_path = p_options["nodes/custom_script"];
- Ref<EditorScenePostImport> post_import_script;
+ Ref<EditorScenePostImport> post_import_script;
- if (post_import_script_path!="") {
- post_import_script_path = post_import_script_path; // FIXME: is there a good reason for this?
+ if (post_import_script_path != "") {
+ post_import_script_path = post_import_script_path; // FIXME: is there a good reason for this?
Ref<Script> scr = ResourceLoader::load(post_import_script_path);
if (!scr.is_valid()) {
- EditorNode::add_io_error(TTR("Couldn't load post-import script:")+" "+post_import_script_path);
+ EditorNode::add_io_error(TTR("Couldn't load post-import script:") + " " + post_import_script_path);
} else {
- post_import_script = Ref<EditorScenePostImport>( memnew( EditorScenePostImport ) );
+ post_import_script = Ref<EditorScenePostImport>(memnew(EditorScenePostImport));
post_import_script->set_script(scr.get_ref_ptr());
if (!post_import_script->get_script_instance()) {
- EditorNode::add_io_error(TTR("Invalid/broken script for post-import (check console):")+" "+post_import_script_path);
+ EditorNode::add_io_error(TTR("Invalid/broken script for post-import (check console):") + " " + post_import_script_path);
post_import_script.unref();
return ERR_CANT_CREATE;
}
}
}
-
if (post_import_script.is_valid()) {
scene = post_import_script->post_import(scene);
if (!scene) {
- EditorNode::add_io_error(TTR("Error running post-import script:")+" "+post_import_script_path);
+ EditorNode::add_io_error(TTR("Error running post-import script:") + " " + post_import_script_path);
return err;
}
-
-
}
- progress.step(TTR("Saving.."),104);
+ progress.step(TTR("Saving.."), 104);
- Ref<PackedScene> packer = memnew( PackedScene );
+ Ref<PackedScene> packer = memnew(PackedScene);
packer->pack(scene);
- print_line("SAVING TO: "+p_save_path+".scn");
- err = ResourceSaver::save(p_save_path+".scn",packer); //do not take over, let the changed files reload themselves
+ print_line("SAVING TO: " + p_save_path + ".scn");
+ err = ResourceSaver::save(p_save_path + ".scn", packer); //do not take over, let the changed files reload themselves
memdelete(scene);
@@ -1348,9 +1275,8 @@ Error ResourceImporterScene::import(const String& p_source_file, const String& p
return OK;
}
-ResourceImporterScene *ResourceImporterScene::singleton=NULL;
+ResourceImporterScene *ResourceImporterScene::singleton = NULL;
-ResourceImporterScene::ResourceImporterScene()
-{
- singleton=this;
+ResourceImporterScene::ResourceImporterScene() {
+ singleton = this;
}
diff --git a/editor/import/resource_importer_scene.h b/editor/import/resource_importer_scene.h
index ab6b223839..799d458837 100644
--- a/editor/import/resource_importer_scene.h
+++ b/editor/import/resource_importer_scene.h
@@ -37,56 +37,53 @@ class Material;
class EditorSceneImporter : public Reference {
- GDCLASS(EditorSceneImporter,Reference );
-public:
+ GDCLASS(EditorSceneImporter, Reference);
+public:
enum ImportFlags {
- IMPORT_SCENE=1,
- IMPORT_ANIMATION=2,
- IMPORT_ANIMATION_DETECT_LOOP=4,
- IMPORT_ANIMATION_OPTIMIZE=8,
- IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS=16,
- IMPORT_ANIMATION_KEEP_VALUE_TRACKS=32,
- IMPORT_GENERATE_TANGENT_ARRAYS=256,
- IMPORT_FAIL_ON_MISSING_DEPENDENCIES=512,
- IMPORT_MATERIALS_IN_INSTANCES=1024
+ IMPORT_SCENE = 1,
+ IMPORT_ANIMATION = 2,
+ IMPORT_ANIMATION_DETECT_LOOP = 4,
+ IMPORT_ANIMATION_OPTIMIZE = 8,
+ IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS = 16,
+ IMPORT_ANIMATION_KEEP_VALUE_TRACKS = 32,
+ IMPORT_GENERATE_TANGENT_ARRAYS = 256,
+ IMPORT_FAIL_ON_MISSING_DEPENDENCIES = 512,
+ IMPORT_MATERIALS_IN_INSTANCES = 1024
};
- virtual uint32_t get_import_flags() const=0;
- virtual void get_extensions(List<String> *r_extensions) const=0;
- virtual Node* import_scene(const String& p_path,uint32_t p_flags,int p_bake_fps,List<String> *r_missing_deps,Error* r_err=NULL)=0;
- virtual Ref<Animation> import_animation(const String& p_path,uint32_t p_flags)=0;
-
-
+ virtual uint32_t get_import_flags() const = 0;
+ virtual void get_extensions(List<String> *r_extensions) const = 0;
+ virtual Node *import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err = NULL) = 0;
+ virtual Ref<Animation> import_animation(const String &p_path, uint32_t p_flags) = 0;
EditorSceneImporter() {}
};
class EditorScenePostImport : public Reference {
- GDCLASS(EditorScenePostImport,Reference );
-protected:
+ GDCLASS(EditorScenePostImport, Reference);
+protected:
static void _bind_methods();
-public:
- virtual Node* post_import(Node* p_scene);
+public:
+ virtual Node *post_import(Node *p_scene);
EditorScenePostImport();
};
-
class ResourceImporterScene : public ResourceImporter {
- GDCLASS(ResourceImporterScene,ResourceImporter)
+ GDCLASS(ResourceImporterScene, ResourceImporter)
- Set< Ref<EditorSceneImporter> > importers;
+ Set<Ref<EditorSceneImporter> > importers;
static ResourceImporterScene *singleton;
-public:
+public:
static ResourceImporterScene *get_singleton() { return singleton; }
- const Set< Ref<EditorSceneImporter> >& get_importers() const { return importers; }
+ const Set<Ref<EditorSceneImporter> > &get_importers() const { return importers; }
void add_importer(Ref<EditorSceneImporter> p_importer) { importers.insert(p_importer); }
@@ -96,26 +93,24 @@ public:
virtual String get_save_extension() const;
virtual String get_resource_type() const;
-
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
- void _make_external_resources(Node* p_node,const String& p_base_path, bool p_make_materials, bool p_make_meshes, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<Mesh>, Ref<Mesh> > &p_meshes);
+ void _make_external_resources(Node *p_node, const String &p_base_path, bool p_make_materials, bool p_make_meshes, Map<Ref<Material>, Ref<Material> > &p_materials, Map<Ref<Mesh>, Ref<Mesh> > &p_meshes);
- Node* _fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>,Ref<Shape> > &collision_map);
+ Node *_fix_node(Node *p_node, Node *p_root, Map<Ref<Mesh>, Ref<Shape> > &collision_map);
- void _create_clips(Node *scene, const Array& p_clips,bool p_bake_all);
- void _filter_anim_tracks(Ref<Animation> anim,Set<String> &keep);
- void _filter_tracks(Node *scene, const String& p_text);
- void _optimize_animations(Node *scene, float p_max_lin_error,float p_max_ang_error,float p_max_angle);
+ void _create_clips(Node *scene, const Array &p_clips, bool p_bake_all);
+ void _filter_anim_tracks(Ref<Animation> anim, Set<String> &keep);
+ void _filter_tracks(Node *scene, const String &p_text);
+ void _optimize_animations(Node *scene, float p_max_lin_error, float p_max_ang_error, float p_max_angle);
- 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=NULL);
+ 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 = NULL);
ResourceImporterScene();
};
-
#endif // RESOURCEIMPORTERSCENE_H
diff --git a/editor/import/resource_importer_texture.cpp b/editor/import/resource_importer_texture.cpp
index f7bd944ceb..cb419e0f4a 100644
--- a/editor/import/resource_importer_texture.cpp
+++ b/editor/import/resource_importer_texture.cpp
@@ -28,48 +28,41 @@
/*************************************************************************/
#include "resource_importer_texture.h"
-#include "io/image_loader.h"
-#include "scene/resources/texture.h"
#include "editor/editor_file_system.h"
#include "io/config_file.h"
+#include "io/image_loader.h"
+#include "scene/resources/texture.h"
-
-void ResourceImporterTexture::_texture_reimport_srgb(const Ref<StreamTexture>& p_tex) {
+void ResourceImporterTexture::_texture_reimport_srgb(const Ref<StreamTexture> &p_tex) {
singleton->mutex->lock();
StringName path = p_tex->get_path();
if (!singleton->make_flags.has(path)) {
- singleton->make_flags[path]=0;
+ singleton->make_flags[path] = 0;
}
- singleton->make_flags[path]|=MAKE_SRGB_FLAG;
+ singleton->make_flags[path] |= MAKE_SRGB_FLAG;
- print_line("requesting srgb for "+String(path));
+ print_line("requesting srgb for " + String(path));
singleton->mutex->unlock();
-
}
-
-
-void ResourceImporterTexture::_texture_reimport_3d(const Ref<StreamTexture>& p_tex) {
-
+void ResourceImporterTexture::_texture_reimport_3d(const Ref<StreamTexture> &p_tex) {
singleton->mutex->lock();
StringName path = p_tex->get_path();
if (!singleton->make_flags.has(path)) {
- singleton->make_flags[path]=0;
+ singleton->make_flags[path] = 0;
}
- singleton->make_flags[path]|=MAKE_3D_FLAG;
+ singleton->make_flags[path] |= MAKE_3D_FLAG;
- print_line("requesting 3d for "+String(path));
+ print_line("requesting 3d for " + String(path));
singleton->mutex->unlock();
-
-
}
void ResourceImporterTexture::update_imports() {
@@ -85,38 +78,36 @@ void ResourceImporterTexture::update_imports() {
}
Vector<String> to_reimport;
- for (Map<StringName,int>::Element *E=make_flags.front();E;E=E->next()) {
-
- print_line("checking for reimport "+String(E->key()));
+ for (Map<StringName, int>::Element *E = make_flags.front(); E; E = E->next()) {
+ print_line("checking for reimport " + String(E->key()));
Ref<ConfigFile> cf;
cf.instance();
- String src_path = String(E->key())+".import";
+ String src_path = String(E->key()) + ".import";
Error err = cf->load(src_path);
- ERR_CONTINUE(err!=OK);
+ ERR_CONTINUE(err != OK);
- bool changed=false;
- if (E->get()&MAKE_SRGB_FLAG && int(cf->get_value("params","flags/srgb"))==2) {
- cf->set_value("params","flags/srgb",1);
- changed=true;
+ bool changed = false;
+ if (E->get() & MAKE_SRGB_FLAG && int(cf->get_value("params", "flags/srgb")) == 2) {
+ cf->set_value("params", "flags/srgb", 1);
+ changed = true;
}
- if (E->get()&MAKE_3D_FLAG && bool(cf->get_value("params","detect_3d"))) {
- cf->set_value("params","detect_3d",false);
- cf->set_value("params","compress/mode",2);
- cf->set_value("params","flags/repeat",true);
- cf->set_value("params","flags/filter",true);
- cf->set_value("params","flags/mipmaps",true);
- changed=true;
+ if (E->get() & MAKE_3D_FLAG && bool(cf->get_value("params", "detect_3d"))) {
+ cf->set_value("params", "detect_3d", false);
+ cf->set_value("params", "compress/mode", 2);
+ cf->set_value("params", "flags/repeat", true);
+ cf->set_value("params", "flags/filter", true);
+ cf->set_value("params", "flags/mipmaps", true);
+ changed = true;
}
if (changed) {
cf->save(src_path);
to_reimport.push_back(E->key());
}
-
}
make_flags.clear();
@@ -126,21 +117,18 @@ void ResourceImporterTexture::update_imports() {
if (to_reimport.size()) {
EditorFileSystem::get_singleton()->reimport_files(to_reimport);
}
-
}
-
-
String ResourceImporterTexture::get_importer_name() const {
return "texture";
}
-String ResourceImporterTexture::get_visible_name() const{
+String ResourceImporterTexture::get_visible_name() const {
return "Texture";
}
-void ResourceImporterTexture::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceImporterTexture::get_recognized_extensions(List<String> *p_extensions) const {
ImageLoader::get_recognized_extensions(p_extensions);
}
@@ -148,14 +136,14 @@ String ResourceImporterTexture::get_save_extension() const {
return "stex";
}
-String ResourceImporterTexture::get_resource_type() const{
+String ResourceImporterTexture::get_resource_type() const {
return "StreamTexture";
}
-bool ResourceImporterTexture::get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const {
+bool ResourceImporterTexture::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
- if (p_option=="compress/lossy_quality" && int(p_options["compress/mode"])!=COMPRESS_LOSSY)
+ if (p_option == "compress/lossy_quality" && int(p_options["compress/mode"]) != COMPRESS_LOSSY)
return false;
return true;
@@ -166,7 +154,7 @@ int ResourceImporterTexture::get_preset_count() const {
}
String ResourceImporterTexture::get_preset_name(int p_idx) const {
- static const char* preset_names[]={
+ static const char *preset_names[] = {
"2D, Detect 3D",
"2D",
"2D Pixel",
@@ -176,30 +164,25 @@ String ResourceImporterTexture::get_preset_name(int p_idx) const {
return preset_names[p_idx];
}
-
-void ResourceImporterTexture::get_import_options(List<ImportOption> *r_options,int p_preset) const {
-
-
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"compress/mode",PROPERTY_HINT_ENUM,"Lossless,Lossy,Video RAM,Uncompressed",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED),p_preset==PRESET_3D?2:0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"compress/lossy_quality",PROPERTY_HINT_RANGE,"0,1,0.01"),0.7));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"flags/repeat",PROPERTY_HINT_ENUM,"Disabled,Enabled,Mirrored"),p_preset==PRESET_3D?1:0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"flags/filter"),p_preset==PRESET_2D_PIXEL?false:true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"flags/mipmaps"),p_preset==PRESET_3D?true:false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"flags/anisotropic"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"flags/srgb",PROPERTY_HINT_ENUM,"Disable,Enable,Detect"),2));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"process/fix_alpha_border"),p_preset!=PRESET_3D?true:false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"process/premult_alpha"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"stream"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"size_limit",PROPERTY_HINT_RANGE,"0,4096,1"),0));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"detect_3d"),p_preset==PRESET_DETECT));
-
+void ResourceImporterTexture::get_import_options(List<ImportOption> *r_options, int p_preset) const {
+
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Lossless,Lossy,Video RAM,Uncompressed", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), p_preset == PRESET_3D ? 2 : 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "compress/lossy_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.7));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "flags/repeat", PROPERTY_HINT_ENUM, "Disabled,Enabled,Mirrored"), p_preset == PRESET_3D ? 1 : 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "flags/filter"), p_preset == PRESET_2D_PIXEL ? false : true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "flags/mipmaps"), p_preset == PRESET_3D ? true : false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "flags/anisotropic"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "flags/srgb", PROPERTY_HINT_ENUM, "Disable,Enable,Detect"), 2));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/fix_alpha_border"), p_preset != PRESET_3D ? true : false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/premult_alpha"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "stream"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "size_limit", PROPERTY_HINT_RANGE, "0,4096,1"), 0));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "detect_3d"), p_preset == PRESET_DETECT));
}
+void ResourceImporterTexture::_save_stex(const Image &p_image, const String &p_to_path, int p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, int p_texture_flags, bool p_streamable, bool p_detect_3d, bool p_detect_srgb) {
-void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_to_path, int p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, int p_texture_flags, bool p_streamable, bool p_detect_3d, bool p_detect_srgb) {
-
-
- FileAccess *f = FileAccess::open(p_to_path,FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(p_to_path, FileAccess::WRITE);
f->store_8('G');
f->store_8('D');
f->store_8('S');
@@ -209,17 +192,16 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
f->store_32(p_image.get_height());
f->store_32(p_texture_flags);
- uint32_t format=0;
+ uint32_t format = 0;
if (p_streamable)
- format|=StreamTexture::FORMAT_BIT_STREAM;
- if (p_mipmaps || p_compress_mode==COMPRESS_VIDEO_RAM) //VRAM always uses mipmaps
- format|=StreamTexture::FORMAT_BIT_HAS_MIPMAPS; //mipmaps bit
+ format |= StreamTexture::FORMAT_BIT_STREAM;
+ if (p_mipmaps || p_compress_mode == COMPRESS_VIDEO_RAM) //VRAM always uses mipmaps
+ format |= StreamTexture::FORMAT_BIT_HAS_MIPMAPS; //mipmaps bit
if (p_detect_3d)
- format|=StreamTexture::FORMAT_BIT_DETECT_3D;
+ format |= StreamTexture::FORMAT_BIT_DETECT_3D;
if (p_detect_srgb)
- format|=StreamTexture::FORMAT_BIT_DETECT_SRGB;
-
+ format |= StreamTexture::FORMAT_BIT_DETECT_SRGB;
switch (p_compress_mode) {
case COMPRESS_LOSSLESS: {
@@ -233,13 +215,13 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
int mmc = image.get_mipmap_count() + 1;
- format|=StreamTexture::FORMAT_BIT_LOSSLESS;
+ format |= StreamTexture::FORMAT_BIT_LOSSLESS;
f->store_32(format);
f->store_32(mmc);
- for(int i=0;i<mmc;i++) {
+ for (int i = 0; i < mmc; i++) {
- if (i>0) {
+ if (i > 0) {
image.shrink_x2();
}
@@ -247,12 +229,10 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
int data_len = data.size();
f->store_32(data_len);
- PoolVector<uint8_t>::Read r= data.read();
- f->store_buffer(r.ptr(),data_len);
-
+ PoolVector<uint8_t>::Read r = data.read();
+ f->store_buffer(r.ptr(), data_len);
}
-
} break;
case COMPRESS_LOSSY: {
Image image = p_image;
@@ -264,23 +244,22 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
int mmc = image.get_mipmap_count() + 1;
- format|=StreamTexture::FORMAT_BIT_LOSSY;
+ format |= StreamTexture::FORMAT_BIT_LOSSY;
f->store_32(format);
f->store_32(mmc);
- for(int i=0;i<mmc;i++) {
+ for (int i = 0; i < mmc; i++) {
- if (i>0) {
+ if (i > 0) {
image.shrink_x2();
}
- PoolVector<uint8_t> data = Image::lossy_packer(image,p_lossy_quality);
+ PoolVector<uint8_t> data = Image::lossy_packer(image, p_lossy_quality);
int data_len = data.size();
f->store_32(data_len);
PoolVector<uint8_t>::Read r = data.read();
- f->store_buffer(r.ptr(),data_len);
-
+ f->store_buffer(r.ptr(), data_len);
}
} break;
case COMPRESS_VIDEO_RAM: {
@@ -293,10 +272,10 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
f->store_32(format);
- PoolVector<uint8_t> data=image.get_data();
+ PoolVector<uint8_t> data = image.get_data();
int dl = data.size();
PoolVector<uint8_t>::Read r = data.read();
- f->store_buffer(r.ptr(),dl);
+ f->store_buffer(r.ptr(), dl);
} break;
case COMPRESS_UNCOMPRESSED: {
@@ -311,11 +290,11 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
format |= image.get_format();
f->store_32(format);
- PoolVector<uint8_t> data=image.get_data();
+ PoolVector<uint8_t> data = image.get_data();
int dl = data.size();
PoolVector<uint8_t>::Read r = data.read();
- f->store_buffer(r.ptr(),dl);
+ f->store_buffer(r.ptr(), dl);
} break;
}
@@ -323,54 +302,52 @@ void ResourceImporterTexture::_save_stex(const Image& p_image, const String& p_t
memdelete(f);
}
-Error ResourceImporterTexture::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) {
+Error ResourceImporterTexture::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) {
int compress_mode = p_options["compress/mode"];
- float lossy= p_options["compress/lossy_quality"];
- int repeat= p_options["flags/repeat"];
- bool filter= p_options["flags/filter"];
- bool mipmaps= p_options["flags/mipmaps"];
- bool anisotropic= p_options["flags/anisotropic"];
- int srgb= p_options["flags/srgb"];
- bool fix_alpha_border= p_options["process/fix_alpha_border"];
- bool premult_alpha= p_options["process/premult_alpha"];
+ float lossy = p_options["compress/lossy_quality"];
+ int repeat = p_options["flags/repeat"];
+ bool filter = p_options["flags/filter"];
+ bool mipmaps = p_options["flags/mipmaps"];
+ bool anisotropic = p_options["flags/anisotropic"];
+ int srgb = p_options["flags/srgb"];
+ bool fix_alpha_border = p_options["process/fix_alpha_border"];
+ bool premult_alpha = p_options["process/premult_alpha"];
bool stream = p_options["stream"];
int size_limit = p_options["size_limit"];
-
Image image;
- Error err = ImageLoader::load_image(p_source_file,&image);
- if (err!=OK)
+ Error err = ImageLoader::load_image(p_source_file, &image);
+ if (err != OK)
return err;
-
- int tex_flags=0;
- if (repeat>0)
- tex_flags|=Texture::FLAG_REPEAT;
- if (repeat==2)
- tex_flags|=Texture::FLAG_MIRRORED_REPEAT;
+ int tex_flags = 0;
+ if (repeat > 0)
+ tex_flags |= Texture::FLAG_REPEAT;
+ if (repeat == 2)
+ tex_flags |= Texture::FLAG_MIRRORED_REPEAT;
if (filter)
- tex_flags|=Texture::FLAG_FILTER;
- if (mipmaps || compress_mode==COMPRESS_VIDEO_RAM)
- tex_flags|=Texture::FLAG_MIPMAPS;
+ tex_flags |= Texture::FLAG_FILTER;
+ if (mipmaps || compress_mode == COMPRESS_VIDEO_RAM)
+ tex_flags |= Texture::FLAG_MIPMAPS;
if (anisotropic)
- tex_flags|=Texture::FLAG_ANISOTROPIC_FILTER;
- if (srgb==1)
- tex_flags|=Texture::FLAG_CONVERT_TO_LINEAR;
+ tex_flags |= Texture::FLAG_ANISOTROPIC_FILTER;
+ if (srgb == 1)
+ tex_flags |= Texture::FLAG_CONVERT_TO_LINEAR;
- if (size_limit >0 && (image.get_width()>size_limit || image.get_height()>size_limit )) {
+ if (size_limit > 0 && (image.get_width() > size_limit || image.get_height() > size_limit)) {
//limit size
if (image.get_width() >= image.get_height()) {
int new_width = size_limit;
int new_height = image.get_height() * new_width / image.get_width();
- image.resize(new_width,new_height,Image::INTERPOLATE_CUBIC);
+ image.resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
} else {
int new_height = size_limit;
int new_width = image.get_width() * new_height / image.get_height();
- image.resize(new_width,new_height,Image::INTERPOLATE_CUBIC);
+ image.resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
}
}
@@ -383,40 +360,37 @@ Error ResourceImporterTexture::import(const String& p_source_file, const String&
}
bool detect_3d = p_options["detect_3d"];
- bool detect_srgb = srgb==2;
+ bool detect_srgb = srgb == 2;
- if (compress_mode==COMPRESS_VIDEO_RAM) {
+ if (compress_mode == COMPRESS_VIDEO_RAM) {
//must import in all formats
//Android, GLES 2.x
- _save_stex(image,p_save_path+".etc.stex",compress_mode,lossy,Image::COMPRESS_ETC,mipmaps,tex_flags,stream,detect_3d,detect_srgb);
+ _save_stex(image, p_save_path + ".etc.stex", compress_mode, lossy, Image::COMPRESS_ETC, mipmaps, tex_flags, stream, detect_3d, detect_srgb);
r_platform_variants->push_back("etc");
//_save_stex(image,p_save_path+".etc2.stex",compress_mode,lossy,Image::COMPRESS_ETC2,mipmaps,tex_flags,stream);
//r_platform_variants->push_back("etc2");
- _save_stex(image,p_save_path+".s3tc.stex",compress_mode,lossy,Image::COMPRESS_S3TC,mipmaps,tex_flags,stream,detect_3d,detect_srgb);
+ _save_stex(image, p_save_path + ".s3tc.stex", compress_mode, lossy, Image::COMPRESS_S3TC, mipmaps, tex_flags, stream, detect_3d, detect_srgb);
r_platform_variants->push_back("s3tc");
} else {
//import normally
- _save_stex(image,p_save_path+".stex",compress_mode,lossy,Image::COMPRESS_16BIT /*this is ignored */,mipmaps,tex_flags,stream,detect_3d,detect_srgb);
+ _save_stex(image, p_save_path + ".stex", compress_mode, lossy, Image::COMPRESS_16BIT /*this is ignored */, mipmaps, tex_flags, stream, detect_3d, detect_srgb);
}
return OK;
}
-ResourceImporterTexture *ResourceImporterTexture::singleton=NULL;
+ResourceImporterTexture *ResourceImporterTexture::singleton = NULL;
-ResourceImporterTexture::ResourceImporterTexture()
-{
+ResourceImporterTexture::ResourceImporterTexture() {
- singleton=this;
- StreamTexture::request_3d_callback=_texture_reimport_3d;
- StreamTexture::request_srgb_callback=_texture_reimport_srgb;
+ singleton = this;
+ StreamTexture::request_3d_callback = _texture_reimport_3d;
+ StreamTexture::request_srgb_callback = _texture_reimport_srgb;
mutex = Mutex::create();
}
-ResourceImporterTexture::~ResourceImporterTexture()
-{
+ResourceImporterTexture::~ResourceImporterTexture() {
memdelete(mutex);
}
-
diff --git a/editor/import/resource_importer_texture.h b/editor/import/resource_importer_texture.h
index 2667fb1601..9be016884d 100644
--- a/editor/import/resource_importer_texture.h
+++ b/editor/import/resource_importer_texture.h
@@ -33,29 +33,23 @@
class StreamTexture;
class ResourceImporterTexture : public ResourceImporter {
- GDCLASS(ResourceImporterTexture,ResourceImporter)
-
-
+ GDCLASS(ResourceImporterTexture, ResourceImporter)
protected:
-
enum {
- MAKE_3D_FLAG=1,
- MAKE_SRGB_FLAG=2
+ MAKE_3D_FLAG = 1,
+ MAKE_SRGB_FLAG = 2
};
Mutex *mutex;
- Map<StringName,int> make_flags;
-
- static void _texture_reimport_srgb(const Ref<StreamTexture>& p_tex);
- static void _texture_reimport_3d(const Ref<StreamTexture>& p_tex);
-
-
+ Map<StringName, int> make_flags;
+ static void _texture_reimport_srgb(const Ref<StreamTexture> &p_tex);
+ static void _texture_reimport_3d(const Ref<StreamTexture> &p_tex);
static ResourceImporterTexture *singleton;
-public:
+public:
static ResourceImporterTexture *get_singleton() { return singleton; }
virtual String get_importer_name() const;
virtual String get_visible_name() const;
@@ -63,7 +57,6 @@ public:
virtual String get_save_extension() const;
virtual String get_resource_type() const;
-
enum Preset {
PRESET_DETECT,
PRESET_2D,
@@ -81,13 +74,12 @@ public:
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
-
- void _save_stex(const Image& p_image, const String& p_to_path, int p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, int p_texture_flags, bool p_streamable,bool p_detect_3d,bool p_detect_srgb);
+ 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 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=NULL);
+ void _save_stex(const Image &p_image, const String &p_to_path, int p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, int p_texture_flags, bool p_streamable, bool p_detect_3d, bool p_detect_srgb);
+ 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 = NULL);
void update_imports();
diff --git a/editor/import/resource_importer_wav.cpp b/editor/import/resource_importer_wav.cpp
index 684ef4dc5c..c28c7dd425 100644
--- a/editor/import/resource_importer_wav.cpp
+++ b/editor/import/resource_importer_wav.cpp
@@ -28,21 +28,21 @@
/*************************************************************************/
#include "resource_importer_wav.h"
-#include "scene/resources/audio_stream_sample.h"
-#include "os/file_access.h"
#include "io/marshalls.h"
#include "io/resource_saver.h"
+#include "os/file_access.h"
+#include "scene/resources/audio_stream_sample.h"
String ResourceImporterWAV::get_importer_name() const {
return "wav";
}
-String ResourceImporterWAV::get_visible_name() const{
+String ResourceImporterWAV::get_visible_name() const {
return "Microsoft WAV";
}
-void ResourceImporterWAV::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceImporterWAV::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("wav");
}
@@ -50,12 +50,12 @@ String ResourceImporterWAV::get_save_extension() const {
return "smp";
}
-String ResourceImporterWAV::get_resource_type() const{
+String ResourceImporterWAV::get_resource_type() const {
return "AudioStreamSample";
}
-bool ResourceImporterWAV::get_option_visibility(const String& p_option,const Map<StringName,Variant>& p_options) const {
+bool ResourceImporterWAV::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
return true;
}
@@ -68,84 +68,78 @@ String ResourceImporterWAV::get_preset_name(int p_idx) const {
return String();
}
+void ResourceImporterWAV::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-void ResourceImporterWAV::get_import_options(List<ImportOption> *r_options,int p_preset) const {
-
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/8_bit"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/mono"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"force/max_rate"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::REAL,"force/max_rate_hz",PROPERTY_HINT_EXP_RANGE,"11025,192000,1"),44100));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"edit/trim"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"edit/normalize"),true));
- r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL,"edit/loop"),false));
- r_options->push_back(ImportOption(PropertyInfo(Variant::INT,"compress/mode",PROPERTY_HINT_ENUM,"Disabled,RAM (Ima-ADPCM)"),0));
-
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/8_bit"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/mono"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force/max_rate"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::REAL, "force/max_rate_hz", PROPERTY_HINT_EXP_RANGE, "11025,192000,1"), 44100));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "edit/trim"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "edit/normalize"), true));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "edit/loop"), false));
+ r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Disabled,RAM (Ima-ADPCM)"), 0));
}
-
-Error ResourceImporterWAV::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) {
+Error ResourceImporterWAV::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) {
/* STEP 1, READ WAVE FILE */
Error err;
- FileAccess *file=FileAccess::open(p_source_file, FileAccess::READ,&err);
+ FileAccess *file = FileAccess::open(p_source_file, FileAccess::READ, &err);
- ERR_FAIL_COND_V( err!=OK, ERR_CANT_OPEN );
+ ERR_FAIL_COND_V(err != OK, ERR_CANT_OPEN);
/* CHECK RIFF */
char riff[5];
- riff[4]=0;
- file->get_buffer((uint8_t*)&riff,4); //RIFF
+ riff[4] = 0;
+ file->get_buffer((uint8_t *)&riff, 4); //RIFF
- if (riff[0]!='R' || riff[1]!='I' || riff[2]!='F' || riff[3]!='F') {
+ if (riff[0] != 'R' || riff[1] != 'I' || riff[2] != 'F' || riff[3] != 'F') {
file->close();
memdelete(file);
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
}
-
/* GET FILESIZE */
- uint32_t filesize=file->get_32();
+ uint32_t filesize = file->get_32();
/* CHECK WAVE */
char wave[4];
- file->get_buffer((uint8_t*)&wave,4); //RIFF
-
- if (wave[0]!='W' || wave[1]!='A' || wave[2]!='V' || wave[3]!='E') {
+ file->get_buffer((uint8_t *)&wave, 4); //RIFF
+ if (wave[0] != 'W' || wave[1] != 'A' || wave[2] != 'V' || wave[3] != 'E') {
file->close();
memdelete(file);
ERR_EXPLAIN("Not a WAV file (no WAVE RIFF Header)")
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
}
- int format_bits=0;
- int format_channels=0;
+ int format_bits = 0;
+ int format_channels = 0;
- AudioStreamSample::LoopMode loop=AudioStreamSample::LOOP_DISABLED;
- bool format_found=false;
- bool data_found=false;
- int format_freq=0;
- int loop_begin=0;
- int loop_end=0;
+ AudioStreamSample::LoopMode loop = AudioStreamSample::LOOP_DISABLED;
+ bool format_found = false;
+ bool data_found = false;
+ int format_freq = 0;
+ int loop_begin = 0;
+ int loop_end = 0;
int frames;
Vector<float> data;
while (!file->eof_reached()) {
-
/* chunk */
char chunkID[4];
- file->get_buffer((uint8_t*)&chunkID,4); //RIFF
+ file->get_buffer((uint8_t *)&chunkID, 4); //RIFF
/* chunk size */
- uint32_t chunksize=file->get_32();
- uint32_t file_pos=file->get_pos(); //save file pos, so we can skip to next chunk safely
+ uint32_t chunksize = file->get_32();
+ uint32_t file_pos = file->get_pos(); //save file pos, so we can skip to next chunk safely
if (file->eof_reached()) {
@@ -153,107 +147,96 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
break;
}
- if (chunkID[0]=='f' && chunkID[1]=='m' && chunkID[2]=='t' && chunkID[3]==' ' && !format_found) {
+ if (chunkID[0] == 'f' && chunkID[1] == 'm' && chunkID[2] == 't' && chunkID[3] == ' ' && !format_found) {
/* IS FORMAT CHUNK */
- uint16_t compression_code=file->get_16();
-
+ uint16_t compression_code = file->get_16();
- if (compression_code!=1) {
+ if (compression_code != 1) {
ERR_PRINT("Format not supported for WAVE file (not PCM). Save WAVE files as uncompressed PCM instead.");
break;
}
- format_channels=file->get_16();
- if (format_channels!=1 && format_channels !=2) {
+ format_channels = file->get_16();
+ if (format_channels != 1 && format_channels != 2) {
ERR_PRINT("Format not supported for WAVE file (not stereo or mono)");
break;
-
}
- format_freq=file->get_32(); //sampling rate
+ format_freq = file->get_32(); //sampling rate
file->get_32(); // average bits/second (unused)
file->get_16(); // block align (unused)
- format_bits=file->get_16(); // bits per sample
+ format_bits = file->get_16(); // bits per sample
- if (format_bits%8) {
+ if (format_bits % 8) {
ERR_PRINT("Strange number of bits in sample (not 8,16,24,32)");
break;
}
/* Dont need anything else, continue */
- format_found=true;
+ format_found = true;
}
-
- if (chunkID[0]=='d' && chunkID[1]=='a' && chunkID[2]=='t' && chunkID[3]=='a' && !data_found) {
+ if (chunkID[0] == 'd' && chunkID[1] == 'a' && chunkID[2] == 't' && chunkID[3] == 'a' && !data_found) {
/* IS FORMAT CHUNK */
- data_found=true;
+ data_found = true;
if (!format_found) {
ERR_PRINT("'data' chunk before 'format' chunk found.");
break;
-
}
- frames=chunksize;
+ frames = chunksize;
- frames/=format_channels;
- frames/=(format_bits>>3);
+ frames /= format_channels;
+ frames /= (format_bits >> 3);
/*print_line("chunksize: "+itos(chunksize));
print_line("channels: "+itos(format_channels));
print_line("bits: "+itos(format_bits));
*/
- int len=frames;
- if (format_channels==2)
- len*=2;
- if (format_bits>8)
- len*=2;
-
-
- data.resize(frames*format_channels);
-
- for (int i=0;i<frames;i++) {
+ int len = frames;
+ if (format_channels == 2)
+ len *= 2;
+ if (format_bits > 8)
+ len *= 2;
+ data.resize(frames * format_channels);
- for (int c=0;c<format_channels;c++) {
+ for (int i = 0; i < frames; i++) {
+ for (int c = 0; c < format_channels; c++) {
- if (format_bits==8) {
+ if (format_bits == 8) {
// 8 bit samples are UNSIGNED
uint8_t s = file->get_8();
- s-=128;
- int8_t *sp=(int8_t*)&s;
+ s -= 128;
+ int8_t *sp = (int8_t *)&s;
- data[i*format_channels+c]=float(*sp)/128.0;
+ data[i * format_channels + c] = float(*sp) / 128.0;
} else {
//16+ bits samples are SIGNED
// if sample is > 16 bits, just read extra bytes
- uint32_t s=0;
- for (int b=0;b<(format_bits>>3);b++) {
+ uint32_t s = 0;
+ for (int b = 0; b < (format_bits >> 3); b++) {
- s|=((uint32_t)file->get_8())<<(b*8);
+ s |= ((uint32_t)file->get_8()) << (b * 8);
}
- s<<=(32-format_bits);
- int32_t ss=s;
+ s <<= (32 - format_bits);
+ int32_t ss = s;
-
- data[i*format_channels+c]=(ss>>16)/32768.0;
+ data[i * format_channels + c] = (ss >> 16) / 32768.0;
}
}
-
}
-
-
if (file->eof_reached()) {
file->close();
memdelete(file);
@@ -262,18 +245,17 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
}
}
- if (chunkID[0]=='s' && chunkID[1]=='m' && chunkID[2]=='p' && chunkID[3]=='l') {
+ if (chunkID[0] == 's' && chunkID[1] == 'm' && chunkID[2] == 'p' && chunkID[3] == 'l') {
//loop point info!
- for(int i=0;i<10;i++)
+ for (int i = 0; i < 10; i++)
file->get_32(); // i wish to know why should i do this... no doc!
- loop=file->get_32()?AudioStreamSample::LOOP_PING_PONG:AudioStreamSample::LOOP_FORWARD;
- loop_begin=file->get_32();
- loop_end=file->get_32();
-
+ loop = file->get_32() ? AudioStreamSample::LOOP_PING_PONG : AudioStreamSample::LOOP_FORWARD;
+ loop_begin = file->get_32();
+ loop_end = file->get_32();
}
- file->seek( file_pos+chunksize );
+ file->seek(file_pos + chunksize);
}
file->close();
@@ -281,19 +263,17 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
// STEP 2, APPLY CONVERSIONS
-
- bool is16=format_bits!=8;
- int rate=format_freq;
+ bool is16 = format_bits != 8;
+ int rate = format_freq;
print_line("Input Sample: ");
- print_line("\tframes: "+itos(frames));
- print_line("\tformat_channels: "+itos(format_channels));
- print_line("\t16bits: "+itos(is16));
- print_line("\trate: "+itos(rate));
- print_line("\tloop: "+itos(loop));
- print_line("\tloop begin: "+itos(loop_begin));
- print_line("\tloop end: "+itos(loop_end));
-
+ print_line("\tframes: " + itos(frames));
+ print_line("\tformat_channels: " + itos(format_channels));
+ print_line("\t16bits: " + itos(is16));
+ print_line("\trate: " + itos(rate));
+ print_line("\tloop: " + itos(loop));
+ print_line("\tloop begin: " + itos(loop_begin));
+ print_line("\tloop end: " + itos(loop_end));
//apply frequency limit
@@ -303,64 +283,62 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
//resampleeee!!!
int new_data_frames = frames * limit_rate_hz / rate;
Vector<float> new_data;
- new_data.resize( new_data_frames * format_channels );
- for(int c=0;c<format_channels;c++) {
+ new_data.resize(new_data_frames * format_channels);
+ for (int c = 0; c < format_channels; c++) {
- for(int i=0;i<new_data_frames;i++) {
+ for (int i = 0; i < new_data_frames; i++) {
//simple cubic interpolation should be enough.
float pos = float(i) * frames / new_data_frames;
- float mu = pos-Math::floor(pos);
+ float mu = pos - Math::floor(pos);
int ipos = int(Math::floor(pos));
- float y0=data[MAX(0,ipos-1)*format_channels+c];
- float y1=data[ipos*format_channels+c];
- float y2=data[MIN(frames-1,ipos+1)*format_channels+c];
- float y3=data[MIN(frames-1,ipos+2)*format_channels+c];
+ float y0 = data[MAX(0, ipos - 1) * format_channels + c];
+ float y1 = data[ipos * format_channels + c];
+ float y2 = data[MIN(frames - 1, ipos + 1) * format_channels + c];
+ float y3 = data[MIN(frames - 1, ipos + 2) * format_channels + c];
- float mu2 = mu*mu;
+ float mu2 = mu * mu;
float a0 = y3 - y2 - y0 + y1;
float a1 = y0 - y1 - a0;
float a2 = y2 - y0;
float a3 = y1;
- float res=(a0*mu*mu2+a1*mu2+a2*mu+a3);
+ float res = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3);
- new_data[i*format_channels+c]=res;
+ new_data[i * format_channels + c] = res;
}
}
if (loop) {
- loop_begin=loop_begin*new_data_frames/frames;
- loop_end=loop_end*new_data_frames/frames;
+ loop_begin = loop_begin * new_data_frames / frames;
+ loop_end = loop_end * new_data_frames / frames;
}
- data=new_data;
- rate=limit_rate_hz;
- frames=new_data_frames;
+ data = new_data;
+ rate = limit_rate_hz;
+ frames = new_data_frames;
}
-
bool normalize = p_options["edit/normalize"];
if (normalize) {
- float max=0;
- for(int i=0;i<data.size();i++) {
+ float max = 0;
+ for (int i = 0; i < data.size(); i++) {
float amp = Math::abs(data[i]);
- if (amp>max)
- max=amp;
+ if (amp > max)
+ max = amp;
}
- if (max>0) {
+ if (max > 0) {
- float mult=1.0/max;
- for(int i=0;i<data.size();i++) {
+ float mult = 1.0 / max;
+ for (int i = 0; i < data.size(); i++) {
- data[i]*=mult;
+ data[i] *= mult;
}
-
}
}
@@ -368,111 +346,108 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
if (trim && !loop) {
- int first=0;
- int last=(frames*format_channels)-1;
- bool found=false;
+ int first = 0;
+ int last = (frames * format_channels) - 1;
+ bool found = false;
float limit = Math::db2linear((float)-30);
- for(int i=0;i<data.size();i++) {
+ for (int i = 0; i < data.size(); i++) {
float amp = Math::abs(data[i]);
if (!found && amp > limit) {
- first=i;
- found=true;
+ first = i;
+ found = true;
}
if (found && amp > limit) {
- last=i;
+ last = i;
}
}
- first/=format_channels;
- last/=format_channels;
+ first /= format_channels;
+ last /= format_channels;
- if (first<last) {
+ if (first < last) {
Vector<float> new_data;
- new_data.resize((last-first+1)*format_channels);
- for(int i=first*format_channels;i<=last*format_channels;i++) {
- new_data[i-first*format_channels]=data[i];
+ new_data.resize((last - first + 1) * format_channels);
+ for (int i = first * format_channels; i <= last * format_channels; i++) {
+ new_data[i - first * format_channels] = data[i];
}
- data=new_data;
- frames=data.size()/format_channels;
+ data = new_data;
+ frames = data.size() / format_channels;
}
-
}
bool make_loop = p_options["edit/loop"];
if (make_loop && !loop) {
- loop=AudioStreamSample::LOOP_FORWARD;
- loop_begin=0;
- loop_end=frames;
+ loop = AudioStreamSample::LOOP_FORWARD;
+ loop_begin = 0;
+ loop_end = frames;
}
int compression = p_options["compress/mode"];
bool force_mono = p_options["force/mono"];
-
- if (force_mono && format_channels==2) {
+ if (force_mono && format_channels == 2) {
Vector<float> new_data;
- new_data.resize(data.size()/2);
- for(int i=0;i<frames;i++) {
- new_data[i]=(data[i*2+0]+data[i*2+1])/2.0;
+ new_data.resize(data.size() / 2);
+ for (int i = 0; i < frames; i++) {
+ new_data[i] = (data[i * 2 + 0] + data[i * 2 + 1]) / 2.0;
}
- data=new_data;
- format_channels=1;
+ data = new_data;
+ format_channels = 1;
}
bool force_8_bit = p_options["force/8_bit"];
if (force_8_bit) {
- is16=false;
+ is16 = false;
}
-
PoolVector<uint8_t> dst_data;
AudioStreamSample::Format dst_format;
- if ( compression == 1) {
+ if (compression == 1) {
- dst_format=AudioStreamSample::FORMAT_IMA_ADPCM;
- if (format_channels==1) {
- _compress_ima_adpcm(data,dst_data);
+ dst_format = AudioStreamSample::FORMAT_IMA_ADPCM;
+ if (format_channels == 1) {
+ _compress_ima_adpcm(data, dst_data);
} else {
//byte interleave
Vector<float> left;
Vector<float> right;
- int tframes = data.size()/2;
+ int tframes = data.size() / 2;
left.resize(tframes);
right.resize(tframes);
- for(int i=0;i<tframes;i++) {
- left[i]=data[i*2+0];
- right[i]=data[i*2+1];
+ for (int i = 0; i < tframes; i++) {
+ left[i] = data[i * 2 + 0];
+ right[i] = data[i * 2 + 1];
}
PoolVector<uint8_t> bleft;
PoolVector<uint8_t> bright;
- _compress_ima_adpcm(left,bleft);
- _compress_ima_adpcm(right,bright);
+ _compress_ima_adpcm(left, bleft);
+ _compress_ima_adpcm(right, bright);
int dl = bleft.size();
- dst_data.resize( dl *2 );
+ dst_data.resize(dl * 2);
- PoolVector<uint8_t>::Write w=dst_data.write();
- PoolVector<uint8_t>::Read rl=bleft.read();
- PoolVector<uint8_t>::Read rr=bright.read();
+ PoolVector<uint8_t>::Write w = dst_data.write();
+ PoolVector<uint8_t>::Read rl = bleft.read();
+ PoolVector<uint8_t>::Read rr = bright.read();
- for(int i=0;i<dl;i++) {
- w[i*2+0]=rl[i];
- w[i*2+1]=rr[i];
+ for (int i = 0; i < dl; i++) {
+ w[i * 2 + 0] = rl[i];
+ w[i * 2 + 1] = rr[i];
}
}
@@ -480,26 +455,25 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
} else {
- dst_format=is16?AudioStreamSample::FORMAT_16_BITS:AudioStreamSample::FORMAT_8_BITS;
- dst_data.resize( data.size() * (is16?2:1));
+ dst_format = is16 ? AudioStreamSample::FORMAT_16_BITS : AudioStreamSample::FORMAT_8_BITS;
+ dst_data.resize(data.size() * (is16 ? 2 : 1));
{
PoolVector<uint8_t>::Write w = dst_data.write();
- int ds=data.size();
- for(int i=0;i<ds;i++) {
+ int ds = data.size();
+ for (int i = 0; i < ds; i++) {
if (is16) {
- int16_t v = CLAMP(data[i]*32768,-32768,32767);
- encode_uint16(v,&w[i*2]);
+ int16_t v = CLAMP(data[i] * 32768, -32768, 32767);
+ encode_uint16(v, &w[i * 2]);
} else {
- int8_t v = CLAMP(data[i]*128,-128,127);
- w[i]=v;
+ int8_t v = CLAMP(data[i] * 128, -128, 127);
+ w[i] = v;
}
}
}
}
-
Ref<AudioStreamSample> sample;
sample.instance();
sample->set_data(dst_data);
@@ -508,17 +482,14 @@ Error ResourceImporterWAV::import(const String& p_source_file, const String& p_s
sample->set_loop_mode(loop);
sample->set_loop_begin(loop_begin);
sample->set_loop_end(loop_end);
- sample->set_stereo(format_channels==2);
-
- ResourceSaver::save(p_save_path+".smp",sample);
+ sample->set_stereo(format_channels == 2);
+ ResourceSaver::save(p_save_path + ".smp", sample);
return OK;
-
}
-void ResourceImporterWAV::_compress_ima_adpcm(const Vector<float>& p_data,PoolVector<uint8_t>& dst_data) {
-
+void ResourceImporterWAV::_compress_ima_adpcm(const Vector<float> &p_data, PoolVector<uint8_t> &dst_data) {
/*p_sample_data->data = (void*)malloc(len);
xm_s8 *dataptr=(xm_s8*)p_sample_data->data;*/
@@ -540,41 +511,37 @@ void ResourceImporterWAV::_compress_ima_adpcm(const Vector<float>& p_data,PoolVe
-1, -1, -1, -1, 2, 4, 6, 8
};
-
int datalen = p_data.size();
- int datamax=datalen;
- if (datalen&1)
+ int datamax = datalen;
+ if (datalen & 1)
datalen++;
- dst_data.resize(datalen/2+4);
+ dst_data.resize(datalen / 2 + 4);
PoolVector<uint8_t>::Write w = dst_data.write();
-
- int i,step_idx=0,prev=0;
+ int i, step_idx = 0, prev = 0;
uint8_t *out = w.ptr();
//int16_t xm_prev=0;
- const float *in=p_data.ptr();
-
+ const float *in = p_data.ptr();
/* initial value is zero */
- *(out++) =0;
- *(out++) =0;
+ *(out++) = 0;
+ *(out++) = 0;
/* Table index initial value */
- *(out++) =0;
+ *(out++) = 0;
/* unused */
- *(out++) =0;
+ *(out++) = 0;
- for (i=0;i<datalen;i++) {
- int step,diff,vpdiff,mask;
+ for (i = 0; i < datalen; i++) {
+ int step, diff, vpdiff, mask;
uint8_t nibble;
int16_t xm_sample;
- if (i>=datamax)
- xm_sample=0;
+ if (i >= datamax)
+ xm_sample = 0;
else {
-
- xm_sample=CLAMP(in[i]*32767.0,-32768,32767);
+ xm_sample = CLAMP(in[i] * 32767.0, -32768, 32767);
/*
if (xm_sample==32767 || xm_sample==-32768)
printf("clippy!\n",xm_sample);
@@ -584,16 +551,16 @@ void ResourceImporterWAV::_compress_ima_adpcm(const Vector<float>& p_data,PoolVe
//xm_sample=xm_sample+xm_prev;
//xm_prev=xm_sample;
- diff = (int)xm_sample - prev ;
+ diff = (int)xm_sample - prev;
- nibble=0 ;
- step = _ima_adpcm_step_table[ step_idx ];
- vpdiff = step >> 3 ;
+ nibble = 0;
+ step = _ima_adpcm_step_table[step_idx];
+ vpdiff = step >> 3;
if (diff < 0) {
- nibble=8;
- diff=-diff ;
+ nibble = 8;
+ diff = -diff;
}
- mask = 4 ;
+ mask = 4;
while (mask) {
if (diff >= step) {
@@ -603,45 +570,38 @@ void ResourceImporterWAV::_compress_ima_adpcm(const Vector<float>& p_data,PoolVe
vpdiff += step;
}
- step >>= 1 ;
- mask >>= 1 ;
+ step >>= 1;
+ mask >>= 1;
};
- if (nibble&8)
- prev-=vpdiff ;
+ if (nibble & 8)
+ prev -= vpdiff;
else
- prev+=vpdiff ;
+ prev += vpdiff;
if (prev > 32767) {
//printf("%i,xms %i, prev %i,diff %i, vpdiff %i, clip up %i\n",i,xm_sample,prev,diff,vpdiff,prev);
- prev=32767;
+ prev = 32767;
} else if (prev < -32768) {
//printf("%i,xms %i, prev %i,diff %i, vpdiff %i, clip down %i\n",i,xm_sample,prev,diff,vpdiff,prev);
- prev = -32768 ;
+ prev = -32768;
}
step_idx += _ima_adpcm_index_table[nibble];
- if (step_idx< 0)
- step_idx= 0 ;
- else if (step_idx> 88)
- step_idx= 88 ;
-
+ if (step_idx < 0)
+ step_idx = 0;
+ else if (step_idx > 88)
+ step_idx = 88;
- if (i&1) {
- *out|=nibble<<4;
+ if (i & 1) {
+ *out |= nibble << 4;
out++;
} else {
- *out=nibble;
+ *out = nibble;
}
/*dataptr[i]=prev>>8;*/
}
-
-
-
-
}
-ResourceImporterWAV::ResourceImporterWAV()
-{
-
+ResourceImporterWAV::ResourceImporterWAV() {
}
diff --git a/editor/import/resource_importer_wav.h b/editor/import/resource_importer_wav.h
index bc93799fee..b78ab1e7bf 100644
--- a/editor/import/resource_importer_wav.h
+++ b/editor/import/resource_importer_wav.h
@@ -29,11 +29,10 @@
#ifndef RESOURCEIMPORTWAV_H
#define RESOURCEIMPORTWAV_H
-
#include "io/resource_import.h"
class ResourceImporterWAV : public ResourceImporter {
- GDCLASS(ResourceImporterWAV,ResourceImporter)
+ GDCLASS(ResourceImporterWAV, ResourceImporter)
public:
virtual String get_importer_name() const;
virtual String get_visible_name() const;
@@ -41,16 +40,15 @@ public:
virtual String get_save_extension() const;
virtual String get_resource_type() const;
-
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
- void _compress_ima_adpcm(const Vector<float>& p_data,PoolVector<uint8_t>& dst_data);
+ void _compress_ima_adpcm(const Vector<float> &p_data, PoolVector<uint8_t> &dst_data);
- 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=NULL);
+ 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 = NULL);
ResourceImporterWAV();
};
diff --git a/editor/import_dock.cpp b/editor/import_dock.cpp
index 910274a13e..d245450114 100644
--- a/editor/import_dock.cpp
+++ b/editor/import_dock.cpp
@@ -29,38 +29,36 @@
#include "import_dock.h"
class ImportDockParameters : public Object {
- GDCLASS(ImportDockParameters,Object)
+ GDCLASS(ImportDockParameters, Object)
public:
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
List<PropertyInfo> properties;
Ref<ResourceImporter> importer;
Vector<String> paths;
-
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
if (values.has(p_name)) {
- values[p_name]=p_value;
+ values[p_name] = p_value;
return true;
}
return false;
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ bool _get(const StringName &p_name, Variant &r_ret) const {
if (values.has(p_name)) {
- r_ret=values[p_name];
+ r_ret = values[p_name];
return true;
}
return false;
-
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ void _get_property_list(List<PropertyInfo> *p_list) const {
- for (const List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
- if (!importer->get_option_visibility(E->get().name,values))
+ for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
+ if (!importer->get_option_visibility(E->get().name, values))
continue;
p_list->push_back(E->get());
}
@@ -71,18 +69,17 @@ public:
}
};
-void ImportDock::set_edit_path(const String& p_path) {
+void ImportDock::set_edit_path(const String &p_path) {
Ref<ConfigFile> config;
config.instance();
- Error err = config->load(p_path+".import");
- if (err!=OK) {
+ Error err = config->load(p_path + ".import");
+ if (err != OK) {
clear();
return;
}
-
- params->importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(config->get_value("remap","importer"));
+ params->importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(config->get_value("remap", "importer"));
if (params->importer.is_null()) {
clear();
return;
@@ -94,44 +91,44 @@ void ImportDock::set_edit_path(const String& p_path) {
params->properties.clear();
params->values.clear();
- for (List<ResourceImporter::ImportOption>::Element *E=options.front();E;E=E->next()) {
+ for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
params->properties.push_back(E->get().option);
- if (config->has_section_key("params",E->get().option.name)) {
- params->values[E->get().option.name]=config->get_value("params",E->get().option.name);
+ if (config->has_section_key("params", E->get().option.name)) {
+ params->values[E->get().option.name] = config->get_value("params", E->get().option.name);
} else {
- params->values[E->get().option.name]=E->get().default_value;
+ params->values[E->get().option.name] = E->get().default_value;
}
}
params->update();
List<Ref<ResourceImporter> > importers;
- ResourceFormatImporter::get_singleton()->get_importers_for_extension(p_path.get_extension(),&importers);
- List<Pair<String,String> > importer_names;
+ ResourceFormatImporter::get_singleton()->get_importers_for_extension(p_path.get_extension(), &importers);
+ List<Pair<String, String> > importer_names;
- for (List<Ref<ResourceImporter> > ::Element *E=importers.front();E;E=E->next()) {
- importer_names.push_back(Pair<String,String>(E->get()->get_visible_name(),E->get()->get_importer_name()));
+ for (List<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
+ importer_names.push_back(Pair<String, String>(E->get()->get_visible_name(), E->get()->get_importer_name()));
}
- importer_names.sort_custom<PairSort<String,String> >();
+ importer_names.sort_custom<PairSort<String, String> >();
import_as->clear();
- for (List<Pair<String,String> >::Element *E=importer_names.front();E;E=E->next()) {
+ for (List<Pair<String, String> >::Element *E = importer_names.front(); E; E = E->next()) {
import_as->add_item(E->get().first);
- import_as->set_item_metadata(import_as->get_item_count()-1,E->get().second);
- if (E->get().second==params->importer->get_importer_name()) {
- import_as->select(import_as->get_item_count()-1);
+ import_as->set_item_metadata(import_as->get_item_count() - 1, E->get().second);
+ if (E->get().second == params->importer->get_importer_name()) {
+ import_as->select(import_as->get_item_count() - 1);
}
}
preset->get_popup()->clear();
- if (params->importer->get_preset_count()==0) {
+ if (params->importer->get_preset_count() == 0) {
preset->get_popup()->add_item(TTR("Default"));
} else {
- for (int i=0;i<params->importer->get_preset_count();i++) {
+ for (int i = 0; i < params->importer->get_preset_count(); i++) {
preset->get_popup()->add_item(params->importer->get_preset_name(i));
}
}
@@ -144,22 +141,22 @@ void ImportDock::set_edit_path(const String& p_path) {
imported->set_text(p_path.get_file());
}
-void ImportDock::set_edit_multiple_paths(const Vector<String>& p_paths) {
+void ImportDock::set_edit_multiple_paths(const Vector<String> &p_paths) {
clear();
//use the value that is repeated the mot
- Map<String,Dictionary> value_frequency;
+ Map<String, Dictionary> value_frequency;
- for(int i=0;i<p_paths.size();i++) {
+ for (int i = 0; i < p_paths.size(); i++) {
Ref<ConfigFile> config;
config.instance();
- Error err = config->load(p_paths[i]+".import");
- ERR_CONTINUE(err!=OK);
+ Error err = config->load(p_paths[i] + ".import");
+ ERR_CONTINUE(err != OK);
- if (i==0) {
- params->importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(config->get_value("remap","importer"));
+ if (i == 0) {
+ params->importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(config->get_value("remap", "importer"));
if (params->importer.is_null()) {
clear();
return;
@@ -167,24 +164,22 @@ void ImportDock::set_edit_multiple_paths(const Vector<String>& p_paths) {
}
List<String> keys;
- config->get_section_keys("params",&keys);
+ config->get_section_keys("params", &keys);
-
- for (List<String>::Element *E=keys.front();E;E=E->next()) {
+ for (List<String>::Element *E = keys.front(); E; E = E->next()) {
if (!value_frequency.has(E->get())) {
- value_frequency[E->get()]=Dictionary();
+ value_frequency[E->get()] = Dictionary();
}
- Variant value = config->get_value("params",E->get());
+ Variant value = config->get_value("params", E->get());
if (value_frequency[E->get()].has(value)) {
- value_frequency[E->get()][value]=int(value_frequency[E->get()][value])+1;
+ value_frequency[E->get()][value] = int(value_frequency[E->get()][value]) + 1;
} else {
- value_frequency[E->get()][value]=1;
+ value_frequency[E->get()][value] = 1;
}
}
-
}
ERR_FAIL_COND(params->importer.is_null());
@@ -195,86 +190,84 @@ void ImportDock::set_edit_multiple_paths(const Vector<String>& p_paths) {
params->properties.clear();
params->values.clear();
- for (List<ResourceImporter::ImportOption>::Element *E=options.front();E;E=E->next()) {
+ for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
params->properties.push_back(E->get().option);
if (value_frequency.has(E->get().option.name)) {
Dictionary d = value_frequency[E->get().option.name];
- int freq=0;
+ int freq = 0;
List<Variant> v;
d.get_key_list(&v);
Variant value;
- for (List<Variant>::Element *F=v.front();F;F=F->next()) {
+ for (List<Variant>::Element *F = v.front(); F; F = F->next()) {
int f = d[F->get()];
- if (f>freq) {
- value=F->get();
+ if (f > freq) {
+ value = F->get();
}
}
- params->values[E->get().option.name]=value;
+ params->values[E->get().option.name] = value;
} else {
- params->values[E->get().option.name]=E->get().default_value;
+ params->values[E->get().option.name] = E->get().default_value;
}
}
params->update();
List<Ref<ResourceImporter> > importers;
- ResourceFormatImporter::get_singleton()->get_importers_for_extension(p_paths[0].get_extension(),&importers);
- List<Pair<String,String> > importer_names;
+ ResourceFormatImporter::get_singleton()->get_importers_for_extension(p_paths[0].get_extension(), &importers);
+ List<Pair<String, String> > importer_names;
- for (List<Ref<ResourceImporter> > ::Element *E=importers.front();E;E=E->next()) {
- importer_names.push_back(Pair<String,String>(E->get()->get_visible_name(),E->get()->get_importer_name()));
+ for (List<Ref<ResourceImporter> >::Element *E = importers.front(); E; E = E->next()) {
+ importer_names.push_back(Pair<String, String>(E->get()->get_visible_name(), E->get()->get_importer_name()));
}
- importer_names.sort_custom<PairSort<String,String> >();
+ importer_names.sort_custom<PairSort<String, String> >();
import_as->clear();
- for (List<Pair<String,String> >::Element *E=importer_names.front();E;E=E->next()) {
+ for (List<Pair<String, String> >::Element *E = importer_names.front(); E; E = E->next()) {
import_as->add_item(E->get().first);
- import_as->set_item_metadata(import_as->get_item_count()-1,E->get().second);
- if (E->get().second==params->importer->get_importer_name()) {
- import_as->select(import_as->get_item_count()-1);
+ import_as->set_item_metadata(import_as->get_item_count() - 1, E->get().second);
+ if (E->get().second == params->importer->get_importer_name()) {
+ import_as->select(import_as->get_item_count() - 1);
}
}
preset->get_popup()->clear();
- if (params->importer->get_preset_count()==0) {
+ if (params->importer->get_preset_count() == 0) {
preset->get_popup()->add_item(TTR("Default"));
} else {
- for (int i=0;i<params->importer->get_preset_count();i++) {
+ for (int i = 0; i < params->importer->get_preset_count(); i++) {
preset->get_popup()->add_item(params->importer->get_preset_name(i));
}
}
- params->paths=p_paths;
+ params->paths = p_paths;
import->set_disabled(false);
import_as->set_disabled(false);
- imported->set_text(itos(p_paths.size())+TTR(" Files"));
+ imported->set_text(itos(p_paths.size()) + TTR(" Files"));
}
void ImportDock::_preset_selected(int p_idx) {
- print_line("preset selected? "+p_idx);
+ print_line("preset selected? " + p_idx);
List<ResourceImporter::ImportOption> options;
- params->importer->get_import_options(&options,p_idx);
+ params->importer->get_import_options(&options, p_idx);
- for (List<ResourceImporter::ImportOption>::Element *E=options.front();E;E=E->next()) {
+ for (List<ResourceImporter::ImportOption>::Element *E = options.front(); E; E = E->next()) {
- params->values[E->get().option.name]=E->get().default_value;
+ params->values[E->get().option.name] = E->get().default_value;
}
params->update();
-
}
-
void ImportDock::clear() {
imported->set_text("");
@@ -285,72 +278,68 @@ void ImportDock::clear() {
params->properties.clear();
params->update();
preset->get_popup()->clear();
-
}
void ImportDock::_reimport() {
- for(int i=0;i<params->paths.size();i++) {
+ for (int i = 0; i < params->paths.size(); i++) {
Ref<ConfigFile> config;
config.instance();
- Error err = config->load(params->paths[i]+".import");
- ERR_CONTINUE(err!=OK);
+ Error err = config->load(params->paths[i] + ".import");
+ ERR_CONTINUE(err != OK);
config->erase_section("params");
- for (List<PropertyInfo>::Element *E=params->properties.front();E;E=E->next()) {
- config->set_value("params",E->get().name,params->values[E->get().name]);
+ for (List<PropertyInfo>::Element *E = params->properties.front(); E; E = E->next()) {
+ config->set_value("params", E->get().name, params->values[E->get().name]);
}
- config->save(params->paths[i]+".import");
+ config->save(params->paths[i] + ".import");
}
EditorFileSystem::get_singleton()->reimport_files(params->paths);
EditorFileSystem::get_singleton()->emit_signal("filesystem_changed"); //it changed, so force emitting the signal
-
}
void ImportDock::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_reimport"),&ImportDock::_reimport);
- ClassDB::bind_method(D_METHOD("_preset_selected"),&ImportDock::_preset_selected);
+ ClassDB::bind_method(D_METHOD("_reimport"), &ImportDock::_reimport);
+ ClassDB::bind_method(D_METHOD("_preset_selected"), &ImportDock::_preset_selected);
}
ImportDock::ImportDock() {
-
- imported = memnew( LineEdit );
+ imported = memnew(LineEdit);
imported->set_editable(false);
add_child(imported);
HBoxContainer *hb = memnew(HBoxContainer);
- add_margin_child(TTR("Import As:"),hb);
- import_as = memnew( OptionButton );
+ add_margin_child(TTR("Import As:"), hb);
+ import_as = memnew(OptionButton);
hb->add_child(import_as);
import_as->set_h_size_flags(SIZE_EXPAND_FILL);
- preset = memnew( MenuButton );
+ preset = memnew(MenuButton);
preset->set_text(TTR("Preset.."));
- preset->get_popup()->connect("index_pressed",this,"_preset_selected");
+ preset->get_popup()->connect("index_pressed", this, "_preset_selected");
hb->add_child(preset);
- import_opts = memnew( PropertyEditor );
+ import_opts = memnew(PropertyEditor);
add_child(import_opts);
import_opts->set_v_size_flags(SIZE_EXPAND_FILL);
import_opts->hide_top_label();
import_opts->set_hide_script(true);
- hb = memnew( HBoxContainer );
+ hb = memnew(HBoxContainer);
add_child(hb);
- import = memnew( Button );
+ import = memnew(Button);
import->set_text(TTR("Reimport"));
- import->connect("pressed",this,"_reimport");
+ import->connect("pressed", this, "_reimport");
hb->add_spacer();
hb->add_child(import);
hb->add_spacer();
- params = memnew( ImportDockParameters );
+ params = memnew(ImportDockParameters);
import_opts->edit(params);
-
}
ImportDock::~ImportDock() {
diff --git a/editor/import_dock.h b/editor/import_dock.h
index 0153955d32..2c78b922eb 100644
--- a/editor/import_dock.h
+++ b/editor/import_dock.h
@@ -29,16 +29,16 @@
#ifndef IMPORTDOCK_H
#define IMPORTDOCK_H
-#include "io/resource_import.h"
#include "editor_file_system.h"
+#include "io/resource_import.h"
+#include "property_editor.h"
#include "scene/gui/box_container.h"
#include "scene/gui/option_button.h"
#include "scene/gui/popup_menu.h"
-#include "property_editor.h"
class ImportDockParameters;
class ImportDock : public VBoxContainer {
- GDCLASS(ImportDock,VBoxContainer)
+ GDCLASS(ImportDock, VBoxContainer)
LineEdit *imported;
OptionButton *import_as;
@@ -46,7 +46,7 @@ class ImportDock : public VBoxContainer {
PropertyEditor *import_opts;
List<PropertyInfo> properties;
- Map<StringName,Variant> property_values;
+ Map<StringName, Variant> property_values;
Button *import;
@@ -55,12 +55,13 @@ class ImportDock : public VBoxContainer {
void _preset_selected(int p_idx);
void _reimport();
+
protected:
static void _bind_methods();
-public:
- void set_edit_path(const String& p_path);
- void set_edit_multiple_paths(const Vector<String>& p_paths);
+public:
+ void set_edit_path(const String &p_path);
+ void set_edit_multiple_paths(const Vector<String> &p_paths);
void clear();
ImportDock();
diff --git a/editor/inspector_dock.h b/editor/inspector_dock.h
index be6ed5fa87..83a7e5f54b 100644
--- a/editor/inspector_dock.h
+++ b/editor/inspector_dock.h
@@ -29,9 +29,8 @@
#ifndef INSPECTOR_DOCK_H
#define INSPECTOR_DOCK_H
-#include "scene/gui/box_container.h"
#include "property_editor.h"
-
+#include "scene/gui/box_container.h"
//this is for now bundled in EditorNode, will be moved away here eventually
diff --git a/editor/io_plugins/editor_atlas.cpp b/editor/io_plugins/editor_atlas.cpp
index c5f1ee73cf..1aa480f442 100644
--- a/editor/io_plugins/editor_atlas.cpp
+++ b/editor/io_plugins/editor_atlas.cpp
@@ -35,7 +35,7 @@ struct _EditorAtlasWorkRect {
Size2i s;
Point2i p;
int idx;
- _FORCE_INLINE_ bool operator<(const _EditorAtlasWorkRect& p_r) const { return s.width > p_r.s.width; };
+ _FORCE_INLINE_ bool operator<(const _EditorAtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
};
struct _EditorAtlasWorkRectResult {
@@ -45,7 +45,7 @@ struct _EditorAtlasWorkRectResult {
int max_h;
};
-void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size) {
+void EditorAtlas::fit(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
//super simple, almost brute force scanline stacking fitter
//it's pretty basic for now, but it tries to make sure that the aspect ratio of the
@@ -55,106 +55,98 @@ void EditorAtlas::fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, S
// for example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
// 256x8192 atlas (won't work anywhere).
- ERR_FAIL_COND(p_rects.size()==0);
+ ERR_FAIL_COND(p_rects.size() == 0);
Vector<_EditorAtlasWorkRect> wrects;
wrects.resize(p_rects.size());
- for(int i=0;i<p_rects.size();i++) {
- wrects[i].s=p_rects[i];
- wrects[i].idx=i;
+ for (int i = 0; i < p_rects.size(); i++) {
+ wrects[i].s = p_rects[i];
+ wrects[i].idx = i;
}
wrects.sort();
int widest = wrects[0].s.width;
Vector<_EditorAtlasWorkRectResult> results;
- for(int i=0;i<=12;i++) {
+ for (int i = 0; i <= 12; i++) {
- int w = 1<<i;
- int max_h=0;
- int max_w=0;
- if ( w < widest )
+ int w = 1 << i;
+ int max_h = 0;
+ int max_w = 0;
+ if (w < widest)
continue;
Vector<int> hmax;
hmax.resize(w);
- for(int j=0;j<w;j++)
- hmax[j]=0;
+ for (int j = 0; j < w; j++)
+ hmax[j] = 0;
//place them
- int ofs=0;
+ int ofs = 0;
- for(int j=0;j<wrects.size();j++) {
+ for (int j = 0; j < wrects.size(); j++) {
+ if (ofs + wrects[j].s.width > w) {
- if (ofs+wrects[j].s.width > w) {
-
- ofs=0;
+ ofs = 0;
}
- int from_y=0;
- for(int k=0;k<wrects[j].s.width;k++) {
+ int from_y = 0;
+ for (int k = 0; k < wrects[j].s.width; k++) {
- if (hmax[ofs+k] > from_y)
- from_y=hmax[ofs+k];
+ if (hmax[ofs + k] > from_y)
+ from_y = hmax[ofs + k];
}
- wrects[j].p.x=ofs;
- wrects[j].p.y=from_y;
-
+ wrects[j].p.x = ofs;
+ wrects[j].p.y = from_y;
+ int end_h = from_y + wrects[j].s.height;
+ int end_w = ofs + wrects[j].s.width;
- int end_h = from_y+wrects[j].s.height;
- int end_w = ofs+wrects[j].s.width;
+ for (int k = 0; k < wrects[j].s.width; k++) {
- for(int k=0;k<wrects[j].s.width;k++) {
-
- hmax[ofs+k]=end_h;
+ hmax[ofs + k] = end_h;
}
if (end_h > max_h)
- max_h=end_h;
+ max_h = end_h;
if (end_w > max_w)
- max_w=end_w;
-
- ofs+=wrects[j].s.width;
+ max_w = end_w;
+ ofs += wrects[j].s.width;
}
_EditorAtlasWorkRectResult result;
- result.result=wrects;
- result.max_h=max_h;
- result.max_w=max_w;
+ result.result = wrects;
+ result.max_h = max_h;
+ result.max_w = max_w;
results.push_back(result);
-
}
//find the result with the best aspect ratio
- int best=-1;
- float best_aspect=1e20;
+ int best = -1;
+ float best_aspect = 1e20;
- for(int i=0;i<results.size();i++) {
+ for (int i = 0; i < results.size(); i++) {
float h = results[i].max_h;
float w = results[i].max_w;
- float aspect = h>w ? h/w : w/h;
+ float aspect = h > w ? h / w : w / h;
if (aspect < best_aspect) {
- best=i;
- best_aspect=aspect;
+ best = i;
+ best_aspect = aspect;
}
}
r_result.resize(p_rects.size());
- for(int i=0;i<p_rects.size();i++) {
+ for (int i = 0; i < p_rects.size(); i++) {
- r_result[ results[best].result[i].idx ]=results[best].result[i].p;
+ r_result[results[best].result[i].idx] = results[best].result[i].p;
}
- r_size=Size2(results[best].max_w,results[best].max_h );
-
+ r_size = Size2(results[best].max_w, results[best].max_h);
}
-
-
diff --git a/editor/io_plugins/editor_atlas.h b/editor/io_plugins/editor_atlas.h
index e0cf76576e..1fb8a8ed4e 100644
--- a/editor/io_plugins/editor_atlas.h
+++ b/editor/io_plugins/editor_atlas.h
@@ -34,10 +34,7 @@
class EditorAtlas {
public:
-
- static void fit(const Vector<Size2i>& p_rects,Vector<Point2i>& r_result, Size2i& r_size);
-
-
+ static void fit(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
};
#endif // EDITOR_ATLAS_H
diff --git a/editor/io_plugins/editor_bitmask_import_plugin.cpp b/editor/io_plugins/editor_bitmask_import_plugin.cpp
index 7282cbe4e7..bccf6c262f 100644
--- a/editor/io_plugins/editor_bitmask_import_plugin.cpp
+++ b/editor/io_plugins/editor_bitmask_import_plugin.cpp
@@ -28,15 +28,15 @@
/*************************************************************************/
#include "editor_bitmask_import_plugin.h"
#if 0
-#include "io/image_loader.h"
-#include "editor/editor_file_dialog.h"
#include "editor/editor_dir_dialog.h"
+#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
+#include "editor/editor_settings.h"
#include "editor/property_editor.h"
+#include "io/image_loader.h"
+#include "io/marshalls.h"
#include "io/resource_saver.h"
#include "os/file_access.h"
-#include "io/marshalls.h"
-#include "editor/editor_settings.h"
class _EditorBitMaskImportOptions : public Object {
diff --git a/editor/io_plugins/editor_export_scene.cpp b/editor/io_plugins/editor_export_scene.cpp
index a593b870f9..e6066b9075 100644
--- a/editor/io_plugins/editor_export_scene.cpp
+++ b/editor/io_plugins/editor_export_scene.cpp
@@ -28,13 +28,13 @@
/*************************************************************************/
#include "editor_export_scene.h"
#if 0
+#include "editor/editor_settings.h"
+#include "global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "os/dir_access.h"
#include "os/file_access.h"
-#include "editor/editor_settings.h"
#include "scene/resources/packed_scene.h"
-#include "global_config.h"
Vector<uint8_t> EditorSceneExportPlugin::custom_export(String& p_path,const Ref<EditorExportPlatform> &p_platform) {
diff --git a/editor/io_plugins/editor_font_import_plugin.cpp b/editor/io_plugins/editor_font_import_plugin.cpp
index c792ad717a..bad3b36383 100644
--- a/editor/io_plugins/editor_font_import_plugin.cpp
+++ b/editor/io_plugins/editor_font_import_plugin.cpp
@@ -28,13 +28,13 @@
/*************************************************************************/
#include "editor_font_import_plugin.h"
#if 0
-#include "scene/gui/dialogs.h"
#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
-#include "os/file_access.h"
#include "editor_atlas.h"
#include "io/image_loader.h"
#include "io/resource_saver.h"
+#include "os/file_access.h"
+#include "scene/gui/dialogs.h"
#ifdef FREETYPE_ENABLED
#include <ft2build.h>
@@ -1406,7 +1406,7 @@ Ref<BitmapFont> EditorFontImportPlugin::generate_font(const Ref<ResourceImportMe
for(int si=0;si<2;si++) {
-#define S_VAR(m_v) (String(si==0?"shadow/":"shadow2/")+m_v)
+#define S_VAR(m_v) (String(si == 0 ? "shadow/" : "shadow2/") + m_v)
if (from->get_option(S_VAR("enabled")).operator bool()) {
int r = from->get_option(S_VAR("radius"));
diff --git a/editor/io_plugins/editor_mesh_import_plugin.cpp b/editor/io_plugins/editor_mesh_import_plugin.cpp
index df9d0a62e6..f4d0868d16 100644
--- a/editor/io_plugins/editor_mesh_import_plugin.cpp
+++ b/editor/io_plugins/editor_mesh_import_plugin.cpp
@@ -30,14 +30,14 @@
#if 0
-#include "editor/editor_file_dialog.h"
#include "editor/editor_dir_dialog.h"
+#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
#include "editor/property_editor.h"
//#include "scene/resources/sample.h"
+#include "io/marshalls.h"
#include "io/resource_saver.h"
#include "os/file_access.h"
-#include "io/marshalls.h"
#include "scene/resources/surface_tool.h"
class _EditorMeshImportOptions : public Object {
diff --git a/editor/io_plugins/editor_sample_import_plugin.cpp b/editor/io_plugins/editor_sample_import_plugin.cpp
index d446d39027..a21d41d8c8 100644
--- a/editor/io_plugins/editor_sample_import_plugin.cpp
+++ b/editor/io_plugins/editor_sample_import_plugin.cpp
@@ -28,14 +28,14 @@
/*************************************************************************/
#include "editor_sample_import_plugin.h"
-#include "editor/editor_file_dialog.h"
#include "editor/editor_dir_dialog.h"
+#include "editor/editor_file_dialog.h"
#include "editor/editor_node.h"
+#include "editor/editor_settings.h"
#include "editor/property_editor.h"
+#include "io/marshalls.h"
#include "io/resource_saver.h"
#include "os/file_access.h"
-#include "io/marshalls.h"
-#include "editor/editor_settings.h"
#if 0
diff --git a/editor/io_plugins/editor_scene_import_plugin.cpp b/editor/io_plugins/editor_scene_import_plugin.cpp
index 963968ce47..52a554f6d1 100644
--- a/editor/io_plugins/editor_scene_import_plugin.cpp
+++ b/editor/io_plugins/editor_scene_import_plugin.cpp
@@ -28,27 +28,27 @@
/*************************************************************************/
#include "editor_scene_import_plugin.h"
#if 0
-#include "global_config.h"
+#include "editor/create_dialog.h"
#include "editor/editor_node.h"
-#include "scene/resources/packed_scene.h"
-#include "scene/resources/box_shape.h"
-#include "os/file_access.h"
-#include "scene/3d/path.h"
-#include "scene/animation/animation_player.h"
+#include "global_config.h"
#include "io/resource_saver.h"
+#include "os/file_access.h"
+#include "os/os.h"
+#include "scene/3d/body_shape.h"
#include "scene/3d/mesh_instance.h"
#include "scene/3d/navigation.h"
-#include "scene/3d/room_instance.h"
-#include "scene/3d/body_shape.h"
+#include "scene/3d/path.h"
#include "scene/3d/physics_body.h"
#include "scene/3d/portal.h"
+#include "scene/3d/room_instance.h"
#include "scene/3d/vehicle_body.h"
+#include "scene/animation/animation_player.h"
+#include "scene/resources/box_shape.h"
+#include "scene/resources/packed_scene.h"
#include "scene/resources/sphere_shape.h"
#include <scene/resources/box_shape.h>
-#include <scene/resources/ray_shape.h>
#include <scene/resources/plane_shape.h>
-#include "editor/create_dialog.h"
-#include "os/os.h"
+#include <scene/resources/ray_shape.h>
@@ -2086,9 +2086,6 @@ Node* EditorSceneImportPlugin::_fix_node(Node *p_node,Node *p_root,Map<Ref<Mesh>
return p_node;
}
-
-
-
#if 0
Error EditorImport::import_scene(const String& p_path,const String& p_dest_path,const String& p_resource_path,uint32_t p_flags,ImageFormat p_image_format,ImageCompression p_image_compression,uint32_t p_image_flags,float p_quality,uint32_t animation_flags,Node **r_scene,Ref<EditorPostImport> p_post_import) {
diff --git a/editor/io_plugins/editor_scene_import_plugin.h b/editor/io_plugins/editor_scene_import_plugin.h
index 2ae0693600..e365a003a3 100644
--- a/editor/io_plugins/editor_scene_import_plugin.h
+++ b/editor/io_plugins/editor_scene_import_plugin.h
@@ -29,21 +29,21 @@
#ifndef EDITOR_SCENE_IMPORT_PLUGIN_H
#define EDITOR_SCENE_IMPORT_PLUGIN_H
#if 0
+#include "editor/editor_dir_dialog.h"
+#include "editor/editor_file_system.h"
+#include "editor/editor_import_export.h"
+#include "editor/io_plugins/editor_texture_import_plugin.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/label.h"
-#include "scene/gui/option_button.h"
#include "scene/gui/line_edit.h"
-#include "scene/gui/file_dialog.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/progress_bar.h"
#include "scene/gui/slider.h"
#include "scene/gui/spin_box.h"
-#include "scene/resources/mesh.h"
-#include "editor/editor_file_system.h"
-#include "editor/editor_dir_dialog.h"
-#include "editor/editor_import_export.h"
-#include "editor/io_plugins/editor_texture_import_plugin.h"
+#include "scene/gui/tree.h"
#include "scene/resources/animation.h"
+#include "scene/resources/mesh.h"
class EditorNode;
diff --git a/editor/io_plugins/editor_scene_importer_fbxconv.cpp b/editor/io_plugins/editor_scene_importer_fbxconv.cpp
index d75a26a948..a2fe4a649b 100644
--- a/editor/io_plugins/editor_scene_importer_fbxconv.cpp
+++ b/editor/io_plugins/editor_scene_importer_fbxconv.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "editor_scene_importer_fbxconv.h"
+#include "editor/editor_settings.h"
#include "os/file_access.h"
#include "os/os.h"
-#include "editor/editor_settings.h"
#include "scene/3d/mesh_instance.h"
#include "scene/animation/animation_player.h"
diff --git a/editor/io_plugins/editor_texture_import_plugin.cpp b/editor/io_plugins/editor_texture_import_plugin.cpp
index 8bafe80673..32742483bc 100644
--- a/editor/io_plugins/editor_texture_import_plugin.cpp
+++ b/editor/io_plugins/editor_texture_import_plugin.cpp
@@ -28,16 +28,16 @@
/*************************************************************************/
#include "editor_texture_import_plugin.h"
#if 0
-#include "io/image_loader.h"
#include "editor/editor_node.h"
-#include "io/resource_saver.h"
-#include "editor_atlas.h"
#include "editor/editor_settings.h"
-#include "io/md5.h"
-#include "io/marshalls.h"
+#include "editor_atlas.h"
#include "global_config.h"
-#include "scene/gui/check_button.h"
+#include "io/image_loader.h"
+#include "io/marshalls.h"
+#include "io/md5.h"
+#include "io/resource_saver.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/check_button.h"
#include "scene/gui/margin_container.h"
#include "scene/io/resource_format_image.h"
diff --git a/editor/io_plugins/editor_texture_import_plugin.h b/editor/io_plugins/editor_texture_import_plugin.h
index f63bc57ecd..5d0d21f116 100644
--- a/editor/io_plugins/editor_texture_import_plugin.h
+++ b/editor/io_plugins/editor_texture_import_plugin.h
@@ -29,24 +29,19 @@
#ifndef EDITOR_TEXTURE_IMPORT_PLUGIN_H
#define EDITOR_TEXTURE_IMPORT_PLUGIN_H
-
-
-
-
-
#if 0
+#include "editor/editor_dir_dialog.h"
+#include "editor/editor_file_system.h"
#include "editor/editor_import_export.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/label.h"
-#include "scene/gui/option_button.h"
#include "scene/gui/line_edit.h"
-#include "scene/gui/file_dialog.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/progress_bar.h"
#include "scene/gui/slider.h"
#include "scene/gui/spin_box.h"
-#include "editor/editor_file_system.h"
-#include "editor/editor_dir_dialog.h"
+#include "scene/gui/tree.h"
diff --git a/editor/io_plugins/editor_translation_import_plugin.cpp b/editor/io_plugins/editor_translation_import_plugin.cpp
index 0fd298d6d3..9aa9f043b3 100644
--- a/editor/io_plugins/editor_translation_import_plugin.cpp
+++ b/editor/io_plugins/editor_translation_import_plugin.cpp
@@ -29,16 +29,16 @@
#include "editor_translation_import_plugin.h"
#if 0
-#include "scene/gui/file_dialog.h"
#include "editor/editor_dir_dialog.h"
#include "editor/editor_node.h"
#include "editor/property_editor.h"
+#include "scene/gui/file_dialog.h"
//#include "scene/resources/sample.h"
+#include "compressed_translation.h"
+#include "editor/project_settings.h"
#include "io/resource_saver.h"
#include "os/file_access.h"
#include "translation.h"
-#include "compressed_translation.h"
-#include "editor/project_settings.h"
class EditorTranslationImportDialog : public ConfirmationDialog {
diff --git a/editor/multi_node_edit.cpp b/editor/multi_node_edit.cpp
index 0428d7ef30..e0e6838402 100644
--- a/editor/multi_node_edit.cpp
+++ b/editor/multi_node_edit.cpp
@@ -28,15 +28,15 @@
/*************************************************************************/
#include "multi_node_edit.h"
-#include "editor_node.h"
#include "core/helper/math_fieldwise.h"
+#include "editor_node.h"
-bool MultiNodeEdit::_set(const StringName& p_name, const Variant& p_value){
+bool MultiNodeEdit::_set(const StringName &p_name, const Variant &p_value) {
return _set_impl(p_name, p_value, "");
}
-bool MultiNodeEdit::_set_impl(const StringName& p_name, const Variant& p_value, const String& p_field) {
+bool MultiNodeEdit::_set_impl(const StringName &p_name, const Variant &p_value, const String &p_field) {
Node *es = EditorNode::get_singleton()->get_edited_scene();
if (!es)
@@ -44,112 +44,109 @@ bool MultiNodeEdit::_set_impl(const StringName& p_name, const Variant& p_value,
String name = p_name;
- if (name=="scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name
- name="script";
+ if (name == "scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name
+ name = "script";
}
- UndoRedo *ur=EditorNode::get_singleton()->get_undo_redo();
+ UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- ur->create_action(TTR("MultiNode Set")+" "+String(name));
- for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) {
+ ur->create_action(TTR("MultiNode Set") + " " + String(name));
+ for (const List<NodePath>::Element *E = nodes.front(); E; E = E->next()) {
if (!es->has_node(E->get()))
continue;
- Node*n=es->get_node(E->get());
+ Node *n = es->get_node(E->get());
if (!n)
continue;
if (p_value.get_type() == Variant::NODE_PATH) {
Node *tonode = n->get_node(p_value);
NodePath p_path = n->get_path_to(tonode);
- ur->add_do_property(n,name,p_path);
+ ur->add_do_property(n, name, p_path);
} else {
Variant new_value;
- if (p_field=="") {
+ if (p_field == "") {
// whole value
- new_value=p_value;
+ new_value = p_value;
} else {
// only one field
- new_value=fieldwise_assign(n->get(name),p_value,p_field);
+ new_value = fieldwise_assign(n->get(name), p_value, p_field);
}
- ur->add_do_property(n,name,new_value);
+ ur->add_do_property(n, name, new_value);
}
- ur->add_undo_property(n,name,n->get(name));
-
-
+ ur->add_undo_property(n, name, n->get(name));
}
- ur->add_do_method(EditorNode::get_singleton()->get_property_editor(),"refresh");
- ur->add_undo_method(EditorNode::get_singleton()->get_property_editor(),"refresh");
+ ur->add_do_method(EditorNode::get_singleton()->get_property_editor(), "refresh");
+ ur->add_undo_method(EditorNode::get_singleton()->get_property_editor(), "refresh");
ur->commit_action();
return true;
}
-bool MultiNodeEdit::_get(const StringName& p_name,Variant &r_ret) const {
+bool MultiNodeEdit::_get(const StringName &p_name, Variant &r_ret) const {
Node *es = EditorNode::get_singleton()->get_edited_scene();
if (!es)
return false;
- String name=p_name;
- if (name=="scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name
- name="script";
+ String name = p_name;
+ if (name == "scripts") { // script set is intercepted at object level (check Variant Object::get() ) ,so use a different name
+ name = "script";
}
- for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) {
+ for (const List<NodePath>::Element *E = nodes.front(); E; E = E->next()) {
if (!es->has_node(E->get()))
continue;
- const Node*n=es->get_node(E->get());
+ const Node *n = es->get_node(E->get());
if (!n)
continue;
bool found;
- r_ret=n->get(name,&found);
+ r_ret = n->get(name, &found);
if (found)
return true;
-
}
return false;
}
-void MultiNodeEdit::_get_property_list( List<PropertyInfo> *p_list) const{
+void MultiNodeEdit::_get_property_list(List<PropertyInfo> *p_list) const {
- HashMap<String,PLData> usage;
+ HashMap<String, PLData> usage;
Node *es = EditorNode::get_singleton()->get_edited_scene();
if (!es)
return;
- int nc=0;
+ int nc = 0;
- List<PLData*> datas;
+ List<PLData *> datas;
- for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) {
+ for (const List<NodePath>::Element *E = nodes.front(); E; E = E->next()) {
if (!es->has_node(E->get()))
continue;
- Node*n=es->get_node(E->get());
+ Node *n = es->get_node(E->get());
if (!n)
continue;
List<PropertyInfo> plist;
- n->get_property_list(&plist,true);
+ n->get_property_list(&plist, true);
- for(List<PropertyInfo>::Element *F=plist.front();F;F=F->next()) {
+ for (List<PropertyInfo>::Element *F = plist.front(); F; F = F->next()) {
- if (F->get().name=="script")
+ if (F->get().name == "script")
continue; //added later manually, since this is intercepted before being set (check Variant Object::get() )
if (!usage.has(F->get().name)) {
PLData pld;
- pld.uses=0;
- pld.info=F->get();
- usage[F->get().name]=pld;
+ pld.uses = 0;
+ pld.info = F->get();
+ usage[F->get().name] = pld;
datas.push_back(usage.getptr(F->get().name));
}
@@ -159,16 +156,14 @@ void MultiNodeEdit::_get_property_list( List<PropertyInfo> *p_list) const{
nc++;
}
- for (List<PLData*>::Element *E=datas.front();E;E=E->next()) {
+ for (List<PLData *>::Element *E = datas.front(); E; E = E->next()) {
- if (nc==E->get()->uses) {
+ if (nc == E->get()->uses) {
p_list->push_back(E->get()->info);
}
}
- p_list->push_back(PropertyInfo(Variant::OBJECT,"scripts",PROPERTY_HINT_RESOURCE_TYPE,"Script"));
-
-
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "scripts", PROPERTY_HINT_RESOURCE_TYPE, "Script"));
}
void MultiNodeEdit::clear_nodes() {
@@ -176,16 +171,15 @@ void MultiNodeEdit::clear_nodes() {
nodes.clear();
}
-void MultiNodeEdit::add_node(const NodePath& p_node){
+void MultiNodeEdit::add_node(const NodePath &p_node) {
nodes.push_back(p_node);
}
-void MultiNodeEdit::set_property_field(const StringName& p_property, const Variant& p_value, const String& p_field) {
+void MultiNodeEdit::set_property_field(const StringName &p_property, const Variant &p_value, const String &p_field) {
_set_impl(p_property, p_value, p_field);
}
-MultiNodeEdit::MultiNodeEdit()
-{
+MultiNodeEdit::MultiNodeEdit() {
}
diff --git a/editor/multi_node_edit.h b/editor/multi_node_edit.h
index 26e557c1cb..2307968794 100644
--- a/editor/multi_node_edit.h
+++ b/editor/multi_node_edit.h
@@ -33,7 +33,7 @@
class MultiNodeEdit : public Reference {
- GDCLASS(MultiNodeEdit,Reference);
+ GDCLASS(MultiNodeEdit, Reference);
List<NodePath> nodes;
struct PLData {
@@ -41,23 +41,18 @@ class MultiNodeEdit : public Reference {
PropertyInfo info;
};
- bool _set_impl(const StringName& p_name, const Variant& p_value, const String& p_field);
-
+ bool _set_impl(const StringName &p_name, const Variant &p_value, const String &p_field);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
-
-
void clear_nodes();
- void add_node(const NodePath& p_node);
+ void add_node(const NodePath &p_node);
- void set_property_field(const StringName& p_property, const Variant& p_value, const String& p_field);
+ void set_property_field(const StringName &p_property, const Variant &p_value, const String &p_field);
MultiNodeEdit();
};
diff --git a/editor/node_dock.cpp b/editor/node_dock.cpp
index fed3d2efb4..d76a427e1f 100644
--- a/editor/node_dock.cpp
+++ b/editor/node_dock.cpp
@@ -38,7 +38,7 @@ void NodeDock::show_groups() {
connections->hide();
}
-void NodeDock::show_connections(){
+void NodeDock::show_connections() {
groups_button->set_pressed(false);
connections_button->set_pressed(true);
@@ -46,24 +46,23 @@ void NodeDock::show_connections(){
connections->show();
}
-
void NodeDock::_bind_methods() {
- ClassDB::bind_method(D_METHOD("show_groups"),&NodeDock::show_groups);
- ClassDB::bind_method(D_METHOD("show_connections"),&NodeDock::show_connections);
+ ClassDB::bind_method(D_METHOD("show_groups"), &NodeDock::show_groups);
+ ClassDB::bind_method(D_METHOD("show_connections"), &NodeDock::show_connections);
}
void NodeDock::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- connections_button->set_icon(get_icon("Connect","EditorIcons"));
- groups_button->set_icon(get_icon("Groups","EditorIcons"));
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ connections_button->set_icon(get_icon("Connect", "EditorIcons"));
+ groups_button->set_icon(get_icon("Groups", "EditorIcons"));
}
}
-NodeDock *NodeDock::singleton=NULL;
+NodeDock *NodeDock::singleton = NULL;
-void NodeDock::set_node(Node* p_node) {
+void NodeDock::set_node(Node *p_node) {
connections->set_node(p_node);
groups->set_current(p_node);
@@ -84,50 +83,47 @@ void NodeDock::set_node(Node* p_node) {
}
}
-NodeDock::NodeDock()
-{
- singleton=this;
+NodeDock::NodeDock() {
+ singleton = this;
set_name(TTR("Node"));
- mode_hb = memnew( HBoxContainer );
+ mode_hb = memnew(HBoxContainer);
add_child(mode_hb);
mode_hb->hide();
-
- connections_button = memnew( ToolButton );
+ connections_button = memnew(ToolButton);
connections_button->set_text(TTR("Signals"));
connections_button->set_toggle_mode(true);
connections_button->set_pressed(true);
connections_button->set_h_size_flags(SIZE_EXPAND_FILL);
mode_hb->add_child(connections_button);
- connections_button->connect("pressed",this,"show_connections");
+ connections_button->connect("pressed", this, "show_connections");
- groups_button = memnew( ToolButton );
+ groups_button = memnew(ToolButton);
groups_button->set_text(TTR("Groups"));
groups_button->set_toggle_mode(true);
groups_button->set_pressed(false);
groups_button->set_h_size_flags(SIZE_EXPAND_FILL);
mode_hb->add_child(groups_button);
- groups_button->connect("pressed",this,"show_groups");
+ groups_button->connect("pressed", this, "show_groups");
- connections = memnew( ConnectionsDock(EditorNode::get_singleton()) );
+ connections = memnew(ConnectionsDock(EditorNode::get_singleton()));
connections->set_undoredo(EditorNode::get_singleton()->get_undo_redo());
add_child(connections);
connections->set_v_size_flags(SIZE_EXPAND_FILL);
connections->hide();
- groups = memnew( GroupsEditor );
+ groups = memnew(GroupsEditor);
groups->set_undo_redo(EditorNode::get_singleton()->get_undo_redo());
add_child(groups);
groups->set_v_size_flags(SIZE_EXPAND_FILL);
groups->hide();
- select_a_node = memnew( Label );
+ select_a_node = memnew(Label);
select_a_node->set_text(TTR("Select a Node to edit Signals and Groups."));
select_a_node->set_v_size_flags(SIZE_EXPAND_FILL);
select_a_node->set_valign(Label::VALIGN_CENTER);
select_a_node->set_align(Label::ALIGN_CENTER);
select_a_node->set_autowrap(true);
add_child(select_a_node);
-
}
diff --git a/editor/node_dock.h b/editor/node_dock.h
index df41ecf5bd..b7d91899d8 100644
--- a/editor/node_dock.h
+++ b/editor/node_dock.h
@@ -34,7 +34,7 @@
class NodeDock : public VBoxContainer {
- GDCLASS(NodeDock,VBoxContainer);
+ GDCLASS(NodeDock, VBoxContainer);
ToolButton *connections_button;
ToolButton *groups_button;
@@ -44,18 +44,16 @@ class NodeDock : public VBoxContainer {
HBoxContainer *mode_hb;
- Label* select_a_node;
+ Label *select_a_node;
protected:
-
static void _bind_methods();
void _notification(int p_what);
public:
-
static NodeDock *singleton;
- void set_node(Node* p_node);
+ void set_node(Node *p_node);
void show_groups();
void show_connections();
diff --git a/editor/output_strings.cpp b/editor/output_strings.cpp
index cb43bb9230..0894a92731 100644
--- a/editor/output_strings.cpp
+++ b/editor/output_strings.cpp
@@ -28,80 +28,76 @@
/*************************************************************************/
#include "output_strings.h"
-
-
void OutputStrings::update_scrollbars() {
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
- v_scroll->set_anchor( MARGIN_LEFT, ANCHOR_END );
- v_scroll->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- v_scroll->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
+ v_scroll->set_anchor(MARGIN_LEFT, ANCHOR_END);
+ v_scroll->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ v_scroll->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
- v_scroll->set_begin( Point2(vmin.width, 0) );
- v_scroll->set_end( Point2(0,0 ) );
+ v_scroll->set_begin(Point2(vmin.width, 0));
+ v_scroll->set_end(Point2(0, 0));
- h_scroll->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- h_scroll->set_anchor( MARGIN_TOP, ANCHOR_END );
- h_scroll->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
+ h_scroll->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ h_scroll->set_anchor(MARGIN_TOP, ANCHOR_END);
+ h_scroll->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
- h_scroll->set_begin( Point2( 0, hmin.y) );
- h_scroll->set_end( Point2(vmin.x, 0) );
+ h_scroll->set_begin(Point2(0, hmin.y));
+ h_scroll->set_end(Point2(vmin.x, 0));
- margin.y=hmin.y;
- margin.x=vmin.x;
+ margin.y = hmin.y;
+ margin.x = vmin.x;
- Ref<StyleBox> tree_st = get_stylebox("bg","Tree");
- int page = ((size_height-(int)margin.y-tree_st->get_margin(MARGIN_TOP)) / font_height);
+ Ref<StyleBox> tree_st = get_stylebox("bg", "Tree");
+ int page = ((size_height - (int)margin.y - tree_st->get_margin(MARGIN_TOP)) / font_height);
v_scroll->set_page(page);
-
}
void OutputStrings::_notification(int p_what) {
- switch(p_what) {
-
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (following) {
- updating=true;
- v_scroll->set_value( v_scroll->get_max() - v_scroll->get_page() );
- updating=false;
+ updating = true;
+ v_scroll->set_value(v_scroll->get_max() - v_scroll->get_page());
+ updating = false;
}
RID ci = get_canvas_item();
Size2 size = get_size();
- Ref<Font> font = get_font("font","Tree");
- Ref<StyleBox> tree_st = get_stylebox("bg","Tree");
- tree_st->draw(ci,Rect2(Point2(),size));
- Color color = get_color("font_color","Tree");
- Ref<Texture> icon_error = get_icon("Error","EditorIcons");
- Ref<Texture> icon_warning = get_icon("Warning","EditorIcons");
+ Ref<Font> font = get_font("font", "Tree");
+ Ref<StyleBox> tree_st = get_stylebox("bg", "Tree");
+ tree_st->draw(ci, Rect2(Point2(), size));
+ Color color = get_color("font_color", "Tree");
+ Ref<Texture> icon_error = get_icon("Error", "EditorIcons");
+ Ref<Texture> icon_warning = get_icon("Warning", "EditorIcons");
//int lines = (size_height-(int)margin.y) / font_height;
- Point2 ofs=tree_st->get_offset();
+ Point2 ofs = tree_st->get_offset();
LineMap::Element *E = line_map.find(v_scroll->get_value());
float h_ofs = (int)h_scroll->get_value();
- Point2 icon_ofs=Point2(0,(font_height-(int)icon_error->get_height())/2);
+ Point2 icon_ofs = Point2(0, (font_height - (int)icon_error->get_height()) / 2);
- while( E && ofs.y < (size_height-(int)margin.y) ) {
+ while (E && ofs.y < (size_height - (int)margin.y)) {
String str = E->get().text;
- Point2 line_ofs=ofs;
+ Point2 line_ofs = ofs;
- switch(E->get().type) {
+ switch (E->get().type) {
case LINE_WARNING: {
- icon_warning->draw(ci,line_ofs+icon_ofs);
+ icon_warning->draw(ci, line_ofs + icon_ofs);
} break;
case LINE_ERROR: {
- icon_error->draw(ci,line_ofs+icon_ofs);
+ icon_error->draw(ci, line_ofs + icon_ofs);
} break;
case LINE_LINK: {
@@ -109,21 +105,21 @@ void OutputStrings::_notification(int p_what) {
default: {}
}
- line_ofs.y+=font->get_ascent();
- line_ofs.x+=icon_error->get_width()+4;
+ line_ofs.y += font->get_ascent();
+ line_ofs.x += icon_error->get_width() + 4;
- for(int i=0;i<str.length();i++) {
- if (line_ofs.x-h_ofs < 0 ) {
- line_ofs.x+=font->get_char_size(str[i],str[i+1]).width;
- } else if (line_ofs.x-h_ofs > size.width - margin.width) {
+ for (int i = 0; i < str.length(); i++) {
+ if (line_ofs.x - h_ofs < 0) {
+ line_ofs.x += font->get_char_size(str[i], str[i + 1]).width;
+ } else if (line_ofs.x - h_ofs > size.width - margin.width) {
break;
} else {
- line_ofs.x+=font->draw_char(ci,Point2(line_ofs.x-h_ofs,line_ofs.y),str[i],str[i+1],color);
+ line_ofs.x += font->draw_char(ci, Point2(line_ofs.x - h_ofs, line_ofs.y), str[i], str[i + 1], color);
}
}
- ofs.y+=font_height;
- E=E->next();
+ ofs.y += font_height;
+ E = E->next();
}
} break;
@@ -131,13 +127,11 @@ void OutputStrings::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE:
case NOTIFICATION_RESIZED: {
-
- font_height = get_font("font","Tree")->get_height();
+ font_height = get_font("font", "Tree")->get_height();
size_height = get_size().height;
update_scrollbars();
} break;
}
-
}
void OutputStrings::_hscroll_changed(float p_value) {
@@ -152,33 +146,31 @@ void OutputStrings::_vscroll_changed(float p_value) {
if (updating)
return;
//user changed scroll
- following=(p_value+v_scroll->get_page())>=v_scroll->get_max();
+ following = (p_value + v_scroll->get_page()) >= v_scroll->get_max();
update();
}
-void OutputStrings::add_line(const String& p_text, const Variant& p_meta, const LineType p_type) {
+void OutputStrings::add_line(const String &p_text, const Variant &p_meta, const LineType p_type) {
+ Vector<String> strings = p_text.split("\n");
- Vector<String> strings=p_text.split("\n");
+ for (int i = 0; i < strings.size(); i++) {
- for(int i=0;i<strings.size();i++) {
-
- if (strings[i].length()==0)
+ if (strings[i].length() == 0)
continue;
int last = line_map.empty() ? 0 : (line_map.back()->key() + 1);
Line l;
- l.text=strings[i];
- l.meta=p_meta;
- l.type=p_type;
- line_map.insert(last,l);
+ l.text = strings[i];
+ l.meta = p_meta;
+ l.type = p_type;
+ line_map.insert(last, l);
- updating=true;
- v_scroll->set_max(last+1);
+ updating = true;
+ v_scroll->set_max(last + 1);
v_scroll->set_min(line_map.front()->key());
- updating=false;
-
+ updating = false;
}
while (line_map.size() > line_max_count) {
@@ -186,30 +178,27 @@ void OutputStrings::add_line(const String& p_text, const Variant& p_meta, const
line_map.erase(line_map.front());
}
-
update();
-
}
-
void OutputStrings::_bind_methods() {
- ClassDB::bind_method("_vscroll_changed",&OutputStrings::_vscroll_changed);
- ClassDB::bind_method("_hscroll_changed",&OutputStrings::_hscroll_changed);
+ ClassDB::bind_method("_vscroll_changed", &OutputStrings::_vscroll_changed);
+ ClassDB::bind_method("_hscroll_changed", &OutputStrings::_hscroll_changed);
}
OutputStrings::OutputStrings() {
- following=true;
- updating=false;
- line_max_count=4096;
- h_scroll = memnew( HScrollBar );
- v_scroll = memnew( VScrollBar );
+ following = true;
+ updating = false;
+ line_max_count = 4096;
+ h_scroll = memnew(HScrollBar);
+ v_scroll = memnew(VScrollBar);
add_child(h_scroll);
add_child(v_scroll);
- size_height=1;
- font_height=1;
+ size_height = 1;
+ font_height = 1;
update_scrollbars();
- h_scroll->connect("value_changed", this,"_hscroll_changed");
- v_scroll->connect("value_changed", this,"_vscroll_changed");
+ h_scroll->connect("value_changed", this, "_hscroll_changed");
+ v_scroll->connect("value_changed", this, "_vscroll_changed");
}
diff --git a/editor/output_strings.h b/editor/output_strings.h
index cc721ef652..392b1d4dc8 100644
--- a/editor/output_strings.h
+++ b/editor/output_strings.h
@@ -29,16 +29,15 @@
#ifndef OUTPUT_STRINGS_H
#define OUTPUT_STRINGS_H
-
+#include "map.h"
#include "scene/gui/control.h"
#include "scene/gui/scroll_bar.h"
-#include "map.h"
class OutputStrings : public Control {
- GDCLASS( OutputStrings, Control );
-public:
+ GDCLASS(OutputStrings, Control);
+public:
enum LineType {
LINE_NORMAL,
@@ -46,23 +45,21 @@ public:
LINE_ERROR,
LINE_LINK
};
-private:
+private:
struct Line {
-
LineType type;
Variant meta;
String text;
};
-
int font_height;
int size_height;
Size2 margin;
- typedef Map<int,Line> LineMap;
- Map<int,Line> line_map;
+ typedef Map<int, Line> LineMap;
+ Map<int, Line> line_map;
VScrollBar *v_scroll;
HScrollBar *h_scroll;
@@ -74,14 +71,13 @@ private:
void _vscroll_changed(float p_value);
void _hscroll_changed(float p_value);
void update_scrollbars();
-protected:
+protected:
static void _bind_methods();
void _notification(int p_what);
public:
-
- void add_line(const String& p_text, const Variant& p_meta=Variant(), const LineType p_type=LINE_NORMAL);
+ void add_line(const String &p_text, const Variant &p_meta = Variant(), const LineType p_type = LINE_NORMAL);
OutputStrings();
};
diff --git a/editor/pane_drag.cpp b/editor/pane_drag.cpp
index 122abd37b9..253b217049 100644
--- a/editor/pane_drag.cpp
+++ b/editor/pane_drag.cpp
@@ -28,48 +28,50 @@
/*************************************************************************/
#include "pane_drag.h"
+void PaneDrag::_gui_input(const InputEvent &p_input) {
-void PaneDrag::_gui_input(const InputEvent& p_input) {
+ if (p_input.type == InputEvent::MOUSE_MOTION && p_input.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
- if (p_input.type==InputEvent::MOUSE_MOTION && p_input.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
-
- emit_signal("dragged",Point2(p_input.mouse_motion.relative_x,p_input.mouse_motion.relative_y));
+ emit_signal("dragged", Point2(p_input.mouse_motion.relative_x, p_input.mouse_motion.relative_y));
}
}
void PaneDrag::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
- Ref<Texture> icon = mouse_over?get_icon("PaneDragHover","EditorIcons"):get_icon("PaneDrag","EditorIcons");
+ Ref<Texture> icon = mouse_over ? get_icon("PaneDragHover", "EditorIcons") : get_icon("PaneDrag", "EditorIcons");
if (!icon.is_null())
- icon->draw(get_canvas_item(),Point2(0,0));
+ icon->draw(get_canvas_item(), Point2(0, 0));
} break;
- case NOTIFICATION_MOUSE_ENTER: mouse_over=true; update(); break;
- case NOTIFICATION_MOUSE_EXIT: mouse_over=false; update(); break;
+ case NOTIFICATION_MOUSE_ENTER:
+ mouse_over = true;
+ update();
+ break;
+ case NOTIFICATION_MOUSE_EXIT:
+ mouse_over = false;
+ update();
+ break;
}
-
}
Size2 PaneDrag::get_minimum_size() const {
- Ref<Texture> icon=get_icon("PaneDrag","EditorIcons");
+ Ref<Texture> icon = get_icon("PaneDrag", "EditorIcons");
if (!icon.is_null())
return icon->get_size();
return Size2();
-
}
void PaneDrag::_bind_methods() {
- ClassDB::bind_method("_gui_input",&PaneDrag::_gui_input);
- ADD_SIGNAL(MethodInfo("dragged",PropertyInfo(Variant::VECTOR2,"amount")));
+ ClassDB::bind_method("_gui_input", &PaneDrag::_gui_input);
+ ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::VECTOR2, "amount")));
}
PaneDrag::PaneDrag() {
- mouse_over=false;
-
+ mouse_over = false;
}
diff --git a/editor/pane_drag.h b/editor/pane_drag.h
index 8796fc2594..30ca6c20a2 100644
--- a/editor/pane_drag.h
+++ b/editor/pane_drag.h
@@ -33,17 +33,16 @@
class PaneDrag : public Control {
- GDCLASS( PaneDrag, Control );
+ GDCLASS(PaneDrag, Control);
bool mouse_over;
-
protected:
-
- void _gui_input(const InputEvent& p_input);
+ void _gui_input(const InputEvent &p_input);
void _notification(int p_what);
virtual Size2 get_minimum_size() const;
static void _bind_methods();
+
public:
PaneDrag();
};
diff --git a/editor/plugins/animation_player_editor_plugin.cpp b/editor/plugins/animation_player_editor_plugin.cpp
index 2e6792bbaa..90d2847103 100644
--- a/editor/plugins/animation_player_editor_plugin.cpp
+++ b/editor/plugins/animation_player_editor_plugin.cpp
@@ -28,17 +28,17 @@
/*************************************************************************/
#include "animation_player_editor_plugin.h"
+#include "editor/animation_editor.h"
+#include "editor/editor_settings.h"
#include "global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "os/keyboard.h"
-#include "editor/editor_settings.h"
-#include "editor/animation_editor.h"
void AnimationPlayerEditor::_node_removed(Node *p_node) {
if (player && player == p_node) {
- player=NULL;
+ player = NULL;
set_process(false);
@@ -47,18 +47,15 @@ void AnimationPlayerEditor::_node_removed(Node *p_node) {
key_editor->show_select_node_warning(true);
_update_player();
//editor->animation_editor_make_visible(false);
-
}
}
void AnimationPlayerEditor::_gui_input(InputEvent p_event) {
-
-
}
void AnimationPlayerEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
if (!player)
return;
@@ -68,7 +65,7 @@ void AnimationPlayerEditor::_notification(int p_what) {
if (player->is_playing()) {
{
- String animname=player->get_current_animation();
+ String animname = player->get_current_animation();
if (player->has_animation(animname)) {
Ref<Animation> anim = player->get_animation(animname);
@@ -88,41 +85,41 @@ void AnimationPlayerEditor::_notification(int p_what) {
frame->set_value(player->get_current_animation_pos());
}
- last_active=player->is_playing();
+ last_active = player->is_playing();
//seek->set_val(player->get_pos());
updating = false;
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
//editor->connect("hide_animation_player_editors",this,"_hide_anim_editors");
- add_anim->set_icon( get_icon("New","EditorIcons") );
- rename_anim->set_icon( get_icon("Rename","EditorIcons") );
- duplicate_anim->set_icon( get_icon("Duplicate","EditorIcons") );
- autoplay->set_icon( get_icon("AutoPlay","EditorIcons") );
- load_anim->set_icon( get_icon("Folder","EditorIcons") );
+ add_anim->set_icon(get_icon("New", "EditorIcons"));
+ rename_anim->set_icon(get_icon("Rename", "EditorIcons"));
+ duplicate_anim->set_icon(get_icon("Duplicate", "EditorIcons"));
+ autoplay->set_icon(get_icon("AutoPlay", "EditorIcons"));
+ load_anim->set_icon(get_icon("Folder", "EditorIcons"));
save_anim->set_icon(get_icon("Save", "EditorIcons"));
save_anim->get_popup()->connect("id_pressed", this, "_animation_save_menu");
- remove_anim->set_icon( get_icon("Remove","EditorIcons") );
+ remove_anim->set_icon(get_icon("Remove", "EditorIcons"));
- blend_anim->set_icon( get_icon("Blend","EditorIcons") );
- play->set_icon( get_icon("PlayStart","EditorIcons") );
- play_from->set_icon( get_icon("Play","EditorIcons") );
- play_bw->set_icon( get_icon("PlayStartBackwards","EditorIcons") );
- play_bw_from->set_icon( get_icon("PlayBackwards","EditorIcons") );
+ blend_anim->set_icon(get_icon("Blend", "EditorIcons"));
+ play->set_icon(get_icon("PlayStart", "EditorIcons"));
+ play_from->set_icon(get_icon("Play", "EditorIcons"));
+ play_bw->set_icon(get_icon("PlayStartBackwards", "EditorIcons"));
+ play_bw_from->set_icon(get_icon("PlayBackwards", "EditorIcons"));
- autoplay_icon=get_icon("AutoPlay","EditorIcons");
- stop->set_icon( get_icon("Stop","EditorIcons") );
- resource_edit_anim->set_icon( get_icon("EditResource","EditorIcons") );
- pin->set_icon(get_icon("Pin","EditorIcons") );
- tool_anim->set_icon(get_icon("Tools","EditorIcons"));
- tool_anim->get_popup()->connect("id_pressed",this,"_animation_tool_menu");
+ autoplay_icon = get_icon("AutoPlay", "EditorIcons");
+ stop->set_icon(get_icon("Stop", "EditorIcons"));
+ resource_edit_anim->set_icon(get_icon("EditResource", "EditorIcons"));
+ pin->set_icon(get_icon("Pin", "EditorIcons"));
+ tool_anim->set_icon(get_icon("Tools", "EditorIcons"));
+ tool_anim->get_popup()->connect("id_pressed", this, "_animation_tool_menu");
blend_editor.next->connect("item_selected", this, "_blend_editor_next_changed");
- nodename->set_icon(get_icon("AnimationPlayer","EditorIcons"));
+ nodename->set_icon(get_icon("AnimationPlayer", "EditorIcons"));
-/*
+ /*
anim_editor_load->set_normal_texture( get_icon("AnimGet","EditorIcons"));
anim_editor_store->set_normal_texture( get_icon("AnimSet","EditorIcons"));
anim_editor_load->set_pressed_texture( get_icon("AnimGet","EditorIcons"));
@@ -131,7 +128,7 @@ void AnimationPlayerEditor::_notification(int p_what) {
anim_editor_store->set_hover_texture( get_icon("AnimSetHl","EditorIcons"));
*/
- get_tree()->connect("node_removed",this,"_node_removed");
+ get_tree()->connect("node_removed", this, "_node_removed");
}
}
@@ -139,46 +136,44 @@ void AnimationPlayerEditor::_autoplay_pressed() {
if (updating)
return;
- if (animation->get_item_count()==0) {
+ if (animation->get_item_count() == 0) {
return;
}
- String current = animation->get_item_text( animation->get_selected() );
- if (player->get_autoplay()==current) {
+ String current = animation->get_item_text(animation->get_selected());
+ if (player->get_autoplay() == current) {
//unset
undo_redo->create_action(TTR("Toggle Autoplay"));
- undo_redo->add_do_method(player,"set_autoplay","");
- undo_redo->add_undo_method(player,"set_autoplay",player->get_autoplay());
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "set_autoplay", "");
+ undo_redo->add_undo_method(player, "set_autoplay", player->get_autoplay());
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
-
} else {
//set
undo_redo->create_action(TTR("Toggle Autoplay"));
- undo_redo->add_do_method(player,"set_autoplay",current);
- undo_redo->add_undo_method(player,"set_autoplay",player->get_autoplay());
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "set_autoplay", current);
+ undo_redo->add_undo_method(player, "set_autoplay", player->get_autoplay());
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
}
-
}
void AnimationPlayerEditor::_play_pressed() {
String current;
- if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
+ if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) {
- current = animation->get_item_text( animation->get_selected() );
+ current = animation->get_item_text(animation->get_selected());
}
- if (current!="") {
+ if (current != "") {
- if (current==player->get_current_animation())
+ if (current == player->get_current_animation())
player->stop(); //so it wont blend with itself
- player->play(current );
+ player->play(current);
}
//unstop
@@ -190,21 +185,21 @@ void AnimationPlayerEditor::_play_pressed() {
void AnimationPlayerEditor::_play_from_pressed() {
String current;
- if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
+ if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) {
- current = animation->get_item_text( animation->get_selected() );
+ current = animation->get_item_text(animation->get_selected());
}
- if (current!="") {
+ if (current != "") {
float time = player->get_current_animation_pos();
- if (current==player->get_current_animation() && player->is_playing()) {
+ if (current == player->get_current_animation() && player->is_playing()) {
player->stop(); //so it wont blend with itself
}
- player->play( current );
+ player->play(current);
player->seek(time);
}
@@ -214,20 +209,19 @@ void AnimationPlayerEditor::_play_from_pressed() {
//pause->set_pressed(false);
}
-
void AnimationPlayerEditor::_play_bw_pressed() {
String current;
- if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
+ if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) {
- current = animation->get_item_text( animation->get_selected() );
+ current = animation->get_item_text(animation->get_selected());
}
- if (current!="") {
+ if (current != "") {
- if (current==player->get_current_animation())
+ if (current == player->get_current_animation())
player->stop(); //so it wont blend with itself
- player->play(current,-1,-1,true);
+ player->play(current, -1, -1, true);
}
//unstop
@@ -239,18 +233,18 @@ void AnimationPlayerEditor::_play_bw_pressed() {
void AnimationPlayerEditor::_play_bw_from_pressed() {
String current;
- if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
+ if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) {
- current = animation->get_item_text( animation->get_selected() );
+ current = animation->get_item_text(animation->get_selected());
}
- if (current!="") {
+ if (current != "") {
float time = player->get_current_animation_pos();
- if (current==player->get_current_animation())
+ if (current == player->get_current_animation())
player->stop(); //so it wont blend with itself
- player->play(current,-1,-1,true);
+ player->play(current, -1, -1, true);
player->seek(time);
}
@@ -279,17 +273,16 @@ void AnimationPlayerEditor::_animation_selected(int p_which) {
// when selecting an animation, the idea is that the only interesting behavior
// ui-wise is that it should play/blend the next one if currently playing
String current;
- if (animation->get_selected()>=0 && animation->get_selected()<animation->get_item_count()) {
+ if (animation->get_selected() >= 0 && animation->get_selected() < animation->get_item_count()) {
- current = animation->get_item_text( animation->get_selected() );
+ current = animation->get_item_text(animation->get_selected());
}
- if (current!="") {
-
+ if (current != "") {
- player->set_current_animation( current );
+ player->set_current_animation(current);
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
{
key_editor->set_animation(anim);
@@ -304,76 +297,69 @@ void AnimationPlayerEditor::_animation_selected(int p_which) {
else
frame->set_step(0.00001);
-
-
} else {
key_editor->set_animation(Ref<Animation>());
key_editor->set_root(NULL);
-
}
-
- autoplay->set_pressed(current==player->get_autoplay());
+ autoplay->set_pressed(current == player->get_autoplay());
}
void AnimationPlayerEditor::_animation_new() {
- renaming=false;
+ renaming = false;
name_title->set_text(TTR("New Animation Name:"));
- int count=1;
- String base=TTR("New Anim");
- while(true) {
- String attempt = base;
- if (count>1)
- attempt+=" ("+itos(count)+")";
+ int count = 1;
+ String base = TTR("New Anim");
+ while (true) {
+ String attempt = base;
+ if (count > 1)
+ attempt += " (" + itos(count) + ")";
if (player->has_animation(attempt)) {
count++;
continue;
}
- base=attempt;
+ base = attempt;
break;
}
name->set_text(base);
- name_dialog->popup_centered(Size2(300,90));
+ name_dialog->popup_centered(Size2(300, 90));
name->select_all();
name->grab_focus();
}
void AnimationPlayerEditor::_animation_rename() {
- if (animation->get_item_count()==0)
+ if (animation->get_item_count() == 0)
return;
int selected = animation->get_selected();
String selected_name = animation->get_item_text(selected);
name_title->set_text(TTR("Change Animation Name:"));
name->set_text(selected_name);
- renaming=true;
- name_dialog->popup_centered(Size2(300,90));
+ renaming = true;
+ name_dialog->popup_centered(Size2(300, 90));
name->select_all();
name->grab_focus();
-
}
void AnimationPlayerEditor::_animation_load() {
ERR_FAIL_COND(!player);
- file->set_mode( EditorFileDialog::MODE_OPEN_FILE );
+ file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
file->clear_filters();
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("Animation",&extensions);
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
-
- file->add_filter("*."+E->get()+" ; "+E->get().to_upper() );
+ ResourceLoader::get_recognized_extensions_for_type("Animation", &extensions);
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file->add_filter("*." + E->get() + " ; " + E->get().to_upper());
}
file->popup_centered_ratio();
current_option = RESOURCE_LOAD;
}
-
-void AnimationPlayerEditor::_animation_save_in_path(const Ref<Resource>& p_resource, const String& p_path) {
+void AnimationPlayerEditor::_animation_save_in_path(const Ref<Resource> &p_resource, const String &p_path) {
int flg = 0;
if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources"))
@@ -393,29 +379,27 @@ void AnimationPlayerEditor::_animation_save_in_path(const Ref<Resource>& p_resou
}
//EditorFileSystem::get_singleton()->update_file(path,p_resource->get_type());
- ((Resource*)p_resource.ptr())->set_path(path);
+ ((Resource *)p_resource.ptr())->set_path(path);
editor->emit_signal("resource_saved", p_resource);
-
}
-void AnimationPlayerEditor::_animation_save(const Ref<Resource>& p_resource) {
+void AnimationPlayerEditor::_animation_save(const Ref<Resource> &p_resource) {
if (p_resource->get_path().is_resource_file()) {
_animation_save_in_path(p_resource, p_resource->get_path());
- }
- else {
+ } else {
_animation_save_as(p_resource);
}
}
-void AnimationPlayerEditor::_animation_save_as(const Ref<Resource>& p_resource) {
+void AnimationPlayerEditor::_animation_save_as(const Ref<Resource> &p_resource) {
file->set_mode(EditorFileDialog::MODE_SAVE_FILE);
List<String> extensions;
ResourceSaver::get_recognized_extensions(p_resource, &extensions);
file->clear_filters();
- for (int i = 0; i<extensions.size(); i++) {
+ for (int i = 0; i < extensions.size(); i++) {
file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
@@ -429,20 +413,17 @@ void AnimationPlayerEditor::_animation_save_as(const Ref<Resource>& p_resource)
file->set_current_path(p_resource->get_path().replacen("." + ext, "." + extensions.front()->get()));
}
}
- }
- else {
+ } else {
String existing;
if (extensions.size()) {
- if( p_resource->get_name() != "" ) {
+ if (p_resource->get_name() != "") {
existing = p_resource->get_name() + "." + extensions.front()->get().to_lower();
- }
- else {
+ } else {
existing = "new_" + p_resource->get_class().to_lower() + "." + extensions.front()->get().to_lower();
}
}
file->set_current_path(existing);
-
}
file->popup_centered_ratio();
file->set_title(TTR("Save Resource As.."));
@@ -471,25 +452,23 @@ void AnimationPlayerEditor::_animation_remove_confirmed() {
undo_redo->commit_action();
}
-void AnimationPlayerEditor::_select_anim_by_name(const String& p_anim) {
+void AnimationPlayerEditor::_select_anim_by_name(const String &p_anim) {
- int idx=-1;
- for(int i=0;i<animation->get_item_count();i++) {
+ int idx = -1;
+ for (int i = 0; i < animation->get_item_count(); i++) {
- if (animation->get_item_text(i)==p_anim) {
+ if (animation->get_item_text(i) == p_anim) {
- idx=i;
+ idx = i;
break;
}
}
- ERR_FAIL_COND(idx==-1);
-
+ ERR_FAIL_COND(idx == -1);
animation->select(idx);
_animation_selected(idx);
-
}
void AnimationPlayerEditor::_animation_name_edited() {
@@ -497,13 +476,13 @@ void AnimationPlayerEditor::_animation_name_edited() {
player->stop();
String new_name = name->get_text();
- if (new_name=="" || new_name.find(":")!=-1 || new_name.find("/")!=-1) {
+ if (new_name == "" || new_name.find(":") != -1 || new_name.find("/") != -1) {
error_dialog->set_text(TTR("ERROR: Invalid animation name!"));
error_dialog->popup_centered_minsize();
return;
}
- if (renaming && animation->get_item_count()>0 && animation->get_item_text(animation->get_selected())==new_name) {
+ if (renaming && animation->get_item_count() > 0 && animation->get_item_text(animation->get_selected()) == new_name) {
name_dialog->hide();
return;
}
@@ -516,51 +495,49 @@ void AnimationPlayerEditor::_animation_name_edited() {
if (renaming) {
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
undo_redo->create_action(TTR("Rename Animation"));
- undo_redo->add_do_method(player,"rename_animation",current,new_name);
- undo_redo->add_do_method(anim.ptr(),"set_name",new_name);
- undo_redo->add_undo_method(player,"rename_animation",new_name,current);
- undo_redo->add_undo_method(anim.ptr(),"set_name",current);
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "rename_animation", current, new_name);
+ undo_redo->add_do_method(anim.ptr(), "set_name", new_name);
+ undo_redo->add_undo_method(player, "rename_animation", new_name, current);
+ undo_redo->add_undo_method(anim.ptr(), "set_name", current);
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
_select_anim_by_name(new_name);
} else {
- Ref<Animation> new_anim = Ref<Animation>(memnew( Animation ));
+ Ref<Animation> new_anim = Ref<Animation>(memnew(Animation));
new_anim->set_name(new_name);
undo_redo->create_action(TTR("Add Animation"));
- undo_redo->add_do_method(player,"add_animation",new_name,new_anim);
- undo_redo->add_undo_method(player,"remove_animation",new_name);
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "add_animation", new_name, new_anim);
+ undo_redo->add_undo_method(player, "remove_animation", new_name);
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
_select_anim_by_name(new_name);
-
}
name_dialog->hide();
}
-
void AnimationPlayerEditor::_blend_editor_next_changed(const int p_idx) {
- if (animation->get_item_count()==0)
+ if (animation->get_item_count() == 0)
return;
String current = animation->get_item_text(animation->get_selected());
undo_redo->create_action(TTR("Blend Next Changed"));
- undo_redo->add_do_method(player,"animation_set_next",current,blend_editor.next->get_item_text(p_idx));
- undo_redo->add_undo_method(player,"animation_set_next",current,player->animation_get_next(current));
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "animation_set_next", current, blend_editor.next->get_item_text(p_idx));
+ undo_redo->add_undo_method(player, "animation_set_next", current, player->animation_get_next(current));
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
}
@@ -571,37 +548,37 @@ void AnimationPlayerEditor::_animation_blend() {
blend_editor.tree->clear();
- if (animation->get_item_count()==0)
+ if (animation->get_item_count() == 0)
return;
String current = animation->get_item_text(animation->get_selected());
- blend_editor.dialog->popup_centered(Size2(400,400));
+ blend_editor.dialog->popup_centered(Size2(400, 400));
blend_editor.tree->set_hide_root(true);
- blend_editor.tree->set_column_min_width(0,10);
- blend_editor.tree->set_column_min_width(1,3);
+ blend_editor.tree->set_column_min_width(0, 10);
+ blend_editor.tree->set_column_min_width(1, 3);
List<StringName> anims;
player->get_animation_list(&anims);
TreeItem *root = blend_editor.tree->create_item();
- updating_blends=true;
+ updating_blends = true;
int i = 0;
bool anim_found = false;
blend_editor.next->clear();
blend_editor.next->add_item("", i);
- for(List<StringName>::Element *E=anims.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
- String to=E->get();
- TreeItem *blend=blend_editor.tree->create_item(root);
- blend->set_editable(0,false);
- blend->set_editable(1,true);
- blend->set_text(0,to);
- blend->set_cell_mode(1,TreeItem::CELL_MODE_RANGE);
- blend->set_range_config(1,0,3600,0.001);
- blend->set_range(1,player->get_blend_time(current,to));
+ String to = E->get();
+ TreeItem *blend = blend_editor.tree->create_item(root);
+ blend->set_editable(0, false);
+ blend->set_editable(1, true);
+ blend->set_text(0, to);
+ blend->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
+ blend->set_range_config(1, 0, 3600, 0.001);
+ blend->set_range(1, player->get_blend_time(current, to));
i++;
blend_editor.next->add_item(to, i);
@@ -617,7 +594,7 @@ void AnimationPlayerEditor::_animation_blend() {
player->animation_set_next(current, blend_editor.next->get_item_text(0));
}
- updating_blends=false;
+ updating_blends = false;
}
void AnimationPlayerEditor::_blend_edited() {
@@ -625,7 +602,7 @@ void AnimationPlayerEditor::_blend_edited() {
if (updating_blends)
return;
- if (animation->get_item_count()==0)
+ if (animation->get_item_count() == 0)
return;
String current = animation->get_item_text(animation->get_selected());
@@ -634,18 +611,18 @@ void AnimationPlayerEditor::_blend_edited() {
if (!selected)
return;
- updating_blends=true;
- String to=selected->get_text(0);
+ updating_blends = true;
+ String to = selected->get_text(0);
float blend_time = selected->get_range(1);
- float prev_blend_time = player->get_blend_time(current,to);
+ float prev_blend_time = player->get_blend_time(current, to);
undo_redo->create_action(TTR("Change Blend Time"));
- undo_redo->add_do_method(player,"set_blend_time",current,to,blend_time);
- undo_redo->add_undo_method(player,"set_blend_time",current,to,prev_blend_time);
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "set_blend_time", current, to, blend_time);
+ undo_redo->add_undo_method(player, "set_blend_time", current, to, prev_blend_time);
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
- updating_blends=false;
+ updating_blends = false;
}
void AnimationPlayerEditor::ensure_visibility() {
@@ -658,20 +635,17 @@ void AnimationPlayerEditor::ensure_visibility() {
Dictionary AnimationPlayerEditor::get_state() const {
-
Dictionary d;
- d["visible"]=is_visible_in_tree();
+ d["visible"] = is_visible_in_tree();
if (EditorNode::get_singleton()->get_edited_scene() && is_visible_in_tree() && player) {
- d["player"]=EditorNode::get_singleton()->get_edited_scene()->get_path_to(player);
- d["animation"]=player->get_current_animation();
-
+ d["player"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(player);
+ d["animation"] = player->get_current_animation();
}
return d;
-
}
-void AnimationPlayerEditor::set_state(const Dictionary& p_state) {
+void AnimationPlayerEditor::set_state(const Dictionary &p_state) {
if (p_state.has("visible") && p_state["visible"]) {
@@ -680,7 +654,7 @@ void AnimationPlayerEditor::set_state(const Dictionary& p_state) {
Node *n = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["player"]);
if (n && n->cast_to<AnimationPlayer>() && EditorNode::get_singleton()->get_editor_selection()->is_selected(n)) {
- player=n->cast_to<AnimationPlayer>();
+ player = n->cast_to<AnimationPlayer>();
_update_player();
show();
set_process(true);
@@ -692,28 +666,24 @@ void AnimationPlayerEditor::set_state(const Dictionary& p_state) {
_select_anim_by_name(anim);
_animation_edit();
}
-
}
}
-
}
-
void AnimationPlayerEditor::_animation_resource_edit() {
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
editor->edit_resource(anim);
}
-
}
void AnimationPlayerEditor::_animation_edit() {
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
key_editor->set_animation(anim);
Node *root = player->get_node(player->get_root());
if (root) {
@@ -724,9 +694,7 @@ void AnimationPlayerEditor::_animation_edit() {
key_editor->set_animation(Ref<Animation>());
key_editor->set_root(NULL);
-
}
-
}
void AnimationPlayerEditor::_dialog_action(String p_file) {
@@ -740,12 +708,10 @@ void AnimationPlayerEditor::_dialog_action(String p_file) {
if (p_file.find_last("/") != -1) {
p_file = p_file.substr(p_file.find_last("/") + 1, p_file.length());
-
}
if (p_file.find_last("\\") != -1) {
p_file = p_file.substr(p_file.find_last("\\") + 1, p_file.length());
-
}
if (p_file.find(".") != -1)
@@ -756,7 +722,6 @@ void AnimationPlayerEditor::_dialog_action(String p_file) {
undo_redo->add_undo_method(player, "remove_animation", p_file);
if (player->has_animation(p_file)) {
undo_redo->add_undo_method(player, "add_animation", p_file, player->get_animation(p_file));
-
}
undo_redo->add_do_method(this, "_animation_player_changed", player);
undo_redo->add_undo_method(this, "_animation_player_changed", player);
@@ -771,7 +736,7 @@ void AnimationPlayerEditor::_dialog_action(String p_file) {
ERR_FAIL_COND(!anim->cast_to<Resource>())
- RES current_res = RES(anim->cast_to<Resource>());
+ RES current_res = RES(anim->cast_to<Resource>());
_animation_save_in_path(current_res, p_file);
}
@@ -779,7 +744,7 @@ void AnimationPlayerEditor::_dialog_action(String p_file) {
}
}
-void AnimationPlayerEditor::_scale_changed(const String& p_scale) {
+void AnimationPlayerEditor::_scale_changed(const String &p_scale) {
player->set_speed_scale(p_scale.to_double());
}
@@ -789,8 +754,7 @@ void AnimationPlayerEditor::_update_animation() {
// the purpose of _update_animation is to reflect the current state
// of the animation player in the current editor..
- updating=true;
-
+ updating = true;
if (player->is_playing()) {
@@ -803,24 +767,23 @@ void AnimationPlayerEditor::_update_animation() {
stop->set_pressed(true);
}
- scale->set_text( String::num(player->get_speed_scale(),2) );
- String current=player->get_current_animation();
+ scale->set_text(String::num(player->get_speed_scale(), 2));
+ String current = player->get_current_animation();
- for (int i=0;i<animation->get_item_count();i++) {
+ for (int i = 0; i < animation->get_item_count(); i++) {
- if (animation->get_item_text(i)==current) {
+ if (animation->get_item_text(i) == current) {
animation->select(i);
break;
}
}
- updating=false;
+ updating = false;
}
void AnimationPlayerEditor::_update_player() {
-
- updating=true;
+ updating = true;
List<StringName> animlist;
if (player)
player->get_animation_list(&animlist);
@@ -831,78 +794,70 @@ void AnimationPlayerEditor::_update_player() {
else
nodename->set_text("<empty>");
-
- add_anim->set_disabled(player==NULL);
- load_anim->set_disabled(player==NULL);
- stop->set_disabled(animlist.size()==0);
- play->set_disabled(animlist.size()==0);
- play_bw->set_disabled(animlist.size()==0);
- play_bw_from->set_disabled(animlist.size()==0);
- play_from->set_disabled(animlist.size()==0);
- autoplay->set_disabled(animlist.size()==0);
- duplicate_anim->set_disabled(animlist.size()==0);
- rename_anim->set_disabled(animlist.size()==0);
- blend_anim->set_disabled(animlist.size()==0);
- remove_anim->set_disabled(animlist.size()==0);
- resource_edit_anim->set_disabled(animlist.size()==0);
+ add_anim->set_disabled(player == NULL);
+ load_anim->set_disabled(player == NULL);
+ stop->set_disabled(animlist.size() == 0);
+ play->set_disabled(animlist.size() == 0);
+ play_bw->set_disabled(animlist.size() == 0);
+ play_bw_from->set_disabled(animlist.size() == 0);
+ play_from->set_disabled(animlist.size() == 0);
+ autoplay->set_disabled(animlist.size() == 0);
+ duplicate_anim->set_disabled(animlist.size() == 0);
+ rename_anim->set_disabled(animlist.size() == 0);
+ blend_anim->set_disabled(animlist.size() == 0);
+ remove_anim->set_disabled(animlist.size() == 0);
+ resource_edit_anim->set_disabled(animlist.size() == 0);
save_anim->set_disabled(animlist.size() == 0);
- tool_anim->set_disabled(player==NULL);
+ tool_anim->set_disabled(player == NULL);
+ int active_idx = -1;
+ for (List<StringName>::Element *E = animlist.front(); E; E = E->next()) {
- int active_idx=-1;
- for (List<StringName>::Element *E=animlist.front();E;E=E->next()) {
-
- if (player->get_autoplay()==E->get())
- animation->add_icon_item(autoplay_icon,E->get());
+ if (player->get_autoplay() == E->get())
+ animation->add_icon_item(autoplay_icon, E->get());
else
animation->add_item(E->get());
- if (player->get_current_animation()==E->get())
- active_idx=animation->get_item_count()-1;
-
+ if (player->get_current_animation() == E->get())
+ active_idx = animation->get_item_count() - 1;
}
if (!player)
return;
- updating=false;
- if (active_idx!=-1) {
+ updating = false;
+ if (active_idx != -1) {
animation->select(active_idx);
- autoplay->set_pressed(animation->get_item_text(active_idx)==player->get_autoplay());
+ autoplay->set_pressed(animation->get_item_text(active_idx) == player->get_autoplay());
_animation_selected(active_idx);
- } else if (animation->get_item_count()>0){
+ } else if (animation->get_item_count() > 0) {
animation->select(0);
- autoplay->set_pressed(animation->get_item_text(0)==player->get_autoplay());
+ autoplay->set_pressed(animation->get_item_text(0) == player->get_autoplay());
_animation_selected(0);
}
//pause->set_pressed(player->is_paused());
-
if (animation->get_item_count()) {
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
key_editor->set_animation(anim);
Node *root = player->get_node(player->get_root());
if (root) {
key_editor->set_root(root);
}
-
}
_update_animation();
}
-
-
void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
-
if (player && pin->is_pressed())
return; //ignore, pinned
- player=p_player;
+ player = p_player;
if (player) {
_update_player();
@@ -911,29 +866,25 @@ void AnimationPlayerEditor::edit(AnimationPlayer *p_player) {
key_editor->show_select_node_warning(true);
//hide();
-
}
-
}
-
void AnimationPlayerEditor::_animation_duplicate() {
-
if (!animation->get_item_count())
return;
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
if (!anim.is_valid())
return;
- Ref<Animation> new_anim = memnew( Animation );
+ Ref<Animation> new_anim = memnew(Animation);
List<PropertyInfo> plist;
anim->get_property_list(&plist);
- for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (E->get().usage&PROPERTY_USAGE_STORAGE) {
+ if (E->get().usage & PROPERTY_USAGE_STORAGE) {
new_anim->set(E->get().name, anim->get(E->get().name));
}
@@ -941,78 +892,73 @@ void AnimationPlayerEditor::_animation_duplicate() {
new_anim->set_path("");
String new_name = current;
- while(player->has_animation(new_name)) {
+ while (player->has_animation(new_name)) {
- new_name=new_name+" (copy)";
+ new_name = new_name + " (copy)";
}
-
undo_redo->create_action(TTR("Duplicate Animation"));
- undo_redo->add_do_method(player,"add_animation",new_name,new_anim);
- undo_redo->add_undo_method(player,"remove_animation",new_name);
- undo_redo->add_do_method(player,"animation_set_next",new_name,player->animation_get_next(current));
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "add_animation", new_name, new_anim);
+ undo_redo->add_undo_method(player, "remove_animation", new_name);
+ undo_redo->add_do_method(player, "animation_set_next", new_name, player->animation_get_next(current));
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
+ for (int i = 0; i < animation->get_item_count(); i++) {
- for(int i=0;i<animation->get_item_count();i++) {
-
- if (animation->get_item_text(i)==new_name) {
+ if (animation->get_item_text(i) == new_name) {
animation->select(i);
_animation_selected(i);
return;
}
}
-
}
-void AnimationPlayerEditor::_seek_value_changed(float p_value,bool p_set) {
+void AnimationPlayerEditor::_seek_value_changed(float p_value, bool p_set) {
if (updating || !player || player->is_playing()) {
return;
};
-
- updating=true;
- String current=player->get_current_animation(); //animation->get_item_text( animation->get_selected() );
+ updating = true;
+ String current = player->get_current_animation(); //animation->get_item_text( animation->get_selected() );
if (current == "" || !player->has_animation(current)) {
- updating=false;
- current="";
+ updating = false;
+ current = "";
return;
};
Ref<Animation> anim;
- anim=player->get_animation(current);
+ anim = player->get_animation(current);
float pos = anim->get_length() * (p_value / frame->get_max());
float step = anim->get_step();
if (step) {
- pos=Math::stepify(pos, step);
- if (pos<0)
- pos=0;
- if (pos>=anim->get_length())
- pos=anim->get_length();
+ pos = Math::stepify(pos, step);
+ if (pos < 0)
+ pos = 0;
+ if (pos >= anim->get_length())
+ pos = anim->get_length();
}
if (player->is_valid() && !p_set) {
float cpos = player->get_current_animation_pos();
- player->seek_delta(pos,pos-cpos);
+ player->seek_delta(pos, pos - cpos);
} else {
- player->seek(pos,true);
+ player->seek(pos, true);
}
-
key_editor->set_anim_pos(pos);
- updating=true;
+ updating = true;
};
void AnimationPlayerEditor::_animation_player_changed(Object *p_pl) {
- if (player==p_pl && is_visible_in_tree()) {
+ if (player == p_pl && is_visible_in_tree()) {
_update_player();
if (blend_editor.dialog->is_visible_in_tree())
@@ -1020,11 +966,9 @@ void AnimationPlayerEditor::_animation_player_changed(Object *p_pl) {
}
}
-
-
void AnimationPlayerEditor::_list_changed() {
- if(is_visible_in_tree())
+ if (is_visible_in_tree())
_update_player();
}
#if 0
@@ -1095,9 +1039,7 @@ void AnimationPlayerEditor::_editor_load(){
void AnimationPlayerEditor::_animation_key_editor_anim_len_changed(float p_len) {
-
frame->set_max(p_len);
-
}
void AnimationPlayerEditor::_animation_key_editor_anim_step_changed(float p_len) {
@@ -1106,49 +1048,43 @@ void AnimationPlayerEditor::_animation_key_editor_anim_step_changed(float p_len)
frame->set_step(p_len);
else
frame->set_step(0.00001);
-
}
-
-void AnimationPlayerEditor::_animation_key_editor_seek(float p_pos,bool p_drag) {
+void AnimationPlayerEditor::_animation_key_editor_seek(float p_pos, bool p_drag) {
if (!is_visible_in_tree())
return;
if (!player)
return;
- if (player->is_playing() )
+ if (player->is_playing())
return;
- updating=true;
- frame->set_value(p_pos);
- updating=false;
- _seek_value_changed(p_pos,!p_drag);
+ updating = true;
+ frame->set_value(p_pos);
+ updating = false;
+ _seek_value_changed(p_pos, !p_drag);
EditorNode::get_singleton()->get_property_editor()->refresh();
-
-
//seekit
}
void AnimationPlayerEditor::_hide_anim_editors() {
- player=NULL;
+ player = NULL;
hide();
set_process(false);
key_editor->set_animation(Ref<Animation>());
key_editor->set_root(NULL);
key_editor->show_select_node_warning(true);
- //editor->animation_editor_make_visible(false);
-
+ //editor->animation_editor_make_visible(false);
}
-
void AnimationPlayerEditor::_animation_tool_menu(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case TOOL_COPY_ANIM: {
@@ -1159,7 +1095,7 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) {
}
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
//editor->edit_resource(anim);
EditorSettings::get_singleton()->set_resource_clipboard(anim);
@@ -1174,28 +1110,27 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) {
}
String name = anim->get_name();
- if (name=="") {
- name=TTR("Pasted Animation");
+ if (name == "") {
+ name = TTR("Pasted Animation");
}
- int idx=1;
+ int idx = 1;
String base = name;
while (player->has_animation(name)) {
idx++;
- name=base+" "+itos(idx);
+ name = base + " " + itos(idx);
}
undo_redo->create_action(TTR("Paste Animation"));
- undo_redo->add_do_method(player,"add_animation",name,anim);
- undo_redo->add_undo_method(player,"remove_animation",name);
- undo_redo->add_do_method(this,"_animation_player_changed",player);
- undo_redo->add_undo_method(this,"_animation_player_changed",player);
+ undo_redo->add_do_method(player, "add_animation", name, anim);
+ undo_redo->add_undo_method(player, "remove_animation", name);
+ undo_redo->add_do_method(this, "_animation_player_changed", player);
+ undo_redo->add_undo_method(this, "_animation_player_changed", player);
undo_redo->commit_action();
_select_anim_by_name(name);
-
} break;
case TOOL_EDIT_RESOURCE: {
@@ -1206,11 +1141,10 @@ void AnimationPlayerEditor::_animation_tool_menu(int p_option) {
}
String current = animation->get_item_text(animation->get_selected());
- Ref<Animation> anim = player->get_animation(current);
+ Ref<Animation> anim = player->get_animation(current);
editor->edit_resource(anim);
} break;
-
}
}
@@ -1221,21 +1155,21 @@ void AnimationPlayerEditor::_animation_save_menu(int p_option) {
Ref<Animation> anim = player->get_animation(current);
switch (p_option) {
- case ANIM_SAVE:
- _animation_save(anim);
- break;
- case ANIM_SAVE_AS:
- _animation_save_as(anim);
- break;
+ case ANIM_SAVE:
+ _animation_save(anim);
+ break;
+ case ANIM_SAVE_AS:
+ _animation_save_as(anim);
+ break;
}
}
}
-void AnimationPlayerEditor::_unhandled_key_input(const InputEvent& p_ev) {
+void AnimationPlayerEditor::_unhandled_key_input(const InputEvent &p_ev) {
- if (is_visible_in_tree() && p_ev.type==InputEvent::KEY && p_ev.key.pressed && !p_ev.key.echo && !p_ev.key.mod.alt && !p_ev.key.mod.control && !p_ev.key.mod.meta) {
+ if (is_visible_in_tree() && p_ev.type == InputEvent::KEY && p_ev.key.pressed && !p_ev.key.echo && !p_ev.key.mod.alt && !p_ev.key.mod.control && !p_ev.key.mod.meta) {
- switch(p_ev.key.scancode) {
+ switch (p_ev.key.scancode) {
case KEY_A: {
if (!p_ev.key.mod.shift)
@@ -1258,130 +1192,119 @@ void AnimationPlayerEditor::_unhandled_key_input(const InputEvent& p_ev) {
void AnimationPlayerEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&AnimationPlayerEditor::_gui_input);
- ClassDB::bind_method(D_METHOD("_node_removed"),&AnimationPlayerEditor::_node_removed);
- ClassDB::bind_method(D_METHOD("_play_pressed"),&AnimationPlayerEditor::_play_pressed);
- ClassDB::bind_method(D_METHOD("_play_from_pressed"),&AnimationPlayerEditor::_play_from_pressed);
- ClassDB::bind_method(D_METHOD("_play_bw_pressed"),&AnimationPlayerEditor::_play_bw_pressed);
- ClassDB::bind_method(D_METHOD("_play_bw_from_pressed"),&AnimationPlayerEditor::_play_bw_from_pressed);
- ClassDB::bind_method(D_METHOD("_stop_pressed"),&AnimationPlayerEditor::_stop_pressed);
- ClassDB::bind_method(D_METHOD("_autoplay_pressed"),&AnimationPlayerEditor::_autoplay_pressed);
- ClassDB::bind_method(D_METHOD("_pause_pressed"),&AnimationPlayerEditor::_pause_pressed);
- ClassDB::bind_method(D_METHOD("_animation_selected"),&AnimationPlayerEditor::_animation_selected);
- ClassDB::bind_method(D_METHOD("_animation_name_edited"),&AnimationPlayerEditor::_animation_name_edited);
- ClassDB::bind_method(D_METHOD("_animation_new"),&AnimationPlayerEditor::_animation_new);
- ClassDB::bind_method(D_METHOD("_animation_rename"),&AnimationPlayerEditor::_animation_rename);
- ClassDB::bind_method(D_METHOD("_animation_load"),&AnimationPlayerEditor::_animation_load);
- ClassDB::bind_method(D_METHOD("_animation_remove"),&AnimationPlayerEditor::_animation_remove);
- ClassDB::bind_method(D_METHOD("_animation_remove_confirmed"),&AnimationPlayerEditor::_animation_remove_confirmed);
- ClassDB::bind_method(D_METHOD("_animation_blend"),&AnimationPlayerEditor::_animation_blend);
- ClassDB::bind_method(D_METHOD("_animation_edit"),&AnimationPlayerEditor::_animation_edit);
- ClassDB::bind_method(D_METHOD("_animation_resource_edit"),&AnimationPlayerEditor::_animation_resource_edit);
- ClassDB::bind_method(D_METHOD("_dialog_action"),&AnimationPlayerEditor::_dialog_action);
- ClassDB::bind_method(D_METHOD("_seek_value_changed"),&AnimationPlayerEditor::_seek_value_changed,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("_animation_player_changed"),&AnimationPlayerEditor::_animation_player_changed);
- ClassDB::bind_method(D_METHOD("_blend_edited"),&AnimationPlayerEditor::_blend_edited);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &AnimationPlayerEditor::_gui_input);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &AnimationPlayerEditor::_node_removed);
+ ClassDB::bind_method(D_METHOD("_play_pressed"), &AnimationPlayerEditor::_play_pressed);
+ ClassDB::bind_method(D_METHOD("_play_from_pressed"), &AnimationPlayerEditor::_play_from_pressed);
+ ClassDB::bind_method(D_METHOD("_play_bw_pressed"), &AnimationPlayerEditor::_play_bw_pressed);
+ ClassDB::bind_method(D_METHOD("_play_bw_from_pressed"), &AnimationPlayerEditor::_play_bw_from_pressed);
+ ClassDB::bind_method(D_METHOD("_stop_pressed"), &AnimationPlayerEditor::_stop_pressed);
+ ClassDB::bind_method(D_METHOD("_autoplay_pressed"), &AnimationPlayerEditor::_autoplay_pressed);
+ ClassDB::bind_method(D_METHOD("_pause_pressed"), &AnimationPlayerEditor::_pause_pressed);
+ ClassDB::bind_method(D_METHOD("_animation_selected"), &AnimationPlayerEditor::_animation_selected);
+ ClassDB::bind_method(D_METHOD("_animation_name_edited"), &AnimationPlayerEditor::_animation_name_edited);
+ ClassDB::bind_method(D_METHOD("_animation_new"), &AnimationPlayerEditor::_animation_new);
+ ClassDB::bind_method(D_METHOD("_animation_rename"), &AnimationPlayerEditor::_animation_rename);
+ ClassDB::bind_method(D_METHOD("_animation_load"), &AnimationPlayerEditor::_animation_load);
+ ClassDB::bind_method(D_METHOD("_animation_remove"), &AnimationPlayerEditor::_animation_remove);
+ ClassDB::bind_method(D_METHOD("_animation_remove_confirmed"), &AnimationPlayerEditor::_animation_remove_confirmed);
+ ClassDB::bind_method(D_METHOD("_animation_blend"), &AnimationPlayerEditor::_animation_blend);
+ ClassDB::bind_method(D_METHOD("_animation_edit"), &AnimationPlayerEditor::_animation_edit);
+ ClassDB::bind_method(D_METHOD("_animation_resource_edit"), &AnimationPlayerEditor::_animation_resource_edit);
+ ClassDB::bind_method(D_METHOD("_dialog_action"), &AnimationPlayerEditor::_dialog_action);
+ ClassDB::bind_method(D_METHOD("_seek_value_changed"), &AnimationPlayerEditor::_seek_value_changed, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("_animation_player_changed"), &AnimationPlayerEditor::_animation_player_changed);
+ ClassDB::bind_method(D_METHOD("_blend_edited"), &AnimationPlayerEditor::_blend_edited);
//ClassDB::bind_method(D_METHOD("_seek_frame_changed"),&AnimationPlayerEditor::_seek_frame_changed);
- ClassDB::bind_method(D_METHOD("_scale_changed"),&AnimationPlayerEditor::_scale_changed);
+ ClassDB::bind_method(D_METHOD("_scale_changed"), &AnimationPlayerEditor::_scale_changed);
//ClassDB::bind_method(D_METHOD("_editor_store_all"),&AnimationPlayerEditor::_editor_store_all);
//ClassDB::bind_method(D_METHOD("_editor_load_all"),&AnimationPlayerEditor::_editor_load_all);
- ClassDB::bind_method(D_METHOD("_list_changed"),&AnimationPlayerEditor::_list_changed);
- ClassDB::bind_method(D_METHOD("_animation_key_editor_seek"),&AnimationPlayerEditor::_animation_key_editor_seek);
- ClassDB::bind_method(D_METHOD("_animation_key_editor_anim_len_changed"),&AnimationPlayerEditor::_animation_key_editor_anim_len_changed);
- ClassDB::bind_method(D_METHOD("_animation_key_editor_anim_step_changed"),&AnimationPlayerEditor::_animation_key_editor_anim_step_changed);
- ClassDB::bind_method(D_METHOD("_hide_anim_editors"),&AnimationPlayerEditor::_hide_anim_editors);
- ClassDB::bind_method(D_METHOD("_animation_duplicate"),&AnimationPlayerEditor::_animation_duplicate);
- ClassDB::bind_method(D_METHOD("_blend_editor_next_changed"),&AnimationPlayerEditor::_blend_editor_next_changed);
- ClassDB::bind_method(D_METHOD("_unhandled_key_input"),&AnimationPlayerEditor::_unhandled_key_input);
- ClassDB::bind_method(D_METHOD("_animation_tool_menu"),&AnimationPlayerEditor::_animation_tool_menu);
+ ClassDB::bind_method(D_METHOD("_list_changed"), &AnimationPlayerEditor::_list_changed);
+ ClassDB::bind_method(D_METHOD("_animation_key_editor_seek"), &AnimationPlayerEditor::_animation_key_editor_seek);
+ ClassDB::bind_method(D_METHOD("_animation_key_editor_anim_len_changed"), &AnimationPlayerEditor::_animation_key_editor_anim_len_changed);
+ ClassDB::bind_method(D_METHOD("_animation_key_editor_anim_step_changed"), &AnimationPlayerEditor::_animation_key_editor_anim_step_changed);
+ ClassDB::bind_method(D_METHOD("_hide_anim_editors"), &AnimationPlayerEditor::_hide_anim_editors);
+ ClassDB::bind_method(D_METHOD("_animation_duplicate"), &AnimationPlayerEditor::_animation_duplicate);
+ ClassDB::bind_method(D_METHOD("_blend_editor_next_changed"), &AnimationPlayerEditor::_blend_editor_next_changed);
+ ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &AnimationPlayerEditor::_unhandled_key_input);
+ ClassDB::bind_method(D_METHOD("_animation_tool_menu"), &AnimationPlayerEditor::_animation_tool_menu);
ClassDB::bind_method(D_METHOD("_animation_save_menu"), &AnimationPlayerEditor::_animation_save_menu);
-
-
-
-
}
-AnimationPlayerEditor *AnimationPlayerEditor::singleton=NULL;
+AnimationPlayerEditor *AnimationPlayerEditor::singleton = NULL;
AnimationPlayer *AnimationPlayerEditor::get_player() const {
return player;
}
AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) {
- editor=p_editor;
- singleton=this;
+ editor = p_editor;
+ singleton = this;
- updating=false;
+ updating = false;
set_focus_mode(FOCUS_ALL);
- player=NULL;
- add_style_override("panel", get_stylebox("panel","Panel"));
-
+ player = NULL;
+ add_style_override("panel", get_stylebox("panel", "Panel"));
- Label * l;
+ Label *l;
/*l= memnew( Label );
l->set_text("Animation Player:");
add_child(l);*/
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
-
- play_bw_from = memnew( ToolButton );
+ play_bw_from = memnew(ToolButton);
play_bw_from->set_tooltip(TTR("Play selected animation backwards from current pos. (A)"));
hb->add_child(play_bw_from);
- play_bw = memnew( ToolButton );
+ play_bw = memnew(ToolButton);
play_bw->set_tooltip(TTR("Play selected animation backwards from end. (Shift+A)"));
hb->add_child(play_bw);
- stop = memnew( ToolButton );
+ stop = memnew(ToolButton);
stop->set_toggle_mode(true);
hb->add_child(stop);
stop->set_tooltip(TTR("Stop animation playback. (S)"));
- play = memnew( ToolButton );
+ play = memnew(ToolButton);
play->set_tooltip(TTR("Play selected animation from start. (Shift+D)"));
hb->add_child(play);
-
- play_from = memnew( ToolButton );
+ play_from = memnew(ToolButton);
play_from->set_tooltip(TTR("Play selected animation from current pos. (D)"));
hb->add_child(play_from);
-
-
//pause = memnew( Button );
//pause->set_toggle_mode(true);
//hb->add_child(pause);
- frame = memnew( SpinBox );
+ frame = memnew(SpinBox);
hb->add_child(frame);
- frame->set_custom_minimum_size(Size2(60,0));
+ frame->set_custom_minimum_size(Size2(60, 0));
frame->set_stretch_ratio(2);
frame->set_tooltip(TTR("Animation position (in seconds)."));
- hb->add_child( memnew( VSeparator));
+ hb->add_child(memnew(VSeparator));
- scale = memnew( LineEdit );
+ scale = memnew(LineEdit);
hb->add_child(scale);
scale->set_h_size_flags(SIZE_EXPAND_FILL);
scale->set_stretch_ratio(1);
scale->set_tooltip(TTR("Scale animation playback globally for the node."));
scale->hide();
-
- add_anim = memnew( ToolButton );
+ add_anim = memnew(ToolButton);
ED_SHORTCUT("animation_player_editor/add_animation", TTR("Create new animation in player."));
add_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/add_animation"));
add_anim->set_tooltip(TTR("Create new animation in player."));
hb->add_child(add_anim);
-
- load_anim = memnew( ToolButton );
+ load_anim = memnew(ToolButton);
ED_SHORTCUT("animation_player_editor/load_from_disk", TTR("Load animation from disk."));
add_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/load_from_disk"));
load_anim->set_tooltip(TTR("Load an animation from disk."));
@@ -1402,159 +1325,146 @@ AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) {
add_child(delete_dialog);
delete_dialog->connect("confirmed", this, "_animation_remove_confirmed");
- duplicate_anim = memnew( ToolButton );
+ duplicate_anim = memnew(ToolButton);
hb->add_child(duplicate_anim);
ED_SHORTCUT("animation_player_editor/duplicate_animation", TTR("Duplicate Animation"));
duplicate_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/duplicate_animation"));
duplicate_anim->set_tooltip(TTR("Duplicate Animation"));
- rename_anim = memnew( ToolButton );
+ rename_anim = memnew(ToolButton);
hb->add_child(rename_anim);
ED_SHORTCUT("animation_player_editor/rename_animation", TTR("Rename Animation"));
rename_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/rename_animation"));
rename_anim->set_tooltip(TTR("Rename Animation"));
- remove_anim = memnew( ToolButton );
+ remove_anim = memnew(ToolButton);
hb->add_child(remove_anim);
ED_SHORTCUT("animation_player_editor/remove_animation", TTR("Remove Animation"));
remove_anim->set_shortcut(ED_GET_SHORTCUT("animation_player_editor/remove_animation"));
remove_anim->set_tooltip(TTR("Remove Animation"));
-
- animation = memnew( OptionButton );
+ animation = memnew(OptionButton);
hb->add_child(animation);
animation->set_h_size_flags(SIZE_EXPAND_FILL);
animation->set_tooltip(TTR("Display list of animations in player."));
animation->set_clip_text(true);
- autoplay = memnew( ToolButton );
+ autoplay = memnew(ToolButton);
hb->add_child(autoplay);
autoplay->set_tooltip(TTR("Autoplay on Load"));
-
-
- blend_anim = memnew( ToolButton );
+ blend_anim = memnew(ToolButton);
hb->add_child(blend_anim);
blend_anim->set_tooltip(TTR("Edit Target Blend Times"));
- tool_anim = memnew( MenuButton);
+ tool_anim = memnew(MenuButton);
//tool_anim->set_flat(false);
tool_anim->set_tooltip(TTR("Animation Tools"));
- tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/copy_animation", TTR("Copy Animation")),TOOL_COPY_ANIM);
- tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation", TTR("Paste Animation")),TOOL_PASTE_ANIM);
+ tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/copy_animation", TTR("Copy Animation")), TOOL_COPY_ANIM);
+ tool_anim->get_popup()->add_shortcut(ED_SHORTCUT("animation_player_editor/paste_animation", TTR("Paste Animation")), TOOL_PASTE_ANIM);
//tool_anim->get_popup()->add_separator();
//tool_anim->get_popup()->add_item("Edit Anim Resource",TOOL_PASTE_ANIM);
hb->add_child(tool_anim);
- nodename = memnew( Button );
+ nodename = memnew(Button);
hb->add_child(nodename);
- pin = memnew( ToolButton );
+ pin = memnew(ToolButton);
pin->set_toggle_mode(true);
hb->add_child(pin);
-
-
- resource_edit_anim= memnew( Button );
+ resource_edit_anim = memnew(Button);
hb->add_child(resource_edit_anim);
resource_edit_anim->hide();
-
file = memnew(EditorFileDialog);
add_child(file);
- name_dialog = memnew( ConfirmationDialog );
+ name_dialog = memnew(ConfirmationDialog);
name_dialog->set_title(TTR("Create New Animation"));
name_dialog->set_hide_on_ok(false);
add_child(name_dialog);
- name = memnew( LineEdit );
+ name = memnew(LineEdit);
name_dialog->add_child(name);
- name->set_pos(Point2(18,30));
- name->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,10);
+ name->set_pos(Point2(18, 30));
+ name->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 10);
name_dialog->register_text_enter(name);
-
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Animation Name:"));
- l->set_pos( Point2(10,10) );
+ l->set_pos(Point2(10, 10));
name_dialog->add_child(l);
- name_title=l;
+ name_title = l;
- error_dialog = memnew( ConfirmationDialog );
+ error_dialog = memnew(ConfirmationDialog);
error_dialog->get_ok()->set_text(TTR("Close"));
//error_dialog->get_cancel()->set_text("Close");
error_dialog->set_text(TTR("Error!"));
add_child(error_dialog);
- name_dialog->connect("confirmed", this,"_animation_name_edited");
+ name_dialog->connect("confirmed", this, "_animation_name_edited");
- blend_editor.dialog = memnew( AcceptDialog );
+ blend_editor.dialog = memnew(AcceptDialog);
add_child(blend_editor.dialog);
blend_editor.dialog->get_ok()->set_text(TTR("Close"));
blend_editor.dialog->set_hide_on_ok(true);
- VBoxContainer *blend_vb = memnew( VBoxContainer);
+ VBoxContainer *blend_vb = memnew(VBoxContainer);
blend_editor.dialog->add_child(blend_vb);
//blend_editor.dialog->set_child_rect(blend_vb);
- blend_editor.tree = memnew( Tree );
+ blend_editor.tree = memnew(Tree);
blend_editor.tree->set_columns(2);
- blend_vb->add_margin_child(TTR("Blend Times:"),blend_editor.tree,true);
- blend_editor.next = memnew( OptionButton );
- blend_vb->add_margin_child(TTR("Next (Auto Queue):"),blend_editor.next);
+ blend_vb->add_margin_child(TTR("Blend Times:"), blend_editor.tree, true);
+ blend_editor.next = memnew(OptionButton);
+ blend_vb->add_margin_child(TTR("Next (Auto Queue):"), blend_editor.next);
blend_editor.dialog->set_title(TTR("Cross-Animation Blend Times"));
- updating_blends=false;
+ updating_blends = false;
- blend_editor.tree->connect("item_edited",this,"_blend_edited");
+ blend_editor.tree->connect("item_edited", this, "_blend_edited");
-
- autoplay->connect("pressed", this,"_autoplay_pressed");
+ autoplay->connect("pressed", this, "_autoplay_pressed");
autoplay->set_toggle_mode(true);
- play->connect("pressed", this,"_play_pressed");
- play_from->connect("pressed", this,"_play_from_pressed");
- play_bw->connect("pressed", this,"_play_bw_pressed");
- play_bw_from->connect("pressed", this,"_play_bw_from_pressed");
- stop->connect("pressed", this,"_stop_pressed");
+ play->connect("pressed", this, "_play_pressed");
+ play_from->connect("pressed", this, "_play_from_pressed");
+ play_bw->connect("pressed", this, "_play_bw_pressed");
+ play_bw_from->connect("pressed", this, "_play_bw_from_pressed");
+ stop->connect("pressed", this, "_stop_pressed");
//pause->connect("pressed", this,"_pause_pressed");
- add_anim->connect("pressed", this,"_animation_new");
- rename_anim->connect("pressed", this,"_animation_rename");
- load_anim->connect("pressed", this,"_animation_load");
- duplicate_anim->connect("pressed", this,"_animation_duplicate");
+ add_anim->connect("pressed", this, "_animation_new");
+ rename_anim->connect("pressed", this, "_animation_rename");
+ load_anim->connect("pressed", this, "_animation_load");
+ duplicate_anim->connect("pressed", this, "_animation_duplicate");
//frame->connect("text_entered", this,"_seek_frame_changed");
- blend_anim->connect("pressed", this,"_animation_blend");
- remove_anim->connect("pressed", this,"_animation_remove");
- animation->connect("item_selected", this,"_animation_selected",Vector<Variant>(),true);
- resource_edit_anim->connect("pressed", this,"_animation_resource_edit");
- file->connect("file_selected", this,"_dialog_action");
- frame->connect("value_changed", this, "_seek_value_changed",Vector<Variant>(),true);
- scale->connect("text_entered", this, "_scale_changed",Vector<Variant>(),true);
-
+ blend_anim->connect("pressed", this, "_animation_blend");
+ remove_anim->connect("pressed", this, "_animation_remove");
+ animation->connect("item_selected", this, "_animation_selected", Vector<Variant>(), true);
+ resource_edit_anim->connect("pressed", this, "_animation_resource_edit");
+ file->connect("file_selected", this, "_dialog_action");
+ frame->connect("value_changed", this, "_seek_value_changed", Vector<Variant>(), true);
+ scale->connect("text_entered", this, "_scale_changed", Vector<Variant>(), true);
-
- renaming=false;
- last_active=false;
+ renaming = false;
+ last_active = false;
set_process_unhandled_key_input(true);
- key_editor = memnew( AnimationKeyEditor);
+ key_editor = memnew(AnimationKeyEditor);
add_child(key_editor);
- add_constant_override("separation",get_constant("separation","VBoxContainer"));
+ add_constant_override("separation", get_constant("separation", "VBoxContainer"));
key_editor->set_v_size_flags(SIZE_EXPAND_FILL);
- key_editor->connect("timeline_changed",this,"_animation_key_editor_seek");
- key_editor->connect("animation_len_changed",this,"_animation_key_editor_anim_len_changed");
- key_editor->connect("animation_step_changed",this,"_animation_key_editor_anim_step_changed");
+ key_editor->connect("timeline_changed", this, "_animation_key_editor_seek");
+ key_editor->connect("animation_len_changed", this, "_animation_key_editor_anim_len_changed");
+ key_editor->connect("animation_step_changed", this, "_animation_key_editor_anim_step_changed");
_update_player();
}
-
void AnimationPlayerEditorPlugin::edit(Object *p_object) {
anim_editor->set_undo_redo(&get_undo_redo());
if (!p_object)
return;
anim_editor->edit(p_object->cast_to<AnimationPlayer>());
-
-
}
bool AnimationPlayerEditorPlugin::handles(Object *p_object) const {
@@ -1575,16 +1485,15 @@ void AnimationPlayerEditorPlugin::make_visible(bool p_visible) {
//anim_editor->hide();
//anim_editor->set_idle_process(false);
}
-
}
AnimationPlayerEditorPlugin::AnimationPlayerEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- anim_editor = memnew( AnimationPlayerEditor(editor) );
+ editor = p_node;
+ anim_editor = memnew(AnimationPlayerEditor(editor));
anim_editor->set_undo_redo(editor->get_undo_redo());
- editor->add_bottom_panel_item(TTR("Animation"),anim_editor);
+ editor->add_bottom_panel_item(TTR("Animation"), anim_editor);
/*
editor->get_viewport()->add_child(anim_editor);
anim_editor->set_area_as_parent_rect();
@@ -1593,12 +1502,7 @@ AnimationPlayerEditorPlugin::AnimationPlayerEditorPlugin(EditorNode *p_node) {
anim_editor->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END);
anim_editor->set_margin( MARGIN_RIGHT, 0 );*/
anim_editor->hide();
-
-
-
}
-
-AnimationPlayerEditorPlugin::~AnimationPlayerEditorPlugin()
-{
+AnimationPlayerEditorPlugin::~AnimationPlayerEditorPlugin() {
}
diff --git a/editor/plugins/animation_player_editor_plugin.h b/editor/plugins/animation_player_editor_plugin.h
index d9b6ad52ff..0eee4afcd4 100644
--- a/editor/plugins/animation_player_editor_plugin.h
+++ b/editor/plugins/animation_player_editor_plugin.h
@@ -29,14 +29,13 @@
#ifndef ANIMATION_PLAYER_EDITOR_PLUGIN_H
#define ANIMATION_PLAYER_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/animation/animation_player.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/texture_button.h"
#include "scene/gui/slider.h"
#include "scene/gui/spin_box.h"
-
+#include "scene/gui/texture_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -44,7 +43,7 @@
class AnimationKeyEditor;
class AnimationPlayerEditor : public VBoxContainer {
- GDCLASS(AnimationPlayerEditor, VBoxContainer );
+ GDCLASS(AnimationPlayerEditor, VBoxContainer);
EditorNode *editor;
AnimationPlayer *player;
@@ -65,7 +64,6 @@ class AnimationPlayerEditor : public VBoxContainer {
RESOURCE_SAVE
};
-
OptionButton *animation;
Button *stop;
Button *play;
@@ -97,30 +95,27 @@ class AnimationPlayerEditor : public VBoxContainer {
EditorFileDialog *file;
AcceptDialog *accept;
- ConfirmationDialog* delete_dialog;
+ ConfirmationDialog *delete_dialog;
int current_option;
struct BlendEditor {
- AcceptDialog * dialog;
+ AcceptDialog *dialog;
Tree *tree;
OptionButton *next;
} blend_editor;
-
ConfirmationDialog *name_dialog;
ConfirmationDialog *error_dialog;
bool renaming;
-
bool updating;
bool updating_blends;
AnimationKeyEditor *key_editor;
-
- void _select_anim_by_name(const String& p_anim);
+ void _select_anim_by_name(const String &p_anim);
void _play_pressed();
void _play_from_pressed();
void _play_bw_pressed();
@@ -134,9 +129,9 @@ class AnimationPlayerEditor : public VBoxContainer {
void _animation_name_edited();
void _animation_load();
- void _animation_save_in_path(const Ref<Resource>& p_resource, const String& p_path);
- void _animation_save(const Ref<Resource>& p_resource);
- void _animation_save_as(const Ref<Resource>& p_resource);
+ void _animation_save_in_path(const Ref<Resource> &p_resource, const String &p_path);
+ void _animation_save(const Ref<Resource> &p_resource);
+ void _animation_save_as(const Ref<Resource> &p_resource);
void _animation_remove();
void _animation_remove_confirmed();
@@ -144,10 +139,10 @@ class AnimationPlayerEditor : public VBoxContainer {
void _animation_edit();
void _animation_duplicate();
void _animation_resource_edit();
- void _scale_changed(const String& p_scale);
+ void _scale_changed(const String &p_scale);
void _dialog_action(String p_file);
- void _seek_frame_changed(const String& p_frame);
- void _seek_value_changed(float p_value, bool p_set=false);
+ void _seek_frame_changed(const String &p_frame);
+ void _seek_value_changed(float p_value, bool p_set = false);
void _blend_editor_next_changed(const int p_idx);
void _list_changed();
@@ -155,7 +150,6 @@ class AnimationPlayerEditor : public VBoxContainer {
void _update_player();
void _blend_edited();
-
void _hide_anim_editors();
void _animation_player_changed(Object *p_pl);
@@ -164,46 +158,43 @@ class AnimationPlayerEditor : public VBoxContainer {
void _animation_key_editor_anim_len_changed(float p_new);
void _animation_key_editor_anim_step_changed(float p_len);
- void _unhandled_key_input(const InputEvent& p_ev);
+ void _unhandled_key_input(const InputEvent &p_ev);
void _animation_tool_menu(int p_option);
void _animation_save_menu(int p_option);
-
AnimationPlayerEditor();
-protected:
+protected:
void _notification(int p_what);
void _gui_input(InputEvent p_event);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
+public:
AnimationPlayer *get_player() const;
static AnimationPlayerEditor *singleton;
- AnimationKeyEditor* get_key_editor() { return key_editor; }
+ AnimationKeyEditor *get_key_editor() { return key_editor; }
Dictionary get_state() const;
- void set_state(const Dictionary& p_state);
-
+ void set_state(const Dictionary &p_state);
void ensure_visibility();
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo=p_undo_redo; }
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
void edit(AnimationPlayer *p_player);
AnimationPlayerEditor(EditorNode *p_editor);
};
class AnimationPlayerEditorPlugin : public EditorPlugin {
- GDCLASS( AnimationPlayerEditorPlugin, EditorPlugin );
+ GDCLASS(AnimationPlayerEditorPlugin, EditorPlugin);
AnimationPlayerEditor *anim_editor;
EditorNode *editor;
public:
-
virtual Dictionary get_state() const { return anim_editor->get_state(); }
- virtual void set_state(const Dictionary& p_state) { anim_editor->set_state(p_state); }
+ virtual void set_state(const Dictionary &p_state) { anim_editor->set_state(p_state); }
virtual String get_name() const { return "Anim"; }
bool has_main_screen() const { return false; }
@@ -213,7 +204,6 @@ public:
AnimationPlayerEditorPlugin(EditorNode *p_node);
~AnimationPlayerEditorPlugin();
-
};
#endif // ANIMATION_PLAYER_EDITOR_PLUGIN_H
diff --git a/editor/plugins/animation_tree_editor_plugin.cpp b/editor/plugins/animation_tree_editor_plugin.cpp
index 988136d475..7800fde7a8 100644
--- a/editor/plugins/animation_tree_editor_plugin.cpp
+++ b/editor/plugins/animation_tree_editor_plugin.cpp
@@ -28,18 +28,17 @@
/*************************************************************************/
#include "animation_tree_editor_plugin.h"
-#include "scene/gui/menu_button.h"
-#include "scene/gui/panel.h"
-#include "scene/main/viewport.h"
-#include "core/io/resource_loader.h"
#include "core/global_config.h"
+#include "core/io/resource_loader.h"
#include "os/input.h"
#include "os/keyboard.h"
+#include "scene/gui/menu_button.h"
+#include "scene/gui/panel.h"
+#include "scene/main/viewport.h"
-void AnimationTreeEditor::edit(AnimationTreePlayer* p_anim_tree) {
-
+void AnimationTreeEditor::edit(AnimationTreePlayer *p_anim_tree) {
- anim_tree=p_anim_tree;
+ anim_tree = p_anim_tree;
if (!anim_tree) {
hide();
@@ -55,59 +54,54 @@ void AnimationTreeEditor::edit(AnimationTreePlayer* p_anim_tree) {
play_button->set_pressed(p_anim_tree->is_active());
//read the orders
}
-
}
Size2 AnimationTreeEditor::_get_maximum_size() {
Size2 max;
- for(List<StringName>::Element *E=order.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = order.front(); E; E = E->next()) {
Point2 pos = anim_tree->node_get_pos(E->get());
- if (click_type==CLICK_NODE && click_node==E->get()) {
+ if (click_type == CLICK_NODE && click_node == E->get()) {
- pos+=click_motion-click_pos;
+ pos += click_motion - click_pos;
}
- pos+=get_node_size(E->get());
- if (pos.x>max.x)
- max.x=pos.x;
- if (pos.y>max.y)
- max.y=pos.y;
-
+ pos += get_node_size(E->get());
+ if (pos.x > max.x)
+ max.x = pos.x;
+ if (pos.y > max.y)
+ max.y = pos.y;
}
return max;
}
+const char *AnimationTreeEditor::_node_type_names[] = { "Output", "Animation", "OneShot", "Mix", "Blend2", "Blend3", "Blend4", "TimeScale", "TimeSeek", "Transition" };
-const char* AnimationTreeEditor::_node_type_names[]={"Output","Animation","OneShot","Mix","Blend2","Blend3","Blend4","TimeScale","TimeSeek","Transition"};
-
-Size2 AnimationTreeEditor::get_node_size(const StringName& p_node) const {
+Size2 AnimationTreeEditor::get_node_size(const StringName &p_node) const {
- AnimationTreePlayer::NodeType type=anim_tree->node_get_type(p_node);
+ AnimationTreePlayer::NodeType type = anim_tree->node_get_type(p_node);
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- Ref<Font> font = get_font("font","PopupMenu");
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ Ref<Font> font = get_font("font", "PopupMenu");
Size2 size = style->get_minimum_size();
- int count=2; // title and name
+ int count = 2; // title and name
int inputs = anim_tree->node_get_input_count(p_node);
- count += inputs?inputs:1;
+ count += inputs ? inputs : 1;
String name = p_node;
+ float name_w = font->get_string_size(name).width;
+ float type_w = font->get_string_size(String(_node_type_names[type])).width;
+ float max_w = MAX(name_w, type_w);
- float name_w = font->get_string_size( name ).width;
- float type_w = font->get_string_size( String(_node_type_names[type]) ).width;
- float max_w=MAX(name_w,type_w);
-
-
-
- switch(type) {
+ switch (type) {
case AnimationTreePlayer::NODE_TIMESEEK:
- case AnimationTreePlayer::NODE_OUTPUT: {} break;
+ case AnimationTreePlayer::NODE_OUTPUT: {
+ } break;
case AnimationTreePlayer::NODE_ANIMATION:
case AnimationTreePlayer::NODE_ONESHOT:
case AnimationTreePlayer::NODE_MIX:
@@ -117,19 +111,18 @@ Size2 AnimationTreeEditor::get_node_size(const StringName& p_node) const {
case AnimationTreePlayer::NODE_TIMESCALE:
case AnimationTreePlayer::NODE_TRANSITION: {
-
- size.height+=font->get_height();
+ size.height += font->get_height();
} break;
- case AnimationTreePlayer::NODE_MAX: {}
+ case AnimationTreePlayer::NODE_MAX: {
+ }
}
- size.x+=max_w+20;
- size.y+=count*(font->get_height()+get_constant("vseparation","PopupMenu"));
+ size.x += max_w + 20;
+ size.y += count * (font->get_height() + get_constant("vseparation", "PopupMenu"));
return size;
}
-
void AnimationTreeEditor::_edit_dialog_changede(String) {
edit_dialog->hide();
@@ -152,69 +145,67 @@ void AnimationTreeEditor::_edit_dialog_changed() {
if (renaming_edit) {
- if (anim_tree->node_rename(edited_node,edit_line[0]->get_text())==OK) {
- for(List<StringName>::Element* E=order.front();E;E=E->next()) {
+ if (anim_tree->node_rename(edited_node, edit_line[0]->get_text()) == OK) {
+ for (List<StringName>::Element *E = order.front(); E; E = E->next()) {
if (E->get() == edited_node)
- E->get()=edit_line[0]->get_text();
+ E->get() = edit_line[0]->get_text();
}
- edited_node=edit_line[0]->get_text();
+ edited_node = edit_line[0]->get_text();
}
update();
return;
}
- AnimationTreePlayer::NodeType type=anim_tree->node_get_type(edited_node);
+ AnimationTreePlayer::NodeType type = anim_tree->node_get_type(edited_node);
- switch(type) {
+ switch (type) {
- case AnimationTreePlayer::NODE_TIMESCALE:
- anim_tree->timescale_node_set_scale(edited_node,edit_line[0]->get_text().to_double());
+ case AnimationTreePlayer::NODE_TIMESCALE:
+ anim_tree->timescale_node_set_scale(edited_node, edit_line[0]->get_text().to_double());
break;
- case AnimationTreePlayer::NODE_ONESHOT:
- anim_tree->oneshot_node_set_fadein_time(edited_node,edit_line[0]->get_text().to_double());
- anim_tree->oneshot_node_set_fadeout_time(edited_node,edit_line[1]->get_text().to_double());
- anim_tree->oneshot_node_set_autorestart_delay(edited_node,edit_line[2]->get_text().to_double());
- anim_tree->oneshot_node_set_autorestart_random_delay(edited_node,edit_line[3]->get_text().to_double());
- anim_tree->oneshot_node_set_autorestart(edited_node,edit_check->is_pressed());
- anim_tree->oneshot_node_set_mix_mode(edited_node,edit_option->get_selected());
+ case AnimationTreePlayer::NODE_ONESHOT:
+ anim_tree->oneshot_node_set_fadein_time(edited_node, edit_line[0]->get_text().to_double());
+ anim_tree->oneshot_node_set_fadeout_time(edited_node, edit_line[1]->get_text().to_double());
+ anim_tree->oneshot_node_set_autorestart_delay(edited_node, edit_line[2]->get_text().to_double());
+ anim_tree->oneshot_node_set_autorestart_random_delay(edited_node, edit_line[3]->get_text().to_double());
+ anim_tree->oneshot_node_set_autorestart(edited_node, edit_check->is_pressed());
+ anim_tree->oneshot_node_set_mix_mode(edited_node, edit_option->get_selected());
break;
- case AnimationTreePlayer::NODE_MIX:
+ case AnimationTreePlayer::NODE_MIX:
- anim_tree->mix_node_set_amount(edited_node,edit_scroll[0]->get_value());
- break;
- case AnimationTreePlayer::NODE_BLEND2:
- anim_tree->blend2_node_set_amount(edited_node,edit_scroll[0]->get_value());
+ anim_tree->mix_node_set_amount(edited_node, edit_scroll[0]->get_value());
+ break;
+ case AnimationTreePlayer::NODE_BLEND2:
+ anim_tree->blend2_node_set_amount(edited_node, edit_scroll[0]->get_value());
- break;
+ break;
- case AnimationTreePlayer::NODE_BLEND3:
- anim_tree->blend3_node_set_amount(edited_node,edit_scroll[0]->get_value());
+ case AnimationTreePlayer::NODE_BLEND3:
+ anim_tree->blend3_node_set_amount(edited_node, edit_scroll[0]->get_value());
- break;
+ break;
case AnimationTreePlayer::NODE_BLEND4:
- anim_tree->blend4_node_set_amount(edited_node,Point2(edit_scroll[0]->get_value(),edit_scroll[1]->get_value()));
+ anim_tree->blend4_node_set_amount(edited_node, Point2(edit_scroll[0]->get_value(), edit_scroll[1]->get_value()));
break;
- case AnimationTreePlayer::NODE_TRANSITION: {
- anim_tree->transition_node_set_xfade_time(edited_node,edit_line[0]->get_text().to_double());
- if (anim_tree->transition_node_get_current(edited_node)!=edit_option->get_selected())
- anim_tree->transition_node_set_current(edited_node,edit_option->get_selected());
+ case AnimationTreePlayer::NODE_TRANSITION: {
+ anim_tree->transition_node_set_xfade_time(edited_node, edit_line[0]->get_text().to_double());
+ if (anim_tree->transition_node_get_current(edited_node) != edit_option->get_selected())
+ anim_tree->transition_node_set_current(edited_node, edit_option->get_selected());
} break;
default: {}
}
-
}
void AnimationTreeEditor::_edit_dialog_animation_changed() {
-
Ref<Animation> anim = property_editor->get_variant().operator RefPtr();
- anim_tree->animation_node_set_animation(edited_node,anim);
+ anim_tree->animation_node_set_animation(edited_node, anim);
update();
}
@@ -235,26 +226,26 @@ void AnimationTreeEditor::_play_toggled() {
anim_tree->set_active(play_button->is_pressed());
}
-
void AnimationTreeEditor::_master_anim_menu_item(int p_item) {
- if(p_item == 0) _edit_filters();
+ if (p_item == 0)
+ _edit_filters();
else {
String str = master_anim_popup->get_item_text(p_item);
- anim_tree->animation_node_set_master_animation(edited_node,str);
+ anim_tree->animation_node_set_master_animation(edited_node, str);
}
update();
}
void AnimationTreeEditor::_popup_edit_dialog() {
- updating_edit=true;
+ updating_edit = true;
- for(int i=0;i<2;i++)
+ for (int i = 0; i < 2; i++)
edit_scroll[i]->hide();
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
edit_line[i]->hide();
edit_label[i]->hide();
@@ -265,32 +256,31 @@ void AnimationTreeEditor::_popup_edit_dialog() {
filter_button->hide();
edit_check->hide();
- Point2 pos = anim_tree->node_get_pos(edited_node)-Point2(h_scroll->get_value(),v_scroll->get_value());
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
+ Point2 pos = anim_tree->node_get_pos(edited_node) - Point2(h_scroll->get_value(), v_scroll->get_value());
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
Size2 size = get_node_size(edited_node);
- Point2 popup_pos( pos.x+style->get_margin(MARGIN_LEFT), pos.y+size.y-style->get_margin(MARGIN_BOTTOM));
- popup_pos+=get_global_pos();
+ Point2 popup_pos(pos.x + style->get_margin(MARGIN_LEFT), pos.y + size.y - style->get_margin(MARGIN_BOTTOM));
+ popup_pos += get_global_pos();
if (renaming_edit) {
edit_label[0]->set_text(TTR("New name:"));
- edit_label[0]->set_pos(Point2(5,5));
+ edit_label[0]->set_pos(Point2(5, 5));
edit_label[0]->show();
- edit_line[0]->set_begin(Point2(15,25));
+ edit_line[0]->set_begin(Point2(15, 25));
edit_line[0]->set_text(edited_node);
edit_line[0]->show();
- edit_dialog->set_size(Size2(150,50));
+ edit_dialog->set_size(Size2(150, 50));
} else {
- AnimationTreePlayer::NodeType type=anim_tree->node_get_type(edited_node);
+ AnimationTreePlayer::NodeType type = anim_tree->node_get_type(edited_node);
-
- switch(type) {
+ switch (type) {
case AnimationTreePlayer::NODE_ANIMATION:
- if (anim_tree->get_master_player()!=NodePath() && anim_tree->has_node(anim_tree->get_master_player()) && anim_tree->get_node(anim_tree->get_master_player())->cast_to<AnimationPlayer>()) {
+ if (anim_tree->get_master_player() != NodePath() && anim_tree->has_node(anim_tree->get_master_player()) && anim_tree->get_node(anim_tree->get_master_player())->cast_to<AnimationPlayer>()) {
AnimationPlayer *ap = anim_tree->get_node(anim_tree->get_master_player())->cast_to<AnimationPlayer>();
master_anim_popup->clear();
@@ -299,302 +289,293 @@ void AnimationTreeEditor::_popup_edit_dialog() {
List<StringName> sn;
ap->get_animation_list(&sn);
sn.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *E=sn.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
master_anim_popup->add_item(E->get());
}
master_anim_popup->set_pos(popup_pos);
master_anim_popup->popup();
} else {
- property_editor->edit(this,"",Variant::OBJECT,anim_tree->animation_node_get_animation(edited_node),PROPERTY_HINT_RESOURCE_TYPE,"Animation");
+ property_editor->edit(this, "", Variant::OBJECT, anim_tree->animation_node_get_animation(edited_node), PROPERTY_HINT_RESOURCE_TYPE, "Animation");
property_editor->set_pos(popup_pos);
property_editor->popup();
- updating_edit=false;
+ updating_edit = false;
}
return;
- case AnimationTreePlayer::NODE_TIMESCALE:
+ case AnimationTreePlayer::NODE_TIMESCALE:
edit_label[0]->set_text(TTR("Scale:"));
- edit_label[0]->set_pos(Point2(5,5));
+ edit_label[0]->set_pos(Point2(5, 5));
edit_label[0]->show();
- edit_line[0]->set_begin(Point2(15,25));
+ edit_line[0]->set_begin(Point2(15, 25));
edit_line[0]->set_text(rtos(anim_tree->timescale_node_get_scale(edited_node)));
edit_line[0]->show();
- edit_dialog->set_size(Size2(150,50));
+ edit_dialog->set_size(Size2(150, 50));
break;
- case AnimationTreePlayer::NODE_ONESHOT:
+ case AnimationTreePlayer::NODE_ONESHOT:
edit_label[0]->set_text(TTR("Fade In (s):"));
- edit_label[0]->set_pos(Point2(5,5));
+ edit_label[0]->set_pos(Point2(5, 5));
edit_label[0]->show();
- edit_line[0]->set_begin(Point2(15,25));
+ edit_line[0]->set_begin(Point2(15, 25));
edit_line[0]->set_text(rtos(anim_tree->oneshot_node_get_fadein_time(edited_node)));
edit_line[0]->show();
edit_label[1]->set_text(TTR("Fade Out (s):"));
- edit_label[1]->set_pos(Point2(5,55));
+ edit_label[1]->set_pos(Point2(5, 55));
edit_label[1]->show();
- edit_line[1]->set_begin(Point2(15,75));
+ edit_line[1]->set_begin(Point2(15, 75));
edit_line[1]->set_text(rtos(anim_tree->oneshot_node_get_fadeout_time(edited_node)));
edit_line[1]->show();
edit_option->clear();
- edit_option->add_item(TTR("Blend"),0);
- edit_option->add_item(TTR("Mix"),1);
- edit_option->set_begin(Point2(15,105));
+ edit_option->add_item(TTR("Blend"), 0);
+ edit_option->add_item(TTR("Mix"), 1);
+ edit_option->set_begin(Point2(15, 105));
- edit_option->select( anim_tree->oneshot_node_get_mix_mode(edited_node));
+ edit_option->select(anim_tree->oneshot_node_get_mix_mode(edited_node));
edit_option->show();
edit_check->set_text(TTR("Auto Restart:"));
- edit_check->set_begin(Point2(15,125));
+ edit_check->set_begin(Point2(15, 125));
edit_check->set_pressed(anim_tree->oneshot_node_has_autorestart(edited_node));
edit_check->show();
edit_label[2]->set_text(TTR("Restart (s):"));
- edit_label[2]->set_pos(Point2(5,145));
+ edit_label[2]->set_pos(Point2(5, 145));
edit_label[2]->show();
- edit_line[2]->set_begin(Point2(15,165));
+ edit_line[2]->set_begin(Point2(15, 165));
edit_line[2]->set_text(rtos(anim_tree->oneshot_node_get_autorestart_delay(edited_node)));
edit_line[2]->show();
edit_label[3]->set_text(TTR("Random Restart (s):"));
- edit_label[3]->set_pos(Point2(5,195));
+ edit_label[3]->set_pos(Point2(5, 195));
edit_label[3]->show();
- edit_line[3]->set_begin(Point2(15,215));
+ edit_line[3]->set_begin(Point2(15, 215));
edit_line[3]->set_text(rtos(anim_tree->oneshot_node_get_autorestart_random_delay(edited_node)));
edit_line[3]->show();
- filter_button->set_begin(Point2(10,245));
+ filter_button->set_begin(Point2(10, 245));
filter_button->show();
- edit_button->set_begin(Point2(10,268));
+ edit_button->set_begin(Point2(10, 268));
edit_button->set_text(TTR("Start!"));
edit_button->show();
- edit_dialog->set_size(Size2(180,293));
+ edit_dialog->set_size(Size2(180, 293));
+
+ break;
+
+ case AnimationTreePlayer::NODE_MIX:
+
+ edit_label[0]->set_text(TTR("Amount:"));
+ edit_label[0]->set_pos(Point2(5, 5));
+ edit_label[0]->show();
+ edit_scroll[0]->set_min(0);
+ edit_scroll[0]->set_max(1);
+ edit_scroll[0]->set_value(anim_tree->mix_node_get_amount(edited_node));
+ edit_scroll[0]->set_begin(Point2(15, 25));
+ edit_scroll[0]->show();
+ edit_dialog->set_size(Size2(150, 50));
break;
+ case AnimationTreePlayer::NODE_BLEND2:
+ edit_label[0]->set_text(TTR("Blend:"));
+ edit_label[0]->set_pos(Point2(5, 5));
+ edit_label[0]->show();
+ edit_scroll[0]->set_min(0);
+ edit_scroll[0]->set_max(1);
+ edit_scroll[0]->set_value(anim_tree->blend2_node_get_amount(edited_node));
+ edit_scroll[0]->set_begin(Point2(15, 25));
+ edit_scroll[0]->show();
+ filter_button->set_begin(Point2(10, 47));
+ filter_button->show();
+ edit_dialog->set_size(Size2(150, 74));
- case AnimationTreePlayer::NODE_MIX:
-
- edit_label[0]->set_text(TTR("Amount:"));
- edit_label[0]->set_pos(Point2(5,5));
- edit_label[0]->show();
- edit_scroll[0]->set_min(0);
- edit_scroll[0]->set_max(1);
- edit_scroll[0]->set_value(anim_tree->mix_node_get_amount(edited_node));
- edit_scroll[0]->set_begin(Point2(15,25));
- edit_scroll[0]->show();
- edit_dialog->set_size(Size2(150,50));
-
- break;
- case AnimationTreePlayer::NODE_BLEND2:
- edit_label[0]->set_text(TTR("Blend:"));
- edit_label[0]->set_pos(Point2(5,5));
- edit_label[0]->show();
- edit_scroll[0]->set_min(0);
- edit_scroll[0]->set_max(1);
- edit_scroll[0]->set_value(anim_tree->blend2_node_get_amount(edited_node));
- edit_scroll[0]->set_begin(Point2(15,25));
- edit_scroll[0]->show();
- filter_button->set_begin(Point2(10,47));
- filter_button->show();
- edit_dialog->set_size(Size2(150,74));
-
- break;
-
- case AnimationTreePlayer::NODE_BLEND3:
- edit_label[0]->set_text(TTR("Blend:"));
- edit_label[0]->set_pos(Point2(5,5));
- edit_label[0]->show();
- edit_scroll[0]->set_min(-1);
- edit_scroll[0]->set_max(1);
- edit_scroll[0]->set_value(anim_tree->blend3_node_get_amount(edited_node));
- edit_scroll[0]->set_begin(Point2(15,25));
- edit_scroll[0]->show();
- edit_dialog->set_size(Size2(150,50));
-
- break;
+ break;
+
+ case AnimationTreePlayer::NODE_BLEND3:
+ edit_label[0]->set_text(TTR("Blend:"));
+ edit_label[0]->set_pos(Point2(5, 5));
+ edit_label[0]->show();
+ edit_scroll[0]->set_min(-1);
+ edit_scroll[0]->set_max(1);
+ edit_scroll[0]->set_value(anim_tree->blend3_node_get_amount(edited_node));
+ edit_scroll[0]->set_begin(Point2(15, 25));
+ edit_scroll[0]->show();
+ edit_dialog->set_size(Size2(150, 50));
+
+ break;
case AnimationTreePlayer::NODE_BLEND4:
edit_label[0]->set_text(TTR("Blend 0:"));
- edit_label[0]->set_pos(Point2(5,5));
+ edit_label[0]->set_pos(Point2(5, 5));
edit_label[0]->show();
edit_scroll[0]->set_min(0);
edit_scroll[0]->set_max(1);
edit_scroll[0]->set_value(anim_tree->blend4_node_get_amount(edited_node).x);
- edit_scroll[0]->set_begin(Point2(15,25));
+ edit_scroll[0]->set_begin(Point2(15, 25));
edit_scroll[0]->show();
edit_label[1]->set_text(TTR("Blend 1:"));
- edit_label[1]->set_pos(Point2(5,55));
+ edit_label[1]->set_pos(Point2(5, 55));
edit_label[1]->show();
edit_scroll[1]->set_min(0);
edit_scroll[1]->set_max(1);
edit_scroll[1]->set_value(anim_tree->blend4_node_get_amount(edited_node).y);
- edit_scroll[1]->set_begin(Point2(15,75));
+ edit_scroll[1]->set_begin(Point2(15, 75));
edit_scroll[1]->show();
- edit_dialog->set_size(Size2(150,100));
+ edit_dialog->set_size(Size2(150, 100));
break;
- case AnimationTreePlayer::NODE_TRANSITION: {
-
+ case AnimationTreePlayer::NODE_TRANSITION: {
- edit_label[0]->set_text(TTR("X-Fade Time (s):"));
- edit_label[0]->set_pos(Point2(5,5));
- edit_label[0]->show();
- edit_line[0]->set_begin(Point2(15,25));
- edit_line[0]->set_text(rtos(anim_tree->transition_node_get_xfade_time(edited_node)));
- edit_line[0]->show();
+ edit_label[0]->set_text(TTR("X-Fade Time (s):"));
+ edit_label[0]->set_pos(Point2(5, 5));
+ edit_label[0]->show();
+ edit_line[0]->set_begin(Point2(15, 25));
+ edit_line[0]->set_text(rtos(anim_tree->transition_node_get_xfade_time(edited_node)));
+ edit_line[0]->show();
- edit_label[1]->set_text(TTR("Current:"));
- edit_label[1]->set_pos(Point2(5,55));
- edit_label[1]->show();
- edit_option->set_begin(Point2(15,75));
+ edit_label[1]->set_text(TTR("Current:"));
+ edit_label[1]->set_pos(Point2(5, 55));
+ edit_label[1]->show();
+ edit_option->set_begin(Point2(15, 75));
- edit_option->clear();
+ edit_option->clear();
- for(int i=0;i<anim_tree->transition_node_get_input_count(edited_node);i++) {
- edit_option->add_item(itos(i),i);
- }
+ for (int i = 0; i < anim_tree->transition_node_get_input_count(edited_node); i++) {
+ edit_option->add_item(itos(i), i);
+ }
- edit_option->select(anim_tree->transition_node_get_current(edited_node));
- edit_option->show();
- edit_dialog->set_size(Size2(150,100));
+ edit_option->select(anim_tree->transition_node_get_current(edited_node));
+ edit_option->show();
+ edit_dialog->set_size(Size2(150, 100));
} break;
default: {}
-
}
-
}
-
-
edit_dialog->set_pos(popup_pos);
edit_dialog->popup();
- updating_edit=false;
+ updating_edit = false;
}
-void AnimationTreeEditor::_draw_node(const StringName& p_node) {
+void AnimationTreeEditor::_draw_node(const StringName &p_node) {
RID ci = get_canvas_item();
- AnimationTreePlayer::NodeType type=anim_tree->node_get_type(p_node);
-
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- Ref<Font> font = get_font("font","PopupMenu");
- Color font_color = get_color("font_color","PopupMenu");
- Color font_color_title = get_color("font_color_hover","PopupMenu");
- font_color_title.a*=0.8;
- Ref<Texture> slot_icon = get_icon("NodeRealSlot","EditorIcons");
+ AnimationTreePlayer::NodeType type = anim_tree->node_get_type(p_node);
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ Ref<Font> font = get_font("font", "PopupMenu");
+ Color font_color = get_color("font_color", "PopupMenu");
+ Color font_color_title = get_color("font_color_hover", "PopupMenu");
+ font_color_title.a *= 0.8;
+ Ref<Texture> slot_icon = get_icon("NodeRealSlot", "EditorIcons");
- Size2 size=get_node_size(p_node);
+ Size2 size = get_node_size(p_node);
Point2 pos = anim_tree->node_get_pos(p_node);
- if (click_type==CLICK_NODE && click_node==p_node) {
-
- pos+=click_motion-click_pos;
- if (pos.x<5)
- pos.x=5;
- if (pos.y<5)
- pos.y=5;
+ if (click_type == CLICK_NODE && click_node == p_node) {
+ pos += click_motion - click_pos;
+ if (pos.x < 5)
+ pos.x = 5;
+ if (pos.y < 5)
+ pos.y = 5;
}
- pos-=Point2(h_scroll->get_value(),v_scroll->get_value());
+ pos -= Point2(h_scroll->get_value(), v_scroll->get_value());
- style->draw(ci,Rect2(pos,size));
+ style->draw(ci, Rect2(pos, size));
- float w = size.width-style->get_minimum_size().width;
- float h = font->get_height()+get_constant("vseparation","PopupMenu");
+ float w = size.width - style->get_minimum_size().width;
+ float h = font->get_height() + get_constant("vseparation", "PopupMenu");
- Point2 ofs=style->get_offset()+pos;
- Point2 ascofs(0,font->get_ascent());
+ Point2 ofs = style->get_offset() + pos;
+ Point2 ascofs(0, font->get_ascent());
Color bx = font_color_title;
- bx.a*=0.1;
- draw_rect(Rect2(ofs,Size2(size.width-style->get_minimum_size().width,font->get_height())),bx);
- font->draw_halign(ci,ofs+ascofs,HALIGN_CENTER,w,String(_node_type_names[type]),font_color_title);
+ bx.a *= 0.1;
+ draw_rect(Rect2(ofs, Size2(size.width - style->get_minimum_size().width, font->get_height())), bx);
+ font->draw_halign(ci, ofs + ascofs, HALIGN_CENTER, w, String(_node_type_names[type]), font_color_title);
- ofs.y+=h;
- font->draw_halign(ci,ofs+ascofs,HALIGN_CENTER,w,p_node,font_color);
- ofs.y+=h;
+ ofs.y += h;
+ font->draw_halign(ci, ofs + ascofs, HALIGN_CENTER, w, p_node, font_color);
+ ofs.y += h;
- int count=2; // title and name
+ int count = 2; // title and name
int inputs = anim_tree->node_get_input_count(p_node);
- count += inputs?inputs:1;
+ count += inputs ? inputs : 1;
- float icon_h_ofs = Math::floor(( font->get_height()-slot_icon->get_height())/2.0 )+1;
+ float icon_h_ofs = Math::floor((font->get_height() - slot_icon->get_height()) / 2.0) + 1;
- if (type!=AnimationTreePlayer::NODE_OUTPUT)
- slot_icon->draw(ci,ofs+Point2(w,icon_h_ofs)); //output
+ if (type != AnimationTreePlayer::NODE_OUTPUT)
+ slot_icon->draw(ci, ofs + Point2(w, icon_h_ofs)); //output
if (inputs) {
- for(int i=0;i<inputs;i++) {
+ for (int i = 0; i < inputs; i++) {
- slot_icon->draw(ci,ofs+Point2(-slot_icon->get_width(),icon_h_ofs));
+ slot_icon->draw(ci, ofs + Point2(-slot_icon->get_width(), icon_h_ofs));
String text;
- switch(type) {
-
- case AnimationTreePlayer::NODE_TIMESCALE:
- case AnimationTreePlayer::NODE_TIMESEEK: text="in"; break;
- case AnimationTreePlayer::NODE_OUTPUT: text="out"; break;
- case AnimationTreePlayer::NODE_ANIMATION: break;
- case AnimationTreePlayer::NODE_ONESHOT: text=(i==0?"in":"add"); break;
- case AnimationTreePlayer::NODE_BLEND2:
- case AnimationTreePlayer::NODE_MIX: text=(i==0?"a":"b"); break;
- case AnimationTreePlayer::NODE_BLEND3:
- switch(i) {
- case 0: text="b-"; break;
- case 1: text="a"; break;
- case 2: text="b+"; break;
-
- }
- break;
-
-
- case AnimationTreePlayer::NODE_BLEND4:
- switch(i) {
- case 0: text="a0"; break;
- case 1: text="b0"; break;
- case 2: text="a1"; break;
- case 3: text="b1"; break;
- }
- break;
-
- case AnimationTreePlayer::NODE_TRANSITION:
- text=itos(i);
- if (anim_tree->transition_node_has_input_auto_advance(p_node,i))
- text+="->";
-
- break;
- default: {}
+ switch (type) {
+
+ case AnimationTreePlayer::NODE_TIMESCALE:
+ case AnimationTreePlayer::NODE_TIMESEEK: text = "in"; break;
+ case AnimationTreePlayer::NODE_OUTPUT: text = "out"; break;
+ case AnimationTreePlayer::NODE_ANIMATION: break;
+ case AnimationTreePlayer::NODE_ONESHOT: text = (i == 0 ? "in" : "add"); break;
+ case AnimationTreePlayer::NODE_BLEND2:
+ case AnimationTreePlayer::NODE_MIX: text = (i == 0 ? "a" : "b"); break;
+ case AnimationTreePlayer::NODE_BLEND3:
+ switch (i) {
+ case 0: text = "b-"; break;
+ case 1: text = "a"; break;
+ case 2: text = "b+"; break;
+ }
+ break;
+
+ case AnimationTreePlayer::NODE_BLEND4:
+ switch (i) {
+ case 0: text = "a0"; break;
+ case 1: text = "b0"; break;
+ case 2: text = "a1"; break;
+ case 3: text = "b1"; break;
+ }
+ break;
+
+ case AnimationTreePlayer::NODE_TRANSITION:
+ text = itos(i);
+ if (anim_tree->transition_node_has_input_auto_advance(p_node, i))
+ text += "->";
+
+ break;
+ default: {}
}
- font->draw(ci,ofs+ascofs+Point2(3,0),text,font_color);
+ font->draw(ci, ofs + ascofs + Point2(3, 0), text, font_color);
- ofs.y+=h;
+ ofs.y += h;
}
} else {
- ofs.y+=h;
+ ofs.y += h;
}
- Ref<StyleBox> pg_bg=get_stylebox("bg","ProgressBar");
- Ref<StyleBox> pg_fill=get_stylebox("fill","ProgressBar");
- Rect2 pg_rect(ofs,Size2(w,h));
+ Ref<StyleBox> pg_bg = get_stylebox("bg", "ProgressBar");
+ Ref<StyleBox> pg_fill = get_stylebox("fill", "ProgressBar");
+ Rect2 pg_rect(ofs, Size2(w, h));
- bool editable=true;
- switch(type) {
+ bool editable = true;
+ switch (type) {
case AnimationTreePlayer::NODE_ANIMATION: {
Ref<Animation> anim = anim_tree->animation_node_get_animation(p_node);
String text;
- if (anim_tree->animation_node_get_master_animation(p_node)!="")
- text=anim_tree->animation_node_get_master_animation(p_node);
+ if (anim_tree->animation_node_get_master_animation(p_node) != "")
+ text = anim_tree->animation_node_get_master_animation(p_node);
else if (anim.is_null())
- text="load..";
+ text = "load..";
else
- text=anim->get_name();
+ text = anim->get_name();
- font->draw_halign(ci,ofs+ascofs,HALIGN_CENTER,w,text,font_color_title);
+ font->draw_halign(ci, ofs + ascofs, HALIGN_CENTER, w, text, font_color_title);
} break;
case AnimationTreePlayer::NODE_ONESHOT:
@@ -605,16 +586,16 @@ void AnimationTreeEditor::_draw_node(const StringName& p_node) {
case AnimationTreePlayer::NODE_TIMESCALE:
case AnimationTreePlayer::NODE_TRANSITION: {
- font->draw_halign(ci,ofs+ascofs,HALIGN_CENTER,w,"edit..",font_color_title);
+ font->draw_halign(ci, ofs + ascofs, HALIGN_CENTER, w, "edit..", font_color_title);
} break;
- default: editable=false;
+ default: editable = false;
}
if (editable) {
- Ref<Texture> arrow = get_icon("arrow","Tree");
- Point2 arrow_ofs( w-arrow->get_width(),Math::floor( (h-arrow->get_height())/2) );
- arrow->draw(ci,ofs+arrow_ofs);
+ Ref<Texture> arrow = get_icon("arrow", "Tree");
+ Point2 arrow_ofs(w - arrow->get_width(), Math::floor((h - arrow->get_height()) / 2));
+ arrow->draw(ci, ofs + arrow_ofs);
}
}
@@ -627,110 +608,104 @@ void AnimationTreeEditor::_node_param_changed() {
}
#endif
-AnimationTreeEditor::ClickType AnimationTreeEditor::_locate_click(const Point2& p_click,StringName *p_node_id,int *p_slot_index) const {
-
+AnimationTreeEditor::ClickType AnimationTreeEditor::_locate_click(const Point2 &p_click, StringName *p_node_id, int *p_slot_index) const {
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- Ref<Font> font = get_font("font","PopupMenu");
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ Ref<Font> font = get_font("font", "PopupMenu");
- float h = (font->get_height()+get_constant("vseparation","PopupMenu"));
+ float h = (font->get_height() + get_constant("vseparation", "PopupMenu"));
- for(const List<StringName>::Element *E=order.back();E;E=E->prev()) {
+ for (const List<StringName>::Element *E = order.back(); E; E = E->prev()) {
StringName node = E->get();
- AnimationTreePlayer::NodeType type=anim_tree->node_get_type(node);
+ AnimationTreePlayer::NodeType type = anim_tree->node_get_type(node);
Point2 pos = anim_tree->node_get_pos(node);
Size2 size = get_node_size(node);
- pos-=Point2(h_scroll->get_value(),v_scroll->get_value());
+ pos -= Point2(h_scroll->get_value(), v_scroll->get_value());
- if (!Rect2(pos,size).has_point(p_click))
+ if (!Rect2(pos, size).has_point(p_click))
continue;
if (p_node_id)
- *p_node_id=node;
+ *p_node_id = node;
- pos=p_click-pos;
+ pos = p_click - pos;
- float y = pos.y-style->get_offset().height;
+ float y = pos.y - style->get_offset().height;
- if (y<2*h)
+ if (y < 2 * h)
return CLICK_NODE;
- y-=2*h;
+ y -= 2 * h;
int inputs = anim_tree->node_get_input_count(node);
- int count = MAX(inputs,1);
+ int count = MAX(inputs, 1);
- if (inputs==0 || (pos.x > size.width/2 && type != AnimationTreePlayer::NODE_OUTPUT)) {
+ if (inputs == 0 || (pos.x > size.width / 2 && type != AnimationTreePlayer::NODE_OUTPUT)) {
- if (y<count*h) {
+ if (y < count * h) {
if (p_slot_index)
- *p_slot_index=0;
+ *p_slot_index = 0;
return CLICK_OUTPUT_SLOT;
}
}
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- if (y<h) {
+ if (y < h) {
if (p_slot_index)
- *p_slot_index=i;
+ *p_slot_index = i;
return CLICK_INPUT_SLOT;
}
- y-=h;
+ y -= h;
}
- bool has_parameters = type!=AnimationTreePlayer::NODE_OUTPUT && type!=AnimationTreePlayer::NODE_TIMESEEK;
+ bool has_parameters = type != AnimationTreePlayer::NODE_OUTPUT && type != AnimationTreePlayer::NODE_TIMESEEK;
return has_parameters ? CLICK_PARAMETER : CLICK_NODE;
}
return CLICK_NONE;
}
-Point2 AnimationTreeEditor::_get_slot_pos(const StringName& p_node,bool p_input,int p_slot) {
+Point2 AnimationTreeEditor::_get_slot_pos(const StringName &p_node, bool p_input, int p_slot) {
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- Ref<Font> font = get_font("font","PopupMenu");
- Ref<Texture> slot_icon = get_icon("NodeRealSlot","EditorIcons");
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ Ref<Font> font = get_font("font", "PopupMenu");
+ Ref<Texture> slot_icon = get_icon("NodeRealSlot", "EditorIcons");
- Size2 size=get_node_size(p_node);
+ Size2 size = get_node_size(p_node);
Point2 pos = anim_tree->node_get_pos(p_node);
- if (click_type==CLICK_NODE && click_node==p_node) {
-
- pos+=click_motion-click_pos;
- if (pos.x<5)
- pos.x=5;
- if (pos.y<5)
- pos.y=5;
+ if (click_type == CLICK_NODE && click_node == p_node) {
+ pos += click_motion - click_pos;
+ if (pos.x < 5)
+ pos.x = 5;
+ if (pos.y < 5)
+ pos.y = 5;
}
- pos-=Point2(h_scroll->get_value(),v_scroll->get_value());
+ pos -= Point2(h_scroll->get_value(), v_scroll->get_value());
+ float w = size.width - style->get_minimum_size().width;
+ float h = font->get_height() + get_constant("vseparation", "PopupMenu");
- float w = size.width-style->get_minimum_size().width;
- float h = font->get_height()+get_constant("vseparation","PopupMenu");
+ pos += style->get_offset();
+ pos.y += h * 2;
- pos+=style->get_offset();
+ pos.y += h * p_slot;
- pos.y+=h*2;
-
- pos.y+=h*p_slot;
-
- pos+=Point2( -slot_icon->get_width()/2.0, h/2.0).floor();
-
- if(!p_input) {
- pos.x+=w+slot_icon->get_width();
+ pos += Point2(-slot_icon->get_width() / 2.0, h / 2.0).floor();
+ if (!p_input) {
+ pos.x += w + slot_icon->get_width();
}
return pos;
-
}
#if 0
@@ -761,123 +736,117 @@ void AnimationTreeEditor::_node_edit_property(const StringName& p_node) {
void AnimationTreeEditor::_gui_input(InputEvent p_event) {
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
if (p_event.mouse_button.pressed) {
-
- if (p_event.mouse_button.button_index==1) {
- click_pos=Point2(p_event.mouse_button.x,p_event.mouse_button.y);
- click_motion=click_pos;
- click_type = _locate_click(click_pos,&click_node,&click_slot);
- if( click_type!=CLICK_NONE) {
+ if (p_event.mouse_button.button_index == 1) {
+ click_pos = Point2(p_event.mouse_button.x, p_event.mouse_button.y);
+ click_motion = click_pos;
+ click_type = _locate_click(click_pos, &click_node, &click_slot);
+ if (click_type != CLICK_NONE) {
order.erase(click_node);
order.push_back(click_node);
update();
}
- switch(click_type) {
+ switch (click_type) {
case CLICK_INPUT_SLOT: {
- click_pos=_get_slot_pos(click_node,true,click_slot);
+ click_pos = _get_slot_pos(click_node, true, click_slot);
} break;
case CLICK_OUTPUT_SLOT: {
- click_pos=_get_slot_pos(click_node,false,click_slot);
+ click_pos = _get_slot_pos(click_node, false, click_slot);
} break;
case CLICK_PARAMETER: {
- edited_node=click_node;
- renaming_edit=false;
+ edited_node = click_node;
+ renaming_edit = false;
_popup_edit_dialog();
//open editor
//_node_edit_property(click_node);
} break;
- default:{}
+ default: {}
}
}
- if (p_event.mouse_button.button_index==2) {
+ if (p_event.mouse_button.button_index == 2) {
- if (click_type!=CLICK_NONE) {
- click_type=CLICK_NONE;
+ if (click_type != CLICK_NONE) {
+ click_type = CLICK_NONE;
update();
} else {
// try to disconnect/remove
- Point2 rclick_pos=Point2(p_event.mouse_button.x,p_event.mouse_button.y);
- rclick_type = _locate_click(rclick_pos,&rclick_node,&rclick_slot);
- if (rclick_type==CLICK_INPUT_SLOT || rclick_type==CLICK_OUTPUT_SLOT) {
+ Point2 rclick_pos = Point2(p_event.mouse_button.x, p_event.mouse_button.y);
+ rclick_type = _locate_click(rclick_pos, &rclick_node, &rclick_slot);
+ if (rclick_type == CLICK_INPUT_SLOT || rclick_type == CLICK_OUTPUT_SLOT) {
node_popup->clear();
- node_popup->add_item(TTR("Disconnect"),NODE_DISCONNECT);
- if (anim_tree->node_get_type(rclick_node)==AnimationTreePlayer::NODE_TRANSITION) {
- node_popup->add_item(TTR("Add Input"),NODE_ADD_INPUT);
- if (rclick_type==CLICK_INPUT_SLOT) {
- if (anim_tree->transition_node_has_input_auto_advance(rclick_node,rclick_slot))
- node_popup->add_item(TTR("Clear Auto-Advance"),NODE_CLEAR_AUTOADVANCE);
+ node_popup->add_item(TTR("Disconnect"), NODE_DISCONNECT);
+ if (anim_tree->node_get_type(rclick_node) == AnimationTreePlayer::NODE_TRANSITION) {
+ node_popup->add_item(TTR("Add Input"), NODE_ADD_INPUT);
+ if (rclick_type == CLICK_INPUT_SLOT) {
+ if (anim_tree->transition_node_has_input_auto_advance(rclick_node, rclick_slot))
+ node_popup->add_item(TTR("Clear Auto-Advance"), NODE_CLEAR_AUTOADVANCE);
else
- node_popup->add_item(TTR("Set Auto-Advance"),NODE_SET_AUTOADVANCE);
- node_popup->add_item(TTR("Delete Input"),NODE_DELETE_INPUT);
-
+ node_popup->add_item(TTR("Set Auto-Advance"), NODE_SET_AUTOADVANCE);
+ node_popup->add_item(TTR("Delete Input"), NODE_DELETE_INPUT);
}
}
- node_popup->set_pos(rclick_pos+get_global_pos());
+ node_popup->set_pos(rclick_pos + get_global_pos());
node_popup->popup();
-
}
- if (rclick_type==CLICK_NODE) {
+ if (rclick_type == CLICK_NODE) {
node_popup->clear();
- node_popup->add_item(TTR("Rename"),NODE_RENAME);
- node_popup->add_item(TTR("Remove"),NODE_ERASE);
- if (anim_tree->node_get_type(rclick_node)==AnimationTreePlayer::NODE_TRANSITION)
- node_popup->add_item(TTR("Add Input"),NODE_ADD_INPUT);
- node_popup->set_pos(rclick_pos+get_global_pos());
+ node_popup->add_item(TTR("Rename"), NODE_RENAME);
+ node_popup->add_item(TTR("Remove"), NODE_ERASE);
+ if (anim_tree->node_get_type(rclick_node) == AnimationTreePlayer::NODE_TRANSITION)
+ node_popup->add_item(TTR("Add Input"), NODE_ADD_INPUT);
+ node_popup->set_pos(rclick_pos + get_global_pos());
node_popup->popup();
}
-
-
}
}
} else {
- if (p_event.mouse_button.button_index==1 && click_type!=CLICK_NONE) {
+ if (p_event.mouse_button.button_index == 1 && click_type != CLICK_NONE) {
- switch(click_type) {
+ switch (click_type) {
case CLICK_INPUT_SLOT:
case CLICK_OUTPUT_SLOT: {
- Point2 dst_click_pos=Point2(p_event.mouse_button.x,p_event.mouse_button.y);
+ Point2 dst_click_pos = Point2(p_event.mouse_button.x, p_event.mouse_button.y);
StringName id;
int slot;
- ClickType dst_click_type = _locate_click(dst_click_pos,&id,&slot);
+ ClickType dst_click_type = _locate_click(dst_click_pos, &id, &slot);
- if (dst_click_type==CLICK_INPUT_SLOT && click_type==CLICK_OUTPUT_SLOT) {
-
- anim_tree->connect_nodes(click_node,id,slot);
+ if (dst_click_type == CLICK_INPUT_SLOT && click_type == CLICK_OUTPUT_SLOT) {
+ anim_tree->connect_nodes(click_node, id, slot);
}
- if (click_type==CLICK_INPUT_SLOT && dst_click_type==CLICK_OUTPUT_SLOT) {
+ if (click_type == CLICK_INPUT_SLOT && dst_click_type == CLICK_OUTPUT_SLOT) {
- anim_tree->connect_nodes(id,click_node,click_slot);
+ anim_tree->connect_nodes(id, click_node, click_slot);
}
} break;
case CLICK_NODE: {
- Point2 new_pos = anim_tree->node_get_pos(click_node)+(click_motion-click_pos);
- if (new_pos.x<5)
- new_pos.x=5;
- if (new_pos.y<5)
- new_pos.y=5;
- anim_tree->node_set_pos(click_node,new_pos);
+ Point2 new_pos = anim_tree->node_get_pos(click_node) + (click_motion - click_pos);
+ if (new_pos.x < 5)
+ new_pos.x = 5;
+ if (new_pos.y < 5)
+ new_pos.y = 5;
+ anim_tree->node_set_pos(click_node, new_pos);
} break;
default: {}
}
- click_type=CLICK_NONE;
+ click_type = CLICK_NONE;
update();
}
}
@@ -885,89 +854,85 @@ void AnimationTreeEditor::_gui_input(InputEvent p_event) {
case InputEvent::MOUSE_MOTION: {
- if (p_event.mouse_motion.button_mask&1 && click_type!=CLICK_NONE) {
+ if (p_event.mouse_motion.button_mask & 1 && click_type != CLICK_NONE) {
- click_motion=Point2(p_event.mouse_button.x,p_event.mouse_button.y);
+ click_motion = Point2(p_event.mouse_button.x, p_event.mouse_button.y);
update();
}
- if ((p_event.mouse_motion.button_mask&4 || Input::get_singleton()->is_key_pressed(KEY_SPACE))) {
+ if ((p_event.mouse_motion.button_mask & 4 || Input::get_singleton()->is_key_pressed(KEY_SPACE))) {
- h_scroll->set_value( h_scroll->get_value() - p_event.mouse_motion.relative_x );
- v_scroll->set_value( v_scroll->get_value() - p_event.mouse_motion.relative_y );
+ h_scroll->set_value(h_scroll->get_value() - p_event.mouse_motion.relative_x);
+ v_scroll->set_value(v_scroll->get_value() - p_event.mouse_motion.relative_y);
update();
}
} break;
}
-
}
-
-void AnimationTreeEditor::_draw_cos_line(const Vector2& p_from, const Vector2& p_to,const Color& p_color) {
+void AnimationTreeEditor::_draw_cos_line(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color) {
static const int steps = 20;
Rect2 r;
- r.pos=p_from;
+ r.pos = p_from;
r.expand_to(p_to);
- Vector2 sign=Vector2((p_from.x < p_to.x) ? 1 : -1,(p_from.y < p_to.y) ? 1 : -1);
+ Vector2 sign = Vector2((p_from.x < p_to.x) ? 1 : -1, (p_from.y < p_to.y) ? 1 : -1);
bool flip = sign.x * sign.y < 0;
Vector2 prev;
- for(int i=0;i<=steps;i++) {
+ for (int i = 0; i <= steps; i++) {
- float d = i/float(steps);
- float c=-Math::cos(d*Math_PI) * 0.5+0.5;
+ float d = i / float(steps);
+ float c = -Math::cos(d * Math_PI) * 0.5 + 0.5;
if (flip)
- c=1.0-c;
- Vector2 p = r.pos+Vector2(d*r.size.width,c*r.size.height);
+ c = 1.0 - c;
+ Vector2 p = r.pos + Vector2(d * r.size.width, c * r.size.height);
- if (i>0) {
+ if (i > 0) {
- draw_line(prev,p,p_color,2);
+ draw_line(prev, p, p_color, 2);
}
- prev=p;
+ prev = p;
}
}
void AnimationTreeEditor::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- play_button->set_icon( get_icon("Play","EditorIcons") );
- add_menu->set_icon( get_icon("Add","EditorIcons") );
+ play_button->set_icon(get_icon("Play", "EditorIcons"));
+ add_menu->set_icon(get_icon("Add", "EditorIcons"));
} break;
case NOTIFICATION_DRAW: {
-
_update_scrollbars();
//VisualServer::get_singleton()->canvas_item_add_rect(get_canvas_item(),Rect2(Point2(),get_size()),Color(0,0,0,1));
- get_stylebox("bg","Tree")->draw(get_canvas_item(),Rect2(Point2(),get_size()));
+ get_stylebox("bg", "Tree")->draw(get_canvas_item(), Rect2(Point2(), get_size()));
- for(List<StringName>::Element *E=order.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = order.front(); E; E = E->next()) {
_draw_node(E->get());
}
- if (click_type==CLICK_INPUT_SLOT || click_type==CLICK_OUTPUT_SLOT) {
+ if (click_type == CLICK_INPUT_SLOT || click_type == CLICK_OUTPUT_SLOT) {
- _draw_cos_line(click_pos,click_motion,Color(0.5,1,0.5,0.8));
+ _draw_cos_line(click_pos, click_motion, Color(0.5, 1, 0.5, 0.8));
}
List<AnimationTreePlayer::Connection> connections;
anim_tree->get_connection_list(&connections);
- for(List<AnimationTreePlayer::Connection>::Element *E=connections.front();E;E=E->next()) {
+ for (List<AnimationTreePlayer::Connection>::Element *E = connections.front(); E; E = E->next()) {
- const AnimationTreePlayer::Connection &c=E->get();
- Point2 source = _get_slot_pos(c.src_node,false,0);
- Point2 dest = _get_slot_pos(c.dst_node,true,c.dst_input);
- Color col = Color(1,1,0.5,0.8);
-/*
+ const AnimationTreePlayer::Connection &c = E->get();
+ Point2 source = _get_slot_pos(c.src_node, false, 0);
+ Point2 dest = _get_slot_pos(c.dst_node, true, c.dst_input);
+ Color col = Color(1, 1, 0.5, 0.8);
+ /*
if (click_type==CLICK_NODE && click_node==c.src_node) {
source+=click_motion-click_pos;
@@ -978,27 +943,25 @@ void AnimationTreeEditor::_notification(int p_what) {
dest+=click_motion-click_pos;
}*/
- _draw_cos_line(source,dest,col);
-
+ _draw_cos_line(source, dest, col);
}
- switch(anim_tree->get_last_error()) {
+ switch (anim_tree->get_last_error()) {
case AnimationTreePlayer::CONNECT_OK: {
- Ref<Font> f = get_font("font","Label");
- f->draw(get_canvas_item(),Point2(5,25+f->get_ascent()),TTR("Animation tree is valid."),Color(0,1,0.6,0.8));
+ Ref<Font> f = get_font("font", "Label");
+ f->draw(get_canvas_item(), Point2(5, 25 + f->get_ascent()), TTR("Animation tree is valid."), Color(0, 1, 0.6, 0.8));
} break;
default: {
- Ref<Font> f = get_font("font","Label");
- f->draw(get_canvas_item(),Point2(5,25+f->get_ascent()),TTR("Animation tree is invalid."),Color(1,0.6,0.0,0.8));
+ Ref<Font> f = get_font("font", "Label");
+ f->draw(get_canvas_item(), Point2(5, 25 + f->get_ascent()), TTR("Animation tree is invalid."), Color(1, 0.6, 0.0, 0.8));
} break;
}
} break;
}
-
}
void AnimationTreeEditor::_update_scrollbars() {
@@ -1007,72 +970,69 @@ void AnimationTreeEditor::_update_scrollbars() {
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
- v_scroll->set_begin( Point2(size.width - vmin.width, 0) );
- v_scroll->set_end( Point2(size.width, size.height) );
-
- h_scroll->set_begin( Point2( 0, size.height - hmin.height) );
- h_scroll->set_end( Point2(size.width-vmin.width, size.height) );
+ v_scroll->set_begin(Point2(size.width - vmin.width, 0));
+ v_scroll->set_end(Point2(size.width, size.height));
+ h_scroll->set_begin(Point2(0, size.height - hmin.height));
+ h_scroll->set_end(Point2(size.width - vmin.width, size.height));
Size2 min = _get_maximum_size();
if (min.height < size.height - hmin.height) {
v_scroll->hide();
- offset.y=0;
+ offset.y = 0;
} else {
v_scroll->show();
v_scroll->set_max(min.height);
v_scroll->set_page(size.height - hmin.height);
- offset.y=v_scroll->get_value();
+ offset.y = v_scroll->get_value();
}
if (min.width < size.width - vmin.width) {
h_scroll->hide();
- offset.x=0;
+ offset.x = 0;
} else {
h_scroll->show();
h_scroll->set_max(min.width);
h_scroll->set_page(size.width - vmin.width);
- offset.x=h_scroll->get_value();
+ offset.x = h_scroll->get_value();
}
}
void AnimationTreeEditor::_scroll_moved(float) {
- offset.x=h_scroll->get_value();
- offset.y=v_scroll->get_value();
+ offset.x = h_scroll->get_value();
+ offset.y = v_scroll->get_value();
update();
}
-
void AnimationTreeEditor::_node_menu_item(int p_item) {
- switch(p_item) {
+ switch (p_item) {
case NODE_DISCONNECT: {
- if (rclick_type==CLICK_INPUT_SLOT) {
+ if (rclick_type == CLICK_INPUT_SLOT) {
- anim_tree->disconnect_nodes(rclick_node,rclick_slot);
+ anim_tree->disconnect_nodes(rclick_node, rclick_slot);
update();
}
- if (rclick_type==CLICK_OUTPUT_SLOT) {
-
+ if (rclick_type == CLICK_OUTPUT_SLOT) {
List<AnimationTreePlayer::Connection> connections;
anim_tree->get_connection_list(&connections);
- for(List<AnimationTreePlayer::Connection>::Element *E=connections.front();E;E=E->next()) {
+ for (List<AnimationTreePlayer::Connection>::Element *E = connections.front(); E; E = E->next()) {
- const AnimationTreePlayer::Connection &c=E->get();
- if( c.dst_node==rclick_node) {
+ const AnimationTreePlayer::Connection &c = E->get();
+ if (c.dst_node == rclick_node) {
- anim_tree->disconnect_nodes(c.dst_node,c.dst_input);
+ anim_tree->disconnect_nodes(c.dst_node, c.dst_input);
}
}
update();
@@ -1081,37 +1041,37 @@ void AnimationTreeEditor::_node_menu_item(int p_item) {
} break;
case NODE_RENAME: {
- renaming_edit=true;
- edited_node=rclick_node;
+ renaming_edit = true;
+ edited_node = rclick_node;
_popup_edit_dialog();
} break;
case NODE_ADD_INPUT: {
- anim_tree->transition_node_set_input_count(rclick_node, anim_tree->transition_node_get_input_count(rclick_node)+1);
+ anim_tree->transition_node_set_input_count(rclick_node, anim_tree->transition_node_get_input_count(rclick_node) + 1);
update();
} break;
- case NODE_DELETE_INPUT: {
+ case NODE_DELETE_INPUT: {
- anim_tree->transition_node_delete_input(rclick_node, rclick_slot);
- update();
- } break;
+ anim_tree->transition_node_delete_input(rclick_node, rclick_slot);
+ update();
+ } break;
case NODE_SET_AUTOADVANCE: {
- anim_tree->transition_node_set_input_auto_advance(rclick_node,rclick_slot,true);
+ anim_tree->transition_node_set_input_auto_advance(rclick_node, rclick_slot, true);
update();
} break;
- case NODE_CLEAR_AUTOADVANCE: {
+ case NODE_CLEAR_AUTOADVANCE: {
- anim_tree->transition_node_set_input_auto_advance(rclick_node,rclick_slot,false);
+ anim_tree->transition_node_set_input_auto_advance(rclick_node, rclick_slot, false);
update();
} break;
case NODE_ERASE: {
- if (rclick_node=="out")
+ if (rclick_node == "out")
break;
order.erase(rclick_node);
anim_tree->remove_node(rclick_node);
@@ -1122,7 +1082,7 @@ void AnimationTreeEditor::_node_menu_item(int p_item) {
StringName AnimationTreeEditor::_add_node(int p_item) {
- static const char* bname[] = {
+ static const char *bname[] = {
"out",
"anim",
"oneshot",
@@ -1136,27 +1096,26 @@ StringName AnimationTreeEditor::_add_node(int p_item) {
};
String name;
- int idx=1;
+ int idx = 1;
- while(true) {
+ while (true) {
name = bname[p_item];
- if (idx>1)
- name+=" "+itos(idx);
+ if (idx > 1)
+ name += " " + itos(idx);
if (anim_tree->node_exists(name))
idx++;
else
break;
}
-
- anim_tree->add_node((AnimationTreePlayer::NodeType)p_item,name);
- anim_tree->node_set_pos(name,Point2(last_x,last_y));
+ anim_tree->add_node((AnimationTreePlayer::NodeType)p_item, name);
+ anim_tree->node_set_pos(name, Point2(last_x, last_y));
order.push_back(name);
- last_x+=10;
- last_y+=10;
- last_x=last_x % (int)get_size().width;
- last_y=last_y % (int)get_size().height;
+ last_x += 10;
+ last_y += 10;
+ last_x = last_x % (int)get_size().width;
+ last_y = last_y % (int)get_size().height;
update();
return name;
@@ -1166,27 +1125,27 @@ void AnimationTreeEditor::_file_dialog_selected(String p_path) {
switch (file_op) {
- case MENU_IMPORT_ANIMATIONS: {
- Vector<String> files = file_dialog->get_selected_files();
+ case MENU_IMPORT_ANIMATIONS: {
+ Vector<String> files = file_dialog->get_selected_files();
- for (int i=0; i<files.size(); i++) {
+ for (int i = 0; i < files.size(); i++) {
- StringName node = _add_node(AnimationTreePlayer::NODE_ANIMATION);
+ StringName node = _add_node(AnimationTreePlayer::NODE_ANIMATION);
- RES anim = ResourceLoader::load(files[i]);
- anim_tree->animation_node_set_animation(node,anim);
- //anim_tree->node_set_name(node, files[i].get_file());
- };
- } break;
+ RES anim = ResourceLoader::load(files[i]);
+ anim_tree->animation_node_set_animation(node, anim);
+ //anim_tree->node_set_name(node, files[i].get_file());
+ };
+ } break;
- default:
- break;
+ default:
+ break;
};
};
void AnimationTreeEditor::_add_menu_item(int p_item) {
- if (p_item==MENU_GRAPH_CLEAR) {
+ if (p_item == MENU_GRAPH_CLEAR) {
//clear
} else if (p_item == MENU_IMPORT_ANIMATIONS) {
@@ -1203,49 +1162,46 @@ void AnimationTreeEditor::_add_menu_item(int p_item) {
Size2 AnimationTreeEditor::get_minimum_size() const {
- return Size2(10,200);
+ return Size2(10, 200);
}
-void AnimationTreeEditor::_find_paths_for_filter(const StringName& p_node,Set<String>& paths) {
+void AnimationTreeEditor::_find_paths_for_filter(const StringName &p_node, Set<String> &paths) {
- ERR_FAIL_COND( !anim_tree->node_exists(p_node) );
+ ERR_FAIL_COND(!anim_tree->node_exists(p_node));
- for(int i=0;i<anim_tree->node_get_input_count(p_node);i++) {
+ for (int i = 0; i < anim_tree->node_get_input_count(p_node); i++) {
- StringName port = anim_tree->node_get_input_source(p_node,i);
- if (port==StringName())
+ StringName port = anim_tree->node_get_input_source(p_node, i);
+ if (port == StringName())
continue;
- _find_paths_for_filter(port,paths);
+ _find_paths_for_filter(port, paths);
}
- if (anim_tree->node_get_type(p_node)==AnimationTreePlayer::NODE_ANIMATION) {
+ if (anim_tree->node_get_type(p_node) == AnimationTreePlayer::NODE_ANIMATION) {
Ref<Animation> anim = anim_tree->animation_node_get_animation(p_node);
if (anim.is_valid()) {
- for(int i=0;i<anim->get_track_count();i++) {
+ for (int i = 0; i < anim->get_track_count(); i++) {
paths.insert(anim->track_get_path(i));
}
}
}
}
-
void AnimationTreeEditor::_filter_edited() {
-
TreeItem *ed = filter->get_edited();
if (!ed)
return;
- if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_ONESHOT) {
- anim_tree->oneshot_node_set_filter_path(edited_node,ed->get_metadata(0),ed->is_checked(0));
- } else if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_BLEND2) {
- anim_tree->blend2_node_set_filter_path(edited_node,ed->get_metadata(0),ed->is_checked(0));
- } else if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_ANIMATION) {
- anim_tree->animation_node_set_filter_path(edited_node,ed->get_metadata(0),ed->is_checked(0));
+ if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_ONESHOT) {
+ anim_tree->oneshot_node_set_filter_path(edited_node, ed->get_metadata(0), ed->is_checked(0));
+ } else if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_BLEND2) {
+ anim_tree->blend2_node_set_filter_path(edited_node, ed->get_metadata(0), ed->is_checked(0));
+ } else if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_ANIMATION) {
+ anim_tree->animation_node_set_filter_path(edited_node, ed->get_metadata(0), ed->is_checked(0));
}
-
}
void AnimationTreeEditor::_edit_filters() {
@@ -1254,47 +1210,44 @@ void AnimationTreeEditor::_edit_filters() {
filter->clear();
Set<String> npb;
- _find_paths_for_filter(edited_node,npb);
+ _find_paths_for_filter(edited_node, npb);
TreeItem *root = filter->create_item();
filter->set_hide_root(true);
- Map<String,TreeItem*> pm;
+ Map<String, TreeItem *> pm;
- Node *base = anim_tree->get_node( anim_tree->get_base_path() );
+ Node *base = anim_tree->get_node(anim_tree->get_base_path());
- for(Set<String>::Element *E=npb.front();E;E=E->next()) {
+ for (Set<String>::Element *E = npb.front(); E; E = E->next()) {
- TreeItem *parent=root;
- String descr=E->get();
+ TreeItem *parent = root;
+ String descr = E->get();
if (base) {
NodePath np = E->get();
- if (np.get_property()!=StringName()) {
+ if (np.get_property() != StringName()) {
Node *n = base->get_node(np);
Skeleton *s = n->cast_to<Skeleton>();
if (s) {
- String skelbase = E->get().substr(0,E->get().find(":"));
-
+ String skelbase = E->get().substr(0, E->get().find(":"));
int bidx = s->find_bone(np.get_property());
- if (bidx!=-1) {
+ if (bidx != -1) {
int bparent = s->get_bone_parent(bidx);
//
- if (bparent!=-1) {
-
+ if (bparent != -1) {
- String bpn = skelbase+":"+s->get_bone_name(bparent);
+ String bpn = skelbase + ":" + s->get_bone_name(bparent);
if (pm.has(bpn)) {
- parent=pm[bpn];
- descr=np.get_property();
+ parent = pm[bpn];
+ descr = np.get_property();
}
} else {
if (pm.has(skelbase)) {
- parent=pm[skelbase];
-
+ parent = pm[skelbase];
}
}
}
@@ -1303,43 +1256,40 @@ void AnimationTreeEditor::_edit_filters() {
}
TreeItem *it = filter->create_item(parent);
- it->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- it->set_text(0,descr);
- it->set_metadata(0,NodePath(E->get()));
- it->set_editable(0,true);
- if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_ONESHOT) {
- it->set_checked(0, anim_tree->oneshot_node_is_path_filtered(edited_node,E->get()));
- } else if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_BLEND2) {
- it->set_checked(0, anim_tree->blend2_node_is_path_filtered(edited_node,E->get()));
- } else if (anim_tree->node_get_type(edited_node)==AnimationTreePlayer::NODE_ANIMATION) {
- it->set_checked(0, anim_tree->animation_node_is_path_filtered(edited_node,E->get()));
+ it->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ it->set_text(0, descr);
+ it->set_metadata(0, NodePath(E->get()));
+ it->set_editable(0, true);
+ if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_ONESHOT) {
+ it->set_checked(0, anim_tree->oneshot_node_is_path_filtered(edited_node, E->get()));
+ } else if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_BLEND2) {
+ it->set_checked(0, anim_tree->blend2_node_is_path_filtered(edited_node, E->get()));
+ } else if (anim_tree->node_get_type(edited_node) == AnimationTreePlayer::NODE_ANIMATION) {
+ it->set_checked(0, anim_tree->animation_node_is_path_filtered(edited_node, E->get()));
}
- pm[E->get()]=it;
+ pm[E->get()] = it;
}
-
-
}
void AnimationTreeEditor::_bind_methods() {
- ClassDB::bind_method( "_add_menu_item", &AnimationTreeEditor::_add_menu_item );
- ClassDB::bind_method( "_node_menu_item", &AnimationTreeEditor::_node_menu_item );
- ClassDB::bind_method( "_gui_input", &AnimationTreeEditor::_gui_input );
+ ClassDB::bind_method("_add_menu_item", &AnimationTreeEditor::_add_menu_item);
+ ClassDB::bind_method("_node_menu_item", &AnimationTreeEditor::_node_menu_item);
+ ClassDB::bind_method("_gui_input", &AnimationTreeEditor::_gui_input);
//ClassDB::bind_method( "_node_param_changed", &AnimationTreeEditor::_node_param_changed );
- ClassDB::bind_method( "_scroll_moved", &AnimationTreeEditor::_scroll_moved );
- ClassDB::bind_method( "_edit_dialog_changeds", &AnimationTreeEditor::_edit_dialog_changeds );
- ClassDB::bind_method( "_edit_dialog_changede", &AnimationTreeEditor::_edit_dialog_changede );
- ClassDB::bind_method( "_edit_dialog_changedf", &AnimationTreeEditor::_edit_dialog_changedf );
- ClassDB::bind_method( "_edit_dialog_changed", &AnimationTreeEditor::_edit_dialog_changed );
- ClassDB::bind_method( "_edit_dialog_animation_changed", &AnimationTreeEditor::_edit_dialog_animation_changed );
- ClassDB::bind_method( "_edit_dialog_edit_animation", &AnimationTreeEditor::_edit_dialog_edit_animation );
- ClassDB::bind_method( "_play_toggled", &AnimationTreeEditor::_play_toggled );
- ClassDB::bind_method( "_edit_oneshot_start", &AnimationTreeEditor::_edit_oneshot_start );
- ClassDB::bind_method( "_file_dialog_selected", &AnimationTreeEditor::_file_dialog_selected);
- ClassDB::bind_method( "_master_anim_menu_item", &AnimationTreeEditor::_master_anim_menu_item);
- ClassDB::bind_method( "_edit_filters", &AnimationTreeEditor::_edit_filters);
- ClassDB::bind_method( "_filter_edited", &AnimationTreeEditor::_filter_edited);
-
+ ClassDB::bind_method("_scroll_moved", &AnimationTreeEditor::_scroll_moved);
+ ClassDB::bind_method("_edit_dialog_changeds", &AnimationTreeEditor::_edit_dialog_changeds);
+ ClassDB::bind_method("_edit_dialog_changede", &AnimationTreeEditor::_edit_dialog_changede);
+ ClassDB::bind_method("_edit_dialog_changedf", &AnimationTreeEditor::_edit_dialog_changedf);
+ ClassDB::bind_method("_edit_dialog_changed", &AnimationTreeEditor::_edit_dialog_changed);
+ ClassDB::bind_method("_edit_dialog_animation_changed", &AnimationTreeEditor::_edit_dialog_animation_changed);
+ ClassDB::bind_method("_edit_dialog_edit_animation", &AnimationTreeEditor::_edit_dialog_edit_animation);
+ ClassDB::bind_method("_play_toggled", &AnimationTreeEditor::_play_toggled);
+ ClassDB::bind_method("_edit_oneshot_start", &AnimationTreeEditor::_edit_oneshot_start);
+ ClassDB::bind_method("_file_dialog_selected", &AnimationTreeEditor::_file_dialog_selected);
+ ClassDB::bind_method("_master_anim_menu_item", &AnimationTreeEditor::_master_anim_menu_item);
+ ClassDB::bind_method("_edit_filters", &AnimationTreeEditor::_edit_filters);
+ ClassDB::bind_method("_filter_edited", &AnimationTreeEditor::_filter_edited);
}
AnimationTreeEditor::AnimationTreeEditor() {
@@ -1349,149 +1299,141 @@ AnimationTreeEditor::AnimationTreeEditor() {
PopupMenu *p;
List<PropertyInfo> defaults;
- add_menu = memnew( MenuButton );
+ add_menu = memnew(MenuButton);
//add_menu->set_
- add_menu->set_pos( Point2( 0,0) );
- add_menu->set_size( Point2( 25,15) );
- add_child( add_menu );
-
- p=add_menu->get_popup();
- p->add_item(TTR("Animation Node"),AnimationTreePlayer::NODE_ANIMATION);
- p->add_item(TTR("OneShot Node"),AnimationTreePlayer::NODE_ONESHOT);
- p->add_item(TTR("Mix Node"),AnimationTreePlayer::NODE_MIX);
- p->add_item(TTR("Blend2 Node"),AnimationTreePlayer::NODE_BLEND2);
- p->add_item(TTR("Blend3 Node"),AnimationTreePlayer::NODE_BLEND3);
- p->add_item(TTR("Blend4 Node"),AnimationTreePlayer::NODE_BLEND4);
- p->add_item(TTR("TimeScale Node"),AnimationTreePlayer::NODE_TIMESCALE);
- p->add_item(TTR("TimeSeek Node"),AnimationTreePlayer::NODE_TIMESEEK);
- p->add_item(TTR("Transition Node"),AnimationTreePlayer::NODE_TRANSITION);
+ add_menu->set_pos(Point2(0, 0));
+ add_menu->set_size(Point2(25, 15));
+ add_child(add_menu);
+
+ p = add_menu->get_popup();
+ p->add_item(TTR("Animation Node"), AnimationTreePlayer::NODE_ANIMATION);
+ p->add_item(TTR("OneShot Node"), AnimationTreePlayer::NODE_ONESHOT);
+ p->add_item(TTR("Mix Node"), AnimationTreePlayer::NODE_MIX);
+ p->add_item(TTR("Blend2 Node"), AnimationTreePlayer::NODE_BLEND2);
+ p->add_item(TTR("Blend3 Node"), AnimationTreePlayer::NODE_BLEND3);
+ p->add_item(TTR("Blend4 Node"), AnimationTreePlayer::NODE_BLEND4);
+ p->add_item(TTR("TimeScale Node"), AnimationTreePlayer::NODE_TIMESCALE);
+ p->add_item(TTR("TimeSeek Node"), AnimationTreePlayer::NODE_TIMESEEK);
+ p->add_item(TTR("Transition Node"), AnimationTreePlayer::NODE_TRANSITION);
p->add_separator();
p->add_item(TTR("Import Animations.."), MENU_IMPORT_ANIMATIONS); // wtf
p->add_separator();
- p->add_item(TTR("Clear"),MENU_GRAPH_CLEAR);
+ p->add_item(TTR("Clear"), MENU_GRAPH_CLEAR);
- p->connect("id_pressed", this,"_add_menu_item");
+ p->connect("id_pressed", this, "_add_menu_item");
play_button = memnew(Button);
- play_button->set_pos(Point2(25,0));
- play_button->set_size(Point2(25,15));
+ play_button->set_pos(Point2(25, 0));
+ play_button->set_size(Point2(25, 15));
add_child(play_button);
play_button->set_toggle_mode(true);
- play_button->connect("pressed", this,"_play_toggled");
-
-
+ play_button->connect("pressed", this, "_play_toggled");
+ last_x = 50;
+ last_y = 50;
-
- last_x=50;
- last_y=50;
-
- property_editor = memnew( CustomPropertyEditor );
+ property_editor = memnew(CustomPropertyEditor);
add_child(property_editor);
- property_editor->connect("variant_changed", this,"_edit_dialog_animation_changed");
- property_editor->connect("resource_edit_request", this, "_edit_dialog_edit_animation");
+ property_editor->connect("variant_changed", this, "_edit_dialog_animation_changed");
+ property_editor->connect("resource_edit_request", this, "_edit_dialog_edit_animation");
- h_scroll = memnew( HScrollBar );
- v_scroll = memnew( VScrollBar );
+ h_scroll = memnew(HScrollBar);
+ v_scroll = memnew(VScrollBar);
add_child(h_scroll);
add_child(v_scroll);
- h_scroll->connect("value_changed", this,"_scroll_moved");
- v_scroll->connect("value_changed", this,"_scroll_moved");
+ h_scroll->connect("value_changed", this, "_scroll_moved");
+ v_scroll->connect("value_changed", this, "_scroll_moved");
- node_popup= memnew(PopupMenu );
+ node_popup = memnew(PopupMenu);
add_child(node_popup);
node_popup->set_as_toplevel(true);
- master_anim_popup = memnew( PopupMenu );
+ master_anim_popup = memnew(PopupMenu);
add_child(master_anim_popup);
- master_anim_popup->connect("id_pressed",this,"_master_anim_menu_item");
+ master_anim_popup->connect("id_pressed", this, "_master_anim_menu_item");
+ node_popup->connect("id_pressed", this, "_node_menu_item");
- node_popup->connect("id_pressed", this,"_node_menu_item");
+ updating_edit = false;
- updating_edit=false;
-
- edit_dialog = memnew( PopupPanel );
+ edit_dialog = memnew(PopupPanel);
//edit_dialog->get_ok()->hide();
//edit_dialog->get_cancel()->hide();
add_child(edit_dialog);
- edit_option = memnew( OptionButton );
- edit_option->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ edit_option = memnew(OptionButton);
+ edit_option->set_anchor(MARGIN_RIGHT, ANCHOR_END);
edit_option->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(edit_option);
- edit_option->connect("item_selected", this,"_edit_dialog_changedf");
+ edit_option->connect("item_selected", this, "_edit_dialog_changedf");
edit_option->hide();
-
- for(int i=0;i<2;i++) {
- edit_scroll[i] = memnew ( HSlider );
- edit_scroll[i]->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ for (int i = 0; i < 2; i++) {
+ edit_scroll[i] = memnew(HSlider);
+ edit_scroll[i]->set_anchor(MARGIN_RIGHT, ANCHOR_END);
edit_scroll[i]->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(edit_scroll[i]);
edit_scroll[i]->hide();
- edit_scroll[i]->connect("value_changed", this,"_edit_dialog_changedf");
+ edit_scroll[i]->connect("value_changed", this, "_edit_dialog_changedf");
}
- for(int i=0;i<4;i++) {
- edit_line[i] = memnew ( LineEdit );
- edit_line[i]->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ for (int i = 0; i < 4; i++) {
+ edit_line[i] = memnew(LineEdit);
+ edit_line[i]->set_anchor(MARGIN_RIGHT, ANCHOR_END);
edit_line[i]->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(edit_line[i]);
edit_line[i]->hide();
- edit_line[i]->connect("text_changed", this,"_edit_dialog_changeds");
- edit_line[i]->connect("text_entered", this,"_edit_dialog_changede");
- edit_label[i] = memnew ( Label );
+ edit_line[i]->connect("text_changed", this, "_edit_dialog_changeds");
+ edit_line[i]->connect("text_entered", this, "_edit_dialog_changede");
+ edit_label[i] = memnew(Label);
edit_dialog->add_child(edit_label[i]);
edit_label[i]->hide();
}
- edit_button = memnew( Button );
- edit_button->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ edit_button = memnew(Button);
+ edit_button->set_anchor(MARGIN_RIGHT, ANCHOR_END);
edit_button->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(edit_button);
edit_button->hide();
- edit_button->connect("pressed", this,"_edit_oneshot_start");
+ edit_button->connect("pressed", this, "_edit_oneshot_start");
- edit_check = memnew( CheckButton );
- edit_check->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ edit_check = memnew(CheckButton);
+ edit_check->set_anchor(MARGIN_RIGHT, ANCHOR_END);
edit_check->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(edit_check);
edit_check->hide();
- edit_check->connect("pressed", this,"_edit_dialog_changed");
+ edit_check->connect("pressed", this, "_edit_dialog_changed");
- file_dialog = memnew( EditorFileDialog );
+ file_dialog = memnew(EditorFileDialog);
file_dialog->set_enable_multiple_selection(true);
file_dialog->set_current_dir(GlobalConfig::get_singleton()->get_resource_path());
add_child(file_dialog);
- file_dialog->connect("file_selected", this, "_file_dialog_selected");
+ file_dialog->connect("file_selected", this, "_file_dialog_selected");
- filter_dialog = memnew( AcceptDialog );
+ filter_dialog = memnew(AcceptDialog);
filter_dialog->set_title(TTR("Edit Node Filters"));
add_child(filter_dialog);
- filter = memnew( Tree );
+ filter = memnew(Tree);
filter_dialog->add_child(filter);
//filter_dialog->set_child_rect(filter);
- filter->connect("item_edited",this,"_filter_edited");
+ filter->connect("item_edited", this, "_filter_edited");
- filter_button = memnew( Button );
- filter_button->set_anchor( MARGIN_RIGHT, ANCHOR_END );
+ filter_button = memnew(Button);
+ filter_button->set_anchor(MARGIN_RIGHT, ANCHOR_END);
filter_button->set_margin(MARGIN_RIGHT, 10);
edit_dialog->add_child(filter_button);
filter_button->hide();
filter_button->set_text(TTR("Filters.."));
- filter_button->connect("pressed", this,"_edit_filters");
+ filter_button->connect("pressed", this, "_edit_filters");
set_clip_contents(true);
}
-
void AnimationTreeEditorPlugin::edit(Object *p_object) {
anim_tree_editor->edit(p_object->cast_to<AnimationTreePlayer>());
-
}
bool AnimationTreeEditorPlugin::handles(Object *p_object) const {
@@ -1518,19 +1460,13 @@ void AnimationTreeEditorPlugin::make_visible(bool p_visible) {
AnimationTreeEditorPlugin::AnimationTreeEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- anim_tree_editor = memnew( AnimationTreeEditor );
- anim_tree_editor->set_custom_minimum_size(Size2(0,300));
+ editor = p_node;
+ anim_tree_editor = memnew(AnimationTreeEditor);
+ anim_tree_editor->set_custom_minimum_size(Size2(0, 300));
- button=editor->add_bottom_panel_item("AnimationTree",anim_tree_editor);
+ button = editor->add_bottom_panel_item("AnimationTree", anim_tree_editor);
button->hide();
-
-
-
}
-
-AnimationTreeEditorPlugin::~AnimationTreeEditorPlugin()
-{
+AnimationTreeEditorPlugin::~AnimationTreeEditorPlugin() {
}
-
diff --git a/editor/plugins/animation_tree_editor_plugin.h b/editor/plugins/animation_tree_editor_plugin.h
index 4e5fb871f1..d998cb99ae 100644
--- a/editor/plugins/animation_tree_editor_plugin.h
+++ b/editor/plugins/animation_tree_editor_plugin.h
@@ -29,22 +29,22 @@
#ifndef ANIMATION_TREE_EDITOR_PLUGIN_H
#define ANIMATION_TREE_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
+#include "editor/property_editor.h"
#include "scene/animation/animation_tree_player.h"
-#include "scene/gui/tree.h"
#include "scene/gui/button.h"
#include "scene/gui/popup.h"
-#include "editor/property_editor.h"
+#include "scene/gui/tree.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class AnimationTreeEditor : public Control {
- GDCLASS(AnimationTreeEditor, Control );
+ GDCLASS(AnimationTreeEditor, Control);
- static const char* _node_type_names[];
+ static const char *_node_type_names[];
enum ClickType {
CLICK_NONE,
@@ -57,8 +57,8 @@ class AnimationTreeEditor : public Control {
enum {
- MENU_GRAPH_CLEAR=100,
- MENU_IMPORT_ANIMATIONS=101,
+ MENU_GRAPH_CLEAR = 100,
+ MENU_IMPORT_ANIMATIONS = 101,
NODE_DISCONNECT,
NODE_RENAME,
NODE_ERASE,
@@ -79,27 +79,26 @@ class AnimationTreeEditor : public Control {
Button *edit_button;
Button *filter_button;
CheckButton *edit_check;
- EditorFileDialog* file_dialog;
+ EditorFileDialog *file_dialog;
int file_op;
void _popup_edit_dialog();
-
- void _setup_edit_dialog(const StringName& p_node);
+ void _setup_edit_dialog(const StringName &p_node);
PopupMenu *master_anim_popup;
PopupMenu *node_popup;
PopupMenu *add_popup;
HScrollBar *h_scroll;
VScrollBar *v_scroll;
- MenuButton* add_menu;
+ MenuButton *add_menu;
CustomPropertyEditor *property_editor;
- AnimationTreePlayer* anim_tree;
+ AnimationTreePlayer *anim_tree;
List<StringName> order;
Set<StringName> active_nodes;
- int last_x,last_y;
+ int last_x, last_y;
Point2 offset;
ClickType click_type;
@@ -115,18 +114,16 @@ class AnimationTreeEditor : public Control {
Size2 _get_maximum_size();
Size2 get_node_size(const StringName &p_node) const;
- void _draw_node(const StringName& p_node);
+ void _draw_node(const StringName &p_node);
AcceptDialog *filter_dialog;
Tree *filter;
-
-
- void _draw_cos_line(const Vector2& p_from, const Vector2& p_to,const Color& p_color);
+ void _draw_cos_line(const Vector2 &p_from, const Vector2 &p_to, const Color &p_color);
void _update_scrollbars();
void _scroll_moved(float);
void _play_toggled();
-/*
+ /*
void _node_param_changed();
void _node_add_callback();
void _node_add(VisualServer::AnimationTreeNodeType p_type);
@@ -137,12 +134,10 @@ class AnimationTreeEditor : public Control {
void _node_menu_item(int p_item);
void _add_menu_item(int p_item);
-
void _filter_edited();
- void _find_paths_for_filter(const StringName& p_node,Set<String>& paths);
+ void _find_paths_for_filter(const StringName &p_node, Set<String> &paths);
void _edit_filters();
-
void _edit_oneshot_start();
void _edit_dialog_animation_changed();
void _edit_dialog_edit_animation();
@@ -151,20 +146,18 @@ class AnimationTreeEditor : public Control {
void _edit_dialog_changedf(float);
void _edit_dialog_changed();
void _dialog_changed() const;
- ClickType _locate_click(const Point2& p_click,StringName *p_node_id,int *p_slot_index) const;
- Point2 _get_slot_pos(const StringName& p_node_id,bool p_input,int p_slot);
+ ClickType _locate_click(const Point2 &p_click, StringName *p_node_id, int *p_slot_index) const;
+ Point2 _get_slot_pos(const StringName &p_node_id, bool p_input, int p_slot);
StringName _add_node(int p_item);
void _file_dialog_selected(String p_path);
-
protected:
void _notification(int p_what);
void _gui_input(InputEvent p_event);
static void _bind_methods();
-public:
-
+public:
virtual Size2 get_minimum_size() const;
void edit(AnimationTreePlayer *p_player);
AnimationTreeEditor();
@@ -172,14 +165,13 @@ public:
class AnimationTreeEditorPlugin : public EditorPlugin {
- GDCLASS( AnimationTreeEditorPlugin, EditorPlugin );
+ GDCLASS(AnimationTreeEditorPlugin, EditorPlugin);
AnimationTreeEditor *anim_tree_editor;
EditorNode *editor;
Button *button;
public:
-
virtual String get_name() const { return "AnimTree"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -188,7 +180,6 @@ public:
AnimationTreeEditorPlugin(EditorNode *p_node);
~AnimationTreeEditorPlugin();
-
};
#endif // ANIMATION_TREE_EDITOR_PLUGIN_H
diff --git a/editor/plugins/baked_light_baker.cpp b/editor/plugins/baked_light_baker.cpp
index e491fe012e..de2b78b8dd 100644
--- a/editor/plugins/baked_light_baker.cpp
+++ b/editor/plugins/baked_light_baker.cpp
@@ -28,11 +28,11 @@
/*************************************************************************/
#include "baked_light_baker.h"
-#include <stdlib.h>
-#include <cmath>
-#include "io/marshalls.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "io/marshalls.h"
+#include <stdlib.h>
+#include <cmath>
#if 0
void baked_light_baker_add_64f(double *dst,double value);
diff --git a/editor/plugins/baked_light_baker.h b/editor/plugins/baked_light_baker.h
index 89788338d9..f328062b1e 100644
--- a/editor/plugins/baked_light_baker.h
+++ b/editor/plugins/baked_light_baker.h
@@ -29,10 +29,10 @@
#ifndef BAKED_LIGHT_BAKER_H
#define BAKED_LIGHT_BAKER_H
+#include "os/thread.h"
#include "scene/3d/baked_light_instance.h"
#include "scene/3d/light.h"
#include "scene/3d/mesh_instance.h"
-#include "os/thread.h"
#if 0
diff --git a/editor/plugins/baked_light_baker_cmpxchg.cpp b/editor/plugins/baked_light_baker_cmpxchg.cpp
index 5e9228b7de..f84c001f78 100644
--- a/editor/plugins/baked_light_baker_cmpxchg.cpp
+++ b/editor/plugins/baked_light_baker_cmpxchg.cpp
@@ -28,85 +28,77 @@
/*************************************************************************/
#include "typedefs.h"
-
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) > 40100
-void baked_light_baker_add_64f(double *dst,double value) {
-
+void baked_light_baker_add_64f(double *dst, double value) {
union {
int64_t i;
double f;
} swapy;
-
- while(true) {
- swapy.f=*dst;
+ while (true) {
+ swapy.f = *dst;
int64_t from = swapy.i;
- swapy.f+=value;
- int64_t to=swapy.i;
- if (__sync_bool_compare_and_swap((int64_t*)dst,from,to))
+ swapy.f += value;
+ int64_t to = swapy.i;
+ if (__sync_bool_compare_and_swap((int64_t *)dst, from, to))
break;
}
}
-void baked_light_baker_add_64i(int64_t *dst,int64_t value) {
-
- while(!__sync_bool_compare_and_swap(dst,*dst,(*dst)+value)) {}
+void baked_light_baker_add_64i(int64_t *dst, int64_t value) {
+ while (!__sync_bool_compare_and_swap(dst, *dst, (*dst) + value)) {
+ }
}
#elif defined(WINDOWS_ENABLED)
#include "windows.h"
-void baked_light_baker_add_64f(double *dst,double value) {
+void baked_light_baker_add_64f(double *dst, double value) {
union {
int64_t i;
double f;
} swapy;
-
- while(true) {
- swapy.f=*dst;
+ while (true) {
+ swapy.f = *dst;
int64_t from = swapy.i;
- swapy.f+=value;
- int64_t to=swapy.i;
- int64_t result = InterlockedCompareExchange64((int64_t*)dst,to,from);
- if (result==from)
+ swapy.f += value;
+ int64_t to = swapy.i;
+ int64_t result = InterlockedCompareExchange64((int64_t *)dst, to, from);
+ if (result == from)
break;
}
-
}
-void baked_light_baker_add_64i(int64_t *dst,int64_t value) {
+void baked_light_baker_add_64i(int64_t *dst, int64_t value) {
- while(true) {
+ while (true) {
int64_t from = *dst;
- int64_t to = from+value;
- int64_t result = InterlockedCompareExchange64(dst,to,from);
- if (result==from)
+ int64_t to = from + value;
+ int64_t result = InterlockedCompareExchange64(dst, to, from);
+ if (result == from)
break;
}
}
-
#else
//in goder (the god of programmers) we trust
#warning seems this platform or compiler does not support safe cmpxchg, your baked lighting may be funny
-void baked_light_baker_add_64f(double *dst,double value) {
-
- *dst+=value;
+void baked_light_baker_add_64f(double *dst, double value) {
+ *dst += value;
}
-void baked_light_baker_add_64i(int64_t *dst,int64_t value) {
-
- *dst+=value;
+void baked_light_baker_add_64i(int64_t *dst, int64_t value) {
+ *dst += value;
}
#endif
diff --git a/editor/plugins/baked_light_editor_plugin.cpp b/editor/plugins/baked_light_editor_plugin.cpp
index 6a7e708b85..5ac4b54600 100644
--- a/editor/plugins/baked_light_editor_plugin.cpp
+++ b/editor/plugins/baked_light_editor_plugin.cpp
@@ -28,11 +28,10 @@
/*************************************************************************/
#include "baked_light_editor_plugin.h"
-#include "scene/gui/box_container.h"
-#include "scene/3d/mesh_instance.h"
#include "io/marshalls.h"
#include "io/resource_saver.h"
-
+#include "scene/3d/mesh_instance.h"
+#include "scene/gui/box_container.h"
#if 0
@@ -153,7 +152,6 @@ void BakedLightEditor::_notification(int p_option) {
it->create_from_image(img);
ResourceSaver::save("baked_octree.png",it);
-
#endif
@@ -375,5 +373,4 @@ BakedLightEditorPlugin::~BakedLightEditorPlugin()
{
}
-
#endif
diff --git a/editor/plugins/baked_light_editor_plugin.h b/editor/plugins/baked_light_editor_plugin.h
index a71de12bcc..036407a574 100644
--- a/editor/plugins/baked_light_editor_plugin.h
+++ b/editor/plugins/baked_light_editor_plugin.h
@@ -29,13 +29,11 @@
#ifndef BAKED_LIGHT_EDITOR_PLUGIN_H
#define BAKED_LIGHT_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "editor/plugins/baked_light_baker.h"
#include "scene/gui/spin_box.h"
-
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -117,4 +115,3 @@ public:
#endif // MULTIMESH_EDITOR_PLUGIN_H
#endif
-
diff --git a/editor/plugins/camera_editor_plugin.cpp b/editor/plugins/camera_editor_plugin.cpp
index 7073acd2c0..96b6da51fd 100644
--- a/editor/plugins/camera_editor_plugin.cpp
+++ b/editor/plugins/camera_editor_plugin.cpp
@@ -30,45 +30,41 @@
#include "spatial_editor_plugin.h"
-
void CameraEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
-/* case NOTIFICATION_PROCESS: {
+ /* case NOTIFICATION_PROCESS: {
if (preview->is_pressed() && node)
node->call("make_current");
} break;*/
}
-
}
void CameraEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
SpatialEditor::get_singleton()->set_custom_camera(NULL);
hide();
}
-
}
void CameraEditor::_pressed() {
- Node *sn = (node && preview->is_pressed())?node:NULL;
+ Node *sn = (node && preview->is_pressed()) ? node : NULL;
SpatialEditor::get_singleton()->set_custom_camera(sn);
}
void CameraEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_pressed"),&CameraEditor::_pressed);
-
+ ClassDB::bind_method(D_METHOD("_pressed"), &CameraEditor::_pressed);
}
void CameraEditor::edit(Node *p_camera) {
- node=p_camera;
+ node = p_camera;
if (!node) {
preview->set_pressed(false);
@@ -82,25 +78,22 @@ void CameraEditor::edit(Node *p_camera) {
}
}
-
CameraEditor::CameraEditor() {
- preview = memnew( Button );
+ preview = memnew(Button);
add_child(preview);
preview->set_text(TTR("Preview"));
preview->set_toggle_mode(true);
- preview->set_anchor(MARGIN_LEFT,Control::ANCHOR_END);
- preview->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END);
- preview->set_margin(MARGIN_LEFT,60);
- preview->set_margin(MARGIN_RIGHT,0);
- preview->set_margin(MARGIN_TOP,0);
- preview->set_margin(MARGIN_BOTTOM,10);
- preview->connect("pressed",this,"_pressed");
-
+ preview->set_anchor(MARGIN_LEFT, Control::ANCHOR_END);
+ preview->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
+ preview->set_margin(MARGIN_LEFT, 60);
+ preview->set_margin(MARGIN_RIGHT, 0);
+ preview->set_margin(MARGIN_TOP, 0);
+ preview->set_margin(MARGIN_BOTTOM, 10);
+ preview->connect("pressed", this, "_pressed");
}
-
void CameraEditorPlugin::edit(Object *p_object) {
SpatialEditor::get_singleton()->set_can_preview(p_object->cast_to<Camera>());
@@ -119,13 +112,12 @@ void CameraEditorPlugin::make_visible(bool p_visible) {
} else {
SpatialEditor::get_singleton()->set_can_preview(NULL);
}
-
}
CameraEditorPlugin::CameraEditorPlugin(EditorNode *p_node) {
- editor=p_node;
-/* camera_editor = memnew( CameraEditor );
+ editor = p_node;
+ /* camera_editor = memnew( CameraEditor );
editor->get_viewport()->add_child(camera_editor);
camera_editor->set_anchor(MARGIN_LEFT,Control::ANCHOR_END);
@@ -138,13 +130,7 @@ CameraEditorPlugin::CameraEditorPlugin(EditorNode *p_node) {
camera_editor->hide();
*/
-
-
}
-
-CameraEditorPlugin::~CameraEditorPlugin()
-{
+CameraEditorPlugin::~CameraEditorPlugin() {
}
-
-
diff --git a/editor/plugins/camera_editor_plugin.h b/editor/plugins/camera_editor_plugin.h
index b5817b9960..f23b0d5cc8 100644
--- a/editor/plugins/camera_editor_plugin.h
+++ b/editor/plugins/camera_editor_plugin.h
@@ -29,8 +29,8 @@
#ifndef CAMERA_EDITOR_PLUGIN_H
#define CAMERA_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/camera.h"
/**
@@ -39,32 +39,32 @@
class CameraEditor : public Control {
- GDCLASS(CameraEditor, Control );
+ GDCLASS(CameraEditor, Control);
Panel *panel;
- Button * preview;
+ Button *preview;
Node *node;
void _pressed();
+
protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
+public:
void edit(Node *p_camera);
CameraEditor();
};
class CameraEditorPlugin : public EditorPlugin {
- GDCLASS( CameraEditorPlugin, EditorPlugin );
+ GDCLASS(CameraEditorPlugin, EditorPlugin);
//CameraEditor *camera_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "Camera"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -73,7 +73,6 @@ public:
CameraEditorPlugin(EditorNode *p_node);
~CameraEditorPlugin();
-
};
#endif // CAMERA_EDITOR_PLUGIN_H
diff --git a/editor/plugins/canvas_item_editor_plugin.cpp b/editor/plugins/canvas_item_editor_plugin.cpp
index 1a0791d864..ebf2fa5a3a 100644
--- a/editor/plugins/canvas_item_editor_plugin.cpp
+++ b/editor/plugins/canvas_item_editor_plugin.cpp
@@ -28,37 +28,35 @@
/*************************************************************************/
#include "canvas_item_editor_plugin.h"
-#include "print_string.h"
+#include "editor/animation_editor.h"
#include "editor/editor_node.h"
+#include "editor/editor_settings.h"
+#include "editor/plugins/animation_player_editor_plugin.h"
+#include "editor/plugins/script_editor_plugin.h"
+#include "editor/script_editor_debugger.h"
+#include "global_config.h"
+#include "os/input.h"
#include "os/keyboard.h"
-#include "scene/main/viewport.h"
-#include "scene/main/canvas_layer.h"
-#include "scene/2d/sprite.h"
+#include "print_string.h"
#include "scene/2d/light_2d.h"
#include "scene/2d/particles_2d.h"
#include "scene/2d/polygon_2d.h"
#include "scene/2d/screen_button.h"
-#include "global_config.h"
-#include "os/input.h"
-#include "editor/editor_settings.h"
+#include "scene/2d/sprite.h"
#include "scene/gui/grid_container.h"
#include "scene/gui/patch_9_rect.h"
-#include "editor/animation_editor.h"
-#include "editor/plugins/animation_player_editor_plugin.h"
-#include "editor/script_editor_debugger.h"
-#include "editor/plugins/script_editor_plugin.h"
+#include "scene/main/canvas_layer.h"
+#include "scene/main/viewport.h"
#include "scene/resources/packed_scene.h"
-
#define MIN_ZOOM 0.01
#define MAX_ZOOM 100
-
class SnapDialog : public ConfirmationDialog {
- GDCLASS(SnapDialog,ConfirmationDialog);
+ GDCLASS(SnapDialog, ConfirmationDialog);
-friend class CanvasItemEditor;
+ friend class CanvasItemEditor;
SpinBox *grid_offset_x;
SpinBox *grid_offset_y;
@@ -68,7 +66,8 @@ friend class CanvasItemEditor;
SpinBox *rotation_step;
public:
- SnapDialog() : ConfirmationDialog() {
+ SnapDialog()
+ : ConfirmationDialog() {
const int SPIN_BOX_GRID_RANGE = 256;
const int SPIN_BOX_ROTATION_RANGE = 360;
Label *label;
@@ -78,71 +77,71 @@ public:
set_title(TTR("Configure Snap"));
get_ok()->set_text(TTR("Close"));
- container = memnew( VBoxContainer );
+ container = memnew(VBoxContainer);
add_child(container);
//set_child_rect(container);
- child_container = memnew( GridContainer );
+ child_container = memnew(GridContainer);
child_container->set_columns(3);
container->add_child(child_container);
- label = memnew( Label );
+ label = memnew(Label);
label->set_text(TTR("Grid Offset:"));
child_container->add_child(label);
label->set_h_size_flags(SIZE_EXPAND_FILL);
- grid_offset_x = memnew( SpinBox );
+ grid_offset_x = memnew(SpinBox);
grid_offset_x->set_min(-SPIN_BOX_GRID_RANGE);
grid_offset_x->set_max(SPIN_BOX_GRID_RANGE);
grid_offset_x->set_suffix("px");
child_container->add_child(grid_offset_x);
- grid_offset_y = memnew( SpinBox );
+ grid_offset_y = memnew(SpinBox);
grid_offset_y->set_min(-SPIN_BOX_GRID_RANGE);
grid_offset_y->set_max(SPIN_BOX_GRID_RANGE);
grid_offset_y->set_suffix("px");
child_container->add_child(grid_offset_y);
- label = memnew( Label );
+ label = memnew(Label);
label->set_text(TTR("Grid Step:"));
child_container->add_child(label);
label->set_h_size_flags(SIZE_EXPAND_FILL);
- grid_step_x = memnew( SpinBox );
+ grid_step_x = memnew(SpinBox);
grid_step_x->set_min(-SPIN_BOX_GRID_RANGE);
grid_step_x->set_max(SPIN_BOX_GRID_RANGE);
grid_step_x->set_suffix("px");
child_container->add_child(grid_step_x);
- grid_step_y = memnew( SpinBox );
+ grid_step_y = memnew(SpinBox);
grid_step_y->set_min(-SPIN_BOX_GRID_RANGE);
grid_step_y->set_max(SPIN_BOX_GRID_RANGE);
grid_step_y->set_suffix("px");
child_container->add_child(grid_step_y);
- container->add_child( memnew( HSeparator ) );
+ container->add_child(memnew(HSeparator));
- child_container = memnew( GridContainer );
+ child_container = memnew(GridContainer);
child_container->set_columns(2);
container->add_child(child_container);
- label = memnew( Label );
+ label = memnew(Label);
label->set_text(TTR("Rotation Offset:"));
child_container->add_child(label);
label->set_h_size_flags(SIZE_EXPAND_FILL);
- rotation_offset = memnew( SpinBox );
+ rotation_offset = memnew(SpinBox);
rotation_offset->set_min(-SPIN_BOX_ROTATION_RANGE);
rotation_offset->set_max(SPIN_BOX_ROTATION_RANGE);
rotation_offset->set_suffix("deg");
child_container->add_child(rotation_offset);
- label = memnew( Label );
+ label = memnew(Label);
label->set_text(TTR("Rotation Step:"));
child_container->add_child(label);
label->set_h_size_flags(SIZE_EXPAND_FILL);
- rotation_step = memnew( SpinBox );
+ rotation_step = memnew(SpinBox);
rotation_step->set_min(-SPIN_BOX_ROTATION_RANGE);
rotation_step->set_max(SPIN_BOX_ROTATION_RANGE);
rotation_step->set_suffix("deg");
@@ -168,12 +167,12 @@ public:
}
};
-void CanvasItemEditor::_edit_set_pivot(const Vector2& mouse_pos) {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+void CanvasItemEditor::_edit_set_pivot(const Vector2 &mouse_pos) {
+ List<Node *> &selection = editor_selection->get_selected_node_list();
undo_redo->create_action(TTR("Move Pivot"));
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Node2D *n2d = E->get()->cast_to<Node2D>();
@@ -184,31 +183,27 @@ void CanvasItemEditor::_edit_set_pivot(const Vector2& mouse_pos) {
Vector2 local_mouse_pos = n2d->get_canvas_transform().affine_inverse().xform(mouse_pos);
- Vector2 motion_ofs = gpos-local_mouse_pos;
+ Vector2 motion_ofs = gpos - local_mouse_pos;
- undo_redo->add_do_method(n2d,"set_global_pos",local_mouse_pos);
- undo_redo->add_do_method(n2d,"edit_set_pivot",offset+n2d->get_global_transform().affine_inverse().basis_xform(motion_ofs));
- undo_redo->add_undo_method(n2d,"set_global_pos",gpos);
- undo_redo->add_undo_method(n2d,"edit_set_pivot",offset);
- for(int i=0;i<n2d->get_child_count();i++) {
+ undo_redo->add_do_method(n2d, "set_global_pos", local_mouse_pos);
+ undo_redo->add_do_method(n2d, "edit_set_pivot", offset + n2d->get_global_transform().affine_inverse().basis_xform(motion_ofs));
+ undo_redo->add_undo_method(n2d, "set_global_pos", gpos);
+ undo_redo->add_undo_method(n2d, "edit_set_pivot", offset);
+ for (int i = 0; i < n2d->get_child_count(); i++) {
Node2D *n2dc = n2d->get_child(i)->cast_to<Node2D>();
if (!n2dc)
continue;
- undo_redo->add_do_method(n2dc,"set_global_pos",n2dc->get_global_position());
- undo_redo->add_undo_method(n2dc,"set_global_pos",n2dc->get_global_position());
-
+ undo_redo->add_do_method(n2dc, "set_global_pos", n2dc->get_global_position());
+ undo_redo->add_undo_method(n2dc, "set_global_pos", n2dc->get_global_position());
}
-
}
-
}
undo_redo->commit_action();
-
}
-void CanvasItemEditor::_unhandled_key_input(const InputEvent& p_ev) {
+void CanvasItemEditor::_unhandled_key_input(const InputEvent &p_ev) {
if (!is_visible_in_tree() || get_viewport()->gui_has_modal_stack())
return;
@@ -216,42 +211,37 @@ void CanvasItemEditor::_unhandled_key_input(const InputEvent& p_ev) {
if (p_ev.key.mod.control)
return;
- if (p_ev.key.pressed && !p_ev.key.echo && p_ev.key.scancode==KEY_V && drag==DRAG_NONE && can_move_pivot) {
+ if (p_ev.key.pressed && !p_ev.key.echo && p_ev.key.scancode == KEY_V && drag == DRAG_NONE && can_move_pivot) {
if (p_ev.key.mod.shift) {
//move drag pivot
- drag=DRAG_PIVOT;
+ drag = DRAG_PIVOT;
} else if (!Input::get_singleton()->is_mouse_button_pressed(0)) {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
Vector2 mouse_pos = viewport->get_local_mouse_pos();
if (selection.size() && viewport->get_rect().has_point(mouse_pos)) {
//just in case, make it work if over viewport
- mouse_pos=transform.affine_inverse().xform(mouse_pos);
- mouse_pos=snap_point(mouse_pos);
+ mouse_pos = transform.affine_inverse().xform(mouse_pos);
+ mouse_pos = snap_point(mouse_pos);
_edit_set_pivot(mouse_pos);
}
-
}
}
-
}
void CanvasItemEditor::_tool_select(int p_index) {
+ ToolButton *tb[TOOL_MAX] = { select_button, list_select_button, move_button, rotate_button, pivot_button, pan_button };
+ for (int i = 0; i < TOOL_MAX; i++) {
- ToolButton *tb[TOOL_MAX]={select_button,list_select_button,move_button,rotate_button,pivot_button,pan_button};
- for(int i=0;i<TOOL_MAX;i++) {
-
- tb[i]->set_pressed(i==p_index);
+ tb[i]->set_pressed(i == p_index);
}
-
viewport->update();
- tool=(Tool)p_index;
-
+ tool = (Tool)p_index;
}
Object *CanvasItemEditor::_get_editor_data(Object *p_what) {
@@ -260,7 +250,7 @@ Object *CanvasItemEditor::_get_editor_data(Object *p_what) {
if (!ci)
return NULL;
- return memnew( CanvasItemEditorSelectedItem );
+ return memnew(CanvasItemEditorSelectedItem);
}
inline float _snap_scalar(float p_offset, float p_step, bool p_snap_relative, float p_target, float p_start) {
@@ -286,89 +276,88 @@ float CanvasItemEditor::snap_angle(float p_target, float p_start) const {
Dictionary CanvasItemEditor::get_state() const {
Dictionary state;
- state["zoom"]=zoom;
- state["ofs"]=Point2(h_scroll->get_value(),v_scroll->get_value());
+ state["zoom"] = zoom;
+ state["ofs"] = Point2(h_scroll->get_value(), v_scroll->get_value());
//state["ofs"]=-transform.get_origin();
- state["snap_offset"]=snap_offset;
- state["snap_step"]=snap_step;
- state["snap_rotation_offset"]=snap_rotation_offset;
- state["snap_rotation_step"]=snap_rotation_step;
- state["snap_grid"]=snap_grid;
- state["snap_show_grid"]=snap_show_grid;
- state["snap_rotation"]=snap_rotation;
- state["snap_relative"]=snap_relative;
- state["snap_pixel"]=snap_pixel;
- state["skeleton_show_bones"]=skeleton_show_bones;
+ state["snap_offset"] = snap_offset;
+ state["snap_step"] = snap_step;
+ state["snap_rotation_offset"] = snap_rotation_offset;
+ state["snap_rotation_step"] = snap_rotation_step;
+ state["snap_grid"] = snap_grid;
+ state["snap_show_grid"] = snap_show_grid;
+ state["snap_rotation"] = snap_rotation;
+ state["snap_relative"] = snap_relative;
+ state["snap_pixel"] = snap_pixel;
+ state["skeleton_show_bones"] = skeleton_show_bones;
return state;
}
-void CanvasItemEditor::set_state(const Dictionary& p_state){
+void CanvasItemEditor::set_state(const Dictionary &p_state) {
- Dictionary state=p_state;
+ Dictionary state = p_state;
if (state.has("zoom")) {
- zoom=p_state["zoom"];
+ zoom = p_state["zoom"];
}
if (state.has("ofs")) {
_update_scrollbars(); // i wonder how safe is calling this here..
- Point2 ofs=p_state["ofs"];
+ Point2 ofs = p_state["ofs"];
h_scroll->set_value(ofs.x);
v_scroll->set_value(ofs.y);
}
if (state.has("snap_step")) {
- snap_step=state["snap_step"];
+ snap_step = state["snap_step"];
}
if (state.has("snap_offset")) {
- snap_offset=state["snap_offset"];
+ snap_offset = state["snap_offset"];
}
if (state.has("snap_rotation_step")) {
- snap_rotation_step=state["snap_rotation_step"];
+ snap_rotation_step = state["snap_rotation_step"];
}
if (state.has("snap_rotation_offset")) {
- snap_rotation_offset=state["snap_rotation_offset"];
+ snap_rotation_offset = state["snap_rotation_offset"];
}
if (state.has("snap_grid")) {
- snap_grid=state["snap_grid"];
+ snap_grid = state["snap_grid"];
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE);
- edit_menu->get_popup()->set_item_checked(idx,snap_grid);
+ edit_menu->get_popup()->set_item_checked(idx, snap_grid);
}
if (state.has("snap_show_grid")) {
- snap_show_grid=state["snap_show_grid"];
+ snap_show_grid = state["snap_show_grid"];
int idx = edit_menu->get_popup()->get_item_index(SNAP_SHOW_GRID);
- edit_menu->get_popup()->set_item_checked(idx,snap_show_grid);
+ edit_menu->get_popup()->set_item_checked(idx, snap_show_grid);
}
if (state.has("snap_rotation")) {
- snap_rotation=state["snap_rotation"];
+ snap_rotation = state["snap_rotation"];
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE_ROTATION);
- edit_menu->get_popup()->set_item_checked(idx,snap_rotation);
+ edit_menu->get_popup()->set_item_checked(idx, snap_rotation);
}
if (state.has("snap_relative")) {
- snap_relative=state["snap_relative"];
+ snap_relative = state["snap_relative"];
int idx = edit_menu->get_popup()->get_item_index(SNAP_RELATIVE);
- edit_menu->get_popup()->set_item_checked(idx,snap_relative);
+ edit_menu->get_popup()->set_item_checked(idx, snap_relative);
}
if (state.has("snap_pixel")) {
- snap_pixel=state["snap_pixel"];
+ snap_pixel = state["snap_pixel"];
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE_PIXEL);
- edit_menu->get_popup()->set_item_checked(idx,snap_pixel);
+ edit_menu->get_popup()->set_item_checked(idx, snap_pixel);
}
if (state.has("skeleton_show_bones")) {
- skeleton_show_bones=state["skeleton_show_bones"];
+ skeleton_show_bones = state["skeleton_show_bones"];
int idx = skeleton_menu->get_item_index(SKELETON_SHOW_BONES);
- skeleton_menu->set_item_checked(idx,skeleton_show_bones);
+ skeleton_menu->set_item_checked(idx, skeleton_show_bones);
}
}
-
void CanvasItemEditor::_add_canvas_item(CanvasItem *p_canvas_item) {
editor_selection->add_node(p_canvas_item);
@@ -388,7 +377,6 @@ void CanvasItemEditor::_remove_canvas_item(CanvasItem *p_canvas_item) {
p_canvas_item->disconnect("hide",this,"_visibility_changed");
canvas_items.erase(p_canvas_item);
#endif
-
}
void CanvasItemEditor::_clear_canvas_items() {
@@ -413,7 +401,6 @@ void CanvasItemEditor::_visibility_changed(ObjectID p_canvas_item) {
#endif
}
-
void CanvasItemEditor::_node_removed(Node *p_node) {
#if 0
CanvasItem *canvas_item = (CanvasItem*)p_node; //not a good cast, but safe
@@ -434,32 +421,31 @@ void CanvasItemEditor::_keying_changed() {
bool CanvasItemEditor::_is_part_of_subscene(CanvasItem *p_item) {
- Node* scene_node = get_tree()->get_edited_scene_root();
- Node* item_owner = p_item->get_owner();
+ Node *scene_node = get_tree()->get_edited_scene_root();
+ Node *item_owner = p_item->get_owner();
- return item_owner && item_owner!=scene_node && p_item!=scene_node && item_owner->get_filename()!="";
+ return item_owner && item_owner != scene_node && p_item != scene_node && item_owner->get_filename() != "";
}
// slow but modern computers should have no problem
-CanvasItem* CanvasItemEditor::_select_canvas_item_at_pos(const Point2& p_pos,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform) {
+CanvasItem *CanvasItemEditor::_select_canvas_item_at_pos(const Point2 &p_pos, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform) {
if (!p_node)
return NULL;
if (p_node->cast_to<Viewport>())
return NULL;
- CanvasItem *c=p_node->cast_to<CanvasItem>();
-
+ CanvasItem *c = p_node->cast_to<CanvasItem>();
- for (int i=p_node->get_child_count()-1;i>=0;i--) {
+ for (int i = p_node->get_child_count() - 1; i >= 0; i--) {
- CanvasItem *r=NULL;
+ CanvasItem *r = NULL;
if (c && !c->is_set_as_toplevel())
- r=_select_canvas_item_at_pos(p_pos,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform);
+ r = _select_canvas_item_at_pos(p_pos, p_node->get_child(i), p_parent_xform * c->get_transform(), p_canvas_xform);
else {
CanvasLayer *cl = p_node->cast_to<CanvasLayer>();
- r=_select_canvas_item_at_pos(p_pos,p_node->get_child(i),transform ,cl ? cl->get_transform() : p_canvas_xform); //use base transform
+ r = _select_canvas_item_at_pos(p_pos, p_node->get_child(i), transform, cl ? cl->get_transform() : p_canvas_xform); //use base transform
}
if (r)
@@ -471,79 +457,73 @@ CanvasItem* CanvasItemEditor::_select_canvas_item_at_pos(const Point2& p_pos,Nod
Rect2 rect = c->get_item_rect();
Point2 local_pos = (p_parent_xform * p_canvas_xform * c->get_transform()).affine_inverse().xform(p_pos);
-
if (rect.has_point(local_pos))
return c;
-
}
return NULL;
}
-void CanvasItemEditor::_find_canvas_items_at_pos(const Point2 &p_pos,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform, Vector<_SelectResult> &r_items) {
+void CanvasItemEditor::_find_canvas_items_at_pos(const Point2 &p_pos, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform, Vector<_SelectResult> &r_items) {
if (!p_node)
return;
if (p_node->cast_to<Viewport>())
return;
- CanvasItem *c=p_node->cast_to<CanvasItem>();
+ CanvasItem *c = p_node->cast_to<CanvasItem>();
- for (int i=p_node->get_child_count()-1;i>=0;i--) {
+ for (int i = p_node->get_child_count() - 1; i >= 0; i--) {
if (c && !c->is_set_as_toplevel())
- _find_canvas_items_at_pos(p_pos,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform, r_items);
+ _find_canvas_items_at_pos(p_pos, p_node->get_child(i), p_parent_xform * c->get_transform(), p_canvas_xform, r_items);
else {
CanvasLayer *cl = p_node->cast_to<CanvasLayer>();
- _find_canvas_items_at_pos(p_pos,p_node->get_child(i),transform ,cl ? cl->get_transform() : p_canvas_xform, r_items); //use base transform
+ _find_canvas_items_at_pos(p_pos, p_node->get_child(i), transform, cl ? cl->get_transform() : p_canvas_xform, r_items); //use base transform
}
}
-
if (c && c->is_visible_in_tree() && !c->has_meta("_edit_lock_") && !c->cast_to<CanvasLayer>()) {
Rect2 rect = c->get_item_rect();
Point2 local_pos = (p_parent_xform * p_canvas_xform * c->get_transform()).affine_inverse().xform(p_pos);
-
if (rect.has_point(local_pos)) {
- Node2D *node=c->cast_to<Node2D>();
+ Node2D *node = c->cast_to<Node2D>();
_SelectResult res;
- res.item=c;
- res.z=node?node->get_z():0;
- res.has_z=node;
+ res.item = c;
+ res.z = node ? node->get_z() : 0;
+ res.has_z = node;
r_items.push_back(res);
}
-
}
return;
}
-void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2& p_rect,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform,List<CanvasItem*> *r_items) {
+void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2 &p_rect, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform, List<CanvasItem *> *r_items) {
if (!p_node)
return;
if (p_node->cast_to<Viewport>())
return;
- CanvasItem *c=p_node->cast_to<CanvasItem>();
-
+ CanvasItem *c = p_node->cast_to<CanvasItem>();
- bool inherited=p_node!=get_tree()->get_edited_scene_root() && p_node->get_filename()!="";
- bool editable=false;
- if (inherited){
- editable=EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node);
+ bool inherited = p_node != get_tree()->get_edited_scene_root() && p_node->get_filename() != "";
+ bool editable = false;
+ if (inherited) {
+ editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node);
}
- bool lock_children=p_node->has_meta("_edit_group_") && p_node->get_meta("_edit_group_");
+ bool lock_children = p_node->has_meta("_edit_group_") && p_node->get_meta("_edit_group_");
if (!lock_children && (!inherited || editable)) {
- for (int i=p_node->get_child_count()-1;i>=0;i--) {
+ for (int i = p_node->get_child_count() - 1; i >= 0; i--) {
if (c && !c->is_set_as_toplevel())
- _find_canvas_items_at_rect(p_rect,p_node->get_child(i),p_parent_xform * c->get_transform(),p_canvas_xform,r_items);
+ _find_canvas_items_at_rect(p_rect, p_node->get_child(i), p_parent_xform * c->get_transform(), p_canvas_xform, r_items);
else {
CanvasLayer *cl = p_node->cast_to<CanvasLayer>();
- _find_canvas_items_at_rect(p_rect,p_node->get_child(i),transform,cl?cl->get_transform():p_canvas_xform,r_items);
+ _find_canvas_items_at_rect(p_rect, p_node->get_child(i), transform, cl ? cl->get_transform() : p_canvas_xform, r_items);
}
}
}
@@ -553,17 +533,14 @@ void CanvasItemEditor::_find_canvas_items_at_rect(const Rect2& p_rect,Node* p_no
Rect2 rect = c->get_item_rect();
Transform2D xform = p_parent_xform * p_canvas_xform * c->get_transform();
- if ( p_rect.has_point( xform.xform( rect.pos ) ) &&
- p_rect.has_point( xform.xform( rect.pos+Vector2(rect.size.x,0) ) ) &&
- p_rect.has_point( xform.xform( rect.pos+Vector2(rect.size.x,rect.size.y) ) ) &&
- p_rect.has_point( xform.xform( rect.pos+Vector2(0,rect.size.y) ) ) ) {
+ if (p_rect.has_point(xform.xform(rect.pos)) &&
+ p_rect.has_point(xform.xform(rect.pos + Vector2(rect.size.x, 0))) &&
+ p_rect.has_point(xform.xform(rect.pos + Vector2(rect.size.x, rect.size.y))) &&
+ p_rect.has_point(xform.xform(rect.pos + Vector2(0, rect.size.y)))) {
r_items->push_back(c);
-
}
}
-
-
}
bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_append, bool p_drag) {
@@ -574,10 +551,10 @@ bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_appe
if (!item) {
if (p_drag) {
- drag_from=transform.affine_inverse().xform(p_click_pos);
+ drag_from = transform.affine_inverse().xform(p_click_pos);
- box_selecting=true;
- box_selecting_to=drag_from;
+ box_selecting = true;
+ box_selecting_to = drag_from;
}
return false; //nothing to add
@@ -590,7 +567,6 @@ bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_appe
viewport->update();
return false;
-
}
_append_canvas_item(item);
viewport->update();
@@ -605,10 +581,10 @@ bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_appe
editor_selection->clear();
if (p_drag) {
- drag_from=transform.affine_inverse().xform(p_click_pos);
+ drag_from = transform.affine_inverse().xform(p_click_pos);
- box_selecting=true;
- box_selecting_to=drag_from;
+ box_selecting = true;
+ box_selecting_to = drag_from;
}
viewport->update();
@@ -621,88 +597,83 @@ bool CanvasItemEditor::_select(CanvasItem *item, Point2 p_click_pos, bool p_appe
editor_selection->add_node(item);
//reselect
if (get_tree()->is_editor_hint()) {
- editor->call("edit_node",item);
+ editor->call("edit_node", item);
}
-
}
if (p_drag) {
//prepare to move!
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
- se->undo_state=canvas_item->edit_get_state();
+ se->undo_state = canvas_item->edit_get_state();
if (canvas_item->cast_to<Node2D>())
- se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot();
-
+ se->undo_pivot = canvas_item->cast_to<Node2D>()->edit_get_pivot();
}
- drag=DRAG_ALL;
- drag_from=transform.affine_inverse().xform(p_click_pos);
- drag_point_from=_find_topleftmost_point();
+ drag = DRAG_ALL;
+ drag_from = transform.affine_inverse().xform(p_click_pos);
+ drag_point_from = _find_topleftmost_point();
}
viewport->update();
return true;
-
}
}
-void CanvasItemEditor::_key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE p_move_mode) {
-
+void CanvasItemEditor::_key_move(const Vector2 &p_dir, bool p_snap, KeyMoveMODE p_move_mode) {
- if (drag!=DRAG_NONE)
+ if (drag != DRAG_NONE)
return;
if (editor_selection->get_selected_node_list().empty())
return;
- undo_redo->create_action(TTR("Move Action"),UndoRedo::MERGE_ENDS);
+ undo_redo->create_action(TTR("Move Action"), UndoRedo::MERGE_ENDS);
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
if (canvas_item->has_meta("_edit_lock_"))
continue;
-
Vector2 drag = p_dir;
if (p_snap)
- drag*=snap_step;
+ drag *= snap_step;
- undo_redo->add_undo_method(canvas_item,"edit_set_state",canvas_item->edit_get_state());
+ undo_redo->add_undo_method(canvas_item, "edit_set_state", canvas_item->edit_get_state());
- if (p_move_mode == MOVE_VIEW_BASE) {
+ if (p_move_mode == MOVE_VIEW_BASE) {
// drag = transform.affine_inverse().basis_xform(p_dir); // zoom sensitive
drag = canvas_item->get_global_transform_with_canvas().affine_inverse().basis_xform(drag);
Rect2 local_rect = canvas_item->get_item_rect();
- local_rect.pos+=drag;
- undo_redo->add_do_method(canvas_item,"edit_set_rect",local_rect);
+ local_rect.pos += drag;
+ undo_redo->add_do_method(canvas_item, "edit_set_rect", local_rect);
} else { // p_move_mode==MOVE_LOCAL_BASE || p_move_mode==MOVE_LOCAL_WITH_ROT
@@ -710,14 +681,14 @@ void CanvasItemEditor::_key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE
if (p_move_mode == MOVE_LOCAL_WITH_ROT) {
Transform2D m;
- m.rotate( node_2d->get_rotation() );
+ m.rotate(node_2d->get_rotation());
drag = m.xform(drag);
}
node_2d->set_position(node_2d->get_position() + drag);
} else if (Control *control = canvas_item->cast_to<Control>()) {
- control->set_pos(control->get_pos()+drag);
+ control->set_pos(control->get_pos() + drag);
}
}
}
@@ -727,53 +698,44 @@ void CanvasItemEditor::_key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE
Point2 CanvasItemEditor::_find_topleftmost_point() {
-
-
- Vector2 tl=Point2(1e10,1e10);
+ Vector2 tl = Point2(1e10, 1e10);
Rect2 r2;
- r2.pos=tl;
-
+ r2.pos = tl;
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
-
-
- Rect2 rect=canvas_item->get_item_rect();
- Transform2D xform=canvas_item->get_global_transform_with_canvas();
+ Rect2 rect = canvas_item->get_item_rect();
+ Transform2D xform = canvas_item->get_global_transform_with_canvas();
r2.expand_to(xform.xform(rect.pos));
- r2.expand_to(xform.xform(rect.pos+Vector2(rect.size.x,0)));
- r2.expand_to(xform.xform(rect.pos+rect.size));
- r2.expand_to(xform.xform(rect.pos+Vector2(0,rect.size.y)));
-
+ r2.expand_to(xform.xform(rect.pos + Vector2(rect.size.x, 0)));
+ r2.expand_to(xform.xform(rect.pos + rect.size));
+ r2.expand_to(xform.xform(rect.pos + Vector2(0, rect.size.y)));
}
return r2.pos;
}
-
-
int CanvasItemEditor::get_item_count() {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- int ic=0;
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ int ic = 0;
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
ic++;
@@ -784,55 +746,54 @@ int CanvasItemEditor::get_item_count() {
CanvasItem *CanvasItemEditor::get_single_item() {
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- Map<Node*,Object*> &selection = editor_selection->get_selection();
-
- CanvasItem *single_item=NULL;
+ CanvasItem *single_item = NULL;
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
if (single_item)
return NULL; //morethan one
- single_item=canvas_item;
+ single_item = canvas_item;
};
return single_item;
}
-CanvasItemEditor::DragType CanvasItemEditor::_find_drag_type(const Transform2D& p_xform, const Rect2& p_local_rect, const Point2& p_click, Vector2& r_point) {
+CanvasItemEditor::DragType CanvasItemEditor::_find_drag_type(const Transform2D &p_xform, const Rect2 &p_local_rect, const Point2 &p_click, Vector2 &r_point) {
CanvasItem *canvas_item = get_single_item();
- ERR_FAIL_COND_V(!canvas_item,DRAG_NONE);
+ ERR_FAIL_COND_V(!canvas_item, DRAG_NONE);
- Rect2 rect=canvas_item->get_item_rect();
- Transform2D xforml=canvas_item->get_global_transform_with_canvas();
- Transform2D xform=transform * xforml;
+ Rect2 rect = canvas_item->get_item_rect();
+ Transform2D xforml = canvas_item->get_global_transform_with_canvas();
+ Transform2D xform = transform * xforml;
- Vector2 endpoints[4]={
+ Vector2 endpoints[4] = {
xform.xform(rect.pos),
- xform.xform(rect.pos+Vector2(rect.size.x,0)),
- xform.xform(rect.pos+rect.size),
- xform.xform(rect.pos+Vector2(0,rect.size.y))
+ xform.xform(rect.pos + Vector2(rect.size.x, 0)),
+ xform.xform(rect.pos + rect.size),
+ xform.xform(rect.pos + Vector2(0, rect.size.y))
};
- Vector2 endpointsl[4]={
+ Vector2 endpointsl[4] = {
xforml.xform(rect.pos),
- xforml.xform(rect.pos+Vector2(rect.size.x,0)),
- xforml.xform(rect.pos+rect.size),
- xforml.xform(rect.pos+Vector2(0,rect.size.y))
+ xforml.xform(rect.pos + Vector2(rect.size.x, 0)),
+ xforml.xform(rect.pos + rect.size),
+ xforml.xform(rect.pos + Vector2(0, rect.size.y))
};
- DragType dragger[]={
+ DragType dragger[] = {
DRAG_TOP_LEFT,
DRAG_TOP,
DRAG_TOP_RIGHT,
@@ -843,34 +804,32 @@ CanvasItemEditor::DragType CanvasItemEditor::_find_drag_type(const Transform2D&
DRAG_LEFT
};
- float radius = (select_handle->get_size().width/2)*1.5;
+ float radius = (select_handle->get_size().width / 2) * 1.5;
//try draggers
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- int prev = (i+3)%4;
- int next = (i+1)%4;
+ int prev = (i + 3) % 4;
+ int next = (i + 1) % 4;
- r_point=endpointsl[i];
+ r_point = endpointsl[i];
Vector2 ofs = ((endpoints[i] - endpoints[prev]).normalized() + ((endpoints[i] - endpoints[next]).normalized())).normalized();
- ofs*=1.4144*(select_handle->get_size().width/2);
+ ofs *= 1.4144 * (select_handle->get_size().width / 2);
- ofs+=endpoints[i];
+ ofs += endpoints[i];
- if (ofs.distance_to(p_click)<radius)
- return dragger[i*2];
+ if (ofs.distance_to(p_click) < radius)
+ return dragger[i * 2];
- ofs = (endpoints[i]+endpoints[next])/2;
- ofs += (endpoints[next]-endpoints[i]).tangent().normalized()*(select_handle->get_size().width/2);
+ ofs = (endpoints[i] + endpoints[next]) / 2;
+ ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2);
- r_point=(endpointsl[i]+endpointsl[next])/2;
-
-
- if (ofs.distance_to(p_click)<radius)
- return dragger[i*2+1];
+ r_point = (endpointsl[i] + endpointsl[next]) / 2;
+ if (ofs.distance_to(p_click) < radius)
+ return dragger[i * 2 + 1];
}
/*
@@ -884,70 +843,66 @@ CanvasItemEditor::DragType CanvasItemEditor::_find_drag_type(const Transform2D&
return DRAG_NONE;
}
-void CanvasItemEditor::incbeg(float& beg,float &end, float inc, float minsize,bool p_symmetric) {
+void CanvasItemEditor::incbeg(float &beg, float &end, float inc, float minsize, bool p_symmetric) {
- if (minsize<0) {
+ if (minsize < 0) {
- beg+=inc;
+ beg += inc;
if (p_symmetric)
- end-=inc;
+ end -= inc;
} else {
if (p_symmetric) {
- beg+=inc;
- end-=inc;
- if (end-beg < minsize) {
- float center = (beg+end)/2.0;
- beg=center-minsize/2.0;
- end=center+minsize/2.0;
+ beg += inc;
+ end -= inc;
+ if (end - beg < minsize) {
+ float center = (beg + end) / 2.0;
+ beg = center - minsize / 2.0;
+ end = center + minsize / 2.0;
}
} else {
- if (end-(beg+inc) < minsize)
- beg=end-minsize;
+ if (end - (beg + inc) < minsize)
+ beg = end - minsize;
else
- beg+=inc;
+ beg += inc;
}
-
}
}
-void CanvasItemEditor::incend(float &beg,float& end, float inc, float minsize,bool p_symmetric) {
+void CanvasItemEditor::incend(float &beg, float &end, float inc, float minsize, bool p_symmetric) {
- if (minsize<0) {
+ if (minsize < 0) {
- end+=inc;
+ end += inc;
if (p_symmetric)
- beg-=inc;
+ beg -= inc;
} else {
if (p_symmetric) {
- end+=inc;
- beg-=inc;
- if (end-beg < minsize) {
- float center = (beg+end)/2.0;
- beg=center-minsize/2.0;
- end=center+minsize/2.0;
+ end += inc;
+ beg -= inc;
+ if (end - beg < minsize) {
+ float center = (beg + end) / 2.0;
+ beg = center - minsize / 2.0;
+ end = center + minsize / 2.0;
}
} else {
- if ((end+inc)-beg < minsize)
- end=beg+minsize;
+ if ((end + inc) - beg < minsize)
+ end = beg + minsize;
else
- end+=inc;
+ end += inc;
}
-
}
}
void CanvasItemEditor::_append_canvas_item(CanvasItem *c) {
editor_selection->add_node(c);
-
}
-
void CanvasItemEditor::_snap_changed() {
((SnapDialog *)snap_dialog)->get_fields(snap_offset, snap_step, snap_rotation_offset, snap_rotation_step);
viewport->update();
@@ -958,16 +913,16 @@ void CanvasItemEditor::_dialog_value_changed(double) {
if (updating_value_dialog)
return;
- switch(last_option) {
+ switch (last_option) {
case ZOOM_SET: {
- zoom=dialog_val->get_value()/100.0;
+ zoom = dialog_val->get_value() / 100.0;
_update_scroll(0);
viewport->update();
} break;
- default:{}
+ default: {}
}
}
@@ -976,7 +931,7 @@ void CanvasItemEditor::_selection_result_pressed(int p_result) {
if (selection_results.size() <= p_result)
return;
- CanvasItem *item=selection_results[p_result].item;
+ CanvasItem *item = selection_results[p_result].item;
if (item)
_select(item, Point2(), additive_selection, false);
@@ -989,31 +944,28 @@ void CanvasItemEditor::_selection_menu_hide() {
selection_menu->set_size(Vector2(0, 0));
}
-bool CanvasItemEditor::get_remove_list(List<Node*> *p_list) {
+bool CanvasItemEditor::get_remove_list(List<Node *> *p_list) {
-
- return false;//!p_list->empty();
+ return false; //!p_list->empty();
}
+void CanvasItemEditor::_list_select(const InputEventMouseButton &b) {
-void CanvasItemEditor::_list_select(const InputEventMouseButton& b) {
-
- Point2 click=Point2(b.x,b.y);
+ Point2 click = Point2(b.x, b.y);
- Node* scene = editor->get_edited_scene();
+ Node *scene = editor->get_edited_scene();
if (!scene)
return;
- _find_canvas_items_at_pos(click, scene,transform,Transform2D(), selection_results);
+ _find_canvas_items_at_pos(click, scene, transform, Transform2D(), selection_results);
- for(int i=0;i<selection_results.size();i++) {
- CanvasItem *item=selection_results[i].item;
- if (item!=scene && item->get_owner()!=scene && !scene->is_editable_instance(item->get_owner())) {
+ for (int i = 0; i < selection_results.size(); i++) {
+ CanvasItem *item = selection_results[i].item;
+ if (item != scene && item->get_owner() != scene && !scene->is_editable_instance(item->get_owner())) {
//invalid result
selection_results.remove(i);
i--;
}
-
}
if (selection_results.size() == 1) {
@@ -1021,7 +973,7 @@ void CanvasItemEditor::_list_select(const InputEventMouseButton& b) {
CanvasItem *item = selection_results[0].item;
selection_results.clear();
- additive_selection=b.mod.shift;
+ additive_selection = b.mod.shift;
if (!_select(item, click, additive_selection, false))
return;
@@ -1030,50 +982,47 @@ void CanvasItemEditor::_list_select(const InputEventMouseButton& b) {
selection_results.sort();
NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
- StringName root_name = root_path.get_name(root_path.get_name_count()-1);
+ StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
for (int i = 0; i < selection_results.size(); i++) {
- CanvasItem *item=selection_results[i].item;
-
+ CanvasItem *item = selection_results[i].item;
Ref<Texture> icon;
if (item->has_meta("_editor_icon"))
- icon=item->get_meta("_editor_icon");
+ icon = item->get_meta("_editor_icon");
else
- icon=get_icon( has_icon(item->get_class(),"EditorIcons")?item->get_class():String("Object"),"EditorIcons");
+ icon = get_icon(has_icon(item->get_class(), "EditorIcons") ? item->get_class() : String("Object"), "EditorIcons");
- String node_path="/"+root_name+"/"+root_path.rel_path_to(item->get_path());
+ String node_path = "/" + root_name + "/" + root_path.rel_path_to(item->get_path());
selection_menu->add_item(item->get_name());
- selection_menu->set_item_icon(i, icon );
+ selection_menu->set_item_icon(i, icon);
selection_menu->set_item_metadata(i, node_path);
- selection_menu->set_item_tooltip(i,String(item->get_name())+
- "\nType: "+item->get_class()+"\nPath: "+node_path);
+ selection_menu->set_item_tooltip(i, String(item->get_name()) +
+ "\nType: " + item->get_class() + "\nPath: " + node_path);
}
- additive_selection=b.mod.shift;
+ additive_selection = b.mod.shift;
- selection_menu->set_global_pos(Vector2( b.global_x, b.global_y ));
+ selection_menu->set_global_pos(Vector2(b.global_x, b.global_y));
selection_menu->popup();
selection_menu->call_deferred("grab_click_focus");
selection_menu->set_invalidate_click_until_motion();
-
return;
}
-
}
-void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
+void CanvasItemEditor::_viewport_gui_input(const InputEvent &p_event) {
- {
+ {
EditorNode *en = editor;
EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
if (!over_plugin_list->empty()) {
- bool discard = over_plugin_list->forward_gui_input(transform,p_event);
+ bool discard = over_plugin_list->forward_gui_input(transform, p_event);
if (discard) {
accept_event();
return;
@@ -1081,42 +1030,40 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
}
}
+ if (p_event.type == InputEvent::MOUSE_BUTTON) {
- if (p_event.type==InputEvent::MOUSE_BUTTON) {
-
- const InputEventMouseButton &b=p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
+ if (b.button_index == BUTTON_WHEEL_DOWN) {
- if (b.button_index==BUTTON_WHEEL_DOWN) {
-
- if (zoom<MIN_ZOOM)
+ if (zoom < MIN_ZOOM)
return;
- float prev_zoom=zoom;
- zoom=zoom*0.95;
+ float prev_zoom = zoom;
+ zoom = zoom * 0.95;
{
- Point2 ofs(b.x,b.y);
- ofs = ofs/prev_zoom - ofs/zoom;
- h_scroll->set_value( h_scroll->get_value() + ofs.x );
- v_scroll->set_value( v_scroll->get_value() + ofs.y );
+ Point2 ofs(b.x, b.y);
+ ofs = ofs / prev_zoom - ofs / zoom;
+ h_scroll->set_value(h_scroll->get_value() + ofs.x);
+ v_scroll->set_value(v_scroll->get_value() + ofs.y);
}
_update_scroll(0);
viewport->update();
return;
}
- if (b.button_index==BUTTON_WHEEL_UP) {
+ if (b.button_index == BUTTON_WHEEL_UP) {
- if (zoom>MAX_ZOOM)
+ if (zoom > MAX_ZOOM)
return;
- float prev_zoom=zoom;
- zoom=zoom*(1.0/0.95);
+ float prev_zoom = zoom;
+ zoom = zoom * (1.0 / 0.95);
{
- Point2 ofs(b.x,b.y);
- ofs = ofs/prev_zoom - ofs/zoom;
- h_scroll->set_value( h_scroll->get_value() + ofs.x );
- v_scroll->set_value( v_scroll->get_value() + ofs.y );
+ Point2 ofs(b.x, b.y);
+ ofs = ofs / prev_zoom - ofs / zoom;
+ h_scroll->set_value(h_scroll->get_value() + ofs.x);
+ v_scroll->set_value(v_scroll->get_value() + ofs.y);
}
_update_scroll(0);
@@ -1124,21 +1071,20 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
return;
}
- if (b.button_index==BUTTON_RIGHT) {
-
+ if (b.button_index == BUTTON_RIGHT) {
- if (b.pressed && (tool==TOOL_SELECT && b.mod.alt)) {
+ if (b.pressed && (tool == TOOL_SELECT && b.mod.alt)) {
_list_select(b);
return;
}
- if (get_item_count() > 0 && drag!=DRAG_NONE) {
+ if (get_item_count() > 0 && drag != DRAG_NONE) {
//cancel drag
if (bone_ik_list.size()) {
- for(List<BoneIK>::Element *E=bone_ik_list.back();E;E=E->prev()) {
+ for (List<BoneIK>::Element *E = bone_ik_list.back(); E; E = E->prev()) {
E->get().node->edit_set_state(E->get().orig_state);
}
@@ -1147,35 +1093,32 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
} else {
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- List<Node*> &selection = editor_selection->get_selected_node_list();
-
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
canvas_item->edit_set_state(se->undo_state);
if (canvas_item->cast_to<Node2D>())
canvas_item->cast_to<Node2D>()->edit_set_pivot(se->undo_pivot);
-
}
}
- drag=DRAG_NONE;
+ drag = DRAG_NONE;
viewport->update();
- can_move_pivot=false;
+ can_move_pivot = false;
} else if (box_selecting) {
- box_selecting=false;
+ box_selecting = false;
viewport->update();
} else if (b.pressed) {
#if 0
@@ -1193,49 +1136,44 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
return;
*/
- if (b.button_index==BUTTON_LEFT && tool==TOOL_LIST_SELECT) {
+ if (b.button_index == BUTTON_LEFT && tool == TOOL_LIST_SELECT) {
if (b.pressed)
_list_select(b);
return;
}
-
- if (b.button_index==BUTTON_LEFT && tool==TOOL_EDIT_PIVOT) {
+ if (b.button_index == BUTTON_LEFT && tool == TOOL_EDIT_PIVOT) {
if (b.pressed) {
- Point2 mouse_pos(b.x,b.y);
- mouse_pos=transform.affine_inverse().xform(mouse_pos);
- mouse_pos=snap_point(mouse_pos);
+ Point2 mouse_pos(b.x, b.y);
+ mouse_pos = transform.affine_inverse().xform(mouse_pos);
+ mouse_pos = snap_point(mouse_pos);
_edit_set_pivot(mouse_pos);
}
return;
}
-
-
- if (tool==TOOL_PAN || b.button_index!=BUTTON_LEFT || Input::get_singleton()->is_key_pressed(KEY_SPACE))
+ if (tool == TOOL_PAN || b.button_index != BUTTON_LEFT || Input::get_singleton()->is_key_pressed(KEY_SPACE))
return;
if (!b.pressed) {
- if (drag!=DRAG_NONE) {
+ if (drag != DRAG_NONE) {
if (undo_redo) {
-
if (bone_ik_list.size()) {
-
undo_redo->create_action(TTR("Edit IK Chain"));
- for(List<BoneIK>::Element *E=bone_ik_list.back();E;E=E->prev()) {
+ for (List<BoneIK>::Element *E = bone_ik_list.back(); E; E = E->prev()) {
- undo_redo->add_do_method(E->get().node,"edit_set_state",E->get().node->edit_get_state());
- undo_redo->add_undo_method(E->get().node,"edit_set_state",E->get().orig_state);
+ undo_redo->add_do_method(E->get().node, "edit_set_state", E->get().node->edit_get_state());
+ undo_redo->add_undo_method(E->get().node, "edit_set_state", E->get().orig_state);
}
- undo_redo->add_do_method(viewport,"update");
- undo_redo->add_undo_method(viewport,"update");
+ undo_redo->add_do_method(viewport, "update");
+ undo_redo->add_undo_method(viewport, "update");
bone_ik_list.clear();
@@ -1244,29 +1182,28 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
undo_redo->create_action(TTR("Edit CanvasItem"));
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- List<Node*> &selection = editor_selection->get_selected_node_list();
-
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
- Variant state=canvas_item->edit_get_state();
- undo_redo->add_do_method(canvas_item,"edit_set_state",state);
- undo_redo->add_undo_method(canvas_item,"edit_set_state",se->undo_state);
+ Variant state = canvas_item->edit_get_state();
+ undo_redo->add_do_method(canvas_item, "edit_set_state", state);
+ undo_redo->add_undo_method(canvas_item, "edit_set_state", se->undo_state);
if (canvas_item->cast_to<Node2D>()) {
Node2D *pvt = canvas_item->cast_to<Node2D>();
if (pvt->edit_has_pivot()) {
- undo_redo->add_do_method(canvas_item,"edit_set_pivot",pvt->edit_get_pivot());
- undo_redo->add_undo_method(canvas_item,"edit_set_pivot",se->undo_pivot);
+ undo_redo->add_do_method(canvas_item, "edit_set_pivot", pvt->edit_get_pivot());
+ undo_redo->add_undo_method(canvas_item, "edit_set_pivot", se->undo_pivot);
}
}
}
@@ -1274,10 +1211,9 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
}
}
- drag=DRAG_NONE;
+ drag = DRAG_NONE;
viewport->update();
- can_move_pivot=false;
-
+ can_move_pivot = false;
}
if (box_selecting) {
@@ -1286,110 +1222,102 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
if ( box_selection_end() ) return;
#endif
- Node* scene = editor->get_edited_scene();
+ Node *scene = editor->get_edited_scene();
if (scene) {
- List<CanvasItem*> selitems;
+ List<CanvasItem *> selitems;
Point2 bsfrom = transform.xform(drag_from);
- Point2 bsto= transform.xform(box_selecting_to);
- if (bsfrom.x>bsto.x)
- SWAP(bsfrom.x,bsto.x);
- if (bsfrom.y>bsto.y)
- SWAP(bsfrom.y,bsto.y);
+ Point2 bsto = transform.xform(box_selecting_to);
+ if (bsfrom.x > bsto.x)
+ SWAP(bsfrom.x, bsto.x);
+ if (bsfrom.y > bsto.y)
+ SWAP(bsfrom.y, bsto.y);
- _find_canvas_items_at_rect(Rect2(bsfrom,bsto-bsfrom),scene,transform,Transform2D(),&selitems);
+ _find_canvas_items_at_rect(Rect2(bsfrom, bsto - bsfrom), scene, transform, Transform2D(), &selitems);
- for(List<CanvasItem*>::Element *E=selitems.front();E;E=E->next()) {
+ for (List<CanvasItem *>::Element *E = selitems.front(); E; E = E->next()) {
_append_canvas_item(E->get());
}
-
}
- box_selecting=false;
+ box_selecting = false;
viewport->update();
-
}
return;
}
-
- Map<ObjectID,BoneList>::Element *Cbone=NULL; //closest
+ Map<ObjectID, BoneList>::Element *Cbone = NULL; //closest
{
bone_ik_list.clear();
- float closest_dist=1e20;
+ float closest_dist = 1e20;
int bone_width = EditorSettings::get_singleton()->get("editors/2d/bone_width");
- for(Map<ObjectID,BoneList>::Element *E=bone_list.front();E;E=E->next()) {
+ for (Map<ObjectID, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
if (E->get().from == E->get().to)
continue;
- Vector2 s[2]={
+ Vector2 s[2] = {
E->get().from,
E->get().to
};
- Vector2 p = Geometry::get_closest_point_to_segment_2d(Vector2(b.x,b.y),s);
- float d = p.distance_to(Vector2(b.x,b.y));
- if (d<bone_width && d<closest_dist) {
- Cbone=E;
- closest_dist=d;
+ Vector2 p = Geometry::get_closest_point_to_segment_2d(Vector2(b.x, b.y), s);
+ float d = p.distance_to(Vector2(b.x, b.y));
+ if (d < bone_width && d < closest_dist) {
+ Cbone = E;
+ closest_dist = d;
}
}
if (Cbone) {
- Node2D *b=NULL;
- Object* obj=ObjectDB::get_instance(Cbone->get().bone);
+ Node2D *b = NULL;
+ Object *obj = ObjectDB::get_instance(Cbone->get().bone);
if (obj)
- b=obj->cast_to<Node2D>();
+ b = obj->cast_to<Node2D>();
if (b) {
+ bool ik_found = false;
+ bool first = true;
- bool ik_found=false;
- bool first=true;
-
-
+ while (b) {
- while(b) {
-
- CanvasItem *pi=b->get_parent_item();
+ CanvasItem *pi = b->get_parent_item();
if (!pi)
break;
- float len=pi->get_global_transform().get_origin().distance_to(b->get_global_position());
- b=pi->cast_to<Node2D>();
+ float len = pi->get_global_transform().get_origin().distance_to(b->get_global_position());
+ b = pi->cast_to<Node2D>();
if (!b)
break;
if (first) {
- bone_orig_xform=b->get_global_transform();
- first=false;
+ bone_orig_xform = b->get_global_transform();
+ first = false;
}
BoneIK bik;
- bik.node=b;
- bik.len=len;
- bik.orig_state=b->edit_get_state();
+ bik.node = b;
+ bik.len = len;
+ bik.orig_state = b->edit_get_state();
bone_ik_list.push_back(bik);
if (b->has_meta("_edit_ik_")) {
- ik_found=bone_ik_list.size()>1;
+ ik_found = bone_ik_list.size() > 1;
break;
}
if (!pi->has_meta("_edit_bone_"))
break;
-
}
if (!ik_found)
bone_ik_list.clear();
-
}
}
}
@@ -1400,92 +1328,86 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
//try single canvas_item edit
CanvasItem *canvas_item = single_item;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
ERR_FAIL_COND(!se);
+ Point2 click(b.x, b.y);
- Point2 click(b.x,b.y);
-
- if ((b.mod.control && tool==TOOL_SELECT) || tool==TOOL_ROTATE) {
+ if ((b.mod.control && tool == TOOL_SELECT) || tool == TOOL_ROTATE) {
- drag=DRAG_ROTATE;
- drag_from=transform.affine_inverse().xform(click);
- se->undo_state=canvas_item->edit_get_state();
+ drag = DRAG_ROTATE;
+ drag_from = transform.affine_inverse().xform(click);
+ se->undo_state = canvas_item->edit_get_state();
if (canvas_item->cast_to<Node2D>())
- se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot();
+ se->undo_pivot = canvas_item->cast_to<Node2D>()->edit_get_pivot();
if (canvas_item->cast_to<Control>())
- se->undo_pivot=Vector2();
+ se->undo_pivot = Vector2();
return;
}
Transform2D xform = transform * canvas_item->get_global_transform_with_canvas();
- Rect2 rect=canvas_item->get_item_rect();
+ Rect2 rect = canvas_item->get_item_rect();
//float handle_radius = handle_len * 1.4144; //magic number, guess what it means!
- if (tool==TOOL_SELECT) {
- drag = _find_drag_type(xform,rect,click,drag_point_from);
+ if (tool == TOOL_SELECT) {
+ drag = _find_drag_type(xform, rect, click, drag_point_from);
if (b.doubleclick) {
- if (canvas_item->get_filename()!="" && canvas_item!=editor->get_edited_scene()) {
+ if (canvas_item->get_filename() != "" && canvas_item != editor->get_edited_scene()) {
editor->open_request(canvas_item->get_filename());
return;
}
}
- if (drag!=DRAG_NONE && (!Cbone || drag!=DRAG_ALL)) {
- drag_from=transform.affine_inverse().xform(click);
- se->undo_state=canvas_item->edit_get_state();
+ if (drag != DRAG_NONE && (!Cbone || drag != DRAG_ALL)) {
+ drag_from = transform.affine_inverse().xform(click);
+ se->undo_state = canvas_item->edit_get_state();
if (canvas_item->cast_to<Node2D>())
- se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot();
+ se->undo_pivot = canvas_item->cast_to<Node2D>()->edit_get_pivot();
return;
}
} else {
- drag=DRAG_NONE;
+ drag = DRAG_NONE;
}
}
//multi canvas_item edit
+ Point2 click = Point2(b.x, b.y);
- Point2 click=Point2(b.x,b.y);
+ if ((b.mod.alt || tool == TOOL_MOVE) && get_item_count()) {
- if ((b.mod.alt || tool==TOOL_MOVE) && get_item_count()) {
+ List<Node *> &selection = editor_selection->get_selected_node_list();
-
- List<Node*> &selection = editor_selection->get_selected_node_list();
-
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
- se->undo_state=canvas_item->edit_get_state();
+ se->undo_state = canvas_item->edit_get_state();
if (canvas_item->cast_to<Node2D>())
- se->undo_pivot=canvas_item->cast_to<Node2D>()->edit_get_pivot();
-
+ se->undo_pivot = canvas_item->cast_to<Node2D>()->edit_get_pivot();
}
-
- drag=DRAG_ALL;
- drag_from=transform.affine_inverse().xform(click);
- drag_point_from=_find_topleftmost_point();
+ drag = DRAG_ALL;
+ drag_from = transform.affine_inverse().xform(click);
+ drag_point_from = _find_topleftmost_point();
viewport->update();
return;
-
}
- Node* scene = editor->get_edited_scene();
+ Node *scene = editor->get_edited_scene();
if (!scene)
return;
@@ -1494,33 +1416,30 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
//no window.... ?
click-=current_window->get_scroll();
}*/
- CanvasItem *c=NULL;
+ CanvasItem *c = NULL;
if (Cbone) {
- Object* obj=ObjectDB::get_instance(Cbone->get().bone);
+ Object *obj = ObjectDB::get_instance(Cbone->get().bone);
if (obj)
- c=obj->cast_to<CanvasItem>();
+ c = obj->cast_to<CanvasItem>();
if (c)
- c=c->get_parent_item();
-
-
+ c = c->get_parent_item();
}
if (!c) {
- c =_select_canvas_item_at_pos(click, scene,transform,Transform2D());
-
+ c = _select_canvas_item_at_pos(click, scene, transform, Transform2D());
- CanvasItem* cn = c;
+ CanvasItem *cn = c;
- while(cn) {
+ while (cn) {
if (cn->has_meta("_edit_group_")) {
- c=cn;
+ c = cn;
}
- cn=cn->get_parent_item();
+ cn = cn->get_parent_item();
}
}
- Node* n = c;
+ Node *n = c;
while ((n && n != scene && n->get_owner() != scene) || (n && !n->is_class("CanvasItem"))) {
n = n->get_parent();
@@ -1530,57 +1449,50 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
if ( b.pressed ) box_selection_start( click );
#endif
- additive_selection=b.mod.shift;
+ additive_selection = b.mod.shift;
if (!_select(c, click, additive_selection))
return;
-
}
- if (p_event.type==InputEvent::MOUSE_MOTION) {
+ if (p_event.type == InputEvent::MOUSE_MOTION) {
if (!viewport->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
viewport->call_deferred("grab_focus");
- const InputEventMouseMotion &m=p_event.mouse_motion;
+ const InputEventMouseMotion &m = p_event.mouse_motion;
if (box_selecting) {
- box_selecting_to=transform.affine_inverse().xform(Point2(m.x,m.y));
+ box_selecting_to = transform.affine_inverse().xform(Point2(m.x, m.y));
viewport->update();
return;
-
}
+ if (drag == DRAG_NONE) {
- if (drag==DRAG_NONE) {
-
-
- if ( (m.button_mask&BUTTON_MASK_LEFT && tool == TOOL_PAN) || m.button_mask&BUTTON_MASK_MIDDLE || (m.button_mask&BUTTON_MASK_LEFT && Input::get_singleton()->is_key_pressed(KEY_SPACE))) {
- h_scroll->set_value( h_scroll->get_value() - m.relative_x/zoom);
- v_scroll->set_value( v_scroll->get_value() - m.relative_y/zoom);
+ if ((m.button_mask & BUTTON_MASK_LEFT && tool == TOOL_PAN) || m.button_mask & BUTTON_MASK_MIDDLE || (m.button_mask & BUTTON_MASK_LEFT && Input::get_singleton()->is_key_pressed(KEY_SPACE))) {
+ h_scroll->set_value(h_scroll->get_value() - m.relative_x / zoom);
+ v_scroll->set_value(v_scroll->get_value() - m.relative_y / zoom);
}
return;
-
}
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
-
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
- bool dragging_bone = drag==DRAG_ALL && selection.size()==1 && bone_ik_list.size();
-
+ bool dragging_bone = drag == DRAG_ALL && selection.size() == 1 && bone_ik_list.size();
if (!dragging_bone) {
canvas_item->edit_set_state(se->undo_state); //reset state and reapply
@@ -1588,23 +1500,20 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
canvas_item->cast_to<Node2D>()->edit_set_pivot(se->undo_pivot);
}
-
Vector2 dfrom = drag_from;
- Vector2 dto = transform.affine_inverse().xform(Point2(m.x,m.y));
+ Vector2 dto = transform.affine_inverse().xform(Point2(m.x, m.y));
if (canvas_item->has_meta("_edit_lock_"))
continue;
-
- if (drag==DRAG_ROTATE) {
+ if (drag == DRAG_ROTATE) {
Vector2 center = canvas_item->get_global_transform_with_canvas().get_origin();
{
Node2D *node = canvas_item->cast_to<Node2D>();
-
if (node) {
real_t angle = node->get_rotation();
- node->set_rotation(snap_angle( angle + (dfrom - center).angle_to(dto-center), angle ));
+ node->set_rotation(snap_angle(angle + (dfrom - center).angle_to(dto - center), angle));
display_rotate_to = dto;
display_rotate_from = center;
viewport->update();
@@ -1614,10 +1523,9 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
{
Control *node = canvas_item->cast_to<Control>();
-
if (node) {
real_t angle = node->get_rotation();
- node->set_rotation(snap_angle( angle + (dfrom - center).angle_to(dto-center), angle ));
+ node->set_rotation(snap_angle(angle + (dfrom - center).angle_to(dto - center), angle));
display_rotate_to = dto;
display_rotate_from = center;
viewport->update();
@@ -1627,14 +1535,13 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
continue;
}
-
bool uniform = m.mod.shift;
- bool symmetric=m.mod.alt;
+ bool symmetric = m.mod.alt;
dto = dto - (drag == DRAG_ALL ? drag_from - drag_point_from : Vector2(0, 0));
- if(uniform && drag == DRAG_ALL) {
- if(ABS(dto.x - drag_point_from.x) > ABS(dto.y - drag_point_from.y)) {
+ if (uniform && drag == DRAG_ALL) {
+ if (ABS(dto.x - drag_point_from.x) > ABS(dto.y - drag_point_from.y)) {
dto.y = drag_point_from.y;
} else {
dto.x = drag_point_from.x;
@@ -1649,128 +1556,118 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
canvas_item->get_global_transform_with_canvas().affine_inverse().xform(dfrom);
Rect2 local_rect = canvas_item->get_item_rect();
- Vector2 begin=local_rect.pos;
- Vector2 end=local_rect.pos+local_rect.size;
+ Vector2 begin = local_rect.pos;
+ Vector2 end = local_rect.pos + local_rect.size;
Vector2 minsize = canvas_item->edit_get_minimum_size();
if (uniform) {
float aspect = local_rect.size.aspect();
- switch(drag) {
+ switch (drag) {
case DRAG_BOTTOM_LEFT:
case DRAG_TOP_RIGHT: {
if (aspect > 1.0) { // width > height, take x as reference
- drag_vector.y = -drag_vector.x/aspect;
+ drag_vector.y = -drag_vector.x / aspect;
} else { // height > width, take y as reference
- drag_vector.x = -drag_vector.y*aspect;
+ drag_vector.x = -drag_vector.y * aspect;
}
} break;
case DRAG_BOTTOM_RIGHT:
case DRAG_TOP_LEFT: {
if (aspect > 1.0) { // width > height, take x as reference
- drag_vector.y = drag_vector.x/aspect;
+ drag_vector.y = drag_vector.x / aspect;
} else { // height > width, take y as reference
- drag_vector.x = drag_vector.y*aspect;
+ drag_vector.x = drag_vector.y * aspect;
}
} break;
default: {}
}
}
- switch(drag) {
+ switch (drag) {
case DRAG_ALL: {
- begin+=drag_vector;
- end+=drag_vector;
+ begin += drag_vector;
+ end += drag_vector;
} break;
case DRAG_RIGHT: {
- incend(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
+ incend(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
} break;
case DRAG_BOTTOM: {
- incend(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
+ incend(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
} break;
case DRAG_BOTTOM_RIGHT: {
- incend(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
- incend(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
+ incend(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
+ incend(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
} break;
case DRAG_TOP_LEFT: {
- incbeg(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
- incbeg(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
+ incbeg(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
+ incbeg(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
} break;
case DRAG_TOP: {
- incbeg(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
+ incbeg(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
} break;
case DRAG_LEFT: {
- incbeg(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
+ incbeg(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
} break;
case DRAG_TOP_RIGHT: {
- incbeg(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
- incend(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
+ incbeg(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
+ incend(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
} break;
case DRAG_BOTTOM_LEFT: {
- incbeg(begin.x,end.x,drag_vector.x,minsize.x,symmetric);
- incend(begin.y,end.y,drag_vector.y,minsize.y,symmetric);
+ incbeg(begin.x, end.x, drag_vector.x, minsize.x, symmetric);
+ incend(begin.y, end.y, drag_vector.y, minsize.y, symmetric);
} break;
case DRAG_PIVOT: {
if (canvas_item->cast_to<Node2D>()) {
- Node2D *n2d =canvas_item->cast_to<Node2D>();
- n2d->edit_set_pivot(se->undo_pivot+drag_vector);
-
+ Node2D *n2d = canvas_item->cast_to<Node2D>();
+ n2d->edit_set_pivot(se->undo_pivot + drag_vector);
}
continue;
} break;
- default:{}
+ default: {}
}
-
-
if (!dragging_bone) {
- local_rect.pos=begin;
- local_rect.size=end-begin;
+ local_rect.pos = begin;
+ local_rect.size = end - begin;
canvas_item->edit_set_rect(local_rect);
} else {
//ok, all that had to be done was done, now solve IK
-
-
-
Node2D *n2d = canvas_item->cast_to<Node2D>();
Transform2D final_xform = bone_orig_xform;
-
-
if (n2d) {
float total_len = 0;
- for (List<BoneIK>::Element *E=bone_ik_list.front();E;E=E->next()) {
+ for (List<BoneIK>::Element *E = bone_ik_list.front(); E; E = E->next()) {
if (E->prev())
- total_len+=E->get().len;
+ total_len += E->get().len;
E->get().pos = E->get().node->get_global_transform().get_origin();
}
{
- final_xform.elements[2]+=dto-dfrom;//final_xform.affine_inverse().basis_xform_inv(drag_vector);
+ final_xform.elements[2] += dto - dfrom; //final_xform.affine_inverse().basis_xform_inv(drag_vector);
//n2d->set_global_transform(final_xform);
-
}
-
CanvasItem *last = bone_ik_list.back()->get().node;
if (!last)
break;
@@ -1783,70 +1680,64 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
//print_line("TOO FAR!");
Vector2 rel = leaf_pos - root_pos;
rel = rel.normalized() * total_len;
- leaf_pos=root_pos+rel;
-
+ leaf_pos = root_pos + rel;
}
- bone_ik_list.front()->get().pos=leaf_pos;
+ bone_ik_list.front()->get().pos = leaf_pos;
//print_line("BONE IK LIST "+itos(bone_ik_list.size()));
+ if (bone_ik_list.size() > 2) {
+ int solver_iterations = 64;
+ float solver_k = 0.3;
- if (bone_ik_list.size()>2) {
- int solver_iterations=64;
- float solver_k=0.3;
-
- for(int i=0;i<solver_iterations;i++) {
-
- for (List<BoneIK>::Element *E=bone_ik_list.front();E;E=E->next()) {
-
+ for (int i = 0; i < solver_iterations; i++) {
+ for (List<BoneIK>::Element *E = bone_ik_list.front(); E; E = E->next()) {
- if (E==bone_ik_list.back()) {
+ if (E == bone_ik_list.back()) {
break;
}
float len = E->next()->get().len;
- if (E->next()==bone_ik_list.back()) {
+ if (E->next() == bone_ik_list.back()) {
//print_line("back");
Vector2 rel = E->get().pos - E->next()->get().pos;
//print_line("PREV "+E->get().pos);
- Vector2 desired = E->next()->get().pos+rel.normalized()*len;
+ Vector2 desired = E->next()->get().pos + rel.normalized() * len;
//print_line("DESIRED "+desired);
- E->get().pos=E->get().pos.linear_interpolate(desired,solver_k);
+ E->get().pos = E->get().pos.linear_interpolate(desired, solver_k);
//print_line("POST "+E->get().pos);
-
- } else if (E==bone_ik_list.front()) {
+ } else if (E == bone_ik_list.front()) {
//only adjust parent
//print_line("front");
Vector2 rel = E->next()->get().pos - E->get().pos;
//print_line("PREV "+E->next()->get().pos);
- Vector2 desired = E->get().pos+rel.normalized()*len;
+ Vector2 desired = E->get().pos + rel.normalized() * len;
//print_line("DESIRED "+desired);
- E->next()->get().pos=E->next()->get().pos.linear_interpolate(desired,solver_k);
+ E->next()->get().pos = E->next()->get().pos.linear_interpolate(desired, solver_k);
//print_line("POST "+E->next()->get().pos);
} else {
Vector2 rel = E->next()->get().pos - E->get().pos;
- Vector2 cen = (E->next()->get().pos + E->get().pos)*0.5;
- rel=rel.linear_interpolate(rel.normalized()*len,solver_k);
- rel*=0.5;
- E->next()->get().pos=cen+rel;
- E->get().pos=cen-rel;
+ Vector2 cen = (E->next()->get().pos + E->get().pos) * 0.5;
+ rel = rel.linear_interpolate(rel.normalized() * len, solver_k);
+ rel *= 0.5;
+ E->next()->get().pos = cen + rel;
+ E->get().pos = cen - rel;
//print_line("mid");
-
}
}
}
}
}
- for (List<BoneIK>::Element *E=bone_ik_list.back();E;E=E->prev()) {
+ for (List<BoneIK>::Element *E = bone_ik_list.back(); E; E = E->prev()) {
Node2D *n = E->get().node;
@@ -1859,90 +1750,81 @@ void CanvasItemEditor::_viewport_gui_input(const InputEvent& p_event) {
Vector2 rel = (E->prev()->get().node->get_global_position() - n->get_global_position()).normalized();
Vector2 rel2 = (E->prev()->get().pos - E->get().pos).normalized();
float rot = rel.angle_to(rel2);
- if (n->get_global_transform().basis_determinant()<0) {
+ if (n->get_global_transform().basis_determinant() < 0) {
//mirrored, rotate the other way
- rot=-rot;
+ rot = -rot;
}
n->rotate(rot);
}
-
}
-
-
break;
}
}
}
- if (p_event.type==InputEvent::KEY) {
+ if (p_event.type == InputEvent::KEY) {
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
- if (k.pressed && drag==DRAG_NONE) {
+ if (k.pressed && drag == DRAG_NONE) {
KeyMoveMODE move_mode = MOVE_VIEW_BASE;
if (k.mod.alt) move_mode = MOVE_LOCAL_BASE;
if (k.mod.control || k.mod.meta) move_mode = MOVE_LOCAL_WITH_ROT;
- if (k.scancode==KEY_UP)
- _key_move( Vector2(0,-1), k.mod.shift, move_mode );
- else if (k.scancode==KEY_DOWN)
- _key_move( Vector2(0,1), k.mod.shift, move_mode );
- else if (k.scancode==KEY_LEFT)
- _key_move( Vector2(-1,0), k.mod.shift, move_mode );
- else if (k.scancode==KEY_RIGHT)
- _key_move( Vector2(1,0), k.mod.shift, move_mode );
- else if (k.scancode==KEY_ESCAPE) {
+ if (k.scancode == KEY_UP)
+ _key_move(Vector2(0, -1), k.mod.shift, move_mode);
+ else if (k.scancode == KEY_DOWN)
+ _key_move(Vector2(0, 1), k.mod.shift, move_mode);
+ else if (k.scancode == KEY_LEFT)
+ _key_move(Vector2(-1, 0), k.mod.shift, move_mode);
+ else if (k.scancode == KEY_RIGHT)
+ _key_move(Vector2(1, 0), k.mod.shift, move_mode);
+ else if (k.scancode == KEY_ESCAPE) {
editor_selection->clear();
viewport->update();
- }
- else
+ } else
return;
accept_event();
}
-
}
-
-
-
-
}
void CanvasItemEditor::_viewport_draw() {
// TODO fetch the viewport?
- Ref<Texture> pivot = get_icon("EditorPivot","EditorIcons");
+ Ref<Texture> pivot = get_icon("EditorPivot", "EditorIcons");
_update_scrollbars();
- RID ci=viewport->get_canvas_item();
+ RID ci = viewport->get_canvas_item();
if (snap_show_grid) {
Size2 s = viewport->get_size();
int last_cell;
Transform2D xform = transform.affine_inverse();
- if (snap_step.x!=0) {
- for(int i=0;i<s.width;i++) {
- int cell = Math::fast_ftoi(Math::floor((xform.xform(Vector2(i,0)).x-snap_offset.x)/snap_step.x));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- viewport->draw_line(Point2(i,0),Point2(i,s.height),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ if (snap_step.x != 0) {
+ for (int i = 0; i < s.width; i++) {
+ int cell = Math::fast_ftoi(Math::floor((xform.xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ viewport->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
- if (snap_step.y!=0) {
- for(int i=0;i<s.height;i++) {
- int cell = Math::fast_ftoi(Math::floor((xform.xform(Vector2(0,i)).y-snap_offset.y)/snap_step.y));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- viewport->draw_line(Point2(0,i),Point2(s.width,i),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ if (snap_step.y != 0) {
+ for (int i = 0; i < s.height; i++) {
+ int cell = Math::fast_ftoi(Math::floor((xform.xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ viewport->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
}
@@ -1950,168 +1832,150 @@ void CanvasItemEditor::_viewport_draw() {
if (viewport->has_focus()) {
Size2 size = viewport->get_size();
if (v_scroll->is_visible_in_tree())
- size.width-=v_scroll->get_size().width;
+ size.width -= v_scroll->get_size().width;
if (h_scroll->is_visible_in_tree())
- size.height-=h_scroll->get_size().height;
+ size.height -= h_scroll->get_size().height;
- get_stylebox("EditorFocus","EditorStyles")->draw(ci,Rect2(Point2(),size));
+ get_stylebox("EditorFocus", "EditorStyles")->draw(ci, Rect2(Point2(), size));
}
- Ref<Texture> lock = get_icon("Lock","EditorIcons");
- Ref<Texture> group = get_icon("Group","EditorIcons");
+ Ref<Texture> lock = get_icon("Lock", "EditorIcons");
+ Ref<Texture> group = get_icon("Group", "EditorIcons");
+ bool single = get_single_item() != NULL;
- bool single = get_single_item()!=NULL;
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- Map<Node*,Object*> &selection = editor_selection->get_selection();
-
- bool pivot_found=false;
-
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ bool pivot_found = false;
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
+ Rect2 rect = canvas_item->get_item_rect();
- Rect2 rect=canvas_item->get_item_rect();
+ Transform2D xform = transform * canvas_item->get_global_transform_with_canvas();
+ VisualServer::get_singleton()->canvas_item_add_set_transform(ci, xform);
- Transform2D xform=transform * canvas_item->get_global_transform_with_canvas();
- VisualServer::get_singleton()->canvas_item_add_set_transform(ci,xform);
-
- Vector2 endpoints[4]={
+ Vector2 endpoints[4] = {
xform.xform(rect.pos),
- xform.xform(rect.pos+Vector2(rect.size.x,0)),
- xform.xform(rect.pos+rect.size),
- xform.xform(rect.pos+Vector2(0,rect.size.y))
+ xform.xform(rect.pos + Vector2(rect.size.x, 0)),
+ xform.xform(rect.pos + rect.size),
+ xform.xform(rect.pos + Vector2(0, rect.size.y))
};
- Color c = Color(1,0.6,0.4,0.7);
+ Color c = Color(1, 0.6, 0.4, 0.7);
- VisualServer::get_singleton()->canvas_item_add_set_transform(ci,Transform2D());
+ VisualServer::get_singleton()->canvas_item_add_set_transform(ci, Transform2D());
- for(int i=0;i<4;i++) {
- viewport->draw_line(endpoints[i],endpoints[(i+1)%4],c,2);
+ for (int i = 0; i < 4; i++) {
+ viewport->draw_line(endpoints[i], endpoints[(i + 1) % 4], c, 2);
}
- if (single && (tool==TOOL_SELECT || tool == TOOL_MOVE || tool == TOOL_ROTATE || tool==TOOL_EDIT_PIVOT)) { //kind of sucks
+ if (single && (tool == TOOL_SELECT || tool == TOOL_MOVE || tool == TOOL_ROTATE || tool == TOOL_EDIT_PIVOT)) { //kind of sucks
if (canvas_item->cast_to<Node2D>()) {
-
if (canvas_item->cast_to<Node2D>()->edit_has_pivot()) {
- viewport->draw_texture(pivot,xform.get_origin()+(-pivot->get_size()/2).floor());
- can_move_pivot=true;
- pivot_found=true;
+ viewport->draw_texture(pivot, xform.get_origin() + (-pivot->get_size() / 2).floor());
+ can_move_pivot = true;
+ pivot_found = true;
}
-
}
+ if (tool == TOOL_SELECT) {
- if (tool==TOOL_SELECT) {
-
+ for (int i = 0; i < 4; i++) {
- for(int i=0;i<4;i++) {
-
- int prev = (i+3)%4;
- int next = (i+1)%4;
+ int prev = (i + 3) % 4;
+ int next = (i + 1) % 4;
Vector2 ofs = ((endpoints[i] - endpoints[prev]).normalized() + ((endpoints[i] - endpoints[next]).normalized())).normalized();
- ofs*=1.4144*(select_handle->get_size().width/2);
-
- select_handle->draw(ci,(endpoints[i]+ofs-(select_handle->get_size()/2)).floor());
+ ofs *= 1.4144 * (select_handle->get_size().width / 2);
- ofs = (endpoints[i]+endpoints[next])/2;
- ofs += (endpoints[next]-endpoints[i]).tangent().normalized()*(select_handle->get_size().width/2);
+ select_handle->draw(ci, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor());
- select_handle->draw(ci,(ofs-(select_handle->get_size()/2)).floor());
+ ofs = (endpoints[i] + endpoints[next]) / 2;
+ ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2);
+ select_handle->draw(ci, (ofs - (select_handle->get_size() / 2)).floor());
}
-
}
}
-
-
//DRAW_EMPTY_RECT( Rect2( current_window->get_scroll()-Point2(1,1), get_size()+Size2(2,2)), Color(0.8,0.8,1.0,0.8) );
//E->get().last_rect = rect;
}
pivot_button->set_disabled(!pivot_found);
- VisualServer::get_singleton()->canvas_item_add_set_transform(ci,Transform2D());
+ VisualServer::get_singleton()->canvas_item_add_set_transform(ci, Transform2D());
+ Color x_axis_color(1.0, 0.4, 0.4, 0.6);
+ Color y_axis_color(0.4, 1.0, 0.4, 0.6);
+ Color area_axis_color(0.4, 0.4, 1.0, 0.4);
+ Color rotate_color(0.4, 0.7, 1.0, 0.8);
-
- Color x_axis_color(1.0,0.4,0.4,0.6);
- Color y_axis_color(0.4,1.0,0.4,0.6);
- Color area_axis_color(0.4,0.4,1.0,0.4);
- Color rotate_color(0.4,0.7,1.0,0.8);
-
- VisualServer::get_singleton()->canvas_item_add_line(ci,Point2(h_scroll->get_min(),0)+transform.get_origin(),Point2(h_scroll->get_max(),0)+transform.get_origin(),x_axis_color);
- VisualServer::get_singleton()->canvas_item_add_line(ci,Point2(0,v_scroll->get_min())+transform.get_origin(),Point2(0,v_scroll->get_max())+transform.get_origin(),y_axis_color);
-
+ VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(h_scroll->get_min(), 0) + transform.get_origin(), Point2(h_scroll->get_max(), 0) + transform.get_origin(), x_axis_color);
+ VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(0, v_scroll->get_min()) + transform.get_origin(), Point2(0, v_scroll->get_max()) + transform.get_origin(), y_axis_color);
if (box_selecting) {
Point2 bsfrom = transform.xform(drag_from);
- Point2 bsto= transform.xform(box_selecting_to);
+ Point2 bsto = transform.xform(box_selecting_to);
-
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(bsfrom,bsto-bsfrom),Color(0.7,0.7,1.0,0.3));
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(bsfrom, bsto - bsfrom), Color(0.7, 0.7, 1.0, 0.3));
}
- if (drag==DRAG_ROTATE) {
- VisualServer::get_singleton()->canvas_item_add_line(ci,transform.xform(display_rotate_from), transform.xform(display_rotate_to),rotate_color);
+ if (drag == DRAG_ROTATE) {
+ VisualServer::get_singleton()->canvas_item_add_line(ci, transform.xform(display_rotate_from), transform.xform(display_rotate_to), rotate_color);
}
- Size2 screen_size = Size2( GlobalConfig::get_singleton()->get("display/window/width"), GlobalConfig::get_singleton()->get("display/window/height") );
+ Size2 screen_size = Size2(GlobalConfig::get_singleton()->get("display/window/width"), GlobalConfig::get_singleton()->get("display/window/height"));
- Vector2 screen_endpoints[4]= {
- transform.xform(Vector2(0,0)),
- transform.xform(Vector2(screen_size.width,0)),
- transform.xform(Vector2(screen_size.width,screen_size.height)),
- transform.xform(Vector2(0,screen_size.height))
+ Vector2 screen_endpoints[4] = {
+ transform.xform(Vector2(0, 0)),
+ transform.xform(Vector2(screen_size.width, 0)),
+ transform.xform(Vector2(screen_size.width, screen_size.height)),
+ transform.xform(Vector2(0, screen_size.height))
};
- for(int i=0;i<4;i++) {
-
- VisualServer::get_singleton()->canvas_item_add_line(ci,screen_endpoints[i], screen_endpoints[(i+1)%4],area_axis_color);
+ for (int i = 0; i < 4; i++) {
+ VisualServer::get_singleton()->canvas_item_add_line(ci, screen_endpoints[i], screen_endpoints[(i + 1) % 4], area_axis_color);
}
- for(List<LockList>::Element*E=lock_list.front();E;E=E->next()) {
+ for (List<LockList>::Element *E = lock_list.front(); E; E = E->next()) {
Vector2 ofs = transform.xform(E->get().pos);
if (E->get().lock) {
- lock->draw(ci,ofs);
- ofs.x+=lock->get_width();
+ lock->draw(ci, ofs);
+ ofs.x += lock->get_width();
}
if (E->get().group) {
- group->draw(ci,ofs);
+ group->draw(ci, ofs);
}
-
}
{
- EditorNode *en = editor;
- EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
-
- if (!over_plugin_list->empty()) {
+ EditorNode *en = editor;
+ EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
- over_plugin_list->forward_draw_over_canvas(transform,viewport);
+ if (!over_plugin_list->empty()) {
- }
- }
+ over_plugin_list->forward_draw_over_canvas(transform, viewport);
+ }
+ }
if (skeleton_show_bones) {
int bone_width = EditorSettings::get_singleton()->get("editors/2d/bone_width");
@@ -2120,16 +1984,16 @@ void CanvasItemEditor::_viewport_draw() {
Color bone_ik_color = EditorSettings::get_singleton()->get("editors/2d/bone_ik_color");
Color bone_selected_color = EditorSettings::get_singleton()->get("editors/2d/bone_selected_color");
- for(Map<ObjectID,BoneList>::Element*E=bone_list.front();E;E=E->next()) {
+ for (Map<ObjectID, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
- E->get().from=Vector2();
- E->get().to=Vector2();
+ E->get().from = Vector2();
+ E->get().to = Vector2();
Object *obj = ObjectDB::get_instance(E->get().bone);
if (!obj)
continue;
- Node2D* n2d = obj->cast_to<Node2D>();
+ Node2D *n2d = obj->cast_to<Node2D>();
if (!n2d)
continue;
@@ -2138,8 +2002,7 @@ void CanvasItemEditor::_viewport_draw() {
CanvasItem *pi = n2d->get_parent_item();
-
- Node2D* pn2d=n2d->get_parent()->cast_to<Node2D>();
+ Node2D *pn2d = n2d->get_parent()->cast_to<Node2D>();
if (!pn2d)
continue;
@@ -2147,19 +2010,17 @@ void CanvasItemEditor::_viewport_draw() {
Vector2 from = transform.xform(pn2d->get_global_position());
Vector2 to = transform.xform(n2d->get_global_position());
- E->get().from=from;
- E->get().to=to;
-
- Vector2 rel = to-from;
- Vector2 relt = rel.tangent().normalized()*bone_width;
-
+ E->get().from = from;
+ E->get().to = to;
+ Vector2 rel = to - from;
+ Vector2 relt = rel.tangent().normalized() * bone_width;
Vector<Vector2> bone_shape;
bone_shape.push_back(from);
- bone_shape.push_back(from+rel*0.2+relt);
+ bone_shape.push_back(from + rel * 0.2 + relt);
bone_shape.push_back(to);
- bone_shape.push_back(from+rel*0.2-relt);
+ bone_shape.push_back(from + rel * 0.2 - relt);
Vector<Color> colors;
if (pi->has_meta("_edit_ik_")) {
@@ -2174,57 +2035,54 @@ void CanvasItemEditor::_viewport_draw() {
colors.push_back(bone_color2);
}
-
- VisualServer::get_singleton()->canvas_item_add_primitive(ci,bone_shape,colors,Vector<Vector2>(),RID());
+ VisualServer::get_singleton()->canvas_item_add_primitive(ci, bone_shape, colors, Vector<Vector2>(), RID());
if (editor_selection->is_selected(pi)) {
- for(int i=0;i<bone_shape.size();i++) {
+ for (int i = 0; i < bone_shape.size(); i++) {
- VisualServer::get_singleton()->canvas_item_add_line(ci,bone_shape[i],bone_shape[(i+1)%bone_shape.size()],bone_selected_color,2);
+ VisualServer::get_singleton()->canvas_item_add_line(ci, bone_shape[i], bone_shape[(i + 1) % bone_shape.size()], bone_selected_color, 2);
}
}
-
}
}
}
void CanvasItemEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- bool all_control=true;
- bool has_control=false;
+ bool all_control = true;
+ bool has_control = false;
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
if (canvas_item->cast_to<Control>())
- has_control=true;
+ has_control = true;
else
- all_control=false;
+ all_control = false;
- CanvasItemEditorSelectedItem *se=editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
+ CanvasItemEditorSelectedItem *se = editor_selection->get_node_editor_data<CanvasItemEditorSelectedItem>(canvas_item);
if (!se)
continue;
- Rect2 r=canvas_item->get_item_rect();
+ Rect2 r = canvas_item->get_item_rect();
Transform2D xform = canvas_item->get_transform();
- if (r != se->prev_rect || xform!=se->prev_xform) {
+ if (r != se->prev_rect || xform != se->prev_xform) {
viewport->update();
- se->prev_rect=r;
- se->prev_xform=xform;
+ se->prev_rect = r;
+ se->prev_xform = xform;
}
-
}
bool show_anchor = all_control && has_control;
@@ -2235,7 +2093,7 @@ void CanvasItemEditor::_notification(int p_what) {
anchor_menu->hide();
}
- for(Map<ObjectID,BoneList>::Element *E=bone_list.front();E;E=E->next()) {
+ for (Map<ObjectID, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
Object *b = ObjectDB::get_instance(E->get().bone);
if (!b) {
@@ -2249,123 +2107,110 @@ void CanvasItemEditor::_notification(int p_what) {
continue;
}
- if (b2->get_global_transform()!=E->get().xform) {
+ if (b2->get_global_transform() != E->get().xform) {
- E->get().xform=b2->get_global_transform();
+ E->get().xform = b2->get_global_transform();
viewport->update();
}
}
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- select_sb->set_texture( get_icon("EditorRect2D","EditorIcons") );
- for(int i=0;i<4;i++) {
- select_sb->set_margin_size(Margin(i),4);
- select_sb->set_default_margin(Margin(i),4);
+ select_sb->set_texture(get_icon("EditorRect2D", "EditorIcons"));
+ for (int i = 0; i < 4; i++) {
+ select_sb->set_margin_size(Margin(i), 4);
+ select_sb->set_default_margin(Margin(i), 4);
}
- select_button->set_icon( get_icon("ToolSelect","EditorIcons"));
- list_select_button->set_icon( get_icon("ListSelect","EditorIcons"));
- move_button->set_icon( get_icon("ToolMove","EditorIcons"));
- rotate_button->set_icon( get_icon("ToolRotate","EditorIcons"));
- pan_button->set_icon( get_icon("ToolPan", "EditorIcons"));
- pivot_button->set_icon( get_icon("EditPivot", "EditorIcons"));
- select_handle=get_icon("EditorHandle","EditorIcons");
- lock_button->set_icon(get_icon("Lock","EditorIcons"));
- unlock_button->set_icon(get_icon("Unlock","EditorIcons"));
- group_button->set_icon(get_icon("Group","EditorIcons"));
- ungroup_button->set_icon(get_icon("Ungroup","EditorIcons"));
- key_insert_button->set_icon(get_icon("Key","EditorIcons"));
-
+ select_button->set_icon(get_icon("ToolSelect", "EditorIcons"));
+ list_select_button->set_icon(get_icon("ListSelect", "EditorIcons"));
+ move_button->set_icon(get_icon("ToolMove", "EditorIcons"));
+ rotate_button->set_icon(get_icon("ToolRotate", "EditorIcons"));
+ pan_button->set_icon(get_icon("ToolPan", "EditorIcons"));
+ pivot_button->set_icon(get_icon("EditPivot", "EditorIcons"));
+ select_handle = get_icon("EditorHandle", "EditorIcons");
+ lock_button->set_icon(get_icon("Lock", "EditorIcons"));
+ unlock_button->set_icon(get_icon("Unlock", "EditorIcons"));
+ group_button->set_icon(get_icon("Group", "EditorIcons"));
+ ungroup_button->set_icon(get_icon("Ungroup", "EditorIcons"));
+ key_insert_button->set_icon(get_icon("Key", "EditorIcons"));
//anchor_menu->add_icon_override("Align Top Left");
- anchor_menu->set_icon(get_icon("Anchor","EditorIcons"));
- PopupMenu *p=anchor_menu->get_popup();
+ anchor_menu->set_icon(get_icon("Anchor", "EditorIcons"));
+ PopupMenu *p = anchor_menu->get_popup();
- p->add_icon_item(get_icon("ControlAlignTopLeft","EditorIcons"),"Top Left",ANCHOR_ALIGN_TOP_LEFT);
- p->add_icon_item(get_icon("ControlAlignTopRight","EditorIcons"),"Top Right",ANCHOR_ALIGN_TOP_RIGHT);
- p->add_icon_item(get_icon("ControlAlignBottomRight","EditorIcons"),"Bottom Right",ANCHOR_ALIGN_BOTTOM_RIGHT);
- p->add_icon_item(get_icon("ControlAlignBottomLeft","EditorIcons"),"Bottom Left",ANCHOR_ALIGN_BOTTOM_LEFT);
+ p->add_icon_item(get_icon("ControlAlignTopLeft", "EditorIcons"), "Top Left", ANCHOR_ALIGN_TOP_LEFT);
+ p->add_icon_item(get_icon("ControlAlignTopRight", "EditorIcons"), "Top Right", ANCHOR_ALIGN_TOP_RIGHT);
+ p->add_icon_item(get_icon("ControlAlignBottomRight", "EditorIcons"), "Bottom Right", ANCHOR_ALIGN_BOTTOM_RIGHT);
+ p->add_icon_item(get_icon("ControlAlignBottomLeft", "EditorIcons"), "Bottom Left", ANCHOR_ALIGN_BOTTOM_LEFT);
p->add_separator();
- p->add_icon_item(get_icon("ControlAlignLeftCenter","EditorIcons"),"Center Left",ANCHOR_ALIGN_CENTER_LEFT);
- p->add_icon_item(get_icon("ControlAlignTopCenter","EditorIcons"),"Center Top",ANCHOR_ALIGN_CENTER_TOP);
- p->add_icon_item(get_icon("ControlAlignRightCenter","EditorIcons"),"Center Right",ANCHOR_ALIGN_CENTER_RIGHT);
- p->add_icon_item(get_icon("ControlAlignBottomCenter","EditorIcons"),"Center Bottom",ANCHOR_ALIGN_CENTER_BOTTOM);
- p->add_icon_item(get_icon("ControlAlignCenter","EditorIcons"),"Center",ANCHOR_ALIGN_CENTER);
+ p->add_icon_item(get_icon("ControlAlignLeftCenter", "EditorIcons"), "Center Left", ANCHOR_ALIGN_CENTER_LEFT);
+ p->add_icon_item(get_icon("ControlAlignTopCenter", "EditorIcons"), "Center Top", ANCHOR_ALIGN_CENTER_TOP);
+ p->add_icon_item(get_icon("ControlAlignRightCenter", "EditorIcons"), "Center Right", ANCHOR_ALIGN_CENTER_RIGHT);
+ p->add_icon_item(get_icon("ControlAlignBottomCenter", "EditorIcons"), "Center Bottom", ANCHOR_ALIGN_CENTER_BOTTOM);
+ p->add_icon_item(get_icon("ControlAlignCenter", "EditorIcons"), "Center", ANCHOR_ALIGN_CENTER);
p->add_separator();
- p->add_icon_item(get_icon("ControlAlignLeftWide","EditorIcons"),"Left Wide",ANCHOR_ALIGN_LEFT_WIDE);
- p->add_icon_item(get_icon("ControlAlignTopWide","EditorIcons"),"Top Wide",ANCHOR_ALIGN_TOP_WIDE);
- p->add_icon_item(get_icon("ControlAlignRightWide","EditorIcons"),"Right Wide",ANCHOR_ALIGN_RIGHT_WIDE);
- p->add_icon_item(get_icon("ControlAlignBottomWide","EditorIcons"),"Bottom Wide",ANCHOR_ALIGN_BOTTOM_WIDE);
- p->add_icon_item(get_icon("ControlVcenterWide","EditorIcons"),"VCenter Wide ",ANCHOR_ALIGN_VCENTER_WIDE);
- p->add_icon_item(get_icon("ControlHcenterWide","EditorIcons"),"HCenter Wide ",ANCHOR_ALIGN_HCENTER_WIDE);
+ p->add_icon_item(get_icon("ControlAlignLeftWide", "EditorIcons"), "Left Wide", ANCHOR_ALIGN_LEFT_WIDE);
+ p->add_icon_item(get_icon("ControlAlignTopWide", "EditorIcons"), "Top Wide", ANCHOR_ALIGN_TOP_WIDE);
+ p->add_icon_item(get_icon("ControlAlignRightWide", "EditorIcons"), "Right Wide", ANCHOR_ALIGN_RIGHT_WIDE);
+ p->add_icon_item(get_icon("ControlAlignBottomWide", "EditorIcons"), "Bottom Wide", ANCHOR_ALIGN_BOTTOM_WIDE);
+ p->add_icon_item(get_icon("ControlVcenterWide", "EditorIcons"), "VCenter Wide ", ANCHOR_ALIGN_VCENTER_WIDE);
+ p->add_icon_item(get_icon("ControlHcenterWide", "EditorIcons"), "HCenter Wide ", ANCHOR_ALIGN_HCENTER_WIDE);
p->add_separator();
- p->add_icon_item(get_icon("ControlAlignWide","EditorIcons"),"Full Rect",ANCHOR_ALIGN_WIDE);
+ p->add_icon_item(get_icon("ControlAlignWide", "EditorIcons"), "Full Rect", ANCHOR_ALIGN_WIDE);
-
- AnimationPlayerEditor::singleton->get_key_editor()->connect("visibility_changed",this,"_keying_changed");
+ AnimationPlayerEditor::singleton->get_key_editor()->connect("visibility_changed", this, "_keying_changed");
_keying_changed();
}
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
- get_tree()->connect("node_removed",this,"_node_removed");
+ get_tree()->connect("node_removed", this, "_node_removed");
}
- if (p_what==NOTIFICATION_DRAW) {
-
-
-
+ if (p_what == NOTIFICATION_DRAW) {
}
}
void CanvasItemEditor::edit(CanvasItem *p_canvas_item) {
- drag=DRAG_NONE;
+ drag = DRAG_NONE;
- editor_selection->clear();//_clear_canvas_items();
+ editor_selection->clear(); //_clear_canvas_items();
editor_selection->add_node(p_canvas_item);
//_add_canvas_item(p_canvas_item);
viewport->update();
-
}
-
-void CanvasItemEditor::_find_canvas_items_span(Node *p_node, Rect2& r_rect, const Transform2D& p_xform) {
-
-
+void CanvasItemEditor::_find_canvas_items_span(Node *p_node, Rect2 &r_rect, const Transform2D &p_xform) {
if (!p_node)
return;
- CanvasItem *c=p_node->cast_to<CanvasItem>();
-
+ CanvasItem *c = p_node->cast_to<CanvasItem>();
- for (int i=p_node->get_child_count()-1;i>=0;i--) {
+ for (int i = p_node->get_child_count() - 1; i >= 0; i--) {
//CanvasItem *r=NULL;
if (c && !c->is_set_as_toplevel())
- _find_canvas_items_span(p_node->get_child(i),r_rect,p_xform * c->get_transform());
+ _find_canvas_items_span(p_node->get_child(i), r_rect, p_xform * c->get_transform());
else
- _find_canvas_items_span(p_node->get_child(i),r_rect,Transform2D());
+ _find_canvas_items_span(p_node->get_child(i), r_rect, Transform2D());
}
-
-
if (c && c->is_visible_in_tree()) {
Rect2 rect = c->get_item_rect();
Transform2D xform = p_xform * c->get_transform();
-
LockList lock;
- lock.lock=c->has_meta("_edit_lock_");
- lock.group=c->has_meta("_edit_group_");
+ lock.lock = c->has_meta("_edit_lock_");
+ lock.group = c->has_meta("_edit_group_");
if (lock.group || lock.lock) {
- lock.pos=xform.xform(rect.pos);
+ lock.pos = xform.xform(rect.pos);
lock_list.push_back(lock);
}
@@ -2374,221 +2219,205 @@ void CanvasItemEditor::_find_canvas_items_span(Node *p_node, Rect2& r_rect, cons
ObjectID id = c->get_instance_ID();
if (!bone_list.has(id)) {
BoneList bone;
- bone.bone=id;
- bone_list[id]=bone;
+ bone.bone = id;
+ bone_list[id] = bone;
}
- bone_list[id].last_pass=bone_last_frame;
+ bone_list[id].last_pass = bone_last_frame;
}
- r_rect.expand_to( xform.xform(rect.pos) );
- r_rect.expand_to( xform.xform(rect.pos+Point2(rect.size.x,0)) );
- r_rect.expand_to( xform.xform(rect.pos+Point2(0,rect.size.y)) );
- r_rect.expand_to( xform.xform(rect.pos+rect.size) );
-
+ r_rect.expand_to(xform.xform(rect.pos));
+ r_rect.expand_to(xform.xform(rect.pos + Point2(rect.size.x, 0)));
+ r_rect.expand_to(xform.xform(rect.pos + Point2(0, rect.size.y)));
+ r_rect.expand_to(xform.xform(rect.pos + rect.size));
}
-
}
void CanvasItemEditor::_update_scrollbars() {
-
- updating_scroll=true;
+ updating_scroll = true;
Size2 size = viewport->get_size();
Size2 hmin = h_scroll->get_minimum_size();
Size2 vmin = v_scroll->get_minimum_size();
- v_scroll->set_begin( Point2(size.width - vmin.width, 0) );
- v_scroll->set_end( Point2(size.width, size.height) );
-
- h_scroll->set_begin( Point2( 0, size.height - hmin.height) );
- h_scroll->set_end( Point2(size.width-vmin.width, size.height) );
+ v_scroll->set_begin(Point2(size.width - vmin.width, 0));
+ v_scroll->set_end(Point2(size.width, size.height));
+ h_scroll->set_begin(Point2(0, size.height - hmin.height));
+ h_scroll->set_end(Point2(size.width - vmin.width, size.height));
- Size2 screen_rect = Size2( GlobalConfig::get_singleton()->get("display/window/width"), GlobalConfig::get_singleton()->get("display/window/height") );
+ Size2 screen_rect = Size2(GlobalConfig::get_singleton()->get("display/window/width"), GlobalConfig::get_singleton()->get("display/window/height"));
+ Rect2 local_rect = Rect2(Point2(), viewport->get_size() - Size2(vmin.width, hmin.height));
- Rect2 local_rect = Rect2(Point2(),viewport->get_size()-Size2(vmin.width,hmin.height));
-
- Rect2 canvas_item_rect=Rect2(Point2(),screen_rect);
+ Rect2 canvas_item_rect = Rect2(Point2(), screen_rect);
lock_list.clear();
bone_last_frame++;
-
-
if (editor->get_edited_scene())
- _find_canvas_items_span(editor->get_edited_scene(),canvas_item_rect,Transform2D());
+ _find_canvas_items_span(editor->get_edited_scene(), canvas_item_rect, Transform2D());
- List<Map<ObjectID,BoneList>::Element*> bone_to_erase;
+ List<Map<ObjectID, BoneList>::Element *> bone_to_erase;
- for(Map<ObjectID,BoneList>::Element*E=bone_list.front();E;E=E->next()) {
+ for (Map<ObjectID, BoneList>::Element *E = bone_list.front(); E; E = E->next()) {
- if (E->get().last_pass!=bone_last_frame) {
+ if (E->get().last_pass != bone_last_frame) {
bone_to_erase.push_back(E);
}
}
- while(bone_to_erase.size()) {
+ while (bone_to_erase.size()) {
bone_list.erase(bone_to_erase.front()->get());
bone_to_erase.pop_front();
}
//expand area so it's easier to do animations and stuff at 0,0
- canvas_item_rect.size+=screen_rect*2;
- canvas_item_rect.pos-=screen_rect;
+ canvas_item_rect.size += screen_rect * 2;
+ canvas_item_rect.pos -= screen_rect;
Point2 ofs;
-
- if (canvas_item_rect.size.height <= (local_rect.size.y/zoom)) {
+ if (canvas_item_rect.size.height <= (local_rect.size.y / zoom)) {
v_scroll->hide();
- ofs.y=canvas_item_rect.pos.y;
+ ofs.y = canvas_item_rect.pos.y;
} else {
v_scroll->show();
v_scroll->set_min(canvas_item_rect.pos.y);
- v_scroll->set_max(canvas_item_rect.pos.y+canvas_item_rect.size.y);
- v_scroll->set_page(local_rect.size.y/zoom);
+ v_scroll->set_max(canvas_item_rect.pos.y + canvas_item_rect.size.y);
+ v_scroll->set_page(local_rect.size.y / zoom);
if (first_update) {
//so 0,0 is visible
v_scroll->set_value(-10);
h_scroll->set_value(-10);
- first_update=false;
-
+ first_update = false;
}
- ofs.y=v_scroll->get_value();
+ ofs.y = v_scroll->get_value();
}
- if (canvas_item_rect.size.width <= (local_rect.size.x/zoom)) {
+ if (canvas_item_rect.size.width <= (local_rect.size.x / zoom)) {
h_scroll->hide();
- ofs.x=canvas_item_rect.pos.x;
+ ofs.x = canvas_item_rect.pos.x;
} else {
h_scroll->show();
h_scroll->set_min(canvas_item_rect.pos.x);
- h_scroll->set_max(canvas_item_rect.pos.x+canvas_item_rect.size.x);
- h_scroll->set_page(local_rect.size.x/zoom);
- ofs.x=h_scroll->get_value();
+ h_scroll->set_max(canvas_item_rect.pos.x + canvas_item_rect.size.x);
+ h_scroll->set_page(local_rect.size.x / zoom);
+ ofs.x = h_scroll->get_value();
}
//transform=Matrix32();
- transform.elements[2]=-ofs*zoom;
+ transform.elements[2] = -ofs * zoom;
editor->get_scene_root()->set_global_canvas_transform(transform);
-
- updating_scroll=false;
+ updating_scroll = false;
//transform.scale_basis(Vector2(zoom,zoom));
-
-
}
void CanvasItemEditor::_update_scroll(float) {
-
if (updating_scroll)
return;
Point2 ofs;
- ofs.x=h_scroll->get_value();
- ofs.y=v_scroll->get_value();
+ ofs.x = h_scroll->get_value();
+ ofs.y = v_scroll->get_value();
//current_window->set_scroll(-ofs);
- transform=Transform2D();
+ transform = Transform2D();
- transform.scale_basis(Size2(zoom,zoom));
- transform.elements[2]=-ofs;
+ transform.scale_basis(Size2(zoom, zoom));
+ transform.elements[2] = -ofs;
editor->get_scene_root()->set_global_canvas_transform(transform);
-
viewport->update();
-
}
-void CanvasItemEditor::_set_anchor(Control::AnchorType p_left,Control::AnchorType p_top,Control::AnchorType p_right,Control::AnchorType p_bottom) {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+void CanvasItemEditor::_set_anchor(Control::AnchorType p_left, Control::AnchorType p_top, Control::AnchorType p_right, Control::AnchorType p_bottom) {
+ List<Node *> &selection = editor_selection->get_selected_node_list();
undo_redo->create_action(TTR("Change Anchors"));
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Control *c = E->get()->cast_to<Control>();
- undo_redo->add_do_method(c,"set_anchor",MARGIN_LEFT,p_left);
- undo_redo->add_do_method(c,"set_anchor",MARGIN_TOP,p_top);
- undo_redo->add_do_method(c,"set_anchor",MARGIN_RIGHT,p_right);
- undo_redo->add_do_method(c,"set_anchor",MARGIN_BOTTOM,p_bottom);
- undo_redo->add_undo_method(c,"set_anchor",MARGIN_LEFT,c->get_anchor(MARGIN_LEFT));
- undo_redo->add_undo_method(c,"set_anchor",MARGIN_TOP,c->get_anchor(MARGIN_TOP));
- undo_redo->add_undo_method(c,"set_anchor",MARGIN_RIGHT,c->get_anchor(MARGIN_RIGHT));
- undo_redo->add_undo_method(c,"set_anchor",MARGIN_BOTTOM,c->get_anchor(MARGIN_BOTTOM));
+ undo_redo->add_do_method(c, "set_anchor", MARGIN_LEFT, p_left);
+ undo_redo->add_do_method(c, "set_anchor", MARGIN_TOP, p_top);
+ undo_redo->add_do_method(c, "set_anchor", MARGIN_RIGHT, p_right);
+ undo_redo->add_do_method(c, "set_anchor", MARGIN_BOTTOM, p_bottom);
+ undo_redo->add_undo_method(c, "set_anchor", MARGIN_LEFT, c->get_anchor(MARGIN_LEFT));
+ undo_redo->add_undo_method(c, "set_anchor", MARGIN_TOP, c->get_anchor(MARGIN_TOP));
+ undo_redo->add_undo_method(c, "set_anchor", MARGIN_RIGHT, c->get_anchor(MARGIN_RIGHT));
+ undo_redo->add_undo_method(c, "set_anchor", MARGIN_BOTTOM, c->get_anchor(MARGIN_BOTTOM));
}
undo_redo->commit_action();
-
}
void CanvasItemEditor::_popup_callback(int p_op) {
- last_option=MenuOption(p_op);
- switch(p_op) {
+ last_option = MenuOption(p_op);
+ switch (p_op) {
case SNAP_USE: {
snap_grid = !snap_grid;
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE);
- edit_menu->get_popup()->set_item_checked(idx,snap_grid);
+ edit_menu->get_popup()->set_item_checked(idx, snap_grid);
} break;
case SNAP_SHOW_GRID: {
snap_show_grid = !snap_show_grid;
int idx = edit_menu->get_popup()->get_item_index(SNAP_SHOW_GRID);
- edit_menu->get_popup()->set_item_checked(idx,snap_show_grid);
+ edit_menu->get_popup()->set_item_checked(idx, snap_show_grid);
viewport->update();
} break;
case SNAP_USE_ROTATION: {
snap_rotation = !snap_rotation;
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE_ROTATION);
- edit_menu->get_popup()->set_item_checked(idx,snap_rotation);
+ edit_menu->get_popup()->set_item_checked(idx, snap_rotation);
} break;
case SNAP_RELATIVE: {
snap_relative = !snap_relative;
int idx = edit_menu->get_popup()->get_item_index(SNAP_RELATIVE);
- edit_menu->get_popup()->set_item_checked(idx,snap_relative);
+ edit_menu->get_popup()->set_item_checked(idx, snap_relative);
} break;
case SNAP_USE_PIXEL: {
snap_pixel = !snap_pixel;
int idx = edit_menu->get_popup()->get_item_index(SNAP_USE_PIXEL);
- edit_menu->get_popup()->set_item_checked(idx,snap_pixel);
+ edit_menu->get_popup()->set_item_checked(idx, snap_pixel);
} break;
case SNAP_CONFIGURE: {
((SnapDialog *)snap_dialog)->set_fields(snap_offset, snap_step, snap_rotation_offset, snap_rotation_step);
- snap_dialog->popup_centered(Size2(220,160));
+ snap_dialog->popup_centered(Size2(220, 160));
} break;
case SKELETON_SHOW_BONES: {
skeleton_show_bones = !skeleton_show_bones;
int idx = skeleton_menu->get_item_index(SKELETON_SHOW_BONES);
- skeleton_menu->set_item_checked(idx,skeleton_show_bones);
+ skeleton_menu->set_item_checked(idx, skeleton_show_bones);
viewport->update();
} break;
case ZOOM_IN: {
- if (zoom>MAX_ZOOM)
+ if (zoom > MAX_ZOOM)
return;
- zoom=zoom*(1.0/0.5);
+ zoom = zoom * (1.0 / 0.5);
_update_scroll(0);
viewport->update();
return;
} break;
case ZOOM_OUT: {
- if (zoom<MIN_ZOOM)
+ if (zoom < MIN_ZOOM)
return;
- zoom=zoom*0.5;
+ zoom = zoom * 0.5;
_update_scroll(0);
viewport->update();
return;
@@ -2596,7 +2425,7 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case ZOOM_RESET: {
- zoom=1;
+ zoom = 1;
_update_scroll(0);
viewport->update();
return;
@@ -2604,51 +2433,49 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case ZOOM_SET: {
- updating_value_dialog=true;
+ updating_value_dialog = true;
dialog_label->set_text(TTR("Zoom (%):"));
dialog_val->set_min(0.1);
dialog_val->set_step(0.1);
dialog_val->set_max(800);
- dialog_val->set_value(zoom*100);
- value_dialog->popup_centered(Size2(200,85));
- updating_value_dialog=false;
-
+ dialog_val->set_value(zoom * 100);
+ value_dialog->popup_centered(Size2(200, 85));
+ updating_value_dialog = false;
} break;
case LOCK_SELECTED: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- canvas_item->set_meta("_edit_lock_",true);
+ canvas_item->set_meta("_edit_lock_", true);
emit_signal("item_lock_status_changed");
}
viewport->update();
} break;
case UNLOCK_SELECTED: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
- canvas_item->set_meta("_edit_lock_",Variant());
+ canvas_item->set_meta("_edit_lock_", Variant());
emit_signal("item_lock_status_changed");
}
@@ -2657,36 +2484,36 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case GROUP_SELECTED: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- canvas_item->set_meta("_edit_group_",true);
+ canvas_item->set_meta("_edit_group_", true);
emit_signal("item_group_status_changed");
}
viewport->update();
} break;
case UNGROUP_SELECTED: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- canvas_item->set_meta("_edit_group_",Variant());
+ canvas_item->set_meta("_edit_group_", Variant());
emit_signal("item_group_status_changed");
}
@@ -2696,23 +2523,21 @@ void CanvasItemEditor::_popup_callback(int p_op) {
case EXPAND_TO_PARENT: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
Control *c = canvas_item->cast_to<Control>();
if (!c)
continue;
c->set_area_as_parent_rect();
-
}
viewport->update();
@@ -2763,114 +2588,111 @@ void CanvasItemEditor::_popup_callback(int p_op) {
//space_selected_items< proj_vector2_y, compare_items_y >();
} break;
case ANCHOR_ALIGN_TOP_LEFT: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_BEGIN);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_BEGIN);
} break;
case ANCHOR_ALIGN_TOP_RIGHT: {
- _set_anchor(ANCHOR_END,ANCHOR_BEGIN,ANCHOR_END,ANCHOR_BEGIN);
+ _set_anchor(ANCHOR_END, ANCHOR_BEGIN, ANCHOR_END, ANCHOR_BEGIN);
} break;
case ANCHOR_ALIGN_BOTTOM_LEFT: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_END,ANCHOR_BEGIN,ANCHOR_END);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_END, ANCHOR_BEGIN, ANCHOR_END);
} break;
case ANCHOR_ALIGN_BOTTOM_RIGHT: {
- _set_anchor(ANCHOR_END,ANCHOR_END,ANCHOR_END,ANCHOR_END);
+ _set_anchor(ANCHOR_END, ANCHOR_END, ANCHOR_END, ANCHOR_END);
} break;
case ANCHOR_ALIGN_CENTER_LEFT: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_CENTER,ANCHOR_BEGIN,ANCHOR_CENTER);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_CENTER, ANCHOR_BEGIN, ANCHOR_CENTER);
} break;
case ANCHOR_ALIGN_CENTER_RIGHT: {
- _set_anchor(ANCHOR_END,ANCHOR_CENTER,ANCHOR_END,ANCHOR_CENTER);
+ _set_anchor(ANCHOR_END, ANCHOR_CENTER, ANCHOR_END, ANCHOR_CENTER);
} break;
case ANCHOR_ALIGN_CENTER_TOP: {
- _set_anchor(ANCHOR_CENTER,ANCHOR_BEGIN,ANCHOR_CENTER,ANCHOR_BEGIN);
+ _set_anchor(ANCHOR_CENTER, ANCHOR_BEGIN, ANCHOR_CENTER, ANCHOR_BEGIN);
} break;
case ANCHOR_ALIGN_CENTER_BOTTOM: {
- _set_anchor(ANCHOR_CENTER,ANCHOR_END,ANCHOR_CENTER,ANCHOR_END);
+ _set_anchor(ANCHOR_CENTER, ANCHOR_END, ANCHOR_CENTER, ANCHOR_END);
} break;
case ANCHOR_ALIGN_CENTER: {
- _set_anchor(ANCHOR_CENTER,ANCHOR_CENTER,ANCHOR_CENTER,ANCHOR_CENTER);
+ _set_anchor(ANCHOR_CENTER, ANCHOR_CENTER, ANCHOR_CENTER, ANCHOR_CENTER);
} break;
case ANCHOR_ALIGN_TOP_WIDE: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_END,ANCHOR_BEGIN);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_END, ANCHOR_BEGIN);
} break;
case ANCHOR_ALIGN_LEFT_WIDE: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_END);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_END);
} break;
case ANCHOR_ALIGN_RIGHT_WIDE: {
- _set_anchor(ANCHOR_END,ANCHOR_BEGIN,ANCHOR_END,ANCHOR_END);
+ _set_anchor(ANCHOR_END, ANCHOR_BEGIN, ANCHOR_END, ANCHOR_END);
} break;
case ANCHOR_ALIGN_BOTTOM_WIDE: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_END,ANCHOR_END,ANCHOR_END);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_END, ANCHOR_END, ANCHOR_END);
} break;
case ANCHOR_ALIGN_VCENTER_WIDE: {
- _set_anchor(ANCHOR_CENTER,ANCHOR_BEGIN,ANCHOR_CENTER,ANCHOR_END);
+ _set_anchor(ANCHOR_CENTER, ANCHOR_BEGIN, ANCHOR_CENTER, ANCHOR_END);
} break;
case ANCHOR_ALIGN_HCENTER_WIDE: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_CENTER,ANCHOR_END,ANCHOR_CENTER);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_CENTER, ANCHOR_END, ANCHOR_CENTER);
} break;
case ANCHOR_ALIGN_WIDE: {
- _set_anchor(ANCHOR_BEGIN,ANCHOR_BEGIN,ANCHOR_END,ANCHOR_END);
+ _set_anchor(ANCHOR_BEGIN, ANCHOR_BEGIN, ANCHOR_END, ANCHOR_END);
} break;
case ANIM_INSERT_KEY:
case ANIM_INSERT_KEY_EXISTING: {
- bool existing = p_op==ANIM_INSERT_KEY_EXISTING;
+ bool existing = p_op == ANIM_INSERT_KEY_EXISTING;
- Map<Node*,Object*> &selection = editor_selection->get_selection();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
if (canvas_item->cast_to<Node2D>()) {
Node2D *n2d = canvas_item->cast_to<Node2D>();
if (key_pos)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d,"transform/pos",n2d->get_position(),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "transform/pos", n2d->get_position(), existing);
if (key_rot)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d,"transform/rot",Math::rad2deg(n2d->get_rotation()),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "transform/rot", Math::rad2deg(n2d->get_rotation()), existing);
if (key_scale)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d,"transform/scale",n2d->get_scale(),existing);
-
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(n2d, "transform/scale", n2d->get_scale(), existing);
if (n2d->has_meta("_edit_bone_") && n2d->get_parent_item()) {
//look for an IK chain
- List<Node2D*> ik_chain;
+ List<Node2D *> ik_chain;
Node2D *n = n2d->get_parent_item()->cast_to<Node2D>();
- bool has_chain=false;
+ bool has_chain = false;
- while(n) {
+ while (n) {
ik_chain.push_back(n);
if (n->has_meta("_edit_ik_")) {
- has_chain=true;
+ has_chain = true;
break;
}
if (!n->get_parent_item())
break;
- n=n->get_parent_item()->cast_to<Node2D>();
+ n = n->get_parent_item()->cast_to<Node2D>();
}
if (has_chain && ik_chain.size()) {
- for(List<Node2D*>::Element *F=ik_chain.front();F;F=F->next()) {
+ for (List<Node2D *>::Element *F = ik_chain.front(); F; F = F->next()) {
if (key_pos)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(),"transform/pos",F->get()->get_position(),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "transform/pos", F->get()->get_position(), existing);
if (key_rot)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(),"transform/rot",Math::rad2deg(F->get()->get_rotation()),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "transform/rot", Math::rad2deg(F->get()->get_rotation()), existing);
if (key_scale)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(),"transform/scale",F->get()->get_scale(),existing);
-
-
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(F->get(), "transform/scale", F->get()->get_scale(), existing);
}
}
}
@@ -2880,11 +2702,10 @@ void CanvasItemEditor::_popup_callback(int p_op) {
Control *ctrl = canvas_item->cast_to<Control>();
if (key_pos)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl,"rect/pos",ctrl->get_pos(),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl, "rect/pos", ctrl->get_pos(), existing);
if (key_scale)
- AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl,"rect/size",ctrl->get_size(),existing);
+ AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl, "rect/size", ctrl->get_size(), existing);
}
-
}
} break;
@@ -2900,7 +2721,7 @@ void CanvasItemEditor::_popup_callback(int p_op) {
key_scale = key_scale_button->is_pressed();
} break;
- /*
+ /*
case ANIM_INSERT_POS_ROT
case ANIM_INSERT_POS_SCALE:
case ANIM_INSERT_ROT_SCALE:
@@ -2929,32 +2750,29 @@ void CanvasItemEditor::_popup_callback(int p_op) {
pose_clipboard.clear();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- Map<Node*,Object*> &selection = editor_selection->get_selection();
-
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
if (canvas_item->cast_to<Node2D>()) {
Node2D *n2d = canvas_item->cast_to<Node2D>();
PoseClipboard pc;
- pc.pos=n2d->get_position();
- pc.rot=n2d->get_rotation();
- pc.scale=n2d->get_scale();
- pc.id=n2d->get_instance_ID();
+ pc.pos = n2d->get_position();
+ pc.rot = n2d->get_rotation();
+ pc.scale = n2d->get_scale();
+ pc.id = n2d->get_instance_ID();
pose_clipboard.push_back(pc);
}
}
-
} break;
case ANIM_PASTE_POSE: {
@@ -2962,7 +2780,7 @@ void CanvasItemEditor::_popup_callback(int p_op) {
break;
undo_redo->create_action(TTR("Paste Pose"));
- for (List<PoseClipboard>::Element *E=pose_clipboard.front();E;E=E->next()) {
+ for (List<PoseClipboard>::Element *E = pose_clipboard.front(); E; E = E->next()) {
Object *o = ObjectDB::get_instance(E->get().id);
if (!o)
@@ -2970,27 +2788,27 @@ void CanvasItemEditor::_popup_callback(int p_op) {
Node2D *n2d = o->cast_to<Node2D>();
if (!n2d)
continue;
- undo_redo->add_do_method(n2d,"set_pos",E->get().pos);
- undo_redo->add_do_method(n2d,"set_rot",E->get().rot);
- undo_redo->add_do_method(n2d,"set_scale",E->get().scale);
- undo_redo->add_undo_method(n2d,"set_pos",n2d->get_position());
- undo_redo->add_undo_method(n2d,"set_rot",n2d->get_rotation());
- undo_redo->add_undo_method(n2d,"set_scale",n2d->get_scale());
+ undo_redo->add_do_method(n2d, "set_pos", E->get().pos);
+ undo_redo->add_do_method(n2d, "set_rot", E->get().rot);
+ undo_redo->add_do_method(n2d, "set_scale", E->get().scale);
+ undo_redo->add_undo_method(n2d, "set_pos", n2d->get_position());
+ undo_redo->add_undo_method(n2d, "set_rot", n2d->get_rotation());
+ undo_redo->add_undo_method(n2d, "set_scale", n2d->get_scale());
}
undo_redo->commit_action();
} break;
case ANIM_CLEAR_POSE: {
- Map<Node*,Object*> &selection = editor_selection->get_selection();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
if (canvas_item->cast_to<Node2D>()) {
@@ -3001,7 +2819,7 @@ void CanvasItemEditor::_popup_callback(int p_op) {
if (key_rot)
n2d->set_rotation(0);
if (key_scale)
- n2d->set_scale(Vector2(1,1));
+ n2d->set_scale(Vector2(1, 1));
} else if (canvas_item->cast_to<Control>()) {
Control *ctrl = canvas_item->cast_to<Control>();
@@ -3013,10 +2831,8 @@ void CanvasItemEditor::_popup_callback(int p_op) {
AnimationPlayerEditor::singleton->get_key_editor()->insert_node_value_key(ctrl,"rect/size",ctrl->get_size());
*/
}
-
}
-
} break;
case VIEW_CENTER_TO_SELECTION:
case VIEW_FRAME_TO_SELECTION: {
@@ -3026,11 +2842,9 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case SKELETON_MAKE_BONES: {
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
-
- Map<Node*,Object*> &selection = editor_selection->get_selection();
-
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Node2D *n2d = E->key()->cast_to<Node2D>();
if (!n2d)
@@ -3040,19 +2854,18 @@ void CanvasItemEditor::_popup_callback(int p_op) {
if (!n2d->get_parent_item())
continue;
- n2d->set_meta("_edit_bone_",true);
+ n2d->set_meta("_edit_bone_", true);
if (!skeleton_show_bones)
skeleton_menu->activate_item(skeleton_menu->get_item_index(SKELETON_SHOW_BONES));
-
}
viewport->update();
} break;
case SKELETON_CLEAR_BONES: {
- Map<Node*,Object*> &selection = editor_selection->get_selection();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Node2D *n2d = E->key()->cast_to<Node2D>();
if (!n2d)
@@ -3060,31 +2873,29 @@ void CanvasItemEditor::_popup_callback(int p_op) {
if (!n2d->is_visible_in_tree())
continue;
- n2d->set_meta("_edit_bone_",Variant());
+ n2d->set_meta("_edit_bone_", Variant());
if (!skeleton_show_bones)
skeleton_menu->activate_item(skeleton_menu->get_item_index(SKELETON_SHOW_BONES));
-
}
viewport->update();
} break;
case SKELETON_SET_IK_CHAIN: {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->get()->cast_to<CanvasItem>();
if (!canvas_item || !canvas_item->is_visible_in_tree())
continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
- canvas_item->set_meta("_edit_ik_",true);
+ canvas_item->set_meta("_edit_ik_", true);
if (!skeleton_show_bones)
skeleton_menu->activate_item(skeleton_menu->get_item_index(SKELETON_SHOW_BONES));
-
}
viewport->update();
@@ -3092,9 +2903,9 @@ void CanvasItemEditor::_popup_callback(int p_op) {
} break;
case SKELETON_CLEAR_IK_CHAIN: {
- Map<Node*,Object*> &selection = editor_selection->get_selection();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *n2d = E->key()->cast_to<CanvasItem>();
if (!n2d)
@@ -3102,15 +2913,13 @@ void CanvasItemEditor::_popup_callback(int p_op) {
if (!n2d->is_visible_in_tree())
continue;
- n2d->set_meta("_edit_ik_",Variant());
+ n2d->set_meta("_edit_ik_", Variant());
if (!skeleton_show_bones)
skeleton_menu->activate_item(skeleton_menu->get_item_index(SKELETON_SHOW_BONES));
-
}
viewport->update();
} break;
-
}
}
#if 0
@@ -3142,20 +2951,18 @@ template< class P, class C > void CanvasItemEditor::space_selected_items() {
}
#endif
-
void CanvasItemEditor::_focus_selection(int p_op) {
Vector2 center(0.f, 0.f);
Rect2 rect;
int count = 0;
- Map<Node*,Object*> &selection = editor_selection->get_selection();
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
CanvasItem *canvas_item = E->key()->cast_to<CanvasItem>();
if (!canvas_item) continue;
- if (canvas_item->get_viewport()!=EditorNode::get_singleton()->get_scene_root())
+ if (canvas_item->get_viewport() != EditorNode::get_singleton()->get_scene_root())
continue;
-
// counting invisible items, for now
//if (!canvas_item->is_visible_in_tree()) continue;
++count;
@@ -3166,30 +2973,30 @@ void CanvasItemEditor::_focus_selection(int p_op) {
Vector2 scale = canvas_item->get_global_transform().get_scale();
real_t angle = canvas_item->get_global_transform().get_rotation();
- Transform2D t(angle, Vector2(0.f,0.f));
+ Transform2D t(angle, Vector2(0.f, 0.f));
item_rect = t.xform(item_rect);
- Rect2 canvas_item_rect(pos + scale*item_rect.pos, scale*item_rect.size);
+ Rect2 canvas_item_rect(pos + scale * item_rect.pos, scale * item_rect.size);
if (count == 1) {
rect = canvas_item_rect;
} else {
rect = rect.merge(canvas_item_rect);
}
};
- if (count==0) return;
+ if (count == 0) return;
if (p_op == VIEW_CENTER_TO_SELECTION) {
- center = rect.pos + rect.size/2;
- Vector2 offset = viewport->get_size()/2 - editor->get_scene_root()->get_global_canvas_transform().xform(center);
- h_scroll->set_value(h_scroll->get_value() - offset.x/zoom);
- v_scroll->set_value(v_scroll->get_value() - offset.y/zoom);
+ center = rect.pos + rect.size / 2;
+ Vector2 offset = viewport->get_size() / 2 - editor->get_scene_root()->get_global_canvas_transform().xform(center);
+ h_scroll->set_value(h_scroll->get_value() - offset.x / zoom);
+ v_scroll->set_value(v_scroll->get_value() - offset.y / zoom);
} else { // VIEW_FRAME_TO_SELECTION
if (rect.size.x > CMP_EPSILON && rect.size.y > CMP_EPSILON) {
- float scale_x = viewport->get_size().x/rect.size.x;
- float scale_y = viewport->get_size().y/rect.size.y;
- zoom = scale_x < scale_y? scale_x:scale_y;
+ float scale_x = viewport->get_size().x / rect.size.x;
+ float scale_y = viewport->get_size().y / rect.size.y;
+ zoom = scale_x < scale_y ? scale_x : scale_y;
zoom *= 0.90;
_update_scroll(0);
call_deferred("_popup_callback", VIEW_CENTER_TO_SELECTION);
@@ -3197,27 +3004,25 @@ void CanvasItemEditor::_focus_selection(int p_op) {
}
}
-
void CanvasItemEditor::_bind_methods() {
- ClassDB::bind_method("_node_removed",&CanvasItemEditor::_node_removed);
- ClassDB::bind_method("_update_scroll",&CanvasItemEditor::_update_scroll);
- ClassDB::bind_method("_popup_callback",&CanvasItemEditor::_popup_callback);
- ClassDB::bind_method("_visibility_changed",&CanvasItemEditor::_visibility_changed);
- ClassDB::bind_method("_dialog_value_changed",&CanvasItemEditor::_dialog_value_changed);
- ClassDB::bind_method("_get_editor_data",&CanvasItemEditor::_get_editor_data);
- ClassDB::bind_method("_tool_select",&CanvasItemEditor::_tool_select);
- ClassDB::bind_method("_keying_changed",&CanvasItemEditor::_keying_changed);
- ClassDB::bind_method("_unhandled_key_input",&CanvasItemEditor::_unhandled_key_input);
- ClassDB::bind_method("_viewport_draw",&CanvasItemEditor::_viewport_draw);
- ClassDB::bind_method("_viewport_gui_input",&CanvasItemEditor::_viewport_gui_input);
- ClassDB::bind_method("_snap_changed",&CanvasItemEditor::_snap_changed);
- ClassDB::bind_method(D_METHOD("_selection_result_pressed"),&CanvasItemEditor::_selection_result_pressed);
- ClassDB::bind_method(D_METHOD("_selection_menu_hide"),&CanvasItemEditor::_selection_menu_hide);
-
- ADD_SIGNAL( MethodInfo("item_lock_status_changed") );
- ADD_SIGNAL( MethodInfo("item_group_status_changed") );
-
+ ClassDB::bind_method("_node_removed", &CanvasItemEditor::_node_removed);
+ ClassDB::bind_method("_update_scroll", &CanvasItemEditor::_update_scroll);
+ ClassDB::bind_method("_popup_callback", &CanvasItemEditor::_popup_callback);
+ ClassDB::bind_method("_visibility_changed", &CanvasItemEditor::_visibility_changed);
+ ClassDB::bind_method("_dialog_value_changed", &CanvasItemEditor::_dialog_value_changed);
+ ClassDB::bind_method("_get_editor_data", &CanvasItemEditor::_get_editor_data);
+ ClassDB::bind_method("_tool_select", &CanvasItemEditor::_tool_select);
+ ClassDB::bind_method("_keying_changed", &CanvasItemEditor::_keying_changed);
+ ClassDB::bind_method("_unhandled_key_input", &CanvasItemEditor::_unhandled_key_input);
+ ClassDB::bind_method("_viewport_draw", &CanvasItemEditor::_viewport_draw);
+ ClassDB::bind_method("_viewport_gui_input", &CanvasItemEditor::_viewport_gui_input);
+ ClassDB::bind_method("_snap_changed", &CanvasItemEditor::_snap_changed);
+ ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &CanvasItemEditor::_selection_result_pressed);
+ ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &CanvasItemEditor::_selection_menu_hide);
+
+ ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
+ ADD_SIGNAL(MethodInfo("item_group_status_changed"));
}
#if 0
@@ -3303,142 +3108,135 @@ VSplitContainer *CanvasItemEditor::get_bottom_split() {
return bottom_split;
}
-
void CanvasItemEditor::focus_selection() {
_focus_selection(VIEW_CENTER_TO_SELECTION);
}
-
CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
tool = TOOL_SELECT;
- undo_redo=p_editor->get_undo_redo();
- editor=p_editor;
- editor_selection=p_editor->get_editor_selection();
+ undo_redo = p_editor->get_undo_redo();
+ editor = p_editor;
+ editor_selection = p_editor->get_editor_selection();
editor_selection->add_editor_plugin(this);
- editor_selection->connect("selection_changed",this,"update");
+ editor_selection->connect("selection_changed", this, "update");
-
- hb = memnew( HBoxContainer );
- add_child( hb );
+ hb = memnew(HBoxContainer);
+ add_child(hb);
hb->set_area_as_parent_rect();
- bottom_split = memnew( VSplitContainer );
+ bottom_split = memnew(VSplitContainer);
bottom_split->set_v_size_flags(SIZE_EXPAND_FILL);
add_child(bottom_split);
- palette_split = memnew( HSplitContainer);
+ palette_split = memnew(HSplitContainer);
palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
bottom_split->add_child(palette_split);
- Control *vp_base = memnew (Control);
+ Control *vp_base = memnew(Control);
vp_base->set_v_size_flags(SIZE_EXPAND_FILL);
palette_split->add_child(vp_base);
- ViewportContainer *vp = memnew (ViewportContainer);
+ ViewportContainer *vp = memnew(ViewportContainer);
vp->set_stretch(true);
vp_base->add_child(vp);
vp->set_area_as_parent_rect();
vp->add_child(p_editor->get_scene_root());
-
- viewport = memnew( CanvasItemEditorViewport(p_editor, this) );
+ viewport = memnew(CanvasItemEditorViewport(p_editor, this));
vp_base->add_child(viewport);
viewport->set_area_as_parent_rect();
viewport->set_clip_contents(true);
- h_scroll = memnew( HScrollBar );
- v_scroll = memnew( VScrollBar );
+ h_scroll = memnew(HScrollBar);
+ v_scroll = memnew(VScrollBar);
viewport->add_child(h_scroll);
viewport->add_child(v_scroll);
- viewport->connect("draw",this,"_viewport_draw");
- viewport->connect("gui_input",this,"_viewport_gui_input");
+ viewport->connect("draw", this, "_viewport_draw");
+ viewport->connect("gui_input", this, "_viewport_gui_input");
-
- h_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),Object::CONNECT_DEFERRED);
- v_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),Object::CONNECT_DEFERRED);
+ h_scroll->connect("value_changed", this, "_update_scroll", Vector<Variant>(), Object::CONNECT_DEFERRED);
+ v_scroll->connect("value_changed", this, "_update_scroll", Vector<Variant>(), Object::CONNECT_DEFERRED);
h_scroll->hide();
v_scroll->hide();
- updating_scroll=false;
+ updating_scroll = false;
viewport->set_focus_mode(FOCUS_ALL);
- handle_len=10;
- first_update=true;
-
+ handle_len = 10;
+ first_update = true;
- select_button = memnew( ToolButton );
+ select_button = memnew(ToolButton);
select_button->set_toggle_mode(true);
hb->add_child(select_button);
- select_button->connect("pressed",this,"_tool_select",make_binds(TOOL_SELECT));
+ select_button->connect("pressed", this, "_tool_select", make_binds(TOOL_SELECT));
select_button->set_pressed(true);
- select_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/select_mode",TTR("Select Mode"),KEY_Q));
- select_button->set_tooltip(TTR("Select Mode")+" $sc\n"+keycode_get_string(KEY_MASK_CMD)+TTR("Drag: Rotate")+"\n"+TTR("Alt+Drag: Move")+"\n"+TTR("Press 'v' to Change Pivot, 'Shift+v' to Drag Pivot (while moving).")+"\n"+TTR("Alt+RMB: Depth list selection"));
+ select_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/select_mode", TTR("Select Mode"), KEY_Q));
+ select_button->set_tooltip(TTR("Select Mode") + " $sc\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Drag: Rotate") + "\n" + TTR("Alt+Drag: Move") + "\n" + TTR("Press 'v' to Change Pivot, 'Shift+v' to Drag Pivot (while moving).") + "\n" + TTR("Alt+RMB: Depth list selection"));
-
- move_button = memnew( ToolButton );
+ move_button = memnew(ToolButton);
move_button->set_toggle_mode(true);
hb->add_child(move_button);
- move_button->connect("pressed",this,"_tool_select",make_binds(TOOL_MOVE));
- move_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/move_mode",TTR("Move Mode"),KEY_W));
+ move_button->connect("pressed", this, "_tool_select", make_binds(TOOL_MOVE));
+ move_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/move_mode", TTR("Move Mode"), KEY_W));
move_button->set_tooltip(TTR("Move Mode"));
- rotate_button = memnew( ToolButton );
+ rotate_button = memnew(ToolButton);
rotate_button->set_toggle_mode(true);
hb->add_child(rotate_button);
- rotate_button->connect("pressed",this,"_tool_select",make_binds(TOOL_ROTATE));
- rotate_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/rotate_mode",TTR("Rotate Mode"),KEY_E));
+ rotate_button->connect("pressed", this, "_tool_select", make_binds(TOOL_ROTATE));
+ rotate_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/rotate_mode", TTR("Rotate Mode"), KEY_E));
rotate_button->set_tooltip(TTR("Rotate Mode"));
hb->add_child(memnew(VSeparator));
- list_select_button = memnew( ToolButton );
+ list_select_button = memnew(ToolButton);
list_select_button->set_toggle_mode(true);
hb->add_child(list_select_button);
- list_select_button->connect("pressed",this,"_tool_select",make_binds(TOOL_LIST_SELECT));
+ list_select_button->connect("pressed", this, "_tool_select", make_binds(TOOL_LIST_SELECT));
list_select_button->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode)."));
- pivot_button = memnew( ToolButton );
+ pivot_button = memnew(ToolButton);
pivot_button->set_toggle_mode(true);
hb->add_child(pivot_button);
- pivot_button->connect("pressed",this,"_tool_select",make_binds(TOOL_EDIT_PIVOT));
+ pivot_button->connect("pressed", this, "_tool_select", make_binds(TOOL_EDIT_PIVOT));
pivot_button->set_tooltip(TTR("Click to change object's rotation pivot."));
- pan_button = memnew( ToolButton );
+ pan_button = memnew(ToolButton);
pan_button->set_toggle_mode(true);
hb->add_child(pan_button);
- pan_button->connect("pressed",this,"_tool_select",make_binds(TOOL_PAN));
+ pan_button->connect("pressed", this, "_tool_select", make_binds(TOOL_PAN));
pan_button->set_tooltip(TTR("Pan Mode"));
hb->add_child(memnew(VSeparator));
- lock_button = memnew( ToolButton );
+ lock_button = memnew(ToolButton);
hb->add_child(lock_button);
- lock_button->connect("pressed",this,"_popup_callback",varray(LOCK_SELECTED));
+ lock_button->connect("pressed", this, "_popup_callback", varray(LOCK_SELECTED));
lock_button->set_tooltip(TTR("Lock the selected object in place (can't be moved)."));
- unlock_button = memnew( ToolButton );
+ unlock_button = memnew(ToolButton);
hb->add_child(unlock_button);
- unlock_button->connect("pressed",this,"_popup_callback",varray(UNLOCK_SELECTED));
+ unlock_button->connect("pressed", this, "_popup_callback", varray(UNLOCK_SELECTED));
unlock_button->set_tooltip(TTR("Unlock the selected object (can be moved)."));
- group_button = memnew( ToolButton );
+ group_button = memnew(ToolButton);
hb->add_child(group_button);
- group_button->connect("pressed",this,"_popup_callback",varray(GROUP_SELECTED));
+ group_button->connect("pressed", this, "_popup_callback", varray(GROUP_SELECTED));
group_button->set_tooltip(TTR("Makes sure the object's children are not selectable."));
- ungroup_button = memnew( ToolButton );
+ ungroup_button = memnew(ToolButton);
hb->add_child(ungroup_button);
- ungroup_button->connect("pressed",this,"_popup_callback",varray(UNGROUP_SELECTED));
+ ungroup_button->connect("pressed", this, "_popup_callback", varray(UNGROUP_SELECTED));
ungroup_button->set_tooltip(TTR("Restores the object's children's ability to be selected."));
hb->add_child(memnew(VSeparator));
- edit_menu = memnew( MenuButton );
+ edit_menu = memnew(MenuButton);
edit_menu->set_text(TTR("Edit"));
hb->add_child(edit_menu);
- edit_menu->get_popup()->connect("id_pressed", this,"_popup_callback");
+ edit_menu->get_popup()->connect("id_pressed", this, "_popup_callback");
PopupMenu *p;
p = edit_menu->get_popup();
@@ -3452,19 +3250,18 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
p->add_separator();
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/expand_to_parent", TTR("Expand to Parent"), KEY_MASK_CMD | KEY_P), EXPAND_TO_PARENT);
p->add_separator();
- p->add_submenu_item(TTR("Skeleton.."),"skeleton");
+ p->add_submenu_item(TTR("Skeleton.."), "skeleton");
skeleton_menu = memnew(PopupMenu);
p->add_child(skeleton_menu);
skeleton_menu->set_name("skeleton");
- skeleton_menu->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_make_bones", TTR("Make Bones"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B ),SKELETON_MAKE_BONES);
+ skeleton_menu->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_make_bones", TTR("Make Bones"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_B), SKELETON_MAKE_BONES);
skeleton_menu->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_clear_bones", TTR("Clear Bones")), SKELETON_CLEAR_BONES);
skeleton_menu->add_separator();
skeleton_menu->add_check_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_show_bones", TTR("Show Bones")), SKELETON_SHOW_BONES);
skeleton_menu->add_separator();
skeleton_menu->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_set_ik_chain", TTR("Make IK Chain")), SKELETON_SET_IK_CHAIN);
skeleton_menu->add_shortcut(ED_SHORTCUT("canvas_item_editor/skeleton_clear_ik_chain", TTR("Clear IK Chain")), SKELETON_CLEAR_IK_CHAIN);
- skeleton_menu->connect("id_pressed", this,"_popup_callback");
-
+ skeleton_menu->connect("id_pressed", this, "_popup_callback");
/*
p->add_item("Align Horizontal",ALIGN_HORIZONTAL);
@@ -3472,10 +3269,10 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
p->add_item("Space Horizontal",SPACE_HORIZONTAL);
p->add_item("Space Vertical",SPACE_VERTICAL);*/
- view_menu = memnew( MenuButton );
+ view_menu = memnew(MenuButton);
view_menu->set_text(TTR("View"));
hb->add_child(view_menu);
- view_menu->get_popup()->connect("id_pressed", this,"_popup_callback");
+ view_menu->get_popup()->connect("id_pressed", this, "_popup_callback");
p = view_menu->get_popup();
@@ -3487,123 +3284,121 @@ CanvasItemEditor::CanvasItemEditor(EditorNode *p_editor) {
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/center_selection", TTR("Center Selection"), KEY_F), VIEW_CENTER_TO_SELECTION);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/frame_selection", TTR("Frame Selection"), KEY_MASK_SHIFT | KEY_F), VIEW_FRAME_TO_SELECTION);
- anchor_menu = memnew( MenuButton );
+ anchor_menu = memnew(MenuButton);
anchor_menu->set_text(TTR("Anchor"));
hb->add_child(anchor_menu);
- anchor_menu->get_popup()->connect("id_pressed", this,"_popup_callback");
+ anchor_menu->get_popup()->connect("id_pressed", this, "_popup_callback");
anchor_menu->hide();
//p = anchor_menu->get_popup();
-
-
- animation_hb = memnew( HBoxContainer );
+ animation_hb = memnew(HBoxContainer);
hb->add_child(animation_hb);
- animation_hb->add_child( memnew( VSeparator ));
+ animation_hb->add_child(memnew(VSeparator));
animation_hb->hide();
- key_loc_button = memnew( Button("loc"));
+ key_loc_button = memnew(Button("loc"));
key_loc_button->set_toggle_mode(true);
key_loc_button->set_pressed(true);
key_loc_button->set_focus_mode(FOCUS_NONE);
- key_loc_button->add_color_override("font_color",Color(1,0.6,0.6));
- key_loc_button->add_color_override("font_color_pressed",Color(0.6,1,0.6));
- key_loc_button->connect("pressed",this,"_popup_callback",varray(ANIM_INSERT_POS));
+ key_loc_button->add_color_override("font_color", Color(1, 0.6, 0.6));
+ key_loc_button->add_color_override("font_color_pressed", Color(0.6, 1, 0.6));
+ key_loc_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_POS));
animation_hb->add_child(key_loc_button);
- key_rot_button = memnew( Button("rot"));
+ key_rot_button = memnew(Button("rot"));
key_rot_button->set_toggle_mode(true);
key_rot_button->set_pressed(true);
key_rot_button->set_focus_mode(FOCUS_NONE);
- key_rot_button->add_color_override("font_color",Color(1,0.6,0.6));
- key_rot_button->add_color_override("font_color_pressed",Color(0.6,1,0.6));
- key_rot_button->connect("pressed",this,"_popup_callback",varray(ANIM_INSERT_ROT));
+ key_rot_button->add_color_override("font_color", Color(1, 0.6, 0.6));
+ key_rot_button->add_color_override("font_color_pressed", Color(0.6, 1, 0.6));
+ key_rot_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_ROT));
animation_hb->add_child(key_rot_button);
- key_scale_button = memnew( Button("scl"));
+ key_scale_button = memnew(Button("scl"));
key_scale_button->set_toggle_mode(true);
key_scale_button->set_focus_mode(FOCUS_NONE);
- key_scale_button->add_color_override("font_color",Color(1,0.6,0.6));
- key_scale_button->add_color_override("font_color_pressed",Color(0.6,1,0.6));
- key_scale_button->connect("pressed",this,"_popup_callback",varray(ANIM_INSERT_SCALE));
+ key_scale_button->add_color_override("font_color", Color(1, 0.6, 0.6));
+ key_scale_button->add_color_override("font_color_pressed", Color(0.6, 1, 0.6));
+ key_scale_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_SCALE));
animation_hb->add_child(key_scale_button);
- key_insert_button = memnew( Button );
+ key_insert_button = memnew(Button);
key_insert_button->set_focus_mode(FOCUS_NONE);
- key_insert_button->connect("pressed",this,"_popup_callback",varray(ANIM_INSERT_KEY));
+ key_insert_button->connect("pressed", this, "_popup_callback", varray(ANIM_INSERT_KEY));
key_insert_button->set_tooltip(TTR("Insert Keys"));
key_insert_button->set_shortcut(ED_SHORTCUT("canvas_item_editor/anim_insert_key", TTR("Insert Key"), KEY_INSERT));
animation_hb->add_child(key_insert_button);
- animation_menu = memnew( MenuButton );
+ animation_menu = memnew(MenuButton);
animation_menu->set_text(TTR("Animation"));
animation_hb->add_child(animation_menu);
- animation_menu->get_popup()->connect("id_pressed", this,"_popup_callback");
+ animation_menu->get_popup()->connect("id_pressed", this, "_popup_callback");
p = animation_menu->get_popup();
p->add_shortcut(ED_GET_SHORTCUT("canvas_item_editor/anim_insert_key"), ANIM_INSERT_KEY);
- p->add_shortcut(ED_SHORTCUT("canvas_item_editor/anim_insert_key_existing_tracks", TTR("Insert Key (Existing Tracks)"), KEY_MASK_CMD+KEY_INSERT), ANIM_INSERT_KEY_EXISTING);
+ p->add_shortcut(ED_SHORTCUT("canvas_item_editor/anim_insert_key_existing_tracks", TTR("Insert Key (Existing Tracks)"), KEY_MASK_CMD + KEY_INSERT), ANIM_INSERT_KEY_EXISTING);
p->add_separator();
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/anim_copy_pose", TTR("Copy Pose")), ANIM_COPY_POSE);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/anim_paste_pose", TTR("Paste Pose")), ANIM_PASTE_POSE);
p->add_shortcut(ED_SHORTCUT("canvas_item_editor/anim_clear_pose", TTR("Clear Pose"), KEY_MASK_SHIFT | KEY_K), ANIM_CLEAR_POSE);
- snap_dialog = memnew( SnapDialog );
- snap_dialog->connect("confirmed",this,"_snap_changed");
+ snap_dialog = memnew(SnapDialog);
+ snap_dialog->connect("confirmed", this, "_snap_changed");
add_child(snap_dialog);
- value_dialog = memnew( AcceptDialog );
+ value_dialog = memnew(AcceptDialog);
value_dialog->set_title(TTR("Set a Value"));
value_dialog->get_ok()->set_text(TTR("Close"));
add_child(value_dialog);
Label *l = memnew(Label);
l->set_text(TTR("Snap (Pixels):"));
- l->set_pos(Point2(5,5));
+ l->set_pos(Point2(5, 5));
value_dialog->add_child(l);
- dialog_label=l;
+ dialog_label = l;
- dialog_val=memnew(SpinBox);
- dialog_val->set_anchor(MARGIN_RIGHT,ANCHOR_END);
- dialog_val->set_begin(Point2(15,25));
- dialog_val->set_end(Point2(10,25));
+ dialog_val = memnew(SpinBox);
+ dialog_val->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ dialog_val->set_begin(Point2(15, 25));
+ dialog_val->set_end(Point2(10, 25));
value_dialog->add_child(dialog_val);
- dialog_val->connect("value_changed",this,"_dialog_value_changed");
- select_sb = Ref<StyleBoxTexture>( memnew( StyleBoxTexture) );
+ dialog_val->connect("value_changed", this, "_dialog_value_changed");
+ select_sb = Ref<StyleBoxTexture>(memnew(StyleBoxTexture));
- selection_menu = memnew( PopupMenu );
+ selection_menu = memnew(PopupMenu);
add_child(selection_menu);
selection_menu->set_custom_minimum_size(Vector2(100, 0));
selection_menu->connect("id_pressed", this, "_selection_result_pressed");
selection_menu->connect("popup_hide", this, "_selection_menu_hide");
- key_pos=true;
- key_rot=true;
- key_scale=false;
-
- zoom=1;
- snap_offset=Vector2(0, 0);
- snap_step=Vector2(10, 10);
- snap_rotation_offset=0;
- snap_rotation_step=15 / (180 / Math_PI);
- snap_grid=false;
- snap_show_grid=false;
- snap_rotation=false;
- snap_pixel=false;
- skeleton_show_bones=true;
- skeleton_menu->set_item_checked(skeleton_menu->get_item_index(SKELETON_SHOW_BONES),true);
- updating_value_dialog=false;
- box_selecting=false;
+ key_pos = true;
+ key_rot = true;
+ key_scale = false;
+
+ zoom = 1;
+ snap_offset = Vector2(0, 0);
+ snap_step = Vector2(10, 10);
+ snap_rotation_offset = 0;
+ snap_rotation_step = 15 / (180 / Math_PI);
+ snap_grid = false;
+ snap_show_grid = false;
+ snap_rotation = false;
+ snap_pixel = false;
+ skeleton_show_bones = true;
+ skeleton_menu->set_item_checked(skeleton_menu->get_item_index(SKELETON_SHOW_BONES), true);
+ updating_value_dialog = false;
+ box_selecting = false;
//zoom=0.5;
- singleton=this;
+ singleton = this;
set_process_unhandled_key_input(true);
- can_move_pivot=false;
- drag=DRAG_NONE;
- bone_last_frame=0;
- additive_selection=false;
+ can_move_pivot = false;
+ drag = DRAG_NONE;
+ bone_last_frame = 0;
+ additive_selection = false;
}
-CanvasItemEditor *CanvasItemEditor::singleton=NULL;
+CanvasItemEditor *CanvasItemEditor::singleton = NULL;
void CanvasItemEditorPlugin::edit(Object *p_object) {
@@ -3621,88 +3416,83 @@ void CanvasItemEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
canvas_item_editor->show();
canvas_item_editor->set_fixed_process(true);
- VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport_rid(),false);
+ VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport_rid(), false);
canvas_item_editor->viewport->grab_focus();
} else {
canvas_item_editor->hide();
canvas_item_editor->set_fixed_process(false);
- VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport_rid(),true);
+ VisualServer::get_singleton()->viewport_set_hide_canvas(editor->get_scene_root()->get_viewport_rid(), true);
}
-
}
Dictionary CanvasItemEditorPlugin::get_state() const {
return canvas_item_editor->get_state();
}
-void CanvasItemEditorPlugin::set_state(const Dictionary& p_state) {
+void CanvasItemEditorPlugin::set_state(const Dictionary &p_state) {
canvas_item_editor->set_state(p_state);
}
CanvasItemEditorPlugin::CanvasItemEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- canvas_item_editor = memnew( CanvasItemEditor(editor) );
+ editor = p_node;
+ canvas_item_editor = memnew(CanvasItemEditor(editor));
canvas_item_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
editor->get_viewport()->add_child(canvas_item_editor);
canvas_item_editor->set_area_as_parent_rect();
canvas_item_editor->hide();
-
}
-
-CanvasItemEditorPlugin::~CanvasItemEditorPlugin()
-{
+CanvasItemEditorPlugin::~CanvasItemEditorPlugin() {
}
-
void CanvasItemEditorViewport::_on_mouse_exit() {
- if (!selector->is_visible()){
+ if (!selector->is_visible()) {
_remove_preview();
}
}
-void CanvasItemEditorViewport::_on_select_type(Object* selected) {
- CheckBox* check = selected->cast_to<CheckBox>();
+void CanvasItemEditorViewport::_on_select_type(Object *selected) {
+ CheckBox *check = selected->cast_to<CheckBox>();
String type = check->get_text();
- selector_label->set_text(vformat(TTR("Add %s"),type));
- label->set_text(vformat(TTR("Adding %s..."),type));
+ selector_label->set_text(vformat(TTR("Add %s"), type));
+ label->set_text(vformat(TTR("Adding %s..."), type));
}
void CanvasItemEditorViewport::_on_change_type() {
if (!button_group->get_pressed_button())
return;
- CheckBox* check=button_group->get_pressed_button()->cast_to<CheckBox>();
- default_type=check->get_text();
+ CheckBox *check = button_group->get_pressed_button()->cast_to<CheckBox>();
+ default_type = check->get_text();
_perform_drop_data();
selector->hide();
}
-void CanvasItemEditorViewport::_create_preview(const Vector<String>& files) const {
- label->set_pos(get_global_pos()+Point2(14,14));
- label_desc->set_pos(label->get_pos()+Point2(0,label->get_size().height));
- for (int i=0;i<files.size();i++) {
- String path=files[i];
- RES res=ResourceLoader::load(path);
- String type=res->get_class();
- if (type=="ImageTexture" || type=="PackedScene") {
- if (type=="ImageTexture") {
- Ref<ImageTexture> texture=Ref<ImageTexture> ( ResourceCache::get(path)->cast_to<ImageTexture>() );
- Sprite* sprite=memnew(Sprite);
+void CanvasItemEditorViewport::_create_preview(const Vector<String> &files) const {
+ label->set_pos(get_global_pos() + Point2(14, 14));
+ label_desc->set_pos(label->get_pos() + Point2(0, label->get_size().height));
+ for (int i = 0; i < files.size(); i++) {
+ String path = files[i];
+ RES res = ResourceLoader::load(path);
+ String type = res->get_class();
+ if (type == "ImageTexture" || type == "PackedScene") {
+ if (type == "ImageTexture") {
+ Ref<ImageTexture> texture = Ref<ImageTexture>(ResourceCache::get(path)->cast_to<ImageTexture>());
+ Sprite *sprite = memnew(Sprite);
sprite->set_texture(texture);
- sprite->set_modulate(Color(1,1,1,0.7f));
+ sprite->set_modulate(Color(1, 1, 1, 0.7f));
preview->add_child(sprite);
label->show();
label_desc->show();
- } else if (type=="PackedScene") {
- Ref<PackedScene> scn=ResourceLoader::load(path);
- if (scn.is_valid()){
- Node* instance=scn->instance();
- if (instance){
+ } else if (type == "PackedScene") {
+ Ref<PackedScene> scn = ResourceLoader::load(path);
+ if (scn.is_valid()) {
+ Node *instance = scn->instance();
+ if (instance) {
preview->add_child(instance);
}
}
@@ -3713,10 +3503,10 @@ void CanvasItemEditorViewport::_create_preview(const Vector<String>& files) cons
}
void CanvasItemEditorViewport::_remove_preview() {
- if (preview->get_parent()){
+ if (preview->get_parent()) {
editor->get_scene_root()->remove_child(preview);
- for (int i=preview->get_child_count()-1;i>=0;i--){
- Node* node=preview->get_child(i);
+ for (int i = preview->get_child_count() - 1; i >= 0; i--) {
+ Node *node = preview->get_child(i);
memdelete(node);
}
label->hide();
@@ -3724,152 +3514,159 @@ void CanvasItemEditorViewport::_remove_preview() {
}
}
-bool CanvasItemEditorViewport::_cyclical_dependency_exists(const String& p_target_scene_path, Node* p_desired_node) {
- if (p_desired_node->get_filename()==p_target_scene_path) {
+bool CanvasItemEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
+ if (p_desired_node->get_filename() == p_target_scene_path) {
return true;
}
- int childCount=p_desired_node->get_child_count();
- for (int i=0;i<childCount;i++) {
- Node* child=p_desired_node->get_child(i);
- if(_cyclical_dependency_exists(p_target_scene_path,child)) {
+ int childCount = p_desired_node->get_child_count();
+ for (int i = 0; i < childCount; i++) {
+ Node *child = p_desired_node->get_child(i);
+ if (_cyclical_dependency_exists(p_target_scene_path, child)) {
return true;
}
}
return false;
}
-void CanvasItemEditorViewport::_create_nodes(Node* parent, Node* child, String& path, const Point2& p_point) {
+void CanvasItemEditorViewport::_create_nodes(Node *parent, Node *child, String &path, const Point2 &p_point) {
child->set_name(path.get_file().get_basename());
- Ref<ImageTexture> texture=Ref<ImageTexture> ( ResourceCache::get(path)->cast_to<ImageTexture>() );
+ Ref<ImageTexture> texture = Ref<ImageTexture>(ResourceCache::get(path)->cast_to<ImageTexture>());
Size2 texture_size = texture->get_size();
- editor_data->get_undo_redo().add_do_method(parent,"add_child",child);
- editor_data->get_undo_redo().add_do_method(child,"set_owner",editor->get_edited_scene());
+ editor_data->get_undo_redo().add_do_method(parent, "add_child", child);
+ editor_data->get_undo_redo().add_do_method(child, "set_owner", editor->get_edited_scene());
editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(parent,"remove_child",child);
+ editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child);
- String new_name=parent->validate_child_name(child);
- ScriptEditorDebugger *sed=ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_create_node",editor->get_edited_scene()->get_path_to(parent),child->get_class(),new_name);
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_remove_node",NodePath(String(editor->get_edited_scene()->get_path_to(parent))+"/"+new_name));
+ String new_name = parent->validate_child_name(child);
+ ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_create_node", editor->get_edited_scene()->get_path_to(parent), child->get_class(), new_name);
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(editor->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
// handle with different property for texture
String property = "texture";
List<PropertyInfo> props;
child->get_property_list(&props);
- for(const List<PropertyInfo>::Element *E=props.front();E;E=E->next() ) {
- if (E->get().name=="config/texture") { // Particles2D
- property="config/texture";
+ for (const List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ if (E->get().name == "config/texture") { // Particles2D
+ property = "config/texture";
break;
- } else if (E->get().name=="texture/texture") { // Polygon2D
- property="texture/texture";
+ } else if (E->get().name == "texture/texture") { // Polygon2D
+ property = "texture/texture";
break;
- } else if (E->get().name=="normal") { // TouchScreenButton
- property="normal";
+ } else if (E->get().name == "normal") { // TouchScreenButton
+ property = "normal";
break;
}
}
- editor_data->get_undo_redo().add_do_property(child,property,texture);
+ editor_data->get_undo_redo().add_do_property(child, property, texture);
// make visible for certain node type
- if (default_type=="Patch9Rect") {
- editor_data->get_undo_redo().add_do_property(child,"rect/size",texture_size);
- } else if (default_type=="Polygon2D") {
+ if (default_type == "Patch9Rect") {
+ editor_data->get_undo_redo().add_do_property(child, "rect/size", texture_size);
+ } else if (default_type == "Polygon2D") {
PoolVector<Vector2> list;
- list.push_back(Vector2(0,0));
- list.push_back(Vector2(texture_size.width,0));
- list.push_back(Vector2(texture_size.width,texture_size.height));
- list.push_back(Vector2(0,texture_size.height));
- editor_data->get_undo_redo().add_do_property(child,"polygon",list);
+ list.push_back(Vector2(0, 0));
+ list.push_back(Vector2(texture_size.width, 0));
+ list.push_back(Vector2(texture_size.width, texture_size.height));
+ list.push_back(Vector2(0, texture_size.height));
+ editor_data->get_undo_redo().add_do_property(child, "polygon", list);
}
// locate at preview position
Point2 pos;
if (parent->has_method("get_global_pos")) {
- pos=parent->call("get_global_pos");
+ pos = parent->call("get_global_pos");
}
- Transform2D trans=canvas->get_canvas_transform();
- Point2 target_pos = (p_point-trans.get_origin())/trans.get_scale().x-pos;
- if (default_type=="Polygon2D" || default_type=="TouchScreenButton" || default_type=="TextureRect" || default_type=="Patch9Rect") {
- target_pos -= texture_size/2;
+ Transform2D trans = canvas->get_canvas_transform();
+ Point2 target_pos = (p_point - trans.get_origin()) / trans.get_scale().x - pos;
+ if (default_type == "Polygon2D" || default_type == "TouchScreenButton" || default_type == "TextureRect" || default_type == "Patch9Rect") {
+ target_pos -= texture_size / 2;
}
- editor_data->get_undo_redo().add_do_method(child,"set_pos",target_pos);
+ editor_data->get_undo_redo().add_do_method(child, "set_pos", target_pos);
}
-bool CanvasItemEditorViewport::_create_instance(Node* parent, String& path, const Point2& p_point) {
- Ref<PackedScene> sdata=ResourceLoader::load(path);
+bool CanvasItemEditorViewport::_create_instance(Node *parent, String &path, const Point2 &p_point) {
+ Ref<PackedScene> sdata = ResourceLoader::load(path);
if (!sdata.is_valid()) { // invalid scene
return false;
}
- Node* instanced_scene=sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
if (!instanced_scene) { // error on instancing
return false;
}
- if (editor->get_edited_scene()->get_filename()!="") { // cyclical instancing
+ if (editor->get_edited_scene()->get_filename() != "") { // cyclical instancing
if (_cyclical_dependency_exists(editor->get_edited_scene()->get_filename(), instanced_scene)) {
memdelete(instanced_scene);
return false;
}
}
- instanced_scene->set_filename( GlobalConfig::get_singleton()->localize_path(path) );
+ instanced_scene->set_filename(GlobalConfig::get_singleton()->localize_path(path));
- editor_data->get_undo_redo().add_do_method(parent,"add_child",instanced_scene);
- editor_data->get_undo_redo().add_do_method(instanced_scene,"set_owner",editor->get_edited_scene());
+ editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
+ editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", editor->get_edited_scene());
editor_data->get_undo_redo().add_do_reference(instanced_scene);
- editor_data->get_undo_redo().add_undo_method(parent,"remove_child",instanced_scene);
+ editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
- String new_name=parent->validate_child_name(instanced_scene);
- ScriptEditorDebugger *sed=ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_instance_node",editor->get_edited_scene()->get_path_to(parent),path,new_name);
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_remove_node",NodePath(String(editor->get_edited_scene()->get_path_to(parent))+"/"+new_name));
+ String new_name = parent->validate_child_name(instanced_scene);
+ ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", editor->get_edited_scene()->get_path_to(parent), path, new_name);
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(editor->get_edited_scene()->get_path_to(parent)) + "/" + new_name));
Point2 pos;
- Node2D* parent_node2d=parent->cast_to<Node2D>();
+ Node2D *parent_node2d = parent->cast_to<Node2D>();
if (parent_node2d) {
- pos=parent_node2d->get_global_position();
+ pos = parent_node2d->get_global_position();
} else {
- Control* parent_control=parent->cast_to<Control>();
+ Control *parent_control = parent->cast_to<Control>();
if (parent_control) {
- pos=parent_control->get_global_pos();
+ pos = parent_control->get_global_pos();
}
}
- Transform2D trans=canvas->get_canvas_transform();
- editor_data->get_undo_redo().add_do_method(instanced_scene,"set_pos",(p_point-trans.get_origin())/trans.get_scale().x-pos);
+ Transform2D trans = canvas->get_canvas_transform();
+ editor_data->get_undo_redo().add_do_method(instanced_scene, "set_pos", (p_point - trans.get_origin()) / trans.get_scale().x - pos);
return true;
}
-void CanvasItemEditorViewport::_perform_drop_data(){
+void CanvasItemEditorViewport::_perform_drop_data() {
_remove_preview();
Vector<String> error_files;
editor_data->get_undo_redo().create_action(TTR("Create Node"));
- for (int i=0;i<selected_files.size();i++) {
- String path=selected_files[i];
- RES res=ResourceLoader::load(path);
+ for (int i = 0; i < selected_files.size(); i++) {
+ String path = selected_files[i];
+ RES res = ResourceLoader::load(path);
if (res.is_null()) {
continue;
}
- String type=res->get_class();
- if (type=="ImageTexture") {
- Node* child;
- if (default_type=="Light2D") child=memnew(Light2D);
- else if (default_type=="Particles2D") child=memnew(Particles2D);
- else if (default_type=="Polygon2D") child=memnew(Polygon2D);
- else if (default_type=="TouchScreenButton") child=memnew(TouchScreenButton);
- else if (default_type=="TextureRect") child=memnew(TextureRect);
- else if (default_type=="Patch9Rect") child=memnew(NinePatchRect);
- else child=memnew(Sprite); // default
+ String type = res->get_class();
+ if (type == "ImageTexture") {
+ Node *child;
+ if (default_type == "Light2D")
+ child = memnew(Light2D);
+ else if (default_type == "Particles2D")
+ child = memnew(Particles2D);
+ else if (default_type == "Polygon2D")
+ child = memnew(Polygon2D);
+ else if (default_type == "TouchScreenButton")
+ child = memnew(TouchScreenButton);
+ else if (default_type == "TextureRect")
+ child = memnew(TextureRect);
+ else if (default_type == "Patch9Rect")
+ child = memnew(NinePatchRect);
+ else
+ child = memnew(Sprite); // default
_create_nodes(target_node, child, path, drop_pos);
- } else if (type=="PackedScene") {
- bool success=_create_instance(target_node, path, drop_pos);
+ } else if (type == "PackedScene") {
+ bool success = _create_instance(target_node, path, drop_pos);
if (!success) {
error_files.push_back(path);
}
@@ -3878,48 +3675,48 @@ void CanvasItemEditorViewport::_perform_drop_data(){
editor_data->get_undo_redo().commit_action();
- if (error_files.size()>0) {
+ if (error_files.size() > 0) {
String files_str;
- for (int i=0;i<error_files.size();i++) {
+ for (int i = 0; i < error_files.size(); i++) {
files_str += error_files[i].get_file().get_basename() + ",";
}
- files_str=files_str.substr(0,files_str.length()-1);
+ files_str = files_str.substr(0, files_str.length() - 1);
accept->get_ok()->set_text(TTR("Ugh"));
- accept->set_text(vformat(TTR("Error instancing scene from %s"),files_str.c_str()));
+ accept->set_text(vformat(TTR("Error instancing scene from %s"), files_str.c_str()));
accept->popup_centered_minsize();
}
}
-bool CanvasItemEditorViewport::can_drop_data(const Point2& p_point,const Variant& p_data) const {
- Dictionary d=p_data;
+bool CanvasItemEditorViewport::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
+ Dictionary d = p_data;
if (d.has("type")) {
- if (String(d["type"])=="files") {
- Vector<String> files=d["files"];
- bool can_instance=false;
- for (int i=0;i<files.size();i++) { // check if dragged files contain resource or scene can be created at least one
- RES res=ResourceLoader::load(files[i]);
+ if (String(d["type"]) == "files") {
+ Vector<String> files = d["files"];
+ bool can_instance = false;
+ for (int i = 0; i < files.size(); i++) { // check if dragged files contain resource or scene can be created at least one
+ RES res = ResourceLoader::load(files[i]);
if (res.is_null()) {
continue;
}
- String type=res->get_class();
- if (type=="PackedScene") {
- Ref<PackedScene> sdata=ResourceLoader::load(files[i]);
- Node* instanced_scene=sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ String type = res->get_class();
+ if (type == "PackedScene") {
+ Ref<PackedScene> sdata = ResourceLoader::load(files[i]);
+ Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
if (!instanced_scene) {
continue;
}
memdelete(instanced_scene);
}
- can_instance=true;
+ can_instance = true;
break;
}
if (can_instance) {
- if (!preview->get_parent()){ // create preview only once
+ if (!preview->get_parent()) { // create preview only once
_create_preview(files);
}
- Transform2D trans=canvas->get_canvas_transform();
- preview->set_position((p_point-trans.get_origin())/trans.get_scale().x);
- label->set_text(vformat(TTR("Adding %s..."),default_type));
+ Transform2D trans = canvas->get_canvas_transform();
+ preview->set_position((p_point - trans.get_origin()) / trans.get_scale().x);
+ label->set_text(vformat(TTR("Adding %s..."), default_type));
}
return can_instance;
}
@@ -3928,25 +3725,25 @@ bool CanvasItemEditorViewport::can_drop_data(const Point2& p_point,const Variant
return false;
}
-void CanvasItemEditorViewport::drop_data(const Point2& p_point,const Variant& p_data) {
- bool is_shift=Input::get_singleton()->is_key_pressed(KEY_SHIFT);
- bool is_alt=Input::get_singleton()->is_key_pressed(KEY_ALT);
+void CanvasItemEditorViewport::drop_data(const Point2 &p_point, const Variant &p_data) {
+ bool is_shift = Input::get_singleton()->is_key_pressed(KEY_SHIFT);
+ bool is_alt = Input::get_singleton()->is_key_pressed(KEY_ALT);
selected_files.clear();
- Dictionary d=p_data;
- if (d.has("type") && String(d["type"])=="files"){
- selected_files=d["files"];
+ Dictionary d = p_data;
+ if (d.has("type") && String(d["type"]) == "files") {
+ selected_files = d["files"];
}
- List<Node*> list=editor->get_editor_selection()->get_selected_node_list();
- if (list.size()==0) {
+ List<Node *> list = editor->get_editor_selection()->get_selected_node_list();
+ if (list.size() == 0) {
accept->get_ok()->set_text(TTR("OK :("));
accept->set_text(TTR("No parent to instance a child at."));
accept->popup_centered_minsize();
_remove_preview();
return;
}
- if (list.size()!=1) {
+ if (list.size() != 1) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation requires a single selected node."));
accept->popup_centered_minsize();
@@ -3954,21 +3751,21 @@ void CanvasItemEditorViewport::drop_data(const Point2& p_point,const Variant& p_
return;
}
- target_node=list[0];
- if (is_shift && target_node!=editor->get_edited_scene()) {
- target_node=target_node->get_parent();
+ target_node = list[0];
+ if (is_shift && target_node != editor->get_edited_scene()) {
+ target_node = target_node->get_parent();
}
- drop_pos=p_point;
+ drop_pos = p_point;
if (is_alt) {
- List<BaseButton*> btn_list;
+ List<BaseButton *> btn_list;
button_group->get_buttons(&btn_list);
- for (int i=0;i<btn_list.size();i++) {
- CheckBox* check=btn_list[i]->cast_to<CheckBox>();
- check->set_pressed(check->get_text()==default_type);
+ for (int i = 0; i < btn_list.size(); i++) {
+ CheckBox *check = btn_list[i]->cast_to<CheckBox>();
+ check->set_pressed(check->get_text() == default_type);
}
- selector_label->set_text(vformat(TTR("Add %s"),default_type));
+ selector_label->set_text(vformat(TTR("Add %s"), default_type));
selector->popup_centered_minsize();
} else {
_perform_drop_data();
@@ -3976,21 +3773,21 @@ void CanvasItemEditorViewport::drop_data(const Point2& p_point,const Variant& p_
}
void CanvasItemEditorViewport::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- connect("mouse_exited",this,"_on_mouse_exit");
- } else if (p_what==NOTIFICATION_EXIT_TREE) {
- disconnect("mouse_exited",this,"_on_mouse_exit");
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ connect("mouse_exited", this, "_on_mouse_exit");
+ } else if (p_what == NOTIFICATION_EXIT_TREE) {
+ disconnect("mouse_exited", this, "_on_mouse_exit");
}
}
void CanvasItemEditorViewport::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_on_select_type"),&CanvasItemEditorViewport::_on_select_type);
- ClassDB::bind_method(D_METHOD("_on_change_type"),&CanvasItemEditorViewport::_on_change_type);
- ClassDB::bind_method(D_METHOD("_on_mouse_exit"),&CanvasItemEditorViewport::_on_mouse_exit);
+ ClassDB::bind_method(D_METHOD("_on_select_type"), &CanvasItemEditorViewport::_on_select_type);
+ ClassDB::bind_method(D_METHOD("_on_change_type"), &CanvasItemEditorViewport::_on_change_type);
+ ClassDB::bind_method(D_METHOD("_on_mouse_exit"), &CanvasItemEditorViewport::_on_mouse_exit);
}
-CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasItemEditor* p_canvas) {
- default_type="Sprite";
+CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasItemEditor *p_canvas) {
+ default_type = "Sprite";
// Node2D
types.push_back("Sprite");
types.push_back("Light2D");
@@ -4001,42 +3798,42 @@ CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasIte
types.push_back("TextureRect");
types.push_back("Patch9Rect");
- target_node=NULL;
- editor=p_node;
- editor_data=editor->get_scene_tree_dock()->get_editor_data();
- canvas=p_canvas;
- preview=memnew( Node2D );
- accept=memnew( AcceptDialog );
+ target_node = NULL;
+ editor = p_node;
+ editor_data = editor->get_scene_tree_dock()->get_editor_data();
+ canvas = p_canvas;
+ preview = memnew(Node2D);
+ accept = memnew(AcceptDialog);
editor->get_gui_base()->add_child(accept);
- selector=memnew( WindowDialog );
+ selector = memnew(WindowDialog);
selector->set_title(TTR("Change default type"));
- VBoxContainer* vbc=memnew(VBoxContainer);
- vbc->add_constant_override("separation",10*EDSCALE);
- vbc->set_custom_minimum_size(Size2(200,260)*EDSCALE);
+ VBoxContainer *vbc = memnew(VBoxContainer);
+ vbc->add_constant_override("separation", 10 * EDSCALE);
+ vbc->set_custom_minimum_size(Size2(200, 260) * EDSCALE);
- selector_label=memnew(Label);
+ selector_label = memnew(Label);
selector_label->set_align(Label::ALIGN_CENTER);
selector_label->set_valign(Label::VALIGN_BOTTOM);
- selector_label->set_custom_minimum_size(Size2(0,30)*EDSCALE);
+ selector_label->set_custom_minimum_size(Size2(0, 30) * EDSCALE);
vbc->add_child(selector_label);
button_group.instance();
- btn_group=memnew( VBoxContainer );
+ btn_group = memnew(VBoxContainer);
btn_group->set_h_size_flags(0);
btn_group->connect("button_selected", this, "_on_select_type");
- for (int i=0;i<types.size();i++) {
- CheckBox* check=memnew(CheckBox);
+ for (int i = 0; i < types.size(); i++) {
+ CheckBox *check = memnew(CheckBox);
check->set_text(types[i]);
btn_group->add_child(check);
check->set_button_group(button_group);
}
vbc->add_child(btn_group);
- Button* ok=memnew(Button);
+ Button *ok = memnew(Button);
ok->set_text(TTR("OK"));
ok->set_h_size_flags(0);
vbc->add_child(ok);
@@ -4045,18 +3842,18 @@ CanvasItemEditorViewport::CanvasItemEditorViewport(EditorNode *p_node, CanvasIte
selector->add_child(vbc);
editor->get_gui_base()->add_child(selector);
- label=memnew(Label);
- label->add_color_override("font_color", Color(1,1,0,1));
- label->add_color_override("font_color_shadow", Color(0,0,0,1));
- label->add_constant_override("shadow_as_outline", 1*EDSCALE);
+ label = memnew(Label);
+ label->add_color_override("font_color", Color(1, 1, 0, 1));
+ label->add_color_override("font_color_shadow", Color(0, 0, 0, 1));
+ label->add_constant_override("shadow_as_outline", 1 * EDSCALE);
label->hide();
editor->get_gui_base()->add_child(label);
- label_desc=memnew(Label);
+ label_desc = memnew(Label);
label_desc->set_text(TTR("Drag & drop + Shift : Add node as sibling\nDrag & drop + Alt : Change node type"));
- label_desc->add_color_override("font_color", Color(0.6,0.6,0.6,1));
- label_desc->add_color_override("font_color_shadow", Color(0.2,0.2,0.2,1));
- label_desc->add_constant_override("shadow_as_outline", 1*EDSCALE);
+ label_desc->add_color_override("font_color", Color(0.6, 0.6, 0.6, 1));
+ label_desc->add_color_override("font_color_shadow", Color(0.2, 0.2, 0.2, 1));
+ label_desc->add_constant_override("shadow_as_outline", 1 * EDSCALE);
label_desc->add_constant_override("line_spacing", 0);
label_desc->hide();
editor->get_gui_base()->add_child(label_desc);
diff --git a/editor/plugins/canvas_item_editor_plugin.h b/editor/plugins/canvas_item_editor_plugin.h
index 0c2dcdff3d..5f22437d39 100644
--- a/editor/plugins/canvas_item_editor_plugin.h
+++ b/editor/plugins/canvas_item_editor_plugin.h
@@ -29,15 +29,15 @@
#ifndef CONTROL_EDITOR_PLUGIN_H
#define CONTROL_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
+#include "scene/2d/canvas_item.h"
+#include "scene/gui/box_container.h"
#include "scene/gui/button_group.h"
#include "scene/gui/check_box.h"
#include "scene/gui/label.h"
-#include "scene/gui/spin_box.h"
#include "scene/gui/panel_container.h"
-#include "scene/gui/box_container.h"
-#include "scene/2d/canvas_item.h"
+#include "scene/gui/spin_box.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -46,7 +46,8 @@ class CanvasItemEditorViewport;
class CanvasItemEditorSelectedItem : public Object {
- GDCLASS(CanvasItemEditorSelectedItem,Object);
+ GDCLASS(CanvasItemEditorSelectedItem, Object);
+
public:
Variant undo_state;
Vector2 undo_pivot;
@@ -55,16 +56,15 @@ public:
float prev_rot;
Rect2 prev_rect;
- CanvasItemEditorSelectedItem() { prev_rot=0; }
+ CanvasItemEditorSelectedItem() { prev_rot = 0; }
};
class CanvasItemEditor : public VBoxContainer {
- GDCLASS(CanvasItemEditor, VBoxContainer );
+ GDCLASS(CanvasItemEditor, VBoxContainer);
EditorNode *editor;
-
enum Tool {
TOOL_SELECT,
@@ -186,15 +186,14 @@ class CanvasItemEditor : public VBoxContainer {
void _tool_select(int p_index);
-
MenuOption last_option;
struct _SelectResult {
- CanvasItem* item;
+ CanvasItem *item;
float z;
bool has_z;
- _FORCE_INLINE_ bool operator<(const _SelectResult& p_rr) const {
+ _FORCE_INLINE_ bool operator<(const _SelectResult &p_rr) const {
return has_z && p_rr.has_z ? p_rr.z < z : p_rr.has_z;
}
};
@@ -205,7 +204,10 @@ class CanvasItemEditor : public VBoxContainer {
Point2 pos;
bool lock;
bool group;
- LockList() { lock=false; group=false; }
+ LockList() {
+ lock = false;
+ group = false;
+ }
};
List<LockList> lock_list;
@@ -220,7 +222,7 @@ class CanvasItemEditor : public VBoxContainer {
};
uint64_t bone_last_frame;
- Map<ObjectID,BoneList> bone_list;
+ Map<ObjectID, BoneList> bone_list;
Transform2D bone_orig_xform;
@@ -272,7 +274,6 @@ class CanvasItemEditor : public VBoxContainer {
PopupMenu *selection_menu;
-
//PopupMenu *popup;
DragType drag;
Point2 drag_from;
@@ -297,14 +298,13 @@ class CanvasItemEditor : public VBoxContainer {
Ref<StyleBoxTexture> select_sb;
Ref<Texture> select_handle;
-
int handle_len;
bool _is_part_of_subscene(CanvasItem *p_item);
- CanvasItem* _select_canvas_item_at_pos(const Point2 &p_pos,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform);
- void _find_canvas_items_at_pos(const Point2 &p_pos,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform, Vector<_SelectResult> &r_items);
- void _find_canvas_items_at_rect(const Rect2& p_rect,Node* p_node,const Transform2D& p_parent_xform,const Transform2D& p_canvas_xform,List<CanvasItem*> *r_items);
+ CanvasItem *_select_canvas_item_at_pos(const Point2 &p_pos, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform);
+ void _find_canvas_items_at_pos(const Point2 &p_pos, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform, Vector<_SelectResult> &r_items);
+ void _find_canvas_items_at_rect(const Rect2 &p_rect, Node *p_node, const Transform2D &p_parent_xform, const Transform2D &p_canvas_xform, List<CanvasItem *> *r_items);
- bool _select(CanvasItem *item, Point2 p_click_pos, bool p_append, bool p_drag=true);
+ bool _select(CanvasItem *item, Point2 p_click_pos, bool p_append, bool p_drag = true);
ConfirmationDialog *snap_dialog;
@@ -314,22 +314,22 @@ class CanvasItemEditor : public VBoxContainer {
CanvasItem *ref_item;
- void _edit_set_pivot(const Vector2& mouse_pos);
+ void _edit_set_pivot(const Vector2 &mouse_pos);
void _add_canvas_item(CanvasItem *p_canvas_item);
void _remove_canvas_item(CanvasItem *p_canvas_item);
void _clear_canvas_items();
void _visibility_changed(ObjectID p_canvas_item);
- void _key_move(const Vector2& p_dir, bool p_snap, KeyMoveMODE p_move_mode);
- void _list_select(const InputEventMouseButton& b);
+ void _key_move(const Vector2 &p_dir, bool p_snap, KeyMoveMODE p_move_mode);
+ void _list_select(const InputEventMouseButton &b);
- DragType _find_drag_type(const Transform2D& p_xform, const Rect2& p_local_rect, const Point2& p_click, Vector2& r_point);
+ DragType _find_drag_type(const Transform2D &p_xform, const Rect2 &p_local_rect, const Point2 &p_click, Vector2 &r_point);
void _popup_callback(int p_op);
bool updating_scroll;
void _update_scroll(float);
void _update_scrollbars();
- void incbeg(float& beg,float& end, float inc, float minsize,bool p_symmetric);
- void incend(float& beg,float& end, float inc, float minsize,bool p_symmetric);
+ void incbeg(float &beg, float &end, float inc, float minsize, bool p_symmetric);
+ void incend(float &beg, float &end, float inc, float minsize, bool p_symmetric);
void _append_canvas_item(CanvasItem *p_item);
void _dialog_value_changed(double);
@@ -341,9 +341,7 @@ class CanvasItemEditor : public VBoxContainer {
Point2 _find_topleftmost_point();
-
- void _find_canvas_items_span(Node *p_node, Rect2& r_rect, const Transform2D& p_xform);
-
+ void _find_canvas_items_span(Node *p_node, Rect2 &r_rect, const Transform2D &p_xform);
Object *_get_editor_data(Object *p_what);
@@ -351,59 +349,59 @@ class CanvasItemEditor : public VBoxContainer {
int get_item_count();
void _keying_changed();
- void _unhandled_key_input(const InputEvent& p_ev);
+ void _unhandled_key_input(const InputEvent &p_ev);
- void _viewport_gui_input(const InputEvent& p_event);
+ void _viewport_gui_input(const InputEvent &p_event);
void _viewport_draw();
void _focus_selection(int p_op);
- void _set_anchor(Control::AnchorType p_left,Control::AnchorType p_top,Control::AnchorType p_right,Control::AnchorType p_bottom);
+ void _set_anchor(Control::AnchorType p_left, Control::AnchorType p_top, Control::AnchorType p_right, Control::AnchorType p_bottom);
HSplitContainer *palette_split;
VSplitContainer *bottom_split;
-friend class CanvasItemEditorPlugin;
-protected:
-
+ friend class CanvasItemEditorPlugin;
+protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
void end_drag();
- void box_selection_start( Point2 &click );
+ void box_selection_start(Point2 &click);
bool box_selection_end();
HBoxContainer *get_panel_hb() { return hb; }
struct compare_items_x {
- bool operator()( const CanvasItem *a, const CanvasItem *b ) const {
+ bool operator()(const CanvasItem *a, const CanvasItem *b) const {
return a->get_global_transform().elements[2].x < b->get_global_transform().elements[2].x;
}
};
struct compare_items_y {
- bool operator()( const CanvasItem *a, const CanvasItem *b ) const {
+ bool operator()(const CanvasItem *a, const CanvasItem *b) const {
return a->get_global_transform().elements[2].y < b->get_global_transform().elements[2].y;
}
};
struct proj_vector2_x {
- float get( const Vector2 &v ) { return v.x; }
- void set( Vector2 &v, float f ) { v.x = f; }
+ float get(const Vector2 &v) { return v.x; }
+ void set(Vector2 &v, float f) { v.x = f; }
};
struct proj_vector2_y {
- float get( const Vector2 &v ) { return v.y; }
- void set( Vector2 &v, float f ) { v.y = f; }
+ float get(const Vector2 &v) { return v.y; }
+ void set(Vector2 &v, float f) { v.y = f; }
};
- template< class P, class C > void space_selected_items();
+ template <class P, class C>
+ void space_selected_items();
static CanvasItemEditor *singleton;
-public:
+public:
Vector2 snap_point(Vector2 p_target, Vector2 p_start = Vector2(0, 0)) const;
float snap_angle(float p_target, float p_start = 0) const;
@@ -411,7 +409,7 @@ public:
static CanvasItemEditor *get_singleton() { return singleton; }
Dictionary get_state() const;
- void set_state(const Dictionary& p_state);
+ void set_state(const Dictionary &p_state);
void add_control_to_menu_panel(Control *p_control);
@@ -420,8 +418,8 @@ public:
Control *get_viewport_control() { return viewport; }
- bool get_remove_list(List<Node*> *p_list);
- void set_undo_redo(UndoRedo *p_undo_redo) {undo_redo=p_undo_redo; }
+ bool get_remove_list(List<Node *> *p_list);
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
void edit(CanvasItem *p_canvas_item);
void focus_selection();
@@ -431,61 +429,59 @@ public:
class CanvasItemEditorPlugin : public EditorPlugin {
- GDCLASS( CanvasItemEditorPlugin, EditorPlugin );
+ GDCLASS(CanvasItemEditorPlugin, EditorPlugin);
CanvasItemEditor *canvas_item_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "2D"; }
bool has_main_screen() const { return true; }
virtual void edit(Object *p_object);
virtual bool handles(Object *p_object) const;
virtual void make_visible(bool p_visible);
- virtual bool get_remove_list(List<Node*> *p_list) { return canvas_item_editor->get_remove_list(p_list); }
+ virtual bool get_remove_list(List<Node *> *p_list) { return canvas_item_editor->get_remove_list(p_list); }
virtual Dictionary get_state() const;
- virtual void set_state(const Dictionary& p_state);
+ virtual void set_state(const Dictionary &p_state);
CanvasItemEditor *get_canvas_item_editor() { return canvas_item_editor; }
CanvasItemEditorPlugin(EditorNode *p_node);
~CanvasItemEditorPlugin();
-
};
class CanvasItemEditorViewport : public Control {
- GDCLASS( CanvasItemEditorViewport, Control );
+ GDCLASS(CanvasItemEditorViewport, Control);
String default_type;
Vector<String> types;
Vector<String> selected_files;
- Node* target_node;
+ Node *target_node;
Point2 drop_pos;
- EditorNode* editor;
- EditorData* editor_data;
- CanvasItemEditor* canvas;
- Node2D* preview;
- AcceptDialog* accept;
- WindowDialog* selector;
- Label* selector_label;
- Label* label;
- Label* label_desc;
- VBoxContainer* btn_group;
+ EditorNode *editor;
+ EditorData *editor_data;
+ CanvasItemEditor *canvas;
+ Node2D *preview;
+ AcceptDialog *accept;
+ WindowDialog *selector;
+ Label *selector_label;
+ Label *label;
+ Label *label_desc;
+ VBoxContainer *btn_group;
Ref<ButtonGroup> button_group;
void _on_mouse_exit();
- void _on_select_type(Object* selected);
+ void _on_select_type(Object *selected);
void _on_change_type();
- void _create_preview(const Vector<String>& files) const;
+ void _create_preview(const Vector<String> &files) const;
void _remove_preview();
- bool _cyclical_dependency_exists(const String& p_target_scene_path, Node* p_desired_node);
- void _create_nodes(Node* parent, Node* child, String& path, const Point2& p_point);
- bool _create_instance(Node* parent, String& path, const Point2& p_point);
+ bool _cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node);
+ void _create_nodes(Node *parent, Node *child, String &path, const Point2 &p_point);
+ bool _create_instance(Node *parent, String &path, const Point2 &p_point);
void _perform_drop_data();
static void _bind_methods();
@@ -494,10 +490,10 @@ protected:
void _notification(int p_what);
public:
- virtual bool can_drop_data(const Point2& p_point,const Variant& p_data) const;
- virtual void drop_data(const Point2& p_point,const Variant& p_data);
+ virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
+ virtual void drop_data(const Point2 &p_point, const Variant &p_data);
- CanvasItemEditorViewport(EditorNode *p_node, CanvasItemEditor* p_canvas);
+ CanvasItemEditorViewport(EditorNode *p_node, CanvasItemEditor *p_canvas);
};
#endif
diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.cpp b/editor/plugins/collision_polygon_2d_editor_plugin.cpp
index 5a45267c85..0f7e3a3990 100644
--- a/editor/plugins/collision_polygon_2d_editor_plugin.cpp
+++ b/editor/plugins/collision_polygon_2d_editor_plugin.cpp
@@ -29,193 +29,177 @@
#include "collision_polygon_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
-
+#include "os/file_access.h"
void CollisionPolygon2DEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
- button_create->set_icon( get_icon("Edit","EditorIcons"));
- button_edit->set_icon( get_icon("MovePoint","EditorIcons"));
+ button_create->set_icon(get_icon("Edit", "EditorIcons"));
+ button_edit->set_icon(get_icon("MovePoint", "EditorIcons"));
button_edit->set_pressed(true);
- get_tree()->connect("node_removed",this,"_node_removed");
+ get_tree()->connect("node_removed", this, "_node_removed");
} break;
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void CollisionPolygon2DEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
canvas_item_editor->get_viewport_control()->update();
}
-
}
-
void CollisionPolygon2DEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MODE_CREATE: {
- mode=MODE_CREATE;
+ mode = MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
-
}
}
void CollisionPolygon2DEditor::_wip_close() {
undo_redo->create_action(TTR("Create Poly"));
- undo_redo->add_undo_method(node,"set_polygon",node->get_polygon());
- undo_redo->add_do_method(node,"set_polygon",wip);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_undo_method(node, "set_polygon", node->get_polygon());
+ undo_redo->add_do_method(node, "set_polygon", wip);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
wip.clear();
- wip_active=false;
- mode=MODE_EDIT;
+ wip_active = false;
+ mode = MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
- edited_point=-1;
+ edited_point = -1;
}
-bool CollisionPolygon2DEditor::forward_gui_input(const InputEvent& p_event) {
-
+bool CollisionPolygon2DEditor::forward_gui_input(const InputEvent &p_event) {
if (!node)
return false;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
-
- Vector2 gpoint = Point2(mb.x,mb.y);
+ Vector2 gpoint = Point2(mb.x, mb.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
Vector<Vector2> poly = node->get_polygon();
//first check if a point is to be added (segment split)
- real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
-
- switch(mode) {
+ real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
+ switch (mode) {
case MODE_CREATE: {
- if (mb.button_index==BUTTON_LEFT && mb.pressed) {
-
+ if (mb.button_index == BUTTON_LEFT && mb.pressed) {
if (!wip_active) {
wip.clear();
- wip.push_back( cpoint );
- wip_active=true;
- edited_point_pos=cpoint;
+ wip.push_back(cpoint);
+ wip_active = true;
+ edited_point_pos = cpoint;
canvas_item_editor->get_viewport_control()->update();
- edited_point=1;
+ edited_point = 1;
return true;
} else {
-
- if (wip.size()>1 && xform.xform(wip[0]).distance_to(gpoint)<grab_treshold) {
+ if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_treshold) {
//wip closed
_wip_close();
return true;
} else {
- wip.push_back( cpoint );
- edited_point=wip.size();
+ wip.push_back(cpoint);
+ edited_point = wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && wip_active) {
_wip_close();
}
-
-
} break;
case MODE_EDIT: {
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (mb.mod.control) {
-
if (poly.size() < 3) {
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_undo_method(node,"set_polygon",poly);
+ undo_redo->add_undo_method(node, "set_polygon", poly);
poly.push_back(cpoint);
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
//search edges
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 points[2] ={ xform.xform(poly[i]),
- xform.xform(poly[(i+1)%poly.size()]) };
+ Vector2 points[2] = { xform.xform(poly[i]),
+ xform.xform(poly[(i + 1) % poly.size()]) };
- Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
- if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
+ Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
+ if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos));
- edited_point=closest_idx+1;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos));
+ edited_point = closest_idx + 1;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
node->set_polygon(poly);
canvas_item_editor->get_viewport_control()->update();
return true;
@@ -224,106 +208,95 @@ bool CollisionPolygon2DEditor::forward_gui_input(const InputEvent& p_event) {
//look for points to move
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- edited_point=closest_idx;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ edited_point = closest_idx;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
- if (edited_point!=-1) {
+ if (edited_point != -1) {
//apply
- ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
- poly[edited_point]=edited_point_pos;
+ ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
+ poly[edited_point] = edited_point_pos;
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_undo_method(node, "set_polygon", pre_move_edit);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- edited_point=-1;
+ edited_point = -1;
return true;
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {
-
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && edited_point == -1) {
-
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
-
+ if (closest_idx >= 0) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
- undo_redo->add_undo_method(node,"set_polygon",poly);
+ undo_redo->add_undo_method(node, "set_polygon", poly);
poly.remove(closest_idx);
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
-
}
-
-
} break;
}
-
-
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {
+ if (edited_point != -1 && (wip_active || mm.button_mask & BUTTON_MASK_LEFT)) {
- Vector2 gpoint = Point2(mm.x,mm.y);
+ Vector2 gpoint = Point2(mm.x, mm.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
canvas_item_editor->get_viewport_control()->update();
-
}
} break;
@@ -341,90 +314,83 @@ void CollisionPolygon2DEditor::_canvas_draw() {
Vector<Vector2> poly;
if (wip_active)
- poly=wip;
+ poly = wip;
else
- poly=node->get_polygon();
-
+ poly = node->get_polygon();
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
-
- for(int i=0;i<poly.size();i++) {
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 p,p2;
- p = i==edited_point ? edited_point_pos : poly[i];
- if ((wip_active && i==poly.size()-1) || (((i+1)%poly.size())==edited_point))
- p2=edited_point_pos;
+ Vector2 p, p2;
+ p = i == edited_point ? edited_point_pos : poly[i];
+ if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point))
+ p2 = edited_point_pos;
else
- p2 = poly[(i+1)%poly.size()];
+ p2 = poly[(i + 1) % poly.size()];
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
- Color col=Color(1,0.3,0.1,0.8);
- vpc->draw_line(point,next_point,col,2);
- vpc->draw_texture(handle,point-handle->get_size()*0.5);
+ Color col = Color(1, 0.3, 0.1, 0.8);
+ vpc->draw_line(point, next_point, col, 2);
+ vpc->draw_texture(handle, point - handle->get_size() * 0.5);
}
}
-
-
void CollisionPolygon2DEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
- node=p_collision_polygon->cast_to<CollisionPolygon2D>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ node = p_collision_polygon->cast_to<CollisionPolygon2D>();
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
wip.clear();
- wip_active=false;
- edited_point=-1;
+ wip_active = false;
+ edited_point = -1;
canvas_item_editor->get_viewport_control()->update();
} else {
- node=NULL;
-
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ node = NULL;
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
}
-
}
void CollisionPolygon2DEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_option"),&CollisionPolygon2DEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&CollisionPolygon2DEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_node_removed"),&CollisionPolygon2DEditor::_node_removed);
-
+ ClassDB::bind_method(D_METHOD("_menu_option"), &CollisionPolygon2DEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &CollisionPolygon2DEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &CollisionPolygon2DEditor::_node_removed);
}
CollisionPolygon2DEditor::CollisionPolygon2DEditor(EditorNode *p_editor) {
- node=NULL;
- canvas_item_editor=NULL;
- editor=p_editor;
+ node = NULL;
+ canvas_item_editor = NULL;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- add_child( memnew( VSeparator ));
- button_create = memnew( ToolButton );
+ add_child(memnew(VSeparator));
+ button_create = memnew(ToolButton);
add_child(button_create);
- button_create->connect("pressed",this,"_menu_option",varray(MODE_CREATE));
+ button_create->connect("pressed", this, "_menu_option", varray(MODE_CREATE));
button_create->set_toggle_mode(true);
button_create->set_tooltip(TTR("Create a new polygon from scratch."));
- button_edit = memnew( ToolButton );
+ button_edit = memnew(ToolButton);
add_child(button_edit);
- button_edit->connect("pressed",this,"_menu_option",varray(MODE_EDIT));
+ button_edit->connect("pressed", this, "_menu_option", varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
button_edit->set_tooltip("Edit existing polygon:\nLMB: Move Point.\nCtrl+LMB: Split Segment.\nRMB: Erase Point.");
- //add_constant_override("separation",0);
+//add_constant_override("separation",0);
#if 0
options = memnew( MenuButton );
@@ -436,11 +402,9 @@ CollisionPolygon2DEditor::CollisionPolygon2DEditor(EditorNode *p_editor) {
#endif
mode = MODE_EDIT;
- wip_active=false;
-
+ wip_active = false;
}
-
void CollisionPolygon2DEditorPlugin::edit(Object *p_object) {
collision_polygon_editor->edit(p_object->cast_to<Node>());
@@ -460,23 +424,16 @@ void CollisionPolygon2DEditorPlugin::make_visible(bool p_visible) {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
-
}
CollisionPolygon2DEditorPlugin::CollisionPolygon2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- collision_polygon_editor = memnew( CollisionPolygon2DEditor(p_node) );
+ editor = p_node;
+ collision_polygon_editor = memnew(CollisionPolygon2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
-
-
-
}
-
-CollisionPolygon2DEditorPlugin::~CollisionPolygon2DEditorPlugin()
-{
+CollisionPolygon2DEditorPlugin::~CollisionPolygon2DEditorPlugin() {
}
-
diff --git a/editor/plugins/collision_polygon_2d_editor_plugin.h b/editor/plugins/collision_polygon_2d_editor_plugin.h
index 796328753d..abd723cce9 100644
--- a/editor/plugins/collision_polygon_2d_editor_plugin.h
+++ b/editor/plugins/collision_polygon_2d_editor_plugin.h
@@ -29,12 +29,11 @@
#ifndef COLLISION_POLYGON_2D_EDITOR_PLUGIN_H
#define COLLISION_POLYGON_2D_EDITOR_PLUGIN_H
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/collision_polygon_2d.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -43,7 +42,7 @@ class CanvasItemEditor;
class CollisionPolygon2DEditor : public HBoxContainer {
- GDCLASS(CollisionPolygon2DEditor, HBoxContainer );
+ GDCLASS(CollisionPolygon2DEditor, HBoxContainer);
UndoRedo *undo_redo;
enum Mode {
@@ -70,7 +69,6 @@ class CollisionPolygon2DEditor : public HBoxContainer {
Vector<Vector2> wip;
bool wip_active;
-
void _wip_close();
void _canvas_draw();
void _menu_option(int p_option);
@@ -79,23 +77,22 @@ protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
- bool forward_gui_input(const InputEvent& p_event);
+public:
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_collision_polygon);
CollisionPolygon2DEditor(EditorNode *p_editor);
};
class CollisionPolygon2DEditorPlugin : public EditorPlugin {
- GDCLASS( CollisionPolygon2DEditorPlugin, EditorPlugin );
+ GDCLASS(CollisionPolygon2DEditorPlugin, EditorPlugin);
CollisionPolygon2DEditor *collision_polygon_editor;
EditorNode *editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "CollisionPolygon2D"; }
bool has_main_screen() const { return false; }
@@ -105,7 +102,6 @@ public:
CollisionPolygon2DEditorPlugin(EditorNode *p_node);
~CollisionPolygon2DEditorPlugin();
-
};
#endif // COLLISION_POLYGON_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/collision_polygon_editor_plugin.cpp b/editor/plugins/collision_polygon_editor_plugin.cpp
index 3aad53b420..62426a7699 100644
--- a/editor/plugins/collision_polygon_editor_plugin.cpp
+++ b/editor/plugins/collision_polygon_editor_plugin.cpp
@@ -28,11 +28,11 @@
/*************************************************************************/
#include "collision_polygon_editor_plugin.h"
-#include "spatial_editor_plugin.h"
-#include "os/file_access.h"
+#include "canvas_item_editor_plugin.h"
#include "editor/editor_settings.h"
+#include "os/file_access.h"
#include "scene/3d/camera.h"
-#include "canvas_item_editor_plugin.h"
+#include "spatial_editor_plugin.h"
#if 0
diff --git a/editor/plugins/collision_polygon_editor_plugin.h b/editor/plugins/collision_polygon_editor_plugin.h
index aaad2174fe..ace8c3429f 100644
--- a/editor/plugins/collision_polygon_editor_plugin.h
+++ b/editor/plugins/collision_polygon_editor_plugin.h
@@ -29,13 +29,13 @@
#ifndef COLLISION_POLYGON_EDITOR_PLUGIN_H
#define COLLISION_POLYGON_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/collision_polygon.h"
#include "scene/3d/immediate_geometry.h"
#include "scene/3d/mesh_instance.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
diff --git a/editor/plugins/collision_shape_2d_editor_plugin.cpp b/editor/plugins/collision_shape_2d_editor_plugin.cpp
index a05eeb7a27..3538878877 100644
--- a/editor/plugins/collision_shape_2d_editor_plugin.cpp
+++ b/editor/plugins/collision_shape_2d_editor_plugin.cpp
@@ -29,23 +29,23 @@
#include "collision_shape_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "scene/resources/segment_shape_2d.h"
-#include "scene/resources/shape_line_2d.h"
-#include "scene/resources/circle_shape_2d.h"
-#include "scene/resources/rectangle_shape_2d.h"
#include "scene/resources/capsule_shape_2d.h"
-#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/circle_shape_2d.h"
#include "scene/resources/concave_polygon_shape_2d.h"
+#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/rectangle_shape_2d.h"
+#include "scene/resources/segment_shape_2d.h"
+#include "scene/resources/shape_line_2d.h"
Variant CollisionShape2DEditor::get_handle_value(int idx) const {
- switch ( shape_type ) {
+ switch (shape_type) {
case CAPSULE_SHAPE: {
Ref<CapsuleShape2D> capsule = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
return capsule->get_radius();
- } else if (idx==1) {
+ } else if (idx == 1) {
return capsule->get_height();
}
@@ -54,7 +54,7 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
case CIRCLE_SHAPE: {
Ref<CircleShape2D> circle = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
return circle->get_radius();
}
@@ -71,7 +71,7 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
case LINE_SHAPE: {
Ref<LineShape2D> line = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
return line->get_d();
} else {
return line->get_normal();
@@ -82,7 +82,7 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
case RAY_SHAPE: {
Ref<RayShape2D> ray = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
return ray->get_length();
}
@@ -91,7 +91,7 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
case RECTANGLE_SHAPE: {
Ref<RectangleShape2D> rect = node->get_shape();
- if (idx<2) {
+ if (idx < 2) {
return rect->get_extents().abs();
}
@@ -100,9 +100,9 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
case SEGMENT_SHAPE: {
Ref<SegmentShape2D> seg = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
return seg->get_a();
- } else if (idx==1) {
+ } else if (idx == 1) {
return seg->get_b();
}
@@ -112,19 +112,19 @@ Variant CollisionShape2DEditor::get_handle_value(int idx) const {
return Variant();
}
-void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) {
+void CollisionShape2DEditor::set_handle(int idx, Point2 &p_point) {
- switch ( shape_type ) {
+ switch (shape_type) {
case CAPSULE_SHAPE: {
if (idx < 2) {
Ref<CapsuleShape2D> capsule = node->get_shape();
real_t parameter = Math::abs(p_point[idx]);
- if (idx==0) {
+ if (idx == 0) {
capsule->set_radius(parameter);
- } else if (idx==1){
- capsule->set_height(parameter*2 - capsule->get_radius()*2);
+ } else if (idx == 1) {
+ capsule->set_height(parameter * 2 - capsule->get_radius() * 2);
}
canvas_item_editor->get_viewport_control()->update();
@@ -149,19 +149,18 @@ void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) {
} break;
case LINE_SHAPE: {
- if (idx<2) {
+ if (idx < 2) {
Ref<LineShape2D> line = node->get_shape();
- if (idx==0){
+ if (idx == 0) {
line->set_d(p_point.length());
- }else{
+ } else {
line->set_normal(p_point.normalized());
}
canvas_item_editor->get_viewport_control()->update();
}
-
} break;
case RAY_SHAPE: {
@@ -174,7 +173,7 @@ void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) {
} break;
case RECTANGLE_SHAPE: {
- if (idx<2) {
+ if (idx < 2) {
Ref<RectangleShape2D> rect = node->get_shape();
Vector2 extents = rect->get_extents();
@@ -191,9 +190,9 @@ void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) {
if (edit_handle < 2) {
Ref<SegmentShape2D> seg = node->get_shape();
- if (idx==0) {
+ if (idx == 0) {
seg->set_a(p_point);
- } else if (idx==1) {
+ } else if (idx == 1) {
seg->set_b(p_point);
}
@@ -204,25 +203,25 @@ void CollisionShape2DEditor::set_handle(int idx, Point2& p_point) {
}
}
-void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) {
+void CollisionShape2DEditor::commit_handle(int idx, Variant &p_org) {
- Control* c = canvas_item_editor->get_viewport_control();
+ Control *c = canvas_item_editor->get_viewport_control();
undo_redo->create_action(TTR("Set Handle"));
- switch ( shape_type ) {
+ switch (shape_type) {
case CAPSULE_SHAPE: {
Ref<CapsuleShape2D> capsule = node->get_shape();
- if (idx==0) {
- undo_redo->add_do_method(capsule.ptr(),"set_radius",capsule->get_radius());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(capsule.ptr(),"set_radius",p_org);
- undo_redo->add_do_method(c,"update");
- } else if (idx==1) {
- undo_redo->add_do_method(capsule.ptr(),"set_height",capsule->get_height());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(capsule.ptr(),"set_height",p_org);
- undo_redo->add_undo_method(c,"update");
+ if (idx == 0) {
+ undo_redo->add_do_method(capsule.ptr(), "set_radius", capsule->get_radius());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(capsule.ptr(), "set_radius", p_org);
+ undo_redo->add_do_method(c, "update");
+ } else if (idx == 1) {
+ undo_redo->add_do_method(capsule.ptr(), "set_height", capsule->get_height());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(capsule.ptr(), "set_height", p_org);
+ undo_redo->add_undo_method(c, "update");
}
} break;
@@ -230,10 +229,10 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) {
case CIRCLE_SHAPE: {
Ref<CircleShape2D> circle = node->get_shape();
- undo_redo->add_do_method(circle.ptr(),"set_radius",circle->get_radius());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(circle.ptr(),"set_radius",p_org);
- undo_redo->add_undo_method(c,"update");
+ undo_redo->add_do_method(circle.ptr(), "set_radius", circle->get_radius());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(circle.ptr(), "set_radius", p_org);
+ undo_redo->add_undo_method(c, "update");
} break;
@@ -248,16 +247,16 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) {
case LINE_SHAPE: {
Ref<LineShape2D> line = node->get_shape();
- if (idx==0) {
- undo_redo->add_do_method(line.ptr(),"set_d",line->get_d());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(line.ptr(),"set_d",p_org);
- undo_redo->add_undo_method(c,"update");
+ if (idx == 0) {
+ undo_redo->add_do_method(line.ptr(), "set_d", line->get_d());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(line.ptr(), "set_d", p_org);
+ undo_redo->add_undo_method(c, "update");
} else {
- undo_redo->add_do_method(line.ptr(),"set_normal",line->get_normal());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(line.ptr(),"set_normal",p_org);
- undo_redo->add_undo_method(c,"update");
+ undo_redo->add_do_method(line.ptr(), "set_normal", line->get_normal());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(line.ptr(), "set_normal", p_org);
+ undo_redo->add_undo_method(c, "update");
}
} break;
@@ -265,35 +264,35 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) {
case RAY_SHAPE: {
Ref<RayShape2D> ray = node->get_shape();
- undo_redo->add_do_method(ray.ptr(),"set_length",ray->get_length());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(ray.ptr(),"set_length",p_org);
- undo_redo->add_undo_method(c,"update");
+ undo_redo->add_do_method(ray.ptr(), "set_length", ray->get_length());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(ray.ptr(), "set_length", p_org);
+ undo_redo->add_undo_method(c, "update");
} break;
case RECTANGLE_SHAPE: {
Ref<RectangleShape2D> rect = node->get_shape();
- undo_redo->add_do_method(rect.ptr(),"set_extents",rect->get_extents());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(rect.ptr(),"set_extents",p_org);
- undo_redo->add_undo_method(c,"update");
+ undo_redo->add_do_method(rect.ptr(), "set_extents", rect->get_extents());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(rect.ptr(), "set_extents", p_org);
+ undo_redo->add_undo_method(c, "update");
} break;
case SEGMENT_SHAPE: {
Ref<SegmentShape2D> seg = node->get_shape();
- if (idx==0) {
- undo_redo->add_do_method(seg.ptr(),"set_a",seg->get_a());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(seg.ptr(),"set_a",p_org);
- undo_redo->add_undo_method(c,"update");
- } else if (idx==1) {
- undo_redo->add_do_method(seg.ptr(),"set_b",seg->get_b());
- undo_redo->add_do_method(c,"update");
- undo_redo->add_undo_method(seg.ptr(),"set_b",p_org);
- undo_redo->add_undo_method(c,"update");
+ if (idx == 0) {
+ undo_redo->add_do_method(seg.ptr(), "set_a", seg->get_a());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(seg.ptr(), "set_a", p_org);
+ undo_redo->add_undo_method(c, "update");
+ } else if (idx == 1) {
+ undo_redo->add_do_method(seg.ptr(), "set_b", seg->get_b());
+ undo_redo->add_do_method(c, "update");
+ undo_redo->add_undo_method(seg.ptr(), "set_b", p_org);
+ undo_redo->add_undo_method(c, "update");
}
} break;
@@ -302,7 +301,7 @@ void CollisionShape2DEditor::commit_handle(int idx, Variant& p_org) {
undo_redo->commit_action();
}
-bool CollisionShape2DEditor::forward_gui_input(const InputEvent& p_event) {
+bool CollisionShape2DEditor::forward_gui_input(const InputEvent &p_event) {
if (!node) {
return false;
@@ -316,13 +315,13 @@ bool CollisionShape2DEditor::forward_gui_input(const InputEvent& p_event) {
return false;
}
- switch( p_event.type ) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton& mb = p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D gt = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Point2 gpoint(mb.x,mb.y);
+ Point2 gpoint(mb.x, mb.y);
if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
@@ -334,7 +333,7 @@ bool CollisionShape2DEditor::forward_gui_input(const InputEvent& p_event) {
}
}
- if (edit_handle==-1) {
+ if (edit_handle == -1) {
pressed = false;
return false;
@@ -362,13 +361,13 @@ bool CollisionShape2DEditor::forward_gui_input(const InputEvent& p_event) {
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion& mm = p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
if (edit_handle == -1 || !pressed) {
return false;
}
- Point2 gpoint = Point2(mm.x,mm.y);
+ Point2 gpoint = Point2(mm.x, mm.y);
Point2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
@@ -437,8 +436,8 @@ void CollisionShape2DEditor::_canvas_draw() {
Control *c = canvas_item_editor->get_viewport_control();
Transform2D gt = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> h = get_icon("EditorHandle","EditorIcons");
- Vector2 size = h->get_size()*0.5;
+ Ref<Texture> h = get_icon("EditorHandle", "EditorIcons");
+ Vector2 size = h->get_size() * 0.5;
handles.clear();
@@ -448,13 +447,13 @@ void CollisionShape2DEditor::_canvas_draw() {
handles.resize(2);
float radius = shape->get_radius();
- float height = shape->get_height()/2;
+ float height = shape->get_height() / 2;
handles[0] = Point2(radius, -height);
- handles[1] = Point2(0,-(height + radius));
+ handles[1] = Point2(0, -(height + radius));
- c->draw_texture(h, gt.xform(handles[0])-size);
- c->draw_texture(h, gt.xform(handles[1])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
+ c->draw_texture(h, gt.xform(handles[1]) - size);
} break;
@@ -462,9 +461,9 @@ void CollisionShape2DEditor::_canvas_draw() {
Ref<CircleShape2D> shape = node->get_shape();
handles.resize(1);
- handles[0] = Point2(shape->get_radius(),0);
+ handles[0] = Point2(shape->get_radius(), 0);
- c->draw_texture(h, gt.xform(handles[0])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
} break;
@@ -483,8 +482,8 @@ void CollisionShape2DEditor::_canvas_draw() {
handles[0] = shape->get_normal() * shape->get_d();
handles[1] = shape->get_normal() * (shape->get_d() + 30.0);
- c->draw_texture(h,gt.xform(handles[0])-size);
- c->draw_texture(h,gt.xform(handles[1])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
+ c->draw_texture(h, gt.xform(handles[1]) - size);
} break;
@@ -492,9 +491,9 @@ void CollisionShape2DEditor::_canvas_draw() {
Ref<RayShape2D> shape = node->get_shape();
handles.resize(1);
- handles[0] = Point2(0,shape->get_length());
+ handles[0] = Point2(0, shape->get_length());
- c->draw_texture(h,gt.xform(handles[0])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
} break;
@@ -503,11 +502,11 @@ void CollisionShape2DEditor::_canvas_draw() {
handles.resize(2);
Vector2 ext = shape->get_extents();
- handles[0] = Point2(ext.x,0);
- handles[1] = Point2(0,-ext.y);
+ handles[0] = Point2(ext.x, 0);
+ handles[1] = Point2(0, -ext.y);
- c->draw_texture(h,gt.xform(handles[0])-size);
- c->draw_texture(h,gt.xform(handles[1])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
+ c->draw_texture(h, gt.xform(handles[1]) - size);
} break;
@@ -518,24 +517,24 @@ void CollisionShape2DEditor::_canvas_draw() {
handles[0] = shape->get_a();
handles[1] = shape->get_b();
- c->draw_texture(h, gt.xform(handles[0])-size);
- c->draw_texture(h, gt.xform(handles[1])-size);
+ c->draw_texture(h, gt.xform(handles[0]) - size);
+ c->draw_texture(h, gt.xform(handles[1]) - size);
} break;
}
}
-void CollisionShape2DEditor::edit(Node* p_node) {
+void CollisionShape2DEditor::edit(Node *p_node) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_node) {
- node=p_node->cast_to<CollisionShape2D>();
+ node = p_node->cast_to<CollisionShape2D>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
_get_current_shape_type();
@@ -543,10 +542,10 @@ void CollisionShape2DEditor::edit(Node* p_node) {
edit_handle = -1;
shape_type = -1;
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
- node=NULL;
+ node = NULL;
}
canvas_item_editor->get_viewport_control()->update();
@@ -554,11 +553,11 @@ void CollisionShape2DEditor::edit(Node* p_node) {
void CollisionShape2DEditor::_bind_methods() {
- ClassDB::bind_method("_canvas_draw",&CollisionShape2DEditor::_canvas_draw);
- ClassDB::bind_method("_get_current_shape_type",&CollisionShape2DEditor::_get_current_shape_type);
+ ClassDB::bind_method("_canvas_draw", &CollisionShape2DEditor::_canvas_draw);
+ ClassDB::bind_method("_get_current_shape_type", &CollisionShape2DEditor::_get_current_shape_type);
}
-CollisionShape2DEditor::CollisionShape2DEditor(EditorNode* p_editor) {
+CollisionShape2DEditor::CollisionShape2DEditor(EditorNode *p_editor) {
node = NULL;
canvas_item_editor = NULL;
@@ -570,12 +569,12 @@ CollisionShape2DEditor::CollisionShape2DEditor(EditorNode* p_editor) {
pressed = false;
}
-void CollisionShape2DEditorPlugin::edit(Object* p_obj) {
+void CollisionShape2DEditorPlugin::edit(Object *p_obj) {
collision_shape_2d_editor->edit(p_obj->cast_to<Node>());
}
-bool CollisionShape2DEditorPlugin::handles(Object* p_obj) const {
+bool CollisionShape2DEditorPlugin::handles(Object *p_obj) const {
return p_obj->is_class("CollisionShape2D");
}
@@ -587,14 +586,13 @@ void CollisionShape2DEditorPlugin::make_visible(bool visible) {
}
}
-CollisionShape2DEditorPlugin::CollisionShape2DEditorPlugin(EditorNode* p_node) {
+CollisionShape2DEditorPlugin::CollisionShape2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
+ editor = p_node;
- collision_shape_2d_editor = memnew( CollisionShape2DEditor(p_node) );
+ collision_shape_2d_editor = memnew(CollisionShape2DEditor(p_node));
p_node->get_gui_base()->add_child(collision_shape_2d_editor);
}
CollisionShape2DEditorPlugin::~CollisionShape2DEditorPlugin() {
-
}
diff --git a/editor/plugins/collision_shape_2d_editor_plugin.h b/editor/plugins/collision_shape_2d_editor_plugin.h
index f7e6da8b4e..75331a1d61 100644
--- a/editor/plugins/collision_shape_2d_editor_plugin.h
+++ b/editor/plugins/collision_shape_2d_editor_plugin.h
@@ -29,8 +29,8 @@
#ifndef COLLISION_SHAPE_2D_EDITOR_PLUGIN_H
#define COLLISION_SHAPE_2D_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/collision_shape_2d.h"
@@ -50,10 +50,10 @@ class CollisionShape2DEditor : public Control {
SEGMENT_SHAPE
};
- EditorNode* editor;
- UndoRedo* undo_redo;
- CanvasItemEditor* canvas_item_editor;
- CollisionShape2D* node;
+ EditorNode *editor;
+ UndoRedo *undo_redo;
+ CanvasItemEditor *canvas_item_editor;
+ CollisionShape2D *node;
Vector<Point2> handles;
@@ -63,8 +63,8 @@ class CollisionShape2DEditor : public Control {
Variant original;
Variant get_handle_value(int idx) const;
- void set_handle(int idx, Point2& p_point);
- void commit_handle(int idx, Variant& p_org);
+ void set_handle(int idx, Point2 &p_point);
+ void commit_handle(int idx, Variant &p_org);
void _get_current_shape_type();
void _canvas_draw();
@@ -73,28 +73,28 @@ protected:
static void _bind_methods();
public:
- bool forward_gui_input(const InputEvent& p_event);
- void edit(Node* p_node);
+ bool forward_gui_input(const InputEvent &p_event);
+ void edit(Node *p_node);
- CollisionShape2DEditor(EditorNode* p_editor);
+ CollisionShape2DEditor(EditorNode *p_editor);
};
class CollisionShape2DEditorPlugin : public EditorPlugin {
GDCLASS(CollisionShape2DEditorPlugin, EditorPlugin);
- CollisionShape2DEditor* collision_shape_2d_editor;
- EditorNode* editor;
+ CollisionShape2DEditor *collision_shape_2d_editor;
+ EditorNode *editor;
public:
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return collision_shape_2d_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return collision_shape_2d_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "CollisionShape2D"; }
bool has_main_screen() const { return false; }
- virtual void edit(Object* p_obj);
- virtual bool handles(Object* p_obj) const;
+ virtual void edit(Object *p_obj);
+ virtual bool handles(Object *p_obj) const;
virtual void make_visible(bool visible);
- CollisionShape2DEditorPlugin(EditorNode* p_editor);
+ CollisionShape2DEditorPlugin(EditorNode *p_editor);
~CollisionShape2DEditorPlugin();
};
diff --git a/editor/plugins/color_ramp_editor_plugin.cpp b/editor/plugins/color_ramp_editor_plugin.cpp
index 82674fabb8..1d1d654bd5 100644
--- a/editor/plugins/color_ramp_editor_plugin.cpp
+++ b/editor/plugins/color_ramp_editor_plugin.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "color_ramp_editor_plugin.h"
-#include "spatial_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
+#include "spatial_editor_plugin.h"
ColorRampEditorPlugin::ColorRampEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- ramp_editor = memnew( ColorRampEdit );
-
+ editor = p_node;
+ ramp_editor = memnew(ColorRampEdit);
- add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM,ramp_editor);
+ add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM, ramp_editor);
ramp_editor->set_custom_minimum_size(Size2(100, 48));
ramp_editor->hide();
@@ -46,7 +45,7 @@ ColorRampEditorPlugin::ColorRampEditorPlugin(EditorNode *p_node) {
void ColorRampEditorPlugin::edit(Object *p_object) {
- ColorRamp* color_ramp = p_object->cast_to<ColorRamp>();
+ ColorRamp *color_ramp = p_object->cast_to<ColorRamp>();
if (!color_ramp)
return;
color_ramp_ref = Ref<ColorRamp>(color_ramp);
@@ -56,7 +55,6 @@ void ColorRampEditorPlugin::edit(Object *p_object) {
bool ColorRampEditorPlugin::handles(Object *p_object) const {
return p_object->is_class("ColorRamp");
-
}
void ColorRampEditorPlugin::make_visible(bool p_visible) {
@@ -66,36 +64,34 @@ void ColorRampEditorPlugin::make_visible(bool p_visible) {
} else {
ramp_editor->hide();
}
-
}
void ColorRampEditorPlugin::_ramp_changed() {
- if(color_ramp_ref.is_valid())
- {
+ if (color_ramp_ref.is_valid()) {
- UndoRedo *ur=EditorNode::get_singleton()->get_undo_redo();
+ UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
//Not sure if I should convert this data to PoolVector
- Vector<float> new_offsets=ramp_editor->get_offsets();
- Vector<Color> new_colors=ramp_editor->get_colors();
- Vector<float> old_offsets=color_ramp_ref->get_offsets();
- Vector<Color> old_colors=color_ramp_ref->get_colors();
+ Vector<float> new_offsets = ramp_editor->get_offsets();
+ Vector<Color> new_colors = ramp_editor->get_colors();
+ Vector<float> old_offsets = color_ramp_ref->get_offsets();
+ Vector<Color> old_colors = color_ramp_ref->get_colors();
- if (old_offsets.size()!=new_offsets.size())
+ if (old_offsets.size() != new_offsets.size())
ur->create_action(TTR("Add/Remove Color Ramp Point"));
else
- ur->create_action(TTR("Modify Color Ramp"),UndoRedo::MERGE_ENDS);
- ur->add_do_method(this,"undo_redo_color_ramp",new_offsets,new_colors);
- ur->add_undo_method(this,"undo_redo_color_ramp",old_offsets,old_colors);
+ ur->create_action(TTR("Modify Color Ramp"), UndoRedo::MERGE_ENDS);
+ ur->add_do_method(this, "undo_redo_color_ramp", new_offsets, new_colors);
+ ur->add_undo_method(this, "undo_redo_color_ramp", old_offsets, old_colors);
ur->commit_action();
//color_ramp_ref->set_points(ramp_editor->get_points());
}
}
-void ColorRampEditorPlugin::_undo_redo_color_ramp(const Vector<float>& offsets,
- const Vector<Color>& colors) {
+void ColorRampEditorPlugin::_undo_redo_color_ramp(const Vector<float> &offsets,
+ const Vector<Color> &colors) {
color_ramp_ref->set_offsets(offsets);
color_ramp_ref->set_colors(colors);
@@ -103,10 +99,10 @@ void ColorRampEditorPlugin::_undo_redo_color_ramp(const Vector<float>& offsets,
ramp_editor->update();
}
-ColorRampEditorPlugin::~ColorRampEditorPlugin(){
+ColorRampEditorPlugin::~ColorRampEditorPlugin() {
}
void ColorRampEditorPlugin::_bind_methods() {
- ClassDB::bind_method(D_METHOD("ramp_changed"),&ColorRampEditorPlugin::_ramp_changed);
- ClassDB::bind_method(D_METHOD("undo_redo_color_ramp","offsets","colors"),&ColorRampEditorPlugin::_undo_redo_color_ramp);
+ ClassDB::bind_method(D_METHOD("ramp_changed"), &ColorRampEditorPlugin::_ramp_changed);
+ ClassDB::bind_method(D_METHOD("undo_redo_color_ramp", "offsets", "colors"), &ColorRampEditorPlugin::_undo_redo_color_ramp);
}
diff --git a/editor/plugins/color_ramp_editor_plugin.h b/editor/plugins/color_ramp_editor_plugin.h
index 0323bd7a46..45ac53c669 100644
--- a/editor/plugins/color_ramp_editor_plugin.h
+++ b/editor/plugins/color_ramp_editor_plugin.h
@@ -29,13 +29,13 @@
#ifndef TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_
#define TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/gui/color_ramp_edit.h"
class ColorRampEditorPlugin : public EditorPlugin {
- GDCLASS( ColorRampEditorPlugin, EditorPlugin );
+ GDCLASS(ColorRampEditorPlugin, EditorPlugin);
bool _2d;
Ref<ColorRamp> color_ramp_ref;
@@ -45,7 +45,7 @@ class ColorRampEditorPlugin : public EditorPlugin {
protected:
static void _bind_methods();
void _ramp_changed();
- void _undo_redo_color_ramp(const Vector<float>& offsets, const Vector<Color>& colors);
+ void _undo_redo_color_ramp(const Vector<float> &offsets, const Vector<Color> &colors);
public:
virtual String get_name() const { return "ColorRamp"; }
@@ -56,7 +56,6 @@ public:
ColorRampEditorPlugin(EditorNode *p_node);
~ColorRampEditorPlugin();
-
};
#endif /* TOOLS_EDITOR_PLUGINS_COLOR_RAMP_EDITOR_PLUGIN_H_ */
diff --git a/editor/plugins/cube_grid_theme_editor_plugin.cpp b/editor/plugins/cube_grid_theme_editor_plugin.cpp
index b8abd2e9cc..e73a9b31af 100644
--- a/editor/plugins/cube_grid_theme_editor_plugin.cpp
+++ b/editor/plugins/cube_grid_theme_editor_plugin.cpp
@@ -29,14 +29,14 @@
#include "cube_grid_theme_editor_plugin.h"
#if 0
+#include "editor/editor_node.h"
+#include "editor/editor_settings.h"
+#include "main/main.h"
#include "scene/3d/mesh_instance.h"
+#include "scene/3d/navigation_mesh.h"
#include "scene/3d/physics_body.h"
#include "scene/main/viewport.h"
#include "scene/resources/packed_scene.h"
-#include "editor/editor_node.h"
-#include "main/main.h"
-#include "editor/editor_settings.h"
-#include "scene/3d/navigation_mesh.h"
void MeshLibraryEditor::edit(const Ref<MeshLibrary>& p_theme) {
diff --git a/editor/plugins/cube_grid_theme_editor_plugin.h b/editor/plugins/cube_grid_theme_editor_plugin.h
index 07e7c7cadd..af3929e616 100644
--- a/editor/plugins/cube_grid_theme_editor_plugin.h
+++ b/editor/plugins/cube_grid_theme_editor_plugin.h
@@ -29,8 +29,8 @@
#ifndef CUBE_GRID_THEME_EDITOR_PLUGIN_H
#define CUBE_GRID_THEME_EDITOR_PLUGIN_H
-#include "scene/resources/mesh_library.h"
#include "editor/editor_node.h"
+#include "scene/resources/mesh_library.h"
#if 0
class MeshLibraryEditor : public Control {
@@ -91,6 +91,5 @@ public:
};
-
#endif // CUBE_GRID_THEME_EDITOR_PLUGIN_H
#endif
diff --git a/editor/plugins/editor_preview_plugins.cpp b/editor/plugins/editor_preview_plugins.cpp
index 3f31f1e0f1..eaadf3976b 100644
--- a/editor/plugins/editor_preview_plugins.cpp
+++ b/editor/plugins/editor_preview_plugins.cpp
@@ -28,15 +28,15 @@
/*************************************************************************/
#include "editor_preview_plugins.h"
-#include "io/resource_loader.h"
#include "editor/editor_settings.h"
#include "io/file_access_memory.h"
+#include "io/resource_loader.h"
#include "os/os.h"
#include "scene/resources/material.h"
//#include "scene/resources/sample.h"
-#include "scene/resources/mesh.h"
-#include "scene/resources/bit_mask.h"
#include "editor/editor_scale.h"
+#include "scene/resources/bit_mask.h"
+#include "scene/resources/mesh.h"
#if 0
bool EditorTexturePreviewPlugin::handles(const String& p_type) const {
@@ -345,21 +345,23 @@ EditorMaterialPreviewPlugin::EditorMaterialPreviewPlugin() {
Vector3(x0 * zr0, z0, y0 *zr0)
};
-#define ADD_POINT(m_idx) \
- normals.push_back(v[m_idx]);\
- vertices.push_back(v[m_idx]*radius);\
- { Vector2 uv(Math::atan2(v[m_idx].x,v[m_idx].z),Math::atan2(-v[m_idx].y,v[m_idx].z));\
- uv/=Math_PI;\
- uv*=4.0;\
- uv=uv*0.5+Vector2(0.5,0.5);\
- uvs.push_back(uv);\
- }\
- { Vector3 t = tt.xform(v[m_idx]);\
- tangents.push_back(t.x);\
- tangents.push_back(t.y);\
- tangents.push_back(t.z);\
- tangents.push_back(1.0);\
- }
+#define ADD_POINT(m_idx) \
+ normals.push_back(v[m_idx]); \
+ vertices.push_back(v[m_idx] * radius); \
+ { \
+ Vector2 uv(Math::atan2(v[m_idx].x, v[m_idx].z), Math::atan2(-v[m_idx].y, v[m_idx].z)); \
+ uv /= Math_PI; \
+ uv *= 4.0; \
+ uv = uv * 0.5 + Vector2(0.5, 0.5); \
+ uvs.push_back(uv); \
+ } \
+ { \
+ Vector3 t = tt.xform(v[m_idx]); \
+ tangents.push_back(t.x); \
+ tangents.push_back(t.y); \
+ tangents.push_back(t.z); \
+ tangents.push_back(1.0); \
+ }
diff --git a/editor/plugins/gi_probe_editor_plugin.cpp b/editor/plugins/gi_probe_editor_plugin.cpp
index 925ac8ef11..0930c91e94 100644
--- a/editor/plugins/gi_probe_editor_plugin.cpp
+++ b/editor/plugins/gi_probe_editor_plugin.cpp
@@ -28,7 +28,6 @@
/*************************************************************************/
#include "gi_probe_editor_plugin.h"
-
void GIProbeEditorPlugin::_bake() {
if (gi_probe) {
@@ -36,14 +35,13 @@ void GIProbeEditorPlugin::_bake() {
}
}
-
void GIProbeEditorPlugin::edit(Object *p_object) {
- GIProbe * s = p_object->cast_to<GIProbe>();
+ GIProbe *s = p_object->cast_to<GIProbe>();
if (!s)
return;
- gi_probe=s;
+ gi_probe = s;
}
bool GIProbeEditorPlugin::handles(Object *p_object) const {
@@ -59,25 +57,23 @@ void GIProbeEditorPlugin::make_visible(bool p_visible) {
bake->hide();
}
-
}
void GIProbeEditorPlugin::_bind_methods() {
- ClassDB::bind_method("_bake",&GIProbeEditorPlugin::_bake);
+ ClassDB::bind_method("_bake", &GIProbeEditorPlugin::_bake);
}
GIProbeEditorPlugin::GIProbeEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- bake = memnew( Button );
- bake->set_icon(editor->get_gui_base()->get_icon("BakedLight","EditorIcons"));
+ editor = p_node;
+ bake = memnew(Button);
+ bake->set_icon(editor->get_gui_base()->get_icon("BakedLight", "EditorIcons"));
bake->hide();
- bake->connect("pressed",this,"_bake");
- add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU,bake);
- gi_probe=NULL;
+ bake->connect("pressed", this, "_bake");
+ add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, bake);
+ gi_probe = NULL;
}
-
GIProbeEditorPlugin::~GIProbeEditorPlugin() {
}
diff --git a/editor/plugins/gi_probe_editor_plugin.h b/editor/plugins/gi_probe_editor_plugin.h
index 982a549368..14d831a01a 100644
--- a/editor/plugins/gi_probe_editor_plugin.h
+++ b/editor/plugins/gi_probe_editor_plugin.h
@@ -29,16 +29,14 @@
#ifndef GIPROBEEDITORPLUGIN_H
#define GIPROBEEDITORPLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/resources/material.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/gi_probe.h"
-
-
+#include "scene/resources/material.h"
class GIProbeEditorPlugin : public EditorPlugin {
- GDCLASS( GIProbeEditorPlugin, EditorPlugin );
+ GDCLASS(GIProbeEditorPlugin, EditorPlugin);
GIProbe *gi_probe;
@@ -46,11 +44,11 @@ class GIProbeEditorPlugin : public EditorPlugin {
EditorNode *editor;
void _bake();
-protected:
+protected:
static void _bind_methods();
-public:
+public:
virtual String get_name() const { return "GIProbe"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -59,7 +57,6 @@ public:
GIProbeEditorPlugin(EditorNode *p_node);
~GIProbeEditorPlugin();
-
};
#endif // GIPROBEEDITORPLUGIN_H
diff --git a/editor/plugins/item_list_editor_plugin.cpp b/editor/plugins/item_list_editor_plugin.cpp
index f31074a9dc..fabbf07a15 100644
--- a/editor/plugins/item_list_editor_plugin.cpp
+++ b/editor/plugins/item_list_editor_plugin.cpp
@@ -30,81 +30,81 @@
#include "io/resource_loader.h"
-bool ItemListPlugin::_set(const StringName& p_name, const Variant& p_value) {
+bool ItemListPlugin::_set(const StringName &p_name, const Variant &p_value) {
String name = p_name;
- int idx = name.get_slice("/",0).to_int();
- String what=name.get_slice("/",1);
-
- if (what=="text")
- set_item_text(idx,p_value);
- else if (what=="icon")
- set_item_icon(idx,p_value);
- else if (what=="checkable")
- set_item_checkable(idx,p_value);
- else if (what=="checked")
- set_item_checked(idx,p_value);
- else if (what=="id")
- set_item_id(idx,p_value);
- else if (what=="enabled")
- set_item_enabled(idx,p_value);
- else if (what=="separator")
- set_item_separator(idx,p_value);
+ int idx = name.get_slice("/", 0).to_int();
+ String what = name.get_slice("/", 1);
+
+ if (what == "text")
+ set_item_text(idx, p_value);
+ else if (what == "icon")
+ set_item_icon(idx, p_value);
+ else if (what == "checkable")
+ set_item_checkable(idx, p_value);
+ else if (what == "checked")
+ set_item_checked(idx, p_value);
+ else if (what == "id")
+ set_item_id(idx, p_value);
+ else if (what == "enabled")
+ set_item_enabled(idx, p_value);
+ else if (what == "separator")
+ set_item_separator(idx, p_value);
else
return false;
return true;
}
-bool ItemListPlugin::_get(const StringName& p_name,Variant &r_ret) const {
+bool ItemListPlugin::_get(const StringName &p_name, Variant &r_ret) const {
String name = p_name;
- int idx = name.get_slice("/",0).to_int();
- String what=name.get_slice("/",1);
-
- if (what=="text")
- r_ret=get_item_text(idx);
- else if (what=="icon")
- r_ret=get_item_icon(idx);
- else if (what=="checkable")
- r_ret=is_item_checkable(idx);
- else if (what=="checked")
- r_ret=is_item_checked(idx);
- else if (what=="id")
- r_ret=get_item_id(idx);
- else if (what=="enabled")
- r_ret=is_item_enabled(idx);
- else if (what=="separator")
- r_ret=is_item_separator(idx);
+ int idx = name.get_slice("/", 0).to_int();
+ String what = name.get_slice("/", 1);
+
+ if (what == "text")
+ r_ret = get_item_text(idx);
+ else if (what == "icon")
+ r_ret = get_item_icon(idx);
+ else if (what == "checkable")
+ r_ret = is_item_checkable(idx);
+ else if (what == "checked")
+ r_ret = is_item_checked(idx);
+ else if (what == "id")
+ r_ret = get_item_id(idx);
+ else if (what == "enabled")
+ r_ret = is_item_enabled(idx);
+ else if (what == "separator")
+ r_ret = is_item_separator(idx);
else
return false;
return true;
}
-void ItemListPlugin::_get_property_list( List<PropertyInfo> *p_list) const {
+void ItemListPlugin::_get_property_list(List<PropertyInfo> *p_list) const {
- for(int i=0;i<get_item_count();i++) {
+ for (int i = 0; i < get_item_count(); i++) {
- String base=itos(i)+"/";
+ String base = itos(i) + "/";
- p_list->push_back( PropertyInfo(Variant::STRING,base+"text") );
- p_list->push_back( PropertyInfo(Variant::OBJECT,base+"icon",PROPERTY_HINT_RESOURCE_TYPE,"Texture") );
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "text"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, base + "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"));
int flags = get_flags();
- if (flags&FLAG_CHECKABLE) {
- p_list->push_back( PropertyInfo(Variant::BOOL,base+"checkable") );
- p_list->push_back( PropertyInfo(Variant::BOOL,base+"checked") );
+ if (flags & FLAG_CHECKABLE) {
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "checkable"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "checked"));
}
- if (flags&FLAG_ID)
- p_list->push_back( PropertyInfo(Variant::INT,base+"id",PROPERTY_HINT_RANGE,"-1,4096") );
+ if (flags & FLAG_ID)
+ p_list->push_back(PropertyInfo(Variant::INT, base + "id", PROPERTY_HINT_RANGE, "-1,4096"));
- if (flags&FLAG_ENABLE)
- p_list->push_back( PropertyInfo(Variant::BOOL,base+"enabled") );
+ if (flags & FLAG_ENABLE)
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "enabled"));
- if (flags&FLAG_SEPARATOR)
- p_list->push_back( PropertyInfo(Variant::BOOL,base+"separator") );
+ if (flags & FLAG_SEPARATOR)
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "separator"));
}
}
@@ -124,12 +124,12 @@ bool ItemListOptionButtonPlugin::handles(Object *p_object) const {
int ItemListOptionButtonPlugin::get_flags() const {
- return FLAG_ICON|FLAG_ID|FLAG_ENABLE;
+ return FLAG_ICON | FLAG_ID | FLAG_ENABLE;
}
void ItemListOptionButtonPlugin::add_item() {
- ob->add_item( vformat(TTR("Item %d"),ob->get_item_count()));
+ ob->add_item(vformat(TTR("Item %d"), ob->get_item_count()));
_change_notify();
}
@@ -146,7 +146,7 @@ void ItemListOptionButtonPlugin::erase(int p_idx) {
ItemListOptionButtonPlugin::ItemListOptionButtonPlugin() {
- ob=NULL;
+ ob = NULL;
}
///////////////////////////////////////////////////////////////
@@ -166,12 +166,12 @@ bool ItemListPopupMenuPlugin::handles(Object *p_object) const {
int ItemListPopupMenuPlugin::get_flags() const {
- return FLAG_ICON|FLAG_CHECKABLE|FLAG_ID|FLAG_ENABLE|FLAG_SEPARATOR;
+ return FLAG_ICON | FLAG_CHECKABLE | FLAG_ID | FLAG_ENABLE | FLAG_SEPARATOR;
}
void ItemListPopupMenuPlugin::add_item() {
- pp->add_item( vformat(TTR("Item %d"),pp->get_item_count()));
+ pp->add_item(vformat(TTR("Item %d"), pp->get_item_count()));
_change_notify();
}
@@ -188,7 +188,7 @@ void ItemListPopupMenuPlugin::erase(int p_idx) {
ItemListPopupMenuPlugin::ItemListPopupMenuPlugin() {
- pp=NULL;
+ pp = NULL;
}
///////////////////////////////////////////////////////////////
@@ -197,8 +197,8 @@ ItemListPopupMenuPlugin::ItemListPopupMenuPlugin() {
void ItemListEditor::_node_removed(Node *p_node) {
- if(p_node==item_list) {
- item_list=NULL;
+ if (p_node == item_list) {
+ item_list = NULL;
hide();
dialog->hide();
}
@@ -206,16 +206,16 @@ void ItemListEditor::_node_removed(Node *p_node) {
void ItemListEditor::_notification(int p_notification) {
- if (p_notification==NOTIFICATION_ENTER_TREE) {
+ if (p_notification == NOTIFICATION_ENTER_TREE) {
- add_button->set_icon(get_icon("Add","EditorIcons"));
- del_button->set_icon(get_icon("Remove","EditorIcons"));
+ add_button->set_icon(get_icon("Add", "EditorIcons"));
+ del_button->set_icon(get_icon("Remove", "EditorIcons"));
}
}
void ItemListEditor::_add_pressed() {
- if (selected_idx==-1)
+ if (selected_idx == -1)
return;
item_plugins[selected_idx]->add_item();
@@ -228,12 +228,12 @@ void ItemListEditor::_delete_pressed() {
if (!ti)
return;
- if (ti->get_parent()!=tree->get_root())
+ if (ti->get_parent() != tree->get_root())
return;
int idx = ti->get_text(0).to_int();
- if (selected_idx==-1)
+ if (selected_idx == -1)
return;
item_plugins[selected_idx]->erase(idx);
@@ -246,15 +246,15 @@ void ItemListEditor::_edit_items() {
void ItemListEditor::edit(Node *p_item_list) {
- item_list=p_item_list;
+ item_list = p_item_list;
if (!item_list) {
- selected_idx=-1;
+ selected_idx = -1;
property_editor->edit(NULL);
return;
}
- for(int i=0;i<item_plugins.size();i++) {
+ for (int i = 0; i < item_plugins.size(); i++) {
if (item_plugins[i]->handles(p_item_list)) {
item_plugins[i]->set_object(p_item_list);
@@ -265,18 +265,18 @@ void ItemListEditor::edit(Node *p_item_list) {
else
toolbar_button->set_icon(Ref<Texture>());
- selected_idx=i;
+ selected_idx = i;
return;
}
}
- selected_idx=-1;
+ selected_idx = -1;
property_editor->edit(NULL);
}
bool ItemListEditor::handles(Object *p_object) const {
- for(int i=0;i<item_plugins.size();i++) {
+ for (int i = 0; i < item_plugins.size(); i++) {
if (item_plugins[i]->handles(p_object)) {
return true;
}
@@ -287,47 +287,47 @@ bool ItemListEditor::handles(Object *p_object) const {
void ItemListEditor::_bind_methods() {
- ClassDB::bind_method("_edit_items",&ItemListEditor::_edit_items);
- ClassDB::bind_method("_add_button",&ItemListEditor::_add_pressed);
- ClassDB::bind_method("_delete_button",&ItemListEditor::_delete_pressed);
+ ClassDB::bind_method("_edit_items", &ItemListEditor::_edit_items);
+ ClassDB::bind_method("_add_button", &ItemListEditor::_add_pressed);
+ ClassDB::bind_method("_delete_button", &ItemListEditor::_delete_pressed);
}
ItemListEditor::ItemListEditor() {
- selected_idx=-1;
+ selected_idx = -1;
- add_child( memnew( VSeparator ) );
+ add_child(memnew(VSeparator));
- toolbar_button = memnew( ToolButton );
+ toolbar_button = memnew(ToolButton);
toolbar_button->set_text(TTR("Items"));
add_child(toolbar_button);
- toolbar_button->connect("pressed",this,"_edit_items");
+ toolbar_button->connect("pressed", this, "_edit_items");
- dialog = memnew( AcceptDialog );
+ dialog = memnew(AcceptDialog);
dialog->set_title(TTR("Item List Editor"));
- add_child( dialog );
+ add_child(dialog);
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
dialog->add_child(vbc);
//dialog->set_child_rect(vbc);
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(hbc);
- add_button = memnew( Button );
+ add_button = memnew(Button);
add_button->set_text(TTR("Add"));
hbc->add_child(add_button);
- add_button->connect("pressed",this,"_add_button");
+ add_button->connect("pressed", this, "_add_button");
hbc->add_spacer();
- del_button = memnew( Button );
+ del_button = memnew(Button);
del_button->set_text(TTR("Delete"));
hbc->add_child(del_button);
- del_button->connect("pressed",this,"_delete_button");
+ del_button->connect("pressed", this, "_delete_button");
- property_editor = memnew( PropertyEditor );
+ property_editor = memnew(PropertyEditor);
property_editor->hide_top_label();
property_editor->set_subsection_selectable(true);
vbc->add_child(property_editor);
@@ -338,8 +338,8 @@ ItemListEditor::ItemListEditor() {
ItemListEditor::~ItemListEditor() {
- for(int i=0;i<item_plugins.size();i++)
- memdelete( item_plugins[i] );
+ for (int i = 0; i < item_plugins.size(); i++)
+ memdelete(item_plugins[i]);
}
void ItemListEditorPlugin::edit(Object *p_object) {
@@ -365,17 +365,14 @@ void ItemListEditorPlugin::make_visible(bool p_visible) {
ItemListEditorPlugin::ItemListEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- item_list_editor = memnew( ItemListEditor );
+ editor = p_node;
+ item_list_editor = memnew(ItemListEditor);
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(item_list_editor);
item_list_editor->hide();
- item_list_editor->add_plugin( memnew( ItemListOptionButtonPlugin ) );
- item_list_editor->add_plugin( memnew( ItemListPopupMenuPlugin ) );
+ item_list_editor->add_plugin(memnew(ItemListOptionButtonPlugin));
+ item_list_editor->add_plugin(memnew(ItemListPopupMenuPlugin));
}
-ItemListEditorPlugin::~ItemListEditorPlugin()
-{
+ItemListEditorPlugin::~ItemListEditorPlugin() {
}
-
-
diff --git a/editor/plugins/item_list_editor_plugin.h b/editor/plugins/item_list_editor_plugin.h
index 25d6ed6757..064c43bda5 100644
--- a/editor/plugins/item_list_editor_plugin.h
+++ b/editor/plugins/item_list_editor_plugin.h
@@ -29,69 +29,66 @@
#ifndef ITEM_LIST_EDITOR_PLUGIN_H
#define ITEM_LIST_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
-#include "editor/editor_node.h"
#include "canvas_item_editor_plugin.h"
+#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
-#include "scene/gui/option_button.h"
#include "scene/gui/menu_button.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/popup_menu.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class ItemListPlugin : public Object {
- GDCLASS(ItemListPlugin,Object);
+ GDCLASS(ItemListPlugin, Object);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
enum Flags {
- FLAG_ICON=1,
- FLAG_CHECKABLE=2,
- FLAG_ID=4,
- FLAG_ENABLE=8,
- FLAG_SEPARATOR=16
+ FLAG_ICON = 1,
+ FLAG_CHECKABLE = 2,
+ FLAG_ID = 4,
+ FLAG_ENABLE = 8,
+ FLAG_SEPARATOR = 16
};
- virtual void set_object(Object *p_object)=0;
- virtual bool handles(Object *p_object) const=0;
+ virtual void set_object(Object *p_object) = 0;
+ virtual bool handles(Object *p_object) const = 0;
- virtual int get_flags() const=0;
+ virtual int get_flags() const = 0;
- virtual void set_item_text(int p_idx, const String& p_text) {}
- virtual String get_item_text(int p_idx) const{ return ""; };
+ virtual void set_item_text(int p_idx, const String &p_text) {}
+ virtual String get_item_text(int p_idx) const { return ""; };
- virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) {}
- virtual Ref<Texture> get_item_icon(int p_idx) const{ return Ref<Texture>(); };
+ virtual void set_item_icon(int p_idx, const Ref<Texture> &p_tex) {}
+ virtual Ref<Texture> get_item_icon(int p_idx) const { return Ref<Texture>(); };
virtual void set_item_checkable(int p_idx, bool p_check) {}
- virtual bool is_item_checkable(int p_idx) const{ return false; };
+ virtual bool is_item_checkable(int p_idx) const { return false; };
virtual void set_item_checked(int p_idx, bool p_checked) {}
- virtual bool is_item_checked(int p_idx) const{ return false; };
+ virtual bool is_item_checked(int p_idx) const { return false; };
virtual void set_item_enabled(int p_idx, int p_enabled) {}
- virtual bool is_item_enabled(int p_idx) const{ return false; };
+ virtual bool is_item_enabled(int p_idx) const { return false; };
virtual void set_item_id(int p_idx, int p_id) {}
- virtual int get_item_id(int p_idx) const{ return -1; };
+ virtual int get_item_id(int p_idx) const { return -1; };
virtual void set_item_separator(int p_idx, bool p_separator) {}
virtual bool is_item_separator(int p_idx) const { return false; };
- virtual void add_item()=0;
- virtual int get_item_count() const=0;
- virtual void erase(int p_idx)=0;
+ virtual void add_item() = 0;
+ virtual int get_item_count() const = 0;
+ virtual void erase(int p_idx) = 0;
ItemListPlugin() {}
};
@@ -100,25 +97,25 @@ public:
class ItemListOptionButtonPlugin : public ItemListPlugin {
- GDCLASS(ItemListOptionButtonPlugin,ItemListPlugin);
+ GDCLASS(ItemListOptionButtonPlugin, ItemListPlugin);
OptionButton *ob;
-public:
+public:
virtual void set_object(Object *p_object);
virtual bool handles(Object *p_object) const;
virtual int get_flags() const;
- virtual void set_item_text(int p_idx, const String& p_text) { ob->set_item_text(p_idx,p_text); }
+ virtual void set_item_text(int p_idx, const String &p_text) { ob->set_item_text(p_idx, p_text); }
virtual String get_item_text(int p_idx) const { return ob->get_item_text(p_idx); }
- virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) { ob->set_item_icon(p_idx, p_tex); }
+ virtual void set_item_icon(int p_idx, const Ref<Texture> &p_tex) { ob->set_item_icon(p_idx, p_tex); }
virtual Ref<Texture> get_item_icon(int p_idx) const { return ob->get_item_icon(p_idx); }
virtual void set_item_enabled(int p_idx, int p_enabled) { ob->set_item_disabled(p_idx, !p_enabled); }
virtual bool is_item_enabled(int p_idx) const { return !ob->is_item_disabled(p_idx); }
- virtual void set_item_id(int p_idx, int p_id) { ob->set_item_ID(p_idx,p_id); }
+ virtual void set_item_id(int p_idx, int p_id) { ob->set_item_ID(p_idx, p_id); }
virtual int get_item_id(int p_idx) const { return ob->get_item_ID(p_idx); }
virtual void add_item();
@@ -130,34 +127,34 @@ public:
class ItemListPopupMenuPlugin : public ItemListPlugin {
- GDCLASS(ItemListPopupMenuPlugin,ItemListPlugin);
+ GDCLASS(ItemListPopupMenuPlugin, ItemListPlugin);
PopupMenu *pp;
-public:
+public:
virtual void set_object(Object *p_object);
virtual bool handles(Object *p_object) const;
virtual int get_flags() const;
- virtual void set_item_text(int p_idx, const String& p_text) { pp->set_item_text(p_idx,p_text); }
+ virtual void set_item_text(int p_idx, const String &p_text) { pp->set_item_text(p_idx, p_text); }
virtual String get_item_text(int p_idx) const { return pp->get_item_text(p_idx); }
- virtual void set_item_icon(int p_idx, const Ref<Texture>& p_tex) { pp->set_item_icon(p_idx,p_tex); }
+ virtual void set_item_icon(int p_idx, const Ref<Texture> &p_tex) { pp->set_item_icon(p_idx, p_tex); }
virtual Ref<Texture> get_item_icon(int p_idx) const { return pp->get_item_icon(p_idx); }
- virtual void set_item_checkable(int p_idx, bool p_check) { pp->set_item_as_checkable(p_idx,p_check); }
+ virtual void set_item_checkable(int p_idx, bool p_check) { pp->set_item_as_checkable(p_idx, p_check); }
virtual bool is_item_checkable(int p_idx) const { return pp->is_item_checkable(p_idx); }
- virtual void set_item_checked(int p_idx, bool p_checked) { pp->set_item_checked(p_idx,p_checked); }
+ virtual void set_item_checked(int p_idx, bool p_checked) { pp->set_item_checked(p_idx, p_checked); }
virtual bool is_item_checked(int p_idx) const { return pp->is_item_checked(p_idx); }
- virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx,!p_enabled); }
+ virtual void set_item_enabled(int p_idx, int p_enabled) { pp->set_item_disabled(p_idx, !p_enabled); }
virtual bool is_item_enabled(int p_idx) const { return !pp->is_item_disabled(p_idx); }
- virtual void set_item_id(int p_idx, int p_id) { pp->set_item_ID(p_idx,p_idx); }
+ virtual void set_item_id(int p_idx, int p_id) { pp->set_item_ID(p_idx, p_idx); }
virtual int get_item_id(int p_idx) const { return pp->get_item_ID(p_idx); }
- virtual void set_item_separator(int p_idx, bool p_separator) { pp->set_item_as_separator(p_idx,p_separator); }
+ virtual void set_item_separator(int p_idx, bool p_separator) { pp->set_item_as_separator(p_idx, p_separator); }
virtual bool is_item_separator(int p_idx) const { return pp->is_item_separator(p_idx); }
virtual void add_item();
@@ -171,7 +168,7 @@ public:
class ItemListEditor : public HBoxContainer {
- GDCLASS(ItemListEditor,HBoxContainer);
+ GDCLASS(ItemListEditor, HBoxContainer);
Node *item_list;
@@ -185,7 +182,7 @@ class ItemListEditor : public HBoxContainer {
int selected_idx;
- Vector<ItemListPlugin*> item_plugins;
+ Vector<ItemListPlugin *> item_plugins;
void _edit_items();
@@ -195,27 +192,25 @@ class ItemListEditor : public HBoxContainer {
void _node_removed(Node *p_node);
protected:
-
void _notification(int p_notification);
static void _bind_methods();
-public:
+public:
void edit(Node *p_item_list);
bool handles(Object *p_object) const;
- void add_plugin(ItemListPlugin* p_plugin) { item_plugins.push_back(p_plugin); }
+ void add_plugin(ItemListPlugin *p_plugin) { item_plugins.push_back(p_plugin); }
ItemListEditor();
~ItemListEditor();
};
class ItemListEditorPlugin : public EditorPlugin {
- GDCLASS(ItemListEditorPlugin,EditorPlugin);
+ GDCLASS(ItemListEditorPlugin, EditorPlugin);
ItemListEditor *item_list_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "ItemList"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -224,7 +219,6 @@ public:
ItemListEditorPlugin(EditorNode *p_node);
~ItemListEditorPlugin();
-
};
#endif // ITEM_LIST_EDITOR_PLUGIN_H
diff --git a/editor/plugins/light_occluder_2d_editor_plugin.cpp b/editor/plugins/light_occluder_2d_editor_plugin.cpp
index be9e52e241..6db25e8455 100644
--- a/editor/plugins/light_occluder_2d_editor_plugin.cpp
+++ b/editor/plugins/light_occluder_2d_editor_plugin.cpp
@@ -29,208 +29,193 @@
#include "light_occluder_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
+#include "os/file_access.h"
void LightOccluder2DEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
- button_create->set_icon( get_icon("Edit","EditorIcons"));
- button_edit->set_icon( get_icon("MovePoint","EditorIcons"));
+ button_create->set_icon(get_icon("Edit", "EditorIcons"));
+ button_edit->set_icon(get_icon("MovePoint", "EditorIcons"));
button_edit->set_pressed(true);
- get_tree()->connect("node_removed",this,"_node_removed");
- create_poly->connect("confirmed",this,"_create_poly");
+ get_tree()->connect("node_removed", this, "_node_removed");
+ create_poly->connect("confirmed", this, "_create_poly");
} break;
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void LightOccluder2DEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
canvas_item_editor->get_viewport_control()->update();
}
-
}
-
void LightOccluder2DEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MODE_CREATE: {
- mode=MODE_CREATE;
+ mode = MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
-
}
}
void LightOccluder2DEditor::_wip_close(bool p_closed) {
undo_redo->create_action(TTR("Create Poly"));
- undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",node->get_occluder_polygon()->get_polygon());
- undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",wip);
- undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_closed",node->get_occluder_polygon()->is_closed());
- undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_closed",p_closed);
+ undo_redo->add_undo_method(node->get_occluder_polygon().ptr(), "set_polygon", node->get_occluder_polygon()->get_polygon());
+ undo_redo->add_do_method(node->get_occluder_polygon().ptr(), "set_polygon", wip);
+ undo_redo->add_undo_method(node->get_occluder_polygon().ptr(), "set_closed", node->get_occluder_polygon()->is_closed());
+ undo_redo->add_do_method(node->get_occluder_polygon().ptr(), "set_closed", p_closed);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
wip.clear();
- wip_active=false;
- mode=MODE_EDIT;
+ wip_active = false;
+ mode = MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
- edited_point=-1;
+ edited_point = -1;
}
-bool LightOccluder2DEditor::forward_gui_input(const InputEvent& p_event) {
-
+bool LightOccluder2DEditor::forward_gui_input(const InputEvent &p_event) {
if (!node)
return false;
if (node->get_occluder_polygon().is_null()) {
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && p_event.mouse_button.pressed) {
create_poly->set_text("No OccluderPolygon2D resource on this node.\nCreate and assign one?");
create_poly->popup_centered_minsize();
}
- return (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1);
+ return (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1);
}
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
-
- Vector2 gpoint = Point2(mb.x,mb.y);
+ Vector2 gpoint = Point2(mb.x, mb.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
Vector<Vector2> poly = Variant(node->get_occluder_polygon()->get_polygon());
//first check if a point is to be added (segment split)
- real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
-
- switch(mode) {
+ real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
+ switch (mode) {
case MODE_CREATE: {
- if (mb.button_index==BUTTON_LEFT && mb.pressed) {
-
+ if (mb.button_index == BUTTON_LEFT && mb.pressed) {
if (!wip_active) {
wip.clear();
- wip.push_back( cpoint );
- wip_active=true;
- edited_point_pos=cpoint;
+ wip.push_back(cpoint);
+ wip_active = true;
+ edited_point_pos = cpoint;
canvas_item_editor->get_viewport_control()->update();
- edited_point=1;
+ edited_point = 1;
return true;
} else {
-
- if (wip.size()>1 && xform.xform(wip[0]).distance_to(gpoint)<grab_treshold) {
+ if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_treshold) {
//wip closed
_wip_close(true);
return true;
- } else if (wip.size()>1 && xform.xform(wip[wip.size()-1]).distance_to(gpoint)<grab_treshold) {
- //wip closed
- _wip_close(false);
- return true;
+ } else if (wip.size() > 1 && xform.xform(wip[wip.size() - 1]).distance_to(gpoint) < grab_treshold) {
+ //wip closed
+ _wip_close(false);
+ return true;
} else {
- wip.push_back( cpoint );
- edited_point=wip.size();
+ wip.push_back(cpoint);
+ edited_point = wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && wip_active) {
_wip_close(true);
}
-
-
} break;
case MODE_EDIT: {
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (mb.mod.control) {
-
if (poly.size() < 3) {
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
+ undo_redo->add_undo_method(node->get_occluder_polygon().ptr(), "set_polygon", poly);
poly.push_back(cpoint);
- undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_occluder_polygon().ptr(), "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
//search edges
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 points[2] ={ xform.xform(poly[i]),
- xform.xform(poly[(i+1)%poly.size()]) };
+ Vector2 points[2] = { xform.xform(poly[i]),
+ xform.xform(poly[(i + 1) % poly.size()]) };
- Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
- if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
+ Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
+ if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos));
- edited_point=closest_idx+1;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos));
+ edited_point = closest_idx + 1;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
node->get_occluder_polygon()->set_polygon(Variant(poly));
canvas_item_editor->get_viewport_control()->update();
return true;
@@ -239,106 +224,95 @@ bool LightOccluder2DEditor::forward_gui_input(const InputEvent& p_event) {
//look for points to move
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- edited_point=closest_idx;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ edited_point = closest_idx;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
- if (edited_point!=-1) {
+ if (edited_point != -1) {
//apply
- ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
- poly[edited_point]=edited_point_pos;
+ ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
+ poly[edited_point] = edited_point_pos;
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
- undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",pre_move_edit);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_occluder_polygon().ptr(), "set_polygon", poly);
+ undo_redo->add_undo_method(node->get_occluder_polygon().ptr(), "set_polygon", pre_move_edit);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- edited_point=-1;
+ edited_point = -1;
return true;
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && edited_point == -1) {
-
-
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
-
+ if (closest_idx >= 0) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
- undo_redo->add_undo_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
+ undo_redo->add_undo_method(node->get_occluder_polygon().ptr(), "set_polygon", poly);
poly.remove(closest_idx);
- undo_redo->add_do_method(node->get_occluder_polygon().ptr(),"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_occluder_polygon().ptr(), "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
-
}
-
-
} break;
}
-
-
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {
+ if (edited_point != -1 && (wip_active || mm.button_mask & BUTTON_MASK_LEFT)) {
- Vector2 gpoint = Point2(mm.x,mm.y);
+ Vector2 gpoint = Point2(mm.x, mm.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
canvas_item_editor->get_viewport_control()->update();
-
}
} break;
@@ -356,111 +330,102 @@ void LightOccluder2DEditor::_canvas_draw() {
Vector<Vector2> poly;
if (wip_active)
- poly=wip;
+ poly = wip;
else
- poly=Variant(node->get_occluder_polygon()->get_polygon());
-
+ poly = Variant(node->get_occluder_polygon()->get_polygon());
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
-
- for(int i=0;i<poly.size();i++) {
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 p,p2;
- p = i==edited_point ? edited_point_pos : poly[i];
- if ((wip_active && i==poly.size()-1) || (((i+1)%poly.size())==edited_point))
- p2=edited_point_pos;
+ Vector2 p, p2;
+ p = i == edited_point ? edited_point_pos : poly[i];
+ if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point))
+ p2 = edited_point_pos;
else
- p2 = poly[(i+1)%poly.size()];
+ p2 = poly[(i + 1) % poly.size()];
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
- Color col=Color(1,0.3,0.1,0.8);
+ Color col = Color(1, 0.3, 0.1, 0.8);
- if (i==poly.size()-1 && (!node->get_occluder_polygon()->is_closed() || wip_active)) {
+ if (i == poly.size() - 1 && (!node->get_occluder_polygon()->is_closed() || wip_active)) {
} else {
- vpc->draw_line(point,next_point,col,2);
+ vpc->draw_line(point, next_point, col, 2);
}
- vpc->draw_texture(handle,point-handle->get_size()*0.5);
+ vpc->draw_texture(handle, point - handle->get_size() * 0.5);
}
}
-
-
void LightOccluder2DEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
- node=p_collision_polygon->cast_to<LightOccluder2D>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ node = p_collision_polygon->cast_to<LightOccluder2D>();
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
wip.clear();
- wip_active=false;
- edited_point=-1;
+ wip_active = false;
+ edited_point = -1;
canvas_item_editor->get_viewport_control()->update();
} else {
- node=NULL;
-
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ node = NULL;
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
}
-
}
-void LightOccluder2DEditor::_create_poly() {
+void LightOccluder2DEditor::_create_poly() {
if (!node)
return;
undo_redo->create_action(TTR("Create Occluder Polygon"));
- undo_redo->add_do_method(node,"set_occluder_polygon",Ref<OccluderPolygon2D>(memnew( OccluderPolygon2D)));
- undo_redo->add_undo_method(node,"set_occluder_polygon",Variant(REF()));
+ undo_redo->add_do_method(node, "set_occluder_polygon", Ref<OccluderPolygon2D>(memnew(OccluderPolygon2D)));
+ undo_redo->add_undo_method(node, "set_occluder_polygon", Variant(REF()));
undo_redo->commit_action();
}
void LightOccluder2DEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_option"),&LightOccluder2DEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&LightOccluder2DEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_node_removed"),&LightOccluder2DEditor::_node_removed);
- ClassDB::bind_method(D_METHOD("_create_poly"),&LightOccluder2DEditor::_create_poly);
-
+ ClassDB::bind_method(D_METHOD("_menu_option"), &LightOccluder2DEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &LightOccluder2DEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &LightOccluder2DEditor::_node_removed);
+ ClassDB::bind_method(D_METHOD("_create_poly"), &LightOccluder2DEditor::_create_poly);
}
-
LightOccluder2DEditor::LightOccluder2DEditor(EditorNode *p_editor) {
- node=NULL;
- canvas_item_editor=NULL;
- editor=p_editor;
+ node = NULL;
+ canvas_item_editor = NULL;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- add_child( memnew( VSeparator ));
- button_create = memnew( ToolButton );
+ add_child(memnew(VSeparator));
+ button_create = memnew(ToolButton);
add_child(button_create);
- button_create->connect("pressed",this,"_menu_option",varray(MODE_CREATE));
+ button_create->connect("pressed", this, "_menu_option", varray(MODE_CREATE));
button_create->set_toggle_mode(true);
button_create->set_tooltip(TTR("Create a new polygon from scratch."));
- button_edit = memnew( ToolButton );
+ button_edit = memnew(ToolButton);
add_child(button_edit);
- button_edit->connect("pressed",this,"_menu_option",varray(MODE_EDIT));
+ button_edit->connect("pressed", this, "_menu_option", varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
- button_edit->set_tooltip(TTR("Edit existing polygon:")+"\n"+TTR("LMB: Move Point.")+"\n"+TTR("Ctrl+LMB: Split Segment.")+"\n"+TTR("RMB: Erase Point."));
+ button_edit->set_tooltip(TTR("Edit existing polygon:") + "\n" + TTR("LMB: Move Point.") + "\n" + TTR("Ctrl+LMB: Split Segment.") + "\n" + TTR("RMB: Erase Point."));
- create_poly = memnew( ConfirmationDialog );
+ create_poly = memnew(ConfirmationDialog);
add_child(create_poly);
create_poly->get_ok()->set_text(TTR("Create"));
-
- //add_constant_override("separation",0);
+//add_constant_override("separation",0);
#if 0
options = memnew( MenuButton );
@@ -472,11 +437,9 @@ LightOccluder2DEditor::LightOccluder2DEditor(EditorNode *p_editor) {
#endif
mode = MODE_EDIT;
- wip_active=false;
-
+ wip_active = false;
}
-
void LightOccluder2DEditorPlugin::edit(Object *p_object) {
collision_polygon_editor->edit(p_object->cast_to<Node>());
@@ -496,23 +459,16 @@ void LightOccluder2DEditorPlugin::make_visible(bool p_visible) {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
-
}
LightOccluder2DEditorPlugin::LightOccluder2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- collision_polygon_editor = memnew( LightOccluder2DEditor(p_node) );
+ editor = p_node;
+ collision_polygon_editor = memnew(LightOccluder2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
-
-
-
}
-
-LightOccluder2DEditorPlugin::~LightOccluder2DEditorPlugin()
-{
+LightOccluder2DEditorPlugin::~LightOccluder2DEditorPlugin() {
}
-
diff --git a/editor/plugins/light_occluder_2d_editor_plugin.h b/editor/plugins/light_occluder_2d_editor_plugin.h
index 1f1c6e86eb..68e5e3f729 100644
--- a/editor/plugins/light_occluder_2d_editor_plugin.h
+++ b/editor/plugins/light_occluder_2d_editor_plugin.h
@@ -29,13 +29,11 @@
#ifndef LIGHT_OCCLUDER_2D_EDITOR_PLUGIN_H
#define LIGHT_OCCLUDER_2D_EDITOR_PLUGIN_H
-
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/light_occluder_2d.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -44,7 +42,7 @@ class CanvasItemEditor;
class LightOccluder2DEditor : public HBoxContainer {
- GDCLASS(LightOccluder2DEditor, HBoxContainer );
+ GDCLASS(LightOccluder2DEditor, HBoxContainer);
UndoRedo *undo_redo;
enum Mode {
@@ -82,24 +80,23 @@ protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
- Vector2 snap_point(const Vector2& p_point) const;
- bool forward_gui_input(const InputEvent& p_event);
+public:
+ Vector2 snap_point(const Vector2 &p_point) const;
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_collision_polygon);
LightOccluder2DEditor(EditorNode *p_editor);
};
class LightOccluder2DEditorPlugin : public EditorPlugin {
- GDCLASS( LightOccluder2DEditorPlugin, EditorPlugin );
+ GDCLASS(LightOccluder2DEditorPlugin, EditorPlugin);
LightOccluder2DEditor *collision_polygon_editor;
EditorNode *editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "LightOccluder2D"; }
bool has_main_screen() const { return false; }
@@ -109,7 +106,6 @@ public:
LightOccluder2DEditorPlugin(EditorNode *p_node);
~LightOccluder2DEditorPlugin();
-
};
#endif // LIGHT_OCCLUDER_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/line_2d_editor_plugin.cpp b/editor/plugins/line_2d_editor_plugin.cpp
index 4a0f90a2b4..b3afe0bb93 100644
--- a/editor/plugins/line_2d_editor_plugin.cpp
+++ b/editor/plugins/line_2d_editor_plugin.cpp
@@ -29,37 +29,33 @@
#include "line_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
+#include "os/file_access.h"
#include "os/keyboard.h"
-
//----------------------------------------------------------------------------
// Line2DEditor
//----------------------------------------------------------------------------
void Line2DEditor::_node_removed(Node *p_node) {
- if(p_node == node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
}
}
void Line2DEditor::_notification(int p_what) {
- switch(p_what) {
- case NOTIFICATION_VISIBILITY_CHANGED:
- // This widget is not a child but should have the same visibility state
- base_hb->set_visible(is_visible());
- break;
+ switch (p_what) {
+ case NOTIFICATION_VISIBILITY_CHANGED:
+ // This widget is not a child but should have the same visibility state
+ base_hb->set_visible(is_visible());
+ break;
}
}
Vector2 Line2DEditor::mouse_to_local_pos(Vector2 gpoint, bool alt) {
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- return !alt? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint))
- : node->get_global_transform().affine_inverse().xform(
- canvas_item_editor->snap_point(
- canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)) );
+ return !alt ? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint)) : node->get_global_transform().affine_inverse().xform(canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)));
}
int Line2DEditor::get_point_index_at(Vector2 gpos) {
@@ -68,9 +64,9 @@ int Line2DEditor::get_point_index_at(Vector2 gpos) {
real_t grab_treshold = EDITOR_DEF("poly_editor/point_grab_radius", 8);
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- for(int i = 0; i < node->get_point_count(); ++i) {
- Point2 p = xform.xform( node->get_point_pos(i) );
- if(gpos.distance_to(p) < grab_treshold) {
+ for (int i = 0; i < node->get_point_count(); ++i) {
+ Point2 p = xform.xform(node->get_point_pos(i));
+ if (gpos.distance_to(p) < grab_treshold) {
return i;
}
}
@@ -78,7 +74,7 @@ int Line2DEditor::get_point_index_at(Vector2 gpos) {
return -1;
}
-bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
+bool Line2DEditor::forward_gui_input(const InputEvent &p_event) {
if (!node)
return false;
@@ -86,25 +82,24 @@ bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
if (!node->is_visible())
return false;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &mb = p_event.mouse_button;
- Vector2 gpoint = Point2(mb.x,mb.y);
+ Vector2 gpoint = Point2(mb.x, mb.y);
Vector2 cpoint = mouse_to_local_pos(gpoint, mb.mod.alt);
- if(mb.pressed && _dragging == false) {
+ if (mb.pressed && _dragging == false) {
int i = get_point_index_at(gpoint);
- if(i != -1) {
+ if (i != -1) {
if (mb.button_index == BUTTON_LEFT && !mb.mod.shift && mode == MODE_EDIT) {
_dragging = true;
action_point = i;
moving_from = node->get_point_pos(i);
moving_screen_from = gpoint;
- }
- else if((mb.button_index == BUTTON_RIGHT && mode == MODE_EDIT) || (mb.button_index == BUTTON_LEFT && mode == MODE_DELETE)) {
+ } else if ((mb.button_index == BUTTON_RIGHT && mode == MODE_EDIT) || (mb.button_index == BUTTON_LEFT && mode == MODE_DELETE)) {
undo_redo->create_action(TTR("Remove Point from Line2D"));
undo_redo->add_do_method(node, "remove_point", i);
undo_redo->add_undo_method(node, "add_point", node->get_point_pos(i), i);
@@ -116,7 +111,7 @@ bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
}
}
- if(mb.pressed && mb.button_index == BUTTON_LEFT && ((mb.mod.command && mode == MODE_EDIT) || mode == MODE_CREATE)) {
+ if (mb.pressed && mb.button_index == BUTTON_LEFT && ((mb.mod.command && mode == MODE_EDIT) || mode == MODE_CREATE)) {
undo_redo->create_action(TTR("Add Point to Line2D"));
undo_redo->add_do_method(node, "add_point", cpoint);
@@ -126,7 +121,7 @@ bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
undo_redo->commit_action();
_dragging = true;
- action_point = node->get_point_count()-1;
+ action_point = node->get_point_count() - 1;
moving_from = node->get_point_pos(action_point);
moving_screen_from = gpoint;
@@ -135,7 +130,7 @@ bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
- if(!mb.pressed && mb.button_index == BUTTON_LEFT && _dragging) {
+ if (!mb.pressed && mb.button_index == BUTTON_LEFT && _dragging) {
undo_redo->create_action(TTR("Move Point in Line2D"));
undo_redo->add_do_method(node, "set_point_pos", action_point, cpoint);
undo_redo->add_undo_method(node, "set_point_pos", action_point, moving_from);
@@ -145,19 +140,17 @@ bool Line2DEditor::forward_gui_input(const InputEvent& p_event) {
_dragging = false;
return true;
}
- }
- break;
+ } break;
case InputEvent::MOUSE_MOTION: {
if (_dragging) {
const InputEventMouseMotion &mm = p_event.mouse_motion;
Vector2 cpoint = mouse_to_local_pos(Vector2(mm.x, mm.y), mm.mod.alt);
- node->set_point_pos(action_point,cpoint);
+ node->set_point_pos(action_point, cpoint);
canvas_item_editor->get_viewport_control()->update();
return true;
}
- }
- break;
+ } break;
}
return false;
@@ -178,7 +171,7 @@ void Line2DEditor::_canvas_draw() {
int len = node->get_point_count();
Control *vpc = canvas_item_editor->get_viewport_control();
- for(int i=0; i < len; ++i) {
+ for (int i = 0; i < len; ++i) {
Vector2 point = xform.xform(node->get_point_pos(i));
vpc->draw_texture_rect(handle, Rect2(point - handle_size * 0.5, handle_size), false);
}
@@ -201,8 +194,7 @@ void Line2DEditor::edit(Node *p_line2d) {
canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
if (!node->is_connected("visibility_changed", this, "_node_visibility_changed"))
node->connect("visibility_changed", this, "_node_visibility_changed");
- }
- else {
+ } else {
if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
// node may have been deleted at this point
@@ -219,7 +211,7 @@ void Line2DEditor::_bind_methods() {
}
void Line2DEditor::_mode_selected(int p_mode) {
- for(unsigned int i = 0; i < _MODE_COUNT; ++i) {
+ for (unsigned int i = 0; i < _MODE_COUNT; ++i) {
toolbar_buttons[i]->set_pressed(i == p_mode);
}
mode = Mode(p_mode);
@@ -233,41 +225,37 @@ Line2DEditor::Line2DEditor(EditorNode *p_editor) {
_dragging = false;
- base_hb = memnew( HBoxContainer );
+ base_hb = memnew(HBoxContainer);
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(base_hb);
- sep = memnew( VSeparator);
+ sep = memnew(VSeparator);
base_hb->add_child(sep);
{
- ToolButton * b = memnew(ToolButton);
+ ToolButton *b = memnew(ToolButton);
b->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveEdit", "EditorIcons"));
b->set_toggle_mode(true);
b->set_focus_mode(Control::FOCUS_NONE);
b->set_tooltip(
- TTR("Select Points")+"\n"
- + TTR("Shift+Drag: Select Control Points")+"\n"
- + keycode_get_string(KEY_MASK_CMD)
- + TTR("Click: Add Point")+"\n"
- + TTR("Right Click: Delete Point"));
+ TTR("Select Points") + "\n" + TTR("Shift+Drag: Select Control Points") + "\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Click: Add Point") + "\n" + TTR("Right Click: Delete Point"));
b->connect("pressed", this, "_mode_selected", varray(MODE_EDIT));
toolbar_buttons[MODE_EDIT] = b;
base_hb->add_child(b);
}
{
- ToolButton * b = memnew(ToolButton);
+ ToolButton *b = memnew(ToolButton);
b->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveCreate", "EditorIcons"));
b->set_toggle_mode(true);
b->set_focus_mode(Control::FOCUS_NONE);
- b->set_tooltip(TTR("Add Point (in empty space)")+"\n"+TTR("Split Segment (in line)"));
+ b->set_tooltip(TTR("Add Point (in empty space)") + "\n" + TTR("Split Segment (in line)"));
b->connect("pressed", this, "_mode_selected", varray(MODE_CREATE));
toolbar_buttons[MODE_CREATE] = b;
base_hb->add_child(b);
}
{
- ToolButton * b = memnew( ToolButton );
+ ToolButton *b = memnew(ToolButton);
b->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveDelete", "EditorIcons"));
b->set_toggle_mode(true);
b->set_focus_mode(Control::FOCUS_NONE);
@@ -297,15 +285,13 @@ bool Line2DEditorPlugin::handles(Object *p_object) const {
void Line2DEditorPlugin::make_visible(bool p_visible) {
line2d_editor->set_visible(p_visible);
- if(p_visible == false)
+ if (p_visible == false)
line2d_editor->edit(NULL);
}
Line2DEditorPlugin::Line2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- line2d_editor = memnew( Line2DEditor(p_node) );
+ editor = p_node;
+ line2d_editor = memnew(Line2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(line2d_editor);
line2d_editor->hide();
}
-
-
diff --git a/editor/plugins/line_2d_editor_plugin.h b/editor/plugins/line_2d_editor_plugin.h
index 6e0da7df38..6bade92da4 100644
--- a/editor/plugins/line_2d_editor_plugin.h
+++ b/editor/plugins/line_2d_editor_plugin.h
@@ -29,13 +29,12 @@
#ifndef LINE_2D_EDITOR_PLUGIN_H
#define LINE_2D_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
+#include "scene/2d/line_2d.h"
#include "scene/2d/path_2d.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
-#include "scene/2d/line_2d.h"
-
+#include "scene/gui/tool_button.h"
class CanvasItemEditor;
@@ -43,7 +42,7 @@ class Line2DEditor : public HBoxContainer {
GDCLASS(Line2DEditor, HBoxContainer)
public:
- bool forward_gui_input(const InputEvent& p_event);
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_line2d);
Line2DEditor(EditorNode *p_editor);
@@ -81,7 +80,7 @@ private:
};
Mode mode;
- ToolButton* toolbar_buttons[_MODE_COUNT];
+ ToolButton *toolbar_buttons[_MODE_COUNT];
bool _dragging;
int action_point;
@@ -90,13 +89,12 @@ private:
};
class Line2DEditorPlugin : public EditorPlugin {
- GDCLASS( Line2DEditorPlugin, EditorPlugin )
+ GDCLASS(Line2DEditorPlugin, EditorPlugin)
public:
virtual bool forward_canvas_gui_input(
- const Transform2D& p_canvas_xform,
- const InputEvent& p_event)
- {
+ const Transform2D &p_canvas_xform,
+ const InputEvent &p_event) {
return line2d_editor->forward_gui_input(p_event);
}
@@ -111,8 +109,6 @@ public:
private:
Line2DEditor *line2d_editor;
EditorNode *editor;
-
};
#endif // LINE_2D_EDITOR_PLUGIN_H
-
diff --git a/editor/plugins/material_editor_plugin.cpp b/editor/plugins/material_editor_plugin.cpp
index cdf7c70d39..8716349cb4 100644
--- a/editor/plugins/material_editor_plugin.cpp
+++ b/editor/plugins/material_editor_plugin.cpp
@@ -205,21 +205,23 @@ MaterialEditor::MaterialEditor() {
Vector3(x0 * zr0, z0, y0 *zr0)
};
- #define ADD_POINT(m_idx) \
- normals.push_back(v[m_idx]);\
- vertices.push_back(v[m_idx]*radius);\
- { Vector2 uv(Math::atan2(v[m_idx].x,v[m_idx].z),Math::atan2(-v[m_idx].y,v[m_idx].z));\
- uv/=Math_PI;\
- uv*=4.0;\
- uv=uv*0.5+Vector2(0.5,0.5);\
- uvs.push_back(uv);\
- }\
- { Vector3 t = tt.xform(v[m_idx]);\
- tangents.push_back(t.x);\
- tangents.push_back(t.y);\
- tangents.push_back(t.z);\
- tangents.push_back(1.0);\
- }
+#define ADD_POINT(m_idx) \
+ normals.push_back(v[m_idx]); \
+ vertices.push_back(v[m_idx] * radius); \
+ { \
+ Vector2 uv(Math::atan2(v[m_idx].x, v[m_idx].z), Math::atan2(-v[m_idx].y, v[m_idx].z)); \
+ uv /= Math_PI; \
+ uv *= 4.0; \
+ uv = uv * 0.5 + Vector2(0.5, 0.5); \
+ uvs.push_back(uv); \
+ } \
+ { \
+ Vector3 t = tt.xform(v[m_idx]); \
+ tangents.push_back(t.x); \
+ tangents.push_back(t.y); \
+ tangents.push_back(t.z); \
+ tangents.push_back(1.0); \
+ }
@@ -256,15 +258,16 @@ MaterialEditor::MaterialEditor() {
PoolVector<Vector3> uvs;
int vtx_idx=0;
- #define ADD_VTX(m_idx);\
- vertices.push_back( face_points[m_idx] );\
- normals.push_back( normal_points[m_idx] );\
- tangents.push_back( normal_points[m_idx][1] );\
- tangents.push_back( normal_points[m_idx][2] );\
- tangents.push_back( normal_points[m_idx][0] );\
- tangents.push_back( 1.0 );\
- uvs.push_back( Vector3(uv_points[m_idx*2+0],uv_points[m_idx*2+1],0) );\
- vtx_idx++;\
+#define ADD_VTX(m_idx) \
+ ; \
+ vertices.push_back(face_points[m_idx]); \
+ normals.push_back(normal_points[m_idx]); \
+ tangents.push_back(normal_points[m_idx][1]); \
+ tangents.push_back(normal_points[m_idx][2]); \
+ tangents.push_back(normal_points[m_idx][0]); \
+ tangents.push_back(1.0); \
+ uvs.push_back(Vector3(uv_points[m_idx * 2 + 0], uv_points[m_idx * 2 + 1], 0)); \
+ vtx_idx++;\
for (int i=0;i<6;i++) {
@@ -409,5 +412,4 @@ MaterialEditorPlugin::~MaterialEditorPlugin()
{
}
-
#endif
diff --git a/editor/plugins/material_editor_plugin.h b/editor/plugins/material_editor_plugin.h
index 604e7e61bd..30bed67a5e 100644
--- a/editor/plugins/material_editor_plugin.h
+++ b/editor/plugins/material_editor_plugin.h
@@ -29,12 +29,12 @@
#ifndef MATERIAL_EDITOR_PLUGIN_H
#define MATERIAL_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/resources/material.h"
+#include "editor/editor_plugin.h"
+#include "scene/3d/camera.h"
#include "scene/3d/light.h"
#include "scene/3d/mesh_instance.h"
-#include "scene/3d/camera.h"
+#include "scene/resources/material.h"
#if 0
class MaterialEditor : public Control {
diff --git a/editor/plugins/mesh_editor_plugin.h b/editor/plugins/mesh_editor_plugin.h
index 80504ae445..ec6d67e2f7 100644
--- a/editor/plugins/mesh_editor_plugin.h
+++ b/editor/plugins/mesh_editor_plugin.h
@@ -31,12 +31,12 @@
#if 0
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/resources/material.h"
+#include "editor/editor_plugin.h"
+#include "scene/3d/camera.h"
#include "scene/3d/light.h"
#include "scene/3d/mesh_instance.h"
-#include "scene/3d/camera.h"
+#include "scene/resources/material.h"
class MeshEditor : public Control {
diff --git a/editor/plugins/mesh_instance_editor_plugin.cpp b/editor/plugins/mesh_instance_editor_plugin.cpp
index 322e212534..972e92e51e 100644
--- a/editor/plugins/mesh_instance_editor_plugin.cpp
+++ b/editor/plugins/mesh_instance_editor_plugin.cpp
@@ -28,27 +28,23 @@
/*************************************************************************/
#include "mesh_instance_editor_plugin.h"
-#include "scene/3d/physics_body.h"
#include "scene/3d/body_shape.h"
-#include "scene/gui/box_container.h"
#include "scene/3d/navigation_mesh.h"
+#include "scene/3d/physics_body.h"
+#include "scene/gui/box_container.h"
#include "spatial_editor_plugin.h"
void MeshInstanceEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
options->hide();
}
-
}
-
-
void MeshInstanceEditor::edit(MeshInstance *p_mesh) {
- node=p_mesh;
-
+ node = p_mesh;
}
void MeshInstanceEditor::_menu_option(int p_option) {
@@ -60,39 +56,39 @@ void MeshInstanceEditor::_menu_option(int p_option) {
return;
}
- switch(p_option) {
+ switch (p_option) {
case MENU_OPTION_CREATE_STATIC_TRIMESH_BODY:
case MENU_OPTION_CREATE_STATIC_CONVEX_BODY: {
- bool trimesh_shape = (p_option==MENU_OPTION_CREATE_STATIC_TRIMESH_BODY);
+ bool trimesh_shape = (p_option == MENU_OPTION_CREATE_STATIC_TRIMESH_BODY);
EditorSelection *editor_selection = EditorNode::get_singleton()->get_editor_selection();
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
if (selection.empty()) {
Ref<Shape> shape = trimesh_shape ? mesh->create_trimesh_shape() : mesh->create_convex_shape();
if (shape.is_null())
return;
- CollisionShape *cshape = memnew( CollisionShape );
+ CollisionShape *cshape = memnew(CollisionShape);
cshape->set_shape(shape);
- StaticBody *body = memnew( StaticBody );
+ StaticBody *body = memnew(StaticBody);
body->add_child(cshape);
- Node *owner = node==get_tree()->get_edited_scene_root() ? node : node->get_owner();
+ Node *owner = node == get_tree()->get_edited_scene_root() ? node : node->get_owner();
if (trimesh_shape)
ur->create_action(TTR("Create Static Trimesh Body"));
else
ur->create_action(TTR("Create Static Convex Body"));
- ur->add_do_method(node,"add_child",body);
- ur->add_do_method(body,"set_owner",owner);
- ur->add_do_method(cshape,"set_owner",owner);
+ ur->add_do_method(node, "add_child", body);
+ ur->add_do_method(body, "set_owner", owner);
+ ur->add_do_method(cshape, "set_owner", owner);
ur->add_do_reference(body);
- ur->add_undo_method(node,"remove_child",body);
+ ur->add_undo_method(node, "remove_child", body);
ur->commit_action();
return;
}
@@ -102,7 +98,7 @@ void MeshInstanceEditor::_menu_option(int p_option) {
else
ur->create_action(TTR("Create Static Convex Body"));
- for (List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
MeshInstance *instance = E->get()->cast_to<MeshInstance>();
if (!instance)
@@ -116,18 +112,18 @@ void MeshInstanceEditor::_menu_option(int p_option) {
if (shape.is_null())
continue;
- CollisionShape *cshape = memnew( CollisionShape );
+ CollisionShape *cshape = memnew(CollisionShape);
cshape->set_shape(shape);
- StaticBody *body = memnew( StaticBody );
+ StaticBody *body = memnew(StaticBody);
body->add_child(cshape);
- Node *owner = instance==get_tree()->get_edited_scene_root() ? instance : instance->get_owner();
+ Node *owner = instance == get_tree()->get_edited_scene_root() ? instance : instance->get_owner();
- ur->add_do_method(instance,"add_child",body);
- ur->add_do_method(body,"set_owner",owner);
- ur->add_do_method(cshape,"set_owner",owner);
+ ur->add_do_method(instance, "add_child", body);
+ ur->add_do_method(body, "set_owner", owner);
+ ur->add_do_method(cshape, "set_owner", owner);
ur->add_do_reference(body);
- ur->add_undo_method(instance,"remove_child",body);
+ ur->add_undo_method(instance, "remove_child", body);
}
ur->commit_action();
@@ -137,22 +133,22 @@ void MeshInstanceEditor::_menu_option(int p_option) {
case MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE:
case MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE: {
- if (node==get_tree()->get_edited_scene_root()) {
+ if (node == get_tree()->get_edited_scene_root()) {
err_dialog->set_text(TTR("This doesn't work on scene root!"));
err_dialog->popup_centered_minsize();
return;
}
- bool trimesh_shape = (p_option==MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
+ bool trimesh_shape = (p_option == MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
Ref<Shape> shape = trimesh_shape ? mesh->create_trimesh_shape() : mesh->create_convex_shape();
if (shape.is_null())
return;
- CollisionShape *cshape = memnew( CollisionShape );
+ CollisionShape *cshape = memnew(CollisionShape);
cshape->set_shape(shape);
- Node *owner = node->get_owner();
+ Node *owner = node->get_owner();
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
@@ -161,36 +157,36 @@ void MeshInstanceEditor::_menu_option(int p_option) {
else
ur->create_action(TTR("Create Convex Shape"));
- ur->add_do_method(node->get_parent(),"add_child",cshape);
- ur->add_do_method(node->get_parent(),"move_child",cshape,node->get_index()+1);
- ur->add_do_method(cshape,"set_owner",owner);
+ ur->add_do_method(node->get_parent(), "add_child", cshape);
+ ur->add_do_method(node->get_parent(), "move_child", cshape, node->get_index() + 1);
+ ur->add_do_method(cshape, "set_owner", owner);
ur->add_do_reference(cshape);
- ur->add_undo_method(node->get_parent(),"remove_child",cshape);
+ ur->add_undo_method(node->get_parent(), "remove_child", cshape);
ur->commit_action();
} break;
case MENU_OPTION_CREATE_NAVMESH: {
- Ref<NavigationMesh> nmesh = memnew( NavigationMesh );
+ Ref<NavigationMesh> nmesh = memnew(NavigationMesh);
if (nmesh.is_null())
return;
nmesh->create_from_mesh(mesh);
- NavigationMeshInstance *nmi = memnew( NavigationMeshInstance );
+ NavigationMeshInstance *nmi = memnew(NavigationMeshInstance);
nmi->set_navigation_mesh(nmesh);
- Node *owner = node==get_tree()->get_edited_scene_root() ? node : node->get_owner();
+ Node *owner = node == get_tree()->get_edited_scene_root() ? node : node->get_owner();
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Navigation Mesh"));
- ur->add_do_method(node,"add_child",nmi);
- ur->add_do_method(nmi,"set_owner",owner);
+ ur->add_do_method(node, "add_child", nmi);
+ ur->add_do_method(nmi, "set_owner", owner);
ur->add_do_reference(nmi);
- ur->add_undo_method(node,"remove_child",nmi);
+ ur->add_undo_method(node, "remove_child", nmi);
ur->commit_action();
} break;
@@ -199,7 +195,6 @@ void MeshInstanceEditor::_menu_option(int p_option) {
outline_dialog->popup_centered(Vector2(200, 90));
} break;
}
-
}
void MeshInstanceEditor::_create_outline_mesh() {
@@ -225,76 +220,73 @@ void MeshInstanceEditor::_create_outline_mesh() {
return;
}
- MeshInstance *mi = memnew( MeshInstance );
+ MeshInstance *mi = memnew(MeshInstance);
mi->set_mesh(mesho);
- Node *owner=node->get_owner();
- if (get_tree()->get_edited_scene_root()==node) {
- owner=node;
+ Node *owner = node->get_owner();
+ if (get_tree()->get_edited_scene_root() == node) {
+ owner = node;
}
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action(TTR("Create Outline"));
- ur->add_do_method(node,"add_child",mi);
- ur->add_do_method(mi,"set_owner",owner);
+ ur->add_do_method(node, "add_child", mi);
+ ur->add_do_method(mi, "set_owner", owner);
ur->add_do_reference(mi);
- ur->add_undo_method(node,"remove_child",mi);
+ ur->add_undo_method(node, "remove_child", mi);
ur->commit_action();
}
void MeshInstanceEditor::_bind_methods() {
- ClassDB::bind_method("_menu_option",&MeshInstanceEditor::_menu_option);
- ClassDB::bind_method("_create_outline_mesh",&MeshInstanceEditor::_create_outline_mesh);
+ ClassDB::bind_method("_menu_option", &MeshInstanceEditor::_menu_option);
+ ClassDB::bind_method("_create_outline_mesh", &MeshInstanceEditor::_create_outline_mesh);
}
MeshInstanceEditor::MeshInstanceEditor() {
-
- options = memnew( MenuButton );
+ options = memnew(MenuButton);
SpatialEditor::get_singleton()->add_control_to_menu_panel(options);
options->set_text(TTR("Mesh"));
- options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MeshInstance","EditorIcons"));
+ options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MeshInstance", "EditorIcons"));
- options->get_popup()->add_item(TTR("Create Trimesh Static Body"),MENU_OPTION_CREATE_STATIC_TRIMESH_BODY);
- options->get_popup()->add_item(TTR("Create Convex Static Body"),MENU_OPTION_CREATE_STATIC_CONVEX_BODY);
+ options->get_popup()->add_item(TTR("Create Trimesh Static Body"), MENU_OPTION_CREATE_STATIC_TRIMESH_BODY);
+ options->get_popup()->add_item(TTR("Create Convex Static Body"), MENU_OPTION_CREATE_STATIC_CONVEX_BODY);
options->get_popup()->add_separator();
- options->get_popup()->add_item(TTR("Create Trimesh Collision Sibling"),MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
- options->get_popup()->add_item(TTR("Create Convex Collision Sibling"),MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE);
+ options->get_popup()->add_item(TTR("Create Trimesh Collision Sibling"), MENU_OPTION_CREATE_TRIMESH_COLLISION_SHAPE);
+ options->get_popup()->add_item(TTR("Create Convex Collision Sibling"), MENU_OPTION_CREATE_CONVEX_COLLISION_SHAPE);
options->get_popup()->add_separator();
- options->get_popup()->add_item(TTR("Create Navigation Mesh"),MENU_OPTION_CREATE_NAVMESH);
+ options->get_popup()->add_item(TTR("Create Navigation Mesh"), MENU_OPTION_CREATE_NAVMESH);
options->get_popup()->add_separator();
- options->get_popup()->add_item(TTR("Create Outline Mesh.."),MENU_OPTION_CREATE_OUTLINE_MESH);
+ options->get_popup()->add_item(TTR("Create Outline Mesh.."), MENU_OPTION_CREATE_OUTLINE_MESH);
- options->get_popup()->connect("id_pressed", this,"_menu_option");
+ options->get_popup()->connect("id_pressed", this, "_menu_option");
- outline_dialog = memnew( ConfirmationDialog );
+ outline_dialog = memnew(ConfirmationDialog);
outline_dialog->set_title(TTR("Create Outline Mesh"));
outline_dialog->get_ok()->set_text(TTR("Create"));
- VBoxContainer *outline_dialog_vbc = memnew( VBoxContainer );
+ VBoxContainer *outline_dialog_vbc = memnew(VBoxContainer);
outline_dialog->add_child(outline_dialog_vbc);
//outline_dialog->set_child_rect(outline_dialog_vbc);
- outline_size = memnew( SpinBox );
+ outline_size = memnew(SpinBox);
outline_size->set_min(0.001);
outline_size->set_max(1024);
outline_size->set_step(0.001);
outline_size->set_value(0.05);
- outline_dialog_vbc->add_margin_child(TTR("Outline Size:"),outline_size);
+ outline_dialog_vbc->add_margin_child(TTR("Outline Size:"), outline_size);
add_child(outline_dialog);
- outline_dialog->connect("confirmed",this,"_create_outline_mesh");
+ outline_dialog->connect("confirmed", this, "_create_outline_mesh");
- err_dialog = memnew( AcceptDialog );
+ err_dialog = memnew(AcceptDialog);
add_child(err_dialog);
-
}
-
void MeshInstanceEditorPlugin::edit(Object *p_object) {
mesh_editor->edit(p_object->cast_to<MeshInstance>());
@@ -314,21 +306,16 @@ void MeshInstanceEditorPlugin::make_visible(bool p_visible) {
mesh_editor->options->hide();
mesh_editor->edit(NULL);
}
-
}
MeshInstanceEditorPlugin::MeshInstanceEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- mesh_editor = memnew( MeshInstanceEditor );
+ editor = p_node;
+ mesh_editor = memnew(MeshInstanceEditor);
editor->get_viewport()->add_child(mesh_editor);
mesh_editor->options->hide();
}
-
-MeshInstanceEditorPlugin::~MeshInstanceEditorPlugin()
-{
+MeshInstanceEditorPlugin::~MeshInstanceEditorPlugin() {
}
-
-
diff --git a/editor/plugins/mesh_instance_editor_plugin.h b/editor/plugins/mesh_instance_editor_plugin.h
index de5be2fbbb..54d42d1a01 100644
--- a/editor/plugins/mesh_instance_editor_plugin.h
+++ b/editor/plugins/mesh_instance_editor_plugin.h
@@ -29,17 +29,14 @@
#ifndef MESH_INSTANCE_EDITOR_PLUGIN_H
#define MESH_INSTANCE_EDITOR_PLUGIN_H
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/mesh_instance.h"
#include "scene/gui/spin_box.h"
-
class MeshInstanceEditor : public Node {
- GDCLASS(MeshInstanceEditor, Node );
-
+ GDCLASS(MeshInstanceEditor, Node);
enum Menu {
@@ -63,26 +60,25 @@ class MeshInstanceEditor : public Node {
void _menu_option(int p_option);
void _create_outline_mesh();
-friend class MeshInstanceEditorPlugin;
+ friend class MeshInstanceEditorPlugin;
protected:
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
+public:
void edit(MeshInstance *p_mesh);
MeshInstanceEditor();
};
class MeshInstanceEditorPlugin : public EditorPlugin {
- GDCLASS( MeshInstanceEditorPlugin, EditorPlugin );
+ GDCLASS(MeshInstanceEditorPlugin, EditorPlugin);
MeshInstanceEditor *mesh_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "MeshInstance"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -91,7 +87,6 @@ public:
MeshInstanceEditorPlugin(EditorNode *p_node);
~MeshInstanceEditorPlugin();
-
};
#endif // MESH_EDITOR_PLUGIN_H
diff --git a/editor/plugins/multimesh_editor_plugin.cpp b/editor/plugins/multimesh_editor_plugin.cpp
index 6259ddf473..126927480a 100644
--- a/editor/plugins/multimesh_editor_plugin.cpp
+++ b/editor/plugins/multimesh_editor_plugin.cpp
@@ -28,29 +28,26 @@
/*************************************************************************/
#include "multimesh_editor_plugin.h"
-#include "scene/gui/box_container.h"
#include "scene/3d/mesh_instance.h"
+#include "scene/gui/box_container.h"
#include "spatial_editor_plugin.h"
void MultiMeshEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
}
-
}
-
void MultiMeshEditor::_populate() {
- if(!node)
+ if (!node)
return;
-
Ref<Mesh> mesh;
- if (mesh_source->get_text()=="") {
+ if (mesh_source->get_text() == "") {
Ref<MultiMesh> multimesh;
multimesh = node->get_multimesh();
@@ -88,7 +85,7 @@ void MultiMeshEditor::_populate() {
return;
}
- mesh=ms_instance->get_mesh();
+ mesh = ms_instance->get_mesh();
if (mesh.is_null()) {
@@ -96,10 +93,9 @@ void MultiMeshEditor::_populate() {
err_dialog->popup_centered_minsize();
return;
}
-
}
- if (surface_source->get_text()=="") {
+ if (surface_source->get_text() == "") {
err_dialog->set_text(TTR("No surface source specified."));
err_dialog->popup_centered_minsize();
@@ -128,7 +124,7 @@ void MultiMeshEditor::_populate() {
PoolVector<Face3> geometry = ss_instance->get_faces(VisualInstance::FACES_SOLID);
- if (geometry.size()==0) {
+ if (geometry.size() == 0) {
err_dialog->set_text(TTR("Surface source is invalid (no faces)."));
err_dialog->popup_centered_minsize();
@@ -140,14 +136,12 @@ void MultiMeshEditor::_populate() {
int gc = geometry.size();
PoolVector<Face3>::Write w = geometry.write();
- for(int i=0;i<gc;i++) {
- for(int j=0;j<3;j++) {
- w[i].vertex[j] = geom_xform.xform( w[i].vertex[j] );
+ for (int i = 0; i < gc; i++) {
+ for (int j = 0; j < 3; j++) {
+ w[i].vertex[j] = geom_xform.xform(w[i].vertex[j]);
}
}
-
-
w = PoolVector<Face3>::Write();
#if 0
node->get_multimesh()->set_instance_count(populate_amount->get_val());
@@ -167,34 +161,31 @@ void MultiMeshEditor::_populate() {
#endif
PoolVector<Face3> faces = geometry;
ERR_EXPLAIN(TTR("Parent has no solid faces to populate."));
- int facecount=faces.size();
+ int facecount = faces.size();
ERR_FAIL_COND(!facecount);
PoolVector<Face3>::Read r = faces.read();
-
-
- float area_accum=0;
- Map<float,int> triangle_area_map;
- for(int i=0;i<facecount;i++) {
+ float area_accum = 0;
+ Map<float, int> triangle_area_map;
+ for (int i = 0; i < facecount; i++) {
float area = r[i].get_area();
- if (area<CMP_EPSILON)
+ if (area < CMP_EPSILON)
continue;
- triangle_area_map[area_accum]=i;
- area_accum+=area;
+ triangle_area_map[area_accum] = i;
+ area_accum += area;
}
ERR_EXPLAIN(TTR("Couldn't map area."));
- ERR_FAIL_COND(triangle_area_map.size()==0);
+ ERR_FAIL_COND(triangle_area_map.size() == 0);
ERR_EXPLAIN(TTR("Couldn't map area."));
- ERR_FAIL_COND(area_accum==0);
-
+ ERR_FAIL_COND(area_accum == 0);
- Ref<MultiMesh> multimesh = memnew( MultiMesh );
+ Ref<MultiMesh> multimesh = memnew(MultiMesh);
multimesh->set_mesh(mesh);
- int instance_count=populate_amount->get_value();
+ int instance_count = populate_amount->get_value();
multimesh->set_transform_format(MultiMesh::TRANSFORM_3D);
multimesh->set_color_format(MultiMesh::COLOR_NONE);
@@ -207,21 +198,21 @@ void MultiMeshEditor::_populate() {
int axis = populate_axis->get_selected();
Transform axis_xform;
- if (axis==Vector3::AXIS_Z) {
- axis_xform.rotate(Vector3(1,0,0),-Math_PI*0.5);
+ if (axis == Vector3::AXIS_Z) {
+ axis_xform.rotate(Vector3(1, 0, 0), -Math_PI * 0.5);
}
- if (axis==Vector3::AXIS_X) {
- axis_xform.rotate(Vector3(0,0,1),-Math_PI*0.5);
+ if (axis == Vector3::AXIS_X) {
+ axis_xform.rotate(Vector3(0, 0, 1), -Math_PI * 0.5);
}
- for(int i=0;i<instance_count;i++) {
+ for (int i = 0; i < instance_count; i++) {
- float areapos = Math::random(0.0f,area_accum);
+ float areapos = Math::random(0.0f, area_accum);
- Map<float,int>::Element *E = triangle_area_map.find_closest(areapos);
+ Map<float, int>::Element *E = triangle_area_map.find_closest(areapos);
ERR_FAIL_COND(!E)
int index = E->get();
- ERR_FAIL_INDEX(index,facecount);
+ ERR_FAIL_INDEX(index, facecount);
// ok FINALLY get face
Face3 face = r[index];
@@ -229,41 +220,33 @@ void MultiMeshEditor::_populate() {
Vector3 pos = face.get_random_point_inside();
Vector3 normal = face.get_plane().normal;
- Vector3 op_axis = (face.vertex[0]-face.vertex[1]).normalized();
+ Vector3 op_axis = (face.vertex[0] - face.vertex[1]).normalized();
Transform xform;
- xform.set_look_at(pos, pos+op_axis,normal);
+ xform.set_look_at(pos, pos + op_axis, normal);
xform = xform * axis_xform;
-
Basis post_xform;
- post_xform.rotate(xform.basis.get_axis(1),-Math::random(-_rotate_random,_rotate_random)*Math_PI);
- post_xform.rotate(xform.basis.get_axis(2),-Math::random(-_tilt_random,_tilt_random)*Math_PI);
- post_xform.rotate(xform.basis.get_axis(0),-Math::random(-_tilt_random,_tilt_random)*Math_PI);
+ post_xform.rotate(xform.basis.get_axis(1), -Math::random(-_rotate_random, _rotate_random) * Math_PI);
+ post_xform.rotate(xform.basis.get_axis(2), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
+ post_xform.rotate(xform.basis.get_axis(0), -Math::random(-_tilt_random, _tilt_random) * Math_PI);
xform.basis = post_xform * xform.basis;
//xform.basis.orthonormalize();
+ xform.basis.scale(Vector3(1, 1, 1) * (_scale + Math::random(-_scale_random, _scale_random)));
- xform.basis.scale(Vector3(1,1,1)*(_scale+Math::random(-_scale_random,_scale_random)));
-
-
- multimesh->set_instance_transform(i,xform);
-
+ multimesh->set_instance_transform(i, xform);
}
-
-
node->set_multimesh(multimesh);
-
}
-void MultiMeshEditor::_browsed(const NodePath& p_path) {
-
+void MultiMeshEditor::_browsed(const NodePath &p_path) {
- NodePath path = node->get_path_to( get_node(p_path) );
+ NodePath path = node->get_path_to(get_node(p_path));
if (browsing_source)
mesh_source->set_text(path);
@@ -273,14 +256,11 @@ void MultiMeshEditor::_browsed(const NodePath& p_path) {
void MultiMeshEditor::_menu_option(int p_option) {
-
- switch(p_option) {
-
+ switch (p_option) {
case MENU_OPTION_POPULATE: {
- if (_last_pp_node!=node) {
-
+ if (_last_pp_node != node) {
surface_source->set_text("..");
mesh_source->set_text("..");
@@ -291,25 +271,23 @@ void MultiMeshEditor::_menu_option(int p_option) {
populate_scale->set_value(1);
populate_amount->set_value(128);
- _last_pp_node=node;
+ _last_pp_node = node;
}
- populate_dialog->popup_centered(Size2(250,380));
+ populate_dialog->popup_centered(Size2(250, 380));
} break;
}
}
-
void MultiMeshEditor::edit(MultiMeshInstance *p_multimesh) {
- node=p_multimesh;
-
+ node = p_multimesh;
}
void MultiMeshEditor::_browse(bool p_source) {
- browsing_source=p_source;
- std->get_scene_tree()->set_marked(node,false);
+ browsing_source = p_source;
+ std->get_scene_tree()->set_marked(node, false);
std->popup_centered_ratio();
if (p_source)
std->set_title(TTR("Select a Source Mesh:"));
@@ -319,113 +297,108 @@ void MultiMeshEditor::_browse(bool p_source) {
void MultiMeshEditor::_bind_methods() {
- ClassDB::bind_method("_menu_option",&MultiMeshEditor::_menu_option);
- ClassDB::bind_method("_populate",&MultiMeshEditor::_populate);
- ClassDB::bind_method("_browsed",&MultiMeshEditor::_browsed);
- ClassDB::bind_method("_browse",&MultiMeshEditor::_browse);
+ ClassDB::bind_method("_menu_option", &MultiMeshEditor::_menu_option);
+ ClassDB::bind_method("_populate", &MultiMeshEditor::_populate);
+ ClassDB::bind_method("_browsed", &MultiMeshEditor::_browsed);
+ ClassDB::bind_method("_browse", &MultiMeshEditor::_browse);
}
MultiMeshEditor::MultiMeshEditor() {
-
- options = memnew( MenuButton );
+ options = memnew(MenuButton);
SpatialEditor::get_singleton()->add_control_to_menu_panel(options);
options->set_text("MultiMesh");
- options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MultiMeshInstance","EditorIcons"));
+ options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("MultiMeshInstance", "EditorIcons"));
options->get_popup()->add_item(TTR("Populate Surface"));
- options->get_popup()->connect("id_pressed", this,"_menu_option");
+ options->get_popup()->connect("id_pressed", this, "_menu_option");
- populate_dialog = memnew( ConfirmationDialog );
+ populate_dialog = memnew(ConfirmationDialog);
populate_dialog->set_title(TTR("Populate MultiMesh"));
add_child(populate_dialog);
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
populate_dialog->add_child(vbc);
//populate_dialog->set_child_rect(vbc);
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
- surface_source = memnew( LineEdit );
+ surface_source = memnew(LineEdit);
hbc->add_child(surface_source);
surface_source->set_h_size_flags(SIZE_EXPAND_FILL);
- Button *b = memnew( Button );
+ Button *b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
- b->connect("pressed",this,"_browse",make_binds(false));
+ b->connect("pressed", this, "_browse", make_binds(false));
- vbc->add_margin_child(TTR("Target Surface:"),hbc);
+ vbc->add_margin_child(TTR("Target Surface:"), hbc);
- hbc = memnew( HBoxContainer );
- mesh_source = memnew( LineEdit );
+ hbc = memnew(HBoxContainer);
+ mesh_source = memnew(LineEdit);
hbc->add_child(mesh_source);
mesh_source->set_h_size_flags(SIZE_EXPAND_FILL);
- b = memnew( Button );
+ b = memnew(Button);
hbc->add_child(b);
b->set_text("..");
- vbc->add_margin_child(TTR("Source Mesh:"),hbc);
- b->connect("pressed",this,"_browse",make_binds(true));
+ vbc->add_margin_child(TTR("Source Mesh:"), hbc);
+ b->connect("pressed", this, "_browse", make_binds(true));
-
- populate_axis = memnew( OptionButton );
+ populate_axis = memnew(OptionButton);
populate_axis->add_item(TTR("X-Axis"));
populate_axis->add_item(TTR("Y-Axis"));
populate_axis->add_item(TTR("Z-Axis"));
populate_axis->select(2);
- vbc->add_margin_child(TTR("Mesh Up Axis:"),populate_axis);
+ vbc->add_margin_child(TTR("Mesh Up Axis:"), populate_axis);
- populate_rotate_random = memnew( HSlider );
+ populate_rotate_random = memnew(HSlider);
populate_rotate_random->set_max(1);
populate_rotate_random->set_step(0.01);
- vbc->add_margin_child(TTR("Random Rotation:"),populate_rotate_random);
+ vbc->add_margin_child(TTR("Random Rotation:"), populate_rotate_random);
- populate_tilt_random = memnew( HSlider );
+ populate_tilt_random = memnew(HSlider);
populate_tilt_random->set_max(1);
populate_tilt_random->set_step(0.01);
- vbc->add_margin_child(TTR("Random Tilt:"),populate_tilt_random);
-
+ vbc->add_margin_child(TTR("Random Tilt:"), populate_tilt_random);
- populate_scale_random = memnew( SpinBox );
+ populate_scale_random = memnew(SpinBox);
populate_scale_random->set_min(0);
populate_scale_random->set_max(1);
populate_scale_random->set_value(0);
populate_scale_random->set_step(0.01);
- vbc->add_margin_child(TTR("Random Scale:"),populate_scale_random);
+ vbc->add_margin_child(TTR("Random Scale:"), populate_scale_random);
- populate_scale = memnew( SpinBox );
+ populate_scale = memnew(SpinBox);
populate_scale->set_min(0.001);
populate_scale->set_max(4096);
populate_scale->set_value(1);
populate_scale->set_step(0.01);
- vbc->add_margin_child(TTR("Scale:"),populate_scale);
+ vbc->add_margin_child(TTR("Scale:"), populate_scale);
-
- populate_amount = memnew( SpinBox );
- populate_amount->set_anchor(MARGIN_RIGHT,ANCHOR_END);
- populate_amount->set_begin( Point2(20,232));
- populate_amount->set_end( Point2(5,237));
+ populate_amount = memnew(SpinBox);
+ populate_amount->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ populate_amount->set_begin(Point2(20, 232));
+ populate_amount->set_end(Point2(5, 237));
populate_amount->set_min(1);
populate_amount->set_max(65536);
populate_amount->set_value(128);
- vbc->add_margin_child(TTR("Amount:"),populate_amount);
+ vbc->add_margin_child(TTR("Amount:"), populate_amount);
populate_dialog->get_ok()->set_text(TTR("Populate"));
- populate_dialog->get_ok()->connect("pressed", this,"_populate");
- std = memnew( SceneTreeDialog );
+ populate_dialog->get_ok()->connect("pressed", this, "_populate");
+ std = memnew(SceneTreeDialog);
populate_dialog->add_child(std);
- std->connect("selected",this,"_browsed");
+ std->connect("selected", this, "_browsed");
- _last_pp_node=NULL;
+ _last_pp_node = NULL;
- err_dialog = memnew( AcceptDialog );
+ err_dialog = memnew(AcceptDialog);
add_child(err_dialog);
}
-
void MultiMeshEditorPlugin::edit(Object *p_object) {
multimesh_editor->edit(p_object->cast_to<MultiMeshInstance>());
@@ -445,21 +418,16 @@ void MultiMeshEditorPlugin::make_visible(bool p_visible) {
multimesh_editor->options->hide();
multimesh_editor->edit(NULL);
}
-
}
MultiMeshEditorPlugin::MultiMeshEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- multimesh_editor = memnew( MultiMeshEditor );
+ editor = p_node;
+ multimesh_editor = memnew(MultiMeshEditor);
editor->get_viewport()->add_child(multimesh_editor);
multimesh_editor->options->hide();
}
-
-MultiMeshEditorPlugin::~MultiMeshEditorPlugin()
-{
+MultiMeshEditorPlugin::~MultiMeshEditorPlugin() {
}
-
-
diff --git a/editor/plugins/multimesh_editor_plugin.h b/editor/plugins/multimesh_editor_plugin.h
index a97b3758a1..eb46733082 100644
--- a/editor/plugins/multimesh_editor_plugin.h
+++ b/editor/plugins/multimesh_editor_plugin.h
@@ -29,8 +29,8 @@
#ifndef MULTIMESH_EDITOR_PLUGIN_H
#define MULTIMESH_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/multimesh_instance.h"
#include "scene/gui/spin_box.h"
@@ -40,12 +40,12 @@
class MultiMeshEditor : public Control {
- GDCLASS(MultiMeshEditor, Control );
+ GDCLASS(MultiMeshEditor, Control);
-friend class MultiMeshEditorPlugin;
+ friend class MultiMeshEditorPlugin;
AcceptDialog *err_dialog;
- MenuButton * options;
+ MenuButton *options;
MultiMeshInstance *_last_pp_node;
bool browsing_source;
@@ -70,7 +70,7 @@ friend class MultiMeshEditorPlugin;
MENU_OPTION_POPULATE
};
- void _browsed(const NodePath& p_path);
+ void _browsed(const NodePath &p_path);
void _menu_option(int);
void _populate();
void _browse(bool p_source);
@@ -78,21 +78,20 @@ friend class MultiMeshEditorPlugin;
protected:
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
+public:
void edit(MultiMeshInstance *p_multimesh);
MultiMeshEditor();
};
class MultiMeshEditorPlugin : public EditorPlugin {
- GDCLASS( MultiMeshEditorPlugin, EditorPlugin );
+ GDCLASS(MultiMeshEditorPlugin, EditorPlugin);
MultiMeshEditor *multimesh_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "MultiMesh"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -101,7 +100,6 @@ public:
MultiMeshEditorPlugin(EditorNode *p_node);
~MultiMeshEditorPlugin();
-
};
#endif // MULTIMESH_EDITOR_PLUGIN_H
diff --git a/editor/plugins/navigation_polygon_editor_plugin.cpp b/editor/plugins/navigation_polygon_editor_plugin.cpp
index 654afb754e..e5b2594872 100644
--- a/editor/plugins/navigation_polygon_editor_plugin.cpp
+++ b/editor/plugins/navigation_polygon_editor_plugin.cpp
@@ -29,372 +29,342 @@
#include "navigation_polygon_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
+#include "os/file_access.h"
void NavigationPolygonEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
- button_create->set_icon( get_icon("Edit","EditorIcons"));
- button_edit->set_icon( get_icon("MovePoint","EditorIcons"));
+ button_create->set_icon(get_icon("Edit", "EditorIcons"));
+ button_edit->set_icon(get_icon("MovePoint", "EditorIcons"));
button_edit->set_pressed(true);
- get_tree()->connect("node_removed",this,"_node_removed");
- create_nav->connect("confirmed",this,"_create_nav");
+ get_tree()->connect("node_removed", this, "_node_removed");
+ create_nav->connect("confirmed", this, "_create_nav");
} break;
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void NavigationPolygonEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
canvas_item_editor->get_viewport_control()->update();
}
-
}
-void NavigationPolygonEditor::_create_nav() {
+void NavigationPolygonEditor::_create_nav() {
if (!node)
return;
undo_redo->create_action(TTR("Create Navigation Polygon"));
- undo_redo->add_do_method(node,"set_navigation_polygon",Ref<NavigationPolygon>(memnew( NavigationPolygon)));
- undo_redo->add_undo_method(node,"set_navigation_polygon",Variant(REF()));
+ undo_redo->add_do_method(node, "set_navigation_polygon", Ref<NavigationPolygon>(memnew(NavigationPolygon)));
+ undo_redo->add_undo_method(node, "set_navigation_polygon", Variant(REF()));
undo_redo->commit_action();
}
void NavigationPolygonEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MODE_CREATE: {
- mode=MODE_CREATE;
+ mode = MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
-
}
}
void NavigationPolygonEditor::_wip_close() {
-
- if (wip.size()>=3) {
+ if (wip.size() >= 3) {
undo_redo->create_action(TTR("Create Poly"));
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"remove_outline",node->get_navigation_polygon()->get_outline_count());
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"add_outline",wip);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "remove_outline", node->get_navigation_polygon()->get_outline_count());
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "add_outline", wip);
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
}
wip.clear();
- wip_active=false;
- edited_point=-1;
+ wip_active = false;
+ edited_point = -1;
}
-bool NavigationPolygonEditor::forward_gui_input(const InputEvent& p_event) {
-
+bool NavigationPolygonEditor::forward_gui_input(const InputEvent &p_event) {
if (!node)
return false;
if (node->get_navigation_polygon().is_null()) {
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && p_event.mouse_button.pressed) {
create_nav->set_text("No NavigationPolygon resource on this node.\nCreate and assign one?");
create_nav->popup_centered_minsize();
}
- return (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1);
+ return (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1);
}
-
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
-
- Vector2 gpoint = Point2(mb.x,mb.y);
+ Vector2 gpoint = Point2(mb.x, mb.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
-
-
//first check if a point is to be added (segment split)
- real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
-
- switch(mode) {
+ real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
+ switch (mode) {
case MODE_CREATE: {
- if (mb.button_index==BUTTON_LEFT && mb.pressed) {
-
+ if (mb.button_index == BUTTON_LEFT && mb.pressed) {
if (!wip_active) {
wip.clear();
- wip.push_back( cpoint );
- wip_active=true;
- edited_point_pos=cpoint;
- edited_outline=-1;
+ wip.push_back(cpoint);
+ wip_active = true;
+ edited_point_pos = cpoint;
+ edited_outline = -1;
canvas_item_editor->get_viewport_control()->update();
- edited_point=1;
+ edited_point = 1;
return true;
} else {
-
- if (wip.size()>1 && xform.xform(wip[0]).distance_to(gpoint)<grab_treshold) {
+ if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_treshold) {
//wip closed
_wip_close();
return true;
} else {
- wip.push_back( cpoint );
- edited_point=wip.size();
+ wip.push_back(cpoint);
+ edited_point = wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && wip_active) {
_wip_close();
}
-
-
} break;
case MODE_EDIT: {
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (mb.mod.control) {
-
//search edges
- int closest_outline=-1;
- int closest_idx=-1;
+ int closest_outline = -1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
-
- for(int j=0;j<node->get_navigation_polygon()->get_outline_count();j++) {
+ real_t closest_dist = 1e10;
+ for (int j = 0; j < node->get_navigation_polygon()->get_outline_count(); j++) {
- PoolVector<Vector2> points=node->get_navigation_polygon()->get_outline(j);
+ PoolVector<Vector2> points = node->get_navigation_polygon()->get_outline(j);
- int pc=points.size();
- PoolVector<Vector2>::Read poly=points.read();
+ int pc = points.size();
+ PoolVector<Vector2>::Read poly = points.read();
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
- Vector2 points[2] ={ xform.xform(poly[i]),
- xform.xform(poly[(i+1)%pc]) };
+ Vector2 points[2] = { xform.xform(poly[i]),
+ xform.xform(poly[(i + 1) % pc]) };
- Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
- if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
+ Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
+ if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_outline=j;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_outline = j;
+ closest_pos = cp;
+ closest_idx = i;
}
-
-
}
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=node->get_navigation_polygon()->get_outline(closest_outline);
+ pre_move_edit = node->get_navigation_polygon()->get_outline(closest_outline);
PoolVector<Point2> poly = pre_move_edit;
- poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos));
- edited_point=closest_idx+1;
- edited_outline=closest_outline;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
- node->get_navigation_polygon()->set_outline(closest_outline,poly);
+ poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos));
+ edited_point = closest_idx + 1;
+ edited_outline = closest_outline;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
+ node->get_navigation_polygon()->set_outline(closest_outline, poly);
canvas_item_editor->get_viewport_control()->update();
return true;
}
} else {
//look for points to move
- int closest_outline=-1;
- int closest_idx=-1;
+ int closest_outline = -1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
-
- for(int j=0;j<node->get_navigation_polygon()->get_outline_count();j++) {
+ real_t closest_dist = 1e10;
+ for (int j = 0; j < node->get_navigation_polygon()->get_outline_count(); j++) {
- PoolVector<Vector2> points=node->get_navigation_polygon()->get_outline(j);
+ PoolVector<Vector2> points = node->get_navigation_polygon()->get_outline(j);
- int pc=points.size();
- PoolVector<Vector2>::Read poly=points.read();
+ int pc = points.size();
+ PoolVector<Vector2>::Read poly = points.read();
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
-
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_outline=j;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_outline = j;
+ closest_idx = i;
}
}
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=node->get_navigation_polygon()->get_outline(closest_outline);
- edited_point=closest_idx;
- edited_outline=closest_outline;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = node->get_navigation_polygon()->get_outline(closest_outline);
+ edited_point = closest_idx;
+ edited_outline = closest_outline;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
- if (edited_point!=-1) {
+ if (edited_point != -1) {
//apply
PoolVector<Vector2> poly = node->get_navigation_polygon()->get_outline(edited_outline);
- ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
- poly.set(edited_point,edited_point_pos);
+ ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
+ poly.set(edited_point, edited_point_pos);
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"set_outline",edited_outline,poly);
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"set_outline",edited_outline,pre_move_edit);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "set_outline", edited_outline, poly);
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "set_outline", edited_outline, pre_move_edit);
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- edited_point=-1;
+ edited_point = -1;
return true;
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && edited_point == -1) {
- int closest_outline=-1;
- int closest_idx=-1;
+ int closest_outline = -1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
-
- for(int j=0;j<node->get_navigation_polygon()->get_outline_count();j++) {
-
+ real_t closest_dist = 1e10;
- PoolVector<Vector2> points=node->get_navigation_polygon()->get_outline(j);
+ for (int j = 0; j < node->get_navigation_polygon()->get_outline_count(); j++) {
- int pc=points.size();
- PoolVector<Vector2>::Read poly=points.read();
+ PoolVector<Vector2> points = node->get_navigation_polygon()->get_outline(j);
- for(int i=0;i<pc;i++) {
+ int pc = points.size();
+ PoolVector<Vector2>::Read poly = points.read();
+ for (int i = 0; i < pc; i++) {
- Vector2 cp =xform.xform(poly[i]);
+ Vector2 cp = xform.xform(poly[i]);
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_outline=j;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_outline = j;
+ closest_idx = i;
}
}
}
- if (closest_idx>=0) {
-
+ if (closest_idx >= 0) {
PoolVector<Vector2> poly = node->get_navigation_polygon()->get_outline(closest_outline);
- if (poly.size()>3) {
+ if (poly.size() > 3) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"set_outline",closest_outline,poly);
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "set_outline", closest_outline, poly);
poly.remove(closest_idx);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"set_outline",closest_outline,poly);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "set_outline", closest_outline, poly);
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
} else {
undo_redo->create_action(TTR("Remove Poly And Point"));
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"add_outline_at_index",poly,closest_outline);
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "add_outline_at_index", poly, closest_outline);
poly.remove(closest_idx);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"remove_outline",closest_outline);
- undo_redo->add_do_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_undo_method(node->get_navigation_polygon().ptr(),"make_polygons_from_outlines");
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "remove_outline", closest_outline);
+ undo_redo->add_do_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_undo_method(node->get_navigation_polygon().ptr(), "make_polygons_from_outlines");
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
-
}
return true;
}
}
-
-
} break;
}
-
-
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {
+ if (edited_point != -1 && (wip_active || mm.button_mask & BUTTON_MASK_LEFT)) {
- Vector2 gpoint = Point2(mm.x,mm.y);
+ Vector2 gpoint = Point2(mm.x, mm.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
canvas_item_editor->get_viewport_control()->update();
-
}
} break;
@@ -409,105 +379,96 @@ void NavigationPolygonEditor::_canvas_draw() {
Control *vpc = canvas_item_editor->get_viewport_control();
if (node->get_navigation_polygon().is_null())
- return;
+ return;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
-
-
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
- for(int j=-1;j<node->get_navigation_polygon()->get_outline_count();j++) {
+ for (int j = -1; j < node->get_navigation_polygon()->get_outline_count(); j++) {
Vector<Vector2> poly;
- if (wip_active && j==edited_outline) {
- poly=wip;
+ if (wip_active && j == edited_outline) {
+ poly = wip;
} else {
- if (j==-1)
+ if (j == -1)
continue;
poly = Variant(node->get_navigation_polygon()->get_outline(j));
}
- for(int i=0;i<poly.size();i++) {
+ for (int i = 0; i < poly.size(); i++) {
-
- Vector2 p,p2;
- p = (j==edited_outline && i==edited_point) ? edited_point_pos : poly[i];
- if (j==edited_outline && ((wip_active && i==poly.size()-1) || (((i+1)%poly.size())==edited_point)))
- p2=edited_point_pos;
+ Vector2 p, p2;
+ p = (j == edited_outline && i == edited_point) ? edited_point_pos : poly[i];
+ if (j == edited_outline && ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point)))
+ p2 = edited_point_pos;
else
- p2 = poly[(i+1)%poly.size()];
+ p2 = poly[(i + 1) % poly.size()];
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
- Color col=Color(1,0.3,0.1,0.8);
- vpc->draw_line(point,next_point,col,2);
- vpc->draw_texture(handle,point-handle->get_size()*0.5);
+ Color col = Color(1, 0.3, 0.1, 0.8);
+ vpc->draw_line(point, next_point, col, 2);
+ vpc->draw_texture(handle, point - handle->get_size() * 0.5);
}
}
}
-
-
void NavigationPolygonEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
- node=p_collision_polygon->cast_to<NavigationPolygonInstance>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ node = p_collision_polygon->cast_to<NavigationPolygonInstance>();
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
wip.clear();
- wip_active=false;
- edited_point=-1;
+ wip_active = false;
+ edited_point = -1;
canvas_item_editor->get_viewport_control()->update();
} else {
- node=NULL;
-
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ node = NULL;
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
}
-
}
void NavigationPolygonEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_option"),&NavigationPolygonEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&NavigationPolygonEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_node_removed"),&NavigationPolygonEditor::_node_removed);
- ClassDB::bind_method(D_METHOD("_create_nav"),&NavigationPolygonEditor::_create_nav);
-
+ ClassDB::bind_method(D_METHOD("_menu_option"), &NavigationPolygonEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &NavigationPolygonEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &NavigationPolygonEditor::_node_removed);
+ ClassDB::bind_method(D_METHOD("_create_nav"), &NavigationPolygonEditor::_create_nav);
}
NavigationPolygonEditor::NavigationPolygonEditor(EditorNode *p_editor) {
- node=NULL;
- canvas_item_editor=NULL;
- editor=p_editor;
+ node = NULL;
+ canvas_item_editor = NULL;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- add_child( memnew( VSeparator ));
- button_create = memnew( ToolButton );
+ add_child(memnew(VSeparator));
+ button_create = memnew(ToolButton);
add_child(button_create);
- button_create->connect("pressed",this,"_menu_option",varray(MODE_CREATE));
+ button_create->connect("pressed", this, "_menu_option", varray(MODE_CREATE));
button_create->set_toggle_mode(true);
button_create->set_tooltip(TTR("Create a new polygon from scratch."));
- button_edit = memnew( ToolButton );
+ button_edit = memnew(ToolButton);
add_child(button_edit);
- button_edit->connect("pressed",this,"_menu_option",varray(MODE_EDIT));
+ button_edit->connect("pressed", this, "_menu_option", varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
- button_edit->set_tooltip(TTR("Edit existing polygon:")+"\n"+TTR("LMB: Move Point.")+"\n"+TTR("Ctrl+LMB: Split Segment.")+"\n"+TTR("RMB: Erase Point."));
- create_nav = memnew( ConfirmationDialog );
+ button_edit->set_tooltip(TTR("Edit existing polygon:") + "\n" + TTR("LMB: Move Point.") + "\n" + TTR("Ctrl+LMB: Split Segment.") + "\n" + TTR("RMB: Erase Point."));
+ create_nav = memnew(ConfirmationDialog);
add_child(create_nav);
create_nav->get_ok()->set_text(TTR("Create"));
-
- //add_constant_override("separation",0);
+//add_constant_override("separation",0);
#if 0
options = memnew( MenuButton );
@@ -519,12 +480,10 @@ NavigationPolygonEditor::NavigationPolygonEditor(EditorNode *p_editor) {
#endif
mode = MODE_EDIT;
- wip_active=false;
- edited_outline=-1;
-
+ wip_active = false;
+ edited_outline = -1;
}
-
void NavigationPolygonEditorPlugin::edit(Object *p_object) {
collision_polygon_editor->edit(p_object->cast_to<Node>());
@@ -544,23 +503,16 @@ void NavigationPolygonEditorPlugin::make_visible(bool p_visible) {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
-
}
NavigationPolygonEditorPlugin::NavigationPolygonEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- collision_polygon_editor = memnew( NavigationPolygonEditor(p_node) );
+ editor = p_node;
+ collision_polygon_editor = memnew(NavigationPolygonEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
-
-
-
}
-
-NavigationPolygonEditorPlugin::~NavigationPolygonEditorPlugin()
-{
+NavigationPolygonEditorPlugin::~NavigationPolygonEditorPlugin() {
}
-
diff --git a/editor/plugins/navigation_polygon_editor_plugin.h b/editor/plugins/navigation_polygon_editor_plugin.h
index 0d5e67e352..ba18756869 100644
--- a/editor/plugins/navigation_polygon_editor_plugin.h
+++ b/editor/plugins/navigation_polygon_editor_plugin.h
@@ -29,13 +29,11 @@
#ifndef NAVIGATIONPOLYGONEDITORPLUGIN_H
#define NAVIGATIONPOLYGONEDITORPLUGIN_H
-
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/navigation_polygon.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -44,7 +42,7 @@ class CanvasItemEditor;
class NavigationPolygonEditor : public HBoxContainer {
- GDCLASS(NavigationPolygonEditor, HBoxContainer );
+ GDCLASS(NavigationPolygonEditor, HBoxContainer);
UndoRedo *undo_redo;
enum Mode {
@@ -74,7 +72,6 @@ class NavigationPolygonEditor : public HBoxContainer {
Vector<Vector2> wip;
bool wip_active;
-
void _wip_close();
void _canvas_draw();
void _create_nav();
@@ -85,23 +82,22 @@ protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
- bool forward_gui_input(const InputEvent& p_event);
+public:
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_collision_polygon);
NavigationPolygonEditor(EditorNode *p_editor);
};
class NavigationPolygonEditorPlugin : public EditorPlugin {
- GDCLASS( NavigationPolygonEditorPlugin, EditorPlugin );
+ GDCLASS(NavigationPolygonEditorPlugin, EditorPlugin);
NavigationPolygonEditor *collision_polygon_editor;
EditorNode *editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "NavigationPolygonInstance"; }
bool has_main_screen() const { return false; }
@@ -111,8 +107,6 @@ public:
NavigationPolygonEditorPlugin(EditorNode *p_node);
~NavigationPolygonEditorPlugin();
-
};
-
#endif // NAVIGATIONPOLYGONEDITORPLUGIN_H
diff --git a/editor/plugins/particles_2d_editor_plugin.cpp b/editor/plugins/particles_2d_editor_plugin.cpp
index 1efdbe9e68..94644cd410 100644
--- a/editor/plugins/particles_2d_editor_plugin.cpp
+++ b/editor/plugins/particles_2d_editor_plugin.cpp
@@ -35,9 +35,9 @@
void Particles2DEditorPlugin::edit(Object *p_object) {
if (p_object) {
- particles=p_object->cast_to<Particles2D>();
+ particles = p_object->cast_to<Particles2D>();
} else {
- particles=NULL;
+ particles = NULL;
}
}
@@ -55,145 +55,135 @@ void Particles2DEditorPlugin::make_visible(bool p_visible) {
toolbar->hide();
}
-
}
-void Particles2DEditorPlugin::_file_selected(const String& p_file) {
+void Particles2DEditorPlugin::_file_selected(const String &p_file) {
- print_line("file: "+p_file);
+ print_line("file: " + p_file);
- int epc=epoints->get_value();
+ int epc = epoints->get_value();
Image img;
- Error err = ImageLoader::load_image(p_file,&img);
- ERR_EXPLAIN(TTR("Error loading image:")+" "+p_file);
- ERR_FAIL_COND(err!=OK);
+ Error err = ImageLoader::load_image(p_file, &img);
+ ERR_EXPLAIN(TTR("Error loading image:") + " " + p_file);
+ ERR_FAIL_COND(err != OK);
img.convert(Image::FORMAT_LA8);
- ERR_FAIL_COND(img.get_format()!=Image::FORMAT_LA8);
- Size2i s = Size2(img.get_width(),img.get_height());
- ERR_FAIL_COND(s.width==0 || s.height==0);
+ ERR_FAIL_COND(img.get_format() != Image::FORMAT_LA8);
+ Size2i s = Size2(img.get_width(), img.get_height());
+ ERR_FAIL_COND(s.width == 0 || s.height == 0);
PoolVector<uint8_t> data = img.get_data();
PoolVector<uint8_t>::Read r = data.read();
Vector<Point2i> valid_positions;
- valid_positions.resize(s.width*s.height);
- int vpc=0;
-
+ valid_positions.resize(s.width * s.height);
+ int vpc = 0;
- for(int i=0;i<s.width*s.height;i++) {
+ for (int i = 0; i < s.width * s.height; i++) {
- uint8_t a = r[i*2+1];
- if (a>128) {
- valid_positions[vpc++]=Point2i(i%s.width,i/s.width);
+ uint8_t a = r[i * 2 + 1];
+ if (a > 128) {
+ valid_positions[vpc++] = Point2i(i % s.width, i / s.width);
}
}
valid_positions.resize(vpc);
ERR_EXPLAIN(TTR("No pixels with transparency > 128 in image.."));
- ERR_FAIL_COND(valid_positions.size()==0);
+ ERR_FAIL_COND(valid_positions.size() == 0);
PoolVector<Point2> epoints;
epoints.resize(epc);
PoolVector<Point2>::Write w = epoints.write();
- Size2 extents = Size2(img.get_width()*0.5,img.get_height()*0.5);
+ Size2 extents = Size2(img.get_width() * 0.5, img.get_height() * 0.5);
- for(int i=0;i<epc;i++) {
+ for (int i = 0; i < epc; i++) {
- Point2 p = valid_positions[Math::rand()%vpc];
- p-=s/2;
- w[i]=p/extents;
+ Point2 p = valid_positions[Math::rand() % vpc];
+ p -= s / 2;
+ w[i] = p / extents;
}
w = PoolVector<Point2>::Write();
undo_redo->create_action(TTR("Set Emission Mask"));
- undo_redo->add_do_method(particles,"set_emission_points",epoints);
- undo_redo->add_do_method(particles,"set_emission_half_extents",extents);
- undo_redo->add_undo_method(particles,"set_emission_points",particles->get_emission_points());
- undo_redo->add_undo_method(particles,"set_emission_half_extents",particles->get_emission_half_extents());
+ undo_redo->add_do_method(particles, "set_emission_points", epoints);
+ undo_redo->add_do_method(particles, "set_emission_half_extents", extents);
+ undo_redo->add_undo_method(particles, "set_emission_points", particles->get_emission_points());
+ undo_redo->add_undo_method(particles, "set_emission_half_extents", particles->get_emission_half_extents());
undo_redo->commit_action();
-
}
void Particles2DEditorPlugin::_menu_callback(int p_idx) {
- switch(p_idx) {
+ switch (p_idx) {
case MENU_LOAD_EMISSION_MASK: {
-
file->popup_centered_ratio();
} break;
case MENU_CLEAR_EMISSION_MASK: {
undo_redo->create_action(TTR("Clear Emission Mask"));
- undo_redo->add_do_method(particles,"set_emission_points",PoolVector<Vector2>());
- undo_redo->add_undo_method(particles,"set_emission_points",particles->get_emission_points());
+ undo_redo->add_do_method(particles, "set_emission_points", PoolVector<Vector2>());
+ undo_redo->add_undo_method(particles, "set_emission_points", particles->get_emission_points());
undo_redo->commit_action();
} break;
}
-
}
-
void Particles2DEditorPlugin::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- menu->get_popup()->connect("id_pressed",this,"_menu_callback");
- menu->set_icon(menu->get_popup()->get_icon("Particles2D","EditorIcons"));
- file->connect("file_selected",this,"_file_selected");
+ menu->get_popup()->connect("id_pressed", this, "_menu_callback");
+ menu->set_icon(menu->get_popup()->get_icon("Particles2D", "EditorIcons"));
+ file->connect("file_selected", this, "_file_selected");
}
}
void Particles2DEditorPlugin::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_callback"),&Particles2DEditorPlugin::_menu_callback);
- ClassDB::bind_method(D_METHOD("_file_selected"),&Particles2DEditorPlugin::_file_selected);
+ ClassDB::bind_method(D_METHOD("_menu_callback"), &Particles2DEditorPlugin::_menu_callback);
+ ClassDB::bind_method(D_METHOD("_file_selected"), &Particles2DEditorPlugin::_file_selected);
}
-
-
Particles2DEditorPlugin::Particles2DEditorPlugin(EditorNode *p_node) {
- particles=NULL;
- editor=p_node;
- undo_redo=editor->get_undo_redo();
+ particles = NULL;
+ editor = p_node;
+ undo_redo = editor->get_undo_redo();
- toolbar = memnew( HBoxContainer );
+ toolbar = memnew(HBoxContainer);
add_control_to_container(CONTAINER_CANVAS_EDITOR_MENU, toolbar);
toolbar->hide();
- toolbar->add_child( memnew( VSeparator ) );
+ toolbar->add_child(memnew(VSeparator));
- menu = memnew( MenuButton );
- menu->get_popup()->add_item(TTR("Load Emission Mask"),MENU_LOAD_EMISSION_MASK);
- menu->get_popup()->add_item(TTR("Clear Emission Mask"),MENU_CLEAR_EMISSION_MASK);
+ menu = memnew(MenuButton);
+ menu->get_popup()->add_item(TTR("Load Emission Mask"), MENU_LOAD_EMISSION_MASK);
+ menu->get_popup()->add_item(TTR("Clear Emission Mask"), MENU_CLEAR_EMISSION_MASK);
menu->set_text("Particles");
toolbar->add_child(menu);
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
List<String> ext;
ImageLoader::get_recognized_extensions(&ext);
- for(List<String>::Element *E=ext.front();E;E=E->next()) {
- file->add_filter("*."+E->get()+"; "+E->get().to_upper());
+ for (List<String>::Element *E = ext.front(); E; E = E->next()) {
+ file->add_filter("*." + E->get() + "; " + E->get().to_upper());
}
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
toolbar->add_child(file);
- epoints = memnew( SpinBox );
+ epoints = memnew(SpinBox);
epoints->set_min(1);
epoints->set_max(8192);
epoints->set_step(1);
epoints->set_value(512);
- file->get_vbox()->add_margin_child(TTR("Generated Point Count:"),epoints);
+ file->get_vbox()->add_margin_child(TTR("Generated Point Count:"), epoints);
}
-Particles2DEditorPlugin::~Particles2DEditorPlugin()
-{
+Particles2DEditorPlugin::~Particles2DEditorPlugin() {
}
-
diff --git a/editor/plugins/particles_2d_editor_plugin.h b/editor/plugins/particles_2d_editor_plugin.h
index ea71c739f3..56122c4354 100644
--- a/editor/plugins/particles_2d_editor_plugin.h
+++ b/editor/plugins/particles_2d_editor_plugin.h
@@ -29,17 +29,17 @@
#ifndef PARTICLES_2D_EDITOR_PLUGIN_H
#define PARTICLES_2D_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/collision_polygon_2d.h"
+#include "scene/2d/particles_2d.h"
#include "scene/gui/box_container.h"
#include "scene/gui/file_dialog.h"
-#include "scene/2d/particles_2d.h"
class Particles2DEditorPlugin : public EditorPlugin {
- GDCLASS( Particles2DEditorPlugin, EditorPlugin );
+ GDCLASS(Particles2DEditorPlugin, EditorPlugin);
enum {
@@ -58,15 +58,14 @@ class Particles2DEditorPlugin : public EditorPlugin {
SpinBox *epoints;
UndoRedo *undo_redo;
- void _file_selected(const String& p_file);
+ void _file_selected(const String &p_file);
void _menu_callback(int p_idx);
+
protected:
void _notification(int p_what);
static void _bind_methods();
public:
-
-
virtual String get_name() const { return "Particles2D"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -75,8 +74,6 @@ public:
Particles2DEditorPlugin(EditorNode *p_node);
~Particles2DEditorPlugin();
-
};
-
#endif // PARTICLES_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/particles_editor_plugin.cpp b/editor/plugins/particles_editor_plugin.cpp
index 4ce1f5eb54..fd26674a0e 100644
--- a/editor/plugins/particles_editor_plugin.cpp
+++ b/editor/plugins/particles_editor_plugin.cpp
@@ -29,9 +29,9 @@
#if 0
#include "particles_editor_plugin.h"
+#include "editor/plugins/spatial_editor_plugin.h"
#include "io/resource_loader.h"
#include "servers/visual/particle_system_sw.h"
-#include "editor/plugins/spatial_editor_plugin.h"
void ParticlesEditor::_node_removed(Node *p_node) {
@@ -457,5 +457,4 @@ ParticlesEditorPlugin::~ParticlesEditorPlugin()
{
}
-
#endif
diff --git a/editor/plugins/particles_editor_plugin.h b/editor/plugins/particles_editor_plugin.h
index 06134ddef2..420e20d641 100644
--- a/editor/plugins/particles_editor_plugin.h
+++ b/editor/plugins/particles_editor_plugin.h
@@ -29,8 +29,8 @@
#ifndef PARTICLES_EDITOR_PLUGIN_H
#define PARTICLES_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/particles.h"
#include "scene/gui/spin_box.h"
diff --git a/editor/plugins/path_2d_editor_plugin.cpp b/editor/plugins/path_2d_editor_plugin.cpp
index 00b026e25b..36605c118f 100644
--- a/editor/plugins/path_2d_editor_plugin.cpp
+++ b/editor/plugins/path_2d_editor_plugin.cpp
@@ -29,12 +29,12 @@
#include "path_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
+#include "os/file_access.h"
#include "os/keyboard.h"
void Path2DEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
@@ -43,26 +43,21 @@ void Path2DEditor::_notification(int p_what) {
//set_pressed_button(button_edit);
//button_edit->set_pressed(true);
-
} break;
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void Path2DEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
}
-
}
-
-bool Path2DEditor::forward_gui_input(const InputEvent& p_event) {
+bool Path2DEditor::forward_gui_input(const InputEvent &p_event) {
if (!node)
return false;
@@ -73,160 +68,151 @@ bool Path2DEditor::forward_gui_input(const InputEvent& p_event) {
if (!node->get_curve().is_valid())
return false;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Vector2 gpoint = Point2(mb.x,mb.y);
- Vector2 cpoint = !mb.mod.alt? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint))
- : node->get_global_transform().affine_inverse().xform( canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)) );
+ Vector2 gpoint = Point2(mb.x, mb.y);
+ Vector2 cpoint = !mb.mod.alt ? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint)) : node->get_global_transform().affine_inverse().xform(canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)));
//first check if a point is to be added (segment split)
- real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
-
-
+ real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
// Test move point!!
- if ( mb.pressed && action==ACTION_NONE ) {
+ if (mb.pressed && action == ACTION_NONE) {
Ref<Curve2D> curve = node->get_curve();
- for(int i=0;i<curve->get_point_count();i++) {
+ for (int i = 0; i < curve->get_point_count(); i++) {
- bool pointunder=false;
+ bool pointunder = false;
{
- Point2 p = xform.xform( curve->get_point_pos(i) );
- if (gpoint.distance_to(p) < grab_treshold ) {
+ Point2 p = xform.xform(curve->get_point_pos(i));
+ if (gpoint.distance_to(p) < grab_treshold) {
- if (mb.button_index==BUTTON_LEFT && !mb.mod.shift && mode==MODE_EDIT) {
+ if (mb.button_index == BUTTON_LEFT && !mb.mod.shift && mode == MODE_EDIT) {
- action=ACTION_MOVING_POINT;
- action_point=i;
- moving_from=curve->get_point_pos(i);
- moving_screen_from=gpoint;
+ action = ACTION_MOVING_POINT;
+ action_point = i;
+ moving_from = curve->get_point_pos(i);
+ moving_screen_from = gpoint;
return true;
- } else if ((mb.button_index==BUTTON_RIGHT && mode==MODE_EDIT) || (mb.button_index==BUTTON_LEFT && mode==MODE_DELETE)) {
+ } else if ((mb.button_index == BUTTON_RIGHT && mode == MODE_EDIT) || (mb.button_index == BUTTON_LEFT && mode == MODE_DELETE)) {
undo_redo->create_action(TTR("Remove Point from Curve"));
- undo_redo->add_do_method(curve.ptr(),"remove_point",i);
- undo_redo->add_undo_method(curve.ptr(),"add_point",curve->get_point_pos(i),curve->get_point_in(i),curve->get_point_out(i),i);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(curve.ptr(), "remove_point", i);
+ undo_redo->add_undo_method(curve.ptr(), "add_point", curve->get_point_pos(i), curve->get_point_in(i), curve->get_point_out(i), i);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
} else
- pointunder=true;
+ pointunder = true;
}
}
- if (mb.button_index==BUTTON_LEFT && i<(curve->get_point_count()-1)) {
- Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_out(i) );
- if (gpoint.distance_to(p) < grab_treshold && (mode == MODE_EDIT || mode==MODE_EDIT_CURVE) ) {
+ if (mb.button_index == BUTTON_LEFT && i < (curve->get_point_count() - 1)) {
+ Point2 p = xform.xform(curve->get_point_pos(i) + curve->get_point_out(i));
+ if (gpoint.distance_to(p) < grab_treshold && (mode == MODE_EDIT || mode == MODE_EDIT_CURVE)) {
- action=ACTION_MOVING_OUT;
- action_point=i;
- moving_from=curve->get_point_out(i);
- moving_screen_from=gpoint;
+ action = ACTION_MOVING_OUT;
+ action_point = i;
+ moving_from = curve->get_point_out(i);
+ moving_screen_from = gpoint;
return true;
}
}
- if (mb.button_index==BUTTON_LEFT && i>0) {
- Point2 p = xform.xform( curve->get_point_pos(i)+curve->get_point_in(i) );
- if (gpoint.distance_to(p) < grab_treshold && (mode == MODE_EDIT || mode==MODE_EDIT_CURVE)) {
+ if (mb.button_index == BUTTON_LEFT && i > 0) {
+ Point2 p = xform.xform(curve->get_point_pos(i) + curve->get_point_in(i));
+ if (gpoint.distance_to(p) < grab_treshold && (mode == MODE_EDIT || mode == MODE_EDIT_CURVE)) {
- action=ACTION_MOVING_IN;
- action_point=i;
- moving_from=curve->get_point_in(i);
- moving_screen_from=gpoint;
+ action = ACTION_MOVING_IN;
+ action_point = i;
+ moving_from = curve->get_point_in(i);
+ moving_screen_from = gpoint;
return true;
}
}
if (pointunder)
return true;
-
}
-
}
// Test add point in empty space!
- if ( mb.pressed && mb.button_index==BUTTON_LEFT && ((mb.mod.command && mode == MODE_EDIT) || mode == MODE_CREATE)) {
+ if (mb.pressed && mb.button_index == BUTTON_LEFT && ((mb.mod.command && mode == MODE_EDIT) || mode == MODE_CREATE)) {
Ref<Curve2D> curve = node->get_curve();
undo_redo->create_action(TTR("Add Point to Curve"));
- undo_redo->add_do_method(curve.ptr(),"add_point",cpoint);
- undo_redo->add_undo_method(curve.ptr(),"remove_point",curve->get_point_count());
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(curve.ptr(), "add_point", cpoint);
+ undo_redo->add_undo_method(curve.ptr(), "remove_point", curve->get_point_count());
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- action=ACTION_MOVING_POINT;
- action_point=curve->get_point_count()-1;
- moving_from=curve->get_point_pos(action_point);
- moving_screen_from=gpoint;
+ action = ACTION_MOVING_POINT;
+ action_point = curve->get_point_count() - 1;
+ moving_from = curve->get_point_pos(action_point);
+ moving_screen_from = gpoint;
canvas_item_editor->get_viewport_control()->update();
return true;
}
- if ( !mb.pressed && mb.button_index==BUTTON_LEFT && action!=ACTION_NONE) {
-
+ if (!mb.pressed && mb.button_index == BUTTON_LEFT && action != ACTION_NONE) {
Ref<Curve2D> curve = node->get_curve();
Vector2 new_pos = moving_from + xform.affine_inverse().basis_xform(gpoint - moving_screen_from);
- switch(action) {
+ switch (action) {
case ACTION_MOVING_POINT: {
-
undo_redo->create_action(TTR("Move Point in Curve"));
- undo_redo->add_do_method(curve.ptr(),"set_point_pos",action_point,cpoint);
- undo_redo->add_undo_method(curve.ptr(),"set_point_pos",action_point,moving_from);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(curve.ptr(), "set_point_pos", action_point, cpoint);
+ undo_redo->add_undo_method(curve.ptr(), "set_point_pos", action_point, moving_from);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
} break;
case ACTION_MOVING_IN: {
undo_redo->create_action(TTR("Move In-Control in Curve"));
- undo_redo->add_do_method(curve.ptr(),"set_point_in",action_point,new_pos);
- undo_redo->add_undo_method(curve.ptr(),"set_point_in",action_point,moving_from);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(curve.ptr(), "set_point_in", action_point, new_pos);
+ undo_redo->add_undo_method(curve.ptr(), "set_point_in", action_point, moving_from);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
} break;
case ACTION_MOVING_OUT: {
undo_redo->create_action(TTR("Move Out-Control in Curve"));
- undo_redo->add_do_method(curve.ptr(),"set_point_out",action_point,new_pos);
- undo_redo->add_undo_method(curve.ptr(),"set_point_out",action_point,moving_from);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(curve.ptr(), "set_point_out", action_point, new_pos);
+ undo_redo->add_undo_method(curve.ptr(), "set_point_out", action_point, moving_from);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
} break;
-
}
- action=ACTION_NONE;
+ action = ACTION_NONE;
return true;
}
-
#if 0
switch(mode) {
@@ -411,44 +397,40 @@ bool Path2DEditor::forward_gui_input(const InputEvent& p_event) {
} break;
}
-
#endif
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
-
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- if ( action!=ACTION_NONE) {
+ if (action != ACTION_NONE) {
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Vector2 gpoint = Point2(mm.x,mm.y);
- Vector2 cpoint = !mm.mod.alt? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint))
- : node->get_global_transform().affine_inverse().xform( canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)) );
+ Vector2 gpoint = Point2(mm.x, mm.y);
+ Vector2 cpoint = !mm.mod.alt ? canvas_item_editor->snap_point(xform.affine_inverse().xform(gpoint)) : node->get_global_transform().affine_inverse().xform(canvas_item_editor->snap_point(canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint)));
Ref<Curve2D> curve = node->get_curve();
Vector2 new_pos = moving_from + xform.affine_inverse().basis_xform(gpoint - moving_screen_from);
- switch(action) {
+ switch (action) {
case ACTION_MOVING_POINT: {
- curve->set_point_pos(action_point,cpoint);
+ curve->set_point_pos(action_point, cpoint);
} break;
case ACTION_MOVING_IN: {
- curve->set_point_in(action_point,new_pos);
+ curve->set_point_in(action_point, new_pos);
} break;
case ACTION_MOVING_OUT: {
- curve->set_point_out(action_point,new_pos);
+ curve->set_point_out(action_point, new_pos);
} break;
}
-
canvas_item_editor->get_viewport_control()->update();
return true;
}
@@ -473,16 +455,16 @@ bool Path2DEditor::forward_gui_input(const InputEvent& p_event) {
void Path2DEditor::_canvas_draw() {
if (!node)
- return ;
+ return;
if (!node->is_visible_in_tree())
return;
if (!node->get_curve().is_valid())
- return ;
+ return;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
Size2 handle_size = handle->get_size();
Ref<Curve2D> curve = node->get_curve();
@@ -490,27 +472,23 @@ void Path2DEditor::_canvas_draw() {
int len = curve->get_point_count();
Control *vpc = canvas_item_editor->get_viewport_control();
-
- for(int i=0;i<len;i++) {
-
+ for (int i = 0; i < len; i++) {
Vector2 point = xform.xform(curve->get_point_pos(i));
- vpc->draw_texture_rect(handle,Rect2(point-handle_size*0.5,handle_size),false,Color(1,1,1,1));
+ vpc->draw_texture_rect(handle, Rect2(point - handle_size * 0.5, handle_size), false, Color(1, 1, 1, 1));
- if (i<len-1) {
- Vector2 pointout = xform.xform(curve->get_point_pos(i)+curve->get_point_out(i));
- vpc->draw_line(point,pointout,Color(0.5,0.5,1.0,0.8),1.0);
- vpc->draw_texture_rect(handle, Rect2(pointout-handle_size*0.5,handle_size),false,Color(1,0.5,1,0.3));
+ if (i < len - 1) {
+ Vector2 pointout = xform.xform(curve->get_point_pos(i) + curve->get_point_out(i));
+ vpc->draw_line(point, pointout, Color(0.5, 0.5, 1.0, 0.8), 1.0);
+ vpc->draw_texture_rect(handle, Rect2(pointout - handle_size * 0.5, handle_size), false, Color(1, 0.5, 1, 0.3));
}
- if (i>0) {
- Vector2 pointin = xform.xform(curve->get_point_pos(i)+curve->get_point_in(i));
- vpc->draw_line(point,pointin,Color(0.5,0.5,1.0,0.8),1.0);
- vpc->draw_texture_rect(handle, Rect2(pointin-handle_size*0.5,handle_size),false,Color(1,0.5,1,0.3));
+ if (i > 0) {
+ Vector2 pointin = xform.xform(curve->get_point_pos(i) + curve->get_point_in(i));
+ vpc->draw_line(point, pointin, Color(0.5, 0.5, 1.0, 0.8), 1.0);
+ vpc->draw_texture_rect(handle, Rect2(pointin - handle_size * 0.5, handle_size), false, Color(1, 0.5, 1, 0.3));
}
-
}
-
}
void Path2DEditor::_node_visibility_changed() {
@@ -523,101 +501,98 @@ void Path2DEditor::_node_visibility_changed() {
void Path2DEditor::edit(Node *p_path2d) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_path2d) {
- node=p_path2d->cast_to<Path2D>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ node = p_path2d->cast_to<Path2D>();
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
if (!node->is_connected("visibility_changed", this, "_node_visibility_changed"))
node->connect("visibility_changed", this, "_node_visibility_changed");
-
} else {
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
// node may have been deleted at this point
if (node && node->is_connected("visibility_changed", this, "_node_visibility_changed"))
node->disconnect("visibility_changed", this, "_node_visibility_changed");
- node=NULL;
+ node = NULL;
}
-
}
void Path2DEditor::_bind_methods() {
//ClassDB::bind_method(D_METHOD("_menu_option"),&Path2DEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&Path2DEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_node_visibility_changed"),&Path2DEditor::_node_visibility_changed);
- ClassDB::bind_method(D_METHOD("_mode_selected"),&Path2DEditor::_mode_selected);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &Path2DEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_node_visibility_changed"), &Path2DEditor::_node_visibility_changed);
+ ClassDB::bind_method(D_METHOD("_mode_selected"), &Path2DEditor::_mode_selected);
}
void Path2DEditor::_mode_selected(int p_mode) {
- if (p_mode==MODE_CREATE) {
+ if (p_mode == MODE_CREATE) {
curve_create->set_pressed(true);
curve_edit->set_pressed(false);
curve_edit_curve->set_pressed(false);
curve_del->set_pressed(false);
- } else if (p_mode==MODE_EDIT) {
+ } else if (p_mode == MODE_EDIT) {
curve_create->set_pressed(false);
curve_edit->set_pressed(true);
curve_edit_curve->set_pressed(false);
curve_del->set_pressed(false);
- } else if (p_mode==MODE_EDIT_CURVE) {
+ } else if (p_mode == MODE_EDIT_CURVE) {
curve_create->set_pressed(false);
curve_edit->set_pressed(false);
curve_edit_curve->set_pressed(true);
curve_del->set_pressed(false);
- } else if (p_mode==MODE_DELETE) {
+ } else if (p_mode == MODE_DELETE) {
curve_create->set_pressed(false);
curve_edit->set_pressed(false);
curve_edit_curve->set_pressed(false);
curve_del->set_pressed(true);
- } else if (p_mode==ACTION_CLOSE) {
+ } else if (p_mode == ACTION_CLOSE) {
//?
if (!node->get_curve().is_valid())
- return ;
- if (node->get_curve()->get_point_count()<3)
+ return;
+ if (node->get_curve()->get_point_count() < 3)
return;
Vector2 begin = node->get_curve()->get_point_pos(0);
- Vector2 end = node->get_curve()->get_point_pos( node->get_curve()->get_point_count() -1 );
- if (begin.distance_to(end)<CMP_EPSILON)
+ Vector2 end = node->get_curve()->get_point_pos(node->get_curve()->get_point_count() - 1);
+ if (begin.distance_to(end) < CMP_EPSILON)
return;
undo_redo->create_action(TTR("Remove Point from Curve"));
- undo_redo->add_do_method(node->get_curve().ptr(),"add_point",begin);
- undo_redo->add_undo_method(node->get_curve().ptr(),"remove_point",node->get_curve()->get_point_count());
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node->get_curve().ptr(), "add_point", begin);
+ undo_redo->add_undo_method(node->get_curve().ptr(), "remove_point", node->get_curve()->get_point_count());
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return;
}
- mode=Mode(p_mode);
-
+ mode = Mode(p_mode);
}
Path2DEditor::Path2DEditor(EditorNode *p_editor) {
- canvas_item_editor=NULL;
- editor=p_editor;
+ canvas_item_editor = NULL;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
- action=ACTION_NONE;
+ action = ACTION_NONE;
#if 0
options = memnew( MenuButton );
add_child(options);
@@ -627,55 +602,50 @@ Path2DEditor::Path2DEditor(EditorNode *p_editor) {
options->get_popup()->connect("id_pressed", this,"_menu_option");
#endif
- base_hb = memnew( HBoxContainer );
+ base_hb = memnew(HBoxContainer);
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(base_hb);
- sep = memnew( VSeparator);
+ sep = memnew(VSeparator);
base_hb->add_child(sep);
- curve_edit = memnew( ToolButton );
- curve_edit->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveEdit","EditorIcons"));
+ curve_edit = memnew(ToolButton);
+ curve_edit->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveEdit", "EditorIcons"));
curve_edit->set_toggle_mode(true);
curve_edit->set_focus_mode(Control::FOCUS_NONE);
- curve_edit->set_tooltip(TTR("Select Points")+"\n"+TTR("Shift+Drag: Select Control Points")+"\n"+keycode_get_string(KEY_MASK_CMD)+TTR("Click: Add Point")+"\n"+TTR("Right Click: Delete Point"));
- curve_edit->connect("pressed",this,"_mode_selected",varray(MODE_EDIT));
+ curve_edit->set_tooltip(TTR("Select Points") + "\n" + TTR("Shift+Drag: Select Control Points") + "\n" + keycode_get_string(KEY_MASK_CMD) + TTR("Click: Add Point") + "\n" + TTR("Right Click: Delete Point"));
+ curve_edit->connect("pressed", this, "_mode_selected", varray(MODE_EDIT));
base_hb->add_child(curve_edit);
- curve_edit_curve = memnew( ToolButton );
- curve_edit_curve->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveCurve","EditorIcons"));
+ curve_edit_curve = memnew(ToolButton);
+ curve_edit_curve->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveCurve", "EditorIcons"));
curve_edit_curve->set_toggle_mode(true);
curve_edit_curve->set_focus_mode(Control::FOCUS_NONE);
curve_edit_curve->set_tooltip(TTR("Select Control Points (Shift+Drag)"));
- curve_edit_curve->connect("pressed",this,"_mode_selected",varray(MODE_EDIT_CURVE));
+ curve_edit_curve->connect("pressed", this, "_mode_selected", varray(MODE_EDIT_CURVE));
base_hb->add_child(curve_edit_curve);
- curve_create = memnew( ToolButton );
- curve_create->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveCreate","EditorIcons"));
+ curve_create = memnew(ToolButton);
+ curve_create->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveCreate", "EditorIcons"));
curve_create->set_toggle_mode(true);
curve_create->set_focus_mode(Control::FOCUS_NONE);
- curve_create->set_tooltip(TTR("Add Point (in empty space)")+"\n"+TTR("Split Segment (in curve)"));
- curve_create->connect("pressed",this,"_mode_selected",varray(MODE_CREATE));
+ curve_create->set_tooltip(TTR("Add Point (in empty space)") + "\n" + TTR("Split Segment (in curve)"));
+ curve_create->connect("pressed", this, "_mode_selected", varray(MODE_CREATE));
base_hb->add_child(curve_create);
- curve_del = memnew( ToolButton );
- curve_del->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveDelete","EditorIcons"));
+ curve_del = memnew(ToolButton);
+ curve_del->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveDelete", "EditorIcons"));
curve_del->set_toggle_mode(true);
curve_del->set_focus_mode(Control::FOCUS_NONE);
curve_del->set_tooltip(TTR("Delete Point"));
- curve_del->connect("pressed",this,"_mode_selected",varray(MODE_DELETE));
+ curve_del->connect("pressed", this, "_mode_selected", varray(MODE_DELETE));
base_hb->add_child(curve_del);
- curve_close = memnew( ToolButton );
- curve_close->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveClose","EditorIcons"));
+ curve_close = memnew(ToolButton);
+ curve_close->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("CurveClose", "EditorIcons"));
curve_close->set_focus_mode(Control::FOCUS_NONE);
curve_close->set_tooltip(TTR("Close Curve"));
- curve_close->connect("pressed",this,"_mode_selected",varray(ACTION_CLOSE));
+ curve_close->connect("pressed", this, "_mode_selected", varray(ACTION_CLOSE));
base_hb->add_child(curve_close);
base_hb->hide();
-
-
curve_edit->set_pressed(true);
-
-
}
-
void Path2DEditorPlugin::edit(Object *p_object) {
path2d_editor->edit(p_object->cast_to<Node>());
@@ -698,21 +668,15 @@ void Path2DEditorPlugin::make_visible(bool p_visible) {
path2d_editor->base_hb->hide();
path2d_editor->edit(NULL);
}
-
}
Path2DEditorPlugin::Path2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- path2d_editor = memnew( Path2DEditor(p_node) );
+ editor = p_node;
+ path2d_editor = memnew(Path2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(path2d_editor);
path2d_editor->hide();
-
-
}
-
-Path2DEditorPlugin::~Path2DEditorPlugin()
-{
+Path2DEditorPlugin::~Path2DEditorPlugin() {
}
-
diff --git a/editor/plugins/path_2d_editor_plugin.h b/editor/plugins/path_2d_editor_plugin.h
index 89f42d94cc..32dd6868bb 100644
--- a/editor/plugins/path_2d_editor_plugin.h
+++ b/editor/plugins/path_2d_editor_plugin.h
@@ -29,11 +29,11 @@
#ifndef PATH_2D_EDITOR_PLUGIN_H
#define PATH_2D_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/path_2d.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -77,7 +77,6 @@ class Path2DEditor : public HBoxContainer {
ACTION_MOVING_OUT,
};
-
Action action;
int action_point;
Point2 moving_from;
@@ -87,28 +86,28 @@ class Path2DEditor : public HBoxContainer {
void _canvas_draw();
void _node_visibility_changed();
-friend class Path2DEditorPlugin;
+ friend class Path2DEditorPlugin;
+
protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
- bool forward_gui_input(const InputEvent& p_event);
+public:
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_path2d);
Path2DEditor(EditorNode *p_editor);
};
class Path2DEditorPlugin : public EditorPlugin {
- GDCLASS( Path2DEditorPlugin, EditorPlugin );
+ GDCLASS(Path2DEditorPlugin, EditorPlugin);
Path2DEditor *path2d_editor;
EditorNode *editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return path2d_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return path2d_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "Path2D"; }
bool has_main_screen() const { return false; }
@@ -118,9 +117,6 @@ public:
Path2DEditorPlugin(EditorNode *p_node);
~Path2DEditorPlugin();
-
};
-
-
#endif // PATH_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/path_editor_plugin.cpp b/editor/plugins/path_editor_plugin.cpp
index a3df39fdaa..0b3587bc5e 100644
--- a/editor/plugins/path_editor_plugin.cpp
+++ b/editor/plugins/path_editor_plugin.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "path_editor_plugin.h"
-#include "spatial_editor_plugin.h"
-#include "scene/resources/curve.h"
#include "os/keyboard.h"
+#include "scene/resources/curve.h"
+#include "spatial_editor_plugin.h"
#if 0
String PathSpatialGizmo::get_handle_name(int p_idx) const {
diff --git a/editor/plugins/path_editor_plugin.h b/editor/plugins/path_editor_plugin.h
index fe1c5ad159..9d0f6eb9f2 100644
--- a/editor/plugins/path_editor_plugin.h
+++ b/editor/plugins/path_editor_plugin.h
@@ -29,10 +29,9 @@
#ifndef PATH_EDITOR_PLUGIN_H
#define PATH_EDITOR_PLUGIN_H
-
#include "editor/spatial_editor_gizmos.h"
#include "scene/3d/path.h"
-# if 0
+#if 0
class PathSpatialGizmo : public EditorSpatialGizmo {
GDCLASS(PathSpatialGizmo,EditorSpatialGizmo);
diff --git a/editor/plugins/polygon_2d_editor_plugin.cpp b/editor/plugins/polygon_2d_editor_plugin.cpp
index 3a41b2cb6b..8d208f9cee 100644
--- a/editor/plugins/polygon_2d_editor_plugin.cpp
+++ b/editor/plugins/polygon_2d_editor_plugin.cpp
@@ -29,66 +29,62 @@
#include "polygon_2d_editor_plugin.h"
#include "canvas_item_editor_plugin.h"
-#include "os/file_access.h"
#include "editor/editor_settings.h"
-#include "os/keyboard.h"
+#include "os/file_access.h"
#include "os/input.h"
+#include "os/keyboard.h"
void Polygon2DEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
- button_create->set_icon( get_icon("Edit","EditorIcons"));
- button_edit->set_icon( get_icon("MovePoint","EditorIcons"));
+ button_create->set_icon(get_icon("Edit", "EditorIcons"));
+ button_edit->set_icon(get_icon("MovePoint", "EditorIcons"));
button_edit->set_pressed(true);
- button_uv->set_icon( get_icon("Uv","EditorIcons"));
+ button_uv->set_icon(get_icon("Uv", "EditorIcons"));
- uv_button[UV_MODE_EDIT_POINT]->set_icon(get_icon("ToolSelect","EditorIcons"));
- uv_button[UV_MODE_MOVE]->set_icon(get_icon("ToolMove","EditorIcons"));
- uv_button[UV_MODE_ROTATE]->set_icon(get_icon("ToolRotate","EditorIcons"));
- uv_button[UV_MODE_SCALE]->set_icon(get_icon("ToolScale","EditorIcons"));
+ uv_button[UV_MODE_EDIT_POINT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
+ uv_button[UV_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
+ uv_button[UV_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
+ uv_button[UV_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
- b_snap_grid->set_icon( get_icon("Grid", "EditorIcons"));
- b_snap_enable->set_icon( get_icon("Snap", "EditorIcons"));
- uv_icon_zoom->set_texture( get_icon("Zoom", "EditorIcons"));
+ b_snap_grid->set_icon(get_icon("Grid", "EditorIcons"));
+ b_snap_enable->set_icon(get_icon("Snap", "EditorIcons"));
+ uv_icon_zoom->set_texture(get_icon("Zoom", "EditorIcons"));
get_tree()->connect("node_removed", this, "_node_removed");
} break;
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void Polygon2DEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
+ if (p_node == node) {
edit(NULL);
hide();
canvas_item_editor->get_viewport_control()->update();
}
-
}
-
void Polygon2DEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MODE_CREATE: {
- mode=MODE_CREATE;
+ mode = MODE_CREATE;
button_create->set_pressed(true);
button_edit->set_pressed(false);
} break;
case MODE_EDIT: {
- mode=MODE_EDIT;
+ mode = MODE_EDIT;
button_create->set_pressed(false);
button_edit->set_pressed(true);
} break;
@@ -101,238 +97,216 @@ void Polygon2DEditor::_menu_option(int p_option) {
return;
}
-
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
- if (uvs.size()!=points.size()) {
+ if (uvs.size() != points.size()) {
undo_redo->create_action(TTR("Create UV Map"));
- undo_redo->add_do_method(node,"set_uv",points);
- undo_redo->add_undo_method(node,"set_uv",uvs);
- undo_redo->add_do_method(uv_edit_draw,"update");
- undo_redo->add_undo_method(uv_edit_draw,"update");
+ undo_redo->add_do_method(node, "set_uv", points);
+ undo_redo->add_undo_method(node, "set_uv", uvs);
+ undo_redo->add_do_method(uv_edit_draw, "update");
+ undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
-
}
-
uv_edit->popup_centered_ratio(0.85);
} break;
case UVEDIT_POLYGON_TO_UV: {
PoolVector<Vector2> points = node->get_polygon();
- if (points.size()==0)
+ if (points.size() == 0)
break;
PoolVector<Vector2> uvs = node->get_uv();
undo_redo->create_action(TTR("Create UV Map"));
- undo_redo->add_do_method(node,"set_uv",points);
- undo_redo->add_undo_method(node,"set_uv",uvs);
- undo_redo->add_do_method(uv_edit_draw,"update");
- undo_redo->add_undo_method(uv_edit_draw,"update");
+ undo_redo->add_do_method(node, "set_uv", points);
+ undo_redo->add_undo_method(node, "set_uv", uvs);
+ undo_redo->add_do_method(uv_edit_draw, "update");
+ undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
-
} break;
case UVEDIT_UV_TO_POLYGON: {
PoolVector<Vector2> points = node->get_polygon();
PoolVector<Vector2> uvs = node->get_uv();
- if (uvs.size()==0)
+ if (uvs.size() == 0)
break;
undo_redo->create_action(TTR("Create UV Map"));
- undo_redo->add_do_method(node,"set_polygon",uvs);
- undo_redo->add_undo_method(node,"set_polygon",points);
- undo_redo->add_do_method(uv_edit_draw,"update");
- undo_redo->add_undo_method(uv_edit_draw,"update");
+ undo_redo->add_do_method(node, "set_polygon", uvs);
+ undo_redo->add_undo_method(node, "set_polygon", points);
+ undo_redo->add_do_method(uv_edit_draw, "update");
+ undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
} break;
case UVEDIT_UV_CLEAR: {
PoolVector<Vector2> uvs = node->get_uv();
- if (uvs.size()==0)
+ if (uvs.size() == 0)
break;
undo_redo->create_action(TTR("Create UV Map"));
- undo_redo->add_do_method(node,"set_uv",PoolVector<Vector2>());
- undo_redo->add_undo_method(node,"set_uv",uvs);
- undo_redo->add_do_method(uv_edit_draw,"update");
- undo_redo->add_undo_method(uv_edit_draw,"update");
+ undo_redo->add_do_method(node, "set_uv", PoolVector<Vector2>());
+ undo_redo->add_undo_method(node, "set_uv", uvs);
+ undo_redo->add_do_method(uv_edit_draw, "update");
+ undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
} break;
-
-
}
}
-void Polygon2DEditor::_set_use_snap(bool p_use)
-{
- use_snap=p_use;
+void Polygon2DEditor::_set_use_snap(bool p_use) {
+ use_snap = p_use;
}
-void Polygon2DEditor::_set_show_grid(bool p_show)
-{
- snap_show_grid=p_show;
+void Polygon2DEditor::_set_show_grid(bool p_show) {
+ snap_show_grid = p_show;
uv_edit_draw->update();
}
-void Polygon2DEditor::_set_snap_off_x(float p_val)
-{
- snap_offset.x=p_val;
+void Polygon2DEditor::_set_snap_off_x(float p_val) {
+ snap_offset.x = p_val;
uv_edit_draw->update();
}
-void Polygon2DEditor::_set_snap_off_y(float p_val)
-{
- snap_offset.y=p_val;
+void Polygon2DEditor::_set_snap_off_y(float p_val) {
+ snap_offset.y = p_val;
uv_edit_draw->update();
}
-void Polygon2DEditor::_set_snap_step_x(float p_val)
-{
- snap_step.x=p_val;
+void Polygon2DEditor::_set_snap_step_x(float p_val) {
+ snap_step.x = p_val;
uv_edit_draw->update();
}
-void Polygon2DEditor::_set_snap_step_y(float p_val)
-{
- snap_step.y=p_val;
+void Polygon2DEditor::_set_snap_step_y(float p_val) {
+ snap_step.y = p_val;
uv_edit_draw->update();
}
void Polygon2DEditor::_wip_close() {
undo_redo->create_action(TTR("Create Poly"));
- undo_redo->add_undo_method(node,"set_polygon",node->get_polygon());
- undo_redo->add_do_method(node,"set_polygon",wip);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_undo_method(node, "set_polygon", node->get_polygon());
+ undo_redo->add_do_method(node, "set_polygon", wip);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
wip.clear();
- wip_active=false;
- mode=MODE_EDIT;
+ wip_active = false;
+ mode = MODE_EDIT;
button_edit->set_pressed(true);
button_create->set_pressed(false);
- edited_point=-1;
+ edited_point = -1;
}
-bool Polygon2DEditor::forward_gui_input(const InputEvent& p_event) {
+bool Polygon2DEditor::forward_gui_input(const InputEvent &p_event) {
- if (node==NULL)
+ if (node == NULL)
return false;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
-
- Vector2 gpoint = Point2(mb.x,mb.y);
+ Vector2 gpoint = Point2(mb.x, mb.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
cpoint = node->get_global_transform().affine_inverse().xform(cpoint);
-
Vector<Vector2> poly = Variant(node->get_polygon());
//first check if a point is to be added (segment split)
- real_t grab_treshold=EDITOR_DEF("editors/poly_editor/point_grab_radius",8);
-
- switch(mode) {
+ real_t grab_treshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);
+ switch (mode) {
case MODE_CREATE: {
- if (mb.button_index==BUTTON_LEFT && mb.pressed) {
-
+ if (mb.button_index == BUTTON_LEFT && mb.pressed) {
if (!wip_active) {
wip.clear();
- wip.push_back( cpoint-node->get_offset() );
- wip_active=true;
- edited_point_pos=cpoint;
+ wip.push_back(cpoint - node->get_offset());
+ wip_active = true;
+ edited_point_pos = cpoint;
canvas_item_editor->get_viewport_control()->update();
- edited_point=1;
+ edited_point = 1;
return true;
} else {
-
- if (wip.size()>1 && xform.xform(wip[0]+node->get_offset()).distance_to(gpoint)<grab_treshold) {
+ if (wip.size() > 1 && xform.xform(wip[0] + node->get_offset()).distance_to(gpoint) < grab_treshold) {
//wip closed
_wip_close();
return true;
} else {
- wip.push_back( cpoint-node->get_offset() );
- edited_point=wip.size();
+ wip.push_back(cpoint - node->get_offset());
+ edited_point = wip.size();
canvas_item_editor->get_viewport_control()->update();
return true;
//add wip point
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && wip_active) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && wip_active) {
_wip_close();
}
-
-
} break;
case MODE_EDIT: {
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (mb.mod.control) {
-
if (poly.size() < 3) {
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_undo_method(node,"set_polygon",poly);
+ undo_redo->add_undo_method(node, "set_polygon", poly);
poly.push_back(cpoint);
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
//search edges
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 points[2] ={ xform.xform(poly[i]+node->get_offset()),
- xform.xform(poly[(i+1)%poly.size()]+node->get_offset()) };
+ Vector2 points[2] = { xform.xform(poly[i] + node->get_offset()),
+ xform.xform(poly[(i + 1) % poly.size()] + node->get_offset()) };
- Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint,points);
- if (cp.distance_squared_to(points[0])<CMP_EPSILON2 || cp.distance_squared_to(points[1])<CMP_EPSILON2)
+ Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
+ if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
continue; //not valid to reuse point
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- poly.insert(closest_idx+1,xform.affine_inverse().xform(closest_pos)-node->get_offset());
- edited_point=closest_idx+1;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ poly.insert(closest_idx + 1, xform.affine_inverse().xform(closest_pos) - node->get_offset());
+ edited_point = closest_idx + 1;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
node->set_polygon(Variant(poly));
canvas_item_editor->get_viewport_control()->update();
return true;
@@ -341,106 +315,95 @@ bool Polygon2DEditor::forward_gui_input(const InputEvent& p_event) {
//look for points to move
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]+node->get_offset());
+ Vector2 cp = xform.xform(poly[i] + node->get_offset());
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
+ if (closest_idx >= 0) {
- pre_move_edit=poly;
- edited_point=closest_idx;
- edited_point_pos=xform.affine_inverse().xform(closest_pos);
+ pre_move_edit = poly;
+ edited_point = closest_idx;
+ edited_point_pos = xform.affine_inverse().xform(closest_pos);
canvas_item_editor->get_viewport_control()->update();
return true;
}
}
} else {
- if (edited_point!=-1) {
+ if (edited_point != -1) {
//apply
- ERR_FAIL_INDEX_V(edited_point,poly.size(),false);
- poly[edited_point]=edited_point_pos-node->get_offset();
+ ERR_FAIL_INDEX_V(edited_point, poly.size(), false);
+ poly[edited_point] = edited_point_pos - node->get_offset();
undo_redo->create_action(TTR("Edit Poly"));
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_undo_method(node,"set_polygon",pre_move_edit);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_undo_method(node, "set_polygon", pre_move_edit);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
- edited_point=-1;
+ edited_point = -1;
return true;
}
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed && edited_point==-1) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed && edited_point == -1) {
-
-
- int closest_idx=-1;
+ int closest_idx = -1;
Vector2 closest_pos;
- real_t closest_dist=1e10;
- for(int i=0;i<poly.size();i++) {
+ real_t closest_dist = 1e10;
+ for (int i = 0; i < poly.size(); i++) {
- Vector2 cp =xform.xform(poly[i]+node->get_offset());
+ Vector2 cp = xform.xform(poly[i] + node->get_offset());
real_t d = cp.distance_to(gpoint);
- if (d<closest_dist && d<grab_treshold) {
- closest_dist=d;
- closest_pos=cp;
- closest_idx=i;
+ if (d < closest_dist && d < grab_treshold) {
+ closest_dist = d;
+ closest_pos = cp;
+ closest_idx = i;
}
-
}
- if (closest_idx>=0) {
-
+ if (closest_idx >= 0) {
undo_redo->create_action(TTR("Edit Poly (Remove Point)"));
- undo_redo->add_undo_method(node,"set_polygon",poly);
+ undo_redo->add_undo_method(node, "set_polygon", poly);
poly.remove(closest_idx);
- undo_redo->add_do_method(node,"set_polygon",poly);
- undo_redo->add_do_method(canvas_item_editor->get_viewport_control(),"update");
- undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(),"update");
+ undo_redo->add_do_method(node, "set_polygon", poly);
+ undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
+ undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
undo_redo->commit_action();
return true;
}
-
}
-
-
} break;
}
-
-
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- if (edited_point!=-1 && (wip_active || mm.button_mask&BUTTON_MASK_LEFT)) {
+ if (edited_point != -1 && (wip_active || mm.button_mask & BUTTON_MASK_LEFT)) {
- Vector2 gpoint = Point2(mm.x,mm.y);
+ Vector2 gpoint = Point2(mm.x, mm.y);
Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
- cpoint=canvas_item_editor->snap_point(cpoint);
+ cpoint = canvas_item_editor->snap_point(cpoint);
edited_point_pos = node->get_global_transform().affine_inverse().xform(cpoint);
canvas_item_editor->get_viewport_control()->update();
-
}
} break;
@@ -458,170 +421,159 @@ void Polygon2DEditor::_canvas_draw() {
Vector<Vector2> poly;
if (wip_active)
- poly=wip;
+ poly = wip;
else
- poly=Variant(node->get_polygon());
-
+ poly = Variant(node->get_polygon());
Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();
- Ref<Texture> handle= get_icon("EditorHandle","EditorIcons");
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
- for(int i=0;i<poly.size();i++) {
+ for (int i = 0; i < poly.size(); i++) {
-
- Vector2 p,p2;
- p = i==edited_point ? edited_point_pos : (poly[i]+node->get_offset());
- if ((wip_active && i==poly.size()-1) || (((i+1)%poly.size())==edited_point))
- p2=edited_point_pos;
+ Vector2 p, p2;
+ p = i == edited_point ? edited_point_pos : (poly[i] + node->get_offset());
+ if ((wip_active && i == poly.size() - 1) || (((i + 1) % poly.size()) == edited_point))
+ p2 = edited_point_pos;
else
- p2 = poly[(i+1)%poly.size()]+node->get_offset();
+ p2 = poly[(i + 1) % poly.size()] + node->get_offset();
Vector2 point = xform.xform(p);
Vector2 next_point = xform.xform(p2);
- Color col=Color(1,0.3,0.1,0.8);
- vpc->draw_line(point,next_point,col,2);
- vpc->draw_texture(handle,point-handle->get_size()*0.5);
+ Color col = Color(1, 0.3, 0.1, 0.8);
+ vpc->draw_line(point, next_point, col, 2);
+ vpc->draw_texture(handle, point - handle->get_size() * 0.5);
}
}
-
void Polygon2DEditor::_uv_mode(int p_mode) {
-
- uv_mode=UVMode(p_mode);
- for(int i=0;i<UV_MODE_MAX;i++) {
- uv_button[i]->set_pressed(p_mode==i);
+ uv_mode = UVMode(p_mode);
+ for (int i = 0; i < UV_MODE_MAX; i++) {
+ uv_button[i]->set_pressed(p_mode == i);
}
}
-
-void Polygon2DEditor::_uv_input(const InputEvent& p_input) {
-
+void Polygon2DEditor::_uv_input(const InputEvent &p_input) {
Transform2D mtx;
- mtx.elements[2]=-uv_draw_ofs;
- mtx.scale_basis(Vector2(uv_draw_zoom,uv_draw_zoom));
-
- if (p_input.type==InputEvent::MOUSE_BUTTON) {
+ mtx.elements[2] = -uv_draw_ofs;
+ mtx.scale_basis(Vector2(uv_draw_zoom, uv_draw_zoom));
+ if (p_input.type == InputEvent::MOUSE_BUTTON) {
- const InputEventMouseButton &mb=p_input.mouse_button;
-
- if (mb.button_index==BUTTON_LEFT) {
+ const InputEventMouseButton &mb = p_input.mouse_button;
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
- uv_drag_from=Vector2(mb.x,mb.y);
- uv_drag=true;
- uv_prev=node->get_uv();
- uv_move_current=uv_mode;
- if (uv_move_current==UV_MODE_EDIT_POINT) {
+ uv_drag_from = Vector2(mb.x, mb.y);
+ uv_drag = true;
+ uv_prev = node->get_uv();
+ uv_move_current = uv_mode;
+ if (uv_move_current == UV_MODE_EDIT_POINT) {
if (mb.mod.shift && mb.mod.command)
- uv_move_current=UV_MODE_SCALE;
+ uv_move_current = UV_MODE_SCALE;
else if (mb.mod.shift)
- uv_move_current=UV_MODE_MOVE;
+ uv_move_current = UV_MODE_MOVE;
else if (mb.mod.command)
- uv_move_current=UV_MODE_ROTATE;
+ uv_move_current = UV_MODE_ROTATE;
}
- if (uv_move_current==UV_MODE_EDIT_POINT) {
+ if (uv_move_current == UV_MODE_EDIT_POINT) {
- uv_drag_index=-1;
- for(int i=0;i<uv_prev.size();i++) {
+ uv_drag_index = -1;
+ for (int i = 0; i < uv_prev.size(); i++) {
- Vector2 tuv=mtx.xform(uv_prev[i]);
- if (tuv.distance_to(Vector2(mb.x,mb.y))<8) {
- uv_drag_from=tuv;
- uv_drag_index=i;
+ Vector2 tuv = mtx.xform(uv_prev[i]);
+ if (tuv.distance_to(Vector2(mb.x, mb.y)) < 8) {
+ uv_drag_from = tuv;
+ uv_drag_index = i;
}
}
- if (uv_drag_index==-1) {
- uv_drag=false;
+ if (uv_drag_index == -1) {
+ uv_drag = false;
}
-
}
} else if (uv_drag) {
undo_redo->create_action(TTR("Transform UV Map"));
- undo_redo->add_do_method(node,"set_uv",node->get_uv());
- undo_redo->add_undo_method(node,"set_uv",uv_prev);
- undo_redo->add_do_method(uv_edit_draw,"update");
- undo_redo->add_undo_method(uv_edit_draw,"update");
+ undo_redo->add_do_method(node, "set_uv", node->get_uv());
+ undo_redo->add_undo_method(node, "set_uv", uv_prev);
+ undo_redo->add_do_method(uv_edit_draw, "update");
+ undo_redo->add_undo_method(uv_edit_draw, "update");
undo_redo->commit_action();
- uv_drag=false;
+ uv_drag = false;
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed) {
if (uv_drag) {
- uv_drag=false;
+ uv_drag = false;
node->set_uv(uv_prev);
uv_edit_draw->update();
}
- } else if (mb.button_index==BUTTON_WHEEL_UP && mb.pressed) {
+ } else if (mb.button_index == BUTTON_WHEEL_UP && mb.pressed) {
- uv_zoom->set_value( uv_zoom->get_value()/0.9 );
- } else if (mb.button_index==BUTTON_WHEEL_DOWN && mb.pressed) {
+ uv_zoom->set_value(uv_zoom->get_value() / 0.9);
+ } else if (mb.button_index == BUTTON_WHEEL_DOWN && mb.pressed) {
- uv_zoom->set_value( uv_zoom->get_value()*0.9);
+ uv_zoom->set_value(uv_zoom->get_value() * 0.9);
}
- } else if (p_input.type==InputEvent::MOUSE_MOTION) {
+ } else if (p_input.type == InputEvent::MOUSE_MOTION) {
- const InputEventMouseMotion &mm=p_input.mouse_motion;
+ const InputEventMouseMotion &mm = p_input.mouse_motion;
- if (mm.button_mask&BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
+ if (mm.button_mask & BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
- Vector2 drag(mm.relative_x,mm.relative_y);
- uv_hscroll->set_value( uv_hscroll->get_value()-drag.x );
- uv_vscroll->set_value( uv_vscroll->get_value()-drag.y );
+ Vector2 drag(mm.relative_x, mm.relative_y);
+ uv_hscroll->set_value(uv_hscroll->get_value() - drag.x);
+ uv_vscroll->set_value(uv_vscroll->get_value() - drag.y);
} else if (uv_drag) {
- Vector2 uv_drag_to=snap_point(Vector2(mm.x,mm.y));
+ Vector2 uv_drag_to = snap_point(Vector2(mm.x, mm.y));
Vector2 drag = mtx.affine_inverse().xform(uv_drag_to) - mtx.affine_inverse().xform(uv_drag_from);
-
- switch(uv_move_current) {
+ switch (uv_move_current) {
case UV_MODE_EDIT_POINT: {
- PoolVector<Vector2> uv_new=uv_prev;
- uv_new.set( uv_drag_index, uv_new[uv_drag_index]+drag );
+ PoolVector<Vector2> uv_new = uv_prev;
+ uv_new.set(uv_drag_index, uv_new[uv_drag_index] + drag);
node->set_uv(uv_new);
} break;
case UV_MODE_MOVE: {
- PoolVector<Vector2> uv_new=uv_prev;
- for(int i=0;i<uv_new.size();i++)
- uv_new.set( i, uv_new[i]+drag );
+ PoolVector<Vector2> uv_new = uv_prev;
+ for (int i = 0; i < uv_new.size(); i++)
+ uv_new.set(i, uv_new[i] + drag);
node->set_uv(uv_new);
-
} break;
case UV_MODE_ROTATE: {
Vector2 center;
- PoolVector<Vector2> uv_new=uv_prev;
+ PoolVector<Vector2> uv_new = uv_prev;
- for(int i=0;i<uv_new.size();i++)
- center+=uv_prev[i];
- center/=uv_new.size();
+ for (int i = 0; i < uv_new.size(); i++)
+ center += uv_prev[i];
+ center /= uv_new.size();
- float angle = (uv_drag_from - mtx.xform(center)).normalized().angle_to( (uv_drag_to - mtx.xform(center)).normalized() );
+ float angle = (uv_drag_from - mtx.xform(center)).normalized().angle_to((uv_drag_to - mtx.xform(center)).normalized());
- for(int i=0;i<uv_new.size();i++) {
+ for (int i = 0; i < uv_new.size(); i++) {
Vector2 rel = uv_prev[i] - center;
- rel=rel.rotated(angle);
- uv_new.set(i,center+rel);
+ rel = rel.rotated(angle);
+ uv_new.set(i, center + rel);
}
node->set_uv(uv_new);
@@ -630,47 +582,41 @@ void Polygon2DEditor::_uv_input(const InputEvent& p_input) {
case UV_MODE_SCALE: {
Vector2 center;
- PoolVector<Vector2> uv_new=uv_prev;
+ PoolVector<Vector2> uv_new = uv_prev;
- for(int i=0;i<uv_new.size();i++)
- center+=uv_prev[i];
- center/=uv_new.size();
+ for (int i = 0; i < uv_new.size(); i++)
+ center += uv_prev[i];
+ center /= uv_new.size();
float from_dist = uv_drag_from.distance_to(mtx.xform(center));
float to_dist = uv_drag_to.distance_to(mtx.xform(center));
- if (from_dist<2)
+ if (from_dist < 2)
break;
- float scale = to_dist/from_dist;
+ float scale = to_dist / from_dist;
-
- for(int i=0;i<uv_new.size();i++) {
+ for (int i = 0; i < uv_new.size(); i++) {
Vector2 rel = uv_prev[i] - center;
- rel=rel*scale;
- uv_new.set(i,center+rel);
+ rel = rel * scale;
+ uv_new.set(i, center + rel);
}
node->set_uv(uv_new);
} break;
-
-
}
uv_edit_draw->update();
}
-
}
-
}
-
void Polygon2DEditor::_uv_scroll_changed(float) {
if (updating_uv_scroll)
return;
- uv_draw_ofs.x=uv_hscroll->get_value();
- uv_draw_ofs.y=uv_vscroll->get_value();
- uv_draw_zoom=uv_zoom->get_value();
+ uv_draw_ofs.x = uv_hscroll->get_value();
+ uv_draw_ofs.y = uv_vscroll->get_value();
+ uv_draw_zoom = uv_zoom->get_value();
uv_edit_draw->update();
}
@@ -681,115 +627,110 @@ void Polygon2DEditor::_uv_draw() {
return;
Transform2D mtx;
- mtx.elements[2]=-uv_draw_ofs;
- mtx.scale_basis(Vector2(uv_draw_zoom,uv_draw_zoom));
+ mtx.elements[2] = -uv_draw_ofs;
+ mtx.scale_basis(Vector2(uv_draw_zoom, uv_draw_zoom));
- VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(),mtx);
- uv_edit_draw->draw_texture(base_tex,Point2());
- VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(),Transform2D());
+ VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), mtx);
+ uv_edit_draw->draw_texture(base_tex, Point2());
+ VS::get_singleton()->canvas_item_add_set_transform(uv_edit_draw->get_canvas_item(), Transform2D());
if (snap_show_grid) {
Size2 s = uv_edit_draw->get_size();
int last_cell;
- if (snap_step.x!=0) {
- for(int i=0;i<s.width;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i,0)).x-snap_offset.x)/snap_step.x));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- uv_edit_draw->draw_line(Point2(i,0),Point2(i,s.height),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ if (snap_step.x != 0) {
+ for (int i = 0; i < s.width; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ uv_edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
- if (snap_step.y!=0) {
- for(int i=0;i<s.height;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0,i)).y-snap_offset.y)/snap_step.y));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- uv_edit_draw->draw_line(Point2(0,i),Point2(s.width,i),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ if (snap_step.y != 0) {
+ for (int i = 0; i < s.height; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ uv_edit_draw->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
}
PoolVector<Vector2> uvs = node->get_uv();
- Ref<Texture> handle = get_icon("EditorHandle","EditorIcons");
+ Ref<Texture> handle = get_icon("EditorHandle", "EditorIcons");
- Rect2 rect(Point2(),mtx.basis_xform(base_tex->get_size()));
+ Rect2 rect(Point2(), mtx.basis_xform(base_tex->get_size()));
rect.expand_to(mtx.basis_xform(uv_edit_draw->get_size()));
- for(int i=0;i<uvs.size();i++) {
+ for (int i = 0; i < uvs.size(); i++) {
- int next = (i+1)%uvs.size();
- uv_edit_draw->draw_line(mtx.xform(uvs[i]),mtx.xform(uvs[next]),Color(0.9,0.5,0.5),2);
- uv_edit_draw->draw_texture(handle,mtx.xform(uvs[i])-handle->get_size()*0.5);
+ int next = (i + 1) % uvs.size();
+ uv_edit_draw->draw_line(mtx.xform(uvs[i]), mtx.xform(uvs[next]), Color(0.9, 0.5, 0.5), 2);
+ uv_edit_draw->draw_texture(handle, mtx.xform(uvs[i]) - handle->get_size() * 0.5);
rect.expand_to(mtx.basis_xform(uvs[i]));
}
- rect=rect.grow(200);
- updating_uv_scroll=true;
+ rect = rect.grow(200);
+ updating_uv_scroll = true;
uv_hscroll->set_min(rect.pos.x);
- uv_hscroll->set_max(rect.pos.x+rect.size.x);
+ uv_hscroll->set_max(rect.pos.x + rect.size.x);
uv_hscroll->set_page(uv_edit_draw->get_size().x);
uv_hscroll->set_value(uv_draw_ofs.x);
uv_hscroll->set_step(0.001);
uv_vscroll->set_min(rect.pos.y);
- uv_vscroll->set_max(rect.pos.y+rect.size.y);
+ uv_vscroll->set_max(rect.pos.y + rect.size.y);
uv_vscroll->set_page(uv_edit_draw->get_size().y);
uv_vscroll->set_value(uv_draw_ofs.y);
uv_vscroll->set_step(0.001);
- updating_uv_scroll=false;
-
+ updating_uv_scroll = false;
}
void Polygon2DEditor::edit(Node *p_collision_polygon) {
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton();
+ canvas_item_editor = CanvasItemEditor::get_singleton();
}
if (p_collision_polygon) {
- node=p_collision_polygon->cast_to<Polygon2D>();
- if (!canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->connect("draw",this,"_canvas_draw");
+ node = p_collision_polygon->cast_to<Polygon2D>();
+ if (!canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->connect("draw", this, "_canvas_draw");
wip.clear();
- wip_active=false;
- edited_point=-1;
+ wip_active = false;
+ edited_point = -1;
} else {
- node=NULL;
-
- if (canvas_item_editor->get_viewport_control()->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->get_viewport_control()->disconnect("draw",this,"_canvas_draw");
+ node = NULL;
+ if (canvas_item_editor->get_viewport_control()->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->get_viewport_control()->disconnect("draw", this, "_canvas_draw");
}
-
}
void Polygon2DEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_option"),&Polygon2DEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&Polygon2DEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_uv_mode"),&Polygon2DEditor::_uv_mode);
- ClassDB::bind_method(D_METHOD("_uv_draw"),&Polygon2DEditor::_uv_draw);
- ClassDB::bind_method(D_METHOD("_uv_input"),&Polygon2DEditor::_uv_input);
- ClassDB::bind_method(D_METHOD("_uv_scroll_changed"),&Polygon2DEditor::_uv_scroll_changed);
- ClassDB::bind_method(D_METHOD("_node_removed"),&Polygon2DEditor::_node_removed);
- ClassDB::bind_method(D_METHOD("_set_use_snap"),&Polygon2DEditor::_set_use_snap);
- ClassDB::bind_method(D_METHOD("_set_show_grid"),&Polygon2DEditor::_set_show_grid);
- ClassDB::bind_method(D_METHOD("_set_snap_off_x"),&Polygon2DEditor::_set_snap_off_x);
- ClassDB::bind_method(D_METHOD("_set_snap_off_y"),&Polygon2DEditor::_set_snap_off_y);
- ClassDB::bind_method(D_METHOD("_set_snap_step_x"),&Polygon2DEditor::_set_snap_step_x);
- ClassDB::bind_method(D_METHOD("_set_snap_step_y"),&Polygon2DEditor::_set_snap_step_y);
-
-
+ ClassDB::bind_method(D_METHOD("_menu_option"), &Polygon2DEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &Polygon2DEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_uv_mode"), &Polygon2DEditor::_uv_mode);
+ ClassDB::bind_method(D_METHOD("_uv_draw"), &Polygon2DEditor::_uv_draw);
+ ClassDB::bind_method(D_METHOD("_uv_input"), &Polygon2DEditor::_uv_input);
+ ClassDB::bind_method(D_METHOD("_uv_scroll_changed"), &Polygon2DEditor::_uv_scroll_changed);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &Polygon2DEditor::_node_removed);
+ ClassDB::bind_method(D_METHOD("_set_use_snap"), &Polygon2DEditor::_set_use_snap);
+ ClassDB::bind_method(D_METHOD("_set_show_grid"), &Polygon2DEditor::_set_show_grid);
+ ClassDB::bind_method(D_METHOD("_set_snap_off_x"), &Polygon2DEditor::_set_snap_off_x);
+ ClassDB::bind_method(D_METHOD("_set_snap_off_y"), &Polygon2DEditor::_set_snap_off_y);
+ ClassDB::bind_method(D_METHOD("_set_snap_step_x"), &Polygon2DEditor::_set_snap_step_x);
+ ClassDB::bind_method(D_METHOD("_set_snap_step_y"), &Polygon2DEditor::_set_snap_step_y);
}
inline float _snap_scalar(float p_offset, float p_step, float p_target) {
@@ -798,8 +739,8 @@ inline float _snap_scalar(float p_offset, float p_step, float p_target) {
Vector2 Polygon2DEditor::snap_point(Vector2 p_target) const {
if (use_snap) {
- p_target.x = _snap_scalar(snap_offset.x*uv_draw_zoom-uv_draw_ofs.x, snap_step.x*uv_draw_zoom, p_target.x);
- p_target.y = _snap_scalar(snap_offset.y*uv_draw_zoom-uv_draw_ofs.y, snap_step.y*uv_draw_zoom, p_target.y);
+ p_target.x = _snap_scalar(snap_offset.x * uv_draw_zoom - uv_draw_ofs.x, snap_step.x * uv_draw_zoom, p_target.x);
+ p_target.y = _snap_scalar(snap_offset.y * uv_draw_zoom - uv_draw_ofs.y, snap_step.y * uv_draw_zoom, p_target.y);
}
return p_target;
@@ -807,31 +748,31 @@ Vector2 Polygon2DEditor::snap_point(Vector2 p_target) const {
Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
- node=NULL;
- canvas_item_editor=NULL;
- editor=p_editor;
+ node = NULL;
+ canvas_item_editor = NULL;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- snap_step=Vector2(10,10);
- use_snap=false;
- snap_show_grid=false;
+ snap_step = Vector2(10, 10);
+ use_snap = false;
+ snap_show_grid = false;
- add_child( memnew( VSeparator ));
- button_create = memnew( ToolButton );
+ add_child(memnew(VSeparator));
+ button_create = memnew(ToolButton);
add_child(button_create);
- button_create->connect("pressed",this,"_menu_option",varray(MODE_CREATE));
+ button_create->connect("pressed", this, "_menu_option", varray(MODE_CREATE));
button_create->set_toggle_mode(true);
- button_edit = memnew( ToolButton );
+ button_edit = memnew(ToolButton);
add_child(button_edit);
- button_edit->connect("pressed",this,"_menu_option",varray(MODE_EDIT));
+ button_edit->connect("pressed", this, "_menu_option", varray(MODE_EDIT));
button_edit->set_toggle_mode(true);
- button_uv = memnew( ToolButton );
+ button_uv = memnew(ToolButton);
add_child(button_uv);
- button_uv->connect("pressed",this,"_menu_option",varray(MODE_EDIT_UV));
+ button_uv->connect("pressed", this, "_menu_option", varray(MODE_EDIT_UV));
- //add_constant_override("separation",0);
+//add_constant_override("separation",0);
#if 0
options = memnew( MenuButton );
@@ -843,73 +784,73 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
#endif
mode = MODE_EDIT;
- wip_active=false;
+ wip_active = false;
- uv_mode=UV_MODE_EDIT_POINT;
- uv_edit = memnew( AcceptDialog );
+ uv_mode = UV_MODE_EDIT_POINT;
+ uv_edit = memnew(AcceptDialog);
add_child(uv_edit);
uv_edit->set_title(TTR("Polygon 2D UV Editor"));
- uv_edit->set_self_modulate(Color(1,1,1,0.9));
+ uv_edit->set_self_modulate(Color(1, 1, 1, 0.9));
- VBoxContainer *uv_main_vb = memnew( VBoxContainer );
+ VBoxContainer *uv_main_vb = memnew(VBoxContainer);
uv_edit->add_child(uv_main_vb);
//uv_edit->set_child_rect(uv_main_vb);
- HBoxContainer *uv_mode_hb = memnew( HBoxContainer );
+ HBoxContainer *uv_mode_hb = memnew(HBoxContainer);
uv_main_vb->add_child(uv_mode_hb);
- for(int i=0;i<UV_MODE_MAX;i++) {
+ for (int i = 0; i < UV_MODE_MAX; i++) {
- uv_button[i]=memnew( ToolButton );
+ uv_button[i] = memnew(ToolButton);
uv_button[i]->set_toggle_mode(true);
uv_mode_hb->add_child(uv_button[i]);
- uv_button[i]->connect("pressed",this,"_uv_mode",varray(i));
+ uv_button[i]->connect("pressed", this, "_uv_mode", varray(i));
uv_button[i]->set_focus_mode(FOCUS_NONE);
}
- uv_button[0]->set_tooltip(TTR("Move Point")+"\n"+TTR("Ctrl: Rotate")+"\n"+TTR("Shift: Move All")+"\n"+TTR("Shift+Ctrl: Scale"));
+ uv_button[0]->set_tooltip(TTR("Move Point") + "\n" + TTR("Ctrl: Rotate") + "\n" + TTR("Shift: Move All") + "\n" + TTR("Shift+Ctrl: Scale"));
uv_button[1]->set_tooltip(TTR("Move Polygon"));
uv_button[2]->set_tooltip(TTR("Rotate Polygon"));
uv_button[3]->set_tooltip(TTR("Scale Polygon"));
uv_button[0]->set_pressed(true);
- HBoxContainer *uv_main_hb = memnew( HBoxContainer );
+ HBoxContainer *uv_main_hb = memnew(HBoxContainer);
uv_main_vb->add_child(uv_main_hb);
- uv_edit_draw = memnew( Control );
+ uv_edit_draw = memnew(Control);
uv_main_hb->add_child(uv_edit_draw);
uv_main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
uv_edit_draw->set_h_size_flags(SIZE_EXPAND_FILL);
- uv_menu = memnew( MenuButton );
+ uv_menu = memnew(MenuButton);
uv_mode_hb->add_child(uv_menu);
uv_menu->set_text(TTR("Edit"));
- uv_menu->get_popup()->add_item(TTR("Polygon->UV"),UVEDIT_POLYGON_TO_UV);
- uv_menu->get_popup()->add_item(TTR("UV->Polygon"),UVEDIT_UV_TO_POLYGON);
+ uv_menu->get_popup()->add_item(TTR("Polygon->UV"), UVEDIT_POLYGON_TO_UV);
+ uv_menu->get_popup()->add_item(TTR("UV->Polygon"), UVEDIT_UV_TO_POLYGON);
uv_menu->get_popup()->add_separator();
- uv_menu->get_popup()->add_item(TTR("Clear UV"),UVEDIT_UV_CLEAR);
- uv_menu->get_popup()->connect("id_pressed",this,"_menu_option");
+ uv_menu->get_popup()->add_item(TTR("Clear UV"), UVEDIT_UV_CLEAR);
+ uv_menu->get_popup()->connect("id_pressed", this, "_menu_option");
- uv_mode_hb->add_child( memnew( VSeparator ));
+ uv_mode_hb->add_child(memnew(VSeparator));
- b_snap_enable = memnew( ToolButton );
+ b_snap_enable = memnew(ToolButton);
uv_mode_hb->add_child(b_snap_enable);
b_snap_enable->set_text(TTR("Snap"));
b_snap_enable->set_focus_mode(FOCUS_NONE);
b_snap_enable->set_toggle_mode(true);
b_snap_enable->set_pressed(use_snap);
b_snap_enable->set_tooltip(TTR("Enable Snap"));
- b_snap_enable->connect("toggled",this,"_set_use_snap");
+ b_snap_enable->connect("toggled", this, "_set_use_snap");
- b_snap_grid = memnew( ToolButton );
+ b_snap_grid = memnew(ToolButton);
uv_mode_hb->add_child(b_snap_grid);
b_snap_grid->set_text(TTR("Grid"));
b_snap_grid->set_focus_mode(FOCUS_NONE);
b_snap_grid->set_toggle_mode(true);
b_snap_grid->set_pressed(snap_show_grid);
b_snap_grid->set_tooltip(TTR("Show Grid"));
- b_snap_grid->connect("toggled",this,"_set_show_grid");
+ b_snap_grid->connect("toggled", this, "_set_show_grid");
- uv_mode_hb->add_child( memnew( VSeparator ));
- uv_mode_hb->add_child( memnew( Label(TTR("Grid Offset:")) ) );
+ uv_mode_hb->add_child(memnew(VSeparator));
+ uv_mode_hb->add_child(memnew(Label(TTR("Grid Offset:"))));
- SpinBox *sb_off_x = memnew( SpinBox );
+ SpinBox *sb_off_x = memnew(SpinBox);
sb_off_x->set_min(-256);
sb_off_x->set_max(256);
sb_off_x->set_step(1);
@@ -918,7 +859,7 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
sb_off_x->connect("value_changed", this, "_set_snap_off_x");
uv_mode_hb->add_child(sb_off_x);
- SpinBox *sb_off_y = memnew( SpinBox );
+ SpinBox *sb_off_y = memnew(SpinBox);
sb_off_y->set_min(-256);
sb_off_y->set_max(256);
sb_off_y->set_step(1);
@@ -927,10 +868,10 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
sb_off_y->connect("value_changed", this, "_set_snap_off_y");
uv_mode_hb->add_child(sb_off_y);
- uv_mode_hb->add_child( memnew( VSeparator ));
- uv_mode_hb->add_child( memnew( Label(TTR("Grid Step:")) ) );
+ uv_mode_hb->add_child(memnew(VSeparator));
+ uv_mode_hb->add_child(memnew(Label(TTR("Grid Step:"))));
- SpinBox *sb_step_x = memnew( SpinBox );
+ SpinBox *sb_step_x = memnew(SpinBox);
sb_step_x->set_min(-256);
sb_step_x->set_max(256);
sb_step_x->set_step(1);
@@ -939,7 +880,7 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
sb_step_x->connect("value_changed", this, "_set_snap_step_x");
uv_mode_hb->add_child(sb_step_x);
- SpinBox *sb_step_y = memnew( SpinBox );
+ SpinBox *sb_step_y = memnew(SpinBox);
sb_step_y->set_min(-256);
sb_step_y->set_max(256);
sb_step_y->set_step(1);
@@ -948,49 +889,44 @@ Polygon2DEditor::Polygon2DEditor(EditorNode *p_editor) {
sb_step_y->connect("value_changed", this, "_set_snap_step_y");
uv_mode_hb->add_child(sb_step_y);
- uv_mode_hb->add_child( memnew( VSeparator ));
- uv_icon_zoom = memnew( TextureRect );
- uv_mode_hb->add_child( uv_icon_zoom );
- uv_zoom = memnew( HSlider );
+ uv_mode_hb->add_child(memnew(VSeparator));
+ uv_icon_zoom = memnew(TextureRect);
+ uv_mode_hb->add_child(uv_icon_zoom);
+ uv_zoom = memnew(HSlider);
uv_zoom->set_min(0.01);
uv_zoom->set_max(4);
uv_zoom->set_value(1);
uv_zoom->set_step(0.01);
uv_mode_hb->add_child(uv_zoom);
- uv_zoom->set_custom_minimum_size(Size2(200,0));
- uv_zoom_value = memnew( SpinBox );
+ uv_zoom->set_custom_minimum_size(Size2(200, 0));
+ uv_zoom_value = memnew(SpinBox);
uv_zoom->share(uv_zoom_value);
- uv_zoom_value->set_custom_minimum_size(Size2(50,0));
+ uv_zoom_value->set_custom_minimum_size(Size2(50, 0));
uv_mode_hb->add_child(uv_zoom_value);
- uv_zoom->connect("value_changed",this,"_uv_scroll_changed");
-
+ uv_zoom->connect("value_changed", this, "_uv_scroll_changed");
-
- uv_vscroll = memnew( VScrollBar);
+ uv_vscroll = memnew(VScrollBar);
uv_main_hb->add_child(uv_vscroll);
- uv_vscroll->connect("value_changed",this,"_uv_scroll_changed");
- uv_hscroll = memnew( HScrollBar );
+ uv_vscroll->connect("value_changed", this, "_uv_scroll_changed");
+ uv_hscroll = memnew(HScrollBar);
uv_main_vb->add_child(uv_hscroll);
- uv_hscroll->connect("value_changed",this,"_uv_scroll_changed");
+ uv_hscroll->connect("value_changed", this, "_uv_scroll_changed");
- uv_edit_draw->connect("draw",this,"_uv_draw");
- uv_edit_draw->connect("gui_input",this,"_uv_input");
- uv_draw_zoom=1.0;
- uv_drag_index=-1;
- uv_drag=false;
- updating_uv_scroll=false;
+ uv_edit_draw->connect("draw", this, "_uv_draw");
+ uv_edit_draw->connect("gui_input", this, "_uv_input");
+ uv_draw_zoom = 1.0;
+ uv_drag_index = -1;
+ uv_drag = false;
+ updating_uv_scroll = false;
- error = memnew( AcceptDialog);
+ error = memnew(AcceptDialog);
add_child(error);
uv_edit_draw->set_clip_contents(true);
-
}
-
void Polygon2DEditorPlugin::edit(Object *p_object) {
-
collision_polygon_editor->edit(p_object->cast_to<Node>());
}
@@ -1008,21 +944,16 @@ void Polygon2DEditorPlugin::make_visible(bool p_visible) {
collision_polygon_editor->hide();
collision_polygon_editor->edit(NULL);
}
-
}
Polygon2DEditorPlugin::Polygon2DEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- collision_polygon_editor = memnew( Polygon2DEditor(p_node) );
+ editor = p_node;
+ collision_polygon_editor = memnew(Polygon2DEditor(p_node));
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(collision_polygon_editor);
collision_polygon_editor->hide();
-
}
-
-Polygon2DEditorPlugin::~Polygon2DEditorPlugin()
-{
+Polygon2DEditorPlugin::~Polygon2DEditorPlugin() {
}
-
diff --git a/editor/plugins/polygon_2d_editor_plugin.h b/editor/plugins/polygon_2d_editor_plugin.h
index c994867705..94eb3f49e8 100644
--- a/editor/plugins/polygon_2d_editor_plugin.h
+++ b/editor/plugins/polygon_2d_editor_plugin.h
@@ -29,11 +29,11 @@
#ifndef POLYGON_2D_EDITOR_PLUGIN_H
#define POLYGON_2D_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/polygon_2d.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -42,7 +42,7 @@ class CanvasItemEditor;
class Polygon2DEditor : public HBoxContainer {
- GDCLASS(Polygon2DEditor, HBoxContainer );
+ GDCLASS(Polygon2DEditor, HBoxContainer);
UndoRedo *undo_redo;
enum Mode {
@@ -88,8 +88,6 @@ class Polygon2DEditor : public HBoxContainer {
Vector2 uv_drag_from;
bool updating_uv_scroll;
-
-
AcceptDialog *error;
ToolButton *button_create;
@@ -114,7 +112,7 @@ class Polygon2DEditor : public HBoxContainer {
Vector2 snap_step;
void _uv_scroll_changed(float);
- void _uv_input(const InputEvent& p_input);
+ void _uv_input(const InputEvent &p_input);
void _uv_draw();
void _uv_mode(int p_mode);
void _wip_close();
@@ -136,22 +134,20 @@ protected:
Vector2 snap_point(Vector2 p_target) const;
public:
-
- bool forward_gui_input(const InputEvent& p_event);
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_collision_polygon);
Polygon2DEditor(EditorNode *p_editor);
};
class Polygon2DEditorPlugin : public EditorPlugin {
- GDCLASS( Polygon2DEditorPlugin, EditorPlugin );
+ GDCLASS(Polygon2DEditorPlugin, EditorPlugin);
Polygon2DEditor *collision_polygon_editor;
EditorNode *editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return collision_polygon_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "Polygon2D"; }
bool has_main_screen() const { return false; }
@@ -161,7 +157,6 @@ public:
Polygon2DEditorPlugin(EditorNode *p_node);
~Polygon2DEditorPlugin();
-
};
#endif // POLYGON_2D_EDITOR_PLUGIN_H
diff --git a/editor/plugins/resource_preloader_editor_plugin.cpp b/editor/plugins/resource_preloader_editor_plugin.cpp
index e876fa55c6..2cdbff8d97 100644
--- a/editor/plugins/resource_preloader_editor_plugin.cpp
+++ b/editor/plugins/resource_preloader_editor_plugin.cpp
@@ -28,40 +28,35 @@
/*************************************************************************/
#include "resource_preloader_editor_plugin.h"
-#include "io/resource_loader.h"
-#include "global_config.h"
#include "editor/editor_settings.h"
-
+#include "global_config.h"
+#include "io/resource_loader.h"
void ResourcePreloaderEditor::_gui_input(InputEvent p_event) {
-
-
}
void ResourcePreloaderEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
-
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
- load->set_icon( get_icon("Folder","EditorIcons") );
- _delete->set_icon( get_icon("Del","EditorIcons") );
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ load->set_icon(get_icon("Folder", "EditorIcons"));
+ _delete->set_icon(get_icon("Del", "EditorIcons"));
}
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
//NodePath("/root")->connect("node_removed", this,"_node_removed",Vector<Variant>(),true);
}
- if (p_what==NOTIFICATION_DRAW) {
-
+ if (p_what == NOTIFICATION_DRAW) {
}
}
-void ResourcePreloaderEditor::_files_load_request(const Vector<String>& p_paths) {
+void ResourcePreloaderEditor::_files_load_request(const Vector<String> &p_paths) {
- for(int i=0;i<p_paths.size();i++) {
+ for (int i = 0; i < p_paths.size(); i++) {
String path = p_paths[i];
@@ -77,41 +72,38 @@ void ResourcePreloaderEditor::_files_load_request(const Vector<String>& p_paths)
return; ///beh should show an error i guess
}
-
String basename = path.get_file().get_basename();
- String name=basename;
- int counter=1;
- while(preloader->has_resource(name)) {
+ String name = basename;
+ int counter = 1;
+ while (preloader->has_resource(name)) {
counter++;
- name=basename+" "+itos(counter);
+ name = basename + " " + itos(counter);
}
undo_redo->create_action(TTR("Add Resource"));
- undo_redo->add_do_method(preloader,"add_resource",name,resource);
- undo_redo->add_undo_method(preloader,"remove_resource",name);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(preloader, "add_resource", name, resource);
+ undo_redo->add_undo_method(preloader, "remove_resource", name);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
}
}
void ResourcePreloaderEditor::_load_pressed() {
- loading_scene=false;
+ loading_scene = false;
file->clear_filters();
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("",&extensions);
- for(int i=0;i<extensions.size();i++)
- file->add_filter("*."+extensions[i]);
+ ResourceLoader::get_recognized_extensions_for_type("", &extensions);
+ for (int i = 0; i < extensions.size(); i++)
+ file->add_filter("*." + extensions[i]);
file->set_mode(EditorFileDialog::MODE_OPEN_FILES);
file->popup_centered_ratio();
-
}
-
void ResourcePreloaderEditor::_item_edited() {
if (!tree->get_selected())
@@ -119,32 +111,29 @@ void ResourcePreloaderEditor::_item_edited() {
TreeItem *s = tree->get_selected();
- if (tree->get_selected_column()==0) {
+ if (tree->get_selected_column() == 0) {
// renamed
- String old_name=s->get_metadata(0);
- String new_name=s->get_text(0);
- if (old_name==new_name)
+ String old_name = s->get_metadata(0);
+ String new_name = s->get_text(0);
+ if (old_name == new_name)
return;
- if (new_name=="" || new_name.find("\\")!=-1 || new_name.find("/")!=-1 || preloader->has_resource(new_name)) {
+ if (new_name == "" || new_name.find("\\") != -1 || new_name.find("/") != -1 || preloader->has_resource(new_name)) {
- s->set_text(0,old_name);
+ s->set_text(0, old_name);
return;
}
RES samp = preloader->get_resource(old_name);
undo_redo->create_action(TTR("Rename Resource"));
- undo_redo->add_do_method(preloader,"remove_resource",old_name);
- undo_redo->add_do_method(preloader,"add_resource",new_name,samp);
- undo_redo->add_undo_method(preloader,"remove_resource",new_name);
- undo_redo->add_undo_method(preloader,"add_resource",old_name,samp);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(preloader, "remove_resource", old_name);
+ undo_redo->add_do_method(preloader, "add_resource", new_name, samp);
+ undo_redo->add_undo_method(preloader, "remove_resource", new_name);
+ undo_redo->add_undo_method(preloader, "add_resource", old_name, samp);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
-
-
}
void ResourcePreloaderEditor::_delete_confirm_pressed() {
@@ -154,17 +143,16 @@ void ResourcePreloaderEditor::_delete_confirm_pressed() {
String to_remove = tree->get_selected()->get_text(0);
undo_redo->create_action(TTR("Delete Resource"));
- undo_redo->add_do_method(preloader,"remove_resource",to_remove);
- undo_redo->add_undo_method(preloader,"add_resource",to_remove,preloader->get_resource(to_remove));
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(preloader, "remove_resource", to_remove);
+ undo_redo->add_undo_method(preloader, "add_resource", to_remove, preloader->get_resource(to_remove));
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
}
-
void ResourcePreloaderEditor::_paste_pressed() {
- RES r=EditorSettings::get_singleton()->get_resource_clipboard();
+ RES r = EditorSettings::get_singleton()->get_resource_clipboard();
if (!r.is_valid()) {
dialog->set_text(TTR("Resource clipboard is empty!"));
dialog->set_title(TTR("Error!"));
@@ -175,31 +163,28 @@ void ResourcePreloaderEditor::_paste_pressed() {
}
String name = r->get_name();
- if (name=="")
- name=r->get_path().get_file();
- if (name=="")
- name=r->get_class();
+ if (name == "")
+ name = r->get_path().get_file();
+ if (name == "")
+ name = r->get_class();
String basename = name;
- int counter=1;
- while(preloader->has_resource(name)) {
+ int counter = 1;
+ while (preloader->has_resource(name)) {
counter++;
- name=basename+" "+itos(counter);
+ name = basename + " " + itos(counter);
}
undo_redo->create_action(TTR("Paste Resource"));
- undo_redo->add_do_method(preloader,"add_resource",name,r);
- undo_redo->add_undo_method(preloader,"remove_resource",name);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(preloader, "add_resource", name, r);
+ undo_redo->add_undo_method(preloader, "remove_resource", name);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
-
void ResourcePreloaderEditor::_delete_pressed() {
-
if (!tree->get_selected())
return;
@@ -211,10 +196,8 @@ void ResourcePreloaderEditor::_delete_pressed() {
//dialog->get_ok()->show();
dialog->get_ok()->set_text("Remove");
dialog->popup_centered(Size2(300,60));*/
-
}
-
void ResourcePreloaderEditor::_update_library() {
tree->clear();
@@ -225,46 +208,40 @@ void ResourcePreloaderEditor::_update_library() {
preloader->get_resource_list(&rnames);
List<String> names;
- for(List<StringName>::Element *E=rnames.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = rnames.front(); E; E = E->next()) {
names.push_back(E->get());
}
names.sort();
- for(List<String>::Element *E=names.front();E;E=E->next()) {
+ for (List<String>::Element *E = names.front(); E; E = E->next()) {
TreeItem *ti = tree->create_item(root);
- ti->set_cell_mode(0,TreeItem::CELL_MODE_STRING);
- ti->set_editable(0,true);
- ti->set_selectable(0,true);
- ti->set_text(0,E->get());
- ti->set_metadata(0,E->get());
-
-
+ ti->set_cell_mode(0, TreeItem::CELL_MODE_STRING);
+ ti->set_editable(0, true);
+ ti->set_selectable(0, true);
+ ti->set_text(0, E->get());
+ ti->set_metadata(0, E->get());
RES r = preloader->get_resource(E->get());
ERR_CONTINUE(r.is_null());
- ti->set_tooltip(0,r->get_path());
+ ti->set_tooltip(0, r->get_path());
String type = r->get_class();
- ti->set_text(1,type);
- ti->set_selectable(1,false);
-
- if (has_icon(type,"EditorIcons"))
- ti->set_icon( 1, get_icon(type,"EditorIcons") );
+ ti->set_text(1, type);
+ ti->set_selectable(1, false);
+ if (has_icon(type, "EditorIcons"))
+ ti->set_icon(1, get_icon(type, "EditorIcons"));
}
//player->add_resource("default",resource);
}
+void ResourcePreloaderEditor::edit(ResourcePreloader *p_preloader) {
-
-void ResourcePreloaderEditor::edit(ResourcePreloader* p_preloader) {
-
- preloader=p_preloader;
-
+ preloader = p_preloader;
if (p_preloader) {
_update_library();
@@ -273,14 +250,11 @@ void ResourcePreloaderEditor::edit(ResourcePreloader* p_preloader) {
hide();
set_fixed_process(false);
}
-
}
+Variant ResourcePreloaderEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
-
-Variant ResourcePreloaderEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
-
- TreeItem*ti =tree->get_item_at_pos(p_point);
+ TreeItem *ti = tree->get_item_at_pos(p_point);
if (!ti)
return Variant();
@@ -290,45 +264,40 @@ Variant ResourcePreloaderEditor::get_drag_data_fw(const Point2& p_point,Control*
if (!res.is_valid())
return Variant();
- return EditorNode::get_singleton()->drag_resource(res,p_from);
-
+ return EditorNode::get_singleton()->drag_resource(res, p_from);
}
-bool ResourcePreloaderEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const {
-
-
+bool ResourcePreloaderEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
if (!d.has("type"))
return false;
- if (d.has("from") && (Object*)(d["from"])==tree)
+ if (d.has("from") && (Object *)(d["from"]) == tree)
return false;
- if (String(d["type"])=="resource" && d.has("resource")) {
- RES r=d["resource"];
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
return r.is_valid();
}
-
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
- if (files.size()==0)
+ if (files.size() == 0)
return false;
return true;
-
}
return false;
}
-void ResourcePreloaderEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) {
+void ResourcePreloaderEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (!can_drop_data_fw(p_point,p_data,p_from))
+ if (!can_drop_data_fw(p_point, p_data, p_from))
return;
Dictionary d = p_data;
@@ -336,39 +305,37 @@ void ResourcePreloaderEditor::drop_data_fw(const Point2& p_point,const Variant&
if (!d.has("type"))
return;
-
- if (String(d["type"])=="resource" && d.has("resource")) {
- RES r=d["resource"];
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
if (r.is_valid()) {
String basename;
- if (r->get_name()!="") {
- basename=r->get_name();
+ if (r->get_name() != "") {
+ basename = r->get_name();
} else if (r->get_path().is_resource_file()) {
basename = r->get_path().get_basename();
} else {
- basename="Resource";
+ basename = "Resource";
}
- String name=basename;
- int counter=0;
- while(preloader->has_resource(name)) {
+ String name = basename;
+ int counter = 0;
+ while (preloader->has_resource(name)) {
counter++;
- name=basename+"_"+itos(counter);
+ name = basename + "_" + itos(counter);
}
undo_redo->create_action(TTR("Add Resource"));
- undo_redo->add_do_method(preloader,"add_resource",name,r);
- undo_redo->add_undo_method(preloader,"remove_resource",name);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(preloader, "add_resource", name, r);
+ undo_redo->add_undo_method(preloader, "remove_resource", name);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
}
}
-
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
@@ -376,83 +343,73 @@ void ResourcePreloaderEditor::drop_data_fw(const Point2& p_point,const Variant&
}
}
-
-
void ResourcePreloaderEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&ResourcePreloaderEditor::_gui_input);
- ClassDB::bind_method(D_METHOD("_load_pressed"),&ResourcePreloaderEditor::_load_pressed);
- ClassDB::bind_method(D_METHOD("_item_edited"),&ResourcePreloaderEditor::_item_edited);
- ClassDB::bind_method(D_METHOD("_delete_pressed"),&ResourcePreloaderEditor::_delete_pressed);
- ClassDB::bind_method(D_METHOD("_paste_pressed"),&ResourcePreloaderEditor::_paste_pressed);
- ClassDB::bind_method(D_METHOD("_delete_confirm_pressed"),&ResourcePreloaderEditor::_delete_confirm_pressed);
- ClassDB::bind_method(D_METHOD("_files_load_request"),&ResourcePreloaderEditor::_files_load_request);
- ClassDB::bind_method(D_METHOD("_update_library"),&ResourcePreloaderEditor::_update_library);
-
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ResourcePreloaderEditor::_gui_input);
+ ClassDB::bind_method(D_METHOD("_load_pressed"), &ResourcePreloaderEditor::_load_pressed);
+ ClassDB::bind_method(D_METHOD("_item_edited"), &ResourcePreloaderEditor::_item_edited);
+ ClassDB::bind_method(D_METHOD("_delete_pressed"), &ResourcePreloaderEditor::_delete_pressed);
+ ClassDB::bind_method(D_METHOD("_paste_pressed"), &ResourcePreloaderEditor::_paste_pressed);
+ ClassDB::bind_method(D_METHOD("_delete_confirm_pressed"), &ResourcePreloaderEditor::_delete_confirm_pressed);
+ ClassDB::bind_method(D_METHOD("_files_load_request"), &ResourcePreloaderEditor::_files_load_request);
+ ClassDB::bind_method(D_METHOD("_update_library"), &ResourcePreloaderEditor::_update_library);
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &ResourcePreloaderEditor::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &ResourcePreloaderEditor::can_drop_data_fw);
ClassDB::bind_method(D_METHOD("drop_data_fw"), &ResourcePreloaderEditor::drop_data_fw);
-
-
}
ResourcePreloaderEditor::ResourcePreloaderEditor() {
//add_style_override("panel", get_stylebox("panel","Panel"));
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
- load = memnew( Button );
+ load = memnew(Button);
load->set_tooltip(TTR("Load Resource"));
hbc->add_child(load);
-
-
- _delete = memnew( Button );
+ _delete = memnew(Button);
hbc->add_child(_delete);
- paste = memnew( Button );
+ paste = memnew(Button);
paste->set_text(TTR("Paste"));
hbc->add_child(paste);
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
add_child(file);
-
- tree = memnew( Tree );
+ tree = memnew(Tree);
tree->set_columns(2);
- tree->set_column_min_width(0,3);
- tree->set_column_min_width(1,1);
- tree->set_column_expand(0,true);
- tree->set_column_expand(1,true);
+ tree->set_column_min_width(0, 3);
+ tree->set_column_min_width(1, 1);
+ tree->set_column_expand(0, true);
+ tree->set_column_expand(1, true);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
tree->set_drag_forwarding(this);
vbc->add_child(tree);
- dialog = memnew( AcceptDialog );
- add_child( dialog );
+ dialog = memnew(AcceptDialog);
+ add_child(dialog);
- load->connect("pressed", this,"_load_pressed");
- _delete->connect("pressed", this,"_delete_pressed");
- paste->connect("pressed", this,"_paste_pressed");
- file->connect("files_selected", this,"_files_load_request");
+ load->connect("pressed", this, "_load_pressed");
+ _delete->connect("pressed", this, "_delete_pressed");
+ paste->connect("pressed", this, "_paste_pressed");
+ file->connect("files_selected", this, "_files_load_request");
//dialog->connect("confirmed", this,"_delete_confirm_pressed");
- tree->connect("item_edited", this,"_item_edited");
- loading_scene=false;
-
+ tree->connect("item_edited", this, "_item_edited");
+ loading_scene = false;
}
-
void ResourcePreloaderEditorPlugin::edit(Object *p_object) {
preloader_editor->set_undo_redo(&get_undo_redo());
- ResourcePreloader * s = p_object->cast_to<ResourcePreloader>();
+ ResourcePreloader *s = p_object->cast_to<ResourcePreloader>();
if (!s)
return;
@@ -479,29 +436,20 @@ void ResourcePreloaderEditorPlugin::make_visible(bool p_visible) {
//preloader_editor->hide();
//preloader_editor->set_process(false);
}
-
}
ResourcePreloaderEditorPlugin::ResourcePreloaderEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- preloader_editor = memnew( ResourcePreloaderEditor );
- preloader_editor->set_custom_minimum_size(Size2(0,250));
+ editor = p_node;
+ preloader_editor = memnew(ResourcePreloaderEditor);
+ preloader_editor->set_custom_minimum_size(Size2(0, 250));
- button=editor->add_bottom_panel_item("ResourcePreloader",preloader_editor);
+ button = editor->add_bottom_panel_item("ResourcePreloader", preloader_editor);
button->hide();
//preloader_editor->set_anchor( MARGIN_TOP, Control::ANCHOR_END);
//preloader_editor->set_margin( MARGIN_TOP, 120 );
-
-
-
-
}
-
-ResourcePreloaderEditorPlugin::~ResourcePreloaderEditorPlugin()
-{
+ResourcePreloaderEditorPlugin::~ResourcePreloaderEditorPlugin() {
}
-
-
diff --git a/editor/plugins/resource_preloader_editor_plugin.h b/editor/plugins/resource_preloader_editor_plugin.h
index 54ccad4341..946a3887ef 100644
--- a/editor/plugins/resource_preloader_editor_plugin.h
+++ b/editor/plugins/resource_preloader_editor_plugin.h
@@ -29,18 +29,16 @@
#ifndef RESOURCE_PRELOADER_EDITOR_PLUGIN_H
#define RESOURCE_PRELOADER_EDITOR_PLUGIN_H
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/tree.h"
#include "scene/main/resource_preloader.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/dialogs.h"
-
class ResourcePreloaderEditor : public PanelContainer {
- GDCLASS(ResourcePreloaderEditor, PanelContainer );
+ GDCLASS(ResourcePreloaderEditor, PanelContainer);
Button *load;
Button *_delete;
@@ -48,17 +46,15 @@ class ResourcePreloaderEditor : public PanelContainer {
Tree *tree;
bool loading_scene;
-
EditorFileDialog *file;
AcceptDialog *dialog;
ResourcePreloader *preloader;
-
void _load_pressed();
void _load_scene_pressed();
- void _files_load_request(const Vector<String>& p_paths);
+ void _files_load_request(const Vector<String> &p_paths);
void _paste_pressed();
void _delete_pressed();
void _delete_confirm_pressed();
@@ -67,33 +63,31 @@ class ResourcePreloaderEditor : public PanelContainer {
UndoRedo *undo_redo;
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
-
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
protected:
void _notification(int p_what);
void _gui_input(InputEvent p_event);
static void _bind_methods();
-public:
- void set_undo_redo(UndoRedo *p_undo_redo) {undo_redo=p_undo_redo; }
+public:
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
- void edit(ResourcePreloader* p_preloader);
+ void edit(ResourcePreloader *p_preloader);
ResourcePreloaderEditor();
};
class ResourcePreloaderEditorPlugin : public EditorPlugin {
- GDCLASS( ResourcePreloaderEditorPlugin, EditorPlugin );
+ GDCLASS(ResourcePreloaderEditorPlugin, EditorPlugin);
ResourcePreloaderEditor *preloader_editor;
EditorNode *editor;
Button *button;
public:
-
virtual String get_name() const { return "ResourcePreloader"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -102,7 +96,6 @@ public:
ResourcePreloaderEditorPlugin(EditorNode *p_node);
~ResourcePreloaderEditorPlugin();
-
};
#endif // RESOURCE_PRELOADER_EDITOR_PLUGIN_H
diff --git a/editor/plugins/rich_text_editor_plugin.cpp b/editor/plugins/rich_text_editor_plugin.cpp
index 797ee8e8ea..72a9278e62 100644
--- a/editor/plugins/rich_text_editor_plugin.cpp
+++ b/editor/plugins/rich_text_editor_plugin.cpp
@@ -28,39 +28,35 @@
/*************************************************************************/
#include "rich_text_editor_plugin.h"
-#include "os/file_access.h"
#include "canvas_item_editor_plugin.h"
+#include "os/file_access.h"
void RichTextEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_FIXED_PROCESS: {
-
} break;
}
-
}
void RichTextEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
}
-
}
-
-void RichTextEditor::_file_selected(const String& p_path) {
+void RichTextEditor::_file_selected(const String &p_path) {
CharString cs;
- FileAccess *fa = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(p_path, FileAccess::READ);
if (!fa) {
ERR_FAIL();
}
- while(!fa->eof_reached())
+ while (!fa->eof_reached())
cs.push_back(fa->get_8());
cs.push_back(0);
memdelete(fa);
@@ -68,12 +64,11 @@ void RichTextEditor::_file_selected(const String& p_path) {
String bbcode;
bbcode.parse_utf8(&cs[0]);
node->parse_bbcode(bbcode);
-
}
void RichTextEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case PARSE_BBCODE: {
@@ -84,42 +79,38 @@ void RichTextEditor::_menu_option(int p_option) {
node->clear();
} break;
-
}
}
void RichTextEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_menu_option"),&RichTextEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_file_selected"),&RichTextEditor::_file_selected);
-
+ ClassDB::bind_method(D_METHOD("_menu_option"), &RichTextEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_file_selected"), &RichTextEditor::_file_selected);
}
void RichTextEditor::edit(Node *p_rich_text) {
- node=p_rich_text->cast_to<RichTextLabel>();
-
+ node = p_rich_text->cast_to<RichTextLabel>();
}
RichTextEditor::RichTextEditor() {
- options = memnew( MenuButton );
+ options = memnew(MenuButton);
//add_child(options);
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(options);
options->set_area_as_parent_rect();
options->set_text("RichText");
- options->get_popup()->add_item(TTR("Parse BBCode"),PARSE_BBCODE);
- options->get_popup()->add_item(TTR("Clear"),CLEAR);
+ options->get_popup()->add_item(TTR("Parse BBCode"), PARSE_BBCODE);
+ options->get_popup()->add_item(TTR("Clear"), CLEAR);
- options->get_popup()->connect("id_pressed", this,"_menu_option");
- file_dialog = memnew( EditorFileDialog );
+ options->get_popup()->connect("id_pressed", this, "_menu_option");
+ file_dialog = memnew(EditorFileDialog);
add_child(file_dialog);
file_dialog->add_filter("*.txt");
file_dialog->set_mode(EditorFileDialog::MODE_OPEN_FILE);
- file_dialog->connect("file_selected",this,"_file_selected");
+ file_dialog->connect("file_selected", this, "_file_selected");
}
-
void RichTextEditorPlugin::edit(Object *p_object) {
rich_text_editor->edit(p_object->cast_to<Node>());
@@ -139,26 +130,21 @@ void RichTextEditorPlugin::make_visible(bool p_visible) {
rich_text_editor->options->hide();
rich_text_editor->edit(NULL);
}
-
}
RichTextEditorPlugin::RichTextEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- rich_text_editor = memnew( RichTextEditor );
+ editor = p_node;
+ rich_text_editor = memnew(RichTextEditor);
editor->get_viewport()->add_child(rich_text_editor);
- rich_text_editor->set_margin(MARGIN_LEFT,184);
- rich_text_editor->set_margin(MARGIN_RIGHT,230);
- rich_text_editor->set_margin(MARGIN_TOP,0);
- rich_text_editor->set_margin(MARGIN_BOTTOM,10);
+ rich_text_editor->set_margin(MARGIN_LEFT, 184);
+ rich_text_editor->set_margin(MARGIN_RIGHT, 230);
+ rich_text_editor->set_margin(MARGIN_TOP, 0);
+ rich_text_editor->set_margin(MARGIN_BOTTOM, 10);
rich_text_editor->options->hide();
-
}
-
-RichTextEditorPlugin::~RichTextEditorPlugin()
-{
+RichTextEditorPlugin::~RichTextEditorPlugin() {
}
-
diff --git a/editor/plugins/rich_text_editor_plugin.h b/editor/plugins/rich_text_editor_plugin.h
index c7f95fb479..ab3c252fcf 100644
--- a/editor/plugins/rich_text_editor_plugin.h
+++ b/editor/plugins/rich_text_editor_plugin.h
@@ -29,10 +29,10 @@
#ifndef RICH_TEXT_EDITOR_PLUGIN_H
#define RICH_TEXT_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/gui/rich_text_label.h"
+#include "editor/editor_plugin.h"
#include "scene/gui/file_dialog.h"
+#include "scene/gui/rich_text_label.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -40,9 +40,9 @@
class RichTextEditor : public Control {
- GDCLASS(RichTextEditor, Control );
+ GDCLASS(RichTextEditor, Control);
- friend class RichTextEditorPlugin;
+ friend class RichTextEditorPlugin;
enum {
@@ -51,32 +51,31 @@ class RichTextEditor : public Control {
};
Panel *panel;
- MenuButton *options;
+ MenuButton *options;
RichTextLabel *node;
EditorFileDialog *file_dialog;
- void _file_selected(const String& p_path);
+ void _file_selected(const String &p_path);
void _menu_option(int p_option);
protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
+public:
void edit(Node *p_rich_text);
RichTextEditor();
};
class RichTextEditorPlugin : public EditorPlugin {
- GDCLASS( RichTextEditorPlugin, EditorPlugin );
+ GDCLASS(RichTextEditorPlugin, EditorPlugin);
RichTextEditor *rich_text_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "RichText"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -85,7 +84,6 @@ public:
RichTextEditorPlugin(EditorNode *p_node);
~RichTextEditorPlugin();
-
};
#endif // RICH_TEXT_EDITOR_PLUGIN_H
diff --git a/editor/plugins/sample_editor_plugin.cpp b/editor/plugins/sample_editor_plugin.cpp
index b6b96c946e..4d685f4289 100644
--- a/editor/plugins/sample_editor_plugin.cpp
+++ b/editor/plugins/sample_editor_plugin.cpp
@@ -29,9 +29,9 @@
#include "sample_editor_plugin.h"
#if 0
-#include "io/resource_loader.h"
-#include "global_config.h"
#include "editor/editor_settings.h"
+#include "global_config.h"
+#include "io/resource_loader.h"
diff --git a/editor/plugins/sample_editor_plugin.h b/editor/plugins/sample_editor_plugin.h
index dae9cef9f4..0e7bccffa7 100644
--- a/editor/plugins/sample_editor_plugin.h
+++ b/editor/plugins/sample_editor_plugin.h
@@ -30,8 +30,8 @@
#define SAMPLE_EDITOR_PLUGIN_H
#if 0
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/audio/sample_player.h"
#include "scene/resources/sample.h"
#include "scene/resources/sample_library.h"
diff --git a/editor/plugins/sample_library_editor_plugin.cpp b/editor/plugins/sample_library_editor_plugin.cpp
index 4ead1d2709..c164428553 100644
--- a/editor/plugins/sample_library_editor_plugin.cpp
+++ b/editor/plugins/sample_library_editor_plugin.cpp
@@ -30,11 +30,11 @@
#if 0
#include "sample_library_editor_plugin.h"
-#include "io/resource_loader.h"
-#include "global_config.h"
#include "editor/editor_settings.h"
-#include "scene/main/viewport.h"
+#include "global_config.h"
+#include "io/resource_loader.h"
#include "sample_editor_plugin.h"
+#include "scene/main/viewport.h"
void SampleLibraryEditor::_gui_input(InputEvent p_event) {
diff --git a/editor/plugins/sample_library_editor_plugin.h b/editor/plugins/sample_library_editor_plugin.h
index 4bbc29b147..a41e1538b4 100644
--- a/editor/plugins/sample_library_editor_plugin.h
+++ b/editor/plugins/sample_library_editor_plugin.h
@@ -29,15 +29,14 @@
#ifndef SAMPLE_LIBRARY_EDITOR_PLUGIN_H
#define SAMPLE_LIBRARY_EDITOR_PLUGIN_H
-
#if 0
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/audio/sample_player.h"
-#include "scene/resources/sample.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/file_dialog.h"
#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
+#include "scene/gui/tree.h"
+#include "scene/resources/sample.h"
class SampleLibraryEditor : public Panel {
diff --git a/editor/plugins/sample_player_editor_plugin.cpp b/editor/plugins/sample_player_editor_plugin.cpp
index 7e2683dedf..a550d96d5c 100644
--- a/editor/plugins/sample_player_editor_plugin.cpp
+++ b/editor/plugins/sample_player_editor_plugin.cpp
@@ -30,7 +30,6 @@
#if 0
#include "sample_player_editor_plugin.h"
-
#include "scene/resources/sample_library.h"
@@ -199,5 +198,4 @@ SamplePlayerEditorPlugin::~SamplePlayerEditorPlugin()
{
}
-
#endif
diff --git a/editor/plugins/sample_player_editor_plugin.h b/editor/plugins/sample_player_editor_plugin.h
index c1d599540a..10a08b8a17 100644
--- a/editor/plugins/sample_player_editor_plugin.h
+++ b/editor/plugins/sample_player_editor_plugin.h
@@ -31,11 +31,11 @@
#if 0
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/spatial_sample_player.h"
-#include "scene/gui/option_button.h"
#include "scene/audio/sample_player.h"
+#include "scene/gui/option_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
diff --git a/editor/plugins/script_editor_plugin.cpp b/editor/plugins/script_editor_plugin.cpp
index 3631d39f9a..4e7a0709fa 100644
--- a/editor/plugins/script_editor_plugin.cpp
+++ b/editor/plugins/script_editor_plugin.cpp
@@ -28,44 +28,41 @@
/*************************************************************************/
#include "script_editor_plugin.h"
+#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "editor/script_editor_debugger.h"
+#include "global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
+#include "os/file_access.h"
+#include "os/input.h"
+#include "os/keyboard.h"
#include "os/keyboard.h"
#include "os/os.h"
-#include "editor/editor_node.h"
-#include "editor/script_editor_debugger.h"
-#include "global_config.h"
-#include "os/file_access.h"
#include "scene/main/viewport.h"
-#include "os/keyboard.h"
-#include "os/input.h"
/*** SCRIPT EDITOR ****/
-
-
void ScriptEditorBase::_bind_methods() {
ADD_SIGNAL(MethodInfo("name_changed"));
- ADD_SIGNAL(MethodInfo("request_help_search",PropertyInfo(Variant::STRING,"topic")));
- ADD_SIGNAL(MethodInfo("request_open_script_at_line",PropertyInfo(Variant::OBJECT,"script"),PropertyInfo(Variant::INT,"line")));
+ ADD_SIGNAL(MethodInfo("request_help_search", PropertyInfo(Variant::STRING, "topic")));
+ ADD_SIGNAL(MethodInfo("request_open_script_at_line", PropertyInfo(Variant::OBJECT, "script"), PropertyInfo(Variant::INT, "line")));
ADD_SIGNAL(MethodInfo("request_save_history"));
- ADD_SIGNAL(MethodInfo("go_to_help",PropertyInfo(Variant::STRING,"what")));
-
+ ADD_SIGNAL(MethodInfo("go_to_help", PropertyInfo(Variant::STRING, "what")));
}
-static bool _can_open_in_editor(Script* p_script) {
+static bool _can_open_in_editor(Script *p_script) {
String path = p_script->get_path();
- if (path.find("::")!=-1) {
+ if (path.find("::") != -1) {
//refuse handling this if it can't be edited
- bool valid=false;
- for(int i=0;i<EditorNode::get_singleton()->get_editor_data().get_edited_scene_count();i++) {
+ bool valid = false;
+ for (int i = 0; i < EditorNode::get_singleton()->get_editor_data().get_edited_scene_count(); i++) {
if (path.begins_with(EditorNode::get_singleton()->get_editor_data().get_scene_path(i))) {
- valid=true;
+ valid = true;
break;
}
}
@@ -76,68 +73,63 @@ static bool _can_open_in_editor(Script* p_script) {
return true;
}
-
class EditorScriptCodeCompletionCache : public ScriptCodeCompletionCache {
-
struct Cache {
uint64_t time_loaded;
RES cache;
};
- Map<String,Cache> cached;
-
+ Map<String, Cache> cached;
public:
-
uint64_t max_time_cache;
int max_cache_size;
void cleanup() {
- List< Map<String,Cache>::Element * > to_clean;
+ List<Map<String, Cache>::Element *> to_clean;
-
- Map<String,Cache>::Element *I=cached.front();
- while(I) {
- if ((OS::get_singleton()->get_ticks_msec()-I->get().time_loaded)>max_time_cache) {
+ Map<String, Cache>::Element *I = cached.front();
+ while (I) {
+ if ((OS::get_singleton()->get_ticks_msec() - I->get().time_loaded) > max_time_cache) {
to_clean.push_back(I);
}
- I=I->next();
+ I = I->next();
}
- while(to_clean.front()) {
+ while (to_clean.front()) {
cached.erase(to_clean.front()->get());
to_clean.pop_front();
}
}
- RES get_cached_resource(const String& p_path) {
+ RES get_cached_resource(const String &p_path) {
- Map<String,Cache>::Element *E=cached.find(p_path);
+ Map<String, Cache>::Element *E = cached.find(p_path);
if (!E) {
Cache c;
- c.cache=ResourceLoader::load(p_path);
- E=cached.insert(p_path,c);
+ c.cache = ResourceLoader::load(p_path);
+ E = cached.insert(p_path, c);
}
- E->get().time_loaded=OS::get_singleton()->get_ticks_msec();
+ E->get().time_loaded = OS::get_singleton()->get_ticks_msec();
- if (cached.size()>max_cache_size) {
+ if (cached.size() > max_cache_size) {
uint64_t older;
- Map<String,Cache>::Element *O=cached.front();
- older=O->get().time_loaded;
- Map<String,Cache>::Element *I=O;
- while(I) {
- if (I->get().time_loaded<older) {
+ Map<String, Cache>::Element *O = cached.front();
+ older = O->get().time_loaded;
+ Map<String, Cache>::Element *I = O;
+ while (I) {
+ if (I->get().time_loaded < older) {
older = I->get().time_loaded;
- O=I;
+ O = I;
}
- I=I->next();
+ I = I->next();
}
- if (O!=E) {//should never heppane..
+ if (O != E) { //should never heppane..
cached.erase(O);
}
}
@@ -145,18 +137,16 @@ public:
return E->get().cache;
}
-
EditorScriptCodeCompletionCache() {
- max_cache_size=128;
- max_time_cache=5*60*1000; //minutes, five
+ max_cache_size = 128;
+ max_time_cache = 5 * 60 * 1000; //minutes, five
}
-
};
#define SORT_SCRIPT_LIST
-void ScriptEditorQuickOpen::popup(const Vector<String>& p_functions, bool p_dontclear) {
+void ScriptEditorQuickOpen::popup(const Vector<String> &p_functions, bool p_dontclear) {
popup_centered_ratio(0.6);
if (p_dontclear)
@@ -164,55 +154,45 @@ void ScriptEditorQuickOpen::popup(const Vector<String>& p_functions, bool p_dont
else
search_box->clear();
search_box->grab_focus();
- functions=p_functions;
+ functions = p_functions;
_update_search();
-
-
}
-
-void ScriptEditorQuickOpen::_text_changed(const String& p_newtext) {
+void ScriptEditorQuickOpen::_text_changed(const String &p_newtext) {
_update_search();
}
-void ScriptEditorQuickOpen::_sbox_input(const InputEvent& p_ie) {
+void ScriptEditorQuickOpen::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY && (
- p_ie.key.scancode == KEY_UP ||
- p_ie.key.scancode == KEY_DOWN ||
- p_ie.key.scancode == KEY_PAGEUP ||
- p_ie.key.scancode == KEY_PAGEDOWN ) ) {
+ if (p_ie.type == InputEvent::KEY && (p_ie.key.scancode == KEY_UP ||
+ p_ie.key.scancode == KEY_DOWN ||
+ p_ie.key.scancode == KEY_PAGEUP ||
+ p_ie.key.scancode == KEY_PAGEDOWN)) {
- search_options->call("_gui_input",p_ie);
+ search_options->call("_gui_input", p_ie);
search_box->accept_event();
}
-
}
-
-
void ScriptEditorQuickOpen::_update_search() {
-
search_options->clear();
TreeItem *root = search_options->create_item();
- for(int i=0;i<functions.size();i++) {
+ for (int i = 0; i < functions.size(); i++) {
String file = functions[i];
- if ((search_box->get_text()=="" || file.findn(search_box->get_text())!=-1)) {
+ if ((search_box->get_text() == "" || file.findn(search_box->get_text()) != -1)) {
TreeItem *ti = search_options->create_item(root);
- ti->set_text(0,file);
- if (root->get_children()==ti)
+ ti->set_text(0, file);
+ if (root->get_children() == ti)
ti->select(0);
-
}
}
- get_ok()->set_disabled(root->get_children()==NULL);
-
+ get_ok()->set_disabled(root->get_children() == NULL);
}
void ScriptEditorQuickOpen::_confirmed() {
@@ -220,88 +200,79 @@ void ScriptEditorQuickOpen::_confirmed() {
TreeItem *ti = search_options->get_selected();
if (!ti)
return;
- int line = ti->get_text(0).get_slice(":",1).to_int();
+ int line = ti->get_text(0).get_slice(":", 1).to_int();
- emit_signal("goto_line",line-1);
+ emit_signal("goto_line", line - 1);
hide();
}
void ScriptEditorQuickOpen::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
- connect("confirmed",this,"_confirmed");
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ connect("confirmed", this, "_confirmed");
}
}
-
-
-
void ScriptEditorQuickOpen::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_changed"),&ScriptEditorQuickOpen::_text_changed);
- ClassDB::bind_method(D_METHOD("_confirmed"),&ScriptEditorQuickOpen::_confirmed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&ScriptEditorQuickOpen::_sbox_input);
-
- ADD_SIGNAL(MethodInfo("goto_line",PropertyInfo(Variant::INT,"line")));
+ ClassDB::bind_method(D_METHOD("_text_changed"), &ScriptEditorQuickOpen::_text_changed);
+ ClassDB::bind_method(D_METHOD("_confirmed"), &ScriptEditorQuickOpen::_confirmed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &ScriptEditorQuickOpen::_sbox_input);
+ ADD_SIGNAL(MethodInfo("goto_line", PropertyInfo(Variant::INT, "line")));
}
-
ScriptEditorQuickOpen::ScriptEditorQuickOpen() {
-
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
- search_box = memnew( LineEdit );
- vbc->add_margin_child(TTR("Search:"),search_box);
- search_box->connect("text_changed",this,"_text_changed");
- search_box->connect("gui_input",this,"_sbox_input");
- search_options = memnew( Tree );
- vbc->add_margin_child(TTR("Matches:"),search_options,true);
+ search_box = memnew(LineEdit);
+ vbc->add_margin_child(TTR("Search:"), search_box);
+ search_box->connect("text_changed", this, "_text_changed");
+ search_box->connect("gui_input", this, "_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);
register_text_enter(search_box);
set_hide_on_ok(false);
- search_options->connect("item_activated",this,"_confirmed");
+ search_options->connect("item_activated", this, "_confirmed");
search_options->set_hide_root(true);
}
-
/////////////////////////////////
-ScriptEditor *ScriptEditor::script_editor=NULL;
+ScriptEditor *ScriptEditor::script_editor = NULL;
/*** SCRIPT EDITOR ******/
-String ScriptEditor::_get_debug_tooltip(const String&p_text,Node *_se) {
+String ScriptEditor::_get_debug_tooltip(const String &p_text, Node *_se) {
//ScriptEditorBase *se=_se->cast_to<ScriptEditorBase>();
String val = debugger->get_var_value(p_text);
- if (val!=String()) {
- return p_text+": "+val;
+ if (val != String()) {
+ return p_text + ": " + val;
} else {
return String();
}
}
-void ScriptEditor::_breaked(bool p_breaked,bool p_can_debug) {
+void ScriptEditor::_breaked(bool p_breaked, bool p_can_debug) {
if (bool(EditorSettings::get_singleton()->get("text_editor/external/use_external_editor"))) {
return;
}
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_NEXT), !(p_breaked && p_can_debug));
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_STEP), !(p_breaked && p_can_debug) );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_BREAK), p_breaked );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), !p_breaked );
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_NEXT), !(p_breaked && p_can_debug));
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_STEP), !(p_breaked && p_can_debug));
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_BREAK), p_breaked);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), !p_breaked);
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se) {
@@ -311,7 +282,6 @@ void ScriptEditor::_breaked(bool p_breaked,bool p_can_debug) {
se->set_debugger_active(p_breaked);
}
-
}
void ScriptEditor::_show_debugger(bool p_show) {
@@ -323,11 +293,10 @@ void ScriptEditor::_script_created(Ref<Script> p_script) {
editor->push_item(p_script.operator->());
}
-
void ScriptEditor::_goto_script_line2(int p_line) {
int selected = tab_container->get_current_tab();
- if (selected<0 || selected>=tab_container->get_child_count())
+ if (selected < 0 || selected >= tab_container->get_child_count())
return;
ScriptEditorBase *current = tab_container->get_child(selected)->cast_to<ScriptEditorBase>();
@@ -335,54 +304,49 @@ void ScriptEditor::_goto_script_line2(int p_line) {
return;
current->goto_line(p_line);
-
}
-void ScriptEditor::_goto_script_line(REF p_script,int p_line) {
-
+void ScriptEditor::_goto_script_line(REF p_script, int p_line) {
editor->push_item(p_script.ptr());
int selected = tab_container->get_current_tab();
- if (selected<0 || selected>=tab_container->get_child_count())
+ if (selected < 0 || selected >= tab_container->get_child_count())
return;
ScriptEditorBase *current = tab_container->get_child(selected)->cast_to<ScriptEditorBase>();
if (!current)
return;
- current->goto_line(p_line,true);
-
+ current->goto_line(p_line, true);
}
-
void ScriptEditor::_update_history_arrows() {
- script_back->set_disabled( history_pos<=0 );
- script_forward->set_disabled( history_pos>=history.size()-1 );
+ script_back->set_disabled(history_pos <= 0);
+ script_forward->set_disabled(history_pos >= history.size() - 1);
}
void ScriptEditor::_save_history() {
-
- if (history_pos>=0 && history_pos<history.size() && history[history_pos].control==tab_container->get_current_tab_control()) {
+ if (history_pos >= 0 && history_pos < history.size() && history[history_pos].control == tab_container->get_current_tab_control()) {
Node *n = tab_container->get_current_tab_control();
if (n->cast_to<ScriptEditorBase>()) {
- history[history_pos].state=n->cast_to<ScriptEditorBase>()->get_edit_state();
+ history[history_pos].state = n->cast_to<ScriptEditorBase>()->get_edit_state();
}
if (n->cast_to<EditorHelp>()) {
- history[history_pos].state=n->cast_to<EditorHelp>()->get_scroll();
+ history[history_pos].state = n->cast_to<EditorHelp>()->get_scroll();
}
}
- history.resize(history_pos+1);
+ history.resize(history_pos + 1);
ScriptHistory sh;
- sh.control=tab_container->get_current_tab_control();
- sh.state=Variant();
+ sh.control = tab_container->get_current_tab_control();
+ sh.state = Variant();
history.push_back(sh);
history_pos++;
@@ -390,7 +354,6 @@ void ScriptEditor::_save_history() {
_update_history_arrows();
}
-
void ScriptEditor::_go_to_tab(int p_idx) {
Node *cn = tab_container->get_child(p_idx);
@@ -400,29 +363,28 @@ void ScriptEditor::_go_to_tab(int p_idx) {
if (!c)
return;
- if (history_pos>=0 && history_pos<history.size() && history[history_pos].control==tab_container->get_current_tab_control()) {
+ if (history_pos >= 0 && history_pos < history.size() && history[history_pos].control == tab_container->get_current_tab_control()) {
Node *n = tab_container->get_current_tab_control();
if (n->cast_to<ScriptEditorBase>()) {
- history[history_pos].state=n->cast_to<ScriptEditorBase>()->get_edit_state();
+ history[history_pos].state = n->cast_to<ScriptEditorBase>()->get_edit_state();
}
if (n->cast_to<EditorHelp>()) {
- history[history_pos].state=n->cast_to<EditorHelp>()->get_scroll();
+ history[history_pos].state = n->cast_to<EditorHelp>()->get_scroll();
}
}
- history.resize(history_pos+1);
+ history.resize(history_pos + 1);
ScriptHistory sh;
- sh.control=c;
- sh.state=Variant();
+ sh.control = c;
+ sh.state = Variant();
history.push_back(sh);
history_pos++;
-
tab_container->set_current_tab(p_idx);
c = tab_container->get_current_tab_control();
@@ -437,23 +399,21 @@ void ScriptEditor::_go_to_tab(int p_idx) {
if (c->cast_to<EditorHelp>()) {
script_name_label->set_text(c->cast_to<EditorHelp>()->get_class());
- script_icon->set_texture(get_icon("Help","EditorIcons"));
+ script_icon->set_texture(get_icon("Help", "EditorIcons"));
if (is_visible_in_tree())
c->cast_to<EditorHelp>()->set_focused();
}
-
-
- c->set_meta("__editor_pass",++edit_pass);
+ c->set_meta("__editor_pass", ++edit_pass);
_update_history_arrows();
- _update_script_colors();
+ _update_script_colors();
_update_selected_editor_menu();
}
void ScriptEditor::_close_tab(int p_idx, bool p_save) {
int selected = p_idx;
- if (selected<0 || selected>=tab_container->get_child_count())
+ if (selected < 0 || selected >= tab_container->get_child_count())
return;
Node *tselected = tab_container->get_child(selected);
@@ -468,27 +428,27 @@ void ScriptEditor::_close_tab(int p_idx, bool p_save) {
}
//remove from history
- history.resize(history_pos+1);
+ history.resize(history_pos + 1);
- for(int i=0;i<history.size();i++) {
- if (history[i].control==tselected) {
+ for (int i = 0; i < history.size(); i++) {
+ if (history[i].control == tselected) {
history.remove(i);
i--;
history_pos--;
}
}
- if (history_pos>=history.size()) {
- history_pos=history.size()-1;
+ if (history_pos >= history.size()) {
+ history_pos = history.size() - 1;
}
int idx = tab_container->get_current_tab();
memdelete(tselected);
- if (idx>=tab_container->get_child_count())
- idx=tab_container->get_child_count()-1;
- if (idx>=0) {
+ if (idx >= tab_container->get_child_count())
+ idx = tab_container->get_child_count() - 1;
+ if (idx >= 0) {
- if (history_pos>=0) {
+ if (history_pos >= 0) {
idx = history[history_pos].control->get_index();
}
tab_container->set_current_tab(idx);
@@ -496,11 +456,8 @@ void ScriptEditor::_close_tab(int p_idx, bool p_save) {
//script_list->select(idx);
}
-
_update_history_arrows();
-
-
_update_script_names();
_save_layout();
}
@@ -508,10 +465,9 @@ void ScriptEditor::_close_tab(int p_idx, bool p_save) {
void ScriptEditor::_close_current_tab() {
_close_tab(tab_container->get_current_tab());
-
}
-void ScriptEditor::_close_discard_current_tab(const String& p_str) {
+void ScriptEditor::_close_discard_current_tab(const String &p_str) {
_close_tab(tab_container->get_current_tab(), false);
erase_tab_confirm->hide();
}
@@ -519,22 +475,20 @@ void ScriptEditor::_close_discard_current_tab(const String& p_str) {
void ScriptEditor::_close_docs_tab() {
int child_count = tab_container->get_child_count();
- for (int i = child_count-1; i>=0; i--) {
+ for (int i = child_count - 1; i >= 0; i--) {
EditorHelp *se = tab_container->get_child(i)->cast_to<EditorHelp>();
if (se) {
_close_tab(i);
}
-
}
-
}
void ScriptEditor::_close_all_tabs() {
int child_count = tab_container->get_child_count();
- for (int i = child_count-1; i>=0; i--) {
+ for (int i = child_count - 1; i >= 0; i--) {
tab_container->set_current_tab(i);
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
@@ -546,34 +500,30 @@ void ScriptEditor::_close_all_tabs() {
_ask_close_current_unsaved_tab(se);
continue;
}
-
}
_close_current_tab();
}
-
}
void ScriptEditor::_ask_close_current_unsaved_tab(ScriptEditorBase *current) {
- erase_tab_confirm->set_text("Close and save changes?\n\""+current->get_name()+"\"");
+ erase_tab_confirm->set_text("Close and save changes?\n\"" + current->get_name() + "\"");
erase_tab_confirm->popup_centered_minsize();
}
-
-void ScriptEditor::_resave_scripts(const String& p_str) {
+void ScriptEditor::_resave_scripts(const String &p_str) {
apply_scripts();
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
continue;
-
Ref<Script> script = se->get_edited_script();
- if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1)
+ if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1)
continue; //internal script, who cares
if (trim_trailing_whitespace_on_save) {
@@ -584,14 +534,11 @@ void ScriptEditor::_resave_scripts(const String& p_str) {
}
disk_changed->hide();
-
}
-void ScriptEditor::_reload_scripts(){
-
+void ScriptEditor::_reload_scripts() {
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se) {
@@ -599,46 +546,36 @@ void ScriptEditor::_reload_scripts(){
continue;
}
-
Ref<Script> script = se->get_edited_script();
- if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) {
+ if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1) {
continue; //internal script, who cares
}
-
uint64_t last_date = script->get_last_modified_time();
uint64_t date = FileAccess::get_modified_time(script->get_path());
//printf("last date: %lli vs date: %lli\n",last_date,date);
- if (last_date==date) {
+ if (last_date == date) {
continue;
}
-
- Ref<Script> rel_script = ResourceLoader::load(script->get_path(),script->get_class(),true);
+ Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), true);
ERR_CONTINUE(!rel_script.is_valid());
- script->set_source_code( rel_script->get_source_code() );
- script->set_last_modified_time( rel_script->get_last_modified_time() );
+ script->set_source_code(rel_script->get_source_code());
+ script->set_last_modified_time(rel_script->get_last_modified_time());
script->reload();
se->reload_text();
-
-
}
disk_changed->hide();
_update_script_names();
-
}
+void ScriptEditor::_res_saved_callback(const Ref<Resource> &p_res) {
-
-void ScriptEditor::_res_saved_callback(const Ref<Resource>& p_res) {
-
-
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se) {
@@ -646,105 +583,94 @@ void ScriptEditor::_res_saved_callback(const Ref<Resource>& p_res) {
continue;
}
-
Ref<Script> script = se->get_edited_script();
- if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) {
+ if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1) {
continue; //internal script, who cares
}
- if (script==p_res) {
+ if (script == p_res) {
se->tag_saved_version();
}
-
}
_update_script_names();
-
if (!pending_auto_reload && auto_reload_running_scripts) {
call_deferred("_live_auto_reload_running_scripts");
- pending_auto_reload=true;
+ pending_auto_reload = true;
}
}
void ScriptEditor::_live_auto_reload_running_scripts() {
- pending_auto_reload=false;
+ pending_auto_reload = false;
debugger->reload_scripts();
}
-
bool ScriptEditor::_test_script_times_on_disk(Ref<Script> p_for_script) {
-
disk_changed_list->clear();
TreeItem *r = disk_changed_list->create_item();
disk_changed_list->set_hide_root(true);
- bool need_ask=false;
- bool need_reload=false;
- bool use_autoreload=bool(EDITOR_DEF("text_editor/files/auto_reload_scripts_on_external_change",false));
-
+ bool need_ask = false;
+ bool need_reload = false;
+ bool use_autoreload = bool(EDITOR_DEF("text_editor/files/auto_reload_scripts_on_external_change", false));
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (se) {
Ref<Script> script = se->get_edited_script();
- if (p_for_script.is_valid() && p_for_script!=script)
+ if (p_for_script.is_valid() && p_for_script != script)
continue;
- if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1)
+ if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1)
continue; //internal script, who cares
-
uint64_t last_date = script->get_last_modified_time();
uint64_t date = FileAccess::get_modified_time(script->get_path());
//printf("last date: %lli vs date: %lli\n",last_date,date);
- if (last_date!=date) {
+ if (last_date != date) {
TreeItem *ti = disk_changed_list->create_item(r);
- ti->set_text(0,script->get_path().get_file());
+ ti->set_text(0, script->get_path().get_file());
if (!use_autoreload || se->is_unsaved()) {
- need_ask=true;
+ need_ask = true;
}
- need_reload=true;
+ need_reload = true;
//r->set_metadata(0,);
}
}
}
-
-
if (need_reload) {
if (!need_ask) {
script_editor->_reload_scripts();
- need_reload=false;
+ need_reload = false;
} else {
- disk_changed->call_deferred("popup_centered_ratio",0.5);
+ disk_changed->call_deferred("popup_centered_ratio", 0.5);
}
}
return need_reload;
}
-
void ScriptEditor::_file_dialog_action(String p_file) {
switch (file_dialog_option) {
case FILE_SAVE_THEME_AS: {
- if(!EditorSettings::get_singleton()->save_text_editor_theme_as(p_file)) {
+ if (!EditorSettings::get_singleton()->save_text_editor_theme_as(p_file)) {
editor->show_warning(TTR("Error while saving theme"), TTR("Error saving"));
}
} break;
case FILE_IMPORT_THEME: {
- if(!EditorSettings::get_singleton()->import_text_editor_theme(p_file)) {
+ if (!EditorSettings::get_singleton()->import_text_editor_theme(p_file)) {
editor->show_warning(TTR("Error importing theme"), TTR("Error importing"));
}
} break;
@@ -754,11 +680,10 @@ void ScriptEditor::_file_dialog_action(String p_file) {
void ScriptEditor::_menu_option(int p_option) {
-
- switch(p_option) {
+ switch (p_option) {
case FILE_NEW: {
script_create_dialog->config("Node", ".gd");
- script_create_dialog->popup_centered(Size2(300, 300)*EDSCALE);
+ script_create_dialog->popup_centered(Size2(300, 300) * EDSCALE);
} break;
case FILE_OPEN: {
@@ -785,7 +710,7 @@ void ScriptEditor::_menu_option(int p_option) {
EditorSettings::get_singleton()->load_text_editor_theme();
} break;
case FILE_SAVE_THEME: {
- if(!EditorSettings::get_singleton()->save_text_editor_theme()) {
+ if (!EditorSettings::get_singleton()->save_text_editor_theme()) {
editor->show_warning(TTR("Error while saving theme"), TTR("Error saving"));
}
} break;
@@ -807,17 +732,17 @@ void ScriptEditor::_menu_option(int p_option) {
String current;
- if (tab_container->get_tab_count()>0) {
- EditorHelp *eh = tab_container->get_child( tab_container->get_current_tab() )->cast_to<EditorHelp>();
+ if (tab_container->get_tab_count() > 0) {
+ EditorHelp *eh = tab_container->get_child(tab_container->get_current_tab())->cast_to<EditorHelp>();
if (eh) {
- current=eh->get_class();
+ current = eh->get_class();
}
}
help_index->popup();
- if (current!="") {
- help_index->call_deferred("select_class",current);
+ if (current != "") {
+ help_index->call_deferred("select_class", current);
}
} break;
case SEARCH_WEBSITE: {
@@ -834,8 +759,8 @@ void ScriptEditor::_menu_option(int p_option) {
} break;
case DEBUG_SHOW: {
if (debugger) {
- bool visible = debug_menu->get_popup()->is_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW) );
- debug_menu->get_popup()->set_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW), !visible);
+ bool visible = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(DEBUG_SHOW));
+ debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(DEBUG_SHOW), !visible);
if (visible)
debugger->hide();
else
@@ -843,25 +768,24 @@ void ScriptEditor::_menu_option(int p_option) {
}
} break;
case DEBUG_SHOW_KEEP_OPEN: {
- bool visible = debug_menu->get_popup()->is_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN) );
+ bool visible = debug_menu->get_popup()->is_item_checked(debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN));
if (debugger)
debugger->set_hide_on_stop(visible);
- debug_menu->get_popup()->set_item_checked( debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN), !visible);
+ debug_menu->get_popup()->set_item_checked(debug_menu->get_popup()->get_item_index(DEBUG_SHOW_KEEP_OPEN), !visible);
} break;
}
-
int selected = tab_container->get_current_tab();
- if (selected<0 || selected>=tab_container->get_child_count())
+ if (selected < 0 || selected >= tab_container->get_child_count())
return;
ScriptEditorBase *current = tab_container->get_child(selected)->cast_to<ScriptEditorBase>();
if (current) {
- switch(p_option) {
+ switch (p_option) {
case FILE_NEW: {
script_create_dialog->config("Node", ".gd");
- script_create_dialog->popup_centered(Size2(300, 300)*EDSCALE);
+ script_create_dialog->popup_centered(Size2(300, 300) * EDSCALE);
} break;
case FILE_SAVE: {
@@ -870,21 +794,21 @@ void ScriptEditor::_menu_option(int p_option) {
if (trim_trailing_whitespace_on_save)
current->trim_trailing_whitespace();
- editor->save_resource( current->get_edited_script() );
+ editor->save_resource(current->get_edited_script());
} break;
case FILE_SAVE_AS: {
current->trim_trailing_whitespace();
editor->push_item(current->get_edited_script()->cast_to<Object>());
- editor->save_resource_as( current->get_edited_script() );
+ editor->save_resource_as(current->get_edited_script());
} break;
case FILE_TOOL_RELOAD:
case FILE_TOOL_RELOAD_SOFT: {
- current->reload(p_option==FILE_TOOL_RELOAD_SOFT);
+ current->reload(p_option == FILE_TOOL_RELOAD_SOFT);
} break;
@@ -926,32 +850,30 @@ void ScriptEditor::_menu_option(int p_option) {
} break;
case WINDOW_MOVE_LEFT: {
- if (tab_container->get_current_tab()>0) {
- tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()-1);
- script_list->call_deferred("select",tab_container->get_current_tab()-1);
- tab_container->move_child(current,tab_container->get_current_tab()-1);
+ if (tab_container->get_current_tab() > 0) {
+ tab_container->call_deferred("set_current_tab", tab_container->get_current_tab() - 1);
+ script_list->call_deferred("select", tab_container->get_current_tab() - 1);
+ tab_container->move_child(current, tab_container->get_current_tab() - 1);
_update_script_names();
}
} break;
case WINDOW_MOVE_RIGHT: {
- if (tab_container->get_current_tab()<tab_container->get_child_count()-1) {
- tab_container->call_deferred("set_current_tab",tab_container->get_current_tab()+1);
- script_list->call_deferred("select",tab_container->get_current_tab()+1);
- tab_container->move_child(current,tab_container->get_current_tab()+1);
+ if (tab_container->get_current_tab() < tab_container->get_child_count() - 1) {
+ tab_container->call_deferred("set_current_tab", tab_container->get_current_tab() + 1);
+ script_list->call_deferred("select", tab_container->get_current_tab() + 1);
+ tab_container->move_child(current, tab_container->get_current_tab() + 1);
_update_script_names();
}
-
} break;
default: {
- if (p_option>=WINDOW_SELECT_BASE) {
-
- tab_container->set_current_tab(p_option-WINDOW_SELECT_BASE);
- script_list->select(p_option-WINDOW_SELECT_BASE);
+ if (p_option >= WINDOW_SELECT_BASE) {
+ tab_container->set_current_tab(p_option - WINDOW_SELECT_BASE);
+ script_list->select(p_option - WINDOW_SELECT_BASE);
}
}
}
@@ -960,7 +882,7 @@ void ScriptEditor::_menu_option(int p_option) {
EditorHelp *help = tab_container->get_current_tab_control()->cast_to<EditorHelp>();
if (help) {
- switch(p_option) {
+ switch (p_option) {
case HELP_SEARCH_FIND: {
help->popup_search();
@@ -977,12 +899,8 @@ void ScriptEditor::_menu_option(int p_option) {
case CLOSE_ALL: {
_close_all_tabs();
} break;
-
-
}
}
-
-
}
void ScriptEditor::_tab_changed(int p_which) {
@@ -992,19 +910,19 @@ void ScriptEditor::_tab_changed(int p_which) {
void ScriptEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- editor->connect("play_pressed",this,"_editor_play");
- editor->connect("pause_pressed",this,"_editor_pause");
- editor->connect("stop_pressed",this,"_editor_stop");
- editor->connect("script_add_function_request",this,"_add_callback");
- editor->connect("resource_saved",this,"_res_saved_callback");
- script_list->connect("item_selected",this,"_script_selected");
- script_split->connect("dragged",this,"_script_split_dragged");
- autosave_timer->connect("timeout",this,"_autosave_scripts");
+ editor->connect("play_pressed", this, "_editor_play");
+ editor->connect("pause_pressed", this, "_editor_pause");
+ editor->connect("stop_pressed", this, "_editor_stop");
+ editor->connect("script_add_function_request", this, "_add_callback");
+ editor->connect("resource_saved", this, "_res_saved_callback");
+ script_list->connect("item_selected", this, "_script_selected");
+ script_split->connect("dragged", this, "_script_split_dragged");
+ autosave_timer->connect("timeout", this, "_autosave_scripts");
{
float autosave_time = EditorSettings::get_singleton()->get("text_editor/files/autosave_interval_secs");
- if (autosave_time>0) {
+ if (autosave_time > 0) {
autosave_timer->set_wait_time(autosave_time);
autosave_timer->start();
} else {
@@ -1012,65 +930,54 @@ void ScriptEditor::_notification(int p_what) {
}
}
- EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed");
- help_search->set_icon(get_icon("Help","EditorIcons"));
- site_search->set_icon(get_icon("Godot","EditorIcons"));
- class_search->set_icon(get_icon("ClassList","EditorIcons"));
-
- script_forward->set_icon(get_icon("Forward","EditorIcons"));
- script_back->set_icon(get_icon("Back","EditorIcons"));
-
-
-
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_editor_settings_changed");
+ help_search->set_icon(get_icon("Help", "EditorIcons"));
+ site_search->set_icon(get_icon("Godot", "EditorIcons"));
+ class_search->set_icon(get_icon("ClassList", "EditorIcons"));
+ script_forward->set_icon(get_icon("Forward", "EditorIcons"));
+ script_back->set_icon(get_icon("Back", "EditorIcons"));
}
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
- get_tree()->connect("tree_changed",this,"_tree_changed");
- editor->connect("request_help",this,"_request_help");
+ get_tree()->connect("tree_changed", this, "_tree_changed");
+ editor->connect("request_help", this, "_request_help");
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
- editor->disconnect("play_pressed",this,"_editor_play");
- editor->disconnect("pause_pressed",this,"_editor_pause");
- editor->disconnect("stop_pressed",this,"_editor_stop");
+ if (p_what == NOTIFICATION_EXIT_TREE) {
+ editor->disconnect("play_pressed", this, "_editor_play");
+ editor->disconnect("pause_pressed", this, "_editor_pause");
+ editor->disconnect("stop_pressed", this, "_editor_stop");
}
- if (p_what==MainLoop::NOTIFICATION_WM_FOCUS_IN) {
+ if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {
_test_script_times_on_disk();
_update_modified_scripts_for_external_editor();
}
- if (p_what==NOTIFICATION_PROCESS) {
-
+ if (p_what == NOTIFICATION_PROCESS) {
}
-
}
bool ScriptEditor::can_take_away_focus() const {
int selected = tab_container->get_current_tab();
- if (selected<0 || selected>=tab_container->get_child_count())
+ if (selected < 0 || selected >= tab_container->get_child_count())
return true;
ScriptEditorBase *current = tab_container->get_child(selected)->cast_to<ScriptEditorBase>();
if (!current)
return true;
-
return current->can_lose_focus_on_node_selection();
-
}
-void ScriptEditor::close_builtin_scripts_from_scene(const String& p_scene) {
-
+void ScriptEditor::close_builtin_scripts_from_scene(const String &p_scene) {
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
@@ -1080,32 +987,27 @@ void ScriptEditor::close_builtin_scripts_from_scene(const String& p_scene) {
if (!script.is_valid())
continue;
- if (script->get_path().find("::")!=-1 && script->get_path().begins_with(p_scene)) { //is an internal script and belongs to scene being closed
+ if (script->get_path().find("::") != -1 && script->get_path().begins_with(p_scene)) { //is an internal script and belongs to scene being closed
_close_tab(i);
i--;
-
}
}
-
}
-
-
}
void ScriptEditor::edited_scene_changed() {
_update_modified_scripts_for_external_editor();
-
}
-static const Node * _find_node_with_script(const Node* p_node, const RefPtr & p_script) {
+static const Node *_find_node_with_script(const Node *p_node, const RefPtr &p_script) {
- if (p_node->get_script()==p_script)
+ if (p_node->get_script() == p_script)
return p_node;
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- const Node *result = _find_node_with_script(p_node->get_child(i),p_script);
+ const Node *result = _find_node_with_script(p_node->get_child(i), p_script);
if (result)
return result;
}
@@ -1115,7 +1017,6 @@ static const Node * _find_node_with_script(const Node* p_node, const RefPtr & p_
Dictionary ScriptEditor::get_state() const {
-
//apply_scripts();
Dictionary state;
@@ -1155,7 +1056,7 @@ Dictionary ScriptEditor::get_state() const {
#endif
return state;
}
-void ScriptEditor::set_state(const Dictionary& p_state) {
+void ScriptEditor::set_state(const Dictionary &p_state) {
#if 0
print_line("attempt set state: "+String(Variant(p_state)));
@@ -1195,7 +1096,6 @@ void ScriptEditor::set_state(const Dictionary& p_state) {
tab_container->set_current_tab(p_state["current"]);
}
#endif
-
}
void ScriptEditor::clear() {
#if 0
@@ -1224,15 +1124,11 @@ void ScriptEditor::clear() {
}
#endif
-
-
}
-
void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) {
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
@@ -1242,27 +1138,23 @@ void ScriptEditor::get_breakpoints(List<String> *p_breakpoints) {
se->get_breakpoints(&bpoints);
Ref<Script> script = se->get_edited_script();
String base = script->get_path();
- ERR_CONTINUE( base.begins_with("local://") || base=="" );
+ ERR_CONTINUE(base.begins_with("local://") || base == "");
- for(List<int>::Element *E=bpoints.front();E;E=E->next()) {
+ for (List<int>::Element *E = bpoints.front(); E; E = E->next()) {
- p_breakpoints->push_back(base+":"+itos(E->get()+1));
+ p_breakpoints->push_back(base + ":" + itos(E->get() + 1));
}
}
-
}
-
-
-
-
void ScriptEditor::ensure_focus_current() {
if (!is_inside_tree())
return;
int cidx = tab_container->get_current_tab();
- if (cidx<0 || cidx>=tab_container->get_tab_count());
+ if (cidx < 0 || cidx >= tab_container->get_tab_count())
+ ;
Control *c = tab_container->get_child(cidx)->cast_to<Control>();
if (!c)
return;
@@ -1277,17 +1169,15 @@ void ScriptEditor::_script_selected(int p_idx) {
grab_focus_block = !Input::get_singleton()->is_mouse_button_pressed(1); //amazing hack, simply amazing
_go_to_tab(script_list->get_item_metadata(p_idx));
- grab_focus_block=false;
+ grab_focus_block = false;
}
void ScriptEditor::ensure_select_current() {
-
- if (tab_container->get_child_count() && tab_container->get_current_tab()>=0) {
+ if (tab_container->get_child_count() && tab_container->get_current_tab() >= 0) {
Node *current = tab_container->get_child(tab_container->get_current_tab());
-
ScriptEditorBase *se = current->cast_to<ScriptEditorBase>();
if (se) {
@@ -1296,11 +1186,8 @@ void ScriptEditor::ensure_select_current() {
if (!grab_focus_block && is_visible_in_tree())
se->ensure_focus();
-
//edit_menu->show();
//search_menu->show();
-
-
}
EditorHelp *eh = current->cast_to<EditorHelp>();
@@ -1309,18 +1196,14 @@ void ScriptEditor::ensure_select_current() {
//edit_menu->hide();
//search_menu->hide();
//script_search_menu->show();
-
}
}
_update_selected_editor_menu();
-
-
-
}
-void ScriptEditor::_find_scripts(Node* p_base, Node* p_current, Set<Ref<Script> > &used) {
- if (p_current!=p_base && p_current->get_owner()!=p_base)
+void ScriptEditor::_find_scripts(Node *p_base, Node *p_current, Set<Ref<Script> > &used) {
+ if (p_current != p_base && p_current->get_owner() != p_base)
return;
if (p_current->get_script_instance()) {
@@ -1329,10 +1212,9 @@ void ScriptEditor::_find_scripts(Node* p_base, Node* p_current, Set<Ref<Script>
used.insert(scr);
}
- for(int i=0;i<p_current->get_child_count();i++) {
- _find_scripts(p_base,p_current->get_child(i),used);
+ for (int i = 0; i < p_current->get_child_count(); i++) {
+ _find_scripts(p_base, p_current->get_child(i), used);
}
-
}
struct _ScriptEditorItemData {
@@ -1345,32 +1227,29 @@ struct _ScriptEditorItemData {
bool used;
int category;
+ bool operator<(const _ScriptEditorItemData &id) const {
- bool operator<(const _ScriptEditorItemData& id) const {
-
- return category==id.category?sort_key<id.sort_key:category<id.category;
+ return category == id.category ? sort_key < id.sort_key : category < id.category;
}
-
};
-
void ScriptEditor::_update_script_colors() {
bool script_temperature_enabled = EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_enabled");
bool highlight_current = EditorSettings::get_singleton()->get("text_editor/open_scripts/highlight_current_script");
int hist_size = EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_history_size");
- Color hot_color=EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_hot_color");
- Color cold_color=EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_cold_color");
+ Color hot_color = EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_hot_color");
+ Color cold_color = EditorSettings::get_singleton()->get("text_editor/open_scripts/script_temperature_cold_color");
- for(int i=0;i<script_list->get_item_count();i++) {
+ for (int i = 0; i < script_list->get_item_count(); i++) {
int c = script_list->get_item_metadata(i);
Node *n = tab_container->get_child(c);
if (!n)
continue;
- script_list->set_item_custom_bg_color(i,Color(0,0,0,0));
+ script_list->set_item_custom_bg_color(i, Color(0, 0, 0, 0));
bool current = tab_container->get_current_tab() == c;
if (current && highlight_current) {
@@ -1382,15 +1261,15 @@ void ScriptEditor::_update_script_colors() {
continue;
}
- int pass=n->get_meta("__editor_pass");
+ int pass = n->get_meta("__editor_pass");
int h = edit_pass - pass;
- if (h>hist_size) {
+ if (h > hist_size) {
continue;
}
- int non_zero_hist_size = ( hist_size == 0 ) ? 1 : hist_size;
- float v = Math::ease((edit_pass-pass)/float(non_zero_hist_size),0.4);
+ int non_zero_hist_size = (hist_size == 0) ? 1 : hist_size;
+ float v = Math::ease((edit_pass - pass) / float(non_zero_hist_size), 0.4);
- script_list->set_item_custom_bg_color(i,hot_color.linear_interpolate(cold_color,v));
+ script_list->set_item_custom_bg_color(i, hot_color.linear_interpolate(cold_color, v));
}
}
}
@@ -1400,22 +1279,21 @@ void ScriptEditor::_update_script_names() {
if (restoring_layout)
return;
- waiting_update_names=false;
+ waiting_update_names = false;
Set<Ref<Script> > used;
- Node* edited = EditorNode::get_singleton()->get_edited_scene();
+ Node *edited = EditorNode::get_singleton()->get_edited_scene();
if (edited) {
- _find_scripts(edited,edited,used);
+ _find_scripts(edited, edited, used);
}
script_list->clear();
bool split_script_help = EditorSettings::get_singleton()->get("text_editor/open_scripts/group_help_pages");
- ScriptSortBy sort_by = (ScriptSortBy) (int) EditorSettings::get_singleton()->get("text_editor/open_scripts/sort_scripts_by");
- ScriptListName display_as = (ScriptListName) (int) EditorSettings::get_singleton()->get("text_editor/open_scripts/list_script_names_as");
+ ScriptSortBy sort_by = (ScriptSortBy)(int)EditorSettings::get_singleton()->get("text_editor/open_scripts/sort_scripts_by");
+ ScriptListName display_as = (ScriptListName)(int)EditorSettings::get_singleton()->get("text_editor/open_scripts/list_script_names_as");
Vector<_ScriptEditorItemData> sedata;
- for(int i=0;i<tab_container->get_child_count();i++) {
-
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (se) {
@@ -1425,39 +1303,38 @@ void ScriptEditor::_update_script_names() {
String path = se->get_edited_script()->get_path();
_ScriptEditorItemData sd;
- sd.icon=icon;
- sd.name=name;
- sd.tooltip=path;
- sd.index=i;
- sd.used=used.has(se->get_edited_script());
- sd.category=0;
-
+ sd.icon = icon;
+ sd.name = name;
+ sd.tooltip = path;
+ sd.index = i;
+ sd.used = used.has(se->get_edited_script());
+ sd.category = 0;
+
switch (sort_by) {
case SORT_BY_NAME: {
- sd.sort_key=name.to_lower();
+ sd.sort_key = name.to_lower();
} break;
case SORT_BY_PATH: {
- sd.sort_key=path;
+ sd.sort_key = path;
} break;
}
-
+
switch (display_as) {
case DISPLAY_NAME: {
- sd.name=name;
+ sd.name = name;
} break;
case DISPLAY_DIR_AND_NAME: {
if (!path.get_base_dir().get_file().empty()) {
- sd.name=path.get_base_dir().get_file() + "/" + name;
+ sd.name = path.get_base_dir().get_file() + "/" + name;
} else {
- sd.name=name;
+ sd.name = name;
}
} break;
case DISPLAY_FULL_PATH: {
- sd.name=path;
+ sd.name = path;
} break;
}
-
sedata.push_back(sd);
}
@@ -1465,62 +1342,50 @@ void ScriptEditor::_update_script_names() {
if (eh) {
String name = eh->get_class();
- Ref<Texture> icon = get_icon("Help","EditorIcons");
- String tooltip = name+" Class Reference";
+ Ref<Texture> icon = get_icon("Help", "EditorIcons");
+ String tooltip = name + " Class Reference";
_ScriptEditorItemData sd;
- sd.icon=icon;
- sd.name=name;
- sd.sort_key=name;
- sd.tooltip=tooltip;
- sd.index=i;
- sd.used=false;
- sd.category=split_script_help?1:0;
+ sd.icon = icon;
+ sd.name = name;
+ sd.sort_key = name;
+ sd.tooltip = tooltip;
+ sd.index = i;
+ sd.used = false;
+ sd.category = split_script_help ? 1 : 0;
sedata.push_back(sd);
-
}
-
}
sedata.sort();
- for(int i=0;i<sedata.size();i++) {
+ for (int i = 0; i < sedata.size(); i++) {
- script_list->add_item(sedata[i].name,sedata[i].icon);
- int index = script_list->get_item_count()-1;
- script_list->set_item_tooltip(index,sedata[i].tooltip);
- script_list->set_item_metadata(index,sedata[i].index);
+ script_list->add_item(sedata[i].name, sedata[i].icon);
+ int index = script_list->get_item_count() - 1;
+ script_list->set_item_tooltip(index, sedata[i].tooltip);
+ script_list->set_item_metadata(index, sedata[i].index);
if (sedata[i].used) {
- script_list->set_item_custom_bg_color(index,Color(88/255.0,88/255.0,60/255.0));
+ script_list->set_item_custom_bg_color(index, Color(88 / 255.0, 88 / 255.0, 60 / 255.0));
}
- if (tab_container->get_current_tab()==sedata[i].index) {
+ if (tab_container->get_current_tab() == sedata[i].index) {
script_list->select(index);
script_name_label->set_text(sedata[i].name);
script_icon->set_texture(sedata[i].icon);
-
}
}
_update_script_colors();
-
-
-
-
}
-
-
-void ScriptEditor::edit(const Ref<Script>& p_script, bool p_grab_focus) {
+void ScriptEditor::edit(const Ref<Script> &p_script, bool p_grab_focus) {
if (p_script.is_null())
return;
// refuse to open built-in if scene is not loaded
-
-
-
// see if already has it
bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change");
@@ -1530,33 +1395,32 @@ void ScriptEditor::edit(const Ref<Script>& p_script, bool p_grab_focus) {
String path = EditorSettings::get_singleton()->get("text_editor/external/exec_path");
String flags = EditorSettings::get_singleton()->get("text_editor/external/exec_flags");
List<String> args;
- flags=flags.strip_edges();
- if (flags!=String()) {
- Vector<String> flagss = flags.split(" ",false);
- for(int i=0;i<flagss.size();i++)
+ flags = flags.strip_edges();
+ if (flags != String()) {
+ Vector<String> flagss = flags.split(" ", false);
+ for (int i = 0; i < flagss.size(); i++)
args.push_back(flagss[i]);
}
args.push_back(GlobalConfig::get_singleton()->globalize_path(p_script->get_path()));
- Error err = OS::get_singleton()->execute(path,args,false);
- if (err==OK)
+ Error err = OS::get_singleton()->execute(path, args, false);
+ if (err == OK)
return;
WARN_PRINT("Couldn't open external text editor, using internal");
}
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
continue;
- if (se->get_edited_script()==p_script) {
+ if (se->get_edited_script() == p_script) {
if (open_dominant || !EditorNode::get_singleton()->is_changing_scene()) {
- if (tab_container->get_current_tab()!=i) {
+ if (tab_container->get_current_tab() != i) {
_go_to_tab(i);
- script_list->select( script_list->find_metadata(i) );
+ script_list->select(script_list->find_metadata(i));
}
if (is_visible_in_tree())
se->ensure_focus();
@@ -1569,7 +1433,7 @@ void ScriptEditor::edit(const Ref<Script>& p_script, bool p_grab_focus) {
ScriptEditorBase *se;
- for(int i=script_editor_func_count-1;i>=0;i--) {
+ for (int i = script_editor_func_count - 1; i >= 0; i--) {
se = script_editor_funcs[i](p_script);
if (se)
break;
@@ -1578,50 +1442,39 @@ void ScriptEditor::edit(const Ref<Script>& p_script, bool p_grab_focus) {
tab_container->add_child(se);
se->set_edited_script(p_script);
- se->set_tooltip_request_func("_get_debug_tooltip",this);
+ se->set_tooltip_request_func("_get_debug_tooltip", this);
if (se->get_edit_menu()) {
se->get_edit_menu()->hide();
menu_hb->add_child(se->get_edit_menu());
- menu_hb->move_child(se->get_edit_menu(),1);
+ menu_hb->move_child(se->get_edit_menu(), 1);
}
-
if (p_grab_focus) {
- _go_to_tab(tab_container->get_tab_count()-1);
+ _go_to_tab(tab_container->get_tab_count() - 1);
}
-
-
-
-
_update_script_names();
_save_layout();
- se->connect("name_changed",this,"_update_script_names");
- se->connect("request_help_search",this,"_help_search");
- se->connect("request_open_script_at_line",this,"_goto_script_line");
- se->connect("go_to_help",this,"_help_class_goto");
- se->connect("request_save_history",this,"_save_history");
-
-
-
+ se->connect("name_changed", this, "_update_script_names");
+ se->connect("request_help_search", this, "_help_search");
+ se->connect("request_open_script_at_line", this, "_goto_script_line");
+ se->connect("go_to_help", this, "_help_class_goto");
+ se->connect("request_save_history", this, "_save_history");
//test for modification, maybe the script was not edited but was loaded
_test_script_times_on_disk(p_script);
_update_modified_scripts_for_external_editor(p_script);
-
}
void ScriptEditor::save_all_scripts() {
-
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
continue;
-
if (!se->is_unsaved())
continue;
@@ -1633,57 +1486,51 @@ void ScriptEditor::save_all_scripts() {
if (script.is_valid())
se->apply_code();
- if (script->get_path()!="" && script->get_path().find("local://")==-1 &&script->get_path().find("::")==-1) {
+ if (script->get_path() != "" && script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) {
//external script, save it
editor->save_resource(script);
//ResourceSaver::save(script->get_path(),script);
-
}
-
}
_update_script_names();
-
}
void ScriptEditor::apply_scripts() const {
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
continue;
se->apply_code();
}
-
}
void ScriptEditor::_editor_play() {
debugger->start();
debug_menu->get_popup()->grab_focus();
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_STEP), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_BREAK), false );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true );
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_STEP), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_BREAK), false);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true);
- //debugger_gui->start_listening(Globals::get_singleton()->get("debug/debug_port"));
+ //debugger_gui->start_listening(Globals::get_singleton()->get("debug/debug_port"));
}
void ScriptEditor::_editor_pause() {
-
-
}
void ScriptEditor::_editor_stop() {
debugger->stop();
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_STEP), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_BREAK), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true );
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_STEP), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_BREAK), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true);
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se) {
@@ -1695,34 +1542,31 @@ void ScriptEditor::_editor_stop() {
}
}
-
-void ScriptEditor::_add_callback(Object *p_obj, const String& p_function, const PoolStringArray& p_args) {
+void ScriptEditor::_add_callback(Object *p_obj, const String &p_function, const PoolStringArray &p_args) {
//print_line("add callback! hohoho"); kinda sad to remove this
ERR_FAIL_COND(!p_obj);
Ref<Script> script = p_obj->get_script();
- ERR_FAIL_COND( !script.is_valid() );
+ ERR_FAIL_COND(!script.is_valid());
editor->push_item(script.ptr());
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
continue;
- if (se->get_edited_script()!=script)
+ if (se->get_edited_script() != script)
continue;
- se->add_callback(p_function,p_args);
+ se->add_callback(p_function, p_args);
_go_to_tab(i);
- script_list->select( script_list->find_metadata(i) );
+ script_list->select(script_list->find_metadata(i));
break;
-
}
-
}
void ScriptEditor::_save_layout() {
@@ -1738,7 +1582,7 @@ void ScriptEditor::_editor_settings_changed() {
trim_trailing_whitespace_on_save = EditorSettings::get_singleton()->get("text_editor/files/trim_trailing_whitespace_on_save");
float autosave_time = EditorSettings::get_singleton()->get("text_editor/files/autosave_interval_secs");
- if (autosave_time>0) {
+ if (autosave_time > 0) {
autosave_timer->set_wait_time(autosave_time);
autosave_timer->start();
} else {
@@ -1752,7 +1596,7 @@ void ScriptEditor::_editor_settings_changed() {
EditorSettings::get_singleton()->load_text_editor_theme();
}
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (!se)
@@ -1763,8 +1607,7 @@ void ScriptEditor::_editor_settings_changed() {
_update_script_colors();
_update_script_names();
- ScriptServer::set_reload_scripts_on_save(EDITOR_DEF("text_editor/files/auto_reload_and_parse_scripts_on_save",true));
-
+ ScriptServer::set_reload_scripts_on_save(EDITOR_DEF("text_editor/files/auto_reload_and_parse_scripts_on_save", true));
}
void ScriptEditor::_autosave_scripts() {
@@ -1777,7 +1620,7 @@ void ScriptEditor::_tree_changed() {
if (waiting_update_names)
return;
- waiting_update_names=true;
+ waiting_update_names = true;
call_deferred("_update_script_names");
}
@@ -1786,7 +1629,7 @@ void ScriptEditor::_script_split_dragged(float) {
_save_layout();
}
-void ScriptEditor::_unhandled_input(const InputEvent& p_event) {
+void ScriptEditor::_unhandled_input(const InputEvent &p_event) {
if (p_event.key.pressed || !is_visible_in_tree()) return;
if (ED_IS_SHORTCUT("script_editor/next_script", p_event)) {
int next_tab = script_list->get_current() + 1;
@@ -1804,21 +1647,21 @@ void ScriptEditor::_unhandled_input(const InputEvent& p_event) {
void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) {
- if (!bool(EDITOR_DEF("text_editor/files/restore_scripts_on_load",true))) {
+ if (!bool(EDITOR_DEF("text_editor/files/restore_scripts_on_load", true))) {
return;
}
- if (!p_layout->has_section_key("ScriptEditor","open_scripts") && !p_layout->has_section_key("ScriptEditor","open_help"))
+ if (!p_layout->has_section_key("ScriptEditor", "open_scripts") && !p_layout->has_section_key("ScriptEditor", "open_help"))
return;
- Array scripts = p_layout->get_value("ScriptEditor","open_scripts");
+ Array scripts = p_layout->get_value("ScriptEditor", "open_scripts");
Array helps;
- if (p_layout->has_section_key("ScriptEditor","open_help"))
- helps=p_layout->get_value("ScriptEditor","open_help");
+ if (p_layout->has_section_key("ScriptEditor", "open_help"))
+ helps = p_layout->get_value("ScriptEditor", "open_help");
- restoring_layout=true;
+ restoring_layout = true;
- for(int i=0;i<scripts.size();i++) {
+ for (int i = 0; i < scripts.size(); i++) {
String path = scripts[i];
if (!FileAccess::exists(path))
@@ -1829,22 +1672,21 @@ void ScriptEditor::set_window_layout(Ref<ConfigFile> p_layout) {
}
}
- for(int i=0;i<helps.size();i++) {
+ for (int i = 0; i < helps.size(); i++) {
String path = helps[i];
_help_class_open(path);
}
- for(int i=0;i<tab_container->get_child_count();i++) {
- tab_container->get_child(i)->set_meta("__editor_pass",Variant());
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
+ tab_container->get_child(i)->set_meta("__editor_pass", Variant());
}
-
- if (p_layout->has_section_key("ScriptEditor","split_offset")) {
- script_split->set_split_offset(p_layout->get_value("ScriptEditor","split_offset"));
+ if (p_layout->has_section_key("ScriptEditor", "split_offset")) {
+ script_split->set_split_offset(p_layout->get_value("ScriptEditor", "split_offset"));
}
- restoring_layout=false;
+ restoring_layout = false;
_update_script_names();
}
@@ -1854,7 +1696,7 @@ void ScriptEditor::get_window_layout(Ref<ConfigFile> p_layout) {
Array scripts;
Array helps;
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *se = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
if (se) {
@@ -1872,26 +1714,23 @@ void ScriptEditor::get_window_layout(Ref<ConfigFile> p_layout) {
helps.push_back(eh->get_class());
}
-
-
}
- p_layout->set_value("ScriptEditor","open_scripts",scripts);
- p_layout->set_value("ScriptEditor","open_help",helps);
- p_layout->set_value("ScriptEditor","split_offset",script_split->get_split_offset());
+ p_layout->set_value("ScriptEditor", "open_scripts", scripts);
+ p_layout->set_value("ScriptEditor", "open_help", helps);
+ p_layout->set_value("ScriptEditor", "split_offset", script_split->get_split_offset());
}
+void ScriptEditor::_help_class_open(const String &p_class) {
-void ScriptEditor::_help_class_open(const String& p_class) {
-
- if (p_class=="")
+ if (p_class == "")
return;
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>();
- if (eh && eh->get_class()==p_class) {
+ if (eh && eh->get_class() == p_class) {
_go_to_tab(i);
_update_script_names();
@@ -1899,27 +1738,26 @@ void ScriptEditor::_help_class_open(const String& p_class) {
}
}
- EditorHelp * eh = memnew( EditorHelp );
-
+ EditorHelp *eh = memnew(EditorHelp);
eh->set_name(p_class);
tab_container->add_child(eh);
- _go_to_tab(tab_container->get_tab_count()-1);
- eh->go_to_class(p_class,0);
- eh->connect("go_to_help",this,"_help_class_goto");
+ _go_to_tab(tab_container->get_tab_count() - 1);
+ eh->go_to_class(p_class, 0);
+ eh->connect("go_to_help", this, "_help_class_goto");
_update_script_names();
_save_layout();
}
-void ScriptEditor::_help_class_goto(const String& p_desc) {
+void ScriptEditor::_help_class_goto(const String &p_desc) {
- String cname=p_desc.get_slice(":",1);
+ String cname = p_desc.get_slice(":", 1);
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
EditorHelp *eh = tab_container->get_child(i)->cast_to<EditorHelp>();
- if (eh && eh->get_class()==cname) {
+ if (eh && eh->get_class() == cname) {
_go_to_tab(i);
eh->go_to_help(p_desc);
@@ -1928,20 +1766,20 @@ void ScriptEditor::_help_class_goto(const String& p_desc) {
}
}
- EditorHelp * eh = memnew( EditorHelp );
+ EditorHelp *eh = memnew(EditorHelp);
eh->set_name(cname);
tab_container->add_child(eh);
- _go_to_tab(tab_container->get_tab_count()-1);
+ _go_to_tab(tab_container->get_tab_count() - 1);
eh->go_to_help(p_desc);
- eh->connect("go_to_help",this,"_help_class_goto");
+ eh->connect("go_to_help", this, "_help_class_goto");
_update_script_names();
_save_layout();
}
void ScriptEditor::_update_selected_editor_menu() {
- for(int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
bool current = tab_container->get_current_tab() == i;
@@ -1953,10 +1791,9 @@ void ScriptEditor::_update_selected_editor_menu() {
else
se->get_edit_menu()->hide();
}
-
}
- EditorHelp *eh=tab_container->get_current_tab_control()->cast_to<EditorHelp>();
+ EditorHelp *eh = tab_container->get_current_tab_control()->cast_to<EditorHelp>();
if (eh) {
script_search_menu->show();
} else {
@@ -1970,14 +1807,14 @@ void ScriptEditor::_update_history_pos(int p_new_pos) {
if (n->cast_to<ScriptEditorBase>()) {
- history[history_pos].state=n->cast_to<ScriptEditorBase>()->get_edit_state();
+ history[history_pos].state = n->cast_to<ScriptEditorBase>()->get_edit_state();
}
if (n->cast_to<EditorHelp>()) {
- history[history_pos].state=n->cast_to<EditorHelp>()->get_scroll();
+ history[history_pos].state = n->cast_to<EditorHelp>()->get_scroll();
}
- history_pos=p_new_pos;
+ history_pos = p_new_pos;
tab_container->set_current_tab(history[history_pos].control->get_index());
n = history[history_pos].control;
@@ -1994,28 +1831,26 @@ void ScriptEditor::_update_history_pos(int p_new_pos) {
n->cast_to<EditorHelp>()->set_focused();
}
- n->set_meta("__editor_pass",++edit_pass);
+ n->set_meta("__editor_pass", ++edit_pass);
_update_script_names();
_update_history_arrows();
_update_selected_editor_menu();
-
}
void ScriptEditor::_history_forward() {
- if (history_pos<history.size()-1) {
- _update_history_pos(history_pos+1);
+ if (history_pos < history.size() - 1) {
+ _update_history_pos(history_pos + 1);
}
}
-void ScriptEditor::_history_back(){
+void ScriptEditor::_history_back() {
- if (history_pos>0) {
- _update_history_pos(history_pos-1);
+ if (history_pos > 0) {
+ _update_history_pos(history_pos - 1);
}
-
}
-void ScriptEditor::set_scene_root_script( Ref<Script> p_script ) {
+void ScriptEditor::set_scene_root_script(Ref<Script> p_script) {
bool open_dominant = EditorSettings::get_singleton()->get("text_editor/files/open_dominant_script_on_scene_change");
@@ -2027,13 +1862,12 @@ void ScriptEditor::set_scene_root_script( Ref<Script> p_script ) {
}
}
-bool ScriptEditor::script_go_to_method(Ref<Script> p_script, const String& p_method) {
+bool ScriptEditor::script_go_to_method(Ref<Script> p_script, const String &p_method) {
-
- for (int i=0;i<tab_container->get_child_count();i++) {
+ for (int i = 0; i < tab_container->get_child_count(); i++) {
ScriptEditorBase *current = tab_container->get_child(i)->cast_to<ScriptEditorBase>();
- if (current && current->get_edited_script()==p_script) {
+ if (current && current->get_edited_script() == p_script) {
if (current->goto_method(p_method)) {
edit(p_script);
return true;
@@ -2046,123 +1880,118 @@ bool ScriptEditor::script_go_to_method(Ref<Script> p_script, const String& p_met
void ScriptEditor::set_live_auto_reload_running_scripts(bool p_enabled) {
- auto_reload_running_scripts=p_enabled;
+ auto_reload_running_scripts = p_enabled;
}
void ScriptEditor::_help_search(String p_text) {
help_search_dialog->popup(p_text);
}
-void ScriptEditor::_open_script_request(const String& p_path) {
+void ScriptEditor::_open_script_request(const String &p_path) {
Ref<Script> script = ResourceLoader::load(p_path);
if (script.is_valid()) {
- script_editor->edit(script,false);
+ script_editor->edit(script, false);
}
}
-int ScriptEditor::script_editor_func_count=0;
+int ScriptEditor::script_editor_func_count = 0;
CreateScriptEditorFunc ScriptEditor::script_editor_funcs[ScriptEditor::SCRIPT_EDITOR_FUNC_MAX];
void ScriptEditor::register_create_script_editor_function(CreateScriptEditorFunc p_func) {
- ERR_FAIL_COND(script_editor_func_count==SCRIPT_EDITOR_FUNC_MAX);
- script_editor_funcs[script_editor_func_count++]=p_func;
+ ERR_FAIL_COND(script_editor_func_count == SCRIPT_EDITOR_FUNC_MAX);
+ script_editor_funcs[script_editor_func_count++] = p_func;
}
void ScriptEditor::_bind_methods() {
- ClassDB::bind_method("_file_dialog_action",&ScriptEditor::_file_dialog_action);
- ClassDB::bind_method("_tab_changed",&ScriptEditor::_tab_changed);
- ClassDB::bind_method("_menu_option",&ScriptEditor::_menu_option);
- ClassDB::bind_method("_close_current_tab",&ScriptEditor::_close_current_tab);
+ ClassDB::bind_method("_file_dialog_action", &ScriptEditor::_file_dialog_action);
+ ClassDB::bind_method("_tab_changed", &ScriptEditor::_tab_changed);
+ ClassDB::bind_method("_menu_option", &ScriptEditor::_menu_option);
+ ClassDB::bind_method("_close_current_tab", &ScriptEditor::_close_current_tab);
ClassDB::bind_method("_close_discard_current_tab", &ScriptEditor::_close_discard_current_tab);
ClassDB::bind_method("_close_docs_tab", &ScriptEditor::_close_docs_tab);
ClassDB::bind_method("_close_all_tabs", &ScriptEditor::_close_all_tabs);
- ClassDB::bind_method("_editor_play",&ScriptEditor::_editor_play);
- ClassDB::bind_method("_editor_pause",&ScriptEditor::_editor_pause);
- ClassDB::bind_method("_editor_stop",&ScriptEditor::_editor_stop);
- ClassDB::bind_method("_add_callback",&ScriptEditor::_add_callback);
- ClassDB::bind_method("_reload_scripts",&ScriptEditor::_reload_scripts);
- ClassDB::bind_method("_resave_scripts",&ScriptEditor::_resave_scripts);
- ClassDB::bind_method("_res_saved_callback",&ScriptEditor::_res_saved_callback);
- ClassDB::bind_method("_goto_script_line",&ScriptEditor::_goto_script_line);
- ClassDB::bind_method("_goto_script_line2",&ScriptEditor::_goto_script_line2);
- ClassDB::bind_method("_help_search",&ScriptEditor::_help_search);
- ClassDB::bind_method("_save_history",&ScriptEditor::_save_history);
-
-
-
- ClassDB::bind_method("_breaked",&ScriptEditor::_breaked);
- ClassDB::bind_method("_show_debugger",&ScriptEditor::_show_debugger);
- ClassDB::bind_method("_get_debug_tooltip",&ScriptEditor::_get_debug_tooltip);
- ClassDB::bind_method("_autosave_scripts",&ScriptEditor::_autosave_scripts);
- ClassDB::bind_method("_editor_settings_changed",&ScriptEditor::_editor_settings_changed);
- ClassDB::bind_method("_update_script_names",&ScriptEditor::_update_script_names);
- ClassDB::bind_method("_tree_changed",&ScriptEditor::_tree_changed);
- ClassDB::bind_method("_script_selected",&ScriptEditor::_script_selected);
- ClassDB::bind_method("_script_created",&ScriptEditor::_script_created);
- ClassDB::bind_method("_script_split_dragged",&ScriptEditor::_script_split_dragged);
- ClassDB::bind_method("_help_class_open",&ScriptEditor::_help_class_open);
- ClassDB::bind_method("_help_class_goto",&ScriptEditor::_help_class_goto);
- ClassDB::bind_method("_request_help",&ScriptEditor::_help_class_open);
- ClassDB::bind_method("_history_forward",&ScriptEditor::_history_forward);
- ClassDB::bind_method("_history_back",&ScriptEditor::_history_back);
- ClassDB::bind_method("_live_auto_reload_running_scripts",&ScriptEditor::_live_auto_reload_running_scripts);
- ClassDB::bind_method("_unhandled_input",&ScriptEditor::_unhandled_input);
-
+ ClassDB::bind_method("_editor_play", &ScriptEditor::_editor_play);
+ ClassDB::bind_method("_editor_pause", &ScriptEditor::_editor_pause);
+ ClassDB::bind_method("_editor_stop", &ScriptEditor::_editor_stop);
+ ClassDB::bind_method("_add_callback", &ScriptEditor::_add_callback);
+ ClassDB::bind_method("_reload_scripts", &ScriptEditor::_reload_scripts);
+ ClassDB::bind_method("_resave_scripts", &ScriptEditor::_resave_scripts);
+ ClassDB::bind_method("_res_saved_callback", &ScriptEditor::_res_saved_callback);
+ ClassDB::bind_method("_goto_script_line", &ScriptEditor::_goto_script_line);
+ ClassDB::bind_method("_goto_script_line2", &ScriptEditor::_goto_script_line2);
+ ClassDB::bind_method("_help_search", &ScriptEditor::_help_search);
+ ClassDB::bind_method("_save_history", &ScriptEditor::_save_history);
+
+ ClassDB::bind_method("_breaked", &ScriptEditor::_breaked);
+ ClassDB::bind_method("_show_debugger", &ScriptEditor::_show_debugger);
+ ClassDB::bind_method("_get_debug_tooltip", &ScriptEditor::_get_debug_tooltip);
+ ClassDB::bind_method("_autosave_scripts", &ScriptEditor::_autosave_scripts);
+ ClassDB::bind_method("_editor_settings_changed", &ScriptEditor::_editor_settings_changed);
+ ClassDB::bind_method("_update_script_names", &ScriptEditor::_update_script_names);
+ ClassDB::bind_method("_tree_changed", &ScriptEditor::_tree_changed);
+ ClassDB::bind_method("_script_selected", &ScriptEditor::_script_selected);
+ ClassDB::bind_method("_script_created", &ScriptEditor::_script_created);
+ ClassDB::bind_method("_script_split_dragged", &ScriptEditor::_script_split_dragged);
+ ClassDB::bind_method("_help_class_open", &ScriptEditor::_help_class_open);
+ ClassDB::bind_method("_help_class_goto", &ScriptEditor::_help_class_goto);
+ ClassDB::bind_method("_request_help", &ScriptEditor::_help_class_open);
+ ClassDB::bind_method("_history_forward", &ScriptEditor::_history_forward);
+ ClassDB::bind_method("_history_back", &ScriptEditor::_history_back);
+ ClassDB::bind_method("_live_auto_reload_running_scripts", &ScriptEditor::_live_auto_reload_running_scripts);
+ ClassDB::bind_method("_unhandled_input", &ScriptEditor::_unhandled_input);
}
ScriptEditor::ScriptEditor(EditorNode *p_editor) {
current_theme = "";
- completion_cache = memnew( EditorScriptCodeCompletionCache );
- restoring_layout=false;
- waiting_update_names=false;
- pending_auto_reload=false;
- auto_reload_running_scripts=false;
- editor=p_editor;
+ completion_cache = memnew(EditorScriptCodeCompletionCache);
+ restoring_layout = false;
+ waiting_update_names = false;
+ pending_auto_reload = false;
+ auto_reload_running_scripts = false;
+ editor = p_editor;
- menu_hb = memnew( HBoxContainer );
+ menu_hb = memnew(HBoxContainer);
add_child(menu_hb);
-
- script_split = memnew( HSplitContainer );
+ script_split = memnew(HSplitContainer);
add_child(script_split);
script_split->set_v_size_flags(SIZE_EXPAND_FILL);
- script_list = memnew( ItemList );
+ script_list = memnew(ItemList);
script_split->add_child(script_list);
- script_list->set_custom_minimum_size(Size2(0,0));
+ script_list->set_custom_minimum_size(Size2(0, 0));
script_split->set_split_offset(140);
- tab_container = memnew( TabContainer );
+ tab_container = memnew(TabContainer);
tab_container->set_tabs_visible(false);
script_split->add_child(tab_container);
-
tab_container->set_h_size_flags(SIZE_EXPAND_FILL);
ED_SHORTCUT("script_editor/next_script", TTR("Next script"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_GREATER);
ED_SHORTCUT("script_editor/prev_script", TTR("Previous script"), KEY_MASK_CMD | KEY_LESS);
set_process_unhandled_input(true);
- file_menu = memnew( MenuButton );
+ file_menu = memnew(MenuButton);
menu_hb->add_child(file_menu);
file_menu->set_text(TTR("File"));
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/new", TTR("New")), FILE_NEW);
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/open", TTR("Open")), FILE_OPEN);
file_menu->get_popup()->add_separator();
- file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save", TTR("Save"), KEY_MASK_ALT|KEY_MASK_CMD|KEY_S), FILE_SAVE);
+ file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save", TTR("Save"), KEY_MASK_ALT | KEY_MASK_CMD | KEY_S), FILE_SAVE);
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_as", TTR("Save As..")), FILE_SAVE_AS);
- file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_all", TTR("Save All"), KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_MASK_ALT|KEY_S), FILE_SAVE_ALL);
+ file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/save_all", TTR("Save All"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_MASK_ALT | KEY_S), FILE_SAVE_ALL);
file_menu->get_popup()->add_separator();
- file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/reload_script_soft", TTR("Soft Reload Script"), KEY_MASK_CMD|KEY_MASK_SHIFT|KEY_R), FILE_TOOL_RELOAD_SOFT);
+ file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/reload_script_soft", TTR("Soft Reload Script"), KEY_MASK_CMD | KEY_MASK_SHIFT | KEY_R), FILE_TOOL_RELOAD_SOFT);
file_menu->get_popup()->add_separator();
- file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/history_previous", TTR("History Prev"), KEY_MASK_ALT|KEY_LEFT), WINDOW_PREV);
- file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/history_next", TTR("History Next"), KEY_MASK_ALT|KEY_RIGHT), WINDOW_NEXT);
+ file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/history_previous", TTR("History Prev"), KEY_MASK_ALT | KEY_LEFT), WINDOW_PREV);
+ file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/history_next", TTR("History Next"), KEY_MASK_ALT | KEY_RIGHT), WINDOW_NEXT);
file_menu->get_popup()->add_separator();
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/import_theme", TTR("Import Theme")), FILE_IMPORT_THEME);
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/reload_theme", TTR("Reload Theme")), FILE_RELOAD_THEME);
@@ -2172,20 +2001,17 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) {
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_docs", TTR("Close Docs")), CLOSE_DOCS);
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_file", TTR("Close"), KEY_MASK_CMD | KEY_W), FILE_CLOSE);
file_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/close_all", TTR("Close All")), CLOSE_ALL);
- file_menu->get_popup()->connect("id_pressed", this,"_menu_option");
-
+ file_menu->get_popup()->connect("id_pressed", this, "_menu_option");
-
- script_search_menu = memnew( MenuButton );
+ script_search_menu = memnew(MenuButton);
menu_hb->add_child(script_search_menu);
script_search_menu->set_text(TTR("Search"));
- script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find", TTR("Find.."), KEY_MASK_CMD|KEY_F), HELP_SEARCH_FIND);
+ script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find", TTR("Find.."), KEY_MASK_CMD | KEY_F), HELP_SEARCH_FIND);
script_search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_next", TTR("Find Next"), KEY_F3), HELP_SEARCH_FIND_NEXT);
- script_search_menu->get_popup()->connect("id_pressed", this,"_menu_option");
+ script_search_menu->get_popup()->connect("id_pressed", this, "_menu_option");
script_search_menu->hide();
-
- debug_menu = memnew( MenuButton );
+ debug_menu = memnew(MenuButton);
menu_hb->add_child(debug_menu);
debug_menu->set_text(TTR("Debug"));
debug_menu->get_popup()->add_separator();
@@ -2197,13 +2023,12 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) {
debug_menu->get_popup()->add_separator();
//debug_menu->get_popup()->add_check_item("Show Debugger",DEBUG_SHOW);
debug_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("debugger/keep_debugger_open", TTR("Keep Debugger Open")), DEBUG_SHOW_KEEP_OPEN);
- debug_menu->get_popup()->connect("id_pressed", this,"_menu_option");
-
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true);
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_STEP), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_BREAK), true );
- debug_menu->get_popup()->set_item_disabled( debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true );
+ debug_menu->get_popup()->connect("id_pressed", this, "_menu_option");
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_NEXT), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_STEP), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_BREAK), true);
+ debug_menu->get_popup()->set_item_disabled(debug_menu->get_popup()->get_item_index(DEBUG_CONTINUE), true);
#if 0
window_menu = memnew( MenuButton );
@@ -2218,13 +2043,11 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) {
#endif
-
menu_hb->add_spacer();
-
- script_icon = memnew( TextureRect );
+ script_icon = memnew(TextureRect);
menu_hb->add_child(script_icon);
- script_name_label = memnew( Label );
+ script_name_label = memnew(Label);
menu_hb->add_child(script_name_label);
script_icon->hide();
@@ -2232,46 +2055,44 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) {
menu_hb->add_spacer();
- site_search = memnew( ToolButton );
+ site_search = memnew(ToolButton);
site_search->set_text(TTR("Tutorials"));
- site_search->connect("pressed",this,"_menu_option",varray(SEARCH_WEBSITE));
+ site_search->connect("pressed", this, "_menu_option", varray(SEARCH_WEBSITE));
menu_hb->add_child(site_search);
site_search->set_tooltip(TTR("Open https://godotengine.org at tutorials section."));
- class_search = memnew( ToolButton );
+ class_search = memnew(ToolButton);
class_search->set_text(TTR("Classes"));
- class_search->connect("pressed",this,"_menu_option",varray(SEARCH_CLASSES));
+ class_search->connect("pressed", this, "_menu_option", varray(SEARCH_CLASSES));
menu_hb->add_child(class_search);
class_search->set_tooltip(TTR("Search the class hierarchy."));
- help_search = memnew( ToolButton );
+ help_search = memnew(ToolButton);
help_search->set_text(TTR("Search Help"));
- help_search->connect("pressed",this,"_menu_option",varray(SEARCH_HELP));
+ help_search->connect("pressed", this, "_menu_option", varray(SEARCH_HELP));
menu_hb->add_child(help_search);
help_search->set_tooltip(TTR("Search the reference documentation."));
- menu_hb->add_child( memnew( VSeparator) );
+ menu_hb->add_child(memnew(VSeparator));
- script_back = memnew( ToolButton );
- script_back->connect("pressed",this,"_history_back");
+ script_back = memnew(ToolButton);
+ script_back->connect("pressed", this, "_history_back");
menu_hb->add_child(script_back);
script_back->set_disabled(true);
script_back->set_tooltip(TTR("Go to previous edited document."));
- script_forward = memnew( ToolButton );
- script_forward->connect("pressed",this,"_history_forward");
+ script_forward = memnew(ToolButton);
+ script_forward->connect("pressed", this, "_history_forward");
menu_hb->add_child(script_forward);
script_forward->set_disabled(true);
script_forward->set_tooltip(TTR("Go to next edited document."));
+ tab_container->connect("tab_changed", this, "_tab_changed");
-
- tab_container->connect("tab_changed", this,"_tab_changed");
-
- erase_tab_confirm = memnew( ConfirmationDialog );
+ erase_tab_confirm = memnew(ConfirmationDialog);
erase_tab_confirm->get_ok()->set_text(TTR("Save"));
erase_tab_confirm->add_button(TTR("Discard"), OS::get_singleton()->get_swap_ok_cancel(), "discard");
- erase_tab_confirm->connect("confirmed", this,"_close_current_tab");
+ erase_tab_confirm->connect("confirmed", this, "_close_current_tab");
erase_tab_confirm->connect("custom_action", this, "_close_discard_current_tab");
add_child(erase_tab_confirm);
@@ -2281,74 +2102,67 @@ ScriptEditor::ScriptEditor(EditorNode *p_editor) {
script_create_dialog->connect("script_created", this, "_script_created");
file_dialog_option = -1;
- file_dialog = memnew( EditorFileDialog );
+ file_dialog = memnew(EditorFileDialog);
add_child(file_dialog);
- file_dialog->connect("file_selected", this,"_file_dialog_action");
-
+ file_dialog->connect("file_selected", this, "_file_dialog_action");
- debugger = memnew( ScriptEditorDebugger(editor) );
- debugger->connect("goto_script_line",this,"_goto_script_line");
- debugger->connect("show_debugger",this,"_show_debugger");
+ debugger = memnew(ScriptEditorDebugger(editor));
+ debugger->connect("goto_script_line", this, "_goto_script_line");
+ debugger->connect("show_debugger", this, "_show_debugger");
- disk_changed = memnew( ConfirmationDialog );
+ disk_changed = memnew(ConfirmationDialog);
{
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
disk_changed->add_child(vbc);
//disk_changed->set_child_rect(vbc);
- Label *dl = memnew( Label );
+ Label *dl = memnew(Label);
dl->set_text(TTR("The following files are newer on disk.\nWhat action should be taken?:"));
vbc->add_child(dl);
- disk_changed_list = memnew( Tree );
+ disk_changed_list = memnew(Tree);
vbc->add_child(disk_changed_list);
disk_changed_list->set_v_size_flags(SIZE_EXPAND_FILL);
- disk_changed->connect("confirmed",this,"_reload_scripts");
+ disk_changed->connect("confirmed", this, "_reload_scripts");
disk_changed->get_ok()->set_text(TTR("Reload"));
- disk_changed->add_button(TTR("Resave"),!OS::get_singleton()->get_swap_ok_cancel(),"resave");
- disk_changed->connect("custom_action",this,"_resave_scripts");
-
-
+ disk_changed->add_button(TTR("Resave"), !OS::get_singleton()->get_swap_ok_cancel(), "resave");
+ disk_changed->connect("custom_action", this, "_resave_scripts");
}
add_child(disk_changed);
- script_editor=this;
+ script_editor = this;
-
- Button *db = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Debugger"),debugger);
+ Button *db = EditorNode::get_singleton()->add_bottom_panel_item(TTR("Debugger"), debugger);
debugger->set_tool_button(db);
+ debugger->connect("breaked", this, "_breaked");
- debugger->connect("breaked",this,"_breaked");
-
- autosave_timer = memnew( Timer );
+ autosave_timer = memnew(Timer);
autosave_timer->set_one_shot(false);
add_child(autosave_timer);
- grab_focus_block=false;
+ grab_focus_block = false;
- help_search_dialog = memnew( EditorHelpSearch );
+ help_search_dialog = memnew(EditorHelpSearch);
add_child(help_search_dialog);
- help_search_dialog->connect("go_to_help",this,"_help_class_goto");
-
+ help_search_dialog->connect("go_to_help", this, "_help_class_goto");
- help_index = memnew( EditorHelpIndex );
+ help_index = memnew(EditorHelpIndex);
add_child(help_index);
- help_index->connect("open_class",this,"_help_class_open");
+ help_index->connect("open_class", this, "_help_class_open");
- history_pos=-1;
+ history_pos = -1;
//debugger_gui->hide();
- edit_pass=0;
+ edit_pass = 0;
trim_trailing_whitespace_on_save = false;
- ScriptServer::edit_request_func=_open_script_request;
+ ScriptServer::edit_request_func = _open_script_request;
}
-
ScriptEditor::~ScriptEditor() {
memdelete(completion_cache);
@@ -2360,7 +2174,6 @@ void ScriptEditorPlugin::edit(Object *p_object) {
return;
script_editor->edit(p_object->cast_to<Script>());
-
}
bool ScriptEditorPlugin::handles(Object *p_object) const {
@@ -2389,7 +2202,6 @@ void ScriptEditorPlugin::make_visible(bool p_visible) {
script_editor->hide();
script_editor->set_process(false);
}
-
}
void ScriptEditorPlugin::selected_notify() {
@@ -2402,7 +2214,7 @@ Dictionary ScriptEditorPlugin::get_state() const {
return script_editor->get_state();
}
-void ScriptEditorPlugin::set_state(const Dictionary& p_state) {
+void ScriptEditorPlugin::set_state(const Dictionary &p_state) {
script_editor->set_state(p_state);
}
@@ -2422,12 +2234,9 @@ void ScriptEditorPlugin::apply_changes() {
}
void ScriptEditorPlugin::restore_global_state() {
-
-
}
void ScriptEditorPlugin::save_global_state() {
-
}
void ScriptEditorPlugin::set_window_layout(Ref<ConfigFile> p_layout) {
@@ -2435,15 +2244,13 @@ void ScriptEditorPlugin::set_window_layout(Ref<ConfigFile> p_layout) {
script_editor->set_window_layout(p_layout);
}
-void ScriptEditorPlugin::get_window_layout(Ref<ConfigFile> p_layout){
+void ScriptEditorPlugin::get_window_layout(Ref<ConfigFile> p_layout) {
script_editor->get_window_layout(p_layout);
}
-
void ScriptEditorPlugin::get_breakpoints(List<String> *p_breakpoints) {
-
return script_editor->get_breakpoints(p_breakpoints);
}
@@ -2452,40 +2259,34 @@ void ScriptEditorPlugin::edited_scene_changed() {
script_editor->edited_scene_changed();
}
-
-
ScriptEditorPlugin::ScriptEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- script_editor = memnew( ScriptEditor(p_node) );
+ editor = p_node;
+ script_editor = memnew(ScriptEditor(p_node));
editor->get_viewport()->add_child(script_editor);
script_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
script_editor->hide();
- EDITOR_DEF("text_editor/files/auto_reload_scripts_on_external_change",true);
- ScriptServer::set_reload_scripts_on_save(EDITOR_DEF("text_editor/files/auto_reload_and_parse_scripts_on_save",true));
- EDITOR_DEF("text_editor/files/open_dominant_script_on_scene_change",true);
- EDITOR_DEF("text_editor/external/use_external_editor",false);
- EDITOR_DEF("text_editor/external/exec_path","");
- EDITOR_DEF("text_editor/open_scripts/script_temperature_enabled",true);
+ EDITOR_DEF("text_editor/files/auto_reload_scripts_on_external_change", true);
+ ScriptServer::set_reload_scripts_on_save(EDITOR_DEF("text_editor/files/auto_reload_and_parse_scripts_on_save", true));
+ EDITOR_DEF("text_editor/files/open_dominant_script_on_scene_change", true);
+ EDITOR_DEF("text_editor/external/use_external_editor", false);
+ EDITOR_DEF("text_editor/external/exec_path", "");
+ EDITOR_DEF("text_editor/open_scripts/script_temperature_enabled", true);
EDITOR_DEF("text_editor/open_scripts/highlight_current_script", true);
- EDITOR_DEF("text_editor/open_scripts/script_temperature_history_size",15);
- EDITOR_DEF("text_editor/open_scripts/script_temperature_hot_color",Color(1,0,0,0.3));
- EDITOR_DEF("text_editor/open_scripts/script_temperature_cold_color",Color(0,0,1,0.3));
- EDITOR_DEF("text_editor/open_scripts/current_script_background_color",Color(0.81,0.81,0.14,0.63));
- EDITOR_DEF("text_editor/open_scripts/group_help_pages",true);
- EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT,"text_editor/open_scripts/sort_scripts_by",PROPERTY_HINT_ENUM,"Name,Path"));
- EDITOR_DEF("text_editor/open_scripts/sort_scripts_by",0);
- EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT,"text_editor/open_scripts/list_script_names_as",PROPERTY_HINT_ENUM,"Name,Parent Directory And Name,Full Path"));
- EDITOR_DEF("text_editor/open_scripts/list_script_names_as",0);
- EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING,"text_editor/external/exec_path",PROPERTY_HINT_GLOBAL_FILE));
- EDITOR_DEF("text_editor/external/exec_flags","");
-
-
-}
-
-
-ScriptEditorPlugin::~ScriptEditorPlugin()
-{
+ EDITOR_DEF("text_editor/open_scripts/script_temperature_history_size", 15);
+ EDITOR_DEF("text_editor/open_scripts/script_temperature_hot_color", Color(1, 0, 0, 0.3));
+ EDITOR_DEF("text_editor/open_scripts/script_temperature_cold_color", Color(0, 0, 1, 0.3));
+ EDITOR_DEF("text_editor/open_scripts/current_script_background_color", Color(0.81, 0.81, 0.14, 0.63));
+ EDITOR_DEF("text_editor/open_scripts/group_help_pages", true);
+ EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "text_editor/open_scripts/sort_scripts_by", PROPERTY_HINT_ENUM, "Name,Path"));
+ EDITOR_DEF("text_editor/open_scripts/sort_scripts_by", 0);
+ EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "text_editor/open_scripts/list_script_names_as", PROPERTY_HINT_ENUM, "Name,Parent Directory And Name,Full Path"));
+ EDITOR_DEF("text_editor/open_scripts/list_script_names_as", 0);
+ EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::STRING, "text_editor/external/exec_path", PROPERTY_HINT_GLOBAL_FILE));
+ EDITOR_DEF("text_editor/external/exec_flags", "");
+}
+
+ScriptEditorPlugin::~ScriptEditorPlugin() {
}
diff --git a/editor/plugins/script_editor_plugin.h b/editor/plugins/script_editor_plugin.h
index bf5316363c..a73e14423d 100644
--- a/editor/plugins/script_editor_plugin.h
+++ b/editor/plugins/script_editor_plugin.h
@@ -29,23 +29,23 @@
#ifndef SCRIPT_EDITOR_PLUGIN_H
#define SCRIPT_EDITOR_PLUGIN_H
+#include "editor/code_editor.h"
+#include "editor/editor_help.h"
#include "editor/editor_plugin.h"
#include "editor/script_create_dialog.h"
+#include "scene/gui/item_list.h"
+#include "scene/gui/menu_button.h"
+#include "scene/gui/split_container.h"
#include "scene/gui/tab_container.h"
#include "scene/gui/text_edit.h"
-#include "scene/gui/menu_button.h"
#include "scene/gui/tool_button.h"
#include "scene/gui/tree.h"
#include "scene/main/timer.h"
#include "script_language.h"
-#include "editor/code_editor.h"
-#include "scene/gui/split_container.h"
-#include "scene/gui/item_list.h"
-#include "editor/editor_help.h"
class ScriptEditorQuickOpen : public ConfirmationDialog {
- GDCLASS(ScriptEditorQuickOpen,ConfirmationDialog )
+ GDCLASS(ScriptEditorQuickOpen, ConfirmationDialog)
LineEdit *search_box;
Tree *search_options;
@@ -53,73 +53,66 @@ class ScriptEditorQuickOpen : public ConfirmationDialog {
void _update_search();
- void _sbox_input(const InputEvent& p_ie);
+ void _sbox_input(const InputEvent &p_ie);
Vector<String> functions;
-
void _confirmed();
- void _text_changed(const String& p_newtext);
+ void _text_changed(const String &p_newtext);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void popup(const Vector<String>& p_base,bool p_dontclear=false);
+public:
+ void popup(const Vector<String> &p_base, bool p_dontclear = false);
ScriptEditorQuickOpen();
};
-
class ScriptEditorDebugger;
-
-
class ScriptEditorBase : public Control {
- GDCLASS( ScriptEditorBase, Control );
+ GDCLASS(ScriptEditorBase, Control);
+
protected:
static void _bind_methods();
-public:
- virtual void apply_code()=0;
- virtual Ref<Script> get_edited_script() const=0;
- virtual Vector<String> get_functions()=0;
- virtual void set_edited_script(const Ref<Script>& p_script)=0;
- virtual void reload_text()=0;
- virtual String get_name()=0;
- virtual Ref<Texture> get_icon()=0;
- virtual bool is_unsaved()=0;
- virtual Variant get_edit_state()=0;
- virtual void set_edit_state(const Variant& p_state)=0;
- virtual void goto_line(int p_line,bool p_with_error=false)=0;
- virtual void trim_trailing_whitespace()=0;
- virtual void ensure_focus()=0;
- virtual void tag_saved_version()=0;
- virtual void reload(bool p_soft)=0;
- virtual void get_breakpoints(List<int> *p_breakpoints)=0;
- virtual bool goto_method(const String& p_method)=0;
- virtual void add_callback(const String& p_function,PoolStringArray p_args)=0;
- virtual void update_settings()=0;
- virtual void set_debugger_active(bool p_active)=0;
+public:
+ virtual void apply_code() = 0;
+ virtual Ref<Script> get_edited_script() const = 0;
+ virtual Vector<String> get_functions() = 0;
+ virtual void set_edited_script(const Ref<Script> &p_script) = 0;
+ virtual void reload_text() = 0;
+ virtual String get_name() = 0;
+ virtual Ref<Texture> get_icon() = 0;
+ virtual bool is_unsaved() = 0;
+ virtual Variant get_edit_state() = 0;
+ virtual void set_edit_state(const Variant &p_state) = 0;
+ virtual void goto_line(int p_line, bool p_with_error = false) = 0;
+ virtual void trim_trailing_whitespace() = 0;
+ virtual void ensure_focus() = 0;
+ virtual void tag_saved_version() = 0;
+ virtual void reload(bool p_soft) = 0;
+ virtual void get_breakpoints(List<int> *p_breakpoints) = 0;
+ virtual bool goto_method(const String &p_method) = 0;
+ virtual void add_callback(const String &p_function, PoolStringArray p_args) = 0;
+ virtual void update_settings() = 0;
+ virtual void set_debugger_active(bool p_active) = 0;
virtual bool can_lose_focus_on_node_selection() { return true; }
- virtual void set_tooltip_request_func(String p_method,Object* p_obj)=0;
- virtual Control *get_edit_menu()=0;
+ virtual void set_tooltip_request_func(String p_method, Object *p_obj) = 0;
+ virtual Control *get_edit_menu() = 0;
ScriptEditorBase() {}
};
-
-typedef ScriptEditorBase* (*CreateScriptEditorFunc)(const Ref<Script>& p_script);
-
+typedef ScriptEditorBase *(*CreateScriptEditorFunc)(const Ref<Script> &p_script);
class EditorScriptCodeCompletionCache;
class ScriptEditor : public VBoxContainer {
- GDCLASS(ScriptEditor, VBoxContainer );
-
+ GDCLASS(ScriptEditor, VBoxContainer);
EditorNode *editor;
enum {
@@ -152,14 +145,14 @@ class ScriptEditor : public VBoxContainer {
WINDOW_MOVE_RIGHT,
WINDOW_NEXT,
WINDOW_PREV,
- WINDOW_SELECT_BASE=100
+ WINDOW_SELECT_BASE = 100
};
-
+
enum ScriptSortBy {
SORT_BY_NAME,
SORT_BY_PATH,
};
-
+
enum ScriptListName {
DISPLAY_NAME,
DISPLAY_DIR_AND_NAME,
@@ -185,7 +178,7 @@ class ScriptEditor : public VBoxContainer {
EditorFileDialog *file_dialog;
ConfirmationDialog *erase_tab_confirm;
ScriptCreateDialog *script_create_dialog;
- ScriptEditorDebugger* debugger;
+ ScriptEditorDebugger *debugger;
ToolButton *scripts_visible;
String current_theme;
@@ -197,7 +190,7 @@ class ScriptEditor : public VBoxContainer {
ToolButton *script_forward;
enum {
- SCRIPT_EDITOR_FUNC_MAX=32
+ SCRIPT_EDITOR_FUNC_MAX = 32
};
static int script_editor_func_count;
@@ -212,7 +205,6 @@ class ScriptEditor : public VBoxContainer {
Vector<ScriptHistory> history;
int history_pos;
-
EditorHelpIndex *help_index;
void _tab_changed(int p_which);
@@ -223,17 +215,17 @@ class ScriptEditor : public VBoxContainer {
bool restoring_layout;
- String _get_debug_tooltip(const String&p_text,Node *_ste);
+ String _get_debug_tooltip(const String &p_text, Node *_ste);
- void _resave_scripts(const String& p_str);
+ void _resave_scripts(const String &p_str);
void _reload_scripts();
- bool _test_script_times_on_disk(Ref<Script> p_for_script=Ref<Script>());
+ bool _test_script_times_on_disk(Ref<Script> p_for_script = Ref<Script>());
- void _close_tab(int p_idx, bool p_save=true);
+ void _close_tab(int p_idx, bool p_save = true);
void _close_current_tab();
- void _close_discard_current_tab(const String& p_str);
+ void _close_discard_current_tab(const String &p_str);
void _close_docs_tab();
void _close_all_tabs();
@@ -255,16 +247,16 @@ class ScriptEditor : public VBoxContainer {
int edit_pass;
- void _add_callback(Object *p_obj, const String& p_function, const PoolStringArray& p_args);
- void _res_saved_callback(const Ref<Resource>& p_res);
+ void _add_callback(Object *p_obj, const String &p_function, const PoolStringArray &p_args);
+ void _res_saved_callback(const Ref<Resource> &p_res);
bool trim_trailing_whitespace_on_save;
void _trim_trailing_whitespace(TextEdit *tx);
void _goto_script_line2(int p_line);
- void _goto_script_line(REF p_script,int p_line);
- void _breaked(bool p_breaked,bool p_can_debug);
+ void _goto_script_line(REF p_script, int p_line);
+ void _breaked(bool p_breaked, bool p_can_debug);
void _show_debugger(bool p_show);
void _update_window_menu();
void _script_created(Ref<Script> p_script);
@@ -277,13 +269,13 @@ class ScriptEditor : public VBoxContainer {
void _script_selected(int p_idx);
- void _find_scripts(Node* p_base, Node* p_current,Set<Ref<Script> >& used);
+ void _find_scripts(Node *p_base, Node *p_current, Set<Ref<Script> > &used);
void _tree_changed();
void _script_split_dragged(float);
- void _unhandled_input(const InputEvent& p_event);
+ void _unhandled_input(const InputEvent &p_event);
void _help_search(String p_text);
@@ -292,36 +284,37 @@ class ScriptEditor : public VBoxContainer {
bool waiting_update_names;
- void _help_class_open(const String& p_class);
- void _help_class_goto(const String& p_desc);
+ void _help_class_open(const String &p_class);
+ void _help_class_goto(const String &p_desc);
void _update_history_arrows();
void _save_history();
void _go_to_tab(int p_idx);
void _update_history_pos(int p_new_pos);
void _update_script_colors();
- void _update_modified_scripts_for_external_editor(Ref<Script> p_for_script=Ref<Script>());
+ void _update_modified_scripts_for_external_editor(Ref<Script> p_for_script = Ref<Script>());
int file_dialog_option;
void _file_dialog_action(String p_file);
- static void _open_script_request(const String& p_path);
+ static void _open_script_request(const String &p_path);
static ScriptEditor *script_editor;
+
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
static ScriptEditor *get_singleton() { return script_editor; }
void ensure_focus_current();
void apply_scripts() const;
void ensure_select_current();
- void edit(const Ref<Script>& p_script,bool p_grab_focus=true);
+ void edit(const Ref<Script> &p_script, bool p_grab_focus = true);
Dictionary get_state() const;
- void set_state(const Dictionary& p_state);
+ void set_state(const Dictionary &p_state);
void clear();
void get_breakpoints(List<String> *p_breakpoints);
@@ -333,15 +326,15 @@ public:
void set_window_layout(Ref<ConfigFile> p_layout);
void get_window_layout(Ref<ConfigFile> p_layout);
- void set_scene_root_script( Ref<Script> p_script );
+ void set_scene_root_script(Ref<Script> p_script);
- bool script_go_to_method(Ref<Script> p_script, const String& p_method);
+ bool script_go_to_method(Ref<Script> p_script, const String &p_method);
virtual void edited_scene_changed();
- void close_builtin_scripts_from_scene(const String& p_scene);
+ void close_builtin_scripts_from_scene(const String &p_scene);
- void goto_help(const String& p_desc) { _help_class_goto(p_desc); }
+ void goto_help(const String &p_desc) { _help_class_goto(p_desc); }
bool can_take_away_focus() const;
@@ -355,12 +348,12 @@ public:
class ScriptEditorPlugin : public EditorPlugin {
- GDCLASS( ScriptEditorPlugin, EditorPlugin );
+ GDCLASS(ScriptEditorPlugin, EditorPlugin);
ScriptEditor *script_editor;
EditorNode *editor;
-public:
+public:
virtual String get_name() const { return "Script"; }
bool has_main_screen() const { return true; }
virtual void edit(Object *p_node);
@@ -369,7 +362,7 @@ public:
virtual void selected_notify();
Dictionary get_state() const;
- virtual void set_state(const Dictionary& p_state);
+ virtual void set_state(const Dictionary &p_state);
virtual void clear();
virtual void save_external_data();
@@ -383,12 +376,10 @@ public:
virtual void get_breakpoints(List<String> *p_breakpoints);
-
virtual void edited_scene_changed();
ScriptEditorPlugin(EditorNode *p_node);
~ScriptEditorPlugin();
-
};
#endif // SCRIPT_EDITOR_PLUGIN_H
diff --git a/editor/plugins/script_text_editor.cpp b/editor/plugins/script_text_editor.cpp
index 8723a863f0..7496ad8cca 100644
--- a/editor/plugins/script_text_editor.cpp
+++ b/editor/plugins/script_text_editor.cpp
@@ -28,30 +28,27 @@
/*************************************************************************/
#include "script_text_editor.h"
+#include "editor/editor_node.h"
#include "editor/editor_settings.h"
-#include "os/keyboard.h"
#include "editor/script_editor_debugger.h"
-#include "editor/editor_node.h"
-
-Vector<String> ScriptTextEditor::get_functions() {
+#include "os/keyboard.h"
+Vector<String> ScriptTextEditor::get_functions() {
String errortxt;
- int line=-1,col;
- TextEdit *te=code_editor->get_text_edit();
+ int line = -1, col;
+ TextEdit *te = code_editor->get_text_edit();
String text = te->get_text();
List<String> fnc;
- if (script->get_language()->validate(text,line,col,errortxt,script->get_path(),&fnc)) {
+ if (script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc)) {
//if valid rewrite functions to latest
functions.clear();
- for (List<String>::Element *E=fnc.front();E;E=E->next()) {
+ for (List<String>::Element *E = fnc.front(); E; E = E->next()) {
functions.push_back(E->get());
}
-
-
}
return functions;
@@ -71,20 +68,19 @@ Ref<Script> ScriptTextEditor::get_edited_script() const {
return script;
}
-bool ScriptTextEditor::goto_method(const String& p_method) {
-
+bool ScriptTextEditor::goto_method(const String &p_method) {
Vector<String> functions = get_functions();
String method_search = p_method + ":";
- for (int i=0;i<functions.size();i++) {
- String function=functions[i];
+ for (int i = 0; i < functions.size(); i++) {
+ String function = functions[i];
if (function.begins_with(method_search)) {
- int line=function.get_slice(":",1).to_int();
- goto_line(line-1);
+ int line = function.get_slice(":", 1).to_int();
+ goto_line(line - 1);
return true;
}
}
@@ -100,105 +96,103 @@ void ScriptTextEditor::_load_theme_settings() {
/* keyword color */
-
- text_edit->add_color_override("background_color", EDITOR_DEF("text_editor/highlighting/background_color",Color(0,0,0,0)));
- text_edit->add_color_override("completion_background_color", EDITOR_DEF("text_editor/highlighting/completion_background_color", Color(0,0,0,0)));
+ text_edit->add_color_override("background_color", EDITOR_DEF("text_editor/highlighting/background_color", Color(0, 0, 0, 0)));
+ text_edit->add_color_override("completion_background_color", EDITOR_DEF("text_editor/highlighting/completion_background_color", Color(0, 0, 0, 0)));
text_edit->add_color_override("completion_selected_color", EDITOR_DEF("text_editor/highlighting/completion_selected_color", Color::html("434244")));
text_edit->add_color_override("completion_existing_color", EDITOR_DEF("text_editor/highlighting/completion_existing_color", Color::html("21dfdfdf")));
text_edit->add_color_override("completion_scroll_color", EDITOR_DEF("text_editor/highlighting/completion_scroll_color", Color::html("ffffff")));
text_edit->add_color_override("completion_font_color", EDITOR_DEF("text_editor/highlighting/completion_font_color", Color::html("aaaaaa")));
- text_edit->add_color_override("font_color",EDITOR_DEF("text_editor/highlighting/text_color",Color(0,0,0)));
- text_edit->add_color_override("line_number_color",EDITOR_DEF("text_editor/highlighting/line_number_color",Color(0,0,0)));
- text_edit->add_color_override("caret_color",EDITOR_DEF("text_editor/highlighting/caret_color",Color(0,0,0)));
- text_edit->add_color_override("caret_background_color",EDITOR_DEF("text_editor/highlighting/caret_background_color",Color(0,0,0)));
- text_edit->add_color_override("font_selected_color",EDITOR_DEF("text_editor/highlighting/text_selected_color",Color(1,1,1)));
- text_edit->add_color_override("selection_color",EDITOR_DEF("text_editor/highlighting/selection_color",Color(0.2,0.2,1)));
- text_edit->add_color_override("brace_mismatch_color",EDITOR_DEF("text_editor/highlighting/brace_mismatch_color",Color(1,0.2,0.2)));
- text_edit->add_color_override("current_line_color",EDITOR_DEF("text_editor/highlighting/current_line_color",Color(0.3,0.5,0.8,0.15)));
- text_edit->add_color_override("line_length_guideline_color", EDITOR_DEF("text_editor/highlighting/line_length_guideline_color", Color(0,0,0)));
- text_edit->add_color_override("word_highlighted_color",EDITOR_DEF("text_editor/highlighting/word_highlighted_color",Color(0.8,0.9,0.9,0.15)));
- text_edit->add_color_override("number_color",EDITOR_DEF("text_editor/highlighting/number_color",Color(0.9,0.6,0.0,2)));
- text_edit->add_color_override("function_color",EDITOR_DEF("text_editor/highlighting/function_color",Color(0.4,0.6,0.8)));
- text_edit->add_color_override("member_variable_color",EDITOR_DEF("text_editor/highlighting/member_variable_color",Color(0.9,0.3,0.3)));
- text_edit->add_color_override("mark_color", EDITOR_DEF("text_editor/highlighting/mark_color", Color(1.0,0.4,0.4,0.4)));
- text_edit->add_color_override("breakpoint_color", EDITOR_DEF("text_editor/highlighting/breakpoint_color", Color(0.8,0.8,0.4,0.2)));
- text_edit->add_color_override("search_result_color",EDITOR_DEF("text_editor/highlighting/search_result_color",Color(0.05,0.25,0.05,1)));
- text_edit->add_color_override("search_result_border_color",EDITOR_DEF("text_editor/highlighting/search_result_border_color",Color(0.1,0.45,0.1,1)));
- text_edit->add_color_override("symbol_color",EDITOR_DEF("text_editor/highlighting/symbol_color",Color::hex(0x005291ff)));
- text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing",4));
-
- Color keyword_color= EDITOR_DEF("text_editor/highlighting/keyword_color",Color(0.5,0.0,0.2));
+ text_edit->add_color_override("font_color", EDITOR_DEF("text_editor/highlighting/text_color", Color(0, 0, 0)));
+ text_edit->add_color_override("line_number_color", EDITOR_DEF("text_editor/highlighting/line_number_color", Color(0, 0, 0)));
+ text_edit->add_color_override("caret_color", EDITOR_DEF("text_editor/highlighting/caret_color", Color(0, 0, 0)));
+ text_edit->add_color_override("caret_background_color", EDITOR_DEF("text_editor/highlighting/caret_background_color", Color(0, 0, 0)));
+ text_edit->add_color_override("font_selected_color", EDITOR_DEF("text_editor/highlighting/text_selected_color", Color(1, 1, 1)));
+ text_edit->add_color_override("selection_color", EDITOR_DEF("text_editor/highlighting/selection_color", Color(0.2, 0.2, 1)));
+ text_edit->add_color_override("brace_mismatch_color", EDITOR_DEF("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)));
+ text_edit->add_color_override("current_line_color", EDITOR_DEF("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)));
+ text_edit->add_color_override("line_length_guideline_color", EDITOR_DEF("text_editor/highlighting/line_length_guideline_color", Color(0, 0, 0)));
+ text_edit->add_color_override("word_highlighted_color", EDITOR_DEF("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)));
+ text_edit->add_color_override("number_color", EDITOR_DEF("text_editor/highlighting/number_color", Color(0.9, 0.6, 0.0, 2)));
+ text_edit->add_color_override("function_color", EDITOR_DEF("text_editor/highlighting/function_color", Color(0.4, 0.6, 0.8)));
+ text_edit->add_color_override("member_variable_color", EDITOR_DEF("text_editor/highlighting/member_variable_color", Color(0.9, 0.3, 0.3)));
+ text_edit->add_color_override("mark_color", EDITOR_DEF("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)));
+ text_edit->add_color_override("breakpoint_color", EDITOR_DEF("text_editor/highlighting/breakpoint_color", Color(0.8, 0.8, 0.4, 0.2)));
+ text_edit->add_color_override("search_result_color", EDITOR_DEF("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)));
+ text_edit->add_color_override("search_result_border_color", EDITOR_DEF("text_editor/highlighting/search_result_border_color", Color(0.1, 0.45, 0.1, 1)));
+ text_edit->add_color_override("symbol_color", EDITOR_DEF("text_editor/highlighting/symbol_color", Color::hex(0x005291ff)));
+ text_edit->add_constant_override("line_spacing", EDITOR_DEF("text_editor/theme/line_spacing", 4));
+
+ Color keyword_color = EDITOR_DEF("text_editor/highlighting/keyword_color", Color(0.5, 0.0, 0.2));
List<String> keywords;
script->get_language()->get_reserved_words(&keywords);
- for(List<String>::Element *E=keywords.front();E;E=E->next()) {
+ for (List<String>::Element *E = keywords.front(); E; E = E->next()) {
- text_edit->add_keyword_color(E->get(),keyword_color);
+ text_edit->add_keyword_color(E->get(), keyword_color);
}
//colorize core types
- Color basetype_color= EDITOR_DEF("text_editor/highlighting/base_type_color",Color(0.3,0.3,0.0));
-
- text_edit->add_keyword_color("Vector2",basetype_color);
- text_edit->add_keyword_color("Vector3",basetype_color);
- text_edit->add_keyword_color("Plane",basetype_color);
- text_edit->add_keyword_color("Quat",basetype_color);
- text_edit->add_keyword_color("AABB",basetype_color);
- text_edit->add_keyword_color("Matrix3",basetype_color);
- text_edit->add_keyword_color("Transform",basetype_color);
- text_edit->add_keyword_color("Color",basetype_color);
- text_edit->add_keyword_color("Image",basetype_color);
- text_edit->add_keyword_color("InputEvent",basetype_color);
- text_edit->add_keyword_color("Rect2",basetype_color);
- text_edit->add_keyword_color("NodePath",basetype_color);
+ Color basetype_color = EDITOR_DEF("text_editor/highlighting/base_type_color", Color(0.3, 0.3, 0.0));
+
+ text_edit->add_keyword_color("Vector2", basetype_color);
+ text_edit->add_keyword_color("Vector3", basetype_color);
+ text_edit->add_keyword_color("Plane", basetype_color);
+ text_edit->add_keyword_color("Quat", basetype_color);
+ text_edit->add_keyword_color("AABB", basetype_color);
+ text_edit->add_keyword_color("Matrix3", basetype_color);
+ text_edit->add_keyword_color("Transform", basetype_color);
+ text_edit->add_keyword_color("Color", basetype_color);
+ text_edit->add_keyword_color("Image", basetype_color);
+ text_edit->add_keyword_color("InputEvent", basetype_color);
+ text_edit->add_keyword_color("Rect2", basetype_color);
+ text_edit->add_keyword_color("NodePath", basetype_color);
//colorize engine types
- Color type_color= EDITOR_DEF("text_editor/highlighting/engine_type_color",Color(0.0,0.2,0.4));
+ Color type_color = EDITOR_DEF("text_editor/highlighting/engine_type_color", Color(0.0, 0.2, 0.4));
List<StringName> types;
ClassDB::get_class_list(&types);
- for(List<StringName>::Element *E=types.front();E;E=E->next()) {
+ 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());
- text_edit->add_keyword_color(n,type_color);
+ text_edit->add_keyword_color(n, type_color);
}
//colorize comments
- Color comment_color = EDITOR_DEF("text_editor/highlighting/comment_color",Color::hex(0x797e7eff));
+ Color comment_color = EDITOR_DEF("text_editor/highlighting/comment_color", Color::hex(0x797e7eff));
List<String> comments;
script->get_language()->get_comment_delimiters(&comments);
- for(List<String>::Element *E=comments.front();E;E=E->next()) {
+ 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();
+ String beg = comment.get_slice(" ", 0);
+ String end = comment.get_slice_count(" ") > 1 ? comment.get_slice(" ", 1) : String();
- text_edit->add_color_region(beg,end,comment_color,end=="");
+ text_edit->add_color_region(beg, end, comment_color, end == "");
}
//colorize strings
- Color string_color = EDITOR_DEF("text_editor/highlighting/string_color",Color::hex(0x6b6f00ff));
+ Color string_color = EDITOR_DEF("text_editor/highlighting/string_color", Color::hex(0x6b6f00ff));
List<String> strings;
script->get_language()->get_string_delimiters(&strings);
- for (List<String>::Element *E=strings.front();E;E=E->next()) {
+ 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();
- text_edit->add_color_region(beg,end,string_color,end=="");
+ String beg = string.get_slice(" ", 0);
+ String end = string.get_slice_count(" ") > 1 ? string.get_slice(" ", 1) : String();
+ text_edit->add_color_region(beg, end, string_color, end == "");
}
}
-
void ScriptTextEditor::reload_text() {
- ERR_FAIL_COND(script.is_null()) ;
+ ERR_FAIL_COND(script.is_null());
TextEdit *te = code_editor->get_text_edit();
int column = te->cursor_get_column();
@@ -216,30 +210,29 @@ void ScriptTextEditor::reload_text() {
te->tag_saved_version();
code_editor->update_line_and_column();
-
}
void ScriptTextEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
//emit_signal("name_changed");
}
}
-void ScriptTextEditor::add_callback(const String& p_function,PoolStringArray p_args) {
+void ScriptTextEditor::add_callback(const String &p_function, PoolStringArray p_args) {
String code = code_editor->get_text_edit()->get_text();
- int pos = script->get_language()->find_function(p_function,code);
- if (pos==-1) {
+ int pos = script->get_language()->find_function(p_function, code);
+ if (pos == -1) {
//does not exist
code_editor->get_text_edit()->deselect();
- pos=code_editor->get_text_edit()->get_line_count()+2;
- String func = script->get_language()->make_function("",p_function,p_args);
+ pos = code_editor->get_text_edit()->get_line_count() + 2;
+ String func = script->get_language()->make_function("", p_function, p_args);
//code=code+func;
- code_editor->get_text_edit()->cursor_set_line(pos+1);
+ code_editor->get_text_edit()->cursor_set_line(pos + 1);
code_editor->get_text_edit()->cursor_set_column(1000000); //none shall be that big
- code_editor->get_text_edit()->insert_text_at_cursor("\n\n"+func);
+ code_editor->get_text_edit()->insert_text_at_cursor("\n\n" + func);
}
code_editor->get_text_edit()->cursor_set_line(pos);
code_editor->get_text_edit()->cursor_set_column(1);
@@ -250,18 +243,18 @@ void ScriptTextEditor::update_settings() {
code_editor->update_editor_settings();
}
-bool ScriptTextEditor::is_unsaved() {
+bool ScriptTextEditor::is_unsaved() {
- return code_editor->get_text_edit()->get_version()!=code_editor->get_text_edit()->get_saved_version();
+ return code_editor->get_text_edit()->get_version() != code_editor->get_text_edit()->get_saved_version();
}
Variant ScriptTextEditor::get_edit_state() {
Dictionary state;
- state["scroll_pos"]=code_editor->get_text_edit()->get_v_scroll();
- state["column"]=code_editor->get_text_edit()->cursor_get_column();
- state["row"]=code_editor->get_text_edit()->cursor_get_line();
+ state["scroll_pos"] = code_editor->get_text_edit()->get_v_scroll();
+ state["column"] = code_editor->get_text_edit()->cursor_get_column();
+ state["row"] = code_editor->get_text_edit()->cursor_get_line();
return state;
}
@@ -283,7 +276,7 @@ void ScriptTextEditor::trim_trailing_whitespace() {
int end = 0;
for (int j = line.length() - 1; j > -1; j--) {
if (line[j] != ' ' && line[j] != '\t') {
- end = j+1;
+ end = j + 1;
break;
}
}
@@ -310,12 +303,12 @@ void ScriptTextEditor::ensure_focus() {
code_editor->get_text_edit()->grab_focus();
}
-void ScriptTextEditor::set_edit_state(const Variant& p_state) {
+void ScriptTextEditor::set_edit_state(const Variant &p_state) {
- Dictionary state=p_state;
+ Dictionary state = p_state;
code_editor->get_text_edit()->set_v_scroll(state["scroll_pos"]);
- code_editor->get_text_edit()->cursor_set_column( state["column"]);
- code_editor->get_text_edit()->cursor_set_line( state["row"] );
+ code_editor->get_text_edit()->cursor_set_column(state["column"]);
+ code_editor->get_text_edit()->cursor_set_line(state["row"]);
code_editor->get_text_edit()->grab_focus();
//int scroll_pos;
@@ -323,40 +316,36 @@ void ScriptTextEditor::set_edit_state(const Variant& p_state) {
//int cursor_row;
}
-String ScriptTextEditor::get_name() {
+String ScriptTextEditor::get_name() {
String name;
- if (script->get_path().find("local://")==-1 && script->get_path().find("::")==-1) {
- name=script->get_path().get_file();
+ if (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) {
+ name = script->get_path().get_file();
if (is_unsaved()) {
- name+="(*)";
+ name += "(*)";
}
- } else if (script->get_name()!="")
- name=script->get_name();
+ } else if (script->get_name() != "")
+ name = script->get_name();
else
- name=script->get_class()+"("+itos(script->get_instance_ID())+")";
+ name = script->get_class() + "(" + itos(script->get_instance_ID()) + ")";
return name;
-
}
Ref<Texture> ScriptTextEditor::get_icon() {
- if (get_parent_control() && get_parent_control()->has_icon(script->get_class(),"EditorIcons")) {
- return get_parent_control()->get_icon(script->get_class(),"EditorIcons");
+ if (get_parent_control() && get_parent_control()->has_icon(script->get_class(), "EditorIcons")) {
+ return get_parent_control()->get_icon(script->get_class(), "EditorIcons");
}
return Ref<Texture>();
}
-
-
-void ScriptTextEditor::set_edited_script(const Ref<Script>& p_script) {
+void ScriptTextEditor::set_edited_script(const Ref<Script> &p_script) {
ERR_FAIL_COND(!script.is_null());
- script=p_script;
-
+ script = p_script;
_load_theme_settings();
@@ -368,22 +357,21 @@ void ScriptTextEditor::set_edited_script(const Ref<Script>& p_script) {
code_editor->update_line_and_column();
}
-
void ScriptTextEditor::_validate_script() {
String errortxt;
- int line=-1,col;
- TextEdit *te=code_editor->get_text_edit();
+ int line = -1, col;
+ TextEdit *te = code_editor->get_text_edit();
String text = te->get_text();
List<String> fnc;
- if (!script->get_language()->validate(text,line,col,errortxt,script->get_path(),&fnc)) {
- String error_text="error("+itos(line)+","+itos(col)+"): "+errortxt;
+ if (!script->get_language()->validate(text, line, col, errortxt, script->get_path(), &fnc)) {
+ String error_text = "error(" + itos(line) + "," + itos(col) + "): " + errortxt;
code_editor->set_error(error_text);
} else {
code_editor->set_error("");
- line=-1;
+ line = -1;
if (!script->is_tool()) {
script->set_source_code(text);
script->update_exports();
@@ -391,31 +379,29 @@ void ScriptTextEditor::_validate_script() {
}
functions.clear();
- for (List<String>::Element *E=fnc.front();E;E=E->next()) {
+ for (List<String>::Element *E = fnc.front(); E; E = E->next()) {
functions.push_back(E->get());
}
-
}
line--;
- for(int i=0;i<te->get_line_count();i++) {
- te->set_line_as_marked(i,line==i);
+ for (int i = 0; i < te->get_line_count(); i++) {
+ te->set_line_as_marked(i, line == i);
}
emit_signal("name_changed");
}
+static Node *_find_node_for_script(Node *p_base, Node *p_current, const Ref<Script> &p_script) {
-static 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)
+ if (p_current->get_owner() != p_base && p_base != p_current)
return NULL;
Ref<Script> c = p_current->get_script();
- if (c==p_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);
+ 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;
}
@@ -423,19 +409,18 @@ static Node* _find_node_for_script(Node* p_base, Node*p_current, const Ref<Scrip
return NULL;
}
-static void _find_changed_scripts_for_external_editor(Node* p_base, Node*p_current, Set<Ref<Script> > &r_scripts) {
+static void _find_changed_scripts_for_external_editor(Node *p_base, Node *p_current, Set<Ref<Script> > &r_scripts) {
- if (p_current->get_owner()!=p_base && p_base!=p_current)
+ if (p_current->get_owner() != p_base && p_base != p_current)
return;
Ref<Script> c = p_current->get_script();
if (c.is_valid())
r_scripts.insert(c);
- for(int i=0;i<p_current->get_child_count();i++) {
- _find_changed_scripts_for_external_editor(p_base,p_current->get_child(i),r_scripts);
+ for (int i = 0; i < p_current->get_child_count(); i++) {
+ _find_changed_scripts_for_external_editor(p_base, p_current->get_child(i), r_scripts);
}
-
}
void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_for_script) {
@@ -447,17 +432,17 @@ void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_fo
Node *base = get_tree()->get_edited_scene_root();
if (base) {
- _find_changed_scripts_for_external_editor(base,base,scripts);
+ _find_changed_scripts_for_external_editor(base, base, scripts);
}
- for (Set<Ref<Script> >::Element *E=scripts.front();E;E=E->next()) {
+ for (Set<Ref<Script> >::Element *E = scripts.front(); E; E = E->next()) {
Ref<Script> script = E->get();
- if (p_for_script.is_valid() && p_for_script!=script)
+ if (p_for_script.is_valid() && p_for_script != script)
continue;
- if (script->get_path()=="" || script->get_path().find("local://")!=-1 || script->get_path().find("::")!=-1) {
+ if (script->get_path() == "" || script->get_path().find("local://") != -1 || script->get_path().find("::") != -1) {
continue; //internal script, who cares, though weird
}
@@ -465,128 +450,120 @@ void ScriptEditor::_update_modified_scripts_for_external_editor(Ref<Script> p_fo
uint64_t last_date = script->get_last_modified_time();
uint64_t date = FileAccess::get_modified_time(script->get_path());
- if (last_date!=date) {
+ if (last_date != date) {
- Ref<Script> rel_script = ResourceLoader::load(script->get_path(),script->get_class(),true);
+ Ref<Script> rel_script = ResourceLoader::load(script->get_path(), script->get_class(), true);
ERR_CONTINUE(!rel_script.is_valid());
- script->set_source_code( rel_script->get_source_code() );
- script->set_last_modified_time( rel_script->get_last_modified_time() );
+ script->set_source_code(rel_script->get_source_code());
+ script->set_last_modified_time(rel_script->get_last_modified_time());
script->update_exports();
}
-
}
}
-
-void ScriptTextEditor::_code_complete_scripts(void* p_ud,const String& p_code, List<String>* r_options) {
+void ScriptTextEditor::_code_complete_scripts(void *p_ud, const String &p_code, List<String> *r_options) {
ScriptTextEditor *ste = (ScriptTextEditor *)p_ud;
- ste->_code_complete_script(p_code,r_options);
+ ste->_code_complete_script(p_code, r_options);
}
-void ScriptTextEditor::_code_complete_script(const String& p_code, List<String>* r_options) {
+void ScriptTextEditor::_code_complete_script(const String &p_code, List<String> *r_options) {
if (color_panel->is_visible_in_tree()) return;
Node *base = get_tree()->get_edited_scene_root();
if (base) {
- base = _find_node_for_script(base,base,script);
+ base = _find_node_for_script(base, base, script);
}
String hint;
- Error err = script->get_language()->complete_code(p_code,script->get_path().get_base_dir(),base,r_options,hint);
- if (hint!="") {
+ Error err = script->get_language()->complete_code(p_code, script->get_path().get_base_dir(), base, r_options, hint);
+ if (hint != "") {
code_editor->get_text_edit()->set_code_hint(hint);
}
-
}
void ScriptTextEditor::_breakpoint_toggled(int p_row) {
- ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(script->get_path(),p_row+1,code_editor->get_text_edit()->is_line_set_as_breakpoint(p_row));
-
+ ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(script->get_path(), p_row + 1, code_editor->get_text_edit()->is_line_set_as_breakpoint(p_row));
}
-static void swap_lines(TextEdit *tx, int line1, int line2)
-{
- String tmp = tx->get_line(line1);
- String tmp2 = tx->get_line(line2);
- tx->set_line(line2, tmp);
- tx->set_line(line1, tmp2);
+static void swap_lines(TextEdit *tx, int line1, int line2) {
+ String tmp = tx->get_line(line1);
+ String tmp2 = tx->get_line(line2);
+ tx->set_line(line2, tmp);
+ tx->set_line(line1, tmp2);
- tx->cursor_set_line(line2);
+ tx->cursor_set_line(line2);
}
-void ScriptTextEditor::_lookup_symbol(const String& p_symbol,int p_row, int p_column) {
+void ScriptTextEditor::_lookup_symbol(const String &p_symbol, int p_row, int p_column) {
Node *base = get_tree()->get_edited_scene_root();
if (base) {
- base = _find_node_for_script(base,base,script);
+ base = _find_node_for_script(base, base, script);
}
-
ScriptLanguage::LookupResult result;
- if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(),p_symbol,script->get_path().get_base_dir(),base,result)==OK) {
+ if (script->get_language()->lookup_code(code_editor->get_text_edit()->get_text_for_lookup_completion(), p_symbol, script->get_path().get_base_dir(), base, result) == OK) {
_goto_line(p_row);
- switch(result.type) {
+ switch (result.type) {
case ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION: {
if (result.script.is_valid()) {
- emit_signal("request_open_script_at_line",result.script,result.location-1);
+ emit_signal("request_open_script_at_line", result.script, result.location - 1);
} else {
emit_signal("request_save_history");
- _goto_line(result.location-1);
+ _goto_line(result.location - 1);
}
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS: {
- emit_signal("go_to_help","class_name:"+result.class_name);
+ emit_signal("go_to_help", "class_name:" + result.class_name);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT: {
StringName cname = result.class_name;
bool success;
- while(true) {
- ClassDB::get_integer_constant(cname,result.class_member,&success);
+ while (true) {
+ ClassDB::get_integer_constant(cname, result.class_member, &success);
if (success) {
- result.class_name=cname;
- cname=ClassDB::get_parent_class(cname);
+ result.class_name = cname;
+ cname = ClassDB::get_parent_class(cname);
} else {
break;
}
}
-
- emit_signal("go_to_help","class_constant:"+result.class_name+":"+result.class_member);
+ emit_signal("go_to_help", "class_constant:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY: {
- emit_signal("go_to_help","class_property:"+result.class_name+":"+result.class_member);
+ emit_signal("go_to_help", "class_property:" + result.class_name + ":" + result.class_member);
} break;
case ScriptLanguage::LookupResult::RESULT_CLASS_METHOD: {
StringName cname = result.class_name;
- while(true) {
- if (ClassDB::has_method(cname,result.class_member)) {
- result.class_name=cname;
- cname=ClassDB::get_parent_class(cname);
+ while (true) {
+ if (ClassDB::has_method(cname, result.class_member)) {
+ result.class_name = cname;
+ cname = ClassDB::get_parent_class(cname);
} else {
break;
}
}
- emit_signal("go_to_help","class_method:"+result.class_name+":"+result.class_member);
+ emit_signal("go_to_help", "class_method:" + result.class_name + ":" + result.class_member);
} break;
}
-
}
}
void ScriptTextEditor::_edit_option(int p_op) {
- switch(p_op) {
+ switch (p_op) {
case EDIT_UNDO: {
code_editor->get_text_edit()->undo();
code_editor->get_text_edit()->call_deferred("grab_focus");
@@ -624,15 +601,13 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
tx->begin_complex_operation();
- if (tx->is_selection_active())
- {
+ if (tx->is_selection_active()) {
int from_line = tx->get_selection_from_line();
- int from_col = tx->get_selection_from_column();
- int to_line = tx->get_selection_to_line();
+ int from_col = tx->get_selection_from_column();
+ int to_line = tx->get_selection_to_line();
int to_column = tx->get_selection_to_column();
- for (int i = from_line; i <= to_line; i++)
- {
+ for (int i = from_line; i <= to_line; i++) {
int line_id = i;
int next_id = i - 1;
@@ -641,12 +616,10 @@ void ScriptTextEditor::_edit_option(int p_op) {
swap_lines(tx, line_id, next_id);
}
- int from_line_up = from_line > 0 ? from_line-1 : from_line;
- int to_line_up = to_line > 0 ? to_line-1 : to_line;
+ int from_line_up = from_line > 0 ? from_line - 1 : from_line;
+ int to_line_up = to_line > 0 ? to_line - 1 : to_line;
tx->select(from_line_up, from_col, to_line_up, to_column);
- }
- else
- {
+ } else {
int line_id = tx->cursor_get_line();
int next_id = line_id - 1;
@@ -667,33 +640,29 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
tx->begin_complex_operation();
- if (tx->is_selection_active())
- {
+ if (tx->is_selection_active()) {
int from_line = tx->get_selection_from_line();
- int from_col = tx->get_selection_from_column();
- int to_line = tx->get_selection_to_line();
+ int from_col = tx->get_selection_from_column();
+ int to_line = tx->get_selection_to_line();
int to_column = tx->get_selection_to_column();
- for (int i = to_line; i >= from_line; i--)
- {
+ for (int i = to_line; i >= from_line; i--) {
int line_id = i;
int next_id = i + 1;
- if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count())
+ if (line_id == tx->get_line_count() - 1 || next_id > tx->get_line_count())
return;
swap_lines(tx, line_id, next_id);
}
- int from_line_down = from_line < tx->get_line_count() ? from_line+1 : from_line;
- int to_line_down = to_line < tx->get_line_count() ? to_line+1 : to_line;
+ int from_line_down = from_line < tx->get_line_count() ? from_line + 1 : from_line;
+ int to_line_down = to_line < tx->get_line_count() ? to_line + 1 : to_line;
tx->select(from_line_down, from_col, to_line_down, to_column);
- }
- else
- {
+ } else {
int line_id = tx->cursor_get_line();
int next_id = line_id + 1;
- if (line_id == tx->get_line_count()-1 || next_id > tx->get_line_count())
+ if (line_id == tx->get_line_count() - 1 || next_id > tx->get_line_count())
return;
swap_lines(tx, line_id, next_id);
@@ -710,23 +679,18 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
tx->begin_complex_operation();
- if (tx->is_selection_active())
- {
+ if (tx->is_selection_active()) {
tx->indent_selection_left();
- }
- else
- {
+ } else {
int begin = tx->cursor_get_line();
String line_text = tx->get_line(begin);
// begins with tab
- if (line_text.begins_with("\t"))
- {
+ if (line_text.begins_with("\t")) {
line_text = line_text.substr(1, line_text.length());
tx->set_line(begin, line_text);
}
// begins with 4 spaces
- else if (line_text.begins_with(" "))
- {
+ else if (line_text.begins_with(" ")) {
line_text = line_text.substr(4, line_text.length());
tx->set_line(begin, line_text);
}
@@ -744,12 +708,9 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
tx->begin_complex_operation();
- if (tx->is_selection_active())
- {
+ if (tx->is_selection_active()) {
tx->indent_selection_right();
- }
- else
- {
+ } else {
int begin = tx->cursor_get_line();
String line_text = tx->get_line(begin);
line_text = '\t' + line_text;
@@ -782,7 +743,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
for (int i = from_line; i <= to_line; i++) {
if (i >= tx->get_line_count() - 1) {
- tx->set_line(i, tx->get_line(i) + "\n");
+ tx->set_line(i, tx->get_line(i) + "\n");
}
String line_clone = tx->get_line(i);
tx->insert_at(line_clone, next_line);
@@ -805,19 +766,16 @@ void ScriptTextEditor::_edit_option(int p_op) {
if (scr.is_null())
return;
-
tx->begin_complex_operation();
- if (tx->is_selection_active())
- {
+ if (tx->is_selection_active()) {
int begin = tx->get_selection_from_line();
int end = tx->get_selection_to_line();
// End of selection ends on the first column of the last line, ignore it.
- if(tx->get_selection_to_column() == 0)
+ if (tx->get_selection_to_column() == 0)
end -= 1;
- for (int i = begin; i <= end; i++)
- {
+ for (int i = begin; i <= end; i++) {
String line_text = tx->get_line(i);
if (line_text.begins_with("#"))
@@ -826,9 +784,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
line_text = "#" + line_text;
tx->set_line(i, line_text);
}
- }
- else
- {
+ } else {
int begin = tx->cursor_get_line();
String line_text = tx->get_line(begin);
@@ -855,18 +811,17 @@ void ScriptTextEditor::_edit_option(int p_op) {
Ref<Script> scr = get_edited_script();
if (scr.is_null())
return;
- int begin,end;
+ int begin, end;
if (te->is_selection_active()) {
- begin=te->get_selection_from_line();
- end=te->get_selection_to_line();
+ begin = te->get_selection_from_line();
+ end = te->get_selection_to_line();
} else {
- begin=0;
- end=te->get_line_count()-1;
+ begin = 0;
+ end = te->get_line_count() - 1;
}
- scr->get_language()->auto_indent_code(text,begin,end);
+ scr->get_language()->auto_indent_code(text, begin, end);
te->set_text(text);
-
} break;
case EDIT_TRIM_TRAILING_WHITESAPCE: {
trim_trailing_whitespace();
@@ -875,7 +830,6 @@ void ScriptTextEditor::_edit_option(int p_op) {
color_panel->popup();
} break;
-
case SEARCH_FIND: {
code_editor->get_find_replace_bar()->popup_search();
@@ -901,20 +855,20 @@ void ScriptTextEditor::_edit_option(int p_op) {
goto_line_dialog->popup_find_line(code_editor->get_text_edit());
} break;
case DEBUG_TOGGLE_BREAKPOINT: {
- int line=code_editor->get_text_edit()->cursor_get_line();
+ int line = code_editor->get_text_edit()->cursor_get_line();
bool dobreak = !code_editor->get_text_edit()->is_line_set_as_breakpoint(line);
- code_editor->get_text_edit()->set_line_as_breakpoint(line,dobreak);
- ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(get_edited_script()->get_path(),line+1,dobreak);
+ code_editor->get_text_edit()->set_line_as_breakpoint(line, dobreak);
+ ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(get_edited_script()->get_path(), line + 1, dobreak);
} break;
case DEBUG_REMOVE_ALL_BREAKPOINTS: {
List<int> bpoints;
code_editor->get_text_edit()->get_breakpoints(&bpoints);
- for(List<int>::Element *E=bpoints.front();E;E=E->next()) {
+ for (List<int>::Element *E = bpoints.front(); E; E = E->next()) {
int line = E->get();
bool dobreak = !code_editor->get_text_edit()->is_line_set_as_breakpoint(line);
- code_editor->get_text_edit()->set_line_as_breakpoint(line,dobreak);
- ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(get_edited_script()->get_path(),line+1,dobreak);
+ code_editor->get_text_edit()->set_line_as_breakpoint(line, dobreak);
+ ScriptEditor::get_singleton()->get_debugger()->set_breakpoint(get_edited_script()->get_path(), line + 1, dobreak);
}
}
case DEBUG_GOTO_NEXT_BREAKPOINT: {
@@ -924,12 +878,12 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
}
- int line=code_editor->get_text_edit()->cursor_get_line();
+ int line = code_editor->get_text_edit()->cursor_get_line();
// wrap around
if (line >= bpoints[bpoints.size() - 1]) {
code_editor->get_text_edit()->cursor_set_line(bpoints[0]);
} else {
- for(List<int>::Element *E=bpoints.front();E;E=E->next()) {
+ for (List<int>::Element *E = bpoints.front(); E; E = E->next()) {
int bline = E->get();
if (bline > line) {
code_editor->get_text_edit()->cursor_set_line(bline);
@@ -946,12 +900,12 @@ void ScriptTextEditor::_edit_option(int p_op) {
return;
}
- int line=code_editor->get_text_edit()->cursor_get_line();
+ int line = code_editor->get_text_edit()->cursor_get_line();
// wrap around
if (line <= bpoints[0]) {
code_editor->get_text_edit()->cursor_set_line(bpoints[bpoints.size() - 1]);
} else {
- for(List<int>::Element *E=bpoints.back();E;E=E->prev()) {
+ for (List<int>::Element *E = bpoints.back(); E; E = E->prev()) {
int bline = E->get();
if (bline < line) {
code_editor->get_text_edit()->cursor_set_line(bline);
@@ -967,7 +921,7 @@ void ScriptTextEditor::_edit_option(int p_op) {
if (text == "")
text = code_editor->get_text_edit()->get_word_under_cursor();
if (text != "") {
- emit_signal("request_help_search",text);
+ emit_signal("request_help_search", text);
}
} break;
}
@@ -975,20 +929,18 @@ void ScriptTextEditor::_edit_option(int p_op) {
void ScriptTextEditor::_bind_methods() {
- ClassDB::bind_method("_validate_script",&ScriptTextEditor::_validate_script);
- ClassDB::bind_method("_load_theme_settings",&ScriptTextEditor::_load_theme_settings);
- ClassDB::bind_method("_breakpoint_toggled",&ScriptTextEditor::_breakpoint_toggled);
- ClassDB::bind_method("_edit_option",&ScriptTextEditor::_edit_option);
- ClassDB::bind_method("_goto_line",&ScriptTextEditor::_goto_line);
- ClassDB::bind_method("_lookup_symbol",&ScriptTextEditor::_lookup_symbol);
+ ClassDB::bind_method("_validate_script", &ScriptTextEditor::_validate_script);
+ ClassDB::bind_method("_load_theme_settings", &ScriptTextEditor::_load_theme_settings);
+ ClassDB::bind_method("_breakpoint_toggled", &ScriptTextEditor::_breakpoint_toggled);
+ ClassDB::bind_method("_edit_option", &ScriptTextEditor::_edit_option);
+ ClassDB::bind_method("_goto_line", &ScriptTextEditor::_goto_line);
+ ClassDB::bind_method("_lookup_symbol", &ScriptTextEditor::_lookup_symbol);
ClassDB::bind_method("_text_edit_gui_input", &ScriptTextEditor::_text_edit_gui_input);
ClassDB::bind_method("_color_changed", &ScriptTextEditor::_color_changed);
-
- ClassDB::bind_method("get_drag_data_fw",&ScriptTextEditor::get_drag_data_fw);
- ClassDB::bind_method("can_drop_data_fw",&ScriptTextEditor::can_drop_data_fw);
- ClassDB::bind_method("drop_data_fw",&ScriptTextEditor::drop_data_fw);
-
+ ClassDB::bind_method("get_drag_data_fw", &ScriptTextEditor::get_drag_data_fw);
+ ClassDB::bind_method("can_drop_data_fw", &ScriptTextEditor::can_drop_data_fw);
+ ClassDB::bind_method("drop_data_fw", &ScriptTextEditor::drop_data_fw);
}
Control *ScriptTextEditor::get_edit_menu() {
@@ -1003,67 +955,59 @@ void ScriptTextEditor::reload(bool p_soft) {
if (scr.is_null())
return;
scr->set_source_code(te->get_text());
- bool soft = p_soft || scr->get_instance_base_type()=="EditorPlugin"; //always soft-reload editor plugins
+ bool soft = p_soft || scr->get_instance_base_type() == "EditorPlugin"; //always soft-reload editor plugins
- scr->get_language()->reload_tool_script(scr,soft);
+ scr->get_language()->reload_tool_script(scr, soft);
}
void ScriptTextEditor::get_breakpoints(List<int> *p_breakpoints) {
code_editor->get_text_edit()->get_breakpoints(p_breakpoints);
-
}
-void ScriptTextEditor::set_tooltip_request_func(String p_method,Object* p_obj) {
+void ScriptTextEditor::set_tooltip_request_func(String p_method, Object *p_obj) {
- code_editor->get_text_edit()->set_tooltip_request_func(p_obj,p_method,this);
+ code_editor->get_text_edit()->set_tooltip_request_func(p_obj, p_method, this);
}
void ScriptTextEditor::set_debugger_active(bool p_active) {
-
-
}
-
-Variant ScriptTextEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant ScriptTextEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
return Variant();
}
-bool ScriptTextEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool ScriptTextEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
if (d.has("type") &&
(
- String(d["type"])=="resource" ||
- String(d["type"])=="files" ||
- String(d["type"])=="nodes"
- ) ) {
+ String(d["type"]) == "resource" ||
+ String(d["type"]) == "files" ||
+ String(d["type"]) == "nodes")) {
-
- return true;
+ return true;
}
-
return false;
-
}
#ifdef TOOLS_ENABLED
-static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const Ref<Script> &script) {
+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 NULL;
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);
+ 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)
return n;
}
@@ -1073,20 +1017,17 @@ static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const R
#else
-static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const Ref<Script> &script) {
+static Node *_find_script_node(Node *p_edited_scene, Node *p_current_node, const Ref<Script> &script) {
return NULL;
}
#endif
-
-
-
-void ScriptTextEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void ScriptTextEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
Dictionary d = p_data;
- if (d.has("type") && String(d["type"])=="resource") {
+ if (d.has("type") && String(d["type"]) == "resource") {
Ref<Resource> res = d["resource"];
if (!res.is_valid()) {
@@ -1099,44 +1040,38 @@ void ScriptTextEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,
}
code_editor->get_text_edit()->insert_text_at_cursor(res->get_path());
-
}
- if (d.has("type") && String(d["type"])=="files") {
-
+ if (d.has("type") && String(d["type"]) == "files") {
Array files = d["files"];
String text_to_drop;
- for(int i=0;i<files.size();i++) {
-
- if (i>0)
- text_to_drop+=",";
- text_to_drop+="\""+String(files[i]).c_escape()+"\"";
+ for (int i = 0; i < files.size(); i++) {
+ if (i > 0)
+ text_to_drop += ",";
+ text_to_drop += "\"" + String(files[i]).c_escape() + "\"";
}
code_editor->get_text_edit()->insert_text_at_cursor(text_to_drop);
-
}
- if (d.has("type") && String(d["type"])=="nodes") {
-
- Node* sn = _find_script_node(get_tree()->get_edited_scene_root(),get_tree()->get_edited_scene_root(),script);
+ if (d.has("type") && String(d["type"]) == "nodes") {
+ Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
if (!sn) {
- EditorNode::get_singleton()->show_warning("Can't drop nodes because script '"+get_name()+"' is not used in this scene.");
+ EditorNode::get_singleton()->show_warning("Can't drop nodes because script '" + get_name() + "' is not used in this scene.");
return;
}
-
Array nodes = d["nodes"];
String text_to_drop;
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
- if (i>0)
- text_to_drop+=",";
+ if (i > 0)
+ text_to_drop += ",";
NodePath np = nodes[i];
Node *node = get_node(np);
@@ -1144,32 +1079,23 @@ void ScriptTextEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,
continue;
}
-
-
String path = sn->get_path_to(node);
- text_to_drop+="\""+path.c_escape()+"\"";
-
-
+ text_to_drop += "\"" + path.c_escape() + "\"";
}
code_editor->get_text_edit()->insert_text_at_cursor(text_to_drop);
-
-
}
-
-
-
}
-void ScriptTextEditor::_text_edit_gui_input(const InputEvent& ev) {
+void ScriptTextEditor::_text_edit_gui_input(const InputEvent &ev) {
if (ev.type == InputEvent::MOUSE_BUTTON) {
InputEventMouseButton mb = ev.mouse_button;
if (mb.button_index == BUTTON_RIGHT && !mb.pressed) {
int col, row;
- TextEdit* tx = code_editor->get_text_edit();
- tx->_get_mouse_pos(Point2i(mb.global_x, mb.global_y)-tx->get_global_pos(), row, col);
- Vector2 mpos = Vector2(mb.global_x, mb.global_y)-tx->get_global_pos();
+ TextEdit *tx = code_editor->get_text_edit();
+ tx->_get_mouse_pos(Point2i(mb.global_x, mb.global_y) - tx->get_global_pos(), row, col);
+ Vector2 mpos = Vector2(mb.global_x, mb.global_y) - tx->get_global_pos();
bool have_selection = (tx->get_selection_text().length() > 0);
bool have_color = (tx->get_word_at_pos(mpos) == "Color");
if (have_color) {
@@ -1177,21 +1103,20 @@ void ScriptTextEditor::_text_edit_gui_input(const InputEvent& ev) {
String line = tx->get_line(row);
color_line = row;
int begin = 0;
- int end = 0;
+ int end = 0;
bool valid = false;
for (int i = col; i < line.length(); i++) {
if (line[i] == '(') {
begin = i;
continue;
- }
- else if (line[i] == ')') {
- end = i+1;
+ } else if (line[i] == ')') {
+ end = i + 1;
valid = true;
break;
}
}
if (valid) {
- color_args = line.substr(begin, end-begin);
+ color_args = line.substr(begin, end - begin);
String stripped = color_args.replace(" ", "").replace("(", "").replace(")", "");
Vector<float> color = stripped.split_floats(",");
if (color.size() > 2) {
@@ -1199,7 +1124,7 @@ void ScriptTextEditor::_text_edit_gui_input(const InputEvent& ev) {
color_picker->set_pick_color(Color(color[0], color[1], color[2], alpha));
}
color_panel->set_pos(get_global_transform().xform(get_local_mouse_pos()));
- Size2 ms = Size2(300, color_picker->get_combined_minimum_size().height+10);
+ Size2 ms = Size2(300, color_picker->get_combined_minimum_size().height + 10);
color_panel->set_size(ms);
} else {
have_color = false;
@@ -1210,12 +1135,12 @@ void ScriptTextEditor::_text_edit_gui_input(const InputEvent& ev) {
}
}
-void ScriptTextEditor::_color_changed(const Color& p_color) {
+void ScriptTextEditor::_color_changed(const Color &p_color) {
String new_args;
if (p_color.a == 1.0f) {
- new_args = String("("+rtos(p_color.r)+", "+rtos(p_color.g)+", "+rtos(p_color.b)+")");
+ new_args = String("(" + rtos(p_color.r) + ", " + rtos(p_color.g) + ", " + rtos(p_color.b) + ")");
} else {
- new_args = String("("+rtos(p_color.r)+", "+rtos(p_color.g)+", "+rtos(p_color.b)+", "+rtos(p_color.a)+")");
+ new_args = String("(" + rtos(p_color.r) + ", " + rtos(p_color.g) + ", " + rtos(p_color.b) + ", " + rtos(p_color.a) + ")");
}
String line = code_editor->get_text_edit()->get_line(color_line);
@@ -1255,20 +1180,20 @@ void ScriptTextEditor::_make_context_menu(bool p_selection, bool p_color) {
ScriptTextEditor::ScriptTextEditor() {
- code_editor = memnew( CodeTextEditor );
+ code_editor = memnew(CodeTextEditor);
add_child(code_editor);
code_editor->set_area_as_parent_rect();
- code_editor->connect("validate_script",this,"_validate_script");
- code_editor->connect("load_theme_settings",this,"_load_theme_settings");
- code_editor->set_code_complete_func(_code_complete_scripts,this);
+ code_editor->connect("validate_script", this, "_validate_script");
+ code_editor->connect("load_theme_settings", this, "_load_theme_settings");
+ code_editor->set_code_complete_func(_code_complete_scripts, this);
code_editor->get_text_edit()->connect("breakpoint_toggled", this, "_breakpoint_toggled");
code_editor->get_text_edit()->connect("symbol_lookup", this, "_lookup_symbol");
update_settings();
code_editor->get_text_edit()->set_callhint_settings(
- EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"),
- EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset"));
+ EditorSettings::get_singleton()->get("text_editor/completion/put_callhint_tooltip_below_current_line"),
+ EditorSettings::get_singleton()->get("text_editor/completion/callhint_tooltip_offset"));
code_editor->get_text_edit()->set_select_identifiers_on_hover(true);
code_editor->get_text_edit()->set_context_menu_enabled(false);
@@ -1285,9 +1210,9 @@ ScriptTextEditor::ScriptTextEditor() {
color_panel->set_child_rect(color_picker); //NOT
color_picker->connect("color_changed", this, "_color_changed");
- edit_hb = memnew (HBoxContainer);
+ edit_hb = memnew(HBoxContainer);
- edit_menu = memnew( MenuButton );
+ edit_menu = memnew(MenuButton);
edit_menu->set_text(TTR("Edit"));
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/undo"), EDIT_UNDO);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/redo"), EDIT_REDO);
@@ -1312,14 +1237,14 @@ ScriptTextEditor::ScriptTextEditor() {
#endif
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/trim_trailing_whitespace"), EDIT_TRIM_TRAILING_WHITESAPCE);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/auto_indent"), EDIT_AUTO_INDENT);
- edit_menu->get_popup()->connect("id_pressed", this,"_edit_option");
+ edit_menu->get_popup()->connect("id_pressed", this, "_edit_option");
edit_menu->get_popup()->add_separator();
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/toggle_breakpoint"), DEBUG_TOGGLE_BREAKPOINT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/remove_all_breakpoints"), DEBUG_REMOVE_ALL_BREAKPOINTS);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_next_breakpoint"), DEBUG_GOTO_NEXT_BREAKPOINT);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/goto_previous_breakpoint"), DEBUG_GOTO_PREV_BREAKPOINT);
- search_menu = memnew( MenuButton );
+ search_menu = memnew(MenuButton);
edit_hb->add_child(search_menu);
search_menu->set_text(TTR("Search"));
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/find"), SEARCH_FIND);
@@ -1332,25 +1257,24 @@ ScriptTextEditor::ScriptTextEditor() {
search_menu->get_popup()->add_separator();
search_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("script_text_editor/contextual_help"), HELP_CONTEXTUAL);
- search_menu->get_popup()->connect("id_pressed", this,"_edit_option");
+ search_menu->get_popup()->connect("id_pressed", this, "_edit_option");
edit_hb->add_child(edit_menu);
- quick_open = memnew( ScriptEditorQuickOpen );
+ quick_open = memnew(ScriptEditorQuickOpen);
add_child(quick_open);
- quick_open->connect("goto_line",this,"_goto_line");
+ quick_open->connect("goto_line", this, "_goto_line");
goto_line_dialog = memnew(GotoLineDialog);
add_child(goto_line_dialog);
-
code_editor->get_text_edit()->set_drag_forwarding(this);
}
-static ScriptEditorBase * create_editor(const Ref<Script>& p_script) {
+static ScriptEditorBase *create_editor(const Ref<Script> &p_script) {
if (p_script->has_source_code()) {
- return memnew( ScriptTextEditor );
+ return memnew(ScriptTextEditor);
}
return NULL;
@@ -1358,44 +1282,44 @@ static ScriptEditorBase * create_editor(const Ref<Script>& p_script) {
void ScriptTextEditor::register_editor() {
- ED_SHORTCUT("script_text_editor/undo", TTR("Undo"), KEY_MASK_CMD|KEY_Z);
- ED_SHORTCUT("script_text_editor/redo", TTR("Redo"), KEY_MASK_CMD|KEY_Y);
- ED_SHORTCUT("script_text_editor/cut", TTR("Cut"), KEY_MASK_CMD|KEY_X);
- ED_SHORTCUT("script_text_editor/copy", TTR("Copy"), KEY_MASK_CMD|KEY_C);
- ED_SHORTCUT("script_text_editor/paste", TTR("Paste"), KEY_MASK_CMD|KEY_V);
- ED_SHORTCUT("script_text_editor/select_all", TTR("Select All"), KEY_MASK_CMD|KEY_A);
- ED_SHORTCUT("script_text_editor/move_up", TTR("Move Up"), KEY_MASK_ALT|KEY_UP);
- ED_SHORTCUT("script_text_editor/move_down", TTR("Move Down"), KEY_MASK_ALT|KEY_DOWN);
+ ED_SHORTCUT("script_text_editor/undo", TTR("Undo"), KEY_MASK_CMD | KEY_Z);
+ ED_SHORTCUT("script_text_editor/redo", TTR("Redo"), KEY_MASK_CMD | KEY_Y);
+ ED_SHORTCUT("script_text_editor/cut", TTR("Cut"), KEY_MASK_CMD | KEY_X);
+ ED_SHORTCUT("script_text_editor/copy", TTR("Copy"), KEY_MASK_CMD | KEY_C);
+ ED_SHORTCUT("script_text_editor/paste", TTR("Paste"), KEY_MASK_CMD | KEY_V);
+ ED_SHORTCUT("script_text_editor/select_all", TTR("Select All"), KEY_MASK_CMD | KEY_A);
+ ED_SHORTCUT("script_text_editor/move_up", TTR("Move Up"), KEY_MASK_ALT | KEY_UP);
+ ED_SHORTCUT("script_text_editor/move_down", TTR("Move Down"), KEY_MASK_ALT | KEY_DOWN);
//leave these at zero, same can be accomplished with tab/shift-tab, including selection
//the next/previous in history shortcut in this case makes a lot more sene.
ED_SHORTCUT("script_text_editor/indent_left", TTR("Indent Left"), 0);
ED_SHORTCUT("script_text_editor/indent_right", TTR("Indent Right"), 0);
- ED_SHORTCUT("script_text_editor/toggle_comment", TTR("Toggle Comment"), KEY_MASK_CMD|KEY_K);
- ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_CMD|KEY_B);
+ ED_SHORTCUT("script_text_editor/toggle_comment", TTR("Toggle Comment"), KEY_MASK_CMD | KEY_K);
+ ED_SHORTCUT("script_text_editor/clone_down", TTR("Clone Down"), KEY_MASK_CMD | KEY_B);
#ifdef OSX_ENABLED
- ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CTRL|KEY_SPACE);
+ ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CTRL | KEY_SPACE);
#else
- ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CMD|KEY_SPACE);
+ ED_SHORTCUT("script_text_editor/complete_symbol", TTR("Complete Symbol"), KEY_MASK_CMD | KEY_SPACE);
#endif
- ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTR("Trim Trailing Whitespace"), KEY_MASK_CTRL|KEY_MASK_ALT|KEY_T);
- ED_SHORTCUT("script_text_editor/auto_indent", TTR("Auto Indent"), KEY_MASK_CMD|KEY_I);
+ ED_SHORTCUT("script_text_editor/trim_trailing_whitespace", TTR("Trim Trailing Whitespace"), KEY_MASK_CTRL | KEY_MASK_ALT | KEY_T);
+ ED_SHORTCUT("script_text_editor/auto_indent", TTR("Auto Indent"), KEY_MASK_CMD | KEY_I);
ED_SHORTCUT("script_text_editor/toggle_breakpoint", TTR("Toggle Breakpoint"), KEY_F9);
- ED_SHORTCUT("script_text_editor/remove_all_breakpoints", TTR("Remove All Breakpoints"), KEY_MASK_CTRL|KEY_MASK_SHIFT|KEY_F9);
- ED_SHORTCUT("script_text_editor/goto_next_breakpoint", TTR("Goto Next Breakpoint"), KEY_MASK_CTRL|KEY_PERIOD);
- ED_SHORTCUT("script_text_editor/goto_previous_breakpoint", TTR("Goto Previous Breakpoint"), KEY_MASK_CTRL|KEY_COMMA);
+ ED_SHORTCUT("script_text_editor/remove_all_breakpoints", TTR("Remove All Breakpoints"), KEY_MASK_CTRL | KEY_MASK_SHIFT | KEY_F9);
+ ED_SHORTCUT("script_text_editor/goto_next_breakpoint", TTR("Goto Next Breakpoint"), KEY_MASK_CTRL | KEY_PERIOD);
+ ED_SHORTCUT("script_text_editor/goto_previous_breakpoint", TTR("Goto Previous Breakpoint"), KEY_MASK_CTRL | KEY_COMMA);
- ED_SHORTCUT("script_text_editor/find", TTR("Find.."), KEY_MASK_CMD|KEY_F);
+ ED_SHORTCUT("script_text_editor/find", TTR("Find.."), KEY_MASK_CMD | KEY_F);
ED_SHORTCUT("script_text_editor/find_next", TTR("Find Next"), KEY_F3);
- ED_SHORTCUT("script_text_editor/find_previous", TTR("Find Previous"), KEY_MASK_SHIFT|KEY_F3);
- ED_SHORTCUT("script_text_editor/replace", TTR("Replace.."), KEY_MASK_CMD|KEY_R);
+ ED_SHORTCUT("script_text_editor/find_previous", TTR("Find Previous"), KEY_MASK_SHIFT | KEY_F3);
+ ED_SHORTCUT("script_text_editor/replace", TTR("Replace.."), KEY_MASK_CMD | KEY_R);
- ED_SHORTCUT("script_text_editor/goto_function", TTR("Goto Function.."), KEY_MASK_SHIFT|KEY_MASK_CMD|KEY_F);
- ED_SHORTCUT("script_text_editor/goto_line", TTR("Goto Line.."), KEY_MASK_CMD|KEY_L);
+ ED_SHORTCUT("script_text_editor/goto_function", TTR("Goto Function.."), KEY_MASK_SHIFT | KEY_MASK_CMD | KEY_F);
+ ED_SHORTCUT("script_text_editor/goto_line", TTR("Goto Line.."), KEY_MASK_CMD | KEY_L);
- ED_SHORTCUT("script_text_editor/contextual_help", TTR("Contextual Help"), KEY_MASK_SHIFT|KEY_F1);
+ ED_SHORTCUT("script_text_editor/contextual_help", TTR("Contextual Help"), KEY_MASK_SHIFT | KEY_F1);
ScriptEditor::register_create_script_editor_function(create_editor);
}
diff --git a/editor/plugins/script_text_editor.h b/editor/plugins/script_text_editor.h
index e30a78340e..c5f65fb1db 100644
--- a/editor/plugins/script_text_editor.h
+++ b/editor/plugins/script_text_editor.h
@@ -29,26 +29,24 @@
#ifndef SCRIPT_TEXT_EDITOR_H
#define SCRIPT_TEXT_EDITOR_H
-#include "script_editor_plugin.h"
#include "scene/gui/color_picker.h"
-
+#include "script_editor_plugin.h"
class ScriptTextEditor : public ScriptEditorBase {
- GDCLASS( ScriptTextEditor, ScriptEditorBase );
+ GDCLASS(ScriptTextEditor, ScriptEditorBase);
CodeTextEditor *code_editor;
Ref<Script> script;
-
Vector<String> functions;
HBoxContainer *edit_hb;
MenuButton *edit_menu;
MenuButton *search_menu;
- PopupMenu *context_menu;
+ PopupMenu *context_menu;
GotoLineDialog *goto_line_dialog;
ScriptEditorQuickOpen *quick_open;
@@ -88,16 +86,13 @@ class ScriptTextEditor : public ScriptEditorBase {
HELP_CONTEXTUAL,
};
-
protected:
-
-
- static void _code_complete_scripts(void* p_ud,const String& p_code, List<String>* r_options);
+ static void _code_complete_scripts(void *p_ud, const String &p_code, List<String> *r_options);
void _breakpoint_toggled(int p_row);
//no longer virtual
void _validate_script();
- void _code_complete_script(const String& p_code, List<String>* r_options);
+ void _code_complete_script(const String &p_code, List<String> *r_options);
void _load_theme_settings();
void _notification(int p_what);
@@ -105,43 +100,42 @@ protected:
void _edit_option(int p_op);
void _make_context_menu(bool p_selection, bool p_color);
- void _text_edit_gui_input(const InputEvent& ev);
- void _color_changed(const Color& p_color);
+ void _text_edit_gui_input(const InputEvent &ev);
+ void _color_changed(const Color &p_color);
void _goto_line(int p_line) { goto_line(p_line); }
- void _lookup_symbol(const String& p_symbol,int p_row, int p_column);
+ void _lookup_symbol(const String &p_symbol, int p_row, int p_column);
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
public:
-
virtual void apply_code();
virtual Ref<Script> get_edited_script() const;
- virtual Vector<String> get_functions() ;
- virtual void set_edited_script(const Ref<Script>& p_script);
+ virtual Vector<String> get_functions();
+ virtual void set_edited_script(const Ref<Script> &p_script);
virtual void reload_text();
- virtual String get_name() ;
- virtual Ref<Texture> get_icon() ;
+ virtual String get_name();
+ virtual Ref<Texture> get_icon();
virtual bool is_unsaved();
virtual Variant get_edit_state();
- virtual void set_edit_state(const Variant& p_state);
+ virtual void set_edit_state(const Variant &p_state);
virtual void ensure_focus();
virtual void trim_trailing_whitespace();
virtual void tag_saved_version();
- virtual void goto_line(int p_line,bool p_with_error=false);
+ virtual void goto_line(int p_line, bool p_with_error = false);
virtual void reload(bool p_soft);
virtual void get_breakpoints(List<int> *p_breakpoints);
- virtual void add_callback(const String& p_function,PoolStringArray p_args);
+ virtual void add_callback(const String &p_function, PoolStringArray p_args);
virtual void update_settings();
- virtual bool goto_method(const String& p_method);
+ virtual bool goto_method(const String &p_method);
- virtual void set_tooltip_request_func(String p_method,Object* p_obj);
+ virtual void set_tooltip_request_func(String p_method, Object *p_obj);
virtual void set_debugger_active(bool p_active);
@@ -150,10 +144,6 @@ public:
static void register_editor();
ScriptTextEditor();
-
};
-
-
-
#endif // SCRIPT_TEXT_EDITOR_H
diff --git a/editor/plugins/shader_editor_plugin.cpp b/editor/plugins/shader_editor_plugin.cpp
index c14d1650fd..c295a6679e 100644
--- a/editor/plugins/shader_editor_plugin.cpp
+++ b/editor/plugins/shader_editor_plugin.cpp
@@ -28,113 +28,99 @@
/*************************************************************************/
#include "shader_editor_plugin.h"
+#include "editor/editor_node.h"
#include "editor/editor_settings.h"
-#include "spatial_editor_plugin.h"
-#include "scene/resources/shader_graph.h"
+#include "editor/property_editor.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "os/keyboard.h"
-#include "editor/editor_node.h"
-#include "editor/property_editor.h"
#include "os/os.h"
+#include "scene/resources/shader_graph.h"
#include "servers/visual/shader_types.h"
+#include "spatial_editor_plugin.h"
/*** SETTINGS EDITOR ****/
-
-
-
/*** SCRIPT EDITOR ****/
-
Ref<Shader> ShaderTextEditor::get_edited_shader() const {
return shader;
}
-void ShaderTextEditor::set_edited_shader(const Ref<Shader>& p_shader) {
-
- shader=p_shader;
+void ShaderTextEditor::set_edited_shader(const Ref<Shader> &p_shader) {
+ shader = p_shader;
_load_theme_settings();
get_text_edit()->set_text(p_shader->get_code());
_line_col_changed();
-
-
}
-
void ShaderTextEditor::_load_theme_settings() {
get_text_edit()->clear_colors();
/* keyword color */
- get_text_edit()->add_color_override("background_color", EDITOR_DEF("text_editor/highlighting/background_color",Color(0,0,0,0)));
- get_text_edit()->add_color_override("completion_background_color", EDITOR_DEF("text_editor/highlighting/completion_background_color", Color(0,0,0,0)));
+ get_text_edit()->add_color_override("background_color", EDITOR_DEF("text_editor/highlighting/background_color", Color(0, 0, 0, 0)));
+ get_text_edit()->add_color_override("completion_background_color", EDITOR_DEF("text_editor/highlighting/completion_background_color", Color(0, 0, 0, 0)));
get_text_edit()->add_color_override("completion_selected_color", EDITOR_DEF("text_editor/highlighting/completion_selected_color", Color::html("434244")));
get_text_edit()->add_color_override("completion_existing_color", EDITOR_DEF("text_editor/highlighting/completion_existing_color", Color::html("21dfdfdf")));
get_text_edit()->add_color_override("completion_scroll_color", EDITOR_DEF("text_editor/highlighting/completion_scroll_color", Color::html("ffffff")));
get_text_edit()->add_color_override("completion_font_color", EDITOR_DEF("text_editor/highlighting/completion_font_color", Color::html("aaaaaa")));
- get_text_edit()->add_color_override("font_color",EDITOR_DEF("text_editor/highlighting/text_color",Color(0,0,0)));
- get_text_edit()->add_color_override("line_number_color",EDITOR_DEF("text_editor/highlighting/line_number_color",Color(0,0,0)));
- get_text_edit()->add_color_override("caret_color",EDITOR_DEF("text_editor/highlighting/caret_color",Color(0,0,0)));
- get_text_edit()->add_color_override("caret_background_color",EDITOR_DEF("text_editor/highlighting/caret_background_color",Color(0,0,0)));
- get_text_edit()->add_color_override("font_selected_color",EDITOR_DEF("text_editor/highlighting/text_selected_color",Color(1,1,1)));
- get_text_edit()->add_color_override("selection_color",EDITOR_DEF("text_editor/highlighting/selection_color",Color(0.2,0.2,1)));
- get_text_edit()->add_color_override("brace_mismatch_color",EDITOR_DEF("text_editor/highlighting/brace_mismatch_color",Color(1,0.2,0.2)));
- get_text_edit()->add_color_override("current_line_color",EDITOR_DEF("text_editor/highlighting/current_line_color",Color(0.3,0.5,0.8,0.15)));
- get_text_edit()->add_color_override("word_highlighted_color",EDITOR_DEF("text_editor/highlighting/word_highlighted_color",Color(0.8,0.9,0.9,0.15)));
- get_text_edit()->add_color_override("number_color",EDITOR_DEF("text_editor/highlighting/number_color",Color(0.9,0.6,0.0,2)));
- get_text_edit()->add_color_override("function_color",EDITOR_DEF("text_editor/highlighting/function_color",Color(0.4,0.6,0.8)));
- get_text_edit()->add_color_override("member_variable_color",EDITOR_DEF("text_editor/highlighting/member_variable_color",Color(0.9,0.3,0.3)));
- get_text_edit()->add_color_override("mark_color", EDITOR_DEF("text_editor/highlighting/mark_color", Color(1.0,0.4,0.4,0.4)));
- get_text_edit()->add_color_override("breakpoint_color", EDITOR_DEF("text_editor/highlighting/breakpoint_color", Color(0.8,0.8,0.4,0.2)));
- get_text_edit()->add_color_override("search_result_color",EDITOR_DEF("text_editor/highlighting/search_result_color",Color(0.05,0.25,0.05,1)));
- get_text_edit()->add_color_override("search_result_border_color",EDITOR_DEF("text_editor/highlighting/search_result_border_color",Color(0.1,0.45,0.1,1)));
- get_text_edit()->add_color_override("symbol_color",EDITOR_DEF("text_editor/highlighting/symbol_color",Color::hex(0x005291ff)));
-
- Color keyword_color= EDITOR_DEF("text_editor/highlighting/keyword_color",Color(0.5,0.0,0.2));
-
+ get_text_edit()->add_color_override("font_color", EDITOR_DEF("text_editor/highlighting/text_color", Color(0, 0, 0)));
+ get_text_edit()->add_color_override("line_number_color", EDITOR_DEF("text_editor/highlighting/line_number_color", Color(0, 0, 0)));
+ get_text_edit()->add_color_override("caret_color", EDITOR_DEF("text_editor/highlighting/caret_color", Color(0, 0, 0)));
+ get_text_edit()->add_color_override("caret_background_color", EDITOR_DEF("text_editor/highlighting/caret_background_color", Color(0, 0, 0)));
+ get_text_edit()->add_color_override("font_selected_color", EDITOR_DEF("text_editor/highlighting/text_selected_color", Color(1, 1, 1)));
+ get_text_edit()->add_color_override("selection_color", EDITOR_DEF("text_editor/highlighting/selection_color", Color(0.2, 0.2, 1)));
+ get_text_edit()->add_color_override("brace_mismatch_color", EDITOR_DEF("text_editor/highlighting/brace_mismatch_color", Color(1, 0.2, 0.2)));
+ get_text_edit()->add_color_override("current_line_color", EDITOR_DEF("text_editor/highlighting/current_line_color", Color(0.3, 0.5, 0.8, 0.15)));
+ get_text_edit()->add_color_override("word_highlighted_color", EDITOR_DEF("text_editor/highlighting/word_highlighted_color", Color(0.8, 0.9, 0.9, 0.15)));
+ get_text_edit()->add_color_override("number_color", EDITOR_DEF("text_editor/highlighting/number_color", Color(0.9, 0.6, 0.0, 2)));
+ get_text_edit()->add_color_override("function_color", EDITOR_DEF("text_editor/highlighting/function_color", Color(0.4, 0.6, 0.8)));
+ get_text_edit()->add_color_override("member_variable_color", EDITOR_DEF("text_editor/highlighting/member_variable_color", Color(0.9, 0.3, 0.3)));
+ get_text_edit()->add_color_override("mark_color", EDITOR_DEF("text_editor/highlighting/mark_color", Color(1.0, 0.4, 0.4, 0.4)));
+ get_text_edit()->add_color_override("breakpoint_color", EDITOR_DEF("text_editor/highlighting/breakpoint_color", Color(0.8, 0.8, 0.4, 0.2)));
+ get_text_edit()->add_color_override("search_result_color", EDITOR_DEF("text_editor/highlighting/search_result_color", Color(0.05, 0.25, 0.05, 1)));
+ get_text_edit()->add_color_override("search_result_border_color", EDITOR_DEF("text_editor/highlighting/search_result_border_color", Color(0.1, 0.45, 0.1, 1)));
+ get_text_edit()->add_color_override("symbol_color", EDITOR_DEF("text_editor/highlighting/symbol_color", Color::hex(0x005291ff)));
+
+ Color keyword_color = EDITOR_DEF("text_editor/highlighting/keyword_color", Color(0.5, 0.0, 0.2));
List<String> keywords;
ShaderLanguage::get_keyword_list(&keywords);
if (shader.is_valid()) {
+ for (const Map<StringName, Map<StringName, ShaderLanguage::DataType> >::Element *E = ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())).front(); E; E = E->next()) {
- for(const Map< StringName, Map<StringName,ShaderLanguage::DataType> >::Element *E=ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())).front();E;E=E->next()) {
-
- for (const Map<StringName,ShaderLanguage::DataType>::Element *F=E->get().front();F;F=F->next()) {
+ for (const Map<StringName, ShaderLanguage::DataType>::Element *F = E->get().front(); F; F = F->next()) {
keywords.push_back(F->key());
}
-
}
- for(const Set<String>::Element *E =ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())).front();E;E=E->next()) {
+ for (const Set<String>::Element *E = ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())).front(); E; E = E->next()) {
keywords.push_back(E->get());
-
}
}
+ for (List<String>::Element *E = keywords.front(); E; E = E->next()) {
- for(List<String>::Element *E=keywords.front();E;E=E->next()) {
-
- get_text_edit()->add_keyword_color(E->get(),keyword_color);
+ get_text_edit()->add_keyword_color(E->get(), keyword_color);
}
//colorize core types
//Color basetype_color= EDITOR_DEF("text_editor/base_type_color",Color(0.3,0.3,0.0));
-
//colorize comments
- Color comment_color = EDITOR_DEF("text_editor/highlighting/comment_color",Color::hex(0x797e7eff));
+ Color comment_color = EDITOR_DEF("text_editor/highlighting/comment_color", Color::hex(0x797e7eff));
- get_text_edit()->add_color_region("/*","*/",comment_color,false);
- get_text_edit()->add_color_region("//","",comment_color,false);
+ get_text_edit()->add_color_region("/*", "*/", comment_color, false);
+ get_text_edit()->add_color_region("//", "", comment_color, false);
/*//colorize strings
Color string_color = EDITOR_DEF("text_editor/string_color",Color::hex(0x6b6f00ff));
@@ -151,38 +137,38 @@ void ShaderTextEditor::_load_theme_settings() {
}*/
}
-void ShaderTextEditor::_code_complete_script(const String& p_code, List<String>* r_options) {
+void ShaderTextEditor::_code_complete_script(const String &p_code, List<String> *r_options) {
print_line("code complete");
ShaderLanguage sl;
String calltip;
- Error err = sl.complete(p_code,ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())),ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())),r_options,calltip);
+ Error err = sl.complete(p_code, ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())), ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())), r_options, calltip);
- if (calltip!="") {
+ if (calltip != "") {
get_text_edit()->set_code_hint(calltip);
}
}
void ShaderTextEditor::_validate_script() {
- String code=get_text_edit()->get_text();
+ String code = get_text_edit()->get_text();
//List<StringName> params;
//shader->get_param_list(&params);
ShaderLanguage sl;
- Error err = sl.compile(code,ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())),ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())));
+ Error err = sl.compile(code, ShaderTypes::get_singleton()->get_functions(VisualServer::ShaderMode(shader->get_mode())), ShaderTypes::get_singleton()->get_modes(VisualServer::ShaderMode(shader->get_mode())));
- if (err!=OK) {
- String error_text="error("+itos(sl.get_error_line())+"): "+sl.get_error_text();
+ if (err != OK) {
+ String error_text = "error(" + itos(sl.get_error_line()) + "): " + sl.get_error_text();
set_error(error_text);
- get_text_edit()->set_line_as_marked(sl.get_error_line(),true);
+ get_text_edit()->set_line_as_marked(sl.get_error_line(), true);
} else {
- for(int i=0;i<get_text_edit()->get_line_count();i++)
- get_text_edit()->set_line_as_marked(i,false);
+ for (int i = 0; i < get_text_edit()->get_line_count(); i++)
+ get_text_edit()->set_line_as_marked(i, false);
set_error("");
}
@@ -191,29 +177,21 @@ void ShaderTextEditor::_validate_script() {
void ShaderTextEditor::_bind_methods() {
-
//ADD_SIGNAL( MethodInfo("script_changed") );
-
}
ShaderTextEditor::ShaderTextEditor() {
-
-
}
/*** SCRIPT EDITOR ******/
-
-
void ShaderEditor::_menu_option(int p_option) {
-
ShaderTextEditor *current = shader_editor;
- switch(p_option) {
+ switch (p_option) {
case EDIT_UNDO: {
-
current->get_text_edit()->undo();
} break;
case EDIT_REDO: {
@@ -260,29 +238,21 @@ void ShaderEditor::_menu_option(int p_option) {
goto_line_dialog->popup_find_line(current->get_text_edit());
} break;
-
}
}
-
void ShaderEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Ref<StyleBox> style = get_stylebox("panel","Panel");
- style->draw( ci, Rect2( Point2(), get_size() ) );
-
+ Ref<StyleBox> style = get_stylebox("panel", "Panel");
+ style->draw(ci, Rect2(Point2(), get_size()));
}
-
}
-
-
Dictionary ShaderEditor::get_state() const {
#if 0
apply_shaders();
@@ -326,7 +296,7 @@ Dictionary ShaderEditor::get_state() const {
#endif
return Dictionary();
}
-void ShaderEditor::set_state(const Dictionary& p_state) {
+void ShaderEditor::set_state(const Dictionary &p_state) {
#if 0
print_line("setting state..");
if (!p_state.has("sources"))
@@ -365,43 +335,41 @@ void ShaderEditor::set_state(const Dictionary& p_state) {
#endif
}
void ShaderEditor::clear() {
-
}
void ShaderEditor::_params_changed() {
-
shader_editor->_validate_script();
}
void ShaderEditor::_editor_settings_changed() {
- shader_editor->get_text_edit()->set_auto_brace_completion(EditorSettings::get_singleton()->get("text_editor/completion/auto_brace_complete"));
- shader_editor->get_text_edit()->set_scroll_pass_end_of_file(EditorSettings::get_singleton()->get("text_editor/cursor/scroll_past_end_of_file"));
- shader_editor->get_text_edit()->set_tab_size(EditorSettings::get_singleton()->get("text_editor/indent/tab_size"));
- shader_editor->get_text_edit()->set_draw_tabs(EditorSettings::get_singleton()->get("text_editor/indent/draw_tabs"));
- shader_editor->get_text_edit()->set_show_line_numbers(EditorSettings::get_singleton()->get("text_editor/line_numbers/show_line_numbers"));
- shader_editor->get_text_edit()->set_syntax_coloring(EditorSettings::get_singleton()->get("text_editor/highlighting/syntax_highlighting"));
- shader_editor->get_text_edit()->set_highlight_all_occurrences(EditorSettings::get_singleton()->get("text_editor/highlighting/highlight_all_occurrences"));
- shader_editor->get_text_edit()->cursor_set_blink_enabled(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink"));
- shader_editor->get_text_edit()->cursor_set_blink_speed(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink_speed"));
- shader_editor->get_text_edit()->add_constant_override("line_spacing", EditorSettings::get_singleton()->get("text_editor/theme/line_spacing"));
- shader_editor->get_text_edit()->cursor_set_block_mode(EditorSettings::get_singleton()->get("text_editor/cursor/block_caret"));
+ shader_editor->get_text_edit()->set_auto_brace_completion(EditorSettings::get_singleton()->get("text_editor/completion/auto_brace_complete"));
+ shader_editor->get_text_edit()->set_scroll_pass_end_of_file(EditorSettings::get_singleton()->get("text_editor/cursor/scroll_past_end_of_file"));
+ shader_editor->get_text_edit()->set_tab_size(EditorSettings::get_singleton()->get("text_editor/indent/tab_size"));
+ shader_editor->get_text_edit()->set_draw_tabs(EditorSettings::get_singleton()->get("text_editor/indent/draw_tabs"));
+ shader_editor->get_text_edit()->set_show_line_numbers(EditorSettings::get_singleton()->get("text_editor/line_numbers/show_line_numbers"));
+ shader_editor->get_text_edit()->set_syntax_coloring(EditorSettings::get_singleton()->get("text_editor/highlighting/syntax_highlighting"));
+ shader_editor->get_text_edit()->set_highlight_all_occurrences(EditorSettings::get_singleton()->get("text_editor/highlighting/highlight_all_occurrences"));
+ shader_editor->get_text_edit()->cursor_set_blink_enabled(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink"));
+ shader_editor->get_text_edit()->cursor_set_blink_speed(EditorSettings::get_singleton()->get("text_editor/cursor/caret_blink_speed"));
+ shader_editor->get_text_edit()->add_constant_override("line_spacing", EditorSettings::get_singleton()->get("text_editor/theme/line_spacing"));
+ shader_editor->get_text_edit()->cursor_set_block_mode(EditorSettings::get_singleton()->get("text_editor/cursor/block_caret"));
}
void ShaderEditor::_bind_methods() {
- ClassDB::bind_method("_editor_settings_changed",&ShaderEditor::_editor_settings_changed);
+ ClassDB::bind_method("_editor_settings_changed", &ShaderEditor::_editor_settings_changed);
- ClassDB::bind_method("_menu_option",&ShaderEditor::_menu_option);
- ClassDB::bind_method("_params_changed",&ShaderEditor::_params_changed);
- ClassDB::bind_method("apply_shaders",&ShaderEditor::apply_shaders);
+ ClassDB::bind_method("_menu_option", &ShaderEditor::_menu_option);
+ ClassDB::bind_method("_params_changed", &ShaderEditor::_params_changed);
+ ClassDB::bind_method("apply_shaders", &ShaderEditor::apply_shaders);
//ClassDB::bind_method("_close_current_tab",&ShaderEditor::_close_current_tab);
}
void ShaderEditor::ensure_select_current() {
-/*
+ /*
if (tab_container->get_child_count() && tab_container->get_current_tab()>=0) {
ShaderTextEditor *ste = tab_container->get_child(tab_container->get_current_tab())->cast_to<ShaderTextEditor>();
@@ -412,20 +380,17 @@ void ShaderEditor::ensure_select_current() {
}*/
}
-void ShaderEditor::edit(const Ref<Shader>& p_shader) {
+void ShaderEditor::edit(const Ref<Shader> &p_shader) {
if (p_shader.is_null())
return;
-
- shader=p_shader;
+ shader = p_shader;
shader_editor->set_edited_shader(p_shader);
//vertex_editor->set_edited_shader(shader,ShaderLanguage::SHADER_MATERIAL_VERTEX);
// see if already has it
-
-
}
void ShaderEditor::save_external_data() {
@@ -434,14 +399,13 @@ void ShaderEditor::save_external_data() {
return;
apply_shaders();
- if (shader->get_path()!="" && shader->get_path().find("local://")==-1 &&shader->get_path().find("::")==-1) {
+ if (shader->get_path() != "" && shader->get_path().find("local://") == -1 && shader->get_path().find("::") == -1) {
//external shader, save it
- ResourceSaver::save(shader->get_path(),shader);
+ ResourceSaver::save(shader->get_path(), shader);
}
}
-void ShaderEditor::apply_shaders() {
-
+void ShaderEditor::apply_shaders() {
if (shader.is_valid()) {
shader->set_code(shader_editor->get_text_edit()->get_text());
@@ -449,75 +413,68 @@ void ShaderEditor::apply_shaders() {
}
}
-
ShaderEditor::ShaderEditor() {
-
- HBoxContainer *hbc = memnew( HBoxContainer);
+ HBoxContainer *hbc = memnew(HBoxContainer);
add_child(hbc);
- edit_menu = memnew( MenuButton );
+ edit_menu = memnew(MenuButton);
hbc->add_child(edit_menu);
- edit_menu->set_pos(Point2(5,-1));
+ edit_menu->set_pos(Point2(5, -1));
edit_menu->set_text(TTR("Edit"));
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/undo", TTR("Undo"), KEY_MASK_CMD|KEY_Z), EDIT_UNDO);
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/redo", TTR("Redo"), KEY_MASK_CMD|KEY_Y), EDIT_REDO);
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/undo", TTR("Undo"), KEY_MASK_CMD | KEY_Z), EDIT_UNDO);
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/redo", TTR("Redo"), KEY_MASK_CMD | KEY_Y), EDIT_REDO);
edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/cut", TTR("Cut"), KEY_MASK_CMD|KEY_X), EDIT_CUT);
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/copy", TTR("Copy"), KEY_MASK_CMD|KEY_C), EDIT_COPY);
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/paste", TTR("Paste"), KEY_MASK_CMD|KEY_V), EDIT_PASTE);
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/cut", TTR("Cut"), KEY_MASK_CMD | KEY_X), EDIT_CUT);
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/copy", TTR("Copy"), KEY_MASK_CMD | KEY_C), EDIT_COPY);
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/paste", TTR("Paste"), KEY_MASK_CMD | KEY_V), EDIT_PASTE);
edit_menu->get_popup()->add_separator();
- edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/select_all", TTR("Select All"), KEY_MASK_CMD|KEY_A), EDIT_SELECT_ALL);
- edit_menu->get_popup()->connect("id_pressed", this,"_menu_option");
+ edit_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/select_all", TTR("Select All"), KEY_MASK_CMD | KEY_A), EDIT_SELECT_ALL);
+ edit_menu->get_popup()->connect("id_pressed", this, "_menu_option");
-
- search_menu = memnew( MenuButton );
+ search_menu = memnew(MenuButton);
hbc->add_child(search_menu);
- search_menu->set_pos(Point2(38,-1));
+ search_menu->set_pos(Point2(38, -1));
search_menu->set_text(TTR("Search"));
- search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find", TTR("Find.."), KEY_MASK_CMD|KEY_F), SEARCH_FIND);
+ search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find", TTR("Find.."), KEY_MASK_CMD | KEY_F), SEARCH_FIND);
search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_next", TTR("Find Next"), KEY_F3), SEARCH_FIND_NEXT);
- search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_previous", TTR("Find Previous"), KEY_MASK_SHIFT|KEY_F3), SEARCH_FIND_PREV);
- search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/replace", TTR("Replace.."), KEY_MASK_CMD|KEY_R), SEARCH_REPLACE);
+ search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/find_previous", TTR("Find Previous"), KEY_MASK_SHIFT | KEY_F3), SEARCH_FIND_PREV);
+ search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/replace", TTR("Replace.."), KEY_MASK_CMD | KEY_R), SEARCH_REPLACE);
search_menu->get_popup()->add_separator();
//search_menu->get_popup()->add_item("Locate Symbol..",SEARCH_LOCATE_SYMBOL,KEY_MASK_CMD|KEY_K);
- search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/goto_line", TTR("Goto Line.."), KEY_MASK_CMD|KEY_L), SEARCH_GOTO_LINE);
- search_menu->get_popup()->connect("id_pressed", this,"_menu_option");
-
+ search_menu->get_popup()->add_shortcut(ED_SHORTCUT("script_editor/goto_line", TTR("Goto Line.."), KEY_MASK_CMD | KEY_L), SEARCH_GOTO_LINE);
+ search_menu->get_popup()->connect("id_pressed", this, "_menu_option");
goto_line_dialog = memnew(GotoLineDialog);
add_child(goto_line_dialog);
- shader_editor = memnew( ShaderTextEditor );
+ shader_editor = memnew(ShaderTextEditor);
add_child(shader_editor);
shader_editor->set_v_size_flags(SIZE_EXPAND_FILL);
-
- shader_editor->connect("script_changed", this,"apply_shaders");
- EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed");
+ shader_editor->connect("script_changed", this, "apply_shaders");
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_editor_settings_changed");
_editor_settings_changed();
}
-
void ShaderEditorPlugin::edit(Object *p_object) {
- Shader* s = p_object->cast_to<Shader>();
+ Shader *s = p_object->cast_to<Shader>();
shader_editor->edit(s);
-
}
bool ShaderEditorPlugin::handles(Object *p_object) const {
bool handles = true;
- Shader *shader=p_object->cast_to<Shader>();
+ Shader *shader = p_object->cast_to<Shader>();
/*
if (!shader || shader->cast_to<ShaderGraph>()) // Dont handle ShaderGraph's
handles = false;
*/
- return shader!=NULL;
+ return shader != NULL;
}
void ShaderEditorPlugin::make_visible(bool p_visible) {
@@ -532,9 +489,7 @@ void ShaderEditorPlugin::make_visible(bool p_visible) {
if (shader_editor->is_visible_in_tree())
editor->hide_bottom_panel();
shader_editor->apply_shaders();
-
}
-
}
void ShaderEditorPlugin::selected_notify() {
@@ -547,7 +502,7 @@ Dictionary ShaderEditorPlugin::get_state() const {
return shader_editor->get_state();
}
-void ShaderEditorPlugin::set_state(const Dictionary& p_state) {
+void ShaderEditorPlugin::set_state(const Dictionary &p_state) {
shader_editor->set_state(p_state);
}
@@ -568,17 +523,12 @@ void ShaderEditorPlugin::apply_changes() {
ShaderEditorPlugin::ShaderEditorPlugin(EditorNode *p_node) {
+ editor = p_node;
+ shader_editor = memnew(ShaderEditor);
- editor=p_node;
- shader_editor = memnew( ShaderEditor );
-
- shader_editor->set_custom_minimum_size(Size2(0,300));
- button=editor->add_bottom_panel_item("Shader",shader_editor);
-
+ shader_editor->set_custom_minimum_size(Size2(0, 300));
+ button = editor->add_bottom_panel_item("Shader", shader_editor);
}
-
ShaderEditorPlugin::~ShaderEditorPlugin() {
}
-
-
diff --git a/editor/plugins/shader_editor_plugin.h b/editor/plugins/shader_editor_plugin.h
index 703913e431..4a56c14ecb 100644
--- a/editor/plugins/shader_editor_plugin.h
+++ b/editor/plugins/shader_editor_plugin.h
@@ -31,41 +31,36 @@
#include "editor/code_editor.h"
#include "editor/editor_plugin.h"
+#include "scene/gui/menu_button.h"
#include "scene/gui/tab_container.h"
#include "scene/gui/text_edit.h"
-#include "scene/gui/menu_button.h"
#include "scene/main/timer.h"
#include "scene/resources/shader.h"
#include "servers/visual/shader_language.h"
class ShaderTextEditor : public CodeTextEditor {
- GDCLASS( ShaderTextEditor, CodeTextEditor );
+ GDCLASS(ShaderTextEditor, CodeTextEditor);
Ref<Shader> shader;
protected:
-
static void _bind_methods();
virtual void _load_theme_settings();
- virtual void _code_complete_script(const String& p_code, List<String>* r_options);
+ virtual void _code_complete_script(const String &p_code, List<String> *r_options);
public:
-
virtual void _validate_script();
-
Ref<Shader> get_edited_shader() const;
- void set_edited_shader(const Ref<Shader>& p_shader);
+ void set_edited_shader(const Ref<Shader> &p_shader);
ShaderTextEditor();
-
};
-
class ShaderEditor : public VBoxContainer {
- GDCLASS(ShaderEditor, VBoxContainer );
+ GDCLASS(ShaderEditor, VBoxContainer);
enum {
@@ -92,32 +87,29 @@ class ShaderEditor : public VBoxContainer {
GotoLineDialog *goto_line_dialog;
ConfirmationDialog *erase_tab_confirm;
-
ShaderTextEditor *shader_editor;
-
void _menu_option(int p_optin);
void _params_changed();
mutable Ref<Shader> shader;
-
void _editor_settings_changed();
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void apply_shaders();
void ensure_select_current();
- void edit(const Ref<Shader>& p_shader);
+ void edit(const Ref<Shader> &p_shader);
Dictionary get_state() const;
- void set_state(const Dictionary& p_state);
+ void set_state(const Dictionary &p_state);
void clear();
- virtual Size2 get_minimum_size() const { return Size2(0,200); }
+ virtual Size2 get_minimum_size() const { return Size2(0, 200); }
void save_external_data();
ShaderEditor();
@@ -125,7 +117,7 @@ public:
class ShaderEditorPlugin : public EditorPlugin {
- GDCLASS( ShaderEditorPlugin, EditorPlugin );
+ GDCLASS(ShaderEditorPlugin, EditorPlugin);
bool _2d;
ShaderEditor *shader_editor;
@@ -133,7 +125,6 @@ class ShaderEditorPlugin : public EditorPlugin {
Button *button;
public:
-
virtual String get_name() const { return "Shader"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -142,7 +133,7 @@ public:
virtual void selected_notify();
Dictionary get_state() const;
- virtual void set_state(const Dictionary& p_state);
+ virtual void set_state(const Dictionary &p_state);
virtual void clear();
virtual void save_external_data();
@@ -150,7 +141,6 @@ public:
ShaderEditorPlugin(EditorNode *p_node);
~ShaderEditorPlugin();
-
};
#endif
diff --git a/editor/plugins/shader_graph_editor_plugin.cpp b/editor/plugins/shader_graph_editor_plugin.cpp
index dac63b4a9f..d55c133dc9 100644
--- a/editor/plugins/shader_graph_editor_plugin.cpp
+++ b/editor/plugins/shader_graph_editor_plugin.cpp
@@ -30,12 +30,12 @@
#if 0
+#include "canvas_item_editor_plugin.h"
+#include "os/keyboard.h"
#include "scene/gui/check_box.h"
#include "scene/gui/menu_button.h"
#include "scene/gui/panel.h"
#include "spatial_editor_plugin.h"
-#include "os/keyboard.h"
-#include "canvas_item_editor_plugin.h"
void GraphColorRampEdit::_gui_input(const InputEvent& p_event) {
@@ -2943,6 +2943,4 @@ ShaderGraphEditorPlugin::~ShaderGraphEditorPlugin()
{
}
-
-
#endif
diff --git a/editor/plugins/shader_graph_editor_plugin.h b/editor/plugins/shader_graph_editor_plugin.h
index 5143722242..e5c59f82f4 100644
--- a/editor/plugins/shader_graph_editor_plugin.h
+++ b/editor/plugins/shader_graph_editor_plugin.h
@@ -29,15 +29,14 @@
#ifndef SHADER_GRAPH_EDITOR_PLUGIN_H
#define SHADER_GRAPH_EDITOR_PLUGIN_H
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/resources/shader.h"
-#include "scene/gui/tree.h"
+#include "editor/editor_plugin.h"
+#include "editor/property_editor.h"
#include "scene/gui/button.h"
#include "scene/gui/graph_edit.h"
#include "scene/gui/popup.h"
-#include "editor/property_editor.h"
+#include "scene/gui/tree.h"
+#include "scene/resources/shader.h"
#include "scene/resources/shader_graph.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
diff --git a/editor/plugins/spatial_editor_plugin.cpp b/editor/plugins/spatial_editor_plugin.cpp
index 8a7969c71b..fcfb20bd7d 100644
--- a/editor/plugins/spatial_editor_plugin.cpp
+++ b/editor/plugins/spatial_editor_plugin.cpp
@@ -28,35 +28,32 @@
/*************************************************************************/
#include "spatial_editor_plugin.h"
-#include "print_string.h"
-#include "os/keyboard.h"
-#include "scene/3d/visual_instance.h"
-#include "scene/3d/camera.h"
#include "camera_matrix.h"
-#include "sort.h"
+#include "editor/animation_editor.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
-#include "scene/resources/surface_tool.h"
+#include "editor/plugins/animation_player_editor_plugin.h"
#include "editor/spatial_editor_gizmos.h"
#include "global_config.h"
-#include "editor/plugins/animation_player_editor_plugin.h"
-#include "editor/animation_editor.h"
+#include "os/keyboard.h"
+#include "print_string.h"
+#include "scene/3d/camera.h"
+#include "scene/3d/visual_instance.h"
+#include "scene/resources/surface_tool.h"
+#include "sort.h"
#define DISTANCE_DEFAULT 4
-
#define GIZMO_ARROW_SIZE 0.3
#define GIZMO_RING_HALF_WIDTH 0.1
//#define GIZMO_SCALE_DEFAULT 0.28
#define GIZMO_SCALE_DEFAULT 0.15
-
void SpatialEditorViewport::_update_camera() {
if (orthogonal) {
//camera->set_orthogonal(size.width*cursor.distance,get_znear(),get_zfar());
camera->set_orthogonal(2 * cursor.distance, 0.1, 8192);
- }
- else
+ } else
camera->set_perspective(get_fov(), get_znear(), get_zfar());
Transform camera_transform;
@@ -83,7 +80,7 @@ String SpatialEditorGizmo::get_handle_name(int p_idx) const {
return "";
}
-Variant SpatialEditorGizmo::get_handle_value(int p_idx) const{
+Variant SpatialEditorGizmo::get_handle_value(int p_idx) const {
if (get_script_instance() && get_script_instance()->has_method("get_handle_value"))
return get_script_instance()->call("get_handle_value", p_idx);
@@ -91,49 +88,46 @@ Variant SpatialEditorGizmo::get_handle_value(int p_idx) const{
return Variant();
}
-void SpatialEditorGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point) {
+void SpatialEditorGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
if (get_script_instance() && get_script_instance()->has_method("set_handle"))
get_script_instance()->call("set_handle", p_idx, p_camera, p_point);
}
-void SpatialEditorGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void SpatialEditorGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
if (get_script_instance() && get_script_instance()->has_method("commit_handle"))
get_script_instance()->call("commit_handle", p_idx, p_restore, p_cancel);
}
-bool SpatialEditorGizmo::intersect_frustum(const Camera *p_camera,const Vector<Plane> &p_frustum) {
+bool SpatialEditorGizmo::intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum) {
return false;
}
-bool SpatialEditorGizmo::intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3& r_pos, Vector3& r_normal,int *r_gizmo_handle,bool p_sec_first) {
+bool SpatialEditorGizmo::intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle, bool p_sec_first) {
return false;
}
-SpatialEditorGizmo::SpatialEditorGizmo(){
+SpatialEditorGizmo::SpatialEditorGizmo() {
- selected=false;
+ selected = false;
}
-
-
int SpatialEditorViewport::get_selected_count() const {
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- Map<Node*,Object*> &selection = editor_selection->get_selection();
-
- int count=0;
+ int count = 0;
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->key()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
@@ -143,36 +137,30 @@ int SpatialEditorViewport::get_selected_count() const {
return count;
}
-
-
float SpatialEditorViewport::get_znear() const {
float val = spatial_editor->get_znear();
- if (val<0.001)
- val=0.001;
+ if (val < 0.001)
+ val = 0.001;
return val;
}
-float SpatialEditorViewport::get_zfar() const{
+float SpatialEditorViewport::get_zfar() const {
float val = spatial_editor->get_zfar();
- if (val<0.001)
- val=0.001;
+ if (val < 0.001)
+ val = 0.001;
return val;
-
}
-float SpatialEditorViewport::get_fov() const{
+float SpatialEditorViewport::get_fov() const {
float val = spatial_editor->get_fov();
- if (val<0.001)
- val=0.001;
- if (val>89)
- val=89;
+ if (val < 0.001)
+ val = 0.001;
+ if (val > 89)
+ val = 89;
return val;
-
}
-
-
Transform SpatialEditorViewport::_get_camera_transform() const {
return camera->get_global_transform();
@@ -183,29 +171,24 @@ Vector3 SpatialEditorViewport::_get_camera_pos() const {
return _get_camera_transform().origin;
}
-Point2 SpatialEditorViewport::_point_to_screen(const Vector3& p_point) {
+Point2 SpatialEditorViewport::_point_to_screen(const Vector3 &p_point) {
return camera->unproject_position(p_point);
-
}
-Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2& p_pos) const {
+Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2 &p_pos) const {
return camera->project_ray_origin(p_pos);
}
-
Vector3 SpatialEditorViewport::_get_camera_normal() const {
return -_get_camera_transform().basis.get_axis(2);
}
-Vector3 SpatialEditorViewport::_get_ray(const Vector2& p_pos) {
-
+Vector3 SpatialEditorViewport::_get_ray(const Vector2 &p_pos) {
return camera->project_ray_normal(p_pos);
-
-
}
/*
void SpatialEditorViewport::_clear_id(Spatial *p_node) {
@@ -221,9 +204,7 @@ void SpatialEditorViewport::_clear_selected() {
editor_selection->clear();
}
-
-
-void SpatialEditorViewport::_select_clicked(bool p_append,bool p_single) {
+void SpatialEditorViewport::_select_clicked(bool p_append, bool p_single) {
if (!clicked)
return;
@@ -232,18 +213,14 @@ void SpatialEditorViewport::_select_clicked(bool p_append,bool p_single) {
if (!obj)
return;
-
Spatial *sp = obj->cast_to<Spatial>();
if (!sp)
return;
- _select(sp, clicked_wants_append,true);
+ _select(sp, clicked_wants_append, true);
}
-
-
-void SpatialEditorViewport::_select(Spatial *p_node, bool p_append,bool p_single) {
-
+void SpatialEditorViewport::_select(Spatial *p_node, bool p_append, bool p_single) {
if (!p_append) {
@@ -261,34 +238,32 @@ void SpatialEditorViewport::_select(Spatial *p_node, bool p_append,bool p_single
editor_selection->add_node(p_node);
}
-
}
-
}
-ObjectID SpatialEditorViewport::_select_ray(const Point2& p_pos, bool p_append,bool &r_includes_current,int *r_gizmo_handle,bool p_alt_select) {
+ObjectID SpatialEditorViewport::_select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle, bool p_alt_select) {
if (r_gizmo_handle)
- *r_gizmo_handle=-1;
+ *r_gizmo_handle = -1;
- Vector3 ray=_get_ray(p_pos);
- Vector3 pos=_get_ray_pos(p_pos);
+ Vector3 ray = _get_ray(p_pos);
+ Vector3 pos = _get_ray_pos(p_pos);
- Vector<ObjectID> instances=VisualServer::get_singleton()->instances_cull_ray(pos,ray,get_tree()->get_root()->get_world()->get_scenario() );
+ Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
Set<Ref<SpatialEditorGizmo> > found_gizmos;
- ObjectID closest=0;
- Spatial *item=NULL;
- float closest_dist=1e20;
- int selected_handle=-1;
+ ObjectID closest = 0;
+ Spatial *item = NULL;
+ float closest_dist = 1e20;
+ int selected_handle = -1;
- for (int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
- Object *obj=ObjectDB::get_instance(instances[i]);
+ Object *obj = ObjectDB::get_instance(instances[i]);
if (!obj)
continue;
- Spatial *spat=obj->cast_to<Spatial>();
+ Spatial *spat = obj->cast_to<Spatial>();
if (!spat)
continue;
@@ -305,62 +280,58 @@ ObjectID SpatialEditorViewport::_select_ray(const Point2& p_pos, bool p_append,b
Vector3 point;
Vector3 normal;
- int handle=-1;
- bool inters = seg->intersect_ray(camera,p_pos,point,normal,NULL,p_alt_select);
+ int handle = -1;
+ bool inters = seg->intersect_ray(camera, p_pos, point, normal, NULL, p_alt_select);
if (!inters)
continue;
float dist = pos.distance_to(point);
- if (dist<0)
+ if (dist < 0)
continue;
if (dist < closest_dist) {
- closest=instances[i];
- closest_dist=dist;
- selected_handle=handle;
- item=spat;
+ closest = instances[i];
+ closest_dist = dist;
+ selected_handle = handle;
+ item = spat;
}
- // if (editor_selection->is_selected(spat))
- // r_includes_current=true;
-
+ // if (editor_selection->is_selected(spat))
+ // r_includes_current=true;
}
-
if (!item)
return 0;
- if (!editor_selection->is_selected(item) || (r_gizmo_handle && selected_handle>=0)) {
+ if (!editor_selection->is_selected(item) || (r_gizmo_handle && selected_handle >= 0)) {
if (r_gizmo_handle)
- *r_gizmo_handle=selected_handle;
-
+ *r_gizmo_handle = selected_handle;
}
return closest;
-
}
-void SpatialEditorViewport::_find_items_at_pos(const Point2& p_pos,bool &r_includes_current,Vector<_RayResult> &results,bool p_alt_select) {
+void SpatialEditorViewport::_find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select) {
- Vector3 ray=_get_ray(p_pos);
- Vector3 pos=_get_ray_pos(p_pos);
+ Vector3 ray = _get_ray(p_pos);
+ Vector3 pos = _get_ray_pos(p_pos);
- Vector<ObjectID> instances=VisualServer::get_singleton()->instances_cull_ray(pos,ray,get_tree()->get_root()->get_world()->get_scenario() );
+ Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(pos, ray, get_tree()->get_root()->get_world()->get_scenario());
Set<Ref<SpatialEditorGizmo> > found_gizmos;
- r_includes_current=false;
+ r_includes_current = false;
- for (int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
- Object *obj=ObjectDB::get_instance(instances[i]);
+ Object *obj = ObjectDB::get_instance(instances[i]);
if (!obj)
continue;
- Spatial *spat=obj->cast_to<Spatial>();
+ Spatial *spat = obj->cast_to<Spatial>();
if (!spat)
continue;
@@ -377,112 +348,100 @@ void SpatialEditorViewport::_find_items_at_pos(const Point2& p_pos,bool &r_inclu
Vector3 point;
Vector3 normal;
- int handle=-1;
- bool inters = seg->intersect_ray(camera,p_pos,point,normal,NULL,p_alt_select);
+ int handle = -1;
+ bool inters = seg->intersect_ray(camera, p_pos, point, normal, NULL, p_alt_select);
if (!inters)
continue;
float dist = pos.distance_to(point);
- if (dist<0)
+ if (dist < 0)
continue;
-
-
if (editor_selection->is_selected(spat))
- r_includes_current=true;
+ r_includes_current = true;
_RayResult res;
- res.item=spat;
- res.depth=dist;
- res.handle=handle;
+ res.item = spat;
+ res.depth = dist;
+ res.handle = handle;
results.push_back(res);
}
-
if (results.empty())
return;
results.sort();
}
-
-Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3& p_pos) {
-
+Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3 &p_pos) {
CameraMatrix cm;
- cm.set_perspective(get_fov(),get_size().aspect(),get_znear(),get_zfar());
- float screen_w,screen_h;
- cm.get_viewport_size(screen_w,screen_h);
+ cm.set_perspective(get_fov(), get_size().aspect(), get_znear(), get_zfar());
+ float screen_w, screen_h;
+ cm.get_viewport_size(screen_w, screen_h);
Transform camera_transform;
- camera_transform.translate( cursor.pos );
- camera_transform.basis.rotate(Vector3(1,0,0),-cursor.x_rot);
- camera_transform.basis.rotate(Vector3(0,1,0),-cursor.y_rot);
- camera_transform.translate(0,0,cursor.distance);
-
- return camera_transform.xform(Vector3( ((p_pos.x/get_size().width)*2.0-1.0)*screen_w, ((1.0-(p_pos.y/get_size().height))*2.0-1.0)*screen_h,-get_znear()));
+ camera_transform.translate(cursor.pos);
+ camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
+ camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
+ camera_transform.translate(0, 0, cursor.distance);
+ return camera_transform.xform(Vector3(((p_pos.x / get_size().width) * 2.0 - 1.0) * screen_w, ((1.0 - (p_pos.y / get_size().height)) * 2.0 - 1.0) * screen_h, -get_znear()));
}
-
void SpatialEditorViewport::_select_region() {
- if (cursor.region_begin==cursor.region_end)
+ if (cursor.region_begin == cursor.region_end)
return; //nothing really
- Vector3 box[4]={
+ Vector3 box[4] = {
Vector3(
- MIN( cursor.region_begin.x, cursor.region_end.x),
- MIN( cursor.region_begin.y, cursor.region_end.y),
- 0
- ),
+ MIN(cursor.region_begin.x, cursor.region_end.x),
+ MIN(cursor.region_begin.y, cursor.region_end.y),
+ 0),
Vector3(
- MAX( cursor.region_begin.x, cursor.region_end.x),
- MIN( cursor.region_begin.y, cursor.region_end.y),
- 0
- ),
+ MAX(cursor.region_begin.x, cursor.region_end.x),
+ MIN(cursor.region_begin.y, cursor.region_end.y),
+ 0),
Vector3(
- MAX( cursor.region_begin.x, cursor.region_end.x),
- MAX( cursor.region_begin.y, cursor.region_end.y),
- 0
- ),
+ MAX(cursor.region_begin.x, cursor.region_end.x),
+ MAX(cursor.region_begin.y, cursor.region_end.y),
+ 0),
Vector3(
- MIN( cursor.region_begin.x, cursor.region_end.x),
- MAX( cursor.region_begin.y, cursor.region_end.y),
- 0
- )
+ MIN(cursor.region_begin.x, cursor.region_end.x),
+ MAX(cursor.region_begin.y, cursor.region_end.y),
+ 0)
};
Vector<Plane> frustum;
- Vector3 cam_pos=_get_camera_pos();
+ Vector3 cam_pos = _get_camera_pos();
Set<Ref<SpatialEditorGizmo> > found_gizmos;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- Vector3 a=_get_screen_to_space(box[i]);
- Vector3 b=_get_screen_to_space(box[(i+1)%4]);
- frustum.push_back( Plane(a,b,cam_pos) );
+ Vector3 a = _get_screen_to_space(box[i]);
+ Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
+ frustum.push_back(Plane(a, b, cam_pos));
}
- Plane near( cam_pos, -_get_camera_normal() );
- near.d-=get_znear();
-
- frustum.push_back( near );
+ Plane near(cam_pos, -_get_camera_normal());
+ near.d -= get_znear();
- Plane far=-near;
- far.d+=500.0;
+ frustum.push_back(near);
- frustum.push_back( far );
+ Plane far = -near;
+ far.d += 500.0;
- Vector<ObjectID> instances=VisualServer::get_singleton()->instances_cull_convex(frustum,get_tree()->get_root()->get_world()->get_scenario());
+ frustum.push_back(far);
+ Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_convex(frustum, get_tree()->get_root()->get_world()->get_scenario());
- for (int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
- Object *obj=ObjectDB::get_instance(instances[i]);
+ Object *obj = ObjectDB::get_instance(instances[i]);
if (!obj)
continue;
Spatial *sp = obj->cast_to<Spatial>();
@@ -497,46 +456,44 @@ void SpatialEditorViewport::_select_region() {
if (found_gizmos.has(seg))
continue;
- if (seg->intersect_frustum(camera,frustum))
- _select(sp,true,false);
+ if (seg->intersect_frustum(camera, frustum))
+ _select(sp, true, false);
}
-
}
void SpatialEditorViewport::_update_name() {
- String ortho = orthogonal?TTR("Orthogonal"):TTR("Perspective");
+ String ortho = orthogonal ? TTR("Orthogonal") : TTR("Perspective");
- if (name!="")
- view_menu->set_text("[ "+name+" "+ortho+" ]");
+ if (name != "")
+ view_menu->set_text("[ " + name + " " + ortho + " ]");
else
- view_menu->set_text("[ "+ortho+" ]");
+ view_menu->set_text("[ " + ortho + " ]");
}
+void SpatialEditorViewport::_compute_edit(const Point2 &p_point) {
-void SpatialEditorViewport::_compute_edit(const Point2& p_point) {
-
- _edit.click_ray=_get_ray( Vector2( p_point.x, p_point.y ) );
- _edit.click_ray_pos=_get_ray_pos( Vector2( p_point.x, p_point.y ) );
- _edit.plane=TRANSFORM_VIEW;
+ _edit.click_ray = _get_ray(Vector2(p_point.x, p_point.y));
+ _edit.click_ray_pos = _get_ray_pos(Vector2(p_point.x, p_point.y));
+ _edit.plane = TRANSFORM_VIEW;
spatial_editor->update_transform_gizmo();
- _edit.center=spatial_editor->get_gizmo_transform().origin;
+ _edit.center = spatial_editor->get_gizmo_transform().origin;
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
//Vector3 center;
//int nc=0;
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
- se->original=se->sp->get_global_transform();
+ se->original = se->sp->get_global_transform();
//center+=se->original.origin;
//nc++;
}
@@ -547,9 +504,9 @@ void SpatialEditorViewport::_compute_edit(const Point2& p_point) {
*/
}
-static int _get_key_modifier(const String& p_property) {
+static int _get_key_modifier(const String &p_property) {
- switch(EditorSettings::get_singleton()->get(p_property).operator int()) {
+ switch (EditorSettings::get_singleton()->get(p_property).operator int()) {
case 0: return 0;
case 1: return KEY_SHIFT;
@@ -560,181 +517,164 @@ static int _get_key_modifier(const String& p_property) {
return 0;
}
-bool SpatialEditorViewport::_gizmo_select(const Vector2& p_screenpos,bool p_hilite_only) {
+bool SpatialEditorViewport::_gizmo_select(const Vector2 &p_screenpos, bool p_hilite_only) {
if (!spatial_editor->is_gizmo_visible())
return false;
- if (get_selected_count()==0) {
+ if (get_selected_count() == 0) {
if (p_hilite_only)
spatial_editor->select_gizmo_hilight_axis(-1);
return false;
}
-
- Vector3 ray_pos=_get_ray_pos( Vector2( p_screenpos.x, p_screenpos.y ) );
- Vector3 ray=_get_ray( Vector2( p_screenpos.x, p_screenpos.y ) );
+ Vector3 ray_pos = _get_ray_pos(Vector2(p_screenpos.x, p_screenpos.y));
+ Vector3 ray = _get_ray(Vector2(p_screenpos.x, p_screenpos.y));
Transform gt = spatial_editor->get_gizmo_transform();
- float gs=gizmo_scale;
+ float gs = gizmo_scale;
- if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) {
+ if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
- int col_axis=-1;
- float col_d=1e20;
+ int col_axis = -1;
+ float col_d = 1e20;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 grabber_pos = gt.origin+gt.basis.get_axis(i)*gs;
- float grabber_radius = gs*GIZMO_ARROW_SIZE;
+ Vector3 grabber_pos = gt.origin + gt.basis.get_axis(i) * gs;
+ float grabber_radius = gs * GIZMO_ARROW_SIZE;
Vector3 r;
- if (Geometry::segment_intersects_sphere(ray_pos,ray_pos+ray*10000.0,grabber_pos,grabber_radius,&r)) {
+ if (Geometry::segment_intersects_sphere(ray_pos, ray_pos + ray * 10000.0, grabber_pos, grabber_radius, &r)) {
float d = r.distance_to(ray_pos);
- if (d<col_d) {
- col_d=d;
- col_axis=i;
+ if (d < col_d) {
+ col_d = d;
+ col_axis = i;
}
}
}
- if (col_axis!=-1) {
-
+ if (col_axis != -1) {
if (p_hilite_only) {
spatial_editor->select_gizmo_hilight_axis(col_axis);
-
} else {
//handle rotate
- _edit.mode=TRANSFORM_TRANSLATE;
- _compute_edit(Point2(p_screenpos.x,p_screenpos.y));
- _edit.plane=TransformPlane(TRANSFORM_X_AXIS+col_axis);
+ _edit.mode = TRANSFORM_TRANSLATE;
+ _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
+ _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
}
return true;
-
-
}
-
}
+ if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
- if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) {
+ int col_axis = -1;
+ float col_d = 1e20;
- int col_axis=-1;
- float col_d=1e20;
+ for (int i = 0; i < 3; i++) {
- for(int i=0;i<3;i++) {
-
- Plane plane(gt.origin,gt.basis.get_axis(i).normalized());
+ Plane plane(gt.origin, gt.basis.get_axis(i).normalized());
Vector3 r;
- if (!plane.intersects_ray(ray_pos,ray,&r))
+ if (!plane.intersects_ray(ray_pos, ray, &r))
continue;
float dist = r.distance_to(gt.origin);
-
-
- if (dist > gs*(1-GIZMO_RING_HALF_WIDTH) && dist < gs *(1+GIZMO_RING_HALF_WIDTH)) {
+ if (dist > gs * (1 - GIZMO_RING_HALF_WIDTH) && dist < gs * (1 + GIZMO_RING_HALF_WIDTH)) {
float d = ray_pos.distance_to(r);
- if (d<col_d) {
- col_d=d;
- col_axis=i;
+ if (d < col_d) {
+ col_d = d;
+ col_axis = i;
}
}
}
- if (col_axis!=-1) {
+ if (col_axis != -1) {
if (p_hilite_only) {
- spatial_editor->select_gizmo_hilight_axis(col_axis+3);
+ spatial_editor->select_gizmo_hilight_axis(col_axis + 3);
} else {
//handle rotate
- _edit.mode=TRANSFORM_ROTATE;
- _compute_edit(Point2(p_screenpos.x,p_screenpos.y));
- _edit.plane=TransformPlane(TRANSFORM_X_AXIS+col_axis);
+ _edit.mode = TRANSFORM_ROTATE;
+ _compute_edit(Point2(p_screenpos.x, p_screenpos.y));
+ _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
}
return true;
}
}
-
if (p_hilite_only)
spatial_editor->select_gizmo_hilight_axis(-1);
return false;
-
}
-
void SpatialEditorViewport::_smouseenter() {
- if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
- surface->grab_focus();
+ if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
+ surface->grab_focus();
}
void SpatialEditorViewport::_list_select(InputEventMouseButton b) {
- _find_items_at_pos(Vector2( b.x, b.y ),clicked_includes_current,selection_results,b.mod.shift);
+ _find_items_at_pos(Vector2(b.x, b.y), clicked_includes_current, selection_results, b.mod.shift);
- Node *scene=editor->get_edited_scene();
+ Node *scene = editor->get_edited_scene();
- for(int i=0;i<selection_results.size();i++) {
- Spatial *item=selection_results[i].item;
- if (item!=scene && item->get_owner()!=scene && !scene->is_editable_instance(item->get_owner())) {
+ for (int i = 0; i < selection_results.size(); i++) {
+ Spatial *item = selection_results[i].item;
+ if (item != scene && item->get_owner() != scene && !scene->is_editable_instance(item->get_owner())) {
//invalid result
selection_results.remove(i);
i--;
}
-
}
-
- clicked_wants_append=b.mod.shift;
+ clicked_wants_append = b.mod.shift;
if (selection_results.size() == 1) {
- clicked=selection_results[0].item->get_instance_ID();
+ clicked = selection_results[0].item->get_instance_ID();
selection_results.clear();
if (clicked) {
- _select_clicked(clicked_wants_append,true);
- clicked=0;
+ _select_clicked(clicked_wants_append, true);
+ clicked = 0;
}
} else if (!selection_results.empty()) {
NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
- StringName root_name = root_path.get_name(root_path.get_name_count()-1);
+ StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
for (int i = 0; i < selection_results.size(); i++) {
- Spatial *spat=selection_results[i].item;
+ Spatial *spat = selection_results[i].item;
Ref<Texture> icon;
if (spat->has_meta("_editor_icon"))
- icon=spat->get_meta("_editor_icon");
+ icon = spat->get_meta("_editor_icon");
else
- icon=get_icon( has_icon(spat->get_class(),"EditorIcons")?spat->get_class():String("Object"),"EditorIcons");
+ icon = get_icon(has_icon(spat->get_class(), "EditorIcons") ? spat->get_class() : String("Object"), "EditorIcons");
- String node_path="/"+root_name+"/"+root_path.rel_path_to(spat->get_path());
+ String node_path = "/" + root_name + "/" + root_path.rel_path_to(spat->get_path());
selection_menu->add_item(spat->get_name());
- selection_menu->set_item_icon(i, icon );
+ selection_menu->set_item_icon(i, icon);
selection_menu->set_item_metadata(i, node_path);
- selection_menu->set_item_tooltip(i,String(spat->get_name())+
- "\nType: "+spat->get_class()+"\nPath: "+node_path);
+ selection_menu->set_item_tooltip(i, String(spat->get_name()) +
+ "\nType: " + spat->get_class() + "\nPath: " + node_path);
}
- selection_menu->set_global_pos(Vector2( b.global_x, b.global_y ));
+ selection_menu->set_global_pos(Vector2(b.global_x, b.global_y));
selection_menu->popup();
selection_menu->call_deferred("grab_click_focus");
selection_menu->set_invalidate_click_until_motion();
-
-
-
}
}
void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
@@ -742,39 +682,37 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (previewing)
return; //do NONE
-
{
EditorNode *en = editor;
EditorPluginList *over_plugin_list = en->get_editor_plugins_over();
if (!over_plugin_list->empty()) {
- bool discard = over_plugin_list->forward_spatial_gui_input(camera,p_event);
+ bool discard = over_plugin_list->forward_spatial_gui_input(camera, p_event);
if (discard)
return;
}
}
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &b=p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
- switch(b.button_index) {
+ switch (b.button_index) {
case BUTTON_WHEEL_UP: {
-
- cursor.distance/=1.08;
- if (cursor.distance<0.001)
- cursor.distance=0.001;
+ cursor.distance /= 1.08;
+ if (cursor.distance < 0.001)
+ cursor.distance = 0.001;
} break;
case BUTTON_WHEEL_DOWN: {
- if (cursor.distance<0.001)
- cursor.distance=0.001;
- cursor.distance*=1.08;
+ if (cursor.distance < 0.001)
+ cursor.distance = 0.001;
+ cursor.distance *= 1.08;
} break;
case BUTTON_RIGHT: {
@@ -783,81 +721,76 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (b.pressed && _edit.gizmo.is_valid()) {
//restore
- _edit.gizmo->commit_handle(_edit.gizmo_handle,_edit.gizmo_initial_value,true);
- _edit.gizmo=Ref<SpatialEditorGizmo>();
+ _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, true);
+ _edit.gizmo = Ref<SpatialEditorGizmo>();
}
- if (_edit.mode==TRANSFORM_NONE && b.pressed) {
-
- Plane cursor_plane(cursor.cursor_pos,_get_camera_normal());
+ if (_edit.mode == TRANSFORM_NONE && b.pressed) {
- Vector3 ray_origin = _get_ray_pos(Vector2(b.x,b.y));
- Vector3 ray_dir = _get_ray(Vector2(b.x,b.y));
+ Plane cursor_plane(cursor.cursor_pos, _get_camera_normal());
+ Vector3 ray_origin = _get_ray_pos(Vector2(b.x, b.y));
+ Vector3 ray_dir = _get_ray(Vector2(b.x, b.y));
//gizmo modify
if (b.mod.control) {
- Vector<ObjectID> instances=VisualServer::get_singleton()->instances_cull_ray(ray_origin,ray_dir,get_tree()->get_root()->get_world()->get_scenario() );
-
- Plane p(ray_origin,_get_camera_normal());
+ Vector<ObjectID> instances = VisualServer::get_singleton()->instances_cull_ray(ray_origin, ray_dir, get_tree()->get_root()->get_world()->get_scenario());
- float min_d=1e10;
- bool found=false;
+ Plane p(ray_origin, _get_camera_normal());
- for (int i=0;i<instances.size();i++) {
+ float min_d = 1e10;
+ bool found = false;
+ for (int i = 0; i < instances.size(); i++) {
- Object *obj=ObjectDB::get_instance(instances[i]);
+ Object *obj = ObjectDB::get_instance(instances[i]);
if (!obj)
continue;
- VisualInstance *vi=obj->cast_to<VisualInstance>();
+ VisualInstance *vi = obj->cast_to<VisualInstance>();
if (!vi)
continue;
//optimize by checking AABB (although should pre sort by distance)
- Rect3 aabb = vi->get_global_transform().xform(vi->get_aabb());
- if (p.distance_to(aabb.get_support(-ray_dir))>min_d)
+ Rect3 aabb = vi->get_global_transform().xform(vi->get_aabb());
+ if (p.distance_to(aabb.get_support(-ray_dir)) > min_d)
continue;
PoolVector<Face3> faces = vi->get_faces(VisualInstance::FACES_SOLID);
int c = faces.size();
- if (c>0) {
+ if (c > 0) {
PoolVector<Face3>::Read r = faces.read();
- for(int j=0;j<c;j++) {
+ for (int j = 0; j < c; j++) {
Vector3 inters;
- if (r[j].intersects_ray(ray_origin,ray_dir,&inters)) {
+ if (r[j].intersects_ray(ray_origin, ray_dir, &inters)) {
float d = p.distance_to(inters);
- if (d<0)
+ if (d < 0)
continue;
- if (d<min_d) {
- min_d=d;
- found=true;
+ if (d < min_d) {
+ min_d = d;
+ found = true;
}
}
-
}
}
-
}
if (found) {
//cursor.cursor_pos=ray_origin+ray_dir*min_d;
//VisualServer::get_singleton()->instance_set_transform(cursor_instance,Transform(Matrix3(),cursor.cursor_pos));
-
}
} else {
Vector3 new_pos;
- if (cursor_plane.intersects_ray(ray_origin,ray_dir,&new_pos)) {
+ if (cursor_plane.intersects_ray(ray_origin, ray_dir, &new_pos)) {
//cursor.cursor_pos=new_pos;
//VisualServer::get_singleton()->instance_set_transform(cursor_instance,Transform(Matrix3(),cursor.cursor_pos));
@@ -871,68 +804,65 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
_list_select(b);
return;
-
}
}
- if (_edit.mode!=TRANSFORM_NONE && b.pressed) {
+ if (_edit.mode != TRANSFORM_NONE && b.pressed) {
//cancel motion
- _edit.mode=TRANSFORM_NONE;
+ _edit.mode = TRANSFORM_NONE;
//_validate_selection();
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
- sp->set_global_transform( se->original );
-
+ sp->set_global_transform(se->original);
}
surface->update();
//VisualServer::get_singleton()->poly_clear(indicators);
- set_message(TTR("Transform Aborted."),3);
+ set_message(TTR("Transform Aborted."), 3);
}
} break;
case BUTTON_MIDDLE: {
- if (b.pressed && _edit.mode!=TRANSFORM_NONE) {
+ if (b.pressed && _edit.mode != TRANSFORM_NONE) {
- switch(_edit.plane ) {
+ switch (_edit.plane) {
case TRANSFORM_VIEW: {
- _edit.plane=TRANSFORM_X_AXIS;
- set_message(TTR("X-Axis Transform."),2);
- name="";
+ _edit.plane = TRANSFORM_X_AXIS;
+ set_message(TTR("X-Axis Transform."), 2);
+ name = "";
_update_name();
} break;
case TRANSFORM_X_AXIS: {
- _edit.plane=TRANSFORM_Y_AXIS;
- set_message(TTR("Y-Axis Transform."),2);
+ _edit.plane = TRANSFORM_Y_AXIS;
+ set_message(TTR("Y-Axis Transform."), 2);
} break;
case TRANSFORM_Y_AXIS: {
- _edit.plane=TRANSFORM_Z_AXIS;
- set_message(TTR("Z-Axis Transform."),2);
+ _edit.plane = TRANSFORM_Z_AXIS;
+ set_message(TTR("Z-Axis Transform."), 2);
} break;
case TRANSFORM_Z_AXIS: {
- _edit.plane=TRANSFORM_VIEW;
- set_message(TTR("View Plane Transform."),2);
+ _edit.plane = TRANSFORM_VIEW;
+ set_message(TTR("View Plane Transform."), 2);
} break;
}
-
}
} break;
case BUTTON_LEFT: {
@@ -940,108 +870,93 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (b.pressed) {
NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation_scheme").operator int();
- if ( (nav_scheme==NAVIGATION_MAYA || nav_scheme==NAVIGATION_MODO) && b.mod.alt) {
+ if ((nav_scheme == NAVIGATION_MAYA || nav_scheme == NAVIGATION_MODO) && b.mod.alt) {
break;
}
- if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_LIST_SELECT) {
+ if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_LIST_SELECT) {
_list_select(b);
break;
}
- _edit.mouse_pos=Point2(b.x,b.y);
- _edit.snap=false;
- _edit.mode=TRANSFORM_NONE;
-
+ _edit.mouse_pos = Point2(b.x, b.y);
+ _edit.snap = false;
+ _edit.mode = TRANSFORM_NONE;
//gizmo has priority over everything
- bool can_select_gizmos=true;
+ bool can_select_gizmos = true;
{
int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
- can_select_gizmos = view_menu->get_popup()->is_item_checked( idx );
+ can_select_gizmos = view_menu->get_popup()->is_item_checked(idx);
}
-
-
if (can_select_gizmos && spatial_editor->get_selected()) {
Ref<SpatialEditorGizmo> seg = spatial_editor->get_selected()->get_gizmo();
if (seg.is_valid()) {
- int handle=-1;
+ int handle = -1;
Vector3 point;
Vector3 normal;
- bool inters = seg->intersect_ray(camera,_edit.mouse_pos,point,normal,&handle,b.mod.shift);
- if (inters && handle!=-1) {
+ bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, b.mod.shift);
+ if (inters && handle != -1) {
- _edit.gizmo=seg;
- _edit.gizmo_handle=handle;
+ _edit.gizmo = seg;
+ _edit.gizmo_handle = handle;
//_edit.gizmo_initial_pos=seg->get_handle_pos(gizmo_handle);
- _edit.gizmo_initial_value=seg->get_handle_value(handle);
+ _edit.gizmo_initial_value = seg->get_handle_value(handle);
break;
-
}
}
}
-
-
if (_gizmo_select(_edit.mouse_pos))
break;
- clicked=0;
- clicked_includes_current=false;
-
+ clicked = 0;
+ clicked_includes_current = false;
- if ((spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT && b.mod.control) || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) {
+ if ((spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT && b.mod.control) || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE) {
/* HANDLE ROTATION */
- if (get_selected_count()==0)
+ if (get_selected_count() == 0)
break; //bye
//handle rotate
- _edit.mode=TRANSFORM_ROTATE;
- _compute_edit(Point2(b.x,b.y));
+ _edit.mode = TRANSFORM_ROTATE;
+ _compute_edit(Point2(b.x, b.y));
break;
-
}
- if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) {
+ if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE) {
- if (get_selected_count()==0)
+ if (get_selected_count() == 0)
break; //bye
//handle rotate
- _edit.mode=TRANSFORM_TRANSLATE;
- _compute_edit(Point2(b.x,b.y));
+ _edit.mode = TRANSFORM_TRANSLATE;
+ _compute_edit(Point2(b.x, b.y));
break;
-
-
}
+ if (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SCALE) {
- if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SCALE) {
-
- if (get_selected_count()==0)
+ if (get_selected_count() == 0)
break; //bye
//handle rotate
- _edit.mode=TRANSFORM_SCALE;
- _compute_edit(Point2(b.x,b.y));
+ _edit.mode = TRANSFORM_SCALE;
+ _compute_edit(Point2(b.x, b.y));
break;
-
-
}
-
-
// todo scale
- int gizmo_handle=-1;
+ int gizmo_handle = -1;
- clicked=_select_ray(Vector2( b.x, b.y ),b.mod.shift,clicked_includes_current,&gizmo_handle,b.mod.shift);
+ clicked = _select_ray(Vector2(b.x, b.y), b.mod.shift, clicked_includes_current, &gizmo_handle, b.mod.shift);
//clicking is always deferred to either move or release
- clicked_wants_append=b.mod.shift;
+ clicked_wants_append = b.mod.shift;
if (!clicked) {
@@ -1049,131 +964,118 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
_clear_selected();
//default to regionselect
- cursor.region_select=true;
- cursor.region_begin=Point2(b.x,b.y);
- cursor.region_end=Point2(b.x,b.y);
+ cursor.region_select = true;
+ cursor.region_begin = Point2(b.x, b.y);
+ cursor.region_end = Point2(b.x, b.y);
}
- if (clicked && gizmo_handle>=0) {
+ if (clicked && gizmo_handle >= 0) {
- Object *obj=ObjectDB::get_instance(clicked);
+ Object *obj = ObjectDB::get_instance(clicked);
if (obj) {
Spatial *spa = obj->cast_to<Spatial>();
if (spa) {
- Ref<SpatialEditorGizmo> seg=spa->get_gizmo();
+ Ref<SpatialEditorGizmo> seg = spa->get_gizmo();
if (seg.is_valid()) {
- _edit.gizmo=seg;
- _edit.gizmo_handle=gizmo_handle;
+ _edit.gizmo = seg;
+ _edit.gizmo_handle = gizmo_handle;
//_edit.gizmo_initial_pos=seg->get_handle_pos(gizmo_handle);
- _edit.gizmo_initial_value=seg->get_handle_value(gizmo_handle);
+ _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle);
//print_line("GIZMO: "+itos(gizmo_handle)+" FROMPOS: "+_edit.orig_gizmo_pos);
break;
-
}
}
-
}
//_compute_edit(Point2(b.x,b.y)); //in case a motion happens..
}
-
-
surface->update();
} else {
-
if (_edit.gizmo.is_valid()) {
- _edit.gizmo->commit_handle(_edit.gizmo_handle,_edit.gizmo_initial_value,false);
- _edit.gizmo=Ref<SpatialEditorGizmo>();
+ _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_initial_value, false);
+ _edit.gizmo = Ref<SpatialEditorGizmo>();
break;
}
if (clicked) {
- _select_clicked(clicked_wants_append,true);
+ _select_clicked(clicked_wants_append, true);
//clickd processing was deferred
- clicked=0;
-
-
+ clicked = 0;
}
if (cursor.region_select) {
_select_region();
- cursor.region_select=false;
+ cursor.region_select = false;
surface->update();
}
+ if (_edit.mode != TRANSFORM_NONE) {
- if (_edit.mode!=TRANSFORM_NONE) {
-
-
- static const char* _transform_name[4]={"None","Rotate","Translate","Scale"};
+ static const char *_transform_name[4] = { "None", "Rotate", "Translate", "Scale" };
undo_redo->create_action(_transform_name[_edit.mode]);
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
- undo_redo->add_do_method(sp,"set_global_transform",sp->get_global_transform());
- undo_redo->add_undo_method(sp,"set_global_transform",se->original);
+ undo_redo->add_do_method(sp, "set_global_transform", sp->get_global_transform());
+ undo_redo->add_undo_method(sp, "set_global_transform", se->original);
}
undo_redo->commit_action();
- _edit.mode=TRANSFORM_NONE;
+ _edit.mode = TRANSFORM_NONE;
//VisualServer::get_singleton()->poly_clear(indicators);
set_message("");
}
-
surface->update();
}
} break;
}
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &m=p_event.mouse_motion;
- _edit.mouse_pos=Point2(p_event.mouse_motion.x,p_event.mouse_motion.y);
+ const InputEventMouseMotion &m = p_event.mouse_motion;
+ _edit.mouse_pos = Point2(p_event.mouse_motion.x, p_event.mouse_motion.y);
if (spatial_editor->get_selected()) {
-
Ref<SpatialEditorGizmo> seg = spatial_editor->get_selected()->get_gizmo();
if (seg.is_valid()) {
- int selected_handle=-1;
+ int selected_handle = -1;
- int handle=-1;
+ int handle = -1;
Vector3 point;
Vector3 normal;
- bool inters = seg->intersect_ray(camera,_edit.mouse_pos,point,normal,&handle,false);
- if (inters && handle!=-1) {
-
- selected_handle=handle;
+ bool inters = seg->intersect_ray(camera, _edit.mouse_pos, point, normal, &handle, false);
+ if (inters && handle != -1) {
+ selected_handle = handle;
}
- if (selected_handle!=spatial_editor->get_over_gizmo_handle()) {
+ if (selected_handle != spatial_editor->get_over_gizmo_handle()) {
spatial_editor->set_over_gizmo_handle(selected_handle);
spatial_editor->get_selected()->update_gizmo();
- if (selected_handle!=-1)
+ if (selected_handle != -1)
spatial_editor->select_gizmo_hilight_axis(-1);
}
}
}
- if (spatial_editor->get_over_gizmo_handle()==-1 && !(m.button_mask&1) && !_edit.gizmo.is_valid()) {
-
- _gizmo_select(_edit.mouse_pos,true);
+ if (spatial_editor->get_over_gizmo_handle() == -1 && !(m.button_mask & 1) && !_edit.gizmo.is_valid()) {
+ _gizmo_select(_edit.mouse_pos, true);
}
NavigationScheme nav_scheme = (NavigationScheme)EditorSettings::get_singleton()->get("editors/3d/navigation_scheme").operator int();
@@ -1181,12 +1083,12 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (_edit.gizmo.is_valid()) {
- _edit.gizmo->set_handle(_edit.gizmo_handle,camera,Vector2(m.x,m.y));
+ _edit.gizmo->set_handle(_edit.gizmo_handle, camera, Vector2(m.x, m.y));
Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle);
String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle);
- set_message(n+": "+String(v));
+ set_message(n + ": " + String(v));
- } else if (m.button_mask&1) {
+ } else if (m.button_mask & 1) {
if (nav_scheme == NAVIGATION_MAYA && m.mod.alt) {
nav_mode = NAVIGATION_ORBIT;
@@ -1201,84 +1103,77 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (!clicked_includes_current) {
- _select_clicked(clicked_wants_append,true);
+ _select_clicked(clicked_wants_append, true);
//clickd processing was deferred
}
-
_compute_edit(_edit.mouse_pos);
- clicked=0;
-
- _edit.mode=TRANSFORM_TRANSLATE;
+ clicked = 0;
+ _edit.mode = TRANSFORM_TRANSLATE;
}
if (cursor.region_select && nav_mode == NAVIGATION_NONE) {
- cursor.region_end=Point2(m.x,m.y);
+ cursor.region_end = Point2(m.x, m.y);
surface->update();
return;
}
- if (_edit.mode==TRANSFORM_NONE && nav_mode == NAVIGATION_NONE)
+ if (_edit.mode == TRANSFORM_NONE && nav_mode == NAVIGATION_NONE)
break;
+ Vector3 ray_pos = _get_ray_pos(Vector2(m.x, m.y));
+ Vector3 ray = _get_ray(Vector2(m.x, m.y));
- Vector3 ray_pos=_get_ray_pos( Vector2( m.x, m.y ) );
- Vector3 ray=_get_ray( Vector2( m.x, m.y ) );
-
-
- switch(_edit.mode) {
+ switch (_edit.mode) {
case TRANSFORM_SCALE: {
-
- Plane plane=Plane(_edit.center,_get_camera_normal());
-
+ Plane plane = Plane(_edit.center, _get_camera_normal());
Vector3 intersection;
- if (!plane.intersects_ray(ray_pos,ray,&intersection))
+ if (!plane.intersects_ray(ray_pos, ray, &intersection))
break;
Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
break;
float center_click_dist = click.distance_to(_edit.center);
float center_inters_dist = intersection.distance_to(_edit.center);
- if (center_click_dist==0)
+ if (center_click_dist == 0)
break;
- float scale = (center_inters_dist / center_click_dist)*100.0;
+ float scale = (center_inters_dist / center_click_dist) * 100.0;
if (_edit.snap || spatial_editor->is_snap_enabled()) {
- scale = Math::stepify(scale,spatial_editor->get_scale_snap());
+ scale = Math::stepify(scale, spatial_editor->get_scale_snap());
}
- set_message(vformat(TTR("Scaling to %s%%."),String::num(scale,1)));
- scale/=100.0;
+ set_message(vformat(TTR("Scaling to %s%%."), String::num(scale, 1)));
+ scale /= 100.0;
Transform r;
- r.basis.scale(Vector3(scale,scale,scale));
+ r.basis.scale(Vector3(scale, scale, scale));
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
+ Transform original = se->original;
- Transform original=se->original;
-
- Transform base=Transform( Basis(), _edit.center);
- Transform t=base * (r * (base.inverse() * original));
+ Transform base = Transform(Basis(), _edit.center);
+ Transform t = base * (r * (base.inverse() * original));
sp->set_global_transform(t);
}
@@ -1289,44 +1184,43 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
case TRANSFORM_TRANSLATE: {
-
Vector3 motion_mask;
Plane plane;
- switch( _edit.plane ) {
+ switch (_edit.plane) {
case TRANSFORM_VIEW:
- motion_mask=Vector3(0,0,0);
- plane=Plane(_edit.center,_get_camera_normal());
- break;
+ motion_mask = Vector3(0, 0, 0);
+ plane = Plane(_edit.center, _get_camera_normal());
+ break;
case TRANSFORM_X_AXIS:
- motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(0);
- plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
- break;
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(0);
+ plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
+ break;
case TRANSFORM_Y_AXIS:
- motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(1);
- plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
- break;
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(1);
+ plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
+ break;
case TRANSFORM_Z_AXIS:
- motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(2);
- plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
- break;
+ motion_mask = spatial_editor->get_gizmo_transform().basis.get_axis(2);
+ plane = Plane(_edit.center, motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
+ break;
}
Vector3 intersection;
- if (!plane.intersects_ray(ray_pos,ray,&intersection))
+ if (!plane.intersects_ray(ray_pos, ray, &intersection))
break;
Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
break;
//_validate_selection();
- Vector3 motion = intersection-click;
- if (motion_mask!=Vector3()) {
- motion=motion_mask.dot(motion)*motion_mask;
+ Vector3 motion = intersection - click;
+ if (motion_mask != Vector3()) {
+ motion = motion_mask.dot(motion) * motion_mask;
}
- float snap=0;
+ float snap = 0;
if (_edit.snap || spatial_editor->is_snap_enabled()) {
@@ -1336,98 +1230,92 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
//set_message("Translating: "+motion);
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp) {
continue;
}
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se) {
continue;
}
- Transform t=se->original;
- t.origin+=motion;
+ Transform t = se->original;
+ t.origin += motion;
sp->set_global_transform(t);
}
} break;
case TRANSFORM_ROTATE: {
-
Plane plane;
- switch( _edit.plane ) {
+ switch (_edit.plane) {
case TRANSFORM_VIEW:
- plane=Plane(_edit.center,_get_camera_normal());
- break;
+ plane = Plane(_edit.center, _get_camera_normal());
+ break;
case TRANSFORM_X_AXIS:
- plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(0));
- break;
+ plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(0));
+ break;
case TRANSFORM_Y_AXIS:
- plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(1));
- break;
+ plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(1));
+ break;
case TRANSFORM_Z_AXIS:
- plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(2));
- break;
+ plane = Plane(_edit.center, spatial_editor->get_gizmo_transform().basis.get_axis(2));
+ break;
}
Vector3 intersection;
- if (!plane.intersects_ray(ray_pos,ray,&intersection))
+ if (!plane.intersects_ray(ray_pos, ray, &intersection))
break;
Vector3 click;
- if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
+ if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click))
break;
+ Vector3 y_axis = (click - _edit.center).normalized();
+ Vector3 x_axis = plane.normal.cross(y_axis).normalized();
- Vector3 y_axis=(click-_edit.center).normalized();
- Vector3 x_axis=plane.normal.cross(y_axis).normalized();
-
- float angle=Math::atan2( x_axis.dot(intersection-_edit.center), y_axis.dot(intersection-_edit.center) );
+ float angle = Math::atan2(x_axis.dot(intersection - _edit.center), y_axis.dot(intersection - _edit.center));
if (_edit.snap || spatial_editor->is_snap_enabled()) {
float snap = spatial_editor->get_rotate_snap();
if (snap) {
- angle=Math::rad2deg(angle)+snap*0.5; //else it wont reach +180
- angle-=Math::fmod(angle,snap);
- set_message(vformat(TTR("Rotating %s degrees."),rtos(angle)));
- angle=Math::deg2rad(angle);
+ angle = Math::rad2deg(angle) + snap * 0.5; //else it wont reach +180
+ angle -= Math::fmod(angle, snap);
+ set_message(vformat(TTR("Rotating %s degrees."), rtos(angle)));
+ angle = Math::deg2rad(angle);
} else
- set_message(vformat(TTR("Rotating %s degrees."),rtos(Math::rad2deg(angle))));
+ set_message(vformat(TTR("Rotating %s degrees."), rtos(Math::rad2deg(angle))));
} else {
- set_message(vformat(TTR("Rotating %s degrees."),rtos(Math::rad2deg(angle))));
+ set_message(vformat(TTR("Rotating %s degrees."), rtos(Math::rad2deg(angle))));
}
-
-
-
Transform r;
- r.basis.rotate(plane.normal,angle);
+ r.basis.rotate(plane.normal, angle);
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
+ Transform original = se->original;
- Transform original=se->original;
-
- Transform base=Transform( Basis(), _edit.center);
- Transform t=base * r * base.inverse() * original;
+ Transform base = Transform(Basis(), _edit.center);
+ Transform t = base * r * base.inverse() * original;
sp->set_global_transform(t);
}
@@ -1446,30 +1334,29 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
VisualServer::get_singleton()->poly_add_primitive(indicators,points,empty,colors,empty);
*/
} break;
- default:{}
+ default: {}
}
-
}
- } else if (m.button_mask&2) {
+ } else if (m.button_mask & 2) {
if (nav_scheme == NAVIGATION_MAYA && m.mod.alt) {
nav_mode = NAVIGATION_ZOOM;
}
- } else if (m.button_mask&4) {
+ } else if (m.button_mask & 4) {
if (nav_scheme == NAVIGATION_GODOT) {
int mod = 0;
if (m.mod.shift)
- mod=KEY_SHIFT;
+ mod = KEY_SHIFT;
if (m.mod.alt)
- mod=KEY_ALT;
+ mod = KEY_ALT;
if (m.mod.control)
- mod=KEY_CONTROL;
+ mod = KEY_CONTROL;
if (m.mod.meta)
- mod=KEY_META;
+ mod = KEY_META;
if (mod == _get_key_modifier("editors/3d/pan_modifier"))
nav_mode = NAVIGATION_PAN;
@@ -1483,19 +1370,19 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
nav_mode = NAVIGATION_PAN;
}
- } else if (EditorSettings::get_singleton()->get("editors/3d/emulate_3_button_mouse")) {
+ } else if (EditorSettings::get_singleton()->get("editors/3d/emulate_3_button_mouse")) {
// Handle trackpad (no external mouse) use case
int mod = 0;
if (m.mod.shift)
- mod=KEY_SHIFT;
+ mod = KEY_SHIFT;
if (m.mod.alt)
- mod=KEY_ALT;
+ mod = KEY_ALT;
if (m.mod.control)
- mod=KEY_CONTROL;
+ mod = KEY_CONTROL;
if (m.mod.meta)
- mod=KEY_META;
+ mod = KEY_META;
- if(mod){
+ if (mod) {
if (mod == _get_key_modifier("editors/3d/pan_modifier"))
nav_mode = NAVIGATION_PAN;
else if (mod == _get_key_modifier("editors/3d/zoom_modifier"))
@@ -1505,56 +1392,55 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
}
}
- switch(nav_mode) {
- case NAVIGATION_PAN:{
+ switch (nav_mode) {
+ case NAVIGATION_PAN: {
- real_t pan_speed = 1/150.0;
+ real_t pan_speed = 1 / 150.0;
int pan_speed_modifier = 10;
- if (nav_scheme==NAVIGATION_MAYA && m.mod.shift)
+ if (nav_scheme == NAVIGATION_MAYA && m.mod.shift)
pan_speed *= pan_speed_modifier;
Transform camera_transform;
camera_transform.translate(cursor.pos);
- camera_transform.basis.rotate(Vector3(1,0,0),-cursor.x_rot);
- camera_transform.basis.rotate(Vector3(0,1,0),-cursor.y_rot);
- Vector3 translation(-m.relative_x*pan_speed,m.relative_y*pan_speed,0);
- translation*=cursor.distance/DISTANCE_DEFAULT;
+ camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
+ camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
+ Vector3 translation(-m.relative_x * pan_speed, m.relative_y * pan_speed, 0);
+ translation *= cursor.distance / DISTANCE_DEFAULT;
camera_transform.translate(translation);
- cursor.pos=camera_transform.origin;
+ cursor.pos = camera_transform.origin;
} break;
case NAVIGATION_ZOOM: {
- real_t zoom_speed = 1/80.0;
+ real_t zoom_speed = 1 / 80.0;
int zoom_speed_modifier = 10;
- if (nav_scheme==NAVIGATION_MAYA && m.mod.shift)
+ if (nav_scheme == NAVIGATION_MAYA && m.mod.shift)
zoom_speed *= zoom_speed_modifier;
NavigationZoomStyle zoom_style = (NavigationZoomStyle)EditorSettings::get_singleton()->get("editors/3d/zoom_style").operator int();
if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
- if ( m.relative_x > 0)
- cursor.distance*=1-m.relative_x*zoom_speed;
+ if (m.relative_x > 0)
+ cursor.distance *= 1 - m.relative_x * zoom_speed;
else if (m.relative_x < 0)
- cursor.distance/=1+m.relative_x*zoom_speed;
- }
- else {
- if ( m.relative_y > 0)
- cursor.distance*=1+m.relative_y*zoom_speed;
+ cursor.distance /= 1 + m.relative_x * zoom_speed;
+ } else {
+ if (m.relative_y > 0)
+ cursor.distance *= 1 + m.relative_y * zoom_speed;
else if (m.relative_y < 0)
- cursor.distance/=1-m.relative_y*zoom_speed;
+ cursor.distance /= 1 - m.relative_y * zoom_speed;
}
} break;
case NAVIGATION_ORBIT: {
- cursor.x_rot+=m.relative_y/80.0;
- cursor.y_rot+=m.relative_x/80.0;
- if (cursor.x_rot>Math_PI/2.0)
- cursor.x_rot=Math_PI/2.0;
- if (cursor.x_rot<-Math_PI/2.0)
- cursor.x_rot=-Math_PI/2.0;
- name="";
+ cursor.x_rot += m.relative_y / 80.0;
+ cursor.y_rot += m.relative_x / 80.0;
+ if (cursor.x_rot > Math_PI / 2.0)
+ cursor.x_rot = Math_PI / 2.0;
+ if (cursor.x_rot < -Math_PI / 2.0)
+ cursor.x_rot = -Math_PI / 2.0;
+ name = "";
_update_name();
} break;
@@ -1568,57 +1454,57 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (ED_IS_SHORTCUT("spatial_editor/snap", p_event)) {
if (_edit.mode != TRANSFORM_NONE) {
- _edit.snap=true;
+ _edit.snap = true;
}
}
if (ED_IS_SHORTCUT("spatial_editor/bottom_view", p_event)) {
cursor.y_rot = 0;
- cursor.x_rot = -Math_PI/2.0;
- set_message(TTR("Bottom View."),2);
+ cursor.x_rot = -Math_PI / 2.0;
+ set_message(TTR("Bottom View."), 2);
name = TTR("Bottom");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/top_view", p_event)) {
cursor.y_rot = 0;
- cursor.x_rot = Math_PI/2.0;
- set_message(TTR("Top View."),2);
+ cursor.x_rot = Math_PI / 2.0;
+ set_message(TTR("Top View."), 2);
name = TTR("Top");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/rear_view", p_event)) {
cursor.x_rot = 0;
cursor.y_rot = Math_PI;
- set_message(TTR("Rear View."),2);
+ set_message(TTR("Rear View."), 2);
name = TTR("Rear");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/front_view", p_event)) {
cursor.x_rot = 0;
- cursor.y_rot=0;
- set_message(TTR("Front View."),2);
- name=TTR("Front");
+ cursor.y_rot = 0;
+ set_message(TTR("Front View."), 2);
+ name = TTR("Front");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/left_view", p_event)) {
- cursor.x_rot=0;
- cursor.y_rot = Math_PI/2.0;
- set_message(TTR("Left View."),2);
+ cursor.x_rot = 0;
+ cursor.y_rot = Math_PI / 2.0;
+ set_message(TTR("Left View."), 2);
name = TTR("Left");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/right_view", p_event)) {
- cursor.x_rot=0;
- cursor.y_rot = -Math_PI/2.0;
- set_message(TTR("Right View."),2);
+ cursor.x_rot = 0;
+ cursor.y_rot = -Math_PI / 2.0;
+ set_message(TTR("Right View."), 2);
name = TTR("Right");
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/switch_perspective_orthogonal", p_event)) {
- _menu_option(orthogonal?VIEW_PERSPECTIVE:VIEW_ORTHOGONAL);
+ _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
_update_name();
}
if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", p_event)) {
- if (!get_selected_count() || _edit.mode!=TRANSFORM_NONE)
+ if (!get_selected_count() || _edit.mode != TRANSFORM_NONE)
break;
if (!AnimationPlayerEditor::singleton->get_key_editor()->has_keying()) {
@@ -1626,18 +1512,17 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
break;
}
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- emit_signal("transform_key_request",sp,"",sp->get_transform());
+ emit_signal("transform_key_request", sp, "", sp->get_transform());
}
-
set_message(TTR("Animation Key Inserted."));
}
@@ -1646,26 +1531,20 @@ void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
}
} break;
-
}
-
}
-void SpatialEditorViewport::set_message(String p_message,float p_time) {
-
- message=p_message;
- message_time=p_time;
+void SpatialEditorViewport::set_message(String p_message, float p_time) {
+ message = p_message;
+ message_time = p_time;
}
-
-
void SpatialEditorViewport::_notification(int p_what) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
-
- bool visible=is_visible_in_tree();
+ bool visible = is_visible_in_tree();
set_process(visible);
@@ -1675,14 +1554,12 @@ void SpatialEditorViewport::_notification(int p_what) {
call_deferred("update_transform_gizmo_view");
}
- if (p_what==NOTIFICATION_RESIZED) {
+ if (p_what == NOTIFICATION_RESIZED) {
call_deferred("update_transform_gizmo_view");
-
}
- if (p_what==NOTIFICATION_PROCESS) {
-
+ if (p_what == NOTIFICATION_PROCESS) {
//force editr camera
/*
@@ -1695,56 +1572,53 @@ void SpatialEditorViewport::_notification(int p_what) {
_update_camera();
- Map<Node*,Object*> &selection = editor_selection->get_selection();
+ Map<Node *, Object *> &selection = editor_selection->get_selection();
- bool changed=false;
- bool exist=false;
+ bool changed = false;
+ bool exist = false;
- for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
+ for (Map<Node *, Object *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->key()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
-
- VisualInstance *vi=sp->cast_to<VisualInstance>();
-
+ VisualInstance *vi = sp->cast_to<VisualInstance>();
if (se->aabb.has_no_surface()) {
- se->aabb=vi?vi->get_aabb():Rect3( Vector3(-0.2,-0.2,-0.2),Vector3(0.4,0.4,0.4));
+ se->aabb = vi ? vi->get_aabb() : Rect3(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
}
- Transform t=sp->get_global_transform();
+ Transform t = sp->get_global_transform();
t.translate(se->aabb.pos);
- t.basis.scale( se->aabb.size );
+ t.basis.scale(se->aabb.size);
- exist=true;
- if (se->last_xform==t)
+ exist = true;
+ if (se->last_xform == t)
continue;
- changed=true;
- se->last_xform=t;
- VisualServer::get_singleton()->instance_set_transform(se->sbox_instance,t);
-
+ changed = true;
+ se->last_xform = t;
+ VisualServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
}
if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
spatial_editor->update_transform_gizmo();
}
- if (message_time>0) {
+ if (message_time > 0) {
- if (message!=last_message) {
+ if (message != last_message) {
surface->update();
- last_message=message;
+ last_message = message;
}
- message_time-=get_fixed_process_delta_time();
- if (message_time<0)
+ message_time -= get_fixed_process_delta_time();
+ if (message_time < 0)
surface->update();
}
@@ -1756,12 +1630,11 @@ void SpatialEditorViewport::_notification(int p_what) {
int atlas_q2 = GlobalConfig::get_singleton()->get("rendering/shadow_atlas/quadrant_2_subdiv");
int atlas_q3 = GlobalConfig::get_singleton()->get("rendering/shadow_atlas/quadrant_3_subdiv");
-
viewport->set_shadow_atlas_size(shadowmap_size);
- viewport->set_shadow_atlas_quadrant_subdiv(0,Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
- viewport->set_shadow_atlas_quadrant_subdiv(1,Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
- viewport->set_shadow_atlas_quadrant_subdiv(2,Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
- viewport->set_shadow_atlas_quadrant_subdiv(3,Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
+ viewport->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q0));
+ viewport->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q1));
+ viewport->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q2));
+ viewport->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(atlas_q3));
//update msaa if changed
@@ -1770,164 +1643,145 @@ void SpatialEditorViewport::_notification(int p_what) {
bool hdr = GlobalConfig::get_singleton()->get("rendering/quality/hdr");
viewport->set_hdr(hdr);
-
-
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- surface->connect("draw",this,"_draw");
- surface->connect("gui_input",this,"_sinput");
- surface->connect("mouse_entered",this,"_smouseenter");
- preview_camera->set_icon(get_icon("Camera","EditorIcons"));
+ surface->connect("draw", this, "_draw");
+ surface->connect("gui_input", this, "_sinput");
+ surface->connect("mouse_entered", this, "_smouseenter");
+ preview_camera->set_icon(get_icon("Camera", "EditorIcons"));
_init_gizmo_instance(index);
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
+ if (p_what == NOTIFICATION_EXIT_TREE) {
_finish_gizmo_instances();
-
}
- if (p_what==NOTIFICATION_MOUSE_ENTER) {
-
-
+ if (p_what == NOTIFICATION_MOUSE_ENTER) {
}
-
- if (p_what==NOTIFICATION_DRAW) {
-
-
-
+ if (p_what == NOTIFICATION_DRAW) {
}
-
}
void SpatialEditorViewport::_draw() {
if (surface->has_focus()) {
Size2 size = surface->get_size();
- Rect2 r =Rect2(Point2(),size);
- get_stylebox("EditorFocus","EditorStyles")->draw(surface->get_canvas_item(),r);
+ Rect2 r = Rect2(Point2(), size);
+ get_stylebox("EditorFocus", "EditorStyles")->draw(surface->get_canvas_item(), r);
}
-
- RID ci=surface->get_canvas_item();
+ RID ci = surface->get_canvas_item();
if (cursor.region_select) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor.region_begin,cursor.region_end-cursor.region_begin),Color(0.7,0.7,1.0,0.3));
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin), Color(0.7, 0.7, 1.0, 0.3));
}
- if (message_time>0) {
- Ref<Font> font = get_font("font","Label");
- Point2 msgpos=Point2(5,get_size().y-20);
- font->draw(ci,msgpos+Point2(1,1),message,Color(0,0,0,0.8));
- font->draw(ci,msgpos+Point2(-1,-1),message,Color(0,0,0,0.8));
- font->draw(ci,msgpos,message,Color(1,1,1,1));
+ if (message_time > 0) {
+ Ref<Font> font = get_font("font", "Label");
+ Point2 msgpos = Point2(5, get_size().y - 20);
+ font->draw(ci, msgpos + Point2(1, 1), message, Color(0, 0, 0, 0.8));
+ font->draw(ci, msgpos + Point2(-1, -1), message, Color(0, 0, 0, 0.8));
+ font->draw(ci, msgpos, message, Color(1, 1, 1, 1));
}
-
- if (_edit.mode==TRANSFORM_ROTATE) {
+ if (_edit.mode == TRANSFORM_ROTATE) {
Point2 center = _point_to_screen(_edit.center);
- VisualServer::get_singleton()->canvas_item_add_line(ci,_edit.mouse_pos, center, Color(0.4,0.7,1.0,0.8));
-
-
+ VisualServer::get_singleton()->canvas_item_add_line(ci, _edit.mouse_pos, center, Color(0.4, 0.7, 1.0, 0.8));
}
if (previewing) {
-
- Size2 ss = Size2( GlobalConfig::get_singleton()->get("display/width"), GlobalConfig::get_singleton()->get("display/height") );
+ Size2 ss = Size2(GlobalConfig::get_singleton()->get("display/width"), GlobalConfig::get_singleton()->get("display/height"));
float aspect = ss.aspect();
Size2 s = get_size();
Rect2 draw_rect;
-
- switch(previewing->get_keep_aspect_mode()) {
+ switch (previewing->get_keep_aspect_mode()) {
case Camera::KEEP_WIDTH: {
- draw_rect.size = Size2(s.width,s.width/aspect);
- draw_rect.pos.x=0;
- draw_rect.pos.y=(s.height-draw_rect.size.y)*0.5;
+ draw_rect.size = Size2(s.width, s.width / aspect);
+ draw_rect.pos.x = 0;
+ draw_rect.pos.y = (s.height - draw_rect.size.y) * 0.5;
} break;
case Camera::KEEP_HEIGHT: {
- draw_rect.size = Size2(s.height*aspect,s.height);
- draw_rect.pos.y=0;
- draw_rect.pos.x=(s.width-draw_rect.size.x)*0.5;
+ draw_rect.size = Size2(s.height * aspect, s.height);
+ draw_rect.pos.y = 0;
+ draw_rect.pos.x = (s.width - draw_rect.size.x) * 0.5;
} break;
}
- draw_rect = Rect2(Vector2(),s).clip(draw_rect);
+ draw_rect = Rect2(Vector2(), s).clip(draw_rect);
- surface->draw_line(draw_rect.pos,draw_rect.pos+Vector2(draw_rect.size.x,0),Color(0.6,0.6,0.1,0.5),2.0);
- surface->draw_line(draw_rect.pos+Vector2(draw_rect.size.x,0),draw_rect.pos+draw_rect.size,Color(0.6,0.6,0.1,0.5),2.0);
- surface->draw_line(draw_rect.pos+draw_rect.size,draw_rect.pos+Vector2(0,draw_rect.size.y),Color(0.6,0.6,0.1,0.5),2.0);
- surface->draw_line(draw_rect.pos,draw_rect.pos+Vector2(0,draw_rect.size.y),Color(0.6,0.6,0.1,0.5),2.0);
+ surface->draw_line(draw_rect.pos, draw_rect.pos + Vector2(draw_rect.size.x, 0), Color(0.6, 0.6, 0.1, 0.5), 2.0);
+ surface->draw_line(draw_rect.pos + Vector2(draw_rect.size.x, 0), draw_rect.pos + draw_rect.size, Color(0.6, 0.6, 0.1, 0.5), 2.0);
+ surface->draw_line(draw_rect.pos + draw_rect.size, draw_rect.pos + Vector2(0, draw_rect.size.y), Color(0.6, 0.6, 0.1, 0.5), 2.0);
+ surface->draw_line(draw_rect.pos, draw_rect.pos + Vector2(0, draw_rect.size.y), Color(0.6, 0.6, 0.1, 0.5), 2.0);
}
-
}
-
void SpatialEditorViewport::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case VIEW_TOP: {
- cursor.x_rot=Math_PI/2.0;
- cursor.y_rot=0;
- name=TTR("Top");
+ cursor.x_rot = Math_PI / 2.0;
+ cursor.y_rot = 0;
+ name = TTR("Top");
_update_name();
} break;
case VIEW_BOTTOM: {
- cursor.x_rot=-Math_PI/2.0;
- cursor.y_rot=0;
- name=TTR("Bottom");
+ cursor.x_rot = -Math_PI / 2.0;
+ cursor.y_rot = 0;
+ name = TTR("Bottom");
_update_name();
} break;
case VIEW_LEFT: {
- cursor.y_rot=Math_PI/2.0;
- cursor.x_rot=0;
- name=TTR("Left");
+ cursor.y_rot = Math_PI / 2.0;
+ cursor.x_rot = 0;
+ name = TTR("Left");
_update_name();
} break;
case VIEW_RIGHT: {
- cursor.y_rot=-Math_PI/2.0;
- cursor.x_rot=0;
- name=TTR("Right");
+ cursor.y_rot = -Math_PI / 2.0;
+ cursor.x_rot = 0;
+ name = TTR("Right");
_update_name();
} break;
case VIEW_FRONT: {
- cursor.y_rot=0;
- cursor.x_rot=0;
- name=TTR("Front");
+ cursor.y_rot = 0;
+ cursor.x_rot = 0;
+ name = TTR("Front");
_update_name();
} break;
case VIEW_REAR: {
- cursor.y_rot=Math_PI;
- cursor.x_rot=0;
- name=TTR("Rear");
+ cursor.y_rot = Math_PI;
+ cursor.x_rot = 0;
+ name = TTR("Rear");
_update_name();
} break;
case VIEW_CENTER_TO_ORIGIN: {
- cursor.pos = Vector3(0,0,0);
+ cursor.pos = Vector3(0, 0, 0);
} break;
case VIEW_CENTER_TO_SELECTION: {
@@ -1942,32 +1796,32 @@ void SpatialEditorViewport::_menu_option(int p_option) {
Transform camera_transform = camera->get_global_transform();
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
undo_redo->create_action(TTR("Align with view"));
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform xform = camera_transform;
xform.scale_basis(sp->get_scale());
- undo_redo->add_do_method(sp,"set_global_transform",xform);
- undo_redo->add_undo_method(sp,"set_global_transform",sp->get_global_transform());
+ undo_redo->add_do_method(sp, "set_global_transform", xform);
+ undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
}
undo_redo->commit_action();
} break;
case VIEW_ENVIRONMENT: {
int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
- bool current = view_menu->get_popup()->is_item_checked( idx );
- current=!current;
+ bool current = view_menu->get_popup()->is_item_checked(idx);
+ current = !current;
if (current) {
camera->set_environment(RES());
@@ -1976,24 +1830,23 @@ void SpatialEditorViewport::_menu_option(int p_option) {
camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
}
- view_menu->get_popup()->set_item_checked( idx, current );
-
+ view_menu->get_popup()->set_item_checked(idx, current);
} break;
case VIEW_PERSPECTIVE: {
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false );
- orthogonal=false;
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
+ orthogonal = false;
call_deferred("update_transform_gizmo_view");
_update_name();
} break;
case VIEW_ORTHOGONAL: {
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true );
- orthogonal=true;
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
+ orthogonal = true;
call_deferred("update_transform_gizmo_view");
_update_name();
@@ -2001,30 +1854,27 @@ void SpatialEditorViewport::_menu_option(int p_option) {
case VIEW_AUDIO_LISTENER: {
int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
- bool current = view_menu->get_popup()->is_item_checked( idx );
- current=!current;
+ bool current = view_menu->get_popup()->is_item_checked(idx);
+ current = !current;
viewport->set_as_audio_listener(current);
- view_menu->get_popup()->set_item_checked( idx, current );
+ view_menu->get_popup()->set_item_checked(idx, current);
} break;
case VIEW_GIZMOS: {
int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
- bool current = view_menu->get_popup()->is_item_checked( idx );
- current=!current;
+ bool current = view_menu->get_popup()->is_item_checked(idx);
+ current = !current;
if (current)
- camera->set_cull_mask( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+index))|(1<<GIZMO_EDIT_LAYER)|(1<<GIZMO_GRID_LAYER) );
+ camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
else
- camera->set_cull_mask( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+index))|(1<<GIZMO_GRID_LAYER) );
- view_menu->get_popup()->set_item_checked( idx, current );
+ camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + index)) | (1 << GIZMO_GRID_LAYER));
+ view_menu->get_popup()->set_item_checked(idx, current);
} break;
-
}
-
}
-
void SpatialEditorViewport::_preview_exited_scene() {
preview_camera->set_pressed(false);
@@ -2032,52 +1882,46 @@ void SpatialEditorViewport::_preview_exited_scene() {
view_menu->show();
}
-
void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
- uint32_t layer=1<<(GIZMO_BASE_LAYER+p_idx);//|(1<<GIZMO_GRID_LAYER);
+ uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx); //|(1<<GIZMO_GRID_LAYER);
- for(int i=0;i<3;i++) {
- move_gizmo_instance[i]=VS::get_singleton()->instance_create();
- VS::get_singleton()->instance_set_base(move_gizmo_instance[i],spatial_editor->get_move_gizmo(i)->get_rid());
- VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i],get_tree()->get_root()->get_world()->get_scenario());
- VS::get_singleton()->instance_set_visible(move_gizmo_instance[i],false);
+ for (int i = 0; i < 3; i++) {
+ move_gizmo_instance[i] = VS::get_singleton()->instance_create();
+ VS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
+ VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
+ VS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
//VS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i],VS::INSTANCE_FLAG_DEPH_SCALE,true);
VS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
- VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i],layer);
+ VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
- rotate_gizmo_instance[i]=VS::get_singleton()->instance_create();
- VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i],spatial_editor->get_rotate_gizmo(i)->get_rid());
- VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i],get_tree()->get_root()->get_world()->get_scenario());
- VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i],false);
+ rotate_gizmo_instance[i] = VS::get_singleton()->instance_create();
+ VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
+ VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world()->get_scenario());
+ VS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
//VS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i],VS::INSTANCE_FLAG_DEPH_SCALE,true);
VS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
- VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i],layer);
+ VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
}
-
}
-
void SpatialEditorViewport::_finish_gizmo_instances() {
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
VS::get_singleton()->free(move_gizmo_instance[i]);
VS::get_singleton()->free(rotate_gizmo_instance[i]);
}
-
}
void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
-
ERR_FAIL_COND(p_activate && !preview);
ERR_FAIL_COND(!p_activate && !previewing);
if (!p_activate) {
- previewing->disconnect("tree_exited",this,"_preview_exited_scene");
- previewing=NULL;
- VS::get_singleton()->viewport_attach_camera( viewport->get_viewport_rid(), camera->get_camera() ); //restore
+ previewing->disconnect("tree_exited", this, "_preview_exited_scene");
+ previewing = NULL;
+ VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
if (!preview)
preview_camera->hide();
view_menu->show();
@@ -2085,12 +1929,11 @@ void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
} else {
- previewing=preview;
- previewing->connect("tree_exited",this,"_preview_exited_scene");
- VS::get_singleton()->viewport_attach_camera( viewport->get_viewport_rid(), preview->get_camera() ); //replace
+ previewing = preview;
+ previewing->connect("tree_exited", this, "_preview_exited_scene");
+ VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
view_menu->hide();
surface->update();
-
}
}
@@ -2099,11 +1942,11 @@ void SpatialEditorViewport::_selection_result_pressed(int p_result) {
if (selection_results.size() <= p_result)
return;
- clicked=selection_results[p_result].item->get_instance_ID();
+ clicked = selection_results[p_result].item->get_instance_ID();
if (clicked) {
- _select_clicked(clicked_wants_append,true);
- clicked=0;
+ _select_clicked(clicked_wants_append, true);
+ clicked = 0;
}
}
@@ -2114,9 +1957,9 @@ void SpatialEditorViewport::_selection_menu_hide() {
selection_menu->set_size(Vector2(0, 0));
}
-void SpatialEditorViewport::set_can_preview(Camera* p_preview) {
+void SpatialEditorViewport::set_can_preview(Camera *p_preview) {
- preview=p_preview;
+ preview = p_preview;
if (!preview_camera->is_pressed()) {
@@ -2135,42 +1978,39 @@ void SpatialEditorViewport::update_transform_gizmo_view() {
Transform xform = spatial_editor->get_gizmo_transform();
-
Transform camera_xform = camera->get_transform();
Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
- Plane p(camera_xform.origin,camz);
- float gizmo_d = Math::abs( p.distance_to(xform.origin ));
- float d0 = camera->unproject_position(camera_xform.origin+camz*gizmo_d).y;
- float d1 = camera->unproject_position(camera_xform.origin+camz*gizmo_d+camy).y;
- float dd = Math::abs(d0-d1);
- if (dd==0)
- dd=0.0001;
+ Plane p(camera_xform.origin, camz);
+ float gizmo_d = Math::abs(p.distance_to(xform.origin));
+ float d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
+ float d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
+ float dd = Math::abs(d0 - d1);
+ if (dd == 0)
+ dd = 0.0001;
float gsize = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_size");
- gizmo_scale=(gsize/Math::abs(dd));
- Vector3 scale = Vector3(1,1,1) * gizmo_scale;
+ gizmo_scale = (gsize / Math::abs(dd));
+ Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
xform.basis.scale(scale);
//xform.basis.scale(GIZMO_SCALE_DEFAULT*Vector3(1,1,1));
-
- for(int i=0;i<3;i++) {
- VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform );
- VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i],spatial_editor->is_gizmo_visible()&& (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) );
- VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform );
- VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i],spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) );
+ for (int i = 0; i < 3; i++) {
+ VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform);
+ VisualServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_MOVE));
+ VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform);
+ VisualServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode() == SpatialEditor::TOOL_MODE_ROTATE));
}
-
}
-void SpatialEditorViewport::set_state(const Dictionary& p_state) {
+void SpatialEditorViewport::set_state(const Dictionary &p_state) {
- cursor.pos=p_state["pos"];
- cursor.x_rot=p_state["x_rot"];
- cursor.y_rot=p_state["y_rot"];
- cursor.distance=p_state["distance"];
+ cursor.pos = p_state["pos"];
+ cursor.x_rot = p_state["x_rot"];
+ cursor.y_rot = p_state["y_rot"];
+ cursor.distance = p_state["distance"];
bool env = p_state["use_environment"];
bool orth = p_state["use_orthogonal"];
if (orth)
@@ -2184,15 +2024,15 @@ void SpatialEditorViewport::set_state(const Dictionary& p_state) {
int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
viewport->set_as_audio_listener(listener);
- view_menu->get_popup()->set_item_checked( idx, listener );
+ view_menu->get_popup()->set_item_checked(idx, listener);
}
if (p_state.has("previewing")) {
Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
if (pv && pv->cast_to<Camera>()) {
- previewing=pv->cast_to<Camera>();
- previewing->connect("tree_exited",this,"_preview_exited_scene");
- VS::get_singleton()->viewport_attach_camera( viewport->get_viewport_rid(), previewing->get_camera() ); //replace
+ previewing = pv->cast_to<Camera>();
+ previewing->connect("tree_exited", this, "_preview_exited_scene");
+ VS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
view_menu->hide();
surface->update();
preview_camera->set_pressed(true);
@@ -2204,127 +2044,121 @@ void SpatialEditorViewport::set_state(const Dictionary& p_state) {
Dictionary SpatialEditorViewport::get_state() const {
Dictionary d;
- d["pos"]=cursor.pos;
- d["x_rot"]=cursor.x_rot;
- d["y_rot"]=cursor.y_rot;
- d["distance"]=cursor.distance;
- d["use_environment"]=camera->get_environment().is_valid();
- d["use_orthogonal"]=camera->get_projection()==Camera::PROJECTION_ORTHOGONAL;
- d["listener"]=viewport->is_audio_listener();
+ d["pos"] = cursor.pos;
+ d["x_rot"] = cursor.x_rot;
+ d["y_rot"] = cursor.y_rot;
+ d["distance"] = cursor.distance;
+ d["use_environment"] = camera->get_environment().is_valid();
+ d["use_orthogonal"] = camera->get_projection() == Camera::PROJECTION_ORTHOGONAL;
+ d["listener"] = viewport->is_audio_listener();
if (previewing) {
- d["previewing"]=EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
+ d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
}
return d;
}
+void SpatialEditorViewport::_bind_methods() {
-void SpatialEditorViewport::_bind_methods(){
-
- ClassDB::bind_method(D_METHOD("_draw"),&SpatialEditorViewport::_draw);
- ClassDB::bind_method(D_METHOD("_smouseenter"),&SpatialEditorViewport::_smouseenter);
- ClassDB::bind_method(D_METHOD("_sinput"),&SpatialEditorViewport::_sinput);
- ClassDB::bind_method(D_METHOD("_menu_option"),&SpatialEditorViewport::_menu_option);
- ClassDB::bind_method(D_METHOD("_toggle_camera_preview"),&SpatialEditorViewport::_toggle_camera_preview);
- ClassDB::bind_method(D_METHOD("_preview_exited_scene"),&SpatialEditorViewport::_preview_exited_scene);
- ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"),&SpatialEditorViewport::update_transform_gizmo_view);
- ClassDB::bind_method(D_METHOD("_selection_result_pressed"),&SpatialEditorViewport::_selection_result_pressed);
- ClassDB::bind_method(D_METHOD("_selection_menu_hide"),&SpatialEditorViewport::_selection_menu_hide);
+ ClassDB::bind_method(D_METHOD("_draw"), &SpatialEditorViewport::_draw);
+ ClassDB::bind_method(D_METHOD("_smouseenter"), &SpatialEditorViewport::_smouseenter);
+ ClassDB::bind_method(D_METHOD("_sinput"), &SpatialEditorViewport::_sinput);
+ ClassDB::bind_method(D_METHOD("_menu_option"), &SpatialEditorViewport::_menu_option);
+ ClassDB::bind_method(D_METHOD("_toggle_camera_preview"), &SpatialEditorViewport::_toggle_camera_preview);
+ ClassDB::bind_method(D_METHOD("_preview_exited_scene"), &SpatialEditorViewport::_preview_exited_scene);
+ ClassDB::bind_method(D_METHOD("update_transform_gizmo_view"), &SpatialEditorViewport::update_transform_gizmo_view);
+ ClassDB::bind_method(D_METHOD("_selection_result_pressed"), &SpatialEditorViewport::_selection_result_pressed);
+ ClassDB::bind_method(D_METHOD("_selection_menu_hide"), &SpatialEditorViewport::_selection_menu_hide);
- ADD_SIGNAL( MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")) );
+ ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
}
-
void SpatialEditorViewport::reset() {
- orthogonal=false;
- message_time=0;
- message="";
- last_message="";
- name="";
+ orthogonal = false;
+ message_time = 0;
+ message = "";
+ last_message = "";
+ name = "";
- cursor.x_rot=0.5;
- cursor.y_rot=0.5;
- cursor.distance=4;
- cursor.region_select=false;
+ cursor.x_rot = 0.5;
+ cursor.y_rot = 0.5;
+ cursor.distance = 4;
+ cursor.region_select = false;
_update_name();
}
-
void SpatialEditorViewport::focus_selection() {
if (!get_selected_count())
return;
Vector3 center;
- int count=0;
+ int count = 0;
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
- center+=sp->get_global_transform().origin;
+ center += sp->get_global_transform().origin;
count++;
}
- if( count != 0 ) {
- center/=float(count);
+ if (count != 0) {
+ center /= float(count);
}
- cursor.pos=center;
+ cursor.pos = center;
}
-
SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
- _edit.mode=TRANSFORM_NONE;
- _edit.plane=TRANSFORM_VIEW;
- _edit.edited_gizmo=0;
- _edit.snap=1;
- _edit.gizmo_handle=0;
-
-
-
- index=p_index;
- editor=p_editor;
- editor_selection=editor->get_editor_selection();
- undo_redo=editor->get_undo_redo();
- clicked=0;
- clicked_includes_current=false;
- orthogonal=false;
- message_time=0;
-
- spatial_editor=p_spatial_editor;
- ViewportContainer *c=memnew(ViewportContainer);
+ _edit.mode = TRANSFORM_NONE;
+ _edit.plane = TRANSFORM_VIEW;
+ _edit.edited_gizmo = 0;
+ _edit.snap = 1;
+ _edit.gizmo_handle = 0;
+
+ index = p_index;
+ editor = p_editor;
+ editor_selection = editor->get_editor_selection();
+ undo_redo = editor->get_undo_redo();
+ clicked = 0;
+ clicked_includes_current = false;
+ orthogonal = false;
+ message_time = 0;
+
+ spatial_editor = p_spatial_editor;
+ ViewportContainer *c = memnew(ViewportContainer);
c->set_stretch(true);
add_child(c);
c->set_area_as_parent_rect();
- viewport = memnew( Viewport );
+ viewport = memnew(Viewport);
viewport->set_disable_input(true);
c->add_child(viewport);
- surface = memnew( Control );
+ surface = memnew(Control);
add_child(surface);
surface->set_area_as_parent_rect();
camera = memnew(Camera);
camera->set_disable_gizmo(true);
- camera->set_cull_mask( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+p_index))|(1<<GIZMO_EDIT_LAYER)|(1<<GIZMO_GRID_LAYER) );
+ camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER));
//camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
viewport->add_child(camera);
camera->make_current();
surface->set_focus_mode(FOCUS_ALL);
- view_menu = memnew( MenuButton );
+ view_menu = memnew(MenuButton);
surface->add_child(view_menu);
- view_menu->set_pos( Point2(4,4));
- view_menu->set_self_modulate(Color(1,1,1,0.5));
+ view_menu->set_pos(Point2(4, 4));
+ view_menu->set_self_modulate(Color(1, 1, 1, 0.5));
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
@@ -2334,60 +2168,52 @@ SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, Ed
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_item(TTR("Perspective") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_PERSPECTIVE);
view_menu->get_popup()->add_check_item(TTR("Orthogonal") + " (" + ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal")->get_as_text() + ")", VIEW_ORTHOGONAL);
- view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE),true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTR("Environment")), VIEW_ENVIRONMENT);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT),true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTR("Audio Listener")), VIEW_AUDIO_LISTENER);
view_menu->get_popup()->add_separator();
- view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("Gizmos")),VIEW_GIZMOS);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_GIZMOS),true);
+ view_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTR("Gizmos")), VIEW_GIZMOS);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
view_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_selection_with_view"), VIEW_ALIGN_SELECTION_WITH_VIEW);
- view_menu->get_popup()->connect("id_pressed",this,"_menu_option");
+ view_menu->get_popup()->connect("id_pressed", this, "_menu_option");
- preview_camera = memnew( Button );
+ preview_camera = memnew(Button);
preview_camera->set_toggle_mode(true);
- preview_camera->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,90);
- preview_camera->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,10);
+ preview_camera->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, 90);
+ preview_camera->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 10);
preview_camera->set_text("preview");
surface->add_child(preview_camera);
preview_camera->hide();
- preview_camera->connect("toggled",this,"_toggle_camera_preview");
- previewing=NULL;
- preview=NULL;
- gizmo_scale=1.0;
+ preview_camera->connect("toggled", this, "_toggle_camera_preview");
+ previewing = NULL;
+ preview = NULL;
+ gizmo_scale = 1.0;
- selection_menu = memnew( PopupMenu );
+ selection_menu = memnew(PopupMenu);
add_child(selection_menu);
selection_menu->set_custom_minimum_size(Vector2(100, 0));
selection_menu->connect("id_pressed", this, "_selection_result_pressed");
selection_menu->connect("popup_hide", this, "_selection_menu_hide");
- if (p_index==0) {
- view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER),true);
+ if (p_index == 0) {
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
viewport->set_as_audio_listener(true);
}
-
- name=TTR("Top");
+ name = TTR("Top");
_update_name();
- EditorSettings::get_singleton()->connect("settings_changed",this,"update_transform_gizmo_view");
-
+ EditorSettings::get_singleton()->connect("settings_changed", this, "update_transform_gizmo_view");
}
-
-
-
-
-
-
-SpatialEditor *SpatialEditor::singleton=NULL;
+SpatialEditor *SpatialEditor::singleton = NULL;
SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
@@ -2395,183 +2221,172 @@ SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
VisualServer::get_singleton()->free(sbox_instance);
}
-
-
void SpatialEditor::select_gizmo_hilight_axis(int p_axis) {
+ for (int i = 0; i < 3; i++) {
- for(int i=0;i<3;i++) {
-
- move_gizmo[i]->surface_set_material(0,i==p_axis?gizmo_hl:gizmo_color[i]);
- rotate_gizmo[i]->surface_set_material(0,(i+3)==p_axis?gizmo_hl:gizmo_color[i]);
+ move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_hl : gizmo_color[i]);
+ rotate_gizmo[i]->surface_set_material(0, (i + 3) == p_axis ? gizmo_hl : gizmo_color[i]);
}
-
}
void SpatialEditor::update_transform_gizmo() {
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
Rect3 center;
- bool first=true;
+ bool first = true;
Basis gizmo_basis;
- bool local_gizmo_coords = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS) );
+ bool local_gizmo_coords = transform_menu->get_popup()->is_item_checked(transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS));
-
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform xf = se->sp->get_global_transform();
if (first) {
- center.pos=xf.origin;
- first=false;
+ center.pos = xf.origin;
+ first = false;
if (local_gizmo_coords) {
- gizmo_basis=xf.basis;
+ gizmo_basis = xf.basis;
gizmo_basis.orthonormalize();
}
} else {
center.expand_to(xf.origin);
- gizmo_basis=Basis();
+ gizmo_basis = Basis();
}
//count++;
}
- Vector3 pcenter = center.pos+center.size*0.5;
- gizmo.visible=!first;
- gizmo.transform.origin=pcenter;
- gizmo.transform.basis=gizmo_basis;
+ Vector3 pcenter = center.pos + center.size * 0.5;
+ gizmo.visible = !first;
+ gizmo.transform.origin = pcenter;
+ gizmo.transform.basis = gizmo_basis;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
viewports[i]->update_transform_gizmo_view();
}
-
}
-
Object *SpatialEditor::_get_editor_data(Object *p_what) {
Spatial *sp = p_what->cast_to<Spatial>();
if (!sp)
return NULL;
+ SpatialEditorSelectedItem *si = memnew(SpatialEditorSelectedItem);
- SpatialEditorSelectedItem *si = memnew( SpatialEditorSelectedItem );
-
- si->sp=sp;
- si->sbox_instance=VisualServer::get_singleton()->instance_create2(selection_box->get_rid(),sp->get_world()->get_scenario());
+ si->sp = sp;
+ si->sbox_instance = VisualServer::get_singleton()->instance_create2(selection_box->get_rid(), sp->get_world()->get_scenario());
VS::get_singleton()->instance_geometry_set_cast_shadows_setting(si->sbox_instance, VS::SHADOW_CASTING_SETTING_OFF);
if (get_tree()->is_editor_hint())
- editor->call("edit_node",sp);
+ editor->call("edit_node", sp);
return si;
}
void SpatialEditor::_generate_selection_box() {
- Rect3 aabb( Vector3(), Vector3(1,1,1) );
- aabb.grow_by( aabb.get_longest_axis_size()/20.0 );
+ Rect3 aabb(Vector3(), Vector3(1, 1, 1));
+ aabb.grow_by(aabb.get_longest_axis_size() / 20.0);
- Ref<SurfaceTool> st = memnew( SurfaceTool );
+ Ref<SurfaceTool> st = memnew(SurfaceTool);
st->begin(Mesh::PRIMITIVE_LINES);
- for (int i=0;i<12;i++) {
+ for (int i = 0; i < 12; i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
/*Vector<Vector3> points;
Vector<Color> colors;
points.push_back(a);
points.push_back(b);*/
- st->add_color( Color(1.0,1.0,0.8,0.8) );
+ st->add_color(Color(1.0, 1.0, 0.8, 0.8));
st->add_vertex(a);
- st->add_color( Color(1.0,1.0,0.8,0.4) );
- st->add_vertex(a.linear_interpolate(b,0.2));
+ st->add_color(Color(1.0, 1.0, 0.8, 0.4));
+ st->add_vertex(a.linear_interpolate(b, 0.2));
- st->add_color( Color(1.0,1.0,0.8,0.4) );
- st->add_vertex(a.linear_interpolate(b,0.8));
- st->add_color( Color(1.0,1.0,0.8,0.8) );
+ st->add_color(Color(1.0, 1.0, 0.8, 0.4));
+ st->add_vertex(a.linear_interpolate(b, 0.8));
+ st->add_color(Color(1.0, 1.0, 0.8, 0.8));
st->add_vertex(b);
-
}
- Ref<FixedSpatialMaterial> mat = memnew( FixedSpatialMaterial );
- mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- mat->set_albedo(Color(1,1,1));
- mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
- mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
+ Ref<FixedSpatialMaterial> mat = memnew(FixedSpatialMaterial);
+ mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ mat->set_albedo(Color(1, 1, 1));
+ mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
+ mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
st->set_material(mat);
selection_box = st->commit();
}
-
Dictionary SpatialEditor::get_state() const {
-
Dictionary d;
- d["snap_enabled"]=snap_enabled;
- d["translate_snap"]=get_translate_snap();
- d["rotate_snap"]=get_rotate_snap();
- d["scale_snap"]=get_scale_snap();
-
- int local_coords_index=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
- d["local_coords"]=transform_menu->get_popup()->is_item_checked( local_coords_index );
-
- int vc=0;
- if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT) ))
- vc=1;
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS) ))
- vc=2;
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS) ))
- vc=3;
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS) ))
- vc=4;
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT) ))
- vc=5;
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT) ))
- vc=6;
-
- d["viewport_mode"]=vc;
+ d["snap_enabled"] = snap_enabled;
+ d["translate_snap"] = get_translate_snap();
+ d["rotate_snap"] = get_rotate_snap();
+ d["scale_snap"] = get_scale_snap();
+
+ int local_coords_index = transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
+ d["local_coords"] = transform_menu->get_popup()->is_item_checked(local_coords_index);
+
+ int vc = 0;
+ if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
+ vc = 1;
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
+ vc = 2;
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
+ vc = 3;
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
+ vc = 4;
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
+ vc = 5;
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
+ vc = 6;
+
+ d["viewport_mode"] = vc;
Array vpdata;
- for(int i=0;i<4;i++) {
- vpdata.push_back( viewports[i]->get_state() );
+ for (int i = 0; i < 4; i++) {
+ vpdata.push_back(viewports[i]->get_state());
}
- d["viewports"]=vpdata;
+ d["viewports"] = vpdata;
- d["default_light"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT) );
- d["ambient_light_color"]=settings_ambient_color->get_pick_color();
+ d["default_light"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT));
+ d["ambient_light_color"] = settings_ambient_color->get_pick_color();
- d["default_srgb"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_SRGB) );
- d["show_grid"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID) );
- d["show_origin"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN) );
- d["fov"]=get_fov();
- d["znear"]=get_znear();
- d["zfar"]=get_zfar();
- d["deflight_rot_x"]=settings_default_light_rot_x;
- d["deflight_rot_y"]=settings_default_light_rot_y;
+ d["default_srgb"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_SRGB));
+ d["show_grid"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
+ d["show_origin"] = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
+ d["fov"] = get_fov();
+ d["znear"] = get_znear();
+ d["zfar"] = get_zfar();
+ d["deflight_rot_x"] = settings_default_light_rot_x;
+ d["deflight_rot_y"] = settings_default_light_rot_y;
return d;
}
-void SpatialEditor::set_state(const Dictionary& p_state) {
+void SpatialEditor::set_state(const Dictionary &p_state) {
Dictionary d = p_state;
if (d.has("snap_enabled")) {
- snap_enabled=d["snap_enabled"];
- int snap_enabled_idx=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_USE_SNAP);
- transform_menu->get_popup()->set_item_checked( snap_enabled_idx, snap_enabled );
+ snap_enabled = d["snap_enabled"];
+ int snap_enabled_idx = transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_USE_SNAP);
+ transform_menu->get_popup()->set_item_checked(snap_enabled_idx, snap_enabled);
}
if (d.has("translate_snap"))
@@ -2584,33 +2399,33 @@ void SpatialEditor::set_state(const Dictionary& p_state) {
snap_scale->set_text(d["scale_snap"]);
if (d.has("local_coords")) {
- int local_coords_idx=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
- transform_menu->get_popup()->set_item_checked( local_coords_idx, d["local_coords"] );
+ int local_coords_idx = transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
+ transform_menu->get_popup()->set_item_checked(local_coords_idx, d["local_coords"]);
update_transform_gizmo();
}
if (d.has("viewport_mode")) {
int vc = d["viewport_mode"];
- if (vc==1)
+ if (vc == 1)
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
- else if (vc==2)
+ else if (vc == 2)
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
- else if (vc==3)
+ else if (vc == 3)
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
- else if (vc==4)
+ else if (vc == 4)
_menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
- else if (vc==5)
+ else if (vc == 5)
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
- else if (vc==6)
+ else if (vc == 6)
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
}
if (d.has("viewports")) {
Array vp = d["viewports"];
- ERR_FAIL_COND(vp.size()>4);
+ ERR_FAIL_COND(vp.size() > 4);
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
viewports[i]->set_state(vp[i]);
}
}
@@ -2626,18 +2441,16 @@ void SpatialEditor::set_state(const Dictionary& p_state) {
bool use = d["default_light"];
bool existing = light_instance.is_valid();
- if (use!=existing) {
+ if (use != existing) {
if (existing) {
VisualServer::get_singleton()->free(light_instance);
- light_instance=RID();
+ light_instance = RID();
} else {
- light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
- VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
-
+ light_instance = VisualServer::get_singleton()->instance_create2(light, get_tree()->get_root()->get_world()->get_scenario());
+ VisualServer::get_singleton()->instance_set_transform(light_instance, light_transform);
}
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), light_instance.is_valid() );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), light_instance.is_valid());
}
-
}
if (d.has("ambient_light_color")) {
settings_ambient_color->set_pick_color(d["ambient_light_color"]);
@@ -2653,7 +2466,7 @@ void SpatialEditor::set_state(const Dictionary& p_state) {
if (d.has("show_grid")) {
bool use = d["show_grid"];
- if (use!=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
+ if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
_menu_item_pressed(MENU_VIEW_GRID);
}
}
@@ -2661,26 +2474,23 @@ void SpatialEditor::set_state(const Dictionary& p_state) {
if (d.has("show_origin")) {
bool use = d["show_origin"];
- if (use!=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use );
- VisualServer::get_singleton()->instance_set_visible(origin_instance,use);
+ if (use != view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
+ VisualServer::get_singleton()->instance_set_visible(origin_instance, use);
}
}
if (d.has("deflight_rot_x"))
- settings_default_light_rot_x=d["deflight_rot_x"];
+ settings_default_light_rot_x = d["deflight_rot_x"];
if (d.has("deflight_rot_y"))
- settings_default_light_rot_y=d["deflight_rot_y"];
+ settings_default_light_rot_y = d["deflight_rot_y"];
_update_default_light_angle();
-
-
}
-
void SpatialEditor::edit(Spatial *p_spatial) {
- if (p_spatial!=selected) {
+ if (p_spatial != selected) {
if (selected) {
Ref<SpatialEditorGizmo> seg = selected->get_gizmo();
@@ -2690,8 +2500,8 @@ void SpatialEditor::edit(Spatial *p_spatial) {
}
}
- selected=p_spatial;
- over_gizmo_handle=-1;
+ selected = p_spatial;
+ over_gizmo_handle = -1;
if (selected) {
@@ -2723,32 +2533,31 @@ void SpatialEditor::_xform_dialog_action() {
Vector3 rotate;
Vector3 translate;
- for(int i=0;i<3;i++) {
- translate[i]=xform_translate[i]->get_text().to_double();
- rotate[i]=Math::deg2rad(xform_rotate[i]->get_text().to_double());
- scale[i]=xform_scale[i]->get_text().to_double();
+ for (int i = 0; i < 3; i++) {
+ translate[i] = xform_translate[i]->get_text().to_double();
+ rotate[i] = Math::deg2rad(xform_rotate[i]->get_text().to_double());
+ scale[i] = xform_scale[i]->get_text().to_double();
}
-
+
t.basis.scale(scale);
t.basis.rotate(rotate);
- t.origin=translate;
-
+ t.origin = translate;
undo_redo->create_action(TTR("XForm Dialog"));
- List<Node*> &selection = editor_selection->get_selected_node_list();
+ List<Node *> &selection = editor_selection->get_selected_node_list();
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
- SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
+ SpatialEditorSelectedItem *se = editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
- bool post = xform_type->get_selected()>0;
+ bool post = xform_type->get_selected() > 0;
Transform tr = sp->get_global_transform();
if (post)
@@ -2756,18 +2565,18 @@ void SpatialEditor::_xform_dialog_action() {
else {
tr.basis = t.basis * tr.basis;
- tr.origin+=t.origin;
+ tr.origin += t.origin;
}
- undo_redo->add_do_method(sp,"set_global_transform",tr);
- undo_redo->add_undo_method(sp,"set_global_transform",sp->get_global_transform());
+ undo_redo->add_do_method(sp, "set_global_transform", tr);
+ undo_redo->add_undo_method(sp, "set_global_transform", sp->get_global_transform());
}
undo_redo->commit_action();
}
void SpatialEditor::_menu_item_pressed(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MENU_TOOL_SELECT:
case MENU_TOOL_MOVE:
@@ -2775,9 +2584,9 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
case MENU_TOOL_SCALE:
case MENU_TOOL_LIST_SELECT: {
- for(int i=0;i<TOOL_MAX;i++)
- tool_button[i]->set_pressed(i==p_option);
- tool_mode=(ToolMode)p_option;
+ for (int i = 0; i < TOOL_MAX; i++)
+ tool_button[i]->set_pressed(i == p_option);
+ tool_mode = (ToolMode)p_option;
//static const char *_mode[]={"Selection Mode.","Translation Mode.","Rotation Mode.","Scale Mode.","List Selection Mode."};
//set_message(_mode[p_option],3);
@@ -2786,55 +2595,53 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
} break;
case MENU_TRANSFORM_USE_SNAP: {
- bool is_checked = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(p_option) );
- snap_enabled=!is_checked;
- transform_menu->get_popup()->set_item_checked( transform_menu->get_popup()->get_item_index(p_option), snap_enabled );
+ bool is_checked = transform_menu->get_popup()->is_item_checked(transform_menu->get_popup()->get_item_index(p_option));
+ snap_enabled = !is_checked;
+ transform_menu->get_popup()->set_item_checked(transform_menu->get_popup()->get_item_index(p_option), snap_enabled);
} break;
case MENU_TRANSFORM_CONFIGURE_SNAP: {
- snap_dialog->popup_centered(Size2(200,180));
+ snap_dialog->popup_centered(Size2(200, 180));
} break;
case MENU_TRANSFORM_LOCAL_COORDS: {
- bool is_checked = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(p_option) );
- transform_menu->get_popup()->set_item_checked( transform_menu->get_popup()->get_item_index(p_option), !is_checked );
+ bool is_checked = transform_menu->get_popup()->is_item_checked(transform_menu->get_popup()->get_item_index(p_option));
+ transform_menu->get_popup()->set_item_checked(transform_menu->get_popup()->get_item_index(p_option), !is_checked);
update_transform_gizmo();
} break;
case MENU_TRANSFORM_DIALOG: {
- for(int i=0;i<3;i++) {
-
+ for (int i = 0; i < 3; i++) {
xform_translate[i]->set_text("0");
xform_rotate[i]->set_text("0");
xform_scale[i]->set_text("1");
-
}
- xform_dialog->popup_centered(Size2(200,200));
+ xform_dialog->popup_centered(Size2(200, 200));
} break;
case MENU_VIEW_USE_DEFAULT_LIGHT: {
- bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
+ bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
if (is_checked) {
VisualServer::get_singleton()->free(light_instance);
- light_instance=RID();
+ light_instance = RID();
} else {
- light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
- VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
+ light_instance = VisualServer::get_singleton()->instance_create2(light, get_tree()->get_root()->get_world()->get_scenario());
+ VisualServer::get_singleton()->instance_set_transform(light_instance, light_transform);
_update_default_light_angle();
}
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), light_instance.is_valid() );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), light_instance.is_valid());
} break;
case MENU_VIEW_USE_DEFAULT_SRGB: {
- bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
+ bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
if (is_checked) {
//viewport_environment->set_enable_fx(Environment::FX_SRGB,false);
@@ -2842,82 +2649,77 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
//viewport_environment->set_enable_fx(Environment::FX_SRGB,true);
}
- is_checked = ! is_checked;
-
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), is_checked );
+ is_checked = !is_checked;
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), is_checked);
} break;
case MENU_VIEW_USE_1_VIEWPORT: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
viewports[i]->hide();
}
viewports[0]->set_area_as_parent_rect();
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
} break;
case MENU_VIEW_USE_2_VIEWPORTS: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
- if (i==1 || i==3)
+ if (i == 1 || i == 3)
viewports[i]->hide();
else
viewports[i]->show();
-
-
}
viewports[0]->set_area_as_parent_rect();
//viewports[0]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
//viewports[2]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
} break;
case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
- if (i==1 || i==3)
+ if (i == 1 || i == 3)
viewports[i]->hide();
else
viewports[i]->show();
-
-
}
viewports[0]->set_area_as_parent_rect();
//viewports[0]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
//viewports[2]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
} break;
case MENU_VIEW_USE_3_VIEWPORTS: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
- if (i==1)
+ if (i == 1)
viewports[i]->hide();
else
viewports[i]->show();
@@ -2931,19 +2733,19 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
//viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
//viewports[3]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
} break;
case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
- if (i==1)
+ if (i == 1)
viewports[i]->hide();
else
viewports[i]->show();
@@ -2957,17 +2759,17 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
viewports[3]->set_area_as_parent_rect();
//viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
} break;
case MENU_VIEW_USE_4_VIEWPORTS: {
- for(int i=1;i<4;i++) {
+ for (int i = 1; i < 4; i++) {
viewports[i]->show();
}
@@ -2984,114 +2786,106 @@ void SpatialEditor::_menu_item_pressed(int p_option) {
//viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
//viewports[3]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
} break;
case MENU_VIEW_DISPLAY_NORMAL: {
+ VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_DISABLED);
- VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_DISABLED );
-
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false);
} break;
case MENU_VIEW_DISPLAY_WIREFRAME: {
- VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_WIREFRAME );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
+ VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_WIREFRAME);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false);
} break;
case MENU_VIEW_DISPLAY_OVERDRAW: {
- VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), true );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
+ VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false);
} break;
case MENU_VIEW_DISPLAY_SHADELESS: {
- VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), true );
+ VisualServer::get_singleton()->scenario_set_debug(get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), true);
} break;
case MENU_VIEW_ORIGIN: {
- bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
+ bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
- is_checked=!is_checked;
- VisualServer::get_singleton()->instance_set_visible(origin_instance,is_checked);
+ is_checked = !is_checked;
+ VisualServer::get_singleton()->instance_set_visible(origin_instance, is_checked);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), is_checked);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), is_checked);
} break;
case MENU_VIEW_GRID: {
- bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
+ bool is_checked = view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(p_option));
- grid_enabled=!is_checked;
+ grid_enabled = !is_checked;
- for(int i=0;i<3;++i) {
+ for (int i = 0; i < 3; ++i) {
if (grid_enable[i]) {
- VisualServer::get_singleton()->instance_set_visible(grid_instance[i],grid_enabled);
- grid_visible[i]=grid_enabled;
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[i], grid_enabled);
+ grid_visible[i] = grid_enabled;
}
}
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), grid_enabled );
-
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(p_option), grid_enabled);
} break;
case MENU_VIEW_CAMERA_SETTINGS: {
- settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size()+Size2(50,50));
+ settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
} break;
-
}
}
-
void SpatialEditor::_init_indicators() {
//make sure that the camera indicator is not selectable
- light=VisualServer::get_singleton()->light_create( VisualServer::LIGHT_DIRECTIONAL );
+ light = VisualServer::get_singleton()->light_create(VisualServer::LIGHT_DIRECTIONAL);
//VisualServer::get_singleton()->light_set_shadow( light, true );
- light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
-
-
-
- light_transform.rotate(Vector3(1,0,0),-Math_PI/5.0);
- VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
+ light_instance = VisualServer::get_singleton()->instance_create2(light, get_tree()->get_root()->get_world()->get_scenario());
+ light_transform.rotate(Vector3(1, 0, 0), -Math_PI / 5.0);
+ VisualServer::get_singleton()->instance_set_transform(light_instance, light_transform);
//RID mat = VisualServer::get_singleton()->fixed_material_create();
///VisualServer::get_singleton()->fixed_material_set_flag(mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA,true);
//VisualServer::get_singleton()->fixed_material_set_flag(mat, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true);
-
{
indicator_mat.instance();
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
//indicator_mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP,true);
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
- indicator_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
+ indicator_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
PoolVector<Color> grid_colors[3];
PoolVector<Vector3> grid_points[3];
@@ -3100,185 +2894,165 @@ void SpatialEditor::_init_indicators() {
Color grid_color = EditorSettings::get_singleton()->get("editors/3d/grid_color");
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1;
+ axis[i] = 1;
Vector3 axis_n1;
- axis_n1[(i+1)%3]=1;
+ axis_n1[(i + 1) % 3] = 1;
Vector3 axis_n2;
- axis_n2[(i+2)%3]=1;
+ axis_n2[(i + 2) % 3] = 1;
- origin_colors.push_back(Color(axis.x,axis.y,axis.z));
- origin_colors.push_back(Color(axis.x,axis.y,axis.z));
- origin_points.push_back(axis*4096);
- origin_points.push_back(axis*-4096);
+ origin_colors.push_back(Color(axis.x, axis.y, axis.z));
+ origin_colors.push_back(Color(axis.x, axis.y, axis.z));
+ origin_points.push_back(axis * 4096);
+ origin_points.push_back(axis * -4096);
#define ORIGIN_GRID_SIZE 25
- for(int j=-ORIGIN_GRID_SIZE;j<=ORIGIN_GRID_SIZE;j++) {
-
+ for (int j = -ORIGIN_GRID_SIZE; j <= ORIGIN_GRID_SIZE; j++) {
grid_colors[i].push_back(grid_color);
grid_colors[i].push_back(grid_color);
grid_colors[i].push_back(grid_color);
grid_colors[i].push_back(grid_color);
- grid_points[i].push_back(axis_n1*ORIGIN_GRID_SIZE+axis_n2*j);
- grid_points[i].push_back(-axis_n1*ORIGIN_GRID_SIZE+axis_n2*j);
- grid_points[i].push_back(axis_n2*ORIGIN_GRID_SIZE+axis_n1*j);
- grid_points[i].push_back(-axis_n2*ORIGIN_GRID_SIZE+axis_n1*j);
-
+ grid_points[i].push_back(axis_n1 * ORIGIN_GRID_SIZE + axis_n2 * j);
+ grid_points[i].push_back(-axis_n1 * ORIGIN_GRID_SIZE + axis_n2 * j);
+ grid_points[i].push_back(axis_n2 * ORIGIN_GRID_SIZE + axis_n1 * j);
+ grid_points[i].push_back(-axis_n2 * ORIGIN_GRID_SIZE + axis_n1 * j);
}
grid[i] = VisualServer::get_singleton()->mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
- d[VisualServer::ARRAY_VERTEX]=grid_points[i];
- d[VisualServer::ARRAY_COLOR]=grid_colors[i];
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i],VisualServer::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(grid[i],0,indicator_mat->get_rid());
- grid_instance[i] = VisualServer::get_singleton()->instance_create2(grid[i],get_tree()->get_root()->get_world()->get_scenario());
-
- grid_visible[i]=false;
- grid_enable[i]=false;
- VisualServer::get_singleton()->instance_set_visible(grid_instance[i],false);
+ d[VisualServer::ARRAY_VERTEX] = grid_points[i];
+ d[VisualServer::ARRAY_COLOR] = grid_colors[i];
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid());
+ grid_instance[i] = VisualServer::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario());
+
+ grid_visible[i] = false;
+ grid_enable[i] = false;
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[i], false);
VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[i], VS::SHADOW_CASTING_SETTING_OFF);
VS::get_singleton()->instance_set_layer_mask(grid_instance[i], 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
-
-
}
origin = VisualServer::get_singleton()->mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
- d[VisualServer::ARRAY_VERTEX]=origin_points;
- d[VisualServer::ARRAY_COLOR]=origin_colors;
-
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin,VisualServer::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(origin,0,indicator_mat->get_rid());
+ d[VisualServer::ARRAY_VERTEX] = origin_points;
+ d[VisualServer::ARRAY_COLOR] = origin_colors;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(origin, VisualServer::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(origin, 0, indicator_mat->get_rid());
//origin = VisualServer::get_singleton()->poly_create();
//VisualServer::get_singleton()->poly_add_primitive(origin,origin_points,Vector<Vector3>(),origin_colors,Vector<Vector3>());
//VisualServer::get_singleton()->poly_set_material(origin,indicator_mat,true);
- origin_instance = VisualServer::get_singleton()->instance_create2(origin,get_tree()->get_root()->get_world()->get_scenario());
- VS::get_singleton()->instance_set_layer_mask(origin_instance,1<<SpatialEditorViewport::GIZMO_GRID_LAYER);
+ origin_instance = VisualServer::get_singleton()->instance_create2(origin, get_tree()->get_root()->get_world()->get_scenario());
+ VS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, VS::SHADOW_CASTING_SETTING_OFF);
-
-
- VisualServer::get_singleton()->instance_set_visible(grid_instance[1],true);
- grid_enable[1]=true;
- grid_visible[1]=true;
- grid_enabled=true;
- last_grid_snap=1;
-
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[1], true);
+ grid_enable[1] = true;
+ grid_visible[1] = true;
+ grid_enabled = true;
+ last_grid_snap = 1;
}
{
cursor_mesh = VisualServer::get_singleton()->mesh_create();
PoolVector<Vector3> cursor_points;
float cs = 0.25;
- cursor_points.push_back(Vector3(+cs,0,0));
- cursor_points.push_back(Vector3(-cs,0,0));
- cursor_points.push_back(Vector3(0,+cs,0));
- cursor_points.push_back(Vector3(0,-cs,0));
- cursor_points.push_back(Vector3(0,0,+cs));
- cursor_points.push_back(Vector3(0,0,-cs));
+ cursor_points.push_back(Vector3(+cs, 0, 0));
+ cursor_points.push_back(Vector3(-cs, 0, 0));
+ cursor_points.push_back(Vector3(0, +cs, 0));
+ cursor_points.push_back(Vector3(0, -cs, 0));
+ cursor_points.push_back(Vector3(0, 0, +cs));
+ cursor_points.push_back(Vector3(0, 0, -cs));
cursor_material.instance();
- cursor_material->set_albedo(Color(0,1,1));
- cursor_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
+ cursor_material->set_albedo(Color(0, 1, 1));
+ cursor_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
Array d;
d.resize(VS::ARRAY_MAX);
- d[VS::ARRAY_VERTEX]=cursor_points;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(cursor_mesh,VS::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(cursor_mesh,0,cursor_material->get_rid());
+ d[VS::ARRAY_VERTEX] = cursor_points;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(cursor_mesh, VS::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(cursor_mesh, 0, cursor_material->get_rid());
- cursor_instance = VisualServer::get_singleton()->instance_create2(cursor_mesh,get_tree()->get_root()->get_world()->get_scenario());
- VS::get_singleton()->instance_set_layer_mask(cursor_instance,1<<SpatialEditorViewport::GIZMO_GRID_LAYER);
+ cursor_instance = VisualServer::get_singleton()->instance_create2(cursor_mesh, get_tree()->get_root()->get_world()->get_scenario());
+ VS::get_singleton()->instance_set_layer_mask(cursor_instance, 1 << SpatialEditorViewport::GIZMO_GRID_LAYER);
VisualServer::get_singleton()->instance_geometry_set_cast_shadows_setting(cursor_instance, VS::SHADOW_CASTING_SETTING_OFF);
-
-
}
-
{
//move gizmo
-
float gizmo_alph = EditorSettings::get_singleton()->get("editors/3d/manipulator_gizmo_opacity");
- gizmo_hl = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ) );
+ gizmo_hl = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
gizmo_hl->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
gizmo_hl->set_flag(FixedSpatialMaterial::FLAG_ONTOP, true);
gizmo_hl->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- gizmo_hl->set_albedo(Color(1,1,1,gizmo_alph+0.2f));
+ gizmo_hl->set_albedo(Color(1, 1, 1, gizmo_alph + 0.2f));
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- move_gizmo[i]=Ref<Mesh>( memnew( Mesh ) );
- rotate_gizmo[i]=Ref<Mesh>( memnew( Mesh ) );
+ move_gizmo[i] = Ref<Mesh>(memnew(Mesh));
+ rotate_gizmo[i] = Ref<Mesh>(memnew(Mesh));
-
- Ref<FixedSpatialMaterial> mat = memnew( FixedSpatialMaterial );
+ Ref<FixedSpatialMaterial> mat = memnew(FixedSpatialMaterial);
mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP, true);
mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
Color col;
- col[i]=1.0;
- col.a= gizmo_alph;
+ col[i] = 1.0;
+ col.a = gizmo_alph;
mat->set_albedo(col);
- gizmo_color[i]=mat;
-
-
-
+ gizmo_color[i] = mat;
Vector3 ivec;
- ivec[i]=1;
+ ivec[i] = 1;
Vector3 nivec;
- nivec[(i+1)%3]=1;
- nivec[(i+2)%3]=1;
+ nivec[(i + 1) % 3] = 1;
+ nivec[(i + 2) % 3] = 1;
Vector3 ivec2;
- ivec2[(i+1)%3]=1;
+ ivec2[(i + 1) % 3] = 1;
Vector3 ivec3;
- ivec3[(i+2)%3]=1;
-
+ ivec3[(i + 2) % 3] = 1;
{
- Ref<SurfaceTool> surftool = memnew( SurfaceTool );
+ Ref<SurfaceTool> surftool = memnew(SurfaceTool);
surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
//translate
- const int arrow_points=5;
- Vector3 arrow[5]={
- nivec*0.0+ivec*0.0,
- nivec*0.01+ivec*0.0,
- nivec*0.01+ivec*1.0,
- nivec*0.1+ivec*1.0,
- nivec*0.0+ivec*(1+GIZMO_ARROW_SIZE),
+ const int arrow_points = 5;
+ Vector3 arrow[5] = {
+ nivec * 0.0 + ivec * 0.0,
+ nivec * 0.01 + ivec * 0.0,
+ nivec * 0.01 + ivec * 1.0,
+ nivec * 0.1 + ivec * 1.0,
+ nivec * 0.0 + ivec * (1 + GIZMO_ARROW_SIZE),
};
- int arrow_sides=6;
+ int arrow_sides = 6;
+ for (int k = 0; k < 7; k++) {
- for(int k = 0; k < 7 ; k++) {
+ Basis ma(ivec, Math_PI * 2 * float(k) / arrow_sides);
+ Basis mb(ivec, Math_PI * 2 * float(k + 1) / arrow_sides);
+ for (int j = 0; j < arrow_points - 1; j++) {
- Basis ma(ivec,Math_PI*2*float(k)/arrow_sides);
- Basis mb(ivec,Math_PI*2*float(k+1)/arrow_sides);
-
-
- for(int j=0;j<arrow_points-1;j++) {
-
- Vector3 points[4]={
+ Vector3 points[4] = {
ma.xform(arrow[j]),
mb.xform(arrow[j]),
- mb.xform(arrow[j+1]),
- ma.xform(arrow[j+1]),
+ mb.xform(arrow[j + 1]),
+ ma.xform(arrow[j + 1]),
};
surftool->add_vertex(points[0]);
surftool->add_vertex(points[1]);
@@ -3288,7 +3062,6 @@ void SpatialEditor::_init_indicators() {
surftool->add_vertex(points[2]);
surftool->add_vertex(points[3]);
}
-
}
surftool->set_material(mat);
@@ -3297,33 +3070,29 @@ void SpatialEditor::_init_indicators() {
{
-
- Ref<SurfaceTool> surftool = memnew( SurfaceTool );
+ Ref<SurfaceTool> surftool = memnew(SurfaceTool);
surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
- Vector3 circle[5]={
- ivec*0.02+ivec2*0.02+ivec2*1.0,
- ivec*-0.02+ivec2*0.02+ivec2*1.0,
- ivec*-0.02+ivec2*-0.02+ivec2*1.0,
- ivec*0.02+ivec2*-0.02+ivec2*1.0,
- ivec*0.02+ivec2*0.02+ivec2*1.0,
+ Vector3 circle[5] = {
+ ivec * 0.02 + ivec2 * 0.02 + ivec2 * 1.0,
+ ivec * -0.02 + ivec2 * 0.02 + ivec2 * 1.0,
+ ivec * -0.02 + ivec2 * -0.02 + ivec2 * 1.0,
+ ivec * 0.02 + ivec2 * -0.02 + ivec2 * 1.0,
+ ivec * 0.02 + ivec2 * 0.02 + ivec2 * 1.0,
};
+ for (int k = 0; k < 33; k++) {
- for(int k = 0; k < 33 ; k++) {
+ Basis ma(ivec, Math_PI * 2 * float(k) / 32);
+ Basis mb(ivec, Math_PI * 2 * float(k + 1) / 32);
+ for (int j = 0; j < 4; j++) {
- Basis ma(ivec,Math_PI*2*float(k)/32);
- Basis mb(ivec,Math_PI*2*float(k+1)/32);
-
-
- for(int j=0;j<4;j++) {
-
- Vector3 points[4]={
+ Vector3 points[4] = {
ma.xform(circle[j]),
mb.xform(circle[j]),
- mb.xform(circle[j+1]),
- ma.xform(circle[j+1]),
+ mb.xform(circle[j + 1]),
+ ma.xform(circle[j + 1]),
};
surftool->add_vertex(points[0]);
surftool->add_vertex(points[1]);
@@ -3333,15 +3102,11 @@ void SpatialEditor::_init_indicators() {
surftool->add_vertex(points[2]);
surftool->add_vertex(points[3]);
}
-
}
surftool->set_material(mat);
surftool->commit(rotate_gizmo[i]);
-
}
-
-
}
}
@@ -3352,18 +3117,16 @@ void SpatialEditor::_init_indicators() {
_generate_selection_box();
-
//get_scene()->get_root_node()->cast_to<EditorNode>()->get_scene_root()->add_child(camera);
//current_camera=camera;
-
}
void SpatialEditor::_finish_indicators() {
VisualServer::get_singleton()->free(origin_instance);
VisualServer::get_singleton()->free(origin);
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
VisualServer::get_singleton()->free(grid_instance[i]);
VisualServer::get_singleton()->free(grid[i]);
}
@@ -3427,17 +3190,16 @@ void SpatialEditor::_unhandled_key_input(InputEvent p_event) {
}
#endif
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::KEY: {
-
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
if (!k.pressed)
break;
- switch(k.scancode) {
+ switch (k.scancode) {
case KEY_Q: _menu_item_pressed(MENU_TOOL_SELECT); break;
case KEY_W: _menu_item_pressed(MENU_TOOL_MOVE); break;
@@ -3448,7 +3210,7 @@ void SpatialEditor::_unhandled_key_input(InputEvent p_event) {
if (k.mod.shift || k.mod.control || k.mod.command)
break;
- if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME))) {
+ if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME))) {
_menu_item_pressed(MENU_VIEW_DISPLAY_NORMAL);
} else {
_menu_item_pressed(MENU_VIEW_DISPLAY_WIREFRAME);
@@ -3464,55 +3226,51 @@ void SpatialEditor::_unhandled_key_input(InputEvent p_event) {
}
void SpatialEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
- tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon( get_icon("ToolSelect","EditorIcons") );
- tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon( get_icon("ToolMove","EditorIcons") );
- tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon( get_icon("ToolRotate","EditorIcons") );
- tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon( get_icon("ToolScale","EditorIcons") );
- tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon( get_icon("ListSelect","EditorIcons") );
- instance_button->set_icon( get_icon("SpatialAdd","EditorIcons") );
+ tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon(get_icon("ToolSelect", "EditorIcons"));
+ tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon(get_icon("ToolMove", "EditorIcons"));
+ tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon(get_icon("ToolRotate", "EditorIcons"));
+ tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon(get_icon("ToolScale", "EditorIcons"));
+ tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon(get_icon("ListSelect", "EditorIcons"));
+ instance_button->set_icon(get_icon("SpatialAdd", "EditorIcons"));
instance_button->hide();
-
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT),get_icon("Panels1","EditorIcons"));
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS),get_icon("Panels2","EditorIcons"));
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT),get_icon("Panels2Alt","EditorIcons"));
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS),get_icon("Panels3","EditorIcons"));
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT),get_icon("Panels3Alt","EditorIcons"));
- view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS),get_icon("Panels4","EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_icon("Panels1", "EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_icon("Panels2", "EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_icon("Panels2Alt", "EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_icon("Panels3", "EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_icon("Panels3Alt", "EditorIcons"));
+ view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_icon("Panels4", "EditorIcons"));
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
- get_tree()->connect("node_removed",this,"_node_removed");
- VS::get_singleton()->scenario_set_fallback_environment(get_viewport()->find_world()->get_scenario(),viewport_environment->get_rid());
-
+ get_tree()->connect("node_removed", this, "_node_removed");
+ VS::get_singleton()->scenario_set_fallback_environment(get_viewport()->find_world()->get_scenario(), viewport_environment->get_rid());
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- gizmos = memnew( SpatialEditorGizmos );
+ gizmos = memnew(SpatialEditorGizmos);
_init_indicators();
_update_default_light_angle();
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
_finish_indicators();
- memdelete( gizmos );
-
+ memdelete(gizmos);
}
}
void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
-
hbc_menu->add_child(p_control);
}
-void SpatialEditor::set_can_preview(Camera* p_preview) {
+void SpatialEditor::set_can_preview(Camera *p_preview) {
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
viewports[i]->set_can_preview(p_preview);
}
}
@@ -3527,17 +3285,16 @@ HSplitContainer *SpatialEditor::get_palette_split() {
return palette_split;
}
+void SpatialEditor::_request_gizmo(Object *p_obj) {
-void SpatialEditor::_request_gizmo(Object* p_obj) {
-
- Spatial *sp=p_obj->cast_to<Spatial>();
+ Spatial *sp = p_obj->cast_to<Spatial>();
if (!sp)
return;
- if (editor->get_edited_scene() && (sp==editor->get_edited_scene() || sp->get_owner()==editor->get_edited_scene() || editor->get_edited_scene()->is_editable_instance(sp->get_owner()))) {
+ if (editor->get_edited_scene() && (sp == editor->get_edited_scene() || sp->get_owner() == editor->get_edited_scene() || editor->get_edited_scene()->is_editable_instance(sp->get_owner()))) {
Ref<SpatialEditorGizmo> seg;
- for(int i=0;i<EditorNode::get_singleton()->get_editor_data().get_editor_plugin_count();i++) {
+ for (int i = 0; i < EditorNode::get_singleton()->get_editor_data().get_editor_plugin_count(); i++) {
seg = EditorNode::get_singleton()->get_editor_data().get_editor_plugin(i)->create_spatial_gizmo(sp);
if (seg.is_valid())
@@ -3552,265 +3309,246 @@ void SpatialEditor::_request_gizmo(Object* p_obj) {
sp->set_gizmo(seg);
}
-
- if (seg.is_valid() && sp==selected) {
+ if (seg.is_valid() && sp == selected) {
seg->set_selected(true);
selected->update_gizmo();
}
-
}
}
-void SpatialEditor::_toggle_maximize_view(Object* p_viewport) {
+void SpatialEditor::_toggle_maximize_view(Object *p_viewport) {
if (!p_viewport) return;
SpatialEditorViewport *current_viewport = p_viewport->cast_to<SpatialEditorViewport>();
if (!current_viewport) return;
- int index=-1;
+ int index = -1;
bool maximized = false;
- for(int i=0;i<4;i++) {
- if (viewports[i]==current_viewport) {
- index=i;
- if ( current_viewport->get_global_rect() == viewport_base->get_global_rect() )
- maximized=true;
+ for (int i = 0; i < 4; i++) {
+ if (viewports[i] == current_viewport) {
+ index = i;
+ if (current_viewport->get_global_rect() == viewport_base->get_global_rect())
+ maximized = true;
break;
}
}
- if (index==-1) return;
+ if (index == -1) return;
if (!maximized) {
- for(int i=0;i<4;i++) {
- if (i==index)
+ for (int i = 0; i < 4; i++) {
+ if (i == index)
viewports[i]->set_area_as_parent_rect();
else
viewports[i]->hide();
}
} else {
- for(int i=0;i<4;i++)
+ for (int i = 0; i < 4; i++)
viewports[i]->show();
- if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT) ))
+ if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT)))
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS) ))
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS)))
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT) ))
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT)))
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS) ))
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS)))
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT) ))
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT)))
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
- else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS) ))
+ else if (view_menu->get_popup()->is_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS)))
_menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
}
-
}
+void SpatialEditor::_node_removed(Node *p_node) {
-void SpatialEditor::_node_removed(Node* p_node) {
-
- if (p_node==selected)
- selected=NULL;
+ if (p_node == selected)
+ selected = NULL;
}
void SpatialEditor::_bind_methods() {
//ClassDB::bind_method("_gui_input",&SpatialEditor::_gui_input);
- ClassDB::bind_method("_unhandled_key_input",&SpatialEditor::_unhandled_key_input);
- ClassDB::bind_method("_node_removed",&SpatialEditor::_node_removed);
- ClassDB::bind_method("_menu_item_pressed",&SpatialEditor::_menu_item_pressed);
- ClassDB::bind_method("_xform_dialog_action",&SpatialEditor::_xform_dialog_action);
- ClassDB::bind_method("_instance_scene",&SpatialEditor::_instance_scene);
- ClassDB::bind_method("_get_editor_data",&SpatialEditor::_get_editor_data);
- ClassDB::bind_method("_request_gizmo",&SpatialEditor::_request_gizmo);
- ClassDB::bind_method("_default_light_angle_input",&SpatialEditor::_default_light_angle_input);
- ClassDB::bind_method("_update_ambient_light_color",&SpatialEditor::_update_ambient_light_color);
- ClassDB::bind_method("_toggle_maximize_view",&SpatialEditor::_toggle_maximize_view);
-
- ADD_SIGNAL( MethodInfo("transform_key_request") );
-
+ ClassDB::bind_method("_unhandled_key_input", &SpatialEditor::_unhandled_key_input);
+ ClassDB::bind_method("_node_removed", &SpatialEditor::_node_removed);
+ ClassDB::bind_method("_menu_item_pressed", &SpatialEditor::_menu_item_pressed);
+ ClassDB::bind_method("_xform_dialog_action", &SpatialEditor::_xform_dialog_action);
+ ClassDB::bind_method("_instance_scene", &SpatialEditor::_instance_scene);
+ ClassDB::bind_method("_get_editor_data", &SpatialEditor::_get_editor_data);
+ ClassDB::bind_method("_request_gizmo", &SpatialEditor::_request_gizmo);
+ ClassDB::bind_method("_default_light_angle_input", &SpatialEditor::_default_light_angle_input);
+ ClassDB::bind_method("_update_ambient_light_color", &SpatialEditor::_update_ambient_light_color);
+ ClassDB::bind_method("_toggle_maximize_view", &SpatialEditor::_toggle_maximize_view);
+ ADD_SIGNAL(MethodInfo("transform_key_request"));
}
void SpatialEditor::clear() {
- settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov",60.0));
- settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near",0.1));
- settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far",1500.0));
+ settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 60.0));
+ settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.1));
+ settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500.0));
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
viewports[i]->reset();
}
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
_menu_item_pressed(MENU_VIEW_DISPLAY_NORMAL);
-
- VisualServer::get_singleton()->instance_set_visible(origin_instance,true);
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
- for(int i=0;i<3;++i) {
+ VisualServer::get_singleton()->instance_set_visible(origin_instance, true);
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
+ for (int i = 0; i < 3; ++i) {
if (grid_enable[i]) {
- VisualServer::get_singleton()->instance_set_visible(grid_instance[i],true);
- grid_visible[i]=true;
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[i], true);
+ grid_visible[i] = true;
}
}
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER),i==0);
- viewports[i]->viewport->set_as_audio_listener(i==0);
+ viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
+ viewports[i]->viewport->set_as_audio_listener(i == 0);
}
- view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true );
+ view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
- settings_default_light_rot_x=Math_PI*0.3;
- settings_default_light_rot_y=Math_PI*0.2;
+ settings_default_light_rot_x = Math_PI * 0.3;
+ settings_default_light_rot_y = Math_PI * 0.2;
//viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,Color(0.15,0.15,0.15));
- settings_ambient_color->set_pick_color(Color(0.15,0.15,0.15));
+ settings_ambient_color->set_pick_color(Color(0.15, 0.15, 0.15));
if (!light_instance.is_valid())
_menu_item_pressed(MENU_VIEW_USE_DEFAULT_LIGHT);
_update_default_light_angle();
-
-
}
-
-void SpatialEditor::_update_ambient_light_color(const Color& p_color) {
+void SpatialEditor::_update_ambient_light_color(const Color &p_color) {
//viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,settings_ambient_color->get_color());
-
}
void SpatialEditor::_update_default_light_angle() {
Transform t;
- t.basis.rotate(Vector3(1,0,0),-settings_default_light_rot_x);
- t.basis.rotate(Vector3(0,1,0),-settings_default_light_rot_y);
+ t.basis.rotate(Vector3(1, 0, 0), -settings_default_light_rot_x);
+ t.basis.rotate(Vector3(0, 1, 0), -settings_default_light_rot_y);
settings_dlight->set_transform(t);
if (light_instance.is_valid()) {
- VS::get_singleton()->instance_set_transform(light_instance,t);
+ VS::get_singleton()->instance_set_transform(light_instance, t);
}
-
}
-void SpatialEditor::_default_light_angle_input(const InputEvent& p_event) {
-
+void SpatialEditor::_default_light_angle_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask&(0x1|0x2|0x4)) {
+ if (p_event.type == InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask & (0x1 | 0x2 | 0x4)) {
- settings_default_light_rot_y = Math::fposmod(settings_default_light_rot_y - p_event.mouse_motion.relative_x*0.01,Math_PI*2.0);
- settings_default_light_rot_x = Math::fposmod(settings_default_light_rot_x - p_event.mouse_motion.relative_y*0.01,Math_PI*2.0);
+ settings_default_light_rot_y = Math::fposmod(settings_default_light_rot_y - p_event.mouse_motion.relative_x * 0.01, Math_PI * 2.0);
+ settings_default_light_rot_x = Math::fposmod(settings_default_light_rot_x - p_event.mouse_motion.relative_y * 0.01, Math_PI * 2.0);
_update_default_light_angle();
}
-
}
-
SpatialEditor::SpatialEditor(EditorNode *p_editor) {
- gizmo.visible=true;
- gizmo.scale=1.0;
+ gizmo.visible = true;
+ gizmo.scale = 1.0;
- viewport_environment = Ref<Environment>( memnew( Environment ) );
- undo_redo=p_editor->get_undo_redo();
+ viewport_environment = Ref<Environment>(memnew(Environment));
+ undo_redo = p_editor->get_undo_redo();
VBoxContainer *vbc = this;
- custom_camera=NULL;
- singleton=this;
- editor=p_editor;
- editor_selection=editor->get_editor_selection();
+ custom_camera = NULL;
+ singleton = this;
+ editor = p_editor;
+ editor_selection = editor->get_editor_selection();
editor_selection->add_editor_plugin(this);
- snap_enabled=false;
+ snap_enabled = false;
tool_mode = TOOL_MODE_SELECT;
//set_focus_mode(FOCUS_ALL);
- hbc_menu = memnew( HBoxContainer );
+ hbc_menu = memnew(HBoxContainer);
vbc->add_child(hbc_menu);
-
Vector<Variant> button_binds;
button_binds.resize(1);
- tool_button[TOOL_MODE_SELECT] = memnew( ToolButton );
- hbc_menu->add_child( tool_button[TOOL_MODE_SELECT] );
+ tool_button[TOOL_MODE_SELECT] = memnew(ToolButton);
+ hbc_menu->add_child(tool_button[TOOL_MODE_SELECT]);
tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
tool_button[TOOL_MODE_SELECT]->set_flat(true);
tool_button[TOOL_MODE_SELECT]->set_pressed(true);
- button_binds[0]=MENU_TOOL_SELECT;
- tool_button[TOOL_MODE_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds);
- tool_button[TOOL_MODE_SELECT]->set_tooltip("Select Mode (Q)\n"+keycode_get_string(KEY_MASK_CMD)+"Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection");
-
+ button_binds[0] = MENU_TOOL_SELECT;
+ tool_button[TOOL_MODE_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
+ tool_button[TOOL_MODE_SELECT]->set_tooltip("Select Mode (Q)\n" + keycode_get_string(KEY_MASK_CMD) + "Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection");
- tool_button[TOOL_MODE_MOVE] = memnew( ToolButton );
+ tool_button[TOOL_MODE_MOVE] = memnew(ToolButton);
- hbc_menu->add_child( tool_button[TOOL_MODE_MOVE] );
+ hbc_menu->add_child(tool_button[TOOL_MODE_MOVE]);
tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
tool_button[TOOL_MODE_MOVE]->set_flat(true);
- button_binds[0]=MENU_TOOL_MOVE;
- tool_button[TOOL_MODE_MOVE]->connect("pressed", this,"_menu_item_pressed",button_binds);
+ button_binds[0] = MENU_TOOL_MOVE;
+ tool_button[TOOL_MODE_MOVE]->connect("pressed", this, "_menu_item_pressed", button_binds);
tool_button[TOOL_MODE_MOVE]->set_tooltip(TTR("Move Mode (W)"));
- tool_button[TOOL_MODE_ROTATE] = memnew( ToolButton );
- hbc_menu->add_child( tool_button[TOOL_MODE_ROTATE] );
+ tool_button[TOOL_MODE_ROTATE] = memnew(ToolButton);
+ hbc_menu->add_child(tool_button[TOOL_MODE_ROTATE]);
tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
tool_button[TOOL_MODE_ROTATE]->set_flat(true);
- button_binds[0]=MENU_TOOL_ROTATE;
- tool_button[TOOL_MODE_ROTATE]->connect("pressed", this,"_menu_item_pressed",button_binds);
+ button_binds[0] = MENU_TOOL_ROTATE;
+ tool_button[TOOL_MODE_ROTATE]->connect("pressed", this, "_menu_item_pressed", button_binds);
tool_button[TOOL_MODE_ROTATE]->set_tooltip(TTR("Rotate Mode (E)"));
- tool_button[TOOL_MODE_SCALE] = memnew( ToolButton );
- hbc_menu->add_child( tool_button[TOOL_MODE_SCALE] );
+ tool_button[TOOL_MODE_SCALE] = memnew(ToolButton);
+ hbc_menu->add_child(tool_button[TOOL_MODE_SCALE]);
tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
tool_button[TOOL_MODE_SCALE]->set_flat(true);
- button_binds[0]=MENU_TOOL_SCALE;
- tool_button[TOOL_MODE_SCALE]->connect("pressed", this,"_menu_item_pressed",button_binds);
+ button_binds[0] = MENU_TOOL_SCALE;
+ tool_button[TOOL_MODE_SCALE]->connect("pressed", this, "_menu_item_pressed", button_binds);
tool_button[TOOL_MODE_SCALE]->set_tooltip(TTR("Scale Mode (R)"));
- instance_button = memnew( Button );
- hbc_menu->add_child( instance_button );
+ instance_button = memnew(Button);
+ hbc_menu->add_child(instance_button);
instance_button->set_flat(true);
- instance_button->connect("pressed",this,"_instance_scene");
+ instance_button->connect("pressed", this, "_instance_scene");
instance_button->hide();
- VSeparator *vs = memnew( VSeparator );
+ VSeparator *vs = memnew(VSeparator);
hbc_menu->add_child(vs);
- tool_button[TOOL_MODE_LIST_SELECT] = memnew( ToolButton );
- hbc_menu->add_child( tool_button[TOOL_MODE_LIST_SELECT] );
+ tool_button[TOOL_MODE_LIST_SELECT] = memnew(ToolButton);
+ hbc_menu->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
- button_binds[0]=MENU_TOOL_LIST_SELECT;
- tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds);
+ button_binds[0] = MENU_TOOL_LIST_SELECT;
+ tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this, "_menu_item_pressed", button_binds);
tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip(TTR("Show a list of all objects at the position clicked\n(same as Alt+RMB in select mode)."));
- vs = memnew( VSeparator );
+ vs = memnew(VSeparator);
hbc_menu->add_child(vs);
-
- ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT+KEY_KP_7);
+ ED_SHORTCUT("spatial_editor/bottom_view", TTR("Bottom View"), KEY_MASK_ALT + KEY_KP_7);
ED_SHORTCUT("spatial_editor/top_view", TTR("Top View"), KEY_KP_7);
- ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT+KEY_KP_1);
+ ED_SHORTCUT("spatial_editor/rear_view", TTR("Rear View"), KEY_MASK_ALT + KEY_KP_1);
ED_SHORTCUT("spatial_editor/front_view", TTR("Front View"), KEY_KP_1);
- ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT+KEY_KP_3);
+ ED_SHORTCUT("spatial_editor/left_view", TTR("Left View"), KEY_MASK_ALT + KEY_KP_3);
ED_SHORTCUT("spatial_editor/right_view", TTR("Right View"), KEY_KP_3);
ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTR("Switch Perspective/Orthogonal view"), KEY_KP_5);
ED_SHORTCUT("spatial_editor/snap", TTR("Snap"), KEY_S);
ED_SHORTCUT("spatial_editor/insert_anim_key", TTR("Insert Animation Key"), KEY_K);
ED_SHORTCUT("spatial_editor/focus_origin", TTR("Focus Origin"), KEY_O);
ED_SHORTCUT("spatial_editor/focus_selection", TTR("Focus Selection"), KEY_F);
- ED_SHORTCUT("spatial_editor/align_selection_with_view", TTR("Align Selection With View"), KEY_MASK_ALT+KEY_MASK_CMD+KEY_F);
-
+ ED_SHORTCUT("spatial_editor/align_selection_with_view", TTR("Align Selection With View"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_F);
PopupMenu *p;
- transform_menu = memnew( MenuButton );
+ transform_menu = memnew(MenuButton);
transform_menu->set_text(TTR("Transform"));
- hbc_menu->add_child( transform_menu );
+ hbc_menu->add_child(transform_menu);
p = transform_menu->get_popup();
p->add_check_shortcut(ED_SHORTCUT("spatial_editor/use_snap", TTR("Use Snap")), MENU_TRANSFORM_USE_SNAP);
@@ -3821,12 +3559,12 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
p->add_separator();
p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTR("Transform Dialog..")), MENU_TRANSFORM_DIALOG);
- p->connect("id_pressed", this,"_menu_item_pressed");
+ p->connect("id_pressed", this, "_menu_item_pressed");
- view_menu = memnew( MenuButton );
+ view_menu = memnew(MenuButton);
view_menu->set_text(TTR("View"));
- view_menu->set_pos( Point2( 212,0) );
- hbc_menu->add_child( view_menu );
+ view_menu->set_pos(Point2(212, 0));
+ hbc_menu->add_child(view_menu);
p = view_menu->get_popup();
@@ -3834,12 +3572,12 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
p->add_check_shortcut(ED_SHORTCUT("spatial_editor/use_default_srgb", TTR("Use Default sRGB")), MENU_VIEW_USE_DEFAULT_SRGB);
p->add_separator();
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD+KEY_1), MENU_VIEW_USE_1_VIEWPORT);
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD+KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KEY_MASK_ALT+KEY_MASK_CMD+KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"),KEY_MASK_CMD+KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KEY_MASK_ALT+KEY_MASK_CMD+KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
- p->add_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD+KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTR("1 Viewport"), KEY_MASK_CMD + KEY_1), MENU_VIEW_USE_1_VIEWPORT);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTR("2 Viewports"), KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTR("2 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_2), MENU_VIEW_USE_2_VIEWPORTS_ALT);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTR("3 Viewports"), KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTR("3 Viewports (Alt)"), KEY_MASK_ALT + KEY_MASK_CMD + KEY_3), MENU_VIEW_USE_3_VIEWPORTS_ALT);
+ p->add_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTR("4 Viewports"), KEY_MASK_CMD + KEY_4), MENU_VIEW_USE_4_VIEWPORTS);
p->add_separator();
p->add_check_shortcut(ED_SHORTCUT("spatial_editor/display_normal", TTR("Display Normal")), MENU_VIEW_DISPLAY_NORMAL);
@@ -3852,212 +3590,195 @@ SpatialEditor::SpatialEditor(EditorNode *p_editor) {
p->add_separator();
p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTR("Settings")), MENU_VIEW_CAMERA_SETTINGS);
+ p->set_item_checked(p->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), true);
+ p->set_item_checked(p->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true);
+ p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
+ p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
- p->set_item_checked( p->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), true );
- p->set_item_checked( p->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true );
- p->set_item_checked( p->get_item_index(MENU_VIEW_ORIGIN), true );
- p->set_item_checked( p->get_item_index(MENU_VIEW_GRID), true );
-
-
- p->connect("id_pressed", this,"_menu_item_pressed");
-
+ p->connect("id_pressed", this, "_menu_item_pressed");
/* REST OF MENU */
- palette_split = memnew( HSplitContainer);
+ palette_split = memnew(HSplitContainer);
palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(palette_split);
- shader_split = memnew( VSplitContainer );
+ shader_split = memnew(VSplitContainer);
shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
palette_split->add_child(shader_split);
- viewport_base = memnew( Control );
+ viewport_base = memnew(Control);
shader_split->add_child(viewport_base);
viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- viewports[i] = memnew( SpatialEditorViewport(this,editor,i) );
- viewports[i]->connect("toggle_maximize_view",this,"_toggle_maximize_view");
+ viewports[i] = memnew(SpatialEditorViewport(this, editor, i));
+ viewports[i]->connect("toggle_maximize_view", this, "_toggle_maximize_view");
viewport_base->add_child(viewports[i]);
}
//vbc->add_child(viewport_base);
-
-
-
/* SNAP DIALOG */
- snap_dialog = memnew( ConfirmationDialog );
+ snap_dialog = memnew(ConfirmationDialog);
snap_dialog->set_title(TTR("Snap Settings"));
add_child(snap_dialog);
- VBoxContainer *snap_dialog_vbc = memnew( VBoxContainer );
+ VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
snap_dialog->add_child(snap_dialog_vbc);
//snap_dialog->set_child_rect(snap_dialog_vbc);
- snap_translate = memnew( LineEdit );
+ snap_translate = memnew(LineEdit);
snap_translate->set_text("1");
- snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"),snap_translate);
+ snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
- snap_rotate = memnew( LineEdit );
+ snap_rotate = memnew(LineEdit);
snap_rotate->set_text("5");
- snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"),snap_rotate);
+ snap_dialog_vbc->add_margin_child(TTR("Rotate Snap (deg.):"), snap_rotate);
- snap_scale = memnew( LineEdit );
+ snap_scale = memnew(LineEdit);
snap_scale->set_text("5");
- snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"),snap_scale);
+ snap_dialog_vbc->add_margin_child(TTR("Scale Snap (%):"), snap_scale);
/* SETTINGS DIALOG */
- settings_dialog = memnew( ConfirmationDialog );
+ settings_dialog = memnew(ConfirmationDialog);
settings_dialog->set_title(TTR("Viewport Settings"));
add_child(settings_dialog);
- settings_vbc = memnew( VBoxContainer );
- settings_vbc->set_custom_minimum_size(Size2(200,0));
+ settings_vbc = memnew(VBoxContainer);
+ settings_vbc->set_custom_minimum_size(Size2(200, 0));
settings_dialog->add_child(settings_vbc);
//settings_dialog->set_child_rect(settings_vbc);
-
-
- settings_light_base = memnew( ViewportContainer );
- settings_light_base->set_custom_minimum_size(Size2(128,128));
- settings_light_base->connect("gui_input",this,"_default_light_angle_input");
- settings_vbc->add_margin_child(TTR("Default Light Normal:"),settings_light_base);
- settings_light_vp = memnew( Viewport );
+ settings_light_base = memnew(ViewportContainer);
+ settings_light_base->set_custom_minimum_size(Size2(128, 128));
+ settings_light_base->connect("gui_input", this, "_default_light_angle_input");
+ settings_vbc->add_margin_child(TTR("Default Light Normal:"), settings_light_base);
+ settings_light_vp = memnew(Viewport);
settings_light_vp->set_disable_input(true);
settings_light_vp->set_use_own_world(true);
settings_light_base->add_child(settings_light_vp);
- settings_dlight = memnew( DirectionalLight );
+ settings_dlight = memnew(DirectionalLight);
settings_light_vp->add_child(settings_dlight);
- settings_sphere = memnew( ImmediateGeometry );
- settings_sphere->begin(Mesh::PRIMITIVE_TRIANGLES,Ref<Texture>());
- settings_sphere->set_color(Color(1,1,1));
- settings_sphere->add_sphere(32,16,1);
+ settings_sphere = memnew(ImmediateGeometry);
+ settings_sphere->begin(Mesh::PRIMITIVE_TRIANGLES, Ref<Texture>());
+ settings_sphere->set_color(Color(1, 1, 1));
+ settings_sphere->add_sphere(32, 16, 1);
settings_sphere->end();
settings_light_vp->add_child(settings_sphere);
- settings_camera = memnew( Camera );
+ settings_camera = memnew(Camera);
settings_light_vp->add_child(settings_camera);
- settings_camera->set_translation(Vector3(0,0,2));
- settings_camera->set_orthogonal(2.1,0.1,5);
-
- settings_default_light_rot_x=Math_PI*0.3;
- settings_default_light_rot_y=Math_PI*0.2;
-
-
+ settings_camera->set_translation(Vector3(0, 0, 2));
+ settings_camera->set_orthogonal(2.1, 0.1, 5);
- settings_ambient_color = memnew( ColorPickerButton );
- settings_vbc->add_margin_child(TTR("Ambient Light Color:"),settings_ambient_color);
- settings_ambient_color->connect("color_changed",this,"_update_ambient_light_color");
- settings_ambient_color->set_pick_color(Color(0.15,0.15,0.15));
+ settings_default_light_rot_x = Math_PI * 0.3;
+ settings_default_light_rot_y = Math_PI * 0.2;
+ settings_ambient_color = memnew(ColorPickerButton);
+ settings_vbc->add_margin_child(TTR("Ambient Light Color:"), settings_ambient_color);
+ settings_ambient_color->connect("color_changed", this, "_update_ambient_light_color");
+ settings_ambient_color->set_pick_color(Color(0.15, 0.15, 0.15));
- settings_fov = memnew( SpinBox );
+ settings_fov = memnew(SpinBox);
settings_fov->set_max(179);
settings_fov->set_min(1);
settings_fov->set_step(0.01);
- settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov",60.0));
- settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"),settings_fov);
+ settings_fov->set_value(EDITOR_DEF("editors/3d/default_fov", 60.0));
+ settings_vbc->add_margin_child(TTR("Perspective FOV (deg.):"), settings_fov);
- settings_znear = memnew( SpinBox );
+ settings_znear = memnew(SpinBox);
settings_znear->set_max(10000);
settings_znear->set_min(0.1);
settings_znear->set_step(0.01);
- settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near",0.1));
- settings_vbc->add_margin_child(TTR("View Z-Near:"),settings_znear);
+ settings_znear->set_value(EDITOR_DEF("editors/3d/default_z_near", 0.1));
+ settings_vbc->add_margin_child(TTR("View Z-Near:"), settings_znear);
- settings_zfar = memnew( SpinBox );
+ settings_zfar = memnew(SpinBox);
settings_zfar->set_max(10000);
settings_zfar->set_min(0.1);
settings_zfar->set_step(0.01);
- settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far",1500));
- settings_vbc->add_margin_child(TTR("View Z-Far:"),settings_zfar);
+ settings_zfar->set_value(EDITOR_DEF("editors/3d/default_z_far", 1500));
+ settings_vbc->add_margin_child(TTR("View Z-Far:"), settings_zfar);
//settings_dialog->get_cancel()->hide();
/* XFORM DIALOG */
- xform_dialog = memnew( ConfirmationDialog );
+ xform_dialog = memnew(ConfirmationDialog);
xform_dialog->set_title(TTR("Transform Change"));
add_child(xform_dialog);
Label *l = memnew(Label);
l->set_text(TTR("Translate:"));
- l->set_pos(Point2(5,5));
+ l->set_pos(Point2(5, 5));
xform_dialog->add_child(l);
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- xform_translate[i] = memnew( LineEdit );
- xform_translate[i]->set_pos( Point2(15+i*60,22) );
- xform_translate[i]->set_size( Size2(50,12 ) );
- xform_dialog->add_child( xform_translate[i] );
+ xform_translate[i] = memnew(LineEdit);
+ xform_translate[i]->set_pos(Point2(15 + i * 60, 22));
+ xform_translate[i]->set_size(Size2(50, 12));
+ xform_dialog->add_child(xform_translate[i]);
}
l = memnew(Label);
l->set_text(TTR("Rotate (deg.):"));
- l->set_pos(Point2(5,45));
+ l->set_pos(Point2(5, 45));
xform_dialog->add_child(l);
- for(int i=0;i<3;i++) {
- xform_rotate[i] = memnew( LineEdit );
- xform_rotate[i]->set_pos( Point2(15+i*60,62) );
- xform_rotate[i]->set_size( Size2(50,22 ) );
+ for (int i = 0; i < 3; i++) {
+ xform_rotate[i] = memnew(LineEdit);
+ xform_rotate[i]->set_pos(Point2(15 + i * 60, 62));
+ xform_rotate[i]->set_size(Size2(50, 22));
xform_dialog->add_child(xform_rotate[i]);
}
l = memnew(Label);
l->set_text(TTR("Scale (ratio):"));
- l->set_pos(Point2(5,85));
+ l->set_pos(Point2(5, 85));
xform_dialog->add_child(l);
- for(int i=0;i<3;i++) {
- xform_scale[i] = memnew( LineEdit );
- xform_scale[i]->set_pos( Point2(15+i*60,102) );
- xform_scale[i]->set_size( Size2(50,22 ) );
+ for (int i = 0; i < 3; i++) {
+ xform_scale[i] = memnew(LineEdit);
+ xform_scale[i]->set_pos(Point2(15 + i * 60, 102));
+ xform_scale[i]->set_size(Size2(50, 22));
xform_dialog->add_child(xform_scale[i]);
}
l = memnew(Label);
l->set_text(TTR("Transform Type"));
- l->set_pos(Point2(5,125));
+ l->set_pos(Point2(5, 125));
xform_dialog->add_child(l);
- xform_type = memnew( OptionButton );
- xform_type->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- xform_type->set_begin( Point2(15,142) );
- xform_type->set_end( Point2(15,75) );
+ xform_type = memnew(OptionButton);
+ xform_type->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ xform_type->set_begin(Point2(15, 142));
+ xform_type->set_end(Point2(15, 75));
xform_type->add_item(TTR("Pre"));
xform_type->add_item(TTR("Post"));
xform_dialog->add_child(xform_type);
- xform_dialog->connect("confirmed", this,"_xform_dialog_action");
+ xform_dialog->connect("confirmed", this, "_xform_dialog_action");
- scenario_debug=VisualServer::SCENARIO_DEBUG_DISABLED;
+ scenario_debug = VisualServer::SCENARIO_DEBUG_DISABLED;
- selected=NULL;
+ selected = NULL;
set_process_unhandled_key_input(true);
add_to_group("_spatial_editor_group");
- EDITOR_DEF("editors/3d/manipulator_gizmo_size",80);
- EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT,"editors/3d/manipulator_gizmo_size",PROPERTY_HINT_RANGE,"16,1024,1"));
- EDITOR_DEF("editors/3d/manipulator_gizmo_opacity",0.2);
+ EDITOR_DEF("editors/3d/manipulator_gizmo_size", 80);
+ EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, "editors/3d/manipulator_gizmo_size", PROPERTY_HINT_RANGE, "16,1024,1"));
+ EDITOR_DEF("editors/3d/manipulator_gizmo_opacity", 0.2);
- over_gizmo_handle=-1;
+ over_gizmo_handle = -1;
}
SpatialEditor::~SpatialEditor() {
-
-
}
-
-
-
void SpatialEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
-
spatial_editor->show();
spatial_editor->set_process(true);
//VisualServer::get_singleton()->viewport_set_hide_scenario(editor->get_scene_root()->get_viewport(),false);
@@ -4068,9 +3789,7 @@ void SpatialEditorPlugin::make_visible(bool p_visible) {
spatial_editor->hide();
spatial_editor->set_process(false);
//VisualServer::get_singleton()->viewport_set_hide_scenario(editor->get_scene_root()->get_viewport(),true);
-
}
-
}
void SpatialEditorPlugin::edit(Object *p_object) {
@@ -4086,46 +3805,39 @@ Dictionary SpatialEditorPlugin::get_state() const {
return spatial_editor->get_state();
}
-void SpatialEditorPlugin::set_state(const Dictionary& p_state) {
+void SpatialEditorPlugin::set_state(const Dictionary &p_state) {
spatial_editor->set_state(p_state);
}
-void SpatialEditor::snap_cursor_to_plane(const Plane& p_plane) {
+void SpatialEditor::snap_cursor_to_plane(const Plane &p_plane) {
//cursor.pos=p_plane.project(cursor.pos);
}
void SpatialEditorPlugin::_bind_methods() {
- ClassDB::bind_method("snap_cursor_to_plane",&SpatialEditorPlugin::snap_cursor_to_plane);
-
+ ClassDB::bind_method("snap_cursor_to_plane", &SpatialEditorPlugin::snap_cursor_to_plane);
}
-void SpatialEditorPlugin::snap_cursor_to_plane(const Plane& p_plane) {
-
+void SpatialEditorPlugin::snap_cursor_to_plane(const Plane &p_plane) {
spatial_editor->snap_cursor_to_plane(p_plane);
}
-
-
-
SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- spatial_editor = memnew( SpatialEditor(p_node) );
+ editor = p_node;
+ spatial_editor = memnew(SpatialEditor(p_node));
spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
editor->get_viewport()->add_child(spatial_editor);
//spatial_editor->set_area_as_parent_rect();
spatial_editor->hide();
- spatial_editor->connect("transform_key_request",editor,"_transform_keyed");
+ spatial_editor->connect("transform_key_request", editor, "_transform_keyed");
//spatial_editor->set_process(true);
}
-
SpatialEditorPlugin::~SpatialEditorPlugin() {
-
}
diff --git a/editor/plugins/spatial_editor_plugin.h b/editor/plugins/spatial_editor_plugin.h
index 44ce4a0281..e0d2a38956 100644
--- a/editor/plugins/spatial_editor_plugin.h
+++ b/editor/plugins/spatial_editor_plugin.h
@@ -29,11 +29,11 @@
#ifndef SPATIAL_EDITOR_PLUGIN_H
#define SPATIAL_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/3d/visual_instance.h"
+#include "editor/editor_plugin.h"
#include "scene/3d/immediate_geometry.h"
#include "scene/3d/light.h"
+#include "scene/3d/visual_instance.h"
#include "scene/gui/panel_container.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -45,29 +45,28 @@ class SpatialEditorGizmos;
class SpatialEditorGizmo : public SpatialGizmo {
- GDCLASS(SpatialEditorGizmo,SpatialGizmo);
+ GDCLASS(SpatialEditorGizmo, SpatialGizmo);
bool selected;
-public:
- void set_selected(bool p_selected) { selected=p_selected; }
+public:
+ void set_selected(bool p_selected) { selected = p_selected; }
bool is_selected() const { return selected; }
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
- virtual bool intersect_frustum(const Camera *p_camera,const Vector<Plane> &p_frustum);
- virtual bool intersect_ray(const Camera *p_camera,const Point2& p_point, Vector3& r_pos, Vector3& r_normal,int *r_gizmo_handle=NULL,bool p_sec_first=false);
+ virtual bool intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum);
+ virtual bool intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false);
SpatialEditorGizmo();
};
-
class SpatialEditorViewport : public Control {
- GDCLASS( SpatialEditorViewport, Control );
-friend class SpatialEditor;
+ GDCLASS(SpatialEditorViewport, Control);
+ friend class SpatialEditor;
enum {
VIEW_TOP,
@@ -85,12 +84,14 @@ friend class SpatialEditor;
VIEW_AUDIO_LISTENER,
VIEW_GIZMOS,
};
+
public:
enum {
- GIZMO_BASE_LAYER=27,
- GIZMO_EDIT_LAYER=26,
- GIZMO_GRID_LAYER=25
+ GIZMO_BASE_LAYER = 27,
+ GIZMO_EDIT_LAYER = 26,
+ GIZMO_GRID_LAYER = 25
};
+
private:
int index;
String name;
@@ -114,31 +115,31 @@ private:
struct _RayResult {
- Spatial* item;
+ Spatial *item;
float depth;
int handle;
- _FORCE_INLINE_ bool operator<(const _RayResult& p_rr) const { return depth<p_rr.depth; }
+ _FORCE_INLINE_ bool operator<(const _RayResult &p_rr) const { return depth < p_rr.depth; }
};
void _update_name();
- void _compute_edit(const Point2& p_point);
+ void _compute_edit(const Point2 &p_point);
void _clear_selected();
- void _select_clicked(bool p_append,bool p_single);
- void _select(Spatial *p_node, bool p_append,bool p_single);
- ObjectID _select_ray(const Point2& p_pos, bool p_append,bool &r_includes_current,int *r_gizmo_handle=NULL,bool p_alt_select=false);
- void _find_items_at_pos(const Point2& p_pos,bool &r_includes_current,Vector<_RayResult> &results,bool p_alt_select=false);
- Vector3 _get_ray_pos(const Vector2& p_pos) const;
- Vector3 _get_ray(const Vector2& p_pos);
- Point2 _point_to_screen(const Vector3& p_point);
+ void _select_clicked(bool p_append, bool p_single);
+ void _select(Spatial *p_node, bool p_append, bool p_single);
+ ObjectID _select_ray(const Point2 &p_pos, bool p_append, bool &r_includes_current, int *r_gizmo_handle = NULL, bool p_alt_select = false);
+ void _find_items_at_pos(const Point2 &p_pos, bool &r_includes_current, Vector<_RayResult> &results, bool p_alt_select = false);
+ Vector3 _get_ray_pos(const Vector2 &p_pos) const;
+ Vector3 _get_ray(const Vector2 &p_pos);
+ Point2 _point_to_screen(const Vector3 &p_point);
Transform _get_camera_transform() const;
int get_selected_count() const;
Vector3 _get_camera_pos() const;
Vector3 _get_camera_normal() const;
- Vector3 _get_screen_to_space(const Vector3& p_vector3);
+ Vector3 _get_screen_to_space(const Vector3 &p_vector3);
void _select_region();
- bool _gizmo_select(const Vector2& p_screenpos,bool p_hilite_only=false);
+ bool _gizmo_select(const Vector2 &p_screenpos, bool p_hilite_only = false);
float get_znear() const;
float get_zfar() const;
@@ -204,32 +205,35 @@ private:
Vector3 cursor_pos;
Vector3 pos;
- float x_rot,y_rot,distance;
+ float x_rot, y_rot, distance;
bool region_select;
- Point2 region_begin,region_end;
+ Point2 region_begin, region_end;
- Cursor() { x_rot=y_rot=0.5; distance=4; region_select=false; }
+ Cursor() {
+ x_rot = y_rot = 0.5;
+ distance = 4;
+ region_select = false;
+ }
} cursor;
RID move_gizmo_instance[3], rotate_gizmo_instance[3];
-
String last_message;
String message;
float message_time;
- void set_message(String p_message,float p_time=5);
+ void set_message(String p_message, float p_time = 5);
//
void _update_camera();
void _draw();
void _smouseenter();
- void _sinput(const InputEvent& p_ie);
+ void _sinput(const InputEvent &p_ie);
SpatialEditor *spatial_editor;
- Camera* previewing;
- Camera* preview;
+ Camera *previewing;
+ Camera *preview;
void _preview_exited_scene();
void _toggle_camera_preview(bool);
@@ -239,17 +243,15 @@ private:
void _selection_menu_hide();
void _list_select(InputEventMouseButton b);
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void update_transform_gizmo_view();
- void set_can_preview(Camera* p_preview);
- void set_state(const Dictionary& p_state);
+ void set_can_preview(Camera *p_preview);
+ void set_state(const Dictionary &p_state);
Dictionary get_state() const;
void reset();
@@ -257,33 +259,29 @@ public:
Viewport *get_viewport_node() { return viewport; }
-
- SpatialEditorViewport(SpatialEditor *p_spatial_editor,EditorNode *p_editor,int p_index);
+ SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index);
};
-
-
class SpatialEditorSelectedItem : public Object {
- GDCLASS(SpatialEditorSelectedItem,Object);
+ GDCLASS(SpatialEditorSelectedItem, Object);
public:
-
Rect3 aabb;
Transform original; // original location when moving
Transform last_xform; // last transform
Spatial *sp;
RID sbox_instance;
- SpatialEditorSelectedItem() { sp=NULL; }
+ SpatialEditorSelectedItem() { sp = NULL; }
~SpatialEditorSelectedItem();
};
class SpatialEditor : public VBoxContainer {
- GDCLASS(SpatialEditor, VBoxContainer );
-public:
+ GDCLASS(SpatialEditor, VBoxContainer);
+public:
enum ToolMode {
TOOL_MODE_SELECT,
@@ -295,13 +293,10 @@ public:
};
-
private:
EditorNode *editor;
EditorSelection *editor_selection;
-
-
Control *viewport_base;
SpatialEditorViewport *viewports[4];
VSplitContainer *shader_split;
@@ -312,14 +307,12 @@ private:
ToolMode tool_mode;
bool orthogonal;
-
VisualServer::ScenarioDebugMode scenario_debug;
RID light;
RID light_instance;
Transform light_transform;
-
RID origin;
RID origin_instance;
RID grid[3];
@@ -333,11 +326,8 @@ private:
Ref<FixedSpatialMaterial> gizmo_color[3];
Ref<FixedSpatialMaterial> gizmo_hl;
-
int over_gizmo_handle;
-
-
Ref<Mesh> selection_box;
RID indicators;
RID indicators_instance;
@@ -346,7 +336,7 @@ private:
Ref<FixedSpatialMaterial> indicator_mat;
Ref<FixedSpatialMaterial> cursor_material;
-/*
+ /*
struct Selected {
AABB aabb;
Transform original; // original location when moving
@@ -364,9 +354,6 @@ private:
Transform transform;
} gizmo;
-
-
-
enum MenuOption {
MENU_TOOL_SELECT,
@@ -396,13 +383,11 @@ private:
};
-
Button *tool_button[TOOL_MAX];
Button *instance_button;
-
- MenuButton* transform_menu;
- MenuButton* view_menu;
+ MenuButton *transform_menu;
+ MenuButton *view_menu;
ConfirmationDialog *snap_dialog;
ConfirmationDialog *xform_dialog;
@@ -412,7 +397,7 @@ private:
LineEdit *snap_translate;
LineEdit *snap_rotate;
LineEdit *snap_scale;
- PanelContainer* menu_panel;
+ PanelContainer *menu_panel;
LineEdit *xform_translate[3];
LineEdit *xform_rotate[3];
@@ -434,16 +419,13 @@ private:
ColorPickerButton *settings_ambient_color;
Image settings_light_dir_image;
-
void _xform_dialog_action();
void _menu_item_pressed(int p_option);
HBoxContainer *hbc_menu;
-
-
-//
-//
+ //
+ //
void _generate_selection_box();
UndoRedo *undo_redo;
@@ -451,7 +433,7 @@ private:
void _init_indicators();
void _finish_indicators();
- void _toggle_maximize_view(Object* p_viewport);
+ void _toggle_maximize_view(Object *p_viewport);
Node *custom_camera;
@@ -461,33 +443,28 @@ private:
Spatial *selected;
- void _request_gizmo(Object* p_obj);
+ void _request_gizmo(Object *p_obj);
static SpatialEditor *singleton;
- void _node_removed(Node* p_node);
+ void _node_removed(Node *p_node);
SpatialEditorGizmos *gizmos;
SpatialEditor();
- void _update_ambient_light_color(const Color& p_color);
+ void _update_ambient_light_color(const Color &p_color);
void _update_default_light_angle();
- void _default_light_angle_input(const InputEvent& p_event);
+ void _default_light_angle_input(const InputEvent &p_event);
protected:
-
-
-
-
void _notification(int p_what);
//void _gui_input(InputEvent p_event);
void _unhandled_key_input(InputEvent p_event);
static void _bind_methods();
-public:
-
+public:
static SpatialEditor *get_singleton() { return singleton; }
- void snap_cursor_to_plane(const Plane& p_plane);
+ void snap_cursor_to_plane(const Plane &p_plane);
float get_znear() const { return settings_znear->get_value(); }
float get_zfar() const { return settings_zfar->get_value(); }
@@ -508,11 +485,11 @@ public:
void update_transform_gizmo();
void select_gizmo_hilight_axis(int p_axis);
- void set_custom_camera(Node *p_camera) { custom_camera=p_camera; }
+ void set_custom_camera(Node *p_camera) { custom_camera = p_camera; }
- void set_undo_redo(UndoRedo *p_undo_redo) {undo_redo=p_undo_redo; }
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
Dictionary get_state() const;
- void set_state(const Dictionary& p_state);
+ void set_state(const Dictionary &p_state);
Ref<Environment> get_viewport_environment() { return viewport_environment; }
@@ -526,12 +503,12 @@ public:
Spatial *get_selected() { return selected; }
int get_over_gizmo_handle() const { return over_gizmo_handle; }
- void set_over_gizmo_handle(int idx) { over_gizmo_handle=idx; }
+ void set_over_gizmo_handle(int idx) { over_gizmo_handle = idx; }
- void set_can_preview(Camera* p_preview);
+ void set_can_preview(Camera *p_preview);
SpatialEditorViewport *get_editor_viewport(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,4,NULL);
+ ERR_FAIL_INDEX_V(p_idx, 4, NULL);
return viewports[p_idx];
}
@@ -544,15 +521,16 @@ public:
class SpatialEditorPlugin : public EditorPlugin {
- GDCLASS( SpatialEditorPlugin, EditorPlugin );
+ GDCLASS(SpatialEditorPlugin, EditorPlugin);
SpatialEditor *spatial_editor;
EditorNode *editor;
+
protected:
static void _bind_methods();
-public:
- void snap_cursor_to_plane(const Plane& p_plane);
+public:
+ void snap_cursor_to_plane(const Plane &p_plane);
SpatialEditor *get_spatial_editor() { return spatial_editor; }
virtual String get_name() const { return "3D"; }
@@ -562,13 +540,11 @@ public:
virtual bool handles(Object *p_object) const;
virtual Dictionary get_state() const;
- virtual void set_state(const Dictionary& p_state);
+ virtual void set_state(const Dictionary &p_state);
virtual void clear() { spatial_editor->clear(); }
-
SpatialEditorPlugin(EditorNode *p_node);
~SpatialEditorPlugin();
-
};
#endif
diff --git a/editor/plugins/sprite_frames_editor_plugin.cpp b/editor/plugins/sprite_frames_editor_plugin.cpp
index 44d6d3c6e1..7adfb90e6f 100644
--- a/editor/plugins/sprite_frames_editor_plugin.cpp
+++ b/editor/plugins/sprite_frames_editor_plugin.cpp
@@ -28,51 +28,44 @@
/*************************************************************************/
#include "sprite_frames_editor_plugin.h"
-#include "io/resource_loader.h"
-#include "global_config.h"
#include "editor/editor_settings.h"
+#include "global_config.h"
+#include "io/resource_loader.h"
#include "scene/3d/sprite_3d.h"
-
-
void SpriteFramesEditor::_gui_input(InputEvent p_event) {
-
-
}
void SpriteFramesEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
-
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
- load->set_icon( get_icon("Folder","EditorIcons") );
- _delete->set_icon( get_icon("Del","EditorIcons") );
- new_anim->set_icon( get_icon("New","EditorIcons") );
- remove_anim->set_icon( get_icon("Del","EditorIcons") );
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ load->set_icon(get_icon("Folder", "EditorIcons"));
+ _delete->set_icon(get_icon("Del", "EditorIcons"));
+ new_anim->set_icon(get_icon("New", "EditorIcons"));
+ remove_anim->set_icon(get_icon("Del", "EditorIcons"));
}
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
//NodePath("/root")->connect("node_removed", this,"_node_removed",Vector<Variant>(),true);
}
- if (p_what==NOTIFICATION_DRAW) {
-
+ if (p_what == NOTIFICATION_DRAW) {
}
}
-void SpriteFramesEditor::_file_load_request(const PoolVector<String>& p_path,int p_at_pos) {
+void SpriteFramesEditor::_file_load_request(const PoolVector<String> &p_path, int p_at_pos) {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- List< Ref<Texture> > resources;
+ List<Ref<Texture> > resources;
- for(int i=0;i<p_path.size();i++) {
+ for (int i = 0; i < p_path.size(); i++) {
- Ref<Texture> resource;
+ Ref<Texture> resource;
resource = ResourceLoader::load(p_path[i]);
if (resource.is_null()) {
@@ -87,26 +80,24 @@ void SpriteFramesEditor::_file_load_request(const PoolVector<String>& p_path,int
resources.push_back(resource);
}
-
if (resources.empty()) {
//print_line("added frames!");
return;
}
undo_redo->create_action(TTR("Add Frame"));
- int fc=frames->get_frame_count(edited_anim);
+ int fc = frames->get_frame_count(edited_anim);
- int count=0;
+ int count = 0;
- for(List< Ref<Texture> >::Element *E=resources.front();E;E=E->next() ) {
+ for (List<Ref<Texture> >::Element *E = resources.front(); E; E = E->next()) {
- undo_redo->add_do_method(frames,"add_frame",edited_anim,E->get(),p_at_pos==-1?-1:p_at_pos+count);
- undo_redo->add_undo_method(frames,"remove_frame",edited_anim,p_at_pos==-1?fc:p_at_pos);
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, E->get(), p_at_pos == -1 ? -1 : p_at_pos + count);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, p_at_pos == -1 ? fc : p_at_pos);
count++;
-
}
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
//print_line("added frames!");
@@ -115,21 +106,19 @@ void SpriteFramesEditor::_file_load_request(const PoolVector<String>& p_path,int
void SpriteFramesEditor::_load_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- loading_scene=false;
+ loading_scene = false;
file->clear_filters();
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("Texture",&extensions);
- for(int i=0;i<extensions.size();i++)
- file->add_filter("*."+extensions[i]);
+ ResourceLoader::get_recognized_extensions_for_type("Texture", &extensions);
+ for (int i = 0; i < extensions.size(); i++)
+ file->add_filter("*." + extensions[i]);
file->set_mode(EditorFileDialog::MODE_OPEN_FILES);
file->popup_centered_ratio();
-
}
-
void SpriteFramesEditor::_item_edited() {
#if 0
@@ -163,38 +152,35 @@ void SpriteFramesEditor::_item_edited() {
}
#endif
-
}
void SpriteFramesEditor::_delete_confirm_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- if (tree->get_current()<0)
+ if (tree->get_current() < 0)
return;
- sel-=1;
- if (sel<0 && frames->get_frame_count(edited_anim))
- sel=0;
+ sel -= 1;
+ if (sel < 0 && frames->get_frame_count(edited_anim))
+ sel = 0;
int to_remove = tree->get_current();
- sel=to_remove;
- Ref<Texture> r = frames->get_frame(edited_anim,to_remove);
+ sel = to_remove;
+ Ref<Texture> r = frames->get_frame(edited_anim, to_remove);
undo_redo->create_action(TTR("Delete Resource"));
- undo_redo->add_do_method(frames,"remove_frame",edited_anim,to_remove);
- undo_redo->add_undo_method(frames,"add_frame",edited_anim,r,to_remove);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "remove_frame", edited_anim, to_remove);
+ undo_redo->add_undo_method(frames, "add_frame", edited_anim, r, to_remove);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
-
void SpriteFramesEditor::_paste_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- Ref<Texture> r=EditorSettings::get_singleton()->get_resource_clipboard();
+ Ref<Texture> r = EditorSettings::get_singleton()->get_resource_clipboard();
if (!r.is_valid()) {
dialog->set_text(TTR("Resource clipboard is empty or not a texture!"));
dialog->set_title(TTR("Error!"));
@@ -204,131 +190,117 @@ void SpriteFramesEditor::_paste_pressed() {
return; ///beh should show an error i guess
}
-
undo_redo->create_action(TTR("Paste Frame"));
- undo_redo->add_do_method(frames,"add_frame",edited_anim,r);
- undo_redo->add_undo_method(frames,"remove_frame",edited_anim,frames->get_frame_count(edited_anim));
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, r);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, frames->get_frame_count(edited_anim));
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_empty_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- int from=-1;
+ int from = -1;
- if (tree->get_current()>=0) {
+ if (tree->get_current() >= 0) {
from = tree->get_current();
- sel=from;
+ sel = from;
} else {
- from=frames->get_frame_count(edited_anim);
+ from = frames->get_frame_count(edited_anim);
}
-
-
Ref<Texture> r;
undo_redo->create_action(TTR("Add Empty"));
- undo_redo->add_do_method(frames,"add_frame",edited_anim,r,from);
- undo_redo->add_undo_method(frames,"remove_frame",edited_anim,from);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, r, from);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, from);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_empty2_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- int from=-1;
+ int from = -1;
- if (tree->get_current()>=0) {
+ if (tree->get_current() >= 0) {
from = tree->get_current();
- sel=from;
+ sel = from;
} else {
- from=frames->get_frame_count(edited_anim);
+ from = frames->get_frame_count(edited_anim);
}
-
-
Ref<Texture> r;
undo_redo->create_action(TTR("Add Empty"));
- undo_redo->add_do_method(frames,"add_frame",edited_anim,r,from+1);
- undo_redo->add_undo_method(frames,"remove_frame",edited_anim,from+1);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, r, from + 1);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, from + 1);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_up_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- if (tree->get_current()<0)
+ if (tree->get_current() < 0)
return;
int to_move = tree->get_current();
- if (to_move<1)
+ if (to_move < 1)
return;
- sel=to_move;
- sel-=1;
+ sel = to_move;
+ sel -= 1;
- Ref<Texture> r = frames->get_frame(edited_anim,to_move);
+ Ref<Texture> r = frames->get_frame(edited_anim, to_move);
undo_redo->create_action(TTR("Delete Resource"));
- undo_redo->add_do_method(frames,"set_frame",edited_anim,to_move,frames->get_frame(edited_anim,to_move-1));
- undo_redo->add_do_method(frames,"set_frame",edited_anim,to_move-1,frames->get_frame(edited_anim,to_move));
- undo_redo->add_undo_method(frames,"set_frame",edited_anim,to_move,frames->get_frame(edited_anim,to_move));
- undo_redo->add_undo_method(frames,"set_frame",edited_anim,to_move-1,frames->get_frame(edited_anim,to_move-1));
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "set_frame", edited_anim, to_move, frames->get_frame(edited_anim, to_move - 1));
+ undo_redo->add_do_method(frames, "set_frame", edited_anim, to_move - 1, frames->get_frame(edited_anim, to_move));
+ undo_redo->add_undo_method(frames, "set_frame", edited_anim, to_move, frames->get_frame(edited_anim, to_move));
+ undo_redo->add_undo_method(frames, "set_frame", edited_anim, to_move - 1, frames->get_frame(edited_anim, to_move - 1));
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_down_pressed() {
ERR_FAIL_COND(!frames->has_animation(edited_anim));
- if (tree->get_current()<0)
+ if (tree->get_current() < 0)
return;
int to_move = tree->get_current();
- if (to_move<0 || to_move>=frames->get_frame_count(edited_anim)-1)
+ if (to_move < 0 || to_move >= frames->get_frame_count(edited_anim) - 1)
return;
- sel=to_move;
- sel+=1;
+ sel = to_move;
+ sel += 1;
- Ref<Texture> r = frames->get_frame(edited_anim,to_move);
+ Ref<Texture> r = frames->get_frame(edited_anim, to_move);
undo_redo->create_action(TTR("Delete Resource"));
- undo_redo->add_do_method(frames,"set_frame",edited_anim,to_move,frames->get_frame(edited_anim,to_move+1));
- undo_redo->add_do_method(frames,"set_frame",edited_anim,to_move+1,frames->get_frame(edited_anim,to_move));
- undo_redo->add_undo_method(frames,"set_frame",edited_anim,to_move,frames->get_frame(edited_anim,to_move));
- undo_redo->add_undo_method(frames,"set_frame",edited_anim,to_move+1,frames->get_frame(edited_anim,to_move+1));
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "set_frame", edited_anim, to_move, frames->get_frame(edited_anim, to_move + 1));
+ undo_redo->add_do_method(frames, "set_frame", edited_anim, to_move + 1, frames->get_frame(edited_anim, to_move));
+ undo_redo->add_undo_method(frames, "set_frame", edited_anim, to_move, frames->get_frame(edited_anim, to_move));
+ undo_redo->add_undo_method(frames, "set_frame", edited_anim, to_move + 1, frames->get_frame(edited_anim, to_move + 1));
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
-
-
}
-
void SpriteFramesEditor::_delete_pressed() {
-
- if (tree->get_current()<0)
+ if (tree->get_current() < 0)
return;
_delete_confirm_pressed(); //it has undo.. why bother with a dialog..
@@ -339,10 +311,8 @@ void SpriteFramesEditor::_delete_pressed() {
//dialog->get_ok()->show();
dialog->get_ok()->set_text("Remove");
dialog->popup_centered(Size2(300,60));*/
-
}
-
void SpriteFramesEditor::_animation_select() {
if (updating)
@@ -350,41 +320,38 @@ void SpriteFramesEditor::_animation_select() {
TreeItem *selected = animations->get_selected();
ERR_FAIL_COND(!selected);
- edited_anim=selected->get_text(0);
+ edited_anim = selected->get_text(0);
_update_library(true);
-
}
-
-static void _find_anim_sprites(Node* p_node,List<Node*> *r_nodes,Ref<SpriteFrames> p_sfames) {
+static void _find_anim_sprites(Node *p_node, List<Node *> *r_nodes, Ref<SpriteFrames> p_sfames) {
Node *edited = EditorNode::get_singleton()->get_edited_scene();
if (!edited)
return;
- if (p_node!=edited && p_node->get_owner()!=edited)
+ if (p_node != edited && p_node->get_owner() != edited)
return;
{
AnimatedSprite *as = p_node->cast_to<AnimatedSprite>();
- if (as && as->get_sprite_frames()==p_sfames) {
+ if (as && as->get_sprite_frames() == p_sfames) {
r_nodes->push_back(p_node);
}
}
{
AnimatedSprite3D *as = p_node->cast_to<AnimatedSprite3D>();
- if (as && as->get_sprite_frames()==p_sfames) {
+ if (as && as->get_sprite_frames() == p_sfames) {
r_nodes->push_back(p_node);
}
}
- for(int i=0;i<p_node->get_child_count();i++) {
- _find_anim_sprites(p_node->get_child(i),r_nodes,p_sfames);
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ _find_anim_sprites(p_node->get_child(i), r_nodes, p_sfames);
}
-
}
-void SpriteFramesEditor::_animation_name_edited(){
+void SpriteFramesEditor::_animation_name_edited() {
if (updating)
return;
@@ -398,86 +365,77 @@ void SpriteFramesEditor::_animation_name_edited(){
String new_name = edited->get_text(0);
- if (new_name==String(edited_anim))
+ if (new_name == String(edited_anim))
return;
- new_name=new_name.replace("/","_").replace(","," ");
+ new_name = new_name.replace("/", "_").replace(",", " ");
- String name=new_name;
- int counter=0;
- while(frames->has_animation(name)) {
+ String name = new_name;
+ int counter = 0;
+ while (frames->has_animation(name)) {
counter++;
- name=new_name+" "+itos(counter);
+ name = new_name + " " + itos(counter);
}
- List<Node*> nodes;
- _find_anim_sprites(EditorNode::get_singleton()->get_edited_scene(),&nodes,Ref<SpriteFrames>(frames));
+ List<Node *> nodes;
+ _find_anim_sprites(EditorNode::get_singleton()->get_edited_scene(), &nodes, Ref<SpriteFrames>(frames));
undo_redo->create_action(TTR("Rename Animation"));
- undo_redo->add_do_method(frames,"rename_animation",edited_anim,name);
- undo_redo->add_undo_method(frames,"rename_animation",name,edited_anim);
+ undo_redo->add_do_method(frames, "rename_animation", edited_anim, name);
+ undo_redo->add_undo_method(frames, "rename_animation", name, edited_anim);
- for(List<Node*>::Element *E=nodes.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) {
String current = E->get()->call("get_animation");
- if (current!=edited_anim)
+ if (current != edited_anim)
continue;
- undo_redo->add_do_method(E->get(),"set_animation",name);
- undo_redo->add_undo_method(E->get(),"set_animation",edited_anim);
-
+ undo_redo->add_do_method(E->get(), "set_animation", name);
+ undo_redo->add_undo_method(E->get(), "set_animation", edited_anim);
}
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
- edited_anim=new_name;
+ edited_anim = new_name;
undo_redo->commit_action();
-
-
-
}
-void SpriteFramesEditor::_animation_add(){
-
+void SpriteFramesEditor::_animation_add() {
String new_name = "New Anim";
- String name=new_name;
- int counter=0;
- while(frames->has_animation(name)) {
+ String name = new_name;
+ int counter = 0;
+ while (frames->has_animation(name)) {
counter++;
- name=new_name+" "+itos(counter);
+ name = new_name + " " + itos(counter);
}
- List<Node*> nodes;
- _find_anim_sprites(EditorNode::get_singleton()->get_edited_scene(),&nodes,Ref<SpriteFrames>(frames));
-
+ List<Node *> nodes;
+ _find_anim_sprites(EditorNode::get_singleton()->get_edited_scene(), &nodes, Ref<SpriteFrames>(frames));
undo_redo->create_action(TTR("Add Animation"));
- undo_redo->add_do_method(frames,"add_animation",name);
- undo_redo->add_undo_method(frames,"remove_animation",name);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "add_animation", name);
+ undo_redo->add_undo_method(frames, "remove_animation", name);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
-
- for(List<Node*>::Element *E=nodes.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) {
String current = E->get()->call("get_animation");
if (frames->has_animation(current))
continue;
- undo_redo->add_do_method(E->get(),"set_animation",name);
- undo_redo->add_undo_method(E->get(),"set_animation",current);
-
+ undo_redo->add_do_method(E->get(), "set_animation", name);
+ undo_redo->add_undo_method(E->get(), "set_animation", current);
}
- edited_anim=new_name;
+ edited_anim = new_name;
undo_redo->commit_action();
-
}
-void SpriteFramesEditor::_animation_remove(){
+void SpriteFramesEditor::_animation_remove() {
//fuck everything
if (updating)
@@ -486,37 +444,33 @@ void SpriteFramesEditor::_animation_remove(){
if (!frames->has_animation(edited_anim))
return;
-
undo_redo->create_action(TTR("Remove Animation"));
- undo_redo->add_do_method(frames,"remove_animation",edited_anim);
- undo_redo->add_undo_method(frames,"add_animation",edited_anim);
- undo_redo->add_undo_method(frames,"set_animation_speed",edited_anim,frames->get_animation_speed(edited_anim));
- undo_redo->add_undo_method(frames,"set_animation_loop",edited_anim,frames->get_animation_loop(edited_anim));
+ undo_redo->add_do_method(frames, "remove_animation", edited_anim);
+ undo_redo->add_undo_method(frames, "add_animation", edited_anim);
+ undo_redo->add_undo_method(frames, "set_animation_speed", edited_anim, frames->get_animation_speed(edited_anim));
+ undo_redo->add_undo_method(frames, "set_animation_loop", edited_anim, frames->get_animation_loop(edited_anim));
int fc = frames->get_frame_count(edited_anim);
- for(int i=0;i<fc;i++) {
- Ref<Texture> frame = frames->get_frame(edited_anim,i);
- undo_redo->add_undo_method(frames,"add_frame",edited_anim,frame);
+ for (int i = 0; i < fc; i++) {
+ Ref<Texture> frame = frames->get_frame(edited_anim, i);
+ undo_redo->add_undo_method(frames, "add_frame", edited_anim, frame);
}
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
-
void SpriteFramesEditor::_animation_loop_changed() {
if (updating)
return;
undo_redo->create_action(TTR("Change Animation Loop"));
- undo_redo->add_do_method(frames,"set_animation_loop",edited_anim,anim_loop->is_pressed());
- undo_redo->add_undo_method(frames,"set_animation_loop",edited_anim,frames->get_animation_loop(edited_anim));
- undo_redo->add_do_method(this,"_update_library",true);
- undo_redo->add_undo_method(this,"_update_library",true);
+ undo_redo->add_do_method(frames, "set_animation_loop", edited_anim, anim_loop->is_pressed());
+ undo_redo->add_undo_method(frames, "set_animation_loop", edited_anim, frames->get_animation_loop(edited_anim));
+ undo_redo->add_do_method(this, "_update_library", true);
+ undo_redo->add_undo_method(this, "_update_library", true);
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_animation_fps_changed(double p_value) {
@@ -524,24 +478,23 @@ void SpriteFramesEditor::_animation_fps_changed(double p_value) {
if (updating)
return;
- undo_redo->create_action(TTR("Change Animation FPS"),UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(frames,"set_animation_speed",edited_anim,p_value);
- undo_redo->add_undo_method(frames,"set_animation_speed",edited_anim,frames->get_animation_speed(edited_anim));
- undo_redo->add_do_method(this,"_update_library",true);
- undo_redo->add_undo_method(this,"_update_library",true);
+ undo_redo->create_action(TTR("Change Animation FPS"), UndoRedo::MERGE_ENDS);
+ undo_redo->add_do_method(frames, "set_animation_speed", edited_anim, p_value);
+ undo_redo->add_undo_method(frames, "set_animation_speed", edited_anim, frames->get_animation_speed(edited_anim));
+ undo_redo->add_do_method(this, "_update_library", true);
+ undo_redo->add_undo_method(this, "_update_library", true);
undo_redo->commit_action();
-
}
void SpriteFramesEditor::_update_library(bool p_skip_selector) {
- updating=true;
+ updating = true;
if (!p_skip_selector) {
animations->clear();
- TreeItem *anim_root=animations->create_item();
+ TreeItem *anim_root = animations->create_item();
List<StringName> anim_names;
@@ -551,76 +504,69 @@ void SpriteFramesEditor::_update_library(bool p_skip_selector) {
anim_names.sort_custom<StringName::AlphCompare>();
- for(List<StringName>::Element *E=anim_names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anim_names.front(); E; E = E->next()) {
String name = E->get();
TreeItem *it = animations->create_item(anim_root);
- it->set_metadata(0,name);
+ it->set_metadata(0, name);
- it->set_text(0,name);
- it->set_editable(0,true);
+ it->set_text(0, name);
+ it->set_editable(0, true);
- if (E->get()==edited_anim) {
+ if (E->get() == edited_anim) {
it->select(0);
}
}
}
-
tree->clear();
if (!frames->has_animation(edited_anim)) {
- updating=false;
+ updating = false;
return;
}
+ if (sel >= frames->get_frame_count(edited_anim))
+ sel = frames->get_frame_count(edited_anim) - 1;
+ else if (sel < 0 && frames->get_frame_count(edited_anim))
+ sel = 0;
- if (sel>=frames->get_frame_count(edited_anim))
- sel=frames->get_frame_count(edited_anim)-1;
- else if (sel<0 && frames->get_frame_count(edited_anim))
- sel=0;
-
- for(int i=0;i<frames->get_frame_count(edited_anim);i++) {
-
+ for (int i = 0; i < frames->get_frame_count(edited_anim); i++) {
String name;
Ref<Texture> icon;
+ if (frames->get_frame(edited_anim, i).is_null()) {
- if (frames->get_frame(edited_anim,i).is_null()) {
-
- name=itos(i)+": "+TTR("(empty)");
+ name = itos(i) + ": " + TTR("(empty)");
} else {
- name=itos(i)+": "+frames->get_frame(edited_anim,i)->get_name();
- icon=frames->get_frame(edited_anim,i);
+ name = itos(i) + ": " + frames->get_frame(edited_anim, i)->get_name();
+ icon = frames->get_frame(edited_anim, i);
}
- tree->add_item(name,icon);
- if (frames->get_frame(edited_anim,i).is_valid())
- tree->set_item_tooltip(tree->get_item_count()-1,frames->get_frame(edited_anim,i)->get_path());
- if (sel==i)
- tree->select(tree->get_item_count()-1);
+ tree->add_item(name, icon);
+ if (frames->get_frame(edited_anim, i).is_valid())
+ tree->set_item_tooltip(tree->get_item_count() - 1, frames->get_frame(edited_anim, i)->get_path());
+ if (sel == i)
+ tree->select(tree->get_item_count() - 1);
}
anim_speed->set_value(frames->get_animation_speed(edited_anim));
anim_loop->set_pressed(frames->get_animation_loop(edited_anim));
- updating=false;
+ updating = false;
//player->add_resource("default",resource);
}
+void SpriteFramesEditor::edit(SpriteFrames *p_frames) {
-
-void SpriteFramesEditor::edit(SpriteFrames* p_frames) {
-
- if (frames==p_frames)
+ if (frames == p_frames)
return;
- frames=p_frames;
-
+ frames = p_frames;
if (p_frames) {
@@ -630,11 +576,10 @@ void SpriteFramesEditor::edit(SpriteFrames* p_frames) {
frames->get_animation_list(&anim_names);
anim_names.sort_custom<StringName::AlphCompare>();
if (anim_names.size()) {
- edited_anim=anim_names.front()->get();
+ edited_anim = anim_names.front()->get();
} else {
- edited_anim=StringName();
+ edited_anim = StringName();
}
-
}
_update_library();
@@ -643,42 +588,38 @@ void SpriteFramesEditor::edit(SpriteFrames* p_frames) {
hide();
//set_fixed_process(false);
}
-
}
-
-Variant SpriteFramesEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant SpriteFramesEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
if (!frames->has_animation(edited_anim))
return false;
- int idx = tree->get_item_at_pos(p_point,true);
+ int idx = tree->get_item_at_pos(p_point, true);
- if (idx<0 || idx>=frames->get_frame_count(edited_anim))
+ if (idx < 0 || idx >= frames->get_frame_count(edited_anim))
return Variant();
- RES frame = frames->get_frame(edited_anim,idx);
+ RES frame = frames->get_frame(edited_anim, idx);
if (frame.is_null())
return Variant();
- return EditorNode::get_singleton()->drag_resource(frame,p_from);
-
-
+ return EditorNode::get_singleton()->drag_resource(frame, p_from);
}
-bool SpriteFramesEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool SpriteFramesEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
Dictionary d = p_data;
if (!d.has("type"))
return false;
- if (d.has("from") && (Object*)(d["from"])==tree)
+ if (d.has("from") && (Object *)(d["from"]) == tree)
return false;
- if (String(d["type"])=="resource" && d.has("resource")) {
- RES r=d["resource"];
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
Ref<Texture> texture = r;
@@ -688,33 +629,30 @@ bool SpriteFramesEditor::can_drop_data_fw(const Point2& p_point,const Variant& p
}
}
-
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
- if (files.size()==0)
+ if (files.size() == 0)
return false;
- for(int i=0;i<files.size();i++) {
+ for (int i = 0; i < files.size(); i++) {
String file = files[0];
String ftype = EditorFileSystem::get_singleton()->get_file_type(file);
- if (!ClassDB::is_parent_class(ftype,"Texture")) {
+ if (!ClassDB::is_parent_class(ftype, "Texture")) {
return false;
}
-
}
return true;
-
}
return false;
}
-void SpriteFramesEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void SpriteFramesEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (!can_drop_data_fw(p_point,p_data,p_from))
+ if (!can_drop_data_fw(p_point, p_data, p_from))
return;
Dictionary d = p_data;
@@ -722,205 +660,188 @@ void SpriteFramesEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
if (!d.has("type"))
return;
- int at_pos = tree->get_item_at_pos(p_point,true);
+ int at_pos = tree->get_item_at_pos(p_point, true);
- if (String(d["type"])=="resource" && d.has("resource")) {
- RES r=d["resource"];
+ if (String(d["type"]) == "resource" && d.has("resource")) {
+ RES r = d["resource"];
Ref<Texture> texture = r;
if (texture.is_valid()) {
undo_redo->create_action(TTR("Add Frame"));
- undo_redo->add_do_method(frames,"add_frame",edited_anim,texture,at_pos==-1?-1:at_pos);
- undo_redo->add_undo_method(frames,"remove_frame",edited_anim,at_pos==-1?frames->get_frame_count(edited_anim):at_pos);
- undo_redo->add_do_method(this,"_update_library");
- undo_redo->add_undo_method(this,"_update_library");
+ undo_redo->add_do_method(frames, "add_frame", edited_anim, texture, at_pos == -1 ? -1 : at_pos);
+ undo_redo->add_undo_method(frames, "remove_frame", edited_anim, at_pos == -1 ? frames->get_frame_count(edited_anim) : at_pos);
+ undo_redo->add_do_method(this, "_update_library");
+ undo_redo->add_undo_method(this, "_update_library");
undo_redo->commit_action();
-
}
}
-
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
PoolVector<String> files = d["files"];
- _file_load_request(files,at_pos);
+ _file_load_request(files, at_pos);
}
-
}
-
void SpriteFramesEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&SpriteFramesEditor::_gui_input);
- ClassDB::bind_method(D_METHOD("_load_pressed"),&SpriteFramesEditor::_load_pressed);
- ClassDB::bind_method(D_METHOD("_empty_pressed"),&SpriteFramesEditor::_empty_pressed);
- ClassDB::bind_method(D_METHOD("_empty2_pressed"),&SpriteFramesEditor::_empty2_pressed);
- ClassDB::bind_method(D_METHOD("_item_edited"),&SpriteFramesEditor::_item_edited);
- ClassDB::bind_method(D_METHOD("_delete_pressed"),&SpriteFramesEditor::_delete_pressed);
- ClassDB::bind_method(D_METHOD("_paste_pressed"),&SpriteFramesEditor::_paste_pressed);
- ClassDB::bind_method(D_METHOD("_delete_confirm_pressed"),&SpriteFramesEditor::_delete_confirm_pressed);
- ClassDB::bind_method(D_METHOD("_file_load_request","files","atpos"),&SpriteFramesEditor::_file_load_request,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("_update_library","skipsel"),&SpriteFramesEditor::_update_library,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("_up_pressed"),&SpriteFramesEditor::_up_pressed);
- ClassDB::bind_method(D_METHOD("_down_pressed"),&SpriteFramesEditor::_down_pressed);
- ClassDB::bind_method(D_METHOD("_animation_select"),&SpriteFramesEditor::_animation_select);
- ClassDB::bind_method(D_METHOD("_animation_name_edited"),&SpriteFramesEditor::_animation_name_edited);
- ClassDB::bind_method(D_METHOD("_animation_add"),&SpriteFramesEditor::_animation_add);
- ClassDB::bind_method(D_METHOD("_animation_remove"),&SpriteFramesEditor::_animation_remove);
- ClassDB::bind_method(D_METHOD("_animation_loop_changed"),&SpriteFramesEditor::_animation_loop_changed);
- ClassDB::bind_method(D_METHOD("_animation_fps_changed"),&SpriteFramesEditor::_animation_fps_changed);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &SpriteFramesEditor::_gui_input);
+ ClassDB::bind_method(D_METHOD("_load_pressed"), &SpriteFramesEditor::_load_pressed);
+ ClassDB::bind_method(D_METHOD("_empty_pressed"), &SpriteFramesEditor::_empty_pressed);
+ ClassDB::bind_method(D_METHOD("_empty2_pressed"), &SpriteFramesEditor::_empty2_pressed);
+ ClassDB::bind_method(D_METHOD("_item_edited"), &SpriteFramesEditor::_item_edited);
+ ClassDB::bind_method(D_METHOD("_delete_pressed"), &SpriteFramesEditor::_delete_pressed);
+ ClassDB::bind_method(D_METHOD("_paste_pressed"), &SpriteFramesEditor::_paste_pressed);
+ ClassDB::bind_method(D_METHOD("_delete_confirm_pressed"), &SpriteFramesEditor::_delete_confirm_pressed);
+ ClassDB::bind_method(D_METHOD("_file_load_request", "files", "atpos"), &SpriteFramesEditor::_file_load_request, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("_update_library", "skipsel"), &SpriteFramesEditor::_update_library, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("_up_pressed"), &SpriteFramesEditor::_up_pressed);
+ ClassDB::bind_method(D_METHOD("_down_pressed"), &SpriteFramesEditor::_down_pressed);
+ ClassDB::bind_method(D_METHOD("_animation_select"), &SpriteFramesEditor::_animation_select);
+ ClassDB::bind_method(D_METHOD("_animation_name_edited"), &SpriteFramesEditor::_animation_name_edited);
+ ClassDB::bind_method(D_METHOD("_animation_add"), &SpriteFramesEditor::_animation_add);
+ ClassDB::bind_method(D_METHOD("_animation_remove"), &SpriteFramesEditor::_animation_remove);
+ ClassDB::bind_method(D_METHOD("_animation_loop_changed"), &SpriteFramesEditor::_animation_loop_changed);
+ ClassDB::bind_method(D_METHOD("_animation_fps_changed"), &SpriteFramesEditor::_animation_fps_changed);
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &SpriteFramesEditor::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &SpriteFramesEditor::can_drop_data_fw);
ClassDB::bind_method(D_METHOD("drop_data_fw"), &SpriteFramesEditor::drop_data_fw);
-
-
}
-
SpriteFramesEditor::SpriteFramesEditor() {
//add_style_override("panel", get_stylebox("panel","Panel"));
- split = memnew( HSplitContainer );
+ split = memnew(HSplitContainer);
add_child(split);
- VBoxContainer *vbc_animlist = memnew( VBoxContainer );
+ VBoxContainer *vbc_animlist = memnew(VBoxContainer);
split->add_child(vbc_animlist);
- vbc_animlist->set_custom_minimum_size(Size2(150,0));
+ vbc_animlist->set_custom_minimum_size(Size2(150, 0));
//vbc_animlist->set_v_size_flags(SIZE_EXPAND_FILL);
-
- VBoxContainer *sub_vb = memnew( VBoxContainer );
- vbc_animlist->add_margin_child(TTR("Animations"),sub_vb,true);
+ VBoxContainer *sub_vb = memnew(VBoxContainer);
+ vbc_animlist->add_margin_child(TTR("Animations"), sub_vb, true);
sub_vb->set_v_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *hbc_animlist = memnew( HBoxContainer );
+ HBoxContainer *hbc_animlist = memnew(HBoxContainer);
sub_vb->add_child(hbc_animlist);
- new_anim = memnew( Button );
+ new_anim = memnew(Button);
hbc_animlist->add_child(new_anim);
- new_anim->connect("pressed",this,"_animation_add");
-
+ new_anim->connect("pressed", this, "_animation_add");
hbc_animlist->add_spacer();
- remove_anim = memnew( Button );
+ remove_anim = memnew(Button);
hbc_animlist->add_child(remove_anim);
- remove_anim->connect("pressed",this,"_animation_remove");
+ remove_anim->connect("pressed", this, "_animation_remove");
- animations = memnew( Tree );
+ animations = memnew(Tree);
sub_vb->add_child(animations);
animations->set_v_size_flags(SIZE_EXPAND_FILL);
animations->set_hide_root(true);
- animations->connect("cell_selected",this,"_animation_select");
- animations->connect("item_edited",this,"_animation_name_edited");
+ animations->connect("cell_selected", this, "_animation_select");
+ animations->connect("item_edited", this, "_animation_name_edited");
animations->set_single_select_cell_editing_only_when_already_selected(true);
-
- anim_speed = memnew( SpinBox);
- vbc_animlist->add_margin_child(TTR("Speed (FPS):"),anim_speed);
+ anim_speed = memnew(SpinBox);
+ vbc_animlist->add_margin_child(TTR("Speed (FPS):"), anim_speed);
anim_speed->set_min(0);
anim_speed->set_max(100);
anim_speed->set_step(0.01);
- anim_speed->connect("value_changed",this,"_animation_fps_changed");
+ anim_speed->connect("value_changed", this, "_animation_fps_changed");
- anim_loop = memnew( CheckButton );
+ anim_loop = memnew(CheckButton);
anim_loop->set_text(TTR("Loop"));
vbc_animlist->add_child(anim_loop);
- anim_loop->connect("pressed",this,"_animation_loop_changed");
+ anim_loop->connect("pressed", this, "_animation_loop_changed");
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
split->add_child(vbc);
vbc->set_h_size_flags(SIZE_EXPAND_FILL);
- sub_vb = memnew( VBoxContainer );
- vbc->add_margin_child(TTR("Animation Frames"),sub_vb,true);
-
+ sub_vb = memnew(VBoxContainer);
+ vbc->add_margin_child(TTR("Animation Frames"), sub_vb, true);
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
sub_vb->add_child(hbc);
//animations = memnew( ItemList );
-
- load = memnew( Button );
+ load = memnew(Button);
load->set_tooltip(TTR("Load Resource"));
hbc->add_child(load);
- paste = memnew( Button );
+ paste = memnew(Button);
paste->set_text(TTR("Paste"));
hbc->add_child(paste);
- empty = memnew( Button );
+ empty = memnew(Button);
empty->set_text(TTR("Insert Empty (Before)"));
hbc->add_child(empty);
- empty2 = memnew( Button );
+ empty2 = memnew(Button);
empty2->set_text(TTR("Insert Empty (After)"));
hbc->add_child(empty2);
- move_up = memnew( Button );
+ move_up = memnew(Button);
move_up->set_text(TTR("Up"));
hbc->add_child(move_up);
- move_down = memnew( Button );
+ move_down = memnew(Button);
move_down->set_text(TTR("Down"));
hbc->add_child(move_down);
- _delete = memnew( Button );
+ _delete = memnew(Button);
hbc->add_child(_delete);
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
add_child(file);
-
- tree = memnew( ItemList );
+ tree = memnew(ItemList);
tree->set_v_size_flags(SIZE_EXPAND_FILL);
tree->set_icon_mode(ItemList::ICON_MODE_TOP);
int thumbnail_size = 96;
tree->set_max_columns(0);
tree->set_icon_mode(ItemList::ICON_MODE_TOP);
- tree->set_fixed_column_width(thumbnail_size*3/2);
+ tree->set_fixed_column_width(thumbnail_size * 3 / 2);
tree->set_max_text_lines(2);
- tree->set_fixed_icon_size(Size2(thumbnail_size,thumbnail_size));
+ tree->set_fixed_icon_size(Size2(thumbnail_size, thumbnail_size));
//tree->set_min_icon_size(Size2(thumbnail_size,thumbnail_size));
tree->set_drag_forwarding(this);
-
-
sub_vb->add_child(tree);
- dialog = memnew( AcceptDialog );
- add_child( dialog );
-
- load->connect("pressed", this,"_load_pressed");
- _delete->connect("pressed", this,"_delete_pressed");
- paste->connect("pressed", this,"_paste_pressed");
- empty->connect("pressed", this,"_empty_pressed");
- empty2->connect("pressed", this,"_empty2_pressed");
- move_up->connect("pressed", this,"_up_pressed");
- move_down->connect("pressed", this,"_down_pressed");
- file->connect("files_selected", this,"_file_load_request");
+ dialog = memnew(AcceptDialog);
+ add_child(dialog);
+
+ load->connect("pressed", this, "_load_pressed");
+ _delete->connect("pressed", this, "_delete_pressed");
+ paste->connect("pressed", this, "_paste_pressed");
+ empty->connect("pressed", this, "_empty_pressed");
+ empty2->connect("pressed", this, "_empty2_pressed");
+ move_up->connect("pressed", this, "_up_pressed");
+ move_down->connect("pressed", this, "_down_pressed");
+ file->connect("files_selected", this, "_file_load_request");
//dialog->connect("confirmed", this,"_delete_confirm_pressed");
//tree->connect("item_selected", this,"_item_edited");
- loading_scene=false;
- sel=-1;
-
- updating=false;
+ loading_scene = false;
+ sel = -1;
- edited_anim="default";
+ updating = false;
+ edited_anim = "default";
}
-
void SpriteFramesEditorPlugin::edit(Object *p_object) {
frames_editor->set_undo_redo(&get_undo_redo());
- SpriteFrames * s = p_object->cast_to<SpriteFrames>();
+ SpriteFrames *s = p_object->cast_to<SpriteFrames>();
if (!s)
return;
@@ -946,24 +867,16 @@ void SpriteFramesEditorPlugin::make_visible(bool p_visible) {
//frames_editor->set_process(false);
}
-
}
SpriteFramesEditorPlugin::SpriteFramesEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- frames_editor = memnew( SpriteFramesEditor );
- frames_editor->set_custom_minimum_size(Size2(0,300));
- button=editor->add_bottom_panel_item("SpriteFrames",frames_editor);
+ editor = p_node;
+ frames_editor = memnew(SpriteFramesEditor);
+ frames_editor->set_custom_minimum_size(Size2(0, 300));
+ button = editor->add_bottom_panel_item("SpriteFrames", frames_editor);
button->hide();
-
-
-
}
-
-SpriteFramesEditorPlugin::~SpriteFramesEditorPlugin()
-{
+SpriteFramesEditorPlugin::~SpriteFramesEditorPlugin() {
}
-
-
diff --git a/editor/plugins/sprite_frames_editor_plugin.h b/editor/plugins/sprite_frames_editor_plugin.h
index 11f545b443..3e9ba710f3 100644
--- a/editor/plugins/sprite_frames_editor_plugin.h
+++ b/editor/plugins/sprite_frames_editor_plugin.h
@@ -29,19 +29,17 @@
#ifndef SPRITE_FRAMES_EDITOR_PLUGIN_H
#define SPRITE_FRAMES_EDITOR_PLUGIN_H
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "scene/gui/tree.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/animated_sprite.h"
-#include "scene/gui/file_dialog.h"
#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/split_container.h"
-
+#include "scene/gui/tree.h"
class SpriteFramesEditor : public PanelContainer {
- GDCLASS(SpriteFramesEditor, PanelContainer );
+ GDCLASS(SpriteFramesEditor, PanelContainer);
Button *load;
Button *_delete;
@@ -58,7 +56,6 @@ class SpriteFramesEditor : public PanelContainer {
Button *new_anim;
Button *remove_anim;
-
Tree *animations;
SpinBox *anim_speed;
CheckButton *anim_loop;
@@ -73,7 +70,7 @@ class SpriteFramesEditor : public PanelContainer {
void _load_pressed();
void _load_scene_pressed();
- void _file_load_request(const PoolVector<String>& p_path, int p_at_pos=-1);
+ void _file_load_request(const PoolVector<String> &p_path, int p_at_pos = -1);
void _paste_pressed();
void _empty_pressed();
void _empty2_pressed();
@@ -81,11 +78,9 @@ class SpriteFramesEditor : public PanelContainer {
void _delete_confirm_pressed();
void _up_pressed();
void _down_pressed();
- void _update_library(bool p_skip_selector=false);
+ void _update_library(bool p_skip_selector = false);
void _item_edited();
-
-
void _animation_select();
void _animation_name_edited();
void _animation_add();
@@ -97,33 +92,32 @@ class SpriteFramesEditor : public PanelContainer {
UndoRedo *undo_redo;
- bool _is_drop_valid(const Dictionary& p_drag_data, const Dictionary& p_item_data) const;
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ bool _is_drop_valid(const Dictionary &p_drag_data, const Dictionary &p_item_data) const;
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
protected:
void _notification(int p_what);
void _gui_input(InputEvent p_event);
static void _bind_methods();
-public:
- void set_undo_redo(UndoRedo *p_undo_redo) {undo_redo=p_undo_redo; }
+public:
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
- void edit(SpriteFrames* p_frames);
+ void edit(SpriteFrames *p_frames);
SpriteFramesEditor();
};
class SpriteFramesEditorPlugin : public EditorPlugin {
- GDCLASS( SpriteFramesEditorPlugin, EditorPlugin );
+ GDCLASS(SpriteFramesEditorPlugin, EditorPlugin);
SpriteFramesEditor *frames_editor;
EditorNode *editor;
Button *button;
public:
-
virtual String get_name() const { return "SpriteFrames"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -132,7 +126,6 @@ public:
SpriteFramesEditorPlugin(EditorNode *p_node);
~SpriteFramesEditorPlugin();
-
};
#endif // SPRITE_FRAMES_EDITOR_PLUGIN_H
diff --git a/editor/plugins/stream_editor_plugin.h b/editor/plugins/stream_editor_plugin.h
index 2ae3b7100e..6b68ba02f9 100644
--- a/editor/plugins/stream_editor_plugin.h
+++ b/editor/plugins/stream_editor_plugin.h
@@ -30,8 +30,8 @@
#define STREAM_EDITOR_PLUGIN_H
#if 0
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/audio/stream_player.h"
/**
diff --git a/editor/plugins/style_box_editor_plugin.cpp b/editor/plugins/style_box_editor_plugin.cpp
index 396ebd0052..093f25e2b0 100644
--- a/editor/plugins/style_box_editor_plugin.cpp
+++ b/editor/plugins/style_box_editor_plugin.cpp
@@ -28,16 +28,14 @@
/*************************************************************************/
#include "style_box_editor_plugin.h"
-
-void StyleBoxEditor::edit(const Ref<StyleBox>& p_stylebox) {
+void StyleBoxEditor::edit(const Ref<StyleBox> &p_stylebox) {
if (stylebox.is_valid())
- stylebox->disconnect("changed",this,"_sb_changed");
- stylebox=p_stylebox;
+ stylebox->disconnect("changed", this, "_sb_changed");
+ stylebox = p_stylebox;
if (p_stylebox.is_valid()) {
- preview->add_style_override("panel",stylebox);
- stylebox->connect("changed",this,"_sb_changed");
-
+ preview->add_style_override("panel", stylebox);
+ stylebox->connect("changed", this, "_sb_changed");
}
}
@@ -48,7 +46,7 @@ void StyleBoxEditor::_sb_changed() {
void StyleBoxEditor::_bind_methods() {
- ClassDB::bind_method("_sb_changed",&StyleBoxEditor::_sb_changed);
+ ClassDB::bind_method("_sb_changed", &StyleBoxEditor::_sb_changed);
//ClassDB::bind_method("_import",&StyleBoxEditor::_import);
//ClassDB::bind_method("_import_accept",&StyleBoxEditor::_import_accept);
//ClassDB::bind_method("_preview_text_changed",&StyleBoxEditor::_preview_text_changed);
@@ -56,39 +54,36 @@ void StyleBoxEditor::_bind_methods() {
StyleBoxEditor::StyleBoxEditor() {
- panel = memnew( Panel );
+ panel = memnew(Panel);
add_child(panel);
panel->set_area_as_parent_rect();
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
l->set_text(TTR("StyleBox Preview:"));
- l->set_pos(Point2(5,5));
+ l->set_pos(Point2(5, 5));
panel->add_child(l);
-
- preview = memnew( Panel );
+ preview = memnew(Panel);
panel->add_child(preview);
- preview->set_pos(Point2(50,50));
- preview->set_size(Size2(200,100));
-
-
+ preview->set_pos(Point2(50, 50));
+ preview->set_size(Size2(200, 100));
}
void StyleBoxEditorPlugin::edit(Object *p_node) {
if (p_node && p_node->cast_to<StyleBox>()) {
- stylebox_editor->edit( p_node->cast_to<StyleBox>() );
+ stylebox_editor->edit(p_node->cast_to<StyleBox>());
stylebox_editor->show();
} else
stylebox_editor->hide();
}
-bool StyleBoxEditorPlugin::handles(Object *p_node) const{
+bool StyleBoxEditorPlugin::handles(Object *p_node) const {
return p_node->is_class("StyleBox");
}
-void StyleBoxEditorPlugin::make_visible(bool p_visible){
+void StyleBoxEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
button->show();
@@ -103,13 +98,10 @@ void StyleBoxEditorPlugin::make_visible(bool p_visible){
StyleBoxEditorPlugin::StyleBoxEditorPlugin(EditorNode *p_node) {
- stylebox_editor = memnew( StyleBoxEditor );
- stylebox_editor->set_custom_minimum_size(Size2(0,250));
+ stylebox_editor = memnew(StyleBoxEditor);
+ stylebox_editor->set_custom_minimum_size(Size2(0, 250));
//p_node->get_viewport()->add_child(stylebox_editor);
- button = p_node->add_bottom_panel_item("StyleBox",stylebox_editor);
+ button = p_node->add_bottom_panel_item("StyleBox", stylebox_editor);
button->hide();
-
-
}
-
diff --git a/editor/plugins/style_box_editor_plugin.h b/editor/plugins/style_box_editor_plugin.h
index 01e636472b..1dfe48d97f 100644
--- a/editor/plugins/style_box_editor_plugin.h
+++ b/editor/plugins/style_box_editor_plugin.h
@@ -29,15 +29,14 @@
#ifndef STYLE_BOX_EDITOR_PLUGIN_H
#define STYLE_BOX_EDITOR_PLUGIN_H
-#include "scene/resources/style_box.h"
-#include "scene/gui/texture_rect.h"
-#include "scene/gui/option_button.h"
#include "editor/editor_node.h"
-
+#include "scene/gui/option_button.h"
+#include "scene/gui/texture_rect.h"
+#include "scene/resources/style_box.h"
class StyleBoxEditor : public Control {
- GDCLASS( StyleBoxEditor, Control );
+ GDCLASS(StyleBoxEditor, Control);
Panel *panel;
Panel *preview;
@@ -47,28 +46,23 @@ class StyleBoxEditor : public Control {
void _sb_changed();
protected:
-
-
static void _bind_methods();
-public:
- void edit(const Ref<StyleBox>& p_stylebox);
+public:
+ void edit(const Ref<StyleBox> &p_stylebox);
StyleBoxEditor();
};
-
-
class StyleBoxEditorPlugin : public EditorPlugin {
- GDCLASS( StyleBoxEditorPlugin, EditorPlugin );
+ GDCLASS(StyleBoxEditorPlugin, EditorPlugin);
StyleBoxEditor *stylebox_editor;
EditorNode *editor;
Button *button;
public:
-
virtual String get_name() const { return "StyleBox"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -76,8 +70,6 @@ public:
virtual void make_visible(bool p_visible);
StyleBoxEditorPlugin(EditorNode *p_node);
-
};
-
#endif // STYLE_BOX_EDITOR_PLUGIN_H
diff --git a/editor/plugins/texture_editor_plugin.cpp b/editor/plugins/texture_editor_plugin.cpp
index af05094e5e..3d05e68cac 100644
--- a/editor/plugins/texture_editor_plugin.cpp
+++ b/editor/plugins/texture_editor_plugin.cpp
@@ -28,76 +28,68 @@
/*************************************************************************/
#include "texture_editor_plugin.h"
-#include "io/resource_loader.h"
-#include "global_config.h"
#include "editor/editor_settings.h"
+#include "global_config.h"
+#include "io/resource_loader.h"
void TextureEditor::_gui_input(InputEvent p_event) {
-
-
}
void TextureEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
-
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
}
-
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
//get_scene()->connect("node_removed",this,"_node_removed");
-
}
- if (p_what==NOTIFICATION_DRAW) {
-
+ if (p_what == NOTIFICATION_DRAW) {
- Ref<Texture> checkerboard = get_icon("Checkerboard","EditorIcons");
+ Ref<Texture> checkerboard = get_icon("Checkerboard", "EditorIcons");
Size2 size = get_size();
- draw_texture_rect(checkerboard,Rect2(Point2(),size),true);
+ draw_texture_rect(checkerboard, Rect2(Point2(), size), true);
- int tex_width = texture->get_width() * size.height / texture ->get_height();
+ int tex_width = texture->get_width() * size.height / texture->get_height();
int tex_height = size.height;
- if (tex_width>size.width) {
- tex_width=size.width;
- tex_height=texture->get_height() * tex_width / texture->get_width();
+ if (tex_width > size.width) {
+ tex_width = size.width;
+ tex_height = texture->get_height() * tex_width / texture->get_width();
}
- int ofs_x = (size.width - tex_width)/2;
- int ofs_y = (size.height - tex_height)/2;
+ int ofs_x = (size.width - tex_width) / 2;
+ int ofs_y = (size.height - tex_height) / 2;
- draw_texture_rect(texture,Rect2(ofs_x,ofs_y,tex_width,tex_height));
+ draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height));
- Ref<Font> font = get_font("font","Label");
+ Ref<Font> font = get_font("font", "Label");
String format;
if (texture->cast_to<ImageTexture>()) {
format = Image::get_format_name(texture->cast_to<ImageTexture>()->get_format());
} else {
- format=texture->get_class();
+ format = texture->get_class();
}
- String text = itos(texture->get_width())+"x"+itos(texture->get_height())+" "+format;
+ String text = itos(texture->get_width()) + "x" + itos(texture->get_height()) + " " + format;
Size2 rect = font->get_string_size(text);
- Vector2 draw_from = size-rect+Size2(-2,font->get_ascent()-2);
- if (draw_from.x<0)
- draw_from.x=0;
+ Vector2 draw_from = size - rect + Size2(-2, font->get_ascent() - 2);
+ if (draw_from.x < 0)
+ draw_from.x = 0;
- draw_string(font,draw_from+Vector2(2,2),text,Color(0,0,0,0.5),size.width);
- draw_string(font,draw_from-Vector2(2,2),text,Color(0,0,0,0.5),size.width);
- draw_string(font,draw_from,text,Color(1,1,1,1),size.width);
+ draw_string(font, draw_from + Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
+ draw_string(font, draw_from - Vector2(2, 2), text, Color(0, 0, 0, 0.5), size.width);
+ draw_string(font, draw_from, text, Color(1, 1, 1, 1), size.width);
}
}
-
-
void TextureEditor::edit(Ref<Texture> p_texture) {
- texture=p_texture;
+ texture = p_texture;
if (!texture.is_null())
update();
@@ -105,27 +97,21 @@ void TextureEditor::edit(Ref<Texture> p_texture) {
hide();
}
-
}
-
-
void TextureEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&TextureEditor::_gui_input);
-
+ ClassDB::bind_method(D_METHOD("_gui_input"), &TextureEditor::_gui_input);
}
TextureEditor::TextureEditor() {
- set_custom_minimum_size(Size2(1,150));
-
+ set_custom_minimum_size(Size2(1, 150));
}
-
void TextureEditorPlugin::edit(Object *p_object) {
- Texture * s = p_object->cast_to<Texture>();
+ Texture *s = p_object->cast_to<Texture>();
if (!s)
return;
@@ -147,23 +133,15 @@ void TextureEditorPlugin::make_visible(bool p_visible) {
texture_editor->hide();
//texture_editor->set_process(false);
}
-
}
TextureEditorPlugin::TextureEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- texture_editor = memnew( TextureEditor );
- add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM,texture_editor);
+ editor = p_node;
+ texture_editor = memnew(TextureEditor);
+ add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM, texture_editor);
texture_editor->hide();
-
-
-
}
-
-TextureEditorPlugin::~TextureEditorPlugin()
-{
+TextureEditorPlugin::~TextureEditorPlugin() {
}
-
-
diff --git a/editor/plugins/texture_editor_plugin.h b/editor/plugins/texture_editor_plugin.h
index 7ad0e918cf..083fbada8b 100644
--- a/editor/plugins/texture_editor_plugin.h
+++ b/editor/plugins/texture_editor_plugin.h
@@ -29,40 +29,34 @@
#ifndef TEXTURE_EDITOR_PLUGIN_H
#define TEXTURE_EDITOR_PLUGIN_H
-
-
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/resources/texture.h"
-
class TextureEditor : public Control {
GDCLASS(TextureEditor, Control);
-
Ref<Texture> texture;
protected:
void _notification(int p_what);
void _gui_input(InputEvent p_event);
static void _bind_methods();
-public:
+public:
void edit(Ref<Texture> p_texture);
TextureEditor();
};
-
class TextureEditorPlugin : public EditorPlugin {
- GDCLASS( TextureEditorPlugin, EditorPlugin );
+ GDCLASS(TextureEditorPlugin, EditorPlugin);
TextureEditor *texture_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "Texture"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -71,7 +65,6 @@ public:
TextureEditorPlugin(EditorNode *p_node);
~TextureEditorPlugin();
-
};
#endif // TEXTURE_EDITOR_PLUGIN_H
diff --git a/editor/plugins/texture_region_editor_plugin.cpp b/editor/plugins/texture_region_editor_plugin.cpp
index aabf938577..5e992d3ec1 100644
--- a/editor/plugins/texture_region_editor_plugin.cpp
+++ b/editor/plugins/texture_region_editor_plugin.cpp
@@ -31,149 +31,148 @@
#include "texture_region_editor_plugin.h"
#include "core/core_string_names.h"
-#include "scene/gui/check_box.h"
#include "os/input.h"
#include "os/keyboard.h"
+#include "scene/gui/check_box.h"
-void draw_margin_line(Control *edit_draw, Vector2 from, Vector2 to){
- Vector2 line = (to-from).normalized() * 10;
+void draw_margin_line(Control *edit_draw, Vector2 from, Vector2 to) {
+ Vector2 line = (to - from).normalized() * 10;
while ((to - from).length_squared() > 200) {
- edit_draw->draw_line(from, from + line,Color(0.97, 0.2, 0.2),2);
- from += line*2;
+ edit_draw->draw_line(from, from + line, Color(0.97, 0.2, 0.2), 2);
+ from += line * 2;
}
}
-void TextureRegionEditor::_region_draw()
-{
+void TextureRegionEditor::_region_draw() {
Ref<Texture> base_tex = NULL;
- if(node_sprite)
+ if (node_sprite)
base_tex = node_sprite->get_texture();
- else if(node_patch9)
+ else if (node_patch9)
base_tex = node_patch9->get_texture();
- else if(obj_styleBox.is_valid())
+ else if (obj_styleBox.is_valid())
base_tex = obj_styleBox->get_texture();
- else if(atlas_tex.is_valid())
+ else if (atlas_tex.is_valid())
base_tex = atlas_tex->get_atlas();
if (base_tex.is_null())
return;
Transform2D mtx;
- mtx.elements[2]=-draw_ofs;
- mtx.scale_basis(Vector2(draw_zoom,draw_zoom));
+ mtx.elements[2] = -draw_ofs;
+ mtx.scale_basis(Vector2(draw_zoom, draw_zoom));
- VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(),mtx);
- edit_draw->draw_texture(base_tex,Point2());
- VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(),Transform2D());
+ VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), mtx);
+ edit_draw->draw_texture(base_tex, Point2());
+ VS::get_singleton()->canvas_item_add_set_transform(edit_draw->get_canvas_item(), Transform2D());
if (snap_mode == SNAP_GRID) {
Size2 s = edit_draw->get_size();
int last_cell;
- if (snap_step.x!=0) {
+ if (snap_step.x != 0) {
if (snap_separation.x == 0)
- for(int i=0;i<s.width;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i,0)).x-snap_offset.x)/snap_step.x));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- edit_draw->draw_line(Point2(i,0),Point2(i,s.height),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ for (int i = 0; i < s.width; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / snap_step.x));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ edit_draw->draw_line(Point2(i, 0), Point2(i, s.height), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
else
- for(int i=0;i<s.width;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i,0)).x-snap_offset.x)/(snap_step.x+snap_separation.x)));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- edit_draw->draw_rect(Rect2(i-snap_separation.x*draw_zoom,0,snap_separation.x*draw_zoom,s.height),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ for (int i = 0; i < s.width; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(i, 0)).x - snap_offset.x) / (snap_step.x + snap_separation.x)));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ edit_draw->draw_rect(Rect2(i - snap_separation.x * draw_zoom, 0, snap_separation.x * draw_zoom, s.height), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
- if (snap_step.y!=0) {
+ if (snap_step.y != 0) {
if (snap_separation.y == 0)
- for(int i=0;i<s.height;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0,i)).y-snap_offset.y)/snap_step.y));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- edit_draw->draw_line(Point2(0,i),Point2(s.width,i),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ for (int i = 0; i < s.height; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / snap_step.y));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ edit_draw->draw_line(Point2(0, i), Point2(s.width, i), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
else
- for(int i=0;i<s.height;i++) {
- int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0,i)).y-snap_offset.y)/(snap_step.y+snap_separation.y)));
- if (i==0)
- last_cell=cell;
- if (last_cell!=cell)
- edit_draw->draw_rect(Rect2(0,i-snap_separation.y*draw_zoom,s.width,snap_separation.y*draw_zoom),Color(0.3,0.7,1,0.3));
- last_cell=cell;
+ for (int i = 0; i < s.height; i++) {
+ int cell = Math::fast_ftoi(Math::floor((mtx.affine_inverse().xform(Vector2(0, i)).y - snap_offset.y) / (snap_step.y + snap_separation.y)));
+ if (i == 0)
+ last_cell = cell;
+ if (last_cell != cell)
+ edit_draw->draw_rect(Rect2(0, i - snap_separation.y * draw_zoom, s.width, snap_separation.y * draw_zoom), Color(0.3, 0.7, 1, 0.3));
+ last_cell = cell;
}
}
} else if (snap_mode == SNAP_AUTOSLICE) {
- for (List<Rect2>::Element *E = autoslice_cache.front();E;E=E->next()) {
+ for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
Rect2 r = E->get();
- Vector2 endpoints[4]={
+ Vector2 endpoints[4] = {
mtx.basis_xform(r.pos),
- mtx.basis_xform(r.pos+Vector2(r.size.x,0)),
- mtx.basis_xform(r.pos+r.size),
- mtx.basis_xform(r.pos+Vector2(0,r.size.y))
+ mtx.basis_xform(r.pos + Vector2(r.size.x, 0)),
+ mtx.basis_xform(r.pos + r.size),
+ mtx.basis_xform(r.pos + Vector2(0, r.size.y))
};
- for(int i=0;i<4;i++) {
- int next = (i+1)%4;
- edit_draw->draw_line(endpoints[i]-draw_ofs, endpoints[next]-draw_ofs, Color(0.3,0.7,1,1) , 2);
+ for (int i = 0; i < 4; i++) {
+ int next = (i + 1) % 4;
+ edit_draw->draw_line(endpoints[i] - draw_ofs, endpoints[next] - draw_ofs, Color(0.3, 0.7, 1, 1), 2);
}
}
}
- Ref<Texture> select_handle = get_icon("EditorHandle","EditorIcons");
+ Ref<Texture> select_handle = get_icon("EditorHandle", "EditorIcons");
- Rect2 scroll_rect(Point2(),mtx.basis_xform(base_tex->get_size()));
+ Rect2 scroll_rect(Point2(), mtx.basis_xform(base_tex->get_size()));
scroll_rect.expand_to(mtx.basis_xform(edit_draw->get_size()));
- Vector2 endpoints[4]={
+ Vector2 endpoints[4] = {
mtx.basis_xform(rect.pos),
- mtx.basis_xform(rect.pos+Vector2(rect.size.x,0)),
- mtx.basis_xform(rect.pos+rect.size),
- mtx.basis_xform(rect.pos+Vector2(0,rect.size.y))
+ mtx.basis_xform(rect.pos + Vector2(rect.size.x, 0)),
+ mtx.basis_xform(rect.pos + rect.size),
+ mtx.basis_xform(rect.pos + Vector2(0, rect.size.y))
};
- Color color(0.9,0.5,0.5);
- for(int i=0;i<4;i++) {
+ Color color(0.9, 0.5, 0.5);
+ for (int i = 0; i < 4; i++) {
- int prev = (i+3)%4;
- int next = (i+1)%4;
+ int prev = (i + 3) % 4;
+ int next = (i + 1) % 4;
Vector2 ofs = ((endpoints[i] - endpoints[prev]).normalized() + ((endpoints[i] - endpoints[next]).normalized())).normalized();
- ofs*=1.4144*(select_handle->get_size().width/2);
+ ofs *= 1.4144 * (select_handle->get_size().width / 2);
- edit_draw->draw_line(endpoints[i]-draw_ofs, endpoints[next]-draw_ofs, color , 2);
+ edit_draw->draw_line(endpoints[i] - draw_ofs, endpoints[next] - draw_ofs, color, 2);
if (snap_mode != SNAP_AUTOSLICE)
- edit_draw->draw_texture(select_handle,(endpoints[i]+ofs-(select_handle->get_size()/2)).floor()-draw_ofs);
+ edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs);
- ofs = (endpoints[next]-endpoints[i])/2;
- ofs += (endpoints[next]-endpoints[i]).tangent().normalized()*(select_handle->get_size().width/2);
+ ofs = (endpoints[next] - endpoints[i]) / 2;
+ ofs += (endpoints[next] - endpoints[i]).tangent().normalized() * (select_handle->get_size().width / 2);
if (snap_mode != SNAP_AUTOSLICE)
- edit_draw->draw_texture(select_handle,(endpoints[i]+ofs-(select_handle->get_size()/2)).floor()-draw_ofs);
+ edit_draw->draw_texture(select_handle, (endpoints[i] + ofs - (select_handle->get_size() / 2)).floor() - draw_ofs);
scroll_rect.expand_to(endpoints[i]);
}
- scroll_rect=scroll_rect.grow(200);
- updating_scroll=true;
+ scroll_rect = scroll_rect.grow(200);
+ updating_scroll = true;
hscroll->set_min(scroll_rect.pos.x);
- hscroll->set_max(scroll_rect.pos.x+scroll_rect.size.x);
+ hscroll->set_max(scroll_rect.pos.x + scroll_rect.size.x);
hscroll->set_page(edit_draw->get_size().x);
hscroll->set_value(draw_ofs.x);
hscroll->set_step(0.001);
vscroll->set_min(scroll_rect.pos.y);
- vscroll->set_max(scroll_rect.pos.y+scroll_rect.size.y);
+ vscroll->set_max(scroll_rect.pos.y + scroll_rect.size.y);
vscroll->set_page(edit_draw->get_size().y);
vscroll->set_value(draw_ofs.y);
vscroll->set_step(0.001);
- updating_scroll=false;
+ updating_scroll = false;
float margins[4];
if (node_patch9 || obj_styleBox.is_valid()) {
@@ -189,40 +188,40 @@ void TextureRegionEditor::_region_draw()
margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT);
}
Vector2 pos[4] = {
- mtx.basis_xform(Vector2(0,margins[0]))+Vector2(0,endpoints[0].y-draw_ofs.y),
- -mtx.basis_xform(Vector2(0,margins[1]))+Vector2(0,endpoints[2].y-draw_ofs.y),
- mtx.basis_xform(Vector2(margins[2],0))+Vector2(endpoints[0].x-draw_ofs.x,0),
- -mtx.basis_xform(Vector2(margins[3],0))+Vector2(endpoints[2].x-draw_ofs.x,0)};
-
- draw_margin_line(edit_draw,pos[0],pos[0]+Vector2(edit_draw->get_size().x,0));
- draw_margin_line(edit_draw,pos[1],pos[1]+Vector2(edit_draw->get_size().x,0));
- draw_margin_line(edit_draw,pos[2],pos[2]+Vector2(0,edit_draw->get_size().y));
- draw_margin_line(edit_draw,pos[3],pos[3]+Vector2(0,edit_draw->get_size().y));
+ mtx.basis_xform(Vector2(0, margins[0])) + Vector2(0, endpoints[0].y - draw_ofs.y),
+ -mtx.basis_xform(Vector2(0, margins[1])) + Vector2(0, endpoints[2].y - draw_ofs.y),
+ mtx.basis_xform(Vector2(margins[2], 0)) + Vector2(endpoints[0].x - draw_ofs.x, 0),
+ -mtx.basis_xform(Vector2(margins[3], 0)) + Vector2(endpoints[2].x - draw_ofs.x, 0)
+ };
+
+ draw_margin_line(edit_draw, pos[0], pos[0] + Vector2(edit_draw->get_size().x, 0));
+ draw_margin_line(edit_draw, pos[1], pos[1] + Vector2(edit_draw->get_size().x, 0));
+ draw_margin_line(edit_draw, pos[2], pos[2] + Vector2(0, edit_draw->get_size().y));
+ draw_margin_line(edit_draw, pos[3], pos[3] + Vector2(0, edit_draw->get_size().y));
}
}
-void TextureRegionEditor::_region_input(const InputEvent& p_input)
-{
+void TextureRegionEditor::_region_input(const InputEvent &p_input) {
Transform2D mtx;
- mtx.elements[2]=-draw_ofs;
- mtx.scale_basis(Vector2(draw_zoom,draw_zoom));
-
- Vector2 endpoints[8]={
- mtx.xform(rect.pos)+Vector2(-4,-4),
- mtx.xform(rect.pos+Vector2(rect.size.x/2,0))+Vector2(0,-4),
- mtx.xform(rect.pos+Vector2(rect.size.x,0))+Vector2(4,-4),
- mtx.xform(rect.pos+Vector2(rect.size.x,rect.size.y/2))+Vector2(4,0),
- mtx.xform(rect.pos+rect.size)+Vector2(4,4),
- mtx.xform(rect.pos+Vector2(rect.size.x/2,rect.size.y))+Vector2(0,4),
- mtx.xform(rect.pos+Vector2(0,rect.size.y))+Vector2(-4,4),
- mtx.xform(rect.pos+Vector2(0,rect.size.y/2))+Vector2(-4,0)
+ mtx.elements[2] = -draw_ofs;
+ mtx.scale_basis(Vector2(draw_zoom, draw_zoom));
+
+ Vector2 endpoints[8] = {
+ mtx.xform(rect.pos) + Vector2(-4, -4),
+ mtx.xform(rect.pos + Vector2(rect.size.x / 2, 0)) + Vector2(0, -4),
+ mtx.xform(rect.pos + Vector2(rect.size.x, 0)) + Vector2(4, -4),
+ mtx.xform(rect.pos + Vector2(rect.size.x, rect.size.y / 2)) + Vector2(4, 0),
+ mtx.xform(rect.pos + rect.size) + Vector2(4, 4),
+ mtx.xform(rect.pos + Vector2(rect.size.x / 2, rect.size.y)) + Vector2(0, 4),
+ mtx.xform(rect.pos + Vector2(0, rect.size.y)) + Vector2(-4, 4),
+ mtx.xform(rect.pos + Vector2(0, rect.size.y / 2)) + Vector2(-4, 0)
};
- if (p_input.type==InputEvent::MOUSE_BUTTON) {
+ if (p_input.type == InputEvent::MOUSE_BUTTON) {
- const InputEventMouseButton &mb=p_input.mouse_button;
+ const InputEventMouseButton &mb = p_input.mouse_button;
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (node_patch9 || obj_styleBox.is_valid()) {
@@ -240,10 +239,11 @@ void TextureRegionEditor::_region_input(const InputEvent& p_input)
margins[3] = obj_styleBox->get_margin_size(MARGIN_RIGHT);
}
Vector2 pos[4] = {
- mtx.basis_xform(rect.pos+Vector2(0,margins[0]))-draw_ofs,
- mtx.basis_xform(rect.pos+rect.size-Vector2(0,margins[1]))-draw_ofs,
- mtx.basis_xform(rect.pos+Vector2(margins[2],0))-draw_ofs,
- mtx.basis_xform(rect.pos+rect.size-Vector2(margins[3],0))-draw_ofs};
+ mtx.basis_xform(rect.pos + Vector2(0, margins[0])) - draw_ofs,
+ mtx.basis_xform(rect.pos + rect.size - Vector2(0, margins[1])) - draw_ofs,
+ mtx.basis_xform(rect.pos + Vector2(margins[2], 0)) - draw_ofs,
+ mtx.basis_xform(rect.pos + rect.size - Vector2(margins[3], 0)) - draw_ofs
+ };
if (Math::abs(mb.y - pos[0].y) < 8) {
edited_margin = 0;
prev_margin = margins[0];
@@ -258,132 +258,130 @@ void TextureRegionEditor::_region_input(const InputEvent& p_input)
prev_margin = margins[3];
}
if (edited_margin >= 0) {
- drag_from=Vector2(mb.x,mb.y);
- drag=true;
+ drag_from = Vector2(mb.x, mb.y);
+ drag = true;
}
}
- if ( edited_margin < 0 && snap_mode == SNAP_AUTOSLICE) {
- Vector2 point = mtx.affine_inverse().xform(Vector2(mb.x,mb.y));
- for (List<Rect2>::Element *E=autoslice_cache.front();E;E=E->next()) {
+ if (edited_margin < 0 && snap_mode == SNAP_AUTOSLICE) {
+ Vector2 point = mtx.affine_inverse().xform(Vector2(mb.x, mb.y));
+ for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
if (E->get().has_point(point)) {
rect = E->get();
- if (Input::get_singleton()->is_key_pressed(KEY_CONTROL)&&!(Input::get_singleton()->is_key_pressed(KEY_SHIFT|KEY_ALT))) {
+ if (Input::get_singleton()->is_key_pressed(KEY_CONTROL) && !(Input::get_singleton()->is_key_pressed(KEY_SHIFT | KEY_ALT))) {
Rect2 r;
- if(node_sprite )
- r=node_sprite->get_region_rect();
- else if(node_patch9)
- r=node_patch9->get_region_rect();
- else if(obj_styleBox.is_valid())
- r=obj_styleBox->get_region_rect();
- else if(atlas_tex.is_valid())
- r =atlas_tex->get_region();
+ if (node_sprite)
+ r = node_sprite->get_region_rect();
+ else if (node_patch9)
+ r = node_patch9->get_region_rect();
+ else if (obj_styleBox.is_valid())
+ r = obj_styleBox->get_region_rect();
+ else if (atlas_tex.is_valid())
+ r = atlas_tex->get_region();
rect.expand_to(r.pos);
- rect.expand_to(r.pos+r.size);
+ rect.expand_to(r.pos + r.size);
}
undo_redo->create_action("Set Region Rect");
- if(node_sprite){
- undo_redo->add_do_method(node_sprite ,"set_region_rect",rect);
- undo_redo->add_undo_method(node_sprite,"set_region_rect",node_sprite->get_region_rect());
- } else if(node_patch9){
- undo_redo->add_do_method(node_patch9 ,"set_region_rect",rect);
- undo_redo->add_undo_method(node_patch9,"set_region_rect",node_patch9->get_region_rect());
+ if (node_sprite) {
+ undo_redo->add_do_method(node_sprite, "set_region_rect", rect);
+ undo_redo->add_undo_method(node_sprite, "set_region_rect", node_sprite->get_region_rect());
+ } else if (node_patch9) {
+ undo_redo->add_do_method(node_patch9, "set_region_rect", rect);
+ undo_redo->add_undo_method(node_patch9, "set_region_rect", node_patch9->get_region_rect());
} else if (obj_styleBox.is_valid()) {
- undo_redo->add_do_method(obj_styleBox.ptr(),"set_region_rect",rect);
- undo_redo->add_undo_method(obj_styleBox.ptr(),"set_region_rect",obj_styleBox->get_region_rect());
+ undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", rect);
+ undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect());
} else if (atlas_tex.is_valid()) {
- undo_redo->add_do_method(atlas_tex.ptr(),"set_region",rect);
- undo_redo->add_undo_method(atlas_tex.ptr(),"set_region",atlas_tex->get_region());
+ undo_redo->add_do_method(atlas_tex.ptr(), "set_region", rect);
+ undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region());
}
- undo_redo->add_do_method(edit_draw,"update");
- undo_redo->add_undo_method(edit_draw,"update");
+ undo_redo->add_do_method(edit_draw, "update");
+ undo_redo->add_undo_method(edit_draw, "update");
undo_redo->commit_action();
break;
}
}
} else if (edited_margin < 0) {
- drag_from=mtx.affine_inverse().xform(Vector2(mb.x,mb.y));
+ drag_from = mtx.affine_inverse().xform(Vector2(mb.x, mb.y));
if (snap_mode == SNAP_PIXEL)
- drag_from = drag_from.snapped(Vector2(1,1));
+ drag_from = drag_from.snapped(Vector2(1, 1));
else if (snap_mode == SNAP_GRID)
- drag_from=snap_point(drag_from);
- drag=true;
- if(node_sprite )
- rect_prev=node_sprite->get_region_rect();
- else if(node_patch9)
- rect_prev=node_patch9->get_region_rect();
- else if(obj_styleBox.is_valid())
- rect_prev=obj_styleBox->get_region_rect();
- else if(atlas_tex.is_valid())
- rect_prev=atlas_tex->get_region();
-
- for (int i=0; i<8;i++) {
- Vector2 tuv=endpoints[i];
- if (tuv.distance_to(Vector2(mb.x,mb.y))<8) {
- drag_index=i;
+ drag_from = snap_point(drag_from);
+ drag = true;
+ if (node_sprite)
+ rect_prev = node_sprite->get_region_rect();
+ else if (node_patch9)
+ rect_prev = node_patch9->get_region_rect();
+ else if (obj_styleBox.is_valid())
+ rect_prev = obj_styleBox->get_region_rect();
+ else if (atlas_tex.is_valid())
+ rect_prev = atlas_tex->get_region();
+
+ for (int i = 0; i < 8; i++) {
+ Vector2 tuv = endpoints[i];
+ if (tuv.distance_to(Vector2(mb.x, mb.y)) < 8) {
+ drag_index = i;
}
}
- if (drag_index==-1) {
+ if (drag_index == -1) {
creating = true;
- rect = Rect2(drag_from,Size2());
+ rect = Rect2(drag_from, Size2());
}
}
} else if (drag) {
if (edited_margin >= 0) {
undo_redo->create_action("Set Margin");
- static Margin m[4] = {MARGIN_TOP,MARGIN_BOTTOM,MARGIN_LEFT,MARGIN_RIGHT};
+ static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
if (node_patch9) {
- undo_redo->add_do_method(node_patch9 ,"set_patch_margin",m[edited_margin],node_patch9->get_patch_margin(m[edited_margin]));
- undo_redo->add_undo_method(node_patch9,"set_patch_margin",m[edited_margin],prev_margin);
+ undo_redo->add_do_method(node_patch9, "set_patch_margin", m[edited_margin], node_patch9->get_patch_margin(m[edited_margin]));
+ undo_redo->add_undo_method(node_patch9, "set_patch_margin", m[edited_margin], prev_margin);
} else if (obj_styleBox.is_valid()) {
- undo_redo->add_do_method(obj_styleBox.ptr() ,"set_margin_size",m[edited_margin],obj_styleBox->get_margin_size(m[edited_margin]));
- undo_redo->add_undo_method(obj_styleBox.ptr(),"set_margin_size",m[edited_margin],prev_margin);
+ undo_redo->add_do_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], obj_styleBox->get_margin_size(m[edited_margin]));
+ undo_redo->add_undo_method(obj_styleBox.ptr(), "set_margin_size", m[edited_margin], prev_margin);
obj_styleBox->emit_signal(CoreStringNames::get_singleton()->changed);
}
edited_margin = -1;
} else {
undo_redo->create_action("Set Region Rect");
- if(node_sprite){
- undo_redo->add_do_method(node_sprite ,"set_region_rect",node_sprite->get_region_rect());
- undo_redo->add_undo_method(node_sprite,"set_region_rect",rect_prev);
- }
- else if(atlas_tex.is_valid()){
- undo_redo->add_do_method(atlas_tex.ptr() ,"set_region",atlas_tex->get_region());
- undo_redo->add_undo_method(atlas_tex.ptr(),"set_region",rect_prev);
- }
- else if(node_patch9){
+ if (node_sprite) {
+ undo_redo->add_do_method(node_sprite, "set_region_rect", node_sprite->get_region_rect());
+ undo_redo->add_undo_method(node_sprite, "set_region_rect", rect_prev);
+ } else if (atlas_tex.is_valid()) {
+ undo_redo->add_do_method(atlas_tex.ptr(), "set_region", atlas_tex->get_region());
+ undo_redo->add_undo_method(atlas_tex.ptr(), "set_region", rect_prev);
+ } else if (node_patch9) {
// FIXME: Is this intentional?
- } else if(node_patch9){
- undo_redo->add_do_method(node_patch9 ,"set_region_rect",node_patch9->get_region_rect());
- undo_redo->add_undo_method(node_patch9,"set_region_rect",rect_prev);
+ } else if (node_patch9) {
+ undo_redo->add_do_method(node_patch9, "set_region_rect", node_patch9->get_region_rect());
+ undo_redo->add_undo_method(node_patch9, "set_region_rect", rect_prev);
} else if (obj_styleBox.is_valid()) {
- undo_redo->add_do_method(obj_styleBox.ptr() ,"set_region_rect",obj_styleBox->get_region_rect());
- undo_redo->add_undo_method(obj_styleBox.ptr(),"set_region_rect",rect_prev);
+ undo_redo->add_do_method(obj_styleBox.ptr(), "set_region_rect", obj_styleBox->get_region_rect());
+ undo_redo->add_undo_method(obj_styleBox.ptr(), "set_region_rect", rect_prev);
}
drag_index = -1;
}
- undo_redo->add_do_method(edit_draw,"update");
- undo_redo->add_undo_method(edit_draw,"update");
+ undo_redo->add_do_method(edit_draw, "update");
+ undo_redo->add_undo_method(edit_draw, "update");
undo_redo->commit_action();
- drag=false;
+ drag = false;
creating = false;
}
- } else if (mb.button_index==BUTTON_RIGHT && mb.pressed) {
+ } else if (mb.button_index == BUTTON_RIGHT && mb.pressed) {
if (drag) {
- drag=false;
+ drag = false;
if (edited_margin >= 0) {
- static Margin m[4] = {MARGIN_TOP,MARGIN_BOTTOM,MARGIN_LEFT,MARGIN_RIGHT};
+ static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
if (node_patch9)
- node_patch9->set_patch_margin(m[edited_margin],prev_margin);
+ node_patch9->set_patch_margin(m[edited_margin], prev_margin);
if (obj_styleBox.is_valid())
- obj_styleBox->set_margin_size(m[edited_margin],prev_margin);
+ obj_styleBox->set_margin_size(m[edited_margin], prev_margin);
edited_margin = -1;
} else {
apply_rect(rect_prev);
- rect=rect_prev;
+ rect = rect_prev;
edit_draw->update();
drag_index = -1;
}
@@ -393,124 +391,120 @@ void TextureRegionEditor::_region_input(const InputEvent& p_input)
} else if (mb.button_index == BUTTON_WHEEL_DOWN && mb.pressed) {
_zoom_out();
}
- } else if (p_input.type==InputEvent::MOUSE_MOTION) {
+ } else if (p_input.type == InputEvent::MOUSE_MOTION) {
- const InputEventMouseMotion &mm=p_input.mouse_motion;
+ const InputEventMouseMotion &mm = p_input.mouse_motion;
- if (mm.button_mask&BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
+ if (mm.button_mask & BUTTON_MASK_MIDDLE || Input::get_singleton()->is_key_pressed(KEY_SPACE)) {
- Vector2 draged(mm.relative_x,mm.relative_y);
- hscroll->set_value( hscroll->get_value()-draged.x );
- vscroll->set_value( vscroll->get_value()-draged.y );
+ Vector2 draged(mm.relative_x, mm.relative_y);
+ hscroll->set_value(hscroll->get_value() - draged.x);
+ vscroll->set_value(vscroll->get_value() - draged.y);
} else if (drag) {
if (edited_margin >= 0) {
float new_margin;
if (edited_margin == 0)
- new_margin = prev_margin + (mm.y-drag_from.y) / draw_zoom;
+ new_margin = prev_margin + (mm.y - drag_from.y) / draw_zoom;
else if (edited_margin == 1)
- new_margin = prev_margin - (mm.y-drag_from.y) / draw_zoom;
+ new_margin = prev_margin - (mm.y - drag_from.y) / draw_zoom;
else if (edited_margin == 2)
- new_margin = prev_margin + (mm.x-drag_from.x) / draw_zoom;
+ new_margin = prev_margin + (mm.x - drag_from.x) / draw_zoom;
else if (edited_margin == 3)
- new_margin = prev_margin - (mm.x-drag_from.x) / draw_zoom;
+ new_margin = prev_margin - (mm.x - drag_from.x) / draw_zoom;
if (new_margin < 0)
new_margin = 0;
- static Margin m[4] = {MARGIN_TOP,MARGIN_BOTTOM,MARGIN_LEFT,MARGIN_RIGHT};
+ static Margin m[4] = { MARGIN_TOP, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT };
if (node_patch9)
- node_patch9->set_patch_margin(m[edited_margin],new_margin);
+ node_patch9->set_patch_margin(m[edited_margin], new_margin);
if (obj_styleBox.is_valid())
- obj_styleBox->set_margin_size(m[edited_margin],new_margin);
+ obj_styleBox->set_margin_size(m[edited_margin], new_margin);
} else {
- Vector2 new_pos = mtx.affine_inverse().xform(Vector2(mm.x,mm.y));
+ Vector2 new_pos = mtx.affine_inverse().xform(Vector2(mm.x, mm.y));
if (snap_mode == SNAP_PIXEL)
- new_pos = new_pos.snapped(Vector2(1,1));
+ new_pos = new_pos.snapped(Vector2(1, 1));
else if (snap_mode == SNAP_GRID)
- new_pos=snap_point(new_pos);
+ new_pos = snap_point(new_pos);
if (creating) {
- rect = Rect2(drag_from,Size2());
+ rect = Rect2(drag_from, Size2());
rect.expand_to(new_pos);
apply_rect(rect);
edit_draw->update();
return;
}
- switch(drag_index) {
- case 0: {
- Vector2 p=rect_prev.pos+rect_prev.size;
- rect = Rect2(p,Size2());
+ switch (drag_index) {
+ case 0: {
+ Vector2 p = rect_prev.pos + rect_prev.size;
+ rect = Rect2(p, Size2());
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 1: {
- Vector2 p=rect_prev.pos+Vector2(0,rect_prev.size.y);
- rect = Rect2(p,Size2(rect_prev.size.x,0));
+ case 1: {
+ Vector2 p = rect_prev.pos + Vector2(0, rect_prev.size.y);
+ rect = Rect2(p, Size2(rect_prev.size.x, 0));
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 2: {
- Vector2 p=rect_prev.pos+Vector2(0,rect_prev.size.y);
- rect = Rect2(p,Size2());
+ case 2: {
+ Vector2 p = rect_prev.pos + Vector2(0, rect_prev.size.y);
+ rect = Rect2(p, Size2());
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 3: {
- Vector2 p=rect_prev.pos;
- rect = Rect2(p,Size2(0,rect_prev.size.y));
+ case 3: {
+ Vector2 p = rect_prev.pos;
+ rect = Rect2(p, Size2(0, rect_prev.size.y));
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 4: {
- Vector2 p=rect_prev.pos;
- rect = Rect2(p,Size2());
+ case 4: {
+ Vector2 p = rect_prev.pos;
+ rect = Rect2(p, Size2());
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 5: {
- Vector2 p=rect_prev.pos;
- rect = Rect2(p,Size2(rect_prev.size.x,0));
+ case 5: {
+ Vector2 p = rect_prev.pos;
+ rect = Rect2(p, Size2(rect_prev.size.x, 0));
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 6: {
- Vector2 p=rect_prev.pos+Vector2(rect_prev.size.x,0);
- rect = Rect2(p,Size2());
+ case 6: {
+ Vector2 p = rect_prev.pos + Vector2(rect_prev.size.x, 0);
+ rect = Rect2(p, Size2());
rect.expand_to(new_pos);
apply_rect(rect);
} break;
- case 7: {
- Vector2 p=rect_prev.pos+Vector2(rect_prev.size.x,0);
- rect = Rect2(p,Size2(0,rect_prev.size.y));
+ case 7: {
+ Vector2 p = rect_prev.pos + Vector2(rect_prev.size.x, 0);
+ rect = Rect2(p, Size2(0, rect_prev.size.y));
rect.expand_to(new_pos);
apply_rect(rect);
} break;
-
}
}
edit_draw->update();
}
-
}
}
-void TextureRegionEditor::_scroll_changed(float)
-{
+void TextureRegionEditor::_scroll_changed(float) {
if (updating_scroll)
return;
- draw_ofs.x=hscroll->get_value();
- draw_ofs.y=vscroll->get_value();
+ draw_ofs.x = hscroll->get_value();
+ draw_ofs.y = vscroll->get_value();
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_mode(int p_mode)
-{
- snap_mode_button->get_popup()->set_item_checked(snap_mode,false);
+void TextureRegionEditor::_set_snap_mode(int p_mode) {
+ snap_mode_button->get_popup()->set_item_checked(snap_mode, false);
snap_mode = p_mode;
snap_mode_button->set_text(snap_mode_button->get_popup()->get_item_text(p_mode));
- snap_mode_button->get_popup()->set_item_checked(snap_mode,true);
+ snap_mode_button->get_popup()->set_item_checked(snap_mode, true);
if (snap_mode == SNAP_GRID)
hb_grid->show();
@@ -520,91 +514,80 @@ void TextureRegionEditor::_set_snap_mode(int p_mode)
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_off_x(float p_val)
-{
- snap_offset.x=p_val;
+void TextureRegionEditor::_set_snap_off_x(float p_val) {
+ snap_offset.x = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_off_y(float p_val)
-{
- snap_offset.y=p_val;
+void TextureRegionEditor::_set_snap_off_y(float p_val) {
+ snap_offset.y = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_step_x(float p_val)
-{
- snap_step.x=p_val;
+void TextureRegionEditor::_set_snap_step_x(float p_val) {
+ snap_step.x = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_step_y(float p_val)
-{
- snap_step.y=p_val;
+void TextureRegionEditor::_set_snap_step_y(float p_val) {
+ snap_step.y = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_sep_x(float p_val)
-{
+void TextureRegionEditor::_set_snap_sep_x(float p_val) {
snap_separation.x = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_set_snap_sep_y(float p_val)
-{
+void TextureRegionEditor::_set_snap_sep_y(float p_val) {
snap_separation.y = p_val;
edit_draw->update();
}
-void TextureRegionEditor::_zoom_in()
-{
+void TextureRegionEditor::_zoom_in() {
if (draw_zoom < 8) {
draw_zoom *= 2;
edit_draw->update();
}
}
-void TextureRegionEditor::_zoom_reset()
-{
+void TextureRegionEditor::_zoom_reset() {
if (draw_zoom == 1) return;
draw_zoom = 1;
edit_draw->update();
}
-void TextureRegionEditor::_zoom_out()
-{
+void TextureRegionEditor::_zoom_out() {
if (draw_zoom > 0.25) {
draw_zoom /= 2;
edit_draw->update();
}
}
-void TextureRegionEditor::apply_rect(const Rect2& rect){
- if(node_sprite)
+void TextureRegionEditor::apply_rect(const Rect2 &rect) {
+ if (node_sprite)
node_sprite->set_region_rect(rect);
- else if(node_patch9)
+ else if (node_patch9)
node_patch9->set_region_rect(rect);
- else if(obj_styleBox.is_valid())
+ else if (obj_styleBox.is_valid())
obj_styleBox->set_region_rect(rect);
- else if(atlas_tex.is_valid())
+ else if (atlas_tex.is_valid())
atlas_tex->set_region(rect);
}
-void TextureRegionEditor::_notification(int p_what)
-{
- switch(p_what) {
- case NOTIFICATION_READY: {
+void TextureRegionEditor::_notification(int p_what) {
+ switch (p_what) {
+ case NOTIFICATION_READY: {
zoom_out->set_icon(get_icon("ZoomLess", "EditorIcons"));
zoom_reset->set_icon(get_icon("ZoomReset", "EditorIcons"));
zoom_in->set_icon(get_icon("ZoomMore", "EditorIcons"));
- icon_zoom->set_texture( get_icon("Zoom", "EditorIcons"));
+ icon_zoom->set_texture(get_icon("Zoom", "EditorIcons"));
} break;
}
}
-void TextureRegionEditor::_node_removed(Object *p_obj)
-{
- if(p_obj == node_sprite || p_obj == node_patch9 || p_obj == obj_styleBox.ptr() || p_obj == atlas_tex.ptr()) {
+void TextureRegionEditor::_node_removed(Object *p_obj) {
+ if (p_obj == node_sprite || p_obj == node_patch9 || p_obj == obj_styleBox.ptr() || p_obj == atlas_tex.ptr()) {
node_patch9 = NULL;
node_sprite = NULL;
obj_styleBox = Ref<StyleBox>(NULL);
@@ -613,35 +596,33 @@ void TextureRegionEditor::_node_removed(Object *p_obj)
}
}
-void TextureRegionEditor::_bind_methods()
-{
- ClassDB::bind_method(D_METHOD("_edit_region"),&TextureRegionEditor::_edit_region);
- ClassDB::bind_method(D_METHOD("_region_draw"),&TextureRegionEditor::_region_draw);
- ClassDB::bind_method(D_METHOD("_region_input"),&TextureRegionEditor::_region_input);
- ClassDB::bind_method(D_METHOD("_scroll_changed"),&TextureRegionEditor::_scroll_changed);
- ClassDB::bind_method(D_METHOD("_node_removed"),&TextureRegionEditor::_node_removed);
- ClassDB::bind_method(D_METHOD("_set_snap_mode"),&TextureRegionEditor::_set_snap_mode);
- ClassDB::bind_method(D_METHOD("_set_snap_off_x"),&TextureRegionEditor::_set_snap_off_x);
- ClassDB::bind_method(D_METHOD("_set_snap_off_y"),&TextureRegionEditor::_set_snap_off_y);
- ClassDB::bind_method(D_METHOD("_set_snap_step_x"),&TextureRegionEditor::_set_snap_step_x);
- ClassDB::bind_method(D_METHOD("_set_snap_step_y"),&TextureRegionEditor::_set_snap_step_y);
- ClassDB::bind_method(D_METHOD("_set_snap_sep_x"),&TextureRegionEditor::_set_snap_sep_x);
- ClassDB::bind_method(D_METHOD("_set_snap_sep_y"),&TextureRegionEditor::_set_snap_sep_y);
- ClassDB::bind_method(D_METHOD("_zoom_in"),&TextureRegionEditor::_zoom_in);
- ClassDB::bind_method(D_METHOD("_zoom_reset"),&TextureRegionEditor::_zoom_reset);
- ClassDB::bind_method(D_METHOD("_zoom_out"),&TextureRegionEditor::_zoom_out);
+void TextureRegionEditor::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_edit_region"), &TextureRegionEditor::_edit_region);
+ ClassDB::bind_method(D_METHOD("_region_draw"), &TextureRegionEditor::_region_draw);
+ ClassDB::bind_method(D_METHOD("_region_input"), &TextureRegionEditor::_region_input);
+ ClassDB::bind_method(D_METHOD("_scroll_changed"), &TextureRegionEditor::_scroll_changed);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &TextureRegionEditor::_node_removed);
+ ClassDB::bind_method(D_METHOD("_set_snap_mode"), &TextureRegionEditor::_set_snap_mode);
+ ClassDB::bind_method(D_METHOD("_set_snap_off_x"), &TextureRegionEditor::_set_snap_off_x);
+ ClassDB::bind_method(D_METHOD("_set_snap_off_y"), &TextureRegionEditor::_set_snap_off_y);
+ ClassDB::bind_method(D_METHOD("_set_snap_step_x"), &TextureRegionEditor::_set_snap_step_x);
+ ClassDB::bind_method(D_METHOD("_set_snap_step_y"), &TextureRegionEditor::_set_snap_step_y);
+ ClassDB::bind_method(D_METHOD("_set_snap_sep_x"), &TextureRegionEditor::_set_snap_sep_x);
+ ClassDB::bind_method(D_METHOD("_set_snap_sep_y"), &TextureRegionEditor::_set_snap_sep_y);
+ ClassDB::bind_method(D_METHOD("_zoom_in"), &TextureRegionEditor::_zoom_in);
+ ClassDB::bind_method(D_METHOD("_zoom_reset"), &TextureRegionEditor::_zoom_reset);
+ ClassDB::bind_method(D_METHOD("_zoom_out"), &TextureRegionEditor::_zoom_out);
}
-void TextureRegionEditor::edit(Object *p_obj)
-{
- if (node_sprite && node_sprite->is_connected("texture_changed",this,"_edit_region"))
- node_sprite->disconnect("texture_changed",this,"_edit_region");
- if (node_patch9 && node_patch9->is_connected("texture_changed",this,"_edit_region"))
- node_patch9->disconnect("texture_changed",this,"_edit_region");
- if (obj_styleBox.is_valid() && obj_styleBox->is_connected("texture_changed",this,"_edit_region"))
- obj_styleBox->disconnect("texture_changed",this,"_edit_region");
- if (atlas_tex.is_valid() && atlas_tex->is_connected("atlas_changed",this,"_edit_region"))
- atlas_tex->disconnect("atlas_changed",this,"_edit_region");
+void TextureRegionEditor::edit(Object *p_obj) {
+ if (node_sprite && node_sprite->is_connected("texture_changed", this, "_edit_region"))
+ node_sprite->disconnect("texture_changed", this, "_edit_region");
+ if (node_patch9 && node_patch9->is_connected("texture_changed", this, "_edit_region"))
+ node_patch9->disconnect("texture_changed", this, "_edit_region");
+ if (obj_styleBox.is_valid() && obj_styleBox->is_connected("texture_changed", this, "_edit_region"))
+ obj_styleBox->disconnect("texture_changed", this, "_edit_region");
+ if (atlas_tex.is_valid() && atlas_tex->is_connected("atlas_changed", this, "_edit_region"))
+ atlas_tex->disconnect("atlas_changed", this, "_edit_region");
if (p_obj) {
node_sprite = p_obj->cast_to<Sprite>();
node_patch9 = p_obj->cast_to<NinePatchRect>();
@@ -649,22 +630,22 @@ void TextureRegionEditor::edit(Object *p_obj)
obj_styleBox = Ref<StyleBoxTexture>(p_obj->cast_to<StyleBoxTexture>());
if (p_obj->cast_to<AtlasTexture>()) {
atlas_tex = Ref<AtlasTexture>(p_obj->cast_to<AtlasTexture>());
- atlas_tex->connect("atlas_changed",this,"_edit_region");
+ atlas_tex->connect("atlas_changed", this, "_edit_region");
} else {
- p_obj->connect("texture_changed",this,"_edit_region");
+ p_obj->connect("texture_changed", this, "_edit_region");
}
p_obj->add_change_receptor(this);
- p_obj->connect("tree_exited",this,"_node_removed",varray(p_obj),CONNECT_ONESHOT);
+ p_obj->connect("tree_exited", this, "_node_removed", varray(p_obj), CONNECT_ONESHOT);
_edit_region();
} else {
- if(node_sprite)
- node_sprite->disconnect("tree_exited",this,"_node_removed");
- else if(node_patch9)
- node_patch9->disconnect("tree_exited",this,"_node_removed");
- else if(obj_styleBox.is_valid())
- obj_styleBox->disconnect("tree_exited",this,"_node_removed");
- else if(atlas_tex.is_valid())
- atlas_tex->disconnect("tree_exited",this,"_node_removed");
+ if (node_sprite)
+ node_sprite->disconnect("tree_exited", this, "_node_removed");
+ else if (node_patch9)
+ node_patch9->disconnect("tree_exited", this, "_node_removed");
+ else if (obj_styleBox.is_valid())
+ obj_styleBox->disconnect("tree_exited", this, "_node_removed");
+ else if (atlas_tex.is_valid())
+ atlas_tex->disconnect("tree_exited", this, "_node_removed");
node_sprite = NULL;
node_patch9 = NULL;
@@ -680,16 +661,15 @@ void TextureRegionEditor::_changed_callback(Object *p_changed, const char *p_pro
}
}
-void TextureRegionEditor::_edit_region()
-{
+void TextureRegionEditor::_edit_region() {
Ref<Texture> texture = NULL;
- if(node_sprite )
+ if (node_sprite)
texture = node_sprite->get_texture();
- else if(node_patch9 )
+ else if (node_patch9)
texture = node_patch9->get_texture();
- else if(obj_styleBox.is_valid())
+ else if (obj_styleBox.is_valid())
texture = obj_styleBox->get_texture();
- else if(atlas_tex.is_valid())
+ else if (atlas_tex.is_valid())
texture = atlas_tex->get_atlas();
if (texture.is_null()) {
@@ -703,30 +683,30 @@ void TextureRegionEditor::_edit_region()
bm.create_from_image_alpha(i);
for (int y = 0; y < i.get_height(); y++) {
for (int x = 0; x < i.get_width(); x++) {
- if (bm.get_bit(Point2(x,y))) {
+ if (bm.get_bit(Point2(x, y))) {
bool found = false;
- for (List<Rect2>::Element *E = autoslice_cache.front(); E; E=E->next()) {
+ for (List<Rect2>::Element *E = autoslice_cache.front(); E; E = E->next()) {
Rect2 grown = E->get().grow(1.5);
- if (grown.has_point(Point2(x,y))) {
- E->get().expand_to(Point2(x,y));
- E->get().expand_to(Point2(x+1,y+1));
- x = E->get().pos.x+E->get().size.x-1;
+ if (grown.has_point(Point2(x, y))) {
+ E->get().expand_to(Point2(x, y));
+ E->get().expand_to(Point2(x + 1, y + 1));
+ x = E->get().pos.x + E->get().size.x - 1;
bool merged = true;
while (merged) {
merged = false;
bool queue_erase = false;
- for (List<Rect2>::Element *F = autoslice_cache.front(); F; F=F->next()) {
- if (queue_erase){
+ for (List<Rect2>::Element *F = autoslice_cache.front(); F; F = F->next()) {
+ if (queue_erase) {
autoslice_cache.erase(F->prev());
queue_erase = false;
}
- if (F==E)
+ if (F == E)
continue;
if (E->get().grow(1).intersects(F->get())) {
E->get().expand_to(F->get().pos);
- E->get().expand_to(F->get().pos+F->get().size);
+ E->get().expand_to(F->get().pos + F->get().size);
if (F->prev()) {
- F=F->prev();
+ F = F->prev();
autoslice_cache.erase(F->next());
} else {
queue_erase = true;
@@ -741,7 +721,7 @@ void TextureRegionEditor::_edit_region()
}
}
if (!found) {
- Rect2 new_rect(x,y,1,1);
+ Rect2 new_rect(x, y, 1, 1);
autoslice_cache.push_back(new_rect);
}
}
@@ -749,12 +729,11 @@ void TextureRegionEditor::_edit_region()
}
}
-
- if(node_sprite )
+ if (node_sprite)
rect = node_sprite->get_region_rect();
- else if(node_patch9 )
+ else if (node_patch9)
rect = node_patch9->get_region_rect();
- else if(obj_styleBox.is_valid())
+ else if (obj_styleBox.is_valid())
rect = obj_styleBox->get_region_rect();
else if (atlas_tex.is_valid())
rect = atlas_tex->get_region();
@@ -764,13 +743,13 @@ void TextureRegionEditor::_edit_region()
inline float _snap_scalar(float p_offset, float p_step, float separation, float p_target) {
if (p_step != 0) {
- float a = Math::stepify(p_target - p_offset, p_step+separation) + p_offset;
+ float a = Math::stepify(p_target - p_offset, p_step + separation) + p_offset;
float b = a;
if (p_target >= 0)
b -= separation;
else
b += p_step;
- return (Math::abs(p_target-a) < Math::abs(p_target-b)) ? a : b;
+ return (Math::abs(p_target - a) < Math::abs(p_target - b)) ? a : b;
}
return p_target;
}
@@ -784,48 +763,47 @@ Vector2 TextureRegionEditor::snap_point(Vector2 p_target) const {
return p_target;
}
-TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
-{
+TextureRegionEditor::TextureRegionEditor(EditorNode *p_editor) {
node_sprite = NULL;
node_patch9 = NULL;
obj_styleBox = Ref<StyleBoxTexture>(NULL);
atlas_tex = Ref<AtlasTexture>(NULL);
- editor=p_editor;
+ editor = p_editor;
undo_redo = editor->get_undo_redo();
- snap_step=Vector2(10,10);
- snap_separation = Vector2(0,0);
+ snap_step = Vector2(10, 10);
+ snap_separation = Vector2(0, 0);
edited_margin = -1;
drag_index = -1;
- drag=false;
+ drag = false;
- VBoxContainer *main_vb = memnew( VBoxContainer );
+ VBoxContainer *main_vb = memnew(VBoxContainer);
add_child(main_vb);
main_vb->set_area_as_parent_rect(0);
- HBoxContainer *hb_tools = memnew( HBoxContainer );
+ HBoxContainer *hb_tools = memnew(HBoxContainer);
main_vb->add_child(hb_tools);
- hb_tools->add_child(memnew( Label(TTR("Snap Mode:")) ));
+ hb_tools->add_child(memnew(Label(TTR("Snap Mode:"))));
- snap_mode_button = memnew( MenuButton );
+ snap_mode_button = memnew(MenuButton);
hb_tools->add_child(snap_mode_button);
snap_mode_button->set_text(TTR("<None>"));
PopupMenu *p = snap_mode_button->get_popup();
- p->add_item(TTR("<None>"),0);
- p->add_item(TTR("Pixel Snap"),1);
- p->add_item(TTR("Grid Snap"),2);
- p->add_item(TTR("Auto Slice"),3);
+ p->add_item(TTR("<None>"), 0);
+ p->add_item(TTR("Pixel Snap"), 1);
+ p->add_item(TTR("Grid Snap"), 2);
+ p->add_item(TTR("Auto Slice"), 3);
for (int i = 0; i < 4; i++)
- p->set_item_as_checkable(i,true);
- p->set_item_checked(0,true);
+ p->set_item_as_checkable(i, true);
+ p->set_item_checked(0, true);
p->connect("id_pressed", this, "_set_snap_mode");
- hb_grid = memnew( HBoxContainer );
+ hb_grid = memnew(HBoxContainer);
hb_tools->add_child(hb_grid);
- hb_grid->add_child( memnew( VSeparator ));
+ hb_grid->add_child(memnew(VSeparator));
- hb_grid->add_child( memnew( Label(TTR("Offset:")) ) );
+ hb_grid->add_child(memnew(Label(TTR("Offset:"))));
- sb_off_x = memnew( SpinBox );
+ sb_off_x = memnew(SpinBox);
sb_off_x->set_min(-256);
sb_off_x->set_max(256);
sb_off_x->set_step(1);
@@ -834,7 +812,7 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
sb_off_x->connect("value_changed", this, "_set_snap_off_x");
hb_grid->add_child(sb_off_x);
- sb_off_y = memnew( SpinBox );
+ sb_off_y = memnew(SpinBox);
sb_off_y->set_min(-256);
sb_off_y->set_max(256);
sb_off_y->set_step(1);
@@ -843,10 +821,10 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
sb_off_y->connect("value_changed", this, "_set_snap_off_y");
hb_grid->add_child(sb_off_y);
- hb_grid->add_child( memnew( VSeparator ));
- hb_grid->add_child( memnew( Label(TTR("Step:")) ) );
+ hb_grid->add_child(memnew(VSeparator));
+ hb_grid->add_child(memnew(Label(TTR("Step:"))));
- sb_step_x = memnew( SpinBox );
+ sb_step_x = memnew(SpinBox);
sb_step_x->set_min(-256);
sb_step_x->set_max(256);
sb_step_x->set_step(1);
@@ -855,7 +833,7 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
sb_step_x->connect("value_changed", this, "_set_snap_step_x");
hb_grid->add_child(sb_step_x);
- sb_step_y = memnew( SpinBox );
+ sb_step_y = memnew(SpinBox);
sb_step_y->set_min(-256);
sb_step_y->set_max(256);
sb_step_y->set_step(1);
@@ -864,10 +842,10 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
sb_step_y->connect("value_changed", this, "_set_snap_step_y");
hb_grid->add_child(sb_step_y);
- hb_grid->add_child( memnew( VSeparator ));
- hb_grid->add_child( memnew( Label(TTR("Separation:")) ) );
+ hb_grid->add_child(memnew(VSeparator));
+ hb_grid->add_child(memnew(Label(TTR("Separation:"))));
- sb_sep_x = memnew( SpinBox );
+ sb_sep_x = memnew(SpinBox);
sb_sep_x->set_min(0);
sb_sep_x->set_max(256);
sb_sep_x->set_step(1);
@@ -876,7 +854,7 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
sb_sep_x->connect("value_changed", this, "_set_snap_sep_x");
hb_grid->add_child(sb_sep_x);
- sb_sep_y = memnew( SpinBox );
+ sb_sep_y = memnew(SpinBox);
sb_sep_y->set_min(0);
sb_sep_y->set_max(256);
sb_sep_y->set_step(1);
@@ -887,60 +865,56 @@ TextureRegionEditor::TextureRegionEditor(EditorNode* p_editor)
hb_grid->hide();
- HBoxContainer *main_hb = memnew( HBoxContainer );
+ HBoxContainer *main_hb = memnew(HBoxContainer);
main_vb->add_child(main_hb);
- edit_draw = memnew( Control );
+ edit_draw = memnew(Control);
main_hb->add_child(edit_draw);
main_hb->set_v_size_flags(SIZE_EXPAND_FILL);
edit_draw->set_h_size_flags(SIZE_EXPAND_FILL);
- Control * separator = memnew( Control );
+ Control *separator = memnew(Control);
separator->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hb_tools->add_child(separator);
- icon_zoom = memnew( TextureRect );
+ icon_zoom = memnew(TextureRect);
hb_tools->add_child(icon_zoom);
- zoom_out = memnew( ToolButton );
+ zoom_out = memnew(ToolButton);
zoom_out->connect("pressed", this, "_zoom_out");
hb_tools->add_child(zoom_out);
- zoom_reset = memnew( ToolButton );
+ zoom_reset = memnew(ToolButton);
zoom_reset->connect("pressed", this, "_zoom_reset");
hb_tools->add_child(zoom_reset);
- zoom_in = memnew( ToolButton );
+ zoom_in = memnew(ToolButton);
zoom_in->connect("pressed", this, "_zoom_in");
hb_tools->add_child(zoom_in);
- vscroll = memnew( VScrollBar);
+ vscroll = memnew(VScrollBar);
main_hb->add_child(vscroll);
- vscroll->connect("value_changed",this,"_scroll_changed");
- hscroll = memnew( HScrollBar );
+ vscroll->connect("value_changed", this, "_scroll_changed");
+ hscroll = memnew(HScrollBar);
main_vb->add_child(hscroll);
- hscroll->connect("value_changed",this,"_scroll_changed");
+ hscroll->connect("value_changed", this, "_scroll_changed");
- edit_draw->connect("draw",this,"_region_draw");
- edit_draw->connect("gui_input",this,"_region_input");
- draw_zoom=1.0;
- updating_scroll=false;
+ edit_draw->connect("draw", this, "_region_draw");
+ edit_draw->connect("gui_input", this, "_region_input");
+ draw_zoom = 1.0;
+ updating_scroll = false;
edit_draw->set_clip_contents(true);
-
}
-void TextureRegionEditorPlugin::edit(Object *p_node)
-{
+void TextureRegionEditorPlugin::edit(Object *p_node) {
region_editor->edit(p_node);
}
-bool TextureRegionEditorPlugin::handles(Object *p_obj) const
-{
+bool TextureRegionEditorPlugin::handles(Object *p_obj) const {
return p_obj->is_class("Sprite") || p_obj->is_class("Patch9Rect") || p_obj->is_class("StyleBoxTexture") || p_obj->is_class("AtlasTexture");
}
-void TextureRegionEditorPlugin::make_visible(bool p_visible)
-{
+void TextureRegionEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
region_button->show();
if (region_button->is_pressed())
@@ -952,21 +926,20 @@ void TextureRegionEditorPlugin::make_visible(bool p_visible)
}
}
-
Dictionary TextureRegionEditorPlugin::get_state() const {
Dictionary state;
- state["zoom"]=region_editor->draw_zoom;
- state["snap_offset"]=region_editor->snap_offset;
- state["snap_step"]=region_editor->snap_step;
- state["snap_separation"]=region_editor->snap_separation;
- state["snap_mode"]=region_editor->snap_mode;
+ state["zoom"] = region_editor->draw_zoom;
+ state["snap_offset"] = region_editor->snap_offset;
+ state["snap_step"] = region_editor->snap_step;
+ state["snap_separation"] = region_editor->snap_separation;
+ state["snap_mode"] = region_editor->snap_mode;
return state;
}
-void TextureRegionEditorPlugin::set_state(const Dictionary& p_state){
+void TextureRegionEditorPlugin::set_state(const Dictionary &p_state) {
- Dictionary state=p_state;
+ Dictionary state = p_state;
if (state.has("zoom")) {
region_editor->draw_zoom = p_state["zoom"];
}
@@ -995,18 +968,16 @@ void TextureRegionEditorPlugin::set_state(const Dictionary& p_state){
if (state.has("snap_mode")) {
region_editor->_set_snap_mode(state["snap_mode"]);
}
-
}
-TextureRegionEditorPlugin::TextureRegionEditorPlugin(EditorNode *p_node)
-{
+TextureRegionEditorPlugin::TextureRegionEditorPlugin(EditorNode *p_node) {
editor = p_node;
- region_editor = memnew ( TextureRegionEditor(p_node) );
+ region_editor = memnew(TextureRegionEditor(p_node));
region_button = p_node->add_bottom_panel_item(TTR("Texture Region"), region_editor);
region_button->set_tooltip(TTR("Texture Region Editor"));
- region_editor->set_custom_minimum_size(Size2(0,200));
+ region_editor->set_custom_minimum_size(Size2(0, 200));
region_editor->hide();
region_button->hide();
}
diff --git a/editor/plugins/texture_region_editor_plugin.h b/editor/plugins/texture_region_editor_plugin.h
index 8e88f0b707..b3763acc22 100644
--- a/editor/plugins/texture_region_editor_plugin.h
+++ b/editor/plugins/texture_region_editor_plugin.h
@@ -33,8 +33,8 @@
#define TEXTURE_REGION_EDITOR_PLUGIN_H
#include "canvas_item_editor_plugin.h"
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/sprite.h"
#include "scene/gui/patch_9_rect.h"
#include "scene/resources/style_box.h"
@@ -42,7 +42,7 @@
class TextureRegionEditor : public Control {
- GDCLASS(TextureRegionEditor, Control );
+ GDCLASS(TextureRegionEditor, Control);
enum SnapMode {
SNAP_NONE,
@@ -57,7 +57,7 @@ class TextureRegionEditor : public Control {
ToolButton *zoom_in;
ToolButton *zoom_reset;
ToolButton *zoom_out;
- HBoxContainer * hb_grid; //For showing/hiding the grid controls when changing the SnapMode
+ HBoxContainer *hb_grid; //For showing/hiding the grid controls when changing the SnapMode
SpinBox *sb_step_y;
SpinBox *sb_step_x;
SpinBox *sb_off_y;
@@ -70,7 +70,7 @@ class TextureRegionEditor : public Control {
HScrollBar *hscroll;
EditorNode *editor;
- UndoRedo* undo_redo;
+ UndoRedo *undo_redo;
Vector2 draw_ofs;
float draw_zoom;
@@ -107,9 +107,9 @@ class TextureRegionEditor : public Control {
void _zoom_in();
void _zoom_reset();
void _zoom_out();
- void apply_rect(const Rect2& rect);
-protected:
+ void apply_rect(const Rect2 &rect);
+protected:
void _notification(int p_what);
void _node_removed(Object *p_obj);
static void _bind_methods();
@@ -119,26 +119,23 @@ protected:
virtual void _changed_callback(Object *p_changed, const char *p_prop);
public:
-
void _edit_region();
void _region_draw();
void _region_input(const InputEvent &p_input);
void _scroll_changed(float);
void edit(Object *p_obj);
- TextureRegionEditor(EditorNode* p_editor);
-
+ TextureRegionEditor(EditorNode *p_editor);
};
-class TextureRegionEditorPlugin : public EditorPlugin
-{
- GDCLASS( TextureRegionEditorPlugin, EditorPlugin );
+class TextureRegionEditorPlugin : public EditorPlugin {
+ GDCLASS(TextureRegionEditorPlugin, EditorPlugin);
Button *region_button;
TextureRegionEditor *region_editor;
EditorNode *editor;
-public:
+public:
virtual String get_name() const { return "TextureRegion"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
diff --git a/editor/plugins/theme_editor_plugin.cpp b/editor/plugins/theme_editor_plugin.cpp
index 4b8fea5a45..03316cc7d9 100644
--- a/editor/plugins/theme_editor_plugin.cpp
+++ b/editor/plugins/theme_editor_plugin.cpp
@@ -28,70 +28,64 @@
/*************************************************************************/
#include "theme_editor_plugin.h"
-#include "version.h"
#include "os/file_access.h"
+#include "version.h"
-void ThemeEditor::edit(const Ref<Theme>& p_theme) {
+void ThemeEditor::edit(const Ref<Theme> &p_theme) {
- theme=p_theme;
+ theme = p_theme;
main_vb->set_theme(p_theme);
-
}
-
void ThemeEditor::_propagate_redraw(Control *p_at) {
p_at->notification(NOTIFICATION_THEME_CHANGED);
p_at->minimum_size_changed();
p_at->update();
- for(int i=0;i<p_at->get_child_count();i++) {
+ for (int i = 0; i < p_at->get_child_count(); i++) {
Control *a = p_at->get_child(i)->cast_to<Control>();
if (a)
_propagate_redraw(a);
-
}
}
void ThemeEditor::_refresh_interval() {
_propagate_redraw(main_vb);
-
}
void ThemeEditor::_type_menu_cbk(int p_option) {
-
- type_edit->set_text( type_menu->get_popup()->get_item_text(p_option) );
+ type_edit->set_text(type_menu->get_popup()->get_item_text(p_option));
}
void ThemeEditor::_name_menu_about_to_show() {
- String fromtype=type_edit->get_text();
+ String fromtype = type_edit->get_text();
List<StringName> names;
- if (popup_mode==POPUP_ADD) {
+ if (popup_mode == POPUP_ADD) {
- switch(type_select->get_selected()) {
+ switch (type_select->get_selected()) {
- case 0: Theme::get_default()->get_icon_list(fromtype,&names); break;
- case 1: Theme::get_default()->get_stylebox_list(fromtype,&names); break;
- case 2: Theme::get_default()->get_font_list(fromtype,&names); break;
- case 3: Theme::get_default()->get_color_list(fromtype,&names); break;
- case 4: Theme::get_default()->get_constant_list(fromtype,&names); break;
+ case 0: Theme::get_default()->get_icon_list(fromtype, &names); break;
+ case 1: Theme::get_default()->get_stylebox_list(fromtype, &names); break;
+ case 2: Theme::get_default()->get_font_list(fromtype, &names); break;
+ case 3: Theme::get_default()->get_color_list(fromtype, &names); break;
+ case 4: Theme::get_default()->get_constant_list(fromtype, &names); break;
}
- } else if (popup_mode==POPUP_REMOVE) {
+ } else if (popup_mode == POPUP_REMOVE) {
- theme->get_icon_list(fromtype,&names);
- theme->get_stylebox_list(fromtype,&names);
- theme->get_font_list(fromtype,&names);
- theme->get_color_list(fromtype,&names);
- theme->get_constant_list(fromtype,&names);
+ theme->get_icon_list(fromtype, &names);
+ theme->get_stylebox_list(fromtype, &names);
+ theme->get_font_list(fromtype, &names);
+ theme->get_color_list(fromtype, &names);
+ theme->get_constant_list(fromtype, &names);
}
-
name_menu->get_popup()->clear();
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
name_menu->get_popup()->add_item(E->get());
}
@@ -99,108 +93,103 @@ void ThemeEditor::_name_menu_about_to_show() {
void ThemeEditor::_name_menu_cbk(int p_option) {
- name_edit->set_text( name_menu->get_popup()->get_item_text(p_option) );
+ name_edit->set_text(name_menu->get_popup()->get_item_text(p_option));
}
struct _TECategory {
- template<class T>
+ template <class T>
struct RefItem {
Ref<T> item;
StringName name;
- bool operator<(const RefItem<T>& p) const { return item->get_instance_ID() < p.item->get_instance_ID(); }
+ bool operator<(const RefItem<T> &p) const { return item->get_instance_ID() < p.item->get_instance_ID(); }
};
- template<class T>
+ template <class T>
struct Item {
T item;
String name;
- bool operator<(const Item<T>& p) const { return name < p.name; }
+ bool operator<(const Item<T> &p) const { return name < p.name; }
};
-
Set<RefItem<StyleBox> > stylebox_items;
Set<RefItem<Font> > font_items;
Set<RefItem<Texture> > icon_items;
Set<Item<Color> > color_items;
Set<Item<int> > constant_items;
-
};
-
void ThemeEditor::_save_template_cbk(String fname) {
String filename = file_dialog->get_current_path();
- Map<String,_TECategory> categories;
+ Map<String, _TECategory> categories;
//fill types
List<StringName> type_list;
Theme::get_default()->get_type_list(&type_list);
- for (List<StringName>::Element *E=type_list.front();E;E=E->next()) {
- categories.insert(E->get(),_TECategory());
+ for (List<StringName>::Element *E = type_list.front(); E; E = E->next()) {
+ categories.insert(E->get(), _TECategory());
}
//fill default theme
- for(Map<String,_TECategory>::Element *E=categories.front();E;E=E->next() ) {
+ for (Map<String, _TECategory>::Element *E = categories.front(); E; E = E->next()) {
_TECategory &tc = E->get();
List<StringName> stylebox_list;
- Theme::get_default()->get_stylebox_list(E->key(),&stylebox_list);
- for (List<StringName>::Element *F=stylebox_list.front();F;F=F->next()) {
+ Theme::get_default()->get_stylebox_list(E->key(), &stylebox_list);
+ for (List<StringName>::Element *F = stylebox_list.front(); F; F = F->next()) {
_TECategory::RefItem<StyleBox> it;
- it.name=F->get();
- it.item=Theme::get_default()->get_stylebox(F->get(),E->key());
+ it.name = F->get();
+ it.item = Theme::get_default()->get_stylebox(F->get(), E->key());
tc.stylebox_items.insert(it);
}
List<StringName> font_list;
- Theme::get_default()->get_font_list(E->key(),&font_list);
- for (List<StringName>::Element *F=font_list.front();F;F=F->next()) {
+ Theme::get_default()->get_font_list(E->key(), &font_list);
+ for (List<StringName>::Element *F = font_list.front(); F; F = F->next()) {
_TECategory::RefItem<Font> it;
- it.name=F->get();
- it.item=Theme::get_default()->get_font(F->get(),E->key());
+ it.name = F->get();
+ it.item = Theme::get_default()->get_font(F->get(), E->key());
tc.font_items.insert(it);
}
List<StringName> icon_list;
- Theme::get_default()->get_icon_list(E->key(),&icon_list);
- for (List<StringName>::Element *F=icon_list.front();F;F=F->next()) {
+ Theme::get_default()->get_icon_list(E->key(), &icon_list);
+ for (List<StringName>::Element *F = icon_list.front(); F; F = F->next()) {
_TECategory::RefItem<Texture> it;
- it.name=F->get();
- it.item=Theme::get_default()->get_icon(F->get(),E->key());
+ it.name = F->get();
+ it.item = Theme::get_default()->get_icon(F->get(), E->key());
tc.icon_items.insert(it);
}
List<StringName> color_list;
- Theme::get_default()->get_color_list(E->key(),&color_list);
- for (List<StringName>::Element *F=color_list.front();F;F=F->next()) {
+ Theme::get_default()->get_color_list(E->key(), &color_list);
+ for (List<StringName>::Element *F = color_list.front(); F; F = F->next()) {
_TECategory::Item<Color> it;
- it.name=F->get();
- it.item=Theme::get_default()->get_color(F->get(),E->key());
+ it.name = F->get();
+ it.item = Theme::get_default()->get_color(F->get(), E->key());
tc.color_items.insert(it);
}
List<StringName> constant_list;
- Theme::get_default()->get_constant_list(E->key(),&constant_list);
- for (List<StringName>::Element *F=constant_list.front();F;F=F->next()) {
+ Theme::get_default()->get_constant_list(E->key(), &constant_list);
+ for (List<StringName>::Element *F = constant_list.front(); F; F = F->next()) {
_TECategory::Item<int> it;
- it.name=F->get();
- it.item=Theme::get_default()->get_constant(F->get(),E->key());
+ it.name = F->get();
+ it.item = Theme::get_default()->get_constant(F->get(), E->key());
tc.constant_items.insert(it);
}
-
}
- FileAccess *file = FileAccess::open(filename,FileAccess::WRITE);
+ FileAccess *file = FileAccess::open(filename, FileAccess::WRITE);
if (!file) {
-
- ERR_EXPLAIN(TTR("Can't save theme to file:")+" "+filename);
+ ERR_EXPLAIN(TTR("Can't save theme to file:") + " " + filename);
return;
}
file->store_line("; ******************* ");
@@ -253,7 +242,7 @@ void ThemeEditor::_save_template_cbk(String fname) {
file->store_line("; ");
file->store_line("; ******************* ");
file->store_line("; ");
- file->store_line("; Template Generated Using: "+String(VERSION_MKSTRING));
+ file->store_line("; Template Generated Using: " + String(VERSION_MKSTRING));
file->store_line("; ");
file->store_line("; ");
file->store_line("");
@@ -266,59 +255,58 @@ void ThemeEditor::_save_template_cbk(String fname) {
file->store_line("");
//write default theme
- for(Map<String,_TECategory>::Element *E=categories.front();E;E=E->next() ) {
+ for (Map<String, _TECategory>::Element *E = categories.front(); E; E = E->next()) {
_TECategory &tc = E->get();
- String underline="; ";
- for(int i=0;i<E->key().length();i++)
- underline+="*";
+ String underline = "; ";
+ for (int i = 0; i < E->key().length(); i++)
+ underline += "*";
file->store_line("");
file->store_line(underline);
- file->store_line("; "+E->key());
+ file->store_line("; " + E->key());
file->store_line(underline);
if (tc.stylebox_items.size())
file->store_line("\n; StyleBox Items:\n");
- for (Set<_TECategory::RefItem<StyleBox> >::Element *F=tc.stylebox_items.front();F;F=F->next()) {
+ for (Set<_TECategory::RefItem<StyleBox> >::Element *F = tc.stylebox_items.front(); F; F = F->next()) {
- file->store_line(E->key()+"."+F->get().name+" = default");
+ file->store_line(E->key() + "." + F->get().name + " = default");
}
if (tc.font_items.size())
file->store_line("\n; Font Items:\n");
- for (Set<_TECategory::RefItem<Font> >::Element *F=tc.font_items.front();F;F=F->next()) {
+ for (Set<_TECategory::RefItem<Font> >::Element *F = tc.font_items.front(); F; F = F->next()) {
- file->store_line(E->key()+"."+F->get().name+" = default");
+ file->store_line(E->key() + "." + F->get().name + " = default");
}
if (tc.icon_items.size())
file->store_line("\n; Icon Items:\n");
- for (Set<_TECategory::RefItem<Texture> >::Element *F=tc.icon_items.front();F;F=F->next()) {
+ for (Set<_TECategory::RefItem<Texture> >::Element *F = tc.icon_items.front(); F; F = F->next()) {
- file->store_line(E->key()+"."+F->get().name+" = default");
+ file->store_line(E->key() + "." + F->get().name + " = default");
}
if (tc.color_items.size())
file->store_line("\n; Color Items:\n");
- for (Set<_TECategory::Item<Color> >::Element *F=tc.color_items.front();F;F=F->next()) {
+ for (Set<_TECategory::Item<Color> >::Element *F = tc.color_items.front(); F; F = F->next()) {
- file->store_line(E->key()+"."+F->get().name+" = default");
+ file->store_line(E->key() + "." + F->get().name + " = default");
}
if (tc.constant_items.size())
file->store_line("\n; Constant Items:\n");
- for (Set<_TECategory::Item<int> >::Element *F=tc.constant_items.front();F;F=F->next()) {
+ for (Set<_TECategory::Item<int> >::Element *F = tc.constant_items.front(); F; F = F->next()) {
- file->store_line(E->key()+"."+F->get().name+" = default");
+ file->store_line(E->key() + "." + F->get().name + " = default");
}
-
}
file->close();
@@ -327,16 +315,16 @@ void ThemeEditor::_save_template_cbk(String fname) {
void ThemeEditor::_dialog_cbk() {
- switch(popup_mode) {
+ switch (popup_mode) {
case POPUP_ADD: {
- switch(type_select->get_selected()) {
+ switch (type_select->get_selected()) {
- case 0: theme->set_icon(name_edit->get_text(),type_edit->get_text(),Ref<Texture>()); break;
- case 1: theme->set_stylebox(name_edit->get_text(),type_edit->get_text(),Ref<StyleBox>()); break;
- case 2: theme->set_font(name_edit->get_text(),type_edit->get_text(),Ref<Font>()); break;
- case 3: theme->set_color(name_edit->get_text(),type_edit->get_text(),Color()); break;
- case 4: theme->set_constant(name_edit->get_text(),type_edit->get_text(),0); break;
+ case 0: theme->set_icon(name_edit->get_text(), type_edit->get_text(), Ref<Texture>()); break;
+ case 1: theme->set_stylebox(name_edit->get_text(), type_edit->get_text(), Ref<StyleBox>()); break;
+ case 2: theme->set_font(name_edit->get_text(), type_edit->get_text(), Ref<Font>()); break;
+ case 3: theme->set_color(name_edit->get_text(), type_edit->get_text(), Color()); break;
+ case 4: theme->set_constant(name_edit->get_text(), type_edit->get_text(), 0); break;
}
} break;
@@ -347,58 +335,50 @@ void ThemeEditor::_dialog_cbk() {
{
names.clear();
- Theme::get_default()->get_icon_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->set_icon(E->get(),fromtype,Ref<Texture>());
-
+ Theme::get_default()->get_icon_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->set_icon(E->get(), fromtype, Ref<Texture>());
}
-
}
{
names.clear();
- Theme::get_default()->get_stylebox_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->set_stylebox(E->get(),fromtype,Ref<StyleBox>());
-
+ Theme::get_default()->get_stylebox_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->set_stylebox(E->get(), fromtype, Ref<StyleBox>());
}
-
}
{
names.clear();
- Theme::get_default()->get_font_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->set_font(E->get(),fromtype,Ref<Font>());
-
+ Theme::get_default()->get_font_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->set_font(E->get(), fromtype, Ref<Font>());
}
}
{
names.clear();
- Theme::get_default()->get_color_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->set_color(E->get(),fromtype,Theme::get_default()->get_color(E->get(),fromtype));
-
+ Theme::get_default()->get_color_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->set_color(E->get(), fromtype, Theme::get_default()->get_color(E->get(), fromtype));
}
}
{
names.clear();
- Theme::get_default()->get_constant_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->set_constant(E->get(),fromtype,Theme::get_default()->get_constant(E->get(),fromtype));
-
+ Theme::get_default()->get_constant_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->set_constant(E->get(), fromtype, Theme::get_default()->get_constant(E->get(), fromtype));
}
}
} break;
case POPUP_REMOVE: {
- switch(type_select->get_selected()) {
+ switch (type_select->get_selected()) {
- case 0: theme->clear_icon(name_edit->get_text(),type_edit->get_text()); break;
- case 1: theme->clear_stylebox(name_edit->get_text(),type_edit->get_text()); break;
- case 2: theme->clear_font(name_edit->get_text(),type_edit->get_text()); break;
- case 3: theme->clear_color(name_edit->get_text(),type_edit->get_text()); break;
- case 4: theme->clear_constant(name_edit->get_text(),type_edit->get_text()); break;
+ case 0: theme->clear_icon(name_edit->get_text(), type_edit->get_text()); break;
+ case 1: theme->clear_stylebox(name_edit->get_text(), type_edit->get_text()); break;
+ case 2: theme->clear_font(name_edit->get_text(), type_edit->get_text()); break;
+ case 3: theme->clear_color(name_edit->get_text(), type_edit->get_text()); break;
+ case 4: theme->clear_constant(name_edit->get_text(), type_edit->get_text()); break;
}
-
} break;
case POPUP_CLASS_REMOVE: {
StringName fromtype = type_edit->get_text();
@@ -406,121 +386,106 @@ void ThemeEditor::_dialog_cbk() {
{
names.clear();
- Theme::get_default()->get_icon_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->clear_icon(E->get(),fromtype);
-
+ Theme::get_default()->get_icon_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->clear_icon(E->get(), fromtype);
}
-
}
{
names.clear();
- Theme::get_default()->get_stylebox_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->clear_stylebox(E->get(),fromtype);
-
+ Theme::get_default()->get_stylebox_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->clear_stylebox(E->get(), fromtype);
}
-
}
{
names.clear();
- Theme::get_default()->get_font_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->clear_font(E->get(),fromtype);
-
+ Theme::get_default()->get_font_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->clear_font(E->get(), fromtype);
}
}
{
names.clear();
- Theme::get_default()->get_color_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->clear_color(E->get(),fromtype);
-
+ Theme::get_default()->get_color_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->clear_color(E->get(), fromtype);
}
}
{
names.clear();
- Theme::get_default()->get_constant_list(fromtype,&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
- theme->clear_constant(E->get(),fromtype);
-
+ Theme::get_default()->get_constant_list(fromtype, &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
+ theme->clear_constant(E->get(), fromtype);
}
}
- }break;
+ } break;
}
-
}
void ThemeEditor::_theme_menu_cbk(int p_option) {
-
- if (p_option==POPUP_CREATE_EMPTY || p_option==POPUP_CREATE_EDITOR_EMPTY) {
-
+ if (p_option == POPUP_CREATE_EMPTY || p_option == POPUP_CREATE_EDITOR_EMPTY) {
Ref<Theme> base_theme;
- if (p_option==POPUP_CREATE_EMPTY) {
+ if (p_option == POPUP_CREATE_EMPTY) {
base_theme = Theme::get_default();
} else {
base_theme = EditorNode::get_singleton()->get_theme_base()->get_theme();
}
-
{
List<StringName> types;
base_theme->get_type_list(&types);
-
- for (List<StringName>::Element *T=types.front();T;T=T->next()) {
+ for (List<StringName>::Element *T = types.front(); T; T = T->next()) {
StringName type = T->get();
List<StringName> icons;
- base_theme->get_icon_list(type,&icons);
+ base_theme->get_icon_list(type, &icons);
- for (List<StringName>::Element *E=icons.front();E;E=E->next()) {
- theme->set_icon(E->get(),type,Ref<Texture>());
+ for (List<StringName>::Element *E = icons.front(); E; E = E->next()) {
+ theme->set_icon(E->get(), type, Ref<Texture>());
}
List<StringName> shaders;
- base_theme->get_shader_list(type,&shaders);
+ base_theme->get_shader_list(type, &shaders);
- for (List<StringName>::Element *E=shaders.front();E;E=E->next()) {
- theme->set_shader(E->get(),type,Ref<Shader>());
+ for (List<StringName>::Element *E = shaders.front(); E; E = E->next()) {
+ theme->set_shader(E->get(), type, Ref<Shader>());
}
List<StringName> styleboxs;
- base_theme->get_stylebox_list(type,&styleboxs);
+ base_theme->get_stylebox_list(type, &styleboxs);
- for (List<StringName>::Element *E=styleboxs.front();E;E=E->next()) {
- theme->set_stylebox(E->get(),type,Ref<StyleBox>());
+ for (List<StringName>::Element *E = styleboxs.front(); E; E = E->next()) {
+ theme->set_stylebox(E->get(), type, Ref<StyleBox>());
}
List<StringName> fonts;
- base_theme->get_font_list(type,&fonts);
+ base_theme->get_font_list(type, &fonts);
- for (List<StringName>::Element *E=fonts.front();E;E=E->next()) {
- theme->set_font(E->get(),type,Ref<Font>());
+ for (List<StringName>::Element *E = fonts.front(); E; E = E->next()) {
+ theme->set_font(E->get(), type, Ref<Font>());
}
List<StringName> colors;
- base_theme->get_color_list(type,&colors);
+ base_theme->get_color_list(type, &colors);
- for (List<StringName>::Element *E=colors.front();E;E=E->next()) {
- theme->set_color(E->get(),type,Color());
+ for (List<StringName>::Element *E = colors.front(); E; E = E->next()) {
+ theme->set_color(E->get(), type, Color());
}
-
List<StringName> constants;
- base_theme->get_constant_list(type,&constants);
+ base_theme->get_constant_list(type, &constants);
- for (List<StringName>::Element *E=constants.front();E;E=E->next()) {
- theme->set_constant(E->get(),type,base_theme->get_constant(type,E->get()));
+ for (List<StringName>::Element *E = constants.front(); E; E = E->next()) {
+ theme->set_constant(E->get(), type, base_theme->get_constant(type, E->get()));
}
-
}
-
}
return;
}
@@ -533,22 +498,21 @@ void ThemeEditor::_theme_menu_cbk(int p_option) {
name_edit->show();
name_menu->show();
-
- if (p_option==POPUP_ADD) {//add
+ if (p_option == POPUP_ADD) { //add
add_del_dialog->set_title(TTR("Add Item"));
add_del_dialog->get_ok()->set_text(TTR("Add"));
- add_del_dialog->popup_centered(Size2(490,85)*EDSCALE);
+ add_del_dialog->popup_centered(Size2(490, 85) * EDSCALE);
- base_theme=Theme::get_default();
+ base_theme = Theme::get_default();
- } else if (p_option==POPUP_CLASS_ADD) {//add
+ } else if (p_option == POPUP_CLASS_ADD) { //add
add_del_dialog->set_title(TTR("Add All Items"));
add_del_dialog->get_ok()->set_text(TTR("Add All"));
- add_del_dialog->popup_centered(Size2(240,85)*EDSCALE);
+ add_del_dialog->popup_centered(Size2(240, 85) * EDSCALE);
- base_theme=Theme::get_default();
+ base_theme = Theme::get_default();
type_select->hide();
name_select_label->hide();
@@ -556,21 +520,21 @@ void ThemeEditor::_theme_menu_cbk(int p_option) {
name_edit->hide();
name_menu->hide();
- } else if (p_option==POPUP_REMOVE) {
+ } else if (p_option == POPUP_REMOVE) {
add_del_dialog->set_title(TTR("Remove Item"));
add_del_dialog->get_ok()->set_text(TTR("Remove"));
- add_del_dialog->popup_centered(Size2(490,85)*EDSCALE);
+ add_del_dialog->popup_centered(Size2(490, 85) * EDSCALE);
- base_theme=theme;
+ base_theme = theme;
- } else if (p_option==POPUP_CLASS_REMOVE) {
+ } else if (p_option == POPUP_CLASS_REMOVE) {
add_del_dialog->set_title("Remove All Items");
add_del_dialog->get_ok()->set_text("Remove All");
- add_del_dialog->popup_centered(Size2(240,85)*EDSCALE);
+ add_del_dialog->popup_centered(Size2(240, 85) * EDSCALE);
- base_theme=Theme::get_default();
+ base_theme = Theme::get_default();
type_select->hide();
name_select_label->hide();
@@ -578,28 +542,28 @@ void ThemeEditor::_theme_menu_cbk(int p_option) {
name_edit->hide();
name_menu->hide();
}
- popup_mode=p_option;
+ popup_mode = p_option;
- ERR_FAIL_COND( theme.is_null() );
+ ERR_FAIL_COND(theme.is_null());
List<StringName> types;
base_theme->get_type_list(&types);
type_menu->get_popup()->clear();
- if (p_option==0 || p_option==1) {//add
+ if (p_option == 0 || p_option == 1) { //add
List<StringName> new_types;
theme->get_type_list(&new_types);
//uh kind of sucks
- for(List<StringName>::Element *F=new_types.front();F;F=F->next()) {
+ for (List<StringName>::Element *F = new_types.front(); F; F = F->next()) {
- bool found=false;
- for(List<StringName>::Element *E=types.front();E;E=E->next()) {
+ bool found = false;
+ for (List<StringName>::Element *E = types.front(); E; E = E->next()) {
- if (E->get()==F->get()) {
- found=true;
+ if (E->get() == F->get()) {
+ found = true;
break;
}
}
@@ -611,20 +575,19 @@ void ThemeEditor::_theme_menu_cbk(int p_option) {
//types.sort();
types.sort_custom<StringName::AlphCompare>();
- for(List<StringName>::Element *E=types.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = types.front(); E; E = E->next()) {
- type_menu->get_popup()->add_item( E->get() );
+ type_menu->get_popup()->add_item(E->get());
}
-
}
void ThemeEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_PROCESS) {
+ if (p_what == NOTIFICATION_PROCESS) {
- time_left-=get_process_delta_time();
- if (time_left<0) {
- time_left=1.5;
+ time_left -= get_process_delta_time();
+ if (time_left < 0) {
+ time_left = 1.5;
_refresh_interval();
}
}
@@ -632,110 +595,101 @@ void ThemeEditor::_notification(int p_what) {
void ThemeEditor::_bind_methods() {
- ClassDB::bind_method("_type_menu_cbk",&ThemeEditor::_type_menu_cbk);
- ClassDB::bind_method("_name_menu_about_to_show",&ThemeEditor::_name_menu_about_to_show);
- ClassDB::bind_method("_name_menu_cbk",&ThemeEditor::_name_menu_cbk);
- ClassDB::bind_method("_theme_menu_cbk",&ThemeEditor::_theme_menu_cbk);
- ClassDB::bind_method("_dialog_cbk",&ThemeEditor::_dialog_cbk);
- ClassDB::bind_method("_save_template_cbk",&ThemeEditor::_save_template_cbk);
+ ClassDB::bind_method("_type_menu_cbk", &ThemeEditor::_type_menu_cbk);
+ ClassDB::bind_method("_name_menu_about_to_show", &ThemeEditor::_name_menu_about_to_show);
+ ClassDB::bind_method("_name_menu_cbk", &ThemeEditor::_name_menu_cbk);
+ ClassDB::bind_method("_theme_menu_cbk", &ThemeEditor::_theme_menu_cbk);
+ ClassDB::bind_method("_dialog_cbk", &ThemeEditor::_dialog_cbk);
+ ClassDB::bind_method("_save_template_cbk", &ThemeEditor::_save_template_cbk);
}
ThemeEditor::ThemeEditor() {
- time_left=0;
+ time_left = 0;
- scroll = memnew( ScrollContainer );
+ scroll = memnew(ScrollContainer);
add_child(scroll);
scroll->set_area_as_parent_rect(3);
- scroll->set_margin(MARGIN_TOP,30*EDSCALE);
+ scroll->set_margin(MARGIN_TOP, 30 * EDSCALE);
//scroll->set_enable_h_scroll(true);
scroll->set_enable_v_scroll(true);
scroll->set_enable_h_scroll(false);
- Panel * panel = memnew( Panel );
+ Panel *panel = memnew(Panel);
scroll->add_child(panel);
- panel->set_custom_minimum_size(Size2(500,800)*EDSCALE);
+ panel->set_custom_minimum_size(Size2(500, 800) * EDSCALE);
panel->set_theme(Theme::get_default());
panel->set_h_size_flags(SIZE_EXPAND_FILL);
- main_vb= memnew( VBoxContainer );
+ main_vb = memnew(VBoxContainer);
panel->add_child(main_vb);
- main_vb->set_area_as_parent_rect(4*EDSCALE);
-
+ main_vb->set_area_as_parent_rect(4 * EDSCALE);
HBoxContainer *hb_menu = memnew(HBoxContainer);
main_vb->add_child(hb_menu);
-
-
- theme_menu = memnew( MenuButton );
+ theme_menu = memnew(MenuButton);
theme_menu->set_text(TTR("Theme"));
- theme_menu->get_popup()->add_item(TTR("Add Item"),POPUP_ADD);
- theme_menu->get_popup()->add_item(TTR("Add Class Items"),POPUP_CLASS_ADD);
- theme_menu->get_popup()->add_item(TTR("Remove Item"),POPUP_REMOVE);
- theme_menu->get_popup()->add_item(TTR("Remove Class Items"),POPUP_CLASS_REMOVE);
+ theme_menu->get_popup()->add_item(TTR("Add Item"), POPUP_ADD);
+ theme_menu->get_popup()->add_item(TTR("Add Class Items"), POPUP_CLASS_ADD);
+ theme_menu->get_popup()->add_item(TTR("Remove Item"), POPUP_REMOVE);
+ theme_menu->get_popup()->add_item(TTR("Remove Class Items"), POPUP_CLASS_REMOVE);
theme_menu->get_popup()->add_separator();
- theme_menu->get_popup()->add_item(TTR("Create Empty Template"),POPUP_CREATE_EMPTY);
- theme_menu->get_popup()->add_item(TTR("Create Empty Editor Template"),POPUP_CREATE_EDITOR_EMPTY);
+ theme_menu->get_popup()->add_item(TTR("Create Empty Template"), POPUP_CREATE_EMPTY);
+ theme_menu->get_popup()->add_item(TTR("Create Empty Editor Template"), POPUP_CREATE_EDITOR_EMPTY);
add_child(theme_menu);
- theme_menu->set_pos(Vector2(3,3)*EDSCALE);
- theme_menu->get_popup()->connect("id_pressed", this,"_theme_menu_cbk");
+ theme_menu->set_pos(Vector2(3, 3) * EDSCALE);
+ theme_menu->get_popup()->connect("id_pressed", this, "_theme_menu_cbk");
-
- HBoxContainer *main_hb = memnew( HBoxContainer );
+ HBoxContainer *main_hb = memnew(HBoxContainer);
main_vb->add_child(main_hb);
-
-
- VBoxContainer *first_vb = memnew( VBoxContainer);
+ VBoxContainer *first_vb = memnew(VBoxContainer);
first_vb->set_h_size_flags(SIZE_EXPAND_FILL);
main_hb->add_child(first_vb);
-
-
//main_panel->add_child(panel);
//panel->set_area_as_parent_rect();
//panel->set_margin( MARGIN_TOP,20 );
- first_vb->add_child(memnew( Label("Label") ));
+ first_vb->add_child(memnew(Label("Label")));
- first_vb->add_child(memnew( Button("Button")) );
- ToolButton *tb = memnew( ToolButton );
+ first_vb->add_child(memnew(Button("Button")));
+ ToolButton *tb = memnew(ToolButton);
tb->set_text("ToolButton");
- first_vb->add_child(tb );
- CheckButton *cb = memnew( CheckButton );
+ first_vb->add_child(tb);
+ CheckButton *cb = memnew(CheckButton);
cb->set_text("CheckButton");
- first_vb->add_child(cb );
- CheckBox *cbx = memnew( CheckBox );
+ first_vb->add_child(cb);
+ CheckBox *cbx = memnew(CheckBox);
cbx->set_text("CheckBox");
- first_vb->add_child(cbx );
+ first_vb->add_child(cbx);
-
- VBoxContainer *bg = memnew( VBoxContainer );
+ VBoxContainer *bg = memnew(VBoxContainer);
bg->set_v_size_flags(SIZE_EXPAND_FILL);
- VBoxContainer *gbvb = memnew( VBoxContainer );
+ VBoxContainer *gbvb = memnew(VBoxContainer);
gbvb->set_v_size_flags(SIZE_EXPAND_FILL);
- CheckBox *rbx1 = memnew( CheckBox );
+ CheckBox *rbx1 = memnew(CheckBox);
rbx1->set_text(TTR("CheckBox Radio1"));
rbx1->set_pressed(true);
gbvb->add_child(rbx1);
- CheckBox *rbx2 = memnew( CheckBox );
+ CheckBox *rbx2 = memnew(CheckBox);
rbx2->set_text(TTR("CheckBox Radio2"));
gbvb->add_child(rbx2);
bg->add_child(gbvb);
first_vb->add_child(bg);
- MenuButton* test_menu_button = memnew( MenuButton );
+ MenuButton *test_menu_button = memnew(MenuButton);
test_menu_button->set_text("MenuButton");
test_menu_button->get_popup()->add_item(TTR("Item"));
test_menu_button->get_popup()->add_separator();
test_menu_button->get_popup()->add_check_item(TTR("Check Item"));
test_menu_button->get_popup()->add_check_item(TTR("Checked Item"));
- test_menu_button->get_popup()->set_item_checked(2,true);
+ test_menu_button->get_popup()->set_item_checked(2, true);
first_vb->add_child(test_menu_button);
- OptionButton *test_option_button = memnew( OptionButton );
+ OptionButton *test_option_button = memnew(OptionButton);
test_option_button->add_item("OptionButton");
test_option_button->add_separator();
test_option_button->add_item(TTR("Has"));
@@ -743,89 +697,85 @@ ThemeEditor::ThemeEditor() {
test_option_button->add_item(TTR("Options"));
first_vb->add_child(test_option_button);
- ColorPickerButton *cpb = memnew( ColorPickerButton );
- first_vb->add_child(cpb );
+ ColorPickerButton *cpb = memnew(ColorPickerButton);
+ first_vb->add_child(cpb);
- first_vb->add_child( memnew( HSeparator ));
- first_vb->add_child( memnew( HSlider ));
- first_vb->add_child( memnew( HScrollBar ));
- first_vb->add_child( memnew( SpinBox ));
- ProgressBar *pb=memnew( ProgressBar );
+ first_vb->add_child(memnew(HSeparator));
+ first_vb->add_child(memnew(HSlider));
+ first_vb->add_child(memnew(HScrollBar));
+ first_vb->add_child(memnew(SpinBox));
+ ProgressBar *pb = memnew(ProgressBar);
pb->set_value(50);
- first_vb->add_child( pb);
- Panel *pn=memnew( Panel );
- pn->set_custom_minimum_size(Size2(40,40)*EDSCALE);
- first_vb->add_child( pn);
- first_vb->add_constant_override("separation",10*EDSCALE);
+ first_vb->add_child(pb);
+ Panel *pn = memnew(Panel);
+ pn->set_custom_minimum_size(Size2(40, 40) * EDSCALE);
+ first_vb->add_child(pn);
+ first_vb->add_constant_override("separation", 10 * EDSCALE);
- VBoxContainer *second_vb = memnew( VBoxContainer );
+ VBoxContainer *second_vb = memnew(VBoxContainer);
second_vb->set_h_size_flags(SIZE_EXPAND_FILL);
main_hb->add_child(second_vb);
- second_vb->add_constant_override("separation",10*EDSCALE);
- LineEdit *le = memnew( LineEdit );
+ second_vb->add_constant_override("separation", 10 * EDSCALE);
+ LineEdit *le = memnew(LineEdit);
le->set_text("LineEdit");
second_vb->add_child(le);
- TextEdit *te = memnew( TextEdit );
+ TextEdit *te = memnew(TextEdit);
te->set_text("TextEdit");
//te->set_v_size_flags(SIZE_EXPAND_FILL);
- te->set_custom_minimum_size(Size2(0,160)*EDSCALE);
+ te->set_custom_minimum_size(Size2(0, 160) * EDSCALE);
second_vb->add_child(te);
Tree *test_tree = memnew(Tree);
second_vb->add_child(test_tree);
- test_tree->set_custom_minimum_size(Size2(0,160)*EDSCALE);
-
+ test_tree->set_custom_minimum_size(Size2(0, 160) * EDSCALE);
TreeItem *item = test_tree->create_item();
- item->set_editable(0,true);
- item->set_text(0,"Tree");
- item = test_tree->create_item( test_tree->get_root() );
+ item->set_editable(0, true);
+ item->set_text(0, "Tree");
+ item = test_tree->create_item(test_tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
- item->set_editable(0,true);
- item->set_text(0,"check");
- item = test_tree->create_item( test_tree->get_root() );
+ item->set_editable(0, true);
+ item->set_text(0, "check");
+ item = test_tree->create_item(test_tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
- item->set_editable(0,true);
- item->set_range_config(0,0,20,0.1);
- item->set_range(0,2);
- item = test_tree->create_item( test_tree->get_root() );
+ item->set_editable(0, true);
+ item->set_range_config(0, 0, 20, 0.1);
+ item->set_range(0, 2);
+ item = test_tree->create_item(test_tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
- item->set_editable(0,true);
- item->set_text(0,TTR("Have,Many,Several,Options!"));
- item->set_range(0,2);
+ item->set_editable(0, true);
+ item->set_text(0, TTR("Have,Many,Several,Options!"));
+ item->set_range(0, 2);
- VBoxContainer *third_vb = memnew( VBoxContainer );
+ VBoxContainer *third_vb = memnew(VBoxContainer);
third_vb->set_h_size_flags(SIZE_EXPAND_FILL);
- third_vb->add_constant_override("separation",10);
+ third_vb->add_constant_override("separation", 10);
main_hb->add_child(third_vb);
- HBoxContainer *vhb = memnew( HBoxContainer );
- vhb->set_custom_minimum_size(Size2(0,160)*EDSCALE);
+ HBoxContainer *vhb = memnew(HBoxContainer);
+ vhb->set_custom_minimum_size(Size2(0, 160) * EDSCALE);
vhb->add_child(memnew(VSeparator));
vhb->add_child(memnew(VSlider));
vhb->add_child(memnew(VScrollBar));
third_vb->add_child(vhb);
- TabContainer *tc = memnew( TabContainer );
+ TabContainer *tc = memnew(TabContainer);
third_vb->add_child(tc);
- tc->set_custom_minimum_size(Size2(0,160)*EDSCALE);
- Control *tcc = memnew( Control );
+ tc->set_custom_minimum_size(Size2(0, 160) * EDSCALE);
+ Control *tcc = memnew(Control);
tcc->set_name(TTR("Tab 1"));
tc->add_child(tcc);
- tcc = memnew( Control );
+ tcc = memnew(Control);
tcc->set_name(TTR("Tab 2"));
tc->add_child(tcc);
- tcc = memnew( Control );
+ tcc = memnew(Control);
tcc->set_name(TTR("Tab 3"));
tc->add_child(tcc);
- main_hb->add_constant_override("separation",20*EDSCALE);
-
-
+ main_hb->add_constant_override("separation", 20 * EDSCALE);
-
-/*
+ /*
test_h_scroll = memnew( HScrollBar );
test_h_scroll->set_pos( Point2( 25, 225 ) );
test_h_scroll->set_size( Point2( 150, 5 ) );
@@ -881,93 +831,88 @@ ThemeEditor::ThemeEditor() {
add_del_dialog->hide();
add_child(add_del_dialog);
-
- Label *l = memnew( Label );
- l->set_pos( Point2(5,5)*EDSCALE );
+ Label *l = memnew(Label);
+ l->set_pos(Point2(5, 5) * EDSCALE);
l->set_text(TTR("Type:"));
add_del_dialog->add_child(l);
- dtype_select_label=l;
-
+ dtype_select_label = l;
- type_edit = memnew( LineEdit );
- type_edit->set_pos(Point2(5,25)*EDSCALE);
- type_edit->set_size(Point2(150,5)*EDSCALE);
+ type_edit = memnew(LineEdit);
+ type_edit->set_pos(Point2(5, 25) * EDSCALE);
+ type_edit->set_size(Point2(150, 5) * EDSCALE);
add_del_dialog->add_child(type_edit);
- type_menu = memnew( MenuButton );
- type_menu->set_pos(Point2(160,25)*EDSCALE);
- type_menu->set_size(Point2(30,5)*EDSCALE);
+ type_menu = memnew(MenuButton);
+ type_menu->set_pos(Point2(160, 25) * EDSCALE);
+ type_menu->set_size(Point2(30, 5) * EDSCALE);
type_menu->set_text("..");
add_del_dialog->add_child(type_menu);
- type_menu->get_popup()->connect("id_pressed", this,"_type_menu_cbk");
+ type_menu->get_popup()->connect("id_pressed", this, "_type_menu_cbk");
- l = memnew( Label );
- l->set_pos( Point2(200,5)*EDSCALE );
+ l = memnew(Label);
+ l->set_pos(Point2(200, 5) * EDSCALE);
l->set_text(TTR("Name:"));
add_del_dialog->add_child(l);
- name_select_label=l;
+ name_select_label = l;
- name_edit = memnew( LineEdit );
- name_edit->set_pos(Point2(200,25)*EDSCALE);
- name_edit->set_size(Point2(150,5)*EDSCALE);
+ name_edit = memnew(LineEdit);
+ name_edit->set_pos(Point2(200, 25) * EDSCALE);
+ name_edit->set_size(Point2(150, 5) * EDSCALE);
add_del_dialog->add_child(name_edit);
- name_menu = memnew( MenuButton );
- name_menu->set_pos(Point2(360,25)*EDSCALE);
- name_menu->set_size(Point2(30,5)*EDSCALE);
+ name_menu = memnew(MenuButton);
+ name_menu->set_pos(Point2(360, 25) * EDSCALE);
+ name_menu->set_size(Point2(30, 5) * EDSCALE);
name_menu->set_text("..");
add_del_dialog->add_child(name_menu);
- name_menu->get_popup()->connect("about_to_show", this,"_name_menu_about_to_show");
- name_menu->get_popup()->connect("id_pressed", this,"_name_menu_cbk");
+ name_menu->get_popup()->connect("about_to_show", this, "_name_menu_about_to_show");
+ name_menu->get_popup()->connect("id_pressed", this, "_name_menu_cbk");
- type_select_label= memnew( Label );
- type_select_label->set_pos( Point2(400,5)*EDSCALE );
+ type_select_label = memnew(Label);
+ type_select_label->set_pos(Point2(400, 5) * EDSCALE);
type_select_label->set_text(TTR("Data Type:"));
add_del_dialog->add_child(type_select_label);
- type_select = memnew( OptionButton );
+ type_select = memnew(OptionButton);
type_select->add_item(TTR("Icon"));
type_select->add_item(TTR("Style"));
type_select->add_item(TTR("Font"));
type_select->add_item(TTR("Color"));
type_select->add_item(TTR("Constant"));
- type_select->set_pos( Point2( 400,25 )*EDSCALE );
- type_select->set_size( Point2( 80,5 )*EDSCALE );
-
+ type_select->set_pos(Point2(400, 25) * EDSCALE);
+ type_select->set_size(Point2(80, 5) * EDSCALE);
add_del_dialog->add_child(type_select);
- add_del_dialog->get_ok()->connect("pressed", this,"_dialog_cbk");
-
+ add_del_dialog->get_ok()->connect("pressed", this, "_dialog_cbk");
- file_dialog = memnew( EditorFileDialog );
+ file_dialog = memnew(EditorFileDialog);
file_dialog->add_filter("*.theme ; Theme File");
add_child(file_dialog);
- file_dialog->connect("file_selected",this,"_save_template_cbk");
+ file_dialog->connect("file_selected", this, "_save_template_cbk");
//MenuButton *name_menu;
//LineEdit *name_edit;
-
}
void ThemeEditorPlugin::edit(Object *p_node) {
if (p_node && p_node->cast_to<Theme>()) {
theme_editor->show();
- theme_editor->edit( p_node->cast_to<Theme>() );
+ theme_editor->edit(p_node->cast_to<Theme>());
} else {
- theme_editor->edit( Ref<Theme>() );
+ theme_editor->edit(Ref<Theme>());
theme_editor->hide();
}
}
-bool ThemeEditorPlugin::handles(Object *p_node) const{
+bool ThemeEditorPlugin::handles(Object *p_node) const {
return p_node->is_class("Theme");
}
-void ThemeEditorPlugin::make_visible(bool p_visible){
+void ThemeEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
theme_editor->set_process(true);
@@ -984,14 +929,11 @@ void ThemeEditorPlugin::make_visible(bool p_visible){
ThemeEditorPlugin::ThemeEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- theme_editor = memnew( ThemeEditor );
- theme_editor->set_custom_minimum_size(Size2(0,200));
+ editor = p_node;
+ theme_editor = memnew(ThemeEditor);
+ theme_editor->set_custom_minimum_size(Size2(0, 200));
//p_node->get_viewport()->add_child(theme_editor);
- button=editor->add_bottom_panel_item("Theme",theme_editor);
+ button = editor->add_bottom_panel_item("Theme", theme_editor);
button->hide();
-
-
}
-
diff --git a/editor/plugins/theme_editor_plugin.h b/editor/plugins/theme_editor_plugin.h
index f661da4cd5..3881cf1a41 100644
--- a/editor/plugins/theme_editor_plugin.h
+++ b/editor/plugins/theme_editor_plugin.h
@@ -29,23 +29,19 @@
#ifndef THEME_EDITOR_PLUGIN_H
#define THEME_EDITOR_PLUGIN_H
-#include "scene/resources/theme.h"
-#include "scene/gui/texture_rect.h"
-#include "scene/gui/option_button.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/check_box.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/check_box.h"
+#include "scene/gui/file_dialog.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/scroll_container.h"
+#include "scene/gui/texture_rect.h"
+#include "scene/resources/theme.h"
#include "editor/editor_node.h"
-
-
-
class ThemeEditor : public Control {
- GDCLASS( ThemeEditor, Control );
-
+ GDCLASS(ThemeEditor, Control);
ScrollContainer *scroll;
VBoxContainer *main_vb;
@@ -62,9 +58,9 @@ class ThemeEditor : public Control {
MenuButton *name_menu;
LineEdit *name_edit;
OptionButton *type_select;
- Label * type_select_label;
- Label * name_select_label;
- Label * dtype_select_label;
+ Label *type_select_label;
+ Label *name_select_label;
+ Label *dtype_select_label;
enum PopupMode {
POPUP_ADD,
@@ -88,29 +84,25 @@ class ThemeEditor : public Control {
void _propagate_redraw(Control *p_at);
void _refresh_interval();
-
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void edit(const Ref<Theme>& p_theme);
+public:
+ void edit(const Ref<Theme> &p_theme);
ThemeEditor();
};
-
-
class ThemeEditorPlugin : public EditorPlugin {
- GDCLASS( ThemeEditorPlugin, EditorPlugin );
+ GDCLASS(ThemeEditorPlugin, EditorPlugin);
ThemeEditor *theme_editor;
EditorNode *editor;
Button *button;
public:
-
virtual String get_name() const { return "Theme"; }
bool has_main_screen() const { return false; }
virtual void edit(Object *p_node);
@@ -118,8 +110,6 @@ public:
virtual void make_visible(bool p_visible);
ThemeEditorPlugin(EditorNode *p_node);
-
};
-
#endif // THEME_EDITOR_PLUGIN_H
diff --git a/editor/plugins/tile_map_editor_plugin.cpp b/editor/plugins/tile_map_editor_plugin.cpp
index fb6d5a786a..8cda9848bd 100644
--- a/editor/plugins/tile_map_editor_plugin.cpp
+++ b/editor/plugins/tile_map_editor_plugin.cpp
@@ -28,25 +28,25 @@
/*************************************************************************/
#include "tile_map_editor_plugin.h"
-#include "os/keyboard.h"
-#include "os/input.h"
#include "canvas_item_editor_plugin.h"
-#include "editor/editor_settings.h"
#include "editor/editor_scale.h"
+#include "editor/editor_settings.h"
+#include "os/input.h"
+#include "os/keyboard.h"
void TileMapEditor::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- transp->set_icon(get_icon("Transpose","EditorIcons"));
- mirror_x->set_icon(get_icon("MirrorX","EditorIcons"));
- mirror_y->set_icon(get_icon("MirrorY","EditorIcons"));
- rotate_0->set_icon(get_icon("Rotate0","EditorIcons"));
- rotate_90->set_icon(get_icon("Rotate90","EditorIcons"));
- rotate_180->set_icon(get_icon("Rotate180","EditorIcons"));
- rotate_270->set_icon(get_icon("Rotate270","EditorIcons"));
+ transp->set_icon(get_icon("Transpose", "EditorIcons"));
+ mirror_x->set_icon(get_icon("MirrorX", "EditorIcons"));
+ mirror_y->set_icon(get_icon("MirrorY", "EditorIcons"));
+ rotate_0->set_icon(get_icon("Rotate0", "EditorIcons"));
+ rotate_90->set_icon(get_icon("Rotate90", "EditorIcons"));
+ rotate_180->set_icon(get_icon("Rotate180", "EditorIcons"));
+ rotate_270->set_icon(get_icon("Rotate270", "EditorIcons"));
} break;
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
@@ -60,24 +60,24 @@ void TileMapEditor::_notification(int p_what) {
void TileMapEditor::_menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case OPTION_BUCKET: {
- tool=TOOL_BUCKET;
+ tool = TOOL_BUCKET;
canvas_item_editor->update();
} break;
case OPTION_PICK_TILE: {
- tool=TOOL_PICKING;
+ tool = TOOL_PICKING;
canvas_item_editor->update();
} break;
case OPTION_SELECT: {
- tool=TOOL_SELECTING;
- selection_active=false;
+ tool = TOOL_SELECTING;
+ selection_active = false;
canvas_item_editor->update();
} break;
@@ -86,7 +86,7 @@ void TileMapEditor::_menu_option(int p_option) {
_update_copydata();
if (selection_active) {
- tool=TOOL_DUPLICATING;
+ tool = TOOL_DUPLICATING;
canvas_item_editor->update();
}
@@ -97,15 +97,15 @@ void TileMapEditor::_menu_option(int p_option) {
return;
undo_redo->create_action("Erase Selection");
- for (int i=rectangle.pos.y;i<=rectangle.pos.y+rectangle.size.y;i++) {
- for (int j=rectangle.pos.x;j<=rectangle.pos.x+rectangle.size.x;j++) {
+ for (int i = rectangle.pos.y; i <= rectangle.pos.y + rectangle.size.y; i++) {
+ for (int j = rectangle.pos.x; j <= rectangle.pos.x + rectangle.size.x; j++) {
_set_cell(Point2i(j, i), TileMap::INVALID_CELL, false, false, false, true);
}
}
undo_redo->commit_action();
- selection_active=false;
+ selection_active = false;
copydata.clear();
canvas_item_editor->update();
@@ -113,15 +113,15 @@ void TileMapEditor::_menu_option(int p_option) {
}
}
-void TileMapEditor::_canvas_mouse_enter() {
+void TileMapEditor::_canvas_mouse_enter() {
- mouse_over=true;
+ mouse_over = true;
canvas_item_editor->update();
}
-void TileMapEditor::_canvas_mouse_exit() {
+void TileMapEditor::_canvas_mouse_exit() {
- mouse_over=false;
+ mouse_over = false;
canvas_item_editor->update();
}
@@ -129,7 +129,7 @@ int TileMapEditor::get_selected_tile() const {
int item = palette->get_current();
- if (item==-1)
+ if (item == -1)
return TileMap::INVALID_CELL;
return palette->get_item_metadata(item);
@@ -145,47 +145,45 @@ void TileMapEditor::set_selected_tile(int p_tile) {
}
}
-void TileMapEditor::_set_cell(const Point2i& p_pos,int p_value,bool p_flip_h, bool p_flip_v, bool p_transpose,bool p_with_undo) {
+void TileMapEditor::_set_cell(const Point2i &p_pos, int p_value, bool p_flip_h, bool p_flip_v, bool p_transpose, bool p_with_undo) {
ERR_FAIL_COND(!node);
- int prev_val=node->get_cell(p_pos.x,p_pos.y);
+ int prev_val = node->get_cell(p_pos.x, p_pos.y);
- bool prev_flip_h=node->is_cell_x_flipped(p_pos.x,p_pos.y);
- bool prev_flip_v=node->is_cell_y_flipped(p_pos.x,p_pos.y);
- bool prev_transpose=node->is_cell_transposed(p_pos.x,p_pos.y);
+ bool prev_flip_h = node->is_cell_x_flipped(p_pos.x, p_pos.y);
+ bool prev_flip_v = node->is_cell_y_flipped(p_pos.x, p_pos.y);
+ bool prev_transpose = node->is_cell_transposed(p_pos.x, p_pos.y);
- if (p_value==prev_val && p_flip_h==prev_flip_h && p_flip_v==prev_flip_v && p_transpose==prev_transpose)
+ if (p_value == prev_val && p_flip_h == prev_flip_h && p_flip_v == prev_flip_v && p_transpose == prev_transpose)
return; //check that it's actually different
if (p_with_undo) {
- undo_redo->add_do_method(node,"set_cellv",Point2(p_pos),p_value,p_flip_h,p_flip_v,p_transpose);
- undo_redo->add_undo_method(node,"set_cellv",Point2(p_pos),prev_val,prev_flip_h,prev_flip_v,prev_transpose);
+ undo_redo->add_do_method(node, "set_cellv", Point2(p_pos), p_value, p_flip_h, p_flip_v, p_transpose);
+ undo_redo->add_undo_method(node, "set_cellv", Point2(p_pos), prev_val, prev_flip_h, prev_flip_v, prev_transpose);
} else {
- node->set_cell(p_pos.x,p_pos.y,p_value,p_flip_h,p_flip_v,p_transpose);
+ node->set_cell(p_pos.x, p_pos.y, p_value, p_flip_h, p_flip_v, p_transpose);
}
-
}
-void TileMapEditor::_text_entered(const String& p_text) {
+void TileMapEditor::_text_entered(const String &p_text) {
canvas_item_editor->grab_focus();
}
-void TileMapEditor::_text_changed(const String& p_text) {
+void TileMapEditor::_text_changed(const String &p_text) {
_update_palette();
}
-void TileMapEditor::_sbox_input(const InputEvent& p_ie) {
+void TileMapEditor::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY && (
- p_ie.key.scancode == KEY_UP ||
- p_ie.key.scancode == KEY_DOWN ||
- p_ie.key.scancode == KEY_PAGEUP ||
- p_ie.key.scancode == KEY_PAGEDOWN ) ) {
+ if (p_ie.type == InputEvent::KEY && (p_ie.key.scancode == KEY_UP ||
+ p_ie.key.scancode == KEY_DOWN ||
+ p_ie.key.scancode == KEY_PAGEUP ||
+ p_ie.key.scancode == KEY_PAGEDOWN)) {
palette->call("_gui_input", p_ie);
search_box->accept_event();
@@ -200,7 +198,7 @@ void TileMapEditor::_update_palette() {
int selected = get_selected_tile();
palette->clear();
- Ref<TileSet> tileset=node->get_tileset();
+ Ref<TileSet> tileset = node->get_tileset();
if (tileset.is_null())
return;
@@ -212,25 +210,25 @@ void TileMapEditor::_update_palette() {
float min_size = EDITOR_DEF("editors/tile_map/preview_size", 64);
min_size *= EDSCALE;
- int hseparation = EDITOR_DEF("editors/tile_map/palette_item_hseparation",8);
+ int hseparation = EDITOR_DEF("editors/tile_map/palette_item_hseparation", 8);
bool show_tile_names = bool(EDITOR_DEF("editors/tile_map/show_tile_names", true));
- palette->add_constant_override("hseparation", hseparation*EDSCALE);
- palette->add_constant_override("vseparation", 8*EDSCALE);
+ palette->add_constant_override("hseparation", hseparation * EDSCALE);
+ palette->add_constant_override("vseparation", 8 * EDSCALE);
palette->set_fixed_icon_size(Size2(min_size, min_size));
palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1));
String filter = search_box->get_text().strip_edges();
- for (List<int>::Element *E=tiles.front();E;E=E->next()) {
+ for (List<int>::Element *E = tiles.front(); E; E = E->next()) {
String name;
- if (tileset->tile_get_name(E->get())!="") {
- name = itos(E->get())+" - "+tileset->tile_get_name(E->get());
+ if (tileset->tile_get_name(E->get()) != "") {
+ name = itos(E->get()) + " - " + tileset->tile_get_name(E->get());
} else {
- name = "#"+itos(E->get());
+ name = "#" + itos(E->get());
}
if (filter != "" && !filter.is_subsequence_ofi(name))
@@ -248,14 +246,14 @@ void TileMapEditor::_update_palette() {
Rect2 region = tileset->tile_get_region(E->get());
if (!region.has_no_area())
- palette->set_item_icon_region(palette->get_item_count()-1, region);
+ palette->set_item_icon_region(palette->get_item_count() - 1, region);
- palette->set_item_icon(palette->get_item_count()-1, tex);
+ palette->set_item_icon(palette->get_item_count() - 1, tex);
}
- palette->set_item_metadata(palette->get_item_count()-1, E->get());
+ palette->set_item_metadata(palette->get_item_count() - 1, E->get());
}
-
+
palette->set_same_column_width(true);
if (selected != -1)
@@ -264,11 +262,11 @@ void TileMapEditor::_update_palette() {
palette->select(0);
}
-void TileMapEditor::_pick_tile(const Point2& p_pos) {
+void TileMapEditor::_pick_tile(const Point2 &p_pos) {
int id = node->get_cell(p_pos.x, p_pos.y);
- if (id==TileMap::INVALID_CELL)
+ if (id == TileMap::INVALID_CELL)
return;
if (search_box->get_text().strip_edges() != "") {
@@ -287,7 +285,7 @@ void TileMapEditor::_pick_tile(const Point2& p_pos) {
canvas_item_editor->update();
}
-PoolVector<Vector2> TileMapEditor::_bucket_fill(const Point2i& p_start, bool erase, bool preview) {
+PoolVector<Vector2> TileMapEditor::_bucket_fill(const Point2i &p_start, bool erase, bool preview) {
int prev_id = node->get_cell(p_start.x, p_start.y);
int id = TileMap::INVALID_CELL;
@@ -299,34 +297,33 @@ PoolVector<Vector2> TileMapEditor::_bucket_fill(const Point2i& p_start, bool era
}
Rect2i r = node->get_item_rect();
- r.pos = r.pos/node->get_cell_size();
- r.size = r.size/node->get_cell_size();
+ r.pos = r.pos / node->get_cell_size();
+ r.size = r.size / node->get_cell_size();
int area = r.get_area();
- if(preview) {
+ if (preview) {
// Test if we can re-use the result from preview bucket fill
bool invalidate_cache = false;
// Area changed
- if(r != bucket_cache_rect)
+ if (r != bucket_cache_rect)
_clear_bucket_cache();
// Cache grid is not initialized
- if(bucket_cache_visited == 0) {
+ if (bucket_cache_visited == 0) {
bucket_cache_visited = new bool[area];
invalidate_cache = true;
}
// Tile ID changed or position wasn't visited by the previous fill
int loc = (p_start.x - r.get_pos().x) + (p_start.y - r.get_pos().y) * r.get_size().x;
- if(prev_id != bucket_cache_tile || !bucket_cache_visited[loc]) {
+ if (prev_id != bucket_cache_tile || !bucket_cache_visited[loc]) {
invalidate_cache = true;
}
- if(invalidate_cache) {
- for(int i = 0; i < area; ++i)
+ if (invalidate_cache) {
+ for (int i = 0; i < area; ++i)
bucket_cache_visited[i] = false;
bucket_cache = PoolVector<Vector2>();
bucket_cache_tile = prev_id;
bucket_cache_rect = r;
- }
- else {
+ } else {
return bucket_cache;
}
}
@@ -346,14 +343,13 @@ PoolVector<Vector2> TileMapEditor::_bucket_fill(const Point2i& p_start, bool era
if (node->get_cell(n.x, n.y) == prev_id) {
- if(preview) {
+ if (preview) {
int loc = (n.x - r.get_pos().x) + (n.y - r.get_pos().y) * r.get_size().x;
- if(bucket_cache_visited[loc])
+ if (bucket_cache_visited[loc])
continue;
bucket_cache_visited[loc] = true;
bucket_cache.push_back(n);
- }
- else {
+ } else {
node->set_cellv(n, id, flip_h, flip_v, transpose);
points.push_back(n);
}
@@ -368,7 +364,7 @@ PoolVector<Vector2> TileMapEditor::_bucket_fill(const Point2i& p_start, bool era
return preview ? bucket_cache : points;
}
-void TileMapEditor::_fill_points(const PoolVector<Vector2> p_points, const Dictionary& p_op) {
+void TileMapEditor::_fill_points(const PoolVector<Vector2> p_points, const Dictionary &p_op) {
int len = p_points.size();
PoolVector<Vector2>::Read pr = p_points.read();
@@ -378,7 +374,7 @@ void TileMapEditor::_fill_points(const PoolVector<Vector2> p_points, const Dicti
bool yf = p_op["flip_v"];
bool tr = p_op["transpose"];
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
_set_cell(pr[i], id, xf, yf, tr);
}
@@ -389,33 +385,33 @@ void TileMapEditor::_erase_points(const PoolVector<Vector2> p_points) {
int len = p_points.size();
PoolVector<Vector2>::Read pr = p_points.read();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
_set_cell(pr[i], TileMap::INVALID_CELL);
}
}
-void TileMapEditor::_select(const Point2i& p_from, const Point2i& p_to) {
+void TileMapEditor::_select(const Point2i &p_from, const Point2i &p_to) {
- Point2i begin=p_from;
- Point2i end=p_to;
+ Point2i begin = p_from;
+ Point2i end = p_to;
if (begin.x > end.x) {
- SWAP( begin.x, end.x);
+ SWAP(begin.x, end.x);
}
if (begin.y > end.y) {
- SWAP( begin.y, end.y);
+ SWAP(begin.y, end.y);
}
- rectangle.pos=begin;
- rectangle.size=end-begin;
+ rectangle.pos = begin;
+ rectangle.size = end - begin;
canvas_item_editor->update();
}
-void TileMapEditor::_draw_cell(int p_cell, const Point2i& p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D& p_xform) {
+void TileMapEditor::_draw_cell(int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D &p_xform) {
Ref<Texture> t = node->get_tileset()->tile_get_texture(p_cell);
@@ -448,75 +444,74 @@ void TileMapEditor::_draw_cell(int p_cell, const Point2i& p_point, bool p_flip_h
SWAP(tile_ofs.x, tile_ofs.y);
}
if (p_flip_h) {
- sc.x*=-1.0;
- tile_ofs.x*=-1.0;
+ sc.x *= -1.0;
+ tile_ofs.x *= -1.0;
}
if (p_flip_v) {
- sc.y*=-1.0;
- tile_ofs.y*=-1.0;
+ sc.y *= -1.0;
+ tile_ofs.y *= -1.0;
}
- if (node->get_tile_origin()==TileMap::TILE_ORIGIN_TOP_LEFT) {
+ if (node->get_tile_origin() == TileMap::TILE_ORIGIN_TOP_LEFT) {
- rect.pos+=tile_ofs;
- } else if (node->get_tile_origin()==TileMap::TILE_ORIGIN_BOTTOM_LEFT) {
+ rect.pos += tile_ofs;
+ } else if (node->get_tile_origin() == TileMap::TILE_ORIGIN_BOTTOM_LEFT) {
Size2 cell_size = node->get_cell_size();
-
- rect.pos+=tile_ofs;
-
- if(p_transpose)
- {
- if(p_flip_h)
- rect.pos.x-=cell_size.x;
+
+ rect.pos += tile_ofs;
+
+ if (p_transpose) {
+ if (p_flip_h)
+ rect.pos.x -= cell_size.x;
else
- rect.pos.x+=cell_size.x;
+ rect.pos.x += cell_size.x;
} else {
- if(p_flip_v)
- rect.pos.y-=cell_size.y;
+ if (p_flip_v)
+ rect.pos.y -= cell_size.y;
else
- rect.pos.y+=cell_size.y;
+ rect.pos.y += cell_size.y;
}
- } else if (node->get_tile_origin()==TileMap::TILE_ORIGIN_CENTER) {
- rect.pos+=node->get_cell_size()/2;
+ } else if (node->get_tile_origin() == TileMap::TILE_ORIGIN_CENTER) {
+ rect.pos += node->get_cell_size() / 2;
Vector2 s = r.size;
- Vector2 center = (s/2) - tile_ofs;
+ Vector2 center = (s / 2) - tile_ofs;
if (p_flip_h)
- rect.pos.x-=s.x-center.x;
+ rect.pos.x -= s.x - center.x;
else
- rect.pos.x-=center.x;
+ rect.pos.x -= center.x;
if (p_flip_v)
- rect.pos.y-=s.y-center.y;
+ rect.pos.y -= s.y - center.y;
else
- rect.pos.y-=center.y;
+ rect.pos.y -= center.y;
}
- rect.pos=p_xform.xform(rect.pos);
- rect.size*=sc;
+ rect.pos = p_xform.xform(rect.pos);
+ rect.size *= sc;
if (r.has_no_area())
- canvas_item_editor->draw_texture_rect(t, rect, false, Color(1,1,1,0.5), p_transpose);
+ canvas_item_editor->draw_texture_rect(t, rect, false, Color(1, 1, 1, 0.5), p_transpose);
else
- canvas_item_editor->draw_texture_rect_region(t, rect, r, Color(1,1,1,0.5), p_transpose);
+ canvas_item_editor->draw_texture_rect_region(t, rect, r, Color(1, 1, 1, 0.5), p_transpose);
}
-void TileMapEditor::_draw_fill_preview(int p_cell, const Point2i& p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D& p_xform) {
+void TileMapEditor::_draw_fill_preview(int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D &p_xform) {
PoolVector<Vector2> points = _bucket_fill(p_point, false, true);
PoolVector<Vector2>::Read pr = points.read();
int len = points.size();
int time_after = OS::get_singleton()->get_ticks_msec();
- for(int i = 0; i < len; ++i) {
+ for (int i = 0; i < len; ++i) {
_draw_cell(p_cell, pr[i], p_flip_h, p_flip_v, p_transpose, p_xform);
}
}
void TileMapEditor::_clear_bucket_cache() {
- if(bucket_cache_visited) {
+ if (bucket_cache_visited) {
delete[] bucket_cache_visited;
bucket_cache_visited = 0;
}
@@ -529,19 +524,19 @@ void TileMapEditor::_update_copydata() {
if (!selection_active)
return;
- for (int i=rectangle.pos.y;i<=rectangle.pos.y+rectangle.size.y;i++) {
+ for (int i = rectangle.pos.y; i <= rectangle.pos.y + rectangle.size.y; i++) {
- for (int j=rectangle.pos.x;j<=rectangle.pos.x+rectangle.size.x;j++) {
+ for (int j = rectangle.pos.x; j <= rectangle.pos.x + rectangle.size.x; j++) {
TileData tcd;
- tcd.cell=node->get_cell(j, i);
+ tcd.cell = node->get_cell(j, i);
- if (tcd.cell!=TileMap::INVALID_CELL) {
- tcd.pos=Point2i(j, i);
- tcd.flip_h=node->is_cell_x_flipped(j,i);
- tcd.flip_v=node->is_cell_y_flipped(j,i);
- tcd.transpose=node->is_cell_transposed(j,i);
+ if (tcd.cell != TileMap::INVALID_CELL) {
+ tcd.pos = Point2i(j, i);
+ tcd.flip_h = node->is_cell_x_flipped(j, i);
+ tcd.flip_v = node->is_cell_y_flipped(j, i);
+ tcd.transpose = node->is_cell_transposed(j, i);
}
copydata.push_back(tcd);
@@ -563,7 +558,7 @@ static inline Vector<Point2i> line(int x0, int x1, int y0, int y1) {
int sy = y0 > y1 ? -1 : 1;
if (dx > dy) {
- float err = dx/2;
+ float err = dx / 2;
for (; x != x1; x += sx) {
points.push_back(Vector2(x, y));
@@ -575,7 +570,7 @@ static inline Vector<Point2i> line(int x0, int x1, int y0, int y1) {
}
}
} else {
- float err = dy/2;
+ float err = dy / 2;
for (; y != y1; y += sy) {
points.push_back(Vector2(x, y));
@@ -593,7 +588,7 @@ static inline Vector<Point2i> line(int x0, int x1, int y0, int y1) {
return points;
}
-bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
+bool TileMapEditor::forward_gui_input(const InputEvent &p_event) {
if (!node || !node->get_tileset().is_valid() || !node->is_visible_in_tree())
return false;
@@ -601,98 +596,98 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
Transform2D xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform();
Transform2D xform_inv = xform.affine_inverse();
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
if (Input::get_singleton()->is_key_pressed(KEY_SPACE))
return false; //drag
- if (tool==TOOL_NONE) {
+ if (tool == TOOL_NONE) {
if (mb.mod.shift) {
if (mb.mod.control)
- tool=TOOL_RECTANGLE_PAINT;
+ tool = TOOL_RECTANGLE_PAINT;
else
- tool=TOOL_LINE_PAINT;
+ tool = TOOL_LINE_PAINT;
- selection_active=false;
- rectangle_begin=over_tile;
+ selection_active = false;
+ rectangle_begin = over_tile;
return true;
}
if (mb.mod.control) {
- tool=TOOL_PICKING;
+ tool = TOOL_PICKING;
_pick_tile(over_tile);
return true;
}
- tool=TOOL_PAINTING;
+ tool = TOOL_PAINTING;
}
- if (tool==TOOL_PAINTING) {
+ if (tool == TOOL_PAINTING) {
int id = get_selected_tile();
- if (id!=TileMap::INVALID_CELL) {
+ if (id != TileMap::INVALID_CELL) {
- tool=TOOL_PAINTING;
+ tool = TOOL_PAINTING;
paint_undo.clear();
- paint_undo[over_tile]=_get_op_from_cell(over_tile);
+ paint_undo[over_tile] = _get_op_from_cell(over_tile);
_set_cell(over_tile, id, flip_h, flip_v, transpose);
}
- } else if (tool==TOOL_PICKING) {
+ } else if (tool == TOOL_PICKING) {
_pick_tile(over_tile);
- } else if (tool==TOOL_SELECTING) {
+ } else if (tool == TOOL_SELECTING) {
- selection_active=true;
- rectangle_begin=over_tile;
+ selection_active = true;
+ rectangle_begin = over_tile;
}
return true;
} else {
- if (tool!=TOOL_NONE) {
+ if (tool != TOOL_NONE) {
- if (tool==TOOL_PAINTING) {
+ if (tool == TOOL_PAINTING) {
- int id=get_selected_tile();
+ int id = get_selected_tile();
- if (id!=TileMap::INVALID_CELL && paint_undo.size()) {
+ if (id != TileMap::INVALID_CELL && paint_undo.size()) {
undo_redo->create_action(TTR("Paint TileMap"));
- for (Map<Point2i,CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
- Point2 p=E->key();
- undo_redo->add_do_method(node,"set_cellv",p,id,flip_h,flip_v,transpose);
- undo_redo->add_undo_method(node,"set_cellv",p,E->get().idx,E->get().xf,E->get().yf,E->get().tr);
+ Point2 p = E->key();
+ undo_redo->add_do_method(node, "set_cellv", p, id, flip_h, flip_v, transpose);
+ undo_redo->add_undo_method(node, "set_cellv", p, E->get().idx, E->get().xf, E->get().yf, E->get().tr);
}
undo_redo->commit_action();
paint_undo.clear();
}
- } else if (tool==TOOL_LINE_PAINT) {
+ } else if (tool == TOOL_LINE_PAINT) {
- int id=get_selected_tile();
+ int id = get_selected_tile();
- if (id!=TileMap::INVALID_CELL) {
+ if (id != TileMap::INVALID_CELL) {
undo_redo->create_action("Line Draw");
- for (Map<Point2i,CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
_set_cell(E->key(), id, flip_h, flip_v, transpose, true);
}
@@ -702,15 +697,15 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
canvas_item_editor->update();
}
- } else if (tool==TOOL_RECTANGLE_PAINT) {
+ } else if (tool == TOOL_RECTANGLE_PAINT) {
- int id=get_selected_tile();
+ int id = get_selected_tile();
- if (id!=TileMap::INVALID_CELL) {
+ if (id != TileMap::INVALID_CELL) {
undo_redo->create_action("Rectangle Paint");
- for (int i=rectangle.pos.y;i<=rectangle.pos.y+rectangle.size.y;i++) {
- for (int j=rectangle.pos.x;j<=rectangle.pos.x+rectangle.size.x;j++) {
+ for (int i = rectangle.pos.y; i <= rectangle.pos.y + rectangle.size.y; i++) {
+ for (int j = rectangle.pos.x; j <= rectangle.pos.x + rectangle.size.x; j++) {
_set_cell(Point2i(j, i), id, flip_h, flip_v, transpose, true);
}
@@ -719,14 +714,14 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
canvas_item_editor->update();
}
- } else if (tool==TOOL_DUPLICATING) {
+ } else if (tool == TOOL_DUPLICATING) {
- Point2 ofs = over_tile-rectangle.pos;
+ Point2 ofs = over_tile - rectangle.pos;
undo_redo->create_action(TTR("Duplicate"));
- for (List<TileData>::Element *E=copydata.front();E;E=E->next()) {
+ for (List<TileData>::Element *E = copydata.front(); E; E = E->next()) {
- _set_cell(E->get().pos+ofs,E->get().cell,E->get().flip_h,E->get().flip_v,E->get().transpose,true);
+ _set_cell(E->get().pos + ofs, E->get().cell, E->get().flip_h, E->get().flip_v, E->get().transpose, true);
}
undo_redo->commit_action();
@@ -734,11 +729,11 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
canvas_item_editor->update();
- } else if (tool==TOOL_SELECTING) {
+ } else if (tool == TOOL_SELECTING) {
canvas_item_editor->update();
- } else if (tool==TOOL_BUCKET) {
+ } else if (tool == TOOL_BUCKET) {
Dictionary pop;
pop["id"] = node->get_cell(over_tile.x, over_tile.y);
@@ -765,28 +760,28 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
undo_redo->commit_action();
}
- tool=TOOL_NONE;
+ tool = TOOL_NONE;
return true;
}
}
- } else if (mb.button_index==BUTTON_RIGHT) {
+ } else if (mb.button_index == BUTTON_RIGHT) {
if (mb.pressed) {
- if (tool==TOOL_SELECTING || selection_active) {
+ if (tool == TOOL_SELECTING || selection_active) {
- tool=TOOL_NONE;
- selection_active=false;
+ tool = TOOL_NONE;
+ selection_active = false;
canvas_item_editor->update();
return true;
}
- if (tool==TOOL_DUPLICATING) {
+ if (tool == TOOL_DUPLICATING) {
- tool=TOOL_NONE;
+ tool = TOOL_NONE;
copydata.clear();
canvas_item_editor->update();
@@ -794,7 +789,7 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
- if (tool==TOOL_NONE) {
+ if (tool == TOOL_NONE) {
paint_undo.clear();
@@ -803,17 +798,17 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
if (mb.mod.shift) {
if (mb.mod.control)
- tool=TOOL_RECTANGLE_ERASE;
+ tool = TOOL_RECTANGLE_ERASE;
else
- tool=TOOL_LINE_ERASE;
+ tool = TOOL_LINE_ERASE;
- selection_active=false;
- rectangle_begin=local;
+ selection_active = false;
+ rectangle_begin = local;
} else {
- tool=TOOL_ERASING;
+ tool = TOOL_ERASING;
- paint_undo[local]=_get_op_from_cell(local);
+ paint_undo[local] = _get_op_from_cell(local);
_set_cell(local, TileMap::INVALID_CELL);
}
@@ -821,30 +816,30 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
}
} else {
- if (tool==TOOL_ERASING || tool==TOOL_RECTANGLE_ERASE || tool==TOOL_LINE_ERASE) {
+ if (tool == TOOL_ERASING || tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) {
if (paint_undo.size()) {
undo_redo->create_action(TTR("Erase TileMap"));
- for (Map<Point2i,CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
- Point2 p=E->key();
- undo_redo->add_do_method(node,"set_cellv",p,TileMap::INVALID_CELL,false,false,false);
- undo_redo->add_undo_method(node,"set_cellv",p,E->get().idx,E->get().xf,E->get().yf,E->get().tr);
+ Point2 p = E->key();
+ undo_redo->add_do_method(node, "set_cellv", p, TileMap::INVALID_CELL, false, false, false);
+ undo_redo->add_undo_method(node, "set_cellv", p, E->get().idx, E->get().xf, E->get().yf, E->get().tr);
}
undo_redo->commit_action();
paint_undo.clear();
}
- if (tool==TOOL_RECTANGLE_ERASE || tool==TOOL_LINE_ERASE) {
+ if (tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) {
canvas_item_editor->update();
}
- tool=TOOL_NONE;
+ tool = TOOL_NONE;
return true;
- } else if (tool==TOOL_BUCKET) {
+ } else if (tool == TOOL_BUCKET) {
Dictionary pop;
pop["id"] = node->get_cell(over_tile.x, over_tile.y);
@@ -869,13 +864,13 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- Point2i new_over_tile = node->world_to_map(xform_inv.xform(Point2(mm.x,mm.y)));
+ Point2i new_over_tile = node->world_to_map(xform_inv.xform(Point2(mm.x, mm.y)));
- if (new_over_tile!=over_tile) {
+ if (new_over_tile != over_tile) {
- over_tile=new_over_tile;
+ over_tile = new_over_tile;
canvas_item_editor->update();
}
@@ -884,15 +879,15 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
if (node->get_tileset()->has_tile(tile_under))
tile_name = node->get_tileset()->tile_get_name(tile_under);
- tile_info->set_text(String::num(over_tile.x)+", "+String::num(over_tile.y)+" ["+tile_name+"]");
+ tile_info->set_text(String::num(over_tile.x) + ", " + String::num(over_tile.y) + " [" + tile_name + "]");
- if (tool==TOOL_PAINTING) {
+ if (tool == TOOL_PAINTING) {
int id = get_selected_tile();
- if (id!=TileMap::INVALID_CELL) {
+ if (id != TileMap::INVALID_CELL) {
if (!paint_undo.has(over_tile)) {
- paint_undo[over_tile]=_get_op_from_cell(over_tile);
+ paint_undo[over_tile] = _get_op_from_cell(over_tile);
}
_set_cell(over_tile, id, flip_h, flip_v, transpose);
@@ -901,21 +896,21 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
}
}
- if (tool==TOOL_SELECTING) {
+ if (tool == TOOL_SELECTING) {
_select(rectangle_begin, over_tile);
return true;
}
- if (tool==TOOL_LINE_PAINT || tool==TOOL_LINE_ERASE) {
+ if (tool == TOOL_LINE_PAINT || tool == TOOL_LINE_ERASE) {
int id = get_selected_tile();
- bool erasing = (tool==TOOL_LINE_ERASE);
+ bool erasing = (tool == TOOL_LINE_ERASE);
if (erasing && paint_undo.size()) {
- for (Map<Point2i, CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
_set_cell(E->key(), E->get().idx, E->get().xf, E->get().yf, E->get().tr);
}
@@ -923,13 +918,13 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
paint_undo.clear();
- if (id!=TileMap::INVALID_CELL) {
+ if (id != TileMap::INVALID_CELL) {
Vector<Point2i> points = line(rectangle_begin.x, over_tile.x, rectangle_begin.y, over_tile.y);
- for (int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
- paint_undo[points[i]]=_get_op_from_cell(points[i]);
+ paint_undo[points[i]] = _get_op_from_cell(points[i]);
if (erasing)
_set_cell(points[i], TileMap::INVALID_CELL);
@@ -940,15 +935,15 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
- if (tool==TOOL_RECTANGLE_PAINT || tool==TOOL_RECTANGLE_ERASE) {
+ if (tool == TOOL_RECTANGLE_PAINT || tool == TOOL_RECTANGLE_ERASE) {
_select(rectangle_begin, over_tile);
- if (tool==TOOL_RECTANGLE_ERASE) {
+ if (tool == TOOL_RECTANGLE_ERASE) {
if (paint_undo.size()) {
- for (Map<Point2i, CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
_set_cell(E->key(), E->get().idx, E->get().xf, E->get().yf, E->get().tr);
}
@@ -956,11 +951,11 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
paint_undo.clear();
- for (int i=rectangle.pos.y;i<=rectangle.pos.y+rectangle.size.y;i++) {
- for (int j=rectangle.pos.x;j<=rectangle.pos.x+rectangle.size.x;j++) {
+ for (int i = rectangle.pos.y; i <= rectangle.pos.y + rectangle.size.y; i++) {
+ for (int j = rectangle.pos.x; j <= rectangle.pos.x + rectangle.size.x; j++) {
Point2i tile = Point2i(j, i);
- paint_undo[tile]=_get_op_from_cell(tile);
+ paint_undo[tile] = _get_op_from_cell(tile);
_set_cell(tile, TileMap::INVALID_CELL);
}
@@ -969,17 +964,17 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
- if (tool==TOOL_ERASING) {
+ if (tool == TOOL_ERASING) {
if (!paint_undo.has(over_tile)) {
- paint_undo[over_tile]=_get_op_from_cell(over_tile);
+ paint_undo[over_tile] = _get_op_from_cell(over_tile);
}
_set_cell(over_tile, TileMap::INVALID_CELL);
return true;
}
- if (tool==TOOL_PICKING && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
+ if (tool == TOOL_PICKING && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
_pick_tile(over_tile);
@@ -993,21 +988,21 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
if (!k.pressed)
break;
- if (k.scancode==KEY_ESCAPE) {
+ if (k.scancode == KEY_ESCAPE) {
- if (tool==TOOL_DUPLICATING)
+ if (tool == TOOL_DUPLICATING)
copydata.clear();
- else if (tool==TOOL_SELECTING || selection_active)
- selection_active=false;
+ else if (tool == TOOL_SELECTING || selection_active)
+ selection_active = false;
- tool=TOOL_NONE;
+ tool = TOOL_NONE;
canvas_item_editor->update();
return true;
}
- if (tool!=TOOL_NONE || !mouse_over)
+ if (tool != TOOL_NONE || !mouse_over)
return false;
if (ED_IS_SHORTCUT("tile_map_editor/erase_selection", p_event)) {
@@ -1016,8 +1011,8 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
if (ED_IS_SHORTCUT("tile_map_editor/select", p_event)) {
- tool=TOOL_SELECTING;
- selection_active=false;
+ tool = TOOL_SELECTING;
+ selection_active = false;
canvas_item_editor->update();
@@ -1027,7 +1022,7 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
_update_copydata();
if (selection_active) {
- tool=TOOL_DUPLICATING;
+ tool = TOOL_DUPLICATING;
canvas_item_editor->update();
@@ -1041,13 +1036,13 @@ bool TileMapEditor::forward_gui_input(const InputEvent& p_event) {
return true;
}
if (ED_IS_SHORTCUT("tile_map_editor/mirror_x", p_event)) {
- flip_h=!flip_h;
+ flip_h = !flip_h;
mirror_x->set_pressed(flip_h);
canvas_item_editor->update();
return true;
}
if (ED_IS_SHORTCUT("tile_map_editor/mirror_y", p_event)) {
- flip_v=!flip_v;
+ flip_v = !flip_v;
mirror_y->set_pressed(flip_v);
canvas_item_editor->update();
return true;
@@ -1074,92 +1069,86 @@ void TileMapEditor::_canvas_draw() {
Transform2D xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform();
Transform2D xform_inv = xform.affine_inverse();
-
- Size2 screen_size=canvas_item_editor->get_size();
+ Size2 screen_size = canvas_item_editor->get_size();
{
Rect2 aabb;
- aabb.pos=node->world_to_map(xform_inv.xform(Vector2()));
- aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(0,screen_size.height))));
- aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(screen_size.width,0))));
+ aabb.pos = node->world_to_map(xform_inv.xform(Vector2()));
+ aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(0, screen_size.height))));
+ aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(screen_size.width, 0))));
aabb.expand_to(node->world_to_map(xform_inv.xform(screen_size)));
- Rect2i si=aabb.grow(1.0);
+ Rect2i si = aabb.grow(1.0);
- if (node->get_half_offset()!=TileMap::HALF_OFFSET_X) {
+ if (node->get_half_offset() != TileMap::HALF_OFFSET_X) {
- int max_lines=2000; //avoid crash if size too smal
+ int max_lines = 2000; //avoid crash if size too smal
- for (int i=(si.pos.x)-1;i<=(si.pos.x+si.size.x);i++) {
+ for (int i = (si.pos.x) - 1; i <= (si.pos.x + si.size.x); i++) {
- Vector2 from = xform.xform(node->map_to_world(Vector2(i,si.pos.y)));
- Vector2 to = xform.xform(node->map_to_world(Vector2(i,si.pos.y+si.size.y+1)));
+ Vector2 from = xform.xform(node->map_to_world(Vector2(i, si.pos.y)));
+ Vector2 to = xform.xform(node->map_to_world(Vector2(i, si.pos.y + si.size.y + 1)));
- Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
- canvas_item_editor->draw_line(from,to,col,1);
- if (max_lines--==0)
+ Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2);
+ canvas_item_editor->draw_line(from, to, col, 1);
+ if (max_lines-- == 0)
break;
}
} else {
- int max_lines=10000; //avoid crash if size too smal
+ int max_lines = 10000; //avoid crash if size too smal
- for (int i=(si.pos.x)-1;i<=(si.pos.x+si.size.x);i++) {
+ for (int i = (si.pos.x) - 1; i <= (si.pos.x + si.size.x); i++) {
- for (int j=(si.pos.y)-1;j<=(si.pos.y+si.size.y);j++) {
+ for (int j = (si.pos.y) - 1; j <= (si.pos.y + si.size.y); j++) {
Vector2 ofs;
- if (ABS(j)&1) {
- ofs=cell_xf[0]*0.5;
+ if (ABS(j) & 1) {
+ ofs = cell_xf[0] * 0.5;
}
- Vector2 from = xform.xform(node->map_to_world(Vector2(i,j),true)+ofs);
- Vector2 to = xform.xform(node->map_to_world(Vector2(i,j+1),true)+ofs);
- Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
- canvas_item_editor->draw_line(from,to,col,1);
+ Vector2 from = xform.xform(node->map_to_world(Vector2(i, j), true) + ofs);
+ Vector2 to = xform.xform(node->map_to_world(Vector2(i, j + 1), true) + ofs);
+ Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2);
+ canvas_item_editor->draw_line(from, to, col, 1);
- if (max_lines--==0)
+ if (max_lines-- == 0)
break;
-
}
-
}
}
- int max_lines=10000; //avoid crash if size too smal
+ int max_lines = 10000; //avoid crash if size too smal
- if (node->get_half_offset()!=TileMap::HALF_OFFSET_Y) {
+ if (node->get_half_offset() != TileMap::HALF_OFFSET_Y) {
- for (int i=(si.pos.y)-1;i<=(si.pos.y+si.size.y);i++) {
+ for (int i = (si.pos.y) - 1; i <= (si.pos.y + si.size.y); i++) {
- Vector2 from = xform.xform(node->map_to_world(Vector2(si.pos.x,i)));
- Vector2 to = xform.xform(node->map_to_world(Vector2(si.pos.x+si.size.x+1,i)));
+ Vector2 from = xform.xform(node->map_to_world(Vector2(si.pos.x, i)));
+ Vector2 to = xform.xform(node->map_to_world(Vector2(si.pos.x + si.size.x + 1, i)));
- Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
- canvas_item_editor->draw_line(from,to,col,1);
+ Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2);
+ canvas_item_editor->draw_line(from, to, col, 1);
- if (max_lines--==0)
+ if (max_lines-- == 0)
break;
-
}
} else {
+ for (int i = (si.pos.y) - 1; i <= (si.pos.y + si.size.y); i++) {
- for (int i=(si.pos.y)-1;i<=(si.pos.y+si.size.y);i++) {
-
- for (int j=(si.pos.x)-1;j<=(si.pos.x+si.size.x);j++) {
+ for (int j = (si.pos.x) - 1; j <= (si.pos.x + si.size.x); j++) {
Vector2 ofs;
- if (ABS(j)&1) {
- ofs=cell_xf[1]*0.5;
+ if (ABS(j) & 1) {
+ ofs = cell_xf[1] * 0.5;
}
- Vector2 from = xform.xform(node->map_to_world(Vector2(j,i),true)+ofs);
- Vector2 to = xform.xform(node->map_to_world(Vector2(j+1,i),true)+ofs);
- Color col=i==0?Color(1,0.8,0.2,0.5):Color(1,0.3,0.1,0.2);
- canvas_item_editor->draw_line(from,to,col,1);
+ Vector2 from = xform.xform(node->map_to_world(Vector2(j, i), true) + ofs);
+ Vector2 to = xform.xform(node->map_to_world(Vector2(j + 1, i), true) + ofs);
+ Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2);
+ canvas_item_editor->draw_line(from, to, col, 1);
- if (max_lines--==0)
+ if (max_lines-- == 0)
break;
-
}
}
}
@@ -1168,74 +1157,73 @@ void TileMapEditor::_canvas_draw() {
if (selection_active) {
Vector<Vector2> points;
- points.push_back( xform.xform( node->map_to_world(( rectangle.pos ) )));
- points.push_back( xform.xform( node->map_to_world((rectangle.pos+Point2(rectangle.size.x+1,0)) ) ));
- points.push_back( xform.xform( node->map_to_world((rectangle.pos+Point2(rectangle.size.x+1,rectangle.size.y+1)) ) ));
- points.push_back( xform.xform( node->map_to_world((rectangle.pos+Point2(0,rectangle.size.y+1)) ) ));
+ points.push_back(xform.xform(node->map_to_world((rectangle.pos))));
+ points.push_back(xform.xform(node->map_to_world((rectangle.pos + Point2(rectangle.size.x + 1, 0)))));
+ points.push_back(xform.xform(node->map_to_world((rectangle.pos + Point2(rectangle.size.x + 1, rectangle.size.y + 1)))));
+ points.push_back(xform.xform(node->map_to_world((rectangle.pos + Point2(0, rectangle.size.y + 1)))));
- canvas_item_editor->draw_colored_polygon(points, Color(0.2,0.8,1,0.4));
+ canvas_item_editor->draw_colored_polygon(points, Color(0.2, 0.8, 1, 0.4));
}
- if (mouse_over){
+ if (mouse_over) {
- Vector2 endpoints[4]={
+ Vector2 endpoints[4] = {
node->map_to_world(over_tile, true),
- node->map_to_world((over_tile+Point2(1,0)), true),
- node->map_to_world((over_tile+Point2(1,1)), true),
- node->map_to_world((over_tile+Point2(0,1)), true)
+ node->map_to_world((over_tile + Point2(1, 0)), true),
+ node->map_to_world((over_tile + Point2(1, 1)), true),
+ node->map_to_world((over_tile + Point2(0, 1)), true)
};
- for (int i=0;i<4;i++) {
- if (node->get_half_offset()==TileMap::HALF_OFFSET_X && ABS(over_tile.y)&1)
- endpoints[i]+=cell_xf[0]*0.5;
- if (node->get_half_offset()==TileMap::HALF_OFFSET_Y && ABS(over_tile.x)&1)
- endpoints[i]+=cell_xf[1]*0.5;
- endpoints[i]=xform.xform(endpoints[i]);
+ for (int i = 0; i < 4; i++) {
+ if (node->get_half_offset() == TileMap::HALF_OFFSET_X && ABS(over_tile.y) & 1)
+ endpoints[i] += cell_xf[0] * 0.5;
+ if (node->get_half_offset() == TileMap::HALF_OFFSET_Y && ABS(over_tile.x) & 1)
+ endpoints[i] += cell_xf[1] * 0.5;
+ endpoints[i] = xform.xform(endpoints[i]);
}
Color col;
- if (node->get_cell(over_tile.x,over_tile.y)!=TileMap::INVALID_CELL)
- col=Color(0.2,0.8,1.0,0.8);
+ if (node->get_cell(over_tile.x, over_tile.y) != TileMap::INVALID_CELL)
+ col = Color(0.2, 0.8, 1.0, 0.8);
else
- col=Color(1.0,0.4,0.2,0.8);
-
- for (int i=0;i<4;i++)
- canvas_item_editor->draw_line(endpoints[i],endpoints[(i+1)%4],col,2);
+ col = Color(1.0, 0.4, 0.2, 0.8);
+ for (int i = 0; i < 4; i++)
+ canvas_item_editor->draw_line(endpoints[i], endpoints[(i + 1) % 4], col, 2);
bool bucket_preview = EditorSettings::get_singleton()->get("editors/tile_map/bucket_fill_preview");
- if (tool==TOOL_SELECTING || tool==TOOL_PICKING || !bucket_preview) {
+ if (tool == TOOL_SELECTING || tool == TOOL_PICKING || !bucket_preview) {
return;
}
- if (tool==TOOL_LINE_PAINT) {
+ if (tool == TOOL_LINE_PAINT) {
if (paint_undo.empty())
return;
int id = get_selected_tile();
- if (id==TileMap::INVALID_CELL)
+ if (id == TileMap::INVALID_CELL)
return;
- for (Map<Point2i, CellOp>::Element *E=paint_undo.front();E;E=E->next()) {
+ for (Map<Point2i, CellOp>::Element *E = paint_undo.front(); E; E = E->next()) {
_draw_cell(id, E->key(), flip_h, flip_v, transpose, xform);
}
- } else if (tool==TOOL_RECTANGLE_PAINT) {
+ } else if (tool == TOOL_RECTANGLE_PAINT) {
int id = get_selected_tile();
- if (id==TileMap::INVALID_CELL)
+ if (id == TileMap::INVALID_CELL)
return;
- for (int i=rectangle.pos.y;i<=rectangle.pos.y+rectangle.size.y;i++) {
- for (int j=rectangle.pos.x;j<=rectangle.pos.x+rectangle.size.x;j++) {
+ for (int i = rectangle.pos.y; i <= rectangle.pos.y + rectangle.size.y; i++) {
+ for (int j = rectangle.pos.x; j <= rectangle.pos.x + rectangle.size.x; j++) {
_draw_cell(id, Point2i(j, i), flip_h, flip_v, transpose, xform);
}
}
- } else if (tool==TOOL_DUPLICATING) {
+ } else if (tool == TOOL_DUPLICATING) {
if (copydata.empty())
return;
@@ -1245,30 +1233,30 @@ void TileMapEditor::_canvas_draw() {
if (ts.is_null())
return;
- Point2 ofs = over_tile-rectangle.pos;
+ Point2 ofs = over_tile - rectangle.pos;
- for (List<TileData>::Element *E=copydata.front();E;E=E->next()) {
+ for (List<TileData>::Element *E = copydata.front(); E; E = E->next()) {
if (!ts->has_tile(E->get().cell))
continue;
TileData tcd = E->get();
- _draw_cell(tcd.cell, tcd.pos+ofs, tcd.flip_h, tcd.flip_v, tcd.transpose, xform);
+ _draw_cell(tcd.cell, tcd.pos + ofs, tcd.flip_h, tcd.flip_v, tcd.transpose, xform);
}
- Rect2i duplicate=rectangle;
- duplicate.pos=over_tile;
+ Rect2i duplicate = rectangle;
+ duplicate.pos = over_tile;
Vector<Vector2> points;
- points.push_back( xform.xform( node->map_to_world(duplicate.pos ) ));
- points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(duplicate.size.x+1,0)) ) ));
- points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(duplicate.size.x+1,duplicate.size.y+1))) ));
- points.push_back( xform.xform( node->map_to_world((duplicate.pos+Point2(0,duplicate.size.y+1))) ));
+ points.push_back(xform.xform(node->map_to_world(duplicate.pos)));
+ points.push_back(xform.xform(node->map_to_world((duplicate.pos + Point2(duplicate.size.x + 1, 0)))));
+ points.push_back(xform.xform(node->map_to_world((duplicate.pos + Point2(duplicate.size.x + 1, duplicate.size.y + 1)))));
+ points.push_back(xform.xform(node->map_to_world((duplicate.pos + Point2(0, duplicate.size.y + 1)))));
- canvas_item_editor->draw_colored_polygon(points, Color(0.2,1.0,0.8,0.2));
+ canvas_item_editor->draw_colored_polygon(points, Color(0.2, 1.0, 0.8, 0.2));
- } else if(tool == TOOL_BUCKET) {
+ } else if (tool == TOOL_BUCKET) {
int tile = get_selected_tile();
_draw_fill_preview(tile, over_tile, flip_h, flip_v, transpose, xform);
@@ -1277,7 +1265,7 @@ void TileMapEditor::_canvas_draw() {
int st = get_selected_tile();
- if (st==TileMap::INVALID_CELL)
+ if (st == TileMap::INVALID_CELL)
return;
_draw_cell(st, over_tile, flip_h, flip_v, transpose, xform);
@@ -1290,41 +1278,40 @@ void TileMapEditor::edit(Node *p_tile_map) {
search_box->set_text("");
if (!canvas_item_editor) {
- canvas_item_editor=CanvasItemEditor::get_singleton()->get_viewport_control();
+ canvas_item_editor = CanvasItemEditor::get_singleton()->get_viewport_control();
}
if (node)
- node->disconnect("settings_changed",this,"_tileset_settings_changed");
+ node->disconnect("settings_changed", this, "_tileset_settings_changed");
if (p_tile_map) {
- node=p_tile_map->cast_to<TileMap>();
- if (!canvas_item_editor->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->connect("draw",this,"_canvas_draw");
- if (!canvas_item_editor->is_connected("mouse_entered",this,"_canvas_mouse_enter"))
- canvas_item_editor->connect("mouse_entered",this,"_canvas_mouse_enter");
- if (!canvas_item_editor->is_connected("mouse_exited",this,"_canvas_mouse_exit"))
- canvas_item_editor->connect("mouse_exited",this,"_canvas_mouse_exit");
+ node = p_tile_map->cast_to<TileMap>();
+ if (!canvas_item_editor->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->connect("draw", this, "_canvas_draw");
+ if (!canvas_item_editor->is_connected("mouse_entered", this, "_canvas_mouse_enter"))
+ canvas_item_editor->connect("mouse_entered", this, "_canvas_mouse_enter");
+ if (!canvas_item_editor->is_connected("mouse_exited", this, "_canvas_mouse_exit"))
+ canvas_item_editor->connect("mouse_exited", this, "_canvas_mouse_exit");
_update_palette();
} else {
- node=NULL;
+ node = NULL;
- if (canvas_item_editor->is_connected("draw",this,"_canvas_draw"))
- canvas_item_editor->disconnect("draw",this,"_canvas_draw");
- if (canvas_item_editor->is_connected("mouse_entered",this,"_canvas_mouse_enter"))
- canvas_item_editor->disconnect("mouse_entered",this,"_canvas_mouse_enter");
- if (canvas_item_editor->is_connected("mouse_exited",this,"_canvas_mouse_exit"))
- canvas_item_editor->disconnect("mouse_exited",this,"_canvas_mouse_exit");
+ if (canvas_item_editor->is_connected("draw", this, "_canvas_draw"))
+ canvas_item_editor->disconnect("draw", this, "_canvas_draw");
+ if (canvas_item_editor->is_connected("mouse_entered", this, "_canvas_mouse_enter"))
+ canvas_item_editor->disconnect("mouse_entered", this, "_canvas_mouse_enter");
+ if (canvas_item_editor->is_connected("mouse_exited", this, "_canvas_mouse_exit"))
+ canvas_item_editor->disconnect("mouse_exited", this, "_canvas_mouse_exit");
_update_palette();
}
if (node)
- node->connect("settings_changed",this,"_tileset_settings_changed");
+ node->connect("settings_changed", this, "_tileset_settings_changed");
_clear_bucket_cache();
-
}
void TileMapEditor::_tileset_settings_changed() {
@@ -1344,66 +1331,62 @@ void TileMapEditor::_icon_size_changed(float p_value) {
void TileMapEditor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_entered"),&TileMapEditor::_text_entered);
- ClassDB::bind_method(D_METHOD("_text_changed"),&TileMapEditor::_text_changed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&TileMapEditor::_sbox_input);
- ClassDB::bind_method(D_METHOD("_menu_option"),&TileMapEditor::_menu_option);
- ClassDB::bind_method(D_METHOD("_canvas_draw"),&TileMapEditor::_canvas_draw);
- ClassDB::bind_method(D_METHOD("_canvas_mouse_enter"),&TileMapEditor::_canvas_mouse_enter);
- ClassDB::bind_method(D_METHOD("_canvas_mouse_exit"),&TileMapEditor::_canvas_mouse_exit);
- ClassDB::bind_method(D_METHOD("_tileset_settings_changed"),&TileMapEditor::_tileset_settings_changed);
- ClassDB::bind_method(D_METHOD("_update_transform_buttons"),&TileMapEditor::_update_transform_buttons);
+ ClassDB::bind_method(D_METHOD("_text_entered"), &TileMapEditor::_text_entered);
+ ClassDB::bind_method(D_METHOD("_text_changed"), &TileMapEditor::_text_changed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &TileMapEditor::_sbox_input);
+ ClassDB::bind_method(D_METHOD("_menu_option"), &TileMapEditor::_menu_option);
+ ClassDB::bind_method(D_METHOD("_canvas_draw"), &TileMapEditor::_canvas_draw);
+ ClassDB::bind_method(D_METHOD("_canvas_mouse_enter"), &TileMapEditor::_canvas_mouse_enter);
+ ClassDB::bind_method(D_METHOD("_canvas_mouse_exit"), &TileMapEditor::_canvas_mouse_exit);
+ ClassDB::bind_method(D_METHOD("_tileset_settings_changed"), &TileMapEditor::_tileset_settings_changed);
+ ClassDB::bind_method(D_METHOD("_update_transform_buttons"), &TileMapEditor::_update_transform_buttons);
- ClassDB::bind_method(D_METHOD("_fill_points"),&TileMapEditor::_fill_points);
- ClassDB::bind_method(D_METHOD("_erase_points"),&TileMapEditor::_erase_points);
+ ClassDB::bind_method(D_METHOD("_fill_points"), &TileMapEditor::_fill_points);
+ ClassDB::bind_method(D_METHOD("_erase_points"), &TileMapEditor::_erase_points);
ClassDB::bind_method(D_METHOD("_icon_size_changed"), &TileMapEditor::_icon_size_changed);
}
-TileMapEditor::CellOp TileMapEditor::_get_op_from_cell(const Point2i& p_pos)
-{
+TileMapEditor::CellOp TileMapEditor::_get_op_from_cell(const Point2i &p_pos) {
CellOp op;
- op.idx = node->get_cell(p_pos.x,p_pos.y);
- if (op.idx!=TileMap::INVALID_CELL) {
- if (node->is_cell_x_flipped(p_pos.x,p_pos.y))
- op.xf=true;
- if (node->is_cell_y_flipped(p_pos.x,p_pos.y))
- op.yf=true;
- if (node->is_cell_transposed(p_pos.x,p_pos.y))
- op.tr=true;
+ op.idx = node->get_cell(p_pos.x, p_pos.y);
+ if (op.idx != TileMap::INVALID_CELL) {
+ if (node->is_cell_x_flipped(p_pos.x, p_pos.y))
+ op.xf = true;
+ if (node->is_cell_y_flipped(p_pos.x, p_pos.y))
+ op.yf = true;
+ if (node->is_cell_transposed(p_pos.x, p_pos.y))
+ op.tr = true;
}
return op;
}
void TileMapEditor::_update_transform_buttons(Object *p_button) {
//ERR_FAIL_NULL(p_button);
- ToolButton *b=p_button->cast_to<ToolButton>();
+ ToolButton *b = p_button->cast_to<ToolButton>();
//ERR_FAIL_COND(!b);
if (b == rotate_0) {
mirror_x->set_pressed(false);
mirror_y->set_pressed(false);
transp->set_pressed(false);
- }
- else if (b == rotate_90) {
+ } else if (b == rotate_90) {
mirror_x->set_pressed(true);
mirror_y->set_pressed(false);
transp->set_pressed(true);
- }
- else if (b == rotate_180) {
+ } else if (b == rotate_180) {
mirror_x->set_pressed(true);
mirror_y->set_pressed(true);
transp->set_pressed(false);
- }
- else if (b == rotate_270) {
+ } else if (b == rotate_270) {
mirror_x->set_pressed(false);
mirror_y->set_pressed(true);
transp->set_pressed(true);
}
- flip_h=mirror_x->is_pressed();
- flip_v=mirror_y->is_pressed();
- transpose=transp->is_pressed();
+ flip_h = mirror_x->is_pressed();
+ flip_v = mirror_y->is_pressed();
+ transpose = transp->is_pressed();
rotate_0->set_pressed(!flip_h && !flip_v && !transpose);
rotate_90->set_pressed(flip_h && !flip_v && transpose);
@@ -1413,36 +1396,36 @@ void TileMapEditor::_update_transform_buttons(Object *p_button) {
TileMapEditor::TileMapEditor(EditorNode *p_editor) {
- node=NULL;
- canvas_item_editor=NULL;
- editor=p_editor;
- undo_redo=editor->get_undo_redo();
+ node = NULL;
+ canvas_item_editor = NULL;
+ editor = p_editor;
+ undo_redo = editor->get_undo_redo();
- tool=TOOL_NONE;
- selection_active=false;
- mouse_over=false;
+ tool = TOOL_NONE;
+ selection_active = false;
+ mouse_over = false;
- flip_h=false;
- flip_v=false;
- transpose=false;
+ flip_h = false;
+ flip_v = false;
+ transpose = false;
bucket_cache_tile = -1;
bucket_cache_visited = 0;
ED_SHORTCUT("tile_map_editor/erase_selection", TTR("Erase selection"), KEY_DELETE);
- ED_SHORTCUT("tile_map_editor/find_tile", TTR("Find tile"), KEY_MASK_CMD+KEY_F);
+ ED_SHORTCUT("tile_map_editor/find_tile", TTR("Find tile"), KEY_MASK_CMD + KEY_F);
ED_SHORTCUT("tile_map_editor/transpose", TTR("Transpose"));
ED_SHORTCUT("tile_map_editor/mirror_x", TTR("Mirror X"), KEY_A);
ED_SHORTCUT("tile_map_editor/mirror_y", TTR("Mirror Y"), KEY_S);
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
search_box->connect("text_entered", this, "_text_entered");
search_box->connect("text_changed", this, "_text_changed");
search_box->connect("gui_input", this, "_sbox_input");
add_child(search_box);
- size_slider = memnew( HSlider );
+ size_slider = memnew(HSlider);
size_slider->set_h_size_flags(SIZE_EXPAND_FILL);
size_slider->set_min(0.1f);
size_slider->set_max(4.0f);
@@ -1454,25 +1437,25 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) {
int mw = EDITOR_DEF("editors/tile_map/palette_min_width", 80);
// Add tile palette
- palette = memnew( ItemList );
+ palette = memnew(ItemList);
palette->set_v_size_flags(SIZE_EXPAND_FILL);
- palette->set_custom_minimum_size(Size2(mw,0));
+ palette->set_custom_minimum_size(Size2(mw, 0));
palette->set_max_columns(0);
palette->set_icon_mode(ItemList::ICON_MODE_TOP);
palette->set_max_text_lines(2);
add_child(palette);
// Add menu items
- toolbar = memnew( HBoxContainer );
+ toolbar = memnew(HBoxContainer);
toolbar->set_h_size_flags(SIZE_EXPAND_FILL);
toolbar->set_alignment(BoxContainer::ALIGN_END);
CanvasItemEditor::get_singleton()->add_control_to_menu_panel(toolbar);
// Tile position
- tile_info = memnew( Label );
+ tile_info = memnew(Label);
toolbar->add_child(tile_info);
- options = memnew( MenuButton );
+ options = memnew(MenuButton);
options->set_text("Tile Map");
options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon("TileMap", "EditorIcons"));
options->set_process_unhandled_key_input(false);
@@ -1483,56 +1466,56 @@ TileMapEditor::TileMapEditor(EditorNode *p_editor) {
p->add_separator();
p->add_item(TTR("Pick Tile"), OPTION_PICK_TILE, KEY_CONTROL);
p->add_separator();
- p->add_shortcut(ED_SHORTCUT("tile_map_editor/select", TTR("Select"), KEY_MASK_CMD+KEY_B), OPTION_SELECT);
- p->add_shortcut(ED_SHORTCUT("tile_map_editor/duplicate_selection", TTR("Duplicate Selection"), KEY_MASK_CMD+KEY_D), OPTION_DUPLICATE);
+ p->add_shortcut(ED_SHORTCUT("tile_map_editor/select", TTR("Select"), KEY_MASK_CMD + KEY_B), OPTION_SELECT);
+ p->add_shortcut(ED_SHORTCUT("tile_map_editor/duplicate_selection", TTR("Duplicate Selection"), KEY_MASK_CMD + KEY_D), OPTION_DUPLICATE);
p->add_shortcut(ED_GET_SHORTCUT("tile_map_editor/erase_selection"), OPTION_ERASE_SELECTION);
p->connect("id_pressed", this, "_menu_option");
toolbar->add_child(options);
- toolbar->add_child( memnew( VSeparator ) );
+ toolbar->add_child(memnew(VSeparator));
- transp = memnew( ToolButton );
+ transp = memnew(ToolButton);
transp->set_toggle_mode(true);
- transp->set_tooltip(TTR("Transpose") + " ("+ED_GET_SHORTCUT("tile_map_editor/transpose")->get_as_text()+")");
+ transp->set_tooltip(TTR("Transpose") + " (" + ED_GET_SHORTCUT("tile_map_editor/transpose")->get_as_text() + ")");
transp->set_focus_mode(FOCUS_NONE);
transp->connect("pressed", this, "_update_transform_buttons", make_binds(transp));
toolbar->add_child(transp);
- mirror_x = memnew( ToolButton );
+ mirror_x = memnew(ToolButton);
mirror_x->set_toggle_mode(true);
- mirror_x->set_tooltip(TTR("Mirror X") + " ("+ED_GET_SHORTCUT("tile_map_editor/mirror_x")->get_as_text()+")");
+ mirror_x->set_tooltip(TTR("Mirror X") + " (" + ED_GET_SHORTCUT("tile_map_editor/mirror_x")->get_as_text() + ")");
mirror_x->set_focus_mode(FOCUS_NONE);
mirror_x->connect("pressed", this, "_update_transform_buttons", make_binds(mirror_x));
toolbar->add_child(mirror_x);
- mirror_y = memnew( ToolButton );
+ mirror_y = memnew(ToolButton);
mirror_y->set_toggle_mode(true);
- mirror_y->set_tooltip(TTR("Mirror Y") + " ("+ED_GET_SHORTCUT("tile_map_editor/mirror_y")->get_as_text()+")");
+ mirror_y->set_tooltip(TTR("Mirror Y") + " (" + ED_GET_SHORTCUT("tile_map_editor/mirror_y")->get_as_text() + ")");
mirror_y->set_focus_mode(FOCUS_NONE);
mirror_y->connect("pressed", this, "_update_transform_buttons", make_binds(mirror_y));
toolbar->add_child(mirror_y);
- toolbar->add_child( memnew( VSeparator ) );
+ toolbar->add_child(memnew(VSeparator));
- rotate_0 = memnew( ToolButton );
+ rotate_0 = memnew(ToolButton);
rotate_0->set_toggle_mode(true);
rotate_0->set_tooltip(TTR("Rotate 0 degrees"));
rotate_0->set_focus_mode(FOCUS_NONE);
rotate_0->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_0));
toolbar->add_child(rotate_0);
- rotate_90 = memnew( ToolButton );
+ rotate_90 = memnew(ToolButton);
rotate_90->set_toggle_mode(true);
rotate_90->set_tooltip(TTR("Rotate 90 degrees"));
rotate_90->set_focus_mode(FOCUS_NONE);
rotate_90->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_90));
toolbar->add_child(rotate_90);
- rotate_180 = memnew( ToolButton );
+ rotate_180 = memnew(ToolButton);
rotate_180->set_toggle_mode(true);
rotate_180->set_tooltip(TTR("Rotate 180 degrees"));
rotate_180->set_focus_mode(FOCUS_NONE);
rotate_180->connect("pressed", this, "_update_transform_buttons", make_binds(rotate_180));
toolbar->add_child(rotate_180);
- rotate_270 = memnew( ToolButton );
+ rotate_270 = memnew(ToolButton);
rotate_270->set_toggle_mode(true);
rotate_270->set_tooltip(TTR("Rotate 270 degrees"));
rotate_270->set_focus_mode(FOCUS_NONE);
@@ -1577,17 +1560,15 @@ void TileMapEditorPlugin::make_visible(bool p_visible) {
TileMapEditorPlugin::TileMapEditorPlugin(EditorNode *p_node) {
- EDITOR_DEF("editors/tile_map/preview_size",64);
- EDITOR_DEF("editors/tile_map/palette_item_hseparation",8);
+ EDITOR_DEF("editors/tile_map/preview_size", 64);
+ EDITOR_DEF("editors/tile_map/palette_item_hseparation", 8);
EDITOR_DEF("editors/tile_map/show_tile_names", true);
EDITOR_DEF("editors/tile_map/bucket_fill_preview", true);
- tile_map_editor = memnew( TileMapEditor(p_node) );
+ tile_map_editor = memnew(TileMapEditor(p_node));
add_control_to_container(CONTAINER_CANVAS_EDITOR_SIDE, tile_map_editor);
tile_map_editor->hide();
}
-TileMapEditorPlugin::~TileMapEditorPlugin()
-{
+TileMapEditorPlugin::~TileMapEditorPlugin() {
}
-
diff --git a/editor/plugins/tile_map_editor_plugin.h b/editor/plugins/tile_map_editor_plugin.h
index 82e2a396d1..a4774a23b9 100644
--- a/editor/plugins/tile_map_editor_plugin.h
+++ b/editor/plugins/tile_map_editor_plugin.h
@@ -29,14 +29,14 @@
#ifndef TILE_MAP_EDITOR_PLUGIN_H
#define TILE_MAP_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
+#include "editor/editor_plugin.h"
#include "scene/2d/tile_map.h"
+#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/label.h"
+#include "scene/gui/tool_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -44,7 +44,7 @@
class TileMapEditor : public VBoxContainer {
- GDCLASS(TileMapEditor, VBoxContainer );
+ GDCLASS(TileMapEditor, VBoxContainer);
enum Tool {
@@ -77,7 +77,7 @@ class TileMapEditor : public VBoxContainer {
Control *canvas_item_editor;
LineEdit *search_box;
- HSlider *size_slider;
+ HSlider *size_slider;
ItemList *palette;
HBoxContainer *toolbar;
@@ -106,7 +106,7 @@ class TileMapEditor : public VBoxContainer {
Point2i over_tile;
- bool * bucket_cache_visited;
+ bool *bucket_cache_visited;
Rect2i bucket_cache_rect;
int bucket_cache_tile;
PoolVector<Vector2> bucket_cache;
@@ -117,7 +117,12 @@ class TileMapEditor : public VBoxContainer {
bool yf;
bool tr;
- CellOp() { idx=-1; xf=false; yf=false; tr=false; }
+ CellOp() {
+ idx = -1;
+ xf = false;
+ yf = false;
+ tr = false;
+ }
};
Map<Point2i, CellOp> paint_undo;
@@ -132,17 +137,17 @@ class TileMapEditor : public VBoxContainer {
List<TileData> copydata;
- void _pick_tile(const Point2& p_pos);
+ void _pick_tile(const Point2 &p_pos);
- PoolVector<Vector2> _bucket_fill(const Point2i& p_start, bool erase=false, bool preview=false);
+ PoolVector<Vector2> _bucket_fill(const Point2i &p_start, bool erase = false, bool preview = false);
- void _fill_points(const PoolVector<Vector2> p_points, const Dictionary& p_op);
+ void _fill_points(const PoolVector<Vector2> p_points, const Dictionary &p_op);
void _erase_points(const PoolVector<Vector2> p_points);
- void _select(const Point2i& p_from, const Point2i& p_to);
+ void _select(const Point2i &p_from, const Point2i &p_to);
- void _draw_cell(int p_cell, const Point2i& p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D& p_xform);
- void _draw_fill_preview(int p_cell, const Point2i& p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D& p_xform);
+ void _draw_cell(int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D &p_xform);
+ void _draw_fill_preview(int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Transform2D &p_xform);
void _clear_bucket_cache();
void _update_copydata();
@@ -150,14 +155,14 @@ class TileMapEditor : public VBoxContainer {
int get_selected_tile() const;
void set_selected_tile(int p_tile);
- void _text_entered(const String& p_text);
- void _text_changed(const String& p_text);
- void _sbox_input(const InputEvent& p_ie);
+ void _text_entered(const String &p_text);
+ void _text_changed(const String &p_text);
+ void _sbox_input(const InputEvent &p_ie);
void _update_palette();
void _canvas_draw();
void _menu_option(int p_option);
- void _set_cell(const Point2i& p_pos, int p_value, bool p_flip_h=false, bool p_flip_v=false, bool p_transpose=false, bool p_with_undo=false);
+ void _set_cell(const Point2i &p_pos, int p_value, bool p_flip_h = false, bool p_flip_v = false, bool p_transpose = false, bool p_with_undo = false);
void _canvas_mouse_enter();
void _canvas_mouse_exit();
@@ -165,17 +170,15 @@ class TileMapEditor : public VBoxContainer {
void _icon_size_changed(float p_value);
protected:
-
void _notification(int p_what);
static void _bind_methods();
- CellOp _get_op_from_cell(const Point2i& p_pos);
- void _update_transform_buttons(Object *p_button=NULL);
+ CellOp _get_op_from_cell(const Point2i &p_pos);
+ void _update_transform_buttons(Object *p_button = NULL);
public:
-
HBoxContainer *get_toolbar() const { return toolbar; }
- bool forward_gui_input(const InputEvent& p_event);
+ bool forward_gui_input(const InputEvent &p_event);
void edit(Node *p_tile_map);
TileMapEditor(EditorNode *p_editor);
@@ -184,13 +187,12 @@ public:
class TileMapEditorPlugin : public EditorPlugin {
- GDCLASS( TileMapEditorPlugin, EditorPlugin );
+ GDCLASS(TileMapEditorPlugin, EditorPlugin);
TileMapEditor *tile_map_editor;
public:
-
- virtual bool forward_canvas_gui_input(const Transform2D& p_canvas_xform,const InputEvent& p_event) { return tile_map_editor->forward_gui_input(p_event); }
+ virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const InputEvent &p_event) { return tile_map_editor->forward_gui_input(p_event); }
virtual String get_name() const { return "TileMap"; }
bool has_main_screen() const { return false; }
@@ -200,8 +202,6 @@ public:
TileMapEditorPlugin(EditorNode *p_node);
~TileMapEditorPlugin();
-
};
-
#endif // TILE_MAP_EDITOR_PLUGIN_H
diff --git a/editor/plugins/tile_set_editor_plugin.cpp b/editor/plugins/tile_set_editor_plugin.cpp
index 3db6c94917..6dee151d99 100644
--- a/editor/plugins/tile_set_editor_plugin.cpp
+++ b/editor/plugins/tile_set_editor_plugin.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "tile_set_editor_plugin.h"
-#include "scene/2d/sprite.h"
#include "scene/2d/physics_body_2d.h"
+#include "scene/2d/sprite.h"
-void TileSetEditor::edit(const Ref<TileSet>& p_tileset) {
+void TileSetEditor::edit(const Ref<TileSet> &p_tileset) {
- tileset=p_tileset;
+ tileset = p_tileset;
}
void TileSetEditor::_import_scene(Node *scene, Ref<TileSet> p_library, bool p_merge) {
@@ -41,85 +41,80 @@ void TileSetEditor::_import_scene(Node *scene, Ref<TileSet> p_library, bool p_me
if (!p_merge)
p_library->clear();
- for(int i=0;i<scene->get_child_count();i++) {
-
+ for (int i = 0; i < scene->get_child_count(); i++) {
Node *child = scene->get_child(i);
-
if (!child->cast_to<Sprite>()) {
- if (child->get_child_count()>0) {
- child=child->get_child(0);
+ if (child->get_child_count() > 0) {
+ child = child->get_child(0);
if (!child->cast_to<Sprite>()) {
continue;
}
} else
continue;
-
-
}
Sprite *mi = child->cast_to<Sprite>();
- Ref<Texture> texture=mi->get_texture();
- Ref<CanvasItemMaterial> material=mi->get_material();
+ Ref<Texture> texture = mi->get_texture();
+ Ref<CanvasItemMaterial> material = mi->get_material();
if (texture.is_null())
continue;
int id = p_library->find_tile_by_name(mi->get_name());
- if (id<0) {
+ if (id < 0) {
- id=p_library->get_last_unused_tile_id();
+ id = p_library->get_last_unused_tile_id();
p_library->create_tile(id);
- p_library->tile_set_name(id,mi->get_name());
+ p_library->tile_set_name(id, mi->get_name());
}
- p_library->tile_set_texture(id,texture);
- p_library->tile_set_material(id,material);
+ p_library->tile_set_texture(id, texture);
+ p_library->tile_set_material(id, material);
- p_library->tile_set_modulate(id,mi->get_modulate());
+ p_library->tile_set_modulate(id, mi->get_modulate());
Vector2 phys_offset;
Size2 s;
if (mi->is_region()) {
- s=mi->get_region_rect().size;
- p_library->tile_set_region(id,mi->get_region_rect());
+ s = mi->get_region_rect().size;
+ p_library->tile_set_region(id, mi->get_region_rect());
} else {
const int frame = mi->get_frame();
const int hframes = mi->get_hframes();
- s=texture->get_size()/Size2(hframes,mi->get_vframes());
- p_library->tile_set_region(id,Rect2(Vector2(frame%hframes,frame/hframes)*s,s));
+ s = texture->get_size() / Size2(hframes, mi->get_vframes());
+ p_library->tile_set_region(id, Rect2(Vector2(frame % hframes, frame / hframes) * s, s));
}
-
+
if (mi->is_centered()) {
- phys_offset+=-s/2;
+ phys_offset += -s / 2;
}
- Vector<Ref<Shape2D> >collisions;
+ Vector<Ref<Shape2D> > collisions;
Ref<NavigationPolygon> nav_poly;
Ref<OccluderPolygon2D> occluder;
- for(int j=0;j<mi->get_child_count();j++) {
+ for (int j = 0; j < mi->get_child_count(); j++) {
Node *child2 = mi->get_child(j);
if (child2->cast_to<NavigationPolygonInstance>())
- nav_poly=child2->cast_to<NavigationPolygonInstance>()->get_navigation_polygon();
+ nav_poly = child2->cast_to<NavigationPolygonInstance>()->get_navigation_polygon();
if (child2->cast_to<LightOccluder2D>())
- occluder=child2->cast_to<LightOccluder2D>()->get_occluder_polygon();
+ occluder = child2->cast_to<LightOccluder2D>()->get_occluder_polygon();
if (!child2->cast_to<StaticBody2D>())
continue;
StaticBody2D *sb = child2->cast_to<StaticBody2D>();
int shape_count = sb->get_shape_count();
- if (shape_count==0)
+ if (shape_count == 0)
continue;
- for (int shape_index=0; shape_index<shape_count; ++shape_index)
- {
- Ref<Shape2D> collision=sb->get_shape(shape_index);
+ for (int shape_index = 0; shape_index < shape_count; ++shape_index) {
+ Ref<Shape2D> collision = sb->get_shape(shape_index);
if (collision.is_valid()) {
collisions.push_back(collision);
}
@@ -128,58 +123,53 @@ void TileSetEditor::_import_scene(Node *scene, Ref<TileSet> p_library, bool p_me
if (collisions.size()) {
- p_library->tile_set_shapes(id,collisions);
- p_library->tile_set_shape_offset(id,-phys_offset);
+ p_library->tile_set_shapes(id, collisions);
+ p_library->tile_set_shape_offset(id, -phys_offset);
} else {
- p_library->tile_set_shape_offset(id,Vector2());
-
+ p_library->tile_set_shape_offset(id, Vector2());
}
- p_library->tile_set_texture_offset(id,mi->get_offset());
- p_library->tile_set_navigation_polygon(id,nav_poly);
- p_library->tile_set_light_occluder(id,occluder);
- p_library->tile_set_occluder_offset(id,-phys_offset);
- p_library->tile_set_navigation_polygon_offset(id,-phys_offset);
-
-
+ p_library->tile_set_texture_offset(id, mi->get_offset());
+ p_library->tile_set_navigation_polygon(id, nav_poly);
+ p_library->tile_set_light_occluder(id, occluder);
+ p_library->tile_set_occluder_offset(id, -phys_offset);
+ p_library->tile_set_navigation_polygon_offset(id, -phys_offset);
}
}
void TileSetEditor::_menu_confirm() {
- switch(option) {
+ switch (option) {
case MENU_OPTION_MERGE_FROM_SCENE:
case MENU_OPTION_CREATE_FROM_SCENE: {
-
EditorNode *en = editor;
- Node * scene = en->get_edited_scene();
+ Node *scene = en->get_edited_scene();
if (!scene)
break;
- _import_scene(scene,tileset,option==MENU_OPTION_MERGE_FROM_SCENE);
-
+ _import_scene(scene, tileset, option == MENU_OPTION_MERGE_FROM_SCENE);
} break;
}
}
-void TileSetEditor::_name_dialog_confirm(const String& name) {
+void TileSetEditor::_name_dialog_confirm(const String &name) {
switch (option) {
case MENU_OPTION_REMOVE_ITEM: {
- int id=tileset->find_tile_by_name(name);
+ int id = tileset->find_tile_by_name(name);
- if (id<0 && name.is_valid_integer())
- id=name.to_int();
+ if (id < 0 && name.is_valid_integer())
+ id = name.to_int();
if (tileset->has_tile(id)) {
tileset->remove_tile(id);
} else {
- err_dialog->set_text(TTR("Could not find tile:")+" " + name);
+ err_dialog->set_text(TTR("Could not find tile:") + " " + name);
err_dialog->popup_centered(Size2(300, 60));
}
} break;
@@ -188,8 +178,8 @@ void TileSetEditor::_name_dialog_confirm(const String& name) {
void TileSetEditor::_menu_cbk(int p_option) {
- option=p_option;
- switch(p_option) {
+ option = p_option;
+ switch (p_option) {
case MENU_OPTION_ADD_ITEM: {
@@ -204,57 +194,54 @@ void TileSetEditor::_menu_cbk(int p_option) {
case MENU_OPTION_CREATE_FROM_SCENE: {
cd->set_text(TTR("Create from scene?"));
- cd->popup_centered(Size2(300,60));
+ cd->popup_centered(Size2(300, 60));
} break;
case MENU_OPTION_MERGE_FROM_SCENE: {
cd->set_text(TTR("Merge from scene?"));
- cd->popup_centered(Size2(300,60));
+ cd->popup_centered(Size2(300, 60));
} break;
}
}
+Error TileSetEditor::update_library_file(Node *p_base_scene, Ref<TileSet> ml, bool p_merge) {
-
-Error TileSetEditor::update_library_file(Node *p_base_scene, Ref<TileSet> ml,bool p_merge) {
-
- _import_scene(p_base_scene,ml,p_merge);
+ _import_scene(p_base_scene, ml, p_merge);
return OK;
-
}
void TileSetEditor::_bind_methods() {
- ClassDB::bind_method("_menu_cbk",&TileSetEditor::_menu_cbk);
- ClassDB::bind_method("_menu_confirm",&TileSetEditor::_menu_confirm);
- ClassDB::bind_method("_name_dialog_confirm",&TileSetEditor::_name_dialog_confirm);
+ ClassDB::bind_method("_menu_cbk", &TileSetEditor::_menu_cbk);
+ ClassDB::bind_method("_menu_confirm", &TileSetEditor::_menu_confirm);
+ ClassDB::bind_method("_name_dialog_confirm", &TileSetEditor::_name_dialog_confirm);
}
TileSetEditor::TileSetEditor(EditorNode *p_editor) {
- Panel *panel = memnew( Panel );
+ Panel *panel = memnew(Panel);
panel->set_area_as_parent_rect();
add_child(panel);
- MenuButton * options = memnew( MenuButton );
+ MenuButton *options = memnew(MenuButton);
panel->add_child(options);
- options->set_pos(Point2(1,1));
+ options->set_pos(Point2(1, 1));
options->set_text("Theme");
- options->get_popup()->add_item(TTR("Add Item"),MENU_OPTION_ADD_ITEM);
- options->get_popup()->add_item(TTR("Remove Item"),MENU_OPTION_REMOVE_ITEM);
+ options->get_popup()->add_item(TTR("Add Item"), MENU_OPTION_ADD_ITEM);
+ options->get_popup()->add_item(TTR("Remove Item"), MENU_OPTION_REMOVE_ITEM);
options->get_popup()->add_separator();
- options->get_popup()->add_item(TTR("Create from Scene"),MENU_OPTION_CREATE_FROM_SCENE);
- options->get_popup()->add_item(TTR("Merge from Scene"),MENU_OPTION_MERGE_FROM_SCENE);
- options->get_popup()->connect("id_pressed", this,"_menu_cbk");
- editor=p_editor;
+ options->get_popup()->add_item(TTR("Create from Scene"), MENU_OPTION_CREATE_FROM_SCENE);
+ options->get_popup()->add_item(TTR("Merge from Scene"), MENU_OPTION_MERGE_FROM_SCENE);
+ options->get_popup()->connect("id_pressed", this, "_menu_cbk");
+ editor = p_editor;
cd = memnew(ConfirmationDialog);
add_child(cd);
- cd->get_ok()->connect("pressed", this,"_menu_confirm");
+ cd->get_ok()->connect("pressed", this, "_menu_confirm");
nd = memnew(EditorNameDialog);
add_child(nd);
nd->set_hide_on_ok(true);
- nd->get_line_edit()->set_margin(MARGIN_TOP,28);
- nd->connect("name_confirmed", this,"_name_dialog_confirm");
+ nd->get_line_edit()->set_margin(MARGIN_TOP, 28);
+ nd->connect("name_confirmed", this, "_name_dialog_confirm");
err_dialog = memnew(AcceptDialog);
add_child(err_dialog);
@@ -264,18 +251,18 @@ TileSetEditor::TileSetEditor(EditorNode *p_editor) {
void TileSetEditorPlugin::edit(Object *p_node) {
if (p_node && p_node->cast_to<TileSet>()) {
- tileset_editor->edit( p_node->cast_to<TileSet>() );
+ tileset_editor->edit(p_node->cast_to<TileSet>());
tileset_editor->show();
} else
tileset_editor->hide();
}
-bool TileSetEditorPlugin::handles(Object *p_node) const{
+bool TileSetEditorPlugin::handles(Object *p_node) const {
return p_node->is_class("TileSet");
}
-void TileSetEditorPlugin::make_visible(bool p_visible){
+void TileSetEditorPlugin::make_visible(bool p_visible) {
if (p_visible)
tileset_editor->show();
@@ -285,13 +272,12 @@ void TileSetEditorPlugin::make_visible(bool p_visible){
TileSetEditorPlugin::TileSetEditorPlugin(EditorNode *p_node) {
- tileset_editor = memnew( TileSetEditor(p_node) );
+ tileset_editor = memnew(TileSetEditor(p_node));
p_node->get_viewport()->add_child(tileset_editor);
tileset_editor->set_area_as_parent_rect();
- tileset_editor->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
- tileset_editor->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_BEGIN );
- tileset_editor->set_end( Point2(0,22) );
+ tileset_editor->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
+ tileset_editor->set_anchor(MARGIN_BOTTOM, Control::ANCHOR_BEGIN);
+ tileset_editor->set_end(Point2(0, 22));
tileset_editor->hide();
-
}
diff --git a/editor/plugins/tile_set_editor_plugin.h b/editor/plugins/tile_set_editor_plugin.h
index 02a82ebd6b..0dabf58f7c 100644
--- a/editor/plugins/tile_set_editor_plugin.h
+++ b/editor/plugins/tile_set_editor_plugin.h
@@ -29,16 +29,13 @@
#ifndef TILE_SET_EDITOR_PLUGIN_H
#define TILE_SET_EDITOR_PLUGIN_H
-
-
-#include "scene/resources/tile_set.h"
-#include "editor/editor_node.h"
#include "editor/editor_name_dialog.h"
-
+#include "editor/editor_node.h"
+#include "scene/resources/tile_set.h"
class TileSetEditor : public Control {
- GDCLASS( TileSetEditor, Control );
+ GDCLASS(TileSetEditor, Control);
Ref<TileSet> tileset;
@@ -59,43 +56,35 @@ class TileSetEditor : public Control {
int option;
void _menu_cbk(int p_option);
void _menu_confirm();
- void _name_dialog_confirm(const String& name);
+ void _name_dialog_confirm(const String &name);
static void _import_scene(Node *p_scene, Ref<TileSet> p_library, bool p_merge);
-
protected:
static void _bind_methods();
-public:
- void edit(const Ref<TileSet>& p_tileset);
- static Error update_library_file(Node *p_base_scene, Ref<TileSet> ml,bool p_merge=true);
+public:
+ void edit(const Ref<TileSet> &p_tileset);
+ static Error update_library_file(Node *p_base_scene, Ref<TileSet> ml, bool p_merge = true);
TileSetEditor(EditorNode *p_editor);
};
-
-
class TileSetEditorPlugin : public EditorPlugin {
- GDCLASS( TileSetEditorPlugin, EditorPlugin );
+ GDCLASS(TileSetEditorPlugin, EditorPlugin);
TileSetEditor *tileset_editor;
EditorNode *editor;
public:
-
virtual String get_name() const { return "TileSet"; }
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);
-
-
TileSetEditorPlugin(EditorNode *p_node);
-
};
-
#endif // TILE_SET_EDITOR_PLUGIN_H
diff --git a/editor/progress_dialog.cpp b/editor/progress_dialog.cpp
index 76626c4556..55f220ba9a 100644
--- a/editor/progress_dialog.cpp
+++ b/editor/progress_dialog.cpp
@@ -28,201 +28,184 @@
/*************************************************************************/
#include "progress_dialog.h"
+#include "editor_scale.h"
#include "main/main.h"
#include "message_queue.h"
#include "os/os.h"
-#include "editor_scale.h"
-void BackgroundProgress::_add_task(const String& p_task,const String& p_label, int p_steps) {
+void BackgroundProgress::_add_task(const String &p_task, const String &p_label, int p_steps) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(tasks.has(p_task));
Task t;
- t.hb = memnew( HBoxContainer );
- Label *l=memnew( Label );
- l->set_text(p_label+" ");
+ t.hb = memnew(HBoxContainer);
+ Label *l = memnew(Label);
+ l->set_text(p_label + " ");
t.hb->add_child(l);
- t.progress = memnew( ProgressBar );
+ t.progress = memnew(ProgressBar);
t.progress->set_max(p_steps);
t.progress->set_value(p_steps);
- Control *ec = memnew( Control );
+ Control *ec = memnew(Control);
ec->set_h_size_flags(SIZE_EXPAND_FILL);
ec->set_v_size_flags(SIZE_EXPAND_FILL);
t.progress->set_area_as_parent_rect();
ec->add_child(t.progress);
- ec->set_custom_minimum_size(Size2(80,5)*EDSCALE);
+ ec->set_custom_minimum_size(Size2(80, 5) * EDSCALE);
t.hb->add_child(ec);
add_child(t.hb);
- tasks[p_task]=t;
-
+ tasks[p_task] = t;
}
void BackgroundProgress::_update() {
_THREAD_SAFE_METHOD_
- for (Map<String,int>::Element *E=updates.front();E;E=E->next()) {
+ for (Map<String, int>::Element *E = updates.front(); E; E = E->next()) {
if (tasks.has(E->key())) {
- _task_step(E->key(),E->get());
+ _task_step(E->key(), E->get());
}
}
updates.clear();
-
-
-
}
-
-void BackgroundProgress::_task_step(const String& p_task, int p_step){
+void BackgroundProgress::_task_step(const String &p_task, int p_step) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(!tasks.has(p_task));
- Task &t=tasks[p_task];
- if (p_step<0)
- t.progress->set_value(t.progress->get_value()+1);
+ Task &t = tasks[p_task];
+ if (p_step < 0)
+ t.progress->set_value(t.progress->get_value() + 1);
else
t.progress->set_value(p_step);
-
}
-void BackgroundProgress::_end_task(const String& p_task){
+void BackgroundProgress::_end_task(const String &p_task) {
_THREAD_SAFE_METHOD_
ERR_FAIL_COND(!tasks.has(p_task));
- Task &t=tasks[p_task];
+ Task &t = tasks[p_task];
memdelete(t.hb);
tasks.erase(p_task);
}
-void BackgroundProgress::_bind_methods(){
-
- ClassDB::bind_method("_add_task",&BackgroundProgress::_add_task);
- ClassDB::bind_method("_task_step",&BackgroundProgress::_task_step);
- ClassDB::bind_method("_end_task",&BackgroundProgress::_end_task);
- ClassDB::bind_method("_update",&BackgroundProgress::_update);
+void BackgroundProgress::_bind_methods() {
+ ClassDB::bind_method("_add_task", &BackgroundProgress::_add_task);
+ ClassDB::bind_method("_task_step", &BackgroundProgress::_task_step);
+ ClassDB::bind_method("_end_task", &BackgroundProgress::_end_task);
+ ClassDB::bind_method("_update", &BackgroundProgress::_update);
}
-void BackgroundProgress::add_task(const String& p_task,const String& p_label, int p_steps){
+void BackgroundProgress::add_task(const String &p_task, const String &p_label, int p_steps) {
- MessageQueue::get_singleton()->push_call(this,"_add_task",p_task,p_label,p_steps);
+ MessageQueue::get_singleton()->push_call(this, "_add_task", p_task, p_label, p_steps);
}
-void BackgroundProgress::task_step(const String& p_task, int p_step){
+void BackgroundProgress::task_step(const String &p_task, int p_step) {
//this code is weird, but it prevents deadlock.
bool no_updates;
{
_THREAD_SAFE_METHOD_
- no_updates=updates.empty();
+ no_updates = updates.empty();
}
if (no_updates)
- MessageQueue::get_singleton()->push_call(this,"_update");
+ MessageQueue::get_singleton()->push_call(this, "_update");
{
_THREAD_SAFE_METHOD_
- updates[p_task]=p_step;
+ updates[p_task] = p_step;
}
-
}
-void BackgroundProgress::end_task(const String& p_task){
-
- MessageQueue::get_singleton()->push_call(this,"_end_task",p_task);
+void BackgroundProgress::end_task(const String &p_task) {
+ MessageQueue::get_singleton()->push_call(this, "_end_task", p_task);
}
-
////////////////////////////////////////////////
-
-ProgressDialog *ProgressDialog::singleton=NULL;
+ProgressDialog *ProgressDialog::singleton = NULL;
void ProgressDialog::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- draw_style_box(style,Rect2(Point2(),get_size()));
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ draw_style_box(style, Rect2(Point2(), get_size()));
} break;
}
}
-
void ProgressDialog::_popup() {
Size2 ms = main->get_combined_minimum_size();
- ms.width = MAX(500*EDSCALE,ms.width);
+ ms.width = MAX(500 * EDSCALE, ms.width);
-
- Ref<StyleBox> style = get_stylebox("panel","PopupMenu");
- ms+=style->get_minimum_size();
- for(int i=0;i<4;i++) {
- main->set_margin(Margin(i),style->get_margin(Margin(i)));
+ Ref<StyleBox> style = get_stylebox("panel", "PopupMenu");
+ ms += style->get_minimum_size();
+ for (int i = 0; i < 4; i++) {
+ main->set_margin(Margin(i), style->get_margin(Margin(i)));
}
popup_centered(ms);
-
}
-void ProgressDialog::add_task(const String& p_task,const String& p_label,int p_steps) {
+void ProgressDialog::add_task(const String &p_task, const String &p_label, int p_steps) {
ERR_FAIL_COND(tasks.has(p_task));
Task t;
- t.vb = memnew( VBoxContainer );
- VBoxContainer *vb2 = memnew( VBoxContainer );
- t.vb->add_margin_child(p_label,vb2);
- t.progress = memnew( ProgressBar );
+ t.vb = memnew(VBoxContainer);
+ VBoxContainer *vb2 = memnew(VBoxContainer);
+ t.vb->add_margin_child(p_label, vb2);
+ t.progress = memnew(ProgressBar);
t.progress->set_max(p_steps);
t.progress->set_value(p_steps);
vb2->add_child(t.progress);
- t.state=memnew( Label );
+ t.state = memnew(Label);
t.state->set_clip_text(true);
vb2->add_child(t.state);
main->add_child(t.vb);
- tasks[p_task]=t;
+ tasks[p_task] = t;
_popup();
-
}
-void ProgressDialog::task_step(const String& p_task, const String& p_state, int p_step,bool p_force_redraw){
+void ProgressDialog::task_step(const String &p_task, const String &p_state, int p_step, bool p_force_redraw) {
ERR_FAIL_COND(!tasks.has(p_task));
if (!p_force_redraw) {
uint64_t tus = OS::get_singleton()->get_ticks_usec();
- if (tus-last_progress_tick < 50000) //50ms
+ if (tus - last_progress_tick < 50000) //50ms
return;
}
- Task &t=tasks[p_task];
- if (p_step<0)
- t.progress->set_value(t.progress->get_value()+1);
+ Task &t = tasks[p_task];
+ if (p_step < 0)
+ t.progress->set_value(t.progress->get_value() + 1);
else
t.progress->set_value(p_step);
t.state->set_text(p_state);
- last_progress_tick=OS::get_singleton()->get_ticks_usec();
+ last_progress_tick = OS::get_singleton()->get_ticks_usec();
Main::iteration(); // this will not work on a lot of platforms, so it's only meant for the editor
-
}
-
-void ProgressDialog::end_task(const String& p_task){
+void ProgressDialog::end_task(const String &p_task) {
ERR_FAIL_COND(!tasks.has(p_task));
- Task &t=tasks[p_task];
+ Task &t = tasks[p_task];
memdelete(t.vb);
tasks.erase(p_task);
@@ -233,14 +216,12 @@ void ProgressDialog::end_task(const String& p_task){
_popup();
}
-
-
ProgressDialog::ProgressDialog() {
- main = memnew( VBoxContainer );
+ main = memnew(VBoxContainer);
add_child(main);
main->set_area_as_parent_rect();
set_exclusive(true);
- last_progress_tick=0;
- singleton=this;
+ last_progress_tick = 0;
+ singleton = this;
}
diff --git a/editor/progress_dialog.h b/editor/progress_dialog.h
index 60acf825a9..346d6a58b3 100644
--- a/editor/progress_dialog.h
+++ b/editor/progress_dialog.h
@@ -29,15 +29,14 @@
#ifndef PROGRESS_DIALOG_H
#define PROGRESS_DIALOG_H
-#include "scene/gui/popup.h"
#include "scene/gui/box_container.h"
-#include "scene/gui/progress_bar.h"
#include "scene/gui/label.h"
-
+#include "scene/gui/popup.h"
+#include "scene/gui/progress_bar.h"
class BackgroundProgress : public HBoxContainer {
- GDCLASS(BackgroundProgress,HBoxContainer);
+ GDCLASS(BackgroundProgress, HBoxContainer);
_THREAD_SAFE_CLASS_
@@ -45,59 +44,53 @@ class BackgroundProgress : public HBoxContainer {
HBoxContainer *hb;
ProgressBar *progress;
-
};
- Map<String,Task> tasks;
- Map<String,int> updates;
+ Map<String, Task> tasks;
+ Map<String, int> updates;
void _update();
protected:
-
- void _add_task(const String& p_task,const String& p_label, int p_steps);
- void _task_step(const String& p_task, int p_step=-1);
- void _end_task(const String& p_task);
+ void _add_task(const String &p_task, const String &p_label, int p_steps);
+ void _task_step(const String &p_task, int p_step = -1);
+ void _end_task(const String &p_task);
static void _bind_methods();
public:
- void add_task(const String& p_task,const String& p_label, int p_steps);
- void task_step(const String& p_task, int p_step=-1);
- void end_task(const String& p_task);
+ void add_task(const String &p_task, const String &p_label, int p_steps);
+ void task_step(const String &p_task, int p_step = -1);
+ void end_task(const String &p_task);
BackgroundProgress() {}
};
-
-
class ProgressDialog : public Popup {
- GDCLASS( ProgressDialog, Popup );
+ GDCLASS(ProgressDialog, Popup);
struct Task {
String task;
VBoxContainer *vb;
ProgressBar *progress;
Label *state;
-
};
- Map<String,Task> tasks;
+ Map<String, Task> tasks;
VBoxContainer *main;
uint64_t last_progress_tick;
static ProgressDialog *singleton;
void _popup();
-protected:
+protected:
void _notification(int p_what);
-public:
+public:
static ProgressDialog *get_singleton() { return singleton; }
- void add_task(const String& p_task,const String& p_label, int p_steps);
- void task_step(const String& p_task, const String& p_state, int p_step=-1, bool p_force_redraw=true);
- void end_task(const String& p_task);
-
+ void add_task(const String &p_task, const String &p_label, int p_steps);
+ void task_step(const String &p_task, const String &p_state, int p_step = -1, bool p_force_redraw = true);
+ void end_task(const String &p_task);
ProgressDialog();
};
diff --git a/editor/project_export.cpp b/editor/project_export.cpp
index fc6d8793d8..78327a5d66 100644
--- a/editor/project_export.cpp
+++ b/editor/project_export.cpp
@@ -27,29 +27,29 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "project_export.h"
-#include "os/dir_access.h"
-#include "os/file_access.h"
+#include "compressed_translation.h"
+#include "editor_data.h"
+#include "editor_node.h"
+#include "editor_settings.h"
#include "global_config.h"
+#include "io/image_loader.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
+#include "io_plugins/editor_texture_import_plugin.h"
+#include "os/dir_access.h"
+#include "os/file_access.h"
#include "os/os.h"
#include "scene/gui/box_container.h"
-#include "scene/gui/tab_container.h"
-#include "scene/gui/scroll_container.h"
#include "scene/gui/margin_container.h"
-#include "editor_data.h"
-#include "io/image_loader.h"
-#include "compressed_translation.h"
-#include "editor_node.h"
-#include "io_plugins/editor_texture_import_plugin.h"
-#include "editor_settings.h"
+#include "scene/gui/scroll_container.h"
+#include "scene/gui/tab_container.h"
void ProjectExportDialog::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_READY: {
- delete_preset->set_icon(get_icon("Del","EditorIcons"));
- connect("confirmed",this,"_export_pck_zip");
+ delete_preset->set_icon(get_icon("Del", "EditorIcons"));
+ connect("confirmed", this, "_export_pck_zip");
} break;
case NOTIFICATION_POPUP_HIDE: {
EditorSettings::get_singleton()->set("interface/dialogs/export_bounds", get_rect());
@@ -57,16 +57,14 @@ void ProjectExportDialog::_notification(int p_what) {
}
}
-
void ProjectExportDialog::popup_export() {
add_preset->get_popup()->clear();
- for(int i=0;i<EditorExport::get_singleton()->get_export_platform_count();i++) {
+ for (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) {
Ref<EditorExportPlatform> plat = EditorExport::get_singleton()->get_export_platform(i);
- add_preset->get_popup()->add_icon_item(plat->get_logo(),plat->get_name());
-
+ add_preset->get_popup()->add_icon_item(plat->get_logo(), plat->get_name());
}
_update_presets();
@@ -85,30 +83,28 @@ void ProjectExportDialog::_add_preset(int p_platform) {
ERR_FAIL_COND(!preset.is_valid());
String name = EditorExport::get_singleton()->get_export_platform(p_platform)->get_name();
- bool make_runnable=true;
- int attempt=1;
- while(true) {
+ bool make_runnable = true;
+ int attempt = 1;
+ while (true) {
- bool valid=true;
+ bool valid = true;
- for(int i=0;i<EditorExport::get_singleton()->get_export_preset_count();i++) {
+ for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
Ref<EditorExportPreset> p = EditorExport::get_singleton()->get_export_preset(i);
- if (p->get_platform()==preset->get_platform() && p->is_runnable()) {
- make_runnable=false;
+ if (p->get_platform() == preset->get_platform() && p->is_runnable()) {
+ make_runnable = false;
}
- if (p->get_name()==name) {
- valid=false;
+ if (p->get_name() == name) {
+ valid = false;
break;
}
-
}
if (valid)
break;
attempt++;
- name = EditorExport::get_singleton()->get_export_platform(p_platform)->get_name()+" "+itos(attempt);
-
+ name = EditorExport::get_singleton()->get_export_platform(p_platform)->get_name() + " " + itos(attempt);
}
preset->set_name(name);
@@ -116,45 +112,42 @@ void ProjectExportDialog::_add_preset(int p_platform) {
preset->set_runnable(make_runnable);
EditorExport::get_singleton()->add_export_preset(preset);
_update_presets();
- _edit_preset(EditorExport::get_singleton()->get_export_preset_count()-1);
-
+ _edit_preset(EditorExport::get_singleton()->get_export_preset_count() - 1);
}
-
void ProjectExportDialog::_update_presets() {
- updating=true;
+ updating = true;
Ref<EditorExportPreset> current;
- if (presets->get_current()>=0 && presets->get_current()<presets->get_item_count())
+ if (presets->get_current() >= 0 && presets->get_current() < presets->get_item_count())
current = EditorExport::get_singleton()->get_export_preset(presets->get_current());
- int current_idx=-1;
+ int current_idx = -1;
presets->clear();
- for(int i=0;i<EditorExport::get_singleton()->get_export_preset_count();i++) {
+ for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
Ref<EditorExportPreset> preset = EditorExport::get_singleton()->get_export_preset(i);
- if (preset==current) {
- current_idx=i;
+ if (preset == current) {
+ current_idx = i;
}
String name = preset->get_name();
if (preset->is_runnable())
- name+=" ("+TTR("Runnable")+")";
- presets->add_item(name,preset->get_platform()->get_logo());
+ name += " (" + TTR("Runnable") + ")";
+ presets->add_item(name, preset->get_platform()->get_logo());
}
- if (current_idx!=-1) {
+ if (current_idx != -1) {
presets->select(current_idx);
//_edit_preset(current_idx);
}
- updating=false;
-
+ updating = false;
}
void ProjectExportDialog::_edit_preset(int p_index) {
- if (p_index<0 || p_index>=presets->get_item_count()) {
+ if (p_index < 0 || p_index >= presets->get_item_count()) {
name->set_text("");
name->set_editable(false);
runnable->set_disabled(true);
@@ -165,12 +158,10 @@ void ProjectExportDialog::_edit_preset(int p_index) {
return;
}
-
Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(p_index);
ERR_FAIL_COND(current.is_null());
-
- updating=true;
+ updating = true;
presets->select(p_index);
sections->show();
@@ -186,53 +177,50 @@ void ProjectExportDialog::_edit_preset(int p_index) {
include_filters->set_text(current->get_include_filter());
exclude_filters->set_text(current->get_exclude_filter());
-
patches->clear();
TreeItem *patch_root = patches->create_item();
Vector<String> patchlist = current->get_patches();
- for(int i=0;i<patchlist.size();i++) {
+ for (int i = 0; i < patchlist.size(); i++) {
TreeItem *patch = patches->create_item(patch_root);
- patch->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
+ patch->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
String file = patchlist[i].get_file();
- patch->set_editable(0,true);
- patch->set_text(0,file.get_file().replace("*",""));
+ patch->set_editable(0, true);
+ patch->set_text(0, file.get_file().replace("*", ""));
if (file.ends_with("*"))
- patch->set_checked(0,true);
- patch->set_tooltip(0,patchlist[i]);
- patch->set_metadata(0,i);
- patch->add_button(0,get_icon("Del","EditorIcons"),0);
- patch->add_button(0,get_icon("folder","FileDialog"),1);
+ patch->set_checked(0, true);
+ patch->set_tooltip(0, patchlist[i]);
+ patch->set_metadata(0, i);
+ patch->add_button(0, get_icon("Del", "EditorIcons"), 0);
+ patch->add_button(0, get_icon("folder", "FileDialog"), 1);
}
TreeItem *patch_add = patches->create_item(patch_root);
- patch_add->set_metadata(0,patchlist.size());
- if (patchlist.size()==0)
- patch_add->set_text(0,"Add initial export..");
+ patch_add->set_metadata(0, patchlist.size());
+ if (patchlist.size() == 0)
+ patch_add->set_text(0, "Add initial export..");
else
- patch_add->set_text(0,"Add previous patches..");
+ patch_add->set_text(0, "Add previous patches..");
- patch_add->add_button(0,get_icon("folder","FileDialog"),1);
+ patch_add->add_button(0, get_icon("folder", "FileDialog"), 1);
_fill_resource_tree();
- updating=false;
-
+ updating = false;
}
-void ProjectExportDialog::_patch_button_pressed(Object* p_item,int p_column,int p_id) {
-
+void ProjectExportDialog::_patch_button_pressed(Object *p_item, int p_column, int p_id) {
- TreeItem *ti = (TreeItem*)p_item;
+ TreeItem *ti = (TreeItem *)p_item;
- patch_index=ti->get_metadata(0);
+ patch_index = ti->get_metadata(0);
Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(presets->get_current());
ERR_FAIL_COND(current.is_null());
- if (p_id==0) {
+ if (p_id == 0) {
Vector<String> patches = current->get_patches();
- ERR_FAIL_INDEX(patch_index,patches.size());
- patch_erase->set_text(vformat(TTR("Delete patch '"+patches[patch_index].get_file()+"' from list?")));
+ ERR_FAIL_INDEX(patch_index, patches.size());
+ patch_erase->set_text(vformat(TTR("Delete patch '" + patches[patch_index].get_file() + "' from list?")));
patch_erase->popup_centered_minsize();
} else {
patch_dialog->popup_centered_ratio();
@@ -251,38 +239,33 @@ void ProjectExportDialog::_patch_edited() {
Vector<String> patches = current->get_patches();
- ERR_FAIL_INDEX(index,patches.size());
+ ERR_FAIL_INDEX(index, patches.size());
- String patch = patches[index].replace("*","");
+ String patch = patches[index].replace("*", "");
if (item->is_checked(0)) {
- patch+="*";
+ patch += "*";
}
- current->set_patch(index,patch);
-
-
-
+ current->set_patch(index, patch);
}
-void ProjectExportDialog::_patch_selected(const String& p_path) {
+void ProjectExportDialog::_patch_selected(const String &p_path) {
Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(presets->get_current());
ERR_FAIL_COND(current.is_null());
Vector<String> patches = current->get_patches();
- if (patch_index >=patches.size()) {
+ if (patch_index >= patches.size()) {
- current->add_patch(GlobalConfig::get_singleton()->get_resource_path().path_to(p_path)+"*");
+ current->add_patch(GlobalConfig::get_singleton()->get_resource_path().path_to(p_path) + "*");
} else {
String enabled = patches[patch_index].ends_with("*") ? String("*") : String();
- current->set_patch(patch_index,GlobalConfig::get_singleton()->get_resource_path().path_to(p_path)+enabled);
-
+ current->set_patch(patch_index, GlobalConfig::get_singleton()->get_resource_path().path_to(p_path) + enabled);
}
_edit_preset(presets->get_current());
-
}
void ProjectExportDialog::_patch_deleted() {
@@ -291,12 +274,11 @@ void ProjectExportDialog::_patch_deleted() {
ERR_FAIL_COND(current.is_null());
Vector<String> patches = current->get_patches();
- if (patch_index <patches.size()) {
+ if (patch_index < patches.size()) {
current->remove_patch(patch_index);
_edit_preset(presets->get_current());
}
-
}
void ProjectExportDialog::_runnable_pressed() {
@@ -309,10 +291,10 @@ void ProjectExportDialog::_runnable_pressed() {
if (runnable->is_pressed()) {
- for(int i=0;i<EditorExport::get_singleton()->get_export_preset_count();i++) {
+ for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {
Ref<EditorExportPreset> p = EditorExport::get_singleton()->get_export_preset(i);
- if (p->get_platform()==current->get_platform()) {
- p->set_runnable(current==p);
+ if (p->get_platform() == current->get_platform()) {
+ p->set_runnable(current == p);
}
}
} else {
@@ -323,7 +305,7 @@ void ProjectExportDialog::_runnable_pressed() {
_update_presets();
}
-void ProjectExportDialog::_name_changed(const String& p_string) {
+void ProjectExportDialog::_name_changed(const String &p_string) {
if (updating)
return;
@@ -333,8 +315,6 @@ void ProjectExportDialog::_name_changed(const String& p_string) {
current->set_name(p_string);
_update_presets();
-
-
}
void ProjectExportDialog::_delete_preset() {
@@ -343,81 +323,76 @@ void ProjectExportDialog::_delete_preset() {
if (current.is_null())
return;
- delete_confirm->set_text(vformat(TTR("Delete preset '%s'?"),current->get_name()));
+ delete_confirm->set_text(vformat(TTR("Delete preset '%s'?"), current->get_name()));
delete_confirm->popup_centered_minsize();
-
}
void ProjectExportDialog::_delete_preset_confirm() {
int idx = presets->get_current();
- parameters->edit(NULL);//to avoid crash
+ parameters->edit(NULL); //to avoid crash
EditorExport::get_singleton()->remove_export_preset(idx);
_update_presets();
_edit_preset(-1);
}
+Variant ProjectExportDialog::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
-Variant ProjectExportDialog::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+ if (p_from == presets) {
+ int pos = presets->get_item_at_pos(p_point, true);
- if (p_from==presets) {
- int pos = presets->get_item_at_pos(p_point,true);
-
- if (pos>=0) {
+ if (pos >= 0) {
Dictionary d;
- d["type"]="export_preset";
- d["preset"]=pos;
+ d["type"] = "export_preset";
+ d["preset"] = pos;
- HBoxContainer *drag = memnew( HBoxContainer);
+ HBoxContainer *drag = memnew(HBoxContainer);
TextureRect *tr = memnew(TextureRect);
tr->set_texture(presets->get_item_icon(pos));
drag->add_child(tr);
- Label *label = memnew( Label );
+ Label *label = memnew(Label);
label->set_text(presets->get_item_text(pos));
drag->add_child(label);
set_drag_preview(drag);
return d;
-
}
- } else if (p_from==patches) {
+ } else if (p_from == patches) {
TreeItem *item = patches->get_item_at_pos(p_point);
- if (item && item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK) {
+ if (item && item->get_cell_mode(0) == TreeItem::CELL_MODE_CHECK) {
int metadata = item->get_metadata(0);
Dictionary d;
- d["type"]="export_patch";
- d["patch"]=metadata;
+ d["type"] = "export_patch";
+ d["patch"] = metadata;
- Label *label = memnew( Label );
+ Label *label = memnew(Label);
label->set_text(item->get_text(0));
set_drag_preview(label);
return d;
}
-
}
return Variant();
}
-bool ProjectExportDialog::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool ProjectExportDialog::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
- if (p_from==presets) {
+ if (p_from == presets) {
Dictionary d = p_data;
- if (!d.has("type") || String(d["type"])!="export_preset")
+ if (!d.has("type") || String(d["type"]) != "export_preset")
return false;
-
- if (presets->get_item_at_pos(p_point,true)<0 && !presets->is_pos_at_end_of_items(p_point))
+ if (presets->get_item_at_pos(p_point, true) < 0 && !presets->is_pos_at_end_of_items(p_point))
return false;
- } else if (p_from==patches) {
+ } else if (p_from == patches) {
Dictionary d = p_data;
- if (!d.has("type") || String(d["type"])!="export_patch")
+ if (!d.has("type") || String(d["type"]) != "export_patch")
return false;
patches->set_drop_mode_flags(Tree::DROP_MODE_ON_ITEM);
@@ -428,47 +403,45 @@ bool ProjectExportDialog::can_drop_data_fw(const Point2& p_point,const Variant&
return false;
}
-
}
return true;
}
-void ProjectExportDialog::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void ProjectExportDialog::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (p_from==presets) {
- Dictionary d=p_data;
+ if (p_from == presets) {
+ Dictionary d = p_data;
int from_pos = d["preset"];
- int to_pos=-1;
+ int to_pos = -1;
- if (presets->get_item_at_pos(p_point,true)>=0) {
- to_pos = presets->get_item_at_pos(p_point,true);
+ if (presets->get_item_at_pos(p_point, true) >= 0) {
+ to_pos = presets->get_item_at_pos(p_point, true);
}
- if (to_pos==-1 && !presets->is_pos_at_end_of_items(p_point))
+ if (to_pos == -1 && !presets->is_pos_at_end_of_items(p_point))
return;
- if (to_pos==from_pos)
+ if (to_pos == from_pos)
return;
- else if (to_pos>from_pos) {
+ else if (to_pos > from_pos) {
to_pos--;
}
-
Ref<EditorExportPreset> preset = EditorExport::get_singleton()->get_export_preset(from_pos);
EditorExport::get_singleton()->remove_export_preset(from_pos);
- EditorExport::get_singleton()->add_export_preset(preset,to_pos);
+ EditorExport::get_singleton()->add_export_preset(preset, to_pos);
_update_presets();
- if (to_pos>=0)
+ if (to_pos >= 0)
_edit_preset(to_pos);
else
- _edit_preset(presets->get_item_count()-1);
- } else if (p_from==patches) {
+ _edit_preset(presets->get_item_count() - 1);
+ } else if (p_from == patches) {
Dictionary d = p_data;
- if (!d.has("type") || String(d["type"])!="export_patch")
+ if (!d.has("type") || String(d["type"]) != "export_patch")
return;
int from_pos = d["patch"];
@@ -477,23 +450,21 @@ void ProjectExportDialog::drop_data_fw(const Point2& p_point,const Variant& p_da
if (!item)
return;
- int to_pos = item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK ? int(item->get_metadata(0)) : -1;
+ int to_pos = item->get_cell_mode(0) == TreeItem::CELL_MODE_CHECK ? int(item->get_metadata(0)) : -1;
- if (to_pos==from_pos)
+ if (to_pos == from_pos)
return;
- else if (to_pos>from_pos) {
+ else if (to_pos > from_pos) {
to_pos--;
}
Ref<EditorExportPreset> preset = EditorExport::get_singleton()->get_export_preset(presets->get_current());
String patch = preset->get_patch(from_pos);
preset->remove_patch(from_pos);
- preset->add_patch(patch,to_pos);
+ preset->add_patch(patch, to_pos);
_edit_preset(presets->get_current());
-
}
-
}
void ProjectExportDialog::_export_type_changed(int p_which) {
@@ -506,13 +477,12 @@ void ProjectExportDialog::_export_type_changed(int p_which) {
return;
current->set_export_filter(EditorExportPreset::ExportFilter(p_which));
- updating=true;
+ updating = true;
_fill_resource_tree();
- updating=false;
-
+ updating = false;
}
-void ProjectExportDialog::_filter_changed(const String& p_filter) {
+void ProjectExportDialog::_filter_changed(const String &p_filter) {
if (updating)
return;
@@ -523,9 +493,6 @@ void ProjectExportDialog::_filter_changed(const String& p_filter) {
current->set_include_filter(include_filters->get_text());
current->set_exclude_filter(exclude_filters->get_text());
-
-
-
}
void ProjectExportDialog::_fill_resource_tree() {
@@ -540,7 +507,7 @@ void ProjectExportDialog::_fill_resource_tree() {
EditorExportPreset::ExportFilter f = current->get_export_filter();
- if (f==EditorExportPreset::EXPORT_ALL_RESOURCES) {
+ if (f == EditorExportPreset::EXPORT_ALL_RESOURCES) {
return;
}
@@ -549,56 +516,50 @@ void ProjectExportDialog::_fill_resource_tree() {
TreeItem *root = include_files->create_item();
-
- _fill_tree(EditorFileSystem::get_singleton()->get_filesystem(),root,current,f==EditorExportPreset::EXPORT_SELECTED_SCENES);
-
+ _fill_tree(EditorFileSystem::get_singleton()->get_filesystem(), root, current, f == EditorExportPreset::EXPORT_SELECTED_SCENES);
}
+bool ProjectExportDialog::_fill_tree(EditorFileSystemDirectory *p_dir, TreeItem *p_item, Ref<EditorExportPreset> &current, bool p_only_scenes) {
-bool ProjectExportDialog::_fill_tree(EditorFileSystemDirectory *p_dir,TreeItem *p_item,Ref<EditorExportPreset> &current,bool p_only_scenes) {
-
- p_item->set_icon(0,get_icon("folder","FileDialog"));
- p_item->set_text(0,p_dir->get_name()+"/");
+ p_item->set_icon(0, get_icon("folder", "FileDialog"));
+ p_item->set_text(0, p_dir->get_name() + "/");
- bool used=false;
- for(int i=0;i<p_dir->get_subdir_count();i++) {
+ bool used = false;
+ for (int i = 0; i < p_dir->get_subdir_count(); i++) {
TreeItem *subdir = include_files->create_item(p_item);
- if (_fill_tree(p_dir->get_subdir(i),subdir,current,p_only_scenes)==false) {
+ if (_fill_tree(p_dir->get_subdir(i), subdir, current, p_only_scenes) == false) {
memdelete(subdir);
} else {
- used=true;
+ used = true;
}
}
-
-
- for(int i=0;i<p_dir->get_file_count();i++) {
+ for (int i = 0; i < p_dir->get_file_count(); i++) {
String type = p_dir->get_file_type(i);
- if (p_only_scenes && type!="PackedScene")
+ if (p_only_scenes && type != "PackedScene")
continue;
TreeItem *file = include_files->create_item(p_item);
- file->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- file->set_text(0,p_dir->get_file(i));
+ file->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ file->set_text(0, p_dir->get_file(i));
Ref<Texture> tex;
- if (has_icon(type,editor_icons)) {
- tex = get_icon(type,editor_icons);
+ if (has_icon(type, editor_icons)) {
+ tex = get_icon(type, editor_icons);
} else {
- tex = get_icon("Object",editor_icons);
+ tex = get_icon("Object", editor_icons);
}
String path = p_dir->get_file_path(i);
- file->set_icon(0,tex);
- file->set_editable(0,true);
- file->set_checked(0,current->has_export_file(path));
- file->set_metadata(0,path);
-
- used=true;
+ file->set_icon(0, tex);
+ file->set_editable(0, true);
+ file->set_checked(0, current->has_export_file(path));
+ file->set_metadata(0, path);
+ used = true;
}
return used;
@@ -624,172 +585,166 @@ void ProjectExportDialog::_tree_changed() {
current->add_export_file(path);
} else {
current->remove_export_file(path);
-
}
}
-
void ProjectExportDialog::_export_pck_zip() {
export_pck_zip->popup_centered_ratio();
}
-void ProjectExportDialog::_export_pck_zip_selected(const String& p_path) {
+void ProjectExportDialog::_export_pck_zip_selected(const String &p_path) {
Ref<EditorExportPreset> current = EditorExport::get_singleton()->get_export_preset(presets->get_current());
- ERR_FAIL_COND (current.is_null());
+ ERR_FAIL_COND(current.is_null());
Ref<EditorExportPlatform> platform = current->get_platform();
- ERR_FAIL_COND( platform.is_null() );
+ ERR_FAIL_COND(platform.is_null());
if (p_path.ends_with(".zip")) {
- platform->save_zip(current,p_path);
+ platform->save_zip(current, p_path);
} else if (p_path.ends_with(".pck")) {
- platform->save_pack(current,p_path);
+ platform->save_pack(current, p_path);
}
}
-
void ProjectExportDialog::_bind_methods() {
- ClassDB::bind_method("_add_preset",&ProjectExportDialog::_add_preset);
- ClassDB::bind_method("_edit_preset",&ProjectExportDialog::_edit_preset);
- ClassDB::bind_method("_runnable_pressed",&ProjectExportDialog::_runnable_pressed);
- ClassDB::bind_method("_name_changed",&ProjectExportDialog::_name_changed);
- ClassDB::bind_method("_delete_preset",&ProjectExportDialog::_delete_preset);
- ClassDB::bind_method("_delete_preset_confirm",&ProjectExportDialog::_delete_preset_confirm);
- ClassDB::bind_method("get_drag_data_fw",&ProjectExportDialog::get_drag_data_fw);
- ClassDB::bind_method("can_drop_data_fw",&ProjectExportDialog::can_drop_data_fw);
- ClassDB::bind_method("drop_data_fw",&ProjectExportDialog::drop_data_fw);
- ClassDB::bind_method("_export_type_changed",&ProjectExportDialog::_export_type_changed);
- ClassDB::bind_method("_filter_changed",&ProjectExportDialog::_filter_changed);
- ClassDB::bind_method("_tree_changed",&ProjectExportDialog::_tree_changed);
- ClassDB::bind_method("_patch_button_pressed",&ProjectExportDialog::_patch_button_pressed);
- ClassDB::bind_method("_patch_selected",&ProjectExportDialog::_patch_selected);
- ClassDB::bind_method("_patch_deleted",&ProjectExportDialog::_patch_deleted);
- ClassDB::bind_method("_patch_edited",&ProjectExportDialog::_patch_edited);
- ClassDB::bind_method("_export_pck_zip",&ProjectExportDialog::_export_pck_zip);
- ClassDB::bind_method("_export_pck_zip_selected",&ProjectExportDialog::_export_pck_zip_selected);
-
-
+ ClassDB::bind_method("_add_preset", &ProjectExportDialog::_add_preset);
+ ClassDB::bind_method("_edit_preset", &ProjectExportDialog::_edit_preset);
+ ClassDB::bind_method("_runnable_pressed", &ProjectExportDialog::_runnable_pressed);
+ ClassDB::bind_method("_name_changed", &ProjectExportDialog::_name_changed);
+ ClassDB::bind_method("_delete_preset", &ProjectExportDialog::_delete_preset);
+ ClassDB::bind_method("_delete_preset_confirm", &ProjectExportDialog::_delete_preset_confirm);
+ ClassDB::bind_method("get_drag_data_fw", &ProjectExportDialog::get_drag_data_fw);
+ ClassDB::bind_method("can_drop_data_fw", &ProjectExportDialog::can_drop_data_fw);
+ ClassDB::bind_method("drop_data_fw", &ProjectExportDialog::drop_data_fw);
+ ClassDB::bind_method("_export_type_changed", &ProjectExportDialog::_export_type_changed);
+ ClassDB::bind_method("_filter_changed", &ProjectExportDialog::_filter_changed);
+ ClassDB::bind_method("_tree_changed", &ProjectExportDialog::_tree_changed);
+ ClassDB::bind_method("_patch_button_pressed", &ProjectExportDialog::_patch_button_pressed);
+ ClassDB::bind_method("_patch_selected", &ProjectExportDialog::_patch_selected);
+ ClassDB::bind_method("_patch_deleted", &ProjectExportDialog::_patch_deleted);
+ ClassDB::bind_method("_patch_edited", &ProjectExportDialog::_patch_edited);
+ ClassDB::bind_method("_export_pck_zip", &ProjectExportDialog::_export_pck_zip);
+ ClassDB::bind_method("_export_pck_zip_selected", &ProjectExportDialog::_export_pck_zip_selected);
}
ProjectExportDialog::ProjectExportDialog() {
set_title(TTR("Export"));
set_resizable(true);
- HBoxContainer *hbox = memnew( HBoxContainer );
+ HBoxContainer *hbox = memnew(HBoxContainer);
add_child(hbox);
- VBoxContainer *preset_vb = memnew( VBoxContainer );
+ VBoxContainer *preset_vb = memnew(VBoxContainer);
preset_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbox->add_child(preset_vb);
- HBoxContainer *preset_hb = memnew( HBoxContainer );
+ HBoxContainer *preset_hb = memnew(HBoxContainer);
preset_hb->add_child(memnew(Label(TTR("Presets"))));
preset_hb->add_spacer();
preset_vb->add_child(preset_hb);
- add_preset = memnew( MenuButton );
+ add_preset = memnew(MenuButton);
add_preset->set_text(TTR("Add.."));
- add_preset->get_popup()->connect("index_pressed",this,"_add_preset");
+ add_preset->get_popup()->connect("index_pressed", this, "_add_preset");
preset_hb->add_child(add_preset);
- MarginContainer *mc = memnew( MarginContainer );
+ MarginContainer *mc = memnew(MarginContainer);
preset_vb->add_child(mc);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
- presets = memnew( ItemList );
+ presets = memnew(ItemList);
presets->set_drag_forwarding(this);
mc->add_child(presets);
- presets->connect("item_selected",this,"_edit_preset");
- delete_preset = memnew( ToolButton );
+ presets->connect("item_selected", this, "_edit_preset");
+ delete_preset = memnew(ToolButton);
preset_hb->add_child(delete_preset);
- delete_preset->connect("pressed",this,"_delete_preset");
+ delete_preset->connect("pressed", this, "_delete_preset");
- VBoxContainer *settings_vb = memnew( VBoxContainer );
+ VBoxContainer *settings_vb = memnew(VBoxContainer);
settings_vb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbox->add_child(settings_vb);
name = memnew(LineEdit);
- settings_vb->add_margin_child(TTR("Name:"),name);
- name->connect("text_changed",this,"_name_changed");
+ settings_vb->add_margin_child(TTR("Name:"), name);
+ name->connect("text_changed", this, "_name_changed");
runnable = memnew(CheckButton);
runnable->set_text(TTR("Runnable"));
- runnable->connect("pressed",this,"_runnable_pressed");
+ runnable->connect("pressed", this, "_runnable_pressed");
settings_vb->add_child(runnable);
- sections = memnew (TabContainer );
+ sections = memnew(TabContainer);
settings_vb->add_child(sections);
sections->set_v_size_flags(SIZE_EXPAND_FILL);
- parameters = memnew (PropertyEditor );
+ parameters = memnew(PropertyEditor);
sections->add_child(parameters);
parameters->set_name(TTR("Options"));
parameters->hide_top_label();
parameters->set_v_size_flags(SIZE_EXPAND_FILL);
parameters->set_hide_script(true);
- VBoxContainer *resources_vb = memnew( VBoxContainer );
+ VBoxContainer *resources_vb = memnew(VBoxContainer);
sections->add_child(resources_vb);
resources_vb->set_name(TTR("Resources"));
- export_filter = memnew( OptionButton );
+ export_filter = memnew(OptionButton);
export_filter->add_item(TTR("Export all resources in the project"));
export_filter->add_item(TTR("Export selected scenes (and dependencies)"));
export_filter->add_item(TTR("Export selected resources (and dependencies)"));
- resources_vb->add_margin_child(TTR("Export Mode:"),export_filter);
- export_filter->connect("item_selected",this,"_export_type_changed");
+ resources_vb->add_margin_child(TTR("Export Mode:"), export_filter);
+ export_filter->connect("item_selected", this, "_export_type_changed");
- include_label = memnew( Label );
+ include_label = memnew(Label);
include_label->set_text(TTR("Resources to export:"));
resources_vb->add_child(include_label);
- include_margin = memnew( MarginContainer );
+ include_margin = memnew(MarginContainer);
include_margin->set_v_size_flags(SIZE_EXPAND_FILL);
resources_vb->add_child(include_margin);
include_files = memnew(Tree);
include_margin->add_child(include_files);
- include_files->connect("item_edited",this,"_tree_changed");
+ include_files->connect("item_edited", this, "_tree_changed");
- include_filters = memnew( LineEdit );
- resources_vb->add_margin_child(TTR("Filters to export non-resource files (comma separated, e.g: *.json, *.txt)"),include_filters);
- include_filters->connect("text_changed",this,"_filter_changed");
+ include_filters = memnew(LineEdit);
+ resources_vb->add_margin_child(TTR("Filters to export non-resource files (comma separated, e.g: *.json, *.txt)"), include_filters);
+ include_filters->connect("text_changed", this, "_filter_changed");
- exclude_filters = memnew( LineEdit );
- resources_vb->add_margin_child(TTR("Filters to exclude files from project (comma separated, e.g: *.json, *.txt)"),exclude_filters);
- exclude_filters->connect("text_changed",this,"_filter_changed");
+ exclude_filters = memnew(LineEdit);
+ resources_vb->add_margin_child(TTR("Filters to exclude files from project (comma separated, e.g: *.json, *.txt)"), exclude_filters);
+ exclude_filters->connect("text_changed", this, "_filter_changed");
- VBoxContainer *patch_vb = memnew( VBoxContainer );
+ VBoxContainer *patch_vb = memnew(VBoxContainer);
sections->add_child(patch_vb);
patch_vb->set_name(TTR("Patches"));
- patches = memnew( Tree );
+ patches = memnew(Tree);
patch_vb->add_child(patches);
patches->set_v_size_flags(SIZE_EXPAND_FILL);
patches->set_hide_root(true);
- patches->connect("button_pressed",this,"_patch_button_pressed");
- patches->connect("item_edited",this,"_patch_edited");
+ patches->connect("button_pressed", this, "_patch_button_pressed");
+ patches->connect("item_edited", this, "_patch_edited");
patches->set_drag_forwarding(this);
patches->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true);
- HBoxContainer *patches_hb = memnew( HBoxContainer );
+ HBoxContainer *patches_hb = memnew(HBoxContainer);
patch_vb->add_child(patches_hb);
patches_hb->add_spacer();
- patch_export = memnew( Button );
+ patch_export = memnew(Button);
patch_export->set_text(TTR("Make Patch"));
patches_hb->add_child(patch_export);
patches_hb->add_spacer();
- patch_dialog = memnew( FileDialog );
+ patch_dialog = memnew(FileDialog);
patch_dialog->add_filter("*.pck ; Pack File");
patch_dialog->set_mode(FileDialog::MODE_OPEN_FILE);
- patch_dialog->connect("file_selected",this,"_patch_selected");
+ patch_dialog->connect("file_selected", this, "_patch_selected");
add_child(patch_dialog);
- patch_erase = memnew( ConfirmationDialog );
+ patch_erase = memnew(ConfirmationDialog);
patch_erase->get_ok()->set_text(TTR("Delete"));
- patch_erase->connect("confirmed",this,"_patch_deleted");
+ patch_erase->connect("confirmed", this, "_patch_deleted");
add_child(patch_erase);
-
//disable by default
name->set_editable(false);
runnable->set_disabled(true);
@@ -797,32 +752,28 @@ ProjectExportDialog::ProjectExportDialog() {
sections->hide();
parameters->edit(NULL);
- delete_confirm = memnew( ConfirmationDialog );
+ delete_confirm = memnew(ConfirmationDialog);
add_child(delete_confirm);
delete_confirm->get_ok()->set_text(TTR("Delete"));
- delete_confirm->connect("confirmed",this,"_delete_preset_confirm");
+ delete_confirm->connect("confirmed", this, "_delete_preset_confirm");
- updating=false;
+ updating = false;
get_ok()->set_text("Export PCK/Zip");
- export_button = add_button("Export Project",!OS::get_singleton()->get_swap_ok_cancel(),"export");
+ export_button = add_button("Export Project", !OS::get_singleton()->get_swap_ok_cancel(), "export");
- export_pck_zip = memnew( FileDialog );
+ export_pck_zip = memnew(FileDialog);
export_pck_zip->add_filter("*.zip ; ZIP File");
export_pck_zip->add_filter("*.pck ; Godot Game Pack");
export_pck_zip->set_access(FileDialog::ACCESS_FILESYSTEM);
export_pck_zip->set_mode(FileDialog::MODE_SAVE_FILE);
add_child(export_pck_zip);
- export_pck_zip->connect("file_selected",this,"_export_pck_zip_selected");
+ export_pck_zip->connect("file_selected", this, "_export_pck_zip_selected");
set_hide_on_ok(false);
-
-
editor_icons = "EditorIcons";
}
ProjectExportDialog::~ProjectExportDialog() {
-
-
}
diff --git a/editor/project_export.h b/editor/project_export.h
index b58ce2dc9d..dff3ab356f 100644
--- a/editor/project_export.h
+++ b/editor/project_export.h
@@ -29,33 +29,30 @@
#ifndef PROJECT_EXPORT_SETTINGS_H
#define PROJECT_EXPORT_SETTINGS_H
-#include "scene/main/timer.h"
-#include "scene/gui/control.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/label.h"
#include "editor/editor_file_dialog.h"
-#include "scene/gui/button.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/dialogs.h"
-#include "scene/gui/tab_container.h"
#include "os/dir_access.h"
#include "os/thread.h"
+#include "scene/gui/button.h"
+#include "scene/gui/control.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
+#include "scene/gui/label.h"
#include "scene/gui/option_button.h"
+#include "scene/gui/tab_container.h"
+#include "scene/gui/tree.h"
+#include "scene/main/timer.h"
-#include "scene/gui/slider.h"
#include "editor/editor_file_system.h"
-#include "property_editor.h"
#include "editor_export.h"
-
+#include "property_editor.h"
+#include "scene/gui/slider.h"
class EditorNode;
class ProjectExportDialog : public ConfirmationDialog {
- GDCLASS( ProjectExportDialog, ConfirmationDialog );
+ GDCLASS(ProjectExportDialog, ConfirmationDialog);
private:
-
-
TabContainer *sections;
MenuButton *add_preset;
@@ -66,7 +63,6 @@ private:
PropertyEditor *parameters;
CheckButton *runnable;
-
EditorFileDialog *pck_export;
EditorFileDialog *file_export;
@@ -80,7 +76,7 @@ private:
LineEdit *exclude_filters;
Tree *include_files;
- Label* include_label;
+ Label *include_label;
MarginContainer *include_margin;
StringName editor_icons;
@@ -93,11 +89,11 @@ private:
Button *export_button;
- void _patch_selected(const String& p_path);
+ void _patch_selected(const String &p_path);
void _patch_deleted();
void _runnable_pressed();
- void _name_changed(const String& p_string);
+ void _name_changed(const String &p_string);
void _add_preset(int p_platform);
void _edit_preset(int p_index);
void _delete_preset();
@@ -106,37 +102,32 @@ private:
void _update_presets();
void _export_type_changed(int p_which);
- void _filter_changed(const String& p_filter);
+ void _filter_changed(const String &p_filter);
void _fill_resource_tree();
- bool _fill_tree(EditorFileSystemDirectory *p_dir,TreeItem *p_item,Ref<EditorExportPreset> &current,bool p_only_scenes);
+ bool _fill_tree(EditorFileSystemDirectory *p_dir, TreeItem *p_item, Ref<EditorExportPreset> &current, bool p_only_scenes);
void _tree_changed();
- void _patch_button_pressed(Object* p_item,int p_column,int p_id);
+ void _patch_button_pressed(Object *p_item, int p_column, int p_id);
void _patch_edited();
-
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
FileDialog *export_pck_zip;
void _export_pck_zip();
- void _export_pck_zip_selected(const String& p_path);
+ void _export_pck_zip_selected(const String &p_path);
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void popup_export();
ProjectExportDialog();
~ProjectExportDialog();
};
-
-
-
#endif // PROJECT_EXPORT_SETTINGS_H
-
diff --git a/editor/project_manager.cpp b/editor/project_manager.cpp
index 34b2d3e82c..7fa8e9bf84 100644
--- a/editor/project_manager.cpp
+++ b/editor/project_manager.cpp
@@ -28,42 +28,41 @@
/*************************************************************************/
#include "project_manager.h"
-#include "version.h"
-#include "os/os.h"
+#include "editor_initialize_ssl.h"
+#include "editor_scale.h"
+#include "editor_settings.h"
+#include "editor_themes.h"
+#include "io/config_file.h"
+#include "io/resource_saver.h"
+#include "io/stream_peer_ssl.h"
+#include "io/zip_io.h"
#include "os/dir_access.h"
#include "os/file_access.h"
#include "os/keyboard.h"
-#include "editor_settings.h"
-#include "scene/gui/separator.h"
-#include "scene/gui/tool_button.h"
-#include "io/config_file.h"
+#include "os/os.h"
+#include "scene/gui/center_container.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/margin_container.h"
#include "scene/gui/panel_container.h"
-#include "scene/gui/center_container.h"
-#include "io/stream_peer_ssl.h"
+#include "scene/gui/separator.h"
#include "scene/gui/texture_rect.h"
-#include "scene/gui/margin_container.h"
-#include "io/resource_saver.h"
-#include "editor_themes.h"
-#include "editor_initialize_ssl.h"
-#include "editor_scale.h"
-#include "io/zip_io.h"
+#include "scene/gui/tool_button.h"
+#include "version.h"
class NewProjectDialog : public ConfirmationDialog {
- GDCLASS(NewProjectDialog,ConfirmationDialog);
+ GDCLASS(NewProjectDialog, ConfirmationDialog);
public:
-
enum Mode {
MODE_NEW,
MODE_IMPORT,
MODE_INSTALL
};
-private:
+private:
Mode mode;
- Label *pp,*pn;
+ Label *pp, *pn;
Label *error;
LineEdit *project_path;
LineEdit *project_name;
@@ -78,10 +77,10 @@ private:
get_ok()->set_disabled(true);
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
String valid_path;
- if (d->change_dir(project_path->get_text())==OK){
- valid_path=project_path->get_text();
- } else if (d->change_dir(project_path->get_text().strip_edges())==OK) {
- valid_path=project_path->get_text().strip_edges();
+ if (d->change_dir(project_path->get_text()) == OK) {
+ valid_path = project_path->get_text();
+ } else if (d->change_dir(project_path->get_text().strip_edges()) == OK) {
+ valid_path = project_path->get_text().strip_edges();
}
if (valid_path == "") {
@@ -90,7 +89,7 @@ private:
return "";
}
- if (mode!=MODE_IMPORT) {
+ if (mode != MODE_IMPORT) {
if (d->file_exists("godot.cfg")) {
@@ -112,34 +111,33 @@ private:
memdelete(d);
get_ok()->set_disabled(false);
return valid_path;
-
}
- void _path_text_changed(const String& p_path) {
+ void _path_text_changed(const String &p_path) {
- String sp=_test_path();
- if ( sp!="" ) {
+ String sp = _test_path();
+ if (sp != "") {
- sp=sp.replace("\\","/");
- int lidx=sp.find_last("/");
+ sp = sp.replace("\\", "/");
+ int lidx = sp.find_last("/");
- if (lidx!=-1) {
- sp=sp.substr(lidx+1,sp.length());
+ if (lidx != -1) {
+ sp = sp.substr(lidx + 1, sp.length());
}
- if (sp=="" && mode==MODE_IMPORT )
- sp=TTR("Imported Project");
+ if (sp == "" && mode == MODE_IMPORT)
+ sp = TTR("Imported Project");
project_name->set_text(sp);
}
}
- void _file_selected(const String& p_path) {
+ void _file_selected(const String &p_path) {
String p = p_path;
- if (mode==MODE_IMPORT) {
+ if (mode == MODE_IMPORT) {
if (p.ends_with("godot.cfg")) {
- p=p.get_base_dir();
+ p = p.get_base_dir();
}
}
String sp = p.simplify_path();
@@ -148,7 +146,7 @@ private:
get_ok()->call_deferred("grab_focus");
}
- void _path_selected(const String& p_path) {
+ void _path_selected(const String &p_path) {
String p = p_path;
String sp = p.simplify_path();
@@ -159,7 +157,7 @@ private:
void _browse_path() {
- if (mode==MODE_IMPORT) {
+ if (mode == MODE_IMPORT) {
fdialog->set_mode(FileDialog::MODE_OPEN_FILE);
fdialog->clear_filters();
@@ -170,27 +168,24 @@ private:
fdialog->popup_centered_ratio();
}
- void _text_changed(const String& p_text) {
+ void _text_changed(const String &p_text) {
_test_path();
}
void ok_pressed() {
- String dir=_test_path();
- if (dir=="") {
+ String dir = _test_path();
+ if (dir == "") {
error->set_text(TTR("Invalid project path (changed anything?)."));
return;
}
- if (mode==MODE_IMPORT) {
+ if (mode == MODE_IMPORT) {
// nothing to do
} else {
- if (mode==MODE_NEW) {
-
-
+ if (mode == MODE_NEW) {
-
- FileAccess *f = FileAccess::open(dir.plus_file("/godot.cfg"),FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(dir.plus_file("/godot.cfg"), FileAccess::WRITE);
if (!f) {
error->set_text(TTR("Couldn't create godot.cfg in project path."));
} else {
@@ -205,18 +200,17 @@ private:
f->store_line("\n");
f->store_line("[application]");
f->store_line("\n");
- f->store_line("name=\""+project_name->get_text()+"\"");
+ f->store_line("name=\"" + project_name->get_text() + "\"");
f->store_line("icon=\"res://icon.png\"");
memdelete(f);
- ResourceSaver::save(dir.plus_file("/icon.png"),get_icon("DefaultProjectIcon","EditorIcons"));
+ ResourceSaver::save(dir.plus_file("/icon.png"), get_icon("DefaultProjectIcon", "EditorIcons"));
}
- } else if (mode==MODE_INSTALL) {
-
+ } else if (mode == MODE_INSTALL) {
- FileAccess *src_f=NULL;
+ FileAccess *src_f = NULL;
zlib_filefunc_def io = zipio_create_io_from_file(&src_f);
unzFile pkg = unzOpen2(zip_path.utf8().get_data(), &io);
@@ -230,34 +224,33 @@ private:
Vector<String> failed_files;
- int idx=0;
- while(ret==UNZ_OK) {
+ int idx = 0;
+ while (ret == UNZ_OK) {
//get filename
unz_file_info info;
char fname[16384];
- ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);
+ ret = unzGetCurrentFileInfo(pkg, &info, fname, 16384, NULL, 0, NULL, 0);
- String path=fname;
+ String path = fname;
- int depth=1; //stuff from github comes with tag
- bool skip=false;
- while(depth>0) {
+ int depth = 1; //stuff from github comes with tag
+ bool skip = false;
+ while (depth > 0) {
int pp = path.find("/");
- if (pp==-1) {
- skip=true;
+ if (pp == -1) {
+ skip = true;
break;
}
- path=path.substr(pp+1,path.length());
+ path = path.substr(pp + 1, path.length());
depth--;
}
-
- if (skip || path==String()) {
+ if (skip || path == String()) {
//
} else if (path.ends_with("/")) { // a dir
- path=path.substr(0,path.length()-1);
+ path = path.substr(0, path.length() - 1);
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
da->make_dir(dir.plus_file(path));
@@ -270,19 +263,17 @@ private:
//read
unzOpenCurrentFile(pkg);
- unzReadCurrentFile(pkg,data.ptr(),data.size());
+ unzReadCurrentFile(pkg, data.ptr(), data.size());
unzCloseCurrentFile(pkg);
- FileAccess *f=FileAccess::open(dir.plus_file(path),FileAccess::WRITE);
+ FileAccess *f = FileAccess::open(dir.plus_file(path), FileAccess::WRITE);
if (f) {
- f->store_buffer(data.ptr(),data.size());
+ f->store_buffer(data.ptr(), data.size());
memdelete(f);
} else {
failed_files.push_back(path);
}
-
-
}
idx++;
@@ -292,14 +283,14 @@ private:
unzClose(pkg);
if (failed_files.size()) {
- String msg=TTR("The following files failed extraction from package:")+"\n\n";
- for(int i=0;i<failed_files.size();i++) {
+ String msg = TTR("The following files failed extraction from package:") + "\n\n";
+ for (int i = 0; i < failed_files.size(); i++) {
- if (i>15) {
- msg+="\nAnd "+itos(failed_files.size()-i)+" more files.";
+ if (i > 15) {
+ msg += "\nAnd " + itos(failed_files.size() - i) + " more files.";
break;
}
- msg+=failed_files[i]+"\n";
+ msg += failed_files[i] + "\n";
}
dialog_error->set_text(msg);
@@ -309,58 +300,50 @@ private:
dialog_error->set_text(TTR("Package Installed Successfully!"));
dialog_error->popup_centered_minsize();
}
-
}
-
}
- dir=dir.replace("\\","/");
+ dir = dir.replace("\\", "/");
if (dir.ends_with("/"))
- dir=dir.substr(0,dir.length()-1);
- String proj=dir.replace("/","::");
- EditorSettings::get_singleton()->set("projects/"+proj,dir);
+ dir = dir.substr(0, dir.length() - 1);
+ String proj = dir.replace("/", "::");
+ EditorSettings::get_singleton()->set("projects/" + proj, dir);
EditorSettings::get_singleton()->save();
-
-
hide();
emit_signal("project_created", dir);
-
}
protected:
-
static void _bind_methods() {
- ClassDB::bind_method("_browse_path",&NewProjectDialog::_browse_path);
- ClassDB::bind_method("_text_changed",&NewProjectDialog::_text_changed);
- ClassDB::bind_method("_path_text_changed",&NewProjectDialog::_path_text_changed);
- ClassDB::bind_method("_path_selected",&NewProjectDialog::_path_selected);
- ClassDB::bind_method("_file_selected",&NewProjectDialog::_file_selected);
- ADD_SIGNAL( MethodInfo("project_created") );
+ ClassDB::bind_method("_browse_path", &NewProjectDialog::_browse_path);
+ ClassDB::bind_method("_text_changed", &NewProjectDialog::_text_changed);
+ ClassDB::bind_method("_path_text_changed", &NewProjectDialog::_path_text_changed);
+ ClassDB::bind_method("_path_selected", &NewProjectDialog::_path_selected);
+ ClassDB::bind_method("_file_selected", &NewProjectDialog::_file_selected);
+ ADD_SIGNAL(MethodInfo("project_created"));
}
public:
-
- void set_zip_path(const String& p_path) {
- zip_path=p_path;
+ void set_zip_path(const String &p_path) {
+ zip_path = p_path;
}
- void set_zip_title(const String& p_title) {
- zip_title=p_title;
+ void set_zip_title(const String &p_title) {
+ zip_title = p_title;
}
void set_mode(Mode p_mode) {
- mode=p_mode;
+ mode = p_mode;
}
void show_dialog() {
-
project_path->clear();
project_name->clear();
- if (mode==MODE_IMPORT) {
+ if (mode == MODE_IMPORT) {
set_title(TTR("Import Existing Project"));
get_ok()->set_text(TTR("Import"));
pp->set_text(TTR("Project Path (Must Exist):"));
@@ -368,9 +351,9 @@ public:
pn->hide();
project_name->hide();
- popup_centered(Size2(500,125)*EDSCALE);
+ popup_centered(Size2(500, 125) * EDSCALE);
- } else if (mode==MODE_NEW){
+ } else if (mode == MODE_NEW) {
set_title(TTR("Create New Project"));
get_ok()->set_text(TTR("Create"));
@@ -379,17 +362,16 @@ public:
pn->show();
project_name->show();
- popup_centered(Size2(500,145)*EDSCALE);
- } else if (mode==MODE_INSTALL){
+ popup_centered(Size2(500, 145) * EDSCALE);
+ } else if (mode == MODE_INSTALL) {
- set_title(TTR("Install Project:")+" "+zip_title);
+ set_title(TTR("Install Project:") + " " + zip_title);
get_ok()->set_text(TTR("Install"));
pp->set_text(TTR("Project Path:"));
pn->hide();
project_name->hide();
- popup_centered(Size2(500,125)*EDSCALE);
-
+ popup_centered(Size2(500, 125) * EDSCALE);
}
project_path->grab_focus();
@@ -398,69 +380,65 @@ public:
NewProjectDialog() {
-
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
//set_child_rect(vb);
- Label* l = memnew(Label);
+ Label *l = memnew(Label);
l->set_text(TTR("Project Path:"));
vb->add_child(l);
- pp=l;
+ pp = l;
- project_path = memnew( LineEdit );
- MarginContainer *mc = memnew( MarginContainer );
+ project_path = memnew(LineEdit);
+ MarginContainer *mc = memnew(MarginContainer);
vb->add_child(mc);
- HBoxContainer *pphb = memnew( HBoxContainer );
+ HBoxContainer *pphb = memnew(HBoxContainer);
mc->add_child(pphb);
pphb->add_child(project_path);
project_path->set_h_size_flags(SIZE_EXPAND_FILL);
- Button* browse = memnew( Button );
+ Button *browse = memnew(Button);
pphb->add_child(browse);
browse->set_text(TTR("Browse"));
- browse->connect("pressed", this,"_browse_path");
+ browse->connect("pressed", this, "_browse_path");
l = memnew(Label);
l->set_text(TTR("Project Name:"));
- l->set_pos(Point2(5,50));
+ l->set_pos(Point2(5, 50));
vb->add_child(l);
- pn=l;
+ pn = l;
- project_name = memnew( LineEdit );
- mc = memnew( MarginContainer );
+ project_name = memnew(LineEdit);
+ mc = memnew(MarginContainer);
vb->add_child(mc);
mc->add_child(project_name);
project_name->set_text(TTR("New Game Project"));
-
l = memnew(Label);
l->set_text(TTR("That's a BINGO!"));
vb->add_child(l);
- error=l;
- l->add_color_override("font_color",Color(1,0.4,0.3,0.8));
+ error = l;
+ l->add_color_override("font_color", Color(1, 0.4, 0.3, 0.8));
l->set_align(Label::ALIGN_CENTER);
DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
project_path->set_text(d->get_current_dir());
memdelete(d);
- fdialog = memnew( FileDialog );
+ fdialog = memnew(FileDialog);
add_child(fdialog);
fdialog->set_access(FileDialog::ACCESS_FILESYSTEM);
- fdialog->set_current_dir( EditorSettings::get_singleton()->get("filesystem/directories/default_project_path") );
- project_name->connect("text_changed", this,"_text_changed");
- project_path->connect("text_changed", this,"_path_text_changed");
- fdialog->connect("dir_selected", this,"_path_selected");
- fdialog->connect("file_selected", this,"_file_selected");
+ fdialog->set_current_dir(EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"));
+ project_name->connect("text_changed", this, "_text_changed");
+ project_path->connect("text_changed", this, "_path_text_changed");
+ fdialog->connect("dir_selected", this, "_path_selected");
+ fdialog->connect("file_selected", this, "_file_selected");
set_hide_on_ok(false);
- mode=MODE_NEW;
+ mode = MODE_NEW;
- dialog_error = memnew( AcceptDialog );
+ dialog_error = memnew(AcceptDialog);
add_child(dialog_error);
}
-
-
};
struct ProjectItem {
@@ -470,20 +448,24 @@ struct ProjectItem {
uint64_t last_modified;
bool favorite;
ProjectItem() {}
- ProjectItem(const String &p_project, const String &p_path, const String &p_conf, uint64_t p_last_modified, bool p_favorite=false) {
- project = p_project; path = p_path; conf = p_conf; last_modified = p_last_modified; favorite=p_favorite;
+ ProjectItem(const String &p_project, const String &p_path, const String &p_conf, uint64_t p_last_modified, bool p_favorite = false) {
+ project = p_project;
+ path = p_path;
+ conf = p_conf;
+ last_modified = p_last_modified;
+ favorite = p_favorite;
}
- _FORCE_INLINE_ bool operator <(const ProjectItem& l) const { return last_modified > l.last_modified; }
- _FORCE_INLINE_ bool operator ==(const ProjectItem& l) const { return project==l.project; }
+ _FORCE_INLINE_ bool operator<(const ProjectItem &l) const { return last_modified > l.last_modified; }
+ _FORCE_INLINE_ bool operator==(const ProjectItem &l) const { return project == l.project; }
};
void ProjectManager::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
get_tree()->set_editor_hint(true);
- } else if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
set_process_unhandled_input(is_visible_in_tree());
}
@@ -493,61 +475,60 @@ void ProjectManager::_panel_draw(Node *p_hb) {
HBoxContainer *hb = p_hb->cast_to<HBoxContainer>();
- hb->draw_line(Point2(0,hb->get_size().y+1),Point2(hb->get_size().x-10,hb->get_size().y+1),get_color("guide_color","Tree"));
+ hb->draw_line(Point2(0, hb->get_size().y + 1), Point2(hb->get_size().x - 10, hb->get_size().y + 1), get_color("guide_color", "Tree"));
if (selected_list.has(hb->get_meta("name"))) {
- hb->draw_style_box( gui_base->get_stylebox("selected","Tree"),Rect2(Point2(),hb->get_size()-Size2(10,0)));
+ hb->draw_style_box(gui_base->get_stylebox("selected", "Tree"), Rect2(Point2(), hb->get_size() - Size2(10, 0)));
}
}
-void ProjectManager::_update_project_buttons()
-{
- for(int i=0;i<scroll_childs->get_child_count();i++) {
+void ProjectManager::_update_project_buttons() {
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
CanvasItem *item = scroll_childs->get_child(i)->cast_to<CanvasItem>();
item->update();
}
bool has_runnable_scene = false;
- for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
+ for (Map<String, String>::Element *E = selected_list.front(); E; E = E->next()) {
const String &selected_main = E->get();
if (selected_main == "") continue;
has_runnable_scene = true;
break;
}
- erase_btn->set_disabled(selected_list.size()<1);
- open_btn->set_disabled(selected_list.size()<1);
+ erase_btn->set_disabled(selected_list.size() < 1);
+ open_btn->set_disabled(selected_list.size() < 1);
run_btn->set_disabled(!has_runnable_scene);
}
-void ProjectManager::_panel_input(const InputEvent& p_ev,Node *p_hb) {
+void ProjectManager::_panel_input(const InputEvent &p_ev, Node *p_hb) {
- if (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.pressed && p_ev.mouse_button.button_index==BUTTON_LEFT) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON && p_ev.mouse_button.pressed && p_ev.mouse_button.button_index == BUTTON_LEFT) {
String clicked = p_hb->get_meta("name");
String clicked_main_scene = p_hb->get_meta("main_scene");
- if (p_ev.key.mod.shift && selected_list.size()>0 && last_clicked!="" && clicked != last_clicked) {
+ if (p_ev.key.mod.shift && selected_list.size() > 0 && last_clicked != "" && clicked != last_clicked) {
int clicked_id = -1;
int last_clicked_id = -1;
- for(int i=0;i<scroll_childs->get_child_count();i++) {
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (!hb) continue;
if (hb->get_meta("name") == clicked) clicked_id = i;
if (hb->get_meta("name") == last_clicked) last_clicked_id = i;
}
- if (last_clicked_id!=-1 && clicked_id!=-1) {
- int min = clicked_id < last_clicked_id? clicked_id : last_clicked_id;
- int max = clicked_id > last_clicked_id? clicked_id : last_clicked_id;
- for(int i=0; i<scroll_childs->get_child_count(); ++i) {
+ if (last_clicked_id != -1 && clicked_id != -1) {
+ int min = clicked_id < last_clicked_id ? clicked_id : last_clicked_id;
+ int max = clicked_id > last_clicked_id ? clicked_id : last_clicked_id;
+ for (int i = 0; i < scroll_childs->get_child_count(); ++i) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (!hb) continue;
- if (i!=clicked_id && (i<min || i>max) && !p_ev.key.mod.control) {
+ if (i != clicked_id && (i < min || i > max) && !p_ev.key.mod.control) {
selected_list.erase(hb->get_meta("name"));
- } else if (i>=min && i<=max) {
+ } else if (i >= min && i <= max) {
selected_list.insert(hb->get_meta("name"), hb->get_meta("main_scene"));
}
}
@@ -560,7 +541,7 @@ void ProjectManager::_panel_input(const InputEvent& p_ev,Node *p_hb) {
} else {
last_clicked = clicked;
- if (p_ev.key.mod.control || selected_list.size()==0) {
+ if (p_ev.key.mod.control || selected_list.size() == 0) {
selected_list.insert(clicked, clicked_main_scene);
} else {
selected_list.clear();
@@ -572,13 +553,12 @@ void ProjectManager::_panel_input(const InputEvent& p_ev,Node *p_hb) {
if (p_ev.mouse_button.doubleclick)
_open_project(); //open if doubleclicked
-
}
}
-void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
+void ProjectManager::_unhandled_input(const InputEvent &p_ev) {
- if (p_ev.type==InputEvent::KEY) {
+ if (p_ev.type == InputEvent::KEY) {
const InputEventKey &k = p_ev.key;
@@ -595,7 +575,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
} break;
case KEY_HOME: {
- for (int i=0; i<scroll_childs->get_child_count(); i++) {
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (hb) {
@@ -610,7 +590,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
} break;
case KEY_END: {
- for (int i=scroll_childs->get_child_count()-1; i>=0; i--) {
+ for (int i = scroll_childs->get_child_count() - 1; i >= 0; i--) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (hb) {
@@ -632,7 +612,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
bool found = false;
- for (int i=scroll_childs->get_child_count()-1; i>=0; i--) {
+ for (int i = scroll_childs->get_child_count() - 1; i >= 0; i--) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (!hb) continue;
@@ -652,7 +632,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
break;
- } else if (current==selected_list.back()->key()) {
+ } else if (current == selected_list.back()->key()) {
found = true;
}
@@ -669,7 +649,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
bool found = selected_list.empty();
- for (int i=0; i<scroll_childs->get_child_count(); i++) {
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
if (!hb) continue;
@@ -690,7 +670,7 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
break;
- } else if (current==selected_list.back()->key()) {
+ } else if (current == selected_list.back()->key()) {
found = true;
}
@@ -698,8 +678,10 @@ void ProjectManager::_unhandled_input(const InputEvent& p_ev) {
} break;
case KEY_F: {
- if (k.mod.command) this->project_filter->search_box->grab_focus();
- else scancode_handled = false;
+ if (k.mod.command)
+ this->project_filter->search_box->grab_focus();
+ else
+ scancode_handled = false;
} break;
default: {
scancode_handled = false;
@@ -716,26 +698,25 @@ void ProjectManager::_favorite_pressed(Node *p_hb) {
String clicked = p_hb->get_meta("name");
bool favorite = !p_hb->get_meta("favorite");
- String proj=clicked.replace(":::",":/");
- proj=proj.replace("::","/");
+ String proj = clicked.replace(":::", ":/");
+ proj = proj.replace("::", "/");
if (favorite) {
- EditorSettings::get_singleton()->set("favorite_projects/"+clicked,proj);
+ EditorSettings::get_singleton()->set("favorite_projects/" + clicked, proj);
} else {
- EditorSettings::get_singleton()->erase("favorite_projects/"+clicked);
+ EditorSettings::get_singleton()->erase("favorite_projects/" + clicked);
}
EditorSettings::get_singleton()->save();
call_deferred("_load_recent_projects");
}
-
void ProjectManager::_load_recent_projects() {
ProjectListFilter::FilterOption filter_option = project_filter->get_filter_option();
String search_term = project_filter->get_search_term();
- while(scroll_childs->get_child_count()>0) {
- memdelete( scroll_childs->get_child(0));
+ while (scroll_childs->get_child_count() > 0) {
+ memdelete(scroll_childs->get_child(0));
}
Map<String, String> selected_list_copy = selected_list;
@@ -743,24 +724,24 @@ void ProjectManager::_load_recent_projects() {
List<PropertyInfo> properties;
EditorSettings::get_singleton()->get_property_list(&properties);
- Color font_color = gui_base->get_color("font_color","Tree");
+ Color font_color = gui_base->get_color("font_color", "Tree");
List<ProjectItem> projects;
List<ProjectItem> favorite_projects;
- for(List<PropertyInfo>::Element *E=properties.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
String _name = E->get().name;
if (!_name.begins_with("projects/") && !_name.begins_with("favorite_projects/"))
continue;
String path = EditorSettings::get_singleton()->get(_name);
- if (filter_option == ProjectListFilter::FILTER_PATH && search_term!="" && path.findn(search_term)==-1)
+ if (filter_option == ProjectListFilter::FILTER_PATH && search_term != "" && path.findn(search_term) == -1)
continue;
- String project = _name.get_slice("/",1);
- String conf=path.plus_file("godot.cfg");
- bool favorite = (_name.begins_with("favorite_projects/"))?true:false;
+ String project = _name.get_slice("/", 1);
+ String conf = path.plus_file("godot.cfg");
+ bool favorite = (_name.begins_with("favorite_projects/")) ? true : false;
uint64_t last_modified = 0;
if (FileAccess::exists(conf)) {
@@ -769,7 +750,7 @@ void ProjectManager::_load_recent_projects() {
String fscache = path.plus_file(".fscache");
if (FileAccess::exists(fscache)) {
uint64_t cache_modified = FileAccess::get_modified_time(fscache);
- if ( cache_modified > last_modified )
+ if (cache_modified > last_modified)
last_modified = cache_modified;
}
@@ -787,19 +768,19 @@ void ProjectManager::_load_recent_projects() {
projects.sort();
favorite_projects.sort();
- for(List<ProjectItem>::Element *E=projects.front();E;) {
+ for (List<ProjectItem>::Element *E = projects.front(); E;) {
List<ProjectItem>::Element *next = E->next();
if (favorite_projects.find(E->get()) != NULL)
projects.erase(E->get());
- E=next;
+ E = next;
}
- for(List<ProjectItem>::Element *E=favorite_projects.back();E;E=E->prev()) {
+ for (List<ProjectItem>::Element *E = favorite_projects.back(); E; E = E->prev()) {
projects.push_front(E->get());
}
- Ref<Texture> favorite_icon = get_icon("Favorites","EditorIcons");
+ Ref<Texture> favorite_icon = get_icon("Favorites", "EditorIcons");
- for(List<ProjectItem>::Element *E=projects.front();E;E=E->next()) {
+ for (List<ProjectItem>::Element *E = projects.front(); E; E = E->next()) {
ProjectItem &item = E->get();
String project = item.project;
@@ -807,89 +788,88 @@ void ProjectManager::_load_recent_projects() {
String conf = item.conf;
bool is_favorite = item.favorite;
- Ref<ConfigFile> cf = memnew( ConfigFile );
+ Ref<ConfigFile> cf = memnew(ConfigFile);
Error err = cf->load(conf);
- ERR_CONTINUE(err!=OK);
+ ERR_CONTINUE(err != OK);
+ String project_name = TTR("Unnamed Project");
- String project_name=TTR("Unnamed Project");
-
- if (cf->has_section_key("application","name")) {
- project_name = static_cast<String>(cf->get_value("application","name")).xml_unescape();
+ if (cf->has_section_key("application", "name")) {
+ project_name = static_cast<String>(cf->get_value("application", "name")).xml_unescape();
}
- if (filter_option==ProjectListFilter::FILTER_NAME && search_term!="" && project_name.findn(search_term)==-1)
+ if (filter_option == ProjectListFilter::FILTER_NAME && search_term != "" && project_name.findn(search_term) == -1)
continue;
Ref<Texture> icon;
- if (cf->has_section_key("application","icon")) {
- String appicon = cf->get_value("application","icon");
- if (appicon!="") {
+ if (cf->has_section_key("application", "icon")) {
+ String appicon = cf->get_value("application", "icon");
+ if (appicon != "") {
Image img;
- Error err = img.load(appicon.replace_first("res://",path+"/"));
- if (err==OK) {
+ Error err = img.load(appicon.replace_first("res://", path + "/"));
+ if (err == OK) {
- img.resize(64,64);
- Ref<ImageTexture> it = memnew( ImageTexture );
+ img.resize(64, 64);
+ Ref<ImageTexture> it = memnew(ImageTexture);
it->create_from_image(img);
- icon=it;
+ icon = it;
}
}
}
if (icon.is_null()) {
- icon=get_icon("DefaultProjectIcon","EditorIcons");
+ icon = get_icon("DefaultProjectIcon", "EditorIcons");
}
String main_scene;
- if (cf->has_section_key("application","main_scene")) {
- main_scene = cf->get_value("application","main_scene");
+ if (cf->has_section_key("application", "main_scene")) {
+ main_scene = cf->get_value("application", "main_scene");
}
selected_list_copy.erase(project);
- HBoxContainer *hb = memnew( HBoxContainer );
- hb->set_meta("name",project);
- hb->set_meta("main_scene",main_scene);
- hb->set_meta("favorite",is_favorite);
- hb->connect("draw",this,"_panel_draw",varray(hb));
- hb->connect("gui_input",this,"_panel_input",varray(hb));
- hb->add_constant_override("separation",10*EDSCALE);
+ HBoxContainer *hb = memnew(HBoxContainer);
+ hb->set_meta("name", project);
+ hb->set_meta("main_scene", main_scene);
+ hb->set_meta("favorite", is_favorite);
+ hb->connect("draw", this, "_panel_draw", varray(hb));
+ hb->connect("gui_input", this, "_panel_input", varray(hb));
+ hb->add_constant_override("separation", 10 * EDSCALE);
- VBoxContainer *favorite_box = memnew( VBoxContainer );
- TextureButton *favorite = memnew( TextureButton );
+ VBoxContainer *favorite_box = memnew(VBoxContainer);
+ TextureButton *favorite = memnew(TextureButton);
favorite->set_normal_texture(favorite_icon);
if (!is_favorite)
- favorite->set_modulate(Color(1,1,1,0.2));
+ favorite->set_modulate(Color(1, 1, 1, 0.2));
favorite->set_v_size_flags(SIZE_EXPAND);
- favorite->connect("pressed",this,"_favorite_pressed",varray(hb));
+ favorite->connect("pressed", this, "_favorite_pressed", varray(hb));
favorite_box->add_child(favorite);
hb->add_child(favorite_box);
- TextureRect *tf = memnew( TextureRect );
+ TextureRect *tf = memnew(TextureRect);
tf->set_texture(icon);
hb->add_child(tf);
VBoxContainer *vb = memnew(VBoxContainer);
vb->set_name("project");
hb->add_child(vb);
- Control *ec = memnew( Control );
- ec->set_custom_minimum_size(Size2(0,1));
+ Control *ec = memnew(Control);
+ ec->set_custom_minimum_size(Size2(0, 1));
vb->add_child(ec);
- Label *title = memnew( Label(project_name) );
- title->add_font_override("font", gui_base->get_font("large","Fonts"));
- title->add_color_override("font_color",font_color);
+ Label *title = memnew(Label(project_name));
+ title->add_font_override("font", gui_base->get_font("large", "Fonts"));
+ title->add_color_override("font_color", font_color);
vb->add_child(title);
- Label *fpath = memnew( Label(path) );
+ Label *fpath = memnew(Label(path));
fpath->set_name("path");
vb->add_child(fpath);
- fpath->set_modulate(Color(1,1,1,0.5));
- fpath->add_color_override("font_color",font_color);
+ fpath->set_modulate(Color(1, 1, 1, 0.5));
+ fpath->add_color_override("font_color", font_color);
scroll_childs->add_child(hb);
}
- for (Map<String,String>::Element *E = selected_list_copy.front();E;E = E->next()) {
+ for (Map<String, String>::Element *E = selected_list_copy.front(); E; E = E->next()) {
String key = E->key();
selected_list.erase(key);
}
@@ -903,13 +883,13 @@ void ProjectManager::_load_recent_projects() {
tabs->set_current_tab(0);
}
-void ProjectManager::_on_project_created(const String& dir) {
- bool has_already=false;
- for (int i=0;i<scroll_childs->get_child_count();i++) {
- HBoxContainer *hb=scroll_childs->get_child(i)->cast_to<HBoxContainer>();
- Label *fpath=hb->get_node(NodePath("project/path"))->cast_to<Label>();
- if (fpath->get_text()==dir) {
- has_already=true;
+void ProjectManager::_on_project_created(const String &dir) {
+ bool has_already = false;
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
+ HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
+ Label *fpath = hb->get_node(NodePath("project/path"))->cast_to<Label>();
+ if (fpath->get_text() == dir) {
+ has_already = true;
break;
}
}
@@ -921,20 +901,20 @@ void ProjectManager::_on_project_created(const String& dir) {
}
}
-void ProjectManager::_update_scroll_pos(const String& dir) {
- for (int i=0;i<scroll_childs->get_child_count();i++) {
- HBoxContainer *hb=scroll_childs->get_child(i)->cast_to<HBoxContainer>();
- Label *fpath=hb->get_node(NodePath("project/path"))->cast_to<Label>();
- if (fpath->get_text()==dir) {
- last_clicked=hb->get_meta("name");
+void ProjectManager::_update_scroll_pos(const String &dir) {
+ for (int i = 0; i < scroll_childs->get_child_count(); i++) {
+ HBoxContainer *hb = scroll_childs->get_child(i)->cast_to<HBoxContainer>();
+ Label *fpath = hb->get_node(NodePath("project/path"))->cast_to<Label>();
+ if (fpath->get_text() == dir) {
+ last_clicked = hb->get_meta("name");
selected_list.clear();
selected_list.insert(hb->get_meta("name"), hb->get_meta("main_scene"));
_update_project_buttons();
- int last_y_visible=scroll->get_v_scroll()+scroll->get_size().y;
- int offset_diff=(hb->get_pos().y + hb->get_size().y)-last_y_visible;
+ int last_y_visible = scroll->get_v_scroll() + scroll->get_size().y;
+ int offset_diff = (hb->get_pos().y + hb->get_size().y) - last_y_visible;
- if (offset_diff>0)
- scroll->set_v_scroll(scroll->get_v_scroll()+offset_diff);
+ if (offset_diff > 0)
+ scroll->set_v_scroll(scroll->get_v_scroll() + offset_diff);
break;
}
}
@@ -942,10 +922,10 @@ void ProjectManager::_update_scroll_pos(const String& dir) {
void ProjectManager::_open_project_confirm() {
- for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
+ for (Map<String, String>::Element *E = selected_list.front(); E; E = E->next()) {
const String &selected = E->key();
- String path = EditorSettings::get_singleton()->get("projects/"+selected);
- print_line("OPENING: "+path+" ("+selected+")");
+ String path = EditorSettings::get_singleton()->get("projects/" + selected);
+ print_line("OPENING: " + path + " (" + selected + ")");
List<String> args;
@@ -956,8 +936,8 @@ void ProjectManager::_open_project_confirm() {
String exec = OS::get_singleton()->get_executable_path();
- OS::ProcessID pid=0;
- Error err = OS::get_singleton()->execute(exec,args,false,&pid);
+ OS::ProcessID pid = 0;
+ Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
}
@@ -966,11 +946,11 @@ void ProjectManager::_open_project_confirm() {
void ProjectManager::_open_project() {
- if (selected_list.size()<1) {
+ if (selected_list.size() < 1) {
return;
}
- if (selected_list.size()>1) {
+ if (selected_list.size() > 1) {
multi_open_ask->set_text(TTR("Are you sure to open more than one project?"));
multi_open_ask->popup_centered_minsize();
} else {
@@ -980,14 +960,14 @@ void ProjectManager::_open_project() {
void ProjectManager::_run_project_confirm() {
- for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
+ for (Map<String, String>::Element *E = selected_list.front(); E; E = E->next()) {
const String &selected_main = E->get();
if (selected_main == "") continue;
const String &selected = E->key();
- String path = EditorSettings::get_singleton()->get("projects/"+selected);
- print_line("OPENING: "+path+" ("+selected+")");
+ String path = EditorSettings::get_singleton()->get("projects/" + selected);
+ print_line("OPENING: " + path + " (" + selected + ")");
List<String> args;
@@ -996,8 +976,8 @@ void ProjectManager::_run_project_confirm() {
String exec = OS::get_singleton()->get_executable_path();
- OS::ProcessID pid=0;
- Error err = OS::get_singleton()->execute(exec,args,false,&pid);
+ OS::ProcessID pid = 0;
+ Error err = OS::get_singleton()->execute(exec, args, false, &pid);
ERR_FAIL_COND(err);
}
//get_scene()->quit(); do not quit
@@ -1005,12 +985,11 @@ void ProjectManager::_run_project_confirm() {
void ProjectManager::_run_project() {
-
- if (selected_list.size()<1) {
+ if (selected_list.size() < 1) {
return;
}
- if (selected_list.size()>1) {
+ if (selected_list.size() > 1) {
multi_run_ask->set_text(TTR("Are you sure to run more than one project?"));
multi_run_ask->popup_centered_minsize();
} else {
@@ -1018,111 +997,97 @@ void ProjectManager::_run_project() {
}
}
-void ProjectManager::_scan_dir(DirAccess *da,float pos, float total,List<String> *r_projects) {
-
+void ProjectManager::_scan_dir(DirAccess *da, float pos, float total, List<String> *r_projects) {
List<String> subdirs;
da->list_dir_begin();
String n = da->get_next();
- while(n!=String()) {
+ while (n != String()) {
if (da->current_is_dir() && !n.begins_with(".")) {
subdirs.push_front(n);
- } else if (n=="godot.cfg") {
+ } else if (n == "godot.cfg") {
r_projects->push_back(da->get_current_dir());
}
- n=da->get_next();
+ n = da->get_next();
}
da->list_dir_end();
- int m=0;
- for(List<String>::Element *E=subdirs.front();E;E=E->next()) {
+ int m = 0;
+ for (List<String>::Element *E = subdirs.front(); E; E = E->next()) {
da->change_dir(E->get());
- float slice=total/subdirs.size();
- _scan_dir(da,pos+slice*m,slice,r_projects);
+ float slice = total / subdirs.size();
+ _scan_dir(da, pos + slice * m, slice, r_projects);
da->change_dir("..");
m++;
}
-
-
}
+void ProjectManager::_scan_begin(const String &p_base) {
-void ProjectManager::_scan_begin(const String& p_base) {
-
- print_line("SCAN PROJECTS AT: "+p_base);
+ print_line("SCAN PROJECTS AT: " + p_base);
List<String> projects;
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
da->change_dir(p_base);
- _scan_dir(da,0,1,&projects);
+ _scan_dir(da, 0, 1, &projects);
memdelete(da);
- print_line("found: "+itos(projects.size())+" projects.");
-
- for(List<String>::Element *E=projects.front();E;E=E->next()) {
- String proj=E->get().replace("/","::");
- EditorSettings::get_singleton()->set("projects/"+proj,E->get());
+ print_line("found: " + itos(projects.size()) + " projects.");
+ for (List<String>::Element *E = projects.front(); E; E = E->next()) {
+ String proj = E->get().replace("/", "::");
+ EditorSettings::get_singleton()->set("projects/" + proj, E->get());
}
EditorSettings::get_singleton()->save();
_load_recent_projects();
-
}
void ProjectManager::_scan_projects() {
scan_dir->popup_centered_ratio();
-
}
-
-void ProjectManager::_new_project() {
+void ProjectManager::_new_project() {
npdialog->set_mode(NewProjectDialog::MODE_NEW);
npdialog->show_dialog();
}
-
-void ProjectManager::_import_project() {
+void ProjectManager::_import_project() {
npdialog->set_mode(NewProjectDialog::MODE_IMPORT);
npdialog->show_dialog();
}
-void ProjectManager::_erase_project_confirm() {
+void ProjectManager::_erase_project_confirm() {
- if (selected_list.size()==0) {
+ if (selected_list.size() == 0) {
return;
}
- for (Map<String,String>::Element *E=selected_list.front(); E; E=E->next()) {
- EditorSettings::get_singleton()->erase("projects/"+E->key());
- EditorSettings::get_singleton()->erase("favorite_projects/"+E->key());
+ for (Map<String, String>::Element *E = selected_list.front(); E; E = E->next()) {
+ EditorSettings::get_singleton()->erase("projects/" + E->key());
+ EditorSettings::get_singleton()->erase("favorite_projects/" + E->key());
}
EditorSettings::get_singleton()->save();
selected_list.clear();
last_clicked = "";
_load_recent_projects();
-
}
-void ProjectManager::_erase_project() {
+void ProjectManager::_erase_project() {
- if (selected_list.size()==0)
+ if (selected_list.size() == 0)
return;
-
erase_ask->set_text(TTR("Remove project from the list? (Folder contents will not be modified)"));
erase_ask->popup_centered_minsize();
-
}
-
-void ProjectManager::_exit_dialog() {
+void ProjectManager::_exit_dialog() {
get_tree()->quit();
}
-
-void ProjectManager::_install_project(const String& p_zip_path,const String& p_title) {
+void ProjectManager::_install_project(const String &p_zip_path, const String &p_title) {
npdialog->set_mode(NewProjectDialog::MODE_INSTALL);
npdialog->set_zip_path(p_zip_path);
@@ -1138,19 +1103,19 @@ void ProjectManager::_files_dropped(PoolStringArray p_files, int p_screen) {
folders_set.insert(da->dir_exists(file) ? file : file.get_base_dir());
}
memdelete(da);
- if (folders_set.size()>0) {
+ if (folders_set.size() > 0) {
PoolStringArray folders;
- for (Set<String>::Element *E=folders_set.front();E;E=E->next()) {
+ for (Set<String>::Element *E = folders_set.front(); E; E = E->next()) {
folders.append(E->get());
}
bool confirm = true;
- if (folders.size()==1) {
+ if (folders.size() == 1) {
DirAccess *dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- if (dir->change_dir(folders[0])==OK) {
+ if (dir->change_dir(folders[0]) == OK) {
dir->list_dir_begin();
String file = dir->get_next();
- while(confirm && file!=String()) {
+ while (confirm && file != String()) {
if (!dir->current_is_dir() && file.ends_with("godot.cfg")) {
confirm = false;
}
@@ -1171,8 +1136,7 @@ void ProjectManager::_files_dropped(PoolStringArray p_files, int p_screen) {
}
}
-void ProjectManager::_scan_multiple_folders(PoolStringArray p_files)
-{
+void ProjectManager::_scan_multiple_folders(PoolStringArray p_files) {
for (int i = 0; i < p_files.size(); i++) {
_scan_begin(p_files.get(i));
}
@@ -1180,29 +1144,27 @@ void ProjectManager::_scan_multiple_folders(PoolStringArray p_files)
void ProjectManager::_bind_methods() {
- ClassDB::bind_method("_open_project",&ProjectManager::_open_project);
- ClassDB::bind_method("_open_project_confirm",&ProjectManager::_open_project_confirm);
- ClassDB::bind_method("_run_project",&ProjectManager::_run_project);
- ClassDB::bind_method("_run_project_confirm",&ProjectManager::_run_project_confirm);
- ClassDB::bind_method("_scan_projects",&ProjectManager::_scan_projects);
- ClassDB::bind_method("_scan_begin",&ProjectManager::_scan_begin);
- ClassDB::bind_method("_import_project",&ProjectManager::_import_project);
- ClassDB::bind_method("_new_project",&ProjectManager::_new_project);
- ClassDB::bind_method("_erase_project",&ProjectManager::_erase_project);
- ClassDB::bind_method("_erase_project_confirm",&ProjectManager::_erase_project_confirm);
- ClassDB::bind_method("_exit_dialog",&ProjectManager::_exit_dialog);
- ClassDB::bind_method("_load_recent_projects",&ProjectManager::_load_recent_projects);
- ClassDB::bind_method("_on_project_created",&ProjectManager::_on_project_created);
- ClassDB::bind_method("_update_scroll_pos",&ProjectManager::_update_scroll_pos);
- ClassDB::bind_method("_panel_draw",&ProjectManager::_panel_draw);
- ClassDB::bind_method("_panel_input",&ProjectManager::_panel_input);
- ClassDB::bind_method("_unhandled_input",&ProjectManager::_unhandled_input);
- ClassDB::bind_method("_favorite_pressed",&ProjectManager::_favorite_pressed);
- ClassDB::bind_method("_install_project",&ProjectManager::_install_project);
- ClassDB::bind_method("_files_dropped",&ProjectManager::_files_dropped);
- ClassDB::bind_method(D_METHOD("_scan_multiple_folders", "files"),&ProjectManager::_scan_multiple_folders);
-
-
+ ClassDB::bind_method("_open_project", &ProjectManager::_open_project);
+ ClassDB::bind_method("_open_project_confirm", &ProjectManager::_open_project_confirm);
+ ClassDB::bind_method("_run_project", &ProjectManager::_run_project);
+ ClassDB::bind_method("_run_project_confirm", &ProjectManager::_run_project_confirm);
+ ClassDB::bind_method("_scan_projects", &ProjectManager::_scan_projects);
+ ClassDB::bind_method("_scan_begin", &ProjectManager::_scan_begin);
+ ClassDB::bind_method("_import_project", &ProjectManager::_import_project);
+ ClassDB::bind_method("_new_project", &ProjectManager::_new_project);
+ ClassDB::bind_method("_erase_project", &ProjectManager::_erase_project);
+ ClassDB::bind_method("_erase_project_confirm", &ProjectManager::_erase_project_confirm);
+ ClassDB::bind_method("_exit_dialog", &ProjectManager::_exit_dialog);
+ ClassDB::bind_method("_load_recent_projects", &ProjectManager::_load_recent_projects);
+ ClassDB::bind_method("_on_project_created", &ProjectManager::_on_project_created);
+ ClassDB::bind_method("_update_scroll_pos", &ProjectManager::_update_scroll_pos);
+ ClassDB::bind_method("_panel_draw", &ProjectManager::_panel_draw);
+ ClassDB::bind_method("_panel_input", &ProjectManager::_panel_input);
+ ClassDB::bind_method("_unhandled_input", &ProjectManager::_unhandled_input);
+ ClassDB::bind_method("_favorite_pressed", &ProjectManager::_favorite_pressed);
+ ClassDB::bind_method("_install_project", &ProjectManager::_install_project);
+ ClassDB::bind_method("_files_dropped", &ProjectManager::_files_dropped);
+ ClassDB::bind_method(D_METHOD("_scan_multiple_folders", "files"), &ProjectManager::_scan_multiple_folders);
}
ProjectManager::ProjectManager() {
@@ -1211,20 +1173,19 @@ ProjectManager::ProjectManager() {
if (!EditorSettings::get_singleton())
EditorSettings::create();
-
EditorSettings::get_singleton()->set_optimize_save(false); //just write settings as they came
{
int dpi_mode = EditorSettings::get_singleton()->get("interface/hidpi_mode");
- if (dpi_mode==0) {
- editor_set_scale( OS::get_singleton()->get_screen_dpi(0) > 150 && OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x>2000 ? 2.0 : 1.0 );
- } else if (dpi_mode==1) {
+ if (dpi_mode == 0) {
+ editor_set_scale(OS::get_singleton()->get_screen_dpi(0) > 150 && OS::get_singleton()->get_screen_size(OS::get_singleton()->get_current_screen()).x > 2000 ? 2.0 : 1.0);
+ } else if (dpi_mode == 1) {
editor_set_scale(0.75);
- } else if (dpi_mode==2) {
+ } else if (dpi_mode == 2) {
editor_set_scale(1.0);
- } else if (dpi_mode==3) {
+ } else if (dpi_mode == 3) {
editor_set_scale(1.5);
- } else if (dpi_mode==4) {
+ } else if (dpi_mode == 4) {
editor_set_scale(2.0);
}
}
@@ -1234,37 +1195,37 @@ ProjectManager::ProjectManager() {
set_area_as_parent_rect();
set_theme(create_editor_theme());
- gui_base = memnew( Control );
+ gui_base = memnew(Control);
add_child(gui_base);
gui_base->set_area_as_parent_rect();
gui_base->set_theme(create_custom_theme());
- Panel *panel = memnew( Panel );
+ Panel *panel = memnew(Panel);
gui_base->add_child(panel);
panel->set_area_as_parent_rect();
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
panel->add_child(vb);
- vb->set_area_as_parent_rect(20*EDSCALE);
- vb->set_margin(MARGIN_TOP,4*EDSCALE);
- vb->set_margin(MARGIN_BOTTOM,4*EDSCALE);
- vb->add_constant_override("separation",15*EDSCALE);
+ vb->set_area_as_parent_rect(20 * EDSCALE);
+ vb->set_margin(MARGIN_TOP, 4 * EDSCALE);
+ vb->set_margin(MARGIN_BOTTOM, 4 * EDSCALE);
+ vb->add_constant_override("separation", 15 * EDSCALE);
String cp;
cp.push_back(0xA9);
cp.push_back(0);
- OS::get_singleton()->set_window_title(_MKSTR(VERSION_NAME)+String(" - ")+TTR("Project Manager")+" - "+cp+" 2008-2017 Juan Linietsky, Ariel Manzur.");
+ OS::get_singleton()->set_window_title(_MKSTR(VERSION_NAME) + String(" - ") + TTR("Project Manager") + " - " + cp + " 2008-2017 Juan Linietsky, Ariel Manzur.");
- HBoxContainer *top_hb = memnew( HBoxContainer);
+ HBoxContainer *top_hb = memnew(HBoxContainer);
vb->add_child(top_hb);
- CenterContainer *ccl = memnew( CenterContainer );
- Label *l = memnew( Label );
- l->set_text(_MKSTR(VERSION_NAME)+String(" - ")+TTR("Project Manager"));
- l->add_font_override("font", gui_base->get_font("doc","EditorFonts"));
+ CenterContainer *ccl = memnew(CenterContainer);
+ Label *l = memnew(Label);
+ l->set_text(_MKSTR(VERSION_NAME) + String(" - ") + TTR("Project Manager"));
+ l->add_font_override("font", gui_base->get_font("doc", "EditorFonts"));
ccl->add_child(l);
top_hb->add_child(ccl);
top_hb->add_spacer();
- l = memnew( Label );
+ l = memnew(Label);
l->set_text("v" VERSION_MKSTRING);
//l->add_font_override("font",get_font("bold","Fonts"));
l->set_align(Label::ALIGN_CENTER);
@@ -1272,11 +1233,11 @@ ProjectManager::ProjectManager() {
//vb->add_child(memnew(HSeparator));
//vb->add_margin_child("\n",memnew(Control));
- tabs = memnew( TabContainer );
+ tabs = memnew(TabContainer);
vb->add_child(tabs);
tabs->set_v_size_flags(SIZE_EXPAND_FILL);
- HBoxContainer *tree_hb = memnew( HBoxContainer);
+ HBoxContainer *tree_hb = memnew(HBoxContainer);
projects_hb = tree_hb;
projects_hb->set_name(TTR("Project List"));
@@ -1292,131 +1253,126 @@ ProjectManager::ProjectManager() {
project_filter = memnew(ProjectListFilter);
search_box->add_child(project_filter);
project_filter->connect("filter_changed", this, "_load_recent_projects");
- project_filter->set_custom_minimum_size(Size2(250,10));
+ project_filter->set_custom_minimum_size(Size2(250, 10));
search_tree_vb->add_child(search_box);
- PanelContainer *pc = memnew( PanelContainer);
- pc->add_style_override("panel", gui_base->get_stylebox("bg","Tree"));
+ PanelContainer *pc = memnew(PanelContainer);
+ pc->add_style_override("panel", gui_base->get_stylebox("bg", "Tree"));
search_tree_vb->add_child(pc);
pc->set_v_size_flags(SIZE_EXPAND_FILL);
- scroll = memnew( ScrollContainer );
+ scroll = memnew(ScrollContainer);
pc->add_child(scroll);
scroll->set_enable_h_scroll(false);
- VBoxContainer *tree_vb = memnew( VBoxContainer);
+ VBoxContainer *tree_vb = memnew(VBoxContainer);
tree_hb->add_child(tree_vb);
- scroll_childs = memnew( VBoxContainer );
+ scroll_childs = memnew(VBoxContainer);
scroll_childs->set_h_size_flags(SIZE_EXPAND_FILL);
scroll->add_child(scroll_childs);
//HBoxContainer *hb = memnew( HBoxContainer );
//vb->add_child(hb);
- Button *open = memnew( Button );
+ Button *open = memnew(Button);
open->set_text(TTR("Edit"));
tree_vb->add_child(open);
- open->connect("pressed", this,"_open_project");
- open_btn=open;
+ open->connect("pressed", this, "_open_project");
+ open_btn = open;
- Button *run = memnew( Button );
+ Button *run = memnew(Button);
run->set_text(TTR("Run"));
tree_vb->add_child(run);
- run->connect("pressed", this,"_run_project");
- run_btn=run;
+ run->connect("pressed", this, "_run_project");
+ run_btn = run;
- tree_vb->add_child(memnew( HSeparator ));
+ tree_vb->add_child(memnew(HSeparator));
- Button *scan = memnew( Button );
+ Button *scan = memnew(Button);
scan->set_text(TTR("Scan"));
tree_vb->add_child(scan);
- scan->connect("pressed", this,"_scan_projects");
+ scan->connect("pressed", this, "_scan_projects");
- tree_vb->add_child(memnew( HSeparator ));
+ tree_vb->add_child(memnew(HSeparator));
- scan_dir = memnew( FileDialog );
+ scan_dir = memnew(FileDialog);
scan_dir->set_access(FileDialog::ACCESS_FILESYSTEM);
scan_dir->set_mode(FileDialog::MODE_OPEN_DIR);
scan_dir->set_title(TTR("Select a Folder to Scan")); // must be after mode or it's overridden
- scan_dir->set_current_dir( EditorSettings::get_singleton()->get("filesystem/directories/default_project_path") );
+ scan_dir->set_current_dir(EditorSettings::get_singleton()->get("filesystem/directories/default_project_path"));
gui_base->add_child(scan_dir);
- scan_dir->connect("dir_selected",this,"_scan_begin");
-
+ scan_dir->connect("dir_selected", this, "_scan_begin");
- Button* create = memnew( Button );
+ Button *create = memnew(Button);
create->set_text(TTR("New Project"));
tree_vb->add_child(create);
- create->connect("pressed", this,"_new_project");
+ create->connect("pressed", this, "_new_project");
- Button* import = memnew( Button );
+ Button *import = memnew(Button);
import->set_text(TTR("Import"));
tree_vb->add_child(import);
- import->connect("pressed", this,"_import_project");
+ import->connect("pressed", this, "_import_project");
-
- Button* erase = memnew( Button );
+ Button *erase = memnew(Button);
erase->set_text(TTR("Remove"));
tree_vb->add_child(erase);
- erase->connect("pressed", this,"_erase_project");
- erase_btn=erase;
-
+ erase->connect("pressed", this, "_erase_project");
+ erase_btn = erase;
tree_vb->add_spacer();
-
if (StreamPeerSSL::is_available()) {
- asset_library = memnew( EditorAssetLibrary(true) );
+ asset_library = memnew(EditorAssetLibrary(true));
asset_library->set_name("Templates");
tabs->add_child(asset_library);
- asset_library->connect("install_asset",this,"_install_project");
+ asset_library->connect("install_asset", this, "_install_project");
} else {
WARN_PRINT("Asset Library not available, as it requires SSL to work.");
}
-
- CenterContainer *cc = memnew( CenterContainer );
- Button * cancel = memnew( Button );
+ CenterContainer *cc = memnew(CenterContainer);
+ Button *cancel = memnew(Button);
cancel->set_text(TTR("Exit"));
- cancel->set_custom_minimum_size(Size2(100,1)*EDSCALE);
+ cancel->set_custom_minimum_size(Size2(100, 1) * EDSCALE);
cc->add_child(cancel);
- cancel->connect("pressed", this,"_exit_dialog");
+ cancel->connect("pressed", this, "_exit_dialog");
vb->add_child(cc);
//
- erase_ask = memnew( ConfirmationDialog );
+ erase_ask = memnew(ConfirmationDialog);
erase_ask->get_ok()->set_text(TTR("Remove"));
- erase_ask->get_ok()->connect("pressed", this,"_erase_project_confirm");
+ erase_ask->get_ok()->connect("pressed", this, "_erase_project_confirm");
gui_base->add_child(erase_ask);
- multi_open_ask = memnew( ConfirmationDialog );
+ multi_open_ask = memnew(ConfirmationDialog);
multi_open_ask->get_ok()->set_text(TTR("Edit"));
multi_open_ask->get_ok()->connect("pressed", this, "_open_project_confirm");
gui_base->add_child(multi_open_ask);
- multi_run_ask = memnew( ConfirmationDialog );
+ multi_run_ask = memnew(ConfirmationDialog);
multi_run_ask->get_ok()->set_text(TTR("Run"));
multi_run_ask->get_ok()->connect("pressed", this, "_run_project_confirm");
gui_base->add_child(multi_run_ask);
- multi_scan_ask = memnew( ConfirmationDialog );
+ multi_scan_ask = memnew(ConfirmationDialog);
multi_scan_ask->get_ok()->set_text(TTR("Scan"));
gui_base->add_child(multi_scan_ask);
OS::get_singleton()->set_low_processor_usage_mode(true);
- npdialog = memnew( NewProjectDialog );
+ npdialog = memnew(NewProjectDialog);
gui_base->add_child(npdialog);
- npdialog->connect("project_created", this,"_on_project_created");
+ npdialog->connect("project_created", this, "_on_project_created");
_load_recent_projects();
- if ( EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path") ) {
- _scan_begin( EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path") );
+ if (EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path")) {
+ _scan_begin(EditorSettings::get_singleton()->get("filesystem/directories/autoscan_project_path"));
}
//get_ok()->set_text("Open");
@@ -1427,7 +1383,6 @@ ProjectManager::ProjectManager() {
SceneTree::get_singleton()->connect("files_dropped", this, "_files_dropped");
}
-
ProjectManager::~ProjectManager() {
if (EditorSettings::get_singleton())
@@ -1445,11 +1400,11 @@ void ProjectListFilter::_command(int p_command) {
switch (p_command) {
case CMD_CLEAR_FILTER: {
- if (search_box->get_text()!="") {
+ if (search_box->get_text() != "") {
search_box->clear();
emit_signal("filter_changed");
}
- }break;
+ } break;
}
}
@@ -1467,27 +1422,27 @@ ProjectListFilter::FilterOption ProjectListFilter::get_filter_option() {
void ProjectListFilter::_filter_option_selected(int p_idx) {
FilterOption selected = (FilterOption)(filter_option->get_selected());
- if (_current_filter != selected ) {
+ if (_current_filter != selected) {
_current_filter = selected;
emit_signal("filter_changed");
}
}
void ProjectListFilter::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- clear_search_button->set_icon(get_icon("CloseHover","EditorIcons"));
+ clear_search_button->set_icon(get_icon("CloseHover", "EditorIcons"));
} break;
}
}
void ProjectListFilter::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_command"),&ProjectListFilter::_command);
+ ClassDB::bind_method(D_METHOD("_command"), &ProjectListFilter::_command);
ClassDB::bind_method(D_METHOD("_search_text_changed"), &ProjectListFilter::_search_text_changed);
ClassDB::bind_method(D_METHOD("_filter_option_selected"), &ProjectListFilter::_filter_option_selected);
- ADD_SIGNAL( MethodInfo("filter_changed") );
+ ADD_SIGNAL(MethodInfo("filter_changed"));
}
ProjectListFilter::ProjectListFilter() {
@@ -1497,20 +1452,19 @@ ProjectListFilter::ProjectListFilter() {
_current_filter = FILTER_NAME;
filter_option = memnew(OptionButton);
- filter_option->set_custom_minimum_size(Size2(80,10));
+ filter_option->set_custom_minimum_size(Size2(80, 10));
filter_option->set_clip_text(true);
filter_option->connect("item_selected", this, "_filter_option_selected");
add_child(filter_option);
_setup_filters();
- search_box = memnew( LineEdit );
- search_box->connect("text_changed",this,"_search_text_changed");
+ search_box = memnew(LineEdit);
+ search_box->connect("text_changed", this, "_search_text_changed");
search_box->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(search_box);
- clear_search_button = memnew( ToolButton );
- clear_search_button->connect("pressed",this,"_command",make_binds(CMD_CLEAR_FILTER));
+ clear_search_button = memnew(ToolButton);
+ clear_search_button->connect("pressed", this, "_command", make_binds(CMD_CLEAR_FILTER));
add_child(clear_search_button);
-
}
diff --git a/editor/project_manager.h b/editor/project_manager.h
index cb6c0b7f26..918b76cb01 100644
--- a/editor/project_manager.h
+++ b/editor/project_manager.h
@@ -29,18 +29,18 @@
#ifndef PROJECT_MANAGER_H
#define PROJECT_MANAGER_H
+#include "editor/asset_library_editor_plugin.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/scroll_container.h"
#include "scene/gui/file_dialog.h"
+#include "scene/gui/scroll_container.h"
#include "scene/gui/tool_button.h"
-#include "editor/asset_library_editor_plugin.h"
+#include "scene/gui/tree.h"
class NewProjectDialog;
class ProjectListFilter;
class ProjectManager : public Control {
- GDCLASS( ProjectManager, Control );
+ GDCLASS(ProjectManager, Control);
Button *erase_btn;
Button *open_btn;
@@ -69,8 +69,6 @@ class ProjectManager : public Control {
Control *gui_base;
-
-
void _scan_projects();
void _run_project();
void _run_project_confirm();
@@ -82,26 +80,26 @@ class ProjectManager : public Control {
void _erase_project_confirm();
void _update_project_buttons();
void _exit_dialog();
- void _scan_begin(const String& p_base);
+ void _scan_begin(const String &p_base);
void _load_recent_projects();
- void _on_project_created(const String& dir);
- void _update_scroll_pos(const String& dir);
- void _scan_dir(DirAccess *da,float pos, float total,List<String> *r_projects);
+ void _on_project_created(const String &dir);
+ void _update_scroll_pos(const String &dir);
+ void _scan_dir(DirAccess *da, float pos, float total, List<String> *r_projects);
- void _install_project(const String& p_zip_path,const String& p_title);
+ void _install_project(const String &p_zip_path, const String &p_title);
void _panel_draw(Node *p_hb);
- void _panel_input(const InputEvent& p_ev,Node *p_hb);
- void _unhandled_input(const InputEvent& p_ev);
+ void _panel_input(const InputEvent &p_ev, Node *p_hb);
+ void _unhandled_input(const InputEvent &p_ev);
void _favorite_pressed(Node *p_hb);
void _files_dropped(PoolStringArray p_files, int p_screen);
void _scan_multiple_folders(PoolStringArray p_files);
protected:
-
void _notification(int p_what);
static void _bind_methods();
+
public:
ProjectManager();
~ProjectManager();
@@ -109,10 +107,9 @@ public:
class ProjectListFilter : public HBoxContainer {
- GDCLASS( ProjectListFilter, HBoxContainer );
+ GDCLASS(ProjectListFilter, HBoxContainer);
private:
-
friend class ProjectManager;
enum Command {
@@ -130,7 +127,7 @@ private:
FilterOption _current_filter;
void _command(int p_command);
- void _search_text_changed(const String& p_newtext);
+ void _search_text_changed(const String &p_newtext);
void _setup_filters();
void _filter_option_selected(int p_idx);
@@ -139,7 +136,6 @@ protected:
static void _bind_methods();
public:
-
String get_search_term();
FilterOption get_filter_option();
ProjectListFilter();
diff --git a/editor/project_settings.cpp b/editor/project_settings.cpp
index 15019b8ca8..43c5ccf3a2 100644
--- a/editor/project_settings.cpp
+++ b/editor/project_settings.cpp
@@ -28,36 +28,36 @@
/*************************************************************************/
#include "project_settings.h"
-#include "scene/gui/tab_container.h"
+#include "editor_node.h"
#include "global_config.h"
+#include "global_constants.h"
#include "os/keyboard.h"
-#include "editor_node.h"
#include "scene/gui/margin_container.h"
+#include "scene/gui/tab_container.h"
#include "translation.h"
-#include "global_constants.h"
-ProjectSettings *ProjectSettings::singleton=NULL;
-
-static const char* _button_names[JOY_BUTTON_MAX]={
-"PS X, XBox A, Nintendo B",
-"PS Circle, XBox B, Nintendo A",
-"PS Square, XBox X, Nintendo Y",
-"PS Triangle, XBox Y, Nintendo X",
-"L, L1",
-"R, R1",
-"L2",
-"R2",
-"L3",
-"R3",
-"Select, Nintendo -",
-"Start, Nintendo +",
-"D-Pad Up",
-"D-Pad Down",
-"D-Pad Left",
-"D-Pad Right"
+ProjectSettings *ProjectSettings::singleton = NULL;
+
+static const char *_button_names[JOY_BUTTON_MAX] = {
+ "PS X, XBox A, Nintendo B",
+ "PS Circle, XBox B, Nintendo A",
+ "PS Square, XBox X, Nintendo Y",
+ "PS Triangle, XBox Y, Nintendo X",
+ "L, L1",
+ "R, R1",
+ "L2",
+ "R2",
+ "L3",
+ "R3",
+ "Select, Nintendo -",
+ "Start, Nintendo +",
+ "D-Pad Up",
+ "D-Pad Down",
+ "D-Pad Left",
+ "D-Pad Right"
};
-static const char* _axis_names[JOY_AXIS_MAX*2] = {
+static const char *_axis_names[JOY_AXIS_MAX * 2] = {
" (Left Stick Left)",
" (Left Stick Right)",
" (Left Stick Up)",
@@ -66,7 +66,7 @@ static const char* _axis_names[JOY_AXIS_MAX*2] = {
" (Right Stick Right)",
" (Right Stick Up)",
" (Right Stick Down)",
- "","","","",
+ "", "", "", "",
"", " (L2)",
"", " (R2)"
};
@@ -77,29 +77,29 @@ void ProjectSettings::_notification(int p_what) {
case NOTIFICATION_ENTER_TREE: {
globals_editor->edit(GlobalConfig::get_singleton());
- search_button->set_icon(get_icon("Zoom","EditorIcons"));
- clear_button->set_icon(get_icon("Close","EditorIcons"));
+ search_button->set_icon(get_icon("Zoom", "EditorIcons"));
+ clear_button->set_icon(get_icon("Close", "EditorIcons"));
- translation_list->connect("button_pressed",this,"_translation_delete");
+ translation_list->connect("button_pressed", this, "_translation_delete");
_update_actions();
- popup_add->add_icon_item(get_icon("Keyboard","EditorIcons"),TTR("Key "),InputEvent::KEY);//"Key " - because the word 'key' has already been used as a key animation
- popup_add->add_icon_item(get_icon("JoyButton","EditorIcons"),TTR("Joy Button"),InputEvent::JOYPAD_BUTTON);
- popup_add->add_icon_item(get_icon("JoyAxis","EditorIcons"),TTR("Joy Axis"),InputEvent::JOYPAD_MOTION);
- popup_add->add_icon_item(get_icon("Mouse","EditorIcons"),TTR("Mouse Button"),InputEvent::MOUSE_BUTTON);
+ popup_add->add_icon_item(get_icon("Keyboard", "EditorIcons"), TTR("Key "), InputEvent::KEY); //"Key " - because the word 'key' has already been used as a key animation
+ popup_add->add_icon_item(get_icon("JoyButton", "EditorIcons"), TTR("Joy Button"), InputEvent::JOYPAD_BUTTON);
+ popup_add->add_icon_item(get_icon("JoyAxis", "EditorIcons"), TTR("Joy Axis"), InputEvent::JOYPAD_MOTION);
+ popup_add->add_icon_item(get_icon("Mouse", "EditorIcons"), TTR("Mouse Button"), InputEvent::MOUSE_BUTTON);
List<String> tfn;
- ResourceLoader::get_recognized_extensions_for_type("Translation",&tfn);
- for (List<String>::Element *E=tfn.front();E;E=E->next()) {
+ ResourceLoader::get_recognized_extensions_for_type("Translation", &tfn);
+ for (List<String>::Element *E = tfn.front(); E; E = E->next()) {
- translation_file_open->add_filter("*."+E->get());
+ translation_file_open->add_filter("*." + E->get());
}
List<String> rfn;
- ResourceLoader::get_recognized_extensions_for_type("Resource",&rfn);
- for (List<String>::Element *E=rfn.front();E;E=E->next()) {
+ ResourceLoader::get_recognized_extensions_for_type("Resource", &rfn);
+ for (List<String>::Element *E = rfn.front(); E; E = E->next()) {
- translation_res_file_open->add_filter("*."+E->get());
- translation_res_option_file_open->add_filter("*."+E->get());
+ translation_res_file_open->add_filter("*." + E->get());
+ translation_res_option_file_open->add_filter("*." + E->get());
}
} break;
case NOTIFICATION_POPUP_HIDE: {
@@ -110,164 +110,155 @@ void ProjectSettings::_notification(int p_what) {
void ProjectSettings::_action_selected() {
- TreeItem *ti=input_editor->get_selected();
+ TreeItem *ti = input_editor->get_selected();
if (!ti || !ti->is_editable(0))
return;
- add_at="input/"+ti->get_text(0);
+ add_at = "input/" + ti->get_text(0);
}
void ProjectSettings::_action_edited() {
- TreeItem *ti=input_editor->get_selected();
+ TreeItem *ti = input_editor->get_selected();
if (!ti)
return;
- String new_name=ti->get_text(0);
- String old_name=add_at.substr(add_at.find("/")+1,add_at.length());
+ String new_name = ti->get_text(0);
+ String old_name = add_at.substr(add_at.find("/") + 1, add_at.length());
- if (new_name==old_name)
+ if (new_name == old_name)
return;
- if (new_name.find("/")!=-1 || new_name.find(":")!=-1 || new_name=="") {
+ if (new_name.find("/") != -1 || new_name.find(":") != -1 || new_name == "") {
- ti->set_text(0,old_name);
- add_at="input/"+old_name;
+ ti->set_text(0, old_name);
+ add_at = "input/" + old_name;
message->set_text(TTR("Invalid action (anything goes but '/' or ':')."));
- message->popup_centered(Size2(300,100));
+ message->popup_centered(Size2(300, 100));
return;
}
- String action_prop="input/"+new_name;
+ String action_prop = "input/" + new_name;
if (GlobalConfig::get_singleton()->has(action_prop)) {
- ti->set_text(0,old_name);
- add_at="input/"+old_name;
+ ti->set_text(0, old_name);
+ add_at = "input/" + old_name;
- message->set_text(vformat(TTR("Action '%s' already exists!"),new_name));
- message->popup_centered(Size2(300,100));
+ message->set_text(vformat(TTR("Action '%s' already exists!"), new_name));
+ message->popup_centered(Size2(300, 100));
return;
}
int order = GlobalConfig::get_singleton()->get_order(add_at);
Array va = GlobalConfig::get_singleton()->get(add_at);
- setting=true;
+ setting = true;
undo_redo->create_action(TTR("Rename Input Action Event"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"clear",add_at);
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set",action_prop,va);
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set_order",action_prop,order);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"clear",action_prop);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set",add_at,va);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set_order",add_at,order);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "clear", add_at);
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set", action_prop, va);
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set_order", action_prop, order);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "clear", action_prop);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set", add_at, va);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set_order", add_at, order);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
- setting=false;
-
- add_at=action_prop;
+ setting = false;
+ add_at = action_prop;
}
-
void ProjectSettings::_device_input_add() {
-
-
-
InputEvent ie;
- String name=add_at;
+ String name = add_at;
Variant old_val = GlobalConfig::get_singleton()->get(name);
- Array arr=old_val;
- ie.device=device_id->get_value();
+ Array arr = old_val;
+ ie.device = device_id->get_value();
- ie.type=add_type;
+ ie.type = add_type;
- switch(add_type) {
+ switch (add_type) {
case InputEvent::MOUSE_BUTTON: {
+ ie.mouse_button.button_index = device_index->get_selected() + 1;
- ie.mouse_button.button_index=device_index->get_selected()+1;
-
- for(int i=0;i<arr.size();i++) {
+ for (int i = 0; i < arr.size(); i++) {
- InputEvent aie=arr[i];
- if (aie.device == ie.device && aie.type==InputEvent::MOUSE_BUTTON && aie.mouse_button.button_index==ie.mouse_button.button_index) {
- return;
- }
+ InputEvent aie = arr[i];
+ if (aie.device == ie.device && aie.type == InputEvent::MOUSE_BUTTON && aie.mouse_button.button_index == ie.mouse_button.button_index) {
+ return;
}
+ }
} break;
case InputEvent::JOYPAD_MOTION: {
- ie.joy_motion.axis = device_index->get_selected()>>1;
- ie.joy_motion.axis_value = device_index->get_selected()&1?1:-1;
+ ie.joy_motion.axis = device_index->get_selected() >> 1;
+ ie.joy_motion.axis_value = device_index->get_selected() & 1 ? 1 : -1;
+ for (int i = 0; i < arr.size(); i++) {
- for(int i=0;i<arr.size();i++) {
-
- InputEvent aie=arr[i];
- if (aie.device == ie.device && aie.type==InputEvent::JOYPAD_MOTION && aie.joy_motion.axis==ie.joy_motion.axis && aie.joy_motion.axis_value==ie.joy_motion.axis_value) {
- return;
- }
+ InputEvent aie = arr[i];
+ if (aie.device == ie.device && aie.type == InputEvent::JOYPAD_MOTION && aie.joy_motion.axis == ie.joy_motion.axis && aie.joy_motion.axis_value == ie.joy_motion.axis_value) {
+ return;
}
+ }
} break;
case InputEvent::JOYPAD_BUTTON: {
- ie.joy_button.button_index=device_index->get_selected();
+ ie.joy_button.button_index = device_index->get_selected();
- for(int i=0;i<arr.size();i++) {
+ for (int i = 0; i < arr.size(); i++) {
- InputEvent aie=arr[i];
- if (aie.device == ie.device && aie.type==InputEvent::JOYPAD_BUTTON && aie.joy_button.button_index==ie.joy_button.button_index) {
- return;
- }
+ InputEvent aie = arr[i];
+ if (aie.device == ie.device && aie.type == InputEvent::JOYPAD_BUTTON && aie.joy_button.button_index == ie.joy_button.button_index) {
+ return;
}
+ }
} break;
- default:{}
+ default: {}
}
-
arr.push_back(ie);
undo_redo->create_action(TTR("Add Input Action Event"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set",name,arr);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set",name,old_val);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set", name, arr);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set", name, old_val);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
_show_last_added(ie, name);
}
-
void ProjectSettings::_press_a_key_confirm() {
- if (last_wait_for_key.type!=InputEvent::KEY)
+ if (last_wait_for_key.type != InputEvent::KEY)
return;
InputEvent ie;
- ie.type=InputEvent::KEY;
- ie.key.scancode=last_wait_for_key.key.scancode;
- ie.key.mod=last_wait_for_key.key.mod;
- String name=add_at;
+ ie.type = InputEvent::KEY;
+ ie.key.scancode = last_wait_for_key.key.scancode;
+ ie.key.mod = last_wait_for_key.key.mod;
+ String name = add_at;
Variant old_val = GlobalConfig::get_singleton()->get(name);
- Array arr=old_val;
+ Array arr = old_val;
- for(int i=0;i<arr.size();i++) {
+ for (int i = 0; i < arr.size(); i++) {
- InputEvent aie=arr[i];
- if (aie.type==InputEvent::KEY && aie.key.scancode==ie.key.scancode && aie.key.mod==ie.key.mod) {
+ InputEvent aie = arr[i];
+ if (aie.type == InputEvent::KEY && aie.key.scancode == ie.key.scancode && aie.key.mod == ie.key.mod) {
return;
}
}
@@ -275,85 +266,81 @@ void ProjectSettings::_press_a_key_confirm() {
arr.push_back(ie);
undo_redo->create_action(TTR("Add Input Action Event"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set",name,arr);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set",name,old_val);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set", name, arr);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set", name, old_val);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
_show_last_added(ie, name);
}
-void ProjectSettings::_show_last_added(const InputEvent& p_event, const String &p_name) {
+void ProjectSettings::_show_last_added(const InputEvent &p_event, const String &p_name) {
TreeItem *r = input_editor->get_root();
String name = p_name;
- name.erase(0,6);
+ name.erase(0, 6);
if (!r)
return;
- r=r->get_children();
+ r = r->get_children();
if (!r)
return;
bool found = false;
- while(r){
+ while (r) {
if (r->get_text(0) != name) {
- r=r->get_next();
+ r = r->get_next();
continue;
}
TreeItem *child = r->get_children();
- while(child){
+ while (child) {
Variant input = child->get_meta("__input");
- if (p_event==input){
+ if (p_event == input) {
child->select(0);
found = true;
break;
}
- child=child->get_next();
+ child = child->get_next();
}
if (found) break;
- r=r->get_next();
+ r = r->get_next();
}
if (found) input_editor->ensure_cursor_is_visible();
}
-void ProjectSettings::_wait_for_key(const InputEvent& p_event) {
-
+void ProjectSettings::_wait_for_key(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && p_event.key.pressed && p_event.key.scancode!=0) {
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed && p_event.key.scancode != 0) {
- last_wait_for_key=p_event;
- String str=keycode_get_string(p_event.key.scancode).capitalize();
+ last_wait_for_key = p_event;
+ String str = keycode_get_string(p_event.key.scancode).capitalize();
if (p_event.key.mod.meta)
- str=TTR("Meta+")+str;
+ str = TTR("Meta+") + str;
if (p_event.key.mod.shift)
- str=TTR("Shift+")+str;
+ str = TTR("Shift+") + str;
if (p_event.key.mod.alt)
- str=TTR("Alt+")+str;
+ str = TTR("Alt+") + str;
if (p_event.key.mod.control)
- str=TTR("Control+")+str;
-
+ str = TTR("Control+") + str;
press_a_key_label->set_text(str);
press_a_key->accept_event();
-
}
}
+void ProjectSettings::_add_item(int p_item) {
-void ProjectSettings::_add_item(int p_item){
+ add_type = InputEvent::Type(p_item);
- add_type=InputEvent::Type(p_item);
-
- switch(add_type) {
+ switch (add_type) {
case InputEvent::KEY: {
press_a_key_label->set_text(TTR("Press a Key.."));
- last_wait_for_key=InputEvent();
- press_a_key->popup_centered(Size2(250,80)*EDSCALE);
+ last_wait_for_key = InputEvent();
+ press_a_key->popup_centered(Size2(250, 80) * EDSCALE);
press_a_key->grab_focus();
} break;
case InputEvent::MOUSE_BUTTON: {
@@ -370,19 +357,19 @@ void ProjectSettings::_add_item(int p_item){
device_index->add_item(TTR("Button 7"));
device_index->add_item(TTR("Button 8"));
device_index->add_item(TTR("Button 9"));
- device_input->popup_centered_minsize(Size2(350,95));
+ device_input->popup_centered_minsize(Size2(350, 95));
} break;
case InputEvent::JOYPAD_MOTION: {
device_id->set_value(0);
device_index_label->set_text(TTR("Joypad Axis Index:"));
device_index->clear();
- for(int i=0;i<JOY_AXIS_MAX*2;i++) {
+ for (int i = 0; i < JOY_AXIS_MAX * 2; i++) {
String desc = _axis_names[i];
- device_index->add_item(TTR("Axis")+" "+itos(i/2)+" "+(i&1?"+":"-")+desc);
+ device_index->add_item(TTR("Axis") + " " + itos(i / 2) + " " + (i & 1 ? "+" : "-") + desc);
}
- device_input->popup_centered_minsize(Size2(350,95));
+ device_input->popup_centered_minsize(Size2(350, 95));
} break;
case InputEvent::JOYPAD_BUTTON: {
@@ -391,90 +378,83 @@ void ProjectSettings::_add_item(int p_item){
device_index_label->set_text(TTR("Joypad Button Index:"));
device_index->clear();
- for(int i=0;i<JOY_BUTTON_MAX;i++) {
+ for (int i = 0; i < JOY_BUTTON_MAX; i++) {
- device_index->add_item(itos(i)+": "+String(_button_names[i]));
+ device_index->add_item(itos(i) + ": " + String(_button_names[i]));
}
- device_input->popup_centered_minsize(Size2(350,95));
+ device_input->popup_centered_minsize(Size2(350, 95));
} break;
- default:{}
+ default: {}
}
}
+void ProjectSettings::_action_button_pressed(Object *p_obj, int p_column, int p_id) {
-
-
-void ProjectSettings::_action_button_pressed(Object* p_obj, int p_column,int p_id) {
-
- TreeItem *ti=p_obj->cast_to<TreeItem>();
+ TreeItem *ti = p_obj->cast_to<TreeItem>();
ERR_FAIL_COND(!ti);
- if (p_id==1) {
+ if (p_id == 1) {
Point2 ofs = input_editor->get_global_pos();
- Rect2 ir=input_editor->get_item_rect(ti);
- ir.pos.y-=input_editor->get_scroll().y;
- ofs+=ir.pos+ir.size;
- ofs.x-=100;
+ Rect2 ir = input_editor->get_item_rect(ti);
+ ir.pos.y -= input_editor->get_scroll().y;
+ ofs += ir.pos + ir.size;
+ ofs.x -= 100;
popup_add->set_pos(ofs);
popup_add->popup();
- add_at="input/"+ti->get_text(0);
+ add_at = "input/" + ti->get_text(0);
- } else if (p_id==2) {
+ } else if (p_id == 2) {
//remove
- if (ti->get_parent()==input_editor->get_root()) {
+ if (ti->get_parent() == input_editor->get_root()) {
//remove main thing
- String name="input/"+ti->get_text(0);
+ String name = "input/" + ti->get_text(0);
Variant old_val = GlobalConfig::get_singleton()->get(name);
- int order=GlobalConfig::get_singleton()->get_order(name);
+ int order = GlobalConfig::get_singleton()->get_order(name);
undo_redo->create_action(TTR("Add Input Action"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"clear",name);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set",name,old_val);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set_order",name,order);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "clear", name);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set", name, old_val);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set_order", name, order);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
} else {
//remove action
- String name="input/"+ti->get_parent()->get_text(0);
+ String name = "input/" + ti->get_parent()->get_text(0);
Variant old_val = GlobalConfig::get_singleton()->get(name);
int idx = ti->get_metadata(0);
Array va = old_val;
- ERR_FAIL_INDEX(idx,va.size());
+ ERR_FAIL_INDEX(idx, va.size());
- for(int i=idx;i<va.size()-1;i++) {
+ for (int i = idx; i < va.size() - 1; i++) {
- va[i]=va[i+1];
+ va[i] = va[i + 1];
}
- va.resize(va.size()-1);
-
+ va.resize(va.size() - 1);
undo_redo->create_action(TTR("Erase Input Action Event"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set",name,va);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"set",name,old_val);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set", name, va);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "set", name, old_val);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
}
}
-
}
-
void ProjectSettings::_update_actions() {
if (setting)
@@ -487,100 +467,98 @@ void ProjectSettings::_update_actions() {
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
- const PropertyInfo &pi=E->get();
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.get_slice("/",1);
- if (name=="")
+ String name = pi.name.get_slice("/", 1);
+ if (name == "")
continue;
- TreeItem *item=input_editor->create_item(root);
+ TreeItem *item = input_editor->create_item(root);
//item->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- item->set_text(0,name);
- item->add_button(0,get_icon("Add","EditorIcons"),1);
+ item->set_text(0, name);
+ item->add_button(0, get_icon("Add", "EditorIcons"), 1);
if (!GlobalConfig::get_singleton()->get_input_presets().find(pi.name)) {
- item->add_button(0,get_icon("Remove","EditorIcons"),2);
- item->set_editable(0,true);
+ item->add_button(0, get_icon("Remove", "EditorIcons"), 2);
+ item->set_editable(0, true);
}
- item->set_custom_bg_color(0,get_color("prop_subsection","Editor"));
+ item->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
//item->set_checked(0,pi.usage&PROPERTY_USAGE_CHECKED);
+ Array actions = GlobalConfig::get_singleton()->get(pi.name);
- Array actions=GlobalConfig::get_singleton()->get(pi.name);
-
- for(int i=0;i<actions.size();i++) {
+ for (int i = 0; i < actions.size(); i++) {
- if (actions[i].get_type()!=Variant::INPUT_EVENT)
+ if (actions[i].get_type() != Variant::INPUT_EVENT)
continue;
InputEvent ie = actions[i];
TreeItem *action = input_editor->create_item(item);
- switch(ie.type) {
+ switch (ie.type) {
case InputEvent::KEY: {
- String str=keycode_get_string(ie.key.scancode).capitalize();
+ String str = keycode_get_string(ie.key.scancode).capitalize();
if (ie.key.mod.meta)
- str=TTR("Meta+")+str;
+ str = TTR("Meta+") + str;
if (ie.key.mod.shift)
- str=TTR("Shift+")+str;
+ str = TTR("Shift+") + str;
if (ie.key.mod.alt)
- str=TTR("Alt+")+str;
+ str = TTR("Alt+") + str;
if (ie.key.mod.control)
- str=TTR("Control+")+str;
+ str = TTR("Control+") + str;
- action->set_text(0,str);
- action->set_icon(0,get_icon("Keyboard","EditorIcons"));
+ action->set_text(0, str);
+ action->set_icon(0, get_icon("Keyboard", "EditorIcons"));
} break;
case InputEvent::JOYPAD_BUTTON: {
- String str = TTR("Device")+" "+itos(ie.device)+", "+TTR("Button")+" "+itos(ie.joy_button.button_index);
- if (ie.joy_button.button_index>=0 && ie.joy_button.button_index<JOY_BUTTON_MAX)
- str+=String()+" ("+_button_names[ie.joy_button.button_index]+").";
+ String str = TTR("Device") + " " + itos(ie.device) + ", " + TTR("Button") + " " + itos(ie.joy_button.button_index);
+ if (ie.joy_button.button_index >= 0 && ie.joy_button.button_index < JOY_BUTTON_MAX)
+ str += String() + " (" + _button_names[ie.joy_button.button_index] + ").";
else
- str+=".";
+ str += ".";
- action->set_text(0,str);
- action->set_icon(0,get_icon("JoyButton","EditorIcons"));
+ action->set_text(0, str);
+ action->set_icon(0, get_icon("JoyButton", "EditorIcons"));
} break;
case InputEvent::MOUSE_BUTTON: {
- String str = TTR("Device")+" "+itos(ie.device)+", ";
+ String str = TTR("Device") + " " + itos(ie.device) + ", ";
switch (ie.mouse_button.button_index) {
- case BUTTON_LEFT: str+=TTR("Left Button."); break;
- case BUTTON_RIGHT: str+=TTR("Right Button."); break;
- case BUTTON_MIDDLE: str+=TTR("Middle Button."); break;
- case BUTTON_WHEEL_UP: str+=TTR("Wheel Up."); break;
- case BUTTON_WHEEL_DOWN: str+=TTR("Wheel Down."); break;
- default: str+=TTR("Button")+" "+itos(ie.mouse_button.button_index)+".";
+ case BUTTON_LEFT: str += TTR("Left Button."); break;
+ case BUTTON_RIGHT: str += TTR("Right Button."); break;
+ case BUTTON_MIDDLE: str += TTR("Middle Button."); break;
+ case BUTTON_WHEEL_UP: str += TTR("Wheel Up."); break;
+ case BUTTON_WHEEL_DOWN: str += TTR("Wheel Down."); break;
+ default: str += TTR("Button") + " " + itos(ie.mouse_button.button_index) + ".";
}
- action->set_text(0,str);
- action->set_icon(0,get_icon("Mouse","EditorIcons"));
+ action->set_text(0, str);
+ action->set_icon(0, get_icon("Mouse", "EditorIcons"));
} break;
case InputEvent::JOYPAD_MOTION: {
int ax = ie.joy_motion.axis;
- int n = 2*ax + (ie.joy_motion.axis_value<0 ? 0:1);
+ int n = 2 * ax + (ie.joy_motion.axis_value < 0 ? 0 : 1);
String desc = _axis_names[n];
- String str = TTR("Device")+" "+itos(ie.device)+", "+TTR("Axis")+" "+itos(ax)+" "+(ie.joy_motion.axis_value<0?"-":"+")+desc +".";
- action->set_text(0,str);
- action->set_icon(0,get_icon("JoyAxis","EditorIcons"));
+ String str = TTR("Device") + " " + itos(ie.device) + ", " + TTR("Axis") + " " + itos(ax) + " " + (ie.joy_motion.axis_value < 0 ? "-" : "+") + desc + ".";
+ action->set_text(0, str);
+ action->set_icon(0, get_icon("JoyAxis", "EditorIcons"));
} break;
}
- action->add_button(0,get_icon("Remove","EditorIcons"),2);
- action->set_metadata(0,i);
+ action->add_button(0, get_icon("Remove", "EditorIcons"), 2);
+ action->set_metadata(0, i);
action->set_meta("__input", ie);
}
}
}
-
void ProjectSettings::popup_project_settings() {
// Restore valid window bounds or pop up at default size.
@@ -595,10 +573,8 @@ void ProjectSettings::popup_project_settings() {
plugin_settings->update_plugins();
}
-
void ProjectSettings::_item_selected() {
-
TreeItem *ti = globals_editor->get_property_editor()->get_scene_tree()->get_selected();
if (!ti)
return;
@@ -607,11 +583,8 @@ void ProjectSettings::_item_selected() {
category->set_text(globals_editor->get_current_section());
property->set_text(ti->get_text(0));
popup_platform->set_disabled(false);
-
-
}
-
void ProjectSettings::_item_adds(String) {
_item_add();
@@ -620,11 +593,11 @@ void ProjectSettings::_item_adds(String) {
void ProjectSettings::_item_add() {
Variant value;
- switch(type->get_selected()) {
- case 0: value=false; break;
- case 1: value=0; break;
- case 2: value=0.0; break;
- case 3: value=""; break;
+ switch (type->get_selected()) {
+ case 0: value = false; break;
+ case 1: value = 0; break;
+ case 2: value = 0.0; break;
+ case 3: value = ""; break;
}
String catname = category->get_text().strip_edges();
@@ -641,7 +614,7 @@ void ProjectSettings::_item_add() {
return;
}*/
- String name = catname!="" ? catname+"/"+propname : propname;
+ String name = catname != "" ? catname + "/" + propname : propname;
undo_redo->create_action("Add Global Property");
@@ -673,7 +646,7 @@ void ProjectSettings::_item_del() {
String propname = property->get_text().strip_edges();
//ERR_FAIL_COND(!propname.is_valid_identifier());
- String name = catname!="" ? catname+"/"+propname : propname;
+ String name = catname != "" ? catname + "/" + propname : propname;
undo_redo->create_action("Delete Global Property");
@@ -700,64 +673,56 @@ void ProjectSettings::_action_adds(String) {
void ProjectSettings::_action_add() {
String action = action_name->get_text();
- if (action.find("/")!=-1 || action.find(":")!=-1 || action=="") {
+ if (action.find("/") != -1 || action.find(":") != -1 || action == "") {
message->set_text(TTR("Invalid action (anything goes but '/' or ':')."));
- message->popup_centered(Size2(300,100));
+ message->popup_centered(Size2(300, 100));
return;
}
- if (GlobalConfig::get_singleton()->has("input/"+action)) {
- message->set_text(vformat(TTR("Action '%s' already exists!"),action));
- message->popup_centered(Size2(300,100));
+ if (GlobalConfig::get_singleton()->has("input/" + action)) {
+ message->set_text(vformat(TTR("Action '%s' already exists!"), action));
+ message->popup_centered(Size2(300, 100));
return;
}
Array va;
- String name = "input/"+action;
+ String name = "input/" + action;
undo_redo->create_action(TTR("Add Input Action Event"));
- undo_redo->add_do_method(GlobalConfig::get_singleton(),"set",name,va);
- undo_redo->add_undo_method(GlobalConfig::get_singleton(),"clear",name);
- undo_redo->add_do_method(this,"_update_actions");
- undo_redo->add_undo_method(this,"_update_actions");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_method(GlobalConfig::get_singleton(), "set", name, va);
+ undo_redo->add_undo_method(GlobalConfig::get_singleton(), "clear", name);
+ undo_redo->add_do_method(this, "_update_actions");
+ undo_redo->add_undo_method(this, "_update_actions");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
TreeItem *r = input_editor->get_root();
if (!r)
return;
- r=r->get_children();
+ r = r->get_children();
if (!r)
return;
- while(r->get_next())
- r=r->get_next();
+ while (r->get_next())
+ r = r->get_next();
if (!r)
return;
r->select(0);
input_editor->ensure_cursor_is_visible();
-
}
-
-void ProjectSettings::_item_checked(const String& p_item, bool p_check) {
-
-
-
+void ProjectSettings::_item_checked(const String &p_item, bool p_check) {
}
-
void ProjectSettings::_save() {
Error err = GlobalConfig::get_singleton()->save();
- message->set_text(err!=OK?TTR("Error saving settings."):TTR("Settings saved OK."));
- message->popup_centered(Size2(300,100));
+ message->set_text(err != OK ? TTR("Error saving settings.") : TTR("Settings saved OK."));
+ message->popup_centered(Size2(300, 100));
}
-
-
-void ProjectSettings::_settings_prop_edited(const String& p_name) {
+void ProjectSettings::_settings_prop_edited(const String &p_name) {
String full_item = globals_editor->get_full_item_path(p_name);
@@ -773,62 +738,56 @@ void ProjectSettings::queue_save() {
_settings_changed();
}
-
void ProjectSettings::_copy_to_platform(int p_which) {
String catname = category->get_text();
if (!catname.is_valid_identifier()) {
message->set_text("Invalid Category.\nValid characters: a-z,A-Z,0-9 or _");
- message->popup_centered(Size2(300,100));
+ message->popup_centered(Size2(300, 100));
return;
}
-
String propname = property->get_text();
if (!propname.is_valid_identifier()) {
message->set_text("Invalid Property.\nValid characters: a-z,A-Z,0-9 or _");
- message->popup_centered(Size2(300,100));
+ message->popup_centered(Size2(300, 100));
return;
}
- String name = catname+"/"+propname;
- Variant value=GlobalConfig::get_singleton()->get(name);
+ String name = catname + "/" + propname;
+ Variant value = GlobalConfig::get_singleton()->get(name);
- catname+="."+popup_platform->get_popup()->get_item_text(p_which);
- name = catname+"/"+propname;
+ catname += "." + popup_platform->get_popup()->get_item_text(p_which);
+ name = catname + "/" + propname;
- GlobalConfig::get_singleton()->set(name,value);
+ GlobalConfig::get_singleton()->set(name, value);
globals_editor->get_property_editor()->update_tree();
-
}
-
-void ProjectSettings::add_translation(const String& p_translation) {
+void ProjectSettings::add_translation(const String &p_translation) {
_translation_add(p_translation);
}
-void ProjectSettings::_translation_add(const String& p_path) {
+void ProjectSettings::_translation_add(const String &p_path) {
PoolStringArray translations = GlobalConfig::get_singleton()->get("locale/translations");
+ for (int i = 0; i < translations.size(); i++) {
- for(int i=0;i<translations.size();i++) {
-
- if (translations[i]==p_path)
+ if (translations[i] == p_path)
return; //exists
}
translations.push_back(p_path);
undo_redo->create_action(TTR("Add Translation"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translations",translations);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translations",GlobalConfig::get_singleton()->get("locale/translations"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translations", translations);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translations", GlobalConfig::get_singleton()->get("locale/translations"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
}
void ProjectSettings::_translation_file_open() {
@@ -836,69 +795,64 @@ void ProjectSettings::_translation_file_open() {
translation_file_open->popup_centered_ratio();
}
-void ProjectSettings::_translation_delete(Object *p_item,int p_column, int p_button) {
+void ProjectSettings::_translation_delete(Object *p_item, int p_column, int p_button) {
TreeItem *ti = p_item->cast_to<TreeItem>();
ERR_FAIL_COND(!ti);
- int idx=ti->get_metadata(0);
+ int idx = ti->get_metadata(0);
PoolStringArray translations = GlobalConfig::get_singleton()->get("locale/translations");
- ERR_FAIL_INDEX(idx,translations.size());
+ ERR_FAIL_INDEX(idx, translations.size());
translations.remove(idx);
undo_redo->create_action(TTR("Remove Translation"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translations",translations);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translations",GlobalConfig::get_singleton()->get("locale/translations"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translations", translations);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translations", GlobalConfig::get_singleton()->get("locale/translations"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
-
}
void ProjectSettings::_translation_res_file_open() {
translation_res_file_open->popup_centered_ratio();
-
}
-void ProjectSettings::_translation_res_add(const String& p_path){
+void ProjectSettings::_translation_res_add(const String &p_path) {
Variant prev;
Dictionary remaps;
if (GlobalConfig::get_singleton()->has("locale/translation_remaps")) {
remaps = GlobalConfig::get_singleton()->get("locale/translation_remaps");
- prev=remaps;
+ prev = remaps;
}
if (remaps.has(p_path))
return; //pointless already has it
- remaps[p_path]=PoolStringArray();
+ remaps[p_path] = PoolStringArray();
undo_redo->create_action(TTR("Add Remapped Path"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translation_remaps",remaps);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translation_remaps",prev);
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translation_remaps", remaps);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translation_remaps", prev);
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
}
-void ProjectSettings::_translation_res_option_file_open(){
+void ProjectSettings::_translation_res_option_file_open() {
translation_res_option_file_open->popup_centered_ratio();
-
}
-void ProjectSettings::_translation_res_option_add(const String& p_path) {
+void ProjectSettings::_translation_res_option_add(const String &p_path) {
ERR_FAIL_COND(!GlobalConfig::get_singleton()->has("locale/translation_remaps"));
@@ -911,29 +865,24 @@ void ProjectSettings::_translation_res_option_add(const String& p_path) {
ERR_FAIL_COND(!remaps.has(key));
PoolStringArray r = remaps[key];
- r.push_back(p_path+":"+"en");
- remaps[key]=r;
-
+ r.push_back(p_path + ":" + "en");
+ remaps[key] = r;
undo_redo->create_action(TTR("Resource Remap Add Remap"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translation_remaps",remaps);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translation_remaps",GlobalConfig::get_singleton()->get("locale/translation_remaps"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translation_remaps", remaps);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translation_remaps", GlobalConfig::get_singleton()->get("locale/translation_remaps"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
}
-
-
void ProjectSettings::_translation_res_select() {
if (updating_translations)
return;
-
call_deferred("_update_translations");
}
@@ -959,31 +908,27 @@ void ProjectSettings::_translation_res_option_changed() {
Vector<String> langs = TranslationServer::get_all_locales();
- ERR_FAIL_INDEX(which,langs.size());
-
+ ERR_FAIL_INDEX(which, langs.size());
ERR_FAIL_COND(!remaps.has(key));
PoolStringArray r = remaps[key];
- ERR_FAIL_INDEX(idx,r.size());
- r.set(idx,path+":"+langs[which]);
- remaps[key]=r;
+ ERR_FAIL_INDEX(idx, r.size());
+ r.set(idx, path + ":" + langs[which]);
+ remaps[key] = r;
- updating_translations=true;
+ updating_translations = true;
undo_redo->create_action(TTR("Change Resource Remap Language"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translation_remaps",remaps);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translation_remaps",GlobalConfig::get_singleton()->get("locale/translation_remaps"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translation_remaps", remaps);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translation_remaps", GlobalConfig::get_singleton()->get("locale/translation_remaps"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
- updating_translations=false;
-
+ updating_translations = false;
}
-
-void ProjectSettings::_translation_res_delete(Object *p_item,int p_column, int p_button) {
-
+void ProjectSettings::_translation_res_delete(Object *p_item, int p_column, int p_button) {
if (updating_translations)
return;
@@ -1001,16 +946,16 @@ void ProjectSettings::_translation_res_delete(Object *p_item,int p_column, int p
remaps.erase(key);
undo_redo->create_action(TTR("Remove Resource Remap"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translation_remaps",remaps);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translation_remaps",GlobalConfig::get_singleton()->get("locale/translation_remaps"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translation_remaps", remaps);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translation_remaps", GlobalConfig::get_singleton()->get("locale/translation_remaps"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
}
-void ProjectSettings::_translation_res_option_delete(Object *p_item,int p_column, int p_button) {
+void ProjectSettings::_translation_res_option_delete(Object *p_item, int p_column, int p_button) {
if (updating_translations)
return;
@@ -1030,20 +975,18 @@ void ProjectSettings::_translation_res_option_delete(Object *p_item,int p_column
ERR_FAIL_COND(!remaps.has(key));
PoolStringArray r = remaps[key];
- ERR_FAIL_INDEX(idx,remaps.size());
+ ERR_FAIL_INDEX(idx, remaps.size());
r.remove(idx);
- remaps[key]=r;
-
+ remaps[key] = r;
undo_redo->create_action(TTR("Remove Resource Remap Option"));
- undo_redo->add_do_property(GlobalConfig::get_singleton(),"locale/translation_remaps",remaps);
- undo_redo->add_undo_property(GlobalConfig::get_singleton(),"locale/translation_remaps",GlobalConfig::get_singleton()->get("locale/translation_remaps"));
- undo_redo->add_do_method(this,"_update_translations");
- undo_redo->add_undo_method(this,"_update_translations");
- undo_redo->add_do_method(this,"_settings_changed");
- undo_redo->add_undo_method(this,"_settings_changed");
+ undo_redo->add_do_property(GlobalConfig::get_singleton(), "locale/translation_remaps", remaps);
+ undo_redo->add_undo_property(GlobalConfig::get_singleton(), "locale/translation_remaps", GlobalConfig::get_singleton()->get("locale/translation_remaps"));
+ undo_redo->add_do_method(this, "_update_translations");
+ undo_redo->add_undo_method(this, "_update_translations");
+ undo_redo->add_do_method(this, "_settings_changed");
+ undo_redo->add_undo_method(this, "_settings_changed");
undo_redo->commit_action();
-
}
void ProjectSettings::_update_translations() {
@@ -1053,7 +996,7 @@ void ProjectSettings::_update_translations() {
if (updating_translations)
return;
- updating_translations=true;
+ updating_translations = true;
translation_list->clear();
TreeItem *root = translation_list->create_item(NULL);
@@ -1061,18 +1004,17 @@ void ProjectSettings::_update_translations() {
if (GlobalConfig::get_singleton()->has("locale/translations")) {
PoolStringArray translations = GlobalConfig::get_singleton()->get("locale/translations");
- for(int i=0;i<translations.size();i++) {
+ for (int i = 0; i < translations.size(); i++) {
TreeItem *t = translation_list->create_item(root);
- t->set_editable(0,false);
- t->set_text(0,translations[i].replace_first("res://",""));
- t->set_tooltip(0,translations[i]);
- t->set_metadata(0,i);
- t->add_button(0,get_icon("Del","EditorIcons"),0);
+ t->set_editable(0, false);
+ t->set_text(0, translations[i].replace_first("res://", ""));
+ t->set_tooltip(0, translations[i]);
+ t->set_metadata(0, i);
+ t->add_button(0, get_icon("Del", "EditorIcons"), 0);
}
}
-
//update translation remaps
String remap_selected;
@@ -1091,10 +1033,10 @@ void ProjectSettings::_update_translations() {
Vector<String> langs = TranslationServer::get_all_locales();
Vector<String> names = TranslationServer::get_all_locale_names();
String langnames;
- for(int i=0;i<names.size();i++) {
- if (i>0)
- langnames+=",";
- langnames+=names[i];
+ for (int i = 0; i < names.size(); i++) {
+ if (i > 0)
+ langnames += ",";
+ langnames += names[i];
}
if (GlobalConfig::get_singleton()->has("locale/translation_remaps")) {
@@ -1103,57 +1045,53 @@ void ProjectSettings::_update_translations() {
List<Variant> rk;
remaps.get_key_list(&rk);
Vector<String> keys;
- for(List<Variant>::Element *E=rk.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = rk.front(); E; E = E->next()) {
keys.push_back(E->get());
}
keys.sort();
- for(int i=0;i<keys.size();i++) {
+ for (int i = 0; i < keys.size(); i++) {
TreeItem *t = translation_remap->create_item(root);
- t->set_editable(0,false);
- t->set_text(0,keys[i].replace_first("res://",""));
- t->set_tooltip(0,keys[i]);
- t->set_metadata(0,keys[i]);
- t->add_button(0,get_icon("Del","EditorIcons"),0);
- if (keys[i]==remap_selected) {
+ t->set_editable(0, false);
+ t->set_text(0, keys[i].replace_first("res://", ""));
+ t->set_tooltip(0, keys[i]);
+ t->set_metadata(0, keys[i]);
+ t->add_button(0, get_icon("Del", "EditorIcons"), 0);
+ if (keys[i] == remap_selected) {
t->select(0);
translation_res_option_add_button->set_disabled(false);
PoolStringArray selected = remaps[keys[i]];
- for(int j=0;j<selected.size();j++) {
+ for (int j = 0; j < selected.size(); j++) {
String s = selected[j];
int qp = s.find_last(":");
- String path = s.substr(0,qp);
- String locale = s.substr(qp+1,s.length());
+ String path = s.substr(0, qp);
+ String locale = s.substr(qp + 1, s.length());
TreeItem *t2 = translation_remap_options->create_item(root2);
- t2->set_editable(0,false);
- t2->set_text(0,path.replace_first("res://",""));
- t2->set_tooltip(0,path);
- t2->set_metadata(0,j);
- t2->add_button(0,get_icon("Del","EditorIcons"),0);
- t2->set_cell_mode(1,TreeItem::CELL_MODE_RANGE);
- t2->set_text(1,langnames);
- t2->set_editable(1,true);
- t2->set_metadata(1,path);
+ t2->set_editable(0, false);
+ t2->set_text(0, path.replace_first("res://", ""));
+ t2->set_tooltip(0, path);
+ t2->set_metadata(0, j);
+ t2->add_button(0, get_icon("Del", "EditorIcons"), 0);
+ t2->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
+ t2->set_text(1, langnames);
+ t2->set_editable(1, true);
+ t2->set_metadata(1, path);
int idx = langs.find(locale);
- print_line("find "+locale+" at "+itos(idx));
- if (idx<0)
- idx=0;
+ print_line("find " + locale + " at " + itos(idx));
+ if (idx < 0)
+ idx = 0;
- t2->set_range(1,idx);
+ t2->set_range(1, idx);
}
}
-
-
}
}
-
- updating_translations=false;
-
+ updating_translations = false;
}
void ProjectSettings::_toggle_search_bar(bool p_pressed) {
@@ -1175,7 +1113,7 @@ void ProjectSettings::_toggle_search_bar(bool p_pressed) {
void ProjectSettings::_clear_search_box() {
- if (search_box->get_text()=="")
+ if (search_box->get_text() == "")
return;
search_box->clear();
@@ -1184,60 +1122,57 @@ void ProjectSettings::_clear_search_box() {
void ProjectSettings::set_plugins_page() {
- tab_container->set_current_tab( plugin_settings->get_index() );
+ tab_container->set_current_tab(plugin_settings->get_index());
}
void ProjectSettings::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_item_selected"),&ProjectSettings::_item_selected);
- ClassDB::bind_method(D_METHOD("_item_add"),&ProjectSettings::_item_add);
- ClassDB::bind_method(D_METHOD("_item_adds"),&ProjectSettings::_item_adds);
- ClassDB::bind_method(D_METHOD("_item_del"),&ProjectSettings::_item_del);
- ClassDB::bind_method(D_METHOD("_item_checked"),&ProjectSettings::_item_checked);
- ClassDB::bind_method(D_METHOD("_save"),&ProjectSettings::_save);
- ClassDB::bind_method(D_METHOD("_action_add"),&ProjectSettings::_action_add);
- ClassDB::bind_method(D_METHOD("_action_adds"),&ProjectSettings::_action_adds);
- ClassDB::bind_method(D_METHOD("_action_selected"),&ProjectSettings::_action_selected);
- ClassDB::bind_method(D_METHOD("_action_edited"),&ProjectSettings::_action_edited);
- ClassDB::bind_method(D_METHOD("_action_button_pressed"),&ProjectSettings::_action_button_pressed);
- ClassDB::bind_method(D_METHOD("_update_actions"),&ProjectSettings::_update_actions);
- ClassDB::bind_method(D_METHOD("_wait_for_key"),&ProjectSettings::_wait_for_key);
- ClassDB::bind_method(D_METHOD("_add_item"),&ProjectSettings::_add_item);
- ClassDB::bind_method(D_METHOD("_device_input_add"),&ProjectSettings::_device_input_add);
- ClassDB::bind_method(D_METHOD("_press_a_key_confirm"),&ProjectSettings::_press_a_key_confirm);
- ClassDB::bind_method(D_METHOD("_settings_prop_edited"),&ProjectSettings::_settings_prop_edited);
- ClassDB::bind_method(D_METHOD("_copy_to_platform"),&ProjectSettings::_copy_to_platform);
- ClassDB::bind_method(D_METHOD("_update_translations"),&ProjectSettings::_update_translations);
- ClassDB::bind_method(D_METHOD("_translation_delete"),&ProjectSettings::_translation_delete);
- ClassDB::bind_method(D_METHOD("_settings_changed"),&ProjectSettings::_settings_changed);
- ClassDB::bind_method(D_METHOD("_translation_add"),&ProjectSettings::_translation_add);
- ClassDB::bind_method(D_METHOD("_translation_file_open"),&ProjectSettings::_translation_file_open);
-
- ClassDB::bind_method(D_METHOD("_translation_res_add"),&ProjectSettings::_translation_res_add);
- ClassDB::bind_method(D_METHOD("_translation_res_file_open"),&ProjectSettings::_translation_res_file_open);
- ClassDB::bind_method(D_METHOD("_translation_res_option_add"),&ProjectSettings::_translation_res_option_add);
- ClassDB::bind_method(D_METHOD("_translation_res_option_file_open"),&ProjectSettings::_translation_res_option_file_open);
- ClassDB::bind_method(D_METHOD("_translation_res_select"),&ProjectSettings::_translation_res_select);
- ClassDB::bind_method(D_METHOD("_translation_res_option_changed"),&ProjectSettings::_translation_res_option_changed);
- ClassDB::bind_method(D_METHOD("_translation_res_delete"),&ProjectSettings::_translation_res_delete);
- ClassDB::bind_method(D_METHOD("_translation_res_option_delete"),&ProjectSettings::_translation_res_option_delete);
-
- ClassDB::bind_method(D_METHOD("_clear_search_box"),&ProjectSettings::_clear_search_box);
- ClassDB::bind_method(D_METHOD("_toggle_search_bar"),&ProjectSettings::_toggle_search_bar);
-
+ ClassDB::bind_method(D_METHOD("_item_selected"), &ProjectSettings::_item_selected);
+ ClassDB::bind_method(D_METHOD("_item_add"), &ProjectSettings::_item_add);
+ ClassDB::bind_method(D_METHOD("_item_adds"), &ProjectSettings::_item_adds);
+ ClassDB::bind_method(D_METHOD("_item_del"), &ProjectSettings::_item_del);
+ ClassDB::bind_method(D_METHOD("_item_checked"), &ProjectSettings::_item_checked);
+ ClassDB::bind_method(D_METHOD("_save"), &ProjectSettings::_save);
+ ClassDB::bind_method(D_METHOD("_action_add"), &ProjectSettings::_action_add);
+ ClassDB::bind_method(D_METHOD("_action_adds"), &ProjectSettings::_action_adds);
+ ClassDB::bind_method(D_METHOD("_action_selected"), &ProjectSettings::_action_selected);
+ ClassDB::bind_method(D_METHOD("_action_edited"), &ProjectSettings::_action_edited);
+ ClassDB::bind_method(D_METHOD("_action_button_pressed"), &ProjectSettings::_action_button_pressed);
+ ClassDB::bind_method(D_METHOD("_update_actions"), &ProjectSettings::_update_actions);
+ ClassDB::bind_method(D_METHOD("_wait_for_key"), &ProjectSettings::_wait_for_key);
+ ClassDB::bind_method(D_METHOD("_add_item"), &ProjectSettings::_add_item);
+ ClassDB::bind_method(D_METHOD("_device_input_add"), &ProjectSettings::_device_input_add);
+ ClassDB::bind_method(D_METHOD("_press_a_key_confirm"), &ProjectSettings::_press_a_key_confirm);
+ ClassDB::bind_method(D_METHOD("_settings_prop_edited"), &ProjectSettings::_settings_prop_edited);
+ ClassDB::bind_method(D_METHOD("_copy_to_platform"), &ProjectSettings::_copy_to_platform);
+ ClassDB::bind_method(D_METHOD("_update_translations"), &ProjectSettings::_update_translations);
+ ClassDB::bind_method(D_METHOD("_translation_delete"), &ProjectSettings::_translation_delete);
+ ClassDB::bind_method(D_METHOD("_settings_changed"), &ProjectSettings::_settings_changed);
+ ClassDB::bind_method(D_METHOD("_translation_add"), &ProjectSettings::_translation_add);
+ ClassDB::bind_method(D_METHOD("_translation_file_open"), &ProjectSettings::_translation_file_open);
+
+ ClassDB::bind_method(D_METHOD("_translation_res_add"), &ProjectSettings::_translation_res_add);
+ ClassDB::bind_method(D_METHOD("_translation_res_file_open"), &ProjectSettings::_translation_res_file_open);
+ ClassDB::bind_method(D_METHOD("_translation_res_option_add"), &ProjectSettings::_translation_res_option_add);
+ ClassDB::bind_method(D_METHOD("_translation_res_option_file_open"), &ProjectSettings::_translation_res_option_file_open);
+ ClassDB::bind_method(D_METHOD("_translation_res_select"), &ProjectSettings::_translation_res_select);
+ ClassDB::bind_method(D_METHOD("_translation_res_option_changed"), &ProjectSettings::_translation_res_option_changed);
+ ClassDB::bind_method(D_METHOD("_translation_res_delete"), &ProjectSettings::_translation_res_delete);
+ ClassDB::bind_method(D_METHOD("_translation_res_option_delete"), &ProjectSettings::_translation_res_option_delete);
+
+ ClassDB::bind_method(D_METHOD("_clear_search_box"), &ProjectSettings::_clear_search_box);
+ ClassDB::bind_method(D_METHOD("_toggle_search_bar"), &ProjectSettings::_toggle_search_bar);
}
ProjectSettings::ProjectSettings(EditorData *p_data) {
-
- singleton=this;
+ singleton = this;
set_title(TTR("Project Settings (godot.cfg)"));
set_resizable(true);
- undo_redo=&p_data->get_undo_redo();
- data=p_data;
-
+ undo_redo = &p_data->get_undo_redo();
+ data = p_data;
- tab_container = memnew( TabContainer );
+ tab_container = memnew(TabContainer);
add_child(tab_container);
//set_child_rect(tab_container);
@@ -1246,52 +1181,52 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
//tab_container->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 15 );
//tab_container->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 );
- VBoxContainer *props_base = memnew( VBoxContainer );
+ VBoxContainer *props_base = memnew(VBoxContainer);
props_base->set_alignment(BoxContainer::ALIGN_BEGIN);
props_base->set_v_size_flags(Control::SIZE_EXPAND_FILL);
tab_container->add_child(props_base);
props_base->set_name(TTR("General"));
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
props_base->add_child(hbc);
- search_button = memnew( ToolButton );
+ search_button = memnew(ToolButton);
search_button->set_toggle_mode(true);
search_button->set_pressed(false);
search_button->set_text(TTR("Search"));
hbc->add_child(search_button);
- search_button->connect("toggled",this,"_toggle_search_bar");
+ search_button->connect("toggled", this, "_toggle_search_bar");
- hbc->add_child( memnew( VSeparator ) );
+ hbc->add_child(memnew(VSeparator));
- add_prop_bar = memnew( HBoxContainer );
+ add_prop_bar = memnew(HBoxContainer);
add_prop_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(add_prop_bar);
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
add_prop_bar->add_child(l);
l->set_text(TTR("Category:"));
- category = memnew( LineEdit );
+ category = memnew(LineEdit);
category->set_h_size_flags(Control::SIZE_EXPAND_FILL);
add_prop_bar->add_child(category);
- category->connect("text_entered",this,"_item_adds");
+ category->connect("text_entered", this, "_item_adds");
- l = memnew( Label );
+ l = memnew(Label);
add_prop_bar->add_child(l);
l->set_text(TTR("Property:"));
- property = memnew( LineEdit );
+ property = memnew(LineEdit);
property->set_h_size_flags(Control::SIZE_EXPAND_FILL);
add_prop_bar->add_child(property);
- property->connect("text_entered",this,"_item_adds");
+ property->connect("text_entered", this, "_item_adds");
- l = memnew( Label );
+ l = memnew(Label);
add_prop_bar->add_child(l);
l->set_text(TTR("Type:"));
- type = memnew( OptionButton );
+ type = memnew(OptionButton);
type->set_h_size_flags(Control::SIZE_EXPAND_FILL);
add_prop_bar->add_child(type);
type->add_item("bool");
@@ -1299,41 +1234,41 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
type->add_item("float");
type->add_item("string");
- Button *add = memnew( Button );
+ Button *add = memnew(Button);
add_prop_bar->add_child(add);
add->set_text(TTR("Add"));
- add->connect("pressed",this,"_item_add");
+ add->connect("pressed", this, "_item_add");
- Button *del = memnew( Button );
+ Button *del = memnew(Button);
add_prop_bar->add_child(del);
del->set_text(TTR("Del"));
- del->connect("pressed",this,"_item_del");
+ del->connect("pressed", this, "_item_del");
- search_bar = memnew( HBoxContainer );
+ search_bar = memnew(HBoxContainer);
search_bar->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(search_bar);
search_bar->hide();
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
search_bar->add_child(search_box);
- clear_button = memnew( ToolButton );
+ clear_button = memnew(ToolButton);
search_bar->add_child(clear_button);
- clear_button->connect("pressed",this,"_clear_search_box");
+ clear_button->connect("pressed", this, "_clear_search_box");
- globals_editor = memnew( SectionedPropertyEditor );
+ globals_editor = memnew(SectionedPropertyEditor);
props_base->add_child(globals_editor);
globals_editor->get_property_editor()->set_undo_redo(EditorNode::get_singleton()->get_undo_redo());
//globals_editor->hide_top_label();
globals_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
globals_editor->get_property_editor()->register_text_enter(search_box);
globals_editor->get_property_editor()->set_capitalize_paths(false);
- globals_editor->get_property_editor()->get_scene_tree()->connect("cell_selected",this,"_item_selected");
- globals_editor->get_property_editor()->connect("property_toggled",this,"_item_checked",varray(),CONNECT_DEFERRED);
- globals_editor->get_property_editor()->connect("property_edited",this,"_settings_prop_edited");
+ globals_editor->get_property_editor()->get_scene_tree()->connect("cell_selected", this, "_item_selected");
+ globals_editor->get_property_editor()->connect("property_toggled", this, "_item_checked", varray(), CONNECT_DEFERRED);
+ globals_editor->get_property_editor()->connect("property_edited", this, "_settings_prop_edited");
-/*
+ /*
Button *save = memnew( Button );
props_base->add_child(save);
@@ -1347,10 +1282,10 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
save->connect("pressed",this,"_save");
*/
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
props_base->add_child(hbc);
- popup_platform = memnew( MenuButton );
+ popup_platform = memnew(MenuButton);
popup_platform->set_text(TTR("Copy To Platform.."));
popup_platform->set_disabled(true);
hbc->add_child(popup_platform);
@@ -1367,102 +1302,101 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
}*/
- popup_platform->get_popup()->connect("id_pressed",this,"_copy_to_platform");
+ popup_platform->get_popup()->connect("id_pressed", this, "_copy_to_platform");
get_ok()->set_text(TTR("Close"));
set_hide_on_ok(true);
- message = memnew( ConfirmationDialog );
+ message = memnew(ConfirmationDialog);
add_child(message);
//message->get_cancel()->hide();
message->set_hide_on_ok(true);
- Control *input_base = memnew( Control );
+ Control *input_base = memnew(Control);
input_base->set_name(TTR("Input Map"));
input_base->set_area_as_parent_rect();
tab_container->add_child(input_base);
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
input_base->add_child(vbc);
- vbc->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 5 );
- vbc->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 5 );
- vbc->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN, 5 );
- vbc->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END, 5 );
+ vbc->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 5);
+ vbc->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 5);
+ vbc->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 5);
+ vbc->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 5);
- l = memnew( Label );
+ l = memnew(Label);
vbc->add_child(l);
- l->set_pos(Point2(6,5));
+ l->set_pos(Point2(6, 5));
l->set_text(TTR("Action:"));
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
- action_name = memnew( LineEdit );
+ action_name = memnew(LineEdit);
action_name->set_h_size_flags(SIZE_EXPAND_FILL);
hbc->add_child(action_name);
- action_name->connect("text_entered",this,"_action_adds");
+ action_name->connect("text_entered", this, "_action_adds");
- add = memnew( Button );
+ add = memnew(Button);
hbc->add_child(add);
add->set_custom_minimum_size(Size2(150, 0));
add->set_text(TTR("Add"));
- add->connect("pressed",this,"_action_add");
+ add->connect("pressed", this, "_action_add");
- input_editor = memnew( Tree );
+ input_editor = memnew(Tree);
vbc->add_child(input_editor);
input_editor->set_v_size_flags(SIZE_EXPAND_FILL);
- input_editor->connect("item_edited",this,"_action_edited");
- input_editor->connect("cell_selected",this,"_action_selected");
- input_editor->connect("button_pressed",this,"_action_button_pressed");
- popup_add = memnew( PopupMenu );
+ input_editor->connect("item_edited", this, "_action_edited");
+ input_editor->connect("cell_selected", this, "_action_selected");
+ input_editor->connect("button_pressed", this, "_action_button_pressed");
+ popup_add = memnew(PopupMenu);
add_child(popup_add);
- popup_add->connect("id_pressed",this,"_add_item");
+ popup_add->connect("id_pressed", this, "_add_item");
- press_a_key = memnew( ConfirmationDialog );
+ press_a_key = memnew(ConfirmationDialog);
press_a_key->set_focus_mode(FOCUS_ALL);
add_child(press_a_key);
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Press a Key.."));
l->set_area_as_parent_rect();
l->set_align(Label::ALIGN_CENTER);
- l->set_margin(MARGIN_TOP,20);
- l->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,30);
- press_a_key_label=l;
+ l->set_margin(MARGIN_TOP, 20);
+ l->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_BEGIN, 30);
+ press_a_key_label = l;
press_a_key->add_child(l);
- press_a_key->connect("gui_input",this,"_wait_for_key");
- press_a_key->connect("confirmed",this,"_press_a_key_confirm");
-
+ press_a_key->connect("gui_input", this, "_wait_for_key");
+ press_a_key->connect("confirmed", this, "_press_a_key_confirm");
- device_input=memnew( ConfirmationDialog );
+ device_input = memnew(ConfirmationDialog);
add_child(device_input);
device_input->get_ok()->set_text(TTR("Add"));
- device_input->connect("confirmed",this,"_device_input_add");
+ device_input->connect("confirmed", this, "_device_input_add");
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
device_input->add_child(hbc);
//device_input->set_child_rect(hbc);
- VBoxContainer *vbc_left = memnew( VBoxContainer );
+ VBoxContainer *vbc_left = memnew(VBoxContainer);
hbc->add_child(vbc_left);
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Device:"));
vbc_left->add_child(l);
- device_id = memnew( SpinBox );
+ device_id = memnew(SpinBox);
device_id->set_value(0);
vbc_left->add_child(device_id);
- VBoxContainer *vbc_right = memnew( VBoxContainer );
+ VBoxContainer *vbc_right = memnew(VBoxContainer);
hbc->add_child(vbc_right);
vbc_right->set_h_size_flags(SIZE_EXPAND_FILL);
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Index:"));
vbc_right->add_child(l);
- device_index_label=l;
+ device_index_label = l;
- device_index = memnew( OptionButton );
+ device_index = memnew(OptionButton);
vbc_right->add_child(device_index);
/*
@@ -1477,99 +1411,96 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
save->set_text("Save");
save->connect("pressed",this,"_save");
*/
- setting=false;
+ setting = false;
//translations
- TabContainer *translations = memnew( TabContainer );
+ TabContainer *translations = memnew(TabContainer);
translations->set_name(TTR("Localization"));
tab_container->add_child(translations);
{
- VBoxContainer *tvb = memnew( VBoxContainer );
+ VBoxContainer *tvb = memnew(VBoxContainer);
translations->add_child(tvb);
tvb->set_name(TTR("Translations"));
- HBoxContainer *thb = memnew( HBoxContainer);
+ HBoxContainer *thb = memnew(HBoxContainer);
tvb->add_child(thb);
- thb->add_child( memnew( Label(TTR("Translations:"))));
+ thb->add_child(memnew(Label(TTR("Translations:"))));
thb->add_spacer();
- Button *addtr = memnew( Button(TTR("Add..")) );
- addtr->connect("pressed",this,"_translation_file_open");
+ Button *addtr = memnew(Button(TTR("Add..")));
+ addtr->connect("pressed", this, "_translation_file_open");
thb->add_child(addtr);
- MarginContainer *tmc = memnew( MarginContainer );
+ MarginContainer *tmc = memnew(MarginContainer);
tvb->add_child(tmc);
tmc->set_v_size_flags(SIZE_EXPAND_FILL);
- translation_list = memnew( Tree );
+ translation_list = memnew(Tree);
translation_list->set_v_size_flags(SIZE_EXPAND_FILL);
tmc->add_child(translation_list);
- translation_file_open=memnew( EditorFileDialog );
+ translation_file_open = memnew(EditorFileDialog);
add_child(translation_file_open);
translation_file_open->set_mode(EditorFileDialog::MODE_OPEN_FILE);
- translation_file_open->connect("file_selected",this,"_translation_add");
-
+ translation_file_open->connect("file_selected", this, "_translation_add");
}
{
- VBoxContainer *tvb = memnew( VBoxContainer );
+ VBoxContainer *tvb = memnew(VBoxContainer);
translations->add_child(tvb);
tvb->set_name(TTR("Remaps"));
- HBoxContainer *thb = memnew( HBoxContainer);
+ HBoxContainer *thb = memnew(HBoxContainer);
tvb->add_child(thb);
- thb->add_child( memnew( Label(TTR("Resources:"))));
+ thb->add_child(memnew(Label(TTR("Resources:"))));
thb->add_spacer();
- Button *addtr = memnew( Button(TTR("Add..")) );
- addtr->connect("pressed",this,"_translation_res_file_open");
+ Button *addtr = memnew(Button(TTR("Add..")));
+ addtr->connect("pressed", this, "_translation_res_file_open");
thb->add_child(addtr);
- MarginContainer *tmc = memnew( MarginContainer );
+ MarginContainer *tmc = memnew(MarginContainer);
tvb->add_child(tmc);
tmc->set_v_size_flags(SIZE_EXPAND_FILL);
- translation_remap = memnew( Tree );
+ translation_remap = memnew(Tree);
translation_remap->set_v_size_flags(SIZE_EXPAND_FILL);
- translation_remap->connect("cell_selected",this,"_translation_res_select");
+ translation_remap->connect("cell_selected", this, "_translation_res_select");
tmc->add_child(translation_remap);
- translation_remap->connect("button_pressed",this,"_translation_res_delete");
+ translation_remap->connect("button_pressed", this, "_translation_res_delete");
- translation_res_file_open=memnew( EditorFileDialog );
+ translation_res_file_open = memnew(EditorFileDialog);
add_child(translation_res_file_open);
translation_res_file_open->set_mode(EditorFileDialog::MODE_OPEN_FILE);
- translation_res_file_open->connect("file_selected",this,"_translation_res_add");
+ translation_res_file_open->connect("file_selected", this, "_translation_res_add");
- thb = memnew( HBoxContainer);
+ thb = memnew(HBoxContainer);
tvb->add_child(thb);
- thb->add_child( memnew( Label(TTR("Remaps by Locale:"))));
+ thb->add_child(memnew(Label(TTR("Remaps by Locale:"))));
thb->add_spacer();
- addtr = memnew( Button(TTR("Add..")) );
- addtr->connect("pressed",this,"_translation_res_option_file_open");
- translation_res_option_add_button=addtr;
+ addtr = memnew(Button(TTR("Add..")));
+ addtr->connect("pressed", this, "_translation_res_option_file_open");
+ translation_res_option_add_button = addtr;
thb->add_child(addtr);
- tmc = memnew( MarginContainer );
+ tmc = memnew(MarginContainer);
tvb->add_child(tmc);
tmc->set_v_size_flags(SIZE_EXPAND_FILL);
- translation_remap_options = memnew( Tree );
+ translation_remap_options = memnew(Tree);
translation_remap_options->set_v_size_flags(SIZE_EXPAND_FILL);
tmc->add_child(translation_remap_options);
translation_remap_options->set_columns(2);
- translation_remap_options->set_column_title(0,TTR("Path"));
- translation_remap_options->set_column_title(1,TTR("Locale"));
+ translation_remap_options->set_column_title(0, TTR("Path"));
+ translation_remap_options->set_column_title(1, TTR("Locale"));
translation_remap_options->set_column_titles_visible(true);
- translation_remap_options->set_column_expand(0,true);
- translation_remap_options->set_column_expand(1,false);
- translation_remap_options->set_column_min_width(1,200);
- translation_remap_options->connect("item_edited",this,"_translation_res_option_changed");
- translation_remap_options->connect("button_pressed",this,"_translation_res_option_delete");
+ translation_remap_options->set_column_expand(0, true);
+ translation_remap_options->set_column_expand(1, false);
+ translation_remap_options->set_column_min_width(1, 200);
+ translation_remap_options->connect("item_edited", this, "_translation_res_option_changed");
+ translation_remap_options->connect("button_pressed", this, "_translation_res_option_delete");
- translation_res_option_file_open=memnew( EditorFileDialog );
+ translation_res_option_file_open = memnew(EditorFileDialog);
add_child(translation_res_option_file_open);
translation_res_option_file_open->set_mode(EditorFileDialog::MODE_OPEN_FILE);
- translation_res_option_file_open->connect("file_selected",this,"_translation_res_option_add");
-
+ translation_res_option_file_open->connect("file_selected", this, "_translation_res_option_add");
}
-
{
- autoload_settings = memnew( EditorAutoloadSettings );
+ autoload_settings = memnew(EditorAutoloadSettings);
autoload_settings->set_name(TTR("AutoLoad"));
tab_container->add_child(autoload_settings);
autoload_settings->connect("autoload_changed", this, "_settings_changed");
@@ -1577,19 +1508,18 @@ ProjectSettings::ProjectSettings(EditorData *p_data) {
{
- plugin_settings = memnew( EditorPluginSettings );
+ plugin_settings = memnew(EditorPluginSettings);
plugin_settings->set_name(TTR("Plugins"));
tab_container->add_child(plugin_settings);
}
- timer = memnew( Timer );
+ timer = memnew(Timer);
timer->set_wait_time(1.5);
- timer->connect("timeout",GlobalConfig::get_singleton(),"save");
+ timer->connect("timeout", GlobalConfig::get_singleton(), "save");
timer->set_one_shot(true);
add_child(timer);
- updating_translations=false;
-
+ updating_translations = false;
/*
Control * es = memnew( Control );
diff --git a/editor/project_settings.h b/editor/project_settings.h
index 96ac2e2c11..892198e00f 100644
--- a/editor/project_settings.h
+++ b/editor/project_settings.h
@@ -29,19 +29,18 @@
#ifndef PROJECT_SETTINGS_H
#define PROJECT_SETTINGS_H
-#include "scene/gui/dialogs.h"
-#include "property_editor.h"
-#include "undo_redo.h"
-#include "editor_data.h"
-#include "scene/gui/tab_container.h"
#include "editor_autoload_settings.h"
+#include "editor_data.h"
#include "editor_plugin_settings.h"
+#include "property_editor.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/tab_container.h"
+#include "undo_redo.h"
//#include "project_export_settings.h"
class ProjectSettings : public AcceptDialog {
- GDCLASS( ProjectSettings, AcceptDialog );
-
+ GDCLASS(ProjectSettings, AcceptDialog);
TabContainer *tab_container;
@@ -65,7 +64,7 @@ class ProjectSettings : public AcceptDialog {
OptionButton *type;
PopupMenu *popup_add;
ConfirmationDialog *press_a_key;
- Label*press_a_key_label;
+ Label *press_a_key_label;
ConfirmationDialog *device_input;
SpinBox *device_id;
OptionButton *device_index;
@@ -82,7 +81,6 @@ class ProjectSettings : public AcceptDialog {
EditorFileDialog *translation_file_open;
Tree *translation_list;
-
Button *translation_res_option_add_button;
EditorFileDialog *translation_res_file_open;
EditorFileDialog *translation_res_option_file_open;
@@ -105,59 +103,53 @@ class ProjectSettings : public AcceptDialog {
void _action_add();
void _device_input_add();
- void _item_checked(const String& p_item, bool p_check);
+ void _item_checked(const String &p_item, bool p_check);
void _action_selected();
void _action_edited();
- void _action_button_pressed(Object* p_obj, int p_column,int p_id);
- void _wait_for_key(const InputEvent& p_event);
+ void _action_button_pressed(Object *p_obj, int p_column, int p_id);
+ void _wait_for_key(const InputEvent &p_event);
void _press_a_key_confirm();
- void _show_last_added(const InputEvent& p_event, const String& p_name);
+ void _show_last_added(const InputEvent &p_event, const String &p_name);
- void _settings_prop_edited(const String& p_name);
+ void _settings_prop_edited(const String &p_name);
void _settings_changed();
//ProjectExportSettings *export_settings;
void _copy_to_platform(int p_which);
-
void _translation_file_open();
- void _translation_add(const String& p_path);
- void _translation_delete(Object *p_item,int p_column, int p_button);
+ void _translation_add(const String &p_path);
+ void _translation_delete(Object *p_item, int p_column, int p_button);
void _update_translations();
void _translation_res_file_open();
- void _translation_res_add(const String& p_path);
- void _translation_res_delete(Object *p_item,int p_column, int p_button);
+ void _translation_res_add(const String &p_path);
+ void _translation_res_delete(Object *p_item, int p_column, int p_button);
void _translation_res_select();
void _translation_res_option_file_open();
- void _translation_res_option_add(const String& p_path);
+ void _translation_res_option_add(const String &p_path);
void _translation_res_option_changed();
- void _translation_res_option_delete(Object *p_item,int p_column, int p_button);
+ void _translation_res_option_delete(Object *p_item, int p_column, int p_button);
void _toggle_search_bar(bool p_pressed);
void _clear_search_box();
-
-
ProjectSettings();
-
static ProjectSettings *singleton;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
public:
-
- void add_translation(const String& p_translation);
+ void add_translation(const String &p_translation);
static ProjectSettings *get_singleton() { return singleton; }
void popup_project_settings();
void set_plugins_page();
void queue_save();
-
ProjectSettings(EditorData *p_data);
};
diff --git a/editor/property_editor.cpp b/editor/property_editor.cpp
index 533a5b156b..f8234d93fd 100644
--- a/editor/property_editor.cpp
+++ b/editor/property_editor.cpp
@@ -28,37 +28,36 @@
/*************************************************************************/
#include "property_editor.h"
-#include "scene/gui/label.h"
-#include "io/resource_loader.h"
+#include "array_property_edit.h"
+#include "class_db.h"
+#include "create_dialog.h"
+#include "editor_export.h"
+#include "editor_file_system.h"
+#include "editor_help.h"
+#include "editor_node.h"
+#include "editor_settings.h"
+#include "global_config.h"
+#include "global_config.h"
#include "io/image_loader.h"
+#include "io/resource_loader.h"
+#include "multi_node_edit.h"
#include "os/input.h"
#include "os/keyboard.h"
-#include "class_db.h"
+#include "pair.h"
#include "print_string.h"
-#include "global_config.h"
+#include "property_selector.h"
+#include "scene/gui/label.h"
+#include "scene/main/viewport.h"
#include "scene/resources/font.h"
-#include "pair.h"
-#include "scene/scene_string_names.h"
-#include "editor_settings.h"
-#include "editor_export.h"
-#include "editor_node.h"
-#include "multi_node_edit.h"
-#include "array_property_edit.h"
-#include "editor_help.h"
#include "scene/resources/packed_scene.h"
-#include "scene/main/viewport.h"
-#include "editor_file_system.h"
-#include "create_dialog.h"
-#include "property_selector.h"
-#include "global_config.h"
+#include "scene/scene_string_names.h"
void CustomPropertyEditor::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
+ get_stylebox("panel", "PopupMenu")->draw(ci, Rect2(Point2(), get_size()));
/*
if (v.get_type()==Variant::COLOR) {
@@ -67,68 +66,63 @@ void CustomPropertyEditor::_notification(int p_what) {
}
}
-
void CustomPropertyEditor::_menu_option(int p_which) {
-
- switch(type) {
+ switch (type) {
case Variant::INT: {
- if (hint==PROPERTY_HINT_FLAGS) {
+ if (hint == PROPERTY_HINT_FLAGS) {
int val = v;
- if (val&(1<<p_which)) {
+ if (val & (1 << p_which)) {
- val&=~(1<<p_which);
+ val &= ~(1 << p_which);
} else {
- val|=(1<<p_which);
+ val |= (1 << p_which);
}
- v=val;
+ v = val;
emit_signal("variant_changed");
- } else if (hint==PROPERTY_HINT_ENUM) {
+ } else if (hint == PROPERTY_HINT_ENUM) {
- v=p_which;
+ v = p_which;
emit_signal("variant_changed");
-
}
} break;
case Variant::STRING: {
- if (hint==PROPERTY_HINT_ENUM) {
+ if (hint == PROPERTY_HINT_ENUM) {
- v=hint_text.get_slice(",",p_which);
+ v = hint_text.get_slice(",", p_which);
emit_signal("variant_changed");
-
}
} break;
case Variant::OBJECT: {
- switch(p_which) {
+ switch (p_which) {
case OBJ_MENU_LOAD: {
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
- String type=(hint==PROPERTY_HINT_RESOURCE_TYPE)?hint_text:String();
+ String type = (hint == PROPERTY_HINT_RESOURCE_TYPE) ? hint_text : String();
List<String> extensions;
- for (int i=0;i<type.get_slice_count(",");i++) {
+ for (int i = 0; i < type.get_slice_count(","); i++) {
- ResourceLoader::get_recognized_extensions_for_type(type.get_slice(",",i),&extensions);
+ ResourceLoader::get_recognized_extensions_for_type(type.get_slice(",", i), &extensions);
}
Set<String> valid_extensions;
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
- print_line("found: "+E->get());
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ print_line("found: " + E->get());
valid_extensions.insert(E->get());
}
file->clear_filters();
- for (Set<String>::Element *E=valid_extensions.front();E;E=E->next()) {
-
- file->add_filter("*."+E->get()+" ; "+E->get().to_upper() );
+ for (Set<String>::Element *E = valid_extensions.front(); E; E = E->next()) {
+ file->add_filter("*." + E->get() + " ; " + E->get().to_upper());
}
file->popup_centered_ratio();
@@ -136,7 +130,7 @@ void CustomPropertyEditor::_menu_option(int p_which) {
case OBJ_MENU_EDIT: {
- RefPtr RefPtr=v;
+ RefPtr RefPtr = v;
if (!RefPtr.is_null()) {
@@ -146,32 +140,30 @@ void CustomPropertyEditor::_menu_option(int p_which) {
} break;
case OBJ_MENU_CLEAR: {
-
- v=Variant();
+ v = Variant();
emit_signal("variant_changed");
hide();
} break;
case OBJ_MENU_MAKE_UNIQUE: {
-
- RefPtr RefPtr=v;
+ RefPtr RefPtr = v;
Ref<Resource> res_orig = RefPtr;
if (res_orig.is_null())
return;
List<PropertyInfo> property_list;
res_orig->get_property_list(&property_list);
- List< Pair<String,Variant> > propvalues;
+ List<Pair<String, Variant> > propvalues;
- for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
- Pair<String,Variant> p;
+ Pair<String, Variant> p;
PropertyInfo &pi = E->get();
- if (pi.usage&PROPERTY_USAGE_STORAGE) {
+ if (pi.usage & PROPERTY_USAGE_STORAGE) {
- p.first=pi.name;
- p.second=res_orig->get(pi.name);
+ p.first = pi.name;
+ p.second = res_orig->get(pi.name);
}
propvalues.push_back(p);
@@ -179,19 +171,19 @@ void CustomPropertyEditor::_menu_option(int p_which) {
String orig_type = res_orig->get_class();
- Object *inst = ClassDB::instance( orig_type );
+ Object *inst = ClassDB::instance(orig_type);
- Ref<Resource> res = Ref<Resource>( inst->cast_to<Resource>() );
+ Ref<Resource> res = Ref<Resource>(inst->cast_to<Resource>());
ERR_FAIL_COND(res.is_null());
- for(List< Pair<String,Variant> >::Element *E=propvalues.front();E;E=E->next()) {
+ for (List<Pair<String, Variant> >::Element *E = propvalues.front(); E; E = E->next()) {
- Pair<String,Variant> &p=E->get();
- res->set(p.first,p.second);
+ Pair<String, Variant> &p = E->get();
+ res->set(p.first, p.second);
}
- v=res.get_ref_ptr();
+ v = res.get_ref_ptr();
emit_signal("variant_changed");
hide();
} break;
@@ -203,14 +195,14 @@ void CustomPropertyEditor::_menu_option(int p_which) {
} break;
case OBJ_MENU_PASTE: {
- v=EditorSettings::get_singleton()->get_resource_clipboard();
+ v = EditorSettings::get_singleton()->get_resource_clipboard();
emit_signal("variant_changed");
} break;
case OBJ_MENU_REIMPORT: {
- RES r=v;
-/* if (r.is_valid() && r->get_import_metadata().is_valid()) {
+ RES r = v;
+ /* if (r.is_valid() && r->get_import_metadata().is_valid()) {
Ref<ResourceImportMetadata> rimd = r->get_import_metadata();
Ref<EditorImportPlugin> eip = EditorImportExport::get_singleton()->get_import_plugin_by_name(rimd->get_editor());
if (eip.is_valid()) {
@@ -225,53 +217,45 @@ void CustomPropertyEditor::_menu_option(int p_which) {
} break;
case OBJ_MENU_SHOW_IN_FILE_SYSTEM: {
- RES r=v;
- FileSystemDock *file_system_dock=EditorNode::get_singleton()->get_filesystem_dock();
+ RES r = v;
+ FileSystemDock *file_system_dock = EditorNode::get_singleton()->get_filesystem_dock();
file_system_dock->navigate_to_path(r->get_path());
// Ensure that the FileSystem dock is visible.
- TabContainer* tab_container=(TabContainer*)file_system_dock->get_parent_control();
+ TabContainer *tab_container = (TabContainer *)file_system_dock->get_parent_control();
tab_container->set_current_tab(file_system_dock->get_position_in_parent());
} break;
default: {
+ ERR_FAIL_COND(inheritors_array.empty());
- ERR_FAIL_COND( inheritors_array.empty() );
-
+ String intype = inheritors_array[p_which - TYPE_BASE_ID];
-
-
- String intype=inheritors_array[p_which-TYPE_BASE_ID];
-
- if (intype=="ViewportTexture") {
+ if (intype == "ViewportTexture") {
scene_tree->set_title(TTR("Pick a Viewport"));
scene_tree->popup_centered_ratio();
- picking_viewport=true;
+ picking_viewport = true;
return;
-
}
Object *obj = ClassDB::instance(intype);
- ERR_BREAK( !obj );
- Resource *res=obj->cast_to<Resource>();
- ERR_BREAK( !res );
- if (owner && hint==PROPERTY_HINT_RESOURCE_TYPE && hint_text=="Script") {
+ ERR_BREAK(!obj);
+ Resource *res = obj->cast_to<Resource>();
+ ERR_BREAK(!res);
+ if (owner && hint == PROPERTY_HINT_RESOURCE_TYPE && hint_text == "Script") {
//make visual script the right type
- res->call("set_instance_base_type",owner->get_class());
+ res->call("set_instance_base_type", owner->get_class());
}
- v=Ref<Resource>(res).get_ref_ptr();
+ v = Ref<Resource>(res).get_ref_ptr();
emit_signal("variant_changed");
} break;
}
-
} break;
- default:{}
+ default: {}
}
-
-
}
void CustomPropertyEditor::hide_menu() {
@@ -288,15 +272,15 @@ String CustomPropertyEditor::get_name() const {
return name;
}
-bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Type p_type, const Variant& p_variant,int p_hint,String p_hint_text) {
+bool CustomPropertyEditor::edit(Object *p_owner, const String &p_name, Variant::Type p_type, const Variant &p_variant, int p_hint, String p_hint_text) {
- owner=p_owner;
- updating=true;
- name=p_name;
- v=p_variant;
+ owner = p_owner;
+ updating = true;
+ name = p_name;
+ v = p_variant;
field_names.clear();
- hint=p_hint;
- hint_text=p_hint_text;
+ hint = p_hint;
+ hint_text = p_hint_text;
type_button->hide();
if (color_picker)
color_picker->hide();
@@ -307,245 +291,251 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
spinbox->hide();
slider->hide();
- for (int i=0;i<MAX_VALUE_EDITORS;i++) {
+ for (int i = 0; i < MAX_VALUE_EDITORS; i++) {
value_editor[i]->hide();
value_label[i]->hide();
- if (i<4)
+ if (i < 4)
scroll[i]->hide();
}
- for (int i=0;i<MAX_ACTION_BUTTONS;i++) {
+ for (int i = 0; i < MAX_ACTION_BUTTONS; i++) {
action_buttons[i]->hide();
}
checks20gc->hide();
- for(int i=0;i<20;i++)
+ for (int i = 0; i < 20; i++)
checks20[i]->hide();
- type = (p_variant.get_type()!=Variant::NIL && p_variant.get_type()!=Variant::_RID && p_type!=Variant::OBJECT)? p_variant.get_type() : p_type;
+ type = (p_variant.get_type() != Variant::NIL && p_variant.get_type() != Variant::_RID && p_type != Variant::OBJECT) ? p_variant.get_type() : p_type;
-
- switch(type) {
+ switch (type) {
case Variant::BOOL: {
checks20gc->show();
- CheckBox *c=checks20[0];
+ CheckBox *c = checks20[0];
c->set_text("True");
- checks20gc->set_pos(Vector2(4,4));
+ checks20gc->set_pos(Vector2(4, 4));
c->set_pressed(v);
c->show();
checks20gc->set_size(checks20gc->get_minimum_size());
- set_size(checks20gc->get_pos()+checks20gc->get_size()+Vector2(4,4)*EDSCALE);
+ set_size(checks20gc->get_pos() + checks20gc->get_size() + Vector2(4, 4) * EDSCALE);
} break;
case Variant::INT:
case Variant::REAL: {
- if (hint==PROPERTY_HINT_RANGE) {
+ if (hint == PROPERTY_HINT_RANGE) {
int c = hint_text.get_slice_count(",");
- float min=0,max=100,step=1;
- if (c>=1) {
+ float min = 0, max = 100, step = 1;
+ if (c >= 1) {
- if (!hint_text.get_slice(",",0).empty())
- min=hint_text.get_slice(",",0).to_double();
+ if (!hint_text.get_slice(",", 0).empty())
+ min = hint_text.get_slice(",", 0).to_double();
}
- if (c>=2) {
+ if (c >= 2) {
- if (!hint_text.get_slice(",",1).empty())
- max=hint_text.get_slice(",",1).to_double();
+ if (!hint_text.get_slice(",", 1).empty())
+ max = hint_text.get_slice(",", 1).to_double();
}
- if (c>=3) {
+ if (c >= 3) {
- if (!hint_text.get_slice(",",2).empty())
- step= hint_text.get_slice(",",2).to_double();
+ if (!hint_text.get_slice(",", 2).empty())
+ step = hint_text.get_slice(",", 2).to_double();
}
- if (c>=4 && hint_text.get_slice(",",3)=="slider") {
+ if (c >= 4 && hint_text.get_slice(",", 3) == "slider") {
slider->set_min(min);
slider->set_max(max);
slider->set_step(step);
slider->set_value(v);
slider->show();
- set_size(Size2(110,30)*EDSCALE);
+ set_size(Size2(110, 30) * EDSCALE);
} else {
spinbox->set_min(min);
spinbox->set_max(max);
spinbox->set_step(step);
spinbox->set_value(v);
spinbox->show();
- set_size(Size2(70,35)*EDSCALE);
+ set_size(Size2(70, 35) * EDSCALE);
}
- } else if (hint==PROPERTY_HINT_ENUM) {
+ } else if (hint == PROPERTY_HINT_ENUM) {
menu->clear();
Vector<String> options = hint_text.split(",");
- for(int i=0;i<options.size();i++) {
- menu->add_item(options[i],i);
+ for (int i = 0; i < options.size(); i++) {
+ menu->add_item(options[i], i);
}
menu->set_pos(get_pos());
menu->popup();
hide();
- updating=false;
+ updating = false;
return false;
-
- } else if (hint==PROPERTY_HINT_LAYERS_2D_PHYSICS || hint==PROPERTY_HINT_LAYERS_2D_RENDER || hint==PROPERTY_HINT_LAYERS_3D_PHYSICS || hint==PROPERTY_HINT_LAYERS_3D_RENDER) {
-
+ } else if (hint == PROPERTY_HINT_LAYERS_2D_PHYSICS || hint == PROPERTY_HINT_LAYERS_2D_RENDER || hint == PROPERTY_HINT_LAYERS_3D_PHYSICS || hint == PROPERTY_HINT_LAYERS_3D_RENDER) {
String title;
String basename;
switch (hint) {
- case PROPERTY_HINT_LAYERS_2D_RENDER: basename="layer_names/2d_render"; title="2D Render Layers"; break;
- case PROPERTY_HINT_LAYERS_2D_PHYSICS: basename="layer_names/2d_physics"; title="2D Physics Layers"; break;
- case PROPERTY_HINT_LAYERS_3D_RENDER: basename="layer_names/3d_render"; title="3D Render Layers"; break;
- case PROPERTY_HINT_LAYERS_3D_PHYSICS: basename="layer_names/3d_physics";title="3D Physics Layers"; break;
+ case PROPERTY_HINT_LAYERS_2D_RENDER:
+ basename = "layer_names/2d_render";
+ title = "2D Render Layers";
+ break;
+ case PROPERTY_HINT_LAYERS_2D_PHYSICS:
+ basename = "layer_names/2d_physics";
+ title = "2D Physics Layers";
+ break;
+ case PROPERTY_HINT_LAYERS_3D_RENDER:
+ basename = "layer_names/3d_render";
+ title = "3D Render Layers";
+ break;
+ case PROPERTY_HINT_LAYERS_3D_PHYSICS:
+ basename = "layer_names/3d_physics";
+ title = "3D Physics Layers";
+ break;
}
checks20gc->show();
uint32_t flgs = v;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- Point2 ofs(4,4);
- ofs.y+=22*i;
- for(int j=0;j<10;j++) {
+ Point2 ofs(4, 4);
+ ofs.y += 22 * i;
+ for (int j = 0; j < 10; j++) {
- int idx = i*10+j;
- CheckBox *c=checks20[idx];
- c->set_text(GlobalConfig::get_singleton()->get(basename+"/layer_"+itos(idx+1)));
- c->set_pressed( flgs & (1<<(i*10+j)) );
+ int idx = i * 10 + j;
+ CheckBox *c = checks20[idx];
+ c->set_text(GlobalConfig::get_singleton()->get(basename + "/layer_" + itos(idx + 1)));
+ c->set_pressed(flgs & (1 << (i * 10 + j)));
c->show();
}
-
-
}
show();
value_label[0]->set_text(title);
value_label[0]->show();
- value_label[0]->set_pos(Vector2(4,4)*EDSCALE);
+ value_label[0]->set_pos(Vector2(4, 4) * EDSCALE);
- checks20gc->set_pos(Vector2(4,4)*EDSCALE+Vector2(0,value_label[0]->get_size().height+4*EDSCALE));
+ checks20gc->set_pos(Vector2(4, 4) * EDSCALE + Vector2(0, value_label[0]->get_size().height + 4 * EDSCALE));
checks20gc->set_size(checks20gc->get_minimum_size());
- set_size(Vector2(4,4)*EDSCALE+checks20gc->get_pos()+checks20gc->get_size());
+ set_size(Vector2(4, 4) * EDSCALE + checks20gc->get_pos() + checks20gc->get_size());
+ } else if (hint == PROPERTY_HINT_EXP_EASING) {
- } else if (hint==PROPERTY_HINT_EXP_EASING) {
-
- easing_draw->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,5);
- easing_draw->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,5);
- easing_draw->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,5);
- easing_draw->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,30);
- type_button->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,3);
- type_button->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,3);
- type_button->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,25);
- type_button->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,7);
+ easing_draw->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 5);
+ easing_draw->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 5);
+ easing_draw->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 5);
+ easing_draw->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 30);
+ type_button->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 3);
+ type_button->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 3);
+ type_button->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, 25);
+ type_button->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 7);
type_button->set_text(TTR("Preset.."));
type_button->get_popup()->clear();
- type_button->get_popup()->add_item(TTR("Linear"),EASING_LINEAR);
- type_button->get_popup()->add_item(TTR("Ease In"),EASING_EASE_IN);
- type_button->get_popup()->add_item(TTR("Ease Out"),EASING_EASE_OUT);
- if (hint_text!="attenuation") {
- type_button->get_popup()->add_item(TTR("Zero"),EASING_ZERO);
- type_button->get_popup()->add_item(TTR("Easing In-Out"),EASING_IN_OUT);
- type_button->get_popup()->add_item(TTR("Easing Out-In"),EASING_OUT_IN);
+ type_button->get_popup()->add_item(TTR("Linear"), EASING_LINEAR);
+ type_button->get_popup()->add_item(TTR("Ease In"), EASING_EASE_IN);
+ type_button->get_popup()->add_item(TTR("Ease Out"), EASING_EASE_OUT);
+ if (hint_text != "attenuation") {
+ type_button->get_popup()->add_item(TTR("Zero"), EASING_ZERO);
+ type_button->get_popup()->add_item(TTR("Easing In-Out"), EASING_IN_OUT);
+ type_button->get_popup()->add_item(TTR("Easing Out-In"), EASING_OUT_IN);
}
type_button->show();
easing_draw->show();
- set_size(Size2(200,150)*EDSCALE);
- } else if (hint==PROPERTY_HINT_FLAGS) {
+ set_size(Size2(200, 150) * EDSCALE);
+ } else if (hint == PROPERTY_HINT_FLAGS) {
menu->clear();
Vector<String> flags = hint_text.split(",");
- for(int i=0;i<flags.size();i++) {
+ for (int i = 0; i < flags.size(); i++) {
String flag = flags[i];
- if (flag=="")
+ if (flag == "")
continue;
- menu->add_check_item(flag,i);
+ menu->add_check_item(flag, i);
int f = v;
- if (f&(1<<i))
- menu->set_item_checked(menu->get_item_index(i),true);
+ if (f & (1 << i))
+ menu->set_item_checked(menu->get_item_index(i), true);
}
menu->set_pos(get_pos());
menu->popup();
hide();
- updating=false;
+ updating = false;
return false;
} else {
List<String> names;
names.push_back("value:");
- config_value_editors(1,1,50,names);
- value_editor[0]->set_text( String::num(v) );
+ config_value_editors(1, 1, 50, names);
+ value_editor[0]->set_text(String::num(v));
}
} break;
case Variant::STRING: {
- if (hint==PROPERTY_HINT_FILE || hint==PROPERTY_HINT_GLOBAL_FILE) {
+ if (hint == PROPERTY_HINT_FILE || hint == PROPERTY_HINT_GLOBAL_FILE) {
List<String> names;
names.push_back(TTR("File.."));
names.push_back(TTR("Clear"));
config_action_buttons(names);
- } else if (hint==PROPERTY_HINT_DIR || hint==PROPERTY_HINT_GLOBAL_DIR) {
+ } else if (hint == PROPERTY_HINT_DIR || hint == PROPERTY_HINT_GLOBAL_DIR) {
List<String> names;
names.push_back(TTR("Dir.."));
names.push_back(TTR("Clear"));
config_action_buttons(names);
- } else if (hint==PROPERTY_HINT_ENUM) {
+ } else if (hint == PROPERTY_HINT_ENUM) {
menu->clear();
Vector<String> options = hint_text.split(",");
- for(int i=0;i<options.size();i++) {
- menu->add_item(options[i],i);
+ for (int i = 0; i < options.size(); i++) {
+ menu->add_item(options[i], i);
}
menu->set_pos(get_pos());
menu->popup();
hide();
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_MULTILINE_TEXT) {
+ } else if (hint == PROPERTY_HINT_MULTILINE_TEXT) {
text_edit->show();
text_edit->set_text(v);
//action_buttons[0];
- int button_margin = get_constant("button_margin","Dialogs");
- int margin = get_constant("margin","Dialogs");
+ int button_margin = get_constant("button_margin", "Dialogs");
+ int margin = get_constant("margin", "Dialogs");
- action_buttons[0]->set_anchor( MARGIN_LEFT, ANCHOR_END );
- action_buttons[0]->set_anchor( MARGIN_TOP, ANCHOR_END );
- action_buttons[0]->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- action_buttons[0]->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
- action_buttons[0]->set_begin( Point2( 70, button_margin-5 ) );
- action_buttons[0]->set_end( Point2( margin, margin ) );
+ action_buttons[0]->set_anchor(MARGIN_LEFT, ANCHOR_END);
+ action_buttons[0]->set_anchor(MARGIN_TOP, ANCHOR_END);
+ action_buttons[0]->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ action_buttons[0]->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
+ action_buttons[0]->set_begin(Point2(70, button_margin - 5));
+ action_buttons[0]->set_end(Point2(margin, margin));
action_buttons[0]->set_text(TTR("Close"));
action_buttons[0]->show();
- } else if (hint==PROPERTY_HINT_TYPE_STRING) {
+ } else if (hint == PROPERTY_HINT_TYPE_STRING) {
/* FIXME: This is repeated twice, with slightly different behavior! Which one? Check line 644 */
if (!create_dialog) {
- create_dialog = memnew( CreateDialog );
- create_dialog->connect("create",this,"_create_dialog_callback");
+ create_dialog = memnew(CreateDialog);
+ create_dialog->connect("create", this, "_create_dialog_callback");
add_child(create_dialog);
}
- if (hint_text!=String()) {
+ if (hint_text != String()) {
create_dialog->set_base_type(hint_text);
} else {
create_dialog->set_base_type("Object");
@@ -553,119 +543,124 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
create_dialog->popup(false);
hide();
- updating=false;
+ updating = false;
return false;
-
- } else if (hint==PROPERTY_HINT_METHOD_OF_VARIANT_TYPE) {
-#define MAKE_PROPSELECT if (!property_select) { property_select = memnew(PropertySelector); property_select->connect("selected",this,"_create_selected_property"); add_child(property_select); } hide();
+ } else if (hint == PROPERTY_HINT_METHOD_OF_VARIANT_TYPE) {
+#define MAKE_PROPSELECT \
+ if (!property_select) { \
+ property_select = memnew(PropertySelector); \
+ property_select->connect("selected", this, "_create_selected_property"); \
+ add_child(property_select); \
+ } \
+ hide();
MAKE_PROPSELECT;
- Variant::Type type=Variant::NIL;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (hint_text==Variant::get_type_name(Variant::Type(i))) {
- type=Variant::Type(i);
+ Variant::Type type = Variant::NIL;
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (hint_text == Variant::get_type_name(Variant::Type(i))) {
+ type = Variant::Type(i);
}
}
if (type)
- property_select->select_method_from_basic_type(type,v);
- updating=false;
+ property_select->select_method_from_basic_type(type, v);
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_METHOD_OF_BASE_TYPE) {
+ } else if (hint == PROPERTY_HINT_METHOD_OF_BASE_TYPE) {
MAKE_PROPSELECT
- property_select->select_method_from_base_type(hint_text,v);
+ property_select->select_method_from_base_type(hint_text, v);
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_METHOD_OF_INSTANCE) {
+ } else if (hint == PROPERTY_HINT_METHOD_OF_INSTANCE) {
MAKE_PROPSELECT
Object *instance = ObjectDB::get_instance(hint_text.to_int64());
if (instance)
- property_select->select_method_from_instance(instance,v);
- updating=false;
+ property_select->select_method_from_instance(instance, v);
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_METHOD_OF_SCRIPT) {
+ } else if (hint == PROPERTY_HINT_METHOD_OF_SCRIPT) {
MAKE_PROPSELECT
Object *obj = ObjectDB::get_instance(hint_text.to_int64());
if (obj && obj->cast_to<Script>()) {
- property_select->select_method_from_script(obj->cast_to<Script>(),v);
+ property_select->select_method_from_script(obj->cast_to<Script>(), v);
}
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE) {
+ } else if (hint == PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE) {
MAKE_PROPSELECT
- Variant::Type type=Variant::NIL;
- String tname=hint_text;
- if (tname.find(".")!=-1)
- tname=tname.get_slice(".",0);
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (tname==Variant::get_type_name(Variant::Type(i))) {
- type=Variant::Type(Variant::Type(i));
+ Variant::Type type = Variant::NIL;
+ String tname = hint_text;
+ if (tname.find(".") != -1)
+ tname = tname.get_slice(".", 0);
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (tname == Variant::get_type_name(Variant::Type(i))) {
+ type = Variant::Type(Variant::Type(i));
}
}
InputEvent::Type iet = InputEvent::NONE;
- if (hint_text.find(".")!=-1) {
- iet=InputEvent::Type(int(hint_text.get_slice(".",1).to_int()));
+ if (hint_text.find(".") != -1) {
+ iet = InputEvent::Type(int(hint_text.get_slice(".", 1).to_int()));
}
if (type)
- property_select->select_property_from_basic_type(type,iet,v);
+ property_select->select_property_from_basic_type(type, iet, v);
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_PROPERTY_OF_BASE_TYPE) {
+ } else if (hint == PROPERTY_HINT_PROPERTY_OF_BASE_TYPE) {
MAKE_PROPSELECT
- property_select->select_property_from_base_type(hint_text,v);
+ property_select->select_property_from_base_type(hint_text, v);
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_PROPERTY_OF_INSTANCE) {
+ } else if (hint == PROPERTY_HINT_PROPERTY_OF_INSTANCE) {
Object *instance = ObjectDB::get_instance(hint_text.to_int64());
if (instance)
- property_select->select_property_from_instance(instance,v);
+ property_select->select_property_from_instance(instance, v);
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_PROPERTY_OF_SCRIPT) {
+ } else if (hint == PROPERTY_HINT_PROPERTY_OF_SCRIPT) {
MAKE_PROPSELECT
Object *obj = ObjectDB::get_instance(hint_text.to_int64());
if (obj && obj->cast_to<Script>()) {
- property_select->select_property_from_script(obj->cast_to<Script>(),v);
+ property_select->select_property_from_script(obj->cast_to<Script>(), v);
}
- updating=false;
+ updating = false;
return false;
- } else if (hint==PROPERTY_HINT_TYPE_STRING) {
+ } else if (hint == PROPERTY_HINT_TYPE_STRING) {
if (!create_dialog) {
/* FIXME: ... and here. See line 529 */
- create_dialog = memnew( CreateDialog );
- create_dialog->connect("create",this,"_create_dialog_callback");
+ create_dialog = memnew(CreateDialog);
+ create_dialog->connect("create", this, "_create_dialog_callback");
add_child(create_dialog);
}
} else {
List<String> names;
names.push_back("string:");
- config_value_editors(1,1,50,names);
- value_editor[0]->set_text( v );
+ config_value_editors(1, 1, 50, names);
+ value_editor[0]->set_text(v);
}
} break;
@@ -673,10 +668,10 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("x");
field_names.push_back("y");
- config_value_editors(2,2,10,field_names);
- Vector2 vec=v;
- value_editor[0]->set_text( String::num( vec.x) );
- value_editor[1]->set_text( String::num( vec.y) );
+ config_value_editors(2, 2, 10, field_names);
+ Vector2 vec = v;
+ value_editor[0]->set_text(String::num(vec.x));
+ value_editor[1]->set_text(String::num(vec.y));
} break;
case Variant::RECT2: {
@@ -684,23 +679,23 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("y");
field_names.push_back("w");
field_names.push_back("h");
- config_value_editors(4,4,10,field_names);
- Rect2 r=v;
- value_editor[0]->set_text( String::num( r.pos.x) );
- value_editor[1]->set_text( String::num( r.pos.y) );
- value_editor[2]->set_text( String::num( r.size.x) );
- value_editor[3]->set_text( String::num( r.size.y) );
+ config_value_editors(4, 4, 10, field_names);
+ Rect2 r = v;
+ value_editor[0]->set_text(String::num(r.pos.x));
+ value_editor[1]->set_text(String::num(r.pos.y));
+ value_editor[2]->set_text(String::num(r.size.x));
+ value_editor[3]->set_text(String::num(r.size.y));
} break;
case Variant::VECTOR3: {
field_names.push_back("x");
field_names.push_back("y");
field_names.push_back("z");
- config_value_editors(3,3,10,field_names);
- Vector3 vec=v;
- value_editor[0]->set_text( String::num( vec.x) );
- value_editor[1]->set_text( String::num( vec.y) );
- value_editor[2]->set_text( String::num( vec.z) );
+ config_value_editors(3, 3, 10, field_names);
+ Vector3 vec = v;
+ value_editor[0]->set_text(String::num(vec.x));
+ value_editor[1]->set_text(String::num(vec.y));
+ value_editor[2]->set_text(String::num(vec.z));
} break;
case Variant::PLANE: {
@@ -708,12 +703,12 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("y");
field_names.push_back("z");
field_names.push_back("d");
- config_value_editors(4,4,10,field_names);
- Plane plane=v;
- value_editor[0]->set_text( String::num( plane.normal.x ) );
- value_editor[1]->set_text( String::num( plane.normal.y ) );
- value_editor[2]->set_text( String::num( plane.normal.z ) );
- value_editor[3]->set_text( String::num( plane.d ) );
+ config_value_editors(4, 4, 10, field_names);
+ Plane plane = v;
+ value_editor[0]->set_text(String::num(plane.normal.x));
+ value_editor[1]->set_text(String::num(plane.normal.y));
+ value_editor[2]->set_text(String::num(plane.normal.z));
+ value_editor[3]->set_text(String::num(plane.d));
} break;
case Variant::QUAT: {
@@ -722,12 +717,12 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("y");
field_names.push_back("z");
field_names.push_back("w");
- config_value_editors(4,4,10,field_names);
- Quat q=v;
- value_editor[0]->set_text( String::num( q.x ) );
- value_editor[1]->set_text( String::num( q.y ) );
- value_editor[2]->set_text( String::num( q.z ) );
- value_editor[3]->set_text( String::num( q.w ) );
+ config_value_editors(4, 4, 10, field_names);
+ Quat q = v;
+ value_editor[0]->set_text(String::num(q.x));
+ value_editor[1]->set_text(String::num(q.y));
+ value_editor[2]->set_text(String::num(q.z));
+ value_editor[3]->set_text(String::num(q.w));
} break;
case Variant::RECT3: {
@@ -738,15 +733,15 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("sx");
field_names.push_back("sy");
field_names.push_back("sz");
- config_value_editors(6,3,16,field_names);
+ config_value_editors(6, 3, 16, field_names);
- Rect3 aabb=v;
- value_editor[0]->set_text( String::num( aabb.pos.x ) );
- value_editor[1]->set_text( String::num( aabb.pos.y ) );
- value_editor[2]->set_text( String::num( aabb.pos.z ) );
- value_editor[3]->set_text( String::num( aabb.size.x ) );
- value_editor[4]->set_text( String::num( aabb.size.y ) );
- value_editor[5]->set_text( String::num( aabb.size.z ) );
+ Rect3 aabb = v;
+ value_editor[0]->set_text(String::num(aabb.pos.x));
+ value_editor[1]->set_text(String::num(aabb.pos.y));
+ value_editor[2]->set_text(String::num(aabb.pos.z));
+ value_editor[3]->set_text(String::num(aabb.size.x));
+ value_editor[4]->set_text(String::num(aabb.size.y));
+ value_editor[5]->set_text(String::num(aabb.size.z));
} break;
case Variant::TRANSFORM2D: {
@@ -757,12 +752,12 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("yy");
field_names.push_back("ox");
field_names.push_back("oy");
- config_value_editors(6,2,16,field_names);
+ config_value_editors(6, 2, 16, field_names);
- Transform2D basis=v;
- for(int i=0;i<6;i++) {
+ Transform2D basis = v;
+ for (int i = 0; i < 6; i++) {
- value_editor[i]->set_text( String::num( basis.elements[i/2][i%2] ) );
+ value_editor[i]->set_text(String::num(basis.elements[i / 2][i % 2]));
}
} break;
@@ -777,18 +772,17 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("zx");
field_names.push_back("zy");
field_names.push_back("zz");
- config_value_editors(9,3,16,field_names);
+ config_value_editors(9, 3, 16, field_names);
- Basis basis=v;
- for(int i=0;i<9;i++) {
+ Basis basis = v;
+ for (int i = 0; i < 9; i++) {
- value_editor[i]->set_text( String::num( basis.elements[i/3][i%3] ) );
+ value_editor[i]->set_text(String::num(basis.elements[i / 3][i % 3]));
}
} break;
case Variant::TRANSFORM: {
-
field_names.push_back("xx");
field_names.push_back("xy");
field_names.push_back("xz");
@@ -801,36 +795,36 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
field_names.push_back("zy");
field_names.push_back("zz");
field_names.push_back("zo");
- config_value_editors(12,4,16,field_names);
+ config_value_editors(12, 4, 16, field_names);
- Transform tr=v;
- for(int i=0;i<9;i++) {
+ Transform tr = v;
+ for (int i = 0; i < 9; i++) {
- value_editor[(i/3)*4+i%3]->set_text( String::num( tr.basis.elements[i/3][i%3] ) );
+ value_editor[(i / 3) * 4 + i % 3]->set_text(String::num(tr.basis.elements[i / 3][i % 3]));
}
- value_editor[3]->set_text( String::num( tr.origin.x ) );
- value_editor[7]->set_text( String::num( tr.origin.y ) );
- value_editor[11]->set_text( String::num( tr.origin.z ) );
+ value_editor[3]->set_text(String::num(tr.origin.x));
+ value_editor[7]->set_text(String::num(tr.origin.y));
+ value_editor[11]->set_text(String::num(tr.origin.z));
} break;
case Variant::COLOR: {
if (!color_picker) {
//late init for performance
- color_picker = memnew( ColorPicker );
+ color_picker = memnew(ColorPicker);
add_child(color_picker);
color_picker->hide();
color_picker->set_area_as_parent_rect();
- for(int i=0;i<4;i++)
- color_picker->set_margin((Margin)i,5);
- color_picker->connect("color_changed",this,"_color_changed");
+ for (int i = 0; i < 4; i++)
+ color_picker->set_margin((Margin)i, 5);
+ color_picker->connect("color_changed", this, "_color_changed");
}
color_picker->show();
- color_picker->set_edit_alpha(hint!=PROPERTY_HINT_COLOR_NO_ALPHA);
+ color_picker->set_edit_alpha(hint != PROPERTY_HINT_COLOR_NO_ALPHA);
color_picker->set_pick_color(v);
- set_size( Size2(300*EDSCALE, color_picker->get_combined_minimum_size().height+10*EDSCALE));
+ set_size(Size2(300 * EDSCALE, color_picker->get_combined_minimum_size().height + 10 * EDSCALE));
color_picker->set_focus_on_line_edit();
/*
int ofs=80;
@@ -886,69 +880,62 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
} break;
case Variant::OBJECT: {
- if (hint!=PROPERTY_HINT_RESOURCE_TYPE)
+ if (hint != PROPERTY_HINT_RESOURCE_TYPE)
break;
-
menu->clear();
- menu->set_size(Size2(1,1));
+ menu->set_size(Size2(1, 1));
- if (p_name=="script" && hint_text=="Script" && owner->cast_to<Node>()) {
- menu->add_icon_item(get_icon("Script","EditorIcons"),TTR("New Script"),OBJ_MENU_NEW_SCRIPT);
+ if (p_name == "script" && hint_text == "Script" && owner->cast_to<Node>()) {
+ menu->add_icon_item(get_icon("Script", "EditorIcons"), TTR("New Script"), OBJ_MENU_NEW_SCRIPT);
menu->add_separator();
- } else if (hint_text!="") {
- int idx=0;
-
- for(int i=0;i<hint_text.get_slice_count(",");i++) {
+ } else if (hint_text != "") {
+ int idx = 0;
+ for (int i = 0; i < hint_text.get_slice_count(","); i++) {
-
- String base=hint_text.get_slice(",",i);
+ String base = hint_text.get_slice(",", i);
Set<String> valid_inheritors;
valid_inheritors.insert(base);
List<StringName> inheritors;
- ClassDB::get_inheriters_from_class(base.strip_edges(),&inheritors);
- List<StringName>::Element *E=inheritors.front();
- while(E) {
+ ClassDB::get_inheriters_from_class(base.strip_edges(), &inheritors);
+ List<StringName>::Element *E = inheritors.front();
+ while (E) {
valid_inheritors.insert(E->get());
- E=E->next();
+ E = E->next();
}
- for(Set<String>::Element *E=valid_inheritors.front();E;E=E->next()) {
+ for (Set<String>::Element *E = valid_inheritors.front(); E; E = E->next()) {
String t = E->get();
if (!ClassDB::can_instance(t))
continue;
inheritors_array.push_back(t);
- int id = TYPE_BASE_ID+idx;
- if (has_icon(t,"EditorIcons")) {
+ int id = TYPE_BASE_ID + idx;
+ if (has_icon(t, "EditorIcons")) {
- menu->add_icon_item(get_icon(t,"EditorIcons"),TTR("New")+" "+t,id);
+ menu->add_icon_item(get_icon(t, "EditorIcons"), TTR("New") + " " + t, id);
} else {
- menu->add_item(TTR("New")+" "+t,id);
+ menu->add_item(TTR("New") + " " + t, id);
}
idx++;
}
-
-
}
if (menu->get_item_count())
menu->add_separator();
}
- menu->add_icon_item(get_icon("Load","EditorIcons"),"Load",OBJ_MENU_LOAD);
+ menu->add_icon_item(get_icon("Load", "EditorIcons"), "Load", OBJ_MENU_LOAD);
if (!RES(v).is_null()) {
-
-
- menu->add_icon_item(get_icon("EditResource","EditorIcons"),"Edit",OBJ_MENU_EDIT);
- menu->add_icon_item(get_icon("Del","EditorIcons"),"Clear",OBJ_MENU_CLEAR);
- menu->add_icon_item(get_icon("Duplicate","EditorIcons"),"Make Unique",OBJ_MENU_MAKE_UNIQUE);
+ menu->add_icon_item(get_icon("EditResource", "EditorIcons"), "Edit", OBJ_MENU_EDIT);
+ menu->add_icon_item(get_icon("Del", "EditorIcons"), "Clear", OBJ_MENU_CLEAR);
+ menu->add_icon_item(get_icon("Duplicate", "EditorIcons"), "Make Unique", OBJ_MENU_MAKE_UNIQUE);
RES r = v;
if (r.is_valid() && r->get_path().is_resource_file()) {
/*if (r->get_import_metadata().is_valid()) {
@@ -956,7 +943,7 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
menu->add_icon_item(get_icon("ReloadSmall","EditorIcons"),"Re-Import",OBJ_MENU_REIMPORT);
}*/
menu->add_separator();
- menu->add_item(TTR("Show in File System"),OBJ_MENU_SHOW_IN_FILE_SYSTEM);
+ menu->add_item(TTR("Show in File System"), OBJ_MENU_SHOW_IN_FILE_SYSTEM);
}
/*if (r.is_valid() && r->get_path().is_resource_file()) {
menu->set_item_tooltip(1,r->get_path());
@@ -964,19 +951,17 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
menu->set_item_tooltip(1,r->get_name()+" ("+r->get_type()+")");
}*/
} else {
-
}
-
- RES cb=EditorSettings::get_singleton()->get_resource_clipboard();
- bool paste_valid=false;
+ RES cb = EditorSettings::get_singleton()->get_resource_clipboard();
+ bool paste_valid = false;
if (cb.is_valid()) {
- if (hint_text=="")
- paste_valid=true;
+ if (hint_text == "")
+ paste_valid = true;
else
- for (int i = 0; i < hint_text.get_slice_count(",");i++)
- if (ClassDB::is_parent_class(cb->get_class(),hint_text.get_slice(",",i))) {
- paste_valid=true;
+ for (int i = 0; i < hint_text.get_slice_count(","); i++)
+ if (ClassDB::is_parent_class(cb->get_class(), hint_text.get_slice(",", i))) {
+ paste_valid = true;
break;
}
}
@@ -984,64 +969,52 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
if (!RES(v).is_null() || paste_valid) {
menu->add_separator();
-
if (!RES(v).is_null()) {
- menu->add_item(TTR("Copy"),OBJ_MENU_COPY);
+ menu->add_item(TTR("Copy"), OBJ_MENU_COPY);
}
if (paste_valid) {
- menu->add_item(TTR("Paste"),OBJ_MENU_PASTE);
+ menu->add_item(TTR("Paste"), OBJ_MENU_PASTE);
}
}
-
-
menu->set_pos(get_pos());
menu->popup();
hide();
- updating=false;
+ updating = false;
return false;
-
} break;
case Variant::INPUT_EVENT: {
-
} break;
case Variant::DICTIONARY: {
-
} break;
case Variant::POOL_BYTE_ARRAY: {
-
} break;
case Variant::POOL_INT_ARRAY: {
-
} break;
case Variant::POOL_REAL_ARRAY: {
-
} break;
case Variant::POOL_STRING_ARRAY: {
-
} break;
case Variant::POOL_VECTOR3_ARRAY: {
-
} break;
case Variant::POOL_COLOR_ARRAY: {
-
} break;
default: {}
}
- updating=false;
+ updating = false;
return true;
}
@@ -1055,20 +1028,20 @@ bool CustomPropertyEditor::edit(Object* p_owner,const String& p_name,Variant::Ty
void CustomPropertyEditor::_file_selected(String p_file) {
- switch(type) {
+ switch (type) {
case Variant::STRING: {
- if (hint==PROPERTY_HINT_FILE || hint==PROPERTY_HINT_DIR) {
+ if (hint == PROPERTY_HINT_FILE || hint == PROPERTY_HINT_DIR) {
- v=GlobalConfig::get_singleton()->localize_path(p_file);
+ v = GlobalConfig::get_singleton()->localize_path(p_file);
emit_signal("variant_changed");
hide();
}
- if (hint==PROPERTY_HINT_GLOBAL_FILE || hint==PROPERTY_HINT_GLOBAL_DIR) {
+ if (hint == PROPERTY_HINT_GLOBAL_FILE || hint == PROPERTY_HINT_GLOBAL_DIR) {
- v=p_file;
+ v = p_file;
emit_signal("variant_changed");
hide();
}
@@ -1076,25 +1049,25 @@ void CustomPropertyEditor::_file_selected(String p_file) {
} break;
case Variant::OBJECT: {
- String type=(hint==PROPERTY_HINT_RESOURCE_TYPE)?hint_text:String();
+ String type = (hint == PROPERTY_HINT_RESOURCE_TYPE) ? hint_text : String();
- RES res = ResourceLoader::load(p_file,type);
+ RES res = ResourceLoader::load(p_file, type);
if (res.is_null()) {
error->set_text(TTR("Error loading file: Not a resource!"));
error->popup_centered_minsize();
break;
}
- v=res.get_ref_ptr();
+ v = res.get_ref_ptr();
emit_signal("variant_changed");
hide();
} break;
case Variant::IMAGE: {
Image image;
- Error err = ImageLoader::load_image(p_file,&image);
+ Error err = ImageLoader::load_image(p_file, &image);
ERR_EXPLAIN(TTR("Couldn't load image"));
ERR_FAIL_COND(err);
- v=image;
+ v = image;
emit_signal("variant_changed");
hide();
} break;
@@ -1104,80 +1077,74 @@ void CustomPropertyEditor::_file_selected(String p_file) {
void CustomPropertyEditor::_type_create_selected(int p_idx) {
+ if (type == Variant::INT || type == Variant::REAL) {
- if (type==Variant::INT || type==Variant::REAL) {
-
-
- float newval=0;
- switch(p_idx) {
+ float newval = 0;
+ switch (p_idx) {
case EASING_LINEAR: {
- newval=1;
+ newval = 1;
} break;
case EASING_EASE_IN: {
- newval=2.0;
+ newval = 2.0;
} break;
case EASING_EASE_OUT: {
- newval=0.5;
+ newval = 0.5;
} break;
case EASING_ZERO: {
- newval=0;
+ newval = 0;
} break;
case EASING_IN_OUT: {
- newval=-0.5;
+ newval = -0.5;
} break;
case EASING_OUT_IN: {
- newval=-2.0;
+ newval = -2.0;
} break;
}
- v=newval;
+ v = newval;
emit_signal("variant_changed");
easing_draw->update();
- } else if (type==Variant::OBJECT) {
+ } else if (type == Variant::OBJECT) {
- ERR_FAIL_INDEX(p_idx,inheritors_array.size());
+ ERR_FAIL_INDEX(p_idx, inheritors_array.size());
//List<String> inheritors;
//ClassDB::get_inheriters_from(hint_text,&inheritors);
//inheritors.push_front(hint_text);
//ERR_FAIL_INDEX( p_idx, inheritors.size() );
- String intype=inheritors_array[p_idx];
+ String intype = inheritors_array[p_idx];
Object *obj = ClassDB::instance(intype);
- ERR_FAIL_COND( !obj );
-
+ ERR_FAIL_COND(!obj);
- Resource *res=obj->cast_to<Resource>();
- ERR_FAIL_COND( !res );
+ Resource *res = obj->cast_to<Resource>();
+ ERR_FAIL_COND(!res);
- v=Ref<Resource>(res).get_ref_ptr();
+ v = Ref<Resource>(res).get_ref_ptr();
emit_signal("variant_changed");
hide();
}
-
}
+void CustomPropertyEditor::_color_changed(const Color &p_color) {
-void CustomPropertyEditor::_color_changed(const Color& p_color) {
-
- v=p_color;
+ v = p_color;
emit_signal("variant_changed");
-
}
void CustomPropertyEditor::_node_path_selected(NodePath p_path) {
if (picking_viewport) {
- Node* to_node=get_node(p_path);
+ Node *to_node = get_node(p_path);
if (!to_node->cast_to<Viewport>()) {
EditorNode::get_singleton()->show_warning("Selected node is not a Viewport!");
return;
@@ -1187,86 +1154,84 @@ void CustomPropertyEditor::_node_path_selected(NodePath p_path) {
vt.instance();
vt->set_viewport_path_in_scene(get_tree()->get_edited_scene_root()->get_path_to(to_node));
vt->setup_local_to_scene();
- v=vt;
+ v = vt;
emit_signal("variant_changed");
return;
}
- if (hint==PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE && hint_text!=String()) {
+ if (hint == PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE && hint_text != String()) {
- Node* node=get_node(hint_text);
+ Node *node = get_node(hint_text);
if (node) {
- Node *tonode=node->get_node(p_path);
+ Node *tonode = node->get_node(p_path);
if (tonode) {
- p_path=node->get_path_to(tonode);
+ p_path = node->get_path_to(tonode);
}
}
} else if (owner) {
- Node *node=NULL;
+ Node *node = NULL;
- if (owner->is_class("Node"))
+ if (owner->is_class("Node"))
node = owner->cast_to<Node>();
else if (owner->is_class("ArrayPropertyEdit"))
node = owner->cast_to<ArrayPropertyEdit>()->get_node();
if (!node) {
- v=p_path;
+ v = p_path;
emit_signal("variant_changed");
call_deferred("hide"); //to not mess with dialogs
return;
}
- Node *tonode=node->get_node(p_path);
+ Node *tonode = node->get_node(p_path);
if (tonode) {
- p_path=node->get_path_to(tonode);
+ p_path = node->get_path_to(tonode);
}
}
- v=p_path;
+ v = p_path;
emit_signal("variant_changed");
call_deferred("hide"); //to not mess with dialogs
-
}
void CustomPropertyEditor::_action_pressed(int p_which) {
-
if (updating)
return;
- switch(type) {
+ switch (type) {
case Variant::BOOL: {
- v=checks20[0]->is_pressed();
+ v = checks20[0]->is_pressed();
emit_signal("variant_changed");
} break;
case Variant::INT: {
- if (hint==PROPERTY_HINT_LAYERS_2D_PHYSICS || hint==PROPERTY_HINT_LAYERS_2D_RENDER || hint==PROPERTY_HINT_LAYERS_3D_PHYSICS || hint==PROPERTY_HINT_LAYERS_3D_RENDER) {
+ if (hint == PROPERTY_HINT_LAYERS_2D_PHYSICS || hint == PROPERTY_HINT_LAYERS_2D_RENDER || hint == PROPERTY_HINT_LAYERS_3D_PHYSICS || hint == PROPERTY_HINT_LAYERS_3D_RENDER) {
uint32_t f = v;
if (checks20[p_which]->is_pressed())
- f|=(1<<p_which);
+ f |= (1 << p_which);
else
- f&=~(1<<p_which);
+ f &= ~(1 << p_which);
- v=f;
+ v = f;
emit_signal("variant_changed");
}
} break;
case Variant::STRING: {
- if (hint==PROPERTY_HINT_MULTILINE_TEXT) {
+ if (hint == PROPERTY_HINT_MULTILINE_TEXT) {
hide();
- } else if (hint==PROPERTY_HINT_FILE || hint==PROPERTY_HINT_GLOBAL_FILE) {
- if (p_which==0) {
+ } else if (hint == PROPERTY_HINT_FILE || hint == PROPERTY_HINT_GLOBAL_FILE) {
+ if (p_which == 0) {
- if (hint==PROPERTY_HINT_FILE)
+ if (hint == PROPERTY_HINT_FILE)
file->set_access(EditorFileDialog::ACCESS_RESOURCES);
else
file->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
@@ -1276,36 +1241,32 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
file->clear_filters();
-
- if (hint_text!="") {
- Vector<String> extensions=hint_text.split(",");
- for(int i=0;i<extensions.size();i++) {
+ if (hint_text != "") {
+ Vector<String> extensions = hint_text.split(",");
+ for (int i = 0; i < extensions.size(); i++) {
String filter = extensions[i];
if (filter.begins_with("."))
- filter="*"+extensions[i];
+ filter = "*" + extensions[i];
else if (!filter.begins_with("*"))
- filter="*."+extensions[i];
-
-
- file->add_filter(filter+" ; "+extensions[i].to_upper() );
+ filter = "*." + extensions[i];
+ file->add_filter(filter + " ; " + extensions[i].to_upper());
}
}
file->popup_centered_ratio();
} else {
- v="";
+ v = "";
emit_signal("variant_changed");
hide();
-
}
- } else if (hint==PROPERTY_HINT_DIR || hint==PROPERTY_HINT_GLOBAL_DIR) {
+ } else if (hint == PROPERTY_HINT_DIR || hint == PROPERTY_HINT_GLOBAL_DIR) {
- if (p_which==0) {
+ if (p_which == 0) {
- if (hint==PROPERTY_HINT_DIR)
+ if (hint == PROPERTY_HINT_DIR)
file->set_access(EditorFileDialog::ACCESS_RESOURCES);
else
file->set_access(EditorFileDialog::ACCESS_FILESYSTEM);
@@ -1314,73 +1275,66 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
file->popup_centered_ratio();
} else {
- v="";
+ v = "";
emit_signal("variant_changed");
hide();
-
}
-
}
} break;
case Variant::NODE_PATH: {
- if (p_which==0) {
+ if (p_which == 0) {
- picking_viewport=false;
+ picking_viewport = false;
scene_tree->set_title(TTR("Pick a Node"));
scene_tree->popup_centered_ratio();
- } else if (p_which==1) {
-
+ } else if (p_which == 1) {
- v=NodePath();
+ v = NodePath();
emit_signal("variant_changed");
hide();
}
} break;
case Variant::OBJECT: {
- if (p_which==0) {
+ if (p_which == 0) {
+ ERR_FAIL_COND(inheritors_array.empty());
- ERR_FAIL_COND( inheritors_array.empty() );
+ String intype = inheritors_array[0];
- String intype=inheritors_array[0];
-
-
- if (hint==PROPERTY_HINT_RESOURCE_TYPE) {
+ if (hint == PROPERTY_HINT_RESOURCE_TYPE) {
Object *obj = ClassDB::instance(intype);
- ERR_BREAK( !obj );
- Resource *res=obj->cast_to<Resource>();
- ERR_BREAK( !res );
+ ERR_BREAK(!obj);
+ Resource *res = obj->cast_to<Resource>();
+ ERR_BREAK(!res);
- v=Ref<Resource>(res).get_ref_ptr();
+ v = Ref<Resource>(res).get_ref_ptr();
emit_signal("variant_changed");
hide();
-
}
- } else if (p_which==1) {
+ } else if (p_which == 1) {
file->set_access(EditorFileDialog::ACCESS_RESOURCES);
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
List<String> extensions;
- String type=(hint==PROPERTY_HINT_RESOURCE_TYPE)?hint_text:String();
+ String type = (hint == PROPERTY_HINT_RESOURCE_TYPE) ? hint_text : String();
- ResourceLoader::get_recognized_extensions_for_type(type,&extensions);
+ ResourceLoader::get_recognized_extensions_for_type(type, &extensions);
file->clear_filters();
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
-
- file->add_filter("*."+E->get()+" ; "+E->get().to_upper() );
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file->add_filter("*." + E->get() + " ; " + E->get().to_upper());
}
file->popup_centered_ratio();
- } else if (p_which==2) {
+ } else if (p_which == 2) {
- RefPtr RefPtr=v;
+ RefPtr RefPtr = v;
if (!RefPtr.is_null()) {
@@ -1388,48 +1342,46 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
hide();
}
- } else if (p_which==3) {
-
+ } else if (p_which == 3) {
- v=Variant();
+ v = Variant();
emit_signal("variant_changed");
hide();
- } else if (p_which==4) {
+ } else if (p_which == 4) {
-
- RefPtr RefPtr=v;
+ RefPtr RefPtr = v;
Ref<Resource> res_orig = RefPtr;
if (res_orig.is_null())
return;
List<PropertyInfo> property_list;
res_orig->get_property_list(&property_list);
- List< Pair<String,Variant> > propvalues;
+ List<Pair<String, Variant> > propvalues;
- for(List<PropertyInfo>::Element *E=property_list.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
- Pair<String,Variant> p;
+ Pair<String, Variant> p;
PropertyInfo &pi = E->get();
- if (pi.usage&PROPERTY_USAGE_STORAGE) {
+ if (pi.usage & PROPERTY_USAGE_STORAGE) {
- p.first=pi.name;
- p.second=res_orig->get(pi.name);
+ p.first = pi.name;
+ p.second = res_orig->get(pi.name);
}
propvalues.push_back(p);
}
- Ref<Resource> res = Ref<Resource>( ClassDB::instance( res_orig->get_class() ));
+ Ref<Resource> res = Ref<Resource>(ClassDB::instance(res_orig->get_class()));
ERR_FAIL_COND(res.is_null());
- for(List< Pair<String,Variant> >::Element *E=propvalues.front();E;E=E->next()) {
+ for (List<Pair<String, Variant> >::Element *E = propvalues.front(); E; E = E->next()) {
- Pair<String,Variant> &p=E->get();
- res->set(p.first,p.second);
+ Pair<String, Variant> &p = E->get();
+ res->set(p.first, p.second);
}
- v=res.get_ref_ptr();
+ v = res.get_ref_ptr();
emit_signal("variant_changed");
hide();
}
@@ -1437,11 +1389,11 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
} break;
case Variant::IMAGE: {
- if (p_which==0) {
+ if (p_which == 0) {
//new image too difficult
ERR_PRINT("New Image Unimplemented");
- } else if (p_which==1) {
+ } else if (p_which == 1) {
file->set_access(EditorFileDialog::ACCESS_RESOURCES);
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
@@ -1450,17 +1402,16 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
file->clear_filters();
- for (List<String>::Element *E=extensions.front();E;E=E->next()) {
-
- file->add_filter("*."+E->get()+" ; "+E->get().to_upper() );
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file->add_filter("*." + E->get() + " ; " + E->get().to_upper());
}
file->popup_centered_ratio();
- } else if (p_which==2) {
+ } else if (p_which == 2) {
- v=Image();
+ v = Image();
emit_signal("variant_changed");
hide();
}
@@ -1468,7 +1419,6 @@ void CustomPropertyEditor::_action_pressed(int p_which) {
} break;
default: {};
}
-
}
void CustomPropertyEditor::_scroll_modified(double p_value) {
@@ -1498,107 +1448,96 @@ void CustomPropertyEditor::_scroll_modified(double p_value) {
*/
}
+void CustomPropertyEditor::_drag_easing(const InputEvent &p_ev) {
-void CustomPropertyEditor::_drag_easing(const InputEvent& p_ev) {
-
-
- if (p_ev.type==InputEvent::MOUSE_MOTION && p_ev.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
+ if (p_ev.type == InputEvent::MOUSE_MOTION && p_ev.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
float rel = p_ev.mouse_motion.relative_x;
- if (rel==0)
+ if (rel == 0)
return;
- bool flip=hint_text=="attenuation";
+ bool flip = hint_text == "attenuation";
if (flip)
- rel=-rel;
+ rel = -rel;
float val = v;
- if (val==0)
+ if (val == 0)
return;
bool sg = val < 0;
val = Math::absf(val);
- val = Math::log(val)/Math::log((float)2.0);
+ val = Math::log(val) / Math::log((float)2.0);
//logspace
- val+=rel*0.05;
+ val += rel * 0.05;
//
- val = Math::pow(2.0f,val);
+ val = Math::pow(2.0f, val);
if (sg)
- val=-val;
+ val = -val;
- v=val;
+ v = val;
easing_draw->update();
//emit_signal("variant_changed");
emit_signal("variant_changed");
}
- if (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index==BUTTON_LEFT) {
-
-
+ if (p_ev.type == InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index == BUTTON_LEFT) {
}
-
}
-
void CustomPropertyEditor::_draw_easing() {
-
RID ci = easing_draw->get_canvas_item();
Size2 s = easing_draw->get_size();
- Rect2 r(Point2(),s);
- r=r.grow(3);
- get_stylebox("normal","LineEdit")->draw(ci,r);
+ Rect2 r(Point2(), s);
+ r = r.grow(3);
+ get_stylebox("normal", "LineEdit")->draw(ci, r);
//VisualServer::get_singleton()->canvas_item_add
-
int points = 48;
- float prev=1.0;
- float exp=v;
- bool flip=hint_text=="attenuation";
+ float prev = 1.0;
+ float exp = v;
+ bool flip = hint_text == "attenuation";
- Ref<Font> f = get_font("font","Label");
- Color color = get_color("font_color","Label");
+ Ref<Font> f = get_font("font", "Label");
+ Color color = get_color("font_color", "Label");
- for(int i=1;i<=points;i++) {
+ for (int i = 1; i <= points; i++) {
- float ifl = i/float(points);
- float iflp = (i-1)/float(points);
+ float ifl = i / float(points);
+ float iflp = (i - 1) / float(points);
- float h = 1.0-Math::ease(ifl,exp);
+ float h = 1.0 - Math::ease(ifl, exp);
if (flip) {
- ifl=1.0-ifl;
- iflp=1.0-iflp;
+ ifl = 1.0 - ifl;
+ iflp = 1.0 - iflp;
}
- VisualServer::get_singleton()->canvas_item_add_line(ci,Point2(iflp*s.width,prev*s.height),Point2(ifl*s.width,h*s.height),color);
- prev=h;
+ VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(iflp * s.width, prev * s.height), Point2(ifl * s.width, h * s.height), color);
+ prev = h;
}
- f->draw(ci,Point2(10,10+f->get_ascent()),String::num(exp,2),color);
+ f->draw(ci, Point2(10, 10 + f->get_ascent()), String::num(exp, 2), color);
}
void CustomPropertyEditor::_text_edit_changed() {
- v=text_edit->get_text();
+ v = text_edit->get_text();
emit_signal("variant_changed");
-
}
void CustomPropertyEditor::_create_dialog_callback() {
-
- v=create_dialog->get_selected_type();
+ v = create_dialog->get_selected_type();
emit_signal("variant_changed");
}
-void CustomPropertyEditor::_create_selected_property(const String& p_prop) {
-
+void CustomPropertyEditor::_create_selected_property(const String &p_prop) {
- v=p_prop;
+ v = p_prop;
emit_signal("variant_changed");
}
@@ -1606,46 +1545,44 @@ void CustomPropertyEditor::_modified(String p_string) {
if (updating)
return;
- updating=true;
- switch(type) {
+ updating = true;
+ switch (type) {
case Variant::INT: {
if (evaluator)
- v=evaluator->eval(value_editor[0]->get_text());
+ v = evaluator->eval(value_editor[0]->get_text());
else
- v=value_editor[0]->get_text().to_int();
+ v = value_editor[0]->get_text().to_int();
emit_signal("variant_changed");
-
} break;
case Variant::REAL: {
- if (hint!=PROPERTY_HINT_EXP_EASING) {
+ if (hint != PROPERTY_HINT_EXP_EASING) {
if (evaluator)
- v=evaluator->eval(value_editor[0]->get_text());
+ v = evaluator->eval(value_editor[0]->get_text());
else
- v=value_editor[0]->get_text().to_double();
+ v = value_editor[0]->get_text().to_double();
emit_signal("variant_changed");
-
}
} break;
case Variant::STRING: {
- v=value_editor[0]->get_text();
+ v = value_editor[0]->get_text();
emit_signal("variant_changed");
} break;
case Variant::VECTOR2: {
Vector2 vec;
if (evaluator) {
- vec.x=evaluator->eval(value_editor[0]->get_text());
- vec.y=evaluator->eval(value_editor[1]->get_text());
+ vec.x = evaluator->eval(value_editor[0]->get_text());
+ vec.y = evaluator->eval(value_editor[1]->get_text());
} else {
- vec.x=value_editor[0]->get_text().to_double();
- vec.y=value_editor[1]->get_text().to_double();
+ vec.x = value_editor[0]->get_text().to_double();
+ vec.y = value_editor[1]->get_text().to_double();
}
- v=vec;
+ v = vec;
_emit_changed_whole_or_field();
} break;
@@ -1653,17 +1590,17 @@ void CustomPropertyEditor::_modified(String p_string) {
Rect2 r2;
if (evaluator) {
- r2.pos.x=evaluator->eval(value_editor[0]->get_text());
- r2.pos.y=evaluator->eval(value_editor[1]->get_text());
- r2.size.x=evaluator->eval(value_editor[2]->get_text());
- r2.size.y=evaluator->eval(value_editor[3]->get_text());
+ r2.pos.x = evaluator->eval(value_editor[0]->get_text());
+ r2.pos.y = evaluator->eval(value_editor[1]->get_text());
+ r2.size.x = evaluator->eval(value_editor[2]->get_text());
+ r2.size.y = evaluator->eval(value_editor[3]->get_text());
} else {
- r2.pos.x=value_editor[0]->get_text().to_double();
- r2.pos.y=value_editor[1]->get_text().to_double();
- r2.size.x=value_editor[2]->get_text().to_double();
- r2.size.y=value_editor[3]->get_text().to_double();
+ r2.pos.x = value_editor[0]->get_text().to_double();
+ r2.pos.y = value_editor[1]->get_text().to_double();
+ r2.size.x = value_editor[2]->get_text().to_double();
+ r2.size.y = value_editor[3]->get_text().to_double();
}
- v=r2;
+ v = r2;
_emit_changed_whole_or_field();
} break;
@@ -1672,15 +1609,15 @@ void CustomPropertyEditor::_modified(String p_string) {
Vector3 vec;
if (evaluator) {
- vec.x=evaluator->eval(value_editor[0]->get_text());
- vec.y=evaluator->eval(value_editor[1]->get_text());
- vec.z=evaluator->eval(value_editor[2]->get_text());
+ vec.x = evaluator->eval(value_editor[0]->get_text());
+ vec.y = evaluator->eval(value_editor[1]->get_text());
+ vec.z = evaluator->eval(value_editor[2]->get_text());
} else {
- vec.x=value_editor[0]->get_text().to_double();
- vec.y=value_editor[1]->get_text().to_double();
- vec.z=value_editor[2]->get_text().to_double();
+ vec.x = value_editor[0]->get_text().to_double();
+ vec.y = value_editor[1]->get_text().to_double();
+ vec.z = value_editor[2]->get_text().to_double();
}
- v=vec;
+ v = vec;
_emit_changed_whole_or_field();
} break;
@@ -1688,17 +1625,17 @@ void CustomPropertyEditor::_modified(String p_string) {
Plane pl;
if (evaluator) {
- pl.normal.x=evaluator->eval(value_editor[0]->get_text());
- pl.normal.y=evaluator->eval(value_editor[1]->get_text());
- pl.normal.z=evaluator->eval(value_editor[2]->get_text());
- pl.d=evaluator->eval(value_editor[3]->get_text());
+ pl.normal.x = evaluator->eval(value_editor[0]->get_text());
+ pl.normal.y = evaluator->eval(value_editor[1]->get_text());
+ pl.normal.z = evaluator->eval(value_editor[2]->get_text());
+ pl.d = evaluator->eval(value_editor[3]->get_text());
} else {
- pl.normal.x=value_editor[0]->get_text().to_double();
- pl.normal.y=value_editor[1]->get_text().to_double();
- pl.normal.z=value_editor[2]->get_text().to_double();
- pl.d=value_editor[3]->get_text().to_double();
+ pl.normal.x = value_editor[0]->get_text().to_double();
+ pl.normal.y = value_editor[1]->get_text().to_double();
+ pl.normal.z = value_editor[2]->get_text().to_double();
+ pl.d = value_editor[3]->get_text().to_double();
}
- v=pl;
+ v = pl;
_emit_changed_whole_or_field();
} break;
@@ -1706,17 +1643,17 @@ void CustomPropertyEditor::_modified(String p_string) {
Quat q;
if (evaluator) {
- q.x=evaluator->eval(value_editor[0]->get_text());
- q.y=evaluator->eval(value_editor[1]->get_text());
- q.z=evaluator->eval(value_editor[2]->get_text());
- q.w=evaluator->eval(value_editor[3]->get_text());
+ q.x = evaluator->eval(value_editor[0]->get_text());
+ q.y = evaluator->eval(value_editor[1]->get_text());
+ q.z = evaluator->eval(value_editor[2]->get_text());
+ q.w = evaluator->eval(value_editor[3]->get_text());
} else {
- q.x=value_editor[0]->get_text().to_double();
- q.y=value_editor[1]->get_text().to_double();
- q.z=value_editor[2]->get_text().to_double();
- q.w=value_editor[3]->get_text().to_double();
+ q.x = value_editor[0]->get_text().to_double();
+ q.y = value_editor[1]->get_text().to_double();
+ q.z = value_editor[2]->get_text().to_double();
+ q.w = value_editor[3]->get_text().to_double();
}
- v=q;
+ v = q;
_emit_changed_whole_or_field();
} break;
@@ -1726,83 +1663,82 @@ void CustomPropertyEditor::_modified(String p_string) {
Vector3 size;
if (evaluator) {
- pos.x=evaluator->eval(value_editor[0]->get_text());
- pos.y=evaluator->eval(value_editor[1]->get_text());
- pos.z=evaluator->eval(value_editor[2]->get_text());
- size.x=evaluator->eval(value_editor[3]->get_text());
- size.y=evaluator->eval(value_editor[4]->get_text());
- size.z=evaluator->eval(value_editor[5]->get_text());
+ pos.x = evaluator->eval(value_editor[0]->get_text());
+ pos.y = evaluator->eval(value_editor[1]->get_text());
+ pos.z = evaluator->eval(value_editor[2]->get_text());
+ size.x = evaluator->eval(value_editor[3]->get_text());
+ size.y = evaluator->eval(value_editor[4]->get_text());
+ size.z = evaluator->eval(value_editor[5]->get_text());
} else {
- pos.x=value_editor[0]->get_text().to_double();
- pos.y=value_editor[1]->get_text().to_double();
- pos.z=value_editor[2]->get_text().to_double();
- size.x=value_editor[3]->get_text().to_double();
- size.y=value_editor[4]->get_text().to_double();
- size.z=value_editor[5]->get_text().to_double();
+ pos.x = value_editor[0]->get_text().to_double();
+ pos.y = value_editor[1]->get_text().to_double();
+ pos.z = value_editor[2]->get_text().to_double();
+ size.x = value_editor[3]->get_text().to_double();
+ size.y = value_editor[4]->get_text().to_double();
+ size.z = value_editor[5]->get_text().to_double();
}
- v=Rect3(pos,size);
+ v = Rect3(pos, size);
_emit_changed_whole_or_field();
} break;
case Variant::TRANSFORM2D: {
Transform2D m;
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
if (evaluator) {
- m.elements[i/2][i%2]=evaluator->eval(value_editor[i]->get_text());
+ m.elements[i / 2][i % 2] = evaluator->eval(value_editor[i]->get_text());
} else {
- m.elements[i/2][i%2]=value_editor[i]->get_text().to_double();
+ m.elements[i / 2][i % 2] = value_editor[i]->get_text().to_double();
}
}
- v=m;
+ v = m;
_emit_changed_whole_or_field();
} break;
case Variant::BASIS: {
Basis m;
- for(int i=0;i<9;i++) {
+ for (int i = 0; i < 9; i++) {
if (evaluator) {
- m.elements[i/3][i%3]=evaluator->eval(value_editor[i]->get_text());
+ m.elements[i / 3][i % 3] = evaluator->eval(value_editor[i]->get_text());
} else {
- m.elements[i/3][i%3]=value_editor[i]->get_text().to_double();
+ m.elements[i / 3][i % 3] = value_editor[i]->get_text().to_double();
}
}
- v=m;
+ v = m;
_emit_changed_whole_or_field();
} break;
case Variant::TRANSFORM: {
Basis basis;
- for(int i=0;i<9;i++) {
+ for (int i = 0; i < 9; i++) {
if (evaluator) {
- basis.elements[i/3][i%3]=evaluator->eval(value_editor[(i/3)*4+i%3]->get_text());
+ basis.elements[i / 3][i % 3] = evaluator->eval(value_editor[(i / 3) * 4 + i % 3]->get_text());
} else {
- basis.elements[i/3][i%3]=value_editor[(i/3)*4+i%3]->get_text().to_double();
+ basis.elements[i / 3][i % 3] = value_editor[(i / 3) * 4 + i % 3]->get_text().to_double();
}
}
Vector3 origin;
if (evaluator) {
- origin.x=evaluator->eval(value_editor[3]->get_text());
- origin.y=evaluator->eval(value_editor[7]->get_text());
- origin.z=evaluator->eval(value_editor[11]->get_text());
+ origin.x = evaluator->eval(value_editor[3]->get_text());
+ origin.y = evaluator->eval(value_editor[7]->get_text());
+ origin.z = evaluator->eval(value_editor[11]->get_text());
} else {
- origin.x=value_editor[3]->get_text().to_double();
- origin.y=value_editor[7]->get_text().to_double();
- origin.z=value_editor[11]->get_text().to_double();
+ origin.x = value_editor[3]->get_text().to_double();
+ origin.y = value_editor[7]->get_text().to_double();
+ origin.z = value_editor[11]->get_text().to_double();
}
- v=Transform(basis,origin);
+ v = Transform(basis, origin);
_emit_changed_whole_or_field();
-
} break;
case Variant::COLOR: {
/*
@@ -1822,49 +1758,40 @@ void CustomPropertyEditor::_modified(String p_string) {
} break;
case Variant::IMAGE: {
-
} break;
case Variant::NODE_PATH: {
- v=NodePath(value_editor[0]->get_text());
+ v = NodePath(value_editor[0]->get_text());
emit_signal("variant_changed");
} break;
case Variant::INPUT_EVENT: {
-
} break;
case Variant::DICTIONARY: {
-
} break;
case Variant::POOL_BYTE_ARRAY: {
-
} break;
case Variant::POOL_INT_ARRAY: {
-
} break;
case Variant::POOL_REAL_ARRAY: {
-
} break;
case Variant::POOL_STRING_ARRAY: {
-
} break;
case Variant::POOL_VECTOR3_ARRAY: {
-
} break;
case Variant::POOL_COLOR_ARRAY: {
-
} break;
default: {}
}
- updating=false;
+ updating = false;
}
void CustomPropertyEditor::_emit_changed_whole_or_field() {
@@ -1872,18 +1799,17 @@ void CustomPropertyEditor::_emit_changed_whole_or_field() {
if (!Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
emit_signal("variant_changed");
} else {
- emit_signal("variant_field_changed",field_names[focused_value_editor]);
+ emit_signal("variant_field_changed", field_names[focused_value_editor]);
}
}
-void CustomPropertyEditor::_range_modified(double p_value)
-{
- v=p_value;
+void CustomPropertyEditor::_range_modified(double p_value) {
+ v = p_value;
emit_signal("variant_changed");
}
void CustomPropertyEditor::_focus_enter() {
- switch(type) {
+ switch (type) {
case Variant::REAL:
case Variant::STRING:
case Variant::VECTOR2:
@@ -1895,9 +1821,9 @@ void CustomPropertyEditor::_focus_enter() {
case Variant::TRANSFORM2D:
case Variant::BASIS:
case Variant::TRANSFORM: {
- for (int i=0;i<MAX_VALUE_EDITORS;++i) {
+ for (int i = 0; i < MAX_VALUE_EDITORS; ++i) {
if (value_editor[i]->has_focus()) {
- focused_value_editor=i;
+ focused_value_editor = i;
value_editor[i]->select_all();
break;
}
@@ -1905,11 +1831,10 @@ void CustomPropertyEditor::_focus_enter() {
} break;
default: {}
}
-
}
void CustomPropertyEditor::_focus_exit() {
- switch(type) {
+ switch (type) {
case Variant::REAL:
case Variant::STRING:
case Variant::VECTOR2:
@@ -1921,225 +1846,211 @@ void CustomPropertyEditor::_focus_exit() {
case Variant::TRANSFORM2D:
case Variant::BASIS:
case Variant::TRANSFORM: {
- for (int i=0;i<MAX_VALUE_EDITORS;++i) {
+ for (int i = 0; i < MAX_VALUE_EDITORS; ++i) {
value_editor[i]->select(0, 0);
}
} break;
default: {}
}
-
}
-void CustomPropertyEditor::config_action_buttons(const List<String>& p_strings) {
+void CustomPropertyEditor::config_action_buttons(const List<String> &p_strings) {
- int w=100;
- int h=18;
- int m=5;
+ int w = 100;
+ int h = 18;
+ int m = 5;
- set_size( Size2( w, m*2+(h+m)*p_strings.size() ) );
+ set_size(Size2(w, m * 2 + (h + m) * p_strings.size()));
- for (int i=0;i<MAX_ACTION_BUTTONS;i++) {
+ for (int i = 0; i < MAX_ACTION_BUTTONS; i++) {
- if (i<p_strings.size()) {
+ if (i < p_strings.size()) {
action_buttons[i]->show();
action_buttons[i]->set_text(p_strings[i]);
- action_buttons[i]->set_pos( Point2( m, m+i*(h+m) ));
- action_buttons[i]->set_size( Size2( w-m*2, h ) );
+ action_buttons[i]->set_pos(Point2(m, m + i * (h + m)));
+ action_buttons[i]->set_size(Size2(w - m * 2, h));
action_buttons[i]->set_flat(true);
} else {
action_buttons[i]->hide();
}
}
-
-
}
-void CustomPropertyEditor::config_value_editors(int p_amount, int p_columns,int p_label_w,const List<String>& p_strings) {
+void CustomPropertyEditor::config_value_editors(int p_amount, int p_columns, int p_label_w, const List<String> &p_strings) {
- int w=80;
- int h=20;
- int m=10;
+ int w = 80;
+ int h = 20;
+ int m = 10;
- int rows=((p_amount-1)/p_columns)+1;
+ int rows = ((p_amount - 1) / p_columns) + 1;
- set_size( Size2( m*(1+p_columns)+(w+p_label_w)*p_columns, m*(1+rows)+h*rows ) );
+ set_size(Size2(m * (1 + p_columns) + (w + p_label_w) * p_columns, m * (1 + rows) + h * rows));
- for (int i=0;i<MAX_VALUE_EDITORS;i++) {
+ for (int i = 0; i < MAX_VALUE_EDITORS; i++) {
- int c=i%p_columns;
- int r=i/p_columns;
+ int c = i % p_columns;
+ int r = i / p_columns;
- if (i<p_amount) {
+ if (i < p_amount) {
value_editor[i]->show();
value_label[i]->show();
- value_label[i]->set_text(i<p_strings.size()?p_strings[i]:String(""));
- value_editor[i]->set_pos( Point2( m+p_label_w+c*(w+m+p_label_w), m+r*(h+m) ));
- value_editor[i]->set_size( Size2( w, h ) );
- value_label[i]->set_pos( Point2( m+c*(w+m+p_label_w), m+r*(h+m) ) );
+ value_label[i]->set_text(i < p_strings.size() ? p_strings[i] : String(""));
+ value_editor[i]->set_pos(Point2(m + p_label_w + c * (w + m + p_label_w), m + r * (h + m)));
+ value_editor[i]->set_size(Size2(w, h));
+ value_label[i]->set_pos(Point2(m + c * (w + m + p_label_w), m + r * (h + m)));
value_editor[i]->set_editable(!read_only);
} else {
value_editor[i]->hide();
value_label[i]->hide();
}
}
-
-
-
}
-
void CustomPropertyEditor::_bind_methods() {
ClassDB::bind_method("_focus_enter", &CustomPropertyEditor::_focus_enter);
ClassDB::bind_method("_focus_exit", &CustomPropertyEditor::_focus_exit);
- ClassDB::bind_method("_modified",&CustomPropertyEditor::_modified);
+ ClassDB::bind_method("_modified", &CustomPropertyEditor::_modified);
ClassDB::bind_method("_range_modified", &CustomPropertyEditor::_range_modified);
- ClassDB::bind_method("_scroll_modified",&CustomPropertyEditor::_scroll_modified);
- ClassDB::bind_method("_action_pressed",&CustomPropertyEditor::_action_pressed);
- ClassDB::bind_method("_file_selected",&CustomPropertyEditor::_file_selected);
- ClassDB::bind_method("_type_create_selected",&CustomPropertyEditor::_type_create_selected);
- ClassDB::bind_method("_node_path_selected",&CustomPropertyEditor::_node_path_selected);
- ClassDB::bind_method("_color_changed",&CustomPropertyEditor::_color_changed);
- ClassDB::bind_method("_draw_easing",&CustomPropertyEditor::_draw_easing);
- ClassDB::bind_method("_drag_easing",&CustomPropertyEditor::_drag_easing);
- ClassDB::bind_method( "_text_edit_changed",&CustomPropertyEditor::_text_edit_changed);
- ClassDB::bind_method( "_menu_option",&CustomPropertyEditor::_menu_option);
- ClassDB::bind_method( "_create_dialog_callback",&CustomPropertyEditor::_create_dialog_callback);
- ClassDB::bind_method( "_create_selected_property",&CustomPropertyEditor::_create_selected_property);
-
-
-
- ADD_SIGNAL( MethodInfo("variant_changed") );
- ADD_SIGNAL( MethodInfo("variant_field_changed",PropertyInfo(Variant::STRING,"field")) );
- ADD_SIGNAL( MethodInfo("resource_edit_request") );
+ ClassDB::bind_method("_scroll_modified", &CustomPropertyEditor::_scroll_modified);
+ ClassDB::bind_method("_action_pressed", &CustomPropertyEditor::_action_pressed);
+ ClassDB::bind_method("_file_selected", &CustomPropertyEditor::_file_selected);
+ ClassDB::bind_method("_type_create_selected", &CustomPropertyEditor::_type_create_selected);
+ ClassDB::bind_method("_node_path_selected", &CustomPropertyEditor::_node_path_selected);
+ ClassDB::bind_method("_color_changed", &CustomPropertyEditor::_color_changed);
+ ClassDB::bind_method("_draw_easing", &CustomPropertyEditor::_draw_easing);
+ ClassDB::bind_method("_drag_easing", &CustomPropertyEditor::_drag_easing);
+ ClassDB::bind_method("_text_edit_changed", &CustomPropertyEditor::_text_edit_changed);
+ ClassDB::bind_method("_menu_option", &CustomPropertyEditor::_menu_option);
+ ClassDB::bind_method("_create_dialog_callback", &CustomPropertyEditor::_create_dialog_callback);
+ ClassDB::bind_method("_create_selected_property", &CustomPropertyEditor::_create_selected_property);
+
+ ADD_SIGNAL(MethodInfo("variant_changed"));
+ ADD_SIGNAL(MethodInfo("variant_field_changed", PropertyInfo(Variant::STRING, "field")));
+ ADD_SIGNAL(MethodInfo("resource_edit_request"));
}
CustomPropertyEditor::CustomPropertyEditor() {
+ read_only = false;
+ updating = false;
- read_only=false;
- updating=false;
-
- for (int i=0;i<MAX_VALUE_EDITORS;i++) {
+ for (int i = 0; i < MAX_VALUE_EDITORS; i++) {
- value_editor[i]=memnew( LineEdit );
- add_child( value_editor[i] );
- value_label[i]=memnew( Label );
- add_child( value_label[i] );
+ value_editor[i] = memnew(LineEdit);
+ add_child(value_editor[i]);
+ value_label[i] = memnew(Label);
+ add_child(value_label[i]);
value_editor[i]->hide();
value_label[i]->hide();
- value_editor[i]->connect("text_entered", this,"_modified");
+ value_editor[i]->connect("text_entered", this, "_modified");
value_editor[i]->connect("focus_entered", this, "_focus_enter");
value_editor[i]->connect("focus_exited", this, "_focus_exit");
}
- focused_value_editor=-1;
+ focused_value_editor = -1;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- scroll[i] = memnew( HScrollBar );
+ scroll[i] = memnew(HScrollBar);
scroll[i]->hide();
scroll[i]->set_min(0);
scroll[i]->set_max(1.0);
scroll[i]->set_step(0.01);
add_child(scroll[i]);
- scroll[i]->connect("value_changed", this,"_scroll_modified");
-
+ scroll[i]->connect("value_changed", this, "_scroll_modified");
}
- checks20gc = memnew( GridContainer );
+ checks20gc = memnew(GridContainer);
add_child(checks20gc);
checks20gc->set_columns(11);
- for(int i=0;i<20;i++) {
- if (i==5 || i==15) {
- Control *space = memnew( Control );
- space->set_custom_minimum_size(Size2(20,0)*EDSCALE);
+ for (int i = 0; i < 20; i++) {
+ if (i == 5 || i == 15) {
+ Control *space = memnew(Control);
+ space->set_custom_minimum_size(Size2(20, 0) * EDSCALE);
checks20gc->add_child(space);
}
- checks20[i]=memnew( CheckBox );
+ checks20[i] = memnew(CheckBox);
checks20[i]->set_toggle_mode(true);
- checks20[i]->set_focus_mode(FOCUS_NONE);
+ checks20[i]->set_focus_mode(FOCUS_NONE);
checks20gc->add_child(checks20[i]);
checks20[i]->hide();
- checks20[i]->connect("pressed",this,"_action_pressed",make_binds(i));
- checks20[i]->set_tooltip(vformat(TTR("Bit %d, val %d."), i, 1<<i));
+ checks20[i]->connect("pressed", this, "_action_pressed", make_binds(i));
+ checks20[i]->set_tooltip(vformat(TTR("Bit %d, val %d."), i, 1 << i));
}
- text_edit = memnew( TextEdit );
+ text_edit = memnew(TextEdit);
add_child(text_edit);
text_edit->set_area_as_parent_rect();
- for(int i=0;i<4;i++)
- text_edit->set_margin((Margin)i,5);
- text_edit->set_margin(MARGIN_BOTTOM,30);
+ for (int i = 0; i < 4; i++)
+ text_edit->set_margin((Margin)i, 5);
+ text_edit->set_margin(MARGIN_BOTTOM, 30);
text_edit->hide();
- text_edit->connect("text_changed",this,"_text_edit_changed");
+ text_edit->connect("text_changed", this, "_text_edit_changed");
- for (int i=0;i<MAX_ACTION_BUTTONS;i++) {
+ for (int i = 0; i < MAX_ACTION_BUTTONS; i++) {
- action_buttons[i]=memnew(Button);
+ action_buttons[i] = memnew(Button);
action_buttons[i]->hide();
add_child(action_buttons[i]);
Vector<Variant> binds;
binds.push_back(i);
- action_buttons[i]->connect("pressed", this,"_action_pressed",binds);
+ action_buttons[i]->connect("pressed", this, "_action_pressed", binds);
}
- color_picker=NULL;
-
-
+ color_picker = NULL;
set_as_toplevel(true);
- file = memnew ( EditorFileDialog );
+ file = memnew(EditorFileDialog);
add_child(file);
file->hide();
- file->connect("file_selected", this,"_file_selected");
- file->connect("dir_selected", this,"_file_selected");
+ file->connect("file_selected", this, "_file_selected");
+ file->connect("dir_selected", this, "_file_selected");
- error = memnew( ConfirmationDialog );
+ error = memnew(ConfirmationDialog);
error->set_title(TTR("Error!"));
add_child(error);
//error->get_cancel()->hide();
- type_button = memnew( MenuButton );
+ type_button = memnew(MenuButton);
add_child(type_button);
type_button->hide();
- type_button->get_popup()->connect("id_pressed", this,"_type_create_selected");
+ type_button->get_popup()->connect("id_pressed", this, "_type_create_selected");
-
- scene_tree = memnew( SceneTreeDialog );
+ scene_tree = memnew(SceneTreeDialog);
add_child(scene_tree);
- scene_tree->connect("selected", this,"_node_path_selected");
+ scene_tree->connect("selected", this, "_node_path_selected");
scene_tree->get_scene_tree()->set_show_enabled_subscene(true);
- texture_preview = memnew( TextureRect );
- add_child( texture_preview);
+ texture_preview = memnew(TextureRect);
+ add_child(texture_preview);
texture_preview->hide();
- easing_draw=memnew( Control );
+ easing_draw = memnew(Control);
add_child(easing_draw);
easing_draw->hide();
- easing_draw->connect("draw",this,"_draw_easing");
- easing_draw->connect("gui_input",this,"_drag_easing");
+ easing_draw->connect("draw", this, "_draw_easing");
+ easing_draw->connect("gui_input", this, "_drag_easing");
//easing_draw->emit_signal(SceneStringNames::get_singleton()->input_event,InputEvent());
easing_draw->set_default_cursor_shape(Control::CURSOR_MOVE);
menu = memnew(PopupMenu);
add_child(menu);
- menu->connect("id_pressed",this,"_menu_option");
+ menu->connect("id_pressed", this, "_menu_option");
evaluator = NULL;
- spinbox = memnew ( SpinBox );
+ spinbox = memnew(SpinBox);
add_child(spinbox);
spinbox->set_area_as_parent_rect(5);
- spinbox->connect("value_changed",this,"_range_modified");
+ spinbox->connect("value_changed", this, "_range_modified");
- slider = memnew ( HSlider );
+ slider = memnew(HSlider);
add_child(slider);
slider->set_area_as_parent_rect(5);
- slider->connect("value_changed",this,"_range_modified");
+ slider->connect("value_changed", this, "_range_modified");
create_dialog = NULL;
property_select = NULL;
@@ -2152,56 +2063,54 @@ bool PropertyEditor::_might_be_in_instance() {
Node *node = obj->cast_to<Node>();
- Node* edited_scene =EditorNode::get_singleton()->get_edited_scene();
+ Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
- bool might_be=false;
+ bool might_be = false;
- while(node) {
+ while (node) {
if (node->get_scene_instance_state().is_valid()) {
- might_be=true;
+ might_be = true;
break;
}
- if (node==edited_scene) {
+ if (node == edited_scene) {
if (node->get_scene_inherited_state().is_valid()) {
- might_be=true;
+ might_be = true;
break;
}
- might_be=false;
+ might_be = false;
break;
}
- node=node->get_owner();
+ node = node->get_owner();
}
return might_be;
-
}
-bool PropertyEditor::_get_instanced_node_original_property(const StringName& p_prop, Variant& value) {
+bool PropertyEditor::_get_instanced_node_original_property(const StringName &p_prop, Variant &value) {
Node *node = obj->cast_to<Node>();
if (!node)
return false;
- Node *orig=node;
+ Node *orig = node;
- Node* edited_scene =EditorNode::get_singleton()->get_edited_scene();
+ Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
- bool found=false;
+ bool found = false;
//print_line("for prop - "+String(p_prop));
-
- while(node) {
+ while (node) {
Ref<SceneState> ss;
- if (node==edited_scene) {
- ss=node->get_scene_inherited_state();
+ if (node == edited_scene) {
+ ss = node->get_scene_inherited_state();
} else {
- ss=node->get_scene_instance_state();
+ ss = node->get_scene_instance_state();
}
//print_line("at - "+String(edited_scene->get_path_to(node)));
@@ -2210,239 +2119,223 @@ bool PropertyEditor::_get_instanced_node_original_property(const StringName& p_p
NodePath np = node->get_path_to(orig);
int node_idx = ss->find_node_by_path(np);
//print_line("\t valid, nodeidx "+itos(node_idx));
- if (node_idx>=0) {
- bool lfound=false;
+ if (node_idx >= 0) {
+ bool lfound = false;
Variant lvar;
- lvar=ss->get_property_value(node_idx,p_prop,lfound);
+ lvar = ss->get_property_value(node_idx, p_prop, lfound);
if (lfound) {
- found=true;
- value=lvar;
+ found = true;
+ value = lvar;
//print_line("\t found value "+String(value));
}
}
}
- if (node==edited_scene) {
+ if (node == edited_scene) {
//just in case
break;
}
- node=node->get_owner();
-
+ node = node->get_owner();
}
return found;
}
-bool PropertyEditor::_is_property_different(const Variant& p_current, const Variant& p_orig,int p_usage) {
-
+bool PropertyEditor::_is_property_different(const Variant &p_current, const Variant &p_orig, int p_usage) {
{
Node *node = obj->cast_to<Node>();
if (!node)
return false;
- Node* edited_scene =EditorNode::get_singleton()->get_edited_scene();
- bool found_state=false;
+ Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
+ bool found_state = false;
//print_line("for prop - "+String(p_prop));
-
- while(node) {
+ while (node) {
Ref<SceneState> ss;
- if (node==edited_scene) {
- ss=node->get_scene_inherited_state();
+ if (node == edited_scene) {
+ ss = node->get_scene_inherited_state();
} else {
- ss=node->get_scene_instance_state();
+ ss = node->get_scene_instance_state();
}
if (ss.is_valid()) {
- found_state=true;
+ found_state = true;
}
- if (node==edited_scene) {
+ if (node == edited_scene) {
//just in case
break;
}
- node=node->get_owner();
+ node = node->get_owner();
}
if (!found_state)
return false; //pointless to check if we are not comparing against anything.
}
- if (p_orig.get_type()==Variant::NIL) {
-
-
+ if (p_orig.get_type() == Variant::NIL) {
//special cases
- if (p_current.is_zero() && p_usage&PROPERTY_USAGE_STORE_IF_NONZERO)
+ if (p_current.is_zero() && p_usage & PROPERTY_USAGE_STORE_IF_NONZERO)
return false;
- if (p_current.is_one() && p_usage&PROPERTY_USAGE_STORE_IF_NONONE)
+ if (p_current.is_one() && p_usage & PROPERTY_USAGE_STORE_IF_NONONE)
return false;
}
- if (p_current.get_type()==Variant::REAL && p_orig.get_type()==Variant::REAL) {
+ if (p_current.get_type() == Variant::REAL && p_orig.get_type() == Variant::REAL) {
float a = p_current;
float b = p_orig;
- return Math::abs(a-b)>CMP_EPSILON; //this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error
+ return Math::abs(a - b) > CMP_EPSILON; //this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error
}
- return bool(Variant::evaluate(Variant::OP_NOT_EQUAL,p_current,p_orig));
+ return bool(Variant::evaluate(Variant::OP_NOT_EQUAL, p_current, p_orig));
}
-TreeItem *PropertyEditor::find_item(TreeItem *p_item,const String& p_name) {
-
+TreeItem *PropertyEditor::find_item(TreeItem *p_item, const String &p_name) {
if (!p_item)
return NULL;
String name = p_item->get_metadata(1);
- if (name==p_name) {
+ if (name == p_name) {
return p_item;
}
- TreeItem *c=p_item->get_children();
+ TreeItem *c = p_item->get_children();
while (c) {
- TreeItem *found = find_item(c,p_name);
+ TreeItem *found = find_item(c, p_name);
if (found)
return found;
- c=c->get_next();
+ c = c->get_next();
}
return NULL;
}
+void PropertyEditor::_changed_callback(Object *p_changed, const char *p_prop) {
-void PropertyEditor::_changed_callback(Object *p_changed,const char * p_prop) {
-
-
- _changed_callbacks(p_changed,p_prop);
+ _changed_callbacks(p_changed, p_prop);
}
-void PropertyEditor::_changed_callbacks(Object *p_changed,const String& p_prop) {
+void PropertyEditor::_changed_callbacks(Object *p_changed, const String &p_prop) {
-
- if (p_changed!=obj)
+ if (p_changed != obj)
return;
if (changing)
return;
- if (p_prop==String())
- update_tree_pending=true;
+ if (p_prop == String())
+ update_tree_pending = true;
else {
- pending[p_prop]=p_prop;
-
+ pending[p_prop] = p_prop;
}
}
-void PropertyEditor::update_property(const String& p_prop) {
+void PropertyEditor::update_property(const String &p_prop) {
if (obj)
- _changed_callbacks(obj,p_prop);
+ _changed_callbacks(obj, p_prop);
}
+void PropertyEditor::set_item_text(TreeItem *p_item, int p_type, const String &p_name, int p_hint, const String &p_hint_text) {
-void PropertyEditor::set_item_text(TreeItem *p_item, int p_type, const String& p_name, int p_hint, const String& p_hint_text) {
-
- switch( p_type ) {
+ switch (p_type) {
case Variant::BOOL: {
- p_item->set_checked( 1, obj->get( p_name ) );
+ p_item->set_checked(1, obj->get(p_name));
} break;
case Variant::REAL:
case Variant::INT: {
- if (p_hint==PROPERTY_HINT_LAYERS_2D_PHYSICS || p_hint==PROPERTY_HINT_LAYERS_2D_RENDER || p_hint==PROPERTY_HINT_LAYERS_3D_PHYSICS || p_hint==PROPERTY_HINT_LAYERS_3D_RENDER) {
+ if (p_hint == PROPERTY_HINT_LAYERS_2D_PHYSICS || p_hint == PROPERTY_HINT_LAYERS_2D_RENDER || p_hint == PROPERTY_HINT_LAYERS_3D_PHYSICS || p_hint == PROPERTY_HINT_LAYERS_3D_RENDER) {
tree->update();
break;
}
- if (p_hint==PROPERTY_HINT_FLAGS) {
+ if (p_hint == PROPERTY_HINT_FLAGS) {
Vector<String> values = p_hint_text.split(",");
String flags;
int val = obj->get(p_name);
- for(int i=0;i<values.size();i++) {
+ for (int i = 0; i < values.size(); i++) {
String v = values[i];
- if (v=="")
+ if (v == "")
continue;
- if (!(val&(1<<i)))
+ if (!(val & (1 << i)))
continue;
- if (flags!="")
- flags+=", ";
- flags+=v;
+ if (flags != "")
+ flags += ", ";
+ flags += v;
}
- p_item->set_text(1, flags );
+ p_item->set_text(1, flags);
break;
}
- if (p_hint==PROPERTY_HINT_EXP_EASING) {
+ if (p_hint == PROPERTY_HINT_EXP_EASING) {
- p_item->set_text(1, String::num(obj->get( p_name ),2) );
+ p_item->set_text(1, String::num(obj->get(p_name), 2));
break;
}
-
//p_item->set_cell_mode( 1, TreeItem::CELL_MODE_RANGE );
- if (p_type==Variant::REAL) {
- p_item->set_range(1, obj->get( p_name ) );
+ if (p_type == Variant::REAL) {
+ p_item->set_range(1, obj->get(p_name));
} else {
/* FIXME: Why are both statements equal? */
- p_item->set_range(1, obj->get( p_name ) );
+ p_item->set_range(1, obj->get(p_name));
}
-
- p_item->set_editable(1,!read_only);
-
+ p_item->set_editable(1, !read_only);
} break;
case Variant::STRING:
+ if (p_hint == PROPERTY_HINT_TYPE_STRING) {
- if (p_hint==PROPERTY_HINT_TYPE_STRING) {
-
- p_item->set_text(1,obj->get(p_name));
+ p_item->set_text(1, obj->get(p_name));
}
- if ( p_hint==PROPERTY_HINT_METHOD_OF_VARIANT_TYPE ||
- p_hint==PROPERTY_HINT_METHOD_OF_BASE_TYPE ||
- p_hint==PROPERTY_HINT_METHOD_OF_INSTANCE ||
- p_hint==PROPERTY_HINT_METHOD_OF_SCRIPT ||
- p_hint==PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE ||
- p_hint==PROPERTY_HINT_PROPERTY_OF_BASE_TYPE ||
- p_hint==PROPERTY_HINT_PROPERTY_OF_INSTANCE ||
- p_hint==PROPERTY_HINT_PROPERTY_OF_SCRIPT ) {
+ if (p_hint == PROPERTY_HINT_METHOD_OF_VARIANT_TYPE ||
+ p_hint == PROPERTY_HINT_METHOD_OF_BASE_TYPE ||
+ p_hint == PROPERTY_HINT_METHOD_OF_INSTANCE ||
+ p_hint == PROPERTY_HINT_METHOD_OF_SCRIPT ||
+ p_hint == PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE ||
+ p_hint == PROPERTY_HINT_PROPERTY_OF_BASE_TYPE ||
+ p_hint == PROPERTY_HINT_PROPERTY_OF_INSTANCE ||
+ p_hint == PROPERTY_HINT_PROPERTY_OF_SCRIPT) {
- p_item->set_text(1,obj->get(p_name));
+ p_item->set_text(1, obj->get(p_name));
}
-
- if (p_hint==PROPERTY_HINT_ENUM) {
+ if (p_hint == PROPERTY_HINT_ENUM) {
Vector<String> strings = p_hint_text.split(",");
String current = obj->get(p_name);
- int idx=0;
- for(int x=0;x<strings.size();x++) {
- if (strings[x]==current) {
- idx=x;
+ int idx = 0;
+ for (int x = 0; x < strings.size(); x++) {
+ if (strings[x] == current) {
+ idx = x;
break;
}
}
p_item->set_text(1, p_hint_text);
- p_item->set_range(1,idx);
+ p_item->set_range(1, idx);
break;
}
@@ -2455,7 +2348,7 @@ void PropertyEditor::set_item_text(TreeItem *p_item, int p_type, const String& p
case Variant::BASIS:
case Variant::TRANSFORM: {
- p_item->set_text(1,obj->get(p_name));
+ p_item->set_text(1, obj->get(p_name));
} break;
case Variant::COLOR: {
@@ -2466,209 +2359,188 @@ void PropertyEditor::set_item_text(TreeItem *p_item, int p_type, const String& p
} break;
case Variant::IMAGE: {
- Image img = obj->get( p_name );
+ Image img = obj->get(p_name);
if (img.empty())
- p_item->set_text(1,"[Image (empty)]");
+ p_item->set_text(1, "[Image (empty)]");
else
- p_item->set_text(1,"[Image "+itos(img.get_width())+"x"+itos(img.get_height())+"-"+String(Image::get_format_name(img.get_format()))+"]");
+ p_item->set_text(1, "[Image " + itos(img.get_width()) + "x" + itos(img.get_height()) + "-" + String(Image::get_format_name(img.get_format())) + "]");
} break;
case Variant::NODE_PATH: {
- p_item->set_text(1,obj->get(p_name));
+ p_item->set_text(1, obj->get(p_name));
} break;
case Variant::OBJECT: {
-
- if (obj->get( p_name ).get_type() == Variant::NIL || obj->get( p_name ).operator RefPtr().is_null()) {
- p_item->set_text(1,"<null>");
- p_item->set_icon(1,Ref<Texture>());
+ if (obj->get(p_name).get_type() == Variant::NIL || obj->get(p_name).operator RefPtr().is_null()) {
+ p_item->set_text(1, "<null>");
+ p_item->set_icon(1, Ref<Texture>());
Dictionary d = p_item->get_metadata(0);
- int hint=d.has("hint")?d["hint"].operator int():-1;
- String hint_text=d.has("hint_text")?d["hint_text"]:"";
- if (hint==PROPERTY_HINT_RESOURCE_TYPE && hint_text == "Texture") {
- p_item->set_icon(1,NULL);
+ int hint = d.has("hint") ? d["hint"].operator int() : -1;
+ String hint_text = d.has("hint_text") ? d["hint_text"] : "";
+ if (hint == PROPERTY_HINT_RESOURCE_TYPE && hint_text == "Texture") {
+ p_item->set_icon(1, NULL);
}
} else {
- RES res = obj->get( p_name ).operator RefPtr();
+ RES res = obj->get(p_name).operator RefPtr();
if (res->is_class("Texture")) {
int tw = EditorSettings::get_singleton()->get("docks/property_editor/texture_preview_width");
- p_item->set_icon_max_width(1,tw);
- p_item->set_icon(1,res);
- p_item->set_text(1,"");
+ p_item->set_icon_max_width(1, tw);
+ p_item->set_icon(1, res);
+ p_item->set_text(1, "");
} else if (res->get_name() != "") {
p_item->set_text(1, res->get_name());
- } else if (res->get_path()!="" && !res->get_path().begins_with("local://")) {
+ } else if (res->get_path() != "" && !res->get_path().begins_with("local://")) {
p_item->set_text(1, res->get_path().get_file());
} else {
- p_item->set_text(1,"<"+res->get_class()+">");
+ p_item->set_text(1, "<" + res->get_class() + ">");
};
-
if (res.is_valid() && res->get_path().is_resource_file()) {
- p_item->set_tooltip(1,res->get_path());
+ p_item->set_tooltip(1, res->get_path());
} else if (res.is_valid()) {
- p_item->set_tooltip(1,res->get_name()+" ("+res->get_class()+")");
+ p_item->set_tooltip(1, res->get_name() + " (" + res->get_class() + ")");
}
+ if (has_icon(res->get_class(), "EditorIcons")) {
- if (has_icon(res->get_class(),"EditorIcons")) {
-
- p_item->set_icon(0,get_icon(res->get_class(),"EditorIcons"));
+ p_item->set_icon(0, get_icon(res->get_class(), "EditorIcons"));
} else {
Dictionary d = p_item->get_metadata(0);
- int hint=d.has("hint")?d["hint"].operator int():-1;
- String hint_text=d.has("hint_text")?d["hint_text"]:"";
- if (hint==PROPERTY_HINT_RESOURCE_TYPE) {
+ int hint = d.has("hint") ? d["hint"].operator int() : -1;
+ String hint_text = d.has("hint_text") ? d["hint_text"] : "";
+ if (hint == PROPERTY_HINT_RESOURCE_TYPE) {
- if (has_icon(hint_text,"EditorIcons")) {
+ if (has_icon(hint_text, "EditorIcons")) {
- p_item->set_icon(0,get_icon(hint_text,"EditorIcons"));
+ p_item->set_icon(0, get_icon(hint_text, "EditorIcons"));
} else {
- p_item->set_icon(0,get_icon("Object","EditorIcons"));
-
+ p_item->set_icon(0, get_icon("Object", "EditorIcons"));
}
}
}
if (!res->is_class("Texture")) {
//texture already previews via itself
- EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res,this,"_resource_preview_done",p_item->get_instance_ID());
+ EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_resource_preview_done", p_item->get_instance_ID());
}
-
-
-
}
-
} break;
default: {};
}
-
}
+void PropertyEditor::_check_reload_status(const String &p_name, TreeItem *item) {
-void PropertyEditor::_check_reload_status(const String&p_name, TreeItem* item) {
-
- bool has_reload=false;
- int found=-1;
- bool is_disabled=false;
+ bool has_reload = false;
+ int found = -1;
+ bool is_disabled = false;
- for(int i=0;i<item->get_button_count(1);i++) {
+ for (int i = 0; i < item->get_button_count(1); i++) {
- if (item->get_button_id(1,i)==3) {
- found=i;
- is_disabled=item->is_button_disabled(1,i);
+ if (item->get_button_id(1, i) == 3) {
+ found = i;
+ is_disabled = item->is_button_disabled(1, i);
break;
}
}
if (_might_be_in_instance()) {
-
Variant vorig;
- Dictionary d=item->get_metadata(0);
- int usage = d.has("usage")?int(int(d["usage"])&(PROPERTY_USAGE_STORE_IF_NONONE|PROPERTY_USAGE_STORE_IF_NONZERO)):0;
-
+ Dictionary d = item->get_metadata(0);
+ int usage = d.has("usage") ? int(int(d["usage"]) & (PROPERTY_USAGE_STORE_IF_NONONE | PROPERTY_USAGE_STORE_IF_NONZERO)) : 0;
- if (_get_instanced_node_original_property(p_name,vorig) || usage) {
+ if (_get_instanced_node_original_property(p_name, vorig) || usage) {
Variant v = obj->get(p_name);
-
- bool changed = _is_property_different(v,vorig,usage);
+ bool changed = _is_property_different(v, vorig, usage);
//if ((found!=-1 && !is_disabled)!=changed) {
- if (changed) {
+ if (changed) {
- has_reload=true;
- } else {
-
- }
+ has_reload = true;
+ } else {
+ }
//}
-
}
-
}
- if (obj->call("property_can_revert",p_name).operator bool()) {
+ if (obj->call("property_can_revert", p_name).operator bool()) {
- has_reload=true;
+ has_reload = true;
}
-
if (!has_reload && !obj->get_script().is_null()) {
Ref<Script> scr = obj->get_script();
Variant orig_value;
- if (scr->get_property_default_value(p_name,orig_value)) {
- if (orig_value!=obj->get(p_name)) {
- has_reload=true;
+ if (scr->get_property_default_value(p_name, orig_value)) {
+ if (orig_value != obj->get(p_name)) {
+ has_reload = true;
}
}
}
//print_line("found: "+itos(found)+" has reload: "+itos(has_reload)+" is_disabled "+itos(is_disabled));
- if (found!=-1 && !has_reload) {
+ if (found != -1 && !has_reload) {
if (!is_disabled) {
- item->erase_button(1,found);
- if (item->get_cell_mode(1)==TreeItem::CELL_MODE_RANGE && item->get_text(1)==String()) {
- item->add_button(1,get_icon("ReloadEmpty","EditorIcons"),3,true);
+ item->erase_button(1, found);
+ if (item->get_cell_mode(1) == TreeItem::CELL_MODE_RANGE && item->get_text(1) == String()) {
+ item->add_button(1, get_icon("ReloadEmpty", "EditorIcons"), 3, true);
}
}
- } else if (found==-1 && has_reload) {
- item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
- } else if (found!=-1 && has_reload && is_disabled) {
- item->erase_button(1,found);
- item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
+ } else if (found == -1 && has_reload) {
+ item->add_button(1, get_icon("ReloadSmall", "EditorIcons"), 3);
+ } else if (found != -1 && has_reload && is_disabled) {
+ item->erase_button(1, found);
+ item->add_button(1, get_icon("ReloadSmall", "EditorIcons"), 3);
}
}
-
-
-bool PropertyEditor::_is_drop_valid(const Dictionary& p_drag_data, const Dictionary& p_item_data) const {
+bool PropertyEditor::_is_drop_valid(const Dictionary &p_drag_data, const Dictionary &p_item_data) const {
Dictionary d = p_item_data;
if (d.has("type")) {
int type = d["type"];
- if (type==Variant::OBJECT && d.has("hint") && d.has("hint_text") && int(d["hint"])==PROPERTY_HINT_RESOURCE_TYPE) {
+ if (type == Variant::OBJECT && d.has("hint") && d.has("hint_text") && int(d["hint"]) == PROPERTY_HINT_RESOURCE_TYPE) {
-
- String allowed_type=d["hint_text"];
+ String allowed_type = d["hint_text"];
Dictionary drag_data = p_drag_data;
- if (drag_data.has("type") && String(drag_data["type"])=="resource") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
Ref<Resource> res = drag_data["resource"];
- for(int i=0;i<allowed_type.get_slice_count(",");i++) {
- String at = allowed_type.get_slice(",",i).strip_edges();
- if (res.is_valid() && ClassDB::is_parent_class(res->get_class(),at)) {
+ for (int i = 0; i < allowed_type.get_slice_count(","); i++) {
+ String at = allowed_type.get_slice(",", i).strip_edges();
+ if (res.is_valid() && ClassDB::is_parent_class(res->get_class(), at)) {
return true;
}
}
-
}
- if (drag_data.has("type") && String(drag_data["type"])=="files") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "files") {
Vector<String> files = drag_data["files"];
- if (files.size()==1) {
+ if (files.size() == 1) {
String file = files[0];
String ftype = EditorFileSystem::get_singleton()->get_file_type(file);
- if (ftype!="") {
+ if (ftype != "") {
- for(int i=0;i<allowed_type.get_slice_count(",");i++) {
- String at = allowed_type.get_slice(",",i).strip_edges();
- if (ClassDB::is_parent_class(ftype,at)) {
+ for (int i = 0; i < allowed_type.get_slice_count(","); i++) {
+ String at = allowed_type.get_slice(",", i).strip_edges();
+ if (ClassDB::is_parent_class(ftype, at)) {
return true;
}
}
@@ -2678,14 +2550,12 @@ bool PropertyEditor::_is_drop_valid(const Dictionary& p_drag_data, const Diction
}
}
-
return false;
-
}
-void PropertyEditor::_mark_drop_fields(TreeItem* p_at) {
+void PropertyEditor::_mark_drop_fields(TreeItem *p_at) {
- if (_is_drop_valid(get_viewport()->gui_get_drag_data(),p_at->get_metadata(0)))
- p_at->set_custom_bg_color(1,Color(0.7,0.5,0.2),true);
+ if (_is_drop_valid(get_viewport()->gui_get_drag_data(), p_at->get_metadata(0)))
+ p_at->set_custom_bg_color(1, Color(0.7, 0.5, 0.2), true);
if (p_at->get_children()) {
_mark_drop_fields(p_at->get_children());
@@ -2696,7 +2566,7 @@ void PropertyEditor::_mark_drop_fields(TreeItem* p_at) {
}
}
-Variant PropertyEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant PropertyEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
TreeItem *item = tree->get_item_at_pos(p_point);
if (!item)
@@ -2707,60 +2577,57 @@ Variant PropertyEditor::get_drag_data_fw(const Point2& p_point,Control* p_from)
return Variant();
int col = tree->get_column_at_pos(p_point);
- if (col==0) {
+ if (col == 0) {
Dictionary dp;
- dp["type"]="obj_property";
- dp["object"]=obj;
- dp["property"]=d["name"];
- dp["value"]=obj->get(d["name"]);
+ dp["type"] = "obj_property";
+ dp["object"] = obj;
+ dp["property"] = d["name"];
+ dp["value"] = obj->get(d["name"]);
- Label *label =memnew( Label );
+ Label *label = memnew(Label);
label->set_text(d["name"]);
set_drag_preview(label);
return dp;
}
-
-
Variant val = obj->get(d["name"]);
- if (val.get_type()==Variant::OBJECT) {
+ if (val.get_type() == Variant::OBJECT) {
RES res = val;
if (res.is_valid()) {
custom_editor->hide_menu();
- return EditorNode::get_singleton()->drag_resource(res,p_from);
+ return EditorNode::get_singleton()->drag_resource(res, p_from);
}
}
return Variant();
}
-bool PropertyEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
+bool PropertyEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
TreeItem *item = tree->get_item_at_pos(p_point);
if (!item)
return false;
int col = tree->get_column_at_pos(p_point);
- if (col!=1)
+ if (col != 1)
return false;
- return _is_drop_valid(p_data,item->get_metadata(0));
-
+ return _is_drop_valid(p_data, item->get_metadata(0));
}
-void PropertyEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
+void PropertyEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
TreeItem *item = tree->get_item_at_pos(p_point);
if (!item)
return;
int col = tree->get_column_at_pos(p_point);
- if (col!=1)
+ if (col != 1)
return;
- if (!_is_drop_valid(p_data,item->get_metadata(0)))
+ if (!_is_drop_valid(p_data, item->get_metadata(0)))
return;
Dictionary d = item->get_metadata(0);
@@ -2768,44 +2635,42 @@ void PropertyEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Co
if (!d.has("name"))
return;
- String name=d["name"];
+ String name = d["name"];
Dictionary drag_data = p_data;
- if (drag_data.has("type") && String(drag_data["type"])=="resource") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "resource") {
Ref<Resource> res = drag_data["resource"];
if (res.is_valid()) {
- _edit_set(name,res);
+ _edit_set(name, res);
return;
}
}
- if (drag_data.has("type") && String(drag_data["type"])=="files") {
+ if (drag_data.has("type") && String(drag_data["type"]) == "files") {
Vector<String> files = drag_data["files"];
- if (files.size()==1) {
+ if (files.size() == 1) {
String file = files[0];
RES res = ResourceLoader::load(file);
if (res.is_valid()) {
- _edit_set(name,res);
+ _edit_set(name, res);
return;
}
}
}
}
-
-void PropertyEditor::_clear_drop_fields(TreeItem* p_at) {
+void PropertyEditor::_clear_drop_fields(TreeItem *p_at) {
Dictionary d = p_at->get_metadata(0);
if (d.has("type")) {
int type = d["type"];
- if (type==Variant::OBJECT) {
+ if (type == Variant::OBJECT) {
p_at->clear_custom_bg_color(1);
}
-
}
if (p_at->get_children()) {
@@ -2819,77 +2684,73 @@ void PropertyEditor::_clear_drop_fields(TreeItem* p_at) {
void PropertyEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- get_tree()->connect("node_removed",this,"_node_removed");
+ get_tree()->connect("node_removed", this, "_node_removed");
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
- get_tree()->disconnect("node_removed",this,"_node_removed");
+ get_tree()->disconnect("node_removed", this, "_node_removed");
edit(NULL);
}
-
- if (p_what==NOTIFICATION_DRAG_BEGIN) {
+ if (p_what == NOTIFICATION_DRAG_BEGIN) {
if (is_visible_in_tree() && tree->get_root()) {
_mark_drop_fields(tree->get_root());
}
}
- if (p_what==NOTIFICATION_DRAG_END) {
+ if (p_what == NOTIFICATION_DRAG_END) {
if (is_visible_in_tree() && tree->get_root()) {
_clear_drop_fields(tree->get_root());
}
-
}
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
-
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
- if (refresh_countdown>0) {
- refresh_countdown-=get_fixed_process_delta_time();
- if (refresh_countdown<=0) {
+ if (refresh_countdown > 0) {
+ refresh_countdown -= get_fixed_process_delta_time();
+ if (refresh_countdown <= 0) {
TreeItem *root = tree->get_root();
_refresh_item(root);
}
}
- changing=true;
+ changing = true;
if (update_tree_pending) {
update_tree();
- update_tree_pending=false;
+ update_tree_pending = false;
} else {
- const String *k=NULL;
- while ((k=pending.next(k))) {
+ const String *k = NULL;
+ while ((k = pending.next(k))) {
- TreeItem * item = find_item(tree->get_root(),*k);
+ TreeItem *item = find_item(tree->get_root(), *k);
if (!item)
continue;
- _check_reload_status(*k,item);
+ _check_reload_status(*k, item);
- Dictionary d=item->get_metadata(0);
- set_item_text(item,d["type"],d["name"],d["hint"],d["hint_text"]);
+ Dictionary d = item->get_metadata(0);
+ set_item_text(item, d["type"], d["name"], d["hint"], d["hint_text"]);
}
}
pending.clear();
- changing=false;
-
+ changing = false;
}
}
-TreeItem *PropertyEditor::get_parent_node(String p_path,HashMap<String,TreeItem*>& item_paths,TreeItem *root) {
+TreeItem *PropertyEditor::get_parent_node(String p_path, HashMap<String, TreeItem *> &item_paths, TreeItem *root) {
- TreeItem *item=NULL;
+ TreeItem *item = NULL;
- if (p_path=="") {
+ if (p_path == "") {
item = root;
} else if (item_paths.has(p_path)) {
@@ -2898,38 +2759,36 @@ TreeItem *PropertyEditor::get_parent_node(String p_path,HashMap<String,TreeItem*
} else {
//printf("path %s parent path %s - item name %s\n",p_path.ascii().get_data(),p_path.left( p_path.find_last("/") ).ascii().get_data(),p_path.right( p_path.find_last("/") ).ascii().get_data() );
- TreeItem *parent = get_parent_node( p_path.left( p_path.find_last("/") ),item_paths,root );
- item = tree->create_item( parent );
+ TreeItem *parent = get_parent_node(p_path.left(p_path.find_last("/")), item_paths, root);
+ item = tree->create_item(parent);
- String name = (p_path.find("/")!=-1)?p_path.right( p_path.find_last("/")+1 ):p_path;
+ String name = (p_path.find("/") != -1) ? p_path.right(p_path.find_last("/") + 1) : p_path;
if (capitalize_paths)
- item->set_text(0, name.capitalize() );
+ item->set_text(0, name.capitalize());
else
- item->set_text(0, name );
+ item->set_text(0, name);
item->set_tooltip(0, p_path);
- if (item->get_parent()!=root) {
- item->set_icon( 0, get_icon("Folder","EditorIcons"));
+ if (item->get_parent() != root) {
+ item->set_icon(0, get_icon("Folder", "EditorIcons"));
}
- item->set_editable(0,false);
- item->set_selectable(0,subsection_selectable);
- item->set_editable(1,false);
- item->set_selectable(1,subsection_selectable);
+ item->set_editable(0, false);
+ item->set_selectable(0, subsection_selectable);
+ item->set_editable(1, false);
+ item->set_selectable(1, subsection_selectable);
- if (item->get_parent()==root) {
+ if (item->get_parent() == root) {
- item->set_custom_bg_color(0,get_color("prop_subsection","Editor"));
- item->set_custom_bg_color(1,get_color("prop_subsection","Editor"));
+ item->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
+ item->set_custom_bg_color(1, get_color("prop_subsection", "Editor"));
}
- item_paths[p_path]=item;
+ item_paths[p_path] = item;
}
return item;
-
}
-
void PropertyEditor::_refresh_item(TreeItem *p_item) {
if (!p_item)
@@ -2937,10 +2796,9 @@ void PropertyEditor::_refresh_item(TreeItem *p_item) {
String name = p_item->get_metadata(1);
- if (name!=String()) {
+ if (name != String()) {
-
- _check_reload_status(name,p_item);
+ _check_reload_status(name, p_item);
#if 0
bool has_reload=false;
@@ -2999,38 +2857,35 @@ void PropertyEditor::_refresh_item(TreeItem *p_item) {
p_item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
}
#endif
- Dictionary d=p_item->get_metadata(0);
- set_item_text(p_item,d["type"],d["name"],d["hint"],d["hint_text"]);
+ Dictionary d = p_item->get_metadata(0);
+ set_item_text(p_item, d["type"], d["name"], d["hint"], d["hint_text"]);
}
- TreeItem *c=p_item->get_children();
+ TreeItem *c = p_item->get_children();
while (c) {
_refresh_item(c);
- c=c->get_next();
+ c = c->get_next();
}
-
}
void PropertyEditor::refresh() {
- if (refresh_countdown>0)
+ if (refresh_countdown > 0)
return;
- refresh_countdown=EditorSettings::get_singleton()->get("docks/property_editor/auto_refresh_interval");
-
+ refresh_countdown = EditorSettings::get_singleton()->get("docks/property_editor/auto_refresh_interval");
}
void PropertyEditor::update_tree() {
-
tree->clear();
if (!obj)
return;
- HashMap<String,TreeItem*> item_path;
+ HashMap<String, TreeItem *> item_path;
TreeItem *root = tree->create_item(NULL);
tree->set_hide_root(true);
@@ -3075,127 +2930,123 @@ void PropertyEditor::update_tree() {
}
*/
List<PropertyInfo> plist;
- obj->get_property_list(&plist,true);
+ obj->get_property_list(&plist, true);
- bool draw_red=false;
+ bool draw_red = false;
{
Node *nod = obj->cast_to<Node>();
Node *es = EditorNode::get_singleton()->get_edited_scene();
- if (nod && es!=nod && nod->get_owner()!=es) {
- draw_red=true;
+ if (nod && es != nod && nod->get_owner() != es) {
+ draw_red = true;
}
}
+ Color sscolor = get_color("prop_subsection", "Editor");
- Color sscolor=get_color("prop_subsection","Editor");
-
- TreeItem * current_category=NULL;
+ TreeItem *current_category = NULL;
String filter = search_box ? search_box->get_text() : "";
String group;
String group_base;
- for (List<PropertyInfo>::Element *I=plist.front() ; I ; I=I->next()) {
+ for (List<PropertyInfo>::Element *I = plist.front(); I; I = I->next()) {
- PropertyInfo& p = I->get();
+ PropertyInfo &p = I->get();
//make sure the property can be edited
- if (p.usage&PROPERTY_USAGE_GROUP) {
+ if (p.usage & PROPERTY_USAGE_GROUP) {
- group=p.name;
- group_base=p.hint_string;
+ group = p.name;
+ group_base = p.hint_string;
continue;
- } else if (p.usage&PROPERTY_USAGE_CATEGORY) {
+ } else if (p.usage & PROPERTY_USAGE_CATEGORY) {
- group="";
- group_base="";
+ group = "";
+ group_base = "";
if (!show_categories)
continue;
- List<PropertyInfo>::Element *N=I->next();
- bool valid=true;
+ List<PropertyInfo>::Element *N = I->next();
+ bool valid = true;
//if no properties in category, skip
- while(N) {
- if (N->get().usage&PROPERTY_USAGE_EDITOR)
+ while (N) {
+ if (N->get().usage & PROPERTY_USAGE_EDITOR)
break;
- if (N->get().usage&PROPERTY_USAGE_CATEGORY) {
- valid=false;
+ if (N->get().usage & PROPERTY_USAGE_CATEGORY) {
+ valid = false;
break;
}
- N=N->next();
+ N = N->next();
}
if (!valid)
continue; //empty, ignore
- TreeItem * sep = tree->create_item(root);
- current_category=sep;
- String type=p.name;
+ TreeItem *sep = tree->create_item(root);
+ current_category = sep;
+ String type = p.name;
/*if (has_icon(type,"EditorIcons"))
sep->set_icon(0,get_icon(type,"EditorIcons") );
else
sep->set_icon(0,get_icon("Object","EditorIcons") );
print_line("CATEGORY: "+type);
*/
- sep->set_text(0,type);
- sep->set_selectable(0,false);
- sep->set_selectable(1,false);
- sep->set_custom_bg_color(0,get_color("prop_category","Editor"));
- sep->set_custom_bg_color(1,get_color("prop_category","Editor"));
+ sep->set_text(0, type);
+ sep->set_selectable(0, false);
+ sep->set_selectable(1, false);
+ sep->set_custom_bg_color(0, get_color("prop_category", "Editor"));
+ sep->set_custom_bg_color(1, get_color("prop_category", "Editor"));
if (use_doc_hints) {
- StringName type=p.name;
+ StringName type = p.name;
if (!class_descr_cache.has(type)) {
String descr;
- DocData *dd=EditorHelp::get_doc_data();
- Map<String,DocData::ClassDoc>::Element *E=dd->class_list.find(type);
+ DocData *dd = EditorHelp::get_doc_data();
+ Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(type);
if (E) {
- descr=E->get().brief_description;
+ descr = E->get().brief_description;
}
- class_descr_cache[type]=descr.word_wrap(80);
-
+ class_descr_cache[type] = descr.word_wrap(80);
}
- sep->set_tooltip(0,TTR("Class:")+" "+p.name+":\n\n"+class_descr_cache[type]);
+ sep->set_tooltip(0, TTR("Class:") + " " + p.name + ":\n\n" + class_descr_cache[type]);
}
//sep->set_custom_color(0,Color(1,1,1));
-
continue;
- } else if ( ! (p.usage&PROPERTY_USAGE_EDITOR ) )
+ } else if (!(p.usage & PROPERTY_USAGE_EDITOR))
continue;
-
- if (hide_script && p.name=="script")
+ if (hide_script && p.name == "script")
continue;
- String basename=p.name;
- if (group!="") {
- if (group_base!="") {
+ String basename = p.name;
+ if (group != "") {
+ if (group_base != "") {
if (basename.begins_with(group_base)) {
- basename=basename.replace_first(group_base,"");
+ basename = basename.replace_first(group_base, "");
} else {
- group=""; //no longer using group base, clear
+ group = ""; //no longer using group base, clear
}
}
}
- if (group!="") {
- basename=group+"/"+basename;
+ if (group != "") {
+ basename = group + "/" + basename;
}
- String name = (basename.find("/")!=-1)?basename.right( basename.find_last("/")+1 ):basename;
+ String name = (basename.find("/") != -1) ? basename.right(basename.find_last("/") + 1) : basename;
if (capitalize_paths)
name = name.camelcase_to_underscore().capitalize();
- String path=basename.left( basename.find_last("/") ) ;
+ String path = basename.left(basename.find_last("/"));
- if (use_filter && filter!="") {
+ if (use_filter && filter != "") {
String cat = path;
@@ -3207,41 +3058,41 @@ void PropertyEditor::update_tree() {
}
//printf("property %s\n",basename.ascii().get_data());
- TreeItem * parent = get_parent_node(path,item_path,current_category?current_category:root );
+ TreeItem *parent = get_parent_node(path, item_path, current_category ? current_category : root);
/*
if (parent->get_parent()==root)
parent=root;
*/
int level = 0;
- if (parent!=root) {
+ if (parent != root) {
level++;
- TreeItem *parent_lev=parent;
- while(parent_lev->get_parent()!=root) {
- parent_lev=parent_lev->get_parent();
+ TreeItem *parent_lev = parent;
+ while (parent_lev->get_parent() != root) {
+ parent_lev = parent_lev->get_parent();
level++;
}
}
- if (level>4)
- level=4;
+ if (level > 4)
+ level = 4;
Color col = sscolor;
- col.a=(level/4.0)*0.7;
+ col.a = (level / 4.0) * 0.7;
- TreeItem * item = tree->create_item( parent );
+ TreeItem *item = tree->create_item(parent);
- if (level>0) {
- item->set_custom_bg_color(0,col);
+ if (level > 0) {
+ item->set_custom_bg_color(0, col);
//item->set_custom_bg_color(1,col);
}
- item->set_editable(0,false);
- item->set_selectable(0,false);
+ item->set_editable(0, false);
+ item->set_selectable(0, false);
- if (p.usage&PROPERTY_USAGE_CHECKABLE) {
+ if (p.usage & PROPERTY_USAGE_CHECKABLE) {
- item->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
- item->set_selectable(0,true);
- item->set_editable(0,true);
- item->set_checked(0,p.usage&PROPERTY_USAGE_CHECKED);
+ item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
+ item->set_selectable(0, true);
+ item->set_editable(0, true);
+ item->set_checked(0, p.usage & PROPERTY_USAGE_CHECKED);
}
item->set_text(0, name);
@@ -3250,182 +3101,175 @@ void PropertyEditor::update_tree() {
if (use_doc_hints) {
StringName setter;
StringName type;
- if (ClassDB::get_setter_and_type_for_property(obj->get_class_name(),p.name,type,setter)) {
+ if (ClassDB::get_setter_and_type_for_property(obj->get_class_name(), p.name, type, setter)) {
String descr;
- bool found=false;
- Map<StringName,Map<StringName,String> >::Element *E=descr_cache.find(type);
+ bool found = false;
+ Map<StringName, Map<StringName, String> >::Element *E = descr_cache.find(type);
if (E) {
- Map<StringName,String>::Element *F=E->get().find(setter);
+ Map<StringName, String>::Element *F = E->get().find(setter);
if (F) {
- found=true;
- descr=F->get();
+ found = true;
+ descr = F->get();
}
}
if (!found) {
- DocData *dd=EditorHelp::get_doc_data();
- Map<String,DocData::ClassDoc>::Element *E=dd->class_list.find(type);
+ DocData *dd = EditorHelp::get_doc_data();
+ Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(type);
if (E) {
- for(int i=0;i<E->get().methods.size();i++) {
- if (E->get().methods[i].name==setter.operator String()) {
- descr=E->get().methods[i].description.strip_edges().word_wrap(80);
+ for (int i = 0; i < E->get().methods.size(); i++) {
+ if (E->get().methods[i].name == setter.operator String()) {
+ descr = E->get().methods[i].description.strip_edges().word_wrap(80);
}
}
}
- descr_cache[type][setter]=descr;
+ descr_cache[type][setter] = descr;
}
- item->set_tooltip(0, TTR("Property:")+" "+p.name+"\n\n"+descr);
+ item->set_tooltip(0, TTR("Property:") + " " + p.name + "\n\n" + descr);
}
}
//EditorHelp::get_doc_data();
Dictionary d;
- d["name"]=p.name;
- d["type"]=(int)p.type;
- d["hint"]=(int)p.hint;
- d["hint_text"]=p.hint_string;
- d["usage"]=(int)p.usage;
+ d["name"] = p.name;
+ d["type"] = (int)p.type;
+ d["hint"] = (int)p.hint;
+ d["hint_text"] = p.hint_string;
+ d["usage"] = (int)p.usage;
- item->set_metadata( 0, d );
- item->set_metadata( 1, p.name );
+ item->set_metadata(0, d);
+ item->set_metadata(1, p.name);
if (draw_red)
- item->set_custom_color(0,Color(0.8,0.4,0.20));
-
+ item->set_custom_color(0, Color(0.8, 0.4, 0.20));
- if (p.name==selected_property) {
+ if (p.name == selected_property) {
item->select(1);
}
-
//printf("property %s type %i\n",p.name.ascii().get_data(),p.type);
- switch( p.type ) {
+ switch (p.type) {
case Variant::BOOL: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CHECK );
- item->set_text(1,TTR("On"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
+ item->set_text(1, TTR("On"));
item->set_tooltip(1, obj->get(p.name) ? "True" : "False");
- item->set_checked( 1, obj->get( p.name ) );
+ item->set_checked(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0, get_icon("Bool","EditorIcons") );
- item->set_editable(1,!read_only);
+ item->set_icon(0, get_icon("Bool", "EditorIcons"));
+ item->set_editable(1, !read_only);
} break;
case Variant::REAL:
case Variant::INT: {
- if (p.hint==PROPERTY_HINT_EXP_EASING) {
+ if (p.hint == PROPERTY_HINT_EXP_EASING) {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_text(1, String::num(obj->get( p.name ),2) );
- item->set_editable(1,!read_only);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_text(1, String::num(obj->get(p.name), 2));
+ item->set_editable(1, !read_only);
if (show_type_icons)
- item->set_icon( 0, get_icon("Curve","EditorIcons"));
+ item->set_icon(0, get_icon("Curve", "EditorIcons"));
break;
-
}
- if (p.hint==PROPERTY_HINT_LAYERS_2D_PHYSICS || p.hint==PROPERTY_HINT_LAYERS_2D_RENDER || p.hint==PROPERTY_HINT_LAYERS_3D_PHYSICS || p.hint==PROPERTY_HINT_LAYERS_3D_RENDER) {
+ if (p.hint == PROPERTY_HINT_LAYERS_2D_PHYSICS || p.hint == PROPERTY_HINT_LAYERS_2D_RENDER || p.hint == PROPERTY_HINT_LAYERS_3D_PHYSICS || p.hint == PROPERTY_HINT_LAYERS_3D_RENDER) {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable(1,!read_only);
- item->set_custom_draw(1,this,"_draw_flags");
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
+ item->set_custom_draw(1, this, "_draw_flags");
break;
}
- if (p.hint==PROPERTY_HINT_FLAGS) {
-
+ if (p.hint == PROPERTY_HINT_FLAGS) {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable(1,!read_only);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
//item->set_icon( 0, get_icon("Curve","EditorIcons"));
Vector<String> values = p.hint_string.split(",");
String flags;
int val = obj->get(p.name);
- for(int i=0;i<values.size();i++) {
+ for (int i = 0; i < values.size(); i++) {
String v = values[i];
- if (v=="")
+ if (v == "")
continue;
- if (!(val&(1<<i)))
+ if (!(val & (1 << i)))
continue;
- if (flags!="")
- flags+=", ";
- flags+=v;
+ if (flags != "")
+ flags += ", ";
+ flags += v;
}
- item->set_text(1, flags );
+ item->set_text(1, flags);
break;
-
}
- if (p.hint==PROPERTY_HINT_ENUM)
- item->set_cell_mode( 1, TreeItem::CELL_MODE_RANGE );
+ if (p.hint == PROPERTY_HINT_ENUM)
+ item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
else
- item->set_cell_mode( 1, TreeItem::CELL_MODE_RANGE_EXPRESSION );
-
+ item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE_EXPRESSION);
- if (p.hint==PROPERTY_HINT_SPRITE_FRAME || p.hint==PROPERTY_HINT_RANGE || p.hint==PROPERTY_HINT_EXP_RANGE) {
+ if (p.hint == PROPERTY_HINT_SPRITE_FRAME || p.hint == PROPERTY_HINT_RANGE || p.hint == PROPERTY_HINT_EXP_RANGE) {
int c = p.hint_string.get_slice_count(",");
- float min=0,max=100,step=1;
- if (c>=1) {
+ float min = 0, max = 100, step = 1;
+ if (c >= 1) {
- min=p.hint_string.get_slice(",",0).to_double();
+ min = p.hint_string.get_slice(",", 0).to_double();
}
- if (c>=2) {
+ if (c >= 2) {
- max=p.hint_string.get_slice(",",1).to_double();
+ max = p.hint_string.get_slice(",", 1).to_double();
}
- if (p.hint!=PROPERTY_HINT_SPRITE_FRAME && c>=3) {
+ if (p.hint != PROPERTY_HINT_SPRITE_FRAME && c >= 3) {
- step= p.hint_string.get_slice(",",2).to_double();
+ step = p.hint_string.get_slice(",", 2).to_double();
}
-
- item->set_range_config(1,min,max,step,p.hint==PROPERTY_HINT_EXP_RANGE);
- } else if (p.hint==PROPERTY_HINT_ENUM) {
+ item->set_range_config(1, min, max, step, p.hint == PROPERTY_HINT_EXP_RANGE);
+ } else if (p.hint == PROPERTY_HINT_ENUM) {
//int c = p.hint_string.get_slice_count(",");
- item->set_text(1,p.hint_string);
+ item->set_text(1, p.hint_string);
if (show_type_icons)
- item->set_icon( 0,get_icon("Enum","EditorIcons") );
- item->set_range(1, obj->get( p.name ) );
- item->set_editable(1,!read_only);
+ item->set_icon(0, get_icon("Enum", "EditorIcons"));
+ item->set_range(1, obj->get(p.name));
+ item->set_editable(1, !read_only);
break;
- } else if (p.hint==PROPERTY_HINT_OBJECT_ID) {
+ } else if (p.hint == PROPERTY_HINT_OBJECT_ID) {
//int c = p.hint_string.get_slice_count(",");
- item->set_cell_mode(1,TreeItem::CELL_MODE_CUSTOM);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
- String type=p.hint_string;
- if (type=="")
- type="Object";
+ String type = p.hint_string;
+ if (type == "")
+ type = "Object";
- ObjectID id = obj->get( p.name );
- if (id!=0) {
- item->set_text(1,type+" ID: "+itos(id));
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ ObjectID id = obj->get(p.name);
+ if (id != 0) {
+ item->set_text(1, type + " ID: " + itos(id));
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
} else {
- item->set_text(1,"[Empty]");
+ item->set_text(1, "[Empty]");
}
- if (has_icon(p.hint_string,"EditorIcons")) {
- type=p.hint_string;
+ if (has_icon(p.hint_string, "EditorIcons")) {
+ type = p.hint_string;
} else {
- type="Object";
+ type = "Object";
}
- item->set_icon(0,get_icon(type,"EditorIcons"));
+ item->set_icon(0, get_icon(type, "EditorIcons"));
break;
@@ -3439,20 +3283,18 @@ void PropertyEditor::update_tree() {
}
};
- if (p.type==Variant::REAL) {
+ if (p.type == Variant::REAL) {
if (show_type_icons)
- item->set_icon( 0, get_icon("Real","EditorIcons"));
- item->set_range(1, obj->get( p.name ) );
+ item->set_icon(0, get_icon("Real", "EditorIcons"));
+ item->set_range(1, obj->get(p.name));
} else {
if (show_type_icons)
- item->set_icon( 0,get_icon("Integer","EditorIcons") );
- item->set_range(1, obj->get( p.name ) );
+ item->set_icon(0, get_icon("Integer", "EditorIcons"));
+ item->set_range(1, obj->get(p.name));
}
-
- item->set_editable(1,!read_only);
-
+ item->set_editable(1, !read_only);
} break;
case Variant::STRING: {
@@ -3464,32 +3306,31 @@ void PropertyEditor::update_tree() {
case PROPERTY_HINT_GLOBAL_DIR:
case PROPERTY_HINT_GLOBAL_FILE: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_STRING );
- item->set_editable(1,!read_only);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_STRING);
+ item->set_editable(1, !read_only);
if (show_type_icons)
- item->set_icon( 0, get_icon("File","EditorIcons") );
- item->set_text(1,obj->get(p.name));
- item->add_button(1,get_icon("Folder","EditorIcons"));
+ item->set_icon(0, get_icon("File", "EditorIcons"));
+ item->set_text(1, obj->get(p.name));
+ item->add_button(1, get_icon("Folder", "EditorIcons"));
} break;
case PROPERTY_HINT_ENUM: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_RANGE );
+ item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
Vector<String> strings = p.hint_string.split(",");
String current = obj->get(p.name);
- int idx=0;
- for(int x=0;x<strings.size();x++) {
- if (strings[x]==current) {
- idx=x;
+ int idx = 0;
+ for (int x = 0; x < strings.size(); x++) {
+ if (strings[x] == current) {
+ idx = x;
break;
}
}
item->set_text(1, p.hint_string);
- item->set_range(1,idx);
- item->set_editable( 1, !read_only );
+ item->set_range(1, idx);
+ item->set_editable(1, !read_only);
if (show_type_icons)
- item->set_icon( 0,get_icon("Enum","EditorIcons") );
-
+ item->set_icon(0, get_icon("Enum", "EditorIcons"));
} break;
case PROPERTY_HINT_METHOD_OF_VARIANT_TYPE: ///< a property of a type
@@ -3502,23 +3343,23 @@ void PropertyEditor::update_tree() {
case PROPERTY_HINT_PROPERTY_OF_SCRIPT: ///< a property of a script & base
case PROPERTY_HINT_TYPE_STRING: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM);
- item->set_editable(1,!read_only);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
if (show_type_icons)
- item->set_icon( 0, get_icon("String","EditorIcons") );
- item->set_text(1,obj->get(p.name));
+ item->set_icon(0, get_icon("String", "EditorIcons"));
+ item->set_text(1, obj->get(p.name));
} break;
default: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_STRING );
- item->set_editable(1,!read_only);
+ item->set_cell_mode(1, TreeItem::CELL_MODE_STRING);
+ item->set_editable(1, !read_only);
if (show_type_icons)
- item->set_icon( 0, get_icon("String","EditorIcons") );
- item->set_text(1,obj->get(p.name));
- if (p.hint==PROPERTY_HINT_MULTILINE_TEXT)
- item->add_button(1,get_icon("MultiLine","EditorIcons") );
+ item->set_icon(0, get_icon("String", "EditorIcons"));
+ item->set_text(1, obj->get(p.name));
+ if (p.hint == PROPERTY_HINT_MULTILINE_TEXT)
+ item->add_button(1, get_icon("MultiLine", "EditorIcons"));
} break;
}
@@ -3526,304 +3367,293 @@ void PropertyEditor::update_tree() {
} break;
case Variant::ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
-
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
String type_name = "Array";
String type_name_suffix = "";
-
+
String hint = p.hint_string;
- while(hint.begins_with(itos(Variant::ARRAY)+":")) {
+ while (hint.begins_with(itos(Variant::ARRAY) + ":")) {
type_name += "<Array";
type_name_suffix += ">";
- hint = hint.substr(2, hint.size()-2);
+ hint = hint.substr(2, hint.size() - 2);
}
- if(hint.find(":") >= 0) {
- hint = hint.substr(0,hint.find(":"));
- if(hint.find("/") >= 0) {
- hint = hint.substr(0,hint.find("/"));
+ if (hint.find(":") >= 0) {
+ hint = hint.substr(0, hint.find(":"));
+ if (hint.find("/") >= 0) {
+ hint = hint.substr(0, hint.find("/"));
}
type_name += "<" + Variant::get_type_name(Variant::Type(hint.to_int()));
type_name_suffix += ">";
}
type_name += type_name_suffix;
-
+
if (v.is_array())
- item->set_text(1,type_name+"["+itos(v.call("size"))+"]");
+ item->set_text(1, type_name + "[" + itos(v.call("size")) + "]");
else
- item->set_text(1,type_name+"[]");
-
- if (show_type_icons)
- item->set_icon( 0, get_icon("ArrayData","EditorIcons") );
+ item->set_text(1, type_name + "[]");
+ if (show_type_icons)
+ item->set_icon(0, get_icon("ArrayData", "EditorIcons"));
} break;
case Variant::POOL_INT_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"IntArray["+itos(v.call("size"))+"]");
+ item->set_text(1, "IntArray[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"IntArray[]");
+ item->set_text(1, "IntArray[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("ArrayInt","EditorIcons") );
-
+ item->set_icon(0, get_icon("ArrayInt", "EditorIcons"));
} break;
case Variant::POOL_REAL_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"FloatArray["+itos(v.call("size"))+"]");
+ item->set_text(1, "FloatArray[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"FloatArray[]");
+ item->set_text(1, "FloatArray[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("ArrayReal","EditorIcons") );
-
+ item->set_icon(0, get_icon("ArrayReal", "EditorIcons"));
} break;
case Variant::POOL_STRING_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"String["+itos(v.call("size"))+"]");
+ item->set_text(1, "String[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"String[]");
+ item->set_text(1, "String[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("ArrayString","EditorIcons") );
-
+ item->set_icon(0, get_icon("ArrayString", "EditorIcons"));
} break;
case Variant::POOL_BYTE_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"Byte["+itos(v.call("size"))+"]");
+ item->set_text(1, "Byte[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"Byte[]");
+ item->set_text(1, "Byte[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("ArrayData","EditorIcons") );
-
+ item->set_icon(0, get_icon("ArrayData", "EditorIcons"));
} break;
case Variant::POOL_VECTOR2_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"Vector2["+itos(v.call("size"))+"]");
+ item->set_text(1, "Vector2[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"Vector2[]");
+ item->set_text(1, "Vector2[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("Vector2","EditorIcons") );
-
+ item->set_icon(0, get_icon("Vector2", "EditorIcons"));
} break;
case Variant::POOL_VECTOR3_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"Vector3["+itos(v.call("size"))+"]");
+ item->set_text(1, "Vector3[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"Vector3[]");
+ item->set_text(1, "Vector3[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("Vector","EditorIcons") );
-
+ item->set_icon(0, get_icon("Vector", "EditorIcons"));
} break;
case Variant::POOL_COLOR_ARRAY: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
Variant v = obj->get(p.name);
if (v.is_array())
- item->set_text(1,"Color["+itos(v.call("size"))+"]");
+ item->set_text(1, "Color[" + itos(v.call("size")) + "]");
else
- item->set_text(1,"Color[]");
+ item->set_text(1, "Color[]");
if (show_type_icons)
- item->set_icon( 0, get_icon("Color","EditorIcons") );
-
+ item->set_icon(0, get_icon("Color", "EditorIcons"));
} break;
case Variant::VECTOR2: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Vector2","EditorIcons") );
+ item->set_icon(0, get_icon("Vector2", "EditorIcons"));
} break;
case Variant::RECT2: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Rect2","EditorIcons") );
+ item->set_icon(0, get_icon("Rect2", "EditorIcons"));
} break;
case Variant::VECTOR3: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Vector","EditorIcons") );
+ item->set_icon(0, get_icon("Vector", "EditorIcons"));
} break;
case Variant::TRANSFORM2D:
case Variant::BASIS: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
item->set_text(1, obj->get(p.name));
} break;
case Variant::TRANSFORM: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Matrix","EditorIcons") );
+ item->set_icon(0, get_icon("Matrix", "EditorIcons"));
} break;
case Variant::PLANE: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Plane","EditorIcons") );
+ item->set_icon(0, get_icon("Plane", "EditorIcons"));
} break;
case Variant::RECT3: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,"Rect3");
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, "Rect3");
if (show_type_icons)
- item->set_icon( 0,get_icon("Rect3","EditorIcons") );
+ item->set_icon(0, get_icon("Rect3", "EditorIcons"));
} break;
case Variant::QUAT: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, true );
- item->set_text(1,obj->get(p.name));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, true);
+ item->set_text(1, obj->get(p.name));
if (show_type_icons)
- item->set_icon( 0,get_icon("Quat","EditorIcons") );
+ item->set_icon(0, get_icon("Quat", "EditorIcons"));
} break;
case Variant::COLOR: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, !read_only );
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
//item->set_text(1,obj->get(p.name));
- item->set_custom_draw(1,this,"_draw_transparency");
+ item->set_custom_draw(1, this, "_draw_transparency");
if (show_type_icons)
- item->set_icon( 0,get_icon("Color","EditorIcons") );
+ item->set_icon(0, get_icon("Color", "EditorIcons"));
} break;
case Variant::IMAGE: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, !read_only );
- Image img = obj->get( p.name );
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
+ Image img = obj->get(p.name);
if (img.empty())
- item->set_text(1,"[Image (empty)]");
+ item->set_text(1, "[Image (empty)]");
else
- item->set_text(1,"[Image "+itos(img.get_width())+"x"+itos(img.get_height())+"-"+String(Image::get_format_name(img.get_format()))+"]");
+ item->set_text(1, "[Image " + itos(img.get_width()) + "x" + itos(img.get_height()) + "-" + String(Image::get_format_name(img.get_format())) + "]");
if (show_type_icons)
- item->set_icon( 0,get_icon("Image","EditorIcons") );
+ item->set_icon(0, get_icon("Image", "EditorIcons"));
} break;
case Variant::NODE_PATH: {
item->set_cell_mode(1, TreeItem::CELL_MODE_STRING);
- item->set_editable( 1, !read_only );
- item->set_text(1,obj->get(p.name));
+ item->set_editable(1, !read_only);
+ item->set_text(1, obj->get(p.name));
item->add_button(1, get_icon("CopyNodePath", "EditorIcons"));
} break;
case Variant::OBJECT: {
- item->set_cell_mode( 1, TreeItem::CELL_MODE_CUSTOM );
- item->set_editable( 1, !read_only );
- item->add_button(1,get_icon("EditResource","EditorIcons"));
+ item->set_cell_mode(1, TreeItem::CELL_MODE_CUSTOM);
+ item->set_editable(1, !read_only);
+ item->add_button(1, get_icon("EditResource", "EditorIcons"));
String type;
- if (p.hint==PROPERTY_HINT_RESOURCE_TYPE)
- type=p.hint_string;
+ if (p.hint == PROPERTY_HINT_RESOURCE_TYPE)
+ type = p.hint_string;
- if (obj->get( p.name ).get_type() == Variant::NIL || obj->get( p.name ).operator RefPtr().is_null()) {
- item->set_text(1,"<null>");
- item->set_icon(1,Ref<Texture>());
+ if (obj->get(p.name).get_type() == Variant::NIL || obj->get(p.name).operator RefPtr().is_null()) {
+ item->set_text(1, "<null>");
+ item->set_icon(1, Ref<Texture>());
} else {
- RES res = obj->get( p.name ).operator RefPtr();
+ RES res = obj->get(p.name).operator RefPtr();
if (res->is_class("Texture")) {
int tw = EditorSettings::get_singleton()->get("docks/property_editor/texture_preview_width");
- item->set_icon_max_width(1,tw);
- item->set_icon(1,res);
- item->set_text(1,"");
+ item->set_icon_max_width(1, tw);
+ item->set_icon(1, res);
+ item->set_text(1, "");
} else if (res->get_name() != "") {
item->set_text(1, res->get_name());
- } else if (res->get_path()!="" && !res->get_path().begins_with("local://")) {
+ } else if (res->get_path() != "" && !res->get_path().begins_with("local://")) {
item->set_text(1, res->get_path().get_file());
} else {
- item->set_text(1,"<"+res->get_class()+">");
+ item->set_text(1, "<" + res->get_class() + ">");
}
- if (has_icon(res->get_class(),"EditorIcons")) {
- type=res->get_class();
+ if (has_icon(res->get_class(), "EditorIcons")) {
+ type = res->get_class();
}
if (res.is_valid() && res->get_path().is_resource_file()) {
- item->set_tooltip(1,res->get_path());
+ item->set_tooltip(1, res->get_path());
} else if (res.is_valid()) {
- item->set_tooltip(1,res->get_name()+" ("+res->get_class()+")");
+ item->set_tooltip(1, res->get_name() + " (" + res->get_class() + ")");
}
if (!res->is_class("Texture")) {
//texture already previews via itself
- EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res,this,"_resource_preview_done",item->get_instance_ID());
+ EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_resource_preview_done", item->get_instance_ID());
}
-
}
-
- if (type!=String()) {
- if (type.find(",")!=-1)
- type=type.get_slice(",",0);
+ if (type != String()) {
+ if (type.find(",") != -1)
+ type = type.get_slice(",", 0);
//printf("prop %s , type %s\n",p.name.ascii().get_data(),p.hint_string.ascii().get_data());
- if (has_icon(type,"EditorIcons"))
- item->set_icon( 0, get_icon(type,"EditorIcons") );
+ if (has_icon(type, "EditorIcons"))
+ item->set_icon(0, get_icon(type, "EditorIcons"));
else
- item->set_icon( 0, get_icon("Object","EditorIcons") );
+ item->set_icon(0, get_icon("Object", "EditorIcons"));
}
//item->double_click_signal.connect( Method1<int>( Method2<int,String>( this, &Editoritem_obj_edited ), p.name ) );
@@ -3834,239 +3664,225 @@ void PropertyEditor::update_tree() {
if (keying) {
- if (p.hint==PROPERTY_HINT_SPRITE_FRAME) {
+ if (p.hint == PROPERTY_HINT_SPRITE_FRAME) {
- item->add_button(1,get_icon("KeyNext","EditorIcons"),5);
+ item->add_button(1, get_icon("KeyNext", "EditorIcons"), 5);
} else {
- item->add_button(1,get_icon("Key","EditorIcons"),2);
+ item->add_button(1, get_icon("Key", "EditorIcons"), 2);
}
}
- bool has_reload=false;
+ bool has_reload = false;
bool mbi = _might_be_in_instance();
if (mbi) {
Variant vorig;
- Dictionary d=item->get_metadata(0);
- int usage = d.has("usage")?int(int(d["usage"])&(PROPERTY_USAGE_STORE_IF_NONONE|PROPERTY_USAGE_STORE_IF_NONZERO)):0;
- if (_get_instanced_node_original_property(p.name,vorig) || usage) {
+ Dictionary d = item->get_metadata(0);
+ int usage = d.has("usage") ? int(int(d["usage"]) & (PROPERTY_USAGE_STORE_IF_NONONE | PROPERTY_USAGE_STORE_IF_NONZERO)) : 0;
+ if (_get_instanced_node_original_property(p.name, vorig) || usage) {
Variant v = obj->get(p.name);
-
- if (_is_property_different(v,vorig,usage)) {
+ if (_is_property_different(v, vorig, usage)) {
//print_line("FOR "+String(p.name)+" RELOAD WITH: "+String(v)+"("+Variant::get_type_name(v.get_type())+")=="+String(vorig)+"("+Variant::get_type_name(vorig.get_type())+")");
- item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
- has_reload=true;
+ item->add_button(1, get_icon("ReloadSmall", "EditorIcons"), 3);
+ has_reload = true;
}
}
-
}
- if (obj->call("property_can_revert",p.name).operator bool()) {
+ if (obj->call("property_can_revert", p.name).operator bool()) {
- item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
- has_reload=true;
+ item->add_button(1, get_icon("ReloadSmall", "EditorIcons"), 3);
+ has_reload = true;
}
if (!has_reload && !obj->get_script().is_null()) {
Ref<Script> scr = obj->get_script();
Variant orig_value;
- if (scr->get_property_default_value(p.name,orig_value)) {
- if (orig_value!=obj->get(p.name)) {
- item->add_button(1,get_icon("ReloadSmall","EditorIcons"),3);
- has_reload=true;
+ if (scr->get_property_default_value(p.name, orig_value)) {
+ if (orig_value != obj->get(p.name)) {
+ item->add_button(1, get_icon("ReloadSmall", "EditorIcons"), 3);
+ has_reload = true;
}
}
}
- if (mbi && !has_reload && item->get_cell_mode(1)==TreeItem::CELL_MODE_RANGE && item->get_text(1)==String()) {
- item->add_button(1,get_icon("ReloadEmpty","EditorIcons"),3,true);
+ if (mbi && !has_reload && item->get_cell_mode(1) == TreeItem::CELL_MODE_RANGE && item->get_text(1) == String()) {
+ item->add_button(1, get_icon("ReloadEmpty", "EditorIcons"), 3, true);
}
-
-
-
}
}
-void PropertyEditor::_draw_transparency(Object *t, const Rect2& p_rect) {
+void PropertyEditor::_draw_transparency(Object *t, const Rect2 &p_rect) {
- TreeItem *ti=t->cast_to<TreeItem>();
+ TreeItem *ti = t->cast_to<TreeItem>();
if (!ti)
- return;
+ return;
- Color color=obj->get(ti->get_metadata(1));
- Ref<Texture> arrow=tree->get_icon("select_arrow");
+ Color color = obj->get(ti->get_metadata(1));
+ Ref<Texture> arrow = tree->get_icon("select_arrow");
// make a little space between consecutive color fields
- Rect2 area=p_rect;
- area.pos.y+=1;
- area.size.height-=2;
- area.size.width-=arrow->get_size().width+5;
+ Rect2 area = p_rect;
+ area.pos.y += 1;
+ area.size.height -= 2;
+ area.size.width -= arrow->get_size().width + 5;
tree->draw_texture_rect(get_icon("Transparent", "EditorIcons"), area, true);
tree->draw_rect(area, color);
-
}
-
void PropertyEditor::_item_selected() {
-
TreeItem *item = tree->get_selected();
ERR_FAIL_COND(!item);
- selected_property=item->get_metadata(1);
-
+ selected_property = item->get_metadata(1);
}
-
-void PropertyEditor::_edit_set(const String& p_name, const Variant& p_value, bool p_refresh_all, const String& p_changed_field) {
+void PropertyEditor::_edit_set(const String &p_name, const Variant &p_value, bool p_refresh_all, const String &p_changed_field) {
if (autoclear) {
TreeItem *item = tree->get_selected();
- if (item && item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK) {
+ if (item && item->get_cell_mode(0) == TreeItem::CELL_MODE_CHECK) {
- item->set_checked(0,true);
+ item->set_checked(0, true);
}
}
- if (!undo_redo|| obj->cast_to<ArrayPropertyEdit>()) { //kind of hacky
+ if (!undo_redo || obj->cast_to<ArrayPropertyEdit>()) { //kind of hacky
- obj->set(p_name,p_value);
+ obj->set(p_name, p_value);
if (p_refresh_all)
- _changed_callbacks(obj,"");
+ _changed_callbacks(obj, "");
else
- _changed_callbacks(obj,p_name);
+ _changed_callbacks(obj, p_name);
- emit_signal(_prop_edited,p_name);
+ emit_signal(_prop_edited, p_name);
} else if (obj->cast_to<MultiNodeEdit>()) {
- obj->cast_to<MultiNodeEdit>()->set_property_field(p_name,p_value,p_changed_field);
- _changed_callbacks(obj,p_name);
- emit_signal(_prop_edited,p_name);
+ obj->cast_to<MultiNodeEdit>()->set_property_field(p_name, p_value, p_changed_field);
+ _changed_callbacks(obj, p_name);
+ emit_signal(_prop_edited, p_name);
} else {
- undo_redo->create_action(TTR("Set")+" "+p_name,UndoRedo::MERGE_ENDS);
- undo_redo->add_do_property(obj,p_name,p_value);
- undo_redo->add_undo_property(obj,p_name,obj->get(p_name));
+ undo_redo->create_action(TTR("Set") + " " + p_name, UndoRedo::MERGE_ENDS);
+ undo_redo->add_do_property(obj, p_name, p_value);
+ undo_redo->add_undo_property(obj, p_name, obj->get(p_name));
if (p_refresh_all) {
- undo_redo->add_do_method(this,"_changed_callback",obj,"");
- undo_redo->add_undo_method(this,"_changed_callback",obj,"");
+ undo_redo->add_do_method(this, "_changed_callback", obj, "");
+ undo_redo->add_undo_method(this, "_changed_callback", obj, "");
} else {
- undo_redo->add_do_method(this,"_changed_callback",obj,p_name);
- undo_redo->add_undo_method(this,"_changed_callback",obj,p_name);
+ undo_redo->add_do_method(this, "_changed_callback", obj, p_name);
+ undo_redo->add_undo_method(this, "_changed_callback", obj, p_name);
}
Resource *r = obj->cast_to<Resource>();
if (r) {
- if (!r->is_edited() && String(p_name)!="resource/edited") {
- undo_redo->add_do_method(r,"set_edited",true);
- undo_redo->add_undo_method(r,"set_edited",false);
+ if (!r->is_edited() && String(p_name) != "resource/edited") {
+ undo_redo->add_do_method(r, "set_edited", true);
+ undo_redo->add_undo_method(r, "set_edited", false);
}
- if (String(p_name)=="resource_local_to_scene") {
+ if (String(p_name) == "resource_local_to_scene") {
bool prev = obj->get(p_name);
bool next = p_value;
if (next) {
- undo_redo->add_do_method(this,"setup_local_to_scene");
+ undo_redo->add_do_method(this, "setup_local_to_scene");
}
if (prev) {
- undo_redo->add_undo_method(this,"setup_local_to_scene");
+ undo_redo->add_undo_method(this, "setup_local_to_scene");
}
}
}
- undo_redo->add_do_method(this,"emit_signal",_prop_edited,p_name);
- undo_redo->add_undo_method(this,"emit_signal",_prop_edited,p_name);
+ undo_redo->add_do_method(this, "emit_signal", _prop_edited, p_name);
+ undo_redo->add_undo_method(this, "emit_signal", _prop_edited, p_name);
undo_redo->commit_action();
}
}
-
void PropertyEditor::_item_edited() {
-
- TreeItem * item = tree->get_edited();
+ TreeItem *item = tree->get_edited();
if (!item)
return; //it all happened too fast..
Dictionary d = item->get_metadata(0);
- String name=d["name"];
+ String name = d["name"];
- if (tree->get_edited_column()==0) {
+ if (tree->get_edited_column() == 0) {
//property checked
if (autoclear) {
if (!item->is_checked(0)) {
- obj->set(name,Variant());
+ obj->set(name, Variant());
update_property(name);
} else {
Variant::CallError ce;
- obj->set(name,Variant::construct(Variant::Type(int(d["type"])),NULL,0,ce));
+ obj->set(name, Variant::construct(Variant::Type(int(d["type"])), NULL, 0, ce));
}
} else {
- emit_signal("property_toggled",name,item->is_checked(0));
+ emit_signal("property_toggled", name, item->is_checked(0));
}
return;
}
- if (autoclear && item->get_cell_mode(0)==TreeItem::CELL_MODE_CHECK && item->get_cell_mode(1)!=TreeItem::CELL_MODE_CUSTOM) {
- item->set_checked(0,true);
-
+ if (autoclear && item->get_cell_mode(0) == TreeItem::CELL_MODE_CHECK && item->get_cell_mode(1) != TreeItem::CELL_MODE_CUSTOM) {
+ item->set_checked(0, true);
}
-
- int type=d["type"];
- int hint= d["hint"];
+ int type = d["type"];
+ int hint = d["hint"];
int usage = d["usage"];
- bool refresh_all = usage&PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED;
+ bool refresh_all = usage & PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED;
- String hint_text=d["hint_text"];
- switch(type) {
+ String hint_text = d["hint_text"];
+ switch (type) {
case Variant::NIL: {
} break;
case Variant::BOOL: {
- _edit_set(name,item->is_checked(1),refresh_all);
+ _edit_set(name, item->is_checked(1), refresh_all);
item->set_tooltip(1, item->is_checked(1) ? "True" : "False");
} break;
case Variant::INT:
case Variant::REAL: {
- if (hint==PROPERTY_HINT_LAYERS_2D_PHYSICS || hint==PROPERTY_HINT_LAYERS_2D_RENDER || hint==PROPERTY_HINT_LAYERS_3D_PHYSICS || hint==PROPERTY_HINT_LAYERS_3D_RENDER)
+ if (hint == PROPERTY_HINT_LAYERS_2D_PHYSICS || hint == PROPERTY_HINT_LAYERS_2D_RENDER || hint == PROPERTY_HINT_LAYERS_3D_PHYSICS || hint == PROPERTY_HINT_LAYERS_3D_RENDER)
break;
- if (hint==PROPERTY_HINT_EXP_EASING)
+ if (hint == PROPERTY_HINT_EXP_EASING)
break;
- if (hint==PROPERTY_HINT_FLAGS)
+ if (hint == PROPERTY_HINT_FLAGS)
break;
- if (type==Variant::INT)
- _edit_set(name,int(item->get_range(1)),refresh_all);
+ if (type == Variant::INT)
+ _edit_set(name, int(item->get_range(1)), refresh_all);
else
- _edit_set(name,item->get_range(1),refresh_all);
+ _edit_set(name, item->get_range(1), refresh_all);
} break;
case Variant::STRING: {
- if (hint==PROPERTY_HINT_ENUM) {
+ if (hint == PROPERTY_HINT_ENUM) {
- int idx= item->get_range(1);
+ int idx = item->get_range(1);
Vector<String> strings = hint_text.split(",");
String txt;
- if (idx>=0 && idx<strings.size()) {
+ if (idx >= 0 && idx < strings.size()) {
- txt=strings[idx];
+ txt = strings[idx];
}
- _edit_set(name,txt,refresh_all);
+ _edit_set(name, txt, refresh_all);
} else {
- _edit_set(name,item->get_text(1),refresh_all);
+ _edit_set(name, item->get_text(1), refresh_all);
}
} break;
- // math types
+ // math types
case Variant::VECTOR3: {
@@ -4094,7 +3910,7 @@ void PropertyEditor::_item_edited() {
} break;
case Variant::NODE_PATH: {
- _edit_set(name, NodePath(item->get_text(1)),refresh_all);
+ _edit_set(name, NodePath(item->get_text(1)), refresh_all);
} break;
@@ -4105,7 +3921,7 @@ void PropertyEditor::_item_edited() {
} break;
- // arrays
+ // arrays
case Variant::POOL_BYTE_ARRAY: {
} break;
@@ -4124,36 +3940,31 @@ void PropertyEditor::_item_edited() {
case Variant::POOL_COLOR_ARRAY: {
} break;
-
-
};
}
-
void PropertyEditor::_resource_edit_request() {
- RES res=custom_editor->get_variant();
+ RES res = custom_editor->get_variant();
if (res.is_null())
return;
- String name=custom_editor->get_name();
+ String name = custom_editor->get_name();
-
- emit_signal("resource_selected",res.get_ref_ptr(),name);
+ emit_signal("resource_selected", res.get_ref_ptr(), name);
}
void PropertyEditor::_custom_editor_edited() {
-
if (!obj)
return;
_edit_set(custom_editor->get_name(), custom_editor->get_variant());
}
-void PropertyEditor::_custom_editor_edited_field(const String& p_field_name) {
+void PropertyEditor::_custom_editor_edited_field(const String &p_field_name) {
- ERR_FAIL_COND(p_field_name=="");
+ ERR_FAIL_COND(p_field_name == "");
if (!obj)
return;
@@ -4163,38 +3974,37 @@ void PropertyEditor::_custom_editor_edited_field(const String& p_field_name) {
void PropertyEditor::_custom_editor_request(bool p_arrow) {
- TreeItem * item = tree->get_edited();
+ TreeItem *item = tree->get_edited();
ERR_FAIL_COND(!item);
Dictionary d = item->get_metadata(0);
//int type=d["type"];
- String name=d["name"];
- Variant::Type type=Variant::NIL;
+ String name = d["name"];
+ Variant::Type type = Variant::NIL;
if (d.has("type"))
- type=(Variant::Type)((int)(d["type"]));
+ type = (Variant::Type)((int)(d["type"]));
- Variant v=obj->get(name);
- int hint=d.has("hint")?d["hint"].operator int():-1;
- String hint_text=d.has("hint_text")?d["hint_text"]:"";
- Rect2 where=tree->get_custom_popup_rect();
+ Variant v = obj->get(name);
+ int hint = d.has("hint") ? d["hint"].operator int() : -1;
+ String hint_text = d.has("hint_text") ? d["hint_text"] : "";
+ Rect2 where = tree->get_custom_popup_rect();
custom_editor->set_pos(where.pos);
- if (custom_editor->edit(obj,name,type,v,hint,hint_text)) {
+ if (custom_editor->edit(obj, name, type, v, hint, hint_text)) {
custom_editor->popup();
}
}
-void PropertyEditor::edit(Object* p_object) {
+void PropertyEditor::edit(Object *p_object) {
-
- if (obj==p_object)
+ if (obj == p_object)
return;
if (obj) {
obj->remove_change_receptor(this);
}
- obj=p_object;
+ obj = p_object;
evaluator->edit(p_object);
@@ -4204,18 +4014,15 @@ void PropertyEditor::edit(Object* p_object) {
obj->add_change_receptor(this);
}
-
-
}
-void PropertyEditor::_set_range_def(Object *p_item, String prop,float p_frame) {
+void PropertyEditor::_set_range_def(Object *p_item, String prop, float p_frame) {
TreeItem *ti = p_item->cast_to<TreeItem>();
ERR_FAIL_COND(!ti);
- ti->call_deferred("set_range",1, p_frame);
- obj->call_deferred("set",prop,p_frame);
-
+ ti->call_deferred("set_range", 1, p_frame);
+ obj->call_deferred("set", prop, p_frame);
}
void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) {
@@ -4224,49 +4031,48 @@ void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) {
Dictionary d = ti->get_metadata(0);
- if (p_button==2) {
+ if (p_button == 2) {
if (!d.has("name"))
return;
- String prop=d["name"];
- emit_signal("property_keyed",prop,obj->get(prop),false);
- } else if (p_button==5) {
+ String prop = d["name"];
+ emit_signal("property_keyed", prop, obj->get(prop), false);
+ } else if (p_button == 5) {
print_line("PB5");
if (!d.has("name"))
return;
- String prop=d["name"];
- emit_signal("property_keyed",prop,obj->get(prop),true);
+ String prop = d["name"];
+ emit_signal("property_keyed", prop, obj->get(prop), true);
//set_range(p_column, ti->get_range(p_column)+1.0 );
- call_deferred("_set_range_def",ti,prop,ti->get_range(p_column)+1.0);
- } else if (p_button==3) {
+ call_deferred("_set_range_def", ti, prop, ti->get_range(p_column) + 1.0);
+ } else if (p_button == 3) {
if (!d.has("name"))
return;
- String prop=d["name"];
+ String prop = d["name"];
Variant vorig;
- if (_might_be_in_instance() && _get_instanced_node_original_property(prop,vorig)) {
+ if (_might_be_in_instance() && _get_instanced_node_original_property(prop, vorig)) {
- _edit_set(prop,vorig);
+ _edit_set(prop, vorig);
return;
}
- if (obj->call("property_can_revert",prop).operator bool()) {
- Variant rev = obj->call("property_get_revert",prop);
- _edit_set(prop,rev);
+ if (obj->call("property_can_revert", prop).operator bool()) {
+ Variant rev = obj->call("property_get_revert", prop);
+ _edit_set(prop, rev);
}
- if (!obj->get_script().is_null()) {
+ if (!obj->get_script().is_null()) {
Ref<Script> scr = obj->get_script();
Variant orig_value;
- if (scr->get_property_default_value(prop,orig_value)) {
- _edit_set(prop,orig_value);
+ if (scr->get_property_default_value(prop, orig_value)) {
+ _edit_set(prop, orig_value);
}
}
-
} else {
Dictionary d = ti->get_metadata(0);
@@ -4284,7 +4090,7 @@ void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) {
String n = d["name"];
String ht = d["hint_text"];
- if(t == Variant::NODE_PATH) {
+ if (t == Variant::NODE_PATH) {
Variant v = obj->get(n);
custom_editor->edit(obj, n, (Variant::Type)t, v, h, ht);
@@ -4294,72 +4100,69 @@ void PropertyEditor::_edit_button(Object *p_item, int p_column, int p_button) {
custom_editor->set_pos(where.pos);
custom_editor->popup();
- } else if (t==Variant::STRING) {
-
+ } else if (t == Variant::STRING) {
Variant v = obj->get(n);
- custom_editor->edit(obj,n,(Variant::Type)t,v,h,ht);
+ custom_editor->edit(obj, n, (Variant::Type)t, v, h, ht);
//Rect2 where=tree->get_custom_popup_rect();
- if (h==PROPERTY_HINT_FILE || h==PROPERTY_HINT_DIR || h==PROPERTY_HINT_GLOBAL_DIR || h==PROPERTY_HINT_GLOBAL_FILE) {
+ if (h == PROPERTY_HINT_FILE || h == PROPERTY_HINT_DIR || h == PROPERTY_HINT_GLOBAL_DIR || h == PROPERTY_HINT_GLOBAL_FILE) {
- Rect2 where=tree->get_item_rect(ti,1);
- where.pos-=tree->get_scroll();
- where.pos+=tree->get_global_pos();
+ Rect2 where = tree->get_item_rect(ti, 1);
+ where.pos -= tree->get_scroll();
+ where.pos += tree->get_global_pos();
custom_editor->set_pos(where.pos);
custom_editor->popup();
} else {
custom_editor->popup_centered_ratio();
}
- } else if (t==Variant::OBJECT) {
+ } else if (t == Variant::OBJECT) {
RES r = obj->get(n);
if (r.is_valid()) {
- emit_signal("resource_selected",r,n);
+ emit_signal("resource_selected", r, n);
}
- } else if (t==Variant::INT && h==PROPERTY_HINT_OBJECT_ID) {
+ } else if (t == Variant::INT && h == PROPERTY_HINT_OBJECT_ID) {
- emit_signal("object_id_selected",obj->get(n));
+ emit_signal("object_id_selected", obj->get(n));
print_line("OBJ ID SELECTED");
- } else if (t==Variant::ARRAY || t==Variant::POOL_INT_ARRAY || t==Variant::POOL_REAL_ARRAY || t==Variant::POOL_STRING_ARRAY || t==Variant::POOL_VECTOR2_ARRAY || t==Variant::POOL_VECTOR3_ARRAY || t==Variant::POOL_COLOR_ARRAY || t==Variant::POOL_BYTE_ARRAY) {
+ } else if (t == Variant::ARRAY || t == Variant::POOL_INT_ARRAY || t == Variant::POOL_REAL_ARRAY || t == Variant::POOL_STRING_ARRAY || t == Variant::POOL_VECTOR2_ARRAY || t == Variant::POOL_VECTOR3_ARRAY || t == Variant::POOL_COLOR_ARRAY || t == Variant::POOL_BYTE_ARRAY) {
Variant v = obj->get(n);
- if (v.get_type()!=t) {
+ if (v.get_type() != t) {
Variant::CallError ce;
- v=Variant::construct(Variant::Type(t),NULL,0,ce);
+ v = Variant::construct(Variant::Type(t), NULL, 0, ce);
}
- Ref<ArrayPropertyEdit> ape = memnew( ArrayPropertyEdit );
- ape->edit(obj,n,ht,Variant::Type(t));
+ Ref<ArrayPropertyEdit> ape = memnew(ArrayPropertyEdit);
+ ape->edit(obj, n, ht, Variant::Type(t));
EditorNode::get_singleton()->push_item(ape.ptr());
}
}
}
-
void PropertyEditor::_node_removed(Node *p_node) {
- if (p_node==obj) {
+ if (p_node == obj) {
edit(NULL);
}
}
-
void PropertyEditor::set_keying(bool p_active) {
- if (keying==p_active)
+ if (keying == p_active)
return;
- keying=p_active;
+ keying = p_active;
update_tree();
}
-void PropertyEditor::_draw_flags(Object *t,const Rect2& p_rect) {
+void PropertyEditor::_draw_flags(Object *t, const Rect2 &p_rect) {
TreeItem *ti = t->cast_to<TreeItem>();
if (!ti)
@@ -4372,41 +4175,37 @@ void PropertyEditor::_draw_flags(Object *t,const Rect2& p_rect) {
uint32_t f = obj->get(d["name"]);
- int bsize = (p_rect.size.height*80/100)/2;
+ int bsize = (p_rect.size.height * 80 / 100) / 2;
- int h = bsize*2+1;
- int vofs = (p_rect.size.height-h)/2;
+ int h = bsize * 2 + 1;
+ int vofs = (p_rect.size.height - h) / 2;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- Point2 ofs(4,vofs);
- if (i==1)
- ofs.y+=bsize+1;
+ Point2 ofs(4, vofs);
+ if (i == 1)
+ ofs.y += bsize + 1;
- ofs+=p_rect.pos;
- for(int j=0;j<10;j++) {
+ ofs += p_rect.pos;
+ for (int j = 0; j < 10; j++) {
- Point2 o = ofs+Point2(j*(bsize+1),0);
- if (j>=5)
- o.x+=1;
+ Point2 o = ofs + Point2(j * (bsize + 1), 0);
+ if (j >= 5)
+ o.x += 1;
- uint32_t idx=i*10+j;
- bool on=f&(1<<idx);
- tree->draw_rect(Rect2(o,Size2(bsize,bsize)),Color(0,0,0,on?0.8:0.3));
+ uint32_t idx = i * 10 + j;
+ bool on = f & (1 << idx);
+ tree->draw_rect(Rect2(o, Size2(bsize, bsize)), Color(0, 0, 0, on ? 0.8 : 0.3));
}
}
-
-
}
-void PropertyEditor::_filter_changed(const String& p_text) {
+void PropertyEditor::_filter_changed(const String &p_text) {
update_tree();
}
-
-
-void PropertyEditor::_resource_preview_done(const String& p_path,const Ref<Texture>& p_preview,Variant p_ud) {
+void PropertyEditor::_resource_preview_done(const String &p_path, const Ref<Texture> &p_preview, Variant p_ud) {
if (p_preview.is_null())
return; //don't bother with empty preview
@@ -4423,38 +4222,38 @@ void PropertyEditor::_resource_preview_done(const String& p_path,const Ref<Textu
int tw = EditorSettings::get_singleton()->get("docks/property_editor/texture_preview_width");
- ti->set_icon(1,p_preview); //should be scaled I think?
- ti->set_icon_max_width(1,tw);
- ti->set_text(1,"");
+ ti->set_icon(1, p_preview); //should be scaled I think?
+ ti->set_icon_max_width(1, tw);
+ ti->set_text(1, "");
}
void PropertyEditor::_bind_methods() {
- ClassDB::bind_method( "_item_edited",&PropertyEditor::_item_edited);
- ClassDB::bind_method( "_item_selected",&PropertyEditor::_item_selected);
- ClassDB::bind_method( "_custom_editor_request",&PropertyEditor::_custom_editor_request);
- ClassDB::bind_method( "_custom_editor_edited",&PropertyEditor::_custom_editor_edited);
- ClassDB::bind_method( "_custom_editor_edited_field",&PropertyEditor::_custom_editor_edited_field,DEFVAL(""));
- ClassDB::bind_method( "_resource_edit_request",&PropertyEditor::_resource_edit_request);
- ClassDB::bind_method( "_node_removed",&PropertyEditor::_node_removed);
- ClassDB::bind_method( "_edit_button",&PropertyEditor::_edit_button);
- ClassDB::bind_method( "_changed_callback",&PropertyEditor::_changed_callbacks);
- ClassDB::bind_method( "_draw_flags",&PropertyEditor::_draw_flags);
- ClassDB::bind_method( "_set_range_def",&PropertyEditor::_set_range_def);
- ClassDB::bind_method( "_filter_changed",&PropertyEditor::_filter_changed);
- ClassDB::bind_method( "update_tree",&PropertyEditor::update_tree);
- ClassDB::bind_method( "_resource_preview_done",&PropertyEditor::_resource_preview_done);
- ClassDB::bind_method( "refresh",&PropertyEditor::refresh);
- ClassDB::bind_method( "_draw_transparency",&PropertyEditor::_draw_transparency);
+ ClassDB::bind_method("_item_edited", &PropertyEditor::_item_edited);
+ ClassDB::bind_method("_item_selected", &PropertyEditor::_item_selected);
+ ClassDB::bind_method("_custom_editor_request", &PropertyEditor::_custom_editor_request);
+ ClassDB::bind_method("_custom_editor_edited", &PropertyEditor::_custom_editor_edited);
+ ClassDB::bind_method("_custom_editor_edited_field", &PropertyEditor::_custom_editor_edited_field, DEFVAL(""));
+ ClassDB::bind_method("_resource_edit_request", &PropertyEditor::_resource_edit_request);
+ ClassDB::bind_method("_node_removed", &PropertyEditor::_node_removed);
+ ClassDB::bind_method("_edit_button", &PropertyEditor::_edit_button);
+ ClassDB::bind_method("_changed_callback", &PropertyEditor::_changed_callbacks);
+ ClassDB::bind_method("_draw_flags", &PropertyEditor::_draw_flags);
+ ClassDB::bind_method("_set_range_def", &PropertyEditor::_set_range_def);
+ ClassDB::bind_method("_filter_changed", &PropertyEditor::_filter_changed);
+ ClassDB::bind_method("update_tree", &PropertyEditor::update_tree);
+ ClassDB::bind_method("_resource_preview_done", &PropertyEditor::_resource_preview_done);
+ ClassDB::bind_method("refresh", &PropertyEditor::refresh);
+ ClassDB::bind_method("_draw_transparency", &PropertyEditor::_draw_transparency);
ClassDB::bind_method(D_METHOD("get_drag_data_fw"), &PropertyEditor::get_drag_data_fw);
ClassDB::bind_method(D_METHOD("can_drop_data_fw"), &PropertyEditor::can_drop_data_fw);
ClassDB::bind_method(D_METHOD("drop_data_fw"), &PropertyEditor::drop_data_fw);
- ADD_SIGNAL( MethodInfo("property_toggled",PropertyInfo( Variant::STRING, "property"),PropertyInfo( Variant::BOOL, "value")));
- ADD_SIGNAL( MethodInfo("resource_selected", PropertyInfo( Variant::OBJECT, "res"),PropertyInfo( Variant::STRING, "prop") ) );
- ADD_SIGNAL( MethodInfo("object_id_selected", PropertyInfo( Variant::INT, "id")) );
- ADD_SIGNAL( MethodInfo("property_keyed",PropertyInfo( Variant::STRING, "property")));
- ADD_SIGNAL( MethodInfo("property_edited",PropertyInfo( Variant::STRING, "property")));
+ ADD_SIGNAL(MethodInfo("property_toggled", PropertyInfo(Variant::STRING, "property"), PropertyInfo(Variant::BOOL, "value")));
+ ADD_SIGNAL(MethodInfo("resource_selected", PropertyInfo(Variant::OBJECT, "res"), PropertyInfo(Variant::STRING, "prop")));
+ ADD_SIGNAL(MethodInfo("object_id_selected", PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("property_keyed", PropertyInfo(Variant::STRING, "property")));
+ ADD_SIGNAL(MethodInfo("property_edited", PropertyInfo(Variant::STRING, "property")));
}
Tree *PropertyEditor::get_scene_tree() {
@@ -4462,7 +4261,7 @@ Tree *PropertyEditor::get_scene_tree() {
return tree;
}
-Label* PropertyEditor::get_top_label() {
+Label *PropertyEditor::get_top_label() {
return top_label;
}
@@ -4470,12 +4269,11 @@ Label* PropertyEditor::get_top_label() {
void PropertyEditor::hide_top_label() {
top_label->hide();
- tree->set_begin( Point2(0,0 ));
+ tree->set_begin(Point2(0, 0));
}
String PropertyEditor::get_selected_path() const {
-
TreeItem *ti = tree->get_selected();
if (!ti)
return "";
@@ -4490,244 +4288,228 @@ String PropertyEditor::get_selected_path() const {
void PropertyEditor::set_capitalize_paths(bool p_capitalize) {
- capitalize_paths=p_capitalize;
+ capitalize_paths = p_capitalize;
}
void PropertyEditor::set_autoclear(bool p_enable) {
- autoclear=p_enable;
+ autoclear = p_enable;
}
void PropertyEditor::set_show_categories(bool p_show) {
- show_categories=p_show;
+ show_categories = p_show;
update_tree();
}
void PropertyEditor::set_use_filter(bool p_use) {
- if (p_use==use_filter)
+ if (p_use == use_filter)
return;
- use_filter=p_use;
+ use_filter = p_use;
update_tree();
}
-void PropertyEditor::register_text_enter(Node* p_line_edit) {
+void PropertyEditor::register_text_enter(Node *p_line_edit) {
ERR_FAIL_NULL(p_line_edit);
- search_box=p_line_edit->cast_to<LineEdit>();
+ search_box = p_line_edit->cast_to<LineEdit>();
if (search_box)
- search_box->connect("text_changed",this,"_filter_changed");
+ search_box->connect("text_changed", this, "_filter_changed");
}
void PropertyEditor::set_subsection_selectable(bool p_selectable) {
- if (p_selectable==subsection_selectable)
+ if (p_selectable == subsection_selectable)
return;
- subsection_selectable=p_selectable;
+ subsection_selectable = p_selectable;
update_tree();
}
PropertyEditor::PropertyEditor() {
- _prop_edited="property_edited";
+ _prop_edited = "property_edited";
- hide_script=false;
+ hide_script = false;
- undo_redo=NULL;
- obj=NULL;
- search_box=NULL;
- changing=false;
- update_tree_pending=false;
+ undo_redo = NULL;
+ obj = NULL;
+ search_box = NULL;
+ changing = false;
+ update_tree_pending = false;
- top_label = memnew( Label );
+ top_label = memnew(Label);
top_label->set_text(TTR("Properties:"));
- top_label->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- top_label->set_begin( Point2( 10,0) );
- top_label->set_end( Point2( 0,12) );
+ top_label->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ top_label->set_begin(Point2(10, 0));
+ top_label->set_end(Point2(0, 12));
add_child(top_label);
-
- tree = memnew( Tree );
- tree->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
- tree->set_begin( Point2(0,19 ));
- tree->set_end( Point2(0,0 ));
+ tree = memnew(Tree);
+ tree->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ tree->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
+ tree->set_begin(Point2(0, 19));
+ tree->set_end(Point2(0, 0));
tree->set_columns(2);
- tree->set_column_expand(0,true);
- tree->set_column_min_width(0,30);
- tree->set_column_expand(1,true);
- tree->set_column_min_width(1,18);
+ tree->set_column_expand(0, true);
+ tree->set_column_min_width(0, 30);
+ tree->set_column_expand(1, true);
+ tree->set_column_min_width(1, 18);
//tree->set_hide_root(true);
- add_child( tree );
+ add_child(tree);
- tree->connect("item_edited", this,"_item_edited",varray(),CONNECT_DEFERRED);
- tree->connect("cell_selected", this,"_item_selected");
+ tree->connect("item_edited", this, "_item_edited", varray(), CONNECT_DEFERRED);
+ tree->connect("cell_selected", this, "_item_selected");
tree->set_drag_forwarding(this);
set_fixed_process(true);
- custom_editor = memnew( CustomPropertyEditor );
+ custom_editor = memnew(CustomPropertyEditor);
add_child(custom_editor);
- tree->connect("custom_popup_edited", this,"_custom_editor_request");
- tree->connect("button_pressed", this,"_edit_button");
- custom_editor->connect("variant_changed", this,"_custom_editor_edited");
- custom_editor->connect("variant_field_changed", this,"_custom_editor_edited_field");
- custom_editor->connect("resource_edit_request", this,"_resource_edit_request",make_binds(),CONNECT_DEFERRED);
+ tree->connect("custom_popup_edited", this, "_custom_editor_request");
+ tree->connect("button_pressed", this, "_edit_button");
+ custom_editor->connect("variant_changed", this, "_custom_editor_edited");
+ custom_editor->connect("variant_field_changed", this, "_custom_editor_edited_field");
+ custom_editor->connect("resource_edit_request", this, "_resource_edit_request", make_binds(), CONNECT_DEFERRED);
tree->set_hide_folding(true);
- evaluator = memnew (PropertyValueEvaluator);
+ evaluator = memnew(PropertyValueEvaluator);
tree->set_value_evaluator(evaluator);
custom_editor->set_value_evaluator(evaluator);
- capitalize_paths=true;
- autoclear=false;
+ capitalize_paths = true;
+ autoclear = false;
tree->set_column_titles_visible(false);
- keying=false;
- read_only=false;
- show_categories=false;
- refresh_countdown=0;
- use_doc_hints=false;
- use_filter=false;
- subsection_selectable=false;
- show_type_icons=EDITOR_DEF("interface/show_type_icons",false);
-
+ keying = false;
+ read_only = false;
+ show_categories = false;
+ refresh_countdown = 0;
+ use_doc_hints = false;
+ use_filter = false;
+ subsection_selectable = false;
+ show_type_icons = EDITOR_DEF("interface/show_type_icons", false);
}
-
-PropertyEditor::~PropertyEditor()
-{
+PropertyEditor::~PropertyEditor() {
memdelete(evaluator);
}
-
/////////////////////////////
-
-
-
-
class SectionedPropertyEditorFilter : public Object {
- GDCLASS( SectionedPropertyEditorFilter, Object );
+ GDCLASS(SectionedPropertyEditorFilter, Object);
Object *edited;
String section;
bool allow_sub;
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
if (!edited)
return false;
- String name=p_name;
- if (section!="") {
- name=section+"/"+name;
+ String name = p_name;
+ if (section != "") {
+ name = section + "/" + name;
}
bool valid;
- edited->set(name,p_value,&valid);
+ edited->set(name, p_value, &valid);
//_change_notify(p_name.operator String().utf8().get_data());
return valid;
}
- bool _get(const StringName& p_name,Variant &r_ret) const{
+ bool _get(const StringName &p_name, Variant &r_ret) const {
if (!edited)
return false;
- String name=p_name;
- if (section!="") {
- name=section+"/"+name;
+ String name = p_name;
+ if (section != "") {
+ name = section + "/" + name;
}
- bool valid=false;
+ bool valid = false;
- r_ret=edited->get(name,&valid);
+ r_ret = edited->get(name, &valid);
return valid;
-
-
}
- void _get_property_list(List<PropertyInfo> *p_list) const{
+ void _get_property_list(List<PropertyInfo> *p_list) const {
if (!edited)
return;
List<PropertyInfo> pinfo;
edited->get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- PropertyInfo pi=E->get();
+ PropertyInfo pi = E->get();
int sp = pi.name.find("/");
- if (pi.name=="resource_path" || pi.name=="resource_name" || pi.name.begins_with("script/")) //skip resource stuff
+ if (pi.name == "resource_path" || pi.name == "resource_name" || pi.name.begins_with("script/")) //skip resource stuff
continue;
- if (sp==-1) {
- pi.name="Global/"+pi.name;
-
+ if (sp == -1) {
+ pi.name = "Global/" + pi.name;
}
- if (pi.name.begins_with(section+"/")) {
- pi.name=pi.name.replace_first(section+"/","");
- if (!allow_sub && pi.name.find("/")!=-1)
+ if (pi.name.begins_with(section + "/")) {
+ pi.name = pi.name.replace_first(section + "/", "");
+ if (!allow_sub && pi.name.find("/") != -1)
continue;
p_list->push_back(pi);
}
}
-
}
- bool property_can_revert(const String& p_name) {
+ bool property_can_revert(const String &p_name) {
- return edited->call("property_can_revert",section+"/"+p_name);
+ return edited->call("property_can_revert", section + "/" + p_name);
}
- Variant property_get_revert(const String& p_name) {
+ Variant property_get_revert(const String &p_name) {
- return edited->call("property_get_revert",section+"/"+p_name);
+ return edited->call("property_get_revert", section + "/" + p_name);
}
protected:
static void _bind_methods() {
- ClassDB::bind_method("property_can_revert",&SectionedPropertyEditorFilter::property_can_revert);
- ClassDB::bind_method("property_get_revert",&SectionedPropertyEditorFilter::property_get_revert);
+ ClassDB::bind_method("property_can_revert", &SectionedPropertyEditorFilter::property_can_revert);
+ ClassDB::bind_method("property_get_revert", &SectionedPropertyEditorFilter::property_get_revert);
}
public:
+ void set_section(const String &p_section, bool p_allow_sub) {
- void set_section(const String& p_section,bool p_allow_sub) {
-
- section=p_section;
- allow_sub=p_allow_sub;
+ section = p_section;
+ allow_sub = p_allow_sub;
_change_notify();
}
- void set_edited(Object* p_edited) {
- edited=p_edited;
+ void set_edited(Object *p_edited) {
+ edited = p_edited;
_change_notify();
}
SectionedPropertyEditorFilter() {
- edited=NULL;
+ edited = NULL;
}
-
};
-
void SectionedPropertyEditor::_bind_methods() {
- ClassDB::bind_method("_section_selected",&SectionedPropertyEditor::_section_selected);
+ ClassDB::bind_method("_section_selected", &SectionedPropertyEditor::_section_selected);
ClassDB::bind_method("update_category_list", &SectionedPropertyEditor::update_category_list);
}
@@ -4737,10 +4519,10 @@ void SectionedPropertyEditor::_section_selected() {
if (!sections->get_selected())
return;
- filter->set_section( sections->get_selected()->get_metadata(0), sections->get_selected()->get_children()==NULL);
+ filter->set_section(sections->get_selected()->get_metadata(0), sections->get_selected()->get_children() == NULL);
}
-void SectionedPropertyEditor::set_current_section(const String& p_section) {
+void SectionedPropertyEditor::set_current_section(const String &p_section) {
if (section_map.has(p_section)) {
section_map[p_section]->select(0);
@@ -4755,17 +4537,17 @@ String SectionedPropertyEditor::get_current_section() const {
return "";
}
-String SectionedPropertyEditor::get_full_item_path(const String& p_item) {
+String SectionedPropertyEditor::get_full_item_path(const String &p_item) {
String base = get_current_section();
- if (base!="")
- return base+"/"+p_item;
+ if (base != "")
+ return base + "/" + p_item;
else
return p_item;
}
-void SectionedPropertyEditor::edit(Object* p_object) {
+void SectionedPropertyEditor::edit(Object *p_object) {
if (!p_object) {
obj = -1;
@@ -4798,7 +4580,7 @@ void SectionedPropertyEditor::edit(Object* p_object) {
void SectionedPropertyEditor::update_category_list() {
- String selected_category=get_current_section();
+ String selected_category = get_current_section();
sections->clear();
Object *o = ObjectDB::get_instance(obj);
@@ -4812,48 +4594,43 @@ void SectionedPropertyEditor::update_category_list() {
section_map.clear();
TreeItem *root = sections->create_item();
- section_map[""]=root;
+ section_map[""] = root;
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ PropertyInfo pi = E->get();
- PropertyInfo pi=E->get();
-
- if (pi.usage&PROPERTY_USAGE_CATEGORY)
+ if (pi.usage & PROPERTY_USAGE_CATEGORY)
continue;
- else if ( !(pi.usage&PROPERTY_USAGE_EDITOR) )
+ else if (!(pi.usage & PROPERTY_USAGE_EDITOR))
continue;
- if (pi.name.find(":")!=-1 || pi.name=="script" || pi.name=="resource_name" || pi.name=="resource_path")
+ if (pi.name.find(":") != -1 || pi.name == "script" || pi.name == "resource_name" || pi.name == "resource_path")
continue;
int sp = pi.name.find("/");
- if (sp==-1)
- pi.name="Global/"+pi.name;
+ if (sp == -1)
+ pi.name = "Global/" + pi.name;
Vector<String> sectionarr = pi.name.split("/");
String metasection;
-
- for(int i=0;i<MIN(2,sectionarr.size()-1);i++) {
+ for (int i = 0; i < MIN(2, sectionarr.size() - 1); i++) {
TreeItem *parent = section_map[metasection];
- if (i>0) {
- metasection+="/"+sectionarr[i];
+ if (i > 0) {
+ metasection += "/" + sectionarr[i];
} else {
- metasection=sectionarr[i];
+ metasection = sectionarr[i];
}
-
if (!section_map.has(metasection)) {
TreeItem *ms = sections->create_item(parent);
- section_map[metasection]=ms;
- ms->set_text(0,sectionarr[i].capitalize());
- ms->set_metadata(0,metasection);
-
+ section_map[metasection] = ms;
+ ms->set_text(0, sectionarr[i].capitalize());
+ ms->set_metadata(0, metasection);
}
}
-
}
if (section_map.has(selected_category)) {
@@ -4870,32 +4647,30 @@ SectionedPropertyEditor::SectionedPropertyEditor() {
obj = -1;
- VBoxContainer *left_vb = memnew( VBoxContainer);
- left_vb->set_custom_minimum_size(Size2(160,0)*EDSCALE);
+ VBoxContainer *left_vb = memnew(VBoxContainer);
+ left_vb->set_custom_minimum_size(Size2(160, 0) * EDSCALE);
add_child(left_vb);
- sections = memnew( Tree );
+ sections = memnew(Tree);
sections->set_v_size_flags(SIZE_EXPAND_FILL);
sections->set_hide_root(true);
- left_vb->add_margin_child(TTR("Sections:"),sections,true);
+ left_vb->add_margin_child(TTR("Sections:"), sections, true);
- VBoxContainer *right_vb = memnew( VBoxContainer);
+ VBoxContainer *right_vb = memnew(VBoxContainer);
right_vb->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(right_vb);
- filter = memnew( SectionedPropertyEditorFilter );
- editor = memnew( PropertyEditor );
+ filter = memnew(SectionedPropertyEditorFilter);
+ editor = memnew(PropertyEditor);
editor->set_v_size_flags(SIZE_EXPAND_FILL);
- right_vb->add_margin_child(TTR("Properties:"),editor,true);
+ right_vb->add_margin_child(TTR("Properties:"), editor, true);
editor->get_scene_tree()->set_column_titles_visible(false);
-
editor->hide_top_label();
- sections->connect("cell_selected",this,"_section_selected");
-
+ sections->connect("cell_selected", this, "_section_selected");
}
SectionedPropertyEditor::~SectionedPropertyEditor() {
@@ -4903,12 +4678,12 @@ SectionedPropertyEditor::~SectionedPropertyEditor() {
memdelete(filter);
}
-double PropertyValueEvaluator::eval(const String& p_text) {
+double PropertyValueEvaluator::eval(const String &p_text) {
if (!obj || !script_language)
return _default_eval(p_text);
- Ref<Script> script= Ref<Script>(script_language ->create_script());
+ Ref<Script> script = Ref<Script>(script_language->create_script());
script->set_source_code(_build_script(p_text));
Error err = script->reload();
if (err) {
@@ -4921,8 +4696,8 @@ double PropertyValueEvaluator::eval(const String& p_text) {
return _default_eval(p_text);
Variant::CallError call_err;
- script_instance->call("set_this",obj);
- double result = script_instance->call("e", NULL, 0, call_err );
+ script_instance->call("set_this", obj);
+ double result = script_instance->call("e", NULL, 0, call_err);
if (call_err.error == Variant::CallError::CALL_OK) {
return result;
}
@@ -4933,12 +4708,11 @@ double PropertyValueEvaluator::eval(const String& p_text) {
return _default_eval(p_text);
}
-
void PropertyValueEvaluator::edit(Object *p_obj) {
obj = p_obj;
}
-String PropertyValueEvaluator::_build_script(const String& p_text) {
+String PropertyValueEvaluator::_build_script(const String &p_text) {
String script_text = "tool\nvar this\nfunc set_this(p_this):\n\tthis=p_this\nfunc e():\n\treturn ";
script_text += p_text.strip_edges();
script_text += "\n";
@@ -4946,15 +4720,14 @@ String PropertyValueEvaluator::_build_script(const String& p_text) {
}
PropertyValueEvaluator::PropertyValueEvaluator() {
- script_language=NULL;
+ script_language = NULL;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- if (ScriptServer::get_language(i)->get_name()=="GDScript") {
- script_language=ScriptServer::get_language(i);
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ if (ScriptServer::get_language(i)->get_name() == "GDScript") {
+ script_language = ScriptServer::get_language(i);
}
}
}
PropertyValueEvaluator::~PropertyValueEvaluator() {
-
}
diff --git a/editor/property_editor.h b/editor/property_editor.h
index c9ae9a85cc..f7f8d0e974 100644
--- a/editor/property_editor.h
+++ b/editor/property_editor.h
@@ -29,19 +29,19 @@
#ifndef PROPERTY_EDITOR_H
#define PROPERTY_EDITOR_H
-#include "scene/gui/tree.h"
+#include "editor/editor_file_dialog.h"
#include "scene/gui/button.h"
#include "scene/gui/check_box.h"
-#include "scene/gui/label.h"
-#include "editor/editor_file_dialog.h"
-#include "scene/gui/dialogs.h"
+#include "scene/gui/check_button.h"
#include "scene/gui/color_picker.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/grid_container.h"
+#include "scene/gui/label.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/texture_rect.h"
-#include "scene/gui/text_edit.h"
-#include "scene/gui/check_button.h"
#include "scene/gui/split_container.h"
-#include "scene/gui/grid_container.h"
+#include "scene/gui/text_edit.h"
+#include "scene/gui/texture_rect.h"
+#include "scene/gui/tree.h"
#include "scene_tree_editor.h"
/**
@@ -54,21 +54,21 @@ class PropertySelector;
class CustomPropertyEditor : public Popup {
- GDCLASS( CustomPropertyEditor, Popup );
+ GDCLASS(CustomPropertyEditor, Popup);
enum {
- MAX_VALUE_EDITORS=12,
- MAX_ACTION_BUTTONS=5,
- OBJ_MENU_LOAD=0,
- OBJ_MENU_EDIT=1,
- OBJ_MENU_CLEAR=2,
- OBJ_MENU_MAKE_UNIQUE=3,
- OBJ_MENU_COPY=4,
- OBJ_MENU_PASTE=5,
- OBJ_MENU_REIMPORT=6,
- OBJ_MENU_NEW_SCRIPT=7,
- OBJ_MENU_SHOW_IN_FILE_SYSTEM=8,
- TYPE_BASE_ID=100
+ MAX_VALUE_EDITORS = 12,
+ MAX_ACTION_BUTTONS = 5,
+ OBJ_MENU_LOAD = 0,
+ OBJ_MENU_EDIT = 1,
+ OBJ_MENU_CLEAR = 2,
+ OBJ_MENU_MAKE_UNIQUE = 3,
+ OBJ_MENU_COPY = 4,
+ OBJ_MENU_PASTE = 5,
+ OBJ_MENU_REIMPORT = 6,
+ OBJ_MENU_NEW_SCRIPT = 7,
+ OBJ_MENU_SHOW_IN_FILE_SYSTEM = 8,
+ TYPE_BASE_ID = 100
};
enum {
@@ -80,7 +80,6 @@ class CustomPropertyEditor : public Popup {
EASING_OUT_IN
};
-
PopupMenu *menu;
SceneTreeDialog *scene_tree;
EditorFileDialog *file;
@@ -108,12 +107,11 @@ class CustomPropertyEditor : public Popup {
SpinBox *spinbox;
HSlider *slider;
-
Control *easing_draw;
CreateDialog *create_dialog;
PropertySelector *property_select;
- Object* owner;
+ Object *owner;
bool updating;
@@ -131,46 +129,41 @@ class CustomPropertyEditor : public Popup {
void _create_dialog_callback();
void _create_selected_property(const String &p_prop);
-
- void _color_changed(const Color& p_color);
+ void _color_changed(const Color &p_color);
void _draw_easing();
void _menu_option(int p_which);
- void _drag_easing(const InputEvent& p_ev);
+ void _drag_easing(const InputEvent &p_ev);
void _node_path_selected(NodePath p_path);
void show_value_editors(int p_amount);
- void config_value_editors(int p_amount, int p_columns,int p_label_w,const List<String>& p_strings);
- void config_action_buttons(const List<String>& p_strings);
+ void config_value_editors(int p_amount, int p_columns, int p_label_w, const List<String> &p_strings);
+ void config_action_buttons(const List<String> &p_strings);
void _emit_changed_whole_or_field();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
-
void hide_menu();
Variant get_variant() const;
String get_name() const;
- void set_read_only(bool p_read_only) { read_only=p_read_only; }
+ void set_read_only(bool p_read_only) { read_only = p_read_only; }
- void set_value_evaluator( PropertyValueEvaluator *p_evaluator) { evaluator=p_evaluator; }
+ void set_value_evaluator(PropertyValueEvaluator *p_evaluator) { evaluator = p_evaluator; }
- bool edit(Object* p_owner,const String& p_name,Variant::Type p_type, const Variant& p_variant,int p_hint,String p_hint_text);
+ bool edit(Object *p_owner, const String &p_name, Variant::Type p_type, const Variant &p_variant, int p_hint, String p_hint_text);
CustomPropertyEditor();
};
class PropertyEditor : public Control {
- GDCLASS( PropertyEditor, Control );
+ GDCLASS(PropertyEditor, Control);
Tree *tree;
Label *top_label;
@@ -179,8 +172,7 @@ class PropertyEditor : public Control {
PropertyValueEvaluator *evaluator;
- Object* obj;
-
+ Object *obj;
StringName _prop_edited;
@@ -198,91 +190,93 @@ class PropertyEditor : public Control {
bool subsection_selectable;
bool hide_script;
- HashMap<String,String> pending;
+ HashMap<String, String> pending;
String selected_property;
- Map<StringName,Map<StringName,String> > descr_cache;
- Map<StringName,String > class_descr_cache;
+ Map<StringName, Map<StringName, String> > descr_cache;
+ Map<StringName, String> class_descr_cache;
CustomPropertyEditor *custom_editor;
void _resource_edit_request();
void _custom_editor_edited();
- void _custom_editor_edited_field(const String& p_field_name);
+ void _custom_editor_edited_field(const String &p_field_name);
void _custom_editor_request(bool p_arrow);
void _item_selected();
void _item_edited();
- TreeItem *get_parent_node(String p_path,HashMap<String,TreeItem*>& item_paths,TreeItem *root);
-
- void set_item_text(TreeItem *p_item, int p_type, const String& p_name, int p_hint=PROPERTY_HINT_NONE, const String& p_hint_text="");
+ TreeItem *get_parent_node(String p_path, HashMap<String, TreeItem *> &item_paths, TreeItem *root);
- TreeItem *find_item(TreeItem *p_item,const String& p_name);
+ void set_item_text(TreeItem *p_item, int p_type, const String &p_name, int p_hint = PROPERTY_HINT_NONE, const String &p_hint_text = "");
+ TreeItem *find_item(TreeItem *p_item, const String &p_name);
- virtual void _changed_callback(Object *p_changed,const char * p_what);
- virtual void _changed_callbacks(Object *p_changed,const String& p_callback);
+ virtual void _changed_callback(Object *p_changed, const char *p_what);
+ virtual void _changed_callbacks(Object *p_changed, const String &p_callback);
- void _check_reload_status(const String&p_name,TreeItem* item);
+ void _check_reload_status(const String &p_name, TreeItem *item);
void _edit_button(Object *p_item, int p_column, int p_button);
void _node_removed(Node *p_node);
-friend class ProjectExportDialog;
- void _edit_set(const String& p_name, const Variant& p_value,bool p_refresh_all=false, const String& p_changed_field="");
- void _draw_flags(Object *ti,const Rect2& p_rect);
+ friend class ProjectExportDialog;
+ void _edit_set(const String &p_name, const Variant &p_value, bool p_refresh_all = false, const String &p_changed_field = "");
+ void _draw_flags(Object *ti, const Rect2 &p_rect);
bool _might_be_in_instance();
- bool _get_instanced_node_original_property(const StringName& p_prop,Variant& value);
- bool _is_property_different(const Variant& p_current, const Variant& p_orig,int p_usage=0);
+ bool _get_instanced_node_original_property(const StringName &p_prop, Variant &value);
+ bool _is_property_different(const Variant &p_current, const Variant &p_orig, int p_usage = 0);
void _refresh_item(TreeItem *p_item);
void _set_range_def(Object *p_item, String prop, float p_frame);
- void _filter_changed(const String& p_text);
+ void _filter_changed(const String &p_text);
- void _mark_drop_fields(TreeItem* p_at);
- void _clear_drop_fields(TreeItem* p_at);
+ void _mark_drop_fields(TreeItem *p_at);
+ void _clear_drop_fields(TreeItem *p_at);
- bool _is_drop_valid(const Dictionary& p_drag_data, const Dictionary& p_item_data) const;
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ bool _is_drop_valid(const Dictionary &p_drag_data, const Dictionary &p_item_data) const;
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
- void _resource_preview_done(const String& p_path,const Ref<Texture>& p_preview,Variant p_ud);
- void _draw_transparency(Object *t, const Rect2& p_rect);
+ void _resource_preview_done(const String &p_path, const Ref<Texture> &p_preview, Variant p_ud);
+ void _draw_transparency(Object *t, const Rect2 &p_rect);
UndoRedo *undo_redo;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo=p_undo_redo; }
+public:
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; }
String get_selected_path() const;
Tree *get_scene_tree();
- Label* get_top_label();
+ Label *get_top_label();
void hide_top_label();
void update_tree();
- void update_property(const String& p_prop);
+ void update_property(const String &p_prop);
void refresh();
- void edit(Object* p_object);
+ void edit(Object *p_object);
void set_keying(bool p_active);
- void set_read_only(bool p_read_only) { read_only=p_read_only; custom_editor->set_read_only(p_read_only);}
+ void set_read_only(bool p_read_only) {
+ read_only = p_read_only;
+ custom_editor->set_read_only(p_read_only);
+ }
void set_capitalize_paths(bool p_capitalize);
void set_autoclear(bool p_enable);
void set_show_categories(bool p_show);
- void set_use_doc_hints(bool p_enable) { use_doc_hints=p_enable; }
- void set_hide_script(bool p_hide) { hide_script=p_hide; }
+ void set_use_doc_hints(bool p_enable) { use_doc_hints = p_enable; }
+ void set_hide_script(bool p_hide) { hide_script = p_hide; }
void set_use_filter(bool p_use);
void register_text_enter(Node *p_line_edit);
@@ -291,36 +285,31 @@ public:
PropertyEditor();
~PropertyEditor();
-
};
-
class SectionedPropertyEditorFilter;
class SectionedPropertyEditor : public HBoxContainer {
-
- GDCLASS(SectionedPropertyEditor,HBoxContainer);
+ GDCLASS(SectionedPropertyEditor, HBoxContainer);
ObjectID obj;
Tree *sections;
SectionedPropertyEditorFilter *filter;
- Map<String,TreeItem*> section_map;
+ Map<String, TreeItem *> section_map;
PropertyEditor *editor;
-
static void _bind_methods();
void _section_selected();
public:
-
PropertyEditor *get_property_editor();
- void edit(Object* p_object);
- String get_full_item_path(const String& p_item);
+ void edit(Object *p_object);
+ String get_full_item_path(const String &p_item);
- void set_current_section(const String& p_section);
+ void set_current_section(const String &p_section);
String get_current_section() const;
void update_category_list();
@@ -330,20 +319,19 @@ public:
};
class PropertyValueEvaluator : public ValueEvaluator {
- GDCLASS( PropertyValueEvaluator, ValueEvaluator );
+ GDCLASS(PropertyValueEvaluator, ValueEvaluator);
Object *obj;
ScriptLanguage *script_language;
- String _build_script(const String& p_text);
+ String _build_script(const String &p_text);
- _FORCE_INLINE_ double _default_eval(const String& p_text) {
+ _FORCE_INLINE_ double _default_eval(const String &p_text) {
return p_text.to_double();
}
public:
-
void edit(Object *p_obj);
- double eval(const String& p_text);
+ double eval(const String &p_text);
PropertyValueEvaluator();
~PropertyValueEvaluator();
diff --git a/editor/property_selector.cpp b/editor/property_selector.cpp
index 71ffae4729..34086ba905 100644
--- a/editor/property_selector.cpp
+++ b/editor/property_selector.cpp
@@ -31,16 +31,16 @@
#include "editor_scale.h"
#include "os/keyboard.h"
-void PropertySelector::_text_changed(const String& p_newtext) {
+void PropertySelector::_text_changed(const String &p_newtext) {
_update_search();
}
-void PropertySelector::_sbox_input(const InputEvent& p_ie) {
+void PropertySelector::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY) {
+ if (p_ie.type == InputEvent::KEY) {
- switch(p_ie.key.scancode) {
+ switch (p_ie.key.scancode) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
@@ -68,10 +68,8 @@ void PropertySelector::_sbox_input(const InputEvent& p_ie) {
}
}
-
void PropertySelector::_update_search() {
-
if (properties)
set_title(TTR("Select Property"));
else
@@ -80,138 +78,132 @@ void PropertySelector::_update_search() {
search_options->clear();
help_bit->set_text("");
-
TreeItem *root = search_options->create_item();
-
if (properties) {
List<PropertyInfo> props;
if (instance) {
- instance->get_property_list(&props,true);
- } else if (type!=Variant::NIL) {
+ instance->get_property_list(&props, true);
+ } else if (type != Variant::NIL) {
Variant v;
- if (type==Variant::INPUT_EVENT) {
+ if (type == Variant::INPUT_EVENT) {
InputEvent ie;
- ie.type=event_type;
- v=ie;
+ ie.type = event_type;
+ v = ie;
} else {
Variant::CallError ce;
- v=Variant::construct(type,NULL,0,ce);
+ v = Variant::construct(type, NULL, 0, ce);
}
v.get_property_list(&props);
} else {
-
Object *obj = ObjectDB::get_instance(script);
if (obj && obj->cast_to<Script>()) {
- props.push_back(PropertyInfo(Variant::NIL,"Script Variables",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_CATEGORY));
+ props.push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CATEGORY));
obj->cast_to<Script>()->get_script_property_list(&props);
}
- StringName base=base_type;
- while(base) {
- props.push_back(PropertyInfo(Variant::NIL,base,PROPERTY_HINT_NONE,"",PROPERTY_USAGE_CATEGORY));
- ClassDB::get_property_list(base,&props,true);
- base=ClassDB::get_parent_class(base);
+ StringName base = base_type;
+ while (base) {
+ props.push_back(PropertyInfo(Variant::NIL, base, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_CATEGORY));
+ ClassDB::get_property_list(base, &props, true);
+ base = ClassDB::get_parent_class(base);
}
-
}
- TreeItem *category=NULL;
-
- bool found=false;
-
- Ref<Texture> type_icons[Variant::VARIANT_MAX]={
- Control::get_icon("MiniVariant","EditorIcons"),
- Control::get_icon("MiniBoolean","EditorIcons"),
- Control::get_icon("MiniInteger","EditorIcons"),
- Control::get_icon("MiniFloat","EditorIcons"),
- Control::get_icon("MiniString","EditorIcons"),
- Control::get_icon("MiniVector2","EditorIcons"),
- Control::get_icon("MiniRect2","EditorIcons"),
- Control::get_icon("MiniVector3","EditorIcons"),
- Control::get_icon("MiniMatrix2","EditorIcons"),
- Control::get_icon("MiniPlane","EditorIcons"),
- Control::get_icon("MiniQuat","EditorIcons"),
- Control::get_icon("MiniAabb","EditorIcons"),
- Control::get_icon("MiniMatrix3","EditorIcons"),
- Control::get_icon("MiniTransform","EditorIcons"),
- Control::get_icon("MiniColor","EditorIcons"),
- Control::get_icon("MiniImage","EditorIcons"),
- Control::get_icon("MiniPath","EditorIcons"),
- Control::get_icon("MiniRid","EditorIcons"),
- Control::get_icon("MiniObject","EditorIcons"),
- Control::get_icon("MiniInput","EditorIcons"),
- Control::get_icon("MiniDictionary","EditorIcons"),
- Control::get_icon("MiniArray","EditorIcons"),
- Control::get_icon("MiniRawArray","EditorIcons"),
- Control::get_icon("MiniIntArray","EditorIcons"),
- Control::get_icon("MiniFloatArray","EditorIcons"),
- Control::get_icon("MiniStringArray","EditorIcons"),
- Control::get_icon("MiniVector2Array","EditorIcons"),
- Control::get_icon("MiniVector3Array","EditorIcons"),
- Control::get_icon("MiniColorArray","EditorIcons")
+ TreeItem *category = NULL;
+
+ bool found = false;
+
+ Ref<Texture> type_icons[Variant::VARIANT_MAX] = {
+ Control::get_icon("MiniVariant", "EditorIcons"),
+ Control::get_icon("MiniBoolean", "EditorIcons"),
+ Control::get_icon("MiniInteger", "EditorIcons"),
+ Control::get_icon("MiniFloat", "EditorIcons"),
+ Control::get_icon("MiniString", "EditorIcons"),
+ Control::get_icon("MiniVector2", "EditorIcons"),
+ Control::get_icon("MiniRect2", "EditorIcons"),
+ Control::get_icon("MiniVector3", "EditorIcons"),
+ Control::get_icon("MiniMatrix2", "EditorIcons"),
+ Control::get_icon("MiniPlane", "EditorIcons"),
+ Control::get_icon("MiniQuat", "EditorIcons"),
+ Control::get_icon("MiniAabb", "EditorIcons"),
+ Control::get_icon("MiniMatrix3", "EditorIcons"),
+ Control::get_icon("MiniTransform", "EditorIcons"),
+ Control::get_icon("MiniColor", "EditorIcons"),
+ Control::get_icon("MiniImage", "EditorIcons"),
+ Control::get_icon("MiniPath", "EditorIcons"),
+ Control::get_icon("MiniRid", "EditorIcons"),
+ Control::get_icon("MiniObject", "EditorIcons"),
+ Control::get_icon("MiniInput", "EditorIcons"),
+ Control::get_icon("MiniDictionary", "EditorIcons"),
+ Control::get_icon("MiniArray", "EditorIcons"),
+ Control::get_icon("MiniRawArray", "EditorIcons"),
+ Control::get_icon("MiniIntArray", "EditorIcons"),
+ Control::get_icon("MiniFloatArray", "EditorIcons"),
+ Control::get_icon("MiniStringArray", "EditorIcons"),
+ Control::get_icon("MiniVector2Array", "EditorIcons"),
+ Control::get_icon("MiniVector3Array", "EditorIcons"),
+ Control::get_icon("MiniColorArray", "EditorIcons")
};
-
- for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
- if (E->get().usage==PROPERTY_USAGE_CATEGORY) {
- if (category && category->get_children()==NULL) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
+ if (E->get().usage == PROPERTY_USAGE_CATEGORY) {
+ if (category && category->get_children() == NULL) {
memdelete(category); //old category was unused
}
category = search_options->create_item(root);
- category->set_text(0,E->get().name);
- category->set_selectable(0,false);
+ category->set_text(0, E->get().name);
+ category->set_selectable(0, false);
Ref<Texture> icon;
- if (E->get().name=="Script Variables") {
- icon=get_icon("Script","EditorIcons");
- } else if (has_icon(E->get().name,"EditorIcons")) {
- icon=get_icon(E->get().name,"EditorIcons");
+ if (E->get().name == "Script Variables") {
+ icon = get_icon("Script", "EditorIcons");
+ } else if (has_icon(E->get().name, "EditorIcons")) {
+ icon = get_icon(E->get().name, "EditorIcons");
} else {
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
}
- category->set_icon(0,icon);
+ category->set_icon(0, icon);
continue;
}
- if (!(E->get().usage&PROPERTY_USAGE_EDITOR))
+ if (!(E->get().usage & PROPERTY_USAGE_EDITOR))
continue;
- if (search_box->get_text()!=String() && E->get().name.find(search_box->get_text())==-1)
+ if (search_box->get_text() != String() && E->get().name.find(search_box->get_text()) == -1)
continue;
- TreeItem *item = search_options->create_item(category?category:root);
- item->set_text(0,E->get().name);
- item->set_metadata(0,E->get().name);
- item->set_icon(0,type_icons[E->get().type]);
+ TreeItem *item = search_options->create_item(category ? category : root);
+ item->set_text(0, E->get().name);
+ item->set_metadata(0, E->get().name);
+ item->set_icon(0, type_icons[E->get().type]);
- if (!found && search_box->get_text()!=String() && E->get().name.find(search_box->get_text())!=-1) {
+ if (!found && search_box->get_text() != String() && E->get().name.find(search_box->get_text()) != -1) {
item->select(0);
- found=true;
+ found = true;
}
- item->set_selectable(0,true);
+ item->set_selectable(0, true);
}
- if (category && category->get_children()==NULL) {
+ if (category && category->get_children() == NULL) {
memdelete(category); //old category was unused
}
} else {
List<MethodInfo> methods;
- if (type!=Variant::NIL) {
+ if (type != Variant::NIL) {
Variant v;
Variant::CallError ce;
- v=Variant::construct(type,NULL,0,ce);
+ v = Variant::construct(type, NULL, 0, ce);
v.get_method_list(&methods);
} else {
-
Object *obj = ObjectDB::get_instance(script);
if (obj && obj->cast_to<Script>()) {
@@ -219,116 +211,107 @@ void PropertySelector::_update_search() {
obj->cast_to<Script>()->get_script_method_list(&methods);
}
- StringName base=base_type;
- while(base) {
- methods.push_back(MethodInfo("*"+String(base)));
- ClassDB::get_method_list(base,&methods,true);
- base=ClassDB::get_parent_class(base);
+ StringName base = base_type;
+ while (base) {
+ methods.push_back(MethodInfo("*" + String(base)));
+ ClassDB::get_method_list(base, &methods, true);
+ base = ClassDB::get_parent_class(base);
}
-
}
- TreeItem *category=NULL;
+ TreeItem *category = NULL;
- bool found=false;
- bool script_methods=false;
+ bool found = false;
+ bool script_methods = false;
- for (List<MethodInfo>::Element *E=methods.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
if (E->get().name.begins_with("*")) {
- if (category && category->get_children()==NULL) {
+ if (category && category->get_children() == NULL) {
memdelete(category); //old category was unused
}
category = search_options->create_item(root);
- category->set_text(0,E->get().name.replace_first("*",""));
- category->set_selectable(0,false);
+ category->set_text(0, E->get().name.replace_first("*", ""));
+ category->set_selectable(0, false);
Ref<Texture> icon;
- script_methods=false;
- if (E->get().name=="*Script Methods") {
- icon=get_icon("Script","EditorIcons");
- script_methods=true;
- } else if (has_icon(E->get().name,"EditorIcons")) {
- icon=get_icon(E->get().name,"EditorIcons");
+ script_methods = false;
+ if (E->get().name == "*Script Methods") {
+ icon = get_icon("Script", "EditorIcons");
+ script_methods = true;
+ } else if (has_icon(E->get().name, "EditorIcons")) {
+ icon = get_icon(E->get().name, "EditorIcons");
} else {
- icon=get_icon("Object","EditorIcons");
+ icon = get_icon("Object", "EditorIcons");
}
- category->set_icon(0,icon);
+ category->set_icon(0, icon);
continue;
}
- String name = E->get().name.get_slice(":",0);
- if (!script_methods && name.begins_with("_") && !(E->get().flags&METHOD_FLAG_VIRTUAL))
+ String name = E->get().name.get_slice(":", 0);
+ if (!script_methods && name.begins_with("_") && !(E->get().flags & METHOD_FLAG_VIRTUAL))
continue;
- if (search_box->get_text()!=String() && name.find(search_box->get_text())==-1)
+ if (search_box->get_text() != String() && name.find(search_box->get_text()) == -1)
continue;
- TreeItem *item = search_options->create_item(category?category:root);
+ TreeItem *item = search_options->create_item(category ? category : root);
- MethodInfo mi=E->get();
+ MethodInfo mi = E->get();
String desc;
- if (mi.name.find(":")!=-1) {
- desc=mi.name.get_slice(":",1)+" ";
- mi.name=mi.name.get_slice(":",0);
- } else if (mi.return_val.type!=Variant::NIL)
- desc=Variant::get_type_name(mi.return_val.type);
+ if (mi.name.find(":") != -1) {
+ desc = mi.name.get_slice(":", 1) + " ";
+ mi.name = mi.name.get_slice(":", 0);
+ } else if (mi.return_val.type != Variant::NIL)
+ desc = Variant::get_type_name(mi.return_val.type);
else
- desc="void ";
-
-
+ desc = "void ";
- desc+=" "+mi.name+" ( ";
+ desc += " " + mi.name + " ( ";
- for(int i=0;i<mi.arguments.size();i++) {
+ for (int i = 0; i < mi.arguments.size(); i++) {
- if (i>0)
- desc+=", ";
+ if (i > 0)
+ desc += ", ";
- if (mi.arguments[i].type==Variant::NIL)
- desc+="var ";
- else if (mi.arguments[i].name.find(":")!=-1) {
- desc+=mi.arguments[i].name.get_slice(":",1)+" ";
- mi.arguments[i].name=mi.arguments[i].name.get_slice(":",0);
+ if (mi.arguments[i].type == Variant::NIL)
+ desc += "var ";
+ else if (mi.arguments[i].name.find(":") != -1) {
+ desc += mi.arguments[i].name.get_slice(":", 1) + " ";
+ mi.arguments[i].name = mi.arguments[i].name.get_slice(":", 0);
} else
- desc+=Variant::get_type_name(mi.arguments[i].type)+" ";
-
- desc+=mi.arguments[i].name;
+ desc += Variant::get_type_name(mi.arguments[i].type) + " ";
+ desc += mi.arguments[i].name;
}
- desc+=" )";
+ desc += " )";
- item->set_text(0,desc);
- item->set_metadata(0,name);
- item->set_selectable(0,true);
+ item->set_text(0, desc);
+ item->set_metadata(0, name);
+ item->set_selectable(0, true);
- if (!found && search_box->get_text()!=String() && name.find(search_box->get_text())!=-1) {
+ if (!found && search_box->get_text() != String() && name.find(search_box->get_text()) != -1) {
item->select(0);
- found=true;
+ found = true;
}
-
}
- if (category && category->get_children()==NULL) {
+ if (category && category->get_children() == NULL) {
memdelete(category); //old category was unused
}
-
}
- get_ok()->set_disabled(root->get_children()==NULL);
-
+ get_ok()->set_disabled(root->get_children() == NULL);
}
-
-
void PropertySelector::_confirmed() {
TreeItem *ti = search_options->get_selected();
if (!ti)
return;
- emit_signal("selected",ti->get_metadata(0));
+ emit_signal("selected", ti->get_metadata(0));
hide();
}
@@ -336,125 +319,112 @@ void PropertySelector::_item_selected() {
help_bit->set_text("");
- TreeItem *item=search_options->get_selected();
+ TreeItem *item = search_options->get_selected();
if (!item)
return;
String name = item->get_metadata(0);
String class_type;
- if (properties && type==Variant::INPUT_EVENT) {
-
- switch(event_type) {
- case InputEvent::NONE: class_type="InputEvent"; break;
- case InputEvent::KEY: class_type="InputEventKey"; break;
- case InputEvent::MOUSE_MOTION: class_type="InputEventMouseMotion"; break;
- case InputEvent::MOUSE_BUTTON: class_type="InputEventMouseButton"; break;
- case InputEvent::JOYPAD_MOTION: class_type="InputEventJoypadMotion"; break;
- case InputEvent::JOYPAD_BUTTON: class_type="InputEventJoypadButton"; break;
- case InputEvent::SCREEN_TOUCH: class_type="InputEventScreenTouch"; break;
- case InputEvent::SCREEN_DRAG: class_type="InputEventScreenDrag"; break;
- case InputEvent::ACTION: class_type="InputEventAction"; break;
+ if (properties && type == Variant::INPUT_EVENT) {
+
+ switch (event_type) {
+ case InputEvent::NONE: class_type = "InputEvent"; break;
+ case InputEvent::KEY: class_type = "InputEventKey"; break;
+ case InputEvent::MOUSE_MOTION: class_type = "InputEventMouseMotion"; break;
+ case InputEvent::MOUSE_BUTTON: class_type = "InputEventMouseButton"; break;
+ case InputEvent::JOYPAD_MOTION: class_type = "InputEventJoypadMotion"; break;
+ case InputEvent::JOYPAD_BUTTON: class_type = "InputEventJoypadButton"; break;
+ case InputEvent::SCREEN_TOUCH: class_type = "InputEventScreenTouch"; break;
+ case InputEvent::SCREEN_DRAG: class_type = "InputEventScreenDrag"; break;
+ case InputEvent::ACTION: class_type = "InputEventAction"; break;
default: {}
}
} else if (type) {
- class_type=Variant::get_type_name(type);
+ class_type = Variant::get_type_name(type);
} else {
- class_type=base_type;
+ class_type = base_type;
}
- DocData *dd=EditorHelp::get_doc_data();
+ DocData *dd = EditorHelp::get_doc_data();
String text;
-
if (properties) {
- String at_class=class_type;
-
-
+ String at_class = class_type;
- while(at_class!=String()) {
+ while (at_class != String()) {
-
- Map<String,DocData::ClassDoc>::Element *E=dd->class_list.find(at_class);
+ 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;
+ for (int i = 0; i < E->get().properties.size(); i++) {
+ if (E->get().properties[i].name == name) {
+ text = E->get().properties[i].description;
}
}
}
- at_class=ClassDB::get_parent_class(at_class);
+ at_class = ClassDB::get_parent_class(at_class);
}
- if (text==String()) {
+ if (text == String()) {
StringName setter;
StringName type;
- if (ClassDB::get_setter_and_type_for_property(class_type,name,type,setter)) {
- Map<String,DocData::ClassDoc>::Element *E=dd->class_list.find(type);
+ if (ClassDB::get_setter_and_type_for_property(class_type, name, type, setter)) {
+ Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(type);
if (E) {
- for(int i=0;i<E->get().methods.size();i++) {
- if (E->get().methods[i].name==setter.operator String()) {
- text=E->get().methods[i].description;
+ for (int i = 0; i < E->get().methods.size(); i++) {
+ if (E->get().methods[i].name == setter.operator String()) {
+ text = E->get().methods[i].description;
}
}
}
-
-
}
}
} else {
+ String at_class = class_type;
- String at_class=class_type;
-
- while(at_class!=String()) {
+ while (at_class != String()) {
- Map<String,DocData::ClassDoc>::Element *E=dd->class_list.find(at_class);
+ Map<String, DocData::ClassDoc>::Element *E = dd->class_list.find(at_class);
if (E) {
- for(int i=0;i<E->get().methods.size();i++) {
- if (E->get().methods[i].name==name) {
- text=E->get().methods[i].description;
+ for (int i = 0; i < E->get().methods.size(); i++) {
+ if (E->get().methods[i].name == name) {
+ text = E->get().methods[i].description;
}
}
}
- at_class=ClassDB::get_parent_class(at_class);
+ at_class = ClassDB::get_parent_class(at_class);
}
}
-
- if (text==String())
+ if (text == String())
return;
help_bit->set_text(text);
-
}
-
void PropertySelector::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
- connect("confirmed",this,"_confirmed");
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ connect("confirmed", this, "_confirmed");
}
}
+void PropertySelector::select_method_from_base_type(const String &p_base, const String &p_current) {
-
-void PropertySelector::select_method_from_base_type(const String& p_base,const String& p_current) {
-
- base_type=p_base;
- selected=p_current;
- type=Variant::NIL;
- script=0;
- properties=false;
- instance=NULL;
+ base_type = p_base;
+ selected = p_current;
+ type = Variant::NIL;
+ script = 0;
+ properties = false;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
@@ -462,70 +432,65 @@ void PropertySelector::select_method_from_base_type(const String& p_base,const S
_update_search();
}
-void PropertySelector::select_method_from_script(const Ref<Script>& p_script,const String& p_current){
+void PropertySelector::select_method_from_script(const Ref<Script> &p_script, const String &p_current) {
- ERR_FAIL_COND( p_script.is_null() );
- base_type=p_script->get_instance_base_type();
- selected=p_current;
- type=Variant::NIL;
- script=p_script->get_instance_ID();
- properties=false;
- instance=NULL;
+ ERR_FAIL_COND(p_script.is_null());
+ base_type = p_script->get_instance_base_type();
+ selected = p_current;
+ type = Variant::NIL;
+ script = p_script->get_instance_ID();
+ properties = false;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
-void PropertySelector::select_method_from_basic_type(Variant::Type p_type, const String &p_current){
+void PropertySelector::select_method_from_basic_type(Variant::Type p_type, const String &p_current) {
- ERR_FAIL_COND(p_type==Variant::NIL);
- base_type="";
- selected=p_current;
- type=p_type;
- script=0;
- properties=false;
- instance=NULL;
+ ERR_FAIL_COND(p_type == Variant::NIL);
+ base_type = "";
+ selected = p_current;
+ type = p_type;
+ script = 0;
+ properties = false;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
-void PropertySelector::select_method_from_instance(Object* p_instance, const String &p_current){
-
+void PropertySelector::select_method_from_instance(Object *p_instance, const String &p_current) {
- base_type=p_instance->get_class();
- selected=p_current;
- type=Variant::NIL;
- script=0;
+ base_type = p_instance->get_class();
+ selected = p_current;
+ type = Variant::NIL;
+ script = 0;
{
Ref<Script> scr = p_instance->get_script();
if (scr.is_valid())
- script=scr->get_instance_ID();
+ script = scr->get_instance_ID();
}
- properties=false;
- instance=NULL;
+ properties = false;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
+void PropertySelector::select_property_from_base_type(const String &p_base, const String &p_current) {
-void PropertySelector::select_property_from_base_type(const String& p_base,const String& p_current) {
-
- base_type=p_base;
- selected=p_current;
- type=Variant::NIL;
- script=0;
- properties=true;
- instance=NULL;
+ base_type = p_base;
+ selected = p_current;
+ type = Variant::NIL;
+ script = 0;
+ properties = true;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
@@ -533,94 +498,85 @@ void PropertySelector::select_property_from_base_type(const String& p_base,const
_update_search();
}
-void PropertySelector::select_property_from_script(const Ref<Script>& p_script,const String& p_current){
+void PropertySelector::select_property_from_script(const Ref<Script> &p_script, const String &p_current) {
- ERR_FAIL_COND( p_script.is_null() );
+ ERR_FAIL_COND(p_script.is_null());
- base_type=p_script->get_instance_base_type();
- selected=p_current;
- type=Variant::NIL;
- script=p_script->get_instance_ID();
- properties=true;
- instance=NULL;
+ base_type = p_script->get_instance_base_type();
+ selected = p_current;
+ type = Variant::NIL;
+ script = p_script->get_instance_ID();
+ properties = true;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
-void PropertySelector::select_property_from_basic_type(Variant::Type p_type, InputEvent::Type p_event_type, const String &p_current){
+void PropertySelector::select_property_from_basic_type(Variant::Type p_type, InputEvent::Type p_event_type, const String &p_current) {
- ERR_FAIL_COND(p_type==Variant::NIL);
- base_type="";
- selected=p_current;
- type=p_type;
- event_type=p_event_type;
- script=0;
- properties=true;
- instance=NULL;
+ ERR_FAIL_COND(p_type == Variant::NIL);
+ base_type = "";
+ selected = p_current;
+ type = p_type;
+ event_type = p_event_type;
+ script = 0;
+ properties = true;
+ instance = NULL;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
-void PropertySelector::select_property_from_instance(Object* p_instance, const String &p_current){
-
+void PropertySelector::select_property_from_instance(Object *p_instance, const String &p_current) {
- base_type="";
- selected=p_current;
- type=Variant::NIL;
- script=0;
- properties=true;
- instance=p_instance;
+ base_type = "";
+ selected = p_current;
+ type = Variant::NIL;
+ script = 0;
+ properties = true;
+ instance = p_instance;
popup_centered_ratio(0.6);
search_box->set_text("");
search_box->grab_focus();
_update_search();
-
}
void PropertySelector::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_changed"),&PropertySelector::_text_changed);
- ClassDB::bind_method(D_METHOD("_confirmed"),&PropertySelector::_confirmed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&PropertySelector::_sbox_input);
- ClassDB::bind_method(D_METHOD("_item_selected"),&PropertySelector::_item_selected);
-
- ADD_SIGNAL(MethodInfo("selected",PropertyInfo(Variant::STRING,"name")));
+ ClassDB::bind_method(D_METHOD("_text_changed"), &PropertySelector::_text_changed);
+ ClassDB::bind_method(D_METHOD("_confirmed"), &PropertySelector::_confirmed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &PropertySelector::_sbox_input);
+ ClassDB::bind_method(D_METHOD("_item_selected"), &PropertySelector::_item_selected);
+ ADD_SIGNAL(MethodInfo("selected", PropertyInfo(Variant::STRING, "name")));
}
-
PropertySelector::PropertySelector() {
-
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
- search_box = memnew( LineEdit );
- vbc->add_margin_child(TTR("Search:"),search_box);
- search_box->connect("text_changed",this,"_text_changed");
- search_box->connect("gui_input",this,"_sbox_input");
- search_options = memnew( Tree );
- vbc->add_margin_child(TTR("Matches:"),search_options,true);
+ search_box = memnew(LineEdit);
+ vbc->add_margin_child(TTR("Search:"), search_box);
+ search_box->connect("text_changed", this, "_text_changed");
+ search_box->connect("gui_input", this, "_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);
register_text_enter(search_box);
set_hide_on_ok(false);
- search_options->connect("item_activated",this,"_confirmed");
- search_options->connect("cell_selected",this,"_item_selected");
+ search_options->connect("item_activated", this, "_confirmed");
+ search_options->connect("cell_selected", this, "_item_selected");
search_options->set_hide_root(true);
search_options->set_hide_folding(true);
- help_bit = memnew( EditorHelpBit );
- vbc->add_margin_child(TTR("Description:"),help_bit);
- help_bit->connect("request_hide",this,"_closed");
-
-
+ help_bit = memnew(EditorHelpBit);
+ vbc->add_margin_child(TTR("Description:"), help_bit);
+ help_bit->connect("request_hide", this, "_closed");
}
diff --git a/editor/property_selector.h b/editor/property_selector.h
index c2ce996be2..c6903ee680 100644
--- a/editor/property_selector.h
+++ b/editor/property_selector.h
@@ -30,22 +30,21 @@
#define PROPERTYSELECTOR_H
#include "editor/property_editor.h"
-#include "scene/gui/rich_text_label.h"
#include "editor_help.h"
+#include "scene/gui/rich_text_label.h"
class PropertySelector : public ConfirmationDialog {
- GDCLASS(PropertySelector,ConfirmationDialog )
-
+ GDCLASS(PropertySelector, ConfirmationDialog)
LineEdit *search_box;
Tree *search_options;
void _update_search();
- void _sbox_input(const InputEvent& p_ie);
+ void _sbox_input(const InputEvent &p_ie);
void _confirmed();
- void _text_changed(const String& p_newtext);
+ void _text_changed(const String &p_newtext);
EditorHelpBit *help_bit;
@@ -58,24 +57,21 @@ class PropertySelector : public ConfirmationDialog {
Object *instance;
void _item_selected();
+
protected:
void _notification(int p_what);
static void _bind_methods();
-
-
public:
-
-
- void select_method_from_base_type(const String& p_base,const String& p_current="");
- void select_method_from_script(const Ref<Script>& p_script,const String& p_current="");
- void select_method_from_basic_type(Variant::Type p_type,const String& p_current="");
- void select_method_from_instance(Object* p_instance, const String &p_current="");
-
- void select_property_from_base_type(const String& p_base,const String& p_current="");
- void select_property_from_script(const Ref<Script>& p_script,const String& p_current="");
- void select_property_from_basic_type(Variant::Type p_type,InputEvent::Type p_event_type,const String& p_current="");
- void select_property_from_instance(Object* p_instance, const String &p_current="");
+ void select_method_from_base_type(const String &p_base, const String &p_current = "");
+ void select_method_from_script(const Ref<Script> &p_script, const String &p_current = "");
+ void select_method_from_basic_type(Variant::Type p_type, const String &p_current = "");
+ void select_method_from_instance(Object *p_instance, const String &p_current = "");
+
+ void select_property_from_base_type(const String &p_base, const String &p_current = "");
+ void select_property_from_script(const Ref<Script> &p_script, const String &p_current = "");
+ void select_property_from_basic_type(Variant::Type p_type, InputEvent::Type p_event_type, const String &p_current = "");
+ void select_property_from_instance(Object *p_instance, const String &p_current = "");
PropertySelector();
};
diff --git a/editor/pvrtc_compress.cpp b/editor/pvrtc_compress.cpp
index b130f6c773..4b4e74cd62 100644
--- a/editor/pvrtc_compress.cpp
+++ b/editor/pvrtc_compress.cpp
@@ -29,21 +29,21 @@
#include "pvrtc_compress.h"
#include "editor_settings.h"
-#include "scene/resources/texture.h"
-#include "io/resource_saver.h"
#include "io/resource_loader.h"
-#include "os/os.h"
+#include "io/resource_saver.h"
#include "os/file_access.h"
+#include "os/os.h"
+#include "scene/resources/texture.h"
-static void (*_base_image_compress_pvrtc2_func)(Image *)=NULL;
-static void (*_base_image_compress_pvrtc4_func)(Image *)=NULL;
+static void (*_base_image_compress_pvrtc2_func)(Image *) = NULL;
+static void (*_base_image_compress_pvrtc4_func)(Image *) = NULL;
-static void _compress_image(Image::CompressMode p_mode,Image *p_image) {
+static void _compress_image(Image::CompressMode p_mode, Image *p_image) {
String ttpath = EditorSettings::get_singleton()->get("filesystem/import/pvrtc_texture_tool");
- if (ttpath.strip_edges()=="" || !FileAccess::exists(ttpath)) {
- switch(p_mode) {
+ if (ttpath.strip_edges() == "" || !FileAccess::exists(ttpath)) {
+ switch (p_mode) {
case Image::COMPRESS_PVRTC2:
if (_base_image_compress_pvrtc2_func)
@@ -51,37 +51,34 @@ static void _compress_image(Image::CompressMode p_mode,Image *p_image) {
else if (_base_image_compress_pvrtc4_func)
_base_image_compress_pvrtc4_func(p_image);
- break;
+ break;
case Image::COMPRESS_PVRTC4:
if (_base_image_compress_pvrtc4_func)
_base_image_compress_pvrtc4_func(p_image);
- break;
+ break;
default: ERR_FAIL();
-
}
return;
}
String spath = EditorSettings::get_singleton()->get_settings_path();
-
List<String> args;
- String src_img = spath+"/"+"_tmp_src_img.png";
- String dst_img = spath+"/"+"_tmp_dst_img.pvr";
+ String src_img = spath + "/" + "_tmp_src_img.png";
+ String dst_img = spath + "/" + "_tmp_dst_img.pvr";
args.push_back("-i");
args.push_back(src_img);
args.push_back("-o");
args.push_back(dst_img);
args.push_back("-f");
- switch(p_mode) {
+ switch (p_mode) {
case Image::COMPRESS_PVRTC2: args.push_back("PVRTC2"); break;
case Image::COMPRESS_PVRTC4: args.push_back("PVRTC4"); break;
case Image::COMPRESS_ETC: args.push_back("ETC"); break;
default: ERR_FAIL();
-
}
if (EditorSettings::get_singleton()->get("filesystem/import/pvrtc_fast_conversion").operator bool()) {
@@ -90,45 +87,43 @@ static void _compress_image(Image::CompressMode p_mode,Image *p_image) {
if (p_image->has_mipmaps())
args.push_back("-m");
- Ref<ImageTexture> t = memnew( ImageTexture );
- t->create_from_image(*p_image,0);
- ResourceSaver::save(src_img,t);
+ Ref<ImageTexture> t = memnew(ImageTexture);
+ t->create_from_image(*p_image, 0);
+ ResourceSaver::save(src_img, t);
- Error err = OS::get_singleton()->execute(ttpath,args,true);
- ERR_EXPLAIN(TTR("Could not execute PVRTC tool:")+" "+ttpath);
- ERR_FAIL_COND(err!=OK);
+ Error err = OS::get_singleton()->execute(ttpath, args, true);
+ ERR_EXPLAIN(TTR("Could not execute PVRTC tool:") + " " + ttpath);
+ ERR_FAIL_COND(err != OK);
+ t = ResourceLoader::load(dst_img, "Texture");
- t=ResourceLoader::load(dst_img,"Texture");
-
- ERR_EXPLAIN(TTR("Can't load back converted image using PVRTC tool:")+" "+dst_img);
+ ERR_EXPLAIN(TTR("Can't load back converted image using PVRTC tool:") + " " + dst_img);
ERR_FAIL_COND(t.is_null());
- *p_image=t->get_data();
+ *p_image = t->get_data();
}
-
static void _compress_pvrtc2(Image *p_image) {
- _compress_image(Image::COMPRESS_PVRTC2,p_image);
+ _compress_image(Image::COMPRESS_PVRTC2, p_image);
}
static void _compress_pvrtc4(Image *p_image) {
- _compress_image(Image::COMPRESS_PVRTC4,p_image);
+ _compress_image(Image::COMPRESS_PVRTC4, p_image);
}
static void _compress_etc(Image *p_image) {
- _compress_image(Image::COMPRESS_ETC,p_image);
+ _compress_image(Image::COMPRESS_ETC, p_image);
}
void _pvrtc_register_compressors() {
- _base_image_compress_pvrtc2_func=Image::_image_compress_pvrtc2_func;
- _base_image_compress_pvrtc4_func=Image::_image_compress_pvrtc4_func;
+ _base_image_compress_pvrtc2_func = Image::_image_compress_pvrtc2_func;
+ _base_image_compress_pvrtc4_func = Image::_image_compress_pvrtc4_func;
- Image::_image_compress_pvrtc2_func=_compress_pvrtc2;
- Image::_image_compress_pvrtc4_func=_compress_pvrtc4;
+ Image::_image_compress_pvrtc2_func = _compress_pvrtc2;
+ Image::_image_compress_pvrtc4_func = _compress_pvrtc4;
//Image::_image_compress_etc_func=_compress_etc; //use the built in one for ETC
}
diff --git a/editor/pvrtc_compress.h b/editor/pvrtc_compress.h
index 4ba29026c5..3699a731a0 100644
--- a/editor/pvrtc_compress.h
+++ b/editor/pvrtc_compress.h
@@ -33,5 +33,4 @@
void _pvrtc_register_compressors();
-
#endif // PVRTC_COMPRESS_H
diff --git a/editor/quick_open.cpp b/editor/quick_open.cpp
index f43189a7bf..bc6b0ad9f3 100644
--- a/editor/quick_open.cpp
+++ b/editor/quick_open.cpp
@@ -32,7 +32,7 @@
void EditorQuickOpen::popup(const StringName &p_base, bool p_enable_multi, bool p_add_dirs, bool p_dontclear) {
- add_directories=p_add_dirs;
+ add_directories = p_add_dirs;
popup_centered_ratio(0.6);
if (p_dontclear)
search_box->select_all();
@@ -43,7 +43,7 @@ void EditorQuickOpen::popup(const StringName &p_base, bool p_enable_multi, bool
else
search_options->set_select_mode(Tree::SELECT_SINGLE);
search_box->grab_focus();
- base_type=p_base;
+ base_type = p_base;
_update_search();
}
@@ -60,10 +60,10 @@ Vector<String> EditorQuickOpen::get_selected_files() const {
Vector<String> files;
- TreeItem* item = search_options->get_next_selected(search_options->get_root());
+ TreeItem *item = search_options->get_next_selected(search_options->get_root());
while (item) {
- files.push_back("res://"+item->get_text(0));
+ files.push_back("res://" + item->get_text(0));
item = search_options->get_next_selected(item);
}
@@ -71,16 +71,16 @@ Vector<String> EditorQuickOpen::get_selected_files() const {
return files;
}
-void EditorQuickOpen::_text_changed(const String& p_newtext) {
+void EditorQuickOpen::_text_changed(const String &p_newtext) {
_update_search();
}
-void EditorQuickOpen::_sbox_input(const InputEvent& p_ie) {
+void EditorQuickOpen::_sbox_input(const InputEvent &p_ie) {
- if (p_ie.type==InputEvent::KEY) {
+ if (p_ie.type == InputEvent::KEY) {
- switch(p_ie.key.scancode) {
+ switch (p_ie.key.scancode) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
@@ -106,7 +106,6 @@ void EditorQuickOpen::_sbox_input(const InputEvent& p_ie) {
} break;
}
}
-
}
float EditorQuickOpen::_path_cmp(String search, String path) const {
@@ -120,10 +119,10 @@ float EditorQuickOpen::_path_cmp(String search, String path) const {
return path.to_lower().similarity(search.to_lower());
}
-void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< String, Ref<Texture> > > &list) {
+void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector<Pair<String, Ref<Texture> > > &list) {
if (!add_directories) {
- for(int i=0;i<efsd->get_subdir_count();i++) {
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
@@ -134,11 +133,11 @@ void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< S
if (add_directories) {
String path = efsd->get_path();
if (!path.ends_with("/"))
- path+="/";
- if (path!="res://") {
- path=path.substr(6,path.length());
+ path += "/";
+ if (path != "res://") {
+ path = path.substr(6, path.length());
if (search_text.is_subsequence_ofi(path)) {
- Pair< String, Ref<Texture> > pair;
+ Pair<String, Ref<Texture> > pair;
pair.first = path;
pair.second = get_icon("folder", "FileDialog");
@@ -161,13 +160,13 @@ void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< S
}
}
}
- for(int i=0;i<efsd->get_file_count();i++) {
+ for (int i = 0; i < efsd->get_file_count(); i++) {
String file = efsd->get_file_path(i);
- file=file.substr(6,file.length());
+ file = file.substr(6, file.length());
- if (ClassDB::is_parent_class(efsd->get_file_type(i),base_type) && (search_text.is_subsequence_ofi(file))) {
- Pair< String, Ref<Texture> > pair;
+ if (ClassDB::is_parent_class(efsd->get_file_type(i), base_type) && (search_text.is_subsequence_ofi(file))) {
+ Pair<String, Ref<Texture> > pair;
pair.first = file;
pair.second = get_icon((has_icon(efsd->get_file_type(i), ei) ? efsd->get_file_type(i) : ot), ei);
@@ -191,14 +190,12 @@ void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< S
}
}
-
if (add_directories) {
- for(int i=0;i<efsd->get_subdir_count();i++) {
+ for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
-
}
void EditorQuickOpen::_update_search() {
@@ -206,7 +203,7 @@ void EditorQuickOpen::_update_search() {
search_options->clear();
TreeItem *root = search_options->create_item();
EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem();
- Vector< Pair< String, Ref<Texture> > > list;
+ Vector<Pair<String, Ref<Texture> > > list;
_parse_fs(efsd, list);
@@ -223,8 +220,7 @@ void EditorQuickOpen::_update_search() {
ti->set_as_cursor(0);
}
- get_ok()->set_disabled(root->get_children()==NULL);
-
+ get_ok()->set_disabled(root->get_children() == NULL);
}
void EditorQuickOpen::_confirmed() {
@@ -238,13 +234,12 @@ void EditorQuickOpen::_confirmed() {
void EditorQuickOpen::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- connect("confirmed",this,"_confirmed");
+ connect("confirmed", this, "_confirmed");
}
}
-
StringName EditorQuickOpen::get_base_type() const {
return base_type;
@@ -252,34 +247,31 @@ StringName EditorQuickOpen::get_base_type() const {
void EditorQuickOpen::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_text_changed"),&EditorQuickOpen::_text_changed);
- ClassDB::bind_method(D_METHOD("_confirmed"),&EditorQuickOpen::_confirmed);
- ClassDB::bind_method(D_METHOD("_sbox_input"),&EditorQuickOpen::_sbox_input);
+ ClassDB::bind_method(D_METHOD("_text_changed"), &EditorQuickOpen::_text_changed);
+ ClassDB::bind_method(D_METHOD("_confirmed"), &EditorQuickOpen::_confirmed);
+ ClassDB::bind_method(D_METHOD("_sbox_input"), &EditorQuickOpen::_sbox_input);
ADD_SIGNAL(MethodInfo("quick_open"));
-
}
-
EditorQuickOpen::EditorQuickOpen() {
-
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
- search_box = memnew( LineEdit );
- vbc->add_margin_child(TTR("Search:"),search_box);
- search_box->connect("text_changed",this,"_text_changed");
- search_box->connect("gui_input",this,"_sbox_input");
- search_options = memnew( Tree );
- vbc->add_margin_child(TTR("Matches:"),search_options,true);
+ search_box = memnew(LineEdit);
+ vbc->add_margin_child(TTR("Search:"), search_box);
+ search_box->connect("text_changed", this, "_text_changed");
+ search_box->connect("gui_input", this, "_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);
register_text_enter(search_box);
set_hide_on_ok(false);
- search_options->connect("item_activated",this,"_confirmed");
+ search_options->connect("item_activated", this, "_confirmed");
search_options->set_hide_root(true);
- ei="EditorIcons";
- ot="Object";
- add_directories=false;
+ ei = "EditorIcons";
+ ot = "Object";
+ add_directories = false;
}
diff --git a/editor/quick_open.h b/editor/quick_open.h
index ef91d910b1..bcb0842c49 100644
--- a/editor/quick_open.h
+++ b/editor/quick_open.h
@@ -29,13 +29,13 @@
#ifndef EDITOR_QUICK_OPEN_H
#define EDITOR_QUICK_OPEN_H
-#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
#include "editor_file_system.h"
#include "pair.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/tree.h"
class EditorQuickOpen : public ConfirmationDialog {
- GDCLASS(EditorQuickOpen,ConfirmationDialog )
+ GDCLASS(EditorQuickOpen, ConfirmationDialog)
LineEdit *search_box;
Tree *search_options;
@@ -44,29 +44,26 @@ class EditorQuickOpen : public ConfirmationDialog {
StringName ot;
bool add_directories;
-
void _update_search();
- void _sbox_input(const InputEvent& p_ie);
- void _parse_fs(EditorFileSystemDirectory *efsd, Vector< Pair< String,Ref <Texture> > > &list);
+ void _sbox_input(const InputEvent &p_ie);
+ void _parse_fs(EditorFileSystemDirectory *efsd, Vector<Pair<String, Ref<Texture> > > &list);
float _path_cmp(String search, String path) const;
-
void _confirmed();
- void _text_changed(const String& p_newtext);
+ void _text_changed(const String &p_newtext);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
StringName get_base_type() const;
String get_selected() const;
Vector<String> get_selected_files() const;
- void popup(const StringName& p_base,bool p_enable_multi=false,bool p_add_dirs=false,bool p_dontclear=false);
+ void popup(const StringName &p_base, bool p_enable_multi = false, bool p_add_dirs = false, bool p_dontclear = false);
EditorQuickOpen();
};
diff --git a/editor/register_exporters.h b/editor/register_exporters.h
index 30ec522a00..d6afd1459a 100644
--- a/editor/register_exporters.h
+++ b/editor/register_exporters.h
@@ -29,7 +29,6 @@
#ifndef REGISTER_EXPORTERS_H
#define REGISTER_EXPORTERS_H
-
void register_exporters();
#endif
diff --git a/editor/reparent_dialog.cpp b/editor/reparent_dialog.cpp
index c5b74d9006..3305c1642a 100644
--- a/editor/reparent_dialog.cpp
+++ b/editor/reparent_dialog.cpp
@@ -28,23 +28,23 @@
/*************************************************************************/
#include "reparent_dialog.h"
-#include "scene/gui/label.h"
-#include "scene/gui/box_container.h"
#include "print_string.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/label.h"
void ReparentDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- connect("confirmed", this,"_reparent");
+ connect("confirmed", this, "_reparent");
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
- disconnect("confirmed", this,"_reparent");
+ disconnect("confirmed", this, "_reparent");
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
@@ -54,67 +54,60 @@ void ReparentDialog::_notification(int p_what) {
void ReparentDialog::_cancel() {
hide();
-
}
void ReparentDialog::_reparent() {
if (tree->get_selected()) {
- emit_signal("reparent",tree->get_selected()->get_path(),keep_transform->is_pressed());
+ emit_signal("reparent", tree->get_selected()->get_path(), keep_transform->is_pressed());
hide();
}
}
-void ReparentDialog::set_current(const Set<Node*>& p_selection) {
+void ReparentDialog::set_current(const Set<Node *> &p_selection) {
- tree->set_marked(p_selection,false,false);
+ tree->set_marked(p_selection, false, false);
//tree->set_selected(p_node->get_parent());
}
void ReparentDialog::_bind_methods() {
- ClassDB::bind_method("_reparent",&ReparentDialog::_reparent);
- ClassDB::bind_method("_cancel",&ReparentDialog::_cancel);
+ ClassDB::bind_method("_reparent", &ReparentDialog::_reparent);
+ ClassDB::bind_method("_cancel", &ReparentDialog::_cancel);
- ADD_SIGNAL( MethodInfo("reparent",PropertyInfo(Variant::NODE_PATH,"path"),PropertyInfo(Variant::BOOL,"keep_global_xform")));
+ ADD_SIGNAL(MethodInfo("reparent", PropertyInfo(Variant::NODE_PATH, "path"), PropertyInfo(Variant::BOOL, "keep_global_xform")));
}
-
ReparentDialog::ReparentDialog() {
set_title(TTR("Reparent Node"));
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
- tree = memnew( SceneTreeEditor(false) );
+ tree = memnew(SceneTreeEditor(false));
tree->set_show_enabled_subscene(true);
- vbc->add_margin_child(TTR("Reparent Location (Select new Parent):"),tree,true);
+ vbc->add_margin_child(TTR("Reparent Location (Select new Parent):"), tree, true);
- tree->get_scene_tree()->connect("item_activated",this,"_reparent");
+ tree->get_scene_tree()->connect("item_activated", this, "_reparent");
//Label *label = memnew( Label );
//label->set_pos( Point2( 15,8) );
//label->set_text("Reparent Location (Select new Parent):");
- keep_transform = memnew( CheckBox );
+ keep_transform = memnew(CheckBox);
keep_transform->set_text(TTR("Keep Global Transform"));
keep_transform->set_pressed(true);
vbc->add_child(keep_transform);
-
//vbc->add_margin_child("Options:",node_only);
//cancel->connect("pressed", this,"_cancel");
get_ok()->set_text(TTR("Reparent"));
-
}
-
-ReparentDialog::~ReparentDialog()
-{
+ReparentDialog::~ReparentDialog() {
}
-
diff --git a/editor/reparent_dialog.h b/editor/reparent_dialog.h
index 200760314c..c66963e298 100644
--- a/editor/reparent_dialog.h
+++ b/editor/reparent_dialog.h
@@ -29,40 +29,36 @@
#ifndef REPARENT_DIALOG_H
#define REPARENT_DIALOG_H
-#include "scene/gui/dialogs.h"
+#include "editor/scene_tree_editor.h"
#include "scene/gui/button.h"
-#include "scene/gui/check_button.h"
#include "scene/gui/check_box.h"
-#include "editor/scene_tree_editor.h"
+#include "scene/gui/check_button.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/line_edit.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class ReparentDialog : public ConfirmationDialog {
- GDCLASS( ReparentDialog, ConfirmationDialog );
+ GDCLASS(ReparentDialog, ConfirmationDialog);
SceneTreeEditor *tree;
CheckBox *keep_transform;
-
void update_tree();
void _reparent();
void _cancel();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_current(const Set<Node*>& p_selection);
+public:
+ void set_current(const Set<Node *> &p_selection);
String get_selected_type();
ReparentDialog();
~ReparentDialog();
-
};
#endif
diff --git a/editor/resources_dock.cpp b/editor/resources_dock.cpp
index 8648361bae..c5f141562a 100644
--- a/editor/resources_dock.cpp
+++ b/editor/resources_dock.cpp
@@ -28,20 +28,19 @@
/*************************************************************************/
#include "resources_dock.h"
+#include "editor_file_system.h"
#include "editor_node.h"
+#include "editor_settings.h"
+#include "global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
-#include "editor_settings.h"
#include "project_settings.h"
-#include "global_config.h"
-#include "editor_file_system.h"
-
void ResourcesDock::_tool_selected(int p_tool) {
- current_action=p_tool;
+ current_action = p_tool;
- switch(p_tool) {
+ switch (p_tool) {
case TOOL_NEW: {
@@ -58,8 +57,7 @@ void ResourcesDock::_tool_selected(int p_tool) {
break;
Ref<Resource> current_res = ti->get_metadata(0);
-
- if (current_res->get_path()!="" && current_res->get_path().find("::")==-1) {
+ if (current_res->get_path() != "" && current_res->get_path().find("::") == -1) {
_file_action(current_res->get_path());
break;
};
@@ -73,7 +71,6 @@ void ResourcesDock::_tool_selected(int p_tool) {
save_resource_as(ti->get_metadata(0));
-
} break;
case TOOL_MAKE_LOCAL: {
@@ -97,93 +94,84 @@ void ResourcesDock::_tool_selected(int p_tool) {
add_resource(EditorSettings::get_singleton()->get_resource_clipboard());
} break;
-
}
}
-
-
void ResourcesDock::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- button_new->set_icon(get_icon("New","EditorIcons"));
- button_open->set_icon(get_icon("Folder","EditorIcons"));
- button_save->set_icon(get_icon("Save","EditorIcons"));
- button_tools->set_icon(get_icon("Tools","EditorIcons"));
-
+ button_new->set_icon(get_icon("New", "EditorIcons"));
+ button_open->set_icon(get_icon("Folder", "EditorIcons"));
+ button_save->set_icon(get_icon("Save", "EditorIcons"));
+ button_tools->set_icon(get_icon("Tools", "EditorIcons"));
} break;
}
-
}
-
-void ResourcesDock::save_resource(const String& p_path,const Ref<Resource>& p_resource) {
+void ResourcesDock::save_resource(const String &p_path, const Ref<Resource> &p_resource) {
editor->get_editor_data().apply_changes_in_editors();
- int flg=0;
+ int flg = 0;
if (EditorSettings::get_singleton()->get("on_save/compress_binary_resources"))
- flg|=ResourceSaver::FLAG_COMPRESS;
+ flg |= ResourceSaver::FLAG_COMPRESS;
/*
if (EditorSettings::get_singleton()->get("on_save/save_paths_as_relative"))
flg|=ResourceSaver::FLAG_RELATIVE_PATHS;
*/
String path = GlobalConfig::get_singleton()->localize_path(p_path);
- Error err = ResourceSaver::save(path,p_resource,flg|ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
+ Error err = ResourceSaver::save(path, p_resource, flg | ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS);
- if (err!=OK) {
+ if (err != OK) {
accept->set_text(TTR("Error saving resource!"));
accept->popup_centered_minsize();
- return;
+ return;
}
//EditorFileSystem::get_singleton()->update_file(path,p_resource->get_type());
- ((Resource*)p_resource.ptr())->set_path(path);
- editor->emit_signal("resource_saved",p_resource);
-
+ ((Resource *)p_resource.ptr())->set_path(path);
+ editor->emit_signal("resource_saved", p_resource);
}
-void ResourcesDock::save_resource_as(const Ref<Resource>& p_resource) {
+void ResourcesDock::save_resource_as(const Ref<Resource> &p_resource) {
- current_action=TOOL_SAVE_AS;
+ current_action = TOOL_SAVE_AS;
RES res(p_resource);
List<String> extensions;
- ResourceSaver::get_recognized_extensions(res,&extensions);
+ ResourceSaver::get_recognized_extensions(res, &extensions);
file->set_mode(EditorFileDialog::MODE_SAVE_FILE);
- if (p_resource->get_path()!="" && p_resource->get_path().find("::")==-1) {
+ if (p_resource->get_path() != "" && p_resource->get_path().find("::") == -1) {
file->set_current_path(p_resource->get_path());
} else {
String existing;
if (extensions.size()) {
- existing="new_"+res->get_class().to_lower()+"."+extensions.front()->get().to_lower();
+ existing = "new_" + res->get_class().to_lower() + "." + extensions.front()->get().to_lower();
}
file->set_current_file(existing);
}
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
file->popup_centered_ratio();
-
}
-void ResourcesDock::_file_action(const String& p_path) {
+void ResourcesDock::_file_action(const String &p_path) {
-
- switch(current_action) {
+ switch (current_action) {
case TOOL_OPEN: {
@@ -198,12 +186,11 @@ void ResourcesDock::_file_action(const String& p_path) {
RES res(current_res);
- save_resource(p_path,res);
+ save_resource(p_path, res);
_update_name(ti);
} break;
-
}
}
@@ -211,39 +198,34 @@ void ResourcesDock::_update_name(TreeItem *item) {
Ref<Resource> res = item->get_metadata(0);
-
- if (res->get_name()!="")
- item->set_text(0,res->get_name());
- else if (res->get_path()!="" && res->get_path().find("::")==-1)
- item->set_text(0,res->get_path().get_file());
+ if (res->get_name() != "")
+ item->set_text(0, res->get_name());
+ else if (res->get_path() != "" && res->get_path().find("::") == -1)
+ item->set_text(0, res->get_path().get_file());
else
- item->set_text(0,res->get_class()+" ("+itos(res->get_instance_ID())+")");
-
+ item->set_text(0, res->get_class() + " (" + itos(res->get_instance_ID()) + ")");
}
-
-void ResourcesDock::remove_resource(const Ref<Resource>& p_resource) {
+void ResourcesDock::remove_resource(const Ref<Resource> &p_resource) {
TreeItem *root = resources->get_root();
ERR_FAIL_COND(!root);
- TreeItem *existing=root->get_children();
+ TreeItem *existing = root->get_children();
- while(existing) {
+ while (existing) {
Ref<Resource> r = existing->get_metadata(0);
- if (r==p_resource) {
+ if (r == p_resource) {
//existing->move_to_top();
memdelete(existing);
return;
}
- existing=existing->get_next();
+ existing = existing->get_next();
}
-
-
}
-void ResourcesDock::add_resource(const Ref<Resource>& p_resource) {
+void ResourcesDock::add_resource(const Ref<Resource> &p_resource) {
if (block_add)
return;
@@ -253,33 +235,32 @@ void ResourcesDock::add_resource(const Ref<Resource>& p_resource) {
TreeItem *root = resources->get_root();
ERR_FAIL_COND(!root);
- TreeItem *existing=root->get_children();
+ TreeItem *existing = root->get_children();
- while(existing) {
+ while (existing) {
Ref<Resource> r = existing->get_metadata(0);
- if (r==p_resource) {
+ if (r == p_resource) {
//existing->move_to_top();
existing->select(0);
resources->ensure_cursor_is_visible();
return; // existing
}
- existing=existing->get_next();
+ existing = existing->get_next();
}
TreeItem *res = resources->create_item(root);
- res->set_metadata(0,p_resource);
+ res->set_metadata(0, p_resource);
- if (has_icon(p_resource->get_class(),"EditorIcons")) {
- res->set_icon(0,get_icon(p_resource->get_class(),"EditorIcons"));
+ if (has_icon(p_resource->get_class(), "EditorIcons")) {
+ res->set_icon(0, get_icon(p_resource->get_class(), "EditorIcons"));
}
_update_name(res);
- res->add_button(0,get_icon("Del","EditorIcons"));
+ res->add_button(0, get_icon("Del", "EditorIcons"));
res->move_to_top();
res->select(0);
resources->ensure_cursor_is_visible();
-
}
void ResourcesDock::_resource_selected() {
@@ -287,23 +268,20 @@ void ResourcesDock::_resource_selected() {
TreeItem *sel = resources->get_selected();
ERR_FAIL_COND(!sel);
-
Ref<Resource> r = sel->get_metadata(0);
if (r.is_null())
return;
- block_add=true;
+ block_add = true;
editor->push_item(r.ptr());
- block_add=false;
+ block_add = false;
}
-void ResourcesDock::_delete(Object* p_item, int p_column, int p_id) {
+void ResourcesDock::_delete(Object *p_item, int p_column, int p_id) {
TreeItem *ti = p_item->cast_to<TreeItem>();
ERR_FAIL_COND(!ti);
-
- call_deferred("remove_resource",ti->get_metadata(0));
-
+ call_deferred("remove_resource", ti->get_metadata(0));
}
void ResourcesDock::_create() {
@@ -314,96 +292,86 @@ void ResourcesDock::_create() {
Resource *r = c->cast_to<Resource>();
ERR_FAIL_COND(!r);
- REF res( r );
+ REF res(r);
editor->push_item(c);
-
}
void ResourcesDock::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_tool_selected"),&ResourcesDock::_tool_selected);
- ClassDB::bind_method(D_METHOD("_create"),&ResourcesDock::_create);
- ClassDB::bind_method(D_METHOD("_resource_selected"),&ResourcesDock::_resource_selected);
- ClassDB::bind_method(D_METHOD("_delete"),&ResourcesDock::_delete);
- ClassDB::bind_method(D_METHOD("remove_resource"),&ResourcesDock::remove_resource);
- ClassDB::bind_method(D_METHOD("_file_action"),&ResourcesDock::_file_action);
-
-
-
+ ClassDB::bind_method(D_METHOD("_tool_selected"), &ResourcesDock::_tool_selected);
+ ClassDB::bind_method(D_METHOD("_create"), &ResourcesDock::_create);
+ ClassDB::bind_method(D_METHOD("_resource_selected"), &ResourcesDock::_resource_selected);
+ ClassDB::bind_method(D_METHOD("_delete"), &ResourcesDock::_delete);
+ ClassDB::bind_method(D_METHOD("remove_resource"), &ResourcesDock::remove_resource);
+ ClassDB::bind_method(D_METHOD("_file_action"), &ResourcesDock::_file_action);
}
void ResourcesDock::cleanup() {
-
resources->clear();
resources->create_item(); //root
-
}
-
ResourcesDock::ResourcesDock(EditorNode *p_editor) {
- editor=p_editor;
+ editor = p_editor;
VBoxContainer *vbc = this;
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
-
Button *b;
- b = memnew( ToolButton );
+ b = memnew(ToolButton);
b->set_tooltip(TTR("Create New Resource"));
- b->connect("pressed",this,"_tool_selected",make_binds(TOOL_NEW));
- hbc->add_child( b );
- button_new=b;
+ b->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW));
+ hbc->add_child(b);
+ button_new = b;
- b = memnew( ToolButton );
+ b = memnew(ToolButton);
b->set_tooltip(TTR("Open Resource"));
- b->connect("pressed",this,"_tool_selected",make_binds(TOOL_OPEN));
- hbc->add_child( b );
- button_open=b;
+ b->connect("pressed", this, "_tool_selected", make_binds(TOOL_OPEN));
+ hbc->add_child(b);
+ button_open = b;
- MenuButton *mb = memnew( MenuButton );
+ MenuButton *mb = memnew(MenuButton);
mb->set_tooltip(TTR("Save Resource"));
- mb->get_popup()->add_item(TTR("Save Resource"),TOOL_SAVE);
- mb->get_popup()->add_item(TTR("Save Resource As.."),TOOL_SAVE_AS);
- mb->get_popup()->connect("id_pressed",this,"_tool_selected" );
- hbc->add_child( mb );
- button_save=mb;
+ mb->get_popup()->add_item(TTR("Save Resource"), TOOL_SAVE);
+ mb->get_popup()->add_item(TTR("Save Resource As.."), TOOL_SAVE_AS);
+ mb->get_popup()->connect("id_pressed", this, "_tool_selected");
+ hbc->add_child(mb);
+ button_save = mb;
hbc->add_spacer();
- mb = memnew( MenuButton );
+ mb = memnew(MenuButton);
mb->set_tooltip(TTR("Resource Tools"));
- mb->get_popup()->add_item(TTR("Make Local"),TOOL_MAKE_LOCAL);
- mb->get_popup()->add_item(TTR("Copy"),TOOL_COPY);
- mb->get_popup()->add_item(TTR("Paste"),TOOL_PASTE);
- mb->get_popup()->connect("id_pressed",this,"_tool_selected" );
- hbc->add_child( mb );
- button_tools=mb;
-
- resources = memnew( Tree );
+ mb->get_popup()->add_item(TTR("Make Local"), TOOL_MAKE_LOCAL);
+ mb->get_popup()->add_item(TTR("Copy"), TOOL_COPY);
+ mb->get_popup()->add_item(TTR("Paste"), TOOL_PASTE);
+ mb->get_popup()->connect("id_pressed", this, "_tool_selected");
+ hbc->add_child(mb);
+ button_tools = mb;
+
+ resources = memnew(Tree);
vbc->add_child(resources);
resources->set_v_size_flags(SIZE_EXPAND_FILL);
resources->create_item(); //root
resources->set_hide_root(true);
- resources->connect("cell_selected",this,"_resource_selected");
- resources->connect("button_pressed",this,"_delete");
+ resources->connect("cell_selected", this, "_resource_selected");
+ resources->connect("button_pressed", this, "_delete");
- create_dialog = memnew( CreateDialog );
+ create_dialog = memnew(CreateDialog);
add_child(create_dialog);
create_dialog->set_base_type("Resource");
- create_dialog->connect("create",this,"_create");
- accept = memnew (AcceptDialog);
+ create_dialog->connect("create", this, "_create");
+ accept = memnew(AcceptDialog);
add_child(accept);
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
add_child(file);
- file->connect("file_selected",this,"_file_action");
+ file->connect("file_selected", this, "_file_action");
-
- block_add=false;
+ block_add = false;
}
-
diff --git a/editor/resources_dock.h b/editor/resources_dock.h
index e225786583..15437f981f 100644
--- a/editor/resources_dock.h
+++ b/editor/resources_dock.h
@@ -29,23 +29,22 @@
#ifndef RESOURCES_DOCK_H
#define RESOURCES_DOCK_H
+#include "create_dialog.h"
+#include "editor_file_dialog.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
#include "scene/gui/control.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/file_dialog.h"
#include "scene/gui/label.h"
-#include "scene/gui/button.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/box_container.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/file_dialog.h"
-#include "create_dialog.h"
-#include "editor_file_dialog.h"
-
+#include "scene/gui/tool_button.h"
+#include "scene/gui/tree.h"
class EditorNode;
class ResourcesDock : public VBoxContainer {
- GDCLASS( ResourcesDock, VBoxContainer );
+ GDCLASS(ResourcesDock, VBoxContainer);
enum {
TOOL_NEW,
@@ -58,7 +57,6 @@ class ResourcesDock : public VBoxContainer {
TOOL_MAX
};
-
EditorNode *editor;
Button *button_new;
@@ -74,32 +72,23 @@ class ResourcesDock : public VBoxContainer {
bool block_add;
int current_action;
+ void _file_action(const String &p_action);
-
-
-
- void _file_action(const String& p_action);
-
-
-
- void _delete(Object* p_item, int p_column, int p_id);
+ void _delete(Object *p_item, int p_column, int p_id);
void _resource_selected();
void _update_name(TreeItem *item);
void _tool_selected(int p_tool);
void _create();
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
- void add_resource(const Ref<Resource>& p_resource);
- void remove_resource(const Ref<Resource>& p_resource);
- void save_resource(const String& p_path,const Ref<Resource>& p_resource);
- void save_resource_as(const Ref<Resource>& p_resource);
-
+ void add_resource(const Ref<Resource> &p_resource);
+ void remove_resource(const Ref<Resource> &p_resource);
+ void save_resource(const String &p_path, const Ref<Resource> &p_resource);
+ void save_resource_as(const Ref<Resource> &p_resource);
void cleanup();
diff --git a/editor/run_settings_dialog.cpp b/editor/run_settings_dialog.cpp
index 4d69c7ad84..35cbb6c410 100644
--- a/editor/run_settings_dialog.cpp
+++ b/editor/run_settings_dialog.cpp
@@ -28,14 +28,12 @@
/*************************************************************************/
#include "run_settings_dialog.h"
-
void RunSettingsDialog::popup_run_settings() {
- popup_centered(Size2( 300, 150 ));
+ popup_centered(Size2(300, 150));
}
-void RunSettingsDialog::set_custom_arguments(const String& p_arguments) {
-
+void RunSettingsDialog::set_custom_arguments(const String &p_arguments) {
arguments->set_text(p_arguments);
}
@@ -44,16 +42,15 @@ String RunSettingsDialog::get_custom_arguments() const {
return arguments->get_text();
}
-
void RunSettingsDialog::_bind_methods() {
- ClassDB::bind_method("_run_mode_changed",&RunSettingsDialog::_run_mode_changed);
+ ClassDB::bind_method("_run_mode_changed", &RunSettingsDialog::_run_mode_changed);
//ClassDB::bind_method("_browse_selected_file",&RunSettingsDialog::_browse_selected_file);
}
void RunSettingsDialog::_run_mode_changed(int idx) {
- if (idx==0)
+ if (idx == 0)
arguments->set_editable(false);
else
arguments->set_editable(true);
@@ -74,17 +71,17 @@ RunSettingsDialog::RunSettingsDialog() {
/* SNAP DIALOG */
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
//set_child_rect(vbc);
- run_mode = memnew( OptionButton );
- vbc->add_margin_child(TTR("Run Mode:"),run_mode);
+ run_mode = memnew(OptionButton);
+ vbc->add_margin_child(TTR("Run Mode:"), run_mode);
run_mode->add_item(TTR("Current Scene"));
run_mode->add_item(TTR("Main Scene"));
- run_mode->connect("item_selected",this,"_run_mode_changed");
- arguments = memnew( LineEdit );
- vbc->add_margin_child(TTR("Main Scene Arguments:"),arguments);
+ run_mode->connect("item_selected", this, "_run_mode_changed");
+ arguments = memnew(LineEdit);
+ vbc->add_margin_child(TTR("Main Scene Arguments:"), arguments);
arguments->set_editable(false);
get_ok()->set_text(TTR("Close"));
@@ -93,6 +90,4 @@ RunSettingsDialog::RunSettingsDialog() {
arguments->set_text("-l $scene");
set_title(TTR("Scene Run Settings"));
-
-
}
diff --git a/editor/run_settings_dialog.h b/editor/run_settings_dialog.h
index 2efc18e43f..98d0368344 100644
--- a/editor/run_settings_dialog.h
+++ b/editor/run_settings_dialog.h
@@ -29,34 +29,35 @@
#ifndef RUN_SETTINGS_DIALOG_H
#define RUN_SETTINGS_DIALOG_H
-#include "scene/gui/dialogs.h"
-#include "scene/gui/line_edit.h"
#include "scene/gui/check_button.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/file_dialog.h"
+#include "scene/gui/line_edit.h"
class RunSettingsDialog : public AcceptDialog {
- GDCLASS( RunSettingsDialog, AcceptDialog);
+ GDCLASS(RunSettingsDialog, AcceptDialog);
+
public:
enum RunMode {
RUN_LOCAL_SCENE,
RUN_MAIN_SCENE,
};
-private:
+private:
OptionButton *run_mode;
LineEdit *arguments;
void _run_mode_changed(int idx);
-protected:
+protected:
static void _bind_methods();
-public:
+public:
int get_run_mode() const;
void set_run_mode(int p_run_mode);
- void set_custom_arguments(const String& p_arguments);
+ void set_custom_arguments(const String &p_arguments);
String get_custom_arguments() const;
void popup_run_settings();
diff --git a/editor/scene_tree_dock.cpp b/editor/scene_tree_dock.cpp
index 47eb84ab79..04b10959ef 100644
--- a/editor/scene_tree_dock.cpp
+++ b/editor/scene_tree_dock.cpp
@@ -28,36 +28,33 @@
/*************************************************************************/
#include "scene_tree_dock.h"
+#include "animation_editor.h"
+#include "core/io/resource_saver.h"
+#include "editor/plugins/animation_player_editor_plugin.h"
+#include "editor/plugins/canvas_item_editor_plugin.h"
+#include "editor/plugins/script_editor_plugin.h"
+#include "editor/plugins/spatial_editor_plugin.h"
#include "editor_node.h"
+#include "editor_settings.h"
#include "global_config.h"
+#include "multi_node_edit.h"
#include "os/keyboard.h"
+#include "scene/main/viewport.h"
#include "scene/resources/packed_scene.h"
-#include "editor_settings.h"
-#include "editor/plugins/canvas_item_editor_plugin.h"
-#include "editor/plugins/spatial_editor_plugin.h"
#include "script_editor_debugger.h"
-#include "editor/plugins/script_editor_plugin.h"
-#include "core/io/resource_saver.h"
-#include "multi_node_edit.h"
-#include "editor/plugins/animation_player_editor_plugin.h"
-#include "animation_editor.h"
-#include "scene/main/viewport.h"
-
void SceneTreeDock::_nodes_drag_begin() {
-
if (restore_script_editor_on_drag) {
EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT);
- restore_script_editor_on_drag=false;
+ restore_script_editor_on_drag = false;
}
-
}
void SceneTreeDock::_input(InputEvent p_event) {
- if (p_event.type==InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index==BUTTON_LEFT) {
- restore_script_editor_on_drag=false; //lost chance
+ if (p_event.type == InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index == BUTTON_LEFT) {
+ restore_script_editor_on_drag = false; //lost chance
}
}
@@ -71,54 +68,41 @@ void SceneTreeDock::_unhandled_key_input(InputEvent p_event) {
if (ED_IS_SHORTCUT("scene_tree/add_child_node", p_event)) {
_tool_selected(TOOL_NEW);
- }
- else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) {
_tool_selected(TOOL_INSTANCE);
- }
- else if (ED_IS_SHORTCUT("scene_tree/change_node_type", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/change_node_type", p_event)) {
_tool_selected(TOOL_REPLACE);
- }
- else if (ED_IS_SHORTCUT("scene_tree/duplicate", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/duplicate", p_event)) {
_tool_selected(TOOL_DUPLICATE);
- }
- else if (ED_IS_SHORTCUT("scene_tree/attach_script", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/attach_script", p_event)) {
_tool_selected(TOOL_ATTACH_SCRIPT);
- }
- else if(ED_IS_SHORTCUT("scene_tree/clear_script", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/clear_script", p_event)) {
_tool_selected(TOOL_CLEAR_SCRIPT);
- }
- else if (ED_IS_SHORTCUT("scene_tree/move_up", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/move_up", p_event)) {
_tool_selected(TOOL_MOVE_UP);
- }
- else if (ED_IS_SHORTCUT("scene_tree/move_down", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/move_down", p_event)) {
_tool_selected(TOOL_MOVE_DOWN);
- }
- else if (ED_IS_SHORTCUT("scene_tree/reparent", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/reparent", p_event)) {
_tool_selected(TOOL_REPARENT);
- }
- else if (ED_IS_SHORTCUT("scene_tree/merge_from_scene", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/merge_from_scene", p_event)) {
_tool_selected(TOOL_MERGE_FROM_SCENE);
- }
- else if (ED_IS_SHORTCUT("scene_tree/save_branch_as_scene", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/save_branch_as_scene", p_event)) {
_tool_selected(TOOL_NEW_SCENE_FROM);
- }
- else if (ED_IS_SHORTCUT("scene_tree/delete_no_confirm", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/delete_no_confirm", p_event)) {
_tool_selected(TOOL_ERASE, true);
- }
- else if(ED_IS_SHORTCUT("scene_tree/copy_node_path", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/copy_node_path", p_event)) {
_tool_selected(TOOL_COPY_NODE_PATH);
- }
- else if (ED_IS_SHORTCUT("scene_tree/delete", p_event)) {
+ } else if (ED_IS_SHORTCUT("scene_tree/delete", p_event)) {
_tool_selected(TOOL_ERASE);
}
}
-void SceneTreeDock::instance(const String& p_file) {
+void SceneTreeDock::instance(const String &p_file) {
Node *parent = scene_tree->get_selected();
if (!parent || !edited_scene) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("OK :("));
accept->set_text(TTR("No parent to instance a child at."));
@@ -130,11 +114,10 @@ void SceneTreeDock::instance(const String& p_file) {
Vector<String> scenes;
scenes.push_back(p_file);
- _perform_instance_scenes(scenes,parent,-1);
-
+ _perform_instance_scenes(scenes, parent, -1);
}
-void SceneTreeDock::instance_scenes(const Vector<String>& p_files, Node *p_parent) {
+void SceneTreeDock::instance_scenes(const Vector<String> &p_files, Node *p_parent) {
Node *parent = p_parent;
@@ -153,111 +136,102 @@ void SceneTreeDock::instance_scenes(const Vector<String>& p_files, Node *p_paren
_perform_instance_scenes(p_files, parent, -1);
}
-void SceneTreeDock::_perform_instance_scenes(const Vector<String>& p_files,Node* parent,int p_pos) {
-
-
+void SceneTreeDock::_perform_instance_scenes(const Vector<String> &p_files, Node *parent, int p_pos) {
ERR_FAIL_COND(!parent);
+ Vector<Node *> instances;
- Vector<Node*> instances;
-
- bool error=false;
+ bool error = false;
- for(int i=0;i<p_files.size();i++) {
+ for (int i = 0; i < p_files.size(); i++) {
Ref<PackedScene> sdata = ResourceLoader::load(p_files[i]);
if (!sdata.is_valid()) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("Ugh"));
- accept->set_text(vformat(TTR("Error loading scene from %s"),p_files[i]));
+ accept->set_text(vformat(TTR("Error loading scene from %s"), p_files[i]));
accept->popup_centered_minsize();
- error=true;
+ error = true;
break;
-
}
- Node*instanced_scene=sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
if (!instanced_scene) {
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("Ugh"));
- accept->set_text(vformat(TTR("Error instancing scene from %s"),p_files[i]));
+ accept->set_text(vformat(TTR("Error instancing scene from %s"), p_files[i]));
accept->popup_centered_minsize();
- error=true;
+ error = true;
break;
-
}
- if (edited_scene->get_filename()!="") {
+ if (edited_scene->get_filename() != "") {
if (_cyclical_dependency_exists(edited_scene->get_filename(), instanced_scene)) {
accept->get_ok()->set_text(TTR("Ok"));
- accept->set_text(vformat(TTR("Cannot instance the scene '%s' because the current scene exists within one of its nodes."),p_files[i]));
+ accept->set_text(vformat(TTR("Cannot instance the scene '%s' because the current scene exists within one of its nodes."), p_files[i]));
accept->popup_centered_minsize();
- error=true;
+ error = true;
break;
}
}
- instanced_scene->set_filename( GlobalConfig::get_singleton()->localize_path(p_files[i]) );
+ instanced_scene->set_filename(GlobalConfig::get_singleton()->localize_path(p_files[i]));
instances.push_back(instanced_scene);
}
if (error) {
- for(int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
memdelete(instances[i]);
}
return;
}
-
-
//instanced_scene->generate_instance_state();
editor_data->get_undo_redo().create_action(TTR("Instance Scene(s)"));
- for(int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
- Node* instanced_scene=instances[i];
+ Node *instanced_scene = instances[i];
- editor_data->get_undo_redo().add_do_method(parent,"add_child",instanced_scene);
- if (p_pos>=0) {
- editor_data->get_undo_redo().add_do_method(parent,"move_child",instanced_scene,p_pos+i);
+ editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene);
+ if (p_pos >= 0) {
+ editor_data->get_undo_redo().add_do_method(parent, "move_child", instanced_scene, p_pos + i);
}
- editor_data->get_undo_redo().add_do_method(instanced_scene,"set_owner",edited_scene);
- editor_data->get_undo_redo().add_do_method(editor_selection,"clear");
- editor_data->get_undo_redo().add_do_method(editor_selection,"add_node",instanced_scene);
+ editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", edited_scene);
+ editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
+ editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", instanced_scene);
editor_data->get_undo_redo().add_do_reference(instanced_scene);
- editor_data->get_undo_redo().add_undo_method(parent,"remove_child",instanced_scene);
+ editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene);
String new_name = parent->validate_child_name(instanced_scene);
ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_instance_node",edited_scene->get_path_to(parent),p_files[i],new_name);
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_remove_node",NodePath(String(edited_scene->get_path_to(parent))+"/"+new_name));
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name);
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name));
}
editor_data->get_undo_redo().commit_action();
-
-
}
-void SceneTreeDock::_replace_with_branch_scene(const String& p_file,Node* base) {
+void SceneTreeDock::_replace_with_branch_scene(const String &p_file, Node *base) {
Ref<PackedScene> sdata = ResourceLoader::load(p_file);
if (!sdata.is_valid()) {
accept->get_ok()->set_text(TTR("Ugh"));
- accept->set_text(vformat(TTR("Error loading scene from %s"),p_file));
+ accept->set_text(vformat(TTR("Error loading scene from %s"), p_file));
accept->popup_centered_minsize();
return;
}
- Node *instanced_scene=sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
+ Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
if (!instanced_scene) {
accept->get_ok()->set_text(TTR("Ugh"));
- accept->set_text(vformat(TTR("Error instancing scene from %s"),p_file));
+ accept->set_text(vformat(TTR("Error instancing scene from %s"), p_file));
accept->popup_centered_minsize();
return;
}
@@ -273,17 +247,17 @@ void SceneTreeDock::_replace_with_branch_scene(const String& p_file,Node* base)
scene_tree->set_selected(instanced_scene);
}
-bool SceneTreeDock::_cyclical_dependency_exists(const String& p_target_scene_path, Node* p_desired_node) {
+bool SceneTreeDock::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) {
int childCount = p_desired_node->get_child_count();
- if (p_desired_node->get_filename()==p_target_scene_path) {
+ if (p_desired_node->get_filename() == p_target_scene_path) {
return true;
}
- for (int i=0;i<childCount;i++) {
- Node* child=p_desired_node->get_child(i);
+ for (int i = 0; i < childCount; i++) {
+ Node *child = p_desired_node->get_child(i);
- if(_cyclical_dependency_exists(p_target_scene_path,child)) {
+ if (_cyclical_dependency_exists(p_target_scene_path, child)) {
return true;
}
}
@@ -291,12 +265,11 @@ bool SceneTreeDock::_cyclical_dependency_exists(const String& p_target_scene_pat
return false;
}
-
void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
- current_option=p_tool;
+ current_option = p_tool;
- switch(p_tool) {
+ switch (p_tool) {
case TOOL_NEW: {
/*
@@ -330,11 +303,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
List<String> extensions;
- ResourceLoader::get_recognized_extensions_for_type("PackedScene",&extensions);
+ ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions);
file->clear_filters();
- for(int i=0;i<extensions.size();i++) {
+ for (int i = 0; i < extensions.size(); i++) {
- file->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
//file->set_current_path(current_path);
@@ -387,20 +360,19 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
editor->push_item(existing.ptr());
else {
String path = selected->get_filename();
- script_create_dialog->config(selected->get_class(),path);
- script_create_dialog->popup_centered(Size2(300,290));
+ script_create_dialog->config(selected->get_class(), path);
+ script_create_dialog->popup_centered(Size2(300, 290));
//script_create_dialog->popup_centered_minsize();
-
}
} break;
case TOOL_CLEAR_SCRIPT: {
Node *selected = scene_tree->get_selected();
- if(!selected)
+ if (!selected)
break;
Ref<Script> existing = selected->get_script();
- if(existing.is_valid()) {
+ if (existing.is_valid()) {
const RefPtr empty;
selected->set_script(empty);
button_create_script->show();
@@ -414,11 +386,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
if (!scene_tree->get_selected())
break;
+ if (scene_tree->get_selected() == edited_scene) {
- if (scene_tree->get_selected()==edited_scene) {
-
-
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation can't be done on the tree root."));
@@ -426,7 +396,6 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
break;
}
-
if (!_validate_no_foreign())
break;
@@ -434,14 +403,14 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
bool MOVING_UP = !MOVING_DOWN;
Node *common_parent = scene_tree->get_selected()->get_parent();
- List<Node*> selection = editor_selection->get_selected_node_list();
- selection.sort_custom<Node::Comparator>(); // sort by index
+ List<Node *> selection = editor_selection->get_selected_node_list();
+ selection.sort_custom<Node::Comparator>(); // sort by index
if (MOVING_DOWN)
selection.invert();
int lowest_id = common_parent->get_child_count() - 1;
int highest_id = 0;
- for (List<Node*>::Element *E = selection.front(); E; E = E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
int index = E->get()->get_index();
if (index > highest_id) highest_id = index;
@@ -479,11 +448,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
if (!edited_scene)
break;
-
if (editor_selection->is_selected(edited_scene)) {
-
- current_option=-1;
+ current_option = -1;
//accept->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation can't be done on the tree root."));
@@ -494,54 +461,53 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
if (!_validate_no_foreign())
break;
- List<Node*> selection = editor_selection->get_selected_node_list();
- if (selection.size()==0)
+ List<Node *> selection = editor_selection->get_selected_node_list();
+ if (selection.size() == 0)
break;
- List<Node*> reselect;
+ List<Node *> reselect;
editor_data->get_undo_redo().create_action(TTR("Duplicate Node(s)"));
- editor_data->get_undo_redo().add_do_method(editor_selection,"clear");
-
- Node *dupsingle=NULL;
+ editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
+ Node *dupsingle = NULL;
- for (List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
Node *node = E->get();
Node *parent = node->get_parent();
- List<Node*> owned;
- node->get_owned_by(node->get_owner(),&owned);
+ List<Node *> owned;
+ node->get_owned_by(node->get_owner(), &owned);
- Map<Node*,Node*> duplimap;
- Node * dup = _duplicate(node,duplimap);
+ Map<Node *, Node *> duplimap;
+ Node *dup = _duplicate(node, duplimap);
ERR_CONTINUE(!dup);
- if (selection.size()==1)
- dupsingle=dup;
+ if (selection.size() == 1)
+ dupsingle = dup;
dup->set_name(parent->validate_child_name(dup));
- editor_data->get_undo_redo().add_do_method(parent,"_add_child_below_node",node, dup);
- for (List<Node*>::Element *F=owned.front();F;F=F->next()) {
+ editor_data->get_undo_redo().add_do_method(parent, "_add_child_below_node", node, dup);
+ for (List<Node *>::Element *F = owned.front(); F; F = F->next()) {
if (!duplimap.has(F->get())) {
continue;
}
- Node *d=duplimap[F->get()];
- editor_data->get_undo_redo().add_do_method(d,"set_owner",node->get_owner());
+ Node *d = duplimap[F->get()];
+ editor_data->get_undo_redo().add_do_method(d, "set_owner", node->get_owner());
}
- editor_data->get_undo_redo().add_do_method(editor_selection,"add_node",dup);
- editor_data->get_undo_redo().add_undo_method(parent,"remove_child",dup);
+ editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", dup);
+ editor_data->get_undo_redo().add_undo_method(parent, "remove_child", dup);
editor_data->get_undo_redo().add_do_reference(dup);
ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_duplicate_node",edited_scene->get_path_to(node),dup->get_name());
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_remove_node",NodePath(String(edited_scene->get_path_to(parent))+"/"+dup->get_name()));
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name());
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + dup->get_name()));
//parent->add_child(dup);
//reselect.push_back(dup);
@@ -552,22 +518,15 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
if (dupsingle)
editor->push_item(dupsingle);
-
-
-
-
} break;
case TOOL_REPARENT: {
-
if (!scene_tree->get_selected())
break;
-
if (editor_selection->is_selected(edited_scene)) {
-
- current_option=-1;
+ current_option = -1;
//confirmation->get_cancel()->hide();
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation can't be done on the tree root."));
@@ -578,23 +537,23 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
if (!_validate_no_foreign())
break;
- List<Node*> nodes = editor_selection->get_selected_node_list();
- Set<Node*> nodeset;
- for(List<Node*>::Element *E=nodes.front();E;E=E->next()) {
+ List<Node *> nodes = editor_selection->get_selected_node_list();
+ Set<Node *> nodeset;
+ for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) {
nodeset.insert(E->get());
}
reparent_dialog->popup_centered_ratio();
- reparent_dialog->set_current( nodeset );
+ reparent_dialog->set_current(nodeset);
} break;
case TOOL_MULTI_EDIT: {
- Node*root=EditorNode::get_singleton()->get_edited_scene();
+ Node *root = EditorNode::get_singleton()->get_edited_scene();
if (!root)
break;
- Ref<MultiNodeEdit> mne = memnew( MultiNodeEdit );
- for (const Map<Node*,Object*>::Element *E=EditorNode::get_singleton()->get_editor_selection()->get_selection().front();E;E=E->next()) {
+ Ref<MultiNodeEdit> mne = memnew(MultiNodeEdit);
+ for (const Map<Node *, Object *>::Element *E = EditorNode::get_singleton()->get_editor_selection()->get_selection().front(); E; E = E->next()) {
mne->add_node(root->get_path_to(E->key()));
}
@@ -604,7 +563,7 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
case TOOL_ERASE: {
- List<Node*> remove_list = editor_selection->get_selected_node_list();
+ List<Node *> remove_list = editor_selection->get_selected_node_list();
if (remove_list.empty())
return;
@@ -640,9 +599,9 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
break;
}
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
- if (selection.size()!=1) {
+ if (selection.size() != 1) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation requires a single selected node."));
accept->popup_centered_minsize();
@@ -651,14 +610,14 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
Node *tocopy = selection.front()->get();
- if (tocopy==scene){
+ if (tocopy == scene) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Can not perform with the root node."));
accept->popup_centered_minsize();
break;
}
- if (tocopy!=editor_data->get_edited_scene_root() && tocopy->get_filename()!="") {
+ if (tocopy != editor_data->get_edited_scene_root() && tocopy->get_filename() != "") {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation can't be done on instanced scenes."));
accept->popup_centered_minsize();
@@ -668,17 +627,17 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
List<String> extensions;
- Ref<PackedScene> sd = memnew( PackedScene );
- ResourceSaver::get_recognized_extensions(sd,&extensions);
+ Ref<PackedScene> sd = memnew(PackedScene);
+ ResourceSaver::get_recognized_extensions(sd, &extensions);
new_scene_from_dialog->clear_filters();
- for(int i=0;i<extensions.size();i++) {
- new_scene_from_dialog->add_filter("*."+extensions[i]+" ; "+extensions[i].to_upper());
+ for (int i = 0; i < extensions.size(); i++) {
+ new_scene_from_dialog->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper());
}
String existing;
if (extensions.size()) {
String root_name(tocopy->get_name());
- existing=root_name+"."+extensions.front()->get().to_lower();
+ existing = root_name + "." + extensions.front()->get().to_lower();
}
new_scene_from_dialog->set_current_path(existing);
@@ -686,11 +645,11 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
new_scene_from_dialog->set_title(TTR("Save New Scene As.."));
} break;
- case TOOL_COPY_NODE_PATH: {
- List<Node*> selection = editor_selection->get_selected_node_list();
+ case TOOL_COPY_NODE_PATH: {
+ List<Node *> selection = editor_selection->get_selected_node_list();
- if(List<Node*>::Element *e = selection.front()) {
- if(Node *node = e->get()) {
+ if (List<Node *>::Element *e = selection.front()) {
+ if (Node *node = e->get()) {
Node *root = EditorNode::get_singleton()->get_edited_scene();
NodePath path = root->get_path().rel_path_to(node->get_path());
OS::get_singleton()->set_clipboard(path);
@@ -698,54 +657,50 @@ void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) {
}
} break;
}
-
}
void SceneTreeDock::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
if (!first_enter)
break;
- first_enter=false;
+ first_enter = false;
- CanvasItemEditorPlugin *canvas_item_plugin = editor_data->get_editor("2D")->cast_to<CanvasItemEditorPlugin>();
+ CanvasItemEditorPlugin *canvas_item_plugin = editor_data->get_editor("2D")->cast_to<CanvasItemEditorPlugin>();
if (canvas_item_plugin) {
canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree");
canvas_item_plugin->get_canvas_item_editor()->connect("item_group_status_changed", scene_tree, "_update_tree");
scene_tree->connect("node_changed", canvas_item_plugin->get_canvas_item_editor()->get_viewport_control(), "update");
}
- button_add->set_icon(get_icon("Add","EditorIcons"));
- button_instance->set_icon(get_icon("Instance","EditorIcons"));
- button_create_script->set_icon(get_icon("ScriptCreate","EditorIcons"));
+ button_add->set_icon(get_icon("Add", "EditorIcons"));
+ button_instance->set_icon(get_icon("Instance", "EditorIcons"));
+ button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons"));
button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons"));
+ filter_icon->set_texture(get_icon("Zoom", "EditorIcons"));
- filter_icon->set_texture(get_icon("Zoom","EditorIcons"));
-
- EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed",this,"_selection_changed");
+ EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed");
} break;
}
}
-
-void SceneTreeDock::_load_request(const String& p_path) {
+void SceneTreeDock::_load_request(const String &p_path) {
editor->open_request(p_path);
}
-void SceneTreeDock::_script_open_request(const Ref<Script>& p_script) {
+void SceneTreeDock::_script_open_request(const Ref<Script> &p_script) {
editor->edit_resource(p_script);
}
void SceneTreeDock::_node_selected() {
-
- Node *node=scene_tree->get_selected();
+ Node *node = scene_tree->get_selected();
if (!node) {
@@ -754,12 +709,10 @@ void SceneTreeDock::_node_selected() {
}
if (ScriptEditor::get_singleton()->is_visible_in_tree()) {
- restore_script_editor_on_drag=true;
+ restore_script_editor_on_drag = true;
}
editor->push_item(node);
-
-
}
void SceneTreeDock::_node_renamed() {
@@ -767,61 +720,57 @@ void SceneTreeDock::_node_renamed() {
_node_selected();
}
-Node *SceneTreeDock::_duplicate(Node *p_node, Map<Node*,Node*> &duplimap) {
+Node *SceneTreeDock::_duplicate(Node *p_node, Map<Node *, Node *> &duplimap) {
- Node *node=NULL;
+ Node *node = NULL;
- if (p_node->get_filename()!="") { //an instance
+ if (p_node->get_filename() != "") { //an instance
- Ref<PackedScene> sd = ResourceLoader::load( p_node->get_filename() );
- ERR_FAIL_COND_V(!sd.is_valid(),NULL);
+ Ref<PackedScene> sd = ResourceLoader::load(p_node->get_filename());
+ ERR_FAIL_COND_V(!sd.is_valid(), NULL);
node = sd->instance(PackedScene::GEN_EDIT_STATE_INSTANCE);
- ERR_FAIL_COND_V(!node,NULL);
+ ERR_FAIL_COND_V(!node, NULL);
node->set_scene_instance_load_placeholder(p_node->get_scene_instance_load_placeholder());
//node->generate_instance_state();
} else {
Object *obj = ClassDB::instance(p_node->get_class());
- ERR_FAIL_COND_V(!obj,NULL);
+ ERR_FAIL_COND_V(!obj, NULL);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
- ERR_FAIL_COND_V(!node,NULL);
-
+ ERR_FAIL_COND_V(!node, NULL);
}
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
String name = E->get().name;
- node->set( name, p_node->get(name) );
-
+ node->set(name, p_node->get(name));
}
-
List<Node::GroupInfo> group_info;
p_node->get_groups(&group_info);
- for (List<Node::GroupInfo>::Element *E=group_info.front();E;E=E->next()) {
+ for (List<Node::GroupInfo>::Element *E = group_info.front(); E; E = E->next()) {
if (E->get().persistent)
- node->add_to_group(E->get().name,true);
+ node->add_to_group(E->get().name, true);
}
-
node->set_name(p_node->get_name());
- duplimap[p_node]=node;
+ duplimap[p_node] = node;
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
Node *child = p_node->get_child(i);
- if (p_node->get_owner()!=child->get_owner())
+ if (p_node->get_owner() != child->get_owner())
continue; //don't bother with not in-scene nodes.
- Node *dup = _duplicate(child,duplimap);
+ Node *dup = _duplicate(child, duplimap);
if (!dup) {
memdelete(node);
return NULL;
@@ -831,131 +780,121 @@ Node *SceneTreeDock::_duplicate(Node *p_node, Map<Node*,Node*> &duplimap) {
}
return node;
-
}
+void SceneTreeDock::_set_owners(Node *p_owner, const Array &p_nodes) {
-void SceneTreeDock::_set_owners(Node *p_owner, const Array& p_nodes) {
-
- for(int i=0;i<p_nodes.size();i++) {
+ for (int i = 0; i < p_nodes.size(); i++) {
- Object *obj=p_nodes[i];
+ Object *obj = p_nodes[i];
if (!obj)
continue;
- Node *n=obj->cast_to<Node>();
+ Node *n = obj->cast_to<Node>();
if (!n)
continue;
n->set_owner(p_owner);
}
}
-
-void SceneTreeDock::_fill_path_renames(Vector<StringName> base_path,Vector<StringName> new_base_path,Node * p_node, List<Pair<NodePath,NodePath> > *p_renames) {
+void SceneTreeDock::_fill_path_renames(Vector<StringName> base_path, Vector<StringName> new_base_path, Node *p_node, List<Pair<NodePath, NodePath> > *p_renames) {
base_path.push_back(p_node->get_name());
if (new_base_path.size())
new_base_path.push_back(p_node->get_name());
- NodePath from( base_path,true );
+ NodePath from(base_path, true);
NodePath to;
if (new_base_path.size())
- to=NodePath( new_base_path,true );
+ to = NodePath(new_base_path, true);
- Pair<NodePath,NodePath> npp;
- npp.first=from;
- npp.second=to;
+ Pair<NodePath, NodePath> npp;
+ npp.first = from;
+ npp.second = to;
p_renames->push_back(npp);
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- _fill_path_renames(base_path,new_base_path,p_node->get_child(i),p_renames);
+ _fill_path_renames(base_path, new_base_path, p_node->get_child(i), p_renames);
}
-
-
}
-void SceneTreeDock::fill_path_renames(Node* p_node, Node *p_new_parent, List<Pair<NodePath,NodePath> > *p_renames) {
+void SceneTreeDock::fill_path_renames(Node *p_node, Node *p_new_parent, List<Pair<NodePath, NodePath> > *p_renames) {
- if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks",true)))
+ if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true)))
return;
-
Vector<StringName> base_path;
Node *n = p_node->get_parent();
- while(n) {
+ while (n) {
base_path.push_back(n->get_name());
- n=n->get_parent();
+ n = n->get_parent();
}
base_path.invert();
Vector<StringName> new_base_path;
if (p_new_parent) {
n = p_new_parent;
- while(n) {
+ while (n) {
new_base_path.push_back(n->get_name());
- n=n->get_parent();
+ n = n->get_parent();
}
new_base_path.invert();
}
- _fill_path_renames(base_path,new_base_path,p_node,p_renames);
+ _fill_path_renames(base_path, new_base_path, p_node, p_renames);
}
-void SceneTreeDock::perform_node_renames(Node* p_base,List<Pair<NodePath,NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims) {
+void SceneTreeDock::perform_node_renames(Node *p_base, List<Pair<NodePath, NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims) {
Map<Ref<Animation>, Set<int> > rem_anims;
if (!r_rem_anims)
- r_rem_anims=&rem_anims;
+ r_rem_anims = &rem_anims;
- if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks",true)))
+ if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true)))
return;
if (!p_base) {
- p_base=edited_scene;
+ p_base = edited_scene;
}
if (!p_base)
return;
-
if (p_base->cast_to<AnimationPlayer>()) {
- AnimationPlayer *ap=p_base->cast_to<AnimationPlayer>();
+ AnimationPlayer *ap = p_base->cast_to<AnimationPlayer>();
List<StringName> anims;
ap->get_animation_list(&anims);
Node *root = ap->get_node(ap->get_root());
-
if (root) {
+ NodePath root_path = root->get_path();
+ NodePath new_root_path = root_path;
- NodePath root_path=root->get_path();
- NodePath new_root_path=root_path;
+ for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) {
-
- for(List<Pair<NodePath,NodePath> >::Element* E=p_renames->front();E;E=E->next()) {
-
- if (E->get().first==root_path) {
- new_root_path=E->get().second;
+ if (E->get().first == root_path) {
+ new_root_path = E->get().second;
break;
}
}
- if (new_root_path!=NodePath()) {
+ if (new_root_path != NodePath()) {
//will not be erased
- for(List<StringName>::Element *E=anims.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = anims.front(); E; E = E->next()) {
- Ref<Animation> anim=ap->get_animation(E->get());
+ Ref<Animation> anim = ap->get_animation(E->get());
if (!r_rem_anims->has(anim)) {
- r_rem_anims->insert(anim,Set<int>());
+ r_rem_anims->insert(anim, Set<int>());
Set<int> &ran = r_rem_anims->find(anim)->get();
- for(int i=0;i<anim->get_track_count();i++)
+ for (int i = 0; i < anim->get_track_count(); i++)
ran.insert(i);
}
@@ -964,9 +903,9 @@ void SceneTreeDock::perform_node_renames(Node* p_base,List<Pair<NodePath,NodePat
if (anim.is_null())
continue;
- for(int i=0;i<anim->get_track_count();i++) {
+ for (int i = 0; i < anim->get_track_count(); i++) {
- NodePath track_np=anim->track_get_path(i);
+ NodePath track_np = anim->track_get_path(i);
Node *n = root->get_node(track_np);
if (!n) {
continue;
@@ -977,31 +916,29 @@ void SceneTreeDock::perform_node_renames(Node* p_base,List<Pair<NodePath,NodePat
if (!ran.has(i))
continue; //channel was removed
- for(List<Pair<NodePath,NodePath> >::Element* E=p_renames->front();E;E=E->next()) {
-
- if (E->get().first==old_np) {
+ for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) {
+ if (E->get().first == old_np) {
- if (E->get().second==NodePath()) {
+ if (E->get().second == NodePath()) {
//will be erased
- int idx=0;
- Set<int>::Element *EI=ran.front();
+ int idx = 0;
+ Set<int>::Element *EI = ran.front();
ERR_FAIL_COND(!EI); //bug
- while(EI->get()!=i) {
+ while (EI->get() != i) {
idx++;
- EI=EI->next();
+ EI = EI->next();
ERR_FAIL_COND(!EI); //another bug
-
}
- editor_data->get_undo_redo().add_do_method(anim.ptr(),"remove_track",idx);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(),"add_track",anim->track_get_type(i),idx);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(),"track_set_path",idx,track_np);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(),"track_set_interpolation_type",idx,anim->track_get_interpolation_type(i));
- for(int j=0;j<anim->track_get_key_count(i);j++) {
+ editor_data->get_undo_redo().add_do_method(anim.ptr(), "remove_track", idx);
+ editor_data->get_undo_redo().add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx);
+ editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", idx, track_np);
+ editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i));
+ for (int j = 0; j < anim->track_get_key_count(i); j++) {
- editor_data->get_undo_redo().add_undo_method(anim.ptr(),"track_insert_key",idx,anim->track_get_key_time(i,j),anim->track_get_key_value(i,j),anim->track_get_key_transition(i,j));
+ editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j));
}
ran.erase(i); //byebye channel
@@ -1010,11 +947,11 @@ void SceneTreeDock::perform_node_renames(Node* p_base,List<Pair<NodePath,NodePat
//will be renamed
NodePath rel_path = new_root_path.rel_path_to(E->get().second);
- NodePath new_path = NodePath( rel_path.get_names(), track_np.get_subnames(), false, track_np.get_property() );
- if (new_path==track_np)
+ NodePath new_path = NodePath(rel_path.get_names(), track_np.get_subnames(), false, track_np.get_property());
+ if (new_path == track_np)
continue; //bleh
- editor_data->get_undo_redo().add_do_method(anim.ptr(),"track_set_path",i,new_path);
- editor_data->get_undo_redo().add_undo_method(anim.ptr(),"track_set_path",i,track_np);
+ editor_data->get_undo_redo().add_do_method(anim.ptr(), "track_set_path", i, new_path);
+ editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", i, track_np);
}
}
}
@@ -1024,120 +961,106 @@ void SceneTreeDock::perform_node_renames(Node* p_base,List<Pair<NodePath,NodePat
}
}
-
- for(int i=0;i<p_base->get_child_count();i++)
- perform_node_renames(p_base->get_child(i),p_renames,r_rem_anims);
-
+ for (int i = 0; i < p_base->get_child_count(); i++)
+ perform_node_renames(p_base->get_child(i), p_renames, r_rem_anims);
}
+void SceneTreeDock::_node_prerenamed(Node *p_node, const String &p_new_name) {
-void SceneTreeDock::_node_prerenamed(Node* p_node, const String& p_new_name) {
-
-
- List<Pair<NodePath,NodePath> > path_renames;
+ List<Pair<NodePath, NodePath> > path_renames;
Vector<StringName> base_path;
Node *n = p_node->get_parent();
- while(n) {
+ while (n) {
base_path.push_back(n->get_name());
- n=n->get_parent();
+ n = n->get_parent();
}
base_path.invert();
-
- Vector<StringName> new_base_path=base_path;
+ Vector<StringName> new_base_path = base_path;
base_path.push_back(p_node->get_name());
new_base_path.push_back(p_new_name);
- Pair<NodePath,NodePath> npp;
- npp.first = NodePath(base_path,true);
- npp.second = NodePath(new_base_path,true);
+ Pair<NodePath, NodePath> npp;
+ npp.first = NodePath(base_path, true);
+ npp.second = NodePath(new_base_path, true);
path_renames.push_back(npp);
+ for (int i = 0; i < p_node->get_child_count(); i++)
+ _fill_path_renames(base_path, new_base_path, p_node->get_child(i), &path_renames);
- for(int i=0;i<p_node->get_child_count();i++)
- _fill_path_renames(base_path,new_base_path,p_node->get_child(i),&path_renames);
-
- perform_node_renames(NULL,&path_renames);
-
+ perform_node_renames(NULL, &path_renames);
}
bool SceneTreeDock::_validate_no_foreign() {
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
- for (List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
- if (E->get()!=edited_scene && E->get()->get_owner()!=edited_scene) {
+ if (E->get() != edited_scene && E->get()->get_owner() != edited_scene) {
accept->get_ok()->set_text(TTR("Makes Sense!"));
accept->set_text(TTR("Can't operate on nodes from a foreign scene!"));
accept->popup_centered_minsize();
return false;
-
}
- if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get()))>=0) {
+ if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get())) >= 0) {
accept->get_ok()->set_text(TTR("Makes Sense!"));
accept->set_text(TTR("Can't operate on nodes the current scene inherits from!"));
accept->popup_centered_minsize();
return false;
-
}
-
}
return true;
}
-void SceneTreeDock::_node_reparent(NodePath p_path,bool p_keep_global_xform) {
-
+void SceneTreeDock::_node_reparent(NodePath p_path, bool p_keep_global_xform) {
Node *new_parent = scene_root->get_node(p_path);
ERR_FAIL_COND(!new_parent);
//ok all valid
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
if (selection.empty())
return; //nothing to reparent
- Vector<Node*> nodes;
+ Vector<Node *> nodes;
- for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = selection.front(); E; E = E->next()) {
nodes.push_back(E->get());
}
- _do_reparent(new_parent,-1,nodes,p_keep_global_xform);
-
+ _do_reparent(new_parent, -1, nodes, p_keep_global_xform);
}
-
-void SceneTreeDock::_do_reparent(Node* p_new_parent,int p_position_in_parent,Vector<Node*> p_nodes,bool p_keep_global_xform) {
-
+void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform) {
Node *new_parent = p_new_parent;
ERR_FAIL_COND(!new_parent);
- Node *validate=new_parent;
- while(validate) {
+ Node *validate = new_parent;
+ while (validate) {
- if (p_nodes.find(validate)!=-1) {
+ if (p_nodes.find(validate) != -1) {
ERR_EXPLAIN("Selection changed at some point.. can't reparent");
ERR_FAIL();
return;
}
- validate=validate->get_parent();
+ validate = validate->get_parent();
}
//ok all valid
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
- if (p_nodes.size()==0)
+ if (p_nodes.size() == 0)
return; //nothing to reparent
//sort by tree order, so re-adding is easy
@@ -1145,103 +1068,96 @@ void SceneTreeDock::_do_reparent(Node* p_new_parent,int p_position_in_parent,Vec
editor_data->get_undo_redo().create_action(TTR("Reparent Node"));
- List<Pair<NodePath,NodePath> > path_renames;
+ List<Pair<NodePath, NodePath> > path_renames;
Vector<StringName> former_names;
- int inc=0;
+ int inc = 0;
- for(int ni=0;ni<p_nodes.size();ni++) {
+ for (int ni = 0; ni < p_nodes.size(); ni++) {
//no undo for now, sorry
Node *node = p_nodes[ni];
- fill_path_renames(node,new_parent,&path_renames);
+ fill_path_renames(node, new_parent, &path_renames);
former_names.push_back(node->get_name());
- List<Node*> owned;
- node->get_owned_by(node->get_owner(),&owned);
+ List<Node *> owned;
+ node->get_owned_by(node->get_owner(), &owned);
Array owners;
- for(List<Node*>::Element *E=owned.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = owned.front(); E; E = E->next()) {
owners.push_back(E->get());
}
-
- if (new_parent==node->get_parent() && node->get_index() < p_position_in_parent+ni) {
+ if (new_parent == node->get_parent() && node->get_index() < p_position_in_parent + ni) {
//if child will generate a gap when moved, adjust
inc--;
}
- editor_data->get_undo_redo().add_do_method(node->get_parent(),"remove_child",node);
- editor_data->get_undo_redo().add_do_method(new_parent,"add_child",node);
+ editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node);
+ editor_data->get_undo_redo().add_do_method(new_parent, "add_child", node);
- if (p_position_in_parent>=0)
- editor_data->get_undo_redo().add_do_method(new_parent,"move_child",node,p_position_in_parent+inc);
+ if (p_position_in_parent >= 0)
+ editor_data->get_undo_redo().add_do_method(new_parent, "move_child", node, p_position_in_parent + inc);
ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
String new_name = new_parent->validate_child_name(node);
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_reparent_node",edited_scene->get_path_to(node),edited_scene->get_path_to(new_parent),new_name,-1);
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_reparent_node",NodePath(String(edited_scene->get_path_to(new_parent))+"/"+new_name),edited_scene->get_path_to(node->get_parent()),node->get_name(),node->get_index());
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, -1);
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)) + "/" + new_name), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index());
if (p_keep_global_xform) {
if (node->cast_to<Node2D>())
- editor_data->get_undo_redo().add_do_method(node,"set_global_transform",node->cast_to<Node2D>()->get_global_transform());
+ editor_data->get_undo_redo().add_do_method(node, "set_global_transform", node->cast_to<Node2D>()->get_global_transform());
if (node->cast_to<Spatial>())
- editor_data->get_undo_redo().add_do_method(node,"set_global_transform",node->cast_to<Spatial>()->get_global_transform());
+ editor_data->get_undo_redo().add_do_method(node, "set_global_transform", node->cast_to<Spatial>()->get_global_transform());
if (node->cast_to<Control>())
- editor_data->get_undo_redo().add_do_method(node,"set_global_pos",node->cast_to<Control>()->get_global_pos());
+ editor_data->get_undo_redo().add_do_method(node, "set_global_pos", node->cast_to<Control>()->get_global_pos());
}
- editor_data->get_undo_redo().add_do_method(this,"_set_owners",edited_scene,owners);
+ editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners);
- if (AnimationPlayerEditor::singleton->get_key_editor()->get_root()==node)
- editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_key_editor(),"set_root",node);
+ if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node)
+ editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node);
- editor_data->get_undo_redo().add_undo_method(new_parent,"remove_child",node);
- editor_data->get_undo_redo().add_undo_method(node,"set_name",former_names[ni]);
+ editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node);
+ editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]);
inc++;
-
}
//add and move in a second step.. (so old order is preserved)
-
-
- for(int ni=0;ni<p_nodes.size();ni++) {
+ for (int ni = 0; ni < p_nodes.size(); ni++) {
Node *node = p_nodes[ni];
- List<Node*> owned;
- node->get_owned_by(node->get_owner(),&owned);
+ List<Node *> owned;
+ node->get_owned_by(node->get_owner(), &owned);
Array owners;
- for(List<Node*>::Element *E=owned.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = owned.front(); E; E = E->next()) {
owners.push_back(E->get());
}
int child_pos = node->get_position_in_parent();
- editor_data->get_undo_redo().add_undo_method(node->get_parent(),"add_child",node);
- editor_data->get_undo_redo().add_undo_method(node->get_parent(),"move_child",node,child_pos);
- editor_data->get_undo_redo().add_undo_method(this,"_set_owners",edited_scene,owners);
- if (AnimationPlayerEditor::singleton->get_key_editor()->get_root()==node)
- editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(),"set_root",node);
+ editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node);
+ editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos);
+ editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners);
+ if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == node)
+ editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", node);
if (p_keep_global_xform) {
if (node->cast_to<Node2D>())
- editor_data->get_undo_redo().add_undo_method(node,"set_transform",node->cast_to<Node2D>()->get_transform());
+ editor_data->get_undo_redo().add_undo_method(node, "set_transform", node->cast_to<Node2D>()->get_transform());
if (node->cast_to<Spatial>())
- editor_data->get_undo_redo().add_undo_method(node,"set_transform",node->cast_to<Spatial>()->get_transform());
+ editor_data->get_undo_redo().add_undo_method(node, "set_transform", node->cast_to<Spatial>()->get_transform());
if (node->cast_to<Control>())
- editor_data->get_undo_redo().add_undo_method(node,"set_pos",node->cast_to<Control>()->get_pos());
+ editor_data->get_undo_redo().add_undo_method(node, "set_pos", node->cast_to<Control>()->get_pos());
}
-
-
-
}
- perform_node_renames(NULL,&path_renames);
+ perform_node_renames(NULL, &path_renames);
editor_data->get_undo_redo().commit_action();
//node->set_owner(owner);
@@ -1256,109 +1172,94 @@ void SceneTreeDock::_script_created(Ref<Script> p_script) {
editor->push_item(p_script.operator->());
button_create_script->hide();
button_clear_script->show();
-
}
-
void SceneTreeDock::_delete_confirm() {
- List<Node*> remove_list = editor_selection->get_selected_node_list();
+ List<Node *> remove_list = editor_selection->get_selected_node_list();
if (remove_list.empty())
return;
-
editor->get_editor_plugins_over()->make_visible(false);
editor_data->get_undo_redo().create_action(TTR("Remove Node(s)"));
- bool entire_scene=false;
+ bool entire_scene = false;
- for(List<Node*>::Element *E=remove_list.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) {
- if (E->get()==edited_scene) {
- entire_scene=true;
+ if (E->get() == edited_scene) {
+ entire_scene = true;
}
}
if (entire_scene) {
- editor_data->get_undo_redo().add_do_method(editor,"set_edited_scene",(Object*)NULL);
- editor_data->get_undo_redo().add_undo_method(editor,"set_edited_scene",edited_scene);
- editor_data->get_undo_redo().add_undo_method(edited_scene,"set_owner",edited_scene->get_owner());
+ editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", (Object *)NULL);
+ editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", edited_scene);
+ editor_data->get_undo_redo().add_undo_method(edited_scene, "set_owner", edited_scene->get_owner());
editor_data->get_undo_redo().add_undo_reference(edited_scene);
} else {
remove_list.sort_custom<Node::Comparator>(); //sort nodes to keep positions
- List<Pair<NodePath,NodePath> > path_renames;
-
+ List<Pair<NodePath, NodePath> > path_renames;
//delete from animation
- for(List<Node*>::Element *E=remove_list.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) {
Node *n = E->get();
if (!n->is_inside_tree() || !n->get_parent())
continue;
- fill_path_renames(n,NULL,&path_renames);
-
+ fill_path_renames(n, NULL, &path_renames);
}
- perform_node_renames(NULL,&path_renames);
+ perform_node_renames(NULL, &path_renames);
//delete for read
- for(List<Node*>::Element *E=remove_list.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) {
Node *n = E->get();
if (!n->is_inside_tree() || !n->get_parent())
continue;
- List<Node*> owned;
- n->get_owned_by(n->get_owner(),&owned);
+ List<Node *> owned;
+ n->get_owned_by(n->get_owner(), &owned);
Array owners;
- for(List<Node*>::Element *E=owned.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = owned.front(); E; E = E->next()) {
owners.push_back(E->get());
}
-
- editor_data->get_undo_redo().add_do_method(n->get_parent(),"remove_child",n);
- editor_data->get_undo_redo().add_undo_method(n->get_parent(),"add_child",n);
- editor_data->get_undo_redo().add_undo_method(n->get_parent(),"move_child",n,n->get_index());
- if (AnimationPlayerEditor::singleton->get_key_editor()->get_root()==n)
- editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(),"set_root",n);
- editor_data->get_undo_redo().add_undo_method(this,"_set_owners",edited_scene,owners);
+ editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n);
+ editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n);
+ editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index());
+ if (AnimationPlayerEditor::singleton->get_key_editor()->get_root() == n)
+ editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_key_editor(), "set_root", n);
+ editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners);
//editor_data->get_undo_redo().add_undo_method(n,"set_owner",n->get_owner());
editor_data->get_undo_redo().add_undo_reference(n);
ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_remove_and_keep_node",edited_scene->get_path_to(n),n->get_instance_ID());
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_restore_node",n->get_instance_ID(),edited_scene->get_path_to(n->get_parent()),n->get_index());
-
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_ID());
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_restore_node", n->get_instance_ID(), edited_scene->get_path_to(n->get_parent()), n->get_index());
}
-
-
}
editor_data->get_undo_redo().commit_action();
-
-
}
-
-
-
void SceneTreeDock::_selection_changed() {
int selection_size = EditorNode::get_singleton()->get_editor_selection()->get_selection().size();
- if (selection_size>1) {
+ if (selection_size > 1) {
//automatically turn on multi-edit
_tool_selected(TOOL_MULTI_EDIT);
}
- if (selection_size==1) {
- if(EditorNode::get_singleton()->get_editor_selection()->get_selection().front()->key()->get_script().is_null()) {
+ if (selection_size == 1) {
+ if (EditorNode::get_singleton()->get_editor_selection()->get_selection().front()->key()->get_script().is_null()) {
button_create_script->show();
button_clear_script->hide();
- }
- else {
+ } else {
button_create_script->hide();
button_clear_script->show();
}
@@ -1368,22 +1269,18 @@ void SceneTreeDock::_selection_changed() {
}
//tool_buttons[TOOL_MULTI_EDIT]->set_disabled(EditorNode::get_singleton()->get_editor_selection()->get_selection().size()<2);
-
}
-
void SceneTreeDock::_create() {
+ if (current_option == TOOL_NEW) {
- if (current_option==TOOL_NEW) {
-
- Node *parent=NULL;
-
+ Node *parent = NULL;
if (edited_scene) {
// If root exists in edited scene
parent = scene_tree->get_selected();
- if( !parent )
+ if (!parent)
parent = edited_scene;
} else {
@@ -1395,32 +1292,30 @@ void SceneTreeDock::_create() {
Object *c = create_dialog->instance_selected();
ERR_FAIL_COND(!c);
- Node *child=c->cast_to<Node>();
+ Node *child = c->cast_to<Node>();
ERR_FAIL_COND(!child);
editor_data->get_undo_redo().create_action(TTR("Create Node"));
if (edited_scene) {
- editor_data->get_undo_redo().add_do_method(parent,"add_child",child);
- editor_data->get_undo_redo().add_do_method(child,"set_owner",edited_scene);
- editor_data->get_undo_redo().add_do_method(editor_selection,"clear");
- editor_data->get_undo_redo().add_do_method(editor_selection,"add_node",child);
+ editor_data->get_undo_redo().add_do_method(parent, "add_child", child);
+ editor_data->get_undo_redo().add_do_method(child, "set_owner", edited_scene);
+ editor_data->get_undo_redo().add_do_method(editor_selection, "clear");
+ editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", child);
editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(parent,"remove_child",child);
-
+ editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child);
String new_name = parent->validate_child_name(child);
ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger();
- editor_data->get_undo_redo().add_do_method(sed,"live_debug_create_node",edited_scene->get_path_to(parent),child->get_class(),new_name);
- editor_data->get_undo_redo().add_undo_method(sed,"live_debug_remove_node",NodePath(String(edited_scene->get_path_to(parent))+"/"+new_name));
+ editor_data->get_undo_redo().add_do_method(sed, "live_debug_create_node", edited_scene->get_path_to(parent), child->get_class(), new_name);
+ editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)) + "/" + new_name));
} else {
- editor_data->get_undo_redo().add_do_method(editor,"set_edited_scene",child);
+ editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", child);
editor_data->get_undo_redo().add_do_reference(child);
- editor_data->get_undo_redo().add_undo_method(editor,"set_edited_scene",(Object*)NULL);
-
+ editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL);
}
editor_data->get_undo_redo().commit_action();
@@ -1431,31 +1326,30 @@ void SceneTreeDock::_create() {
Control *ct = c->cast_to<Control>();
Size2 ms = ct->get_minimum_size();
- if (ms.width<4)
- ms.width=40;
- if (ms.height<4)
- ms.height=40;
+ if (ms.width < 4)
+ ms.width = 40;
+ if (ms.height < 4)
+ ms.height = 40;
ct->set_size(ms);
}
-
- } else if (current_option==TOOL_REPLACE) {
- Node * n = scene_tree->get_selected();
+ } else if (current_option == TOOL_REPLACE) {
+ Node *n = scene_tree->get_selected();
ERR_FAIL_COND(!n);
Object *c = create_dialog->instance_selected();
ERR_FAIL_COND(!c);
- Node *newnode=c->cast_to<Node>();
+ Node *newnode = c->cast_to<Node>();
ERR_FAIL_COND(!newnode);
List<PropertyInfo> pinfo;
n->get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
- newnode->set(E->get().name,n->get(E->get().name));
+ newnode->set(E->get().name, n->get(E->get().name));
}
editor->push_item(NULL);
@@ -1464,41 +1358,40 @@ void SceneTreeDock::_create() {
List<MethodInfo> sl;
n->get_signal_list(&sl);
- for (List<MethodInfo>::Element *E=sl.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = sl.front(); E; E = E->next()) {
List<Object::Connection> cl;
- n->get_signal_connection_list(E->get().name,&cl);
+ n->get_signal_connection_list(E->get().name, &cl);
- for(List<Object::Connection>::Element *F=cl.front();F;F=F->next()) {
+ for (List<Object::Connection>::Element *F = cl.front(); F; F = F->next()) {
- Object::Connection &c=F->get();
- if (!(c.flags&Object::CONNECT_PERSIST))
+ Object::Connection &c = F->get();
+ if (!(c.flags & Object::CONNECT_PERSIST))
continue;
- newnode->connect(c.signal,c.target,c.method,varray(),Object::CONNECT_PERSIST);
+ newnode->connect(c.signal, c.target, c.method, varray(), Object::CONNECT_PERSIST);
}
-
}
- String newname=n->get_name();
+ String newname = n->get_name();
- List<Node*> to_erase;
- for(int i=0;i<n->get_child_count();i++) {
- if (n->get_child(i)->get_owner()==NULL && n->is_owned_by_parent()) {
+ List<Node *> to_erase;
+ for (int i = 0; i < n->get_child_count(); i++) {
+ if (n->get_child(i)->get_owner() == NULL && n->is_owned_by_parent()) {
to_erase.push_back(n->get_child(i));
}
}
- n->replace_by(newnode,true);
+ n->replace_by(newnode, true);
- if (n==edited_scene) {
- edited_scene=newnode;
+ if (n == edited_scene) {
+ edited_scene = newnode;
editor->set_edited_scene(newnode);
newnode->set_editable_instances(n->get_editable_instances());
}
//small hack to make collisionshapes and other kind of nodes to work
- for(int i=0;i<newnode->get_child_count();i++) {
- Node *c=newnode->get_child(i);
- c->call("set_transform", c->call("get_transform") );
+ for (int i = 0; i < newnode->get_child_count(); i++) {
+ Node *c = newnode->get_child(i);
+ c->call("set_transform", c->call("get_transform"));
}
editor_data->get_undo_redo().clear_history();
newnode->set_name(newname);
@@ -1507,27 +1400,21 @@ void SceneTreeDock::_create() {
memdelete(n);
- while(to_erase.front()) {
+ while (to_erase.front()) {
memdelete(to_erase.front()->get());
to_erase.pop_front();
}
-
-
-
}
-
}
+void SceneTreeDock::set_edited_scene(Node *p_scene) {
-void SceneTreeDock::set_edited_scene(Node* p_scene) {
-
- edited_scene=p_scene;
+ edited_scene = p_scene;
}
-void SceneTreeDock::set_selected(Node *p_node, bool p_emit_selected ) {
-
- scene_tree->set_selected(p_node,p_emit_selected);
+void SceneTreeDock::set_selected(Node *p_node, bool p_emit_selected) {
+ scene_tree->set_selected(p_node, p_emit_selected);
}
void SceneTreeDock::import_subscene() {
@@ -1537,17 +1424,16 @@ void SceneTreeDock::import_subscene() {
void SceneTreeDock::_import_subscene() {
- Node* parent = scene_tree->get_selected();
+ Node *parent = scene_tree->get_selected();
if (!parent) {
parent = editor_data->get_edited_scene_root();
ERR_FAIL_COND(!parent);
}
- import_subscene_dialog->move(parent,edited_scene);
+ import_subscene_dialog->move(parent, edited_scene);
editor_data->get_undo_redo().clear_history(); //no undo for now..
-
-/*
+ /*
editor_data->get_undo_redo().create_action("Import Subscene");
editor_data->get_undo_redo().add_do_method(parent,"add_child",ss);
//editor_data->get_undo_redo().add_do_method(editor_selection,"clear");
@@ -1560,9 +1446,9 @@ void SceneTreeDock::_import_subscene() {
void SceneTreeDock::_new_scene_from(String p_file) {
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
- if (selection.size()!=1) {
+ if (selection.size() != 1) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("This operation requires a single selected node."));
accept->popup_centered_minsize();
@@ -1571,33 +1457,32 @@ void SceneTreeDock::_new_scene_from(String p_file) {
Node *base = selection.front()->get();
- Map<Node*,Node*> reown;
- reown[editor_data->get_edited_scene_root()]=base;
+ Map<Node *, Node *> reown;
+ reown[editor_data->get_edited_scene_root()] = base;
Node *copy = base->duplicate_and_reown(reown);
if (copy) {
- Ref<PackedScene> sdata = memnew( PackedScene );
+ Ref<PackedScene> sdata = memnew(PackedScene);
Error err = sdata->pack(copy);
memdelete(copy);
- if (err!=OK) {
+ if (err != OK) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Couldn't save new scene. Likely dependencies (instances) couldn't be satisfied."));
accept->popup_centered_minsize();
return;
}
- int flg=0;
+ int flg = 0;
if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources"))
- flg|=ResourceSaver::FLAG_COMPRESS;
+ flg |= ResourceSaver::FLAG_COMPRESS;
/*
if (EditorSettings::get_singleton()->get("filesystem/on_save/save_paths_as_relative"))
flg|=ResourceSaver::FLAG_RELATIVE_PATHS;
*/
-
- err = ResourceSaver::save(p_file,sdata,flg);
- if (err!=OK) {
+ err = ResourceSaver::save(p_file, sdata, flg);
+ if (err != OK) {
accept->get_ok()->set_text(TTR("I see.."));
accept->set_text(TTR("Error saving scene."));
accept->popup_centered_minsize();
@@ -1610,29 +1495,27 @@ void SceneTreeDock::_new_scene_from(String p_file) {
accept->popup_centered_minsize();
return;
}
-
}
-static bool _is_node_visible(Node* p_node) {
+static bool _is_node_visible(Node *p_node) {
if (!p_node->get_owner())
return false;
- if (p_node->get_owner()!=EditorNode::get_singleton()->get_edited_scene() && !EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node->get_owner()))
+ if (p_node->get_owner() != EditorNode::get_singleton()->get_edited_scene() && !EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node->get_owner()))
return false;
return true;
-
}
-static bool _has_visible_children(Node* p_node) {
+static bool _has_visible_children(Node *p_node) {
bool collapsed = p_node->is_displayed_folded();
if (collapsed)
return false;
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- Node* child = p_node->get_child(i);
+ Node *child = p_node->get_child(i);
if (!_is_node_visible(child))
continue;
@@ -1640,87 +1523,76 @@ static bool _has_visible_children(Node* p_node) {
}
return false;
-
}
+static Node *_find_last_visible(Node *p_node) {
-
-static Node* _find_last_visible(Node* p_node) {
-
- Node* last=NULL;
+ Node *last = NULL;
bool collapsed = p_node->is_displayed_folded();
- if (!collapsed) {
- for(int i=0;i<p_node->get_child_count();i++) {
+ if (!collapsed) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
if (_is_node_visible(p_node->get_child(i))) {
- last=p_node->get_child(i);
+ last = p_node->get_child(i);
}
}
}
if (last) {
- Node* lastc=_find_last_visible(last);
+ Node *lastc = _find_last_visible(last);
if (lastc)
- last=lastc;
-
+ last = lastc;
} else {
- last=p_node;
+ last = p_node;
}
return last;
}
+void SceneTreeDock::_normalize_drop(Node *&to_node, int &to_pos, int p_type) {
-void SceneTreeDock::_normalize_drop(Node*& to_node, int &to_pos, int p_type) {
-
- to_pos=-1;
+ to_pos = -1;
- if (p_type==-1) {
+ if (p_type == -1) {
//drop at above selected node
- if (to_node==EditorNode::get_singleton()->get_edited_scene()) {
- to_node=NULL;
+ if (to_node == EditorNode::get_singleton()->get_edited_scene()) {
+ to_node = NULL;
ERR_EXPLAIN("Cannot perform drop above the root node!");
ERR_FAIL();
}
- to_pos=to_node->get_index();
- to_node=to_node->get_parent();
-
- } else if (p_type==1) {
- //drop at below selected node
- if (to_node==EditorNode::get_singleton()->get_edited_scene()) {
- //if at lower sibling of root node
- to_pos=0; //just insert at begining of root node
- return;
- }
-
-
- Node* lower_sibling=NULL;
-
+ to_pos = to_node->get_index();
+ to_node = to_node->get_parent();
+ } else if (p_type == 1) {
+ //drop at below selected node
+ if (to_node == EditorNode::get_singleton()->get_edited_scene()) {
+ //if at lower sibling of root node
+ to_pos = 0; //just insert at begining of root node
+ return;
+ }
- if (_has_visible_children(to_node) ) {
- to_pos=0;
- } else {
+ Node *lower_sibling = NULL;
+ if (_has_visible_children(to_node)) {
+ to_pos = 0;
+ } else {
- for(int i=to_node->get_index()+1;i<to_node->get_parent()->get_child_count();i++) {
- Node *c =to_node->get_parent()->get_child(i);
- if (_is_node_visible(c)) {
- lower_sibling=c;
- break;
- }
- }
- if (lower_sibling) {
- to_pos=lower_sibling->get_index();
+ for (int i = to_node->get_index() + 1; i < to_node->get_parent()->get_child_count(); i++) {
+ Node *c = to_node->get_parent()->get_child(i);
+ if (_is_node_visible(c)) {
+ lower_sibling = c;
+ break;
}
-
- to_node=to_node->get_parent();
-
-
}
+ if (lower_sibling) {
+ to_pos = lower_sibling->get_index();
+ }
+
+ to_node = to_node->get_parent();
+ }
#if 0
//quite complicated, look for next visible in tree
upper_sibling=_find_last_visible(upper_sibling);
@@ -1741,19 +1613,17 @@ void SceneTreeDock::_normalize_drop(Node*& to_node, int &to_pos, int p_type) {
to_node=to_node->get_parent();
}
#endif
-
}
-
}
-void SceneTreeDock::_files_dropped(Vector<String> p_files,NodePath p_to,int p_type) {
+void SceneTreeDock::_files_dropped(Vector<String> p_files, NodePath p_to, int p_type) {
Node *node = get_node(p_to);
ERR_FAIL_COND(!node);
- int to_pos=-1;
- _normalize_drop(node,to_pos,p_type);
- _perform_instance_scenes(p_files,node,to_pos);
+ int to_pos = -1;
+ _normalize_drop(node, to_pos, p_type);
+ _perform_instance_scenes(p_files, node, to_pos);
}
void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) {
@@ -1765,58 +1635,56 @@ void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) {
}
}
-void SceneTreeDock::_nodes_dragged(Array p_nodes,NodePath p_to,int p_type) {
+void SceneTreeDock::_nodes_dragged(Array p_nodes, NodePath p_to, int p_type) {
- Vector<Node*> nodes;
+ Vector<Node *> nodes;
Node *to_node;
- for(int i=0;i<p_nodes.size();i++) {
- Node *n=get_node((p_nodes[i]));
+ for (int i = 0; i < p_nodes.size(); i++) {
+ Node *n = get_node((p_nodes[i]));
if (n) {
nodes.push_back(n);
}
}
- if (nodes.size()==0)
+ if (nodes.size() == 0)
return;
- to_node=get_node(p_to);
+ to_node = get_node(p_to);
if (!to_node)
return;
- int to_pos=-1;
-
- _normalize_drop(to_node,to_pos,p_type);
- _do_reparent(to_node,to_pos,nodes,true);
+ int to_pos = -1;
+ _normalize_drop(to_node, to_pos, p_type);
+ _do_reparent(to_node, to_pos, nodes, true);
}
-void SceneTreeDock::_tree_rmb(const Vector2& p_menu_pos) {
+void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) {
if (!EditorNode::get_singleton()->get_edited_scene()) {
menu->clear();
- menu->add_icon_shortcut(get_icon("Add","EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
- menu->add_icon_shortcut(get_icon("Instance","EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
+ menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
+ menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
- menu->set_size(Size2(1,1));
+ menu->set_size(Size2(1, 1));
menu->set_pos(p_menu_pos);
menu->popup();
return;
}
- List<Node*> selection = editor_selection->get_selected_node_list();
+ List<Node *> selection = editor_selection->get_selected_node_list();
- if (selection.size()==0)
+ if (selection.size() == 0)
return;
menu->clear();
-
- if (selection.size()==1) {
- menu->add_icon_shortcut(get_icon("Add","EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
- menu->add_icon_shortcut(get_icon("Instance","EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
+ if (selection.size() == 1) {
+ menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW);
+ menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE);
menu->add_separator();
- menu->add_icon_shortcut(get_icon("Reload","EditorIcons"),ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE);
+ menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE);
//menu->add_separator(); moved to their own dock
//menu->add_icon_item(get_icon("Groups","EditorIcons"),TTR("Edit Groups"),TOOL_GROUP);
//menu->add_icon_item(get_icon("Connect","EditorIcons"),TTR("Edit Connections"),TOOL_CONNECT);
@@ -1826,28 +1694,26 @@ void SceneTreeDock::_tree_rmb(const Vector2& p_menu_pos) {
menu->add_separator();
}
- menu->add_icon_shortcut(get_icon("Up","EditorIcons"),ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP);
- menu->add_icon_shortcut(get_icon("Down","EditorIcons"),ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN);
- menu->add_icon_shortcut(get_icon("Duplicate","EditorIcons"),ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE);
- menu->add_icon_shortcut(get_icon("Reparent","EditorIcons"),ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT);
+ menu->add_icon_shortcut(get_icon("Up", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP);
+ menu->add_icon_shortcut(get_icon("Down", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN);
+ menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE);
+ menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT);
- if (selection.size()==1) {
+ if (selection.size() == 1) {
menu->add_separator();
- menu->add_icon_shortcut(get_icon("Blend","EditorIcons"),ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE);
- menu->add_icon_shortcut(get_icon("CreateNewSceneFrom","EditorIcons"),ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM);
+ menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE);
+ menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM);
menu->add_separator();
- menu->add_icon_shortcut(get_icon("CopyNodePath","EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH);
+ menu->add_icon_shortcut(get_icon("CopyNodePath", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH);
}
menu->add_separator();
- menu->add_icon_shortcut(get_icon("Remove","EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE);
- menu->set_size(Size2(1,1));
+ menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE);
+ menu->set_size(Size2(1, 1));
menu->set_pos(p_menu_pos);
menu->popup();
-
}
-
-void SceneTreeDock::_filter_changed(const String& p_filter) {
+void SceneTreeDock::_filter_changed(const String &p_filter) {
scene_tree->set_filter(p_filter);
}
@@ -1857,13 +1723,12 @@ String SceneTreeDock::get_filter() {
return filter->get_text();
}
-void SceneTreeDock::set_filter(const String& p_filter){
+void SceneTreeDock::set_filter(const String &p_filter) {
filter->set_text(p_filter);
scene_tree->set_filter(p_filter);
}
-
void SceneTreeDock::_focus_node() {
Node *node = scene_tree->get_selected();
@@ -1878,105 +1743,99 @@ void SceneTreeDock::_focus_node() {
}
}
-void SceneTreeDock::open_script_dialog(Node* p_for_node) {
+void SceneTreeDock::open_script_dialog(Node *p_for_node) {
- scene_tree->set_selected(p_for_node,false);
+ scene_tree->set_selected(p_for_node, false);
_tool_selected(TOOL_ATTACH_SCRIPT);
}
void SceneTreeDock::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_tool_selected"),&SceneTreeDock::_tool_selected,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("_create"),&SceneTreeDock::_create);
+ ClassDB::bind_method(D_METHOD("_tool_selected"), &SceneTreeDock::_tool_selected, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("_create"), &SceneTreeDock::_create);
//ClassDB::bind_method(D_METHOD("_script_created"),&SceneTreeDock::_script_created);
- ClassDB::bind_method(D_METHOD("_node_reparent"),&SceneTreeDock::_node_reparent);
- ClassDB::bind_method(D_METHOD("_set_owners"),&SceneTreeDock::_set_owners);
- ClassDB::bind_method(D_METHOD("_node_selected"),&SceneTreeDock::_node_selected);
- ClassDB::bind_method(D_METHOD("_node_renamed"),&SceneTreeDock::_node_renamed);
- ClassDB::bind_method(D_METHOD("_script_created"),&SceneTreeDock::_script_created);
- ClassDB::bind_method(D_METHOD("_load_request"),&SceneTreeDock::_load_request);
- ClassDB::bind_method(D_METHOD("_script_open_request"),&SceneTreeDock::_script_open_request);
- ClassDB::bind_method(D_METHOD("_unhandled_key_input"),&SceneTreeDock::_unhandled_key_input);
- ClassDB::bind_method(D_METHOD("_input"),&SceneTreeDock::_input);
- ClassDB::bind_method(D_METHOD("_nodes_drag_begin"),&SceneTreeDock::_nodes_drag_begin);
- ClassDB::bind_method(D_METHOD("_delete_confirm"),&SceneTreeDock::_delete_confirm);
- ClassDB::bind_method(D_METHOD("_node_prerenamed"),&SceneTreeDock::_node_prerenamed);
- ClassDB::bind_method(D_METHOD("_import_subscene"),&SceneTreeDock::_import_subscene);
- ClassDB::bind_method(D_METHOD("_selection_changed"),&SceneTreeDock::_selection_changed);
- ClassDB::bind_method(D_METHOD("_new_scene_from"),&SceneTreeDock::_new_scene_from);
- ClassDB::bind_method(D_METHOD("_nodes_dragged"),&SceneTreeDock::_nodes_dragged);
- ClassDB::bind_method(D_METHOD("_files_dropped"),&SceneTreeDock::_files_dropped);
- ClassDB::bind_method(D_METHOD("_script_dropped"),&SceneTreeDock::_script_dropped);
- ClassDB::bind_method(D_METHOD("_tree_rmb"),&SceneTreeDock::_tree_rmb);
- ClassDB::bind_method(D_METHOD("_filter_changed"),&SceneTreeDock::_filter_changed);
- ClassDB::bind_method(D_METHOD("_focus_node"),&SceneTreeDock::_focus_node);
-
-
- ClassDB::bind_method(D_METHOD("instance"),&SceneTreeDock::instance);
+ ClassDB::bind_method(D_METHOD("_node_reparent"), &SceneTreeDock::_node_reparent);
+ ClassDB::bind_method(D_METHOD("_set_owners"), &SceneTreeDock::_set_owners);
+ ClassDB::bind_method(D_METHOD("_node_selected"), &SceneTreeDock::_node_selected);
+ ClassDB::bind_method(D_METHOD("_node_renamed"), &SceneTreeDock::_node_renamed);
+ ClassDB::bind_method(D_METHOD("_script_created"), &SceneTreeDock::_script_created);
+ ClassDB::bind_method(D_METHOD("_load_request"), &SceneTreeDock::_load_request);
+ ClassDB::bind_method(D_METHOD("_script_open_request"), &SceneTreeDock::_script_open_request);
+ ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &SceneTreeDock::_unhandled_key_input);
+ ClassDB::bind_method(D_METHOD("_input"), &SceneTreeDock::_input);
+ ClassDB::bind_method(D_METHOD("_nodes_drag_begin"), &SceneTreeDock::_nodes_drag_begin);
+ ClassDB::bind_method(D_METHOD("_delete_confirm"), &SceneTreeDock::_delete_confirm);
+ ClassDB::bind_method(D_METHOD("_node_prerenamed"), &SceneTreeDock::_node_prerenamed);
+ ClassDB::bind_method(D_METHOD("_import_subscene"), &SceneTreeDock::_import_subscene);
+ ClassDB::bind_method(D_METHOD("_selection_changed"), &SceneTreeDock::_selection_changed);
+ ClassDB::bind_method(D_METHOD("_new_scene_from"), &SceneTreeDock::_new_scene_from);
+ ClassDB::bind_method(D_METHOD("_nodes_dragged"), &SceneTreeDock::_nodes_dragged);
+ ClassDB::bind_method(D_METHOD("_files_dropped"), &SceneTreeDock::_files_dropped);
+ ClassDB::bind_method(D_METHOD("_script_dropped"), &SceneTreeDock::_script_dropped);
+ ClassDB::bind_method(D_METHOD("_tree_rmb"), &SceneTreeDock::_tree_rmb);
+ ClassDB::bind_method(D_METHOD("_filter_changed"), &SceneTreeDock::_filter_changed);
+ ClassDB::bind_method(D_METHOD("_focus_node"), &SceneTreeDock::_focus_node);
+
+ ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance);
}
+SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSelection *p_editor_selection, EditorData &p_editor_data) {
-
-SceneTreeDock::SceneTreeDock(EditorNode *p_editor,Node *p_scene_root,EditorSelection *p_editor_selection,EditorData &p_editor_data) {
-
- editor=p_editor;
- edited_scene=NULL;
- editor_data=&p_editor_data;
- editor_selection=p_editor_selection;
- scene_root=p_scene_root;
+ editor = p_editor;
+ edited_scene = NULL;
+ editor_data = &p_editor_data;
+ editor_selection = p_editor_selection;
+ scene_root = p_scene_root;
VBoxContainer *vbc = this;
- HBoxContainer *filter_hbc = memnew( HBoxContainer );
+ HBoxContainer *filter_hbc = memnew(HBoxContainer);
ToolButton *tb;
- ED_SHORTCUT("scene_tree/add_child_node",TTR("Add Child Node"), KEY_MASK_CMD|KEY_A);
- ED_SHORTCUT("scene_tree/instance_scene",TTR("Instance Child Scene"));
+ ED_SHORTCUT("scene_tree/add_child_node", TTR("Add Child Node"), KEY_MASK_CMD | KEY_A);
+ ED_SHORTCUT("scene_tree/instance_scene", TTR("Instance Child Scene"));
ED_SHORTCUT("scene_tree/change_node_type", TTR("Change Type"));
ED_SHORTCUT("scene_tree/attach_script", TTR("Attach Script"));
ED_SHORTCUT("scene_tree/clear_script", TTR("Clear Script"));
ED_SHORTCUT("scene_tree/move_up", TTR("Move Up"), KEY_MASK_CMD | KEY_UP);
ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN);
- ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"),KEY_MASK_CMD | KEY_D);
+ ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"), KEY_MASK_CMD | KEY_D);
ED_SHORTCUT("scene_tree/reparent", TTR("Reparent"));
ED_SHORTCUT("scene_tree/merge_from_scene", TTR("Merge From Scene"));
ED_SHORTCUT("scene_tree/save_branch_as_scene", TTR("Save Branch as Scene"));
- ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD|KEY_C);
- ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT|KEY_DELETE);
+ ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD | KEY_C);
+ ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT | KEY_DELETE);
ED_SHORTCUT("scene_tree/delete", TTR("Delete"), KEY_DELETE);
- tb = memnew( ToolButton );
- tb->connect("pressed",this,"_tool_selected",make_binds(TOOL_NEW, false));
+ tb = memnew(ToolButton);
+ tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false));
tb->set_tooltip(TTR("Add/Create a New Node"));
tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node"));
filter_hbc->add_child(tb);
- button_add=tb;
+ button_add = tb;
- tb = memnew( ToolButton );
- tb->connect("pressed",this,"_tool_selected",make_binds(TOOL_INSTANCE, false));
+ tb = memnew(ToolButton);
+ tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false));
tb->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists."));
tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene"));
filter_hbc->add_child(tb);
- button_instance=tb;
-
-
+ button_instance = tb;
vbc->add_child(filter_hbc);
- filter = memnew( LineEdit );
+ filter = memnew(LineEdit);
filter->set_h_size_flags(SIZE_EXPAND_FILL);
filter_hbc->add_child(filter);
- filter_icon = memnew( TextureRect );
+ filter_icon = memnew(TextureRect);
filter_hbc->add_child(filter_icon);
filter_icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
- filter->connect("text_changed",this,"_filter_changed");
+ filter->connect("text_changed", this, "_filter_changed");
-
- tb = memnew( ToolButton );
- tb->connect("pressed",this,"_tool_selected",make_binds(TOOL_ATTACH_SCRIPT, false));
+ tb = memnew(ToolButton);
+ tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false));
tb->set_tooltip(TTR("Attach a new or existing script for the selected node."));
tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script"));
filter_hbc->add_child(tb);
- button_create_script=tb;
+ button_create_script = tb;
tb = memnew(ToolButton);
tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false));
@@ -1985,32 +1844,30 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor,Node *p_scene_root,EditorSelec
filter_hbc->add_child(tb);
button_clear_script = tb;
-
- scene_tree = memnew( SceneTreeEditor(false,true,true ));
+ scene_tree = memnew(SceneTreeEditor(false, true, true));
vbc->add_child(scene_tree);
- scene_tree->set_v_size_flags(SIZE_EXPAND|SIZE_FILL);
- scene_tree->connect("rmb_pressed",this,"_tree_rmb");
-
- scene_tree->connect("node_selected", this,"_node_selected",varray(),CONNECT_DEFERRED);
- scene_tree->connect("node_renamed", this,"_node_renamed",varray(),CONNECT_DEFERRED);
- scene_tree->connect("node_prerename", this,"_node_prerenamed");
- scene_tree->connect("open",this,"_load_request");
- scene_tree->connect("open_script",this,"_script_open_request");
- scene_tree->connect("nodes_rearranged",this,"_nodes_dragged");
- scene_tree->connect("files_dropped",this,"_files_dropped");
- scene_tree->connect("script_dropped",this,"_script_dropped");
- scene_tree->connect("nodes_dragged",this,"_nodes_drag_begin");
+ scene_tree->set_v_size_flags(SIZE_EXPAND | SIZE_FILL);
+ scene_tree->connect("rmb_pressed", this, "_tree_rmb");
+
+ scene_tree->connect("node_selected", this, "_node_selected", varray(), CONNECT_DEFERRED);
+ scene_tree->connect("node_renamed", this, "_node_renamed", varray(), CONNECT_DEFERRED);
+ scene_tree->connect("node_prerename", this, "_node_prerenamed");
+ scene_tree->connect("open", this, "_load_request");
+ scene_tree->connect("open_script", this, "_script_open_request");
+ scene_tree->connect("nodes_rearranged", this, "_nodes_dragged");
+ scene_tree->connect("files_dropped", this, "_files_dropped");
+ scene_tree->connect("script_dropped", this, "_script_dropped");
+ scene_tree->connect("nodes_dragged", this, "_nodes_drag_begin");
scene_tree->get_scene_tree()->connect("item_double_clicked", this, "_focus_node");
scene_tree->set_undo_redo(&editor_data->get_undo_redo());
scene_tree->set_editor_selection(editor_selection);
-
- create_dialog = memnew( CreateDialog );
+ create_dialog = memnew(CreateDialog);
create_dialog->set_base_type("Node");
add_child(create_dialog);
- create_dialog->connect("create",this,"_create");
+ create_dialog->connect("create", this, "_create");
//groups_editor = memnew( GroupsEditor );
//add_child(groups_editor);
@@ -2020,42 +1877,41 @@ SceneTreeDock::SceneTreeDock(EditorNode *p_editor,Node *p_scene_root,EditorSelec
//add_child(connect_dialog);
//connect_dialog->set_undoredo(&editor_data->get_undo_redo());
- script_create_dialog = memnew( ScriptCreateDialog );
+ script_create_dialog = memnew(ScriptCreateDialog);
add_child(script_create_dialog);
- script_create_dialog->connect("script_created",this,"_script_created");
+ script_create_dialog->connect("script_created", this, "_script_created");
- reparent_dialog = memnew( ReparentDialog );
+ reparent_dialog = memnew(ReparentDialog);
add_child(reparent_dialog);
- reparent_dialog->connect("reparent",this,"_node_reparent");
+ reparent_dialog->connect("reparent", this, "_node_reparent");
- accept = memnew( AcceptDialog );
+ accept = memnew(AcceptDialog);
add_child(accept);
- file = memnew( EditorFileDialog );
+ file = memnew(EditorFileDialog);
add_child(file);
- file->connect("file_selected",this,"instance");
+ file->connect("file_selected", this, "instance");
set_process_unhandled_key_input(true);
- delete_dialog = memnew( ConfirmationDialog );
+ delete_dialog = memnew(ConfirmationDialog);
add_child(delete_dialog);
- delete_dialog->connect("confirmed",this,"_delete_confirm");
+ delete_dialog->connect("confirmed", this, "_delete_confirm");
- import_subscene_dialog = memnew( EditorSubScene );
+ import_subscene_dialog = memnew(EditorSubScene);
add_child(import_subscene_dialog);
- import_subscene_dialog->connect("subscene_selected",this,"_import_subscene");
+ import_subscene_dialog->connect("subscene_selected", this, "_import_subscene");
- new_scene_from_dialog = memnew( EditorFileDialog );
+ new_scene_from_dialog = memnew(EditorFileDialog);
new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE);
add_child(new_scene_from_dialog);
- new_scene_from_dialog->connect("file_selected",this,"_new_scene_from");
-
+ new_scene_from_dialog->connect("file_selected", this, "_new_scene_from");
- menu = memnew( PopupMenu );
+ menu = memnew(PopupMenu);
add_child(menu);
- menu->connect("id_pressed",this,"_tool_selected");
- first_enter=true;
- restore_script_editor_on_drag=false;
+ menu->connect("id_pressed", this, "_tool_selected");
+ first_enter = true;
+ restore_script_editor_on_drag = false;
- vbc->add_constant_override("separation",4);
+ vbc->add_constant_override("separation", 4);
set_process_input(true);
}
diff --git a/editor/scene_tree_dock.h b/editor/scene_tree_dock.h
index 2ee7ba3d06..b43a6ea9b1 100644
--- a/editor/scene_tree_dock.h
+++ b/editor/scene_tree_dock.h
@@ -29,27 +29,27 @@
#ifndef SCENE_TREE_DOCK_H
#define SCENE_TREE_DOCK_H
-#include "scene/gui/control.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/label.h"
-#include "scene/gui/button.h"
-#include "scene/gui/tool_button.h"
-#include "scene/gui/box_container.h"
-#include "scene/gui/popup_menu.h"
-#include "scene_tree_editor.h"
+#include "connections_dialog.h"
#include "create_dialog.h"
#include "editor_data.h"
+#include "editor_sub_scene.h"
#include "groups_editor.h"
-#include "connections_dialog.h"
-#include "script_create_dialog.h"
#include "reparent_dialog.h"
#include "scene/animation/animation_player.h"
-#include "editor_sub_scene.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
+#include "scene/gui/control.h"
+#include "scene/gui/label.h"
+#include "scene/gui/popup_menu.h"
+#include "scene/gui/tool_button.h"
+#include "scene/gui/tree.h"
+#include "scene_tree_editor.h"
+#include "script_create_dialog.h"
class EditorNode;
class SceneTreeDock : public VBoxContainer {
- GDCLASS( SceneTreeDock, VBoxContainer );
+ GDCLASS(SceneTreeDock, VBoxContainer);
enum Tool {
@@ -72,7 +72,6 @@ class SceneTreeDock : public VBoxContainer {
TOOL_BUTTON_MAX
};
-
bool restore_script_editor_on_drag;
int current_option;
@@ -105,7 +104,7 @@ class SceneTreeDock : public VBoxContainer {
LineEdit *filter;
TextureRect *filter_icon;
- PopupMenu * menu;
+ PopupMenu *menu;
bool first_enter;
@@ -114,15 +113,15 @@ class SceneTreeDock : public VBoxContainer {
Node *edited_scene;
EditorNode *editor;
- Node *_duplicate(Node *p_node, Map<Node*,Node*> &duplimap);
+ Node *_duplicate(Node *p_node, Map<Node *, Node *> &duplimap);
void _node_reparent(NodePath p_path, bool p_keep_global_xform);
- void _do_reparent(Node* p_new_parent, int p_position_in_parent, Vector<Node*> p_nodes, bool p_keep_global_xform);
+ void _do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform);
- void _set_owners(Node *p_owner, const Array& p_nodes);
- void _load_request(const String& p_path);
- void _script_open_request(const Ref<Script>& p_script);
+ void _set_owners(Node *p_owner, const Array &p_nodes);
+ void _load_request(const String &p_path);
+ void _script_open_request(const Ref<Script> &p_script);
- bool _cyclical_dependency_exists(const String& p_target_scene_path, Node* p_desired_node);
+ bool _cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node);
void _node_selected();
void _node_renamed();
@@ -130,8 +129,7 @@ class SceneTreeDock : public VBoxContainer {
void _delete_confirm();
-
- void _node_prerenamed(Node* p_node, const String& p_new_name);
+ void _node_prerenamed(Node *p_node, const String &p_new_name);
void _nodes_drag_begin();
void _input(InputEvent p_event);
@@ -144,45 +142,45 @@ class SceneTreeDock : public VBoxContainer {
bool _validate_no_foreign();
void _selection_changed();
- void _fill_path_renames(Vector<StringName> base_path,Vector<StringName> new_base_path,Node * p_node, List<Pair<NodePath,NodePath> > *p_renames);
+ void _fill_path_renames(Vector<StringName> base_path, Vector<StringName> new_base_path, Node *p_node, List<Pair<NodePath, NodePath> > *p_renames);
- void _normalize_drop(Node*& to_node, int &to_pos, int p_type);
+ void _normalize_drop(Node *&to_node, int &to_pos, int p_type);
- void _nodes_dragged(Array p_nodes,NodePath p_to,int p_type);
- void _files_dropped(Vector<String> p_files,NodePath p_to,int p_type);
+ void _nodes_dragged(Array p_nodes, NodePath p_to, int p_type);
+ void _files_dropped(Vector<String> p_files, NodePath p_to, int p_type);
void _script_dropped(String p_file, NodePath p_to);
- void _tree_rmb(const Vector2& p_menu_pos);
+ void _tree_rmb(const Vector2 &p_menu_pos);
- void _filter_changed(const String& p_filter);
+ void _filter_changed(const String &p_filter);
- void _perform_instance_scenes(const Vector<String>& p_files,Node* parent,int p_pos);
- void _replace_with_branch_scene(const String& p_file,Node* base);
+ void _perform_instance_scenes(const Vector<String> &p_files, Node *parent, int p_pos);
+ void _replace_with_branch_scene(const String &p_file, Node *base);
void _file_selected(String p_file);
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
String get_filter();
- void set_filter(const String& p_filter);
+ void set_filter(const String &p_filter);
void _focus_node();
void import_subscene();
- void set_edited_scene(Node* p_scene);
- void instance(const String& p_path);
- void instance_scenes(const Vector<String>& p_files, Node *p_parent=NULL);
- void set_selected(Node *p_node, bool p_emit_selected=false);
- void fill_path_renames(Node* p_node, Node *p_new_parent, List<Pair<NodePath,NodePath> > *p_renames);
- void perform_node_renames(Node* p_base,List<Pair<NodePath,NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims=NULL);
+ void set_edited_scene(Node *p_scene);
+ void instance(const String &p_path);
+ void instance_scenes(const Vector<String> &p_files, Node *p_parent = NULL);
+ void set_selected(Node *p_node, bool p_emit_selected = false);
+ void fill_path_renames(Node *p_node, Node *p_new_parent, List<Pair<NodePath, NodePath> > *p_renames);
+ void perform_node_renames(Node *p_base, List<Pair<NodePath, NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims = NULL);
SceneTreeEditor *get_tree_editor() { return scene_tree; }
EditorData *get_editor_data() { return editor_data; }
- void open_script_dialog(Node* p_for_node);
- SceneTreeDock(EditorNode *p_editor,Node *p_scene_root,EditorSelection *p_editor_selection,EditorData &p_editor_data);
+ void open_script_dialog(Node *p_for_node);
+ SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSelection *p_editor_selection, EditorData &p_editor_data);
};
#endif // SCENE_TREE_DOCK_H
diff --git a/editor/scene_tree_editor.cpp b/editor/scene_tree_editor.cpp
index fb21747ebb..3310405ae9 100644
--- a/editor/scene_tree_editor.cpp
+++ b/editor/scene_tree_editor.cpp
@@ -28,22 +28,21 @@
/*************************************************************************/
#include "scene_tree_editor.h"
-#include "scene/gui/label.h"
+#include "editor/plugins/canvas_item_editor_plugin.h"
#include "editor_node.h"
-#include "print_string.h"
#include "message_queue.h"
+#include "print_string.h"
+#include "scene/gui/label.h"
#include "scene/main/viewport.h"
-#include "editor/plugins/canvas_item_editor_plugin.h"
#include "scene/resources/packed_scene.h"
Node *SceneTreeEditor::get_scene_node() {
- ERR_FAIL_COND_V(!is_inside_tree(),NULL);
+ ERR_FAIL_COND_V(!is_inside_tree(), NULL);
return get_tree()->get_edited_scene_root();
}
-
void SceneTreeEditor::_subscene_option(int p_idx) {
Object *obj = ObjectDB::get_instance(instance_node);
@@ -53,7 +52,7 @@ void SceneTreeEditor::_subscene_option(int p_idx) {
if (!node)
return;
- switch(p_idx) {
+ switch (p_idx) {
case SCENE_MENU_EDITABLE_CHILDREN: {
@@ -61,11 +60,11 @@ void SceneTreeEditor::_subscene_option(int p_idx) {
editable = !editable;
//node->set_instance_children_editable(editable);
- EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node,editable);
- instance_menu->set_item_checked(0,editable);
+ EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, editable);
+ instance_menu->set_item_checked(0, editable);
if (editable) {
node->set_scene_instance_load_placeholder(false);
- instance_menu->set_item_checked(1,false);
+ instance_menu->set_item_checked(1, false);
}
_update_tree();
@@ -78,48 +77,46 @@ void SceneTreeEditor::_subscene_option(int p_idx) {
//node->set_instance_children_editable(editable);
if (placeholder) {
- EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node,false);
+ EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, false);
}
node->set_scene_instance_load_placeholder(placeholder);
- instance_menu->set_item_checked(0,false);
- instance_menu->set_item_checked(1,placeholder);
+ instance_menu->set_item_checked(0, false);
+ instance_menu->set_item_checked(1, placeholder);
_update_tree();
} break;
case SCENE_MENU_OPEN: {
- emit_signal("open",node->get_filename());
+ emit_signal("open", node->get_filename());
} break;
case SCENE_MENU_CLEAR_INHERITANCE: {
clear_inherit_confirm->popup_centered_minsize();
} break;
case SCENE_MENU_CLEAR_INSTANCING: {
- Node*root=EditorNode::get_singleton()->get_edited_scene();
+ Node *root = EditorNode::get_singleton()->get_edited_scene();
if (!root)
break;
-
- ERR_FAIL_COND(node->get_filename()==String());
+ ERR_FAIL_COND(node->get_filename() == String());
undo_redo->create_action("Discard Instancing");
- undo_redo->add_do_method(node,"set_filename","");
- undo_redo->add_undo_method(node,"set_filename",node->get_filename());
+ undo_redo->add_do_method(node, "set_filename", "");
+ undo_redo->add_undo_method(node, "set_filename", node->get_filename());
- _node_replace_owner(node,node,root);
+ _node_replace_owner(node, node, root);
- undo_redo->add_do_method(this,"update_tree");
- undo_redo->add_undo_method(this,"update_tree");
+ undo_redo->add_do_method(this, "update_tree");
+ undo_redo->add_undo_method(this, "update_tree");
undo_redo->commit_action();
-
} break;
case SCENE_MENU_OPEN_INHERITED: {
if (node && node->get_scene_inherited_state().is_valid()) {
- emit_signal("open",node->get_scene_inherited_state()->get_path());
+ emit_signal("open", node->get_scene_inherited_state()->get_path());
}
} break;
case SCENE_MENU_CLEAR_INHERITANCE_CONFIRM: {
@@ -130,100 +127,94 @@ void SceneTreeEditor::_subscene_option(int p_idx) {
}
} break;
-
-
}
-
}
+void SceneTreeEditor::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root) {
-void SceneTreeEditor::_node_replace_owner(Node* p_base,Node* p_node,Node* p_root) {
+ if (p_base != p_node) {
- if (p_base!=p_node) {
+ if (p_node->get_owner() == p_base) {
- if (p_node->get_owner()==p_base) {
-
- undo_redo->add_do_method(p_node,"set_owner",p_root);
- undo_redo->add_undo_method(p_node,"set_owner",p_base);
+ undo_redo->add_do_method(p_node, "set_owner", p_root);
+ undo_redo->add_undo_method(p_node, "set_owner", p_base);
}
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- _node_replace_owner(p_base,p_node->get_child(i),p_root);
+ _node_replace_owner(p_base, p_node->get_child(i), p_root);
}
}
+void SceneTreeEditor::_cell_button_pressed(Object *p_item, int p_column, int p_id) {
-void SceneTreeEditor::_cell_button_pressed(Object *p_item,int p_column,int p_id) {
-
- TreeItem *item=p_item->cast_to<TreeItem>();
+ TreeItem *item = p_item->cast_to<TreeItem>();
ERR_FAIL_COND(!item);
NodePath np = item->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
ERR_FAIL_COND(!n);
- if (p_id==BUTTON_SUBSCENE) {
+ if (p_id == BUTTON_SUBSCENE) {
//open scene request
- Rect2 item_rect = tree->get_item_rect(item,0);
- item_rect.pos.y-=tree->get_scroll().y;
- item_rect.pos+=tree->get_global_pos();
+ Rect2 item_rect = tree->get_item_rect(item, 0);
+ item_rect.pos.y -= tree->get_scroll().y;
+ item_rect.pos += tree->get_global_pos();
- if (n==get_scene_node()) {
- inheritance_menu->set_pos(item_rect.pos+Vector2(0,item_rect.size.y));
- inheritance_menu->set_size(Vector2(item_rect.size.x,0));
+ if (n == get_scene_node()) {
+ inheritance_menu->set_pos(item_rect.pos + Vector2(0, item_rect.size.y));
+ inheritance_menu->set_size(Vector2(item_rect.size.x, 0));
inheritance_menu->popup();
- instance_node=n->get_instance_ID();
+ instance_node = n->get_instance_ID();
} else {
- instance_menu->set_pos(item_rect.pos+Vector2(0,item_rect.size.y));
- instance_menu->set_size(Vector2(item_rect.size.x,0));
+ instance_menu->set_pos(item_rect.pos + Vector2(0, item_rect.size.y));
+ instance_menu->set_size(Vector2(item_rect.size.x, 0));
if (EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(n))
- instance_menu->set_item_checked(0,true);
+ instance_menu->set_item_checked(0, true);
else
- instance_menu->set_item_checked(0,false);
+ instance_menu->set_item_checked(0, false);
- if (n->get_owner()==get_scene_node()) {
- instance_menu->set_item_checked(1,n->get_scene_instance_load_placeholder());
- instance_menu->set_item_disabled(1,false);
+ if (n->get_owner() == get_scene_node()) {
+ instance_menu->set_item_checked(1, n->get_scene_instance_load_placeholder());
+ instance_menu->set_item_disabled(1, false);
} else {
- instance_menu->set_item_checked(1,false);
- instance_menu->set_item_disabled(1,true);
+ instance_menu->set_item_checked(1, false);
+ instance_menu->set_item_disabled(1, true);
}
instance_menu->popup();
- instance_node=n->get_instance_ID();
+ instance_node = n->get_instance_ID();
}
//emit_signal("open",n->get_filename());
- } else if (p_id==BUTTON_SCRIPT) {
- RefPtr script=n->get_script();
+ } else if (p_id == BUTTON_SCRIPT) {
+ RefPtr script = n->get_script();
if (!script.is_null())
- emit_signal("open_script",script);
-
- } else if (p_id==BUTTON_VISIBILITY) {
+ emit_signal("open_script", script);
+ } else if (p_id == BUTTON_VISIBILITY) {
if (n->is_class("Spatial")) {
bool v = bool(n->call("is_visible"));
undo_redo->create_action(TTR("Toggle Spatial Visible"));
- undo_redo->add_do_method(n,"set_visible",!v);
- undo_redo->add_undo_method(n,"set_visible",v);
+ undo_redo->add_do_method(n, "set_visible", !v);
+ undo_redo->add_undo_method(n, "set_visible", v);
undo_redo->commit_action();
} else if (n->is_class("CanvasItem")) {
bool v = bool(n->call("is_visible"));
undo_redo->create_action(TTR("Toggle CanvasItem Visible"));
- undo_redo->add_do_method(n,v?"hide":"show");
- undo_redo->add_undo_method(n,v?"show":"hide");
+ undo_redo->add_do_method(n, v ? "hide" : "show");
+ undo_redo->add_undo_method(n, v ? "show" : "hide");
undo_redo->commit_action();
}
- } else if (p_id==BUTTON_LOCK) {
+ } else if (p_id == BUTTON_LOCK) {
if (n->is_class("CanvasItem")) {
n->set_meta("_edit_lock_", Variant());
@@ -231,44 +222,44 @@ void SceneTreeEditor::_cell_button_pressed(Object *p_item,int p_column,int p_id)
emit_signal("node_changed");
}
- } else if (p_id==BUTTON_GROUP) {
+ } else if (p_id == BUTTON_GROUP) {
if (n->is_class("CanvasItem")) {
n->set_meta("_edit_group_", Variant());
_update_tree();
emit_signal("node_changed");
}
- } else if (p_id==BUTTON_WARNING) {
+ } else if (p_id == BUTTON_WARNING) {
String config_err = n->get_configuration_warning();
- if (config_err==String())
+ if (config_err == String())
return;
- config_err=config_err.word_wrap(80);
+ config_err = config_err.word_wrap(80);
warning->set_text(config_err);
warning->popup_centered_minsize();
- } else if (p_id==BUTTON_SIGNALS) {
+ } else if (p_id == BUTTON_SIGNALS) {
editor_selection->clear();
editor_selection->add_node(n);
set_selected(n);
- NodeDock::singleton->get_parent()->call("set_current_tab",NodeDock::singleton->get_index());
+ NodeDock::singleton->get_parent()->call("set_current_tab", NodeDock::singleton->get_index());
NodeDock::singleton->show_connections();
- } else if (p_id==BUTTON_GROUPS) {
+ } else if (p_id == BUTTON_GROUPS) {
editor_selection->clear();
editor_selection->add_node(n);
set_selected(n);
- NodeDock::singleton->get_parent()->call("set_current_tab",NodeDock::singleton->get_index());
+ NodeDock::singleton->get_parent()->call("set_current_tab", NodeDock::singleton->get_index());
NodeDock::singleton->show_groups();
}
}
-bool SceneTreeEditor::_add_nodes(Node *p_node,TreeItem *p_parent) {
+bool SceneTreeEditor::_add_nodes(Node *p_node, TreeItem *p_parent) {
if (!p_node)
return false;
@@ -276,34 +267,34 @@ bool SceneTreeEditor::_add_nodes(Node *p_node,TreeItem *p_parent) {
// only owned nodes are editable, since nodes can create their own (manually owned) child nodes,
// which the editor needs not to know about.
- bool part_of_subscene=false;
+ bool part_of_subscene = false;
- if (!display_foreign && p_node->get_owner()!=get_scene_node() && p_node!=get_scene_node()) {
+ if (!display_foreign && p_node->get_owner() != get_scene_node() && p_node != get_scene_node()) {
if ((show_enabled_subscene || can_open_instance) && p_node->get_owner() && (get_scene_node()->is_editable_instance(p_node->get_owner()))) {
- part_of_subscene=true;
+ part_of_subscene = true;
//allow
} else {
return false;
}
} else {
- part_of_subscene = p_node!=get_scene_node() && get_scene_node()->get_scene_inherited_state().is_valid() && get_scene_node()->get_scene_inherited_state()->find_node_by_path(get_scene_node()->get_path_to(p_node))>=0;
+ part_of_subscene = p_node != get_scene_node() && get_scene_node()->get_scene_inherited_state().is_valid() && get_scene_node()->get_scene_inherited_state()->find_node_by_path(get_scene_node()->get_path_to(p_node)) >= 0;
}
TreeItem *item = tree->create_item(p_parent);
- item->set_text(0, p_node->get_name() );
+ item->set_text(0, p_node->get_name());
if (can_rename && !part_of_subscene /*(p_node->get_owner() == get_scene_node() || p_node==get_scene_node())*/)
item->set_editable(0, true);
- item->set_selectable(0,true);
+ item->set_selectable(0, true);
if (can_rename) {
#ifdef ENABLE_DEPRECATED
if (p_node->has_meta("_editor_collapsed")) {
//remove previous way of storing folding, which did not get along with scene inheritance and instancing
if ((bool)p_node->get_meta("_editor_collapsed"))
p_node->set_display_folded(true);
- p_node->set_meta("_editor_collapsed",Variant());
+ p_node->set_meta("_editor_collapsed", Variant());
}
#endif
bool collapsed = p_node->is_displayed_folded();
@@ -313,111 +304,107 @@ bool SceneTreeEditor::_add_nodes(Node *p_node,TreeItem *p_parent) {
Ref<Texture> icon;
if (p_node->has_meta("_editor_icon"))
- icon=p_node->get_meta("_editor_icon");
+ icon = p_node->get_meta("_editor_icon");
else
- icon=get_icon( (has_icon(p_node->get_class(),"EditorIcons")?p_node->get_class():String("Object")),"EditorIcons");
- item->set_icon(0, icon );
- item->set_metadata( 0,p_node->get_path() );
+ icon = get_icon((has_icon(p_node->get_class(), "EditorIcons") ? p_node->get_class() : String("Object")), "EditorIcons");
+ item->set_icon(0, icon);
+ item->set_metadata(0, p_node->get_path());
if (part_of_subscene) {
//item->set_selectable(0,marked_selectable);
- item->set_custom_color(0,Color(0.8,0.4,0.20));
+ item->set_custom_color(0, Color(0.8, 0.4, 0.20));
} else if (marked.has(p_node)) {
- item->set_selectable(0,marked_selectable);
- item->set_custom_color(0,Color(0.8,0.1,0.10));
+ item->set_selectable(0, marked_selectable);
+ item->set_custom_color(0, Color(0.8, 0.1, 0.10));
} else if (!marked_selectable && !marked_children_selectable) {
- Node *node=p_node;
- while(node) {
+ Node *node = p_node;
+ while (node) {
if (marked.has(node)) {
- item->set_selectable(0,false);
- item->set_custom_color(0,Color(0.8,0.1,0.10));
+ item->set_selectable(0, false);
+ item->set_custom_color(0, Color(0.8, 0.1, 0.10));
break;
}
- node=node->get_parent();
+ node = node->get_parent();
}
}
-
-
if (can_rename) { //should be can edit..
String warning = p_node->get_configuration_warning();
- if (warning!=String()) {
- item->add_button(0,get_icon("NodeWarning","EditorIcons"),BUTTON_WARNING);
+ if (warning != String()) {
+ item->add_button(0, get_icon("NodeWarning", "EditorIcons"), BUTTON_WARNING);
}
bool has_connections = p_node->has_persistent_signal_connections();
bool has_groups = p_node->has_persistent_groups();
if (has_connections && has_groups) {
- item->add_button(0,get_icon("ConnectionAndGroups","EditorIcons"),BUTTON_SIGNALS);
+ item->add_button(0, get_icon("ConnectionAndGroups", "EditorIcons"), BUTTON_SIGNALS);
} else if (has_connections) {
- item->add_button(0,get_icon("Connect","EditorIcons"),BUTTON_SIGNALS);
+ item->add_button(0, get_icon("Connect", "EditorIcons"), BUTTON_SIGNALS);
} else if (has_groups) {
- item->add_button(0,get_icon("Groups","EditorIcons"),BUTTON_GROUPS);
+ item->add_button(0, get_icon("Groups", "EditorIcons"), BUTTON_GROUPS);
}
}
- if (p_node==get_scene_node() && p_node->get_scene_inherited_state().is_valid()) {
- item->add_button(0,get_icon("InstanceOptions","EditorIcons"),BUTTON_SUBSCENE);
- item->set_tooltip(0,TTR("Inherits:")+" "+p_node->get_scene_inherited_state()->get_path()+"\n"+TTR("Type:")+" "+p_node->get_class());
- } else if (p_node!=get_scene_node() && p_node->get_filename()!="" && can_open_instance) {
+ if (p_node == get_scene_node() && p_node->get_scene_inherited_state().is_valid()) {
+ item->add_button(0, get_icon("InstanceOptions", "EditorIcons"), BUTTON_SUBSCENE);
+ item->set_tooltip(0, TTR("Inherits:") + " " + p_node->get_scene_inherited_state()->get_path() + "\n" + TTR("Type:") + " " + p_node->get_class());
+ } else if (p_node != get_scene_node() && p_node->get_filename() != "" && can_open_instance) {
- item->add_button(0,get_icon("InstanceOptions","EditorIcons"),BUTTON_SUBSCENE);
- item->set_tooltip(0,TTR("Instance:")+" "+p_node->get_filename()+"\n"+TTR("Type:")+" "+p_node->get_class());
+ item->add_button(0, get_icon("InstanceOptions", "EditorIcons"), BUTTON_SUBSCENE);
+ item->set_tooltip(0, TTR("Instance:") + " " + p_node->get_filename() + "\n" + TTR("Type:") + " " + p_node->get_class());
} else {
- item->set_tooltip(0,String(p_node->get_name())+"\n"+TTR("Type:")+" "+p_node->get_class());
+ item->set_tooltip(0, String(p_node->get_name()) + "\n" + TTR("Type:") + " " + p_node->get_class());
}
if (can_open_instance) {
- if (!p_node->is_connected("script_changed",this,"_node_script_changed"))
- p_node->connect("script_changed",this,"_node_script_changed",varray(p_node));
-
+ if (!p_node->is_connected("script_changed", this, "_node_script_changed"))
+ p_node->connect("script_changed", this, "_node_script_changed", varray(p_node));
if (!p_node->get_script().is_null()) {
- item->add_button(0,get_icon("Script","EditorIcons"),BUTTON_SCRIPT);
+ item->add_button(0, get_icon("Script", "EditorIcons"), BUTTON_SCRIPT);
}
if (p_node->is_class("CanvasItem")) {
- bool is_locked = p_node->has_meta("_edit_lock_");//_edit_group_
+ bool is_locked = p_node->has_meta("_edit_lock_"); //_edit_group_
if (is_locked)
- item->add_button(0,get_icon("Lock", "EditorIcons"), BUTTON_LOCK);
+ item->add_button(0, get_icon("Lock", "EditorIcons"), BUTTON_LOCK);
bool is_grouped = p_node->has_meta("_edit_group_");
if (is_grouped)
- item->add_button(0,get_icon("Group", "EditorIcons"), BUTTON_GROUP);
+ item->add_button(0, get_icon("Group", "EditorIcons"), BUTTON_GROUP);
bool v = p_node->call("is_visible");
if (v)
- item->add_button(0,get_icon("Visible","EditorIcons"),BUTTON_VISIBILITY);
+ item->add_button(0, get_icon("Visible", "EditorIcons"), BUTTON_VISIBILITY);
else
- item->add_button(0,get_icon("Hidden","EditorIcons"),BUTTON_VISIBILITY);
+ item->add_button(0, get_icon("Hidden", "EditorIcons"), BUTTON_VISIBILITY);
- if (!p_node->is_connected("visibility_changed",this,"_node_visibility_changed"))
- p_node->connect("visibility_changed",this,"_node_visibility_changed",varray(p_node));
+ if (!p_node->is_connected("visibility_changed", this, "_node_visibility_changed"))
+ p_node->connect("visibility_changed", this, "_node_visibility_changed", varray(p_node));
_update_visibility_color(p_node, item);
} else if (p_node->is_class("Spatial")) {
bool v = p_node->call("is_visible");
if (v)
- item->add_button(0,get_icon("Visible","EditorIcons"),BUTTON_VISIBILITY);
+ item->add_button(0, get_icon("Visible", "EditorIcons"), BUTTON_VISIBILITY);
else
- item->add_button(0,get_icon("Hidden","EditorIcons"),BUTTON_VISIBILITY);
+ item->add_button(0, get_icon("Hidden", "EditorIcons"), BUTTON_VISIBILITY);
- if (!p_node->is_connected("visibility_changed",this,"_node_visibility_changed"))
- p_node->connect("visibility_changed",this,"_node_visibility_changed",varray(p_node));
+ if (!p_node->is_connected("visibility_changed", this, "_node_visibility_changed"))
+ p_node->connect("visibility_changed", this, "_node_visibility_changed", varray(p_node));
_update_visibility_color(p_node, item);
}
-
}
if (editor_selection) {
@@ -427,20 +414,19 @@ bool SceneTreeEditor::_add_nodes(Node *p_node,TreeItem *p_parent) {
}
}
- if (selected==p_node) {
+ if (selected == p_node) {
if (!editor_selection)
item->select(0);
item->set_as_cursor(0);
}
- bool keep= (filter.is_subsequence_ofi(String(p_node->get_name())));
+ bool keep = (filter.is_subsequence_ofi(String(p_node->get_name())));
- for (int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- bool child_keep = _add_nodes(p_node->get_child(i),item);
+ bool child_keep = _add_nodes(p_node->get_child(i), item);
keep = keep || child_keep;
-
}
if (!keep) {
@@ -449,26 +435,23 @@ bool SceneTreeEditor::_add_nodes(Node *p_node,TreeItem *p_parent) {
} else {
return true;
}
-
}
-
void SceneTreeEditor::_node_visibility_changed(Node *p_node) {
-
- if (p_node!=get_scene_node() && !p_node->get_owner()) {
+ if (p_node != get_scene_node() && !p_node->get_owner()) {
return;
}
- TreeItem* item=p_node?_find(tree->get_root(),p_node->get_path()):NULL;
+ TreeItem *item = p_node ? _find(tree->get_root(), p_node->get_path()) : NULL;
if (!item) {
return;
}
- int idx=item->get_button_by_id(0,BUTTON_VISIBILITY);
- ERR_FAIL_COND(idx==-1);
+ int idx = item->get_button_by_id(0, BUTTON_VISIBILITY);
+ ERR_FAIL_COND(idx == -1);
- bool visible=false;
+ bool visible = false;
if (p_node->is_class("CanvasItem")) {
visible = p_node->call("is_visible");
@@ -478,22 +461,22 @@ void SceneTreeEditor::_node_visibility_changed(Node *p_node) {
}
if (visible)
- item->set_button(0,idx,get_icon("Visible","EditorIcons"));
+ item->set_button(0, idx, get_icon("Visible", "EditorIcons"));
else
- item->set_button(0,idx,get_icon("Hidden","EditorIcons"));
+ item->set_button(0, idx, get_icon("Hidden", "EditorIcons"));
_update_visibility_color(p_node, item);
}
void SceneTreeEditor::_update_visibility_color(Node *p_node, TreeItem *p_item) {
if (p_node->is_class("CanvasItem") || p_node->is_class("Spatial")) {
- Color color(1,1,1,1);
+ Color color(1, 1, 1, 1);
bool visible_on_screen = p_node->call("is_visible");
if (!visible_on_screen) {
- color = Color(0.6,0.6,0.6,1);
+ color = Color(0.6, 0.6, 0.6, 1);
}
- int idx=p_item->get_button_by_id(0,BUTTON_VISIBILITY);
- p_item->set_button_color(0,idx,color);
+ int idx = p_item->get_button_by_id(0, BUTTON_VISIBILITY);
+ p_item->set_button_color(0, idx, color);
}
}
@@ -515,7 +498,6 @@ void SceneTreeEditor::_node_script_changed(Node *p_node) {
item->add_button(0,get_icon("Script","EditorIcons"),2);
}*/
-
}
void SceneTreeEditor::_node_removed(Node *p_node) {
@@ -523,75 +505,69 @@ void SceneTreeEditor::_node_removed(Node *p_node) {
if (EditorNode::get_singleton()->is_exiting())
return; //speed up exit
- if (p_node->is_connected("script_changed",this,"_node_script_changed"))
- p_node->disconnect("script_changed",this,"_node_script_changed");
+ if (p_node->is_connected("script_changed", this, "_node_script_changed"))
+ p_node->disconnect("script_changed", this, "_node_script_changed");
if (p_node->is_class("Spatial") || p_node->is_class("CanvasItem")) {
- if (p_node->is_connected("visibility_changed",this,"_node_visibility_changed"))
- p_node->disconnect("visibility_changed",this,"_node_visibility_changed");
+ if (p_node->is_connected("visibility_changed", this, "_node_visibility_changed"))
+ p_node->disconnect("visibility_changed", this, "_node_visibility_changed");
}
- if (p_node==selected) {
- selected=NULL;
+ if (p_node == selected) {
+ selected = NULL;
emit_signal("node_selected");
}
-
-
}
void SceneTreeEditor::_update_tree() {
-
if (!is_inside_tree()) {
- tree_dirty=false;
+ tree_dirty = false;
return;
}
- updating_tree=true;
+ updating_tree = true;
tree->clear();
if (get_scene_node()) {
- _add_nodes( get_scene_node(), NULL );
+ _add_nodes(get_scene_node(), NULL);
last_hash = hash_djb2_one_64(0);
- _compute_hash(get_scene_node(),last_hash);
-
+ _compute_hash(get_scene_node(), last_hash);
}
- updating_tree=false;
-
- tree_dirty=false;
+ updating_tree = false;
+ tree_dirty = false;
}
-void SceneTreeEditor::_compute_hash(Node *p_node,uint64_t &hash) {
+void SceneTreeEditor::_compute_hash(Node *p_node, uint64_t &hash) {
- hash=hash_djb2_one_64(p_node->get_instance_ID(),hash);
+ hash = hash_djb2_one_64(p_node->get_instance_ID(), hash);
if (p_node->get_parent())
- hash=hash_djb2_one_64(p_node->get_parent()->get_instance_ID(),hash); //so a reparent still produces a different hash
-
+ hash = hash_djb2_one_64(p_node->get_parent()->get_instance_ID(), hash); //so a reparent still produces a different hash
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- _compute_hash(p_node->get_child(i),hash);
+ _compute_hash(p_node->get_child(i), hash);
}
}
void SceneTreeEditor::_test_update_tree() {
- pending_test_update=false;
+ pending_test_update = false;
if (!is_inside_tree())
return;
- if(tree_dirty)
+ if (tree_dirty)
return; // don't even bother
uint64_t hash = hash_djb2_one_64(0);
if (get_scene_node())
- _compute_hash(get_scene_node(),hash);
+ _compute_hash(get_scene_node(), hash);
//test hash
- if (hash==last_hash)
+ if (hash == last_hash)
return; // did not change
- MessageQueue::get_singleton()->push_call(this,"_update_tree");
- tree_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_update_tree");
+ tree_dirty = true;
}
void SceneTreeEditor::_tree_changed() {
@@ -603,43 +579,36 @@ void SceneTreeEditor::_tree_changed() {
if (tree_dirty)
return;
- MessageQueue::get_singleton()->push_call(this,"_test_update_tree");
- pending_test_update=true;
-
+ MessageQueue::get_singleton()->push_call(this, "_test_update_tree");
+ pending_test_update = true;
}
void SceneTreeEditor::_selected_changed() {
-
TreeItem *s = tree->get_selected();
ERR_FAIL_COND(!s);
NodePath np = s->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
-
- if (n==selected)
+ if (n == selected)
return;
-
selected = get_node(np);
blocked++;
emit_signal("node_selected");
blocked--;
-
-
}
-
-void SceneTreeEditor::_cell_multi_selected(Object *p_object,int p_cell,bool p_selected) {
+void SceneTreeEditor::_cell_multi_selected(Object *p_object, int p_cell, bool p_selected) {
TreeItem *item = p_object->cast_to<TreeItem>();
ERR_FAIL_COND(!item);
NodePath np = item->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
if (!n)
return;
@@ -652,187 +621,174 @@ void SceneTreeEditor::_cell_multi_selected(Object *p_object,int p_cell,bool p_se
} else {
editor_selection->remove_node(n);
-
}
-
}
void SceneTreeEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
- get_tree()->connect("tree_changed",this,"_tree_changed");
- get_tree()->connect("node_removed",this,"_node_removed");
- get_tree()->connect("node_configuration_warning_changed",this,"_warning_changed");
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- instance_menu->set_item_icon(5,get_icon("Load","EditorIcons"));
- tree->connect("item_collapsed",this,"_cell_collapsed");
- inheritance_menu->set_item_icon(2,get_icon("Load","EditorIcons"));
- clear_inherit_confirm->connect("confirmed",this,"_subscene_option",varray(SCENE_MENU_CLEAR_INHERITANCE_CONFIRM));
+ get_tree()->connect("tree_changed", this, "_tree_changed");
+ get_tree()->connect("node_removed", this, "_node_removed");
+ get_tree()->connect("node_configuration_warning_changed", this, "_warning_changed");
- EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed");
+ instance_menu->set_item_icon(5, get_icon("Load", "EditorIcons"));
+ tree->connect("item_collapsed", this, "_cell_collapsed");
+ inheritance_menu->set_item_icon(2, get_icon("Load", "EditorIcons"));
+ clear_inherit_confirm->connect("confirmed", this, "_subscene_option", varray(SCENE_MENU_CLEAR_INHERITANCE_CONFIRM));
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_editor_settings_changed");
//get_scene()->connect("tree_changed",this,"_tree_changed",Vector<Variant>(),CONNECT_DEFERRED);
//get_scene()->connect("node_removed",this,"_node_removed",Vector<Variant>(),CONNECT_DEFERRED);
_update_tree();
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
- get_tree()->disconnect("tree_changed",this,"_tree_changed");
- get_tree()->disconnect("node_removed",this,"_node_removed");
- tree->disconnect("item_collapsed",this,"_cell_collapsed");
- clear_inherit_confirm->disconnect("confirmed",this,"_subscene_option");
- get_tree()->disconnect("node_configuration_warning_changed",this,"_warning_changed");
- EditorSettings::get_singleton()->disconnect("settings_changed",this,"_editor_settings_changed");
+ if (p_what == NOTIFICATION_EXIT_TREE) {
+
+ get_tree()->disconnect("tree_changed", this, "_tree_changed");
+ get_tree()->disconnect("node_removed", this, "_node_removed");
+ tree->disconnect("item_collapsed", this, "_cell_collapsed");
+ clear_inherit_confirm->disconnect("confirmed", this, "_subscene_option");
+ get_tree()->disconnect("node_configuration_warning_changed", this, "_warning_changed");
+ EditorSettings::get_singleton()->disconnect("settings_changed", this, "_editor_settings_changed");
}
-
}
-
-TreeItem* SceneTreeEditor::_find(TreeItem *p_node,const NodePath& p_path) {
+TreeItem *SceneTreeEditor::_find(TreeItem *p_node, const NodePath &p_path) {
if (!p_node)
return NULL;
- NodePath np=p_node->get_metadata(0);
- if (np==p_path)
+ NodePath np = p_node->get_metadata(0);
+ if (np == p_path)
return p_node;
- TreeItem *children=p_node->get_children();
- while(children) {
+ TreeItem *children = p_node->get_children();
+ while (children) {
- TreeItem *n=_find(children,p_path);
+ TreeItem *n = _find(children, p_path);
if (n)
return n;
- children=children->get_next();
+ children = children->get_next();
}
return NULL;
}
-void SceneTreeEditor::set_selected(Node *p_node,bool p_emit_selected) {
+void SceneTreeEditor::set_selected(Node *p_node, bool p_emit_selected) {
- ERR_FAIL_COND(blocked>0);
+ ERR_FAIL_COND(blocked > 0);
if (pending_test_update)
_test_update_tree();
if (tree_dirty)
_update_tree();
- if (selected==p_node)
+ if (selected == p_node)
return;
-
- TreeItem* item=p_node?_find(tree->get_root(),p_node->get_path()):NULL;
+ TreeItem *item = p_node ? _find(tree->get_root(), p_node->get_path()) : NULL;
if (item) {
// make visible when it's collapsed
- TreeItem* node=item->get_parent();
- while (node && node!=tree->get_root()) {
+ TreeItem *node = item->get_parent();
+ while (node && node != tree->get_root()) {
node->set_collapsed(false);
- node=node->get_parent();
+ node = node->get_parent();
}
item->select(0);
item->set_as_cursor(0);
- selected=p_node;
+ selected = p_node;
tree->ensure_cursor_is_visible();
} else {
if (!p_node)
- selected=NULL;
+ selected = NULL;
_update_tree();
- selected=p_node;
+ selected = p_node;
if (p_emit_selected)
emit_signal("node_selected");
}
-
}
-void SceneTreeEditor::_rename_node(ObjectID p_node,const String& p_name) {
+void SceneTreeEditor::_rename_node(ObjectID p_node, const String &p_name) {
Object *o = ObjectDB::get_instance(p_node);
ERR_FAIL_COND(!o);
Node *n = o->cast_to<Node>();
ERR_FAIL_COND(!n);
- TreeItem* item=_find(tree->get_root(),n->get_path());
+ TreeItem *item = _find(tree->get_root(), n->get_path());
ERR_FAIL_COND(!item);
- n->set_name( p_name );
- item->set_metadata(0,n->get_path());
- item->set_text(0,p_name);
+ n->set_name(p_name);
+ item->set_metadata(0, n->get_path());
+ item->set_text(0, p_name);
emit_signal("node_renamed");
if (!tree_dirty) {
- MessageQueue::get_singleton()->push_call(this,"_update_tree");
- tree_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_update_tree");
+ tree_dirty = true;
}
-
-
}
-
void SceneTreeEditor::_renamed() {
- TreeItem *which=tree->get_edited();
+ TreeItem *which = tree->get_edited();
ERR_FAIL_COND(!which);
NodePath np = which->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
ERR_FAIL_COND(!n);
- String new_name=which->get_text(0);
+ String new_name = which->get_text(0);
if (new_name.find(".") != -1 || new_name.find("/") != -1) {
- error->set_text(TTR("Invalid node name, the following characters are not allowed:")+"\n \".\", \"/\"");
+ error->set_text(TTR("Invalid node name, the following characters are not allowed:") + "\n \".\", \"/\"");
error->popup_centered_minsize();
- new_name=n->get_name();
+ new_name = n->get_name();
}
- if (new_name==n->get_name())
+ if (new_name == n->get_name())
return;
if (!undo_redo) {
- n->set_name( new_name );
- which->set_metadata(0,n->get_path());
+ n->set_name(new_name);
+ which->set_metadata(0, n->get_path());
emit_signal("node_renamed");
} else {
undo_redo->create_action(TTR("Rename Node"));
- emit_signal("node_prerename",n,new_name);
- undo_redo->add_do_method(this,"_rename_node",n->get_instance_ID(),new_name);
- undo_redo->add_undo_method(this,"_rename_node",n->get_instance_ID(),n->get_name());
+ emit_signal("node_prerename", n, new_name);
+ undo_redo->add_do_method(this, "_rename_node", n->get_instance_ID(), new_name);
+ undo_redo->add_undo_method(this, "_rename_node", n->get_instance_ID(), n->get_name());
undo_redo->commit_action();
}
}
-
Node *SceneTreeEditor::get_selected() {
return selected;
}
-void SceneTreeEditor::set_marked(const Set<Node*>& p_marked,bool p_selectable,bool p_children_selectable) {
+void SceneTreeEditor::set_marked(const Set<Node *> &p_marked, bool p_selectable, bool p_children_selectable) {
if (tree_dirty)
_update_tree();
- marked=p_marked;
- marked_selectable=p_selectable;
- marked_children_selectable=p_children_selectable;
+ marked = p_marked;
+ marked_selectable = p_selectable;
+ marked_children_selectable = p_children_selectable;
_update_tree();
}
-void SceneTreeEditor::set_marked(Node *p_marked,bool p_selectable,bool p_children_selectable) {
+void SceneTreeEditor::set_marked(Node *p_marked, bool p_selectable, bool p_children_selectable) {
- Set<Node*> s;
+ Set<Node *> s;
if (p_marked)
s.insert(p_marked);
- set_marked(s,p_selectable,p_children_selectable);
-
-
+ set_marked(s, p_selectable, p_children_selectable);
}
-void SceneTreeEditor::set_filter(const String& p_filter) {
+void SceneTreeEditor::set_filter(const String &p_filter) {
- filter=p_filter;
+ filter = p_filter;
_update_tree();
}
@@ -841,10 +797,9 @@ String SceneTreeEditor::get_filter() const {
return filter;
}
-
void SceneTreeEditor::set_display_foreign_nodes(bool p_display) {
- display_foreign=p_display;
+ display_foreign = p_display;
_update_tree();
}
bool SceneTreeEditor::get_display_foreign_nodes() const {
@@ -854,10 +809,10 @@ bool SceneTreeEditor::get_display_foreign_nodes() const {
void SceneTreeEditor::set_editor_selection(EditorSelection *p_selection) {
- editor_selection=p_selection;
+ editor_selection = p_selection;
tree->set_select_mode(Tree::SELECT_MULTI);
tree->set_cursor_can_exit_tree(false);
- editor_selection->connect("selection_changed",this,"_selection_changed");
+ editor_selection->connect("selection_changed", this, "_selection_changed");
}
void SceneTreeEditor::_update_selection(TreeItem *item) {
@@ -869,7 +824,7 @@ void SceneTreeEditor::_update_selection(TreeItem *item) {
if (!has_node(np))
return;
- Node *n=get_node(np);
+ Node *n = get_node(np);
if (!n)
return;
@@ -879,13 +834,12 @@ void SceneTreeEditor::_update_selection(TreeItem *item) {
else
item->deselect(0);
- TreeItem *c=item->get_children();
+ TreeItem *c = item->get_children();
-
- while(c) {
+ while (c) {
_update_selection(c);
- c=c->get_next();
+ c = c->get_next();
}
}
@@ -894,7 +848,7 @@ void SceneTreeEditor::_selection_changed() {
if (!editor_selection)
return;
- TreeItem *root=tree->get_root();
+ TreeItem *root = tree->get_root();
if (!root)
return;
@@ -908,60 +862,59 @@ void SceneTreeEditor::_cell_collapsed(Object *p_obj) {
if (!can_rename)
return;
- TreeItem *ti=p_obj->cast_to<TreeItem>();
+ TreeItem *ti = p_obj->cast_to<TreeItem>();
if (!ti)
return;
- bool collapsed=ti->is_collapsed();
+ bool collapsed = ti->is_collapsed();
NodePath np = ti->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
ERR_FAIL_COND(!n);
n->set_display_folded(collapsed);
-
}
-Variant SceneTreeEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant SceneTreeEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
if (!can_rename)
return Variant(); //not editable tree
- Vector<Node*> selected;
+ Vector<Node *> selected;
Vector<Ref<Texture> > icons;
- TreeItem *next=tree->get_next_selected(NULL);
+ TreeItem *next = tree->get_next_selected(NULL);
while (next) {
NodePath np = next->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
if (n) {
selected.push_back(n);
icons.push_back(next->get_icon(0));
}
- next=tree->get_next_selected(next);
+ next = tree->get_next_selected(next);
}
if (selected.empty())
return Variant();
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
Array objs;
int list_max = 10;
float opacity_step = 1.0f / list_max;
float opacity_item = 1.0f;
- for(int i=0;i<selected.size();i++) {
+ for (int i = 0; i < selected.size(); i++) {
- if (i<list_max){
- HBoxContainer *hb = memnew( HBoxContainer );
+ if (i < list_max) {
+ HBoxContainer *hb = memnew(HBoxContainer);
TextureRect *tf = memnew(TextureRect);
tf->set_texture(icons[i]);
hb->add_child(tf);
- Label *label = memnew( Label( selected[i]->get_name() ) );
+ Label *label = memnew(Label(selected[i]->get_name()));
hb->add_child(label);
vb->add_child(hb);
- hb->set_modulate(Color(1,1,1,opacity_item));
+ hb->set_modulate(Color(1, 1, 1, opacity_item));
opacity_item -= opacity_step;
}
NodePath p = selected[i]->get_path();
@@ -970,10 +923,10 @@ Variant SceneTreeEditor::get_drag_data_fw(const Point2& p_point,Control* p_from)
set_drag_preview(vb);
Dictionary drag_data;
- drag_data["type"]="nodes";
- drag_data["nodes"]=objs;
+ drag_data["type"] = "nodes";
+ drag_data["nodes"] = objs;
- tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN|Tree::DROP_MODE_ON_ITEM);
+ tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN | Tree::DROP_MODE_ON_ITEM);
emit_signal("nodes_dragged");
return drag_data;
@@ -983,15 +936,14 @@ bool SceneTreeEditor::_is_script_type(const StringName &p_type) const {
return (script_types->find(p_type));
}
-bool SceneTreeEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const {
+bool SceneTreeEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
if (!can_rename)
return false; //not editable tree
- if (filter!=String())
+ if (filter != String())
return false; //can't rearrange tree with filter turned on
-
- Dictionary d=p_data;
+ Dictionary d = p_data;
if (!d.has("type"))
return false;
@@ -1000,14 +952,14 @@ bool SceneTreeEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_da
return false;
int section = tree->get_drop_section_at_pos(p_point);
- if (section<-1 || (section==-1 && !item->get_parent()))
+ if (section < -1 || (section == -1 && !item->get_parent()))
return false;
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
- if (files.size()==0)
+ if (files.size() == 0)
return false; //weird
if (_is_script_type(EditorFileSystem::get_singleton()->get_file_type(files[0]))) {
@@ -1015,112 +967,103 @@ bool SceneTreeEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_da
return true;
}
- for(int i=0;i<files.size();i++) {
+ for (int i = 0; i < files.size(); i++) {
String file = files[i];
String ftype = EditorFileSystem::get_singleton()->get_file_type(file);
- if (ftype!="PackedScene")
+ if (ftype != "PackedScene")
return false;
}
- tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN|Tree::DROP_MODE_ON_ITEM); //so it works..
+ tree->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN | Tree::DROP_MODE_ON_ITEM); //so it works..
return true;
}
-
- if (String(d["type"])=="nodes") {
+ if (String(d["type"]) == "nodes") {
return true;
}
return false;
}
-void SceneTreeEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) {
+void SceneTreeEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
- if (!can_drop_data_fw(p_point,p_data,p_from))
+ if (!can_drop_data_fw(p_point, p_data, p_from))
return;
TreeItem *item = tree->get_item_at_pos(p_point);
if (!item)
return;
int section = tree->get_drop_section_at_pos(p_point);
- if (section<-1)
+ if (section < -1)
return;
NodePath np = item->get_metadata(0);
- Node *n=get_node(np);
+ Node *n = get_node(np);
if (!n)
return;
- Dictionary d=p_data;
+ Dictionary d = p_data;
- if (String(d["type"])=="nodes") {
- Array nodes=d["nodes"];
- emit_signal("nodes_rearranged",nodes,np,section);
+ if (String(d["type"]) == "nodes") {
+ Array nodes = d["nodes"];
+ emit_signal("nodes_rearranged", nodes, np, section);
}
- if (String(d["type"])=="files") {
+ if (String(d["type"]) == "files") {
Vector<String> files = d["files"];
-
String ftype = EditorFileSystem::get_singleton()->get_file_type(files[0]);
if (_is_script_type(ftype)) {
- emit_signal("script_dropped", files[0],np);
+ emit_signal("script_dropped", files[0], np);
} else {
- emit_signal("files_dropped",files,np,section);
+ emit_signal("files_dropped", files, np, section);
}
}
-
}
-void SceneTreeEditor::_rmb_select(const Vector2& p_pos) {
+void SceneTreeEditor::_rmb_select(const Vector2 &p_pos) {
- emit_signal("rmb_pressed",tree->get_global_transform().xform(p_pos));
+ emit_signal("rmb_pressed", tree->get_global_transform().xform(p_pos));
}
-
-void SceneTreeEditor::_warning_changed(Node* p_for_node) {
+void SceneTreeEditor::_warning_changed(Node *p_for_node) {
//should use a timer
update_timer->start();
//print_line("WARNING CHANGED "+String(p_for_node->get_name()));
-
}
-
void SceneTreeEditor::_editor_settings_changed() {
bool enable_rl = EditorSettings::get_singleton()->get("docks/scene_tree/draw_relationship_lines");
Color rl_color = EditorSettings::get_singleton()->get("docks/scene_tree/relationship_line_color");
if (enable_rl) {
- tree->add_constant_override("draw_relationship_lines",1);
+ tree->add_constant_override("draw_relationship_lines", 1);
tree->add_color_override("relationship_line_color", rl_color);
- }
- else
- tree->add_constant_override("draw_relationship_lines",0);
-
+ } else
+ tree->add_constant_override("draw_relationship_lines", 0);
}
-
void SceneTreeEditor::_bind_methods() {
- ClassDB::bind_method("_tree_changed",&SceneTreeEditor::_tree_changed);
- ClassDB::bind_method("_update_tree",&SceneTreeEditor::_update_tree);
- ClassDB::bind_method("_node_removed",&SceneTreeEditor::_node_removed);
- ClassDB::bind_method("_selected_changed",&SceneTreeEditor::_selected_changed);
- ClassDB::bind_method("_renamed",&SceneTreeEditor::_renamed);
- ClassDB::bind_method("_rename_node",&SceneTreeEditor::_rename_node);
- ClassDB::bind_method("_test_update_tree",&SceneTreeEditor::_test_update_tree);
- ClassDB::bind_method("_cell_multi_selected",&SceneTreeEditor::_cell_multi_selected);
- ClassDB::bind_method("_selection_changed",&SceneTreeEditor::_selection_changed);
- ClassDB::bind_method("_cell_button_pressed",&SceneTreeEditor::_cell_button_pressed);
- ClassDB::bind_method("_cell_collapsed",&SceneTreeEditor::_cell_collapsed);
- ClassDB::bind_method("_subscene_option",&SceneTreeEditor::_subscene_option);
- ClassDB::bind_method("_rmb_select",&SceneTreeEditor::_rmb_select);
- ClassDB::bind_method("_warning_changed",&SceneTreeEditor::_warning_changed);
-
- ClassDB::bind_method("_node_script_changed",&SceneTreeEditor::_node_script_changed);
- ClassDB::bind_method("_node_visibility_changed",&SceneTreeEditor::_node_visibility_changed);
+ ClassDB::bind_method("_tree_changed", &SceneTreeEditor::_tree_changed);
+ ClassDB::bind_method("_update_tree", &SceneTreeEditor::_update_tree);
+ ClassDB::bind_method("_node_removed", &SceneTreeEditor::_node_removed);
+ ClassDB::bind_method("_selected_changed", &SceneTreeEditor::_selected_changed);
+ ClassDB::bind_method("_renamed", &SceneTreeEditor::_renamed);
+ ClassDB::bind_method("_rename_node", &SceneTreeEditor::_rename_node);
+ ClassDB::bind_method("_test_update_tree", &SceneTreeEditor::_test_update_tree);
+ ClassDB::bind_method("_cell_multi_selected", &SceneTreeEditor::_cell_multi_selected);
+ ClassDB::bind_method("_selection_changed", &SceneTreeEditor::_selection_changed);
+ ClassDB::bind_method("_cell_button_pressed", &SceneTreeEditor::_cell_button_pressed);
+ ClassDB::bind_method("_cell_collapsed", &SceneTreeEditor::_cell_collapsed);
+ ClassDB::bind_method("_subscene_option", &SceneTreeEditor::_subscene_option);
+ ClassDB::bind_method("_rmb_select", &SceneTreeEditor::_rmb_select);
+ ClassDB::bind_method("_warning_changed", &SceneTreeEditor::_warning_changed);
+
+ ClassDB::bind_method("_node_script_changed", &SceneTreeEditor::_node_script_changed);
+ ClassDB::bind_method("_node_visibility_changed", &SceneTreeEditor::_node_visibility_changed);
ClassDB::bind_method("_editor_settings_changed", &SceneTreeEditor::_editor_settings_changed);
@@ -1130,187 +1073,166 @@ void SceneTreeEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("update_tree"), &SceneTreeEditor::update_tree);
- ADD_SIGNAL( MethodInfo("node_selected") );
- ADD_SIGNAL( MethodInfo("node_renamed") );
- ADD_SIGNAL( MethodInfo("node_prerename") );
- ADD_SIGNAL( MethodInfo("node_changed") );
- ADD_SIGNAL( MethodInfo("nodes_dragged") );
- ADD_SIGNAL( MethodInfo("nodes_rearranged",PropertyInfo(Variant::ARRAY,"paths"),PropertyInfo(Variant::NODE_PATH,"to_path"),PropertyInfo(Variant::INT,"type") ) );
- ADD_SIGNAL( MethodInfo("files_dropped",PropertyInfo(Variant::POOL_STRING_ARRAY,"files"),PropertyInfo(Variant::NODE_PATH,"to_path"),PropertyInfo(Variant::INT,"type") ) );
- ADD_SIGNAL( MethodInfo("script_dropped",PropertyInfo(Variant::STRING,"file"),PropertyInfo(Variant::NODE_PATH,"to_path")));
- ADD_SIGNAL( MethodInfo("rmb_pressed",PropertyInfo(Variant::VECTOR2,"pos")) ) ;
-
- ADD_SIGNAL( MethodInfo("open") );
- ADD_SIGNAL( MethodInfo("open_script") );
-
-
+ ADD_SIGNAL(MethodInfo("node_selected"));
+ ADD_SIGNAL(MethodInfo("node_renamed"));
+ ADD_SIGNAL(MethodInfo("node_prerename"));
+ ADD_SIGNAL(MethodInfo("node_changed"));
+ ADD_SIGNAL(MethodInfo("nodes_dragged"));
+ ADD_SIGNAL(MethodInfo("nodes_rearranged", PropertyInfo(Variant::ARRAY, "paths"), PropertyInfo(Variant::NODE_PATH, "to_path"), PropertyInfo(Variant::INT, "type")));
+ ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::NODE_PATH, "to_path"), PropertyInfo(Variant::INT, "type")));
+ ADD_SIGNAL(MethodInfo("script_dropped", PropertyInfo(Variant::STRING, "file"), PropertyInfo(Variant::NODE_PATH, "to_path")));
+ ADD_SIGNAL(MethodInfo("rmb_pressed", PropertyInfo(Variant::VECTOR2, "pos")));
+
+ ADD_SIGNAL(MethodInfo("open"));
+ ADD_SIGNAL(MethodInfo("open_script"));
}
+SceneTreeEditor::SceneTreeEditor(bool p_label, bool p_can_rename, bool p_can_open_instance) {
-SceneTreeEditor::SceneTreeEditor(bool p_label,bool p_can_rename, bool p_can_open_instance) {
+ undo_redo = NULL;
+ tree_dirty = true;
+ selected = NULL;
-
- undo_redo=NULL;
- tree_dirty=true;
- selected=NULL;
-
- marked_selectable=false;
- marked_children_selectable=false;
- can_rename=p_can_rename;
- can_open_instance=p_can_open_instance;
- display_foreign=false;
- editor_selection=NULL;
+ marked_selectable = false;
+ marked_children_selectable = false;
+ can_rename = p_can_rename;
+ can_open_instance = p_can_open_instance;
+ display_foreign = false;
+ editor_selection = NULL;
if (p_label) {
- Label *label = memnew( Label );
- label->set_pos( Point2(10, 0));
+ Label *label = memnew(Label);
+ label->set_pos(Point2(10, 0));
label->set_text(TTR("Scene Tree (Nodes):"));
add_child(label);
}
- tree = memnew( Tree );
- tree->set_anchor( MARGIN_RIGHT, ANCHOR_END );
- tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END );
- tree->set_begin( Point2(0,p_label?18:0 ));
- tree->set_end( Point2(0,0 ));
+ tree = memnew(Tree);
+ tree->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ tree->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
+ tree->set_begin(Point2(0, p_label ? 18 : 0));
+ tree->set_end(Point2(0, 0));
- add_child( tree );
+ add_child(tree);
tree->set_drag_forwarding(this);
if (p_can_rename) {
tree->set_allow_rmb_select(true);
- tree->connect("item_rmb_selected",this,"_rmb_select");
- tree->connect("empty_tree_rmb_selected",this,"_rmb_select");
+ tree->connect("item_rmb_selected", this, "_rmb_select");
+ tree->connect("empty_tree_rmb_selected", this, "_rmb_select");
}
- tree->connect("cell_selected", this,"_selected_changed");
- tree->connect("item_edited", this,"_renamed",varray(),CONNECT_DEFERRED);
- tree->connect("multi_selected",this,"_cell_multi_selected");
- tree->connect("button_pressed",this,"_cell_button_pressed");
+ tree->connect("cell_selected", this, "_selected_changed");
+ tree->connect("item_edited", this, "_renamed", varray(), CONNECT_DEFERRED);
+ tree->connect("multi_selected", this, "_cell_multi_selected");
+ tree->connect("button_pressed", this, "_cell_button_pressed");
//tree->connect("item_edited", this,"_renamed",Vector<Variant>(),true);
- error = memnew( AcceptDialog );
+ error = memnew(AcceptDialog);
add_child(error);
- warning = memnew( AcceptDialog );
+ warning = memnew(AcceptDialog);
add_child(warning);
warning->set_title("Node Configuration Warning!");
+ show_enabled_subscene = false;
- show_enabled_subscene=false;
+ last_hash = 0;
+ pending_test_update = false;
+ updating_tree = false;
+ blocked = 0;
- last_hash=0;
- pending_test_update=false;
- updating_tree=false;
- blocked=0;
-
- instance_menu = memnew( PopupMenu );
- instance_menu->add_check_item(TTR("Editable Children"),SCENE_MENU_EDITABLE_CHILDREN);
- instance_menu->add_check_item(TTR("Load As Placeholder"),SCENE_MENU_USE_PLACEHOLDER);
+ instance_menu = memnew(PopupMenu);
+ instance_menu->add_check_item(TTR("Editable Children"), SCENE_MENU_EDITABLE_CHILDREN);
+ instance_menu->add_check_item(TTR("Load As Placeholder"), SCENE_MENU_USE_PLACEHOLDER);
instance_menu->add_separator();
- instance_menu->add_item(TTR("Discard Instancing"),SCENE_MENU_CLEAR_INSTANCING);
+ instance_menu->add_item(TTR("Discard Instancing"), SCENE_MENU_CLEAR_INSTANCING);
instance_menu->add_separator();
- instance_menu->add_item(TTR("Open in Editor"),SCENE_MENU_OPEN);
- instance_menu->connect("id_pressed",this,"_subscene_option");
+ instance_menu->add_item(TTR("Open in Editor"), SCENE_MENU_OPEN);
+ instance_menu->connect("id_pressed", this, "_subscene_option");
add_child(instance_menu);
- inheritance_menu = memnew( PopupMenu );
- inheritance_menu->add_item(TTR("Clear Inheritance"),SCENE_MENU_CLEAR_INHERITANCE);
+ inheritance_menu = memnew(PopupMenu);
+ inheritance_menu->add_item(TTR("Clear Inheritance"), SCENE_MENU_CLEAR_INHERITANCE);
inheritance_menu->add_separator();
- inheritance_menu->add_item(TTR("Open in Editor"),SCENE_MENU_OPEN_INHERITED);
- inheritance_menu->connect("id_pressed",this,"_subscene_option");
+ inheritance_menu->add_item(TTR("Open in Editor"), SCENE_MENU_OPEN_INHERITED);
+ inheritance_menu->connect("id_pressed", this, "_subscene_option");
add_child(inheritance_menu);
- clear_inherit_confirm = memnew( ConfirmationDialog );
+ clear_inherit_confirm = memnew(ConfirmationDialog);
clear_inherit_confirm->set_text(TTR("Clear Inheritance? (No Undo!)"));
clear_inherit_confirm->get_ok()->set_text(TTR("Clear!"));
add_child(clear_inherit_confirm);
update_timer = memnew(Timer);
- update_timer->connect("timeout",this,"_update_tree");
+ update_timer->connect("timeout", this, "_update_tree");
update_timer->set_one_shot(true);
update_timer->set_wait_time(0.5);
add_child(update_timer);
script_types = memnew(List<StringName>);
ClassDB::get_inheriters_from_class("Script", script_types);
-
}
-
-
SceneTreeEditor::~SceneTreeEditor() {
memdelete(script_types);
}
-
/******** DIALOG *********/
void SceneTreeDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- connect("confirmed", this,"_select");
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ connect("confirmed", this, "_select");
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
- disconnect("confirmed", this,"_select");
-
+ if (p_what == NOTIFICATION_EXIT_TREE) {
+ disconnect("confirmed", this, "_select");
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
+ get_stylebox("panel", "PopupMenu")->draw(ci, Rect2(Point2(), get_size()));
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED && is_visible_in_tree()) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED && is_visible_in_tree()) {
tree->update_tree();
}
-
-
}
void SceneTreeDialog::_cancel() {
hide();
-
-
-
}
void SceneTreeDialog::_select() {
if (tree->get_selected()) {
- emit_signal("selected",tree->get_selected()->get_path());
+ emit_signal("selected", tree->get_selected()->get_path());
hide();
}
}
void SceneTreeDialog::_bind_methods() {
- ClassDB::bind_method("_select",&SceneTreeDialog::_select);
- ClassDB::bind_method("_cancel",&SceneTreeDialog::_cancel);
- ADD_SIGNAL( MethodInfo("selected",PropertyInfo(Variant::NODE_PATH,"path")));
-
+ ClassDB::bind_method("_select", &SceneTreeDialog::_select);
+ ClassDB::bind_method("_cancel", &SceneTreeDialog::_cancel);
+ ADD_SIGNAL(MethodInfo("selected", PropertyInfo(Variant::NODE_PATH, "path")));
}
-
SceneTreeDialog::SceneTreeDialog() {
set_title(TTR("Select a Node"));
- tree = memnew( SceneTreeEditor(false,false) );
+ tree = memnew(SceneTreeEditor(false, false));
add_child(tree);
//set_child_rect(tree);
- tree->get_scene_tree()->connect("item_activated",this,"_select");
-
+ tree->get_scene_tree()->connect("item_activated", this, "_select");
}
-
-SceneTreeDialog::~SceneTreeDialog()
-{
+SceneTreeDialog::~SceneTreeDialog() {
}
diff --git a/editor/scene_tree_editor.h b/editor/scene_tree_editor.h
index 5586f02c00..22ef492379 100644
--- a/editor/scene_tree_editor.h
+++ b/editor/scene_tree_editor.h
@@ -29,30 +29,30 @@
#ifndef SCENE_TREE_EDITOR_H
#define SCENE_TREE_EDITOR_H
-#include "scene/gui/tree.h"
+#include "editor_data.h"
+#include "editor_settings.h"
#include "scene/gui/button.h"
#include "scene/gui/dialogs.h"
+#include "scene/gui/tree.h"
#include "undo_redo.h"
-#include "editor_data.h"
-#include "editor_settings.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class SceneTreeEditor : public Control {
- GDCLASS( SceneTreeEditor, Control );
+ GDCLASS(SceneTreeEditor, Control);
EditorSelection *editor_selection;
enum {
- BUTTON_SUBSCENE=0,
- BUTTON_VISIBILITY=1,
- BUTTON_SCRIPT=2,
- BUTTON_LOCK=3,
- BUTTON_GROUP=4,
- BUTTON_WARNING=5,
- BUTTON_SIGNALS=6,
- BUTTON_GROUPS=7,
+ BUTTON_SUBSCENE = 0,
+ BUTTON_VISIBILITY = 1,
+ BUTTON_SCRIPT = 2,
+ BUTTON_LOCK = 3,
+ BUTTON_GROUP = 4,
+ BUTTON_WARNING = 5,
+ BUTTON_SIGNALS = 6,
+ BUTTON_GROUPS = 7,
};
enum {
@@ -79,18 +79,18 @@ class SceneTreeEditor : public Control {
int blocked;
- void _compute_hash(Node *p_node,uint64_t &hash);
+ void _compute_hash(Node *p_node, uint64_t &hash);
- bool _add_nodes(Node *p_node,TreeItem *p_parent);
+ bool _add_nodes(Node *p_node, TreeItem *p_parent);
void _test_update_tree();
void _update_tree();
void _tree_changed();
void _node_removed(Node *p_node);
- TreeItem* _find(TreeItem *p_node,const NodePath& p_path);
+ TreeItem *_find(TreeItem *p_node, const NodePath &p_path);
void _notification(int p_what);
void _selected_changed();
- void _rename_node(ObjectID p_node,const String& p_name);
+ void _rename_node(ObjectID p_node, const String &p_name);
void _cell_collapsed(Object *p_obj);
@@ -104,7 +104,7 @@ class SceneTreeEditor : public Control {
void _renamed();
UndoRedo *undo_redo;
- Set<Node*> marked;
+ Set<Node *> marked;
bool marked_selectable;
bool marked_children_selectable;
bool display_foreign;
@@ -112,67 +112,62 @@ class SceneTreeEditor : public Control {
bool pending_test_update;
static void _bind_methods();
- void _cell_button_pressed(Object *p_item,int p_column,int p_id);
- void _cell_multi_selected(Object *p_object,int p_cel,bool p_selected);
+ void _cell_button_pressed(Object *p_item, int p_column, int p_id);
+ void _cell_multi_selected(Object *p_object, int p_cel, bool p_selected);
void _update_selection(TreeItem *item);
void _node_script_changed(Node *p_node);
void _node_visibility_changed(Node *p_node);
void _update_visibility_color(Node *p_node, TreeItem *p_item);
void _subscene_option(int p_idx);
- void _node_replace_owner(Node* p_base,Node* p_node,Node* p_root);
-
+ void _node_replace_owner(Node *p_base, Node *p_node, Node *p_root);
void _selection_changed();
Node *get_scene_node();
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
- void _rmb_select(const Vector2& p_pos);
+ void _rmb_select(const Vector2 &p_pos);
- void _warning_changed(Node* p_for_node);
+ void _warning_changed(Node *p_for_node);
void _editor_settings_changed();
- Timer* update_timer;
+ Timer *update_timer;
List<StringName> *script_types;
bool _is_script_type(const StringName &p_type) const;
public:
-
- void set_filter(const String& p_filter);
+ void set_filter(const String &p_filter);
String get_filter() const;
- void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo=p_undo_redo; };
+ void set_undo_redo(UndoRedo *p_undo_redo) { undo_redo = p_undo_redo; };
void set_display_foreign_nodes(bool p_display);
bool get_display_foreign_nodes() const;
- void set_marked(const Set<Node*>& p_marked,bool p_selectable=false,bool p_children_selectable=true);
- void set_marked(Node *p_marked,bool p_selectable=false,bool p_children_selectable=true);
- void set_selected(Node *p_node,bool p_emit_selected=true);
+ void set_marked(const Set<Node *> &p_marked, bool p_selectable = false, bool p_children_selectable = true);
+ void set_marked(Node *p_marked, bool p_selectable = false, bool p_children_selectable = true);
+ void set_selected(Node *p_node, bool p_emit_selected = true);
Node *get_selected();
- void set_can_rename(bool p_can_rename) { can_rename=p_can_rename; }
+ void set_can_rename(bool p_can_rename) { can_rename = p_can_rename; }
void set_editor_selection(EditorSelection *p_selection);
- void set_show_enabled_subscene(bool p_show) { show_enabled_subscene=p_show; }
+ void set_show_enabled_subscene(bool p_show) { show_enabled_subscene = p_show; }
void update_tree() { _update_tree(); }
+ Tree *get_scene_tree() { return tree; }
- Tree* get_scene_tree() { return tree; }
-
- SceneTreeEditor(bool p_label=true,bool p_can_rename=false, bool p_can_open_instance=false);
+ SceneTreeEditor(bool p_label = true, bool p_can_rename = false, bool p_can_open_instance = false);
~SceneTreeEditor();
-
};
-
class SceneTreeDialog : public ConfirmationDialog {
- GDCLASS( SceneTreeDialog, ConfirmationDialog );
+ GDCLASS(SceneTreeDialog, ConfirmationDialog);
SceneTreeEditor *tree;
//Button *select;
@@ -182,18 +177,14 @@ class SceneTreeDialog : public ConfirmationDialog {
void _select();
void _cancel();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
SceneTreeEditor *get_scene_tree() { return tree; }
SceneTreeDialog();
~SceneTreeDialog();
-
};
-
#endif
diff --git a/editor/script_create_dialog.cpp b/editor/script_create_dialog.cpp
index dfaa1f645c..d1a8aa62e5 100644
--- a/editor/script_create_dialog.cpp
+++ b/editor/script_create_dialog.cpp
@@ -28,84 +28,81 @@
/*************************************************************************/
#include "script_create_dialog.h"
-#include "script_language.h"
+#include "editor_file_system.h"
#include "global_config.h"
#include "io/resource_saver.h"
#include "os/file_access.h"
-#include "editor_file_system.h"
+#include "script_language.h"
-void ScriptCreateDialog::config(const String& p_base_name,const String&p_base_path) {
+void ScriptCreateDialog::config(const String &p_base_name, const String &p_base_path) {
class_name->set_text("");
parent_name->set_text(p_base_name);
- if (p_base_path!="") {
- initial_bp=p_base_path.get_basename();
- file_path->set_text(initial_bp+"."+ScriptServer::get_language( language_menu->get_selected() )->get_extension());
+ if (p_base_path != "") {
+ initial_bp = p_base_path.get_basename();
+ file_path->set_text(initial_bp + "." + ScriptServer::get_language(language_menu->get_selected())->get_extension());
} else {
- initial_bp="";
+ initial_bp = "";
file_path->set_text("");
}
_class_name_changed("");
_path_changed(file_path->get_text());
}
-bool ScriptCreateDialog::_validate(const String& p_string) {
+bool ScriptCreateDialog::_validate(const String &p_string) {
- if (p_string.length()==0)
+ if (p_string.length() == 0)
return false;
+ for (int i = 0; i < p_string.length(); i++) {
- for(int i=0;i<p_string.length();i++) {
-
- if (i==0) {
- if (p_string[0]>='0' && p_string[0]<='9')
+ if (i == 0) {
+ if (p_string[0] >= '0' && p_string[0] <= '9')
return false; // no start with number plz
}
- bool valid_char = (p_string[i]>='0' && p_string[i]<='9') || (p_string[i]>='a' && p_string[i]<='z') || (p_string[i]>='A' && p_string[i]<='Z') || p_string[i]=='_';
+ bool valid_char = (p_string[i] >= '0' && p_string[i] <= '9') || (p_string[i] >= 'a' && p_string[i] <= 'z') || (p_string[i] >= 'A' && p_string[i] <= 'Z') || p_string[i] == '_';
if (!valid_char)
return false;
-
}
return true;
}
-void ScriptCreateDialog::_class_name_changed(const String& p_name) {
+void ScriptCreateDialog::_class_name_changed(const String &p_name) {
if (!_validate(parent_name->get_text())) {
error_label->set_text(TTR("Invalid parent class name"));
- error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ error_label->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
} else if (class_name->is_editable()) {
- if (class_name->get_text()=="") {
- error_label->set_text(TTR("Valid chars:")+" a-z A-Z 0-9 _");
- error_label->add_color_override("font_color",Color(1,1,1,0.6));
+ if (class_name->get_text() == "") {
+ error_label->set_text(TTR("Valid chars:") + " a-z A-Z 0-9 _");
+ error_label->add_color_override("font_color", Color(1, 1, 1, 0.6));
} else if (!_validate(class_name->get_text())) {
error_label->set_text(TTR("Invalid class name"));
- error_label->add_color_override("font_color",Color(1,0.2,0.2,0.8));
+ error_label->add_color_override("font_color", Color(1, 0.2, 0.2, 0.8));
} else {
error_label->set_text(TTR("Valid name"));
- error_label->add_color_override("font_color",Color(0,1.0,0.8,0.8));
+ error_label->add_color_override("font_color", Color(0, 1.0, 0.8, 0.8));
}
} else {
error_label->set_text(TTR("N/A"));
- error_label->add_color_override("font_color",Color(0,1.0,0.8,0.8));
+ error_label->add_color_override("font_color", Color(0, 1.0, 0.8, 0.8));
}
}
void ScriptCreateDialog::ok_pressed() {
- if (create_new){
+ if (create_new) {
_create_new();
} else {
_load_exist();
}
- create_new=true;
+ create_new = true;
_update_controls();
-
}
void ScriptCreateDialog::_create_new() {
@@ -123,14 +120,14 @@ void ScriptCreateDialog::_create_new() {
String cname;
if (class_name->is_editable())
- cname=class_name->get_text();
+ cname = class_name->get_text();
- Ref<Script> scr = ScriptServer::get_language( language_menu->get_selected() )->get_template(cname,parent_name->get_text());
+ Ref<Script> scr = ScriptServer::get_language(language_menu->get_selected())->get_template(cname, parent_name->get_text());
String selected_language = language_menu->get_item_text(language_menu->get_selected());
editor_settings->set_project_metadata("script_setup", "last_selected_language", selected_language);
- if (cname!="")
+ if (cname != "")
scr->set_name(cname);
if (!internal->is_pressed()) {
@@ -141,8 +138,8 @@ void ScriptCreateDialog::_create_new() {
alert->popup_centered_minsize();
return;
}
- Error err = ResourceSaver::save(lpath,scr,ResourceSaver::FLAG_CHANGE_PATH);
- if (err!=OK) {
+ Error err = ResourceSaver::save(lpath, scr, ResourceSaver::FLAG_CHANGE_PATH);
+ if (err != OK) {
alert->set_text(TTR("Could not create script in filesystem."));
alert->popup_centered_minsize();
return;
@@ -150,13 +147,12 @@ void ScriptCreateDialog::_create_new() {
}
hide();
- emit_signal("script_created",scr);
-
+ emit_signal("script_created", scr);
}
void ScriptCreateDialog::_load_exist() {
- String path=file_path->get_text();
+ String path = file_path->get_text();
RES p_script = ResourceLoader::load(path, "Script");
if (p_script.is_null()) {
alert->get_ok()->set_text(TTR("Ugh"));
@@ -166,41 +162,40 @@ void ScriptCreateDialog::_load_exist() {
}
hide();
- emit_signal("script_created",p_script.get_ref_ptr());
-
+ emit_signal("script_created", p_script.get_ref_ptr());
}
void ScriptCreateDialog::_lang_changed(int l) {
- l=language_menu->get_selected();
- if (ScriptServer::get_language( l )->has_named_classes()) {
+ l = language_menu->get_selected();
+ if (ScriptServer::get_language(l)->has_named_classes()) {
class_name->set_editable(true);
} else {
class_name->set_editable(false);
}
- String selected_ext="."+ScriptServer::get_language( l )->get_extension();
- String path=file_path->get_text();
- String extension="";
- if (path.find(".")>=0) {
- extension=path.get_extension();
+ String selected_ext = "." + ScriptServer::get_language(l)->get_extension();
+ String path = file_path->get_text();
+ String extension = "";
+ if (path.find(".") >= 0) {
+ extension = path.get_extension();
}
- if (extension.length()==0) {
+ if (extension.length() == 0) {
// add extension if none
- path+=selected_ext;
+ path += selected_ext;
_path_changed(path);
} else {
// change extension by selected language
List<String> extensions;
// get all possible extensions for script
- for (int l=0;l<language_menu->get_item_count();l++) {
- ScriptServer::get_language( l )->get_recognized_extensions(&extensions);
+ for (int l = 0; l < language_menu->get_item_count(); l++) {
+ ScriptServer::get_language(l)->get_recognized_extensions(&extensions);
}
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- if (E->get().nocasecmp_to(extension)==0) {
- path=path.get_basename()+selected_ext;
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ if (E->get().nocasecmp_to(extension) == 0) {
+ path = path.get_basename() + selected_ext;
_path_changed(path);
break;
}
@@ -208,7 +203,6 @@ void ScriptCreateDialog::_lang_changed(int l) {
}
file_path->set_text(path);
_class_name_changed(class_name->get_text());
-
}
void ScriptCreateDialog::_built_in_pressed() {
@@ -218,7 +212,6 @@ void ScriptCreateDialog::_built_in_pressed() {
} else {
path_vb->show();
}
-
}
void ScriptCreateDialog::_browse_path() {
@@ -229,80 +222,76 @@ void ScriptCreateDialog::_browse_path() {
List<String> extensions;
// get all possible extensions for script
- for (int l=0;l<language_menu->get_item_count();l++) {
- ScriptServer::get_language( l )->get_recognized_extensions(&extensions);
+ for (int l = 0; l < language_menu->get_item_count(); l++) {
+ ScriptServer::get_language(l)->get_recognized_extensions(&extensions);
}
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- file_browse->add_filter("*."+E->get());
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ file_browse->add_filter("*." + E->get());
}
file_browse->set_current_path(file_path->get_text());
file_browse->popup_centered_ratio();
-
}
-void ScriptCreateDialog::_file_selected(const String& p_file) {
+void ScriptCreateDialog::_file_selected(const String &p_file) {
String p = GlobalConfig::get_singleton()->localize_path(p_file);
file_path->set_text(p);
_path_changed(p);
-
}
-void ScriptCreateDialog::_path_changed(const String& p_path) {
+void ScriptCreateDialog::_path_changed(const String &p_path) {
- path_valid=false;
- String p =p_path;
+ path_valid = false;
+ String p = p_path;
- if (p=="") {
+ if (p == "") {
path_error_label->set_text(TTR("Path is empty"));
- path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ path_error_label->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
return;
-
}
p = GlobalConfig::get_singleton()->localize_path(p);
if (!p.begins_with("res://")) {
path_error_label->set_text(TTR("Path is not local"));
- path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ path_error_label->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
return;
}
if (p.find("/") || p.find("\\")) {
DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- if (d->change_dir(p.get_base_dir())!=OK) {
+ if (d->change_dir(p.get_base_dir()) != OK) {
path_error_label->set_text(TTR("Invalid base path"));
- path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ path_error_label->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
memdelete(d);
return;
-
}
memdelete(d);
}
FileAccess *f = FileAccess::create(FileAccess::ACCESS_RESOURCES);
- create_new=!f->file_exists(p);
+ create_new = !f->file_exists(p);
memdelete(f);
- String extension=p.get_extension();
+ String extension = p.get_extension();
List<String> extensions;
// get all possible extensions for script
- for (int l=0;l<language_menu->get_item_count();l++) {
- ScriptServer::get_language( l )->get_recognized_extensions(&extensions);
+ for (int l = 0; l < language_menu->get_item_count(); l++) {
+ ScriptServer::get_language(l)->get_recognized_extensions(&extensions);
}
- bool found=false;
- int index=0;
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- if (E->get().nocasecmp_to(extension)==0) {
+ bool found = false;
+ int index = 0;
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ if (E->get().nocasecmp_to(extension) == 0) {
language_menu->select(index); // change Language option by extension
- found=true;
+ found = true;
break;
}
index++;
@@ -310,16 +299,15 @@ void ScriptCreateDialog::_path_changed(const String& p_path) {
if (!found) {
path_error_label->set_text(TTR("Invalid extension"));
- path_error_label->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ path_error_label->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
return;
}
_update_controls();
- path_error_label->add_color_override("font_color",Color(0,1.0,0.8,0.8));
-
- path_valid=true;
+ path_error_label->add_color_override("font_color", Color(0, 1.0, 0.8, 0.8));
+ path_valid = true;
}
void ScriptCreateDialog::_update_controls() {
@@ -333,48 +321,45 @@ void ScriptCreateDialog::_update_controls() {
}
parent_name->set_editable(create_new);
internal->set_disabled(!create_new);
-
}
-
void ScriptCreateDialog::_bind_methods() {
- ClassDB::bind_method("_class_name_changed",&ScriptCreateDialog::_class_name_changed);
- ClassDB::bind_method("_lang_changed",&ScriptCreateDialog::_lang_changed);
- ClassDB::bind_method("_built_in_pressed",&ScriptCreateDialog::_built_in_pressed);
- ClassDB::bind_method("_browse_path",&ScriptCreateDialog::_browse_path);
- ClassDB::bind_method("_file_selected",&ScriptCreateDialog::_file_selected);
- ClassDB::bind_method("_path_changed",&ScriptCreateDialog::_path_changed);
- ADD_SIGNAL(MethodInfo("script_created",PropertyInfo(Variant::OBJECT,"script",PROPERTY_HINT_RESOURCE_TYPE,"Script")));
+ ClassDB::bind_method("_class_name_changed", &ScriptCreateDialog::_class_name_changed);
+ ClassDB::bind_method("_lang_changed", &ScriptCreateDialog::_lang_changed);
+ ClassDB::bind_method("_built_in_pressed", &ScriptCreateDialog::_built_in_pressed);
+ ClassDB::bind_method("_browse_path", &ScriptCreateDialog::_browse_path);
+ ClassDB::bind_method("_file_selected", &ScriptCreateDialog::_file_selected);
+ ClassDB::bind_method("_path_changed", &ScriptCreateDialog::_path_changed);
+ ADD_SIGNAL(MethodInfo("script_created", PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script")));
}
ScriptCreateDialog::ScriptCreateDialog() {
/* SNAP DIALOG */
- VBoxContainer *vb = memnew( VBoxContainer );
+ VBoxContainer *vb = memnew(VBoxContainer);
add_child(vb);
//set_child_rect(vb);
-
- class_name = memnew( LineEdit );
- VBoxContainer *vb2 = memnew( VBoxContainer );
+ class_name = memnew(LineEdit);
+ VBoxContainer *vb2 = memnew(VBoxContainer);
vb2->add_child(class_name);
- class_name->connect("text_changed", this,"_class_name_changed");
+ class_name->connect("text_changed", this, "_class_name_changed");
error_label = memnew(Label);
error_label->set_text("valid chars: a-z A-Z 0-9 _");
error_label->set_align(Label::ALIGN_CENTER);
vb2->add_child(error_label);
- vb->add_margin_child(TTR("Class Name:"),vb2);
+ vb->add_margin_child(TTR("Class Name:"), vb2);
- parent_name = memnew( LineEdit );
- vb->add_margin_child(TTR("Inherits:"),parent_name);
- parent_name->connect("text_changed", this,"_class_name_changed");
+ parent_name = memnew(LineEdit);
+ vb->add_margin_child(TTR("Inherits:"), parent_name);
+ parent_name->connect("text_changed", this, "_class_name_changed");
- language_menu = memnew( OptionButton );
- vb->add_margin_child(TTR("Language"),language_menu);
+ language_menu = memnew(OptionButton);
+ vb->add_margin_child(TTR("Language"), language_menu);
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
language_menu->add_item(ScriptServer::get_language(i)->get_name());
}
@@ -383,55 +368,53 @@ ScriptCreateDialog::ScriptCreateDialog() {
String last_selected_language = editor_settings->get_project_metadata("script_setup", "last_selected_language", "");
if (last_selected_language != "")
for (int i = 0; i < language_menu->get_item_count(); i++)
- if (language_menu->get_item_text(i) == last_selected_language)
- {
+ if (language_menu->get_item_text(i) == last_selected_language) {
language_menu->select(i);
break;
- }
- else language_menu->select(0);
+ } else
+ language_menu->select(0);
- language_menu->connect("item_selected",this,"_lang_changed");
+ language_menu->connect("item_selected", this, "_lang_changed");
//parent_name->set_text();
- vb2 = memnew( VBoxContainer );
- path_vb = memnew( VBoxContainer );
+ vb2 = memnew(VBoxContainer);
+ path_vb = memnew(VBoxContainer);
vb2->add_child(path_vb);
- HBoxContainer *hbc = memnew( HBoxContainer );
- file_path = memnew( LineEdit );
- file_path->connect("text_changed",this,"_path_changed");
+ HBoxContainer *hbc = memnew(HBoxContainer);
+ file_path = memnew(LineEdit);
+ file_path->connect("text_changed", this, "_path_changed");
hbc->add_child(file_path);
file_path->set_h_size_flags(SIZE_EXPAND_FILL);
- Button *b = memnew( Button );
+ Button *b = memnew(Button);
b->set_text(" .. ");
- b->connect("pressed",this,"_browse_path");
+ b->connect("pressed", this, "_browse_path");
hbc->add_child(b);
path_vb->add_child(hbc);
- path_error_label = memnew( Label );
- path_vb->add_child( path_error_label );
+ path_error_label = memnew(Label);
+ path_vb->add_child(path_error_label);
path_error_label->set_text(TTR("Error!"));
path_error_label->set_align(Label::ALIGN_CENTER);
-
- internal = memnew( CheckButton );
+ internal = memnew(CheckButton);
internal->set_text(TTR("Built-In Script"));
vb2->add_child(internal);
- internal->connect("pressed",this,"_built_in_pressed");
+ internal->connect("pressed", this, "_built_in_pressed");
- vb->add_margin_child(TTR("Path:"),vb2);
+ vb->add_margin_child(TTR("Path:"), vb2);
- set_size(Size2(200,150));
+ set_size(Size2(200, 150));
set_hide_on_ok(false);
set_title(TTR("Attach Node Script"));
- file_browse = memnew( EditorFileDialog );
- file_browse->connect("file_selected",this,"_file_selected");
+ file_browse = memnew(EditorFileDialog);
+ file_browse->connect("file_selected", this, "_file_selected");
add_child(file_browse);
get_ok()->set_text(TTR("Create"));
- alert = memnew( AcceptDialog );
+ alert = memnew(AcceptDialog);
add_child(alert);
_lang_changed(0);
- create_new=true;
+ create_new = true;
}
diff --git a/editor/script_create_dialog.h b/editor/script_create_dialog.h
index ad9616c071..a3ad06dbbf 100644
--- a/editor/script_create_dialog.h
+++ b/editor/script_create_dialog.h
@@ -29,15 +29,15 @@
#ifndef SCRIPT_CREATE_DIALOG_H
#define SCRIPT_CREATE_DIALOG_H
-#include "scene/gui/dialogs.h"
-#include "scene/gui/line_edit.h"
-#include "scene/gui/option_button.h"
#include "editor/editor_file_dialog.h"
#include "editor/editor_settings.h"
#include "scene/gui/check_button.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/option_button.h"
class ScriptCreateDialog : public ConfirmationDialog {
- GDCLASS(ScriptCreateDialog,ConfirmationDialog);
+ GDCLASS(ScriptCreateDialog, ConfirmationDialog);
LineEdit *class_name;
Label *error_label;
@@ -54,24 +54,23 @@ class ScriptCreateDialog : public ConfirmationDialog {
String initial_bp;
EditorSettings *editor_settings;
-
- void _path_changed(const String& p_path=String());
- void _lang_changed(int l=0);
+ void _path_changed(const String &p_path = String());
+ void _lang_changed(int l = 0);
void _built_in_pressed();
- bool _validate(const String& p_strin);
- void _class_name_changed(const String& p_name);
+ bool _validate(const String &p_strin);
+ void _class_name_changed(const String &p_name);
void _browse_path();
- void _file_selected(const String& p_file);
+ void _file_selected(const String &p_file);
virtual void ok_pressed();
void _create_new();
void _load_exist();
void _update_controls();
-protected:
+protected:
static void _bind_methods();
-public:
- void config(const String& p_base_name,const String&p_base_path);
+public:
+ void config(const String &p_base_name, const String &p_base_path);
ScriptCreateDialog();
};
diff --git a/editor/script_editor_debugger.cpp b/editor/script_editor_debugger.cpp
index fa33ffe5c7..b7a904c255 100644
--- a/editor/script_editor_debugger.cpp
+++ b/editor/script_editor_debugger.cpp
@@ -28,150 +28,134 @@
/*************************************************************************/
#include "script_editor_debugger.h"
-#include "scene/gui/separator.h"
-#include "scene/gui/label.h"
-#include "scene/gui/split_container.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/texture_button.h"
-#include "scene/gui/tab_container.h"
-#include "scene/gui/line_edit.h"
-#include "scene/gui/dialogs.h"
-#include "scene/gui/rich_text_label.h"
-#include "scene/gui/margin_container.h"
-#include "property_editor.h"
-#include "global_config.h"
#include "editor_node.h"
-#include "main/performance.h"
#include "editor_profiler.h"
#include "editor_settings.h"
+#include "global_config.h"
+#include "main/performance.h"
+#include "property_editor.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/label.h"
+#include "scene/gui/line_edit.h"
+#include "scene/gui/margin_container.h"
+#include "scene/gui/rich_text_label.h"
+#include "scene/gui/separator.h"
+#include "scene/gui/split_container.h"
+#include "scene/gui/tab_container.h"
+#include "scene/gui/texture_button.h"
+#include "scene/gui/tree.h"
class ScriptEditorDebuggerVariables : public Object {
- GDCLASS( ScriptEditorDebuggerVariables, Object );
+ GDCLASS(ScriptEditorDebuggerVariables, Object);
List<PropertyInfo> props;
- Map<StringName,Variant> values;
-protected:
+ Map<StringName, Variant> values;
- bool _set(const StringName& p_name, const Variant& p_value) {
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value) {
return false;
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ bool _get(const StringName &p_name, Variant &r_ret) const {
if (!values.has(p_name))
return false;
- r_ret=values[p_name];
+ r_ret = values[p_name];
return true;
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ void _get_property_list(List<PropertyInfo> *p_list) const {
- for(const List<PropertyInfo>::Element *E=props.front();E;E=E->next() )
+ for (const List<PropertyInfo>::Element *E = props.front(); E; E = E->next())
p_list->push_back(E->get());
}
-
public:
-
-
void clear() {
props.clear();
values.clear();
}
- String get_var_value(const String& p_var) const {
+ String get_var_value(const String &p_var) const {
- for(Map<StringName,Variant>::Element *E=values.front();E;E=E->next()) {
- String v = E->key().operator String().get_slice("/",1);
- if (v==p_var)
+ for (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) {
+ String v = E->key().operator String().get_slice("/", 1);
+ if (v == p_var)
return E->get();
}
return "";
}
- void add_property(const String &p_name, const Variant& p_value) {
+ void add_property(const String &p_name, const Variant &p_value) {
PropertyInfo pinfo;
- pinfo.name=p_name;
- pinfo.type=p_value.get_type();
+ pinfo.name = p_name;
+ pinfo.type = p_value.get_type();
props.push_back(pinfo);
- values[p_name]=p_value;
-
+ values[p_name] = p_value;
}
void update() {
_change_notify();
}
-
ScriptEditorDebuggerVariables() {
-
}
};
-
class ScriptEditorDebuggerInspectedObject : public Object {
- GDCLASS( ScriptEditorDebuggerInspectedObject, Object);
-
-
-
+ GDCLASS(ScriptEditorDebuggerInspectedObject, Object);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
if (!prop_values.has(p_name))
return false;
- emit_signal("value_edited",p_name,p_value);
- prop_values[p_name]=p_value;
+ emit_signal("value_edited", p_name, p_value);
+ prop_values[p_name] = p_value;
return true;
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ bool _get(const StringName &p_name, Variant &r_ret) const {
if (!prop_values.has(p_name))
return false;
- r_ret=prop_values[p_name];
+ r_ret = prop_values[p_name];
return true;
-
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ void _get_property_list(List<PropertyInfo> *p_list) const {
p_list->clear(); //sorry, no want category
- for (const List<PropertyInfo>::Element *E=prop_list.front();E;E=E->next()) {
+ for (const List<PropertyInfo>::Element *E = prop_list.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
}
-
static void _bind_methods() {
ADD_SIGNAL(MethodInfo("value_edited"));
}
public:
-
ObjectID last_edited_id;
List<PropertyInfo> prop_list;
- Map<StringName,Variant> prop_values;
+ Map<StringName, Variant> prop_values;
void update() {
_change_notify();
}
- void update_single(const char* p_prop) {
+ void update_single(const char *p_prop) {
_change_notify(p_prop);
}
- ScriptEditorDebuggerInspectedObject() { last_edited_id=0; }
-
-
+ ScriptEditorDebuggerInspectedObject() { last_edited_id = 0; }
};
void ScriptEditorDebugger::debug_next() {
@@ -184,7 +168,6 @@ void ScriptEditorDebugger::debug_next() {
ppeer->put_var(msg);
stack_dump->clear();
inspector->edit(NULL);
-
}
void ScriptEditorDebugger::debug_step() {
@@ -208,7 +191,6 @@ void ScriptEditorDebugger::debug_break() {
Array msg;
msg.push_back("break");
ppeer->put_var(msg);
-
}
void ScriptEditorDebugger::debug_continue() {
@@ -222,18 +204,15 @@ void ScriptEditorDebugger::debug_continue() {
Array msg;
msg.push_back("continue");
ppeer->put_var(msg);
-
-
}
-void ScriptEditorDebugger::_scene_tree_folded(Object* obj) {
-
+void ScriptEditorDebugger::_scene_tree_folded(Object *obj) {
if (updating_scene_tree) {
return;
}
- TreeItem *item=obj->cast_to<TreeItem>();
+ TreeItem *item = obj->cast_to<TreeItem>();
if (!item)
return;
@@ -244,13 +223,10 @@ void ScriptEditorDebugger::_scene_tree_folded(Object* obj) {
} else {
unfold_cache.insert(id);
}
-
-
}
void ScriptEditorDebugger::_scene_tree_selected() {
-
if (updating_scene_tree) {
return;
@@ -267,11 +243,9 @@ void ScriptEditorDebugger::_scene_tree_selected() {
msg.push_back("inspect_object");
msg.push_back(inspected_object_id);
ppeer->put_var(msg);
-
}
-void ScriptEditorDebugger::_scene_tree_property_value_edited(const String& p_prop,const Variant& p_value) {
-
+void ScriptEditorDebugger::_scene_tree_property_value_edited(const String &p_prop, const Variant &p_value) {
Array msg;
msg.push_back("set_object_property");
@@ -279,17 +253,16 @@ void ScriptEditorDebugger::_scene_tree_property_value_edited(const String& p_pro
msg.push_back(p_prop);
msg.push_back(p_value);
ppeer->put_var(msg);
- inspect_edited_object_timeout=0.7; //avoid annoyance, don't request soon after editing
+ inspect_edited_object_timeout = 0.7; //avoid annoyance, don't request soon after editing
}
void ScriptEditorDebugger::_scene_tree_property_select_object(ObjectID p_object) {
- inspected_object_id=p_object;
+ inspected_object_id = p_object;
Array msg;
msg.push_back("inspect_object");
msg.push_back(inspected_object_id);
ppeer->put_var(msg);
-
}
void ScriptEditorDebugger::_scene_tree_request() {
@@ -300,7 +273,6 @@ void ScriptEditorDebugger::_scene_tree_request() {
Array msg;
msg.push_back("request_scene_tree");
ppeer->put_var(msg);
-
}
void ScriptEditorDebugger::_video_mem_request() {
@@ -311,38 +283,34 @@ void ScriptEditorDebugger::_video_mem_request() {
Array msg;
msg.push_back("request_video_mem");
ppeer->put_var(msg);
-
}
Size2 ScriptEditorDebugger::get_minimum_size() const {
Size2 ms = Control::get_minimum_size();
- ms.y = MAX(ms.y , 250 );
+ ms.y = MAX(ms.y, 250);
return ms;
-
}
-void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_data) {
+void ScriptEditorDebugger::_parse_message(const String &p_msg, const Array &p_data) {
-
-
- if (p_msg=="debug_enter") {
+ if (p_msg == "debug_enter") {
Array msg;
msg.push_back("get_stack_dump");
ppeer->put_var(msg);
- ERR_FAIL_COND(p_data.size()!=2);
- bool can_continue=p_data[0];
+ ERR_FAIL_COND(p_data.size() != 2);
+ bool can_continue = p_data[0];
String error = p_data[1];
step->set_disabled(!can_continue);
next->set_disabled(!can_continue);
reason->set_text(error);
reason->set_tooltip(error);
- breaked=true;
+ breaked = true;
dobreak->set_disabled(true);
docontinue->set_disabled(false);
- emit_signal("breaked",true,can_continue);
+ emit_signal("breaked", true, can_continue);
OS::get_singleton()->move_window_to_foreground();
- if (error!="") {
+ if (error != "") {
tabs->set_current_tab(0);
}
@@ -350,12 +318,11 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
EditorNode::get_singleton()->get_pause_button()->set_pressed(true);
-
EditorNode::get_singleton()->make_bottom_panel_item_visible(this);
- } else if (p_msg=="debug_exit") {
+ } else if (p_msg == "debug_exit") {
- breaked=false;
+ breaked = false;
step->set_disabled(true);
next->set_disabled(true);
reason->set_text("");
@@ -364,47 +331,45 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
forward->set_disabled(true);
dobreak->set_disabled(false);
docontinue->set_disabled(true);
- emit_signal("breaked",false,false,Variant());
+ emit_signal("breaked", false, false, Variant());
//tabs->set_current_tab(0);
profiler->set_enabled(true);
profiler->disable_seeking();
EditorNode::get_singleton()->get_pause_button()->set_pressed(false);
-
- } else if (p_msg=="message:click_ctrl") {
+ } else if (p_msg == "message:click_ctrl") {
clicked_ctrl->set_text(p_data[0]);
clicked_ctrl_type->set_text(p_data[1]);
- } else if (p_msg=="message:scene_tree") {
+ } else if (p_msg == "message:scene_tree") {
inspect_scene_tree->clear();
- Map<int,TreeItem*> lv;
+ Map<int, TreeItem *> lv;
- updating_scene_tree=true;
+ updating_scene_tree = true;
- for(int i=0;i<p_data.size();i+=4) {
+ for (int i = 0; i < p_data.size(); i += 4) {
TreeItem *p;
int level = p_data[i];
- if (level==0) {
+ if (level == 0) {
p = NULL;
} else {
- ERR_CONTINUE(!lv.has(level-1));
- p=lv[level-1];
+ ERR_CONTINUE(!lv.has(level - 1));
+ p = lv[level - 1];
}
-
TreeItem *it = inspect_scene_tree->create_item(p);
- ObjectID id = ObjectID(p_data[i+3]);
+ ObjectID id = ObjectID(p_data[i + 3]);
- it->set_text(0,p_data[i+1]);
- if (has_icon(p_data[i+2],"EditorIcons"))
- it->set_icon(0,get_icon(p_data[i+2],"EditorIcons"));
- it->set_metadata(0,id);
- if (id==inspected_object_id) {
+ it->set_text(0, p_data[i + 1]);
+ if (has_icon(p_data[i + 2], "EditorIcons"))
+ it->set_icon(0, get_icon(p_data[i + 2], "EditorIcons"));
+ it->set_metadata(0, id);
+ if (id == inspected_object_id) {
it->select(0);
}
@@ -417,100 +382,93 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
it->set_collapsed(true);
}
}
- lv[level]=it;
+ lv[level] = it;
}
- updating_scene_tree=false;
+ updating_scene_tree = false;
le_clear->set_disabled(false);
le_set->set_disabled(false);
- } else if (p_msg=="message:inspect_object") {
-
+ } else if (p_msg == "message:inspect_object") {
ObjectID id = p_data[0];
String type = p_data[1];
Variant path = p_data[2]; //what to do yet, i don't know
- int prop_count=p_data[3];
+ int prop_count = p_data[3];
- int idx=4;
+ int idx = 4;
-
- if (inspected_object->last_edited_id!=id) {
+ if (inspected_object->last_edited_id != id) {
inspected_object->prop_list.clear();
inspected_object->prop_values.clear();
}
- for(int i=0;i<prop_count;i++) {
+ for (int i = 0; i < prop_count; i++) {
PropertyInfo pinfo;
- pinfo.name=p_data[idx++];
- pinfo.type=Variant::Type(int(p_data[idx++]));
- pinfo.hint=PropertyHint(int(p_data[idx++]));
- pinfo.hint_string=p_data[idx++];
+ pinfo.name = p_data[idx++];
+ pinfo.type = Variant::Type(int(p_data[idx++]));
+ pinfo.hint = PropertyHint(int(p_data[idx++]));
+ pinfo.hint_string = p_data[idx++];
if (pinfo.name.begins_with("*")) {
- pinfo.name=pinfo.name.substr(1,pinfo.name.length());
- pinfo.usage=PROPERTY_USAGE_CATEGORY;
+ pinfo.name = pinfo.name.substr(1, pinfo.name.length());
+ pinfo.usage = PROPERTY_USAGE_CATEGORY;
} else {
- pinfo.usage=PROPERTY_USAGE_EDITOR;
+ pinfo.usage = PROPERTY_USAGE_EDITOR;
}
- if (inspected_object->last_edited_id!=id) {
+ if (inspected_object->last_edited_id != id) {
//don't update.. it's the same, instead refresh
inspected_object->prop_list.push_back(pinfo);
}
+ inspected_object->prop_values[pinfo.name] = p_data[idx++];
- inspected_object->prop_values[pinfo.name]=p_data[idx++];
-
- if (inspected_object->last_edited_id==id) {
+ if (inspected_object->last_edited_id == id) {
//same, just update value, don't rebuild
inspected_object->update_single(pinfo.name.ascii().get_data());
}
-
}
-
-
- if (inspected_object->last_edited_id!=id) {
+ if (inspected_object->last_edited_id != id) {
//only if different
inspected_object->update();
}
- inspected_object->last_edited_id=id;
-
+ inspected_object->last_edited_id = id;
inspect_properties->edit(inspected_object);
- } else if (p_msg=="message:video_mem") {
+ } else if (p_msg == "message:video_mem") {
vmem_tree->clear();
- TreeItem* root=vmem_tree->create_item();
+ TreeItem *root = vmem_tree->create_item();
- int total=0;
+ int total = 0;
- for(int i=0;i<p_data.size();i+=4) {
+ for (int i = 0; i < p_data.size(); i += 4) {
TreeItem *it = vmem_tree->create_item(root);
- String type=p_data[i+1];
- int bytes=p_data[i+3].operator int();
- it->set_text(0,p_data[i+0]); //path
- it->set_text(1,type); //type
- it->set_text(2,p_data[i+2]); //type
- it->set_text(3,String::humanize_size(bytes)); //type
- total+=bytes;
-
- if (has_icon(type,"EditorIcons"))
- it->set_icon(0,get_icon(type,"EditorIcons"));
+ String type = p_data[i + 1];
+ int bytes = p_data[i + 3].operator int();
+ it->set_text(0, p_data[i + 0]); //path
+ it->set_text(1, type); //type
+ it->set_text(2, p_data[i + 2]); //type
+ it->set_text(3, String::humanize_size(bytes)); //type
+ total += bytes;
+
+ if (has_icon(type, "EditorIcons"))
+ it->set_icon(0, get_icon(type, "EditorIcons"));
}
- vmem_total->set_tooltip(TTR("Bytes:")+" "+itos(total));
+ vmem_total->set_tooltip(TTR("Bytes:") + " " + itos(total));
vmem_total->set_text(String::humanize_size(total));
- } else if (p_msg=="stack_dump") {
+ } else if (p_msg == "stack_dump") {
stack_dump->clear();
TreeItem *r = stack_dump->create_item();
- for(int i=0;i<p_data.size();i++) {
+ for (int i = 0; i < p_data.size(); i++) {
Dictionary d = p_data[i];
ERR_CONTINUE(!d.has("function"));
@@ -518,65 +476,61 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
ERR_CONTINUE(!d.has("line"));
ERR_CONTINUE(!d.has("id"));
TreeItem *s = stack_dump->create_item(r);
- d["frame"]=i;
- s->set_metadata(0,d);
+ d["frame"] = i;
+ s->set_metadata(0, d);
//String line = itos(i)+" - "+String(d["file"])+":"+itos(d["line"])+" - at func: "+d["function"];
- String line = itos(i)+" - "+String(d["file"])+":"+itos(d["line"]);
- s->set_text(0,line);
+ String line = itos(i) + " - " + String(d["file"]) + ":" + itos(d["line"]);
+ s->set_text(0, line);
- if (i==0)
+ if (i == 0)
s->select(0);
}
- } else if (p_msg=="stack_frame_vars") {
-
+ } else if (p_msg == "stack_frame_vars") {
variables->clear();
-
-
- int ofs =0;
+ int ofs = 0;
int mcount = p_data[ofs];
ofs++;
- for(int i=0;i<mcount;i++) {
+ for (int i = 0; i < mcount; i++) {
- String n = p_data[ofs+i*2+0];
- Variant v = p_data[ofs+i*2+1];
+ String n = p_data[ofs + i * 2 + 0];
+ Variant v = p_data[ofs + i * 2 + 1];
if (n.begins_with("*")) {
- n=n.substr(1,n.length());
+ n = n.substr(1, n.length());
}
- variables->add_property("members/"+n,v);
+ variables->add_property("members/" + n, v);
}
- ofs+=mcount*2;
+ ofs += mcount * 2;
mcount = p_data[ofs];
ofs++;
- for(int i=0;i<mcount;i++) {
+ for (int i = 0; i < mcount; i++) {
- String n = p_data[ofs+i*2+0];
- Variant v = p_data[ofs+i*2+1];
+ String n = p_data[ofs + i * 2 + 0];
+ Variant v = p_data[ofs + i * 2 + 1];
if (n.begins_with("*")) {
- n=n.substr(1,n.length());
+ n = n.substr(1, n.length());
}
-
- variables->add_property("locals/"+n,v);
+ variables->add_property("locals/" + n, v);
}
variables->update();
inspector->edit(variables);
- } else if (p_msg=="output") {
+ } else if (p_msg == "output") {
//OUT
- for(int i=0;i<p_data.size();i++) {
+ for (int i = 0; i < p_data.size(); i++) {
String t = p_data[i];
//LOG
@@ -587,26 +541,24 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
}
}
EditorNode::get_log()->add_message(t);
-
}
- } else if (p_msg=="performance") {
+ } else if (p_msg == "performance") {
Array arr = p_data[0];
Vector<float> p;
p.resize(arr.size());
- for(int i=0;i<arr.size();i++) {
- p[i]=arr[i];
- if (i<perf_items.size()) {
- perf_items[i]->set_text(1,rtos(p[i]));
- if (p[i]>perf_max[i])
- perf_max[i]=p[i];
+ for (int i = 0; i < arr.size(); i++) {
+ p[i] = arr[i];
+ if (i < perf_items.size()) {
+ perf_items[i]->set_text(1, rtos(p[i]));
+ if (p[i] > perf_max[i])
+ perf_max[i] = p[i];
}
-
}
perf_history.push_front(p);
perf_draw->update();
- } else if (p_msg=="error") {
+ } else if (p_msg == "error") {
Array err = p_data[0];
@@ -618,30 +570,28 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
bool warning = err[9];
bool e;
- String time = String("%d:%02d:%02d:%04d").sprintf(vals,&e);
- String txt=time+" - "+(err[8].is_zero()?String(err[7]):String(err[8]));
-
- String tooltip=TTR("Type:")+String(warning?TTR("Warning"):TTR("Error"));
- tooltip+="\n"+TTR("Description:")+" "+String(err[8]);
- tooltip+="\n"+TTR("Time:")+" "+time;
- tooltip+="\nC "+TTR("Error:")+" "+String(err[7]);
- tooltip+="\nC "+TTR("Source:")+" "+String(err[5])+":"+String(err[6]);
- tooltip+="\nC "+TTR("Function:")+" "+String(err[4]);
-
+ String time = String("%d:%02d:%02d:%04d").sprintf(vals, &e);
+ String txt = time + " - " + (err[8].is_zero() ? String(err[7]) : String(err[8]));
+ String tooltip = TTR("Type:") + String(warning ? TTR("Warning") : TTR("Error"));
+ tooltip += "\n" + TTR("Description:") + " " + String(err[8]);
+ tooltip += "\n" + TTR("Time:") + " " + time;
+ tooltip += "\nC " + TTR("Error:") + " " + String(err[7]);
+ tooltip += "\nC " + TTR("Source:") + " " + String(err[5]) + ":" + String(err[6]);
+ tooltip += "\nC " + TTR("Function:") + " " + String(err[4]);
- error_list->add_item(txt,EditorNode::get_singleton()->get_gui_base()->get_icon(warning?"Warning":"Error","EditorIcons"));
- error_list->set_item_tooltip( error_list->get_item_count() -1,tooltip );
+ error_list->add_item(txt, EditorNode::get_singleton()->get_gui_base()->get_icon(warning ? "Warning" : "Error", "EditorIcons"));
+ error_list->set_item_tooltip(error_list->get_item_count() - 1, tooltip);
int scc = p_data[1];
Array stack;
stack.resize(scc);
- for(int i=0;i<scc;i++) {
- stack[i]=p_data[2+i];
+ for (int i = 0; i < scc; i++) {
+ stack[i] = p_data[2 + i];
}
- error_list->set_item_metadata( error_list->get_item_count() -1,stack );
+ error_list->set_item_metadata(error_list->get_item_count() - 1, stack);
error_count++;
/*
@@ -664,252 +614,230 @@ void ScriptEditorDebugger::_parse_message(const String& p_msg,const Array& p_dat
packet_peer_stream->put_var(oe.callstack);
*/
- } else if (p_msg=="profile_sig") {
+ } else if (p_msg == "profile_sig") {
//cache a signature
- print_line("SIG: "+String(Variant(p_data)));
- profiler_signature[p_data[1]]=p_data[0];
+ print_line("SIG: " + String(Variant(p_data)));
+ profiler_signature[p_data[1]] = p_data[0];
- } else if (p_msg=="profile_frame" || p_msg=="profile_total") {
+ } else if (p_msg == "profile_frame" || p_msg == "profile_total") {
EditorProfiler::Metric metric;
- metric.valid=true;
- metric.frame_number=p_data[0];
- metric.frame_time=p_data[1];
- metric.idle_time=p_data[2];
- metric.fixed_time=p_data[3];
- metric.fixed_frame_time=p_data[4];
+ metric.valid = true;
+ metric.frame_number = p_data[0];
+ metric.frame_time = p_data[1];
+ metric.idle_time = p_data[2];
+ metric.fixed_time = p_data[3];
+ metric.fixed_frame_time = p_data[4];
int frame_data_amount = p_data[6];
int frame_function_amount = p_data[7];
-
if (frame_data_amount) {
EditorProfiler::Metric::Category frame_time;
- frame_time.signature="category_frame_time";
- frame_time.name="Frame Time";
- frame_time.total_time=metric.frame_time;
+ frame_time.signature = "category_frame_time";
+ frame_time.name = "Frame Time";
+ frame_time.total_time = metric.frame_time;
EditorProfiler::Metric::Category::Item item;
- item.calls=1;
- item.line=0;
- item.name="Fixed Time";
- item.total=metric.fixed_time;
- item.self=item.total;
- item.signature="fixed_time";
-
+ item.calls = 1;
+ item.line = 0;
+ item.name = "Fixed Time";
+ item.total = metric.fixed_time;
+ item.self = item.total;
+ item.signature = "fixed_time";
frame_time.items.push_back(item);
- item.name="Idle Time";
- item.total=metric.idle_time;
- item.self=item.total;
- item.signature="idle_time";
+ item.name = "Idle Time";
+ item.total = metric.idle_time;
+ item.self = item.total;
+ item.signature = "idle_time";
frame_time.items.push_back(item);
- item.name="Fixed Frame Time";
- item.total=metric.fixed_frame_time;
- item.self=item.total;
- item.signature="fixed_frame_time";
+ item.name = "Fixed Frame Time";
+ item.total = metric.fixed_frame_time;
+ item.self = item.total;
+ item.signature = "fixed_frame_time";
frame_time.items.push_back(item);
metric.categories.push_back(frame_time);
-
}
-
-
- int idx=8;
- for(int i=0;i<frame_data_amount;i++) {
+ int idx = 8;
+ for (int i = 0; i < frame_data_amount; i++) {
EditorProfiler::Metric::Category c;
- String name=p_data[idx++];
- Array values=p_data[idx++];
- c.name=name.capitalize();
- c.items.resize(values.size()/2);
- c.total_time=0;
- c.signature="categ::"+name;
- for(int i=0;i<values.size();i+=2) {
+ String name = p_data[idx++];
+ Array values = p_data[idx++];
+ c.name = name.capitalize();
+ c.items.resize(values.size() / 2);
+ c.total_time = 0;
+ c.signature = "categ::" + name;
+ for (int i = 0; i < values.size(); i += 2) {
EditorProfiler::Metric::Category::Item item;
- item.name=values[i];
- item.calls=1;
- item.self=values[i+1];
- item.total=item.self;
- item.signature="categ::"+name+"::"+item.name;
- item.name=item.name.capitalize();
- c.total_time+=item.total;
- c.items[i/2]=item;
-
-
+ item.name = values[i];
+ item.calls = 1;
+ item.self = values[i + 1];
+ item.total = item.self;
+ item.signature = "categ::" + name + "::" + item.name;
+ item.name = item.name.capitalize();
+ c.total_time += item.total;
+ c.items[i / 2] = item;
}
metric.categories.push_back(c);
}
EditorProfiler::Metric::Category funcs;
- funcs.total_time=p_data[5]; //script time
+ funcs.total_time = p_data[5]; //script time
funcs.items.resize(frame_function_amount);
- funcs.name="Script Functions";
- funcs.signature="script_functions";
- for(int i=0;i<frame_function_amount;i++) {
+ funcs.name = "Script Functions";
+ funcs.signature = "script_functions";
+ for (int i = 0; i < frame_function_amount; i++) {
int signature = p_data[idx++];
int calls = p_data[idx++];
float total = p_data[idx++];
float self = p_data[idx++];
-
-
EditorProfiler::Metric::Category::Item item;
if (profiler_signature.has(signature)) {
- item.signature=profiler_signature[signature];
+ item.signature = profiler_signature[signature];
String name = profiler_signature[signature];
Vector<String> strings = name.split("::");
- if (strings.size()==3) {
- item.name=strings[2];
- item.script=strings[0];
- item.line=strings[1].to_int();
+ if (strings.size() == 3) {
+ item.name = strings[2];
+ item.script = strings[0];
+ item.line = strings[1].to_int();
}
} else {
- item.name="SigErr "+itos(signature);
+ item.name = "SigErr " + itos(signature);
}
-
-
-
- item.calls=calls;
- item.self=self;
- item.total=total;
- funcs.items[i]=item;
-
+ item.calls = calls;
+ item.self = self;
+ item.total = total;
+ funcs.items[i] = item;
}
metric.categories.push_back(funcs);
- if (p_msg=="profile_frame")
- profiler->add_frame_metric(metric,false);
+ if (p_msg == "profile_frame")
+ profiler->add_frame_metric(metric, false);
else
- profiler->add_frame_metric(metric,true);
+ profiler->add_frame_metric(metric, true);
- } else if (p_msg=="kill_me") {
+ } else if (p_msg == "kill_me") {
editor->call_deferred("stop_child_process");
}
-
}
-
-void ScriptEditorDebugger::_performance_select(Object*,int,bool) {
+void ScriptEditorDebugger::_performance_select(Object *, int, bool) {
perf_draw->update();
-
}
void ScriptEditorDebugger::_performance_draw() {
-
Vector<int> which;
- for(int i=0;i<perf_items.size();i++) {
-
+ for (int i = 0; i < perf_items.size(); i++) {
if (perf_items[i]->is_selected(0))
which.push_back(i);
}
-
- if(which.empty())
+ if (which.empty())
return;
- Ref<StyleBox> graph_sb = get_stylebox("normal","TextEdit");
- Ref<Font> graph_font = get_font("font","TextEdit");
+ Ref<StyleBox> graph_sb = get_stylebox("normal", "TextEdit");
+ Ref<Font> graph_font = get_font("font", "TextEdit");
int cols = Math::ceil(Math::sqrt((float)which.size()));
- int rows = (which.size()+1)/cols;
- if (which.size()==1)
- rows=1;
-
-
- int margin =3;
- int point_sep=5;
- Size2i s = Size2i(perf_draw->get_size())/Size2i(cols,rows);
- for(int i=0;i<which.size();i++) {
-
- Point2i p(i%cols,i/cols);
- Rect2i r(p*s,s);
- r.pos+=Point2(margin,margin);
- r.size-=Point2(margin,margin)*2.0;
- perf_draw->draw_style_box(graph_sb,r);
- r.pos+=graph_sb->get_offset();
- r.size-=graph_sb->get_minimum_size();
- int pi=which[i];
- Color c = Color(0.7,0.9,0.5);
- c.set_hsv(Math::fmod(c.get_h()+pi*0.7654,1),c.get_s(),c.get_v());
-
- c.a=0.8;
- perf_draw->draw_string(graph_font,r.pos+Point2(0,graph_font->get_ascent()),perf_items[pi]->get_text(0),c,r.size.x);
- c.a=0.6;
- perf_draw->draw_string(graph_font,r.pos+Point2(graph_font->get_char_size('X').width,graph_font->get_ascent()+graph_font->get_height()),perf_items[pi]->get_text(1),c,r.size.y);
-
- float spacing=point_sep/float(cols);
+ int rows = (which.size() + 1) / cols;
+ if (which.size() == 1)
+ rows = 1;
+
+ int margin = 3;
+ int point_sep = 5;
+ Size2i s = Size2i(perf_draw->get_size()) / Size2i(cols, rows);
+ for (int i = 0; i < which.size(); i++) {
+
+ Point2i p(i % cols, i / cols);
+ Rect2i r(p * s, s);
+ r.pos += Point2(margin, margin);
+ r.size -= Point2(margin, margin) * 2.0;
+ perf_draw->draw_style_box(graph_sb, r);
+ r.pos += graph_sb->get_offset();
+ r.size -= graph_sb->get_minimum_size();
+ int pi = which[i];
+ Color c = Color(0.7, 0.9, 0.5);
+ c.set_hsv(Math::fmod(c.get_h() + pi * 0.7654, 1), c.get_s(), c.get_v());
+
+ c.a = 0.8;
+ perf_draw->draw_string(graph_font, r.pos + Point2(0, graph_font->get_ascent()), perf_items[pi]->get_text(0), c, r.size.x);
+ c.a = 0.6;
+ perf_draw->draw_string(graph_font, r.pos + Point2(graph_font->get_char_size('X').width, graph_font->get_ascent() + graph_font->get_height()), perf_items[pi]->get_text(1), c, r.size.y);
+
+ float spacing = point_sep / float(cols);
float from = r.size.width;
- List<Vector<float> >::Element *E=perf_history.front();
- float prev=-1;
- while(from>=0 && E) {
+ List<Vector<float> >::Element *E = perf_history.front();
+ float prev = -1;
+ while (from >= 0 && E) {
float m = perf_max[pi];
- if (m==0)
- m=0.00001;
- float h = E->get()[pi]/m;
- h=(1.0-h)*r.size.y;
-
- c.a=0.7;
- if (E!=perf_history.front())
- perf_draw->draw_line(r.pos+Point2(from,h),r.pos+Point2(from+spacing,prev),c,2.0);
- prev=h;
- E=E->next();
- from-=spacing;
+ if (m == 0)
+ m = 0.00001;
+ float h = E->get()[pi] / m;
+ h = (1.0 - h) * r.size.y;
+
+ c.a = 0.7;
+ if (E != perf_history.front())
+ perf_draw->draw_line(r.pos + Point2(from, h), r.pos + Point2(from + spacing, prev), c, 2.0);
+ prev = h;
+ E = E->next();
+ from -= spacing;
}
-
}
-
}
void ScriptEditorDebugger::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
inspector->edit(variables);
- step->set_icon( get_icon("DebugStep","EditorIcons"));
- next->set_icon( get_icon("DebugNext","EditorIcons"));
- back->set_icon( get_icon("Back","EditorIcons"));
- forward->set_icon( get_icon("Forward","EditorIcons"));
- dobreak->set_icon( get_icon("Pause","EditorIcons"));
- docontinue->set_icon( get_icon("DebugContinue","EditorIcons"));
+ step->set_icon(get_icon("DebugStep", "EditorIcons"));
+ next->set_icon(get_icon("DebugNext", "EditorIcons"));
+ back->set_icon(get_icon("Back", "EditorIcons"));
+ forward->set_icon(get_icon("Forward", "EditorIcons"));
+ dobreak->set_icon(get_icon("Pause", "EditorIcons"));
+ docontinue->set_icon(get_icon("DebugContinue", "EditorIcons"));
//scene_tree_refresh->set_icon( get_icon("Reload","EditorIcons"));
- le_set->connect("pressed",this,"_live_edit_set");
- le_clear->connect("pressed",this,"_live_edit_clear");
- error_list->connect("item_selected",this,"_error_selected");
- error_stack->connect("item_selected",this,"_error_stack_selected");
- vmem_refresh->set_icon( get_icon("Reload","EditorIcons"));
+ le_set->connect("pressed", this, "_live_edit_set");
+ le_clear->connect("pressed", this, "_live_edit_clear");
+ error_list->connect("item_selected", this, "_error_selected");
+ error_stack->connect("item_selected", this, "_error_stack_selected");
+ vmem_refresh->set_icon(get_icon("Reload", "EditorIcons"));
} break;
case NOTIFICATION_PROCESS: {
if (connection.is_valid()) {
- inspect_scene_tree_timeout-=get_process_delta_time();
- if (inspect_scene_tree_timeout<0) {
- inspect_scene_tree_timeout=EditorSettings::get_singleton()->get("debugger/scene_tree_refresh_interval");
+ inspect_scene_tree_timeout -= get_process_delta_time();
+ if (inspect_scene_tree_timeout < 0) {
+ inspect_scene_tree_timeout = EditorSettings::get_singleton()->get("debugger/scene_tree_refresh_interval");
if (inspect_scene_tree->is_visible_in_tree()) {
_scene_tree_request();
- if (inspected_object_id!=0) {
+ if (inspected_object_id != 0) {
//take the chance and re-inspect selected object
Array msg;
msg.push_back("inspect_object");
@@ -919,9 +847,9 @@ void ScriptEditorDebugger::_notification(int p_what) {
}
}
- inspect_edited_object_timeout-=get_process_delta_time();
- if (inspect_edited_object_timeout<0) {
- inspect_edited_object_timeout=EditorSettings::get_singleton()->get("debugger/remote_inspect_refresh_interval");
+ inspect_edited_object_timeout -= get_process_delta_time();
+ if (inspect_edited_object_timeout < 0) {
+ inspect_edited_object_timeout = EditorSettings::get_singleton()->get("debugger/remote_inspect_refresh_interval");
if (inspect_scene_tree->is_visible_in_tree() && inspected_object_id) {
//take the chance and re-inspect selected object
Array msg;
@@ -932,20 +860,20 @@ void ScriptEditorDebugger::_notification(int p_what) {
}
}
- if (error_count!=last_error_count) {
+ if (error_count != last_error_count) {
- if (error_count==0) {
+ if (error_count == 0) {
error_split->set_name(TTR("Errors"));
debugger_button->set_text(TTR("Debugger"));
debugger_button->set_icon(Ref<Texture>());
- tabs->set_tab_icon(error_split->get_index(),Ref<Texture>());
+ tabs->set_tab_icon(error_split->get_index(), Ref<Texture>());
} else {
- error_split->set_name(TTR("Errors")+" ("+itos(error_count)+")");
- debugger_button->set_text(TTR("Debugger")+" ("+itos(error_count)+")");
- debugger_button->set_icon(get_icon("Error","EditorIcons"));
- tabs->set_tab_icon(error_split->get_index(),get_icon("Error","EditorIcons"));
+ error_split->set_name(TTR("Errors") + " (" + itos(error_count) + ")");
+ debugger_button->set_text(TTR("Debugger") + " (" + itos(error_count) + ")");
+ debugger_button->set_icon(get_icon("Error", "EditorIcons"));
+ tabs->set_tab_icon(error_split->get_index(), get_icon("Error", "EditorIcons"));
}
- last_error_count=error_count;
+ last_error_count = error_count;
}
if (connection.is_null()) {
@@ -975,7 +903,7 @@ void ScriptEditorDebugger::_notification(int p_what) {
le_clear->set_disabled(false);
error_list->clear();
error_stack->clear();
- error_count=0;
+ error_count = 0;
profiler_signature.clear();
//live_edit_root->set_text("/root");
@@ -987,7 +915,6 @@ void ScriptEditorDebugger::_notification(int p_what) {
_profiler_activate(true);
}
-
} else {
break;
@@ -1004,86 +931,76 @@ void ScriptEditorDebugger::_notification(int p_what) {
break;
};
- while(ppeer->get_available_packet_count() > 0) {
+ while (ppeer->get_available_packet_count() > 0) {
if (pending_in_queue) {
- int todo = MIN( ppeer->get_available_packet_count(), pending_in_queue );
+ int todo = MIN(ppeer->get_available_packet_count(), pending_in_queue);
- for(int i=0;i<todo;i++) {
+ for (int i = 0; i < todo; i++) {
Variant cmd;
Error ret = ppeer->get_var(cmd);
- if (ret!=OK) {
+ if (ret != OK) {
stop();
- ERR_FAIL_COND(ret!=OK);
+ ERR_FAIL_COND(ret != OK);
}
message.push_back(cmd);
pending_in_queue--;
}
-
- if (pending_in_queue==0) {
- _parse_message(message_type,message);
+ if (pending_in_queue == 0) {
+ _parse_message(message_type, message);
message.clear();
-
}
-
} else {
- if (ppeer->get_available_packet_count()>=2) {
-
+ if (ppeer->get_available_packet_count() >= 2) {
Variant cmd;
Error ret = ppeer->get_var(cmd);
- if (ret!=OK) {
+ if (ret != OK) {
stop();
- ERR_FAIL_COND(ret!=OK);
+ ERR_FAIL_COND(ret != OK);
}
- if (cmd.get_type()!=Variant::STRING) {
+ if (cmd.get_type() != Variant::STRING) {
stop();
- ERR_FAIL_COND(cmd.get_type()!=Variant::STRING);
+ ERR_FAIL_COND(cmd.get_type() != Variant::STRING);
}
- message_type=cmd;
+ message_type = cmd;
//print_line("GOT: "+message_type);
ret = ppeer->get_var(cmd);
- if (ret!=OK) {
+ if (ret != OK) {
stop();
- ERR_FAIL_COND(ret!=OK);
+ ERR_FAIL_COND(ret != OK);
}
- if (cmd.get_type()!=Variant::INT) {
+ if (cmd.get_type() != Variant::INT) {
stop();
- ERR_FAIL_COND(cmd.get_type()!=Variant::INT);
+ ERR_FAIL_COND(cmd.get_type() != Variant::INT);
}
- pending_in_queue=cmd;
+ pending_in_queue = cmd;
- if (pending_in_queue==0) {
- _parse_message(message_type,Array());
+ if (pending_in_queue == 0) {
+ _parse_message(message_type, Array());
message.clear();
}
} else {
-
break;
}
-
}
}
-
-
} break;
}
-
}
-
void ScriptEditorDebugger::start() {
stop();
@@ -1094,28 +1011,22 @@ void ScriptEditorDebugger::start() {
uint16_t port = GLOBAL_GET("network/debug/remote_port");
perf_history.clear();
- for(int i=0;i<Performance::MONITOR_MAX;i++) {
+ for (int i = 0; i < Performance::MONITOR_MAX; i++) {
- perf_max[i]=0;
+ perf_max[i] = 0;
}
server->listen(port);
set_process(true);
-
}
-void ScriptEditorDebugger::pause(){
-
-
+void ScriptEditorDebugger::pause() {
}
-void ScriptEditorDebugger::unpause(){
-
-
+void ScriptEditorDebugger::unpause() {
}
-void ScriptEditorDebugger::stop(){
-
+void ScriptEditorDebugger::stop() {
set_process(false);
@@ -1128,7 +1039,7 @@ void ScriptEditorDebugger::stop(){
connection.unref();
}
- pending_in_queue=0;
+ pending_in_queue = 0;
message.clear();
node_path_cache.clear();
@@ -1144,14 +1055,11 @@ void ScriptEditorDebugger::stop(){
EditorNode::get_singleton()->get_pause_button()->set_pressed(false);
EditorNode::get_singleton()->get_pause_button()->set_disabled(true);
-
-
if (hide_on_stop) {
if (is_visible_in_tree())
EditorNode::get_singleton()->hide_bottom_panel();
- emit_signal("show_debugger",false);
+ emit_signal("show_debugger", false);
}
-
}
void ScriptEditorDebugger::_profiler_activate(bool p_enable) {
@@ -1159,13 +1067,12 @@ void ScriptEditorDebugger::_profiler_activate(bool p_enable) {
if (!connection.is_valid())
return;
-
if (p_enable) {
profiler_signature.clear();
Array msg;
msg.push_back("start_profiling");
int max_funcs = EditorSettings::get_singleton()->get("debugger/profiler_frame_max_functions");
- max_funcs = CLAMP(max_funcs,16,512);
+ max_funcs = CLAMP(max_funcs, 16, 512);
msg.push_back(max_funcs);
ppeer->put_var(msg);
@@ -1177,9 +1084,7 @@ void ScriptEditorDebugger::_profiler_activate(bool p_enable) {
ppeer->put_var(msg);
print_line("END PROFILING!");
-
}
-
}
void ScriptEditorDebugger::_profiler_seeked() {
@@ -1192,18 +1097,16 @@ void ScriptEditorDebugger::_profiler_seeked() {
debug_break();
}
-
void ScriptEditorDebugger::_stack_dump_frame_selected() {
TreeItem *ti = stack_dump->get_selected();
if (!ti)
return;
-
Dictionary d = ti->get_metadata(0);
Ref<Script> s = ResourceLoader::load(d["file"]);
- emit_signal("goto_script_line",s,int(d["line"])-1);
+ emit_signal("goto_script_line", s, int(d["line"]) - 1);
ERR_FAIL_COND(connection.is_null());
ERR_FAIL_COND(!connection->is_connected_to_host());
@@ -1213,23 +1116,21 @@ void ScriptEditorDebugger::_stack_dump_frame_selected() {
msg.push_back("get_stack_frame_vars");
msg.push_back(d["frame"]);
ppeer->put_var(msg);
-
}
void ScriptEditorDebugger::_output_clear() {
//output->clear();
//output->push_color(Color(0,0,0));
-
}
-String ScriptEditorDebugger::get_var_value(const String& p_var) const {
+String ScriptEditorDebugger::get_var_value(const String &p_var) const {
if (!breaked)
return String();
return variables->get_var_value(p_var);
}
-int ScriptEditorDebugger::_get_node_path_cache(const NodePath& p_path) {
+int ScriptEditorDebugger::_get_node_path_cache(const NodePath &p_path) {
const int *r = node_path_cache.getptr(p_path);
if (r)
@@ -1237,38 +1138,36 @@ int ScriptEditorDebugger::_get_node_path_cache(const NodePath& p_path) {
last_path_id++;
- node_path_cache[p_path]=last_path_id;
+ node_path_cache[p_path] = last_path_id;
Array msg;
msg.push_back("live_node_path");
msg.push_back(p_path);
msg.push_back(last_path_id);
ppeer->put_var(msg);
-
return last_path_id;
}
-int ScriptEditorDebugger::_get_res_path_cache(const String& p_path) {
+int ScriptEditorDebugger::_get_res_path_cache(const String &p_path) {
- Map<String,int>::Element *E=res_path_cache.find(p_path);
+ Map<String, int>::Element *E = res_path_cache.find(p_path);
if (E)
return E->get();
last_path_id++;
- res_path_cache[p_path]=last_path_id;
+ res_path_cache[p_path] = last_path_id;
Array msg;
msg.push_back("live_res_path");
msg.push_back(p_path);
msg.push_back(last_path_id);
ppeer->put_var(msg);
-
return last_path_id;
}
-void ScriptEditorDebugger::_method_changed(Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE) {
+void ScriptEditorDebugger::_method_changed(Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE) {
if (!p_base || !live_debug || !connection.is_valid() || !editor->get_edited_scene())
return;
@@ -1277,9 +1176,9 @@ void ScriptEditorDebugger::_method_changed(Object*p_base,const StringName& p_nam
VARIANT_ARGPTRS
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
//no pointers, sorry
- if (argptr[i] && (argptr[i]->get_type()==Variant::OBJECT || argptr[i]->get_type()==Variant::_RID))
+ if (argptr[i] && (argptr[i]->get_type() == Variant::OBJECT || argptr[i]->get_type() == Variant::_RID))
return;
}
@@ -1288,25 +1187,22 @@ void ScriptEditorDebugger::_method_changed(Object*p_base,const StringName& p_nam
NodePath path = editor->get_edited_scene()->get_path_to(node);
int pathid = _get_node_path_cache(path);
-
-
Array msg;
msg.push_back("live_node_call");
msg.push_back(pathid);
msg.push_back(p_name);
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
//no pointers, sorry
msg.push_back(*argptr[i]);
}
ppeer->put_var(msg);
return;
-
}
Resource *res = p_base->cast_to<Resource>();
- if (res && res->get_path()!=String()) {
+ if (res && res->get_path() != String()) {
String respath = res->get_path();
int pathid = _get_res_path_cache(respath);
@@ -1315,7 +1211,7 @@ void ScriptEditorDebugger::_method_changed(Object*p_base,const StringName& p_nam
msg.push_back("live_res_call");
msg.push_back(pathid);
msg.push_back(p_name);
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
//no pointers, sorry
msg.push_back(*argptr[i]);
}
@@ -1327,7 +1223,7 @@ void ScriptEditorDebugger::_method_changed(Object*p_base,const StringName& p_nam
//print_line("method");
}
-void ScriptEditorDebugger::_property_changed(Object*p_base,const StringName& p_property,const Variant& p_value){
+void ScriptEditorDebugger::_property_changed(Object *p_base, const StringName &p_property, const Variant &p_value) {
if (!p_base || !live_debug || !connection.is_valid() || !editor->get_edited_scene())
return;
@@ -1339,10 +1235,9 @@ void ScriptEditorDebugger::_property_changed(Object*p_base,const StringName& p_p
NodePath path = editor->get_edited_scene()->get_path_to(node);
int pathid = _get_node_path_cache(path);
-
if (p_value.is_ref()) {
Ref<Resource> res = p_value;
- if (res.is_valid() && res->get_path()!=String()) {
+ if (res.is_valid() && res->get_path() != String()) {
Array msg;
msg.push_back("live_node_prop_res");
@@ -1361,22 +1256,19 @@ void ScriptEditorDebugger::_property_changed(Object*p_base,const StringName& p_p
ppeer->put_var(msg);
}
-
return;
-
}
Resource *res = p_base->cast_to<Resource>();
- if (res && res->get_path()!=String()) {
+ if (res && res->get_path() != String()) {
String respath = res->get_path();
int pathid = _get_res_path_cache(respath);
-
if (p_value.is_ref()) {
Ref<Resource> res = p_value;
- if (res.is_valid() && res->get_path()!=String()) {
+ if (res.is_valid() && res->get_path() != String()) {
Array msg;
msg.push_back("live_res_prop_res");
@@ -1395,32 +1287,27 @@ void ScriptEditorDebugger::_property_changed(Object*p_base,const StringName& p_p
ppeer->put_var(msg);
}
-
return;
}
-
//print_line("prop");
}
-void ScriptEditorDebugger::_method_changeds(void *p_ud,Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE) {
-
- ScriptEditorDebugger *sed = (ScriptEditorDebugger*)p_ud;
- sed->_method_changed(p_base,p_name,VARIANT_ARG_PASS);
-
+void ScriptEditorDebugger::_method_changeds(void *p_ud, Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE) {
+ ScriptEditorDebugger *sed = (ScriptEditorDebugger *)p_ud;
+ sed->_method_changed(p_base, p_name, VARIANT_ARG_PASS);
}
-void ScriptEditorDebugger::_property_changeds(void *p_ud,Object*p_base,const StringName& p_property,const Variant& p_value){
-
- ScriptEditorDebugger *sed = (ScriptEditorDebugger*)p_ud;
- sed->_property_changed(p_base,p_property,p_value);
+void ScriptEditorDebugger::_property_changeds(void *p_ud, Object *p_base, const StringName &p_property, const Variant &p_value) {
+ ScriptEditorDebugger *sed = (ScriptEditorDebugger *)p_ud;
+ sed->_property_changed(p_base, p_property, p_value);
}
void ScriptEditorDebugger::set_live_debugging(bool p_enable) {
- live_debug=p_enable;
+ live_debug = p_enable;
}
void ScriptEditorDebugger::_live_edit_set() {
@@ -1428,16 +1315,15 @@ void ScriptEditorDebugger::_live_edit_set() {
if (!connection.is_valid())
return;
- TreeItem* ti = inspect_scene_tree->get_selected();
+ TreeItem *ti = inspect_scene_tree->get_selected();
if (!ti)
return;
String path;
- while(ti) {
- String lp=ti->get_text(0);
- path="/"+lp+path;
- ti=ti->get_parent();
-
+ while (ti) {
+ String lp = ti->get_text(0);
+ path = "/" + lp + path;
+ ti = ti->get_parent();
}
NodePath np = path;
@@ -1445,8 +1331,6 @@ void ScriptEditorDebugger::_live_edit_set() {
editor->get_editor_data().set_edited_scene_live_edit_root(np);
update_live_edit_root();
-
-
}
void ScriptEditorDebugger::_live_edit_clear() {
@@ -1455,7 +1339,6 @@ void ScriptEditorDebugger::_live_edit_clear() {
editor->get_editor_data().set_edited_scene_live_edit_root(np);
update_live_edit_root();
-
}
void ScriptEditorDebugger::update_live_edit_root() {
@@ -1473,10 +1356,9 @@ void ScriptEditorDebugger::update_live_edit_root() {
ppeer->put_var(msg);
}
live_edit_root->set_text(np);
-
}
-void ScriptEditorDebugger::live_debug_create_node(const NodePath& p_parent,const String& p_type,const String& p_name) {
+void ScriptEditorDebugger::live_debug_create_node(const NodePath &p_parent, const String &p_type, const String &p_name) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1488,7 +1370,7 @@ void ScriptEditorDebugger::live_debug_create_node(const NodePath& p_parent,const
}
}
-void ScriptEditorDebugger::live_debug_instance_node(const NodePath& p_parent,const String& p_path,const String& p_name){
+void ScriptEditorDebugger::live_debug_instance_node(const NodePath &p_parent, const String &p_path, const String &p_name) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1498,9 +1380,8 @@ void ScriptEditorDebugger::live_debug_instance_node(const NodePath& p_parent,con
msg.push_back(p_name);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::live_debug_remove_node(const NodePath& p_at){
+void ScriptEditorDebugger::live_debug_remove_node(const NodePath &p_at) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1508,9 +1389,8 @@ void ScriptEditorDebugger::live_debug_remove_node(const NodePath& p_at){
msg.push_back(p_at);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::live_debug_remove_and_keep_node(const NodePath& p_at,ObjectID p_keep_id) {
+void ScriptEditorDebugger::live_debug_remove_and_keep_node(const NodePath &p_at, ObjectID p_keep_id) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1519,9 +1399,8 @@ void ScriptEditorDebugger::live_debug_remove_and_keep_node(const NodePath& p_at,
msg.push_back(p_keep_id);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::live_debug_restore_node(ObjectID p_id, const NodePath& p_at, int p_at_pos){
+void ScriptEditorDebugger::live_debug_restore_node(ObjectID p_id, const NodePath &p_at, int p_at_pos) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1531,9 +1410,8 @@ void ScriptEditorDebugger::live_debug_restore_node(ObjectID p_id, const NodePath
msg.push_back(p_at_pos);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::live_debug_duplicate_node(const NodePath& p_at,const String& p_new_name){
+void ScriptEditorDebugger::live_debug_duplicate_node(const NodePath &p_at, const String &p_new_name) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1542,9 +1420,8 @@ void ScriptEditorDebugger::live_debug_duplicate_node(const NodePath& p_at,const
msg.push_back(p_new_name);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::live_debug_reparent_node(const NodePath& p_at, const NodePath& p_new_place, const String &p_new_name, int p_at_pos){
+void ScriptEditorDebugger::live_debug_reparent_node(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) {
if (live_debug && connection.is_valid()) {
Array msg;
@@ -1555,67 +1432,62 @@ void ScriptEditorDebugger::live_debug_reparent_node(const NodePath& p_at, const
msg.push_back(p_at_pos);
ppeer->put_var(msg);
}
-
}
-void ScriptEditorDebugger::set_breakpoint(const String& p_path,int p_line,bool p_enabled) {
+void ScriptEditorDebugger::set_breakpoint(const String &p_path, int p_line, bool p_enabled) {
if (connection.is_valid()) {
- Array msg;
- msg.push_back("breakpoint");
- msg.push_back(p_path);
- msg.push_back(p_line);
- msg.push_back(p_enabled);
- ppeer->put_var(msg);
- }
+ Array msg;
+ msg.push_back("breakpoint");
+ msg.push_back(p_path);
+ msg.push_back(p_line);
+ msg.push_back(p_enabled);
+ ppeer->put_var(msg);
+ }
}
-
void ScriptEditorDebugger::reload_scripts() {
if (connection.is_valid()) {
- Array msg;
- msg.push_back("reload_scripts");
- ppeer->put_var(msg);
- }
+ Array msg;
+ msg.push_back("reload_scripts");
+ ppeer->put_var(msg);
+ }
}
-
void ScriptEditorDebugger::_error_selected(int p_idx) {
error_stack->clear();
- Array st=error_list->get_item_metadata(p_idx);
- for(int i=0;i<st.size();i+=2) {
+ Array st = error_list->get_item_metadata(p_idx);
+ for (int i = 0; i < st.size(); i += 2) {
- String script=st[i];
- int line=st[i+1];
+ String script = st[i];
+ int line = st[i + 1];
Array md;
md.push_back(st[i]);
- md.push_back(st[i+1]);
+ md.push_back(st[i + 1]);
- String str = script.get_file()+":"+itos(line);
+ String str = script.get_file() + ":" + itos(line);
error_stack->add_item(str);
- error_stack->set_item_metadata(error_stack->get_item_count()-1,md);
- error_stack->set_item_tooltip(error_stack->get_item_count()-1,TTR("File:")+" "+String(st[i])+"\n"+TTR("Line:")+" "+itos(line));
+ error_stack->set_item_metadata(error_stack->get_item_count() - 1, md);
+ error_stack->set_item_tooltip(error_stack->get_item_count() - 1, TTR("File:") + " " + String(st[i]) + "\n" + TTR("Line:") + " " + itos(line));
}
}
-void ScriptEditorDebugger:: _error_stack_selected(int p_idx){
+void ScriptEditorDebugger::_error_stack_selected(int p_idx) {
Array arr = error_stack->get_item_metadata(p_idx);
- if (arr.size()!=2)
+ if (arr.size() != 2)
return;
-
Ref<Script> s = ResourceLoader::load(arr[0]);
- emit_signal("goto_script_line",s,int(arr[1])-1);
-
+ emit_signal("goto_script_line", s, int(arr[1]) - 1);
}
void ScriptEditorDebugger::set_hide_on_stop(bool p_hide) {
- hide_on_stop=p_hide;
+ hide_on_stop = p_hide;
}
void ScriptEditorDebugger::_paused() {
@@ -1630,180 +1502,169 @@ void ScriptEditorDebugger::_paused() {
if (breaked && !EditorNode::get_singleton()->get_pause_button()->is_pressed()) {
debug_continue();
}
-
}
void ScriptEditorDebugger::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_stack_dump_frame_selected"),&ScriptEditorDebugger::_stack_dump_frame_selected);
- ClassDB::bind_method(D_METHOD("debug_next"),&ScriptEditorDebugger::debug_next);
- ClassDB::bind_method(D_METHOD("debug_step"),&ScriptEditorDebugger::debug_step);
- ClassDB::bind_method(D_METHOD("debug_break"),&ScriptEditorDebugger::debug_break);
- ClassDB::bind_method(D_METHOD("debug_continue"),&ScriptEditorDebugger::debug_continue);
- ClassDB::bind_method(D_METHOD("_output_clear"),&ScriptEditorDebugger::_output_clear);
- ClassDB::bind_method(D_METHOD("_performance_draw"),&ScriptEditorDebugger::_performance_draw);
- ClassDB::bind_method(D_METHOD("_performance_select"),&ScriptEditorDebugger::_performance_select);
- ClassDB::bind_method(D_METHOD("_scene_tree_request"),&ScriptEditorDebugger::_scene_tree_request);
- ClassDB::bind_method(D_METHOD("_video_mem_request"),&ScriptEditorDebugger::_video_mem_request);
- ClassDB::bind_method(D_METHOD("_live_edit_set"),&ScriptEditorDebugger::_live_edit_set);
- ClassDB::bind_method(D_METHOD("_live_edit_clear"),&ScriptEditorDebugger::_live_edit_clear);
-
- ClassDB::bind_method(D_METHOD("_error_selected"),&ScriptEditorDebugger::_error_selected);
- ClassDB::bind_method(D_METHOD("_error_stack_selected"),&ScriptEditorDebugger::_error_stack_selected);
- ClassDB::bind_method(D_METHOD("_profiler_activate"),&ScriptEditorDebugger::_profiler_activate);
- ClassDB::bind_method(D_METHOD("_profiler_seeked"),&ScriptEditorDebugger::_profiler_seeked);
-
- ClassDB::bind_method(D_METHOD("_paused"),&ScriptEditorDebugger::_paused);
-
- ClassDB::bind_method(D_METHOD("_scene_tree_selected"),&ScriptEditorDebugger::_scene_tree_selected);
- ClassDB::bind_method(D_METHOD("_scene_tree_folded"),&ScriptEditorDebugger::_scene_tree_folded);
-
-
- ClassDB::bind_method(D_METHOD("live_debug_create_node"),&ScriptEditorDebugger::live_debug_create_node);
- ClassDB::bind_method(D_METHOD("live_debug_instance_node"),&ScriptEditorDebugger::live_debug_instance_node);
- ClassDB::bind_method(D_METHOD("live_debug_remove_node"),&ScriptEditorDebugger::live_debug_remove_node);
- ClassDB::bind_method(D_METHOD("live_debug_remove_and_keep_node"),&ScriptEditorDebugger::live_debug_remove_and_keep_node);
- ClassDB::bind_method(D_METHOD("live_debug_restore_node"),&ScriptEditorDebugger::live_debug_restore_node);
- ClassDB::bind_method(D_METHOD("live_debug_duplicate_node"),&ScriptEditorDebugger::live_debug_duplicate_node);
- ClassDB::bind_method(D_METHOD("live_debug_reparent_node"),&ScriptEditorDebugger::live_debug_reparent_node);
- ClassDB::bind_method(D_METHOD("_scene_tree_property_select_object"),&ScriptEditorDebugger::_scene_tree_property_select_object);
- ClassDB::bind_method(D_METHOD("_scene_tree_property_value_edited"),&ScriptEditorDebugger::_scene_tree_property_value_edited);
+ ClassDB::bind_method(D_METHOD("_stack_dump_frame_selected"), &ScriptEditorDebugger::_stack_dump_frame_selected);
+ ClassDB::bind_method(D_METHOD("debug_next"), &ScriptEditorDebugger::debug_next);
+ ClassDB::bind_method(D_METHOD("debug_step"), &ScriptEditorDebugger::debug_step);
+ ClassDB::bind_method(D_METHOD("debug_break"), &ScriptEditorDebugger::debug_break);
+ ClassDB::bind_method(D_METHOD("debug_continue"), &ScriptEditorDebugger::debug_continue);
+ ClassDB::bind_method(D_METHOD("_output_clear"), &ScriptEditorDebugger::_output_clear);
+ ClassDB::bind_method(D_METHOD("_performance_draw"), &ScriptEditorDebugger::_performance_draw);
+ ClassDB::bind_method(D_METHOD("_performance_select"), &ScriptEditorDebugger::_performance_select);
+ ClassDB::bind_method(D_METHOD("_scene_tree_request"), &ScriptEditorDebugger::_scene_tree_request);
+ ClassDB::bind_method(D_METHOD("_video_mem_request"), &ScriptEditorDebugger::_video_mem_request);
+ ClassDB::bind_method(D_METHOD("_live_edit_set"), &ScriptEditorDebugger::_live_edit_set);
+ ClassDB::bind_method(D_METHOD("_live_edit_clear"), &ScriptEditorDebugger::_live_edit_clear);
+
+ ClassDB::bind_method(D_METHOD("_error_selected"), &ScriptEditorDebugger::_error_selected);
+ ClassDB::bind_method(D_METHOD("_error_stack_selected"), &ScriptEditorDebugger::_error_stack_selected);
+ ClassDB::bind_method(D_METHOD("_profiler_activate"), &ScriptEditorDebugger::_profiler_activate);
+ ClassDB::bind_method(D_METHOD("_profiler_seeked"), &ScriptEditorDebugger::_profiler_seeked);
+
+ ClassDB::bind_method(D_METHOD("_paused"), &ScriptEditorDebugger::_paused);
+
+ ClassDB::bind_method(D_METHOD("_scene_tree_selected"), &ScriptEditorDebugger::_scene_tree_selected);
+ ClassDB::bind_method(D_METHOD("_scene_tree_folded"), &ScriptEditorDebugger::_scene_tree_folded);
+
+ ClassDB::bind_method(D_METHOD("live_debug_create_node"), &ScriptEditorDebugger::live_debug_create_node);
+ ClassDB::bind_method(D_METHOD("live_debug_instance_node"), &ScriptEditorDebugger::live_debug_instance_node);
+ ClassDB::bind_method(D_METHOD("live_debug_remove_node"), &ScriptEditorDebugger::live_debug_remove_node);
+ ClassDB::bind_method(D_METHOD("live_debug_remove_and_keep_node"), &ScriptEditorDebugger::live_debug_remove_and_keep_node);
+ ClassDB::bind_method(D_METHOD("live_debug_restore_node"), &ScriptEditorDebugger::live_debug_restore_node);
+ ClassDB::bind_method(D_METHOD("live_debug_duplicate_node"), &ScriptEditorDebugger::live_debug_duplicate_node);
+ ClassDB::bind_method(D_METHOD("live_debug_reparent_node"), &ScriptEditorDebugger::live_debug_reparent_node);
+ ClassDB::bind_method(D_METHOD("_scene_tree_property_select_object"), &ScriptEditorDebugger::_scene_tree_property_select_object);
+ ClassDB::bind_method(D_METHOD("_scene_tree_property_value_edited"), &ScriptEditorDebugger::_scene_tree_property_value_edited);
ADD_SIGNAL(MethodInfo("goto_script_line"));
- ADD_SIGNAL(MethodInfo("breaked",PropertyInfo(Variant::BOOL,"reallydid"),PropertyInfo(Variant::BOOL,"can_debug")));
- ADD_SIGNAL(MethodInfo("show_debugger",PropertyInfo(Variant::BOOL,"reallydid")));
+ ADD_SIGNAL(MethodInfo("breaked", PropertyInfo(Variant::BOOL, "reallydid"), PropertyInfo(Variant::BOOL, "can_debug")));
+ ADD_SIGNAL(MethodInfo("show_debugger", PropertyInfo(Variant::BOOL, "reallydid")));
}
-ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){
-
-
+ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor) {
- ppeer = Ref<PacketPeerStream>( memnew( PacketPeerStream ) );
- editor=p_editor;
+ ppeer = Ref<PacketPeerStream>(memnew(PacketPeerStream));
+ editor = p_editor;
- tabs = memnew( TabContainer );
+ tabs = memnew(TabContainer);
tabs->set_v_size_flags(SIZE_EXPAND_FILL);
tabs->set_area_as_parent_rect();
add_child(tabs);
-
{ //debugger
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
vbc->set_name(TTR("Debugger"));
//tabs->add_child(vbc);
- Control *dbg=vbc;
+ Control *dbg = vbc;
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
-
- reason = memnew( LineEdit );
+ reason = memnew(LineEdit);
reason->set_text("");
reason->set_editable(false);
hbc->add_child(reason);
- reason->add_color_override("font_color",Color(1,0.4,0.0,0.8));
+ reason->add_color_override("font_color", Color(1, 0.4, 0.0, 0.8));
reason->set_h_size_flags(SIZE_EXPAND_FILL);
//reason->set_clip_text(true);
- hbc->add_child( memnew( VSeparator) );
+ hbc->add_child(memnew(VSeparator));
- step = memnew( Button );
+ step = memnew(Button);
hbc->add_child(step);
step->set_tooltip(TTR("Step Into"));
- step->connect("pressed",this,"debug_step");
+ step->connect("pressed", this, "debug_step");
- next = memnew( Button );
+ next = memnew(Button);
hbc->add_child(next);
next->set_tooltip(TTR("Step Over"));
- next->connect("pressed",this,"debug_next");
+ next->connect("pressed", this, "debug_next");
- hbc->add_child( memnew( VSeparator) );
+ hbc->add_child(memnew(VSeparator));
- dobreak = memnew( Button );
+ dobreak = memnew(Button);
hbc->add_child(dobreak);
dobreak->set_tooltip(TTR("Break"));
- dobreak->connect("pressed",this,"debug_break");
+ dobreak->connect("pressed", this, "debug_break");
- docontinue = memnew( Button );
+ docontinue = memnew(Button);
hbc->add_child(docontinue);
docontinue->set_tooltip(TTR("Continue"));
- docontinue->connect("pressed",this,"debug_continue");
+ docontinue->connect("pressed", this, "debug_continue");
//hbc->add_child( memnew( VSeparator) );
- back = memnew( Button );
+ back = memnew(Button);
hbc->add_child(back);
back->set_tooltip(TTR("Inspect Previous Instance"));
back->hide();
- forward = memnew( Button );
+ forward = memnew(Button);
hbc->add_child(forward);
forward->set_tooltip(TTR("Inspect Next Instance"));
forward->hide();
-
- HSplitContainer *sc = memnew( HSplitContainer );
+ HSplitContainer *sc = memnew(HSplitContainer);
vbc->add_child(sc);
sc->set_v_size_flags(SIZE_EXPAND_FILL);
- stack_dump = memnew( Tree );
+ stack_dump = memnew(Tree);
stack_dump->set_columns(1);
stack_dump->set_column_titles_visible(true);
- stack_dump->set_column_title(0,TTR("Stack Frames"));
+ stack_dump->set_column_title(0, TTR("Stack Frames"));
stack_dump->set_h_size_flags(SIZE_EXPAND_FILL);
stack_dump->set_hide_root(true);
- stack_dump->connect("cell_selected",this,"_stack_dump_frame_selected");
+ stack_dump->connect("cell_selected", this, "_stack_dump_frame_selected");
sc->add_child(stack_dump);
- inspector = memnew( PropertyEditor );
+ inspector = memnew(PropertyEditor);
inspector->set_h_size_flags(SIZE_EXPAND_FILL);
inspector->hide_top_label();
- inspector->get_scene_tree()->set_column_title(0,TTR("Variable"));
+ inspector->get_scene_tree()->set_column_title(0, TTR("Variable"));
inspector->set_capitalize_paths(false);
inspector->set_read_only(true);
sc->add_child(inspector);
server = TCP_Server::create_ref();
- pending_in_queue=0;
+ pending_in_queue = 0;
- variables = memnew( ScriptEditorDebuggerVariables );
+ variables = memnew(ScriptEditorDebuggerVariables);
- breaked=false;
+ breaked = false;
tabs->add_child(dbg);
//tabs->move_child(vbc,0);
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
vbc->add_child(hbc);
-
}
- { //errors
-
+ { //errors
- error_split = memnew( HSplitContainer );
- VBoxContainer *errvb = memnew( VBoxContainer );
+ error_split = memnew(HSplitContainer);
+ VBoxContainer *errvb = memnew(VBoxContainer);
errvb->set_h_size_flags(SIZE_EXPAND_FILL);
- error_list = memnew( ItemList );
- errvb->add_margin_child(TTR("Errors:"),error_list,true);
+ error_list = memnew(ItemList);
+ errvb->add_margin_child(TTR("Errors:"), error_list, true);
error_split->add_child(errvb);
- errvb = memnew( VBoxContainer );
+ errvb = memnew(VBoxContainer);
errvb->set_h_size_flags(SIZE_EXPAND_FILL);
- error_stack = memnew( ItemList );
- errvb->add_margin_child(TTR("Stack Trace (if applicable):"),error_stack,true);
+ error_stack = memnew(ItemList);
+ errvb->add_margin_child(TTR("Stack Trace (if applicable):"), error_stack, true);
error_split->add_child(errvb);
error_split->set_name(TTR("Errors"));
tabs->add_child(error_split);
}
-
{ // inquire
-
- inspect_info = memnew( HSplitContainer );
+ inspect_info = memnew(HSplitContainer);
inspect_info->set_name(TTR("Remote Inspector"));
tabs->add_child(inspect_info);
@@ -1811,10 +1672,10 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){
info_left->set_h_size_flags(SIZE_EXPAND_FILL);
inspect_info->add_child(info_left);
- inspect_scene_tree = memnew( Tree );
- info_left->add_margin_child(TTR("Live Scene Tree:"),inspect_scene_tree,true);
- inspect_scene_tree->connect("cell_selected",this,"_scene_tree_selected");
- inspect_scene_tree->connect("item_collapsed",this,"_scene_tree_folded");
+ inspect_scene_tree = memnew(Tree);
+ info_left->add_margin_child(TTR("Live Scene Tree:"), inspect_scene_tree, true);
+ inspect_scene_tree->connect("cell_selected", this, "_scene_tree_selected");
+ inspect_scene_tree->connect("item_collapsed", this, "_scene_tree_folded");
//
@@ -1822,95 +1683,93 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){
info_right->set_h_size_flags(SIZE_EXPAND_FILL);
inspect_info->add_child(info_right);
- inspect_properties = memnew( PropertyEditor );
+ inspect_properties = memnew(PropertyEditor);
inspect_properties->hide_top_label();
inspect_properties->set_show_categories(true);
- inspect_properties->connect("object_id_selected",this,"_scene_tree_property_select_object");
+ inspect_properties->connect("object_id_selected", this, "_scene_tree_property_select_object");
- info_right->add_margin_child(TTR("Remote Object Properties: "),inspect_properties,true);
+ info_right->add_margin_child(TTR("Remote Object Properties: "), inspect_properties, true);
- inspect_scene_tree_timeout=EDITOR_DEF("debugger/scene_tree_refresh_interval",1.0);
- inspect_edited_object_timeout=EDITOR_DEF("debugger/remote_inspect_refresh_interval",0.2);
- inspected_object_id=0;
- updating_scene_tree=false;
+ inspect_scene_tree_timeout = EDITOR_DEF("debugger/scene_tree_refresh_interval", 1.0);
+ inspect_edited_object_timeout = EDITOR_DEF("debugger/remote_inspect_refresh_interval", 0.2);
+ inspected_object_id = 0;
+ updating_scene_tree = false;
- inspected_object = memnew( ScriptEditorDebuggerInspectedObject );
- inspected_object->connect("value_edited",this,"_scene_tree_property_value_edited");
+ inspected_object = memnew(ScriptEditorDebuggerInspectedObject);
+ inspected_object->connect("value_edited", this, "_scene_tree_property_value_edited");
}
{ //profiler
- profiler = memnew( EditorProfiler );
+ profiler = memnew(EditorProfiler);
profiler->set_name(TTR("Profiler"));
tabs->add_child(profiler);
- profiler->connect("enable_profiling",this,"_profiler_activate");
- profiler->connect("break_request",this,"_profiler_seeked");
+ profiler->connect("enable_profiling", this, "_profiler_activate");
+ profiler->connect("break_request", this, "_profiler_seeked");
}
-
{ //monitors
- HSplitContainer *hsp = memnew( HSplitContainer );
+ HSplitContainer *hsp = memnew(HSplitContainer);
perf_monitors = memnew(Tree);
perf_monitors->set_columns(2);
- perf_monitors->set_column_title(0,TTR("Monitor"));
- perf_monitors->set_column_title(1,TTR("Value"));
+ perf_monitors->set_column_title(0, TTR("Monitor"));
+ perf_monitors->set_column_title(1, TTR("Value"));
perf_monitors->set_column_titles_visible(true);
hsp->add_child(perf_monitors);
perf_monitors->set_select_mode(Tree::SELECT_MULTI);
- perf_monitors->connect("multi_selected",this,"_performance_select");
- perf_draw = memnew( Control );
- perf_draw->connect("draw",this,"_performance_draw");
+ perf_monitors->connect("multi_selected", this, "_performance_select");
+ perf_draw = memnew(Control);
+ perf_draw->connect("draw", this, "_performance_draw");
hsp->add_child(perf_draw);
hsp->set_name(TTR("Monitors"));
hsp->set_split_offset(300);
tabs->add_child(hsp);
perf_max.resize(Performance::MONITOR_MAX);
- Map<String,TreeItem*> bases;
- TreeItem *root=perf_monitors->create_item();
+ Map<String, TreeItem *> bases;
+ TreeItem *root = perf_monitors->create_item();
perf_monitors->set_hide_root(true);
- for(int i=0;i<Performance::MONITOR_MAX;i++) {
+ for (int i = 0; i < Performance::MONITOR_MAX; i++) {
String n = Performance::get_singleton()->get_monitor_name(Performance::Monitor(i));
- String base = n.get_slice("/",0);
- String name = n.get_slice("/",1);
+ String base = n.get_slice("/", 0);
+ String name = n.get_slice("/", 1);
if (!bases.has(base)) {
TreeItem *b = perf_monitors->create_item(root);
- b->set_text(0,base.capitalize());
- b->set_editable(0,false);
- b->set_selectable(0,false);
- bases[base]=b;
+ b->set_text(0, base.capitalize());
+ b->set_editable(0, false);
+ b->set_selectable(0, false);
+ bases[base] = b;
}
TreeItem *it = perf_monitors->create_item(bases[base]);
- it->set_editable(0,false);
- it->set_selectable(0,true);
- it->set_text(0,name.capitalize());
+ it->set_editable(0, false);
+ it->set_selectable(0, true);
+ it->set_text(0, name.capitalize());
perf_items.push_back(it);
- perf_max[i]=0;
-
+ perf_max[i] = 0;
}
}
{ //vmem inspect
- VBoxContainer *vmem_vb = memnew( VBoxContainer );
- HBoxContainer *vmem_hb = memnew( HBoxContainer );
- Label *vmlb = memnew(Label(TTR("List of Video Memory Usage by Resource:")+" ") );
+ VBoxContainer *vmem_vb = memnew(VBoxContainer);
+ HBoxContainer *vmem_hb = memnew(HBoxContainer);
+ Label *vmlb = memnew(Label(TTR("List of Video Memory Usage by Resource:") + " "));
vmlb->set_h_size_flags(SIZE_EXPAND_FILL);
- vmem_hb->add_child( vmlb );
- vmem_hb->add_child( memnew(Label(TTR("Total:")+" ")) );
- vmem_total = memnew( LineEdit );
+ vmem_hb->add_child(vmlb);
+ vmem_hb->add_child(memnew(Label(TTR("Total:") + " ")));
+ vmem_total = memnew(LineEdit);
vmem_total->set_editable(false);
- vmem_total->set_custom_minimum_size(Size2(100,1)*EDSCALE);
+ vmem_total->set_custom_minimum_size(Size2(100, 1) * EDSCALE);
vmem_hb->add_child(vmem_total);
- vmem_refresh = memnew( Button );
+ vmem_refresh = memnew(Button);
vmem_hb->add_child(vmem_refresh);
vmem_vb->add_child(vmem_hb);
- vmem_refresh->connect("pressed",this,"_video_mem_request");
+ vmem_refresh->connect("pressed", this, "_video_mem_request");
- MarginContainer *vmmc = memnew( MarginContainer );
- vmem_tree = memnew( Tree );
+ MarginContainer *vmmc = memnew(MarginContainer);
+ vmem_tree = memnew(Tree);
vmem_tree->set_v_size_flags(SIZE_EXPAND_FILL);
vmem_tree->set_h_size_flags(SIZE_EXPAND_FILL);
vmmc->add_child(vmem_tree);
@@ -1920,69 +1779,64 @@ ScriptEditorDebugger::ScriptEditorDebugger(EditorNode *p_editor){
vmem_vb->set_name(TTR("Video Mem"));
vmem_tree->set_columns(4);
vmem_tree->set_column_titles_visible(true);
- vmem_tree->set_column_title(0,TTR("Resource Path"));
- vmem_tree->set_column_expand(0,true);
- vmem_tree->set_column_expand(1,false);
- vmem_tree->set_column_title(1,TTR("Type"));
- vmem_tree->set_column_min_width(1,100);
- vmem_tree->set_column_expand(2,false);
- vmem_tree->set_column_title(2,TTR("Format"));
- vmem_tree->set_column_min_width(2,150);
- vmem_tree->set_column_expand(3,false);
- vmem_tree->set_column_title(3,TTR("Usage"));
- vmem_tree->set_column_min_width(3,80);
+ vmem_tree->set_column_title(0, TTR("Resource Path"));
+ vmem_tree->set_column_expand(0, true);
+ vmem_tree->set_column_expand(1, false);
+ vmem_tree->set_column_title(1, TTR("Type"));
+ vmem_tree->set_column_min_width(1, 100);
+ vmem_tree->set_column_expand(2, false);
+ vmem_tree->set_column_title(2, TTR("Format"));
+ vmem_tree->set_column_min_width(2, 150);
+ vmem_tree->set_column_expand(3, false);
+ vmem_tree->set_column_title(3, TTR("Usage"));
+ vmem_tree->set_column_min_width(3, 80);
vmem_tree->set_hide_root(true);
tabs->add_child(vmem_vb);
}
{ // misc
- VBoxContainer *info_left = memnew( VBoxContainer );
+ VBoxContainer *info_left = memnew(VBoxContainer);
info_left->set_h_size_flags(SIZE_EXPAND_FILL);
info_left->set_name(TTR("Misc"));
tabs->add_child(info_left);
- clicked_ctrl = memnew( LineEdit );
- info_left->add_margin_child(TTR("Clicked Control:"),clicked_ctrl);
- clicked_ctrl_type = memnew( LineEdit );
- info_left->add_margin_child(TTR("Clicked Control Type:"),clicked_ctrl_type);
+ clicked_ctrl = memnew(LineEdit);
+ info_left->add_margin_child(TTR("Clicked Control:"), clicked_ctrl);
+ clicked_ctrl_type = memnew(LineEdit);
+ info_left->add_margin_child(TTR("Clicked Control Type:"), clicked_ctrl_type);
- live_edit_root = memnew( LineEdit );
+ live_edit_root = memnew(LineEdit);
{
- HBoxContainer *lehb = memnew( HBoxContainer );
- Label *l = memnew( Label(TTR("Live Edit Root:")) );
+ HBoxContainer *lehb = memnew(HBoxContainer);
+ Label *l = memnew(Label(TTR("Live Edit Root:")));
lehb->add_child(l);
l->set_h_size_flags(SIZE_EXPAND_FILL);
- le_set = memnew( Button(TTR("Set From Tree")) );
+ le_set = memnew(Button(TTR("Set From Tree")));
lehb->add_child(le_set);
- le_clear = memnew( Button(TTR("Clear")) );
+ le_clear = memnew(Button(TTR("Clear")));
lehb->add_child(le_clear);
info_left->add_child(lehb);
- MarginContainer *mc = memnew( MarginContainer );
+ MarginContainer *mc = memnew(MarginContainer);
mc->add_child(live_edit_root);
info_left->add_child(mc);
le_set->set_disabled(true);
le_clear->set_disabled(true);
}
-
}
-
-
- msgdialog = memnew( AcceptDialog );
+ msgdialog = memnew(AcceptDialog);
add_child(msgdialog);
- p_editor->get_undo_redo()->set_method_notify_callback(_method_changeds,this);
- p_editor->get_undo_redo()->set_property_notify_callback(_property_changeds,this);
- live_debug=false;
- last_path_id=false;
- error_count=0;
- hide_on_stop=true;
- last_error_count=0;
-
- EditorNode::get_singleton()->get_pause_button()->connect("pressed",this,"_paused");
-
+ p_editor->get_undo_redo()->set_method_notify_callback(_method_changeds, this);
+ p_editor->get_undo_redo()->set_property_notify_callback(_property_changeds, this);
+ live_debug = false;
+ last_path_id = false;
+ error_count = 0;
+ hide_on_stop = true;
+ last_error_count = 0;
+ EditorNode::get_singleton()->get_pause_button()->connect("pressed", this, "_paused");
}
ScriptEditorDebugger::~ScriptEditorDebugger() {
@@ -1994,5 +1848,4 @@ ScriptEditorDebugger::~ScriptEditorDebugger() {
server->stop();
memdelete(inspected_object);
-
}
diff --git a/editor/script_editor_debugger.h b/editor/script_editor_debugger.h
index a02934bbaf..74fbbf8f4b 100644
--- a/editor/script_editor_debugger.h
+++ b/editor/script_editor_debugger.h
@@ -29,11 +29,11 @@
#ifndef SCRIPT_EDITOR_DEBUGGER_H
#define SCRIPT_EDITOR_DEBUGGER_H
-#include "scene/gui/box_container.h"
-#include "scene/gui/button.h"
-#include "core/io/tcp_server.h"
#include "core/io/packet_peer.h"
+#include "core/io/tcp_server.h"
#include "property_editor.h"
+#include "scene/gui/box_container.h"
+#include "scene/gui/button.h"
class Tree;
class PropertyEditor;
@@ -49,17 +49,14 @@ class HSplitContainer;
class ItemList;
class EditorProfiler;
-
-
class ScriptEditorDebuggerInspectedObject;
class ScriptEditorDebugger : public Control {
- GDCLASS( ScriptEditorDebugger, Control );
+ GDCLASS(ScriptEditorDebugger, Control);
AcceptDialog *msgdialog;
-
Button *debugger_button;
LineEdit *clicked_ctrl;
@@ -68,8 +65,6 @@ class ScriptEditorDebugger : public Control {
Button *le_set;
Button *le_clear;
-
-
Tree *inspect_scene_tree;
HSplitContainer *inspect_info;
PropertyEditor *inspect_properties;
@@ -80,8 +75,6 @@ class ScriptEditorDebugger : public Control {
bool updating_scene_tree;
Set<ObjectID> unfold_cache;
-
-
HSplitContainer *error_split;
ItemList *error_list;
ItemList *error_stack;
@@ -91,8 +84,6 @@ class ScriptEditorDebugger : public Control {
bool hide_on_stop;
-
-
TabContainer *tabs;
LineEdit *reason;
@@ -107,9 +98,9 @@ class ScriptEditorDebugger : public Control {
List<Vector<float> > perf_history;
Vector<float> perf_max;
- Vector<TreeItem*> perf_items;
+ Vector<TreeItem *> perf_items;
- Map<int,String> profiler_signature;
+ Map<int, String> profiler_signature;
Tree *perf_monitors;
Control *perf_draw;
@@ -129,9 +120,9 @@ class ScriptEditorDebugger : public Control {
Array message;
int pending_in_queue;
- HashMap<NodePath,int> node_path_cache;
+ HashMap<NodePath, int> node_path_cache;
int last_path_id;
- Map<String,int> res_path_cache;
+ Map<String, int> res_path_cache;
EditorProfiler *profiler;
@@ -146,28 +137,27 @@ class ScriptEditorDebugger : public Control {
void _stack_dump_frame_selected();
void _output_clear();
-
- void _scene_tree_folded(Object* obj);
+ void _scene_tree_folded(Object *obj);
void _scene_tree_selected();
void _scene_tree_request();
- void _parse_message(const String& p_msg,const Array& p_data);
+ void _parse_message(const String &p_msg, const Array &p_data);
void _scene_tree_property_select_object(ObjectID p_object);
- void _scene_tree_property_value_edited(const String& p_prop,const Variant& p_value);
+ void _scene_tree_property_value_edited(const String &p_prop, const Variant &p_value);
void _video_mem_request();
- int _get_node_path_cache(const NodePath& p_path);
+ int _get_node_path_cache(const NodePath &p_path);
- int _get_res_path_cache(const String& p_path);
+ int _get_res_path_cache(const String &p_path);
void _live_edit_set();
void _live_edit_clear();
- void _method_changed(Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE);
- void _property_changed(Object*p_base,const StringName& p_property,const Variant& p_value);
+ void _method_changed(Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE);
+ void _property_changed(Object *p_base, const StringName &p_property, const Variant &p_value);
- static void _method_changeds(void *p_ud,Object*p_base,const StringName& p_name,VARIANT_ARG_DECLARE);
- static void _property_changeds(void *p_ud,Object*p_base,const StringName& p_property,const Variant& p_value);
+ static void _method_changeds(void *p_ud, Object *p_base, const StringName &p_name, VARIANT_ARG_DECLARE);
+ static void _property_changeds(void *p_ud, Object *p_base, const StringName &p_property, const Variant &p_value);
void _error_selected(int p_idx);
void _error_stack_selected(int p_idx);
@@ -175,17 +165,13 @@ class ScriptEditorDebugger : public Control {
void _profiler_activate(bool p_enable);
void _profiler_seeked();
-
-
void _paused();
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
void start();
void pause();
void unpause();
@@ -196,30 +182,30 @@ public:
void debug_break();
void debug_continue();
- String get_var_value(const String& p_var) const;
+ String get_var_value(const String &p_var) const;
void set_live_debugging(bool p_enable);
- void live_debug_create_node(const NodePath& p_parent,const String& p_type,const String& p_name);
- void live_debug_instance_node(const NodePath& p_parent,const String& p_path,const String& p_name);
- void live_debug_remove_node(const NodePath& p_at);
- void live_debug_remove_and_keep_node(const NodePath& p_at,ObjectID p_keep_id);
- void live_debug_restore_node(ObjectID p_id,const NodePath& p_at,int p_at_pos);
- void live_debug_duplicate_node(const NodePath& p_at,const String& p_new_name);
- void live_debug_reparent_node(const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos);
+ void live_debug_create_node(const NodePath &p_parent, const String &p_type, const String &p_name);
+ void live_debug_instance_node(const NodePath &p_parent, const String &p_path, const String &p_name);
+ void live_debug_remove_node(const NodePath &p_at);
+ void live_debug_remove_and_keep_node(const NodePath &p_at, ObjectID p_keep_id);
+ void live_debug_restore_node(ObjectID p_id, const NodePath &p_at, int p_at_pos);
+ void live_debug_duplicate_node(const NodePath &p_at, const String &p_new_name);
+ void live_debug_reparent_node(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos);
- void set_breakpoint(const String& p_path,int p_line,bool p_enabled);
+ void set_breakpoint(const String &p_path, int p_line, bool p_enabled);
void update_live_edit_root();
void set_hide_on_stop(bool p_hide);
- void set_tool_button(Button *p_tb) { debugger_button=p_tb; }
+ void set_tool_button(Button *p_tb) { debugger_button = p_tb; }
void reload_scripts();
virtual Size2 get_minimum_size() const;
- ScriptEditorDebugger(EditorNode *p_editor=NULL);
+ ScriptEditorDebugger(EditorNode *p_editor = NULL);
~ScriptEditorDebugger();
};
diff --git a/editor/settings_config_dialog.cpp b/editor/settings_config_dialog.cpp
index 7d8d6ffcec..909ed99da6 100644
--- a/editor/settings_config_dialog.cpp
+++ b/editor/settings_config_dialog.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "settings_config_dialog.h"
-#include "editor_settings.h"
-#include "scene/gui/margin_container.h"
-#include "global_config.h"
#include "editor_file_system.h"
#include "editor_node.h"
+#include "editor_settings.h"
+#include "global_config.h"
#include "os/keyboard.h"
+#include "scene/gui/margin_container.h"
void EditorSettingsDialog::ok_pressed() {
@@ -42,7 +42,6 @@ void EditorSettingsDialog::ok_pressed() {
_settings_save();
timer->stop();
-
}
void EditorSettingsDialog::_settings_changed() {
@@ -50,7 +49,7 @@ void EditorSettingsDialog::_settings_changed() {
timer->start();
}
-void EditorSettingsDialog::_settings_property_edited(const String& p_name) {
+void EditorSettingsDialog::_settings_property_edited(const String &p_name) {
String full_name = property_editor->get_full_item_path(p_name);
@@ -63,10 +62,8 @@ void EditorSettingsDialog::_settings_property_edited(const String& p_name) {
void EditorSettingsDialog::_settings_save() {
-
EditorSettings::get_singleton()->notify_changes();
EditorSettings::get_singleton()->save();
-
}
void EditorSettingsDialog::cancel_pressed() {
@@ -75,10 +72,8 @@ void EditorSettingsDialog::cancel_pressed() {
return;
EditorSettings::get_singleton()->notify_changes();
-
}
-
void EditorSettingsDialog::popup_edit_settings() {
if (!EditorSettings::get_singleton())
@@ -104,7 +99,7 @@ void EditorSettingsDialog::popup_edit_settings() {
void EditorSettingsDialog::_clear_search_box() {
- if (search_box->get_text()=="")
+ if (search_box->get_text() == "")
return;
search_box->clear();
@@ -112,13 +107,13 @@ void EditorSettingsDialog::_clear_search_box() {
}
void EditorSettingsDialog::_clear_shortcut_search_box() {
- if (shortcut_search_box->get_text()=="")
+ if (shortcut_search_box->get_text() == "")
return;
shortcut_search_box->clear();
}
-void EditorSettingsDialog::_filter_shortcuts(const String& p_filter) {
+void EditorSettingsDialog::_filter_shortcuts(const String &p_filter) {
shortcut_filter = p_filter;
_update_shortcuts();
}
@@ -136,7 +131,6 @@ void EditorSettingsDialog::_notification(int p_what) {
}
}
-
void EditorSettingsDialog::_update_shortcuts() {
shortcuts->clear();
@@ -145,9 +139,9 @@ void EditorSettingsDialog::_update_shortcuts() {
EditorSettings::get_singleton()->get_shortcut_list(&slist);
TreeItem *root = shortcuts->create_item();
- Map<String,TreeItem*> sections;
+ Map<String, TreeItem *> sections;
- for(List<String>::Element *E=slist.front();E;E=E->next()) {
+ for (List<String>::Element *E = slist.front(); E; E = E->next()) {
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(E->get());
if (!sc->has_meta("original"))
@@ -155,38 +149,38 @@ void EditorSettingsDialog::_update_shortcuts() {
InputEvent original = sc->get_meta("original");
- String section_name = E->get().get_slice("/",0);
+ String section_name = E->get().get_slice("/", 0);
TreeItem *section;
if (sections.has(section_name)) {
- section=sections[section_name];
+ section = sections[section_name];
} else {
section = shortcuts->create_item(root);
- section->set_text(0,section_name.capitalize());
+ section->set_text(0, section_name.capitalize());
- sections[section_name]=section;
- section->set_custom_bg_color(0,get_color("prop_subsection","Editor"));
- section->set_custom_bg_color(1,get_color("prop_subsection","Editor"));
+ sections[section_name] = section;
+ section->set_custom_bg_color(0, get_color("prop_subsection", "Editor"));
+ section->set_custom_bg_color(1, get_color("prop_subsection", "Editor"));
}
if (shortcut_filter.is_subsequence_ofi(sc->get_name())) {
TreeItem *item = shortcuts->create_item(section);
- item->set_text(0,sc->get_name());
- item->set_text(1,sc->get_as_text());
- if (!sc->is_shortcut(original) && !(sc->get_shortcut().type==InputEvent::NONE && original.type==InputEvent::NONE)) {
- item->add_button(1,get_icon("Reload","EditorIcons"),2);
+ item->set_text(0, sc->get_name());
+ item->set_text(1, sc->get_as_text());
+ if (!sc->is_shortcut(original) && !(sc->get_shortcut().type == InputEvent::NONE && original.type == InputEvent::NONE)) {
+ item->add_button(1, get_icon("Reload", "EditorIcons"), 2);
}
- item->add_button(1,get_icon("Edit","EditorIcons"),0);
- item->add_button(1,get_icon("Close","EditorIcons"),1);
- item->set_tooltip(0,E->get());
- item->set_metadata(0,E->get());
+ item->add_button(1, get_icon("Edit", "EditorIcons"), 0);
+ item->add_button(1, get_icon("Close", "EditorIcons"), 1);
+ item->set_tooltip(0, E->get());
+ item->set_metadata(0, E->get());
}
}
// remove sections with no shortcuts
- for(Map<String,TreeItem*>::Element *E=sections.front();E;E=E->next()) {
+ for (Map<String, TreeItem *>::Element *E = sections.front(); E; E = E->next()) {
TreeItem *section = E->get();
if (section->get_children() == NULL) {
root->remove_child(section);
@@ -194,37 +188,37 @@ void EditorSettingsDialog::_update_shortcuts() {
}
}
-void EditorSettingsDialog::_shortcut_button_pressed(Object* p_item,int p_column,int p_idx) {
+void EditorSettingsDialog::_shortcut_button_pressed(Object *p_item, int p_column, int p_idx) {
- TreeItem *ti=p_item->cast_to<TreeItem>();
+ TreeItem *ti = p_item->cast_to<TreeItem>();
ERR_FAIL_COND(!ti);
String item = ti->get_metadata(0);
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(item);
- if (p_idx==0) {
+ if (p_idx == 0) {
press_a_key_label->set_text(TTR("Press a Key.."));
- last_wait_for_key=InputEvent();
- press_a_key->popup_centered(Size2(250,80)*EDSCALE);
+ last_wait_for_key = InputEvent();
+ press_a_key->popup_centered(Size2(250, 80) * EDSCALE);
press_a_key->grab_focus();
press_a_key->get_ok()->set_focus_mode(FOCUS_NONE);
press_a_key->get_cancel()->set_focus_mode(FOCUS_NONE);
- shortcut_configured=item;
+ shortcut_configured = item;
- } else if (p_idx==1) {//erase
+ } else if (p_idx == 1) { //erase
if (!sc.is_valid())
return; //pointless, there is nothing
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Erase Shortcut");
- ur->add_do_method(sc.ptr(),"set_shortcut",InputEvent());
- ur->add_undo_method(sc.ptr(),"set_shortcut",sc->get_shortcut());
- ur->add_do_method(this,"_update_shortcuts");
- ur->add_undo_method(this,"_update_shortcuts");
- ur->add_do_method(this,"_settings_changed");
- ur->add_undo_method(this,"_settings_changed");
+ ur->add_do_method(sc.ptr(), "set_shortcut", InputEvent());
+ ur->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
+ ur->add_do_method(this, "_update_shortcuts");
+ ur->add_undo_method(this, "_update_shortcuts");
+ ur->add_do_method(this, "_settings_changed");
+ ur->add_undo_method(this, "_settings_changed");
ur->commit_action();
- } else if (p_idx==2) {//revert to original
+ } else if (p_idx == 2) { //revert to original
if (!sc.is_valid())
return; //pointless, there is nothing
@@ -232,82 +226,71 @@ void EditorSettingsDialog::_shortcut_button_pressed(Object* p_item,int p_column,
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
ur->create_action("Restore Shortcut");
- ur->add_do_method(sc.ptr(),"set_shortcut",original);
- ur->add_undo_method(sc.ptr(),"set_shortcut",sc->get_shortcut());
- ur->add_do_method(this,"_update_shortcuts");
- ur->add_undo_method(this,"_update_shortcuts");
- ur->add_do_method(this,"_settings_changed");
- ur->add_undo_method(this,"_settings_changed");
+ ur->add_do_method(sc.ptr(), "set_shortcut", original);
+ ur->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
+ ur->add_do_method(this, "_update_shortcuts");
+ ur->add_undo_method(this, "_update_shortcuts");
+ ur->add_do_method(this, "_settings_changed");
+ ur->add_undo_method(this, "_settings_changed");
ur->commit_action();
}
}
+void EditorSettingsDialog::_wait_for_key(const InputEvent &p_event) {
-void EditorSettingsDialog::_wait_for_key(const InputEvent& p_event) {
-
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed && p_event.key.scancode != 0) {
- if (p_event.type==InputEvent::KEY && p_event.key.pressed && p_event.key.scancode!=0) {
-
- last_wait_for_key=p_event;
- String str=keycode_get_string(p_event.key.scancode).capitalize();
+ last_wait_for_key = p_event;
+ String str = keycode_get_string(p_event.key.scancode).capitalize();
if (p_event.key.mod.meta)
- str=TTR("Meta+")+str;
+ str = TTR("Meta+") + str;
if (p_event.key.mod.shift)
- str=TTR("Shift+")+str;
+ str = TTR("Shift+") + str;
if (p_event.key.mod.alt)
- str=TTR("Alt+")+str;
+ str = TTR("Alt+") + str;
if (p_event.key.mod.control)
- str=TTR("Control+")+str;
-
+ str = TTR("Control+") + str;
press_a_key_label->set_text(str);
press_a_key->accept_event();
-
}
}
-
-
-
void EditorSettingsDialog::_press_a_key_confirm() {
- if (last_wait_for_key.type!=InputEvent::KEY)
+ if (last_wait_for_key.type != InputEvent::KEY)
return;
InputEvent ie;
- ie.type=InputEvent::KEY;
- ie.key.scancode=last_wait_for_key.key.scancode;
- ie.key.mod=last_wait_for_key.key.mod;
+ ie.type = InputEvent::KEY;
+ ie.key.scancode = last_wait_for_key.key.scancode;
+ ie.key.mod = last_wait_for_key.key.mod;
Ref<ShortCut> sc = EditorSettings::get_singleton()->get_shortcut(shortcut_configured);
UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
- ur->create_action("Change Shortcut '"+shortcut_configured+"'");
- ur->add_do_method(sc.ptr(),"set_shortcut",ie);
- ur->add_undo_method(sc.ptr(),"set_shortcut",sc->get_shortcut());
- ur->add_do_method(this,"_update_shortcuts");
- ur->add_undo_method(this,"_update_shortcuts");
- ur->add_do_method(this,"_settings_changed");
- ur->add_undo_method(this,"_settings_changed");
+ ur->create_action("Change Shortcut '" + shortcut_configured + "'");
+ ur->add_do_method(sc.ptr(), "set_shortcut", ie);
+ ur->add_undo_method(sc.ptr(), "set_shortcut", sc->get_shortcut());
+ ur->add_do_method(this, "_update_shortcuts");
+ ur->add_undo_method(this, "_update_shortcuts");
+ ur->add_do_method(this, "_settings_changed");
+ ur->add_undo_method(this, "_settings_changed");
ur->commit_action();
-
-
-
}
void EditorSettingsDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_settings_save"),&EditorSettingsDialog::_settings_save);
- ClassDB::bind_method(D_METHOD("_settings_changed"),&EditorSettingsDialog::_settings_changed);
- ClassDB::bind_method(D_METHOD("_settings_property_edited"),&EditorSettingsDialog::_settings_property_edited);
- ClassDB::bind_method(D_METHOD("_clear_search_box"),&EditorSettingsDialog::_clear_search_box);
- ClassDB::bind_method(D_METHOD("_clear_shortcut_search_box"),&EditorSettingsDialog::_clear_shortcut_search_box);
- ClassDB::bind_method(D_METHOD("_shortcut_button_pressed"),&EditorSettingsDialog::_shortcut_button_pressed);
- ClassDB::bind_method(D_METHOD("_filter_shortcuts"),&EditorSettingsDialog::_filter_shortcuts);
- ClassDB::bind_method(D_METHOD("_update_shortcuts"),&EditorSettingsDialog::_update_shortcuts);
- ClassDB::bind_method(D_METHOD("_press_a_key_confirm"),&EditorSettingsDialog::_press_a_key_confirm);
- ClassDB::bind_method(D_METHOD("_wait_for_key"),&EditorSettingsDialog::_wait_for_key);
-
+ ClassDB::bind_method(D_METHOD("_settings_save"), &EditorSettingsDialog::_settings_save);
+ ClassDB::bind_method(D_METHOD("_settings_changed"), &EditorSettingsDialog::_settings_changed);
+ ClassDB::bind_method(D_METHOD("_settings_property_edited"), &EditorSettingsDialog::_settings_property_edited);
+ ClassDB::bind_method(D_METHOD("_clear_search_box"), &EditorSettingsDialog::_clear_search_box);
+ ClassDB::bind_method(D_METHOD("_clear_shortcut_search_box"), &EditorSettingsDialog::_clear_shortcut_search_box);
+ ClassDB::bind_method(D_METHOD("_shortcut_button_pressed"), &EditorSettingsDialog::_shortcut_button_pressed);
+ ClassDB::bind_method(D_METHOD("_filter_shortcuts"), &EditorSettingsDialog::_filter_shortcuts);
+ ClassDB::bind_method(D_METHOD("_update_shortcuts"), &EditorSettingsDialog::_update_shortcuts);
+ ClassDB::bind_method(D_METHOD("_press_a_key_confirm"), &EditorSettingsDialog::_press_a_key_confirm);
+ ClassDB::bind_method(D_METHOD("_wait_for_key"), &EditorSettingsDialog::_wait_for_key);
}
EditorSettingsDialog::EditorSettingsDialog() {
@@ -315,31 +298,31 @@ EditorSettingsDialog::EditorSettingsDialog() {
set_title(TTR("Editor Settings"));
set_resizable(true);
- tabs = memnew( TabContainer );
+ tabs = memnew(TabContainer);
add_child(tabs);
//set_child_rect(tabs);
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
tabs->add_child(vbc);
vbc->set_name(TTR("General"));
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
vbc->add_child(hbc);
- Label *l = memnew( Label );
- l->set_text(TTR("Search:")+" ");
+ Label *l = memnew(Label);
+ l->set_text(TTR("Search:") + " ");
hbc->add_child(l);
- search_box = memnew( LineEdit );
+ search_box = memnew(LineEdit);
search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(search_box);
- clear_button = memnew( ToolButton );
+ clear_button = memnew(ToolButton);
hbc->add_child(clear_button);
- clear_button->connect("pressed",this,"_clear_search_box");
+ clear_button->connect("pressed", this, "_clear_search_box");
- property_editor = memnew( SectionedPropertyEditor );
+ property_editor = memnew(SectionedPropertyEditor);
//property_editor->hide_top_label();
property_editor->get_property_editor()->set_use_filter(true);
property_editor->get_property_editor()->register_text_enter(search_box);
@@ -347,69 +330,67 @@ EditorSettingsDialog::EditorSettingsDialog() {
vbc->add_child(property_editor);
property_editor->get_property_editor()->connect("property_edited", this, "_settings_property_edited");
- vbc = memnew( VBoxContainer );
+ vbc = memnew(VBoxContainer);
tabs->add_child(vbc);
vbc->set_name(TTR("Shortcuts"));
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
hbc->set_h_size_flags(Control::SIZE_EXPAND_FILL);
vbc->add_child(hbc);
- l = memnew( Label );
- l->set_text(TTR("Search:")+" ");
+ l = memnew(Label);
+ l->set_text(TTR("Search:") + " ");
hbc->add_child(l);
- shortcut_search_box = memnew( LineEdit );
+ shortcut_search_box = memnew(LineEdit);
shortcut_search_box->set_h_size_flags(Control::SIZE_EXPAND_FILL);
hbc->add_child(shortcut_search_box);
shortcut_search_box->connect("text_changed", this, "_filter_shortcuts");
- shortcut_clear_button = memnew( ToolButton );
+ shortcut_clear_button = memnew(ToolButton);
hbc->add_child(shortcut_clear_button);
- shortcut_clear_button->connect("pressed",this,"_clear_shortcut_search_box");
+ shortcut_clear_button->connect("pressed", this, "_clear_shortcut_search_box");
- shortcuts = memnew( Tree );
- vbc->add_margin_child("Shortcut List:",shortcuts,true);
+ shortcuts = memnew(Tree);
+ vbc->add_margin_child("Shortcut List:", shortcuts, true);
shortcuts->set_columns(2);
shortcuts->set_hide_root(true);
//shortcuts->set_hide_folding(true);
shortcuts->set_column_titles_visible(true);
- shortcuts->set_column_title(0,"Name");
- shortcuts->set_column_title(1,"Binding");
- shortcuts->connect("button_pressed",this,"_shortcut_button_pressed");
+ shortcuts->set_column_title(0, "Name");
+ shortcuts->set_column_title(1, "Binding");
+ shortcuts->connect("button_pressed", this, "_shortcut_button_pressed");
- press_a_key = memnew( ConfirmationDialog );
+ press_a_key = memnew(ConfirmationDialog);
press_a_key->set_focus_mode(FOCUS_ALL);
add_child(press_a_key);
- l = memnew( Label );
+ l = memnew(Label);
l->set_text(TTR("Press a Key.."));
l->set_area_as_parent_rect();
l->set_align(Label::ALIGN_CENTER);
- l->set_margin(MARGIN_TOP,20);
- l->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,30);
- press_a_key_label=l;
+ l->set_margin(MARGIN_TOP, 20);
+ l->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_BEGIN, 30);
+ press_a_key_label = l;
press_a_key->add_child(l);
- press_a_key->connect("gui_input",this,"_wait_for_key");
- press_a_key->connect("confirmed",this,"_press_a_key_confirm");
+ press_a_key->connect("gui_input", this, "_wait_for_key");
+ press_a_key->connect("confirmed", this, "_press_a_key_confirm");
//Button *load = memnew( Button );
//load->set_text("Load..");
//hbc->add_child(load);
-
//get_ok()->set_text("Apply");
set_hide_on_ok(true);
//get_cancel()->set_text("Close");
- timer = memnew( Timer );
+ timer = memnew(Timer);
timer->set_wait_time(1.5);
- timer->connect("timeout",this,"_settings_save");
+ timer->connect("timeout", this, "_settings_save");
timer->set_one_shot(true);
add_child(timer);
- EditorSettings::get_singleton()->connect("settings_changed",this,"_settings_changed");
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_settings_changed");
get_ok()->set_text(TTR("Close"));
- updating=false;
-
+ updating = false;
}
diff --git a/editor/settings_config_dialog.h b/editor/settings_config_dialog.h
index 17a05c27d3..ff6a831fe3 100644
--- a/editor/settings_config_dialog.h
+++ b/editor/settings_config_dialog.h
@@ -29,16 +29,13 @@
#ifndef SETTINGS_CONFIG_DIALOG_H
#define SETTINGS_CONFIG_DIALOG_H
-
#include "property_editor.h"
-#include "scene/gui/tab_container.h"
#include "scene/gui/rich_text_label.h"
+#include "scene/gui/tab_container.h"
class EditorSettingsDialog : public AcceptDialog {
- GDCLASS(EditorSettingsDialog,AcceptDialog);
-
-
+ GDCLASS(EditorSettingsDialog, AcceptDialog);
bool updating;
@@ -64,28 +61,26 @@ class EditorSettingsDialog : public AcceptDialog {
virtual void ok_pressed();
void _settings_changed();
- void _settings_property_edited(const String& p_name);
+ void _settings_property_edited(const String &p_name);
void _settings_save();
void _notification(int p_what);
-
void _press_a_key_confirm();
- void _wait_for_key(const InputEvent& p_event);
+ void _wait_for_key(const InputEvent &p_event);
void _clear_shortcut_search_box();
void _clear_search_box();
- void _filter_shortcuts(const String& p_filter);
+ void _filter_shortcuts(const String &p_filter);
void _update_shortcuts();
- void _shortcut_button_pressed(Object* p_item,int p_column,int p_idx);
+ void _shortcut_button_pressed(Object *p_item, int p_column, int p_idx);
protected:
-
static void _bind_methods();
-public:
+public:
void popup_edit_settings();
EditorSettingsDialog();
diff --git a/editor/spatial_editor_gizmos.cpp b/editor/spatial_editor_gizmos.cpp
index 825db5356b..8a24ed2b2f 100644
--- a/editor/spatial_editor_gizmos.cpp
+++ b/editor/spatial_editor_gizmos.cpp
@@ -29,36 +29,32 @@
#include "spatial_editor_gizmos.h"
#include "geometry.h"
+#include "quick_hull.h"
#include "scene/3d/camera.h"
-#include "scene/resources/surface_tool.h"
-#include "scene/resources/sphere_shape.h"
#include "scene/resources/box_shape.h"
#include "scene/resources/capsule_shape.h"
-#include "scene/resources/ray_shape.h"
#include "scene/resources/convex_polygon_shape.h"
#include "scene/resources/plane_shape.h"
-#include "quick_hull.h"
+#include "scene/resources/ray_shape.h"
+#include "scene/resources/sphere_shape.h"
+#include "scene/resources/surface_tool.h"
// Keep small children away from this file.
// It's so ugly it will eat them alive
-
-
#define HANDLE_HALF_SIZE 0.05
void EditorSpatialGizmo::clear() {
- for(int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
if (instances[i].instance.is_valid())
VS::get_singleton()->free(instances[i].instance);
-
-
}
- billboard_handle=false;
+ billboard_handle = false;
collision_segments.clear();
- collision_mesh=Ref<TriangleMesh>();
+ collision_mesh = Ref<TriangleMesh>();
instances.clear();
handles.clear();
secondary_handles.clear();
@@ -68,168 +64,155 @@ void EditorSpatialGizmo::redraw() {
if (get_script_instance() && get_script_instance()->has_method("redraw"))
get_script_instance()->call("redraw");
-
-
}
void EditorSpatialGizmo::Instance::create_instance(Spatial *p_base) {
- instance = VS::get_singleton()->instance_create2(mesh->get_rid(),p_base->get_world()->get_scenario());
- VS::get_singleton()->instance_attach_object_instance_ID(instance,p_base->get_instance_ID());
+ instance = VS::get_singleton()->instance_create2(mesh->get_rid(), p_base->get_world()->get_scenario());
+ VS::get_singleton()->instance_attach_object_instance_ID(instance, p_base->get_instance_ID());
if (billboard)
- VS::get_singleton()->instance_geometry_set_flag(instance,VS::INSTANCE_FLAG_BILLBOARD,true);
+ VS::get_singleton()->instance_geometry_set_flag(instance, VS::INSTANCE_FLAG_BILLBOARD, true);
if (unscaled)
- VS::get_singleton()->instance_geometry_set_flag(instance,VS::INSTANCE_FLAG_DEPH_SCALE,true);
+ VS::get_singleton()->instance_geometry_set_flag(instance, VS::INSTANCE_FLAG_DEPH_SCALE, true);
if (skeleton.is_valid())
- VS::get_singleton()->instance_attach_skeleton(instance,skeleton);
+ VS::get_singleton()->instance_attach_skeleton(instance, skeleton);
if (extra_margin)
- VS::get_singleton()->instance_set_extra_visibility_margin(instance,1);
- VS::get_singleton()->instance_geometry_set_cast_shadows_setting(instance,VS::SHADOW_CASTING_SETTING_OFF);
- VS::get_singleton()->instance_set_layer_mask(instance,1<<SpatialEditorViewport::GIZMO_EDIT_LAYER); //gizmos are 26
+ VS::get_singleton()->instance_set_extra_visibility_margin(instance, 1);
+ VS::get_singleton()->instance_geometry_set_cast_shadows_setting(instance, VS::SHADOW_CASTING_SETTING_OFF);
+ VS::get_singleton()->instance_set_layer_mask(instance, 1 << SpatialEditorViewport::GIZMO_EDIT_LAYER); //gizmos are 26
}
-
-
-void EditorSpatialGizmo::add_mesh(const Ref<Mesh>& p_mesh,bool p_billboard, const RID &p_skeleton) {
+void EditorSpatialGizmo::add_mesh(const Ref<Mesh> &p_mesh, bool p_billboard, const RID &p_skeleton) {
ERR_FAIL_COND(!spatial_node);
Instance ins;
- ins.billboard=p_billboard;
- ins.mesh=p_mesh;
- ins.skeleton=p_skeleton;
+ ins.billboard = p_billboard;
+ ins.mesh = p_mesh;
+ ins.skeleton = p_skeleton;
if (valid) {
ins.create_instance(spatial_node);
- VS::get_singleton()->instance_set_transform(ins.instance,spatial_node->get_global_transform());
+ VS::get_singleton()->instance_set_transform(ins.instance, spatial_node->get_global_transform());
}
instances.push_back(ins);
-
}
-void EditorSpatialGizmo::add_lines(const Vector<Vector3> &p_lines, const Ref<Material> &p_material,bool p_billboard){
+void EditorSpatialGizmo::add_lines(const Vector<Vector3> &p_lines, const Ref<Material> &p_material, bool p_billboard) {
ERR_FAIL_COND(!spatial_node);
Instance ins;
- Ref<Mesh> mesh = memnew( Mesh );
+ Ref<Mesh> mesh = memnew(Mesh);
Array a;
a.resize(Mesh::ARRAY_MAX);
- a[Mesh::ARRAY_VERTEX]=p_lines;
+ a[Mesh::ARRAY_VERTEX] = p_lines;
PoolVector<Color> color;
color.resize(p_lines.size());
{
PoolVector<Color>::Write w = color.write();
- for(int i=0;i<p_lines.size();i++) {
+ for (int i = 0; i < p_lines.size(); i++) {
if (is_selected())
- w[i]=Color(1,1,1,0.6);
+ w[i] = Color(1, 1, 1, 0.6);
else
- w[i]=Color(1,1,1,0.25);
+ w[i] = Color(1, 1, 1, 0.25);
}
-
}
- a[Mesh::ARRAY_COLOR]=color;
-
+ a[Mesh::ARRAY_COLOR] = color;
- mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,a);
- mesh->surface_set_material(0,p_material);
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, a);
+ mesh->surface_set_material(0, p_material);
if (p_billboard) {
- float md=0;
- for(int i=0;i<p_lines.size();i++) {
-
- md=MAX(0,p_lines[i].length());
+ float md = 0;
+ for (int i = 0; i < p_lines.size(); i++) {
+ md = MAX(0, p_lines[i].length());
}
if (md) {
- mesh->set_custom_aabb(Rect3(Vector3(-md,-md,-md),Vector3(md,md,md)*2.0));
+ mesh->set_custom_aabb(Rect3(Vector3(-md, -md, -md), Vector3(md, md, md) * 2.0));
}
}
- ins.billboard=p_billboard;
- ins.mesh=mesh;
+ ins.billboard = p_billboard;
+ ins.mesh = mesh;
if (valid) {
ins.create_instance(spatial_node);
- VS::get_singleton()->instance_set_transform(ins.instance,spatial_node->get_global_transform());
+ VS::get_singleton()->instance_set_transform(ins.instance, spatial_node->get_global_transform());
}
instances.push_back(ins);
-
}
-void EditorSpatialGizmo::add_unscaled_billboard(const Ref<Material>& p_material,float p_scale) {
+void EditorSpatialGizmo::add_unscaled_billboard(const Ref<Material> &p_material, float p_scale) {
ERR_FAIL_COND(!spatial_node);
Instance ins;
- Vector<Vector3 > vs;
- Vector<Vector2 > uv;
+ Vector<Vector3> vs;
+ Vector<Vector2> uv;
- vs.push_back(Vector3(-p_scale,p_scale,0));
- vs.push_back(Vector3(p_scale,p_scale,0));
- vs.push_back(Vector3(p_scale,-p_scale,0));
- vs.push_back(Vector3(-p_scale,-p_scale,0));
+ vs.push_back(Vector3(-p_scale, p_scale, 0));
+ vs.push_back(Vector3(p_scale, p_scale, 0));
+ vs.push_back(Vector3(p_scale, -p_scale, 0));
+ vs.push_back(Vector3(-p_scale, -p_scale, 0));
- uv.push_back(Vector2(1,0));
- uv.push_back(Vector2(0,0));
- uv.push_back(Vector2(0,1));
- uv.push_back(Vector2(1,1));
+ uv.push_back(Vector2(1, 0));
+ uv.push_back(Vector2(0, 0));
+ uv.push_back(Vector2(0, 1));
+ uv.push_back(Vector2(1, 1));
- Ref<Mesh> mesh = memnew( Mesh );
+ Ref<Mesh> mesh = memnew(Mesh);
Array a;
a.resize(Mesh::ARRAY_MAX);
- a[Mesh::ARRAY_VERTEX]=vs;
- a[Mesh::ARRAY_TEX_UV]=uv;
- mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLE_FAN,a);
- mesh->surface_set_material(0,p_material);
+ a[Mesh::ARRAY_VERTEX] = vs;
+ a[Mesh::ARRAY_TEX_UV] = uv;
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLE_FAN, a);
+ mesh->surface_set_material(0, p_material);
if (true) {
- float md=0;
- for(int i=0;i<vs.size();i++) {
-
- md=MAX(0,vs[i].length());
+ float md = 0;
+ for (int i = 0; i < vs.size(); i++) {
+ md = MAX(0, vs[i].length());
}
if (md) {
- mesh->set_custom_aabb(Rect3(Vector3(-md,-md,-md),Vector3(md,md,md)*2.0));
+ mesh->set_custom_aabb(Rect3(Vector3(-md, -md, -md), Vector3(md, md, md) * 2.0));
}
}
- ins.mesh=mesh;
- ins.unscaled=true;
- ins.billboard=true;
+ ins.mesh = mesh;
+ ins.unscaled = true;
+ ins.billboard = true;
if (valid) {
ins.create_instance(spatial_node);
- VS::get_singleton()->instance_set_transform(ins.instance,spatial_node->get_global_transform());
+ VS::get_singleton()->instance_set_transform(ins.instance, spatial_node->get_global_transform());
}
instances.push_back(ins);
-
-
}
-void EditorSpatialGizmo::add_collision_triangles(const Ref<TriangleMesh>& p_tmesh) {
+void EditorSpatialGizmo::add_collision_triangles(const Ref<TriangleMesh> &p_tmesh) {
- collision_mesh=p_tmesh;
+ collision_mesh = p_tmesh;
}
void EditorSpatialGizmo::add_collision_segments(const Vector<Vector3> &p_lines) {
- int from=collision_segments.size();
- collision_segments.resize(from+p_lines.size());
- for(int i=0;i<p_lines.size();i++) {
+ int from = collision_segments.size();
+ collision_segments.resize(from + p_lines.size());
+ for (int i = 0; i < p_lines.size(); i++) {
- collision_segments[from+i]=p_lines[i];
+ collision_segments[from + i] = p_lines[i];
}
}
+void EditorSpatialGizmo::add_handles(const Vector<Vector3> &p_handles, bool p_billboard, bool p_secondary) {
-void EditorSpatialGizmo::add_handles(const Vector<Vector3> &p_handles, bool p_billboard,bool p_secondary){
-
- billboard_handle=p_billboard;
+ billboard_handle = p_billboard;
if (!is_selected())
return;
@@ -239,82 +222,75 @@ void EditorSpatialGizmo::add_handles(const Vector<Vector3> &p_handles, bool p_bi
ERR_FAIL_COND(!spatial_node);
Instance ins;
-
- Ref<Mesh> mesh = memnew( Mesh );
+ Ref<Mesh> mesh = memnew(Mesh);
#if 1
Array a;
a.resize(VS::ARRAY_MAX);
- a[VS::ARRAY_VERTEX]=p_handles;
- print_line("handles?: "+itos(p_handles.size()));
+ a[VS::ARRAY_VERTEX] = p_handles;
+ print_line("handles?: " + itos(p_handles.size()));
PoolVector<Color> colors;
{
colors.resize(p_handles.size());
- PoolVector<Color>::Write w=colors.write();
- for(int i=0;i<p_handles.size();i++) {
+ PoolVector<Color>::Write w = colors.write();
+ for (int i = 0; i < p_handles.size(); i++) {
- Color col(1,1,1,1);
- if (SpatialEditor::get_singleton()->get_over_gizmo_handle()!=i)
- col=Color(0.9,0.9,0.9,0.9);
- w[i]=col;
+ Color col(1, 1, 1, 1);
+ if (SpatialEditor::get_singleton()->get_over_gizmo_handle() != i)
+ col = Color(0.9, 0.9, 0.9, 0.9);
+ w[i] = col;
}
-
}
- a[VS::ARRAY_COLOR]=colors;
- mesh->add_surface_from_arrays(Mesh::PRIMITIVE_POINTS,a);
- mesh->surface_set_material(0,SpatialEditorGizmos::singleton->handle2_material);
+ a[VS::ARRAY_COLOR] = colors;
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_POINTS, a);
+ mesh->surface_set_material(0, SpatialEditorGizmos::singleton->handle2_material);
if (p_billboard) {
- float md=0;
- for(int i=0;i<p_handles.size();i++) {
-
- md=MAX(0,p_handles[i].length());
+ float md = 0;
+ for (int i = 0; i < p_handles.size(); i++) {
+ md = MAX(0, p_handles[i].length());
}
if (md) {
- mesh->set_custom_aabb(Rect3(Vector3(-md,-md,-md),Vector3(md,md,md)*2.0));
+ mesh->set_custom_aabb(Rect3(Vector3(-md, -md, -md), Vector3(md, md, md) * 2.0));
}
}
-
-
#else
- for(int ih=0;ih<p_handles.size();ih++) {
-
+ for (int ih = 0; ih < p_handles.size(); ih++) {
Vector<Vector3> vertices;
Vector<Vector3> normals;
- int vtx_idx=0;
+ int vtx_idx = 0;
-#define ADD_VTX(m_idx) \
- vertices.push_back( (face_points[m_idx]*HANDLE_HALF_SIZE+p_handles[ih]) );\
- normals.push_back( normal_points[m_idx] );\
- vtx_idx++;\
-
- for (int i=0;i<6;i++) {
+#define ADD_VTX(m_idx) \
+ vertices.push_back((face_points[m_idx] * HANDLE_HALF_SIZE + p_handles[ih])); \
+ normals.push_back(normal_points[m_idx]); \
+ vtx_idx++;
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
Vector3 normal_points[4];
- float uv_points[8]={0,0,0,1,1,1,1,0};
+ float uv_points[8] = { 0, 0, 0, 1, 1, 1, 1, 0 };
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
- normal_points[j]=Vector3();
- normal_points[j][i%3]=(i>=3?-1:1);
+ normal_points[j] = Vector3();
+ normal_points[j][i % 3] = (i >= 3 ? -1 : 1);
}
//tri 1
ADD_VTX(0);
@@ -324,81 +300,72 @@ void EditorSpatialGizmo::add_handles(const Vector<Vector3> &p_handles, bool p_bi
ADD_VTX(2);
ADD_VTX(3);
ADD_VTX(0);
-
}
-
Array d;
d.resize(VS::ARRAY_MAX);
- d[VisualServer::ARRAY_NORMAL]= normals ;
- d[VisualServer::ARRAY_VERTEX]= vertices ;
-
- mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES,d);
- mesh->surface_set_material(ih,SpatialEditorGizmos::singleton->handle_material);
-
+ d[VisualServer::ARRAY_NORMAL] = normals;
+ d[VisualServer::ARRAY_VERTEX] = vertices;
+ mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, d);
+ mesh->surface_set_material(ih, SpatialEditorGizmos::singleton->handle_material);
}
#endif
- ins.mesh=mesh;
- ins.billboard=p_billboard;
- ins.extra_margin=true;
+ ins.mesh = mesh;
+ ins.billboard = p_billboard;
+ ins.extra_margin = true;
if (valid) {
ins.create_instance(spatial_node);
- VS::get_singleton()->instance_set_transform(ins.instance,spatial_node->get_global_transform());
+ VS::get_singleton()->instance_set_transform(ins.instance, spatial_node->get_global_transform());
}
instances.push_back(ins);
if (!p_secondary) {
- int chs=handles.size();
- handles.resize(chs+p_handles.size());
- for(int i=0;i<p_handles.size();i++) {
- handles[i+chs]=p_handles[i];
+ int chs = handles.size();
+ handles.resize(chs + p_handles.size());
+ for (int i = 0; i < p_handles.size(); i++) {
+ handles[i + chs] = p_handles[i];
}
} else {
- int chs=secondary_handles.size();
- secondary_handles.resize(chs+p_handles.size());
- for(int i=0;i<p_handles.size();i++) {
- secondary_handles[i+chs]=p_handles[i];
+ int chs = secondary_handles.size();
+ secondary_handles.resize(chs + p_handles.size());
+ for (int i = 0; i < p_handles.size(); i++) {
+ secondary_handles[i + chs] = p_handles[i];
}
-
}
-
}
-
-void EditorSpatialGizmo::set_spatial_node(Spatial *p_node){
+void EditorSpatialGizmo::set_spatial_node(Spatial *p_node) {
ERR_FAIL_NULL(p_node);
- spatial_node=p_node;
-
+ spatial_node = p_node;
}
-bool EditorSpatialGizmo::intersect_frustum(const Camera *p_camera,const Vector<Plane> &p_frustum) {
+bool EditorSpatialGizmo::intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum) {
- ERR_FAIL_COND_V(!spatial_node,false);
- ERR_FAIL_COND_V(!valid,false);
+ ERR_FAIL_COND_V(!spatial_node, false);
+ ERR_FAIL_COND_V(!valid, false);
if (collision_segments.size()) {
- const Plane *p=p_frustum.ptr();
- int fc=p_frustum.size();
+ const Plane *p = p_frustum.ptr();
+ int fc = p_frustum.size();
- int vc=collision_segments.size();
- const Vector3* vptr=collision_segments.ptr();
+ int vc = collision_segments.size();
+ const Vector3 *vptr = collision_segments.ptr();
Transform t = spatial_node->get_global_transform();
- for(int i=0;i<vc/2;i++) {
+ for (int i = 0; i < vc / 2; i++) {
+ Vector3 a = t.xform(vptr[i * 2 + 0]);
+ Vector3 b = t.xform(vptr[i * 2 + 1]);
- Vector3 a=t.xform(vptr[i*2+0]);
- Vector3 b=t.xform(vptr[i*2+1]);
+ bool any_out = false;
+ for (int j = 0; j < fc; j++) {
- bool any_out=false;
- for(int j=0;j<fc;j++) {
+ if (p[j].distance_to(a) > 0 && p[j].distance_to(b) > 0) {
- if (p[j].distance_to(a) > 0 && p[j].distance_to(b) >0) {
-
- any_out=true;
+ any_out = true;
break;
}
}
@@ -413,305 +380,276 @@ bool EditorSpatialGizmo::intersect_frustum(const Camera *p_camera,const Vector<P
return false;
}
+bool EditorSpatialGizmo::intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle, bool p_sec_first) {
-bool EditorSpatialGizmo::intersect_ray(const Camera *p_camera,const Point2& p_point, Vector3& r_pos, Vector3& r_normal,int *r_gizmo_handle,bool p_sec_first) {
-
- ERR_FAIL_COND_V(!spatial_node,false);
- ERR_FAIL_COND_V(!valid,false);
+ ERR_FAIL_COND_V(!spatial_node, false);
+ ERR_FAIL_COND_V(!valid, false);
if (r_gizmo_handle) {
Transform t = spatial_node->get_global_transform();
t.orthonormalize();
if (billboard_handle) {
- t.set_look_at(t.origin,t.origin+p_camera->get_transform().basis.get_axis(2),p_camera->get_transform().basis.get_axis(1));
+ t.set_look_at(t.origin, t.origin + p_camera->get_transform().basis.get_axis(2), p_camera->get_transform().basis.get_axis(1));
}
- float min_d=1e20;
- int idx=-1;
+ float min_d = 1e20;
+ int idx = -1;
- for(int i=0;i<secondary_handles.size();i++) {
+ for (int i = 0; i < secondary_handles.size(); i++) {
Vector3 hpos = t.xform(secondary_handles[i]);
Vector2 p = p_camera->unproject_position(hpos);
- if (p.distance_to(p_point)<SpatialEditorGizmos::singleton->handle_t->get_width()*0.6) {
-
+ if (p.distance_to(p_point) < SpatialEditorGizmos::singleton->handle_t->get_width() * 0.6) {
real_t dp = p_camera->get_transform().origin.distance_to(hpos);
- if (dp<min_d) {
-
- r_pos=t.xform(hpos);
- r_normal=p_camera->get_transform().basis.get_axis(2);
- min_d=dp;
- idx=i+handles.size();
+ if (dp < min_d) {
+ r_pos = t.xform(hpos);
+ r_normal = p_camera->get_transform().basis.get_axis(2);
+ min_d = dp;
+ idx = i + handles.size();
}
}
}
- if (p_sec_first && idx!=-1) {
+ if (p_sec_first && idx != -1) {
- *r_gizmo_handle=idx;
+ *r_gizmo_handle = idx;
return true;
}
- min_d=1e20;
+ min_d = 1e20;
- for(int i=0;i<handles.size();i++) {
+ for (int i = 0; i < handles.size(); i++) {
Vector3 hpos = t.xform(handles[i]);
Vector2 p = p_camera->unproject_position(hpos);
- if (p.distance_to(p_point)<SpatialEditorGizmos::singleton->handle_t->get_width()*0.6) {
-
+ if (p.distance_to(p_point) < SpatialEditorGizmos::singleton->handle_t->get_width() * 0.6) {
real_t dp = p_camera->get_transform().origin.distance_to(hpos);
- if (dp<min_d) {
-
- r_pos=t.xform(hpos);
- r_normal=p_camera->get_transform().basis.get_axis(2);
- min_d=dp;
- idx=i;
+ if (dp < min_d) {
+ r_pos = t.xform(hpos);
+ r_normal = p_camera->get_transform().basis.get_axis(2);
+ min_d = dp;
+ idx = i;
}
}
}
- if (idx>=0) {
- *r_gizmo_handle=idx;
+ if (idx >= 0) {
+ *r_gizmo_handle = idx;
return true;
}
-
-
}
if (collision_segments.size()) {
- Plane camp(p_camera->get_transform().origin,(-p_camera->get_transform().basis.get_axis(2)).normalized());
+ Plane camp(p_camera->get_transform().origin, (-p_camera->get_transform().basis.get_axis(2)).normalized());
- int vc=collision_segments.size();
- const Vector3* vptr=collision_segments.ptr();
+ int vc = collision_segments.size();
+ const Vector3 *vptr = collision_segments.ptr();
Transform t = spatial_node->get_global_transform();
if (billboard_handle) {
- t.set_look_at(t.origin,t.origin+p_camera->get_transform().basis.get_axis(2),p_camera->get_transform().basis.get_axis(1));
+ t.set_look_at(t.origin, t.origin + p_camera->get_transform().basis.get_axis(2), p_camera->get_transform().basis.get_axis(1));
}
Vector3 cp;
- float cpd=1e20;
-
- for(int i=0;i<vc/2;i++) {
+ float cpd = 1e20;
+ for (int i = 0; i < vc / 2; i++) {
- Vector3 a=t.xform(vptr[i*2+0]);
- Vector3 b=t.xform(vptr[i*2+1]);
+ Vector3 a = t.xform(vptr[i * 2 + 0]);
+ Vector3 b = t.xform(vptr[i * 2 + 1]);
Vector2 s[2];
s[0] = p_camera->unproject_position(a);
s[1] = p_camera->unproject_position(b);
-
- Vector2 p = Geometry::get_closest_point_to_segment_2d(p_point,s);
+ Vector2 p = Geometry::get_closest_point_to_segment_2d(p_point, s);
float pd = p.distance_to(p_point);
- if (pd<cpd) {
-
+ if (pd < cpd) {
float d = s[0].distance_to(s[1]);
Vector3 tcp;
- if (d>0) {
+ if (d > 0) {
- float d2=s[0].distance_to(p)/d;
- tcp = a+(b-a)*d2;
+ float d2 = s[0].distance_to(p) / d;
+ tcp = a + (b - a) * d2;
} else {
- tcp=a;
-
+ tcp = a;
}
- if (camp.distance_to(tcp)<p_camera->get_znear())
+ if (camp.distance_to(tcp) < p_camera->get_znear())
continue;
- cp=tcp;
- cpd=pd;
+ cp = tcp;
+ cpd = pd;
}
}
- if (cpd<8) {
+ if (cpd < 8) {
- r_pos=cp;
- r_normal=-p_camera->project_ray_normal(p_point);
+ r_pos = cp;
+ r_normal = -p_camera->project_ray_normal(p_point);
return true;
}
return false;
}
-
if (collision_mesh.is_valid()) {
Transform gt = spatial_node->get_global_transform();
if (billboard_handle) {
- gt.set_look_at(gt.origin,gt.origin+p_camera->get_transform().basis.get_axis(2),p_camera->get_transform().basis.get_axis(1));
+ gt.set_look_at(gt.origin, gt.origin + p_camera->get_transform().basis.get_axis(2), p_camera->get_transform().basis.get_axis(1));
}
- Transform ai=gt.affine_inverse();
+ Transform ai = gt.affine_inverse();
Vector3 ray_from = ai.xform(p_camera->project_ray_origin(p_point));
- Vector3 ray_dir=ai.basis.xform(p_camera->project_ray_normal(p_point)).normalized();
- Vector3 rpos,rnorm;
-
+ Vector3 ray_dir = ai.basis.xform(p_camera->project_ray_normal(p_point)).normalized();
+ Vector3 rpos, rnorm;
- if (collision_mesh->intersect_ray(ray_from,ray_dir,rpos,rnorm)) {
+ if (collision_mesh->intersect_ray(ray_from, ray_dir, rpos, rnorm)) {
- r_pos=gt.xform(rpos);
- r_normal=gt.basis.xform(rnorm).normalized();
+ r_pos = gt.xform(rpos);
+ r_normal = gt.basis.xform(rnorm).normalized();
return true;
}
}
return false;
-
}
-
-
void EditorSpatialGizmo::create() {
ERR_FAIL_COND(!spatial_node);
ERR_FAIL_COND(valid);
- valid=true;
+ valid = true;
- for(int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
instances[i].create_instance(spatial_node);
}
transform();
-
}
-void EditorSpatialGizmo::transform(){
+void EditorSpatialGizmo::transform() {
ERR_FAIL_COND(!spatial_node);
ERR_FAIL_COND(!valid);
- for(int i=0;i<instances.size();i++) {
- VS::get_singleton()->instance_set_transform(instances[i].instance,spatial_node->get_global_transform());
+ for (int i = 0; i < instances.size(); i++) {
+ VS::get_singleton()->instance_set_transform(instances[i].instance, spatial_node->get_global_transform());
}
-
}
-
-void EditorSpatialGizmo::free(){
+void EditorSpatialGizmo::free() {
ERR_FAIL_COND(!spatial_node);
ERR_FAIL_COND(!valid);
- for(int i=0;i<instances.size();i++) {
+ for (int i = 0; i < instances.size(); i++) {
if (instances[i].instance.is_valid())
VS::get_singleton()->free(instances[i].instance);
- instances[i].instance=RID();
+ instances[i].instance = RID();
}
- valid=false;
-
-
+ valid = false;
}
-
void EditorSpatialGizmo::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_lines","lines","material:Material","billboard"),&EditorSpatialGizmo::add_lines,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("add_mesh","mesh:Mesh","billboard","skeleton"),&EditorSpatialGizmo::add_mesh,DEFVAL(false),DEFVAL(RID()));
- ClassDB::bind_method(D_METHOD("add_collision_segments","segments"),&EditorSpatialGizmo::add_collision_segments);
- ClassDB::bind_method(D_METHOD("add_collision_triangles","triangles:TriangleMesh"),&EditorSpatialGizmo::add_collision_triangles);
- ClassDB::bind_method(D_METHOD("add_unscaled_billboard","material:Material","default_scale"),&EditorSpatialGizmo::add_unscaled_billboard,DEFVAL(1));
- ClassDB::bind_method(D_METHOD("add_handles","handles","billboard","secondary"),&EditorSpatialGizmo::add_handles,DEFVAL(false),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("set_spatial_node","node:Spatial"),&EditorSpatialGizmo::_set_spatial_node);
- ClassDB::bind_method(D_METHOD("clear"),&EditorSpatialGizmo::clear);
-
- BIND_VMETHOD( MethodInfo("redraw"));
- BIND_VMETHOD( MethodInfo(Variant::STRING,"get_handle_name",PropertyInfo(Variant::INT,"index")));
- BIND_VMETHOD( MethodInfo("get_handle_value:Variant",PropertyInfo(Variant::INT,"index")));
- BIND_VMETHOD( MethodInfo("set_handle",PropertyInfo(Variant::INT,"index"),PropertyInfo(Variant::OBJECT,"camera:Camera"),PropertyInfo(Variant::VECTOR2,"point")));
- MethodInfo cm = MethodInfo("commit_handle",PropertyInfo(Variant::INT,"index"),PropertyInfo(Variant::NIL,"restore:Variant"),PropertyInfo(Variant::BOOL,"cancel"));
+ ClassDB::bind_method(D_METHOD("add_lines", "lines", "material:Material", "billboard"), &EditorSpatialGizmo::add_lines, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("add_mesh", "mesh:Mesh", "billboard", "skeleton"), &EditorSpatialGizmo::add_mesh, DEFVAL(false), DEFVAL(RID()));
+ ClassDB::bind_method(D_METHOD("add_collision_segments", "segments"), &EditorSpatialGizmo::add_collision_segments);
+ ClassDB::bind_method(D_METHOD("add_collision_triangles", "triangles:TriangleMesh"), &EditorSpatialGizmo::add_collision_triangles);
+ ClassDB::bind_method(D_METHOD("add_unscaled_billboard", "material:Material", "default_scale"), &EditorSpatialGizmo::add_unscaled_billboard, DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("add_handles", "handles", "billboard", "secondary"), &EditorSpatialGizmo::add_handles, DEFVAL(false), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("set_spatial_node", "node:Spatial"), &EditorSpatialGizmo::_set_spatial_node);
+ ClassDB::bind_method(D_METHOD("clear"), &EditorSpatialGizmo::clear);
+
+ BIND_VMETHOD(MethodInfo("redraw"));
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "get_handle_name", PropertyInfo(Variant::INT, "index")));
+ BIND_VMETHOD(MethodInfo("get_handle_value:Variant", PropertyInfo(Variant::INT, "index")));
+ BIND_VMETHOD(MethodInfo("set_handle", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::OBJECT, "camera:Camera"), PropertyInfo(Variant::VECTOR2, "point")));
+ MethodInfo cm = MethodInfo("commit_handle", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::NIL, "restore:Variant"), PropertyInfo(Variant::BOOL, "cancel"));
cm.default_arguments.push_back(false);
- BIND_VMETHOD( cm );
+ BIND_VMETHOD(cm);
}
EditorSpatialGizmo::EditorSpatialGizmo() {
- valid=false;
- billboard_handle=false;
- base=NULL;
- spatial_node=NULL;
+ valid = false;
+ billboard_handle = false;
+ base = NULL;
+ spatial_node = NULL;
}
-EditorSpatialGizmo::~EditorSpatialGizmo(){
+EditorSpatialGizmo::~EditorSpatialGizmo() {
clear();
}
Vector3 EditorSpatialGizmo::get_handle_pos(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,handles.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_idx, handles.size(), Vector3());
return handles[p_idx];
-
}
//// light gizmo
-
String LightSpatialGizmo::get_handle_name(int p_idx) const {
- if (p_idx==0)
+ if (p_idx == 0)
return "Radius";
else
return "Aperture";
}
+Variant LightSpatialGizmo::get_handle_value(int p_idx) const {
-Variant LightSpatialGizmo::get_handle_value(int p_idx) const{
-
- if (p_idx==0)
+ if (p_idx == 0)
return light->get_param(Light::PARAM_RANGE);
- if (p_idx==1)
+ if (p_idx == 1)
return light->get_param(Light::PARAM_SPOT_ANGLE);
return Variant();
}
-
-static float _find_closest_angle_to_half_pi_arc(const Vector3& p_from, const Vector3& p_to, float p_arc_radius,const Transform& p_arc_xform) {
+static float _find_closest_angle_to_half_pi_arc(const Vector3 &p_from, const Vector3 &p_to, float p_arc_radius, const Transform &p_arc_xform) {
//bleh, discrete is simpler
- static const int arc_test_points=64;
+ static const int arc_test_points = 64;
float min_d = 1e20;
Vector3 min_p;
+ for (int i = 0; i < arc_test_points; i++) {
- for(int i=0;i<arc_test_points;i++) {
+ float a = i * Math_PI * 0.5 / arc_test_points;
+ float an = (i + 1) * Math_PI * 0.5 / arc_test_points;
+ Vector3 p = Vector3(Math::cos(a), 0, -Math::sin(a)) * p_arc_radius;
+ Vector3 n = Vector3(Math::cos(an), 0, -Math::sin(an)) * p_arc_radius;
- float a = i*Math_PI*0.5/arc_test_points;
- float an = (i+1)*Math_PI*0.5/arc_test_points;
- Vector3 p=Vector3( Math::cos(a), 0, -Math::sin(a) )*p_arc_radius;
- Vector3 n=Vector3( Math::cos(an), 0,- Math::sin(an) )*p_arc_radius;
-
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(p,n,p_from,p_to,ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(p, n, p_from, p_to, ra, rb);
float d = ra.distance_to(rb);
- if (d<min_d) {
- min_d=d;
- min_p=ra;
+ if (d < min_d) {
+ min_d = d;
+ min_p = ra;
}
-
}
//min_p = p_arc_xform.affine_inverse().xform(min_p);
- float a = Vector2(min_p.x,-min_p.z).angle();
- return a*180.0/Math_PI;
+ float a = Vector2(min_p.x, -min_p.z).angle();
+ return a * 180.0 / Math_PI;
}
-
-void LightSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point) {
+void LightSpatialGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Transform gt = light->get_global_transform();
gt.orthonormalize();
@@ -720,152 +658,135 @@ void LightSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_p
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 s[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*4096)};
- if (p_idx==0) {
+ Vector3 s[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 4096) };
+ if (p_idx == 0) {
if (light->cast_to<SpotLight>()) {
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),Vector3(0,0,-4096),s[0],s[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), Vector3(0, 0, -4096), s[0], s[1], ra, rb);
float d = -ra.z;
- if (d<0)
- d=0;
+ if (d < 0)
+ d = 0;
- light->set_param(Light::PARAM_RANGE,d);
+ light->set_param(Light::PARAM_RANGE, d);
} else if (light->cast_to<OmniLight>()) {
- Plane cp=Plane( gt.origin, p_camera->get_transform().basis.get_axis(2));
+ Plane cp = Plane(gt.origin, p_camera->get_transform().basis.get_axis(2));
Vector3 inters;
- if (cp.intersects_ray(ray_from,ray_dir,&inters)) {
+ if (cp.intersects_ray(ray_from, ray_dir, &inters)) {
float r = inters.distance_to(gt.origin);
- light->set_param(Light::PARAM_RANGE,r);
+ light->set_param(Light::PARAM_RANGE, r);
}
-
}
- } else if (p_idx==1) {
+ } else if (p_idx == 1) {
- float a = _find_closest_angle_to_half_pi_arc(s[0],s[1],light->get_param(Light::PARAM_RANGE),gt);
- light->set_param(Light::PARAM_SPOT_ANGLE,CLAMP(a,0.01,89.99));
+ float a = _find_closest_angle_to_half_pi_arc(s[0], s[1], light->get_param(Light::PARAM_RANGE), gt);
+ light->set_param(Light::PARAM_SPOT_ANGLE, CLAMP(a, 0.01, 89.99));
}
}
-void LightSpatialGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void LightSpatialGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
if (p_cancel) {
- light->set_param(p_idx==0?Light::PARAM_RANGE:Light::PARAM_SPOT_ANGLE,p_restore);
+ light->set_param(p_idx == 0 ? Light::PARAM_RANGE : Light::PARAM_SPOT_ANGLE, p_restore);
- } else if (p_idx==0) {
+ } else if (p_idx == 0) {
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Light Radius"));
- ur->add_do_method(light,"set_param",Light::PARAM_RANGE,light->get_param(Light::PARAM_RANGE));
- ur->add_undo_method(light,"set_param",Light::PARAM_RANGE,p_restore);
+ ur->add_do_method(light, "set_param", Light::PARAM_RANGE, light->get_param(Light::PARAM_RANGE));
+ ur->add_undo_method(light, "set_param", Light::PARAM_RANGE, p_restore);
ur->commit_action();
- } else if (p_idx==1) {
+ } else if (p_idx == 1) {
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Light Radius"));
- ur->add_do_method(light,"set_param",Light::PARAM_SPOT_ANGLE,light->get_param(Light::PARAM_SPOT_ANGLE));
- ur->add_undo_method(light,"set_param",Light::PARAM_SPOT_ANGLE,p_restore);
+ ur->add_do_method(light, "set_param", Light::PARAM_SPOT_ANGLE, light->get_param(Light::PARAM_SPOT_ANGLE));
+ ur->add_undo_method(light, "set_param", Light::PARAM_SPOT_ANGLE, p_restore);
ur->commit_action();
-
}
}
-
-
void LightSpatialGizmo::redraw() {
-
if (light->cast_to<DirectionalLight>()) {
-
-
- const int arrow_points=5;
- Vector3 arrow[arrow_points]={
- Vector3(0,0,2),
- Vector3(1,1,2),
- Vector3(1,1,-1),
- Vector3(2,2,-1),
- Vector3(0,0,-3)
+ const int arrow_points = 5;
+ Vector3 arrow[arrow_points] = {
+ Vector3(0, 0, 2),
+ Vector3(1, 1, 2),
+ Vector3(1, 1, -1),
+ Vector3(2, 2, -1),
+ Vector3(0, 0, -3)
};
- int arrow_sides=4;
+ int arrow_sides = 4;
Vector<Vector3> lines;
+ for (int i = 0; i < arrow_sides; i++) {
- for(int i = 0; i < arrow_sides ; i++) {
-
+ Basis ma(Vector3(0, 0, 1), Math_PI * 2 * float(i) / arrow_sides);
+ Basis mb(Vector3(0, 0, 1), Math_PI * 2 * float(i + 1) / arrow_sides);
- Basis ma(Vector3(0,0,1),Math_PI*2*float(i)/arrow_sides);
- Basis mb(Vector3(0,0,1),Math_PI*2*float(i+1)/arrow_sides);
+ for (int j = 1; j < arrow_points - 1; j++) {
-
- for(int j=1;j<arrow_points-1;j++) {
-
- if (j!=2) {
+ if (j != 2) {
lines.push_back(ma.xform(arrow[j]));
- lines.push_back(ma.xform(arrow[j+1]));
+ lines.push_back(ma.xform(arrow[j + 1]));
}
- if (j<arrow_points-1) {
+ if (j < arrow_points - 1) {
lines.push_back(ma.xform(arrow[j]));
lines.push_back(mb.xform(arrow[j]));
}
-
}
}
- add_lines(lines,SpatialEditorGizmos::singleton->light_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->light_material);
add_collision_segments(lines);
- add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_directional_icon,0.05);
-
+ add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_directional_icon, 0.05);
}
if (light->cast_to<OmniLight>()) {
clear();
-
OmniLight *on = light->cast_to<OmniLight>();
float r = on->get_param(Light::PARAM_RANGE);
Vector<Vector3> points;
- for(int i=0;i<=360;i++) {
+ for (int i = 0; i <= 360; i++) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r;
/*points.push_back(Vector3(a.x,0,a.y));
points.push_back(Vector3(b.x,0,b.y));
points.push_back(Vector3(0,a.x,a.y));
points.push_back(Vector3(0,b.x,b.y));*/
- points.push_back(Vector3(a.x,a.y,0));
- points.push_back(Vector3(b.x,b.y,0));
-
+ points.push_back(Vector3(a.x, a.y, 0));
+ points.push_back(Vector3(b.x, b.y, 0));
}
- add_lines(points,SpatialEditorGizmos::singleton->light_material,true);
+ add_lines(points, SpatialEditorGizmos::singleton->light_material, true);
add_collision_segments(points);
- add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_omni_icon,0.05);
+ add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_omni_icon, 0.05);
Vector<Vector3> handles;
- handles.push_back(Vector3(r,0,0));
- add_handles(handles,true);
-
-
+ handles.push_back(Vector3(r, 0, 0));
+ add_handles(handles, true);
}
-
if (light->cast_to<SpotLight>()) {
clear();
@@ -874,108 +795,97 @@ void LightSpatialGizmo::redraw() {
SpotLight *on = light->cast_to<SpotLight>();
float r = on->get_param(Light::PARAM_RANGE);
- float w = r*Math::sin(Math::deg2rad(on->get_param(Light::PARAM_SPOT_ANGLE)));
- float d = r*Math::cos(Math::deg2rad(on->get_param(Light::PARAM_SPOT_ANGLE)));
-
+ float w = r * Math::sin(Math::deg2rad(on->get_param(Light::PARAM_SPOT_ANGLE)));
+ float d = r * Math::cos(Math::deg2rad(on->get_param(Light::PARAM_SPOT_ANGLE)));
+ for (int i = 0; i < 360; i++) {
- for(int i=0;i<360;i++) {
-
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*w;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*w;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * w;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * w;
/*points.push_back(Vector3(a.x,0,a.y));
points.push_back(Vector3(b.x,0,b.y));
points.push_back(Vector3(0,a.x,a.y));
points.push_back(Vector3(0,b.x,b.y));*/
- points.push_back(Vector3(a.x,a.y,-d));
- points.push_back(Vector3(b.x,b.y,-d));
+ points.push_back(Vector3(a.x, a.y, -d));
+ points.push_back(Vector3(b.x, b.y, -d));
- if (i%90==0) {
+ if (i % 90 == 0) {
- points.push_back(Vector3(a.x,a.y,-d));
+ points.push_back(Vector3(a.x, a.y, -d));
points.push_back(Vector3());
-
}
-
-
}
- points.push_back(Vector3(0,0,-r));
+ points.push_back(Vector3(0, 0, -r));
points.push_back(Vector3());
- add_lines(points,SpatialEditorGizmos::singleton->light_material);
+ add_lines(points, SpatialEditorGizmos::singleton->light_material);
Vector<Vector3> handles;
- handles.push_back(Vector3(0,0,-r));
+ handles.push_back(Vector3(0, 0, -r));
Vector<Vector3> collision_segments;
- for(int i=0;i<64;i++) {
+ for (int i = 0; i < 64; i++) {
- float ra=i*Math_PI*2.0/64.0;
- float rb=(i+1)*Math_PI*2.0/64.0;
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*w;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*w;
+ float ra = i * Math_PI * 2.0 / 64.0;
+ float rb = (i + 1) * Math_PI * 2.0 / 64.0;
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * w;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * w;
- collision_segments.push_back(Vector3(a.x,a.y,-d));
- collision_segments.push_back(Vector3(b.x,b.y,-d));
+ collision_segments.push_back(Vector3(a.x, a.y, -d));
+ collision_segments.push_back(Vector3(b.x, b.y, -d));
- if (i%16==0) {
+ if (i % 16 == 0) {
- collision_segments.push_back(Vector3(a.x,a.y,-d));
+ collision_segments.push_back(Vector3(a.x, a.y, -d));
collision_segments.push_back(Vector3());
-
}
- if (i==16) {
+ if (i == 16) {
- handles.push_back(Vector3(a.x,a.y,-d));
+ handles.push_back(Vector3(a.x, a.y, -d));
}
-
}
- collision_segments.push_back(Vector3(0,0,-r));
+ collision_segments.push_back(Vector3(0, 0, -r));
collision_segments.push_back(Vector3());
-
add_handles(handles);
add_collision_segments(collision_segments);
- add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_omni_icon,0.05);
-
+ add_unscaled_billboard(SpatialEditorGizmos::singleton->light_material_omni_icon, 0.05);
}
-
}
-LightSpatialGizmo::LightSpatialGizmo(Light* p_light){
+LightSpatialGizmo::LightSpatialGizmo(Light *p_light) {
- light=p_light;
+ light = p_light;
set_spatial_node(p_light);
-
}
//////
String CameraSpatialGizmo::get_handle_name(int p_idx) const {
- if (camera->get_projection()==Camera::PROJECTION_PERSPECTIVE) {
+ if (camera->get_projection() == Camera::PROJECTION_PERSPECTIVE) {
return "FOV";
} else {
return "Size";
}
}
-Variant CameraSpatialGizmo::get_handle_value(int p_idx) const{
+Variant CameraSpatialGizmo::get_handle_value(int p_idx) const {
- if (camera->get_projection()==Camera::PROJECTION_PERSPECTIVE) {
+ if (camera->get_projection() == Camera::PROJECTION_PERSPECTIVE) {
return camera->get_fov();
} else {
return camera->get_size();
}
}
-void CameraSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point){
+void CameraSpatialGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Transform gt = camera->get_global_transform();
gt.orthonormalize();
@@ -984,36 +894,35 @@ void CameraSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 s[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*4096)};
+ Vector3 s[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 4096) };
- if (camera->get_projection()==Camera::PROJECTION_PERSPECTIVE) {
- Transform gt=camera->get_global_transform();
- float a = _find_closest_angle_to_half_pi_arc(s[0],s[1],1.0,gt);
- camera->set("fov",a);
+ if (camera->get_projection() == Camera::PROJECTION_PERSPECTIVE) {
+ Transform gt = camera->get_global_transform();
+ float a = _find_closest_angle_to_half_pi_arc(s[0], s[1], 1.0, gt);
+ camera->set("fov", a);
} else {
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(0,0,-1),Vector3(4096,0,-1),s[0],s[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(0, 0, -1), Vector3(4096, 0, -1), s[0], s[1], ra, rb);
float d = ra.x * 2.0;
- if (d<0)
- d=0;
+ if (d < 0)
+ d = 0;
- camera->set("size",d);
+ camera->set("size", d);
}
-
}
-void CameraSpatialGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void CameraSpatialGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
- if (camera->get_projection()==Camera::PROJECTION_PERSPECTIVE) {
+ if (camera->get_projection() == Camera::PROJECTION_PERSPECTIVE) {
if (p_cancel) {
- camera->set("fov",p_restore);
+ camera->set("fov", p_restore);
} else {
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Camera FOV"));
- ur->add_do_property(camera,"fov",camera->get_fov());
- ur->add_undo_property(camera,"fov",p_restore);
+ ur->add_do_property(camera, "fov", camera->get_fov());
+ ur->add_undo_property(camera, "fov", p_restore);
ur->commit_action();
}
@@ -1021,111 +930,102 @@ void CameraSpatialGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p
if (p_cancel) {
- camera->set("size",p_restore);
+ camera->set("size", p_restore);
} else {
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Camera Size"));
- ur->add_do_property(camera,"size",camera->get_size());
- ur->add_undo_property(camera,"size",p_restore);
+ ur->add_do_property(camera, "size", camera->get_size());
+ ur->add_undo_property(camera, "size", p_restore);
ur->commit_action();
}
-
}
-
}
-void CameraSpatialGizmo::redraw(){
+void CameraSpatialGizmo::redraw() {
clear();
Vector<Vector3> lines;
Vector<Vector3> handles;
-
- switch(camera->get_projection()) {
+ switch (camera->get_projection()) {
case Camera::PROJECTION_PERSPECTIVE: {
float fov = camera->get_fov();
- Vector3 side=Vector3( Math::sin(Math::deg2rad(fov)), 0, -Math::cos(Math::deg2rad(fov)) );
- Vector3 nside=side;
- nside.x=-nside.x;
- Vector3 up=Vector3(0,side.x,0);
-
+ Vector3 side = Vector3(Math::sin(Math::deg2rad(fov)), 0, -Math::cos(Math::deg2rad(fov)));
+ Vector3 nside = side;
+ nside.x = -nside.x;
+ Vector3 up = Vector3(0, side.x, 0);
-#define ADD_TRIANGLE( m_a, m_b, m_c)\
-{\
- lines.push_back(m_a);\
- lines.push_back(m_b);\
- lines.push_back(m_b);\
- lines.push_back(m_c);\
- lines.push_back(m_c);\
- lines.push_back(m_a);\
-}
+#define ADD_TRIANGLE(m_a, m_b, m_c) \
+ { \
+ lines.push_back(m_a); \
+ lines.push_back(m_b); \
+ lines.push_back(m_b); \
+ lines.push_back(m_c); \
+ lines.push_back(m_c); \
+ lines.push_back(m_a); \
+ }
- ADD_TRIANGLE( Vector3(), side+up, side-up );
- ADD_TRIANGLE( Vector3(), nside+up, nside-up );
- ADD_TRIANGLE( Vector3(), side+up, nside+up );
- ADD_TRIANGLE( Vector3(), side-up, nside-up );
+ ADD_TRIANGLE(Vector3(), side + up, side - up);
+ ADD_TRIANGLE(Vector3(), nside + up, nside - up);
+ ADD_TRIANGLE(Vector3(), side + up, nside + up);
+ ADD_TRIANGLE(Vector3(), side - up, nside - up);
handles.push_back(side);
- side.x*=0.25;
- nside.x*=0.25;
- Vector3 tup( 0, up.y*3/2,side.z);
- ADD_TRIANGLE( tup, side+up, nside+up );
+ side.x *= 0.25;
+ nside.x *= 0.25;
+ Vector3 tup(0, up.y * 3 / 2, side.z);
+ ADD_TRIANGLE(tup, side + up, nside + up);
} break;
case Camera::PROJECTION_ORTHOGONAL: {
-#define ADD_QUAD( m_a, m_b, m_c, m_d)\
-{\
- lines.push_back(m_a);\
- lines.push_back(m_b);\
- lines.push_back(m_b);\
- lines.push_back(m_c);\
- lines.push_back(m_c);\
- lines.push_back(m_d);\
- lines.push_back(m_d);\
- lines.push_back(m_a);\
-}
+#define ADD_QUAD(m_a, m_b, m_c, m_d) \
+ { \
+ lines.push_back(m_a); \
+ lines.push_back(m_b); \
+ lines.push_back(m_b); \
+ lines.push_back(m_c); \
+ lines.push_back(m_c); \
+ lines.push_back(m_d); \
+ lines.push_back(m_d); \
+ lines.push_back(m_a); \
+ }
float size = camera->get_size();
- float hsize=size*0.5;
- Vector3 right(hsize,0,0);
- Vector3 up(0,hsize,0);
- Vector3 back(0,0,-1.0);
- Vector3 front(0,0,0);
+ float hsize = size * 0.5;
+ Vector3 right(hsize, 0, 0);
+ Vector3 up(0, hsize, 0);
+ Vector3 back(0, 0, -1.0);
+ Vector3 front(0, 0, 0);
- ADD_QUAD( -up-right,-up+right,up+right,up-right);
- ADD_QUAD( -up-right+back,-up+right+back,up+right+back,up-right+back);
- ADD_QUAD( up+right,up+right+back,up-right+back,up-right);
- ADD_QUAD( -up+right,-up+right+back,-up-right+back,-up-right);
- handles.push_back(right+back);
+ ADD_QUAD(-up - right, -up + right, up + right, up - right);
+ ADD_QUAD(-up - right + back, -up + right + back, up + right + back, up - right + back);
+ ADD_QUAD(up + right, up + right + back, up - right + back, up - right);
+ ADD_QUAD(-up + right, -up + right + back, -up - right + back, -up - right);
+ handles.push_back(right + back);
- right.x*=0.25;
- Vector3 tup( 0, up.y*3/2,back.z );
- ADD_TRIANGLE( tup, right+up+back, -right+up+back );
+ right.x *= 0.25;
+ Vector3 tup(0, up.y * 3 / 2, back.z);
+ ADD_TRIANGLE(tup, right + up + back, -right + up + back);
} break;
-
}
- add_lines(lines,SpatialEditorGizmos::singleton->camera_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->camera_material);
add_collision_segments(lines);
add_handles(handles);
}
+CameraSpatialGizmo::CameraSpatialGizmo(Camera *p_camera) {
-CameraSpatialGizmo::CameraSpatialGizmo(Camera* p_camera){
-
- camera=p_camera;
+ camera = p_camera;
set_spatial_node(camera);
}
-
-
-
//////
void MeshInstanceSpatialGizmo::redraw() {
@@ -1139,47 +1039,42 @@ void MeshInstanceSpatialGizmo::redraw() {
add_collision_triangles(tm);
}
-MeshInstanceSpatialGizmo::MeshInstanceSpatialGizmo(MeshInstance* p_mesh) {
+MeshInstanceSpatialGizmo::MeshInstanceSpatialGizmo(MeshInstance *p_mesh) {
- mesh=p_mesh;
+ mesh = p_mesh;
set_spatial_node(p_mesh);
}
/////
-
void Position3DSpatialGizmo::redraw() {
clear();
add_mesh(SpatialEditorGizmos::singleton->pos3d_mesh);
Vector<Vector3> cursor_points;
float cs = 0.25;
- cursor_points.push_back(Vector3(+cs,0,0));
- cursor_points.push_back(Vector3(-cs,0,0));
- cursor_points.push_back(Vector3(0,+cs,0));
- cursor_points.push_back(Vector3(0,-cs,0));
- cursor_points.push_back(Vector3(0,0,+cs));
- cursor_points.push_back(Vector3(0,0,-cs));
+ cursor_points.push_back(Vector3(+cs, 0, 0));
+ cursor_points.push_back(Vector3(-cs, 0, 0));
+ cursor_points.push_back(Vector3(0, +cs, 0));
+ cursor_points.push_back(Vector3(0, -cs, 0));
+ cursor_points.push_back(Vector3(0, 0, +cs));
+ cursor_points.push_back(Vector3(0, 0, -cs));
add_collision_segments(cursor_points);
-
}
+Position3DSpatialGizmo::Position3DSpatialGizmo(Position3D *p_p3d) {
-Position3DSpatialGizmo::Position3DSpatialGizmo(Position3D* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
-
/////
void SkeletonSpatialGizmo::redraw() {
clear();
- Ref<SurfaceTool> surface_tool( memnew( SurfaceTool ));
-
+ Ref<SurfaceTool> surface_tool(memnew(SurfaceTool));
surface_tool->begin(Mesh::PRIMITIVE_LINES);
surface_tool->set_material(SpatialEditorGizmos::singleton->skeleton_material);
@@ -1191,77 +1086,75 @@ void SkeletonSpatialGizmo::redraw() {
bones.resize(4);
weights.resize(4);
- for(int i=0;i<4;i++) {
- bones[i]=0;
- weights[i]=0;
+ for (int i = 0; i < 4; i++) {
+ bones[i] = 0;
+ weights[i] = 0;
}
- weights[0]=1;
-
+ weights[0] = 1;
Rect3 aabb;
- Color bonecolor = Color(1.0,0.4,0.4,0.3);
- Color rootcolor = Color(0.4,1.0,0.4,0.1);
+ Color bonecolor = Color(1.0, 0.4, 0.4, 0.3);
+ Color rootcolor = Color(0.4, 1.0, 0.4, 0.1);
- for (int i=0;i<skel->get_bone_count();i++) {
+ for (int i = 0; i < skel->get_bone_count(); i++) {
int parent = skel->get_bone_parent(i);
- if (parent>=0) {
- grests[i]=grests[parent] * skel->get_bone_rest(i);
+ if (parent >= 0) {
+ grests[i] = grests[parent] * skel->get_bone_rest(i);
Vector3 v0 = grests[parent].origin;
Vector3 v1 = grests[i].origin;
- Vector3 d = (v1-v0).normalized();
+ Vector3 d = (v1 - v0).normalized();
float dist = v0.distance_to(v1);
//find closest axis
- int closest=-1;
+ int closest = -1;
float closest_d = 0.0;
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
float dp = Math::abs(grests[parent].basis[j].normalized().dot(d));
- if (j==0 || dp>closest_d)
- closest=j;
+ if (j == 0 || dp > closest_d)
+ closest = j;
}
//find closest other
Vector3 first;
Vector3 points[4];
- int pointidx=0;
- for(int j=0;j<3;j++) {
+ int pointidx = 0;
+ for (int j = 0; j < 3; j++) {
- bones[0]=parent;
+ bones[0] = parent;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(rootcolor);
- surface_tool->add_vertex(v0-grests[parent].basis[j].normalized()*dist*0.05);
+ surface_tool->add_vertex(v0 - grests[parent].basis[j].normalized() * dist * 0.05);
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(rootcolor);
- surface_tool->add_vertex(v0+grests[parent].basis[j].normalized()*dist*0.05);
+ surface_tool->add_vertex(v0 + grests[parent].basis[j].normalized() * dist * 0.05);
- if (j==closest)
+ if (j == closest)
continue;
Vector3 axis;
- if (first==Vector3()) {
+ if (first == Vector3()) {
axis = d.cross(d.cross(grests[parent].basis[j])).normalized();
- first=axis;
+ first = axis;
} else {
axis = d.cross(first).normalized();
}
- for(int k=0;k<2;k++) {
-
- if (k==1)
- axis=-axis;
- Vector3 point = v0+d*dist*0.2;
- point+=axis*dist*0.1;
+ for (int k = 0; k < 2; k++) {
+ if (k == 1)
+ axis = -axis;
+ Vector3 point = v0 + d * dist * 0.2;
+ point += axis * dist * 0.1;
- bones[0]=parent;
+ bones[0] = parent;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(bonecolor);
@@ -1271,27 +1164,24 @@ void SkeletonSpatialGizmo::redraw() {
surface_tool->add_color(bonecolor);
surface_tool->add_vertex(point);
- bones[0]=parent;
+ bones[0] = parent;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(bonecolor);
surface_tool->add_vertex(point);
- bones[0]=i;
+ bones[0] = i;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(bonecolor);
surface_tool->add_vertex(v1);
- points[pointidx++]=point;
-
+ points[pointidx++] = point;
}
-
}
- SWAP( points[1],points[2] );
- for(int j=0;j<4;j++) {
+ SWAP(points[1], points[2]);
+ for (int j = 0; j < 4; j++) {
-
- bones[0]=parent;
+ bones[0] = parent;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(bonecolor);
@@ -1299,11 +1189,10 @@ void SkeletonSpatialGizmo::redraw() {
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
surface_tool->add_color(bonecolor);
- surface_tool->add_vertex(points[(j+1)%4]);
+ surface_tool->add_vertex(points[(j + 1) % 4]);
}
-
-/*
+ /*
bones[0]=parent;
surface_tool->add_bones(bones);
surface_tool->add_weights(weights);
@@ -1317,10 +1206,10 @@ void SkeletonSpatialGizmo::redraw() {
*/
} else {
- grests[i]=skel->get_bone_rest(i);
- bones[0]=i;
+ grests[i] = skel->get_bone_rest(i);
+ bones[0] = i;
}
-/*
+ /*
Transform t = grests[i];
t.orthonormalize();
@@ -1361,18 +1250,15 @@ void SkeletonSpatialGizmo::redraw() {
}
Ref<Mesh> m = surface_tool->commit();
- add_mesh(m,false,skel->get_skeleton());
-
+ add_mesh(m, false, skel->get_skeleton());
}
-SkeletonSpatialGizmo::SkeletonSpatialGizmo(Skeleton* p_skel) {
+SkeletonSpatialGizmo::SkeletonSpatialGizmo(Skeleton *p_skel) {
- skel=p_skel;
+ skel = p_skel;
set_spatial_node(p_skel);
}
-
-
void RoomSpatialGizmo::redraw() {
clear();
@@ -1382,194 +1268,178 @@ void RoomSpatialGizmo::redraw() {
PoolVector<Face3> faces = roomie->get_geometry_hint();
Vector<Vector3> lines;
- int fc=faces.size();
- PoolVector<Face3>::Read r =faces.read();
+ int fc = faces.size();
+ PoolVector<Face3>::Read r = faces.read();
- Map<_EdgeKey,Vector3> edge_map;
+ Map<_EdgeKey, Vector3> edge_map;
- for(int i=0;i<fc;i++) {
+ for (int i = 0; i < fc; i++) {
Vector3 fn = r[i].get_plane().normal;
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
_EdgeKey ek;
- ek.from=r[i].vertex[j].snapped(CMP_EPSILON);
- ek.to=r[i].vertex[(j+1)%3].snapped(CMP_EPSILON);
- if (ek.from<ek.to)
- SWAP(ek.from,ek.to);
+ ek.from = r[i].vertex[j].snapped(CMP_EPSILON);
+ ek.to = r[i].vertex[(j + 1) % 3].snapped(CMP_EPSILON);
+ if (ek.from < ek.to)
+ SWAP(ek.from, ek.to);
- Map<_EdgeKey,Vector3>::Element *E=edge_map.find(ek);
+ Map<_EdgeKey, Vector3>::Element *E = edge_map.find(ek);
if (E) {
- if (E->get().dot(fn) >0.9) {
+ if (E->get().dot(fn) > 0.9) {
- E->get()=Vector3();
+ E->get() = Vector3();
}
} else {
- edge_map[ek]=fn;
+ edge_map[ek] = fn;
}
-
}
}
- for(Map<_EdgeKey,Vector3>::Element *E=edge_map.front();E;E=E->next()) {
+ for (Map<_EdgeKey, Vector3>::Element *E = edge_map.front(); E; E = E->next()) {
- if (E->get()!=Vector3()) {
+ if (E->get() != Vector3()) {
lines.push_back(E->key().from);
lines.push_back(E->key().to);
}
}
- add_lines(lines,SpatialEditorGizmos::singleton->room_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->room_material);
add_collision_segments(lines);
-
}
-RoomSpatialGizmo::RoomSpatialGizmo(Room* p_room){
+RoomSpatialGizmo::RoomSpatialGizmo(Room *p_room) {
set_spatial_node(p_room);
- room=p_room;
+ room = p_room;
}
/////
-
void PortalSpatialGizmo::redraw() {
clear();
Vector<Point2> points = portal->get_shape();
- if (points.size()==0) {
+ if (points.size() == 0) {
return;
}
Vector<Vector3> lines;
Vector3 center;
- for(int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
Vector3 f;
- f.x=points[i].x;
- f.y=points[i].y;
+ f.x = points[i].x;
+ f.y = points[i].y;
Vector3 fn;
- fn.x=points[(i+1)%points.size()].x;
- fn.y=points[(i+1)%points.size()].y;
- center+=f;
+ fn.x = points[(i + 1) % points.size()].x;
+ fn.y = points[(i + 1) % points.size()].y;
+ center += f;
lines.push_back(f);
lines.push_back(fn);
}
- center/=points.size();
+ center /= points.size();
lines.push_back(center);
- lines.push_back(center+Vector3(0,0,1));
+ lines.push_back(center + Vector3(0, 0, 1));
- add_lines(lines,SpatialEditorGizmos::singleton->portal_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->portal_material);
add_collision_segments(lines);
-
}
-PortalSpatialGizmo::PortalSpatialGizmo(Portal* p_portal){
+PortalSpatialGizmo::PortalSpatialGizmo(Portal *p_portal) {
set_spatial_node(p_portal);
- portal=p_portal;
+ portal = p_portal;
}
/////
-
void RayCastSpatialGizmo::redraw() {
clear();
-
Vector<Vector3> lines;
lines.push_back(Vector3());
lines.push_back(raycast->get_cast_to());
- add_lines(lines,SpatialEditorGizmos::singleton->raycast_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->raycast_material);
add_collision_segments(lines);
-
}
-RayCastSpatialGizmo::RayCastSpatialGizmo(RayCast* p_raycast) {
+RayCastSpatialGizmo::RayCastSpatialGizmo(RayCast *p_raycast) {
set_spatial_node(p_raycast);
- raycast=p_raycast;
+ raycast = p_raycast;
}
-
-
/////
-
void VehicleWheelSpatialGizmo::redraw() {
clear();
-
Vector<Vector3> points;
float r = car_wheel->get_radius();
- const int skip=10;
- for(int i=0;i<=360;i+=skip) {
+ const int skip = 10;
+ for (int i = 0; i <= 360; i += skip) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+skip);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + skip);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r;
- points.push_back(Vector3(0,a.x,a.y));
- points.push_back(Vector3(0,b.x,b.y));
+ points.push_back(Vector3(0, a.x, a.y));
+ points.push_back(Vector3(0, b.x, b.y));
- const int springsec=4;
+ const int springsec = 4;
- for(int j=0;j<springsec;j++) {
- float t = car_wheel->get_suspension_rest_length()*5;
- points.push_back(Vector3(a.x,i/360.0*t/springsec+j*(t/springsec),a.y)*0.2);
- points.push_back(Vector3(b.x,(i+skip)/360.0*t/springsec+j*(t/springsec),b.y)*0.2);
+ for (int j = 0; j < springsec; j++) {
+ float t = car_wheel->get_suspension_rest_length() * 5;
+ points.push_back(Vector3(a.x, i / 360.0 * t / springsec + j * (t / springsec), a.y) * 0.2);
+ points.push_back(Vector3(b.x, (i + skip) / 360.0 * t / springsec + j * (t / springsec), b.y) * 0.2);
}
-
-
}
//travel
- points.push_back(Vector3(0,0,0));
- points.push_back(Vector3(0,car_wheel->get_suspension_rest_length(),0));
+ points.push_back(Vector3(0, 0, 0));
+ points.push_back(Vector3(0, car_wheel->get_suspension_rest_length(), 0));
//axis
- points.push_back(Vector3(r*0.2,car_wheel->get_suspension_rest_length(),0));
- points.push_back(Vector3(-r*0.2,car_wheel->get_suspension_rest_length(),0));
+ points.push_back(Vector3(r * 0.2, car_wheel->get_suspension_rest_length(), 0));
+ points.push_back(Vector3(-r * 0.2, car_wheel->get_suspension_rest_length(), 0));
//axis
- points.push_back(Vector3(r*0.2,0,0));
- points.push_back(Vector3(-r*0.2,0,0));
+ points.push_back(Vector3(r * 0.2, 0, 0));
+ points.push_back(Vector3(-r * 0.2, 0, 0));
//forward line
- points.push_back(Vector3(0,-r,0));
- points.push_back(Vector3(0,-r,r*2));
- points.push_back(Vector3(0,-r,r*2));
- points.push_back(Vector3(r*2*0.2,-r,r*2*0.8));
- points.push_back(Vector3(0,-r,r*2));
- points.push_back(Vector3(-r*2*0.2,-r,r*2*0.8));
-
- add_lines(points,SpatialEditorGizmos::singleton->car_wheel_material);
+ points.push_back(Vector3(0, -r, 0));
+ points.push_back(Vector3(0, -r, r * 2));
+ points.push_back(Vector3(0, -r, r * 2));
+ points.push_back(Vector3(r * 2 * 0.2, -r, r * 2 * 0.8));
+ points.push_back(Vector3(0, -r, r * 2));
+ points.push_back(Vector3(-r * 2 * 0.2, -r, r * 2 * 0.8));
+
+ add_lines(points, SpatialEditorGizmos::singleton->car_wheel_material);
add_collision_segments(points);
-
}
-VehicleWheelSpatialGizmo::VehicleWheelSpatialGizmo(VehicleWheel* p_car_wheel){
+VehicleWheelSpatialGizmo::VehicleWheelSpatialGizmo(VehicleWheel *p_car_wheel) {
set_spatial_node(p_car_wheel);
- car_wheel=p_car_wheel;
+ car_wheel = p_car_wheel;
}
-
-
///
void TestCubeSpatialGizmo::redraw() {
@@ -1578,20 +1448,14 @@ void TestCubeSpatialGizmo::redraw() {
add_collision_triangles(SpatialEditorGizmos::singleton->test_cube_tm);
}
-TestCubeSpatialGizmo::TestCubeSpatialGizmo(TestCube* p_tc) {
+TestCubeSpatialGizmo::TestCubeSpatialGizmo(TestCube *p_tc) {
- tc=p_tc;
+ tc = p_tc;
set_spatial_node(p_tc);
}
-
///////////
-
-
-
-
-
String CollisionShapeSpatialGizmo::get_handle_name(int p_idx) const {
Ref<Shape> s = cs->get_shape();
@@ -1610,7 +1474,7 @@ String CollisionShapeSpatialGizmo::get_handle_name(int p_idx) const {
if (s->cast_to<CapsuleShape>()) {
- return p_idx==0?"Radius":"Height";
+ return p_idx == 0 ? "Radius" : "Height";
}
if (s->cast_to<RayShape>()) {
@@ -1620,7 +1484,7 @@ String CollisionShapeSpatialGizmo::get_handle_name(int p_idx) const {
return "";
}
-Variant CollisionShapeSpatialGizmo::get_handle_value(int p_idx) const{
+Variant CollisionShapeSpatialGizmo::get_handle_value(int p_idx) const {
Ref<Shape> s = cs->get_shape();
if (s.is_null())
@@ -1641,7 +1505,7 @@ Variant CollisionShapeSpatialGizmo::get_handle_value(int p_idx) const{
if (s->cast_to<CapsuleShape>()) {
Ref<CapsuleShape> cs = s;
- return p_idx==0?cs->get_radius():cs->get_height();
+ return p_idx == 0 ? cs->get_radius() : cs->get_height();
}
if (s->cast_to<RayShape>()) {
@@ -1652,7 +1516,7 @@ Variant CollisionShapeSpatialGizmo::get_handle_value(int p_idx) const{
return Variant();
}
-void CollisionShapeSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point){
+void CollisionShapeSpatialGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Ref<Shape> s = cs->get_shape();
if (s.is_null())
return;
@@ -1664,16 +1528,16 @@ void CollisionShapeSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Po
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 sg[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*4096)};
+ Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 4096) };
if (s->cast_to<SphereShape>()) {
Ref<SphereShape> ss = s;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),Vector3(4096,0,0),sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), Vector3(4096, 0, 0), sg[0], sg[1], ra, rb);
float d = ra.x;
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
ss->set_radius(d);
}
@@ -1681,62 +1545,58 @@ void CollisionShapeSpatialGizmo::set_handle(int p_idx,Camera *p_camera, const Po
if (s->cast_to<RayShape>()) {
Ref<RayShape> rs = s;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),Vector3(0,0,4096),sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), Vector3(0, 0, 4096), sg[0], sg[1], ra, rb);
float d = ra.z;
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
rs->set_length(d);
}
-
if (s->cast_to<BoxShape>()) {
Vector3 axis;
- axis[p_idx]=1.0;
+ axis[p_idx] = 1.0;
Ref<BoxShape> bs = s;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),axis*4096,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
Vector3 he = bs->get_extents();
- he[p_idx]=d;
+ he[p_idx] = d;
bs->set_extents(he);
-
}
if (s->cast_to<CapsuleShape>()) {
Vector3 axis;
- axis[p_idx==0?0:2]=1.0;
+ axis[p_idx == 0 ? 0 : 2] = 1.0;
Ref<CapsuleShape> cs = s;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),axis*4096,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), axis * 4096, sg[0], sg[1], ra, rb);
float d = axis.dot(ra);
- if (p_idx==1)
- d-=cs->get_radius();
- if (d<0.001)
- d=0.001;
+ if (p_idx == 1)
+ d -= cs->get_radius();
+ if (d < 0.001)
+ d = 0.001;
- if (p_idx==0)
+ if (p_idx == 0)
cs->set_radius(d);
- else if (p_idx==1)
- cs->set_height(d*2.0);
-
+ else if (p_idx == 1)
+ cs->set_height(d * 2.0);
}
-
}
-void CollisionShapeSpatialGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void CollisionShapeSpatialGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
Ref<Shape> s = cs->get_shape();
if (s.is_null())
return;
if (s->cast_to<SphereShape>()) {
- Ref<SphereShape> ss=s;
+ Ref<SphereShape> ss = s;
if (p_cancel) {
ss->set_radius(p_restore);
return;
@@ -1744,15 +1604,14 @@ void CollisionShapeSpatialGizmo::commit_handle(int p_idx,const Variant& p_restor
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Sphere Shape Radius"));
- ur->add_do_method(ss.ptr(),"set_radius",ss->get_radius());
- ur->add_undo_method(ss.ptr(),"set_radius",p_restore);
+ ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius());
+ ur->add_undo_method(ss.ptr(), "set_radius", p_restore);
ur->commit_action();
-
}
if (s->cast_to<BoxShape>()) {
- Ref<BoxShape> ss=s;
+ Ref<BoxShape> ss = s;
if (p_cancel) {
ss->set_extents(p_restore);
return;
@@ -1760,16 +1619,16 @@ void CollisionShapeSpatialGizmo::commit_handle(int p_idx,const Variant& p_restor
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Box Shape Extents"));
- ur->add_do_method(ss.ptr(),"set_extents",ss->get_extents());
- ur->add_undo_method(ss.ptr(),"set_extents",p_restore);
+ ur->add_do_method(ss.ptr(), "set_extents", ss->get_extents());
+ ur->add_undo_method(ss.ptr(), "set_extents", p_restore);
ur->commit_action();
}
if (s->cast_to<CapsuleShape>()) {
- Ref<CapsuleShape> ss=s;
+ Ref<CapsuleShape> ss = s;
if (p_cancel) {
- if (p_idx==0)
+ if (p_idx == 0)
ss->set_radius(p_restore);
else
ss->set_height(p_restore);
@@ -1777,24 +1636,22 @@ void CollisionShapeSpatialGizmo::commit_handle(int p_idx,const Variant& p_restor
}
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
- if (p_idx==0) {
+ if (p_idx == 0) {
ur->create_action(TTR("Change Capsule Shape Radius"));
- ur->add_do_method(ss.ptr(),"set_radius",ss->get_radius());
- ur->add_undo_method(ss.ptr(),"set_radius",p_restore);
+ ur->add_do_method(ss.ptr(), "set_radius", ss->get_radius());
+ ur->add_undo_method(ss.ptr(), "set_radius", p_restore);
} else {
ur->create_action(TTR("Change Capsule Shape Height"));
- ur->add_do_method(ss.ptr(),"set_height",ss->get_height());
- ur->add_undo_method(ss.ptr(),"set_height",p_restore);
-
+ ur->add_do_method(ss.ptr(), "set_height", ss->get_height());
+ ur->add_undo_method(ss.ptr(), "set_height", p_restore);
}
ur->commit_action();
-
}
if (s->cast_to<RayShape>()) {
- Ref<RayShape> ss=s;
+ Ref<RayShape> ss = s;
if (p_cancel) {
ss->set_length(p_restore);
return;
@@ -1802,14 +1659,12 @@ void CollisionShapeSpatialGizmo::commit_handle(int p_idx,const Variant& p_restor
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Ray Shape Length"));
- ur->add_do_method(ss.ptr(),"set_length",ss->get_length());
- ur->add_undo_method(ss.ptr(),"set_length",p_restore);
+ ur->add_do_method(ss.ptr(), "set_length", ss->get_length());
+ ur->add_undo_method(ss.ptr(), "set_length", p_restore);
ur->commit_action();
-
}
-
}
-void CollisionShapeSpatialGizmo::redraw(){
+void CollisionShapeSpatialGizmo::redraw() {
clear();
@@ -1819,176 +1674,168 @@ void CollisionShapeSpatialGizmo::redraw(){
if (s->cast_to<SphereShape>()) {
- Ref<SphereShape> sp= s;
- float r=sp->get_radius();
+ Ref<SphereShape> sp = s;
+ float r = sp->get_radius();
Vector<Vector3> points;
- for(int i=0;i<=360;i++) {
+ for (int i = 0; i <= 360; i++) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r;
-
- points.push_back(Vector3(a.x,0,a.y));
- points.push_back(Vector3(b.x,0,b.y));
- points.push_back(Vector3(0,a.x,a.y));
- points.push_back(Vector3(0,b.x,b.y));
- points.push_back(Vector3(a.x,a.y,0));
- points.push_back(Vector3(b.x,b.y,0));
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r;
+ points.push_back(Vector3(a.x, 0, a.y));
+ points.push_back(Vector3(b.x, 0, b.y));
+ points.push_back(Vector3(0, a.x, a.y));
+ points.push_back(Vector3(0, b.x, b.y));
+ points.push_back(Vector3(a.x, a.y, 0));
+ points.push_back(Vector3(b.x, b.y, 0));
}
Vector<Vector3> collision_segments;
- for(int i=0;i<64;i++) {
+ for (int i = 0; i < 64; i++) {
- float ra=i*Math_PI*2.0/64.0;
- float rb=(i+1)*Math_PI*2.0/64.0;
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r;
+ float ra = i * Math_PI * 2.0 / 64.0;
+ float rb = (i + 1) * Math_PI * 2.0 / 64.0;
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r;
- collision_segments.push_back(Vector3(a.x,0,a.y));
- collision_segments.push_back(Vector3(b.x,0,b.y));
- collision_segments.push_back(Vector3(0,a.x,a.y));
- collision_segments.push_back(Vector3(0,b.x,b.y));
- collision_segments.push_back(Vector3(a.x,a.y,0));
- collision_segments.push_back(Vector3(b.x,b.y,0));
+ collision_segments.push_back(Vector3(a.x, 0, a.y));
+ collision_segments.push_back(Vector3(b.x, 0, b.y));
+ collision_segments.push_back(Vector3(0, a.x, a.y));
+ collision_segments.push_back(Vector3(0, b.x, b.y));
+ collision_segments.push_back(Vector3(a.x, a.y, 0));
+ collision_segments.push_back(Vector3(b.x, b.y, 0));
}
- add_lines(points,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(points, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(collision_segments);
Vector<Vector3> handles;
- handles.push_back(Vector3(r,0,0));
+ handles.push_back(Vector3(r, 0, 0));
add_handles(handles);
-
}
if (s->cast_to<BoxShape>()) {
- Ref<BoxShape> bs=s;
+ Ref<BoxShape> bs = s;
Vector<Vector3> lines;
Rect3 aabb;
- aabb.pos=-bs->get_extents();
- aabb.size=aabb.pos*-2;
+ aabb.pos = -bs->get_extents();
+ aabb.size = aabb.pos * -2;
- for(int i=0;i<12;i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ for (int i = 0; i < 12; i++) {
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
Vector<Vector3> handles;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 ax;
- ax[i]=bs->get_extents()[i];
+ ax[i] = bs->get_extents()[i];
handles.push_back(ax);
}
- add_lines(lines,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(lines);
add_handles(handles);
-
}
if (s->cast_to<CapsuleShape>()) {
- Ref<CapsuleShape> cs=s;
+ Ref<CapsuleShape> cs = s;
float radius = cs->get_radius();
float height = cs->get_height();
-
Vector<Vector3> points;
- Vector3 d(0,0,height*0.5);
- for(int i=0;i<360;i++) {
+ Vector3 d(0, 0, height * 0.5);
+ for (int i = 0; i < 360; i++) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*radius;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*radius;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius;
- points.push_back(Vector3(a.x,a.y,0)+d);
- points.push_back(Vector3(b.x,b.y,0)+d);
+ points.push_back(Vector3(a.x, a.y, 0) + d);
+ points.push_back(Vector3(b.x, b.y, 0) + d);
- points.push_back(Vector3(a.x,a.y,0)-d);
- points.push_back(Vector3(b.x,b.y,0)-d);
+ points.push_back(Vector3(a.x, a.y, 0) - d);
+ points.push_back(Vector3(b.x, b.y, 0) - d);
- if (i%90==0) {
+ if (i % 90 == 0) {
- points.push_back(Vector3(a.x,a.y,0)+d);
- points.push_back(Vector3(a.x,a.y,0)-d);
+ points.push_back(Vector3(a.x, a.y, 0) + d);
+ points.push_back(Vector3(a.x, a.y, 0) - d);
}
- Vector3 dud = i<180?d:-d;
-
- points.push_back(Vector3(0,a.y,a.x)+dud);
- points.push_back(Vector3(0,b.y,b.x)+dud);
- points.push_back(Vector3(a.y,0,a.x)+dud);
- points.push_back(Vector3(b.y,0,b.x)+dud);
+ Vector3 dud = i < 180 ? d : -d;
+ points.push_back(Vector3(0, a.y, a.x) + dud);
+ points.push_back(Vector3(0, b.y, b.x) + dud);
+ points.push_back(Vector3(a.y, 0, a.x) + dud);
+ points.push_back(Vector3(b.y, 0, b.x) + dud);
}
- add_lines(points,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(points, SpatialEditorGizmos::singleton->shape_material);
Vector<Vector3> collision_segments;
- for(int i=0;i<64;i++) {
+ for (int i = 0; i < 64; i++) {
- float ra=i*Math_PI*2.0/64.0;
- float rb=(i+1)*Math_PI*2.0/64.0;
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*radius;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*radius;
+ float ra = i * Math_PI * 2.0 / 64.0;
+ float rb = (i + 1) * Math_PI * 2.0 / 64.0;
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius;
- collision_segments.push_back(Vector3(a.x,a.y,0)+d);
- collision_segments.push_back(Vector3(b.x,b.y,0)+d);
+ collision_segments.push_back(Vector3(a.x, a.y, 0) + d);
+ collision_segments.push_back(Vector3(b.x, b.y, 0) + d);
- collision_segments.push_back(Vector3(a.x,a.y,0)-d);
- collision_segments.push_back(Vector3(b.x,b.y,0)-d);
+ collision_segments.push_back(Vector3(a.x, a.y, 0) - d);
+ collision_segments.push_back(Vector3(b.x, b.y, 0) - d);
- if (i%16==0) {
+ if (i % 16 == 0) {
- collision_segments.push_back(Vector3(a.x,a.y,0)+d);
- collision_segments.push_back(Vector3(a.x,a.y,0)-d);
+ collision_segments.push_back(Vector3(a.x, a.y, 0) + d);
+ collision_segments.push_back(Vector3(a.x, a.y, 0) - d);
}
- Vector3 dud = i<32?d:-d;
-
- collision_segments.push_back(Vector3(0,a.y,a.x)+dud);
- collision_segments.push_back(Vector3(0,b.y,b.x)+dud);
- collision_segments.push_back(Vector3(a.y,0,a.x)+dud);
- collision_segments.push_back(Vector3(b.y,0,b.x)+dud);
+ Vector3 dud = i < 32 ? d : -d;
+ collision_segments.push_back(Vector3(0, a.y, a.x) + dud);
+ collision_segments.push_back(Vector3(0, b.y, b.x) + dud);
+ collision_segments.push_back(Vector3(a.y, 0, a.x) + dud);
+ collision_segments.push_back(Vector3(b.y, 0, b.x) + dud);
}
add_collision_segments(collision_segments);
Vector<Vector3> handles;
- handles.push_back(Vector3(cs->get_radius(),0,0));
- handles.push_back(Vector3(0,0,cs->get_height()*0.5+cs->get_radius()));
+ handles.push_back(Vector3(cs->get_radius(), 0, 0));
+ handles.push_back(Vector3(0, 0, cs->get_height() * 0.5 + cs->get_radius()));
add_handles(handles);
-
-
}
if (s->cast_to<PlaneShape>()) {
- Ref<PlaneShape> ps=s;
+ Ref<PlaneShape> ps = s;
Plane p = ps->get_plane();
Vector<Vector3> points;
Vector3 n1 = p.get_any_perpendicular_normal();
Vector3 n2 = p.normal.cross(n1).normalized();
- Vector3 pface[4]={
- p.normal*p.d+n1*10.0+n2*10.0,
- p.normal*p.d+n1*10.0+n2*-10.0,
- p.normal*p.d+n1*-10.0+n2*-10.0,
- p.normal*p.d+n1*-10.0+n2*10.0,
+ Vector3 pface[4] = {
+ p.normal * p.d + n1 * 10.0 + n2 * 10.0,
+ p.normal * p.d + n1 * 10.0 + n2 * -10.0,
+ p.normal * p.d + n1 * -10.0 + n2 * -10.0,
+ p.normal * p.d + n1 * -10.0 + n2 * 10.0,
};
points.push_back(pface[0]);
@@ -1999,106 +1846,92 @@ void CollisionShapeSpatialGizmo::redraw(){
points.push_back(pface[3]);
points.push_back(pface[3]);
points.push_back(pface[0]);
- points.push_back(p.normal*p.d);
- points.push_back(p.normal*p.d+p.normal*3);
+ points.push_back(p.normal * p.d);
+ points.push_back(p.normal * p.d + p.normal * 3);
- add_lines(points,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(points, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(points);
-
}
-
if (s->cast_to<ConvexPolygonShape>()) {
PoolVector<Vector3> points = s->cast_to<ConvexPolygonShape>()->get_points();
- if (points.size()>3) {
+ if (points.size() > 3) {
QuickHull qh;
Vector<Vector3> varr = Variant(points);
Geometry::MeshData md;
- Error err = qh.build(varr,md);
- if (err==OK) {
+ Error err = qh.build(varr, md);
+ if (err == OK) {
Vector<Vector3> points;
- points.resize(md.edges.size()*2);
- for(int i=0;i<md.edges.size();i++) {
- points[i*2+0]=md.vertices[md.edges[i].a];
- points[i*2+1]=md.vertices[md.edges[i].b];
+ points.resize(md.edges.size() * 2);
+ for (int i = 0; i < md.edges.size(); i++) {
+ points[i * 2 + 0] = md.vertices[md.edges[i].a];
+ points[i * 2 + 1] = md.vertices[md.edges[i].b];
}
-
- add_lines(points,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(points, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(points);
-
}
}
-
}
-
if (s->cast_to<RayShape>()) {
- Ref<RayShape> rs=s;
+ Ref<RayShape> rs = s;
Vector<Vector3> points;
points.push_back(Vector3());
- points.push_back(Vector3(0,0,rs->get_length()));
- add_lines(points,SpatialEditorGizmos::singleton->shape_material);
+ points.push_back(Vector3(0, 0, rs->get_length()));
+ add_lines(points, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(points);
Vector<Vector3> handles;
- handles.push_back(Vector3(0,0,rs->get_length()));
+ handles.push_back(Vector3(0, 0, rs->get_length()));
add_handles(handles);
-
-
}
-
}
-CollisionShapeSpatialGizmo::CollisionShapeSpatialGizmo(CollisionShape* p_cs) {
+CollisionShapeSpatialGizmo::CollisionShapeSpatialGizmo(CollisionShape *p_cs) {
- cs=p_cs;
+ cs = p_cs;
set_spatial_node(p_cs);
}
-
-
/////
-
void CollisionPolygonSpatialGizmo::redraw() {
clear();
Vector<Vector2> points = polygon->get_polygon();
- float depth = polygon->get_depth()*0.5;
+ float depth = polygon->get_depth() * 0.5;
Vector<Vector3> lines;
- for(int i=0;i<points.size();i++) {
-
- int n = (i+1)%points.size();
- lines.push_back(Vector3(points[i].x,points[i].y,depth));
- lines.push_back(Vector3(points[n].x,points[n].y,depth));
- lines.push_back(Vector3(points[i].x,points[i].y,-depth));
- lines.push_back(Vector3(points[n].x,points[n].y,-depth));
- lines.push_back(Vector3(points[i].x,points[i].y,depth));
- lines.push_back(Vector3(points[i].x,points[i].y,-depth));
+ for (int i = 0; i < points.size(); i++) {
+ int n = (i + 1) % points.size();
+ lines.push_back(Vector3(points[i].x, points[i].y, depth));
+ lines.push_back(Vector3(points[n].x, points[n].y, depth));
+ lines.push_back(Vector3(points[i].x, points[i].y, -depth));
+ lines.push_back(Vector3(points[n].x, points[n].y, -depth));
+ lines.push_back(Vector3(points[i].x, points[i].y, depth));
+ lines.push_back(Vector3(points[i].x, points[i].y, -depth));
}
- add_lines(lines,SpatialEditorGizmos::singleton->shape_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->shape_material);
add_collision_segments(lines);
}
-CollisionPolygonSpatialGizmo::CollisionPolygonSpatialGizmo(CollisionPolygon* p_polygon){
+CollisionPolygonSpatialGizmo::CollisionPolygonSpatialGizmo(CollisionPolygon *p_polygon) {
set_spatial_node(p_polygon);
- polygon=p_polygon;
+ polygon = p_polygon;
}
///
-
String VisibilityNotifierGizmo::get_handle_name(int p_idx) const {
- switch(p_idx) {
+ switch (p_idx) {
case 0: return "X";
case 1: return "Y";
case 2: return "Z";
@@ -2106,12 +1939,11 @@ String VisibilityNotifierGizmo::get_handle_name(int p_idx) const {
return "";
}
-Variant VisibilityNotifierGizmo::get_handle_value(int p_idx) const{
+Variant VisibilityNotifierGizmo::get_handle_value(int p_idx) const {
return notifier->get_aabb();
}
-void VisibilityNotifierGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point){
-
+void VisibilityNotifierGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Transform gt = notifier->get_global_transform();
//gt.orthonormalize();
@@ -2121,25 +1953,24 @@ void VisibilityNotifierGizmo::set_handle(int p_idx,Camera *p_camera, const Point
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 sg[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*4096)};
- Vector3 ofs = aabb.pos+aabb.size*0.5;
+ Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 4096) };
+ Vector3 ofs = aabb.pos + aabb.size * 0.5;
Vector3 axis;
- axis[p_idx]=1.0;
+ axis[p_idx] = 1.0;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(ofs,ofs+axis*4096,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(ofs, ofs + axis * 4096, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
- aabb.pos[p_idx]=(aabb.pos[p_idx]+aabb.size[p_idx]*0.5)-d;
- aabb.size[p_idx]=d*2;
+ aabb.pos[p_idx] = (aabb.pos[p_idx] + aabb.size[p_idx] * 0.5) - d;
+ aabb.size[p_idx] = d * 2;
notifier->set_aabb(aabb);
}
-void VisibilityNotifierGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
-
+void VisibilityNotifierGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
if (p_cancel) {
notifier->set_aabb(p_restore);
@@ -2148,57 +1979,52 @@ void VisibilityNotifierGizmo::commit_handle(int p_idx,const Variant& p_restore,b
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Notifier Extents"));
- ur->add_do_method(notifier,"set_aabb",notifier->get_aabb());
- ur->add_undo_method(notifier,"set_aabb",p_restore);
+ ur->add_do_method(notifier, "set_aabb", notifier->get_aabb());
+ ur->add_undo_method(notifier, "set_aabb", p_restore);
ur->commit_action();
-
}
-void VisibilityNotifierGizmo::redraw(){
+void VisibilityNotifierGizmo::redraw() {
clear();
Vector<Vector3> lines;
Rect3 aabb = notifier->get_aabb();
- for(int i=0;i<12;i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ for (int i = 0; i < 12; i++) {
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
Vector<Vector3> handles;
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 ax;
- ax[i]=aabb.pos[i]+aabb.size[i];
+ ax[i] = aabb.pos[i] + aabb.size[i];
handles.push_back(ax);
}
- add_lines(lines,SpatialEditorGizmos::singleton->visibility_notifier_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->visibility_notifier_material);
//add_unscaled_billboard(SpatialEditorGizmos::singleton->visi,0.05);
add_collision_segments(lines);
add_handles(handles);
-
}
-VisibilityNotifierGizmo::VisibilityNotifierGizmo(VisibilityNotifier* p_notifier){
+VisibilityNotifierGizmo::VisibilityNotifierGizmo(VisibilityNotifier *p_notifier) {
- notifier=p_notifier;
+ notifier = p_notifier;
set_spatial_node(p_notifier);
}
////////
-
///
-
String ReflectionProbeGizmo::get_handle_name(int p_idx) const {
- switch(p_idx) {
+ switch (p_idx) {
case 0: return "Extents X";
case 1: return "Extents Y";
case 2: return "Extents Z";
@@ -2209,63 +2035,61 @@ String ReflectionProbeGizmo::get_handle_name(int p_idx) const {
return "";
}
-Variant ReflectionProbeGizmo::get_handle_value(int p_idx) const{
+Variant ReflectionProbeGizmo::get_handle_value(int p_idx) const {
- return Rect3(probe->get_extents(),probe->get_origin_offset());
+ return Rect3(probe->get_extents(), probe->get_origin_offset());
}
-void ReflectionProbeGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point){
+void ReflectionProbeGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Transform gt = probe->get_global_transform();
//gt.orthonormalize();
Transform gi = gt.affine_inverse();
-
- if (p_idx<3) {
+ if (p_idx < 3) {
Vector3 extents = probe->get_extents();
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 sg[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*16384)};
+ Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 16384) };
Vector3 axis;
- axis[p_idx]=1.0;
+ axis[p_idx] = 1.0;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),axis*16384,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), axis * 16384, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
- extents[p_idx]=d;
+ extents[p_idx] = d;
probe->set_extents(extents);
} else {
- p_idx-=3;
+ p_idx -= 3;
Vector3 origin = probe->get_origin_offset();
- origin[p_idx]=0;
+ origin[p_idx] = 0;
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 sg[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*16384)};
+ Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 16384) };
Vector3 axis;
- axis[p_idx]=1.0;
+ axis[p_idx] = 1.0;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(origin-axis*16384,origin+axis*16384,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(origin - axis * 16384, origin + axis * 16384, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
- d+=0.25;
+ d += 0.25;
- origin[p_idx]=d;
+ origin[p_idx] = d;
probe->set_origin_offset(origin);
-
}
}
-void ReflectionProbeGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void ReflectionProbeGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
Rect3 restore = p_restore;
@@ -2277,15 +2101,14 @@ void ReflectionProbeGizmo::commit_handle(int p_idx,const Variant& p_restore,bool
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Probe Extents"));
- ur->add_do_method(probe,"set_extents",probe->get_extents());
- ur->add_do_method(probe,"set_origin_offset",probe->get_origin_offset());
- ur->add_undo_method(probe,"set_extents",restore.pos);
- ur->add_undo_method(probe,"set_origin_offset",restore.size);
+ ur->add_do_method(probe, "set_extents", probe->get_extents());
+ ur->add_do_method(probe, "set_origin_offset", probe->get_origin_offset());
+ ur->add_undo_method(probe, "set_extents", restore.pos);
+ ur->add_undo_method(probe, "set_origin_offset", restore.size);
ur->commit_action();
-
}
-void ReflectionProbeGizmo::redraw(){
+void ReflectionProbeGizmo::redraw() {
clear();
@@ -2294,69 +2117,61 @@ void ReflectionProbeGizmo::redraw(){
Vector3 extents = probe->get_extents();
Rect3 aabb;
- aabb.pos=-extents;
- aabb.size=extents*2;
+ aabb.pos = -extents;
+ aabb.size = extents * 2;
- for(int i=0;i<12;i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ for (int i = 0; i < 12; i++) {
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
Vector3 ep = aabb.get_endpoint(i);
internal_lines.push_back(probe->get_origin_offset());
internal_lines.push_back(ep);
-
-
}
Vector<Vector3> handles;
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 ax;
- ax[i]=aabb.pos[i]+aabb.size[i];
+ ax[i] = aabb.pos[i] + aabb.size[i];
handles.push_back(ax);
}
- for(int i=0;i<3;i++) {
-
+ for (int i = 0; i < 3; i++) {
- Vector3 orig_handle=probe->get_origin_offset();
- orig_handle[i]-=0.25;
+ Vector3 orig_handle = probe->get_origin_offset();
+ orig_handle[i] -= 0.25;
lines.push_back(orig_handle);
handles.push_back(orig_handle);
- orig_handle[i]+=0.5;
+ orig_handle[i] += 0.5;
lines.push_back(orig_handle);
}
- add_lines(lines,SpatialEditorGizmos::singleton->reflection_probe_material);
- add_lines(internal_lines,SpatialEditorGizmos::singleton->reflection_probe_material_internal);
+ add_lines(lines, SpatialEditorGizmos::singleton->reflection_probe_material);
+ add_lines(internal_lines, SpatialEditorGizmos::singleton->reflection_probe_material_internal);
//add_unscaled_billboard(SpatialEditorGizmos::singleton->visi,0.05);
add_collision_segments(lines);
add_handles(handles);
-
}
-ReflectionProbeGizmo::ReflectionProbeGizmo(ReflectionProbe* p_probe){
+ReflectionProbeGizmo::ReflectionProbeGizmo(ReflectionProbe *p_probe) {
- probe=p_probe;
+ probe = p_probe;
set_spatial_node(p_probe);
}
////////
-
-
///
-
String GIProbeGizmo::get_handle_name(int p_idx) const {
- switch(p_idx) {
+ switch (p_idx) {
case 0: return "Extents X";
case 1: return "Extents Y";
case 2: return "Extents Z";
@@ -2364,39 +2179,37 @@ String GIProbeGizmo::get_handle_name(int p_idx) const {
return "";
}
-Variant GIProbeGizmo::get_handle_value(int p_idx) const{
+Variant GIProbeGizmo::get_handle_value(int p_idx) const {
return probe->get_extents();
}
-void GIProbeGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point){
+void GIProbeGizmo::set_handle(int p_idx, Camera *p_camera, const Point2 &p_point) {
Transform gt = probe->get_global_transform();
//gt.orthonormalize();
Transform gi = gt.affine_inverse();
-
Vector3 extents = probe->get_extents();
Vector3 ray_from = p_camera->project_ray_origin(p_point);
Vector3 ray_dir = p_camera->project_ray_normal(p_point);
- Vector3 sg[2]={gi.xform(ray_from),gi.xform(ray_from+ray_dir*16384)};
+ Vector3 sg[2] = { gi.xform(ray_from), gi.xform(ray_from + ray_dir * 16384) };
Vector3 axis;
- axis[p_idx]=1.0;
+ axis[p_idx] = 1.0;
- Vector3 ra,rb;
- Geometry::get_closest_points_between_segments(Vector3(),axis*16384,sg[0],sg[1],ra,rb);
+ Vector3 ra, rb;
+ Geometry::get_closest_points_between_segments(Vector3(), axis * 16384, sg[0], sg[1], ra, rb);
float d = ra[p_idx];
- if (d<0.001)
- d=0.001;
+ if (d < 0.001)
+ d = 0.001;
- extents[p_idx]=d;
+ extents[p_idx] = d;
probe->set_extents(extents);
-
}
-void GIProbeGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
+void GIProbeGizmo::commit_handle(int p_idx, const Variant &p_restore, bool p_cancel) {
Vector3 restore = p_restore;
@@ -2407,108 +2220,97 @@ void GIProbeGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cance
UndoRedo *ur = SpatialEditor::get_singleton()->get_undo_redo();
ur->create_action(TTR("Change Probe Extents"));
- ur->add_do_method(probe,"set_extents",probe->get_extents());
- ur->add_undo_method(probe,"set_extents",restore);
+ ur->add_do_method(probe, "set_extents", probe->get_extents());
+ ur->add_undo_method(probe, "set_extents", restore);
ur->commit_action();
-
}
-void GIProbeGizmo::redraw(){
+void GIProbeGizmo::redraw() {
clear();
Vector<Vector3> lines;
Vector3 extents = probe->get_extents();
- static const int subdivs[GIProbe::SUBDIV_MAX]={64,128,256,512};
+ static const int subdivs[GIProbe::SUBDIV_MAX] = { 64, 128, 256, 512 };
- Rect3 aabb = Rect3(-extents,extents*2);
+ Rect3 aabb = Rect3(-extents, extents * 2);
int subdiv = subdivs[probe->get_subdiv()];
- float cell_size = aabb.get_longest_axis_size()/subdiv;
+ float cell_size = aabb.get_longest_axis_size() / subdiv;
-
- for(int i=0;i<12;i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ for (int i = 0; i < 12; i++) {
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
- add_lines(lines,SpatialEditorGizmos::singleton->gi_probe_material);
+ add_lines(lines, SpatialEditorGizmos::singleton->gi_probe_material);
add_collision_segments(lines);
lines.clear();
- for(int i=1;i<subdiv;i++) {
-
- for(int j=0;j<3;j++) {
-
+ for (int i = 1; i < subdiv; i++) {
+ for (int j = 0; j < 3; j++) {
- if (cell_size*i>aabb.size[j]) {
+ if (cell_size * i > aabb.size[j]) {
continue;
}
Vector2 dir;
- dir[j]=1.0;
- Vector2 ta,tb;
- int j_n1=(j+1)%3;
- int j_n2=(j+2)%3;
- ta[j_n1]=1.0;
- tb[j_n2]=1.0;
+ dir[j] = 1.0;
+ Vector2 ta, tb;
+ int j_n1 = (j + 1) % 3;
+ int j_n2 = (j + 2) % 3;
+ ta[j_n1] = 1.0;
+ tb[j_n2] = 1.0;
+ for (int k = 0; k < 4; k++) {
- for(int k=0;k<4;k++) {
+ Vector3 from = aabb.pos, to = aabb.pos;
+ from[j] += cell_size * i;
+ to[j] += cell_size * i;
- Vector3 from=aabb.pos,to=aabb.pos;
- from[j]+= cell_size*i;
- to[j]+=cell_size*i;
-
- if (k&1) {
- to[j_n1]+=aabb.size[j_n1];
+ if (k & 1) {
+ to[j_n1] += aabb.size[j_n1];
} else {
- to[j_n2]+=aabb.size[j_n2];
+ to[j_n2] += aabb.size[j_n2];
}
- if (k&2) {
- from[j_n1]+=aabb.size[j_n1];
- from[j_n2]+=aabb.size[j_n2];
+ if (k & 2) {
+ from[j_n1] += aabb.size[j_n1];
+ from[j_n2] += aabb.size[j_n2];
}
lines.push_back(from);
lines.push_back(to);
}
-
}
-
}
- add_lines(lines,SpatialEditorGizmos::singleton->gi_probe_material_internal);
+ add_lines(lines, SpatialEditorGizmos::singleton->gi_probe_material_internal);
Vector<Vector3> handles;
-
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 ax;
- ax[i]=aabb.pos[i]+aabb.size[i];
+ ax[i] = aabb.pos[i] + aabb.size[i];
handles.push_back(ax);
}
-
add_handles(handles);
-
}
-GIProbeGizmo::GIProbeGizmo(GIProbe* p_probe){
+GIProbeGizmo::GIProbeGizmo(GIProbe *p_probe) {
- probe=p_probe;
+ probe = p_probe;
set_spatial_node(p_probe);
}
////////
-
void NavigationMeshSpatialGizmo::redraw() {
clear();
@@ -2517,16 +2319,16 @@ void NavigationMeshSpatialGizmo::redraw() {
return;
PoolVector<Vector3> vertices = navmeshie->get_vertices();
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
List<Face3> faces;
- for(int i=0;i<navmeshie->get_polygon_count();i++) {
+ for (int i = 0; i < navmeshie->get_polygon_count(); i++) {
Vector<int> p = navmeshie->get_polygon(i);
- for(int j=2;j<p.size();j++) {
+ for (int j = 2; j < p.size(); j++) {
Face3 f;
- f.vertex[0]=vr[p[0]];
- f.vertex[1]=vr[p[j-1]];
- f.vertex[2]=vr[p[j]];
+ f.vertex[0] = vr[p[0]];
+ f.vertex[1] = vr[p[j - 1]];
+ f.vertex[2] = vr[p[j]];
faces.push_back(f);
}
@@ -2535,45 +2337,43 @@ void NavigationMeshSpatialGizmo::redraw() {
if (faces.empty())
return;
- Map<_EdgeKey,bool> edge_map;
+ Map<_EdgeKey, bool> edge_map;
PoolVector<Vector3> tmeshfaces;
- tmeshfaces.resize(faces.size()*3);
+ tmeshfaces.resize(faces.size() * 3);
{
- PoolVector<Vector3>::Write tw=tmeshfaces.write();
- int tidx=0;
+ PoolVector<Vector3>::Write tw = tmeshfaces.write();
+ int tidx = 0;
-
- for(List<Face3>::Element *E=faces.front();E;E=E->next()) {
+ for (List<Face3>::Element *E = faces.front(); E; E = E->next()) {
const Face3 &f = E->get();
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- tw[tidx++]=f.vertex[j];
+ tw[tidx++] = f.vertex[j];
_EdgeKey ek;
- ek.from=f.vertex[j].snapped(CMP_EPSILON);
- ek.to=f.vertex[(j+1)%3].snapped(CMP_EPSILON);
- if (ek.from<ek.to)
- SWAP(ek.from,ek.to);
+ ek.from = f.vertex[j].snapped(CMP_EPSILON);
+ ek.to = f.vertex[(j + 1) % 3].snapped(CMP_EPSILON);
+ if (ek.from < ek.to)
+ SWAP(ek.from, ek.to);
- Map<_EdgeKey,bool>::Element *E=edge_map.find(ek);
+ Map<_EdgeKey, bool>::Element *E = edge_map.find(ek);
if (E) {
- E->get()=false;
+ E->get() = false;
} else {
- edge_map[ek]=true;
+ edge_map[ek] = true;
}
-
}
}
}
Vector<Vector3> lines;
- for(Map<_EdgeKey,bool>::Element *E=edge_map.front();E;E=E->next()) {
+ for (Map<_EdgeKey, bool>::Element *E = edge_map.front(); E; E = E->next()) {
if (E->get()) {
lines.push_back(E->key().from);
@@ -2581,55 +2381,50 @@ void NavigationMeshSpatialGizmo::redraw() {
}
}
- Ref<TriangleMesh> tmesh = memnew( TriangleMesh );
+ Ref<TriangleMesh> tmesh = memnew(TriangleMesh);
tmesh->create(tmeshfaces);
if (lines.size())
- add_lines(lines,navmesh->is_enabled()?SpatialEditorGizmos::singleton->navmesh_edge_material:SpatialEditorGizmos::singleton->navmesh_edge_material_disabled);
+ add_lines(lines, navmesh->is_enabled() ? SpatialEditorGizmos::singleton->navmesh_edge_material : SpatialEditorGizmos::singleton->navmesh_edge_material_disabled);
add_collision_triangles(tmesh);
- Ref<Mesh> m = memnew( Mesh );
+ Ref<Mesh> m = memnew(Mesh);
Array a;
a.resize(Mesh::ARRAY_MAX);
- a[0]=tmeshfaces;
- m->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,a);
- m->surface_set_material(0,navmesh->is_enabled()?SpatialEditorGizmos::singleton->navmesh_solid_material:SpatialEditorGizmos::singleton->navmesh_solid_material_disabled);
+ a[0] = tmeshfaces;
+ m->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, a);
+ m->surface_set_material(0, navmesh->is_enabled() ? SpatialEditorGizmos::singleton->navmesh_solid_material : SpatialEditorGizmos::singleton->navmesh_solid_material_disabled);
add_mesh(m);
add_collision_segments(lines);
-
}
-NavigationMeshSpatialGizmo::NavigationMeshSpatialGizmo(NavigationMeshInstance *p_navmesh){
+NavigationMeshSpatialGizmo::NavigationMeshSpatialGizmo(NavigationMeshInstance *p_navmesh) {
set_spatial_node(p_navmesh);
- navmesh=p_navmesh;
+ navmesh = p_navmesh;
}
//////
///
///
-
-
void PinJointSpatialGizmo::redraw() {
clear();
Vector<Vector3> cursor_points;
float cs = 0.25;
- cursor_points.push_back(Vector3(+cs,0,0));
- cursor_points.push_back(Vector3(-cs,0,0));
- cursor_points.push_back(Vector3(0,+cs,0));
- cursor_points.push_back(Vector3(0,-cs,0));
- cursor_points.push_back(Vector3(0,0,+cs));
- cursor_points.push_back(Vector3(0,0,-cs));
+ cursor_points.push_back(Vector3(+cs, 0, 0));
+ cursor_points.push_back(Vector3(-cs, 0, 0));
+ cursor_points.push_back(Vector3(0, +cs, 0));
+ cursor_points.push_back(Vector3(0, -cs, 0));
+ cursor_points.push_back(Vector3(0, 0, +cs));
+ cursor_points.push_back(Vector3(0, 0, -cs));
add_collision_segments(cursor_points);
- add_lines(cursor_points,SpatialEditorGizmos::singleton->joint_material);
-
+ add_lines(cursor_points, SpatialEditorGizmos::singleton->joint_material);
}
+PinJointSpatialGizmo::PinJointSpatialGizmo(PinJoint *p_p3d) {
-PinJointSpatialGizmo::PinJointSpatialGizmo(PinJoint* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
@@ -2644,71 +2439,63 @@ void HingeJointSpatialGizmo::redraw() {
cursor_points.push_back(Vector3(-cs,0,0));
cursor_points.push_back(Vector3(0,+cs,0));
cursor_points.push_back(Vector3(0,-cs,0));*/
- cursor_points.push_back(Vector3(0,0,+cs*2));
- cursor_points.push_back(Vector3(0,0,-cs*2));
+ cursor_points.push_back(Vector3(0, 0, +cs * 2));
+ cursor_points.push_back(Vector3(0, 0, -cs * 2));
float ll = p3d->get_param(HingeJoint::PARAM_LIMIT_LOWER);
float ul = p3d->get_param(HingeJoint::PARAM_LIMIT_UPPER);
- if (p3d->get_flag(HingeJoint::FLAG_USE_LIMIT) && ll<ul) {
+ if (p3d->get_flag(HingeJoint::FLAG_USE_LIMIT) && ll < ul) {
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(ul-ll)/points;
- float n = ll+(i+1)*(ul-ll)/points;
+ float s = ll + i * (ul - ll) / points;
+ float n = ll + (i + 1) * (ul - ll) / points;
- Vector3 from=Vector3( -Math::sin(s),Math::cos(s), 0 )*cs;
- Vector3 to=Vector3( -Math::sin(n),Math::cos(n), 0 )*cs;
+ Vector3 from = Vector3(-Math::sin(s), Math::cos(s), 0) * cs;
+ Vector3 to = Vector3(-Math::sin(n), Math::cos(n), 0) * cs;
- if (i==points-1) {
+ if (i == points - 1) {
cursor_points.push_back(to);
cursor_points.push_back(Vector3());
}
- if (i==0) {
+ if (i == 0) {
cursor_points.push_back(from);
cursor_points.push_back(Vector3());
}
-
cursor_points.push_back(from);
cursor_points.push_back(to);
-
-
}
- cursor_points.push_back(Vector3(0,cs*1.5,0));
+ cursor_points.push_back(Vector3(0, cs * 1.5, 0));
cursor_points.push_back(Vector3());
} else {
-
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(Math_PI*2.0)/points;
- float n = ll+(i+1)*(Math_PI*2.0)/points;
+ float s = ll + i * (Math_PI * 2.0) / points;
+ float n = ll + (i + 1) * (Math_PI * 2.0) / points;
- Vector3 from=Vector3( -Math::sin(s),Math::cos(s), 0 )*cs;
- Vector3 to=Vector3( -Math::sin(n),Math::cos(n), 0 )*cs;
+ Vector3 from = Vector3(-Math::sin(s), Math::cos(s), 0) * cs;
+ Vector3 to = Vector3(-Math::sin(n), Math::cos(n), 0) * cs;
cursor_points.push_back(from);
cursor_points.push_back(to);
-
}
-
}
add_collision_segments(cursor_points);
- add_lines(cursor_points,SpatialEditorGizmos::singleton->joint_material);
-
+ add_lines(cursor_points, SpatialEditorGizmos::singleton->joint_material);
}
+HingeJointSpatialGizmo::HingeJointSpatialGizmo(HingeJoint *p_p3d) {
-HingeJointSpatialGizmo::HingeJointSpatialGizmo(HingeJoint* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
@@ -2725,105 +2512,94 @@ void SliderJointSpatialGizmo::redraw() {
cursor_points.push_back(Vector3(-cs,0,0));
cursor_points.push_back(Vector3(0,+cs,0));
cursor_points.push_back(Vector3(0,-cs,0));*/
- cursor_points.push_back(Vector3(0,0,+cs*2));
- cursor_points.push_back(Vector3(0,0,-cs*2));
+ cursor_points.push_back(Vector3(0, 0, +cs * 2));
+ cursor_points.push_back(Vector3(0, 0, -cs * 2));
float ll = p3d->get_param(SliderJoint::PARAM_ANGULAR_LIMIT_LOWER);
float ul = p3d->get_param(SliderJoint::PARAM_ANGULAR_LIMIT_UPPER);
float lll = -p3d->get_param(SliderJoint::PARAM_LINEAR_LIMIT_LOWER);
float lul = -p3d->get_param(SliderJoint::PARAM_LINEAR_LIMIT_UPPER);
- if (lll>lul) {
-
- cursor_points.push_back(Vector3(lul,0,0));
- cursor_points.push_back(Vector3(lll,0,0));
-
- cursor_points.push_back(Vector3(lul,-cs,-cs));
- cursor_points.push_back(Vector3(lul,-cs,cs));
- cursor_points.push_back(Vector3(lul,-cs,cs));
- cursor_points.push_back(Vector3(lul,cs,cs));
- cursor_points.push_back(Vector3(lul,cs,cs));
- cursor_points.push_back(Vector3(lul,cs,-cs));
- cursor_points.push_back(Vector3(lul,cs,-cs));
- cursor_points.push_back(Vector3(lul,-cs,-cs));
-
-
- cursor_points.push_back(Vector3(lll,-cs,-cs));
- cursor_points.push_back(Vector3(lll,-cs,cs));
- cursor_points.push_back(Vector3(lll,-cs,cs));
- cursor_points.push_back(Vector3(lll,cs,cs));
- cursor_points.push_back(Vector3(lll,cs,cs));
- cursor_points.push_back(Vector3(lll,cs,-cs));
- cursor_points.push_back(Vector3(lll,cs,-cs));
- cursor_points.push_back(Vector3(lll,-cs,-cs));
-
+ if (lll > lul) {
+
+ cursor_points.push_back(Vector3(lul, 0, 0));
+ cursor_points.push_back(Vector3(lll, 0, 0));
+
+ cursor_points.push_back(Vector3(lul, -cs, -cs));
+ cursor_points.push_back(Vector3(lul, -cs, cs));
+ cursor_points.push_back(Vector3(lul, -cs, cs));
+ cursor_points.push_back(Vector3(lul, cs, cs));
+ cursor_points.push_back(Vector3(lul, cs, cs));
+ cursor_points.push_back(Vector3(lul, cs, -cs));
+ cursor_points.push_back(Vector3(lul, cs, -cs));
+ cursor_points.push_back(Vector3(lul, -cs, -cs));
+
+ cursor_points.push_back(Vector3(lll, -cs, -cs));
+ cursor_points.push_back(Vector3(lll, -cs, cs));
+ cursor_points.push_back(Vector3(lll, -cs, cs));
+ cursor_points.push_back(Vector3(lll, cs, cs));
+ cursor_points.push_back(Vector3(lll, cs, cs));
+ cursor_points.push_back(Vector3(lll, cs, -cs));
+ cursor_points.push_back(Vector3(lll, cs, -cs));
+ cursor_points.push_back(Vector3(lll, -cs, -cs));
} else {
- cursor_points.push_back(Vector3(+cs*2,0,0));
- cursor_points.push_back(Vector3(-cs*2,0,0));
-
+ cursor_points.push_back(Vector3(+cs * 2, 0, 0));
+ cursor_points.push_back(Vector3(-cs * 2, 0, 0));
}
- if (ll<ul) {
+ if (ll < ul) {
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(ul-ll)/points;
- float n = ll+(i+1)*(ul-ll)/points;
+ float s = ll + i * (ul - ll) / points;
+ float n = ll + (i + 1) * (ul - ll) / points;
- Vector3 from=Vector3(0, Math::cos(s), -Math::sin(s) )*cs;
- Vector3 to=Vector3(0,Math::cos(n), -Math::sin(n) )*cs;
+ Vector3 from = Vector3(0, Math::cos(s), -Math::sin(s)) * cs;
+ Vector3 to = Vector3(0, Math::cos(n), -Math::sin(n)) * cs;
- if (i==points-1) {
+ if (i == points - 1) {
cursor_points.push_back(to);
cursor_points.push_back(Vector3());
}
- if (i==0) {
+ if (i == 0) {
cursor_points.push_back(from);
cursor_points.push_back(Vector3());
}
-
cursor_points.push_back(from);
cursor_points.push_back(to);
-
-
}
- cursor_points.push_back(Vector3(0,cs*1.5,0));
+ cursor_points.push_back(Vector3(0, cs * 1.5, 0));
cursor_points.push_back(Vector3());
} else {
-
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(Math_PI*2.0)/points;
- float n = ll+(i+1)*(Math_PI*2.0)/points;
+ float s = ll + i * (Math_PI * 2.0) / points;
+ float n = ll + (i + 1) * (Math_PI * 2.0) / points;
- Vector3 from=Vector3(0,Math::cos(s),-Math::sin(s) )*cs;
- Vector3 to=Vector3( 0,Math::cos(n),-Math::sin(n) )*cs;
+ Vector3 from = Vector3(0, Math::cos(s), -Math::sin(s)) * cs;
+ Vector3 to = Vector3(0, Math::cos(n), -Math::sin(n)) * cs;
cursor_points.push_back(from);
cursor_points.push_back(to);
-
}
-
}
add_collision_segments(cursor_points);
- add_lines(cursor_points,SpatialEditorGizmos::singleton->joint_material);
-
+ add_lines(cursor_points, SpatialEditorGizmos::singleton->joint_material);
}
+SliderJointSpatialGizmo::SliderJointSpatialGizmo(SliderJoint *p_p3d) {
-SliderJointSpatialGizmo::SliderJointSpatialGizmo(SliderJoint* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
@@ -2837,72 +2613,65 @@ void ConeTwistJointSpatialGizmo::redraw() {
Vector<Vector3> points;
float r = 1.0;
- float w = r*Math::sin(p3d->get_param(ConeTwistJoint::PARAM_SWING_SPAN));
- float d = r*Math::cos(p3d->get_param(ConeTwistJoint::PARAM_SWING_SPAN));
-
+ float w = r * Math::sin(p3d->get_param(ConeTwistJoint::PARAM_SWING_SPAN));
+ float d = r * Math::cos(p3d->get_param(ConeTwistJoint::PARAM_SWING_SPAN));
//swing
- for(int i=0;i<360;i+=10) {
+ for (int i = 0; i < 360; i += 10) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+10);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*w;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*w;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 10);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * w;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * w;
/*points.push_back(Vector3(a.x,0,a.y));
points.push_back(Vector3(b.x,0,b.y));
points.push_back(Vector3(0,a.x,a.y));
points.push_back(Vector3(0,b.x,b.y));*/
- points.push_back(Vector3(d,a.x,a.y));
- points.push_back(Vector3(d,b.x,b.y));
+ points.push_back(Vector3(d, a.x, a.y));
+ points.push_back(Vector3(d, b.x, b.y));
- if (i%90==0) {
+ if (i % 90 == 0) {
- points.push_back(Vector3(d,a.x,a.y));
+ points.push_back(Vector3(d, a.x, a.y));
points.push_back(Vector3());
-
}
}
points.push_back(Vector3());
- points.push_back(Vector3(1,0,0));
+ points.push_back(Vector3(1, 0, 0));
//twist
/*
*/
- float ts=Math::rad2deg(p3d->get_param(ConeTwistJoint::PARAM_TWIST_SPAN));
- ts=MIN(ts,720);
-
+ float ts = Math::rad2deg(p3d->get_param(ConeTwistJoint::PARAM_TWIST_SPAN));
+ ts = MIN(ts, 720);
- for(int i=0;i<int(ts);i+=5) {
+ for (int i = 0; i < int(ts); i += 5) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+5);
- float c = i/720.0;
- float cn = (i+5)/720.0;
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*w*c;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*w*cn;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 5);
+ float c = i / 720.0;
+ float cn = (i + 5) / 720.0;
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * w * c;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * w * cn;
/*points.push_back(Vector3(a.x,0,a.y));
points.push_back(Vector3(b.x,0,b.y));
points.push_back(Vector3(0,a.x,a.y));
points.push_back(Vector3(0,b.x,b.y));*/
- points.push_back(Vector3(c,a.x,a.y));
- points.push_back(Vector3(cn,b.x,b.y));
-
+ points.push_back(Vector3(c, a.x, a.y));
+ points.push_back(Vector3(cn, b.x, b.y));
}
-
add_collision_segments(points);
- add_lines(points,SpatialEditorGizmos::singleton->joint_material);
-
+ add_lines(points, SpatialEditorGizmos::singleton->joint_material);
}
+ConeTwistJointSpatialGizmo::ConeTwistJointSpatialGizmo(ConeTwistJoint *p_p3d) {
-ConeTwistJointSpatialGizmo::ConeTwistJointSpatialGizmo(ConeTwistJoint* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
@@ -2919,7 +2688,7 @@ void Generic6DOFJointSpatialGizmo::redraw() {
Vector<Vector3> cursor_points;
float cs = 0.25;
- for(int ax=0;ax<3;ax++) {
+ for (int ax = 0; ax < 3; ax++) {
/*cursor_points.push_back(Vector3(+cs,0,0));
cursor_points.push_back(Vector3(-cs,0,0));
cursor_points.push_back(Vector3(0,+cs,0));
@@ -2932,11 +2701,11 @@ void Generic6DOFJointSpatialGizmo::redraw() {
float lll;
float lul;
- int a1,a2,a3;
+ int a1, a2, a3;
bool enable_ang;
bool enable_lin;
- switch(ax) {
+ switch (ax) {
case 0:
ll = p3d->get_param_x(Generic6DOFJoint::PARAM_ANGULAR_LOWER_LIMIT);
ul = p3d->get_param_x(Generic6DOFJoint::PARAM_ANGULAR_UPPER_LIMIT);
@@ -2944,10 +2713,10 @@ void Generic6DOFJointSpatialGizmo::redraw() {
lul = -p3d->get_param_x(Generic6DOFJoint::PARAM_LINEAR_UPPER_LIMIT);
enable_ang = p3d->get_flag_x(Generic6DOFJoint::FLAG_ENABLE_ANGULAR_LIMIT);
enable_lin = p3d->get_flag_x(Generic6DOFJoint::FLAG_ENABLE_LINEAR_LIMIT);
- a1=0;
- a2=1;
- a3=2;
- break;
+ a1 = 0;
+ a2 = 1;
+ a3 = 2;
+ break;
case 1:
ll = p3d->get_param_y(Generic6DOFJoint::PARAM_ANGULAR_LOWER_LIMIT);
ul = p3d->get_param_y(Generic6DOFJoint::PARAM_ANGULAR_UPPER_LIMIT);
@@ -2955,10 +2724,10 @@ void Generic6DOFJointSpatialGizmo::redraw() {
lul = -p3d->get_param_y(Generic6DOFJoint::PARAM_LINEAR_UPPER_LIMIT);
enable_ang = p3d->get_flag_y(Generic6DOFJoint::FLAG_ENABLE_ANGULAR_LIMIT);
enable_lin = p3d->get_flag_y(Generic6DOFJoint::FLAG_ENABLE_LINEAR_LIMIT);
- a1=2;
- a2=0;
- a3=1;
- break;
+ a1 = 2;
+ a2 = 0;
+ a3 = 1;
+ break;
case 2:
ll = p3d->get_param_z(Generic6DOFJoint::PARAM_ANGULAR_LOWER_LIMIT);
ul = p3d->get_param_z(Generic6DOFJoint::PARAM_ANGULAR_UPPER_LIMIT);
@@ -2967,125 +2736,113 @@ void Generic6DOFJointSpatialGizmo::redraw() {
enable_ang = p3d->get_flag_z(Generic6DOFJoint::FLAG_ENABLE_ANGULAR_LIMIT);
enable_lin = p3d->get_flag_z(Generic6DOFJoint::FLAG_ENABLE_LINEAR_LIMIT);
- a1=1;
- a2=2;
- a3=0;
- break;
- }
-
-#define ADD_VTX(x,y,z)\
- {\
- Vector3 v;\
- v[a1]=(x);\
- v[a2]=(y);\
- v[a3]=(z);\
- cursor_points.push_back(v);\
- }
-
-#define SET_VTX(what,x,y,z)\
- {\
- Vector3 v;\
- v[a1]=(x);\
- v[a2]=(y);\
- v[a3]=(z);\
- what=v;\
+ a1 = 1;
+ a2 = 2;
+ a3 = 0;
+ break;
}
-
-
-
- if (enable_lin && lll>=lul) {
-
- ADD_VTX(lul,0,0);
- ADD_VTX(lll,0,0);
-
- ADD_VTX(lul,-cs,-cs);
- ADD_VTX(lul,-cs,cs);
- ADD_VTX(lul,-cs,cs);
- ADD_VTX(lul,cs,cs);
- ADD_VTX(lul,cs,cs);
- ADD_VTX(lul,cs,-cs);
- ADD_VTX(lul,cs,-cs);
- ADD_VTX(lul,-cs,-cs);
-
-
- ADD_VTX(lll,-cs,-cs);
- ADD_VTX(lll,-cs,cs);
- ADD_VTX(lll,-cs,cs);
- ADD_VTX(lll,cs,cs);
- ADD_VTX(lll,cs,cs);
- ADD_VTX(lll,cs,-cs);
- ADD_VTX(lll,cs,-cs);
- ADD_VTX(lll,-cs,-cs);
-
+#define ADD_VTX(x, y, z) \
+ { \
+ Vector3 v; \
+ v[a1] = (x); \
+ v[a2] = (y); \
+ v[a3] = (z); \
+ cursor_points.push_back(v); \
+ }
+
+#define SET_VTX(what, x, y, z) \
+ { \
+ Vector3 v; \
+ v[a1] = (x); \
+ v[a2] = (y); \
+ v[a3] = (z); \
+ what = v; \
+ }
+
+ if (enable_lin && lll >= lul) {
+
+ ADD_VTX(lul, 0, 0);
+ ADD_VTX(lll, 0, 0);
+
+ ADD_VTX(lul, -cs, -cs);
+ ADD_VTX(lul, -cs, cs);
+ ADD_VTX(lul, -cs, cs);
+ ADD_VTX(lul, cs, cs);
+ ADD_VTX(lul, cs, cs);
+ ADD_VTX(lul, cs, -cs);
+ ADD_VTX(lul, cs, -cs);
+ ADD_VTX(lul, -cs, -cs);
+
+ ADD_VTX(lll, -cs, -cs);
+ ADD_VTX(lll, -cs, cs);
+ ADD_VTX(lll, -cs, cs);
+ ADD_VTX(lll, cs, cs);
+ ADD_VTX(lll, cs, cs);
+ ADD_VTX(lll, cs, -cs);
+ ADD_VTX(lll, cs, -cs);
+ ADD_VTX(lll, -cs, -cs);
} else {
- ADD_VTX(+cs*2,0,0);
- ADD_VTX(-cs*2,0,0);
-
+ ADD_VTX(+cs * 2, 0, 0);
+ ADD_VTX(-cs * 2, 0, 0);
}
- if (enable_ang && ll<=ul) {
+ if (enable_ang && ll <= ul) {
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(ul-ll)/points;
- float n = ll+(i+1)*(ul-ll)/points;
+ float s = ll + i * (ul - ll) / points;
+ float n = ll + (i + 1) * (ul - ll) / points;
Vector3 from;
- SET_VTX(from,0, Math::cos(s), -Math::sin(s) );
- from*=cs;
+ SET_VTX(from, 0, Math::cos(s), -Math::sin(s));
+ from *= cs;
Vector3 to;
- SET_VTX(to,0,Math::cos(n), -Math::sin(n));
- to*=cs;
+ SET_VTX(to, 0, Math::cos(n), -Math::sin(n));
+ to *= cs;
- if (i==points-1) {
+ if (i == points - 1) {
cursor_points.push_back(to);
cursor_points.push_back(Vector3());
}
- if (i==0) {
+ if (i == 0) {
cursor_points.push_back(from);
cursor_points.push_back(Vector3());
}
-
cursor_points.push_back(from);
cursor_points.push_back(to);
-
-
}
- ADD_VTX(0,cs*1.5,0);
+ ADD_VTX(0, cs * 1.5, 0);
cursor_points.push_back(Vector3());
} else {
-
const int points = 32;
- for(int i=0;i<points;i++) {
+ for (int i = 0; i < points; i++) {
- float s = ll+i*(Math_PI*2.0)/points;
- float n = ll+(i+1)*(Math_PI*2.0)/points;
+ float s = ll + i * (Math_PI * 2.0) / points;
+ float n = ll + (i + 1) * (Math_PI * 2.0) / points;
//Vector3 from=Vector3(0,Math::cos(s),-Math::sin(s) )*cs;
//Vector3 to=Vector3( 0,Math::cos(n),-Math::sin(n) )*cs;
Vector3 from;
- SET_VTX(from,0, Math::cos(s), -Math::sin(s) );
- from*=cs;
+ SET_VTX(from, 0, Math::cos(s), -Math::sin(s));
+ from *= cs;
Vector3 to;
- SET_VTX(to,0,Math::cos(n), -Math::sin(n));
- to*=cs;
+ SET_VTX(to, 0, Math::cos(n), -Math::sin(n));
+ to *= cs;
cursor_points.push_back(from);
cursor_points.push_back(to);
-
}
-
}
}
@@ -3093,14 +2850,12 @@ void Generic6DOFJointSpatialGizmo::redraw() {
#undef SET_VTX
add_collision_segments(cursor_points);
- add_lines(cursor_points,SpatialEditorGizmos::singleton->joint_material);
-
+ add_lines(cursor_points, SpatialEditorGizmos::singleton->joint_material);
}
+Generic6DOFJointSpatialGizmo::Generic6DOFJointSpatialGizmo(Generic6DOFJoint *p_p3d) {
-Generic6DOFJointSpatialGizmo::Generic6DOFJointSpatialGizmo(Generic6DOFJoint* p_p3d) {
-
- p3d=p_p3d;
+ p3d = p_p3d;
set_spatial_node(p3d);
}
@@ -3108,147 +2863,140 @@ Generic6DOFJointSpatialGizmo::Generic6DOFJointSpatialGizmo(Generic6DOFJoint* p_p
///
////
-
-SpatialEditorGizmos *SpatialEditorGizmos::singleton=NULL;
+SpatialEditorGizmos *SpatialEditorGizmos::singleton = NULL;
Ref<SpatialEditorGizmo> SpatialEditorGizmos::get_gizmo(Spatial *p_spatial) {
if (p_spatial->cast_to<Light>()) {
- Ref<LightSpatialGizmo> lsg = memnew( LightSpatialGizmo(p_spatial->cast_to<Light>()) );
+ Ref<LightSpatialGizmo> lsg = memnew(LightSpatialGizmo(p_spatial->cast_to<Light>()));
return lsg;
}
-
-
if (p_spatial->cast_to<Camera>()) {
- Ref<CameraSpatialGizmo> lsg = memnew( CameraSpatialGizmo(p_spatial->cast_to<Camera>()) );
+ Ref<CameraSpatialGizmo> lsg = memnew(CameraSpatialGizmo(p_spatial->cast_to<Camera>()));
return lsg;
}
if (p_spatial->cast_to<Skeleton>()) {
- Ref<SkeletonSpatialGizmo> lsg = memnew( SkeletonSpatialGizmo(p_spatial->cast_to<Skeleton>()) );
+ Ref<SkeletonSpatialGizmo> lsg = memnew(SkeletonSpatialGizmo(p_spatial->cast_to<Skeleton>()));
return lsg;
}
-
if (p_spatial->cast_to<Position3D>()) {
- Ref<Position3DSpatialGizmo> lsg = memnew( Position3DSpatialGizmo(p_spatial->cast_to<Position3D>()) );
+ Ref<Position3DSpatialGizmo> lsg = memnew(Position3DSpatialGizmo(p_spatial->cast_to<Position3D>()));
return lsg;
}
if (p_spatial->cast_to<MeshInstance>()) {
- Ref<MeshInstanceSpatialGizmo> misg = memnew( MeshInstanceSpatialGizmo(p_spatial->cast_to<MeshInstance>()) );
+ Ref<MeshInstanceSpatialGizmo> misg = memnew(MeshInstanceSpatialGizmo(p_spatial->cast_to<MeshInstance>()));
return misg;
}
if (p_spatial->cast_to<Room>()) {
- Ref<RoomSpatialGizmo> misg = memnew( RoomSpatialGizmo(p_spatial->cast_to<Room>()) );
+ Ref<RoomSpatialGizmo> misg = memnew(RoomSpatialGizmo(p_spatial->cast_to<Room>()));
return misg;
}
if (p_spatial->cast_to<NavigationMeshInstance>()) {
- Ref<NavigationMeshSpatialGizmo> misg = memnew( NavigationMeshSpatialGizmo(p_spatial->cast_to<NavigationMeshInstance>()) );
+ Ref<NavigationMeshSpatialGizmo> misg = memnew(NavigationMeshSpatialGizmo(p_spatial->cast_to<NavigationMeshInstance>()));
return misg;
}
if (p_spatial->cast_to<RayCast>()) {
- Ref<RayCastSpatialGizmo> misg = memnew( RayCastSpatialGizmo(p_spatial->cast_to<RayCast>()) );
+ Ref<RayCastSpatialGizmo> misg = memnew(RayCastSpatialGizmo(p_spatial->cast_to<RayCast>()));
return misg;
}
if (p_spatial->cast_to<Portal>()) {
- Ref<PortalSpatialGizmo> misg = memnew( PortalSpatialGizmo(p_spatial->cast_to<Portal>()) );
+ Ref<PortalSpatialGizmo> misg = memnew(PortalSpatialGizmo(p_spatial->cast_to<Portal>()));
return misg;
}
-
if (p_spatial->cast_to<TestCube>()) {
- Ref<TestCubeSpatialGizmo> misg = memnew( TestCubeSpatialGizmo(p_spatial->cast_to<TestCube>()) );
+ Ref<TestCubeSpatialGizmo> misg = memnew(TestCubeSpatialGizmo(p_spatial->cast_to<TestCube>()));
return misg;
}
if (p_spatial->cast_to<CollisionShape>()) {
- Ref<CollisionShapeSpatialGizmo> misg = memnew( CollisionShapeSpatialGizmo(p_spatial->cast_to<CollisionShape>()) );
+ Ref<CollisionShapeSpatialGizmo> misg = memnew(CollisionShapeSpatialGizmo(p_spatial->cast_to<CollisionShape>()));
return misg;
}
if (p_spatial->cast_to<VisibilityNotifier>()) {
- Ref<VisibilityNotifierGizmo> misg = memnew( VisibilityNotifierGizmo(p_spatial->cast_to<VisibilityNotifier>()) );
+ Ref<VisibilityNotifierGizmo> misg = memnew(VisibilityNotifierGizmo(p_spatial->cast_to<VisibilityNotifier>()));
return misg;
}
if (p_spatial->cast_to<ReflectionProbe>()) {
- Ref<ReflectionProbeGizmo> misg = memnew( ReflectionProbeGizmo(p_spatial->cast_to<ReflectionProbe>()) );
+ Ref<ReflectionProbeGizmo> misg = memnew(ReflectionProbeGizmo(p_spatial->cast_to<ReflectionProbe>()));
return misg;
}
if (p_spatial->cast_to<GIProbe>()) {
- Ref<GIProbeGizmo> misg = memnew( GIProbeGizmo(p_spatial->cast_to<GIProbe>()) );
+ Ref<GIProbeGizmo> misg = memnew(GIProbeGizmo(p_spatial->cast_to<GIProbe>()));
return misg;
}
if (p_spatial->cast_to<VehicleWheel>()) {
- Ref<VehicleWheelSpatialGizmo> misg = memnew( VehicleWheelSpatialGizmo(p_spatial->cast_to<VehicleWheel>()) );
+ Ref<VehicleWheelSpatialGizmo> misg = memnew(VehicleWheelSpatialGizmo(p_spatial->cast_to<VehicleWheel>()));
return misg;
}
if (p_spatial->cast_to<PinJoint>()) {
- Ref<PinJointSpatialGizmo> misg = memnew( PinJointSpatialGizmo(p_spatial->cast_to<PinJoint>()) );
+ Ref<PinJointSpatialGizmo> misg = memnew(PinJointSpatialGizmo(p_spatial->cast_to<PinJoint>()));
return misg;
}
if (p_spatial->cast_to<HingeJoint>()) {
- Ref<HingeJointSpatialGizmo> misg = memnew( HingeJointSpatialGizmo(p_spatial->cast_to<HingeJoint>()) );
+ Ref<HingeJointSpatialGizmo> misg = memnew(HingeJointSpatialGizmo(p_spatial->cast_to<HingeJoint>()));
return misg;
}
if (p_spatial->cast_to<SliderJoint>()) {
- Ref<SliderJointSpatialGizmo> misg = memnew( SliderJointSpatialGizmo(p_spatial->cast_to<SliderJoint>()) );
+ Ref<SliderJointSpatialGizmo> misg = memnew(SliderJointSpatialGizmo(p_spatial->cast_to<SliderJoint>()));
return misg;
}
if (p_spatial->cast_to<ConeTwistJoint>()) {
- Ref<ConeTwistJointSpatialGizmo> misg = memnew( ConeTwistJointSpatialGizmo(p_spatial->cast_to<ConeTwistJoint>()) );
+ Ref<ConeTwistJointSpatialGizmo> misg = memnew(ConeTwistJointSpatialGizmo(p_spatial->cast_to<ConeTwistJoint>()));
return misg;
}
if (p_spatial->cast_to<Generic6DOFJoint>()) {
- Ref<Generic6DOFJointSpatialGizmo> misg = memnew( Generic6DOFJointSpatialGizmo(p_spatial->cast_to<Generic6DOFJoint>()) );
+ Ref<Generic6DOFJointSpatialGizmo> misg = memnew(Generic6DOFJointSpatialGizmo(p_spatial->cast_to<Generic6DOFJoint>()));
return misg;
}
if (p_spatial->cast_to<CollisionPolygon>()) {
- Ref<CollisionPolygonSpatialGizmo> misg = memnew( CollisionPolygonSpatialGizmo(p_spatial->cast_to<CollisionPolygon>()) );
+ Ref<CollisionPolygonSpatialGizmo> misg = memnew(CollisionPolygonSpatialGizmo(p_spatial->cast_to<CollisionPolygon>()));
return misg;
}
-
return Ref<SpatialEditorGizmo>();
}
+Ref<FixedSpatialMaterial> SpatialEditorGizmos::create_line_material(const Color &p_base_color) {
-Ref<FixedSpatialMaterial> SpatialEditorGizmos::create_line_material(const Color& p_base_color) {
-
- Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
line_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
line_material->set_line_width(3.0);
line_material->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
@@ -3257,112 +3005,108 @@ Ref<FixedSpatialMaterial> SpatialEditorGizmos::create_line_material(const Color&
line_material->set_albedo(p_base_color);
return line_material;
-
}
-Ref<FixedSpatialMaterial> SpatialEditorGizmos::create_solid_material(const Color& p_base_color) {
+Ref<FixedSpatialMaterial> SpatialEditorGizmos::create_solid_material(const Color &p_base_color) {
- Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
line_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
line_material->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
line_material->set_albedo(p_base_color);
return line_material;
-
}
SpatialEditorGizmos::SpatialEditorGizmos() {
- singleton=this;
+ singleton = this;
- handle_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ handle_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
handle_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
- handle_material->set_albedo(Color(0.8,0.8,0.8));
+ handle_material->set_albedo(Color(0.8, 0.8, 0.8));
- handle2_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ handle2_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
handle2_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
handle2_material->set_flag(FixedSpatialMaterial::FLAG_USE_POINT_SIZE, true);
- handle_t = SpatialEditor::get_singleton()->get_icon("Editor3DHandle","EditorIcons");
+ handle_t = SpatialEditor::get_singleton()->get_icon("Editor3DHandle", "EditorIcons");
handle2_material->set_point_size(handle_t->get_width());
- handle2_material->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,handle_t);
- handle2_material->set_albedo(Color(1,1,1));
+ handle2_material->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, handle_t);
+ handle2_material->set_albedo(Color(1, 1, 1));
handle2_material->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
handle2_material->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
handle2_material->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
- light_material = create_line_material(Color(1,1,0.2));
+ light_material = create_line_material(Color(1, 1, 0.2));
- light_material_omni_icon = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ light_material_omni_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
light_material_omni_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
light_material_omni_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
light_material_omni_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
light_material_omni_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- light_material_omni_icon->set_albedo(Color(1,1,1,0.9));
- light_material_omni_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,SpatialEditor::get_singleton()->get_icon("GizmoLight","EditorIcons"));
-
+ light_material_omni_icon->set_albedo(Color(1, 1, 1, 0.9));
+ light_material_omni_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("GizmoLight", "EditorIcons"));
- light_material_directional_icon = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ light_material_directional_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
light_material_directional_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
light_material_directional_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
light_material_directional_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
light_material_directional_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- light_material_directional_icon->set_albedo(Color(1,1,1,0.9));
- light_material_directional_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,SpatialEditor::get_singleton()->get_icon("GizmoDirectionalLight","EditorIcons"));
+ light_material_directional_icon->set_albedo(Color(1, 1, 1, 0.9));
+ light_material_directional_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("GizmoDirectionalLight", "EditorIcons"));
- camera_material = create_line_material(Color(1.0,0.5,1.0));
+ camera_material = create_line_material(Color(1.0, 0.5, 1.0));
-
- navmesh_edge_material = create_line_material(Color(0.1,0.8,1.0));
- navmesh_solid_material = create_solid_material(Color(0.1,0.8,1.0,0.4));
+ navmesh_edge_material = create_line_material(Color(0.1, 0.8, 1.0));
+ navmesh_solid_material = create_solid_material(Color(0.1, 0.8, 1.0, 0.4));
navmesh_edge_material->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, false);
navmesh_edge_material->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, false);
navmesh_solid_material->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
- navmesh_edge_material_disabled = create_line_material(Color(1.0,0.8,0.1));
- navmesh_solid_material_disabled = create_solid_material(Color(1.0,0.8,0.1,0.4));
+ navmesh_edge_material_disabled = create_line_material(Color(1.0, 0.8, 0.1));
+ navmesh_solid_material_disabled = create_solid_material(Color(1.0, 0.8, 0.1, 0.4));
navmesh_edge_material_disabled->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, false);
navmesh_edge_material_disabled->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, false);
navmesh_solid_material_disabled->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
- skeleton_material = create_line_material(Color(0.6,1.0,0.3));
+ skeleton_material = create_line_material(Color(0.6, 1.0, 0.3));
skeleton_material->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
- skeleton_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- skeleton_material->set_flag(FixedSpatialMaterial::FLAG_ONTOP,true);
+ skeleton_material->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ skeleton_material->set_flag(FixedSpatialMaterial::FLAG_ONTOP, true);
skeleton_material->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
//position 3D Shared mesh
- pos3d_mesh = Ref<Mesh>( memnew( Mesh ) );
+ pos3d_mesh = Ref<Mesh>(memnew(Mesh));
{
PoolVector<Vector3> cursor_points;
PoolVector<Color> cursor_colors;
float cs = 0.25;
- cursor_points.push_back(Vector3(+cs,0,0));
- cursor_points.push_back(Vector3(-cs,0,0));
- cursor_points.push_back(Vector3(0,+cs,0));
- cursor_points.push_back(Vector3(0,-cs,0));
- cursor_points.push_back(Vector3(0,0,+cs));
- cursor_points.push_back(Vector3(0,0,-cs));
- cursor_colors.push_back(Color(1,0.5,0.5,0.7));
- cursor_colors.push_back(Color(1,0.5,0.5,0.7));
- cursor_colors.push_back(Color(0.5,1,0.5,0.7));
- cursor_colors.push_back(Color(0.5,1,0.5,0.7));
- cursor_colors.push_back(Color(0.5,0.5,1,0.7));
- cursor_colors.push_back(Color(0.5,0.5,1,0.7));
-
- Ref<FixedSpatialMaterial> mat = memnew( FixedSpatialMaterial );
- mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
- mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
+ cursor_points.push_back(Vector3(+cs, 0, 0));
+ cursor_points.push_back(Vector3(-cs, 0, 0));
+ cursor_points.push_back(Vector3(0, +cs, 0));
+ cursor_points.push_back(Vector3(0, -cs, 0));
+ cursor_points.push_back(Vector3(0, 0, +cs));
+ cursor_points.push_back(Vector3(0, 0, -cs));
+ cursor_colors.push_back(Color(1, 0.5, 0.5, 0.7));
+ cursor_colors.push_back(Color(1, 0.5, 0.5, 0.7));
+ cursor_colors.push_back(Color(0.5, 1, 0.5, 0.7));
+ cursor_colors.push_back(Color(0.5, 1, 0.5, 0.7));
+ cursor_colors.push_back(Color(0.5, 0.5, 1, 0.7));
+ cursor_colors.push_back(Color(0.5, 0.5, 1, 0.7));
+
+ Ref<FixedSpatialMaterial> mat = memnew(FixedSpatialMaterial);
+ mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
+ mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
mat->set_line_width(3);
Array d;
d.resize(VS::ARRAY_MAX);
- d[Mesh::ARRAY_VERTEX]=cursor_points;
- d[Mesh::ARRAY_COLOR]=cursor_colors;
- pos3d_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,d);
- pos3d_mesh->surface_set_material(0,mat);
+ d[Mesh::ARRAY_VERTEX] = cursor_points;
+ d[Mesh::ARRAY_COLOR] = cursor_colors;
+ pos3d_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, d);
+ pos3d_mesh->surface_set_material(0, mat);
}
listener_line_mesh = Ref<Mesh>(memnew(Mesh));
@@ -3389,48 +3133,47 @@ SpatialEditorGizmos::SpatialEditorGizmos() {
listener_line_mesh->surface_set_material(0, mat);
}
-
- sample_player_icon = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ sample_player_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
sample_player_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
sample_player_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
sample_player_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
sample_player_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- sample_player_icon->set_albedo(Color(1,1,1,0.9));
- sample_player_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,SpatialEditor::get_singleton()->get_icon("GizmoSpatialSamplePlayer","EditorIcons"));
-
- room_material = create_line_material(Color(1.0,0.6,0.9));
- portal_material = create_line_material(Color(1.0,0.8,0.6));
- raycast_material = create_line_material(Color(1.0,0.8,0.6));
- car_wheel_material = create_line_material(Color(0.6,0.8,1.0));
- visibility_notifier_material = create_line_material(Color(1.0,0.5,1.0));
- reflection_probe_material = create_line_material(Color(0.5,1.0,0.7));
- reflection_probe_material_internal = create_line_material(Color(0.3,0.8,0.5,0.15));
- gi_probe_material = create_line_material(Color(0.7,1.0,0.5));
- gi_probe_material_internal = create_line_material(Color(0.5,0.8,0.3,0.1));
- joint_material = create_line_material(Color(0.6,0.8,1.0));
-
- stream_player_icon = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ sample_player_icon->set_albedo(Color(1, 1, 1, 0.9));
+ sample_player_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("GizmoSpatialSamplePlayer", "EditorIcons"));
+
+ room_material = create_line_material(Color(1.0, 0.6, 0.9));
+ portal_material = create_line_material(Color(1.0, 0.8, 0.6));
+ raycast_material = create_line_material(Color(1.0, 0.8, 0.6));
+ car_wheel_material = create_line_material(Color(0.6, 0.8, 1.0));
+ visibility_notifier_material = create_line_material(Color(1.0, 0.5, 1.0));
+ reflection_probe_material = create_line_material(Color(0.5, 1.0, 0.7));
+ reflection_probe_material_internal = create_line_material(Color(0.3, 0.8, 0.5, 0.15));
+ gi_probe_material = create_line_material(Color(0.7, 1.0, 0.5));
+ gi_probe_material_internal = create_line_material(Color(0.5, 0.8, 0.3, 0.1));
+ joint_material = create_line_material(Color(0.6, 0.8, 1.0));
+
+ stream_player_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
stream_player_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
stream_player_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
stream_player_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
stream_player_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- stream_player_icon->set_albedo(Color(1,1,1,0.9));
- stream_player_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,SpatialEditor::get_singleton()->get_icon("GizmoSpatialStreamPlayer","EditorIcons"));
+ stream_player_icon->set_albedo(Color(1, 1, 1, 0.9));
+ stream_player_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("GizmoSpatialStreamPlayer", "EditorIcons"));
- visibility_notifier_icon = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ visibility_notifier_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
visibility_notifier_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
visibility_notifier_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
visibility_notifier_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
visibility_notifier_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- visibility_notifier_icon->set_albedo(Color(1,1,1,0.9));
- visibility_notifier_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO,SpatialEditor::get_singleton()->get_icon("Visible","EditorIcons"));
+ visibility_notifier_icon->set_albedo(Color(1, 1, 1, 0.9));
+ visibility_notifier_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("Visible", "EditorIcons"));
listener_icon = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
listener_icon->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
listener_icon->set_cull_mode(FixedSpatialMaterial::CULL_DISABLED);
listener_icon->set_depth_draw_mode(FixedSpatialMaterial::DEPTH_DRAW_DISABLED);
listener_icon->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- listener_icon->set_albedo( Color(1, 1, 1, 0.9));
+ listener_icon->set_albedo(Color(1, 1, 1, 0.9));
listener_icon->set_texture(FixedSpatialMaterial::TEXTURE_ALBEDO, SpatialEditor::get_singleton()->get_icon("GizmoListener", "EditorIcons"));
{
@@ -3439,26 +3182,25 @@ SpatialEditorGizmos::SpatialEditorGizmos() {
#undef ADD_VTX
#define ADD_VTX(m_idx) \
- vertices.push_back( face_points[m_idx] );
-
- for (int i=0;i<6;i++) {
+ vertices.push_back(face_points[m_idx]);
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
}
//tri 1
@@ -3469,15 +3211,11 @@ SpatialEditorGizmos::SpatialEditorGizmos() {
ADD_VTX(2);
ADD_VTX(3);
ADD_VTX(0);
-
}
- test_cube_tm = Ref<TriangleMesh>( memnew( TriangleMesh ) );
+ test_cube_tm = Ref<TriangleMesh>(memnew(TriangleMesh));
test_cube_tm->create(vertices);
}
- shape_material = create_line_material(Color(0.2,1,1.0));
-
-
+ shape_material = create_line_material(Color(0.2, 1, 1.0));
}
-
diff --git a/editor/spatial_editor_gizmos.h b/editor/spatial_editor_gizmos.h
index c44a987144..76564c5a99 100644
--- a/editor/spatial_editor_gizmos.h
+++ b/editor/spatial_editor_gizmos.h
@@ -29,35 +29,33 @@
#ifndef SPATIAL_EDITOR_GIZMOS_H
#define SPATIAL_EDITOR_GIZMOS_H
-
#include "editor/plugins/spatial_editor_plugin.h"
+#include "scene/3d/body_shape.h"
+#include "scene/3d/camera.h"
+#include "scene/3d/gi_probe.h"
#include "scene/3d/light.h"
#include "scene/3d/listener.h"
-#include "scene/3d/camera.h"
-#include "scene/3d/position_3d.h"
-#include "scene/3d/test_cube.h"
#include "scene/3d/mesh_instance.h"
-#include "scene/3d/body_shape.h"
-#include "scene/3d/room_instance.h"
-#include "scene/3d/visibility_notifier.h"
+#include "scene/3d/navigation_mesh.h"
#include "scene/3d/portal.h"
+#include "scene/3d/position_3d.h"
#include "scene/3d/ray_cast.h"
-#include "scene/3d/navigation_mesh.h"
#include "scene/3d/reflection_probe.h"
-#include "scene/3d/gi_probe.h"
+#include "scene/3d/room_instance.h"
+#include "scene/3d/test_cube.h"
+#include "scene/3d/visibility_notifier.h"
-#include "scene/3d/vehicle_body.h"
#include "scene/3d/collision_polygon.h"
#include "scene/3d/physics_joint.h"
-
+#include "scene/3d/vehicle_body.h"
class Camera;
-class EditorSpatialGizmo : public SpatialEditorGizmo {
+class EditorSpatialGizmo : public SpatialEditorGizmo {
- GDCLASS(EditorSpatialGizmo,SpatialGizmo);
+ GDCLASS(EditorSpatialGizmo, SpatialGizmo);
- struct Instance{
+ struct Instance {
RID instance;
Ref<Mesh> mesh;
@@ -68,14 +66,13 @@ class EditorSpatialGizmo : public SpatialEditorGizmo {
bool extra_margin;
Instance() {
- billboard=false;
- unscaled=false;
- can_intersect=false;
- extra_margin=false;
+ billboard = false;
+ unscaled = false;
+ can_intersect = false;
+ extra_margin = false;
}
void create_instance(Spatial *p_base);
-
};
Vector<Vector3> collision_segments;
@@ -96,22 +93,23 @@ class EditorSpatialGizmo : public SpatialEditorGizmo {
Spatial *spatial_node;
void _set_spatial_node(Node *p_node) { set_spatial_node(p_node->cast_to<Spatial>()); }
+
protected:
- void add_lines(const Vector<Vector3> &p_lines,const Ref<Material>& p_material,bool p_billboard=false);
- void add_mesh(const Ref<Mesh>& p_mesh,bool p_billboard=false,const RID& p_skeleton=RID());
+ void add_lines(const Vector<Vector3> &p_lines, const Ref<Material> &p_material, bool p_billboard = false);
+ void add_mesh(const Ref<Mesh> &p_mesh, bool p_billboard = false, const RID &p_skeleton = RID());
void add_collision_segments(const Vector<Vector3> &p_lines);
- void add_collision_triangles(const Ref<TriangleMesh>& p_tmesh);
- void add_unscaled_billboard(const Ref<Material>& p_material,float p_scale=1);
- void add_handles(const Vector<Vector3> &p_handles,bool p_billboard=false,bool p_secondary=false);
+ void add_collision_triangles(const Ref<TriangleMesh> &p_tmesh);
+ void add_unscaled_billboard(const Ref<Material> &p_material, float p_scale = 1);
+ void add_handles(const Vector<Vector3> &p_handles, bool p_billboard = false, bool p_secondary = false);
void set_spatial_node(Spatial *p_node);
static void _bind_methods();
-public:
+public:
virtual Vector3 get_handle_pos(int p_idx) const;
- virtual bool intersect_frustum(const Camera *p_camera,const Vector<Plane> &p_frustum);
- virtual bool intersect_ray(const Camera *p_camera,const Point2& p_point, Vector3& r_pos, Vector3& r_normal,int *r_gizmo_handle=NULL,bool p_sec_first=false);
+ virtual bool intersect_frustum(const Camera *p_camera, const Vector<Plane> &p_frustum);
+ virtual bool intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3 &r_pos, Vector3 &r_normal, int *r_gizmo_handle = NULL, bool p_sec_first = false);
void clear();
void create();
@@ -123,358 +121,286 @@ public:
~EditorSpatialGizmo();
};
+class LightSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(LightSpatialGizmo, EditorSpatialGizmo);
-class LightSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(LightSpatialGizmo,EditorSpatialGizmo);
-
- Light* light;
+ Light *light;
public:
-
-
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- LightSpatialGizmo(Light* p_light=NULL);
-
+ LightSpatialGizmo(Light *p_light = NULL);
};
-class CameraSpatialGizmo : public EditorSpatialGizmo {
+class CameraSpatialGizmo : public EditorSpatialGizmo {
- GDCLASS(CameraSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(CameraSpatialGizmo, EditorSpatialGizmo);
- Camera* camera;
+ Camera *camera;
public:
-
-
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- CameraSpatialGizmo(Camera* p_camera=NULL);
-
+ CameraSpatialGizmo(Camera *p_camera = NULL);
};
+class MeshInstanceSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(MeshInstanceSpatialGizmo, EditorSpatialGizmo);
-class MeshInstanceSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(MeshInstanceSpatialGizmo,EditorSpatialGizmo);
-
- MeshInstance* mesh;
+ MeshInstance *mesh;
public:
-
void redraw();
- MeshInstanceSpatialGizmo(MeshInstance* p_mesh=NULL);
-
+ MeshInstanceSpatialGizmo(MeshInstance *p_mesh = NULL);
};
-class Position3DSpatialGizmo : public EditorSpatialGizmo {
+class Position3DSpatialGizmo : public EditorSpatialGizmo {
- GDCLASS(Position3DSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(Position3DSpatialGizmo, EditorSpatialGizmo);
- Position3D* p3d;
+ Position3D *p3d;
public:
-
void redraw();
- Position3DSpatialGizmo(Position3D* p_p3d=NULL);
-
+ Position3DSpatialGizmo(Position3D *p_p3d = NULL);
};
-class SkeletonSpatialGizmo : public EditorSpatialGizmo {
+class SkeletonSpatialGizmo : public EditorSpatialGizmo {
- GDCLASS(SkeletonSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(SkeletonSpatialGizmo, EditorSpatialGizmo);
- Skeleton* skel;
+ Skeleton *skel;
public:
-
void redraw();
- SkeletonSpatialGizmo(Skeleton* p_skel=NULL);
-
+ SkeletonSpatialGizmo(Skeleton *p_skel = NULL);
};
+class TestCubeSpatialGizmo : public EditorSpatialGizmo {
-class TestCubeSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(TestCubeSpatialGizmo, EditorSpatialGizmo);
- GDCLASS(TestCubeSpatialGizmo,EditorSpatialGizmo);
-
- TestCube* tc;
+ TestCube *tc;
public:
void redraw();
- TestCubeSpatialGizmo(TestCube* p_tc=NULL);
-
+ TestCubeSpatialGizmo(TestCube *p_tc = NULL);
};
+class RoomSpatialGizmo : public EditorSpatialGizmo {
-class RoomSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(RoomSpatialGizmo,EditorSpatialGizmo);
-
+ GDCLASS(RoomSpatialGizmo, EditorSpatialGizmo);
struct _EdgeKey {
Vector3 from;
Vector3 to;
- bool operator<(const _EdgeKey& p_with) const { return from==p_with.from ? to < p_with.to : from < p_with.from; }
+ bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; }
};
-
-
- Room* room;
+ Room *room;
public:
-
void redraw();
- RoomSpatialGizmo(Room* p_room=NULL);
-
+ RoomSpatialGizmo(Room *p_room = NULL);
};
+class PortalSpatialGizmo : public EditorSpatialGizmo {
-class PortalSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(PortalSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(PortalSpatialGizmo, EditorSpatialGizmo);
- Portal* portal;
+ Portal *portal;
public:
-
void redraw();
- PortalSpatialGizmo(Portal* p_portal=NULL);
-
+ PortalSpatialGizmo(Portal *p_portal = NULL);
};
+class VisibilityNotifierGizmo : public EditorSpatialGizmo {
-class VisibilityNotifierGizmo : public EditorSpatialGizmo {
-
- GDCLASS(VisibilityNotifierGizmo ,EditorSpatialGizmo);
+ GDCLASS(VisibilityNotifierGizmo, EditorSpatialGizmo);
-
- VisibilityNotifier* notifier;
+ VisibilityNotifier *notifier;
public:
-
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- VisibilityNotifierGizmo(VisibilityNotifier* p_notifier=NULL);
-
+ VisibilityNotifierGizmo(VisibilityNotifier *p_notifier = NULL);
};
+class ReflectionProbeGizmo : public EditorSpatialGizmo {
-class ReflectionProbeGizmo : public EditorSpatialGizmo {
+ GDCLASS(ReflectionProbeGizmo, EditorSpatialGizmo);
- GDCLASS(ReflectionProbeGizmo ,EditorSpatialGizmo);
-
-
- ReflectionProbe* probe;
+ ReflectionProbe *probe;
public:
-
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- ReflectionProbeGizmo(ReflectionProbe* p_notifier=NULL);
-
+ ReflectionProbeGizmo(ReflectionProbe *p_notifier = NULL);
};
-class GIProbeGizmo : public EditorSpatialGizmo {
-
- GDCLASS(GIProbeGizmo ,EditorSpatialGizmo);
+class GIProbeGizmo : public EditorSpatialGizmo {
+ GDCLASS(GIProbeGizmo, EditorSpatialGizmo);
- GIProbe* probe;
+ GIProbe *probe;
public:
-
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- GIProbeGizmo(GIProbe* p_notifier=NULL);
-
+ GIProbeGizmo(GIProbe *p_notifier = NULL);
};
+class CollisionShapeSpatialGizmo : public EditorSpatialGizmo {
-class CollisionShapeSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(CollisionShapeSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(CollisionShapeSpatialGizmo, EditorSpatialGizmo);
- CollisionShape* cs;
+ CollisionShape *cs;
public:
virtual String get_handle_name(int p_idx) const;
virtual Variant get_handle_value(int p_idx) const;
- virtual void set_handle(int p_idx,Camera *p_camera, const Point2& p_point);
- virtual void commit_handle(int p_idx,const Variant& p_restore,bool p_cancel=false);
+ virtual void set_handle(int p_idx, Camera *p_camera, const Point2 &p_point);
+ virtual void commit_handle(int p_idx, const Variant &p_restore, bool p_cancel = false);
void redraw();
- CollisionShapeSpatialGizmo(CollisionShape* p_cs=NULL);
-
+ CollisionShapeSpatialGizmo(CollisionShape *p_cs = NULL);
};
+class CollisionPolygonSpatialGizmo : public EditorSpatialGizmo {
-class CollisionPolygonSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(CollisionPolygonSpatialGizmo, EditorSpatialGizmo);
- GDCLASS(CollisionPolygonSpatialGizmo,EditorSpatialGizmo);
-
- CollisionPolygon* polygon;
+ CollisionPolygon *polygon;
public:
-
void redraw();
- CollisionPolygonSpatialGizmo(CollisionPolygon* p_polygon=NULL);
-
+ CollisionPolygonSpatialGizmo(CollisionPolygon *p_polygon = NULL);
};
+class RayCastSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(RayCastSpatialGizmo, EditorSpatialGizmo);
-class RayCastSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(RayCastSpatialGizmo,EditorSpatialGizmo);
-
- RayCast* raycast;
+ RayCast *raycast;
public:
-
void redraw();
- RayCastSpatialGizmo(RayCast* p_raycast=NULL);
-
+ RayCastSpatialGizmo(RayCast *p_raycast = NULL);
};
+class VehicleWheelSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(VehicleWheelSpatialGizmo, EditorSpatialGizmo);
-class VehicleWheelSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(VehicleWheelSpatialGizmo,EditorSpatialGizmo);
-
- VehicleWheel* car_wheel;
+ VehicleWheel *car_wheel;
public:
-
void redraw();
- VehicleWheelSpatialGizmo(VehicleWheel* p_car_wheel=NULL);
-
+ VehicleWheelSpatialGizmo(VehicleWheel *p_car_wheel = NULL);
};
+class NavigationMeshSpatialGizmo : public EditorSpatialGizmo {
-class NavigationMeshSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(NavigationMeshSpatialGizmo,EditorSpatialGizmo);
-
+ GDCLASS(NavigationMeshSpatialGizmo, EditorSpatialGizmo);
struct _EdgeKey {
Vector3 from;
Vector3 to;
- bool operator<(const _EdgeKey& p_with) const { return from==p_with.from ? to < p_with.to : from < p_with.from; }
+ bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; }
};
-
-
- NavigationMeshInstance* navmesh;
+ NavigationMeshInstance *navmesh;
public:
-
void redraw();
- NavigationMeshSpatialGizmo(NavigationMeshInstance* p_navmesh=NULL);
-
+ NavigationMeshSpatialGizmo(NavigationMeshInstance *p_navmesh = NULL);
};
+class PinJointSpatialGizmo : public EditorSpatialGizmo {
-class PinJointSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(PinJointSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(PinJointSpatialGizmo, EditorSpatialGizmo);
- PinJoint* p3d;
+ PinJoint *p3d;
public:
-
void redraw();
- PinJointSpatialGizmo(PinJoint* p_p3d=NULL);
-
+ PinJointSpatialGizmo(PinJoint *p_p3d = NULL);
};
+class HingeJointSpatialGizmo : public EditorSpatialGizmo {
-class HingeJointSpatialGizmo : public EditorSpatialGizmo {
-
- GDCLASS(HingeJointSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(HingeJointSpatialGizmo, EditorSpatialGizmo);
- HingeJoint* p3d;
+ HingeJoint *p3d;
public:
-
void redraw();
- HingeJointSpatialGizmo(HingeJoint* p_p3d=NULL);
-
+ HingeJointSpatialGizmo(HingeJoint *p_p3d = NULL);
};
-class SliderJointSpatialGizmo : public EditorSpatialGizmo {
+class SliderJointSpatialGizmo : public EditorSpatialGizmo {
- GDCLASS(SliderJointSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(SliderJointSpatialGizmo, EditorSpatialGizmo);
- SliderJoint* p3d;
+ SliderJoint *p3d;
public:
-
void redraw();
- SliderJointSpatialGizmo(SliderJoint* p_p3d=NULL);
-
+ SliderJointSpatialGizmo(SliderJoint *p_p3d = NULL);
};
-class ConeTwistJointSpatialGizmo : public EditorSpatialGizmo {
+class ConeTwistJointSpatialGizmo : public EditorSpatialGizmo {
- GDCLASS(ConeTwistJointSpatialGizmo,EditorSpatialGizmo);
+ GDCLASS(ConeTwistJointSpatialGizmo, EditorSpatialGizmo);
- ConeTwistJoint* p3d;
+ ConeTwistJoint *p3d;
public:
-
void redraw();
- ConeTwistJointSpatialGizmo(ConeTwistJoint* p_p3d=NULL);
-
+ ConeTwistJointSpatialGizmo(ConeTwistJoint *p_p3d = NULL);
};
+class Generic6DOFJointSpatialGizmo : public EditorSpatialGizmo {
-class Generic6DOFJointSpatialGizmo : public EditorSpatialGizmo {
+ GDCLASS(Generic6DOFJointSpatialGizmo, EditorSpatialGizmo);
- GDCLASS(Generic6DOFJointSpatialGizmo,EditorSpatialGizmo);
-
- Generic6DOFJoint* p3d;
+ Generic6DOFJoint *p3d;
public:
-
void redraw();
- Generic6DOFJointSpatialGizmo(Generic6DOFJoint* p_p3d=NULL);
-
+ Generic6DOFJointSpatialGizmo(Generic6DOFJoint *p_p3d = NULL);
};
-
-class SpatialEditorGizmos {
+class SpatialEditorGizmos {
public:
-
- Ref<FixedSpatialMaterial> create_line_material(const Color& p_base_color);
- Ref<FixedSpatialMaterial> create_solid_material(const Color& p_base_color);
+ Ref<FixedSpatialMaterial> create_line_material(const Color &p_base_color);
+ Ref<FixedSpatialMaterial> create_solid_material(const Color &p_base_color);
Ref<FixedSpatialMaterial> handle2_material;
Ref<FixedSpatialMaterial> handle_material;
Ref<FixedSpatialMaterial> light_material;
@@ -513,7 +439,6 @@ public:
Ref<TriangleMesh> test_cube_tm;
-
Ref<SpatialEditorGizmo> get_gizmo(Spatial *p_spatial);
SpatialEditorGizmos();
diff --git a/main/input_default.cpp b/main/input_default.cpp
index a9f643c785..bc409960d6 100644
--- a/main/input_default.cpp
+++ b/main/input_default.cpp
@@ -27,48 +27,46 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "input_default.h"
-#include "servers/visual_server.h"
-#include "os/os.h"
#include "input_map.h"
+#include "os/os.h"
#include "scene/resources/texture.h"
+#include "servers/visual_server.h"
-void InputDefault::SpeedTrack::update(const Vector2& p_delta_p) {
+void InputDefault::SpeedTrack::update(const Vector2 &p_delta_p) {
uint64_t tick = OS::get_singleton()->get_ticks_usec();
- uint32_t tdiff = tick-last_tick;
+ uint32_t tdiff = tick - last_tick;
float delta_t = tdiff / 1000000.0;
- last_tick=tick;
-
+ last_tick = tick;
- accum+=p_delta_p;
- accum_t+=delta_t;
+ accum += p_delta_p;
+ accum_t += delta_t;
- if (accum_t>max_ref_frame*10)
- accum_t=max_ref_frame*10;
+ if (accum_t > max_ref_frame * 10)
+ accum_t = max_ref_frame * 10;
- while( accum_t>=min_ref_frame ) {
+ while (accum_t >= min_ref_frame) {
float slice_t = min_ref_frame / accum_t;
- Vector2 slice = accum*slice_t;
- accum=accum-slice;
- accum_t-=min_ref_frame;
+ Vector2 slice = accum * slice_t;
+ accum = accum - slice;
+ accum_t -= min_ref_frame;
- speed=(slice/min_ref_frame).linear_interpolate(speed,min_ref_frame/max_ref_frame);
+ speed = (slice / min_ref_frame).linear_interpolate(speed, min_ref_frame / max_ref_frame);
}
-
}
void InputDefault::SpeedTrack::reset() {
last_tick = OS::get_singleton()->get_ticks_usec();
- speed=Vector2();
- accum_t=0;
+ speed = Vector2();
+ accum_t = 0;
}
InputDefault::SpeedTrack::SpeedTrack() {
- min_ref_frame=0.1;
- max_ref_frame=0.3;
- reset();
+ min_ref_frame = 0.1;
+ max_ref_frame = 0.3;
+ reset();
}
bool InputDefault::is_key_pressed(int p_scancode) const {
@@ -80,22 +78,21 @@ bool InputDefault::is_key_pressed(int p_scancode) const {
bool InputDefault::is_mouse_button_pressed(int p_button) const {
_THREAD_SAFE_METHOD_
- return (mouse_button_mask&(1<<p_button))!=0;
+ return (mouse_button_mask & (1 << p_button)) != 0;
}
+static int _combine_device(int p_value, int p_device) {
-static int _combine_device(int p_value,int p_device) {
-
- return p_value|(p_device<<20);
+ return p_value | (p_device << 20);
}
-bool InputDefault::is_joy_button_pressed(int p_device, int p_button) const{
+bool InputDefault::is_joy_button_pressed(int p_device, int p_button) const {
_THREAD_SAFE_METHOD_
- return joy_buttons_pressed.has(_combine_device(p_button,p_device));
+ return joy_buttons_pressed.has(_combine_device(p_button, p_device));
}
-bool InputDefault::is_action_pressed(const StringName& p_action) const{
+bool InputDefault::is_action_pressed(const StringName &p_action) const {
return action_state.has(p_action) && action_state[p_action].pressed;
#if 0
@@ -152,37 +149,36 @@ bool InputDefault::is_action_pressed(const StringName& p_action) const{
#endif
}
-bool InputDefault::is_action_just_pressed(const StringName& p_action) const {
+bool InputDefault::is_action_just_pressed(const StringName &p_action) const {
- const Map<StringName,Action>::Element *E=action_state.find(p_action);
+ const Map<StringName, Action>::Element *E = action_state.find(p_action);
if (!E)
return false;
if (Engine::get_singleton()->is_in_fixed_frame()) {
- return E->get().pressed && E->get().fixed_frame==Engine::get_singleton()->get_fixed_frames();
+ return E->get().pressed && E->get().fixed_frame == Engine::get_singleton()->get_fixed_frames();
} else {
- return E->get().pressed && E->get().idle_frame==Engine::get_singleton()->get_idle_frames();
+ return E->get().pressed && E->get().idle_frame == Engine::get_singleton()->get_idle_frames();
}
}
-bool InputDefault::is_action_just_released(const StringName& p_action) const{
+bool InputDefault::is_action_just_released(const StringName &p_action) const {
- const Map<StringName,Action>::Element *E=action_state.find(p_action);
+ const Map<StringName, Action>::Element *E = action_state.find(p_action);
if (!E)
return false;
if (Engine::get_singleton()->is_in_fixed_frame()) {
- return !E->get().pressed && E->get().fixed_frame==Engine::get_singleton()->get_fixed_frames();
+ return !E->get().pressed && E->get().fixed_frame == Engine::get_singleton()->get_fixed_frames();
} else {
- return !E->get().pressed && E->get().idle_frame==Engine::get_singleton()->get_idle_frames();
+ return !E->get().pressed && E->get().idle_frame == Engine::get_singleton()->get_idle_frames();
}
}
-
-float InputDefault::get_joy_axis(int p_device,int p_axis) const{
+float InputDefault::get_joy_axis(int p_device, int p_axis) const {
_THREAD_SAFE_METHOD_
- int c = _combine_device(p_axis,p_device);
+ int c = _combine_device(p_axis, p_device);
if (_joy_axis.has(c)) {
return _joy_axis[c];
} else {
@@ -222,11 +218,11 @@ float InputDefault::get_joy_vibration_duration(int p_device) {
static String _hex_str(uint8_t p_byte) {
- static const char* dict = "0123456789abcdef";
+ static const char *dict = "0123456789abcdef";
char ret[3];
ret[2] = 0;
- ret[0] = dict[p_byte>>4];
+ ret[0] = dict[p_byte >> 4];
ret[1] = dict[p_byte & 0xf];
return ret;
@@ -246,22 +242,21 @@ void InputDefault::joy_connection_changed(int p_idx, bool p_connected, String p_
String uidname = p_guid;
if (p_guid == "") {
int uidlen = MIN(p_name.length(), 16);
- for (int i=0; i<uidlen; i++) {
+ for (int i = 0; i < uidlen; i++) {
uidname = uidname + _hex_str(p_name[i]);
};
};
js.uid = uidname;
js.connected = true;
int mapping = fallback_mapping;
- for (int i=0; i < map_db.size(); i++) {
+ for (int i = 0; i < map_db.size(); i++) {
if (js.uid == map_db[i].uid) {
mapping = i;
js.name = map_db[i].name;
};
};
js.mapping = mapping;
- }
- else {
+ } else {
js.connected = false;
for (int i = 0; i < JOY_BUTTON_MAX; i++) {
@@ -277,19 +272,19 @@ void InputDefault::joy_connection_changed(int p_idx, bool p_connected, String p_
emit_signal("joy_connection_changed", p_idx, p_connected);
};
-Vector3 InputDefault::get_gravity() const{
+Vector3 InputDefault::get_gravity() const {
_THREAD_SAFE_METHOD_
return gravity;
}
-Vector3 InputDefault::get_accelerometer() const{
+Vector3 InputDefault::get_accelerometer() const {
_THREAD_SAFE_METHOD_
return accelerometer;
}
-Vector3 InputDefault::get_magnetometer() const{
+Vector3 InputDefault::get_magnetometer() const {
_THREAD_SAFE_METHOD_
return magnetometer;
@@ -301,16 +296,16 @@ Vector3 InputDefault::get_gyroscope() const {
return gyroscope;
}
-void InputDefault::parse_input_event(const InputEvent& p_event) {
+void InputDefault::parse_input_event(const InputEvent &p_event) {
_THREAD_SAFE_METHOD_
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::KEY: {
if (p_event.key.echo)
break;
- if (p_event.key.scancode==0)
+ if (p_event.key.scancode == 0)
break;
//print_line(p_event);
@@ -326,37 +321,37 @@ void InputDefault::parse_input_event(const InputEvent& p_event) {
break;
if (p_event.mouse_button.pressed)
- mouse_button_mask|=(1<<p_event.mouse_button.button_index);
+ mouse_button_mask |= (1 << p_event.mouse_button.button_index);
else
- mouse_button_mask&=~(1<<p_event.mouse_button.button_index);
+ mouse_button_mask &= ~(1 << p_event.mouse_button.button_index);
- if (main_loop && emulate_touch && p_event.mouse_button.button_index==1) {
+ if (main_loop && emulate_touch && p_event.mouse_button.button_index == 1) {
InputEventScreenTouch touch_event;
- touch_event.index=0;
- touch_event.pressed=p_event.mouse_button.pressed;
- touch_event.x=p_event.mouse_button.x;
- touch_event.y=p_event.mouse_button.y;
+ touch_event.index = 0;
+ touch_event.pressed = p_event.mouse_button.pressed;
+ touch_event.x = p_event.mouse_button.x;
+ touch_event.y = p_event.mouse_button.y;
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.screen_touch=touch_event;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.screen_touch = touch_event;
main_loop->input_event(ev);
}
} break;
case InputEvent::MOUSE_MOTION: {
- if (main_loop && emulate_touch && p_event.mouse_motion.button_mask&1) {
+ if (main_loop && emulate_touch && p_event.mouse_motion.button_mask & 1) {
InputEventScreenDrag drag_event;
- drag_event.index=0;
- drag_event.x=p_event.mouse_motion.x;
- drag_event.y=p_event.mouse_motion.y;
- drag_event.relative_x=p_event.mouse_motion.relative_x;
- drag_event.relative_y=p_event.mouse_motion.relative_y;
- drag_event.speed_x=p_event.mouse_motion.speed_x;
- drag_event.speed_y=p_event.mouse_motion.speed_y;
+ drag_event.index = 0;
+ drag_event.x = p_event.mouse_motion.x;
+ drag_event.y = p_event.mouse_motion.y;
+ drag_event.relative_x = p_event.mouse_motion.relative_x;
+ drag_event.relative_y = p_event.mouse_motion.relative_y;
+ drag_event.speed_x = p_event.mouse_motion.speed_x;
+ drag_event.speed_y = p_event.mouse_motion.speed_y;
InputEvent ev;
- ev.type=InputEvent::SCREEN_DRAG;
- ev.screen_drag=drag_event;
+ ev.type = InputEvent::SCREEN_DRAG;
+ ev.screen_drag = drag_event;
main_loop->input_event(ev);
}
@@ -364,7 +359,7 @@ void InputDefault::parse_input_event(const InputEvent& p_event) {
} break;
case InputEvent::JOYPAD_BUTTON: {
- int c = _combine_device(p_event.joy_button.button_index,p_event.device);
+ int c = _combine_device(p_event.joy_button.button_index, p_event.device);
if (p_event.joy_button.pressed)
joy_buttons_pressed.insert(c);
@@ -374,33 +369,30 @@ void InputDefault::parse_input_event(const InputEvent& p_event) {
case InputEvent::JOYPAD_MOTION: {
set_joy_axis(p_event.device, p_event.joy_motion.axis, p_event.joy_motion.axis_value);
} break;
-
}
-
if (!p_event.is_echo()) {
- for (const Map<StringName,InputMap::Action>::Element *E=InputMap::get_singleton()->get_action_map().front();E;E=E->next()) {
+ for (const Map<StringName, InputMap::Action>::Element *E = InputMap::get_singleton()->get_action_map().front(); E; E = E->next()) {
- if (InputMap::get_singleton()->event_is_action(p_event,E->key()) && is_action_pressed(E->key()) != p_event.is_pressed()) {
+ if (InputMap::get_singleton()->event_is_action(p_event, E->key()) && is_action_pressed(E->key()) != p_event.is_pressed()) {
Action action;
- action.fixed_frame=Engine::get_singleton()->get_fixed_frames();
- action.idle_frame=Engine::get_singleton()->get_idle_frames();
- action.pressed=p_event.is_pressed();
- action_state[E->key()]=action;
+ action.fixed_frame = Engine::get_singleton()->get_fixed_frames();
+ action.idle_frame = Engine::get_singleton()->get_idle_frames();
+ action.pressed = p_event.is_pressed();
+ action_state[E->key()] = action;
}
}
}
if (main_loop)
main_loop->input_event(p_event);
-
}
-void InputDefault::set_joy_axis(int p_device,int p_axis,float p_value) {
+void InputDefault::set_joy_axis(int p_device, int p_axis, float p_value) {
_THREAD_SAFE_METHOD_
- int c = _combine_device(p_axis,p_device);
- _joy_axis[c]=p_value;
+ int c = _combine_device(p_axis, p_device);
+ _joy_axis[c] = p_value;
}
void InputDefault::start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration) {
@@ -426,47 +418,42 @@ void InputDefault::stop_joy_vibration(int p_device) {
joy_vibration[p_device] = vibration;
}
-void InputDefault::set_gravity(const Vector3& p_gravity) {
+void InputDefault::set_gravity(const Vector3 &p_gravity) {
_THREAD_SAFE_METHOD_
- gravity=p_gravity;
-
+ gravity = p_gravity;
}
-void InputDefault::set_accelerometer(const Vector3& p_accel) {
+void InputDefault::set_accelerometer(const Vector3 &p_accel) {
_THREAD_SAFE_METHOD_
- accelerometer=p_accel;
-
+ accelerometer = p_accel;
}
-void InputDefault::set_magnetometer(const Vector3& p_magnetometer) {
+void InputDefault::set_magnetometer(const Vector3 &p_magnetometer) {
_THREAD_SAFE_METHOD_
- magnetometer=p_magnetometer;
-
+ magnetometer = p_magnetometer;
}
-void InputDefault::set_gyroscope(const Vector3& p_gyroscope) {
+void InputDefault::set_gyroscope(const Vector3 &p_gyroscope) {
_THREAD_SAFE_METHOD_
- gyroscope=p_gyroscope;
-
+ gyroscope = p_gyroscope;
}
void InputDefault::set_main_loop(MainLoop *p_main_loop) {
- main_loop=p_main_loop;
-
+ main_loop = p_main_loop;
}
-void InputDefault::set_mouse_pos(const Point2& p_posf) {
+void InputDefault::set_mouse_pos(const Point2 &p_posf) {
- mouse_speed_track.update(p_posf-mouse_pos);
- mouse_pos=p_posf;
+ mouse_speed_track.update(p_posf - mouse_pos);
+ mouse_pos = p_posf;
if (custom_cursor.is_valid()) {
VisualServer::get_singleton()->cursor_set_pos(get_mouse_pos());
}
@@ -483,46 +470,42 @@ Point2 InputDefault::get_last_mouse_speed() const {
int InputDefault::get_mouse_button_mask() const {
- return mouse_button_mask;// do not trust OS implementaiton, should remove it - OS::get_singleton()->get_mouse_button_state();
+ return mouse_button_mask; // do not trust OS implementaiton, should remove it - OS::get_singleton()->get_mouse_button_state();
}
-void InputDefault::warp_mouse_pos(const Vector2& p_to) {
+void InputDefault::warp_mouse_pos(const Vector2 &p_to) {
OS::get_singleton()->warp_mouse_pos(p_to);
}
-
void InputDefault::iteration(float p_step) {
-
-
}
-void InputDefault::action_press(const StringName& p_action) {
+void InputDefault::action_press(const StringName &p_action) {
Action action;
- action.fixed_frame=Engine::get_singleton()->get_fixed_frames();
- action.idle_frame=Engine::get_singleton()->get_idle_frames();
- action.pressed=true;
-
- action_state[p_action]=action;
+ action.fixed_frame = Engine::get_singleton()->get_fixed_frames();
+ action.idle_frame = Engine::get_singleton()->get_idle_frames();
+ action.pressed = true;
+ action_state[p_action] = action;
}
-void InputDefault::action_release(const StringName& p_action){
+void InputDefault::action_release(const StringName &p_action) {
Action action;
- action.fixed_frame=Engine::get_singleton()->get_fixed_frames();
- action.idle_frame=Engine::get_singleton()->get_idle_frames();
- action.pressed=false;
+ action.fixed_frame = Engine::get_singleton()->get_fixed_frames();
+ action.idle_frame = Engine::get_singleton()->get_idle_frames();
+ action.pressed = false;
- action_state[p_action]=action;
+ action_state[p_action] = action;
}
void InputDefault::set_emulate_touch(bool p_emulate) {
- emulate_touch=p_emulate;
+ emulate_touch = p_emulate;
}
bool InputDefault::is_emulating_touchscreen() const {
@@ -530,11 +513,11 @@ bool InputDefault::is_emulating_touchscreen() const {
return emulate_touch;
}
-void InputDefault::set_custom_mouse_cursor(const RES& p_cursor,const Vector2& p_hotspot) {
- if (custom_cursor==p_cursor)
+void InputDefault::set_custom_mouse_cursor(const RES &p_cursor, const Vector2 &p_hotspot) {
+ if (custom_cursor == p_cursor)
return;
- custom_cursor=p_cursor;
+ custom_cursor = p_cursor;
if (p_cursor.is_null()) {
set_mouse_mode(MOUSE_MODE_VISIBLE);
@@ -544,7 +527,7 @@ void InputDefault::set_custom_mouse_cursor(const RES& p_cursor,const Vector2& p_
Rect2 region = atex.is_valid() ? atex->get_region() : Rect2();
set_mouse_mode(MOUSE_MODE_HIDDEN);
VisualServer::get_singleton()->cursor_set_visible(true);
- VisualServer::get_singleton()->cursor_set_texture(custom_cursor->get_rid(),p_hotspot, 0, region);
+ VisualServer::get_singleton()->cursor_set_texture(custom_cursor->get_rid(), p_hotspot, 0, region);
VisualServer::get_singleton()->cursor_set_pos(get_mouse_pos());
}
}
@@ -560,13 +543,12 @@ void InputDefault::set_mouse_in_window(bool p_in_window) {
set_mouse_mode(MOUSE_MODE_VISIBLE);
VisualServer::get_singleton()->cursor_set_visible(false);
}
-
}
}
// from github.com/gabomdq/SDL_GameControllerDB
-static const char *s_ControllerMappings [] = {
- #ifdef WINDOWS_ENABLED
+static const char *s_ControllerMappings[] = {
+#ifdef WINDOWS_ENABLED
"00f00300000000000000504944564944,RetroUSB.com RetroPad,a:b1,b:b5,x:b0,y:b4,back:b2,start:b3,leftshoulder:b6,rightshoulder:b7,leftx:a0,lefty:a1,",
"00f0f100000000000000504944564944,RetroUSB.com Super RetroPort,a:b1,b:b5,x:b0,y:b4,back:b2,start:b3,leftshoulder:b6,rightshoulder:b7,leftx:a0,lefty:a1,",
"02200090000000000000504944564944,8Bitdo NES30 PRO USB,a:b0,b:b1,x:b3,y:b4,leftshoulder:b6,rightshoulder:b7,lefttrigger:b8,righttrigger:b9,back:b10,start:b11,leftstick:b13,rightstick:b14,leftx:a0,lefty:a1,rightx:a3,righty:a4,dpup:h0.1,dpright:h0.2,dpdown:h0.4,dpleft:h0.8,",
@@ -613,9 +595,9 @@ static const char *s_ControllerMappings [] = {
"ff113133000000000000504944564944,SVEN X-PAD,a:b2,b:b3,y:b1,x:b0,start:b5,back:b4,leftshoulder:b6,rightshoulder:b7,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a4,lefttrigger:b8,righttrigger:b9,",
"ffff0000000000000000504944564944,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
"__XINPUT_DEVICE__,XInput Gamepad,a:b12,b:b13,x:b14,y:b15,start:b4,back:b5,leftstick:b6,rightstick:b7,leftshoulder:b8,rightshoulder:b9,dpup:b0,dpdown:b1,dpleft:b2,dpright:b3,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a4,righttrigger:a5,",
- #endif
+#endif
- #ifdef OSX_ENABLED
+#ifdef OSX_ENABLED
"0500000047532047616d657061640000,GameStop Gamepad,a:b0,b:b1,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,guide:,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b2,y:b3,",
"050000005769696d6f74652028303000,Wii Remote,a:b4,b:b5,y:b9,x:b10,start:b6,guide:b8,back:b7,dpup:b2,dpleft:b0,dpdown:b3,dpright:b1,leftx:a0,lefty:a1,lefttrigger:b12,righttrigger:,leftshoulder:b11,",
"050000005769696d6f74652028313800,Wii U Pro Controller,a:b16,b:b15,x:b18,y:b17,back:b7,guide:b8,start:b6,leftstick:b23,rightstick:b24,leftshoulder:b19,rightshoulder:b20,dpup:b11,dpdown:b12,dpleft:b13,dpright:b14,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b21,righttrigger:b22,",
@@ -642,9 +624,9 @@ static const char *s_ControllerMappings [] = {
"ad1b00000000000001f9000000000000,Gamestop BB-070 X360 Controller,a:b0,b:b1,back:b9,dpdown:b12,dpleft:b13,dpright:b14,dpup:b11,guide:b10,leftshoulder:b4,leftstick:b6,lefttrigger:a2,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b7,righttrigger:a5,rightx:a3,righty:a4,start:b8,x:b2,y:b3,",
"b4040000000000000a01000000000000,Sega Saturn USB Gamepad,a:b0,b:b1,x:b3,y:b4,back:b5,guide:b2,start:b8,leftshoulder:b6,rightshoulder:b7,leftx:a0,lefty:a1,",
"d814000000000000cecf000000000000,MC Cthulhu,leftx:,lefty:,rightx:,righty:,lefttrigger:b6,a:b1,b:b2,y:b3,x:b0,start:b9,back:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,righttrigger:b7,",
- #endif
+#endif
- #if X11_ENABLED
+#if X11_ENABLED
"0000000058626f782047616d65706100,Xbox Gamepad (userspace driver),a:b0,b:b1,x:b2,y:b3,start:b7,back:b6,guide:b8,dpup:h0.1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,lefttrigger:a5,righttrigger:a4,leftstick:b9,rightstick:b10,leftx:a0,lefty:a1,rightx:a2,righty:a3,",
"0300000000f000000300000000010000,RetroUSB.com RetroPad,a:b1,b:b5,x:b0,y:b4,back:b2,start:b3,leftshoulder:b6,rightshoulder:b7,leftx:a0,lefty:a1,",
"0300000000f00000f100000000010000,RetroUSB.com Super RetroPort,a:b1,b:b5,x:b0,y:b4,back:b2,start:b3,leftshoulder:b6,rightshoulder:b7,leftx:a0,lefty:a1,",
@@ -727,9 +709,9 @@ static const char *s_ControllerMappings [] = {
"050000007e0500003003000001000000,Nintendo Wii U Pro Controller,a:b0,b:b1,x:b3,y:b2,back:b8,start:b9,guide:b10,leftshoulder:b4,rightshoulder:b5,leftstick:b11,rightstick:b12,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7,dpup:b13,dpleft:b15,dpdown:b14,dpright:b16,",
"05000000d6200000ad0d000001000000,Moga Pro,a:b0,b:b1,y:b3,x:b2,start:b6,leftstick:b7,rightstick:b8,leftshoulder:b4,rightshoulder:b5,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a5,righttrigger:a4,",
"060000004c0500006802000000010000,PS3 Controller (Bluetooth),a:b14,b:b13,y:b12,x:b15,start:b3,guide:b16,back:b0,leftstick:b1,rightstick:b2,leftshoulder:b10,rightshoulder:b11,dpup:b4,dpleft:b7,dpdown:b6,dpright:b5,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b8,righttrigger:b9,",
- #endif
+#endif
- #if defined(__ANDROID__)
+#if defined(__ANDROID__)
"Default Android Gamepad,Default Controller,leftx:a0,lefty:a1,dpdown:h0.4,rightstick:b8,rightshoulder:b10,rightx:a2,start:b6,righty:a3,dpleft:h0.8,lefttrigger:a4,x:b2,dpup:h0.1,back:b4,leftstick:b7,leftshoulder:b9,y:b3,a:b0,dpright:h0.2,righttrigger:a5,b:b1,",
"47656e6572696320582d426f78207061,Logitech F-310,leftx:a0,lefty:a1,dpdown:h0.4,rightstick:b8,rightshoulder:b10,rightx:a2,start:b6,righty:a3,dpleft:h0.8,lefttrigger:a5,x:b2,dpup:h0.1,leftstick:b7,leftshoulder:b9,y:b3,a:b0,dpright:h0.2,righttrigger:a4,b:b1,",
"484f524920434f2e2c4c544420205041,Hori Gem Pad 3,leftx:a0,lefty:a1,dpdown:h0.4,rightstick:b6,rightshoulder:b18,rightx:a2,start:b16,righty:a3,dpleft:h0.8,lefttrigger:b9,x:b0,dpup:h0.1,back:b15,leftstick:b4,leftshoulder:b3,y:b2,a:b1,dpright:h0.2,righttrigger:b10,b:b17,",
@@ -737,9 +719,9 @@ static const char *s_ControllerMappings [] = {
"4e564944494120436f72706f72617469,NVIDIA Controller,a:b0,b:b1,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,leftshoulder:b9,leftstick:b7,lefttrigger:a4,leftx:a0,lefty:a1,rightshoulder:b10,rightstick:b8,righttrigger:a5,rightx:a2,righty:a3,start:b6,x:b2,y:b3,",
"532e542e442e20496e74657261637420,3dfx InterAct HammerHead FX,leftx:a0,lefty:a1,dpdown:h0.4,rightstick:b25,rightshoulder:b27,rightx:a2,start:b31,righty:a3,dpleft:h0.8,lefttrigger:b28,x:b20,dpup:h0.1,back:b30,leftstick:b22,leftshoulder:b26,y:b21,a:b23,dpright:h0.2,righttrigger:b29,b:b24,",
"506572666f726d616e63652044657369,PDP Rock Candy Wireless Controller for PS3,leftx:a0,lefty:a1,dpdown:h0.4,rightstick:b6,rightshoulder:b18,rightx:a2,start:b16,righty:a3,dpleft:h0.8,lefttrigger:b9,x:b0,dpup:h0.1,back:h0.2,leftstick:b4,leftshoulder:b3,y:b2,a:b1,dpright:h0.2,righttrigger:b10,b:b17,",
- #endif
+#endif
- #ifdef JAVASCRIPT_ENABLED
+#ifdef JAVASCRIPT_ENABLED
"Default HTML5 Gamepad, Default Mapping,leftx:a0,lefty:a1,dpdown:b13,rightstick:b11,rightshoulder:b5,rightx:a2,start:b9,righty:a3,dpleft:b14,lefttrigger:a6,x:b2,dpup:b12,back:b8,leftstick:b10,leftshoulder:b4,y:b3,a:b0,dpright:b15,righttrigger:a7,b:b1,",
"303435652d303238652d4d6963726f73,Wired X360 Controller,leftx:a0,lefty:a1,dpdown:a7,rightstick:b10,rightshoulder:b5,rightx:a3,start:b7,righty:a4,dpleft:a6,lefttrigger:a2,x:b2,dpup:a7,back:b6,leftstick:b9,leftshoulder:b4,y:b3,a:b0,dpright:a6,righttrigger:a5,b:b1,",
"303435652d303731392d58626f782033,Wireless X360 Controller,leftx:a0,lefty:a1,dpdown:b14,rightstick:b10,rightshoulder:b5,rightx:a3,start:b7,righty:a4,dpleft:b11,lefttrigger:a2,x:b2,dpup:b13,back:b6,leftstick:b9,leftshoulder:b4,y:b3,a:b0,dpright:b12,righttrigger:a5,b:b1,",
@@ -747,19 +729,19 @@ static const char *s_ControllerMappings [] = {
"303534632d303563342d536f6e792043,PS4 Controller USB/Linux,leftx:a0,lefty:a1,dpdown:a7,rightstick:b11,rightshoulder:b5,rightx:a2,start:b9,righty:a5,dpleft:a6,lefttrigger:a3,x:b0,dpup:a7,back:b8,leftstick:b10,leftshoulder:b4,y:b3,a:b1,dpright:a6,righttrigger:a4,b:b2,",
"303534632d303563342d576972656c65,PS4 Controller USB/Win,leftx:a0,lefty:a1,dpdown:b15,rightstick:b11,rightshoulder:b5,rightx:a2,start:b9,righty:a5,lefttrigger:a3,x:b0,dpup:b14,dpleft:b16,dpright:b17,back:b8,leftstick:b10,leftshoulder:b4,y:b3,a:b1,righttrigger:b7,b:b2,",
"c2a94d6963726f736f66742058626f78,Wireless X360 Controller,leftx:a0,lefty:a1,dpdown:b14,rightstick:b10,rightshoulder:b5,rightx:a3,start:b7,righty:a4,dpleft:b11,lefttrigger:a2,x:b2,dpup:b13,back:b6,leftstick:b9,leftshoulder:b4,y:b3,a:b0,dpright:b12,righttrigger:a5,b:b1,",
- #endif
+#endif
- #ifdef UWP_ENABLED
+#ifdef UWP_ENABLED
"__UWP_GAMEPAD__,Xbox Controller,a:b2,b:b3,x:b4,y:b5,start:b0,back:b1,leftstick:b12,rightstick:b13,leftshoulder:b10,rightshoulder:b11,dpup:b6,dpdown:b7,dpleft:b8,dpright:b9,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:a4,righttrigger:a5,",
- #endif
+#endif
NULL
};
InputDefault::InputDefault() {
- mouse_button_mask=0;
- emulate_touch=false;
- main_loop=NULL;
+ mouse_button_mask = 0;
+ emulate_touch = false;
+ main_loop = NULL;
hat_map_default[HAT_UP].type = TYPE_BUTTON;
hat_map_default[HAT_UP].index = JOY_DPAD_UP;
@@ -783,7 +765,7 @@ InputDefault::InputDefault() {
if (env_mapping != "") {
Vector<String> entries = env_mapping.split("\n");
- for (int i=0; i < entries.size(); i++) {
+ for (int i = 0; i < entries.size(); i++) {
if (entries[i] == "")
continue;
parse_mapping(entries[i]);
@@ -797,11 +779,10 @@ InputDefault::InputDefault() {
};
}
-
uint32_t InputDefault::joy_button(uint32_t p_last_id, int p_device, int p_button, bool p_pressed) {
_THREAD_SAFE_METHOD_;
- Joypad& joy = joy_names[p_device];
+ Joypad &joy = joy_names[p_device];
//printf("got button %i, mapping is %i\n", p_button, joy.mapping);
if (joy.last_buttons[p_button] == p_pressed) {
return p_last_id;
@@ -812,7 +793,7 @@ uint32_t InputDefault::joy_button(uint32_t p_last_id, int p_device, int p_button
return _button_event(p_last_id, p_device, p_button, p_pressed);
};
- Map<int,JoyEvent>::Element* el = map_db[joy.mapping].buttons.find(p_button);
+ Map<int, JoyEvent>::Element *el = map_db[joy.mapping].buttons.find(p_button);
if (!el) {
//don't process un-mapped events for now, it could mess things up badly for devices with additional buttons/axis
//return _button_event(p_last_id, p_device, p_button, p_pressed);
@@ -837,11 +818,11 @@ uint32_t InputDefault::joy_button(uint32_t p_last_id, int p_device, int p_button
return p_last_id; // no event?
};
-uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, const JoyAxis& p_value) {
+uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, const JoyAxis &p_value) {
_THREAD_SAFE_METHOD_;
- Joypad& joy = joy_names[p_device];
+ Joypad &joy = joy_names[p_device];
if (joy.last_axis[p_axis] == p_value.value) {
return p_last_id;
@@ -849,12 +830,11 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
if (p_value.value > joy.last_axis[p_axis]) {
- if (p_value.value < joy.last_axis[p_axis] + joy.filter ) {
+ if (p_value.value < joy.last_axis[p_axis] + joy.filter) {
return p_last_id;
}
- }
- else if (p_value.value > joy.last_axis[p_axis] - joy.filter) {
+ } else if (p_value.value > joy.last_axis[p_axis] - joy.filter) {
return p_last_id;
}
@@ -874,13 +854,12 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
return _axis_event(p_last_id, p_device, p_axis, val);
};
- Map<int,JoyEvent>::Element* el = map_db[joy.mapping].axis.find(p_axis);
+ Map<int, JoyEvent>::Element *el = map_db[joy.mapping].axis.find(p_axis);
if (!el) {
//return _axis_event(p_last_id, p_device, p_axis, p_value);
return p_last_id;
};
-
JoyEvent map = el->get();
if (map.type == TYPE_BUTTON) {
@@ -903,7 +882,7 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
p_last_id = _button_event(p_last_id, p_device, JOY_DPAD_DOWN, false);
}
}
- if ( pressed == joy_buttons_pressed.has(_combine_device(button, p_device))) {
+ if (pressed == joy_buttons_pressed.has(_combine_device(button, p_device))) {
return p_last_id;
}
return _button_event(p_last_id, p_device, button, true);
@@ -920,14 +899,14 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
p_last_id = _button_event(p_last_id, p_device, JOY_DPAD_RIGHT, false);
}
}
- if ( pressed == joy_buttons_pressed.has(_combine_device(button, p_device))) {
+ if (pressed == joy_buttons_pressed.has(_combine_device(button, p_device))) {
return p_last_id;
}
return _button_event(p_last_id, p_device, button, true);
}
float deadzone = p_value.min == 0 ? 0.5f : 0.0f;
bool pressed = p_value.value > deadzone ? true : false;
- if (pressed == joy_buttons_pressed.has(_combine_device(map.index,p_device))) {
+ if (pressed == joy_buttons_pressed.has(_combine_device(map.index, p_device))) {
// button already pressed or released, this is an axis bounce value
return p_last_id;
};
@@ -936,7 +915,7 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
if (map.type == TYPE_AXIS) {
- return _axis_event(p_last_id, p_device, map.index, val );
+ return _axis_event(p_last_id, p_device, map.index, val);
};
//printf("invalid mapping\n");
return p_last_id;
@@ -945,9 +924,9 @@ uint32_t InputDefault::joy_axis(uint32_t p_last_id, int p_device, int p_axis, co
uint32_t InputDefault::joy_hat(uint32_t p_last_id, int p_device, int p_val) {
_THREAD_SAFE_METHOD_;
- const Joypad& joy = joy_names[p_device];
+ const Joypad &joy = joy_names[p_device];
- JoyEvent* map;
+ JoyEvent *map;
if (joy.mapping == -1) {
map = hat_map_default;
@@ -957,17 +936,17 @@ uint32_t InputDefault::joy_hat(uint32_t p_last_id, int p_device, int p_val) {
int cur_val = joy_names[p_device].hat_current;
- if ( (p_val & HAT_MASK_UP) != (cur_val & HAT_MASK_UP) ) {
+ if ((p_val & HAT_MASK_UP) != (cur_val & HAT_MASK_UP)) {
p_last_id = _button_event(p_last_id, p_device, map[HAT_UP].index, p_val & HAT_MASK_UP);
};
- if ( (p_val & HAT_MASK_RIGHT) != (cur_val & HAT_MASK_RIGHT) ) {
+ if ((p_val & HAT_MASK_RIGHT) != (cur_val & HAT_MASK_RIGHT)) {
p_last_id = _button_event(p_last_id, p_device, map[HAT_RIGHT].index, p_val & HAT_MASK_RIGHT);
};
- if ( (p_val & HAT_MASK_DOWN) != (cur_val & HAT_MASK_DOWN) ) {
+ if ((p_val & HAT_MASK_DOWN) != (cur_val & HAT_MASK_DOWN)) {
p_last_id = _button_event(p_last_id, p_device, map[HAT_DOWN].index, p_val & HAT_MASK_DOWN);
};
- if ( (p_val & HAT_MASK_LEFT) != (cur_val & HAT_MASK_LEFT) ) {
+ if ((p_val & HAT_MASK_LEFT) != (cur_val & HAT_MASK_LEFT)) {
p_last_id = _button_event(p_last_id, p_device, map[HAT_LEFT].index, p_val & HAT_MASK_LEFT);
};
@@ -999,7 +978,7 @@ uint32_t InputDefault::_axis_event(uint32_t p_last_id, int p_device, int p_axis,
ievent.joy_motion.axis = p_axis;
ievent.joy_motion.axis_value = p_value;
- parse_input_event( ievent );
+ parse_input_event(ievent);
return p_last_id;
};
@@ -1007,14 +986,14 @@ uint32_t InputDefault::_axis_event(uint32_t p_last_id, int p_device, int p_axis,
InputDefault::JoyEvent InputDefault::_find_to_event(String p_to) {
// string names of the SDL buttons in the same order as input_event.h godot buttons
- static const char* buttons[] = {"a", "b", "x", "y", "leftshoulder", "rightshoulder", "lefttrigger", "righttrigger", "leftstick", "rightstick", "back", "start", "dpup", "dpdown", "dpleft", "dpright", "guide", NULL };
+ static const char *buttons[] = { "a", "b", "x", "y", "leftshoulder", "rightshoulder", "lefttrigger", "righttrigger", "leftstick", "rightstick", "back", "start", "dpup", "dpdown", "dpleft", "dpright", "guide", NULL };
- static const char* axis[] = {"leftx", "lefty", "rightx", "righty", NULL };
+ static const char *axis[] = { "leftx", "lefty", "rightx", "righty", NULL };
JoyEvent ret;
ret.type = -1;
- int i=0;
+ int i = 0;
while (buttons[i]) {
if (p_to == buttons[i]) {
@@ -1070,30 +1049,30 @@ void InputDefault::parse_mapping(String p_mapping) {
String etype = from.substr(0, 1);
if (etype == "a") {
- int aid = from.substr(1, from.length()-1).to_int();
+ int aid = from.substr(1, from.length() - 1).to_int();
mapping.axis[aid] = to_event;
} else if (etype == "b") {
- int bid = from.substr(1, from.length()-1).to_int();
+ int bid = from.substr(1, from.length() - 1).to_int();
mapping.buttons[bid] = to_event;
} else if (etype == "h") {
int hat_value = from.get_slice(".", 1).to_int();
switch (hat_value) {
- case 1:
- mapping.hat[HAT_UP] = to_event;
- break;
- case 2:
- mapping.hat[HAT_RIGHT] = to_event;
- break;
- case 4:
- mapping.hat[HAT_DOWN] = to_event;
- break;
- case 8:
- mapping.hat[HAT_LEFT] = to_event;
- break;
+ case 1:
+ mapping.hat[HAT_UP] = to_event;
+ break;
+ case 2:
+ mapping.hat[HAT_RIGHT] = to_event;
+ break;
+ case 4:
+ mapping.hat[HAT_DOWN] = to_event;
+ break;
+ case 8:
+ mapping.hat[HAT_LEFT] = to_event;
+ break;
};
};
};
@@ -1106,21 +1085,21 @@ void InputDefault::add_joy_mapping(String p_mapping, bool p_update_existing) {
if (p_update_existing) {
Vector<String> entry = p_mapping.split(",");
String uid = entry[0];
- for (int i=0; i<joy_names.size(); i++) {
+ for (int i = 0; i < joy_names.size(); i++) {
if (uid == joy_names[i].uid) {
- joy_names[i].mapping = map_db.size() -1;
+ joy_names[i].mapping = map_db.size() - 1;
}
}
}
}
void InputDefault::remove_joy_mapping(String p_guid) {
- for (int i=map_db.size()-1; i >= 0;i--) {
+ for (int i = map_db.size() - 1; i >= 0; i--) {
if (p_guid == map_db[i].uid) {
map_db.remove(i);
}
}
- for (int i=0; i<joy_names.size(); i++) {
+ for (int i = 0; i < joy_names.size(); i++) {
if (joy_names[i].uid == p_guid) {
joy_names[i].mapping = -1;
}
@@ -1170,7 +1149,7 @@ Array InputDefault::get_connected_joypads() {
return ret;
}
-static const char* _buttons[] = {
+static const char *_buttons[] = {
"Face Button Bottom",
"Face Button Right",
"Face Button Left",
@@ -1189,7 +1168,7 @@ static const char* _buttons[] = {
"DPAD Right"
};
-static const char* _axes[] = {
+static const char *_axes[] = {
"Left Stick X",
"Left Stick Y",
"Right Stick X",
@@ -1215,7 +1194,7 @@ int InputDefault::get_joy_button_index_from_string(String p_button) {
}
int InputDefault::get_unused_joy_id() {
- for (int i=0;i<JOYPADS_MAX;i++) {
+ for (int i = 0; i < JOYPADS_MAX; i++) {
if (!joy_names.has(i) || !joy_names[i].connected) {
return i;
}
diff --git a/main/input_default.h b/main/input_default.h
index 78bc0f4355..a1a055366c 100644
--- a/main/input_default.h
+++ b/main/input_default.h
@@ -31,18 +31,16 @@
#include "os/input.h"
-
class InputDefault : public Input {
- GDCLASS( InputDefault, Input );
+ GDCLASS(InputDefault, Input);
_THREAD_SAFE_CLASS_
int mouse_button_mask;
-
Set<int> keys_pressed;
Set<int> joy_buttons_pressed;
- Map<int,float> _joy_axis;
+ Map<int, float> _joy_axis;
//Map<StringName,int> custom_action_press;
Vector3 gravity;
Vector3 accelerometer;
@@ -57,8 +55,7 @@ class InputDefault : public Input {
bool pressed;
};
- Map<StringName,Action> action_state;
-
+ Map<StringName, Action> action_state;
bool emulate_touch;
@@ -80,7 +77,7 @@ class InputDefault : public Input {
float min_ref_frame;
float max_ref_frame;
- void update(const Vector2& p_delta_p);
+ void update(const Vector2 &p_delta_p);
void reset();
SpeedTrack();
};
@@ -101,7 +98,6 @@ class InputDefault : public Input {
for (int i = 0; i < JOY_AXIS_MAX; i++) {
last_axis[i] = 0.0f;
-
}
for (int i = 0; i < JOY_BUTTON_MAX + 19; i++) {
@@ -118,6 +114,7 @@ class InputDefault : public Input {
Map<int, Joypad> joy_names;
int fallback_mapping;
RES custom_cursor;
+
public:
enum HatMask {
HAT_MASK_CENTER = 0,
@@ -145,7 +142,6 @@ public:
};
private:
-
enum JoyType {
TYPE_BUTTON,
TYPE_AXIS,
@@ -163,8 +159,8 @@ private:
String uid;
String name;
- Map<int,JoyEvent> buttons;
- Map<int,JoyEvent> axis;
+ Map<int, JoyEvent> buttons;
+ Map<int, JoyEvent> axis;
JoyEvent hat[HAT_MAX];
};
@@ -178,17 +174,14 @@ private:
float _handle_deadzone(int p_device, int p_axis, float p_value);
public:
-
-
-
virtual bool is_key_pressed(int p_scancode) const;
virtual bool is_mouse_button_pressed(int p_button) const;
virtual bool is_joy_button_pressed(int p_device, int p_button) const;
- virtual bool is_action_pressed(const StringName& p_action) const;
- virtual bool is_action_just_pressed(const StringName& p_action) const;
- virtual bool is_action_just_released(const StringName& p_action) const;
+ virtual bool is_action_pressed(const StringName &p_action) const;
+ virtual bool is_action_just_pressed(const StringName &p_action) const;
+ virtual bool is_action_just_released(const StringName &p_action) const;
- virtual float get_joy_axis(int p_device,int p_axis) const;
+ virtual float get_joy_axis(int p_device, int p_axis) const;
String get_joy_name(int p_idx);
virtual Array get_connected_joypads();
virtual Vector2 get_joy_vibration_strength(int p_device);
@@ -206,47 +199,46 @@ public:
virtual Point2 get_last_mouse_speed() const;
virtual int get_mouse_button_mask() const;
- virtual void warp_mouse_pos(const Vector2& p_to);
-
+ virtual void warp_mouse_pos(const Vector2 &p_to);
- void parse_input_event(const InputEvent& p_event);
- void set_gravity(const Vector3& p_gravity);
- void set_accelerometer(const Vector3& p_accel);
- void set_magnetometer(const Vector3& p_magnetometer);
- void set_gyroscope(const Vector3& p_gyroscope);
- void set_joy_axis(int p_device,int p_axis,float p_value);
+ void parse_input_event(const InputEvent &p_event);
+ void set_gravity(const Vector3 &p_gravity);
+ void set_accelerometer(const Vector3 &p_accel);
+ void set_magnetometer(const Vector3 &p_magnetometer);
+ void set_gyroscope(const Vector3 &p_gyroscope);
+ void set_joy_axis(int p_device, int p_axis, float p_value);
- virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration=0);
+ virtual void start_joy_vibration(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration = 0);
virtual void stop_joy_vibration(int p_device);
void set_main_loop(MainLoop *main_loop);
- void set_mouse_pos(const Point2& p_posf);
+ void set_mouse_pos(const Point2 &p_posf);
- void action_press(const StringName& p_action);
- void action_release(const StringName& p_action);
+ void action_press(const StringName &p_action);
+ void action_release(const StringName &p_action);
void iteration(float p_step);
void set_emulate_touch(bool p_emulate);
virtual bool is_emulating_touchscreen() const;
- virtual void set_custom_mouse_cursor(const RES& p_cursor,const Vector2& p_hotspot=Vector2());
+ virtual void set_custom_mouse_cursor(const RES &p_cursor, const Vector2 &p_hotspot = Vector2());
virtual void set_mouse_in_window(bool p_in_window);
void parse_mapping(String p_mapping);
uint32_t joy_button(uint32_t p_last_id, int p_device, int p_button, bool p_pressed);
- uint32_t joy_axis(uint32_t p_last_id, int p_device, int p_axis, const JoyAxis& p_value);
+ uint32_t joy_axis(uint32_t p_last_id, int p_device, int p_axis, const JoyAxis &p_value);
uint32_t joy_hat(uint32_t p_last_id, int p_device, int p_val);
- virtual void add_joy_mapping(String p_mapping, bool p_update_existing=false);
+ virtual void add_joy_mapping(String p_mapping, bool p_update_existing = false);
virtual void remove_joy_mapping(String p_guid);
virtual bool is_joy_known(int p_device);
virtual String get_joy_guid(int p_device) const;
virtual String get_joy_button_string(int p_button);
virtual String get_joy_axis_string(int p_axis);
- virtual int get_joy_axis_index_from_string(String p_axis);
- virtual int get_joy_button_index_from_string(String p_button);
+ virtual int get_joy_axis_index_from_string(String p_axis);
+ virtual int get_joy_button_index_from_string(String p_button);
int get_unused_joy_id();
diff --git a/main/main.cpp b/main/main.cpp
index 32aea6a4a5..f905e22070 100644
--- a/main/main.cpp
+++ b/main/main.cpp
@@ -27,31 +27,31 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "main.h"
-#include "os/os.h"
-#include "global_config.h"
-#include "splash.h"
#include "core/register_core_types.h"
-#include "scene/register_scene_types.h"
#include "drivers/register_driver_types.h"
-#include "servers/register_server_types.h"
+#include "global_config.h"
+#include "message_queue.h"
#include "modules/register_module_types.h"
+#include "os/os.h"
+#include "scene/register_scene_types.h"
#include "script_debugger_local.h"
#include "script_debugger_remote.h"
-#include "message_queue.h"
+#include "servers/register_server_types.h"
+#include "splash.h"
#include "input_map.h"
#include "io/resource_loader.h"
#include "scene/main/scene_main_loop.h"
#include "servers/audio_server.h"
-#include "script_language.h"
#include "io/resource_loader.h"
+#include "script_language.h"
+#include "core/io/ip.h"
#include "main/tests/test_main.h"
#include "os/dir_access.h"
-#include "core/io/ip.h"
-#include "scene/resources/packed_scene.h"
#include "scene/main/viewport.h"
+#include "scene/resources/packed_scene.h"
#ifdef TOOLS_ENABLED
#include "editor/doc/doc_data.h"
@@ -62,57 +62,56 @@
#include "io/file_access_network.h"
#include "servers/physics_2d_server.h"
-#include "core/io/stream_peer_tcp.h"
-#include "core/os/thread.h"
#include "core/io/file_access_pack.h"
#include "core/io/file_access_zip.h"
#include "core/io/stream_peer_ssl.h"
-#include "translation.h"
-#include "version.h"
+#include "core/io/stream_peer_tcp.h"
+#include "core/os/thread.h"
#include "main/input_default.h"
#include "performance.h"
+#include "translation.h"
+#include "version.h"
-static GlobalConfig *globals=NULL;
-static Engine *engine=NULL;
-static InputMap *input_map=NULL;
-static bool _start_success=false;
-static ScriptDebugger *script_debugger=NULL;
-AudioServer *audio_server=NULL;
+static GlobalConfig *globals = NULL;
+static Engine *engine = NULL;
+static InputMap *input_map = NULL;
+static bool _start_success = false;
+static ScriptDebugger *script_debugger = NULL;
+AudioServer *audio_server = NULL;
-static MessageQueue *message_queue=NULL;
+static MessageQueue *message_queue = NULL;
static Performance *performance = NULL;
-static PackedData *packed_data=NULL;
+static PackedData *packed_data = NULL;
#ifdef MINIZIP_ENABLED
-static ZipArchive *zip_packed_data=NULL;
+static ZipArchive *zip_packed_data = NULL;
#endif
-static FileAccessNetworkClient *file_access_network_client=NULL;
+static FileAccessNetworkClient *file_access_network_client = NULL;
static TranslationServer *translation_server = NULL;
static OS::VideoMode video_mode;
-static bool init_maximized=false;
-static bool init_windowed=false;
-static bool init_fullscreen=false;
-static bool init_use_custom_pos=false;
-static bool debug_collisions=false;
-static bool debug_navigation=false;
-static int frame_delay=0;
+static bool init_maximized = false;
+static bool init_windowed = false;
+static bool init_fullscreen = false;
+static bool init_use_custom_pos = false;
+static bool debug_collisions = false;
+static bool debug_navigation = false;
+static int frame_delay = 0;
static Vector2 init_custom_pos;
-static int video_driver_idx=-1;
-static int audio_driver_idx=-1;
+static int video_driver_idx = -1;
+static int audio_driver_idx = -1;
static String locale;
-static bool use_debug_profiler=false;
-static bool force_lowdpi=false;
-static int init_screen=-1;
-static bool use_vsync=true;
-static bool editor=false;
+static bool use_debug_profiler = false;
+static bool force_lowdpi = false;
+static int init_screen = -1;
+static bool use_vsync = true;
+static bool editor = false;
-static String unescape_cmdline(const String& p_str) {
+static String unescape_cmdline(const String &p_str) {
- return p_str.replace("%20"," ");
+ return p_str.replace("%20", " ");
}
-
//#define DEBUG_INIT
#ifdef DEBUG_INIT
@@ -121,10 +120,10 @@ static String unescape_cmdline(const String& p_str) {
#define MAIN_PRINT(m_txt)
#endif
-void Main::print_help(const char* p_binary) {
+void Main::print_help(const char *p_binary) {
- OS::get_singleton()->print(VERSION_FULL_NAME" (c) 2008-2017 Juan Linietsky, Ariel Manzur.\n");
- OS::get_singleton()->print("Usage: %s [options] [scene]\n",p_binary);
+ OS::get_singleton()->print(VERSION_FULL_NAME " (c) 2008-2017 Juan Linietsky, Ariel Manzur.\n");
+ OS::get_singleton()->print("Usage: %s [options] [scene]\n", p_binary);
OS::get_singleton()->print("Options:\n");
OS::get_singleton()->print("\t-path [dir] : Path to a game, containing godot.cfg\n");
#ifdef TOOLS_ENABLED
@@ -132,9 +131,9 @@ void Main::print_help(const char* p_binary) {
#endif
OS::get_singleton()->print("\t-test [test] : Run a test.\n");
OS::get_singleton()->print("\t\t(");
- const char **test_names=tests_get_names();
- const char* coma = "";
- while(*test_names) {
+ const char **test_names = tests_get_names();
+ const char *coma = "";
+ while (*test_names) {
OS::get_singleton()->print("%s%s", coma, *test_names);
test_names++;
@@ -148,23 +147,23 @@ void Main::print_help(const char* p_binary) {
OS::get_singleton()->print("\t-mx\t\t Request Maximized\n");
OS::get_singleton()->print("\t-w\t\t Request Windowed\n");
OS::get_singleton()->print("\t-vd DRIVER\t : Video Driver (");
- for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
+ for (int i = 0; i < OS::get_singleton()->get_video_driver_count(); i++) {
- if (i!=0)
+ if (i != 0)
OS::get_singleton()->print(", ");
- OS::get_singleton()->print("%s",OS::get_singleton()->get_video_driver_name(i));
+ OS::get_singleton()->print("%s", OS::get_singleton()->get_video_driver_name(i));
}
OS::get_singleton()->print(")\n");
OS::get_singleton()->print("\t-ldpi\t : Force low-dpi mode (OSX Only)\n");
OS::get_singleton()->print("\t-ad DRIVER\t : Audio Driver (");
- for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
+ for (int i = 0; i < OS::get_singleton()->get_audio_driver_count(); i++) {
- if (i!=0)
+ if (i != 0)
OS::get_singleton()->print(", ");
- OS::get_singleton()->print("%s",OS::get_singleton()->get_audio_driver_name(i));
+ OS::get_singleton()->print("%s", OS::get_singleton()->get_audio_driver_name(i));
}
- OS::get_singleton()->print(")\n");
+ OS::get_singleton()->print(")\n");
OS::get_singleton()->print("\t-rthread <mode>\t : Render Thread Mode ('unsafe', 'safe', 'separate').\n");
OS::get_singleton()->print("\t-s,-script [script] : Run a script.\n");
OS::get_singleton()->print("\t-d,-debug : Debug (local stdout debugger).\n");
@@ -183,14 +182,13 @@ void Main::print_help(const char* p_binary) {
#endif
}
-
-Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {
+Error Main::setup(const char *execpath, int argc, char *argv[], bool p_second_phase) {
RID_OwnerBase::init_rid();
OS::get_singleton()->initialize_core();
- engine = memnew( Engine );
+ engine = memnew(Engine);
ClassDB::init();
@@ -201,17 +199,16 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
MAIN_PRINT("Main: Initialize Globals");
-
Thread::_main_thread_id = Thread::get_caller_ID();
- globals = memnew( GlobalConfig );
- input_map = memnew( InputMap );
+ globals = memnew(GlobalConfig);
+ input_map = memnew(InputMap);
register_core_settings(); //here globals is present
- translation_server = memnew( TranslationServer );
- performance = memnew( Performance );
- globals->add_singleton(GlobalConfig::Singleton("Performance",performance));
+ translation_server = memnew(TranslationServer);
+ performance = memnew(Performance);
+ globals->add_singleton(GlobalConfig::Singleton("Performance", performance));
MAIN_PRINT("Main: Parse CMDLine");
@@ -219,34 +216,34 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
List<String> args;
List<String> main_args;
- for(int i=0;i<argc;i++) {
+ for (int i = 0; i < argc; i++) {
args.push_back(String::utf8(argv[i]));
}
- List<String>::Element *I=args.front();
+ List<String>::Element *I = args.front();
- I=args.front();
+ I = args.front();
while (I) {
- I->get()=unescape_cmdline(I->get().strip_escapes());
+ I->get() = unescape_cmdline(I->get().strip_escapes());
//print_line("CMD: "+I->get());
- I=I->next();
+ I = I->next();
}
- I=args.front();
+ I = args.front();
video_mode = OS::get_singleton()->get_default_video_mode();
- String video_driver="";
- String audio_driver="";
- String game_path=".";
+ String video_driver = "";
+ String audio_driver = "";
+ String game_path = ".";
String debug_mode;
String debug_host;
String main_pack;
- bool quiet_stdout=false;
- int rtm=-1;
+ bool quiet_stdout = false;
+ int rtm = -1;
String remotefs;
String remotefs_pass;
@@ -255,10 +252,10 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
List<String> pack_list;
Vector<String> breakpoints;
- bool use_custom_res=true;
- bool force_res=false;
+ bool use_custom_res = true;
+ bool force_res = false;
- I=args.front();
+ I = args.front();
packed_data = PackedData::get_singleton();
if (!packed_data)
@@ -276,233 +273,207 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
packed_data->add_pack_source(zip_packed_data);
#endif
+ while (I) {
-
- while(I) {
-
- List<String>::Element *N=I->next();
+ List<String>::Element *N = I->next();
if (I->get() == "-noop") {
// no op
- } else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution
+ } else if (I->get() == "-h" || I->get() == "--help" || I->get() == "/?") { // resolution
goto error;
-
- } else if (I->get()=="-r") { // resolution
+ } else if (I->get() == "-r") { // resolution
if (I->next()) {
- String vm=I->next()->get();
+ String vm = I->next()->get();
- if (vm.find("x")==-1) { // invalid parameter format
+ if (vm.find("x") == -1) { // invalid parameter format
- OS::get_singleton()->print("Invalid -r argument: %s\n",vm.utf8().get_data());
+ OS::get_singleton()->print("Invalid -r argument: %s\n", vm.utf8().get_data());
goto error;
-
-
}
- int w=vm.get_slice("x",0).to_int();
- int h=vm.get_slice("x",1).to_int();
+ int w = vm.get_slice("x", 0).to_int();
+ int h = vm.get_slice("x", 1).to_int();
- if (w==0 || h==0) {
+ if (w == 0 || h == 0) {
OS::get_singleton()->print("Invalid -r resolution, x and y must be >0\n");
goto error;
-
}
- video_mode.width=w;
- video_mode.height=h;
- force_res=true;
+ video_mode.width = w;
+ video_mode.height = h;
+ force_res = true;
- N=I->next()->next();
+ N = I->next()->next();
} else {
OS::get_singleton()->print("Invalid -p argument, needs resolution\n");
goto error;
-
-
}
- } else if (I->get()=="-p") { // position
+ } else if (I->get() == "-p") { // position
if (I->next()) {
- String vm=I->next()->get();
+ String vm = I->next()->get();
- if (vm.find("x")==-1) { // invalid parameter format
+ if (vm.find("x") == -1) { // invalid parameter format
- OS::get_singleton()->print("Invalid -p argument: %s\n",vm.utf8().get_data());
+ OS::get_singleton()->print("Invalid -p argument: %s\n", vm.utf8().get_data());
goto error;
-
-
}
- int x=vm.get_slice("x",0).to_int();
- int y=vm.get_slice("x",1).to_int();
+ int x = vm.get_slice("x", 0).to_int();
+ int y = vm.get_slice("x", 1).to_int();
- init_custom_pos=Point2(x,y);
- init_use_custom_pos=true;
+ init_custom_pos = Point2(x, y);
+ init_use_custom_pos = true;
- N=I->next()->next();
+ N = I->next()->next();
} else {
OS::get_singleton()->print("Invalid -r argument, needs position\n");
goto error;
-
-
}
+ } else if (I->get() == "-mx") { // video driver
- } else if (I->get()=="-mx") { // video driver
+ init_maximized = true;
+ } else if (I->get() == "-w") { // video driver
- init_maximized=true;
- } else if (I->get()=="-w") { // video driver
+ init_windowed = true;
+ } else if (I->get() == "-profile") { // video driver
- init_windowed=true;
- } else if (I->get()=="-profile") { // video driver
-
- use_debug_profiler=true;
- } else if (I->get()=="-vd") { // video driver
+ use_debug_profiler = true;
+ } else if (I->get() == "-vd") { // video driver
if (I->next()) {
- video_driver=I->next()->get();
- N=I->next()->next();
+ video_driver = I->next()->get();
+ N = I->next()->next();
} else {
OS::get_singleton()->print("Invalid -cd argument, needs driver name\n");
goto error;
-
}
- } else if (I->get()=="-lang") { // language
+ } else if (I->get() == "-lang") { // language
if (I->next()) {
- locale=I->next()->get();
- N=I->next()->next();
+ locale = I->next()->get();
+ N = I->next()->next();
} else {
OS::get_singleton()->print("Invalid -lang argument, needs language code\n");
goto error;
-
}
- } else if (I->get()=="-ldpi") { // language
+ } else if (I->get() == "-ldpi") { // language
- force_lowdpi=true;
- } else if (I->get()=="-rfs") { // language
+ force_lowdpi = true;
+ } else if (I->get() == "-rfs") { // language
if (I->next()) {
- remotefs=I->next()->get();
- N=I->next()->next();
+ remotefs = I->next()->get();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-rfs_pass") { // language
+ } else if (I->get() == "-rfs_pass") { // language
if (I->next()) {
- remotefs_pass=I->next()->get();
- N=I->next()->next();
+ remotefs_pass = I->next()->get();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-rthread") { // language
+ } else if (I->get() == "-rthread") { // language
if (I->next()) {
- if (I->next()->get()=="safe")
- rtm=OS::RENDER_THREAD_SAFE;
- else if (I->next()->get()=="unsafe")
- rtm=OS::RENDER_THREAD_UNSAFE;
- else if (I->next()->get()=="separate")
- rtm=OS::RENDER_SEPARATE_THREAD;
-
+ if (I->next()->get() == "safe")
+ rtm = OS::RENDER_THREAD_SAFE;
+ else if (I->next()->get() == "unsafe")
+ rtm = OS::RENDER_THREAD_UNSAFE;
+ else if (I->next()->get() == "separate")
+ rtm = OS::RENDER_SEPARATE_THREAD;
- N=I->next()->next();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-ad") { // video driver
+ } else if (I->get() == "-ad") { // video driver
if (I->next()) {
- audio_driver=I->next()->get();
- N=I->next()->next();
+ audio_driver = I->next()->get();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-f") { // fullscreen
+ } else if (I->get() == "-f") { // fullscreen
//video_mode.fullscreen=false;
- init_fullscreen=true;
- } else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor
+ init_fullscreen = true;
+ } else if (I->get() == "-e" || I->get() == "-editor") { // fonud editor
- editor=true;
- } else if (I->get()=="-nowindow") { // fullscreen
+ editor = true;
+ } else if (I->get() == "-nowindow") { // fullscreen
OS::get_singleton()->set_no_window_mode(true);
- } else if (I->get()=="-quiet") { // fullscreen
+ } else if (I->get() == "-quiet") { // fullscreen
- quiet_stdout=true;
- } else if (I->get()=="-v") { // fullscreen
- OS::get_singleton()->_verbose_stdout=true;
- } else if (I->get()=="-path") { // resolution
+ quiet_stdout = true;
+ } else if (I->get() == "-v") { // fullscreen
+ OS::get_singleton()->_verbose_stdout = true;
+ } else if (I->get() == "-path") { // resolution
if (I->next()) {
String p = I->next()->get();
- if (OS::get_singleton()->set_cwd(p)==OK) {
+ if (OS::get_singleton()->set_cwd(p) == OK) {
//nothing
} else {
- game_path=I->next()->get(); //use game_path instead
+ game_path = I->next()->get(); //use game_path instead
}
- N=I->next()->next();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-bp") { // /breakpoints
+ } else if (I->get() == "-bp") { // /breakpoints
if (I->next()) {
String bplist = I->next()->get();
- breakpoints= bplist.split(",");
- N=I->next()->next();
+ breakpoints = bplist.split(",");
+ N = I->next()->next();
} else {
goto error;
-
}
-
- } else if (I->get()=="-fdelay") { // resolution
+ } else if (I->get() == "-fdelay") { // resolution
if (I->next()) {
- frame_delay=I->next()->get().to_int();
- N=I->next()->next();
+ frame_delay = I->next()->get().to_int();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-timescale") { // resolution
+ } else if (I->get() == "-timescale") { // resolution
if (I->next()) {
Engine::get_singleton()->set_time_scale(I->next()->get().to_double());
- N=I->next()->next();
+ N = I->next()->next();
} else {
goto error;
-
}
-
} else if (I->get() == "-pack") {
if (I->next()) {
@@ -518,66 +489,62 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
if (I->next()) {
- main_pack=I->next()->get();
+ main_pack = I->next()->get();
N = I->next()->next();
} else {
goto error;
};
- } else if (I->get()=="-debug" || I->get()=="-d") {
- debug_mode="local";
- } else if (I->get()=="-debugcol" || I->get()=="-dc") {
- debug_collisions=true;
- } else if (I->get()=="-debugnav" || I->get()=="-dn") {
- debug_navigation=true;
- } else if (I->get()=="-editor_scene") {
+ } else if (I->get() == "-debug" || I->get() == "-d") {
+ debug_mode = "local";
+ } else if (I->get() == "-debugcol" || I->get() == "-dc") {
+ debug_collisions = true;
+ } else if (I->get() == "-debugnav" || I->get() == "-dn") {
+ debug_navigation = true;
+ } else if (I->get() == "-editor_scene") {
if (I->next()) {
- GlobalConfig::get_singleton()->set("editor_scene",game_path=I->next()->get());
+ GlobalConfig::get_singleton()->set("editor_scene", game_path = I->next()->get());
} else {
goto error;
-
}
- } else if (I->get()=="-rdebug") {
+ } else if (I->get() == "-rdebug") {
if (I->next()) {
- debug_mode="remote";
- debug_host=I->next()->get();
- if (debug_host.find(":")==-1) { //wrong host
+ debug_mode = "remote";
+ debug_host = I->next()->get();
+ if (debug_host.find(":") == -1) { //wrong host
OS::get_singleton()->print("Invalid debug host string\n");
goto error;
}
- N=I->next()->next();
+ N = I->next()->next();
} else {
goto error;
-
}
- } else if (I->get()=="-epid") {
+ } else if (I->get() == "-epid") {
if (I->next()) {
- int editor_pid=I->next()->get().to_int();
- GlobalConfig::get_singleton()->set("editor_pid",editor_pid);
- N=I->next()->next();
+ int editor_pid = I->next()->get().to_int();
+ GlobalConfig::get_singleton()->set("editor_pid", editor_pid);
+ N = I->next()->next();
} else {
goto error;
-
}
} else {
//test for game path
- bool gpfound=false;
+ bool gpfound = false;
- if (!I->get().begins_with("-") && game_path=="") {
- DirAccess* da = DirAccess::open(I->get());
- if (da!=NULL) {
- game_path=I->get();
- gpfound=true;
+ if (!I->get().begins_with("-") && game_path == "") {
+ DirAccess *da = DirAccess::open(I->get());
+ if (da != NULL) {
+ game_path = I->get();
+ gpfound = true;
memdelete(da);
}
-
}
if (!gpfound) {
@@ -585,51 +552,50 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
}
}
- I=N;
+ I = N;
}
- GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc",60);
+ GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc", 60);
- GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second",2048);
- GLOBAL_DEF("network/debug/remote_port",6007);
+ GLOBAL_DEF("network/debug/max_remote_stdout_chars_per_second", 2048);
+ GLOBAL_DEF("network/debug/remote_port", 6007);
if (debug_mode == "remote") {
- ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
+ ScriptDebuggerRemote *sdr = memnew(ScriptDebuggerRemote);
uint16_t debug_port = GLOBAL_GET("network/debug/remote_port");
- if (debug_host.find(":")!=-1) {
- debug_port=debug_host.get_slicec(':',1).to_int();
- debug_host=debug_host.get_slicec(':',0);
+ if (debug_host.find(":") != -1) {
+ debug_port = debug_host.get_slicec(':', 1).to_int();
+ debug_host = debug_host.get_slicec(':', 0);
}
- Error derr = sdr->connect_to_host(debug_host,debug_port);
+ Error derr = sdr->connect_to_host(debug_host, debug_port);
- if (derr!=OK) {
+ if (derr != OK) {
memdelete(sdr);
} else {
- script_debugger=sdr;
+ script_debugger = sdr;
}
- } else if (debug_mode=="local") {
-
- script_debugger = memnew( ScriptDebuggerLocal );
+ } else if (debug_mode == "local") {
+ script_debugger = memnew(ScriptDebuggerLocal);
}
FileAccessNetwork::configure();
- if (remotefs!="") {
+ if (remotefs != "") {
- file_access_network_client=memnew(FileAccessNetworkClient);
+ file_access_network_client = memnew(FileAccessNetworkClient);
int port;
- if (remotefs.find(":")!=-1) {
- port=remotefs.get_slicec(':',1).to_int();
- remotefs=remotefs.get_slicec(':',0);
+ if (remotefs.find(":") != -1) {
+ port = remotefs.get_slicec(':', 1).to_int();
+ remotefs = remotefs.get_slicec(':', 0);
} else {
- port=6010;
+ port = 6010;
}
- Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
+ Error err = file_access_network_client->connect(remotefs, port, remotefs_pass);
if (err) {
- OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
+ OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n", remotefs.utf8().get_data(), port);
goto error;
}
@@ -638,36 +604,34 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
if (script_debugger) {
//there is a debugger, parse breakpoints
- for(int i=0;i<breakpoints.size();i++) {
+ for (int i = 0; i < breakpoints.size(); i++) {
String bp = breakpoints[i];
- int sp=bp.find_last(":");
- if (sp==-1) {
- ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
- ERR_CONTINUE(sp==-1);
+ int sp = bp.find_last(":");
+ if (sp == -1) {
+ ERR_EXPLAIN("Invalid breakpoint: '" + bp + "', expected file:line format.");
+ ERR_CONTINUE(sp == -1);
}
- script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
+ script_debugger->insert_breakpoint(bp.substr(sp + 1, bp.length()).to_int(), bp.substr(0, sp));
}
}
-
#ifdef TOOLS_ENABLED
if (editor) {
packed_data->set_disabled(true);
globals->set_disable_platform_override(true);
- StreamPeerSSL::initialize_certs=false; //will be initialized by editor
+ StreamPeerSSL::initialize_certs = false; //will be initialized by editor
}
#endif
-
- if (globals->setup(game_path,main_pack)!=OK) {
+ if (globals->setup(game_path, main_pack) != OK) {
#ifdef TOOLS_ENABLED
- editor=false;
+ editor = false;
#else
- OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());
+ OS::get_singleton()->print("error: Couldn't load game path '%s'\n", game_path.ascii().get_data());
goto error;
#endif
@@ -675,26 +639,26 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
if (editor) {
main_args.push_back("-editor");
- init_maximized=true;
- use_custom_res=false;
+ init_maximized = true;
+ use_custom_res = false;
}
if (bool(GlobalConfig::get_singleton()->get("application/disable_stdout"))) {
- quiet_stdout=true;
+ quiet_stdout = true;
}
if (bool(GlobalConfig::get_singleton()->get("application/disable_stderr"))) {
_print_error_enabled = false;
};
if (quiet_stdout)
- _print_line_enabled=false;
+ _print_line_enabled = false;
OS::get_singleton()->set_cmdline(execpath, main_args);
#ifdef TOOLS_ENABLED
- if (main_args.size()==0 && (!GlobalConfig::get_singleton()->has("application/main_loop_type")) && (!GlobalConfig::get_singleton()->has("application/main_scene") || String(GlobalConfig::get_singleton()->get("application/main_scene"))==""))
- use_custom_res=false; //project manager (run without arguments)
+ if (main_args.size() == 0 && (!GlobalConfig::get_singleton()->has("application/main_loop_type")) && (!GlobalConfig::get_singleton()->has("application/main_scene") || String(GlobalConfig::get_singleton()->get("application/main_scene")) == ""))
+ use_custom_res = false; //project manager (run without arguments)
#endif
@@ -703,148 +667,141 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
else
input_map->load_from_globals(); //keys for game
- if (video_driver=="") // specified in godot.cfg
- video_driver=GLOBAL_DEF("display/driver/name",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));
+ if (video_driver == "") // specified in godot.cfg
+ video_driver = GLOBAL_DEF("display/driver/name", Variant((const char *)OS::get_singleton()->get_video_driver_name(0)));
if (!force_res && use_custom_res && globals->has("display/window/width"))
- video_mode.width=globals->get("display/window/width");
- if (!force_res &&use_custom_res && globals->has("display/window/height"))
- video_mode.height=globals->get("display/window/height");
+ video_mode.width = globals->get("display/window/width");
+ if (!force_res && use_custom_res && globals->has("display/window/height"))
+ video_mode.height = globals->get("display/window/height");
if (!editor && (!bool(globals->get("display/window/allow_hidpi")) || force_lowdpi)) {
- OS::get_singleton()->_allow_hidpi=false;
+ OS::get_singleton()->_allow_hidpi = false;
}
if (use_custom_res && globals->has("display/window/fullscreen"))
- video_mode.fullscreen=globals->get("display/window/fullscreen");
+ video_mode.fullscreen = globals->get("display/window/fullscreen");
if (use_custom_res && globals->has("display/window/resizable"))
- video_mode.resizable=globals->get("display/window/resizable");
+ video_mode.resizable = globals->get("display/window/resizable");
if (use_custom_res && globals->has("display/window/borderless"))
video_mode.borderless_window = globals->get("display/window/borderless");
if (!force_res && use_custom_res && globals->has("display/window/test_width") && globals->has("display/window/test_height")) {
int tw = globals->get("display/window/test_width");
int th = globals->get("display/window/test_height");
- if (tw>0 && th>0) {
- video_mode.width=tw;
- video_mode.height=th;
+ if (tw > 0 && th > 0) {
+ video_mode.width = tw;
+ video_mode.height = th;
}
}
-
- GLOBAL_DEF("display/window/width",video_mode.width);
- GLOBAL_DEF("display/window/height",video_mode.height);
- GLOBAL_DEF("display/window/allow_hidpi",false);
- GLOBAL_DEF("display/window/fullscreen",video_mode.fullscreen);
- GLOBAL_DEF("display/window/resizable",video_mode.resizable);
+ GLOBAL_DEF("display/window/width", video_mode.width);
+ GLOBAL_DEF("display/window/height", video_mode.height);
+ GLOBAL_DEF("display/window/allow_hidpi", false);
+ GLOBAL_DEF("display/window/fullscreen", video_mode.fullscreen);
+ GLOBAL_DEF("display/window/resizable", video_mode.resizable);
GLOBAL_DEF("display/window/borderless", video_mode.borderless_window);
use_vsync = GLOBAL_DEF("display/window/use_vsync", use_vsync);
- GLOBAL_DEF("display/window/test_width",0);
- GLOBAL_DEF("display/window/test_height",0);
- Engine::get_singleton()->_pixel_snap=GLOBAL_DEF("rendering/2d/use_pixel_snap",false);
- OS::get_singleton()->_keep_screen_on=GLOBAL_DEF("display/energy_saving/keep_screen_on",true);
- if (rtm==-1) {
- rtm=GLOBAL_DEF("rendering/threads/thread_model",OS::RENDER_THREAD_SAFE);
- if (rtm>=1) //hack for now
- rtm=1;
-
+ GLOBAL_DEF("display/window/test_width", 0);
+ GLOBAL_DEF("display/window/test_height", 0);
+ Engine::get_singleton()->_pixel_snap = GLOBAL_DEF("rendering/2d/use_pixel_snap", false);
+ OS::get_singleton()->_keep_screen_on = GLOBAL_DEF("display/energy_saving/keep_screen_on", true);
+ if (rtm == -1) {
+ rtm = GLOBAL_DEF("rendering/threads/thread_model", OS::RENDER_THREAD_SAFE);
+ if (rtm >= 1) //hack for now
+ rtm = 1;
}
- if (rtm>=0 && rtm<3) {
+ if (rtm >= 0 && rtm < 3) {
if (editor) {
- rtm=OS::RENDER_THREAD_SAFE;
+ rtm = OS::RENDER_THREAD_SAFE;
}
- OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);
+ OS::get_singleton()->_render_thread_mode = OS::RenderThreadMode(rtm);
}
-
-
/* Determine Video Driver */
- if (audio_driver=="") { // specified in godot.cfg
- audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));
+ if (audio_driver == "") { // specified in godot.cfg
+ audio_driver = GLOBAL_DEF("audio/driver", OS::get_singleton()->get_audio_driver_name(0));
}
+ for (int i = 0; i < OS::get_singleton()->get_video_driver_count(); i++) {
- for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
-
- if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {
+ if (video_driver == OS::get_singleton()->get_video_driver_name(i)) {
- video_driver_idx=i;
+ video_driver_idx = i;
break;
}
}
- if (video_driver_idx<0) {
+ if (video_driver_idx < 0) {
- OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
+ OS::get_singleton()->alert("Invalid Video Driver: " + video_driver);
video_driver_idx = 0;
//goto error;
}
- for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
+ for (int i = 0; i < OS::get_singleton()->get_audio_driver_count(); i++) {
- if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {
+ if (audio_driver == OS::get_singleton()->get_audio_driver_name(i)) {
- audio_driver_idx=i;
+ audio_driver_idx = i;
break;
}
}
- if (audio_driver_idx<0) {
+ if (audio_driver_idx < 0) {
- OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
+ OS::get_singleton()->alert("Invalid Audio Driver: " + audio_driver);
audio_driver_idx = 0;
//goto error;
}
{
- String orientation = GLOBAL_DEF("display/handheld/orientation","landscape");
+ String orientation = GLOBAL_DEF("display/handheld/orientation", "landscape");
- if (orientation=="portrait")
+ if (orientation == "portrait")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
- else if (orientation=="reverse_landscape")
+ else if (orientation == "reverse_landscape")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
- else if (orientation=="reverse_portrait")
+ else if (orientation == "reverse_portrait")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
- else if (orientation=="sensor_landscape")
+ else if (orientation == "sensor_landscape")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
- else if (orientation=="sensor_portrait")
+ else if (orientation == "sensor_portrait")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
- else if (orientation=="sensor")
+ else if (orientation == "sensor")
OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
else
OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
}
-
- Engine::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/common/fixed_fps",60));
- Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/fps/force_fps",0));
+ Engine::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/common/fixed_fps", 60));
+ Engine::get_singleton()->set_target_fps(GLOBAL_DEF("debug/fps/force_fps", 0));
GLOBAL_DEF("debug/stdout/print_fps", OS::get_singleton()->is_stdout_verbose());
if (!OS::get_singleton()->_verbose_stdout) //overrided
- OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/stdout/verbose_stdout",false);
+ OS::get_singleton()->_verbose_stdout = GLOBAL_DEF("debug/stdout/verbose_stdout", false);
- if (frame_delay==0) {
- frame_delay=GLOBAL_DEF("application/frame_delay_msec",0);
+ if (frame_delay == 0) {
+ frame_delay = GLOBAL_DEF("application/frame_delay_msec", 0);
}
Engine::get_singleton()->set_frame_delay(frame_delay);
- message_queue = memnew( MessageQueue );
+ message_queue = memnew(MessageQueue);
GlobalConfig::get_singleton()->register_global_defaults();
if (p_second_phase)
return setup2();
-
return OK;
- error:
+error:
- video_driver="";
- audio_driver="";
- game_path="";
+ video_driver = "";
+ audio_driver = "";
+ game_path = "";
args.clear();
main_args.clear();
@@ -856,7 +813,7 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
if (input_map)
memdelete(input_map);
if (translation_server)
- memdelete( translation_server );
+ memdelete(translation_server);
if (globals)
memdelete(globals);
if (engine)
@@ -868,9 +825,9 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
if (file_access_network_client)
memdelete(file_access_network_client);
-// Note 1: *zip_packed_data live into *packed_data
-// Note 2: PackedData::~PackedData destroy this.
-/*
+ // Note 1: *zip_packed_data live into *packed_data
+ // Note 2: PackedData::~PackedData destroy this.
+ /*
#ifdef MINIZIP_ENABLED
if (zip_packed_data)
memdelete( zip_packed_data );
@@ -883,24 +840,23 @@ Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phas
OS::get_singleton()->_cmdline.clear();
if (message_queue)
- memdelete( message_queue);
+ memdelete(message_queue);
OS::get_singleton()->finalize_core();
- locale=String();
+ locale = String();
return ERR_INVALID_PARAMETER;
}
Error Main::setup2() {
-
- OS::get_singleton()->initialize(video_mode,video_driver_idx,audio_driver_idx);
+ OS::get_singleton()->initialize(video_mode, video_driver_idx, audio_driver_idx);
if (init_use_custom_pos) {
OS::get_singleton()->set_window_position(init_custom_pos);
}
//right moment to create and initialize the audio server
- audio_server = memnew( AudioServer );
+ audio_server = memnew(AudioServer);
audio_server->init();
OS::get_singleton()->set_use_vsync(use_vsync);
@@ -909,12 +865,12 @@ Error Main::setup2() {
MAIN_PRINT("Main: Setup Logo");
- bool show_logo=true;
+ bool show_logo = true;
#ifdef JAVASCRIPT_ENABLED
- show_logo=false;
+ show_logo = false;
#endif
- if (init_screen!=-1) {
+ if (init_screen != -1) {
OS::get_singleton()->set_current_screen(init_screen);
}
if (init_windowed) {
@@ -926,32 +882,32 @@ Error Main::setup2() {
}
MAIN_PRINT("Main: Load Remaps");
- Color clear = GLOBAL_DEF("rendering/viewport/default_clear_color",Color(0.3,0.3,0.3));
+ Color clear = GLOBAL_DEF("rendering/viewport/default_clear_color", Color(0.3, 0.3, 0.3));
VisualServer::get_singleton()->set_default_clear_color(clear);
if (show_logo) { //boot logo!
- String boot_logo_path=GLOBAL_DEF("application/boot_splash",String());
- bool boot_logo_scale=GLOBAL_DEF("application/boot_splash_fullsize",true);
- GlobalConfig::get_singleton()->set_custom_property_info("application/boot_splash",PropertyInfo(Variant::STRING,"application/boot_splash",PROPERTY_HINT_FILE,"*.png"));
+ String boot_logo_path = GLOBAL_DEF("application/boot_splash", String());
+ bool boot_logo_scale = GLOBAL_DEF("application/boot_splash_fullsize", true);
+ GlobalConfig::get_singleton()->set_custom_property_info("application/boot_splash", PropertyInfo(Variant::STRING, "application/boot_splash", PROPERTY_HINT_FILE, "*.png"));
Image boot_logo;
boot_logo_path = boot_logo_path.strip_edges();
- if (boot_logo_path!=String() /*&& FileAccess::exists(boot_logo_path)*/) {
- print_line("Boot splash path: "+boot_logo_path);
+ if (boot_logo_path != String() /*&& FileAccess::exists(boot_logo_path)*/) {
+ print_line("Boot splash path: " + boot_logo_path);
Error err = boot_logo.load(boot_logo_path);
if (err)
ERR_PRINTS("Non-existing or invalid boot splash at: " + boot_logo_path + ". Loading default splash.");
}
if (!boot_logo.empty()) {
- OS::get_singleton()->_msec_splash=OS::get_singleton()->get_ticks_msec();
+ OS::get_singleton()->_msec_splash = OS::get_singleton()->get_ticks_msec();
Color boot_bg = GLOBAL_DEF("application/boot_bg_color", clear);
- VisualServer::get_singleton()->set_boot_image(boot_logo, boot_bg,boot_logo_scale);
+ VisualServer::get_singleton()->set_boot_image(boot_logo, boot_bg, boot_logo_scale);
#ifndef TOOLS_ENABLED
- //no tools, so free the boot logo (no longer needed)
- //GlobalConfig::get_singleton()->set("application/boot_logo",Image());
+//no tools, so free the boot logo (no longer needed)
+//GlobalConfig::get_singleton()->set("application/boot_logo",Image());
#endif
} else {
@@ -963,7 +919,7 @@ Error Main::setup2() {
MAIN_PRINT("Main: ClearColor");
VisualServer::get_singleton()->set_default_clear_color(boot_splash_bg_color);
MAIN_PRINT("Main: Image");
- VisualServer::get_singleton()->set_boot_image(splash, boot_splash_bg_color,false);
+ VisualServer::get_singleton()->set_boot_image(splash, boot_splash_bg_color, false);
#endif
}
@@ -972,13 +928,13 @@ Error Main::setup2() {
}
MAIN_PRINT("Main: DCC");
- VisualServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("rendering/viewport/default_clear_color",Color(0.3,0.3,0.3)));
+ VisualServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("rendering/viewport/default_clear_color", Color(0.3, 0.3, 0.3)));
MAIN_PRINT("Main: END");
- GLOBAL_DEF("application/icon",String());
- GlobalConfig::get_singleton()->set_custom_property_info("application/icon",PropertyInfo(Variant::STRING,"application/icon",PROPERTY_HINT_FILE,"*.png,*.webp"));
+ GLOBAL_DEF("application/icon", String());
+ GlobalConfig::get_singleton()->set_custom_property_info("application/icon", PropertyInfo(Variant::STRING, "application/icon", PROPERTY_HINT_FILE, "*.png,*.webp"));
- if (bool(GLOBAL_DEF("display/handheld/emulate_touchscreen",false))) {
+ if (bool(GLOBAL_DEF("display/handheld/emulate_touchscreen", false))) {
if (!OS::get_singleton()->has_touchscreen_ui_hint() && Input::get_singleton() && !editor) {
//only if no touchscreen ui hint, set emulation
InputDefault *id = Input::get_singleton()->cast_to<InputDefault>();
@@ -987,8 +943,6 @@ Error Main::setup2() {
}
}
-
-
MAIN_PRINT("Main: Load Remaps");
MAIN_PRINT("Main: Load Scene Types");
@@ -996,18 +950,18 @@ Error Main::setup2() {
register_scene_types();
register_server_types();
- GLOBAL_DEF("display/mouse_cursor/custom_image",String());
- GLOBAL_DEF("display/mouse_cursor/custom_image_hotspot",Vector2());
- GlobalConfig::get_singleton()->set_custom_property_info("display/mouse_cursor/custom_image",PropertyInfo(Variant::STRING,"display/mouse_cursor/custom_image",PROPERTY_HINT_FILE,"*.png,*.webp"));
+ GLOBAL_DEF("display/mouse_cursor/custom_image", String());
+ GLOBAL_DEF("display/mouse_cursor/custom_image_hotspot", Vector2());
+ GlobalConfig::get_singleton()->set_custom_property_info("display/mouse_cursor/custom_image", PropertyInfo(Variant::STRING, "display/mouse_cursor/custom_image", PROPERTY_HINT_FILE, "*.png,*.webp"));
- if (String(GlobalConfig::get_singleton()->get("display/mouse_cursor/custom_image"))!=String()) {
+ if (String(GlobalConfig::get_singleton()->get("display/mouse_cursor/custom_image")) != String()) {
//print_line("use custom cursor");
- Ref<Texture> cursor=ResourceLoader::load(GlobalConfig::get_singleton()->get("display/mouse_cursor/custom_image"));
+ Ref<Texture> cursor = ResourceLoader::load(GlobalConfig::get_singleton()->get("display/mouse_cursor/custom_image"));
if (cursor.is_valid()) {
//print_line("loaded ok");
Vector2 hotspot = GlobalConfig::get_singleton()->get("display/mouse_cursor/custom_image_hotspot");
- Input::get_singleton()->set_custom_mouse_cursor(cursor,hotspot);
+ Input::get_singleton()->set_custom_mouse_cursor(cursor, hotspot);
}
}
#ifdef TOOLS_ENABLED
@@ -1028,43 +982,39 @@ Error Main::setup2() {
MAIN_PRINT("Main: Load Translations");
translation_server->setup(); //register translations, load them, etc.
- if (locale!="") {
+ if (locale != "") {
translation_server->set_locale(locale);
}
translation_server->load_translations();
-
audio_server->load_default_bus_layout();
if (use_debug_profiler && script_debugger) {
script_debugger->profiling_start();
}
- _start_success=true;
- locale=String();
+ _start_success = true;
+ locale = String();
ClassDB::set_current_api(ClassDB::API_NONE); //no more api is registered at this point
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line("CORE API HASH: "+itos(ClassDB::get_api_hash(ClassDB::API_CORE)));
- print_line("EDITOR API HASH: "+itos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
+ print_line("CORE API HASH: " + itos(ClassDB::get_api_hash(ClassDB::API_CORE)));
+ print_line("EDITOR API HASH: " + itos(ClassDB::get_api_hash(ClassDB::API_EDITOR)));
}
MAIN_PRINT("Main: Done");
return OK;
-
}
-
-
bool Main::start() {
- ERR_FAIL_COND_V(!_start_success,false);
+ ERR_FAIL_COND_V(!_start_success, false);
- bool editor=false;
+ bool editor = false;
String doc_tool;
List<String> removal_docs;
- bool doc_base=true;
+ bool doc_base = true;
String game_path;
String script;
String test;
@@ -1072,52 +1022,52 @@ bool Main::start() {
String _export_platform;
String _import;
String _import_script;
- bool noquit=false;
- bool export_debug=false;
+ bool noquit = false;
+ bool export_debug = false;
bool project_manager_request = false;
List<String> args = OS::get_singleton()->get_cmdline_args();
- for (int i=0;i<args.size();i++) {
+ for (int i = 0; i < args.size(); i++) {
//parameters that do not have an argument to the right
- if (args[i]=="-nodocbase") {
- doc_base=false;
- } else if (args[i]=="-noquit") {
- noquit=true;
- } else if (args[i]=="-editor" || args[i]=="-e") {
- editor=true;
+ if (args[i] == "-nodocbase") {
+ doc_base = false;
+ } else if (args[i] == "-noquit") {
+ noquit = true;
+ } else if (args[i] == "-editor" || args[i] == "-e") {
+ editor = true;
} else if (args[i] == "-pm" || args[i] == "-project_manager") {
project_manager_request = true;
} else if (args[i].length() && args[i][0] != '-' && game_path == "") {
- game_path=args[i];
+ game_path = args[i];
}
//parameters that have an argument to the right
- else if (i < (args.size()-1)) {
- bool parsed_pair=true;
- if (args[i]=="-doctool") {
- doc_tool=args[i+1];
- for(int j=i+2; j<args.size();j++)
+ else if (i < (args.size() - 1)) {
+ bool parsed_pair = true;
+ if (args[i] == "-doctool") {
+ doc_tool = args[i + 1];
+ for (int j = i + 2; j < args.size(); j++)
removal_docs.push_back(args[j]);
- } else if (args[i]=="-script" || args[i]=="-s") {
- script=args[i+1];
- } else if (args[i]=="-level" || args[i]=="-l") {
- Engine::get_singleton()->_custom_level=args[i+1];
- } else if (args[i]=="-test") {
- test=args[i+1];
- } else if (args[i]=="-export") {
- editor=true; //needs editor
- _export_platform=args[i+1];
- } else if (args[i]=="-export_debug") {
- editor=true; //needs editor
- _export_platform=args[i+1];
- export_debug=true;
- } else if (args[i]=="-import") {
- editor=true; //needs editor
- _import=args[i+1];
- } else if (args[i]=="-import_script") {
- editor=true; //needs editor
- _import_script=args[i+1];
+ } else if (args[i] == "-script" || args[i] == "-s") {
+ script = args[i + 1];
+ } else if (args[i] == "-level" || args[i] == "-l") {
+ Engine::get_singleton()->_custom_level = args[i + 1];
+ } else if (args[i] == "-test") {
+ test = args[i + 1];
+ } else if (args[i] == "-export") {
+ editor = true; //needs editor
+ _export_platform = args[i + 1];
+ } else if (args[i] == "-export_debug") {
+ editor = true; //needs editor
+ _export_platform = args[i + 1];
+ export_debug = true;
+ } else if (args[i] == "-import") {
+ editor = true; //needs editor
+ _import = args[i + 1];
+ } else if (args[i] == "-import_script") {
+ editor = true; //needs editor
+ _import_script = args[i + 1];
} else {
// The parameter does not match anything known, don't skip the next argument
- parsed_pair=false;
+ parsed_pair = false;
}
if (parsed_pair) {
i++;
@@ -1125,26 +1075,24 @@ bool Main::start() {
}
}
- GLOBAL_DEF("editor/active",editor);
-
+ GLOBAL_DEF("editor/active", editor);
String main_loop_type;
#ifdef TOOLS_ENABLED
- if(doc_tool!="") {
+ if (doc_tool != "") {
DocData doc;
doc.generate(doc_base);
DocData docsrc;
- if (docsrc.load(doc_tool)==OK) {
+ if (docsrc.load(doc_tool) == OK) {
print_line("Doc exists. Merging..");
doc.merge_from(docsrc);
} else {
print_line("No Doc exists. Generating empty.");
-
}
- for(List<String>::Element* E= removal_docs.front(); E; E=E->next()) {
+ for (List<String>::Element *E = removal_docs.front(); E; E = E->next()) {
DocData rmdoc;
if (rmdoc.load(E->get()) == OK) {
print_line(String("Removing classes in ") + E->get());
@@ -1157,76 +1105,72 @@ bool Main::start() {
return false;
}
-
#endif
- if (_export_platform!="") {
- if (game_path=="") {
- String err="Command line param ";
- err+=export_debug?"-export_debug":"-export";
- err+=" passed but no destination path given.\n";
- err+="Please specify the binary's file path to export to. Aborting export.";
+ if (_export_platform != "") {
+ if (game_path == "") {
+ String err = "Command line param ";
+ err += export_debug ? "-export_debug" : "-export";
+ err += " passed but no destination path given.\n";
+ err += "Please specify the binary's file path to export to. Aborting export.";
ERR_PRINT(err.utf8().get_data());
return false;
}
}
- if(script=="" && game_path=="" && String(GLOBAL_DEF("application/main_scene",""))!="") {
- game_path=GLOBAL_DEF("application/main_scene","");
+ if (script == "" && game_path == "" && String(GLOBAL_DEF("application/main_scene", "")) != "") {
+ game_path = GLOBAL_DEF("application/main_scene", "");
}
-
- MainLoop *main_loop=NULL;
+ MainLoop *main_loop = NULL;
if (editor) {
main_loop = memnew(SceneTree);
};
- if (test!="") {
+ if (test != "") {
#ifdef DEBUG_ENABLED
- main_loop = test_main(test,args);
+ main_loop = test_main(test, args);
if (!main_loop)
return false;
#endif
- } else if (script!="") {
+ } else if (script != "") {
Ref<Script> script_res = ResourceLoader::load(script);
- ERR_EXPLAIN("Can't load script: "+script);
- ERR_FAIL_COND_V(script_res.is_null(),false);
-
- if( script_res->can_instance() /*&& script_res->inherits_from("SceneTreeScripted")*/) {
+ ERR_EXPLAIN("Can't load script: " + script);
+ ERR_FAIL_COND_V(script_res.is_null(), false);
+ if (script_res->can_instance() /*&& script_res->inherits_from("SceneTreeScripted")*/) {
- StringName instance_type=script_res->get_instance_base_type();
+ StringName instance_type = script_res->get_instance_base_type();
Object *obj = ClassDB::instance(instance_type);
- MainLoop *script_loop = obj?obj->cast_to<MainLoop>():NULL;
+ MainLoop *script_loop = obj ? obj->cast_to<MainLoop>() : NULL;
if (!script_loop) {
if (obj)
memdelete(obj);
- ERR_EXPLAIN("Can't load script '"+script+"', it does not inherit from a MainLoop type");
- ERR_FAIL_COND_V(!script_loop,false);
+ ERR_EXPLAIN("Can't load script '" + script + "', it does not inherit from a MainLoop type");
+ ERR_FAIL_COND_V(!script_loop, false);
}
-
script_loop->set_init_script(script_res);
- main_loop=script_loop;
+ main_loop = script_loop;
} else {
return false;
}
} else {
- main_loop_type=GLOBAL_DEF("application/main_loop_type","");
+ main_loop_type = GLOBAL_DEF("application/main_loop_type", "");
}
- if (!main_loop && main_loop_type=="")
- main_loop_type="SceneTree";
+ if (!main_loop && main_loop_type == "")
+ main_loop_type = "SceneTree";
if (!main_loop) {
if (!ClassDB::class_exists(main_loop_type)) {
- OS::get_singleton()->alert("godot: error: MainLoop type doesn't exist: "+main_loop_type);
+ OS::get_singleton()->alert("godot: error: MainLoop type doesn't exist: " + main_loop_type);
return false;
} else {
@@ -1236,13 +1180,12 @@ bool Main::start() {
ERR_FAIL_V(false);
}
- main_loop=ml->cast_to<MainLoop>();
+ main_loop = ml->cast_to<MainLoop>();
if (!main_loop) {
memdelete(ml);
ERR_EXPLAIN("Invalid MainLoop type");
ERR_FAIL_V(false);
-
}
}
}
@@ -1259,20 +1202,19 @@ bool Main::start() {
}
#ifdef TOOLS_ENABLED
-
- EditorNode *editor_node=NULL;
+ EditorNode *editor_node = NULL;
if (editor) {
- editor_node = memnew( EditorNode );
+ editor_node = memnew(EditorNode);
sml->get_root()->add_child(editor_node);
//root_node->set_editor(editor);
//startup editor
- if (_export_platform!="") {
+ if (_export_platform != "") {
- editor_node->export_platform(_export_platform,game_path,export_debug,"",true);
- game_path=""; //no load anything
+ editor_node->export_platform(_export_platform, game_path, export_debug, "", true);
+ game_path = ""; //no load anything
}
}
#endif
@@ -1280,117 +1222,112 @@ bool Main::start() {
if (!editor) {
//standard helpers that can be changed from main config
- String stretch_mode = GLOBAL_DEF("display/stretch/mode","disabled");
- String stretch_aspect = GLOBAL_DEF("display/stretch/aspect","ignore");
- Size2i stretch_size = Size2(GLOBAL_DEF("display/screen/width",0),GLOBAL_DEF("display/screen/height",0));
+ String stretch_mode = GLOBAL_DEF("display/stretch/mode", "disabled");
+ String stretch_aspect = GLOBAL_DEF("display/stretch/aspect", "ignore");
+ Size2i stretch_size = Size2(GLOBAL_DEF("display/screen/width", 0), GLOBAL_DEF("display/screen/height", 0));
- SceneTree::StretchMode sml_sm=SceneTree::STRETCH_MODE_DISABLED;
- if (stretch_mode=="2d")
- sml_sm=SceneTree::STRETCH_MODE_2D;
- else if (stretch_mode=="viewport")
- sml_sm=SceneTree::STRETCH_MODE_VIEWPORT;
+ SceneTree::StretchMode sml_sm = SceneTree::STRETCH_MODE_DISABLED;
+ if (stretch_mode == "2d")
+ sml_sm = SceneTree::STRETCH_MODE_2D;
+ else if (stretch_mode == "viewport")
+ sml_sm = SceneTree::STRETCH_MODE_VIEWPORT;
- SceneTree::StretchAspect sml_aspect=SceneTree::STRETCH_ASPECT_IGNORE;
- if (stretch_aspect=="keep")
- sml_aspect=SceneTree::STRETCH_ASPECT_KEEP;
- else if (stretch_aspect=="keep_width")
- sml_aspect=SceneTree::STRETCH_ASPECT_KEEP_WIDTH;
- else if (stretch_aspect=="keep_height")
- sml_aspect=SceneTree::STRETCH_ASPECT_KEEP_HEIGHT;
+ SceneTree::StretchAspect sml_aspect = SceneTree::STRETCH_ASPECT_IGNORE;
+ if (stretch_aspect == "keep")
+ sml_aspect = SceneTree::STRETCH_ASPECT_KEEP;
+ else if (stretch_aspect == "keep_width")
+ sml_aspect = SceneTree::STRETCH_ASPECT_KEEP_WIDTH;
+ else if (stretch_aspect == "keep_height")
+ sml_aspect = SceneTree::STRETCH_ASPECT_KEEP_HEIGHT;
- sml->set_screen_stretch(sml_sm,sml_aspect,stretch_size);
+ sml->set_screen_stretch(sml_sm, sml_aspect, stretch_size);
- sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
- sml->set_quit_on_go_back(GLOBAL_DEF("application/quit_on_go_back",true));
+ sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit", true));
+ sml->set_quit_on_go_back(GLOBAL_DEF("application/quit_on_go_back", true));
String appname = GlobalConfig::get_singleton()->get("application/name");
appname = TranslationServer::get_singleton()->translate(appname);
OS::get_singleton()->set_window_title(appname);
- int shadow_atlas_size = GLOBAL_DEF("rendering/shadow_atlas/size",2048);
- int shadow_atlas_q0_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_0_subdiv",2);
- int shadow_atlas_q1_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_1_subdiv",2);
- int shadow_atlas_q2_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_2_subdiv",3);
- int shadow_atlas_q3_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_3_subdiv",4);
+ int shadow_atlas_size = GLOBAL_DEF("rendering/shadow_atlas/size", 2048);
+ int shadow_atlas_q0_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_0_subdiv", 2);
+ int shadow_atlas_q1_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_1_subdiv", 2);
+ int shadow_atlas_q2_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_2_subdiv", 3);
+ int shadow_atlas_q3_subdiv = GLOBAL_DEF("rendering/shadow_atlas/quadrant_3_subdiv", 4);
sml->get_root()->set_shadow_atlas_size(shadow_atlas_size);
- sml->get_root()->set_shadow_atlas_quadrant_subdiv(0,Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q0_subdiv));
- sml->get_root()->set_shadow_atlas_quadrant_subdiv(1,Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q1_subdiv));
- sml->get_root()->set_shadow_atlas_quadrant_subdiv(2,Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q2_subdiv));
- sml->get_root()->set_shadow_atlas_quadrant_subdiv(3,Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q3_subdiv));
+ sml->get_root()->set_shadow_atlas_quadrant_subdiv(0, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q0_subdiv));
+ sml->get_root()->set_shadow_atlas_quadrant_subdiv(1, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q1_subdiv));
+ sml->get_root()->set_shadow_atlas_quadrant_subdiv(2, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q2_subdiv));
+ sml->get_root()->set_shadow_atlas_quadrant_subdiv(3, Viewport::ShadowAtlasQuadrantSubdiv(shadow_atlas_q3_subdiv));
} else {
- GLOBAL_DEF("display/stretch/mode","disabled");
- GlobalConfig::get_singleton()->set_custom_property_info("display/stretch/mode",PropertyInfo(Variant::STRING,"display/stretch/mode",PROPERTY_HINT_ENUM,"disabled,2d,viewport"));
- GLOBAL_DEF("display/stretch/aspect","ignore");
- GlobalConfig::get_singleton()->set_custom_property_info("display/stretch/aspect",PropertyInfo(Variant::STRING,"display/stretch/aspect",PROPERTY_HINT_ENUM,"ignore,keep,keep_width,keep_height"));
- sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
- sml->set_quit_on_go_back(GLOBAL_DEF("application/quit_on_go_back",true));
-
- GLOBAL_DEF("rendering/shadow_atlas/size",2048);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/size",PropertyInfo(Variant::INT,"rendering/shadow_atlas/size",PROPERTY_HINT_RANGE,"256,16384"));
-
- GLOBAL_DEF("rendering/shadow_atlas/quadrant_0_subdiv",2);
- GLOBAL_DEF("rendering/shadow_atlas/quadrant_1_subdiv",2);
- GLOBAL_DEF("rendering/shadow_atlas/quadrant_2_subdiv",3);
- GLOBAL_DEF("rendering/shadow_atlas/quadrant_3_subdiv",4);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_0_subdiv",PropertyInfo(Variant::INT,"rendering/shadow_atlas/quadrant_0_subdiv",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_1_subdiv",PropertyInfo(Variant::INT,"rendering/shadow_atlas/quadrant_1_subdiv",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_2_subdiv",PropertyInfo(Variant::INT,"rendering/shadow_atlas/quadrant_2_subdiv",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_3_subdiv",PropertyInfo(Variant::INT,"rendering/shadow_atlas/quadrant_3_subdiv",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
+ GLOBAL_DEF("display/stretch/mode", "disabled");
+ GlobalConfig::get_singleton()->set_custom_property_info("display/stretch/mode", PropertyInfo(Variant::STRING, "display/stretch/mode", PROPERTY_HINT_ENUM, "disabled,2d,viewport"));
+ GLOBAL_DEF("display/stretch/aspect", "ignore");
+ GlobalConfig::get_singleton()->set_custom_property_info("display/stretch/aspect", PropertyInfo(Variant::STRING, "display/stretch/aspect", PROPERTY_HINT_ENUM, "ignore,keep,keep_width,keep_height"));
+ sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit", true));
+ sml->set_quit_on_go_back(GLOBAL_DEF("application/quit_on_go_back", true));
+
+ GLOBAL_DEF("rendering/shadow_atlas/size", 2048);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/size", PropertyInfo(Variant::INT, "rendering/shadow_atlas/size", PROPERTY_HINT_RANGE, "256,16384"));
+
+ GLOBAL_DEF("rendering/shadow_atlas/quadrant_0_subdiv", 2);
+ GLOBAL_DEF("rendering/shadow_atlas/quadrant_1_subdiv", 2);
+ GLOBAL_DEF("rendering/shadow_atlas/quadrant_2_subdiv", 3);
+ GLOBAL_DEF("rendering/shadow_atlas/quadrant_3_subdiv", 4);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_0_subdiv", PropertyInfo(Variant::INT, "rendering/shadow_atlas/quadrant_0_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_1_subdiv", PropertyInfo(Variant::INT, "rendering/shadow_atlas/quadrant_1_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_2_subdiv", PropertyInfo(Variant::INT, "rendering/shadow_atlas/quadrant_2_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/shadow_atlas/quadrant_3_subdiv", PropertyInfo(Variant::INT, "rendering/shadow_atlas/quadrant_3_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"));
}
-
String local_game_path;
- if (game_path!="" && !project_manager_request) {
+ if (game_path != "" && !project_manager_request) {
- local_game_path=game_path.replace("\\","/");
+ local_game_path = game_path.replace("\\", "/");
if (!local_game_path.begins_with("res://")) {
- bool absolute=(local_game_path.size()>1) && (local_game_path[0]=='/' || local_game_path[1]==':');
+ bool absolute = (local_game_path.size() > 1) && (local_game_path[0] == '/' || local_game_path[1] == ':');
if (!absolute) {
if (GlobalConfig::get_singleton()->is_using_datapack()) {
- local_game_path="res://"+local_game_path;
+ local_game_path = "res://" + local_game_path;
} else {
- int sep=local_game_path.find_last("/");
+ int sep = local_game_path.find_last("/");
- if (sep==-1) {
+ if (sep == -1) {
DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
- local_game_path=da->get_current_dir()+"/"+local_game_path;
- memdelete(da) ;
+ local_game_path = da->get_current_dir() + "/" + local_game_path;
+ memdelete(da);
} else {
- DirAccess *da = DirAccess::open(local_game_path.substr(0,sep));
+ DirAccess *da = DirAccess::open(local_game_path.substr(0, sep));
if (da) {
- local_game_path=da->get_current_dir()+"/"+local_game_path.substr(sep+1,local_game_path.length());
+ local_game_path = da->get_current_dir() + "/" + local_game_path.substr(sep + 1, local_game_path.length());
memdelete(da);
}
}
}
-
}
}
- local_game_path=GlobalConfig::get_singleton()->localize_path(local_game_path);
+ local_game_path = GlobalConfig::get_singleton()->localize_path(local_game_path);
#ifdef TOOLS_ENABLED
if (editor) {
-
- if (_import!="") {
+ if (_import != "") {
//editor_node->import_scene(_import,local_game_path,_import_script);
if (!noquit)
sml->quit();
- game_path=""; //no load anything
+ game_path = ""; //no load anything
} else {
Error serr = editor_node->load_scene(local_game_path);
-
-
}
OS::get_singleton()->set_context(OS::CONTEXT_EDITOR);
@@ -1400,71 +1337,70 @@ bool Main::start() {
}
if (!project_manager_request && !editor) {
- if (game_path!="" || script!="") {
+ if (game_path != "" || script != "") {
//autoload
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
//first pass, add the constants so they exist before any script is loaded
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ 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_slicec('/',1);
+ String name = s.get_slicec('/', 1);
String path = GlobalConfig::get_singleton()->get(s);
- bool global_var=false;
+ bool global_var = false;
if (path.begins_with("*")) {
- global_var=true;
+ global_var = true;
}
if (global_var) {
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- ScriptServer::get_language(i)->add_global_constant(name,Variant());
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ScriptServer::get_language(i)->add_global_constant(name, Variant());
}
}
-
}
//second pass, load into global constants
- List<Node*> to_add;
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ List<Node *> to_add;
+ 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_slicec('/',1);
+ String name = s.get_slicec('/', 1);
String path = GlobalConfig::get_singleton()->get(s);
- bool global_var=false;
+ bool global_var = false;
if (path.begins_with("*")) {
- global_var=true;
- path=path.substr(1,path.length()-1);
+ global_var = true;
+ path = path.substr(1, path.length() - 1);
}
RES res = ResourceLoader::load(path);
- ERR_EXPLAIN("Can't autoload: "+path);
+ ERR_EXPLAIN("Can't autoload: " + path);
ERR_CONTINUE(res.is_null());
- Node *n=NULL;
+ Node *n = NULL;
if (res->is_class("PackedScene")) {
Ref<PackedScene> ps = res;
- n=ps->instance();
+ n = ps->instance();
} else if (res->is_class("Script")) {
Ref<Script> s = res;
StringName ibt = s->get_instance_base_type();
- bool valid_type = ClassDB::is_parent_class(ibt,"Node");
- ERR_EXPLAIN("Script does not inherit a Node: "+path);
- ERR_CONTINUE( !valid_type );
+ bool valid_type = ClassDB::is_parent_class(ibt, "Node");
+ ERR_EXPLAIN("Script does not inherit a Node: " + path);
+ ERR_CONTINUE(!valid_type);
Object *obj = ClassDB::instance(ibt);
- ERR_EXPLAIN("Cannot instance script for autoload, expected 'Node' inheritance, got: "+String(ibt));
- ERR_CONTINUE( obj==NULL );
+ ERR_EXPLAIN("Cannot instance script for autoload, expected 'Node' inheritance, got: " + String(ibt));
+ ERR_CONTINUE(obj == NULL);
n = obj->cast_to<Node>();
n->set_script(s.get_ref_ptr());
}
- ERR_EXPLAIN("Path in autoload not a node or script: "+path);
+ ERR_EXPLAIN("Path in autoload not a node or script: " + path);
ERR_CONTINUE(!n);
n->set_name(name);
@@ -1473,35 +1409,34 @@ bool Main::start() {
to_add.push_back(n);
if (global_var) {
- for(int i=0;i<ScriptServer::get_language_count();i++) {
- ScriptServer::get_language(i)->add_global_constant(name,n);
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
+ ScriptServer::get_language(i)->add_global_constant(name, n);
}
}
-
}
- for(List<Node*>::Element *E=to_add.front();E;E=E->next()) {
+ for (List<Node *>::Element *E = to_add.front(); E; E = E->next()) {
sml->get_root()->add_child(E->get());
}
//singletons
}
- if (game_path!="") {
- Node *scene=NULL;
+ if (game_path != "") {
+ Node *scene = NULL;
Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
if (scenedata.is_valid())
- scene=scenedata->instance();
+ scene = scenedata->instance();
- ERR_EXPLAIN("Failed loading scene: "+local_game_path);
- ERR_FAIL_COND_V(!scene,false)
+ ERR_EXPLAIN("Failed loading scene: " + local_game_path);
+ ERR_FAIL_COND_V(!scene, false)
//sml->get_root()->add_child(scene);
sml->add_current_scene(scene);
- String iconpath = GLOBAL_DEF("application/icon","Variant()");
- if (iconpath!="") {
+ String iconpath = GLOBAL_DEF("application/icon", "Variant()");
+ if (iconpath != "") {
Image icon;
- if (icon.load(iconpath)==OK)
+ if (icon.load(iconpath) == OK)
OS::get_singleton()->set_icon(icon);
}
}
@@ -1529,10 +1464,10 @@ bool Main::start() {
};
}
*/
- if (project_manager_request || (script=="" && test=="" && game_path=="" && !editor)) {
+ if (project_manager_request || (script == "" && test == "" && game_path == "" && !editor)) {
- ProjectManager *pmanager = memnew( ProjectManager );
- ProgressDialog *progress_dialog = memnew( ProgressDialog );
+ ProjectManager *pmanager = memnew(ProjectManager);
+ ProgressDialog *progress_dialog = memnew(ProgressDialog);
pmanager->add_child(progress_dialog);
sml->get_root()->add_child(pmanager);
OS::get_singleton()->set_context(OS::CONTEXT_PROJECTMAN);
@@ -1541,57 +1476,56 @@ bool Main::start() {
#endif
}
- OS::get_singleton()->set_main_loop( main_loop );
+ OS::get_singleton()->set_main_loop(main_loop);
return true;
}
-uint64_t Main::last_ticks=0;
-uint64_t Main::target_ticks=0;
-float Main::time_accum=0;
-uint32_t Main::frames=0;
-uint32_t Main::frame=0;
+uint64_t Main::last_ticks = 0;
+uint64_t Main::target_ticks = 0;
+float Main::time_accum = 0;
+uint32_t Main::frames = 0;
+uint32_t Main::frame = 0;
bool Main::force_redraw_requested = false;
//for performance metrics
-static uint64_t fixed_process_max=0;
-static uint64_t idle_process_max=0;
-
+static uint64_t fixed_process_max = 0;
+static uint64_t idle_process_max = 0;
bool Main::iteration() {
- uint64_t ticks=OS::get_singleton()->get_ticks_usec();
- uint64_t ticks_elapsed=ticks-last_ticks;
+ uint64_t ticks = OS::get_singleton()->get_ticks_usec();
+ uint64_t ticks_elapsed = ticks - last_ticks;
- double step=(double)ticks_elapsed / 1000000.0;
- float frame_slice=1.0/Engine::get_singleton()->get_iterations_per_second();
+ double step = (double)ticks_elapsed / 1000000.0;
+ float frame_slice = 1.0 / Engine::get_singleton()->get_iterations_per_second();
/*
if (time_accum+step < frame_slice)
return false;
*/
- uint64_t fixed_process_ticks=0;
- uint64_t idle_process_ticks=0;
+ uint64_t fixed_process_ticks = 0;
+ uint64_t idle_process_ticks = 0;
- frame+=ticks_elapsed;
+ frame += ticks_elapsed;
- last_ticks=ticks;
+ last_ticks = ticks;
- if (step>frame_slice*8)
- step=frame_slice*8;
+ if (step > frame_slice * 8)
+ step = frame_slice * 8;
- time_accum+=step;
+ time_accum += step;
float time_scale = Engine::get_singleton()->get_time_scale();
- bool exit=false;
+ bool exit = false;
int iters = 0;
- Engine::get_singleton()->_in_fixed=true;
+ Engine::get_singleton()->_in_fixed = true;
- while(time_accum>frame_slice) {
+ while (time_accum > frame_slice) {
uint64_t fixed_begin = OS::get_singleton()->get_ticks_usec();
@@ -1601,39 +1535,38 @@ bool Main::iteration() {
Physics2DServer::get_singleton()->sync();
Physics2DServer::get_singleton()->flush_queries();
- if (OS::get_singleton()->get_main_loop()->iteration( frame_slice*time_scale )) {
- exit=true;
+ if (OS::get_singleton()->get_main_loop()->iteration(frame_slice * time_scale)) {
+ exit = true;
break;
}
message_queue->flush();
- PhysicsServer::get_singleton()->step(frame_slice*time_scale);
+ PhysicsServer::get_singleton()->step(frame_slice * time_scale);
Physics2DServer::get_singleton()->end_sync();
- Physics2DServer::get_singleton()->step(frame_slice*time_scale);
+ Physics2DServer::get_singleton()->step(frame_slice * time_scale);
- time_accum-=frame_slice;
+ time_accum -= frame_slice;
message_queue->flush();
/*
if (AudioServer::get_singleton())
AudioServer::get_singleton()->update();
*/
- fixed_process_ticks=MAX(fixed_process_ticks,OS::get_singleton()->get_ticks_usec()-fixed_begin); // keep the largest one for reference
- fixed_process_max=MAX(OS::get_singleton()->get_ticks_usec()-fixed_begin,fixed_process_max);
+ fixed_process_ticks = MAX(fixed_process_ticks, OS::get_singleton()->get_ticks_usec() - fixed_begin); // keep the largest one for reference
+ fixed_process_max = MAX(OS::get_singleton()->get_ticks_usec() - fixed_begin, fixed_process_max);
iters++;
Engine::get_singleton()->_fixed_frames++;
}
- Engine::get_singleton()->_in_fixed=false;
+ Engine::get_singleton()->_in_fixed = false;
uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();
- OS::get_singleton()->get_main_loop()->idle( step*time_scale );
+ OS::get_singleton()->get_main_loop()->idle(step * time_scale);
message_queue->flush();
-
VisualServer::get_singleton()->sync(); //sync if still drawing from previous frames.
if (OS::get_singleton()->can_draw()) {
@@ -1653,41 +1586,39 @@ bool Main::iteration() {
if (AudioServer::get_singleton())
AudioServer::get_singleton()->update();
- idle_process_ticks=OS::get_singleton()->get_ticks_usec()-idle_begin;
- idle_process_max=MAX(idle_process_ticks,idle_process_max);
+ idle_process_ticks = OS::get_singleton()->get_ticks_usec() - idle_begin;
+ idle_process_max = MAX(idle_process_ticks, idle_process_max);
uint64_t frame_time = OS::get_singleton()->get_ticks_usec() - ticks;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->frame();
}
if (script_debugger) {
if (script_debugger->is_profiling()) {
- script_debugger->profiling_set_frame_times(USEC_TO_SEC(frame_time),USEC_TO_SEC(idle_process_ticks),USEC_TO_SEC(fixed_process_ticks),frame_slice);
+ script_debugger->profiling_set_frame_times(USEC_TO_SEC(frame_time), USEC_TO_SEC(idle_process_ticks), USEC_TO_SEC(fixed_process_ticks), frame_slice);
}
script_debugger->idle_poll();
}
-
//x11_delay_usec(10000);
frames++;
Engine::get_singleton()->_idle_frames++;
- if (frame>1000000) {
+ if (frame > 1000000) {
if (GLOBAL_DEF("debug/stdout/print_fps", OS::get_singleton()->is_stdout_verbose())) {
- print_line("FPS: "+itos(frames));
+ print_line("FPS: " + itos(frames));
};
- Engine::get_singleton()->_fps=frames;
+ Engine::get_singleton()->_fps = frames;
performance->set_process_time(USEC_TO_SEC(idle_process_max));
performance->set_fixed_process_time(USEC_TO_SEC(fixed_process_max));
- idle_process_max=0;
- fixed_process_max=0;
+ idle_process_max = 0;
+ fixed_process_max = 0;
-
- frame%=1000000;
- frames=0;
+ frame %= 1000000;
+ frames = 0;
}
if (OS::get_singleton()->is_in_low_processor_usage_mode() || !OS::get_singleton()->can_draw())
@@ -1695,17 +1626,17 @@ bool Main::iteration() {
else {
uint32_t frame_delay = Engine::get_singleton()->get_frame_delay();
if (frame_delay)
- OS::get_singleton()->delay_usec( Engine::get_singleton()->get_frame_delay()*1000 );
+ OS::get_singleton()->delay_usec(Engine::get_singleton()->get_frame_delay() * 1000);
}
int target_fps = Engine::get_singleton()->get_target_fps();
- if (target_fps>0) {
- uint64_t time_step = 1000000L/target_fps;
+ if (target_fps > 0) {
+ uint64_t time_step = 1000000L / target_fps;
target_ticks += time_step;
uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
- if (current_ticks<target_ticks) OS::get_singleton()->delay_usec(target_ticks-current_ticks);
+ if (current_ticks < target_ticks) OS::get_singleton()->delay_usec(target_ticks - current_ticks);
current_ticks = OS::get_singleton()->get_ticks_usec();
- target_ticks = MIN(MAX(target_ticks,current_ticks-time_step),current_ticks+time_step);
+ target_ticks = MIN(MAX(target_ticks, current_ticks - time_step), current_ticks + time_step);
}
return exit;
@@ -1716,7 +1647,6 @@ void Main::force_redraw() {
force_redraw_requested = true;
};
-
void Main::cleanup() {
ERR_FAIL_COND(!_start_success);
@@ -1732,14 +1662,13 @@ void Main::cleanup() {
OS::get_singleton()->delete_main_loop();
OS::get_singleton()->_cmdline.clear();
- OS::get_singleton()->_execpath="";
- OS::get_singleton()->_local_clipboard="";
+ OS::get_singleton()->_execpath = "";
+ OS::get_singleton()->_local_clipboard = "";
if (audio_server) {
memdelete(audio_server);
}
-
#ifdef TOOLS_ENABLED
EditorNode::unregister_editor_types();
#endif
@@ -1751,7 +1680,6 @@ void Main::cleanup() {
OS::get_singleton()->finalize();
-
if (packed_data)
memdelete(packed_data);
if (file_access_network_client)
@@ -1761,16 +1689,13 @@ void Main::cleanup() {
if (input_map)
memdelete(input_map);
if (translation_server)
- memdelete( translation_server );
+ memdelete(translation_server);
if (globals)
memdelete(globals);
if (engine)
memdelete(engine);
-
-
-
- memdelete( message_queue );
+ memdelete(message_queue);
unregister_core_driver_types();
unregister_core_types();
@@ -1778,6 +1703,4 @@ void Main::cleanup() {
//PerformanceMetrics::finish();
OS::get_singleton()->clear_last_error();
OS::get_singleton()->finalize_core();
-
-
}
diff --git a/main/main.h b/main/main.h
index 42c8a984bf..dadf45dfde 100644
--- a/main/main.h
+++ b/main/main.h
@@ -36,19 +36,18 @@
#include "error_list.h"
#include "typedefs.h"
-
class Main {
- static void print_help(const char* p_binary);
+ static void print_help(const char *p_binary);
static uint64_t last_ticks;
static uint64_t target_ticks;
static float time_accum;
static uint32_t frames;
static uint32_t frame;
static bool force_redraw_requested;
-public:
- static Error setup(const char *execpath,int argc, char *argv[],bool p_second_phase=true);
+public:
+ static Error setup(const char *execpath, int argc, char *argv[], bool p_second_phase = true);
static Error setup2();
static bool start();
static bool iteration();
diff --git a/main/performance.cpp b/main/performance.cpp
index bc5d8c33c4..d566bc325f 100644
--- a/main/performance.cpp
+++ b/main/performance.cpp
@@ -27,57 +27,53 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "performance.h"
+#include "message_queue.h"
#include "os/os.h"
-#include "servers/visual_server.h"
+#include "scene/main/scene_main_loop.h"
#include "servers/physics_2d_server.h"
#include "servers/physics_server.h"
-#include "message_queue.h"
-#include "scene/main/scene_main_loop.h"
-Performance *Performance::singleton=NULL;
-
-
-
+#include "servers/visual_server.h"
+Performance *Performance::singleton = NULL;
void Performance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_monitor","monitor"),&Performance::get_monitor);
-
- BIND_CONSTANT( TIME_FPS );
- BIND_CONSTANT( TIME_PROCESS );
- BIND_CONSTANT( TIME_FIXED_PROCESS );
- BIND_CONSTANT( MEMORY_STATIC );
- BIND_CONSTANT( MEMORY_DYNAMIC );
- BIND_CONSTANT( MEMORY_STATIC_MAX );
- BIND_CONSTANT( MEMORY_DYNAMIC_MAX );
- BIND_CONSTANT( MEMORY_MESSAGE_BUFFER_MAX );
- BIND_CONSTANT( OBJECT_COUNT );
- BIND_CONSTANT( OBJECT_RESOURCE_COUNT );
- BIND_CONSTANT( OBJECT_NODE_COUNT );
- BIND_CONSTANT( RENDER_OBJECTS_IN_FRAME );
- BIND_CONSTANT( RENDER_VERTICES_IN_FRAME );
- BIND_CONSTANT( RENDER_MATERIAL_CHANGES_IN_FRAME );
- BIND_CONSTANT( RENDER_SHADER_CHANGES_IN_FRAME );
- BIND_CONSTANT( RENDER_SURFACE_CHANGES_IN_FRAME );
- BIND_CONSTANT( RENDER_DRAW_CALLS_IN_FRAME );
- BIND_CONSTANT( RENDER_USAGE_VIDEO_MEM_TOTAL );
- BIND_CONSTANT( RENDER_VIDEO_MEM_USED );
- BIND_CONSTANT( RENDER_TEXTURE_MEM_USED );
- BIND_CONSTANT( RENDER_VERTEX_MEM_USED );
- BIND_CONSTANT( PHYSICS_2D_ACTIVE_OBJECTS );
- BIND_CONSTANT( PHYSICS_2D_COLLISION_PAIRS );
- BIND_CONSTANT( PHYSICS_2D_ISLAND_COUNT );
- BIND_CONSTANT( PHYSICS_3D_ACTIVE_OBJECTS );
- BIND_CONSTANT( PHYSICS_3D_COLLISION_PAIRS );
- BIND_CONSTANT( PHYSICS_3D_ISLAND_COUNT );
-
- BIND_CONSTANT( MONITOR_MAX );
-
+ ClassDB::bind_method(D_METHOD("get_monitor", "monitor"), &Performance::get_monitor);
+
+ BIND_CONSTANT(TIME_FPS);
+ BIND_CONSTANT(TIME_PROCESS);
+ BIND_CONSTANT(TIME_FIXED_PROCESS);
+ BIND_CONSTANT(MEMORY_STATIC);
+ BIND_CONSTANT(MEMORY_DYNAMIC);
+ BIND_CONSTANT(MEMORY_STATIC_MAX);
+ BIND_CONSTANT(MEMORY_DYNAMIC_MAX);
+ BIND_CONSTANT(MEMORY_MESSAGE_BUFFER_MAX);
+ BIND_CONSTANT(OBJECT_COUNT);
+ BIND_CONSTANT(OBJECT_RESOURCE_COUNT);
+ BIND_CONSTANT(OBJECT_NODE_COUNT);
+ BIND_CONSTANT(RENDER_OBJECTS_IN_FRAME);
+ BIND_CONSTANT(RENDER_VERTICES_IN_FRAME);
+ BIND_CONSTANT(RENDER_MATERIAL_CHANGES_IN_FRAME);
+ BIND_CONSTANT(RENDER_SHADER_CHANGES_IN_FRAME);
+ BIND_CONSTANT(RENDER_SURFACE_CHANGES_IN_FRAME);
+ BIND_CONSTANT(RENDER_DRAW_CALLS_IN_FRAME);
+ BIND_CONSTANT(RENDER_USAGE_VIDEO_MEM_TOTAL);
+ BIND_CONSTANT(RENDER_VIDEO_MEM_USED);
+ BIND_CONSTANT(RENDER_TEXTURE_MEM_USED);
+ BIND_CONSTANT(RENDER_VERTEX_MEM_USED);
+ BIND_CONSTANT(PHYSICS_2D_ACTIVE_OBJECTS);
+ BIND_CONSTANT(PHYSICS_2D_COLLISION_PAIRS);
+ BIND_CONSTANT(PHYSICS_2D_ISLAND_COUNT);
+ BIND_CONSTANT(PHYSICS_3D_ACTIVE_OBJECTS);
+ BIND_CONSTANT(PHYSICS_3D_COLLISION_PAIRS);
+ BIND_CONSTANT(PHYSICS_3D_ISLAND_COUNT);
+
+ BIND_CONSTANT(MONITOR_MAX);
}
String Performance::get_monitor_name(Monitor p_monitor) const {
- ERR_FAIL_INDEX_V(p_monitor,MONITOR_MAX,String());
- static const char* names[MONITOR_MAX]={
+ ERR_FAIL_INDEX_V(p_monitor, MONITOR_MAX, String());
+ static const char *names[MONITOR_MAX] = {
"time/fps",
"time/process",
@@ -110,14 +106,11 @@ String Performance::get_monitor_name(Monitor p_monitor) const {
};
return names[p_monitor];
-
-
}
-
float Performance::get_monitor(Monitor p_monitor) const {
- switch(p_monitor) {
+ switch (p_monitor) {
case TIME_FPS: return Engine::get_singleton()->get_frames_per_second();
case TIME_PROCESS: return _process_time;
case TIME_FIXED_PROCESS: return _fixed_process_time;
@@ -137,7 +130,6 @@ float Performance::get_monitor(Monitor p_monitor) const {
if (!sml)
return 0;
return sml->get_node_count();
-
};
case RENDER_OBJECTS_IN_FRAME: return VS::get_singleton()->get_render_info(VS::INFO_OBJECTS_IN_FRAME);
case RENDER_VERTICES_IN_FRAME: return VS::get_singleton()->get_render_info(VS::INFO_VERTICES_IN_FRAME);
@@ -164,18 +156,17 @@ float Performance::get_monitor(Monitor p_monitor) const {
void Performance::set_process_time(float p_pt) {
- _process_time=p_pt;
+ _process_time = p_pt;
}
void Performance::set_fixed_process_time(float p_pt) {
- _fixed_process_time=p_pt;
+ _fixed_process_time = p_pt;
}
-
Performance::Performance() {
- _process_time=0;
- _fixed_process_time=0;
- singleton=this;
+ _process_time = 0;
+ _fixed_process_time = 0;
+ singleton = this;
}
diff --git a/main/performance.h b/main/performance.h
index 8b5626b681..03bec11296 100644
--- a/main/performance.h
+++ b/main/performance.h
@@ -34,18 +34,17 @@
#define PERF_WARN_OFFLINE_FUNCTION
#define PERF_WARN_PROCESS_SYNC
-
class Performance : public Object {
- GDCLASS(Performance,Object);
+ GDCLASS(Performance, Object);
static Performance *singleton;
static void _bind_methods();
float _process_time;
float _fixed_process_time;
-public:
+public:
enum Monitor {
TIME_FPS,
@@ -79,7 +78,6 @@ public:
MONITOR_MAX
};
-
float get_monitor(Monitor p_monitor) const;
String get_monitor_name(Monitor p_monitor) const;
@@ -89,10 +87,8 @@ public:
static Performance *get_singleton() { return singleton; }
Performance();
-
};
-VARIANT_ENUM_CAST( Performance::Monitor );
-
+VARIANT_ENUM_CAST(Performance::Monitor);
#endif // PERFORMANCE_H
diff --git a/main/splash.h b/main/splash.h
index 3423f1b932..401cf5a022 100644
--- a/main/splash.h
+++ b/main/splash.h
@@ -1419,5 +1419,5 @@ static const unsigned char app_icon_png[] = {
0x42, 0x60, 0x82
};
-static const Color boot_splash_bg_color = Color(224/255.0,224/255.0,224/255.0);
+static const Color boot_splash_bg_color = Color(224 / 255.0, 224 / 255.0, 224 / 255.0);
#endif // SPLASH_H
diff --git a/main/tests/test_containers.cpp b/main/tests/test_containers.cpp
index 8926066fe6..d860d9940e 100644
--- a/main/tests/test_containers.cpp
+++ b/main/tests/test_containers.cpp
@@ -29,19 +29,18 @@
#include "test_containers.h"
#include "dvector.h"
-#include "set.h"
-#include "print_string.h"
#include "math_funcs.h"
+#include "print_string.h"
#include "servers/visual/default_mouse_cursor.xpm"
+#include "set.h"
-#include "variant.h"
-#include "list.h"
#include "image.h"
+#include "list.h"
+#include "variant.h"
namespace TestContainers {
-MainLoop * test() {
-
+MainLoop *test() {
/*
HashMap<int,int> int_map;
@@ -53,14 +52,13 @@ MainLoop * test() {
}
*/
-
{
Image img;
img.create(default_mouse_cursor_xpm);
{
- for (int i=0; i<8; i++) {
+ for (int i = 0; i < 8; i++) {
Image mipmap;
//img.make_mipmap(mipmap);
@@ -68,7 +66,6 @@ MainLoop * test() {
if (img.get_width() <= 4) break;
};
};
-
};
#if 0
@@ -103,5 +100,4 @@ MainLoop * test() {
return NULL;
}
-
}
diff --git a/main/tests/test_containers.h b/main/tests/test_containers.h
index bbc132f1c2..990bf4f819 100644
--- a/main/tests/test_containers.h
+++ b/main/tests/test_containers.h
@@ -36,8 +36,7 @@
namespace TestContainers {
-MainLoop * test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_gdscript.cpp b/main/tests/test_gdscript.cpp
index e9ac238f2a..fcbecc768b 100644
--- a/main/tests/test_gdscript.cpp
+++ b/main/tests/test_gdscript.cpp
@@ -28,47 +28,44 @@
/*************************************************************************/
#include "test_gdscript.h"
-
+#include "os/file_access.h"
#include "os/main_loop.h"
#include "os/os.h"
-#include "os/file_access.h"
#ifdef GDSCRIPT_ENABLED
-#include "modules/gdscript/gd_tokenizer.h"
-#include "modules/gdscript/gd_parser.h"
#include "modules/gdscript/gd_compiler.h"
+#include "modules/gdscript/gd_parser.h"
#include "modules/gdscript/gd_script.h"
-
+#include "modules/gdscript/gd_tokenizer.h"
namespace TestGDScript {
-
-static void _print_indent(int p_ident,const String& p_text) {
+static void _print_indent(int p_ident, const String &p_text) {
String txt;
- for(int i=0;i<p_ident;i++) {
- txt+='\t';
+ for (int i = 0; i < p_ident; i++) {
+ txt += '\t';
}
- print_line(txt+p_text);
+ print_line(txt + p_text);
}
static String _parser_extends(const GDParser::ClassNode *p_class) {
- String txt="extends ";
- if (String(p_class->extends_file)!="") {
- txt+="\""+p_class->extends_file+"\"";
+ String txt = "extends ";
+ if (String(p_class->extends_file) != "") {
+ txt += "\"" + p_class->extends_file + "\"";
if (p_class->extends_class.size())
- txt+=".";
+ txt += ".";
}
- for(int i=0;i<p_class->extends_class.size();i++) {
+ for (int i = 0; i < p_class->extends_class.size(); i++) {
- if (i!=0)
- txt+=".";
+ if (i != 0)
+ txt += ".";
- txt+=p_class->extends_class[i];
+ txt += p_class->extends_class[i];
}
return txt;
@@ -77,153 +74,222 @@ static String _parser_extends(const GDParser::ClassNode *p_class) {
static String _parser_expr(const GDParser::Node *p_expr) {
String txt;
- switch(p_expr->type) {
+ switch (p_expr->type) {
case GDParser::Node::TYPE_IDENTIFIER: {
const GDParser::IdentifierNode *id_node = static_cast<const GDParser::IdentifierNode *>(p_expr);
- txt=id_node->name;
+ txt = id_node->name;
} break;
case GDParser::Node::TYPE_CONSTANT: {
const GDParser::ConstantNode *c_node = static_cast<const GDParser::ConstantNode *>(p_expr);
- if (c_node->value.get_type()==Variant::STRING)
- txt="\""+String(c_node->value)+"\"";
+ if (c_node->value.get_type() == Variant::STRING)
+ txt = "\"" + String(c_node->value) + "\"";
else
- txt=c_node->value;
+ txt = c_node->value;
} break;
case GDParser::Node::TYPE_SELF: {
- txt="self";
+ txt = "self";
} break;
case GDParser::Node::TYPE_ARRAY: {
const GDParser::ArrayNode *arr_node = static_cast<const GDParser::ArrayNode *>(p_expr);
- txt+="[";
- for(int i=0;i<arr_node->elements.size();i++) {
+ txt += "[";
+ for (int i = 0; i < arr_node->elements.size(); i++) {
- if (i>0)
- txt+=", ";
- txt+=_parser_expr(arr_node->elements[i]);
+ if (i > 0)
+ txt += ", ";
+ txt += _parser_expr(arr_node->elements[i]);
}
- txt+="]";
+ txt += "]";
} break;
case GDParser::Node::TYPE_DICTIONARY: {
const GDParser::DictionaryNode *dict_node = static_cast<const GDParser::DictionaryNode *>(p_expr);
- txt+="{";
- for(int i=0;i<dict_node->elements.size();i++) {
+ txt += "{";
+ for (int i = 0; i < dict_node->elements.size(); i++) {
- if (i>0)
- txt+=", ";
+ if (i > 0)
+ txt += ", ";
const GDParser::DictionaryNode::Pair &p = dict_node->elements[i];
- txt+=_parser_expr(p.key);
- txt+=":";
- txt+=_parser_expr(p.value);
+ txt += _parser_expr(p.key);
+ txt += ":";
+ txt += _parser_expr(p.value);
}
- txt+="}";
+ txt += "}";
} break;
case GDParser::Node::TYPE_OPERATOR: {
const GDParser::OperatorNode *c_node = static_cast<const GDParser::OperatorNode *>(p_expr);
- switch(c_node->op) {
+ switch (c_node->op) {
case GDParser::OperatorNode::OP_PARENT_CALL:
- txt+=".";
+ txt += ".";
case GDParser::OperatorNode::OP_CALL: {
- ERR_FAIL_COND_V(c_node->arguments.size()<1,"");
+ ERR_FAIL_COND_V(c_node->arguments.size() < 1, "");
String func_name;
const GDParser::Node *nfunc = c_node->arguments[0];
- int arg_ofs=0;
- if (nfunc->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
+ int arg_ofs = 0;
+ if (nfunc->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
const GDParser::BuiltInFunctionNode *bif_node = static_cast<const GDParser::BuiltInFunctionNode *>(nfunc);
- func_name=GDFunctions::get_func_name(bif_node->function);
- arg_ofs=1;
- } else if (nfunc->type==GDParser::Node::TYPE_TYPE) {
+ func_name = GDFunctions::get_func_name(bif_node->function);
+ arg_ofs = 1;
+ } else if (nfunc->type == GDParser::Node::TYPE_TYPE) {
const GDParser::TypeNode *t_node = static_cast<const GDParser::TypeNode *>(nfunc);
- func_name=Variant::get_type_name(t_node->vtype);
- arg_ofs=1;
+ func_name = Variant::get_type_name(t_node->vtype);
+ arg_ofs = 1;
} else {
- ERR_FAIL_COND_V(c_node->arguments.size()<2,"");
+ ERR_FAIL_COND_V(c_node->arguments.size() < 2, "");
nfunc = c_node->arguments[1];
- ERR_FAIL_COND_V(nfunc->type!=GDParser::Node::TYPE_IDENTIFIER,"");
+ ERR_FAIL_COND_V(nfunc->type != GDParser::Node::TYPE_IDENTIFIER, "");
- if (c_node->arguments[0]->type!=GDParser::Node::TYPE_SELF)
- func_name=_parser_expr(c_node->arguments[0])+".";
+ if (c_node->arguments[0]->type != GDParser::Node::TYPE_SELF)
+ func_name = _parser_expr(c_node->arguments[0]) + ".";
- func_name+=_parser_expr(nfunc);
- arg_ofs=2;
+ func_name += _parser_expr(nfunc);
+ arg_ofs = 2;
}
- txt+=func_name+"(";
+ txt += func_name + "(";
- for(int i=arg_ofs;i<c_node->arguments.size();i++) {
+ for (int i = arg_ofs; i < c_node->arguments.size(); i++) {
- const GDParser::Node *arg=c_node->arguments[i];
- if (i>arg_ofs)
- txt+=", ";
- txt+=_parser_expr(arg);
+ const GDParser::Node *arg = c_node->arguments[i];
+ if (i > arg_ofs)
+ txt += ", ";
+ txt += _parser_expr(arg);
}
- txt+=")";
+ txt += ")";
} break;
case GDParser::OperatorNode::OP_INDEX: {
- ERR_FAIL_COND_V(c_node->arguments.size()!=2,"");
+ ERR_FAIL_COND_V(c_node->arguments.size() != 2, "");
//index with []
- txt=_parser_expr(c_node->arguments[0])+"["+_parser_expr(c_node->arguments[1])+"]";
+ txt = _parser_expr(c_node->arguments[0]) + "[" + _parser_expr(c_node->arguments[1]) + "]";
} break;
case GDParser::OperatorNode::OP_INDEX_NAMED: {
- ERR_FAIL_COND_V(c_node->arguments.size()!=2,"");
-
- txt=_parser_expr(c_node->arguments[0])+"."+_parser_expr(c_node->arguments[1]);
-
- } break;
- case GDParser::OperatorNode::OP_NEG: { txt="-"+_parser_expr(c_node->arguments[0]); } break;
- case GDParser::OperatorNode::OP_NOT: { txt="not "+_parser_expr(c_node->arguments[0]); } break;
- case GDParser::OperatorNode::OP_BIT_INVERT: { txt="~"+_parser_expr(c_node->arguments[0]); } break;
- case GDParser::OperatorNode::OP_PREINC: {} break;
- case GDParser::OperatorNode::OP_PREDEC: {} break;
- case GDParser::OperatorNode::OP_INC: {} break;
- case GDParser::OperatorNode::OP_DEC: {} break;
- case GDParser::OperatorNode::OP_IN: { txt=_parser_expr(c_node->arguments[0])+" in "+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"=="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_NOT_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"!="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_LESS: { txt=_parser_expr(c_node->arguments[0])+"<"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_LESS_EQUAL: { txt=_parser_expr(c_node->arguments[0])+"<="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_GREATER: { txt=_parser_expr(c_node->arguments[0])+">"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_GREATER_EQUAL: { txt=_parser_expr(c_node->arguments[0])+">="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_AND: { txt=_parser_expr(c_node->arguments[0])+" and "+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_OR: { txt=_parser_expr(c_node->arguments[0])+" or "+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ADD: { txt=_parser_expr(c_node->arguments[0])+"+"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_SUB: { txt=_parser_expr(c_node->arguments[0])+"-"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_MUL: { txt=_parser_expr(c_node->arguments[0])+"*"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_DIV: { txt=_parser_expr(c_node->arguments[0])+"/"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_MOD: { txt=_parser_expr(c_node->arguments[0])+"%"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_SHIFT_LEFT: { txt=_parser_expr(c_node->arguments[0])+"<<"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_SHIFT_RIGHT: { txt=_parser_expr(c_node->arguments[0])+">>"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN: { txt=_parser_expr(c_node->arguments[0])+"="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_ADD: { txt=_parser_expr(c_node->arguments[0])+"+="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_SUB: { txt=_parser_expr(c_node->arguments[0])+"-="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_MUL: { txt=_parser_expr(c_node->arguments[0])+"*="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_DIV: { txt=_parser_expr(c_node->arguments[0])+"/="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_MOD: { txt=_parser_expr(c_node->arguments[0])+"%="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT:{ txt=_parser_expr(c_node->arguments[0])+"<<="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: { txt=_parser_expr(c_node->arguments[0])+">>="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: { txt=_parser_expr(c_node->arguments[0])+"&="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: { txt=_parser_expr(c_node->arguments[0])+"|="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: { txt=_parser_expr(c_node->arguments[0])+"^="+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_BIT_AND: { txt=_parser_expr(c_node->arguments[0])+"&"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_BIT_OR: { txt=_parser_expr(c_node->arguments[0])+"|"+_parser_expr(c_node->arguments[1]); } break;
- case GDParser::OperatorNode::OP_BIT_XOR: { txt=_parser_expr(c_node->arguments[0])+"^"+_parser_expr(c_node->arguments[1]); } break;
- default: {}
+ ERR_FAIL_COND_V(c_node->arguments.size() != 2, "");
+ txt = _parser_expr(c_node->arguments[0]) + "." + _parser_expr(c_node->arguments[1]);
+
+ } break;
+ case GDParser::OperatorNode::OP_NEG: {
+ txt = "-" + _parser_expr(c_node->arguments[0]);
+ } break;
+ case GDParser::OperatorNode::OP_NOT: {
+ txt = "not " + _parser_expr(c_node->arguments[0]);
+ } break;
+ case GDParser::OperatorNode::OP_BIT_INVERT: {
+ txt = "~" + _parser_expr(c_node->arguments[0]);
+ } break;
+ case GDParser::OperatorNode::OP_PREINC: {
+ } break;
+ case GDParser::OperatorNode::OP_PREDEC: {
+ } break;
+ case GDParser::OperatorNode::OP_INC: {
+ } break;
+ case GDParser::OperatorNode::OP_DEC: {
+ } break;
+ case GDParser::OperatorNode::OP_IN: {
+ txt = _parser_expr(c_node->arguments[0]) + " in " + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_EQUAL: {
+ txt = _parser_expr(c_node->arguments[0]) + "==" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_NOT_EQUAL: {
+ txt = _parser_expr(c_node->arguments[0]) + "!=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_LESS: {
+ txt = _parser_expr(c_node->arguments[0]) + "<" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_LESS_EQUAL: {
+ txt = _parser_expr(c_node->arguments[0]) + "<=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_GREATER: {
+ txt = _parser_expr(c_node->arguments[0]) + ">" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_GREATER_EQUAL: {
+ txt = _parser_expr(c_node->arguments[0]) + ">=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_AND: {
+ txt = _parser_expr(c_node->arguments[0]) + " and " + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_OR: {
+ txt = _parser_expr(c_node->arguments[0]) + " or " + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ADD: {
+ txt = _parser_expr(c_node->arguments[0]) + "+" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_SUB: {
+ txt = _parser_expr(c_node->arguments[0]) + "-" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_MUL: {
+ txt = _parser_expr(c_node->arguments[0]) + "*" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_DIV: {
+ txt = _parser_expr(c_node->arguments[0]) + "/" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_MOD: {
+ txt = _parser_expr(c_node->arguments[0]) + "%" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_SHIFT_LEFT: {
+ txt = _parser_expr(c_node->arguments[0]) + "<<" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_SHIFT_RIGHT: {
+ txt = _parser_expr(c_node->arguments[0]) + ">>" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN: {
+ txt = _parser_expr(c_node->arguments[0]) + "=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_ADD: {
+ txt = _parser_expr(c_node->arguments[0]) + "+=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_SUB: {
+ txt = _parser_expr(c_node->arguments[0]) + "-=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_MUL: {
+ txt = _parser_expr(c_node->arguments[0]) + "*=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_DIV: {
+ txt = _parser_expr(c_node->arguments[0]) + "/=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_MOD: {
+ txt = _parser_expr(c_node->arguments[0]) + "%=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: {
+ txt = _parser_expr(c_node->arguments[0]) + "<<=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: {
+ txt = _parser_expr(c_node->arguments[0]) + ">>=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: {
+ txt = _parser_expr(c_node->arguments[0]) + "&=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: {
+ txt = _parser_expr(c_node->arguments[0]) + "|=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: {
+ txt = _parser_expr(c_node->arguments[0]) + "^=" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_BIT_AND: {
+ txt = _parser_expr(c_node->arguments[0]) + "&" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_BIT_OR: {
+ txt = _parser_expr(c_node->arguments[0]) + "|" + _parser_expr(c_node->arguments[1]);
+ } break;
+ case GDParser::OperatorNode::OP_BIT_XOR: {
+ txt = _parser_expr(c_node->arguments[0]) + "^" + _parser_expr(c_node->arguments[1]);
+ } break;
+ default: {}
}
} break;
@@ -233,71 +299,68 @@ static String _parser_expr(const GDParser::Node *p_expr) {
} break;
default: {
- String error="Parser bug at "+itos(p_expr->line)+", invalid expression type: "+itos(p_expr->type);
+ String error = "Parser bug at " + itos(p_expr->line) + ", invalid expression type: " + itos(p_expr->type);
ERR_EXPLAIN(error);
ERR_FAIL_V("");
-
}
-
}
return txt;
//return "("+txt+")";
}
+static void _parser_show_block(const GDParser::BlockNode *p_block, int p_indent) {
-static void _parser_show_block(const GDParser::BlockNode *p_block,int p_indent) {
+ for (int i = 0; i < p_block->statements.size(); i++) {
- for(int i=0;i<p_block->statements.size();i++) {
+ const GDParser::Node *statement = p_block->statements[i];
- const GDParser::Node *statement=p_block->statements[i];
-
- switch(statement->type) {
+ switch (statement->type) {
case GDParser::Node::TYPE_CONTROL_FLOW: {
const GDParser::ControlFlowNode *cf_node = static_cast<const GDParser::ControlFlowNode *>(statement);
- switch(cf_node->cf_type) {
+ switch (cf_node->cf_type) {
case GDParser::ControlFlowNode::CF_IF: {
- ERR_FAIL_COND(cf_node->arguments.size()!=1);
+ ERR_FAIL_COND(cf_node->arguments.size() != 1);
String txt;
- txt+="if ";
- txt+=_parser_expr(cf_node->arguments[0]);
- txt+=":";
- _print_indent(p_indent,txt);
+ txt += "if ";
+ txt += _parser_expr(cf_node->arguments[0]);
+ txt += ":";
+ _print_indent(p_indent, txt);
ERR_FAIL_COND(!cf_node->body);
- _parser_show_block(cf_node->body,p_indent+1);
+ _parser_show_block(cf_node->body, p_indent + 1);
if (cf_node->body_else) {
- _print_indent(p_indent,"else:");
- _parser_show_block(cf_node->body_else,p_indent+1);
+ _print_indent(p_indent, "else:");
+ _parser_show_block(cf_node->body_else, p_indent + 1);
}
} break;
case GDParser::ControlFlowNode::CF_FOR: {
- ERR_FAIL_COND(cf_node->arguments.size()!=2);
+ ERR_FAIL_COND(cf_node->arguments.size() != 2);
String txt;
- txt+="for ";
- txt+=_parser_expr(cf_node->arguments[0]);
- txt+=" in ";
- txt+=_parser_expr(cf_node->arguments[1]);
- txt+=":";
- _print_indent(p_indent,txt);
+ txt += "for ";
+ txt += _parser_expr(cf_node->arguments[0]);
+ txt += " in ";
+ txt += _parser_expr(cf_node->arguments[1]);
+ txt += ":";
+ _print_indent(p_indent, txt);
ERR_FAIL_COND(!cf_node->body);
- _parser_show_block(cf_node->body,p_indent+1);
+ _parser_show_block(cf_node->body, p_indent + 1);
} break;
case GDParser::ControlFlowNode::CF_WHILE: {
- ERR_FAIL_COND(cf_node->arguments.size()!=1);
+ ERR_FAIL_COND(cf_node->arguments.size() != 1);
String txt;
- txt+="while ";
- txt+=_parser_expr(cf_node->arguments[0]);
- txt+=":";
- _print_indent(p_indent,txt);
+ txt += "while ";
+ txt += _parser_expr(cf_node->arguments[0]);
+ txt += ":";
+ _print_indent(p_indent, txt);
ERR_FAIL_COND(!cf_node->body);
- _parser_show_block(cf_node->body,p_indent+1);
+ _parser_show_block(cf_node->body, p_indent + 1);
} break;
case GDParser::ControlFlowNode::CF_SWITCH: {
@@ -305,18 +368,18 @@ static void _parser_show_block(const GDParser::BlockNode *p_block,int p_indent)
} break;
case GDParser::ControlFlowNode::CF_CONTINUE: {
- _print_indent(p_indent,"continue");
+ _print_indent(p_indent, "continue");
} break;
case GDParser::ControlFlowNode::CF_BREAK: {
- _print_indent(p_indent,"break");
+ _print_indent(p_indent, "break");
} break;
case GDParser::ControlFlowNode::CF_RETURN: {
if (cf_node->arguments.size())
- _print_indent(p_indent,"return "+_parser_expr(cf_node->arguments[0]));
+ _print_indent(p_indent, "return " + _parser_expr(cf_node->arguments[0]));
else
- _print_indent(p_indent,"return ");
+ _print_indent(p_indent, "return ");
} break;
}
@@ -324,121 +387,110 @@ static void _parser_show_block(const GDParser::BlockNode *p_block,int p_indent)
case GDParser::Node::TYPE_LOCAL_VAR: {
const GDParser::LocalVarNode *lv_node = static_cast<const GDParser::LocalVarNode *>(statement);
- _print_indent(p_indent,"var "+String(lv_node->name));
+ _print_indent(p_indent, "var " + String(lv_node->name));
} break;
default: {
//expression i guess
- _print_indent(p_indent,_parser_expr(statement));
-
+ _print_indent(p_indent, _parser_expr(statement));
}
}
}
}
-static void _parser_show_function(const GDParser::FunctionNode *p_func,int p_indent,GDParser::BlockNode *p_initializer=NULL) {
+static void _parser_show_function(const GDParser::FunctionNode *p_func, int p_indent, GDParser::BlockNode *p_initializer = NULL) {
String txt;
if (p_func->_static)
- txt="static ";
- txt+="func ";
- if (p_func->name=="") // initializer
- txt+="[built-in-initializer]";
+ txt = "static ";
+ txt += "func ";
+ if (p_func->name == "") // initializer
+ txt += "[built-in-initializer]";
else
- txt+=String(p_func->name);
- txt+="(";
+ txt += String(p_func->name);
+ txt += "(";
- for(int i=0;i<p_func->arguments.size();i++) {
+ for (int i = 0; i < p_func->arguments.size(); i++) {
- if (i!=0)
- txt+=", ";
- txt+="var "+String(p_func->arguments[i]);
- if (i>=(p_func->arguments.size()-p_func->default_values.size())) {
+ if (i != 0)
+ txt += ", ";
+ txt += "var " + String(p_func->arguments[i]);
+ if (i >= (p_func->arguments.size() - p_func->default_values.size())) {
int defarg = i - (p_func->arguments.size() - p_func->default_values.size());
- txt+="=";
- txt+=_parser_expr(p_func->default_values[defarg]);
+ txt += "=";
+ txt += _parser_expr(p_func->default_values[defarg]);
}
}
- txt+=")";
+ txt += ")";
//todo constructor check!
- txt+=":";
+ txt += ":";
- _print_indent(p_indent,txt);
+ _print_indent(p_indent, txt);
if (p_initializer)
- _parser_show_block(p_initializer,p_indent+1);
- _parser_show_block(p_func->body,p_indent+1);
+ _parser_show_block(p_initializer, p_indent + 1);
+ _parser_show_block(p_func->body, p_indent + 1);
}
-static void _parser_show_class(const GDParser::ClassNode *p_class,int p_indent,const Vector<String>& p_code) {
+static void _parser_show_class(const GDParser::ClassNode *p_class, int p_indent, const Vector<String> &p_code) {
- if (p_indent==0 && (String(p_class->extends_file)!="" || p_class->extends_class.size())) {
+ if (p_indent == 0 && (String(p_class->extends_file) != "" || p_class->extends_class.size())) {
- _print_indent(p_indent,_parser_extends(p_class));
+ _print_indent(p_indent, _parser_extends(p_class));
print_line("\n");
-
}
- for(int i=0;i<p_class->subclasses.size();i++) {
-
+ for (int i = 0; i < p_class->subclasses.size(); i++) {
- const GDParser::ClassNode *subclass=p_class->subclasses[i];
- String line="class "+subclass->name;
- if (String(subclass->extends_file)!="" || subclass->extends_class.size())
- line+=" "+_parser_extends(subclass);
- line+=":";
- _print_indent(p_indent,line);
- _parser_show_class(subclass,p_indent+1,p_code);
+ const GDParser::ClassNode *subclass = p_class->subclasses[i];
+ String line = "class " + subclass->name;
+ if (String(subclass->extends_file) != "" || subclass->extends_class.size())
+ line += " " + _parser_extends(subclass);
+ line += ":";
+ _print_indent(p_indent, line);
+ _parser_show_class(subclass, p_indent + 1, p_code);
print_line("\n");
}
+ for (int i = 0; i < p_class->constant_expressions.size(); i++) {
- for(int i=0;i<p_class->constant_expressions.size();i++) {
-
- const GDParser::ClassNode::Constant &constant=p_class->constant_expressions[i];
- _print_indent(p_indent,"const "+String(constant.identifier)+"="+_parser_expr(constant.expression));
+ const GDParser::ClassNode::Constant &constant = p_class->constant_expressions[i];
+ _print_indent(p_indent, "const " + String(constant.identifier) + "=" + _parser_expr(constant.expression));
}
+ for (int i = 0; i < p_class->variables.size(); i++) {
- for(int i=0;i<p_class->variables.size();i++) {
-
- const GDParser::ClassNode::Member &m=p_class->variables[i];
-
- _print_indent(p_indent,"var "+String(m.identifier));
+ const GDParser::ClassNode::Member &m = p_class->variables[i];
+ _print_indent(p_indent, "var " + String(m.identifier));
}
print_line("\n");
- for(int i=0;i<p_class->static_functions.size();i++) {
+ for (int i = 0; i < p_class->static_functions.size(); i++) {
- _parser_show_function(p_class->static_functions[i],p_indent);
+ _parser_show_function(p_class->static_functions[i], p_indent);
print_line("\n");
-
}
- for(int i=0;i<p_class->functions.size();i++) {
+ for (int i = 0; i < p_class->functions.size(); i++) {
- if (String(p_class->functions[i]->name)=="_init") {
- _parser_show_function(p_class->functions[i],p_indent,p_class->initializer);
+ if (String(p_class->functions[i]->name) == "_init") {
+ _parser_show_function(p_class->functions[i], p_indent, p_class->initializer);
} else
- _parser_show_function(p_class->functions[i],p_indent);
+ _parser_show_function(p_class->functions[i], p_indent);
print_line("\n");
-
}
//_parser_show_function(p_class->initializer,p_indent);
print_line("\n");
-
-
}
+static String _disassemble_addr(const Ref<GDScript> &p_script, const GDFunction &func, int p_addr) {
-static String _disassemble_addr(const Ref<GDScript>& p_script,const GDFunction& func, int p_addr) {
+ int addr = p_addr & GDFunction::ADDR_MASK;
- int addr=p_addr&GDFunction::ADDR_MASK;
-
- switch(p_addr>>GDFunction::ADDR_BITS) {
+ switch (p_addr >> GDFunction::ADDR_BITS) {
case GDFunction::ADDR_TYPE_SELF: {
return "self";
@@ -448,434 +500,417 @@ static String _disassemble_addr(const Ref<GDScript>& p_script,const GDFunction&
} break;
case GDFunction::ADDR_TYPE_MEMBER: {
- return "member("+p_script->debug_get_member_by_index(addr)+")";
+ return "member(" + p_script->debug_get_member_by_index(addr) + ")";
} break;
case GDFunction::ADDR_TYPE_CLASS_CONSTANT: {
- return "class_const("+func.get_global_name(addr)+")";
+ return "class_const(" + func.get_global_name(addr) + ")";
} break;
case GDFunction::ADDR_TYPE_LOCAL_CONSTANT: {
- Variant v=func.get_constant(addr);
+ Variant v = func.get_constant(addr);
String txt;
- if (v.get_type()==Variant::STRING || v.get_type()==Variant::NODE_PATH)
- txt="\""+String(v)+"\"";
+ if (v.get_type() == Variant::STRING || v.get_type() == Variant::NODE_PATH)
+ txt = "\"" + String(v) + "\"";
else
- txt=v;
- return "const("+txt+")";
+ txt = v;
+ return "const(" + txt + ")";
} break;
case GDFunction::ADDR_TYPE_STACK: {
- return "stack("+itos(addr)+")";
+ return "stack(" + itos(addr) + ")";
} break;
case GDFunction::ADDR_TYPE_STACK_VARIABLE: {
- return "var_stack("+itos(addr)+")";
+ return "var_stack(" + itos(addr) + ")";
} break;
case GDFunction::ADDR_TYPE_GLOBAL: {
- return "global("+func.get_global_name(addr)+")";
+ return "global(" + func.get_global_name(addr) + ")";
} break;
case GDFunction::ADDR_TYPE_NIL: {
return "nil";
} break;
-
}
return "<err>";
}
-static void _disassemble_class(const Ref<GDScript>& p_class,const Vector<String>& p_code) {
-
+static void _disassemble_class(const Ref<GDScript> &p_class, const Vector<String> &p_code) {
- const Map<StringName,GDFunction*>& mf = p_class->debug_get_member_functions();
+ const Map<StringName, GDFunction *> &mf = p_class->debug_get_member_functions();
- for(const Map<StringName,GDFunction*>::Element *E=mf.front();E;E=E->next()) {
+ for (const Map<StringName, GDFunction *>::Element *E = mf.front(); E; E = E->next()) {
-
- const GDFunction &func=*E->get();
+ const GDFunction &func = *E->get();
const int *code = func.get_code();
- int codelen=func.get_code_size();
+ int codelen = func.get_code_size();
String defargs;
if (func.get_default_argument_count()) {
- defargs="defarg at: ";
- for(int i=0;i<func.get_default_argument_count();i++) {
+ defargs = "defarg at: ";
+ for (int i = 0; i < func.get_default_argument_count(); i++) {
- if (i>0)
- defargs+=",";
- defargs+=itos(func.get_default_argument_addr(i));
+ if (i > 0)
+ defargs += ",";
+ defargs += itos(func.get_default_argument_addr(i));
}
- defargs+=" ";
+ defargs += " ";
}
- print_line("== function "+String(func.get_name())+"() :: stack size: "+itos(func.get_max_stack_size())+" "+defargs+"==");
-
-#define DADDR(m_ip) (_disassemble_addr(p_class,func,code[ip+m_ip]))
+ print_line("== function " + String(func.get_name()) + "() :: stack size: " + itos(func.get_max_stack_size()) + " " + defargs + "==");
- for(int ip=0;ip<codelen;) {
+#define DADDR(m_ip) (_disassemble_addr(p_class, func, code[ip + m_ip]))
+ for (int ip = 0; ip < codelen;) {
- int incr=0;
- String txt=itos(ip)+" ";
+ int incr = 0;
+ String txt = itos(ip) + " ";
- switch(code[ip]) {
+ switch (code[ip]) {
case GDFunction::OPCODE_OPERATOR: {
- int op = code[ip+1];
- txt+="op ";
+ int op = code[ip + 1];
+ txt += "op ";
String opname = Variant::get_operator_name(Variant::Operator(op));
- txt+=DADDR(4);
- txt+=" = ";
- txt+=DADDR(2);
- txt+=" "+opname+" ";
- txt+=DADDR(3);
- incr+=5;
+ txt += DADDR(4);
+ txt += " = ";
+ txt += DADDR(2);
+ txt += " " + opname + " ";
+ txt += DADDR(3);
+ incr += 5;
} break;
case GDFunction::OPCODE_SET: {
- txt+="set ";
- txt+=DADDR(1);
- txt+="[";
- txt+=DADDR(2);
- txt+="]=";
- txt+=DADDR(3);
- incr+=4;
+ txt += "set ";
+ txt += DADDR(1);
+ txt += "[";
+ txt += DADDR(2);
+ txt += "]=";
+ txt += DADDR(3);
+ incr += 4;
} break;
case GDFunction::OPCODE_GET: {
- txt+=" get ";
- txt+=DADDR(3);
- txt+="=";
- txt+=DADDR(1);
- txt+="[";
- txt+=DADDR(2);
- txt+="]";
- incr+=4;
+ txt += " get ";
+ txt += DADDR(3);
+ txt += "=";
+ txt += DADDR(1);
+ txt += "[";
+ txt += DADDR(2);
+ txt += "]";
+ incr += 4;
} break;
case GDFunction::OPCODE_SET_NAMED: {
- txt+=" set_named ";
- txt+=DADDR(1);
- txt+="[\"";
- txt+=func.get_global_name(code[ip+2]);
- txt+="\"]=";
- txt+=DADDR(3);
- incr+=4;
-
+ txt += " set_named ";
+ txt += DADDR(1);
+ txt += "[\"";
+ txt += func.get_global_name(code[ip + 2]);
+ txt += "\"]=";
+ txt += DADDR(3);
+ incr += 4;
} break;
case GDFunction::OPCODE_GET_NAMED: {
- txt+=" get_named ";
- txt+=DADDR(3);
- txt+="=";
- txt+=DADDR(1);
- txt+="[\"";
- txt+=func.get_global_name(code[ip+2]);
- txt+="\"]";
- incr+=4;
+ txt += " get_named ";
+ txt += DADDR(3);
+ txt += "=";
+ txt += DADDR(1);
+ txt += "[\"";
+ txt += func.get_global_name(code[ip + 2]);
+ txt += "\"]";
+ incr += 4;
} break;
case GDFunction::OPCODE_SET_MEMBER: {
- txt+=" set_member ";
- txt+="[\"";
- txt+=func.get_global_name(code[ip+1]);
- txt+="\"]=";
- txt+=DADDR(2);
- incr+=3;
-
+ txt += " set_member ";
+ txt += "[\"";
+ txt += func.get_global_name(code[ip + 1]);
+ txt += "\"]=";
+ txt += DADDR(2);
+ incr += 3;
} break;
case GDFunction::OPCODE_GET_MEMBER: {
- txt+=" get_member ";
- txt+=DADDR(2);
- txt+="=";
- txt+="[\"";
- txt+=func.get_global_name(code[ip+1]);
- txt+="\"]";
- incr+=3;
+ txt += " get_member ";
+ txt += DADDR(2);
+ txt += "=";
+ txt += "[\"";
+ txt += func.get_global_name(code[ip + 1]);
+ txt += "\"]";
+ incr += 3;
} break;
case GDFunction::OPCODE_ASSIGN: {
- txt+=" assign ";
- txt+=DADDR(1);
- txt+="=";
- txt+=DADDR(2);
- incr+=3;
-
+ txt += " assign ";
+ txt += DADDR(1);
+ txt += "=";
+ txt += DADDR(2);
+ incr += 3;
} break;
case GDFunction::OPCODE_ASSIGN_TRUE: {
- txt+=" assign ";
- txt+=DADDR(1);
- txt+="= true";
- incr+=2;
+ txt += " assign ";
+ txt += DADDR(1);
+ txt += "= true";
+ incr += 2;
} break;
case GDFunction::OPCODE_ASSIGN_FALSE: {
- txt+=" assign ";
- txt+=DADDR(1);
- txt+="= false";
- incr+=2;
+ txt += " assign ";
+ txt += DADDR(1);
+ txt += "= false";
+ incr += 2;
} break;
case GDFunction::OPCODE_CONSTRUCT: {
- Variant::Type t=Variant::Type(code[ip+1]);
- int argc=code[ip+2];
+ Variant::Type t = Variant::Type(code[ip + 1]);
+ int argc = code[ip + 2];
- txt+=" construct ";
- txt+=DADDR(3+argc);
- txt+=" = ";
+ txt += " construct ";
+ txt += DADDR(3 + argc);
+ txt += " = ";
- txt+=Variant::get_type_name(t)+"(";
- for(int i=0;i<argc;i++) {
+ txt += Variant::get_type_name(t) + "(";
+ for (int i = 0; i < argc; i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(i+3);
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(i + 3);
}
- txt+=")";
+ txt += ")";
- incr=4+argc;
+ incr = 4 + argc;
} break;
case GDFunction::OPCODE_CONSTRUCT_ARRAY: {
- int argc=code[ip+1];
- txt+=" make_array ";
- txt+=DADDR(2+argc);
- txt+=" = [ ";
+ int argc = code[ip + 1];
+ txt += " make_array ";
+ txt += DADDR(2 + argc);
+ txt += " = [ ";
- for(int i=0;i<argc;i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(2+i);
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(2 + i);
}
- txt+="]";
+ txt += "]";
- incr+=3+argc;
+ incr += 3 + argc;
} break;
case GDFunction::OPCODE_CONSTRUCT_DICTIONARY: {
- int argc=code[ip+1];
- txt+=" make_dict ";
- txt+=DADDR(2+argc*2);
- txt+=" = { ";
-
- for(int i=0;i<argc;i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(2+i*2+0);
- txt+=":";
- txt+=DADDR(2+i*2+1);
+ int argc = code[ip + 1];
+ txt += " make_dict ";
+ txt += DADDR(2 + argc * 2);
+ txt += " = { ";
+
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(2 + i * 2 + 0);
+ txt += ":";
+ txt += DADDR(2 + i * 2 + 1);
}
- txt+="}";
+ txt += "}";
- incr+=3+argc*2;
+ incr += 3 + argc * 2;
} break;
case GDFunction::OPCODE_CALL:
case GDFunction::OPCODE_CALL_RETURN: {
- bool ret=code[ip]==GDFunction::OPCODE_CALL_RETURN;
+ bool ret = code[ip] == GDFunction::OPCODE_CALL_RETURN;
if (ret)
- txt+=" call-ret ";
+ txt += " call-ret ";
else
- txt+=" call ";
-
+ txt += " call ";
- int argc=code[ip+1];
+ int argc = code[ip + 1];
if (ret) {
- txt+=DADDR(4+argc)+"=";
+ txt += DADDR(4 + argc) + "=";
}
- txt+=DADDR(2)+".";
- txt+=String(func.get_global_name(code[ip+3]));
- txt+="(";
+ txt += DADDR(2) + ".";
+ txt += String(func.get_global_name(code[ip + 3]));
+ txt += "(";
- for(int i=0;i<argc;i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(4+i);
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(4 + i);
}
- txt+=")";
+ txt += ")";
-
- incr=5+argc;
+ incr = 5 + argc;
} break;
case GDFunction::OPCODE_CALL_BUILT_IN: {
- txt+=" call-built-in ";
+ txt += " call-built-in ";
- int argc=code[ip+2];
- txt+=DADDR(3+argc)+"=";
+ int argc = code[ip + 2];
+ txt += DADDR(3 + argc) + "=";
- txt+=GDFunctions::get_func_name(GDFunctions::Function(code[ip+1]));
- txt+="(";
+ txt += GDFunctions::get_func_name(GDFunctions::Function(code[ip + 1]));
+ txt += "(";
- for(int i=0;i<argc;i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(3+i);
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(3 + i);
}
- txt+=")";
-
+ txt += ")";
- incr=4+argc;
+ incr = 4 + argc;
} break;
case GDFunction::OPCODE_CALL_SELF_BASE: {
- txt+=" call-self-base ";
+ txt += " call-self-base ";
- int argc=code[ip+2];
- txt+=DADDR(3+argc)+"=";
+ int argc = code[ip + 2];
+ txt += DADDR(3 + argc) + "=";
- txt+=func.get_global_name(code[ip+1]);
- txt+="(";
+ txt += func.get_global_name(code[ip + 1]);
+ txt += "(";
- for(int i=0;i<argc;i++) {
- if (i>0)
- txt+=", ";
- txt+=DADDR(3+i);
+ for (int i = 0; i < argc; i++) {
+ if (i > 0)
+ txt += ", ";
+ txt += DADDR(3 + i);
}
- txt+=")";
-
+ txt += ")";
- incr=4+argc;
+ incr = 4 + argc;
} break;
case GDFunction::OPCODE_YIELD: {
- txt+=" yield ";
- incr=1;
+ txt += " yield ";
+ incr = 1;
} break;
case GDFunction::OPCODE_YIELD_SIGNAL: {
- txt+=" yield_signal ";
- txt+=DADDR(1);
- txt+=",";
- txt+=DADDR(2);
- incr=3;
+ txt += " yield_signal ";
+ txt += DADDR(1);
+ txt += ",";
+ txt += DADDR(2);
+ incr = 3;
} break;
case GDFunction::OPCODE_YIELD_RESUME: {
- txt+=" yield resume: ";
- txt+=DADDR(1);
- incr=2;
+ txt += " yield resume: ";
+ txt += DADDR(1);
+ incr = 2;
} break;
case GDFunction::OPCODE_JUMP: {
- txt+=" jump ";
- txt+=itos(code[ip+1]);
+ txt += " jump ";
+ txt += itos(code[ip + 1]);
- incr=2;
+ incr = 2;
} break;
case GDFunction::OPCODE_JUMP_IF: {
+ txt += " jump-if ";
+ txt += DADDR(1);
+ txt += " to ";
+ txt += itos(code[ip + 2]);
- txt+=" jump-if ";
- txt+=DADDR(1);
- txt+=" to ";
- txt+=itos(code[ip+2]);
-
- incr=3;
+ incr = 3;
} break;
case GDFunction::OPCODE_JUMP_IF_NOT: {
+ txt += " jump-if-not ";
+ txt += DADDR(1);
+ txt += " to ";
+ txt += itos(code[ip + 2]);
- txt+=" jump-if-not ";
- txt+=DADDR(1);
- txt+=" to ";
- txt+=itos(code[ip+2]);
-
- incr=3;
+ incr = 3;
} break;
case GDFunction::OPCODE_JUMP_TO_DEF_ARGUMENT: {
-
- txt+=" jump-to-default-argument ";
- incr=1;
+ txt += " jump-to-default-argument ";
+ incr = 1;
} break;
case GDFunction::OPCODE_RETURN: {
- txt+=" return ";
- txt+=DADDR(1);
+ txt += " return ";
+ txt += DADDR(1);
- incr=2;
+ incr = 2;
} break;
case GDFunction::OPCODE_ITERATE_BEGIN: {
- txt+=" for-init "+DADDR(4)+" in "+DADDR(2)+" counter "+DADDR(1)+" end "+itos(code[ip+3]);
- incr+=5;
+ txt += " for-init " + DADDR(4) + " in " + DADDR(2) + " counter " + DADDR(1) + " end " + itos(code[ip + 3]);
+ incr += 5;
} break;
case GDFunction::OPCODE_ITERATE: {
- txt+=" for-loop "+DADDR(4)+" in "+DADDR(2)+" counter "+DADDR(1)+" end "+itos(code[ip+3]);
- incr+=5;
+ txt += " for-loop " + DADDR(4) + " in " + DADDR(2) + " counter " + DADDR(1) + " end " + itos(code[ip + 3]);
+ incr += 5;
} break;
case GDFunction::OPCODE_LINE: {
-
-
- int line = code[ip+1]-1;
- if (line>=0 && line <p_code.size())
- txt="\n"+itos(line+1)+": "+p_code[line]+"\n";
+ int line = code[ip + 1] - 1;
+ if (line >= 0 && line < p_code.size())
+ txt = "\n" + itos(line + 1) + ": " + p_code[line] + "\n";
else
- txt="";
- incr+=2;
+ txt = "";
+ incr += 2;
} break;
case GDFunction::OPCODE_END: {
- txt+=" end";
- incr+=1;
+ txt += " end";
+ incr += 1;
} break;
case GDFunction::OPCODE_ASSERT: {
- txt+=" assert ";
- txt+=DADDR(1);
- incr+=2;
+ txt += " assert ";
+ txt += DADDR(1);
+ incr += 2;
} break;
-
}
- if (incr==0) {
+ if (incr == 0) {
- ERR_EXPLAIN("unhandled opcode: "+itos(code[ip]));
- ERR_BREAK(incr==0);
+ ERR_EXPLAIN("unhandled opcode: " + itos(code[ip]));
+ ERR_BREAK(incr == 0);
}
- ip+=incr;
- if (txt!="")
+ ip += incr;
+ if (txt != "")
print_line(txt);
}
}
}
-MainLoop* test(TestType p_test) {
+MainLoop *test(TestType p_test) {
List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
@@ -886,153 +921,137 @@ MainLoop* test(TestType p_test) {
String test = cmdlargs.back()->get();
- FileAccess *fa = FileAccess::open(test,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(test, FileAccess::READ);
if (!fa) {
- ERR_EXPLAIN("Could not open file: "+test);
+ ERR_EXPLAIN("Could not open file: " + test);
ERR_FAIL_V(NULL);
}
-
Vector<uint8_t> buf;
int flen = fa->get_len();
- buf.resize(fa->get_len()+1);
- fa->get_buffer(&buf[0],flen);
- buf[flen]=0;
+ buf.resize(fa->get_len() + 1);
+ fa->get_buffer(&buf[0], flen);
+ buf[flen] = 0;
String code;
- code.parse_utf8((const char*)&buf[0]);
+ code.parse_utf8((const char *)&buf[0]);
Vector<String> lines;
- int last=0;
+ int last = 0;
- for(int i=0;i<=code.length();i++) {
+ for (int i = 0; i <= code.length(); i++) {
- if (code[i]=='\n' || code[i]==0) {
+ if (code[i] == '\n' || code[i] == 0) {
- lines.push_back(code.substr(last,i-last));
- last=i+1;
+ lines.push_back(code.substr(last, i - last));
+ last = i + 1;
}
}
-
- if (p_test==TEST_TOKENIZER) {
+ if (p_test == TEST_TOKENIZER) {
GDTokenizerText tk;
tk.set_code(code);
- int line=-1;
- while(tk.get_token()!=GDTokenizer::TK_EOF) {
-
+ int line = -1;
+ while (tk.get_token() != GDTokenizer::TK_EOF) {
String text;
- if (tk.get_token()==GDTokenizer::TK_IDENTIFIER)
- text="'"+tk.get_token_identifier()+"' (identifier)";
- else if (tk.get_token()==GDTokenizer::TK_CONSTANT) {
- Variant c= tk.get_token_constant();
- if (c.get_type()==Variant::STRING)
- text="\""+String(c)+"\"";
+ if (tk.get_token() == GDTokenizer::TK_IDENTIFIER)
+ text = "'" + tk.get_token_identifier() + "' (identifier)";
+ else if (tk.get_token() == GDTokenizer::TK_CONSTANT) {
+ Variant c = tk.get_token_constant();
+ if (c.get_type() == Variant::STRING)
+ text = "\"" + String(c) + "\"";
else
- text=c;
-
- text=text+" ("+Variant::get_type_name(c.get_type())+" constant)";
- } else if (tk.get_token()==GDTokenizer::TK_ERROR)
- text="ERROR: "+tk.get_token_error();
- else if (tk.get_token()==GDTokenizer::TK_NEWLINE)
- text="newline ("+itos(tk.get_token_line())+") + indent: "+itos(tk.get_token_line_indent());
- else if (tk.get_token()==GDTokenizer::TK_BUILT_IN_FUNC)
- text="'"+String(GDFunctions::get_func_name(tk.get_token_built_in_func()))+"' (built-in function)";
+ text = c;
+
+ text = text + " (" + Variant::get_type_name(c.get_type()) + " constant)";
+ } else if (tk.get_token() == GDTokenizer::TK_ERROR)
+ text = "ERROR: " + tk.get_token_error();
+ else if (tk.get_token() == GDTokenizer::TK_NEWLINE)
+ text = "newline (" + itos(tk.get_token_line()) + ") + indent: " + itos(tk.get_token_line_indent());
+ else if (tk.get_token() == GDTokenizer::TK_BUILT_IN_FUNC)
+ text = "'" + String(GDFunctions::get_func_name(tk.get_token_built_in_func())) + "' (built-in function)";
else
- text=tk.get_token_name(tk.get_token());
-
+ text = tk.get_token_name(tk.get_token());
- if (tk.get_token_line()!=line) {
- int from=line+1;
+ if (tk.get_token_line() != line) {
+ int from = line + 1;
line = tk.get_token_line();
- for(int i=from;i<=line;i++) {
- int l=i-1;
- if (l>=0 && l<lines.size()) {
- print_line("\n"+itos(i)+": "+lines[l]+"\n");
+ for (int i = from; i <= line; i++) {
+ int l = i - 1;
+ if (l >= 0 && l < lines.size()) {
+ print_line("\n" + itos(i) + ": " + lines[l] + "\n");
}
}
}
- print_line("\t("+itos(tk.get_token_column())+"): "+text);
+ print_line("\t(" + itos(tk.get_token_column()) + "): " + text);
tk.advance();
-
}
}
- if (p_test==TEST_PARSER) {
-
+ if (p_test == TEST_PARSER) {
GDParser parser;
Error err = parser.parse(code);
if (err) {
- print_line("Parse Error:\n"+itos(parser.get_error_line())+":"+itos(parser.get_error_column())+":"+parser.get_error());
+ print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
memdelete(fa);
return NULL;
-
}
- const GDParser::Node* root = parser.get_parse_tree();
- ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,NULL);
- const GDParser::ClassNode *cnode=static_cast<const GDParser::ClassNode*>(root);
-
- _parser_show_class(cnode,0,lines);
+ const GDParser::Node *root = parser.get_parse_tree();
+ ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, NULL);
+ const GDParser::ClassNode *cnode = static_cast<const GDParser::ClassNode *>(root);
+ _parser_show_class(cnode, 0, lines);
}
- if (p_test==TEST_COMPILER) {
-
+ if (p_test == TEST_COMPILER) {
GDParser parser;
Error err = parser.parse(code);
if (err) {
- print_line("Parse Error:\n"+itos(parser.get_error_line())+":"+itos(parser.get_error_column())+":"+parser.get_error());
+ print_line("Parse Error:\n" + itos(parser.get_error_line()) + ":" + itos(parser.get_error_column()) + ":" + parser.get_error());
memdelete(fa);
return NULL;
-
}
- GDScript *script = memnew( GDScript );
+ GDScript *script = memnew(GDScript);
GDCompiler gdc;
- err = gdc.compile(&parser,script);
+ err = gdc.compile(&parser, script);
if (err) {
- print_line("Compile Error:\n"+itos(gdc.get_error_line())+":"+itos(gdc.get_error_column())+":"+gdc.get_error());
+ print_line("Compile Error:\n" + itos(gdc.get_error_line()) + ":" + itos(gdc.get_error_column()) + ":" + gdc.get_error());
memdelete(script);
return NULL;
-
}
+ Ref<GDScript> gds = Ref<GDScript>(script);
- Ref<GDScript> gds =Ref<GDScript>( script );
-
- Ref<GDScript> current=gds;
+ Ref<GDScript> current = gds;
- while(current.is_valid()) {
+ while (current.is_valid()) {
print_line("** CLASS **");
- _disassemble_class(current,lines);
+ _disassemble_class(current, lines);
- current=current->get_base();
+ current = current->get_base();
}
-
-
-
- } else if (p_test==TEST_BYTECODE) {
+ } else if (p_test == TEST_BYTECODE) {
Vector<uint8_t> buf = GDTokenizerBuffer::parse_code_string(code);
- String dst = test.get_basename()+".gdc";
- FileAccess *fw = FileAccess::open(dst,FileAccess::WRITE);
- fw->store_buffer(buf.ptr(),buf.size());
+ String dst = test.get_basename() + ".gdc";
+ FileAccess *fw = FileAccess::open(dst, FileAccess::WRITE);
+ fw->store_buffer(buf.ptr(), buf.size());
memdelete(fw);
}
-
#if 0
Parser parser;
Error err = parser.parse(code);
@@ -1043,20 +1062,17 @@ MainLoop* test(TestType p_test) {
}
#endif
-
-
memdelete(fa);
return NULL;
}
-
}
#else
namespace TestGDScript {
-MainLoop* test(TestType p_test) {
+MainLoop *test(TestType p_test) {
return NULL;
}
diff --git a/main/tests/test_gdscript.h b/main/tests/test_gdscript.h
index 7541e7b20f..3b2a4aa4ec 100644
--- a/main/tests/test_gdscript.h
+++ b/main/tests/test_gdscript.h
@@ -40,8 +40,7 @@ enum TestType {
TEST_BYTECODE,
};
-MainLoop* test(TestType p_type);
-
+MainLoop *test(TestType p_type);
}
#endif // TEST_GDSCRIPT_H
diff --git a/main/tests/test_gui.cpp b/main/tests/test_gui.cpp
index 6833558f07..c291afaf32 100644
--- a/main/tests/test_gui.cpp
+++ b/main/tests/test_gui.cpp
@@ -30,51 +30,46 @@
#include "test_gui.h"
-#include "scene/main/scene_main_loop.h"
+#include "io/image_loader.h"
#include "os/os.h"
-#include "scene/gui/control.h"
+#include "print_string.h"
+#include "scene/2d/sprite.h"
#include "scene/gui/button.h"
+#include "scene/gui/control.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
-#include "scene/gui/scroll_bar.h"
-#include "scene/gui/popup_menu.h"
-#include "scene/gui/option_button.h"
-#include "scene/gui/spin_box.h"
#include "scene/gui/menu_button.h"
-#include "scene/gui/progress_bar.h"
+#include "scene/gui/option_button.h"
#include "scene/gui/panel.h"
-#include "scene/gui/tab_container.h"
-#include "scene/gui/tree.h"
+#include "scene/gui/popup_menu.h"
+#include "scene/gui/progress_bar.h"
#include "scene/gui/rich_text_label.h"
+#include "scene/gui/scroll_bar.h"
+#include "scene/gui/spin_box.h"
+#include "scene/gui/tab_container.h"
#include "scene/gui/texture_rect.h"
-#include "io/image_loader.h"
-#include "print_string.h"
-#include "scene/2d/sprite.h"
+#include "scene/gui/tree.h"
+#include "scene/main/scene_main_loop.h"
-#include "scene/main/viewport.h"
#include "scene/3d/camera.h"
#include "scene/3d/test_cube.h"
+#include "scene/main/viewport.h"
namespace TestGUI {
-
class TestMainLoop : public SceneTree {
-
Control *control;
public:
-
virtual void request_quit() {
quit();
-
}
virtual void init() {
SceneTree::init();
-
#if 0
@@ -105,35 +100,33 @@ public:
return;
#endif
- Panel * frame = memnew( Panel );
- frame->set_anchor( MARGIN_RIGHT, Control::ANCHOR_END );
- frame->set_anchor( MARGIN_BOTTOM, Control::ANCHOR_END );
- frame->set_end( Point2(0,0) );
+ Panel *frame = memnew(Panel);
+ frame->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
+ frame->set_anchor(MARGIN_BOTTOM, Control::ANCHOR_END);
+ frame->set_end(Point2(0, 0));
- Ref<Theme> t = memnew( Theme );
+ Ref<Theme> t = memnew(Theme);
frame->set_theme(t);
- get_root()->add_child( frame );
+ get_root()->add_child(frame);
- Label *label = memnew( Label );
+ Label *label = memnew(Label);
- label->set_pos( Point2( 80,90 ) );
- label->set_size( Point2( 170,80 ) );
- label->set_align( Label::ALIGN_FILL );
+ label->set_pos(Point2(80, 90));
+ label->set_size(Point2(170, 80));
+ label->set_align(Label::ALIGN_FILL);
//label->set_text("There");
label->set_text("There was once upon a time a beautiful unicorn that loved to play with little girls...");
frame->add_child(label);
- Button *button = memnew( Button );
+ Button *button = memnew(Button);
- button->set_pos( Point2( 20,20 ) );
- button->set_size( Point2( 1,1 ) );
+ button->set_pos(Point2(20, 20));
+ button->set_size(Point2(1, 1));
button->set_text("This is a biggie button");
-
- frame->add_child( button );
-
+ frame->add_child(button);
#if 0
Sprite *tf = memnew( Sprite );
@@ -154,90 +147,85 @@ public:
return;
#endif
- Tree * tree = memnew( Tree );
+ Tree *tree = memnew(Tree);
tree->set_columns(2);
- tree->set_pos( Point2( 230,210 ) );
- tree->set_size( Point2( 150,250 ) );
-
+ tree->set_pos(Point2(230, 210));
+ tree->set_size(Point2(150, 250));
TreeItem *item = tree->create_item();
- item->set_editable(0,true);
- item->set_text(0,"root");
- item = tree->create_item( tree->get_root() );
+ item->set_editable(0, true);
+ item->set_text(0, "root");
+ item = tree->create_item(tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_CHECK);
- item->set_editable(0,true);
- item->set_text(0,"check");
+ item->set_editable(0, true);
+ item->set_text(0, "check");
item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
- item->set_editable(1,true);
- item->set_text(1,"check2");
- item = tree->create_item( tree->get_root() );
+ item->set_editable(1, true);
+ item->set_text(1, "check2");
+ item = tree->create_item(tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
- item->set_editable(0,true);
- item->set_range_config(0,0,20,0.1);
- item->set_range(0,2);
- item->add_button(0,Theme::get_default()->get_icon("folder","FileDialog"));
+ item->set_editable(0, true);
+ item->set_range_config(0, 0, 20, 0.1);
+ item->set_range(0, 2);
+ item->add_button(0, Theme::get_default()->get_icon("folder", "FileDialog"));
item->set_cell_mode(1, TreeItem::CELL_MODE_RANGE);
- item->set_editable(1,true);
- item->set_range_config(1,0,20,0.1);
- item->set_range(1,3);
+ item->set_editable(1, true);
+ item->set_range_config(1, 0, 20, 0.1);
+ item->set_range(1, 3);
- item = tree->create_item( tree->get_root() );
+ item = tree->create_item(tree->get_root());
item->set_cell_mode(0, TreeItem::CELL_MODE_RANGE);
- item->set_editable(0,true);
- item->set_text(0,"Have,Many,Several,Options!");
- item->set_range(0,2);
+ item->set_editable(0, true);
+ item->set_text(0, "Have,Many,Several,Options!");
+ item->set_range(0, 2);
- item = tree->create_item( item );
- item->set_editable(0,true);
- item->set_text(0,"Gershwin!");
+ item = tree->create_item(item);
+ item->set_editable(0, true);
+ item->set_text(0, "Gershwin!");
frame->add_child(tree);
//control = memnew( Control );
//root->add_child( control );
+ LineEdit *line_edit = memnew(LineEdit);
-
- LineEdit *line_edit = memnew( LineEdit );
-
- line_edit->set_pos( Point2( 30,190 ) );
- line_edit->set_size( Point2( 180,1 ) );
+ line_edit->set_pos(Point2(30, 190));
+ line_edit->set_size(Point2(180, 1));
frame->add_child(line_edit);
- HScrollBar *hscroll = memnew( HScrollBar );
+ HScrollBar *hscroll = memnew(HScrollBar);
- hscroll->set_pos( Point2( 30,290 ) );
- hscroll->set_size( Point2( 180,1 ) );
+ hscroll->set_pos(Point2(30, 290));
+ hscroll->set_size(Point2(180, 1));
hscroll->set_max(10);
hscroll->set_page(4);
frame->add_child(hscroll);
+ SpinBox *spin = memnew(SpinBox);
-
- SpinBox *spin = memnew( SpinBox );
-
- spin->set_pos( Point2( 30,260 ) );
- spin->set_size( Point2( 120,1 ) );
+ spin->set_pos(Point2(30, 260));
+ spin->set_size(Point2(120, 1));
frame->add_child(spin);
hscroll->share(spin);
- ProgressBar *progress = memnew( ProgressBar );
+ ProgressBar *progress = memnew(ProgressBar);
- progress->set_pos( Point2( 30,330 ) );
- progress->set_size( Point2( 120,1 ) );
+ progress->set_pos(Point2(30, 330));
+ progress->set_size(Point2(120, 1));
frame->add_child(progress);
hscroll->share(progress);
- MenuButton *menu_button = memnew( MenuButton );
+ MenuButton *menu_button = memnew(MenuButton);
menu_button->set_text("I'm a menu!");
- menu_button->set_pos( Point2( 30,380 ) );
- menu_button->set_size( Point2( 1,1 ) );
+ menu_button->set_pos(Point2(30, 380));
+ menu_button->set_size(Point2(1, 1));
frame->add_child(menu_button);
@@ -248,15 +236,15 @@ public:
popup->add_separator();
popup->add_item("Popup");
popup->add_check_item("Check Popup");
- popup->set_item_checked(4,true);
+ popup->set_item_checked(4, true);
- OptionButton *options = memnew( OptionButton );
+ OptionButton *options = memnew(OptionButton);
options->add_item("Hello, testing");
options->add_item("My Dearest");
- options->set_pos( Point2( 230,180 ) );
- options->set_size( Point2( 1,1 ) );
+ options->set_pos(Point2(230, 180));
+ options->set_size(Point2(1, 1));
frame->add_child(options);
@@ -290,32 +278,30 @@ public:
frame->add_child(tree);
*/
+ RichTextLabel *richtext = memnew(RichTextLabel);
- RichTextLabel *richtext = memnew( RichTextLabel );
-
- richtext->set_pos( Point2( 600,210 ) );
- richtext->set_size( Point2( 180,250 ) );
- richtext->set_anchor_and_margin(MARGIN_RIGHT,Control::ANCHOR_END,20);
+ richtext->set_pos(Point2(600, 210));
+ richtext->set_size(Point2(180, 250));
+ richtext->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, 20);
frame->add_child(richtext);
-
richtext->add_text("Hello, My Friends!\n\nWelcome to the amazing world of ");
richtext->add_newline();
richtext->add_newline();
- richtext->push_color(Color(1,0.5,0.5));
+ richtext->push_color(Color(1, 0.5, 0.5));
richtext->add_text("leprechauns");
richtext->pop();
richtext->add_text(" and ");
- richtext->push_color(Color(0,1.0,0.5));
+ richtext->push_color(Color(0, 1.0, 0.5));
richtext->add_text("faeries.\n");
richtext->pop();
richtext->add_text("In this new episode, we will attemp to ");
- richtext->push_font(richtext->get_font("mono_font","Fonts"));
- richtext->push_color(Color(0.7,0.5,1.0));
+ richtext->push_font(richtext->get_font("mono_font", "Fonts"));
+ richtext->push_color(Color(0.7, 0.5, 1.0));
richtext->add_text("deliver something nice");
richtext->pop();
richtext->pop();
@@ -333,42 +319,39 @@ public:
richtext->add_text("of the rich text label for huge text (not like this text will really be huge but, you know).\nAs long as it is so long that it will work nicely for a test/demo, then it's welcomed in my book...\nChanging subject, the day is cloudy today and I'm wondering if I'll get che chance to travel somewhere nice. Sometimes, watching the clouds from satellite images may give a nice insight about how pressure zones in our planet work, althogh it also makes it pretty obvious to see why most weather forecasts get it wrong so often.\nClouds are so difficult to predict!\nBut it's pretty cool how our civilization has adapted to having water falling from the sky each time it rains...");
//richtext->add_text("Hello!\nGorgeous..");
-
//richtext->push_meta("http://www.scrollingcapabilities.xz");
///richtext->add_text("Hello!\n");
//richtext->pop();
- richtext->set_anchor(MARGIN_RIGHT,Control::ANCHOR_END);
+ richtext->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
+ TabContainer *tabc = memnew(TabContainer);
- TabContainer * tabc = memnew( TabContainer );
-
- Control *ctl= memnew( Control );
+ Control *ctl = memnew(Control);
ctl->set_name("tab 1");
tabc->add_child(ctl);
- ctl= memnew( Control );
+ ctl = memnew(Control);
ctl->set_name("tab 2");
tabc->add_child(ctl);
- label = memnew( Label );
+ label = memnew(Label);
label->set_text("Some Label");
- label->set_pos( Point2(20,20) );
+ label->set_pos(Point2(20, 20));
ctl->add_child(label);
- ctl= memnew( Control );
+ ctl = memnew(Control);
ctl->set_name("tab 3");
- button = memnew( Button );
+ button = memnew(Button);
button->set_text("Some Button");
- button->set_pos( Point2(30,50) );
+ button->set_pos(Point2(30, 50));
ctl->add_child(button);
tabc->add_child(ctl);
frame->add_child(tabc);
- tabc->set_pos( Point2( 400,210 ) );
- tabc->set_size( Point2( 180,250 ) );
-
+ tabc->set_pos(Point2(400, 210));
+ tabc->set_size(Point2(180, 250));
/*Ref<ImageTexture> text = memnew( ImageTexture );
text->load("test_data/concave.png");
@@ -385,18 +368,12 @@ public:
sprite2->set_pos(Point2(50, 50));
sprite2->show();*/
}
-
-
-
};
+MainLoop *test() {
-MainLoop* test() {
-
-
- return memnew( TestMainLoop );
+ return memnew(TestMainLoop);
}
-
}
#endif
diff --git a/main/tests/test_gui.h b/main/tests/test_gui.h
index d053770bdd..5ffa077dc9 100644
--- a/main/tests/test_gui.h
+++ b/main/tests/test_gui.h
@@ -36,9 +36,7 @@
*/
namespace TestGUI {
-MainLoop* test();
-
+MainLoop *test();
}
-
#endif
diff --git a/main/tests/test_image.cpp b/main/tests/test_image.cpp
index dbe0111367..c57968ad10 100644
--- a/main/tests/test_image.cpp
+++ b/main/tests/test_image.cpp
@@ -28,26 +28,24 @@
/*************************************************************************/
#include "test_image.h"
-#include "os/main_loop.h"
+#include "io/image_loader.h"
#include "math_funcs.h"
+#include "os/main_loop.h"
#include "print_string.h"
-#include "io/image_loader.h"
namespace TestImage {
-
class TestMainLoop : public MainLoop {
bool quit;
-public:
- virtual void input_event(const InputEvent& p_event) {
-
+public:
+ virtual void input_event(const InputEvent &p_event) {
}
virtual void init() {
- quit=false;
+ quit = false;
}
virtual bool iteration(float p_time) {
@@ -59,21 +57,16 @@ public:
}
virtual void finish() {
-
}
-
};
-
-MainLoop* test() {
+MainLoop *test() {
Image img;
- ImageLoader::load_image("as1.png",&img);
-
- img.resize(512,512);
+ ImageLoader::load_image("as1.png", &img);
- return memnew( TestMainLoop );
+ img.resize(512, 512);
+ return memnew(TestMainLoop);
}
-
}
diff --git a/main/tests/test_image.h b/main/tests/test_image.h
index 51ce6d5cc7..f520462429 100644
--- a/main/tests/test_image.h
+++ b/main/tests/test_image.h
@@ -37,8 +37,7 @@
namespace TestImage {
-MainLoop* test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_io.cpp b/main/tests/test_io.cpp
index af4742afa7..dfc1f05383 100644
--- a/main/tests/test_io.cpp
+++ b/main/tests/test_io.cpp
@@ -30,31 +30,25 @@
#ifdef MINIZIP_ENABLED
-
-
-#include "os/main_loop.h"
-#include "os/os.h"
-#include "scene/resources/texture.h"
-#include "print_string.h"
+#include "core/global_config.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
#include "os/dir_access.h"
-#include "core/global_config.h"
+#include "os/main_loop.h"
+#include "os/os.h"
+#include "print_string.h"
+#include "scene/resources/texture.h"
#include "io/file_access_memory.h"
namespace TestIO {
-
class TestMainLoop : public MainLoop {
-
bool quit;
public:
- virtual void input_event(const InputEvent& p_event) {
-
-
+ virtual void input_event(const InputEvent &p_event) {
}
virtual bool idle(float p_time) {
return false;
@@ -62,53 +56,48 @@ public:
virtual void request_quit() {
- quit=true;
-
+ quit = true;
}
virtual void init() {
- quit=true;
+ quit = true;
}
virtual bool iteration(float p_time) {
return quit;
}
virtual void finish() {
-
}
-
-
};
-
-MainLoop* test() {
+MainLoop *test() {
print_line("this is test io");
- DirAccess* da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
+ DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
da->change_dir(".");
- print_line("Opening current dir "+ da->get_current_dir());
+ print_line("Opening current dir " + da->get_current_dir());
String entry;
da->list_dir_begin();
- while ( (entry = da->get_next()) != "") {
+ while ((entry = da->get_next()) != "") {
- print_line("entry "+entry+" is dir: " + Variant(da->current_is_dir()));
+ print_line("entry " + entry + " is dir: " + Variant(da->current_is_dir()));
};
da->list_dir_end();
RES texture = ResourceLoader::load("test_data/rock.png");
ERR_FAIL_COND_V(texture.is_null(), NULL);
- ResourceSaver::save("test_data/rock.xml",texture);
+ ResourceSaver::save("test_data/rock.xml", texture);
print_line("localize paths");
print_line(GlobalConfig::get_singleton()->localize_path("algo.xml"));
print_line(GlobalConfig::get_singleton()->localize_path("c:\\windows\\algo.xml"));
- print_line(GlobalConfig::get_singleton()->localize_path(GlobalConfig::get_singleton()->get_resource_path()+"/something/something.xml"));
+ print_line(GlobalConfig::get_singleton()->localize_path(GlobalConfig::get_singleton()->get_resource_path() + "/something/something.xml"));
print_line(GlobalConfig::get_singleton()->localize_path("somedir/algo.xml"));
{
- FileAccess* z = FileAccess::open("test_data/archive.zip", FileAccess::READ);
+ FileAccess *z = FileAccess::open("test_data/archive.zip", FileAccess::READ);
int len = z->get_len();
Vector<uint8_t> zip;
zip.resize(len);
@@ -186,23 +175,17 @@ MainLoop* test() {
print_line("test done");
-
- return memnew( TestMainLoop );
-
+ return memnew(TestMainLoop);
}
-
}
#else
namespace TestIO {
-
-MainLoop* test() {
+MainLoop *test() {
return NULL;
}
-
}
#endif
-
diff --git a/main/tests/test_io.h b/main/tests/test_io.h
index bb6a4a4474..21c1356c35 100644
--- a/main/tests/test_io.h
+++ b/main/tests/test_io.h
@@ -37,8 +37,7 @@
namespace TestIO {
-MainLoop* test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_main.cpp b/main/tests/test_main.cpp
index 27f7c2d025..ca039402c1 100644
--- a/main/tests/test_main.cpp
+++ b/main/tests/test_main.cpp
@@ -31,24 +31,23 @@
#ifdef DEBUG_ENABLED
-#include "test_string.h"
#include "test_containers.h"
-#include "test_math.h"
#include "test_gui.h"
-#include "test_render.h"
-#include "test_sound.h"
+#include "test_math.h"
#include "test_physics.h"
#include "test_physics_2d.h"
+#include "test_render.h"
+#include "test_sound.h"
+#include "test_string.h"
-#include "test_io.h"
-#include "test_shader_lang.h"
#include "test_gdscript.h"
#include "test_image.h"
+#include "test_io.h"
+#include "test_shader_lang.h"
+const char **tests_get_names() {
-const char ** tests_get_names() {
-
- static const char* test_names[]={
+ static const char *test_names[] = {
"string",
"containers",
"math",
@@ -64,82 +63,81 @@ const char ** tests_get_names() {
return test_names;
}
-MainLoop* test_main(String p_test,const List<String>& p_args) {
-
+MainLoop *test_main(String p_test, const List<String> &p_args) {
- if (p_test=="string") {
+ if (p_test == "string") {
return TestString::test();
}
- if (p_test=="containers") {
+ if (p_test == "containers") {
return TestContainers::test();
}
- if (p_test=="math") {
+ if (p_test == "math") {
return TestMath::test();
}
- if (p_test=="physics") {
+ if (p_test == "physics") {
return TestPhysics::test();
}
- if (p_test=="physics_2d") {
+ if (p_test == "physics_2d") {
return TestPhysics2D::test();
}
- if (p_test=="render") {
+ if (p_test == "render") {
return TestRender::test();
}
- #ifndef _3D_DISABLED
- if (p_test=="gui") {
+#ifndef _3D_DISABLED
+ if (p_test == "gui") {
return TestGUI::test();
}
- #endif
+#endif
//if (p_test=="sound") {
// return TestSound::test();
//}
- if (p_test=="io") {
+ if (p_test == "io") {
return TestIO::test();
}
- if (p_test=="shaderlang") {
+ if (p_test == "shaderlang") {
return TestShaderLang::test();
}
- if (p_test=="gd_tokenizer") {
+ if (p_test == "gd_tokenizer") {
return TestGDScript::test(TestGDScript::TEST_TOKENIZER);
}
- if (p_test=="gd_parser") {
+ if (p_test == "gd_parser") {
return TestGDScript::test(TestGDScript::TEST_PARSER);
}
- if (p_test=="gd_compiler") {
+ if (p_test == "gd_compiler") {
return TestGDScript::test(TestGDScript::TEST_COMPILER);
}
- if (p_test=="gd_bytecode") {
+ if (p_test == "gd_bytecode") {
return TestGDScript::test(TestGDScript::TEST_BYTECODE);
}
- if (p_test=="image") {
+ if (p_test == "image") {
return TestImage::test();
}
@@ -149,16 +147,16 @@ MainLoop* test_main(String p_test,const List<String>& p_args) {
#else
-const char ** tests_get_names() {
+const char **tests_get_names() {
- static const char* test_names[]={
+ static const char *test_names[] = {
NULL
};
return test_names;
}
-MainLoop* test_main(String p_test,const List<String>& p_args) {
+MainLoop *test_main(String p_test, const List<String> &p_args) {
return NULL;
}
diff --git a/main/tests/test_main.h b/main/tests/test_main.h
index 4d9419a4f6..729f2ca1f8 100644
--- a/main/tests/test_main.h
+++ b/main/tests/test_main.h
@@ -29,13 +29,10 @@
#ifndef TEST_MAIN_H
#define TEST_MAIN_H
-#include "ustring.h"
#include "list.h"
+#include "ustring.h"
-const char ** tests_get_names();
-MainLoop* test_main(String p_test,const List<String>& p_args);
-
+const char **tests_get_names();
+MainLoop *test_main(String p_test, const List<String> &p_args);
#endif
-
-
diff --git a/main/tests/test_math.cpp b/main/tests/test_math.cpp
index 43164bb2e6..c82ae1abf5 100644
--- a/main/tests/test_math.cpp
+++ b/main/tests/test_math.cpp
@@ -28,26 +28,25 @@
/*************************************************************************/
#include "test_math.h"
-#include "ustring.h"
-#include "print_string.h"
-#include "transform.h"
-#include "matrix3.h"
-#include "math_funcs.h"
#include "camera_matrix.h"
-#include "scene/main/node.h"
-#include "variant.h"
-#include "servers/visual/shader_language.h"
+#include "math_funcs.h"
+#include "matrix3.h"
+#include "os/file_access.h"
#include "os/keyboard.h"
+#include "os/os.h"
+#include "print_string.h"
+#include "scene/main/node.h"
#include "scene/resources/texture.h"
+#include "servers/visual/shader_language.h"
+#include "transform.h"
+#include "ustring.h"
+#include "variant.h"
#include "vmap.h"
-#include "os/os.h"
-#include "os/file_access.h"
#include "method_ptrcall.h"
namespace TestMath {
-
class GetClassAndNamespace {
String code;
@@ -75,11 +74,10 @@ class GetClassAndNamespace {
TK_ERROR
};
-
Token get_token() {
while (true) {
- switch(code[idx]) {
+ switch (code[idx]) {
case '\n': {
@@ -128,28 +126,27 @@ class GetClassAndNamespace {
};
case '#': {
//compiler directive
- while(code[idx]!='\n' && code[idx]!=0) {
+ while (code[idx] != '\n' && code[idx] != 0) {
idx++;
}
continue;
} break;
case '/': {
-
- switch(code[idx+1]) {
+ switch (code[idx + 1]) {
case '*': { // block comment
- idx+=2;
- while(true) {
- if (code[idx]==0) {
- error_str="Unterminated comment";
- error=true;
+ idx += 2;
+ while (true) {
+ if (code[idx] == 0) {
+ error_str = "Unterminated comment";
+ error = true;
return TK_ERROR;
- } else if (code[idx]=='*' &&code[idx+1]=='/') {
+ } else if (code[idx] == '*' && code[idx + 1] == '/') {
- idx+=2;
+ idx += 2;
break;
- } else if (code[idx]=='\n') {
+ } else if (code[idx] == '\n') {
line++;
}
@@ -159,17 +156,16 @@ class GetClassAndNamespace {
} break;
case '/': { // line comment skip
- while(code[idx]!='\n' && code[idx]!=0) {
+ while (code[idx] != '\n' && code[idx] != 0) {
idx++;
}
} break;
default: {
- value="/";
+ value = "/";
idx++;
return TK_SYMBOL;
}
-
}
continue; // a comment
@@ -179,34 +175,36 @@ class GetClassAndNamespace {
CharType begin_str = code[idx];
idx++;
- String tk_string=String();
- while(true) {
- if (code[idx]==0) {
- error_str="Unterminated String";
- error=true;
+ String tk_string = String();
+ while (true) {
+ if (code[idx] == 0) {
+ error_str = "Unterminated String";
+ error = true;
return TK_ERROR;
- } else if (code[idx]==begin_str) {
+ } else if (code[idx] == begin_str) {
idx++;
break;
- } else if (code[idx]=='\\') {
+ } else if (code[idx] == '\\') {
//escaped characters...
idx++;
CharType next = code[idx];
- if (next==0) {
- error_str="Unterminated String";
- error=true;
+ if (next == 0) {
+ error_str = "Unterminated String";
+ error = true;
return TK_ERROR;
}
- CharType res=0;
+ CharType res = 0;
- switch(next) {
+ 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;
- /* too much, not needed for now
+ 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;
+ /* too much, not needed for now
case 'u': {
//hexnumbarh - oct is deprecated
@@ -245,8 +243,10 @@ class GetClassAndNamespace {
} break;*/
- case '\"': res='\"'; break;
- case '\\': res='\\'; break;
+ case '\"': res = '\"'; break;
+ case '\\':
+ res = '\\';
+ break;
//case '/': res='/'; break;
default: {
res = next;
@@ -255,133 +255,130 @@ class GetClassAndNamespace {
} break;
}
- tk_string+=res;
+ tk_string += res;
} else {
- if (code[idx]=='\n')
+ if (code[idx] == '\n')
line++;
- tk_string+=code[idx];
+ tk_string += code[idx];
}
idx++;
}
- value=tk_string;
+ value = tk_string;
return TK_STRING;
} break;
default: {
- if (code[idx]<=32) {
+ if (code[idx] <= 32) {
idx++;
break;
}
- if ( (code[idx]>=33 && code[idx]<=47) || (code[idx]>=58 && code[idx]<=64) || (code[idx]>=91 && code[idx]<=96) || (code[idx]>=123 && code[idx]<=127)){
- value=String::chr(code[idx]);
+ if ((code[idx] >= 33 && code[idx] <= 47) || (code[idx] >= 58 && code[idx] <= 64) || (code[idx] >= 91 && code[idx] <= 96) || (code[idx] >= 123 && code[idx] <= 127)) {
+ value = String::chr(code[idx]);
idx++;
return TK_SYMBOL;
}
- if (code[idx]=='-' || (code[idx]>='0' && code[idx]<='9')) {
+ if (code[idx] == '-' || (code[idx] >= '0' && code[idx] <= '9')) {
//a number
const CharType *rptr;
- double number = String::to_double(&code[idx],&rptr);
- idx+=(rptr - &code[idx]);
- value=number;
+ double number = String::to_double(&code[idx], &rptr);
+ idx += (rptr - &code[idx]);
+ value = number;
return TK_NUMBER;
- } else if ((code[idx]>='A' && code[idx]<='Z') || (code[idx]>='a' && code[idx]<='z') || code[idx]>127) {
+ } else if ((code[idx] >= 'A' && code[idx] <= 'Z') || (code[idx] >= 'a' && code[idx] <= 'z') || code[idx] > 127) {
String id;
- while((code[idx]>='A' && code[idx]<='Z') || (code[idx]>='a' && code[idx]<='z') || code[idx]>127) {
+ while ((code[idx] >= 'A' && code[idx] <= 'Z') || (code[idx] >= 'a' && code[idx] <= 'z') || code[idx] > 127) {
- id+=code[idx];
+ id += code[idx];
idx++;
}
- value=id;
+ value = id;
return TK_IDENTIFIER;
} else {
- error_str="Unexpected character.";
- error=true;
+ error_str = "Unexpected character.";
+ error = true;
return TK_ERROR;
}
}
-
}
}
}
public:
- Error parse(const String& p_code,const String& p_known_class_name=String()) {
+ Error parse(const String &p_code, const String &p_known_class_name = String()) {
- code=p_code;
- idx=0;
- line=0;
- error_str=String();
- error=false;
- value=Variant();
- class_name=String();
+ code = p_code;
+ idx = 0;
+ line = 0;
+ error_str = String();
+ error = false;
+ value = Variant();
+ class_name = String();
- bool use_next_class=false;
+ bool use_next_class = false;
Token tk = get_token();
- Map<int,String> namespace_stack;
- int curly_stack=0;
+ Map<int, String> namespace_stack;
+ int curly_stack = 0;
+ while (!error || tk != TK_EOF) {
- while(!error || tk!=TK_EOF) {
-
- if (tk==TK_BRACKET_OPEN) {
+ if (tk == TK_BRACKET_OPEN) {
tk = get_token();
- if (tk==TK_IDENTIFIER && String(value)=="ScriptClass") {
- if (get_token()==TK_BRACKET_CLOSE) {
- use_next_class=true;
+ if (tk == TK_IDENTIFIER && String(value) == "ScriptClass") {
+ if (get_token() == TK_BRACKET_CLOSE) {
+ use_next_class = true;
}
}
- } else if (tk==TK_IDENTIFIER && String(value)=="class") {
+ } else if (tk == TK_IDENTIFIER && String(value) == "class") {
tk = get_token();
- if (tk==TK_IDENTIFIER) {
+ if (tk == TK_IDENTIFIER) {
String name = value;
- if (use_next_class || p_known_class_name==name) {
- for (Map<int,String>::Element *E=namespace_stack.front();E;E=E->next()) {
- class_name+=E->get()+".";
+ if (use_next_class || p_known_class_name == name) {
+ for (Map<int, String>::Element *E = namespace_stack.front(); E; E = E->next()) {
+ class_name += E->get() + ".";
}
- class_name+=String(value);
+ class_name += String(value);
break;
}
}
- } else if (tk==TK_IDENTIFIER && String(value)=="namespace") {
+ } else if (tk == TK_IDENTIFIER && String(value) == "namespace") {
String name;
int at_level = curly_stack;
- while(true) {
+ while (true) {
tk = get_token();
- if (tk==TK_IDENTIFIER) {
- name+=String(value);
+ if (tk == TK_IDENTIFIER) {
+ name += String(value);
}
tk = get_token();
- if (tk==TK_PERIOD) {
- name+=".";
- } else if (tk==TK_CURLY_BRACKET_OPEN) {
+ if (tk == TK_PERIOD) {
+ name += ".";
+ } else if (tk == TK_CURLY_BRACKET_OPEN) {
curly_stack++;
break;
} else {
break; //whathever else
}
-
}
- if (name!=String()) {
- namespace_stack[at_level]=name;
+ if (name != String()) {
+ namespace_stack[at_level] = name;
}
- } else if (tk==TK_CURLY_BRACKET_OPEN) {
+ } else if (tk == TK_CURLY_BRACKET_OPEN) {
curly_stack++;
- } else if (tk==TK_CURLY_BRACKET_CLOSE) {
+ } else if (tk == TK_CURLY_BRACKET_CLOSE) {
curly_stack--;
if (namespace_stack.has(curly_stack)) {
namespace_stack.erase(curly_stack);
@@ -394,10 +391,7 @@ public:
if (error)
return ERR_PARSE_ERROR;
-
-
return OK;
-
}
String get_error() {
@@ -407,23 +401,19 @@ public:
String get_class() {
return class_name;
}
-
};
-
void test_vec(Plane p_vec) {
-
CameraMatrix cm;
- cm.set_perspective(45,1,0,100);
- Plane v0=cm.xform4(p_vec);
-
- print_line("out: "+v0);
- v0.normal.z = (v0.d/100.0 *2.0-1.0) * v0.d;
- print_line("out_F: "+v0);
+ cm.set_perspective(45, 1, 0, 100);
+ Plane v0 = cm.xform4(p_vec);
+ print_line("out: " + v0);
+ v0.normal.z = (v0.d / 100.0 * 2.0 - 1.0) * v0.d;
+ print_line("out_F: " + v0);
-/*v0: 0, 0, -0.1, 0.1
+ /*v0: 0, 0, -0.1, 0.1
v1: 0, 0, 0, 0.1
fix: 0, 0, 0, 0.1
v0: 0, 0, 1.302803, 1.5
@@ -439,49 +429,41 @@ v0: 0, 0, 100, 100
v1: 0, 0, 100, 100
fix: 0, 0, 100, 100
*/
-
-
}
-uint32_t ihash( uint32_t a)
-{
- a = (a+0x7ed55d16) + (a<<12);
- a = (a^0xc761c23c) ^ (a>>19);
- a = (a+0x165667b1) + (a<<5);
- a = (a+0xd3a2646c) ^ (a<<9);
- a = (a+0xfd7046c5) + (a<<3);
- a = (a^0xb55a4f09) ^ (a>>16);
- return a;
+uint32_t ihash(uint32_t a) {
+ a = (a + 0x7ed55d16) + (a << 12);
+ a = (a ^ 0xc761c23c) ^ (a >> 19);
+ a = (a + 0x165667b1) + (a << 5);
+ a = (a + 0xd3a2646c) ^ (a << 9);
+ a = (a + 0xfd7046c5) + (a << 3);
+ a = (a ^ 0xb55a4f09) ^ (a >> 16);
+ return a;
}
-uint32_t ihash2( uint32_t a) {
- a = (a ^ 61) ^ (a >> 16);
- a = a + (a << 3);
- a = a ^ (a >> 4);
- a = a * 0x27d4eb2d;
- a = a ^ (a >> 15);
- return a;
+uint32_t ihash2(uint32_t a) {
+ a = (a ^ 61) ^ (a >> 16);
+ a = a + (a << 3);
+ a = a ^ (a >> 4);
+ a = a * 0x27d4eb2d;
+ a = a ^ (a >> 15);
+ return a;
}
-uint32_t ihash3( uint32_t a)
-{
- a = (a+0x479ab41d) + (a<<8);
- a = (a^0xe4aa10ce) ^ (a>>5);
- a = (a+0x9942f0a6) - (a<<14);
- a = (a^0x5aedd67d) ^ (a>>3);
- a = (a+0x17bea992) + (a<<7);
- return a;
+uint32_t ihash3(uint32_t a) {
+ a = (a + 0x479ab41d) + (a << 8);
+ a = (a ^ 0xe4aa10ce) ^ (a >> 5);
+ a = (a + 0x9942f0a6) - (a << 14);
+ a = (a ^ 0x5aedd67d) ^ (a >> 3);
+ a = (a + 0x17bea992) + (a << 7);
+ return a;
}
+MainLoop *test() {
-
-
-MainLoop* test() {
-
-
- print_line("Dvectors: "+itos(MemoryPool::allocs_used));
- print_line("Mem used: "+itos(MemoryPool::total_memory));
- print_line("MAx mem used: "+itos(MemoryPool::max_memory));
+ print_line("Dvectors: " + itos(MemoryPool::allocs_used));
+ print_line("Mem used: " + itos(MemoryPool::total_memory));
+ print_line("MAx mem used: " + itos(MemoryPool::max_memory));
PoolVector<int> ints;
ints.resize(20);
@@ -489,8 +471,8 @@ MainLoop* test() {
{
PoolVector<int>::Write w;
w = ints.write();
- for(int i=0;i<ints.size();i++) {
- w[i]=i;
+ for (int i = 0; i < ints.size(); i++) {
+ w[i] = i;
}
}
@@ -498,15 +480,14 @@ MainLoop* test() {
{
PoolVector<int>::Read r = posho.read();
- for(int i=0;i<posho.size();i++) {
- print_line(itos(i)+" : " +itos(r[i]));
+ for (int i = 0; i < posho.size(); i++) {
+ print_line(itos(i) + " : " + itos(r[i]));
}
}
- print_line("later Dvectors: "+itos(MemoryPool::allocs_used));
- print_line("later Mem used: "+itos(MemoryPool::total_memory));
- print_line("Mlater Ax mem used: "+itos(MemoryPool::max_memory));
-
+ print_line("later Dvectors: " + itos(MemoryPool::allocs_used));
+ print_line("later Mem used: " + itos(MemoryPool::total_memory));
+ print_line("Mlater Ax mem used: " + itos(MemoryPool::max_memory));
return NULL;
@@ -519,29 +500,27 @@ MainLoop* test() {
String test = cmdlargs.back()->get();
- FileAccess *fa = FileAccess::open(test,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(test, FileAccess::READ);
if (!fa) {
- ERR_EXPLAIN("Could not open file: "+test);
+ ERR_EXPLAIN("Could not open file: " + test);
ERR_FAIL_V(NULL);
}
-
Vector<uint8_t> buf;
int flen = fa->get_len();
- buf.resize(fa->get_len()+1);
- fa->get_buffer(&buf[0],flen);
- buf[flen]=0;
-
+ buf.resize(fa->get_len() + 1);
+ fa->get_buffer(&buf[0], flen);
+ buf[flen] = 0;
String code;
- code.parse_utf8((const char*)&buf[0]);
+ code.parse_utf8((const char *)&buf[0]);
GetClassAndNamespace getclass;
if (getclass.parse(code)) {
- print_line("Parse error: "+getclass.get_error());
+ print_line("Parse error: " + getclass.get_error());
} else {
- print_line("Found class: "+getclass.get_class());
+ print_line("Found class: " + getclass.get_class());
}
return NULL;
@@ -552,35 +531,33 @@ MainLoop* test() {
List<StringName> tl;
ClassDB::get_class_list(&tl);
-
- for (List<StringName>::Element *E=tl.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = tl.front(); E; E = E->next()) {
Vector<uint8_t> m5b = E->get().operator String().md5_buffer();
hashes.push_back(hashes.size());
-
}
//hashes.resize(50);
- for(int i=nearest_shift(hashes.size());i<20;i++) {
+ for (int i = nearest_shift(hashes.size()); i < 20; i++) {
- bool success=true;
- for(int s=0;s<10000;s++) {
+ bool success = true;
+ for (int s = 0; s < 10000; s++) {
Set<uint32_t> existing;
- success=true;
+ success = true;
- for(int j=0;j<hashes.size();j++) {
+ for (int j = 0; j < hashes.size(); j++) {
- uint32_t eh = ihash2(ihash3(hashes[j]+ihash(s)+s))&((1<<i)-1);
+ uint32_t eh = ihash2(ihash3(hashes[j] + ihash(s) + s)) & ((1 << i) - 1);
if (existing.has(eh)) {
- success=false;
+ success = false;
break;
}
existing.insert(eh);
}
if (success) {
- print_line("success at "+itos(i)+"/"+itos(nearest_shift(hashes.size()))+" shift "+itos(s));
+ print_line("success at " + itos(i) + "/" + itos(nearest_shift(hashes.size())) + " shift " + itos(s));
break;
}
}
@@ -590,47 +567,42 @@ MainLoop* test() {
print_line("DONE");
-
-
return NULL;
}
{
-
//print_line("NUM: "+itos(237641278346127));
- print_line("NUM: "+itos(-128));
+ print_line("NUM: " + itos(-128));
return NULL;
-
}
-
{
- Vector3 v(1,2,3);
+ Vector3 v(1, 2, 3);
v.normalize();
- float a=0.3;
+ float a = 0.3;
//Quat q(v,a);
- Basis m(v,a);
+ Basis m(v, a);
- Vector3 v2(7,3,1);
+ Vector3 v2(7, 3, 1);
v2.normalize();
- float a2=0.8;
+ float a2 = 0.8;
//Quat q(v,a);
- Basis m2(v2,a2);
+ Basis m2(v2, a2);
- Quat q=m;
- Quat q2=m2;
+ Quat q = m;
+ Quat q2 = m2;
Basis m3 = m.inverse() * m2;
- Quat q3 = (q.inverse() * q2);//.normalized();
+ Quat q3 = (q.inverse() * q2); //.normalized();
print_line(Quat(m3));
print_line(q3);
- print_line("before v: "+v+" a: "+rtos(a));
- q.get_axis_and_angle(v,a);
- print_line("after v: "+v+" a: "+rtos(a));
+ print_line("before v: " + v + " a: " + rtos(a));
+ q.get_axis_and_angle(v, a);
+ print_line("after v: " + v + " a: " + rtos(a));
}
return NULL;
@@ -638,98 +610,91 @@ MainLoop* test() {
List<String> args;
args.push_back("-l");
- Error err = OS::get_singleton()->execute("/bin/ls",args,true,NULL,&ret);
- print_line("error: "+itos(err));
+ Error err = OS::get_singleton()->execute("/bin/ls", args, true, NULL, &ret);
+ print_line("error: " + itos(err));
print_line(ret);
return NULL;
Basis m3;
- m3.rotate(Vector3(1,0,0),0.2);
- m3.rotate(Vector3(0,1,0),1.77);
- m3.rotate(Vector3(0,0,1),212);
+ m3.rotate(Vector3(1, 0, 0), 0.2);
+ m3.rotate(Vector3(0, 1, 0), 1.77);
+ m3.rotate(Vector3(0, 0, 1), 212);
Basis m32;
m32.set_euler(m3.get_euler());
- print_line("ELEULEEEEEEEEEEEEEEEEEER: "+m3.get_euler()+" vs "+m32.get_euler());
-
+ print_line("ELEULEEEEEEEEEEEEEEEEEER: " + m3.get_euler() + " vs " + m32.get_euler());
return NULL;
{
Dictionary d;
- d["momo"]=1;
- Dictionary b=d;
- b["44"]=4;
+ d["momo"] = 1;
+ Dictionary b = d;
+ b["44"] = 4;
}
-
-
return NULL;
- print_line("inters: "+rtos(Geometry::segment_intersects_circle(Vector2(-5,0),Vector2(-2,0),Vector2(),1.0)));
-
-
-
- print_line("cross: "+Vector3(1,2,3).cross(Vector3(4,5,7)));
- print_line("dot: "+rtos(Vector3(1,2,3).dot(Vector3(4,5,7))));
- print_line("abs: "+Vector3(-1,2,-3).abs());
- print_line("distance_to: "+rtos(Vector3(1,2,3).distance_to(Vector3(4,5,7))));
- print_line("distance_squared_to: "+rtos(Vector3(1,2,3).distance_squared_to(Vector3(4,5,7))));
- print_line("plus: "+(Vector3(1,2,3)+Vector3(Vector3(4,5,7))));
- print_line("minus: "+(Vector3(1,2,3)-Vector3(Vector3(4,5,7))));
- print_line("mul: "+(Vector3(1,2,3)*Vector3(Vector3(4,5,7))));
- print_line("div: "+(Vector3(1,2,3)/Vector3(Vector3(4,5,7))));
- print_line("mul scalar: "+(Vector3(1,2,3)*2));
- print_line("premul scalar: "+(2*Vector3(1,2,3)));
- print_line("div scalar: "+(Vector3(1,2,3)/3.0));
- print_line("length: "+rtos(Vector3(1,2,3).length()));
- print_line("length squared: "+rtos(Vector3(1,2,3).length_squared()));
- print_line("normalized: "+Vector3(1,2,3).normalized());
- print_line("inverse: "+Vector3(1,2,3).inverse());
+ print_line("inters: " + rtos(Geometry::segment_intersects_circle(Vector2(-5, 0), Vector2(-2, 0), Vector2(), 1.0)));
+
+ print_line("cross: " + Vector3(1, 2, 3).cross(Vector3(4, 5, 7)));
+ print_line("dot: " + rtos(Vector3(1, 2, 3).dot(Vector3(4, 5, 7))));
+ print_line("abs: " + Vector3(-1, 2, -3).abs());
+ print_line("distance_to: " + rtos(Vector3(1, 2, 3).distance_to(Vector3(4, 5, 7))));
+ print_line("distance_squared_to: " + rtos(Vector3(1, 2, 3).distance_squared_to(Vector3(4, 5, 7))));
+ print_line("plus: " + (Vector3(1, 2, 3) + Vector3(Vector3(4, 5, 7))));
+ print_line("minus: " + (Vector3(1, 2, 3) - Vector3(Vector3(4, 5, 7))));
+ print_line("mul: " + (Vector3(1, 2, 3) * Vector3(Vector3(4, 5, 7))));
+ print_line("div: " + (Vector3(1, 2, 3) / Vector3(Vector3(4, 5, 7))));
+ print_line("mul scalar: " + (Vector3(1, 2, 3) * 2));
+ print_line("premul scalar: " + (2 * Vector3(1, 2, 3)));
+ print_line("div scalar: " + (Vector3(1, 2, 3) / 3.0));
+ print_line("length: " + rtos(Vector3(1, 2, 3).length()));
+ print_line("length squared: " + rtos(Vector3(1, 2, 3).length_squared()));
+ print_line("normalized: " + Vector3(1, 2, 3).normalized());
+ print_line("inverse: " + Vector3(1, 2, 3).inverse());
{
- Vector3 v(4,5,7);
+ Vector3 v(4, 5, 7);
v.normalize();
- print_line("normalize: "+v);
+ print_line("normalize: " + v);
}
{
- Vector3 v(4,5,7);
- v+=Vector3(1,2,3);
- print_line("+=: "+v);
+ Vector3 v(4, 5, 7);
+ v += Vector3(1, 2, 3);
+ print_line("+=: " + v);
}
{
- Vector3 v(4,5,7);
- v-=Vector3(1,2,3);
- print_line("-=: "+v);
+ Vector3 v(4, 5, 7);
+ v -= Vector3(1, 2, 3);
+ print_line("-=: " + v);
}
{
- Vector3 v(4,5,7);
- v*=Vector3(1,2,3);
- print_line("*=: "+v);
+ Vector3 v(4, 5, 7);
+ v *= Vector3(1, 2, 3);
+ print_line("*=: " + v);
}
{
- Vector3 v(4,5,7);
- v/=Vector3(1,2,3);
- print_line("/=: "+v);
+ Vector3 v(4, 5, 7);
+ v /= Vector3(1, 2, 3);
+ print_line("/=: " + v);
}
{
- Vector3 v(4,5,7);
- v*=2.0;
- print_line("scalar *=: "+v);
+ Vector3 v(4, 5, 7);
+ v *= 2.0;
+ print_line("scalar *=: " + v);
}
{
- Vector3 v(4,5,7);
- v/=2.0;
- print_line("scalar /=: "+v);
+ Vector3 v(4, 5, 7);
+ v /= 2.0;
+ print_line("scalar /=: " + v);
}
-
-
#if 0
print_line(String("C:\\momo\\.\\popo\\..\\gongo").simplify_path());
print_line(String("res://../popo/..//gongo").simplify_path());
@@ -811,7 +776,5 @@ MainLoop* test() {
#endif
return NULL;
-
}
-
}
diff --git a/main/tests/test_math.h b/main/tests/test_math.h
index 1ca8a8c12a..239f16f6b0 100644
--- a/main/tests/test_math.h
+++ b/main/tests/test_math.h
@@ -33,8 +33,7 @@
namespace TestMath {
-MainLoop* test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_physics.cpp b/main/tests/test_physics.cpp
index fe0fad9bc8..6637139c86 100644
--- a/main/tests/test_physics.cpp
+++ b/main/tests/test_physics.cpp
@@ -28,19 +28,18 @@
/*************************************************************************/
#include "test_physics.h"
-
-#include "servers/visual_server.h"
-#include "servers/physics_server.h"
-#include "os/main_loop.h"
-#include "math_funcs.h"
-#include "print_string.h"
#include "map.h"
+#include "math_funcs.h"
+#include "os/main_loop.h"
#include "os/os.h"
+#include "print_string.h"
#include "quick_hull.h"
+#include "servers/physics_server.h"
+#include "servers/visual_server.h"
class TestPhysicsMainLoop : public MainLoop {
- GDCLASS( TestPhysicsMainLoop, MainLoop );
+ GDCLASS(TestPhysicsMainLoop, MainLoop);
enum {
LINK_COUNT = 20,
@@ -58,150 +57,145 @@ class TestPhysicsMainLoop : public MainLoop {
RID character;
- float ofs_x,ofs_y;
+ float ofs_x, ofs_y;
Point2 joy_direction;
List<RID> bodies;
- Map<PhysicsServer::ShapeType,RID> type_shape_map;
- Map<PhysicsServer::ShapeType,RID> type_mesh_map;
+ Map<PhysicsServer::ShapeType, RID> type_shape_map;
+ Map<PhysicsServer::ShapeType, RID> type_mesh_map;
void body_changed_transform(Object *p_state, RID p_visual_instance) {
- PhysicsDirectBodyState *state = (PhysicsDirectBodyState*)p_state;
- VisualServer *vs=VisualServer::get_singleton();
- Transform t=state->get_transform();
+ PhysicsDirectBodyState *state = (PhysicsDirectBodyState *)p_state;
+ VisualServer *vs = VisualServer::get_singleton();
+ Transform t = state->get_transform();
//t.basis.scale( Vector3(1.0,0.5,0.2) );
- vs->instance_set_transform(p_visual_instance,t);
+ vs->instance_set_transform(p_visual_instance, t);
}
bool quit;
protected:
-
static void _bind_methods() {
- ClassDB::bind_method("body_changed_transform",&TestPhysicsMainLoop::body_changed_transform);
+ ClassDB::bind_method("body_changed_transform", &TestPhysicsMainLoop::body_changed_transform);
}
- RID create_body(PhysicsServer::ShapeType p_shape, PhysicsServer::BodyMode p_body,const Transform p_location,bool p_active_default=true,const Transform&p_shape_xform=Transform()) {
+ RID create_body(PhysicsServer::ShapeType p_shape, PhysicsServer::BodyMode p_body, const Transform p_location, bool p_active_default = true, const Transform &p_shape_xform = Transform()) {
- VisualServer *vs=VisualServer::get_singleton();
- PhysicsServer * ps = PhysicsServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
+ PhysicsServer *ps = PhysicsServer::get_singleton();
- RID mesh_instance = vs->instance_create2(type_mesh_map[p_shape],scenario);
- RID body = ps->body_create(p_body,!p_active_default);
- ps->body_set_space(body,space);
- ps->body_set_param(body,PhysicsServer::BODY_PARAM_BOUNCE,0.0);
+ RID mesh_instance = vs->instance_create2(type_mesh_map[p_shape], scenario);
+ RID body = ps->body_create(p_body, !p_active_default);
+ ps->body_set_space(body, space);
+ ps->body_set_param(body, PhysicsServer::BODY_PARAM_BOUNCE, 0.0);
//todo set space
- ps->body_add_shape(body,type_shape_map[p_shape]);
- ps->body_set_force_integration_callback(body,this,"body_changed_transform",mesh_instance);
+ ps->body_add_shape(body, type_shape_map[p_shape]);
+ ps->body_set_force_integration_callback(body, this, "body_changed_transform", mesh_instance);
- ps->body_set_state( body, PhysicsServer::BODY_STATE_TRANSFORM,p_location);
+ ps->body_set_state(body, PhysicsServer::BODY_STATE_TRANSFORM, p_location);
bodies.push_back(body);
- if (p_body==PhysicsServer::BODY_MODE_STATIC) {
+ if (p_body == PhysicsServer::BODY_MODE_STATIC) {
- vs->instance_set_transform(mesh_instance,p_location);
+ vs->instance_set_transform(mesh_instance, p_location);
}
return body;
}
- RID create_static_plane(const Plane& p_plane) {
+ RID create_static_plane(const Plane &p_plane) {
- PhysicsServer * ps = PhysicsServer::get_singleton();
+ PhysicsServer *ps = PhysicsServer::get_singleton();
RID plane_shape = ps->shape_create(PhysicsServer::SHAPE_PLANE);
- ps->shape_set_data( plane_shape, p_plane );
+ ps->shape_set_data(plane_shape, p_plane);
- RID b = ps->body_create( PhysicsServer::BODY_MODE_STATIC );
- ps->body_set_space(b,space);
+ RID b = ps->body_create(PhysicsServer::BODY_MODE_STATIC);
+ ps->body_set_space(b, space);
//todo set space
ps->body_add_shape(b, plane_shape);
return b;
-
}
- void configure_body(RID p_body,float p_mass, float p_friction, float p_bounce) {
-
- PhysicsServer * ps = PhysicsServer::get_singleton();
- ps->body_set_param( p_body, PhysicsServer::BODY_PARAM_MASS, p_mass );
- ps->body_set_param( p_body, PhysicsServer::BODY_PARAM_FRICTION, p_friction );
- ps->body_set_param( p_body, PhysicsServer::BODY_PARAM_BOUNCE, p_bounce );
+ void configure_body(RID p_body, float p_mass, float p_friction, float p_bounce) {
+ PhysicsServer *ps = PhysicsServer::get_singleton();
+ ps->body_set_param(p_body, PhysicsServer::BODY_PARAM_MASS, p_mass);
+ ps->body_set_param(p_body, PhysicsServer::BODY_PARAM_FRICTION, p_friction);
+ ps->body_set_param(p_body, PhysicsServer::BODY_PARAM_BOUNCE, p_bounce);
}
void init_shapes() {
- VisualServer *vs=VisualServer::get_singleton();
- PhysicsServer * ps = PhysicsServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
+ PhysicsServer *ps = PhysicsServer::get_singleton();
/* SPHERE SHAPE */
- RID sphere_mesh = vs->make_sphere_mesh(10,20,0.5);
- type_mesh_map[PhysicsServer::SHAPE_SPHERE]=sphere_mesh;
+ RID sphere_mesh = vs->make_sphere_mesh(10, 20, 0.5);
+ type_mesh_map[PhysicsServer::SHAPE_SPHERE] = sphere_mesh;
- RID sphere_shape=ps->shape_create(PhysicsServer::SHAPE_SPHERE);
- ps->shape_set_data( sphere_shape, 0.5 );
- type_shape_map[PhysicsServer::SHAPE_SPHERE]=sphere_shape;
+ RID sphere_shape = ps->shape_create(PhysicsServer::SHAPE_SPHERE);
+ ps->shape_set_data(sphere_shape, 0.5);
+ type_shape_map[PhysicsServer::SHAPE_SPHERE] = sphere_shape;
/* BOX SHAPE */
- PoolVector<Plane> box_planes = Geometry::build_box_planes(Vector3(0.5,0.5,0.5));
+ PoolVector<Plane> box_planes = Geometry::build_box_planes(Vector3(0.5, 0.5, 0.5));
RID box_mesh = vs->mesh_create();
Geometry::MeshData box_data = Geometry::build_convex_mesh(box_planes);
- vs->mesh_add_surface_from_mesh_data(box_mesh,box_data);
- type_mesh_map[PhysicsServer::SHAPE_BOX]=box_mesh;
-
- RID box_shape=ps->shape_create(PhysicsServer::SHAPE_BOX);
- ps->shape_set_data( box_shape, Vector3(0.5,0.5,0.5) );
- type_shape_map[PhysicsServer::SHAPE_BOX]=box_shape;
+ vs->mesh_add_surface_from_mesh_data(box_mesh, box_data);
+ type_mesh_map[PhysicsServer::SHAPE_BOX] = box_mesh;
+ RID box_shape = ps->shape_create(PhysicsServer::SHAPE_BOX);
+ ps->shape_set_data(box_shape, Vector3(0.5, 0.5, 0.5));
+ type_shape_map[PhysicsServer::SHAPE_BOX] = box_shape;
/* CAPSULE SHAPE */
- PoolVector<Plane> capsule_planes = Geometry::build_capsule_planes(0.5,0.7,12,Vector3::AXIS_Z);
+ PoolVector<Plane> capsule_planes = Geometry::build_capsule_planes(0.5, 0.7, 12, Vector3::AXIS_Z);
RID capsule_mesh = vs->mesh_create();
Geometry::MeshData capsule_data = Geometry::build_convex_mesh(capsule_planes);
- vs->mesh_add_surface_from_mesh_data(capsule_mesh,capsule_data);
+ vs->mesh_add_surface_from_mesh_data(capsule_mesh, capsule_data);
- type_mesh_map[PhysicsServer::SHAPE_CAPSULE]=capsule_mesh;
+ type_mesh_map[PhysicsServer::SHAPE_CAPSULE] = capsule_mesh;
- RID capsule_shape=ps->shape_create(PhysicsServer::SHAPE_CAPSULE);
+ RID capsule_shape = ps->shape_create(PhysicsServer::SHAPE_CAPSULE);
Dictionary capsule_params;
- capsule_params["radius"]=0.5;
- capsule_params["height"]=1.4;
- ps->shape_set_data( capsule_shape, capsule_params );
- type_shape_map[PhysicsServer::SHAPE_CAPSULE]=capsule_shape;
+ capsule_params["radius"] = 0.5;
+ capsule_params["height"] = 1.4;
+ ps->shape_set_data(capsule_shape, capsule_params);
+ type_shape_map[PhysicsServer::SHAPE_CAPSULE] = capsule_shape;
/* CONVEX SHAPE */
- PoolVector<Plane> convex_planes = Geometry::build_cylinder_planes(0.5,0.7,5,Vector3::AXIS_Z);
+ PoolVector<Plane> convex_planes = Geometry::build_cylinder_planes(0.5, 0.7, 5, Vector3::AXIS_Z);
RID convex_mesh = vs->mesh_create();
Geometry::MeshData convex_data = Geometry::build_convex_mesh(convex_planes);
- QuickHull::build(convex_data.vertices,convex_data);
- vs->mesh_add_surface_from_mesh_data(convex_mesh,convex_data);
+ QuickHull::build(convex_data.vertices, convex_data);
+ vs->mesh_add_surface_from_mesh_data(convex_mesh, convex_data);
- type_mesh_map[PhysicsServer::SHAPE_CONVEX_POLYGON]=convex_mesh;
-
- RID convex_shape=ps->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON);
- ps->shape_set_data( convex_shape, convex_data.vertices );
- type_shape_map[PhysicsServer::SHAPE_CONVEX_POLYGON]=convex_shape;
+ type_mesh_map[PhysicsServer::SHAPE_CONVEX_POLYGON] = convex_mesh;
+ RID convex_shape = ps->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON);
+ ps->shape_set_data(convex_shape, convex_data.vertices);
+ type_shape_map[PhysicsServer::SHAPE_CONVEX_POLYGON] = convex_shape;
}
- void make_trimesh(Vector<Vector3> p_faces,const Transform& p_xform=Transform()) {
+ void make_trimesh(Vector<Vector3> p_faces, const Transform &p_xform = Transform()) {
- VisualServer *vs=VisualServer::get_singleton();
- PhysicsServer * ps = PhysicsServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
+ PhysicsServer *ps = PhysicsServer::get_singleton();
RID trimesh_shape = ps->shape_create(PhysicsServer::SHAPE_CONCAVE_POLYGON);
ps->shape_set_data(trimesh_shape, p_faces);
- p_faces=ps->shape_get_data(trimesh_shape); // optimized one
+ p_faces = ps->shape_get_data(trimesh_shape); // optimized one
Vector<Vector3> normals; // for drawing
- for (int i=0;i<p_faces.size()/3;i++) {
+ for (int i = 0; i < p_faces.size() / 3; i++) {
- Plane p( p_faces[i*3+0],p_faces[i*3+1], p_faces[i*3+2] );
+ Plane p(p_faces[i * 3 + 0], p_faces[i * 3 + 1], p_faces[i * 3 + 2]);
normals.push_back(p.normal);
normals.push_back(p.normal);
normals.push_back(p.normal);
@@ -210,95 +204,85 @@ protected:
RID trimesh_mesh = vs->mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
- d[VS::ARRAY_VERTEX]=p_faces;
- d[VS::ARRAY_NORMAL]=normals;
- vs->mesh_add_surface_from_arrays(trimesh_mesh, VS::PRIMITIVE_TRIANGLES, d );
+ d[VS::ARRAY_VERTEX] = p_faces;
+ d[VS::ARRAY_NORMAL] = normals;
+ vs->mesh_add_surface_from_arrays(trimesh_mesh, VS::PRIMITIVE_TRIANGLES, d);
//vs->material_set_flag( trimesh_mat, VisualServer::MATERIAL_FLAG_UNSHADED,true);
+ RID triins = vs->instance_create2(trimesh_mesh, scenario);
- RID triins = vs->instance_create2(trimesh_mesh,scenario);
-
-
- RID tribody = ps->body_create( PhysicsServer::BODY_MODE_STATIC);
- ps->body_set_space(tribody,space);
+ RID tribody = ps->body_create(PhysicsServer::BODY_MODE_STATIC);
+ ps->body_set_space(tribody, space);
//todo set space
ps->body_add_shape(tribody, trimesh_shape);
Transform tritrans = p_xform;
- ps->body_set_state( tribody, PhysicsServer::BODY_STATE_TRANSFORM, tritrans );
- vs->instance_set_transform( triins, tritrans );
+ ps->body_set_state(tribody, PhysicsServer::BODY_STATE_TRANSFORM, tritrans);
+ vs->instance_set_transform(triins, tritrans);
//RID trimesh_material = vs->fixed_material_create();
//vs->material_generate( trimesh_material, Color(0.2,0.4,0.6) );
//vs->mesh_surface_set_material( trimesh_mesh, 0, trimesh_material );
-
}
- void make_grid(int p_width,int p_height,float p_cellsize,float p_cellheight,const Transform& p_xform=Transform()) {
+ void make_grid(int p_width, int p_height, float p_cellsize, float p_cellheight, const Transform &p_xform = Transform()) {
- Vector< Vector< float > > grid;
+ Vector<Vector<float> > grid;
grid.resize(p_width);
- for (int i=0;i<p_width;i++) {
+ for (int i = 0; i < p_width; i++) {
grid[i].resize(p_height);
- for (int j=0;j<p_height;j++) {
+ for (int j = 0; j < p_height; j++) {
- grid[i][j]=1.0+Math::random(-p_cellheight, p_cellheight );
+ grid[i][j] = 1.0 + Math::random(-p_cellheight, p_cellheight);
}
}
Vector<Vector3> faces;
- for (int i=1;i<p_width;i++) {
-
- for (int j=1;j<p_height;j++) {
-
+ for (int i = 1; i < p_width; i++) {
-#define MAKE_VERTEX(m_x,m_z)\
- faces.push_back( Vector3( (m_x-p_width/2)*p_cellsize, grid[m_x][m_z], (m_z-p_height/2)*p_cellsize ) )
+ for (int j = 1; j < p_height; j++) {
- MAKE_VERTEX(i,j-1);
- MAKE_VERTEX(i,j);
- MAKE_VERTEX(i-1,j);
+#define MAKE_VERTEX(m_x, m_z) \
+ faces.push_back(Vector3((m_x - p_width / 2) * p_cellsize, grid[m_x][m_z], (m_z - p_height / 2) * p_cellsize))
- MAKE_VERTEX(i-1,j-1);
- MAKE_VERTEX(i,j-1);
- MAKE_VERTEX(i-1,j);
+ MAKE_VERTEX(i, j - 1);
+ MAKE_VERTEX(i, j);
+ MAKE_VERTEX(i - 1, j);
+ MAKE_VERTEX(i - 1, j - 1);
+ MAKE_VERTEX(i, j - 1);
+ MAKE_VERTEX(i - 1, j);
}
}
- make_trimesh(faces,p_xform);
-
+ make_trimesh(faces, p_xform);
}
-
public:
- virtual void input_event(const InputEvent& p_event) {
-
- if (p_event.type==InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask&4) {
+ virtual void input_event(const InputEvent &p_event) {
- ofs_y-=p_event.mouse_motion.relative_y/200.0;
- ofs_x+=p_event.mouse_motion.relative_x/200.0;
+ if (p_event.type == InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask & 4) {
+ ofs_y -= p_event.mouse_motion.relative_y / 200.0;
+ ofs_x += p_event.mouse_motion.relative_x / 200.0;
}
- if (p_event.type==InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask&1) {
+ if (p_event.type == InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask & 1) {
- float y=-p_event.mouse_motion.relative_y/20.0;
- float x=p_event.mouse_motion.relative_x/20.0;
+ float y = -p_event.mouse_motion.relative_y / 20.0;
+ float x = p_event.mouse_motion.relative_x / 20.0;
if (mover.is_valid()) {
+ PhysicsServer *ps = PhysicsServer::get_singleton();
+ Transform t = ps->body_get_state(mover, PhysicsServer::BODY_STATE_TRANSFORM);
+ t.origin += Vector3(x, y, 0);
- PhysicsServer * ps = PhysicsServer::get_singleton();
- Transform t = ps->body_get_state(mover,PhysicsServer::BODY_STATE_TRANSFORM);
- t.origin+=Vector3(x,y,0);
-
- ps->body_set_state(mover,PhysicsServer::BODY_STATE_TRANSFORM,t);
+ ps->body_set_state(mover, PhysicsServer::BODY_STATE_TRANSFORM, t);
}
-
}
if (p_event.type == InputEvent::JOYPAD_MOTION) {
@@ -317,30 +301,28 @@ public:
virtual void request_quit() {
- quit=true;
+ quit = true;
}
virtual void init() {
- ofs_x=ofs_y=0;
+ ofs_x = ofs_y = 0;
init_shapes();
PhysicsServer *ps = PhysicsServer::get_singleton();
- space=ps->space_create();
- ps->space_set_active(space,true);
+ space = ps->space_create();
+ ps->space_set_active(space, true);
- VisualServer *vs=VisualServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
/* LIGHT */
- RID lightaux = vs->light_create( VisualServer::LIGHT_DIRECTIONAL );
+ RID lightaux = vs->light_create(VisualServer::LIGHT_DIRECTIONAL);
//vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,0.0) );
scenario = vs->scenario_create();
- vs->light_set_shadow(lightaux,true);
- light = vs->instance_create2( lightaux,scenario );
+ vs->light_set_shadow(lightaux, true);
+ light = vs->instance_create2(lightaux, scenario);
Transform t;
- t.rotate(Vector3(1.0,0,0),0.6);
- vs->instance_set_transform(light,t);
-
-
+ t.rotate(Vector3(1.0, 0, 0), 0.6);
+ vs->instance_set_transform(light, t);
/* CAMERA */
@@ -348,29 +330,27 @@ public:
RID viewport = vs->viewport_create();
Size2i screen_size = OS::get_singleton()->get_window_size();
- vs->viewport_set_size(viewport,screen_size.x,screen_size.y);
- vs->viewport_attach_to_screen(viewport,Rect2(Vector2(),screen_size));
- vs->viewport_set_active(viewport,true);
- vs->viewport_attach_camera( viewport, camera );
- vs->viewport_set_scenario( viewport, scenario );
-
-
- vs->camera_set_perspective(camera,60,0.1,40.0);
- vs->camera_set_transform(camera,Transform( Basis(), Vector3(0,9,12)));
+ vs->viewport_set_size(viewport, screen_size.x, screen_size.y);
+ vs->viewport_attach_to_screen(viewport, Rect2(Vector2(), screen_size));
+ vs->viewport_set_active(viewport, true);
+ vs->viewport_attach_camera(viewport, camera);
+ vs->viewport_set_scenario(viewport, scenario);
+
+ vs->camera_set_perspective(camera, 60, 0.1, 40.0);
+ vs->camera_set_transform(camera, Transform(Basis(), Vector3(0, 9, 12)));
//vs->scenario_set_debug(scenario,VS::SCENARIO_DEBUG_WIREFRAME);
Transform gxf;
- gxf.basis.scale(Vector3(1.4,0.4,1.4));
- gxf.origin=Vector3(-2,1,-2);
- make_grid(5,5,2.5,1,gxf);
+ gxf.basis.scale(Vector3(1.4, 0.4, 1.4));
+ gxf.origin = Vector3(-2, 1, -2);
+ make_grid(5, 5, 2.5, 1, gxf);
//create_body(PhysicsServer::SHAPE_BOX,PhysicsServer::BODY_MODE_STATIC,gxf);
//create_static_plane( Plane( Vector3(0,1,0), -2) );
//test_joint();
test_fall();
//test_joint();
-
-/*
+ /*
Vector<Vector3> faces;
faces.push_back( Vector3(10,0,-5) );
faces.push_back( Vector3(0,0,10) );
@@ -378,7 +358,7 @@ public:
make_trimesh(faces);
*/
/* Make Trimesh */
- quit=false;
+ quit = false;
return;
#if 0
@@ -400,9 +380,8 @@ public:
for (int j=1;j<GRID_SIZE;j++) {
-
-#define MAKE_VERTEX(m_x,m_z)\
- faces.push_back( Vector3( m_x-GRID_SIZE/2.0, grid[m_x][m_z], m_z-GRID_SIZE/2.0 )*3.0 )
+#define MAKE_VERTEX(m_x, m_z) \
+ faces.push_back(Vector3(m_x - GRID_SIZE / 2.0, grid[m_x][m_z], m_z - GRID_SIZE / 2.0) * 3.0)
MAKE_VERTEX(i,j-1);
MAKE_VERTEX(i,j);
@@ -458,24 +437,22 @@ public:
if (mover.is_valid()) {
static float joy_speed = 10;
- PhysicsServer * ps = PhysicsServer::get_singleton();
- Transform t = ps->body_get_state(mover,PhysicsServer::BODY_STATE_TRANSFORM);
- t.origin+=Vector3(joy_speed * joy_direction.x * p_time, -joy_speed * joy_direction.y * p_time,0);
- ps->body_set_state(mover,PhysicsServer::BODY_STATE_TRANSFORM,t);
+ PhysicsServer *ps = PhysicsServer::get_singleton();
+ Transform t = ps->body_get_state(mover, PhysicsServer::BODY_STATE_TRANSFORM);
+ t.origin += Vector3(joy_speed * joy_direction.x * p_time, -joy_speed * joy_direction.y * p_time, 0);
+ ps->body_set_state(mover, PhysicsServer::BODY_STATE_TRANSFORM, t);
};
-
Transform cameratr;
- cameratr.rotate(Vector3(0,1,0),ofs_x);
- cameratr.rotate(Vector3(1,0,0),-ofs_y);
- cameratr.translate(Vector3(0,2,8));
- VisualServer *vs=VisualServer::get_singleton();
- vs->camera_set_transform(camera,cameratr);
+ cameratr.rotate(Vector3(0, 1, 0), ofs_x);
+ cameratr.rotate(Vector3(1, 0, 0), -ofs_y);
+ cameratr.translate(Vector3(0, 2, 8));
+ VisualServer *vs = VisualServer::get_singleton();
+ vs->camera_set_transform(camera, cameratr);
return quit;
}
virtual void finish() {
-
}
void test_joint() {
@@ -535,115 +512,93 @@ public:
void test_character() {
- VisualServer *vs=VisualServer::get_singleton();
- PhysicsServer * ps = PhysicsServer::get_singleton();
-
+ VisualServer *vs = VisualServer::get_singleton();
+ PhysicsServer *ps = PhysicsServer::get_singleton();
- PoolVector<Plane> capsule_planes = Geometry::build_capsule_planes(0.5,1,12,5,Vector3::AXIS_Y);
+ PoolVector<Plane> capsule_planes = Geometry::build_capsule_planes(0.5, 1, 12, 5, Vector3::AXIS_Y);
RID capsule_mesh = vs->mesh_create();
Geometry::MeshData capsule_data = Geometry::build_convex_mesh(capsule_planes);
- vs->mesh_add_surface_from_mesh_data(capsule_mesh,capsule_data);
- type_mesh_map[PhysicsServer::SHAPE_CAPSULE]=capsule_mesh;
+ vs->mesh_add_surface_from_mesh_data(capsule_mesh, capsule_data);
+ type_mesh_map[PhysicsServer::SHAPE_CAPSULE] = capsule_mesh;
- RID capsule_shape=ps->shape_create(PhysicsServer::SHAPE_CAPSULE);
+ RID capsule_shape = ps->shape_create(PhysicsServer::SHAPE_CAPSULE);
Dictionary capsule_params;
- capsule_params["radius"]=0.5;
- capsule_params["height"]=1;
+ capsule_params["radius"] = 0.5;
+ capsule_params["height"] = 1;
Transform shape_xform;
- shape_xform.rotate(Vector3(1,0,0),Math_PI/2.0);
+ shape_xform.rotate(Vector3(1, 0, 0), Math_PI / 2.0);
//shape_xform.origin=Vector3(1,1,1);
- ps->shape_set_data( capsule_shape, capsule_params);
-
+ ps->shape_set_data(capsule_shape, capsule_params);
- RID mesh_instance = vs->instance_create2(capsule_mesh,scenario);
+ RID mesh_instance = vs->instance_create2(capsule_mesh, scenario);
character = ps->body_create(PhysicsServer::BODY_MODE_CHARACTER);
- ps->body_set_space(character,space);
+ ps->body_set_space(character, space);
//todo add space
- ps->body_add_shape(character,capsule_shape);
+ ps->body_add_shape(character, capsule_shape);
- ps->body_set_force_integration_callback(character,this,"body_changed_transform",mesh_instance);
+ ps->body_set_force_integration_callback(character, this, "body_changed_transform", mesh_instance);
-
- ps->body_set_state( character, PhysicsServer::BODY_STATE_TRANSFORM,Transform(Basis(),Vector3(-2,5,-2)));
+ ps->body_set_state(character, PhysicsServer::BODY_STATE_TRANSFORM, Transform(Basis(), Vector3(-2, 5, -2)));
bodies.push_back(character);
-
-
}
void test_fall() {
+ for (int i = 0; i < 35; i++) {
- for (int i=0;i<35;i++) {
-
- static const PhysicsServer::ShapeType shape_idx[]={
+ static const PhysicsServer::ShapeType shape_idx[] = {
PhysicsServer::SHAPE_CAPSULE,
PhysicsServer::SHAPE_BOX,
PhysicsServer::SHAPE_SPHERE,
PhysicsServer::SHAPE_CONVEX_POLYGON
};
- PhysicsServer::ShapeType type=shape_idx[i%4];
+ PhysicsServer::ShapeType type = shape_idx[i % 4];
//type=PhysicsServer::SHAPE_CONVEX_POLYGON;
Transform t;
- t.origin=Vector3(0.0*i,3.5+1.1*i,0.7+0.0*i);
+ t.origin = Vector3(0.0 * i, 3.5 + 1.1 * i, 0.7 + 0.0 * i);
//t.origin=Vector3(-0.7+0.0*i,0.5+4.1*i,0);
- t.basis.rotate(Vector3(0.2,-1,0),Math_PI/2*0.6);
+ t.basis.rotate(Vector3(0.2, -1, 0), Math_PI / 2 * 0.6);
//t.basis.rotate(Vector3(0,-1,0),Math_PI/4*i);
//t.basis.rotate(Vector3(0,-1,0),Math_PI/4*i);
//t.basis.rotate(Vector3(-1,0,0),Math_PI/4*i);
-
- create_body(type,PhysicsServer::BODY_MODE_RIGID,t);
+ create_body(type, PhysicsServer::BODY_MODE_RIGID, t);
//RID b = create_body(type,i==0?PhysicsServer::BODY_MODE_STATIC:PhysicsServer::BODY_MODE_RIGID,t);
-
}
- create_static_plane( Plane( Vector3(0,1,0), -1) );
-
+ create_static_plane(Plane(Vector3(0, 1, 0), -1));
-/*
+ /*
create_static_plane( Plane( Vector3(1,0,0), -2) );
create_static_plane( Plane( Vector3(-1,0,0), -2) );
create_static_plane( Plane( Vector3(0,0,1), -2) );
create_static_plane( Plane( Vector3(0,0,-1), -2) );
*/
-
-
}
void test_activate() {
- create_body(PhysicsServer::SHAPE_BOX,PhysicsServer::BODY_MODE_RIGID,Transform(Basis(),Vector3(0,2,0)),true);
+ create_body(PhysicsServer::SHAPE_BOX, PhysicsServer::BODY_MODE_RIGID, Transform(Basis(), Vector3(0, 2, 0)), true);
//create_body(PhysicsServer::SHAPE_SPHERE,PhysicsServer::BODY_MODE_RIGID,Transform(Basis(),Vector3(0,6,0)),true);
- create_static_plane( Plane( Vector3(0,1,0), -1) );
-
+ create_static_plane(Plane(Vector3(0, 1, 0), -1));
}
-
virtual bool idle(float p_time) {
return false;
}
-
-
-
-
-
-
TestPhysicsMainLoop() {
-
}
};
namespace TestPhysics {
-MainLoop* test() {
-
- return memnew( TestPhysicsMainLoop );
+MainLoop *test() {
+ return memnew(TestPhysicsMainLoop);
}
-
}
diff --git a/main/tests/test_physics.h b/main/tests/test_physics.h
index 68693fd931..a0dc15e421 100644
--- a/main/tests/test_physics.h
+++ b/main/tests/test_physics.h
@@ -37,8 +37,7 @@
namespace TestPhysics {
-MainLoop* test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_physics_2d.cpp b/main/tests/test_physics_2d.cpp
index 4321a356f5..8818c4b595 100644
--- a/main/tests/test_physics_2d.cpp
+++ b/main/tests/test_physics_2d.cpp
@@ -28,23 +28,21 @@
/*************************************************************************/
#include "test_physics_2d.h"
-#include "servers/visual_server.h"
-#include "servers/physics_2d_server.h"
+#include "map.h"
#include "os/main_loop.h"
+#include "os/os.h"
#include "print_string.h"
-#include "map.h"
#include "scene/resources/texture.h"
-#include "os/os.h"
+#include "servers/physics_2d_server.h"
+#include "servers/visual_server.h"
-static const unsigned char convex_png[]={
-0x89,0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,0x0,0x0,0x40,0x0,0x0,0x0,0x40,0x8,0x6,0x0,0x0,0x0,0xaa,0x69,0x71,0xde,0x0,0x0,0x0,0x1,0x73,0x52,0x47,0x42,0x0,0xae,0xce,0x1c,0xe9,0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0x0,0x0,0x0,0x0,0x0,0xf9,0x43,0xbb,0x7f,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,0xdb,0x6,0xa,0x3,0x13,0x31,0x66,0xa7,0xac,0x79,0x0,0x0,0x4,0xef,0x49,0x44,0x41,0x54,0x78,0xda,0xed,0x9b,0xdd,0x4e,0x2a,0x57,0x14,0xc7,0xf7,0x1e,0xc0,0x19,0x38,0x32,0x80,0xa,0x6a,0xda,0x18,0xa3,0xc6,0x47,0x50,0x7b,0xa1,0xd9,0x36,0x27,0x7e,0x44,0xed,0x45,0x4d,0x93,0x3e,0x40,0x1f,0x64,0x90,0xf4,0x1,0xbc,0xf0,0xc2,0x9c,0x57,0x30,0x4d,0xbc,0xa8,0x6d,0xc,0x69,0x26,0xb5,0x68,0x8b,0x35,0x7e,0x20,0xb4,0xf5,0x14,0xbf,0x51,0x3c,0x52,0xe,0xc,0xe,0xc8,0xf0,0xb1,0x7a,0x51,0x3d,0xb1,0x9e,0x19,0x1c,0x54,0x70,0x1c,0xdc,0x9,0x17,0x64,0x8,0xc9,0xff,0xb7,0xd6,0x7f,0xcd,0x3f,0x2b,0xd9,0x8,0xbd,0x9c,0xda,0x3e,0xf8,0x31,0xff,0xc,0x0,0x8,0x42,0x88,0x9c,0x9f,0x9f,0xbf,0xa,0x87,0xc3,0xad,0x7d,0x7d,0x7d,0x7f,0x23,0x84,0x78,0x8c,0x31,0xaf,0x55,0x0,0xc6,0xc7,0x14,0x1e,0x8f,0xc7,0xbf,0x38,0x3c,0x3c,0x6c,0x9b,0x9f,0x9f,0x6f,0xb8,0x82,0x9b,0xee,0xe8,0xe8,0xf8,0x12,0x0,0xbe,0xd3,0x2a,0x8,0xfc,0x50,0xd1,0xf9,0x7c,0x9e,0x8a,0x46,0xa3,0x5f,0x9d,0x9e,0x9e,0x7e,0xb2,0xb0,0xb0,0x60,0xe5,0x79,0x1e,0xf1,0xfc,0x7f,0x3a,0x9,0x21,0x88,0x10,0x82,0x26,0x26,0x26,0xde,0x77,0x75,0x75,0x85,0x59,0x96,0xfd,0x5e,0x6b,0x20,0xf0,0x7d,0x85,0x4b,0x92,0xf4,0xfa,0xe0,0xe0,0xe0,0xd3,0xb9,0xb9,0xb9,0x46,0x49,0x92,0xea,0x6f,0xa,0xbf,0x7d,0x8,0x21,0x68,0x70,0x70,0xb0,0x38,0x39,0x39,0x79,0xd6,0xd9,0xd9,0xb9,0xcf,0x30,0xcc,0xa2,0xd6,0xad,0x21,0x2b,0x1c,0x0,0x38,0x41,0x10,0xfc,0xdb,0xdb,0xdb,0x27,0x1e,0x8f,0x27,0x4b,0x8,0x1,0x84,0x90,0xea,0xf,0x21,0x4,0x3c,0x1e,0x4f,0x76,0x67,0x67,0x67,0x3f,0x9f,0xcf,0xff,0x7c,0x5,0xf3,0xd9,0x0,0xe0,0x2,0x81,0xc0,0xa9,0xdb,0xed,0x2e,0x94,0x2b,0x5c,0xe,0xc4,0xca,0xca,0x8a,0x18,0x8d,0x46,0x3,0x0,0xc0,0x69,0x1e,0x4,0x0,0x90,0x48,0x24,0x12,0xe4,0x38,0xee,0x41,0xc2,0x6f,0x43,0xe0,0x38,0xe,0xfc,0x7e,0xbf,0x10,0x8b,0xc5,0xd6,0x35,0xd,0x22,0x9b,0xcd,0x7a,0x96,0x97,0x97,0x33,0xf,0xad,0x7c,0x29,0x10,0x9b,0x9b,0x9b,0xef,0x2e,0x2e,0x2e,0x7e,0xd5,0x1c,0x8,0x0,0x20,0xe1,0x70,0x38,0xfc,0x98,0xd5,0x57,0x2,0xe1,0x76,0xbb,0xf3,0xa1,0x50,0xe8,0x38,0x9b,0xcd,0xfe,0xa2,0x9,0x8,0x0,0x40,0x2e,0x2f,0x2f,0x7d,0x4b,0x4b,0x4b,0xb9,0x4a,0x54,0x5f,0x9,0xc4,0xd2,0xd2,0x92,0xb4,0xb7,0xb7,0xf7,0x36,0x97,0xcb,0x4d,0x3d,0x29,0x8,0x0,0xe0,0x42,0xa1,0xd0,0x71,0xb5,0xc4,0xdf,0xb6,0xc5,0x93,0xe,0x4a,0x0,0x20,0xa9,0x54,0xea,0x37,0xb7,0xdb,0x5d,0xa8,0xa6,0x78,0x39,0x10,0x6b,0x6b,0x6b,0xf1,0x64,0x32,0xb9,0x5a,0x55,0x10,0x0,0xc0,0x6d,0x6c,0x6c,0x9c,0x57,0xbb,0xfa,0x25,0x40,0x14,0x3,0x81,0x40,0x34,0x93,0xc9,0x2c,0x57,0x1c,0x4,0x0,0x90,0x58,0x2c,0xb6,0x5e,0xe9,0xc1,0x77,0x1f,0x10,0x53,0x53,0x53,0x52,0xc5,0x83,0x14,0x0,0x70,0x7e,0xbf,0x5f,0xd0,0x42,0xf5,0x95,0x40,0xf8,0x7c,0xbe,0xcb,0xa3,0xa3,0xa3,0x3f,0x1e,0xbd,0x1b,0x0,0x80,0x1c,0x1f,0x1f,0x87,0xb4,0x56,0xfd,0xaa,0x5,0x29,0x51,0x14,0xbf,0xf5,0xf9,0x7c,0x97,0x5a,0xad,0xbe,0x12,0x88,0xf5,0xf5,0xf5,0xd8,0x83,0x83,0x54,0xb5,0x42,0x8f,0x66,0x83,0x94,0xd6,0xbd,0x5f,0xce,0x7c,0x38,0x3c,0x3c,0xfc,0xb3,0x50,0x28,0xb8,0xcb,0x2,0x1,0x0,0xdc,0xf4,0xf4,0xf4,0xfe,0x73,0x15,0x2f,0x17,0xa4,0x22,0x91,0x48,0x50,0xb5,0x2d,0x0,0x80,0x9b,0x99,0x99,0x79,0xfb,0xdc,0x1,0xc8,0x5,0xa9,0x44,0x22,0xf1,0xfb,0x9d,0x10,0x0,0x80,0x9b,0x9d,0x9d,0xd,0xea,0x5,0xc0,0xad,0xfd,0x43,0x1a,0x0,0xb8,0xdb,0x9a,0xa9,0x8f,0xb6,0xa4,0x46,0xa3,0xa4,0xb7,0xd5,0x37,0xcf,0xf3,0x68,0x75,0x75,0xf5,0x4c,0xee,0x99,0x1c,0x80,0x9c,0x1e,0xf7,0xff,0x16,0x8b,0x45,0x50,0x5,0xa0,0xb7,0xb7,0xb7,0x85,0x10,0xa2,0x2b,0xf1,0x84,0x10,0xd4,0xdf,0xdf,0x6f,0x57,0x3,0x80,0x37,0x18,0xc,0x5,0x3d,0x2,0xa0,0x69,0x3a,0x8b,0x10,0xe2,0x4b,0x2,0xc0,0x18,0xf3,0xc1,0x60,0x70,0x47,0x8f,0x16,0x38,0x3a,0x3a,0x5a,0x93,0x5b,0xc3,0x7f,0x64,0x81,0xba,0xba,0x3a,0x49,0x8f,0x0,0x1a,0x1a,0x1a,0xd4,0xcd,0x0,0x93,0xc9,0xa4,0xcb,0x21,0xe8,0x74,0x3a,0xd5,0x1,0xa0,0x69,0x5a,0x77,0x1d,0x80,0x31,0x2e,0x38,0x9d,0x4e,0xb1,0x66,0x1,0x30,0xc,0x23,0x28,0x3d,0x93,0x9b,0x1,0xb9,0x9a,0x6,0x60,0x36,0x9b,0x75,0xd7,0x1,0x4a,0x21,0xa8,0x26,0x0,0x94,0xa,0x41,0xb2,0x0,0x18,0x86,0xc9,0xe9,0xd,0x80,0x52,0x8,0x92,0x5,0x60,0xb1,0x58,0x74,0x67,0x1,0xa5,0x10,0xa4,0x4,0x40,0x77,0x43,0xd0,0xe1,0x70,0xa8,0x9f,0x1,0x14,0x45,0x1,0x45,0x51,0x79,0x3d,0x1,0x68,0x6e,0x6e,0x4e,0xaa,0x6,0x80,0x10,0x42,0x6,0x83,0x41,0x37,0x36,0x28,0x15,0x82,0x6a,0x2,0x0,0x4d,0xd3,0xa9,0x52,0xcf,0x95,0x0,0xe8,0x66,0xe,0x98,0xcd,0x66,0xa1,0x6c,0x0,0x7a,0x5a,0x8b,0x59,0x2c,0x96,0x64,0xcd,0x2,0xb8,0x2b,0x4,0xe9,0xde,0x2,0x77,0x85,0xa0,0x9a,0xb0,0x40,0xa9,0x10,0xa4,0x8,0xc0,0x64,0x32,0xe9,0x6,0x40,0xa9,0x10,0x54,0xaa,0x3,0x74,0xf3,0x16,0x70,0xb9,0x5c,0xe5,0x3,0xe8,0xe9,0xe9,0x69,0xd5,0xc3,0x66,0x18,0x63,0x5c,0x68,0x6a,0x6a,0x12,0xcb,0x5,0xa0,0x9b,0xd5,0x38,0x4d,0xd3,0x29,0x8a,0xa2,0xa0,0x2c,0x0,0x18,0x63,0x3e,0x14,0xa,0xfd,0x55,0xb,0x21,0x48,0xd1,0x2,0x7a,0x59,0x8d,0xdf,0x1b,0x80,0x1e,0x56,0xe3,0x84,0x10,0x34,0x30,0x30,0x60,0xbb,0xeb,0x77,0x46,0x5,0xef,0x48,0xcf,0x4d,0xec,0x8d,0x99,0x5,0xf5,0xf5,0xf5,0xef,0x46,0x47,0x47,0xb,0x2e,0x97,0xeb,0xbc,0x54,0x8,0x52,0x4,0xc0,0x30,0x8c,0xf4,0x5c,0x4,0x9b,0x4c,0xa6,0xf4,0xf8,0xf8,0xb8,0xc8,0xb2,0x6c,0x32,0x9d,0x4e,0xff,0xd4,0xdd,0xdd,0x7d,0x66,0x34,0x1a,0x8b,0xd7,0x3,0xfd,0xae,0x5b,0x29,0xb2,0x57,0x66,0xb6,0xb6,0xb6,0xde,0xc4,0xe3,0xf1,0x6f,0xae,0xaf,0xc1,0x28,0x5d,0x85,0x79,0x2,0xc1,0x60,0xb5,0x5a,0xa3,0xa3,0xa3,0xa3,0x45,0xab,0xd5,0x9a,0x2a,0x16,0x8b,0x8b,0x6d,0x6d,0x6d,0xef,0xd5,0x8a,0x55,0xd,0x20,0x91,0x48,0xbc,0x3e,0x38,0x38,0xf8,0xda,0x6e,0xb7,0xf7,0x5f,0x5c,0x5c,0xd4,0x7b,0xbd,0xde,0xbc,0x20,0x8,0xcd,0x85,0x42,0x81,0xfe,0xf0,0xae,0xac,0x10,0x98,0x9b,0xd5,0xc5,0x18,0x17,0x59,0x96,0x3d,0x1d,0x19,0x19,0x1,0x96,0x65,0x5,0x8a,0xa2,0x7e,0x6c,0x69,0x69,0x49,0x3d,0x44,0xb0,0x2a,0x0,0x1f,0xcc,0x74,0x75,0x41,0xea,0xfa,0x7b,0x32,0x99,0x64,0x76,0x77,0x77,0x5d,0xe,0x87,0xa3,0x5f,0x14,0xc5,0x57,0x57,0x60,0x5a,0x8b,0xc5,0xa2,0xf1,0xbe,0x50,0x6e,0xa,0x66,0x18,0x26,0x31,0x36,0x36,0x96,0x65,0x59,0x36,0x29,0x49,0x92,0xb7,0xbd,0xbd,0xfd,0x9f,0x72,0xda,0xf9,0xd1,0x1,0xa8,0x1,0x93,0xcf,0xe7,0xa9,0x93,0x93,0x13,0x1b,0x4d,0xd3,0x9f,0xb,0x82,0x60,0xf5,0x7a,0xbd,0xd9,0x54,0x2a,0xe5,0xcc,0x64,0x32,0xe,0xb9,0x6e,0xb9,0x16,0x8c,0x31,0x2e,0xda,0x6c,0xb6,0xc8,0xd0,0xd0,0x10,0x65,0xb3,0xd9,0x92,0x95,0xa8,0x6e,0xc5,0x0,0xa8,0xe9,0x96,0x68,0x34,0x6a,0xdd,0xdf,0xdf,0x6f,0x76,0xb9,0x5c,0x9f,0x89,0xa2,0x58,0xbf,0xb8,0xb8,0x8,0x26,0x93,0x29,0x3b,0x3c,0x3c,0x8c,0xed,0x76,0x7b,0xd2,0x68,0x34,0xfe,0xd0,0xd8,0xd8,0x98,0xae,0xb6,0xe0,0x8a,0x1,0x50,0xb,0xe6,0xa9,0x5,0xbf,0x9c,0x97,0xf3,0xff,0xf3,0x2f,0x6a,0x82,0x7f,0xf6,0x4e,0xca,0x1b,0xf5,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82
+static const unsigned char convex_png[] = {
+ 0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x40, 0x8, 0x6, 0x0, 0x0, 0x0, 0xaa, 0x69, 0x71, 0xde, 0x0, 0x0, 0x0, 0x1, 0x73, 0x52, 0x47, 0x42, 0x0, 0xae, 0xce, 0x1c, 0xe9, 0x0, 0x0, 0x0, 0x6, 0x62, 0x4b, 0x47, 0x44, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf9, 0x43, 0xbb, 0x7f, 0x0, 0x0, 0x0, 0x9, 0x70, 0x48, 0x59, 0x73, 0x0, 0x0, 0xb, 0x13, 0x0, 0x0, 0xb, 0x13, 0x1, 0x0, 0x9a, 0x9c, 0x18, 0x0, 0x0, 0x0, 0x7, 0x74, 0x49, 0x4d, 0x45, 0x7, 0xdb, 0x6, 0xa, 0x3, 0x13, 0x31, 0x66, 0xa7, 0xac, 0x79, 0x0, 0x0, 0x4, 0xef, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xed, 0x9b, 0xdd, 0x4e, 0x2a, 0x57, 0x14, 0xc7, 0xf7, 0x1e, 0xc0, 0x19, 0x38, 0x32, 0x80, 0xa, 0x6a, 0xda, 0x18, 0xa3, 0xc6, 0x47, 0x50, 0x7b, 0xa1, 0xd9, 0x36, 0x27, 0x7e, 0x44, 0xed, 0x45, 0x4d, 0x93, 0x3e, 0x40, 0x1f, 0x64, 0x90, 0xf4, 0x1, 0xbc, 0xf0, 0xc2, 0x9c, 0x57, 0x30, 0x4d, 0xbc, 0xa8, 0x6d, 0xc, 0x69, 0x26, 0xb5, 0x68, 0x8b, 0x35, 0x7e, 0x20, 0xb4, 0xf5, 0x14, 0xbf, 0x51, 0x3c, 0x52, 0xe, 0xc, 0xe, 0xc8, 0xf0, 0xb1, 0x7a, 0x51, 0x3d, 0xb1, 0x9e, 0x19, 0x1c, 0x54, 0x70, 0x1c, 0xdc, 0x9, 0x17, 0x64, 0x8, 0xc9, 0xff, 0xb7, 0xd6, 0x7f, 0xcd, 0x3f, 0x2b, 0xd9, 0x8, 0xbd, 0x9c, 0xda, 0x3e, 0xf8, 0x31, 0xff, 0xc, 0x0, 0x8, 0x42, 0x88, 0x9c, 0x9f, 0x9f, 0xbf, 0xa, 0x87, 0xc3, 0xad, 0x7d, 0x7d, 0x7d, 0x7f, 0x23, 0x84, 0x78, 0x8c, 0x31, 0xaf, 0x55, 0x0, 0xc6, 0xc7, 0x14, 0x1e, 0x8f, 0xc7, 0xbf, 0x38, 0x3c, 0x3c, 0x6c, 0x9b, 0x9f, 0x9f, 0x6f, 0xb8, 0x82, 0x9b, 0xee, 0xe8, 0xe8, 0xf8, 0x12, 0x0, 0xbe, 0xd3, 0x2a, 0x8, 0xfc, 0x50, 0xd1, 0xf9, 0x7c, 0x9e, 0x8a, 0x46, 0xa3, 0x5f, 0x9d, 0x9e, 0x9e, 0x7e, 0xb2, 0xb0, 0xb0, 0x60, 0xe5, 0x79, 0x1e, 0xf1, 0xfc, 0x7f, 0x3a, 0x9, 0x21, 0x88, 0x10, 0x82, 0x26, 0x26, 0x26, 0xde, 0x77, 0x75, 0x75, 0x85, 0x59, 0x96, 0xfd, 0x5e, 0x6b, 0x20, 0xf0, 0x7d, 0x85, 0x4b, 0x92, 0xf4, 0xfa, 0xe0, 0xe0, 0xe0, 0xd3, 0xb9, 0xb9, 0xb9, 0x46, 0x49, 0x92, 0xea, 0x6f, 0xa, 0xbf, 0x7d, 0x8, 0x21, 0x68, 0x70, 0x70, 0xb0, 0x38, 0x39, 0x39, 0x79, 0xd6, 0xd9, 0xd9, 0xb9, 0xcf, 0x30, 0xcc, 0xa2, 0xd6, 0xad, 0x21, 0x2b, 0x1c, 0x0, 0x38, 0x41, 0x10, 0xfc, 0xdb, 0xdb, 0xdb, 0x27, 0x1e, 0x8f, 0x27, 0x4b, 0x8, 0x1, 0x84, 0x90, 0xea, 0xf, 0x21, 0x4, 0x3c, 0x1e, 0x4f, 0x76, 0x67, 0x67, 0x67, 0x3f, 0x9f, 0xcf, 0xff, 0x7c, 0x5, 0xf3, 0xd9, 0x0, 0xe0, 0x2, 0x81, 0xc0, 0xa9, 0xdb, 0xed, 0x2e, 0x94, 0x2b, 0x5c, 0xe, 0xc4, 0xca, 0xca, 0x8a, 0x18, 0x8d, 0x46, 0x3, 0x0, 0xc0, 0x69, 0x1e, 0x4, 0x0, 0x90, 0x48, 0x24, 0x12, 0xe4, 0x38, 0xee, 0x41, 0xc2, 0x6f, 0x43, 0xe0, 0x38, 0xe, 0xfc, 0x7e, 0xbf, 0x10, 0x8b, 0xc5, 0xd6, 0x35, 0xd, 0x22, 0x9b, 0xcd, 0x7a, 0x96, 0x97, 0x97, 0x33, 0xf, 0xad, 0x7c, 0x29, 0x10, 0x9b, 0x9b, 0x9b, 0xef, 0x2e, 0x2e, 0x2e, 0x7e, 0xd5, 0x1c, 0x8, 0x0, 0x20, 0xe1, 0x70, 0x38, 0xfc, 0x98, 0xd5, 0x57, 0x2, 0xe1, 0x76, 0xbb, 0xf3, 0xa1, 0x50, 0xe8, 0x38, 0x9b, 0xcd, 0xfe, 0xa2, 0x9, 0x8, 0x0, 0x40, 0x2e, 0x2f, 0x2f, 0x7d, 0x4b, 0x4b, 0x4b, 0xb9, 0x4a, 0x54, 0x5f, 0x9, 0xc4, 0xd2, 0xd2, 0x92, 0xb4, 0xb7, 0xb7, 0xf7, 0x36, 0x97, 0xcb, 0x4d, 0x3d, 0x29, 0x8, 0x0, 0xe0, 0x42, 0xa1, 0xd0, 0x71, 0xb5, 0xc4, 0xdf, 0xb6, 0xc5, 0x93, 0xe, 0x4a, 0x0, 0x20, 0xa9, 0x54, 0xea, 0x37, 0xb7, 0xdb, 0x5d, 0xa8, 0xa6, 0x78, 0x39, 0x10, 0x6b, 0x6b, 0x6b, 0xf1, 0x64, 0x32, 0xb9, 0x5a, 0x55, 0x10, 0x0, 0xc0, 0x6d, 0x6c, 0x6c, 0x9c, 0x57, 0xbb, 0xfa, 0x25, 0x40, 0x14, 0x3, 0x81, 0x40, 0x34, 0x93, 0xc9, 0x2c, 0x57, 0x1c, 0x4, 0x0, 0x90, 0x58, 0x2c, 0xb6, 0x5e, 0xe9, 0xc1, 0x77, 0x1f, 0x10, 0x53, 0x53, 0x53, 0x52, 0xc5, 0x83, 0x14, 0x0, 0x70, 0x7e, 0xbf, 0x5f, 0xd0, 0x42, 0xf5, 0x95, 0x40, 0xf8, 0x7c, 0xbe, 0xcb, 0xa3, 0xa3, 0xa3, 0x3f, 0x1e, 0xbd, 0x1b, 0x0, 0x80, 0x1c, 0x1f, 0x1f, 0x87, 0xb4, 0x56, 0xfd, 0xaa, 0x5, 0x29, 0x51, 0x14, 0xbf, 0xf5, 0xf9, 0x7c, 0x97, 0x5a, 0xad, 0xbe, 0x12, 0x88, 0xf5, 0xf5, 0xf5, 0xd8, 0x83, 0x83, 0x54, 0xb5, 0x42, 0x8f, 0x66, 0x83, 0x94, 0xd6, 0xbd, 0x5f, 0xce, 0x7c, 0x38, 0x3c, 0x3c, 0xfc, 0xb3, 0x50, 0x28, 0xb8, 0xcb, 0x2, 0x1, 0x0, 0xdc, 0xf4, 0xf4, 0xf4, 0xfe, 0x73, 0x15, 0x2f, 0x17, 0xa4, 0x22, 0x91, 0x48, 0x50, 0xb5, 0x2d, 0x0, 0x80, 0x9b, 0x99, 0x99, 0x79, 0xfb, 0xdc, 0x1, 0xc8, 0x5, 0xa9, 0x44, 0x22, 0xf1, 0xfb, 0x9d, 0x10, 0x0, 0x80, 0x9b, 0x9d, 0x9d, 0xd, 0xea, 0x5, 0xc0, 0xad, 0xfd, 0x43, 0x1a, 0x0, 0xb8, 0xdb, 0x9a, 0xa9, 0x8f, 0xb6, 0xa4, 0x46, 0xa3, 0xa4, 0xb7, 0xd5, 0x37, 0xcf, 0xf3, 0x68, 0x75, 0x75, 0xf5, 0x4c, 0xee, 0x99, 0x1c, 0x80, 0x9c, 0x1e, 0xf7, 0xff, 0x16, 0x8b, 0x45, 0x50, 0x5, 0xa0, 0xb7, 0xb7, 0xb7, 0x85, 0x10, 0xa2, 0x2b, 0xf1, 0x84, 0x10, 0xd4, 0xdf, 0xdf, 0x6f, 0x57, 0x3, 0x80, 0x37, 0x18, 0xc, 0x5, 0x3d, 0x2, 0xa0, 0x69, 0x3a, 0x8b, 0x10, 0xe2, 0x4b, 0x2, 0xc0, 0x18, 0xf3, 0xc1, 0x60, 0x70, 0x47, 0x8f, 0x16, 0x38, 0x3a, 0x3a, 0x5a, 0x93, 0x5b, 0xc3, 0x7f, 0x64, 0x81, 0xba, 0xba, 0x3a, 0x49, 0x8f, 0x0, 0x1a, 0x1a, 0x1a, 0xd4, 0xcd, 0x0, 0x93, 0xc9, 0xa4, 0xcb, 0x21, 0xe8, 0x74, 0x3a, 0xd5, 0x1, 0xa0, 0x69, 0x5a, 0x77, 0x1d, 0x80, 0x31, 0x2e, 0x38, 0x9d, 0x4e, 0xb1, 0x66, 0x1, 0x30, 0xc, 0x23, 0x28, 0x3d, 0x93, 0x9b, 0x1, 0xb9, 0x9a, 0x6, 0x60, 0x36, 0x9b, 0x75, 0xd7, 0x1, 0x4a, 0x21, 0xa8, 0x26, 0x0, 0x94, 0xa, 0x41, 0xb2, 0x0, 0x18, 0x86, 0xc9, 0xe9, 0xd, 0x80, 0x52, 0x8, 0x92, 0x5, 0x60, 0xb1, 0x58, 0x74, 0x67, 0x1, 0xa5, 0x10, 0xa4, 0x4, 0x40, 0x77, 0x43, 0xd0, 0xe1, 0x70, 0xa8, 0x9f, 0x1, 0x14, 0x45, 0x1, 0x45, 0x51, 0x79, 0x3d, 0x1, 0x68, 0x6e, 0x6e, 0x4e, 0xaa, 0x6, 0x80, 0x10, 0x42, 0x6, 0x83, 0x41, 0x37, 0x36, 0x28, 0x15, 0x82, 0x6a, 0x2, 0x0, 0x4d, 0xd3, 0xa9, 0x52, 0xcf, 0x95, 0x0, 0xe8, 0x66, 0xe, 0x98, 0xcd, 0x66, 0xa1, 0x6c, 0x0, 0x7a, 0x5a, 0x8b, 0x59, 0x2c, 0x96, 0x64, 0xcd, 0x2, 0xb8, 0x2b, 0x4, 0xe9, 0xde, 0x2, 0x77, 0x85, 0xa0, 0x9a, 0xb0, 0x40, 0xa9, 0x10, 0xa4, 0x8, 0xc0, 0x64, 0x32, 0xe9, 0x6, 0x40, 0xa9, 0x10, 0x54, 0xaa, 0x3, 0x74, 0xf3, 0x16, 0x70, 0xb9, 0x5c, 0xe5, 0x3, 0xe8, 0xe9, 0xe9, 0x69, 0xd5, 0xc3, 0x66, 0x18, 0x63, 0x5c, 0x68, 0x6a, 0x6a, 0x12, 0xcb, 0x5, 0xa0, 0x9b, 0xd5, 0x38, 0x4d, 0xd3, 0x29, 0x8a, 0xa2, 0xa0, 0x2c, 0x0, 0x18, 0x63, 0x3e, 0x14, 0xa, 0xfd, 0x55, 0xb, 0x21, 0x48, 0xd1, 0x2, 0x7a, 0x59, 0x8d, 0xdf, 0x1b, 0x80, 0x1e, 0x56, 0xe3, 0x84, 0x10, 0x34, 0x30, 0x30, 0x60, 0xbb, 0xeb, 0x77, 0x46, 0x5, 0xef, 0x48, 0xcf, 0x4d, 0xec, 0x8d, 0x99, 0x5, 0xf5, 0xf5, 0xf5, 0xef, 0x46, 0x47, 0x47, 0xb, 0x2e, 0x97, 0xeb, 0xbc, 0x54, 0x8, 0x52, 0x4, 0xc0, 0x30, 0x8c, 0xf4, 0x5c, 0x4, 0x9b, 0x4c, 0xa6, 0xf4, 0xf8, 0xf8, 0xb8, 0xc8, 0xb2, 0x6c, 0x32, 0x9d, 0x4e, 0xff, 0xd4, 0xdd, 0xdd, 0x7d, 0x66, 0x34, 0x1a, 0x8b, 0xd7, 0x3, 0xfd, 0xae, 0x5b, 0x29, 0xb2, 0x57, 0x66, 0xb6, 0xb6, 0xb6, 0xde, 0xc4, 0xe3, 0xf1, 0x6f, 0xae, 0xaf, 0xc1, 0x28, 0x5d, 0x85, 0x79, 0x2, 0xc1, 0x60, 0xb5, 0x5a, 0xa3, 0xa3, 0xa3, 0xa3, 0x45, 0xab, 0xd5, 0x9a, 0x2a, 0x16, 0x8b, 0x8b, 0x6d, 0x6d, 0x6d, 0xef, 0xd5, 0x8a, 0x55, 0xd, 0x20, 0x91, 0x48, 0xbc, 0x3e, 0x38, 0x38, 0xf8, 0xda, 0x6e, 0xb7, 0xf7, 0x5f, 0x5c, 0x5c, 0xd4, 0x7b, 0xbd, 0xde, 0xbc, 0x20, 0x8, 0xcd, 0x85, 0x42, 0x81, 0xfe, 0xf0, 0xae, 0xac, 0x10, 0x98, 0x9b, 0xd5, 0xc5, 0x18, 0x17, 0x59, 0x96, 0x3d, 0x1d, 0x19, 0x19, 0x1, 0x96, 0x65, 0x5, 0x8a, 0xa2, 0x7e, 0x6c, 0x69, 0x69, 0x49, 0x3d, 0x44, 0xb0, 0x2a, 0x0, 0x1f, 0xcc, 0x74, 0x75, 0x41, 0xea, 0xfa, 0x7b, 0x32, 0x99, 0x64, 0x76, 0x77, 0x77, 0x5d, 0xe, 0x87, 0xa3, 0x5f, 0x14, 0xc5, 0x57, 0x57, 0x60, 0x5a, 0x8b, 0xc5, 0xa2, 0xf1, 0xbe, 0x50, 0x6e, 0xa, 0x66, 0x18, 0x26, 0x31, 0x36, 0x36, 0x96, 0x65, 0x59, 0x36, 0x29, 0x49, 0x92, 0xb7, 0xbd, 0xbd, 0xfd, 0x9f, 0x72, 0xda, 0xf9, 0xd1, 0x1, 0xa8, 0x1, 0x93, 0xcf, 0xe7, 0xa9, 0x93, 0x93, 0x13, 0x1b, 0x4d, 0xd3, 0x9f, 0xb, 0x82, 0x60, 0xf5, 0x7a, 0xbd, 0xd9, 0x54, 0x2a, 0xe5, 0xcc, 0x64, 0x32, 0xe, 0xb9, 0x6e, 0xb9, 0x16, 0x8c, 0x31, 0x2e, 0xda, 0x6c, 0xb6, 0xc8, 0xd0, 0xd0, 0x10, 0x65, 0xb3, 0xd9, 0x92, 0x95, 0xa8, 0x6e, 0xc5, 0x0, 0xa8, 0xe9, 0x96, 0x68, 0x34, 0x6a, 0xdd, 0xdf, 0xdf, 0x6f, 0x76, 0xb9, 0x5c, 0x9f, 0x89, 0xa2, 0x58, 0xbf, 0xb8, 0xb8, 0x8, 0x26, 0x93, 0x29, 0x3b, 0x3c, 0x3c, 0x8c, 0xed, 0x76, 0x7b, 0xd2, 0x68, 0x34, 0xfe, 0xd0, 0xd8, 0xd8, 0x98, 0xae, 0xb6, 0xe0, 0x8a, 0x1, 0x50, 0xb, 0xe6, 0xa9, 0x5, 0xbf, 0x9c, 0x97, 0xf3, 0xff, 0xf3, 0x2f, 0x6a, 0x82, 0x7f, 0xf6, 0x4e, 0xca, 0x1b, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
};
-
class TestPhysics2DMainLoop : public MainLoop {
- GDCLASS( TestPhysics2DMainLoop, MainLoop );
-
+ GDCLASS(TestPhysics2DMainLoop, MainLoop);
RID circle_img;
RID circle_shape;
@@ -54,8 +52,7 @@ class TestPhysics2DMainLoop : public MainLoop {
RID ray_query;
Transform2D view_xform;
- Vector2 ray_from,ray_to;
-
+ Vector2 ray_from, ray_to;
struct BodyShapeData {
@@ -63,10 +60,8 @@ class TestPhysics2DMainLoop : public MainLoop {
RID shape;
};
-
BodyShapeData body_shape_data[8];
-
void _create_body_shape_data() {
VisualServer *vs = VisualServer::get_singleton();
Physics2DServer *ps = Physics2DServer::get_singleton();
@@ -76,53 +71,51 @@ class TestPhysics2DMainLoop : public MainLoop {
{
PoolVector<uint8_t> pixels;
- pixels.resize(32*2*2);
- for(int i=0;i<2;i++) {
+ pixels.resize(32 * 2 * 2);
+ for (int i = 0; i < 2; i++) {
- for(int j=0;j<32;j++) {
+ for (int j = 0; j < 32; j++) {
- pixels.set(i*32*2+j*2+0,(j==0)?255:0);
- pixels.set(i*32*2+j*2+1,255);
+ pixels.set(i * 32 * 2 + j * 2 + 0, (j == 0) ? 255 : 0);
+ pixels.set(i * 32 * 2 + j * 2 + 1, 255);
}
}
- Image image(32,2,0,Image::FORMAT_LA8,pixels);
+ Image image(32, 2, 0, Image::FORMAT_LA8, pixels);
- body_shape_data[Physics2DServer::SHAPE_SEGMENT].image=vs->texture_create_from_image(image);
+ body_shape_data[Physics2DServer::SHAPE_SEGMENT].image = vs->texture_create_from_image(image);
RID segment_shape = ps->shape_create(Physics2DServer::SHAPE_SEGMENT);
- Rect2 sg(Point2(-16,0),Point2(16,0));
- ps->shape_set_data(segment_shape,sg);
+ Rect2 sg(Point2(-16, 0), Point2(16, 0));
+ ps->shape_set_data(segment_shape, sg);
body_shape_data[Physics2DServer::SHAPE_SEGMENT].shape = segment_shape;
-
}
// CIRCLE
{
PoolVector<uint8_t> pixels;
- pixels.resize(32*32*2);
- for(int i=0;i<32;i++) {
+ pixels.resize(32 * 32 * 2);
+ for (int i = 0; i < 32; i++) {
- for(int j=0;j<32;j++) {
+ for (int j = 0; j < 32; j++) {
- bool black=Vector2(i-16,j-16).length_squared() < 16*16;
+ bool black = Vector2(i - 16, j - 16).length_squared() < 16 * 16;
- pixels.set(i*32*2+j*2+0,(i==16 || j==16)?255:0);
- pixels.set(i*32*2+j*2+1,black?255:0);
+ pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16) ? 255 : 0);
+ pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0);
}
}
- Image image(32,32,0,Image::FORMAT_LA8,pixels);
+ Image image(32, 32, 0, Image::FORMAT_LA8, pixels);
- body_shape_data[Physics2DServer::SHAPE_CIRCLE].image=vs->texture_create_from_image(image);
+ body_shape_data[Physics2DServer::SHAPE_CIRCLE].image = vs->texture_create_from_image(image);
RID circle_shape = ps->shape_create(Physics2DServer::SHAPE_CIRCLE);
- ps->shape_set_data(circle_shape,16);
+ ps->shape_set_data(circle_shape, 16);
body_shape_data[Physics2DServer::SHAPE_CIRCLE].shape = circle_shape;
-
}
// BOX
@@ -130,167 +123,151 @@ class TestPhysics2DMainLoop : public MainLoop {
{
PoolVector<uint8_t> pixels;
- pixels.resize(32*32*2);
- for(int i=0;i<32;i++) {
+ pixels.resize(32 * 32 * 2);
+ for (int i = 0; i < 32; i++) {
- for(int j=0;j<32;j++) {
+ for (int j = 0; j < 32; j++) {
- bool black=i>0 && i<31 && j>0 && j<31;
+ bool black = i > 0 && i < 31 && j > 0 && j < 31;
- pixels.set(i*32*2+j*2+0,black?0:255);
- pixels.set(i*32*2+j*2+1,255);
+ pixels.set(i * 32 * 2 + j * 2 + 0, black ? 0 : 255);
+ pixels.set(i * 32 * 2 + j * 2 + 1, 255);
}
}
- Image image(32,32,0,Image::FORMAT_LA8,pixels);
+ Image image(32, 32, 0, Image::FORMAT_LA8, pixels);
- body_shape_data[Physics2DServer::SHAPE_RECTANGLE].image=vs->texture_create_from_image(image);
+ body_shape_data[Physics2DServer::SHAPE_RECTANGLE].image = vs->texture_create_from_image(image);
RID rectangle_shape = ps->shape_create(Physics2DServer::SHAPE_RECTANGLE);
- ps->shape_set_data(rectangle_shape,Vector2(16,16));
+ ps->shape_set_data(rectangle_shape, Vector2(16, 16));
body_shape_data[Physics2DServer::SHAPE_RECTANGLE].shape = rectangle_shape;
-
}
-
// CAPSULE
{
PoolVector<uint8_t> pixels;
- pixels.resize(32*64*2);
- for(int i=0;i<64;i++) {
-
- for(int j=0;j<32;j++) {
+ pixels.resize(32 * 64 * 2);
+ for (int i = 0; i < 64; i++) {
+ for (int j = 0; j < 32; j++) {
- int si = i>48 ? i - 32 : (i<16 ? i : 16);
- bool black=Vector2(si-16,j-16).length_squared() < 16*16;
-
- pixels.set(i*32*2+j*2+0,(i==16 || j==16 || i==48)?255:0);
- pixels.set(i*32*2+j*2+1,black?255:0);
+ int si = i > 48 ? i - 32 : (i < 16 ? i : 16);
+ bool black = Vector2(si - 16, j - 16).length_squared() < 16 * 16;
+ pixels.set(i * 32 * 2 + j * 2 + 0, (i == 16 || j == 16 || i == 48) ? 255 : 0);
+ pixels.set(i * 32 * 2 + j * 2 + 1, black ? 255 : 0);
}
}
- Image image(32,64,0,Image::FORMAT_LA8,pixels);
+ Image image(32, 64, 0, Image::FORMAT_LA8, pixels);
- body_shape_data[Physics2DServer::SHAPE_CAPSULE].image=vs->texture_create_from_image(image);
+ body_shape_data[Physics2DServer::SHAPE_CAPSULE].image = vs->texture_create_from_image(image);
RID capsule_shape = ps->shape_create(Physics2DServer::SHAPE_CAPSULE);
- ps->shape_set_data(capsule_shape,Vector2(16,32));
+ ps->shape_set_data(capsule_shape, Vector2(16, 32));
body_shape_data[Physics2DServer::SHAPE_CAPSULE].shape = capsule_shape;
-
}
// CONVEX
{
-
Image image(convex_png);
- body_shape_data[Physics2DServer::SHAPE_CONVEX_POLYGON].image=vs->texture_create_from_image(image);
+ body_shape_data[Physics2DServer::SHAPE_CONVEX_POLYGON].image = vs->texture_create_from_image(image);
RID convex_polygon_shape = ps->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON);
PoolVector<Vector2> arr;
- Point2 sb(32,32);
- arr.push_back(Point2(20,3)-sb);
- arr.push_back(Point2(58,23)-sb);
- arr.push_back(Point2(55,54)-sb);
- arr.push_back(Point2(27,60)-sb);
- arr.push_back(Point2(5,56)-sb);
- arr.push_back(Point2(4,20)-sb);
- arr.push_back(Point2(11,7)-sb);
- ps->shape_set_data(convex_polygon_shape,arr);
+ Point2 sb(32, 32);
+ arr.push_back(Point2(20, 3) - sb);
+ arr.push_back(Point2(58, 23) - sb);
+ arr.push_back(Point2(55, 54) - sb);
+ arr.push_back(Point2(27, 60) - sb);
+ arr.push_back(Point2(5, 56) - sb);
+ arr.push_back(Point2(4, 20) - sb);
+ arr.push_back(Point2(11, 7) - sb);
+ ps->shape_set_data(convex_polygon_shape, arr);
body_shape_data[Physics2DServer::SHAPE_CONVEX_POLYGON].shape = convex_polygon_shape;
-
}
-
-
}
-
-
-
void _do_ray_query() {
/*
Physics2DServer *ps = Physics2DServer::get_singleton();
ps->query_intersection_segment(ray_query,ray_from,ray_to);
*/
-
}
protected:
+ void input_event(const InputEvent &p_event) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON) {
- void input_event(const InputEvent& p_event) {
-
- if (p_event.type==InputEvent::MOUSE_BUTTON) {
-
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
if (mb.pressed) {
- Point2 p( mb.x, mb.y );
+ Point2 p(mb.x, mb.y);
- if (mb.button_index==1) {
- ray_to=p;
+ if (mb.button_index == 1) {
+ ray_to = p;
_do_ray_query();
- } else if (mb.button_index==2) {
- ray_from=p;
+ } else if (mb.button_index == 2) {
+ ray_from = p;
_do_ray_query();
}
-
}
}
- if (p_event.type==InputEvent::MOUSE_MOTION) {
+ if (p_event.type == InputEvent::MOUSE_MOTION) {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
- Point2 p( mm.x, mm.y );
+ Point2 p(mm.x, mm.y);
- if (mm.button_mask&BUTTON_MASK_LEFT) {
- ray_to=p;
+ if (mm.button_mask & BUTTON_MASK_LEFT) {
+ ray_to = p;
_do_ray_query();
- } else if (mm.button_mask&BUTTON_MASK_RIGHT) {
- ray_from=p;
+ } else if (mm.button_mask & BUTTON_MASK_RIGHT) {
+ ray_from = p;
_do_ray_query();
}
}
}
- RID _add_body(Physics2DServer::ShapeType p_shape, const Transform2D& p_xform) {
+ RID _add_body(Physics2DServer::ShapeType p_shape, const Transform2D &p_xform) {
VisualServer *vs = VisualServer::get_singleton();
Physics2DServer *ps = Physics2DServer::get_singleton();
RID body = ps->body_create();
- ps->body_add_shape(body,body_shape_data[p_shape].shape);
- ps->body_set_space(body,space);
- ps->body_set_continuous_collision_detection_mode(body,Physics2DServer::CCD_MODE_CAST_SHAPE);
- ps->body_set_state(body,Physics2DServer::BODY_STATE_TRANSFORM,p_xform);
+ ps->body_add_shape(body, body_shape_data[p_shape].shape);
+ ps->body_set_space(body, space);
+ ps->body_set_continuous_collision_detection_mode(body, Physics2DServer::CCD_MODE_CAST_SHAPE);
+ ps->body_set_state(body, Physics2DServer::BODY_STATE_TRANSFORM, p_xform);
//print_line("add body with xform: "+p_xform);
RID sprite = vs->canvas_item_create();
- vs->canvas_item_set_parent(sprite,canvas);
- vs->canvas_item_set_transform(sprite,p_xform);
- Size2 imgsize( vs->texture_get_width(body_shape_data[p_shape].image),vs->texture_get_height(body_shape_data[p_shape].image) );
- vs->canvas_item_add_texture_rect(sprite,Rect2(-imgsize/2.0,imgsize),body_shape_data[p_shape].image);
+ vs->canvas_item_set_parent(sprite, canvas);
+ vs->canvas_item_set_transform(sprite, p_xform);
+ Size2 imgsize(vs->texture_get_width(body_shape_data[p_shape].image), vs->texture_get_height(body_shape_data[p_shape].image));
+ vs->canvas_item_add_texture_rect(sprite, Rect2(-imgsize / 2.0, imgsize), body_shape_data[p_shape].image);
- ps->body_set_force_integration_callback(body,this,"_body_moved",sprite);
+ ps->body_set_force_integration_callback(body, this, "_body_moved", sprite);
//RID q = ps->query_create(this,"_body_moved",sprite);
//ps->query_body_state(q,body);
return body;
}
- void _add_plane(const Vector2& p_normal, real_t p_d) {
+ void _add_plane(const Vector2 &p_normal, real_t p_d) {
Physics2DServer *ps = Physics2DServer::get_singleton();
@@ -299,85 +276,73 @@ protected:
arr.push_back(p_d);
RID plane = ps->shape_create(Physics2DServer::SHAPE_LINE);
- ps->shape_set_data(plane,arr);
+ ps->shape_set_data(plane, arr);
RID plane_body = ps->body_create(Physics2DServer::BODY_MODE_STATIC);
- ps->body_set_space(plane_body,space);
- ps->body_add_shape(plane_body,plane);
-
+ ps->body_set_space(plane_body, space);
+ ps->body_add_shape(plane_body, plane);
}
- void _add_concave(const Vector<Vector2>& p_points,const Transform2D& p_xform=Transform2D()) {
+ void _add_concave(const Vector<Vector2> &p_points, const Transform2D &p_xform = Transform2D()) {
Physics2DServer *ps = Physics2DServer::get_singleton();
VisualServer *vs = VisualServer::get_singleton();
RID concave = ps->shape_create(Physics2DServer::SHAPE_CONCAVE_POLYGON);
- ps->shape_set_data(concave,p_points);
+ ps->shape_set_data(concave, p_points);
RID body = ps->body_create(Physics2DServer::BODY_MODE_STATIC);
- ps->body_set_space(body,space);
- ps->body_add_shape(body,concave);
- ps->body_set_state(body,Physics2DServer::BODY_STATE_TRANSFORM,p_xform);
-
+ ps->body_set_space(body, space);
+ ps->body_add_shape(body, concave);
+ ps->body_set_state(body, Physics2DServer::BODY_STATE_TRANSFORM, p_xform);
RID sprite = vs->canvas_item_create();
- vs->canvas_item_set_parent(sprite,canvas);
- vs->canvas_item_set_transform(sprite,p_xform);
- for(int i=0;i<p_points.size();i+=2) {
- vs->canvas_item_add_line(sprite,p_points[i],p_points[i+1],Color(0,0,0),2);
+ vs->canvas_item_set_parent(sprite, canvas);
+ vs->canvas_item_set_transform(sprite, p_xform);
+ for (int i = 0; i < p_points.size(); i += 2) {
+ vs->canvas_item_add_line(sprite, p_points[i], p_points[i + 1], Color(0, 0, 0), 2);
}
-
}
- void _body_moved(Object *p_state,RID p_sprite) {
- Physics2DDirectBodyState *state=(Physics2DDirectBodyState *)p_state;
- VisualServer::get_singleton()->canvas_item_set_transform(p_sprite,state->get_transform());
+ void _body_moved(Object *p_state, RID p_sprite) {
+ Physics2DDirectBodyState *state = (Physics2DDirectBodyState *)p_state;
+ VisualServer::get_singleton()->canvas_item_set_transform(p_sprite, state->get_transform());
}
- void _ray_query_callback(const RID& p_rid, ObjectID p_id, int p_shape, const Vector2& p_point, const Vector2& p_normal) {
-
+ void _ray_query_callback(const RID &p_rid, ObjectID p_id, int p_shape, const Vector2 &p_point, const Vector2 &p_normal) {
Vector2 ray_end;
if (p_rid.is_valid()) {
- ray_end=p_point;
+ ray_end = p_point;
} else {
- ray_end=ray_to;
+ ray_end = ray_to;
}
VisualServer *vs = VisualServer::get_singleton();
vs->canvas_item_clear(ray);
- vs->canvas_item_add_line(ray,ray_from,ray_end,p_rid.is_valid()?Color(0,1,0.4):Color(1,0.4,0),2);
+ vs->canvas_item_add_line(ray, ray_from, ray_end, p_rid.is_valid() ? Color(0, 1, 0.4) : Color(1, 0.4, 0), 2);
if (p_rid.is_valid())
- vs->canvas_item_add_line(ray,ray_end,ray_end+p_normal*20,p_rid.is_valid()?Color(0,1,0.4):Color(1,0.4,0),2);
-
+ vs->canvas_item_add_line(ray, ray_end, ray_end + p_normal * 20, p_rid.is_valid() ? Color(0, 1, 0.4) : Color(1, 0.4, 0), 2);
}
static void _bind_methods() {
-
- ClassDB::bind_method(D_METHOD("_body_moved"),&TestPhysics2DMainLoop::_body_moved);
- ClassDB::bind_method(D_METHOD("_ray_query_callback"),&TestPhysics2DMainLoop::_ray_query_callback);
+ ClassDB::bind_method(D_METHOD("_body_moved"), &TestPhysics2DMainLoop::_body_moved);
+ ClassDB::bind_method(D_METHOD("_ray_query_callback"), &TestPhysics2DMainLoop::_ray_query_callback);
}
-
public:
-
-
-
virtual void init() {
VisualServer *vs = VisualServer::get_singleton();
Physics2DServer *ps = Physics2DServer::get_singleton();
-
-
- space=ps->space_create();
- ps->space_set_active(space,true);
+ space = ps->space_create();
+ ps->space_set_active(space, true);
ps->set_active(true);
- ps->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,Vector2(0,1));
- ps->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY,98);
+ ps->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY_VECTOR, Vector2(0, 1));
+ ps->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY, 98);
{
@@ -385,30 +350,29 @@ public:
canvas = vs->canvas_create();
Size2i screen_size = OS::get_singleton()->get_window_size();
- vs->viewport_attach_canvas(vp,canvas);
- vs->viewport_set_size(vp,screen_size.x,screen_size.y);
- vs->viewport_attach_to_screen(vp,Rect2(Vector2(),screen_size));
- vs->viewport_set_active(vp,true);
+ vs->viewport_attach_canvas(vp, canvas);
+ vs->viewport_set_size(vp, screen_size.x, screen_size.y);
+ vs->viewport_attach_to_screen(vp, Rect2(Vector2(), screen_size));
+ vs->viewport_set_active(vp, true);
Transform2D smaller;
//smaller.scale(Vector2(0.6,0.6));
//smaller.elements[2]=Vector2(100,0);
//view_xform = smaller;
- vs->viewport_set_canvas_transform(vp,canvas,view_xform);
-
+ vs->viewport_set_canvas_transform(vp, canvas, view_xform);
}
ray = vs->canvas_item_create();
- vs->canvas_item_set_parent(ray,canvas);
+ vs->canvas_item_set_parent(ray, canvas);
//ray_query = ps->query_create(this,"_ray_query_callback",Variant());
//ps->query_intersection(ray_query,space);
_create_body_shape_data();
- for(int i=0;i<32;i++) {
+ for (int i = 0; i < 32; i++) {
- Physics2DServer::ShapeType types[4]={
+ Physics2DServer::ShapeType types[4] = {
Physics2DServer::SHAPE_CIRCLE,
Physics2DServer::SHAPE_CAPSULE,
Physics2DServer::SHAPE_RECTANGLE,
@@ -416,9 +380,9 @@ public:
};
- Physics2DServer::ShapeType type = types[i%4];
+ Physics2DServer::ShapeType type = types[i % 4];
//type=Physics2DServer::SHAPE_SEGMENT;
- _add_body(type,Transform2D(i*0.8,Point2(152+i*40,100-40*i)));
+ _add_body(type, Transform2D(i * 0.8, Point2(152 + i * 40, 100 - 40 * i)));
/*
if (i==0)
ps->body_set_mode(b,Physics2DServer::BODY_MODE_STATIC);
@@ -431,47 +395,36 @@ public:
Point2 prev;
Vector<Point2> parr;
- for(int i=0;i<30;i++) {
+ for (int i = 0; i < 30; i++) {
- Point2 p(i*60,Math::randf() * 70+340);
- if (i>0) {
+ Point2 p(i * 60, Math::randf() * 70 + 340);
+ if (i > 0) {
parr.push_back(prev);
parr.push_back(p);
}
- prev=p;
+ prev = p;
}
_add_concave(parr);
//_add_plane(Vector2(0.0,-1).normalized(),-300);
//_add_plane(Vector2(1,0).normalized(),50);
//_add_plane(Vector2(-1,0).normalized(),-600);
-
}
virtual bool idle(float p_time) {
-
return false;
}
virtual void finish() {
-
-
}
-
TestPhysics2DMainLoop() {}
-
};
-
namespace TestPhysics2D {
+MainLoop *test() {
-MainLoop* test() {
-
-
- return memnew( TestPhysics2DMainLoop );
+ return memnew(TestPhysics2DMainLoop);
}
-
-
}
diff --git a/main/tests/test_physics_2d.h b/main/tests/test_physics_2d.h
index dee18edfe0..883bf15201 100644
--- a/main/tests/test_physics_2d.h
+++ b/main/tests/test_physics_2d.h
@@ -29,13 +29,11 @@
#ifndef TEST_PHYSICS_2D_H
#define TEST_PHYSICS_2D_H
-
#include "os/main_loop.h"
namespace TestPhysics2D {
-MainLoop* test();
-
+MainLoop *test();
}
#endif // TEST_PHYSICS_2D_H
diff --git a/main/tests/test_render.cpp b/main/tests/test_render.cpp
index 512c48b116..188d736ff6 100644
--- a/main/tests/test_render.cpp
+++ b/main/tests/test_render.cpp
@@ -28,22 +28,20 @@
/*************************************************************************/
#include "test_render.h"
-#include "servers/visual_server.h"
-#include "os/main_loop.h"
#include "math_funcs.h"
-#include "print_string.h"
+#include "os/keyboard.h"
+#include "os/main_loop.h"
#include "os/os.h"
+#include "print_string.h"
#include "quick_hull.h"
-#include "os/keyboard.h"
+#include "servers/visual_server.h"
#define OBJECT_COUNT 50
namespace TestRender {
-
class TestMainLoop : public MainLoop {
-
RID test_cube;
RID instance;
RID camera;
@@ -62,37 +60,30 @@ class TestMainLoop : public MainLoop {
float ofs;
bool quit;
-protected:
-
+protected:
public:
- virtual void input_event(const InputEvent& p_event) {
+ virtual void input_event(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && p_event.key.pressed)
- quit=true;
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed)
+ quit = true;
}
virtual void init() {
-
print_line("INITIALIZING TEST RENDER");
- VisualServer *vs=VisualServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
test_cube = vs->get_test_cube();
scenario = vs->scenario_create();
-
-
-
-
-
Vector<Vector3> vts;
-/*
+ /*
PoolVector<Plane> sp = Geometry::build_sphere_planes(2,5,5);
Geometry::MeshData md2 = Geometry::build_convex_mesh(sp);
vts=md2.vertices;
*/
-/*
+ /*
static const int s = 20;
for(int i=0;i<s;i++) {
@@ -118,20 +109,20 @@ public:
vts.push_back(Vector3(1,0,0));
vts.push_back(Vector3(-1,0,0));*/
- vts.push_back(Vector3(1,1,1));
- vts.push_back(Vector3(1,-1,1));
- vts.push_back(Vector3(-1,1,1));
- vts.push_back(Vector3(-1,-1,1));
- vts.push_back(Vector3(1,1,-1));
- vts.push_back(Vector3(1,-1,-1));
- vts.push_back(Vector3(-1,1,-1));
- vts.push_back(Vector3(-1,-1,-1));
+ vts.push_back(Vector3(1, 1, 1));
+ vts.push_back(Vector3(1, -1, 1));
+ vts.push_back(Vector3(-1, 1, 1));
+ vts.push_back(Vector3(-1, -1, 1));
+ vts.push_back(Vector3(1, 1, -1));
+ vts.push_back(Vector3(1, -1, -1));
+ vts.push_back(Vector3(-1, 1, -1));
+ vts.push_back(Vector3(-1, -1, -1));
Geometry::MeshData md;
- Error err = QuickHull::build(vts,md);
- print_line("ERR: "+itos(err));
+ Error err = QuickHull::build(vts, md);
+ print_line("ERR: " + itos(err));
test_cube = vs->mesh_create();
- vs->mesh_add_surface_from_mesh_data(test_cube,md);
+ vs->mesh_add_surface_from_mesh_data(test_cube, md);
//vs->scenario_set_debug(scenario,VS::SCENARIO_DEBUG_WIREFRAME);
/*
@@ -143,46 +134,41 @@ public:
vs->material_set_shader(tcmat,sm);
*/
-
List<String> cmdline = OS::get_singleton()->get_cmdline_args();
int object_count = OBJECT_COUNT;
- if (cmdline.size() > 0 && cmdline[cmdline.size()-1].to_int()) {
- object_count = cmdline[cmdline.size()-1].to_int();
+ if (cmdline.size() > 0 && cmdline[cmdline.size() - 1].to_int()) {
+ object_count = cmdline[cmdline.size() - 1].to_int();
};
- for (int i=0;i<object_count;i++) {
+ for (int i = 0; i < object_count; i++) {
InstanceInfo ii;
+ ii.instance = vs->instance_create2(test_cube, scenario);
- ii.instance = vs->instance_create2( test_cube, scenario );
-
-
- ii.base.translate( Math::random(-20,20), Math::random(-20,20),Math::random(-20,18) );
- ii.base.rotate( Vector3(0,1,0), Math::randf() * Math_PI );
- ii.base.rotate( Vector3(1,0,0), Math::randf() * Math_PI );
- vs->instance_set_transform( ii.instance, ii.base );
+ ii.base.translate(Math::random(-20, 20), Math::random(-20, 20), Math::random(-20, 18));
+ ii.base.rotate(Vector3(0, 1, 0), Math::randf() * Math_PI);
+ ii.base.rotate(Vector3(1, 0, 0), Math::randf() * Math_PI);
+ vs->instance_set_transform(ii.instance, ii.base);
- ii.rot_axis = Vector3( Math::random(-1,1), Math::random(-1,1), Math::random(-1,1) ).normalized();
+ ii.rot_axis = Vector3(Math::random(-1, 1), Math::random(-1, 1), Math::random(-1, 1)).normalized();
instances.push_back(ii);
-
}
camera = vs->camera_create();
-// vs->camera_set_perspective( camera, 60.0,0.1, 100.0 );
+ // vs->camera_set_perspective( camera, 60.0,0.1, 100.0 );
viewport = vs->viewport_create();
Size2i screen_size = OS::get_singleton()->get_window_size();
- vs->viewport_set_size(viewport,screen_size.x,screen_size.y);
- vs->viewport_attach_to_screen(viewport,Rect2(Vector2(),screen_size));
- vs->viewport_set_active(viewport,true);
- vs->viewport_attach_camera( viewport, camera );
- vs->viewport_set_scenario( viewport, scenario );
- vs->camera_set_transform(camera, Transform( Basis(), Vector3(0,3,30 ) ) );
- vs->camera_set_perspective( camera, 60, 0.1, 1000);
-
+ vs->viewport_set_size(viewport, screen_size.x, screen_size.y);
+ vs->viewport_attach_to_screen(viewport, Rect2(Vector2(), screen_size));
+ vs->viewport_set_active(viewport, true);
+ vs->viewport_attach_camera(viewport, camera);
+ vs->viewport_set_scenario(viewport, scenario);
+ vs->camera_set_transform(camera, Transform(Basis(), Vector3(0, 3, 30)));
+ vs->camera_set_perspective(camera, 60, 0.1, 1000);
/*
RID lightaux = vs->light_create( VisualServer::LIGHT_OMNI );
@@ -193,44 +179,44 @@ public:
*/
RID lightaux;
- lightaux = vs->light_create( VisualServer::LIGHT_DIRECTIONAL );
+ lightaux = vs->light_create(VisualServer::LIGHT_DIRECTIONAL);
//vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,0.0) );
- vs->light_set_color( lightaux, Color(1.0,1.0,1.0) );
+ vs->light_set_color(lightaux, Color(1.0, 1.0, 1.0));
//vs->light_set_shadow( lightaux, true );
- light = vs->instance_create2( lightaux, scenario );
+ light = vs->instance_create2(lightaux, scenario);
Transform lla;
//lla.set_look_at(Vector3(),Vector3(1,-1,1),Vector3(0,1,0));
- lla.set_look_at(Vector3(),Vector3(-0.000000,-0.836026,-0.548690),Vector3(0,1,0));
+ lla.set_look_at(Vector3(), Vector3(-0.000000, -0.836026, -0.548690), Vector3(0, 1, 0));
- vs->instance_set_transform( light, lla );
+ vs->instance_set_transform(light, lla);
- lightaux = vs->light_create( VisualServer::LIGHT_OMNI );
+ lightaux = vs->light_create(VisualServer::LIGHT_OMNI);
//vs->light_set_color( lightaux, VisualServer::LIGHT_COLOR_AMBIENT, Color(0.0,0.0,1.0) );
- vs->light_set_color( lightaux, Color(1.0,1.0,0.0) );
- vs->light_set_param( lightaux, VisualServer::LIGHT_PARAM_RANGE, 4 );
- vs->light_set_param( lightaux, VisualServer::LIGHT_PARAM_ENERGY, 8 );
+ vs->light_set_color(lightaux, Color(1.0, 1.0, 0.0));
+ vs->light_set_param(lightaux, VisualServer::LIGHT_PARAM_RANGE, 4);
+ vs->light_set_param(lightaux, VisualServer::LIGHT_PARAM_ENERGY, 8);
//vs->light_set_shadow( lightaux, true );
//light = vs->instance_create( lightaux );
- ofs=0;
- quit=false;
+ ofs = 0;
+ quit = false;
}
virtual bool iteration(float p_time) {
- VisualServer *vs=VisualServer::get_singleton();
+ VisualServer *vs = VisualServer::get_singleton();
//Transform t;
//t.rotate(Vector3(0, 1, 0), ofs);
//t.translate(Vector3(0,0,20 ));
//vs->camera_set_transform(camera, t);
- ofs+=p_time*0.05;
+ ofs += p_time * 0.05;
//return quit;
- for(List<InstanceInfo>::Element *E=instances.front();E;E=E->next()) {
+ for (List<InstanceInfo>::Element *E = instances.front(); E; E = E->next()) {
- Transform pre( Basis(E->get().rot_axis, ofs), Vector3() );
- vs->instance_set_transform( E->get().instance, pre * E->get().base );
+ Transform pre(Basis(E->get().rot_axis, ofs), Vector3());
+ vs->instance_set_transform(E->get().instance, pre * E->get().base);
/*
if( !E->next() ) {
@@ -246,18 +232,12 @@ public:
return quit;
}
-
virtual void finish() {
-
}
-
};
+MainLoop *test() {
-MainLoop* test() {
-
- return memnew( TestMainLoop );
-
+ return memnew(TestMainLoop);
}
-
}
diff --git a/main/tests/test_render.h b/main/tests/test_render.h
index b6f6d81881..1dbf3c7f29 100644
--- a/main/tests/test_render.h
+++ b/main/tests/test_render.h
@@ -37,8 +37,7 @@
namespace TestRender {
-MainLoop* test();
-
+MainLoop *test();
}
#endif
diff --git a/main/tests/test_shader_lang.cpp b/main/tests/test_shader_lang.cpp
index 64c3853065..4ca09fe656 100644
--- a/main/tests/test_shader_lang.cpp
+++ b/main/tests/test_shader_lang.cpp
@@ -28,28 +28,25 @@
/*************************************************************************/
#include "test_shader_lang.h"
-
+#include "os/file_access.h"
#include "os/main_loop.h"
#include "os/os.h"
-#include "os/file_access.h"
+#include "print_string.h"
#include "scene/gui/control.h"
#include "scene/gui/text_edit.h"
-#include "print_string.h"
#include "servers/visual/shader_language.h"
//#include "drivers/gles2/shader_compiler_gles2.h"
-
typedef ShaderLanguage SL;
namespace TestShaderLang {
-
static String _mktab(int p_level) {
String tb;
- for(int i=0;i<p_level;i++) {
- tb+="\t";
+ for (int i = 0; i < p_level; i++) {
+ tb += "\t";
}
return tb;
@@ -62,11 +59,9 @@ static String _typestr(SL::DataType p_type) {
return "";
}
-
static String _prestr(SL::DataPrecision p_pres) {
-
- switch(p_pres) {
+ switch (p_pres) {
case SL::PRECISION_LOWP: return "lowp ";
case SL::PRECISION_MEDIUMP: return "mediump ";
case SL::PRECISION_HIGHP: return "highp ";
@@ -75,60 +70,56 @@ static String _prestr(SL::DataPrecision p_pres) {
return "";
}
-
static String _opstr(SL::Operator p_op) {
return ShaderLanguage::get_operator_text(p_op);
-
-
}
-
-static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value>& p_values) {
-
- switch(p_type) {
- case SL::TYPE_BOOL: return p_values[0].boolean?"true":"false";
- case SL::TYPE_BVEC2: return String()+"bvec2("+(p_values[0].boolean?"true":"false")+(p_values[1].boolean?"true":"false")+")";
- case SL::TYPE_BVEC3: return String()+"bvec3("+(p_values[0].boolean?"true":"false")+","+(p_values[1].boolean?"true":"false")+","+(p_values[2].boolean?"true":"false")+")";
- case SL::TYPE_BVEC4: return String()+"bvec4("+(p_values[0].boolean?"true":"false")+","+(p_values[1].boolean?"true":"false")+","+(p_values[2].boolean?"true":"false")+","+(p_values[3].boolean?"true":"false")+")";
- case SL::TYPE_INT: return rtos(p_values[0].sint);
- case SL::TYPE_IVEC2: return String()+"ivec2("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+")";
- case SL::TYPE_IVEC3: return String()+"ivec3("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+","+rtos(p_values[2].sint)+")";
- case SL::TYPE_IVEC4: return String()+"ivec4("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+","+rtos(p_values[2].sint)+","+rtos(p_values[3].sint)+")";
- case SL::TYPE_UINT: return rtos(p_values[0].real);
- case SL::TYPE_UVEC2: return String()+"uvec2("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+")";
- case SL::TYPE_UVEC3: return String()+"uvec3("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+")";
- case SL::TYPE_UVEC4: return String()+"uvec4("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+","+rtos(p_values[3].real)+")";
- case SL::TYPE_FLOAT: return rtos(p_values[0].real);
- case SL::TYPE_VEC2: return String()+"vec2("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+")";
- case SL::TYPE_VEC3: return String()+"vec3("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+")";
- case SL::TYPE_VEC4: return String()+"vec4("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+","+rtos(p_values[3].real)+")";
+static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value> &p_values) {
+
+ switch (p_type) {
+ case SL::TYPE_BOOL: return p_values[0].boolean ? "true" : "false";
+ case SL::TYPE_BVEC2: return String() + "bvec2(" + (p_values[0].boolean ? "true" : "false") + (p_values[1].boolean ? "true" : "false") + ")";
+ case SL::TYPE_BVEC3: return String() + "bvec3(" + (p_values[0].boolean ? "true" : "false") + "," + (p_values[1].boolean ? "true" : "false") + "," + (p_values[2].boolean ? "true" : "false") + ")";
+ case SL::TYPE_BVEC4: return String() + "bvec4(" + (p_values[0].boolean ? "true" : "false") + "," + (p_values[1].boolean ? "true" : "false") + "," + (p_values[2].boolean ? "true" : "false") + "," + (p_values[3].boolean ? "true" : "false") + ")";
+ case SL::TYPE_INT: return rtos(p_values[0].sint);
+ case SL::TYPE_IVEC2: return String() + "ivec2(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + ")";
+ case SL::TYPE_IVEC3: return String() + "ivec3(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + "," + rtos(p_values[2].sint) + ")";
+ case SL::TYPE_IVEC4: return String() + "ivec4(" + rtos(p_values[0].sint) + "," + rtos(p_values[1].sint) + "," + rtos(p_values[2].sint) + "," + rtos(p_values[3].sint) + ")";
+ case SL::TYPE_UINT: return rtos(p_values[0].real);
+ case SL::TYPE_UVEC2: return String() + "uvec2(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + ")";
+ case SL::TYPE_UVEC3: return String() + "uvec3(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + ")";
+ case SL::TYPE_UVEC4: return String() + "uvec4(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + "," + rtos(p_values[3].real) + ")";
+ case SL::TYPE_FLOAT: return rtos(p_values[0].real);
+ case SL::TYPE_VEC2: return String() + "vec2(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + ")";
+ case SL::TYPE_VEC3: return String() + "vec3(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + ")";
+ case SL::TYPE_VEC4: return String() + "vec4(" + rtos(p_values[0].real) + "," + rtos(p_values[1].real) + "," + rtos(p_values[2].real) + "," + rtos(p_values[3].real) + ")";
default: ERR_FAIL_V(String());
}
}
-static String dump_node_code(SL::Node *p_node,int p_level) {
+static String dump_node_code(SL::Node *p_node, int p_level) {
String code;
- switch(p_node->type) {
+ switch (p_node->type) {
case SL::Node::TYPE_SHADER: {
- SL::ShaderNode *pnode=(SL::ShaderNode*)p_node;
+ SL::ShaderNode *pnode = (SL::ShaderNode *)p_node;
- for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) {
+ for (Map<StringName, SL::ShaderNode::Uniform>::Element *E = pnode->uniforms.front(); E; E = E->next()) {
- String ucode="uniform ";
- ucode+=_prestr(E->get().precission);
- ucode+=_typestr(E->get().type);
- ucode+=" "+String(E->key());
+ String ucode = "uniform ";
+ ucode += _prestr(E->get().precission);
+ ucode += _typestr(E->get().type);
+ ucode += " " + String(E->key());
if (E->get().default_value.size()) {
- ucode+=" = "+get_constant_text(E->get().type,E->get().default_value);
+ ucode += " = " + get_constant_text(E->get().type, E->get().default_value);
}
- static const char*hint_name[SL::ShaderNode::Uniform::HINT_MAX]={
+ static const char *hint_name[SL::ShaderNode::Uniform::HINT_MAX] = {
"",
"color",
"range",
@@ -139,38 +130,36 @@ static String dump_node_code(SL::Node *p_node,int p_level) {
};
if (E->get().hint)
- ucode+=" : "+String(hint_name[E->get().hint]);
-
- code+=ucode+"\n";
+ ucode += " : " + String(hint_name[E->get().hint]);
+ code += ucode + "\n";
}
- for(Map<StringName,SL::ShaderNode::Varying>::Element *E=pnode->varyings.front();E;E=E->next()) {
-
- String vcode="varying ";
- vcode+=_prestr(E->get().precission);
- vcode+=_typestr(E->get().type);
- vcode+=" "+String(E->key());
+ for (Map<StringName, SL::ShaderNode::Varying>::Element *E = pnode->varyings.front(); E; E = E->next()) {
- code+=vcode+"\n";
+ String vcode = "varying ";
+ vcode += _prestr(E->get().precission);
+ vcode += _typestr(E->get().type);
+ vcode += " " + String(E->key());
+ code += vcode + "\n";
}
- for(int i=0;i<pnode->functions.size();i++) {
+ for (int i = 0; i < pnode->functions.size(); i++) {
- SL::FunctionNode *fnode=pnode->functions[i].function;
+ SL::FunctionNode *fnode = pnode->functions[i].function;
String header;
- header=_typestr(fnode->return_type)+" "+fnode->name+"(";
- for(int i=0;i<fnode->arguments.size();i++) {
+ header = _typestr(fnode->return_type) + " " + fnode->name + "(";
+ for (int i = 0; i < fnode->arguments.size(); i++) {
- if (i>0)
- header+=", ";
- header+=_prestr(fnode->arguments[i].precision)+_typestr(fnode->arguments[i].type)+" "+fnode->arguments[i].name;
+ if (i > 0)
+ header += ", ";
+ header += _prestr(fnode->arguments[i].precision) + _typestr(fnode->arguments[i].type) + " " + fnode->arguments[i].name;
}
- header+=")\n";
- code+=header;
- code+=dump_node_code(fnode->body,p_level+1);
+ header += ")\n";
+ code += header;
+ code += dump_node_code(fnode->body, p_level + 1);
}
//code+=dump_node_code(pnode->body,p_level);
@@ -179,44 +168,42 @@ static String dump_node_code(SL::Node *p_node,int p_level) {
} break;
case SL::Node::TYPE_BLOCK: {
- SL::BlockNode *bnode=(SL::BlockNode*)p_node;
+ SL::BlockNode *bnode = (SL::BlockNode *)p_node;
//variables
- code+=_mktab(p_level-1)+"{\n";
- for(Map<StringName,SL::BlockNode::Variable>::Element *E=bnode->variables.front();E;E=E->next()) {
+ code += _mktab(p_level - 1) + "{\n";
+ for (Map<StringName, SL::BlockNode::Variable>::Element *E = bnode->variables.front(); E; E = E->next()) {
- code+=_mktab(p_level)+_prestr(E->get().precision)+_typestr(E->get().type)+" "+E->key()+";\n";
+ code += _mktab(p_level) + _prestr(E->get().precision) + _typestr(E->get().type) + " " + E->key() + ";\n";
}
- for(int i=0;i<bnode->statements.size();i++) {
+ for (int i = 0; i < bnode->statements.size(); i++) {
- String scode = dump_node_code(bnode->statements[i],p_level);
+ String scode = dump_node_code(bnode->statements[i], p_level);
- if (bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW) {
- code+=scode; //use directly
+ if (bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type == SL::Node::TYPE_CONTROL_FLOW) {
+ code += scode; //use directly
} else {
- code+=_mktab(p_level)+scode+";\n";
+ code += _mktab(p_level) + scode + ";\n";
}
}
- code+=_mktab(p_level-1)+"}\n";
-
+ code += _mktab(p_level - 1) + "}\n";
} break;
case SL::Node::TYPE_VARIABLE: {
- SL::VariableNode *vnode=(SL::VariableNode*)p_node;
- code=vnode->name;
+ SL::VariableNode *vnode = (SL::VariableNode *)p_node;
+ code = vnode->name;
} break;
case SL::Node::TYPE_CONSTANT: {
- SL::ConstantNode *cnode=(SL::ConstantNode*)p_node;
- return get_constant_text(cnode->datatype,cnode->values);
+ SL::ConstantNode *cnode = (SL::ConstantNode *)p_node;
+ return get_constant_text(cnode->datatype, cnode->values);
} break;
case SL::Node::TYPE_OPERATOR: {
- SL::OperatorNode *onode=(SL::OperatorNode*)p_node;
-
+ SL::OperatorNode *onode = (SL::OperatorNode *)p_node;
- switch(onode->op) {
+ switch (onode->op) {
case SL::OP_ASSIGN:
case SL::OP_ASSIGN_ADD:
@@ -229,84 +216,79 @@ static String dump_node_code(SL::Node *p_node,int p_level) {
case SL::OP_ASSIGN_BIT_AND:
case SL::OP_ASSIGN_BIT_OR:
case SL::OP_ASSIGN_BIT_XOR:
- code=dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level);
+ code = dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level);
break;
case SL::OP_BIT_INVERT:
case SL::OP_NEGATE:
case SL::OP_NOT:
case SL::OP_DECREMENT:
case SL::OP_INCREMENT:
- code=_opstr(onode->op)+dump_node_code(onode->arguments[0],p_level);
+ code = _opstr(onode->op) + dump_node_code(onode->arguments[0], p_level);
break;
case SL::OP_POST_DECREMENT:
case SL::OP_POST_INCREMENT:
- code=dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op);
+ code = dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op);
break;
case SL::OP_CALL:
case SL::OP_CONSTRUCT:
- code=dump_node_code(onode->arguments[0],p_level)+"(";
- for(int i=1;i<onode->arguments.size();i++) {
- if (i>1)
- code+=", ";
- code+=dump_node_code(onode->arguments[i],p_level);
+ code = dump_node_code(onode->arguments[0], p_level) + "(";
+ for (int i = 1; i < onode->arguments.size(); i++) {
+ if (i > 1)
+ code += ", ";
+ code += dump_node_code(onode->arguments[i], p_level);
}
- code+=")";
+ code += ")";
break;
default: {
- code="("+dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")";
+ code = "(" + dump_node_code(onode->arguments[0], p_level) + _opstr(onode->op) + dump_node_code(onode->arguments[1], p_level) + ")";
break;
-
}
}
} break;
case SL::Node::TYPE_CONTROL_FLOW: {
- SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node;
- if (cfnode->flow_op==SL::FLOW_OP_IF) {
+ SL::ControlFlowNode *cfnode = (SL::ControlFlowNode *)p_node;
+ if (cfnode->flow_op == SL::FLOW_OP_IF) {
- code+=_mktab(p_level)+"if ("+dump_node_code(cfnode->expressions[0],p_level)+")\n";
- code+=dump_node_code(cfnode->blocks[0],p_level+1);
- if (cfnode->blocks.size()==2) {
+ code += _mktab(p_level) + "if (" + dump_node_code(cfnode->expressions[0], p_level) + ")\n";
+ code += dump_node_code(cfnode->blocks[0], p_level + 1);
+ if (cfnode->blocks.size() == 2) {
- code+=_mktab(p_level)+"else\n";
- code+=dump_node_code(cfnode->blocks[1],p_level+1);
+ code += _mktab(p_level) + "else\n";
+ code += dump_node_code(cfnode->blocks[1], p_level + 1);
}
-
- } else if (cfnode->flow_op==SL::FLOW_OP_RETURN) {
+ } else if (cfnode->flow_op == SL::FLOW_OP_RETURN) {
if (cfnode->blocks.size()) {
- code="return "+dump_node_code(cfnode->blocks[0],p_level);
+ code = "return " + dump_node_code(cfnode->blocks[0], p_level);
} else {
- code="return";
+ code = "return";
}
}
} break;
case SL::Node::TYPE_MEMBER: {
- SL::MemberNode *mnode=(SL::MemberNode*)p_node;
- code=dump_node_code(mnode->owner,p_level)+"."+mnode->name;
+ SL::MemberNode *mnode = (SL::MemberNode *)p_node;
+ code = dump_node_code(mnode->owner, p_level) + "." + mnode->name;
} break;
}
return code;
-
}
-static Error recreate_code(void *p_str,SL::ShaderNode *p_program) {
-
+static Error recreate_code(void *p_str, SL::ShaderNode *p_program) {
- String *str=(String*)p_str;
+ String *str = (String *)p_str;
- *str=dump_node_code(p_program,0);
+ *str = dump_node_code(p_program, 0);
return OK;
}
-
-MainLoop* test() {
+MainLoop *test() {
List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
@@ -318,7 +300,7 @@ MainLoop* test() {
String test = cmdlargs.back()->get();
- FileAccess *fa = FileAccess::open(test,FileAccess::READ);
+ FileAccess *fa = FileAccess::open(test, FileAccess::READ);
if (!fa) {
ERR_FAIL_V(NULL);
@@ -326,36 +308,34 @@ MainLoop* test() {
String code;
- while(true) {
+ while (true) {
CharType c = fa->get_8();
if (fa->eof_reached())
break;
- code+=c;
+ code += c;
}
SL sl;
- print_line("tokens:\n\n"+sl.token_debug(code));
+ print_line("tokens:\n\n" + sl.token_debug(code));
- Map<StringName,Map<StringName,SL::DataType> > dt;
- dt["fragment"]["ALBEDO"]=SL::TYPE_VEC3;
+ Map<StringName, Map<StringName, SL::DataType> > dt;
+ dt["fragment"]["ALBEDO"] = SL::TYPE_VEC3;
Set<String> rm;
rm.insert("popo");
- Error err = sl.compile(code,dt,rm);
+ Error err = sl.compile(code, dt, rm);
if (err) {
- print_line("Error at line: "+rtos(sl.get_error_line())+": "+sl.get_error_text());
+ print_line("Error at line: " + rtos(sl.get_error_line()) + ": " + sl.get_error_text());
return NULL;
} else {
String code;
- recreate_code(&code,sl.get_shader());
- print_line("code:\n\n"+code);
+ recreate_code(&code, sl.get_shader());
+ print_line("code:\n\n" + code);
}
return NULL;
}
-
-
}
diff --git a/main/tests/test_shader_lang.h b/main/tests/test_shader_lang.h
index aae047ce10..3a3797ecdc 100644
--- a/main/tests/test_shader_lang.h
+++ b/main/tests/test_shader_lang.h
@@ -33,8 +33,7 @@
namespace TestShaderLang {
-MainLoop* test();
-
+MainLoop *test();
}
#endif // TEST_SHADER_LANG_H
diff --git a/main/tests/test_sound.cpp b/main/tests/test_sound.cpp
index 095ce001ba..9683faf1e5 100644
--- a/main/tests/test_sound.cpp
+++ b/main/tests/test_sound.cpp
@@ -27,14 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "test_sound.h"
-#include "servers/visual_server.h"
-#include "os/main_loop.h"
#include "math_funcs.h"
+#include "os/main_loop.h"
+#include "servers/visual_server.h"
#include "io/resource_loader.h"
+#include "os/os.h"
#include "print_string.h"
#include "servers/audio_server.h"
-#include "os/os.h"
#if 0
namespace TestSound {
diff --git a/main/tests/test_sound.h b/main/tests/test_sound.h
index 167751bd1d..1246e3b9c5 100644
--- a/main/tests/test_sound.h
+++ b/main/tests/test_sound.h
@@ -33,8 +33,7 @@
namespace TestSound {
-MainLoop* test();
-
+MainLoop *test();
}
#endif // TEST_SOUND_H
diff --git a/main/tests/test_string.cpp b/main/tests/test_string.cpp
index ca7fdedcb8..41ec113845 100644
--- a/main/tests/test_string.cpp
+++ b/main/tests/test_string.cpp
@@ -29,9 +29,9 @@
#include "ustring.h"
#include <wchar.h>
//#include "math_funcs.h"
-#include <stdio.h>
-#include "os/os.h"
#include "core/io/ip_address.h"
+#include "os/os.h"
+#include <stdio.h>
#include "test_string.h"
@@ -44,10 +44,9 @@ bool test_1() {
String s = "Hello";
OS::get_singleton()->print("\tExpected: Hello\n");
- OS::get_singleton()->print("\tResulted: %ls\n",s.c_str());
-
- return (wcscmp(s.c_str(),L"Hello")==0);
+ OS::get_singleton()->print("\tResulted: %ls\n", s.c_str());
+ return (wcscmp(s.c_str(), L"Hello") == 0);
}
bool test_2() {
@@ -58,10 +57,9 @@ bool test_2() {
String t = s;
OS::get_singleton()->print("\tExpected: Dolly\n");
- OS::get_singleton()->print("\tResulted: %ls\n",t.c_str());
-
- return (wcscmp(t.c_str(),L"Dolly")==0);
+ OS::get_singleton()->print("\tResulted: %ls\n", t.c_str());
+ return (wcscmp(t.c_str(), L"Dolly") == 0);
}
bool test_3() {
@@ -72,10 +70,9 @@ bool test_3() {
String t(s);
OS::get_singleton()->print("\tExpected: Sheep\n");
- OS::get_singleton()->print("\tResulted: %ls\n",t.c_str());
-
- return (wcscmp(t.c_str(),L"Sheep")==0);
+ OS::get_singleton()->print("\tResulted: %ls\n", t.c_str());
+ return (wcscmp(t.c_str(), L"Sheep") == 0);
}
bool test_4() {
@@ -85,10 +82,9 @@ bool test_4() {
String s(L"Give me");
OS::get_singleton()->print("\tExpected: Give me\n");
- OS::get_singleton()->print("\tResulted: %ls\n",s.c_str());
-
- return (wcscmp(s.c_str(),L"Give me")==0);
+ OS::get_singleton()->print("\tResulted: %ls\n", s.c_str());
+ return (wcscmp(s.c_str(), L"Give me") == 0);
}
bool test_5() {
@@ -98,89 +94,81 @@ bool test_5() {
String s(L"Wool");
OS::get_singleton()->print("\tExpected: Wool\n");
- OS::get_singleton()->print("\tResulted: %ls\n",s.c_str());
-
- return (wcscmp(s.c_str(),L"Wool")==0);
+ OS::get_singleton()->print("\tResulted: %ls\n", s.c_str());
+ return (wcscmp(s.c_str(), L"Wool") == 0);
}
bool test_6() {
OS::get_singleton()->print("\n\nTest 6: comparisons (equal)\n");
-
- String s="Test Compare";
+ String s = "Test Compare";
OS::get_singleton()->print("\tComparing to \"Test Compare\"\n");
- if (! ( s=="Test Compare" ) )
+ if (!(s == "Test Compare"))
return false;
- if (! ( s==L"Test Compare" ) )
+ if (!(s == L"Test Compare"))
return false;
- if (! ( s==String("Test Compare") ) )
+ if (!(s == String("Test Compare")))
return false;
return true;
-
}
bool test_7() {
OS::get_singleton()->print("\n\nTest 7: comparisons (unequal)\n");
-
- String s="Test Compare";
+ String s = "Test Compare";
OS::get_singleton()->print("\tComparing to \"Test Compare\"\n");
- if (! ( s!="Peanut" ) )
+ if (!(s != "Peanut"))
return false;
- if (! ( s!=L"Coconut" ) )
+ if (!(s != L"Coconut"))
return false;
- if (! ( s!=String("Butter") ) )
+ if (!(s != String("Butter")))
return false;
return true;
-
}
bool test_8() {
OS::get_singleton()->print("\n\nTest 8: comparisons (operator<)\n");
-
- String s="Bees";
+ String s = "Bees";
OS::get_singleton()->print("\tComparing to \"Bees\"\n");
- if ( ! (s < "Elephant") )
+ if (!(s < "Elephant"))
return false;
- if ( s < L"Amber" )
+ if (s < L"Amber")
return false;
- if ( s < String("Beatrix") )
+ if (s < String("Beatrix"))
return false;
return true;
-
}
bool test_9() {
OS::get_singleton()->print("\n\nTest 9: Concatenation\n");
-
String s;
- s+="Have";
- s+=' ';
- s+='a';
- s+=String(" ");
+ s += "Have";
+ s += ' ';
+ s += 'a';
+ s += String(" ");
s = s + L"Nice";
s = s + " ";
s = s + String("Day");
@@ -188,14 +176,13 @@ bool test_9() {
OS::get_singleton()->print("\tComparing to \"Have a Nice Day\"\n");
return (s == "Have a Nice Day");
-
}
bool test_10() {
OS::get_singleton()->print("\n\nTest 10: Misc funcs (size/length/empty/etc)\n");
- if (! String("").empty())
+ if (!String("").empty())
return false;
if (String("Mellon").size() != 7)
@@ -205,44 +192,39 @@ bool test_10() {
return false;
return true;
-
}
-
bool test_11() {
OS::get_singleton()->print("\n\nTest 11: Operator[]\n");
- String a="Kugar Sane";
+ String a = "Kugar Sane";
- a[0]='S';
- a[6]='C';
+ a[0] = 'S';
+ a[6] = 'C';
if (a != "Sugar Cane")
return false;
- if (a[1]!='u')
+ if (a[1] != 'u')
return false;
return true;
-
}
bool test_12() {
OS::get_singleton()->print("\n\nTest 12: case functions\n");
-
- String a="MoMoNgA";
+ String a = "MoMoNgA";
if (a.to_upper() != "MOMONGA")
return false;
- if (a.nocasecmp_to("momonga")!=0)
+ if (a.nocasecmp_to("momonga") != 0)
return false;
return true;
-
}
bool test_13() {
@@ -251,16 +233,15 @@ bool test_13() {
/* how can i embed UTF in here? */
- static const CharType ustr[] = { 0x304A , 0x360F, 0x3088, 0x3046, 0 };
+ static const CharType ustr[] = { 0x304A, 0x360F, 0x3088, 0x3046, 0 };
//static const wchar_t ustr[] = { 'P', 0xCE, 'p',0xD3, 0 };
- String s=ustr;
-
- OS::get_singleton()->print("\tUnicode: %ls\n",ustr);
- s.parse_utf8( s.utf8().get_data() );
- OS::get_singleton()->print("\tConvert/Parse UTF8: %ls\n",s.c_str());
+ String s = ustr;
- return (s==ustr);
+ OS::get_singleton()->print("\tUnicode: %ls\n", ustr);
+ s.parse_utf8(s.utf8().get_data());
+ OS::get_singleton()->print("\tConvert/Parse UTF8: %ls\n", s.c_str());
+ return (s == ustr);
}
bool test_14() {
@@ -268,195 +249,180 @@ bool test_14() {
OS::get_singleton()->print("\n\nTest 14: ASCII\n");
String s = L"Primero Leche";
- OS::get_singleton()->print("\tAscii: %s\n",s.ascii().get_data());
-
- String t=s.ascii().get_data();
- return (s==t);
+ OS::get_singleton()->print("\tAscii: %s\n", s.ascii().get_data());
+ String t = s.ascii().get_data();
+ return (s == t);
}
bool test_15() {
OS::get_singleton()->print("\n\nTest 15: substr\n");
- String s="Killer Baby";
- OS::get_singleton()->print("\tsubstr(3,4) of \"%ls\" is \"%ls\"\n",s.c_str(),s.substr(3,4).c_str());
-
- return (s.substr(3,4)=="ler ");
+ String s = "Killer Baby";
+ OS::get_singleton()->print("\tsubstr(3,4) of \"%ls\" is \"%ls\"\n", s.c_str(), s.substr(3, 4).c_str());
+ return (s.substr(3, 4) == "ler ");
}
bool test_16() {
OS::get_singleton()->print("\n\nTest 16: find\n");
- String s="Pretty Woman";
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
- OS::get_singleton()->print("\t\"tty\" is at %i pos.\n",s.find("tty"));
- OS::get_singleton()->print("\t\"Revenge of the Monster Truck\" is at %i pos.\n",s.find("Revenge of the Monster Truck"));
+ String s = "Pretty Woman";
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
+ OS::get_singleton()->print("\t\"tty\" is at %i pos.\n", s.find("tty"));
+ OS::get_singleton()->print("\t\"Revenge of the Monster Truck\" is at %i pos.\n", s.find("Revenge of the Monster Truck"));
- if (s.find("tty")!=3)
+ if (s.find("tty") != 3)
return false;
- if (s.find("Revenge of the Monster Truck")!=-1)
+ if (s.find("Revenge of the Monster Truck") != -1)
return false;
return true;
-
}
bool test_17() {
OS::get_singleton()->print("\n\nTest 17: find no case\n");
- String s="Pretty Whale";
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
- OS::get_singleton()->print("\t\"WHA\" is at %i pos.\n",s.findn("WHA"));
- OS::get_singleton()->print("\t\"Revenge of the Monster SawFish\" is at %i pos.\n",s.findn("Revenge of the Monster Truck"));
+ String s = "Pretty Whale";
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
+ OS::get_singleton()->print("\t\"WHA\" is at %i pos.\n", s.findn("WHA"));
+ OS::get_singleton()->print("\t\"Revenge of the Monster SawFish\" is at %i pos.\n", s.findn("Revenge of the Monster Truck"));
- if (s.findn("WHA")!=7)
+ if (s.findn("WHA") != 7)
return false;
- if (s.findn("Revenge of the Monster SawFish")!=-1)
+ if (s.findn("Revenge of the Monster SawFish") != -1)
return false;
return true;
-
}
bool test_18() {
OS::get_singleton()->print("\n\nTest 18: find no case\n");
- String s="Pretty Whale";
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
- OS::get_singleton()->print("\t\"WHA\" is at %i pos.\n",s.findn("WHA"));
- OS::get_singleton()->print("\t\"Revenge of the Monster SawFish\" is at %i pos.\n",s.findn("Revenge of the Monster Truck"));
+ String s = "Pretty Whale";
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
+ OS::get_singleton()->print("\t\"WHA\" is at %i pos.\n", s.findn("WHA"));
+ OS::get_singleton()->print("\t\"Revenge of the Monster SawFish\" is at %i pos.\n", s.findn("Revenge of the Monster Truck"));
- if (s.findn("WHA")!=7)
+ if (s.findn("WHA") != 7)
return false;
- if (s.findn("Revenge of the Monster SawFish")!=-1)
+ if (s.findn("Revenge of the Monster SawFish") != -1)
return false;
return true;
-
}
bool test_19() {
OS::get_singleton()->print("\n\nTest 19: Search & replace\n");
- String s="Happy Birthday, Anna!";
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
+ String s = "Happy Birthday, Anna!";
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
- s=s.replace("Birthday","Halloween");
- OS::get_singleton()->print("\tReplaced Birthday/Halloween: %ls.\n",s.c_str());
-
- return (s=="Happy Halloween, Anna!");
+ s = s.replace("Birthday", "Halloween");
+ OS::get_singleton()->print("\tReplaced Birthday/Halloween: %ls.\n", s.c_str());
+ return (s == "Happy Halloween, Anna!");
}
bool test_20() {
OS::get_singleton()->print("\n\nTest 20: Insertion\n");
- String s="Who is Frederic?";
-
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
- s=s.insert( s.find("?")," Chopin" );
- OS::get_singleton()->print("\tInserted Chopin: %ls.\n",s.c_str());
+ String s = "Who is Frederic?";
- return (s=="Who is Frederic Chopin?");
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
+ s = s.insert(s.find("?"), " Chopin");
+ OS::get_singleton()->print("\tInserted Chopin: %ls.\n", s.c_str());
+ return (s == "Who is Frederic Chopin?");
}
bool test_21() {
OS::get_singleton()->print("\n\nTest 21: Number -> String\n");
- OS::get_singleton()->print("\tPi is %f\n",33.141593);
- OS::get_singleton()->print("\tPi String is %ls\n",String::num(3.141593).c_str());
-
- return String::num(3.141593)=="3.141593";
+ OS::get_singleton()->print("\tPi is %f\n", 33.141593);
+ OS::get_singleton()->print("\tPi String is %ls\n", String::num(3.141593).c_str());
+ return String::num(3.141593) == "3.141593";
}
bool test_22() {
OS::get_singleton()->print("\n\nTest 22: String -> Int\n");
- static const char* nums[4]={ "1237461283", "- 22", "0", " - 1123412" };
- static const int num[4]={ 1237461283, -22, 0, -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++) {
- OS::get_singleton()->print("\tString: \"%s\" as Int is %i\n",nums[i],String(nums[i]).to_int());
+ for (int i = 0; i < 4; i++) {
+ OS::get_singleton()->print("\tString: \"%s\" as Int is %i\n", nums[i], String(nums[i]).to_int());
- if (String(nums[i]).to_int()!=num[i])
+ if (String(nums[i]).to_int() != num[i])
return false;
}
return true;
-
}
bool test_23() {
OS::get_singleton()->print("\n\nTest 23: String -> Float\n");
- 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 };
+ 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++) {
- OS::get_singleton()->print("\tString: \"%s\" as Float is %f\n",nums[i],String(nums[i]).to_double());
+ for (int i = 0; i < 4; i++) {
+ OS::get_singleton()->print("\tString: \"%s\" as Float is %f\n", nums[i], String(nums[i]).to_double());
- if ( ABS(String(nums[i]).to_double()-num[i])>0.00001)
+ if (ABS(String(nums[i]).to_double() - num[i]) > 0.00001)
return false;
}
return true;
-
}
-
bool test_24() {
OS::get_singleton()->print("\n\nTest 24: Slicing\n");
- String s="Mars,Jupiter,Saturn,Uranus";
-
- const char*slices[4]={"Mars","Jupiter","Saturn","Uranus"};
+ String s = "Mars,Jupiter,Saturn,Uranus";
- OS::get_singleton()->print("\tSlicing \"%ls\" by \"%s\"..\n",s.c_str(),",");
+ const char *slices[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
- for (int i=0;i<s.get_slice_count(",");i++) {
+ OS::get_singleton()->print("\tSlicing \"%ls\" by \"%s\"..\n", s.c_str(), ",");
- OS::get_singleton()->print("\t\t%i- %ls\n",i+1,s.get_slice(",",i).c_str());
+ for (int i = 0; i < s.get_slice_count(","); i++) {
+ OS::get_singleton()->print("\t\t%i- %ls\n", i + 1, s.get_slice(",", i).c_str());
- if (s.get_slice(",",i)!=slices[i])
+ if (s.get_slice(",", i) != slices[i])
return false;
}
return true;
-
}
bool test_25() {
OS::get_singleton()->print("\n\nTest 25: Erasing\n");
- String s="Josephine is such a cute girl!";
+ String s = "Josephine is such a cute girl!";
- OS::get_singleton()->print("\tString: %ls\n",s.c_str());
+ OS::get_singleton()->print("\tString: %ls\n", s.c_str());
OS::get_singleton()->print("\tRemoving \"cute\"\n");
- s.erase(s.find("cute "),String("cute ").length());
- OS::get_singleton()->print("\tResult: %ls\n",s.c_str());
-
-
- return (s=="Josephine is such a girl!");
+ s.erase(s.find("cute "), String("cute ").length());
+ OS::get_singleton()->print("\tResult: %ls\n", s.c_str());
+ return (s == "Josephine is such a girl!");
}
bool test_26() {
@@ -466,8 +432,8 @@ bool test_26() {
};
struct test_27_data {
- char const * data;
- char const * begin;
+ char const *data;
+ char const *begin;
bool expected;
};
@@ -475,13 +441,13 @@ bool test_27() {
OS::get_singleton()->print("\n\nTest 27: begins_with\n");
test_27_data tc[] = {
- {"res://foobar", "res://", true},
- {"res", "res://", false},
- {"abc", "abc", true}
+ { "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) {
+ for (size_t i = 0; state && i < count; ++i) {
String s = tc[i].data;
state = s.begins_with(tc[i].begin) == tc[i].expected;
if (state) {
@@ -496,7 +462,6 @@ bool test_27() {
return state;
};
-
bool test_28() {
OS::get_singleton()->print("\n\nTest 28: sprintf\n");
@@ -925,22 +890,22 @@ TestFunc test_funcs[] = {
};
-MainLoop* test() {
+MainLoop *test() {
/** A character length != wchar_t may be forced, so the tests wont work */
- ERR_FAIL_COND_V( sizeof(CharType) != sizeof(wchar_t), NULL );
+ ERR_FAIL_COND_V(sizeof(CharType) != sizeof(wchar_t), NULL);
- int count=0;
- int passed=0;
+ int count = 0;
+ int passed = 0;
- while(true) {
+ while (true) {
if (!test_funcs[count])
break;
- bool pass=test_funcs[count]();
+ bool pass = test_funcs[count]();
if (pass)
passed++;
- OS::get_singleton()->print("\t%s\n",pass?"PASS":"FAILED");
+ OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED");
count++;
}
@@ -954,5 +919,4 @@ MainLoop* test() {
return NULL;
}
-
}
diff --git a/main/tests/test_string.h b/main/tests/test_string.h
index 12df7f126f..c8116a0c53 100644
--- a/main/tests/test_string.h
+++ b/main/tests/test_string.h
@@ -29,16 +29,12 @@
#ifndef TEST_STRING_H
#define TEST_STRING_H
-#include "ustring.h"
#include "os/main_loop.h"
+#include "ustring.h"
namespace TestString {
-MainLoop* test();
-
+MainLoop *test();
}
-
#endif
-
-
diff --git a/modules/cscript/godot_c.cpp b/modules/cscript/godot_c.cpp
index 85ee28d6d2..f754f2bb21 100644
--- a/modules/cscript/godot_c.cpp
+++ b/modules/cscript/godot_c.cpp
@@ -27,4 +27,3 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "godot_c.h"
-
diff --git a/modules/cscript/godot_c.h b/modules/cscript/godot_c.h
index 97a63a439f..e38de1e489 100644
--- a/modules/cscript/godot_c.h
+++ b/modules/cscript/godot_c.h
@@ -33,7 +33,6 @@
extern "C" {
#endif
-
#if defined(GDAPI_BUILT_IN) || !defined(WINDOWS_ENABLED)
#define GDAPI
#elif defined(GDAPI_EXPORTS)
@@ -42,10 +41,8 @@ extern "C" {
#define GDAPI __declspec(dllimport)
#endif
-
#define GODOT_API_VERSION 1
-
typedef int godot_bool;
#define GODOT_FALSE 0
@@ -53,7 +50,6 @@ typedef int godot_bool;
////// Image
-
#define GODOT_IMAGE_FORMAT_GRAYSCALE 0
#define GODOT_IMAGE_FORMAT_INTENSITY 1
#define GODOT_IMAGE_FORMAT_GRAYSCALE_ALPHA 2
@@ -77,11 +73,11 @@ typedef int godot_bool;
#define GODOT_IMAGE_FORMAT_ATC_ALPHA_EXPLICIT 20
#define GODOT_IMAGE_FORMAT_ATC_ALPHA_INTERPOLATED 21
-typedef void* godot_image;
+typedef void *godot_image;
godot_image GDAPI godot_image_create_empty();
-godot_image GDAPI godot_image_create(int p_width,int p_height,int p_format,int p_use_mipmaps);
-godot_image GDAPI godot_image_create_with_data(int p_width,int p_height,int p_format,int p_use_mipmaps,unsigned char* p_buffer);
+godot_image GDAPI godot_image_create(int p_width, int p_height, int p_format, int p_use_mipmaps);
+godot_image GDAPI godot_image_create_with_data(int p_width, int p_height, int p_format, int p_use_mipmaps, unsigned char *p_buffer);
int GDAPI godot_image_get_width(godot_image p_image);
int GDAPI godot_image_get_height(godot_image p_image);
int GDAPI godot_image_get_format(godot_image p_image);
@@ -89,10 +85,9 @@ int GDAPI godot_image_get_mipmap_count(godot_image p_image);
godot_image GDAPI godot_image_copy(godot_image p_image);
void GDAPI godot_image_free(godot_image p_image);
-
////// RID
-typedef void* godot_rid;
+typedef void *godot_rid;
godot_rid GDAPI godot_rid_create();
godot_rid GDAPI godot_rid_copy(godot_rid p_rid);
@@ -100,37 +95,36 @@ void GDAPI godot_rid_free(godot_rid p_rid);
////// Variant (forward declared)
-typedef void* godot_variant;
-
+typedef void *godot_variant;
////// Dictionary
-typedef void* godot_dictionary;
+typedef void *godot_dictionary;
godot_dictionary GDAPI godot_dictionary_create();
-void GDAPI godot_dictionary_has(godot_dictionary p_dictionary,godot_variant p_key);
-godot_variant GDAPI godot_dictionary_get(godot_dictionary p_dictionary,godot_variant p_key);
-void GDAPI godot_dictionary_insert(godot_dictionary p_dictionary,godot_variant p_key,godot_variant p_value);
-void GDAPI godot_dictionary_remove(godot_dictionary p_dictionary,godot_variant p_key);
+void GDAPI godot_dictionary_has(godot_dictionary p_dictionary, godot_variant p_key);
+godot_variant GDAPI godot_dictionary_get(godot_dictionary p_dictionary, godot_variant p_key);
+void GDAPI godot_dictionary_insert(godot_dictionary p_dictionary, godot_variant p_key, godot_variant p_value);
+void GDAPI godot_dictionary_remove(godot_dictionary p_dictionary, godot_variant p_key);
void GDAPI godot_dictionary_clear(godot_dictionary p_dictionary);
int GDAPI godot_dictionary_get_size(godot_dictionary p_dictionary);
-void GDAPI godot_dictionary_get_keys(godot_dictionary p_dictionary,godot_variant* p_keys);
+void GDAPI godot_dictionary_get_keys(godot_dictionary p_dictionary, godot_variant *p_keys);
godot_dictionary GDAPI godot_dictionary_copy(godot_dictionary p_dictionary);
void GDAPI godot_dictionary_free(godot_dictionary p_dictionary);
////// Array
-typedef void* godot_array;
+typedef void *godot_array;
godot_array GDAPI godot_array_create();
-godot_variant GDAPI godot_array_get(godot_array p_array,int p_index);
-void GDAPI godot_array_set(godot_array p_array,int p_index,godot_variant p_value);
-void GDAPI godot_array_resize(godot_array p_array,int p_size);
-void GDAPI godot_array_insert(godot_array p_array,int p_position,godot_variant p_value);
-void GDAPI godot_array_remove(godot_array p_array,int p_position);
+godot_variant GDAPI godot_array_get(godot_array p_array, int p_index);
+void GDAPI godot_array_set(godot_array p_array, int p_index, godot_variant p_value);
+void GDAPI godot_array_resize(godot_array p_array, int p_size);
+void GDAPI godot_array_insert(godot_array p_array, int p_position, godot_variant p_value);
+void GDAPI godot_array_remove(godot_array p_array, int p_position);
void GDAPI godot_array_clear(godot_array p_array);
int GDAPI godot_array_get_size(godot_array p_array);
-int GDAPI godot_array_find(godot_array p_array,godot_variant p_value,int p_from_pos=-1);
+int GDAPI godot_array_find(godot_array p_array, godot_variant p_value, int p_from_pos = -1);
godot_array GDAPI godot_array_copy(godot_array p_array);
void GDAPI godot_array_free(godot_array p_array);
@@ -143,9 +137,9 @@ void GDAPI godot_array_free(godot_array p_array);
#define INPUT_EVENT_BUTTON_WHEEL_DOWN 5
#define INPUT_EVENT_BUTTON_WHEEL_LEFT 6
#define INPUT_EVENT_BUTTON_WHEEL_RIGHT 7
-#define INPUT_EVENT_BUTTON_MASK_LEFT (1<<(INPUT_EVENT_BUTTON_LEFT-1))
-#define INPUT_EVENT_BUTTON_MASK_RIGHT (1<<(INPUT_EVENT_BUTTON_RIGHT-1))
-#define INPUT_EVENT_BUTTON_MASK_MIDDLE (1<<(INPUT_EVENT_BUTTON_MIDDLE-1))
+#define INPUT_EVENT_BUTTON_MASK_LEFT (1 << (INPUT_EVENT_BUTTON_LEFT - 1))
+#define INPUT_EVENT_BUTTON_MASK_RIGHT (1 << (INPUT_EVENT_BUTTON_RIGHT - 1))
+#define INPUT_EVENT_BUTTON_MASK_MIDDLE (1 << (INPUT_EVENT_BUTTON_MIDDLE - 1))
#define INPUT_EVENT_TYPE_NONE 0
#define INPUT_EVENT_TYPE_KEY 1
@@ -157,8 +151,7 @@ void GDAPI godot_array_free(godot_array p_array);
#define INPUT_EVENT_TYPE_SCREEN_DRAG 7
#define INPUT_EVENT_TYPE_ACTION 8
-typedef void* godot_input_event;
-
+typedef void *godot_input_event;
godot_input_event GDAPI godot_input_event_create();
godot_input_event GDAPI godot_input_event_copy(godot_input_event p_input_event);
@@ -201,7 +194,6 @@ int GDAPI godot_input_event_joypad_button_get_button_index(godot_input_event p_e
godot_bool GDAPI godot_input_event_joypad_button_is_pressed(godot_input_event p_event);
float GDAPI godot_input_event_joypad_button_get_pressure(godot_input_event p_event);
-
int GDAPI godot_input_event_screen_touch_get_index(godot_input_event p_event);
int GDAPI godot_input_event_screen_touch_get_x(godot_input_event p_event);
int GDAPI godot_input_event_screen_touch_get_y(godot_input_event p_event);
@@ -215,49 +207,47 @@ int GDAPI godot_input_event_screen_drag_get_relative_y(godot_input_event p_event
int GDAPI godot_input_event_screen_drag_get_speed_x(godot_input_event p_event);
int GDAPI godot_input_event_screen_drag_get_speed_y(godot_input_event p_event);
-int GDAPI godot_input_event_is_action(godot_input_event p_event,char *p_action);
-int GDAPI godot_input_event_is_action_pressed(godot_input_event p_event,char *p_action);
+int GDAPI godot_input_event_is_action(godot_input_event p_event, char *p_action);
+int GDAPI godot_input_event_is_action_pressed(godot_input_event p_event, char *p_action);
////// ByteArray
-typedef void* godot_byte_array;
+typedef void *godot_byte_array;
godot_byte_array GDAPI godot_byte_array_create();
godot_byte_array GDAPI godot_byte_array_copy(godot_byte_array p_byte_array);
void GDAPI godot_byte_array_free(godot_byte_array p_byte_array);
int GDAPI godot_byte_array_get_size(godot_byte_array p_byte_array);
-unsigned char GDAPI godot_byte_array_get(godot_byte_array p_byte_array,int p_index);
-void GDAPI godot_byte_array_set(godot_byte_array p_byte_array,int p_index,unsigned char p_value);
-void GDAPI godot_byte_array_remove(godot_byte_array p_byte_array,int p_index);
+unsigned char GDAPI godot_byte_array_get(godot_byte_array p_byte_array, int p_index);
+void GDAPI godot_byte_array_set(godot_byte_array p_byte_array, int p_index, unsigned char p_value);
+void GDAPI godot_byte_array_remove(godot_byte_array p_byte_array, int p_index);
void GDAPI godot_byte_array_clear(godot_byte_array p_byte_array);
-typedef void* godot_byte_array_lock;
+typedef void *godot_byte_array_lock;
godot_byte_array_lock GDAPI godot_byte_array_get_lock(godot_byte_array p_byte_array);
unsigned char GDAPI *godot_byte_array_lock_get_pointer(godot_byte_array_lock p_byte_array_lock);
void GDAPI godot_byte_array_lock_free(godot_byte_array_lock p_byte_array_lock);
-
-godot_image GDAPI godot_image_create_with_array(int p_width,int p_height,int p_format,int p_use_mipmaps,godot_array p_array);
+godot_image GDAPI godot_image_create_with_array(int p_width, int p_height, int p_format, int p_use_mipmaps, godot_array p_array);
godot_byte_array GDAPI godot_image_get_data(godot_image p_image);
-
////// IntArray
-typedef void* godot_int_array;
+typedef void *godot_int_array;
godot_int_array GDAPI godot_int_array_create();
godot_int_array GDAPI godot_int_array_copy(godot_int_array p_int_array);
void GDAPI godot_int_array_free(godot_int_array p_int_array);
int GDAPI godot_int_array_get_size(godot_int_array p_int_array);
-int GDAPI godot_int_array_get(godot_int_array p_int_array,int p_index);
-void GDAPI godot_int_array_set(godot_int_array p_int_array,int p_index,int p_value);
-void GDAPI godot_int_array_remove(godot_int_array p_int_array,int p_index);
+int GDAPI godot_int_array_get(godot_int_array p_int_array, int p_index);
+void GDAPI godot_int_array_set(godot_int_array p_int_array, int p_index, int p_value);
+void GDAPI godot_int_array_remove(godot_int_array p_int_array, int p_index);
void GDAPI godot_int_array_clear(godot_int_array p_int_array);
-typedef void* godot_int_array_lock;
+typedef void *godot_int_array_lock;
godot_int_array_lock GDAPI godot_int_array_get_lock(godot_int_array p_int_array);
int GDAPI *godot_int_array_lock_get_pointer(godot_int_array_lock p_int_array_lock);
@@ -265,44 +255,41 @@ void GDAPI godot_int_array_lock_free(godot_int_array_lock p_int_array_lock);
////// RealArray
-typedef void* godot_real_array;
-
+typedef void *godot_real_array;
godot_real_array GDAPI godot_real_array_create();
godot_real_array GDAPI godot_real_array_copy(godot_real_array p_real_array);
void GDAPI godot_real_array_free(godot_real_array p_real_array);
int GDAPI godot_real_array_get_size(godot_real_array p_real_array);
-float GDAPI godot_real_array_get(godot_real_array p_real_array,int p_index);
-void GDAPI godot_real_array_set(godot_real_array p_real_array,int p_index,float p_value);
-void GDAPI godot_real_array_remove(godot_real_array p_real_array,int p_index);
+float GDAPI godot_real_array_get(godot_real_array p_real_array, int p_index);
+void GDAPI godot_real_array_set(godot_real_array p_real_array, int p_index, float p_value);
+void GDAPI godot_real_array_remove(godot_real_array p_real_array, int p_index);
void GDAPI godot_real_array_clear(godot_real_array p_real_array);
-typedef void* godot_real_array_lock;
+typedef void *godot_real_array_lock;
godot_real_array_lock GDAPI godot_real_array_get_lock(godot_real_array p_real_array);
float GDAPI *godot_real_array_lock_get_pointer(godot_real_array_lock p_real_array_lock);
void GDAPI godot_real_array_lock_free(godot_real_array_lock p_real_array_lock);
-
////// StringArray
-typedef void* godot_string_array;
-
+typedef void *godot_string_array;
godot_string_array GDAPI godot_string_array_create();
godot_string_array GDAPI godot_string_array_copy(godot_string_array p_string_array);
void GDAPI godot_string_array_free(godot_string_array p_string_array);
int GDAPI godot_string_array_get_size(godot_string_array p_string_array);
-int GDAPI godot_string_array_get(godot_string_array p_string_array,int p_index,unsigned char* p_string,int p_max_len);
-void GDAPI godot_string_array_set(godot_string_array p_string_array,int p_index,unsigned char *p_string);
-void GDAPI godot_string_array_remove(godot_string_array p_string_array,int p_index);
+int GDAPI godot_string_array_get(godot_string_array p_string_array, int p_index, unsigned char *p_string, int p_max_len);
+void GDAPI godot_string_array_set(godot_string_array p_string_array, int p_index, unsigned char *p_string);
+void GDAPI godot_string_array_remove(godot_string_array p_string_array, int p_index);
void GDAPI godot_string_array_clear(godot_string_array p_string_array);
////// Vector2Array
-typedef void* godot_vector2_array;
+typedef void *godot_vector2_array;
godot_vector2_array GDAPI godot_vector2_array_create();
godot_vector2_array GDAPI godot_vector2_array_copy(godot_vector2_array p_vector2_array);
@@ -310,13 +297,12 @@ void GDAPI godot_vector2_array_free(godot_vector2_array p_vector2_array);
int GDAPI godot_vector2_array_get_size(godot_vector2_array p_vector2_array);
int GDAPI godot_vector2_array_get_stride(godot_vector2_array p_vector2_array);
-void GDAPI godot_vector2_array_get(godot_vector2_array p_vector2_array,int p_index,float* p_vector2);
-void GDAPI godot_vector2_array_set(godot_vector2_array p_vector2_array,int p_index,float *p_vector2);
-void GDAPI godot_vector2_array_remove(godot_vector2_array p_vector2_array,int p_index);
+void GDAPI godot_vector2_array_get(godot_vector2_array p_vector2_array, int p_index, float *p_vector2);
+void GDAPI godot_vector2_array_set(godot_vector2_array p_vector2_array, int p_index, float *p_vector2);
+void GDAPI godot_vector2_array_remove(godot_vector2_array p_vector2_array, int p_index);
void GDAPI godot_vector2_array_clear(godot_vector2_array p_vector2_array);
-
-typedef void* godot_vector2_array_lock;
+typedef void *godot_vector2_array_lock;
godot_vector2_array_lock GDAPI godot_vector2_array_get_lock(godot_vector2_array p_vector2_array);
float GDAPI *godot_vector2_array_lock_get_pointer(godot_vector2_array_lock p_vector2_array_lock);
@@ -324,7 +310,7 @@ void GDAPI godot_vector2_array_lock_free(godot_vector2_array_lock p_vector2_arra
////// Vector3Array
-typedef void* godot_vector3_array;
+typedef void *godot_vector3_array;
godot_vector3_array GDAPI godot_vector3_array_create();
godot_vector3_array GDAPI godot_vector3_array_copy(godot_vector3_array p_vector3_array);
@@ -332,13 +318,12 @@ void GDAPI godot_vector3_array_free(godot_vector3_array p_vector3_array);
int GDAPI godot_vector3_array_get_size(godot_vector3_array p_vector3_array);
int GDAPI godot_vector3_array_get_stride(godot_vector3_array p_vector3_array);
-void GDAPI godot_vector3_array_get(godot_vector3_array p_vector3_array,int p_index,float* p_vector3);
-void GDAPI godot_vector3_array_set(godot_vector3_array p_vector3_array,int p_index,float *p_vector3);
-void GDAPI godot_vector3_array_remove(godot_vector3_array p_vector3_array,int p_index);
+void GDAPI godot_vector3_array_get(godot_vector3_array p_vector3_array, int p_index, float *p_vector3);
+void GDAPI godot_vector3_array_set(godot_vector3_array p_vector3_array, int p_index, float *p_vector3);
+void GDAPI godot_vector3_array_remove(godot_vector3_array p_vector3_array, int p_index);
void GDAPI godot_vector3_array_clear(godot_vector3_array p_vector3_array);
-
-typedef void* godot_vector3_array_lock;
+typedef void *godot_vector3_array_lock;
godot_vector3_array_lock GDAPI godot_vector3_array_get_lock(godot_vector3_array p_vector3_array);
float GDAPI *godot_vector3_array_lock_get_pointer(godot_vector3_array_lock p_vector3_array_lock);
@@ -346,7 +331,7 @@ void GDAPI godot_vector3_array_lock_free(godot_vector3_array_lock p_vector3_arra
////// ColorArray
-typedef void* godot_color_array;
+typedef void *godot_color_array;
godot_color_array GDAPI godot_color_array_create();
godot_color_array GDAPI godot_color_array_copy(godot_color_array p_color_array);
@@ -354,19 +339,17 @@ void GDAPI godot_color_array_free(godot_color_array p_color_array);
int GDAPI godot_color_array_get_size(godot_color_array p_color_array);
int GDAPI godot_color_array_get_stride(godot_color_array p_color_array);
-void GDAPI godot_color_array_get(godot_color_array p_color_array,int p_index,float* p_color);
-void GDAPI godot_color_array_set(godot_color_array p_color_array,int p_index,float *p_color);
-void GDAPI godot_color_array_remove(godot_color_array p_color_array,int p_index);
+void GDAPI godot_color_array_get(godot_color_array p_color_array, int p_index, float *p_color);
+void GDAPI godot_color_array_set(godot_color_array p_color_array, int p_index, float *p_color);
+void GDAPI godot_color_array_remove(godot_color_array p_color_array, int p_index);
void GDAPI godot_color_array_clear(godot_color_array p_color_array);
-
-typedef void* godot_color_array_lock;
+typedef void *godot_color_array_lock;
godot_color_array_lock GDAPI godot_color_array_get_lock(godot_color_array p_color_array);
float GDAPI *godot_color_array_lock_get_pointer(godot_color_array_lock p_color_array_lock);
void GDAPI godot_color_array_lock_free(godot_color_array_lock p_color_array_lock);
-
////// Instance (forward declared)
typedef void *godot_instance;
@@ -409,52 +392,52 @@ godot_variant *godot_variant_new();
int GDAPI godot_variant_get_type(godot_variant p_variant);
void GDAPI godot_variant_set_null(godot_variant p_variant);
-void GDAPI godot_variant_set_bool(godot_variant p_variant,godot_bool p_bool);
-void GDAPI godot_variant_set_int(godot_variant p_variant,int p_int);
-void GDAPI godot_variant_set_float(godot_variant p_variant,int p_float);
-void GDAPI godot_variant_set_string(godot_variant p_variant,char *p_string);
-void GDAPI godot_variant_set_vector2(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_rect2(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_vector3(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_matrix32(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_plane(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_aabb(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_matrix3(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_transform(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_color(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_set_image(godot_variant p_variant,godot_image *p_image);
-void GDAPI godot_variant_set_node_path(godot_variant p_variant,char *p_path);
-void GDAPI godot_variant_set_rid(godot_variant p_variant,char *p_path);
-void GDAPI godot_variant_set_instance(godot_variant p_variant,godot_instance p_instance);
-void GDAPI godot_variant_set_input_event(godot_variant p_variant,godot_input_event p_instance);
-void GDAPI godot_variant_set_dictionary(godot_variant p_variant,godot_dictionary p_dictionary);
-void GDAPI godot_variant_set_array(godot_variant p_variant,godot_array p_array);
-void GDAPI godot_variant_set_byte_array(godot_variant p_variant,godot_byte_array p_array);
-void GDAPI godot_variant_set_int_array(godot_variant p_variant,godot_byte_array p_array);
-void GDAPI godot_variant_set_string_array(godot_variant p_variant,godot_string_array p_array);
-void GDAPI godot_variant_set_vector2_array(godot_variant p_variant,godot_vector2_array p_array);
-void GDAPI godot_variant_set_vector3_array(godot_variant p_variant,godot_vector3_array p_array);
-void GDAPI godot_variant_set_color_array(godot_variant p_variant,godot_color_array p_array);
+void GDAPI godot_variant_set_bool(godot_variant p_variant, godot_bool p_bool);
+void GDAPI godot_variant_set_int(godot_variant p_variant, int p_int);
+void GDAPI godot_variant_set_float(godot_variant p_variant, int p_float);
+void GDAPI godot_variant_set_string(godot_variant p_variant, char *p_string);
+void GDAPI godot_variant_set_vector2(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_rect2(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_vector3(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_matrix32(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_plane(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_aabb(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_matrix3(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_transform(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_color(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_set_image(godot_variant p_variant, godot_image *p_image);
+void GDAPI godot_variant_set_node_path(godot_variant p_variant, char *p_path);
+void GDAPI godot_variant_set_rid(godot_variant p_variant, char *p_path);
+void GDAPI godot_variant_set_instance(godot_variant p_variant, godot_instance p_instance);
+void GDAPI godot_variant_set_input_event(godot_variant p_variant, godot_input_event p_instance);
+void GDAPI godot_variant_set_dictionary(godot_variant p_variant, godot_dictionary p_dictionary);
+void GDAPI godot_variant_set_array(godot_variant p_variant, godot_array p_array);
+void GDAPI godot_variant_set_byte_array(godot_variant p_variant, godot_byte_array p_array);
+void GDAPI godot_variant_set_int_array(godot_variant p_variant, godot_byte_array p_array);
+void GDAPI godot_variant_set_string_array(godot_variant p_variant, godot_string_array p_array);
+void GDAPI godot_variant_set_vector2_array(godot_variant p_variant, godot_vector2_array p_array);
+void GDAPI godot_variant_set_vector3_array(godot_variant p_variant, godot_vector3_array p_array);
+void GDAPI godot_variant_set_color_array(godot_variant p_variant, godot_color_array p_array);
godot_bool GDAPI godot_variant_get_bool(godot_variant p_variant);
int GDAPI godot_variant_get_int(godot_variant p_variant);
float GDAPI godot_variant_get_float(godot_variant p_variant);
-int GDAPI godot_variant_get_string(godot_variant p_variant,char *p_string,int p_bufsize);
-void GDAPI godot_variant_get_vector2(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_rect2(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_vector3(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_matrix32(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_plane(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_aabb(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_matrix3(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_transform(godot_variant p_variant,float *p_elems);
-void GDAPI godot_variant_get_color(godot_variant p_variant,float *p_elems);
+int GDAPI godot_variant_get_string(godot_variant p_variant, char *p_string, int p_bufsize);
+void GDAPI godot_variant_get_vector2(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_rect2(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_vector3(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_matrix32(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_plane(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_aabb(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_matrix3(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_transform(godot_variant p_variant, float *p_elems);
+void GDAPI godot_variant_get_color(godot_variant p_variant, float *p_elems);
godot_image GDAPI *godot_variant_get_image(godot_variant p_variant);
-int GDAPI godot_variant_get_node_path(godot_variant p_variant,char *p_path, int p_bufsize);
+int GDAPI godot_variant_get_node_path(godot_variant p_variant, char *p_path, int p_bufsize);
godot_rid GDAPI godot_variant_get_rid(godot_variant p_variant);
godot_instance GDAPI godot_variant_get_instance(godot_variant p_variant);
-void GDAPI godot_variant_get_input_event(godot_variant p_variant,godot_input_event);
-void GDAPI godot_variant_get_dictionary(godot_variant p_variant,godot_dictionary);
+void GDAPI godot_variant_get_input_event(godot_variant p_variant, godot_input_event);
+void GDAPI godot_variant_get_dictionary(godot_variant p_variant, godot_dictionary);
godot_array GDAPI godot_variant_get_array(godot_variant p_variant);
godot_byte_array GDAPI godot_variant_get_byte_array(godot_variant p_variant);
godot_byte_array GDAPI godot_variant_get_int_array(godot_variant p_variant);
@@ -463,7 +446,6 @@ godot_vector2_array GDAPI godot_variant_get_vector2_array(godot_variant p_varian
godot_vector3_array GDAPI godot_variant_get_vector3_array(godot_variant p_variant);
godot_color_array GDAPI godot_variant_get_color_array(godot_variant p_variant);
-
void GDAPI godot_variant_delete(godot_variant p_variant);
////// Class
@@ -471,17 +453,16 @@ void GDAPI godot_variant_delete(godot_variant p_variant);
char GDAPI **godot_class_get_list(); //get list of classes in array to array of strings, must be freed, use godot_list_free()
-int GDAPI godot_class_get_base(char* p_class,char *p_base,int p_max_len);
-int GDAPI godot_class_get_name(char* p_class,char *p_base,int p_max_len);
-
-char GDAPI **godot_class_get_method_list(char* p_class); //free with godot_list_free()
-int GDAPI godot_class_method_get_argument_count(char* p_class,char *p_method);
-int GDAPI godot_class_method_get_argument_type(char* p_class,char *p_method,int p_argument);
-godot_variant GDAPI godot_class_method_get_argument_default_value(char* p_class,char *p_method,int p_argument);
+int GDAPI godot_class_get_base(char *p_class, char *p_base, int p_max_len);
+int GDAPI godot_class_get_name(char *p_class, char *p_base, int p_max_len);
-char GDAPI **godot_class_get_constant_list(char* p_class); //free with godot_list_free()
-int GDAPI godot_class_constant_get_value(char* p_class,char *p_constant);
+char GDAPI **godot_class_get_method_list(char *p_class); //free with godot_list_free()
+int GDAPI godot_class_method_get_argument_count(char *p_class, char *p_method);
+int GDAPI godot_class_method_get_argument_type(char *p_class, char *p_method, int p_argument);
+godot_variant GDAPI godot_class_method_get_argument_default_value(char *p_class, char *p_method, int p_argument);
+char GDAPI **godot_class_get_constant_list(char *p_class); //free with godot_list_free()
+int GDAPI godot_class_constant_get_value(char *p_class, char *p_constant);
////// Instance
@@ -491,8 +472,8 @@ typedef int godot_call_error;
#define GODOT_CALL_ERROR_WRONG_ARGUMENTS
#define GODOT_CALL_ERROR_INVALID_INSTANCE
-godot_instance GDAPI godot_instance_new(char* p_class);
-int GDAPI godot_instance_get_class(godot_instance p_instance,char* p_class,int p_max_len);
+godot_instance GDAPI godot_instance_new(char *p_class);
+int GDAPI godot_instance_get_class(godot_instance p_instance, char *p_class, int p_max_len);
typedef struct {
char *name;
@@ -501,34 +482,32 @@ typedef struct {
int usage;
} godot_property_info;
-godot_call_error GDAPI godot_instance_call(godot_instance p_instance, char* p_method, ...);
-godot_call_error GDAPI godot_instance_call_ret(godot_instance p_instance, godot_variant r_return, char* p_method, ...);
-godot_bool GDAPI godot_instance_set(godot_instance p_instance, char* p_prop,godot_variant p_value);
-godot_variant GDAPI godot_instance_get(godot_instance p_instance, char* p_prop);
-
+godot_call_error GDAPI godot_instance_call(godot_instance p_instance, char *p_method, ...);
+godot_call_error GDAPI godot_instance_call_ret(godot_instance p_instance, godot_variant r_return, char *p_method, ...);
+godot_bool GDAPI godot_instance_set(godot_instance p_instance, char *p_prop, godot_variant p_value);
+godot_variant GDAPI godot_instance_get(godot_instance p_instance, char *p_prop);
#define GODOT_PROPERTY_HINT_NONE 0 ///< no hint provided.
-#define GODOT_PROPERTY_HINT_RANGE 1///< hint_text = "min,max,step,slider; //slider is optional"
-#define GODOT_PROPERTY_HINT_EXP_RANGE 2///< hint_text = "min,max,step", exponential edit
-#define GODOT_PROPERTY_HINT_ENUM 3///< hint_text= "val1,val2,val3,etc"
-#define GODOT_PROPERTY_HINT_EXP_EASING 4/// exponential easing funciton (Math::ease)
-#define GODOT_PROPERTY_HINT_LENGTH 5///< hint_text= "length" (as integer)
+#define GODOT_PROPERTY_HINT_RANGE 1 ///< hint_text = "min,max,step,slider; //slider is optional"
+#define GODOT_PROPERTY_HINT_EXP_RANGE 2 ///< hint_text = "min,max,step", exponential edit
+#define GODOT_PROPERTY_HINT_ENUM 3 ///< hint_text= "val1,val2,val3,etc"
+#define GODOT_PROPERTY_HINT_EXP_EASING 4 /// exponential easing funciton (Math::ease)
+#define GODOT_PROPERTY_HINT_LENGTH 5 ///< hint_text= "length" (as integer)
#define GODOT_PROPERTY_HINT_SPRITE_FRAME 6
-#define GODOT_PROPERTY_HINT_KEY_ACCEL 7///< hint_text= "length" (as integer)
-#define GODOT_PROPERTY_HINT_FLAGS 8///< hint_text= "flag1,flag2,etc" (as bit flags)
+#define GODOT_PROPERTY_HINT_KEY_ACCEL 7 ///< hint_text= "length" (as integer)
+#define GODOT_PROPERTY_HINT_FLAGS 8 ///< hint_text= "flag1,flag2,etc" (as bit flags)
#define GODOT_PROPERTY_HINT_ALL_FLAGS 9
#define GODOT_PROPERTY_HINT_FILE 10 ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc,"
#define GODOT_PROPERTY_HINT_DIR 11 ///< a directort path must be passed
-#define GODOT_PROPERTY_HINT_GLOBAL_FILE 12///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc,"
+#define GODOT_PROPERTY_HINT_GLOBAL_FILE 12 ///< a file path must be passed, hint_text (optionally) is a filter "*.png,*.wav,*.doc,"
#define GODOT_PROPERTY_HINT_GLOBAL_DIR 13 ///< a directort path must be passed
-#define GODOT_PROPERTY_HINT_RESOURCE_TYPE 14///< a resource object type
-#define GODOT_PROPERTY_HINT_MULTILINE_TEXT 15///< used for string properties that can contain multiple lines
-#define GODOT_PROPERTY_HINT_COLOR_NO_ALPHA 16///< used for ignoring alpha component when editing a color
+#define GODOT_PROPERTY_HINT_RESOURCE_TYPE 14 ///< a resource object type
+#define GODOT_PROPERTY_HINT_MULTILINE_TEXT 15 ///< used for string properties that can contain multiple lines
+#define GODOT_PROPERTY_HINT_COLOR_NO_ALPHA 16 ///< used for ignoring alpha component when editing a color
#define GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSY 17
#define GODOT_PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS 18
#define GODOT_PROPERTY_HINT_OBJECT_ID 19
-
#define GODOT_PROPERTY_USAGE_STORAGE 1
#define GODOT_PROPERTY_USAGE_EDITOR 2
#define GODOT_PROPERTY_USAGE_NETWORK 4
@@ -546,51 +525,43 @@ godot_variant GDAPI godot_instance_get(godot_instance p_instance, char* p_prop);
#define GODOT_PROPERTY_USAGE_STORE_IF_NULL 16384
#define GODOT_PROPERTY_USAGE_ANIMATE_AS_TRIGGER 32768
-#define GODOT_PROPERTY_USAGE_DEFAULT GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_EDITOR|GODOT_PROPERTY_USAGE_NETWORK
-#define GODOT_PROPERTY_USAGE_DEFAULT_INTL GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_EDITOR|GODOT_PROPERTY_USAGE_NETWORK|GODOT_PROPERTY_USAGE_INTERNATIONALIZED
-#define GODOT_PROPERTY_USAGE_NOEDITOR GODOT_PROPERTY_USAGE_STORAGE|GODOT_PROPERTY_USAGE_NETWORK
-
+#define GODOT_PROPERTY_USAGE_DEFAULT GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK
+#define GODOT_PROPERTY_USAGE_DEFAULT_INTL GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_EDITOR | GODOT_PROPERTY_USAGE_NETWORK | GODOT_PROPERTY_USAGE_INTERNATIONALIZED
+#define GODOT_PROPERTY_USAGE_NOEDITOR GODOT_PROPERTY_USAGE_STORAGE | GODOT_PROPERTY_USAGE_NETWORK
godot_property_info GDAPI **godot_instance_get_property_list(godot_instance p_instance);
-void GDAPI godot_instance_free_property_list(godot_instance p_instance,godot_property_info** p_list);
-
-
+void GDAPI godot_instance_free_property_list(godot_instance p_instance, godot_property_info **p_list);
void GDAPI godot_list_free(char **p_name); //helper to free all the class list
-
////// Script API
-typedef void* (godot_script_instance_func)(godot_instance); //passed an instance, return a pointer to your userdata
-typedef void (godot_script_free_func)(godot_instance,void*); //passed an instance, please free your userdata
-
-void GDAPI godot_script_register(char* p_base,char* p_name,godot_script_instance_func p_instance_func,godot_script_free_func p_free_func);
-void GDAPI godot_script_unregister(char* p_name);
+typedef void *(godot_script_instance_func)(godot_instance); //passed an instance, return a pointer to your userdata
+typedef void(godot_script_free_func)(godot_instance, void *); //passed an instance, please free your userdata
-typedef GDAPI godot_variant (godot_script_func)(godot_instance,void*,godot_variant*,int); //instance,userdata,arguments,argument count. Return something or NULL. Arguments must not be freed.
+void GDAPI godot_script_register(char *p_base, char *p_name, godot_script_instance_func p_instance_func, godot_script_free_func p_free_func);
+void GDAPI godot_script_unregister(char *p_name);
+typedef GDAPI godot_variant(godot_script_func)(godot_instance, void *, godot_variant *, int); //instance,userdata,arguments,argument count. Return something or NULL. Arguments must not be freed.
-void GDAPI godot_script_add_function(char* p_name,char* p_function_name,godot_script_func p_func);
-void GDAPI godot_script_add_validated_function(char* p_name,char* p_function_name,godot_script_func p_func,int* p_arg_types,int p_arg_count,godot_variant* p_default_args,int p_default_arg_count);
+void GDAPI godot_script_add_function(char *p_name, char *p_function_name, godot_script_func p_func);
+void GDAPI godot_script_add_validated_function(char *p_name, char *p_function_name, godot_script_func p_func, int *p_arg_types, int p_arg_count, godot_variant *p_default_args, int p_default_arg_count);
-typedef void (godot_set_property_func)(godot_instance,void*,godot_variant); //instance,userdata,value. Value must not be freed.
-typedef godot_variant (godot_get_property_func)(godot_instance,void*); //instance,userdata. Return a value or NULL.
-
-void GDAPI godot_script_add_property(char* p_name,char* p_path,godot_set_property_func p_set_func,godot_get_property_func p_get_func);
-void GDAPI godot_script_add_listed_property(char* p_name,char* p_path,godot_set_property_func p_set_func,godot_get_property_func p_get_func,int p_type,int p_hint,char* p_hint_string,int p_usage);
+typedef void(godot_set_property_func)(godot_instance, void *, godot_variant); //instance,userdata,value. Value must not be freed.
+typedef godot_variant(godot_get_property_func)(godot_instance, void *); //instance,userdata. Return a value or NULL.
+void GDAPI godot_script_add_property(char *p_name, char *p_path, godot_set_property_func p_set_func, godot_get_property_func p_get_func);
+void GDAPI godot_script_add_listed_property(char *p_name, char *p_path, godot_set_property_func p_set_func, godot_get_property_func p_get_func, int p_type, int p_hint, char *p_hint_string, int p_usage);
////// System Functions
//using these will help Godot track how much memory is in use in debug mode
void GDAPI *godot_alloc(int p_bytes);
-void GDAPI *godot_realloc(void* p_ptr,int p_bytes);
-void GDAPI godot_free(void* p_ptr);
-
+void GDAPI *godot_realloc(void *p_ptr, int p_bytes);
+void GDAPI godot_free(void *p_ptr);
#ifdef __cplusplus
}
#endif
-
#endif // GODOT_C_H
diff --git a/modules/cscript/register_types.cpp b/modules/cscript/register_types.cpp
index d2101bbd49..2477bc51e2 100644
--- a/modules/cscript/register_types.cpp
+++ b/modules/cscript/register_types.cpp
@@ -28,10 +28,7 @@
/*************************************************************************/
#include "register_types.h"
-
void register_cscript_types() {
-
}
void unregister_cscript_types() {
-
}
diff --git a/modules/dds/register_types.cpp b/modules/dds/register_types.cpp
index 917305f543..d0eaf3f995 100644
--- a/modules/dds/register_types.cpp
+++ b/modules/dds/register_types.cpp
@@ -34,7 +34,7 @@ static ResourceFormatDDS *resource_loader_dds = NULL;
void register_dds_types() {
- resource_loader_dds = memnew( ResourceFormatDDS );
+ resource_loader_dds = memnew(ResourceFormatDDS);
ResourceLoader::add_resource_format_loader(resource_loader_dds);
}
diff --git a/modules/dds/texture_loader_dds.cpp b/modules/dds/texture_loader_dds.cpp
index 600cae991e..9c976179fa 100644
--- a/modules/dds/texture_loader_dds.cpp
+++ b/modules/dds/texture_loader_dds.cpp
@@ -29,18 +29,17 @@
#include "texture_loader_dds.h"
#include "os/file_access.h"
-
enum {
- DDS_MAGIC=0x20534444,
- DDSD_CAPS=0x00000001,
- DDSD_PIXELFORMAT=0x00001000,
- DDSD_PITCH=0x00000008,
- DDSD_LINEARSIZE=0x00080000,
- DDSD_MIPMAPCOUNT=0x00020000,
- DDPF_FOURCC=0x00000004,
- DDPF_ALPHAPIXELS=0x00000001,
- DDPF_INDEXED=0x00000020,
- DDPF_RGB=0x00000040,
+ DDS_MAGIC = 0x20534444,
+ DDSD_CAPS = 0x00000001,
+ DDSD_PIXELFORMAT = 0x00001000,
+ DDSD_PITCH = 0x00000008,
+ DDSD_LINEARSIZE = 0x00080000,
+ DDSD_MIPMAPCOUNT = 0x00020000,
+ DDPF_FOURCC = 0x00000004,
+ DDPF_ALPHAPIXELS = 0x00000001,
+ DDPF_INDEXED = 0x00000020,
+ DDPF_RGB = 0x00000040,
};
enum DDSFormat {
@@ -72,41 +71,39 @@ struct DDSFormatInfo {
Image::Format format;
};
-
-static const DDSFormatInfo dds_format_info[DDS_MAX]={
- {"DXT1",true,false,4,8,Image::FORMAT_DXT1},
- {"DXT3",true,false,4,16,Image::FORMAT_DXT3},
- {"DXT5",true,false,4,16,Image::FORMAT_DXT5},
- {"ATI1",true,false,4,8,Image::FORMAT_ATI1},
- {"ATI2",true,false,4,16,Image::FORMAT_ATI2},
- {"BGRA8",false,false,1,4,Image::FORMAT_RGBA8},
- {"BGR8",false,false,1,3,Image::FORMAT_RGB8},
- {"RGBA8",false,false,1,4,Image::FORMAT_RGBA8},
- {"RGB8",false,false,1,3,Image::FORMAT_RGB8},
- {"BGR5A1",false,false,1,2,Image::FORMAT_RGBA8},
- {"BGR565",false,false,1,2,Image::FORMAT_RGB8},
- {"BGR10A2",false,false,1,4,Image::FORMAT_RGBA8},
- {"GRAYSCALE",false,false,1,1,Image::FORMAT_L8},
- {"GRAYSCALE_ALPHA",false,false,1,2,Image::FORMAT_LA8}
+static const DDSFormatInfo dds_format_info[DDS_MAX] = {
+ { "DXT1", true, false, 4, 8, Image::FORMAT_DXT1 },
+ { "DXT3", true, false, 4, 16, Image::FORMAT_DXT3 },
+ { "DXT5", true, false, 4, 16, Image::FORMAT_DXT5 },
+ { "ATI1", true, false, 4, 8, Image::FORMAT_ATI1 },
+ { "ATI2", true, false, 4, 16, Image::FORMAT_ATI2 },
+ { "BGRA8", false, false, 1, 4, Image::FORMAT_RGBA8 },
+ { "BGR8", false, false, 1, 3, Image::FORMAT_RGB8 },
+ { "RGBA8", false, false, 1, 4, Image::FORMAT_RGBA8 },
+ { "RGB8", false, false, 1, 3, Image::FORMAT_RGB8 },
+ { "BGR5A1", false, false, 1, 2, Image::FORMAT_RGBA8 },
+ { "BGR565", false, false, 1, 2, Image::FORMAT_RGB8 },
+ { "BGR10A2", false, false, 1, 4, Image::FORMAT_RGBA8 },
+ { "GRAYSCALE", false, false, 1, 1, Image::FORMAT_L8 },
+ { "GRAYSCALE_ALPHA", false, false, 1, 2, Image::FORMAT_LA8 }
};
-
-RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatDDS::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
return RES();
FileAccessRef fref(f);
if (r_error)
- *r_error=ERR_FILE_CORRUPT;
+ *r_error = ERR_FILE_CORRUPT;
- ERR_EXPLAIN("Unable to open DDS texture file: "+p_path);
- ERR_FAIL_COND_V(err!=OK,RES());
+ ERR_EXPLAIN("Unable to open DDS texture file: " + p_path);
+ ERR_FAIL_COND_V(err != OK, RES());
uint32_t magic = f->get_32();
uint32_t hsize = f->get_32();
@@ -118,18 +115,17 @@ 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)) {
+ if (magic != DDS_MAGIC || hsize != 124 || !(flags & DDSD_PIXELFORMAT) || !(flags & DDSD_CAPS)) {
- ERR_EXPLAIN("Invalid or Unsupported DDS texture file: "+p_path);
+ ERR_EXPLAIN("Invalid or Unsupported DDS texture file: " + p_path);
ERR_FAIL_V(RES());
}
-
/* uint32_t format_size = */ f->get_32();
uint32_t format_flags = f->get_32();
uint32_t format_fourcc = f->get_32();
@@ -155,258 +151,249 @@ RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path,
//printf("rmask: %x gmask: %x, bmask: %x, amask: %x\n",format_red_mask,format_green_mask,format_blue_mask,format_alpha_mask);
//must avoid this later
- while(f->get_pos()<128)
+ while (f->get_pos() < 128)
f->get_8();
-
DDSFormat dds_format;
- if (format_flags&DDPF_FOURCC && format_fourcc==0x31545844) { //'1TXD'
+ if (format_flags & DDPF_FOURCC && format_fourcc == 0x31545844) { //'1TXD'
- dds_format=DDS_DXT1;
- } else if (format_flags&DDPF_FOURCC && format_fourcc==0x33545844) { //'3TXD'
+ dds_format = DDS_DXT1;
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x33545844) { //'3TXD'
- dds_format=DDS_DXT3;
+ dds_format = DDS_DXT3;
- } else if (format_flags&DDPF_FOURCC && format_fourcc==0x35545844) { //'5TXD'
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x35545844) { //'5TXD'
- dds_format=DDS_DXT5;
- } else if (format_flags&DDPF_FOURCC && format_fourcc==0x31495441) { //'1ITA'
+ dds_format = DDS_DXT5;
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x31495441) { //'1ITA'
- dds_format=DDS_ATI1;
- } else if (format_flags&DDPF_FOURCC && format_fourcc==0x32495441) { //'2ITA'
+ dds_format = DDS_ATI1;
+ } else if (format_flags & DDPF_FOURCC && format_fourcc == 0x32495441) { //'2ITA'
- dds_format=DDS_ATI2;
+ dds_format = DDS_ATI2;
- } 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) {
+ } 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_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_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_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;
+ 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) {
+ } 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_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_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_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;
+ } 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_LUMINANCE_ALPHA;
+ } else if (format_flags & DDPF_INDEXED && format_rgb_bits == 8) {
- dds_format=DDS_BGR565;
+ 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_EXPLAIN("Unrecognized or Unsupported color layout in DDS: "+p_path);
+ 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_EXPLAIN("Unrecognized or Unsupported color layout in DDS: " + p_path);
ERR_FAIL_V(RES());
-
}
- if (!(flags&DDSD_MIPMAPCOUNT))
- mipmaps=1;
+ if (!(flags & DDSD_MIPMAPCOUNT))
+ mipmaps = 1;
//print_line("found format: "+String(dds_format_info[dds_format].name));
PoolVector<uint8_t> src_data;
- const DDSFormatInfo &info=dds_format_info[dds_format];
+ const DDSFormatInfo &info = dds_format_info[dds_format];
uint32_t w = width;
uint32_t h = height;
-
if (info.compressed) {
//compressed bc
- uint32_t size = MAX( info.divisor, w )/info.divisor * MAX( info.divisor, h )/info.divisor * info.block_size;
- ERR_FAIL_COND_V( size!=pitch, RES() );
- ERR_FAIL_COND_V( !(flags&DDSD_LINEARSIZE), RES() );
+ uint32_t size = MAX(info.divisor, w) / info.divisor * MAX(info.divisor, h) / info.divisor * info.block_size;
+ ERR_FAIL_COND_V(size != pitch, RES());
+ ERR_FAIL_COND_V(!(flags & DDSD_LINEARSIZE), RES());
- for(uint32_t i=1;i<mipmaps;i++) {
+ 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;
+ 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;
//printf("%i x %i - block: %i\n",w,h,bsize);
- size+= bsize;
+ size += bsize;
}
src_data.resize(size);
PoolVector<uint8_t>::Write wb = src_data.write();
- f->get_buffer(wb.ptr(),size);
- wb=PoolVector<uint8_t>::Write();
+ f->get_buffer(wb.ptr(), size);
+ wb = PoolVector<uint8_t>::Write();
} else if (info.palette) {
//indexed
- ERR_FAIL_COND_V( !(flags&DDSD_PITCH), RES());
- ERR_FAIL_COND_V( format_rgb_bits!=8, RES() );
+ ERR_FAIL_COND_V(!(flags & DDSD_PITCH), RES());
+ ERR_FAIL_COND_V(format_rgb_bits != 8, RES());
- uint32_t size = pitch*height;
- ERR_FAIL_COND_V( size != width*height * info.block_size, RES());
+ uint32_t size = pitch * height;
+ ERR_FAIL_COND_V(size != width * height * info.block_size, RES());
- uint8_t pallete[256*4];
- f->get_buffer(pallete,256*4);
+ uint8_t pallete[256 * 4];
+ f->get_buffer(pallete, 256 * 4);
- int colsize=3;
- for(int i=0;i<256;i++) {
+ int colsize = 3;
+ for (int i = 0; i < 256; i++) {
- if (pallete[i*4+3]<255)
- colsize=4;
+ if (pallete[i * 4 + 3] < 255)
+ colsize = 4;
}
int w = width;
int h = height;
- for(uint32_t i=1;i<mipmaps;i++) {
+ for (uint32_t i = 1; i < mipmaps; i++) {
- w=(w+1)>>1;
- h=(h+1)>>1;
- size+= w*h*info.block_size;
+ w = (w + 1) >> 1;
+ h = (h + 1) >> 1;
+ size += w * h * info.block_size;
}
- src_data.resize(size + 256*colsize );
+ src_data.resize(size + 256 * colsize);
PoolVector<uint8_t>::Write wb = src_data.write();
- f->get_buffer(wb.ptr(),size);
+ f->get_buffer(wb.ptr(), size);
- for(int i=0;i<256;i++) {
+ for (int i = 0; i < 256; i++) {
- int dst_ofs = size+i*colsize;
- int src_ofs = i*4;
- wb[dst_ofs+0]=pallete[src_ofs+2];
- wb[dst_ofs+1]=pallete[src_ofs+1];
- wb[dst_ofs+2]=pallete[src_ofs+0];
- if (colsize==4)
- wb[dst_ofs+3]=pallete[src_ofs+3];
+ int dst_ofs = size + i * colsize;
+ int src_ofs = i * 4;
+ wb[dst_ofs + 0] = pallete[src_ofs + 2];
+ wb[dst_ofs + 1] = pallete[src_ofs + 1];
+ wb[dst_ofs + 2] = pallete[src_ofs + 0];
+ if (colsize == 4)
+ wb[dst_ofs + 3] = pallete[src_ofs + 3];
}
-
- wb=PoolVector<uint8_t>::Write();
+ wb = PoolVector<uint8_t>::Write();
} else {
//uncompressed generic...
- uint32_t size = width*height*info.block_size;
-
+ uint32_t size = width * height * info.block_size;
- for(uint32_t i=1;i<mipmaps;i++) {
+ for (uint32_t i = 1; i < mipmaps; i++) {
- w=(w+1)>>1;
- h=(h+1)>>1;
- size+= w*h*info.block_size;
+ w = (w + 1) >> 1;
+ h = (h + 1) >> 1;
+ size += w * h * info.block_size;
}
- if (dds_format==DDS_BGR565)
- size=size*3/2;
- else if (dds_format==DDS_BGR5A1)
- size=size*2;
+ if (dds_format == DDS_BGR565)
+ size = size * 3 / 2;
+ else if (dds_format == DDS_BGR5A1)
+ size = size * 2;
src_data.resize(size);
PoolVector<uint8_t>::Write wb = src_data.write();
- f->get_buffer(wb.ptr(),size);
-
+ f->get_buffer(wb.ptr(), size);
- switch(dds_format) {
+ switch (dds_format) {
case DDS_BGR5A1: {
// TO RGBA
- int colcount = size/4;
+ int colcount = size / 4;
- for(int i=colcount-1;i>=0;i--) {
+ for (int i = colcount - 1; i >= 0; i--) {
- int src_ofs = i*2;
- int dst_ofs = i*4;
+ int src_ofs = i * 2;
+ int dst_ofs = i * 4;
- uint8_t a=wb[src_ofs+1]&0x80;
- uint8_t b= wb[src_ofs]&0x1F;
- uint8_t g= (wb[src_ofs]>>5) | ((wb[src_ofs+1]&0x3)<<3);
- uint8_t r= (wb[src_ofs+1]>>2)&0x1F;
- wb[dst_ofs+0]=r<<3;
- wb[dst_ofs+1]=g<<3;
- wb[dst_ofs+2]=b<<3;
- wb[dst_ofs+3]=a?255:0;
+ uint8_t a = wb[src_ofs + 1] & 0x80;
+ uint8_t b = wb[src_ofs] & 0x1F;
+ uint8_t g = (wb[src_ofs] >> 5) | ((wb[src_ofs + 1] & 0x3) << 3);
+ uint8_t r = (wb[src_ofs + 1] >> 2) & 0x1F;
+ wb[dst_ofs + 0] = r << 3;
+ wb[dst_ofs + 1] = g << 3;
+ wb[dst_ofs + 2] = b << 3;
+ wb[dst_ofs + 3] = a ? 255 : 0;
}
} break;
case DDS_BGR565: {
- int colcount = size/3;
-
- for(int i=colcount-1;i>=0;i--) {
+ int colcount = size / 3;
- int src_ofs = i*2;
- int dst_ofs = i*3;
+ for (int i = colcount - 1; i >= 0; i--) {
- uint8_t b= wb[src_ofs]&0x1F;
- uint8_t g= (wb[src_ofs]>>5) | ((wb[src_ofs+1]&0x7)<<3);
- uint8_t r= wb[src_ofs+1]>>3;
- wb[dst_ofs+0]=r<<3;
- wb[dst_ofs+1]=g<<2;
- wb[dst_ofs+2]=b<<3;//b<<3;
+ int src_ofs = i * 2;
+ int dst_ofs = i * 3;
+ uint8_t b = wb[src_ofs] & 0x1F;
+ uint8_t g = (wb[src_ofs] >> 5) | ((wb[src_ofs + 1] & 0x7) << 3);
+ uint8_t r = wb[src_ofs + 1] >> 3;
+ wb[dst_ofs + 0] = r << 3;
+ wb[dst_ofs + 1] = g << 2;
+ wb[dst_ofs + 2] = b << 3; //b<<3;
}
} break;
case DDS_BGR10A2: {
// TO RGBA
- int colcount = size/4;
-
- for(int i=colcount-1;i>=0;i--) {
-
- int ofs = i*4;
+ int colcount = size / 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);
+ for (int i = colcount - 1; i >= 0; i--) {
- uint8_t a= (w32&0xc0000000) >> 24;
- uint8_t r= (w32&0x3ff00000) >> 22;
- uint8_t g= (w32&0xffc00) >> 12;
- uint8_t b= (w32&0x3ff) >> 2;
+ 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);
- wb[ofs+0]=r;
- wb[ofs+1]=g;
- wb[ofs+2]=b;
- wb[ofs+3]=a==0xc0 ? 255 : a; //0xc0 should be opaque
+ uint8_t a = (w32 & 0xc0000000) >> 24;
+ uint8_t r = (w32 & 0x3ff00000) >> 22;
+ uint8_t g = (w32 & 0xffc00) >> 12;
+ uint8_t b = (w32 & 0x3ff) >> 2;
+ wb[ofs + 0] = r;
+ wb[ofs + 1] = g;
+ wb[ofs + 2] = b;
+ wb[ofs + 3] = a == 0xc0 ? 255 : a; //0xc0 should be opaque
}
} break;
case DDS_BGRA8: {
- int colcount = size/4;
+ int colcount = size / 4;
- for(int i=0;i<colcount;i++) {
+ for (int i = 0; i < colcount; i++) {
- SWAP( wb[i*4+0],wb[i*4+2] );
+ SWAP(wb[i * 4 + 0], wb[i * 4 + 2]);
}
} break;
case DDS_BGR8: {
- int colcount = size/3;
+ int colcount = size / 3;
- for(int i=0;i<colcount;i++) {
+ for (int i = 0; i < colcount; i++) {
- SWAP( wb[i*3+0],wb[i*3+2] );
+ SWAP(wb[i * 3 + 0], wb[i * 3 + 2]);
}
} break;
case DDS_RGBA8: {
- /* do nothing either
+ /* do nothing either
int colcount = size/4;
for(int i=0;i<colcount;i++) {
@@ -446,24 +433,20 @@ RES ResourceFormatDDS::load(const String &p_path, const String& p_original_path,
} break;
default: {}
-
}
- wb=PoolVector<uint8_t>::Write();
+ wb = PoolVector<uint8_t>::Write();
}
+ Image img(width, height, mipmaps - 1, info.format, src_data);
- Image img(width,height,mipmaps-1,info.format,src_data);
-
- Ref<ImageTexture> texture = memnew( ImageTexture );
+ Ref<ImageTexture> texture = memnew(ImageTexture);
texture->create_from_image(img);
if (r_error)
- *r_error=OK;
-
+ *r_error = OK;
return texture;
-
}
void ResourceFormatDDS::get_recognized_extensions(List<String> *p_extensions) const {
@@ -471,14 +454,14 @@ void ResourceFormatDDS::get_recognized_extensions(List<String> *p_extensions) co
p_extensions->push_back("dds");
}
-bool ResourceFormatDDS::handles_type(const String& p_type) const {
+bool ResourceFormatDDS::handles_type(const String &p_type) const {
- return ClassDB::is_parent_class(p_type,"Texture");
+ return ClassDB::is_parent_class(p_type, "Texture");
}
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 d09af680c7..c347937cd5 100644
--- a/modules/dds/texture_loader_dds.h
+++ b/modules/dds/texture_loader_dds.h
@@ -29,15 +29,14 @@
#ifndef TEXTURE_LOADER_DDS_H
#define TEXTURE_LOADER_DDS_H
-#include "scene/resources/texture.h"
#include "io/resource_loader.h"
+#include "scene/resources/texture.h"
-class ResourceFormatDDS : public ResourceFormatLoader{
+class ResourceFormatDDS : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
virtual ~ResourceFormatDDS() {}
diff --git a/modules/enet/networked_multiplayer_enet.cpp b/modules/enet/networked_multiplayer_enet.cpp
index af555b7eb6..2dfb0b4a6a 100644
--- a/modules/enet/networked_multiplayer_enet.cpp
+++ b/modules/enet/networked_multiplayer_enet.cpp
@@ -26,98 +26,96 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "os/os.h"
-#include "io/marshalls.h"
#include "networked_multiplayer_enet.h"
+#include "io/marshalls.h"
+#include "os/os.h"
void NetworkedMultiplayerENet::set_transfer_mode(TransferMode p_mode) {
- transfer_mode=p_mode;
+ transfer_mode = p_mode;
}
-void NetworkedMultiplayerENet::set_target_peer(int p_peer){
+void NetworkedMultiplayerENet::set_target_peer(int p_peer) {
- target_peer=p_peer;
+ target_peer = p_peer;
}
-int NetworkedMultiplayerENet::get_packet_peer() const{
+int NetworkedMultiplayerENet::get_packet_peer() const {
- ERR_FAIL_COND_V(!active,1);
- ERR_FAIL_COND_V(incoming_packets.size()==0,1);
+ ERR_FAIL_COND_V(!active, 1);
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, 1);
return incoming_packets.front()->get().from;
-
}
-Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth){
+Error NetworkedMultiplayerENet::create_server(int p_port, int p_max_clients, int p_in_bandwidth, int p_out_bandwidth) {
- ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
ENetAddress address;
address.host = bind_ip;
address.port = p_port;
- host = enet_host_create (& address /* the address to bind the server host to */,
- p_max_clients /* allow up to 32 clients and/or outgoing connections */,
- SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
- p_in_bandwidth /* assume any amount of incoming bandwidth */,
- p_out_bandwidth /* assume any amount of outgoing bandwidth */);
+ host = enet_host_create(&address /* the address to bind the server host to */,
+ p_max_clients /* allow up to 32 clients and/or outgoing connections */,
+ SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
+ p_in_bandwidth /* assume any amount of incoming bandwidth */,
+ p_out_bandwidth /* assume any amount of outgoing bandwidth */);
- ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
_setup_compressor();
- active=true;
- server=true;
- refuse_connections=false;
- unique_id=1;
- connection_status=CONNECTION_CONNECTED;
+ active = true;
+ server = true;
+ refuse_connections = false;
+ unique_id = 1;
+ connection_status = CONNECTION_CONNECTED;
return OK;
}
-Error NetworkedMultiplayerENet::create_client(const IP_Address& p_ip, int p_port, int p_in_bandwidth, int p_out_bandwidth){
+Error NetworkedMultiplayerENet::create_client(const IP_Address &p_ip, int p_port, int p_in_bandwidth, int p_out_bandwidth) {
- ERR_FAIL_COND_V(active,ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(active, ERR_ALREADY_IN_USE);
ERR_FAIL_COND_V(!p_ip.is_ipv4(), ERR_INVALID_PARAMETER);
- host = enet_host_create (NULL /* create a client host */,
- 1 /* only allow 1 outgoing connection */,
- SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
- p_in_bandwidth /* 56K modem with 56 Kbps downstream bandwidth */,
- p_out_bandwidth /* 56K modem with 14 Kbps upstream bandwidth */);
-
- ERR_FAIL_COND_V(!host,ERR_CANT_CREATE);
+ host = enet_host_create(NULL /* create a client host */,
+ 1 /* only allow 1 outgoing connection */,
+ SYSCH_MAX /* allow up to SYSCH_MAX channels to be used */,
+ p_in_bandwidth /* 56K modem with 56 Kbps downstream bandwidth */,
+ p_out_bandwidth /* 56K modem with 14 Kbps upstream bandwidth */);
+ ERR_FAIL_COND_V(!host, ERR_CANT_CREATE);
_setup_compressor();
ENetAddress address;
- address.host=*((uint32_t *)p_ip.get_ipv4());
- address.port=p_port;
+ address.host = *((uint32_t *)p_ip.get_ipv4());
+ address.port = p_port;
//enet_address_set_host (& address, "localhost");
//address.port = p_port;
- unique_id=_gen_unique_id();
+ unique_id = _gen_unique_id();
/* Initiate the connection, allocating the enough channels */
- ENetPeer *peer = enet_host_connect (host, & address, SYSCH_MAX, unique_id);
+ ENetPeer *peer = enet_host_connect(host, &address, SYSCH_MAX, unique_id);
if (peer == NULL) {
enet_host_destroy(host);
- ERR_FAIL_COND_V(!peer,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!peer, ERR_CANT_CREATE);
}
//technically safe to ignore the peer or anything else.
- connection_status=CONNECTION_CONNECTING;
- active=true;
- server=false;
- refuse_connections=false;
+ connection_status = CONNECTION_CONNECTING;
+ active = true;
+ server = false;
+ refuse_connections = false;
return OK;
}
-void NetworkedMultiplayerENet::poll(){
+void NetworkedMultiplayerENet::poll() {
ERR_FAIL_COND(!active);
@@ -130,17 +128,16 @@ void NetworkedMultiplayerENet::poll(){
if (!host || !active) //might have been disconnected while emitting a notification
return;
- int ret = enet_host_service (host, & event, 1);
+ int ret = enet_host_service(host, &event, 1);
- if (ret<0) {
+ if (ret < 0) {
//error, do something?
break;
- } else if (ret==0) {
+ } else if (ret == 0) {
break;
}
- switch (event.type)
- {
+ switch (event.type) {
case ENET_EVENT_TYPE_CONNECT: {
/* Store any relevant client information here. */
@@ -150,39 +147,39 @@ void NetworkedMultiplayerENet::poll(){
}
IP_Address ip;
- ip.set_ipv4((uint8_t *)&(event.peer -> address.host));
+ ip.set_ipv4((uint8_t *)&(event.peer->address.host));
- int *new_id = memnew( int );
+ int *new_id = memnew(int);
*new_id = event.data;
- if (*new_id==0) { //data zero is sent by server (enet won't let you configure this). Server is always 1
- *new_id=1;
+ if (*new_id == 0) { //data zero is sent by server (enet won't let you configure this). Server is always 1
+ *new_id = 1;
}
- event.peer->data=new_id;
+ event.peer->data = new_id;
- peer_map[*new_id]=event.peer;
+ peer_map[*new_id] = event.peer;
- connection_status=CONNECTION_CONNECTED; //if connecting, this means it connected t something!
+ connection_status = CONNECTION_CONNECTED; //if connecting, this means it connected t something!
- emit_signal("peer_connected",*new_id);
+ emit_signal("peer_connected", *new_id);
if (server) {
//someone connected, let it know of all the peers available
- for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
+ 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 (NULL,8,ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_ADD_PEER,&packet->data[0]);
- encode_uint32(E->key(),&packet->data[4]);
- enet_peer_send(event.peer,SYSCH_CONFIG,packet);
+ ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
+ encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
+ encode_uint32(E->key(), &packet->data[4]);
+ enet_peer_send(event.peer, SYSCH_CONFIG, packet);
//send the new peer to existing peers
- packet = enet_packet_create (NULL,8,ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_ADD_PEER,&packet->data[0]);
- encode_uint32(*new_id,&packet->data[4]);
- enet_peer_send(E->get(),SYSCH_CONFIG,packet);
+ packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
+ encode_uint32(SYSMSG_ADD_PEER, &packet->data[0]);
+ encode_uint32(*new_id, &packet->data[4]);
+ enet_peer_send(E->get(), SYSCH_CONFIG, packet);
}
} else {
@@ -194,9 +191,7 @@ void NetworkedMultiplayerENet::poll(){
/* Reset the peer's client information. */
- int *id = (int*)event.peer -> data;
-
-
+ int *id = (int *)event.peer->data;
if (!id) {
if (!server) {
@@ -206,15 +201,15 @@ void NetworkedMultiplayerENet::poll(){
if (server) {
//someone disconnected, let it know to everyone else
- for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
+ for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
- if (E->key()==*id)
+ if (E->key() == *id)
continue;
//send the new peer to existing peers
- ENetPacket* packet = enet_packet_create (NULL,8,ENET_PACKET_FLAG_RELIABLE);
- encode_uint32(SYSMSG_REMOVE_PEER,&packet->data[0]);
- encode_uint32(*id,&packet->data[4]);
- enet_peer_send(E->get(),SYSCH_CONFIG,packet);
+ ENetPacket *packet = enet_packet_create(NULL, 8, ENET_PACKET_FLAG_RELIABLE);
+ encode_uint32(SYSMSG_REMOVE_PEER, &packet->data[0]);
+ encode_uint32(*id, &packet->data[4]);
+ enet_peer_send(E->get(), SYSCH_CONFIG, packet);
}
} else if (!server) {
emit_signal("server_disconnected");
@@ -222,91 +217,87 @@ void NetworkedMultiplayerENet::poll(){
return;
}
- emit_signal("peer_disconnected",*id);
+ emit_signal("peer_disconnected", *id);
peer_map.erase(*id);
- memdelete( id );
-
+ memdelete(id);
}
-
} break;
case ENET_EVENT_TYPE_RECEIVE: {
-
- if (event.channelID==SYSCH_CONFIG) {
+ if (event.channelID == SYSCH_CONFIG) {
//some config message
- ERR_CONTINUE( event.packet->dataLength < 8);
+ ERR_CONTINUE(event.packet->dataLength < 8);
// Only server can send config messages
- ERR_CONTINUE( server );
+ ERR_CONTINUE(server);
int msg = decode_uint32(&event.packet->data[0]);
int id = decode_uint32(&event.packet->data[4]);
- switch(msg) {
+ switch (msg) {
case SYSMSG_ADD_PEER: {
- peer_map[id]=NULL;
- emit_signal("peer_connected",id);
+ peer_map[id] = NULL;
+ emit_signal("peer_connected", id);
} break;
case SYSMSG_REMOVE_PEER: {
peer_map.erase(id);
- emit_signal("peer_disconnected",id);
+ emit_signal("peer_disconnected", id);
} break;
}
enet_packet_destroy(event.packet);
- } else if (event.channelID < SYSCH_MAX){
+ } else if (event.channelID < SYSCH_MAX) {
Packet packet;
packet.packet = event.packet;
- uint32_t *id = (uint32_t*)event.peer->data;
-
- ERR_CONTINUE(event.packet->dataLength<12)
+ uint32_t *id = (uint32_t *)event.peer->data;
+ ERR_CONTINUE(event.packet->dataLength < 12)
uint32_t source = decode_uint32(&event.packet->data[0]);
int target = decode_uint32(&event.packet->data[4]);
uint32_t flags = decode_uint32(&event.packet->data[8]);
- packet.from=source;
+ packet.from = source;
if (server) {
// Someone is cheating and trying to fake the source!
- ERR_CONTINUE(source!=*id);
+ ERR_CONTINUE(source != *id);
- packet.from=*id;
+ packet.from = *id;
- if (target==0) {
+ if (target == 0) {
//re-send the everyone but sender :|
incoming_packets.push_back(packet);
//and make copies for sending
- for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
+ 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,flags);
+ ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
- enet_peer_send(E->get(),event.channelID,packet2);
+ enet_peer_send(E->get(), event.channelID, packet2);
}
- } else if (target<0) {
+ } else if (target < 0) {
//to all but one
//and make copies for sending
- for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
+ 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,flags);
+ ENetPacket *packet2 = enet_packet_create(packet.packet->data, packet.packet->dataLength, flags);
- enet_peer_send(E->get(),event.channelID,packet2);
+ enet_peer_send(E->get(), event.channelID, packet2);
}
if (-target != 1) {
@@ -317,27 +308,25 @@ void NetworkedMultiplayerENet::poll(){
enet_packet_destroy(packet.packet);
}
- } else if (target==1) {
+ } else if (target == 1) {
//to myself and only myself
incoming_packets.push_back(packet);
} else {
//to someone else, specifically
ERR_CONTINUE(!peer_map.has(target));
- enet_peer_send(peer_map[target],event.channelID,packet.packet);
+ enet_peer_send(peer_map[target], event.channelID, packet.packet);
}
} else {
incoming_packets.push_back(packet);
}
-
//destroy packet later..
} else {
ERR_CONTINUE(true);
}
-
- }break;
+ } break;
case ENET_EVENT_TYPE_NONE: {
//do nothing
} break;
@@ -346,7 +335,7 @@ void NetworkedMultiplayerENet::poll(){
}
bool NetworkedMultiplayerENet::is_server() const {
- ERR_FAIL_COND_V(!active,false);
+ ERR_FAIL_COND_V(!active, false);
return server;
}
@@ -358,115 +347,112 @@ void NetworkedMultiplayerENet::close_connection() {
_pop_current_packet();
- bool peers_disconnected=false;
- for (Map<int,ENetPeer*>::Element *E=peer_map.front();E;E=E->next()) {
+ bool peers_disconnected = false;
+ for (Map<int, ENetPeer *>::Element *E = peer_map.front(); E; E = E->next()) {
if (E->get()) {
- enet_peer_disconnect_now(E->get(),unique_id);
- peers_disconnected=true;
+ enet_peer_disconnect_now(E->get(), unique_id);
+ peers_disconnected = true;
}
}
if (peers_disconnected) {
enet_host_flush(host);
OS::get_singleton()->delay_usec(100); //wait 100ms for disconnection packets to send
-
}
enet_host_destroy(host);
- active=false;
+ active = false;
incoming_packets.clear();
- unique_id=1; //server is 1
- connection_status=CONNECTION_DISCONNECTED;
+ unique_id = 1; //server is 1
+ connection_status = CONNECTION_DISCONNECTED;
}
int NetworkedMultiplayerENet::get_available_packet_count() const {
return incoming_packets.size();
}
-Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const{
+Error NetworkedMultiplayerENet::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const {
- ERR_FAIL_COND_V(incoming_packets.size()==0,ERR_UNAVAILABLE);
+ ERR_FAIL_COND_V(incoming_packets.size() == 0, ERR_UNAVAILABLE);
_pop_current_packet();
current_packet = incoming_packets.front()->get();
incoming_packets.pop_front();
- *r_buffer=(const uint8_t*)(&current_packet.packet->data[12]);
- r_buffer_size=current_packet.packet->dataLength-12;
+ *r_buffer = (const uint8_t *)(&current_packet.packet->data[12]);
+ r_buffer_size = current_packet.packet->dataLength - 12;
return OK;
}
-Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer,int p_buffer_size){
+Error NetworkedMultiplayerENet::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
- ERR_FAIL_COND_V(!active,ERR_UNCONFIGURED);
- ERR_FAIL_COND_V(connection_status!=CONNECTION_CONNECTED,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!active, ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(connection_status != CONNECTION_CONNECTED, ERR_UNCONFIGURED);
- int packet_flags=0;
- int channel=SYSCH_RELIABLE;
+ int packet_flags = 0;
+ int channel = SYSCH_RELIABLE;
- switch(transfer_mode) {
+ switch (transfer_mode) {
case TRANSFER_MODE_UNRELIABLE: {
- packet_flags=ENET_PACKET_FLAG_UNSEQUENCED;
- channel=SYSCH_UNRELIABLE;
+ packet_flags = ENET_PACKET_FLAG_UNSEQUENCED;
+ channel = SYSCH_UNRELIABLE;
} break;
case TRANSFER_MODE_UNRELIABLE_ORDERED: {
- packet_flags=0;
- channel=SYSCH_UNRELIABLE;
+ packet_flags = 0;
+ channel = SYSCH_UNRELIABLE;
} break;
case TRANSFER_MODE_RELIABLE: {
- packet_flags=ENET_PACKET_FLAG_RELIABLE;
- channel=SYSCH_RELIABLE;
+ packet_flags = ENET_PACKET_FLAG_RELIABLE;
+ channel = SYSCH_RELIABLE;
} break;
}
- Map<int,ENetPeer*>::Element *E=NULL;
+ Map<int, ENetPeer *>::Element *E = NULL;
- if (target_peer!=0) {
+ if (target_peer != 0) {
E = peer_map.find(ABS(target_peer));
if (!E) {
- ERR_EXPLAIN("Invalid Target Peer: "+itos(target_peer));
+ ERR_EXPLAIN("Invalid Target Peer: " + itos(target_peer));
ERR_FAIL_V(ERR_INVALID_PARAMETER);
}
}
- ENetPacket * packet = enet_packet_create (NULL,p_buffer_size+12,packet_flags);
- encode_uint32(unique_id,&packet->data[0]); //source ID
- encode_uint32(target_peer,&packet->data[4]); //dest ID
- encode_uint32(packet_flags,&packet->data[8]); //dest ID
- copymem(&packet->data[12],p_buffer,p_buffer_size);
+ ENetPacket *packet = enet_packet_create(NULL, p_buffer_size + 12, packet_flags);
+ encode_uint32(unique_id, &packet->data[0]); //source ID
+ encode_uint32(target_peer, &packet->data[4]); //dest ID
+ encode_uint32(packet_flags, &packet->data[8]); //dest ID
+ copymem(&packet->data[12], p_buffer, p_buffer_size);
if (server) {
- if (target_peer==0) {
- enet_host_broadcast(host,channel,packet);
- } else if (target_peer<0) {
+ if (target_peer == 0) {
+ enet_host_broadcast(host, channel, packet);
+ } else if (target_peer < 0) {
//send to all but one
//and make copies for sending
- int exclude=-target_peer;
+ int exclude = -target_peer;
- for (Map<int,ENetPeer*>::Element *F=peer_map.front();F;F=F->next()) {
+ 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);
+ ENetPacket *packet2 = enet_packet_create(packet->data, packet->dataLength, packet_flags);
- enet_peer_send(F->get(),channel,packet2);
+ enet_peer_send(F->get(), channel, packet2);
}
enet_packet_destroy(packet); //original packet no longer needed
} else {
- enet_peer_send (E->get(), channel, packet);
-
+ 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..
-
+ ERR_FAIL_COND_V(!peer_map.has(1), ERR_BUG);
+ enet_peer_send(peer_map[1], channel, packet); //send to server for broadcast..
}
enet_host_flush(host);
@@ -476,17 +462,16 @@ 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
+ return 1 << 24; //anything is good
}
void NetworkedMultiplayerENet::_pop_current_packet() const {
if (current_packet.packet) {
enet_packet_destroy(current_packet.packet);
- current_packet.packet=NULL;
- current_packet.from=0;
+ current_packet.packet = NULL;
+ current_packet.from = 0;
}
-
}
NetworkedMultiplayerPeer::ConnectionStatus NetworkedMultiplayerENet::get_connection_status() const {
@@ -498,24 +483,24 @@ uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
uint32_t hash = 0;
- while (hash==0 || hash==1) {
+ while (hash == 0 || hash == 1) {
hash = hash_djb2_one_32(
- (uint32_t)OS::get_singleton()->get_ticks_usec() );
+ (uint32_t)OS::get_singleton()->get_ticks_usec());
hash = hash_djb2_one_32(
- (uint32_t)OS::get_singleton()->get_unix_time(), hash );
+ (uint32_t)OS::get_singleton()->get_unix_time(), hash);
hash = hash_djb2_one_32(
- (uint32_t)OS::get_singleton()->get_data_dir().hash64(), hash );
+ (uint32_t)OS::get_singleton()->get_data_dir().hash64(), hash);
/*
hash = hash_djb2_one_32(
(uint32_t)OS::get_singleton()->get_unique_ID().hash64(), hash );
*/
hash = hash_djb2_one_32(
- (uint32_t)((uint64_t)this), hash ); //rely on aslr heap
+ (uint32_t)((uint64_t)this), hash); //rely on aslr heap
hash = hash_djb2_one_32(
- (uint32_t)((uint64_t)&hash), hash ); //rely on aslr stack
+ (uint32_t)((uint64_t)&hash), hash); //rely on aslr stack
- hash=hash&0x7FFFFFFF; // make it compatible with unsigned, since negatie id is used for exclusion
+ hash = hash & 0x7FFFFFFF; // make it compatible with unsigned, since negatie id is used for exclusion
}
return hash;
@@ -523,13 +508,13 @@ uint32_t NetworkedMultiplayerENet::_gen_unique_id() const {
int NetworkedMultiplayerENet::get_unique_id() const {
- ERR_FAIL_COND_V(!active,0);
+ ERR_FAIL_COND_V(!active, 0);
return unique_id;
}
void NetworkedMultiplayerENet::set_refuse_new_connections(bool p_enable) {
- refuse_connections=p_enable;
+ refuse_connections = p_enable;
}
bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
@@ -539,79 +524,78 @@ bool NetworkedMultiplayerENet::is_refusing_new_connections() const {
void NetworkedMultiplayerENet::set_compression_mode(CompressionMode p_mode) {
- compression_mode=p_mode;
+ compression_mode = p_mode;
}
-NetworkedMultiplayerENet::CompressionMode NetworkedMultiplayerENet::get_compression_mode() const{
+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) {
+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);
+ NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
- if (size_t(enet->src_compressor_mem.size())<inLimit) {
- enet->src_compressor_mem.resize( inLimit );
+ if (size_t(enet->src_compressor_mem.size()) < inLimit) {
+ enet->src_compressor_mem.resize(inLimit);
}
int total = inLimit;
- int ofs=0;
- while(total) {
- for(size_t i=0;i<inBufferCount;i++) {
- int to_copy = MIN(total,int(inBuffers[i].dataLength));
- copymem(&enet->src_compressor_mem[ofs],inBuffers[i].data,to_copy);
- ofs+=to_copy;
- total-=to_copy;
+ int ofs = 0;
+ while (total) {
+ for (size_t i = 0; i < inBufferCount; i++) {
+ int to_copy = MIN(total, int(inBuffers[i].dataLength));
+ copymem(&enet->src_compressor_mem[ofs], inBuffers[i].data, to_copy);
+ ofs += to_copy;
+ total -= to_copy;
}
}
Compression::Mode mode;
- switch(enet->compression_mode) {
+ switch (enet->compression_mode) {
case COMPRESS_FASTLZ: {
- mode=Compression::MODE_FASTLZ;
+ mode = Compression::MODE_FASTLZ;
} break;
case COMPRESS_ZLIB: {
- mode=Compression::MODE_DEFLATE;
+ mode = Compression::MODE_DEFLATE;
} break;
default: { ERR_FAIL_V(0); }
}
- int req_size = Compression::get_max_compressed_buffer_size(ofs,mode);
- if (enet->dst_compressor_mem.size()<req_size) {
+ int req_size = Compression::get_max_compressed_buffer_size(ofs, mode);
+ if (enet->dst_compressor_mem.size() < req_size) {
enet->dst_compressor_mem.resize(req_size);
}
- int ret=Compression::compress(enet->dst_compressor_mem.ptr(),enet->src_compressor_mem.ptr(),ofs,mode);
+ int ret = Compression::compress(enet->dst_compressor_mem.ptr(), 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);
+ copymem(outData, enet->dst_compressor_mem.ptr(), ret);
return ret;
}
-size_t NetworkedMultiplayerENet::enet_decompress (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit){
+size_t NetworkedMultiplayerENet::enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit) {
- NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet*)(context);
+ NetworkedMultiplayerENet *enet = (NetworkedMultiplayerENet *)(context);
int ret = -1;
- switch(enet->compression_mode) {
+ switch (enet->compression_mode) {
case COMPRESS_FASTLZ: {
- ret=Compression::decompress(outData,outLimit,inData,inLimit,Compression::MODE_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);
+ ret = Compression::decompress(outData, outLimit, inData, inLimit, Compression::MODE_DEFLATE);
} break;
default: {}
}
- if (ret<0) {
+ if (ret < 0) {
return 0;
} else {
return ret;
@@ -620,11 +604,11 @@ size_t NetworkedMultiplayerENet::enet_decompress (void * context, const enet_uin
void NetworkedMultiplayerENet::_setup_compressor() {
- switch(compression_mode) {
+ switch (compression_mode) {
case COMPRESS_NONE: {
- enet_host_compress(host,NULL);
+ enet_host_compress(host, NULL);
} break;
case COMPRESS_RANGE_CODER: {
enet_host_compress_with_range_coder(host);
@@ -632,60 +616,58 @@ void NetworkedMultiplayerENet::_setup_compressor() {
case COMPRESS_FASTLZ:
case COMPRESS_ZLIB: {
- enet_host_compress(host,&enet_compressor);
+ enet_host_compress(host, &enet_compressor);
} break;
}
}
-void NetworkedMultiplayerENet::enet_compressor_destroy(void * context){
+void NetworkedMultiplayerENet::enet_compressor_destroy(void *context) {
//do none
}
-
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","ip","port","in_bandwidth","out_bandwidth"),&NetworkedMultiplayerENet::create_client,DEFVAL(0),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("close_connection"),&NetworkedMultiplayerENet::close_connection);
- ClassDB::bind_method(D_METHOD("set_compression_mode","mode"),&NetworkedMultiplayerENet::set_compression_mode);
- ClassDB::bind_method(D_METHOD("get_compression_mode"),&NetworkedMultiplayerENet::get_compression_mode);
- ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"),&NetworkedMultiplayerENet::set_bind_ip);
-
- BIND_CONSTANT( COMPRESS_NONE );
- BIND_CONSTANT( COMPRESS_RANGE_CODER );
- BIND_CONSTANT( COMPRESS_FASTLZ );
- BIND_CONSTANT( COMPRESS_ZLIB );
+ 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", "ip", "port", "in_bandwidth", "out_bandwidth"), &NetworkedMultiplayerENet::create_client, DEFVAL(0), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("close_connection"), &NetworkedMultiplayerENet::close_connection);
+ ClassDB::bind_method(D_METHOD("set_compression_mode", "mode"), &NetworkedMultiplayerENet::set_compression_mode);
+ ClassDB::bind_method(D_METHOD("get_compression_mode"), &NetworkedMultiplayerENet::get_compression_mode);
+ ClassDB::bind_method(D_METHOD("set_bind_ip", "ip"), &NetworkedMultiplayerENet::set_bind_ip);
+
+ BIND_CONSTANT(COMPRESS_NONE);
+ BIND_CONSTANT(COMPRESS_RANGE_CODER);
+ BIND_CONSTANT(COMPRESS_FASTLZ);
+ BIND_CONSTANT(COMPRESS_ZLIB);
}
-
-NetworkedMultiplayerENet::NetworkedMultiplayerENet(){
-
- active=false;
- server=false;
- refuse_connections=false;
- unique_id=0;
- target_peer=0;
- current_packet.packet=NULL;
- transfer_mode=TRANSFER_MODE_RELIABLE;
- connection_status=CONNECTION_DISCONNECTED;
- compression_mode=COMPRESS_NONE;
- enet_compressor.context=this;
- enet_compressor.compress=enet_compress;
- enet_compressor.decompress=enet_decompress;
- enet_compressor.destroy=enet_compressor_destroy;
-
- bind_ip=ENET_HOST_ANY;
+NetworkedMultiplayerENet::NetworkedMultiplayerENet() {
+
+ active = false;
+ server = false;
+ refuse_connections = false;
+ unique_id = 0;
+ target_peer = 0;
+ current_packet.packet = NULL;
+ transfer_mode = TRANSFER_MODE_RELIABLE;
+ connection_status = CONNECTION_DISCONNECTED;
+ compression_mode = COMPRESS_NONE;
+ enet_compressor.context = this;
+ enet_compressor.compress = enet_compress;
+ enet_compressor.decompress = enet_decompress;
+ enet_compressor.destroy = enet_compressor_destroy;
+
+ bind_ip = ENET_HOST_ANY;
}
-NetworkedMultiplayerENet::~NetworkedMultiplayerENet(){
+NetworkedMultiplayerENet::~NetworkedMultiplayerENet() {
close_connection();
}
// sets IP for ENet to bind when using create_server
// if no IP is set, then ENet bind to ENET_HOST_ANY
-void NetworkedMultiplayerENet::set_bind_ip(const IP_Address& p_ip){
+void NetworkedMultiplayerENet::set_bind_ip(const IP_Address &p_ip) {
ERR_FAIL_COND(!p_ip.is_ipv4());
- bind_ip=*(uint32_t *)p_ip.get_ipv4();
+ bind_ip = *(uint32_t *)p_ip.get_ipv4();
}
diff --git a/modules/enet/networked_multiplayer_enet.h b/modules/enet/networked_multiplayer_enet.h
index dcf8c2429b..4e95adec10 100644
--- a/modules/enet/networked_multiplayer_enet.h
+++ b/modules/enet/networked_multiplayer_enet.h
@@ -29,13 +29,13 @@
#ifndef NETWORKED_MULTIPLAYER_ENET_H
#define NETWORKED_MULTIPLAYER_ENET_H
-#include "io/networked_multiplayer_peer.h"
#include "enet/enet.h"
#include "io/compression.h"
+#include "io/networked_multiplayer_peer.h"
class NetworkedMultiplayerENet : public NetworkedMultiplayerPeer {
- GDCLASS(NetworkedMultiplayerENet,NetworkedMultiplayerPeer)
+ GDCLASS(NetworkedMultiplayerENet, NetworkedMultiplayerPeer)
public:
enum CompressionMode {
COMPRESS_NONE,
@@ -43,9 +43,8 @@ public:
COMPRESS_FASTLZ,
COMPRESS_ZLIB
};
-private:
-
+private:
enum {
SYSMSG_ADD_PEER,
SYSMSG_REMOVE_PEER
@@ -74,7 +73,7 @@ private:
ConnectionStatus connection_status;
- Map<int,ENetPeer*> peer_map;
+ Map<int, ENetPeer *> peer_map;
struct Packet {
@@ -95,25 +94,24 @@ private:
Vector<uint8_t> dst_compressor_mem;
ENetCompressor enet_compressor;
- static size_t enet_compress(void * context, const ENetBuffer * inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 * outData, size_t outLimit);
- static size_t enet_decompress (void * context, const enet_uint8 * inData, size_t inLimit, enet_uint8 * outData, size_t outLimit);
- static void enet_compressor_destroy(void * context);
+ static size_t enet_compress(void *context, const ENetBuffer *inBuffers, size_t inBufferCount, size_t inLimit, enet_uint8 *outData, size_t outLimit);
+ static size_t enet_decompress(void *context, const enet_uint8 *inData, size_t inLimit, enet_uint8 *outData, size_t outLimit);
+ static void enet_compressor_destroy(void *context);
void _setup_compressor();
enet_uint32 bind_ip;
+
protected:
static void _bind_methods();
-public:
+public:
virtual void set_transfer_mode(TransferMode p_mode);
virtual void set_target_peer(int p_peer);
-
virtual int get_packet_peer() const;
-
- Error create_server(int p_port, int p_max_peers=32, int p_in_bandwidth=0, int p_out_bandwidth=0);
- Error create_client(const IP_Address& p_ip, int p_port, int p_in_bandwidth=0, int p_out_bandwidth=0);
+ Error create_server(int p_port, int p_max_peers = 32, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
+ Error create_client(const IP_Address &p_ip, int p_port, int p_in_bandwidth = 0, int p_out_bandwidth = 0);
void close_connection();
@@ -122,8 +120,8 @@ public:
virtual bool is_server() const;
virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const; ///< buffer is GONE after next get_packet
- virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size);
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const; ///< buffer is GONE after next get_packet
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
virtual int get_max_packet_size() const;
@@ -140,10 +138,9 @@ public:
NetworkedMultiplayerENet();
~NetworkedMultiplayerENet();
- void set_bind_ip(const IP_Address& p_ip);
+ void set_bind_ip(const IP_Address &p_ip);
};
VARIANT_ENUM_CAST(NetworkedMultiplayerENet::CompressionMode);
-
#endif // NETWORKED_MULTIPLAYER_ENET_H
diff --git a/modules/enet/register_types.cpp b/modules/enet/register_types.cpp
index 2b4dd35d33..0dea038520 100644
--- a/modules/enet/register_types.cpp
+++ b/modules/enet/register_types.cpp
@@ -30,14 +30,14 @@
#include "error_macros.h"
#include "networked_multiplayer_enet.h"
-static bool enet_ok=false;
+static bool enet_ok = false;
void register_enet_types() {
- if (enet_initialize() !=0 ) {
+ if (enet_initialize() != 0) {
ERR_PRINT("ENet initialization failure");
} else {
- enet_ok=true;
+ enet_ok = true;
}
ClassDB::register_class<NetworkedMultiplayerENet>();
@@ -47,5 +47,4 @@ void unregister_enet_types() {
if (enet_ok)
enet_deinitialize();
-
}
diff --git a/modules/etc1/image_etc.cpp b/modules/etc1/image_etc.cpp
index 2d883bff0f..642ec027f3 100644
--- a/modules/etc1/image_etc.cpp
+++ b/modules/etc1/image_etc.cpp
@@ -28,175 +28,154 @@
/*************************************************************************/
#include "image_etc.h"
#include "image.h"
-#include "rg_etc1.h"
-#include "print_string.h"
#include "os/copymem.h"
+#include "print_string.h"
+#include "rg_etc1.h"
static void _decompress_etc(Image *p_img) {
- ERR_FAIL_COND(p_img->get_format()!=Image::FORMAT_ETC);
+ ERR_FAIL_COND(p_img->get_format() != Image::FORMAT_ETC);
int imgw = p_img->get_width();
int imgh = p_img->get_height();
- PoolVector<uint8_t> src=p_img->get_data();
+ PoolVector<uint8_t> src = p_img->get_data();
PoolVector<uint8_t> dst;
PoolVector<uint8_t>::Read r = src.read();
- int mmc=p_img->get_mipmap_count();
+ int mmc = p_img->get_mipmap_count();
+ for (int i = 0; i <= mmc; i++) {
- for(int i=0;i<=mmc;i++) {
-
- dst.resize(dst.size()+imgw*imgh*3);
- const uint8_t *srcbr=&r[p_img->get_mipmap_offset(i)];
+ dst.resize(dst.size() + imgw * imgh * 3);
+ const uint8_t *srcbr = &r[p_img->get_mipmap_offset(i)];
PoolVector<uint8_t>::Write w = dst.write();
- uint8_t *wptr = &w[dst.size()-imgw*imgh*3];
-
- int bw=MAX(imgw/4,1);
- int bh=MAX(imgh/4,1);
-
- for(int y=0;y<bh;y++) {
+ uint8_t *wptr = &w[dst.size() - imgw * imgh * 3];
- for(int x=0;x<bw;x++) {
+ int bw = MAX(imgw / 4, 1);
+ int bh = MAX(imgh / 4, 1);
- uint8_t block[4*4*4];
+ for (int y = 0; y < bh; y++) {
+ for (int x = 0; x < bw; x++) {
- rg_etc1::unpack_etc1_block(srcbr,(unsigned int*)block);
- srcbr+=8;
+ uint8_t block[4 * 4 * 4];
- int maxx=MIN(imgw,4);
- int maxy=MIN(imgh,4);
+ rg_etc1::unpack_etc1_block(srcbr, (unsigned int *)block);
+ srcbr += 8;
- for(int yy=0;yy<maxy;yy++) {
+ int maxx = MIN(imgw, 4);
+ int maxy = MIN(imgh, 4);
- for(int xx=0;xx<maxx;xx++) {
+ for (int yy = 0; yy < maxy; yy++) {
- uint32_t src_ofs = (yy*4+xx)*4;
- uint32_t dst_ofs = ((y*4+yy)*imgw+x*4+xx)*3;
- wptr[dst_ofs+0]=block[src_ofs+0];
- wptr[dst_ofs+1]=block[src_ofs+1];
- wptr[dst_ofs+2]=block[src_ofs+2];
+ for (int xx = 0; xx < maxx; xx++) {
+ uint32_t src_ofs = (yy * 4 + xx) * 4;
+ uint32_t dst_ofs = ((y * 4 + yy) * imgw + x * 4 + xx) * 3;
+ wptr[dst_ofs + 0] = block[src_ofs + 0];
+ wptr[dst_ofs + 1] = block[src_ofs + 1];
+ wptr[dst_ofs + 2] = block[src_ofs + 2];
}
}
-
}
-
}
- imgw=MAX(1,imgw/2);
- imgh=MAX(1,imgh/2);
+ imgw = MAX(1, imgw / 2);
+ imgh = MAX(1, imgh / 2);
}
-
- r=PoolVector<uint8_t>::Read();
+ r = PoolVector<uint8_t>::Read();
//print_line("Re Creating ETC into regular image: w "+itos(p_img->get_width())+" h "+itos(p_img->get_height())+" mm "+itos(p_img->get_mipmaps()));
- *p_img=Image(p_img->get_width(),p_img->get_height(),p_img->has_mipmaps(),Image::FORMAT_RGB8,dst);
+ *p_img = Image(p_img->get_width(), p_img->get_height(), p_img->has_mipmaps(), Image::FORMAT_RGB8, dst);
if (p_img->has_mipmaps())
p_img->generate_mipmaps();
-
-
}
static void _compress_etc(Image *p_img) {
Image img = *p_img;
- int imgw=img.get_width(),imgh=img.get_height();
+ int imgw = img.get_width(), imgh = img.get_height();
- ERR_FAIL_COND( nearest_power_of_2(imgw)!=imgw || nearest_power_of_2(imgh)!=imgh );
+ ERR_FAIL_COND(nearest_power_of_2(imgw) != imgw || nearest_power_of_2(imgh) != imgh);
- if (img.get_format()!=Image::FORMAT_RGB8)
+ if (img.get_format() != Image::FORMAT_RGB8)
img.convert(Image::FORMAT_RGB8);
-
PoolVector<uint8_t> res_data;
PoolVector<uint8_t> dst_data;
PoolVector<uint8_t>::Read r = img.get_data().read();
- int target_size = Image::get_image_data_size(p_img->get_width(),p_img->get_height(),Image::FORMAT_ETC,p_img->has_mipmaps()?-1:0);
- int mmc = p_img->has_mipmaps() ? Image::get_image_required_mipmaps(p_img->get_width(),p_img->get_height(),Image::FORMAT_ETC) : 0;
+ int target_size = Image::get_image_data_size(p_img->get_width(), p_img->get_height(), Image::FORMAT_ETC, p_img->has_mipmaps() ? -1 : 0);
+ int mmc = p_img->has_mipmaps() ? Image::get_image_required_mipmaps(p_img->get_width(), p_img->get_height(), Image::FORMAT_ETC) : 0;
dst_data.resize(target_size);
- int mc=0;
- int ofs=0;
- PoolVector<uint8_t>::Write w=dst_data.write();
-
+ int mc = 0;
+ int ofs = 0;
+ PoolVector<uint8_t>::Write w = dst_data.write();
rg_etc1::etc1_pack_params pp;
- pp.m_quality=rg_etc1::cLowQuality;
- for(int i=0;i<=mmc;i++) {
-
+ pp.m_quality = rg_etc1::cLowQuality;
+ for (int i = 0; i <= mmc; i++) {
- int bw=MAX(imgw/4,1);
- int bh=MAX(imgh/4,1);
+ int bw = MAX(imgw / 4, 1);
+ int bh = MAX(imgh / 4, 1);
const uint8_t *src = &r[img.get_mipmap_offset(i)];
- int mmsize = MAX(bw,1)*MAX(bh,1)*8;
+ int mmsize = MAX(bw, 1) * MAX(bh, 1) * 8;
uint8_t *dst = &w[ofs];
- ofs+=mmsize;
-
+ ofs += mmsize;
//print_line("bh: "+itos(bh)+" bw: "+itos(bw));
- for(int y=0;y<bh;y++) {
+ for (int y = 0; y < bh; y++) {
- for(int x=0;x<bw;x++) {
+ for (int x = 0; x < bw; x++) {
//print_line("x: "+itos(x)+" y: "+itos(y));
- uint8_t block[4*4*4];
- zeromem(block,4*4*4);
+ uint8_t block[4 * 4 * 4];
+ zeromem(block, 4 * 4 * 4);
uint8_t cblock[8];
- int maxy = MIN(imgh,4);
- int maxx = MIN(imgw,4);
-
-
- for(int yy=0;yy<maxy;yy++) {
-
- for(int xx=0;xx<maxx;xx++) {
+ int maxy = MIN(imgh, 4);
+ int maxx = MIN(imgw, 4);
+ for (int yy = 0; yy < maxy; yy++) {
- uint32_t dst_ofs = (yy*4+xx)*4;
- uint32_t src_ofs = ((y*4+yy)*imgw+x*4+xx)*3;
- block[dst_ofs+0]=src[src_ofs+0];
- block[dst_ofs+1]=src[src_ofs+1];
- block[dst_ofs+2]=src[src_ofs+2];
- block[dst_ofs+3]=255;
+ for (int xx = 0; xx < maxx; xx++) {
+ uint32_t dst_ofs = (yy * 4 + xx) * 4;
+ uint32_t src_ofs = ((y * 4 + yy) * imgw + x * 4 + xx) * 3;
+ block[dst_ofs + 0] = src[src_ofs + 0];
+ block[dst_ofs + 1] = src[src_ofs + 1];
+ block[dst_ofs + 2] = src[src_ofs + 2];
+ block[dst_ofs + 3] = 255;
}
}
- rg_etc1::pack_etc1_block(cblock, (const unsigned int*)block, pp);
- for(int j=0;j<8;j++) {
+ rg_etc1::pack_etc1_block(cblock, (const unsigned int *)block, pp);
+ for (int j = 0; j < 8; j++) {
- dst[j]=cblock[j];
+ dst[j] = cblock[j];
}
- dst+=8;
+ dst += 8;
}
-
}
- imgw=MAX(1,imgw/2);
- imgh=MAX(1,imgh/2);
+ imgw = MAX(1, imgw / 2);
+ imgh = MAX(1, imgh / 2);
mc++;
-
}
- *p_img=Image(p_img->get_width(),p_img->get_height(),(mc-1)?true:false,Image::FORMAT_ETC,dst_data);
-
-
+ *p_img = Image(p_img->get_width(), p_img->get_height(), (mc - 1) ? true : false, Image::FORMAT_ETC, dst_data);
}
void _register_etc1_compress_func() {
rg_etc1::pack_etc1_block_init();
- Image::_image_compress_etc_func=_compress_etc;
- Image::_image_decompress_etc=_decompress_etc;
-
-
+ Image::_image_compress_etc_func = _compress_etc;
+ Image::_image_decompress_etc = _decompress_etc;
}
diff --git a/modules/etc1/image_etc.h b/modules/etc1/image_etc.h
index 6ab10126f8..18461819d6 100644
--- a/modules/etc1/image_etc.h
+++ b/modules/etc1/image_etc.h
@@ -29,7 +29,6 @@
#ifndef IMAGE_ETC1_H
#define IMAGE_ETC1_H
-
void _register_etc1_compress_func();
#endif // IMAGE_ETC_H
diff --git a/modules/etc1/register_types.cpp b/modules/etc1/register_types.cpp
index d02ef83478..b3b6419d26 100644
--- a/modules/etc1/register_types.cpp
+++ b/modules/etc1/register_types.cpp
@@ -35,7 +35,7 @@ static ResourceFormatPKM *resource_loader_pkm = NULL;
void register_etc1_types() {
- resource_loader_pkm = memnew( ResourceFormatPKM );
+ resource_loader_pkm = memnew(ResourceFormatPKM);
ResourceLoader::add_resource_format_loader(resource_loader_pkm);
_register_etc1_compress_func();
diff --git a/modules/etc1/texture_loader_pkm.cpp b/modules/etc1/texture_loader_pkm.cpp
index b00e71c485..bce10e691e 100644
--- a/modules/etc1/texture_loader_pkm.cpp
+++ b/modules/etc1/texture_loader_pkm.cpp
@@ -32,38 +32,38 @@
#include <string.h>
struct ETC1Header {
- char tag[6]; // "PKM 10"
- uint16_t format; // Format == number of mips (== zero)
- uint16_t texWidth; // Texture dimensions, multiple of 4 (big-endian)
- uint16_t texHeight;
- uint16_t origWidth; // Original dimensions (big-endian)
- uint16_t origHeight;
+ char tag[6]; // "PKM 10"
+ uint16_t format; // Format == number of mips (== zero)
+ uint16_t texWidth; // Texture dimensions, multiple of 4 (big-endian)
+ uint16_t texHeight;
+ uint16_t origWidth; // Original dimensions (big-endian)
+ uint16_t origHeight;
};
-RES ResourceFormatPKM::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatPKM::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
return RES();
FileAccessRef fref(f);
if (r_error)
- *r_error=ERR_FILE_CORRUPT;
+ *r_error = ERR_FILE_CORRUPT;
- ERR_EXPLAIN("Unable to open PKM texture file: "+p_path);
- ERR_FAIL_COND_V(err!=OK,RES());
+ ERR_EXPLAIN("Unable to open PKM texture file: " + p_path);
+ ERR_FAIL_COND_V(err != OK, RES());
// big endian
f->set_endian_swap(true);
ETC1Header h;
- ERR_EXPLAIN("Invalid or Unsupported PKM texture file: "+p_path);
- f->get_buffer((uint8_t *) &h.tag, sizeof(h.tag));
- if(strncmp(h.tag, "PKM 10", sizeof(h.tag)))
+ ERR_EXPLAIN("Invalid or Unsupported PKM texture file: " + p_path);
+ f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag));
+ if (strncmp(h.tag, "PKM 10", sizeof(h.tag)))
ERR_FAIL_V(RES());
h.format = f->get_16();
@@ -77,20 +77,20 @@ RES ResourceFormatPKM::load(const String &p_path, const String& p_original_path,
uint32_t size = h.texWidth * h.texHeight / 2;
src_data.resize(size);
PoolVector<uint8_t>::Write wb = src_data.write();
- f->get_buffer(wb.ptr(),size);
- wb=PoolVector<uint8_t>::Write();
+ f->get_buffer(wb.ptr(), size);
+ wb = PoolVector<uint8_t>::Write();
int mipmaps = h.format;
int width = h.origWidth;
int height = h.origHeight;
- Image img(width,height,mipmaps,Image::FORMAT_ETC,src_data);
+ Image img(width, height, mipmaps, Image::FORMAT_ETC, src_data);
- Ref<ImageTexture> texture = memnew( ImageTexture );
+ Ref<ImageTexture> texture = memnew(ImageTexture);
texture->create_from_image(img);
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return texture;
}
@@ -100,14 +100,14 @@ void ResourceFormatPKM::get_recognized_extensions(List<String> *p_extensions) co
p_extensions->push_back("pkm");
}
-bool ResourceFormatPKM::handles_type(const String& p_type) const {
+bool ResourceFormatPKM::handles_type(const String &p_type) const {
- return ClassDB::is_parent_class(p_type,"Texture");
+ return ClassDB::is_parent_class(p_type, "Texture");
}
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/etc1/texture_loader_pkm.h b/modules/etc1/texture_loader_pkm.h
index 9be7b051d3..19d15d21fc 100644
--- a/modules/etc1/texture_loader_pkm.h
+++ b/modules/etc1/texture_loader_pkm.h
@@ -29,15 +29,14 @@
#ifndef TEXTURE_LOADER_PKM_H
#define TEXTURE_LOADER_PKM_H
-#include "scene/resources/texture.h"
#include "io/resource_loader.h"
+#include "scene/resources/texture.h"
-class ResourceFormatPKM : public ResourceFormatLoader{
+class ResourceFormatPKM : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
virtual ~ResourceFormatPKM() {}
diff --git a/modules/gdscript/gd_compiler.cpp b/modules/gdscript/gd_compiler.cpp
index 398c2cf82a..9591740438 100644
--- a/modules/gdscript/gd_compiler.cpp
+++ b/modules/gdscript/gd_compiler.cpp
@@ -29,53 +29,51 @@
#include "gd_compiler.h"
#include "gd_script.h"
-bool GDCompiler::_is_class_member_property(CodeGen & codegen, const StringName & p_name) {
+bool GDCompiler::_is_class_member_property(CodeGen &codegen, const StringName &p_name) {
if (!codegen.function_node || codegen.function_node->_static)
return false;
- return _is_class_member_property(codegen.script,p_name);
+ return _is_class_member_property(codegen.script, p_name);
}
-bool GDCompiler::_is_class_member_property(GDScript *owner, const StringName & p_name) {
-
+bool GDCompiler::_is_class_member_property(GDScript *owner, const StringName &p_name) {
GDScript *scr = owner;
- GDNativeClass *nc=NULL;
- while(scr) {
+ GDNativeClass *nc = NULL;
+ while (scr) {
if (scr->native.is_valid())
- nc=scr->native.ptr();
- scr=scr->_base;
+ nc = scr->native.ptr();
+ scr = scr->_base;
}
- ERR_FAIL_COND_V(!nc,false);
+ ERR_FAIL_COND_V(!nc, false);
- return ClassDB::has_property(nc->get_name(),p_name);
+ return ClassDB::has_property(nc->get_name(), p_name);
}
+void GDCompiler::_set_error(const String &p_error, const GDParser::Node *p_node) {
-void GDCompiler::_set_error(const String& p_error,const GDParser::Node *p_node) {
-
- if (error!="")
+ if (error != "")
return;
- error=p_error;
+ error = p_error;
if (p_node) {
- err_line=p_node->line;
- err_column=p_node->column;
+ err_line = p_node->line;
+ err_column = p_node->column;
} else {
- err_line=0;
- err_column=0;
+ err_line = 0;
+ err_column = 0;
}
}
-bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level) {
+bool GDCompiler::_create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level) {
- ERR_FAIL_COND_V(on->arguments.size()!=1,false);
+ 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)
+ int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level);
+ if (src_address_a < 0)
return false;
codegen.opcodes.push_back(GDFunction::OPCODE_OPERATOR); // perform operator
@@ -86,22 +84,20 @@ bool GDCompiler::_create_unary_operator(CodeGen& codegen,const GDParser::Operato
return true;
}
-bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer) {
-
- ERR_FAIL_COND_V(on->arguments.size()!=2,false);
+bool GDCompiler::_create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer) {
+ 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);
- if (src_address_a<0)
+ int src_address_a = _parse_expression(codegen, on->arguments[0], p_stack_level, false, p_initializer);
+ if (src_address_a < 0)
return false;
- if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)
+ if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::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)
+ 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(GDFunction::OPCODE_OPERATOR); // perform operator
codegen.opcodes.push_back(op); //which operator
codegen.opcodes.push_back(src_address_a); // argument 1
@@ -109,7 +105,6 @@ bool GDCompiler::_create_binary_operator(CodeGen& codegen,const GDParser::Operat
return true;
}
-
/*
int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_expression) {
@@ -128,55 +123,52 @@ int GDCompiler::_parse_subexpression(CodeGen& codegen,const GDParser::Node *p_ex
}
*/
-int GDCompiler::_parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level) {
+int GDCompiler::_parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level) {
- Variant::Operator var_op=Variant::OP_MAX;
+ Variant::Operator var_op = Variant::OP_MAX;
+ switch (p_expression->op) {
- switch(p_expression->op) {
-
- case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op=Variant::OP_ADD; break;
- case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op=Variant::OP_SUBSTRACT; break;
- case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op=Variant::OP_MULTIPLY; break;
- case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op=Variant::OP_DIVIDE; break;
- case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op=Variant::OP_MODULE; break;
- case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op=Variant::OP_SHIFT_LEFT; break;
- case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op=Variant::OP_SHIFT_RIGHT; break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op=Variant::OP_BIT_AND; break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op=Variant::OP_BIT_OR; break;
- case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op=Variant::OP_BIT_XOR; break;
+ case GDParser::OperatorNode::OP_ASSIGN_ADD: var_op = Variant::OP_ADD; break;
+ case GDParser::OperatorNode::OP_ASSIGN_SUB: var_op = Variant::OP_SUBSTRACT; break;
+ case GDParser::OperatorNode::OP_ASSIGN_MUL: var_op = Variant::OP_MULTIPLY; break;
+ case GDParser::OperatorNode::OP_ASSIGN_DIV: var_op = Variant::OP_DIVIDE; break;
+ case GDParser::OperatorNode::OP_ASSIGN_MOD: var_op = Variant::OP_MODULE; break;
+ case GDParser::OperatorNode::OP_ASSIGN_SHIFT_LEFT: var_op = Variant::OP_SHIFT_LEFT; break;
+ case GDParser::OperatorNode::OP_ASSIGN_SHIFT_RIGHT: var_op = Variant::OP_SHIFT_RIGHT; break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_AND: var_op = Variant::OP_BIT_AND; break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_OR: var_op = Variant::OP_BIT_OR; break;
+ case GDParser::OperatorNode::OP_ASSIGN_BIT_XOR: var_op = Variant::OP_BIT_XOR; break;
case GDParser::OperatorNode::OP_INIT_ASSIGN:
case GDParser::OperatorNode::OP_ASSIGN: {
//none
} break;
- default: {
+ default: {
ERR_FAIL_V(-1);
}
}
- bool initializer = p_expression->op==GDParser::OperatorNode::OP_INIT_ASSIGN;
+ bool initializer = p_expression->op == GDParser::OperatorNode::OP_INIT_ASSIGN;
- if (var_op==Variant::OP_MAX) {
+ if (var_op == Variant::OP_MAX) {
- return _parse_expression(codegen,p_expression->arguments[1],p_stack_level,false,initializer);
+ return _parse_expression(codegen, p_expression->arguments[1], p_stack_level, false, initializer);
}
- if (!_create_binary_operator(codegen,p_expression,var_op,p_stack_level,initializer))
+ if (!_create_binary_operator(codegen, p_expression, var_op, p_stack_level, initializer))
return -1;
- int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::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;
-
}
-int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root,bool p_initializer) {
+int GDCompiler::_parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root, bool p_initializer) {
-
- switch(p_expression->type) {
+ switch (p_expression->type) {
//should parse variable declaration and adjust stack accordingly...
case GDParser::Node::TYPE_IDENTIFIER: {
//return identifier
@@ -185,16 +177,15 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
//This could be made much simpler by just indexing "self", but done this way (with custom self-addressing modes) increases peformance a lot.
- const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode*>(p_expression);
+ const GDParser::IdentifierNode *in = static_cast<const GDParser::IdentifierNode *>(p_expression);
StringName identifier = in->name;
-
- if (_is_class_member_property(codegen,identifier)) {
+ if (_is_class_member_property(codegen, identifier)) {
//get property
codegen.opcodes.push_back(GDFunction::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)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::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;
@@ -204,8 +195,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
if (!p_initializer && codegen.stack_identifiers.has(identifier)) {
int pos = codegen.stack_identifiers[identifier];
- return pos|(GDFunction::ADDR_TYPE_STACK_VARIABLE<<GDFunction::ADDR_BITS);
-
+ return pos | (GDFunction::ADDR_TYPE_STACK_VARIABLE << GDFunction::ADDR_BITS);
}
//TRY MEMBERS!
if (!codegen.function_node || !codegen.function_node->_static) {
@@ -215,7 +205,7 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
if (codegen.script->member_indices.has(identifier)) {
int idx = codegen.script->member_indices[identifier].index;
- return idx|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS); //argument (stack root)
+ return idx | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS); //argument (stack root)
}
}
@@ -225,45 +215,44 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
while (owner) {
GDScript *scr = owner;
- GDNativeClass *nc=NULL;
- while(scr) {
+ GDNativeClass *nc = NULL;
+ while (scr) {
if (scr->constants.has(identifier)) {
//int idx=scr->constants[identifier];
int idx = codegen.get_name_map_pos(identifier);
- return idx|(GDFunction::ADDR_TYPE_CLASS_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root)
+ return idx | (GDFunction::ADDR_TYPE_CLASS_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root)
}
if (scr->native.is_valid())
- nc=scr->native.ptr();
- scr=scr->_base;
+ nc = scr->native.ptr();
+ scr = scr->_base;
}
// CLASS C++ Integer Constant
if (nc) {
- bool success=false;
- int constant = ClassDB::get_integer_constant(nc->get_name(),identifier,&success);
+ bool success = false;
+ int constant = ClassDB::get_integer_constant(nc->get_name(), identifier, &success);
if (success) {
- Variant key=constant;
+ Variant key = constant;
int idx;
if (!codegen.constant_map.has(key)) {
- idx=codegen.constant_map.size();
- codegen.constant_map[key]=idx;
+ idx = codegen.constant_map.size();
+ codegen.constant_map[key] = idx;
} else {
- idx=codegen.constant_map[key];
+ idx = codegen.constant_map[key];
}
- return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //make it a local constant (faster access)
+ return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //make it a local constant (faster access)
}
-
}
- owner=owner->_owner;
+ owner = owner->_owner;
}
/*
@@ -278,58 +267,55 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
if (GDScriptLanguage::get_singleton()->get_global_map().has(identifier)) {
int idx = GDScriptLanguage::get_singleton()->get_global_map()[identifier];
- return idx|(GDFunction::ADDR_TYPE_GLOBAL<<GDFunction::ADDR_BITS); //argument (stack root)
+ return idx | (GDFunction::ADDR_TYPE_GLOBAL << GDFunction::ADDR_BITS); //argument (stack root)
}
//not found, error
- _set_error("Identifier not found: "+String(identifier),p_expression);
+ _set_error("Identifier not found: " + String(identifier), p_expression);
return -1;
-
} break;
case GDParser::Node::TYPE_CONSTANT: {
//return constant
- const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode*>(p_expression);
-
+ const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_expression);
int idx;
if (!codegen.constant_map.has(cn->value)) {
- idx=codegen.constant_map.size();
- codegen.constant_map[cn->value]=idx;
+ idx = codegen.constant_map.size();
+ codegen.constant_map[cn->value] = idx;
} else {
- idx=codegen.constant_map[cn->value];
+ idx = codegen.constant_map[cn->value];
}
-
- return idx|(GDFunction::ADDR_TYPE_LOCAL_CONSTANT<<GDFunction::ADDR_BITS); //argument (stack root)
+ return idx | (GDFunction::ADDR_TYPE_LOCAL_CONSTANT << GDFunction::ADDR_BITS); //argument (stack root)
} break;
case GDParser::Node::TYPE_SELF: {
//return constant
if (codegen.function_node && codegen.function_node->_static) {
- _set_error("'self' not present in static function!",p_expression);
+ _set_error("'self' not present in static function!", p_expression);
return -1;
}
- return (GDFunction::ADDR_TYPE_SELF<<GDFunction::ADDR_BITS);
+ return (GDFunction::ADDR_TYPE_SELF << GDFunction::ADDR_BITS);
} break;
case GDParser::Node::TYPE_ARRAY: {
- const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode*>(p_expression);
+ const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_expression);
Vector<int> values;
- int slevel=p_stack_level;
+ int slevel = p_stack_level;
- for(int i=0;i<an->elements.size();i++) {
+ for (int i = 0; i < an->elements.size(); i++) {
- int ret = _parse_expression(codegen,an->elements[i],slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, an->elements[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -339,10 +325,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_ARRAY);
codegen.opcodes.push_back(values.size());
- for(int i=0;i<values.size();i++)
+ for (int i = 0; i < values.size(); i++)
codegen.opcodes.push_back(values[i]);
- int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::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;
@@ -350,27 +336,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
} break;
case GDParser::Node::TYPE_DICTIONARY: {
- const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode*>(p_expression);
+ const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(p_expression);
Vector<int> values;
- int slevel=p_stack_level;
+ int slevel = p_stack_level;
- for(int i=0;i<dn->elements.size();i++) {
+ for (int i = 0; i < dn->elements.size(); i++) {
- int ret = _parse_expression(codegen,dn->elements[i].key,slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, dn->elements[i].key, slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
values.push_back(ret);
- ret = _parse_expression(codegen,dn->elements[i].value,slevel);
- if (ret<0)
+ ret = _parse_expression(codegen, dn->elements[i].value, slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -380,10 +366,10 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
codegen.opcodes.push_back(GDFunction::OPCODE_CONSTRUCT_DICTIONARY);
codegen.opcodes.push_back(dn->elements.size());
- for(int i=0;i<values.size();i++)
+ for (int i = 0; i < values.size(); i++)
codegen.opcodes.push_back(values[i]);
- int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::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;
@@ -392,27 +378,24 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
case GDParser::Node::TYPE_OPERATOR: {
//hell breaks loose
- const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode*>(p_expression);
- switch(on->op) {
-
+ const GDParser::OperatorNode *on = static_cast<const GDParser::OperatorNode *>(p_expression);
+ switch (on->op) {
//call/constructor operator
case GDParser::OperatorNode::OP_PARENT_CALL: {
-
- ERR_FAIL_COND_V(on->arguments.size()<1,-1);
+ ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
const GDParser::IdentifierNode *in = (const GDParser::IdentifierNode *)on->arguments[0];
-
Vector<int> arguments;
int slevel = p_stack_level;
- for(int i=1;i<on->arguments.size();i++) {
+ for (int i = 1; i < on->arguments.size(); i++) {
- int ret = _parse_expression(codegen,on->arguments[i],slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, on->arguments[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -425,27 +408,27 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
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++)
+ for (int i = 0; i < arguments.size(); i++)
codegen.opcodes.push_back(arguments[i]); //arguments
} break;
case GDParser::OperatorNode::OP_CALL: {
- if (on->arguments[0]->type==GDParser::Node::TYPE_TYPE) {
+ if (on->arguments[0]->type == GDParser::Node::TYPE_TYPE) {
//construct a basic type
- ERR_FAIL_COND_V(on->arguments.size()<1,-1);
+ ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
const GDParser::TypeNode *tn = (const GDParser::TypeNode *)on->arguments[0];
int vtype = tn->vtype;
Vector<int> arguments;
int slevel = p_stack_level;
- for(int i=1;i<on->arguments.size();i++) {
+ for (int i = 1; i < on->arguments.size(); i++) {
- int ret = _parse_expression(codegen,on->arguments[i],slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, on->arguments[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -457,24 +440,23 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
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++)
+ for (int i = 0; i < arguments.size(); i++)
codegen.opcodes.push_back(arguments[i]); //arguments
- } else if (on->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
+ } else if (on->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
//built in function
- ERR_FAIL_COND_V(on->arguments.size()<1,-1);
-
+ ERR_FAIL_COND_V(on->arguments.size() < 1, -1);
Vector<int> arguments;
int slevel = p_stack_level;
- for(int i=1;i<on->arguments.size();i++) {
+ for (int i = 1; i < on->arguments.size(); i++) {
- int ret = _parse_expression(codegen,on->arguments[i],slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, on->arguments[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -482,79 +464,74 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
arguments.push_back(ret);
}
-
codegen.opcodes.push_back(GDFunction::OPCODE_CALL_BUILT_IN);
- codegen.opcodes.push_back(static_cast<const GDParser::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(static_cast<const GDParser::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]);
} else {
//regular function
- ERR_FAIL_COND_V(on->arguments.size()<2,-1);
+ ERR_FAIL_COND_V(on->arguments.size() < 2, -1);
const GDParser::Node *instance = on->arguments[0];
- if (instance->type==GDParser::Node::TYPE_SELF) {
+ if (instance->type == GDParser::Node::TYPE_SELF) {
//room for optimization
-
}
-
Vector<int> arguments;
int slevel = p_stack_level;
- for(int i=0;i<on->arguments.size();i++) {
+ for (int i = 0; i < on->arguments.size(); i++) {
int ret;
- if (i==0 && on->arguments[i]->type==GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) {
+ if (i == 0 && on->arguments[i]->type == GDParser::Node::TYPE_SELF && codegen.function_node && codegen.function_node->_static) {
//static call to self
- ret=(GDFunction::ADDR_TYPE_CLASS<<GDFunction::ADDR_BITS);
- } else if (i==1) {
+ ret = (GDFunction::ADDR_TYPE_CLASS << GDFunction::ADDR_BITS);
+ } else if (i == 1) {
- if (on->arguments[i]->type!=GDParser::Node::TYPE_IDENTIFIER) {
- _set_error("Attempt to call a non-identifier.",on);
+ if (on->arguments[i]->type != GDParser::Node::TYPE_IDENTIFIER) {
+ _set_error("Attempt to call a non-identifier.", on);
return -1;
}
- GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode*>(on->arguments[i]);
- ret=codegen.get_name_map_pos(id->name);
+ GDParser::IdentifierNode *id = static_cast<GDParser::IdentifierNode *>(on->arguments[i]);
+ ret = codegen.get_name_map_pos(id->name);
} else {
- ret = _parse_expression(codegen,on->arguments[i],slevel);
- if (ret<0)
+ ret = _parse_expression(codegen, on->arguments[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (ret & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
}
arguments.push_back(ret);
-
}
- codegen.opcodes.push_back(p_root?GDFunction::OPCODE_CALL:GDFunction::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(p_root ? GDFunction::OPCODE_CALL : GDFunction::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]);
}
} break;
case GDParser::OperatorNode::OP_YIELD: {
-
- ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size()!=2,-1);
+ ERR_FAIL_COND_V(on->arguments.size() && on->arguments.size() != 2, -1);
Vector<int> arguments;
int slevel = p_stack_level;
- for(int i=0;i<on->arguments.size();i++) {
+ for (int i = 0; i < on->arguments.size(); i++) {
- int ret = _parse_expression(codegen,on->arguments[i],slevel);
- if (ret<0)
+ int ret = _parse_expression(codegen, on->arguments[i], slevel);
+ if (ret < 0)
return ret;
- if (ret&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) {
+ if (ret & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) {
slevel++;
codegen.alloc_stack(slevel);
}
@@ -562,8 +539,8 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
}
//push call bytecode
- codegen.opcodes.push_back(arguments.size()==0?GDFunction::OPCODE_YIELD:GDFunction::OPCODE_YIELD_SIGNAL); // basic type constructor
- for(int i=0;i<arguments.size();i++)
+ codegen.opcodes.push_back(arguments.size() == 0 ? GDFunction::OPCODE_YIELD : GDFunction::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(GDFunction::OPCODE_YIELD_RESUME);
//next will be where to place the result :)
@@ -574,60 +551,60 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
case GDParser::OperatorNode::OP_INDEX:
case GDParser::OperatorNode::OP_INDEX_NAMED: {
- ERR_FAIL_COND_V(on->arguments.size()!=2,-1);
+ ERR_FAIL_COND_V(on->arguments.size() != 2, -1);
int slevel = p_stack_level;
- bool named=(on->op==GDParser::OperatorNode::OP_INDEX_NAMED);
+ bool named = (on->op == GDParser::OperatorNode::OP_INDEX_NAMED);
- int from = _parse_expression(codegen,on->arguments[0],slevel);
- if (from<0)
+ int from = _parse_expression(codegen, on->arguments[0], slevel);
+ if (from < 0)
return from;
int index;
if (named) {
- if (on->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) {
+ if (on->arguments[0]->type == GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) {
- GDParser::IdentifierNode* identifier = static_cast<GDParser::IdentifierNode*>(on->arguments[1]);
- const Map<StringName,GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(identifier->name);
+ GDParser::IdentifierNode *identifier = static_cast<GDParser::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<GDParser::IdentifierNode*>(on->arguments[1])->name;
- _set_error("Must use '"+n+"' instead of 'self."+n+"' in getter.",on);
+ if (MI && MI->get().getter == codegen.function_node->name) {
+ String n = static_cast<GDParser::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=="") {
+ if (MI && MI->get().getter == "") {
// Faster than indexing self (as if no self. had been used)
- return (MI->get().index)|(GDFunction::ADDR_TYPE_MEMBER<<GDFunction::ADDR_BITS);
+ return (MI->get().index) | (GDFunction::ADDR_TYPE_MEMBER << GDFunction::ADDR_BITS);
}
}
- index=codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode*>(on->arguments[1])->name);
+ index = codegen.get_name_map_pos(static_cast<GDParser::IdentifierNode *>(on->arguments[1])->name);
} else {
- if (on->arguments[1]->type==GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value.get_type()==Variant::STRING) {
+ if (on->arguments[1]->type == GDParser::Node::TYPE_CONSTANT && static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value.get_type() == Variant::STRING) {
//also, somehow, named (speed up anyway)
- StringName name = static_cast<const GDParser::ConstantNode*>(on->arguments[1])->value;
- index=codegen.get_name_map_pos(name);
- named=true;
+ StringName name = static_cast<const GDParser::ConstantNode *>(on->arguments[1])->value;
+ index = codegen.get_name_map_pos(name);
+ named = true;
} else {
//regular indexing
- if (from&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (from & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
- index = _parse_expression(codegen,on->arguments[1],slevel);
- if (index<0)
+ index = _parse_expression(codegen, on->arguments[1], slevel);
+ if (index < 0)
return index;
}
}
- codegen.opcodes.push_back(named?GDFunction::OPCODE_GET_NAMED:GDFunction::OPCODE_GET); // perform operator
+ codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET); // perform operator
codegen.opcodes.push_back(from); // argument 1
codegen.opcodes.push_back(index); // argument 2 (unary only takes one parameter)
@@ -636,66 +613,66 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
// AND operator with early out on failure
- int res = _parse_expression(codegen,on->arguments[0],p_stack_level);
- if (res<0)
+ int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
+ if (res < 0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
- int jump_fail_pos=codegen.opcodes.size();
+ 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)
+ res = _parse_expression(codegen, on->arguments[1], p_stack_level);
+ if (res < 0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
- int jump_fail_pos2=codegen.opcodes.size();
+ 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(GDFunction::OPCODE_ASSIGN_TRUE);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size()+3);
- codegen.opcodes[jump_fail_pos]=codegen.opcodes.size();
- codegen.opcodes[jump_fail_pos2]=codegen.opcodes.size();
+ codegen.opcodes.push_back(codegen.opcodes.size() + 3);
+ codegen.opcodes[jump_fail_pos] = codegen.opcodes.size();
+ codegen.opcodes[jump_fail_pos2] = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_FALSE);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
- return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS;
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
+ return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS;
} break;
case GDParser::OperatorNode::OP_OR: {
// OR operator with early out on success
- int res = _parse_expression(codegen,on->arguments[0],p_stack_level);
- if (res<0)
+ int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
+ if (res < 0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF);
codegen.opcodes.push_back(res);
- int jump_success_pos=codegen.opcodes.size();
+ 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)
+ res = _parse_expression(codegen, on->arguments[1], p_stack_level);
+ if (res < 0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF);
codegen.opcodes.push_back(res);
- int jump_success_pos2=codegen.opcodes.size();
+ 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(GDFunction::OPCODE_ASSIGN_FALSE);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size()+3);
- codegen.opcodes[jump_success_pos]=codegen.opcodes.size();
- codegen.opcodes[jump_success_pos2]=codegen.opcodes.size();
+ codegen.opcodes.push_back(codegen.opcodes.size() + 3);
+ codegen.opcodes[jump_success_pos] = codegen.opcodes.size();
+ codegen.opcodes[jump_success_pos2] = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN_TRUE);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
- return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS;
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
+ return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS;
} break;
// ternary operators
@@ -703,70 +680,113 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
// x IF a ELSE y operator with early out on failure
- int res = _parse_expression(codegen,on->arguments[0],p_stack_level);
- if (res<0)
+ int res = _parse_expression(codegen, on->arguments[0], p_stack_level);
+ if (res < 0)
return res;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(res);
- int jump_fail_pos=codegen.opcodes.size();
+ 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)
+ res = _parse_expression(codegen, on->arguments[1], p_stack_level);
+ if (res < 0)
return res;
-
+
codegen.alloc_stack(p_stack_level); //it will be used..
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
- int jump_past_pos=codegen.opcodes.size();
+ int jump_past_pos = codegen.opcodes.size();
codegen.opcodes.push_back(0);
-
- codegen.opcodes[jump_fail_pos]=codegen.opcodes.size();
- res = _parse_expression(codegen,on->arguments[2],p_stack_level);
- if (res<0)
+
+ codegen.opcodes[jump_fail_pos] = codegen.opcodes.size();
+ res = _parse_expression(codegen, on->arguments[2], p_stack_level);
+ if (res < 0)
return res;
-
+
codegen.opcodes.push_back(GDFunction::OPCODE_ASSIGN);
- codegen.opcodes.push_back(p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ codegen.opcodes.push_back(p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
codegen.opcodes.push_back(res);
-
- codegen.opcodes[jump_past_pos]=codegen.opcodes.size();
-
- return p_stack_level|GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS;
+
+ codegen.opcodes[jump_past_pos] = codegen.opcodes.size();
+
+ return p_stack_level | GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS;
} break;
//unary operators
- case GDParser::OperatorNode::OP_NEG: { if (!_create_unary_operator(codegen,on,Variant::OP_NEGATE,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_NOT: { if (!_create_unary_operator(codegen,on,Variant::OP_NOT,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_BIT_INVERT: { if (!_create_unary_operator(codegen,on,Variant::OP_BIT_NEGATE,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_PREINC: { } break; //?
- case GDParser::OperatorNode::OP_PREDEC: { } break;
- case GDParser::OperatorNode::OP_INC: { } break;
- case GDParser::OperatorNode::OP_DEC: { } break;
+ case GDParser::OperatorNode::OP_NEG: {
+ if (!_create_unary_operator(codegen, on, Variant::OP_NEGATE, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_NOT: {
+ if (!_create_unary_operator(codegen, on, Variant::OP_NOT, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_BIT_INVERT: {
+ if (!_create_unary_operator(codegen, on, Variant::OP_BIT_NEGATE, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_PREINC: {
+ } break; //?
+ case GDParser::OperatorNode::OP_PREDEC: {
+ } break;
+ case GDParser::OperatorNode::OP_INC: {
+ } break;
+ case GDParser::OperatorNode::OP_DEC: {
+ } break;
//binary operators (in precedence order)
- case GDParser::OperatorNode::OP_IN: { if (!_create_binary_operator(codegen,on,Variant::OP_IN,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_EQUAL,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_NOT_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_NOT_EQUAL,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_LESS: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_LESS_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_LESS_EQUAL,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_GREATER: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_GREATER_EQUAL: { if (!_create_binary_operator(codegen,on,Variant::OP_GREATER_EQUAL,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_ADD: { if (!_create_binary_operator(codegen,on,Variant::OP_ADD,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_SUB: { if (!_create_binary_operator(codegen,on,Variant::OP_SUBSTRACT,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_MUL: { if (!_create_binary_operator(codegen,on,Variant::OP_MULTIPLY,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_DIV: { if (!_create_binary_operator(codegen,on,Variant::OP_DIVIDE,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_MOD: { if (!_create_binary_operator(codegen,on,Variant::OP_MODULE,p_stack_level)) return -1;} break;
+ case GDParser::OperatorNode::OP_IN: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_IN, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_EQUAL: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_EQUAL, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_NOT_EQUAL: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_NOT_EQUAL, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_LESS: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_LESS, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_LESS_EQUAL: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_LESS_EQUAL, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_GREATER: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_GREATER, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_GREATER_EQUAL: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_GREATER_EQUAL, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_ADD: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_ADD, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_SUB: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_SUBSTRACT, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_MUL: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_MULTIPLY, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_DIV: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_DIVIDE, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_MOD: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_MODULE, p_stack_level)) return -1;
+ } break;
//case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break;
//case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_BIT_AND: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_AND,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_BIT_OR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_OR,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_BIT_XOR: { if (!_create_binary_operator(codegen,on,Variant::OP_BIT_XOR,p_stack_level)) return -1;} break;
- //shift
- case GDParser::OperatorNode::OP_SHIFT_LEFT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_LEFT,p_stack_level)) return -1;} break;
- case GDParser::OperatorNode::OP_SHIFT_RIGHT: { if (!_create_binary_operator(codegen,on,Variant::OP_SHIFT_RIGHT,p_stack_level)) return -1;} break;
+ case GDParser::OperatorNode::OP_BIT_AND: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_BIT_AND, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_BIT_OR: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_BIT_OR, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_BIT_XOR: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_BIT_XOR, p_stack_level)) return -1;
+ } break;
+ //shift
+ case GDParser::OperatorNode::OP_SHIFT_LEFT: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_LEFT, p_stack_level)) return -1;
+ } break;
+ case GDParser::OperatorNode::OP_SHIFT_RIGHT: {
+ if (!_create_binary_operator(codegen, on, Variant::OP_SHIFT_RIGHT, p_stack_level)) return -1;
+ } break;
//assignment operators
case GDParser::OperatorNode::OP_ASSIGN_ADD:
case GDParser::OperatorNode::OP_ASSIGN_SUB:
@@ -781,63 +801,57 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
case GDParser::OperatorNode::OP_INIT_ASSIGN:
case GDParser::OperatorNode::OP_ASSIGN: {
- ERR_FAIL_COND_V(on->arguments.size()!=2,-1);
-
-
- if (on->arguments[0]->type==GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED)) {
- //SET (chained) MODE!!
+ ERR_FAIL_COND_V(on->arguments.size() != 2, -1);
+ if (on->arguments[0]->type == GDParser::Node::TYPE_OPERATOR && (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX || static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED)) {
+//SET (chained) MODE!!
#ifdef DEBUG_ENABLED
- if (static_cast<GDParser::OperatorNode*>(on->arguments[0])->op==GDParser::OperatorNode::OP_INDEX_NAMED) {
- const GDParser::OperatorNode* inon = static_cast<GDParser::OperatorNode*>(on->arguments[0]);
-
+ if (static_cast<GDParser::OperatorNode *>(on->arguments[0])->op == GDParser::OperatorNode::OP_INDEX_NAMED) {
+ const GDParser::OperatorNode *inon = static_cast<GDParser::OperatorNode *>(on->arguments[0]);
- if (inon->arguments[0]->type==GDParser::Node::TYPE_SELF && codegen.script && codegen.function_node && !codegen.function_node->_static) {
+ if (inon->arguments[0]->type == GDParser::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<GDParser::IdentifierNode*>(inon->arguments[1])->name);
- if (MI && MI->get().setter==codegen.function_node->name) {
- String n = static_cast<GDParser::IdentifierNode*>(inon->arguments[1])->name;
- _set_error("Must use '"+n+"' instead of 'self."+n+"' in setter.",inon);
+ const Map<StringName, GDScript::MemberInfo>::Element *MI = codegen.script->member_indices.find(static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name);
+ if (MI && MI->get().setter == codegen.function_node->name) {
+ String n = static_cast<GDParser::IdentifierNode *>(inon->arguments[1])->name;
+ _set_error("Must use '" + n + "' instead of 'self." + n + "' in setter.", inon);
return -1;
}
}
}
#endif
+ int slevel = p_stack_level;
- int slevel=p_stack_level;
-
- GDParser::OperatorNode* op = static_cast<GDParser::OperatorNode*>(on->arguments[0]);
+ GDParser::OperatorNode *op = static_cast<GDParser::OperatorNode *>(on->arguments[0]);
/* Find chain of sets */
StringName assign_property;
- List<GDParser::OperatorNode*> chain;
+ List<GDParser::OperatorNode *> chain;
{
//create get/set chain
- GDParser::OperatorNode* n=op;
- while(true) {
+ GDParser::OperatorNode *n = op;
+ while (true) {
chain.push_back(n);
- if (n->arguments[0]->type!=GDParser::Node::TYPE_OPERATOR) {
+ if (n->arguments[0]->type != GDParser::Node::TYPE_OPERATOR) {
//check for a built-in property
- if (n->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) {
+ if (n->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) {
- GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode*>(n->arguments[0]);
- if (_is_class_member_property(codegen,identifier->name)) {
+ GDParser::IdentifierNode *identifier = static_cast<GDParser::IdentifierNode *>(n->arguments[0]);
+ if (_is_class_member_property(codegen, identifier->name)) {
assign_property = identifier->name;
-
}
-
}
break;
}
- n = static_cast<GDParser::OperatorNode*>(n->arguments[0]);
- if (n->op!=GDParser::OperatorNode::OP_INDEX && n->op!=GDParser::OperatorNode::OP_INDEX_NAMED)
+ n = static_cast<GDParser::OperatorNode *>(n->arguments[0]);
+ if (n->op != GDParser::OperatorNode::OP_INDEX && n->op != GDParser::OperatorNode::OP_INDEX_NAMED)
break;
}
}
@@ -845,23 +859,21 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
/* Chain of gets */
//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)
+ int prev_pos = _parse_expression(codegen, chain.back()->get()->arguments[0], slevel);
+ if (prev_pos < 0)
return prev_pos;
- int retval=prev_pos;
+ int retval = prev_pos;
//print_line("retval: "+itos(retval));
- if (retval&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (retval & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
-
Vector<int> setchain;
-
- if (assign_property!=StringName()) {
+ if (assign_property != StringName()) {
// recover and assign at the end, this allows stuff like
// position.x+=2.0
@@ -871,37 +883,34 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
setchain.push_back(GDFunction::OPCODE_SET_MEMBER);
}
- for(List<GDParser::OperatorNode*>::Element *E=chain.back();E;E=E->prev()) {
+ for (List<GDParser::OperatorNode *>::Element *E = chain.back(); E; E = E->prev()) {
-
- if (E==chain.front()) //ignore first
+ if (E == chain.front()) //ignore first
break;
- bool named = E->get()->op==GDParser::OperatorNode::OP_INDEX_NAMED;
+ bool named = E->get()->op == GDParser::OperatorNode::OP_INDEX_NAMED;
int key_idx;
if (named) {
- key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(E->get()->arguments[1])->name);
+ key_idx = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(E->get()->arguments[1])->name);
//printf("named key %x\n",key_idx);
} else {
- if (prev_pos&(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)) {
+ if (prev_pos & (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)) {
slevel++;
codegen.alloc_stack(slevel);
}
GDParser::Node *key = E->get()->arguments[1];
- key_idx = _parse_expression(codegen,key,slevel);
+ key_idx = _parse_expression(codegen, key, slevel);
//printf("expr key %x\n",key_idx);
-
//stack was raised here if retval was stack but..
-
}
- if (key_idx<0) //error
+ if (key_idx < 0) //error
return key_idx;
codegen.opcodes.push_back(named ? GDFunction::OPCODE_GET_NAMED : GDFunction::OPCODE_GET);
@@ -909,134 +918,116 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
codegen.opcodes.push_back(key_idx);
slevel++;
codegen.alloc_stack(slevel);
- int dst_pos = (GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|slevel;
+ int dst_pos = (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | slevel;
codegen.opcodes.push_back(dst_pos);
-
//add in reverse order, since it will be reverted
-
setchain.push_back(dst_pos);
setchain.push_back(key_idx);
setchain.push_back(prev_pos);
setchain.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET);
- prev_pos=dst_pos;
-
+ prev_pos = dst_pos;
}
setchain.invert();
-
int set_index;
- bool named=false;
+ bool named = false;
+ if (static_cast<const GDParser::OperatorNode *>(op)->op == GDParser::OperatorNode::OP_INDEX_NAMED) {
- if (static_cast<const GDParser::OperatorNode*>(op)->op==GDParser::OperatorNode::OP_INDEX_NAMED) {
-
-
- set_index=codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name);
- named=true;
+ set_index = codegen.get_name_map_pos(static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name);
+ named = true;
} else {
- set_index = _parse_expression(codegen,op->arguments[1],slevel+1);
- named=false;
+ set_index = _parse_expression(codegen, op->arguments[1], slevel + 1);
+ named = false;
}
-
- if (set_index<0) //error
+ if (set_index < 0) //error
return set_index;
- if (set_index&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (set_index & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
-
- int set_value = _parse_assign_right_expression(codegen,on,slevel+1);
- if (set_value<0) //error
+ int set_value = _parse_assign_right_expression(codegen, on, slevel + 1);
+ if (set_value < 0) //error
return set_value;
- codegen.opcodes.push_back(named?GDFunction::OPCODE_SET_NAMED:GDFunction::OPCODE_SET);
+ codegen.opcodes.push_back(named ? GDFunction::OPCODE_SET_NAMED : GDFunction::OPCODE_SET);
codegen.opcodes.push_back(prev_pos);
codegen.opcodes.push_back(set_index);
codegen.opcodes.push_back(set_value);
- for(int i=0;i<setchain.size();i++) {
-
+ for (int i = 0; i < setchain.size(); i++) {
codegen.opcodes.push_back(setchain[i]);
}
return retval;
-
- } else if (on->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER && _is_class_member_property(codegen,static_cast<GDParser::IdentifierNode*>(on->arguments[0])->name)) {
+ } else if (on->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER && _is_class_member_property(codegen, static_cast<GDParser::IdentifierNode *>(on->arguments[0])->name)) {
//assignment to member property
int slevel = p_stack_level;
- int src_address = _parse_assign_right_expression(codegen,on,slevel);
- if (src_address<0)
+ int src_address = _parse_assign_right_expression(codegen, on, slevel);
+ if (src_address < 0)
return -1;
- StringName name = static_cast<GDParser::IdentifierNode*>(on->arguments[0])->name;
+ StringName name = static_cast<GDParser::IdentifierNode *>(on->arguments[0])->name;
codegen.opcodes.push_back(GDFunction::OPCODE_SET_MEMBER);
codegen.opcodes.push_back(codegen.get_name_map_pos(name));
codegen.opcodes.push_back(src_address);
- return GDFunction::ADDR_TYPE_NIL<<GDFunction::ADDR_BITS;
+ return GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS;
} else {
-
-
//REGULAR ASSIGNMENT MODE!!
int slevel = p_stack_level;
- int dst_address_a = _parse_expression(codegen,on->arguments[0],slevel,false,on->op==GDParser::OperatorNode::OP_INIT_ASSIGN);
- if (dst_address_a<0)
+ int dst_address_a = _parse_expression(codegen, on->arguments[0], slevel, false, on->op == GDParser::OperatorNode::OP_INIT_ASSIGN);
+ if (dst_address_a < 0)
return -1;
- if (dst_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS) {
+ if (dst_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) {
slevel++;
codegen.alloc_stack(slevel);
}
- int src_address_b = _parse_assign_right_expression(codegen,on,slevel);
- if (src_address_b<0)
+ int src_address_b = _parse_assign_right_expression(codegen, on, slevel);
+ if (src_address_b < 0)
return -1;
-
-
-
codegen.opcodes.push_back(GDFunction::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 GDParser::OperatorNode::OP_EXTENDS: {
- ERR_FAIL_COND_V(on->arguments.size()!=2,false);
-
+ ERR_FAIL_COND_V(on->arguments.size() != 2, false);
int slevel = p_stack_level;
- int src_address_a = _parse_expression(codegen,on->arguments[0],slevel);
- if (src_address_a<0)
+ int src_address_a = _parse_expression(codegen, on->arguments[0], slevel);
+ if (src_address_a < 0)
return -1;
- if (src_address_a&GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)
+ if (src_address_a & GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS)
slevel++; //uses stack for return, increase stack
- int src_address_b = _parse_expression(codegen,on->arguments[1],slevel);
- if (src_address_b<0)
+ int src_address_b = _parse_expression(codegen, on->arguments[1], slevel);
+ if (src_address_b < 0)
return -1;
codegen.opcodes.push_back(GDFunction::OPCODE_EXTENDS_TEST); // perform operator
@@ -1046,14 +1037,13 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
} break;
default: {
-
- ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #"+itos(on->op)+" in parse tree while parsing expression.");
+ ERR_EXPLAIN("Bug in bytecode compiler, unexpected operator #" + itos(on->op) + " in parse tree while parsing expression.");
ERR_FAIL_V(0); //unreachable code
} break;
}
- int dst_addr=(p_stack_level)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int dst_addr = (p_stack_level) | (GDFunction::ADDR_TYPE_STACK << GDFunction::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;
@@ -1064,47 +1054,43 @@ int GDCompiler::_parse_expression(CodeGen& codegen,const GDParser::Node *p_expre
ERR_EXPLAIN("Bug in bytecode compiler, unexpected node in parse tree while parsing expression.");
ERR_FAIL_V(-1); //unreachable code
} break;
-
-
}
ERR_FAIL_V(-1); //unreachable code
}
-
-Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level,int p_break_addr,int p_continue_addr) {
+Error GDCompiler::_parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level, int p_break_addr, int p_continue_addr) {
codegen.push_stack_identifiers();
- int new_identifiers=0;
- codegen.current_line=p_block->line;
+ int new_identifiers = 0;
+ codegen.current_line = p_block->line;
- for(int i=0;i<p_block->statements.size();i++) {
+ for (int i = 0; i < p_block->statements.size(); i++) {
const GDParser::Node *s = p_block->statements[i];
-
- switch(s->type) {
+ switch (s->type) {
case GDParser::Node::TYPE_NEWLINE: {
#ifdef DEBUG_ENABLED
- const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode*>(s);
+ const GDParser::NewLineNode *nl = static_cast<const GDParser::NewLineNode *>(s);
codegen.opcodes.push_back(GDFunction::OPCODE_LINE);
codegen.opcodes.push_back(nl->line);
- codegen.current_line=nl->line;
+ codegen.current_line = nl->line;
#endif
} break;
case GDParser::Node::TYPE_CONTROL_FLOW: {
// try subblocks
- const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode*>(s);
+ const GDParser::ControlFlowNode *cf = static_cast<const GDParser::ControlFlowNode *>(s);
- switch(cf->cf_type) {
+ switch (cf->cf_type) {
case GDParser::ControlFlowNode::CF_MATCH: {
GDParser::MatchNode *match = cf->match;
-
+
GDParser::IdentifierNode *id = memnew(GDParser::IdentifierNode);
id->name = "#match_value";
-
+
// var #match_value
// copied because there is no _parse_statement :(
codegen.add_stack_identifier(id->name, p_stack_level++);
@@ -1112,25 +1098,25 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
new_identifiers++;
GDParser::OperatorNode *op = memnew(GDParser::OperatorNode);
- op->op=GDParser::OperatorNode::OP_ASSIGN;
+ op->op = GDParser::OperatorNode::OP_ASSIGN;
op->arguments.push_back(id);
op->arguments.push_back(match->val_to_match);
-
+
int ret = _parse_expression(codegen, op, p_stack_level);
if (ret < 0) {
return ERR_PARSE_ERROR;
}
-
+
// break address
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(codegen.opcodes.size() + 3);
int break_addr = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(0); // break addr
-
+
for (int j = 0; j < match->compiled_pattern_branches.size(); j++) {
GDParser::MatchNode::CompiledPatternBranch branch = match->compiled_pattern_branches[j];
-
+
// jump over continue
// jump unconditionally
// continue address
@@ -1139,87 +1125,81 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
if (ret < 0) {
return ERR_PARSE_ERROR;
}
-
+
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF);
codegen.opcodes.push_back(ret);
codegen.opcodes.push_back(codegen.opcodes.size() + 3);
int continue_addr = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(0);
-
-
-
+
Error err = _parse_block(codegen, branch.body, p_stack_level, p_break_addr, continue_addr);
if (err) {
return ERR_PARSE_ERROR;
}
-
+
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(break_addr);
-
+
codegen.opcodes[continue_addr + 1] = codegen.opcodes.size();
}
-
+
codegen.opcodes[break_addr + 1] = codegen.opcodes.size();
-
-
+
} break;
-
+
case GDParser::ControlFlowNode::CF_IF: {
#ifdef DEBUG_ENABLED
codegen.opcodes.push_back(GDFunction::OPCODE_LINE);
codegen.opcodes.push_back(cf->line);
- codegen.current_line=cf->line;
+ codegen.current_line = cf->line;
#endif
- int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false);
- if (ret<0)
+ int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
+ if (ret < 0)
return ERR_PARSE_ERROR;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(ret);
- int else_addr=codegen.opcodes.size();
+ int else_addr = codegen.opcodes.size();
codegen.opcodes.push_back(0); //temporary
- Error err = _parse_block(codegen,cf->body,p_stack_level,p_break_addr,p_continue_addr);
+ Error err = _parse_block(codegen, cf->body, p_stack_level, p_break_addr, p_continue_addr);
if (err)
return err;
if (cf->body_else) {
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
- int end_addr=codegen.opcodes.size();
+ int end_addr = codegen.opcodes.size();
codegen.opcodes.push_back(0);
- codegen.opcodes[else_addr]=codegen.opcodes.size();
+ codegen.opcodes[else_addr] = codegen.opcodes.size();
- Error err = _parse_block(codegen,cf->body_else,p_stack_level,p_break_addr,p_continue_addr);
+ Error err = _parse_block(codegen, cf->body_else, p_stack_level, p_break_addr, p_continue_addr);
if (err)
return err;
- codegen.opcodes[end_addr]=codegen.opcodes.size();
+ codegen.opcodes[end_addr] = codegen.opcodes.size();
} else {
//end without else
- codegen.opcodes[else_addr]=codegen.opcodes.size();
-
+ codegen.opcodes[else_addr] = codegen.opcodes.size();
}
} break;
case GDParser::ControlFlowNode::CF_FOR: {
-
-
- int slevel=p_stack_level;
- int iter_stack_pos=slevel;
- int iterator_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
- int counter_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
- int container_pos = (slevel++)|(GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS);
+ int slevel = p_stack_level;
+ int iter_stack_pos = slevel;
+ int iterator_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
+ int counter_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
+ int container_pos = (slevel++) | (GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS);
codegen.alloc_stack(slevel);
- codegen.push_stack_identifiers();
- codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode*>(cf->arguments[0])->name,iter_stack_pos);
+ codegen.push_stack_identifiers();
+ codegen.add_stack_identifier(static_cast<const GDParser::IdentifierNode *>(cf->arguments[0])->name, iter_stack_pos);
- int ret = _parse_expression(codegen,cf->arguments[1],slevel,false);
- if (ret<0)
+ int ret = _parse_expression(codegen, cf->arguments[1], slevel, false);
+ if (ret < 0)
return ERR_COMPILATION_FAILED;
//assign container
@@ -1231,32 +1211,29 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
codegen.opcodes.push_back(GDFunction::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(codegen.opcodes.size() + 4);
codegen.opcodes.push_back(iterator_pos);
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next
- codegen.opcodes.push_back(codegen.opcodes.size()+8);
+ codegen.opcodes.push_back(codegen.opcodes.size() + 8);
//break loop
- int break_pos=codegen.opcodes.size();
+ int break_pos = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP); //skip code for next
codegen.opcodes.push_back(0); //skip code for next
//next loop
- int continue_pos=codegen.opcodes.size();
+ int continue_pos = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::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);
+ Error err = _parse_block(codegen, cf->body, slevel, break_pos, continue_pos);
if (err)
return err;
-
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(continue_pos);
- codegen.opcodes[break_pos+1]=codegen.opcodes.size();
-
+ codegen.opcodes[break_pos + 1] = codegen.opcodes.size();
codegen.pop_stack_identifiers();
@@ -1264,25 +1241,25 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
case GDParser::ControlFlowNode::CF_WHILE: {
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
- codegen.opcodes.push_back(codegen.opcodes.size()+3);
- int break_addr=codegen.opcodes.size();
+ codegen.opcodes.push_back(codegen.opcodes.size() + 3);
+ int break_addr = codegen.opcodes.size();
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(0);
- int continue_addr=codegen.opcodes.size();
+ int continue_addr = codegen.opcodes.size();
- int ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false);
- if (ret<0)
+ int ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
+ if (ret < 0)
return ERR_PARSE_ERROR;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_IF_NOT);
codegen.opcodes.push_back(ret);
codegen.opcodes.push_back(break_addr);
- Error err = _parse_block(codegen,cf->body,p_stack_level,break_addr,continue_addr);
+ Error err = _parse_block(codegen, cf->body, p_stack_level, break_addr, continue_addr);
if (err)
return err;
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
codegen.opcodes.push_back(continue_addr);
- codegen.opcodes[break_addr+1]=codegen.opcodes.size();
+ codegen.opcodes[break_addr + 1] = codegen.opcodes.size();
} break;
case GDParser::ControlFlowNode::CF_SWITCH: {
@@ -1290,9 +1267,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
} break;
case GDParser::ControlFlowNode::CF_BREAK: {
- if (p_break_addr<0) {
+ if (p_break_addr < 0) {
- _set_error("'break'' not within loop",cf);
+ _set_error("'break'' not within loop", cf);
return ERR_COMPILATION_FAILED;
}
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP);
@@ -1301,9 +1278,9 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
} break;
case GDParser::ControlFlowNode::CF_CONTINUE: {
- if (p_continue_addr<0) {
+ if (p_continue_addr < 0) {
- _set_error("'continue' not within loop",cf);
+ _set_error("'continue' not within loop", cf);
return ERR_COMPILATION_FAILED;
}
@@ -1317,29 +1294,28 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
if (cf->arguments.size()) {
- ret = _parse_expression(codegen,cf->arguments[0],p_stack_level,false);
- if (ret<0)
+ ret = _parse_expression(codegen, cf->arguments[0], p_stack_level, false);
+ if (ret < 0)
return ERR_PARSE_ERROR;
} else {
- ret=GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS;
+ ret = GDFunction::ADDR_TYPE_NIL << GDFunction::ADDR_BITS;
}
codegen.opcodes.push_back(GDFunction::OPCODE_RETURN);
codegen.opcodes.push_back(ret);
} break;
-
}
} break;
case GDParser::Node::TYPE_ASSERT: {
// try subblocks
- const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode*>(s);
+ const GDParser::AssertNode *as = static_cast<const GDParser::AssertNode *>(s);
- int ret = _parse_expression(codegen,as->condition,p_stack_level,false);
- if (ret<0)
+ int ret = _parse_expression(codegen, as->condition, p_stack_level, false);
+ if (ret < 0)
return ERR_PARSE_ERROR;
codegen.opcodes.push_back(GDFunction::OPCODE_ASSERT);
@@ -1353,99 +1329,91 @@ Error GDCompiler::_parse_block(CodeGen& codegen,const GDParser::BlockNode *p_blo
} break;
case GDParser::Node::TYPE_LOCAL_VAR: {
+ const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(s);
- const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode*>(s);
-
- 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);
+ 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.add_stack_identifier(lv->name, p_stack_level++);
codegen.alloc_stack(p_stack_level);
new_identifiers++;
} break;
default: {
//expression
- int ret = _parse_expression(codegen,s,p_stack_level,true);
- if (ret<0)
+ int ret = _parse_expression(codegen, s, p_stack_level, true);
+ if (ret < 0)
return ERR_PARSE_ERROR;
} break;
-
}
-
}
codegen.pop_stack_identifiers();
return OK;
}
-
-Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready) {
+Error GDCompiler::_parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready) {
Vector<int> bytecode;
CodeGen codegen;
- 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=ScriptDebugger::get_singleton()!=NULL;
+ 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 = ScriptDebugger::get_singleton() != NULL;
Vector<StringName> argnames;
- int stack_level=0;
+ int stack_level = 0;
if (p_func) {
- for(int i=0;i<p_func->arguments.size();i++) {
- 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);
+ for (int i = 0; i < p_func->arguments.size(); i++) {
+ 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);
+ codegen.add_stack_identifier(p_func->arguments[i], i);
#ifdef TOOLS_ENABLED
argnames.push_back(p_func->arguments[i]);
#endif
}
- stack_level=p_func->arguments.size();
+ stack_level = p_func->arguments.size();
}
codegen.alloc_stack(stack_level);
/* Parse initializer -if applies- */
- bool is_initializer=!p_for_ready && !p_func;
+ bool is_initializer = !p_for_ready && !p_func;
- if (is_initializer || (p_func && String(p_func->name)=="_init")) {
+ 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()){
+ if (!p_func && p_class->extends_used && p_script->native.is_null()) {
//call implicit parent constructor
codegen.opcodes.push_back(GDFunction::OPCODE_CALL_SELF_BASE);
codegen.opcodes.push_back(codegen.get_name_map_pos("_init"));
codegen.opcodes.push_back(0);
- codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK<<GDFunction::ADDR_BITS)|0);
-
+ codegen.opcodes.push_back((GDFunction::ADDR_TYPE_STACK << GDFunction::ADDR_BITS) | 0);
}
- Error err = _parse_block(codegen,p_class->initializer,stack_level);
+ Error err = _parse_block(codegen, p_class->initializer, stack_level);
if (err)
return err;
- is_initializer=true;
-
+ is_initializer = true;
}
- if (p_for_ready || (p_func && String(p_func->name)=="_ready")) {
+ 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);
+ Error err = _parse_block(codegen, p_class->ready, stack_level);
if (err)
return err;
}
-
}
-
/* Parse default argument code -if applies- */
Vector<int> defarg_addr;
@@ -1457,196 +1425,185 @@ Error GDCompiler::_parse_function(GDScript *p_script,const GDParser::ClassNode *
codegen.opcodes.push_back(GDFunction::OPCODE_JUMP_TO_DEF_ARGUMENT);
defarg_addr.push_back(codegen.opcodes.size());
- for(int i=0;i<p_func->default_values.size();i++) {
+ for (int i = 0; i < p_func->default_values.size(); i++) {
- _parse_expression(codegen,p_func->default_values[i],stack_level,true);
+ _parse_expression(codegen, p_func->default_values[i], stack_level, true);
defarg_addr.push_back(codegen.opcodes.size());
}
-
defarg_addr.invert();
}
-
-
- Error err = _parse_block(codegen,p_func->body,stack_level);
+ Error err = _parse_block(codegen, p_func->body, stack_level);
if (err)
return err;
- func_name=p_func->name;
+ func_name = p_func->name;
} else {
if (p_for_ready)
- func_name="_ready";
+ func_name = "_ready";
else
- func_name="_init";
+ func_name = "_init";
}
codegen.opcodes.push_back(GDFunction::OPCODE_END);
- GDFunction *gdfunc=NULL;
+ GDFunction *gdfunc = NULL;
/*
if (String(p_func->name)=="") { //initializer func
gdfunc = &p_script->initializer;
*/
//} else { //regular func
- p_script->member_functions[func_name]=memnew(GDFunction);
- gdfunc = p_script->member_functions[func_name];
+ p_script->member_functions[func_name] = memnew(GDFunction);
+ gdfunc = p_script->member_functions[func_name];
//}
if (p_func) {
- gdfunc->_static=p_func->_static;
- gdfunc->rpc_mode=p_func->rpc_mode;
+ gdfunc->_static = p_func->_static;
+ gdfunc->rpc_mode = p_func->rpc_mode;
}
#ifdef TOOLS_ENABLED
- gdfunc->arg_names=argnames;
+ gdfunc->arg_names = argnames;
#endif
//constants
if (codegen.constant_map.size()) {
- gdfunc->_constant_count=codegen.constant_map.size();
+ gdfunc->_constant_count = codegen.constant_map.size();
gdfunc->constants.resize(codegen.constant_map.size());
- gdfunc->_constants_ptr=&gdfunc->constants[0];
- const Variant *K=NULL;
- while((K=codegen.constant_map.next(K))) {
+ gdfunc->_constants_ptr = &gdfunc->constants[0];
+ const Variant *K = NULL;
+ while ((K = codegen.constant_map.next(K))) {
int idx = codegen.constant_map[*K];
- gdfunc->constants[idx]=*K;
+ gdfunc->constants[idx] = *K;
}
} else {
- gdfunc->_constants_ptr=NULL;
- gdfunc->_constant_count=0;
+ gdfunc->_constants_ptr = NULL;
+ gdfunc->_constant_count = 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()) {
+ for (Map<StringName, int>::Element *E = codegen.name_map.front(); E; E = E->next()) {
- gdfunc->global_names[E->get()]=E->key();
+ gdfunc->global_names[E->get()] = E->key();
}
- gdfunc->_global_names_count=gdfunc->global_names.size();
+ gdfunc->_global_names_count = gdfunc->global_names.size();
} else {
gdfunc->_global_names_ptr = NULL;
- gdfunc->_global_names_count =0;
+ gdfunc->_global_names_count = 0;
}
-
if (codegen.opcodes.size()) {
- gdfunc->code=codegen.opcodes;
- gdfunc->_code_ptr=&gdfunc->code[0];
- gdfunc->_code_size=codegen.opcodes.size();
+ gdfunc->code = codegen.opcodes;
+ gdfunc->_code_ptr = &gdfunc->code[0];
+ gdfunc->_code_size = codegen.opcodes.size();
} else {
- gdfunc->_code_ptr=NULL;
- gdfunc->_code_size=0;
+ gdfunc->_code_ptr = NULL;
+ gdfunc->_code_size = 0;
}
if (defarg_addr.size()) {
- gdfunc->default_arguments=defarg_addr;
- gdfunc->_default_arg_count=defarg_addr.size()-1;
- gdfunc->_default_arg_ptr=&gdfunc->default_arguments[0];
+ 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=NULL;
+ gdfunc->_default_arg_count = 0;
+ gdfunc->_default_arg_ptr = NULL;
}
- 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;
+ 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;
#ifdef DEBUG_ENABLED
- if (ScriptDebugger::get_singleton()){
+ if (ScriptDebugger::get_singleton()) {
String signature;
//path
- if (p_script->get_path()!=String())
- signature+=p_script->get_path();
+ if (p_script->get_path() != String())
+ signature += p_script->get_path();
//loc
if (p_func) {
- signature+="::"+itos(p_func->body->line);
+ signature += "::" + itos(p_func->body->line);
} else {
- signature+="::0";
+ signature += "::0";
}
//funciton and class
if (p_class->name) {
- signature+="::"+String(p_class->name)+"."+String(func_name);
+ signature += "::" + String(p_class->name) + "." + String(func_name);
} else {
- signature+="::"+String(func_name);
+ signature += "::" + String(func_name);
}
-
-
- gdfunc->profile.signature=signature;
+ gdfunc->profile.signature = signature;
}
#endif
- gdfunc->_script=p_script;
- gdfunc->source=source;
+ gdfunc->_script = p_script;
+ gdfunc->source = source;
#ifdef DEBUG_ENABLED
{
- gdfunc->func_cname=(String(source)+" - "+String(func_name)).utf8();
- gdfunc->_func_cname=gdfunc->func_cname.get_data();
-
+ 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;
+ 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_func->line;
#endif
} else {
- gdfunc->_initial_line=0;
+ gdfunc->_initial_line = 0;
}
if (codegen.debug_stack)
- gdfunc->stack_debug=codegen.stack_debug;
+ gdfunc->stack_debug = codegen.stack_debug;
if (is_initializer)
- p_script->initializer=gdfunc;
-
+ p_script->initializer = gdfunc;
return OK;
}
-
-
Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state) {
- Map<StringName,Ref<GDScript> > old_subclasses;
+ Map<StringName, Ref<GDScript> > old_subclasses;
if (p_keep_state) {
- old_subclasses=p_script->subclasses;
+ old_subclasses = p_script->subclasses;
}
- p_script->native=Ref<GDNativeClass>();
- p_script->base=Ref<GDScript>();
- p_script->_base=NULL;
+ p_script->native = Ref<GDNativeClass>();
+ p_script->base = Ref<GDScript>();
+ p_script->_base = NULL;
p_script->members.clear();
p_script->constants.clear();
- for (Map<StringName,GDFunction*>::Element *E=p_script->member_functions.front();E;E=E->next()) {
+ for (Map<StringName, GDFunction *>::Element *E = p_script->member_functions.front(); E; E = E->next()) {
memdelete(E->get());
}
p_script->member_functions.clear();
p_script->member_indices.clear();
p_script->member_info.clear();
p_script->_signals.clear();
- p_script->initializer=NULL;
+ p_script->initializer = NULL;
p_script->subclasses.clear();
- p_script->_owner=p_owner;
- p_script->tool=p_class->tool;
- p_script->name=p_class->name;
-
+ p_script->_owner = p_owner;
+ p_script->tool = p_class->tool;
+ p_script->name = p_class->name;
Ref<GDNativeClass> native;
@@ -1656,8 +1613,7 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
Ref<GDScript> script;
-
- if (path!="") {
+ if (path != "") {
//path (and optionally subclasses)
if (path.is_rel_path()) {
@@ -1667,47 +1623,46 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
if (p_owner) {
GDScript *current_class = p_owner;
while (current_class != NULL) {
- base=current_class->get_path();
- if (base=="")
+ base = current_class->get_path();
+ if (base == "")
current_class = current_class->_owner;
else
break;
}
- }
- else {
+ } else {
base = p_script->get_path();
}
- if (base=="" || base.is_rel_path()) {
- _set_error("Could not resolve relative path for parent class: "+path,p_class);
+ if (base == "" || base.is_rel_path()) {
+ _set_error("Could not resolve relative path for parent class: " + path, p_class);
return ERR_FILE_NOT_FOUND;
}
- path=base.get_base_dir().plus_file(path).simplify_path();
+ path = base.get_base_dir().plus_file(path).simplify_path();
}
script = ResourceLoader::load(path);
if (script.is_null()) {
- _set_error("Could not load base class: "+path,p_class);
+ _set_error("Could not load base class: " + path, p_class);
return ERR_FILE_NOT_FOUND;
}
if (!script->valid) {
- _set_error("Script not fully loaded (cyclic preload?): "+path,p_class);
+ _set_error("Script not fully loaded (cyclic preload?): " + path, p_class);
return ERR_BUSY;
}
//print_line("EXTENDS PATH: "+path+" script is "+itos(script.is_valid())+" indices is "+itos(script->member_indices.size())+" valid? "+itos(script->valid));
if (p_class->extends_class.size()) {
- for(int i=0;i<p_class->extends_class.size();i++) {
+ for (int i = 0; i < p_class->extends_class.size(); i++) {
String sub = p_class->extends_class[i];
if (script->subclasses.has(sub)) {
Ref<Script> subclass = script->subclasses[sub]; //avoid reference from dissapearing
- script=subclass;
+ script = subclass;
} else {
- _set_error("Could not find subclass: "+sub,p_class);
+ _set_error("Could not find subclass: " + sub, p_class);
return ERR_FILE_NOT_FOUND;
}
}
@@ -1715,54 +1670,52 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
} else {
- ERR_FAIL_COND_V(p_class->extends_class.size()==0,ERR_BUG);
+ ERR_FAIL_COND_V(p_class->extends_class.size() == 0, ERR_BUG);
//look around for the subclasses
- String base=p_class->extends_class[0];
+ String base = p_class->extends_class[0];
GDScript *p = p_owner;
Ref<GDScript> base_class;
- while(p) {
+ while (p) {
if (p->subclasses.has(base)) {
- base_class=p->subclasses[base];
+ base_class = p->subclasses[base];
break;
}
- p=p->_owner;
+ p = p->_owner;
}
if (base_class.is_valid()) {
- for(int i=1;i<p_class->extends_class.size();i++) {
+ for (int i = 1; i < p_class->extends_class.size(); i++) {
- String subclass=p_class->extends_class[i];
+ String subclass = p_class->extends_class[i];
if (base_class->subclasses.has(subclass)) {
- base_class=base_class->subclasses[subclass];
+ base_class = base_class->subclasses[subclass];
} else {
- _set_error("Could not find subclass: "+subclass,p_class);
+ _set_error("Could not find subclass: " + subclass, p_class);
return ERR_FILE_NOT_FOUND;
}
}
- script=base_class;
-
+ script = base_class;
} else {
- if (p_class->extends_class.size()>1) {
+ if (p_class->extends_class.size() > 1) {
- _set_error("Invalid inheritance (unknown class+subclasses)",p_class);
+ _set_error("Invalid inheritance (unknown class+subclasses)", p_class);
return ERR_FILE_NOT_FOUND;
-
}
//if not found, try engine classes
if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {
- _set_error("Unknown class: '"+base+"'",p_class);
+ _set_error("Unknown class: '" + base + "'", p_class);
return ERR_FILE_NOT_FOUND;
}
@@ -1770,66 +1723,62 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx];
if (!native.is_valid()) {
- _set_error("Global not a class: '"+base+"'",p_class);
+ _set_error("Global not a class: '" + base + "'", p_class);
return ERR_FILE_NOT_FOUND;
}
}
-
-
}
if (script.is_valid()) {
- p_script->base=script;
- p_script->_base=p_script->base.ptr();
- p_script->member_indices=script->member_indices;
+ p_script->base = script;
+ p_script->_base = p_script->base.ptr();
+ p_script->member_indices = script->member_indices;
} else if (native.is_valid()) {
- p_script->native=native;
+ p_script->native = native;
} else {
- _set_error("Could not determine inheritance",p_class);
+ _set_error("Could not determine inheritance", p_class);
return ERR_FILE_NOT_FOUND;
}
-
- }else {
+ } else {
// without extends, implicitly extend Reference
int native_idx = GDScriptLanguage::get_singleton()->get_global_map()["Reference"];
native = GDScriptLanguage::get_singleton()->get_global_array()[native_idx];
ERR_FAIL_COND_V(native.is_null(), ERR_BUG);
- p_script->native=native;
+ p_script->native = native;
}
//print_line("Script: "+p_script->get_path()+" indices: "+itos(p_script->member_indices.size()));
-
- for(int i=0;i<p_class->variables.size();i++) {
+ for (int i = 0; i < p_class->variables.size(); i++) {
StringName name = p_class->variables[i].identifier;
if (p_script->member_indices.has(name)) {
- _set_error("Member '"+name+"' already exists (in current or parent class)",p_class);
+ _set_error("Member '" + name + "' already exists (in current or parent class)", p_class);
return ERR_ALREADY_EXISTS;
}
- if (_is_class_member_property(p_script,name)) {
- _set_error("Member '"+name+"' already exists as a class property.",p_class);
+ if (_is_class_member_property(p_script, name)) {
+ _set_error("Member '" + name + "' already exists as a class property.", p_class);
return ERR_ALREADY_EXISTS;
}
- if (p_class->variables[i]._export.type!=Variant::NIL) {
+ if (p_class->variables[i]._export.type != Variant::NIL) {
- p_script->member_info[name]=p_class->variables[i]._export;
+ p_script->member_info[name] = p_class->variables[i]._export;
#ifdef TOOLS_ENABLED
- if (p_class->variables[i].default_value.get_type()!=Variant::NIL) {
+ 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->member_default_values[name] = p_class->variables[i].default_value;
}
#endif
} else {
- p_script->member_info[name]=PropertyInfo(Variant::NIL,name,PROPERTY_HINT_NONE,"",PROPERTY_USAGE_SCRIPT_VARIABLE);
+ p_script->member_info[name] = PropertyInfo(Variant::NIL, name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
}
//int new_idx = p_script->member_indices.size();
@@ -1837,176 +1786,168 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
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.rpc_mode = p_class->variables[i].rpc_mode;
- p_script->member_indices[name]=minfo;
+ p_script->member_indices[name] = minfo;
p_script->members.insert(name);
#ifdef TOOLS_ENABLED
- p_script->member_lines[name]=p_class->variables[i].line;
+ p_script->member_lines[name] = p_class->variables[i].line;
#endif
-
-
}
- for(int i=0;i<p_class->constant_expressions.size();i++) {
+ for (int i = 0; i < p_class->constant_expressions.size(); i++) {
StringName name = p_class->constant_expressions[i].identifier;
- ERR_CONTINUE( p_class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT );
+ ERR_CONTINUE(p_class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT);
- if (_is_class_member_property(p_script,name)) {
- _set_error("Member '"+name+"' already exists as a class property.",p_class);
+ if (_is_class_member_property(p_script, name)) {
+ _set_error("Member '" + name + "' already exists as a class property.", p_class);
return ERR_ALREADY_EXISTS;
}
- GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode*>(p_class->constant_expressions[i].expression);
+ GDParser::ConstantNode *constant = static_cast<GDParser::ConstantNode *>(p_class->constant_expressions[i].expression);
- p_script->constants.insert(name,constant->value);
- //p_script->constants[constant->value].make_const();
+ p_script->constants.insert(name, constant->value);
+//p_script->constants[constant->value].make_const();
#ifdef TOOLS_ENABLED
- p_script->member_lines[name]=p_class->constant_expressions[i].expression->line;
+ p_script->member_lines[name] = p_class->constant_expressions[i].expression->line;
#endif
-
}
- for(int i=0;i<p_class->_signals.size();i++) {
+ for (int i = 0; i < p_class->_signals.size(); i++) {
StringName name = p_class->_signals[i].name;
GDScript *c = p_script;
- while(c) {
+ while (c) {
if (c->_signals.has(name)) {
- _set_error("Signal '"+name+"' redefined (in current or parent class)",p_class);
+ _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();
+ c = c->base.ptr();
} else {
- c=NULL;
+ c = NULL;
}
}
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);
+ 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->_signals[name]=p_class->_signals[i].arguments;
+ p_script->_signals[name] = p_class->_signals[i].arguments;
}
//parse sub-classes
- for(int i=0;i<p_class->subclasses.size();i++) {
+ for (int i = 0; i < p_class->subclasses.size(); i++) {
StringName name = p_class->subclasses[i]->name;
Ref<GDScript> subclass;
if (old_subclasses.has(name)) {
- subclass=old_subclasses[name];
+ subclass = old_subclasses[name];
} else {
subclass.instance();
}
- Error err = _parse_class(subclass.ptr(),p_script,p_class->subclasses[i],p_keep_state);
+ Error err = _parse_class(subclass.ptr(), p_script, p_class->subclasses[i], 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] = p_class->subclasses[i]->line;
#endif
- p_script->constants.insert(name,subclass); //once parsed, goes to the list of constants
- p_script->subclasses.insert(name,subclass);
-
+ p_script->constants.insert(name, subclass); //once parsed, goes to the list of constants
+ p_script->subclasses.insert(name, subclass);
}
-
//parse methods
- bool has_initializer=false;
- bool has_ready=false;
+ bool has_initializer = false;
+ bool has_ready = false;
- for(int i=0;i<p_class->functions.size();i++) {
+ 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 (!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++) {
+ for (int i = 0; i < p_class->static_functions.size(); i++) {
- Error err = _parse_function(p_script,p_class,p_class->static_functions[i]);
+ Error err = _parse_function(p_script, p_class, p_class->static_functions[i]);
if (err)
return err;
}
-
if (!has_initializer) {
//create a constructor
- Error err = _parse_function(p_script,p_class,NULL);
+ Error err = _parse_function(p_script, p_class, NULL);
if (err)
return err;
}
if (!has_ready && p_class->ready->statements.size()) {
//create a constructor
- Error err = _parse_function(p_script,p_class,NULL,true);
+ Error err = _parse_function(p_script, p_class, NULL, true);
if (err)
return err;
}
#ifdef DEBUG_ENABLED
//validate setters/getters if debug is enabled
- for(int i=0;i<p_class->variables.size();i++) {
+ for (int i = 0; i < p_class->variables.size(); i++) {
if (p_class->variables[i].setter) {
- const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].setter);
+ const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].setter);
if (!E) {
- _set_error("Setter function '"+String(p_class->variables[i].setter)+"' not found in class.",NULL);
- err_line=p_class->variables[i].line;
- err_column=0;
+ _set_error("Setter function '" + String(p_class->variables[i].setter) + "' not found in class.", NULL);
+ err_line = p_class->variables[i].line;
+ err_column = 0;
return ERR_PARSE_ERROR;
}
if (E->get()->is_static()) {
- _set_error("Setter function '"+String(p_class->variables[i].setter)+"' is static.",NULL);
- err_line=p_class->variables[i].line;
- err_column=0;
+ _set_error("Setter function '" + String(p_class->variables[i].setter) + "' is static.", NULL);
+ err_line = p_class->variables[i].line;
+ err_column = 0;
return ERR_PARSE_ERROR;
}
-
}
if (p_class->variables[i].getter) {
- const Map<StringName,GDFunction*>::Element *E=p_script->get_member_functions().find(p_class->variables[i].getter);
+ const Map<StringName, GDFunction *>::Element *E = p_script->get_member_functions().find(p_class->variables[i].getter);
if (!E) {
- _set_error("Getter function '"+String(p_class->variables[i].getter)+"' not found in class.",NULL);
- err_line=p_class->variables[i].line;
- err_column=0;
+ _set_error("Getter function '" + String(p_class->variables[i].getter) + "' not found in class.", NULL);
+ err_line = p_class->variables[i].line;
+ err_column = 0;
return ERR_PARSE_ERROR;
}
if (E->get()->is_static()) {
- _set_error("Getter function '"+String(p_class->variables[i].getter)+"' is static.",NULL);
- err_line=p_class->variables[i].line;
- err_column=0;
+ _set_error("Getter function '" + String(p_class->variables[i].getter) + "' is static.", NULL);
+ err_line = p_class->variables[i].line;
+ err_column = 0;
return ERR_PARSE_ERROR;
}
-
}
}
@@ -2014,96 +1955,88 @@ Error GDCompiler::_parse_class(GDScript *p_script, GDScript *p_owner, const GDPa
if (p_keep_state) {
- print_line("RELOAD KEEP "+p_script->path);
- for (Set<Object*>::Element *E=p_script->instances.front();E;) {
+ print_line("RELOAD KEEP " + p_script->path);
+ for (Set<Object *>::Element *E = p_script->instances.front(); E;) {
- Set<Object*>::Element *N = E->next();
+ Set<Object *>::Element *N = E->next();
ScriptInstance *si = E->get()->get_script_instance();
if (si->is_placeholder()) {
#ifdef TOOLS_ENABLED
- PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance*>(si);
+ PlaceHolderScriptInstance *psi = static_cast<PlaceHolderScriptInstance *>(si);
if (p_script->is_tool()) {
//re-create as an instance
p_script->placeholders.erase(psi); //remove placeholder
- GDInstance* instance = memnew( GDInstance );
- instance->base_ref=E->get()->cast_to<Reference>();
+ GDInstance *instance = memnew(GDInstance);
+ instance->base_ref = E->get()->cast_to<Reference>();
instance->members.resize(p_script->member_indices.size());
- instance->script=Ref<GDScript>(p_script);
- instance->owner=E->get();
+ instance->script = Ref<GDScript>(p_script);
+ instance->owner = E->get();
//needed for hot reloading
- for(Map<StringName,GDScript::MemberInfo>::Element *E=p_script->member_indices.front();E;E=E->next()) {
- instance->member_indices_cache[E->key()]=E->get().index;
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = p_script->member_indices.front(); E; E = E->next()) {
+ instance->member_indices_cache[E->key()] = E->get().index;
}
instance->owner->set_script_instance(instance);
-
/* STEP 2, INITIALIZE AND CONSRTUCT */
Variant::CallError ce;
- p_script->initializer->call(instance,NULL,0,ce);
+ p_script->initializer->call(instance, NULL, 0, ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
+ if (ce.error != Variant::CallError::CALL_OK) {
//well, tough luck, not goinna do anything here
}
}
#endif
} else {
- GDInstance *gi = static_cast<GDInstance*>(si);
+ GDInstance *gi = static_cast<GDInstance *>(si);
gi->reload_members();
}
- E=N;
-
+ E = N;
}
-
-
}
#endif
- p_script->valid=true;
+ p_script->valid = true;
return OK;
}
-Error GDCompiler::compile(const GDParser *p_parser,GDScript *p_script,bool p_keep_state) {
+Error GDCompiler::compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state) {
- err_line=-1;
- err_column=-1;
- error="";
- parser=p_parser;
- const GDParser::Node* root = parser->get_parse_tree();
- ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_INVALID_DATA);
+ err_line = -1;
+ err_column = -1;
+ error = "";
+ parser = p_parser;
+ const GDParser::Node *root = parser->get_parse_tree();
+ ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_INVALID_DATA);
- source=p_script->get_path();
+ source = p_script->get_path();
- Error err = _parse_class(p_script,NULL,static_cast<const GDParser::ClassNode*>(root),p_keep_state);
+ Error err = _parse_class(p_script, NULL, static_cast<const GDParser::ClassNode *>(root), p_keep_state);
if (err)
return err;
return OK;
-
}
String GDCompiler::get_error() const {
return error;
}
-int GDCompiler::get_error_line() const{
+int GDCompiler::get_error_line() const {
return err_line;
}
-int GDCompiler::get_error_column() const{
+int GDCompiler::get_error_column() const {
return err_column;
}
-GDCompiler::GDCompiler()
-{
+GDCompiler::GDCompiler() {
}
-
-
diff --git a/modules/gdscript/gd_compiler.h b/modules/gdscript/gd_compiler.h
index eb6079e8e0..c84bd97246 100644
--- a/modules/gdscript/gd_compiler.h
+++ b/modules/gdscript/gd_compiler.h
@@ -32,7 +32,6 @@
#include "gd_parser.h"
#include "gd_script.h"
-
class GDCompiler {
const GDParser *parser;
@@ -43,83 +42,86 @@ class GDCompiler {
const GDParser::FunctionNode *function_node;
bool debug_stack;
- List< Map<StringName,int> > stack_id_stack;
- Map<StringName,int> stack_identifiers;
-
- List<GDFunction::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;
- GDFunction::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_id_stack.push_back( stack_identifiers );
- if (debug_stack) {
-
- block_identifier_stack.push_back(block_identifiers);
- block_identifiers.clear();
- }
- }
-
- 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()) {
-
- GDFunction::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();
- }
- }
+ List<Map<StringName, int> > stack_id_stack;
+ Map<StringName, int> stack_identifiers;
+
+ List<GDFunction::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;
+ GDFunction::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_id_stack.push_back(stack_identifiers);
+ if (debug_stack) {
+
+ block_identifier_stack.push_back(block_identifiers);
+ block_identifiers.clear();
+ }
+ }
+
+ 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()) {
+
+ GDFunction::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_identifier_pos(const StringName& p_dentifier) const;
- HashMap<Variant,int,VariantHasher,VariantComparator> constant_map;
- Map<StringName,int> name_map;
+ HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
+ Map<StringName, int> name_map;
- int get_name_map_pos(const StringName& p_identifier) {
+ 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;
+ ret = name_map.size();
+ name_map[p_identifier] = ret;
} else {
- ret=name_map[p_identifier];
+ ret = name_map[p_identifier];
}
return ret;
}
- int get_constant_pos(const Variant& p_constant) {
+ 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;
+ constant_map[p_constant] = pos;
return pos;
}
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 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;
+ }
- int current_line;
+ int current_line;
int stack_max;
int call_max;
};
@@ -135,28 +137,27 @@ class GDCompiler {
Ref<GDScript> _parse_class(GDParser::ClassNode *p_class);
#endif
- bool _is_class_member_property(CodeGen & codegen, const StringName & p_name);
- bool _is_class_member_property(GDScript *owner, const StringName & p_name);
+ bool _is_class_member_property(CodeGen &codegen, const StringName &p_name);
+ bool _is_class_member_property(GDScript *owner, const StringName &p_name);
- void _set_error(const String& p_error,const GDParser::Node *p_node);
+ void _set_error(const String &p_error, const GDParser::Node *p_node);
- bool _create_unary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level);
- bool _create_binary_operator(CodeGen& codegen,const GDParser::OperatorNode *on,Variant::Operator op, int p_stack_level,bool p_initializer=false);
+ bool _create_unary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level);
+ bool _create_binary_operator(CodeGen &codegen, const GDParser::OperatorNode *on, Variant::Operator op, int p_stack_level, bool p_initializer = false);
//int _parse_subexpression(CodeGen& codegen,const GDParser::BlockNode *p_block,const GDParser::Node *p_expression);
- int _parse_assign_right_expression(CodeGen& codegen,const GDParser::OperatorNode *p_expression, int p_stack_level);
- int _parse_expression(CodeGen& codegen,const GDParser::Node *p_expression, int p_stack_level,bool p_root=false,bool p_initializer=false);
- Error _parse_block(CodeGen& codegen,const GDParser::BlockNode *p_block,int p_stack_level=0,int p_break_addr=-1,int p_continue_addr=-1);
- Error _parse_function(GDScript *p_script,const GDParser::ClassNode *p_class,const GDParser::FunctionNode *p_func,bool p_for_ready=false);
- Error _parse_class(GDScript *p_script,GDScript *p_owner,const GDParser::ClassNode *p_class,bool p_keep_state);
+ int _parse_assign_right_expression(CodeGen &codegen, const GDParser::OperatorNode *p_expression, int p_stack_level);
+ int _parse_expression(CodeGen &codegen, const GDParser::Node *p_expression, int p_stack_level, bool p_root = false, bool p_initializer = false);
+ Error _parse_block(CodeGen &codegen, const GDParser::BlockNode *p_block, int p_stack_level = 0, int p_break_addr = -1, int p_continue_addr = -1);
+ Error _parse_function(GDScript *p_script, const GDParser::ClassNode *p_class, const GDParser::FunctionNode *p_func, bool p_for_ready = false);
+ Error _parse_class(GDScript *p_script, GDScript *p_owner, const GDParser::ClassNode *p_class, bool p_keep_state);
int err_line;
int err_column;
StringName source;
String error;
public:
-
- Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state=false);
+ Error compile(const GDParser *p_parser, GDScript *p_script, bool p_keep_state = false);
String get_error() const;
int get_error_line() const;
@@ -165,5 +166,4 @@ public:
GDCompiler();
};
-
#endif // COMPILER_H
diff --git a/modules/gdscript/gd_editor.cpp b/modules/gdscript/gd_editor.cpp
index 9dd41847d7..bd428941e0 100644
--- a/modules/gdscript/gd_editor.cpp
+++ b/modules/gdscript/gd_editor.cpp
@@ -26,8 +26,8 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "gd_script.h"
#include "gd_compiler.h"
+#include "gd_script.h"
#include "global_config.h"
#include "os/file_access.h"
@@ -35,73 +35,64 @@ void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const
p_delimiters->push_back("#");
p_delimiters->push_back("\"\"\" \"\"\"");
-
}
void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
p_delimiters->push_back("\" \"");
p_delimiters->push_back("' '");
-
-
}
-Ref<Script> GDScriptLanguage::get_template(const String& p_class_name, const String& p_base_class_name) const {
+Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
- String _template = String()+
- "extends %BASE%\n\n"+
- "# class member variables go here, for example:\n"+
- "# var a = 2\n"+
- "# var b = \"textvar\"\n\n"+
- "func _ready():\n"+
- "\t# Called every time the node is added to the scene.\n"+
- "\t# Initialization here\n"+
- "\tpass\n";
+ String _template = String() +
+ "extends %BASE%\n\n" +
+ "# class member variables go here, for example:\n" +
+ "# var a = 2\n" +
+ "# var b = \"textvar\"\n\n" +
+ "func _ready():\n" +
+ "\t# Called every time the node is added to the scene.\n" +
+ "\t# Initialization here\n" +
+ "\tpass\n";
- _template = _template.replace("%BASE%",p_base_class_name);
+ _template = _template.replace("%BASE%", p_base_class_name);
Ref<GDScript> script;
script.instance();
script->set_source_code(_template);
return script;
-
}
-
-
-
-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) const {
+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) const {
GDParser parser;
- Error err = parser.parse(p_script,p_path.get_base_dir(),true,p_path);
+ Error err = parser.parse(p_script, p_path.get_base_dir(), true, p_path);
if (err) {
- r_line_error=parser.get_error_line();
- r_col_error=parser.get_error_column();
- r_test_error=parser.get_error();
+ r_line_error = parser.get_error_line();
+ r_col_error = parser.get_error_column();
+ r_test_error = parser.get_error();
return false;
} else {
const GDParser::Node *root = parser.get_parse_tree();
- ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false);
+ ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false);
- const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root);
- Map<int,String> funcs;
- for(int i=0;i<cl->functions.size();i++) {
+ const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root);
+ Map<int, String> funcs;
+ for (int i = 0; i < cl->functions.size(); i++) {
- funcs[cl->functions[i]->line]=cl->functions[i]->name;
+ funcs[cl->functions[i]->line] = cl->functions[i]->name;
}
- for(int i=0;i<cl->static_functions.size();i++) {
+ for (int i = 0; i < cl->static_functions.size(); i++) {
- funcs[cl->static_functions[i]->line]=cl->static_functions[i]->name;
+ funcs[cl->static_functions[i]->line] = cl->static_functions[i]->name;
}
- for (Map<int,String>::Element *E=funcs.front();E;E=E->next()) {
+ for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) {
- r_functions->push_back(E->get()+":"+itos(E->key()));
+ r_functions->push_back(E->get() + ":" + itos(E->key()));
}
-
-
}
return true;
@@ -112,142 +103,133 @@ bool GDScriptLanguage::has_named_classes() const {
return false;
}
-int GDScriptLanguage::find_function(const String& p_function,const String& p_code) const {
+int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const {
GDTokenizerText tokenizer;
tokenizer.set_code(p_code);
- int indent=0;
- while(tokenizer.get_token()!=GDTokenizer::TK_EOF && tokenizer.get_token()!=GDTokenizer::TK_ERROR) {
+ int indent = 0;
+ while (tokenizer.get_token() != GDTokenizer::TK_EOF && tokenizer.get_token() != GDTokenizer::TK_ERROR) {
- if (tokenizer.get_token()==GDTokenizer::TK_NEWLINE) {
- indent=tokenizer.get_token_line_indent();
+ if (tokenizer.get_token() == GDTokenizer::TK_NEWLINE) {
+ indent = tokenizer.get_token_line_indent();
}
//print_line("TOKEN: "+String(GDTokenizer::get_token_name(tokenizer.get_token())));
- if (indent==0 && tokenizer.get_token()==GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1)==GDTokenizer::TK_IDENTIFIER) {
+ if (indent == 0 && tokenizer.get_token() == GDTokenizer::TK_PR_FUNCTION && tokenizer.get_token(1) == GDTokenizer::TK_IDENTIFIER) {
String identifier = tokenizer.get_token_identifier(1);
- if (identifier==p_function) {
+ if (identifier == p_function) {
return tokenizer.get_token_line();
}
}
tokenizer.advance();
//print_line("NEXT: "+String(GDTokenizer::get_token_name(tokenizer.get_token())));
-
}
return -1;
}
Script *GDScriptLanguage::create_script() const {
- return memnew( GDScript );
+ return memnew(GDScript);
}
/* DEBUGGER FUNCTIONS */
-
-bool GDScriptLanguage::debug_break_parse(const String& p_file, int p_line,const String& p_error) {
+bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
//break because of parse error
- if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) {
-
- _debug_parse_err_line=p_line;
- _debug_parse_err_file=p_file;
- _debug_error=p_error;
- ScriptDebugger::get_singleton()->debug(this,false);
- return true;
- } else {
- return false;
- }
+ if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) {
+ _debug_parse_err_line = p_line;
+ _debug_parse_err_file = p_file;
+ _debug_error = p_error;
+ ScriptDebugger::get_singleton()->debug(this, false);
+ return true;
+ } else {
+ return false;
+ }
}
-bool GDScriptLanguage::debug_break(const String& p_error,bool p_allow_continue) {
-
- if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) {
+bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
- _debug_parse_err_line=-1;
- _debug_parse_err_file="";
- _debug_error=p_error;
- ScriptDebugger::get_singleton()->debug(this,p_allow_continue);
- return true;
- } else {
- return false;
- }
+ if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) {
+ _debug_parse_err_line = -1;
+ _debug_parse_err_file = "";
+ _debug_error = p_error;
+ ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
+ return true;
+ } else {
+ return false;
+ }
}
String GDScriptLanguage::debug_get_error() const {
- return _debug_error;
+ 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)
+ if (_debug_parse_err_line >= 0)
return _debug_parse_err_line;
- ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,-1);
+ ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
- int l = _debug_call_stack_pos - p_level -1;
-
- return *(_call_stack[l].line);
+ int l = _debug_call_stack_pos - p_level - 1;
+ return *(_call_stack[l].line);
}
String GDScriptLanguage::debug_get_stack_level_function(int p_level) const {
- if (_debug_parse_err_line>=0)
+ 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();
+ 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)
+ 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();
-
+ 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) {
+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)
+ 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;
+ ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
+ int l = _debug_call_stack_pos - p_level - 1;
- GDFunction *f = _call_stack[l].function;
+ GDFunction *f = _call_stack[l].function;
- List<Pair<StringName,int> > locals;
+ List<Pair<StringName, int> > locals;
- 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]);
- }
+ 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) {
+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)
+ 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;
-
+ ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
+ int l = _debug_call_stack_pos - p_level - 1;
GDInstance *instance = _call_stack[l].instance;
@@ -255,25 +237,23 @@ void GDScriptLanguage::debug_get_stack_level_members(int p_level,List<String> *p
return;
Ref<GDScript> script = instance->get_script();
- ERR_FAIL_COND( script.is_null() );
-
+ ERR_FAIL_COND(script.is_null());
- const Map<StringName,GDScript::MemberInfo>& mi = script->debug_get_member_indices();
+ 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()) {
+ 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));
+ p_values->push_back(instance->debug_get_member_by_index(E->get().index));
}
-
}
-void GDScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) {
+void GDScriptLanguage::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 GDScriptLanguage::debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems,int p_max_depth) {
+String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
- if (_debug_parse_err_line>=0)
+ if (_debug_parse_err_line >= 0)
return "";
return "";
}
@@ -283,11 +263,9 @@ void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) con
p_extensions->push_back("gd");
}
-
void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
-
- for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
+ for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
p_functions->push_back(GDFunctions::get_info(GDFunctions::Function(i)));
}
@@ -295,33 +273,33 @@ void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const
//not really "functions", but..
{
MethodInfo mi;
- mi.name="preload:Resource";
- mi.arguments.push_back(PropertyInfo(Variant::STRING,"path"));
- mi.return_val=PropertyInfo(Variant::OBJECT,"",PROPERTY_HINT_RESOURCE_TYPE,"Resource");
+ mi.name = "preload:Resource";
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "path"));
+ mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "Resource");
p_functions->push_back(mi);
}
{
MethodInfo mi;
- mi.name="yield:GDFunctionState";
- mi.arguments.push_back(PropertyInfo(Variant::OBJECT,"object"));
- mi.arguments.push_back(PropertyInfo(Variant::STRING,"signal"));
+ mi.name = "yield:GDFunctionState";
+ mi.arguments.push_back(PropertyInfo(Variant::OBJECT, "object"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "signal"));
mi.default_arguments.push_back(Variant::NIL);
mi.default_arguments.push_back(Variant::STRING);
p_functions->push_back(mi);
}
{
MethodInfo mi;
- mi.name="assert";
- mi.arguments.push_back(PropertyInfo(Variant::BOOL,"condition"));
+ mi.name = "assert";
+ mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition"));
p_functions->push_back(mi);
}
}
-void GDScriptLanguage::get_public_constants(List<Pair<String,Variant> > *p_constants) const {
+void GDScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_constants) const {
- Pair<String,Variant> pi;
- pi.first="PI";
- pi.second=Math_PI;
+ Pair<String, Variant> pi;
+ pi.first = "PI";
+ pi.second = Math_PI;
p_constants->push_back(pi);
Pair<String, Variant> infinity;
@@ -335,22 +313,21 @@ void GDScriptLanguage::get_public_constants(List<Pair<String,Variant> > *p_const
p_constants->push_back(nan);
}
-String GDScriptLanguage::make_function(const String& p_class,const String& p_name,const PoolStringArray& p_args) const {
+String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const {
- String s="func "+p_name+"(";
+ String s = "func " + p_name + "(";
if (p_args.size()) {
- s+=" ";
- for(int i=0;i<p_args.size();i++) {
- if (i>0)
- s+=", ";
- s+=p_args[i].get_slice(":",0);
+ s += " ";
+ for (int i = 0; i < p_args.size(); i++) {
+ if (i > 0)
+ s += ", ";
+ s += p_args[i].get_slice(":", 0);
}
- s+=" ";
+ s += " ";
}
- s+="):\n\tpass # replace with function body\n";
+ s += "):\n\tpass # replace with function body\n";
return s;
-
}
#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
@@ -361,17 +338,14 @@ struct GDCompletionIdentifier {
Ref<GDScript> script;
Variant::Type type;
Variant value; //im case there is a value, also return it
-
};
-
-
-static GDCompletionIdentifier _get_type_from_variant(const Variant& p_variant) {
+static GDCompletionIdentifier _get_type_from_variant(const Variant &p_variant) {
GDCompletionIdentifier t;
- t.type=p_variant.get_type();
- t.value=p_variant;
- if (p_variant.get_type()==Variant::OBJECT) {
+ t.type = p_variant.get_type();
+ t.value = p_variant;
+ if (p_variant.get_type() == Variant::OBJECT) {
Object *obj = p_variant;
if (obj) {
/*
@@ -380,19 +354,19 @@ static GDCompletionIdentifier _get_type_from_variant(const Variant& p_variant) {
t.value=Variant();
} else {
*/
- t.obj_type=obj->get_class();
+ t.obj_type = obj->get_class();
//}
}
}
return t;
}
-static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo& p_info) {
+static GDCompletionIdentifier _get_type_from_pinfo(const PropertyInfo &p_info) {
GDCompletionIdentifier t;
- t.type=p_info.type;
- if (p_info.hint==PROPERTY_HINT_RESOURCE_TYPE) {
- t.obj_type=p_info.hint_string;
+ t.type = p_info.type;
+ if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ t.obj_type = p_info.hint_string;
}
return t;
}
@@ -402,15 +376,11 @@ struct GDCompletionContext {
const GDParser::ClassNode *_class;
const GDParser::FunctionNode *function;
const GDParser::BlockNode *block;
- Object* base;
+ Object *base;
String base_path;
-
};
-
-static Ref<Reference> _get_parent_class(GDCompletionContext& context) {
-
-
+static Ref<Reference> _get_parent_class(GDCompletionContext &context) {
if (context._class->extends_used) {
//do inheritance
@@ -419,12 +389,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) {
Ref<GDScript> script;
Ref<GDNativeClass> native;
- if (path!="") {
+ if (path != "") {
//path (and optionally subclasses)
if (path.is_rel_path()) {
- path=context.base_path.plus_file(path);
+ path = context.base_path.plus_file(path);
}
if (ScriptCodeCompletionCache::get_sigleton())
@@ -443,12 +413,12 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) {
if (context._class->extends_class.size()) {
- for(int i=0;i<context._class->extends_class.size();i++) {
+ for (int i = 0; i < context._class->extends_class.size(); i++) {
String sub = context._class->extends_class[i];
if (script->get_subclasses().has(sub)) {
- script=script->get_subclasses()[sub];
+ script = script->get_subclasses()[sub];
} else {
return REF();
@@ -461,17 +431,16 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) {
} else {
- if (context._class->extends_class.size()==0) {
+ if (context._class->extends_class.size() == 0) {
ERR_PRINT("BUG");
return REF();
}
- String base=context._class->extends_class[0];
+ String base = context._class->extends_class[0];
- if (context._class->extends_class.size()>1) {
+ if (context._class->extends_class.size() > 1) {
return REF();
-
}
//if not found, try engine classes
if (!GDScriptLanguage::get_singleton()->get_global_map().has(base)) {
@@ -482,22 +451,19 @@ static Ref<Reference> _get_parent_class(GDCompletionContext& context) {
int base_idx = GDScriptLanguage::get_singleton()->get_global_map()[base];
native = GDScriptLanguage::get_singleton()->get_global_array()[base_idx];
return native;
-
}
-
}
return Ref<Reference>();
}
-
-static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) {
+static GDCompletionIdentifier _get_native_class(GDCompletionContext &context) {
//eeh...
GDCompletionIdentifier id;
- id.type=Variant::NIL;
+ id.type = Variant::NIL;
- REF pc = _get_parent_class(context);
+ REF pc = _get_parent_class(context);
if (!pc.is_valid()) {
return id;
}
@@ -507,204 +473,191 @@ static GDCompletionIdentifier _get_native_class(GDCompletionContext& context) {
if (s.is_null() && nc.is_null()) {
return id;
}
- while(!s.is_null()) {
- nc=s->get_native();
- s=s->get_base();
+ while (!s.is_null()) {
+ nc = s->get_native();
+ s = s->get_base();
}
if (nc.is_null()) {
return id;
}
-
-
- id.type=Variant::OBJECT;
+ id.type = Variant::OBJECT;
if (context.base)
- id.value=context.base;
- id.obj_type=nc->get_name();
+ id.value = context.base;
+ id.obj_type = nc->get_name();
return id;
}
-static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type);
-
+static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type);
-static bool _guess_expression_type(GDCompletionContext& context,const GDParser::Node* p_node,int p_line,GDCompletionIdentifier &r_type) {
+static bool _guess_expression_type(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, GDCompletionIdentifier &r_type) {
+ if (p_node->type == GDParser::Node::TYPE_CONSTANT) {
- if (p_node->type==GDParser::Node::TYPE_CONSTANT) {
+ const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(p_node);
- const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(p_node);
-
- r_type=_get_type_from_variant(cn->value);
+ r_type = _get_type_from_variant(cn->value);
return true;
- } else if (p_node->type==GDParser::Node::TYPE_DICTIONARY) {
-
- r_type.type=Variant::DICTIONARY;
+ } else if (p_node->type == GDParser::Node::TYPE_DICTIONARY) {
+ r_type.type = Variant::DICTIONARY;
//what the heck, fill it anyway
const GDParser::DictionaryNode *an = static_cast<const GDParser::DictionaryNode *>(p_node);
Dictionary d;
- for(int i=0;i<an->elements.size();i++) {
+ for (int i = 0; i < an->elements.size(); i++) {
GDCompletionIdentifier k;
- if (_guess_expression_type(context,an->elements[i].key,p_line,k) && k.value.get_type()!=Variant::NIL) {
+ if (_guess_expression_type(context, an->elements[i].key, p_line, k) && k.value.get_type() != Variant::NIL) {
GDCompletionIdentifier v;
- if (_guess_expression_type(context,an->elements[i].value,p_line,v)) {
- d[k.value]=v.value;
+ if (_guess_expression_type(context, an->elements[i].value, p_line, v)) {
+ d[k.value] = v.value;
}
-
}
}
- r_type.value=d;
+ r_type.value = d;
return true;
- } else if (p_node->type==GDParser::Node::TYPE_ARRAY) {
+ } else if (p_node->type == GDParser::Node::TYPE_ARRAY) {
- r_type.type=Variant::ARRAY;
+ r_type.type = Variant::ARRAY;
//what the heck, fill it anyway
const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(p_node);
Array arr;
arr.resize(an->elements.size());
- for(int i=0;i<an->elements.size();i++) {
+ for (int i = 0; i < an->elements.size(); i++) {
GDCompletionIdentifier ci;
- if (_guess_expression_type(context,an->elements[i],p_line,ci)) {
- arr[i]=ci.value;
+ if (_guess_expression_type(context, an->elements[i], p_line, ci)) {
+ arr[i] = ci.value;
}
}
- r_type.value=arr;
+ r_type.value = arr;
return true;
- } else if (p_node->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
+ } else if (p_node->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
- MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode*>(p_node)->function);
- r_type=_get_type_from_pinfo(mi.return_val);
+ MethodInfo mi = GDFunctions::get_info(static_cast<const GDParser::BuiltInFunctionNode *>(p_node)->function);
+ r_type = _get_type_from_pinfo(mi.return_val);
return true;
- } else if (p_node->type==GDParser::Node::TYPE_IDENTIFIER) {
+ } else if (p_node->type == GDParser::Node::TYPE_IDENTIFIER) {
- return _guess_identifier_type(context,p_line-1,static_cast<const GDParser::IdentifierNode *>(p_node)->name,r_type);
- } else if (p_node->type==GDParser::Node::TYPE_SELF) {
+ return _guess_identifier_type(context, p_line - 1, static_cast<const GDParser::IdentifierNode *>(p_node)->name, r_type);
+ } else if (p_node->type == GDParser::Node::TYPE_SELF) {
//eeh...
- r_type=_get_native_class(context);
- return r_type.type!=Variant::NIL;
-
- } else if (p_node->type==GDParser::Node::TYPE_OPERATOR) {
+ r_type = _get_native_class(context);
+ return r_type.type != Variant::NIL;
+ } else if (p_node->type == GDParser::Node::TYPE_OPERATOR) {
const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node);
- if (op->op==GDParser::OperatorNode::OP_CALL) {
- if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) {
+ if (op->op == GDParser::OperatorNode::OP_CALL) {
+ if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) {
const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]);
- r_type.type=tn->vtype;
+ r_type.type = tn->vtype;
return true;
- } else if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
-
+ } else if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
const GDParser::BuiltInFunctionNode *bin = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]);
- return _guess_expression_type(context,bin,p_line,r_type);
-
- } else if (op->arguments.size()>1 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) {
+ return _guess_expression_type(context, bin, p_line, r_type);
+ } else if (op->arguments.size() > 1 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) {
GDCompletionIdentifier base;
- if (!_guess_expression_type(context,op->arguments[0],p_line,base))
+ if (!_guess_expression_type(context, op->arguments[0], p_line, base))
return false;
StringName id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name;
- if (base.type==Variant::OBJECT) {
+ if (base.type == Variant::OBJECT) {
- if (id.operator String()=="new" && base.value.get_type()==Variant::OBJECT) {
+ if (id.operator String() == "new" && base.value.get_type() == Variant::OBJECT) {
Object *obj = base.value;
if (obj && obj->cast_to<GDNativeClass>()) {
GDNativeClass *gdnc = obj->cast_to<GDNativeClass>();
- r_type.type=Variant::OBJECT;
- r_type.value=Variant();
- r_type.obj_type=gdnc->get_name();
+ r_type.type = Variant::OBJECT;
+ r_type.value = Variant();
+ r_type.obj_type = gdnc->get_name();
return true;
}
}
- if (ClassDB::has_method(base.obj_type,id)) {
+ if (ClassDB::has_method(base.obj_type, id)) {
#ifdef TOOLS_ENABLED
- MethodBind *mb = ClassDB::get_method(base.obj_type,id);
+ MethodBind *mb = ClassDB::get_method(base.obj_type, id);
PropertyInfo pi = mb->get_argument_info(-1);
//try calling the function if constant and all args are constant, should not crash..
Object *baseptr = base.value;
+ if (mb->is_const() && pi.type == Variant::OBJECT) {
- if (mb->is_const() && pi.type==Variant::OBJECT) {
-
- bool all_valid=true;
+ bool all_valid = true;
Vector<Variant> args;
- for(int i=2;i<op->arguments.size();i++) {
+ for (int i = 2; i < op->arguments.size(); i++) {
GDCompletionIdentifier arg;
- if (_guess_expression_type(context,op->arguments[i],p_line,arg)) {
- if (arg.value.get_type()!=Variant::NIL && arg.value.get_type()!=Variant::OBJECT) { // calling with object seems dangerous, i don' t know
+ if (_guess_expression_type(context, op->arguments[i], p_line, arg)) {
+ if (arg.value.get_type() != Variant::NIL && arg.value.get_type() != Variant::OBJECT) { // calling with object seems dangerous, i don' t know
args.push_back(arg.value);
} else {
- all_valid=false;
+ all_valid = false;
break;
}
} else {
- all_valid=false;
+ all_valid = false;
}
}
- if (all_valid && String(id)=="get_node" && ClassDB::is_parent_class(base.obj_type,"Node") && args.size()) {
+ if (all_valid && String(id) == "get_node" && ClassDB::is_parent_class(base.obj_type, "Node") && args.size()) {
- String arg1=args[0];
+ String arg1 = args[0];
if (arg1.begins_with("/root/")) {
- String which = arg1.get_slice("/",2);
- if (which!="") {
+ String which = arg1.get_slice("/", 2);
+ if (which != "") {
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
//print_line("find singleton");
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
String s = E->get().name;
if (!s.begins_with("autoload/"))
continue;
//print_line("found "+s);
- String name = s.get_slice("/",1);
+ String name = s.get_slice("/", 1);
//print_line("name: "+name+", which: "+which);
- if (name==which) {
+ if (name == which) {
String script = GlobalConfig::get_singleton()->get(s);
if (!script.begins_with("res://")) {
- script="res://"+script;
+ 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";
+ script = script.get_basename() + ".gd";
}
if (FileAccess::exists(script)) {
//print_line("is a script");
-
Ref<Script> scr;
if (ScriptCodeCompletionCache::get_sigleton())
scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script);
else
scr = ResourceLoader::load(script);
-
- r_type.obj_type="Node";
- r_type.type=Variant::OBJECT;
- r_type.script=scr;
- r_type.value=Variant();
+ r_type.obj_type = "Node";
+ r_type.type = Variant::OBJECT;
+ r_type.script = scr;
+ r_type.value = Variant();
return true;
-
}
}
}
@@ -712,40 +665,34 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser::
}
}
-
-
if (baseptr) {
if (all_valid) {
- Vector<const Variant*> argptr;
- for(int i=0;i<args.size();i++) {
+ Vector<const Variant *> argptr;
+ for (int i = 0; i < args.size(); i++) {
argptr.push_back(&args[i]);
}
Variant::CallError ce;
- Variant ret=mb->call(baseptr,argptr.ptr(),argptr.size(),ce);
+ Variant ret = mb->call(baseptr, argptr.ptr(), argptr.size(), ce);
+ if (ce.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
- if (ce.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
+ if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != NULL) {
- if (ret.get_type()!=Variant::OBJECT || ret.operator Object*()!=NULL) {
-
- r_type=_get_type_from_variant(ret);
+ r_type = _get_type_from_variant(ret);
return true;
}
}
-
}
}
}
- r_type.type=pi.type;
- if (pi.hint==PROPERTY_HINT_RESOURCE_TYPE) {
- r_type.obj_type=pi.hint_string;
+ r_type.type = pi.type;
+ if (pi.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ r_type.obj_type = pi.hint_string;
}
-
-
return true;
#else
return false;
@@ -756,115 +703,108 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser::
} else {
//method for some variant..
Variant::CallError ce;
- Variant v = Variant::construct(base.type,NULL,0,ce);
+ Variant v = Variant::construct(base.type, NULL, 0, ce);
List<MethodInfo> mi;
v.get_method_list(&mi);
- for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {
-
- if (!E->get().name.begins_with("_") && E->get().name==id.operator String()) {
+ for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) {
+ if (!E->get().name.begins_with("_") && E->get().name == id.operator String()) {
MethodInfo mi = E->get();
- r_type.type=mi.return_val.type;
- if (mi.return_val.hint==PROPERTY_HINT_RESOURCE_TYPE) {
- r_type.obj_type=mi.return_val.hint_string;
+ r_type.type = mi.return_val.type;
+ if (mi.return_val.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ r_type.obj_type = mi.return_val.hint_string;
}
return true;
}
}
-
}
-
-
}
- } else if (op->op==GDParser::OperatorNode::OP_INDEX || op->op==GDParser::OperatorNode::OP_INDEX_NAMED) {
+ } else if (op->op == GDParser::OperatorNode::OP_INDEX || op->op == GDParser::OperatorNode::OP_INDEX_NAMED) {
GDCompletionIdentifier p1;
GDCompletionIdentifier p2;
+ if (op->op == GDParser::OperatorNode::OP_INDEX_NAMED) {
-
- if (op->op==GDParser::OperatorNode::OP_INDEX_NAMED) {
-
- if (op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) {
- String id = static_cast<const GDParser::IdentifierNode*>(op->arguments[1])->name;
- p2.type=Variant::STRING;
- p2.value=id;
+ if (op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) {
+ String id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1])->name;
+ p2.type = Variant::STRING;
+ p2.value = id;
}
} else {
if (op->arguments[1]) {
- if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) {
+ if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) {
return false;
}
}
}
- if (op->arguments[0]->type==GDParser::Node::TYPE_ARRAY) {
+ if (op->arguments[0]->type == GDParser::Node::TYPE_ARRAY) {
const GDParser::ArrayNode *an = static_cast<const GDParser::ArrayNode *>(op->arguments[0]);
if (p2.value.is_num()) {
int index = p2.value;
- if (index<0 || index>=an->elements.size())
+ if (index < 0 || index >= an->elements.size())
return false;
- return _guess_expression_type(context,an->elements[index],p_line,r_type);
+ return _guess_expression_type(context, an->elements[index], p_line, r_type);
}
- } else if (op->arguments[0]->type==GDParser::Node::TYPE_DICTIONARY) {
+ } else if (op->arguments[0]->type == GDParser::Node::TYPE_DICTIONARY) {
const GDParser::DictionaryNode *dn = static_cast<const GDParser::DictionaryNode *>(op->arguments[0]);
- if (p2.value.get_type()==Variant::NIL)
+ if (p2.value.get_type() == Variant::NIL)
return false;
- for(int i=0;i<dn->elements.size();i++) {
+ for (int i = 0; i < dn->elements.size(); i++) {
GDCompletionIdentifier k;
- if (!_guess_expression_type(context,dn->elements[i].key,p_line,k)) {
+ if (!_guess_expression_type(context, dn->elements[i].key, p_line, k)) {
return false;
}
- if (k.value.get_type()==Variant::NIL)
+ if (k.value.get_type() == Variant::NIL)
return false;
- if (k.value==p2.value) {
+ if (k.value == p2.value) {
- return _guess_expression_type(context,dn->elements[i].value,p_line,r_type);
+ return _guess_expression_type(context, dn->elements[i].value, p_line, r_type);
}
}
} else {
if (op->arguments[0]) {
- if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) {
+ if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) {
return false;
}
-
}
- if (p1.value.get_type()==Variant::OBJECT) {
+ if (p1.value.get_type() == Variant::OBJECT) {
//??
- } else if (p1.value.get_type()!=Variant::NIL) {
+ } else if (p1.value.get_type() != Variant::NIL) {
bool valid;
- Variant ret = p1.value.get(p2.value,&valid);
+ Variant ret = p1.value.get(p2.value, &valid);
if (valid) {
- r_type=_get_type_from_variant(ret);
+ r_type = _get_type_from_variant(ret);
return true;
}
} else {
- if (p1.type!=Variant::NIL) {
+ if (p1.type != Variant::NIL) {
Variant::CallError ce;
- Variant base = Variant::construct(p1.type,NULL,0,ce);
+ Variant base = Variant::construct(p1.type, NULL, 0, ce);
bool valid;
- Variant ret = base.get(p2.value,&valid);
+ Variant ret = base.get(p2.value, &valid);
if (valid) {
- r_type=_get_type_from_variant(ret);
+ r_type = _get_type_from_variant(ret);
return true;
}
}
@@ -873,127 +813,115 @@ static bool _guess_expression_type(GDCompletionContext& context,const GDParser::
} else {
-
Variant::Operator vop = Variant::OP_MAX;
- switch(op->op) {
- case GDParser::OperatorNode::OP_ADD: vop=Variant::OP_ADD; break;
- case GDParser::OperatorNode::OP_SUB: vop=Variant::OP_SUBSTRACT; break;
- case GDParser::OperatorNode::OP_MUL: vop=Variant::OP_MULTIPLY; break;
- case GDParser::OperatorNode::OP_DIV: vop=Variant::OP_DIVIDE; break;
- case GDParser::OperatorNode::OP_MOD: vop=Variant::OP_MODULE; break;
- case GDParser::OperatorNode::OP_SHIFT_LEFT: vop=Variant::OP_SHIFT_LEFT; break;
- case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop=Variant::OP_SHIFT_RIGHT; break;
- case GDParser::OperatorNode::OP_BIT_AND: vop=Variant::OP_BIT_AND; break;
- case GDParser::OperatorNode::OP_BIT_OR: vop=Variant::OP_BIT_OR; break;
- case GDParser::OperatorNode::OP_BIT_XOR: vop=Variant::OP_BIT_XOR; break;
- default:{}
-
+ switch (op->op) {
+ case GDParser::OperatorNode::OP_ADD: vop = Variant::OP_ADD; break;
+ case GDParser::OperatorNode::OP_SUB: vop = Variant::OP_SUBSTRACT; break;
+ case GDParser::OperatorNode::OP_MUL: vop = Variant::OP_MULTIPLY; break;
+ case GDParser::OperatorNode::OP_DIV: vop = Variant::OP_DIVIDE; break;
+ case GDParser::OperatorNode::OP_MOD: vop = Variant::OP_MODULE; break;
+ case GDParser::OperatorNode::OP_SHIFT_LEFT: vop = Variant::OP_SHIFT_LEFT; break;
+ case GDParser::OperatorNode::OP_SHIFT_RIGHT: vop = Variant::OP_SHIFT_RIGHT; break;
+ case GDParser::OperatorNode::OP_BIT_AND: vop = Variant::OP_BIT_AND; break;
+ case GDParser::OperatorNode::OP_BIT_OR: vop = Variant::OP_BIT_OR; break;
+ case GDParser::OperatorNode::OP_BIT_XOR: vop = Variant::OP_BIT_XOR; break;
+ default: {}
}
-
-
- if (vop==Variant::OP_MAX)
+ if (vop == Variant::OP_MAX)
return false;
-
-
GDCompletionIdentifier p1;
GDCompletionIdentifier p2;
if (op->arguments[0]) {
- if (!_guess_expression_type(context,op->arguments[0],p_line,p1)) {
+ if (!_guess_expression_type(context, op->arguments[0], p_line, p1)) {
return false;
}
-
}
- if (op->arguments.size()>1) {
- if (!_guess_expression_type(context,op->arguments[1],p_line,p2)) {
+ if (op->arguments.size() > 1) {
+ if (!_guess_expression_type(context, op->arguments[1], p_line, p2)) {
return false;
}
}
Variant::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,NULL,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,NULL,0,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, NULL, 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, NULL, 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 || vop == Variant::OP_MODULE) && v2.get_type() == Variant::INT) {
+ v2 = 1;
+ v2_use_value = false;
}
- if (vop==Variant::OP_DIVIDE && v2.get_type()==Variant::REAL) {
- v2=1.0;
- v2_use_value=false;
+ if (vop == Variant::OP_DIVIDE && v2.get_type() == Variant::REAL) {
+ v2 = 1.0;
+ v2_use_value = false;
}
Variant r;
bool valid;
- Variant::evaluate(vop,v1,v2,r,valid);
+ Variant::evaluate(vop, v1, v2, r, valid);
if (!valid)
return false;
- r_type.type=r.get_type();
+ r_type.type = r.get_type();
if (v1_use_value && v2_use_value)
- r_type.value=r;
+ r_type.value = r;
return true;
-
}
-
}
return false;
}
-
-static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) {
-
+static bool _guess_identifier_type_in_block(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) {
GDCompletionIdentifier gdi = _get_native_class(context);
- if (gdi.obj_type!=StringName()) {
+ if (gdi.obj_type != StringName()) {
bool valid;
- Variant::Type t = ClassDB::get_property_type(gdi.obj_type,p_identifier,&valid);
- if (t!=Variant::NIL && valid) {
- r_type.type=t;
+ Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_identifier, &valid);
+ if (t != Variant::NIL && valid) {
+ r_type.type = t;
return true;
}
}
- const GDParser::Node *last_assign=NULL;
- int last_assign_line=-1;
+ const GDParser::Node *last_assign = NULL;
+ int last_assign_line = -1;
- for (int i=0;i<context.block->statements.size();i++) {
+ for (int i = 0; i < context.block->statements.size(); i++) {
- if (context.block->statements[i]->line>p_line)
+ if (context.block->statements[i]->line > p_line)
continue;
+ if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) {
- if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) {
-
- const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]);
+ const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]);
- if (lv->assign && lv->name==p_identifier) {
+ if (lv->assign && lv->name == p_identifier) {
- last_assign=lv->assign;
- last_assign_line=context.block->statements[i]->line;
+ last_assign = lv->assign;
+ last_assign_line = context.block->statements[i]->line;
}
}
- if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) {
+ if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) {
const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(context.block->statements[i]);
- if (op->op==GDParser::OperatorNode::OP_ASSIGN) {
+ if (op->op == GDParser::OperatorNode::OP_ASSIGN) {
- if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) {
+ if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) {
const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]);
- if (id->name==p_identifier) {
+ if (id->name == p_identifier) {
- last_assign=op->arguments[1];
- last_assign_line=context.block->statements[i]->line;
+ last_assign = op->arguments[1];
+ last_assign_line = context.block->statements[i]->line;
}
}
}
@@ -1003,20 +931,18 @@ static bool _guess_identifier_type_in_block(GDCompletionContext& context,int p_l
//use the last assignment, (then backwards?)
if (last_assign) {
- return _guess_expression_type(context,last_assign,last_assign_line,r_type);
+ return _guess_expression_type(context, last_assign, last_assign_line, r_type);
}
-
return false;
}
+static bool _guess_identifier_from_assignment_in_function(GDCompletionContext &context, int p_src_line, const StringName &p_identifier, const StringName &p_function, GDCompletionIdentifier &r_type) {
-static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& context, int p_src_line, const StringName& p_identifier, const StringName& p_function,GDCompletionIdentifier &r_type) {
-
- const GDParser::FunctionNode* func=NULL;
- for(int i=0;i<context._class->functions.size();i++) {
- if (context._class->functions[i]->name==p_function) {
- func=context._class->functions[i];
+ const GDParser::FunctionNode *func = NULL;
+ for (int i = 0; i < context._class->functions.size(); i++) {
+ if (context._class->functions[i]->name == p_function) {
+ func = context._class->functions[i];
break;
}
}
@@ -1024,23 +950,23 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c
if (!func)
return false;
- for(int i=0;i<func->body->statements.size();i++) {
+ for (int i = 0; i < func->body->statements.size(); i++) {
if (func->body->statements[i]->line == p_src_line) {
break;
}
- if (func->body->statements[i]->type==GDParser::BlockNode::TYPE_OPERATOR) {
+ if (func->body->statements[i]->type == GDParser::BlockNode::TYPE_OPERATOR) {
const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->body->statements[i]);
- if (op->op==GDParser::OperatorNode::OP_ASSIGN) {
+ if (op->op == GDParser::OperatorNode::OP_ASSIGN) {
- if (op->arguments.size() && op->arguments[0]->type==GDParser::Node::TYPE_IDENTIFIER) {
+ if (op->arguments.size() && op->arguments[0]->type == GDParser::Node::TYPE_IDENTIFIER) {
const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[0]);
- if (id->name==p_identifier) {
+ if (id->name == p_identifier) {
- return _guess_expression_type(context,op->arguments[1],func->body->statements[i]->line,r_type);
+ return _guess_expression_type(context, op->arguments[1], func->body->statements[i]->line, r_type);
}
}
}
@@ -1050,66 +976,62 @@ static bool _guess_identifier_from_assignment_in_function(GDCompletionContext& c
return false;
}
-static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const StringName& p_identifier,GDCompletionIdentifier &r_type) {
+static bool _guess_identifier_type(GDCompletionContext &context, int p_line, const StringName &p_identifier, GDCompletionIdentifier &r_type) {
//go to block first
+ const GDParser::BlockNode *block = context.block;
- const GDParser::BlockNode *block=context.block;
-
- while(block) {
+ while (block) {
GDCompletionContext c = context;
- c.block=block;
+ c.block = block;
- if (_guess_identifier_type_in_block(c,p_line,p_identifier,r_type)) {
+ if (_guess_identifier_type_in_block(c, p_line, p_identifier, r_type)) {
return true;
}
- block=block->parent_block;
+ block = block->parent_block;
}
//guess from argument if virtual
- if (context.function && context.function->name!=StringName()) {
+ if (context.function && context.function->name != StringName()) {
int argindex = -1;
- for(int i=0;i<context.function->arguments.size();i++) {
+ for (int i = 0; i < context.function->arguments.size(); i++) {
- if (context.function->arguments[i]==p_identifier) {
- argindex=i;
+ if (context.function->arguments[i] == p_identifier) {
+ argindex = i;
break;
}
-
}
- if (argindex!=-1) {
- GDCompletionIdentifier id =_get_native_class(context);
- if (id.type==Variant::OBJECT && id.obj_type!=StringName()) {
+ if (argindex != -1) {
+ GDCompletionIdentifier id = _get_native_class(context);
+ if (id.type == Variant::OBJECT && id.obj_type != StringName()) {
//this kinda sucks but meh
List<MethodInfo> vmethods;
- ClassDB::get_virtual_methods(id.obj_type,&vmethods);
- for (List<MethodInfo>::Element *E=vmethods.front();E;E=E->next()) {
-
+ ClassDB::get_virtual_methods(id.obj_type, &vmethods);
+ for (List<MethodInfo>::Element *E = vmethods.front(); E; E = E->next()) {
- if (E->get().name==context.function->name && argindex<E->get().arguments.size()) {
+ if (E->get().name == context.function->name && argindex < E->get().arguments.size()) {
- PropertyInfo arg=E->get().arguments[argindex];
+ PropertyInfo arg = E->get().arguments[argindex];
int scp = arg.name.find(":");
- if (scp!=-1) {
+ if (scp != -1) {
-
- r_type.type=Variant::OBJECT;
- r_type.obj_type=arg.name.substr(scp+1,arg.name.length());
+ r_type.type = Variant::OBJECT;
+ r_type.obj_type = arg.name.substr(scp + 1, arg.name.length());
return true;
} else {
- r_type.type=arg.type;
- if (arg.hint==PROPERTY_HINT_RESOURCE_TYPE)
- r_type.obj_type=arg.hint_string;
+ r_type.type = arg.type;
+ if (arg.hint == PROPERTY_HINT_RESOURCE_TYPE)
+ r_type.obj_type = arg.hint_string;
return true;
}
}
@@ -1120,40 +1042,40 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const
//guess type in constant
- for(int i=0;i<context._class->constant_expressions.size();i++) {
+ for (int i = 0; i < context._class->constant_expressions.size(); i++) {
- if (context._class->constant_expressions[i].identifier==p_identifier) {
+ if (context._class->constant_expressions[i].identifier == p_identifier) {
- ERR_FAIL_COND_V( context._class->constant_expressions[i].expression->type!=GDParser::Node::TYPE_CONSTANT, false );
- r_type=_get_type_from_variant(static_cast<const GDParser::ConstantNode*>(context._class->constant_expressions[i].expression)->value );
+ ERR_FAIL_COND_V(context._class->constant_expressions[i].expression->type != GDParser::Node::TYPE_CONSTANT, false);
+ r_type = _get_type_from_variant(static_cast<const GDParser::ConstantNode *>(context._class->constant_expressions[i].expression)->value);
return true;
}
}
if (!(context.function && context.function->_static)) {
- for(int i=0;i<context._class->variables.size();i++) {
+ for (int i = 0; i < context._class->variables.size(); i++) {
- if (context._class->variables[i].identifier==p_identifier) {
+ if (context._class->variables[i].identifier == p_identifier) {
- if (context._class->variables[i]._export.type!=Variant::NIL) {
+ if (context._class->variables[i]._export.type != Variant::NIL) {
- r_type=_get_type_from_pinfo(context._class->variables[i]._export);
+ r_type = _get_type_from_pinfo(context._class->variables[i]._export);
return true;
} else if (context._class->variables[i].expression) {
- bool rtype = _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type);
- if (rtype && r_type.type!=Variant::NIL)
+ bool rtype = _guess_expression_type(context, context._class->variables[i].expression, context._class->variables[i].line, r_type);
+ if (rtype && r_type.type != Variant::NIL)
return true;
//return _guess_expression_type(context,context._class->variables[i].expression,context._class->variables[i].line,r_type);
}
//try to guess from assignment in construtor or _ready
- if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_ready",r_type))
+ if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_ready", r_type))
return true;
- if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_enter_tree",r_type))
+ if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_enter_tree", r_type))
return true;
- if (_guess_identifier_from_assignment_in_function(context,p_line+1,p_identifier,"_init",r_type))
+ if (_guess_identifier_from_assignment_in_function(context, p_line + 1, p_identifier, "_init", r_type))
return true;
return false;
@@ -1165,115 +1087,107 @@ static bool _guess_identifier_type(GDCompletionContext& context,int p_line,const
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ 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_identifier)) {
+ String name = s.get_slice("/", 1);
+ if (name == String(p_identifier)) {
String path = GlobalConfig::get_singleton()->get(s);
if (path.begins_with("*")) {
- String script =path.substr(1,path.length());
+ 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";
+ script = script.get_basename() + ".gd";
}
if (FileAccess::exists(script)) {
//print_line("is a script");
-
Ref<Script> scr;
if (ScriptCodeCompletionCache::get_sigleton())
scr = ScriptCodeCompletionCache::get_sigleton()->get_cached_resource(script);
else
scr = ResourceLoader::load(script);
-
- r_type.obj_type="Node";
- r_type.type=Variant::OBJECT;
- r_type.script=scr;
- r_type.value=Variant();
+ r_type.obj_type = "Node";
+ r_type.type = Variant::OBJECT;
+ r_type.script = scr;
+ r_type.value = Variant();
return true;
-
}
}
}
-
}
//global
- for(Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) {
- if (E->key()==p_identifier) {
+ for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) {
+ if (E->key() == p_identifier) {
- r_type=_get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]);
+ r_type = _get_type_from_variant(GDScriptLanguage::get_singleton()->get_global_array()[E->get()]);
return true;
}
-
}
return false;
}
-
-static void _find_identifiers_in_block(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) {
+static void _find_identifiers_in_block(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) {
if (p_only_functions)
return;
- for (int i=0;i<context.block->statements.size();i++) {
+ for (int i = 0; i < context.block->statements.size(); i++) {
- if (context.block->statements[i]->line>p_line)
+ if (context.block->statements[i]->line > p_line)
continue;
+ if (context.block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) {
- if (context.block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) {
-
- const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]);
+ const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(context.block->statements[i]);
result.insert(lv->name.operator String());
}
}
}
-static void _find_identifiers_in_class(GDCompletionContext& context,bool p_static,bool p_only_functions,Set<String>& result) {
+static void _find_identifiers_in_class(GDCompletionContext &context, bool p_static, bool p_only_functions, Set<String> &result) {
if (!p_static && !p_only_functions) {
- for(int i=0;i<context._class->variables.size();i++) {
+ for (int i = 0; i < context._class->variables.size(); i++) {
result.insert(context._class->variables[i].identifier);
}
}
if (!p_only_functions) {
- for(int i=0;i<context._class->constant_expressions.size();i++) {
+ for (int i = 0; i < context._class->constant_expressions.size(); i++) {
result.insert(context._class->constant_expressions[i].identifier);
}
- for(int i=0;i<context._class->subclasses.size();i++) {
+ for (int i = 0; i < context._class->subclasses.size(); i++) {
result.insert(context._class->subclasses[i]->name);
}
-
}
- for(int i=0;i<context._class->static_functions.size();i++) {
+ for (int i = 0; i < context._class->static_functions.size(); i++) {
if (context._class->static_functions[i]->arguments.size())
- result.insert(context._class->static_functions[i]->name.operator String()+"(");
+ result.insert(context._class->static_functions[i]->name.operator String() + "(");
else
- result.insert(context._class->static_functions[i]->name.operator String()+"()");
+ result.insert(context._class->static_functions[i]->name.operator String() + "()");
}
if (!p_static) {
- for(int i=0;i<context._class->functions.size();i++) {
+ for (int i = 0; i < context._class->functions.size(); i++) {
if (context._class->functions[i]->arguments.size())
- result.insert(context._class->functions[i]->name.operator String()+"(");
+ result.insert(context._class->functions[i]->name.operator String() + "(");
else
- result.insert(context._class->functions[i]->name.operator String()+"()");
+ result.insert(context._class->functions[i]->name.operator String() + "()");
}
}
@@ -1281,135 +1195,130 @@ static void _find_identifiers_in_class(GDCompletionContext& context,bool p_stati
Ref<Reference> base = _get_parent_class(context);
- while(true) {
+ while (true) {
Ref<GDScript> script = base;
Ref<GDNativeClass> nc = base;
if (script.is_valid()) {
if (!p_static && !p_only_functions) {
- for (const Set<StringName>::Element *E=script->get_members().front();E;E=E->next()) {
+ for (const Set<StringName>::Element *E = script->get_members().front(); E; E = E->next()) {
result.insert(E->get().operator String());
}
}
if (!p_only_functions) {
- for (const Map<StringName,Variant>::Element *E=script->get_constants().front();E;E=E->next()) {
+ for (const Map<StringName, Variant>::Element *E = script->get_constants().front(); E; E = E->next()) {
result.insert(E->key().operator String());
}
}
- for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) {
+ for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) {
if (!p_static || E->get()->is_static()) {
if (E->get()->get_argument_count())
- result.insert(E->key().operator String()+"(");
+ result.insert(E->key().operator String() + "(");
else
- result.insert(E->key().operator String()+"()");
+ result.insert(E->key().operator String() + "()");
}
}
- if (!p_only_functions) {
- for (const Map<StringName,Ref<GDScript> >::Element *E=script->get_subclasses().front();E;E=E->next()) {
+ if (!p_only_functions) {
+ for (const Map<StringName, Ref<GDScript> >::Element *E = script->get_subclasses().front(); E; E = E->next()) {
result.insert(E->key().operator String());
}
}
- base=script->get_base();
+ base = script->get_base();
if (base.is_null())
- base=script->get_native();
+ base = script->get_native();
} else if (nc.is_valid()) {
StringName type = nc->get_name();
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()) {
+ ClassDB::get_integer_constant_list(type, &constants);
+ for (List<String>::Element *E = constants.front(); E; E = E->next()) {
result.insert(E->get());
}
List<PropertyInfo> pinfo;
- ClassDB::get_property_list(type,&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))
+ 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)
+ if (E->get().name.find("/") != -1)
continue;
result.insert(E->get().name);
}
-
}
List<MethodInfo> methods;
- ClassDB::get_method_list(type,&methods);
- for(List<MethodInfo>::Element *E=methods.front();E;E=E->next()) {
+ ClassDB::get_method_list(type, &methods);
+ for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
if (E->get().name.begins_with("_"))
continue;
if (E->get().arguments.size())
- result.insert(E->get().name+"(");
+ result.insert(E->get().name + "(");
else
- result.insert(E->get().name+"()");
+ result.insert(E->get().name + "()");
}
-
-
break;
} else
break;
-
}
-
}
-static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_only_functions,Set<String>& result) {
+static void _find_identifiers(GDCompletionContext &context, int p_line, bool p_only_functions, Set<String> &result) {
- const GDParser::BlockNode *block=context.block;
+ const GDParser::BlockNode *block = context.block;
if (context.function) {
- const GDParser::FunctionNode* f = context.function;
+ const GDParser::FunctionNode *f = context.function;
- for (int i=0;i<f->arguments.size();i++) {
+ for (int i = 0; i < f->arguments.size(); i++) {
result.insert(f->arguments[i].operator String());
}
}
- while(block) {
+ while (block) {
GDCompletionContext c = context;
- c.block=block;
+ c.block = block;
- _find_identifiers_in_block(c,p_line,p_only_functions,result);
- block=block->parent_block;
+ _find_identifiers_in_block(c, p_line, p_only_functions, result);
+ block = block->parent_block;
}
- const GDParser::ClassNode *clss=context._class;
+ const GDParser::ClassNode *clss = context._class;
- bool _static=context.function && context.function->_static;
+ bool _static = context.function && context.function->_static;
- while(clss) {
+ while (clss) {
GDCompletionContext c = context;
- c._class=clss;
- c.block=NULL;
- c.function=NULL;
- _find_identifiers_in_class(c,_static,p_only_functions,result);
- clss=clss->owner;
+ c._class = clss;
+ c.block = NULL;
+ c.function = NULL;
+ _find_identifiers_in_class(c, _static, p_only_functions, result);
+ clss = clss->owner;
}
- for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
+ for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
result.insert(GDFunctions::get_func_name(GDFunctions::Function(i)));
}
- static const char*_type_names[Variant::VARIANT_MAX]={
- "null","bool","int","float","String","Vector2","Rect2","Vector3","Transform2D","Plane","Quat","AABB","Basis","Transform",
- "Color","Image","NodePath","RID","Object","InputEvent","Dictionary","Array","RawArray","IntArray","FloatArray","StringArray",
- "Vector2Array","Vector3Array","ColorArray"};
+ static const char *_type_names[Variant::VARIANT_MAX] = {
+ "null", "bool", "int", "float", "String", "Vector2", "Rect2", "Vector3", "Transform2D", "Plane", "Quat", "AABB", "Basis", "Transform",
+ "Color", "Image", "NodePath", "RID", "Object", "InputEvent", "Dictionary", "Array", "RawArray", "IntArray", "FloatArray", "StringArray",
+ "Vector2Array", "Vector3Array", "ColorArray"
+ };
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
result.insert(_type_names[i]);
}
@@ -1417,37 +1326,34 @@ static void _find_identifiers(GDCompletionContext& context,int p_line,bool p_onl
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ 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);
+ String name = s.get_slice("/", 1);
String path = GlobalConfig::get_singleton()->get(s);
if (path.begins_with("*")) {
result.insert(name);
}
-
}
-
- for(const Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) {
+ for (const Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) {
result.insert(E->key().operator String());
}
}
-
-static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true) {
+static String _get_visual_datatype(const PropertyInfo &p_info, bool p_isarg = true) {
String n = p_info.name;
int idx = n.find(":");
- if (idx!=-1) {
- return n.substr(idx+1,n.length());
+ if (idx != -1) {
+ return n.substr(idx + 1, n.length());
}
- if (p_info.type==Variant::OBJECT && p_info.hint==PROPERTY_HINT_RESOURCE_TYPE)
+ if (p_info.type == Variant::OBJECT && p_info.hint == PROPERTY_HINT_RESOURCE_TYPE)
return p_info.hint_string;
- if (p_info.type==Variant::NIL) {
+ if (p_info.type == Variant::NIL) {
if (p_isarg)
return "var";
else
@@ -1457,74 +1363,68 @@ static String _get_visual_datatype(const PropertyInfo& p_info,bool p_isarg=true)
return Variant::get_type_name(p_info.type);
}
-static void _make_function_hint(const GDParser::FunctionNode* p_func,int p_argidx,String& arghint) {
+static void _make_function_hint(const GDParser::FunctionNode *p_func, int p_argidx, String &arghint) {
- arghint="func "+p_func->name+"(";
- for (int i=0;i<p_func->arguments.size();i++) {
- if (i>0)
- arghint+=", ";
+ arghint = "func " + p_func->name + "(";
+ for (int i = 0; i < p_func->arguments.size(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
+ arghint += " ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+=p_func->arguments[i].operator String();
- int deffrom = p_func->arguments.size()-p_func->default_values.size();
+ arghint += p_func->arguments[i].operator String();
+ int deffrom = p_func->arguments.size() - p_func->default_values.size();
- if (i>=deffrom) {
- int defidx = deffrom-i;
+ if (i >= deffrom) {
+ int defidx = deffrom - i;
- if (defidx>=0 && defidx<p_func->default_values.size()) {
+ if (defidx >= 0 && defidx < p_func->default_values.size()) {
- if (p_func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) {
-
- const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]);
- if (op->op==GDParser::OperatorNode::OP_ASSIGN) {
- const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]);
- arghint+="="+cn->value.get_construct_string();
+ if (p_func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) {
+ const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_func->default_values[defidx]);
+ if (op->op == GDParser::OperatorNode::OP_ASSIGN) {
+ const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]);
+ arghint += "=" + cn->value.get_construct_string();
}
} else {
-
}
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
}
- if (p_func->arguments.size()>0)
- arghint+=" ";
- arghint+=")";
+ if (p_func->arguments.size() > 0)
+ arghint += " ";
+ arghint += ")";
}
-
-static void _find_type_arguments(GDCompletionContext& context,const GDParser::Node*p_node,int p_line,const StringName& p_method,const GDCompletionIdentifier& id, int p_argidx, Set<String>& result, String& arghint) {
-
+static void _find_type_arguments(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, const StringName &p_method, const GDCompletionIdentifier &id, int p_argidx, Set<String> &result, String &arghint) {
//print_line("find type arguments?");
- if (id.type==Variant::INPUT_EVENT && String(p_method)=="is_action" && p_argidx==0) {
+ if (id.type == Variant::INPUT_EVENT && String(p_method) == "is_action" && p_argidx == 0) {
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
- result.insert("\""+name+"\"");
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
+ result.insert("\"" + name + "\"");
}
+ } else if (id.type == Variant::OBJECT && id.obj_type != StringName()) {
- } else if (id.type==Variant::OBJECT && id.obj_type!=StringName()) {
-
-
- MethodBind *m = ClassDB::get_method(id.obj_type,p_method);
+ MethodBind *m = ClassDB::get_method(id.obj_type, p_method);
if (!m) {
//not in static method, see script
@@ -1532,51 +1432,49 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No
Ref<GDScript> on_script;
if (id.value.get_type()) {
- Object *obj=id.value;
-
+ Object *obj = id.value;
if (obj) {
-
GDScript *scr = obj->cast_to<GDScript>();
if (scr) {
while (scr) {
- for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) {
- if (E->get()->is_static() && p_method==E->get()->get_name()) {
- arghint="static func "+String(p_method)+"(";
- for(int i=0;i<E->get()->get_argument_count();i++) {
- if (i>0)
- arghint+=", ";
+ for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) {
+ if (E->get()->is_static() && p_method == E->get()->get_name()) {
+ arghint = "static func " + String(p_method) + "(";
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+="var "+E->get()->get_argument_name(i);
- int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count();
- if (i>=deffrom) {
- int defidx = deffrom-i;
- if (defidx>=0 && defidx<E->get()->get_default_argument_count()) {
- arghint+="="+E->get()->get_default_argument(defidx).get_construct_string();
+ arghint += "var " + E->get()->get_argument_name(i);
+ int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count();
+ if (i >= deffrom) {
+ int defidx = deffrom - i;
+ if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) {
+ arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string();
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
}
- arghint+=")";
+ arghint += ")";
return; //found
}
}
if (scr->get_base().is_valid())
- scr=scr->get_base().ptr();
+ scr = scr->get_base().ptr();
else
- scr=NULL;
+ scr = NULL;
}
} else {
- on_script=obj->get_script();
+ on_script = obj->get_script();
}
}
}
@@ -1584,7 +1482,7 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No
//print_line("but it has a script?");
if (!on_script.is_valid() && id.script.is_valid()) {
//print_line("yes");
- on_script=id.script;
+ on_script = id.script;
}
if (on_script.is_valid()) {
@@ -1596,110 +1494,108 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No
String code = scr->get_source_code();
//print_line("has source code!");
- if (code!="") {
+ if (code != "") {
//if there is code, parse it. This way is slower but updates in real-time
GDParser p;
//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);
- Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false);
+ Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false);
- if (err==OK) {
+ if (err == OK) {
//print_line("checking the functions...");
//only if ok, otherwise use what is cached on the script
//GDParser::ClassNode *base = p.
const GDParser::Node *root = p.get_parse_tree();
- ERR_FAIL_COND(root->type!=GDParser::Node::TYPE_CLASS);
+ ERR_FAIL_COND(root->type != GDParser::Node::TYPE_CLASS);
- const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root);
+ const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root);
- const GDParser::FunctionNode* func=NULL;
- bool st=false;
+ const GDParser::FunctionNode *func = NULL;
+ bool st = false;
- for(int i=0;i<cl->functions.size();i++) {
+ for (int i = 0; i < cl->functions.size(); i++) {
//print_line(String(cl->functions[i]->name)+" vs "+String(p_method));
- if (cl->functions[i]->name==p_method) {
- func=cl->functions[i];
+ if (cl->functions[i]->name == p_method) {
+ func = cl->functions[i];
}
}
- for(int i=0;i<cl->static_functions.size();i++) {
+ for (int i = 0; i < cl->static_functions.size(); i++) {
//print_line(String(cl->static_functions[i]->name)+" vs "+String(p_method));
- if (cl->static_functions[i]->name==p_method) {
- func=cl->static_functions[i];
- st=true;
+ if (cl->static_functions[i]->name == p_method) {
+ func = cl->static_functions[i];
+ st = true;
}
-
}
if (func) {
- arghint="func "+String(p_method)+"(";
+ arghint = "func " + String(p_method) + "(";
if (st)
- arghint="static "+arghint;
- for(int i=0;i<func->arguments.size();i++) {
- if (i>0)
- arghint+=", ";
+ arghint = "static " + arghint;
+ for (int i = 0; i < func->arguments.size(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+="var "+String(func->arguments[i]);
- int deffrom = func->arguments.size()-func->default_values.size();
- if (i>=deffrom) {
+ arghint += "var " + String(func->arguments[i]);
+ int deffrom = func->arguments.size() - func->default_values.size();
+ if (i >= deffrom) {
- int defidx = deffrom-i;
+ int defidx = deffrom - i;
- if (defidx>=0 && defidx<func->default_values.size() && func->default_values[defidx]->type==GDParser::Node::TYPE_OPERATOR) {
- const GDParser::OperatorNode *op=static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]);
- if (op->op==GDParser::OperatorNode::OP_ASSIGN) {
- const GDParser::ConstantNode *cn=static_cast<const GDParser::ConstantNode *>(op->arguments[1]);
- arghint+="="+cn->value.get_construct_string();
+ if (defidx >= 0 && defidx < func->default_values.size() && func->default_values[defidx]->type == GDParser::Node::TYPE_OPERATOR) {
+ const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(func->default_values[defidx]);
+ if (op->op == GDParser::OperatorNode::OP_ASSIGN) {
+ const GDParser::ConstantNode *cn = static_cast<const GDParser::ConstantNode *>(op->arguments[1]);
+ arghint += "=" + cn->value.get_construct_string();
}
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
}
- arghint+=" )";
+ arghint += " )";
return;
}
} else {
//print_line("failed parsing?");
- code="";
+ code = "";
}
-
}
- if (code=="") {
+ if (code == "") {
- for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) {
- if (p_method==E->get()->get_name()) {
- arghint="func "+String(p_method)+"(";
- for(int i=0;i<E->get()->get_argument_count();i++) {
- if (i>0)
- arghint+=", ";
+ for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) {
+ if (p_method == E->get()->get_name()) {
+ arghint = "func " + String(p_method) + "(";
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+="var "+E->get()->get_argument_name(i);
- int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count();
- if (i>=deffrom) {
- int defidx = deffrom-i;
- if (defidx>=0 && defidx<E->get()->get_default_argument_count()) {
- arghint+="="+E->get()->get_default_argument(defidx).get_construct_string();
+ arghint += "var " + E->get()->get_argument_name(i);
+ int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count();
+ if (i >= deffrom) {
+ int defidx = deffrom - i;
+ if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) {
+ arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string();
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
}
- arghint+=")";
+ arghint += ")";
return; //found
}
}
@@ -1721,46 +1617,43 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No
}
if (scr->get_base().is_valid())
- scr=scr->get_base().ptr();
+ scr = scr->get_base().ptr();
else
- scr=NULL;
+ scr = NULL;
}
}
}
-
} else {
//regular method
- if (p_method.operator String()=="connect") {
-
+ if (p_method.operator String() == "connect") {
- if (p_argidx==0) {
+ if (p_argidx == 0) {
List<MethodInfo> sigs;
- ClassDB::get_signal_list(id.obj_type,&sigs);
+ ClassDB::get_signal_list(id.obj_type, &sigs);
if (id.script.is_valid()) {
id.script->get_script_signal_list(&sigs);
- } else if (id.value.get_type()==Variant::OBJECT) {
+ } else if (id.value.get_type() == Variant::OBJECT) {
Object *obj = id.value;
if (obj && !obj->get_script().is_null()) {
- Ref<Script> scr=obj->get_script();
+ Ref<Script> scr = obj->get_script();
if (scr.is_valid()) {
scr->get_script_signal_list(&sigs);
}
}
}
- for (List<MethodInfo>::Element *E=sigs.front();E;E=E->next()) {
- result.insert("\""+E->get().name+"\"");
+ for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) {
+ result.insert("\"" + E->get().name + "\"");
}
- } else if (p_argidx==2){
-
+ } else if (p_argidx == 2) {
if (context._class) {
- for(int i=0;i<context._class->functions.size();i++) {
- result.insert("\""+context._class->functions[i]->name+"\"");
+ for (int i = 0; i < context._class->functions.size(); i++) {
+ result.insert("\"" + context._class->functions[i]->name + "\"");
}
}
}
@@ -1773,173 +1666,163 @@ static void _find_type_arguments(GDCompletionContext& context,const GDParser::No
}*/
} else {
- if (p_argidx==0 && (String(p_method)=="get_node" || String(p_method)=="has_node") && ClassDB::is_parent_class(id.obj_type,"Node")) {
+ if (p_argidx == 0 && (String(p_method) == "get_node" || String(p_method) == "has_node") && ClassDB::is_parent_class(id.obj_type, "Node")) {
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
String s = E->get().name;
if (!s.begins_with("autoload/"))
continue;
//print_line("found "+s);
- String name = s.get_slice("/",1);
- result.insert("\"/root/"+name+"\"");
+ String name = s.get_slice("/", 1);
+ result.insert("\"/root/" + name + "\"");
}
}
- Object *obj=id.value;
+ Object *obj = id.value;
if (obj) {
List<String> options;
- obj->get_argument_options(p_method,p_argidx,&options);
+ obj->get_argument_options(p_method, p_argidx, &options);
- for(List<String>::Element *E=options.front();E;E=E->next()) {
+ for (List<String>::Element *E = options.front(); E; E = E->next()) {
result.insert(E->get());
}
}
-
}
- arghint = _get_visual_datatype(m->get_argument_info(-1),false)+" "+p_method.operator String()+String("(");
+ arghint = _get_visual_datatype(m->get_argument_info(-1), false) + " " + p_method.operator String() + String("(");
- for(int i=0;i<m->get_argument_count();i++) {
- if (i>0)
- arghint+=", ";
+ for (int i = 0; i < m->get_argument_count(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
+ arghint += " ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
String n = m->get_argument_info(i).name;
int dp = n.find(":");
- if (dp!=-1)
- n=n.substr(0,dp);
- arghint+=_get_visual_datatype(m->get_argument_info(i))+" "+n;
- int deffrom = m->get_argument_count()-m->get_default_argument_count();
+ if (dp != -1)
+ n = n.substr(0, dp);
+ arghint += _get_visual_datatype(m->get_argument_info(i)) + " " + n;
+ int deffrom = m->get_argument_count() - m->get_default_argument_count();
+ if (i >= deffrom) {
+ int defidx = i - deffrom;
- if (i>=deffrom) {
- int defidx = i-deffrom;
-
- if (defidx>=0 && defidx<m->get_default_argument_count()) {
- Variant v= m->get_default_argument(i);
- arghint+="="+v.get_construct_string();
+ if (defidx >= 0 && defidx < m->get_default_argument_count()) {
+ Variant v = m->get_default_argument(i);
+ arghint += "=" + v.get_construct_string();
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
-
}
- if (m->get_argument_count()>0)
- arghint+=" ";
-
+ if (m->get_argument_count() > 0)
+ arghint += " ";
- arghint+=")";
+ arghint += ")";
}
-
}
}
+static void _find_call_arguments(GDCompletionContext &context, const GDParser::Node *p_node, int p_line, int p_argidx, Set<String> &result, String &arghint) {
-static void _find_call_arguments(GDCompletionContext& context,const GDParser::Node* p_node, int p_line,int p_argidx, Set<String>& result, String& arghint) {
-
-
-
- if (!p_node || p_node->type!=GDParser::Node::TYPE_OPERATOR) {
+ if (!p_node || p_node->type != GDParser::Node::TYPE_OPERATOR) {
return;
}
const GDParser::OperatorNode *op = static_cast<const GDParser::OperatorNode *>(p_node);
- if (op->op!=GDParser::OperatorNode::OP_CALL) {
+ if (op->op != GDParser::OperatorNode::OP_CALL) {
return;
}
- if (op->arguments[0]->type==GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
+ if (op->arguments[0]->type == GDParser::Node::TYPE_BUILT_IN_FUNCTION) {
//complete built-in function
- const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode*>(op->arguments[0]);
+ const GDParser::BuiltInFunctionNode *fn = static_cast<const GDParser::BuiltInFunctionNode *>(op->arguments[0]);
MethodInfo mi = GDFunctions::get_info(fn->function);
- arghint = _get_visual_datatype(mi.return_val,false)+" "+GDFunctions::get_func_name(fn->function)+String("(");
- for(int i=0;i<mi.arguments.size();i++) {
- if (i>0)
- arghint+=", ";
+ arghint = _get_visual_datatype(mi.return_val, false) + " " + GDFunctions::get_func_name(fn->function) + String("(");
+ for (int i = 0; i < mi.arguments.size(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name;
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name;
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
-
}
- if (mi.arguments.size()>0)
- arghint+=" ";
- arghint+=")";
+ if (mi.arguments.size() > 0)
+ arghint += " ";
+ arghint += ")";
- } else if (op->arguments[0]->type==GDParser::Node::TYPE_TYPE) {
+ } else if (op->arguments[0]->type == GDParser::Node::TYPE_TYPE) {
//complete constructor
- const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode*>(op->arguments[0]);
+ const GDParser::TypeNode *tn = static_cast<const GDParser::TypeNode *>(op->arguments[0]);
List<MethodInfo> mil;
- Variant::get_constructor_list(tn->vtype,&mil);
+ Variant::get_constructor_list(tn->vtype, &mil);
- for(List<MethodInfo>::Element *E=mil.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = mil.front(); E; E = E->next()) {
MethodInfo mi = E->get();
- if (mi.arguments.size()==0)
+ if (mi.arguments.size() == 0)
continue;
if (E->prev())
- arghint+="\n";
- arghint += Variant::get_type_name(tn->vtype)+" "+Variant::get_type_name(tn->vtype)+String("(");
- for(int i=0;i<mi.arguments.size();i++) {
- if (i>0)
- arghint+=", ";
+ arghint += "\n";
+ arghint += Variant::get_type_name(tn->vtype) + " " + Variant::get_type_name(tn->vtype) + String("(");
+ for (int i = 0; i < mi.arguments.size(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+=_get_visual_datatype(mi.arguments[i])+" "+mi.arguments[i].name;
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += _get_visual_datatype(mi.arguments[i]) + " " + mi.arguments[i].name;
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
-
}
- if (mi.arguments.size()>0)
- arghint+=" ";
- arghint+=")";
+ if (mi.arguments.size() > 0)
+ arghint += " ";
+ arghint += ")";
}
- } else if (op->arguments.size()>=2 && op->arguments[1]->type==GDParser::Node::TYPE_IDENTIFIER) {
+ } else if (op->arguments.size() >= 2 && op->arguments[1]->type == GDParser::Node::TYPE_IDENTIFIER) {
//make sure identifier exists...
- const GDParser::IdentifierNode *id=static_cast<const GDParser::IdentifierNode *>(op->arguments[1]);
+ const GDParser::IdentifierNode *id = static_cast<const GDParser::IdentifierNode *>(op->arguments[1]);
- if (op->arguments[0]->type==GDParser::Node::TYPE_SELF) {
+ if (op->arguments[0]->type == GDParser::Node::TYPE_SELF) {
//self, look up
- for(int i=0;i<context._class->static_functions.size();i++) {
- if (context._class->static_functions[i]->name==id->name) {
- _make_function_hint(context._class->static_functions[i],p_argidx,arghint);
+ for (int i = 0; i < context._class->static_functions.size(); i++) {
+ if (context._class->static_functions[i]->name == id->name) {
+ _make_function_hint(context._class->static_functions[i], p_argidx, arghint);
return;
}
}
if (context.function && !context.function->_static) {
- for(int i=0;i<context._class->functions.size();i++) {
- if (context._class->functions[i]->name==id->name) {
- _make_function_hint(context._class->functions[i],p_argidx,arghint);
+ for (int i = 0; i < context._class->functions.size(); i++) {
+ if (context._class->functions[i]->name == id->name) {
+ _make_function_hint(context._class->functions[i], p_argidx, arghint);
return;
}
}
@@ -1947,64 +1830,61 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No
Ref<Reference> base = _get_parent_class(context);
- while(true) {
+ while (true) {
Ref<GDScript> script = base;
Ref<GDNativeClass> nc = base;
if (script.is_valid()) {
+ for (const Map<StringName, GDFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) {
- for (const Map<StringName,GDFunction*>::Element *E=script->get_member_functions().front();E;E=E->next()) {
-
- if (E->key()==id->name) {
+ if (E->key() == id->name) {
if (context.function && context.function->_static && !E->get()->is_static())
continue;
-
- arghint = "func "+id->name.operator String()+String("(");
- for(int i=0;i<E->get()->get_argument_count();i++) {
- if (i>0)
- arghint+=", ";
+ arghint = "func " + id->name.operator String() + String("(");
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
+ if (i > 0)
+ arghint += ", ";
else
- arghint+=" ";
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ arghint += " ";
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
- arghint+=E->get()->get_argument_name(i);
- int deffrom = E->get()->get_argument_count()-E->get()->get_default_argument_count();
- if (i>=deffrom) {
- int defidx = deffrom-i;
- if (defidx>=0 && defidx<E->get()->get_default_argument_count()) {
- arghint+="="+E->get()->get_default_argument(defidx).get_construct_string();
+ arghint += E->get()->get_argument_name(i);
+ int deffrom = E->get()->get_argument_count() - E->get()->get_default_argument_count();
+ if (i >= deffrom) {
+ int defidx = deffrom - i;
+ if (defidx >= 0 && defidx < E->get()->get_default_argument_count()) {
+ arghint += "=" + E->get()->get_default_argument(defidx).get_construct_string();
}
}
- if (i==p_argidx) {
- arghint+=String::chr(0xFFFF);
+ if (i == p_argidx) {
+ arghint += String::chr(0xFFFF);
}
-
}
- if (E->get()->get_argument_count()>0)
- arghint+=" ";
- arghint+=")";
+ if (E->get()->get_argument_count() > 0)
+ arghint += " ";
+ arghint += ")";
return;
}
}
- base=script->get_base();
+ base = script->get_base();
if (base.is_null())
- base=script->get_native();
+ base = script->get_native();
} else if (nc.is_valid()) {
if (context.function && !context.function->_static) {
GDCompletionIdentifier ci;
- ci.type=Variant::OBJECT;
- ci.obj_type=nc->get_name();
+ ci.type = Variant::OBJECT;
+ ci.obj_type = nc->get_name();
if (!context._class->owner)
- ci.value=context.base;
+ ci.value = context.base;
- _find_type_arguments(context,p_node,p_line,id->name,ci,p_argidx,result,arghint);
+ _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, arghint);
//guess type..
/*
List<MethodInfo> methods;
@@ -2019,20 +1899,17 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No
break;
} else
break;
-
}
} else {
//indexed lookup
GDCompletionIdentifier ci;
- if (_guess_expression_type(context,op->arguments[0],p_line,ci)) {
+ if (_guess_expression_type(context, op->arguments[0], p_line, ci)) {
- _find_type_arguments(context,p_node,p_line,id->name,ci,p_argidx,result,arghint);
+ _find_type_arguments(context, p_node, p_line, id->name, ci, p_argidx, result, arghint);
return;
}
-
}
-
}
#if 0
bool _static=context.function->_static;
@@ -2127,42 +2004,40 @@ static void _find_call_arguments(GDCompletionContext& context,const GDParser::No
}
#endif
-
}
-Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) {
+Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) {
GDParser p;
- p.parse(p_code,p_base_path,false,"",true);
- bool isfunction=false;
+ p.parse(p_code, p_base_path, false, "", true);
+ bool isfunction = false;
Set<String> options;
GDCompletionContext context;
- context._class=p.get_completion_class();
- context.block=p.get_completion_block();
- context.function=p.get_completion_function();
- context.base=p_owner;
- context.base_path=p_base_path;
+ context._class = p.get_completion_class();
+ context.block = p.get_completion_block();
+ context.function = p.get_completion_function();
+ context.base = p_owner;
+ context.base_path = p_base_path;
- switch(p.get_completion_type()) {
+ switch (p.get_completion_type()) {
case GDParser::COMPLETION_NONE: {
} break;
case GDParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
List<StringName> constants;
- Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(),&constants);
- for(List<StringName>::Element *E=constants.front();E;E=E->next()) {
+ Variant::get_numeric_constants_for_type(p.get_completion_built_in_constant(), &constants);
+ for (List<StringName>::Element *E = constants.front(); E; E = E->next()) {
options.insert(E->get().operator String());
}
-
} break;
case GDParser::COMPLETION_FUNCTION:
- isfunction=true;
+ isfunction = true;
case GDParser::COMPLETION_IDENTIFIER: {
- _find_identifiers(context,p.get_completion_line(),isfunction,options);
+ _find_identifiers(context, p.get_completion_line(), isfunction, options);
} break;
case GDParser::COMPLETION_PARENT_FUNCTION: {
@@ -2171,98 +2046,91 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
if (p_owner) {
List<String> opts;
- p_owner->get_argument_options("get_node",0,&opts);
+ p_owner->get_argument_options("get_node", 0, &opts);
- for (List<String>::Element *E=opts.front();E;E=E->next()) {
+ for (List<String>::Element *E = opts.front(); E; E = E->next()) {
String opt = E->get().strip_edges();
if (opt.begins_with("\"") && opt.ends_with("\"")) {
- String idopt=opt.substr(1,opt.length()-2);
- if (idopt.replace("/","_").is_valid_identifier()) {
+ String idopt = opt.substr(1, opt.length() - 2);
+ if (idopt.replace("/", "_").is_valid_identifier()) {
options.insert(idopt);
} else {
options.insert(opt);
}
}
}
-
}
} break;
case GDParser::COMPLETION_METHOD:
- isfunction=true;
+ isfunction = true;
case GDParser::COMPLETION_INDEX: {
const GDParser::Node *node = p.get_completion_node();
- if (node->type!=GDParser::Node::TYPE_OPERATOR)
+ if (node->type != GDParser::Node::TYPE_OPERATOR)
break;
-
-
-
GDCompletionIdentifier t;
- if (_guess_expression_type(context,static_cast<const GDParser::OperatorNode *>(node)->arguments[0],p.get_completion_line(),t)) {
+ if (_guess_expression_type(context, static_cast<const GDParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) {
- if (t.type==Variant::OBJECT && t.obj_type=="GDNativeClass") {
+ if (t.type == Variant::OBJECT && t.obj_type == "GDNativeClass") {
//native enum
Ref<GDNativeClass> gdn = t.value;
if (gdn.is_valid()) {
StringName cn = gdn->get_name();
List<String> cnames;
- ClassDB::get_integer_constant_list(cn,&cnames);
- for (List<String>::Element *E=cnames.front();E;E=E->next()) {
+ ClassDB::get_integer_constant_list(cn, &cnames);
+ for (List<String>::Element *E = cnames.front(); E; E = E->next()) {
options.insert(E->get());
}
List<PropertyInfo> pinfo;
- ClassDB::get_property_list(cn,&pinfo);
+ ClassDB::get_property_list(cn, &pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- if (E->get().usage&(PROPERTY_USAGE_GROUP|PROPERTY_USAGE_CATEGORY))
+ 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)
+ if (E->get().name.find("/") != -1)
continue;
options.insert(E->get().name);
}
}
- } else if (t.type==Variant::OBJECT && t.obj_type!=StringName()) {
+ } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) {
Ref<GDScript> on_script;
if (t.value.get_type()) {
- Object *obj=t.value;
-
+ Object *obj = t.value;
if (obj) {
-
GDScript *scr = obj->cast_to<GDScript>();
if (scr) {
while (scr) {
if (!isfunction) {
- for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) {
+ for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) {
options.insert(E->key());
}
}
- for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) {
+ for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) {
if (E->get()->is_static())
options.insert(E->key());
}
if (scr->get_base().is_valid())
- scr=scr->get_base().ptr();
+ scr = scr->get_base().ptr();
else
- scr=NULL;
+ scr = NULL;
}
} else {
- on_script=obj->get_script();
+ on_script = obj->get_script();
}
}
}
-
if (!on_script.is_valid() && t.script.is_valid()) {
- on_script=t.script;
+ on_script = t.script;
}
if (on_script.is_valid()) {
@@ -2273,132 +2141,119 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
String code = scr->get_source_code();
- if (code!="") {
+ if (code != "") {
//if there is code, parse it. This way is slower but updates in real-time
GDParser p;
- Error err = p.parse(scr->get_source_code(),scr->get_path().get_base_dir(),true,"",false);
+ Error err = p.parse(scr->get_source_code(), scr->get_path().get_base_dir(), true, "", false);
- if (err==OK) {
+ if (err == OK) {
//only if ok, otherwise use what is cached on the script
//GDParser::ClassNode *base = p.
const GDParser::Node *root = p.get_parse_tree();
- ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,ERR_PARSE_ERROR);
+ ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, ERR_PARSE_ERROR);
- const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode*>(root);
+ const GDParser::ClassNode *cl = static_cast<const GDParser::ClassNode *>(root);
- for(int i=0;i<cl->functions.size();i++) {
+ for (int i = 0; i < cl->functions.size(); i++) {
if (cl->functions[i]->arguments.size())
- options.insert(String(cl->functions[i]->name)+"(");
+ options.insert(String(cl->functions[i]->name) + "(");
else
- options.insert(String(cl->functions[i]->name)+"()");
+ options.insert(String(cl->functions[i]->name) + "()");
}
- for(int i=0;i<cl->static_functions.size();i++) {
+ for (int i = 0; i < cl->static_functions.size(); i++) {
if (cl->static_functions[i]->arguments.size())
- options.insert(String(cl->static_functions[i]->name)+"(");
+ options.insert(String(cl->static_functions[i]->name) + "(");
else
- options.insert(String(cl->static_functions[i]->name)+"()");
-
+ options.insert(String(cl->static_functions[i]->name) + "()");
}
if (!isfunction) {
- for(int i=0;i<cl->variables.size();i++) {
+ for (int i = 0; i < cl->variables.size(); i++) {
options.insert(String(cl->variables[i].identifier));
}
- for(int i=0;i<cl->constant_expressions.size();i++) {
+ for (int i = 0; i < cl->constant_expressions.size(); i++) {
options.insert(String(cl->constant_expressions[i].identifier));
}
-
}
-
} else {
- code=""; //well, then no code
+ code = ""; //well, then no code
}
-
}
- if (code=="") {
+ if (code == "") {
//use class directly, no code was found
if (!isfunction) {
- for (const Map<StringName,Variant>::Element *E=scr->get_constants().front();E;E=E->next()) {
+ for (const Map<StringName, Variant>::Element *E = scr->get_constants().front(); E; E = E->next()) {
options.insert(E->key());
}
}
- for (const Map<StringName,GDFunction*>::Element *E=scr->get_member_functions().front();E;E=E->next()) {
+ for (const Map<StringName, GDFunction *>::Element *E = scr->get_member_functions().front(); E; E = E->next()) {
if (E->get()->get_argument_count())
- options.insert(String(E->key())+"()");
+ options.insert(String(E->key()) + "()");
else
- options.insert(String(E->key())+"(");
-
+ options.insert(String(E->key()) + "(");
}
- for (const Set<StringName>::Element *E=scr->get_members().front();E;E=E->next()) {
+ for (const Set<StringName>::Element *E = scr->get_members().front(); E; E = E->next()) {
options.insert(E->get());
}
}
if (scr->get_base().is_valid())
- scr=scr->get_base().ptr();
+ scr = scr->get_base().ptr();
else
- scr=NULL;
+ scr = NULL;
}
}
}
-
-
-
-
-
if (!isfunction) {
- ClassDB::get_integer_constant_list(t.obj_type,r_options);
+ ClassDB::get_integer_constant_list(t.obj_type, r_options);
List<PropertyInfo> pinfo;
- ClassDB::get_property_list(t.obj_type,&pinfo);
+ ClassDB::get_property_list(t.obj_type, &pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- if (E->get().usage&(PROPERTY_USAGE_GROUP|PROPERTY_USAGE_CATEGORY))
+ 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)
+ if (E->get().name.find("/") != -1)
continue;
r_options->push_back(E->get().name);
}
}
-
List<MethodInfo> mi;
- ClassDB::get_method_list(t.obj_type,&mi);
- for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {
+ ClassDB::get_method_list(t.obj_type, &mi);
+ for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) {
if (E->get().name.begins_with("_"))
continue;
if (E->get().arguments.size())
- options.insert(E->get().name+"(");
+ options.insert(E->get().name + "(");
else
- options.insert(E->get().name+"()");
-
+ options.insert(E->get().name + "()");
}
} else {
-
- if (t.type==Variant::INPUT_EVENT) {
+ if (t.type == Variant::INPUT_EVENT) {
//this is hardcoded otherwise it's not obvious
Set<String> exclude;
- for(int i=0;i<InputEvent::TYPE_MAX;i++) {
+ for (int i = 0; i < InputEvent::TYPE_MAX; i++) {
InputEvent ie;
- ie.type=InputEvent::Type(i);
- static const char*evnames[]={
+ ie.type = InputEvent::Type(i);
+ static const char *evnames[] = {
"# Common",
"# Key",
"# MouseMotion",
@@ -2414,22 +2269,20 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
Variant v = ie;
- if (i==0) {
+ if (i == 0) {
List<MethodInfo> mi;
v.get_method_list(&mi);
- for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {
- r_options->push_back(E->get().name+"(");
-
+ for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) {
+ r_options->push_back(E->get().name + "(");
}
-
}
List<PropertyInfo> pi;
v.get_property_list(&pi);
- for (List<PropertyInfo>::Element *E=pi.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pi.front(); E; E = E->next()) {
- if (i==0)
+ if (i == 0)
exclude.insert(E->get().name);
else if (exclude.has(E->get().name))
continue;
@@ -2439,67 +2292,64 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
}
return OK;
} else {
- if (t.value.get_type()==Variant::NIL) {
+ if (t.value.get_type() == Variant::NIL) {
Variant::CallError ce;
- t.value=Variant::construct(t.type,NULL,0,ce);
+ t.value = Variant::construct(t.type, NULL, 0, ce);
}
-
if (!isfunction) {
List<PropertyInfo> pl;
t.value.get_property_list(&pl);
- for (List<PropertyInfo>::Element *E=pl.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) {
- if (E->get().name.find("/")==-1)
+ if (E->get().name.find("/") == -1)
options.insert(E->get().name);
}
}
List<MethodInfo> mi;
t.value.get_method_list(&mi);
- for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) {
if (E->get().arguments.size())
- options.insert(E->get().name+"(");
+ options.insert(E->get().name + "(");
else
- options.insert(E->get().name+"()");
-
+ options.insert(E->get().name + "()");
}
}
}
}
-
} break;
case GDParser::COMPLETION_CALL_ARGUMENTS: {
- _find_call_arguments(context,p.get_completion_node(),p.get_completion_line(),p.get_completion_argument_index(),options,r_call_hint);
+ _find_call_arguments(context, p.get_completion_node(), p.get_completion_line(), p.get_completion_argument_index(), options, r_call_hint);
} break;
case GDParser::COMPLETION_VIRTUAL_FUNC: {
GDCompletionIdentifier cid = _get_native_class(context);
- if (cid.obj_type!=StringName()) {
+ if (cid.obj_type != StringName()) {
List<MethodInfo> vm;
- ClassDB::get_virtual_methods(cid.obj_type,&vm);
- for(List<MethodInfo>::Element *E=vm.front();E;E=E->next()) {
+ ClassDB::get_virtual_methods(cid.obj_type, &vm);
+ for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) {
- MethodInfo &mi=E->get();
+ MethodInfo &mi = E->get();
String m = mi.name;
- if (m.find(":")!=-1)
- m=m.substr(0,m.find(":"));
- m+="(";
+ if (m.find(":") != -1)
+ m = m.substr(0, m.find(":"));
+ m += "(";
if (mi.arguments.size()) {
- for(int i=0;i<mi.arguments.size();i++) {
- if (i>0)
- m+=", ";
- String n =mi.arguments[i].name;
- if (n.find(":")!=-1)
- n=n.substr(0,n.find(":"));
- m+=n;
+ for (int i = 0; i < mi.arguments.size(); i++) {
+ if (i > 0)
+ m += ", ";
+ String n = mi.arguments[i].name;
+ if (n.find(":") != -1)
+ n = n.substr(0, n.find(":"));
+ m += n;
}
}
- m+="):";
+ m += "):";
options.insert(m);
}
@@ -2510,24 +2360,22 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
const GDParser::Node *node = p.get_completion_node();
GDCompletionIdentifier t;
- if (!_guess_expression_type(context,node,p.get_completion_line(),t))
+ if (!_guess_expression_type(context, node, p.get_completion_line(), t))
break;
- if (t.type==Variant::OBJECT && t.obj_type!=StringName()) {
+ if (t.type == Variant::OBJECT && t.obj_type != StringName()) {
List<MethodInfo> sigs;
- ClassDB::get_signal_list(t.obj_type,&sigs);
- for (List<MethodInfo>::Element *E=sigs.front();E;E=E->next()) {
- options.insert("\""+E->get().name+"\"");
+ ClassDB::get_signal_list(t.obj_type, &sigs);
+ for (List<MethodInfo>::Element *E = sigs.front(); E; E = E->next()) {
+ options.insert("\"" + E->get().name + "\"");
}
}
} break;
-
}
-
- for(Set<String>::Element *E=options.front();E;E=E->next()) {
+ for (Set<String>::Element *E = options.front(); E; E = E->next()) {
r_options->push_back(E->get());
}
@@ -2536,25 +2384,23 @@ Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base
#else
-Error GDScriptLanguage::complete_code(const String& p_code, const String& p_base_path, Object*p_owner, List<String>* r_options, String &r_call_hint) {
+Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) {
return OK;
}
#endif
-
-void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const {
-
+void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
Vector<String> lines = p_code.split("\n");
List<int> indent_stack;
- for(int i=0;i<lines.size();i++) {
+ 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') {
+ int tc = 0;
+ for (int j = 0; j < l.length(); j++) {
+ if (l[j] == ' ' || l[j] == '\t') {
tc++;
} else {
@@ -2562,252 +2408,237 @@ void GDScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_
}
}
-
- String st = l.substr(tc,l.length()).strip_edges();
- if (st=="" || st.begins_with("#"))
+ String st = l.substr(tc, l.length()).strip_edges();
+ if (st == "" || st.begins_with("#"))
continue; //ignore!
- int ilevel=0;
+ int ilevel = 0;
if (indent_stack.size()) {
- ilevel=indent_stack.back()->get();
+ ilevel = indent_stack.back()->get();
}
- if (tc>ilevel) {
+ if (tc > ilevel) {
indent_stack.push_back(tc);
- } else if (tc<ilevel) {
- while(indent_stack.size() && indent_stack.back()->get()>tc) {
+ } else if (tc < ilevel) {
+ while (indent_stack.size() && indent_stack.back()->get() > tc) {
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) {
+ if (i >= p_from_line) {
- l="";
- for(int j=0;j<indent_stack.size();j++)
- l+="\t";
- l+=st;
+ l = "";
+ for (int j = 0; j < indent_stack.size(); j++)
+ l += "\t";
+ l += st;
-
- } else if (i>p_to_line) {
+ } else if (i > p_to_line) {
break;
}
//print_line(itos(indent_stack.size())+","+itos(tc)+": "+l);
- lines[i]=l;
+ lines[i] = l;
}
- p_code="";
- for(int i=0;i<lines.size();i++) {
- if (i>0)
- p_code+="\n";
- p_code+=lines[i];
+ p_code = "";
+ for (int i = 0; i < lines.size(); i++) {
+ if (i > 0)
+ p_code += "\n";
+ p_code += lines[i];
}
-
}
#ifdef TOOLS_ENABLED
-Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol,const String& p_base_path, Object*p_owner,LookupResult& r_result) {
-
+Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_base_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;
- r_result.class_name=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
+ r_result.class_name = p_symbol;
return OK;
}
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
Variant::Type t = Variant::Type(i);
- if (Variant::get_type_name(t)==p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS;
- r_result.class_name=Variant::get_type_name(t);
+ if (Variant::get_type_name(t) == p_symbol) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
+ r_result.class_name = Variant::get_type_name(t);
return OK;
}
}
- for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
- if (GDFunctions::get_func_name(GDFunctions::Function(i))==p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name="@GDScript";
- r_result.class_member=p_symbol;
+ for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
+ if (GDFunctions::get_func_name(GDFunctions::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;
}
}
GDParser p;
- p.parse(p_code,p_base_path,false,"",true);
+ p.parse(p_code, p_base_path, false, "", true);
- if (p.get_completion_type()==GDParser::COMPLETION_NONE)
+ if (p.get_completion_type() == GDParser::COMPLETION_NONE)
return ERR_CANT_RESOLVE;
GDCompletionContext context;
- context._class=p.get_completion_class();
- context.block=p.get_completion_block();
- context.function=p.get_completion_function();
- context.base=p_owner;
- context.base_path=p_base_path;
- bool isfunction=false;
+ context._class = p.get_completion_class();
+ context.block = p.get_completion_block();
+ context.function = p.get_completion_function();
+ context.base = p_owner;
+ context.base_path = p_base_path;
+ bool isfunction = false;
- switch(p.get_completion_type()) {
+ switch (p.get_completion_type()) {
case GDParser::COMPLETION_GET_NODE:
case GDParser::COMPLETION_NONE: {
} break;
case GDParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name=Variant::get_type_name(p.get_completion_built_in_constant());
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
+ r_result.class_name = Variant::get_type_name(p.get_completion_built_in_constant());
+ r_result.class_member = p_symbol;
return OK;
} break;
case GDParser::COMPLETION_FUNCTION: {
-
if (context._class && context._class->functions.size()) {
- for(int i=0;i<context._class->functions.size();i++) {
- if (context._class->functions[i]->name==p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=context._class->functions[i]->line;
+ for (int i = 0; i < context._class->functions.size(); i++) {
+ if (context._class->functions[i]->name == p_symbol) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = context._class->functions[i]->line;
return OK;
}
}
}
Ref<GDScript> parent = _get_parent_class(context);
- while(parent.is_valid()) {
+ while (parent.is_valid()) {
int line = parent->get_member_line(p_symbol);
- if (line>=0) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=line;
- r_result.script=parent;
+ if (line >= 0) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = line;
+ r_result.script = parent;
return OK;
-
}
- parent=parent->get_base();
+ parent = parent->get_base();
}
GDCompletionIdentifier identifier = _get_native_class(context);
- print_line("identifier: "+String(identifier.obj_type));
+ print_line("identifier: " + String(identifier.obj_type));
- if (ClassDB::has_method(identifier.obj_type,p_symbol)) {
+ if (ClassDB::has_method(identifier.obj_type, p_symbol)) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name=identifier.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = identifier.obj_type;
+ r_result.class_member = p_symbol;
return OK;
}
-
} break;
case GDParser::COMPLETION_IDENTIFIER: {
//check if a function
if (p.get_completion_identifier_is_function()) {
if (context._class && context._class->functions.size()) {
- for(int i=0;i<context._class->functions.size();i++) {
- if (context._class->functions[i]->name==p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=context._class->functions[i]->line;
+ for (int i = 0; i < context._class->functions.size(); i++) {
+ if (context._class->functions[i]->name == p_symbol) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = context._class->functions[i]->line;
return OK;
}
}
}
Ref<GDScript> parent = _get_parent_class(context);
- while(parent.is_valid()) {
+ while (parent.is_valid()) {
int line = parent->get_member_line(p_symbol);
- if (line>=0) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=line;
- r_result.script=parent;
+ if (line >= 0) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = line;
+ r_result.script = parent;
return OK;
-
}
- parent=parent->get_base();
+ parent = parent->get_base();
}
GDCompletionIdentifier identifier = _get_native_class(context);
+ if (ClassDB::has_method(identifier.obj_type, p_symbol)) {
- if (ClassDB::has_method(identifier.obj_type,p_symbol)) {
-
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name=identifier.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = identifier.obj_type;
+ r_result.class_member = p_symbol;
return OK;
}
} else {
-
GDCompletionIdentifier gdi = _get_native_class(context);
- if (gdi.obj_type!=StringName()) {
+ if (gdi.obj_type != StringName()) {
bool valid;
- Variant::Type t = ClassDB::get_property_type(gdi.obj_type,p_symbol,&valid);
- if (t!=Variant::NIL && valid) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
- r_result.class_name=gdi.obj_type;
- r_result.class_member=p_symbol;
+ Variant::Type t = ClassDB::get_property_type(gdi.obj_type, p_symbol, &valid);
+ if (t != Variant::NIL && valid) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
+ r_result.class_name = gdi.obj_type;
+ r_result.class_member = p_symbol;
return OK;
-
}
}
- const GDParser::BlockNode *block=context.block;
+ const GDParser::BlockNode *block = context.block;
//search in blocks going up (local var?)
- while(block) {
-
+ while (block) {
+ for (int i = 0; i < block->statements.size(); i++) {
- for (int i=0;i<block->statements.size();i++) {
-
- if (block->statements[i]->line>p.get_completion_line())
+ if (block->statements[i]->line > p.get_completion_line())
continue;
+ if (block->statements[i]->type == GDParser::BlockNode::TYPE_LOCAL_VAR) {
- if (block->statements[i]->type==GDParser::BlockNode::TYPE_LOCAL_VAR) {
-
- const GDParser::LocalVarNode *lv=static_cast<const GDParser::LocalVarNode *>(block->statements[i]);
+ const GDParser::LocalVarNode *lv = static_cast<const GDParser::LocalVarNode *>(block->statements[i]);
- if (lv->assign && lv->name==p_symbol) {
+ if (lv->assign && lv->name == p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=block->statements[i]->line;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = block->statements[i]->line;
return OK;
}
}
}
- block=block->parent_block;
+ block = block->parent_block;
}
//guess from function arguments
- if (context.function && context.function->name!=StringName()) {
+ if (context.function && context.function->name != StringName()) {
- for(int i=0;i<context.function->arguments.size();i++) {
+ 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;
+ if (context.function->arguments[i] == p_symbol) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = context.function->line;
return OK;
}
-
}
}
//guess in class constants
- for(int i=0;i<context._class->constant_expressions.size();i++) {
+ for (int i = 0; i < context._class->constant_expressions.size(); i++) {
- if (context._class->constant_expressions[i].identifier==p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=context._class->constant_expressions[i].expression->line;
+ if (context._class->constant_expressions[i].identifier == p_symbol) {
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = context._class->constant_expressions[i].expression->line;
return OK;
}
}
@@ -2815,12 +2646,12 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
//guess in class variables
if (!(context.function && context.function->_static)) {
- for(int i=0;i<context._class->variables.size();i++) {
+ for (int i = 0; i < context._class->variables.size(); i++) {
- if (context._class->variables[i].identifier==p_symbol) {
+ if (context._class->variables[i].identifier == p_symbol) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=context._class->variables[i].line;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = context._class->variables[i].line;
return OK;
}
}
@@ -2830,29 +2661,29 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
List<PropertyInfo> props;
GlobalConfig::get_singleton()->get_property_list(&props);
- for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ 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 name = s.get_slice("/", 1);
+ if (name == String(p_symbol)) {
String path = GlobalConfig::get_singleton()->get(s);
if (path.begins_with("*")) {
- String script =path.substr(1,path.length());
+ 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";
+ script = script.get_basename() + ".gd";
}
if (FileAccess::exists(script)) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=0;
- r_result.script=ResourceLoader::load(script);
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = 0;
+ r_result.script = ResourceLoader::load(script);
return OK;
}
}
@@ -2860,33 +2691,32 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
}
//global
- for(Map<StringName,int>::Element *E=GDScriptLanguage::get_singleton()->get_global_map().front();E;E=E->next()) {
- if (E->key()==p_symbol) {
+ for (Map<StringName, int>::Element *E = GDScriptLanguage::get_singleton()->get_global_map().front(); E; E = E->next()) {
+ if (E->key() == p_symbol) {
Variant value = GDScriptLanguage::get_singleton()->get_global_array()[E->get()];
- if (value.get_type()==Variant::OBJECT) {
+ if (value.get_type() == Variant::OBJECT) {
Object *obj = value;
if (obj) {
if (obj->cast_to<GDNativeClass>()) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS;
- r_result.class_name=obj->cast_to<GDNativeClass>()->get_name();
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
+ r_result.class_name = obj->cast_to<GDNativeClass>()->get_name();
} else {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS;
- r_result.class_name=obj->get_class();
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
+ r_result.class_name = obj->get_class();
}
return OK;
}
} else {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name="@Global Scope";
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
+ r_result.class_name = "@Global Scope";
+ r_result.class_member = p_symbol;
return OK;
}
}
-
}
#if 0
GDCompletionIdentifier identifier;
@@ -2907,122 +2737,109 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
} break;
case GDParser::COMPLETION_METHOD:
- isfunction=true;
+ isfunction = true;
case GDParser::COMPLETION_INDEX: {
const GDParser::Node *node = p.get_completion_node();
- if (node->type!=GDParser::Node::TYPE_OPERATOR)
+ if (node->type != GDParser::Node::TYPE_OPERATOR)
break;
-
-
-
GDCompletionIdentifier t;
- if (_guess_expression_type(context,static_cast<const GDParser::OperatorNode *>(node)->arguments[0],p.get_completion_line(),t)) {
+ if (_guess_expression_type(context, static_cast<const GDParser::OperatorNode *>(node)->arguments[0], p.get_completion_line(), t)) {
- if (t.type==Variant::OBJECT && t.obj_type=="GDNativeClass") {
+ if (t.type == Variant::OBJECT && t.obj_type == "GDNativeClass") {
//native enum
Ref<GDNativeClass> gdn = t.value;
if (gdn.is_valid()) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name=gdn->get_name();
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
+ r_result.class_name = gdn->get_name();
+ r_result.class_member = p_symbol;
return OK;
-
}
- } else if (t.type==Variant::OBJECT && t.obj_type!=StringName()) {
+ } else if (t.type == Variant::OBJECT && t.obj_type != StringName()) {
Ref<GDScript> on_script;
if (t.value.get_type()) {
- Object *obj=t.value;
-
+ Object *obj = t.value;
if (obj) {
-
- on_script=obj->get_script();
+ on_script = obj->get_script();
if (on_script.is_valid()) {
int loc = on_script->get_member_line(p_symbol);
- if (loc>=0) {
- r_result.script=on_script;
- r_result.type=ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
- r_result.location=loc;
+ if (loc >= 0) {
+ r_result.script = on_script;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
+ r_result.location = loc;
return OK;
}
}
}
}
- if (ClassDB::has_method(t.obj_type,p_symbol)) {
+ if (ClassDB::has_method(t.obj_type, p_symbol)) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name=t.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = t.obj_type;
+ r_result.class_member = p_symbol;
return OK;
-
}
bool success;
- ClassDB::get_integer_constant(t.obj_type,p_symbol,&success);
+ ClassDB::get_integer_constant(t.obj_type, p_symbol, &success);
if (success) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name=t.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
+ r_result.class_name = t.obj_type;
+ r_result.class_member = p_symbol;
return OK;
}
-
- ClassDB::get_property_type(t.obj_type,p_symbol,&success);
+ ClassDB::get_property_type(t.obj_type, p_symbol, &success);
if (success) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
- r_result.class_name=t.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
+ r_result.class_name = t.obj_type;
+ r_result.class_member = p_symbol;
return OK;
}
-
} else {
Variant::CallError ce;
- Variant v = Variant::construct(t.type,NULL,0,ce);
+ Variant v = Variant::construct(t.type, NULL, 0, ce);
bool valid;
- v.get_numeric_constant_value(t.type,p_symbol,&valid);
+ v.get_numeric_constant_value(t.type, p_symbol, &valid);
if (valid) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
- r_result.class_name=Variant::get_type_name(t.type);
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
+ r_result.class_name = Variant::get_type_name(t.type);
+ r_result.class_member = p_symbol;
return OK;
}
//todo check all inputevent types for property
- v.get(p_symbol,&valid);
+ v.get(p_symbol, &valid);
if (valid) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
- r_result.class_name=Variant::get_type_name(t.type);
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
+ r_result.class_name = Variant::get_type_name(t.type);
+ r_result.class_member = p_symbol;
return OK;
}
if (v.has_method(p_symbol)) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name=Variant::get_type_name(t.type);
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = Variant::get_type_name(t.type);
+ r_result.class_member = p_symbol;
return OK;
-
}
-
-
}
}
-
} break;
case GDParser::COMPLETION_CALL_ARGUMENTS: {
@@ -3032,18 +2849,17 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
GDCompletionIdentifier cid = _get_native_class(context);
- if (cid.obj_type!=StringName()) {
+ if (cid.obj_type != StringName()) {
List<MethodInfo> vm;
- ClassDB::get_virtual_methods(cid.obj_type,&vm);
- for(List<MethodInfo>::Element *E=vm.front();E;E=E->next()) {
+ ClassDB::get_virtual_methods(cid.obj_type, &vm);
+ for (List<MethodInfo>::Element *E = vm.front(); E; E = E->next()) {
- if (p_symbol==E->get().name) {
+ if (p_symbol == E->get().name) {
- r_result.type=ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
- r_result.class_name=cid.obj_type;
- r_result.class_member=p_symbol;
+ r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
+ r_result.class_name = cid.obj_type;
+ r_result.class_member = p_symbol;
return OK;
-
}
}
}
@@ -3053,10 +2869,8 @@ Error GDScriptLanguage::lookup_code(const String& p_code, const String& p_symbol
return ERR_CANT_RESOLVE;
} break;
-
}
-
return ERR_CANT_RESOLVE;
}
diff --git a/modules/gdscript/gd_function.cpp b/modules/gdscript/gd_function.cpp
index 519fb1cd8c..aaf97001e9 100644
--- a/modules/gdscript/gd_function.cpp
+++ b/modules/gdscript/gd_function.cpp
@@ -28,21 +28,21 @@
/*************************************************************************/
#include "gd_function.h"
+#include "gd_functions.h"
#include "gd_script.h"
#include "os/os.h"
-#include "gd_functions.h"
-Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self, Variant *p_stack,String& r_error) const{
+Variant *GDFunction::_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const {
- int address = p_address&ADDR_MASK;
+ int address = p_address & ADDR_MASK;
//sequential table (jump table generated by compiler)
- switch((p_address&ADDR_TYPE_MASK)>>ADDR_BITS) {
+ switch ((p_address & ADDR_TYPE_MASK) >> ADDR_BITS) {
case ADDR_TYPE_SELF: {
if (!p_instance) {
- r_error="Cannot access self without instance.";
+ r_error = "Cannot access self without instance.";
return NULL;
}
return &self;
@@ -54,7 +54,7 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript
case ADDR_TYPE_MEMBER: {
//member indexing is O(1)
if (!p_instance) {
- r_error="Cannot access member without instance.";
+ r_error = "Cannot access member without instance.";
return NULL;
}
return &p_instance->members[address];
@@ -62,41 +62,38 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript
case ADDR_TYPE_CLASS_CONSTANT: {
//todo change to index!
- GDScript *o=p_script;
- ERR_FAIL_INDEX_V(address,_global_names_count,NULL);
+ GDScript *o = p_script;
+ ERR_FAIL_INDEX_V(address, _global_names_count, NULL);
const StringName *sn = &_global_names_ptr[address];
- while(o) {
- GDScript *s=o;
- while(s) {
+ while (o) {
+ GDScript *s = o;
+ while (s) {
- Map<StringName,Variant>::Element *E=s->constants.find(*sn);
+ Map<StringName, Variant>::Element *E = s->constants.find(*sn);
if (E) {
return &E->get();
}
- s=s->_base;
+ s = s->_base;
}
- o=o->_owner;
+ o = o->_owner;
}
-
ERR_EXPLAIN("GDCompiler bug..");
ERR_FAIL_V(NULL);
} break;
case ADDR_TYPE_LOCAL_CONSTANT: {
- ERR_FAIL_INDEX_V(address,_constant_count,NULL);
+ ERR_FAIL_INDEX_V(address, _constant_count, NULL);
return &_constants_ptr[address];
} break;
case ADDR_TYPE_STACK:
case ADDR_TYPE_STACK_VARIABLE: {
- ERR_FAIL_INDEX_V(address,_stack_size,NULL);
+ ERR_FAIL_INDEX_V(address, _stack_size, NULL);
return &p_stack[address];
} break;
case ADDR_TYPE_GLOBAL: {
-
- ERR_FAIL_INDEX_V(address,GDScriptLanguage::get_singleton()->get_global_array_size(),NULL);
-
+ ERR_FAIL_INDEX_V(address, GDScriptLanguage::get_singleton()->get_global_array_size(), NULL);
return &GDScriptLanguage::get_singleton()->get_global_array()[address];
} break;
@@ -110,37 +107,33 @@ Variant *GDFunction::_get_variant(int p_address,GDInstance *p_instance,GDScript
return NULL;
}
-
-String GDFunction::_get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const {
-
-
+String GDFunction::_get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const {
String err_text;
- if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- int errorarg=p_err.argument;
- err_text="Invalid type in "+p_where+". Cannot convert argument "+itos(errorarg+1)+" from "+Variant::get_type_name(argptrs[errorarg]->get_type())+" to "+Variant::get_type_name(p_err.expected)+".";
- } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
- } else if (p_err.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- err_text="Invalid call to "+p_where+". Expected "+itos(p_err.argument)+" arguments.";
- } else if (p_err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
- err_text="Invalid call. Nonexistent "+p_where+".";
- } else if (p_err.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
- err_text="Attempt to call "+p_where+" on a null instance.";
+ if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ int errorarg = p_err.argument;
+ err_text = "Invalid type in " + p_where + ". Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(p_err.expected) + ".";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
+ err_text = "Invalid call to " + p_where + ". Expected " + itos(p_err.argument) + " arguments.";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
+ err_text = "Invalid call. Nonexistent " + p_where + ".";
+ } else if (p_err.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
+ err_text = "Attempt to call " + p_where + " on a null instance.";
} else {
- err_text="Bug, call error: #"+itos(p_err.error);
+ err_text = "Bug, call error: #" + itos(p_err.error);
}
return err_text;
-
}
-static String _get_var_type(const Variant* p_type) {
+static String _get_var_type(const Variant *p_type) {
String basestr;
- if (p_type->get_type()==Variant::OBJECT) {
+ if (p_type->get_type() == Variant::OBJECT) {
Object *bobj = *p_type;
if (!bobj) {
basestr = "null instance";
@@ -148,15 +141,15 @@ static String _get_var_type(const Variant* p_type) {
#ifdef DEBUG_ENABLED
if (ObjectDB::instance_validate(bobj)) {
if (bobj->get_script_instance())
- basestr= bobj->get_class()+" ("+bobj->get_script_instance()->get_script()->get_path().get_file()+")";
+ basestr = bobj->get_class() + " (" + bobj->get_script_instance()->get_script()->get_path().get_file() + ")";
else
basestr = bobj->get_class();
} else {
- basestr="previously freed instance";
+ basestr = "previously freed instance";
}
#else
- basestr="Object";
+ basestr = "Object";
#endif
}
@@ -165,114 +158,108 @@ static String _get_var_type(const Variant* p_type) {
}
return basestr;
-
}
-Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError& r_err, CallState *p_state) {
-
+Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state) {
if (!_code_ptr) {
return Variant();
}
- r_err.error=Variant::CallError::CALL_OK;
+ r_err.error = Variant::CallError::CALL_OK;
Variant self;
Variant retvalue;
Variant *stack = NULL;
Variant **call_args;
- int defarg=0;
+ int defarg = 0;
#ifdef DEBUG_ENABLED
- //GDScriptLanguage::get_singleton()->calls++;
+//GDScriptLanguage::get_singleton()->calls++;
#endif
- uint32_t alloca_size=0;
+ uint32_t alloca_size = 0;
GDScript *_class;
- int ip=0;
- int line=_initial_line;
-
-
+ int ip = 0;
+ int line = _initial_line;
if (p_state) {
//use existing (supplied) state (yielded)
- stack=(Variant*)p_state->stack.ptr();
- call_args=(Variant**)stack + sizeof(Variant)*p_state->stack_size;
- line=p_state->line;
- ip=p_state->ip;
- alloca_size=p_state->stack.size();
- _class=p_state->_class;
- p_instance=p_state->instance;
- defarg=p_state->defarg;
- self=p_state->self;
+ stack = (Variant *)p_state->stack.ptr();
+ call_args = (Variant **)stack + sizeof(Variant) * p_state->stack_size;
+ line = p_state->line;
+ ip = p_state->ip;
+ alloca_size = p_state->stack.size();
+ _class = p_state->_class;
+ p_instance = p_state->instance;
+ defarg = p_state->defarg;
+ self = p_state->self;
//stack[p_state->result_pos]=p_state->result; //assign stack with result
} else {
- if (p_argcount!=_argument_count) {
-
- if (p_argcount>_argument_count) {
+ if (p_argcount != _argument_count) {
- r_err.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_err.argument=_argument_count;
+ if (p_argcount > _argument_count) {
+ r_err.error = Variant::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=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_err.argument=_argument_count - _default_arg_count;
+ r_err.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_err.argument = _argument_count - _default_arg_count;
return Variant();
} else {
- defarg=_argument_count-p_argcount;
+ defarg = _argument_count - p_argcount;
}
}
- alloca_size = sizeof(Variant*)*_call_size + sizeof(Variant)*_stack_size;
+ alloca_size = sizeof(Variant *) * _call_size + sizeof(Variant) * _stack_size;
if (alloca_size) {
- uint8_t *aptr = (uint8_t*)alloca(alloca_size);
+ uint8_t *aptr = (uint8_t *)alloca(alloca_size);
if (_stack_size) {
- stack=(Variant*)aptr;
- for(int i=0;i<p_argcount;i++)
- memnew_placement(&stack[i],Variant(*p_args[i]));
- for(int i=p_argcount;i<_stack_size;i++)
- memnew_placement(&stack[i],Variant);
+ stack = (Variant *)aptr;
+ for (int i = 0; i < p_argcount; i++)
+ memnew_placement(&stack[i], Variant(*p_args[i]));
+ for (int i = p_argcount; i < _stack_size; i++)
+ memnew_placement(&stack[i], Variant);
} else {
- stack=NULL;
+ stack = NULL;
}
if (_call_size) {
- call_args = (Variant**)&aptr[sizeof(Variant)*_stack_size];
+ call_args = (Variant **)&aptr[sizeof(Variant) * _stack_size];
} else {
- call_args=NULL;
+ call_args = NULL;
}
-
} else {
- stack=NULL;
- call_args=NULL;
+ stack = NULL;
+ call_args = NULL;
}
if (p_instance) {
- if (p_instance->base_ref && static_cast<Reference*>(p_instance->owner)->is_referenced()) {
+ if (p_instance->base_ref && static_cast<Reference *>(p_instance->owner)->is_referenced()) {
- self=REF(static_cast<Reference*>(p_instance->owner));
+ self = REF(static_cast<Reference *>(p_instance->owner));
} else {
- self=p_instance->owner;
+ self = p_instance->owner;
}
- _class=p_instance->script.ptr();
+ _class = p_instance->script.ptr();
} else {
- _class=_script;
+ _class = _script;
}
}
@@ -281,537 +268,519 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton())
- GDScriptLanguage::get_singleton()->enter_function(p_instance,this,stack,&ip,&line);
-
-#define CHECK_SPACE(m_space)\
- ERR_BREAK((ip+m_space)>_code_size)
+ GDScriptLanguage::get_singleton()->enter_function(p_instance, this, stack, &ip, &line);
-#define GET_VARIANT_PTR(m_v,m_code_ofs) \
- Variant *m_v; \
- m_v = _get_variant(_code_ptr[ip+m_code_ofs],p_instance,_class,self,stack,err_text);\
- if (!m_v)\
- break;
+#define CHECK_SPACE(m_space) \
+ 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, _class, self, stack, err_text); \
+ if (!m_v) \
+ break;
#else
#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,_class,self,stack,err_text);
+#define GET_VARIANT_PTR(m_v, m_code_ofs) \
+ Variant *m_v; \
+ m_v = _get_variant(_code_ptr[ip + m_code_ofs], p_instance, _class, self, stack, err_text);
#endif
-
#ifdef DEBUG_ENABLED
uint64_t function_start_time;
uint64_t function_call_time;
if (GDScriptLanguage::get_singleton()->profiling) {
- function_start_time=OS::get_singleton()->get_ticks_usec();
- function_call_time=0;
+ function_start_time = OS::get_singleton()->get_ticks_usec();
+ function_call_time = 0;
profile.call_count++;
profile.frame_call_count++;
}
#endif
- bool exit_ok=false;
+ bool exit_ok = false;
- while(ip<_code_size) {
+ while (ip < _code_size) {
-
- int last_opcode=_code_ptr[ip];
- switch(_code_ptr[ip]) {
+ int last_opcode = _code_ptr[ip];
+ switch (_code_ptr[ip]) {
case OPCODE_OPERATOR: {
CHECK_SPACE(5);
bool valid;
- Variant::Operator op = (Variant::Operator)_code_ptr[ip+1];
- ERR_BREAK(op>=Variant::OP_MAX);
+ Variant::Operator op = (Variant::Operator)_code_ptr[ip + 1];
+ ERR_BREAK(op >= Variant::OP_MAX);
- GET_VARIANT_PTR(a,2);
- GET_VARIANT_PTR(b,3);
- GET_VARIANT_PTR(dst,4);
+ 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);
+ Variant::evaluate(op, *a, *b, ret, valid);
#else
- Variant::evaluate(op,*a,*b,*dst,valid);
+ Variant::evaluate(op, *a, *b, *dst, valid);
#endif
if (!valid) {
#ifdef DEBUG_ENABLED
- if (ret.get_type()==Variant::STRING) {
+ 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)+"'.";
+ 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)+"'.";
+ 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) + "'.";
}
#endif
break;
-
}
#ifdef DEBUG_ENABLED
- *dst=ret;
+ *dst = ret;
#endif
- ip+=5;
+ ip += 5;
continue;
}
case OPCODE_EXTENDS_TEST: {
CHECK_SPACE(4);
- GET_VARIANT_PTR(a,1);
- GET_VARIANT_PTR(b,2);
- GET_VARIANT_PTR(dst,3);
+ GET_VARIANT_PTR(a, 1);
+ GET_VARIANT_PTR(b, 2);
+ GET_VARIANT_PTR(dst, 3);
#ifdef DEBUG_ENABLED
- if (a->get_type()!=Variant::OBJECT || a->operator Object*()==NULL) {
+ if (a->get_type() != Variant::OBJECT || a->operator Object *() == NULL) {
- err_text="Left operand of 'extends' is not an instance of anything.";
+ err_text = "Left operand of 'extends' is not an instance of anything.";
break;
-
}
- if (b->get_type()!=Variant::OBJECT || b->operator Object*()==NULL) {
+ if (b->get_type() != Variant::OBJECT || b->operator Object *() == NULL) {
- err_text="Right operand of 'extends' is not a class.";
+ err_text = "Right operand of 'extends' is not a class.";
break;
-
}
#endif
-
Object *obj_A = *a;
Object *obj_B = *b;
-
GDScript *scr_B = obj_B->cast_to<GDScript>();
- bool extends_ok=false;
+ bool extends_ok = false;
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()) {
+ 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());
+ GDScript *cmp = static_cast<GDScript *>(obj_A->get_script_instance()->get_script().ptr());
//bool found=false;
- while(cmp) {
+ while (cmp) {
- if (cmp==scr_B) {
+ if (cmp == scr_B) {
//inherits from script, all ok
- extends_ok=true;
+ extends_ok = true;
break;
-
}
- cmp=cmp->_base;
+ cmp = cmp->_base;
}
-
}
-
} else {
- GDNativeClass *nc= obj_B->cast_to<GDNativeClass>();
+ GDNativeClass *nc = obj_B->cast_to<GDNativeClass>();
if (!nc) {
- err_text="Right operand of 'extends' is not a class (type: '"+obj_B->get_class()+"').";
+ err_text = "Right operand of 'extends' is not a class (type: '" + obj_B->get_class() + "').";
break;
}
- extends_ok=ClassDB::is_parent_class(obj_A->get_class_name(),nc->get_name());
+ extends_ok = ClassDB::is_parent_class(obj_A->get_class_name(), nc->get_name());
}
- *dst=extends_ok;
- ip+=4;
+ *dst = extends_ok;
+ ip += 4;
continue;
}
case OPCODE_SET: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(dst,1);
- GET_VARIANT_PTR(index,2);
- GET_VARIANT_PTR(value,3);
+ GET_VARIANT_PTR(dst, 1);
+ GET_VARIANT_PTR(index, 2);
+ GET_VARIANT_PTR(value, 3);
bool valid;
- dst->set(*index,*value,&valid);
+ dst->set(*index, *value, &valid);
if (!valid) {
String v = index->operator String();
- if (v!="") {
- v="'"+v+"'";
+ if (v != "") {
+ v = "'" + v + "'";
} else {
- v="of type '"+_get_var_type(index)+"'";
+ v = "of type '" + _get_var_type(index) + "'";
}
- err_text="Invalid set index "+v+" (on base: '"+_get_var_type(dst)+"').";
+ err_text = "Invalid set index " + v + " (on base: '" + _get_var_type(dst) + "').";
break;
}
- ip+=4;
+ ip += 4;
continue;
}
case OPCODE_GET: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(src,1);
- GET_VARIANT_PTR(index,2);
- GET_VARIANT_PTR(dst,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);
+ Variant ret = src->get(*index, &valid);
#else
- *dst = src->get(*index,&valid);
+ *dst = src->get(*index, &valid);
#endif
if (!valid) {
String v = index->operator String();
- if (v!="") {
- v="'"+v+"'";
+ if (v != "") {
+ v = "'" + v + "'";
} else {
- v="of type '"+_get_var_type(index)+"'";
+ v = "of type '" + _get_var_type(index) + "'";
}
- err_text="Invalid get index "+v+" (on base: '"+_get_var_type(src)+"').";
+ err_text = "Invalid get index " + v + " (on base: '" + _get_var_type(src) + "').";
break;
}
#ifdef DEBUG_ENABLED
- *dst=ret;
+ *dst = ret;
#endif
- ip+=4;
+ ip += 4;
continue;
}
case OPCODE_SET_NAMED: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(dst,1);
- GET_VARIANT_PTR(value,3);
+ GET_VARIANT_PTR(dst, 1);
+ GET_VARIANT_PTR(value, 3);
- int indexname = _code_ptr[ip+2];
+ int indexname = _code_ptr[ip + 2];
- ERR_BREAK(indexname<0 || indexname>=_global_names_count);
+ ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
const StringName *index = &_global_names_ptr[indexname];
bool valid;
- dst->set_named(*index,*value,&valid);
+ dst->set_named(*index, *value, &valid);
if (!valid) {
String err_type;
- err_text="Invalid set index '"+String(*index)+"' (on base: '"+_get_var_type(dst)+"').";
+ err_text = "Invalid set index '" + String(*index) + "' (on base: '" + _get_var_type(dst) + "').";
break;
}
- ip+=4;
+ ip += 4;
continue;
}
case OPCODE_GET_NAMED: {
-
CHECK_SPACE(4);
- GET_VARIANT_PTR(src,1);
- GET_VARIANT_PTR(dst,3);
+ GET_VARIANT_PTR(src, 1);
+ GET_VARIANT_PTR(dst, 3);
- int indexname = _code_ptr[ip+2];
+ int indexname = _code_ptr[ip + 2];
- ERR_BREAK(indexname<0 || indexname>=_global_names_count);
+ 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);
+ Variant ret = src->get_named(*index, &valid);
#else
- *dst = src->get_named(*index,&valid);
+ *dst = src->get_named(*index, &valid);
#endif
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()+"()' ?";
+ err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "'). Did you mean '." + index->operator String() + "()' ?";
} else {
- err_text="Invalid get index '"+index->operator String()+"' (on base: '"+_get_var_type(src)+"').";
+ err_text = "Invalid get index '" + index->operator String() + "' (on base: '" + _get_var_type(src) + "').";
}
break;
}
#ifdef DEBUG_ENABLED
- *dst=ret;
+ *dst = ret;
#endif
- ip+=4;
+ ip += 4;
continue;
}
case OPCODE_SET_MEMBER: {
CHECK_SPACE(3);
- int indexname = _code_ptr[ip+1];
- ERR_BREAK(indexname<0 || indexname>=_global_names_count);
+ int indexname = _code_ptr[ip + 1];
+ ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
const StringName *index = &_global_names_ptr[indexname];
- GET_VARIANT_PTR(src,2);
+ GET_VARIANT_PTR(src, 2);
bool valid;
- bool ok = ClassDB::set_property(p_instance->owner,*index,*src,&valid);
+ bool ok = ClassDB::set_property(p_instance->owner, *index, *src, &valid);
#ifdef DEBUG_ENABLED
if (!ok) {
- err_text="Internal error setting property: "+String(*index);
+ err_text = "Internal error setting property: " + String(*index);
break;
} else if (!valid) {
- err_text="Error setting property '"+String(*index)+"' with value of type "+Variant::get_type_name(src->get_type())+".";
+ err_text = "Error setting property '" + String(*index) + "' with value of type " + Variant::get_type_name(src->get_type()) + ".";
break;
-
}
#endif
- ip+=3;
+ ip += 3;
continue;
}
case OPCODE_GET_MEMBER: {
CHECK_SPACE(3);
- int indexname = _code_ptr[ip+1];
- ERR_BREAK(indexname<0 || indexname>=_global_names_count);
+ int indexname = _code_ptr[ip + 1];
+ ERR_BREAK(indexname < 0 || indexname >= _global_names_count);
const StringName *index = &_global_names_ptr[indexname];
- GET_VARIANT_PTR(dst,2);
- bool ok = ClassDB::get_property(p_instance->owner,*index,*dst);
+ GET_VARIANT_PTR(dst, 2);
+ bool ok = ClassDB::get_property(p_instance->owner, *index, *dst);
#ifdef DEBUG_ENABLED
if (!ok) {
- err_text="Internal error getting property: "+String(*index);
+ err_text = "Internal error getting property: " + String(*index);
break;
}
#endif
- ip+=3;
+ ip += 3;
continue;
}
case OPCODE_ASSIGN: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(dst,1);
- GET_VARIANT_PTR(src,2);
+ GET_VARIANT_PTR(dst, 1);
+ GET_VARIANT_PTR(src, 2);
*dst = *src;
- ip+=3;
+ ip += 3;
continue;
}
case OPCODE_ASSIGN_TRUE: {
CHECK_SPACE(2);
- GET_VARIANT_PTR(dst,1);
+ GET_VARIANT_PTR(dst, 1);
*dst = true;
- ip+=2;
+ ip += 2;
continue;
}
case OPCODE_ASSIGN_FALSE: {
CHECK_SPACE(2);
- GET_VARIANT_PTR(dst,1);
+ GET_VARIANT_PTR(dst, 1);
*dst = false;
- ip+=2;
+ ip += 2;
continue;
}
case 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::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;
+ for (int i = 0; i < argc; i++) {
+ GET_VARIANT_PTR(v, 3 + i);
+ argptrs[i] = v;
}
- GET_VARIANT_PTR(dst,3+argc);
+ GET_VARIANT_PTR(dst, 3 + argc);
Variant::CallError err;
- *dst = Variant::construct(t,(const Variant**)argptrs,argc,err);
+ *dst = Variant::construct(t, (const Variant **)argptrs, argc, err);
- if (err.error!=Variant::CallError::CALL_OK) {
+ if (err.error != Variant::CallError::CALL_OK) {
- err_text=_get_call_error(err,"'"+Variant::get_type_name(t)+"' constructor",(const Variant**)argptrs);
+ err_text = _get_call_error(err, "'" + Variant::get_type_name(t) + "' constructor", (const Variant **)argptrs);
break;
}
- ip+=4+argc;
+ ip += 4 + argc;
//construct a basic type
continue;
}
case OPCODE_CONSTRUCT_ARRAY: {
CHECK_SPACE(1);
- int argc=_code_ptr[ip+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;
+ 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);
+ GET_VARIANT_PTR(dst, 2 + argc);
- *dst=array;
+ *dst = array;
- ip+=3+argc;
+ ip += 3 + argc;
continue;
}
case OPCODE_CONSTRUCT_DICTIONARY: {
CHECK_SPACE(1);
- int argc=_code_ptr[ip+1];
+ int argc = _code_ptr[ip + 1];
Dictionary dict; //arrays are always shared
- CHECK_SPACE(argc*2+2);
+ 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;
+ 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);
+ GET_VARIANT_PTR(dst, 2 + argc * 2);
- *dst=dict;
+ *dst = dict;
- ip+=3+argc*2;
+ ip += 3 + argc * 2;
continue;
}
case OPCODE_CALL_RETURN:
case OPCODE_CALL: {
-
CHECK_SPACE(4);
- bool call_ret = _code_ptr[ip]==OPCODE_CALL_RETURN;
+ 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];
+ int argc = _code_ptr[ip + 1];
+ GET_VARIANT_PTR(base, 2);
+ int nameg = _code_ptr[ip + 3];
- ERR_BREAK(nameg<0 || nameg>=_global_names_count);
+ ERR_BREAK(nameg < 0 || nameg >= _global_names_count);
const StringName *methodname = &_global_names_ptr[nameg];
- ERR_BREAK(argc<0);
- ip+=4;
- CHECK_SPACE(argc+1);
+ 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;
+ for (int i = 0; i < argc; i++) {
+ GET_VARIANT_PTR(v, i);
+ argptrs[i] = v;
}
#ifdef DEBUG_ENABLED
uint64_t call_time;
if (GDScriptLanguage::get_singleton()->profiling) {
- call_time=OS::get_singleton()->get_ticks_usec();
+ call_time = OS::get_singleton()->get_ticks_usec();
}
#endif
Variant::CallError err;
if (call_ret) {
- GET_VARIANT_PTR(ret,argc);
- base->call_ptr(*methodname,(const Variant**)argptrs,argc,ret,err);
+ GET_VARIANT_PTR(ret, argc);
+ base->call_ptr(*methodname, (const Variant **)argptrs, argc, ret, err);
} else {
- base->call_ptr(*methodname,(const Variant**)argptrs,argc,NULL,err);
+ base->call_ptr(*methodname, (const Variant **)argptrs, argc, NULL, err);
}
#ifdef DEBUG_ENABLED
if (GDScriptLanguage::get_singleton()->profiling) {
- function_call_time+=OS::get_singleton()->get_ticks_usec() - call_time;
+ function_call_time += OS::get_singleton()->get_ticks_usec() - call_time;
}
#endif
- if (err.error!=Variant::CallError::CALL_OK) {
-
+ if (err.error != Variant::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==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- err.argument-=1;
+ if (methodstr == "call") {
+ if (argc >= 1) {
+ methodstr = String(*argptrs[0]) + " (via call)";
+ if (err.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ err.argument -= 1;
}
}
- } else if (methodstr=="free") {
+ } else if (methodstr == "free") {
- if (err.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
+ if (err.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
if (base->is_ref()) {
- err_text="Attempted to free a reference.";
+ err_text = "Attempted to free a reference.";
break;
- } else if (base->get_type()==Variant::OBJECT) {
+ } else if (base->get_type() == Variant::OBJECT) {
- err_text="Attempted to free a locked object (calling or emitting).";
+ err_text = "Attempted to free a locked object (calling or emitting).";
break;
}
}
}
- err_text=_get_call_error(err,"function '"+methodstr+"' in base '"+basestr+"'",(const Variant**)argptrs);
+ err_text = _get_call_error(err, "function '" + methodstr + "' in base '" + basestr + "'", (const Variant **)argptrs);
break;
}
//_call_func(NULL,base,*methodname,ip,argc,p_instance,stack);
- ip+=argc+1;
+ ip += argc + 1;
continue;
}
case OPCODE_CALL_BUILT_IN: {
CHECK_SPACE(4);
- GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip+1]);
- int argc=_code_ptr[ip+2];
- ERR_BREAK(argc<0);
+ GDFunctions::Function func = GDFunctions::Function(_code_ptr[ip + 1]);
+ int argc = _code_ptr[ip + 2];
+ ERR_BREAK(argc < 0);
- ip+=3;
- CHECK_SPACE(argc+1);
+ 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;
+ for (int i = 0; i < argc; i++) {
+ GET_VARIANT_PTR(v, i);
+ argptrs[i] = v;
}
- GET_VARIANT_PTR(dst,argc);
+ GET_VARIANT_PTR(dst, argc);
Variant::CallError err;
- GDFunctions::call(func,(const Variant**)argptrs,argc,*dst,err);
-
- if (err.error!=Variant::CallError::CALL_OK) {
+ GDFunctions::call(func, (const Variant **)argptrs, argc, *dst, err);
+ if (err.error != Variant::CallError::CALL_OK) {
String methodstr = GDFunctions::get_func_name(func);
- if (dst->get_type()==Variant::STRING) {
+ if (dst->get_type() == Variant::STRING) {
//call provided error string
- err_text="Error calling built-in function '"+methodstr+"': "+String(*dst);
+ err_text = "Error calling built-in function '" + methodstr + "': " + String(*dst);
} else {
- err_text=_get_call_error(err,"built-in function '"+methodstr+"'",(const Variant**)argptrs);
+ err_text = _get_call_error(err, "built-in function '" + methodstr + "'", (const Variant **)argptrs);
}
break;
}
- ip+=argc+1;
+ ip += argc + 1;
continue;
}
case OPCODE_CALL_SELF: {
@@ -821,37 +790,36 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a
case OPCODE_CALL_SELF_BASE: {
CHECK_SPACE(2);
- int self_fun = _code_ptr[ip+1];
+ int self_fun = _code_ptr[ip + 1];
#ifdef DEBUG_ENABLED
- if (self_fun<0 || self_fun>=_global_names_count) {
+ if (self_fun < 0 || self_fun >= _global_names_count) {
- err_text="compiler bug, function name not found";
+ err_text = "compiler bug, function name not found";
break;
}
#endif
const StringName *methodname = &_global_names_ptr[self_fun];
- int argc=_code_ptr[ip+2];
+ int argc = _code_ptr[ip + 2];
- CHECK_SPACE(2+argc+1);
+ 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;
+ for (int i = 0; i < argc; i++) {
+ GET_VARIANT_PTR(v, i + 3);
+ argptrs[i] = v;
}
- GET_VARIANT_PTR(dst,argc+3);
+ GET_VARIANT_PTR(dst, argc + 3);
const GDScript *gds = _script;
-
- const Map<StringName,GDFunction*>::Element *E=NULL;
+ const Map<StringName, GDFunction *>::Element *E = NULL;
while (gds->base.ptr()) {
- gds=gds->base.ptr();
- E=gds->member_functions.find(*methodname);
+ gds = gds->base.ptr();
+ E = gds->member_functions.find(*methodname);
if (E)
break;
}
@@ -860,344 +828,332 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a
if (E) {
- *dst=E->get()->call(p_instance,(const Variant**)argptrs,argc,err);
+ *dst = E->get()->call(p_instance, (const Variant **)argptrs, argc, err);
} else if (gds->native.ptr()) {
- if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
+ if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
- MethodBind *mb = ClassDB::get_method(gds->native->get_name(),*methodname);
+ MethodBind *mb = ClassDB::get_method(gds->native->get_name(), *methodname);
if (!mb) {
- err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
} else {
- *dst=mb->call(p_instance->owner,(const Variant**)argptrs,argc,err);
+ *dst = mb->call(p_instance->owner, (const Variant **)argptrs, argc, err);
}
} else {
- err.error=Variant::CallError::CALL_OK;
+ err.error = Variant::CallError::CALL_OK;
}
} else {
- if (*methodname!=GDScriptLanguage::get_singleton()->strings._init) {
- err.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ if (*methodname != GDScriptLanguage::get_singleton()->strings._init) {
+ err.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
} else {
- err.error=Variant::CallError::CALL_OK;
+ err.error = Variant::CallError::CALL_OK;
}
}
-
- if (err.error!=Variant::CallError::CALL_OK) {
-
+ if (err.error != Variant::CallError::CALL_OK) {
String methodstr = *methodname;
- err_text=_get_call_error(err,"function '"+methodstr+"'",(const Variant**)argptrs);
+ err_text = _get_call_error(err, "function '" + methodstr + "'", (const Variant **)argptrs);
break;
}
- ip+=4+argc;
+ ip += 4 + argc;
continue;
}
case OPCODE_YIELD:
case OPCODE_YIELD_SIGNAL: {
- int ipofs=1;
- if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) {
+ int ipofs = 1;
+ if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) {
CHECK_SPACE(4);
- ipofs+=2;
+ ipofs += 2;
} else {
CHECK_SPACE(2);
-
}
- Ref<GDFunctionState> gdfs = memnew( GDFunctionState );
- gdfs->function=this;
+ Ref<GDFunctionState> gdfs = memnew(GDFunctionState);
+ 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[sizeof(Variant)*i],Variant(stack[i]));
+ for (int i = 0; i < _stack_size; i++) {
+ memnew_placement(&gdfs->state.stack[sizeof(Variant) * i], Variant(stack[i]));
}
- gdfs->state.stack_size=_stack_size;
- gdfs->state.self=self;
- gdfs->state.alloca_size=alloca_size;
- gdfs->state._class=_class;
- gdfs->state.ip=ip+ipofs;
- gdfs->state.line=line;
- gdfs->state.instance_id=(p_instance && p_instance->get_owner())?p_instance->get_owner()->get_instance_ID():0;
- gdfs->state.script_id=_class->get_instance_ID();
+ gdfs->state.stack_size = _stack_size;
+ gdfs->state.self = self;
+ gdfs->state.alloca_size = alloca_size;
+ gdfs->state._class = _class;
+ gdfs->state.ip = ip + ipofs;
+ gdfs->state.line = line;
+ gdfs->state.instance_id = (p_instance && p_instance->get_owner()) ? p_instance->get_owner()->get_instance_ID() : 0;
+ gdfs->state.script_id = _class->get_instance_ID();
//gdfs->state.result_pos=ip+ipofs-1;
- gdfs->state.defarg=defarg;
- gdfs->state.instance=p_instance;
- gdfs->function=this;
+ gdfs->state.defarg = defarg;
+ gdfs->state.instance = p_instance;
+ gdfs->function = this;
- retvalue=gdfs;
+ retvalue = gdfs;
- if (_code_ptr[ip]==OPCODE_YIELD_SIGNAL) {
- GET_VARIANT_PTR(argobj,1);
- GET_VARIANT_PTR(argname,2);
+ if (_code_ptr[ip] == OPCODE_YIELD_SIGNAL) {
+ GET_VARIANT_PTR(argobj, 1);
+ GET_VARIANT_PTR(argname, 2);
//do the oneshot connect
- if (argobj->get_type()!=Variant::OBJECT) {
- err_text="First argument of yield() not of type object.";
+ if (argobj->get_type() != Variant::OBJECT) {
+ err_text = "First argument of yield() not of type object.";
break;
}
- if (argname->get_type()!=Variant::STRING) {
- err_text="Second argument of yield() not a string (for signal name).";
+ if (argname->get_type() != Variant::STRING) {
+ err_text = "Second argument of yield() not a string (for signal name).";
break;
}
- Object *obj=argobj->operator Object *();
+ Object *obj = argobj->operator Object *();
String signal = argname->operator String();
#ifdef DEBUG_ENABLED
if (!obj) {
- err_text="First argument of yield() is null.";
+ err_text = "First argument of yield() is null.";
break;
}
if (ScriptDebugger::get_singleton()) {
if (!ObjectDB::instance_validate(obj)) {
- err_text="First argument of yield() is a previously freed instance.";
+ err_text = "First argument of yield() is a previously freed instance.";
break;
}
}
- if (signal.length()==0) {
+ if (signal.length() == 0) {
- err_text="Second argument of yield() is an empty string (for signal name).";
+ err_text = "Second argument of yield() is an empty string (for signal name).";
break;
}
#endif
- Error err = obj->connect(signal,gdfs.ptr(),"_signal_callback",varray(gdfs),Object::CONNECT_ONESHOT);
- if (err!=OK) {
- err_text="Error connecting to signal: "+signal+" during yield().";
+ Error err = obj->connect(signal, gdfs.ptr(), "_signal_callback", varray(gdfs), Object::CONNECT_ONESHOT);
+ if (err != OK) {
+ err_text = "Error connecting to signal: " + signal + " during yield().";
break;
}
-
-
}
- exit_ok=true;
+ exit_ok = true;
break;
}
case OPCODE_YIELD_RESUME: {
CHECK_SPACE(2);
if (!p_state) {
- err_text=("Invalid Resume (bug?)");
+ err_text = ("Invalid Resume (bug?)");
break;
}
- GET_VARIANT_PTR(result,1);
- *result=p_state->result;
- ip+=2;
+ GET_VARIANT_PTR(result, 1);
+ *result = p_state->result;
+ ip += 2;
continue;
}
case OPCODE_JUMP: {
CHECK_SPACE(2);
- int to = _code_ptr[ip+1];
+ int to = _code_ptr[ip + 1];
- ERR_BREAK(to<0 || to>_code_size);
- ip=to;
+ ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
continue;
}
case OPCODE_JUMP_IF: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(test,1);
+ GET_VARIANT_PTR(test, 1);
bool valid;
bool result = test->booleanize(valid);
#ifdef DEBUG_ENABLED
if (!valid) {
- err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
+ err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type());
break;
}
#endif
if (result) {
- int to = _code_ptr[ip+2];
- ERR_BREAK(to<0 || to>_code_size);
- ip=to;
+ int to = _code_ptr[ip + 2];
+ ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
continue;
}
- ip+=3;
+ ip += 3;
continue;
}
case OPCODE_JUMP_IF_NOT: {
CHECK_SPACE(3);
- GET_VARIANT_PTR(test,1);
+ GET_VARIANT_PTR(test, 1);
bool valid;
bool result = test->booleanize(valid);
#ifdef DEBUG_ENABLED
if (!valid) {
- err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
+ err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type());
break;
}
#endif
if (!result) {
- int to = _code_ptr[ip+2];
- ERR_BREAK(to<0 || to>_code_size);
- ip=to;
+ int to = _code_ptr[ip + 2];
+ ERR_BREAK(to < 0 || to > _code_size);
+ ip = to;
continue;
}
- ip+=3;
+ ip += 3;
continue;
}
case OPCODE_JUMP_TO_DEF_ARGUMENT: {
CHECK_SPACE(2);
- ip=_default_arg_ptr[defarg];
+ ip = _default_arg_ptr[defarg];
continue;
}
case OPCODE_RETURN: {
CHECK_SPACE(2);
- GET_VARIANT_PTR(r,1);
- retvalue=*r;
- exit_ok=true;
+ GET_VARIANT_PTR(r, 1);
+ retvalue = *r;
+ exit_ok = true;
break;
}
case OPCODE_ITERATE_BEGIN: {
CHECK_SPACE(8); //space for this an regular iterate
- GET_VARIANT_PTR(counter,1);
- GET_VARIANT_PTR(container,2);
+ GET_VARIANT_PTR(counter, 1);
+ GET_VARIANT_PTR(container, 2);
bool valid;
- if (!container->iter_init(*counter,valid)) {
+ if (!container->iter_init(*counter, valid)) {
if (!valid) {
- err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"'.";
+ err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "'.";
break;
}
- int jumpto=_code_ptr[ip+3];
- ERR_BREAK(jumpto<0 || jumpto>_code_size);
- ip=jumpto;
+ int jumpto = _code_ptr[ip + 3];
+ ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
continue;
}
- GET_VARIANT_PTR(iterator,4);
+ GET_VARIANT_PTR(iterator, 4);
-
- *iterator=container->iter_get(*counter,valid);
+ *iterator = container->iter_get(*counter, valid);
if (!valid) {
- err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"'.";
+ err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "'.";
break;
}
-
- ip+=5; //skip regular iterate which is always next
+ ip += 5; //skip regular iterate which is always next
continue;
}
case OPCODE_ITERATE: {
CHECK_SPACE(4);
- GET_VARIANT_PTR(counter,1);
- GET_VARIANT_PTR(container,2);
+ GET_VARIANT_PTR(counter, 1);
+ GET_VARIANT_PTR(container, 2);
bool valid;
- if (!container->iter_next(*counter,valid)) {
+ if (!container->iter_next(*counter, valid)) {
if (!valid) {
- err_text="Unable to iterate on object of type "+Variant::get_type_name(container->get_type())+"' (type changed since first iteration?).";
+ err_text = "Unable to iterate on object of type " + Variant::get_type_name(container->get_type()) + "' (type changed since first iteration?).";
break;
}
- int jumpto=_code_ptr[ip+3];
- ERR_BREAK(jumpto<0 || jumpto>_code_size);
- ip=jumpto;
+ int jumpto = _code_ptr[ip + 3];
+ ERR_BREAK(jumpto < 0 || jumpto > _code_size);
+ ip = jumpto;
continue;
}
- GET_VARIANT_PTR(iterator,4);
+ GET_VARIANT_PTR(iterator, 4);
- *iterator=container->iter_get(*counter,valid);
+ *iterator = container->iter_get(*counter, valid);
if (!valid) {
- err_text="Unable to obtain iterator object of type "+Variant::get_type_name(container->get_type())+"' (but was obtained on first iteration?).";
+ err_text = "Unable to obtain iterator object of type " + Variant::get_type_name(container->get_type()) + "' (but was obtained on first iteration?).";
break;
}
- ip+=5; //loop again
+ ip += 5; //loop again
continue;
}
case OPCODE_ASSERT: {
CHECK_SPACE(2);
- GET_VARIANT_PTR(test,1);
+ GET_VARIANT_PTR(test, 1);
#ifdef DEBUG_ENABLED
bool valid;
bool result = test->booleanize(valid);
-
if (!valid) {
- err_text="cannot evaluate conditional expression of type: "+Variant::get_type_name(test->get_type());
+ err_text = "cannot evaluate conditional expression of type: " + Variant::get_type_name(test->get_type());
break;
}
-
if (!result) {
- err_text="Assertion failed.";
+ err_text = "Assertion failed.";
break;
}
#endif
- ip+=2;
+ ip += 2;
continue;
}
case OPCODE_BREAKPOINT: {
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton()) {
- GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement",true);
+ GDScriptLanguage::get_singleton()->debug_break("Breakpoint Statement", true);
}
#endif
- ip+=1;
+ ip += 1;
continue;
}
case OPCODE_LINE: {
CHECK_SPACE(2);
- line=_code_ptr[ip+1];
- ip+=2;
+ line = _code_ptr[ip + 1];
+ ip += 2;
if (ScriptDebugger::get_singleton()) {
// line
- bool do_break=false;
+ bool do_break = false;
- if (ScriptDebugger::get_singleton()->get_lines_left()>0) {
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0) {
- if (ScriptDebugger::get_singleton()->get_depth()<=0)
- ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 );
- if (ScriptDebugger::get_singleton()->get_lines_left()<=0)
- do_break=true;
+ if (ScriptDebugger::get_singleton()->get_depth() <= 0)
+ ScriptDebugger::get_singleton()->set_lines_left(ScriptDebugger::get_singleton()->get_lines_left() - 1);
+ if (ScriptDebugger::get_singleton()->get_lines_left() <= 0)
+ do_break = true;
}
- if (ScriptDebugger::get_singleton()->is_breakpoint(line,source))
- do_break=true;
+ if (ScriptDebugger::get_singleton()->is_breakpoint(line, source))
+ do_break = true;
if (do_break) {
- GDScriptLanguage::get_singleton()->debug_break("Breakpoint",true);
+ GDScriptLanguage::get_singleton()->debug_break("Breakpoint", true);
}
ScriptDebugger::get_singleton()->line_poll();
-
}
continue;
}
case OPCODE_END: {
- exit_ok=true;
+ exit_ok = true;
break;
-
}
default: {
- err_text="Illegal opcode "+itos(_code_ptr[ip])+" at address "+itos(ip);
+ err_text = "Illegal opcode " + itos(_code_ptr[ip]) + " at address " + itos(ip);
break;
}
-
}
if (exit_ok)
@@ -1206,73 +1162,69 @@ Variant GDFunction::call(GDInstance *p_instance, const Variant **p_args, int p_a
// function, file, line, error, explanation
String err_file;
if (p_instance)
- err_file=p_instance->script->path;
+ err_file = p_instance->script->path;
else if (_class)
- err_file=_class->path;
- if (err_file=="")
- err_file="<built-in>";
+ err_file = _class->path;
+ if (err_file == "")
+ err_file = "<built-in>";
String err_func = name;
- if (p_instance && 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 (p_instance && 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)) {
+ 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);
+ _err_print_error(err_func.utf8().get_data(), err_file.utf8().get_data(), err_line, err_text.utf8().get_data(), ERR_HANDLER_SCRIPT);
}
-
break;
}
#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;
-
+ 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;
}
#endif
if (ScriptDebugger::get_singleton())
GDScriptLanguage::get_singleton()->exit_function();
-
if (_stack_size) {
//free stack
- for(int i=0;i<_stack_size;i++)
+ for (int i = 0; i < _stack_size; i++)
stack[i].~Variant();
}
return retvalue;
-
}
-const int* GDFunction::get_code() const {
+const int *GDFunction::get_code() const {
return _code_ptr;
}
-int GDFunction::get_code_size() const{
+int GDFunction::get_code_size() const {
return _code_size;
}
Variant GDFunction::get_constant(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,constants.size(),"<errconst>");
+ ERR_FAIL_INDEX_V(p_idx, constants.size(), "<errconst>");
return constants[p_idx];
}
StringName GDFunction::get_global_name(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,global_names.size(),"<errgname>");
+ ERR_FAIL_INDEX_V(p_idx, global_names.size(), "<errgname>");
return global_names[p_idx];
}
@@ -1280,13 +1232,12 @@ int GDFunction::get_default_argument_count() const {
return default_arguments.size();
}
-int GDFunction::get_default_argument_addr(int p_arg) const{
+int GDFunction::get_default_argument_addr(int p_arg) const {
- ERR_FAIL_INDEX_V(p_arg,default_arguments.size(),-1);
+ ERR_FAIL_INDEX_V(p_arg, default_arguments.size(), -1);
return default_arguments[p_arg];
}
-
StringName GDFunction::get_name() const {
return name;
@@ -1311,66 +1262,60 @@ struct _GDFKCS {
bool operator<(const _GDFKCS &p_r) const {
- return order<p_r.order;
+ return order < p_r.order;
}
};
-void GDFunction::debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const {
+void GDFunction::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()) {
- 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)
+ const StackDebug &sd = E->get();
+ if (sd.line > p_line)
break;
if (sd.added) {
if (!sdmap.has(sd.identifier)) {
_GDFKC d;
- d.order=oc++;
+ d.order = oc++;
d.pos.push_back(sd.pos);
- sdmap[sd.identifier]=d;
+ sdmap[sd.identifier] = d;
} else {
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())
sdmap.erase(sd.identifier);
}
-
}
-
List<_GDFKCS> stackpositions;
- for(Map<StringName,_GDFKC>::Element *E=sdmap.front();E;E=E->next() ) {
+ for (Map<StringName, _GDFKC>::Element *E = sdmap.front(); E; E = E->next()) {
_GDFKCS spp;
- spp.id=E->key();
- spp.order=E->get().order;
- spp.pos=E->get().pos.back()->get();
+ spp.id = E->key();
+ spp.order = E->get().order;
+ spp.pos = E->get().pos.back()->get();
stackpositions.push_back(spp);
}
stackpositions.sort();
- for(List<_GDFKCS>::Element *E=stackpositions.front();E;E=E->next()) {
+ 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;
+ Pair<StringName, int> p;
+ p.first = E->get().id;
+ p.second = E->get().pos;
r_stackvars->push_back(p);
}
-
-
}
#if 0
@@ -1389,14 +1334,15 @@ void GDFunction::clear() {
}
#endif
-GDFunction::GDFunction() : function_list(this) {
+GDFunction::GDFunction()
+ : function_list(this) {
- _stack_size=0;
- _call_size=0;
- rpc_mode=ScriptInstance::RPC_MODE_DISABLED;
- name="<anonymous>";
+ _stack_size = 0;
+ _call_size = 0;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
+ name = "<anonymous>";
#ifdef DEBUG_ENABLED
- _func_cname=NULL;
+ _func_cname = NULL;
if (GDScriptLanguage::get_singleton()->lock) {
GDScriptLanguage::get_singleton()->lock->lock();
@@ -1407,20 +1353,20 @@ GDFunction::GDFunction() : function_list(this) {
GDScriptLanguage::get_singleton()->lock->unlock();
}
- 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;
+ 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
}
-GDFunction::~GDFunction() {
+GDFunction::~GDFunction() {
#ifdef DEBUG_ENABLED
if (GDScriptLanguage::get_singleton()->lock) {
GDScriptLanguage::get_singleton()->lock->lock();
@@ -1435,8 +1381,7 @@ GDFunction::~GDFunction() {
/////////////////////
-
-Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
+Variant GDFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
#ifdef DEBUG_ENABLED
if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) {
@@ -1451,51 +1396,50 @@ Variant GDFunctionState::_signal_callback(const Variant** p_args, int p_argcount
#endif
Variant arg;
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- ERR_FAIL_COND_V(!function,Variant());
+ ERR_FAIL_COND_V(!function, Variant());
- if (p_argcount==0) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
+ if (p_argcount == 0) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
return Variant();
- } else if (p_argcount==1) {
+ } else if (p_argcount == 1) {
//noooneee
- } else if (p_argcount==2) {
- arg=*p_args[0];
+ } else if (p_argcount == 2) {
+ arg = *p_args[0];
} else {
Array extra_args;
- for(int i=0;i<p_argcount-1;i++) {
+ for (int i = 0; i < p_argcount - 1; i++) {
extra_args.push_back(*p_args[i]);
}
- arg=extra_args;
+ arg = extra_args;
}
- Ref<GDFunctionState> self = *p_args[p_argcount-1];
+ Ref<GDFunctionState> self = *p_args[p_argcount - 1];
if (self.is_null()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=p_argcount-1;
- r_error.expected=Variant::OBJECT;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = p_argcount - 1;
+ r_error.expected = Variant::OBJECT;
return Variant();
}
- state.result=arg;
- Variant ret = function->call(NULL,NULL,0,r_error,&state);
- function=NULL; //cleaned up;
- state.result=Variant();
+ state.result = arg;
+ Variant ret = function->call(NULL, NULL, 0, r_error, &state);
+ function = NULL; //cleaned up;
+ state.result = Variant();
return ret;
}
-
bool GDFunctionState::is_valid() const {
- return function!=NULL;
+ return function != NULL;
}
-Variant GDFunctionState::resume(const Variant& p_arg) {
+Variant GDFunctionState::resume(const Variant &p_arg) {
- ERR_FAIL_COND_V(!function,Variant());
+ ERR_FAIL_COND_V(!function, Variant());
#ifdef DEBUG_ENABLED
if (state.instance_id && !ObjectDB::get_instance(state.instance_id)) {
ERR_EXPLAIN("Resumed after yield, but class instance is gone");
@@ -1508,36 +1452,33 @@ Variant GDFunctionState::resume(const Variant& p_arg) {
}
#endif
- state.result=p_arg;
+ state.result = p_arg;
Variant::CallError err;
- Variant ret = function->call(NULL,NULL,0,err,&state);
- function=NULL; //cleaned up;
- state.result=Variant();
+ Variant ret = function->call(NULL, NULL, 0, err, &state);
+ function = NULL; //cleaned up;
+ state.result = Variant();
return ret;
}
-
void GDFunctionState::_bind_methods() {
- ClassDB::bind_method(D_METHOD("resume:Variant","arg"),&GDFunctionState::resume,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("is_valid"),&GDFunctionState::is_valid);
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"_signal_callback",&GDFunctionState::_signal_callback,MethodInfo("_signal_callback"));
-
+ ClassDB::bind_method(D_METHOD("resume:Variant", "arg"), &GDFunctionState::resume, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("is_valid"), &GDFunctionState::is_valid);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &GDFunctionState::_signal_callback, MethodInfo("_signal_callback"));
}
GDFunctionState::GDFunctionState() {
- function=NULL;
+ function = NULL;
}
GDFunctionState::~GDFunctionState() {
- if (function!=NULL) {
+ if (function != NULL) {
//never called, deinitialize stack
- for(int i=0;i<state.stack_size;i++) {
- Variant *v=(Variant*)&state.stack[sizeof(Variant)*i];
+ for (int i = 0; i < state.stack_size; i++) {
+ Variant *v = (Variant *)&state.stack[sizeof(Variant) * i];
v->~Variant();
}
}
}
-
diff --git a/modules/gdscript/gd_function.h b/modules/gdscript/gd_function.h
index aff6341601..321b3b6cfa 100644
--- a/modules/gdscript/gd_function.h
+++ b/modules/gdscript/gd_function.h
@@ -29,21 +29,19 @@
#ifndef GD_FUNCTION_H
#define GD_FUNCTION_H
-#include "self_list.h"
#include "os/thread.h"
#include "pair.h"
-#include "variant.h"
-#include "string_db.h"
#include "reference.h"
#include "script_language.h"
+#include "self_list.h"
+#include "string_db.h"
+#include "variant.h"
class GDInstance;
class GDScript;
-
class GDFunction {
public:
-
enum Opcode {
OPCODE_OPERATOR,
OPCODE_EXTENDS_TEST,
@@ -81,18 +79,18 @@ public:
};
enum Address {
- ADDR_BITS=24,
- ADDR_MASK=((1<<ADDR_BITS)-1),
- ADDR_TYPE_MASK=~ADDR_MASK,
- ADDR_TYPE_SELF=0,
- ADDR_TYPE_CLASS=1,
- ADDR_TYPE_MEMBER=2,
- ADDR_TYPE_CLASS_CONSTANT=3,
- ADDR_TYPE_LOCAL_CONSTANT=4,
- ADDR_TYPE_STACK=5,
- ADDR_TYPE_STACK_VARIABLE=6,
- ADDR_TYPE_GLOBAL=7,
- ADDR_TYPE_NIL=8
+ ADDR_BITS = 24,
+ ADDR_MASK = ((1 << ADDR_BITS) - 1),
+ ADDR_TYPE_MASK = ~ADDR_MASK,
+ ADDR_TYPE_SELF = 0,
+ ADDR_TYPE_CLASS = 1,
+ ADDR_TYPE_MEMBER = 2,
+ ADDR_TYPE_CLASS_CONSTANT = 3,
+ ADDR_TYPE_LOCAL_CONSTANT = 4,
+ ADDR_TYPE_STACK = 5,
+ ADDR_TYPE_STACK_VARIABLE = 6,
+ ADDR_TYPE_GLOBAL = 7,
+ ADDR_TYPE_NIL = 8
};
enum RPCMode {
@@ -103,16 +101,16 @@ public:
RPC_SYNC_SLAVE
};
- struct StackDebug {
+ struct StackDebug {
- int line;
- int pos;
- bool added;
- StringName identifier;
- };
+ int line;
+ int pos;
+ bool added;
+ StringName identifier;
+ };
private:
-friend class GDCompiler;
+ friend class GDCompiler;
StringName source;
@@ -146,15 +144,15 @@ friend class GDCompiler;
List<StackDebug> stack_debug;
- _FORCE_INLINE_ Variant *_get_variant(int p_address,GDInstance *p_instance,GDScript *p_script,Variant &self,Variant *p_stack,String& r_error) const;
- _FORCE_INLINE_ String _get_call_error(const Variant::CallError& p_err, const String& p_where,const Variant**argptrs) const;
+ _FORCE_INLINE_ Variant *_get_variant(int p_address, GDInstance *p_instance, GDScript *p_script, Variant &self, Variant *p_stack, String &r_error) const;
+ _FORCE_INLINE_ String _get_call_error(const Variant::CallError &p_err, const String &p_where, const Variant **argptrs) const;
-friend class GDScriptLanguage;
+ friend class GDScriptLanguage;
SelfList<GDFunction> function_list;
#ifdef DEBUG_ENABLED
CharString func_cname;
- const char*_func_cname;
+ const char *_func_cname;
struct Profile {
StringName signature;
@@ -172,9 +170,6 @@ friend class GDScriptLanguage;
#endif
public:
-
-
-
struct CallState {
ObjectID instance_id; //by debug only
@@ -190,12 +185,11 @@ public:
int line;
int defarg;
Variant result;
-
};
_FORCE_INLINE_ bool is_static() const { return _static; }
- const int* get_code() const; //used for debug
+ const int *get_code() const; //used for debug
int get_code_size() const;
Variant get_constant(int p_idx) const;
StringName get_global_name(int p_idx) const;
@@ -206,48 +200,46 @@ public:
GDScript *get_script() const { return _script; }
StringName get_source() const { return source; }
- void debug_get_stack_member_state(int p_line,List<Pair<StringName,int> > *r_stackvars) const;
+ void debug_get_stack_member_state(int p_line, List<Pair<StringName, int> > *r_stackvars) const;
- _FORCE_INLINE_ bool is_empty() const { return _code_size==0; }
+ _FORCE_INLINE_ bool is_empty() const { return _code_size == 0; }
int get_argument_count() const { return _argument_count; }
StringName get_argument_name(int p_idx) const {
#ifdef TOOLS_ENABLED
- ERR_FAIL_INDEX_V(p_idx,arg_names.size(),StringName());
+ ERR_FAIL_INDEX_V(p_idx, arg_names.size(), StringName());
return arg_names[p_idx];
#endif
return StringName();
-
}
Variant get_default_argument(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,default_arguments.size(),Variant());
+ ERR_FAIL_INDEX_V(p_idx, default_arguments.size(), Variant());
return default_arguments[p_idx];
}
- Variant call(GDInstance *p_instance,const Variant **p_args, int p_argcount,Variant::CallError& r_err,CallState *p_state=NULL);
+ Variant call(GDInstance *p_instance, const Variant **p_args, int p_argcount, Variant::CallError &r_err, CallState *p_state = NULL);
_FORCE_INLINE_ ScriptInstance::RPCMode get_rpc_mode() const { return rpc_mode; }
GDFunction();
~GDFunction();
};
-
class GDFunctionState : public Reference {
- GDCLASS(GDFunctionState,Reference);
-friend class GDFunction;
+ GDCLASS(GDFunctionState, Reference);
+ friend class GDFunction;
GDFunction *function;
GDFunction::CallState state;
- Variant _signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+ Variant _signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+
protected:
static void _bind_methods();
-public:
+public:
bool is_valid() const;
- Variant resume(const Variant& p_arg=Variant());
+ Variant resume(const Variant &p_arg = Variant());
GDFunctionState();
~GDFunctionState();
};
-
#endif // GD_FUNCTION_H
diff --git a/modules/gdscript/gd_functions.cpp b/modules/gdscript/gd_functions.cpp
index d0fc241734..fa92f0a194 100644
--- a/modules/gdscript/gd_functions.cpp
+++ b/modules/gdscript/gd_functions.cpp
@@ -27,21 +27,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "gd_functions.h"
-#include "math_funcs.h"
#include "class_db.h"
-#include "reference.h"
-#include "gd_script.h"
#include "func_ref.h"
+#include "gd_script.h"
+#include "io/json.h"
+#include "io/marshalls.h"
+#include "math_funcs.h"
#include "os/os.h"
+#include "reference.h"
#include "variant_parser.h"
-#include "io/marshalls.h"
-#include "io/json.h"
const char *GDFunctions::get_func_name(Function p_func) {
- ERR_FAIL_INDEX_V(p_func,FUNC_MAX,"");
+ ERR_FAIL_INDEX_V(p_func, FUNC_MAX, "");
- static const char *_names[FUNC_MAX]={
+ static const char *_names[FUNC_MAX] = {
"sin",
"cos",
"tan",
@@ -115,35 +115,34 @@ const char *GDFunctions::get_func_name(Function p_func) {
};
return _names[p_func];
-
}
-void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Variant &r_ret,Variant::CallError &r_error) {
+void GDFunctions::call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error) {
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
#ifdef DEBUG_ENABLED
-#define VALIDATE_ARG_COUNT(m_count) \
- if (p_arg_count<m_count) {\
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;\
- r_error.argument=m_count;\
- r_ret=Variant();\
- return;\
- }\
- if (p_arg_count>m_count) {\
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;\
- r_error.argument=m_count;\
- r_ret=Variant();\
- return;\
+#define VALIDATE_ARG_COUNT(m_count) \
+ if (p_arg_count < m_count) { \
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; \
+ r_error.argument = m_count; \
+ r_ret = Variant(); \
+ return; \
+ } \
+ if (p_arg_count > m_count) { \
+ r_error.error = Variant::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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\
- r_error.argument=m_arg;\
- r_error.expected=Variant::REAL;\
- r_ret=Variant();\
- return;\
+#define VALIDATE_ARG_NUM(m_arg) \
+ if (!p_args[m_arg]->is_num()) { \
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \
+ r_error.argument = m_arg; \
+ r_error.expected = Variant::REAL; \
+ r_ret = Variant(); \
+ return; \
}
#else
@@ -154,245 +153,245 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
//using a switch, so the compiler generates a jumptable
- switch(p_func) {
+ switch (p_func) {
case MATH_SIN: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- r_ret=Math::sin((double)*p_args[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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ r_ret = Math::fposmod((double)*p_args[0], (double)*p_args[1]);
} break;
case MATH_FLOOR: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- r_ret=Math::floor((double)*p_args[0]);
- } break;
+ 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]);
+ 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]);
+ r_ret = Math::round((double)*p_args[0]);
} break;
case MATH_ABS: {
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()==Variant::INT) {
+ 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::REAL) {
+ r_ret = ABS(i);
+ } else if (p_args[0]->get_type() == Variant::REAL) {
double r = *p_args[0];
- r_ret=Math::abs(r);
+ r_ret = Math::abs(r);
} else {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::REAL;
- r_ret=Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::REAL;
+ r_ret = Variant();
}
} break;
case MATH_SIGN: {
- VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()==Variant::INT) {
+ 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::REAL) {
+ int64_t i = *p_args[0];
+ r_ret = i < 0 ? -1 : (i > 0 ? +1 : 0);
+ } else if (p_args[0]->get_type() == Variant::REAL) {
- real_t r = *p_args[0];
- r_ret= r < 0.0 ? -1.0 : ( r > 0.0 ? +1.0 : 0.0);
- } else {
+ real_t r = *p_args[0];
+ r_ret = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
+ } else {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::REAL;
- r_ret=Variant();
- }
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::REAL;
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ 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]);
+ r_ret = Math::is_inf((double)*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]);
+ r_ret = Math::ease((double)*p_args[0], (double)*p_args[1]);
} break;
case MATH_DECIMALS: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- r_ret=Math::step_decimals((double)*p_args[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]);
+ r_ret = Math::stepify((double)*p_args[0], (double)*p_args[1]);
} break;
case MATH_LERP: {
VALIDATE_ARG_COUNT(3);
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
VALIDATE_ARG_NUM(2);
- r_ret=Math::lerp((double)*p_args[0],(double)*p_args[1],(double)*p_args[2]);
+ r_ret = Math::lerp((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]);
+ r_ret = Math::dectime((double)*p_args[0], (double)*p_args[1], (double)*p_args[2]);
} break;
case MATH_RANDOMIZE: {
Math::randomize();
- r_ret=Variant();
+ r_ret = Variant();
} break;
case MATH_RAND: {
- r_ret=Math::rand();
+ r_ret = Math::rand();
} break;
case MATH_RANDF: {
- r_ret=Math::randf();
+ 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]);
+ 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];
+ uint64_t seed = *p_args[0];
Math::seed(seed);
- r_ret=Variant();
+ r_ret = Variant();
} break;
case MATH_RANDSEED: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- uint64_t seed=*p_args[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;
+ r_ret = reta;
} break;
case MATH_DEG2RAD: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- r_ret=Math::deg2rad((double)*p_args[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]);
+ 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]);
+ 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]);
+ r_ret = Math::db2linear((double)*p_args[0]);
} break;
case LOGIC_MAX: {
VALIDATE_ARG_COUNT(2);
- if (p_args[0]->get_type()==Variant::INT && p_args[1]->get_type()==Variant::INT) {
+ 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);
+ r_ret = MAX(a, b);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -400,17 +399,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
real_t a = *p_args[0];
real_t b = *p_args[1];
- r_ret=MAX(a,b);
+ 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) {
+ 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);
+ r_ret = MIN(a, b);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -418,17 +417,17 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
real_t a = *p_args[0];
real_t b = *p_args[1];
- r_ret=MIN(a,b);
+ 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) {
+ 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);
+ r_ret = CLAMP(a, b, c);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -438,7 +437,7 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
real_t b = *p_args[1];
real_t c = *p_args[2];
- r_ret=CLAMP(a,b,c);
+ r_ret = CLAMP(a, b, c);
}
} break;
case LOGIC_NEAREST_PO2: {
@@ -449,87 +448,80 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
} break;
case OBJ_WEAKREF: {
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::OBJECT) {
+ if (p_args[0]->get_type() != Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
- r_ret=Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ r_ret = Variant();
return;
-
}
if (p_args[0]->is_ref()) {
REF r = *p_args[0];
if (!r.is_valid()) {
- r_ret=Variant();
+ r_ret = Variant();
return;
}
- Ref<WeakRef> wref = memnew( WeakRef );
+ Ref<WeakRef> wref = memnew(WeakRef);
wref->set_ref(r);
- r_ret=wref;
+ r_ret = wref;
} else {
Object *obj = *p_args[0];
if (!obj) {
- r_ret=Variant();
+ r_ret = Variant();
return;
}
- Ref<WeakRef> wref = memnew( WeakRef );
+ Ref<WeakRef> wref = memnew(WeakRef);
wref->set_obj(obj);
- r_ret=wref;
+ r_ret = wref;
}
-
-
-
} break;
case FUNC_FUNCREF: {
VALIDATE_ARG_COUNT(2);
- if (p_args[0]->get_type()!=Variant::OBJECT) {
+ if (p_args[0]->get_type() != Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
- r_ret=Variant();
+ r_error.error = Variant::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) {
+ if (p_args[1]->get_type() != Variant::STRING && p_args[1]->get_type() != Variant::NODE_PATH) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
- r_ret=Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
+ r_ret = Variant();
return;
-
}
- Ref<FuncRef> fr = memnew( FuncRef);
+ Ref<FuncRef> fr = memnew(FuncRef);
fr->set_instance(*p_args[0]);
fr->set_function(*p_args[1]);
- r_ret=fr;
+ 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) {
+ 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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::INT;
+ r_ret = RTR("Invalid type argument to convert(), use TYPE_* constants.");
+ r_error.error = Variant::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);
+ r_ret = Variant::construct(Variant::Type(type), p_args, 1, r_error);
}
} break;
case TYPE_OF: {
@@ -547,125 +539,122 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
case TEXT_CHAR: {
VALIDATE_ARG_COUNT(1);
VALIDATE_ARG_NUM(0);
- CharType result[2] = {*p_args[0], 0};
- r_ret=String(result);
+ CharType result[2] = { *p_args[0], 0 };
+ r_ret = String(result);
} break;
case TEXT_STR: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
String os = p_args[i]->operator String();
- if (i==0)
- str=os;
+ if (i == 0)
+ str = os;
else
- str+=os;
+ str += os;
}
- r_ret=str;
+ r_ret = str;
} break;
case TEXT_PRINT: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
- str+=p_args[i]->operator String();
+ str += p_args[i]->operator String();
}
//str+="\n";
print_line(str);
- r_ret=Variant();
-
+ r_ret = Variant();
} break;
case TEXT_PRINT_TABBED: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
if (i)
- str+="\t";
- str+=p_args[i]->operator String();
+ str += "\t";
+ str += p_args[i]->operator String();
}
//str+="\n";
print_line(str);
- r_ret=Variant();
-
+ r_ret = Variant();
} break;
case TEXT_PRINT_SPACED: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
if (i)
- str+=" ";
- str+=p_args[i]->operator String();
+ str += " ";
+ str += p_args[i]->operator String();
}
//str+="\n";
print_line(str);
- r_ret=Variant();
-
+ r_ret = Variant();
} break;
case TEXT_PRINTERR: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
- str+=p_args[i]->operator String();
+ str += p_args[i]->operator String();
}
//str+="\n";
- OS::get_singleton()->printerr("%s\n",str.utf8().get_data());
- r_ret=Variant();
+ OS::get_singleton()->printerr("%s\n", str.utf8().get_data());
+ r_ret = Variant();
} break;
case TEXT_PRINTRAW: {
String str;
- for(int i=0;i<p_arg_count;i++) {
+ for (int i = 0; i < p_arg_count; i++) {
- str+=p_args[i]->operator String();
+ str += p_args[i]->operator String();
}
//str+="\n";
- OS::get_singleton()->print("%s",str.utf8().get_data());
- r_ret=Variant();
+ OS::get_singleton()->print("%s", str.utf8().get_data());
+ 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;
+ 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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
+ r_ret = Variant();
return;
}
VariantParser::StreamString ss;
- ss.s=*p_args[0];
+ ss.s = *p_args[0];
String errs;
int line;
- Error err = VariantParser::parse(&ss,r_ret,errs,line);
+ Error err = VariantParser::parse(&ss, r_ret, errs, line);
- if (err!=OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- r_ret="Parse error at line "+itos(line)+": "+errs;
+ if (err != OK) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
+ r_ret = "Parse error at line " + itos(line) + ": " + errs;
return;
}
@@ -675,106 +664,104 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
PoolByteArray barr;
int len;
- Error err = encode_variant(*p_args[0],NULL,len);
+ Error err = encode_variant(*p_args[0], NULL, len);
if (err) {
- r_error.error=Variant::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).";
+ r_error.error = Variant::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);
{
PoolByteArray::Write w = barr.write();
- encode_variant(*p_args[0],w.ptr(),len);
-
+ encode_variant(*p_args[0], w.ptr(), len);
}
- r_ret=barr;
+ r_ret = barr;
} break;
case BYTES_TO_VAR: {
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::POOL_BYTE_ARRAY) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::POOL_BYTE_ARRAY;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::POOL_BYTE_ARRAY) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::POOL_BYTE_ARRAY;
+ r_ret = Variant();
return;
}
- PoolByteArray varr=*p_args[0];
+ PoolByteArray varr = *p_args[0];
Variant ret;
{
- PoolByteArray::Read r=varr.read();
- Error err = decode_variant(ret,r.ptr(),varr.size(),NULL);
- if (err!=OK) {
- r_ret=RTR("Not enough bytes for decoding bytes, or invalid format.");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::POOL_BYTE_ARRAY;
+ PoolByteArray::Read r = varr.read();
+ Error err = decode_variant(ret, r.ptr(), varr.size(), NULL);
+ if (err != OK) {
+ r_ret = RTR("Not enough bytes for decoding bytes, or invalid format.");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::POOL_BYTE_ARRAY;
return;
}
-
}
- r_ret=ret;
+ r_ret = ret;
} break;
case GEN_RANGE: {
- switch(p_arg_count) {
+ switch (p_arg_count) {
case 0: {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
- r_ret=Variant();
+ r_error.error = Variant::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];
+ int count = *p_args[0];
Array arr;
- if (count<=0) {
- r_ret=arr;
+ if (count <= 0) {
+ r_ret = arr;
return;
}
Error err = arr.resize(count);
- if (err!=OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret=Variant();
+ if (err != OK) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_ret = Variant();
return;
}
- for(int i=0;i<count;i++) {
- arr[i]=i;
+ for (int i = 0; i < count; i++) {
+ arr[i] = i;
}
- r_ret=arr;
+ r_ret = arr;
} break;
case 2: {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
- int from=*p_args[0];
- int to=*p_args[1];
+ int from = *p_args[0];
+ int to = *p_args[1];
Array arr;
- if (from>=to) {
- r_ret=arr;
+ if (from >= to) {
+ r_ret = arr;
return;
}
- Error err = arr.resize(to-from);
- if (err!=OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret=Variant();
+ Error err = arr.resize(to - from);
+ if (err != OK) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_ret = Variant();
return;
}
- for(int i=from;i<to;i++)
- arr[i-from]=i;
- r_ret=arr;
+ for (int i = from; i < to; i++)
+ arr[i - from] = i;
+ r_ret = arr;
} break;
case 3: {
@@ -782,65 +769,64 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
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) {
+ 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=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_ret = RTR("step argument is zero!");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return;
}
Array arr;
- if (from>=to && incr>0) {
- r_ret=arr;
+ if (from >= to && incr > 0) {
+ r_ret = arr;
return;
}
- if (from<=to && incr<0) {
- r_ret=arr;
+ if (from <= to && incr < 0) {
+ r_ret = arr;
return;
}
//calculate how many
- int count=0;
- if (incr>0) {
+ int count = 0;
+ if (incr > 0) {
- count=((to-from-1)/incr)+1;
+ count = ((to - from - 1) / incr) + 1;
} else {
- count=((from-to-1)/-incr)+1;
+ count = ((from - to - 1) / -incr) + 1;
}
-
Error err = arr.resize(count);
- if (err!=OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_ret=Variant();
+ if (err != OK) {
+ r_error.error = Variant::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;
+ 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;
+ int idx = 0;
+ for (int i = from; i > to; i += incr) {
+ arr[idx++] = i;
}
}
- r_ret=arr;
+ r_ret = arr;
} break;
default: {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=3;
- r_ret=Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = 3;
+ r_ret = Variant();
} break;
}
@@ -848,13 +834,13 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
} break;
case RESOURCE_LOAD: {
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::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]);
+ r_ret = ResourceLoader::load(*p_args[0]);
}
} break;
@@ -862,91 +848,85 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_ret=Variant();
+ if (p_args[0]->get_type() == Variant::NIL) {
+ r_ret = Variant();
+ } else if (p_args[0]->get_type() != Variant::OBJECT) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_ret = Variant();
} else {
Object *obj = *p_args[0];
if (!obj) {
- r_ret=Variant();
+ r_ret = Variant();
- } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language()!=GDScriptLanguage::get_singleton()) {
+ } else if (!obj->get_script_instance() || obj->get_script_instance()->get_language() != GDScriptLanguage::get_singleton()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::DICTIONARY;
- r_ret=RTR("Not a script with an instance");
+ r_error.error = Variant::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 {
- GDInstance *ins = static_cast<GDInstance*>(obj->get_script_instance());
+ GDInstance *ins = static_cast<GDInstance *>(obj->get_script_instance());
Ref<GDScript> base = ins->get_script();
if (base.is_null()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::DICTIONARY;
- r_ret=RTR("Not based on a script");
+ r_error.error = Variant::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) {
+ while (p->_owner) {
sname.push_back(p->name);
- p=p->_owner;
+ p = p->_owner;
}
sname.invert();
-
if (!p->path.is_resource_file()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::DICTIONARY;
- r_ret=Variant();
+ r_error.error = Variant::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");
+ r_ret = RTR("Not based on a resource file");
return;
}
- NodePath cp(sname,Vector<StringName>(),false);
+ NodePath cp(sname, Vector<StringName>(), false);
Dictionary d;
- d["@subpath"]=cp;
- d["@path"]=p->path;
-
+ d["@subpath"] = cp;
+ d["@path"] = p->path;
p = base.ptr();
- while(p) {
+ while (p) {
- for(Set<StringName>::Element *E=p->members.front();E;E=E->next()) {
+ for (Set<StringName>::Element *E = p->members.front(); E; E = E->next()) {
Variant value;
- if (ins->get(E->get(),value)) {
+ if (ins->get(E->get(), value)) {
String k = E->get();
if (!d.has(k)) {
- d[k]=value;
+ d[k] = value;
}
}
}
- p=p->_base;
+ p = p->_base;
}
- r_ret=d;
-
+ r_ret = d;
}
}
@@ -955,12 +935,12 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::DICTIONARY) {
+ if (p_args[0]->get_type() != Variant::DICTIONARY) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::DICTIONARY;
- r_ret=Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::DICTIONARY;
+ r_ret = Variant();
return;
}
@@ -969,10 +949,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
if (!d.has("@path")) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
- r_ret=RTR("Invalid instance dictionary format (missing @path)");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
+ r_ret = RTR("Invalid instance dictionary format (missing @path)");
return;
}
@@ -980,10 +960,10 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
Ref<Script> scr = ResourceLoader::load(d["@path"]);
if (!scr.is_valid()) {
- r_error.error=Variant::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)");
+ r_error.error = Variant::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;
}
@@ -991,40 +971,40 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
if (!gdscr.is_valid()) {
- r_error.error=Variant::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)");
+ r_error.error = Variant::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"];
+ sub = d["@subpath"];
}
- for(int i=0;i<sub.get_name_count();i++) {
+ for (int i = 0; i < sub.get_name_count(); i++) {
- gdscr = gdscr->subclasses[ sub.get_name(i)];
+ gdscr = gdscr->subclasses[sub.get_name(i)];
if (!gdscr.is_valid()) {
- r_error.error=Variant::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)");
+ r_error.error = Variant::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(NULL,0,r_error);
+ r_ret = gdscr->_new(NULL, 0, r_error);
- GDInstance *ins = static_cast<GDInstance*>(static_cast<Object*>(r_ret)->get_script_instance());
+ GDInstance *ins = static_cast<GDInstance *>(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())) {
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = gd_ref->member_indices.front(); E; E = E->next()) {
+ if (d.has(E->key())) {
ins->members[E->get().index] = d[E->key()];
}
}
@@ -1034,23 +1014,23 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::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);
+ Error err = JSON::parse(*p_args[0], r_ret, errs, errl);
- if (err!=OK) {
- r_ret=itos(errl)+":"+errs;
+ if (err != OK) {
+ r_ret = itos(errl) + ":" + errs;
} else {
- r_ret="";
+ r_ret = "";
}
} break;
@@ -1058,21 +1038,21 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::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);
+ Error err = JSON::parse(*p_args[0], r_ret, errs, errl);
- if (err!=OK) {
- r_ret=Variant();
+ if (err != OK) {
+ r_ret = Variant();
}
} break;
@@ -1084,22 +1064,22 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
case HASH: {
VALIDATE_ARG_COUNT(1);
- r_ret=p_args[0]->hash();
+ r_ret = p_args[0]->hash();
} break;
case COLOR8: {
- if (p_arg_count<3) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=3;
- r_ret=Variant();
+ if (p_arg_count < 3) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 3;
+ r_ret = Variant();
return;
}
- if (p_arg_count>4) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=4;
- r_ret=Variant();
+ if (p_arg_count > 4) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = 4;
+ r_ret = Variant();
return;
}
@@ -1108,78 +1088,76 @@ void GDFunctions::call(Function p_func,const Variant **p_args,int p_arg_count,Va
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);
+ 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) {
+ if (p_arg_count == 4) {
VALIDATE_ARG_NUM(3);
- color.a=(float)*p_args[3]/255.0f;
+ color.a = (float)*p_args[3] / 255.0f;
}
- r_ret=color;
+ r_ret = color;
} break;
case COLORN: {
- if (p_arg_count<1) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
- r_ret=Variant();
+ if (p_arg_count < 1) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
+ r_ret = Variant();
return;
}
- if (p_arg_count>2) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=2;
- r_ret=Variant();
+ if (p_arg_count > 2) {
+ r_error.error = Variant::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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_ret=Variant();
+
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::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) {
+ if (p_arg_count == 2) {
VALIDATE_ARG_NUM(1);
- color.a=*p_args[1];
+ color.a = *p_args[1];
}
- r_ret=color;
+ r_ret = color;
}
} break;
case PRINT_STACK: {
- ScriptLanguage* script = GDScriptLanguage::get_singleton();
- for (int i=0; i < script->debug_get_stack_level_count(); i++) {
+ 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)+"'");
+ 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 INSTANCE_FROM_ID: {
VALIDATE_ARG_COUNT(1);
- if (p_args[0]->get_type()!=Variant::INT && p_args[0]->get_type()!=Variant::REAL) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::INT;
- r_ret=Variant();
+ if (p_args[0]->get_type() != Variant::INT && p_args[0]->get_type() != Variant::REAL) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::INT;
+ r_ret = Variant();
break;
}
- uint32_t id=*p_args[0];
- r_ret=ObjectDB::get_instance(id);
+ uint32_t id = *p_args[0];
+ r_ret = ObjectDB::get_instance(id);
} break;
case FUNC_MAX: {
ERR_FAIL();
} break;
-
}
-
}
bool GDFunctions::is_deterministic(Function p_func) {
@@ -1187,7 +1165,7 @@ bool GDFunctions::is_deterministic(Function p_func) {
//man i couldn't have chosen a worse function name,
//way too controversial..
- switch(p_func) {
+ switch (p_func) {
case MATH_SIN:
case MATH_COS:
@@ -1231,16 +1209,13 @@ bool GDFunctions::is_deterministic(Function p_func) {
case TEXT_CHAR:
case TEXT_STR:
case COLOR8:
-// enable for debug only, otherwise not desirable - case GEN_RANGE:
+ // enable for debug only, otherwise not desirable - case GEN_RANGE:
return true;
default:
return false;
-
}
return false;
-
-
}
MethodInfo GDFunctions::get_info(Function p_func) {
@@ -1248,401 +1223,401 @@ MethodInfo GDFunctions::get_info(Function p_func) {
#ifdef TOOLS_ENABLED
//using a switch, so the compiler generates a jumptable
- switch(p_func) {
+ switch (p_func) {
case MATH_SIN: {
- MethodInfo mi("sin",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("sin", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_COS: {
- MethodInfo mi("cos",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("cos", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_TAN: {
- MethodInfo mi("tan",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("tan", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_SINH: {
- MethodInfo mi("sinh",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("sinh", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_COSH: {
- MethodInfo mi("cosh",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("cosh", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_TANH: {
- MethodInfo mi("tanh",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("tanh", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ASIN: {
- MethodInfo mi("asin",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("asin", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ACOS: {
- MethodInfo mi("acos",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("acos", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ATAN: {
- MethodInfo mi("atan",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("atan", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ATAN2: {
- MethodInfo mi("atan2",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("atan2", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_SQRT: {
- MethodInfo mi("sqrt",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("sqrt", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_FMOD: {
- MethodInfo mi("fmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("fmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_FPOSMOD: {
- MethodInfo mi("fposmod",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("fposmod", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_FLOOR: {
- MethodInfo mi("floor",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("floor", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
- } break;
+ } break;
case MATH_CEIL: {
- MethodInfo mi("ceil",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("ceil", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ROUND: {
- MethodInfo mi("round",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("round", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ABS: {
- MethodInfo mi("abs",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("abs", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_SIGN: {
- MethodInfo mi("sign",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("sign", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_POW: {
- MethodInfo mi("pow",PropertyInfo(Variant::REAL,"x"),PropertyInfo(Variant::REAL,"y"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("pow", PropertyInfo(Variant::REAL, "x"), PropertyInfo(Variant::REAL, "y"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_LOG: {
- MethodInfo mi("log",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("log", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_EXP: {
- MethodInfo mi("exp",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("exp", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ISNAN: {
- MethodInfo mi("is_nan",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("is_nan", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_ISINF: {
- MethodInfo mi("is_inf",PropertyInfo(Variant::REAL,"s"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("is_inf", PropertyInfo(Variant::REAL, "s"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_EASE: {
- MethodInfo mi("ease",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"curve"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("ease", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "curve"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_DECIMALS: {
- MethodInfo mi("decimals",PropertyInfo(Variant::REAL,"step"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("decimals", PropertyInfo(Variant::REAL, "step"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_STEPIFY: {
- MethodInfo mi("stepify",PropertyInfo(Variant::REAL,"s"),PropertyInfo(Variant::REAL,"step"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("stepify", PropertyInfo(Variant::REAL, "s"), PropertyInfo(Variant::REAL, "step"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_LERP: {
- MethodInfo mi("lerp",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to"), PropertyInfo(Variant::REAL,"weight"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("lerp", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"), PropertyInfo(Variant::REAL, "weight"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_DECTIME: {
- MethodInfo mi("dectime",PropertyInfo(Variant::REAL,"value"),PropertyInfo(Variant::REAL,"amount"),PropertyInfo(Variant::REAL,"step"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("dectime", PropertyInfo(Variant::REAL, "value"), PropertyInfo(Variant::REAL, "amount"), PropertyInfo(Variant::REAL, "step"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_RANDOMIZE: {
MethodInfo mi("randomize");
- mi.return_val.type=Variant::NIL;
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case MATH_RAND: {
MethodInfo mi("randi");
- mi.return_val.type=Variant::INT;
+ mi.return_val.type = Variant::INT;
return mi;
} break;
case MATH_RANDF: {
MethodInfo mi("randf");
- mi.return_val.type=Variant::REAL;
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_RANDOM: {
- MethodInfo mi("rand_range",PropertyInfo(Variant::REAL,"from"),PropertyInfo(Variant::REAL,"to"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("rand_range", PropertyInfo(Variant::REAL, "from"), PropertyInfo(Variant::REAL, "to"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_SEED: {
- MethodInfo mi("seed",PropertyInfo(Variant::INT,"seed"));
- mi.return_val.type=Variant::NIL;
+ 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;
+ 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::REAL,"deg"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("deg2rad", PropertyInfo(Variant::REAL, "deg"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_RAD2DEG: {
- MethodInfo mi("rad2deg",PropertyInfo(Variant::REAL,"rad"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("rad2deg", PropertyInfo(Variant::REAL, "rad"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_LINEAR2DB: {
- MethodInfo mi("linear2db",PropertyInfo(Variant::REAL,"nrg"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("linear2db", PropertyInfo(Variant::REAL, "nrg"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case MATH_DB2LINEAR: {
- MethodInfo mi("db2linear",PropertyInfo(Variant::REAL,"db"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("db2linear", PropertyInfo(Variant::REAL, "db"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case LOGIC_MAX: {
- MethodInfo mi("max",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("max", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case LOGIC_MIN: {
- MethodInfo mi("min",PropertyInfo(Variant::REAL,"a"),PropertyInfo(Variant::REAL,"b"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("min", PropertyInfo(Variant::REAL, "a"), PropertyInfo(Variant::REAL, "b"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case LOGIC_CLAMP: {
- MethodInfo mi("clamp",PropertyInfo(Variant::REAL,"val"),PropertyInfo(Variant::REAL,"min"),PropertyInfo(Variant::REAL,"max"));
- mi.return_val.type=Variant::REAL;
+ MethodInfo mi("clamp", PropertyInfo(Variant::REAL, "val"), PropertyInfo(Variant::REAL, "min"), PropertyInfo(Variant::REAL, "max"));
+ mi.return_val.type = Variant::REAL;
return mi;
} break;
case LOGIC_NEAREST_PO2: {
- MethodInfo mi("nearest_po2",PropertyInfo(Variant::INT,"val"));
- mi.return_val.type=Variant::INT;
+ MethodInfo mi("nearest_po2", PropertyInfo(Variant::INT, "val"));
+ 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.name="WeakRef";
+ MethodInfo mi("weakref", PropertyInfo(Variant::OBJECT, "obj"));
+ mi.return_val.type = Variant::OBJECT;
+ mi.return_val.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.name="FuncRef";
+ MethodInfo mi("funcref", PropertyInfo(Variant::OBJECT, "instance"), PropertyInfo(Variant::STRING, "funcname"));
+ mi.return_val.type = Variant::OBJECT;
+ mi.return_val.name = "FuncRef";
return mi;
} break;
case TYPE_CONVERT: {
- MethodInfo mi("convert",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::INT,"type"));
- mi.return_val.type=Variant::OBJECT;
+ MethodInfo mi("convert", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::INT, "type"));
+ mi.return_val.type = Variant::OBJECT;
return mi;
} break;
case TYPE_OF: {
- MethodInfo mi("typeof",PropertyInfo(Variant::NIL,"what"));
- mi.return_val.type=Variant::INT;
+ MethodInfo mi("typeof", PropertyInfo(Variant::NIL, "what"));
+ 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;
+ 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,"ascii"));
- mi.return_val.type=Variant::STRING;
+ MethodInfo mi("char", PropertyInfo(Variant::INT, "ascii"));
+ mi.return_val.type = Variant::STRING;
return mi;
} break;
case TEXT_STR: {
- MethodInfo mi("str",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::STRING;
+ MethodInfo mi("str", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::STRING;
return mi;
} break;
case TEXT_PRINT: {
- MethodInfo mi("print",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("print", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case TEXT_PRINT_TABBED: {
- MethodInfo mi("printt",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("printt", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case TEXT_PRINT_SPACED: {
- MethodInfo mi("prints",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("prints", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case TEXT_PRINTERR: {
- MethodInfo mi("printerr",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("printerr", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case TEXT_PRINTRAW: {
- MethodInfo mi("printraw",PropertyInfo(Variant::NIL,"what"),PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("printraw", PropertyInfo(Variant::NIL, "what"), PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case VAR_TO_STR: {
- MethodInfo mi("var2str",PropertyInfo(Variant::NIL,"var"));
- mi.return_val.type=Variant::STRING;
+ MethodInfo mi("var2str", PropertyInfo(Variant::NIL, "var"));
+ mi.return_val.type = Variant::STRING;
return mi;
} break;
case STR_TO_VAR: {
- MethodInfo mi("str2var:Variant",PropertyInfo(Variant::STRING,"string"));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("str2var:Variant", PropertyInfo(Variant::STRING, "string"));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case VAR_TO_BYTES: {
- MethodInfo mi("var2bytes",PropertyInfo(Variant::NIL,"var"));
- mi.return_val.type=Variant::POOL_BYTE_ARRAY;
+ MethodInfo mi("var2bytes", PropertyInfo(Variant::NIL, "var"));
+ mi.return_val.type = Variant::POOL_BYTE_ARRAY;
return mi;
} break;
case BYTES_TO_VAR: {
- MethodInfo mi("bytes2var:Variant",PropertyInfo(Variant::POOL_BYTE_ARRAY,"bytes"));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("bytes2var:Variant", PropertyInfo(Variant::POOL_BYTE_ARRAY, "bytes"));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case GEN_RANGE: {
- MethodInfo mi("range",PropertyInfo(Variant::NIL,"..."));
- mi.return_val.type=Variant::ARRAY;
+ MethodInfo mi("range", PropertyInfo(Variant::NIL, "..."));
+ mi.return_val.type = Variant::ARRAY;
return mi;
} break;
case RESOURCE_LOAD: {
- MethodInfo mi("load",PropertyInfo(Variant::STRING,"path"));
- mi.return_val.type=Variant::OBJECT;
- mi.return_val.name="Resource";
+ MethodInfo mi("load", PropertyInfo(Variant::STRING, "path"));
+ mi.return_val.type = Variant::OBJECT;
+ mi.return_val.name = "Resource";
return mi;
} break;
case INST2DICT: {
- MethodInfo mi("inst2dict",PropertyInfo(Variant::OBJECT,"inst"));
- mi.return_val.type=Variant::DICTIONARY;
+ 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;
+ MethodInfo mi("dict2inst", PropertyInfo(Variant::DICTIONARY, "dict"));
+ mi.return_val.type = Variant::OBJECT;
return mi;
} break;
case VALIDATE_JSON: {
- MethodInfo mi("validate_json:Variant",PropertyInfo(Variant::STRING,"json"));
- mi.return_val.type=Variant::STRING;
+ MethodInfo mi("validate_json:Variant", PropertyInfo(Variant::STRING, "json"));
+ mi.return_val.type = Variant::STRING;
return mi;
} break;
case PARSE_JSON: {
- MethodInfo mi("parse_json:Variant",PropertyInfo(Variant::STRING,"json"));
- mi.return_val.type=Variant::NIL;
+ MethodInfo mi("parse_json:Variant", PropertyInfo(Variant::STRING, "json"));
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case TO_JSON: {
- MethodInfo mi("to_json",PropertyInfo(Variant::NIL,"var:Variant"));
- mi.return_val.type=Variant::STRING;
+ MethodInfo mi("to_json", PropertyInfo(Variant::NIL, "var:Variant"));
+ mi.return_val.type = Variant::STRING;
return mi;
} break;
case HASH: {
- MethodInfo mi("hash",PropertyInfo(Variant::NIL,"var:Variant"));
- mi.return_val.type=Variant::INT;
+ MethodInfo mi("hash", PropertyInfo(Variant::NIL, "var: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.return_val.type=Variant::COLOR;
+ MethodInfo mi("Color8", PropertyInfo(Variant::INT, "r8"), PropertyInfo(Variant::INT, "g8"), PropertyInfo(Variant::INT, "b8"), PropertyInfo(Variant::INT, "a8"));
+ mi.return_val.type = Variant::COLOR;
return mi;
} break;
case COLORN: {
- MethodInfo mi("ColorN",PropertyInfo(Variant::STRING,"name"),PropertyInfo(Variant::REAL,"alpha"));
- mi.return_val.type=Variant::COLOR;
+ MethodInfo mi("ColorN", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::REAL, "alpha"));
+ mi.return_val.type = Variant::COLOR;
return mi;
} break;
case PRINT_STACK: {
MethodInfo mi("print_stack");
- mi.return_val.type=Variant::NIL;
+ mi.return_val.type = Variant::NIL;
return mi;
} break;
case INSTANCE_FROM_ID: {
- MethodInfo mi("instance_from_id",PropertyInfo(Variant::INT,"instance_id"));
- mi.return_val.type=Variant::OBJECT;
+ MethodInfo mi("instance_from_id", PropertyInfo(Variant::INT, "instance_id"));
+ mi.return_val.type = Variant::OBJECT;
return mi;
} break;
@@ -1650,7 +1625,6 @@ MethodInfo GDFunctions::get_info(Function p_func) {
ERR_FAIL_V(MethodInfo());
} break;
-
}
#endif
diff --git a/modules/gdscript/gd_functions.h b/modules/gdscript/gd_functions.h
index 6e30b4dbb5..cde1a9210d 100644
--- a/modules/gdscript/gd_functions.h
+++ b/modules/gdscript/gd_functions.h
@@ -33,7 +33,6 @@
class GDFunctions {
public:
-
enum Function {
MATH_SIN,
MATH_COS,
@@ -110,10 +109,9 @@ public:
};
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,Variant::CallError &r_error);
+ static void call(Function p_func, const Variant **p_args, int p_arg_count, Variant &r_ret, Variant::CallError &r_error);
static bool is_deterministic(Function p_func);
static MethodInfo get_info(Function p_func);
-
};
#endif // GD_FUNCTIONS_H
diff --git a/modules/gdscript/gd_parser.cpp b/modules/gdscript/gd_parser.cpp
index 5147ccd63f..86b97e27a9 100644
--- a/modules/gdscript/gd_parser.cpp
+++ b/modules/gdscript/gd_parser.cpp
@@ -27,74 +27,72 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "gd_parser.h"
-#include "print_string.h"
+#include "gd_script.h"
#include "io/resource_loader.h"
#include "os/file_access.h"
+#include "print_string.h"
#include "script_language.h"
-#include "gd_script.h"
-template<class T>
-T* GDParser::alloc_node() {
+template <class T>
+T *GDParser::alloc_node() {
- T *t = memnew( T);
+ T *t = memnew(T);
- t->next=list;
- list=t;
+ t->next = list;
+ list = t;
if (!head)
- head=t;
+ head = t;
- t->line=tokenizer->get_token_line();
- t->column=tokenizer->get_token_column();
+ t->line = tokenizer->get_token_line();
+ t->column = tokenizer->get_token_column();
return t;
-
}
bool GDParser::_end_statement() {
- if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) {
+ if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) {
tokenizer->advance();
return true; //handle next
- } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) {
return true; //will be handled properly
}
return false;
}
-bool GDParser::_enter_indent_block(BlockNode* p_block) {
-
+bool GDParser::_enter_indent_block(BlockNode *p_block) {
- if (tokenizer->get_token()!=GDTokenizer::TK_COLON) {
+ if (tokenizer->get_token() != GDTokenizer::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);
+ _set_error("':' expected at end of line.", error_line, error_column);
return false;
}
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) {
// be more python-like
int current = tab_level.back()->get();
- tab_level.push_back(current+1);
+ tab_level.push_back(current + 1);
return true;
//_set_error("newline expected after ':'.");
//return false;
}
- while(true) {
+ while (true) {
- if (tokenizer->get_token()!=GDTokenizer::TK_NEWLINE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_NEWLINE) {
return false; //wtf
- } else if (tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) {
+ } else if (tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) {
int indent = tokenizer->get_token_line_indent();
int current = tab_level.back()->get();
- if (indent<=current) {
- print_line("current: "+itos(current)+" indent: "+itos(indent));
+ if (indent <= current) {
+ print_line("current: " + itos(current) + " indent: " + itos(indent));
print_line("less than current");
return false;
}
@@ -106,52 +104,51 @@ bool GDParser::_enter_indent_block(BlockNode* p_block) {
} else if (p_block) {
NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line=tokenizer->get_token_line();
+ nl->line = tokenizer->get_token_line();
p_block->statements.push_back(nl);
-
}
tokenizer->advance(); // go to next newline
}
}
-bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_static,bool p_can_codecomplete) {
+bool GDParser::_parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete) {
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
tokenizer->advance();
} else {
- parenthesis ++;
- int argidx=0;
+ parenthesis++;
+ int argidx = 0;
- while(true) {
+ while (true) {
- if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) {
_make_completable_call(argidx);
- completion_node=p_parent;
- } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING && tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) {
+ completion_node = p_parent;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING && tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) {
//completing a string argument..
- completion_cursor=tokenizer->get_token_constant();
+ completion_cursor = tokenizer->get_token_constant();
_make_completable_call(argidx);
- completion_node=p_parent;
+ completion_node = p_parent;
tokenizer->advance(1);
return false;
}
- Node*arg = _parse_expression(p_parent,p_static);
+ Node *arg = _parse_expression(p_parent, p_static);
if (!arg)
return false;
p_args.push_back(arg);
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
tokenizer->advance();
break;
- } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
- if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expression expected");
return false;
@@ -164,57 +161,52 @@ bool GDParser::_parse_arguments(Node* p_parent,Vector<Node*>& p_args,bool p_stat
_set_error("Expected ',' or ')'");
return false;
}
-
}
- parenthesis --;
+ parenthesis--;
}
return true;
-
}
-
void GDParser::_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;
+ 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();
-
}
+bool GDParser::_get_completable_identifier(CompletionType p_type, StringName &identifier) {
-bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& identifier) {
-
- identifier=StringName();
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) {
- identifier=tokenizer->get_token_identifier();
+ identifier = StringName();
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) {
+ identifier = tokenizer->get_token_identifier();
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::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;
+ if (tokenizer->get_token() == GDTokenizer::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();
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) {
- identifier=identifier.operator String() + tokenizer->get_token_identifier().operator String();
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) {
+ identifier = identifier.operator String() + tokenizer->get_token_identifier().operator String();
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) {
- completion_ident_is_call=true;
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) {
+ completion_ident_is_call = true;
}
return true;
}
@@ -222,132 +214,129 @@ bool GDParser::_get_completable_identifier(CompletionType p_type,StringName& ide
return false;
}
-
-GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_allow_assign,bool p_parsing_constant) {
+GDParser::Node *GDParser::_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=NULL;
+ Node *expr = NULL;
int op_line = tokenizer->get_token_line(); // when operators are created at the bottom, the line might have been changed (\n found)
- while(true) {
-
+ while (true) {
/*****************/
/* Parse Operand */
/*****************/
- if (parenthesis>0) {
+ if (parenthesis > 0) {
//remove empty space (only allowed if inside parenthesis
- while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
}
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) {
//subexpression ()
tokenizer->advance();
parenthesis++;
- Node* subexpr = _parse_expression(p_parent,p_static,p_allow_assign,p_parsing_constant);
+ Node *subexpr = _parse_expression(p_parent, p_static, p_allow_assign, p_parsing_constant);
parenthesis--;
if (!subexpr)
return NULL;
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in expression");
return NULL;
}
tokenizer->advance();
- expr=subexpr;
- } else if (tokenizer->get_token()==GDTokenizer::TK_DOLLAR) {
+ expr = subexpr;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_DOLLAR) {
tokenizer->advance();
String path;
- bool need_identifier=true;
- bool done=false;
+ bool need_identifier = true;
+ bool done = false;
- while(!done) {
+ while (!done) {
- switch(tokenizer->get_token()) {
+ switch (tokenizer->get_token()) {
case GDTokenizer::TK_CURSOR: {
- completion_cursor=StringName();
- 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;
+ completion_cursor = StringName();
+ 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 GDTokenizer::TK_CONSTANT: {
if (!need_identifier) {
- done=true;
+ done = true;
break;
}
- if (tokenizer->get_token_constant().get_type()!=Variant::STRING) {
+ if (tokenizer->get_token_constant().get_type() != Variant::STRING) {
_set_error("Expected string constant or identifier after '$' or '/'.");
return NULL;
}
- path+=String(tokenizer->get_token_constant());
+ path += String(tokenizer->get_token_constant());
tokenizer->advance();
- need_identifier=false;
+ need_identifier = false;
} break;
case GDTokenizer::TK_IDENTIFIER: {
if (!need_identifier) {
- done=true;
+ done = true;
break;
}
- path+=String(tokenizer->get_token_identifier());
+ path += String(tokenizer->get_token_identifier());
tokenizer->advance();
- need_identifier=false;
+ need_identifier = false;
} break;
case GDTokenizer::TK_OP_DIV: {
if (need_identifier) {
- done=true;
+ done = true;
break;
}
- path+="/";
+ path += "/";
tokenizer->advance();
- need_identifier=true;
+ need_identifier = true;
} break;
default: {
- done=true;
+ done = true;
break;
}
}
}
- if (path=="") {
+ if (path == "") {
_set_error("Path expected after $.");
return NULL;
-
}
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_CALL;
+ op->op = OperatorNode::OP_CALL;
op->arguments.push_back(alloc_node<SelfNode>());
IdentifierNode *funcname = alloc_node<IdentifierNode>();
- funcname->name="get_node";
+ funcname->name = "get_node";
op->arguments.push_back(funcname);
@@ -355,47 +344,45 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
nodepath->value = NodePath(StringName(path));
op->arguments.push_back(nodepath);
- expr=op;
+ expr = op;
- } else if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) {
tokenizer->advance();
continue; //no point in cursor in the middle of expression
- } else if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) {
//constant defined by tokenizer
ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value=tokenizer->get_token_constant();
+ constant->value = tokenizer->get_token_constant();
tokenizer->advance();
- expr=constant;
- } else if (tokenizer->get_token()==GDTokenizer::TK_CONST_PI) {
+ expr = constant;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_PI) {
//constant defined by tokenizer
ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value=Math_PI;
+ constant->value = Math_PI;
tokenizer->advance();
- expr=constant;
- }
- else if (tokenizer->get_token() == GDTokenizer::TK_CONST_INF) {
+ expr = constant;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_INF) {
//constant defined by tokenizer
ConstantNode *constant = alloc_node<ConstantNode>();
constant->value = Math_INF;
tokenizer->advance();
expr = constant;
- }
- else if (tokenizer->get_token() == GDTokenizer::TK_CONST_NAN) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CONST_NAN) {
//constant defined by tokenizer
ConstantNode *constant = alloc_node<ConstantNode>();
constant->value = Math_NAN;
tokenizer->advance();
expr = constant;
- } else if (tokenizer->get_token()==GDTokenizer::TK_PR_PRELOAD) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_PR_PRELOAD) {
//constant defined by tokenizer
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after 'preload'");
return NULL;
}
@@ -409,18 +396,18 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
Node *subexpr = _parse_and_reduce_expression(p_parent, p_static);
if (subexpr) {
if (subexpr->type == Node::TYPE_CONSTANT) {
- cn = static_cast<ConstantNode*>(subexpr);
+ cn = static_cast<ConstantNode *>(subexpr);
found_constant = true;
}
if (subexpr->type == Node::TYPE_IDENTIFIER) {
- IdentifierNode *in = static_cast<IdentifierNode*>(subexpr);
+ IdentifierNode *in = static_cast<IdentifierNode *>(subexpr);
Vector<ClassNode::Constant> ce = current_class->constant_expressions;
// Try to find the constant expression by the identifier
- for(int i=0; i < ce.size(); ++i){
- if(ce[i].identifier == in->name) {
- if(ce[i].expression->type == Node::TYPE_CONSTANT) {
- cn = static_cast<ConstantNode*>(ce[i].expression);
+ for (int i = 0; i < ce.size(); ++i) {
+ if (ce[i].identifier == in->name) {
+ if (ce[i].expression->type == Node::TYPE_CONSTANT) {
+ cn = static_cast<ConstantNode *>(ce[i].expression);
found_constant = true;
}
}
@@ -429,7 +416,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
if (found_constant && cn->value.get_type() == Variant::STRING) {
valid = true;
- path = (String) cn->value;
+ path = (String)cn->value;
}
}
@@ -438,17 +425,15 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
return NULL;
}
- if (!path.is_abs_path() && base_path!="")
- path=base_path+"/"+path;
- path = path.replace("///","//").simplify_path();
- if (path==self_path) {
+ if (!path.is_abs_path() && base_path != "")
+ path = base_path + "/" + path;
+ path = path.replace("///", "//").simplify_path();
+ if (path == self_path) {
_set_error("Can't preload itself (use 'get_script()').");
return NULL;
-
}
-
Ref<Resource> res;
if (!validating) {
@@ -459,33 +444,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
res = ResourceLoader::load(path);
}
if (!res.is_valid()) {
- _set_error("Can't preload resource at path: "+path);
+ _set_error("Can't preload resource at path: " + path);
return NULL;
}
} else {
if (!FileAccess::exists(path)) {
- _set_error("Can't preload resource at path: "+path);
+ _set_error("Can't preload resource at path: " + path);
return NULL;
}
}
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' after 'preload' path");
return NULL;
}
ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value=res;
+ constant->value = res;
tokenizer->advance();
- expr=constant;
- } else if (tokenizer->get_token()==GDTokenizer::TK_PR_YIELD) {
+ expr = constant;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_PR_YIELD) {
//constant defined by tokenizer
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after 'yield'");
return NULL;
}
@@ -493,65 +478,63 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
tokenizer->advance();
OperatorNode *yield = alloc_node<OperatorNode>();
- yield->op=OperatorNode::OP_YIELD;
+ yield->op = OperatorNode::OP_YIELD;
- while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
- expr=yield;
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ expr = yield;
tokenizer->advance();
} else {
- parenthesis ++;
+ parenthesis++;
- Node *object = _parse_and_reduce_expression(p_parent,p_static);
+ Node *object = _parse_and_reduce_expression(p_parent, p_static);
if (!object)
return NULL;
yield->arguments.push_back(object);
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
_set_error("Expected ',' after first argument of 'yield'");
return NULL;
}
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::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;
+ if (tokenizer->get_token() == GDTokenizer::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();
}
- Node *signal = _parse_and_reduce_expression(p_parent,p_static);
+ Node *signal = _parse_and_reduce_expression(p_parent, p_static);
if (!signal)
return NULL;
yield->arguments.push_back(signal);
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' after second argument of 'yield'");
return NULL;
}
- parenthesis --;
+ parenthesis--;
tokenizer->advance();
- expr=yield;
+ expr = yield;
}
-
- } else if (tokenizer->get_token()==GDTokenizer::TK_SELF) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_SELF) {
if (p_static) {
_set_error("'self'' not allowed in static function or constant expression");
@@ -560,51 +543,50 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
//constant defined by tokenizer
SelfNode *self = alloc_node<SelfNode>();
tokenizer->advance();
- expr=self;
- } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1)==GDTokenizer::TK_PERIOD) {
+ expr = self;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token(1) == GDTokenizer::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)) {
+ if (_get_completable_identifier(COMPLETION_BUILT_IN_TYPE_CONSTANT, identifier)) {
- completion_built_in_constant=bi_type;
+ completion_built_in_constant = bi_type;
}
- if (identifier==StringName()) {
+ if (identifier == StringName()) {
_set_error("Built-in type constant expected after '.'");
return NULL;
}
- if (!Variant::has_numeric_constant(bi_type,identifier)) {
+ if (!Variant::has_numeric_constant(bi_type, identifier)) {
- _set_error("Static constant '"+identifier.operator String()+"' not present in built-in type "+Variant::get_type_name(bi_type)+".");
+ _set_error("Static constant '" + identifier.operator String() + "' not present in built-in type " + Variant::get_type_name(bi_type) + ".");
return NULL;
}
ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value=Variant::get_numeric_constant_value(bi_type,identifier);
- expr=cn;
+ cn->value = Variant::get_numeric_constant_value(bi_type, identifier);
+ expr = cn;
-
- } else if (tokenizer->get_token(1)==GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC)) {
+ } else if (tokenizer->get_token(1) == GDTokenizer::TK_PARENTHESIS_OPEN && (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE || tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC)) {
//function or constructor
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_CALL;
+ op->op = OperatorNode::OP_CALL;
- if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) {
TypeNode *tn = alloc_node<TypeNode>();
- tn->vtype=tokenizer->get_token_type();
+ tn->vtype = tokenizer->get_token_type();
op->arguments.push_back(tn);
tokenizer->advance(2);
- } else if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) {
BuiltInFunctionNode *bn = alloc_node<BuiltInFunctionNode>();
- bn->function=tokenizer->get_token_built_in_func();
+ bn->function = tokenizer->get_token_built_in_func();
op->arguments.push_back(bn);
tokenizer->advance(2);
} else {
@@ -613,43 +595,40 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
op->arguments.push_back(self);
StringName identifier;
- if (_get_completable_identifier(COMPLETION_FUNCTION,identifier)) {
-
+ if (_get_completable_identifier(COMPLETION_FUNCTION, identifier)) {
}
- IdentifierNode* id = alloc_node<IdentifierNode>();
- id->name=identifier;
+ IdentifierNode *id = alloc_node<IdentifierNode>();
+ id->name = identifier;
op->arguments.push_back(id);
tokenizer->advance(1);
}
- if (tokenizer->get_token()==GDTokenizer::TK_CURSOR) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) {
_make_completable_call(0);
- completion_node=op;
-
+ completion_node = op;
}
- if (!_parse_arguments(op,op->arguments,p_static,true))
+ if (!_parse_arguments(op, op->arguments, p_static, true))
return NULL;
- expr=op;
+ expr = op;
- } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) {
//identifier (reference)
- const ClassNode* cln = current_class;
- bool bfn = false;
- StringName identifier;
- if (_get_completable_identifier(COMPLETION_IDENTIFIER,identifier)) {
-
+ const ClassNode *cln = current_class;
+ bool bfn = false;
+ StringName identifier;
+ if (_get_completable_identifier(COMPLETION_IDENTIFIER, identifier)) {
}
if (p_parsing_constant) {
- for( int i=0; i<cln->constant_expressions.size(); ++i ) {
+ for (int i = 0; i < cln->constant_expressions.size(); ++i) {
- if( cln->constant_expressions[i].identifier == identifier ) {
+ if (cln->constant_expressions[i].identifier == identifier) {
expr = cln->constant_expressions[i].expression;
- bfn = true;
+ bfn = true;
break;
}
}
@@ -657,37 +636,36 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
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] ];
- expr=constant;
+ constant->value = GDScriptLanguage::get_singleton()->get_global_array()[GDScriptLanguage::get_singleton()->get_global_map()[identifier]];
+ expr = constant;
bfn = true;
}
}
- if ( !bfn ) {
+ if (!bfn) {
IdentifierNode *id = alloc_node<IdentifierNode>();
id->name = identifier;
expr = id;
}
- } else if (tokenizer->get_token()==GDTokenizer::TK_OP_ADD || tokenizer->get_token()==GDTokenizer::TK_OP_SUB || tokenizer->get_token()==GDTokenizer::TK_OP_NOT || tokenizer->get_token()==GDTokenizer::TK_OP_BIT_INVERT) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_OP_ADD || tokenizer->get_token() == GDTokenizer::TK_OP_SUB || tokenizer->get_token() == GDTokenizer::TK_OP_NOT || tokenizer->get_token() == GDTokenizer::TK_OP_BIT_INVERT) {
//single prefix operators like !expr +expr -expr ++expr --expr
alloc_node<OperatorNode>();
Expression e;
- e.is_op=true;
+ e.is_op = true;
- switch(tokenizer->get_token()) {
- case GDTokenizer::TK_OP_ADD: e.op=OperatorNode::OP_POS; break;
- case GDTokenizer::TK_OP_SUB: e.op=OperatorNode::OP_NEG; break;
- case GDTokenizer::TK_OP_NOT: e.op=OperatorNode::OP_NOT; break;
- case GDTokenizer::TK_OP_BIT_INVERT: e.op=OperatorNode::OP_BIT_INVERT; break;
+ switch (tokenizer->get_token()) {
+ case GDTokenizer::TK_OP_ADD: e.op = OperatorNode::OP_POS; break;
+ case GDTokenizer::TK_OP_SUB: e.op = OperatorNode::OP_NEG; break;
+ case GDTokenizer::TK_OP_NOT: e.op = OperatorNode::OP_NOT; break;
+ case GDTokenizer::TK_OP_BIT_INVERT: e.op = OperatorNode::OP_BIT_INVERT; break;
default: {}
}
-
tokenizer->advance();
- if (e.op!=OperatorNode::OP_NOT && tokenizer->get_token()==GDTokenizer::TK_OP_NOT) {
+ if (e.op != OperatorNode::OP_NOT && tokenizer->get_token() == GDTokenizer::TK_OP_NOT) {
_set_error("Misplaced 'not'.");
return NULL;
}
@@ -702,33 +680,33 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
op->arguments.push_back(subexpr);
expr=op;*/
- } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) {
// array
tokenizer->advance();
ArrayNode *arr = alloc_node<ArrayNode>();
- bool expecting_comma=false;
+ bool expecting_comma = false;
- while(true) {
+ while (true) {
- if (tokenizer->get_token()==GDTokenizer::TK_EOF) {
+ if (tokenizer->get_token() == GDTokenizer::TK_EOF) {
_set_error("Unterminated array");
return NULL;
- } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_CLOSE) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_CLOSE) {
tokenizer->advance();
break;
- } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance(); //ignore newline
- } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
if (!expecting_comma) {
_set_error("expression or ']' expected");
return NULL;
}
- expecting_comma=false;
+ expecting_comma = false;
tokenizer->advance(); //ignore newline
} else {
//parse expression
@@ -736,16 +714,16 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
_set_error("',' or ']' expected");
return NULL;
}
- Node *n = _parse_expression(arr,p_static,p_allow_assign,p_parsing_constant);
+ Node *n = _parse_expression(arr, p_static, p_allow_assign, p_parsing_constant);
if (!n)
return NULL;
arr->elements.push_back(n);
- expecting_comma=true;
+ expecting_comma = true;
}
}
- expr=arr;
- } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_OPEN) {
+ expr = arr;
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_OPEN) {
// array
tokenizer->advance();
@@ -760,105 +738,105 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
};
- Node *key=NULL;
+ Node *key = NULL;
Set<Variant> keys;
- DictExpect expecting=DICT_EXPECT_KEY;
+ DictExpect expecting = DICT_EXPECT_KEY;
- while(true) {
+ while (true) {
- if (tokenizer->get_token()==GDTokenizer::TK_EOF) {
+ if (tokenizer->get_token() == GDTokenizer::TK_EOF) {
_set_error("Unterminated dictionary");
return NULL;
- } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_CLOSE) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) {
- if (expecting==DICT_EXPECT_COLON) {
+ if (expecting == DICT_EXPECT_COLON) {
_set_error("':' expected");
return NULL;
}
- if (expecting==DICT_EXPECT_VALUE) {
+ if (expecting == DICT_EXPECT_VALUE) {
_set_error("value expected");
return NULL;
}
tokenizer->advance();
break;
- } else if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance(); //ignore newline
- } else if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
- if (expecting==DICT_EXPECT_KEY) {
+ if (expecting == DICT_EXPECT_KEY) {
_set_error("key or '}' expected");
return NULL;
}
- if (expecting==DICT_EXPECT_VALUE) {
+ if (expecting == DICT_EXPECT_VALUE) {
_set_error("value expected");
return NULL;
}
- if (expecting==DICT_EXPECT_COLON) {
+ if (expecting == DICT_EXPECT_COLON) {
_set_error("':' expected");
return NULL;
}
- expecting=DICT_EXPECT_KEY;
+ expecting = DICT_EXPECT_KEY;
tokenizer->advance(); //ignore newline
- } else if (tokenizer->get_token()==GDTokenizer::TK_COLON) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_COLON) {
- if (expecting==DICT_EXPECT_KEY) {
+ if (expecting == DICT_EXPECT_KEY) {
_set_error("key or '}' expected");
return NULL;
}
- if (expecting==DICT_EXPECT_VALUE) {
+ if (expecting == DICT_EXPECT_VALUE) {
_set_error("value expected");
return NULL;
}
- if (expecting==DICT_EXPECT_COMMA) {
+ if (expecting == DICT_EXPECT_COMMA) {
_set_error("',' or '}' expected");
return NULL;
}
- expecting=DICT_EXPECT_VALUE;
+ expecting = DICT_EXPECT_VALUE;
tokenizer->advance(); //ignore newline
} else {
- if (expecting==DICT_EXPECT_COMMA) {
+ if (expecting == DICT_EXPECT_COMMA) {
_set_error("',' or '}' expected");
return NULL;
}
- if (expecting==DICT_EXPECT_COLON) {
+ if (expecting == DICT_EXPECT_COLON) {
_set_error("':' expected");
return NULL;
}
- if (expecting==DICT_EXPECT_KEY) {
+ if (expecting == DICT_EXPECT_KEY) {
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)==GDTokenizer::TK_OP_ASSIGN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) == GDTokenizer::TK_OP_ASSIGN) {
//lua style identifier, easier to write
ConstantNode *cn = alloc_node<ConstantNode>();
cn->value = tokenizer->get_token_identifier();
key = cn;
tokenizer->advance(2);
- expecting=DICT_EXPECT_VALUE;
+ expecting = DICT_EXPECT_VALUE;
} else {
//python/js style more flexible
- key = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant);
+ key = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant);
if (!key)
return NULL;
- expecting=DICT_EXPECT_COLON;
+ expecting = DICT_EXPECT_COLON;
}
}
- if (expecting==DICT_EXPECT_VALUE) {
- Node *value = _parse_expression(dict,p_static,p_allow_assign,p_parsing_constant);
+ if (expecting == DICT_EXPECT_VALUE) {
+ Node *value = _parse_expression(dict, p_static, p_allow_assign, p_parsing_constant);
if (!value)
return NULL;
- expecting=DICT_EXPECT_COMMA;
+ expecting = DICT_EXPECT_COMMA;
if (key->type == GDParser::Node::TYPE_CONSTANT) {
- Variant const& keyName = static_cast<const GDParser::ConstantNode*>(key)->value;
+ Variant const &keyName = static_cast<const GDParser::ConstantNode *>(key)->value;
if (keys.has(keyName)) {
_set_error("Duplicate key found in Dictionary literal");
@@ -868,43 +846,40 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
}
DictionaryNode::Pair pair;
- pair.key=key;
- pair.value=value;
+ pair.key = key;
+ pair.value = value;
dict->elements.push_back(pair);
- key=NULL;
-
+ key = NULL;
}
-
}
}
- expr=dict;
+ expr = dict;
- } else if (tokenizer->get_token()==GDTokenizer::TK_PERIOD && (tokenizer->get_token(1)==GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1)==GDTokenizer::TK_CURSOR) && tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && (tokenizer->get_token(1) == GDTokenizer::TK_IDENTIFIER || tokenizer->get_token(1) == GDTokenizer::TK_CURSOR) && tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) {
// parent call
tokenizer->advance(); //goto identifier
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_PARENT_CALL;
-
+ op->op = OperatorNode::OP_PARENT_CALL;
/*SelfNode *self = alloc_node<SelfNode>();
op->arguments.push_back(self);
forbidden for now */
StringName identifier;
- if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION,identifier)) {
+ if (_get_completable_identifier(COMPLETION_PARENT_FUNCTION, identifier)) {
//indexing stuff
}
IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name=identifier;
+ id->name = identifier;
op->arguments.push_back(id);
tokenizer->advance(1);
- if (!_parse_arguments(op,op->arguments,p_static))
+ if (!_parse_arguments(op, op->arguments, p_static))
return NULL;
- expr=op;
+ expr = op;
} else {
@@ -912,113 +887,106 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
//print_line("found bug?");
- _set_error("Error parsing expression, misplaced: "+String(tokenizer->get_token_name(tokenizer->get_token())));
- return NULL; //nothing
+ _set_error("Error parsing expression, misplaced: " + String(tokenizer->get_token_name(tokenizer->get_token())));
+ return NULL; //nothing
}
if (!expr) {
ERR_EXPLAIN("GDParser bug, couldn't figure out what expression is..");
- ERR_FAIL_COND_V(!expr,NULL);
+ ERR_FAIL_COND_V(!expr, NULL);
}
-
/******************/
/* Parse Indexing */
/******************/
-
while (true) {
//expressions can be indexed any number of times
- if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) {
//indexing using "."
- if (tokenizer->get_token(1)!=GDTokenizer::TK_CURSOR && tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1)!=GDTokenizer::TK_BUILT_IN_FUNC ) {
+ if (tokenizer->get_token(1) != GDTokenizer::TK_CURSOR && tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER && tokenizer->get_token(1) != GDTokenizer::TK_BUILT_IN_FUNC) {
_set_error("Expected identifier as member");
return NULL;
- } else if (tokenizer->get_token(2)==GDTokenizer::TK_PARENTHESIS_OPEN) {
+ } else if (tokenizer->get_token(2) == GDTokenizer::TK_PARENTHESIS_OPEN) {
//call!!
- OperatorNode * op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_CALL;
+ OperatorNode *op = alloc_node<OperatorNode>();
+ op->op = OperatorNode::OP_CALL;
tokenizer->advance();
- IdentifierNode * id = alloc_node<IdentifierNode>();
- if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_FUNC ) {
+ IdentifierNode *id = alloc_node<IdentifierNode>();
+ if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_FUNC) {
//small hack so built in funcs don't obfuscate methods
- id->name=GDFunctions::get_func_name(tokenizer->get_token_built_in_func());
+ id->name = GDFunctions::get_func_name(tokenizer->get_token_built_in_func());
tokenizer->advance();
} else {
StringName identifier;
- if (_get_completable_identifier(COMPLETION_METHOD,identifier)) {
- completion_node=op;
+ if (_get_completable_identifier(COMPLETION_METHOD, identifier)) {
+ completion_node = op;
//indexing stuff
}
- id->name=identifier;
+ 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()==GDTokenizer::TK_CURSOR) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CURSOR) {
_make_completable_call(0);
- completion_node=op;
-
+ completion_node = op;
}
- if (!_parse_arguments(op,op->arguments,p_static,true))
+ if (!_parse_arguments(op, op->arguments, p_static, true))
return NULL;
- expr=op;
+ expr = op;
} else {
//simple indexing!
-
- OperatorNode * op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_INDEX_NAMED;
+ OperatorNode *op = alloc_node<OperatorNode>();
+ op->op = OperatorNode::OP_INDEX_NAMED;
tokenizer->advance();
-
StringName identifier;
- if (_get_completable_identifier(COMPLETION_INDEX,identifier)) {
+ if (_get_completable_identifier(COMPLETION_INDEX, identifier)) {
- if (identifier==StringName()) {
- identifier="@temp"; //so it parses allright
+ if (identifier == StringName()) {
+ identifier = "@temp"; //so it parses allright
}
- completion_node=op;
+ completion_node = op;
//indexing stuff
}
- IdentifierNode * id = alloc_node<IdentifierNode>();
- id->name=identifier;
+ IdentifierNode *id = alloc_node<IdentifierNode>();
+ id->name = identifier;
op->arguments.push_back(expr);
op->arguments.push_back(id);
- expr=op;
-
-
+ expr = op;
}
- } else if (tokenizer->get_token()==GDTokenizer::TK_BRACKET_OPEN) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_OPEN) {
//indexing using "[]"
- OperatorNode * op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_INDEX;
+ 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);
+ Node *subexpr = _parse_expression(op, p_static, p_allow_assign, p_parsing_constant);
if (!subexpr) {
return NULL;
}
- if (tokenizer->get_token()!=GDTokenizer::TK_BRACKET_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_BRACKET_CLOSE) {
_set_error("Expected ']'");
return NULL;
}
@@ -1026,7 +994,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
op->arguments.push_back(expr);
op->arguments.push_back(subexpr);
tokenizer->advance(1);
- expr=op;
+ expr = op;
} else
break;
@@ -1036,88 +1004,91 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
/* Parse Operator */
/******************/
- if (parenthesis>0) {
+ if (parenthesis > 0) {
//remove empty space (only allowed if inside parenthesis
- while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
}
Expression e;
- e.is_op=false;
- e.node=expr;
+ e.is_op = false;
+ e.node = expr;
expression.push_back(e);
// determine which operator is next
OperatorNode::Operator op;
- bool valid=true;
+ bool valid = true;
//assign, if allowed is only alowed on the first operator
-#define _VALIDATE_ASSIGN if (!p_allow_assign) { _set_error("Unexpected assign."); return NULL; } p_allow_assign=false;
- switch(tokenizer->get_token()) { //see operator
-
- case GDTokenizer::TK_OP_IN: op=OperatorNode::OP_IN; break;
- case GDTokenizer::TK_OP_EQUAL: op=OperatorNode::OP_EQUAL ; break;
- case GDTokenizer::TK_OP_NOT_EQUAL: op=OperatorNode::OP_NOT_EQUAL ; break;
- case GDTokenizer::TK_OP_LESS: op=OperatorNode::OP_LESS ; break;
- case GDTokenizer::TK_OP_LESS_EQUAL: op=OperatorNode::OP_LESS_EQUAL ; break;
- case GDTokenizer::TK_OP_GREATER: op=OperatorNode::OP_GREATER ; break;
- case GDTokenizer::TK_OP_GREATER_EQUAL: op=OperatorNode::OP_GREATER_EQUAL ; break;
- case GDTokenizer::TK_OP_AND: op=OperatorNode::OP_AND ; break;
- case GDTokenizer::TK_OP_OR: op=OperatorNode::OP_OR ; break;
- case GDTokenizer::TK_OP_ADD: op=OperatorNode::OP_ADD ; break;
- case GDTokenizer::TK_OP_SUB: op=OperatorNode::OP_SUB ; break;
- case GDTokenizer::TK_OP_MUL: op=OperatorNode::OP_MUL ; break;
- case GDTokenizer::TK_OP_DIV: op=OperatorNode::OP_DIV ; break;
- case GDTokenizer::TK_OP_MOD: op=OperatorNode::OP_MOD ; break;
+#define _VALIDATE_ASSIGN \
+ if (!p_allow_assign) { \
+ _set_error("Unexpected assign."); \
+ return NULL; \
+ } \
+ p_allow_assign = false;
+ switch (tokenizer->get_token()) { //see operator
+
+ case GDTokenizer::TK_OP_IN: op = OperatorNode::OP_IN; break;
+ case GDTokenizer::TK_OP_EQUAL: op = OperatorNode::OP_EQUAL; break;
+ case GDTokenizer::TK_OP_NOT_EQUAL: op = OperatorNode::OP_NOT_EQUAL; break;
+ case GDTokenizer::TK_OP_LESS: op = OperatorNode::OP_LESS; break;
+ case GDTokenizer::TK_OP_LESS_EQUAL: op = OperatorNode::OP_LESS_EQUAL; break;
+ case GDTokenizer::TK_OP_GREATER: op = OperatorNode::OP_GREATER; break;
+ case GDTokenizer::TK_OP_GREATER_EQUAL: op = OperatorNode::OP_GREATER_EQUAL; break;
+ case GDTokenizer::TK_OP_AND: op = OperatorNode::OP_AND; break;
+ case GDTokenizer::TK_OP_OR: op = OperatorNode::OP_OR; break;
+ case GDTokenizer::TK_OP_ADD: op = OperatorNode::OP_ADD; break;
+ case GDTokenizer::TK_OP_SUB: op = OperatorNode::OP_SUB; break;
+ case GDTokenizer::TK_OP_MUL: op = OperatorNode::OP_MUL; break;
+ case GDTokenizer::TK_OP_DIV: op = OperatorNode::OP_DIV; break;
+ case GDTokenizer::TK_OP_MOD:
+ op = OperatorNode::OP_MOD;
+ break;
//case GDTokenizer::TK_OP_NEG: op=OperatorNode::OP_NEG ; break;
- case GDTokenizer::TK_OP_SHIFT_LEFT: op=OperatorNode::OP_SHIFT_LEFT ; break;
- case GDTokenizer::TK_OP_SHIFT_RIGHT: op=OperatorNode::OP_SHIFT_RIGHT ; break;
- case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN ; break;
- case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_ADD ; break;
- case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SUB ; break;
- case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MUL ; break;
- case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_DIV ; break;
- case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_MOD ; break;
- case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_LEFT; break;
- case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break;
- case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_AND ; break;
- case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_OR ; break;
- case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op=OperatorNode::OP_ASSIGN_BIT_XOR ; break;
- case GDTokenizer::TK_OP_BIT_AND: op=OperatorNode::OP_BIT_AND ; break;
- case GDTokenizer::TK_OP_BIT_OR: op=OperatorNode::OP_BIT_OR ; break;
- case GDTokenizer::TK_OP_BIT_XOR: op=OperatorNode::OP_BIT_XOR ; break;
- case GDTokenizer::TK_PR_EXTENDS: op=OperatorNode::OP_EXTENDS; break;
- case GDTokenizer::TK_CF_IF: op=OperatorNode::OP_TERNARY_IF; break;
- case GDTokenizer::TK_CF_ELSE: op=OperatorNode::OP_TERNARY_ELSE; break;
- default: valid=false; break;
+ case GDTokenizer::TK_OP_SHIFT_LEFT: op = OperatorNode::OP_SHIFT_LEFT; break;
+ case GDTokenizer::TK_OP_SHIFT_RIGHT: op = OperatorNode::OP_SHIFT_RIGHT; break;
+ case GDTokenizer::TK_OP_ASSIGN: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN; break;
+ case GDTokenizer::TK_OP_ASSIGN_ADD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_ADD; break;
+ case GDTokenizer::TK_OP_ASSIGN_SUB: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SUB; break;
+ case GDTokenizer::TK_OP_ASSIGN_MUL: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MUL; break;
+ case GDTokenizer::TK_OP_ASSIGN_DIV: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_DIV; break;
+ case GDTokenizer::TK_OP_ASSIGN_MOD: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_MOD; break;
+ case GDTokenizer::TK_OP_ASSIGN_SHIFT_LEFT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_LEFT; break;
+ case GDTokenizer::TK_OP_ASSIGN_SHIFT_RIGHT: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_SHIFT_RIGHT; break;
+ case GDTokenizer::TK_OP_ASSIGN_BIT_AND: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_AND; break;
+ case GDTokenizer::TK_OP_ASSIGN_BIT_OR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_OR; break;
+ case GDTokenizer::TK_OP_ASSIGN_BIT_XOR: _VALIDATE_ASSIGN op = OperatorNode::OP_ASSIGN_BIT_XOR; break;
+ case GDTokenizer::TK_OP_BIT_AND: op = OperatorNode::OP_BIT_AND; break;
+ case GDTokenizer::TK_OP_BIT_OR: op = OperatorNode::OP_BIT_OR; break;
+ case GDTokenizer::TK_OP_BIT_XOR: op = OperatorNode::OP_BIT_XOR; break;
+ case GDTokenizer::TK_PR_EXTENDS: op = OperatorNode::OP_EXTENDS; break;
+ case GDTokenizer::TK_CF_IF: op = OperatorNode::OP_TERNARY_IF; break;
+ case GDTokenizer::TK_CF_ELSE: op = OperatorNode::OP_TERNARY_ELSE; break;
+ default: valid = false; break;
}
if (valid) {
- e.is_op=true;
- e.op=op;
+ e.is_op = true;
+ e.op = op;
expression.push_back(e);
tokenizer->advance();
} else {
break;
}
-
}
/* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
+ while (expression.size() > 1) {
- 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++) {
-
+ 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 (!expression[i].is_op) {
@@ -1126,102 +1097,115 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
int priority;
- bool unary=false;
- bool ternary=false;
- bool error=false;
+ bool unary = false;
+ bool ternary = false;
+ bool error = false;
- switch(expression[i].op) {
+ switch (expression[i].op) {
- case OperatorNode::OP_EXTENDS: priority=-1; break; //before anything
+ case OperatorNode::OP_EXTENDS:
+ priority = -1;
+ break; //before anything
- case OperatorNode::OP_BIT_INVERT: priority=0; unary=true; break;
- case OperatorNode::OP_NEG: priority=1; unary=true; break;
- case OperatorNode::OP_POS: priority=1; unary=true; break;
+ case OperatorNode::OP_BIT_INVERT:
+ priority = 0;
+ unary = true;
+ break;
+ case OperatorNode::OP_NEG:
+ priority = 1;
+ unary = true;
+ break;
+ 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_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_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_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_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_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_EQUAL: priority = 8; break;
+ case OperatorNode::OP_NOT_EQUAL: priority = 8; break;
-
- case OperatorNode::OP_IN: priority=10; 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 OperatorNode::OP_TERNARY_IF: priority=14; ternary=true; break;
- case OperatorNode::OP_TERNARY_ELSE: priority=14; error=true; break; // Errors out when found without IF (since IF would consume it)
+ case OperatorNode::OP_IN: priority = 10; break;
- 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;
+ case OperatorNode::OP_NOT:
+ priority = 11;
+ unary = true;
+ break;
+ case OperatorNode::OP_AND: priority = 12; break;
+ case OperatorNode::OP_OR: priority = 13; break;
+ case OperatorNode::OP_TERNARY_IF:
+ priority = 14;
+ ternary = true;
+ break;
+ case OperatorNode::OP_TERNARY_ELSE:
+ priority = 14;
+ error = true;
+ break; // Errors out when found without IF (since IF would consume it)
+
+ 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("GDParser bug, invalid operator in expression: "+itos(expression[i].op));
+ _set_error("GDParser bug, invalid operator in expression: " + itos(expression[i].op));
return NULL;
}
-
}
- if (priority<min_priority) {
- if(error) {
+ if (priority < min_priority) {
+ if (error) {
_set_error("Unexpected operator");
return NULL;
}
// < is used for left to right (default)
// <= is used for right to left
- next_op=i;
- min_priority=priority;
- is_unary=unary;
- is_ternary=ternary;
+ next_op = i;
+ min_priority = priority;
+ is_unary = unary;
+ is_ternary = ternary;
}
-
}
-
- if (next_op==-1) {
-
+ if (next_op == -1) {
_set_error("Yet another parser bug....");
- ERR_FAIL_COND_V(next_op==-1,NULL);
+ ERR_FAIL_COND_V(next_op == -1, NULL);
}
-
// OK! create operator..
if (is_unary) {
- int expr_pos=next_op;
- while(expression[expr_pos].is_op) {
+ int expr_pos = next_op;
+ while (expression[expr_pos].is_op) {
expr_pos++;
- if (expr_pos==expression.size()) {
+ if (expr_pos == expression.size()) {
//can happen..
_set_error("Unexpected end of expression..");
return NULL;
@@ -1229,44 +1213,43 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
}
//consecutively do unary opeators
- for(int i=expr_pos-1;i>=next_op;i--) {
+ for (int i = expr_pos - 1; i >= next_op; i--) {
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[i].is_op=false;
- expression[i].node=op;
- expression.remove(i+1);
+ 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[i].is_op = false;
+ expression[i].node = op;
+ expression.remove(i + 1);
}
-
- } else if(is_ternary) {
- if (next_op <1 || next_op>=(expression.size()-1)) {
+ } else if (is_ternary) {
+ if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
-
- if(next_op>=(expression.size()-2) || expression[next_op+2].op != OperatorNode::OP_TERNARY_ELSE) {
+
+ if (next_op >= (expression.size() - 2) || expression[next_op + 2].op != OperatorNode::OP_TERNARY_ELSE) {
_set_error("Expected else after ternary if.");
ERR_FAIL_V(NULL);
}
- if(next_op>=(expression.size()-3)) {
+ if (next_op >= (expression.size() - 3)) {
_set_error("Expected value after ternary else.");
ERR_FAIL_V(NULL);
}
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[next_op].op;
- op->line=op_line; //line might have been changed from a \n
+ 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) {
+ if (expression[next_op - 1].is_op) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
- if (expression[next_op+1].is_op) {
+ 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 an unary op in a valid combination,
@@ -1276,7 +1259,7 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
return NULL;
}
- if (expression[next_op+3].is_op) {
+ 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 an unary op in a valid combination,
@@ -1286,35 +1269,34 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
return NULL;
}
-
- 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
+ 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[next_op-1].node=op;
+ expression[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)) {
+ if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[next_op].op;
- op->line=op_line; //line might have been changed from a \n
+ 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) {
+ if (expression[next_op - 1].is_op) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
- if (expression[next_op+1].is_op) {
+ 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 an unary op in a valid combination,
@@ -1324,26 +1306,22 @@ GDParser::Node* GDParser::_parse_expression(Node *p_parent,bool p_static,bool p_
return NULL;
}
-
- 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
+ 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[next_op-1].node=op;
+ expression[next_op - 1].node = op;
expression.remove(next_op);
expression.remove(next_op);
}
-
}
return expression[0].node;
-
}
+GDParser::Node *GDParser::_reduce_expression(Node *p_node, bool p_to_const) {
-GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
-
- switch(p_node->type) {
+ switch (p_node->type) {
case Node::TYPE_BUILT_IN_FUNCTION: {
//many may probably be optimizable
@@ -1351,14 +1329,14 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
} break;
case Node::TYPE_ARRAY: {
- ArrayNode *an = static_cast<ArrayNode*>(p_node);
- bool all_constants=true;
+ ArrayNode *an = static_cast<ArrayNode *>(p_node);
+ bool all_constants = true;
- for(int i=0;i<an->elements.size();i++) {
+ for (int i = 0; i < an->elements.size(); i++) {
- an->elements[i]=_reduce_expression(an->elements[i],p_to_const);
- if (an->elements[i]->type!=Node::TYPE_CONSTANT)
- all_constants=false;
+ an->elements[i] = _reduce_expression(an->elements[i], p_to_const);
+ if (an->elements[i]->type != Node::TYPE_CONSTANT)
+ all_constants = false;
}
if (all_constants && p_to_const) {
@@ -1368,12 +1346,11 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
Array arr;
//print_line("mk array "+itos(!p_to_const));
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;
-
+ for (int i = 0; i < an->elements.size(); i++) {
+ ConstantNode *acn = static_cast<ConstantNode *>(an->elements[i]);
+ arr[i] = acn->value;
}
- cn->value=arr;
+ cn->value = arr;
return cn;
}
@@ -1382,18 +1359,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
} 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++) {
+ DictionaryNode *dn = static_cast<DictionaryNode *>(p_node);
+ bool all_constants = true;
- dn->elements[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[i].value=_reduce_expression(dn->elements[i].value,p_to_const);
- if (dn->elements[i].value->type!=Node::TYPE_CONSTANT)
- all_constants=false;
+ for (int i = 0; i < dn->elements.size(); i++) {
+ dn->elements[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[i].value = _reduce_expression(dn->elements[i].value, p_to_const);
+ if (dn->elements[i].value->type != Node::TYPE_CONSTANT)
+ all_constants = false;
}
if (all_constants && p_to_const) {
@@ -1401,157 +1377,143 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
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);
-
- dict[key_c->value]=value_c->value;
+ 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);
+ dict[key_c->value] = value_c->value;
}
- cn->value=dict;
+ cn->value = dict;
return cn;
}
return dn;
-
} break;
case Node::TYPE_OPERATOR: {
- OperatorNode *op=static_cast<OperatorNode*>(p_node);
+ OperatorNode *op = static_cast<OperatorNode *>(p_node);
- bool all_constants=true;
- int last_not_constant=-1;
+ bool all_constants = true;
+ int last_not_constant = -1;
- for(int i=0;i<op->arguments.size();i++) {
+ for (int i = 0; i < op->arguments.size(); i++) {
- op->arguments[i]=_reduce_expression(op->arguments[i],p_to_const);
- if (op->arguments[i]->type!=Node::TYPE_CONSTANT) {
- all_constants=false;
- last_not_constant=i;
+ op->arguments[i] = _reduce_expression(op->arguments[i], p_to_const);
+ if (op->arguments[i]->type != Node::TYPE_CONSTANT) {
+ all_constants = false;
+ last_not_constant = i;
}
}
- if (op->op==OperatorNode::OP_EXTENDS) {
+ if (op->op == OperatorNode::OP_EXTENDS) {
//nothing much
return op;
-
- } if (op->op==OperatorNode::OP_PARENT_CALL) {
+ }
+ if (op->op == OperatorNode::OP_PARENT_CALL) {
//nothing much
return op;
- } else if (op->op==OperatorNode::OP_CALL) {
+ } 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 && GDFunctions::is_deterministic( static_cast<BuiltInFunctionNode*>(op->arguments[0])->function))) && last_not_constant==0) {
+ if ((op->arguments[0]->type == Node::TYPE_TYPE || (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && GDFunctions::is_deterministic(static_cast<BuiltInFunctionNode *>(op->arguments[0])->function))) && last_not_constant == 0) {
//native type constructor or intrinsic function
- const Variant **vptr=NULL;
- Vector<Variant*> ptrs;
- if (op->arguments.size()>1) {
-
- ptrs.resize(op->arguments.size()-1);
- for(int i=0;i<ptrs.size();i++) {
+ const Variant **vptr = NULL;
+ 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[i]=&cn->value;
+ ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i + 1]);
+ ptrs[i] = &cn->value;
}
- vptr=(const Variant**)&ptrs[0];
-
-
+ vptr = (const Variant **)&ptrs[0];
}
Variant::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);
+ 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 {
- GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function;
- GDFunctions::call(func,vptr,ptrs.size(),v,ce);
+ GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function;
+ GDFunctions::call(func, vptr, ptrs.size(), v, ce);
}
-
- if (ce.error!=Variant::CallError::CALL_OK) {
+ if (ce.error != Variant::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";
+ 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 {
- GDFunctions::Function func = static_cast<BuiltInFunctionNode*>(op->arguments[0])->function;
- errwhere=String("'")+GDFunctions::get_func_name(func)+"'' intrinsic function";
-
+ GDFunctions::Function func = static_cast<BuiltInFunctionNode *>(op->arguments[0])->function;
+ errwhere = String("'") + GDFunctions::get_func_name(func) + "'' intrinsic function";
}
- switch(ce.error) {
+ switch (ce.error) {
case Variant::CallError::CALL_ERROR_INVALID_ARGUMENT: {
- _set_error("Invalid argument (#"+itos(ce.argument+1)+") for "+errwhere+".");
+ _set_error("Invalid argument (#" + itos(ce.argument + 1) + ") for " + errwhere + ".");
} break;
case Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
- _set_error("Too many arguments for "+errwhere+".");
+ _set_error("Too many arguments for " + errwhere + ".");
} break;
case Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: {
- _set_error("Too few arguments for "+errwhere+".");
+ _set_error("Too few arguments for " + errwhere + ".");
} break;
default: {
- _set_error("Invalid arguments for "+errwhere+".");
+ _set_error("Invalid arguments for " + errwhere + ".");
} break;
}
- error_line=op->line;
+ error_line = op->line;
return p_node;
}
ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value=v;
+ cn->value = v;
return cn;
- } else if (op->arguments[0]->type==Node::TYPE_BUILT_IN_FUNCTION && last_not_constant==0) {
-
-
-
-
-
+ } else if (op->arguments[0]->type == Node::TYPE_BUILT_IN_FUNCTION && last_not_constant == 0) {
}
return op; //don't reduce yet
- } else if (op->op==OperatorNode::OP_YIELD) {
+ } else if (op->op == OperatorNode::OP_YIELD) {
return op;
- } else if (op->op==OperatorNode::OP_INDEX) {
+ } else if (op->op == OperatorNode::OP_INDEX) {
//can reduce indices into constant arrays or dictionaries
if (all_constants) {
- ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]);
- ConstantNode *cb = static_cast<ConstantNode*>(op->arguments[1]);
-
-
+ ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]);
+ ConstantNode *cb = static_cast<ConstantNode *>(op->arguments[1]);
bool valid;
- Variant v = ca->value.get(cb->value,&valid);
+ Variant v = ca->value.get(cb->value, &valid);
if (!valid) {
_set_error("invalid index in constant expression");
- error_line=op->line;
+ error_line = op->line;
return op;
}
ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value=v;
+ cn->value = v;
return cn;
} /*else if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) {
@@ -1573,32 +1535,31 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
return op;
- } else if (op->op==OperatorNode::OP_INDEX_NAMED) {
+ } else if (op->op == OperatorNode::OP_INDEX_NAMED) {
- if (op->arguments[0]->type==Node::TYPE_CONSTANT && op->arguments[1]->type==Node::TYPE_IDENTIFIER) {
+ if (op->arguments[0]->type == Node::TYPE_CONSTANT && op->arguments[1]->type == Node::TYPE_IDENTIFIER) {
- ConstantNode *ca = static_cast<ConstantNode*>(op->arguments[0]);
- IdentifierNode *ib = static_cast<IdentifierNode*>(op->arguments[1]);
+ ConstantNode *ca = static_cast<ConstantNode *>(op->arguments[0]);
+ IdentifierNode *ib = static_cast<IdentifierNode *>(op->arguments[1]);
bool valid;
- Variant v = ca->value.get_named(ib->name,&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;
+ _set_error("invalid index '" + String(ib->name) + "' in constant expression");
+ error_line = op->line;
return op;
}
ConstantNode *cn = alloc_node<ConstantNode>();
- cn->value=v;
+ cn->value = v;
return cn;
}
return op;
-
}
//validate assignment (don't assign to cosntant expression
- switch(op->op) {
+ switch (op->op) {
case OperatorNode::OP_ASSIGN:
case OperatorNode::OP_ASSIGN_ADD:
@@ -1612,17 +1573,17 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
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;
+ 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;
}
- if (op->arguments[0]->type==Node::TYPE_OPERATOR) {
- OperatorNode *on = static_cast<OperatorNode*>(op->arguments[0]);
+ 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;
+ _set_error("Can't assign to an expression", tokenizer->get_token_line() - 1);
+ error_line = op->line;
return op;
}
}
@@ -1633,59 +1594,105 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
//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;\
+#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; \
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;\
+#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; \
return cn;
- switch(op->op) {
+ 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;
+ 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_SUBSTRACT); } 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_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_SUBSTRACT);
+ } 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;
default: { ERR_FAIL_V(op); }
}
@@ -1694,16 +1701,15 @@ GDParser::Node* GDParser::_reduce_expression(Node *p_node,bool p_to_const) {
default: {
return p_node;
} break;
-
}
}
-GDParser::Node* GDParser::_parse_and_reduce_expression(Node *p_parent,bool p_static,bool p_reduce_const,bool p_allow_assign) {
+GDParser::Node *GDParser::_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);
+ Node *expr = _parse_expression(p_parent, p_static, p_allow_assign, p_reduce_const);
if (!expr || error_set)
return NULL;
- expr = _reduce_expression(expr,p_reduce_const);
+ expr = _reduce_expression(expr, p_reduce_const);
if (!expr || error_set)
return NULL;
return expr;
@@ -1715,43 +1721,42 @@ bool GDParser::_recover_from_completion() {
return false; //can't recover if no completion
}
//skip stuff until newline
- while(tokenizer->get_token()!=GDTokenizer::TK_NEWLINE && tokenizer->get_token()!=GDTokenizer::TK_EOF && tokenizer->get_token()!=GDTokenizer::TK_ERROR) {
+ while (tokenizer->get_token() != GDTokenizer::TK_NEWLINE && tokenizer->get_token() != GDTokenizer::TK_EOF && tokenizer->get_token() != GDTokenizer::TK_ERROR) {
tokenizer->advance();
}
- completion_found=false;
- error_set=false;
- if(tokenizer->get_token() == GDTokenizer::TK_ERROR){
+ completion_found = false;
+ error_set = false;
+ if (tokenizer->get_token() == GDTokenizer::TK_ERROR) {
error_set = true;
}
return true;
}
-GDParser::PatternNode *GDParser::_parse_pattern(bool p_static)
-{
-
+GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) {
+
PatternNode *pattern = alloc_node<PatternNode>();
-
+
GDTokenizer::Token token = tokenizer->get_token();
if (error_set)
return NULL;
-
+
if (token == GDTokenizer::TK_EOF) {
return NULL;
}
-
+
switch (token) {
// array
case GDTokenizer::TK_BRACKET_OPEN: {
tokenizer->advance();
pattern->pt_type = GDParser::PatternNode::PT_ARRAY;
while (true) {
-
+
if (tokenizer->get_token() == GDTokenizer::TK_BRACKET_CLOSE) {
tokenizer->advance();
break;
}
-
+
if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) {
// match everything
tokenizer->advance(2);
@@ -1769,14 +1774,14 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static)
return NULL;
}
}
-
+
PatternNode *sub_pattern = _parse_pattern(p_static);
if (!sub_pattern) {
return NULL;
}
-
+
pattern->array.push_back(sub_pattern);
-
+
if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
continue;
@@ -1801,12 +1806,12 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static)
tokenizer->advance();
pattern->pt_type = GDParser::PatternNode::PT_DICTIONARY;
while (true) {
-
+
if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) {
tokenizer->advance();
break;
}
-
+
if (tokenizer->get_token() == GDTokenizer::TK_PERIOD && tokenizer->get_token(1) == GDTokenizer::TK_PERIOD) {
// match everything
tokenizer->advance(2);
@@ -1824,33 +1829,32 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static)
return NULL;
}
}
-
+
Node *key = _parse_and_reduce_expression(pattern, p_static);
if (!key) {
_set_error("Not a valid key in pattern");
return NULL;
}
-
+
if (key->type != GDParser::Node::TYPE_CONSTANT) {
_set_error("Not a constant expression as key");
return NULL;
}
-
+
if (tokenizer->get_token() == GDTokenizer::TK_COLON) {
tokenizer->advance();
-
+
PatternNode *value = _parse_pattern(p_static);
if (!value) {
_set_error("Expected pattern in dictionary value");
return NULL;
}
-
- pattern->dictionary.insert(static_cast<ConstantNode*>(key), value);
+
+ pattern->dictionary.insert(static_cast<ConstantNode *>(key), value);
} else {
- pattern->dictionary.insert(static_cast<ConstantNode*>(key), NULL);
+ pattern->dictionary.insert(static_cast<ConstantNode *>(key), NULL);
}
-
-
+
if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
continue;
@@ -1873,47 +1877,47 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static)
if (error_set) {
return NULL;
}
-
+
if (value->type != Node::TYPE_IDENTIFIER && value->type != Node::TYPE_CONSTANT) {
_set_error("Only constant expressions or variables allowed in a pattern");
return NULL;
}
-
+
pattern->pt_type = PatternNode::PT_CONSTANT;
pattern->constant = value;
} break;
}
-
+
return pattern;
}
-void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode*> &p_branches, bool p_static)
-{
+void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static) {
int indent_level = tab_level.back()->get();
-
+
while (true) {
-
- while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE && _parse_newline());
-
+
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE && _parse_newline())
+ ;
+
// GDTokenizer::Token token = tokenizer->get_token();
if (error_set)
return;
-
+
if (indent_level > tab_level.back()->get()) {
return; // go back a level
}
-
- if (pending_newline!=-1) {
- pending_newline=-1;
+
+ if (pending_newline != -1) {
+ pending_newline = -1;
}
-
+
PatternBranchNode *branch = alloc_node<PatternBranchNode>();
-
+
branch->patterns.push_back(_parse_pattern(p_static));
if (!branch->patterns[0]) {
return;
}
-
+
while (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
branch->patterns.push_back(_parse_pattern(p_static));
@@ -1921,263 +1925,249 @@ void GDParser::_parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode
return;
}
}
-
- if(!_enter_indent_block()) {
+
+ if (!_enter_indent_block()) {
_set_error("Expected block in pattern branch");
return;
}
-
+
branch->body = alloc_node<BlockNode>();
branch->body->parent_block = p_block;
p_block->sub_blocks.push_back(branch->body);
current_block = branch->body;
-
+
_parse_block(branch->body, p_static);
-
+
current_block = p_block;
-
+
p_branches.push_back(branch);
}
}
-
-void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node*> &p_bindings)
-{
+void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match, Node *&p_resulting_node, Map<StringName, Node *> &p_bindings) {
switch (p_pattern->pt_type) {
case PatternNode::PT_CONSTANT: {
-
+
// typecheck
BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
typeof_node->function = GDFunctions::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);
-
+
OperatorNode *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);
-
-
+
// comare 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);
-
-
+
OperatorNode *comparison = alloc_node<OperatorNode>();
comparison->op = OperatorNode::OP_AND;
comparison->arguments.push_back(type_comp);
comparison->arguments.push_back(value_comp);
-
+
p_resulting_node = comparison;
-
+
} 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);
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
-
+
{
// typecheck
BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
typeof_node->function = GDFunctions::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";
-
+
OperatorNode *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());
-
+
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);
-
+
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;
}
-
-
-
+
for (int i = 0; i < p_pattern->array.size(); i++) {
PatternNode *pattern = p_pattern->array[i];
-
+
Node *condition = NULL;
-
+
ConstantNode *index = alloc_node<ConstantNode>();
index->value = Variant(i);
-
+
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;
-
+
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
-
-
+
{
// typecheck
BuiltInFunctionNode *typeof_node = alloc_node<BuiltInFunctionNode>();
typeof_node->function = GDFunctions::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";
-
+
OperatorNode *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());
-
+
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);
-
+
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;
}
-
-
-
- for (Map<ConstantNode*, PatternNode*>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) {
-
+
+ for (Map<ConstantNode *, PatternNode *>::Element *e = p_pattern->dictionary.front(); e; e = e->next()) {
+
Node *condition = NULL;
-
+
// chech for has, then for pattern
-
+
IdentifierNode *has = alloc_node<IdentifierNode>();
has->name = "has";
-
+
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());
-
-
+
if (e->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(e->key());
-
+
_generate_pattern(e->value(), indexed_value, condition, p_bindings);
-
+
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);
-
+
condition = has_and_pattern;
} 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;
}
-
+
} break;
case PatternNode::PT_IGNORE_REST:
case PatternNode::PT_WILDCARD: {
@@ -2187,119 +2177,110 @@ void GDParser::_generate_pattern(PatternNode *p_pattern, Node *p_node_to_match,
p_resulting_node = true_value;
} break;
default: {
-
+
} break;
}
}
-void GDParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement)
-{
+void GDParser::_transform_match_statment(BlockNode *p_block, MatchNode *p_match_statement) {
IdentifierNode *id = alloc_node<IdentifierNode>();
id->name = "#match_value";
-
+
for (int i = 0; i < p_match_statement->branches.size(); i++) {
-
+
PatternBranchNode *branch = p_match_statement->branches[i];
-
+
MatchNode::CompiledPatternBranch compiled_branch;
compiled_branch.compiled_pattern = NULL;
-
- Map<StringName, Node*> binding;
-
+
+ Map<StringName, Node *> binding;
+
for (int j = 0; j < branch->patterns.size(); j++) {
PatternNode *pattern = branch->patterns[j];
-
- Map<StringName, Node*> bindings;
+
+ Map<StringName, Node *> bindings;
Node *resulting_node;
_generate_pattern(pattern, id, resulting_node, bindings);
-
+
if (!binding.empty() && !bindings.empty()) {
_set_error("Multipatterns can't contain bindings");
return;
} else {
binding = bindings;
}
-
+
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;
}
-
}
-
-
+
// prepare the body ...hehe
- for (Map<StringName, Node*>::Element *e = binding.front(); e; e = e->next()) {
+ for (Map<StringName, Node *>::Element *e = binding.front(); e; e = e->next()) {
LocalVarNode *local_var = alloc_node<LocalVarNode>();
local_var->name = e->key();
local_var->assign = e->value();
-
IdentifierNode *id = alloc_node<IdentifierNode>();
id->name = local_var->name;
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_ASSIGN;
+ op->op = OperatorNode::OP_ASSIGN;
op->arguments.push_back(id);
op->arguments.push_back(local_var->assign);
-
+
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);
}
-
}
-void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
+void GDParser::_parse_block(BlockNode *p_block, bool p_static) {
int indent_level = tab_level.back()->get();
-
#ifdef DEBUG_ENABLED
NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line=tokenizer->get_token_line();
+ nl->line = tokenizer->get_token_line();
p_block->statements.push_back(nl);
#endif
- while(true) {
+ while (true) {
GDTokenizer::Token token = tokenizer->get_token();
if (error_set)
return;
- if (indent_level>tab_level.back()->get()) {
- p_block->end_line=tokenizer->get_token_line();
+ if (indent_level > tab_level.back()->get()) {
+ p_block->end_line = tokenizer->get_token_line();
return; //go back a level
}
- if (pending_newline!=-1) {
+ if (pending_newline != -1) {
NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line=pending_newline;
+ nl->line = pending_newline;
p_block->statements.push_back(nl);
- pending_newline=-1;
-
+ pending_newline = -1;
}
- switch(token) {
-
+ switch (token) {
case GDTokenizer::TK_EOF:
- p_block->end_line=tokenizer->get_token_line();
+ p_block->end_line = tokenizer->get_token_line();
case GDTokenizer::TK_ERROR: {
return; //go back
@@ -2310,26 +2291,25 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
if (!_parse_newline()) {
if (!error_set) {
- p_block->end_line=tokenizer->get_token_line();
- pending_newline=p_block->end_line;
-
+ p_block->end_line = tokenizer->get_token_line();
+ pending_newline = p_block->end_line;
}
return;
}
NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line=tokenizer->get_token_line();
+ nl->line = tokenizer->get_token_line();
p_block->statements.push_back(nl);
} break;
case GDTokenizer::TK_CF_PASS: {
- if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE && tokenizer->get_token(1)!=GDTokenizer::TK_EOF) {
+ if (tokenizer->get_token(1) != GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE && tokenizer->get_token(1) != GDTokenizer::TK_EOF) {
_set_error("Expected ';' or <NewLine>.");
return;
}
tokenizer->advance();
- if(tokenizer->get_token()==GDTokenizer::TK_SEMICOLON) {
+ if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON) {
// Ignore semicolon after 'pass'
tokenizer->advance();
}
@@ -2338,26 +2318,26 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
//variale declaration and (eventual) initialization
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier for local variable name.");
return;
}
StringName n = tokenizer->get_token_identifier();
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)+").");
+ 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){
- for (int i=0;i<check_block->variables.size();i++){
- if (n == check_block->variables[i]){
- _set_error("Variable '"+String(n)+"' already defined in the scope (at line: "+itos(check_block->variable_lines[i])+").");
+ while (check_block) {
+ for (int i = 0; i < check_block->variables.size(); i++) {
+ if (n == check_block->variables[i]) {
+ _set_error("Variable '" + String(n) + "' already defined in the scope (at line: " + itos(check_block->variable_lines[i]) + ").");
return;
}
}
@@ -2367,20 +2347,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
p_block->variables.push_back(n); //line?
p_block->variable_lines.push_back(tokenizer->get_token_line());
-
//must know when the local variable is declared
LocalVarNode *lv = alloc_node<LocalVarNode>();
- lv->name=n;
+ lv->name = n;
p_block->statements.push_back(lv);
- Node *assigned=NULL;
+ Node *assigned = NULL;
- if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) {
tokenizer->advance();
- Node *subexpr=NULL;
+ Node *subexpr = NULL;
- subexpr = _parse_and_reduce_expression(p_block,p_static);
+ subexpr = _parse_and_reduce_expression(p_block, p_static);
if (!subexpr) {
if (_recover_from_completion()) {
break;
@@ -2388,23 +2367,19 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
return;
}
-
-
- lv->assign=subexpr;
- assigned=subexpr;
+ lv->assign = subexpr;
+ assigned = subexpr;
} else {
ConstantNode *c = alloc_node<ConstantNode>();
- c->value=Variant();
+ c->value = Variant();
assigned = c;
-
}
IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name=n;
-
+ id->name = n;
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_ASSIGN;
+ op->op = OperatorNode::OP_ASSIGN;
op->arguments.push_back(id);
op->arguments.push_back(assigned);
p_block->statements.push_back(op);
@@ -2418,8 +2393,8 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
case GDTokenizer::TK_CF_IF: {
tokenizer->advance();
-
- Node *condition = _parse_and_reduce_expression(p_block,p_static);
+
+ Node *condition = _parse_and_reduce_expression(p_block, p_static);
if (!condition) {
if (_recover_from_completion()) {
break;
@@ -2429,39 +2404,39 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
ControlFlowNode *cf_if = alloc_node<ControlFlowNode>();
- cf_if->cf_type=ControlFlowNode::CF_IF;
+ 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->parent_block = p_block;
p_block->sub_blocks.push_back(cf_if->body);
if (!_enter_indent_block(cf_if->body)) {
_set_error("Expected intended block after 'if'");
- p_block->end_line=tokenizer->get_token_line();
+ 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;
+ 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);
- while(true) {
+ while (true) {
- while(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
if (tab_level.back()->get() < indent_level) { //not at current indent level
- p_block->end_line=tokenizer->get_token_line();
+ p_block->end_line = tokenizer->get_token_line();
return;
}
- if (tokenizer->get_token()==GDTokenizer::TK_CF_ELIF) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CF_ELIF) {
if (tab_level.back()->get() > indent_level) {
@@ -2471,15 +2446,15 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
- cf_if->body_else=alloc_node<BlockNode>();
- cf_if->body_else->parent_block=p_block;
+ 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;
+ cf_else->cf_type = ControlFlowNode::CF_IF;
//condition
- Node *condition = _parse_and_reduce_expression(p_block,p_static);
+ Node *condition = _parse_and_reduce_expression(p_block, p_static);
if (!condition) {
if (_recover_from_completion()) {
break;
@@ -2487,66 +2462,60 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
return;
}
cf_else->arguments.push_back(condition);
- cf_else->cf_type=ControlFlowNode::CF_IF;
+ 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;
+ 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 indented block after 'elif'");
- p_block->end_line=tokenizer->get_token_line();
+ 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;
+ current_block = cf_else->body;
+ _parse_block(cf_else->body, p_static);
+ current_block = p_block;
if (error_set)
return;
-
- } else if (tokenizer->get_token()==GDTokenizer::TK_CF_ELSE) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CF_ELSE) {
if (tab_level.back()->get() > indent_level) {
_set_error("Invalid indent");
return;
}
-
tokenizer->advance();
- cf_if->body_else=alloc_node<BlockNode>();
- cf_if->body_else->parent_block=p_block;
+ 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 indented block after 'else'");
- p_block->end_line=tokenizer->get_token_line();
+ p_block->end_line = tokenizer->get_token_line();
return;
}
- current_block=cf_if->body_else;
- _parse_block(cf_if->body_else,p_static);
- current_block=p_block;
+ current_block = cf_if->body_else;
+ _parse_block(cf_if->body_else, p_static);
+ current_block = p_block;
if (error_set)
return;
-
break; //after else, exit
} else
break;
-
}
-
} break;
case GDTokenizer::TK_CF_WHILE: {
tokenizer->advance();
- Node *condition = _parse_and_reduce_expression(p_block,p_static);
+ Node *condition = _parse_and_reduce_expression(p_block, p_static);
if (!condition) {
if (_recover_from_completion()) {
break;
@@ -2556,22 +2525,22 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
ControlFlowNode *cf_while = alloc_node<ControlFlowNode>();
- cf_while->cf_type=ControlFlowNode::CF_WHILE;
+ cf_while->cf_type = ControlFlowNode::CF_WHILE;
cf_while->arguments.push_back(condition);
cf_while->body = alloc_node<BlockNode>();
- cf_while->body->parent_block=p_block;
+ 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 indented block after 'while'");
- p_block->end_line=tokenizer->get_token_line();
+ 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;
+ current_block = cf_while->body;
+ _parse_block(cf_while->body, p_static);
+ current_block = p_block;
if (error_set)
return;
p_block->statements.push_back(cf_while);
@@ -2580,24 +2549,24 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("identifier expected after 'for'");
}
IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name=tokenizer->get_token_identifier();
+ id->name = tokenizer->get_token_identifier();
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_OP_IN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_OP_IN) {
_set_error("'in' expected after identifier");
return;
}
tokenizer->advance();
- Node *container = _parse_and_reduce_expression(p_block,p_static);
+ Node *container = _parse_and_reduce_expression(p_block, p_static);
if (!container) {
if (_recover_from_completion()) {
break;
@@ -2605,91 +2574,90 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
return;
}
- if (container->type==Node::TYPE_OPERATOR) {
+ 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==GDFunctions::GEN_RANGE) {
+ 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 == GDFunctions::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<Node *> args;
Vector<double> constants;
- bool constant=false;
+ bool constant = false;
- for(int i=1;i<op->arguments.size();i++) {
+ for (int i = 1; i < op->arguments.size(); i++) {
args.push_back(op->arguments[i]);
- if (constant && op->arguments[i]->type==Node::TYPE_CONSTANT) {
- ConstantNode *c = static_cast<ConstantNode*>(op->arguments[i]);
- if (c->value.get_type()==Variant::REAL || c->value.get_type()==Variant::INT) {
+ if (constant && op->arguments[i]->type == Node::TYPE_CONSTANT) {
+ ConstantNode *c = static_cast<ConstantNode *>(op->arguments[i]);
+ if (c->value.get_type() == Variant::REAL || c->value.get_type() == Variant::INT) {
constants.push_back(c->value);
- constant=true;
+ constant = true;
}
} else {
- constant=false;
+ constant = false;
}
}
- if (args.size()>0 && args.size()<4) {
+ if (args.size() > 0 && args.size() < 4) {
if (constant) {
ConstantNode *cn = alloc_node<ConstantNode>();
- switch(args.size()) {
- case 1: cn->value=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;
+ switch (args.size()) {
+ case 1: cn->value = 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;
}
- container=cn;
+ container = cn;
} else {
OperatorNode *on = alloc_node<OperatorNode>();
- on->op=OperatorNode::OP_CALL;
+ on->op = OperatorNode::OP_CALL;
TypeNode *tn = alloc_node<TypeNode>();
on->arguments.push_back(tn);
- switch(args.size()) {
- case 1: tn->vtype=Variant::REAL; break;
- case 2: tn->vtype=Variant::VECTOR2; break;
- case 3: tn->vtype=Variant::VECTOR3; break;
+ switch (args.size()) {
+ case 1: tn->vtype = Variant::REAL; break;
+ case 2: tn->vtype = Variant::VECTOR2; break;
+ case 3: tn->vtype = Variant::VECTOR3; break;
}
- for(int i=0;i<args.size();i++) {
+ for (int i = 0; i < args.size(); i++) {
on->arguments.push_back(args[i]);
}
- container=on;
+ container = on;
}
}
}
-
}
ControlFlowNode *cf_for = alloc_node<ControlFlowNode>();
- cf_for->cf_type=ControlFlowNode::CF_FOR;
+ 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;
+ 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();
+ p_block->end_line = tokenizer->get_token_line();
return;
}
- current_block=cf_for->body;
+ current_block = cf_for->body;
// this is for checking variable for redefining
// inside this _parse_block
cf_for->body->variables.push_back(id->name);
cf_for->body->variable_lines.push_back(id->line);
- _parse_block(cf_for->body,p_static);
+ _parse_block(cf_for->body, p_static);
cf_for->body->variables.remove(0);
cf_for->body->variable_lines.remove(0);
- current_block=p_block;
+ current_block = p_block;
if (error_set)
return;
@@ -2699,7 +2667,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
ControlFlowNode *cf_continue = alloc_node<ControlFlowNode>();
- cf_continue->cf_type=ControlFlowNode::CF_CONTINUE;
+ cf_continue->cf_type = ControlFlowNode::CF_CONTINUE;
p_block->statements.push_back(cf_continue);
if (!_end_statement()) {
_set_error("Expected end of statement (continue)");
@@ -2710,7 +2678,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
ControlFlowNode *cf_break = alloc_node<ControlFlowNode>();
- cf_break->cf_type=ControlFlowNode::CF_BREAK;
+ cf_break->cf_type = ControlFlowNode::CF_BREAK;
p_block->statements.push_back(cf_break);
if (!_end_statement()) {
_set_error("Expected end of statement (break)");
@@ -2721,11 +2689,9 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
ControlFlowNode *cf_return = alloc_node<ControlFlowNode>();
- cf_return->cf_type=ControlFlowNode::CF_RETURN;
+ cf_return->cf_type = ControlFlowNode::CF_RETURN;
-
-
- if (tokenizer->get_token()==GDTokenizer::TK_SEMICOLON || tokenizer->get_token()==GDTokenizer::TK_NEWLINE || tokenizer->get_token()==GDTokenizer::TK_EOF) {
+ if (tokenizer->get_token() == GDTokenizer::TK_SEMICOLON || tokenizer->get_token() == GDTokenizer::TK_NEWLINE || tokenizer->get_token() == GDTokenizer::TK_EOF) {
//expect end of statement
p_block->statements.push_back(cf_return);
if (!_end_statement()) {
@@ -2733,7 +2699,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
}
} else {
//expect expression
- Node *retexpr = _parse_and_reduce_expression(p_block,p_static);
+ Node *retexpr = _parse_and_reduce_expression(p_block, p_static);
if (!retexpr) {
if (_recover_from_completion()) {
break;
@@ -2748,52 +2714,51 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
}
}
-
} break;
case GDTokenizer::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);
-
+
_transform_match_statment(compiled_branches, match_node);
-
+
ControlFlowNode *match_cf_node = alloc_node<ControlFlowNode>();
match_cf_node->cf_type = ControlFlowNode::CF_MATCH;
match_cf_node->match = match_node;
-
+
p_block->statements.push_back(match_cf_node);
-
+
_end_statement();
} break;
case GDTokenizer::TK_PR_ASSERT: {
tokenizer->advance();
- Node *condition = _parse_and_reduce_expression(p_block,p_static);
+ Node *condition = _parse_and_reduce_expression(p_block, p_static);
if (!condition) {
if (_recover_from_completion()) {
break;
@@ -2801,7 +2766,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
return;
}
AssertNode *an = alloc_node<AssertNode>();
- an->condition=condition;
+ an->condition = condition;
p_block->statements.push_back(an);
if (!_end_statement()) {
@@ -2822,7 +2787,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
} break;
default: {
- Node *expression = _parse_and_reduce_expression(p_block,p_static,false,true);
+ Node *expression = _parse_and_reduce_expression(p_block, p_static, false, true);
if (!expression) {
if (_recover_from_completion()) {
break;
@@ -2836,7 +2801,7 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
}
} break;
- /*
+ /*
case GDTokenizer::TK_CF_LOCAL: {
if (tokenizer->get_token(1)!=GDTokenizer::TK_SEMICOLON && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE ) {
@@ -2846,37 +2811,35 @@ void GDParser::_parse_block(BlockNode *p_block,bool p_static) {
tokenizer->advance();
} break;
*/
-
}
}
-
}
bool GDParser::_parse_newline() {
- if (tokenizer->get_token(1)!=GDTokenizer::TK_EOF && tokenizer->get_token(1)!=GDTokenizer::TK_NEWLINE) {
+ if (tokenizer->get_token(1) != GDTokenizer::TK_EOF && tokenizer->get_token(1) != GDTokenizer::TK_NEWLINE) {
int indent = tokenizer->get_token_line_indent();
int current_indent = tab_level.back()->get();
- if (indent>current_indent) {
+ if (indent > current_indent) {
_set_error("Unexpected indent.");
return false;
}
- if (indent<current_indent) {
+ if (indent < current_indent) {
- while(indent<current_indent) {
+ while (indent < current_indent) {
//exit block
- if (tab_level.size()==1) {
+ if (tab_level.size() == 1) {
_set_error("Invalid indent. BUG?");
return false;
}
tab_level.pop_back();
- if (tab_level.back()->get()<indent) {
+ if (tab_level.back()->get() < indent) {
_set_error("Unindent does not match any outer indentation level.");
return false;
@@ -2891,13 +2854,10 @@ bool GDParser::_parse_newline() {
tokenizer->advance();
return true;
-
}
-
void GDParser::_parse_extends(ClassNode *p_class) {
-
if (p_class->extends_used) {
_set_error("'extends' already used for this class.");
@@ -2910,73 +2870,70 @@ void GDParser::_parse_extends(ClassNode *p_class) {
return;
}
- p_class->extends_used=true;
+ p_class->extends_used = true;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE && tokenizer->get_token_type()==Variant::OBJECT) {
+ if (tokenizer->get_token() == GDTokenizer::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;
}
// see if inheritance happens from a file
- if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT) {
Variant constant = tokenizer->get_token_constant();
- if (constant.get_type()!=Variant::STRING) {
+ if (constant.get_type() != Variant::STRING) {
_set_error("'extends' constant must be a string.");
return;
}
- p_class->extends_file=constant;
+ p_class->extends_file = constant;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PERIOD) {
return;
} else
tokenizer->advance();
-
}
- while(true) {
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ while (true) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Invalid 'extends' syntax, expected string constant (path) and/or identifier (parent class).");
return;
}
- StringName identifier=tokenizer->get_token_identifier();
+ StringName identifier = tokenizer->get_token_identifier();
p_class->extends_class.push_back(identifier);
tokenizer->advance(1);
- if (tokenizer->get_token()!=GDTokenizer::TK_PERIOD)
+ if (tokenizer->get_token() != GDTokenizer::TK_PERIOD)
return;
}
-
}
void GDParser::_parse_class(ClassNode *p_class) {
int indent_level = tab_level.back()->get();
- while(true) {
+ while (true) {
GDTokenizer::Token token = tokenizer->get_token();
if (error_set)
return;
-
- if (indent_level>tab_level.back()->get()) {
- p_class->end_line=tokenizer->get_token_line();
+ if (indent_level > tab_level.back()->get()) {
+ p_class->end_line = tokenizer->get_token_line();
return; //go back a level
}
- switch(token) {
+ switch (token) {
case GDTokenizer::TK_EOF:
- p_class->end_line=tokenizer->get_token_line();
+ p_class->end_line = tokenizer->get_token_line();
case GDTokenizer::TK_ERROR: {
return; //go back
//end of file!
@@ -2984,7 +2941,7 @@ void GDParser::_parse_class(ClassNode *p_class) {
case GDTokenizer::TK_NEWLINE: {
if (!_parse_newline()) {
if (!error_set) {
- p_class->end_line=tokenizer->get_token_line();
+ p_class->end_line = tokenizer->get_token_line();
}
return;
}
@@ -3008,7 +2965,7 @@ void GDParser::_parse_class(ClassNode *p_class) {
return;
}
- p_class->tool=true;
+ p_class->tool = true;
tokenizer->advance();
} break;
@@ -3018,7 +2975,7 @@ void GDParser::_parse_class(ClassNode *p_class) {
StringName name;
StringName extends;
- if (tokenizer->get_token(1)!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token(1) != GDTokenizer::TK_IDENTIFIER) {
_set_error("'class' syntax: 'class <Name>:' or 'class <Name> extends <BaseClass>:'");
return;
@@ -3028,16 +2985,15 @@ void GDParser::_parse_class(ClassNode *p_class) {
ClassNode *newclass = alloc_node<ClassNode>();
newclass->initializer = alloc_node<BlockNode>();
- newclass->initializer->parent_class=newclass;
+ newclass->initializer->parent_class = newclass;
newclass->ready = alloc_node<BlockNode>();
- newclass->ready->parent_class=newclass;
- newclass->name=name;
- newclass->owner=p_class;
+ newclass->ready->parent_class = newclass;
+ newclass->name = name;
+ newclass->owner = p_class;
p_class->subclasses.push_back(newclass);
-
- if (tokenizer->get_token()==GDTokenizer::TK_PR_EXTENDS) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PR_EXTENDS) {
_parse_extends(newclass);
if (error_set)
@@ -3049,9 +3005,9 @@ void GDParser::_parse_class(ClassNode *p_class) {
_set_error("Indented block expected.");
return;
}
- current_class=newclass;
+ current_class = newclass;
_parse_class(newclass);
- current_class=p_class;
+ current_class = p_class;
} break;
/* this is for functions....
@@ -3062,7 +3018,7 @@ void GDParser::_parse_class(ClassNode *p_class) {
*/
case GDTokenizer::TK_PR_STATIC: {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) {
_set_error("Expected 'func'.");
return;
@@ -3071,42 +3027,38 @@ void GDParser::_parse_class(ClassNode *p_class) {
}; //fallthrough to function
case GDTokenizer::TK_PR_FUNCTION: {
- bool _static=false;
- pending_newline=-1;
+ bool _static = false;
+ pending_newline = -1;
- if (tokenizer->get_token(-1)==GDTokenizer::TK_PR_STATIC) {
+ if (tokenizer->get_token(-1) == GDTokenizer::TK_PR_STATIC) {
- _static=true;
+ _static = true;
}
-
tokenizer->advance();
StringName name;
- if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC,name)) {
-
+ if (_get_completable_identifier(COMPLETION_VIRTUAL_FUNC, name)) {
}
-
- if (name==StringName()) {
+ if (name == StringName()) {
_set_error("Expected 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("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->functions[i]->line)+").");
+ for (int i = 0; i < p_class->functions.size(); i++) {
+ if (p_class->functions[i]->name == name) {
+ _set_error("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("Function '"+String(name)+"' already exists in this class (at line: "+itos(p_class->static_functions[i]->line)+").");
+ for (int i = 0; i < p_class->static_functions.size(); i++) {
+ if (p_class->static_functions[i]->name == name) {
+ _set_error("Function '" + String(name) + "' already exists in this class (at line: " + itos(p_class->static_functions[i]->line) + ").");
}
}
-
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after identifier (syntax: 'func <identifier>([arguments]):' ).");
return;
@@ -3115,39 +3067,37 @@ void GDParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
Vector<StringName> arguments;
- Vector<Node*> default_values;
+ Vector<Node *> default_values;
int fnline = tokenizer->get_token_line();
-
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
//has arguments
- bool defaulting=false;
- while(true) {
+ bool defaulting = false;
+ while (true) {
- if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
continue;
}
- if (tokenizer->get_token()==GDTokenizer::TK_PR_VAR) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PR_VAR) {
tokenizer->advance(); //var before the identifier is allowed
}
-
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier for argument.");
return;
}
- StringName argname=tokenizer->get_token_identifier();
+ StringName argname = tokenizer->get_token_identifier();
arguments.push_back(argname);
tokenizer->advance();
- if (defaulting && tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) {
+ if (defaulting && tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) {
_set_error("Default parameter expected.");
return;
@@ -3155,21 +3105,20 @@ void GDParser::_parse_class(ClassNode *p_class) {
//tokenizer->advance();
-
- if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) {
- defaulting=true;
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) {
+ defaulting = true;
tokenizer->advance(1);
- Node *defval=NULL;
+ Node *defval = NULL;
- defval=_parse_and_reduce_expression(p_class,_static);
+ defval = _parse_and_reduce_expression(p_class, _static);
if (!defval || error_set)
return;
OperatorNode *on = alloc_node<OperatorNode>();
- on->op=OperatorNode::OP_ASSIGN;
+ on->op = OperatorNode::OP_ASSIGN;
IdentifierNode *in = alloc_node<IdentifierNode>();
- in->name=argname;
+ in->name = argname;
on->arguments.push_back(in);
on->arguments.push_back(defval);
@@ -3182,14 +3131,14 @@ void GDParser::_parse_class(ClassNode *p_class) {
default_values.push_back(on);
}
- while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
continue;
- } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ',' or ')'.");
return;
@@ -3197,68 +3146,63 @@ void GDParser::_parse_class(ClassNode *p_class) {
break;
}
-
-
}
tokenizer->advance();
BlockNode *block = alloc_node<BlockNode>();
- block->parent_class=p_class;
+ block->parent_class = p_class;
- if (name=="_init") {
+ if (name == "_init") {
if (p_class->extends_used) {
OperatorNode *cparent = alloc_node<OperatorNode>();
- cparent->op=OperatorNode::OP_PARENT_CALL;
+ cparent->op = OperatorNode::OP_PARENT_CALL;
block->statements.push_back(cparent);
IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name="_init";
+ id->name = "_init";
cparent->arguments.push_back(id);
- if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_OPEN) {
_set_error("expected '(' for parent constructor arguments.");
}
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
//has arguments
- parenthesis ++;
- while(true) {
+ parenthesis++;
+ while (true) {
- Node *arg = _parse_and_reduce_expression(p_class,_static);
+ Node *arg = _parse_and_reduce_expression(p_class, _static);
cparent->arguments.push_back(arg);
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
continue;
- } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ',' or ')'.");
return;
}
break;
-
}
- parenthesis --;
+ parenthesis--;
}
tokenizer->advance();
}
} else {
-
- if (tokenizer->get_token()==GDTokenizer::TK_PERIOD) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PERIOD) {
_set_error("Parent constructor call found for a class without inheritance.");
return;
}
-
}
}
@@ -3269,34 +3213,32 @@ void GDParser::_parse_class(ClassNode *p_class) {
}
FunctionNode *function = alloc_node<FunctionNode>();
- function->name=name;
- function->arguments=arguments;
- function->default_values=default_values;
- function->_static=_static;
- function->line=fnline;
-
- function->rpc_mode=rpc_mode;
- rpc_mode=ScriptInstance::RPC_MODE_DISABLED;
+ function->name = name;
+ function->arguments = arguments;
+ function->default_values = default_values;
+ function->_static = _static;
+ function->line = fnline;
+ function->rpc_mode = rpc_mode;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
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=NULL;
+ current_function = function;
+ function->body = block;
+ current_block = block;
+ _parse_block(block, _static);
+ current_block = NULL;
//arguments
} break;
case GDTokenizer::TK_PR_SIGNAL: {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier after 'signal'.");
return;
}
@@ -3305,22 +3247,20 @@ void GDParser::_parse_class(ClassNode *p_class) {
sig.name = tokenizer->get_token_identifier();
tokenizer->advance();
-
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) {
tokenizer->advance();
- while(true) {
- if (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (true) {
+ if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
continue;
}
-
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
tokenizer->advance();
break;
}
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier in signal argument.");
return;
}
@@ -3328,13 +3268,13 @@ void GDParser::_parse_class(ClassNode *p_class) {
sig.arguments.push_back(tokenizer->get_token_identifier());
tokenizer->advance();
- while (tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
- } else if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ } else if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ',' or ')' after signal parameter identifier.");
return;
}
@@ -3352,33 +3292,33 @@ void GDParser::_parse_class(ClassNode *p_class) {
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_OPEN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_OPEN) {
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) {
Variant::Type type = tokenizer->get_token_type();
- if (type==Variant::NIL) {
+ if (type == Variant::NIL) {
_set_error("Can't export null type.");
return;
}
- current_export.type=type;
- current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE;
+ current_export.type = type;
+ current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
tokenizer->advance();
-
- String hint_prefix ="";
-
- if(type == Variant::ARRAY && tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+
+ String hint_prefix = "";
+
+ if (type == Variant::ARRAY && tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
- while(tokenizer->get_token()==GDTokenizer::TK_BUILT_IN_TYPE) {
+ while (tokenizer->get_token() == GDTokenizer::TK_BUILT_IN_TYPE) {
type = tokenizer->get_token_type();
-
+
tokenizer->advance();
- if(type == Variant::ARRAY) {
- hint_prefix += itos(Variant::ARRAY)+":";
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (type == Variant::ARRAY) {
+ hint_prefix += itos(Variant::ARRAY) + ":";
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
}
} else {
@@ -3387,56 +3327,54 @@ void GDParser::_parse_class(ClassNode *p_class) {
}
}
}
-
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
// hint expected next!
tokenizer->advance();
- switch(type) {
-
+ switch (type) {
case Variant::INT: {
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FLAGS") {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FLAGS") {
//current_export.hint=PROPERTY_HINT_ALL_FLAGS;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
break;
}
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA)
- {
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
_set_error("Expected ')' or ',' in bit flags hint.");
return;
}
- current_export.hint=PROPERTY_HINT_FLAGS;
+ current_export.hint = PROPERTY_HINT_FLAGS;
tokenizer->advance();
bool first = true;
- while(true) {
+ while (true) {
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) {
- current_export=PropertyInfo();
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
+ current_export = PropertyInfo();
_set_error("Expected a string constant in named bit flags hint.");
return;
}
String c = tokenizer->get_token_constant();
if (!first)
- current_export.hint_string+=",";
+ current_export.hint_string += ",";
else
- first=false;
+ first = false;
- current_export.hint_string+=c.xml_escape();
+ current_export.hint_string += c.xml_escape();
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
- current_export=PropertyInfo();
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
+ current_export = PropertyInfo();
_set_error("Expected ')' or ',' in named bit flags hint.");
return;
}
@@ -3446,39 +3384,38 @@ void GDParser::_parse_class(ClassNode *p_class) {
break;
}
- if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) {
//enumeration
- current_export.hint=PROPERTY_HINT_ENUM;
- bool first=true;
- while(true) {
+ current_export.hint = PROPERTY_HINT_ENUM;
+ bool first = true;
+ while (true) {
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected a string constant in enumeration hint.");
return;
}
String c = tokenizer->get_token_constant();
if (!first)
- current_export.hint_string+=",";
+ current_export.hint_string += ",";
else
- first=false;
+ first = false;
- current_export.hint_string+=c.xml_escape();
+ current_export.hint_string += c.xml_escape();
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
- current_export=PropertyInfo();
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
+ current_export = PropertyInfo();
_set_error("Expected ')' or ',' in enumeration hint.");
return;
}
tokenizer->advance();
-
}
break;
@@ -3487,10 +3424,10 @@ void GDParser::_parse_class(ClassNode *p_class) {
}; //fallthrough to use the same
case Variant::REAL: {
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EASE") {
- current_export.hint=PROPERTY_HINT_EXP_EASING;
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EASE") {
+ current_export.hint = PROPERTY_HINT_EXP_EASING;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in hint.");
return;
}
@@ -3498,146 +3435,143 @@ void GDParser::_parse_class(ClassNode *p_class) {
}
// range
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="EXP") {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "EXP") {
- current_export.hint=PROPERTY_HINT_EXP_RANGE;
+ current_export.hint = PROPERTY_HINT_EXP_RANGE;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- else if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
+ else if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
_set_error("Expected ')' or ',' in exponential range hint.");
return;
}
tokenizer->advance();
- }
- else
- current_export.hint=PROPERTY_HINT_RANGE;
+ } else
+ current_export.hint = PROPERTY_HINT_RANGE;
- float sign=1.0;
+ float sign = 1.0;
- if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) {
- sign=-1;
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) {
+ sign = -1;
tokenizer->advance();
}
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected a range in numeric hint.");
return;
-
}
- current_export.hint_string=rtos(sign*double(tokenizer->get_token_constant()));
+ current_export.hint_string = rtos(sign * double(tokenizer->get_token_constant()));
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE) {
- current_export.hint_string="0,"+current_export.hint_string;
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ current_export.hint_string = "0," + current_export.hint_string;
break;
}
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected ',' or ')' in numeric range hint.");
return;
}
tokenizer->advance();
- sign=1.0;
- if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) {
- sign=-1;
+ sign = 1.0;
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) {
+ sign = -1;
tokenizer->advance();
}
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected a number as upper bound in numeric range hint.");
return;
}
- current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant()));
+ current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant()));
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected ',' or ')' in numeric range hint.");
return;
}
tokenizer->advance();
- sign=1.0;
- if (tokenizer->get_token()==GDTokenizer::TK_OP_SUB) {
- sign=-1;
+ sign = 1.0;
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_SUB) {
+ sign = -1;
tokenizer->advance();
}
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || !tokenizer->get_token_constant().is_num()) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected a number as step in numeric range hint.");
return;
}
- current_export.hint_string+=","+rtos(sign*double(tokenizer->get_token_constant()));
+ current_export.hint_string += "," + rtos(sign * double(tokenizer->get_token_constant()));
tokenizer->advance();
} break;
case Variant::STRING: {
- if (tokenizer->get_token()==GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type()==Variant::STRING) {
+ if (tokenizer->get_token() == GDTokenizer::TK_CONSTANT && tokenizer->get_token_constant().get_type() == Variant::STRING) {
//enumeration
- current_export.hint=PROPERTY_HINT_ENUM;
- bool first=true;
- while(true) {
+ current_export.hint = PROPERTY_HINT_ENUM;
+ bool first = true;
+ while (true) {
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected a string constant in enumeration hint.");
return;
}
String c = tokenizer->get_token_constant();
if (!first)
- current_export.hint_string+=",";
+ current_export.hint_string += ",";
else
- first=false;
+ first = false;
- current_export.hint_string+=c.xml_escape();
+ current_export.hint_string += c.xml_escape();
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
- current_export=PropertyInfo();
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
+ current_export = PropertyInfo();
_set_error("Expected ')' or ',' in enumeration hint.");
return;
}
tokenizer->advance();
-
}
break;
}
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="DIR") {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "DIR") {
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
- current_export.hint=PROPERTY_HINT_DIR;
- else if (tokenizer->get_token()==GDTokenizer::TK_COMMA ) {
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
+ current_export.hint = PROPERTY_HINT_DIR;
+ else if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier()=="GLOBAL")) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER || !(tokenizer->get_token_identifier() == "GLOBAL")) {
_set_error("Expected 'GLOBAL' after comma in directory hint.");
return;
}
@@ -3645,42 +3579,41 @@ void GDParser::_parse_class(ClassNode *p_class) {
_set_error("Global filesystem hints may only be used in tool scripts.");
return;
}
- current_export.hint=PROPERTY_HINT_GLOBAL_DIR;
+ current_export.hint = PROPERTY_HINT_GLOBAL_DIR;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in hint.");
return;
}
- }
- else {
+ } else {
_set_error("Expected ')' or ',' in hint.");
return;
}
break;
}
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="FILE") {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "FILE") {
- current_export.hint=PROPERTY_HINT_FILE;
+ current_export.hint = PROPERTY_HINT_FILE;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="GLOBAL") {
+ if (tokenizer->get_token() == GDTokenizer::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;
+ current_export.hint = PROPERTY_HINT_GLOBAL_FILE;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_PARENTHESIS_CLOSE)
+ if (tokenizer->get_token() == GDTokenizer::TK_PARENTHESIS_CLOSE)
break;
- else if (tokenizer->get_token()==GDTokenizer::TK_COMMA)
+ else if (tokenizer->get_token() == GDTokenizer::TK_COMMA)
tokenizer->advance();
else {
_set_error("Expected ')' or ',' in hint.");
@@ -3688,31 +3621,30 @@ void GDParser::_parse_class(ClassNode *p_class) {
}
}
- if (tokenizer->get_token()!=GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type()!=Variant::STRING) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CONSTANT || tokenizer->get_token_constant().get_type() != Variant::STRING) {
- if (current_export.hint==PROPERTY_HINT_GLOBAL_FILE)
+ 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();
+ current_export.hint_string = tokenizer->get_token_constant();
tokenizer->advance();
-
}
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in hint.");
return;
}
break;
}
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier()=="MULTILINE") {
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER && tokenizer->get_token_identifier() == "MULTILINE") {
- current_export.hint=PROPERTY_HINT_MULTILINE_TEXT;
+ current_export.hint = PROPERTY_HINT_MULTILINE_TEXT;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in hint.");
return;
}
@@ -3721,20 +3653,20 @@ void GDParser::_parse_class(ClassNode *p_class) {
} break;
case Variant::COLOR: {
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER ) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
- current_export=PropertyInfo();
+ 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") {
+ if (identifier == "RGB") {
+ current_export.hint = PROPERTY_HINT_COLOR_NO_ALPHA;
+ } else if (identifier == "RGBA") {
//none
} else {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Color type hint expects RGB or RGBA as hints");
return;
}
@@ -3743,54 +3675,51 @@ void GDParser::_parse_class(ClassNode *p_class) {
} break;
default: {
- current_export=PropertyInfo();
- _set_error("Type '"+Variant::get_type_name(type)+"' can't take hints.");
+ current_export = PropertyInfo();
+ _set_error("Type '" + Variant::get_type_name(type) + "' can't take hints.");
return;
} break;
}
-
}
- if(current_export.type == Variant::ARRAY && !hint_prefix.empty()) {
- if(current_export.hint) {
- hint_prefix += "/"+itos(current_export.hint);
+ if (current_export.type == Variant::ARRAY && !hint_prefix.empty()) {
+ 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_NONE;
+ current_export.hint_string = hint_prefix + ":" + current_export.hint_string;
+ current_export.hint = PROPERTY_HINT_NONE;
}
- } else if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) {
+ } else if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) {
String identifier = tokenizer->get_token_identifier();
- if (!ClassDB::is_parent_class(identifier,"Resource")) {
+ if (!ClassDB::is_parent_class(identifier, "Resource")) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Export hint not a type or resource.");
}
- current_export.type=Variant::OBJECT;
- current_export.hint=PROPERTY_HINT_RESOURCE_TYPE;
- current_export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE;
+ current_export.type = Variant::OBJECT;
+ current_export.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ current_export.usage |= PROPERTY_USAGE_SCRIPT_VARIABLE;
- current_export.hint_string=identifier;
+ current_export.hint_string = identifier;
tokenizer->advance();
}
- if (tokenizer->get_token()!=GDTokenizer::TK_PARENTHESIS_CLOSE) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PARENTHESIS_CLOSE) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected ')' or ',' after export hint.");
return;
-
}
tokenizer->advance();
-
}
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_ONREADY && tokenizer->get_token()!=GDTokenizer::TK_PR_REMOTE && tokenizer->get_token()!=GDTokenizer::TK_PR_MASTER && tokenizer->get_token()!=GDTokenizer::TK_PR_SLAVE && tokenizer->get_token()!=GDTokenizer::TK_PR_SYNC) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_ONREADY && tokenizer->get_token() != GDTokenizer::TK_PR_REMOTE && tokenizer->get_token() != GDTokenizer::TK_PR_MASTER && tokenizer->get_token() != GDTokenizer::TK_PR_SLAVE && tokenizer->get_token() != GDTokenizer::TK_PR_SYNC) {
- current_export=PropertyInfo();
+ current_export = PropertyInfo();
_set_error("Expected 'var', 'onready', 'remote', 'master', 'slave' or 'sync'.");
return;
}
@@ -3801,7 +3730,7 @@ void GDParser::_parse_class(ClassNode *p_class) {
//may be fallthrough from export, ignore if so
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) {
_set_error("Expected 'var'.");
return;
}
@@ -3812,19 +3741,19 @@ void GDParser::_parse_class(ClassNode *p_class) {
//may be fallthrough from export, ignore if so
tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) {
+ if (current_export.type) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) {
_set_error("Expected 'var'.");
return;
}
} else {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) {
_set_error("Expected 'var' or 'func'.");
return;
}
}
- rpc_mode=ScriptInstance::RPC_MODE_REMOTE;
+ rpc_mode = ScriptInstance::RPC_MODE_REMOTE;
continue;
} break;
@@ -3832,47 +3761,47 @@ void GDParser::_parse_class(ClassNode *p_class) {
//may be fallthrough from export, ignore if so
tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) {
+ if (current_export.type) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) {
_set_error("Expected 'var'.");
return;
}
} else {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) {
_set_error("Expected 'var' or 'func'.");
return;
}
}
- rpc_mode=ScriptInstance::RPC_MODE_MASTER;
+ rpc_mode = ScriptInstance::RPC_MODE_MASTER;
continue;
} break;
case GDTokenizer::TK_PR_SLAVE: {
//may be fallthrough from export, ignore if so
tokenizer->advance();
- if (current_export.type) {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR) {
+ if (current_export.type) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR) {
_set_error("Expected 'var'.");
return;
}
} else {
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) {
_set_error("Expected 'var' or 'func'.");
return;
}
}
- rpc_mode=ScriptInstance::RPC_MODE_SLAVE;
+ rpc_mode = ScriptInstance::RPC_MODE_SLAVE;
continue;
} break;
case GDTokenizer::TK_PR_SYNC: {
//may be fallthrough from export, ignore if so
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_PR_VAR && tokenizer->get_token()!=GDTokenizer::TK_PR_FUNCTION) {
+ if (tokenizer->get_token() != GDTokenizer::TK_PR_VAR && tokenizer->get_token() != GDTokenizer::TK_PR_FUNCTION) {
if (current_export.type)
_set_error("Expected 'var'.");
else
@@ -3880,48 +3809,48 @@ void GDParser::_parse_class(ClassNode *p_class) {
return;
}
- rpc_mode=ScriptInstance::RPC_MODE_SYNC;
+ rpc_mode = ScriptInstance::RPC_MODE_SYNC;
continue;
} break;
case GDTokenizer::TK_PR_VAR: {
//variale declaration and (eventual) initialization
ClassNode::Member member;
- bool autoexport = tokenizer->get_token(-1)==GDTokenizer::TK_PR_EXPORT;
- if (current_export.type!=Variant::NIL) {
- member._export=current_export;
- current_export=PropertyInfo();
+ bool autoexport = tokenizer->get_token(-1) == GDTokenizer::TK_PR_EXPORT;
+ if (current_export.type != Variant::NIL) {
+ member._export = current_export;
+ current_export = PropertyInfo();
}
- bool onready = tokenizer->get_token(-1)==GDTokenizer::TK_PR_ONREADY;
+ bool onready = tokenizer->get_token(-1) == GDTokenizer::TK_PR_ONREADY;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier for member variable name.");
return;
}
- member.identifier=tokenizer->get_token_identifier();
- member.expression=NULL;
- member._export.name=member.identifier;
- member.line=tokenizer->get_token_line();
- member.rpc_mode=rpc_mode;
+ member.identifier = tokenizer->get_token_identifier();
+ member.expression = NULL;
+ member._export.name = member.identifier;
+ member.line = tokenizer->get_token_line();
+ member.rpc_mode = rpc_mode;
tokenizer->advance();
- rpc_mode=ScriptInstance::RPC_MODE_DISABLED;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
- if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) {
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) {
#ifdef DEBUG_ENABLED
int line = tokenizer->get_token_line();
#endif
tokenizer->advance();
- Node *subexpr=NULL;
+ Node *subexpr = NULL;
- subexpr = _parse_and_reduce_expression(p_class,false,autoexport);
+ subexpr = _parse_and_reduce_expression(p_class, false, autoexport);
if (!subexpr) {
if (_recover_from_completion()) {
break;
@@ -3930,24 +3859,23 @@ void GDParser::_parse_class(ClassNode *p_class) {
}
//discourage common error
- if (!onready && subexpr->type==Node::TYPE_OPERATOR) {
+ 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") {
+ 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");
+ _set_error("Use 'onready var " + String(member.identifier) + " = get_node(..)' instead");
return;
-
}
}
}
- member.expression=subexpr;
+ member.expression = subexpr;
if (autoexport) {
- if (1)/*(subexpr->type==Node::TYPE_ARRAY) {
+ if (1) /*(subexpr->type==Node::TYPE_ARRAY) {
member._export.type=Variant::ARRAY;
@@ -3957,54 +3885,53 @@ void GDParser::_parse_class(ClassNode *p_class) {
} else*/ {
- if (subexpr->type!=Node::TYPE_CONSTANT) {
+ 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) {
+ ConstantNode *cn = static_cast<ConstantNode *>(subexpr);
+ if (cn->value.get_type() == Variant::NIL) {
_set_error("Can't accept a null constant expression for infering export type.");
return;
}
- member._export.type=cn->value.get_type();
- member._export.usage|=PROPERTY_USAGE_SCRIPT_VARIABLE;
- if (cn->value.get_type()==Variant::OBJECT) {
+ 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 = obj->cast_to<Resource>();
- if(res==NULL) {
+ if (res == NULL) {
_set_error("Exported constant not a type or resource.");
return;
}
- member._export.hint=PROPERTY_HINT_RESOURCE_TYPE;
- member._export.hint_string=res->get_class();
+ 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) {
+ if (subexpr->type == Node::TYPE_CONSTANT && member._export.type != Variant::NIL) {
- ConstantNode *cn = static_cast<ConstantNode*>(subexpr);
- if (cn->value.get_type()!=Variant::NIL) {
- member.default_value=cn->value;
+ ConstantNode *cn = static_cast<ConstantNode *>(subexpr);
+ if (cn->value.get_type() != Variant::NIL) {
+ member.default_value = cn->value;
}
}
#endif
IdentifierNode *id = alloc_node<IdentifierNode>();
- id->name=member.identifier;
+ id->name = member.identifier;
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=OperatorNode::OP_INIT_ASSIGN;
+ op->op = OperatorNode::OP_INIT_ASSIGN;
op->arguments.push_back(id);
op->arguments.push_back(subexpr);
-
#ifdef DEBUG_ENABLED
NewLineNode *nl = alloc_node<NewLineNode>();
- nl->line=line;
+ nl->line = line;
if (onready)
p_class->ready->statements.push_back(nl);
else
@@ -4015,8 +3942,6 @@ void GDParser::_parse_class(ClassNode *p_class) {
else
p_class->initializer->statements.push_back(op);
-
-
} else {
if (autoexport) {
@@ -4024,36 +3949,33 @@ void GDParser::_parse_class(ClassNode *p_class) {
_set_error("Type-less export needs a constant expression assigned to infer type.");
return;
}
-
}
- if (tokenizer->get_token()==GDTokenizer::TK_PR_SETGET) {
-
+ if (tokenizer->get_token() == GDTokenizer::TK_PR_SETGET) {
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() != GDTokenizer::TK_COMMA) {
//just comma means using only getter
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier for setter function after 'notify'.");
}
- member.setter=tokenizer->get_token_identifier();
+ member.setter = tokenizer->get_token_identifier();
tokenizer->advance();
}
- if (tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
//there is a getter
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected identifier for getter function after ','.");
}
- member.getter=tokenizer->get_token_identifier();
+ member.getter = tokenizer->get_token_identifier();
tokenizer->advance();
-
}
}
@@ -4070,25 +3992,25 @@ void GDParser::_parse_class(ClassNode *p_class) {
ClassNode::Constant constant;
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
+ if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
_set_error("Expected name (identifier) for constant.");
return;
}
- constant.identifier=tokenizer->get_token_identifier();
+ constant.identifier = tokenizer->get_token_identifier();
tokenizer->advance();
- if (tokenizer->get_token()!=GDTokenizer::TK_OP_ASSIGN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_OP_ASSIGN) {
_set_error("Constant expects assignment.");
return;
}
tokenizer->advance();
- Node *subexpr=NULL;
+ Node *subexpr = NULL;
- subexpr = _parse_and_reduce_expression(p_class,true,true);
+ subexpr = _parse_and_reduce_expression(p_class, true, true);
if (!subexpr) {
if (_recover_from_completion()) {
break;
@@ -4096,10 +4018,10 @@ void GDParser::_parse_class(ClassNode *p_class) {
return;
}
- if (subexpr->type!=Node::TYPE_CONSTANT) {
+ if (subexpr->type != Node::TYPE_CONSTANT) {
_set_error("Expected constant expression");
}
- constant.expression=subexpr;
+ constant.expression = subexpr;
p_class->constant_expressions.push_back(constant);
@@ -4117,46 +4039,46 @@ void GDParser::_parse_class(ClassNode *p_class) {
Dictionary enum_dict;
tokenizer->advance();
- if (tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER) {
- enum_name=tokenizer->get_token_identifier();
+ if (tokenizer->get_token() == GDTokenizer::TK_IDENTIFIER) {
+ enum_name = tokenizer->get_token_identifier();
tokenizer->advance();
}
- if (tokenizer->get_token()!=GDTokenizer::TK_CURLY_BRACKET_OPEN) {
+ if (tokenizer->get_token() != GDTokenizer::TK_CURLY_BRACKET_OPEN) {
_set_error("Expected '{' in enum declaration");
return;
}
tokenizer->advance();
-
- while(true) {
- if(tokenizer->get_token()==GDTokenizer::TK_NEWLINE) {
-
+
+ while (true) {
+ if (tokenizer->get_token() == GDTokenizer::TK_NEWLINE) {
+
tokenizer->advance(); // Ignore newlines
- } else if (tokenizer->get_token()==GDTokenizer::TK_CURLY_BRACKET_CLOSE) {
-
+ } else if (tokenizer->get_token() == GDTokenizer::TK_CURLY_BRACKET_CLOSE) {
+
tokenizer->advance();
break; // End of enum
- } else if (tokenizer->get_token()!=GDTokenizer::TK_IDENTIFIER) {
-
- if(tokenizer->get_token()==GDTokenizer::TK_EOF) {
+ } else if (tokenizer->get_token() != GDTokenizer::TK_IDENTIFIER) {
+
+ if (tokenizer->get_token() == GDTokenizer::TK_EOF) {
_set_error("Unexpected end of file.");
} else {
_set_error(String("Unexpected ") + GDTokenizer::get_token_name(tokenizer->get_token()) + ", expected identifier");
}
-
+
return;
} else { // tokenizer->get_token()==GDTokenizer::TK_IDENTIFIER
ClassNode::Constant constant;
-
- constant.identifier=tokenizer->get_token_identifier();
-
+
+ constant.identifier = tokenizer->get_token_identifier();
+
tokenizer->advance();
-
- if (tokenizer->get_token()==GDTokenizer::TK_OP_ASSIGN) {
+
+ if (tokenizer->get_token() == GDTokenizer::TK_OP_ASSIGN) {
tokenizer->advance();
- Node *subexpr=NULL;
+ Node *subexpr = NULL;
- subexpr = _parse_and_reduce_expression(p_class,true,true);
+ subexpr = _parse_and_reduce_expression(p_class, true, true);
if (!subexpr) {
if (_recover_from_completion()) {
break;
@@ -4164,19 +4086,19 @@ void GDParser::_parse_class(ClassNode *p_class) {
return;
}
- if (subexpr->type!=Node::TYPE_CONSTANT) {
+ if (subexpr->type != Node::TYPE_CONSTANT) {
_set_error("Expected constant expression");
}
-
- const ConstantNode *subexpr_const = static_cast<const ConstantNode*>(subexpr);
-
- if(subexpr_const->value.get_type() != Variant::INT) {
+
+ const ConstantNode *subexpr_const = static_cast<const ConstantNode *>(subexpr);
+
+ if (subexpr_const->value.get_type() != Variant::INT) {
_set_error("Expected an int value for enum");
}
-
+
last_assign = subexpr_const->value;
-
- constant.expression=subexpr;
+
+ constant.expression = subexpr;
} else {
last_assign = last_assign + 1;
@@ -4184,27 +4106,26 @@ void GDParser::_parse_class(ClassNode *p_class) {
cn->value = last_assign;
constant.expression = cn;
}
-
- if(tokenizer->get_token()==GDTokenizer::TK_COMMA) {
+
+ if (tokenizer->get_token() == GDTokenizer::TK_COMMA) {
tokenizer->advance();
}
- if(enum_name != "") {
- const ConstantNode *cn = static_cast<const ConstantNode*>(constant.expression);
+ if (enum_name != "") {
+ const ConstantNode *cn = static_cast<const ConstantNode *>(constant.expression);
enum_dict[constant.identifier] = cn->value;
}
p_class->constant_expressions.push_back(constant);
}
-
}
-
- if(enum_name != "") {
+
+ if (enum_name != "") {
ClassNode::Constant enum_constant;
- enum_constant.identifier=enum_name;
+ enum_constant.identifier = enum_name;
ConstantNode *cn = alloc_node<ConstantNode>();
cn->value = enum_dict;
- enum_constant.expression=cn;
+ enum_constant.expression = cn;
p_class->constant_expressions.push_back(enum_constant);
}
@@ -4213,46 +4134,37 @@ void GDParser::_parse_class(ClassNode *p_class) {
return;
}
-
-
-
} break;
-
+
case GDTokenizer::TK_CONSTANT: {
- if(tokenizer->get_token_constant().get_type() == Variant::STRING) {
+ 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()));
+ _set_error(String() + "Unexpected constant of type: " + Variant::get_type_name(tokenizer->get_token_constant().get_type()));
return;
}
} break;
default: {
- _set_error(String()+"Unexpected token: "+tokenizer->get_token_name(tokenizer->get_token())+":"+tokenizer->get_token_identifier());
+ _set_error(String() + "Unexpected token: " + tokenizer->get_token_name(tokenizer->get_token()) + ":" + tokenizer->get_token_identifier());
return;
} break;
-
}
-
}
-
-
}
-
-void GDParser::_set_error(const String& p_error, int p_line, int p_column) {
-
+void GDParser::_set_error(const String &p_error, int p_line, int p_column) {
if (error_set)
return; //allow no further errors
- 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;
+ 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;
}
String GDParser::get_error() const {
@@ -4269,27 +4181,25 @@ int GDParser::get_error_column() const {
return error_column;
}
+Error GDParser::_parse(const String &p_base_path) {
-Error GDParser::_parse(const String& p_base_path) {
-
-
- base_path=p_base_path;
+ base_path = p_base_path;
clear();
//assume class
ClassNode *main_class = alloc_node<ClassNode>();
main_class->initializer = alloc_node<BlockNode>();
- main_class->initializer->parent_class=main_class;
+ main_class->initializer->parent_class = main_class;
main_class->ready = alloc_node<BlockNode>();
- main_class->ready->parent_class=main_class;
- current_class=main_class;
+ main_class->ready->parent_class = main_class;
+ current_class = main_class;
_parse_class(main_class);
- if (tokenizer->get_token()==GDTokenizer::TK_ERROR) {
- error_set=false;
- _set_error("Parse Error: "+tokenizer->get_token_error());
+ if (tokenizer->get_token() == GDTokenizer::TK_ERROR) {
+ error_set = false;
+ _set_error("Parse Error: " + tokenizer->get_token_error());
}
if (error_set) {
@@ -4299,60 +4209,59 @@ Error GDParser::_parse(const String& p_base_path) {
return OK;
}
-Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path, const String &p_self_path) {
-
- for_completion=false;
- validating=false;
- completion_type=COMPLETION_NONE;
- completion_node=NULL;
- completion_class=NULL;
- completion_function=NULL;
- completion_block=NULL;
- completion_found=false;
- current_block=NULL;
- current_class=NULL;
- current_function=NULL;
-
- self_path=p_self_path;
- GDTokenizerBuffer *tb = memnew( GDTokenizerBuffer );
+Error GDParser::parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path, const String &p_self_path) {
+
+ for_completion = false;
+ validating = false;
+ completion_type = COMPLETION_NONE;
+ completion_node = NULL;
+ completion_class = NULL;
+ completion_function = NULL;
+ completion_block = NULL;
+ completion_found = false;
+ current_block = NULL;
+ current_class = NULL;
+ current_function = NULL;
+
+ self_path = p_self_path;
+ GDTokenizerBuffer *tb = memnew(GDTokenizerBuffer);
tb->set_code_buffer(p_bytecode);
- tokenizer=tb;
+ tokenizer = tb;
Error ret = _parse(p_base_path);
memdelete(tb);
- tokenizer=NULL;
+ tokenizer = NULL;
return ret;
}
+Error GDParser::parse(const String &p_code, const String &p_base_path, bool p_just_validate, const String &p_self_path, bool p_for_completion) {
-Error GDParser::parse(const String& p_code, const String& p_base_path, bool p_just_validate, const String &p_self_path,bool p_for_completion) {
-
- completion_type=COMPLETION_NONE;
- completion_node=NULL;
- completion_class=NULL;
- completion_function=NULL;
- completion_block=NULL;
- completion_found=false;
- current_block=NULL;
- current_class=NULL;
+ completion_type = COMPLETION_NONE;
+ completion_node = NULL;
+ completion_class = NULL;
+ completion_function = NULL;
+ completion_block = NULL;
+ completion_found = false;
+ current_block = NULL;
+ current_class = NULL;
- current_function=NULL;
+ current_function = NULL;
- self_path=p_self_path;
- GDTokenizerText *tt = memnew( GDTokenizerText );
+ self_path = p_self_path;
+ GDTokenizerText *tt = memnew(GDTokenizerText);
tt->set_code(p_code);
- validating=p_just_validate;
- for_completion=p_for_completion;
- tokenizer=tt;
+ validating = p_just_validate;
+ for_completion = p_for_completion;
+ tokenizer = tt;
Error ret = _parse(p_base_path);
memdelete(tt);
- tokenizer=NULL;
+ tokenizer = NULL;
return ret;
}
bool GDParser::is_tool_script() const {
- return (head && head->type==Node::TYPE_CLASS && static_cast<const ClassNode*>(head)->tool);
+ return (head && head->type == Node::TYPE_CLASS && static_cast<const ClassNode *>(head)->tool);
}
const GDParser::Node *GDParser::get_parse_tree() const {
@@ -4362,44 +4271,42 @@ const GDParser::Node *GDParser::get_parse_tree() const {
void GDParser::clear() {
- while(list) {
+ while (list) {
- Node *l=list;
- list=list->next;
+ Node *l = list;
+ list = list->next;
memdelete(l);
}
- head=NULL;
- list=NULL;
+ head = NULL;
+ list = NULL;
- completion_type=COMPLETION_NONE;
- completion_node=NULL;
- completion_class=NULL;
- completion_function=NULL;
- completion_block=NULL;
- current_block=NULL;
- current_class=NULL;
+ completion_type = COMPLETION_NONE;
+ completion_node = NULL;
+ completion_class = NULL;
+ completion_function = NULL;
+ completion_block = NULL;
+ current_block = NULL;
+ current_class = NULL;
- completion_found=false;
- rpc_mode=ScriptInstance::RPC_MODE_DISABLED;
+ completion_found = false;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
- current_function=NULL;
+ current_function = NULL;
- validating=false;
- for_completion=false;
- error_set=false;
+ validating = false;
+ for_completion = false;
+ error_set = false;
tab_level.clear();
tab_level.push_back(0);
- error_line=0;
- error_column=0;
- pending_newline=-1;
- parenthesis=0;
- current_export.type=Variant::NIL;
- error="";
-
+ error_line = 0;
+ error_column = 0;
+ pending_newline = -1;
+ parenthesis = 0;
+ current_export.type = Variant::NIL;
+ error = "";
}
-
GDParser::CompletionType GDParser::get_completion_type() {
return completion_type;
@@ -4415,12 +4322,12 @@ int GDParser::get_completion_line() {
return completion_line;
}
-Variant::Type GDParser::get_completion_built_in_constant(){
+Variant::Type GDParser::get_completion_built_in_constant() {
return completion_built_in_constant;
}
-GDParser::Node *GDParser::get_completion_node(){
+GDParser::Node *GDParser::get_completion_node() {
return completion_node;
}
@@ -4430,12 +4337,12 @@ GDParser::BlockNode *GDParser::get_completion_block() {
return completion_block;
}
-GDParser::ClassNode *GDParser::get_completion_class(){
+GDParser::ClassNode *GDParser::get_completion_class() {
return completion_class;
}
-GDParser::FunctionNode *GDParser::get_completion_function(){
+GDParser::FunctionNode *GDParser::get_completion_function() {
return completion_function;
}
@@ -4452,12 +4359,11 @@ int GDParser::get_completion_identifier_is_function() {
GDParser::GDParser() {
- head=NULL;
- list=NULL;
- tokenizer=NULL;
- pending_newline=-1;
+ head = NULL;
+ list = NULL;
+ tokenizer = NULL;
+ pending_newline = -1;
clear();
-
}
GDParser::~GDParser() {
diff --git a/modules/gdscript/gd_parser.h b/modules/gdscript/gd_parser.h
index 7968bf85df..8d2c136818 100644
--- a/modules/gdscript/gd_parser.h
+++ b/modules/gdscript/gd_parser.h
@@ -29,15 +29,14 @@
#ifndef GD_PARSER_H
#define GD_PARSER_H
-#include "gd_tokenizer.h"
#include "gd_functions.h"
+#include "gd_tokenizer.h"
#include "map.h"
#include "object.h"
#include "script_language.h"
class GDParser {
public:
-
struct Node {
enum Type {
@@ -59,7 +58,7 @@ public:
TYPE_NEWLINE,
};
- Node * next;
+ Node *next;
int line;
int column;
Type type;
@@ -78,7 +77,6 @@ public:
StringName extends_file;
Vector<StringName> extends_class;
-
struct Member {
PropertyInfo _export;
#ifdef TOOLS_ENABLED
@@ -101,11 +99,11 @@ public:
Vector<StringName> arguments;
};
- Vector<ClassNode*> subclasses;
+ Vector<ClassNode *> subclasses;
Vector<Member> variables;
Vector<Constant> constant_expressions;
- Vector<FunctionNode*> functions;
- Vector<FunctionNode*> static_functions;
+ Vector<FunctionNode *> functions;
+ Vector<FunctionNode *> static_functions;
Vector<Signal> _signals;
BlockNode *initializer;
BlockNode *ready;
@@ -113,74 +111,88 @@ public:
//Vector<Node*> initializers;
int end_line;
- ClassNode() { tool=false; type=TYPE_CLASS; extends_used=false; end_line=-1; owner=NULL;}
+ ClassNode() {
+ tool = false;
+ type = TYPE_CLASS;
+ extends_used = false;
+ end_line = -1;
+ owner = NULL;
+ }
};
-
-
struct FunctionNode : public Node {
bool _static;
ScriptInstance::RPCMode rpc_mode;
StringName name;
Vector<StringName> arguments;
- Vector<Node*> default_values;
+ Vector<Node *> default_values;
BlockNode *body;
- FunctionNode() { type=TYPE_FUNCTION; _static=false; rpc_mode=ScriptInstance::RPC_MODE_DISABLED; }
-
+ FunctionNode() {
+ type = TYPE_FUNCTION;
+ _static = false;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
+ }
};
struct BlockNode : public Node {
ClassNode *parent_class;
BlockNode *parent_block;
- Map<StringName,int> locals;
- List<Node*> statements;
+ Map<StringName, int> locals;
+ List<Node *> statements;
Vector<StringName> variables;
Vector<int> variable_lines;
//the following is useful for code completion
- List<BlockNode*> sub_blocks;
+ List<BlockNode *> sub_blocks;
int end_line;
- BlockNode() { type=TYPE_BLOCK; end_line=-1; parent_block=NULL; parent_class=NULL; }
+ BlockNode() {
+ type = TYPE_BLOCK;
+ end_line = -1;
+ parent_block = NULL;
+ parent_class = NULL;
+ }
};
struct TypeNode : public Node {
Variant::Type vtype;
- TypeNode() { type=TYPE_TYPE; }
+ TypeNode() { type = TYPE_TYPE; }
};
struct BuiltInFunctionNode : public Node {
GDFunctions::Function function;
- BuiltInFunctionNode() { type=TYPE_BUILT_IN_FUNCTION; }
+ BuiltInFunctionNode() { type = TYPE_BUILT_IN_FUNCTION; }
};
struct IdentifierNode : public Node {
StringName name;
- IdentifierNode() { type=TYPE_IDENTIFIER; }
+ IdentifierNode() { type = TYPE_IDENTIFIER; }
};
struct LocalVarNode : public Node {
StringName name;
Node *assign;
- LocalVarNode() { type=TYPE_LOCAL_VAR; assign=NULL;}
+ LocalVarNode() {
+ type = TYPE_LOCAL_VAR;
+ assign = NULL;
+ }
};
struct ConstantNode : public Node {
Variant value;
- ConstantNode() { type=TYPE_CONSTANT; }
+ ConstantNode() { type = TYPE_CONSTANT; }
};
struct ArrayNode : public Node {
- Vector<Node*> elements;
- ArrayNode() { type=TYPE_ARRAY; }
+ Vector<Node *> elements;
+ ArrayNode() { type = TYPE_ARRAY; }
};
-
struct DictionaryNode : public Node {
struct Pair {
@@ -190,11 +202,11 @@ public:
};
Vector<Pair> elements;
- DictionaryNode() { type=TYPE_DICTIONARY; }
+ DictionaryNode() { type = TYPE_DICTIONARY; }
};
struct SelfNode : public Node {
- SelfNode() { type=TYPE_SELF; }
+ SelfNode() { type = TYPE_SELF; }
};
struct OperatorNode : public Node {
@@ -255,13 +267,12 @@ public:
Operator op;
- Vector<Node*> arguments;
- OperatorNode() { type=TYPE_OPERATOR; }
+ Vector<Node *> arguments;
+ OperatorNode() { type = TYPE_OPERATOR; }
};
-
-
+
struct PatternNode : public Node {
-
+
enum PatternType {
PT_CONSTANT,
PT_BIND,
@@ -270,30 +281,29 @@ public:
PT_IGNORE_REST,
PT_WILDCARD
};
-
+
PatternType pt_type;
-
+
Node *constant;
StringName bind;
- Map<ConstantNode*, PatternNode*> dictionary;
- Vector<PatternNode*> array;
-
+ Map<ConstantNode *, PatternNode *> dictionary;
+ Vector<PatternNode *> array;
};
-
+
struct PatternBranchNode : public Node {
- Vector<PatternNode*> patterns;
+ Vector<PatternNode *> patterns;
BlockNode *body;
};
-
+
struct MatchNode : public Node {
Node *val_to_match;
- Vector<PatternBranchNode*> branches;
-
+ Vector<PatternBranchNode *> branches;
+
struct CompiledPatternBranch {
Node *compiled_pattern;
BlockNode *body;
};
-
+
Vector<CompiledPatternBranch> compiled_pattern_branches;
};
@@ -310,30 +320,34 @@ public:
};
CFType cf_type;
- Vector<Node*> arguments;
+ Vector<Node *> arguments;
BlockNode *body;
BlockNode *body_else;
-
+
MatchNode *match;
ControlFlowNode *_else; //used for if
- ControlFlowNode() { type=TYPE_CONTROL_FLOW; cf_type=CF_IF; body=NULL; body_else=NULL;}
+ ControlFlowNode() {
+ type = TYPE_CONTROL_FLOW;
+ cf_type = CF_IF;
+ body = NULL;
+ body_else = NULL;
+ }
};
struct AssertNode : public Node {
- Node* condition;
- AssertNode() { type=TYPE_ASSERT; }
+ Node *condition;
+ AssertNode() { type = TYPE_ASSERT; }
};
struct BreakpointNode : public Node {
- BreakpointNode() { type=TYPE_BREAKPOINT; }
+ BreakpointNode() { type = TYPE_BREAKPOINT; }
};
struct NewLineNode : public Node {
- NewLineNode() { type=TYPE_NEWLINE; }
+ NewLineNode() { type = TYPE_NEWLINE; }
};
-
struct Expression {
bool is_op;
@@ -343,8 +357,7 @@ public:
};
};
-
-/*
+ /*
struct OperatorNode : public Node {
DataType return_cache;
@@ -428,18 +441,13 @@ public:
COMPLETION_YIELD,
};
-
-
private:
-
-
GDTokenizer *tokenizer;
-
Node *head;
Node *list;
- template<class T>
- T* alloc_node();
+ template <class T>
+ T *alloc_node();
bool validating;
bool for_completion;
@@ -456,12 +464,11 @@ private:
String base_path;
String self_path;
-
ClassNode *current_class;
FunctionNode *current_function;
BlockNode *current_block;
- bool _get_completable_identifier(CompletionType p_type,StringName& identifier);
+ bool _get_completable_identifier(CompletionType p_type, StringName &identifier);
void _make_completable_call(int p_arg);
CompletionType completion_type;
@@ -481,41 +488,34 @@ private:
ScriptInstance::RPCMode rpc_mode;
-
- void _set_error(const String& p_error, int p_line=-1, int p_column=-1);
+ void _set_error(const String &p_error, int p_line = -1, int p_column = -1);
bool _recover_from_completion();
-
- bool _parse_arguments(Node* p_parent, Vector<Node*>& p_args, bool p_static, bool p_can_codecomplete=false);
- bool _enter_indent_block(BlockNode *p_block=NULL);
+ bool _parse_arguments(Node *p_parent, Vector<Node *> &p_args, bool p_static, bool p_can_codecomplete = false);
+ bool _enter_indent_block(BlockNode *p_block = NULL);
bool _parse_newline();
- Node* _parse_expression(Node *p_parent, bool p_static, bool p_allow_assign=false, bool p_parsing_constant=false);
- 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);
+ 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);
-
-
-
PatternNode *_parse_pattern(bool p_static);
- void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode*> &p_branches, bool p_static);
+ void _parse_pattern_block(BlockNode *p_block, Vector<PatternBranchNode *> &p_branches, bool p_static);
void _transform_match_statment(BlockNode *p_block, 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 _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();
- Error _parse(const String& p_base_path);
+ Error _parse(const String &p_base_path);
public:
-
String get_error() const;
int get_error_line() const;
int get_error_column() const;
- 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);
- Error parse_bytecode(const Vector<uint8_t> &p_bytecode,const String& p_base_path="",const String& p_self_path="");
+ 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);
+ Error parse_bytecode(const Vector<uint8_t> &p_bytecode, const String &p_base_path = "", const String &p_self_path = "");
bool is_tool_script() const;
const Node *get_parse_tree() const;
diff --git a/modules/gdscript/gd_script.cpp b/modules/gdscript/gd_script.cpp
index 4e72bc39a4..e1cc75acfc 100644
--- a/modules/gdscript/gd_script.cpp
+++ b/modules/gdscript/gd_script.cpp
@@ -27,18 +27,18 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "gd_script.h"
+#include "gd_compiler.h"
#include "global_config.h"
#include "global_constants.h"
-#include "gd_compiler.h"
-#include "os/file_access.h"
#include "io/file_access_encrypted.h"
+#include "os/file_access.h"
#include "os/os.h"
///////////////////////////
-GDNativeClass::GDNativeClass(const StringName& p_name) {
+GDNativeClass::GDNativeClass(const StringName &p_name) {
- name=p_name;
+ name = p_name;
}
/*void GDNativeClass::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount){
@@ -46,33 +46,30 @@ GDNativeClass::GDNativeClass(const StringName& p_name) {
}*/
-
-bool GDNativeClass::_get(const StringName& p_name,Variant &r_ret) const {
+bool GDNativeClass::_get(const StringName &p_name, Variant &r_ret) const {
bool ok;
int v = ClassDB::get_integer_constant(name, p_name, &ok);
if (ok) {
- r_ret=v;
+ r_ret = v;
return true;
} else {
return false;
}
}
-
void GDNativeClass::_bind_methods() {
- ClassDB::bind_method(D_METHOD("new"),&GDNativeClass::_new);
-
+ ClassDB::bind_method(D_METHOD("new"), &GDNativeClass::_new);
}
Variant GDNativeClass::_new() {
Object *o = instance();
if (!o) {
- ERR_EXPLAIN("Class type: '"+String(name)+"' is not instantiable.");
- ERR_FAIL_COND_V(!o,Variant());
+ ERR_EXPLAIN("Class type: '" + String(name) + "' is not instantiable.");
+ ERR_FAIL_COND_V(!o, Variant());
}
Reference *ref = o->cast_to<Reference>();
@@ -81,7 +78,6 @@ Variant GDNativeClass::_new() {
} else {
return o;
}
-
}
Object *GDNativeClass::instance() {
@@ -89,27 +85,24 @@ Object *GDNativeClass::instance() {
return ClassDB::instance(name);
}
-
-
-GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError& r_error) {
-
+GDInstance *GDScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error) {
/* STEP 1, CREATE */
- GDInstance* instance = memnew( GDInstance );
- instance->base_ref=p_isref;
+ GDInstance *instance = memnew(GDInstance);
+ instance->base_ref = p_isref;
instance->members.resize(member_indices.size());
- instance->script=Ref<GDScript>(this);
- instance->owner=p_owner;
+ instance->script = Ref<GDScript>(this);
+ instance->owner = p_owner;
#ifdef DEBUG_ENABLED
//needed for hot reloading
- for(Map<StringName,MemberInfo>::Element *E=member_indices.front();E;E=E->next()) {
- instance->member_indices_cache[E->key()]=E->get().index;
+ for (Map<StringName, MemberInfo>::Element *E = member_indices.front(); E; E = E->next()) {
+ instance->member_indices_cache[E->key()] = E->get().index;
}
#endif
instance->owner->set_script_instance(instance);
- /* STEP 2, INITIALIZE AND CONSRTUCT */
+/* STEP 2, INITIALIZE AND CONSRTUCT */
#ifndef NO_THREADS
GDScriptLanguage::singleton->lock->lock();
@@ -121,10 +114,10 @@ GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Obj
GDScriptLanguage::singleton->lock->unlock();
#endif
- initializer->call(instance,p_args,p_argcount,r_error);
+ initializer->call(instance, p_args, p_argcount, r_error);
- if (r_error.error!=Variant::CallError::CALL_OK) {
- instance->script=Ref<GDScript>();
+ if (r_error.error != Variant::CallError::CALL_OK) {
+ instance->script = Ref<GDScript>();
instance->owner->set_script_instance(NULL);
#ifndef NO_THREADS
GDScriptLanguage::singleton->lock->lock();
@@ -134,47 +127,45 @@ GDInstance* GDScript::_create_instance(const Variant** p_args,int p_argcount,Obj
GDScriptLanguage::singleton->lock->unlock();
#endif
- ERR_FAIL_COND_V(r_error.error!=Variant::CallError::CALL_OK, NULL); //error constructing
+ ERR_FAIL_COND_V(r_error.error != Variant::CallError::CALL_OK, NULL); //error constructing
}
//@TODO make thread safe
return instance;
-
}
-Variant GDScript::_new(const Variant** p_args,int p_argcount,Variant::CallError& r_error) {
+Variant GDScript::_new(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
/* STEP 1, CREATE */
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
REF ref;
- Object *owner=NULL;
+ Object *owner = NULL;
- GDScript *_baseptr=this;
+ GDScript *_baseptr = this;
while (_baseptr->_base) {
- _baseptr=_baseptr->_base;
+ _baseptr = _baseptr->_base;
}
ERR_FAIL_COND_V(_baseptr->native.is_null(), Variant());
if (_baseptr->native.ptr()) {
- owner=_baseptr->native->instance();
+ owner = _baseptr->native->instance();
} else {
- owner=memnew( Reference ); //by default, no base means use reference
+ owner = memnew(Reference); //by default, no base means use reference
}
- Reference *r=owner->cast_to<Reference>();
+ Reference *r = owner->cast_to<Reference>();
if (r) {
- ref=REF(r);
+ ref = REF(r);
}
-
- GDInstance* instance = _create_instance(p_args,p_argcount,owner,r!=NULL,r_error);
+ GDInstance *instance = _create_instance(p_args, p_argcount, owner, r != NULL, r_error);
if (!instance) {
if (ref.is_null()) {
memdelete(owner); //no owner, sorry
@@ -193,13 +184,12 @@ bool GDScript::can_instance() const {
//return valid; //any script in GDscript can instance
return valid || (!tool && !ScriptServer::is_scripting_enabled());
-
}
Ref<Script> GDScript::get_base_script() const {
if (_base) {
- return Ref<GDScript>( _base );
+ return Ref<GDScript>(_base);
} else {
return Ref<Script>();
}
@@ -218,14 +208,11 @@ struct _GDScriptMemberSort {
int index;
StringName name;
- _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort& p_member) const { return index < p_member.index; }
-
+ _FORCE_INLINE_ bool operator<(const _GDScriptMemberSort &p_member) const { return index < p_member.index; }
};
-
#ifdef TOOLS_ENABLED
-
void GDScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
placeholders.erase(p_placeholder);
@@ -275,86 +262,80 @@ void GDScript::_update_placeholder(PlaceHolderScriptInstance *p_placeholder) {
}*/
#endif
-
void GDScript::get_script_method_list(List<MethodInfo> *p_list) const {
- for (const Map<StringName,GDFunction*>::Element *E=member_functions.front();E;E=E->next()) {
+ for (const Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
MethodInfo mi;
- mi.name=E->key();
- for(int i=0;i<E->get()->get_argument_count();i++) {
+ mi.name = E->key();
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
PropertyInfo arg;
- arg.type=Variant::NIL; //variant
- arg.name=E->get()->get_argument_name(i);
+ arg.type = Variant::NIL; //variant
+ arg.name = E->get()->get_argument_name(i);
mi.arguments.push_back(arg);
}
- mi.return_val.name="Variant";
+ mi.return_val.name = "Variant";
p_list->push_back(mi);
}
}
void GDScript::get_script_property_list(List<PropertyInfo> *p_list) const {
- const GDScript *sptr=this;
+ const GDScript *sptr = this;
List<PropertyInfo> props;
- while(sptr) {
+ while (sptr) {
Vector<_GDScriptMemberSort> msort;
- for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
+ 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;
- ms.name=E->key();
+ ms.index = sptr->member_indices[E->key()].index;
+ ms.name = E->key();
msort.push_back(ms);
-
}
msort.sort();
msort.invert();
- for(int i=0;i<msort.size();i++) {
+ for (int i = 0; i < msort.size(); i++) {
props.push_front(sptr->member_info[msort[i].name]);
-
}
sptr = sptr->_base;
}
- for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
-
}
-bool GDScript::has_method(const StringName& p_method) const {
+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 {
+MethodInfo GDScript::get_method_info(const StringName &p_method) const {
- const Map<StringName,GDFunction*>::Element *E=member_functions.find(p_method);
+ const Map<StringName, GDFunction *>::Element *E = member_functions.find(p_method);
if (!E)
return MethodInfo();
MethodInfo mi;
- mi.name=E->key();
- for(int i=0;i<E->get()->get_argument_count();i++) {
+ mi.name = E->key();
+ for (int i = 0; i < E->get()->get_argument_count(); i++) {
PropertyInfo arg;
- arg.type=Variant::NIL; //variant
- arg.name=E->get()->get_argument_name(i);
+ arg.type = Variant::NIL; //variant
+ arg.name = E->get()->get_argument_name(i);
mi.arguments.push_back(arg);
}
- mi.return_val.name="Variant";
+ mi.return_val.name = "Variant";
return mi;
-
}
-
-bool GDScript::get_property_default_value(const StringName& p_property, Variant &r_value) const {
+bool GDScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
#ifdef TOOLS_ENABLED
@@ -363,26 +344,23 @@ bool GDScript::get_property_default_value(const StringName& p_property, Variant
print_line("\t"+String(String(I->key())+":"+String(I->get())));
}
*/
- const Map<StringName,Variant>::Element *E=member_default_values_cache.find(p_property);
+ const Map<StringName, Variant>::Element *E = member_default_values_cache.find(p_property);
if (E) {
- r_value=E->get();
+ r_value = E->get();
return true;
}
if (base_cache.is_valid()) {
- return base_cache->get_property_default_value(p_property,r_value);
+ return base_cache->get_property_default_value(p_property, r_value);
}
#endif
return false;
-
}
-ScriptInstance* GDScript::instance_create(Object *p_this) {
-
+ScriptInstance *GDScript::instance_create(Object *p_this) {
if (!tool && !ScriptServer::is_scripting_enabled()) {
-
#ifdef TOOLS_ENABLED
//instance a fake script for editing the values
@@ -392,7 +370,7 @@ ScriptInstance* GDScript::instance_create(Object *p_this) {
for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
print_line(E->get().name);
}*/
- PlaceHolderScriptInstance *si = memnew( PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(),Ref<Script>(this),p_this) );
+ PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(GDScriptLanguage::get_singleton(), Ref<Script>(this), p_this));
placeholders.insert(si);
//_update_placeholder(si);
_update_exports();
@@ -402,32 +380,30 @@ ScriptInstance* GDScript::instance_create(Object *p_this) {
#endif
}
- GDScript *top=this;
- while(top->_base)
- top=top->_base;
+ GDScript *top = this;
+ 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 (!ClassDB::is_parent_class(p_this->get_class_name(), top->native->get_name())) {
if (ScriptDebugger::get_singleton()) {
- GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),0,"Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_class()+"'");
+ GDScriptLanguage::get_singleton()->debug_break_parse(get_path(), 0, "Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
}
- ERR_EXPLAIN("Script inherits from native type '"+String(top->native->get_name())+"', so it can't be instanced in object of type: '"+p_this->get_class()+"'");
+ ERR_EXPLAIN("Script inherits from native type '" + String(top->native->get_name()) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
ERR_FAIL_V(NULL);
-
}
}
Variant::CallError unchecked_error;
- return _create_instance(NULL,0,p_this,p_this->cast_to<Reference>(),unchecked_error);
-
+ return _create_instance(NULL, 0, p_this, p_this->cast_to<Reference>(), unchecked_error);
}
bool GDScript::instance_has(const Object *p_this) const {
#ifndef NO_THREADS
GDScriptLanguage::singleton->lock->lock();
#endif
- bool hasit = instances.has((Object*)p_this);
+ bool hasit = instances.has((Object *)p_this);
#ifndef NO_THREADS
GDScriptLanguage::singleton->lock->unlock();
@@ -438,39 +414,37 @@ bool GDScript::instance_has(const Object *p_this) const {
bool GDScript::has_source_code() const {
- return source!="";
+ return source != "";
}
String GDScript::get_source_code() const {
return source;
}
-void GDScript::set_source_code(const String& p_code) {
+void GDScript::set_source_code(const String &p_code) {
- if (source==p_code)
+ if (source == p_code)
return;
- source=p_code;
+ source = p_code;
#ifdef TOOLS_ENABLED
- source_changed_cache=true;
- //print_line("SC CHANGED "+get_path());
+ source_changed_cache = true;
+//print_line("SC CHANGED "+get_path());
#endif
-
}
#ifdef TOOLS_ENABLED
-void GDScript::_update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames) {
+void GDScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
if (base_cache.is_valid()) {
- base_cache->_update_exports_values(values,propnames);
+ base_cache->_update_exports_values(values, propnames);
}
- for(Map<StringName,Variant>::Element *E=member_default_values_cache.front();E;E=E->next()) {
- values[E->key()]=E->get();
+ for (Map<StringName, Variant>::Element *E = member_default_values_cache.front(); E; E = E->next()) {
+ values[E->key()] = E->get();
}
- for (List<PropertyInfo>::Element *E=members_cache.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = members_cache.front(); E; E = E->next()) {
propnames.push_back(E->get());
}
-
}
#endif
@@ -478,90 +452,87 @@ bool GDScript::_update_exports() {
#ifdef TOOLS_ENABLED
- bool changed=false;
+ bool changed = false;
if (source_changed_cache) {
//print_line("updating source for "+get_path());
- source_changed_cache=false;
- changed=true;
+ source_changed_cache = false;
+ changed = true;
- String basedir=path;
+ String basedir = path;
- if (basedir=="")
- basedir=get_path();
+ if (basedir == "")
+ basedir = get_path();
- if (basedir!="")
- basedir=basedir.get_base_dir();
+ if (basedir != "")
+ basedir = basedir.get_base_dir();
GDParser parser;
- Error err = parser.parse(source,basedir,true,path);
+ Error err = parser.parse(source, basedir, true, path);
- if (err==OK) {
+ if (err == OK) {
- const GDParser::Node* root = parser.get_parse_tree();
- ERR_FAIL_COND_V(root->type!=GDParser::Node::TYPE_CLASS,false);
+ const GDParser::Node *root = parser.get_parse_tree();
+ ERR_FAIL_COND_V(root->type != GDParser::Node::TYPE_CLASS, false);
- const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode*>(root);
+ const GDParser::ClassNode *c = static_cast<const GDParser::ClassNode *>(root);
if (base_cache.is_valid()) {
base_cache->inheriters_cache.erase(get_instance_ID());
- base_cache=Ref<GDScript>();
+ base_cache = Ref<GDScript>();
}
-
- if (c->extends_used && String(c->extends_file)!="" && String(c->extends_file) != get_path()) {
+ if (c->extends_used && String(c->extends_file) != "" && String(c->extends_file) != get_path()) {
String path = c->extends_file;
if (path.is_rel_path()) {
String base = get_path();
- if (base=="" || base.is_rel_path()) {
+ if (base == "" || base.is_rel_path()) {
- ERR_PRINT(("Could not resolve relative path for parent class: "+path).utf8().get_data());
+ ERR_PRINT(("Could not resolve relative path for parent class: " + path).utf8().get_data());
} else {
- path=base.get_base_dir().plus_file(path);
+ path = base.get_base_dir().plus_file(path);
}
}
- if (path!=get_path()) {
+ if (path != get_path()) {
Ref<GDScript> bf = ResourceLoader::load(path);
if (bf.is_valid()) {
//print_line("parent is: "+bf->get_path());
- base_cache=bf;
+ base_cache = bf;
bf->inheriters_cache.insert(get_instance_ID());
//bf->_update_exports(p_instances,true,false);
-
}
} else {
- ERR_PRINT(("Path extending itself in "+path).utf8().get_data());
+ ERR_PRINT(("Path extending itself in " + path).utf8().get_data());
}
}
members_cache.clear();
member_default_values_cache.clear();
- for(int i=0;i<c->variables.size();i++) {
- if (c->variables[i]._export.type==Variant::NIL)
+ 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);
//print_line("found "+c->variables[i]._export.name);
- member_default_values_cache[c->variables[i].identifier]=c->variables[i].default_value;
+ member_default_values_cache[c->variables[i].identifier] = c->variables[i].default_value;
}
_signals.clear();
- for(int i=0;i<c->_signals.size();i++) {
- _signals[c->_signals[i].name]=c->_signals[i].arguments;
+ for (int i = 0; i < c->_signals.size(); i++) {
+ _signals[c->_signals[i].name] = c->_signals[i].arguments;
}
}
} else {
//print_line("unchaged is "+get_path());
-
}
if (base_cache.is_valid()) {
@@ -575,13 +546,13 @@ bool GDScript::_update_exports() {
//print_line("updating placeholders for "+get_path());
//update placeholders if any
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
List<PropertyInfo> propnames;
- _update_exports_values(values,propnames);
+ _update_exports_values(values, propnames);
- for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
+ for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
- E->get()->update(propnames,values);
+ E->get()->update(propnames, values);
}
}
@@ -597,14 +568,14 @@ void GDScript::update_exports() {
_update_exports();
- Set<ObjectID> copy=inheriters_cache; //might get modified
+ Set<ObjectID> copy = inheriters_cache; //might get modified
//print_line("update exports for "+get_path()+" ic: "+itos(copy.size()));
- for(Set<ObjectID>::Element *E=copy.front();E;E=E->next()) {
- Object *id=ObjectDB::get_instance(E->get());
+ for (Set<ObjectID>::Element *E = copy.front(); E; E = E->next()) {
+ Object *id = ObjectDB::get_instance(E->get());
if (!id)
continue;
- GDScript *s=id->cast_to<GDScript>();
+ GDScript *s = id->cast_to<GDScript>();
if (!s)
continue;
s->update_exports();
@@ -613,12 +584,12 @@ void GDScript::update_exports() {
#endif
}
-void GDScript::_set_subclass_path(Ref<GDScript>& p_sc,const String& p_path) {
+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()) {
+ 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);
+ _set_subclass_path(E->get(), p_path);
}
}
@@ -633,58 +604,54 @@ Error GDScript::reload(bool p_keep_state) {
GDScriptLanguage::singleton->lock->unlock();
#endif
- ERR_FAIL_COND_V(!p_keep_state && has_instances,ERR_ALREADY_IN_USE);
-
- String basedir=path;
-
- if (basedir=="")
- basedir=get_path();
+ ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);
- if (basedir!="")
- basedir=basedir.get_base_dir();
+ String basedir = path;
+ if (basedir == "")
+ basedir = get_path();
+ if (basedir != "")
+ basedir = basedir.get_base_dir();
-
- valid=false;
+ valid = false;
GDParser parser;
- Error err = parser.parse(source,basedir,false,path);
+ Error err = parser.parse(source, basedir, false, path);
if (err) {
if (ScriptDebugger::get_singleton()) {
- 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_error_line(), "Parser Error: " + parser.get_error());
}
- _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_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();
GDCompiler compiler;
- err = compiler.compile(&parser,this,p_keep_state);
+ err = compiler.compile(&parser, this, p_keep_state);
if (err) {
if (can_run) {
if (ScriptDebugger::get_singleton()) {
- GDScriptLanguage::get_singleton()->debug_break_parse(get_path(),compiler.get_error_line(),"Parser Error: "+compiler.get_error());
+ 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.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;
}
}
- valid=true;
+ valid = true;
- for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
+ for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
- _set_subclass_path(E->get(),path);
+ _set_subclass_path(E->get(), path);
}
#ifdef TOOLS_ENABLED
- /*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
+/*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
_update_placeholder(E->get());
}*/
@@ -702,74 +669,67 @@ ScriptLanguage *GDScript::get_language() const {
return GDScriptLanguage::get_singleton();
}
+Variant GDScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant GDScript::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+ GDScript *top = this;
+ while (top) {
-
- GDScript *top=this;
- while(top) {
-
- Map<StringName,GDFunction*>::Element *E=top->member_functions.find(p_method);
+ Map<StringName, GDFunction *>::Element *E = top->member_functions.find(p_method);
if (E) {
if (!E->get()->is_static()) {
- WARN_PRINT(String("Can't call non-static function: '"+String(p_method)+"' in script.").utf8().get_data());
+ WARN_PRINT(String("Can't call non-static function: '" + String(p_method) + "' in script.").utf8().get_data());
}
- return E->get()->call(NULL,p_args,p_argcount,r_error);
+ return E->get()->call(NULL, p_args, p_argcount, r_error);
}
- top=top->_base;
+ top = top->_base;
}
//none found, regular
- return Script::call(p_method,p_args,p_argcount,r_error);
-
+ return Script::call(p_method, p_args, p_argcount, r_error);
}
-bool GDScript::_get(const StringName& p_name,Variant &r_ret) const {
+bool GDScript::_get(const StringName &p_name, Variant &r_ret) const {
{
-
- const GDScript *top=this;
- while(top) {
+ const GDScript *top = this;
+ while (top) {
{
- const Map<StringName,Variant>::Element *E=top->constants.find(p_name);
+ const Map<StringName, Variant>::Element *E = top->constants.find(p_name);
if (E) {
- r_ret= E->get();
+ r_ret = E->get();
return true;
}
}
{
- const Map<StringName,Ref<GDScript> >::Element *E=subclasses.find(p_name);
+ const Map<StringName, Ref<GDScript> >::Element *E = subclasses.find(p_name);
if (E) {
- r_ret=E->get();
+ r_ret = E->get();
return true;
}
}
- top=top->_base;
+ top = top->_base;
}
- if (p_name==GDScriptLanguage::get_singleton()->strings._script_source) {
+ if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
- r_ret=get_source_code();
+ r_ret = get_source_code();
return true;
}
}
-
-
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) {
+ if (p_name == GDScriptLanguage::get_singleton()->strings._script_source) {
set_source_code(p_value);
reload();
@@ -781,159 +741,147 @@ bool GDScript::_set(const StringName& p_name, const Variant& p_value) {
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) );
+ p_properties->push_back(PropertyInfo(Variant::STRING, "script/source", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
}
-
void GDScript::_bind_methods() {
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"new",&GDScript::_new,MethodInfo(Variant::OBJECT,"new"));
-
- ClassDB::bind_method(D_METHOD("get_as_byte_code"),&GDScript::get_as_byte_code);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &GDScript::_new, MethodInfo(Variant::OBJECT, "new"));
+ ClassDB::bind_method(D_METHOD("get_as_byte_code"), &GDScript::get_as_byte_code);
}
-
Vector<uint8_t> GDScript::get_as_byte_code() const {
GDTokenizerBuffer tokenizer;
return tokenizer.parse_code_string(source);
};
-
-Error GDScript::load_byte_code(const String& p_path) {
+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);
+ 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[i]=script_encryption_key[i];
+ for (int i = 0; i < key.size(); i++) {
+ key[i] = script_encryption_key[i];
}
- Error err = fae->open_and_parse(fa,key,FileAccessEncrypted::MODE_READ);
- ERR_FAIL_COND_V(err,err);
+ Error err = fae->open_and_parse(fa, key, FileAccessEncrypted::MODE_READ);
+ ERR_FAIL_COND_V(err, err);
bytecode.resize(fae->get_len());
- fae->get_buffer(bytecode.ptr(),bytecode.size());
+ fae->get_buffer(bytecode.ptr(), bytecode.size());
memdelete(fae);
} else {
bytecode = FileAccess::get_file_as_array(p_path);
}
- ERR_FAIL_COND_V(bytecode.size()==0,ERR_PARSE_ERROR);
- path=p_path;
+ ERR_FAIL_COND_V(bytecode.size() == 0, ERR_PARSE_ERROR);
+ path = p_path;
- String basedir=path;
+ String basedir = path;
- if (basedir=="")
- basedir=get_path();
+ if (basedir == "")
+ basedir = get_path();
- if (basedir!="")
- basedir=basedir.get_base_dir();
+ if (basedir != "")
+ basedir = basedir.get_base_dir();
- valid=false;
+ valid = false;
GDParser parser;
- Error err = parser.parse_bytecode(bytecode,basedir,get_path());
+ 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_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);
}
GDCompiler compiler;
- err = compiler.compile(&parser,this);
+ 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_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;
+ valid = true;
- for(Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
+ for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
- _set_subclass_path(E->get(),path);
+ _set_subclass_path(E->get(), path);
}
return OK;
}
-
-Error GDScript::load_source_code(const String& p_path) {
-
+Error GDScript::load_source_code(const String &p_path) {
PoolVector<uint8_t> sourcef;
Error err;
- FileAccess *f=FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
}
int len = f->get_len();
- sourcef.resize(len+1);
+ sourcef.resize(len + 1);
PoolVector<uint8_t>::Write w = sourcef.write();
- int r = f->get_buffer(w.ptr(),len);
+ int r = f->get_buffer(w.ptr(), len);
f->close();
memdelete(f);
- ERR_FAIL_COND_V(r!=len,ERR_CANT_OPEN);
- w[len]=0;
+ ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
+ w[len] = 0;
String s;
- if (s.parse_utf8((const char*)w.ptr())) {
+ if (s.parse_utf8((const char *)w.ptr())) {
- ERR_EXPLAIN("Script '"+p_path+"' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
+ ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode.");
ERR_FAIL_V(ERR_INVALID_DATA);
}
- source=s;
+ source = s;
#ifdef TOOLS_ENABLED
- source_changed_cache=true;
+ source_changed_cache = true;
#endif
//print_line("LSC :"+get_path());
- path=p_path;
+ path = p_path;
return OK;
-
}
-
-const Map<StringName,GDFunction*>& GDScript::debug_get_member_functions() const {
+const Map<StringName, GDFunction *> &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()) {
- 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;
}
-bool GDScript::has_script_signal(const StringName& p_signal) const {
+bool GDScript::has_script_signal(const StringName &p_signal) const {
if (_signals.has(p_signal))
return true;
if (base.is_valid()) {
return base->has_script_signal(p_signal);
}
#ifdef TOOLS_ENABLED
- else if (base_cache.is_valid()){
+ else if (base_cache.is_valid()) {
return base_cache->has_script_signal(p_signal);
}
@@ -942,13 +890,13 @@ bool GDScript::has_script_signal(const StringName& p_signal) const {
}
void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
- for(const Map<StringName,Vector<StringName> >::Element *E=_signals.front();E;E=E->next()) {
+ 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++) {
+ mi.name = E->key();
+ for (int i = 0; i < E->get().size(); i++) {
PropertyInfo arg;
- arg.name=E->get()[i];
+ arg.name = E->get()[i];
mi.arguments.push_back(arg);
}
r_signals->push_back(mi);
@@ -958,27 +906,25 @@ void GDScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
base->get_script_signal_list(r_signals);
}
#ifdef TOOLS_ENABLED
- else if (base_cache.is_valid()){
+ else if (base_cache.is_valid()) {
base_cache->get_script_signal_list(r_signals);
}
#endif
-
}
+GDScript::GDScript()
+ : script_list(this) {
-GDScript::GDScript() : script_list(this) {
-
-
- _static_ref=this;
- valid=false;
- subclass_count=0;
- initializer=NULL;
- _base=NULL;
- _owner=NULL;
- tool=false;
+ _static_ref = this;
+ valid = false;
+ subclass_count = 0;
+ initializer = NULL;
+ _base = NULL;
+ _owner = NULL;
+ tool = false;
#ifdef TOOLS_ENABLED
- source_changed_cache=false;
+ source_changed_cache = false;
#endif
#ifdef DEBUG_ENABLED
@@ -994,12 +940,12 @@ GDScript::GDScript() : script_list(this) {
}
GDScript::~GDScript() {
- for (Map<StringName,GDFunction*>::Element *E=member_functions.front();E;E=E->next()) {
- memdelete( E->get() );
+ for (Map<StringName, GDFunction *>::Element *E = member_functions.front(); E; E = E->next()) {
+ memdelete(E->get());
}
- for (Map<StringName,Ref<GDScript> >::Element *E=subclasses.front();E;E=E->next()) {
- E->get()->_owner=NULL; //bye, you are no longer owned cause I died
+ for (Map<StringName, Ref<GDScript> >::Element *E = subclasses.front(); E; E = E->next()) {
+ E->get()->_owner = NULL; //bye, you are no longer owned cause I died
}
#ifdef DEBUG_ENABLED
@@ -1014,48 +960,41 @@ GDScript::~GDScript() {
#endif
}
-
-
-
-
//////////////////////////////
// INSTANCE //
//////////////////////////////
-
-bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
+bool GDInstance::set(const StringName &p_name, const Variant &p_value) {
//member
{
- const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
+ const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
if (E) {
if (E->get().setter) {
- const Variant *val=&p_value;
+ const Variant *val = &p_value;
Variant::CallError err;
- call(E->get().setter,&val,1,err);
- if (err.error==Variant::CallError::CALL_OK) {
+ call(E->get().setter, &val, 1, err);
+ if (err.error == Variant::CallError::CALL_OK) {
return true; //function exists, call was successful
}
- }
- else
+ } else
members[E->get().index] = p_value;
return true;
}
}
- GDScript *sptr=script.ptr();
- while(sptr) {
-
+ GDScript *sptr = script.ptr();
+ while (sptr) {
- Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
+ Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._set);
if (E) {
- Variant name=p_name;
- const Variant *args[2]={&name,&p_value};
+ Variant name = p_name;
+ const Variant *args[2] = { &name, &p_value };
Variant::CallError err;
- Variant ret = E->get()->call(this,(const Variant**)args,2,err);
- if (err.error==Variant::CallError::CALL_OK && ret.get_type()==Variant::BOOL && ret.operator bool())
+ Variant ret = E->get()->call(this, (const Variant **)args, 2, err);
+ if (err.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::BOOL && ret.operator bool())
return true;
}
sptr = sptr->_base;
@@ -1064,54 +1003,50 @@ bool GDInstance::set(const StringName& p_name, const Variant& p_value) {
return false;
}
-bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
+bool GDInstance::get(const StringName &p_name, Variant &r_ret) const {
-
-
- const GDScript *sptr=script.ptr();
- while(sptr) {
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
{
- const Map<StringName,GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
+ const Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.find(p_name);
if (E) {
if (E->get().getter) {
Variant::CallError err;
- r_ret=const_cast<GDInstance*>(this)->call(E->get().getter,NULL,0,err);
- if (err.error==Variant::CallError::CALL_OK) {
+ r_ret = const_cast<GDInstance *>(this)->call(E->get().getter, NULL, 0, err);
+ if (err.error == Variant::CallError::CALL_OK) {
return true;
}
}
- r_ret=members[E->get().index];
+ r_ret = members[E->get().index];
return true; //index found
-
}
}
{
const GDScript *sl = sptr;
- while(sl) {
- const Map<StringName,Variant>::Element *E = sl->constants.find(p_name);
+ while (sl) {
+ const Map<StringName, Variant>::Element *E = sl->constants.find(p_name);
if (E) {
- r_ret=E->get();
+ r_ret = E->get();
return true; //index found
-
}
- sl=sl->_base;
+ sl = sl->_base;
}
}
{
- const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
+ const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get);
if (E) {
- Variant name=p_name;
- const Variant *args[1]={&name};
+ Variant name = p_name;
+ const Variant *args[1] = { &name };
Variant::CallError err;
- Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),(const Variant**)args,1,err);
- if (err.error==Variant::CallError::CALL_OK && ret.get_type()!=Variant::NIL) {
- r_ret=ret;
+ Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), (const Variant **)args, 1, err);
+ if (err.error == Variant::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
+ r_ret = ret;
return true;
}
}
@@ -1120,94 +1055,86 @@ bool GDInstance::get(const StringName& p_name, Variant &r_ret) const {
}
return false;
-
}
-Variant::Type GDInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const {
+Variant::Type GDInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
-
- const GDScript *sptr=script.ptr();
- while(sptr) {
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
if (sptr->member_info.has(p_name)) {
if (r_is_valid)
- *r_is_valid=true;
+ *r_is_valid = true;
return sptr->member_info[p_name].type;
}
sptr = sptr->_base;
}
if (r_is_valid)
- *r_is_valid=false;
+ *r_is_valid = false;
return Variant::NIL;
}
void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
// exported members, not doen yet!
- const GDScript *sptr=script.ptr();
+ const GDScript *sptr = script.ptr();
List<PropertyInfo> props;
- while(sptr) {
-
+ while (sptr) {
- const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
+ const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._get_property_list);
if (E) {
-
Variant::CallError err;
- Variant ret = const_cast<GDFunction*>(E->get())->call(const_cast<GDInstance*>(this),NULL,0,err);
- if (err.error==Variant::CallError::CALL_OK) {
+ Variant ret = const_cast<GDFunction *>(E->get())->call(const_cast<GDInstance *>(this), NULL, 0, err);
+ if (err.error == Variant::CallError::CALL_OK) {
- if (ret.get_type()!=Variant::ARRAY) {
+ if (ret.get_type() != Variant::ARRAY) {
ERR_EXPLAIN("Wrong type for _get_property list, must be an array of dictionaries.");
ERR_FAIL();
}
Array arr = ret;
- for(int i=0;i<arr.size();i++) {
+ for (int i = 0; i < arr.size(); i++) {
Dictionary d = arr[i];
ERR_CONTINUE(!d.has("name"));
ERR_CONTINUE(!d.has("type"));
PropertyInfo pinfo;
- pinfo.type = Variant::Type( d["type"].operator int());
- ERR_CONTINUE(pinfo.type<0 || pinfo.type>=Variant::VARIANT_MAX );
+ pinfo.type = Variant::Type(d["type"].operator int());
+ ERR_CONTINUE(pinfo.type < 0 || pinfo.type >= Variant::VARIANT_MAX);
pinfo.name = d["name"];
- ERR_CONTINUE(pinfo.name=="");
+ ERR_CONTINUE(pinfo.name == "");
if (d.has("hint"))
- pinfo.hint=PropertyHint(d["hint"].operator int());
+ pinfo.hint = PropertyHint(d["hint"].operator int());
if (d.has("hint_string"))
- pinfo.hint_string=d["hint_string"];
+ pinfo.hint_string = d["hint_string"];
if (d.has("usage"))
- pinfo.usage=d["usage"];
+ pinfo.usage = d["usage"];
props.push_back(pinfo);
-
}
-
}
}
//instance a fake script for editing the values
Vector<_GDScriptMemberSort> msort;
- for(Map<StringName,PropertyInfo>::Element *E=sptr->member_info.front();E;E=E->next()) {
+ 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;
- ms.name=E->key();
+ ms.index = sptr->member_indices[E->key()].index;
+ ms.name = E->key();
msort.push_back(ms);
-
}
msort.sort();
msort.invert();
- for(int i=0;i<msort.size();i++) {
+ for (int i = 0; i < msort.size(); i++) {
props.push_front(sptr->member_info[msort[i].name]);
-
}
#if 0
if (sptr->member_functions.has("_get_property_list")) {
@@ -1256,7 +1183,7 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
//props.invert();
- for (List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) {
p_properties->push_back(E->get());
}
@@ -1264,28 +1191,27 @@ void GDInstance::get_property_list(List<PropertyInfo> *p_properties) const {
void GDInstance::get_method_list(List<MethodInfo> *p_list) const {
- const GDScript *sptr=script.ptr();
- while(sptr) {
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
- for (Map<StringName,GDFunction*>::Element *E = sptr->member_functions.front();E;E=E->next()) {
+ for (Map<StringName, GDFunction *>::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++)
- mi.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
+ mi.name = E->key();
+ mi.flags |= METHOD_FLAG_FROM_SCRIPT;
+ 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;
}
-
}
-bool GDInstance::has_method(const StringName& p_method) const {
+bool GDInstance::has_method(const StringName &p_method) const {
- const GDScript *sptr=script.ptr();
- while(sptr) {
- const Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
+ const GDScript *sptr = script.ptr();
+ while (sptr) {
+ const Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
if (E)
return true;
sptr = sptr->_base;
@@ -1293,81 +1219,74 @@ bool GDInstance::has_method(const StringName& p_method) const {
return false;
}
-Variant GDInstance::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+Variant GDInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
//printf("calling %ls:%i method %ls\n", script->get_path().c_str(), -1, String(p_method).c_str());
- GDScript *sptr=script.ptr();
- while(sptr) {
- Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
+ GDScript *sptr = script.ptr();
+ while (sptr) {
+ Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
if (E) {
- return E->get()->call(this,p_args,p_argcount,r_error);
+ return E->get()->call(this, p_args, p_argcount, r_error);
}
sptr = sptr->_base;
}
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
}
-void GDInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) {
+void GDInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
- GDScript *sptr=script.ptr();
+ GDScript *sptr = script.ptr();
Variant::CallError ce;
- while(sptr) {
- Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
+ while (sptr) {
+ Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
if (E) {
- E->get()->call(this,p_args,p_argcount,ce);
+ E->get()->call(this, p_args, p_argcount, ce);
}
sptr = sptr->_base;
}
-
}
-
-void GDInstance::_ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) {
+void GDInstance::_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);
+ _ml_call_reversed(sptr->_base, p_method, p_args, p_argcount);
Variant::CallError ce;
- Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method);
+ Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(p_method);
if (E) {
- E->get()->call(this,p_args,p_argcount,ce);
+ E->get()->call(this, p_args, p_argcount, ce);
}
-
}
-void GDInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) {
+void GDInstance::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);
+ _ml_call_reversed(script.ptr(), p_method, p_args, p_argcount);
}
}
-
-
void GDInstance::notification(int p_notification) {
//notification is not virutal, it gets called at ALL levels just like in C.
- Variant value=p_notification;
- const Variant *args[1]={&value };
+ Variant value = p_notification;
+ const Variant *args[1] = { &value };
- GDScript *sptr=script.ptr();
- while(sptr) {
- Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
+ GDScript *sptr = script.ptr();
+ while (sptr) {
+ Map<StringName, GDFunction *>::Element *E = sptr->member_functions.find(GDScriptLanguage::get_singleton()->strings._notification);
if (E) {
Variant::CallError err;
- E->get()->call(this,args,1,err);
- if (err.error!=Variant::CallError::CALL_OK) {
+ E->get()->call(this, args, 1, err);
+ if (err.error != Variant::CallError::CALL_OK) {
//print error about notification call
-
}
}
sptr = sptr->_base;
}
-
}
Ref<Script> GDInstance::get_script() const {
@@ -1380,46 +1299,42 @@ ScriptLanguage *GDInstance::get_language() {
return GDScriptLanguage::get_singleton();
}
-GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName& p_method) const {
+GDInstance::RPCMode GDInstance::get_rpc_mode(const StringName &p_method) const {
const GDScript *cscript = script.ptr();
- while(cscript) {
- const Map<StringName,GDFunction*>::Element *E=cscript->member_functions.find(p_method);
+ while (cscript) {
+ const Map<StringName, GDFunction *>::Element *E = cscript->member_functions.find(p_method);
if (E) {
- if (E->get()->get_rpc_mode()!=RPC_MODE_DISABLED) {
+ if (E->get()->get_rpc_mode() != RPC_MODE_DISABLED) {
return E->get()->get_rpc_mode();
}
-
}
- cscript=cscript->_base;
+ cscript = cscript->_base;
}
return RPC_MODE_DISABLED;
}
-GDInstance::RPCMode GDInstance::get_rset_mode(const StringName& p_variable) const {
+GDInstance::RPCMode GDInstance::get_rset_mode(const StringName &p_variable) const {
const GDScript *cscript = script.ptr();
- while(cscript) {
- const Map<StringName,GDScript::MemberInfo>::Element *E=cscript->member_indices.find(p_variable);
+ while (cscript) {
+ const Map<StringName, GDScript::MemberInfo>::Element *E = cscript->member_indices.find(p_variable);
if (E) {
if (E->get().rpc_mode) {
return E->get().rpc_mode;
}
-
}
- cscript=cscript->_base;
+ cscript = cscript->_base;
}
return RPC_MODE_DISABLED;
}
-
-
void GDInstance::reload_members() {
#ifdef DEBUG_ENABLED
@@ -1430,44 +1345,42 @@ void GDInstance::reload_members() {
new_members.resize(script->member_indices.size());
//pass the values to the new indices
- for(Map<StringName,GDScript::MemberInfo>::Element *E=script->member_indices.front();E;E=E->next()) {
+ 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[E->get().index]=value;
+ new_members[E->get().index] = value;
}
-
}
//apply
- members=new_members;
+ members = new_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()) {
+ for (Map<StringName, GDScript::MemberInfo>::Element *E = script->member_indices.front(); E; E = E->next()) {
- member_indices_cache[E->key()]=E->get().index;
+ member_indices_cache[E->key()] = E->get().index;
}
#endif
}
GDInstance::GDInstance() {
- owner=NULL;
- base_ref=false;
+ owner = NULL;
+ base_ref = false;
}
GDInstance::~GDInstance() {
if (script.is_valid() && owner) {
#ifndef NO_THREADS
- GDScriptLanguage::singleton->lock->lock();
+ GDScriptLanguage::singleton->lock->lock();
#endif
- script->instances.erase(owner);
+ script->instances.erase(owner);
#ifndef NO_THREADS
- GDScriptLanguage::singleton->lock->unlock();
+ GDScriptLanguage::singleton->lock->unlock();
#endif
-
}
}
@@ -1477,8 +1390,7 @@ GDInstance::~GDInstance() {
/************* SCRIPT LANGUAGE **************/
/************* SCRIPT LANGUAGE **************/
-GDScriptLanguage *GDScriptLanguage::singleton=NULL;
-
+GDScriptLanguage *GDScriptLanguage::singleton = NULL;
String GDScriptLanguage::get_name() const {
@@ -1487,63 +1399,60 @@ String GDScriptLanguage::get_name() const {
/* LANGUAGE FUNCTIONS */
-void GDScriptLanguage::_add_global(const StringName& p_name,const Variant& p_value) {
-
+void GDScriptLanguage::_add_global(const StringName &p_name, const Variant &p_value) {
if (globals.has(p_name)) {
//overwrite existing
- global_array[globals[p_name]]=p_value;
+ global_array[globals[p_name]] = p_value;
return;
}
- globals[p_name]=global_array.size();
+ globals[p_name] = global_array.size();
global_array.push_back(p_value);
- _global_array=global_array.ptr();
+ _global_array = global_array.ptr();
}
-void GDScriptLanguage::add_global_constant(const StringName& p_variable,const Variant& p_value) {
+void GDScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) {
- _add_global(p_variable,p_value);
+ _add_global(p_variable, p_value);
}
-
void GDScriptLanguage::init() {
-
//populate global constants
- int gcc=GlobalConstants::get_global_constant_count();
- for(int i=0;i<gcc;i++) {
+ int gcc = GlobalConstants::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(GlobalConstants::get_global_constant_name(i)), GlobalConstants::get_global_constant_value(i));
}
- _add_global(StaticCString::create("PI"),Math_PI);
- _add_global(StaticCString::create("INF"),Math_INF);
- _add_global(StaticCString::create("NAN"),Math_NAN);
+ _add_global(StaticCString::create("PI"), Math_PI);
+ _add_global(StaticCString::create("INF"), Math_INF);
+ _add_global(StaticCString::create("NAN"), Math_NAN);
//populate native classes
List<StringName> class_list;
ClassDB::get_class_list(&class_list);
- for(List<StringName>::Element *E=class_list.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = class_list.front(); E; E = E->next()) {
StringName n = E->get();
String s = String(n);
if (s.begins_with("_"))
- n=s.substr(1,s.length());
+ n = s.substr(1, s.length());
if (globals.has(n))
continue;
- Ref<GDNativeClass> nc = memnew( GDNativeClass(E->get()) );
- _add_global(n,nc);
+ Ref<GDNativeClass> nc = memnew(GDNativeClass(E->get()));
+ _add_global(n, nc);
}
//populate singletons
List<GlobalConfig::Singleton> singletons;
GlobalConfig::get_singleton()->get_singletons(&singletons);
- for(List<GlobalConfig::Singleton>::Element *E=singletons.front();E;E=E->next()) {
+ for (List<GlobalConfig::Singleton>::Element *E = singletons.front(); E; E = E->next()) {
- _add_global(E->get().name,E->get().ptr);
+ _add_global(E->get().name, E->get().ptr);
}
}
@@ -1555,14 +1464,12 @@ 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::finish() {
}
void GDScriptLanguage::profiling_start() {
@@ -1572,27 +1479,26 @@ void GDScriptLanguage::profiling_start() {
lock->lock();
}
- SelfList<GDFunction> *elem=function_list.first();
- while(elem) {
- elem->self()->profile.call_count=0;
- elem->self()->profile.self_time=0;
- elem->self()->profile.total_time=0;
- elem->self()->profile.frame_call_count=0;
- elem->self()->profile.frame_self_time=0;
- elem->self()->profile.frame_total_time=0;
- elem->self()->profile.last_frame_call_count=0;
- elem->self()->profile.last_frame_self_time=0;
- elem->self()->profile.last_frame_total_time=0;
- elem=elem->next();
+ SelfList<GDFunction> *elem = function_list.first();
+ while (elem) {
+ elem->self()->profile.call_count = 0;
+ elem->self()->profile.self_time = 0;
+ elem->self()->profile.total_time = 0;
+ elem->self()->profile.frame_call_count = 0;
+ elem->self()->profile.frame_self_time = 0;
+ elem->self()->profile.frame_total_time = 0;
+ elem->self()->profile.last_frame_call_count = 0;
+ elem->self()->profile.last_frame_self_time = 0;
+ elem->self()->profile.last_frame_total_time = 0;
+ elem = elem->next();
}
- profiling=true;
+ profiling = true;
if (lock) {
lock->unlock();
}
#endif
-
}
void GDScriptLanguage::profiling_stop() {
@@ -1602,7 +1508,7 @@ void GDScriptLanguage::profiling_stop() {
lock->lock();
}
- profiling=false;
+ profiling = false;
if (lock) {
lock->unlock();
}
@@ -1610,95 +1516,83 @@ void GDScriptLanguage::profiling_stop() {
#endif
}
-int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr,int p_info_max) {
+int GDScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) {
- int current=0;
+ int current = 0;
#ifdef DEBUG_ENABLED
if (lock) {
lock->lock();
}
-
- SelfList<GDFunction> *elem=function_list.first();
- while(elem) {
- if (current>=p_info_max)
+ SelfList<GDFunction> *elem = function_list.first();
+ while (elem) {
+ 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;
- p_info_arr[current].signature=elem->self()->profile.signature;
- elem=elem->next();
+ 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;
+ p_info_arr[current].signature = elem->self()->profile.signature;
+ elem = elem->next();
current++;
}
-
-
if (lock) {
lock->unlock();
}
-
#endif
return current;
-
-
}
-int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr,int p_info_max) {
+int GDScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
- int current=0;
+ int current = 0;
#ifdef DEBUG_ENABLED
if (lock) {
lock->lock();
}
-
- SelfList<GDFunction> *elem=function_list.first();
- while(elem) {
- if (current>=p_info_max)
+ SelfList<GDFunction> *elem = function_list.first();
+ while (elem) {
+ 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;
- p_info_arr[current].total_time=elem->self()->profile.last_frame_total_time;
- p_info_arr[current].signature=elem->self()->profile.signature;
+ 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;
+ p_info_arr[current].total_time = elem->self()->profile.last_frame_total_time;
+ p_info_arr[current].signature = elem->self()->profile.signature;
//print_line(String(elem->self()->profile.signature)+": "+itos(elem->self()->profile.last_frame_call_count));
current++;
}
- elem=elem->next();
-
+ elem = elem->next();
}
-
if (lock) {
lock->unlock();
}
-
#endif
return current;
-
}
-
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 {
+ 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()) {
+ const GDScript *I = B->get_base().ptr();
+ while (I) {
+ if (I == A.ptr()) {
// A is a base of B
return true;
}
- I=I->get_base().ptr();
+ I = I->get_base().ptr();
}
return false; //not a base
@@ -1707,8 +1601,6 @@ struct GDScriptDepSort {
void GDScriptLanguage::reload_all_scripts() {
-
-
#ifdef DEBUG_ENABLED
print_line("RELOAD ALL SCRIPTS");
if (lock) {
@@ -1717,13 +1609,13 @@ void GDScriptLanguage::reload_all_scripts() {
List<Ref<GDScript> > scripts;
- SelfList<GDScript> *elem=script_list.first();
- while(elem) {
+ SelfList<GDScript> *elem = script_list.first();
+ while (elem) {
if (elem->self()->get_path().is_resource_file()) {
- print_line("FOUND: "+elem->self()->get_path());
+ print_line("FOUND: " + elem->self()->get_path());
scripts.push_back(Ref<GDScript>(elem->self())); //cast to gdscript to avoid being erased by accident
}
- elem=elem->next();
+ elem = elem->next();
}
if (lock) {
@@ -1734,18 +1626,16 @@ 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()) {
+ for (List<Ref<GDScript> >::Element *E = scripts.front(); E; E = E->next()) {
- print_line("RELOADING: "+E->get()->get_path());
+ print_line("RELOADING: " + E->get()->get_path());
E->get()->load_source_code(E->get()->get_path());
E->get()->reload(true);
}
#endif
}
-
-void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload) {
-
+void GDScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
#ifdef DEBUG_ENABLED
@@ -1755,13 +1645,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof
List<Ref<GDScript> > scripts;
- SelfList<GDScript> *elem=script_list.first();
- while(elem) {
+ 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();
+ elem = elem->next();
}
if (lock) {
@@ -1770,68 +1660,68 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof
//when someone asks you why dynamically typed languages are easier to write....
- Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > > to_reload;
+ Map<Ref<GDScript>, Map<ObjectID, List<Pair<StringName, Variant> > > > to_reload;
//as scripts are going to be reloaded, must proceed without locking here
scripts.sort_custom<GDScriptDepSort>(); //update in inheritance dependency order
- for(List<Ref<GDScript> >::Element *E=scripts.front();E;E=E->next()) {
+ 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());
+ bool reload = E->get() == p_script || to_reload.has(E->get()->get_base());
if (!reload)
continue;
- to_reload.insert(E->get(),Map<ObjectID,List<Pair<StringName,Variant> > >());
+ 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()];
+ Map<ObjectID, List<Pair<StringName, Variant> > > &map = to_reload[E->get()];
- while(E->get()->instances.front()) {
+ while (E->get()->instances.front()) {
Object *obj = E->get()->instances.front()->get();
//save instance info
- List<Pair<StringName,Variant> > state;
+ List<Pair<StringName, Variant> > state;
if (obj->get_script_instance()) {
obj->get_script_instance()->get_property_state(state);
- map[obj->get_instance_ID()]=state;
+ map[obj->get_instance_ID()] = state;
obj->set_script(RefPtr());
}
}
- //same thing for placeholders
+//same thing for placeholders
#ifdef TOOLS_ENABLED
- while(E->get()->placeholders.size()) {
+ while (E->get()->placeholders.size()) {
Object *obj = E->get()->placeholders.front()->get()->get_owner();
//save instance info
- List<Pair<StringName,Variant> > state;
+ List<Pair<StringName, Variant> > state;
if (obj->get_script_instance()) {
obj->get_script_instance()->get_property_state(state);
- map[obj->get_instance_ID()]=state;
+ map[obj->get_instance_ID()] = state;
obj->set_script(RefPtr());
}
}
#endif
- for(Map<ObjectID,List<Pair<StringName,Variant> > >::Element *F=E->get()->pending_reload_state.front();F;F=F->next()) {
- map[F->key()]=F->get(); //pending to reload, use this one instead
+ for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get()->pending_reload_state.front(); F; F = F->next()) {
+ map[F->key()] = F->get(); //pending to reload, use this one instead
}
}
}
- for(Map< Ref<GDScript>, Map<ObjectID,List<Pair<StringName,Variant> > > >::Element *E=to_reload.front();E;E=E->next()) {
+ 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()) {
+ for (Map<ObjectID, List<Pair<StringName, Variant> > >::Element *F = E->get().front(); F; F = F->next()) {
Object *obj = ObjectDB::get_instance(F->key());
if (!obj)
@@ -1845,13 +1735,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof
if (!obj->get_script_instance()) {
//failed, save reload state for next time if not saved
if (!scr->pending_reload_state.has(obj->get_instance_ID())) {
- scr->pending_reload_state[obj->get_instance_ID()]=F->get();
+ scr->pending_reload_state[obj->get_instance_ID()] = F->get();
}
continue;
}
- for (List<Pair<StringName,Variant> >::Element *G=F->get().front();G;G=G->next()) {
- obj->get_script_instance()->set(G->get().first,G->get().second);
+ for (List<Pair<StringName, Variant> >::Element *G = F->get().front(); G; G = G->next()) {
+ obj->get_script_instance()->set(G->get().first, G->get().second);
}
scr->pending_reload_state.erase(obj->get_instance_ID()); //as it reloaded, remove pending state
@@ -1860,14 +1750,13 @@ void GDScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_sof
//if instance states were saved, set them!
}
-
#endif
}
void GDScriptLanguage::frame() {
//print_line("calls: "+itos(calls));
- calls=0;
+ calls = 0;
#ifdef DEBUG_ENABLED
if (profiling) {
@@ -1875,18 +1764,17 @@ void GDScriptLanguage::frame() {
lock->lock();
}
- SelfList<GDFunction> *elem=function_list.first();
- while(elem) {
- elem->self()->profile.last_frame_call_count=elem->self()->profile.frame_call_count;
- elem->self()->profile.last_frame_self_time=elem->self()->profile.frame_self_time;
- elem->self()->profile.last_frame_total_time=elem->self()->profile.frame_total_time;
- elem->self()->profile.frame_call_count=0;
- elem->self()->profile.frame_self_time=0;
- elem->self()->profile.frame_total_time=0;
- elem=elem->next();
+ SelfList<GDFunction> *elem = function_list.first();
+ while (elem) {
+ elem->self()->profile.last_frame_call_count = elem->self()->profile.frame_call_count;
+ elem->self()->profile.last_frame_self_time = elem->self()->profile.frame_self_time;
+ elem->self()->profile.last_frame_total_time = elem->self()->profile.frame_total_time;
+ elem->self()->profile.frame_call_count = 0;
+ elem->self()->profile.frame_self_time = 0;
+ elem->self()->profile.frame_total_time = 0;
+ elem = elem->next();
}
-
if (lock) {
lock->unlock();
}
@@ -1896,9 +1784,9 @@ void GDScriptLanguage::frame() {
}
/* EDITOR FUNCTIONS */
-void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
+void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
- static const char *_reserved_words[]={
+ static const char *_reserved_words[] = {
// operators
"and",
"in",
@@ -1948,11 +1836,10 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
"sync",
"master",
"slave",
- 0};
-
-
- const char **w=_reserved_words;
+ 0
+ };
+ const char **w = _reserved_words;
while (*w) {
@@ -1960,73 +1847,69 @@ void GDScriptLanguage::get_reserved_words(List<String> *p_words) const {
w++;
}
- for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
+ for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
p_words->push_back(GDFunctions::get_func_name(GDFunctions::Function(i)));
}
-
}
GDScriptLanguage::GDScriptLanguage() {
- calls=0;
+ calls = 0;
ERR_FAIL_COND(singleton);
- singleton=this;
+ singleton = this;
strings._init = StaticCString::create("_init");
strings._notification = StaticCString::create("_notification");
- strings._set= StaticCString::create("_set");
- strings._get= StaticCString::create("_get");
- strings._get_property_list= StaticCString::create("_get_property_list");
- strings._script_source=StaticCString::create("script/source");
- _debug_parse_err_line=-1;
- _debug_parse_err_file="";
+ strings._set = StaticCString::create("_set");
+ strings._get = StaticCString::create("_get");
+ strings._get_property_list = StaticCString::create("_get_property_list");
+ strings._script_source = StaticCString::create("script/source");
+ _debug_parse_err_line = -1;
+ _debug_parse_err_file = "";
#ifdef NO_THREADS
- lock=NULL;
+ lock = NULL;
#else
lock = Mutex::create();
#endif
- profiling=false;
- script_frame_time=0;
+ profiling = false;
+ script_frame_time = 0;
- _debug_call_stack_pos=0;
- int dmcs=GLOBAL_DEF("debug/script/max_call_stack",1024);
+ _debug_call_stack_pos = 0;
+ int dmcs = GLOBAL_DEF("debug/script/max_call_stack", 1024);
if (ScriptDebugger::get_singleton()) {
//debugging enabled!
_debug_max_call_stack = dmcs;
- if (_debug_max_call_stack<1024)
- _debug_max_call_stack=1024;
- _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
+ if (_debug_max_call_stack < 1024)
+ _debug_max_call_stack = 1024;
+ _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
} else {
- _debug_max_call_stack=0;
- _call_stack=NULL;
+ _debug_max_call_stack = 0;
+ _call_stack = NULL;
}
-
}
-
GDScriptLanguage::~GDScriptLanguage() {
-
if (lock) {
memdelete(lock);
- lock=NULL;
+ lock = NULL;
}
- if (_call_stack) {
+ if (_call_stack) {
memdelete_arr(_call_stack);
}
- singleton=NULL;
+ singleton = NULL;
}
/*************** RESOURCE ***************/
-RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderGDScript::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_FILE_CANT_OPEN;
+ *r_error = ERR_FILE_CANT_OPEN;
- GDScript *script = memnew( GDScript );
+ GDScript *script = memnew(GDScript);
Ref<GDScript> scriptres(script);
@@ -2036,18 +1919,17 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori
script->set_path(p_original_path);
Error err = script->load_byte_code(p_path);
+ if (err != OK) {
- if (err!=OK) {
-
- ERR_FAIL_COND_V(err!=OK, RES());
+ ERR_FAIL_COND_V(err != OK, RES());
}
} else {
Error err = script->load_source_code(p_path);
- if (err!=OK) {
+ if (err != OK) {
- ERR_FAIL_COND_V(err!=OK, RES());
+ ERR_FAIL_COND_V(err != OK, RES());
}
script->set_script_path(p_original_path); // script needs this.
@@ -2057,7 +1939,7 @@ RES ResourceFormatLoaderGDScript::load(const String &p_path, const String& p_ori
script->reload();
}
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return scriptres;
}
@@ -2068,38 +1950,36 @@ void ResourceFormatLoaderGDScript::get_recognized_extensions(List<String> *p_ext
p_extensions->push_back("gde");
}
-bool ResourceFormatLoaderGDScript::handles_type(const String& p_type) const {
+bool ResourceFormatLoaderGDScript::handles_type(const String &p_type) const {
- return (p_type=="Script" || p_type=="GDScript");
+ 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")
+ if (el == "gd" || el == "gdc" || el == "gde")
return "GDScript";
return "";
}
-
-Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
+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);
+ ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);
String source = sqscr->get_source_code();
Error err;
- FileAccess *file = FileAccess::open(p_path,FileAccess::WRITE,&err);
-
+ FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
if (err) {
- ERR_FAIL_COND_V(err,err);
+ ERR_FAIL_COND_V(err, err);
}
file->store_string(source);
- if (file->get_error()!=OK && file->get_error()!=ERR_FILE_EOF) {
+ if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
memdelete(file);
return ERR_CANT_CREATE;
}
@@ -2107,20 +1987,19 @@ Error ResourceFormatSaverGDScript::save(const String &p_path,const RES& p_resour
memdelete(file);
if (ScriptServer::is_reload_scripts_on_save_enabled()) {
- GDScriptLanguage::get_singleton()->reload_tool_script(p_resource,false);
+ GDScriptLanguage::get_singleton()->reload_tool_script(p_resource, false);
}
return OK;
}
-void ResourceFormatSaverGDScript::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
+void ResourceFormatSaverGDScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
if (p_resource->cast_to<GDScript>()) {
p_extensions->push_back("gd");
}
-
}
-bool ResourceFormatSaverGDScript::recognize(const RES& p_resource) const {
+bool ResourceFormatSaverGDScript::recognize(const RES &p_resource) const {
- return p_resource->cast_to<GDScript>()!=NULL;
+ return p_resource->cast_to<GDScript>() != NULL;
}
diff --git a/modules/gdscript/gd_script.h b/modules/gdscript/gd_script.h
index 4d3baa5bc0..d64cc9798d 100644
--- a/modules/gdscript/gd_script.h
+++ b/modules/gdscript/gd_script.h
@@ -29,50 +29,45 @@
#ifndef GD_SCRIPT_H
#define GD_SCRIPT_H
-#include "script_language.h"
+#include "gd_function.h"
#include "io/resource_loader.h"
#include "io/resource_saver.h"
-#include "gd_function.h"
+#include "script_language.h"
class GDNativeClass : public Reference {
- GDCLASS(GDNativeClass,Reference);
+ GDCLASS(GDNativeClass, Reference);
StringName name;
-protected:
- bool _get(const StringName& p_name,Variant &r_ret) const;
+protected:
+ bool _get(const StringName &p_name, Variant &r_ret) const;
static void _bind_methods();
public:
-
- _FORCE_INLINE_ const StringName& get_name() const { return name; }
+ _FORCE_INLINE_ const StringName &get_name() const { return name; }
Variant _new();
Object *instance();
- GDNativeClass(const StringName& p_name);
+ GDNativeClass(const StringName &p_name);
};
-
class GDScript : public Script {
-
- GDCLASS(GDScript,Script);
+ GDCLASS(GDScript, Script);
bool tool;
bool valid;
-
struct MemberInfo {
int index;
StringName setter;
StringName getter;
ScriptInstance::RPCMode rpc_mode;
-
};
-friend class GDInstance;
-friend class GDFunction;
-friend class GDCompiler;
-friend class GDFunctions;
-friend class GDScriptLanguage;
+ friend class GDInstance;
+ friend class GDFunction;
+ friend class GDCompiler;
+ friend class GDFunctions;
+ friend class GDScriptLanguage;
Variant _static_ref; //used for static call
Ref<GDNativeClass> native;
@@ -81,130 +76,125 @@ friend class GDScriptLanguage;
GDScript *_owner; //for subclasses
Set<StringName> members; //members are just indices to the instanced script.
- Map<StringName,Variant> constants;
- Map<StringName,GDFunction*> member_functions;
- Map<StringName,MemberInfo> member_indices; //members are just indices to the instanced script.
- Map<StringName,Ref<GDScript> > subclasses;
- Map<StringName,Vector<StringName> > _signals;
-
+ Map<StringName, Variant> constants;
+ Map<StringName, GDFunction *> member_functions;
+ Map<StringName, MemberInfo> member_indices; //members are just indices to the instanced script.
+ Map<StringName, Ref<GDScript> > subclasses;
+ Map<StringName, Vector<StringName> > _signals;
#ifdef TOOLS_ENABLED
- Map<StringName,int> member_lines;
+ Map<StringName, int> member_lines;
- Map<StringName,Variant> member_default_values;
+ Map<StringName, Variant> member_default_values;
List<PropertyInfo> members_cache;
- Map<StringName,Variant> member_default_values_cache;
+ Map<StringName, Variant> member_default_values_cache;
Ref<GDScript> base_cache;
Set<ObjectID> inheriters_cache;
bool source_changed_cache;
- void _update_exports_values(Map<StringName,Variant>& values, List<PropertyInfo> &propnames);
+ void _update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames);
#endif
- Map<StringName,PropertyInfo> member_info;
+ Map<StringName, PropertyInfo> member_info;
GDFunction *initializer; //direct pointer to _init , faster to locate
int subclass_count;
- Set<Object*> instances;
+ Set<Object *> instances;
//exported members
String source;
String path;
String name;
SelfList<GDScript> script_list;
+ GDInstance *_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Variant::CallError &r_error);
- GDInstance* _create_instance(const Variant** p_args,int p_argcount,Object *p_owner,bool p_isref,Variant::CallError &r_error);
-
- void _set_subclass_path(Ref<GDScript>& p_sc,const String& p_path);
+ void _set_subclass_path(Ref<GDScript> &p_sc, const String &p_path);
#ifdef TOOLS_ENABLED
- Set<PlaceHolderScriptInstance*> placeholders;
+ Set<PlaceHolderScriptInstance *> placeholders;
//void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
#endif
#ifdef DEBUG_ENABLED
- Map<ObjectID,List<Pair<StringName,Variant> > > pending_reload_state;
+ Map<ObjectID, List<Pair<StringName, Variant> > > pending_reload_state;
#endif
bool _update_exports();
protected:
- bool _get(const StringName& p_name,Variant &r_ret) const;
- bool _set(const StringName& p_name, const Variant& p_value);
+ 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,Variant::CallError &r_error);
+ Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
//void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount);
static void _bind_methods();
-public:
+public:
bool is_valid() const { return valid; }
- const Map<StringName,Ref<GDScript> >& get_subclasses() const { return subclasses; }
- const Map<StringName,Variant >& get_constants() const { return constants; }
- const Set<StringName>& get_members() const { return members; }
- const Map<StringName,GDFunction*>& get_member_functions() const { return member_functions; }
- const Ref<GDNativeClass>& get_native() const { return native; }
+ const Map<StringName, Ref<GDScript> > &get_subclasses() const { return subclasses; }
+ const Map<StringName, Variant> &get_constants() const { return constants; }
+ const Set<StringName> &get_members() const { return members; }
+ const Map<StringName, GDFunction *> &get_member_functions() const { return member_functions; }
+ const Ref<GDNativeClass> &get_native() const { return native; }
- virtual bool has_script_signal(const StringName& p_signal) const;
+ virtual bool has_script_signal(const StringName &p_signal) const;
virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
-
bool is_tool() const { return tool; }
Ref<GDScript> get_base() const;
- const Map<StringName,MemberInfo>& debug_get_member_indices() const { return member_indices; }
- const Map<StringName,GDFunction*>& debug_get_member_functions() const; //this is debug only
+ const Map<StringName, MemberInfo> &debug_get_member_indices() const { return member_indices; }
+ const Map<StringName, GDFunction *> &debug_get_member_functions() const; //this is debug only
StringName debug_get_member_by_index(int p_idx) const;
- Variant _new(const Variant** p_args,int p_argcount,Variant::CallError& r_error);
+ Variant _new(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
virtual bool can_instance() const;
virtual Ref<Script> get_base_script() const;
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 ScriptInstance *instance_create(Object *p_this);
virtual bool instance_has(const Object *p_this) const;
virtual bool has_source_code() const;
virtual String get_source_code() const;
- virtual void set_source_code(const String& p_code);
+ virtual void set_source_code(const String &p_code);
virtual void update_exports();
- virtual Error reload(bool p_keep_state=false);
+ virtual Error reload(bool p_keep_state = false);
virtual String get_node_type() const;
- 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);
- Error load_byte_code(const String& p_path);
+ 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);
+ Error load_byte_code(const String &p_path);
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;
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 bool has_method(const StringName &p_method) const;
+ virtual MethodInfo get_method_info(const StringName &p_method) const;
virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
-
virtual ScriptLanguage *get_language() const;
- virtual int get_member_line(const StringName& p_member) const {
+ virtual int get_member_line(const StringName &p_member) const {
#ifdef TOOLS_ENABLED
if (member_lines.has(p_member))
return member_lines[p_member];
else
#endif
return -1;
-
}
GDScript();
@@ -212,37 +202,34 @@ public:
};
class GDInstance : public ScriptInstance {
-friend class GDScript;
-friend class GDFunction;
-friend class GDFunctions;
-friend class GDCompiler;
+ friend class GDScript;
+ friend class GDFunction;
+ friend class GDFunctions;
+ friend class GDCompiler;
Object *owner;
Ref<GDScript> script;
#ifdef DEBUG_ENABLED
- Map<StringName,int> member_indices_cache; //used only for hot script reloading
+ Map<StringName, int> member_indices_cache; //used only for hot script reloading
#endif
Vector<Variant> members;
bool base_ref;
-
- void _ml_call_reversed(GDScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount);
+ void _ml_call_reversed(GDScript *sptr, const StringName &p_method, const Variant **p_args, int p_argcount);
public:
+ _FORCE_INLINE_ Object *get_owner() { return owner; }
- _FORCE_INLINE_ Object* get_owner() { return owner; }
-
- virtual bool set(const StringName& p_name, const Variant& p_value);
- virtual bool get(const StringName& p_name, Variant &r_ret) const;
+ 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=NULL) const;
-
+ virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const;
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,Variant::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);
+ virtual bool has_method(const StringName &p_method) const;
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::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]; }
@@ -252,27 +239,24 @@ public:
virtual ScriptLanguage *get_language();
- void set_path(const String& p_path);
+ void set_path(const String &p_path);
void reload_members();
- virtual RPCMode get_rpc_mode(const StringName& p_method) const;
- virtual RPCMode get_rset_mode(const StringName& p_variable) const;
-
+ virtual RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual RPCMode get_rset_mode(const StringName &p_variable) const;
GDInstance();
~GDInstance();
-
};
class GDScriptLanguage : public ScriptLanguage {
static GDScriptLanguage *singleton;
- Variant* _global_array;
+ Variant *_global_array;
Vector<Variant> global_array;
- Map<StringName,int> globals;
-
+ Map<StringName, int> globals;
struct CallLevel {
@@ -281,10 +265,8 @@ class GDScriptLanguage : public ScriptLanguage {
GDInstance *instance;
int *ip;
int *line;
-
};
-
int _debug_parse_err_line;
String _debug_parse_err_file;
String _debug_error;
@@ -292,65 +274,61 @@ class GDScriptLanguage : public ScriptLanguage {
int _debug_max_call_stack;
CallLevel *_call_stack;
- void _add_global(const StringName& p_name,const Variant& p_value);
+ void _add_global(const StringName &p_name, const Variant &p_value);
-friend class GDInstance;
+ friend class GDInstance;
Mutex *lock;
-
-
-
-friend class GDScript;
+ friend class GDScript;
SelfList<GDScript>::List script_list;
-friend class GDFunction;
+ friend class GDFunction;
SelfList<GDFunction>::List function_list;
bool profiling;
uint64_t script_frame_time;
-public:
-
+public:
int calls;
- bool debug_break(const String& p_error,bool p_allow_continue=true);
- bool debug_break_parse(const String& p_file, int p_line,const String& p_error);
+ bool debug_break(const String &p_error, bool p_allow_continue = true);
+ bool debug_break_parse(const String &p_file, int p_line, const String &p_error);
- _FORCE_INLINE_ void enter_function(GDInstance *p_instance,GDFunction *p_function, Variant *p_stack, int *p_ip, int *p_line) {
+ _FORCE_INLINE_ void enter_function(GDInstance *p_instance, GDFunction *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 (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0)
- ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() +1 );
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0)
+ ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() + 1);
if (_debug_call_stack_pos >= _debug_max_call_stack) {
//stack overflow
- _debug_error="Stack Overflow (Stack Size: "+itos(_debug_max_call_stack)+")";
+ _debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")";
ScriptDebugger::get_singleton()->debug(this);
return;
}
- _call_stack[_debug_call_stack_pos].stack=p_stack;
- _call_stack[_debug_call_stack_pos].instance=p_instance;
- _call_stack[_debug_call_stack_pos].function=p_function;
- _call_stack[_debug_call_stack_pos].ip=p_ip;
- _call_stack[_debug_call_stack_pos].line=p_line;
+ _call_stack[_debug_call_stack_pos].stack = p_stack;
+ _call_stack[_debug_call_stack_pos].instance = p_instance;
+ _call_stack[_debug_call_stack_pos].function = p_function;
+ _call_stack[_debug_call_stack_pos].ip = p_ip;
+ _call_stack[_debug_call_stack_pos].line = p_line;
_debug_call_stack_pos++;
}
_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 (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0)
- ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() -1 );
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0)
+ ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() - 1);
- if (_debug_call_stack_pos==0) {
+ if (_debug_call_stack_pos == 0) {
- _debug_error="Stack Underflow (Engine Bug)";
+ _debug_error = "Stack Underflow (Engine Bug)";
ScriptDebugger::get_singleton()->debug(this);
return;
}
@@ -358,16 +336,15 @@ public:
_debug_call_stack_pos--;
}
-
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);
- for(int i=0;i<_debug_call_stack_pos;i++) {
- csi[_debug_call_stack_pos-i-1].line=_call_stack[i].line?*_call_stack[i].line:0;
- csi[_debug_call_stack_pos-i-1].script=Ref<GDScript>(_call_stack[i].function->get_script());
+ for (int i = 0; i < _debug_call_stack_pos; i++) {
+ csi[_debug_call_stack_pos - i - 1].line = _call_stack[i].line ? *_call_stack[i].line : 0;
+ csi[_debug_call_stack_pos - i - 1].script = Ref<GDScript>(_call_stack[i].function->get_script());
}
return csi;
}
@@ -383,10 +360,9 @@ public:
} strings;
-
_FORCE_INLINE_ int get_global_array_size() const { return global_array.size(); }
- _FORCE_INLINE_ Variant* get_global_array() { return _global_array; }
- _FORCE_INLINE_ const Map<StringName,int>& get_global_map() { return globals; }
+ _FORCE_INLINE_ Variant *get_global_array() { return _global_array; }
+ _FORCE_INLINE_ const Map<StringName, int> &get_global_map() { return globals; }
_FORCE_INLINE_ static GDScriptLanguage *get_singleton() { return singleton; }
@@ -396,26 +372,25 @@ public:
virtual void init();
virtual String get_type() const;
virtual String get_extension() const;
- virtual Error execute_file(const String& p_path) ;
+ virtual Error execute_file(const String &p_path);
virtual void finish();
/* 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 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=NULL) const;
+ virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const;
+ 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 = NULL) const;
virtual Script *create_script() const;
virtual bool has_named_classes() 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 PoolStringArray& p_args) const;
- virtual Error complete_code(const String& p_code, const String& p_base_path, Object*p_owner,List<String>* r_options,String& r_call_hint);
+ virtual int find_function(const String &p_function, const String &p_code) const;
+ virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const;
+ virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint);
#ifdef TOOLS_ENABLED
- virtual Error lookup_code(const String& p_code, const String& p_symbol, const String& p_base_path, Object*p_owner, LookupResult& r_result);
+ virtual Error lookup_code(const String &p_code, const String &p_symbol, const String &p_base_path, Object *p_owner, LookupResult &r_result);
#endif
- virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const;
- virtual void add_global_constant(const StringName& p_variable,const Variant& p_value);
-
+ virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const;
+ virtual void add_global_constant(const StringName &p_variable, const Variant &p_value);
/* DEBUGGER FUNCTIONS */
@@ -424,24 +399,24 @@ public:
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;
- virtual void debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual void debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1);
+ virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1);
virtual void reload_all_scripts();
- virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload);
+ virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload);
virtual void frame();
virtual void get_public_functions(List<MethodInfo> *p_functions) const;
- virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const;
+ virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const;
virtual void profiling_start();
virtual void profiling_stop();
- 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);
+ 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);
/* LOADER FUNCTIONS */
@@ -451,24 +426,19 @@ public:
~GDScriptLanguage();
};
-
class ResourceFormatLoaderGDScript : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
class ResourceFormatSaverGDScript : 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;
-
+ 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;
};
#endif // GD_SCRIPT_H
diff --git a/modules/gdscript/gd_tokenizer.cpp b/modules/gdscript/gd_tokenizer.cpp
index 54b9624e8e..981924191f 100644
--- a/modules/gdscript/gd_tokenizer.cpp
+++ b/modules/gdscript/gd_tokenizer.cpp
@@ -27,212 +27,205 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "gd_tokenizer.h"
-#include "print_string.h"
#include "gd_functions.h"
#include "io/marshalls.h"
#include "map.h"
+#include "print_string.h"
-const char* GDTokenizer::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",
-"do",
-"while",
-"switch (reserved)",
-"case (reserved)",
-"break",
-"continue",
-"pass",
-"return",
-"match",
-"func",
-"class",
-"extends",
-"onready",
-"tool",
-"static",
-"export",
-"setget",
-"const",
-"var",
-"enum",
-"preload",
-"assert",
-"yield",
-"signal",
-"breakpoint",
-"rpc",
-"sync",
-"master",
-"slave",
-"'['",
-"']'",
-"'{'",
-"'}'",
-"'('",
-"')'",
-"','",
-"';'",
-"'.'",
-"'?'",
-"':'",
-"'\\n'",
-"PI",
-"_",
-"INF",
-"NAN",
-"Error",
-"EOF",
-"Cursor"};
+const char *GDTokenizer::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",
+ "do",
+ "while",
+ "switch (reserved)",
+ "case (reserved)",
+ "break",
+ "continue",
+ "pass",
+ "return",
+ "match",
+ "func",
+ "class",
+ "extends",
+ "onready",
+ "tool",
+ "static",
+ "export",
+ "setget",
+ "const",
+ "var",
+ "enum",
+ "preload",
+ "assert",
+ "yield",
+ "signal",
+ "breakpoint",
+ "rpc",
+ "sync",
+ "master",
+ "slave",
+ "'['",
+ "']'",
+ "'{'",
+ "'}'",
+ "'('",
+ "')'",
+ "','",
+ "';'",
+ "'.'",
+ "'?'",
+ "':'",
+ "'\\n'",
+ "PI",
+ "_",
+ "INF",
+ "NAN",
+ "Error",
+ "EOF",
+ "Cursor"
+};
const char *GDTokenizer::get_token_name(Token p_token) {
- ERR_FAIL_INDEX_V(p_token,TK_MAX,"<error>");
+ ERR_FAIL_INDEX_V(p_token, TK_MAX, "<error>");
return token_names[p_token];
}
static bool _is_text_char(CharType c) {
- return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_';
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
static bool _is_number(CharType c) {
- return (c>='0' && c<='9');
+ return (c >= '0' && c <= '9');
}
static bool _is_hex(CharType c) {
- return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
-void GDTokenizerText::_make_token(Token p_type) {
+void GDTokenizerText::_make_token(Token p_type) {
- TokenData &tk=tk_rb[tk_rb_pos];
+ TokenData &tk = tk_rb[tk_rb_pos];
- tk.type=p_type;
- tk.line=line;
- tk.col=column;
+ tk.type = p_type;
+ tk.line = line;
+ tk.col = column;
- tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE;
+ tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
}
-void GDTokenizerText::_make_identifier(const StringName& p_identifier) {
+void GDTokenizerText::_make_identifier(const StringName &p_identifier) {
- TokenData &tk=tk_rb[tk_rb_pos];
+ 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;
+ tk.type = TK_IDENTIFIER;
+ tk.identifier = p_identifier;
+ tk.line = line;
+ tk.col = column;
+ tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
}
-void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) {
-
- TokenData &tk=tk_rb[tk_rb_pos];
+void GDTokenizerText::_make_built_in_func(GDFunctions::Function p_func) {
- tk.type=TK_BUILT_IN_FUNC;
- tk.func=p_func;
- tk.line=line;
- tk.col=column;
+ TokenData &tk = tk_rb[tk_rb_pos];
- tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE;
+ 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;
}
-void GDTokenizerText::_make_constant(const Variant& p_constant) {
+void GDTokenizerText::_make_constant(const Variant &p_constant) {
- TokenData &tk=tk_rb[tk_rb_pos];
+ 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;
+ tk.type = TK_CONSTANT;
+ tk.constant = p_constant;
+ tk.line = line;
+ tk.col = column;
+ tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
}
-void GDTokenizerText::_make_type(const Variant::Type& p_type) {
-
-
- TokenData &tk=tk_rb[tk_rb_pos];
+void GDTokenizerText::_make_type(const Variant::Type &p_type) {
- tk.type=TK_BUILT_IN_TYPE;
- tk.vtype=p_type;
- tk.line=line;
- tk.col=column;
+ TokenData &tk = tk_rb[tk_rb_pos];
- tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE;
+ 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 GDTokenizerText::_make_error(const String &p_error) {
-void GDTokenizerText::_make_error(const String& p_error) {
-
- error_flag=true;
- last_error=p_error;
-
- 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;
+ error_flag = true;
+ last_error = p_error;
+ 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;
}
-
void GDTokenizerText::_make_newline(int p_spaces) {
- TokenData &tk=tk_rb[tk_rb_pos];
- tk.type=TK_NEWLINE;
- tk.constant=p_spaces;
- tk.line=line;
- tk.col=column;
- tk_rb_pos=(tk_rb_pos+1)%TK_RB_SIZE;
+ TokenData &tk = tk_rb[tk_rb_pos];
+ tk.type = TK_NEWLINE;
+ tk.constant = p_spaces;
+ tk.line = line;
+ tk.col = column;
+ tk_rb_pos = (tk_rb_pos + 1) % TK_RB_SIZE;
}
void GDTokenizerText::_advance() {
@@ -243,29 +236,32 @@ void GDTokenizerText::_advance() {
return;
}
- if (code_pos>=len) {
+ 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; }
+#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_node_path = false;
+ StringMode string_mode = STRING_DOUBLE_QUOTE;
- bool is_node_path = false;
- StringMode string_mode=STRING_DOUBLE_QUOTE;
-
- switch(GETCHAR(0)) {
+ switch (GETCHAR(0)) {
case 0:
_make_token(TK_EOF);
break;
case '\\':
INCPOS(1);
- if (GETCHAR(0)=='\r') {
+ if (GETCHAR(0) == '\r') {
INCPOS(1);
}
- if (GETCHAR(0)!='\n') {
+ if (GETCHAR(0) != '\n') {
_make_error("Expected newline after '\\'.");
return;
}
@@ -273,7 +269,7 @@ void GDTokenizerText::_advance() {
INCPOS(1);
line++;
- while(GETCHAR(0)==' ' || GETCHAR(0)=='\t') {
+ while (GETCHAR(0) == ' ' || GETCHAR(0) == '\t') {
INCPOS(1);
}
@@ -286,9 +282,9 @@ void GDTokenizerText::_advance() {
case '\n': {
line++;
INCPOS(1);
- column=1;
- int i=0;
- while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') {
+ column = 1;
+ int i = 0;
+ while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') {
i++;
}
@@ -298,19 +294,19 @@ void GDTokenizerText::_advance() {
#if 1 //py style tokenizer
case '#': { // line comment skip
- while(GETCHAR(0)!='\n') {
+ while (GETCHAR(0) != '\n') {
code_pos++;
- if (GETCHAR(0)==0) { //end of file
+ if (GETCHAR(0) == 0) { //end of file
//_make_error("Unterminated Comment");
_make_token(TK_EOF);
return;
}
}
INCPOS(1);
- column=1;
+ column = 1;
line++;
- int i=0;
- while(GETCHAR(i)==' ' || GETCHAR(i)=='\t') {
+ int i = 0;
+ while (GETCHAR(i) == ' ' || GETCHAR(i) == '\t') {
i++;
}
_make_newline(i);
@@ -320,7 +316,7 @@ void GDTokenizerText::_advance() {
#endif
case '/': {
- switch(GETCHAR(1)) {
+ switch (GETCHAR(1)) {
#if 0 // c style tokenizer
case '*': { // block comment
int pos = code_pos+2;
@@ -376,11 +372,10 @@ void GDTokenizerText::_advance() {
} break;
default:
_make_token(TK_OP_DIV);
-
}
} break;
case '=': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_EQUAL);
INCPOS(1);
@@ -389,12 +384,12 @@ void GDTokenizerText::_advance() {
} break;
case '<': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_LESS_EQUAL);
INCPOS(1);
- } else if (GETCHAR(1)=='<') {
- if (GETCHAR(2)=='=') {
+ } else if (GETCHAR(1) == '<') {
+ if (GETCHAR(2) == '=') {
_make_token(TK_OP_ASSIGN_SHIFT_LEFT);
INCPOS(1);
} else {
@@ -406,11 +401,11 @@ void GDTokenizerText::_advance() {
} break;
case '>': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_GREATER_EQUAL);
INCPOS(1);
- } else if (GETCHAR(1)=='>') {
- if (GETCHAR(2)=='=') {
+ } else if (GETCHAR(1) == '>') {
+ if (GETCHAR(2) == '=') {
_make_token(TK_OP_ASSIGN_SHIFT_RIGHT);
INCPOS(1);
@@ -424,7 +419,7 @@ void GDTokenizerText::_advance() {
} break;
case '!': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_NOT_EQUAL);
INCPOS(1);
} else {
@@ -468,7 +463,7 @@ void GDTokenizerText::_advance() {
_make_token(TK_DOLLAR); //for the get_node() shortener
break;
case '^': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_BIT_XOR);
INCPOS(1);
} else {
@@ -480,11 +475,11 @@ void GDTokenizerText::_advance() {
_make_token(TK_OP_BIT_INVERT);
break;
case '&': {
- if (GETCHAR(1)=='&') {
+ if (GETCHAR(1) == '&') {
_make_token(TK_OP_AND);
INCPOS(1);
- } else if (GETCHAR(1)=='=') {
+ } else if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_BIT_AND);
INCPOS(1);
} else {
@@ -492,11 +487,11 @@ void GDTokenizerText::_advance() {
}
} break;
case '|': {
- if (GETCHAR(1)=='|') {
+ if (GETCHAR(1) == '|') {
_make_token(TK_OP_OR);
INCPOS(1);
- } else if (GETCHAR(1)=='=') {
+ } else if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_BIT_OR);
INCPOS(1);
} else {
@@ -505,7 +500,7 @@ void GDTokenizerText::_advance() {
} break;
case '*': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_MUL);
INCPOS(1);
} else {
@@ -514,10 +509,10 @@ void GDTokenizerText::_advance() {
} break;
case '+': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_ADD);
INCPOS(1);
- /*
+ /*
} else if (GETCHAR(1)=='+') {
_make_token(TK_OP_PLUS_PLUS);
INCPOS(1);
@@ -529,10 +524,10 @@ void GDTokenizerText::_advance() {
} break;
case '-': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_SUB);
INCPOS(1);
- /*
+ /*
} else if (GETCHAR(1)=='-') {
_make_token(TK_OP_MINUS_MINUS);
INCPOS(1);
@@ -543,7 +538,7 @@ void GDTokenizerText::_advance() {
} break;
case '%': {
- if (GETCHAR(1)=='=') {
+ if (GETCHAR(1) == '=') {
_make_token(TK_OP_ASSIGN_MOD);
INCPOS(1);
} else {
@@ -551,106 +546,103 @@ void GDTokenizerText::_advance() {
}
} break;
case '@':
- if( CharType(GETCHAR(1))!='"' && CharType(GETCHAR(1))!='\'' ) {
+ if (CharType(GETCHAR(1)) != '"' && CharType(GETCHAR(1)) != '\'') {
_make_error("Unexpected '@'");
return;
}
INCPOS(1);
- is_node_path=true;
+ is_node_path = true;
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;
+ 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) {
+ while (true) {
+ if (CharType(GETCHAR(i)) == 0) {
_make_error("Unterminated String");
return;
- } else if( string_mode==STRING_DOUBLE_QUOTE && CharType(GETCHAR(i))=='"' ) {
+ } else if (string_mode == STRING_DOUBLE_QUOTE && CharType(GETCHAR(i)) == '"') {
break;
- } else if( string_mode==STRING_SINGLE_QUOTE && CharType(GETCHAR(i))=='\'' ) {
+ } 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;
+ } 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') {
+ } else if (string_mode != STRING_MULTILINE && CharType(GETCHAR(i)) == '\n') {
_make_error("Unexpected EOL at String.");
return;
- } else if( CharType(GETCHAR(i))==0xFFFF) {
+ } else if (CharType(GETCHAR(i)) == 0xFFFF) {
//string ends here, next will be TK
i--;
break;
- } else if (CharType(GETCHAR(i))=='\\') {
+ } else if (CharType(GETCHAR(i)) == '\\') {
//escaped characters...
i++;
CharType next = GETCHAR(i);
- if (next==0) {
+ 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
+ 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': {
//hexnumbarh - oct is deprecated
- i+=1;
- for(int j=0;j<4;j++) {
- CharType c = GETCHAR(i+j);
- if (c==0) {
+ i += 1;
+ for (int j = 0; j < 4; j++) {
+ CharType c = GETCHAR(i + j);
+ if (c == 0) {
_make_error("Unterminated String");
return;
}
- if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) {
_make_error("Malformed hex constant in string");
return;
}
CharType v;
- 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;
+ 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 {
ERR_PRINT("BUG");
- v=0;
+ v = 0;
}
- res<<=4;
- res|=v;
-
-
+ res <<= 4;
+ res |= v;
}
- i+=3;
+ i += 3;
} break;
default: {
@@ -660,15 +652,15 @@ void GDTokenizerText::_advance() {
} break;
}
- str+=res;
+ str += res;
} else {
- if (CharType(GETCHAR(i))=='\n') {
+ if (CharType(GETCHAR(i)) == '\n') {
line++;
- column=1;
+ column = 1;
}
- str+=CharType(GETCHAR(i));
+ str += CharType(GETCHAR(i));
}
i++;
}
@@ -686,54 +678,54 @@ void GDTokenizerText::_advance() {
} break;
default: {
- if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) {
+ 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 sign_found=false;
+ bool period_found = false;
+ bool exponent_found = false;
+ bool hexa_found = false;
+ bool sign_found = false;
String str;
- int i=0;
+ int i = 0;
- while(true) {
- if (GETCHAR(i)=='.') {
+ while (true) {
+ if (GETCHAR(i) == '.') {
if (period_found || exponent_found) {
_make_error("Invalid numeric constant at '.'");
return;
}
- period_found=true;
- } else if (GETCHAR(i)=='x') {
- if (hexa_found || str.length()!=1 || !( (i==1 && str[0]=='0') || (i==2 && str[1]=='0' && str[0]=='-') ) ) {
+ period_found = true;
+ } else if (GETCHAR(i) == 'x') {
+ if (hexa_found || str.length() != 1 || !((i == 1 && str[0] == '0') || (i == 2 && str[1] == '0' && str[0] == '-'))) {
_make_error("Invalid numeric constant at 'x'");
return;
}
- hexa_found=true;
- } else if (!hexa_found && GETCHAR(i)=='e') {
+ hexa_found = true;
+ } else if (!hexa_found && GETCHAR(i) == 'e') {
if (hexa_found || exponent_found) {
_make_error("Invalid numeric constant at 'e'");
return;
}
- exponent_found=true;
+ exponent_found = true;
} else if (_is_number(GETCHAR(i))) {
//all ok
} else if (hexa_found && _is_hex(GETCHAR(i))) {
- } else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) {
+ } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) {
if (sign_found) {
_make_error("Invalid numeric constant at '-'");
return;
}
- sign_found=true;
+ sign_found = true;
} else
break;
- str+=CharType(GETCHAR(i));
+ 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);
+ if (!(_is_number(str[str.length() - 1]) || (hexa_found && _is_hex(str[str.length() - 1])))) {
+ _make_error("Invalid numeric constant: " + str);
return;
}
@@ -748,13 +740,12 @@ void GDTokenizerText::_advance() {
} else {
int64_t val = str.to_int64();
_make_constant(val);
-
}
return;
}
- if (GETCHAR(0)=='.') {
+ if (GETCHAR(0) == '.') {
//parse period
_make_token(TK_PERIOD);
break;
@@ -763,74 +754,76 @@ void GDTokenizerText::_advance() {
if (_is_text_char(GETCHAR(0))) {
// parse identifier
String str;
- str+=CharType(GETCHAR(0));
+ str += CharType(GETCHAR(0));
- int i=1;
- while(_is_text_char(GETCHAR(i))) {
- str+=CharType(GETCHAR(i));
+ int i = 1;
+ while (_is_text_char(GETCHAR(i))) {
+ str += CharType(GETCHAR(i));
i++;
}
- bool identifier=false;
+ bool identifier = false;
- if (str=="null") {
+ if (str == "null") {
_make_constant(Variant());
- } else if (str=="true") {
+ } else if (str == "true") {
_make_constant(true);
- } else if (str=="false") {
+ } else if (str == "false") {
_make_constant(false);
} else {
- bool found=false;
+ bool found = false;
- struct _bit { Variant::Type type; const char *text;};
+ struct _bit {
+ Variant::Type type;
+ const char *text;
+ };
//built in types
- static const _bit type_list[]={
+ static const _bit type_list[] = {
//types
- {Variant::BOOL,"bool"},
- {Variant::INT,"int"},
- {Variant::REAL,"float"},
- {Variant::STRING,"String"},
- {Variant::VECTOR2,"Vector2"},
- {Variant::RECT2,"Rect2"},
- {Variant::TRANSFORM2D,"Transform2D"},
- {Variant::VECTOR3,"Vector3"},
- {Variant::RECT3,"Rect3"},
- {Variant::PLANE,"Plane"},
- {Variant::QUAT,"Quat"},
- {Variant::BASIS,"Basis"},
- {Variant::TRANSFORM,"Transform"},
- {Variant::COLOR,"Color"},
- {Variant::IMAGE,"Image"},
- {Variant::_RID,"RID"},
- {Variant::OBJECT,"Object"},
- {Variant::INPUT_EVENT,"InputEvent"},
- {Variant::NODE_PATH,"NodePath"},
- {Variant::DICTIONARY,"Dictionary"},
- {Variant::ARRAY,"Array"},
- {Variant::POOL_BYTE_ARRAY,"PoolByteArray"},
- {Variant::POOL_INT_ARRAY,"PoolIntArray"},
- {Variant::POOL_REAL_ARRAY,"PoolFloatArray"},
- {Variant::POOL_STRING_ARRAY,"PoolStringArray"},
- {Variant::POOL_VECTOR2_ARRAY,"PoolVector2Array"},
- {Variant::POOL_VECTOR3_ARRAY,"PoolVector3Array"},
- {Variant::POOL_COLOR_ARRAY,"PoolColorArray"},
- {Variant::VARIANT_MAX,NULL},
+ { Variant::BOOL, "bool" },
+ { Variant::INT, "int" },
+ { Variant::REAL, "float" },
+ { Variant::STRING, "String" },
+ { Variant::VECTOR2, "Vector2" },
+ { Variant::RECT2, "Rect2" },
+ { Variant::TRANSFORM2D, "Transform2D" },
+ { Variant::VECTOR3, "Vector3" },
+ { Variant::RECT3, "Rect3" },
+ { Variant::PLANE, "Plane" },
+ { Variant::QUAT, "Quat" },
+ { Variant::BASIS, "Basis" },
+ { Variant::TRANSFORM, "Transform" },
+ { Variant::COLOR, "Color" },
+ { Variant::IMAGE, "Image" },
+ { Variant::_RID, "RID" },
+ { Variant::OBJECT, "Object" },
+ { Variant::INPUT_EVENT, "InputEvent" },
+ { Variant::NODE_PATH, "NodePath" },
+ { Variant::DICTIONARY, "Dictionary" },
+ { Variant::ARRAY, "Array" },
+ { Variant::POOL_BYTE_ARRAY, "PoolByteArray" },
+ { Variant::POOL_INT_ARRAY, "PoolIntArray" },
+ { Variant::POOL_REAL_ARRAY, "PoolFloatArray" },
+ { Variant::POOL_STRING_ARRAY, "PoolStringArray" },
+ { Variant::POOL_VECTOR2_ARRAY, "PoolVector2Array" },
+ { Variant::POOL_VECTOR3_ARRAY, "PoolVector3Array" },
+ { Variant::POOL_COLOR_ARRAY, "PoolColorArray" },
+ { Variant::VARIANT_MAX, NULL },
};
{
+ int idx = 0;
- int idx=0;
-
- while(type_list[idx].text) {
+ while (type_list[idx].text) {
- if (str==type_list[idx].text) {
+ if (str == type_list[idx].text) {
_make_type(type_list[idx].type);
- found=true;
+ found = true;
break;
}
idx++;
@@ -841,12 +834,12 @@ void GDTokenizerText::_advance() {
//built in func?
- for(int i=0;i<GDFunctions::FUNC_MAX;i++) {
+ for (int i = 0; i < GDFunctions::FUNC_MAX; i++) {
- if (str==GDFunctions::get_func_name(GDFunctions::Function(i))) {
+ if (str == GDFunctions::get_func_name(GDFunctions::Function(i))) {
_make_built_in_func(GDFunctions::Function(i));
- found=true;
+ found = true;
break;
}
}
@@ -856,66 +849,68 @@ void GDTokenizerText::_advance() {
if (!found) {
+ struct _kws {
+ Token token;
+ const char *text;
+ };
- struct _kws { Token token; const char *text;};
-
- static const _kws keyword_list[]={
+ static const _kws keyword_list[] = {
//ops
- {TK_OP_IN,"in"},
- {TK_OP_NOT,"not"},
- {TK_OP_OR,"or"},
- {TK_OP_AND,"and"},
+ { TK_OP_IN, "in" },
+ { TK_OP_NOT, "not" },
+ { TK_OP_OR, "or" },
+ { TK_OP_AND, "and" },
//func
- {TK_PR_FUNCTION,"func"},
- {TK_PR_CLASS,"class"},
- {TK_PR_EXTENDS,"extends"},
- {TK_PR_ONREADY,"onready"},
- {TK_PR_TOOL,"tool"},
- {TK_PR_STATIC,"static"},
- {TK_PR_EXPORT,"export"},
- {TK_PR_SETGET,"setget"},
- {TK_PR_VAR,"var"},
- {TK_PR_PRELOAD,"preload"},
- {TK_PR_ASSERT,"assert"},
- {TK_PR_YIELD,"yield"},
- {TK_PR_SIGNAL,"signal"},
- {TK_PR_BREAKPOINT,"breakpoint"},
- {TK_PR_REMOTE,"remote"},
- {TK_PR_MASTER,"master"},
- {TK_PR_SLAVE,"slave"},
- {TK_PR_SYNC,"sync"},
- {TK_PR_CONST,"const"},
- {TK_PR_ENUM,"enum"},
+ { TK_PR_FUNCTION, "func" },
+ { TK_PR_CLASS, "class" },
+ { TK_PR_EXTENDS, "extends" },
+ { TK_PR_ONREADY, "onready" },
+ { TK_PR_TOOL, "tool" },
+ { TK_PR_STATIC, "static" },
+ { TK_PR_EXPORT, "export" },
+ { TK_PR_SETGET, "setget" },
+ { TK_PR_VAR, "var" },
+ { TK_PR_PRELOAD, "preload" },
+ { TK_PR_ASSERT, "assert" },
+ { TK_PR_YIELD, "yield" },
+ { TK_PR_SIGNAL, "signal" },
+ { TK_PR_BREAKPOINT, "breakpoint" },
+ { TK_PR_REMOTE, "remote" },
+ { TK_PR_MASTER, "master" },
+ { TK_PR_SLAVE, "slave" },
+ { TK_PR_SYNC, "sync" },
+ { TK_PR_CONST, "const" },
+ { TK_PR_ENUM, "enum" },
//controlflow
- {TK_CF_IF,"if"},
- {TK_CF_ELIF,"elif"},
- {TK_CF_ELSE,"else"},
- {TK_CF_FOR,"for"},
- {TK_CF_WHILE,"while"},
- {TK_CF_DO,"do"},
- {TK_CF_SWITCH,"switch"},
- {TK_CF_CASE,"case"},
- {TK_CF_BREAK,"break"},
- {TK_CF_CONTINUE,"continue"},
- {TK_CF_RETURN,"return"},
- {TK_CF_MATCH, "match"},
- {TK_CF_PASS,"pass"},
- {TK_SELF,"self"},
- {TK_CONST_PI,"PI"},
- {TK_WILDCARD,"_"},
- {TK_CONST_INF,"INF"},
- {TK_CONST_NAN,"NAN"},
- {TK_ERROR,NULL}
+ { TK_CF_IF, "if" },
+ { TK_CF_ELIF, "elif" },
+ { TK_CF_ELSE, "else" },
+ { TK_CF_FOR, "for" },
+ { TK_CF_WHILE, "while" },
+ { TK_CF_DO, "do" },
+ { TK_CF_SWITCH, "switch" },
+ { TK_CF_CASE, "case" },
+ { TK_CF_BREAK, "break" },
+ { TK_CF_CONTINUE, "continue" },
+ { TK_CF_RETURN, "return" },
+ { TK_CF_MATCH, "match" },
+ { TK_CF_PASS, "pass" },
+ { TK_SELF, "self" },
+ { TK_CONST_PI, "PI" },
+ { TK_WILDCARD, "_" },
+ { TK_CONST_INF, "INF" },
+ { TK_CONST_NAN, "NAN" },
+ { TK_ERROR, NULL }
};
- int idx=0;
- found=false;
+ int idx = 0;
+ found = false;
- while(keyword_list[idx].text) {
+ while (keyword_list[idx].text) {
- if (str==keyword_list[idx].text) {
+ if (str == keyword_list[idx].text) {
_make_token(keyword_list[idx].token);
- found=true;
+ found = true;
break;
}
idx++;
@@ -923,10 +918,9 @@ void GDTokenizerText::_advance() {
}
if (!found)
- identifier=true;
+ identifier = true;
}
-
if (identifier) {
_make_identifier(str);
}
@@ -943,381 +937,358 @@ void GDTokenizerText::_advance() {
INCPOS(1);
break;
}
-
}
-void GDTokenizerText::set_code(const String& p_code) {
+void GDTokenizerText::set_code(const String &p_code) {
- code=p_code;
+ code = p_code;
len = p_code.length();
if (len) {
- _code=&code[0];
+ _code = &code[0];
} else {
- _code=NULL;
+ _code = NULL;
}
- 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;
- last_error="";
- for(int i=0;i<MAX_LOOKAHEAD+1;i++)
+ 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;
+ last_error = "";
+ for (int i = 0; i < MAX_LOOKAHEAD + 1; i++)
_advance();
}
GDTokenizerText::Token GDTokenizerText::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);
+ 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;
+ int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
return tk_rb[ofs].type;
}
int GDTokenizerText::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);
+ 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;
+ int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
return tk_rb[ofs].line;
}
int GDTokenizerText::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);
+ 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;
+ int ofs = (TK_RB_SIZE + tk_rb_pos + p_offset - MAX_LOOKAHEAD - 1) % TK_RB_SIZE;
return tk_rb[ofs].col;
}
-const Variant& GDTokenizerText::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);
+const Variant &GDTokenizerText::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);
+ 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;
}
StringName GDTokenizerText::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());
+ 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());
+ 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;
-
}
GDFunctions::Function GDTokenizerText::get_token_built_in_func(int p_offset) const {
- ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX);
- ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, GDFunctions::FUNC_MAX);
+ ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, GDFunctions::FUNC_MAX);
+ ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, GDFunctions::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,GDFunctions::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, GDFunctions::FUNC_MAX);
return tk_rb[ofs].func;
-
}
Variant::Type GDTokenizerText::get_token_type(int p_offset) const {
- ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, Variant::NIL);
- ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, Variant::NIL);
+ ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, Variant::NIL);
+ ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, Variant::NIL);
- 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);
+ 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;
-
}
-
int GDTokenizerText::get_token_line_indent(int p_offset) const {
- ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, 0);
- ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, 0);
+ ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, 0);
+ ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, 0);
- 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);
+ 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;
-
}
String GDTokenizerText::get_token_error(int p_offset) const {
- ERR_FAIL_COND_V( p_offset <= -MAX_LOOKAHEAD, String());
- ERR_FAIL_COND_V( p_offset >= MAX_LOOKAHEAD, String());
+ ERR_FAIL_COND_V(p_offset <= -MAX_LOOKAHEAD, String());
+ ERR_FAIL_COND_V(p_offset >= MAX_LOOKAHEAD, String());
- 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());
+ 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;
}
void GDTokenizerText::advance(int p_amount) {
- ERR_FAIL_COND( p_amount <=0 );
- for(int i=0;i<p_amount;i++)
+ ERR_FAIL_COND(p_amount <= 0);
+ for (int i = 0; i < p_amount; i++)
_advance();
}
-
-
-
-
-
-
-
-
-
-
//////////////////////////////////////////////////////////////////////////////////////////////////////
#define BYTECODE_VERSION 12
-Error GDTokenizerBuffer::set_code_buffer(const Vector<uint8_t> & p_buffer) {
-
+Error GDTokenizerBuffer::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);
+ 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]);
- if (version>BYTECODE_VERSION) {
+ if (version > BYTECODE_VERSION) {
ERR_EXPLAIN("Bytecode is too New! Please use a newer engine version.");
- ERR_FAIL_COND_V(version>BYTECODE_VERSION,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(version > BYTECODE_VERSION, ERR_INVALID_DATA);
}
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;
+ const uint8_t *b = buf;
- b=&buf[24];
- total_len-=24;
+ b = &buf[24];
+ total_len -= 24;
identifiers.resize(identifier_count);
- for(int i=0;i<identifier_count;i++) {
+ 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;
+ 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[j]=b[j]^0xb6;
+ for (int j = 0; j < len; j++) {
+ cs[j] = b[j] ^ 0xb6;
}
- cs[cs.size()-1]=0;
+ cs[cs.size() - 1] = 0;
String s;
- s.parse_utf8((const char*)cs.ptr());
- b+=len;
- total_len-=len+4;
- identifiers[i]=s;
+ s.parse_utf8((const char *)cs.ptr());
+ b += len;
+ total_len -= len + 4;
+ identifiers[i] = s;
}
constants.resize(constant_count);
- for(int i=0;i<constant_count;i++) {
+ for (int i = 0; i < constant_count; i++) {
Variant v;
int len;
- Error err = decode_variant(v,b,total_len,&len);
+ Error err = decode_variant(v, b, total_len, &len);
if (err)
return err;
- b+=len;
- total_len-=len;
- constants[i]=v;
-
+ b += len;
+ total_len -= len;
+ constants[i] = v;
}
- ERR_FAIL_COND_V(line_count*8>total_len,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(line_count * 8 > total_len, ERR_INVALID_DATA);
- for(int i=0;i<line_count;i++) {
+ for (int i = 0; i < line_count; i++) {
- uint32_t token=decode_uint32(b);
- b+=4;
- uint32_t linecol=decode_uint32(b);
- b+=4;
+ uint32_t token = decode_uint32(b);
+ b += 4;
+ uint32_t linecol = decode_uint32(b);
+ b += 4;
- lines.insert(token,linecol);
- total_len-=8;
+ lines.insert(token, linecol);
+ total_len -= 8;
}
tokens.resize(token_count);
- for(int i=0;i<token_count;i++) {
+ for (int i = 0; i < token_count; i++) {
- ERR_FAIL_COND_V( total_len < 1, ERR_INVALID_DATA);
+ 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);
+ if ((*b) & TOKEN_BYTE_MASK) { //little endian always
+ ERR_FAIL_COND_V(total_len < 4, ERR_INVALID_DATA);
- tokens[i]=decode_uint32(b)&~TOKEN_BYTE_MASK;
- b+=4;
+ tokens[i] = decode_uint32(b) & ~TOKEN_BYTE_MASK;
+ b += 4;
} else {
- tokens[i]=*b;
- b+=1;
+ tokens[i] = *b;
+ b += 1;
total_len--;
}
}
- token=0;
+ token = 0;
return OK;
-
}
-
-Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) {
+Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String &p_code) {
Vector<uint8_t> buf;
-
- Map<StringName,int> identifier_map;
- HashMap<Variant,int,VariantHasher,VariantComparator> constant_map;
- Map<uint32_t,int> line_map;
+ Map<StringName, int> identifier_map;
+ HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
+ Map<uint32_t, int> line_map;
Vector<uint32_t> token_array;
GDTokenizerText tt;
tt.set_code(p_code);
- int line=-1;
+ int line = -1;
- while(true) {
+ while (true) {
- if (tt.get_token_line()!=line) {
+ if (tt.get_token_line() != line) {
- line=tt.get_token_line();
- line_map[line]=token_array.size();
+ line = tt.get_token_line();
+ line_map[line] = token_array.size();
}
- uint32_t token=tt.get_token();
- switch(tt.get_token()) {
+ uint32_t token = tt.get_token();
+ switch (tt.get_token()) {
case TK_IDENTIFIER: {
StringName id = tt.get_token_identifier();
if (!identifier_map.has(id)) {
int idx = identifier_map.size();
- identifier_map[id]=idx;
+ identifier_map[id] = idx;
}
- token|=identifier_map[id]<<TOKEN_BITS;
+ token |= identifier_map[id] << TOKEN_BITS;
} break;
case TK_CONSTANT: {
Variant c = tt.get_token_constant();
if (!constant_map.has(c)) {
int idx = constant_map.size();
- constant_map[c]=idx;
+ constant_map[c] = idx;
}
- token|=constant_map[c]<<TOKEN_BITS;
+ token |= constant_map[c] << TOKEN_BITS;
} break;
case TK_BUILT_IN_TYPE: {
- token|=tt.get_token_type()<<TOKEN_BITS;
+ token |= tt.get_token_type() << TOKEN_BITS;
} break;
case TK_BUILT_IN_FUNC: {
- token|=tt.get_token_built_in_func()<<TOKEN_BITS;
+ token |= tt.get_token_built_in_func() << TOKEN_BITS;
} break;
case TK_NEWLINE: {
- token|=tt.get_token_line_indent()<<TOKEN_BITS;
+ token |= tt.get_token_line_indent() << TOKEN_BITS;
} break;
case TK_ERROR: {
ERR_FAIL_V(Vector<uint8_t>());
} break;
default: {}
-
};
token_array.push_back(token);
- if (tt.get_token()==TK_EOF)
+ if (tt.get_token() == TK_EOF)
break;
tt.advance();
-
}
//reverse maps
- 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();
+ 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();
}
- Map<int,Variant> rev_constant_map;
- const Variant *K =NULL;
- while((K=constant_map.next(K))) {
- rev_constant_map[constant_map[*K]]=*K;
+ Map<int, Variant> rev_constant_map;
+ const Variant *K = NULL;
+ while ((K = constant_map.next(K))) {
+ rev_constant_map[constant_map[*K]] = *K;
}
- 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();
+ 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();
}
//save header
buf.resize(24);
- buf[0]='G';
- buf[1]='D';
- buf[2]='S';
- buf[3]='C';
- encode_uint32(BYTECODE_VERSION,&buf[4]);
- encode_uint32(identifier_map.size(),&buf[8]);
- encode_uint32(constant_map.size(),&buf[12]);
- encode_uint32(line_map.size(),&buf[16]);
- encode_uint32(token_array.size(),&buf[20]);
+ buf[0] = 'G';
+ buf[1] = 'D';
+ buf[2] = 'S';
+ buf[3] = 'C';
+ encode_uint32(BYTECODE_VERSION, &buf[4]);
+ encode_uint32(identifier_map.size(), &buf[8]);
+ encode_uint32(constant_map.size(), &buf[12]);
+ encode_uint32(line_map.size(), &buf[16]);
+ encode_uint32(token_array.size(), &buf[20]);
//save identifiers
- for(Map<int,StringName>::Element *E=rev_identifier_map.front();E;E=E->next()) {
+ 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;
+ 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++) {
+ encode_uint32(len + extra, ibuf);
+ for (int i = 0; i < 4; i++) {
buf.push_back(ibuf[i]);
}
- for(int i=0;i<len;i++) {
- buf.push_back(cs[i]^0xb6);
+ for (int i = 0; i < len; i++) {
+ buf.push_back(cs[i] ^ 0xb6);
}
- for(int i=0;i<extra;i++) {
- buf.push_back(0^0xb6);
+ for (int i = 0; i < extra; i++) {
+ buf.push_back(0 ^ 0xb6);
}
}
- for(Map<int,Variant>::Element *E=rev_constant_map.front();E;E=E->next()) {
+ for (Map<int, Variant>::Element *E = rev_constant_map.front(); E; E = E->next()) {
int len;
- Error err = encode_variant(E->get(),NULL,len);
- ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>());
- int pos=buf.size();
- buf.resize(pos+len);
- encode_variant(E->get(),&buf[pos],len);
+ Error err = encode_variant(E->get(), NULL, len);
+ ERR_FAIL_COND_V(err != OK, Vector<uint8_t>());
+ int pos = buf.size();
+ buf.resize(pos + len);
+ encode_variant(E->get(), &buf[pos], len);
}
- for(Map<int,uint32_t>::Element *E=rev_line_map.front();E;E=E->next()) {
+ 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++)
+ encode_uint32(E->key(), &ibuf[0]);
+ encode_uint32(E->get(), &ibuf[4]);
+ for (int i = 0; i < 8; i++)
buf.push_back(ibuf[i]);
}
- for(int i=0;i<token_array.size();i++) {
+ for (int i = 0; i < token_array.size(); i++) {
uint32_t token = token_array[i];
- if (token&~TOKEN_MASK) {
+ 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++) {
+ encode_uint32(token_array[i] | TOKEN_BYTE_MASK, &buf4[0]);
+ for (int j = 0; j < 4; j++) {
buf.push_back(buf4[j]);
}
} else {
@@ -1326,102 +1297,94 @@ Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) {
}
return buf;
-
}
GDTokenizerBuffer::Token GDTokenizerBuffer::get_token(int p_offset) const {
- int offset = token+p_offset;
+ int offset = token + p_offset;
- if (offset<0 || offset>=tokens.size())
+ if (offset < 0 || offset >= tokens.size())
return TK_EOF;
- return GDTokenizerBuffer::Token(tokens[offset]&TOKEN_MASK);
+ return GDTokenizerBuffer::Token(tokens[offset] & TOKEN_MASK);
}
+StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const {
-StringName GDTokenizerBuffer::get_token_identifier(int p_offset) const{
+ int offset = token + p_offset;
- int offset = token+p_offset;
-
- ERR_FAIL_INDEX_V(offset,tokens.size(),StringName());
- uint32_t identifier = tokens[offset]>>TOKEN_BITS;
- ERR_FAIL_INDEX_V(identifier,(uint32_t)identifiers.size(),StringName());
+ ERR_FAIL_INDEX_V(offset, tokens.size(), StringName());
+ uint32_t identifier = tokens[offset] >> TOKEN_BITS;
+ ERR_FAIL_INDEX_V(identifier, (uint32_t)identifiers.size(), StringName());
return identifiers[identifier];
}
-GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const{
+GDFunctions::Function GDTokenizerBuffer::get_token_built_in_func(int p_offset) const {
- int offset = token+p_offset;
- ERR_FAIL_INDEX_V(offset,tokens.size(),GDFunctions::FUNC_MAX);
- return GDFunctions::Function(tokens[offset]>>TOKEN_BITS);
+ int offset = token + p_offset;
+ ERR_FAIL_INDEX_V(offset, tokens.size(), GDFunctions::FUNC_MAX);
+ return GDFunctions::Function(tokens[offset] >> TOKEN_BITS);
}
-Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const{
+Variant::Type GDTokenizerBuffer::get_token_type(int p_offset) const {
- int offset = token+p_offset;
- ERR_FAIL_INDEX_V(offset,tokens.size(),Variant::NIL);
+ int offset = token + p_offset;
+ ERR_FAIL_INDEX_V(offset, tokens.size(), Variant::NIL);
- return Variant::Type(tokens[offset]>>TOKEN_BITS);
+ return Variant::Type(tokens[offset] >> TOKEN_BITS);
}
-int GDTokenizerBuffer::get_token_line(int p_offset) const{
+int GDTokenizerBuffer::get_token_line(int p_offset) const {
- int offset = token+p_offset;
+ int offset = token + p_offset;
int pos = lines.find_nearest(offset);
- if (pos<0)
+ if (pos < 0)
return -1;
- if (pos>=lines.size())
- pos=lines.size()-1;
+ if (pos >= lines.size())
+ pos = lines.size() - 1;
uint32_t l = lines.getv(pos);
- return l&TOKEN_LINE_MASK;
-
+ return l & TOKEN_LINE_MASK;
}
-int GDTokenizerBuffer::get_token_column(int p_offset) const{
+int GDTokenizerBuffer::get_token_column(int p_offset) const {
- int offset = token+p_offset;
+ int offset = token + p_offset;
int pos = lines.find_nearest(offset);
- if (pos<0)
+ if (pos < 0)
return -1;
- if (pos>=lines.size())
- pos=lines.size()-1;
+ if (pos >= lines.size())
+ pos = lines.size() - 1;
uint32_t l = lines.getv(pos);
- return l>>TOKEN_LINE_BITS;
-
+ return l >> TOKEN_LINE_BITS;
}
-int GDTokenizerBuffer::get_token_line_indent(int p_offset) const{
+int GDTokenizerBuffer::get_token_line_indent(int p_offset) const {
- int offset = token+p_offset;
- ERR_FAIL_INDEX_V(offset,tokens.size(),0);
- return tokens[offset]>>TOKEN_BITS;
+ int offset = token + p_offset;
+ ERR_FAIL_INDEX_V(offset, tokens.size(), 0);
+ return tokens[offset] >> TOKEN_BITS;
}
-const Variant& GDTokenizerBuffer::get_token_constant(int p_offset) const{
-
+const Variant &GDTokenizerBuffer::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_INDEX_V(constant,(uint32_t)constants.size(),nil);
+ int offset = token + p_offset;
+ ERR_FAIL_INDEX_V(offset, tokens.size(), nil);
+ uint32_t constant = tokens[offset] >> TOKEN_BITS;
+ ERR_FAIL_INDEX_V(constant, (uint32_t)constants.size(), nil);
return constants[constant];
-
}
-String GDTokenizerBuffer::get_token_error(int p_offset) const{
+String GDTokenizerBuffer::get_token_error(int p_offset) const {
ERR_FAIL_V(String());
}
-void GDTokenizerBuffer::advance(int p_amount){
+void GDTokenizerBuffer::advance(int p_amount) {
- ERR_FAIL_INDEX(p_amount+token,tokens.size());
- token+=p_amount;
+ ERR_FAIL_INDEX(p_amount + token, tokens.size());
+ token += p_amount;
}
-GDTokenizerBuffer::GDTokenizerBuffer(){
-
- token=0;
+GDTokenizerBuffer::GDTokenizerBuffer() {
+ token = 0;
}
-
diff --git a/modules/gdscript/gd_tokenizer.h b/modules/gdscript/gd_tokenizer.h
index 1e9eda7947..c1ed8ad92e 100644
--- a/modules/gdscript/gd_tokenizer.h
+++ b/modules/gdscript/gd_tokenizer.h
@@ -29,15 +29,14 @@
#ifndef GD_TOKENIZER_H
#define GD_TOKENIZER_H
+#include "gd_functions.h"
+#include "string_db.h"
#include "ustring.h"
#include "variant.h"
-#include "string_db.h"
-#include "gd_functions.h"
#include "vmap.h"
class GDTokenizer {
public:
-
enum Token {
TK_EMPTY,
@@ -137,37 +136,36 @@ public:
};
protected:
-
enum StringMode {
STRING_SINGLE_QUOTE,
STRING_DOUBLE_QUOTE,
STRING_MULTILINE
};
- static const char* token_names[TK_MAX];
+ static const char *token_names[TK_MAX];
+
public:
static const char *get_token_name(Token p_token);
- 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 GDFunctions::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 String get_token_error(int p_offset=0) const=0;
- virtual void advance(int p_amount=1)=0;
+ 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 GDFunctions::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 String get_token_error(int p_offset = 0) const = 0;
+ virtual void advance(int p_amount = 1) = 0;
virtual ~GDTokenizer(){};
-
};
class GDTokenizerText : public GDTokenizer {
enum {
- MAX_LOOKAHEAD=4,
- TK_RB_SIZE=MAX_LOOKAHEAD*2+1
+ MAX_LOOKAHEAD = 4,
+ TK_RB_SIZE = MAX_LOOKAHEAD * 2 + 1
};
@@ -179,17 +177,21 @@ class GDTokenizerText : public GDTokenizer {
Variant::Type vtype; //for type types
GDFunctions::Function func; //function for built in functions
};
- int line,col;
- TokenData() { type = TK_EMPTY; line=col=0; vtype=Variant::NIL; }
+ int line, col;
+ TokenData() {
+ type = TK_EMPTY;
+ line = col = 0;
+ vtype = Variant::NIL;
+ }
};
void _make_token(Token p_type);
- void _make_newline(int p_spaces=0);
- void _make_identifier(const StringName& p_identifier);
+ void _make_newline(int p_spaces = 0);
+ void _make_identifier(const StringName &p_identifier);
void _make_built_in_func(GDFunctions::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);
+ void _make_constant(const Variant &p_constant);
+ void _make_type(const Variant::Type &p_type);
+ void _make_error(const String &p_error);
String code;
int len;
@@ -197,66 +199,58 @@ class GDTokenizerText : public GDTokenizer {
const CharType *_code;
int line;
int column;
- TokenData tk_rb[TK_RB_SIZE*2+1];
+ TokenData tk_rb[TK_RB_SIZE * 2 + 1];
int tk_rb_pos;
String last_error;
bool error_flag;
void _advance();
-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 GDFunctions::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 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);
+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 GDFunctions::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 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);
};
-
-
-
class GDTokenizerBuffer : public GDTokenizer {
-
enum {
- 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,
+ 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,
};
-
Vector<StringName> identifiers;
Vector<Variant> constants;
- VMap<uint32_t,uint32_t> lines;
+ VMap<uint32_t, uint32_t> lines;
Vector<uint32_t> tokens;
Variant nil;
int token;
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 GDFunctions::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 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);
+ 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 GDFunctions::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 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);
GDTokenizerBuffer();
};
diff --git a/modules/gdscript/register_types.cpp b/modules/gdscript/register_types.cpp
index d1d69c6709..5acd412f7e 100644
--- a/modules/gdscript/register_types.cpp
+++ b/modules/gdscript/register_types.cpp
@@ -29,22 +29,20 @@
#include "register_types.h"
#include "gd_script.h"
+#include "io/file_access_encrypted.h"
#include "io/resource_loader.h"
#include "os/file_access.h"
-#include "io/file_access_encrypted.h"
-
-
-GDScriptLanguage *script_language_gd=NULL;
-ResourceFormatLoaderGDScript *resource_loader_gd=NULL;
-ResourceFormatSaverGDScript *resource_saver_gd=NULL;
+GDScriptLanguage *script_language_gd = NULL;
+ResourceFormatLoaderGDScript *resource_loader_gd = NULL;
+ResourceFormatSaverGDScript *resource_saver_gd = NULL;
#if 0
#ifdef TOOLS_ENABLED
#include "editor/editor_import_export.h"
-#include "gd_tokenizer.h"
#include "editor/editor_node.h"
#include "editor/editor_settings.h"
+#include "gd_tokenizer.h"
class EditorExportGDScript : public EditorExportPlugin {
@@ -133,7 +131,6 @@ static void register_editor_plugin() {
EditorImportExport::get_singleton()->add_export_plugin(egd);
}
-
#endif
#endif
void register_gdscript_types() {
@@ -141,12 +138,12 @@ void register_gdscript_types() {
ClassDB::register_class<GDScript>();
ClassDB::register_virtual_class<GDFunctionState>();
- script_language_gd=memnew( GDScriptLanguage );
+ script_language_gd = memnew(GDScriptLanguage);
//script_language_gd->init();
ScriptServer::register_language(script_language_gd);
- resource_loader_gd=memnew( ResourceFormatLoaderGDScript );
+ resource_loader_gd = memnew(ResourceFormatLoaderGDScript);
ResourceLoader::add_resource_format_loader(resource_loader_gd);
- resource_saver_gd=memnew( ResourceFormatSaverGDScript );
+ resource_saver_gd = memnew(ResourceFormatSaverGDScript);
ResourceSaver::add_resource_format_saver(resource_saver_gd);
#if 0
#ifdef TOOLS_ENABLED
@@ -154,18 +151,15 @@ void register_gdscript_types() {
EditorNode::add_init_callback(register_editor_plugin);
#endif
#endif
-
}
void unregister_gdscript_types() {
-
ScriptServer::unregister_language(script_language_gd);
if (script_language_gd)
- memdelete( script_language_gd );
+ memdelete(script_language_gd);
if (resource_loader_gd)
- memdelete( resource_loader_gd );
+ memdelete(resource_loader_gd);
if (resource_saver_gd)
- memdelete( resource_saver_gd );
-
+ memdelete(resource_saver_gd);
}
diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp
index d4fb174bfe..128592fa29 100644
--- a/modules/gridmap/grid_map.cpp
+++ b/modules/gridmap/grid_map.cpp
@@ -27,36 +27,36 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "grid_map.h"
-#include "servers/visual_server.h"
-#include "scene/resources/surface_tool.h"
#include "message_queue.h"
#include "scene/3d/light.h"
+#include "scene/resources/surface_tool.h"
+#include "servers/visual_server.h"
#include "io/marshalls.h"
-#include "scene/scene_string_names.h"
#include "os/os.h"
#include "scene/resources/mesh_library.h"
+#include "scene/scene_string_names.h"
-bool GridMap::_set(const StringName& p_name, const Variant& p_value) {
+bool GridMap::_set(const StringName &p_name, const Variant &p_value) {
- String name=p_name;
+ String name = p_name;
- if (name=="theme") {
+ if (name == "theme") {
set_theme(p_value);
- } else if (name=="cell_size") {
+ } else if (name == "cell_size") {
set_cell_size(p_value);
- } else if (name=="cell_octant_size") {
+ } else if (name == "cell_octant_size") {
set_octant_size(p_value);
- } else if (name=="cell_center_x") {
+ } else if (name == "cell_center_x") {
set_center_x(p_value);
- } else if (name=="cell_center_y") {
+ } else if (name == "cell_center_y") {
set_center_y(p_value);
- } else if (name=="cell_center_z") {
+ } else if (name == "cell_center_z") {
set_center_z(p_value);
- } else if (name=="cell_scale") {
+ } else if (name == "cell_scale") {
set_cell_scale(p_value);
-/* } else if (name=="cells") {
+ /* } else if (name=="cells") {
PoolVector<int> cells = p_value;
int amount=cells.size();
PoolVector<int>::Read r = cells.read();
@@ -73,146 +73,138 @@ bool GridMap::_set(const StringName& p_name, const Variant& p_value) {
}
_recreate_octant_data();*/
- } else if (name=="data") {
+ } else if (name == "data") {
Dictionary d = p_value;
if (d.has("cells")) {
PoolVector<int> cells = d["cells"];
- int amount=cells.size();
+ int amount = cells.size();
PoolVector<int>::Read r = cells.read();
- ERR_FAIL_COND_V(amount%3,false); // not even
+ ERR_FAIL_COND_V(amount % 3, false); // not even
cell_map.clear();
- for(int i=0;i<amount/3;i++) {
+ for (int i = 0; i < amount / 3; i++) {
IndexKey ik;
- ik.key=decode_uint64((const uint8_t*)&r[i*3]);
+ ik.key = decode_uint64((const uint8_t *)&r[i * 3]);
Cell cell;
- cell.cell=decode_uint32((const uint8_t*)&r[i*3+2]);
- cell_map[ik]=cell;
-
+ cell.cell = decode_uint32((const uint8_t *)&r[i * 3 + 2]);
+ cell_map[ik] = cell;
}
}
_recreate_octant_data();
-
} else if (name.begins_with("areas/")) {
- int which = name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="bounds") {
- ERR_FAIL_COND_V(area_map.has(which),false);
- create_area(which,p_value);
+ int which = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "bounds") {
+ ERR_FAIL_COND_V(area_map.has(which), false);
+ create_area(which, p_value);
return true;
}
- ERR_FAIL_COND_V(!area_map.has(which),false);
+ ERR_FAIL_COND_V(!area_map.has(which), false);
- if (what=="name")
- area_set_name(which,p_value);
- else if (what=="disable_distance")
- area_set_portal_disable_distance(which,p_value);
- else if (what=="exterior_portal")
- area_set_portal_disable_color(which,p_value);
+ if (what == "name")
+ area_set_name(which, p_value);
+ else if (what == "disable_distance")
+ area_set_portal_disable_distance(which, p_value);
+ else if (what == "exterior_portal")
+ area_set_portal_disable_color(which, p_value);
else
return false;
} else
return false;
return true;
-
-
}
-bool GridMap::_get(const StringName& p_name,Variant &r_ret) const {
-
- String name=p_name;
-
- if (name=="theme") {
- r_ret= get_theme();
- } else if (name=="cell_size") {
- r_ret= get_cell_size();
- } else if (name=="cell_octant_size") {
- r_ret= get_octant_size();
- } else if (name=="cell_center_x") {
- r_ret= get_center_x();
- } else if (name=="cell_center_y") {
- r_ret= get_center_y();
- } else if (name=="cell_center_z") {
- r_ret= get_center_z();
- } else if (name=="cell_scale") {
- r_ret= cell_scale;
- } else if (name=="data") {
+bool GridMap::_get(const StringName &p_name, Variant &r_ret) const {
+
+ String name = p_name;
+
+ if (name == "theme") {
+ r_ret = get_theme();
+ } else if (name == "cell_size") {
+ r_ret = get_cell_size();
+ } else if (name == "cell_octant_size") {
+ r_ret = get_octant_size();
+ } else if (name == "cell_center_x") {
+ r_ret = get_center_x();
+ } else if (name == "cell_center_y") {
+ r_ret = get_center_y();
+ } else if (name == "cell_center_z") {
+ r_ret = get_center_z();
+ } else if (name == "cell_scale") {
+ r_ret = cell_scale;
+ } else if (name == "data") {
Dictionary d;
PoolVector<int> cells;
- cells.resize(cell_map.size()*3);
+ cells.resize(cell_map.size() * 3);
{
PoolVector<int>::Write w = cells.write();
- int i=0;
- for (Map<IndexKey,Cell>::Element *E=cell_map.front();E;E=E->next(),i++) {
+ 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]);
+ encode_uint64(E->key().key, (uint8_t *)&w[i * 3]);
+ encode_uint32(E->get().cell, (uint8_t *)&w[i * 3 + 2]);
}
}
- d["cells"]=cells;
-
+ d["cells"] = cells;
-
- r_ret= d;
+ r_ret = d;
} else if (name.begins_with("areas/")) {
- int which = name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="bounds")
- r_ret= area_get_bounds(which);
- else if (what=="name")
- r_ret= area_get_name(which);
- else if (what=="disable_distance")
- r_ret= area_get_portal_disable_distance(which);
- else if (what=="exterior_portal")
- r_ret= area_is_exterior_portal(which);
+ int which = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "bounds")
+ r_ret = area_get_bounds(which);
+ else if (what == "name")
+ r_ret = area_get_name(which);
+ else if (what == "disable_distance")
+ r_ret = area_get_portal_disable_distance(which);
+ else if (what == "exterior_portal")
+ r_ret = area_is_exterior_portal(which);
else
return false;
} else
return false;
return true;
-
}
-void GridMap::_get_property_list( List<PropertyInfo> *p_list) const {
+void GridMap::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo( Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary"));
- p_list->push_back( PropertyInfo( Variant::NIL, "Cell", PROPERTY_HINT_NONE,"cell_",PROPERTY_USAGE_GROUP));
- p_list->push_back( PropertyInfo( Variant::REAL, "cell_size",PROPERTY_HINT_RANGE,"0.01,16384,0.01") );
- p_list->push_back( PropertyInfo( Variant::INT, "cell_octant_size",PROPERTY_HINT_RANGE,"1,1024,1") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "cell_center_x") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "cell_center_y") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "cell_center_z") );
- p_list->push_back( PropertyInfo( Variant::REAL, "cell_scale") );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "MeshLibrary"));
+ p_list->push_back(PropertyInfo(Variant::NIL, "Cell", PROPERTY_HINT_NONE, "cell_", PROPERTY_USAGE_GROUP));
+ p_list->push_back(PropertyInfo(Variant::REAL, "cell_size", PROPERTY_HINT_RANGE, "0.01,16384,0.01"));
+ p_list->push_back(PropertyInfo(Variant::INT, "cell_octant_size", PROPERTY_HINT_RANGE, "1,1024,1"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "cell_center_x"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "cell_center_y"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "cell_center_z"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "cell_scale"));
- p_list->push_back( PropertyInfo( Variant::DICTIONARY, "data", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
+ p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
- for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
+ for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
- String base="areas/"+itos(E->key())+"/";
- p_list->push_back( PropertyInfo( Variant::RECT3, base+"bounds", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
- p_list->push_back( PropertyInfo( Variant::STRING, base+"name", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
- p_list->push_back( PropertyInfo( Variant::REAL, base+"disable_distance", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
- p_list->push_back( PropertyInfo( Variant::COLOR, base+"disable_color", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
- p_list->push_back( PropertyInfo( Variant::BOOL, base+"exterior_portal", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE) );
+ String base = "areas/" + itos(E->key()) + "/";
+ p_list->push_back(PropertyInfo(Variant::RECT3, base + "bounds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
+ p_list->push_back(PropertyInfo(Variant::REAL, base + "disable_distance", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
+ p_list->push_back(PropertyInfo(Variant::COLOR, base + "disable_color", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "exterior_portal", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE));
}
}
-
-void GridMap::set_theme(const Ref<MeshLibrary>& p_theme) {
+void GridMap::set_theme(const Ref<MeshLibrary> &p_theme) {
if (!theme.is_null())
theme->unregister_owner(this);
- theme=p_theme;
+ theme = p_theme;
if (!theme.is_null())
theme->register_owner(this);
@@ -220,35 +212,34 @@ void GridMap::set_theme(const Ref<MeshLibrary>& p_theme) {
_change_notify("theme");
}
-Ref<MeshLibrary> GridMap::get_theme() const{
+Ref<MeshLibrary> GridMap::get_theme() const {
return theme;
}
-void GridMap::set_cell_size(float p_size){
+void GridMap::set_cell_size(float p_size) {
- cell_size=p_size;
+ cell_size = p_size;
_recreate_octant_data();
-
}
-float GridMap::get_cell_size() const{
+float GridMap::get_cell_size() const {
return cell_size;
}
-void GridMap::set_octant_size(int p_size){
+void GridMap::set_octant_size(int p_size) {
- octant_size=p_size;
+ 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;
+ center_x = p_enable;
_recreate_octant_data();
}
@@ -258,7 +249,7 @@ bool GridMap::get_center_x() const {
void GridMap::set_center_y(bool p_enable) {
- center_y=p_enable;
+ center_y = p_enable;
_recreate_octant_data();
}
@@ -268,7 +259,7 @@ bool GridMap::get_center_y() const {
void GridMap::set_center_z(bool p_enable) {
- center_z=p_enable;
+ center_z = p_enable;
_recreate_octant_data();
}
@@ -276,56 +267,52 @@ bool GridMap::get_center_z() const {
return center_z;
}
+int GridMap::_find_area(const IndexKey &p_pos) const {
-int GridMap::_find_area(const IndexKey& p_pos) const {
-
- for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
- //this should somehow be faster...
- const Area& a=*E->get();
- if ( p_pos.x>=a.from.x && p_pos.x<a.to.x &&
- p_pos.y>=a.from.y && p_pos.y<a.to.y &&
- p_pos.z>=a.from.z && p_pos.z<a.to.z ) {
+ for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
+ //this should somehow be faster...
+ const Area &a = *E->get();
+ if (p_pos.x >= a.from.x && p_pos.x < a.to.x &&
+ p_pos.y >= a.from.y && p_pos.y < a.to.y &&
+ p_pos.z >= a.from.z && p_pos.z < a.to.z) {
return E->key();
}
}
return 0;
}
-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(int p_x, int p_y, int p_z, int p_item, int p_rot) {
- 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_x), 1 << 20);
+ ERR_FAIL_INDEX(ABS(p_y), 1 << 20);
+ ERR_FAIL_INDEX(ABS(p_z), 1 << 20);
IndexKey key;
- key.x=p_x;
- key.y=p_y;
- key.z=p_z;
+ key.x = p_x;
+ key.y = p_y;
+ key.z = p_z;
OctantKey ok;
- ok.x=p_x/octant_size;
- ok.y=p_y/octant_size;
- ok.z=p_z/octant_size;
+ ok.x = p_x / octant_size;
+ ok.y = p_y / octant_size;
+ ok.z = p_z / octant_size;
ok.area = _find_area(key);
-
if (cell_map.has(key)) {
- int prev_item=cell_map[key].item;
+ int prev_item = cell_map[key].item;
- OctantKey octantkey=ok;
+ OctantKey octantkey = ok;
ERR_FAIL_COND(!octant_map.has(octantkey));
- Octant& g = *octant_map[octantkey];
+ Octant &g = *octant_map[octantkey];
ERR_FAIL_COND(!g.items.has(prev_item));
ERR_FAIL_COND(!g.items[prev_item].cells.has(key));
-
g.items[prev_item].cells.erase(key);
- if (g.items[prev_item].cells.size()==0) {
+ if (g.items[prev_item].cells.size() == 0) {
VS::get_singleton()->free(g.items[prev_item].multimesh_instance);
g.items.erase(prev_item);
-
}
if (g.items.empty()) {
@@ -339,136 +326,129 @@ void GridMap::set_cell_item(int p_x,int p_y,int p_z, int p_item,int p_rot){
octant_map.erase(octantkey);
} else {
-
- g.dirty=true;
+ g.dirty = true;
}
cell_map.erase(key);
_queue_dirty_map();
}
- if (p_item<0)
+ if (p_item < 0)
return;
- OctantKey octantkey=ok;
+ OctantKey octantkey = ok;
//add later
if (!octant_map.has(octantkey)) {
-
- Octant *g = memnew( Octant );
- g->dirty=true;
+ Octant *g = memnew(Octant);
+ g->dirty = true;
g->static_body = PhysicsServer::get_singleton()->body_create(PhysicsServer::BODY_MODE_STATIC);
- PhysicsServer::get_singleton()->body_attach_object_instance_ID(g->static_body,get_instance_ID());
+ PhysicsServer::get_singleton()->body_attach_object_instance_ID(g->static_body, get_instance_ID());
if (is_inside_world())
- PhysicsServer::get_singleton()->body_set_space(g->static_body,get_world()->get_space());
+ PhysicsServer::get_singleton()->body_set_space(g->static_body, get_world()->get_space());
- SceneTree *st=SceneTree::get_singleton();
+ SceneTree *st = SceneTree::get_singleton();
if (st && st->is_debugging_collisions_hint()) {
- g->collision_debug=VisualServer::get_singleton()->mesh_create();
- g->collision_debug_instance=VisualServer::get_singleton()->instance_create();
- VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance,g->collision_debug);
+ g->collision_debug = VisualServer::get_singleton()->mesh_create();
+ g->collision_debug_instance = VisualServer::get_singleton()->instance_create();
+ VisualServer::get_singleton()->instance_set_base(g->collision_debug_instance, g->collision_debug);
if (is_inside_world()) {
- VisualServer::get_singleton()->instance_set_scenario(g->collision_debug_instance,get_world()->get_scenario());
- VisualServer::get_singleton()->instance_set_transform(g->collision_debug_instance,get_global_transform());
+ VisualServer::get_singleton()->instance_set_scenario(g->collision_debug_instance, get_world()->get_scenario());
+ VisualServer::get_singleton()->instance_set_transform(g->collision_debug_instance, get_global_transform());
}
-
}
- octant_map[octantkey]=g;
+ octant_map[octantkey] = g;
}
- Octant& g = *octant_map[octantkey];
+ Octant &g = *octant_map[octantkey];
if (!g.items.has(p_item)) {
Octant::ItemInstances ii;
if (theme.is_valid() && theme->has_item(p_item)) {
- ii.mesh=theme->get_item_mesh(p_item);
- ii.shape=theme->get_item_shape(p_item);
- ii.navmesh=theme->get_item_navmesh(p_item);
+ ii.mesh = theme->get_item_mesh(p_item);
+ ii.shape = theme->get_item_shape(p_item);
+ ii.navmesh = theme->get_item_navmesh(p_item);
}
- ii.multimesh = Ref<MultiMesh>( memnew( MultiMesh ) );
+ ii.multimesh = Ref<MultiMesh>(memnew(MultiMesh));
ii.multimesh->set_color_format(MultiMesh::COLOR_NONE);
ii.multimesh->set_transform_format(MultiMesh::TRANSFORM_3D);
ii.multimesh->set_mesh(ii.mesh);
ii.multimesh_instance = VS::get_singleton()->instance_create();
- VS::get_singleton()->instance_set_base(ii.multimesh_instance,ii.multimesh->get_rid());
+ VS::get_singleton()->instance_set_base(ii.multimesh_instance, ii.multimesh->get_rid());
- g.items[p_item]=ii;
+ g.items[p_item] = ii;
}
Octant::ItemInstances &ii = g.items[p_item];
ii.cells.insert(key);
- g.dirty=true;
+ g.dirty = true;
_queue_dirty_map();
- cell_map[key]=Cell();
- Cell &c=cell_map[key];
- c.item=p_item;
- c.rot=p_rot;
-
+ cell_map[key] = Cell();
+ Cell &c = cell_map[key];
+ c.item = p_item;
+ c.rot = p_rot;
}
-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(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);
IndexKey key;
- key.x=p_x;
- key.y=p_y;
- key.z=p_z;
+ key.x = p_x;
+ key.y = p_y;
+ key.z = p_z;
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{
+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);
+ 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);
IndexKey key;
- key.x=p_x;
- key.y=p_y;
- key.z=p_z;
+ key.x = p_x;
+ key.y = p_y;
+ key.z = p_z;
if (!cell_map.has(key))
return -1;
return cell_map[key].rot;
-
}
-void GridMap::_octant_enter_tree(const OctantKey &p_key){
+void GridMap::_octant_enter_tree(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
- if(navigation){
- Octant&g = *octant_map[p_key];
+ if (navigation) {
+ Octant &g = *octant_map[p_key];
- Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z));
+ Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z));
_octant_clear_navmesh(p_key);
- for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) {
- Octant::ItemInstances &ii=E->get();
+ for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) {
+ Octant::ItemInstances &ii = E->get();
- for(Set<IndexKey>::Element *F=ii.cells.front();F;F=F->next()) {
+ for (Set<IndexKey>::Element *F = ii.cells.front(); F; F = F->next()) {
- IndexKey ik=F->get();
- Map<IndexKey,Cell>::Element *C=cell_map.find(ik);
+ IndexKey ik = F->get();
+ Map<IndexKey, Cell>::Element *C = cell_map.find(ik);
ERR_CONTINUE(!C);
- Vector3 cellpos = Vector3(ik.x,ik.y,ik.z );
+ Vector3 cellpos = Vector3(ik.x, ik.y, ik.z);
Transform xform;
- if (clip && ( (clip_above && cellpos[clip_axis]>clip_floor) || (!clip_above && cellpos[clip_axis]<clip_floor))) {
+ if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) {
xform.basis.set_zero();
@@ -477,16 +457,15 @@ void GridMap::_octant_enter_tree(const OctantKey &p_key){
xform.basis.set_orthogonal_index(C->get().rot);
}
-
- xform.set_origin( cellpos*cell_size+ofs);
- xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale));
+ xform.set_origin(cellpos * cell_size + ofs);
+ xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
// add the item's navmesh at given xform to GridMap's Navigation ancestor
- if(ii.navmesh.is_valid()){
- int nm_id = navigation->navmesh_create(ii.navmesh,xform,this);
+ if (ii.navmesh.is_valid()) {
+ int nm_id = navigation->navmesh_create(ii.navmesh, xform, this);
Octant::NavMesh nm;
- nm.id=nm_id;
- nm.xform=xform;
- g.navmesh_ids[ik]=nm;
+ nm.id = nm_id;
+ nm.xform = xform;
+ g.navmesh_ids[ik] = nm;
}
}
}
@@ -496,56 +475,53 @@ void GridMap::_octant_enter_tree(const OctantKey &p_key){
void GridMap::_octant_enter_world(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
- Octant&g = *octant_map[p_key];
- PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform());
- PhysicsServer::get_singleton()->body_set_space(g.static_body,get_world()->get_space());
+ Octant &g = *octant_map[p_key];
+ PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
+ PhysicsServer::get_singleton()->body_set_space(g.static_body, get_world()->get_space());
//print_line("BODYPOS: "+get_global_transform());
-
if (g.collision_debug_instance.is_valid()) {
- VS::get_singleton()->instance_set_scenario(g.collision_debug_instance,get_world()->get_scenario());
- VS::get_singleton()->instance_set_transform(g.collision_debug_instance,get_global_transform());
+ VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, get_world()->get_scenario());
+ VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
if (area_map.has(p_key.area)) {
- VS::get_singleton()->instance_set_room(g.collision_debug_instance,area_map[p_key.area]->instance);
+ VS::get_singleton()->instance_set_room(g.collision_debug_instance, area_map[p_key.area]->instance);
}
}
- for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) {
+ for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) {
- VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance,get_world()->get_scenario());
- VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform());
+ VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance, get_world()->get_scenario());
+ VS::get_singleton()->instance_set_transform(E->get().multimesh_instance, get_global_transform());
//print_line("INSTANCEPOS: "+get_global_transform());
if (area_map.has(p_key.area)) {
- VS::get_singleton()->instance_set_room(E->get().multimesh_instance,area_map[p_key.area]->instance);
+ VS::get_singleton()->instance_set_room(E->get().multimesh_instance, area_map[p_key.area]->instance);
}
}
}
-
void GridMap::_octant_transform(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
- Octant&g = *octant_map[p_key];
- PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform());
+ Octant &g = *octant_map[p_key];
+ PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
if (g.collision_debug_instance.is_valid()) {
- VS::get_singleton()->instance_set_transform(g.collision_debug_instance,get_global_transform());
+ VS::get_singleton()->instance_set_transform(g.collision_debug_instance, get_global_transform());
}
- for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) {
+ for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) {
- VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform());
+ VS::get_singleton()->instance_set_transform(E->get().multimesh_instance, get_global_transform());
//print_line("UPDATEPOS: "+get_global_transform());
}
-
}
-void GridMap::_octant_clear_navmesh(const OctantKey &p_key){
- Octant&g = *octant_map[p_key];
+void GridMap::_octant_clear_navmesh(const OctantKey &p_key) {
+ Octant &g = *octant_map[p_key];
if (navigation) {
- for(Map<IndexKey,Octant::NavMesh>::Element *E=g.navmesh_ids.front();E;E=E->next()) {
+ for (Map<IndexKey, Octant::NavMesh>::Element *E = g.navmesh_ids.front(); E; E = E->next()) {
Octant::NavMesh *nvm = &E->get();
- if(nvm && nvm->id){
+ if (nvm && nvm->id) {
navigation->navmesh_remove(E->get().id);
}
}
@@ -555,7 +531,7 @@ void GridMap::_octant_clear_navmesh(const OctantKey &p_key){
void GridMap::_octant_update(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
- Octant&g = *octant_map[p_key];
+ Octant &g = *octant_map[p_key];
if (!g.dirty)
return;
@@ -576,31 +552,30 @@ void GridMap::_octant_update(const OctantKey &p_key) {
* set item's multimesh's instance count to number of cells which have this item
* and set said multimesh bounding box to one containing all cells which have this item
*/
- for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) {
+ for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) {
- Octant::ItemInstances &ii=E->get();
+ Octant::ItemInstances &ii = E->get();
ii.multimesh->set_instance_count(ii.cells.size());
Rect3 aabb;
- Rect3 mesh_aabb = ii.mesh.is_null()?Rect3():ii.mesh->get_aabb();
-
- Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z));
+ Rect3 mesh_aabb = ii.mesh.is_null() ? Rect3() : ii.mesh->get_aabb();
+ Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z));
//print_line("OCTANT, CELLS: "+itos(ii.cells.size()));
- int idx=0;
+ int idx = 0;
// foreach cell containing this item type
- for(Set<IndexKey>::Element *F=ii.cells.front();F;F=F->next()) {
- IndexKey ik=F->get();
- Map<IndexKey,Cell>::Element *C=cell_map.find(ik);
+ for (Set<IndexKey>::Element *F = ii.cells.front(); F; F = F->next()) {
+ IndexKey ik = F->get();
+ Map<IndexKey, Cell>::Element *C = cell_map.find(ik);
ERR_CONTINUE(!C);
- Vector3 cellpos = Vector3(ik.x,ik.y,ik.z );
+ Vector3 cellpos = Vector3(ik.x, ik.y, ik.z);
Transform xform;
- if (clip && ( (clip_above && cellpos[clip_axis]>clip_floor) || (!clip_above && cellpos[clip_axis]<clip_floor))) {
+ if (clip && ((clip_above && cellpos[clip_axis] > clip_floor) || (!clip_above && cellpos[clip_axis] < clip_floor))) {
xform.basis.set_zero();
@@ -609,19 +584,17 @@ void GridMap::_octant_update(const OctantKey &p_key) {
xform.basis.set_orthogonal_index(C->get().rot);
}
+ xform.set_origin(cellpos * cell_size + ofs);
+ xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
- xform.set_origin( cellpos*cell_size+ofs);
- xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale));
-
- ii.multimesh->set_instance_transform(idx,xform);
+ ii.multimesh->set_instance_transform(idx, xform);
//ii.multimesh->set_instance_transform(idx,Transform() );
//ii.multimesh->set_instance_color(idx,Color(1,1,1,1));
//print_line("MMINST: "+xform);
+ if (idx == 0) {
- if(idx==0) {
-
- aabb=xform.xform(mesh_aabb);
+ aabb = xform.xform(mesh_aabb);
} else {
aabb.merge_with(xform.xform(mesh_aabb));
@@ -630,22 +603,22 @@ void GridMap::_octant_update(const OctantKey &p_key) {
// add the item's shape at given xform to octant's static_body
if (ii.shape.is_valid()) {
// add the item's shape
- PhysicsServer::get_singleton()->body_add_shape(g.static_body,ii.shape->get_rid(),xform);
+ PhysicsServer::get_singleton()->body_add_shape(g.static_body, ii.shape->get_rid(), xform);
if (g.collision_debug.is_valid()) {
- ii.shape->add_vertices_to_array(col_debug,xform);
+ ii.shape->add_vertices_to_array(col_debug, xform);
}
//print_line("PHIS x: "+xform);
}
// add the item's navmesh at given xform to GridMap's Navigation ancestor
- if(navigation){
- if(ii.navmesh.is_valid()){
- int nm_id = navigation->navmesh_create(ii.navmesh,xform,this);
+ if (navigation) {
+ if (ii.navmesh.is_valid()) {
+ int nm_id = navigation->navmesh_create(ii.navmesh, xform, this);
Octant::NavMesh nm;
- nm.id=nm_id;
- nm.xform=xform;
- g.navmesh_ids[ik]=nm;
+ nm.id = nm_id;
+ nm.xform = xform;
+ g.navmesh_ids[ik] = nm;
}
}
@@ -653,95 +626,84 @@ void GridMap::_octant_update(const OctantKey &p_key) {
}
//ii.multimesh->set_aabb(aabb);
-
-
}
if (col_debug.size()) {
-
Array arr;
arr.resize(VS::ARRAY_MAX);
- arr[VS::ARRAY_VERTEX]=col_debug;
+ arr[VS::ARRAY_VERTEX] = col_debug;
- VS::get_singleton()->mesh_add_surface_from_arrays(g.collision_debug,VS::PRIMITIVE_LINES,arr);
- SceneTree *st=SceneTree::get_singleton();
+ VS::get_singleton()->mesh_add_surface_from_arrays(g.collision_debug, VS::PRIMITIVE_LINES, arr);
+ SceneTree *st = SceneTree::get_singleton();
if (st) {
- VS::get_singleton()->mesh_surface_set_material( g.collision_debug, 0,st->get_debug_collision_material()->get_rid() );
+ VS::get_singleton()->mesh_surface_set_material(g.collision_debug, 0, st->get_debug_collision_material()->get_rid());
}
}
- g.dirty=false;
-
+ g.dirty = false;
}
-
void GridMap::_octant_exit_world(const OctantKey &p_key) {
ERR_FAIL_COND(!octant_map.has(p_key));
- Octant&g = *octant_map[p_key];
- PhysicsServer::get_singleton()->body_set_state(g.static_body,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform());
- PhysicsServer::get_singleton()->body_set_space(g.static_body,RID());
-
+ Octant &g = *octant_map[p_key];
+ PhysicsServer::get_singleton()->body_set_state(g.static_body, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
+ PhysicsServer::get_singleton()->body_set_space(g.static_body, RID());
if (g.collision_debug_instance.is_valid()) {
- VS::get_singleton()->instance_set_room(g.collision_debug_instance,RID());
- VS::get_singleton()->instance_set_scenario(g.collision_debug_instance,RID());
+ VS::get_singleton()->instance_set_room(g.collision_debug_instance, RID());
+ VS::get_singleton()->instance_set_scenario(g.collision_debug_instance, RID());
}
- for(Map<int,Octant::ItemInstances>::Element *E=g.items.front();E;E=E->next()) {
+ for (Map<int, Octant::ItemInstances>::Element *E = g.items.front(); E; E = E->next()) {
- VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance,RID());
+ VS::get_singleton()->instance_set_scenario(E->get().multimesh_instance, RID());
//VS::get_singleton()->instance_set_transform(E->get().multimesh_instance,get_global_transform());
- VS::get_singleton()->instance_set_room(E->get().multimesh_instance,RID());
+ VS::get_singleton()->instance_set_room(E->get().multimesh_instance, RID());
}
-
}
-
void GridMap::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
_update_area_instances();
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
//IndexKey ik;
//ik.key = E->key().indexkey;
_octant_enter_world(E->key());
_octant_update(E->key());
}
- awaiting_update=false;
-
- last_transform=get_global_transform();
+ awaiting_update = false;
+ last_transform = get_global_transform();
} 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()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
_octant_transform(E->key());
}
- last_transform=new_xform;
+ last_transform = new_xform;
} break;
case NOTIFICATION_EXIT_WORLD: {
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
_octant_exit_world(E->key());
}
-
//_queue_dirty_map(MAP_DIRTY_INSTANCES|MAP_DIRTY_TRANSFORMS);
//_update_dirty_map_callback();
//_update_area_instances();
@@ -749,41 +711,39 @@ void GridMap::_notification(int p_what) {
} break;
case NOTIFICATION_ENTER_TREE: {
- Spatial *c=this;
- while(c) {
- navigation=c->cast_to<Navigation>();
+ Spatial *c = this;
+ while (c) {
+ navigation = c->cast_to<Navigation>();
if (navigation) {
break;
}
- c=c->get_parent()->cast_to<Spatial>();
+ c = c->get_parent()->cast_to<Spatial>();
}
- if(navigation){
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ if (navigation) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
if (navigation) {
_octant_enter_tree(E->key());
}
}
}
- _queue_dirty_map();
+ _queue_dirty_map();
} break;
case NOTIFICATION_EXIT_TREE: {
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
if (navigation) {
_octant_clear_navmesh(E->key());
}
}
- navigation=NULL;
+ navigation = NULL;
} break;
}
}
-
-
void GridMap::_queue_dirty_map() {
if (awaiting_update)
@@ -791,34 +751,32 @@ void GridMap::_queue_dirty_map() {
if (is_inside_world()) {
- MessageQueue::get_singleton()->push_call(this,"_update_dirty_map_callback");
- awaiting_update=true;
+ MessageQueue::get_singleton()->push_call(this, "_update_dirty_map_callback");
+ awaiting_update = true;
}
}
void GridMap::_recreate_octant_data() {
- Map<IndexKey,Cell> cell_copy=cell_map;
+ Map<IndexKey, Cell> cell_copy = cell_map;
_clear_internal(true);
- for (Map<IndexKey,Cell>::Element *E=cell_copy.front();E;E=E->next()) {
+ 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(E->key().x, E->key().y, E->key().z, E->get().item, E->get().rot);
}
-
}
void GridMap::_clear_internal(bool p_keep_areas) {
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
if (is_inside_world())
_octant_exit_world(E->key());
- for (Map<int,Octant::ItemInstances>::Element *F=E->get()->items.front();F;F=F->next()) {
+ for (Map<int, Octant::ItemInstances>::Element *F = E->get()->items.front(); F; F = F->next()) {
VS::get_singleton()->free(F->get().multimesh_instance);
}
-
if (E->get()->collision_debug.is_valid())
VS::get_singleton()->free(E->get()->collision_debug);
if (E->get()->collision_debug_instance.is_valid())
@@ -826,7 +784,6 @@ void GridMap::_clear_internal(bool p_keep_areas) {
PhysicsServer::get_singleton()->free(E->get()->static_body);
memdelete(E->get());
-
}
octant_map.clear();
@@ -835,253 +792,231 @@ void GridMap::_clear_internal(bool p_keep_areas) {
if (p_keep_areas)
return;
- for (Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
-
+ for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
VS::get_singleton()->free(E->get()->base_portal);
VS::get_singleton()->free(E->get()->instance);
- for(int i=0;i<E->get()->portals.size();i++) {
+ for (int i = 0; i < E->get()->portals.size(); i++) {
VS::get_singleton()->free(E->get()->portals[i].instance);
}
memdelete(E->get());
}
-
}
void GridMap::clear() {
_clear_internal();
-
}
-void GridMap::resource_changed(const RES& p_res) {
+void GridMap::resource_changed(const RES &p_res) {
_recreate_octant_data();
}
-
void GridMap::_update_dirty_map_callback() {
if (!awaiting_update)
return;
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
_octant_update(E->key());
}
-
- awaiting_update=false;
-
+ awaiting_update = false;
}
-
void GridMap::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_theme","theme:MeshLibrary"),&GridMap::set_theme);
- ClassDB::bind_method(D_METHOD("get_theme:MeshLibrary"),&GridMap::get_theme);
+ ClassDB::bind_method(D_METHOD("set_theme", "theme:MeshLibrary"), &GridMap::set_theme);
+ ClassDB::bind_method(D_METHOD("get_theme:MeshLibrary"), &GridMap::get_theme);
- ClassDB::bind_method(D_METHOD("set_cell_size","size"),&GridMap::set_cell_size);
- ClassDB::bind_method(D_METHOD("get_cell_size"),&GridMap::get_cell_size);
+ ClassDB::bind_method(D_METHOD("set_cell_size", "size"), &GridMap::set_cell_size);
+ ClassDB::bind_method(D_METHOD("get_cell_size"), &GridMap::get_cell_size);
- 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_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", "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("_recreate_octants"),&GridMap::_recreate_octants);
- ClassDB::bind_method(D_METHOD("_update_dirty_map_callback"),&GridMap::_update_dirty_map_callback);
- ClassDB::bind_method(D_METHOD("resource_changed","resource"),&GridMap::resource_changed);
-
- ClassDB::bind_method(D_METHOD("set_center_x","enable"),&GridMap::set_center_x);
- ClassDB::bind_method(D_METHOD("get_center_x"),&GridMap::get_center_x);
- ClassDB::bind_method(D_METHOD("set_center_y","enable"),&GridMap::set_center_y);
- ClassDB::bind_method(D_METHOD("get_center_y"),&GridMap::get_center_y);
- ClassDB::bind_method(D_METHOD("set_center_z","enable"),&GridMap::set_center_z);
- ClassDB::bind_method(D_METHOD("get_center_z"),&GridMap::get_center_z);
-
- ClassDB::bind_method(D_METHOD("set_clip","enabled","clipabove","floor","axis"),&GridMap::set_clip,DEFVAL(true),DEFVAL(0),DEFVAL(Vector3::AXIS_X));
-
- ClassDB::bind_method(D_METHOD("create_area","id","area"),&GridMap::create_area);
- ClassDB::bind_method(D_METHOD("area_get_bounds","area","bounds"),&GridMap::area_get_bounds);
- ClassDB::bind_method(D_METHOD("area_set_exterior_portal","area","enable"),&GridMap::area_set_exterior_portal);
- ClassDB::bind_method(D_METHOD("area_set_name","area","name"),&GridMap::area_set_name);
- ClassDB::bind_method(D_METHOD("area_get_name","area"),&GridMap::area_get_name);
- ClassDB::bind_method(D_METHOD("area_is_exterior_portal","area"),&GridMap::area_is_exterior_portal);
- ClassDB::bind_method(D_METHOD("area_set_portal_disable_distance","area","distance"),&GridMap::area_set_portal_disable_distance);
- ClassDB::bind_method(D_METHOD("area_get_portal_disable_distance","area"),&GridMap::area_get_portal_disable_distance);
- ClassDB::bind_method(D_METHOD("area_set_portal_disable_color","area","color"),&GridMap::area_set_portal_disable_color);
- ClassDB::bind_method(D_METHOD("area_get_portal_disable_color","area"),&GridMap::area_get_portal_disable_color);
- ClassDB::bind_method(D_METHOD("erase_area","area"),&GridMap::erase_area);
- ClassDB::bind_method(D_METHOD("get_unused_area_id","area"),&GridMap::get_unused_area_id);
-
- ClassDB::bind_method(D_METHOD("clear"),&GridMap::clear);
-
- ClassDB::bind_method(D_METHOD("get_meshes"),&GridMap::get_meshes);
-
- BIND_CONSTANT( INVALID_CELL_ITEM );
-
+ ClassDB::bind_method(D_METHOD("_update_dirty_map_callback"), &GridMap::_update_dirty_map_callback);
+ ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &GridMap::resource_changed);
+
+ ClassDB::bind_method(D_METHOD("set_center_x", "enable"), &GridMap::set_center_x);
+ ClassDB::bind_method(D_METHOD("get_center_x"), &GridMap::get_center_x);
+ ClassDB::bind_method(D_METHOD("set_center_y", "enable"), &GridMap::set_center_y);
+ ClassDB::bind_method(D_METHOD("get_center_y"), &GridMap::get_center_y);
+ ClassDB::bind_method(D_METHOD("set_center_z", "enable"), &GridMap::set_center_z);
+ ClassDB::bind_method(D_METHOD("get_center_z"), &GridMap::get_center_z);
+
+ ClassDB::bind_method(D_METHOD("set_clip", "enabled", "clipabove", "floor", "axis"), &GridMap::set_clip, DEFVAL(true), DEFVAL(0), DEFVAL(Vector3::AXIS_X));
+
+ ClassDB::bind_method(D_METHOD("create_area", "id", "area"), &GridMap::create_area);
+ ClassDB::bind_method(D_METHOD("area_get_bounds", "area", "bounds"), &GridMap::area_get_bounds);
+ ClassDB::bind_method(D_METHOD("area_set_exterior_portal", "area", "enable"), &GridMap::area_set_exterior_portal);
+ ClassDB::bind_method(D_METHOD("area_set_name", "area", "name"), &GridMap::area_set_name);
+ ClassDB::bind_method(D_METHOD("area_get_name", "area"), &GridMap::area_get_name);
+ ClassDB::bind_method(D_METHOD("area_is_exterior_portal", "area"), &GridMap::area_is_exterior_portal);
+ ClassDB::bind_method(D_METHOD("area_set_portal_disable_distance", "area", "distance"), &GridMap::area_set_portal_disable_distance);
+ ClassDB::bind_method(D_METHOD("area_get_portal_disable_distance", "area"), &GridMap::area_get_portal_disable_distance);
+ ClassDB::bind_method(D_METHOD("area_set_portal_disable_color", "area", "color"), &GridMap::area_set_portal_disable_color);
+ ClassDB::bind_method(D_METHOD("area_get_portal_disable_color", "area"), &GridMap::area_get_portal_disable_color);
+ ClassDB::bind_method(D_METHOD("erase_area", "area"), &GridMap::erase_area);
+ ClassDB::bind_method(D_METHOD("get_unused_area_id", "area"), &GridMap::get_unused_area_id);
+
+ ClassDB::bind_method(D_METHOD("clear"), &GridMap::clear);
+
+ ClassDB::bind_method(D_METHOD("get_meshes"), &GridMap::get_meshes);
+
+ BIND_CONSTANT(INVALID_CELL_ITEM);
}
void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3::Axis p_axis) {
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;
- clip_axis=p_axis;
- clip_above=p_clip_above;
+ clip = p_enabled;
+ clip_floor = p_floor;
+ clip_axis = p_axis;
+ clip_above = p_clip_above;
//make it all update
- for(Map<OctantKey,Octant*>::Element *E=octant_map.front();E;E=E->next()) {
-
- Octant *g=E->get();
- g->dirty=true;
+ for (Map<OctantKey, Octant *>::Element *E = octant_map.front(); E; E = E->next()) {
+ Octant *g = E->get();
+ g->dirty = true;
}
- awaiting_update=true;
+ awaiting_update = true;
_update_dirty_map_callback();
}
-
void GridMap::_update_areas() {
//clear the portals
- for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
+ for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
//this should somehow be faster...
- Area& a=*E->get();
+ Area &a = *E->get();
a.portals.clear();
if (a.instance.is_valid()) {
VisualServer::get_singleton()->free(a.instance);
- a.instance=RID();
+ a.instance = RID();
}
}
//test all areas against all areas and create portals - this sucks (slow :( )
- for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
- Area& a=*E->get();
+ for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
+ Area &a = *E->get();
if (a.exterior_portal) //that's pretty much all it does... yes it is
continue;
- Vector3 from_a(a.from.x,a.from.y,a.from.z);
- Vector3 to_a(a.to.x,a.to.y,a.to.z);
+ Vector3 from_a(a.from.x, a.from.y, a.from.z);
+ Vector3 to_a(a.to.x, a.to.y, a.to.z);
- for(Map<int,Area*>::Element *F=area_map.front();F;F=F->next()) {
+ for (Map<int, Area *>::Element *F = area_map.front(); F; F = F->next()) {
- Area& b=*F->get();
- Vector3 from_b(b.from.x,b.from.y,b.from.z);
- Vector3 to_b(b.to.x,b.to.y,b.to.z);
+ Area &b = *F->get();
+ Vector3 from_b(b.from.x, b.from.y, b.from.z);
+ Vector3 to_b(b.to.x, b.to.y, b.to.z);
// initially test intersection and discards
- int axis=-1;
- float sign=0;
- bool valid=true;
- Vector3 axmin,axmax;
-
+ int axis = -1;
+ float sign = 0;
+ bool valid = true;
+ Vector3 axmin, axmax;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (from_a[i]==to_b[i]) {
+ if (from_a[i] == to_b[i]) {
- if (axis!=-1) {
- valid=false;
+ if (axis != -1) {
+ valid = false;
break;
}
- axis=i;
- sign=-1;
- } else if (from_b[i]==to_a[i]) {
+ axis = i;
+ sign = -1;
+ } else if (from_b[i] == to_a[i]) {
- if (axis!=-1) {
- valid=false;
+ if (axis != -1) {
+ valid = false;
break;
}
- axis=i;
- sign=+1;
+ axis = i;
+ sign = +1;
}
-
- if (from_a[i] > to_b[i] || to_a[i] < from_b[i] ) {
- valid=false;
+ if (from_a[i] > to_b[i] || to_a[i] < from_b[i]) {
+ valid = false;
break;
} else {
- axmin[i]= ( from_a[i] > from_b[i] ) ? from_a[i] :from_b[i];
- axmax[i]= ( to_a[i] < to_b[i] ) ? to_a[i] :to_b[i];
-
+ axmin[i] = (from_a[i] > from_b[i]) ? from_a[i] : from_b[i];
+ axmax[i] = (to_a[i] < to_b[i]) ? to_a[i] : to_b[i];
}
-
-
}
- if (axis==-1 || !valid)
+ if (axis == -1 || !valid)
continue;
Transform xf;
+ for (int i = 0; i < 3; i++) {
- for(int i=0;i<3;i++) {
-
-
-
- int ax=(axis+i)%3;
+ int ax = (axis + i) % 3;
Vector3 axis_vec;
- float scale = (i==0)?sign:((axmax[ax]-axmin[ax])*cell_size);
- axis_vec[ax]=scale;
- xf.basis.set_axis((2+i)%3,axis_vec);
- xf.origin[i]=axmin[i]*cell_size;
-
+ float scale = (i == 0) ? sign : ((axmax[ax] - axmin[ax]) * cell_size);
+ axis_vec[ax] = scale;
+ xf.basis.set_axis((2 + i) % 3, axis_vec);
+ xf.origin[i] = axmin[i] * cell_size;
}
-
-
Area::Portal portal;
- portal.xform=xf;
+ portal.xform = xf;
a.portals.push_back(portal);
}
}
_update_area_instances();
-
}
void GridMap::_update_area_instances() {
Transform base_xform;
if (_in_tree)
- base_xform=get_global_transform();
+ base_xform = get_global_transform();
- for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
+ for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
//this should somehow be faster...
- Area& a=*E->get();
- if (a.instance.is_valid()!=_in_tree) {
+ Area &a = *E->get();
+ if (a.instance.is_valid() != _in_tree) {
if (!_in_tree) {
- for(int i=0;i<a.portals.size();i++) {
+ for (int i = 0; i < a.portals.size(); i++) {
- Area::Portal&p=a.portals[i];
+ Area::Portal &p = a.portals[i];
ERR_CONTINUE(!p.instance.is_valid());
VisualServer::get_singleton()->free(p.instance);
- p.instance=RID();
+ p.instance = RID();
}
VisualServer::get_singleton()->free(a.instance);
- a.instance=RID();
+ a.instance = RID();
} else {
//a.instance = VisualServer::get_singleton()->instance_create2(base_room,get_world()->get_scenario());
- for(int i=0;i<a.portals.size();i++) {
+ for (int i = 0; i < a.portals.size(); i++) {
- Area::Portal&p=a.portals[i];
+ Area::Portal &p = a.portals[i];
ERR_CONTINUE(p.instance.is_valid());
- p.instance=VisualServer::get_singleton()->instance_create2(a.base_portal,get_world()->get_scenario());
- VisualServer::get_singleton()->instance_set_room(p.instance,a.instance);
+ p.instance = VisualServer::get_singleton()->instance_create2(a.base_portal, get_world()->get_scenario());
+ VisualServer::get_singleton()->instance_set_room(p.instance, a.instance);
}
}
}
@@ -1089,62 +1024,57 @@ void GridMap::_update_area_instances() {
if (a.instance.is_valid()) {
Transform xform;
- Vector3 from_a(a.from.x,a.from.y,a.from.z);
- Vector3 to_a(a.to.x,a.to.y,a.to.z);
+ Vector3 from_a(a.from.x, a.from.y, a.from.z);
+ Vector3 to_a(a.to.x, a.to.y, a.to.z);
- for(int i=0;i<3;i++) {
- xform.origin[i]=from_a[i]*cell_size;
+ for (int i = 0; i < 3; i++) {
+ xform.origin[i] = from_a[i] * cell_size;
Vector3 s;
- s[i]=(to_a[i]-from_a[i])*cell_size;
- xform.basis.set_axis(i,s);
+ s[i] = (to_a[i] - from_a[i]) * cell_size;
+ xform.basis.set_axis(i, s);
}
+ VisualServer::get_singleton()->instance_set_transform(a.instance, base_xform * xform);
- VisualServer::get_singleton()->instance_set_transform(a.instance,base_xform * xform);
-
- for(int i=0;i<a.portals.size();i++) {
+ for (int i = 0; i < a.portals.size(); i++) {
- Area::Portal&p=a.portals[i];
+ Area::Portal &p = a.portals[i];
ERR_CONTINUE(!p.instance.is_valid());
- VisualServer::get_singleton()->instance_set_transform(p.instance,base_xform * xform);
-
+ VisualServer::get_singleton()->instance_set_transform(p.instance, base_xform * xform);
}
-
}
}
-
}
-Error GridMap::create_area(int p_id,const Rect3& p_bounds) {
+Error GridMap::create_area(int p_id, const Rect3 &p_bounds) {
- ERR_FAIL_COND_V(area_map.has(p_id),ERR_ALREADY_EXISTS);
+ ERR_FAIL_COND_V(area_map.has(p_id), ERR_ALREADY_EXISTS);
ERR_EXPLAIN("ID 0 is taken as global area, start from 1");
- ERR_FAIL_COND_V(p_id==0,ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(p_bounds.has_no_area(),ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_id == 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_bounds.has_no_area(), ERR_INVALID_PARAMETER);
// FIRST VALIDATE AREA
- IndexKey from,to;
- from.x=p_bounds.pos.x;
- from.y=p_bounds.pos.y;
- from.z=p_bounds.pos.z;
- to.x=p_bounds.pos.x+p_bounds.size.x;
- to.y=p_bounds.pos.y+p_bounds.size.y;
- to.z=p_bounds.pos.z+p_bounds.size.z;
-
-
- for(Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
+ IndexKey from, to;
+ from.x = p_bounds.pos.x;
+ from.y = p_bounds.pos.y;
+ from.z = p_bounds.pos.z;
+ to.x = p_bounds.pos.x + p_bounds.size.x;
+ to.y = p_bounds.pos.y + p_bounds.size.y;
+ to.z = p_bounds.pos.z + p_bounds.size.z;
+
+ for (Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
//this should somehow be faster...
- Area& a=*E->get();
+ Area &a = *E->get();
//does it interset with anything else?
- if ( from.x >= a.to.x ||
- to.x <= a.from.x ||
- from.y >= a.to.y ||
- to.y <= a.from.y ||
- from.z >= a.to.z ||
- to.z <= a.from.z ) {
+ if (from.x >= a.to.x ||
+ to.x <= a.from.x ||
+ from.y >= a.to.y ||
+ to.y <= a.from.y ||
+ from.z >= a.to.z ||
+ to.z <= a.from.z) {
// all good
} else {
@@ -1153,62 +1083,60 @@ Error GridMap::create_area(int p_id,const Rect3& p_bounds) {
}
}
-
- Area *area = memnew( Area );
- area->from=from;
- area->to=to;
- area->portal_disable_distance=0;
- area->exterior_portal=false;
- area->name="Area "+itos(p_id);
- area_map[p_id]=area;
+ Area *area = memnew(Area);
+ area->from = from;
+ area->to = to;
+ area->portal_disable_distance = 0;
+ area->exterior_portal = false;
+ area->name = "Area " + itos(p_id);
+ area_map[p_id] = area;
_recreate_octant_data();
return OK;
}
Rect3 GridMap::area_get_bounds(int p_area) const {
- ERR_FAIL_COND_V(!area_map.has(p_area),Rect3());
+ ERR_FAIL_COND_V(!area_map.has(p_area), Rect3());
const Area *a = area_map[p_area];
Rect3 aabb;
- aabb.pos=Vector3(a->from.x,a->from.y,a->from.z);
- aabb.size=Vector3(a->to.x,a->to.y,a->to.z)-aabb.pos;
+ aabb.pos = Vector3(a->from.x, a->from.y, a->from.z);
+ aabb.size = Vector3(a->to.x, a->to.y, a->to.z) - aabb.pos;
return aabb;
}
-void GridMap::area_set_name(int p_area,const String& p_name) {
+void GridMap::area_set_name(int p_area, const String &p_name) {
ERR_FAIL_COND(!area_map.has(p_area));
Area *a = area_map[p_area];
- a->name=p_name;
+ a->name = p_name;
}
String GridMap::area_get_name(int p_area) const {
- ERR_FAIL_COND_V(!area_map.has(p_area),"");
+ ERR_FAIL_COND_V(!area_map.has(p_area), "");
const Area *a = area_map[p_area];
return a->name;
}
-
-void GridMap::area_set_exterior_portal(int p_area,bool p_enable) {
+void GridMap::area_set_exterior_portal(int p_area, bool p_enable) {
ERR_FAIL_COND(!area_map.has(p_area));
Area *a = area_map[p_area];
- if (a->exterior_portal==p_enable)
+ if (a->exterior_portal == p_enable)
return;
- a->exterior_portal=p_enable;
+ a->exterior_portal = p_enable;
_recreate_octant_data();
}
bool GridMap::area_is_exterior_portal(int p_area) const {
- ERR_FAIL_COND_V(!area_map.has(p_area),false);
+ ERR_FAIL_COND_V(!area_map.has(p_area), false);
const Area *a = area_map[p_area];
return a->exterior_portal;
@@ -1219,13 +1147,12 @@ void GridMap::area_set_portal_disable_distance(int p_area, float p_distance) {
ERR_FAIL_COND(!area_map.has(p_area));
Area *a = area_map[p_area];
- a->portal_disable_distance=p_distance;
-
+ a->portal_disable_distance = p_distance;
}
float GridMap::area_get_portal_disable_distance(int p_area) const {
- ERR_FAIL_COND_V(!area_map.has(p_area),0);
+ ERR_FAIL_COND_V(!area_map.has(p_area), 0);
const Area *a = area_map[p_area];
return a->portal_disable_distance;
@@ -1236,13 +1163,12 @@ void GridMap::area_set_portal_disable_color(int p_area, Color p_color) {
ERR_FAIL_COND(!area_map.has(p_area));
Area *a = area_map[p_area];
- a->portal_disable_color=p_color;
-
+ a->portal_disable_color = p_color;
}
Color GridMap::area_get_portal_disable_color(int p_area) const {
- ERR_FAIL_COND_V(!area_map.has(p_area),Color());
+ ERR_FAIL_COND_V(!area_map.has(p_area), Color());
const Area *a = area_map[p_area];
return a->portal_disable_color;
@@ -1250,34 +1176,29 @@ Color GridMap::area_get_portal_disable_color(int p_area) const {
void GridMap::get_area_list(List<int> *p_areas) const {
- for(const Map<int,Area*>::Element *E=area_map.front();E;E=E->next()) {
+ for (const Map<int, Area *>::Element *E = area_map.front(); E; E = E->next()) {
p_areas->push_back(E->key());
}
-
}
-
GridMap::Area::Portal::~Portal() {
if (instance.is_valid())
VisualServer::get_singleton()->free(instance);
}
-
GridMap::Area::Area() {
- base_portal=VisualServer::get_singleton()->portal_create();
- Vector< Point2 > points;
- points.push_back( Point2( 0, 1 ) );
- points.push_back( Point2( 1, 1 ) );
- points.push_back( Point2( 1, 0 ) );
- points.push_back( Point2( 0, 0 ) );
- VisualServer::get_singleton()->portal_set_shape(base_portal,points);
-
+ base_portal = VisualServer::get_singleton()->portal_create();
+ Vector<Point2> points;
+ points.push_back(Point2(0, 1));
+ points.push_back(Point2(1, 1));
+ points.push_back(Point2(1, 0));
+ points.push_back(Point2(0, 0));
+ VisualServer::get_singleton()->portal_set_shape(base_portal, points);
}
-
GridMap::Area::~Area() {
if (instance.is_valid())
@@ -1289,7 +1210,7 @@ void GridMap::erase_area(int p_area) {
ERR_FAIL_COND(!area_map.has(p_area));
- Area* a=area_map[p_area];
+ Area *a = area_map[p_area];
memdelete(a);
area_map.erase(p_area);
_recreate_octant_data();
@@ -1300,92 +1221,79 @@ int GridMap::get_unused_area_id() const {
if (area_map.empty())
return 1;
else
- return area_map.back()->key()+1;
+ return area_map.back()->key() + 1;
}
void GridMap::set_cell_scale(float p_scale) {
- cell_scale=p_scale;
+ cell_scale = p_scale;
_queue_dirty_map();
}
-float GridMap::get_cell_scale() const{
+float GridMap::get_cell_scale() const {
return cell_scale;
}
-
-
-
Array GridMap::get_meshes() {
if (theme.is_null())
return Array();
- Vector3 ofs(cell_size*0.5*int(center_x),cell_size*0.5*int(center_y),cell_size*0.5*int(center_z));
+ Vector3 ofs(cell_size * 0.5 * int(center_x), cell_size * 0.5 * int(center_y), cell_size * 0.5 * int(center_z));
Array meshes;
- for (Map<IndexKey,Cell>::Element *E=cell_map.front();E;E=E->next()) {
-
+ for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) {
int id = E->get().item;
if (!theme->has_item(id))
continue;
- Ref<Mesh> mesh=theme->get_item_mesh(id);
+ Ref<Mesh> mesh = theme->get_item_mesh(id);
if (mesh.is_null())
continue;
- IndexKey ik=E->key();
+ IndexKey ik = E->key();
- Vector3 cellpos = Vector3(ik.x,ik.y,ik.z );
+ Vector3 cellpos = Vector3(ik.x, ik.y, ik.z);
Transform xform;
xform.basis.set_orthogonal_index(E->get().rot);
-
- xform.set_origin( cellpos*cell_size+ofs);
- xform.basis.scale(Vector3(cell_scale,cell_scale,cell_scale));
+ xform.set_origin(cellpos * cell_size + ofs);
+ xform.basis.scale(Vector3(cell_scale, cell_scale, cell_scale));
meshes.push_back(xform);
meshes.push_back(mesh);
-
}
return meshes;
}
-
-
-
GridMap::GridMap() {
- cell_size=2;
- octant_size=4;
- awaiting_update=false;
- _in_tree=false;
- center_x=true;
- center_y=true;
- center_z=true;
-
- clip=false;
- clip_floor=0;
- clip_axis=Vector3::AXIS_Z;
- clip_above=true;
- cell_scale=1.0;
+ cell_size = 2;
+ octant_size = 4;
+ awaiting_update = false;
+ _in_tree = false;
+ center_x = true;
+ center_y = true;
+ center_z = true;
+ clip = false;
+ clip_floor = 0;
+ clip_axis = Vector3::AXIS_Z;
+ clip_above = true;
+ cell_scale = 1.0;
navigation = NULL;
set_notify_transform(true);
}
-
GridMap::~GridMap() {
if (!theme.is_null())
theme->unregister_owner(this);
clear();
-
}
-
diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h
index 5d4133383b..2a0c2b9646 100644
--- a/modules/gridmap/grid_map.h
+++ b/modules/gridmap/grid_map.h
@@ -29,26 +29,23 @@
#ifndef GRID_MAP_H
#define GRID_MAP_H
-
-#include "scene/resources/mesh_library.h"
-#include "scene/3d/spatial.h"
#include "scene/3d/navigation.h"
+#include "scene/3d/spatial.h"
+#include "scene/resources/mesh_library.h"
#include "scene/resources/multimesh.h"
//heh heh, godotsphir!! this shares no code and the design is completely different with previous projects i've done..
//should scale better with hardware that supports instancing
-
class BakedLightInstance;
class GridMap : public Spatial {
-
- GDCLASS( GridMap, Spatial );
+ GDCLASS(GridMap, Spatial);
enum {
- MAP_DIRTY_TRANSFORMS=1,
- MAP_DIRTY_INSTANCES=2,
+ MAP_DIRTY_TRANSFORMS = 1,
+ MAP_DIRTY_INSTANCES = 2,
};
union IndexKey {
@@ -60,12 +57,12 @@ class GridMap : public Spatial {
};
uint64_t key;
- _FORCE_INLINE_ bool operator<(const IndexKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const IndexKey &p_key) const {
return key < p_key.key;
}
- IndexKey() { key=0; }
+ IndexKey() { key = 0; }
};
/**
@@ -75,12 +72,16 @@ class GridMap : public Spatial {
struct {
unsigned int item : 16;
- unsigned int rot:5;
- unsigned int layer:8;
+ unsigned int rot : 5;
+ unsigned int layer : 8;
};
uint32_t cell;
- Cell() { item=0; rot=0; layer=0; }
+ Cell() {
+ item = 0;
+ rot = 0;
+ layer = 0;
+ }
};
/**
@@ -108,8 +109,8 @@ class GridMap : public Spatial {
bool dirty;
RID static_body;
- Map<int,ItemInstances> items;
- Map<IndexKey,NavMesh> navmesh_ids;
+ Map<int, ItemInstances> items;
+ Map<IndexKey, NavMesh> navmesh_ids;
};
union OctantKey {
@@ -123,13 +124,13 @@ class GridMap : public Spatial {
uint64_t key;
- _FORCE_INLINE_ bool operator<(const OctantKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const OctantKey &p_key) const {
return key < p_key.key;
}
//OctantKey(const IndexKey& p_k, int p_item) { indexkey=p_k.key; item=p_item; }
- OctantKey() { key=0; }
+ OctantKey() { key = 0; }
};
Transform last_transform;
@@ -137,7 +138,7 @@ class GridMap : public Spatial {
bool _in_tree;
float cell_size;
int octant_size;
- bool center_x,center_y,center_z;
+ bool center_x, center_y, center_z;
float cell_scale;
Navigation *navigation;
@@ -146,7 +147,6 @@ class GridMap : public Spatial {
int clip_floor;
Vector3::Axis clip_axis;
-
/**
* @brief An Area is something like a room: it has doors, and Octants can choose to belong to it.
*/
@@ -173,11 +173,9 @@ class GridMap : public Spatial {
Ref<MeshLibrary> theme;
- Map<OctantKey,Octant*> octant_map;
- Map<IndexKey,Cell> cell_map;
- Map<int,Area*> area_map;
-
-
+ Map<OctantKey, Octant *> octant_map;
+ Map<IndexKey, Cell> cell_map;
+ Map<int, Area *> area_map;
void _recreate_octant_data();
@@ -189,11 +187,11 @@ class GridMap : public Spatial {
float param[VS::LIGHT_PARAM_MAX];
};
- _FORCE_INLINE_ int _find_area(const IndexKey& p_pos) const;
+ _FORCE_INLINE_ int _find_area(const IndexKey &p_pos) const;
_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;
+ return Vector3(p_key.x, p_key.y, p_key.z) * cell_size * octant_size;
}
void _octant_enter_world(const OctantKey &p_key);
@@ -201,37 +199,33 @@ class GridMap : public Spatial {
void _octant_exit_world(const OctantKey &p_key);
void _octant_update(const OctantKey &p_key);
void _octant_transform(const OctantKey &p_key);
- void _octant_clear_navmesh(const GridMap::OctantKey&);
+ void _octant_clear_navmesh(const GridMap::OctantKey &);
bool awaiting_update;
void _queue_dirty_map();
void _update_dirty_map_callback();
- void resource_changed(const RES& p_res);
-
+ void resource_changed(const RES &p_res);
void _update_areas();
void _update_area_instances();
- void _clear_internal(bool p_keep_areas=false);
+ void _clear_internal(bool p_keep_areas = false);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
-
public:
-
enum {
- INVALID_CELL_ITEM=-1
+ INVALID_CELL_ITEM = -1
};
- void set_theme(const Ref<MeshLibrary>& p_theme);
+ void set_theme(const Ref<MeshLibrary> &p_theme);
Ref<MeshLibrary> get_theme() const;
void set_cell_size(float p_size);
@@ -240,7 +234,6 @@ public:
void set_octant_size(int p_size);
int get_octant_size() const;
-
void set_center_x(bool p_enable);
bool get_center_x() const;
void set_center_y(bool p_enable);
@@ -248,16 +241,16 @@ 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_orientation=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(int p_x, int p_y, int p_z, int p_item, int p_orientation = 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_clip(bool p_enabled, bool p_clip_above=true, int p_floor=0, Vector3::Axis p_axis=Vector3::AXIS_X);
+ void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X);
- Error create_area(int p_id,const Rect3& p_area);
+ Error create_area(int p_id, const Rect3 &p_area);
Rect3 area_get_bounds(int p_area) const;
- void area_set_exterior_portal(int p_area,bool p_enable);
- void area_set_name(int p_area,const String& p_name);
+ void area_set_exterior_portal(int p_area, bool p_enable);
+ void area_set_name(int p_area, const String &p_name);
String area_get_name(int p_area) const;
bool area_is_exterior_portal(int p_area) const;
void area_set_portal_disable_distance(int p_area, float p_distance);
@@ -271,11 +264,8 @@ public:
void set_cell_scale(float p_scale);
float get_cell_scale() const;
-
-
Array get_meshes();
-
void clear();
GridMap();
diff --git a/modules/gridmap/grid_map_editor_plugin.cpp b/modules/gridmap/grid_map_editor_plugin.cpp
index a5d2f84c68..a6a3a03503 100644
--- a/modules/gridmap/grid_map_editor_plugin.cpp
+++ b/modules/gridmap/grid_map_editor_plugin.cpp
@@ -27,59 +27,53 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "grid_map_editor_plugin.h"
+#include "editor/editor_settings.h"
#include "editor/plugins/spatial_editor_plugin.h"
#include "scene/3d/camera.h"
-#include "editor/editor_settings.h"
-#include "os/keyboard.h"
#include "geometry.h"
+#include "os/keyboard.h"
void GridMapEditor::_node_removed(Node *p_node) {
- if(p_node==node) {
- node=NULL;
+ if (p_node == node) {
+ node = NULL;
hide();
theme_pallete->hide();
}
-
}
-
void GridMapEditor::_configure() {
- if(!node)
+ if (!node)
return;
update_grid();
-
}
-void GridMapEditor::_menu_option(int p_option) {
+void GridMapEditor::_menu_option(int p_option) {
-
- switch(p_option) {
+ switch (p_option) {
case MENU_OPTION_CONFIGURE: {
-
} 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);
+ int index = options->get_popup()->get_item_index(MENU_OPTION_LOCK_VIEW);
+ lock_view = !options->get_popup()->is_item_checked(index);
- options->get_popup()->set_item_checked(index,lock_view);
+ options->get_popup()->set_item_checked(index, lock_view);
} break;
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);
+ 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);
}
_update_clip();
@@ -88,102 +82,100 @@ void GridMapEditor::_menu_option(int p_option) {
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);
- options->get_popup()->set_item_checked(idx,i==new_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);
+ options->get_popup()->set_item_checked(idx, i == new_axis);
}
- edit_axis=Vector3::Axis(new_axis);
+ edit_axis = Vector3::Axis(new_axis);
update_grid();
_update_clip();
} break;
case MENU_OPTION_CURSOR_ROTATE_Y: {
Basis r;
- if (input_action==INPUT_DUPLICATE) {
+ if (input_action == INPUT_DUPLICATE) {
r.set_orthogonal_index(selection.duplicate_rot);
- r.rotate(Vector3(0,1,0),-Math_PI/2.0);
- selection.duplicate_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0);
+ selection.duplicate_rot = r.get_orthogonal_index();
_update_duplicate_indicator();
break;
}
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(0,1,0),-Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 1, 0), -Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_X: {
Basis r;
- if (input_action==INPUT_DUPLICATE) {
+ if (input_action == INPUT_DUPLICATE) {
r.set_orthogonal_index(selection.duplicate_rot);
- r.rotate(Vector3(1,0,0),-Math_PI/2.0);
- selection.duplicate_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0);
+ selection.duplicate_rot = r.get_orthogonal_index();
_update_duplicate_indicator();
break;
}
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(1,0,0),-Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(1, 0, 0), -Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_ROTATE_Z: {
Basis r;
- if (input_action==INPUT_DUPLICATE) {
+ if (input_action == INPUT_DUPLICATE) {
r.set_orthogonal_index(selection.duplicate_rot);
- r.rotate(Vector3(0,0,1),-Math_PI/2.0);
- selection.duplicate_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0);
+ selection.duplicate_rot = r.get_orthogonal_index();
_update_duplicate_indicator();
break;
}
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(0,0,1),-Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 0, 1), -Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Y: {
Basis r;
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(0,1,0),Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 1, 0), Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_X: {
Basis r;
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(1,0,0),Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(1, 0, 0), Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_BACK_ROTATE_Z: {
Basis r;
r.set_orthogonal_index(cursor_rot);
- r.rotate(Vector3(0,0,1),Math_PI/2.0);
- cursor_rot=r.get_orthogonal_index();
+ r.rotate(Vector3(0, 0, 1), Math_PI / 2.0);
+ cursor_rot = r.get_orthogonal_index();
_update_cursor_transform();
} break;
case MENU_OPTION_CURSOR_CLEAR_ROTATION: {
- if (input_action==INPUT_DUPLICATE) {
-
+ if (input_action == INPUT_DUPLICATE) {
- selection.duplicate_rot=0;
+ selection.duplicate_rot = 0;
_update_duplicate_indicator();
break;
}
- cursor_rot=0;
+ cursor_rot = 0;
_update_cursor_transform();
} break;
-
case MENU_OPTION_DUPLICATE_SELECTS: {
int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS);
- options->get_popup()->set_item_checked( idx, !options->get_popup()->is_item_checked( idx ) );
+ options->get_popup()->set_item_checked(idx, !options->get_popup()->is_item_checked(idx));
} break;
case MENU_OPTION_SELECTION_MAKE_AREA:
case MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR: {
@@ -191,37 +183,34 @@ void GridMapEditor::_menu_option(int p_option) {
if (!selection.active)
break;
int area = node->get_unused_area_id();
- Error err = node->create_area(area,Rect3(selection.begin,selection.end-selection.begin+Vector3(1,1,1)));
- if (err!=OK) {
-
-
+ Error err = node->create_area(area, Rect3(selection.begin, selection.end - selection.begin + Vector3(1, 1, 1)));
+ if (err != OK) {
}
- if (p_option==MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR) {
+ if (p_option == MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR) {
- node->area_set_exterior_portal(area,true);
+ node->area_set_exterior_portal(area, true);
}
_update_areas_display();
update_areas();
-
} break;
case MENU_OPTION_REMOVE_AREA: {
- if (selected_area<1)
+ if (selected_area < 1)
return;
node->erase_area(selected_area);
_update_areas_display();
update_areas();
} break;
case MENU_OPTION_SELECTION_DUPLICATE:
- if (!(selection.active && input_action==INPUT_NONE))
+ if (!(selection.active && input_action == INPUT_NONE))
return;
- if (last_mouseover==Vector3(-1,-1,-1)) //nono mouseovering anythin
+ if (last_mouseover == Vector3(-1, -1, -1)) //nono mouseovering anythin
break;
- input_action=INPUT_DUPLICATE;
- selection.click=last_mouseover;
- selection.current=last_mouseover;
- selection.duplicate_rot=0;
+ input_action = INPUT_DUPLICATE;
+ selection.click = last_mouseover;
+ selection.current = last_mouseover;
+ selection.duplicate_rot = 0;
_update_duplicate_indicator();
break;
case MENU_OPTION_SELECTION_CLEAR: {
@@ -230,28 +219,24 @@ void GridMapEditor::_menu_option(int p_option) {
_delete_selection();
-
} break;
case MENU_OPTION_GRIDMAP_SETTINGS: {
settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
} break;
-
}
}
void GridMapEditor::_update_cursor_transform() {
- cursor_transform=Transform();
- cursor_transform.origin=cursor_origin;
+ cursor_transform = Transform();
+ cursor_transform.origin = cursor_origin;
cursor_transform.basis.set_orthogonal_index(cursor_rot);
cursor_transform = node->get_transform() * cursor_transform;
-
if (cursor_instance.is_valid()) {
- VisualServer::get_singleton()->instance_set_transform(cursor_instance,cursor_transform);
- VisualServer::get_singleton()->instance_set_visible(cursor_instance,cursor_visible);
+ VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform);
+ VisualServer::get_singleton()->instance_set_visible(cursor_instance, cursor_visible);
}
-
}
void GridMapEditor::_update_selection_transform() {
@@ -260,93 +245,87 @@ void GridMapEditor::_update_selection_transform() {
Transform xf;
xf.basis.set_zero();
- VisualServer::get_singleton()->instance_set_transform(selection_instance,xf);
+ VisualServer::get_singleton()->instance_set_transform(selection_instance, xf);
return;
}
Transform xf;
- xf.scale(Vector3(1,1,1)*(Vector3(1,1,1)+(selection.end-selection.begin))*node->get_cell_size());
- xf.origin=selection.begin*node->get_cell_size();
-
- VisualServer::get_singleton()->instance_set_transform(selection_instance,node->get_global_transform() * xf);
+ xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size());
+ xf.origin = selection.begin * node->get_cell_size();
+ VisualServer::get_singleton()->instance_set_transform(selection_instance, node->get_global_transform() * xf);
}
void GridMapEditor::_validate_selection() {
if (!selection.active)
return;
- selection.begin=selection.click;
- selection.end=selection.current;
-
- if (selection.begin.x>selection.end.x)
- SWAP(selection.begin.x,selection.end.x);
- if (selection.begin.y>selection.end.y)
- SWAP(selection.begin.y,selection.end.y);
- if (selection.begin.z>selection.end.z)
- SWAP(selection.begin.z,selection.end.z);
+ selection.begin = selection.click;
+ selection.end = selection.current;
+ if (selection.begin.x > selection.end.x)
+ SWAP(selection.begin.x, selection.end.x);
+ if (selection.begin.y > selection.end.y)
+ SWAP(selection.begin.y, selection.end.y);
+ if (selection.begin.z > selection.end.z)
+ SWAP(selection.begin.z, selection.end.z);
_update_selection_transform();
}
-bool GridMapEditor::do_input_action(Camera* p_camera,const Point2& p_point,bool p_click) {
+bool GridMapEditor::do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click) {
if (!spatial_editor)
return false;
-
- if (selected_pallete<0 && input_action!=INPUT_COPY && input_action!=INPUT_SELECT && input_action!=INPUT_DUPLICATE)
+ if (selected_pallete < 0 && input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE)
return false;
Ref<MeshLibrary> theme = node->get_theme();
if (theme.is_null())
return false;
- if (input_action!=INPUT_COPY && input_action!=INPUT_SELECT && input_action!=INPUT_DUPLICATE && !theme->has_item(selected_pallete))
+ if (input_action != INPUT_COPY && input_action != INPUT_SELECT && input_action != INPUT_DUPLICATE && !theme->has_item(selected_pallete))
return false;
Camera *camera = p_camera;
Vector3 from = camera->project_ray_origin(p_point);
Vector3 normal = camera->project_ray_normal(p_point);
Transform local_xform = node->get_global_transform().affine_inverse();
- Vector<Plane> planes=camera->get_frustum();
- from=local_xform.xform(from);
- normal=local_xform.basis.xform(normal).normalized();
-
+ Vector<Plane> planes = camera->get_frustum();
+ from = local_xform.xform(from);
+ normal = local_xform.basis.xform(normal).normalized();
Plane p;
- p.normal[edit_axis]=1.0;
- p.d=edit_floor[edit_axis]*node->get_cell_size();
+ p.normal[edit_axis] = 1.0;
+ p.d = edit_floor[edit_axis] * node->get_cell_size();
Vector3 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++) {
+ for (int i = 0; i < planes.size(); i++) {
Plane fp = local_xform.xform(planes[i]);
if (fp.is_point_over(inters))
return false;
}
-
int cell[3];
- float cell_size[3]={node->get_cell_size(),node->get_cell_size(),node->get_cell_size()};
+ float cell_size[3] = { node->get_cell_size(), node->get_cell_size(), node->get_cell_size() };
- last_mouseover=Vector3(-1,-1,-1);
+ last_mouseover = Vector3(-1, -1, -1);
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (i==edit_axis)
- cell[i]=edit_floor[i];
+ if (i == edit_axis)
+ cell[i] = edit_floor[i];
else {
- cell[i]=inters[i]/node->get_cell_size();
- if (inters[i]<0)
- cell[i]-=1; //compensate negative
- grid_ofs[i]=cell[i]*cell_size[i];
+ cell[i] = inters[i] / node->get_cell_size();
+ if (inters[i] < 0)
+ cell[i] -= 1; //compensate negative
+ grid_ofs[i] = cell[i] * cell_size[i];
}
/*if (cell[i]<0 || cell[i]>=grid_size[i]) {
@@ -357,68 +336,65 @@ bool GridMapEditor::do_input_action(Camera* p_camera,const Point2& p_point,bool
}*/
}
- last_mouseover=Vector3(cell[0],cell[1],cell[2]);
- VS::get_singleton()->instance_set_transform(grid_instance[edit_axis],Transform(Basis(),grid_ofs));
-
+ last_mouseover = Vector3(cell[0], cell[1], cell[2]);
+ VS::get_singleton()->instance_set_transform(grid_instance[edit_axis], Transform(Basis(), grid_ofs));
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;
+ 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;
_update_cursor_transform();
-
}
- if (input_action==INPUT_DUPLICATE) {
+ if (input_action == INPUT_DUPLICATE) {
- selection.current=Vector3(cell[0],cell[1],cell[2]);
+ selection.current = Vector3(cell[0], cell[1], cell[2]);
_update_duplicate_indicator();
- } else if (input_action==INPUT_SELECT) {
+ } else if (input_action == INPUT_SELECT) {
- selection.current=Vector3(cell[0],cell[1],cell[2]);
+ selection.current = Vector3(cell[0], cell[1], cell[2]);
if (p_click)
- selection.click=selection.current;
- selection.active=true;
+ selection.click = selection.current;
+ selection.active = true;
_validate_selection();
return true;
- } else if (input_action==INPUT_COPY) {
+ } else if (input_action == INPUT_COPY) {
- int item=node->get_cell_item(cell[0],cell[1],cell[2]);
- if (item>=0) {
- selected_pallete=item;
+ int item = node->get_cell_item(cell[0], cell[1], cell[2]);
+ if (item >= 0) {
+ selected_pallete = item;
theme_pallete->set_current(item);
update_pallete();
_update_cursor_instance();
}
return true;
- } if (input_action==INPUT_PAINT) {
+ }
+ if (input_action == INPUT_PAINT) {
SetItem si;
- si.pos=Vector3(cell[0],cell[1],cell[2]);
- si.new_value=selected_pallete;
- 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.pos = Vector3(cell[0], cell[1], cell[2]);
+ si.new_value = selected_pallete;
+ 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]);
set_items.push_back(si);
- node->set_cell_item(cell[0],cell[1],cell[2],selected_pallete,cursor_rot);
+ node->set_cell_item(cell[0], cell[1], cell[2], selected_pallete, cursor_rot);
return true;
- } else if (input_action==INPUT_ERASE) {
+ } else if (input_action == INPUT_ERASE) {
SetItem si;
- si.pos=Vector3(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.pos = Vector3(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]);
set_items.push_back(si);
- node->set_cell_item(cell[0],cell[1],cell[2],-1);
+ node->set_cell_item(cell[0], cell[1], cell[2], -1);
return true;
}
-
return false;
-
}
void GridMapEditor::_delete_selection() {
@@ -427,269 +403,253 @@ void GridMapEditor::_delete_selection() {
return;
undo_redo->create_action("GridMap Delete Selection");
- for(int i=selection.begin.x;i<=selection.end.x;i++) {
+ for (int i = selection.begin.x; i <= selection.end.x; i++) {
- for(int j=selection.begin.y;j<=selection.end.y;j++) {
+ for (int j = selection.begin.y; j <= selection.end.y; j++) {
- for(int k=selection.begin.z;k<=selection.end.z;k++) {
+ 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));
+ 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));
}
-
}
}
undo_redo->commit_action();
- selection.active=false;
+ selection.active = false;
_validate_selection();
-
}
void GridMapEditor::_update_duplicate_indicator() {
- if (!selection.active || input_action!=INPUT_DUPLICATE) {
+ if (!selection.active || input_action != INPUT_DUPLICATE) {
Transform xf;
xf.basis.set_zero();
- VisualServer::get_singleton()->instance_set_transform(duplicate_instance,xf);
+ VisualServer::get_singleton()->instance_set_transform(duplicate_instance, xf);
return;
}
Transform xf;
- xf.scale(Vector3(1,1,1)*(Vector3(1,1,1)+(selection.end-selection.begin))*node->get_cell_size());
- xf.origin=(selection.begin+(selection.current-selection.click))*node->get_cell_size();
+ xf.scale(Vector3(1, 1, 1) * (Vector3(1, 1, 1) + (selection.end - selection.begin)) * node->get_cell_size());
+ xf.origin = (selection.begin + (selection.current - selection.click)) * node->get_cell_size();
Basis rot;
rot.set_orthogonal_index(selection.duplicate_rot);
xf.basis = rot * xf.basis;
- VisualServer::get_singleton()->instance_set_transform(duplicate_instance,node->get_global_transform() * xf);
-
-
+ VisualServer::get_singleton()->instance_set_transform(duplicate_instance, node->get_global_transform() * xf);
}
-struct __Item { Vector3 pos; int rot; int item ; };
+struct __Item {
+ Vector3 pos;
+ int rot;
+ int item;
+};
void GridMapEditor::_duplicate_paste() {
if (!selection.active)
return;
int idx = options->get_popup()->get_item_index(MENU_OPTION_DUPLICATE_SELECTS);
- bool reselect = options->get_popup()->is_item_checked( idx );
+ bool reselect = options->get_popup()->is_item_checked(idx);
-
-
- List< __Item > items;
+ List<__Item> items;
Basis rot;
rot.set_orthogonal_index(selection.duplicate_rot);
- for(int i=selection.begin.x;i<=selection.end.x;i++) {
+ for (int i = selection.begin.x; i <= selection.end.x; i++) {
- for(int j=selection.begin.y;j<=selection.end.y;j++) {
+ for (int j = selection.begin.y; j <= selection.end.y; j++) {
- for(int k=selection.begin.z;k<=selection.end.z;k++) {
+ 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)
+ int itm = node->get_cell_item(i, j, k);
+ if (itm == GridMap::INVALID_CELL_ITEM)
continue;
- int orientation = node->get_cell_item_orientation(i,j,k);
+ int orientation = node->get_cell_item_orientation(i, j, k);
__Item item;
- Vector3 rel=Vector3(i,j,k)-selection.begin;
+ Vector3 rel = Vector3(i, j, k) - selection.begin;
rel = rot.xform(rel);
Basis orm;
orm.set_orthogonal_index(orientation);
orm = rot * orm;
- item.pos=selection.begin+rel;
- item.item=itm;
- item.rot=orm.get_orthogonal_index();
+ item.pos = selection.begin + rel;
+ item.item = itm;
+ item.rot = orm.get_orthogonal_index();
items.push_back(item);
}
-
}
}
- Vector3 ofs=selection.current-selection.click;
+ Vector3 ofs = selection.current - selection.click;
if (items.size()) {
undo_redo->create_action("GridMap Duplicate Selection");
- for(List< __Item >::Element *E=items.front();E;E=E->next()) {
- __Item &it=E->get();
- Vector3 pos = it.pos+ofs;
-
- undo_redo->add_do_method(node,"set_cell_item",pos.x,pos.y,pos.z,it.item,it.rot);
- 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));
+ for (List<__Item>::Element *E = items.front(); E; E = E->next()) {
+ __Item &it = E->get();
+ Vector3 pos = it.pos + ofs;
+ undo_redo->add_do_method(node, "set_cell_item", pos.x, pos.y, pos.z, it.item, it.rot);
+ 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->commit_action();
}
-
if (reselect) {
- selection.begin+=ofs;
- selection.end+=ofs;
- selection.click=selection.begin;
- selection.current=selection.end;
+ selection.begin += ofs;
+ selection.end += ofs;
+ selection.click = selection.begin;
+ selection.current = selection.end;
_validate_selection();
}
-
}
-bool GridMapEditor::forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) {
+bool GridMapEditor::forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event) {
if (!node) {
return false;
}
- if (edit_mode->get_selected()==0) { // regular click
+ if (edit_mode->get_selected() == 0) { // regular click
switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- if (p_event.mouse_button.button_index==BUTTON_WHEEL_UP && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) {
+ if (p_event.mouse_button.button_index == BUTTON_WHEEL_UP && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) {
if (p_event.mouse_button.pressed)
- floor->set_value( floor->get_value() +1);
+ floor->set_value(floor->get_value() + 1);
return true; //eaten
- } else if (p_event.mouse_button.button_index==BUTTON_WHEEL_DOWN && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) {
+ } else if (p_event.mouse_button.button_index == BUTTON_WHEEL_DOWN && (p_event.mouse_button.mod.command || p_event.mouse_button.mod.shift)) {
if (p_event.mouse_button.pressed)
- floor->set_value( floor->get_value() -1);
+ floor->set_value(floor->get_value() - 1);
return true;
}
if (p_event.mouse_button.pressed) {
- if (p_event.mouse_button.button_index==BUTTON_LEFT) {
+ if (p_event.mouse_button.button_index == BUTTON_LEFT) {
- if (input_action==INPUT_DUPLICATE) {
+ if (input_action == INPUT_DUPLICATE) {
//paste
_duplicate_paste();
- input_action=INPUT_NONE;
+ input_action = INPUT_NONE;
_update_duplicate_indicator();
} else if (p_event.mouse_button.mod.shift) {
- input_action=INPUT_SELECT;
+ input_action = INPUT_SELECT;
} else if (p_event.mouse_button.mod.command)
- input_action=INPUT_COPY;
+ input_action = INPUT_COPY;
else {
- input_action=INPUT_PAINT;
+ input_action = INPUT_PAINT;
set_items.clear();
}
- } else if (p_event.mouse_button.button_index==BUTTON_RIGHT)
- if (input_action==INPUT_DUPLICATE) {
+ } else if (p_event.mouse_button.button_index == BUTTON_RIGHT)
+ if (input_action == INPUT_DUPLICATE) {
- input_action=INPUT_NONE;
+ input_action = INPUT_NONE;
_update_duplicate_indicator();
} else {
- input_action=INPUT_ERASE;
+ input_action = INPUT_ERASE;
set_items.clear();
}
else
return false;
- return do_input_action(p_camera,Point2(p_event.mouse_button.x,p_event.mouse_button.y),true);
+ return do_input_action(p_camera, Point2(p_event.mouse_button.x, p_event.mouse_button.y), true);
} else {
-
if (
- (p_event.mouse_button.button_index==BUTTON_RIGHT && input_action==INPUT_ERASE) ||
- (p_event.mouse_button.button_index==BUTTON_LEFT && input_action==INPUT_PAINT) ) {
+ (p_event.mouse_button.button_index == BUTTON_RIGHT && input_action == INPUT_ERASE) ||
+ (p_event.mouse_button.button_index == BUTTON_LEFT && input_action == INPUT_PAINT)) {
if (set_items.size()) {
undo_redo->create_action("GridMap Paint");
- for(List<SetItem>::Element *E=set_items.front();E;E=E->next()) {
+ 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);
+ 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);
}
- for(List<SetItem>::Element *E=set_items.back();E;E=E->prev()) {
+ 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);
+ 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->commit_action();
}
set_items.clear();
- input_action=INPUT_NONE;
+ input_action = INPUT_NONE;
return true;
-
}
-
-
- if (p_event.mouse_button.button_index==BUTTON_LEFT && input_action!=INPUT_NONE) {
+ if (p_event.mouse_button.button_index == BUTTON_LEFT && input_action != INPUT_NONE) {
set_items.clear();
- input_action=INPUT_NONE;
+ input_action = INPUT_NONE;
return true;
}
- if (p_event.mouse_button.button_index==BUTTON_RIGHT && (input_action==INPUT_ERASE || input_action==INPUT_DUPLICATE)) {
- input_action=INPUT_NONE;
+ if (p_event.mouse_button.button_index == BUTTON_RIGHT && (input_action == INPUT_ERASE || input_action == INPUT_DUPLICATE)) {
+ input_action = INPUT_NONE;
return true;
}
}
} break;
case InputEvent::MOUSE_MOTION: {
- return do_input_action(p_camera,Point2(p_event.mouse_motion.x,p_event.mouse_motion.y),false);
+ return do_input_action(p_camera, Point2(p_event.mouse_motion.x, p_event.mouse_motion.y), false);
} break;
}
- } else if (edit_mode->get_selected()==1) {
+ } else if (edit_mode->get_selected() == 1) {
//area mode, select an area
switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- if (p_event.mouse_button.button_index==BUTTON_LEFT && p_event.mouse_button.pressed) {
+ if (p_event.mouse_button.button_index == BUTTON_LEFT && p_event.mouse_button.pressed) {
- Point2 point = Point2(p_event.mouse_motion.x,p_event.mouse_motion.y);
+ Point2 point = Point2(p_event.mouse_motion.x, p_event.mouse_motion.y);
Camera *camera = p_camera;
Vector3 from = camera->project_ray_origin(point);
Vector3 normal = camera->project_ray_normal(point);
Transform local_xform = node->get_global_transform().affine_inverse();
- from=local_xform.xform(from);
- normal=local_xform.basis.xform(normal).normalized();
+ from = local_xform.xform(from);
+ normal = local_xform.basis.xform(normal).normalized();
List<int> areas;
node->get_area_list(&areas);
- float min_d=1e10;
- int min_area=-1;
+ float min_d = 1e10;
+ int min_area = -1;
-
- for(List<int>::Element *E=areas.front();E;E=E->next()) {
+ for (List<int>::Element *E = areas.front(); E; E = E->next()) {
int area = E->get();
Rect3 aabb = node->area_get_bounds(area);
- aabb.pos*=node->get_cell_size();
- aabb.size*=node->get_cell_size();
-
+ aabb.pos *= node->get_cell_size();
+ aabb.size *= node->get_cell_size();
- Vector3 rclip,rnormal;
- if (!aabb.intersects_segment(from,from+normal*10000,&rclip,&rnormal))
+ Vector3 rclip, rnormal;
+ if (!aabb.intersects_segment(from, from + normal * 10000, &rclip, &rnormal))
continue;
float d = normal.dot(rclip);
- if (d<min_d) {
- min_d=d;
- min_area=area;
+ if (d < min_d) {
+ min_d = d;
+ min_area = area;
}
}
- selected_area=min_area;
+ selected_area = min_area;
update_areas();
-
}
} break;
}
-
}
-
return false;
}
@@ -697,12 +657,11 @@ struct _CGMEItemSort {
String name;
int id;
- _FORCE_INLINE_ bool operator<(const _CGMEItemSort& r_it) const { return name < r_it.name; }
-
+ _FORCE_INLINE_ bool operator<(const _CGMEItemSort &r_it) const { return name < r_it.name; }
};
void GridMapEditor::_set_display_mode(int p_mode) {
- if (display_mode==p_mode) {
+ if (display_mode == p_mode) {
return;
}
@@ -714,32 +673,32 @@ void GridMapEditor::_set_display_mode(int p_mode) {
mode_thumbnail->set_pressed(true);
}
- display_mode=p_mode;
+ display_mode = p_mode;
update_pallete();
}
-void GridMapEditor::update_pallete() {
+void GridMapEditor::update_pallete() {
int selected = theme_pallete->get_current();
theme_pallete->clear();
if (display_mode == DISPLAY_THUMBNAIL) {
theme_pallete->set_max_columns(0);
theme_pallete->set_icon_mode(ItemList::ICON_MODE_TOP);
- } else if (display_mode == DISPLAY_LIST){
+ } else if (display_mode == DISPLAY_LIST) {
theme_pallete->set_max_columns(1);
theme_pallete->set_icon_mode(ItemList::ICON_MODE_LEFT);
}
- float min_size = EDITOR_DEF("editors/grid_map/preview_size",64);
+ float min_size = EDITOR_DEF("editors/grid_map/preview_size", 64);
theme_pallete->set_fixed_icon_size(Size2(min_size, min_size));
- theme_pallete->set_fixed_column_width(min_size*3/2);
+ theme_pallete->set_fixed_column_width(min_size * 3 / 2);
theme_pallete->set_max_text_lines(2);
Ref<MeshLibrary> theme = node->get_theme();
if (theme.is_null()) {
- last_theme=NULL;
+ last_theme = NULL;
return;
}
@@ -747,65 +706,63 @@ void GridMapEditor::update_pallete() {
ids = theme->get_item_list();
List<_CGMEItemSort> il;
- for(int i=0;i<ids.size();i++) {
+ for (int i = 0; i < ids.size(); i++) {
_CGMEItemSort is;
- is.id=ids[i];
- is.name=theme->get_item_name(ids[i]);
+ is.id = ids[i];
+ is.name = theme->get_item_name(ids[i]);
il.push_back(is);
}
il.sort();
int item = 0;
- for(List<_CGMEItemSort>::Element *E=il.front();E;E=E->next()) {
+ for (List<_CGMEItemSort>::Element *E = il.front(); E; E = E->next()) {
int id = E->get().id;
theme_pallete->add_item("");
- String name=theme->get_item_name(id);
+ String name = theme->get_item_name(id);
Ref<Texture> preview = theme->get_item_preview(id);
if (!preview.is_null()) {
theme_pallete->set_item_icon(item, preview);
theme_pallete->set_item_tooltip(item, name);
}
- if (name!="") {
- theme_pallete->set_item_text(item,name);
+ if (name != "") {
+ theme_pallete->set_item_text(item, name);
}
theme_pallete->set_item_metadata(item, id);
item++;
}
- if (selected!=-1) {
+ if (selected != -1) {
theme_pallete->select(selected);
}
- last_theme=theme.operator->();
+ last_theme = theme.operator->();
}
-
void GridMapEditor::_area_renamed() {
- TreeItem * it = area_list->get_selected();
+ TreeItem *it = area_list->get_selected();
int area = it->get_metadata(0);
- if (area<1)
+ if (area < 1)
return;
- node->area_set_name(area,it->get_text(0));
+ node->area_set_name(area, it->get_text(0));
}
-
void GridMapEditor::_area_selected() {
- TreeItem * it = area_list->get_selected();
+ TreeItem *it = area_list->get_selected();
int area = it->get_metadata(0);
- if (area<1)
+ if (area < 1)
return;
- selected_area=area;
+ selected_area = area;
}
-void GridMapEditor::update_areas() {
+void GridMapEditor::update_areas() {
area_list->clear();
@@ -814,246 +771,221 @@ void GridMapEditor::update_areas() {
TreeItem *root = area_list->create_item(NULL);
area_list->set_hide_root(true);
- TreeItem *selected=NULL;
-
+ TreeItem *selected = NULL;
- for (List<int>::Element *E=areas.front();E;E=E->next()) {
+ for (List<int>::Element *E = areas.front(); E; E = E->next()) {
int area = E->get();
TreeItem *ti = area_list->create_item(root);
- String name=node->area_get_name(area);
+ String name = node->area_get_name(area);
- ti->set_metadata(0,area);
- ti->set_text(0,name);
- ti->set_editable(0,true);
- if (area==selected_area)
- selected=ti;
+ ti->set_metadata(0, area);
+ ti->set_text(0, name);
+ ti->set_editable(0, true);
+ if (area == selected_area)
+ selected = ti;
}
-
if (selected)
selected->select(0);
-
}
void GridMapEditor::edit(GridMap *p_gridmap) {
- node=p_gridmap;
+ node = p_gridmap;
VS *vs = VS::get_singleton();
- last_mouseover=Vector3(-1,-1,-1);
- input_action=INPUT_NONE;
- selection.active=false;
+ last_mouseover = Vector3(-1, -1, -1);
+ input_action = INPUT_NONE;
+ selection.active = false;
_update_selection_transform();
_update_duplicate_indicator();
- spatial_editor = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>();
+ spatial_editor = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>();
if (!node) {
set_process(false);
- for(int i=0;i<3;i++) {
- VisualServer::get_singleton()->instance_set_visible(grid_instance[i],false);
-
+ for (int i = 0; i < 3; i++) {
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[i], false);
}
- VisualServer::get_singleton()->instance_set_visible(cursor_instance,false);
+ VisualServer::get_singleton()->instance_set_visible(cursor_instance, false);
_clear_areas();
return;
}
-
update_pallete();
update_areas();
set_process(true);
Vector3 edited_floor = p_gridmap->get_meta("_editor_floor_");
- clip_mode=p_gridmap->has_meta("_editor_clip_")?ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()):CLIP_DISABLED;
-
-
-
- for(int i=0;i<3;i++) {
- if (vs->mesh_get_surface_count(grid[i])>0)
- vs->mesh_remove_surface(grid[i],0);
- edit_floor[i]=edited_floor[i];
+ clip_mode = p_gridmap->has_meta("_editor_clip_") ? ClipMode(p_gridmap->get_meta("_editor_clip_").operator int()) : CLIP_DISABLED;
+ for (int i = 0; i < 3; i++) {
+ if (vs->mesh_get_surface_count(grid[i]) > 0)
+ vs->mesh_remove_surface(grid[i], 0);
+ edit_floor[i] = edited_floor[i];
}
{
//update grids
indicator_mat.instance();
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
- indicator_mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- indicator_mat->set_albedo(Color(0.8,0.5,0.1));
-
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
+ indicator_mat->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ indicator_mat->set_albedo(Color(0.8, 0.5, 0.1));
Vector<Vector3> grid_points[3];
Vector<Color> grid_colors[3];
- float cell_size[3]={p_gridmap->get_cell_size(),p_gridmap->get_cell_size(),p_gridmap->get_cell_size()};
+ float cell_size[3] = { p_gridmap->get_cell_size(), p_gridmap->get_cell_size(), p_gridmap->get_cell_size() };
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1;
+ axis[i] = 1;
Vector3 axis_n1;
- axis_n1[(i+1)%3]=cell_size[(i+1)%3];
+ axis_n1[(i + 1) % 3] = cell_size[(i + 1) % 3];
Vector3 axis_n2;
- axis_n2[(i+2)%3]=cell_size[(i+2)%3];
+ axis_n2[(i + 2) % 3] = cell_size[(i + 2) % 3];
- for(int j=-GRID_CURSOR_SIZE;j<=GRID_CURSOR_SIZE;j++) {
+ for (int j = -GRID_CURSOR_SIZE; j <= GRID_CURSOR_SIZE; j++) {
- for(int k=-GRID_CURSOR_SIZE;k<=GRID_CURSOR_SIZE;k++) {
+ 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);
+ Vector3 p = axis_n1 * j + axis_n2 * k;
+ float trans = Math::pow(MAX(0, 1.0 - (Vector2(j, k).length() / GRID_CURSOR_SIZE)), 2);
- Vector3 pj = axis_n1*(j+1) + axis_n2 *k;
- float transj = Math::pow(MAX(0,1.0-(Vector2(j+1,k).length()/GRID_CURSOR_SIZE)),2);
+ Vector3 pj = axis_n1 * (j + 1) + axis_n2 * k;
+ float transj = Math::pow(MAX(0, 1.0 - (Vector2(j + 1, k).length() / GRID_CURSOR_SIZE)), 2);
- Vector3 pk = axis_n1*j + axis_n2 *(k+1);
- float transk = Math::pow(MAX(0,1.0-(Vector2(j,k+1).length()/GRID_CURSOR_SIZE)),2);
+ Vector3 pk = axis_n1 * j + axis_n2 * (k + 1);
+ float transk = Math::pow(MAX(0, 1.0 - (Vector2(j, k + 1).length() / GRID_CURSOR_SIZE)), 2);
grid_points[i].push_back(p);
grid_points[i].push_back(pk);
- grid_colors[i].push_back(Color(1,1,1,trans));
- grid_colors[i].push_back(Color(1,1,1,transk));
+ grid_colors[i].push_back(Color(1, 1, 1, trans));
+ grid_colors[i].push_back(Color(1, 1, 1, transk));
grid_points[i].push_back(p);
grid_points[i].push_back(pj);
- grid_colors[i].push_back(Color(1,1,1,trans));
- grid_colors[i].push_back(Color(1,1,1,transj));
+ grid_colors[i].push_back(Color(1, 1, 1, trans));
+ grid_colors[i].push_back(Color(1, 1, 1, transj));
}
-
}
Array d;
d.resize(VS::ARRAY_MAX);
- d[VS::ARRAY_VERTEX]=grid_points[i];
- d[VS::ARRAY_COLOR]=grid_colors[i];
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i],VisualServer::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(grid[i],0,indicator_mat->get_rid());
-
-
+ d[VS::ARRAY_VERTEX] = grid_points[i];
+ d[VS::ARRAY_COLOR] = grid_colors[i];
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(grid[i], VisualServer::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(grid[i], 0, indicator_mat->get_rid());
}
-
}
update_grid();
_update_clip();
_update_areas_display();
-
-
}
void GridMapEditor::_update_clip() {
-
- node->set_meta("_editor_clip_",clip_mode);
- if (clip_mode==CLIP_DISABLED)
+ node->set_meta("_editor_clip_", clip_mode);
+ if (clip_mode == CLIP_DISABLED)
node->set_clip(false);
else
- node->set_clip(true,clip_mode==CLIP_ABOVE,edit_floor[edit_axis],edit_axis);
+ 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.. what do i care
+ grid_xform.origin.x -= 1; //force update in hackish way.. what do i care
//VS *vs = VS::get_singleton();
- grid_ofs[edit_axis]=edit_floor[edit_axis]*node->get_cell_size();
-
- edit_grid_xform.origin=grid_ofs;
- edit_grid_xform.basis=Basis();
+ grid_ofs[edit_axis] = edit_floor[edit_axis] * node->get_cell_size();
+ edit_grid_xform.origin = grid_ofs;
+ edit_grid_xform.basis = Basis();
- for(int i=0;i<3;i++) {
- VisualServer::get_singleton()->instance_set_visible(grid_instance[i],i==edit_axis);
-
+ for (int i = 0; i < 3; i++) {
+ VisualServer::get_singleton()->instance_set_visible(grid_instance[i], i == edit_axis);
}
- updating=true;
+ updating = true;
floor->set_value(edit_floor[edit_axis]);
- updating=false;
-
+ updating = false;
}
-
-
void GridMapEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- theme_pallete->connect("item_selected", this,"_item_selected_cbk");
- edit_mode->connect("item_selected", this,"_edit_mode_changed");
- area_list->connect("item_edited", this,"_area_renamed");
- area_list->connect("item_selected", this,"_area_selected");
- for(int i=0;i<3;i++) {
+ theme_pallete->connect("item_selected", this, "_item_selected_cbk");
+ edit_mode->connect("item_selected", this, "_edit_mode_changed");
+ area_list->connect("item_edited", this, "_area_renamed");
+ area_list->connect("item_selected", this, "_area_selected");
+ for (int i = 0; i < 3; i++) {
- grid[i]=VS::get_singleton()->mesh_create();
- grid_instance[i]=VS::get_singleton()->instance_create2(grid[i],get_tree()->get_root()->get_world()->get_scenario());
+ grid[i] = VS::get_singleton()->mesh_create();
+ grid_instance[i] = VS::get_singleton()->instance_create2(grid[i], get_tree()->get_root()->get_world()->get_scenario());
}
- selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh,get_tree()->get_root()->get_world()->get_scenario());
- duplicate_instance = VisualServer::get_singleton()->instance_create2(duplicate_mesh,get_tree()->get_root()->get_world()->get_scenario());
+ selection_instance = VisualServer::get_singleton()->instance_create2(selection_mesh, get_tree()->get_root()->get_world()->get_scenario());
+ duplicate_instance = VisualServer::get_singleton()->instance_create2(duplicate_mesh, get_tree()->get_root()->get_world()->get_scenario());
_update_selection_transform();
_update_duplicate_indicator();
- } else if (p_what==NOTIFICATION_EXIT_TREE) {
+ } else if (p_what == NOTIFICATION_EXIT_TREE) {
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
VS::get_singleton()->free(grid_instance[i]);
VS::get_singleton()->free(grid[i]);
- grid_instance[i]=RID();
- grid[i]=RID();
+ grid_instance[i] = RID();
+ grid[i] = RID();
}
VisualServer::get_singleton()->free(selection_instance);
VisualServer::get_singleton()->free(duplicate_instance);
- selection_instance=RID();
- duplicate_instance=RID();
+ selection_instance = RID();
+ duplicate_instance = RID();
- } else if (p_what==NOTIFICATION_PROCESS) {
+ } else if (p_what == NOTIFICATION_PROCESS) {
Transform xf = node->get_global_transform();
- if (xf!=grid_xform) {
- for(int i=0;i<3;i++) {
-
+ if (xf != grid_xform) {
+ for (int i = 0; i < 3; i++) {
- VS::get_singleton()->instance_set_transform(grid_instance[i],xf * edit_grid_xform);
+ VS::get_singleton()->instance_set_transform(grid_instance[i], xf * edit_grid_xform);
}
- grid_xform=xf;
+ grid_xform = xf;
}
Ref<MeshLibrary> cgmt = node->get_theme();
- if (cgmt.operator->()!=last_theme)
+ if (cgmt.operator->() != last_theme)
update_pallete();
if (lock_view) {
- EditorNode*editor = get_tree()->get_root()->get_child(0)->cast_to<EditorNode>();
+ EditorNode *editor = get_tree()->get_root()->get_child(0)->cast_to<EditorNode>();
Plane p;
- p.normal[edit_axis]=1.0;
- p.d=edit_floor[edit_axis]*node->get_cell_size();
+ p.normal[edit_axis] = 1.0;
+ p.d = edit_floor[edit_axis] * node->get_cell_size();
p = node->get_transform().xform(p); // plane to snap
SpatialEditorPlugin *sep = editor->get_editor_plugin_screen()->cast_to<SpatialEditorPlugin>();
if (sep)
sep->snap_cursor_to_plane(p);
- //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p);
-
+ //editor->get_editor_plugin_screen()->call("snap_cursor_to_plane",p);
}
}
-
}
void GridMapEditor::_update_cursor_instance() {
@@ -1063,32 +995,30 @@ void GridMapEditor::_update_cursor_instance() {
if (cursor_instance.is_valid())
VisualServer::get_singleton()->free(cursor_instance);
- cursor_instance=RID();
+ cursor_instance = RID();
- if (selected_pallete>=0) {
+ if (selected_pallete >= 0) {
if (node && !node->get_theme().is_null()) {
Ref<Mesh> mesh = node->get_theme()->get_item_mesh(selected_pallete);
if (!mesh.is_null() && mesh->get_rid().is_valid()) {
- cursor_instance=VisualServer::get_singleton()->instance_create2(mesh->get_rid(),get_tree()->get_root()->get_world()->get_scenario());
- VisualServer::get_singleton()->instance_set_transform(cursor_instance,cursor_transform);
+ cursor_instance = VisualServer::get_singleton()->instance_create2(mesh->get_rid(), get_tree()->get_root()->get_world()->get_scenario());
+ VisualServer::get_singleton()->instance_set_transform(cursor_instance, cursor_transform);
}
}
}
-
}
void GridMapEditor::_item_selected_cbk(int idx) {
- selected_pallete=theme_pallete->get_item_metadata(idx);
+ selected_pallete = theme_pallete->get_item_metadata(idx);
_update_cursor_instance();
-
}
void GridMapEditor::_clear_areas() {
- for(int i=0;i<areas.size();i++) {
+ for (int i = 0; i < areas.size(); i++) {
VisualServer::get_singleton()->free(areas[i].instance);
VisualServer::get_singleton()->free(areas[i].mesh);
@@ -1154,7 +1084,7 @@ void GridMapEditor::_update_areas_display() {
void GridMapEditor::_edit_mode_changed(int p_what) {
- if (p_what==0) {
+ if (p_what == 0) {
theme_pallete->show();
area_list->hide();
@@ -1162,89 +1092,82 @@ void GridMapEditor::_edit_mode_changed(int p_what) {
theme_pallete->hide();
area_list->show();
-
}
}
void GridMapEditor::_floor_changed(float p_value) {
-
if (updating)
return;
- edit_floor[edit_axis]=p_value;
- node->set_meta("_editor_floor_",Vector3(edit_floor[0],edit_floor[1],edit_floor[2]));
+ edit_floor[edit_axis] = p_value;
+ node->set_meta("_editor_floor_", Vector3(edit_floor[0], edit_floor[1], edit_floor[2]));
update_grid();
_update_clip();
-
}
void GridMapEditor::_bind_methods() {
- ClassDB::bind_method("_menu_option",&GridMapEditor::_menu_option);
- ClassDB::bind_method("_configure",&GridMapEditor::_configure);
- ClassDB::bind_method("_item_selected_cbk",&GridMapEditor::_item_selected_cbk);
- ClassDB::bind_method("_edit_mode_changed",&GridMapEditor::_edit_mode_changed);
- ClassDB::bind_method("_area_renamed",&GridMapEditor::_area_renamed);
- ClassDB::bind_method("_area_selected",&GridMapEditor::_area_selected);
- ClassDB::bind_method("_floor_changed",&GridMapEditor::_floor_changed);
+ ClassDB::bind_method("_menu_option", &GridMapEditor::_menu_option);
+ ClassDB::bind_method("_configure", &GridMapEditor::_configure);
+ ClassDB::bind_method("_item_selected_cbk", &GridMapEditor::_item_selected_cbk);
+ ClassDB::bind_method("_edit_mode_changed", &GridMapEditor::_edit_mode_changed);
+ ClassDB::bind_method("_area_renamed", &GridMapEditor::_area_renamed);
+ ClassDB::bind_method("_area_selected", &GridMapEditor::_area_selected);
+ ClassDB::bind_method("_floor_changed", &GridMapEditor::_floor_changed);
- ClassDB::bind_method(D_METHOD("_set_display_mode","mode"), &GridMapEditor::_set_display_mode);
+ ClassDB::bind_method(D_METHOD("_set_display_mode", "mode"), &GridMapEditor::_set_display_mode);
}
-
-
GridMapEditor::GridMapEditor(EditorNode *p_editor) {
+ input_action = INPUT_NONE;
+ editor = p_editor;
+ undo_redo = p_editor->get_undo_redo();
- input_action=INPUT_NONE;
- editor=p_editor;
- undo_redo=p_editor->get_undo_redo();
-
- int mw = EDITOR_DEF("editors/grid_map/palette_min_width",230);
- Control *ec = memnew( Control);
- ec->set_custom_minimum_size(Size2(mw,0));
+ int mw = EDITOR_DEF("editors/grid_map/palette_min_width", 230);
+ Control *ec = memnew(Control);
+ ec->set_custom_minimum_size(Size2(mw, 0));
add_child(ec);
-
- spatial_editor_hb = memnew( HBoxContainer );
+ spatial_editor_hb = memnew(HBoxContainer);
SpatialEditor::get_singleton()->add_control_to_menu_panel(spatial_editor_hb);
- options = memnew( MenuButton );
+ options = memnew(MenuButton);
spatial_editor_hb->add_child(options);
spatial_editor_hb->hide();
options->set_text("Grid");
- options->get_popup()->add_check_item("Snap View",MENU_OPTION_LOCK_VIEW);
+ options->get_popup()->add_check_item("Snap View", MENU_OPTION_LOCK_VIEW);
options->get_popup()->add_separator();
- options->get_popup()->add_item("Prev Level ("+keycode_get_string(KEY_MASK_CMD)+"Down Wheel)",MENU_OPTION_PREV_LEVEL);
- options->get_popup()->add_item("Next Level ("+keycode_get_string(KEY_MASK_CMD)+"Up Wheel)",MENU_OPTION_NEXT_LEVEL);
+ options->get_popup()->add_item("Prev Level (" + keycode_get_string(KEY_MASK_CMD) + "Down Wheel)", MENU_OPTION_PREV_LEVEL);
+ options->get_popup()->add_item("Next Level (" + keycode_get_string(KEY_MASK_CMD) + "Up Wheel)", MENU_OPTION_NEXT_LEVEL);
options->get_popup()->add_separator();
- options->get_popup()->add_check_item("Clip Disabled",MENU_OPTION_CLIP_DISABLED);
- options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true );
- options->get_popup()->add_check_item("Clip Above",MENU_OPTION_CLIP_ABOVE);
- options->get_popup()->add_check_item("Clip Below",MENU_OPTION_CLIP_BELOW);
+ options->get_popup()->add_check_item("Clip Disabled", MENU_OPTION_CLIP_DISABLED);
+ options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_CLIP_DISABLED), true);
+ options->get_popup()->add_check_item("Clip Above", MENU_OPTION_CLIP_ABOVE);
+ options->get_popup()->add_check_item("Clip Below", MENU_OPTION_CLIP_BELOW);
options->get_popup()->add_separator();
- options->get_popup()->add_check_item("Edit X Axis",MENU_OPTION_X_AXIS,KEY_Z);
- options->get_popup()->add_check_item("Edit Y Axis",MENU_OPTION_Y_AXIS,KEY_X);
- options->get_popup()->add_check_item("Edit Z Axis",MENU_OPTION_Z_AXIS,KEY_C);
- options->get_popup()->set_item_checked( options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true );
+ options->get_popup()->add_check_item("Edit X Axis", MENU_OPTION_X_AXIS, KEY_Z);
+ options->get_popup()->add_check_item("Edit Y Axis", MENU_OPTION_Y_AXIS, KEY_X);
+ options->get_popup()->add_check_item("Edit Z Axis", MENU_OPTION_Z_AXIS, KEY_C);
+ options->get_popup()->set_item_checked(options->get_popup()->get_item_index(MENU_OPTION_Y_AXIS), true);
options->get_popup()->add_separator();
- options->get_popup()->add_item("Cursor Rotate X",MENU_OPTION_CURSOR_ROTATE_X,KEY_A);
- options->get_popup()->add_item("Cursor Rotate Y",MENU_OPTION_CURSOR_ROTATE_Y,KEY_S);
- options->get_popup()->add_item("Cursor Rotate Z",MENU_OPTION_CURSOR_ROTATE_Z,KEY_D);
- options->get_popup()->add_item("Cursor Back Rotate X",MENU_OPTION_CURSOR_BACK_ROTATE_X,KEY_MASK_SHIFT+KEY_A);
- options->get_popup()->add_item("Cursor Back Rotate Y",MENU_OPTION_CURSOR_BACK_ROTATE_Y,KEY_MASK_SHIFT+KEY_S);
- options->get_popup()->add_item("Cursor Back Rotate Z",MENU_OPTION_CURSOR_BACK_ROTATE_Z,KEY_MASK_SHIFT+KEY_D);
- options->get_popup()->add_item("Cursor Clear Rotation",MENU_OPTION_CURSOR_CLEAR_ROTATION,KEY_W);
+ options->get_popup()->add_item("Cursor Rotate X", MENU_OPTION_CURSOR_ROTATE_X, KEY_A);
+ options->get_popup()->add_item("Cursor Rotate Y", MENU_OPTION_CURSOR_ROTATE_Y, KEY_S);
+ options->get_popup()->add_item("Cursor Rotate Z", MENU_OPTION_CURSOR_ROTATE_Z, KEY_D);
+ options->get_popup()->add_item("Cursor Back Rotate X", MENU_OPTION_CURSOR_BACK_ROTATE_X, KEY_MASK_SHIFT + KEY_A);
+ options->get_popup()->add_item("Cursor Back Rotate Y", MENU_OPTION_CURSOR_BACK_ROTATE_Y, KEY_MASK_SHIFT + KEY_S);
+ options->get_popup()->add_item("Cursor Back Rotate Z", MENU_OPTION_CURSOR_BACK_ROTATE_Z, KEY_MASK_SHIFT + KEY_D);
+ options->get_popup()->add_item("Cursor Clear Rotation", MENU_OPTION_CURSOR_CLEAR_ROTATION, KEY_W);
options->get_popup()->add_separator();
- options->get_popup()->add_check_item("Duplicate Selects",MENU_OPTION_DUPLICATE_SELECTS);
+ options->get_popup()->add_check_item("Duplicate Selects", MENU_OPTION_DUPLICATE_SELECTS);
options->get_popup()->add_separator();
- options->get_popup()->add_item("Create Area",MENU_OPTION_SELECTION_MAKE_AREA,KEY_CONTROL+KEY_C);
- options->get_popup()->add_item("Create Exterior Connector",MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR);
- options->get_popup()->add_item("Erase Area",MENU_OPTION_REMOVE_AREA);
+ options->get_popup()->add_item("Create Area", MENU_OPTION_SELECTION_MAKE_AREA, KEY_CONTROL + KEY_C);
+ options->get_popup()->add_item("Create Exterior Connector", MENU_OPTION_SELECTION_MAKE_EXTERIOR_CONNECTOR);
+ options->get_popup()->add_item("Erase Area", MENU_OPTION_REMOVE_AREA);
options->get_popup()->add_separator();
- options->get_popup()->add_item("Selection -> Duplicate",MENU_OPTION_SELECTION_DUPLICATE,KEY_MASK_SHIFT+KEY_INSERT);
- options->get_popup()->add_item("Selection -> Clear",MENU_OPTION_SELECTION_CLEAR,KEY_MASK_SHIFT+KEY_DELETE);
+ options->get_popup()->add_item("Selection -> Duplicate", MENU_OPTION_SELECTION_DUPLICATE, KEY_MASK_SHIFT + KEY_INSERT);
+ options->get_popup()->add_item("Selection -> Clear", MENU_OPTION_SELECTION_CLEAR, KEY_MASK_SHIFT + KEY_DELETE);
//options->get_popup()->add_separator();
//options->get_popup()->add_item("Configure",MENU_OPTION_CONFIGURE);
@@ -1265,46 +1188,46 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
settings_pick_distance->set_value(EDITOR_DEF("editors/grid_map/pick_distance", 5000.0));
settings_vbc->add_margin_child("Pick Distance:", settings_pick_distance);
- clip_mode=CLIP_DISABLED;
- options->get_popup()->connect("id_pressed", this,"_menu_option");
+ clip_mode = CLIP_DISABLED;
+ options->get_popup()->connect("id_pressed", this, "_menu_option");
- HBoxContainer *hb = memnew( HBoxContainer );
+ HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
hb->set_h_size_flags(SIZE_EXPAND_FILL);
edit_mode = memnew(OptionButton);
edit_mode->set_area_as_parent_rect();
- edit_mode->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,24);
- edit_mode->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,14);
+ edit_mode->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_BEGIN, 24);
+ edit_mode->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 14);
edit_mode->add_item("Tiles");
edit_mode->add_item("Areas");
hb->add_child(edit_mode);
edit_mode->set_h_size_flags(SIZE_EXPAND_FILL);
- mode_thumbnail = memnew( ToolButton );
+ mode_thumbnail = memnew(ToolButton);
mode_thumbnail->set_toggle_mode(true);
mode_thumbnail->set_pressed(true);
- mode_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail","EditorIcons"));
+ mode_thumbnail->set_icon(p_editor->get_gui_base()->get_icon("FileThumbnail", "EditorIcons"));
hb->add_child(mode_thumbnail);
mode_thumbnail->connect("pressed", this, "_set_display_mode", varray(DISPLAY_THUMBNAIL));
- mode_list = memnew( ToolButton );
+ mode_list = memnew(ToolButton);
mode_list->set_toggle_mode(true);
mode_list->set_pressed(false);
mode_list->set_icon(p_editor->get_gui_base()->get_icon("FileList", "EditorIcons"));
hb->add_child(mode_list);
mode_list->connect("pressed", this, "_set_display_mode", varray(DISPLAY_LIST));
- EDITOR_DEF("editors/grid_map/preview_size",64);
+ EDITOR_DEF("editors/grid_map/preview_size", 64);
display_mode = DISPLAY_THUMBNAIL;
- selected_area=-1;
+ selected_area = -1;
- theme_pallete = memnew( ItemList );
+ theme_pallete = memnew(ItemList);
add_child(theme_pallete);
theme_pallete->set_v_size_flags(SIZE_EXPAND_FILL);
- area_list = memnew( Tree );
+ area_list = memnew(Tree);
add_child(area_list);
area_list->set_v_size_flags(SIZE_EXPAND_FILL);
area_list->hide();
@@ -1314,26 +1237,25 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
fl->set_text(" Floor: ");
spatial_editor_hb->add_child(fl);
- floor = memnew( SpinBox );
+ floor = memnew(SpinBox);
floor->set_min(-32767);
floor->set_max(32767);
floor->set_step(1);
- floor->get_line_edit()->add_constant_override("minimum_spaces",16);
+ floor->get_line_edit()->add_constant_override("minimum_spaces", 16);
spatial_editor_hb->add_child(floor);
- floor->connect("value_changed",this,"_floor_changed");
-
+ floor->connect("value_changed", this, "_floor_changed");
- edit_axis=Vector3::AXIS_Y;
- edit_floor[0]=-1;
- edit_floor[1]=-1;
- edit_floor[2]=-1;
+ edit_axis = Vector3::AXIS_Y;
+ edit_floor[0] = -1;
+ edit_floor[1] = -1;
+ edit_floor[2] = -1;
- cursor_visible=false;
- selected_pallete=-1;
- lock_view=false;
- cursor_rot=0;
- last_mouseover=Vector3(-1,-1,-1);
+ cursor_visible = false;
+ selected_pallete = -1;
+ lock_view = false;
+ cursor_rot = 0;
+ last_mouseover = Vector3(-1, -1, -1);
selection_mesh = VisualServer::get_singleton()->mesh_create();
duplicate_mesh = VisualServer::get_singleton()->mesh_create();
@@ -1341,45 +1263,43 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
{
//selection mesh create
-
PoolVector<Vector3> lines;
PoolVector<Vector3> triangles;
- for (int i=0;i<6;i++) {
-
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
}
- triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5));
- triangles.push_back(face_points[1]*0.5+Vector3(0.5,0.5,0.5));
- triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5));
+ triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5));
+ triangles.push_back(face_points[1] * 0.5 + Vector3(0.5, 0.5, 0.5));
+ triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5));
- triangles.push_back(face_points[2]*0.5+Vector3(0.5,0.5,0.5));
- triangles.push_back(face_points[3]*0.5+Vector3(0.5,0.5,0.5));
- triangles.push_back(face_points[0]*0.5+Vector3(0.5,0.5,0.5));
+ triangles.push_back(face_points[2] * 0.5 + Vector3(0.5, 0.5, 0.5));
+ triangles.push_back(face_points[3] * 0.5 + Vector3(0.5, 0.5, 0.5));
+ triangles.push_back(face_points[0] * 0.5 + Vector3(0.5, 0.5, 0.5));
}
- for(int i=0;i<12;i++) {
+ for (int i = 0; i < 12; i++) {
- Rect3 base(Vector3(0,0,0),Vector3(1,1,1));
- Vector3 a,b;
- base.get_edge(i,a,b);
+ Rect3 base(Vector3(0, 0, 0), Vector3(1, 1, 1));
+ Vector3 a, b;
+ base.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
@@ -1388,49 +1308,42 @@ GridMapEditor::GridMapEditor(EditorNode *p_editor) {
d.resize(VS::ARRAY_MAX);
inner_mat.instance();
- inner_mat->set_albedo(Color(0.7,0.7,1.0,0.3));
- inner_mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP,true);
- inner_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- inner_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
+ inner_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.3));
+ inner_mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP, true);
+ inner_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ inner_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
-
- d[VS::ARRAY_VERTEX]=triangles;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh,VS::PRIMITIVE_TRIANGLES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,0,inner_mat->get_rid());
+ d[VS::ARRAY_VERTEX] = triangles;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, VS::PRIMITIVE_TRIANGLES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 0, inner_mat->get_rid());
outer_mat.instance();
- outer_mat->set_albedo(Color(0.7,0.7,1.0,0.3));
- outer_mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP,true);
- outer_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
+ outer_mat->set_albedo(Color(0.7, 0.7, 1.0, 0.3));
+ outer_mat->set_flag(FixedSpatialMaterial::FLAG_ONTOP, true);
+ outer_mat->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
outer_mat->set_line_width(3.0);
- outer_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT,true);
-
-
- d[VS::ARRAY_VERTEX]=lines;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh,VS::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh,1,outer_mat->get_rid());
+ outer_mat->set_feature(FixedSpatialMaterial::FEATURE_TRANSPARENT, true);
- d[VS::ARRAY_VERTEX]=triangles;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh,VS::PRIMITIVE_TRIANGLES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,0,inner_mat->get_rid());
+ d[VS::ARRAY_VERTEX] = lines;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(selection_mesh, VS::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(selection_mesh, 1, outer_mat->get_rid());
- d[VS::ARRAY_VERTEX]=lines;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh,VS::PRIMITIVE_LINES,d);
- VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh,1,outer_mat->get_rid());
+ d[VS::ARRAY_VERTEX] = triangles;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh, VS::PRIMITIVE_TRIANGLES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 0, inner_mat->get_rid());
+ d[VS::ARRAY_VERTEX] = lines;
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(duplicate_mesh, VS::PRIMITIVE_LINES, d);
+ VisualServer::get_singleton()->mesh_surface_set_material(duplicate_mesh, 1, outer_mat->get_rid());
}
- selection.active=false;
- updating=false;
-
+ selection.active = false;
+ updating = false;
}
-
-
-
GridMapEditor::~GridMapEditor() {
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
if (grid[i].is_valid())
VisualServer::get_singleton()->free(grid[i]);
@@ -1440,12 +1353,10 @@ GridMapEditor::~GridMapEditor() {
VisualServer::get_singleton()->free(cursor_instance);
}
-
VisualServer::get_singleton()->free(selection_mesh);
if (selection_instance.is_valid())
VisualServer::get_singleton()->free(selection_instance);
-
VisualServer::get_singleton()->free(duplicate_mesh);
if (duplicate_instance.is_valid())
VisualServer::get_singleton()->free(duplicate_instance);
@@ -1455,8 +1366,7 @@ GridMapEditor::~GridMapEditor() {
void GridMapEditorPlugin::edit(Object *p_object) {
-
- gridmap_editor->edit(p_object?p_object->cast_to<GridMap>():NULL);
+ gridmap_editor->edit(p_object ? p_object->cast_to<GridMap>() : NULL);
}
bool GridMapEditorPlugin::handles(Object *p_object) const {
@@ -1477,26 +1387,18 @@ void GridMapEditorPlugin::make_visible(bool p_visible) {
gridmap_editor->edit(NULL);
gridmap_editor->set_process(false);
}
-
}
-
GridMapEditorPlugin::GridMapEditorPlugin(EditorNode *p_node) {
- editor=p_node;
- gridmap_editor = memnew( GridMapEditor(editor) );
+ editor = p_node;
+ gridmap_editor = memnew(GridMapEditor(editor));
SpatialEditor::get_singleton()->get_palette_split()->add_child(gridmap_editor);
- SpatialEditor::get_singleton()->get_palette_split()->move_child(gridmap_editor,0);
+ SpatialEditor::get_singleton()->get_palette_split()->move_child(gridmap_editor, 0);
gridmap_editor->hide();
-
-
-
}
-
-GridMapEditorPlugin::~GridMapEditorPlugin()
-{
+GridMapEditorPlugin::~GridMapEditorPlugin() {
}
-
diff --git a/modules/gridmap/grid_map_editor_plugin.h b/modules/gridmap/grid_map_editor_plugin.h
index 07ac34cd4e..27a063ee41 100644
--- a/modules/gridmap/grid_map_editor_plugin.h
+++ b/modules/gridmap/grid_map_editor_plugin.h
@@ -29,10 +29,10 @@
#ifndef GRID_MAP_EDITOR_PLUGIN_H
#define GRID_MAP_EDITOR_PLUGIN_H
-#include "editor/editor_plugin.h"
#include "editor/editor_node.h"
-#include "grid_map.h"
+#include "editor/editor_plugin.h"
#include "editor/pane_drag.h"
+#include "grid_map.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -40,11 +40,11 @@
class SpatialEditorPlugin;
class GridMapEditor : public VBoxContainer {
- GDCLASS(GridMapEditor, VBoxContainer );
+ GDCLASS(GridMapEditor, VBoxContainer);
enum {
- GRID_CURSOR_SIZE=50
+ GRID_CURSOR_SIZE = 50
};
enum InputAction {
@@ -65,14 +65,14 @@ class GridMapEditor : public VBoxContainer {
};
enum DisplayMode {
- DISPLAY_THUMBNAIL,
- DISPLAY_LIST
+ DISPLAY_THUMBNAIL,
+ DISPLAY_LIST
};
UndoRedo *undo_redo;
InputAction input_action;
Panel *panel;
- MenuButton * options;
+ MenuButton *options;
SpinBox *floor;
OptionButton *edit_mode;
ToolButton *mode_thumbnail;
@@ -94,7 +94,7 @@ class GridMapEditor : public VBoxContainer {
List<SetItem> set_items;
GridMap *node;
- MeshLibrary* last_theme;
+ MeshLibrary *last_theme;
ClipMode clip_mode;
bool lock_view;
@@ -118,10 +118,8 @@ class GridMapEditor : public VBoxContainer {
bool updating;
-
struct Selection {
-
Vector3 click;
Vector3 current;
Vector3 begin;
@@ -141,7 +139,6 @@ class GridMapEditor : public VBoxContainer {
int selected_area;
int cursor_rot;
-
enum Menu {
MENU_OPTION_CONFIGURE,
@@ -173,7 +170,6 @@ class GridMapEditor : public VBoxContainer {
SpatialEditorPlugin *spatial_editor;
-
struct AreaDisplay {
RID mesh;
@@ -212,20 +208,18 @@ class GridMapEditor : public VBoxContainer {
void update_areas();
EditorNode *editor;
- bool do_input_action(Camera* p_camera,const Point2& p_point,bool p_click);
+ bool do_input_action(Camera *p_camera, const Point2 &p_point, bool p_click);
-friend class GridMapEditorPlugin;
+ friend class GridMapEditorPlugin;
Panel *theme_panel;
protected:
void _notification(int p_what);
void _node_removed(Node *p_node);
static void _bind_methods();
-public:
-
- bool forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event);
-
+public:
+ bool forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event);
void edit(GridMap *p_gridmap);
GridMapEditor() {}
@@ -235,14 +229,13 @@ public:
class GridMapEditorPlugin : public EditorPlugin {
- GDCLASS( GridMapEditorPlugin, EditorPlugin );
+ GDCLASS(GridMapEditorPlugin, EditorPlugin);
GridMapEditor *gridmap_editor;
EditorNode *editor;
public:
-
- virtual bool forward_spatial_input_event(Camera* p_camera,const InputEvent& p_event) { return gridmap_editor->forward_spatial_input_event(p_camera,p_event); }
+ virtual bool forward_spatial_input_event(Camera *p_camera, const InputEvent &p_event) { return gridmap_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_node);
@@ -251,7 +244,6 @@ public:
GridMapEditorPlugin(EditorNode *p_node);
~GridMapEditorPlugin();
-
};
#endif // CUBE_GRID_MAP_EDITOR_PLUGIN_H
diff --git a/modules/gridmap/register_types.cpp b/modules/gridmap/register_types.cpp
index 9cd70a0f9b..4035caea78 100644
--- a/modules/gridmap/register_types.cpp
+++ b/modules/gridmap/register_types.cpp
@@ -43,9 +43,5 @@ void register_gridmap_types() {
#endif
}
-
-
void unregister_gridmap_types() {
-
-
}
diff --git a/modules/jpg/image_loader_jpegd.cpp b/modules/jpg/image_loader_jpegd.cpp
index 1152d42e1b..ca928c4fe6 100644
--- a/modules/jpg/image_loader_jpegd.cpp
+++ b/modules/jpg/image_loader_jpegd.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "image_loader_jpegd.h"
-#include "print_string.h"
#include "os/os.h"
+#include "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) {
-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_mem_stream mem_stream(p_buffer, p_buffer_len);
jpgd::jpeg_decoder decoder(&mem_stream);
@@ -48,8 +47,8 @@ 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();
int comps = decoder.get_num_components();
- if (comps==3)
- comps=4; //weird
+ if (comps == 3)
+ comps = 4; //weird
if (decoder.begin_decoding() != jpgd::JPGD_SUCCESS)
return ERR_FILE_CORRUPT;
@@ -62,42 +61,34 @@ Error jpeg_load_image_from_buffer(Image *p_image,const uint8_t* p_buffer, int p_
PoolVector<uint8_t>::Write dw = data.write();
- jpgd::uint8 *pImage_data = (jpgd::uint8*)dw.ptr();
+ jpgd::uint8 *pImage_data = (jpgd::uint8 *)dw.ptr();
- for (int y = 0; y < image_height; y++)
- {
- const jpgd::uint8* pScan_line;
+ for (int y = 0; y < image_height; y++) {
+ const jpgd::uint8 *pScan_line;
jpgd::uint scan_line_len;
- if (decoder.decode((const void**)&pScan_line, &scan_line_len) != jpgd::JPGD_SUCCESS)
- {
+ if (decoder.decode((const void **)&pScan_line, &scan_line_len) != jpgd::JPGD_SUCCESS) {
return ERR_FILE_CORRUPT;
}
jpgd::uint8 *pDst = pImage_data + y * dst_bpl;
memcpy(pDst, pScan_line, dst_bpl);
-
-
}
-
//all good
Image::Format fmt;
- if (comps==1)
- fmt=Image::FORMAT_L8;
+ if (comps == 1)
+ fmt = Image::FORMAT_L8;
else
- fmt=Image::FORMAT_RGBA8;
+ fmt = Image::FORMAT_RGBA8;
dw = PoolVector<uint8_t>::Write();
- p_image->create(image_width,image_height,0,fmt,data);
+ p_image->create(image_width, image_height, 0, fmt, data);
return OK;
-
}
-
-Error ImageLoaderJPG::load_image(Image *p_image,FileAccess *f) {
-
+Error ImageLoaderJPG::load_image(Image *p_image, FileAccess *f) {
PoolVector<uint8_t> src_image;
int src_image_len = f->get_len();
@@ -106,30 +97,27 @@ Error ImageLoaderJPG::load_image(Image *p_image,FileAccess *f) {
PoolVector<uint8_t>::Write w = src_image.write();
- f->get_buffer(&w[0],src_image_len);
+ f->get_buffer(&w[0], src_image_len);
f->close();
-
- Error err = jpeg_load_image_from_buffer(p_image,w.ptr(),src_image_len);
+ Error err = jpeg_load_image_from_buffer(p_image, w.ptr(), src_image_len);
w = PoolVector<uint8_t>::Write();
return err;
-
}
void ImageLoaderJPG::get_recognized_extensions(List<String> *p_extensions) const {
-
+
p_extensions->push_back("jpg");
p_extensions->push_back("jpeg");
}
-
-static Image _jpegd_mem_loader_func(const uint8_t* p_png,int p_size) {
+static Image _jpegd_mem_loader_func(const uint8_t *p_png, int p_size) {
Image img;
- Error err = jpeg_load_image_from_buffer(&img,p_png,p_size);
+ Error err = jpeg_load_image_from_buffer(&img, p_png, p_size);
if (err)
ERR_PRINT("Couldn't initialize ImageLoaderJPG with the given resource.");
@@ -138,7 +126,5 @@ static Image _jpegd_mem_loader_func(const uint8_t* p_png,int p_size) {
ImageLoaderJPG::ImageLoaderJPG() {
- Image::_jpg_mem_loader_func=_jpegd_mem_loader_func;
+ 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 aeb219aa5d..0803cfba1e 100644
--- a/modules/jpg/image_loader_jpegd.h
+++ b/modules/jpg/image_loader_jpegd.h
@@ -36,14 +36,10 @@
*/
class ImageLoaderJPG : public ImageFormatLoader {
-
public:
-
- virtual Error load_image(Image *p_image,FileAccess *f);
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
+ virtual Error load_image(Image *p_image, FileAccess *f);
+ virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderJPG();
};
-
-
#endif
diff --git a/modules/jpg/register_types.cpp b/modules/jpg/register_types.cpp
index bcd467f5fc..ce0330643a 100644
--- a/modules/jpg/register_types.cpp
+++ b/modules/jpg/register_types.cpp
@@ -34,11 +34,11 @@ static ImageLoaderJPG *image_loader_jpg = NULL;
void register_jpg_types() {
- image_loader_jpg = memnew( ImageLoaderJPG );
+ image_loader_jpg = memnew(ImageLoaderJPG);
ImageLoader::add_image_format_loader(image_loader_jpg);
}
void unregister_jpg_types() {
- memdelete( image_loader_jpg );
+ memdelete(image_loader_jpg);
}
diff --git a/modules/openssl/stream_peer_openssl.cpp b/modules/openssl/stream_peer_openssl.cpp
index 43a1f610d8..3b25b8a50e 100644
--- a/modules/openssl/stream_peer_openssl.cpp
+++ b/modules/openssl/stream_peer_openssl.cpp
@@ -29,12 +29,11 @@
#include "stream_peer_openssl.h"
//hostname matching code from curl
-
//#include <openssl/applink.c> // To prevent crashing (see the OpenSSL FAQ)
bool StreamPeerOpenSSL::_match_host_name(const char *name, const char *hostname) {
- return Tool_Curl_cert_hostcheck(name,hostname)==CURL_HOST_MATCH;
+ return Tool_Curl_cert_hostcheck(name, hostname) == CURL_HOST_MATCH;
//print_line("MATCH: "+String(name)+" vs "+String(hostname));
//return true;
}
@@ -47,36 +46,32 @@ Error StreamPeerOpenSSL::_match_common_name(const char *hostname, const X509 *se
char *common_name_str = NULL;
// Find the position of the CN field in the Subject field of the certificate
- common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1);
+ common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *)server_cert), NID_commonName, -1);
- ERR_FAIL_COND_V(common_name_loc < 0, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(common_name_loc < 0, ERR_INVALID_PARAMETER);
// Extract the CN field
- common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc);
+ common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *)server_cert), common_name_loc);
- ERR_FAIL_COND_V(common_name_entry == NULL, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(common_name_entry == NULL, ERR_INVALID_PARAMETER);
// Convert the CN field to a C string
common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
- ERR_FAIL_COND_V(common_name_asn1 == NULL, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(common_name_asn1 == NULL, ERR_INVALID_PARAMETER);
- common_name_str = (char *) ASN1_STRING_data(common_name_asn1);
+ common_name_str = (char *)ASN1_STRING_data(common_name_asn1);
// Make sure there isn't an embedded NUL character in the CN
bool malformed_certificate = (size_t)ASN1_STRING_length(common_name_asn1) != strlen(common_name_str);
- ERR_FAIL_COND_V(malformed_certificate, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(malformed_certificate, ERR_INVALID_PARAMETER);
// Compare expected hostname with the CN
-
- return _match_host_name(common_name_str,hostname)?OK:FAILED;
-
+ return _match_host_name(common_name_str, hostname) ? OK : FAILED;
}
-
/**
* Tries to find a match for hostname in the certificate's Subject Alternative Name extension.
*
@@ -90,26 +85,25 @@ Error StreamPeerOpenSSL::_match_subject_alternative_name(const char *hostname, c
STACK_OF(GENERAL_NAME) *san_names = NULL;
// Try to extract the names within the SAN extension from the certificate
- san_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL);
+ san_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i((X509 *)server_cert, NID_subject_alt_name, NULL, NULL);
if (san_names == NULL) {
return ERR_FILE_NOT_FOUND;
}
san_names_nb = sk_GENERAL_NAME_num(san_names);
// Check each name within the extension
- for (i=0; i<san_names_nb; i++) {
+ for (i = 0; i < san_names_nb; i++) {
const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
if (current_name->type == GEN_DNS) {
// Current name is a DNS name, let's check it
- char *dns_name = (char *) ASN1_STRING_data(current_name->d.dNSName);
+ char *dns_name = (char *)ASN1_STRING_data(current_name->d.dNSName);
// Make sure there isn't an embedded NUL character in the DNS name
if ((size_t)ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) {
result = ERR_INVALID_PARAMETER;
break;
- }
- else { // Compare expected hostname with the DNS name
+ } else { // Compare expected hostname with the DNS name
if (_match_host_name(dns_name, hostname)) {
result = OK;
break;
@@ -131,19 +125,19 @@ int StreamPeerOpenSSL::_cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg
bool base_cert_valid = X509_verify_cert(x509_ctx);
if (!base_cert_valid) {
- print_line("Cause: "+String(X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx))));
+ print_line("Cause: " + String(X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx))));
ERR_print_errors_fp(stdout);
}
X509 *server_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
- ERR_FAIL_COND_V(!server_cert,0);
+ ERR_FAIL_COND_V(!server_cert, 0);
char cert_str[256];
- X509_NAME_oneline(X509_get_subject_name (server_cert),
- cert_str, sizeof (cert_str));
+ X509_NAME_oneline(X509_get_subject_name(server_cert),
+ cert_str, sizeof(cert_str));
- print_line("CERT STR: "+String(cert_str));
- print_line("VALID: "+itos(base_cert_valid));
+ print_line("CERT STR: " + String(cert_str));
+ print_line("VALID: " + itos(base_cert_valid));
if (!base_cert_valid)
return 0;
@@ -152,27 +146,24 @@ int StreamPeerOpenSSL::_cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg
if (ssl->validate_hostname) {
- Error err = _match_subject_alternative_name(ssl->hostname.utf8().get_data(),server_cert);
+ Error err = _match_subject_alternative_name(ssl->hostname.utf8().get_data(), server_cert);
- if (err==ERR_FILE_NOT_FOUND) {
+ if (err == ERR_FILE_NOT_FOUND) {
- err = _match_common_name(ssl->hostname.utf8().get_data(),server_cert);
+ err = _match_common_name(ssl->hostname.utf8().get_data(), server_cert);
}
- if (err!=OK) {
+ if (err != OK) {
- ssl->status=STATUS_ERROR_HOSTNAME_MISMATCH;
+ ssl->status = STATUS_ERROR_HOSTNAME_MISMATCH;
return 0;
}
}
return 1;
-
}
-
-
-int StreamPeerOpenSSL::_bio_create( BIO *b ) {
+int StreamPeerOpenSSL::_bio_create(BIO *b) {
b->init = 1;
b->num = 0;
b->ptr = NULL;
@@ -180,31 +171,29 @@ int StreamPeerOpenSSL::_bio_create( BIO *b ) {
return 1;
}
-int StreamPeerOpenSSL::_bio_destroy( BIO *b )
-{
- if ( b == NULL )
+int StreamPeerOpenSSL::_bio_destroy(BIO *b) {
+ if (b == NULL)
return 0;
- b->ptr = NULL; /* sb_tls_remove() will free it */
+ b->ptr = NULL; /* sb_tls_remove() will free it */
b->init = 0;
b->flags = 0;
return 1;
}
-int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) {
+int StreamPeerOpenSSL::_bio_read(BIO *b, char *buf, int len) {
-
- if ( buf == NULL || len <= 0 ) return 0;
+ if (buf == NULL || len <= 0) return 0;
StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr;
- ERR_FAIL_COND_V( sp == NULL, 0);
+ ERR_FAIL_COND_V(sp == NULL, 0);
- BIO_clear_retry_flags( b );
+ BIO_clear_retry_flags(b);
if (sp->use_blocking) {
- Error err = sp->base->get_data((uint8_t*)buf,len);
- if (err!=OK) {
+ Error err = sp->base->get_data((uint8_t *)buf, len);
+ if (err != OK) {
return -1;
}
@@ -212,12 +201,12 @@ int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) {
} else {
int got;
- Error err = sp->base->get_partial_data((uint8_t*)buf,len,got);
- if (err!=OK) {
+ Error err = sp->base->get_partial_data((uint8_t *)buf, len, got);
+ if (err != OK) {
return -1;
}
- if (got==0) {
- BIO_set_retry_read( b );
+ if (got == 0) {
+ BIO_set_retry_read(b);
}
return got;
}
@@ -226,19 +215,19 @@ int StreamPeerOpenSSL::_bio_read( BIO *b, char *buf, int len ) {
return 0;
}
-int StreamPeerOpenSSL::_bio_write( BIO *b, const char *buf, int len ) {
+int StreamPeerOpenSSL::_bio_write(BIO *b, const char *buf, int len) {
- if ( buf == NULL || len <= 0 ) return 0;
+ if (buf == NULL || len <= 0) return 0;
StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr;
- ERR_FAIL_COND_V( sp == NULL, 0);
+ ERR_FAIL_COND_V(sp == NULL, 0);
- BIO_clear_retry_flags( b );
+ BIO_clear_retry_flags(b);
if (sp->use_blocking) {
- Error err = sp->base->put_data((const uint8_t*)buf,len);
- if (err!=OK) {
+ Error err = sp->base->put_data((const uint8_t *)buf, len);
+ if (err != OK) {
return -1;
}
@@ -246,43 +235,39 @@ int StreamPeerOpenSSL::_bio_write( BIO *b, const char *buf, int len ) {
} else {
int sent;
- Error err = sp->base->put_partial_data((const uint8_t*)buf,len,sent);
- if (err!=OK) {
+ Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent);
+ if (err != OK) {
return -1;
}
- if (sent==0) {
- BIO_set_retry_write( b );
+ if (sent == 0) {
+ BIO_set_retry_write(b);
}
return sent;
-
}
//unreachable
return 0;
}
-long StreamPeerOpenSSL::_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
-{
- if ( cmd == BIO_CTRL_FLUSH ) {
+long StreamPeerOpenSSL::_bio_ctrl(BIO *b, int cmd, long num, void *ptr) {
+ if (cmd == BIO_CTRL_FLUSH) {
/* The OpenSSL library needs this */
return 1;
}
return 0;
}
-int StreamPeerOpenSSL::_bio_gets( BIO *b, char *buf, int len )
-{
+int StreamPeerOpenSSL::_bio_gets(BIO *b, char *buf, int len) {
return -1;
}
-int StreamPeerOpenSSL::_bio_puts( BIO *b, const char *str )
-{
- return _bio_write( b, str, strlen( str ) );
+int StreamPeerOpenSSL::_bio_puts(BIO *b, const char *str) {
+ return _bio_write(b, str, strlen(str));
}
BIO_METHOD StreamPeerOpenSSL::_bio_method = {
/* it's a source/sink BIO */
- ( 100 | 0x400 ),
+ (100 | 0x400),
"streampeer glue",
_bio_write,
_bio_read,
@@ -293,35 +278,29 @@ BIO_METHOD StreamPeerOpenSSL::_bio_method = {
_bio_destroy
};
-Error StreamPeerOpenSSL::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String& p_for_hostname) {
+Error StreamPeerOpenSSL::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
if (connected)
disconnect_from_stream();
-
- hostname=p_for_hostname;
- status=STATUS_DISCONNECTED;
+ hostname = p_for_hostname;
+ status = STATUS_DISCONNECTED;
// Set up a SSL_CTX object, which will tell our BIO object how to do its work
ctx = SSL_CTX_new(SSLv23_client_method());
- base=p_base;
- validate_certs=p_validate_certs;
- validate_hostname=p_for_hostname!="";
-
-
-
+ base = p_base;
+ validate_certs = p_validate_certs;
+ validate_hostname = p_for_hostname != "";
if (p_validate_certs) {
-
if (certs.size()) {
//yay for undocumented OpenSSL functions
X509_STORE *store = SSL_CTX_get_cert_store(ctx);
- for(int i=0;i<certs.size();i++) {
-
- X509_STORE_add_cert(store,certs[i]);
+ for (int i = 0; i < certs.size(); i++) {
+ X509_STORE_add_cert(store, certs[i]);
}
#if 0
const unsigned char *in=(const unsigned char *)certs.ptr();
@@ -343,7 +322,6 @@ Error StreamPeerOpenSSL::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
//int res = SSL_CTX_load_verify_locations(ctx,"/etc/ssl/certs/ca-certificates.crt",NULL);
//print_line("verify locations res: "+itos(res));
-
/* Ask OpenSSL to verify the server certificate. Note that this
* does NOT include verifying that the hostname is correct.
* So, by itself, this means anyone with any legitimate
@@ -366,183 +344,176 @@ Error StreamPeerOpenSSL::connect_to_stream(Ref<StreamPeer> p_base, bool p_valida
* OpenSSL's built-in routine which would have been called if
* we hadn't set the callback. Therefore, we're just
* "wrapping" OpenSSL's routine, not replacing it. */
- SSL_CTX_set_cert_verify_callback (ctx, _cert_verify_callback,this);
+ SSL_CTX_set_cert_verify_callback(ctx, _cert_verify_callback, this);
//Let the verify_callback catch the verify_depth error so that we get an appropriate error in the logfile. (??)
- SSL_CTX_set_verify_depth(ctx,max_cert_chain_depth + 1);
-
+ SSL_CTX_set_verify_depth(ctx, max_cert_chain_depth + 1);
}
-
-
-
-
- ssl = SSL_new( ctx );
- bio = BIO_new( &_bio_method );
+ ssl = SSL_new(ctx);
+ bio = BIO_new(&_bio_method);
bio->ptr = this;
- SSL_set_bio( ssl, bio, bio );
+ SSL_set_bio(ssl, bio, bio);
- if (p_for_hostname!=String()) {
- SSL_set_tlsext_host_name(ssl,p_for_hostname.utf8().get_data());
+ if (p_for_hostname != String()) {
+ SSL_set_tlsext_host_name(ssl, p_for_hostname.utf8().get_data());
}
- use_blocking=true; // let handshake use blocking
+ use_blocking = true; // let handshake use blocking
// Set the SSL to automatically retry on failure.
SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
// Same as before, try to connect.
- int result = SSL_connect( ssl );
+ int result = SSL_connect(ssl);
- print_line("CONNECTION RESULT: "+itos(result));
- if (result<1) {
+ print_line("CONNECTION RESULT: " + itos(result));
+ if (result < 1) {
ERR_print_errors_fp(stdout);
_print_error(result);
}
- X509 * peer = SSL_get_peer_certificate(ssl);
+ X509 *peer = SSL_get_peer_certificate(ssl);
if (peer) {
bool cert_ok = SSL_get_verify_result(ssl) == X509_V_OK;
- print_line("cert_ok: "+itos(cert_ok));
+ print_line("cert_ok: " + itos(cert_ok));
- } else if (validate_certs){
- status=STATUS_ERROR_NO_CERTIFICATE;
+ } else if (validate_certs) {
+ status = STATUS_ERROR_NO_CERTIFICATE;
}
- connected=true;
- status=STATUS_CONNECTED;
+ connected = true;
+ status = STATUS_CONNECTED;
return OK;
}
Error StreamPeerOpenSSL::accept_stream(Ref<StreamPeer> p_base) {
-
return ERR_UNAVAILABLE;
}
void StreamPeerOpenSSL::_print_error(int err) {
- err = SSL_get_error(ssl,err);
- switch(err) {
+ err = SSL_get_error(ssl, err);
+ switch (err) {
case SSL_ERROR_NONE: ERR_PRINT("NO ERROR: The TLS/SSL I/O operation completed"); break;
case SSL_ERROR_ZERO_RETURN: ERR_PRINT("The TLS/SSL connection has been closed.");
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
- ERR_PRINT("The operation did not complete."); break;
+ ERR_PRINT("The operation did not complete.");
+ break;
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
- ERR_PRINT("The connect/accept operation did not complete"); break;
+ ERR_PRINT("The connect/accept operation did not complete");
+ break;
case SSL_ERROR_WANT_X509_LOOKUP:
- ERR_PRINT("The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again."); break;
+ ERR_PRINT("The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again.");
+ break;
case SSL_ERROR_SYSCALL:
- ERR_PRINT("Some I/O error occurred. The OpenSSL error queue may contain more information on the error."); break;
+ ERR_PRINT("Some I/O error occurred. The OpenSSL error queue may contain more information on the error.");
+ break;
case SSL_ERROR_SSL:
- ERR_PRINT("A failure in the SSL library occurred, usually a protocol error."); break;
-
+ ERR_PRINT("A failure in the SSL library occurred, usually a protocol error.");
+ break;
}
}
-Error StreamPeerOpenSSL::put_data(const uint8_t* p_data,int p_bytes) {
+Error StreamPeerOpenSSL::put_data(const uint8_t *p_data, int p_bytes) {
- ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
- while(p_bytes>0) {
- int ret = SSL_write(ssl,p_data,p_bytes);
- if (ret<=0) {
+ while (p_bytes > 0) {
+ int ret = SSL_write(ssl, p_data, p_bytes);
+ if (ret <= 0) {
_print_error(ret);
disconnect_from_stream();
return ERR_CONNECTION_ERROR;
}
- p_data+=ret;
- p_bytes-=ret;
+ p_data += ret;
+ p_bytes -= ret;
}
return OK;
-
}
-Error StreamPeerOpenSSL::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent){
+Error StreamPeerOpenSSL::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
- ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED);
- if (p_bytes==0)
+ ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
+ if (p_bytes == 0)
return OK;
- Error err = put_data(p_data,p_bytes);
- if (err!=OK)
+ Error err = put_data(p_data, p_bytes);
+ if (err != OK)
return err;
- r_sent=p_bytes;
+ r_sent = p_bytes;
return OK;
-
}
-Error StreamPeerOpenSSL::get_data(uint8_t* p_buffer, int p_bytes){
+Error StreamPeerOpenSSL::get_data(uint8_t *p_buffer, int p_bytes) {
- ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
- while(p_bytes>0) {
+ while (p_bytes > 0) {
- int ret = SSL_read(ssl,p_buffer,p_bytes);
- if (ret<=0) {
+ int ret = SSL_read(ssl, p_buffer, p_bytes);
+ if (ret <= 0) {
_print_error(ret);
disconnect_from_stream();
return ERR_CONNECTION_ERROR;
}
- p_buffer+=ret;
- p_bytes-=ret;
+ p_buffer += ret;
+ p_bytes -= ret;
}
return OK;
}
-Error StreamPeerOpenSSL::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received){
+Error StreamPeerOpenSSL::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
- ERR_FAIL_COND_V(!connected,ERR_UNCONFIGURED);
- if (p_bytes==0) {
- r_received=0;
+ ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
+ if (p_bytes == 0) {
+ r_received = 0;
return OK;
}
- Error err = get_data(p_buffer,p_bytes);
- if (err!=OK)
+ Error err = get_data(p_buffer, p_bytes);
+ if (err != OK)
return err;
- r_received=p_bytes;
+ r_received = p_bytes;
return OK;
}
int StreamPeerOpenSSL::get_available_bytes() const {
- ERR_FAIL_COND_V(!connected,0);
+ ERR_FAIL_COND_V(!connected, 0);
return SSL_pending(ssl);
-
}
StreamPeerOpenSSL::StreamPeerOpenSSL() {
- ctx=NULL;
- ssl=NULL;
- bio=NULL;
- connected=false;
- use_blocking=true; //might be improved int the future, but for now it always blocks
- max_cert_chain_depth=9;
- flags=0;
+ ctx = NULL;
+ ssl = NULL;
+ bio = NULL;
+ connected = false;
+ use_blocking = true; //might be improved int the future, but for now it always blocks
+ max_cert_chain_depth = 9;
+ flags = 0;
}
void StreamPeerOpenSSL::disconnect_from_stream() {
if (!connected)
return;
- SSL_shutdown( ssl );
- SSL_free( ssl );
+ SSL_shutdown(ssl);
+ SSL_free(ssl);
SSL_CTX_free(ctx);
- base=Ref<StreamPeer>();
- connected=false;
- validate_certs=false;
- validate_hostname=false;
- status=STATUS_DISCONNECTED;
-
-
+ base = Ref<StreamPeer>();
+ connected = false;
+ validate_certs = false;
+ validate_hostname = false;
+ status = STATUS_DISCONNECTED;
}
StreamPeerOpenSSL::Status StreamPeerOpenSSL::get_status() const {
@@ -550,27 +521,24 @@ StreamPeerOpenSSL::Status StreamPeerOpenSSL::get_status() const {
return status;
}
-
StreamPeerOpenSSL::~StreamPeerOpenSSL() {
disconnect_from_stream();
}
-StreamPeerSSL* StreamPeerOpenSSL::_create_func() {
+StreamPeerSSL *StreamPeerOpenSSL::_create_func() {
- return memnew( StreamPeerOpenSSL );
+ return memnew(StreamPeerOpenSSL);
}
+Vector<X509 *> StreamPeerOpenSSL::certs;
-Vector<X509*> StreamPeerOpenSSL::certs;
-
-
-void StreamPeerOpenSSL::_load_certs(const PoolByteArray& p_array) {
+void StreamPeerOpenSSL::_load_certs(const PoolByteArray &p_array) {
PoolByteArray::Read r = p_array.read();
- BIO* mem = BIO_new(BIO_s_mem());
- BIO_puts(mem,(const char*)r.ptr());
- while(true) {
- X509*cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
+ BIO *mem = BIO_new(BIO_s_mem());
+ BIO_puts(mem, (const char *)r.ptr());
+ while (true) {
+ X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
if (!cert)
break;
certs.push_back(cert);
@@ -580,66 +548,62 @@ void StreamPeerOpenSSL::_load_certs(const PoolByteArray& p_array) {
void StreamPeerOpenSSL::initialize_ssl() {
- available=true;
+ available = true;
- load_certs_func=_load_certs;
+ load_certs_func = _load_certs;
- _create=_create_func;
+ _create = _create_func;
CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use
SSL_library_init(); // Initialize OpenSSL's SSL libraries
SSL_load_error_strings(); // Load SSL error strings
ERR_load_BIO_strings(); // Load BIO error strings
OpenSSL_add_all_algorithms(); // Load all available encryption algorithms
- String certs_path =GLOBAL_DEF("network/ssl/certificates","");
- GlobalConfig::get_singleton()->set_custom_property_info("network/ssl/certificates",PropertyInfo(Variant::STRING,"network/ssl/certificates",PROPERTY_HINT_FILE,"*.crt"));
- if (certs_path!="") {
-
-
+ String certs_path = GLOBAL_DEF("network/ssl/certificates", "");
+ GlobalConfig::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt"));
+ if (certs_path != "") {
- FileAccess *f=FileAccess::open(certs_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(certs_path, FileAccess::READ);
if (f) {
PoolByteArray arr;
int flen = f->get_len();
- arr.resize(flen+1);
+ arr.resize(flen + 1);
{
PoolByteArray::Write w = arr.write();
- f->get_buffer(w.ptr(),flen);
- w[flen]=0; //end f string
+ f->get_buffer(w.ptr(), flen);
+ w[flen] = 0; //end f string
}
memdelete(f);
_load_certs(arr);
- print_line("Loaded certs from '"+certs_path+"': "+itos(certs.size()));
+ print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size()));
}
}
- String config_path =GLOBAL_DEF("network/ssl/config","");
- GlobalConfig::get_singleton()->set_custom_property_info("network/ssl/config",PropertyInfo(Variant::STRING,"network/ssl/config",PROPERTY_HINT_FILE,"*.cnf"));
- if (config_path!="") {
+ String config_path = GLOBAL_DEF("network/ssl/config", "");
+ GlobalConfig::get_singleton()->set_custom_property_info("network/ssl/config", PropertyInfo(Variant::STRING, "network/ssl/config", PROPERTY_HINT_FILE, "*.cnf"));
+ if (config_path != "") {
Vector<uint8_t> data = FileAccess::get_file_as_array(config_path);
if (data.size()) {
data.push_back(0);
- BIO* mem = BIO_new(BIO_s_mem());
- BIO_puts(mem,(const char*) data.ptr());
+ BIO *mem = BIO_new(BIO_s_mem());
+ BIO_puts(mem, (const char *)data.ptr());
- while(true) {
- X509*cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
+ while (true) {
+ X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
if (!cert)
break;
certs.push_back(cert);
}
BIO_free(mem);
}
- print_line("Loaded certs from '"+certs_path+"': "+itos(certs.size()));
-
+ print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size()));
}
-
}
-void StreamPeerOpenSSL::finalize_ssl(){
+void StreamPeerOpenSSL::finalize_ssl() {
- for(int i=0;i<certs.size();i++) {
+ for (int i = 0; i < certs.size(); i++) {
X509_free(certs[i]);
}
certs.clear();
diff --git a/modules/openssl/stream_peer_openssl.h b/modules/openssl/stream_peer_openssl.h
index 84ae03fe07..56b45802df 100644
--- a/modules/openssl/stream_peer_openssl.h
+++ b/modules/openssl/stream_peer_openssl.h
@@ -29,26 +29,26 @@
#ifndef STREAM_PEER_OPEN_SSL_H
#define STREAM_PEER_OPEN_SSL_H
-#include <stdio.h> // If you don't know what this is for stop reading now.
-#include "io/stream_peer_ssl.h"
+#include "curl_hostcheck.h"
#include "global_config.h"
+#include "io/stream_peer_ssl.h"
#include "os/file_access.h"
-#include "curl_hostcheck.h"
+#include <stdio.h> // If you don't know what this is for stop reading now.
#include <openssl/bio.h> // BIO objects for I/O
-#include <openssl/ssl.h> // SSL and SSL_CTX for SSL connections
#include <openssl/err.h> // Error reporting
+#include <openssl/ssl.h> // SSL and SSL_CTX for SSL connections
#include <openssl/x509v3.h>
class StreamPeerOpenSSL : public StreamPeerSSL {
private:
- static int _bio_create( BIO *b );
- static int _bio_destroy( BIO *b );
- static int _bio_read( BIO *b, char *buf, int len );
- static int _bio_write( BIO *b, const char *buf, int len );
- static long _bio_ctrl( BIO *b, int cmd, long num, void *ptr );
- static int _bio_gets( BIO *b, char *buf, int len );
- static int _bio_puts( BIO *b, const char *str );
+ static int _bio_create(BIO *b);
+ static int _bio_destroy(BIO *b);
+ static int _bio_read(BIO *b, char *buf, int len);
+ static int _bio_write(BIO *b, const char *buf, int len);
+ static long _bio_ctrl(BIO *b, int cmd, long num, void *ptr);
+ static int _bio_gets(BIO *b, char *buf, int len);
+ static int _bio_puts(BIO *b, const char *str);
static BIO_METHOD _bio_method;
@@ -56,16 +56,14 @@ private:
static Error _match_common_name(const char *hostname, const X509 *server_cert);
static Error _match_subject_alternative_name(const char *hostname, const X509 *server_cert);
-
static int _cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg);
-
Status status;
String hostname;
int max_cert_chain_depth;
- SSL_CTX* ctx;
- SSL* ssl;
- BIO* bio;
+ SSL_CTX *ctx;
+ SSL *ssl;
+ BIO *bio;
bool connected;
int flags;
bool use_blocking;
@@ -74,28 +72,28 @@ private:
Ref<StreamPeer> base;
- static StreamPeerSSL* _create_func();
+ static StreamPeerSSL *_create_func();
void _print_error(int err);
- static Vector<X509*> certs;
+ static Vector<X509 *> certs;
+
+ static void _load_certs(const PoolByteArray &p_array);
- static void _load_certs(const PoolByteArray& p_array);
protected:
static void _bind_methods();
-public:
-
+public:
virtual Error accept_stream(Ref<StreamPeer> p_base);
- virtual Error connect_to_stream(Ref<StreamPeer> p_base,bool p_validate_certs=false,const String& p_for_hostname=String());
+ virtual Error connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs = false, const String &p_for_hostname = String());
virtual Status get_status() const;
virtual void disconnect_from_stream();
- virtual Error put_data(const uint8_t* p_data,int p_bytes);
- virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent);
+ virtual Error put_data(const uint8_t *p_data, int p_bytes);
+ virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent);
- virtual Error get_data(uint8_t* p_buffer, int p_bytes);
- virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received);
+ virtual Error get_data(uint8_t *p_buffer, int p_bytes);
+ virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received);
virtual int get_available_bytes() const;
diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp
index 4a6b2e224c..52b055ca82 100644
--- a/modules/opus/audio_stream_opus.cpp
+++ b/modules/opus/audio_stream_opus.cpp
@@ -30,32 +30,32 @@
/*************************************************************************/
#include "audio_stream_opus.h"
-const float AudioStreamPlaybackOpus::osrate=48000.0f;
+const float AudioStreamPlaybackOpus::osrate = 48000.0f;
int AudioStreamPlaybackOpus::_op_read_func(void *_stream, unsigned char *_ptr, int _nbytes) {
- FileAccess *fa=(FileAccess*)_stream;
+ FileAccess *fa = (FileAccess *)_stream;
- if(fa->eof_reached())
+ if (fa->eof_reached())
return 0;
- uint8_t *dst = (uint8_t*)_ptr;
+ uint8_t *dst = (uint8_t *)_ptr;
int read = fa->get_buffer(dst, _nbytes);
return read;
}
-int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence){
+int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, int _whence) {
#ifdef SEEK_SET
- FileAccess *fa=(FileAccess*)_stream;
+ FileAccess *fa = (FileAccess *)_stream;
switch (_whence) {
case SEEK_SET: {
fa->seek(_offset);
} break;
case SEEK_CUR: {
- fa->seek(fa->get_pos()+_offset);
+ fa->seek(fa->get_pos() + _offset);
} break;
case SEEK_END: {
fa->seek_end(_offset);
@@ -64,7 +64,7 @@ int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, in
ERR_PRINT("BUG, wtf was whence set to?\n");
}
}
- int ret=fa->eof_reached()?-1:0;
+ int ret = fa->eof_reached() ? -1 : 0;
return ret;
#else
return -1; // no seeking
@@ -74,97 +74,100 @@ int AudioStreamPlaybackOpus::_op_seek_func(void *_stream, opus_int64 _offset, in
int AudioStreamPlaybackOpus::_op_close_func(void *_stream) {
if (!_stream)
return 0;
- FileAccess *fa=(FileAccess*)_stream;
+ FileAccess *fa = (FileAccess *)_stream;
if (fa->is_open())
fa->close();
return 0;
}
opus_int64 AudioStreamPlaybackOpus::_op_tell_func(void *_stream) {
- FileAccess *_fa = (FileAccess*)_stream;
+ FileAccess *_fa = (FileAccess *)_stream;
return (opus_int64)_fa->get_pos();
}
void AudioStreamPlaybackOpus::_clear_stream() {
- if(!stream_loaded)
+ if (!stream_loaded)
return;
op_free(opus_file);
_close_file();
- stream_loaded=false;
- stream_channels=1;
- playing=false;
+ stream_loaded = false;
+ stream_channels = 1;
+ playing = false;
}
void AudioStreamPlaybackOpus::_close_file() {
if (f) {
memdelete(f);
- f=NULL;
+ f = NULL;
}
}
Error AudioStreamPlaybackOpus::_load_stream() {
- ERR_FAIL_COND_V(!stream_valid,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED);
_clear_stream();
- if (file=="")
+ if (file == "")
return ERR_INVALID_DATA;
Error err;
- f=FileAccess::open(file,FileAccess::READ,&err);
+ f = FileAccess::open(file, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V( err, err );
+ ERR_FAIL_COND_V(err, err);
}
int _err = 0;
- opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&_err);
+ opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err);
switch (_err) {
case OP_EREAD: { // - Can't read the file.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CANT_READ );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CANT_READ);
} break;
case OP_EVERSION: // - Unrecognized version number.
case OP_ENOTFORMAT: // - Stream is not Opus data.
- case OP_EIMPL : { // - Stream used non-implemented feature.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ case OP_EIMPL: { // - Stream used non-implemented feature.
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
} break;
case OP_EBADLINK: // - Failed to find old data after seeking.
case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks.
case OP_EBADHEADER: { // - Invalid or mising Opus bitstream header.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CORRUPT );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CORRUPT);
} break;
case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_BUG );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_BUG);
} break;
}
- repeats=0;
- stream_loaded=true;
-
+ repeats = 0;
+ stream_loaded = true;
return OK;
}
AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() {
- loops=false;
- playing=false;
+ loops = false;
+ playing = false;
f = NULL;
- stream_loaded=false;
- stream_valid=false;
- repeats=0;
- paused=true;
- stream_channels=0;
- current_section=0;
- length=0;
- loop_restart_time=0;
- pre_skip=0;
+ stream_loaded = false;
+ stream_valid = false;
+ repeats = 0;
+ paused = true;
+ stream_channels = 0;
+ current_section = 0;
+ length = 0;
+ loop_restart_time = 0;
+ pre_skip = 0;
_op_callbacks.read = _op_read_func;
_op_callbacks.seek = _op_seek_func;
@@ -173,59 +176,62 @@ AudioStreamPlaybackOpus::AudioStreamPlaybackOpus() {
}
Error AudioStreamPlaybackOpus::set_file(const String &p_file) {
- file=p_file;
- stream_valid=false;
+ file = p_file;
+ stream_valid = false;
Error err;
- f=FileAccess::open(file,FileAccess::READ,&err);
+ f = FileAccess::open(file, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V( err, err );
+ ERR_FAIL_COND_V(err, err);
}
int _err;
- opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&_err);
+ opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &_err);
switch (_err) {
case OP_EREAD: { // - Can't read the file.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CANT_READ );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CANT_READ);
} break;
case OP_EVERSION: // - Unrecognized version number.
case OP_ENOTFORMAT: // - Stream is not Opus data.
- case OP_EIMPL : { // - Stream used non-implemented feature.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ case OP_EIMPL: { // - Stream used non-implemented feature.
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
} break;
case OP_EBADLINK: // - Failed to find old data after seeking.
case OP_EBADTIMESTAMP: // - Timestamp failed the validity checks.
case OP_EBADHEADER: { // - Invalid or mising Opus bitstream header.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CORRUPT );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CORRUPT);
} break;
case OP_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_BUG );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_BUG);
} break;
}
- const OpusHead *oinfo = op_head(opus_file,-1);
+ const OpusHead *oinfo = op_head(opus_file, -1);
- stream_channels=oinfo->channel_count;
- pre_skip=oinfo->pre_skip;
- frames_mixed=pre_skip;
- ogg_int64_t len = op_pcm_total(opus_file,-1);
- if(len < 0) {
+ stream_channels = oinfo->channel_count;
+ pre_skip = oinfo->pre_skip;
+ frames_mixed = pre_skip;
+ ogg_int64_t len = op_pcm_total(opus_file, -1);
+ if (len < 0) {
length = 0;
} else {
- length=(len/osrate);
+ length = (len / osrate);
}
op_free(opus_file);
memdelete(f);
- f=NULL;
- stream_valid=true;
-
+ f = NULL;
+ stream_valid = true;
return OK;
}
@@ -234,102 +240,100 @@ void AudioStreamPlaybackOpus::play(float p_from) {
if (playing)
stop();
- if (_load_stream()!=OK)
+ if (_load_stream() != OK)
return;
- frames_mixed=pre_skip;
- playing=true;
- if (p_from>0) {
+ frames_mixed = pre_skip;
+ playing = true;
+ if (p_from > 0) {
seek_pos(p_from);
}
}
void AudioStreamPlaybackOpus::stop() {
_clear_stream();
- playing=false;
+ playing = false;
}
void AudioStreamPlaybackOpus::seek_pos(float p_time) {
- if(!playing) return;
+ if (!playing) return;
ogg_int64_t pcm_offset = (ogg_int64_t)(p_time * osrate);
- bool ok = op_pcm_seek(opus_file,pcm_offset)==0;
- if(!ok) {
+ bool ok = op_pcm_seek(opus_file, pcm_offset) == 0;
+ if (!ok) {
ERR_PRINT("Seek time over stream size.");
return;
}
- frames_mixed=osrate*p_time;
+ frames_mixed = osrate * p_time;
}
-int AudioStreamPlaybackOpus::mix(int16_t* p_bufer,int p_frames) {
+int AudioStreamPlaybackOpus::mix(int16_t *p_bufer, int p_frames) {
if (!playing)
return 0;
- int total=p_frames;
+ int total = p_frames;
while (true) {
int todo = p_frames;
- if (todo==0 || todo<MIN_MIX) {
+ if (todo == 0 || todo < MIN_MIX) {
break;
}
- int ret=op_read(opus_file,(opus_int16*)p_bufer,todo*stream_channels,&current_section);
- if (ret<0) {
+ int ret = op_read(opus_file, (opus_int16 *)p_bufer, todo * stream_channels, &current_section);
+ if (ret < 0) {
playing = false;
- ERR_EXPLAIN("Error reading Opus File: "+file);
- ERR_BREAK(ret<0);
- } else if (ret==0) { // end of song, reload?
+ ERR_EXPLAIN("Error reading Opus File: " + file);
+ ERR_BREAK(ret < 0);
+ } else if (ret == 0) { // end of song, reload?
op_free(opus_file);
_close_file();
- f=FileAccess::open(file,FileAccess::READ);
+ f = FileAccess::open(file, FileAccess::READ);
int errv = 0;
- opus_file = op_open_callbacks(f,&_op_callbacks,NULL,0,&errv);
- if (errv!=0) {
- playing=false;
+ opus_file = op_open_callbacks(f, &_op_callbacks, NULL, 0, &errv);
+ if (errv != 0) {
+ playing = false;
break; // :(
}
if (!has_loop()) {
- playing=false;
- repeats=1;
+ playing = false;
+ repeats = 1;
break;
}
if (loop_restart_time) {
- bool ok = op_pcm_seek(opus_file, (loop_restart_time*osrate)+pre_skip)==0;
+ bool ok = op_pcm_seek(opus_file, (loop_restart_time * osrate) + pre_skip) == 0;
if (!ok) {
- playing=false;
+ playing = false;
ERR_PRINT("loop restart time rejected")
}
- frames_mixed=(loop_restart_time*osrate)+pre_skip;
+ frames_mixed = (loop_restart_time * osrate) + pre_skip;
} else {
- frames_mixed=pre_skip;
+ frames_mixed = pre_skip;
}
repeats++;
continue;
-
}
- stream_channels=op_head(opus_file,current_section)->channel_count;
-
- frames_mixed+=ret;
+ stream_channels = op_head(opus_file, current_section)->channel_count;
- p_bufer+=ret*stream_channels;
- p_frames-=ret;
+ frames_mixed += ret;
+ p_bufer += ret * stream_channels;
+ p_frames -= ret;
}
- return total-p_frames;
+ return total - p_frames;
}
float AudioStreamPlaybackOpus::get_length() const {
- if(!stream_loaded) {
- if(const_cast<AudioStreamPlaybackOpus*>(this)->_load_stream() != OK)
+ if (!stream_loaded) {
+ if (const_cast<AudioStreamPlaybackOpus *>(this)->_load_stream() != OK)
return 0;
}
return length;
@@ -339,7 +343,7 @@ float AudioStreamPlaybackOpus::get_pos() const {
int32_t frames = int32_t(frames_mixed);
if (frames < 0)
- frames=0;
+ frames = 0;
return double(frames) / osrate;
}
@@ -351,9 +355,9 @@ AudioStreamPlaybackOpus::~AudioStreamPlaybackOpus() {
_clear_stream();
}
-RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderAudioStreamOpus::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=OK;
+ *r_error = OK;
AudioStreamOpus *opus_stream = memnew(AudioStreamOpus);
opus_stream->set_file(p_path);
@@ -366,11 +370,11 @@ void ResourceFormatLoaderAudioStreamOpus::get_recognized_extensions(List<String>
}
String ResourceFormatLoaderAudioStreamOpus::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="opus")
+ if (p_path.get_extension().to_lower() == "opus")
return "AudioStreamOpus";
return "";
}
-bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String& p_type) const {
- return (p_type=="AudioStream" || p_type=="AudioStreamOpus");
+bool ResourceFormatLoaderAudioStreamOpus::handles_type(const String &p_type) const {
+ return (p_type == "AudioStream" || p_type == "AudioStreamOpus");
}
diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h
index 5093456ccd..f1bee121b2 100644
--- a/modules/opus/audio_stream_opus.h
+++ b/modules/opus/audio_stream_opus.h
@@ -40,10 +40,10 @@
class AudioStreamPlaybackOpus : public AudioStreamPlayback {
- GDCLASS(AudioStreamPlaybackOpus,AudioStreamPlayback)
+ GDCLASS(AudioStreamPlaybackOpus, AudioStreamPlayback)
enum {
- MIN_MIX=1024
+ MIN_MIX = 1024
};
FileAccess *f;
@@ -78,19 +78,19 @@ class AudioStreamPlaybackOpus : public AudioStreamPlayback {
float loop_restart_time;
public:
- Error set_file(const String& p_file);
+ Error set_file(const String &p_file);
- virtual void play(float p_from=0);
+ virtual void play(float p_from = 0);
virtual void stop();
virtual bool is_playing() const { return playing; }
- virtual void set_loop_restart_time(float p_time) { loop_restart_time=p_time; }
+ virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; }
- virtual void set_paused(bool p_paused) { paused=p_paused; }
+ virtual void set_paused(bool p_paused) { paused = p_paused; }
virtual bool is_paused() const { return paused; }
- virtual void set_loop(bool p_enable) { loops=p_enable; }
- virtual bool has_loop() const {return loops; }
+ virtual void set_loop(bool p_enable) { loops = p_enable; }
+ virtual bool has_loop() const { return loops; }
virtual float get_length() const;
@@ -106,35 +106,33 @@ public:
virtual int get_minimum_buffer_size() const;
- virtual int mix(int16_t* p_bufer,int p_frames);
+ virtual int mix(int16_t *p_bufer, int p_frames);
AudioStreamPlaybackOpus();
~AudioStreamPlaybackOpus();
};
+class AudioStreamOpus : public AudioStream {
-class AudioStreamOpus: public AudioStream {
-
- GDCLASS(AudioStreamOpus,AudioStream)
+ GDCLASS(AudioStreamOpus, AudioStream)
String file;
-public:
+public:
Ref<AudioStreamPlayback> instance_playback() {
- Ref<AudioStreamPlaybackOpus> pb = memnew( AudioStreamPlaybackOpus );
+ Ref<AudioStreamPlaybackOpus> pb = memnew(AudioStreamPlaybackOpus);
pb->set_file(file);
return pb;
}
- void set_file(const String& p_file) { file=p_file; }
-
+ void set_file(const String &p_file) { file = p_file; }
};
-class ResourceFormatLoaderAudioStreamOpus: public ResourceFormatLoader {
+class ResourceFormatLoaderAudioStreamOpus : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
};
diff --git a/modules/opus/register_types.cpp b/modules/opus/register_types.cpp
index a177bc9463..8a48c5084e 100644
--- a/modules/opus/register_types.cpp
+++ b/modules/opus/register_types.cpp
@@ -34,12 +34,12 @@ static ResourceFormatLoaderAudioStreamOpus *opus_stream_loader = NULL;
void register_opus_types() {
- opus_stream_loader = memnew( ResourceFormatLoaderAudioStreamOpus );
+ opus_stream_loader = memnew(ResourceFormatLoaderAudioStreamOpus);
ResourceLoader::add_resource_format_loader(opus_stream_loader);
ClassDB::register_class<AudioStreamOpus>();
}
void unregister_opus_types() {
- memdelete( opus_stream_loader );
+ memdelete(opus_stream_loader);
}
diff --git a/modules/pbm/bitmap_loader_pbm.cpp b/modules/pbm/bitmap_loader_pbm.cpp
index ab0805a6b0..04051fc38f 100644
--- a/modules/pbm/bitmap_loader_pbm.cpp
+++ b/modules/pbm/bitmap_loader_pbm.cpp
@@ -30,30 +30,27 @@
#include "os/file_access.h"
#include "scene/resources/bit_mask.h"
-
-static bool _get_token(FileAccessRef& f,uint8_t &saved,PoolVector<uint8_t>& r_token,bool p_binary=false,bool p_single_chunk=false) {
-
+static bool _get_token(FileAccessRef &f, uint8_t &saved, PoolVector<uint8_t> &r_token, bool p_binary = false, bool p_single_chunk = false) {
int token_max = r_token.size();
PoolVector<uint8_t>::Write w;
if (token_max)
- w=r_token.write();
- int ofs=0;
- bool lf=false;
-
+ w = r_token.write();
+ int ofs = 0;
+ bool lf = false;
- while(true) {
+ while (true) {
uint8_t b;
if (saved) {
- b=saved;
- saved=0;
+ b = saved;
+ saved = 0;
} else {
b = f->get_8();
}
if (f->eof_reached()) {
if (ofs) {
- w=PoolVector<uint8_t>::Write();
+ w = PoolVector<uint8_t>::Write();
r_token.resize(ofs);
return true;
} else {
@@ -61,9 +58,9 @@ static bool _get_token(FileAccessRef& f,uint8_t &saved,PoolVector<uint8_t>& r_to
}
}
- if (!ofs && !p_binary && b=='#') {
+ if (!ofs && !p_binary && b == '#') {
//skip comment
- while(b!='\n') {
+ while (b != '\n') {
if (f->eof_reached()) {
return false;
}
@@ -71,182 +68,165 @@ static bool _get_token(FileAccessRef& f,uint8_t &saved,PoolVector<uint8_t>& r_to
b = f->get_8();
}
- lf=true;
+ lf = true;
- } else if (b<=32 && !(p_binary && (ofs || lf))) {
+ } else if (b <= 32 && !(p_binary && (ofs || lf))) {
- if (b=='\n') {
- lf=true;
+ if (b == '\n') {
+ lf = true;
}
-
if (ofs && !p_single_chunk) {
- w=PoolVector<uint8_t>::Write();
+ w = PoolVector<uint8_t>::Write();
r_token.resize(ofs);
- saved=b;
+ saved = b;
return true;
}
} else {
- bool resized=false;
- while (ofs>=token_max) {
+ bool resized = false;
+ while (ofs >= token_max) {
if (token_max)
- token_max<<=1;
+ token_max <<= 1;
else
- token_max=1;
- resized=true;
+ token_max = 1;
+ resized = true;
}
if (resized) {
- w=PoolVector<uint8_t>::Write();
+ w = PoolVector<uint8_t>::Write();
r_token.resize(token_max);
- w=r_token.write();
+ w = r_token.write();
}
- w[ofs++]=b;
+ w[ofs++] = b;
}
}
return false;
}
-static int _get_number_from_token(PoolVector<uint8_t>& r_token) {
+static int _get_number_from_token(PoolVector<uint8_t> &r_token) {
int len = r_token.size();
PoolVector<uint8_t>::Read r = r_token.read();
- return String::to_int((const char*)r.ptr(),len);
-
+ return String::to_int((const char *)r.ptr(), len);
}
+RES ResourceFormatPBM::load(const String &p_path, const String &p_original_path, Error *r_error) {
-RES ResourceFormatPBM::load(const String &p_path,const String& p_original_path,Error *r_error) {
-
-#define _RETURN(m_err)\
-{\
- if (r_error)\
- *r_error=m_err;\
- ERR_FAIL_V(RES());\
-}
-
+#define _RETURN(m_err) \
+ { \
+ if (r_error) \
+ *r_error = m_err; \
+ ERR_FAIL_V(RES()); \
+ }
- FileAccessRef f=FileAccess::open(p_path,FileAccess::READ);
- uint8_t saved=0;
+ FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
+ uint8_t saved = 0;
if (!f)
_RETURN(ERR_CANT_OPEN);
PoolVector<uint8_t> token;
- if (!_get_token(f,saved,token)) {
+ if (!_get_token(f, saved, token)) {
_RETURN(ERR_PARSE_ERROR);
}
- if (token.size()!=2) {
+ if (token.size() != 2) {
_RETURN(ERR_FILE_CORRUPT);
}
- if (token[0]!='P') {
+ if (token[0] != 'P') {
_RETURN(ERR_FILE_CORRUPT);
}
- if (token[1]!='1' && token[1]!='4') {
+ if (token[1] != '1' && token[1] != '4') {
_RETURN(ERR_FILE_CORRUPT);
}
- bool bits = token[1]=='4';
+ bool bits = token[1] == '4';
- if (!_get_token(f,saved,token)) {
+ if (!_get_token(f, saved, token)) {
_RETURN(ERR_PARSE_ERROR);
}
int width = _get_number_from_token(token);
- if (width<=0) {
+ if (width <= 0) {
_RETURN(ERR_FILE_CORRUPT);
}
-
- if (!_get_token(f,saved,token)) {
+ if (!_get_token(f, saved, token)) {
_RETURN(ERR_PARSE_ERROR);
}
int height = _get_number_from_token(token);
- if (height<=0) {
+ if (height <= 0) {
_RETURN(ERR_FILE_CORRUPT);
}
-
Ref<BitMap> bm;
bm.instance();
- bm->create(Size2i(width,height));
+ bm->create(Size2i(width, height));
if (!bits) {
- int required_bytes = width*height;
- if (!_get_token(f,saved,token,false,true)) {
+ int required_bytes = width * height;
+ if (!_get_token(f, saved, token, false, true)) {
_RETURN(ERR_PARSE_ERROR);
}
- if (token.size()<required_bytes) {
+ if (token.size() < required_bytes) {
_RETURN(ERR_FILE_CORRUPT);
}
- PoolVector<uint8_t>::Read r=token.read();
-
- for(int i=0;i<height;i++) {
- for(int j=0;j<width;j++) {
+ PoolVector<uint8_t>::Read r = token.read();
+ for (int i = 0; i < height; i++) {
+ for (int j = 0; j < width; j++) {
- char num = r[i*width+j];
- bm->set_bit(Point2i(j,i),num=='0');
+ char num = r[i * width + j];
+ bm->set_bit(Point2i(j, i), num == '0');
}
-
}
-
-
} else {
//a single, entire token of bits!
- if (!_get_token(f,saved,token,true)) {
+ if (!_get_token(f, saved, token, true)) {
_RETURN(ERR_PARSE_ERROR);
}
- int required_bytes = Math::ceil((width*height)/8.0);
- if (token.size()<required_bytes) {
+ int required_bytes = Math::ceil((width * height) / 8.0);
+ if (token.size() < required_bytes) {
_RETURN(ERR_FILE_CORRUPT);
}
- PoolVector<uint8_t>::Read r=token.read();
+ PoolVector<uint8_t>::Read r = token.read();
int bitwidth = width;
if (bitwidth % 8)
- bitwidth+=8-(bitwidth%8);
+ bitwidth += 8 - (bitwidth % 8);
- for(int i=0;i<height;i++) {
- for(int j=0;j<width;j++) {
+ for (int i = 0; i < height; i++) {
+ for (int j = 0; j < width; j++) {
- int ofs = bitwidth*i+j;
+ int ofs = bitwidth * i + j;
- uint8_t byte = r[ofs/8];
- bool bit = (byte>>(7-(ofs%8)))&1;
-
- bm->set_bit(Point2i(j,i),!bit);
+ uint8_t byte = r[ofs / 8];
+ bool bit = (byte >> (7 - (ofs % 8))) & 1;
+ bm->set_bit(Point2i(j, i), !bit);
}
-
}
-
}
return bm;
-
-
}
void ResourceFormatPBM::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("pbm");
}
-bool ResourceFormatPBM::handles_type(const String& p_type) const {
- return p_type=="BitMap";
+bool ResourceFormatPBM::handles_type(const String &p_type) const {
+ return p_type == "BitMap";
}
String ResourceFormatPBM::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="pbm")
+ if (p_path.get_extension().to_lower() == "pbm")
return "BitMap";
return "";
}
-
-
diff --git a/modules/pbm/bitmap_loader_pbm.h b/modules/pbm/bitmap_loader_pbm.h
index b60b38fcca..5e5062f435 100644
--- a/modules/pbm/bitmap_loader_pbm.h
+++ b/modules/pbm/bitmap_loader_pbm.h
@@ -36,15 +36,11 @@
*/
class ResourceFormatPBM : public ResourceFormatLoader {
-
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
};
-
-
#endif
diff --git a/modules/pbm/register_types.cpp b/modules/pbm/register_types.cpp
index 0dd39ce1e4..abfc08c909 100644
--- a/modules/pbm/register_types.cpp
+++ b/modules/pbm/register_types.cpp
@@ -30,15 +30,15 @@
#include "bitmap_loader_pbm.h"
-static ResourceFormatPBM * pbm_loader = NULL;
+static ResourceFormatPBM *pbm_loader = NULL;
void register_pbm_types() {
- pbm_loader = memnew( ResourceFormatPBM );
+ pbm_loader = memnew(ResourceFormatPBM);
ResourceLoader::add_resource_format_loader(pbm_loader);
}
void unregister_pbm_types() {
- memdelete( pbm_loader );
+ memdelete(pbm_loader);
}
diff --git a/modules/pvr/register_types.cpp b/modules/pvr/register_types.cpp
index 2464e78984..76fe7970d3 100644
--- a/modules/pvr/register_types.cpp
+++ b/modules/pvr/register_types.cpp
@@ -34,7 +34,7 @@ static ResourceFormatPVR *resource_loader_pvr = NULL;
void register_pvr_types() {
- resource_loader_pvr = memnew( ResourceFormatPVR );
+ resource_loader_pvr = memnew(ResourceFormatPVR);
ResourceLoader::add_resource_format_loader(resource_loader_pvr);
}
diff --git a/modules/pvr/texture_loader_pvr.cpp b/modules/pvr/texture_loader_pvr.cpp
index 9805675f2c..0409998408 100644
--- a/modules/pvr/texture_loader_pvr.cpp
+++ b/modules/pvr/texture_loader_pvr.cpp
@@ -27,49 +27,47 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture_loader_pvr.h"
-#include "os/file_access.h"
-#include <string.h>
#include "PvrTcEncoder.h"
#include "RgbaBitmap.h"
+#include "os/file_access.h"
+#include <string.h>
-static void _pvrtc_decompress(Image* p_img);
+static void _pvrtc_decompress(Image *p_img);
enum PVRFLags {
- PVR_HAS_MIPMAPS=0x00000100,
- PVR_TWIDDLED=0x00000200,
- PVR_NORMAL_MAP=0x00000400,
- PVR_BORDER=0x00000800,
- PVR_CUBE_MAP=0x00001000,
- PVR_FALSE_MIPMAPS=0x00002000,
- PVR_VOLUME_TEXTURES=0x00004000,
- PVR_HAS_ALPHA=0x00008000,
- PVR_VFLIP=0x00010000
+ PVR_HAS_MIPMAPS = 0x00000100,
+ PVR_TWIDDLED = 0x00000200,
+ PVR_NORMAL_MAP = 0x00000400,
+ PVR_BORDER = 0x00000800,
+ PVR_CUBE_MAP = 0x00001000,
+ PVR_FALSE_MIPMAPS = 0x00002000,
+ 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) {
+RES ResourceFormatPVR::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
if (!f)
return RES();
FileAccessRef faref(f);
- ERR_FAIL_COND_V(err,RES());
+ ERR_FAIL_COND_V(err, RES());
if (r_error)
- *r_error=ERR_FILE_CORRUPT;
+ *r_error = ERR_FILE_CORRUPT;
uint32_t hsize = f->get_32();
- ERR_FAIL_COND_V(hsize!=52,RES());
+ ERR_FAIL_COND_V(hsize != 52, RES());
uint32_t height = f->get_32();
uint32_t width = f->get_32();
uint32_t mipmaps = f->get_32();
@@ -80,12 +78,12 @@ RES ResourceFormatPVR::load(const String &p_path,const String& p_original_path,E
uint32_t gmask = f->get_32();
uint32_t bmask = f->get_32();
uint32_t amask = f->get_32();
- uint8_t pvrid[5]={0,0,0,0,0};
- f->get_buffer(pvrid,4);
- ERR_FAIL_COND_V(String((char*)pvrid)!="PVR!",RES());
+ uint8_t pvrid[5] = { 0, 0, 0, 0, 0 };
+ f->get_buffer(pvrid, 4);
+ ERR_FAIL_COND_V(String((char *)pvrid) != "PVR!", RES());
uint32_t surfcount = f->get_32();
-/*
+ /*
print_line("height: "+itos(height));
print_line("width: "+itos(width));
print_line("mipmaps: "+itos(mipmaps));
@@ -102,149 +100,144 @@ RES ResourceFormatPVR::load(const String &p_path,const String& p_original_path,E
PoolVector<uint8_t> data;
data.resize(surfsize);
- ERR_FAIL_COND_V(data.size()==0,RES());
-
+ ERR_FAIL_COND_V(data.size() == 0, RES());
PoolVector<uint8_t>::Write w = data.write();
- f->get_buffer(&w[0],surfsize);
+ f->get_buffer(&w[0], surfsize);
err = f->get_error();
- ERR_FAIL_COND_V(err!=OK,RES());
+ ERR_FAIL_COND_V(err != OK, RES());
- Image::Format format=Image::FORMAT_MAX;
+ Image::Format format = Image::FORMAT_MAX;
-
- switch(flags&0xFF) {
+ 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_PVRTC2A : Image::FORMAT_PVRTC2; 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_PVRTC4A : Image::FORMAT_PVRTC4; break;
case 0x16:
- format=Image::FORMAT_L8; break;
+ format = Image::FORMAT_L8;
+ break;
case 0x17:
- format=Image::FORMAT_LA8; break;
+ format = Image::FORMAT_LA8;
+ break;
case 0x20:
case 0x80:
case 0x81:
- format=Image::FORMAT_DXT1; break;
+ format = Image::FORMAT_DXT1;
+ break;
case 0x21:
case 0x22:
case 0x82:
case 0x83:
- format=Image::FORMAT_DXT3; break;
+ format = Image::FORMAT_DXT3;
+ break;
case 0x23:
case 0x24:
case 0x84:
case 0x85:
- format=Image::FORMAT_DXT5; break;
+ format = Image::FORMAT_DXT5;
+ break;
case 0x4:
case 0x15:
- format=Image::FORMAT_RGB8; break;
+ format = Image::FORMAT_RGB8;
+ break;
case 0x5:
case 0x12:
- format=Image::FORMAT_RGBA8; break;
+ format = Image::FORMAT_RGBA8;
+ break;
case 0x36:
- format=Image::FORMAT_ETC; break;
+ format = Image::FORMAT_ETC;
+ break;
default:
- ERR_EXPLAIN("Unsupported format in PVR texture: "+itos(flags&0xFF));
+ ERR_EXPLAIN("Unsupported format in PVR texture: " + itos(flags & 0xFF));
ERR_FAIL_V(RES());
-
}
w = PoolVector<uint8_t>::Write();
- int tex_flags=Texture::FLAG_FILTER|Texture::FLAG_REPEAT;
+ int tex_flags = Texture::FLAG_FILTER | Texture::FLAG_REPEAT;
if (mipmaps)
- tex_flags|=Texture::FLAG_MIPMAPS;
+ tex_flags |= Texture::FLAG_MIPMAPS;
+ print_line("flip: " + itos(flags & PVR_VFLIP));
- print_line("flip: "+itos(flags&PVR_VFLIP));
+ Image image(width, height, mipmaps, format, data);
+ ERR_FAIL_COND_V(image.empty(), RES());
- Image image(width,height,mipmaps,format,data);
- ERR_FAIL_COND_V(image.empty(),RES());
-
- Ref<ImageTexture> texture = memnew( ImageTexture );
- texture->create_from_image(image,tex_flags);
+ Ref<ImageTexture> texture = memnew(ImageTexture);
+ texture->create_from_image(image, tex_flags);
if (r_error)
- *r_error=OK;
+ *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,"Texture");
+ return ClassDB::is_parent_class(p_type, "Texture");
}
String ResourceFormatPVR::get_resource_type(const String &p_path) const {
-
- if (p_path.get_extension().to_lower()=="pvr")
+ if (p_path.get_extension().to_lower() == "pvr")
return "Texture";
return "";
}
-
-
-static void _compress_pvrtc4(Image * p_img) {
+static void _compress_pvrtc4(Image *p_img) {
Image img = *p_img;
- bool make_mipmaps=false;
- if (img.get_width()%8 || img.get_height()%8) {
- make_mipmaps=img.has_mipmaps();
- img.resize(img.get_width()+(8-(img.get_width()%8)),img.get_height()+(8-(img.get_height()%8)));
+ bool make_mipmaps = false;
+ if (img.get_width() % 8 || img.get_height() % 8) {
+ make_mipmaps = img.has_mipmaps();
+ img.resize(img.get_width() + (8 - (img.get_width() % 8)), img.get_height() + (8 - (img.get_height() % 8)));
}
img.convert(Image::FORMAT_RGBA8);
if (!img.has_mipmaps() && make_mipmaps)
img.generate_mipmaps();
- bool use_alpha=img.detect_alpha();
+ bool use_alpha = img.detect_alpha();
Image new_img;
- new_img.create(img.get_width(),img.get_height(),true,use_alpha?Image::FORMAT_PVRTC4A:Image::FORMAT_PVRTC4);
- PoolVector<uint8_t> data=new_img.get_data();
+ new_img.create(img.get_width(), img.get_height(), true, use_alpha ? Image::FORMAT_PVRTC4A : Image::FORMAT_PVRTC4);
+ PoolVector<uint8_t> data = new_img.get_data();
{
- PoolVector<uint8_t>::Write wr=data.write();
- PoolVector<uint8_t>::Read r=img.get_data().read();
+ PoolVector<uint8_t>::Write wr = data.write();
+ PoolVector<uint8_t>::Read r = img.get_data().read();
+ for (int i = 0; i <= new_img.get_mipmap_count(); i++) {
- 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);
- copymem(bm.GetData(),&r[ofs],size);
+ int ofs, size, w, h;
+ img.get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
+ Javelin::RgbaBitmap bm(w, h);
+ copymem(bm.GetData(), &r[ofs], size);
{
Javelin::ColorRgba<unsigned char> *dp = bm.GetData();
- for(int j=0;j<size/4;j++) {
- SWAP(dp[j].r,dp[j].b);
+ for (int j = 0; j < size / 4; j++) {
+ 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);
+ new_img.get_mipmap_offset_size_and_dimensions(i, ofs, size, w, h);
+ Javelin::PvrTcEncoder::EncodeRgba4Bpp(&wr[ofs], bm);
}
-
}
- *p_img = Image(new_img.get_width(),new_img.get_height(),new_img.has_mipmaps(),new_img.get_format(),data);
-
+ *p_img = Image(new_img.get_width(), new_img.get_height(), new_img.has_mipmaps(), new_img.get_format(), data);
}
ResourceFormatPVR::ResourceFormatPVR() {
-
- Image::_image_decompress_pvrtc=_pvrtc_decompress;
- Image::_image_compress_pvrtc4_func=_compress_pvrtc4;
- Image::_image_compress_pvrtc2_func=_compress_pvrtc4;
-
+ Image::_image_decompress_pvrtc = _pvrtc_decompress;
+ Image::_image_compress_pvrtc4_func = _compress_pvrtc4;
+ Image::_image_compress_pvrtc2_func = _compress_pvrtc4;
}
/////////////////////////////////////////////////////////
@@ -253,7 +246,6 @@ ResourceFormatPVR::ResourceFormatPVR() {
/////////////////////////////////////////////////////////
-
#define PT_INDEX 2
#define BLK_Y_SIZE 4
#define BLK_X_MAX 8
@@ -267,52 +259,48 @@ ResourceFormatPVR::ResourceFormatPVR() {
legal coordinate range
*/
#define LIMIT_COORD(Val, Size, p_tiled) \
- ((p_tiled)? WRAP_COORD((Val), (Size)): CLAMP((Val), 0, (Size)-1))
-
+ ((p_tiled) ? WRAP_COORD((Val), (Size)) : CLAMP((Val), 0, (Size)-1))
struct PVRTCBlock {
//blocks are 64 bits
uint32_t data[2];
};
+_FORCE_INLINE_ bool is_po2(uint32_t p_input) {
-
-_FORCE_INLINE_ bool is_po2( uint32_t p_input ) {
-
- if( p_input==0 )
- return 0;
- uint32_t minus1=p_input- 1;
- return ((p_input|minus1)==(p_input^minus1))?1:0;
+ if (p_input == 0)
+ return 0;
+ uint32_t minus1 = p_input - 1;
+ return ((p_input | minus1) == (p_input ^ minus1)) ? 1 : 0;
}
-
-static void unpack_5554(const PVRTCBlock *p_block, int p_ab_colors[2][4]) {
+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++) {
+ for (int i = 0; i < 2; i++) {
- if(raw_bits[i] & (1<<15)) {
+ 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)
- p_ab_colors[0][2]|= p_ab_colors[0][2] >> 4;
+ 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)
+ 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;
+ p_ab_colors[i][0] = (raw_bits[i] >> (8 - 1)) & 0x1E;
+ p_ab_colors[i][1] = (raw_bits[i] >> (4 - 1)) & 0x1E;
p_ab_colors[i][0] |= p_ab_colors[i][0] >> 4;
p_ab_colors[i][1] |= p_ab_colors[i][1] >> 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
p_ab_colors[0][2] |= p_ab_colors[0][2] >> 4;
@@ -322,55 +310,52 @@ 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) {
+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) {
+ if (p_2bit && block_mod_mode) {
- for(int y = 0; y < BLK_Y_SIZE; y++) {
- for(int x = 0; x < BLK_X_2BPP; x++) {
+ 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;
+ p_modulation_modes[y + p_y][x + p_x] = block_mod_mode;
- if(((x^y)&1) == 0) {
- p_modulation[y+p_y][x+p_x] = modulation_bits & 3;
+ if (((x ^ y) & 1) == 0) {
+ p_modulation[y + p_y][x + p_x] = modulation_bits & 3;
modulation_bits >>= 2;
}
}
}
- } else if(p_2bit) {
+ } 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;
+ 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)
- p_modulation[y+p_y][x+p_x] = 0x3;
+ if (modulation_bits & 1)
+ p_modulation[y + p_y][x + p_x] = 0x3;
else
- p_modulation[y+p_y][x+p_x] = 0x0;
+ p_modulation[y + p_y][x + p_x] = 0x0;
modulation_bits >>= 1;
}
}
- } else {
- for(int y = 0; y < BLK_Y_SIZE; y++) {
- for(int x = 0; x < BLK_X_4BPP; x++) {
- p_modulation_modes[y+p_y][x+p_x] = block_mod_mode;
- p_modulation[y+p_y][x+p_x] = modulation_bits & 3;
+ } else {
+ for (int y = 0; y < BLK_Y_SIZE; y++) {
+ for (int x = 0; x < BLK_X_4BPP; x++) {
+ p_modulation_modes[y + p_y][x + p_x] = block_mod_mode;
+ p_modulation[y + p_y][x + p_x] = modulation_bits & 3;
modulation_bits >>= 2;
}
}
}
- ERR_FAIL_COND(modulation_bits!=0);
+ ERR_FAIL_COND(modulation_bits != 0);
}
-
-
static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], const int p_colorr[4], const int p_colors[4], bool p_2bit, const int x, const int y, int r_result[4]) {
int u, v, uscale;
int k;
@@ -379,7 +364,7 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con
int P[4], Q[4], R[4], S[4];
- for(k = 0; k < 4; k++) {
+ for (k = 0; k < 4; k++) {
P[k] = p_colorp[k];
Q[k] = p_colorq[k];
R[k] = p_colorr[k];
@@ -388,22 +373,22 @@ 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
u = (x & 0x3) | ((~x & 0x2) << 1);
- v = v - BLK_Y_SIZE/2;
+ v = v - BLK_Y_SIZE / 2;
- if(p_2bit) {
- u = u - BLK_X_2BPP/2;
+ if (p_2bit) {
+ u = u - BLK_X_2BPP / 2;
uscale = 8;
} else {
- u = u - BLK_X_4BPP/2;
+ u = u - BLK_X_4BPP / 2;
uscale = 4;
}
- for(k = 0; k < 4; k++) {
+ for (k = 0; k < 4; k++) {
tmp1 = P[k] * uscale + u * (Q[k] - P[k]);
tmp2 = R[k] * uscale + u * (S[k] - R[k]);
@@ -412,82 +397,77 @@ static void interpolate_colors(const int p_colorp[4], const int p_colorq[4], con
r_result[k] = tmp1;
}
- if(p_2bit) {
- for(k = 0; k < 3; k++) {
+ if (p_2bit) {
+ for (k = 0; k < 3; k++) {
r_result[k] >>= 2;
}
r_result[3] >>= 1;
} else {
- for(k = 0; k < 3; k++) {
+ for (k = 0; k < 3; k++) {
r_result[k] >>= 1;
}
}
- for(k = 0; k < 4; k++) {
+ for (k = 0; k < 4; k++) {
ERR_FAIL_COND(r_result[k] >= 256);
}
-
- for(k = 0; k < 3; k++) {
+ for (k = 0; k < 3; k++) {
r_result[k] += r_result[k] >> 5;
}
r_result[3] += r_result[3] >> 4;
- for(k = 0; k < 4; k++) {
+ for (k = 0; k < 4; k++) {
ERR_FAIL_COND(r_result[k] >= 256);
}
-
}
-
-static void get_modulation_value(int x, int y, const int p_2bit, const int p_modulation[8][16], const int p_modulation_modes[8][16], int *r_mod, int *p_dopt)
-{
- static const int rep_vals0[4] = {0, 3, 5, 8};
- static const int rep_vals1[4] = {0, 4, 4, 8};
+static void get_modulation_value(int x, int y, const int p_2bit, const int p_modulation[8][16], const int p_modulation_modes[8][16], int *r_mod, int *p_dopt) {
+ static const int rep_vals0[4] = { 0, 3, 5, 8 };
+ static const int rep_vals1[4] = { 0, 4, 4, 8 };
int mod_val;
y = (y & 0x3) | ((~y & 0x2) << 1);
- if(p_2bit)
+ if (p_2bit)
x = (x & 0x7) | ((~x & 0x4) << 1);
else
x = (x & 0x3) | ((~x & 0x2) << 1);
*p_dopt = 0;
- if(p_modulation_modes[y][x]==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)
+ } else if (p_2bit) {
+ if (((x ^ y) & 1) == 0)
mod_val = rep_vals0[p_modulation[y][x]];
- 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]] +
- rep_vals0[p_modulation[y][x+1]] + 2) / 4;
- } else if(p_modulation_modes[y][x] == 2) {
- mod_val = (
- rep_vals0[p_modulation[y][x-1]] +
- rep_vals0[p_modulation[y][x+1]] + 1) / 2;
+ 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]] +
+ rep_vals0[p_modulation[y][x + 1]] + 2) /
+ 4;
+ } else if (p_modulation_modes[y][x] == 2) {
+ mod_val = (rep_vals0[p_modulation[y][x - 1]] +
+ rep_vals0[p_modulation[y][x + 1]] + 1) /
+ 2;
} else {
- mod_val = (
- rep_vals0[p_modulation[y-1][x]] +
- rep_vals0[p_modulation[y+1][x]] + 1) / 2;
+ mod_val = (rep_vals0[p_modulation[y - 1][x]] +
+ rep_vals0[p_modulation[y + 1][x]] + 1) /
+ 2;
}
- } else {
+ } else {
mod_val = rep_vals1[p_modulation[y][x]];
*p_dopt = p_modulation[y][x] == PT_INDEX;
}
- *r_mod =mod_val;
+ *r_mod = mod_val;
}
-
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) {
@@ -502,51 +482,50 @@ static uint32_t twiddle_uv(uint32_t p_height, uint32_t p_width, uint32_t p_y, ui
int shift_count;
- ERR_FAIL_COND_V(p_y >= p_height,0);
- ERR_FAIL_COND_V(p_x >= p_width,0);
+ ERR_FAIL_COND_V(p_y >= p_height, 0);
+ ERR_FAIL_COND_V(p_x >= p_width, 0);
- ERR_FAIL_COND_V(!is_po2(p_height),0);
- ERR_FAIL_COND_V(!is_po2(p_width),0);
+ ERR_FAIL_COND_V(!is_po2(p_height), 0);
+ ERR_FAIL_COND_V(!is_po2(p_width), 0);
- if(p_height < p_width) {
+ if (p_height < p_width) {
min_dimension = p_height;
- max_value = p_x;
+ max_value = p_x;
} else {
min_dimension = p_width;
- max_value = p_y;
+ max_value = p_y;
}
- if(disable_twiddling)
- return (p_y* p_width + p_x);
+ if (disable_twiddling)
+ return (p_y * p_width + p_x);
scr_bit_pos = 1;
dst_bit_pos = 1;
- twiddled = 0;
+ twiddled = 0;
shift_count = 0;
- while(scr_bit_pos < min_dimension) {
- if(p_y & scr_bit_pos) {
+ while (scr_bit_pos < min_dimension) {
+ if (p_y & scr_bit_pos) {
twiddled |= dst_bit_pos;
}
- if(p_x & scr_bit_pos) {
+ if (p_x & scr_bit_pos) {
twiddled |= (dst_bit_pos << 1);
}
scr_bit_pos <<= 1;
dst_bit_pos <<= 2;
shift_count += 1;
-
}
max_value >>= shift_count;
- twiddled |= (max_value << (2*shift_count));
+ twiddled |= (max_value << (2 * shift_count));
return twiddled;
}
-static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_width, const int p_height, const int p_tiled, unsigned char* p_dst) {
+static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int p_width, const int p_height, const int p_tiled, unsigned char *p_dst) {
int x, y;
int i, j;
@@ -567,55 +546,50 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
// local neighbourhood of blocks
PVRTCBlock *p_blocks[2][2];
- PVRTCBlock *prev[2][2] = {{NULL, NULL}, {NULL, NULL}};
+ PVRTCBlock *prev[2][2] = { { NULL, NULL }, { NULL, NULL } };
struct
{
int Reps[2][4];
- }colors5554[2][2];
-
+ } colors5554[2][2];
int ASig[4], BSig[4];
int r_result[4];
- if(p_2bit)
+ if (p_2bit)
x_block_size = BLK_X_2BPP;
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++)
- {
+ 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);
+ block_x = (x - x_block_size / 2);
+ blk_y = (y - BLK_Y_SIZE / 2);
block_x = LIMIT_COORD(block_x, p_width, p_tiled);
blk_y = LIMIT_COORD(blk_y, p_height, p_tiled);
-
block_x /= x_block_size;
blk_y /= BLK_Y_SIZE;
- block_xp1 = LIMIT_COORD(block_x+1, block_width, p_tiled);
- blk_yp1 = LIMIT_COORD(blk_y+1, block_height, p_tiled);
+ block_xp1 = LIMIT_COORD(block_x + 1, block_width, p_tiled);
+ blk_yp1 = LIMIT_COORD(blk_y + 1, block_height, p_tiled);
- p_blocks[0][0] = p_comp_img +twiddle_uv(block_height, block_width, blk_y, block_x);
- p_blocks[0][1] = p_comp_img +twiddle_uv(block_height, block_width, blk_y, block_xp1);
- p_blocks[1][0] = p_comp_img +twiddle_uv(block_height, block_width, blk_yp1, block_x);
- p_blocks[1][1] = p_comp_img +twiddle_uv(block_height, block_width, blk_yp1, block_xp1);
+ p_blocks[0][0] = p_comp_img + twiddle_uv(block_height, block_width, blk_y, block_x);
+ p_blocks[0][1] = p_comp_img + twiddle_uv(block_height, block_width, blk_y, block_xp1);
+ p_blocks[1][0] = p_comp_img + twiddle_uv(block_height, block_width, blk_yp1, block_x);
+ p_blocks[1][1] = p_comp_img + twiddle_uv(block_height, block_width, blk_yp1, block_xp1);
- if(memcmp(prev, p_blocks, 4*sizeof(void*)) != 0) {
+ if (memcmp(prev, p_blocks, 4 * sizeof(void *)) != 0) {
p_y = 0;
- for(i = 0; i < 2; i++) {
+ for (i = 0; i < 2; i++) {
p_x = 0;
- for(j = 0; j < 2; j++) {
+ for (j = 0; j < 2; j++) {
unpack_5554(p_blocks[i][j], colors5554[i][j].Reps);
unpack_modulations(
@@ -631,11 +605,9 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
p_y += BLK_Y_SIZE;
}
-
- memcpy(prev, p_blocks, 4*sizeof(void*));
+ memcpy(prev, p_blocks, 4 * sizeof(void *));
}
-
interpolate_colors(
colors5554[0][0].Reps[0],
colors5554[0][1].Reps[0],
@@ -652,28 +624,27 @@ static void decompress_pvrtc(PVRTCBlock *p_comp_img, const int p_2bit, const int
p_2bit, x, y,
BSig);
- get_modulation_value(x,y, p_2bit, (const int (*)[16])p_modulation, (const int (*)[16])p_modulation_modes,
- &Mod, &DoPT);
+ get_modulation_value(x, y, p_2bit, (const int(*)[16])p_modulation, (const int(*)[16])p_modulation_modes,
+ &Mod, &DoPT);
- for(i = 0; i < 4; i++) {
+ for (i = 0; i < 4; i++) {
r_result[i] = ASig[i] * 8 + Mod * (BSig[i] - ASig[i]);
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];
- p_dst[u_pos+1] = (uint8_t)r_result[1];
- p_dst[u_pos+2] = (uint8_t)r_result[2];
- p_dst[u_pos+3] = (uint8_t)r_result[3];
+ u_pos = (x + y * p_width) << 2;
+ p_dst[u_pos + 0] = (uint8_t)r_result[0];
+ p_dst[u_pos + 1] = (uint8_t)r_result[1];
+ p_dst[u_pos + 2] = (uint8_t)r_result[2];
+ p_dst[u_pos + 3] = (uint8_t)r_result[3];
}
}
}
-static void _pvrtc_decompress(Image* p_img) {
+static void _pvrtc_decompress(Image *p_img) {
/*
static void decompress_pvrtc(const void *p_comp_img, const int p_2bit, const int p_width, const int p_height, unsigned char* p_dst) {
@@ -681,19 +652,18 @@ static void _pvrtc_decompress(Image* p_img) {
}
*/
- 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);
+ 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_PVRTC2 || p_img->get_format() == Image::FORMAT_PVRTC2A);
PoolVector<uint8_t> data = p_img->get_data();
PoolVector<uint8_t>::Read r = data.read();
-
PoolVector<uint8_t> newdata;
- newdata.resize( p_img->get_width() * p_img->get_height() * 4);
- PoolVector<uint8_t>::Write w=newdata.write();
+ newdata.resize(p_img->get_width() * p_img->get_height() * 4);
+ PoolVector<uint8_t>::Write w = newdata.write();
- decompress_pvrtc((PVRTCBlock*)r.ptr(),_2bit,p_img->get_width(),p_img->get_height(),0,(unsigned char*)w.ptr());
+ decompress_pvrtc((PVRTCBlock *)r.ptr(), _2bit, p_img->get_width(), p_img->get_height(), 0, (unsigned char *)w.ptr());
/*
for(int i=0;i<newdata.size();i++) {
@@ -701,21 +671,12 @@ static void _pvrtc_decompress(Image* p_img) {
}
*/
- w=PoolVector<uint8_t>::Write();
- r=PoolVector<uint8_t>::Read();
+ w = PoolVector<uint8_t>::Write();
+ r = PoolVector<uint8_t>::Read();
- bool make_mipmaps=p_img->has_mipmaps();
- Image newimg(p_img->get_width(),p_img->get_height(),false,Image::FORMAT_RGBA8,newdata);
+ bool make_mipmaps = p_img->has_mipmaps();
+ Image newimg(p_img->get_width(), p_img->get_height(), false, Image::FORMAT_RGBA8, newdata);
if (make_mipmaps)
newimg.generate_mipmaps();
- *p_img=newimg;
-
+ *p_img = newimg;
}
-
-
-
-
-
-
-
-
diff --git a/modules/pvr/texture_loader_pvr.h b/modules/pvr/texture_loader_pvr.h
index bad48b4569..768070ee61 100644
--- a/modules/pvr/texture_loader_pvr.h
+++ b/modules/pvr/texture_loader_pvr.h
@@ -29,22 +29,18 @@
#ifndef TEXTURE_LOADER_PVR_H
#define TEXTURE_LOADER_PVR_H
-
-#include "scene/resources/texture.h"
#include "io/resource_loader.h"
+#include "scene/resources/texture.h"
-
-class ResourceFormatPVR : public ResourceFormatLoader{
+class ResourceFormatPVR : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path,Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path, Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
ResourceFormatPVR();
virtual ~ResourceFormatPVR() {}
};
-
#endif // TEXTURE_LOADER_PVR_H
diff --git a/modules/regex/regex.cpp b/modules/regex/regex.cpp
index 3d1dd048a8..e8fed382b5 100644
--- a/modules/regex/regex.cpp
+++ b/modules/regex/regex.cpp
@@ -28,11 +28,10 @@
/*************************************************************************/
#include "regex.h"
-#include <wctype.h>
#include <wchar.h>
+#include <wctype.h>
-static int RegEx_hex2int(const CharType c)
-{
+static int RegEx_hex2int(const CharType c) {
if ('0' <= c && c <= '9')
return int(c - '0');
else if ('a' <= c && c <= 'f')
@@ -45,7 +44,7 @@ static int RegEx_hex2int(const CharType c)
struct RegExSearch {
Ref<RegExMatch> match;
- const CharType* str;
+ const CharType *str;
int end;
int eof;
@@ -63,7 +62,8 @@ struct RegExSearch {
return str[p_pos];
}
- RegExSearch(Ref<RegExMatch>& p_match, int p_end, int p_lookahead) : match(p_match) {
+ RegExSearch(Ref<RegExMatch> &p_match, int p_end, int p_lookahead)
+ : match(p_match) {
str = p_match->string.c_str();
end = p_end;
@@ -71,14 +71,13 @@ struct RegExSearch {
complete = false;
lookahead_pos.resize(p_lookahead);
}
-
};
struct RegExNode {
- RegExNode* next;
- RegExNode* previous;
- RegExNode* parent;
+ RegExNode *next;
+ RegExNode *previous;
+ RegExNode *parent;
bool quantifiable;
int length;
@@ -100,12 +99,12 @@ struct RegExNode {
// For avoiding RTTI
virtual bool is_look_behind() { return false; }
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
return next ? next->test(s, pos) : -1;
}
- virtual int test_parent(RegExSearch& s, int pos) const {
+ virtual int test_parent(RegExSearch &s, int pos) const {
if (next)
pos = next->test(s, pos);
@@ -135,9 +134,7 @@ struct RegExNode {
if (parent)
parent->increment_length(amount, subtract);
-
}
-
};
struct RegExNodeChar : public RegExNode {
@@ -151,7 +148,7 @@ struct RegExNodeChar : public RegExNode {
ch = p_char;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (s.end <= pos || 0 > pos || s.at(pos) != ch)
return -1;
@@ -159,7 +156,7 @@ struct RegExNodeChar : public RegExNode {
return next ? next->test(s, pos + 1) : pos + 1;
}
- static CharType parse_escape(const CharType*& c) {
+ static CharType parse_escape(const CharType *&c) {
int point = 0;
switch (c[1]) {
@@ -209,7 +206,7 @@ struct RegExNodeRange : public RegExNode {
end = p_end;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (s.end <= pos || 0 > pos)
return -1;
@@ -233,7 +230,7 @@ struct RegExNodeShorthand : public RegExNode {
repr = p_repr;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (s.end <= pos || 0 > pos)
return -1;
@@ -351,7 +348,7 @@ struct RegExNodeClass : public RegExNode {
type = p_type;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (s.end <= pos || 0 > pos)
return -1;
@@ -362,9 +359,10 @@ struct RegExNodeClass : public RegExNode {
return next ? next->test(s, pos + 1) : pos + 1;
}
-#define REGEX_CMP_CLASS(POS, NAME) if (cmp_class(POS, #NAME)) return Type_ ## NAME
+#define REGEX_CMP_CLASS(POS, NAME) \
+ if (cmp_class(POS, #NAME)) return Type_##NAME
- static Type parse_type(const CharType*& p_pos) {
+ static Type parse_type(const CharType *&p_pos) {
REGEX_CMP_CLASS(p_pos, alnum);
REGEX_CMP_CLASS(p_pos, alpha);
@@ -383,7 +381,7 @@ struct RegExNodeClass : public RegExNode {
return Type_none;
}
- static bool cmp_class(const CharType*& p_pos, const char* p_text) {
+ static bool cmp_class(const CharType *&p_pos, const char *p_text) {
unsigned int i = 0;
for (i = 0; p_text[i] != '\0'; ++i)
@@ -405,7 +403,7 @@ struct RegExNodeAnchorStart : public RegExNode {
length = 0;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (pos != 0)
return -1;
@@ -421,7 +419,7 @@ struct RegExNodeAnchorEnd : public RegExNode {
length = 0;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (pos != s.eof)
return -1;
@@ -440,7 +438,7 @@ struct RegExNodeWordBoundary : public RegExNode {
inverse = p_inverse;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
bool left = false;
bool right = false;
@@ -469,7 +467,7 @@ struct RegExNodeQuantifier : public RegExNode {
int min;
int max;
bool greedy;
- RegExNode* child;
+ RegExNode *child;
RegExNodeQuantifier(int p_min, int p_max) {
@@ -485,18 +483,18 @@ struct RegExNodeQuantifier : public RegExNode {
memdelete(child);
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
return test_step(s, pos, 0, pos);
}
- virtual int test_parent(RegExSearch& s, int pos) const {
+ virtual int test_parent(RegExSearch &s, int pos) const {
s.complete = false;
return pos;
}
- int test_step(RegExSearch& s, int pos, int level, int start) const {
+ int test_step(RegExSearch &s, int pos, int level, int start) const {
if (pos > s.end)
return -1;
@@ -554,9 +552,9 @@ struct RegExNodeBackReference : public RegExNode {
id = p_id;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
- RegExMatch::Group& ref = s.match->captures[id];
+ RegExMatch::Group &ref = s.match->captures[id];
for (int i = 0; i < ref.length; ++i) {
if (pos + i >= s.end)
@@ -569,13 +567,12 @@ struct RegExNodeBackReference : public RegExNode {
}
};
-
struct RegExNodeGroup : public RegExNode {
bool inverse;
bool reset_pos;
- Vector<RegExNode*> childset;
- RegExNode* back;
+ Vector<RegExNode *> childset;
+ RegExNode *back;
RegExNodeGroup() {
@@ -592,7 +589,7 @@ struct RegExNodeGroup : public RegExNode {
memdelete(childset[i]);
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
for (int i = 0; i < childset.size(); ++i) {
@@ -622,7 +619,7 @@ struct RegExNodeGroup : public RegExNode {
return -1;
}
- void add_child(RegExNode* node) {
+ void add_child(RegExNode *node) {
node->parent = this;
node->previous = back;
@@ -644,9 +641,9 @@ struct RegExNodeGroup : public RegExNode {
back = NULL;
}
- RegExNode* swap_back(RegExNode* node) {
+ RegExNode *swap_back(RegExNode *node) {
- RegExNode* old = back;
+ RegExNode *old = back;
if (old) {
if (!old->previous)
@@ -670,9 +667,9 @@ struct RegExNodeCapturing : public RegExNodeGroup {
id = p_id;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
- RegExMatch::Group& ref = s.match->captures[id];
+ RegExMatch::Group &ref = s.match->captures[id];
int old_start = ref.start;
ref.start = pos;
@@ -688,14 +685,14 @@ struct RegExNodeCapturing : public RegExNodeGroup {
return res;
}
- virtual int test_parent(RegExSearch& s, int pos) const {
+ virtual int test_parent(RegExSearch &s, int pos) const {
- RegExMatch::Group& ref = s.match->captures[id];
+ RegExMatch::Group &ref = s.match->captures[id];
ref.length = pos - ref.start;
return RegExNode::test_parent(s, pos);
}
- static Variant parse_name(const CharType*& c, bool p_allow_numeric) {
+ static Variant parse_name(const CharType *&c, bool p_allow_numeric) {
if (c[1] == '0') {
return -1;
@@ -732,13 +729,13 @@ struct RegExNodeLookAhead : public RegExNodeGroup {
id = p_id;
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
s.lookahead_pos[id] = pos;
return RegExNodeGroup::test(s, pos);
}
- virtual int test_parent(RegExSearch& s, int pos) const {
+ virtual int test_parent(RegExSearch &s, int pos) const {
return RegExNode::test_parent(s, s.lookahead_pos[id]);
}
@@ -755,7 +752,7 @@ struct RegExNodeLookBehind : public RegExNodeGroup {
virtual bool is_look_behind() { return true; }
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
if (pos < length)
return -1;
@@ -766,7 +763,7 @@ struct RegExNodeLookBehind : public RegExNodeGroup {
struct RegExNodeBracket : public RegExNode {
bool inverse;
- Vector<RegExNode*> children;
+ Vector<RegExNode *> children;
RegExNodeBracket() {
@@ -781,7 +778,7 @@ struct RegExNodeBracket : public RegExNode {
memdelete(children[i]);
}
- virtual int test(RegExSearch& s, int pos) const {
+ virtual int test(RegExSearch &s, int pos) const {
for (int i = 0; i < children.size(); ++i) {
@@ -803,7 +800,7 @@ struct RegExNodeBracket : public RegExNode {
return -1;
}
- void add_child(RegExNode* node) {
+ void add_child(RegExNode *node) {
node->parent = this;
children.push_back(node);
@@ -816,16 +813,16 @@ struct RegExNodeBracket : public RegExNode {
}
};
-#define REGEX_EXPAND_FAIL(MSG)\
-{\
- ERR_PRINT(MSG);\
- return String();\
-}
+#define REGEX_EXPAND_FAIL(MSG) \
+ { \
+ ERR_PRINT(MSG); \
+ return String(); \
+ }
-String RegExMatch::expand(const String& p_template) const {
+String RegExMatch::expand(const String &p_template) const {
String res;
- for (const CharType* c = p_template.c_str(); *c != '\0'; ++c) {
+ for (const CharType *c = p_template.c_str(); *c != '\0'; ++c) {
if (c[0] == '\\') {
if (('1' <= c[1] && c[1] <= '9') || (c[1] == 'g' && c[2] == '{')) {
@@ -850,9 +847,9 @@ String RegExMatch::expand(const String& p_template) const {
res += get_string(ref);
- } else if (c[1] =='g' && c[2] == '<') {
+ } else if (c[1] == 'g' && c[2] == '<') {
- const CharType* d = &c[2];
+ const CharType *d = &c[2];
Variant name = RegExNodeCapturing::parse_name(d, true);
if (name == Variant(-1))
@@ -864,7 +861,7 @@ String RegExMatch::expand(const String& p_template) const {
} else {
- const CharType* d = c;
+ const CharType *d = c;
CharType ch = RegExNodeChar::parse_escape(d);
if (c == d)
REGEX_EXPAND_FAIL("invalid escape token");
@@ -891,7 +888,7 @@ Array RegExMatch::get_group_array() const {
Array res;
for (int i = 1; i < captures.size(); ++i) {
- const RegExMatch::Group& capture = captures[i];
+ const RegExMatch::Group &capture = captures[i];
if (capture.name.get_type() != Variant::INT)
continue;
@@ -916,7 +913,7 @@ Dictionary RegExMatch::get_name_dict() const {
Dictionary res;
for (int i = 1; i < captures.size(); ++i) {
- const RegExMatch::Group& capture = captures[i];
+ const RegExMatch::Group &capture = captures[i];
if (capture.name.get_type() != Variant::STRING)
continue;
@@ -928,11 +925,11 @@ Dictionary RegExMatch::get_name_dict() const {
return res;
}
-String RegExMatch::get_string(const Variant& p_name) const {
+String RegExMatch::get_string(const Variant &p_name) const {
for (int i = 0; i < captures.size(); ++i) {
- const RegExMatch::Group& capture = captures[i];
+ const RegExMatch::Group &capture = captures[i];
if (capture.name != p_name)
continue;
@@ -945,7 +942,7 @@ String RegExMatch::get_string(const Variant& p_name) const {
return String();
}
-int RegExMatch::get_start(const Variant& p_name) const {
+int RegExMatch::get_start(const Variant &p_name) const {
for (int i = 0; i < captures.size(); ++i)
if (captures[i].name == p_name)
@@ -953,7 +950,7 @@ int RegExMatch::get_start(const Variant& p_name) const {
return -1;
}
-int RegExMatch::get_end(const Variant& p_name) const {
+int RegExMatch::get_end(const Variant &p_name) const {
for (int i = 0; i < captures.size(); ++i)
if (captures[i].name == p_name)
@@ -962,7 +959,6 @@ int RegExMatch::get_end(const Variant& p_name) const {
}
RegExMatch::RegExMatch() {
-
}
static bool RegEx_is_shorthand(CharType ch) {
@@ -981,14 +977,14 @@ static bool RegEx_is_shorthand(CharType ch) {
return false;
}
-#define REGEX_COMPILE_FAIL(MSG)\
-{\
- ERR_PRINT(MSG);\
- clear();\
- return FAILED;\
-}
+#define REGEX_COMPILE_FAIL(MSG) \
+ { \
+ ERR_PRINT(MSG); \
+ clear(); \
+ return FAILED; \
+ }
-Error RegEx::compile(const String& p_pattern) {
+Error RegEx::compile(const String &p_pattern) {
ERR_FAIL_COND_V(p_pattern.length() == 0, FAILED);
@@ -998,21 +994,21 @@ Error RegEx::compile(const String& p_pattern) {
clear();
pattern = p_pattern;
group_names.push_back(0);
- RegExNodeGroup* root_group = memnew(RegExNodeCapturing(0));
+ RegExNodeGroup *root_group = memnew(RegExNodeCapturing(0));
root = root_group;
- Vector<RegExNodeGroup*> stack;
+ Vector<RegExNodeGroup *> stack;
stack.push_back(root_group);
int lookahead_level = 0;
int numeric_groups = 0;
const int numeric_max = 9;
- for (const CharType* c = p_pattern.c_str(); *c != '\0'; ++c) {
+ for (const CharType *c = p_pattern.c_str(); *c != '\0'; ++c) {
switch (c[0]) {
case '(':
if (c[1] == '?') {
- RegExNodeGroup* group = NULL;
+ RegExNodeGroup *group = NULL;
switch (c[2]) {
case ':':
c = &c[2];
@@ -1033,7 +1029,7 @@ Error RegEx::compile(const String& p_pattern) {
break;
case 'P':
if (c[3] == '<') {
- const CharType* d = &c[3];
+ const CharType *d = &c[3];
Variant name = RegExNodeCapturing::parse_name(d, false);
if (name == Variant(-1))
REGEX_COMPILE_FAIL("unrecognised character for group name");
@@ -1051,14 +1047,14 @@ Error RegEx::compile(const String& p_pattern) {
} else if (numeric_groups < numeric_max) {
- RegExNodeCapturing* group = memnew(RegExNodeCapturing(group_names.size()));
+ RegExNodeCapturing *group = memnew(RegExNodeCapturing(group_names.size()));
group_names.push_back(++numeric_groups);
stack[0]->add_child(group);
stack.insert(0, group);
} else {
- RegExNodeGroup* group = memnew(RegExNodeGroup());
+ RegExNodeGroup *group = memnew(RegExNodeGroup());
stack[0]->add_child(group);
stack.insert(0, group);
}
@@ -1105,10 +1101,10 @@ Error RegEx::compile(const String& p_pattern) {
}
stack[0]->add_child(memnew(RegExNodeBackReference(ref)));
+ }
+ if (c[1] == 'g' && c[2] == '<') {
- } if (c[1] =='g' && c[2] == '<') {
-
- const CharType* d = &c[2];
+ const CharType *d = &c[2];
Variant name = RegExNodeCapturing::parse_name(d, true);
if (name == Variant(-1))
@@ -1144,103 +1140,100 @@ Error RegEx::compile(const String& p_pattern) {
} else {
- const CharType* d = c;
+ const CharType *d = c;
CharType ch = RegExNodeChar::parse_escape(d);
if (c == d)
REGEX_COMPILE_FAIL("invalid escape token");
stack[0]->add_child(memnew(RegExNodeChar(ch)));
c = d;
-
}
break;
- case '[':
- {
- RegExNodeBracket* bracket = memnew(RegExNodeBracket());
- stack[0]->add_child(bracket);
- if (c[1] == '^') {
- bracket->inverse = true;
- ++c;
- }
- bool first_child = true;
- CharType previous_child;
- bool previous_child_single = false;
- while (true) {
- ++c;
- if (!first_child && c[0] == ']') {
+ case '[': {
+ RegExNodeBracket *bracket = memnew(RegExNodeBracket());
+ stack[0]->add_child(bracket);
+ if (c[1] == '^') {
+ bracket->inverse = true;
+ ++c;
+ }
+ bool first_child = true;
+ CharType previous_child;
+ bool previous_child_single = false;
+ while (true) {
+ ++c;
+ if (!first_child && c[0] == ']') {
- break;
+ break;
- } else if (c[0] == '\0') {
+ } else if (c[0] == '\0') {
- REGEX_COMPILE_FAIL("unclosed bracket expression '['");
+ REGEX_COMPILE_FAIL("unclosed bracket expression '['");
- } else if (c[0] == '\\') {
+ } else if (c[0] == '\\') {
- if (RegEx_is_shorthand(c[1])) {
- bracket->add_child(memnew(RegExNodeShorthand(*(++c))));
- } else {
- const CharType* d = c;
- CharType ch = RegExNodeChar::parse_escape(d);
- if (c == d)
- REGEX_COMPILE_FAIL("invalid escape token");
- bracket->add_child(memnew(RegExNodeChar(ch)));
- c = d;
- previous_child = ch;
- previous_child_single = true;
- }
-
- } else if (c[0] == ']' && c[1] == ':') {
-
- const CharType* d = &c[2];
- RegExNodeClass::Type type = RegExNodeClass::parse_type(d);
- if (type != RegExNodeClass::Type_none) {
+ if (RegEx_is_shorthand(c[1])) {
+ bracket->add_child(memnew(RegExNodeShorthand(*(++c))));
+ } else {
+ const CharType *d = c;
+ CharType ch = RegExNodeChar::parse_escape(d);
+ if (c == d)
+ REGEX_COMPILE_FAIL("invalid escape token");
+ bracket->add_child(memnew(RegExNodeChar(ch)));
+ c = d;
+ previous_child = ch;
+ previous_child_single = true;
+ }
- c = d;
- previous_child_single = false;
+ } else if (c[0] == ']' && c[1] == ':') {
- } else {
+ const CharType *d = &c[2];
+ RegExNodeClass::Type type = RegExNodeClass::parse_type(d);
+ if (type != RegExNodeClass::Type_none) {
- bracket->add_child(memnew(RegExNodeChar('[')));
- previous_child = '[';
- previous_child_single = true;
- }
- } else if (previous_child_single && c[0] == '-') {
+ c = d;
+ previous_child_single = false;
- if (c[1] != '\0' && c[1] != ']') {
+ } else {
- CharType next;
+ bracket->add_child(memnew(RegExNodeChar('[')));
+ previous_child = '[';
+ previous_child_single = true;
+ }
+ } else if (previous_child_single && c[0] == '-') {
- if (c[1] == '\\') {
- const CharType* d = ++c;
- next = RegExNodeChar::parse_escape(d);
- if (c == d)
- REGEX_COMPILE_FAIL("invalid escape token");
- } else {
- next = *(++c);
- }
+ if (c[1] != '\0' && c[1] != ']') {
- if (next < previous_child)
- REGEX_COMPILE_FAIL("text range out of order");
+ CharType next;
- bracket->pop_back();
- bracket->add_child(memnew(RegExNodeRange(previous_child, next)));
- previous_child_single = false;
+ if (c[1] == '\\') {
+ const CharType *d = ++c;
+ next = RegExNodeChar::parse_escape(d);
+ if (c == d)
+ REGEX_COMPILE_FAIL("invalid escape token");
} else {
-
- bracket->add_child(memnew(RegExNodeChar('-')));
- previous_child = '-';
- previous_child_single = true;
+ next = *(++c);
}
+
+ if (next < previous_child)
+ REGEX_COMPILE_FAIL("text range out of order");
+
+ bracket->pop_back();
+ bracket->add_child(memnew(RegExNodeRange(previous_child, next)));
+ previous_child_single = false;
} else {
- bracket->add_child(memnew(RegExNodeChar(c[0])));
- previous_child = c[0];
+ bracket->add_child(memnew(RegExNodeChar('-')));
+ previous_child = '-';
previous_child_single = true;
}
- first_child = false;
+ } else {
+
+ bracket->add_child(memnew(RegExNodeChar(c[0])));
+ previous_child = c[0];
+ previous_child_single = true;
}
+ first_child = false;
}
- break;
+ } break;
case '|':
for (int i = 0; i < stack.size(); ++i)
if (stack[i]->is_look_behind())
@@ -1259,82 +1252,81 @@ Error RegEx::compile(const String& p_pattern) {
case '?':
case '*':
case '+':
- case '{':
- {
- int min_val = 0;
- int max_val = -1;
- bool valid = true;
- const CharType* d = c;
- bool max_set = true;
- switch (c[0]) {
- case '?':
- min_val = 0;
- max_val = 1;
- break;
- case '*':
- min_val = 0;
- max_val = -1;
- break;
- case '+':
- min_val = 1;
- max_val = -1;
- break;
- case '{':
- max_set = false;
- while (valid) {
- ++d;
- if (d[0] == '}') {
- break;
- } else if (d[0] == ',') {
- max_set = true;
- } else if ('0' <= d[0] && d[0] <= '9') {
- if (max_set) {
- if (max_val < 0)
- max_val = int(d[0] - '0');
- else
- max_val = max_val * 10 + int(d[0] - '0');
- } else {
- min_val = min_val * 10 + int(d[0] - '0');
- }
+ case '{': {
+ int min_val = 0;
+ int max_val = -1;
+ bool valid = true;
+ const CharType *d = c;
+ bool max_set = true;
+ switch (c[0]) {
+ case '?':
+ min_val = 0;
+ max_val = 1;
+ break;
+ case '*':
+ min_val = 0;
+ max_val = -1;
+ break;
+ case '+':
+ min_val = 1;
+ max_val = -1;
+ break;
+ case '{':
+ max_set = false;
+ while (valid) {
+ ++d;
+ if (d[0] == '}') {
+ break;
+ } else if (d[0] == ',') {
+ max_set = true;
+ } else if ('0' <= d[0] && d[0] <= '9') {
+ if (max_set) {
+ if (max_val < 0)
+ max_val = int(d[0] - '0');
+ else
+ max_val = max_val * 10 + int(d[0] - '0');
} else {
- valid = false;
+ min_val = min_val * 10 + int(d[0] - '0');
}
+ } else {
+ valid = false;
}
- break;
- default:
- break;
- }
+ }
+ break;
+ default:
+ break;
+ }
- if (!max_set)
- max_val = min_val;
+ if (!max_set)
+ max_val = min_val;
- if (valid) {
+ if (valid) {
- c = d;
+ c = d;
- if (stack[0]->back == NULL || !stack[0]->back->quantifiable)
- REGEX_COMPILE_FAIL("element not quantifiable");
+ if (stack[0]->back == NULL || !stack[0]->back->quantifiable)
+ REGEX_COMPILE_FAIL("element not quantifiable");
- if (min_val != max_val)
- for (int i = 0; i < stack.size(); ++i)
- if (stack[i]->is_look_behind())
- REGEX_COMPILE_FAIL("variable length quantifiers inside lookbehind not supported");
+ if (min_val != max_val)
+ for (int i = 0; i < stack.size(); ++i)
+ if (stack[i]->is_look_behind())
+ REGEX_COMPILE_FAIL("variable length quantifiers inside lookbehind not supported");
- RegExNodeQuantifier* quant = memnew(RegExNodeQuantifier(min_val, max_val));
- quant->child = stack[0]->swap_back(quant);
- quant->child->previous = NULL;
- quant->child->parent = quant;
+ RegExNodeQuantifier *quant = memnew(RegExNodeQuantifier(min_val, max_val));
+ quant->child = stack[0]->swap_back(quant);
+ quant->child->previous = NULL;
+ quant->child->parent = quant;
- if (min_val == max_val && quant->child->length >= 0)
- quant->length = max_val * quant->child->length;
+ if (min_val == max_val && quant->child->length >= 0)
+ quant->length = max_val * quant->child->length;
- if (c[1] == '?') {
- quant->greedy = false;
- ++c;
- }
- break;
+ if (c[1] == '?') {
+ quant->greedy = false;
+ ++c;
}
+ break;
}
+ }
default:
stack[0]->add_child(memnew(RegExNodeChar(c[0])));
break;
@@ -1345,7 +1337,7 @@ Error RegEx::compile(const String& p_pattern) {
return OK;
}
-Ref<RegExMatch> RegEx::search(const String& p_text, int p_start, int p_end) const {
+Ref<RegExMatch> RegEx::search(const String &p_text, int p_start, int p_end) const {
ERR_FAIL_COND_V(!is_valid(), NULL);
ERR_FAIL_COND_V(p_start < 0, NULL);
@@ -1382,7 +1374,7 @@ Ref<RegExMatch> RegEx::search(const String& p_text, int p_start, int p_end) cons
return NULL;
}
-String RegEx::sub(const String& p_text, const String& p_replacement, bool p_all, int p_start, int p_end) const {
+String RegEx::sub(const String &p_text, const String &p_replacement, bool p_all, int p_start, int p_end) const {
ERR_FAIL_COND_V(!is_valid(), p_text);
ERR_FAIL_COND_V(p_start < 0, p_text);
@@ -1400,7 +1392,7 @@ String RegEx::sub(const String& p_text, const String& p_replacement, bool p_all,
Ref<RegExMatch> m = search(text, start, p_end);
- RegExMatch::Group& s = m->captures[0];
+ RegExMatch::Group &s = m->captures[0];
if (s.start < 0)
break;
@@ -1467,7 +1459,7 @@ RegEx::RegEx() {
lookahead_depth = 0;
}
-RegEx::RegEx(const String& p_pattern) {
+RegEx::RegEx(const String &p_pattern) {
root = NULL;
compile(p_pattern);
@@ -1481,27 +1473,26 @@ RegEx::~RegEx() {
void RegExMatch::_bind_methods() {
- ClassDB::bind_method(D_METHOD("expand","template"),&RegExMatch::expand);
- ClassDB::bind_method(D_METHOD("get_group_count"),&RegExMatch::get_group_count);
- ClassDB::bind_method(D_METHOD("get_group_array"),&RegExMatch::get_group_array);
- ClassDB::bind_method(D_METHOD("get_names"),&RegExMatch::get_names);
- ClassDB::bind_method(D_METHOD("get_name_dict"),&RegExMatch::get_name_dict);
- ClassDB::bind_method(D_METHOD("get_string","name"),&RegExMatch::get_string, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_start","name"),&RegExMatch::get_start, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_end","name"),&RegExMatch::get_end, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("expand", "template"), &RegExMatch::expand);
+ ClassDB::bind_method(D_METHOD("get_group_count"), &RegExMatch::get_group_count);
+ ClassDB::bind_method(D_METHOD("get_group_array"), &RegExMatch::get_group_array);
+ ClassDB::bind_method(D_METHOD("get_names"), &RegExMatch::get_names);
+ ClassDB::bind_method(D_METHOD("get_name_dict"), &RegExMatch::get_name_dict);
+ ClassDB::bind_method(D_METHOD("get_string", "name"), &RegExMatch::get_string, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_start", "name"), &RegExMatch::get_start, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("get_end", "name"), &RegExMatch::get_end, DEFVAL(0));
}
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","text","start","end"),&RegEx::search, DEFVAL(0), DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("sub","text","replacement","all","start","end"),&RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("is_valid"),&RegEx::is_valid);
- ClassDB::bind_method(D_METHOD("get_pattern"),&RegEx::get_pattern);
- ClassDB::bind_method(D_METHOD("get_group_count"),&RegEx::get_group_count);
- ClassDB::bind_method(D_METHOD("get_names"),&RegEx::get_names);
+ ClassDB::bind_method(D_METHOD("clear"), &RegEx::clear);
+ ClassDB::bind_method(D_METHOD("compile", "pattern"), &RegEx::compile);
+ ClassDB::bind_method(D_METHOD("search", "text", "start", "end"), &RegEx::search, DEFVAL(0), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("sub", "text", "replacement", "all", "start", "end"), &RegEx::sub, DEFVAL(false), DEFVAL(0), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("is_valid"), &RegEx::is_valid);
+ ClassDB::bind_method(D_METHOD("get_pattern"), &RegEx::get_pattern);
+ ClassDB::bind_method(D_METHOD("get_group_count"), &RegEx::get_group_count);
+ ClassDB::bind_method(D_METHOD("get_names"), &RegEx::get_names);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "pattern"), "compile", "get_pattern");
}
-
diff --git a/modules/regex/regex.h b/modules/regex/regex.h
index 193d818da3..7aecf9b3ec 100644
--- a/modules/regex/regex.h
+++ b/modules/regex/regex.h
@@ -30,11 +30,11 @@
#ifndef REGEX_H
#define REGEX_H
-#include "core/vector.h"
-#include "core/ustring.h"
#include "core/dictionary.h"
#include "core/reference.h"
#include "core/resource.h"
+#include "core/ustring.h"
+#include "core/vector.h"
class RegExNode;
@@ -57,12 +57,10 @@ class RegExMatch : public Reference {
friend class RegExNodeBackReference;
protected:
-
static void _bind_methods();
public:
-
- String expand(const String& p_template) const;
+ String expand(const String &p_template) const;
int get_group_count() const;
Array get_group_array() const;
@@ -70,34 +68,31 @@ public:
Array get_names() const;
Dictionary get_name_dict() const;
- String get_string(const Variant& p_name) const;
- int get_start(const Variant& p_name) const;
- int get_end(const Variant& p_name) const;
+ String get_string(const Variant &p_name) const;
+ int get_start(const Variant &p_name) const;
+ int get_end(const Variant &p_name) const;
RegExMatch();
-
};
class RegEx : public Resource {
GDCLASS(RegEx, Resource);
- RegExNode* root;
+ RegExNode *root;
Vector<Variant> group_names;
String pattern;
int lookahead_depth;
protected:
-
static void _bind_methods();
public:
-
void clear();
- Error compile(const String& p_pattern);
+ Error compile(const String &p_pattern);
- Ref<RegExMatch> search(const String& p_text, int p_start = 0, int p_end = -1) const;
- String sub(const String& p_text, const String& p_replacement, bool p_all = false, int p_start = 0, int p_end = -1) const;
+ Ref<RegExMatch> search(const String &p_text, int p_start = 0, int p_end = -1) const;
+ String sub(const String &p_text, const String &p_replacement, bool p_all = false, int p_start = 0, int p_end = -1) const;
bool is_valid() const;
String get_pattern() const;
@@ -105,10 +100,8 @@ public:
Array get_names() const;
RegEx();
- RegEx(const String& p_pattern);
+ RegEx(const String &p_pattern);
~RegEx();
-
};
#endif // REGEX_H
-
diff --git a/modules/regex/register_types.cpp b/modules/regex/register_types.cpp
index c62a04d80f..2e24edcd84 100644
--- a/modules/regex/register_types.cpp
+++ b/modules/regex/register_types.cpp
@@ -38,6 +38,4 @@ void register_regex_types() {
}
void unregister_regex_types() {
-
}
-
diff --git a/modules/squish/image_compress_squish.cpp b/modules/squish/image_compress_squish.cpp
index 28c200596b..dd46dac234 100644
--- a/modules/squish/image_compress_squish.cpp
+++ b/modules/squish/image_compress_squish.cpp
@@ -34,58 +34,61 @@
void image_compress_squish(Image *p_image) {
- int w=p_image->get_width();
- int h=p_image->get_height();
+ int w = p_image->get_width();
+ int h = p_image->get_height();
- if (!p_image->has_mipmaps() ) {
- ERR_FAIL_COND( !w || w % 4 != 0);
- ERR_FAIL_COND( !h || h % 4 != 0);
+ if (!p_image->has_mipmaps()) {
+ ERR_FAIL_COND(!w || w % 4 != 0);
+ ERR_FAIL_COND(!h || h % 4 != 0);
} else {
- ERR_FAIL_COND( !w || w !=nearest_power_of_2(w) );
- ERR_FAIL_COND( !h || h !=nearest_power_of_2(h) );
+ ERR_FAIL_COND(!w || w != nearest_power_of_2(w));
+ ERR_FAIL_COND(!h || h != nearest_power_of_2(h));
};
- if (p_image->get_format()>=Image::FORMAT_DXT1)
+ if (p_image->get_format() >= Image::FORMAT_DXT1)
return; //do not compress, already compressed
- int shift=0;
- int squish_comp=squish::kColourRangeFit;
+ int shift = 0;
+ int squish_comp = squish::kColourRangeFit;
Image::Format target_format;
- if (p_image->get_format()==Image::FORMAT_LA8) {
+ if (p_image->get_format() == Image::FORMAT_LA8) {
//compressed normalmap
- target_format = Image::FORMAT_DXT5; squish_comp|=squish::kDxt5;
- } else if (p_image->detect_alpha()!=Image::ALPHA_NONE) {
+ target_format = Image::FORMAT_DXT5;
+ squish_comp |= squish::kDxt5;
+ } else if (p_image->detect_alpha() != Image::ALPHA_NONE) {
- target_format = Image::FORMAT_DXT3; squish_comp|=squish::kDxt3;
+ target_format = Image::FORMAT_DXT3;
+ squish_comp |= squish::kDxt3;
} else {
- target_format = Image::FORMAT_DXT1; shift=1; squish_comp|=squish::kDxt1;
+ target_format = Image::FORMAT_DXT1;
+ shift = 1;
+ squish_comp |= squish::kDxt1;
}
p_image->convert(Image::FORMAT_RGBA8); //always expects rgba
PoolVector<uint8_t> data;
- int target_size = Image::get_image_data_size(w,h,target_format,p_image->has_mipmaps()?-1:0);
- int mm_count = p_image->has_mipmaps() ? Image::get_image_required_mipmaps(w,h,target_format) : 0;
+ int target_size = Image::get_image_data_size(w, h, target_format, p_image->has_mipmaps() ? -1 : 0);
+ int mm_count = p_image->has_mipmaps() ? Image::get_image_required_mipmaps(w, h, target_format) : 0;
data.resize(target_size);
PoolVector<uint8_t>::Read rb = p_image->get_data().read();
PoolVector<uint8_t>::Write wb = data.write();
- int dst_ofs=0;
+ int dst_ofs = 0;
- for(int i=0;i<=mm_count;i++) {
+ for (int i = 0; i <= mm_count; i++) {
int src_ofs = p_image->get_mipmap_offset(i);
- squish::CompressImage( &rb[src_ofs],w,h,&wb[dst_ofs],squish_comp);
- dst_ofs+=(MAX(4,w)*MAX(4,h))>>shift;
- w>>=1;
- h>>=1;
+ squish::CompressImage(&rb[src_ofs], w, h, &wb[dst_ofs], squish_comp);
+ dst_ofs += (MAX(4, w) * MAX(4, h)) >> shift;
+ w >>= 1;
+ h >>= 1;
}
rb = PoolVector<uint8_t>::Read();
wb = PoolVector<uint8_t>::Write();
- p_image->create(p_image->get_width(),p_image->get_height(),p_image->has_mipmaps(),target_format,data);
-
+ p_image->create(p_image->get_width(), p_image->get_height(), p_image->has_mipmaps(), target_format, data);
}
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
index d3d7ab2307..884eb905fa 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
@@ -28,20 +28,19 @@
/*************************************************************************/
#include "audio_stream_ogg_vorbis.h"
-#include "thirdparty/stb_vorbis/stb_vorbis.c"
#include "os/file_access.h"
+#include "thirdparty/stb_vorbis/stb_vorbis.c"
-
-void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame* p_buffer,int p_frames) {
+void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) {
ERR_FAIL_COND(!active);
- int todo=p_frames;
+ int todo = p_frames;
- while(todo) {
+ while (todo) {
- int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream,2,(float*)p_buffer,todo*2);
- todo-=mixed;
+ int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, (float *)p_buffer, todo * 2);
+ todo -= mixed;
if (todo) {
//end of file!
@@ -50,15 +49,13 @@ void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame* p_buffer,int p_fram
seek_pos(0);
loops++;
} else {
- for(int i=mixed;i<p_frames;i++) {
- p_buffer[i]=AudioFrame(0,0);
+ for (int i = mixed; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
}
- active=false;
+ active = false;
}
}
}
-
-
}
float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() {
@@ -66,20 +63,17 @@ float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() {
return vorbis_stream->sample_rate;
}
-
void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) {
seek_pos(p_from_pos);
- active=true;
- loops=0;
+ active = true;
+ loops = 0;
_begin_resample();
-
-
}
void AudioStreamPlaybackOGGVorbis::stop() {
- active=false;
+ active = false;
}
bool AudioStreamPlaybackOGGVorbis::is_playing() const {
@@ -93,14 +87,14 @@ int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
float AudioStreamPlaybackOGGVorbis::get_pos() const {
- return float(frames_mixed)/vorbis_stream->sample_rate;
+ return float(frames_mixed) / vorbis_stream->sample_rate;
}
void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) {
if (!active)
return;
- stb_vorbis_seek(ogg_stream, uint32_t(p_time*vorbis_stream->sample_rate));
+ stb_vorbis_seek(ogg_stream, uint32_t(p_time * vorbis_stream->sample_rate));
}
float AudioStreamPlaybackOGGVorbis::get_length() const {
@@ -117,27 +111,25 @@ AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {
Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
-
-
Ref<AudioStreamPlaybackOGGVorbis> ovs;
- printf("instance at %p, data %p\n",this,data);
+ printf("instance at %p, data %p\n", this, data);
- ERR_FAIL_COND_V(data==NULL,ovs);
+ ERR_FAIL_COND_V(data == NULL, ovs);
ovs.instance();
- ovs->vorbis_stream=Ref<AudioStreamOGGVorbis>(this);
- ovs->ogg_alloc.alloc_buffer=(char*)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size);
- ovs->ogg_alloc.alloc_buffer_length_in_bytes=decode_mem_size;
- ovs->frames_mixed=0;
- ovs->active=false;
- ovs->loops=0;
- int error ;
- ovs->ogg_stream = stb_vorbis_open_memory( (const unsigned char*)data, data_len, &error, &ovs->ogg_alloc );
+ ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this);
+ ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size);
+ ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size;
+ ovs->frames_mixed = 0;
+ ovs->active = false;
+ ovs->loops = 0;
+ int error;
+ ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc);
if (!ovs->ogg_stream) {
AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer);
- ovs->ogg_alloc.alloc_buffer=NULL;
- ERR_FAIL_COND_V(!ovs->ogg_stream,Ref<AudioStreamPlaybackOGGVorbis>());
+ ovs->ogg_alloc.alloc_buffer = NULL;
+ ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>());
}
return ovs;
@@ -145,40 +137,40 @@ Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() {
String AudioStreamOGGVorbis::get_stream_name() const {
- return "";//return stream_name;
+ return ""; //return stream_name;
}
-void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t>& p_data) {
+void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) {
- int src_data_len=p_data.size();
-#define MAX_TEST_MEM (1<<20)
+ int src_data_len = p_data.size();
+#define MAX_TEST_MEM (1 << 20)
- uint32_t alloc_try=1024;
+ uint32_t alloc_try = 1024;
PoolVector<char> alloc_mem;
PoolVector<char>::Write w;
- stb_vorbis * ogg_stream=NULL;
+ stb_vorbis *ogg_stream = NULL;
stb_vorbis_alloc ogg_alloc;
- while(alloc_try<MAX_TEST_MEM) {
+ while (alloc_try < MAX_TEST_MEM) {
alloc_mem.resize(alloc_try);
w = alloc_mem.write();
- ogg_alloc.alloc_buffer=w.ptr();
- ogg_alloc.alloc_buffer_length_in_bytes=alloc_try;
+ ogg_alloc.alloc_buffer = w.ptr();
+ ogg_alloc.alloc_buffer_length_in_bytes = alloc_try;
PoolVector<uint8_t>::Read src_datar = p_data.read();
int error;
- ogg_stream = stb_vorbis_open_memory( (const unsigned char*)src_datar.ptr(), src_data_len, &error, &ogg_alloc );
+ ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc);
- if (!ogg_stream && error==VORBIS_outofmem) {
+ if (!ogg_stream && error == VORBIS_outofmem) {
w = PoolVector<char>::Write();
- alloc_try*=2;
+ alloc_try *= 2;
} else {
- ERR_FAIL_COND(alloc_try==MAX_TEST_MEM);
- ERR_FAIL_COND(ogg_stream==NULL);
+ ERR_FAIL_COND(alloc_try == MAX_TEST_MEM);
+ ERR_FAIL_COND(ogg_stream == NULL);
stb_vorbis_info info = stb_vorbis_get_info(ogg_stream);
@@ -190,19 +182,17 @@ void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t>& p_data) {
//print_line("succeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size));
- length=stb_vorbis_stream_length_in_seconds(ogg_stream);
+ length = stb_vorbis_stream_length_in_seconds(ogg_stream);
stb_vorbis_close(ogg_stream);
- data = AudioServer::get_singleton()->audio_data_alloc(src_data_len,src_datar.ptr());
- data_len=src_data_len;
+ data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr());
+ data_len = src_data_len;
break;
}
}
-
- printf("create at %p, data %p\n",this,data);
-
+ printf("create at %p, data %p\n", this, data);
}
PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const {
@@ -213,16 +203,15 @@ PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const {
vdata.resize(data_len);
{
PoolVector<uint8_t>::Write w = vdata.write();
- copymem(w.ptr(),data,data_len);
+ copymem(w.ptr(), data, data_len);
}
-
}
return vdata;
}
void AudioStreamOGGVorbis::set_loop(bool p_enable) {
- loop=p_enable;
+ loop = p_enable;
}
bool AudioStreamOGGVorbis::has_loop() const {
@@ -230,31 +219,24 @@ bool AudioStreamOGGVorbis::has_loop() const {
return loop;
}
-
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);
-
- ClassDB::bind_method(D_METHOD("set_loop","enable"),&AudioStreamOGGVorbis::set_loop);
- ClassDB::bind_method(D_METHOD("has_loop"),&AudioStreamOGGVorbis::has_loop);
+ ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data);
+ ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data);
- ADD_PROPERTY(PropertyInfo(Variant::POOL_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");
+ ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop);
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_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");
}
AudioStreamOGGVorbis::AudioStreamOGGVorbis() {
-
- data=NULL;
- length=0;
- sample_rate=1;
- channels=1;
- decode_mem_size=0;
- loop=false;
+ data = NULL;
+ length = 0;
+ sample_rate = 1;
+ channels = 1;
+ decode_mem_size = 0;
+ loop = false;
}
-
-
-
-
diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.h b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
index 2313fc4ae3..c32b3e578d 100644
--- a/modules/stb_vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.h
@@ -29,36 +29,35 @@
#ifndef AUDIO_STREAM_STB_VORBIS_H
#define AUDIO_STREAM_STB_VORBIS_H
-#include "servers/audio/audio_stream.h"
#include "io/resource_loader.h"
+#include "servers/audio/audio_stream.h"
#define STB_VORBIS_HEADER_ONLY
#include "thirdparty/stb_vorbis/stb_vorbis.c"
#undef STB_VORBIS_HEADER_ONLY
-
class AudioStreamOGGVorbis;
class AudioStreamPlaybackOGGVorbis : public AudioStreamPlaybackResampled {
- GDCLASS( AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled )
+ GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlaybackResampled)
- stb_vorbis * ogg_stream;
+ stb_vorbis *ogg_stream;
stb_vorbis_alloc ogg_alloc;
uint32_t frames_mixed;
bool active;
int loops;
-friend class AudioStreamOGGVorbis;
+ friend class AudioStreamOGGVorbis;
Ref<AudioStreamOGGVorbis> vorbis_stream;
-protected:
- virtual void _mix_internal(AudioFrame* p_buffer, int p_frames);
+protected:
+ virtual void _mix_internal(AudioFrame *p_buffer, int p_frames);
virtual float get_stream_sampling_rate();
public:
- virtual void start(float p_from_pos=0.0);
+ virtual void start(float p_from_pos = 0.0);
virtual void stop();
virtual bool is_playing() const;
@@ -69,17 +68,17 @@ public:
virtual float get_length() const; //if supported, otherwise return 0
- AudioStreamPlaybackOGGVorbis() { }
+ AudioStreamPlaybackOGGVorbis() {}
~AudioStreamPlaybackOGGVorbis();
};
class AudioStreamOGGVorbis : public AudioStream {
- GDCLASS( AudioStreamOGGVorbis, AudioStream )
- OBJ_SAVE_TYPE( AudioStream ) //children are all saved as AudioStream, so they can be exchanged
+ GDCLASS(AudioStreamOGGVorbis, AudioStream)
+ OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged
RES_BASE_EXTENSION("asogg");
-friend class AudioStreamPlaybackOGGVorbis;
+ friend class AudioStreamPlaybackOGGVorbis;
void *data;
uint32_t data_len;
@@ -89,23 +88,21 @@ friend class AudioStreamPlaybackOGGVorbis;
int channels;
float length;
bool loop;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void set_loop(bool p_enable);
bool has_loop() const;
virtual Ref<AudioStreamPlayback> instance_playback();
virtual String get_stream_name() const;
- void set_data(const PoolVector<uint8_t>& p_data);
+ void set_data(const PoolVector<uint8_t> &p_data);
PoolVector<uint8_t> get_data() const;
AudioStreamOGGVorbis();
};
-
-
#endif
diff --git a/modules/stb_vorbis/register_types.cpp b/modules/stb_vorbis/register_types.cpp
index 41fbc6fbd7..36b7ebc11a 100644
--- a/modules/stb_vorbis/register_types.cpp
+++ b/modules/stb_vorbis/register_types.cpp
@@ -41,5 +41,4 @@ void register_stb_vorbis_types() {
}
void unregister_stb_vorbis_types() {
-
}
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
index 03495652d4..11d8551db5 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.cpp
@@ -37,11 +37,11 @@ String ResourceImporterOGGVorbis::get_importer_name() const {
return "ogg_vorbis";
}
-String ResourceImporterOGGVorbis::get_visible_name() const{
+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");
}
@@ -50,12 +50,12 @@ String ResourceImporterOGGVorbis::get_save_extension() const {
return "asogg";
}
-String ResourceImporterOGGVorbis::get_resource_type() 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 {
+bool ResourceImporterOGGVorbis::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
return true;
}
@@ -68,23 +68,18 @@ String ResourceImporterOGGVorbis::get_preset_name(int p_idx) const {
return String();
}
+void ResourceImporterOGGVorbis::get_import_options(List<ImportOption> *r_options, int p_preset) const {
-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::BOOL, "loop"), true));
}
-
-
-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) {
+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) {
bool loop = p_options["loop"];
- FileAccess *f = FileAccess::open(p_source_file,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ);
if (!f) {
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
}
size_t len = f->get_len();
@@ -93,7 +88,7 @@ Error ResourceImporterOGGVorbis::import(const String& p_source_file, const Strin
data.resize(len);
PoolVector<uint8_t>::Write w = data.write();
- f->get_buffer(w.ptr(),len);
+ f->get_buffer(w.ptr(), len);
memdelete(f);
@@ -103,10 +98,8 @@ Error ResourceImporterOGGVorbis::import(const String& p_source_file, const Strin
ogg_stream->set_data(data);
ogg_stream->set_loop(loop);
- return ResourceSaver::save(p_save_path+".asogg",ogg_stream);
+ return ResourceSaver::save(p_save_path + ".asogg", ogg_stream);
}
-ResourceImporterOGGVorbis::ResourceImporterOGGVorbis()
-{
-
+ResourceImporterOGGVorbis::ResourceImporterOGGVorbis() {
}
diff --git a/modules/stb_vorbis/resource_importer_ogg_vorbis.h b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
index 15fc2cd2f3..2f0fcbe9a1 100644
--- a/modules/stb_vorbis/resource_importer_ogg_vorbis.h
+++ b/modules/stb_vorbis/resource_importer_ogg_vorbis.h
@@ -29,12 +29,11 @@
#ifndef RESOURCEIMPORTEROGGVORBIS_H
#define RESOURCEIMPORTEROGGVORBIS_H
-
-#include "io/resource_import.h"
#include "audio_stream_ogg_vorbis.h"
+#include "io/resource_import.h"
class ResourceImporterOGGVorbis : public ResourceImporter {
- GDCLASS(ResourceImporterOGGVorbis,ResourceImporter)
+ GDCLASS(ResourceImporterOGGVorbis, ResourceImporter)
public:
virtual String get_importer_name() const;
virtual String get_visible_name() const;
@@ -45,10 +44,10 @@ public:
virtual int get_preset_count() const;
virtual String get_preset_name(int p_idx) const;
- 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;
+ virtual bool get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const;
- 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=NULL);
+ 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 = NULL);
ResourceImporterOGGVorbis();
};
diff --git a/modules/theora/register_types.cpp b/modules/theora/register_types.cpp
index 58f63465c9..deb54b5d80 100644
--- a/modules/theora/register_types.cpp
+++ b/modules/theora/register_types.cpp
@@ -30,16 +30,16 @@
#include "video_stream_theora.h"
-static ResourceFormatLoaderVideoStreamTheora* theora_stream_loader = NULL;
+static ResourceFormatLoaderVideoStreamTheora *theora_stream_loader = NULL;
void register_theora_types() {
- theora_stream_loader = memnew( ResourceFormatLoaderVideoStreamTheora );
+ theora_stream_loader = memnew(ResourceFormatLoaderVideoStreamTheora);
ResourceLoader::add_resource_format_loader(theora_stream_loader);
ClassDB::register_class<VideoStreamTheora>();
}
void unregister_theora_types() {
- memdelete( theora_stream_loader );
+ memdelete(theora_stream_loader);
}
diff --git a/modules/theora/video_stream_theora.cpp b/modules/theora/video_stream_theora.cpp
index 2a7b2707bf..c390701adb 100644
--- a/modules/theora/video_stream_theora.cpp
+++ b/modules/theora/video_stream_theora.cpp
@@ -32,9 +32,9 @@
#include "os/os.h"
#include "yuv2rgb.h"
-int VideoStreamPlaybackTheora:: buffer_data() {
+int VideoStreamPlaybackTheora::buffer_data() {
- char *buffer=ogg_sync_buffer(&oy,4096);
+ char *buffer = ogg_sync_buffer(&oy, 4096);
#ifdef THEORA_USE_THREAD_STREAMING
@@ -42,44 +42,44 @@ int VideoStreamPlaybackTheora:: buffer_data() {
do {
thread_sem->post();
- read = MIN(ring_buffer.data_left(),4096);
+ read = MIN(ring_buffer.data_left(), 4096);
if (read) {
- ring_buffer.read((uint8_t*)buffer,read);
- ogg_sync_wrote(&oy,read);
+ ring_buffer.read((uint8_t *)buffer, read);
+ ogg_sync_wrote(&oy, read);
} else {
OS::get_singleton()->delay_usec(100);
}
- } while(read==0);
+ } while (read == 0);
return read;
#else
- int bytes=file->get_buffer((uint8_t*)buffer, 4096);
- ogg_sync_wrote(&oy,bytes);
- return(bytes);
+ int bytes = file->get_buffer((uint8_t *)buffer, 4096);
+ ogg_sync_wrote(&oy, bytes);
+ return (bytes);
#endif
}
-int VideoStreamPlaybackTheora::queue_page(ogg_page *page){
- if(theora_p) {
- ogg_stream_pagein(&to,page);
- if (to.e_o_s)
- theora_eos=true;
- }
- if(vorbis_p) {
- ogg_stream_pagein(&vo,page);
- if (vo.e_o_s)
- vorbis_eos=true;
- }
- return 0;
+int VideoStreamPlaybackTheora::queue_page(ogg_page *page) {
+ if (theora_p) {
+ ogg_stream_pagein(&to, page);
+ if (to.e_o_s)
+ theora_eos = true;
+ }
+ if (vorbis_p) {
+ ogg_stream_pagein(&vo, page);
+ if (vo.e_o_s)
+ vorbis_eos = true;
+ }
+ return 0;
}
-void VideoStreamPlaybackTheora::video_write(void){
+void VideoStreamPlaybackTheora::video_write(void) {
th_ycbcr_buffer yuv;
- th_decode_ycbcr_out(td,yuv);
+ th_decode_ycbcr_out(td, yuv);
// FIXME: The way stuff is commented out with `//*/` closing comments
// sounds very fishy...
@@ -116,27 +116,27 @@ void VideoStreamPlaybackTheora::video_write(void){
frame_data.resize(size.x * size.y * pitch);
{
PoolVector<uint8_t>::Write w = frame_data.write();
- char* dst = (char*)w.ptr();
+ char *dst = (char *)w.ptr();
//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, 0);
+ 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, 0);
} 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, 0);
+ 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, 0);
} else if (px_fmt == TH_PF_420) {
- yuv420_2_rgb8888((uint8_t*)dst, (uint8_t*)yuv[0].data, (uint8_t*)yuv[2].data, (uint8_t*)yuv[1].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x<<2, 0);
+ yuv420_2_rgb8888((uint8_t *)dst, (uint8_t *)yuv[0].data, (uint8_t *)yuv[2].data, (uint8_t *)yuv[1].data, size.x, size.y, yuv[0].stride, yuv[1].stride, size.x << 2, 0);
};
format = Image::FORMAT_RGBA8;
}
- Image img(size.x,size.y,0,Image::FORMAT_RGBA8,frame_data); //zero copy image creation
+ Image img(size.x, size.y, 0, Image::FORMAT_RGBA8, frame_data); //zero copy image creation
texture->set_data(img); //zero copy send to visual server
@@ -241,7 +241,7 @@ void VideoStreamPlaybackTheora::clear() {
if (!file)
return;
- if(vorbis_p){
+ if (vorbis_p) {
ogg_stream_clear(&vo);
if (vorbis_p >= 3) {
vorbis_block_clear(&vb);
@@ -251,7 +251,7 @@ void VideoStreamPlaybackTheora::clear() {
vorbis_info_clear(&vi);
vorbis_p = 0;
}
- if(theora_p){
+ if (theora_p) {
ogg_stream_clear(&to);
th_decode_free(td);
th_comment_clear(&tc);
@@ -261,11 +261,11 @@ void VideoStreamPlaybackTheora::clear() {
ogg_sync_clear(&oy);
#ifdef THEORA_USE_THREAD_STREAMING
- thread_exit=true;
+ thread_exit = true;
thread_sem->post(); //just in case
Thread::wait_to_finish(thread);
memdelete(thread);
- thread=NULL;
+ thread = NULL;
ring_buffer.clear();
#endif
//file_name = "";
@@ -275,21 +275,21 @@ void VideoStreamPlaybackTheora::clear() {
videobuf_ready = 0;
frames_pending = 0;
videobuf_time = 0;
- theora_eos=false;
- vorbis_eos=false;
+ theora_eos = false;
+ vorbis_eos = false;
if (file) {
memdelete(file);
}
- file=NULL;
+ file = NULL;
playing = false;
};
-void VideoStreamPlaybackTheora::set_file(const String& p_file) {
+void VideoStreamPlaybackTheora::set_file(const String &p_file) {
ERR_FAIL_COND(playing);
ogg_packet op;
- th_setup_info *ts = NULL;
+ th_setup_info *ts = NULL;
file_name = p_file;
if (file) {
@@ -299,14 +299,14 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
ERR_FAIL_COND(!file);
#ifdef THEORA_USE_THREAD_STREAMING
- thread_exit=false;
- thread_eof=false;
+ thread_exit = false;
+ thread_eof = false;
//pre-fill buffer
int to_read = ring_buffer.space_left();
- int read = file->get_buffer(read_buffer.ptr(),to_read);
- ring_buffer.write(read_buffer.ptr(),read);
+ int read = file->get_buffer(read_buffer.ptr(), to_read);
+ ring_buffer.write(read_buffer.ptr(), read);
- thread=Thread::create(_streaming_thread,this);
+ thread = Thread::create(_streaming_thread, this);
#endif
@@ -320,42 +320,39 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
th_comment_init(&tc);
th_info_init(&ti);
- theora_eos=false;
- vorbis_eos=false;
+ theora_eos = false;
+ vorbis_eos = false;
/* Ogg file open; parse the headers */
/* Only interested in Vorbis/Theora streams */
int stateflag = 0;
- int audio_track_skip=audio_track;
-
+ int audio_track_skip = audio_track;
- while(!stateflag){
- int ret=buffer_data();
- if(ret==0)break;
- while(ogg_sync_pageout(&oy,&og)>0){
+ while (!stateflag) {
+ int ret = buffer_data();
+ if (ret == 0) break;
+ while (ogg_sync_pageout(&oy, &og) > 0) {
ogg_stream_state test;
/* is this a mandated initial header? If not, stop parsing */
- if(!ogg_page_bos(&og)){
+ if (!ogg_page_bos(&og)) {
/* don't leak the page; get it into the appropriate stream */
queue_page(&og);
- stateflag=1;
+ stateflag = 1;
break;
}
- ogg_stream_init(&test,ogg_page_serialno(&og));
- ogg_stream_pagein(&test,&og);
- ogg_stream_packetout(&test,&op);
-
+ ogg_stream_init(&test, ogg_page_serialno(&og));
+ ogg_stream_pagein(&test, &og);
+ ogg_stream_packetout(&test, &op);
/* identify the codec: try theora */
- if(!theora_p && th_decode_headerin(&ti,&tc,&ts,&op)>=0){
+ if (!theora_p && th_decode_headerin(&ti, &tc, &ts, &op) >= 0) {
/* it is theora */
- copymem(&to,&test,sizeof(test));
- theora_p=1;
- }else if(!vorbis_p && vorbis_synthesis_headerin(&vi,&vc,&op)>=0){
-
+ 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) {
@@ -367,10 +364,10 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
audio_track_skip--;
} else {
- copymem(&vo,&test,sizeof(test));
- vorbis_p=1;
+ copymem(&vo, &test, sizeof(test));
+ vorbis_p = 1;
}
- }else{
+ } else {
/* whatever it is, we don't care about it */
ogg_stream_clear(&test);
}
@@ -379,20 +376,20 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
}
/* we're expecting more header packets. */
- while((theora_p && theora_p<3) || (vorbis_p && vorbis_p<3)){
+ while ((theora_p && theora_p < 3) || (vorbis_p && vorbis_p < 3)) {
int ret;
/* look for further theora headers */
- while(theora_p && (theora_p<3) && (ret=ogg_stream_packetout(&to,&op))){
- if(ret<0){
- fprintf(stderr,"Error parsing Theora stream headers; "
- "corrupt stream?\n");
+ while (theora_p && (theora_p < 3) && (ret = ogg_stream_packetout(&to, &op))) {
+ if (ret < 0) {
+ fprintf(stderr, "Error parsing Theora stream headers; "
+ "corrupt stream?\n");
clear();
return;
}
- if(!th_decode_headerin(&ti,&tc,&ts,&op)){
- fprintf(stderr,"Error parsing Theora stream headers; "
- "corrupt stream?\n");
+ if (!th_decode_headerin(&ti, &tc, &ts, &op)) {
+ fprintf(stderr, "Error parsing Theora stream headers; "
+ "corrupt stream?\n");
clear();
return;
}
@@ -400,31 +397,31 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
}
/* look for more vorbis header packets */
- while(vorbis_p && (vorbis_p<3) && (ret=ogg_stream_packetout(&vo,&op))){
- if(ret<0){
- fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
+ while (vorbis_p && (vorbis_p < 3) && (ret = ogg_stream_packetout(&vo, &op))) {
+ if (ret < 0) {
+ fprintf(stderr, "Error parsing Vorbis stream headers; corrupt stream?\n");
clear();
return;
}
- ret = vorbis_synthesis_headerin(&vi,&vc,&op);
- if(ret){
- fprintf(stderr,"Error parsing Vorbis stream headers; corrupt stream?\n");
+ ret = vorbis_synthesis_headerin(&vi, &vc, &op);
+ if (ret) {
+ fprintf(stderr, "Error parsing Vorbis stream headers; corrupt stream?\n");
clear();
return;
}
vorbis_p++;
- if(vorbis_p==3)break;
+ if (vorbis_p == 3) break;
}
/* The header pages/packets will arrive before anything else we
care about, or the stream is not obeying spec */
- if(ogg_sync_pageout(&oy,&og)>0){
+ if (ogg_sync_pageout(&oy, &og) > 0) {
queue_page(&og); /* demux into the appropriate stream */
- }else{
- int ret=buffer_data(); /* someone needs more data */
- if(ret==0){
- fprintf(stderr,"End of file while searching for codec headers.\n");
+ } else {
+ int ret = buffer_data(); /* someone needs more data */
+ if (ret == 0) {
+ fprintf(stderr, "End of file while searching for codec headers.\n");
clear();
return;
}
@@ -432,30 +429,30 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
}
/* and now we have it all. initialize decoders */
- if(theora_p){
- td=th_decode_alloc(&ti,ts);
+ if (theora_p) {
+ td = th_decode_alloc(&ti, ts);
printf("Ogg logical stream %lx is Theora %dx%d %.02f fps",
- to.serialno,ti.pic_width,ti.pic_height,
- (double)ti.fps_numerator/ti.fps_denominator);
- px_fmt=ti.pixel_fmt;
- switch(ti.pixel_fmt){
- case TH_PF_420: printf(" 4:2:0 video\n"); break;
- case TH_PF_422: printf(" 4:2:2 video\n"); break;
- case TH_PF_444: printf(" 4:4:4 video\n"); break;
- case TH_PF_RSVD:
- default:
- printf(" video\n (UNKNOWN Chroma sampling!)\n");
- break;
+ to.serialno, ti.pic_width, ti.pic_height,
+ (double)ti.fps_numerator / ti.fps_denominator);
+ px_fmt = ti.pixel_fmt;
+ switch (ti.pixel_fmt) {
+ case TH_PF_420: printf(" 4:2:0 video\n"); break;
+ case TH_PF_422: printf(" 4:2:2 video\n"); break;
+ case TH_PF_444: printf(" 4:4:4 video\n"); break;
+ case TH_PF_RSVD:
+ default:
+ printf(" video\n (UNKNOWN Chroma sampling!)\n");
+ break;
}
- if(ti.pic_width!=ti.frame_width || ti.pic_height!=ti.frame_height)
+ if (ti.pic_width != ti.frame_width || ti.pic_height != ti.frame_height)
printf(" Frame content is %dx%d with offset (%d,%d).\n",
- ti.frame_width, ti.frame_height, ti.pic_x, ti.pic_y);
- th_decode_ctl(td,TH_DECCTL_GET_PPLEVEL_MAX,&pp_level_max,
- sizeof(pp_level_max));
- pp_level=pp_level_max;
- pp_level=0;
- th_decode_ctl(td,TH_DECCTL_SET_PPLEVEL,&pp_level,sizeof(pp_level));
- pp_inc=0;
+ ti.frame_width, ti.frame_height, ti.pic_x, ti.pic_y);
+ th_decode_ctl(td, TH_DECCTL_GET_PPLEVEL_MAX, &pp_level_max,
+ sizeof(pp_level_max));
+ pp_level = pp_level_max;
+ pp_level = 0;
+ th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level, sizeof(pp_level));
+ pp_inc = 0;
/*{
int arg = 0xffff;
@@ -468,14 +465,14 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
int w;
int h;
- w=(ti.pic_x+ti.frame_width+1&~1)-(ti.pic_x&~1);
- h=(ti.pic_y+ti.frame_height+1&~1)-(ti.pic_y&~1);
+ w = (ti.pic_x + ti.frame_width + 1 & ~1) - (ti.pic_x & ~1);
+ h = (ti.pic_y + ti.frame_height + 1 & ~1) - (ti.pic_y & ~1);
size.x = w;
size.y = h;
- texture->create(w,h,Image::FORMAT_RGBA8,Texture::FLAG_FILTER|Texture::FLAG_VIDEO_SURFACE);
+ texture->create(w, h, Image::FORMAT_RGBA8, Texture::FLAG_FILTER | Texture::FLAG_VIDEO_SURFACE);
- }else{
+ } else {
/* tear down the partial theora setup */
th_info_clear(&ti);
th_comment_clear(&tc);
@@ -483,32 +480,30 @@ void VideoStreamPlaybackTheora::set_file(const String& p_file) {
th_setup_free(ts);
- if(vorbis_p){
- vorbis_synthesis_init(&vd,&vi);
- vorbis_block_init(&vd,&vb);
- fprintf(stderr,"Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.\n",
- vo.serialno,vi.channels,vi.rate);
+ if (vorbis_p) {
+ vorbis_synthesis_init(&vd, &vi);
+ vorbis_block_init(&vd, &vb);
+ fprintf(stderr, "Ogg logical stream %lx is Vorbis %d channel %ld Hz audio.\n",
+ vo.serialno, vi.channels, vi.rate);
//_setup(vi.channels, vi.rate);
- }else{
+ } else {
/* tear down the partial vorbis setup */
vorbis_info_clear(&vi);
vorbis_comment_clear(&vc);
}
playing = false;
- buffering=true;
- time=0;
- audio_frames_wrote=0;
-
-
+ buffering = true;
+ time = 0;
+ audio_frames_wrote = 0;
};
float VideoStreamPlaybackTheora::get_time() const {
//print_line("total: "+itos(get_total())+" todo: "+itos(get_todo()));
//return MAX(0,time-((get_total())/(float)vi.rate));
- return time-AudioServer::get_singleton()->get_output_delay()-delay_compensation;//-((get_total())/(float)vi.rate);
+ return time - AudioServer::get_singleton()->get_output_delay() - delay_compensation; //-((get_total())/(float)vi.rate);
};
Ref<Texture> VideoStreamPlaybackTheora::get_texture() {
@@ -526,8 +521,6 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
return;
};
-
-
#ifdef THEORA_USE_THREAD_STREAMING
thread_sem->post();
#endif
@@ -535,112 +528,102 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
//double ctime =AudioServer::get_singleton()->get_mix_time();
//print_line("play "+rtos(p_delta));
- time+=p_delta;
+ time += p_delta;
- if (videobuf_time>get_time()) {
+ if (videobuf_time > get_time()) {
return; //no new frames need to be produced
}
- bool frame_done=false;
- bool audio_done=!vorbis_p;
+ bool frame_done = false;
+ bool audio_done = !vorbis_p;
while (!frame_done || (!audio_done && !vorbis_eos)) {
//a frame needs to be produced
ogg_packet op;
- bool no_theora=false;
-
+ bool no_theora = false;
while (vorbis_p) {
int ret;
float **pcm;
- bool buffer_full=false;
+ bool buffer_full = false;
/* if there's pending, decoded audio, grab it */
- if ((ret=vorbis_synthesis_pcmout(&vd,&pcm))>0) {
+ if ((ret = vorbis_synthesis_pcmout(&vd, &pcm)) > 0) {
-
-
- const int AUXBUF_LEN=4096;
+ const int AUXBUF_LEN = 4096;
int to_read = ret;
int16_t aux_buffer[AUXBUF_LEN];
- while(to_read) {
+ while (to_read) {
- int m = MIN(AUXBUF_LEN/vi.channels,to_read);
+ int m = MIN(AUXBUF_LEN / vi.channels, to_read);
int count = 0;
- for(int j=0;j<m;j++){
- for(int i=0;i<vi.channels;i++){
+ for (int j = 0; j < m; j++) {
+ for (int i = 0; i < vi.channels; i++) {
- int val=Math::fast_ftoi(pcm[i][j]*32767.f);
- if(val>32767)val=32767;
- if(val<-32768)val=-32768;
+ int val = Math::fast_ftoi(pcm[i][j] * 32767.f);
+ if (val > 32767) val = 32767;
+ if (val < -32768) val = -32768;
aux_buffer[count++] = val;
}
}
if (mix_callback) {
- int mixed = mix_callback(mix_udata,aux_buffer,m);
- to_read-=mixed;
- if (mixed!=m) { //could mix no more
- buffer_full=true;
+ int mixed = mix_callback(mix_udata, aux_buffer, m);
+ to_read -= mixed;
+ if (mixed != m) { //could mix no more
+ buffer_full = true;
break;
}
} else {
- to_read-=m; //just pretend we sent the audio
+ to_read -= m; //just pretend we sent the audio
}
-
-
}
+ int tr = vorbis_synthesis_read(&vd, ret - to_read);
- int tr = vorbis_synthesis_read(&vd, ret-to_read);
-
-
- if (vd.granulepos>=0) {
+ if (vd.granulepos >= 0) {
//print_line("wrote: "+itos(audio_frames_wrote)+" gpos: "+itos(vd.granulepos));
}
//print_line("mix audio!");
- audio_frames_wrote+=ret-to_read;
+ audio_frames_wrote += ret - to_read;
//print_line("AGP: "+itos(vd.granulepos)+" added "+itos(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! */
- vorbis_synthesis_blockin(&vd,&vb);
+ if (ogg_stream_packetout(&vo, &op) > 0) {
+ if (vorbis_synthesis(&vb, &op) == 0) { /* test for success! */
+ vorbis_synthesis_blockin(&vd, &vb);
}
- } else { /* we need more data; break out to suck in another page */
+ } else { /* we need more data; break out to suck in another page */
//printf("need moar data\n");
break;
};
}
-
- audio_done = videobuf_time < (audio_frames_wrote/float(vi.rate));
+ audio_done = videobuf_time < (audio_frames_wrote / float(vi.rate));
if (buffer_full)
break;
}
- while(theora_p && !frame_done){
+ while (theora_p && !frame_done) {
/* theora is one in, one out... */
- if(ogg_stream_packetout(&to,&op)>0){
+ 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,
- sizeof(pp_level));
- pp_inc=0;
+ if (false && pp_inc) {
+ pp_level += pp_inc;
+ th_decode_ctl(td, TH_DECCTL_SET_PPLEVEL, &pp_level,
+ sizeof(pp_level));
+ pp_inc = 0;
}
/*HACK: This should be set after a seek or a gap, but we might not have
a granulepos for the first packet (we only have them for the last
@@ -648,13 +631,13 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
To do this right, we should back-track from the last packet on the
page and compute the correct granulepos for the first packet after
a seek or a gap.*/
- if(op.granulepos>=0){
- th_decode_ctl(td,TH_DECCTL_SET_GRANPOS,&op.granulepos,
- sizeof(op.granulepos));
+ if (op.granulepos >= 0) {
+ th_decode_ctl(td, TH_DECCTL_SET_GRANPOS, &op.granulepos,
+ sizeof(op.granulepos));
}
ogg_int64_t videobuf_granulepos;
- if(th_decode_packetin(td,&op,&videobuf_granulepos)==0){
- videobuf_time=th_granule_time(td,videobuf_granulepos);
+ if (th_decode_packetin(td, &op, &videobuf_granulepos) == 0) {
+ videobuf_time = th_granule_time(td, videobuf_granulepos);
//printf("frame time %f, play time %f, ready %i\n", (float)videobuf_time, get_time(), videobuf_ready);
@@ -664,27 +647,25 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
keyframing. Soon enough libtheora will be able to deal
with non-keyframe seeks. */
- if(videobuf_time>=get_time()) {
- frame_done=true;
- } else{
+ if (videobuf_time >= get_time()) {
+ frame_done = true;
+ } else {
/*If we are too slow, reduce the pp level.*/
- pp_inc=pp_level>0?-1:0;
+ pp_inc = pp_level > 0 ? -1 : 0;
}
} else {
-
}
} else {
- no_theora=true;
+ no_theora = true;
break;
}
}
-
- //print_line("no theora: "+itos(no_theora)+" theora eos: "+itos(theora_eos)+" frame done "+itos(frame_done));
+//print_line("no theora: "+itos(no_theora)+" theora eos: "+itos(theora_eos)+" frame done "+itos(frame_done));
#ifdef THEORA_USE_THREAD_STREAMING
- if (file && thread_eof && no_theora && theora_eos && ring_buffer.data_left()==0) {
+ if (file && thread_eof && no_theora && theora_eos && ring_buffer.data_left() == 0) {
#else
if (file && /*!videobuf_ready && */ no_theora && theora_eos) {
#endif
@@ -692,7 +673,7 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
stop();
return;
};
- #if 0
+#if 0
if (!videobuf_ready || audio_todo > 0){
/* no data yet for somebody. Grab another page */
@@ -701,23 +682,22 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
queue_page(&og);
}
}
- #else
-
+#else
- if (!frame_done || !audio_done){
+ if (!frame_done || !audio_done) {
//what's the point of waiting for audio to grab a page?
buffer_data();
- while(ogg_sync_pageout(&oy,&og)>0){
+ while (ogg_sync_pageout(&oy, &og) > 0) {
queue_page(&og);
}
}
- #endif
+#endif
/* If playback has begun, top audio buffer off immediately. */
//if(stateflag) audio_write_nonblocking();
/* are we at or past time for this video frame? */
- if(videobuf_ready && videobuf_time<=get_time()){
+ if (videobuf_ready && videobuf_time <= get_time()) {
//video_write();
//videobuf_ready=0;
@@ -725,35 +705,29 @@ void VideoStreamPlaybackTheora::update(float p_delta) {
//printf("frame at %f not ready (time %f), ready %i\n", (float)videobuf_time, get_time(), videobuf_ready);
}
- float tdiff=videobuf_time-get_time();
+ float tdiff = videobuf_time - get_time();
/*If we have lots of extra time, increase the post-processing level.*/
- if(tdiff>ti.fps_denominator*0.25/ti.fps_numerator){
- pp_inc=pp_level<pp_level_max?1:0;
- }
- else if(tdiff<ti.fps_denominator*0.05/ti.fps_numerator){
- pp_inc=pp_level>0?-1:0;
+ if (tdiff > ti.fps_denominator * 0.25 / ti.fps_numerator) {
+ pp_inc = pp_level < pp_level_max ? 1 : 0;
+ } else if (tdiff < ti.fps_denominator * 0.05 / ti.fps_numerator) {
+ pp_inc = pp_level > 0 ? -1 : 0;
}
-
}
video_write();
-
};
-
void VideoStreamPlaybackTheora::play() {
if (!playing)
- time=0;
+ time = 0;
else {
stop();
}
playing = true;
- delay_compensation=GlobalConfig::get_singleton()->get("audio/video_delay_compensation_ms");
- delay_compensation/=1000.0;
-
-
+ delay_compensation = GlobalConfig::get_singleton()->get("audio/video_delay_compensation_ms");
+ delay_compensation /= 1000.0;
};
void VideoStreamPlaybackTheora::stop() {
@@ -764,7 +738,7 @@ void VideoStreamPlaybackTheora::stop() {
set_file(file_name); //reset
}
playing = false;
- time=0;
+ time = 0;
};
bool VideoStreamPlaybackTheora::is_playing() const {
@@ -774,7 +748,7 @@ bool VideoStreamPlaybackTheora::is_playing() const {
void VideoStreamPlaybackTheora::set_paused(bool p_paused) {
- paused=p_paused;
+ paused = p_paused;
//pau = !p_paused;
};
@@ -783,7 +757,7 @@ bool VideoStreamPlaybackTheora::is_paused(bool p_paused) const {
return paused;
};
-void VideoStreamPlaybackTheora::set_loop(bool p_enable) {
+void VideoStreamPlaybackTheora::set_loop(bool p_enable){
};
@@ -812,52 +786,49 @@ float VideoStreamPlaybackTheora::get_pos() const {
return get_time();
};
-void VideoStreamPlaybackTheora::seek_pos(float p_time) {
+void VideoStreamPlaybackTheora::seek_pos(float p_time){
// no
};
-void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback,void *p_userdata) {
+void VideoStreamPlaybackTheora::set_mix_callback(AudioMixCallback p_callback, void *p_userdata) {
- mix_callback=p_callback;
- mix_udata=p_userdata;
+ mix_callback = p_callback;
+ mix_udata = p_userdata;
}
-int VideoStreamPlaybackTheora::get_channels() const{
+int VideoStreamPlaybackTheora::get_channels() const {
return vi.channels;
}
void VideoStreamPlaybackTheora::set_audio_track(int p_idx) {
- audio_track=p_idx;
+ audio_track = p_idx;
}
-int VideoStreamPlaybackTheora::get_mix_rate() const{
+int VideoStreamPlaybackTheora::get_mix_rate() const {
return vi.rate;
}
#ifdef THEORA_USE_THREAD_STREAMING
-
void VideoStreamPlaybackTheora::_streaming_thread(void *ud) {
- VideoStreamPlaybackTheora *vs=(VideoStreamPlaybackTheora*)ud;
+ VideoStreamPlaybackTheora *vs = (VideoStreamPlaybackTheora *)ud;
- while(!vs->thread_exit) {
+ 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);
- vs->ring_buffer.write(vs->read_buffer.ptr(),read);
- vs->thread_eof=vs->file->eof_reached();
+ int read = vs->file->get_buffer(vs->read_buffer.ptr(), to_read);
+ vs->ring_buffer.write(vs->read_buffer.ptr(), read);
+ vs->thread_eof = vs->file->eof_reached();
}
-
-
}
vs->thread_sem->wait();
@@ -875,24 +846,24 @@ VideoStreamPlaybackTheora::VideoStreamPlaybackTheora() {
playing = false;
frames_pending = 0;
videobuf_time = 0;
- paused=false;
+ paused = false;
- buffering=false;
- texture = Ref<ImageTexture>( memnew(ImageTexture ));
- mix_callback=NULL;
- mix_udata=NULL;
- audio_track=0;
- delay_compensation=0;
- audio_frames_wrote=0;
+ buffering = false;
+ texture = Ref<ImageTexture>(memnew(ImageTexture));
+ mix_callback = NULL;
+ mix_udata = NULL;
+ audio_track = 0;
+ delay_compensation = 0;
+ audio_frames_wrote = 0;
#ifdef THEORA_USE_THREAD_STREAMING
- int rb_power = nearest_shift(RB_SIZE_KB*1024);
+ int rb_power = nearest_shift(RB_SIZE_KB * 1024);
ring_buffer.resize(rb_power);
- read_buffer.resize(RB_SIZE_KB*1024);
- thread_sem=Semaphore::create();
- thread=NULL;
- thread_exit=false;
- thread_eof=false;
+ read_buffer.resize(RB_SIZE_KB * 1024);
+ thread_sem = Semaphore::create();
+ thread = NULL;
+ thread_exit = false;
+ thread_eof = false;
#endif
};
@@ -907,20 +878,17 @@ VideoStreamPlaybackTheora::~VideoStreamPlaybackTheora() {
if (file)
memdelete(file);
-
-
};
-
-RES ResourceFormatLoaderVideoStreamTheora::load(const String &p_path,const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderVideoStreamTheora::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_FILE_CANT_OPEN;
+ *r_error = ERR_FILE_CANT_OPEN;
VideoStreamTheora *stream = memnew(VideoStreamTheora);
stream->set_file(p_path);
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return Ref<VideoStreamTheora>(stream);
}
@@ -930,14 +898,14 @@ void ResourceFormatLoaderVideoStreamTheora::get_recognized_extensions(List<Strin
p_extensions->push_back("ogm");
p_extensions->push_back("ogv");
}
-bool ResourceFormatLoaderVideoStreamTheora::handles_type(const String& p_type) const {
- return (p_type=="VideoStream" || p_type=="VideoStreamTheora");
+bool ResourceFormatLoaderVideoStreamTheora::handles_type(const String &p_type) const {
+ return (p_type == "VideoStream" || p_type == "VideoStreamTheora");
}
String ResourceFormatLoaderVideoStreamTheora::get_resource_type(const String &p_path) const {
- String exl=p_path.get_extension().to_lower();
- if (exl=="ogm" || exl=="ogv")
+ String exl = p_path.get_extension().to_lower();
+ if (exl == "ogm" || exl == "ogv")
return "VideoStreamTheora";
return "";
}
diff --git a/modules/theora/video_stream_theora.h b/modules/theora/video_stream_theora.h
index 0e1f5fa864..ea568906da 100644
--- a/modules/theora/video_stream_theora.h
+++ b/modules/theora/video_stream_theora.h
@@ -31,8 +31,8 @@
#include "io/resource_loader.h"
#include "os/file_access.h"
-#include "os/thread.h"
#include "os/semaphore.h"
+#include "os/thread.h"
#include "ring_buffer.h"
#include "scene/resources/video_stream.h"
@@ -53,7 +53,7 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback {
Image::Format format;
PoolVector<uint8_t> frame_data;
int frames_pending;
- FileAccess* file;
+ FileAccess *file;
String file_name;
int audio_frames_wrote;
Point2i size;
@@ -66,18 +66,18 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback {
bool theora_eos;
bool vorbis_eos;
- ogg_sync_state oy;
- ogg_page og;
+ ogg_sync_state oy;
+ ogg_page og;
ogg_stream_state vo;
ogg_stream_state to;
- th_info ti;
- th_comment tc;
- th_dec_ctx *td;
- vorbis_info vi;
+ th_info ti;
+ th_comment tc;
+ th_dec_ctx *td;
+ vorbis_info vi;
vorbis_dsp_state vd;
- vorbis_block vb;
- vorbis_comment vc;
- th_pixel_fmt px_fmt;
+ vorbis_block vb;
+ vorbis_comment vc;
+ th_pixel_fmt px_fmt;
double videobuf_time;
int pp_inc;
@@ -97,13 +97,13 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback {
Ref<ImageTexture> texture;
AudioMixCallback mix_callback;
- void* mix_udata;
+ void *mix_udata;
bool paused;
#ifdef THEORA_USE_THREAD_STREAMING
enum {
- RB_SIZE_KB=1024
+ RB_SIZE_KB = 1024
};
RingBuffer<uint8_t> ring_buffer;
@@ -117,15 +117,12 @@ class VideoStreamPlaybackTheora : public VideoStreamPlayback {
#endif
-
int audio_track;
protected:
-
void clear();
-
-public:
+public:
virtual void play();
virtual void stop();
virtual bool is_playing() const;
@@ -145,13 +142,12 @@ public:
virtual float get_pos() const;
virtual void seek_pos(float p_time);
-
- void set_file(const String& p_file);
+ void set_file(const String &p_file);
virtual Ref<Texture> get_texture();
virtual void update(float p_delta);
- virtual void set_mix_callback(AudioMixCallback p_callback,void *p_userdata);
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata);
virtual int get_channels() const;
virtual int get_mix_rate() const;
@@ -161,39 +157,33 @@ public:
~VideoStreamPlaybackTheora();
};
-
-
class VideoStreamTheora : public VideoStream {
- GDCLASS(VideoStreamTheora,VideoStream);
+ GDCLASS(VideoStreamTheora, VideoStream);
String file;
int audio_track;
-
public:
-
Ref<VideoStreamPlayback> instance_playback() {
- Ref<VideoStreamPlaybackTheora> pb = memnew( VideoStreamPlaybackTheora );
+ Ref<VideoStreamPlaybackTheora> pb = memnew(VideoStreamPlaybackTheora);
pb->set_audio_track(audio_track);
pb->set_file(file);
return pb;
}
- void set_file(const String& p_file) { file=p_file; }
- void set_audio_track(int p_track) { audio_track=p_track; }
-
- VideoStreamTheora() { audio_track=0; }
+ void set_file(const String &p_file) { file = p_file; }
+ void set_audio_track(int p_track) { audio_track = p_track; }
+ VideoStreamTheora() { audio_track = 0; }
};
class ResourceFormatLoaderVideoStreamTheora : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
#endif
diff --git a/modules/visual_script/register_types.cpp b/modules/visual_script/register_types.cpp
index 5fe87a4956..b05ea716ed 100644
--- a/modules/visual_script/register_types.cpp
+++ b/modules/visual_script/register_types.cpp
@@ -28,23 +28,21 @@
/*************************************************************************/
#include "register_types.h"
-#include "visual_script.h"
-#include "visual_script_editor.h"
#include "io/resource_loader.h"
-#include "visual_script_nodes.h"
-#include "visual_script_func_nodes.h"
+#include "visual_script.h"
#include "visual_script_builtin_funcs.h"
+#include "visual_script_editor.h"
+#include "visual_script_expression.h"
#include "visual_script_flow_control.h"
+#include "visual_script_func_nodes.h"
+#include "visual_script_nodes.h"
#include "visual_script_yield_nodes.h"
-#include "visual_script_expression.h"
-
-
-VisualScriptLanguage *visual_script_language=NULL;
+VisualScriptLanguage *visual_script_language = NULL;
void register_visual_script_types() {
- visual_script_language=memnew( VisualScriptLanguage );
+ visual_script_language = memnew(VisualScriptLanguage);
//script_language_gd->init();
ScriptServer::register_language(visual_script_language);
@@ -78,7 +76,6 @@ void register_visual_script_types() {
ClassDB::register_class<VisualScriptPreload>();
ClassDB::register_class<VisualScriptTypeCast>();
-
ClassDB::register_class<VisualScriptFunctionCall>();
ClassDB::register_class<VisualScriptPropertySet>();
ClassDB::register_class<VisualScriptPropertyGet>();
@@ -91,14 +88,13 @@ void register_visual_script_types() {
ClassDB::register_class<VisualScriptIterator>();
ClassDB::register_class<VisualScriptSequence>();
ClassDB::register_class<VisualScriptInputFilter>();
- ClassDB::register_class<VisualScriptSwitch >();
+ ClassDB::register_class<VisualScriptSwitch>();
ClassDB::register_class<VisualScriptYield>();
ClassDB::register_class<VisualScriptYieldSignal>();
ClassDB::register_class<VisualScriptBuiltinFunc>();
-
ClassDB::register_class<VisualScriptExpression>();
register_visual_script_nodes();
@@ -111,13 +107,10 @@ void register_visual_script_types() {
#ifdef TOOLS_ENABLED
VisualScriptEditor::register_editor();
#endif
-
-
}
void unregister_visual_script_types() {
-
unregister_visual_script_nodes();
ScriptServer::unregister_language(visual_script_language);
@@ -126,6 +119,5 @@ void unregister_visual_script_types() {
VisualScriptEditor::free_clipboard();
#endif
if (visual_script_language)
- memdelete( visual_script_language );
-
+ memdelete(visual_script_language);
}
diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp
index 9f742591d5..2b884c34fb 100644
--- a/modules/visual_script/visual_script.cpp
+++ b/modules/visual_script/visual_script.cpp
@@ -28,16 +28,14 @@
/*************************************************************************/
#include "visual_script.h"
-#include "visual_script_nodes.h"
-#include "scene/main/node.h"
-#include "os/os.h"
#include "global_config.h"
-
-
+#include "os/os.h"
+#include "scene/main/node.h"
+#include "visual_script_nodes.h"
//used by editor, this is not really saved
void VisualScriptNode::set_breakpoint(bool p_breakpoint) {
- breakpoint=p_breakpoint;
+ breakpoint = p_breakpoint;
}
bool VisualScriptNode::is_breakpoint() const {
@@ -47,76 +45,68 @@ bool VisualScriptNode::is_breakpoint() const {
void VisualScriptNode::_notification(int p_what) {
- if (p_what==NOTIFICATION_POSTINITIALIZE) {
+ if (p_what == NOTIFICATION_POSTINITIALIZE) {
int dvc = get_input_value_port_count();
- for(int i=0;i<dvc;i++) {
+ for (int i = 0; i < dvc; i++) {
Variant::Type expected = get_input_value_port_info(i).type;
Variant::CallError ce;
- default_input_values.push_back(Variant::construct(expected,NULL,0,ce,false));
+ default_input_values.push_back(Variant::construct(expected, NULL, 0, ce, false));
}
}
}
-void VisualScriptNode::ports_changed_notify(){
+void VisualScriptNode::ports_changed_notify() {
-
- 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
+ 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
emit_signal("ports_changed");
-
}
-void VisualScriptNode::set_default_input_value(int p_port,const Variant& p_value) {
+void VisualScriptNode::set_default_input_value(int p_port, const Variant &p_value) {
- ERR_FAIL_INDEX(p_port,default_input_values.size());
+ ERR_FAIL_INDEX(p_port, default_input_values.size());
- default_input_values[p_port]=p_value;
+ default_input_values[p_port] = p_value;
#ifdef TOOLS_ENABLED
- for (Set<VisualScript*>::Element *E=scripts_used.front();E;E=E->next()) {
+ for (Set<VisualScript *>::Element *E = scripts_used.front(); E; E = E->next()) {
E->get()->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());
+ 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;
+ default_input_values = p_values;
}
-
void VisualScriptNode::validate_input_default_values() {
-
-
default_input_values.resize(get_input_value_port_count());
//actually validate on save
- for(int i=0;i<get_input_value_port_count();i++) {
+ 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()) {
+ if (expected == Variant::NIL || expected == default_input_values[i].get_type()) {
continue;
- } else {
+ } else {
//not the same, reconvert
Variant::CallError ce;
Variant existing = default_input_values[i];
- const Variant *existingp=&existing;
- default_input_values[i] = Variant::construct(expected,&existingp,1,ce,false);
- if (ce.error!=Variant::CallError::CALL_OK) {
+ const Variant *existingp = &existing;
+ default_input_values[i] = Variant::construct(expected, &existingp, 1, ce, false);
+ if (ce.error != Variant::CallError::CALL_OK) {
//could not convert? force..
- default_input_values[i] = Variant::construct(expected,NULL,0,ce,false);
+ default_input_values[i] = Variant::construct(expected, NULL, 0, ce, false);
}
}
}
@@ -129,29 +119,27 @@ Array VisualScriptNode::_get_default_input_values() const {
return default_input_values;
}
-
-
void VisualScriptNode::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_visual_script:VisualScript"),&VisualScriptNode::get_visual_script);
- ClassDB::bind_method(D_METHOD("set_default_input_value","port_idx","value:Variant"),&VisualScriptNode::set_default_input_value);
- ClassDB::bind_method(D_METHOD("get_default_input_value:Variant","port_idx"),&VisualScriptNode::get_default_input_value);
- ClassDB::bind_method(D_METHOD("_set_default_input_values","values"),&VisualScriptNode::_set_default_input_values);
- ClassDB::bind_method(D_METHOD("_get_default_input_values"),&VisualScriptNode::_get_default_input_values);
+ ClassDB::bind_method(D_METHOD("get_visual_script:VisualScript"), &VisualScriptNode::get_visual_script);
+ ClassDB::bind_method(D_METHOD("set_default_input_value", "port_idx", "value:Variant"), &VisualScriptNode::set_default_input_value);
+ ClassDB::bind_method(D_METHOD("get_default_input_value:Variant", "port_idx"), &VisualScriptNode::get_default_input_value);
+ ClassDB::bind_method(D_METHOD("_set_default_input_values", "values"), &VisualScriptNode::_set_default_input_values);
+ ClassDB::bind_method(D_METHOD("_get_default_input_values"), &VisualScriptNode::_get_default_input_values);
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"_default_input_values",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_default_input_values","_get_default_input_values");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_default_input_values", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_default_input_values", "_get_default_input_values");
ADD_SIGNAL(MethodInfo("ports_changed"));
}
-VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess* p_inputs,int p_output) const {
+VisualScriptNode::TypeGuess VisualScriptNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
PropertyInfo pinfo = get_output_value_port_info(p_output);
TypeGuess tg;
- tg.type=pinfo.type;
- if (pinfo.hint==PROPERTY_HINT_RESOURCE_TYPE) {
- tg.GDCLASS=pinfo.hint_string;
+ tg.type = pinfo.type;
+ if (pinfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ tg.GDCLASS = pinfo.hint_string;
}
return tg;
@@ -166,7 +154,7 @@ Ref<VisualScript> VisualScriptNode::get_visual_script() const {
}
VisualScriptNode::VisualScriptNode() {
- breakpoint=false;
+ breakpoint = false;
}
////////////////
@@ -175,8 +163,8 @@ VisualScriptNode::VisualScriptNode() {
VisualScriptNodeInstance::VisualScriptNodeInstance() {
- sequence_outputs=NULL;
- input_ports=NULL;
+ sequence_outputs = NULL;
+ input_ports = NULL;
}
VisualScriptNodeInstance::~VisualScriptNodeInstance() {
@@ -192,44 +180,41 @@ VisualScriptNodeInstance::~VisualScriptNodeInstance() {
if (output_ports) {
memdelete_arr(output_ports);
}
-
}
-void VisualScript::add_function(const StringName& p_name) {
+void VisualScript::add_function(const StringName &p_name) {
- ERR_FAIL_COND( instances.size() );
+ ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(functions.has(p_name));
- functions[p_name]=Function();
- functions[p_name].scroll=Vector2(-50,-100);
+ functions[p_name] = Function();
+ functions[p_name].scroll = Vector2(-50, -100);
}
-bool VisualScript::has_function(const StringName& p_name) const {
+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(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()) {
+ for (Map<int, Function::NodeData>::Element *E = functions[p_name].nodes.front(); E; E = E->next()) {
- E->get().node->disconnect("ports_changed",this,"_node_ports_changed");
+ E->get().node->disconnect("ports_changed", this, "_node_ports_changed");
E->get().node->scripts_used.erase(this);
}
functions.erase(p_name);
-
}
-void VisualScript::rename_function(const StringName& p_name,const StringName& p_new_name) {
+void VisualScript::rename_function(const StringName &p_name, const StringName &p_new_name) {
- ERR_FAIL_COND( instances.size() );
+ 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());
@@ -238,60 +223,51 @@ void VisualScript::rename_function(const StringName& p_name,const StringName& p_
ERR_FAIL_COND(variables.has(p_new_name));
ERR_FAIL_COND(custom_signals.has(p_new_name));
- functions[p_new_name]=functions[p_name];
+ functions[p_new_name] = functions[p_name];
functions.erase(p_name);
-
}
-void VisualScript::set_function_scroll(const StringName& p_name, const Vector2& p_scroll) {
+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;
-
+ functions[p_name].scroll = p_scroll;
}
-Vector2 VisualScript::get_function_scroll(const StringName& p_name) const {
+Vector2 VisualScript::get_function_scroll(const StringName &p_name) const {
- ERR_FAIL_COND_V(!functions.has(p_name),Vector2());
+ ERR_FAIL_COND_V(!functions.has(p_name), Vector2());
return functions[p_name].scroll;
-
}
-
void VisualScript::get_function_list(List<StringName> *r_functions) const {
- for (const Map<StringName,Function>::Element *E=functions.front();E;E=E->next()) {
+ 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>();
-
}
-int VisualScript::get_function_node_id(const StringName& p_name) const {
+int VisualScript::get_function_node_id(const StringName &p_name) const {
- ERR_FAIL_COND_V(!functions.has(p_name),-1);
+ ERR_FAIL_COND_V(!functions.has(p_name), -1);
return functions[p_name].function_id;
-
}
-
void VisualScript::_node_ports_changed(int p_id) {
-
-
StringName function;
- for (Map<StringName,Function>::Element *E=functions.front();E;E=E->next()) {
+ for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
if (E->get().nodes.has(p_id)) {
- function=E->key();
+ function = E->key();
break;
}
}
- ERR_FAIL_COND(function==StringName());
+ ERR_FAIL_COND(function == StringName());
Function &func = functions[function];
Ref<VisualScriptNode> vsn = func.nodes[p_id].node;
@@ -305,18 +281,18 @@ void VisualScript::_node_ports_changed(int p_id) {
{
List<SequenceConnection> to_remove;
- for (Set<SequenceConnection>::Element *E=func.sequence_connections.front();E;E=E->next()) {
- if (E->get().from_node==p_id && E->get().from_output>=vsn->get_output_sequence_port_count()) {
+ for (Set<SequenceConnection>::Element *E = func.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()) {
+ if (E->get().to_node == p_id && !vsn->has_input_sequence_port()) {
to_remove.push_back(E->get());
}
}
- while(to_remove.size()) {
+ while (to_remove.size()) {
func.sequence_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
@@ -326,17 +302,16 @@ void VisualScript::_node_ports_changed(int p_id) {
List<DataConnection> to_remove;
-
- for (Set<DataConnection>::Element *E=func.data_connections.front();E;E=E->next()) {
- if (E->get().from_node==p_id && E->get().from_port>=vsn->get_output_value_port_count()) {
+ for (Set<DataConnection>::Element *E = func.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());
}
- if (E->get().to_node==p_id && E->get().to_port>=vsn->get_input_value_port_count()) {
+ if (E->get().to_node == p_id && E->get().to_port >= vsn->get_input_value_port_count()) {
to_remove.push_back(E->get());
}
}
- while(to_remove.size()) {
+ while (to_remove.size()) {
func.data_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
@@ -344,48 +319,44 @@ void VisualScript::_node_ports_changed(int p_id) {
#ifdef TOOLS_ENABLED
set_edited(true); //something changed, let's set as edited
- emit_signal("node_ports_changed",function,p_id);
+ emit_signal("node_ports_changed", function, 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(const StringName &p_func, int p_id, const Ref<VisualScriptNode> &p_node, const Point2 &p_pos) {
- ERR_FAIL_COND( instances.size() );
+ ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!functions.has(p_func));
-
- for (Map<StringName,Function>::Element *E=functions.front();E;E=E->next()) {
+ for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
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 (p_node->cast_to<VisualScriptFunction>()) {
//the function indeed
ERR_EXPLAIN("A function node already has been set here.");
- ERR_FAIL_COND(func.function_id>=0);
+ ERR_FAIL_COND(func.function_id >= 0);
- func.function_id=p_id;
+ func.function_id = p_id;
}
Function::NodeData nd;
- nd.node=p_node;
- nd.pos=p_pos;
+ nd.node = p_node;
+ nd.pos = p_pos;
Ref<VisualScriptNode> vsn = p_node;
- vsn->connect("ports_changed",this,"_node_ports_changed",varray(p_id));
+ vsn->connect("ports_changed", this, "_node_ports_changed", varray(p_id));
vsn->scripts_used.insert(this);
-
-
- func.nodes[p_id]=nd;
+ func.nodes[p_id] = nd;
}
-void VisualScript::remove_node(const StringName& p_func,int p_id){
+void VisualScript::remove_node(const StringName &p_func, int p_id) {
- ERR_FAIL_COND( instances.size() );
+ ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!functions.has(p_func));
Function &func = functions[p_func];
@@ -393,13 +364,13 @@ void VisualScript::remove_node(const StringName& p_func,int p_id){
{
List<SequenceConnection> to_remove;
- for (Set<SequenceConnection>::Element *E=func.sequence_connections.front();E;E=E->next()) {
- if (E->get().from_node==p_id || E->get().to_node==p_id) {
+ for (Set<SequenceConnection>::Element *E = func.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()) {
+ while (to_remove.size()) {
func.sequence_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
@@ -409,254 +380,239 @@ void VisualScript::remove_node(const StringName& p_func,int p_id){
List<DataConnection> to_remove;
-
- for (Set<DataConnection>::Element *E=func.data_connections.front();E;E=E->next()) {
- if (E->get().from_node==p_id || E->get().to_node==p_id) {
+ for (Set<DataConnection>::Element *E = func.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()) {
+ while (to_remove.size()) {
func.data_connections.erase(to_remove.front()->get());
to_remove.pop_front();
}
}
if (func.nodes[p_id].node->cast_to<VisualScriptFunction>()) {
- func.function_id=-1; //revert to invalid
+ func.function_id = -1; //revert to invalid
}
- func.nodes[p_id].node->disconnect("ports_changed",this,"_node_ports_changed");
+ func.nodes[p_id].node->disconnect("ports_changed", this, "_node_ports_changed");
func.nodes[p_id].node->scripts_used.erase(this);
func.nodes.erase(p_id);
-
-
}
+bool VisualScript::has_node(const StringName &p_func, int p_id) const {
-bool VisualScript::has_node(const StringName& p_func,int p_id) const {
-
- ERR_FAIL_COND_V(!functions.has(p_func),false);
+ ERR_FAIL_COND_V(!functions.has(p_func), false);
const Function &func = functions[p_func];
return func.nodes.has(p_id);
}
-Ref<VisualScriptNode> VisualScript::get_node(const StringName& p_func,int p_id) const{
+Ref<VisualScriptNode> VisualScript::get_node(const StringName &p_func, int p_id) const {
- ERR_FAIL_COND_V(!functions.has(p_func),Ref<VisualScriptNode>());
+ 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>());
+ ERR_FAIL_COND_V(!func.nodes.has(p_id), Ref<VisualScriptNode>());
return func.nodes[p_id].node;
}
-void VisualScript::set_node_pos(const StringName& p_func,int p_id,const Point2& p_pos) {
+void VisualScript::set_node_pos(const StringName &p_func, int p_id, const Point2 &p_pos) {
- ERR_FAIL_COND( instances.size() );
+ 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;
+ func.nodes[p_id].pos = p_pos;
}
-Point2 VisualScript::get_node_pos(const StringName& p_func,int p_id) const{
+Point2 VisualScript::get_node_pos(const StringName &p_func, int p_id) const {
- ERR_FAIL_COND_V(!functions.has(p_func),Point2());
+ 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());
+ ERR_FAIL_COND_V(!func.nodes.has(p_id), Point2());
return func.nodes[p_id].pos;
}
-
-void VisualScript::get_node_list(const StringName& p_func,List<int> *r_nodes) const{
+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()) {
+ for (const Map<int, Function::NodeData>::Element *E = func.nodes.front(); E; E = E->next()) {
r_nodes->push_back(E->key());
}
-
}
+void VisualScript::sequence_connect(const StringName &p_func, int p_from_node, int p_from_output, int p_to_node) {
-void VisualScript::sequence_connect(const StringName& p_func,int p_from_node,int p_from_output,int p_to_node){
-
- ERR_FAIL_COND( instances.size() );
+ 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;
+ 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));
func.sequence_connections.insert(sc);
-
}
-void VisualScript::sequence_disconnect(const StringName& p_func,int p_from_node,int p_from_output,int p_to_node){
+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];
SequenceConnection sc;
- sc.from_node=p_from_node;
- sc.from_output=p_from_output;
- sc.to_node=p_to_node;
+ 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));
func.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{
+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);
+ ERR_FAIL_COND_V(!functions.has(p_func), false);
const 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;
+ sc.from_node = p_from_node;
+ sc.from_output = p_from_output;
+ sc.to_node = p_to_node;
return func.sequence_connections.has(sc);
}
-void VisualScript::get_sequence_connection_list(const StringName& p_func,List<SequenceConnection> *r_connection) const {
+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()) {
+ for (const Set<SequenceConnection>::Element *E = func.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(const StringName& p_func,int p_from_node,int p_from_port,int p_to_node,int p_to_port) {
-
- ERR_FAIL_COND( instances.size() );
+ 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;
- dc.from_port=p_from_port;
- dc.to_node=p_to_node;
- dc.to_port=p_to_port;
+ 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(func.data_connections.has(dc));
func.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) {
+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];
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;
+ 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(!func.data_connections.has(dc));
func.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 {
+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);
+ ERR_FAIL_COND_V(!functions.has(p_func), false);
const Function &func = functions[p_func];
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;
+ 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);
-
}
-bool VisualScript::is_input_value_port_connected(const StringName& p_func,int p_node,int p_port) const {
+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);
+ 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)
+ 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)
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 {
+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);
+ 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) {
- *r_node=E->get().from_node;
- *r_port=E->get().from_port;
+ 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) {
+ *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 {
+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()) {
+ for (const Set<DataConnection>::Element *E = func.data_connections.front(); E; E = E->next()) {
r_connection->push_back(E->get());
}
}
-void VisualScript::add_variable(const StringName& p_name,const Variant& p_default_value,bool p_export) {
+void VisualScript::add_variable(const StringName &p_name, const Variant &p_default_value, bool p_export) {
- ERR_FAIL_COND( instances.size() );
+ ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(variables.has(p_name));
Variable v;
- v.default_value=p_default_value;
- v.info.type=p_default_value.get_type();
- v.info.name=p_name;
- v.info.hint=PROPERTY_HINT_NONE;
- v._export=p_export;
+ v.default_value = p_default_value;
+ v.info.type = p_default_value.get_type();
+ v.info.name = p_name;
+ v.info.hint = PROPERTY_HINT_NONE;
+ v._export = p_export;
- variables[p_name]=v;
+ variables[p_name] = v;
#ifdef TOOLS_ENABLED
_update_placeholders();
#endif
-
}
-bool VisualScript::has_variable(const StringName& p_name) const {
+bool VisualScript::has_variable(const StringName &p_name) const {
return variables.has(p_name);
}
-void VisualScript::remove_variable(const StringName& p_name) {
+void VisualScript::remove_variable(const StringName &p_name) {
ERR_FAIL_COND(!variables.has(p_name));
variables.erase(p_name);
@@ -666,111 +622,101 @@ void VisualScript::remove_variable(const StringName& p_name) {
#endif
}
-void VisualScript::set_variable_default_value(const StringName& p_name,const Variant& p_value){
+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;
+ variables[p_name].default_value = p_value;
#ifdef TOOLS_ENABLED
_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());
+ 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(instances.size());
ERR_FAIL_COND(!variables.has(p_name));
- variables[p_name].info=p_info;
- variables[p_name].info.name=p_name;
+ variables[p_name].info = p_info;
+ variables[p_name].info.name = p_name;
#ifdef TOOLS_ENABLED
_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());
+ 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) {
+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;
+ variables[p_name]._export = p_export;
}
-bool VisualScript::get_variable_export(const StringName& p_name) const {
+bool VisualScript::get_variable_export(const StringName &p_name) const {
- ERR_FAIL_COND_V(!variables.has(p_name),false);
+ 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) {
+void VisualScript::_set_variable_info(const StringName &p_name, const Dictionary &p_info) {
PropertyInfo pinfo;
if (p_info.has("type"))
- pinfo.type=Variant::Type(int(p_info["type"]));
+ pinfo.type = Variant::Type(int(p_info["type"]));
if (p_info.has("name"))
- pinfo.name=p_info["name"];
+ pinfo.name = p_info["name"];
if (p_info.has("hint"))
- pinfo.hint=PropertyHint(int(p_info["hint"]));
+ pinfo.hint = PropertyHint(int(p_info["hint"]));
if (p_info.has("hint_string"))
- pinfo.hint_string=p_info["hint_string"];
+ pinfo.hint_string = p_info["hint_string"];
if (p_info.has("usage"))
- pinfo.usage=p_info["usage"];
+ pinfo.usage = p_info["usage"];
- set_variable_info(p_name,pinfo);
+ set_variable_info(p_name, pinfo);
}
-Dictionary VisualScript::_get_variable_info(const StringName& p_name) const{
+Dictionary VisualScript::_get_variable_info(const StringName &p_name) const {
- PropertyInfo pinfo=get_variable_info(p_name);
+ PropertyInfo pinfo = get_variable_info(p_name);
Dictionary d;
- d["type"]=pinfo.type;
- d["name"]=pinfo.name;
- d["hint"]=pinfo.hint;
- d["hint_string"]=pinfo.hint_string;
- d["usage"]=pinfo.usage;
+ d["type"] = pinfo.type;
+ d["name"] = pinfo.name;
+ d["hint"] = pinfo.hint;
+ d["hint_string"] = pinfo.hint_string;
+ d["usage"] = pinfo.usage;
return d;
}
-void VisualScript::get_variable_list(List<StringName> *r_variables) const{
-
+void VisualScript::get_variable_list(List<StringName> *r_variables) const {
- for (Map<StringName,Variable>::Element *E=variables.front();E;E=E->next()) {
+ for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
r_variables->push_back(E->key());
}
r_variables->sort_custom<StringName::AlphCompare>();
}
+void VisualScript::set_instance_base_type(const StringName &p_type) {
-void VisualScript::set_instance_base_type(const StringName& p_type) {
-
- ERR_FAIL_COND( instances.size() );
- base_type=p_type;
+ ERR_FAIL_COND(instances.size());
+ base_type = p_type;
}
+void VisualScript::rename_variable(const StringName &p_name, const StringName &p_new_name) {
-void VisualScript::rename_variable(const StringName& p_name,const StringName& p_new_name) {
-
- ERR_FAIL_COND( instances.size() );
+ 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());
@@ -779,103 +725,94 @@ void VisualScript::rename_variable(const StringName& p_name,const StringName& p_
ERR_FAIL_COND(variables.has(p_new_name));
ERR_FAIL_COND(custom_signals.has(p_new_name));
- variables[p_new_name]=variables[p_name];
+ variables[p_new_name] = variables[p_name];
variables.erase(p_name);
-
}
-void VisualScript::add_custom_signal(const StringName& p_name) {
+void VisualScript::add_custom_signal(const StringName &p_name) {
- ERR_FAIL_COND( instances.size() );
+ ERR_FAIL_COND(instances.size());
ERR_FAIL_COND(!String(p_name).is_valid_identifier());
ERR_FAIL_COND(custom_signals.has(p_name));
- custom_signals[p_name]=Vector<Argument>();
+ custom_signals[p_name] = Vector<Argument>();
}
-bool VisualScript::has_custom_signal(const StringName& p_name) const {
+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(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
Argument arg;
- arg.type=p_type;
- arg.name=p_name;
- if (p_index<0)
+ arg.type = p_type;
+ arg.name = p_name;
+ if (p_index < 0)
custom_signals[p_func].push_back(arg);
else
- custom_signals[p_func].insert(0,arg);
-
+ 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(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx,custom_signals[p_func].size());
- custom_signals[p_func][p_argidx].type=p_type;
+ ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
+ custom_signals[p_func][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);
+ 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() );
+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][p_argidx].name=p_name;
-
+ ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
+ custom_signals[p_func][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());
+ 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(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx,custom_signals[p_func].size());
+ ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
custom_signals[p_func].remove(p_argidx);
-
}
-int VisualScript::custom_signal_get_argument_count(const StringName& p_func) const {
+int VisualScript::custom_signal_get_argument_count(const StringName &p_func) const {
- ERR_FAIL_COND_V(!custom_signals.has(p_func),0);
+ 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(instances.size());
ERR_FAIL_COND(!custom_signals.has(p_func));
- ERR_FAIL_INDEX(p_argidx,custom_signals[p_func].size());
- ERR_FAIL_INDEX(p_with_argidx,custom_signals[p_func].size());
-
- SWAP( custom_signals[p_func][p_argidx], custom_signals[p_func][p_with_argidx] );
+ ERR_FAIL_INDEX(p_argidx, custom_signals[p_func].size());
+ ERR_FAIL_INDEX(p_with_argidx, custom_signals[p_func].size());
+ SWAP(custom_signals[p_func][p_argidx], custom_signals[p_func][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(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) {
+void VisualScript::rename_custom_signal(const StringName &p_name, const StringName &p_new_name) {
- ERR_FAIL_COND( instances.size() );
+ 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());
@@ -884,30 +821,28 @@ void VisualScript::rename_custom_signal(const StringName& p_name,const StringNam
ERR_FAIL_COND(variables.has(p_new_name));
ERR_FAIL_COND(custom_signals.has(p_new_name));
- custom_signals[p_new_name]=custom_signals[p_name];
+ custom_signals[p_new_name] = custom_signals[p_name];
custom_signals.erase(p_name);
-
}
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()) {
+ for (const Map<StringName, Vector<Argument> >::Element *E = custom_signals.front(); E; E = E->next()) {
r_custom_signals->push_back(E->key());
}
r_custom_signals->sort_custom<StringName::AlphCompare>();
-
}
int VisualScript::get_available_id() const {
- int max_id=0;
- for (Map<StringName,Function>::Element *E=functions.front();E;E=E->next()) {
+ 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);
+ max_id = MAX(max_id, last_id + 1);
}
return max_id;
@@ -915,14 +850,11 @@ int VisualScript::get_available_id() const {
/////////////////////////////////
-
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;
@@ -932,84 +864,74 @@ Ref<Script> VisualScript::get_base_script() const {
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)
+ if (placeholders.size() == 0)
return; //no bother if no placeholders
List<PropertyInfo> pinfo;
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
- for (Map<StringName,Variable>::Element *E=variables.front();E;E=E->next()) {
+ for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
if (!E->get()._export)
continue;
PropertyInfo p = E->get().info;
- p.name=String(E->key());
+ p.name = String(E->key());
pinfo.push_back(p);
- values[p.name]=E->get().default_value;
+ values[p.name] = E->get().default_value;
}
- for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) {
+ for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
- E->get()->update(pinfo,values);
+ E->get()->update(pinfo, values);
}
-
}
#endif
-
-ScriptInstance* VisualScript::instance_create(Object *p_this) {
-
-
+ScriptInstance *VisualScript::instance_create(Object *p_this) {
#ifdef TOOLS_ENABLED
if (!ScriptServer::is_scripting_enabled()) {
-
- PlaceHolderScriptInstance *sins = memnew( PlaceHolderScriptInstance(VisualScriptLanguage::singleton,Ref<Script>((Script*)this),p_this));
+ PlaceHolderScriptInstance *sins = memnew(PlaceHolderScriptInstance(VisualScriptLanguage::singleton, Ref<Script>((Script *)this), p_this));
placeholders.insert(sins);
List<PropertyInfo> pinfo;
- Map<StringName,Variant> values;
+ Map<StringName, Variant> values;
- for (Map<StringName,Variable>::Element *E=variables.front();E;E=E->next()) {
+ for (Map<StringName, Variable>::Element *E = variables.front(); E; E = E->next()) {
if (!E->get()._export)
continue;
PropertyInfo p = E->get().info;
- p.name=String(E->key());
+ p.name = String(E->key());
pinfo.push_back(p);
- values[p.name]=E->get().default_value;
+ values[p.name] = E->get().default_value;
}
- sins->update(pinfo,values);
+ sins->update(pinfo, values);
return sins;
}
#endif
-
- VisualScriptInstance *instance=memnew( VisualScriptInstance );
- instance->create(Ref<VisualScript>(this),p_this);
-
+ VisualScriptInstance *instance = memnew(VisualScriptInstance);
+ instance->create(Ref<VisualScript>(this), p_this);
if (VisualScriptLanguage::singleton->lock)
VisualScriptLanguage::singleton->lock->lock();
- instances[p_this]=instance;
+ instances[p_this] = instance;
if (VisualScriptLanguage::singleton->lock)
VisualScriptLanguage::singleton->lock->unlock();
@@ -1019,7 +941,7 @@ ScriptInstance* VisualScript::instance_create(Object *p_this) {
bool VisualScript::instance_has(const Object *p_this) const {
- return instances.has((Object*)p_this);
+ return instances.has((Object *)p_this);
}
bool VisualScript::has_source_code() const {
@@ -1032,8 +954,7 @@ String VisualScript::get_source_code() const {
return String();
}
-void VisualScript::set_source_code(const String& p_code) {
-
+void VisualScript::set_source_code(const String &p_code) {
}
Error VisualScript::reload(bool p_keep_state) {
@@ -1041,74 +962,66 @@ Error VisualScript::reload(bool p_keep_state) {
return OK;
}
-
bool VisualScript::is_tool() const {
return false;
}
-
String VisualScript::get_node_type() const {
return String();
}
-
ScriptLanguage *VisualScript::get_language() const {
return VisualScriptLanguage::singleton;
}
-
-bool VisualScript::has_script_signal(const StringName& p_signal) const {
+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()) {
+ 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++) {
+ mi.name = E->key();
+ for (int i = 0; i < E->get().size(); i++) {
PropertyInfo arg;
- arg.type=E->get()[i].type;
- arg.name=E->get()[i].name;
+ arg.type = E->get()[i].type;
+ arg.name = E->get()[i].name;
mi.arguments.push_back(arg);
}
-
r_signals->push_back(mi);
}
-
-
}
-
-bool VisualScript::get_property_default_value(const StringName& p_property,Variant& r_value) const {
+bool VisualScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
if (!variables.has(p_property))
return false;
- r_value=variables[ p_property ].default_value;
+ 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()) {
+ for (Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
MethodInfo mi;
- mi.name=E->key();
- if (E->get().function_id>=0) {
+ mi.name = E->key();
+ if (E->get().function_id >= 0) {
- Ref<VisualScriptFunction> func=E->get().nodes[E->get().function_id].node;
+ Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node;
if (func.is_valid()) {
- for(int i=0;i<func->get_argument_count();i++) {
+ for (int i = 0; i < func->get_argument_count(); i++) {
PropertyInfo arg;
- arg.name=func->get_argument_name(i);
- arg.type=func->get_argument_type(i);
+ arg.name = func->get_argument_name(i);
+ arg.type = func->get_argument_type(i);
mi.arguments.push_back(arg);
}
}
@@ -1118,27 +1031,27 @@ void VisualScript::get_script_method_list(List<MethodInfo> *p_list) const {
}
}
-bool VisualScript::has_method(const StringName& p_method) 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{
+MethodInfo VisualScript::get_method_info(const StringName &p_method) const {
- const Map<StringName,Function>::Element *E=functions.find(p_method);
+ const Map<StringName, Function>::Element *E = functions.find(p_method);
if (!E)
return MethodInfo();
MethodInfo mi;
- mi.name=E->key();
- if (E->get().function_id>=0) {
+ mi.name = E->key();
+ if (E->get().function_id >= 0) {
- Ref<VisualScriptFunction> func=E->get().nodes[E->get().function_id].node;
+ Ref<VisualScriptFunction> func = E->get().nodes[E->get().function_id].node;
if (func.is_valid()) {
- for(int i=0;i<func->get_argument_count();i++) {
+ for (int i = 0; i < func->get_argument_count(); i++) {
PropertyInfo arg;
- arg.name=func->get_argument_name(i);
- arg.type=func->get_argument_type(i);
+ arg.name = func->get_argument_name(i);
+ arg.type = func->get_argument_type(i);
mi.arguments.push_back(arg);
}
}
@@ -1152,7 +1065,7 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const {
List<StringName> vars;
get_variable_list(&vars);
- for (List<StringName>::Element *E=vars.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
if (!variables[E->get()]._export)
continue;
p_list->push_back(variables[E->get()].info);
@@ -1162,9 +1075,9 @@ void VisualScript::get_script_property_list(List<PropertyInfo> *p_list) const {
#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<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()) {
+ for (const Map<int, Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
if (F->get().node->is_edited()) {
return true;
}
@@ -1175,324 +1088,296 @@ bool VisualScript::are_subnodes_edited() const {
}
#endif
-void VisualScript::_set_data(const Dictionary& p_data) {
+void VisualScript::_set_data(const Dictionary &p_data) {
Dictionary d = p_data;
if (d.has("base_type"))
- base_type=d["base_type"];
+ base_type = d["base_type"];
variables.clear();
- Array vars=d["variables"];
- for (int i=0;i<vars.size();i++) {
+ Array vars = d["variables"];
+ for (int i = 0; i < vars.size(); i++) {
- Dictionary v=vars[i];
+ Dictionary v = vars[i];
StringName name = v["name"];
add_variable(name);
- _set_variable_info(name,v);
- set_variable_default_value(name,v["default_value"]);
- set_variable_export(name,v.has("export") && bool(v["export"]));
-
+ _set_variable_info(name, v);
+ set_variable_default_value(name, v["default_value"]);
+ set_variable_export(name, v.has("export") && bool(v["export"]));
}
-
custom_signals.clear();
- Array sigs=d["signals"];
- for (int i=0;i<sigs.size();i++) {
+ Array sigs = d["signals"];
+ for (int i = 0; i < sigs.size(); i++) {
- Dictionary cs=sigs[i];
+ Dictionary cs = sigs[i];
add_custom_signal(cs["name"]);
- Array args=cs["arguments"];
- for(int j=0;j<args.size();j+=2) {
- custom_signal_add_argument(cs["name"],Variant::Type(int(args[j+1])),args[j]);
+ Array args = cs["arguments"];
+ for (int j = 0; j < args.size(); j += 2) {
+ custom_signal_add_argument(cs["name"], Variant::Type(int(args[j + 1])), args[j]);
}
}
- Array funcs=d["functions"];
+ Array funcs = d["functions"];
functions.clear();
- for (int i=0;i<funcs.size();i++) {
+ for (int i = 0; i < funcs.size(); i++) {
- Dictionary func=funcs[i];
+ Dictionary func = funcs[i];
-
- StringName name=func["name"];
+ StringName name = func["name"];
//int id=func["function_id"];
add_function(name);
- set_function_scroll(name,func["scroll"]);
+ set_function_scroll(name, func["scroll"]);
Array nodes = func["nodes"];
- for(int i=0;i<nodes.size();i+=3) {
+ for (int i = 0; i < nodes.size(); i += 3) {
- add_node(name,nodes[i],nodes[i+2],nodes[i+1]);
+ add_node(name, nodes[i], nodes[i + 2], nodes[i + 1]);
}
+ Array sequence_connections = func["sequence_connections"];
- Array sequence_connections=func["sequence_connections"];
-
- for (int j=0;j<sequence_connections.size();j+=3) {
+ 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(name, sequence_connections[j + 0], sequence_connections[j + 1], sequence_connections[j + 2]);
}
+ Array data_connections = func["data_connections"];
- Array data_connections=func["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]);
+ 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]);
}
-
-
}
-
}
-Dictionary VisualScript::_get_data() const{
+Dictionary VisualScript::_get_data() const {
Dictionary d;
- d["base_type"]=base_type;
+ d["base_type"] = base_type;
Array vars;
- for (const Map<StringName,Variable>::Element *E=variables.front();E;E=E->next()) {
+ 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;
+ var["name"] = E->key(); //make sure it's the right one
+ var["default_value"] = E->get().default_value;
+ var["export"] = E->get()._export;
vars.push_back(var);
}
- d["variables"]=vars;
+ d["variables"] = vars;
Array sigs;
- for (const Map<StringName,Vector<Argument> >::Element *E=custom_signals.front();E;E=E->next()) {
+ for (const Map<StringName, Vector<Argument> >::Element *E = custom_signals.front(); E; E = E->next()) {
Dictionary cs;
- cs["name"]=E->key();
+ cs["name"] = E->key();
Array args;
- for(int i=0;i<E->get().size();i++) {
+ for (int i = 0; i < E->get().size(); i++) {
args.push_back(E->get()[i].name);
args.push_back(E->get()[i].type);
}
- cs["arguments"]=args;
+ cs["arguments"] = args;
sigs.push_back(cs);
}
- d["signals"]=sigs;
+ d["signals"] = sigs;
Array funcs;
- for (const Map<StringName,Function>::Element *E=functions.front();E;E=E->next()) {
+ for (const Map<StringName, Function>::Element *E = functions.front(); E; E = E->next()) {
Dictionary func;
- func["name"]=E->key();
- func["function_id"]=E->get().function_id;
- func["scroll"]=E->get().scroll;
+ 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()) {
+ 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;
+ func["nodes"] = nodes;
Array sequence_connections;
- for (const Set<SequenceConnection>::Element *F=E->get().sequence_connections.front();F;F=F->next()) {
+ 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;
+ func["sequence_connections"] = sequence_connections;
Array data_connections;
- for (const Set<DataConnection>::Element *F=E->get().data_connections.front();F;F=F->next()) {
+ for (const Set<DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) {
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);
-
}
-
- func["data_connections"]=data_connections;
+ func["data_connections"] = data_connections;
funcs.push_back(func);
-
}
- d["functions"]=funcs;
-
+ d["functions"] = funcs;
return d;
-
}
void VisualScript::_bind_methods() {
-
-
- ClassDB::bind_method(D_METHOD("_node_ports_changed"),&VisualScript::_node_ports_changed);
-
- ClassDB::bind_method(D_METHOD("add_function","name"),&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","ofs"),&VisualScript::set_function_scroll);
- ClassDB::bind_method(D_METHOD("get_function_scroll"),&VisualScript::get_function_scroll);
-
- ClassDB::bind_method(D_METHOD("add_node","func","id","node","pos"),&VisualScript::add_node,DEFVAL(Point2()));
- ClassDB::bind_method(D_METHOD("remove_node","func","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_pos","func","id","pos"),&VisualScript::set_node_pos);
- ClassDB::bind_method(D_METHOD("get_node_pos","func","id"),&VisualScript::get_node_pos);
-
- 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("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("add_variable","name","default_value","export"),&VisualScript::add_variable,DEFVAL(Variant()),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("has_variable","name"),&VisualScript::has_variable);
- ClassDB::bind_method(D_METHOD("remove_variable","name"),&VisualScript::remove_variable);
- ClassDB::bind_method(D_METHOD("set_variable_default_value","name","value"),&VisualScript::set_variable_default_value);
- ClassDB::bind_method(D_METHOD("get_variable_default_value","name"),&VisualScript::get_variable_default_value);
- ClassDB::bind_method(D_METHOD("set_variable_info","name","value"),&VisualScript::_set_variable_info);
- ClassDB::bind_method(D_METHOD("get_variable_info","name"),&VisualScript::_get_variable_info);
- ClassDB::bind_method(D_METHOD("set_variable_export","name","enable"),&VisualScript::set_variable_export);
- ClassDB::bind_method(D_METHOD("get_variable_export","name"),&VisualScript::get_variable_export);
- ClassDB::bind_method(D_METHOD("rename_variable","name","new_name"),&VisualScript::rename_variable);
-
- ClassDB::bind_method(D_METHOD("add_custom_signal","name"),&VisualScript::add_custom_signal);
- ClassDB::bind_method(D_METHOD("has_custom_signal","name"),&VisualScript::has_custom_signal);
- ClassDB::bind_method(D_METHOD("custom_signal_add_argument","name","type","argname","index"),&VisualScript::custom_signal_add_argument,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("custom_signal_set_argument_type","name","argidx","type"),&VisualScript::custom_signal_set_argument_type);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_type","name","argidx"),&VisualScript::custom_signal_get_argument_type);
- ClassDB::bind_method(D_METHOD("custom_signal_set_argument_name","name","argidx","argname"),&VisualScript::custom_signal_set_argument_name);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_name","name","argidx"),&VisualScript::custom_signal_get_argument_name);
- ClassDB::bind_method(D_METHOD("custom_signal_remove_argument","argidx"),&VisualScript::custom_signal_remove_argument);
- ClassDB::bind_method(D_METHOD("custom_signal_get_argument_count","name"),&VisualScript::custom_signal_get_argument_count);
- ClassDB::bind_method(D_METHOD("custom_signal_swap_argument","name","argidx","withidx"),&VisualScript::custom_signal_swap_argument);
- ClassDB::bind_method(D_METHOD("remove_custom_signal","name"),&VisualScript::remove_custom_signal);
- ClassDB::bind_method(D_METHOD("rename_custom_signal","name","new_name"),&VisualScript::rename_custom_signal);
+ ClassDB::bind_method(D_METHOD("_node_ports_changed"), &VisualScript::_node_ports_changed);
+
+ ClassDB::bind_method(D_METHOD("add_function", "name"), &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", "ofs"), &VisualScript::set_function_scroll);
+ ClassDB::bind_method(D_METHOD("get_function_scroll"), &VisualScript::get_function_scroll);
+
+ ClassDB::bind_method(D_METHOD("add_node", "func", "id", "node", "pos"), &VisualScript::add_node, DEFVAL(Point2()));
+ ClassDB::bind_method(D_METHOD("remove_node", "func", "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_pos", "func", "id", "pos"), &VisualScript::set_node_pos);
+ ClassDB::bind_method(D_METHOD("get_node_pos", "func", "id"), &VisualScript::get_node_pos);
+
+ 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("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("add_variable", "name", "default_value", "export"), &VisualScript::add_variable, DEFVAL(Variant()), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("has_variable", "name"), &VisualScript::has_variable);
+ ClassDB::bind_method(D_METHOD("remove_variable", "name"), &VisualScript::remove_variable);
+ ClassDB::bind_method(D_METHOD("set_variable_default_value", "name", "value"), &VisualScript::set_variable_default_value);
+ ClassDB::bind_method(D_METHOD("get_variable_default_value", "name"), &VisualScript::get_variable_default_value);
+ ClassDB::bind_method(D_METHOD("set_variable_info", "name", "value"), &VisualScript::_set_variable_info);
+ ClassDB::bind_method(D_METHOD("get_variable_info", "name"), &VisualScript::_get_variable_info);
+ ClassDB::bind_method(D_METHOD("set_variable_export", "name", "enable"), &VisualScript::set_variable_export);
+ ClassDB::bind_method(D_METHOD("get_variable_export", "name"), &VisualScript::get_variable_export);
+ ClassDB::bind_method(D_METHOD("rename_variable", "name", "new_name"), &VisualScript::rename_variable);
+
+ ClassDB::bind_method(D_METHOD("add_custom_signal", "name"), &VisualScript::add_custom_signal);
+ ClassDB::bind_method(D_METHOD("has_custom_signal", "name"), &VisualScript::has_custom_signal);
+ ClassDB::bind_method(D_METHOD("custom_signal_add_argument", "name", "type", "argname", "index"), &VisualScript::custom_signal_add_argument, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("custom_signal_set_argument_type", "name", "argidx", "type"), &VisualScript::custom_signal_set_argument_type);
+ ClassDB::bind_method(D_METHOD("custom_signal_get_argument_type", "name", "argidx"), &VisualScript::custom_signal_get_argument_type);
+ ClassDB::bind_method(D_METHOD("custom_signal_set_argument_name", "name", "argidx", "argname"), &VisualScript::custom_signal_set_argument_name);
+ ClassDB::bind_method(D_METHOD("custom_signal_get_argument_name", "name", "argidx"), &VisualScript::custom_signal_get_argument_name);
+ ClassDB::bind_method(D_METHOD("custom_signal_remove_argument", "argidx"), &VisualScript::custom_signal_remove_argument);
+ ClassDB::bind_method(D_METHOD("custom_signal_get_argument_count", "name"), &VisualScript::custom_signal_get_argument_count);
+ ClassDB::bind_method(D_METHOD("custom_signal_swap_argument", "name", "argidx", "withidx"), &VisualScript::custom_signal_swap_argument);
+ ClassDB::bind_method(D_METHOD("remove_custom_signal", "name"), &VisualScript::remove_custom_signal);
+ ClassDB::bind_method(D_METHOD("rename_custom_signal", "name", "new_name"), &VisualScript::rename_custom_signal);
//ClassDB::bind_method(D_METHOD("set_variable_info","name","info"),&VScript::set_variable_info);
//ClassDB::bind_method(D_METHOD("get_variable_info","name"),&VScript::set_variable_info);
- ClassDB::bind_method(D_METHOD("set_instance_base_type","type"),&VisualScript::set_instance_base_type);
+ ClassDB::bind_method(D_METHOD("set_instance_base_type", "type"), &VisualScript::set_instance_base_type);
- ClassDB::bind_method(D_METHOD("_set_data","data"),&VisualScript::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"),&VisualScript::_get_data);
+ ClassDB::bind_method(D_METHOD("_set_data", "data"), &VisualScript::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &VisualScript::_get_data);
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_data","_get_data");
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_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::STRING, "function"), PropertyInfo(Variant::INT, "id")));
}
VisualScript::VisualScript() {
- base_type="Object";
-
+ base_type = "Object";
}
VisualScript::~VisualScript() {
- while(!functions.empty()) {
+ while (!functions.empty()) {
remove_function(functions.front()->key());
}
-
}
////////////////////////////////////////////
+bool VisualScriptInstance::set(const StringName &p_name, const Variant &p_value) {
-
-bool VisualScriptInstance::set(const StringName& p_name, const Variant& p_value) {
-
-
- Map<StringName,Variant>::Element *E=variables.find(p_name);
+ Map<StringName, Variant>::Element *E = variables.find(p_name);
if (!E)
return false;
- E->get()=p_value;
+ E->get() = p_value;
return true;
}
+bool VisualScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
-bool VisualScriptInstance::get(const StringName& p_name, Variant &r_ret) const {
-
- const Map<StringName,Variant>::Element *E=variables.find(p_name);
+ const Map<StringName, Variant>::Element *E = variables.find(p_name);
if (!E)
return false;
- r_ret=E->get();
+ r_ret = E->get();
return true;
}
-void VisualScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const{
+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()) {
+ for (const Map<StringName, VisualScript::Variable>::Element *E = script->variables.front(); E; E = E->next()) {
if (!E->get()._export)
continue;
PropertyInfo p = E->get().info;
- p.name=String(E->key());
+ p.name = String(E->key());
p_properties->push_back(p);
-
}
}
-Variant::Type VisualScriptInstance::get_property_type(const StringName& p_name,bool *r_is_valid) const{
-
+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);
+ const Map<StringName, VisualScript::Variable>::Element *E = script->variables.find(p_name);
if (!E) {
if (r_is_valid)
- *r_is_valid=false;
+ *r_is_valid = false;
ERR_FAIL_V(Variant::NIL);
}
if (r_is_valid)
- *r_is_valid=true;
+ *r_is_valid = true;
return E->get().info.type;
-
}
-void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const{
+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()) {
+ for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.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)) {
+ 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;
if (vsf.is_valid()) {
- for(int i=0;i<vsf->get_argument_count();i++) {
+ for (int i = 0; i < vsf->get_argument_count(); i++) {
PropertyInfo arg;
- arg.name=vsf->get_argument_name(i);
- arg.type=vsf->get_argument_type(i);
+ arg.name = vsf->get_argument_name(i);
+ arg.type = vsf->get_argument_type(i);
mi.arguments.push_back(arg);
}
@@ -1503,136 +1388,127 @@ void VisualScriptInstance::get_method_list(List<MethodInfo> *p_list) const{
p_list->push_back(mi);
}
-
}
-bool VisualScriptInstance::has_method(const StringName& p_method) const{
+bool VisualScriptInstance::has_method(const StringName &p_method) const {
return script->functions.has(p_method);
}
-
//#define VSDEBUG(m_text) print_line(m_text)
#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,Variant::CallError& r_error,String& error_str,VisualScriptNodeInstance** r_error_node) {
+void VisualScriptInstance::_dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Variant::CallError &r_error, String &error_str, VisualScriptNodeInstance **r_error_node) {
- ERR_FAIL_COND(node->pass_idx==-1);
+ 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;
+ pass_stack[node->pass_idx] = p_pass;
if (!node->dependencies.empty()) {
int dc = node->dependencies.size();
- VisualScriptNodeInstance **deps=node->dependencies.ptr();
+ VisualScriptNodeInstance **deps = node->dependencies.ptr();
- for(int i=0;i<dc;i++) {
+ 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!=Variant::CallError::CALL_OK)
+ _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 != Variant::CallError::CALL_OK)
return;
-
}
}
-
- for(int i=0;i<node->input_port_count;i++) {
+ 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)
- input_args[i]=&default_values[index];
+ input_args[i] = &default_values[index];
} else {
//regular temporary in stack
- input_args[i]=&variant_stack[index];
-
+ input_args[i] = &variant_stack[index];
}
}
- for(int i=0 ; i<node->output_port_count ; i++) {
- output_args[i] = &variant_stack[ node->output_ports[i] ];
+ for (int i = 0; i < node->output_port_count; i++) {
+ output_args[i] = &variant_stack[node->output_ports[i]];
}
- Variant *working_mem=node->working_mem_idx>=0 ? &variant_stack[node->working_mem_idx] : (Variant*)NULL;
+ Variant *working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)NULL;
- node->step(input_args,output_args,VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE,working_mem,r_error,error_str);
+ node->step(input_args, output_args, VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE, working_mem, r_error, error_str);
//ignore return
- if (r_error.error!=Variant::CallError::CALL_OK) {
- *r_error_node=node;
+ if (r_error.error != Variant::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, Variant::CallError &r_error) {
+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, Variant::CallError &r_error) {
- Map<StringName,Function>::Element *F = functions.find(p_method);
- ERR_FAIL_COND_V(!F,Variant());
- Function *f=&F->get();
+ 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
- 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);
- Variant **output_args=(Variant**)(input_args + max_input_args);
+ 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);
+ Variant **output_args = (Variant **)(input_args + max_input_args);
int flow_max = f->flow_stack_size;
- int* flow_stack = flow_max? (int*)(output_args + max_output_args) : (int*)NULL;
+ int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL;
int *pass_stack = flow_stack + flow_max;
String error_str;
- VisualScriptNodeInstance* node=p_node;
- bool error=false;
- int current_node_id=f->node;
+ VisualScriptNodeInstance *node = p_node;
+ bool error = false;
+ int current_node_id = f->node;
Variant return_value;
- Variant *working_mem=NULL;
+ Variant *working_mem = NULL;
- int flow_stack_pos=p_flow_stack_pos;
+ int flow_stack_pos = p_flow_stack_pos;
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton()) {
- VisualScriptLanguage::singleton->enter_function(this,&p_method,variant_stack,&working_mem,&current_node_id);
+ VisualScriptLanguage::singleton->enter_function(this, &p_method, variant_stack, &working_mem, &current_node_id);
}
#endif
- while(true) {
+ while (true) {
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));
+ 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
- working_mem=node->working_mem_idx>=0 ? &variant_stack[node->working_mem_idx] : (Variant*)NULL;
+ working_mem = node->working_mem_idx >= 0 ? &variant_stack[node->working_mem_idx] : (Variant *)NULL;
- VSDEBUG("WORKING MEM: "+itos(node->working_mem_idx));
+ VSDEBUG("WORKING MEM: " + itos(node->working_mem_idx));
- if (current_node_id==f->node) {
+ if (current_node_id == f->node) {
//if function node, set up function arguments from begining of stack
- for(int i=0;i<f->argument_count;i++) {
- input_args[i]=&variant_stack[i];
+ for (int i = 0; i < f->argument_count; i++) {
+ input_args[i] = &variant_stack[i];
}
} else {
//run dependencies first
-
if (!node->dependencies.empty()) {
int dc = node->dependencies.size();
- VisualScriptNodeInstance **deps=node->dependencies.ptr();
+ VisualScriptNodeInstance **deps = node->dependencies.ptr();
- for(int i=0;i<dc;i++) {
+ 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!=Variant::CallError::CALL_OK) {
- error=true;
- current_node_id=node->id;
+ _dependency_step(deps[i], p_pass, pass_stack, input_args, output_args, variant_stack, r_error, error_str, &node);
+ if (r_error.error != Variant::CallError::CALL_OK) {
+ error = true;
+ current_node_id = node->id;
break;
}
}
@@ -1641,22 +1517,20 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
if (!error) {
//setup input pointers normally
- VSDEBUG("INPUT PORTS: "+itos(node->input_port_count));
-
- for(int i=0 ; i<node->input_port_count ; i++) {
+ 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)
- input_args[i]=&default_values[index];
- VSDEBUG("\tPORT "+itos(i)+" DEFAULT VAL");
+ input_args[i] = &default_values[index];
+ VSDEBUG("\tPORT " + itos(i) + " DEFAULT VAL");
} else {
//regular temporary in stack
- input_args[i]=&variant_stack[index];
- VSDEBUG("PORT "+itos(i)+" AT STACK "+itos(index));
-
+ input_args[i] = &variant_stack[index];
+ VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(index));
}
}
}
@@ -1667,10 +1541,10 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
//setup output pointers
- VSDEBUG("OUTPUT PORTS: "+itos(node->output_port_count));
- for(int i=0 ; i<node->output_port_count ; i++) {
- output_args[i] = &variant_stack[ node->output_ports[i] ];
- VSDEBUG("PORT "+itos(i)+" AT STACK "+itos(node->output_ports[i]));
+ VSDEBUG("OUTPUT PORTS: " + itos(node->output_port_count));
+ for (int i = 0; i < node->output_port_count; i++) {
+ output_args[i] = &variant_stack[node->output_ports[i]];
+ VSDEBUG("PORT " + itos(i) + " AT STACK " + itos(node->output_ports[i]));
}
//do step
@@ -1678,57 +1552,55 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
VisualScriptNodeInstance::StartMode start_mode;
{
if (p_resuming_yield)
- start_mode=VisualScriptNodeInstance::START_MODE_RESUME_YIELD;
+ start_mode = VisualScriptNodeInstance::START_MODE_RESUME_YIELD;
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
- start_mode=VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE;
+ start_mode = VisualScriptNodeInstance::START_MODE_BEGIN_SEQUENCE;
else
- start_mode=VisualScriptNodeInstance::START_MODE_CONTINUE_SEQUENCE;
+ start_mode = VisualScriptNodeInstance::START_MODE_CONTINUE_SEQUENCE;
}
- VSDEBUG("STEP - STARTSEQ: "+itos(start_mode));
+ VSDEBUG("STEP - STARTSEQ: " + itos(start_mode));
- int ret = node->step(input_args,output_args,start_mode,working_mem,r_error,error_str);
+ int ret = node->step(input_args, output_args, start_mode, working_mem, r_error, error_str);
- if (r_error.error!=Variant::CallError::CALL_OK) {
+ if (r_error.error != Variant::CallError::CALL_OK) {
//use error from step
- error=true;
+ error = true;
break;
}
- if (ret&VisualScriptNodeInstance::STEP_YIELD_BIT) {
+ if (ret & VisualScriptNodeInstance::STEP_YIELD_BIT) {
//yielded!
- if (node->get_working_memory_size()==0) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- error_str=RTR("A node yielded without working memory, please read the docs on how to yield properly!");
- error=true;
+ if (node->get_working_memory_size() == 0) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ error_str = RTR("A node yielded without working memory, please read the docs on how to yield properly!");
+ error = true;
break;
} else {
Ref<VisualScriptFunctionState> state = *working_mem;
if (!state.is_valid()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- error_str=RTR("Node yielded, but did not return a function state in the first working memory.");
- error=true;
+ r_error.error = Variant::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
- state->instance_id=get_owner_ptr()->get_instance_ID();
- state->script_id=get_script()->get_instance_ID();
- state->instance=this;
- state->function=p_method;
- state->working_mem_index=node->working_mem_idx;
- state->variant_stack_size=f->max_stack;
- state->node=node;
- state->flow_stack_pos=flow_stack_pos;
+ state->instance_id = get_owner_ptr()->get_instance_ID();
+ state->script_id = get_script()->get_instance_ID();
+ state->instance = this;
+ state->function = p_method;
+ state->working_mem_index = node->working_mem_idx;
+ state->variant_stack_size = f->max_stack;
+ state->node = node;
+ state->flow_stack_pos = flow_stack_pos;
state->stack.resize(p_stack_size);
- state->pass=p_pass;
- copymem(state->stack.ptr(),p_stack,p_stack_size);
+ state->pass = p_pass;
+ copymem(state->stack.ptr(), p_stack, p_stack_size);
//step 2, run away, return directly
- r_error.error=Variant::CallError::CALL_OK;
-
+ r_error.error = Variant::CallError::CALL_OK;
#ifdef DEBUG_ENABLED
//will re-enter later, so exiting
@@ -1738,67 +1610,65 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
#endif
return state;
-
}
}
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton()) {
// line
- bool do_break=false;
+ bool do_break = false;
- if (ScriptDebugger::get_singleton()->get_lines_left()>0) {
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0) {
- if (ScriptDebugger::get_singleton()->get_depth()<=0)
- ScriptDebugger::get_singleton()->set_lines_left( ScriptDebugger::get_singleton()->get_lines_left() -1 );
- if (ScriptDebugger::get_singleton()->get_lines_left()<=0)
- do_break=true;
+ if (ScriptDebugger::get_singleton()->get_depth() <= 0)
+ ScriptDebugger::get_singleton()->set_lines_left(ScriptDebugger::get_singleton()->get_lines_left() - 1);
+ if (ScriptDebugger::get_singleton()->get_lines_left() <= 0)
+ do_break = true;
}
- if (ScriptDebugger::get_singleton()->is_breakpoint(current_node_id,source))
- do_break=true;
+ if (ScriptDebugger::get_singleton()->is_breakpoint(current_node_id, source))
+ do_break = true;
if (do_break) {
- VisualScriptLanguage::singleton->debug_break("Breakpoint",true);
+ VisualScriptLanguage::singleton->debug_break("Breakpoint", true);
}
ScriptDebugger::get_singleton()->line_poll();
-
}
#endif
int output = ret & VisualScriptNodeInstance::STEP_MASK;
- VSDEBUG("STEP RETURN: "+itos(ret));
+ VSDEBUG("STEP RETURN: " + itos(ret));
if (ret & VisualScriptNodeInstance::STEP_EXIT_FUNCTION_BIT) {
- if (node->get_working_memory_size()==0) {
+ if (node->get_working_memory_size() == 0) {
- r_error.error=Variant::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;
+ r_error.error = Variant::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
- return_value=*working_mem;
+ return_value = *working_mem;
}
- VSDEBUG("EXITING FUNCTION - VALUE "+String(return_value));
+ VSDEBUG("EXITING FUNCTION - VALUE " + String(return_value));
break; //exit function requested, bye
}
- VisualScriptNodeInstance *next=NULL; //next node
+ VisualScriptNodeInstance *next = NULL; //next node
- if ( (ret==output || ret&VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) {
+ if ((ret == output || ret & VisualScriptNodeInstance::STEP_FLAG_PUSH_STACK_BIT) && node->sequence_output_count) {
//if no exit bit was set, and has sequence outputs, guess next node
- if (output<0 || output>=node->sequence_output_count) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- error_str=RTR("Node returned an invalid sequence output: ")+itos(output);
- error=true;
+ if (output < 0 || output >= node->sequence_output_count) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ error_str = RTR("Node returned an invalid sequence output: ") + itos(output);
+ error = true;
break;
}
next = node->sequence_outputs[output];
if (next) {
- VSDEBUG("GOT NEXT NODE - "+itos(next->get_id()));
+ VSDEBUG("GOT NEXT NODE - " + itos(next->get_id()));
} else {
VSDEBUG("GOT NEXT NODE - NULL");
}
@@ -1813,20 +1683,19 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
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
- if (flow_stack_pos>0) {
+ if (flow_stack_pos > 0) {
flow_stack_pos--;
- node = instances[ flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_MASK ];
+ node = instances[flow_stack[flow_stack_pos] & VisualScriptNodeInstance::FLOW_STACK_MASK];
VSDEBUG("NEXT IS GO BACK");
} else {
VSDEBUG("NEXT IS GO BACK, BUT NO NEXT SO EXIT");
@@ -1834,7 +1703,6 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
}
} 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
// because each node has a working memory, we can't really do a sub-sequence
@@ -1843,43 +1711,41 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
bool found = false;
- for(int i=flow_stack_pos;i>=0;i--) {
-
+ 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[i]=next->get_id();
- sequence_bits[next->sequence_index]=false;
- found=true;
+ if ((flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK) == next->get_id()) {
+ flow_stack_pos = i; //roll back and remove bit
+ flow_stack[i] = next->get_id();
+ sequence_bits[next->sequence_index] = false;
+ found = true;
}
}
if (!found) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- error_str=RTR("Found sequence bit but not the node in the stack, report bug!");
- error=true;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ error_str = RTR("Found sequence bit but not the node in the stack, report bug!");
+ error = true;
break;
}
- node=next;
- VSDEBUG("RE-ENTERED A LOOP, RETURNED STACK POS TO - "+itos(flow_stack_pos));
+ node = next;
+ VSDEBUG("RE-ENTERED A LOOP, RETURNED STACK POS TO - " + itos(flow_stack_pos));
} else {
// check for stack overflow
- if (flow_stack_pos+1 >= flow_max) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- error_str=RTR("Stack overflow with stack depth: ")+itos(output);
- error=true;
+ if (flow_stack_pos + 1 >= flow_max) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ error_str = RTR("Stack overflow with stack depth: ") + itos(output);
+ error = true;
break;
}
node = next;
flow_stack_pos++;
- flow_stack[flow_stack_pos]=node->get_id();
+ flow_stack[flow_stack_pos] = node->get_id();
VSDEBUG("INCREASE FLOW STACK");
-
}
} else {
@@ -1887,14 +1753,14 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
bool found = false;
- for(int i=flow_stack_pos;i>=0;i--) {
+ for (int i = flow_stack_pos; i >= 0; i--) {
- VSDEBUG("FS "+itos(i)+" - "+itos(flow_stack[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;
+ node = instances[flow_stack[i] & VisualScriptNodeInstance::FLOW_STACK_MASK];
+ flow_stack_pos = i;
+ found = true;
break;
}
}
@@ -1904,59 +1770,53 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
break; //done, couldn't find a push stack bit
}
- VSDEBUG("NO NEXT NODE, GO BACK TO: "+itos(flow_stack_pos));
-
+ 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
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!=Variant::CallError::CALL_ERROR_INVALID_METHOD || error_str==String())) {
+ if (node && (r_error.error != Variant::CallError::CALL_ERROR_INVALID_METHOD || error_str == String())) {
- if (error_str!=String()) {
- error_str+=" ";
+ if (error_str != String()) {
+ error_str += " ";
}
- if (r_error.error==Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
- int errorarg=r_error.argument;
- error_str+="Cannot convert argument "+itos(errorarg+1)+" to "+Variant::get_type_name(r_error.expected)+".";
- } else if (r_error.error==Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
- error_str+="Expected "+itos(r_error.argument)+" arguments.";
- } else if (r_error.error==Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
- error_str+="Expected "+itos(r_error.argument)+" arguments.";
- } else if (r_error.error==Variant::CallError::CALL_ERROR_INVALID_METHOD) {
- error_str+="Invalid Call.";
- } else if (r_error.error==Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
- error_str+="Base Instance is null";
+ if (r_error.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
+ int errorarg = r_error.argument;
+ error_str += "Cannot convert argument " + itos(errorarg + 1) + " to " + Variant::get_type_name(r_error.expected) + ".";
+ } else if (r_error.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
+ error_str += "Expected " + itos(r_error.argument) + " arguments.";
+ } else if (r_error.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
+ error_str += "Expected " + itos(r_error.argument) + " arguments.";
+ } else if (r_error.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
+ error_str += "Invalid Call.";
+ } else if (r_error.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
+ error_str += "Base Instance is null";
}
}
-
//if (!GDScriptLanguage::get_singleton()->debug_break(err_text,false)) {
- // debugger break did not happen
+ // debugger break did not happen
- if (!VisualScriptLanguage::singleton->debug_break(error_str,false)) {
+ 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);
+ _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=
}
@@ -1967,64 +1827,62 @@ Variant VisualScriptInstance::_call_internal(const StringName& p_method, void* p
#endif
//clean up variant stack
- for(int i=0;i<f->max_stack;i++) {
+ for (int i = 0; i < f->max_stack; i++) {
variant_stack[i].~Variant();
}
-
return return_value;
}
+Variant VisualScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant VisualScriptInstance::call(const StringName& p_method, const Variant** p_args, int p_argcount, Variant::CallError &r_error){
+ r_error.error = Variant::CallError::CALL_OK; //ok by default
- r_error.error=Variant::CallError::CALL_OK; //ok by default
-
- Map<StringName,Function>::Element *F = functions.find(p_method);
+ Map<StringName, Function>::Element *F = functions.find(p_method);
if (!F) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
}
- VSDEBUG("CALLING: "+String(p_method));
+ VSDEBUG("CALLING: " + String(p_method));
- Function *f=&F->get();
+ Function *f = &F->get();
- int total_stack_size=0;
+ int total_stack_size = 0;
- total_stack_size+=f->max_stack*sizeof(Variant); //variants
- total_stack_size+=f->node_count*sizeof(bool);
- total_stack_size+=(max_input_args+max_output_args)*sizeof(Variant*); //arguments
- total_stack_size+=f->flow_stack_size*sizeof(int); //flow
- total_stack_size+=f->pass_stack_size*sizeof(int);
+ total_stack_size += f->max_stack * sizeof(Variant); //variants
+ total_stack_size += f->node_count * sizeof(bool);
+ total_stack_size += (max_input_args + max_output_args) * sizeof(Variant *); //arguments
+ total_stack_size += f->flow_stack_size * sizeof(int); //flow
+ total_stack_size += f->pass_stack_size * sizeof(int);
- VSDEBUG("STACK SIZE: "+itos(total_stack_size));
- VSDEBUG("STACK VARIANTS: : "+itos(f->max_stack));
- VSDEBUG("SEQBITS: : "+itos(f->node_count));
- VSDEBUG("MAX INPUT: "+itos(max_input_args));
- VSDEBUG("MAX OUTPUT: "+itos(max_output_args));
- VSDEBUG("FLOW STACK SIZE: "+itos(f->flow_stack_size));
- VSDEBUG("PASS STACK SIZE: "+itos(f->pass_stack_size));
+ VSDEBUG("STACK SIZE: " + itos(total_stack_size));
+ VSDEBUG("STACK VARIANTS: : " + itos(f->max_stack));
+ VSDEBUG("SEQBITS: : " + itos(f->node_count));
+ VSDEBUG("MAX INPUT: " + itos(max_input_args));
+ VSDEBUG("MAX OUTPUT: " + itos(max_output_args));
+ VSDEBUG("FLOW STACK SIZE: " + itos(f->flow_stack_size));
+ VSDEBUG("PASS STACK SIZE: " + itos(f->pass_stack_size));
void *stack = alloca(total_stack_size);
- Variant *variant_stack=(Variant*)stack;
- bool *sequence_bits = (bool*)(variant_stack + f->max_stack);
- const Variant **input_args=(const Variant**)(sequence_bits+f->node_count);
- Variant **output_args=(Variant**)(input_args + max_input_args);
+ Variant *variant_stack = (Variant *)stack;
+ bool *sequence_bits = (bool *)(variant_stack + f->max_stack);
+ const Variant **input_args = (const Variant **)(sequence_bits + f->node_count);
+ Variant **output_args = (Variant **)(input_args + max_input_args);
int flow_max = f->flow_stack_size;
- int* flow_stack = flow_max? (int*)(output_args + max_output_args) : (int*)NULL;
+ int *flow_stack = flow_max ? (int *)(output_args + max_output_args) : (int *)NULL;
int *pass_stack = flow_stack + flow_max;
- for(int i=0;i<f->node_count;i++) {
- sequence_bits[i]=false; //all starts as false
+ for (int i = 0; i < f->node_count; i++) {
+ sequence_bits[i] = false; //all starts as false
}
- zeromem(pass_stack,f->pass_stack_size*sizeof(int));
+ zeromem(pass_stack, f->pass_stack_size * sizeof(int));
- Map<int,VisualScriptNodeInstance*>::Element *E = instances.find(f->node);
+ Map<int, VisualScriptNodeInstance *>::Element *E = instances.find(f->node);
if (!E) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
ERR_EXPLAIN("No VisualScriptFunction node in function!");
ERR_FAIL_V(Variant());
@@ -2032,66 +1890,62 @@ Variant VisualScriptInstance::call(const StringName& p_method, const Variant** p
VisualScriptNodeInstance *node = E->get();
-
- if (flow_stack) {
- flow_stack[0]=node->get_id();
+ if (flow_stack) {
+ flow_stack[0] = node->get_id();
}
- VSDEBUG("ARGUMENTS: "+itos(f->argument_count)=" RECEIVED: "+itos(p_argcount));
+ VSDEBUG("ARGUMENTS: " + itos(f->argument_count) = " RECEIVED: " + itos(p_argcount));
- if (p_argcount<f->argument_count) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=node->get_input_port_count();
+ if (p_argcount < f->argument_count) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = node->get_input_port_count();
return Variant();
}
- if (p_argcount>f->argument_count) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=node->get_input_port_count();
+ if (p_argcount > f->argument_count) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = node->get_input_port_count();
return Variant();
}
//allocate variant stack
- for(int i=0;i<f->max_stack;i++) {
- memnew_placement(&variant_stack[i],Variant);
+ 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)
- for(int i=0;i<p_argcount;i++) {
- variant_stack[i]=*p_args[i];
+ for (int i = 0; i < p_argcount; i++) {
+ variant_stack[i] = *p_args[i];
}
- return _call_internal(p_method,stack,total_stack_size,node,0,0,false,r_error);
-
-
+ return _call_internal(p_method, stack, total_stack_size, node, 0, 0, false, r_error);
}
-void VisualScriptInstance::notification(int p_notification){
+void VisualScriptInstance::notification(int p_notification) {
//do nothing as this is called using virtual
- Variant what=p_notification;
- const Variant*whatp=&what;
+ Variant what = p_notification;
+ const Variant *whatp = &what;
Variant::CallError ce;
- call(VisualScriptLanguage::singleton->notification,&whatp,1,ce); //do as call
-
+ call(VisualScriptLanguage::singleton->notification, &whatp, 1, ce); //do as call
}
-Ref<Script> VisualScriptInstance::get_script() const{
+Ref<Script> VisualScriptInstance::get_script() const {
return script;
}
-ScriptInstance::RPCMode VisualScriptInstance::get_rpc_mode(const StringName& p_method) const {
+ScriptInstance::RPCMode VisualScriptInstance::get_rpc_mode(const StringName &p_method) const {
- const Map<StringName,VisualScript::Function>::Element *E = script->functions.find(p_method);
+ const Map<StringName, VisualScript::Function>::Element *E = script->functions.find(p_method);
if (!E) {
return RPC_MODE_DISABLED;
}
- if (E->get().function_id>=0 && E->get().nodes.has(E->get().function_id)) {
+ 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;
if (vsf.is_valid()) {
@@ -2103,24 +1957,23 @@ ScriptInstance::RPCMode VisualScriptInstance::get_rpc_mode(const StringName& p_m
return RPC_MODE_DISABLED;
}
-ScriptInstance::RPCMode VisualScriptInstance::get_rset_mode(const StringName& p_variable) const {
+ScriptInstance::RPCMode VisualScriptInstance::get_rset_mode(const StringName &p_variable) const {
return RPC_MODE_DISABLED;
}
+void VisualScriptInstance::create(const Ref<VisualScript> &p_script, Object *p_owner) {
-void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_owner) {
-
- script=p_script;
- owner=p_owner;
- source=p_script->get_path();
+ script = p_script;
+ owner = p_owner;
+ source = p_script->get_path();
max_input_args = 0;
max_output_args = 0;
if (p_owner->cast_to<Node>()) {
//turn on these if they exist and base is a node
- Node* node = p_owner->cast_to<Node>();
+ Node *node = p_owner->cast_to<Node>();
if (p_script->functions.has("_process"))
node->set_process(true);
if (p_script->functions.has("_fixed_process"))
@@ -2133,86 +1986,81 @@ void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_ow
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::Variable>::Element *E = script->variables.front(); E; E = E->next()) {
+ variables[E->key()] = E->get().default_value;
//no hacer que todo exporte, solo las que queres!
}
-
- for(const Map<StringName,VisualScript::Function>::Element *E=script->functions.front();E;E=E->next()) {
+ for (const Map<StringName, VisualScript::Function>::Element *E = script->functions.front(); E; E = E->next()) {
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;
+ 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()));
+ 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 );
+ ERR_CONTINUE(function.node < 0);
}
{
- Ref<VisualScriptFunction> func_node = script->get_node(E->key(),E->get().function_id);
+ 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()));
+ VisualScriptLanguage::singleton->debug_break_parse(get_script()->get_path(), 0, "No VisualScriptFunction typed start node in function: " + String(E->key()));
}
- 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();
+ 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();
}
//multiple passes are required to set up this complex thing..
-
-
-
//first create the nodes
- for (const Map<int,VisualScript::Function::NodeData>::Element *F=E->get().nodes.front();F;F=F->next()) {
+ 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->base = node.ptr();
- instance->id=F->key();
+ instance->id = F->key();
instance->input_port_count = node->get_input_value_port_count();
- instance->input_ports=NULL;
+ instance->input_ports = NULL;
instance->output_port_count = node->get_output_value_port_count();
- instance->output_ports=NULL;
+ 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;
+ 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 = 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->input_ports[i] = -1; //if not assigned, will become default value
+ }
}
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
+ 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
}
}
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
+ 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
}
}
@@ -2228,32 +2076,30 @@ void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_ow
var_name = String(node->cast_to<VisualScriptLocalVarSet>()->get_var_name()).strip_edges();
if (!local_var_indices.has(var_name)) {
- local_var_indices[var_name]=function.max_stack;
+ local_var_indices[var_name] = function.max_stack;
function.max_stack++;
}
- instance->working_mem_idx=local_var_indices[var_name];
+ instance->working_mem_idx = local_var_indices[var_name];
} else if (instance->get_working_memory_size()) {
instance->working_mem_idx = function.max_stack;
- function.max_stack+=instance->get_working_memory_size();
+ function.max_stack += instance->get_working_memory_size();
} else {
- instance->working_mem_idx=-1; //no working mem
+ instance->working_mem_idx = -1; //no working mem
}
- max_input_args = MAX( max_input_args, instance->input_port_count );
- max_output_args = MAX( max_output_args, instance->output_port_count );
-
- instances[F->key()]=instance;
-
+ max_input_args = MAX(max_input_args, instance->input_port_count);
+ max_output_args = MAX(max_output_args, instance->output_port_count);
+ instances[F->key()] = instance;
}
function.trash_pos = function.max_stack++; //create pos for trash
//second pass, do data connections
- for(const Set<VisualScript::DataConnection>::Element *F=E->get().data_connections.front();F;F=F->next()) {
+ for (const Set<VisualScript::DataConnection>::Element *F = E->get().data_connections.front(); F; F = F->next()) {
VisualScript::DataConnection dc = F->get();
ERR_CONTINUE(!instances.has(dc.from_node));
@@ -2263,29 +2109,27 @@ void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_ow
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) {
+ if (from->output_ports[dc.from_port] == -1) {
int stack_pos = function.max_stack++;
from->output_ports[dc.from_port] = stack_pos;
}
-
- if (from->get_sequence_output_count()==0 && to->dependencies.find(from)==-1) {
+ 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;
+ if (from->pass_idx == -1) {
+ from->pass_idx = function.pass_stack_size;
function.pass_stack_size++;
}
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()) {
+ 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));
@@ -2294,16 +2138,14 @@ void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_ow
VisualScriptNodeInstance *to = instances[sc.to_node];
ERR_CONTINUE(sc.from_output >= from->sequence_output_count);
- from->sequence_outputs[sc.from_output]=to;
-
+ from->sequence_outputs[sc.from_output] = to;
}
//fourth pass:
// 1) unassigned input ports to default values
// 2) connect unassigned output ports to trash
-
- for (const Map<int,VisualScript::Function::NodeData>::Element *F=E->get().nodes.front();F;F=F->next()) {
+ for (const Map<int, VisualScript::Function::NodeData>::Element *F = E->get().nodes.front(); F; F = F->next()) {
ERR_CONTINUE(!instances.has(F->key()));
@@ -2311,37 +2153,33 @@ void VisualScriptInstance::create(const Ref<VisualScript>& p_script,Object *p_ow
VisualScriptNodeInstance *instance = instances[F->key()];
// conect to default values
- for(int i=0;i<instance->input_port_count;i++) {
- if (instance->input_ports[i]==-1) {
+ 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) );
+ default_values.push_back(node->get_default_input_value(i));
}
}
// conect to trash
- for(int i=0;i<instance->output_port_count;i++) {
- if (instance->output_ports[i]==-1) {
+ 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->key()] = function;
}
}
-ScriptLanguage *VisualScriptInstance::get_language(){
+ScriptLanguage *VisualScriptInstance::get_language() {
return VisualScriptLanguage::singleton;
}
-
VisualScriptInstance::VisualScriptInstance() {
-
-
}
VisualScriptInstance::~VisualScriptInstance() {
@@ -2354,22 +2192,18 @@ VisualScriptInstance::~VisualScriptInstance() {
if (VisualScriptLanguage::singleton->lock)
VisualScriptLanguage::singleton->lock->unlock();
- for (Map<int,VisualScriptNodeInstance*>::Element *E=instances.front();E;E=E->next()) {
+ for (Map<int, VisualScriptNodeInstance *>::Element *E = instances.front(); E; E = E->next()) {
memdelete(E->get());
}
}
-
-
/////////////////////////////////////////////
-
/////////////////////
+Variant VisualScriptFunctionState::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant VisualScriptFunctionState::_signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- ERR_FAIL_COND_V(function==StringName(),Variant());
+ ERR_FAIL_COND_V(function == StringName(), Variant());
#ifdef DEBUG_ENABLED
if (instance_id && !ObjectDB::get_instance(instance_id)) {
@@ -2383,61 +2217,61 @@ Variant VisualScriptFunctionState::_signal_callback(const Variant** p_args, int
}
#endif
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
Array args;
- if (p_argcount==0) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
+ if (p_argcount == 0) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
return Variant();
- } else if (p_argcount==1) {
+ } else if (p_argcount == 1) {
//noooneee, reserved for me, me and only me.
} else {
- for(int i=0;i<p_argcount-1;i++) {
+ for (int i = 0; i < p_argcount - 1; i++) {
args.push_back(*p_args[i]);
}
}
- Ref<VisualScriptFunctionState> self = *p_args[p_argcount-1]; //hi, I'm myself, needed this to remain alive.
+ Ref<VisualScriptFunctionState> self = *p_args[p_argcount - 1]; //hi, I'm myself, needed this to remain alive.
if (self.is_null()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=p_argcount-1;
- r_error.expected=Variant::OBJECT;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = p_argcount - 1;
+ r_error.expected = Variant::OBJECT;
return Variant();
}
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Variant *working_mem = ((Variant*)stack.ptr()) + working_mem_index;
+ 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.ptr(),stack.size(),node,flow_stack_pos,pass,true,r_error);
- function=StringName(); //invalidate
+ Variant ret = instance->_call_internal(function, stack.ptr(), stack.size(), node, flow_stack_pos, pass, true, r_error);
+ function = StringName(); //invalidate
return ret;
}
-void VisualScriptFunctionState::connect_to_signal(Object* p_obj, const String& p_signal, Array p_binds) {
+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++) {
+ 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(p_signal,this,"_signal_callback",binds);
+ p_obj->connect(p_signal, this, "_signal_callback", binds);
}
bool VisualScriptFunctionState::is_valid() const {
- return function!=StringName();
+ return function != StringName();
}
Variant VisualScriptFunctionState::resume(Array p_args) {
- ERR_FAIL_COND_V(function==StringName(),Variant());
+ ERR_FAIL_COND_V(function == StringName(), Variant());
#ifdef DEBUG_ENABLED
if (instance_id && !ObjectDB::get_instance(instance_id)) {
ERR_EXPLAIN("Resumed after yield, but class instance is gone");
@@ -2451,44 +2285,38 @@ Variant VisualScriptFunctionState::resume(Array p_args) {
#endif
Variant::CallError r_error;
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Variant *working_mem = ((Variant*)stack.ptr()) + working_mem_index;
+ 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.ptr(),stack.size(),node,flow_stack_pos,pass,true,r_error);
- function=StringName(); //invalidate
+ Variant ret = instance->_call_internal(function, stack.ptr(), stack.size(), node, flow_stack_pos, pass, true, r_error);
+ function = StringName(); //invalidate
return ret;
}
-
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:Array","args"),&VisualScriptFunctionState::resume,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("is_valid"),&VisualScriptFunctionState::is_valid);
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"_signal_callback",&VisualScriptFunctionState::_signal_callback,MethodInfo("_signal_callback"));
+ ClassDB::bind_method(D_METHOD("connect_to_signal", "obj", "signals", "args"), &VisualScriptFunctionState::connect_to_signal);
+ ClassDB::bind_method(D_METHOD("resume:Array", "args"), &VisualScriptFunctionState::resume, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("is_valid"), &VisualScriptFunctionState::is_valid);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &VisualScriptFunctionState::_signal_callback, MethodInfo("_signal_callback"));
}
VisualScriptFunctionState::VisualScriptFunctionState() {
-
}
VisualScriptFunctionState::~VisualScriptFunctionState() {
- if (function!=StringName()) {
- Variant *s = ((Variant*)stack.ptr());
- for(int i=0;i<variant_stack_size;i++) {
+ if (function != StringName()) {
+ Variant *s = ((Variant *)stack.ptr());
+ for (int i = 0; i < variant_stack_size; i++) {
s[i].~Variant();
}
}
}
-
-
-
-
///////////////////////////////////////////////
String VisualScriptLanguage::get_name() const {
@@ -2498,8 +2326,6 @@ String VisualScriptLanguage::get_name() const {
/* LANGUAGE FUNCTIONS */
void VisualScriptLanguage::init() {
-
-
}
String VisualScriptLanguage::get_type() const {
@@ -2509,207 +2335,185 @@ 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);
return script;
}
-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) const {
+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) const {
return false;
}
Script *VisualScriptLanguage::create_script() const {
- return memnew( VisualScript );
+ return memnew(VisualScript);
}
bool VisualScriptLanguage::has_named_classes() const {
return false;
}
-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 PoolStringArray& p_args) const {
+String VisualScriptLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const {
return String();
}
-void VisualScriptLanguage::auto_indent_code(String& p_code,int p_from_line,int p_to_line) const {
-
-
+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) {
-
-
+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) {
+bool VisualScriptLanguage::debug_break_parse(const String &p_file, int p_node, const String &p_error) {
//break because of parse error
- if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) {
-
- _debug_parse_err_node=p_node;
- _debug_parse_err_file=p_file;
- _debug_error=p_error;
- ScriptDebugger::get_singleton()->debug(this,false);
- return true;
- } else {
- return false;
- }
+ if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) {
+ _debug_parse_err_node = p_node;
+ _debug_parse_err_file = p_file;
+ _debug_error = p_error;
+ ScriptDebugger::get_singleton()->debug(this, false);
+ return true;
+ } else {
+ return false;
+ }
}
-bool VisualScriptLanguage::debug_break(const String& p_error,bool p_allow_continue) {
-
- if (ScriptDebugger::get_singleton() && Thread::get_caller_ID()==Thread::get_main_ID()) {
+bool VisualScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
- _debug_parse_err_node=-1;
- _debug_parse_err_file="";
- _debug_error=p_error;
- ScriptDebugger::get_singleton()->debug(this,p_allow_continue);
- return true;
- } else {
- return false;
- }
+ if (ScriptDebugger::get_singleton() && Thread::get_caller_ID() == Thread::get_main_ID()) {
+ _debug_parse_err_node = -1;
+ _debug_parse_err_file = "";
+ _debug_error = p_error;
+ ScriptDebugger::get_singleton()->debug(this, p_allow_continue);
+ return true;
+ } else {
+ return false;
+ }
}
-
String VisualScriptLanguage::debug_get_error() const {
- return _debug_error;
+ 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)
+ if (_debug_parse_err_node >= 0)
return _debug_parse_err_node;
- ERR_FAIL_INDEX_V(p_level,_debug_call_stack_pos,-1);
-
- int l = _debug_call_stack_pos - p_level -1;
+ ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
- return *(_call_stack[l].current_id);
+ int l = _debug_call_stack_pos - p_level - 1;
+ return *(_call_stack[l].current_id);
}
String VisualScriptLanguage::debug_get_stack_level_function(int p_level) const {
- if (_debug_parse_err_node>=0)
+ 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;
+ 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)
+ 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();
-
+ 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) {
+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)
+ if (_debug_parse_err_node >= 0)
return;
- ERR_FAIL_INDEX(p_level,_debug_call_stack_pos);
+ ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
- int l = _debug_call_stack_pos - p_level -1;
+ int l = _debug_call_stack_pos - p_level - 1;
const StringName *f = _call_stack[l].function;
ERR_FAIL_COND(!_call_stack[l].instance->functions.has(*f));
//VisualScriptInstance::Function *func = &_call_stack[l].instance->functions[*f];
- VisualScriptNodeInstance *node =_call_stack[l].instance->instances[*_call_stack[l].current_id];
+ VisualScriptNodeInstance *node = _call_stack[l].instance->instances[*_call_stack[l].current_id];
ERR_FAIL_COND(!node);
p_locals->push_back("node_name");
p_values->push_back(node->get_base_node()->get_text());
- for(int i=0;i<node->input_port_count;i++) {
+ for (int i = 0; i < node->input_port_count; i++) {
String name = node->get_base_node()->get_input_value_port_info(i).name;
- if (name==String()) {
- name="in_"+itos(i);
+ if (name == String()) {
+ name = "in_" + itos(i);
}
- p_locals->push_back("input/"+name);
+ p_locals->push_back("input/" + name);
//value is trickier
int in_from = node->input_ports[i];
- int in_value = in_from&VisualScriptNodeInstance::INPUT_MASK;
+ int in_value = in_from & VisualScriptNodeInstance::INPUT_MASK;
- if (in_from&VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
+ if (in_from & VisualScriptNodeInstance::INPUT_DEFAULT_VALUE_BIT) {
p_values->push_back(_call_stack[l].instance->default_values[in_value]);
} else {
- p_values->push_back( _call_stack[l].stack[ in_value] );
+ p_values->push_back(_call_stack[l].stack[in_value]);
}
}
- for(int i=0;i<node->output_port_count;i++) {
+ 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);
+ if (name == String()) {
+ name = "out_" + itos(i);
}
- p_locals->push_back("output/"+name);
+ p_locals->push_back("output/" + name);
//value is trickier
int in_from = node->output_ports[i];
- p_values->push_back( _call_stack[l].stack[ in_from] );
-
+ p_values->push_back(_call_stack[l].stack[in_from]);
}
- for(int i=0;i<node->get_working_memory_size();i++) {
- p_locals->push_back("working_mem/mem_"+itos(i));
- p_values->push_back( (*_call_stack[l].work_mem)[i]);
+ for (int i = 0; i < node->get_working_memory_size(); i++) {
+ p_locals->push_back("working_mem/mem_" + itos(i));
+ p_values->push_back((*_call_stack[l].work_mem)[i]);
}
-/*
+ /*
ERR_FAIL_INDEX(p_level,_debug_call_stack_pos);
@@ -2725,14 +2529,13 @@ void VisualScriptLanguage::debug_get_stack_level_locals(int p_level,List<String>
}
*/
}
-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) {
+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)
+ 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;
-
+ 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())
@@ -2740,123 +2543,103 @@ void VisualScriptLanguage::debug_get_stack_level_members(int p_level,List<String
List<StringName> vars;
vs->get_variable_list(&vars);
- for (List<StringName>::Element *E=vars.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
Variant v;
- if (_call_stack[l].instance->get_variable(E->get(),&v)) {
- p_members->push_back("variables/"+E->get());
+ if (_call_stack[l].instance->get_variable(E->get(), &v)) {
+ p_members->push_back("variables/" + E->get());
p_values->push_back(v);
}
}
}
-void VisualScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems,int p_max_depth) {
+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) {
- if (_debug_parse_err_node>=0)
+ if (_debug_parse_err_node >= 0)
return "";
return "";
}
-
-
void VisualScriptLanguage::reload_all_scripts() {
-
-
}
-void VisualScriptLanguage::reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload) {
-
-
+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::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) {
+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) {
+int VisualScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) {
return 0;
}
+VisualScriptLanguage *VisualScriptLanguage::singleton = NULL;
-VisualScriptLanguage* VisualScriptLanguage::singleton=NULL;
-
-
-void VisualScriptLanguage::add_register_func(const String& p_name,VisualScriptNodeRegisterFunc p_func) {
+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;
+ register_funcs[p_name] = p_func;
}
-Ref<VisualScriptNode> VisualScriptLanguage::create_node_from_name(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>());
+ 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()) {
+ 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";
- singleton=this;
+ notification = "_notification";
+ _step = "_step";
+ _subcall = "_subcall";
+ singleton = this;
#ifndef NO_THREADS
lock = Mutex::create();
#endif
-
- _debug_parse_err_node=-1;
- _debug_parse_err_file="";
- _debug_call_stack_pos=0;
- int dmcs=GLOBAL_DEF("debug/script/max_call_stack",1024);
+ _debug_parse_err_node = -1;
+ _debug_parse_err_file = "";
+ _debug_call_stack_pos = 0;
+ int dmcs = GLOBAL_DEF("debug/script/max_call_stack", 1024);
if (ScriptDebugger::get_singleton()) {
//debugging enabled!
_debug_max_call_stack = dmcs;
- if (_debug_max_call_stack<1024)
- _debug_max_call_stack=1024;
- _call_stack = memnew_arr( CallLevel, _debug_max_call_stack+1 );
+ if (_debug_max_call_stack < 1024)
+ _debug_max_call_stack = 1024;
+ _call_stack = memnew_arr(CallLevel, _debug_max_call_stack + 1);
} else {
- _debug_max_call_stack=0;
- _call_stack=NULL;
+ _debug_max_call_stack = 0;
+ _call_stack = NULL;
}
-
}
VisualScriptLanguage::~VisualScriptLanguage() {
@@ -2864,8 +2647,8 @@ VisualScriptLanguage::~VisualScriptLanguage() {
if (lock)
memdelete(lock);
- if (_call_stack) {
+ if (_call_stack) {
memdelete_arr(_call_stack);
}
- singleton=NULL;
+ singleton = NULL;
}
diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h
index ef73a89048..e3af3f4a1b 100644
--- a/modules/visual_script/visual_script.h
+++ b/modules/visual_script/visual_script.h
@@ -29,19 +29,19 @@
#ifndef VSCRIPT_H
#define VSCRIPT_H
-#include "script_language.h"
#include "os/thread.h"
+#include "script_language.h"
class VisualScriptInstance;
class VisualScriptNodeInstance;
class VisualScript;
class VisualScriptNode : public Resource {
- GDCLASS(VisualScriptNode,Resource)
+ GDCLASS(VisualScriptNode, Resource)
-friend class VisualScript;
+ friend class VisualScript;
- Set<VisualScript*> scripts_used;
+ Set<VisualScript *> scripts_used;
Array default_input_values;
bool breakpoint;
@@ -50,41 +50,40 @@ friend class VisualScript;
Array _get_default_input_values() const;
void validate_input_default_values();
-protected:
+protected:
void _notification(int p_what);
void ports_changed_notify();
static void _bind_methods();
-public:
+public:
Ref<VisualScript> get_visual_script() const;
- virtual int get_output_sequence_port_count() const=0;
- virtual bool has_input_sequence_port() const=0;
+ virtual int get_output_sequence_port_count() const = 0;
+ virtual bool has_input_sequence_port() const = 0;
- virtual String get_output_sequence_port_text(int p_port) const=0;
+ virtual String get_output_sequence_port_text(int p_port) const = 0;
virtual bool has_mixed_input_and_sequence_ports() const { return false; }
- virtual int get_input_value_port_count() const=0;
- virtual int get_output_value_port_count() const=0;
+ virtual int get_input_value_port_count() const = 0;
+ virtual int get_output_value_port_count() const = 0;
+ virtual PropertyInfo get_input_value_port_info(int p_idx) const = 0;
+ virtual PropertyInfo get_output_value_port_info(int p_idx) const = 0;
- virtual PropertyInfo get_input_value_port_info(int p_idx) const=0;
- virtual PropertyInfo get_output_value_port_info(int p_idx) const=0;
-
- void set_default_input_value(int p_port,const Variant& p_value);
+ void set_default_input_value(int p_port, const Variant &p_value);
Variant get_default_input_value(int p_port) const;
- virtual String get_caption() const=0;
- virtual String get_text() const=0;
- virtual String get_category() const=0;
+ virtual String get_caption() const = 0;
+ virtual String get_text() const = 0;
+ virtual String get_category() const = 0;
//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;
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance) = 0;
struct TypeGuess {
@@ -93,32 +92,32 @@ public:
StringName GDCLASS;
Ref<Script> script;
- TypeGuess() { type=Variant::NIL; ev_type=InputEvent::NONE; }
+ TypeGuess() {
+ type = Variant::NIL;
+ ev_type = InputEvent::NONE;
+ }
};
- virtual TypeGuess guess_output_type(TypeGuess* p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptNode();
};
-
class VisualScriptNodeInstance {
-friend class VisualScriptInstance;
-friend class VisualScriptLanguage; //for debugger
-
+ friend class VisualScriptInstance;
+ friend class VisualScriptLanguage; //for debugger
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)
+ 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)
};
-
int id;
int sequence_index;
VisualScriptNodeInstance **sequence_outputs;
int sequence_output_count;
- Vector<VisualScriptNodeInstance*> dependencies;
+ Vector<VisualScriptNodeInstance *> dependencies;
int *input_ports;
int input_port_count;
int *output_ports;
@@ -129,7 +128,6 @@ friend class VisualScriptLanguage; //for debugger
VisualScriptNode *base;
public:
-
enum StartMode {
START_MODE_BEGIN_SEQUENCE,
START_MODE_CONTINUE_SEQUENCE,
@@ -137,44 +135,42 @@ 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_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)
- 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
+ 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
};
- _FORCE_INLINE_ int get_input_port_count() const { return input_port_count; }
- _FORCE_INLINE_ int get_output_port_count() const { return output_port_count; }
- _FORCE_INLINE_ int get_sequence_output_count() const { return sequence_output_count; }
+ _FORCE_INLINE_ int get_input_port_count() const { return input_port_count; }
+ _FORCE_INLINE_ int get_output_port_count() const { return output_port_count; }
+ _FORCE_INLINE_ int get_sequence_output_count() const { return sequence_output_count; }
- _FORCE_INLINE_ int get_id() const { return id; }
+ _FORCE_INLINE_ int get_id() const { return id; }
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,Variant::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, Variant::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 ); }
+ Ref<VisualScriptNode> get_base_node() { return Ref<VisualScriptNode>(base); }
VisualScriptNodeInstance();
virtual ~VisualScriptNodeInstance();
};
-
class VisualScript : public Script {
- GDCLASS( VisualScript, Script )
+ GDCLASS(VisualScript, Script)
RES_BASE_EXTENSION("vs");
public:
-
struct SequenceConnection {
union {
@@ -187,9 +183,9 @@ public:
uint64_t id;
};
- bool operator<(const SequenceConnection& p_connection) const {
+ bool operator<(const SequenceConnection &p_connection) const {
- return id<p_connection.id;
+ return id < p_connection.id;
}
};
@@ -206,15 +202,14 @@ public:
uint64_t id;
};
- bool operator<(const DataConnection& p_connection) const {
+ bool operator<(const DataConnection &p_connection) const {
- return id<p_connection.id;
+ return id < p_connection.id;
}
};
-
private:
-friend class VisualScriptInstance;
+ friend class VisualScriptInstance;
StringName base_type;
struct Argument {
@@ -228,7 +223,7 @@ friend class VisualScriptInstance;
Ref<VisualScriptNode> node;
};
- Map<int,NodeData> nodes;
+ Map<int, NodeData> nodes;
Set<SequenceConnection> sequence_connections;
@@ -238,9 +233,7 @@ friend class VisualScriptInstance;
Vector2 scroll;
-
- Function() { function_id=-1; }
-
+ Function() { function_id = -1; }
};
struct Variable {
@@ -249,109 +242,101 @@ friend class VisualScriptInstance;
bool _export;
};
+ Map<StringName, Function> functions;
+ Map<StringName, Variable> variables;
+ Map<StringName, Vector<Argument> > custom_signals;
-
- Map<StringName,Function> functions;
- Map<StringName,Variable> variables;
- Map<StringName,Vector<Argument> > custom_signals;
-
- Map<Object*,VisualScriptInstance*> instances;
+ Map<Object *, VisualScriptInstance *> instances;
#ifdef TOOLS_ENABLED
- Set<PlaceHolderScriptInstance*> placeholders;
+ Set<PlaceHolderScriptInstance *> placeholders;
//void _update_placeholder(PlaceHolderScriptInstance *p_placeholder);
virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder);
void _update_placeholders();
#endif
- void _set_variable_info(const StringName& p_name,const Dictionary& p_info);
- Dictionary _get_variable_info(const StringName& p_name) const;
-
+ void _set_variable_info(const StringName &p_name, const Dictionary &p_info);
+ Dictionary _get_variable_info(const StringName &p_name) const;
- void _set_data(const Dictionary& p_data);
+ void _set_data(const Dictionary &p_data);
Dictionary _get_data() const;
protected:
-
void _node_ports_changed(int p_id);
static void _bind_methods();
-public:
-
- void add_function(const StringName& p_name);
- 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;
+public:
+ void add_function(const StringName &p_name);
+ 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 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_pos(const StringName& p_func,int p_id,const Point2& p_pos);
- Point2 get_node_pos(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_name,int p_node,int p_port) const;
- bool get_input_value_port_connection_source(const StringName& p_name,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;
- void remove_variable(const StringName& p_name);
- void set_variable_default_value(const StringName& p_name,const Variant& p_value);
- Variant get_variable_default_value(const StringName& p_name) const;
- void set_variable_info(const StringName& p_name,const PropertyInfo& p_info);
- PropertyInfo get_variable_info(const StringName& p_name) const;
- void set_variable_export(const StringName& p_name,bool p_export);
- bool get_variable_export(const StringName& p_name) const;
+ int get_function_node_id(const StringName &p_name) const;
+
+ 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_pos(const StringName &p_func, int p_id, const Point2 &p_pos);
+ Point2 get_node_pos(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_name, int p_node, int p_port) const;
+ bool get_input_value_port_connection_source(const StringName &p_name, 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;
+ void remove_variable(const StringName &p_name);
+ void set_variable_default_value(const StringName &p_name, const Variant &p_value);
+ Variant get_variable_default_value(const StringName &p_name) const;
+ void set_variable_info(const StringName &p_name, const PropertyInfo &p_info);
+ PropertyInfo get_variable_info(const StringName &p_name) const;
+ void set_variable_export(const StringName &p_name, bool p_export);
+ bool get_variable_export(const StringName &p_name) const;
void get_variable_list(List<StringName> *r_variables) const;
- void rename_variable(const StringName& p_name,const StringName& p_new_name);
-
-
- void add_custom_signal(const StringName& p_name);
- bool has_custom_signal(const StringName& p_name) const;
- void custom_signal_add_argument(const StringName& p_func,Variant::Type p_type,const String& p_name,int p_index=-1);
- void custom_signal_set_argument_type(const StringName& p_func,int p_argidx,Variant::Type p_type);
- Variant::Type custom_signal_get_argument_type(const StringName& p_func,int p_argidx) const;
- void custom_signal_set_argument_name(const StringName& p_func,int p_argidx,const String& p_name);
- String custom_signal_get_argument_name(const StringName& p_func,int p_argidx) const;
- void custom_signal_remove_argument(const StringName& p_func,int p_argidx);
- int custom_signal_get_argument_count(const StringName& p_func) const;
- void custom_signal_swap_argument(const StringName& p_func,int p_argidx,int p_with_argidx);
- void remove_custom_signal(const StringName& p_name);
- void rename_custom_signal(const StringName& p_name,const StringName& p_new_name);
+ void rename_variable(const StringName &p_name, const StringName &p_new_name);
+
+ void add_custom_signal(const StringName &p_name);
+ bool has_custom_signal(const StringName &p_name) const;
+ void custom_signal_add_argument(const StringName &p_func, Variant::Type p_type, const String &p_name, int p_index = -1);
+ void custom_signal_set_argument_type(const StringName &p_func, int p_argidx, Variant::Type p_type);
+ Variant::Type custom_signal_get_argument_type(const StringName &p_func, int p_argidx) const;
+ void custom_signal_set_argument_name(const StringName &p_func, int p_argidx, const String &p_name);
+ String custom_signal_get_argument_name(const StringName &p_func, int p_argidx) const;
+ void custom_signal_remove_argument(const StringName &p_func, int p_argidx);
+ int custom_signal_get_argument_count(const StringName &p_func) const;
+ void custom_signal_swap_argument(const StringName &p_func, int p_argidx, int p_with_argidx);
+ void remove_custom_signal(const StringName &p_name);
+ void rename_custom_signal(const StringName &p_name, const StringName &p_new_name);
void get_custom_signal_list(List<StringName> *r_custom_signals) const;
int get_available_id() const;
- void set_instance_base_type(const StringName& p_type);
+ void set_instance_base_type(const StringName &p_type);
virtual bool can_instance() const;
virtual Ref<Script> get_base_script() const;
virtual StringName get_instance_base_type() const;
- virtual ScriptInstance* instance_create(Object *p_this);
+ virtual ScriptInstance *instance_create(Object *p_this);
virtual bool instance_has(const Object *p_this) const;
-
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 void set_source_code(const String &p_code);
+ virtual Error reload(bool p_keep_state = false);
virtual bool is_tool() const;
@@ -359,14 +344,14 @@ public:
virtual ScriptLanguage *get_language() const;
- virtual bool has_script_signal(const StringName& p_signal) const;
+ virtual bool has_script_signal(const StringName &p_signal) const;
virtual void get_script_signal_list(List<MethodInfo> *r_signals) const;
- 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;
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 bool has_method(const StringName &p_method) const;
+ virtual MethodInfo get_method_info(const StringName &p_method) const;
virtual void get_script_property_list(List<PropertyInfo> *p_list) const;
@@ -378,13 +363,12 @@ public:
~VisualScript();
};
-
class VisualScriptInstance : public ScriptInstance {
Object *owner;
Ref<VisualScript> script;
- Map<StringName,Variant> variables; //using variable path, not script
- Map<int,VisualScriptNodeInstance*> instances;
+ Map<StringName, Variant> variables; //using variable path, not script
+ Map<int, VisualScriptNodeInstance *> instances;
struct Function {
int node;
@@ -398,50 +382,48 @@ class VisualScriptInstance : public ScriptInstance {
bool valid;
};
- Map<StringName,Function> functions;
+ Map<StringName, Function> functions;
Vector<Variant> default_values;
- int max_input_args,max_output_args;
+ int max_input_args, max_output_args;
StringName source;
- void _dependency_step(VisualScriptNodeInstance* node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Variant::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,Variant::CallError &r_error);
-
+ void _dependency_step(VisualScriptNodeInstance *node, int p_pass, int *pass_stack, const Variant **input_args, Variant **output_args, Variant *variant_stack, Variant::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, Variant::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;
+ 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=NULL) const;
+ virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const;
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,Variant::CallError &r_error);
+ virtual bool has_method(const StringName &p_method) const;
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
virtual void notification(int p_notification);
- bool set_variable(const StringName& p_variable,const Variant& p_value) {
+ bool set_variable(const StringName &p_variable, const Variant &p_value) {
- Map<StringName,Variant>::Element *E=variables.find(p_variable);
+ Map<StringName, Variant>::Element *E = variables.find(p_variable);
if (!E)
return false;
- E->get()=p_value;
+ E->get() = p_value;
return true;
}
- bool get_variable(const StringName& p_variable,Variant* r_variable) const {
+ bool get_variable(const StringName &p_variable, Variant *r_variable) const {
- const Map<StringName,Variant>::Element *E=variables.find(p_variable);
+ const Map<StringName, Variant>::Element *E = variables.find(p_variable);
if (!E)
return false;
- *r_variable=E->get();
+ *r_variable = E->get();
return true;
-
}
virtual Ref<Script> get_script() const;
@@ -449,22 +431,21 @@ public:
_FORCE_INLINE_ VisualScript *get_script_ptr() { return script.ptr(); }
_FORCE_INLINE_ Object *get_owner_ptr() { return owner; }
- void create(const Ref<VisualScript>& p_script,Object *p_owner);
+ void create(const Ref<VisualScript> &p_script, Object *p_owner);
virtual ScriptLanguage *get_language();
- virtual RPCMode get_rpc_mode(const StringName& p_method) const;
- virtual RPCMode get_rset_mode(const StringName& p_variable) const;
+ virtual RPCMode get_rpc_mode(const StringName &p_method) const;
+ virtual RPCMode get_rset_mode(const StringName &p_variable) const;
VisualScriptInstance();
~VisualScriptInstance();
};
-
class VisualScriptFunctionState : public Reference {
- GDCLASS(VisualScriptFunctionState,Reference);
-friend class VisualScriptInstance;
+ GDCLASS(VisualScriptFunctionState, Reference);
+ friend class VisualScriptInstance;
ObjectID instance_id;
ObjectID script_id;
@@ -477,36 +458,34 @@ friend class VisualScriptInstance;
int flow_stack_pos;
int pass;
- Variant _signal_callback(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+ Variant _signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+
protected:
static void _bind_methods();
-public:
- void connect_to_signal(Object* p_obj,const String& p_signal,Array p_binds);
+public:
+ void connect_to_signal(Object *p_obj, const String &p_signal, Array p_binds);
bool is_valid() const;
Variant resume(Array p_args);
VisualScriptFunctionState();
~VisualScriptFunctionState();
};
-
-typedef Ref<VisualScriptNode> (*VisualScriptNodeRegisterFunc)(const String& p_type);
+typedef Ref<VisualScriptNode> (*VisualScriptNodeRegisterFunc)(const String &p_type);
class VisualScriptLanguage : public ScriptLanguage {
- Map<String,VisualScriptNodeRegisterFunc> register_funcs;
+ Map<String, VisualScriptNodeRegisterFunc> register_funcs;
struct CallLevel {
- Variant *stack;
- Variant **work_mem;
- const StringName *function;
- VisualScriptInstance *instance;
- int *current_id;
-
+ Variant *stack;
+ Variant **work_mem;
+ const StringName *function;
+ VisualScriptInstance *instance;
+ int *current_id;
};
-
int _debug_parse_err_node;
String _debug_parse_err_file;
String _debug_error;
@@ -520,52 +499,52 @@ public:
StringName _step;
StringName _subcall;
- static VisualScriptLanguage* singleton;
+ static VisualScriptLanguage *singleton;
Mutex *lock;
- bool debug_break(const String& p_error,bool p_allow_continue=true);
- bool debug_break_parse(const String& p_file, int p_node,const String& p_error);
+ bool debug_break(const String &p_error, bool p_allow_continue = true);
+ 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) {
+ _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 (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0)
- ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() +1 );
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0)
+ ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() + 1);
- if (_debug_call_stack_pos >= _debug_max_call_stack) {
- //stack overflow
- _debug_error="Stack Overflow (Stack Size: "+itos(_debug_max_call_stack)+")";
- ScriptDebugger::get_singleton()->debug(this);
- return;
- }
+ if (_debug_call_stack_pos >= _debug_max_call_stack) {
+ //stack overflow
+ _debug_error = "Stack Overflow (Stack Size: " + itos(_debug_max_call_stack) + ")";
+ ScriptDebugger::get_singleton()->debug(this);
+ return;
+ }
- _call_stack[_debug_call_stack_pos].stack=p_stack;
- _call_stack[_debug_call_stack_pos].instance=p_instance;
- _call_stack[_debug_call_stack_pos].function=p_function;
- _call_stack[_debug_call_stack_pos].work_mem=p_work_mem;
- _call_stack[_debug_call_stack_pos].current_id=current_id;
- _debug_call_stack_pos++;
+ _call_stack[_debug_call_stack_pos].stack = p_stack;
+ _call_stack[_debug_call_stack_pos].instance = p_instance;
+ _call_stack[_debug_call_stack_pos].function = p_function;
+ _call_stack[_debug_call_stack_pos].work_mem = p_work_mem;
+ _call_stack[_debug_call_stack_pos].current_id = current_id;
+ _debug_call_stack_pos++;
}
_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 (ScriptDebugger::get_singleton()->get_lines_left()>0 && ScriptDebugger::get_singleton()->get_depth()>=0)
- ScriptDebugger::get_singleton()->set_depth( ScriptDebugger::get_singleton()->get_depth() -1 );
+ if (ScriptDebugger::get_singleton()->get_lines_left() > 0 && ScriptDebugger::get_singleton()->get_depth() >= 0)
+ ScriptDebugger::get_singleton()->set_depth(ScriptDebugger::get_singleton()->get_depth() - 1);
- if (_debug_call_stack_pos==0) {
+ if (_debug_call_stack_pos == 0) {
- _debug_error="Stack Underflow (Engine Bug)";
- ScriptDebugger::get_singleton()->debug(this);
- return;
- }
+ _debug_error = "Stack Underflow (Engine Bug)";
+ ScriptDebugger::get_singleton()->debug(this);
+ return;
+ }
- _debug_call_stack_pos--;
+ _debug_call_stack_pos--;
}
//////////////////////////////////////
@@ -576,22 +555,21 @@ public:
virtual void init();
virtual String get_type() const;
virtual String get_extension() const;
- virtual Error execute_file(const String& p_path) ;
+ virtual Error execute_file(const String &p_path);
virtual void finish();
/* 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 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=NULL) const;
+ virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const;
+ 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 = NULL) const;
virtual Script *create_script() const;
virtual bool has_named_classes() 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 PoolStringArray& p_args) const;
- virtual void auto_indent_code(String& p_code,int p_from_line,int p_to_line) const;
- virtual void add_global_constant(const StringName& p_variable,const Variant& p_value);
-
+ virtual int find_function(const String &p_function, const String &p_code) const;
+ virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const;
+ virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const;
+ virtual void add_global_constant(const StringName &p_variable, const Variant &p_value);
/* DEBUGGER FUNCTIONS */
@@ -600,45 +578,40 @@ public:
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;
- virtual void debug_get_stack_level_locals(int p_level,List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual void debug_get_stack_level_members(int p_level,List<String> *p_members, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems=-1,int p_max_depth=-1);
- virtual String debug_parse_stack_level_expression(int p_level,const String& p_expression,int p_max_subitems=-1,int p_max_depth=-1);
-
+ virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1);
+ virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1);
virtual void reload_all_scripts();
- virtual void reload_tool_script(const Ref<Script>& p_script,bool p_soft_reload);
+ virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload);
/* LOADER FUNCTIONS */
virtual void get_recognized_extensions(List<String> *p_extensions) const;
virtual void get_public_functions(List<MethodInfo> *p_functions) const;
- virtual void get_public_constants(List<Pair<String,Variant> > *p_constants) const;
+ virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const;
virtual void profiling_start();
virtual void profiling_stop();
- 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);
+ 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);
- void add_register_func(const String& p_name,VisualScriptNodeRegisterFunc p_func);
- Ref<VisualScriptNode> create_node_from_name(const String& p_name);
+ void add_register_func(const String &p_name, VisualScriptNodeRegisterFunc p_func);
+ Ref<VisualScriptNode> create_node_from_name(const String &p_name);
void get_registered_node_names(List<String> *r_names);
-
VisualScriptLanguage();
~VisualScriptLanguage();
-
};
//aid for registering
-template<class T>
-static Ref<VisualScriptNode> create_node_generic(const String& p_name) {
+template <class T>
+static Ref<VisualScriptNode> create_node_generic(const String &p_name) {
Ref<T> node;
node.instance();
return node;
}
-
-
#endif // VSCRIPT_H
diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp
index e83cd3e614..378ca06f90 100644
--- a/modules/visual_script/visual_script_builtin_funcs.cpp
+++ b/modules/visual_script/visual_script_builtin_funcs.cpp
@@ -28,15 +28,15 @@
/*************************************************************************/
#include "visual_script_builtin_funcs.h"
-#include "math_funcs.h"
#include "class_db.h"
-#include "reference.h"
#include "func_ref.h"
+#include "io/marshalls.h"
+#include "math_funcs.h"
#include "os/os.h"
+#include "reference.h"
#include "variant_parser.h"
-#include "io/marshalls.h"
-const char* VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX]={
+const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX] = {
"sin",
"cos",
"tan",
@@ -96,10 +96,10 @@ const char* VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX
"color_named",
};
-VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String& p_string) {
+VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(const String &p_string) {
- for(int i=0;i<FUNC_MAX;i++) {
- if (p_string==func_name[i])
+ for (int i = 0; i < FUNC_MAX; i++) {
+ if (p_string == func_name[i])
return BuiltinFunc(i);
}
@@ -108,19 +108,18 @@ VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::find_function(cons
String VisualScriptBuiltinFunc::get_func_name(BuiltinFunc p_func) {
- ERR_FAIL_INDEX_V(p_func,FUNC_MAX,String());
+ 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{
+bool VisualScriptBuiltinFunc::has_input_sequence_port() const {
- switch(func) {
+ switch (func) {
case MATH_RANDOMIZE:
case TEXT_PRINT:
@@ -129,15 +128,12 @@ bool VisualScriptBuiltinFunc::has_input_sequence_port() const{
return true;
default:
return false;
-
}
-
}
int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
-
- switch(p_func) {
+ switch (p_func) {
case MATH_RANDOMIZE:
case MATH_RAND:
@@ -200,19 +196,19 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) {
case MATH_DECTIME:
case LOGIC_CLAMP:
return 3;
- case FUNC_MAX:{}
-
+ case FUNC_MAX: {
+ }
}
return 0;
}
-int VisualScriptBuiltinFunc::get_input_value_port_count() const{
+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) {
+ switch (func) {
case MATH_RANDOMIZE:
case TEXT_PRINT:
case TEXT_PRINTERR:
@@ -233,9 +229,9 @@ String VisualScriptBuiltinFunc::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const {
- switch(func) {
+ switch (func) {
case MATH_SIN:
case MATH_COS:
@@ -248,67 +244,67 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
case MATH_ATAN:
case MATH_ATAN2:
case MATH_SQRT: {
- return PropertyInfo(Variant::REAL,"num");
+ return PropertyInfo(Variant::REAL, "num");
} break;
case MATH_FMOD:
case MATH_FPOSMOD: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"x");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "x");
else
- return PropertyInfo(Variant::REAL,"y");
+ return PropertyInfo(Variant::REAL, "y");
} break;
case MATH_FLOOR:
case MATH_CEIL:
case MATH_ROUND:
case MATH_ABS:
case MATH_SIGN: {
- return PropertyInfo(Variant::REAL,"num");
+ return PropertyInfo(Variant::REAL, "num");
} break;
case MATH_POW: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"x");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "x");
else
- return PropertyInfo(Variant::REAL,"y");
+ return PropertyInfo(Variant::REAL, "y");
} break;
case MATH_LOG:
case MATH_EXP:
case MATH_ISNAN:
case MATH_ISINF: {
- return PropertyInfo(Variant::REAL,"num");
+ return PropertyInfo(Variant::REAL, "num");
} break;
case MATH_EASE: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"s");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "s");
else
- return PropertyInfo(Variant::REAL,"curve");
+ return PropertyInfo(Variant::REAL, "curve");
} break;
case MATH_DECIMALS: {
- return PropertyInfo(Variant::REAL,"step");
+ return PropertyInfo(Variant::REAL, "step");
} break;
case MATH_STEPIFY: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"s");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "s");
else
- return PropertyInfo(Variant::REAL,"steps");
+ return PropertyInfo(Variant::REAL, "steps");
} break;
case MATH_LERP: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"from");
- else if (p_idx==1)
- return PropertyInfo(Variant::REAL,"to");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "from");
+ else if (p_idx == 1)
+ return PropertyInfo(Variant::REAL, "to");
else
- return PropertyInfo(Variant::REAL,"weight");
+ return PropertyInfo(Variant::REAL, "weight");
} break;
case MATH_DECTIME: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"value");
- else if (p_idx==1)
- return PropertyInfo(Variant::REAL,"amount");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "value");
+ else if (p_idx == 1)
+ return PropertyInfo(Variant::REAL, "amount");
else
- return PropertyInfo(Variant::REAL,"step");
+ return PropertyInfo(Variant::REAL, "step");
} break;
case MATH_RANDOMIZE: {
@@ -320,139 +316,140 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const
} break;
case MATH_RANDOM: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"from");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "from");
else
- return PropertyInfo(Variant::REAL,"to");
+ return PropertyInfo(Variant::REAL, "to");
} break;
case MATH_SEED: {
- return PropertyInfo(Variant::INT,"seed");
+ return PropertyInfo(Variant::INT, "seed");
} break;
case MATH_RANDSEED: {
- return PropertyInfo(Variant::INT,"seed");
+ return PropertyInfo(Variant::INT, "seed");
} break;
case MATH_DEG2RAD: {
- return PropertyInfo(Variant::REAL,"deg");
+ return PropertyInfo(Variant::REAL, "deg");
} break;
case MATH_RAD2DEG: {
- return PropertyInfo(Variant::REAL,"rad");
+ return PropertyInfo(Variant::REAL, "rad");
} break;
case MATH_LINEAR2DB: {
- return PropertyInfo(Variant::REAL,"nrg");
+ return PropertyInfo(Variant::REAL, "nrg");
} break;
case MATH_DB2LINEAR: {
- return PropertyInfo(Variant::REAL,"db");
+ return PropertyInfo(Variant::REAL, "db");
} break;
case LOGIC_MAX: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"a");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "a");
else
- return PropertyInfo(Variant::REAL,"b");
+ return PropertyInfo(Variant::REAL, "b");
} break;
case LOGIC_MIN: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"a");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "a");
else
- return PropertyInfo(Variant::REAL,"b");
+ return PropertyInfo(Variant::REAL, "b");
} break;
case LOGIC_CLAMP: {
- if (p_idx==0)
- return PropertyInfo(Variant::REAL,"a");
- else if (p_idx==0) // FIXME: is it ok to test p_idx == 0 twice?
- return PropertyInfo(Variant::REAL,"min");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::REAL, "a");
+ else if (p_idx == 0) // FIXME: is it ok to test p_idx == 0 twice?
+ return PropertyInfo(Variant::REAL, "min");
else
- return PropertyInfo(Variant::REAL,"max");
+ return PropertyInfo(Variant::REAL, "max");
} break;
case LOGIC_NEAREST_PO2: {
- return PropertyInfo(Variant::INT,"num");
+ return PropertyInfo(Variant::INT, "num");
} break;
case OBJ_WEAKREF: {
- return PropertyInfo(Variant::OBJECT,"source");
+ return PropertyInfo(Variant::OBJECT, "source");
} break;
case FUNC_FUNCREF: {
- if (p_idx==0)
- return PropertyInfo(Variant::OBJECT,"instance");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::OBJECT, "instance");
else
- return PropertyInfo(Variant::STRING,"funcname");
+ return PropertyInfo(Variant::STRING, "funcname");
} break;
case TYPE_CONVERT: {
- if (p_idx==0)
- return PropertyInfo(Variant::NIL,"what");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::NIL, "what");
else
- return PropertyInfo(Variant::STRING,"type");
+ return PropertyInfo(Variant::STRING, "type");
} break;
case TYPE_OF: {
- return PropertyInfo(Variant::NIL,"what");
+ return PropertyInfo(Variant::NIL, "what");
} break;
case TYPE_EXISTS: {
- return PropertyInfo(Variant::STRING,"type");
+ return PropertyInfo(Variant::STRING, "type");
} break;
case TEXT_CHAR: {
- return PropertyInfo(Variant::INT,"ascii");
+ return PropertyInfo(Variant::INT, "ascii");
} break;
case TEXT_STR: {
- return PropertyInfo(Variant::NIL,"value");
+ return PropertyInfo(Variant::NIL, "value");
} break;
case TEXT_PRINT: {
- return PropertyInfo(Variant::NIL,"value");
+ return PropertyInfo(Variant::NIL, "value");
} break;
case TEXT_PRINTERR: {
- return PropertyInfo(Variant::NIL,"value");
+ return PropertyInfo(Variant::NIL, "value");
} break;
case TEXT_PRINTRAW: {
- return PropertyInfo(Variant::NIL,"value");
+ return PropertyInfo(Variant::NIL, "value");
} break;
case VAR_TO_STR: {
- return PropertyInfo(Variant::NIL,"var");
+ return PropertyInfo(Variant::NIL, "var");
} break;
case STR_TO_VAR: {
- return PropertyInfo(Variant::STRING,"string");
+ return PropertyInfo(Variant::STRING, "string");
} break;
case VAR_TO_BYTES: {
- return PropertyInfo(Variant::NIL,"var");
+ return PropertyInfo(Variant::NIL, "var");
} break;
case BYTES_TO_VAR: {
- return PropertyInfo(Variant::POOL_BYTE_ARRAY,"bytes");
+ return PropertyInfo(Variant::POOL_BYTE_ARRAY, "bytes");
} break;
case COLORN: {
- if (p_idx==0)
- return PropertyInfo(Variant::STRING,"name");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::STRING, "name");
else
- return PropertyInfo(Variant::REAL,"alpha");
+ return PropertyInfo(Variant::REAL, "alpha");
} break;
- case FUNC_MAX:{}
+ case FUNC_MAX: {
+ }
}
return PropertyInfo();
}
-PropertyInfo VisualScriptBuiltinFunc::get_output_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) {
+ Variant::Type t = Variant::NIL;
+ switch (func) {
case MATH_SIN:
case MATH_COS:
@@ -469,36 +466,36 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
case MATH_FPOSMOD:
case MATH_FLOOR:
case MATH_CEIL: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case MATH_ROUND: {
- t=Variant::INT;
+ t = Variant::INT;
} break;
case MATH_ABS: {
- t=Variant::NIL;
+ t = Variant::NIL;
} break;
case MATH_SIGN: {
- t=Variant::NIL;
+ t = Variant::NIL;
} break;
case MATH_POW:
case MATH_LOG:
case MATH_EXP: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case MATH_ISNAN:
case MATH_ISINF: {
- t=Variant::BOOL;
+ t = Variant::BOOL;
} break;
case MATH_EASE: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case MATH_DECIMALS: {
- t=Variant::INT;
+ t = Variant::INT;
} break;
case MATH_STEPIFY:
case MATH_LERP:
case MATH_DECTIME: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case MATH_RANDOMIZE: {
@@ -506,71 +503,67 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
} break;
case MATH_RAND: {
- t=Variant::INT;
+ t = Variant::INT;
} break;
case MATH_RANDF:
case MATH_RANDOM: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case MATH_SEED: {
} break;
case MATH_RANDSEED: {
- if (p_idx==0)
- return PropertyInfo(Variant::INT,"rnd");
+ if (p_idx == 0)
+ return PropertyInfo(Variant::INT, "rnd");
else
- return PropertyInfo(Variant::INT,"seed");
+ return PropertyInfo(Variant::INT, "seed");
} break;
case MATH_DEG2RAD:
case MATH_RAD2DEG:
case MATH_LINEAR2DB:
case MATH_DB2LINEAR: {
- t=Variant::REAL;
+ t = Variant::REAL;
} break;
case LOGIC_MAX:
case LOGIC_MIN:
case LOGIC_CLAMP: {
-
} break;
case LOGIC_NEAREST_PO2: {
- t=Variant::NIL;
+ t = Variant::NIL;
} break;
case OBJ_WEAKREF: {
- t=Variant::OBJECT;
+ t = Variant::OBJECT;
} break;
case FUNC_FUNCREF: {
- t=Variant::OBJECT;
+ t = Variant::OBJECT;
} break;
case TYPE_CONVERT: {
-
-
} break;
case TYPE_OF: {
- t=Variant::INT;
+ t = Variant::INT;
} break;
case TYPE_EXISTS: {
- t=Variant::BOOL;
+ t = Variant::BOOL;
} break;
case TEXT_CHAR:
case TEXT_STR: {
- t=Variant::STRING;
+ t = Variant::STRING;
} break;
case TEXT_PRINT: {
-
} break;
case TEXT_PRINTERR: {
@@ -579,26 +572,26 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons
} break;
case VAR_TO_STR: {
- t=Variant::STRING;
+ t = Variant::STRING;
} break;
case STR_TO_VAR: {
} break;
case VAR_TO_BYTES: {
- t=Variant::POOL_BYTE_ARRAY;
+ t = Variant::POOL_BYTE_ARRAY;
} break;
case BYTES_TO_VAR: {
-
} break;
case COLORN: {
- t=Variant::COLOR;
+ t = Variant::COLOR;
} break;
- case FUNC_MAX:{}
+ case FUNC_MAX: {
+ }
}
- return PropertyInfo(t,"");
+ return PropertyInfo(t, "");
}
String VisualScriptBuiltinFunc::get_caption() const {
@@ -613,8 +606,8 @@ String VisualScriptBuiltinFunc::get_text() const {
void VisualScriptBuiltinFunc::set_func(BuiltinFunc p_which) {
- ERR_FAIL_INDEX(p_which,FUNC_MAX);
- func=p_which;
+ ERR_FAIL_INDEX(p_which, FUNC_MAX);
+ func = p_which;
_change_notify();
ports_changed_notify();
}
@@ -623,256 +616,252 @@ VisualScriptBuiltinFunc::BuiltinFunc VisualScriptBuiltinFunc::get_func() {
return func;
}
-
-#define VALIDATE_ARG_NUM(m_arg) \
- if (!p_inputs[m_arg]->is_num()) {\
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;\
- r_error.argument=m_arg;\
- r_error.expected=Variant::REAL;\
- return;\
+#define VALIDATE_ARG_NUM(m_arg) \
+ if (!p_inputs[m_arg]->is_num()) { \
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; \
+ r_error.argument = m_arg; \
+ r_error.expected = Variant::REAL; \
+ return; \
}
+void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Variant::CallError &r_error, String &r_error_str) {
-void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inputs,Variant* r_return,Variant::CallError& r_error,String& r_error_str) {
-
- switch(p_func) {
+ switch (p_func) {
case VisualScriptBuiltinFunc::MATH_SIN: {
VALIDATE_ARG_NUM(0);
- *r_return=Math::sin((double)*p_inputs[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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *r_return = Math::fposmod((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_FLOOR: {
VALIDATE_ARG_NUM(0);
- *r_return=Math::floor((double)*p_inputs[0]);
- } break;
+ *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]);
+ *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]);
+ *r_return = Math::round((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_ABS: {
- if (p_inputs[0]->get_type()==Variant::INT) {
+ 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::REAL) {
+ *r_return = ABS(i);
+ } else if (p_inputs[0]->get_type() == Variant::REAL) {
real_t r = *p_inputs[0];
- *r_return=Math::abs(r);
+ *r_return = Math::abs(r);
} else {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::REAL;
-
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::REAL;
}
} break;
case VisualScriptBuiltinFunc::MATH_SIGN: {
- if (p_inputs[0]->get_type()==Variant::INT) {
+ 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::REAL) {
-
- real_t r = *p_inputs[0];
- *r_return= r < 0.0 ? -1.0 : ( r > 0.0 ? +1.0 : 0.0);
- } else {
+ int64_t i = *p_inputs[0];
+ *r_return = i < 0 ? -1 : (i > 0 ? +1 : 0);
+ } else if (p_inputs[0]->get_type() == Variant::REAL) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::REAL;
+ real_t r = *p_inputs[0];
+ *r_return = r < 0.0 ? -1.0 : (r > 0.0 ? +1.0 : 0.0);
+ } else {
- }
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::REAL;
+ }
} 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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *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]);
+ *r_return = Math::ease((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_DECIMALS: {
VALIDATE_ARG_NUM(0);
- *r_return=Math::step_decimals((double)*p_inputs[0]);
+ *r_return = Math::step_decimals((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::MATH_STEPIFY: {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
- *r_return=Math::stepify((double)*p_inputs[0],(double)*p_inputs[1]);
+ *r_return = Math::stepify((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]);
+ *r_return = Math::lerp((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);
- *r_return=Math::dectime((double)*p_inputs[0],(double)*p_inputs[1],(double)*p_inputs[2]);
+ *r_return = Math::dectime((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]);
} break;
case VisualScriptBuiltinFunc::MATH_RANDOMIZE: {
Math::randomize();
} break;
case VisualScriptBuiltinFunc::MATH_RAND: {
- *r_return=Math::rand();
+ *r_return = Math::rand();
} break;
case VisualScriptBuiltinFunc::MATH_RANDF: {
- *r_return=Math::randf();
+ *r_return = Math::randf();
} break;
case VisualScriptBuiltinFunc::MATH_RANDOM: {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
- *r_return=Math::random((double)*p_inputs[0],(double)*p_inputs[1]);
+ *r_return = Math::random((double)*p_inputs[0], (double)*p_inputs[1]);
} break;
case VisualScriptBuiltinFunc::MATH_SEED: {
VALIDATE_ARG_NUM(0);
- uint64_t seed=*p_inputs[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];
+ uint64_t seed = *p_inputs[0];
int ret = Math::rand_from_seed(&seed);
Array reta;
reta.push_back(ret);
reta.push_back(seed);
- *r_return=reta;
+ *r_return = reta;
} break;
case VisualScriptBuiltinFunc::MATH_DEG2RAD: {
VALIDATE_ARG_NUM(0);
- *r_return=Math::deg2rad((double)*p_inputs[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]);
+ *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]);
+ *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]);
+ *r_return = Math::db2linear((double)*p_inputs[0]);
} break;
case VisualScriptBuiltinFunc::LOGIC_MAX: {
- if (p_inputs[0]->get_type()==Variant::INT && p_inputs[1]->get_type()==Variant::INT) {
+ 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);
+ *r_return = MAX(a, b);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -880,17 +869,17 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
real_t a = *p_inputs[0];
real_t b = *p_inputs[1];
- *r_return=MAX(a,b);
+ *r_return = MAX(a, b);
}
} break;
case VisualScriptBuiltinFunc::LOGIC_MIN: {
- if (p_inputs[0]->get_type()==Variant::INT && p_inputs[1]->get_type()==Variant::INT) {
+ 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);
+ *r_return = MIN(a, b);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -898,17 +887,17 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
real_t a = *p_inputs[0];
real_t b = *p_inputs[1];
- *r_return=MIN(a,b);
+ *r_return = MIN(a, b);
}
} 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) {
+ 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];
- *r_return=CLAMP(a,b,c);
+ *r_return = CLAMP(a, b, c);
} else {
VALIDATE_ARG_NUM(0);
VALIDATE_ARG_NUM(1);
@@ -918,7 +907,7 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
real_t b = *p_inputs[1];
real_t c = *p_inputs[2];
- *r_return=CLAMP(a,b,c);
+ *r_return = CLAMP(a, b, c);
}
} break;
case VisualScriptBuiltinFunc::LOGIC_NEAREST_PO2: {
@@ -929,14 +918,13 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
} break;
case VisualScriptBuiltinFunc::OBJ_WEAKREF: {
- if (p_inputs[0]->get_type()!=Variant::OBJECT) {
+ if (p_inputs[0]->get_type() != Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::OBJECT;
return;
-
}
if (p_inputs[0]->is_ref()) {
@@ -947,95 +935,87 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
return;
}
- Ref<WeakRef> wref = memnew( WeakRef );
+ Ref<WeakRef> wref = memnew(WeakRef);
wref->set_ref(r);
- *r_return=wref;
+ *r_return = wref;
} else {
Object *obj = *p_inputs[0];
if (!obj) {
return;
}
- Ref<WeakRef> wref = memnew( WeakRef );
+ Ref<WeakRef> wref = memnew(WeakRef);
wref->set_obj(obj);
- *r_return=wref;
+ *r_return = wref;
}
-
-
-
} break;
case VisualScriptBuiltinFunc::FUNC_FUNCREF: {
- if (p_inputs[0]->get_type()!=Variant::OBJECT) {
+ if (p_inputs[0]->get_type() != Variant::OBJECT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::OBJECT;
+ r_error.error = Variant::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) {
+ if (p_inputs[1]->get_type() != Variant::STRING && p_inputs[1]->get_type() != Variant::NODE_PATH) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
return;
-
}
- Ref<FuncRef> fr = memnew( FuncRef);
+ Ref<FuncRef> fr = memnew(FuncRef);
fr->set_instance(*p_inputs[0]);
fr->set_function(*p_inputs[1]);
- *r_return=fr;
+ *r_return = fr;
} break;
case VisualScriptBuiltinFunc::TYPE_CONVERT: {
VALIDATE_ARG_NUM(1);
- int type=*p_inputs[1];
- if (type<0 || type>=Variant::VARIANT_MAX) {
+ 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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::INT;
+ r_error_str = RTR("Invalid type argument to convert(), use TYPE_* constants.");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::INT;
return;
} else {
-
- *r_return=Variant::construct(Variant::Type(type),p_inputs,1,r_error);
+ *r_return = Variant::construct(Variant::Type(type), 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};
-
- *r_return=String(result);
+ CharType result[2] = { *p_inputs[0], 0 };
+
+ *r_return = String(result);
} break;
case VisualScriptBuiltinFunc::TEXT_STR: {
String str = *p_inputs[0];
- *r_return=str;
+ *r_return = str;
} break;
case VisualScriptBuiltinFunc::TEXT_PRINT: {
@@ -1043,7 +1023,6 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
String str = *p_inputs[0];
print_line(str);
-
} break;
case VisualScriptBuiltinFunc::TEXT_PRINTERR: {
@@ -1051,98 +1030,93 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
String str = *p_inputs[0];
//str+="\n";
- OS::get_singleton()->printerr("%s\n",str.utf8().get_data());
-
+ OS::get_singleton()->printerr("%s\n", str.utf8().get_data());
} break;
case VisualScriptBuiltinFunc::TEXT_PRINTRAW: {
String str = *p_inputs[0];
//str+="\n";
- OS::get_singleton()->print("%s",str.utf8().get_data());
-
+ 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;
+ 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=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
+ if (p_inputs[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
return;
}
VariantParser::StreamString ss;
- ss.s=*p_inputs[0];
+ ss.s = *p_inputs[0];
String errs;
int line;
- Error err = VariantParser::parse(&ss,*r_return,errs,line);
+ Error err = VariantParser::parse(&ss, *r_return, errs, line);
- if (err!=OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
- *r_return="Parse error at line "+itos(line)+": "+errs;
+ if (err != OK) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
+ *r_return = "Parse error at line " + itos(line) + ": " + errs;
return;
}
} break;
case VisualScriptBuiltinFunc::VAR_TO_BYTES: {
-
PoolByteArray barr;
int len;
- Error err = encode_variant(*p_inputs[0],NULL,len);
+ Error err = encode_variant(*p_inputs[0], NULL, len);
if (err) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::NIL;
- r_error_str="Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::NIL;
+ r_error_str = "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID).";
return;
}
barr.resize(len);
{
PoolByteArray::Write w = barr.write();
- encode_variant(*p_inputs[0],w.ptr(),len);
-
+ encode_variant(*p_inputs[0], w.ptr(), len);
}
- *r_return=barr;
+ *r_return = barr;
} break;
case VisualScriptBuiltinFunc::BYTES_TO_VAR: {
- if (p_inputs[0]->get_type()!=Variant::POOL_BYTE_ARRAY) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::POOL_BYTE_ARRAY;
+ if (p_inputs[0]->get_type() != Variant::POOL_BYTE_ARRAY) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::POOL_BYTE_ARRAY;
return;
}
- PoolByteArray varr=*p_inputs[0];
+ PoolByteArray varr = *p_inputs[0];
Variant ret;
{
- PoolByteArray::Read r=varr.read();
- Error err = decode_variant(ret,r.ptr(),varr.size(),NULL);
- if (err!=OK) {
- r_error_str=RTR("Not enough bytes for decoding bytes, or invalid format.");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::POOL_BYTE_ARRAY;
+ PoolByteArray::Read r = varr.read();
+ Error err = decode_variant(ret, r.ptr(), varr.size(), NULL);
+ if (err != OK) {
+ r_error_str = RTR("Not enough bytes for decoding bytes, or invalid format.");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::POOL_BYTE_ARRAY;
return;
}
-
}
- *r_return=ret;
+ *r_return = ret;
} break;
case VisualScriptBuiltinFunc::COLORN: {
@@ -1150,72 +1124,65 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func,const Variant** p_inp
VALIDATE_ARG_NUM(1);
Color color = Color::named(*p_inputs[0]);
- color.a=*p_inputs[1];
-
- *r_return=String(color);
+ color.a = *p_inputs[1];
+
+ *r_return = String(color);
} break;
default: {}
}
-
}
-
class VisualScriptNodeInstanceBuiltinFunc : public VisualScriptNodeInstance {
public:
-
VisualScriptBuiltinFunc *node;
VisualScriptInstance *instance;
VisualScriptBuiltinFunc::BuiltinFunc func;
-
//virtual int get_working_memory_size() const { return 0; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- VisualScriptBuiltinFunc::exec_func(func,p_inputs,p_outputs[0],r_error,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) {
+VisualScriptNodeInstance *VisualScriptBuiltinFunc::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceBuiltinFunc * instance = memnew(VisualScriptNodeInstanceBuiltinFunc );
- instance->node=this;
- instance->instance=p_instance;
- instance->func=func;
+ VisualScriptNodeInstanceBuiltinFunc *instance = memnew(VisualScriptNodeInstanceBuiltinFunc);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->func = func;
return instance;
}
-
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);
+ 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++) {
+ for (int i = 0; i < FUNC_MAX; i++) {
- if (i>0)
- cc+=",";
- cc+=func_name[i];
+ if (i > 0)
+ cc += ",";
+ cc += func_name[i];
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"function",PROPERTY_HINT_ENUM,cc),"set_func","get_func");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "function", PROPERTY_HINT_ENUM, cc), "set_func", "get_func");
}
VisualScriptBuiltinFunc::VisualScriptBuiltinFunc() {
- func=MATH_SIN;
+ func = MATH_SIN;
}
-template<VisualScriptBuiltinFunc::BuiltinFunc func>
-static Ref<VisualScriptNode> create_builtin_func_node(const String& p_name) {
+template <VisualScriptBuiltinFunc::BuiltinFunc func>
+static Ref<VisualScriptNode> create_builtin_func_node(const String &p_name) {
Ref<VisualScriptBuiltinFunc> node;
node.instance();
@@ -1225,69 +1192,67 @@ static Ref<VisualScriptNode> create_builtin_func_node(const String& p_name) {
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>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sinh",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SINH>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/cosh",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_COSH>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/tanh",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_TANH>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/asin",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ASIN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/acos",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ACOS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan2",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN2>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sqrt",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SQRT>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/fmod",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FMOD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/fposmod",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FPOSMOD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/floor",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FLOOR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/ceil",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CEIL>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/round",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ROUND>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/abs",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ABS>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/sign",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SIGN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/pow",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POW>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/log",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LOG>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/exp",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EXP>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/isnan",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISNAN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/isinf",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISINF>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/ease",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EASE>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/decimals",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_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/lerp",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>);
- 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/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/seed",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SEED>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/randseed",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDSEED>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/deg2rad",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DEG2RAD>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/rad2deg",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAD2DEG>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/linear2db",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LINEAR2DB>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/db2linear",create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DB2LINEAR>);
-
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/max",create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MAX>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/min",create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MIN>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/clamp",create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_CLAMP>);
- 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>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/char",create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_CHAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/str",create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_STR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/print",create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINT>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/printerr",create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTERR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/printraw",create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTRAW>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2str",create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_STR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/str2var",create_builtin_func_node<VisualScriptBuiltinFunc::STR_TO_VAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2bytes",create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_BYTES>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/bytes2var",create_builtin_func_node<VisualScriptBuiltinFunc::BYTES_TO_VAR>);
- VisualScriptLanguage::singleton->add_register_func("functions/built_in/color_named",create_builtin_func_node<VisualScriptBuiltinFunc::COLORN>);
-
+ 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>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/sinh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SINH>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/cosh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_COSH>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/tanh", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_TANH>);
+
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/asin", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ASIN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/acos", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ACOS>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/atan2", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ATAN2>);
+
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/sqrt", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SQRT>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/fmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FMOD>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/fposmod", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FPOSMOD>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/floor", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_FLOOR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/ceil", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_CEIL>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/round", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ROUND>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/abs", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ABS>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/sign", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SIGN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/pow", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_POW>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/log", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LOG>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/exp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EXP>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/isnan", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISNAN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/isinf", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_ISINF>);
+
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/ease", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_EASE>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/decimals", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_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/lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>);
+ 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/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/seed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_SEED>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/randseed", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDSEED>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/deg2rad", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DEG2RAD>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/rad2deg", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAD2DEG>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/linear2db", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LINEAR2DB>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/db2linear", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DB2LINEAR>);
+
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/max", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MAX>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/min", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_MIN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/clamp", create_builtin_func_node<VisualScriptBuiltinFunc::LOGIC_CLAMP>);
+ 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>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/char", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_CHAR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/str", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_STR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/print", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINT>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/printerr", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTERR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/printraw", create_builtin_func_node<VisualScriptBuiltinFunc::TEXT_PRINTRAW>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2str", create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_STR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/str2var", create_builtin_func_node<VisualScriptBuiltinFunc::STR_TO_VAR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/var2bytes", create_builtin_func_node<VisualScriptBuiltinFunc::VAR_TO_BYTES>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/bytes2var", create_builtin_func_node<VisualScriptBuiltinFunc::BYTES_TO_VAR>);
+ VisualScriptLanguage::singleton->add_register_func("functions/built_in/color_named", create_builtin_func_node<VisualScriptBuiltinFunc::COLORN>);
}
diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h
index 75bea4b1b5..7246239513 100644
--- a/modules/visual_script/visual_script_builtin_funcs.h
+++ b/modules/visual_script/visual_script_builtin_funcs.h
@@ -31,12 +31,10 @@
#include "visual_script.h"
-
class VisualScriptBuiltinFunc : public VisualScriptNode {
- GDCLASS(VisualScriptBuiltinFunc,VisualScriptNode)
+ GDCLASS(VisualScriptBuiltinFunc, VisualScriptNode)
public:
-
enum BuiltinFunc {
MATH_SIN,
MATH_COS,
@@ -100,27 +98,25 @@ public:
static int get_func_argument_count(BuiltinFunc p_func);
static String get_func_name(BuiltinFunc p_func);
- static void exec_func(BuiltinFunc p_func, const Variant** p_inputs, Variant* r_return, Variant::CallError& r_error, String& r_error_str);
- static BuiltinFunc find_function(const String& p_string);
+ static void exec_func(BuiltinFunc p_func, const Variant **p_inputs, Variant *r_return, Variant::CallError &r_error, String &r_error_str);
+ static BuiltinFunc find_function(const String &p_string);
private:
- static const char* func_name[FUNC_MAX];
+ static const char *func_name[FUNC_MAX];
BuiltinFunc func;
+
protected:
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -131,15 +127,13 @@ public:
void set_func(BuiltinFunc p_which);
BuiltinFunc get_func();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptBuiltinFunc();
};
VARIANT_ENUM_CAST(VisualScriptBuiltinFunc::BuiltinFunc)
-
void register_visual_script_builtin_func_node();
-
#endif // VISUAL_SCRIPT_BUILTIN_FUNCS_H
diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp
index 7dd7059c31..5b1b496f72 100644
--- a/modules/visual_script/visual_script_editor.cpp
+++ b/modules/visual_script/visual_script_editor.cpp
@@ -29,29 +29,28 @@
#include "visual_script_editor.h"
#include "editor/editor_node.h"
-#include "visual_script_nodes.h"
-#include "visual_script_flow_control.h"
-#include "visual_script_func_nodes.h"
-#include "visual_script_expression.h"
-#include "os/input.h"
#include "editor/editor_resource_preview.h"
+#include "os/input.h"
#include "os/keyboard.h"
+#include "visual_script_expression.h"
+#include "visual_script_flow_control.h"
+#include "visual_script_func_nodes.h"
+#include "visual_script_nodes.h"
#ifdef TOOLS_ENABLED
class VisualScriptEditorSignalEdit : public Object {
- GDCLASS(VisualScriptEditorSignalEdit,Object)
+ GDCLASS(VisualScriptEditorSignalEdit, Object)
StringName sig;
+
public:
UndoRedo *undo_redo;
Ref<VisualScript> script;
-
protected:
-
static void _bind_methods() {
- ClassDB::bind_method("_sig_changed",&VisualScriptEditorSignalEdit::_sig_changed);
+ ClassDB::bind_method("_sig_changed", &VisualScriptEditorSignalEdit::_sig_changed);
}
void _sig_changed() {
@@ -59,149 +58,138 @@ protected:
_change_notify();
}
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
- if (sig==StringName())
+ if (sig == StringName())
return false;
- if (p_name=="argument_count") {
+ if (p_name == "argument_count") {
- int new_argc=p_value;
+ 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("Change Signal Arguments");
-
-
if (new_argc < argc) {
- for(int i=new_argc;i<argc;i++) {
- undo_redo->add_do_method(script.ptr(),"custom_signal_remove_argument",sig,new_argc);
- 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);
+ for (int i = new_argc; i < argc; i++) {
+ undo_redo->add_do_method(script.ptr(), "custom_signal_remove_argument", sig, new_argc);
+ 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) {
+ } else if (new_argc > argc) {
- for(int i=argc;i<new_argc;i++) {
+ 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);
+ 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);
}
}
- undo_redo->add_do_method(this,"_sig_changed");
- undo_redo->add_undo_method(this,"_sig_changed");
+ undo_redo->add_do_method(this, "_sig_changed");
+ undo_redo->add_undo_method(this, "_sig_changed");
undo_redo->commit_action();
return true;
}
if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/",1).to_int()-1;
- 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 idx = String(p_name).get_slice("/", 1).to_int() - 1;
+ 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;
+ int old_type = script->custom_signal_get_argument_type(sig, idx);
+ int new_type = p_value;
undo_redo->create_action("Change Argument Type");
- undo_redo->add_do_method(script.ptr(),"custom_signal_set_argument_type",sig,idx,new_type);
- undo_redo->add_undo_method(script.ptr(),"custom_signal_set_argument_type",sig,idx,old_type);
+ undo_redo->add_do_method(script.ptr(), "custom_signal_set_argument_type", sig, idx, new_type);
+ undo_redo->add_undo_method(script.ptr(), "custom_signal_set_argument_type", sig, idx, old_type);
undo_redo->commit_action();
return true;
}
- if (what=="name") {
+ if (what == "name") {
- String old_name = script->custom_signal_get_argument_name(sig,idx);
- String new_name=p_value;
+ String old_name = script->custom_signal_get_argument_name(sig, idx);
+ String new_name = p_value;
undo_redo->create_action("Change Argument name");
- undo_redo->add_do_method(script.ptr(),"custom_signal_set_argument_name",sig,idx,new_name);
- undo_redo->add_undo_method(script.ptr(),"custom_signal_set_argument_name",sig,idx,old_name);
+ undo_redo->add_do_method(script.ptr(), "custom_signal_set_argument_name", sig, idx, new_name);
+ undo_redo->add_undo_method(script.ptr(), "custom_signal_set_argument_name", sig, idx, old_name);
undo_redo->commit_action();
return true;
}
-
-
}
-
return false;
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ bool _get(const StringName &p_name, Variant &r_ret) const {
- if (sig==StringName())
+ if (sig == StringName())
return false;
- if (p_name=="argument_count") {
+ if (p_name == "argument_count") {
r_ret = script->custom_signal_get_argument_count(sig);
return true;
}
if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/",1).to_int()-1;
- ERR_FAIL_INDEX_V(idx,script->custom_signal_get_argument_count(sig),false);
- String what = String(p_name).get_slice("/",2);
- if (what=="type") {
- r_ret = script->custom_signal_get_argument_type(sig,idx);
+ int idx = String(p_name).get_slice("/", 1).to_int() - 1;
+ ERR_FAIL_INDEX_V(idx, script->custom_signal_get_argument_count(sig), false);
+ String what = String(p_name).get_slice("/", 2);
+ if (what == "type") {
+ r_ret = script->custom_signal_get_argument_type(sig, idx);
return true;
}
- if (what=="name") {
- r_ret = script->custom_signal_get_argument_name(sig,idx);
+ if (what == "name") {
+ r_ret = script->custom_signal_get_argument_name(sig, idx);
return true;
}
-
-
-
}
return false;
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ 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";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ p_list->push_back(PropertyInfo(Variant::INT, "argument_count", PROPERTY_HINT_RANGE, "0,256"));
+ String argt = "Variant";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- for(int i=0;i<script->custom_signal_get_argument_count(sig);i++) {
- p_list->push_back(PropertyInfo(Variant::INT,"argument/"+itos(i+1)+"/type",PROPERTY_HINT_ENUM,argt));
- p_list->push_back(PropertyInfo(Variant::STRING,"argument/"+itos(i+1)+"/name"));
+ for (int i = 0; i < script->custom_signal_get_argument_count(sig); i++) {
+ p_list->push_back(PropertyInfo(Variant::INT, "argument/" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
+ p_list->push_back(PropertyInfo(Variant::STRING, "argument/" + itos(i + 1) + "/name"));
}
}
public:
+ void edit(const StringName &p_sig) {
-
- void edit(const StringName& p_sig) {
-
- sig=p_sig;
+ sig = p_sig;
_change_notify();
}
- VisualScriptEditorSignalEdit() { undo_redo=NULL; }
+ VisualScriptEditorSignalEdit() { undo_redo = NULL; }
};
class VisualScriptEditorVariableEdit : public Object {
- GDCLASS(VisualScriptEditorVariableEdit,Object)
+ GDCLASS(VisualScriptEditorVariableEdit, Object)
StringName var;
+
public:
UndoRedo *undo_redo;
Ref<VisualScript> script;
-
protected:
-
static void _bind_methods() {
- ClassDB::bind_method("_var_changed",&VisualScriptEditorVariableEdit::_var_changed);
- ClassDB::bind_method("_var_value_changed",&VisualScriptEditorVariableEdit::_var_value_changed);
+ ClassDB::bind_method("_var_changed", &VisualScriptEditorVariableEdit::_var_changed);
+ ClassDB::bind_method("_var_value_changed", &VisualScriptEditorVariableEdit::_var_value_changed);
}
void _var_changed() {
@@ -213,138 +201,132 @@ protected:
_change_notify("value"); //so the whole tree is not redrawn, makes editing smoother in general
}
- bool _set(const StringName& p_name, const Variant& p_value) {
+ bool _set(const StringName &p_name, const Variant &p_value) {
- if (var==StringName())
+ if (var == StringName())
return false;
-
-
- if (String(p_name)=="value") {
+ if (String(p_name) == "value") {
undo_redo->create_action("Set Variable Default Value");
- Variant current=script->get_variable_default_value(var);
- undo_redo->add_do_method(script.ptr(),"set_variable_default_value",var,p_value);
- undo_redo->add_undo_method(script.ptr(),"set_variable_default_value",var,current);
- undo_redo->add_do_method(this,"_var_value_changed");
- undo_redo->add_undo_method(this,"_var_value_changed");
+ Variant current = script->get_variable_default_value(var);
+ undo_redo->add_do_method(script.ptr(), "set_variable_default_value", var, p_value);
+ undo_redo->add_undo_method(script.ptr(), "set_variable_default_value", var, current);
+ undo_redo->add_do_method(this, "_var_value_changed");
+ undo_redo->add_undo_method(this, "_var_value_changed");
undo_redo->commit_action();
return true;
}
- Dictionary d = script->call("get_variable_info",var);
+ Dictionary d = script->call("get_variable_info", var);
- if (String(p_name)=="type") {
+ if (String(p_name) == "type") {
- Dictionary dc=d.copy();
- dc["type"]=p_value;
+ Dictionary dc = d.copy();
+ dc["type"] = p_value;
undo_redo->create_action("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);
- undo_redo->add_do_method(this,"_var_changed");
- undo_redo->add_undo_method(this,"_var_changed");
+ undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
+ undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
+ undo_redo->add_do_method(this, "_var_changed");
+ undo_redo->add_undo_method(this, "_var_changed");
undo_redo->commit_action();
return true;
}
- if (String(p_name)=="hint") {
+ if (String(p_name) == "hint") {
- Dictionary dc=d.copy();
- dc["hint"]=p_value;
+ Dictionary dc = d.copy();
+ dc["hint"] = p_value;
undo_redo->create_action("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);
- undo_redo->add_do_method(this,"_var_changed");
- undo_redo->add_undo_method(this,"_var_changed");
+ undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
+ undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
+ undo_redo->add_do_method(this, "_var_changed");
+ undo_redo->add_undo_method(this, "_var_changed");
undo_redo->commit_action();
return true;
}
- if (String(p_name)=="hint_string") {
+ if (String(p_name) == "hint_string") {
- Dictionary dc=d.copy();
- dc["hint_string"]=p_value;
+ Dictionary dc = d.copy();
+ dc["hint_string"] = p_value;
undo_redo->create_action("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);
- undo_redo->add_do_method(this,"_var_changed");
- undo_redo->add_undo_method(this,"_var_changed");
+ undo_redo->add_do_method(script.ptr(), "set_variable_info", var, dc);
+ undo_redo->add_undo_method(script.ptr(), "set_variable_info", var, d);
+ undo_redo->add_do_method(this, "_var_changed");
+ undo_redo->add_undo_method(this, "_var_changed");
undo_redo->commit_action();
return true;
}
- if (String(p_name)=="export") {
- script->set_variable_export(var,p_value);
+ if (String(p_name) == "export") {
+ script->set_variable_export(var, p_value);
return true;
}
-
return false;
}
- bool _get(const StringName& p_name,Variant &r_ret) const {
+ 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);
+ if (String(p_name) == "value") {
+ r_ret = script->get_variable_default_value(var);
return true;
}
PropertyInfo pinfo = script->get_variable_info(var);
- if (String(p_name)=="type") {
- r_ret=pinfo.type;
+ if (String(p_name) == "type") {
+ r_ret = pinfo.type;
return true;
}
- if (String(p_name)=="hint") {
- r_ret=pinfo.hint;
+ if (String(p_name) == "hint") {
+ r_ret = pinfo.hint;
return true;
}
- if (String(p_name)=="hint_string") {
- r_ret=pinfo.hint_string;
+ if (String(p_name) == "hint_string") {
+ r_ret = pinfo.hint_string;
return true;
}
- if (String(p_name)=="export") {
- r_ret=script->get_variable_export(var);
+ if (String(p_name) == "export") {
+ r_ret = script->get_variable_export(var);
return true;
}
return false;
}
- void _get_property_list( List<PropertyInfo> *p_list) const {
+ 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++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Variant";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- 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));
- p_list->push_back(PropertyInfo(Variant::INT,"hint",PROPERTY_HINT_ENUM,"None,Range,ExpRange,Enum,ExpEasing,Length,SpriteFrame,KeyAccel,BitFlags,AllFlags,File,Dir,GlobalFile,GlobalDir,ResourceType,MultilineText"));
- p_list->push_back(PropertyInfo(Variant::STRING,"hint_string"));
- p_list->push_back(PropertyInfo(Variant::BOOL,"export"));
-
+ 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));
+ p_list->push_back(PropertyInfo(Variant::INT, "hint", PROPERTY_HINT_ENUM, "None,Range,ExpRange,Enum,ExpEasing,Length,SpriteFrame,KeyAccel,BitFlags,AllFlags,File,Dir,GlobalFile,GlobalDir,ResourceType,MultilineText"));
+ p_list->push_back(PropertyInfo(Variant::STRING, "hint_string"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "export"));
}
public:
+ void edit(const StringName &p_var) {
-
- void edit(const StringName& p_var) {
-
- var=p_var;
+ var = p_var;
_change_notify();
}
- VisualScriptEditorVariableEdit() { undo_redo=NULL; }
+ VisualScriptEditorVariableEdit() { undo_redo = NULL; }
};
static Color _color_from_type(Variant::Type p_type) {
Color color;
- switch(p_type) {
+ switch (p_type) {
case Variant::NIL: color = Color::html("69ecbd"); break;
case Variant::BOOL: color = Color::html("8da6f0"); break;
@@ -380,66 +362,60 @@ static Color _color_from_type(Variant::Type p_type) {
case Variant::POOL_COLOR_ARRAY: color = Color::html("e9ff97"); break;
default:
- color.set_hsv(p_type/float(Variant::VARIANT_MAX),0.7,0.7);
+ color.set_hsv(p_type / float(Variant::VARIANT_MAX), 0.7, 0.7);
}
return color;
}
-
-
void VisualScriptEditor::_update_graph_connections() {
graph->clear_connections();
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(edited_func,&sequence_conns);
+ script->get_sequence_connection_list(edited_func, &sequence_conns);
+ for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
- 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);
+ graph->connect_node(itos(E->get().from_node), E->get().from_output, itos(E->get().to_node), 0);
}
List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(edited_func,&data_conns);
-
- for (List<VisualScript::DataConnection>::Element *E=data_conns.front();E;E=E->next()) {
+ script->get_data_connection_list(edited_func, &data_conns);
- VisualScript::DataConnection dc=E->get();
+ for (List<VisualScript::DataConnection>::Element *E = data_conns.front(); E; E = E->next()) {
+ VisualScript::DataConnection dc = E->get();
- Ref<VisualScriptNode> from_node = script->get_node(edited_func,E->get().from_node);
- Ref<VisualScriptNode> to_node = script->get_node(edited_func,E->get().to_node);
+ Ref<VisualScriptNode> from_node = script->get_node(edited_func, E->get().from_node);
+ Ref<VisualScriptNode> to_node = script->get_node(edited_func, E->get().to_node);
if (to_node->has_input_sequence_port()) {
dc.to_port++;
}
- dc.from_port+=from_node->get_output_sequence_port_count();
+ 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)
return;
- updating_graph=true;
+ updating_graph = true;
//byebye all nodes
- if (p_only_id>=0) {
+ if (p_only_id >= 0) {
if (graph->has_node(itos(p_only_id))) {
- Node* gid = graph->get_node(itos(p_only_id));
+ Node *gid = graph->get_node(itos(p_only_id));
if (gid)
memdelete(gid);
}
} else {
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
if (graph->get_child(i)->cast_to<GraphNode>()) {
memdelete(graph->get_child(i));
@@ -451,172 +427,160 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
if (!script->has_function(edited_func)) {
graph->hide();
select_func_text->show();
- updating_graph=false;
+ updating_graph = false;
return;
}
graph->show();
select_func_text->hide();
- Ref<Texture> type_icons[Variant::VARIANT_MAX]={
- Control::get_icon("MiniVariant","EditorIcons"),
- Control::get_icon("MiniBoolean","EditorIcons"),
- Control::get_icon("MiniInteger","EditorIcons"),
- Control::get_icon("MiniFloat","EditorIcons"),
- Control::get_icon("MiniString","EditorIcons"),
- Control::get_icon("MiniVector2","EditorIcons"),
- Control::get_icon("MiniRect2","EditorIcons"),
- Control::get_icon("MiniVector3","EditorIcons"),
- Control::get_icon("MiniTransform2D","EditorIcons"),
- Control::get_icon("MiniPlane","EditorIcons"),
- Control::get_icon("MiniQuat","EditorIcons"),
- Control::get_icon("MiniAabb","EditorIcons"),
- Control::get_icon("MiniBasis","EditorIcons"),
- Control::get_icon("MiniTransform","EditorIcons"),
- Control::get_icon("MiniColor","EditorIcons"),
- Control::get_icon("MiniImage","EditorIcons"),
- Control::get_icon("MiniPath","EditorIcons"),
- Control::get_icon("MiniRid","EditorIcons"),
- Control::get_icon("MiniObject","EditorIcons"),
- Control::get_icon("MiniInput","EditorIcons"),
- Control::get_icon("MiniDictionary","EditorIcons"),
- Control::get_icon("MiniArray","EditorIcons"),
- Control::get_icon("MiniRawArray","EditorIcons"),
- Control::get_icon("MiniIntArray","EditorIcons"),
- Control::get_icon("MiniFloatArray","EditorIcons"),
- Control::get_icon("MiniStringArray","EditorIcons"),
- Control::get_icon("MiniVector2Array","EditorIcons"),
- Control::get_icon("MiniVector3Array","EditorIcons"),
- Control::get_icon("MiniColorArray","EditorIcons")
+ Ref<Texture> type_icons[Variant::VARIANT_MAX] = {
+ Control::get_icon("MiniVariant", "EditorIcons"),
+ Control::get_icon("MiniBoolean", "EditorIcons"),
+ Control::get_icon("MiniInteger", "EditorIcons"),
+ Control::get_icon("MiniFloat", "EditorIcons"),
+ Control::get_icon("MiniString", "EditorIcons"),
+ Control::get_icon("MiniVector2", "EditorIcons"),
+ Control::get_icon("MiniRect2", "EditorIcons"),
+ Control::get_icon("MiniVector3", "EditorIcons"),
+ Control::get_icon("MiniTransform2D", "EditorIcons"),
+ Control::get_icon("MiniPlane", "EditorIcons"),
+ Control::get_icon("MiniQuat", "EditorIcons"),
+ Control::get_icon("MiniAabb", "EditorIcons"),
+ Control::get_icon("MiniBasis", "EditorIcons"),
+ Control::get_icon("MiniTransform", "EditorIcons"),
+ Control::get_icon("MiniColor", "EditorIcons"),
+ Control::get_icon("MiniImage", "EditorIcons"),
+ Control::get_icon("MiniPath", "EditorIcons"),
+ Control::get_icon("MiniRid", "EditorIcons"),
+ Control::get_icon("MiniObject", "EditorIcons"),
+ Control::get_icon("MiniInput", "EditorIcons"),
+ Control::get_icon("MiniDictionary", "EditorIcons"),
+ Control::get_icon("MiniArray", "EditorIcons"),
+ Control::get_icon("MiniRawArray", "EditorIcons"),
+ Control::get_icon("MiniIntArray", "EditorIcons"),
+ Control::get_icon("MiniFloatArray", "EditorIcons"),
+ Control::get_icon("MiniStringArray", "EditorIcons"),
+ Control::get_icon("MiniVector2Array", "EditorIcons"),
+ Control::get_icon("MiniVector3Array", "EditorIcons"),
+ Control::get_icon("MiniColorArray", "EditorIcons")
};
-
-
- Ref<Texture> seq_port = Control::get_icon("VisualShaderPort","EditorIcons");
+ Ref<Texture> seq_port = Control::get_icon("VisualShaderPort", "EditorIcons");
List<int> ids;
- script->get_node_list(edited_func,&ids);
- StringName editor_icons="EditorIcons";
+ script->get_node_list(edited_func, &ids);
+ StringName editor_icons = "EditorIcons";
- for(List<int>::Element *E=ids.front();E;E=E->next()) {
+ for (List<int>::Element *E = ids.front(); E; E = E->next()) {
- if (p_only_id>=0 && p_only_id!=E->get())
+ if (p_only_id >= 0 && p_only_id != E->get())
continue;
- Ref<VisualScriptNode> node = script->get_node(edited_func,E->get());
- Vector2 pos = script->get_node_pos(edited_func,E->get());
+ Ref<VisualScriptNode> node = script->get_node(edited_func, E->get());
+ Vector2 pos = script->get_node_pos(edited_func, E->get());
- GraphNode *gnode = memnew( GraphNode );
+ GraphNode *gnode = memnew(GraphNode);
gnode->set_title(node->get_caption());
- if (error_line==E->get()) {
+ if (error_line == E->get()) {
gnode->set_overlay(GraphNode::OVERLAY_POSITION);
} else if (node->is_breakpoint()) {
gnode->set_overlay(GraphNode::OVERLAY_BREAKPOINT);
}
- if (EditorSettings::get_singleton()->has("editors/visual_script/color_"+node->get_category())) {
- gnode->set_modulate(EditorSettings::get_singleton()->get("editors/visual_script/color_"+node->get_category()));
+ if (EditorSettings::get_singleton()->has("editors/visual_script/color_" + node->get_category())) {
+ gnode->set_modulate(EditorSettings::get_singleton()->get("editors/visual_script/color_" + node->get_category()));
}
-
-
- gnode->set_meta("__vnode",node);
+ gnode->set_meta("__vnode", node);
gnode->set_name(itos(E->get()));
- gnode->connect("dragged",this,"_node_moved",varray(E->get()));
- gnode->connect("close_request",this,"_remove_node",varray(E->get()),CONNECT_DEFERRED);
+ gnode->connect("dragged", this, "_node_moved", varray(E->get()));
+ gnode->connect("close_request", this, "_remove_node", varray(E->get()), CONNECT_DEFERRED);
-
- if (E->get()!=script->get_function_node_id(edited_func)) {
+ if (E->get() != script->get_function_node_id(edited_func)) {
//function can't be erased
gnode->set_show_close_button(true);
}
-
if (node->cast_to<VisualScriptExpression>()) {
- LineEdit *line_edit = memnew( LineEdit );
+ LineEdit *line_edit = memnew(LineEdit);
line_edit->set_text(node->get_text());
line_edit->set_expand_to_text_length(true);
- line_edit->add_font_override("font",get_font("source","EditorFonts"));
+ line_edit->add_font_override("font", get_font("source", "EditorFonts"));
gnode->add_child(line_edit);
- line_edit->connect("text_changed",this,"_expression_text_changed",varray(E->get()));
+ line_edit->connect("text_changed", this, "_expression_text_changed", varray(E->get()));
} else {
- Label *text = memnew( Label );
+ Label *text = memnew(Label);
text->set_text(node->get_text());
gnode->add_child(text);
}
-
if (node->cast_to<VisualScriptComment>()) {
- Ref<VisualScriptComment> vsc=node;
+ Ref<VisualScriptComment> vsc = node;
gnode->set_comment(true);
gnode->set_resizeable(true);
- gnode->set_custom_minimum_size(vsc->get_size()*EDSCALE);
- gnode->connect("resize_request",this,"_comment_node_resized",varray(E->get()));
-
+ gnode->set_custom_minimum_size(vsc->get_size() * EDSCALE);
+ gnode->connect("resize_request", this, "_comment_node_resized", varray(E->get()));
}
+ 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();
- gnode->set_slot(0,node->has_input_sequence_port(),TYPE_SEQUENCE,Color(1,1,1,1),single_seq_output,TYPE_SEQUENCE,Color(1,1,1,1),seq_port,seq_port);
- gnode->set_offset(pos*EDSCALE);
+ bool single_seq_output = node->get_output_sequence_port_count() == 1 && node->get_output_sequence_port_text(0) == String();
+ gnode->set_slot(0, node->has_input_sequence_port(), TYPE_SEQUENCE, Color(1, 1, 1, 1), single_seq_output, TYPE_SEQUENCE, Color(1, 1, 1, 1), seq_port, seq_port);
+ gnode->set_offset(pos * EDSCALE);
slot_idx++;
-
- int mixed_seq_ports=0;
+ int mixed_seq_ports = 0;
if (!single_seq_output) {
if (node->has_mixed_input_and_sequence_ports()) {
- mixed_seq_ports=node->get_output_sequence_port_count();
+ mixed_seq_ports = node->get_output_sequence_port_count();
} else {
- for(int i=0;i<node->get_output_sequence_port_count();i++) {
+ for (int i = 0; i < node->get_output_sequence_port_count(); i++) {
- Label *text2 = memnew( Label );
+ 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,Color(1,1,1,1),seq_port,seq_port);
+ gnode->set_slot(slot_idx, false, 0, Color(), true, TYPE_SEQUENCE, Color(1, 1, 1, 1), 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++) {
+ 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;
+ bool left_ok = false;
+ Variant::Type left_type = Variant::NIL;
String left_name;
-
-
- if (i<node->get_input_value_port_count()) {
+ 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;
+ left_ok = true;
+ left_type = pi.type;
+ left_name = pi.name;
}
- bool right_ok=false;
- Variant::Type right_type=Variant::NIL;
+ 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;
}
- HBoxContainer *hbc = memnew( HBoxContainer);
+ HBoxContainer *hbc = memnew(HBoxContainer);
if (left_ok) {
Ref<Texture> t;
- if (left_type>=0 && left_type<Variant::VARIANT_MAX) {
- t=type_icons[left_type];
+ if (left_type >= 0 && left_type < Variant::VARIANT_MAX) {
+ t = type_icons[left_type];
}
if (t.is_valid()) {
TextureRect *tf = memnew(TextureRect);
@@ -627,51 +591,51 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
hbc->add_child(memnew(Label(left_name)));
- if (left_type!=Variant::NIL && !script->is_input_value_port_connected(edited_func,E->get(),i)) {
+ if (left_type != Variant::NIL && !script->is_input_value_port_connected(edited_func, E->get(), i)) {
PropertyInfo pi = node->get_input_value_port_info(i);
- Button *button = memnew( Button );
+ Button *button = memnew(Button);
Variant value = node->get_default_input_value(i);
- if (value.get_type()!=left_type) {
+ if (value.get_type() != left_type) {
//different type? for now convert
//not the same, reconvert
Variant::CallError ce;
- const Variant *existingp=&value;
- value = Variant::construct(left_type,&existingp,1,ce,false);
+ 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",this,"_draw_color_over_button",varray(button,value));
- } else if (left_type==Variant::OBJECT && Ref<Resource>(value).is_valid()) {
+ if (left_type == Variant::COLOR) {
+ button->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
+ button->connect("draw", this, "_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);
+ EditorResourcePreview::get_singleton()->queue_edited_resource_preview(res, this, "_button_resource_previewed", arr);
- } else if (pi.type==Variant::INT && pi.hint==PROPERTY_HINT_ENUM){
+ } else if (pi.type == Variant::INT && pi.hint == PROPERTY_HINT_ENUM) {
- button->set_text(pi.hint_string.get_slice(",",value));
+ button->set_text(pi.hint_string.get_slice(",", value));
} else {
button->set_text(value);
}
- button->connect("pressed",this,"_default_value_edited",varray(button,E->get(),i));
+ button->connect("pressed", this, "_default_value_edited", varray(button, E->get(), i));
hbc->add_child(button);
}
} else {
Control *c = memnew(Control);
- c->set_custom_minimum_size(Size2(10,0)*EDSCALE);
+ c->set_custom_minimum_size(Size2(10, 0) * EDSCALE);
hbc->add_child(c);
}
hbc->add_spacer();
- if (i<mixed_seq_ports) {
+ if (i < mixed_seq_ports) {
- Label *text2 = memnew( Label );
+ Label *text2 = memnew(Label);
text2->set_text(node->get_output_sequence_port_text(i));
text2->set_align(Label::ALIGN_RIGHT);
hbc->add_child(text2);
@@ -682,8 +646,8 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
hbc->add_child(memnew(Label(right_name)));
Ref<Texture> t;
- if (right_type>=0 && right_type<Variant::VARIANT_MAX) {
- t=type_icons[right_type];
+ if (right_type >= 0 && right_type < Variant::VARIANT_MAX) {
+ t = type_icons[right_type];
}
if (t.is_valid()) {
TextureRect *tf = memnew(TextureRect);
@@ -691,15 +655,14 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
hbc->add_child(tf);
}
-
}
gnode->add_child(hbc);
- if (i<mixed_seq_ports) {
- gnode->set_slot(slot_idx,left_ok,left_type,_color_from_type(left_type),true,TYPE_SEQUENCE,Color(1,1,1,1),Ref<Texture>(),seq_port);
+ if (i < mixed_seq_ports) {
+ gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type), true, TYPE_SEQUENCE, Color(1, 1, 1, 1), Ref<Texture>(), seq_port);
} else {
- gnode->set_slot(slot_idx,left_ok,left_type,_color_from_type(left_type),right_ok,right_type,_color_from_type(right_type));
+ gnode->set_slot(slot_idx, left_ok, left_type, _color_from_type(left_type), right_ok, right_type, _color_from_type(right_type));
}
slot_idx++;
@@ -708,137 +671,134 @@ void VisualScriptEditor::_update_graph(int p_only_id) {
graph->add_child(gnode);
if (gnode->is_comment()) {
- graph->move_child(gnode,0);
+ graph->move_child(gnode, 0);
}
}
_update_graph_connections();
- graph->call_deferred("set_scroll_ofs",script->get_function_scroll(edited_func)*EDSCALE); //may need to adapt a bit, let it do so
- updating_graph=false;
-
+ graph->call_deferred("set_scroll_ofs", script->get_function_scroll(edited_func) * EDSCALE); //may need to adapt a bit, let it do so
+ updating_graph = false;
}
void VisualScriptEditor::_update_members() {
-
- updating_members=true;
+ updating_members = true;
members->clear();
TreeItem *root = members->create_item();
TreeItem *functions = members->create_item(root);
- functions->set_selectable(0,false);
- functions->set_text(0,TTR("Functions:"));
- functions->add_button(0,Control::get_icon("Override","EditorIcons"),1);
- functions->add_button(0,Control::get_icon("Add","EditorIcons"),0);
- functions->set_custom_bg_color(0,Control::get_color("prop_section","Editor"));
+ functions->set_selectable(0, false);
+ functions->set_text(0, TTR("Functions:"));
+ functions->add_button(0, Control::get_icon("Override", "EditorIcons"), 1);
+ functions->add_button(0, Control::get_icon("Add", "EditorIcons"), 0);
+ functions->set_custom_bg_color(0, Control::get_color("prop_section", "Editor"));
List<StringName> func_names;
script->get_function_list(&func_names);
- for (List<StringName>::Element *E=func_names.front();E;E=E->next()) {
- TreeItem *ti = members->create_item(functions) ;
- ti->set_text(0,E->get());
- ti->set_selectable(0,true);
- ti->set_editable(0,true);
+ for (List<StringName>::Element *E = func_names.front(); E; E = E->next()) {
+ TreeItem *ti = members->create_item(functions);
+ ti->set_text(0, E->get());
+ ti->set_selectable(0, true);
+ ti->set_editable(0, true);
//ti->add_button(0,Control::get_icon("Edit","EditorIcons"),0); function arguments are in the node now
- ti->add_button(0,Control::get_icon("Del","EditorIcons"),1);
- ti->set_metadata(0,E->get());
- if (E->get()==edited_func) {
- ti->set_custom_bg_color(0,get_color("prop_category","Editor"));
- ti->set_custom_color(0,Color(1,1,1,1));
+ ti->add_button(0, Control::get_icon("Del", "EditorIcons"), 1);
+ ti->set_metadata(0, E->get());
+ if (E->get() == edited_func) {
+ ti->set_custom_bg_color(0, get_color("prop_category", "Editor"));
+ ti->set_custom_color(0, Color(1, 1, 1, 1));
}
- if (selected==E->get())
+ if (selected == E->get())
ti->select(0);
}
TreeItem *variables = members->create_item(root);
- variables->set_selectable(0,false);
- variables->set_text(0,TTR("Variables:"));
- variables->add_button(0,Control::get_icon("Add","EditorIcons"));
- variables->set_custom_bg_color(0,Control::get_color("prop_section","Editor"));
-
- Ref<Texture> type_icons[Variant::VARIANT_MAX]={
- Control::get_icon("MiniVariant","EditorIcons"),
- Control::get_icon("MiniBoolean","EditorIcons"),
- Control::get_icon("MiniInteger","EditorIcons"),
- Control::get_icon("MiniFloat","EditorIcons"),
- Control::get_icon("MiniString","EditorIcons"),
- Control::get_icon("MiniVector2","EditorIcons"),
- Control::get_icon("MiniRect2","EditorIcons"),
- Control::get_icon("MiniVector3","EditorIcons"),
- Control::get_icon("MiniMatrix32","EditorIcons"),
- Control::get_icon("MiniPlane","EditorIcons"),
- Control::get_icon("MiniQuat","EditorIcons"),
- Control::get_icon("MiniAabb","EditorIcons"),
- Control::get_icon("MiniMatrix3","EditorIcons"),
- Control::get_icon("MiniTransform","EditorIcons"),
- Control::get_icon("MiniColor","EditorIcons"),
- Control::get_icon("MiniImage","EditorIcons"),
- Control::get_icon("MiniPath","EditorIcons"),
- Control::get_icon("MiniRid","EditorIcons"),
- Control::get_icon("MiniObject","EditorIcons"),
- Control::get_icon("MiniInput","EditorIcons"),
- Control::get_icon("MiniDictionary","EditorIcons"),
- Control::get_icon("MiniArray","EditorIcons"),
- Control::get_icon("MiniRawArray","EditorIcons"),
- Control::get_icon("MiniIntArray","EditorIcons"),
- Control::get_icon("MiniFloatArray","EditorIcons"),
- Control::get_icon("MiniStringArray","EditorIcons"),
- Control::get_icon("MiniVector2Array","EditorIcons"),
- Control::get_icon("MiniVector3Array","EditorIcons"),
- Control::get_icon("MiniColorArray","EditorIcons")
+ variables->set_selectable(0, false);
+ variables->set_text(0, TTR("Variables:"));
+ variables->add_button(0, Control::get_icon("Add", "EditorIcons"));
+ variables->set_custom_bg_color(0, Control::get_color("prop_section", "Editor"));
+
+ Ref<Texture> type_icons[Variant::VARIANT_MAX] = {
+ Control::get_icon("MiniVariant", "EditorIcons"),
+ Control::get_icon("MiniBoolean", "EditorIcons"),
+ Control::get_icon("MiniInteger", "EditorIcons"),
+ Control::get_icon("MiniFloat", "EditorIcons"),
+ Control::get_icon("MiniString", "EditorIcons"),
+ Control::get_icon("MiniVector2", "EditorIcons"),
+ Control::get_icon("MiniRect2", "EditorIcons"),
+ Control::get_icon("MiniVector3", "EditorIcons"),
+ Control::get_icon("MiniMatrix32", "EditorIcons"),
+ Control::get_icon("MiniPlane", "EditorIcons"),
+ Control::get_icon("MiniQuat", "EditorIcons"),
+ Control::get_icon("MiniAabb", "EditorIcons"),
+ Control::get_icon("MiniMatrix3", "EditorIcons"),
+ Control::get_icon("MiniTransform", "EditorIcons"),
+ Control::get_icon("MiniColor", "EditorIcons"),
+ Control::get_icon("MiniImage", "EditorIcons"),
+ Control::get_icon("MiniPath", "EditorIcons"),
+ Control::get_icon("MiniRid", "EditorIcons"),
+ Control::get_icon("MiniObject", "EditorIcons"),
+ Control::get_icon("MiniInput", "EditorIcons"),
+ Control::get_icon("MiniDictionary", "EditorIcons"),
+ Control::get_icon("MiniArray", "EditorIcons"),
+ Control::get_icon("MiniRawArray", "EditorIcons"),
+ Control::get_icon("MiniIntArray", "EditorIcons"),
+ Control::get_icon("MiniFloatArray", "EditorIcons"),
+ Control::get_icon("MiniStringArray", "EditorIcons"),
+ Control::get_icon("MiniVector2Array", "EditorIcons"),
+ Control::get_icon("MiniVector3Array", "EditorIcons"),
+ Control::get_icon("MiniColorArray", "EditorIcons")
};
List<StringName> var_names;
script->get_variable_list(&var_names);
- for (List<StringName>::Element *E=var_names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = var_names.front(); E; E = E->next()) {
TreeItem *ti = members->create_item(variables);
- ti->set_text(0,E->get());
+ ti->set_text(0, E->get());
Variant var = script->get_variable_default_value(E->get());
- ti->set_suffix(0,"="+String(var));
- ti->set_icon(0,type_icons[script->get_variable_info(E->get()).type]);
-
- ti->set_selectable(0,true);
- ti->set_editable(0,true);
- ti->add_button(0,Control::get_icon("Edit","EditorIcons"),0);
- ti->add_button(0,Control::get_icon("Del","EditorIcons"),1);
- ti->set_metadata(0,E->get());
- if (selected==E->get())
+ ti->set_suffix(0, "=" + String(var));
+ ti->set_icon(0, type_icons[script->get_variable_info(E->get()).type]);
+
+ ti->set_selectable(0, true);
+ ti->set_editable(0, true);
+ ti->add_button(0, Control::get_icon("Edit", "EditorIcons"), 0);
+ ti->add_button(0, Control::get_icon("Del", "EditorIcons"), 1);
+ ti->set_metadata(0, E->get());
+ if (selected == E->get())
ti->select(0);
}
TreeItem *_signals = members->create_item(root);
- _signals->set_selectable(0,false);
- _signals->set_text(0,TTR("Signals:"));
- _signals->add_button(0,Control::get_icon("Add","EditorIcons"));
- _signals->set_custom_bg_color(0,Control::get_color("prop_section","Editor"));
+ _signals->set_selectable(0, false);
+ _signals->set_text(0, TTR("Signals:"));
+ _signals->add_button(0, Control::get_icon("Add", "EditorIcons"));
+ _signals->set_custom_bg_color(0, Control::get_color("prop_section", "Editor"));
List<StringName> signal_names;
script->get_custom_signal_list(&signal_names);
- for (List<StringName>::Element *E=signal_names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = signal_names.front(); E; E = E->next()) {
TreeItem *ti = members->create_item(_signals);
- ti->set_text(0,E->get());
- ti->set_selectable(0,true);
- ti->set_editable(0,true);
- ti->add_button(0,Control::get_icon("Edit","EditorIcons"),0);
- ti->add_button(0,Control::get_icon("Del","EditorIcons"),1);
- ti->set_metadata(0,E->get());
- if (selected==E->get())
+ ti->set_text(0, E->get());
+ ti->set_selectable(0, true);
+ ti->set_editable(0, true);
+ ti->add_button(0, Control::get_icon("Edit", "EditorIcons"), 0);
+ ti->add_button(0, Control::get_icon("Del", "EditorIcons"), 1);
+ ti->set_metadata(0, E->get());
+ if (selected == E->get())
ti->select(0);
}
- String base_type=script->get_instance_base_type();
- String icon_type=base_type;
- if (!Control::has_icon(base_type,"EditorIcons")) {
- icon_type="Object";
+ String base_type = script->get_instance_base_type();
+ String icon_type = base_type;
+ if (!Control::has_icon(base_type, "EditorIcons")) {
+ icon_type = "Object";
}
base_type_select->set_text(base_type);
- base_type_select->set_icon(Control::get_icon(icon_type,"EditorIcons"));
-
- updating_members=false;
+ base_type_select->set_icon(Control::get_icon(icon_type, "EditorIcons"));
+ updating_members = false;
}
void VisualScriptEditor::_member_selected() {
@@ -846,30 +806,24 @@ void VisualScriptEditor::_member_selected() {
if (updating_members)
return;
- TreeItem *ti=members->get_selected();
+ TreeItem *ti = members->get_selected();
ERR_FAIL_COND(!ti);
-
- selected=ti->get_metadata(0);
+ selected = ti->get_metadata(0);
//print_line("selected: "+String(selected));
+ if (ti->get_parent() == members->get_root()->get_children()) {
- if (ti->get_parent()==members->get_root()->get_children()) {
-
- if (edited_func!=selected) {
+ if (edited_func != selected) {
- revert_on_drag=edited_func;
- edited_func=selected;
+ revert_on_drag = edited_func;
+ edited_func = selected;
_update_members();
_update_graph();
}
return; //or crash because it will become invalid
-
}
-
-
-
}
void VisualScriptEditor::_member_edited() {
@@ -877,78 +831,75 @@ void VisualScriptEditor::_member_edited() {
if (updating_members)
return;
- TreeItem *ti=members->get_edited();
+ TreeItem *ti = members->get_edited();
ERR_FAIL_COND(!ti);
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);
- updating_members=false;
+ EditorNode::get_singleton()->show_warning(TTR("Name is not a valid identifier:") + " " + new_name);
+ updating_members = true;
+ ti->set_text(0, name);
+ updating_members = false;
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);
- updating_members=true;
- ti->set_text(0,name);
- updating_members=false;
+ 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);
+ updating_members = false;
return;
}
- TreeItem *root=members->get_root();
+ TreeItem *root = members->get_root();
- if (ti->get_parent()==root->get_children()) {
+ if (ti->get_parent() == root->get_children()) {
- if (edited_func==selected) {
- edited_func=new_name;
+ if (edited_func == selected) {
+ edited_func = new_name;
}
- selected=new_name;
-
+ selected = new_name;
_update_graph();
undo_redo->create_action(TTR("Rename Function"));
- undo_redo->add_do_method(script.ptr(),"rename_function",name,new_name);
- undo_redo->add_undo_method(script.ptr(),"rename_function",new_name,name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "rename_function", name, new_name);
+ undo_redo->add_undo_method(script.ptr(), "rename_function", new_name, name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
-
}
- if (ti->get_parent()==root->get_children()->get_next()) {
+ if (ti->get_parent() == root->get_children()->get_next()) {
- selected=new_name;
+ selected = new_name;
undo_redo->create_action(TTR("Rename Variable"));
- undo_redo->add_do_method(script.ptr(),"rename_variable",name,new_name);
- undo_redo->add_undo_method(script.ptr(),"rename_variable",new_name,name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "rename_variable", name, new_name);
+ undo_redo->add_undo_method(script.ptr(), "rename_variable", new_name, name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
}
- if (ti->get_parent()==root->get_children()->get_next()->get_next()) {
+ if (ti->get_parent() == root->get_children()->get_next()->get_next()) {
- selected=new_name;
+ selected = new_name;
undo_redo->create_action(TTR("Rename Signal"));
- undo_redo->add_do_method(script.ptr(),"rename_custom_signal",name,new_name);
- undo_redo->add_undo_method(script.ptr(),"rename_custom_signal",new_name,name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "rename_custom_signal", name, new_name);
+ undo_redo->add_undo_method(script.ptr(), "rename_custom_signal", new_name, name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
@@ -961,137 +912,131 @@ void VisualScriptEditor::_override_pressed(int p_id) {
ERR_FAIL_COND(!virtuals_in_menu.has(p_id));
- VirtualInMenu vim=virtuals_in_menu[p_id];
+ VirtualInMenu vim = virtuals_in_menu[p_id];
String name = _validate_name(vim.name);
- selected=name;
- edited_func=selected;
+ selected = name;
+ edited_func = selected;
Ref<VisualScriptFunction> func_node;
func_node.instance();
func_node->set_name(vim.name);
undo_redo->create_action(TTR("Add Function"));
- undo_redo->add_do_method(script.ptr(),"add_function",name);
- for(int i=0;i<vim.args.size();i++) {
- func_node->add_argument(vim.args[i].first,vim.args[i].second);
+ undo_redo->add_do_method(script.ptr(), "add_function", name);
+ for (int i = 0; i < vim.args.size(); i++) {
+ func_node->add_argument(vim.args[i].first, vim.args[i].second);
}
-
- undo_redo->add_do_method(script.ptr(),"add_node",name,script->get_available_id(),func_node);
- if (vim.ret!=Variant::NIL || vim.ret_variant) {
+ undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id(), func_node);
+ if (vim.ret != Variant::NIL || vim.ret_variant) {
Ref<VisualScriptReturn> ret_node;
ret_node.instance();
ret_node->set_return_type(vim.ret);
ret_node->set_enable_return_value(true);
ret_node->set_name(vim.name);
- undo_redo->add_do_method(script.ptr(),"add_node",name,script->get_available_id()+1,ret_node,Vector2(500,0));
-
+ undo_redo->add_do_method(script.ptr(), "add_node", name, script->get_available_id() + 1, ret_node, Vector2(500, 0));
}
- undo_redo->add_undo_method(script.ptr(),"remove_function",name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_undo_method(script.ptr(), "remove_function", name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
-
_update_graph();
}
void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_button) {
- TreeItem *ti=p_item->cast_to<TreeItem>();
+ TreeItem *ti = p_item->cast_to<TreeItem>();
- TreeItem *root=members->get_root();
+ TreeItem *root = members->get_root();
- if (ti->get_parent()==root) {
+ if (ti->get_parent() == root) {
//main buttons
- if (ti==root->get_children()) {
+ if (ti == root->get_children()) {
//add function, this one uses menu
- if (p_button==1) {
+ if (p_button == 1) {
new_function_menu->clear();
- new_function_menu->set_size(Size2(0,0));
- int idx=0;
+ new_function_menu->set_size(Size2(0, 0));
+ int idx = 0;
virtuals_in_menu.clear();
List<MethodInfo> mi;
- ClassDB::get_method_list(script->get_instance_base_type(),&mi);
- for (List<MethodInfo>::Element *E=mi.front();E;E=E->next()) {
- MethodInfo mi=E->get();
- if (mi.flags&METHOD_FLAG_VIRTUAL) {
+ ClassDB::get_method_list(script->get_instance_base_type(), &mi);
+ for (List<MethodInfo>::Element *E = mi.front(); E; E = E->next()) {
+ MethodInfo mi = E->get();
+ if (mi.flags & METHOD_FLAG_VIRTUAL) {
VirtualInMenu vim;
- vim.name=mi.name;
- vim.ret=mi.return_val.type;
- if (mi.return_val.name!=String())
- vim.ret_variant=true;
+ vim.name = mi.name;
+ vim.ret = mi.return_val.type;
+ if (mi.return_val.name != String())
+ vim.ret_variant = true;
else
- vim.ret_variant=false;
+ vim.ret_variant = false;
String desc;
- if (mi.return_val.type==Variant::NIL)
- desc="var";
+ if (mi.return_val.type == Variant::NIL)
+ desc = "var";
else
- desc=Variant::get_type_name(mi.return_val.type);
- desc+=" "+mi.name+" ( ";
-
+ desc = Variant::get_type_name(mi.return_val.type);
+ desc += " " + mi.name + " ( ";
- for(int i=0;i<mi.arguments.size();i++) {
+ for (int i = 0; i < mi.arguments.size(); i++) {
- if (i>0)
- desc+=", ";
+ if (i > 0)
+ desc += ", ";
- if (mi.arguments[i].type==Variant::NIL)
- desc+="var ";
+ if (mi.arguments[i].type == Variant::NIL)
+ desc += "var ";
else
- desc+=Variant::get_type_name(mi.arguments[i].type)+" ";
+ desc += Variant::get_type_name(mi.arguments[i].type) + " ";
- desc+=mi.arguments[i].name;
-
- Pair<Variant::Type,String> p;
- p.first=mi.arguments[i].type;
- p.second=mi.arguments[i].name;
- vim.args.push_back( p );
+ desc += mi.arguments[i].name;
+ Pair<Variant::Type, String> p;
+ p.first = mi.arguments[i].type;
+ p.second = mi.arguments[i].name;
+ vim.args.push_back(p);
}
- desc+=" )";
+ desc += " )";
- virtuals_in_menu[idx]=vim;
+ virtuals_in_menu[idx] = vim;
- new_function_menu->add_item(desc,idx);
+ new_function_menu->add_item(desc, idx);
idx++;
}
}
Rect2 pos = members->get_item_rect(ti);
- new_function_menu->set_pos(members->get_global_pos()+pos.pos+Vector2(0,pos.size.y));
+ new_function_menu->set_pos(members->get_global_pos() + pos.pos + Vector2(0, pos.size.y));
new_function_menu->popup();
return;
- } else if (p_button==0) {
-
+ } else if (p_button == 0) {
String name = _validate_name("new_function");
- selected=name;
- edited_func=selected;
+ selected = name;
+ edited_func = selected;
Ref<VisualScriptFunction> func_node;
func_node.instance();
func_node->set_name(name);
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);
- undo_redo->add_undo_method(script.ptr(),"remove_function",name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ 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);
+ undo_redo->add_undo_method(script.ptr(), "remove_function", name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
@@ -1099,70 +1044,67 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
}
return; //or crash because it will become invalid
-
}
- if (ti==root->get_children()->get_next()) {
+ if (ti == root->get_children()->get_next()) {
//add variable
String name = _validate_name("new_variable");
- selected=name;
+ selected = name;
undo_redo->create_action(TTR("Add Variable"));
- undo_redo->add_do_method(script.ptr(),"add_variable",name);
- undo_redo->add_undo_method(script.ptr(),"remove_variable",name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "add_variable", name);
+ undo_redo->add_undo_method(script.ptr(), "remove_variable", name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
-
}
- if (ti==root->get_children()->get_next()->get_next()) {
+ if (ti == root->get_children()->get_next()->get_next()) {
//add variable
String name = _validate_name("new_signal");
- selected=name;
+ selected = name;
undo_redo->create_action(TTR("Add Signal"));
- undo_redo->add_do_method(script.ptr(),"add_custom_signal",name);
- undo_redo->add_undo_method(script.ptr(),"remove_custom_signal",name);
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "add_custom_signal", name);
+ undo_redo->add_undo_method(script.ptr(), "remove_custom_signal", name);
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
-
}
} else {
- if (ti->get_parent()==root->get_children()) {
+ if (ti->get_parent() == root->get_children()) {
//edit/remove function
String name = ti->get_metadata(0);
- if (p_button==1) {
+ if (p_button == 1) {
//delete the function
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);
+ 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_pos(name,E->get()));
+ 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_pos(name, E->get()));
}
List<VisualScript::SequenceConnection> seq_connections;
- script->get_sequence_connection_list(name,&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);
+ 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);
}
List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(name,&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);
+ 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);
}
/*
@@ -1170,98 +1112,89 @@ void VisualScriptEditor::_member_button(Object *p_item, int p_column, int p_butt
undo_redo->add_undo_method(script.ptr(),"function_add_argument",name,script->function_get_argument_name(name,i),script->function_get_argument_type(name,i));
}
*/
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- } else if (p_button==0) {
-
+ } else if (p_button == 0) {
}
return; //or crash because it will become invalid
-
}
- if (ti->get_parent()==root->get_children()->get_next()) {
+ if (ti->get_parent() == root->get_children()->get_next()) {
//edit/remove variable
String name = ti->get_metadata(0);
- if (p_button==1) {
-
+ if (p_button == 1) {
undo_redo->create_action(TTR("Remove Variable"));
- undo_redo->add_do_method(script.ptr(),"remove_variable",name);
- undo_redo->add_undo_method(script.ptr(),"add_variable",name,script->get_variable_default_value(name));
- undo_redo->add_undo_method(script.ptr(),"set_variable_info",name,script->call("get_variable_info",name)); //return as dict
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "remove_variable", name);
+ undo_redo->add_undo_method(script.ptr(), "add_variable", name, script->get_variable_default_value(name));
+ undo_redo->add_undo_method(script.ptr(), "set_variable_info", name, script->call("get_variable_info", name)); //return as dict
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
return; //or crash because it will become invalid
- } else if (p_button==0) {
+ } else if (p_button == 0) {
variable_editor->edit(name);
- edit_variable_dialog->set_title(TTR("Editing Variable:")+" "+name);
- edit_variable_dialog->popup_centered_minsize(Size2(400,200)*EDSCALE);
+ edit_variable_dialog->set_title(TTR("Editing Variable:") + " " + name);
+ edit_variable_dialog->popup_centered_minsize(Size2(400, 200) * EDSCALE);
}
-
}
- if (ti->get_parent()==root->get_children()->get_next()->get_next()) {
+ if (ti->get_parent() == root->get_children()->get_next()->get_next()) {
//edit/remove variable
String name = ti->get_metadata(0);
- if (p_button==1) {
+ if (p_button == 1) {
undo_redo->create_action(TTR("Remove Signal"));
- undo_redo->add_do_method(script.ptr(),"remove_custom_signal",name);
- undo_redo->add_undo_method(script.ptr(),"add_custom_signal",name);
+ undo_redo->add_do_method(script.ptr(), "remove_custom_signal", name);
+ undo_redo->add_undo_method(script.ptr(), "add_custom_signal", name);
- for(int i=0;i<script->custom_signal_get_argument_count(name);i++) {
- undo_redo->add_undo_method(script.ptr(),"custom_signal_add_argument",name,script->custom_signal_get_argument_name(name,i),script->custom_signal_get_argument_type(name,i));
+ for (int i = 0; i < script->custom_signal_get_argument_count(name); i++) {
+ undo_redo->add_undo_method(script.ptr(), "custom_signal_add_argument", name, script->custom_signal_get_argument_name(name, i), script->custom_signal_get_argument_type(name, i));
}
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
- } else if (p_button==0) {
+ } else if (p_button == 0) {
signal_editor->edit(name);
- edit_signal_dialog->set_title(TTR("Editing Signal:")+" "+name);
- edit_signal_dialog->popup_centered_minsize(Size2(400,300)*EDSCALE);
+ edit_signal_dialog->set_title(TTR("Editing Signal:") + " " + name);
+ edit_signal_dialog->popup_centered_minsize(Size2(400, 300) * EDSCALE);
}
return; //or crash because it will become invalid
-
}
-
-
}
}
-void VisualScriptEditor::_expression_text_changed(const String& p_text,int p_id) {
+void VisualScriptEditor::_expression_text_changed(const String &p_text, int p_id) {
- Ref<VisualScriptExpression> vse = script->get_node(edited_func,p_id);
+ Ref<VisualScriptExpression> vse = script->get_node(edited_func, p_id);
if (!vse.is_valid())
return;
+ updating_graph = true;
- updating_graph=true;
-
- undo_redo->create_action(TTR("Change Expression"),UndoRedo::MERGE_ENDS);
- undo_redo->add_do_property(vse.ptr(),"expression",p_text);
- undo_redo->add_undo_property(vse.ptr(),"expression",vse->get("expression"));
- undo_redo->add_do_method(this,"_update_graph",p_id);
- undo_redo->add_undo_method(this,"_update_graph",p_id);
+ undo_redo->create_action(TTR("Change Expression"), UndoRedo::MERGE_ENDS);
+ undo_redo->add_do_property(vse.ptr(), "expression", p_text);
+ undo_redo->add_undo_property(vse.ptr(), "expression", vse->get("expression"));
+ undo_redo->add_do_method(this, "_update_graph", p_id);
+ undo_redo->add_undo_method(this, "_update_graph", p_id);
undo_redo->commit_action();
Node *node = graph->get_node(itos(p_id));
if (node->cast_to<Control>())
- node->cast_to<Control>()->set_size(Vector2(1,1)); //shrink if text is smaller
-
- updating_graph=false;
+ node->cast_to<Control>()->set_size(Vector2(1, 1)); //shrink if text is smaller
+ updating_graph = false;
}
void VisualScriptEditor::_available_node_doubleclicked() {
@@ -1272,27 +1205,27 @@ void VisualScriptEditor::_available_node_doubleclicked() {
return;
String which = item->get_metadata(0);
- if (which==String())
+ if (which == String())
return;
Vector2 ofs = graph->get_scroll_ofs() + graph->get_size() * 0.5;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
- while(true) {
- bool exists=false;
+ while (true) {
+ bool exists = false;
List<int> existing;
- script->get_node_list(edited_func,&existing);
- for (List<int>::Element *E=existing.front();E;E=E->next()) {
- Point2 pos = script->get_node_pos(edited_func,E->get());
- if (pos.distance_to(ofs)<15) {
- ofs+=Vector2(graph->get_snap(),graph->get_snap());
- exists=true;
+ script->get_node_list(edited_func, &existing);
+ for (List<int>::Element *E = existing.front(); E; E = E->next()) {
+ Point2 pos = script->get_node_pos(edited_func, E->get());
+ if (pos.distance_to(ofs) < 15) {
+ ofs += Vector2(graph->get_snap(), graph->get_snap());
+ exists = true;
break;
}
}
@@ -1300,26 +1233,23 @@ void VisualScriptEditor::_available_node_doubleclicked() {
if (exists)
continue;
break;
-
}
-
Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(which);
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,vnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
-
}
void VisualScriptEditor::_update_available_nodes() {
@@ -1328,63 +1258,61 @@ void VisualScriptEditor::_update_available_nodes() {
TreeItem *root = nodes->create_item();
- Map<String,TreeItem*> path_cache;
+ Map<String, TreeItem *> path_cache;
String filter = node_filter->get_text();
List<String> fnodes;
VisualScriptLanguage::singleton->get_registered_node_names(&fnodes);
- for (List<String>::Element *E=fnodes.front();E;E=E->next()) {
-
+ for (List<String>::Element *E = fnodes.front(); E; E = E->next()) {
Vector<String> path = E->get().split("/");
- if (filter!=String() && path.size() && path[path.size()-1].findn(filter)==-1)
+ if (filter != String() && path.size() && path[path.size() - 1].findn(filter) == -1)
continue;
String sp;
- TreeItem* parent=root;
+ TreeItem *parent = root;
- for(int i=0;i<path.size()-1;i++) {
+ for (int i = 0; i < path.size() - 1; i++) {
- if (i>0)
- sp+=",";
- sp+=path[i];
+ if (i > 0)
+ sp += ",";
+ sp += path[i];
if (!path_cache.has(sp)) {
- TreeItem* pathn = nodes->create_item(parent);
- pathn->set_selectable(0,false);
- pathn->set_text(0,path[i].capitalize());
- path_cache[sp]=pathn;
- parent=pathn;
- if (filter==String()) {
+ TreeItem *pathn = nodes->create_item(parent);
+ pathn->set_selectable(0, false);
+ pathn->set_text(0, path[i].capitalize());
+ path_cache[sp] = pathn;
+ parent = pathn;
+ if (filter == String()) {
pathn->set_collapsed(true); //should remember state
}
} else {
- parent=path_cache[sp];
+ parent = path_cache[sp];
}
}
TreeItem *item = nodes->create_item(parent);
- item->set_text(0,path[path.size()-1].capitalize());
- item->set_selectable(0,true);
- item->set_metadata(0,E->get());
+ item->set_text(0, path[path.size() - 1].capitalize());
+ item->set_selectable(0, true);
+ item->set_metadata(0, E->get());
}
-
}
-String VisualScriptEditor::_validate_name(const String& p_name) const {
+String VisualScriptEditor::_validate_name(const String &p_name) const {
- String valid=p_name;
+ String valid = p_name;
- int counter=1;
- while(true) {
+ int counter = 1;
+ while (true) {
bool exists = script->has_function(valid) || script->has_variable(valid) || script->has_custom_signal(valid);
if (exists) {
counter++;
- valid=p_name+"_"+itos(counter);
+ valid = p_name + "_" + itos(counter);
continue;
}
@@ -1396,10 +1324,9 @@ String VisualScriptEditor::_validate_name(const String& p_name) const {
void VisualScriptEditor::_on_nodes_delete() {
-
List<int> to_erase;
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
if (gn->is_selected() && gn->is_close_button_visible()) {
@@ -1413,48 +1340,42 @@ void VisualScriptEditor::_on_nodes_delete() {
undo_redo->create_action("Remove VisualScript Nodes");
- for(List<int>::Element*F=to_erase.front();F;F=F->next()) {
-
-
- undo_redo->add_do_method(script.ptr(),"remove_node",edited_func,F->get());
- undo_redo->add_undo_method(script.ptr(),"add_node",edited_func,F->get(),script->get_node(edited_func,F->get()),script->get_node_pos(edited_func,F->get()));
+ for (List<int>::Element *F = to_erase.front(); F; F = F->next()) {
+ undo_redo->add_do_method(script.ptr(), "remove_node", edited_func, F->get());
+ undo_redo->add_undo_method(script.ptr(), "add_node", edited_func, F->get(), script->get_node(edited_func, F->get()), script->get_node_pos(edited_func, F->get()));
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(edited_func,&sequence_conns);
+ script->get_sequence_connection_list(edited_func, &sequence_conns);
+ for (List<VisualScript::SequenceConnection>::Element *E = sequence_conns.front(); E; E = E->next()) {
- for (List<VisualScript::SequenceConnection>::Element *E=sequence_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(),"sequence_connect",edited_func,E->get().from_node,E->get().from_output,E->get().to_node);
+ if (E->get().from_node == F->get() || E->get().to_node == F->get()) {
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, E->get().from_node, E->get().from_output, E->get().to_node);
}
}
List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(edited_func,&data_conns);
+ script->get_data_connection_list(edited_func, &data_conns);
- for (List<VisualScript::DataConnection>::Element *E=data_conns.front();E;E=E->next()) {
+ 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",edited_func,E->get().from_node,E->get().from_port,E->get().to_node,E->get().to_port);
+ if (E->get().from_node == F->get() || E->get().to_node == F->get()) {
+ undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
}
}
-
}
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
}
-
void VisualScriptEditor::_on_nodes_duplicate() {
-
List<int> to_duplicate;
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
if (gn->is_selected() && gn->is_close_button_visible()) {
@@ -1467,64 +1388,60 @@ void VisualScriptEditor::_on_nodes_duplicate() {
return;
undo_redo->create_action("Duplicate VisualScript Nodes");
- int idc=script->get_available_id()+1;
+ int idc = script->get_available_id() + 1;
Set<int> to_select;
- for(List<int>::Element*F=to_duplicate.front();F;F=F->next()) {
+ for (List<int>::Element *F = to_duplicate.front(); F; F = F->next()) {
- Ref<VisualScriptNode> node = script->get_node(edited_func,F->get());
+ Ref<VisualScriptNode> node = script->get_node(edited_func, F->get());
Ref<VisualScriptNode> dupe = node->duplicate();
int new_id = idc++;
to_select.insert(new_id);
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,dupe,script->get_node_pos(edited_func,F->get())+Vector2(20,20));
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
-
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, dupe, script->get_node_pos(edited_func, F->get()) + Vector2(20, 20));
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
}
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
int id = gn->get_name().operator String().to_int();
gn->set_selected(to_select.has(id));
-
}
}
if (to_select.size()) {
- EditorNode::get_singleton()->push_item(script->get_node(edited_func,to_select.front()->get()).ptr());
+ EditorNode::get_singleton()->push_item(script->get_node(edited_func, to_select.front()->get()).ptr());
}
-
}
-void VisualScriptEditor::_input(const InputEvent& p_event) {
+void VisualScriptEditor::_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index==BUTTON_LEFT) {
- revert_on_drag=String(); //so we can still drag functions
+ if (p_event.type == InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index == BUTTON_LEFT) {
+ revert_on_drag = String(); //so we can still drag functions
}
}
-Variant VisualScriptEditor::get_drag_data_fw(const Point2& p_point,Control* p_from) {
+Variant VisualScriptEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
-
- if (p_from==nodes) {
+ if (p_from == nodes) {
TreeItem *it = nodes->get_item_at_pos(p_point);
if (!it)
return Variant();
- String type=it->get_metadata(0);
- if (type==String())
+ String type = it->get_metadata(0);
+ if (type == String())
return Variant();
Dictionary dd;
- dd["type"]="visual_script_node_drag";
- dd["node_type"]=type;
+ dd["type"] = "visual_script_node_drag";
+ dd["node_type"] = type;
Label *label = memnew(Label);
label->set_text(it->get_text(0));
@@ -1532,49 +1449,42 @@ Variant VisualScriptEditor::get_drag_data_fw(const Point2& p_point,Control* p_fr
return dd;
}
- if (p_from==members) {
-
+ if (p_from == members) {
TreeItem *it = members->get_item_at_pos(p_point);
if (!it)
return Variant();
- String type=it->get_metadata(0);
+ String type = it->get_metadata(0);
- if (type==String())
+ if (type == String())
return Variant();
-
Dictionary dd;
- TreeItem *root=members->get_root();
+ TreeItem *root = members->get_root();
- if (it->get_parent()==root->get_children()) {
+ if (it->get_parent() == root->get_children()) {
- dd["type"]="visual_script_function_drag";
- dd["function"]=type;
- if (revert_on_drag!=String()) {
- edited_func=revert_on_drag; //revert so function does not change
- revert_on_drag=String();
+ dd["type"] = "visual_script_function_drag";
+ dd["function"] = type;
+ if (revert_on_drag != String()) {
+ edited_func = revert_on_drag; //revert so function does not change
+ revert_on_drag = String();
_update_graph();
}
- } else if (it->get_parent()==root->get_children()->get_next()) {
+ } 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_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;
+ dd["type"] = "visual_script_signal_drag";
+ dd["signal"] = type;
} else {
return Variant();
}
-
-
-
-
-
Label *label = memnew(Label);
label->set_text(it->get_text(0));
set_drag_preview(label);
@@ -1583,78 +1493,69 @@ Variant VisualScriptEditor::get_drag_data_fw(const Point2& p_point,Control* p_fr
return Variant();
}
-bool VisualScriptEditor::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{
-
- if (p_from==graph) {
+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" ||
- String(d["type"])=="visual_script_function_drag" ||
- String(d["type"])=="visual_script_variable_drag" ||
- String(d["type"])=="visual_script_signal_drag" ||
- String(d["type"])=="obj_property" ||
- String(d["type"])=="resource" ||
- String(d["type"])=="files" ||
- String(d["type"])=="nodes"
- ) ) {
-
+ (String(d["type"]) == "visual_script_node_drag" ||
+ String(d["type"]) == "visual_script_function_drag" ||
+ String(d["type"]) == "visual_script_variable_drag" ||
+ String(d["type"]) == "visual_script_signal_drag" ||
+ String(d["type"]) == "obj_property" ||
+ String(d["type"]) == "resource" ||
+ String(d["type"]) == "files" ||
+ String(d["type"]) == "nodes")) {
- if (String(d["type"])=="obj_property") {
+ if (String(d["type"]) == "obj_property") {
#ifdef OSX_ENABLED
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Meta to drop a Getter. Hold Shift to drop a generic signature."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Meta to drop a Getter. Hold Shift to drop a generic signature."));
#else
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Ctrl to drop a Getter. Hold Shift to drop a generic signature."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a Getter. Hold Shift to drop a generic signature."));
#endif
- }
+ }
- if (String(d["type"])=="nodes") {
+ if (String(d["type"]) == "nodes") {
#ifdef OSX_ENABLED
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Meta to drop a simple reference to the node."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Meta to drop a simple reference to the node."));
#else
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Ctrl to drop a simple reference to the node."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a simple reference to the node."));
#endif
- }
+ }
- if (String(d["type"])=="visual_script_variable_drag") {
+ if (String(d["type"]) == "visual_script_variable_drag") {
#ifdef OSX_ENABLED
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Meta to drop a Variable Setter."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Meta to drop a Variable Setter."));
#else
- const_cast<VisualScriptEditor*>(this)->_show_hint(TTR("Hold Ctrl to drop a Variable Setter."));
+ const_cast<VisualScriptEditor *>(this)->_show_hint(TTR("Hold Ctrl to drop a Variable Setter."));
#endif
- }
-
- return true;
+ }
+ return true;
}
-
-
-
}
-
return false;
}
#ifdef TOOLS_ENABLED
-static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const Ref<Script> &script) {
+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 NULL;
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);
+ 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)
return n;
}
@@ -1664,43 +1565,40 @@ static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const R
#endif
+void VisualScriptEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
-
-void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){
-
- if (p_from==graph) {
+ if (p_from == graph) {
Dictionary d = p_data;
- if (d.has("type") && String(d["type"])=="visual_script_node_drag") {
+ if (d.has("type") && String(d["type"]) == "visual_script_node_drag") {
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
-
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Ref<VisualScriptNode> vnode = VisualScriptLanguage::singleton->create_node_from_name(d["node_type"]);
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,vnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
}
- if (d.has("type") && String(d["type"])=="visual_script_variable_drag") {
+ if (d.has("type") && String(d["type"]) == "visual_script_variable_drag") {
#ifdef OSX_ENABLED
bool use_set = Input::get_singleton()->is_key_pressed(KEY_META);
@@ -1710,50 +1608,50 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Ref<VisualScriptNode> vnode;
if (use_set) {
Ref<VisualScriptVariableSet> vnodes;
vnodes.instance();
vnodes->set_variable(d["variable"]);
- vnode=vnodes;
+ vnode = vnodes;
} else {
Ref<VisualScriptVariableGet> vnodeg;
vnodeg.instance();
vnodeg->set_variable(d["variable"]);
- vnode=vnodeg;
+ vnode = vnodeg;
}
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,vnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
}
- if (d.has("type") && String(d["type"])=="visual_script_function_drag") {
+ if (d.has("type") && 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();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Ref<VisualScriptFunctionCall> vnode;
vnode.instance();
@@ -1762,33 +1660,31 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,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_do_method(script.ptr(), "add_node", edited_func, 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",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
-
}
-
- if (d.has("type") && String(d["type"])=="visual_script_signal_drag") {
+ if (d.has("type") && 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();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Ref<VisualScriptEmitSignal> vnode;
vnode.instance();
@@ -1797,28 +1693,28 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,vnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
}
- if (d.has("type") && String(d["type"])=="resource") {
+ if (d.has("type") && String(d["type"]) == "resource") {
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Ref<VisualScriptPreload> prnode;
prnode.instance();
@@ -1827,28 +1723,28 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Preload Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,prnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, prnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- Node* node = graph->get_node(itos(new_id));
+ Node *node = graph->get_node(itos(new_id));
if (node) {
graph->set_selected(node);
_node_selected(node);
}
}
- if (d.has("type") && String(d["type"])=="files") {
+ if (d.has("type") && String(d["type"]) == "files") {
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
Array files = d["files"];
@@ -1858,7 +1754,7 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
if (files.size()) {
undo_redo->create_action(TTR("Add Preload Node"));
- for(int i=0;i<files.size();i++) {
+ for (int i = 0; i < files.size(); i++) {
Ref<Resource> res = ResourceLoader::load(files[i]);
if (!res.is_valid())
@@ -1868,22 +1764,21 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
prnode.instance();
prnode->set_preload(res);
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,prnode,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, prnode, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, new_id);
new_ids.push_back(new_id);
new_id++;
- ofs+=Vector2(20,20)*EDSCALE;
+ ofs += Vector2(20, 20) * EDSCALE;
}
-
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
}
- for(List<int>::Element *E=new_ids.front();E;E=E->next()) {
+ for (List<int>::Element *E = new_ids.front(); E; E = E->next()) {
- Node* node = graph->get_node(itos(E->get()));
+ Node *node = graph->get_node(itos(E->get()));
if (node) {
graph->set_selected(node);
_node_selected(node);
@@ -1891,42 +1786,39 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
}
}
- if (d.has("type") && String(d["type"])=="nodes") {
-
- Node* sn = _find_script_node(get_tree()->get_edited_scene_root(),get_tree()->get_edited_scene_root(),script);
+ if (d.has("type") && String(d["type"]) == "nodes") {
+ Node *sn = _find_script_node(get_tree()->get_edited_scene_root(), get_tree()->get_edited_scene_root(), script);
if (!sn) {
- EditorNode::get_singleton()->show_warning("Can't drop nodes because script '"+get_name()+"' is not used in this scene.");
+ EditorNode::get_singleton()->show_warning("Can't drop nodes because script '" + get_name() + "' is not used in this scene.");
return;
}
-
#ifdef OSX_ENABLED
bool use_node = Input::get_singleton()->is_key_pressed(KEY_META);
#else
bool use_node = Input::get_singleton()->is_key_pressed(KEY_CONTROL);
#endif
-
Array nodes = d["nodes"];
Vector2 ofs = graph->get_scroll_ofs() + p_point;
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
undo_redo->create_action(TTR("Add Node(s) From Tree"));
int base_id = script->get_available_id();
- if (nodes.size()>1) {
- use_node=true;
+ if (nodes.size() > 1) {
+ use_node = true;
}
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
NodePath np = nodes[i];
Node *node = get_node(np);
@@ -1940,8 +1832,7 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
Ref<VisualScriptSceneNode> scene_node;
scene_node.instance();
scene_node->set_node_path(sn->get_path_to(node));
- n=scene_node;
-
+ n = scene_node;
} else {
Ref<VisualScriptFunctionCall> call;
@@ -1949,38 +1840,33 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
call->set_call_mode(VisualScriptFunctionCall::CALL_MODE_NODE_PATH);
call->set_base_path(sn->get_path_to(node));
call->set_base_type(node->get_class());
- n=call;
+ n = call;
method_select->select_method_from_instance(node);
- selecting_method_id=base_id;
-
+ selecting_method_id = base_id;
}
-
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,base_id,n,ofs);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,base_id);
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, base_id, n, ofs);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id);
base_id++;
- ofs+=Vector2(25,25);
+ ofs += Vector2(25, 25);
}
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
-
-
}
- if (d.has("type") && String(d["type"])=="obj_property") {
-
- Node* sn = _find_script_node(get_tree()->get_edited_scene_root(),get_tree()->get_edited_scene_root(),script);
+ if (d.has("type") && 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)) {
- EditorNode::get_singleton()->show_warning("Can't drop properties because script '"+get_name()+"' is not used in this scene.\nDrop holding 'Shift' to just copy the signature.");
+ EditorNode::get_singleton()->show_warning("Can't drop properties because script '" + get_name() + "' is not used in this scene.\nDrop holding 'Shift' to just copy the signature.");
return;
}
- Object *obj=d["object"];
+ Object *obj = d["object"];
if (!obj)
return;
@@ -1990,10 +1876,10 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
if (graph->is_using_snap()) {
int snap = graph->get_snap();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
#ifdef OSX_ENABLED
bool use_get = Input::get_singleton()->is_key_pressed(KEY_META);
#else
@@ -2002,7 +1888,6 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
if (!node || Input::get_singleton()->is_key_pressed(KEY_SHIFT)) {
-
if (use_get)
undo_redo->create_action(TTR("Add Getter Property"));
else
@@ -2022,7 +1907,7 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
pset->set_use_builtin_value(true);
pset->set_builtin_value(d["value"]);
}*/
- vnode=pset;
+ vnode = pset;
} else {
Ref<VisualScriptPropertyGet> pget;
@@ -2030,26 +1915,23 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
pget->set_base_type(obj->get_class());
- vnode=pget;
-
+ vnode = pget;
}
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,base_id,vnode,ofs);
- undo_redo->add_do_method(vnode.ptr(),"set_property",d["property"]);
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, 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_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
}
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,base_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
} else {
-
-
if (use_get)
undo_redo->create_action(TTR("Add Getter Property"));
else
@@ -2063,74 +1945,63 @@ void VisualScriptEditor::drop_data_fw(const Point2& p_point,const Variant& p_dat
Ref<VisualScriptPropertySet> pset;
pset.instance();
- if (sn==node) {
+ if (sn == node) {
pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_SELF);
} else {
pset->set_call_mode(VisualScriptPropertySet::CALL_MODE_NODE_PATH);
pset->set_base_path(sn->get_path_to(node));
}
- vnode=pset;
+ vnode = pset;
} else {
Ref<VisualScriptPropertyGet> pget;
pget.instance();
- if (sn==node) {
+ if (sn == node) {
pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_SELF);
} else {
pget->set_call_mode(VisualScriptPropertyGet::CALL_MODE_NODE_PATH);
pget->set_base_path(sn->get_path_to(node));
}
- vnode=pget;
-
+ vnode = pget;
}
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,base_id,vnode,ofs);
- undo_redo->add_do_method(vnode.ptr(),"set_property",d["property"]);
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, 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_do_method(vnode.ptr(), "set_default_input_value", 0, d["value"]);
}
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,base_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, base_id);
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
}
-
-
}
-
-
}
-
-
}
+void VisualScriptEditor::_selected_method(const String &p_method) {
-void VisualScriptEditor::_selected_method(const String& p_method) {
-
- Ref<VisualScriptFunctionCall> vsfc = script->get_node(edited_func,selecting_method_id);
+ Ref<VisualScriptFunctionCall> vsfc = script->get_node(edited_func, selecting_method_id);
if (!vsfc.is_valid())
return;
vsfc->set_function(p_method);
-
}
-void VisualScriptEditor::_draw_color_over_button(Object* obj,Color p_color) {
+void VisualScriptEditor::_draw_color_over_button(Object *obj, Color p_color) {
Button *button = obj->cast_to<Button>();
if (!button)
return;
- Ref<StyleBox> normal = get_stylebox("normal","Button" );
- button->draw_rect(Rect2(normal->get_offset(),button->get_size()-normal->get_minimum_size()),p_color);
-
+ Ref<StyleBox> normal = get_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<Texture>& p_preview,Variant p_ud) {
-
+void VisualScriptEditor::_button_resource_previewed(const String &p_path, const Ref<Texture> &p_preview, Variant p_ud) {
- Array ud=p_ud;
- ERR_FAIL_COND(ud.size()!=2);
+ Array ud = p_ud;
+ ERR_FAIL_COND(ud.size() != 2);
ObjectID id = ud[0];
Object *obj = ObjectDB::get_instance(id);
@@ -2147,73 +2018,63 @@ void VisualScriptEditor::_button_resource_previewed(const String& p_path,const R
b->set_icon(p_preview);
}
-
}
/////////////////////////
-
-
void VisualScriptEditor::apply_code() {
-
-
}
-Ref<Script> VisualScriptEditor::get_edited_script() const{
+Ref<Script> VisualScriptEditor::get_edited_script() const {
return script;
}
-Vector<String> VisualScriptEditor::get_functions(){
+Vector<String> VisualScriptEditor::get_functions() {
return Vector<String>();
}
-void VisualScriptEditor::set_edited_script(const Ref<Script>& p_script){
-
-
- script=p_script;
- signal_editor->script=p_script;
- signal_editor->undo_redo=undo_redo;
- variable_editor->script=p_script;
- variable_editor->undo_redo=undo_redo;
+void VisualScriptEditor::set_edited_script(const Ref<Script> &p_script) {
+ script = p_script;
+ signal_editor->script = p_script;
+ signal_editor->undo_redo = undo_redo;
+ variable_editor->script = p_script;
+ variable_editor->undo_redo = undo_redo;
- script->connect("node_ports_changed",this,"_node_ports_changed");
+ script->connect("node_ports_changed", this, "_node_ports_changed");
_update_members();
_update_available_nodes();
}
-void VisualScriptEditor::reload_text(){
-
-
+void VisualScriptEditor::reload_text() {
}
-String VisualScriptEditor::get_name(){
+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 (script->get_path().find("local://") == -1 && script->get_path().find("::") == -1) {
+ name = script->get_path().get_file();
if (is_unsaved()) {
- name+="(*)";
+ name += "(*)";
}
- } else if (script->get_name()!="")
- name=script->get_name();
+ } else if (script->get_name() != "")
+ name = script->get_name();
else
- name=script->get_class()+"("+itos(script->get_instance_ID())+")";
+ name = script->get_class() + "(" + itos(script->get_instance_ID()) + ")";
return name;
-
}
-Ref<Texture> VisualScriptEditor::get_icon(){
+Ref<Texture> VisualScriptEditor::get_icon() {
- return Control::get_icon("VisualScript","EditorIcons");
+ return Control::get_icon("VisualScript", "EditorIcons");
}
-bool VisualScriptEditor::is_unsaved(){
+bool VisualScriptEditor::is_unsaved() {
#ifdef TOOLS_ENABLED
return script->is_edited() || script->are_subnodes_edited();
@@ -2222,24 +2083,23 @@ bool VisualScriptEditor::is_unsaved(){
#endif
}
-Variant VisualScriptEditor::get_edit_state(){
+Variant VisualScriptEditor::get_edit_state() {
Dictionary d;
- d["function"]=edited_func;
- d["scroll"]=graph->get_scroll_ofs();
- d["zoom"]=graph->get_zoom();
- d["using_snap"]=graph->is_using_snap();
- d["snap"]=graph->get_snap();
+ d["function"] = edited_func;
+ d["scroll"] = graph->get_scroll_ofs();
+ d["zoom"] = graph->get_zoom();
+ d["using_snap"] = graph->is_using_snap();
+ d["snap"] = graph->get_snap();
return d;
}
-void VisualScriptEditor::set_edit_state(const Variant& p_state){
+void VisualScriptEditor::set_edit_state(const Variant &p_state) {
Dictionary d = p_state;
if (d.has("function")) {
- edited_func=p_state;
- selected=edited_func;
-
+ edited_func = p_state;
+ selected = edited_func;
}
_update_graph();
@@ -2257,10 +2117,8 @@ void VisualScriptEditor::set_edit_state(const Variant& p_state){
if (d.has("snap_enabled")) {
graph->set_use_snap(d["snap_enabled"]);
}
-
}
-
void VisualScriptEditor::_center_on_node(int p_id) {
Node *n = graph->get_node(itos(p_id));
@@ -2269,94 +2127,87 @@ void VisualScriptEditor::_center_on_node(int p_id) {
GraphNode *gn = n->cast_to<GraphNode>();
if (gn) {
gn->set_selected(true);
- Vector2 new_scroll = gn->get_offset() - graph->get_size()*0.5 + gn->get_size()*0.5;
- graph->set_scroll_ofs( new_scroll );
- script->set_function_scroll(edited_func,new_scroll/EDSCALE);
+ Vector2 new_scroll = gn->get_offset() - graph->get_size() * 0.5 + gn->get_size() * 0.5;
+ graph->set_scroll_ofs(new_scroll);
+ script->set_function_scroll(edited_func, new_scroll / EDSCALE);
script->set_edited(true); //so it's saved
-
}
}
-void VisualScriptEditor::goto_line(int p_line, bool p_with_error){
+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)
- error_line=p_line;
+ error_line = p_line;
List<StringName> functions;
script->get_function_list(&functions);
- for (List<StringName>::Element *E=functions.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = functions.front(); E; E = E->next()) {
- if (script->has_node(E->get(),p_line)) {
+ if (script->has_node(E->get(), p_line)) {
- edited_func=E->get();
- selected=edited_func;
+ edited_func = E->get();
+ selected = edited_func;
_update_graph();
_update_members();
- call_deferred("_center_on_node",p_line); //editor might be just created and size might not exist yet
+ call_deferred("_center_on_node", p_line); //editor might be just created and size might not exist yet
return;
}
}
}
-void VisualScriptEditor::trim_trailing_whitespace(){
-
-
+void VisualScriptEditor::trim_trailing_whitespace() {
}
-void VisualScriptEditor::ensure_focus(){
+void VisualScriptEditor::ensure_focus() {
graph->grab_focus();
}
-void VisualScriptEditor::tag_saved_version(){
-
-
+void VisualScriptEditor::tag_saved_version() {
}
-void VisualScriptEditor::reload(bool p_soft){
-
-
+void VisualScriptEditor::reload(bool p_soft) {
}
-void VisualScriptEditor::get_breakpoints(List<int> *p_breakpoints){
+void VisualScriptEditor::get_breakpoints(List<int> *p_breakpoints) {
List<StringName> functions;
script->get_function_list(&functions);
- for (List<StringName>::Element *E=functions.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = functions.front(); E; E = E->next()) {
List<int> nodes;
- script->get_node_list(E->get(),&nodes);
- for (List<int>::Element *F=nodes.front();F;F=F->next()) {
+ script->get_node_list(E->get(), &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(E->get(), F->get());
if (vsn->is_breakpoint()) {
- p_breakpoints->push_back(F->get()-1); //subtract 1 because breakpoints in text start from zero
+ p_breakpoints->push_back(F->get() - 1); //subtract 1 because breakpoints in text start from zero
}
}
}
}
-bool VisualScriptEditor::goto_method(const String& p_method){
+bool VisualScriptEditor::goto_method(const String &p_method) {
if (!script->has_function(p_method))
return false;
- edited_func=p_method;
- selected=edited_func;
+ edited_func = p_method;
+ selected = edited_func;
_update_members();
_update_graph();
return true;
}
-void VisualScriptEditor::add_callback(const String& p_function,PoolStringArray p_args){
+void VisualScriptEditor::add_callback(const String &p_function, PoolStringArray p_args) {
if (script->has_function(p_function)) {
- edited_func=p_function;
- selected=edited_func;
+ edited_func = p_function;
+ selected = edited_func;
_update_members();
_update_graph();
return;
@@ -2364,59 +2215,56 @@ void VisualScriptEditor::add_callback(const String& p_function,PoolStringArray p
Ref<VisualScriptFunction> func;
func.instance();
- for(int i=0;i<p_args.size();i++) {
+ for (int i = 0; i < p_args.size(); i++) {
String name = p_args[i];
- Variant::Type type=Variant::NIL;
+ Variant::Type type = Variant::NIL;
- if (name.find(":")!=-1) {
- String tt = name.get_slice(":",1);
- name=name.get_slice(":",0);
- for(int j=0;j<Variant::VARIANT_MAX;j++) {
+ if (name.find(":") != -1) {
+ 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);
+ if (tname == tt) {
+ type = Variant::Type(j);
break;
}
}
}
- func->add_argument(type,name);
+ func->add_argument(type, name);
}
func->set_name(p_function);
script->add_function(p_function);
- script->add_node(p_function,script->get_available_id(),func);
+ script->add_node(p_function, script->get_available_id(), func);
- edited_func=p_function;
- selected=edited_func;
+ edited_func = p_function;
+ selected = edited_func;
_update_members();
_update_graph();
- graph->call_deferred("set_scroll_ofs",script->get_function_scroll(edited_func)); //for first time it might need to be later
+ graph->call_deferred("set_scroll_ofs", script->get_function_scroll(edited_func)); //for first time it might need to be later
//undo_redo->clear_history();
-
}
-void VisualScriptEditor::update_settings(){
+void VisualScriptEditor::update_settings() {
_update_graph();
}
void VisualScriptEditor::set_debugger_active(bool p_active) {
if (!p_active) {
- error_line=-1;
+ error_line = -1;
_update_graph(); //clear line break
}
}
-void VisualScriptEditor::set_tooltip_request_func(String p_method,Object* p_obj){
-
-
+void VisualScriptEditor::set_tooltip_request_func(String p_method, Object *p_obj) {
}
-Control *VisualScriptEditor::get_edit_menu(){
+Control *VisualScriptEditor::get_edit_menu() {
return edit_menu;
}
@@ -2430,58 +2278,53 @@ void VisualScriptEditor::_change_base_type_callback() {
String bt = select_base_type->get_selected_type();
- ERR_FAIL_COND(bt==String());
+ ERR_FAIL_COND(bt == String());
undo_redo->create_action("Change Base Type");
- undo_redo->add_do_method(script.ptr(),"set_instance_base_type",bt);
- undo_redo->add_undo_method(script.ptr(),"set_instance_base_type",script->get_instance_base_type());
- undo_redo->add_do_method(this,"_update_members");
- undo_redo->add_undo_method(this,"_update_members");
+ undo_redo->add_do_method(script.ptr(), "set_instance_base_type", bt);
+ undo_redo->add_undo_method(script.ptr(), "set_instance_base_type", script->get_instance_base_type());
+ undo_redo->add_do_method(this, "_update_members");
+ undo_redo->add_undo_method(this, "_update_members");
undo_redo->commit_action();
-
}
-void VisualScriptEditor::_node_selected(Node* p_node) {
+void VisualScriptEditor::_node_selected(Node *p_node) {
Ref<VisualScriptNode> vnode = p_node->get_meta("__vnode");
if (vnode.is_null())
return;
- EditorNode::get_singleton()->push_item(vnode.ptr()); //edit node in inspector
+ 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) {
+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;
+ if (p_slot < p_node->get_output_sequence_port_count()) {
+ r_sequence = true;
+ r_real_slot = p_slot;
return true;
}
- r_real_slot=p_slot-p_node->get_output_sequence_port_count();
- r_sequence=false;
-
- return (r_real_slot<p_node->get_output_value_port_count());
+ r_real_slot = p_slot - p_node->get_output_sequence_port_count();
+ r_sequence = false;
+ return (r_real_slot < p_node->get_output_value_port_count());
}
-static bool _get_in_slot(const Ref<VisualScriptNode>& p_node,int p_slot,int& r_real_slot,bool& r_sequence) {
+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;
+ if (p_slot == 0 && p_node->has_input_sequence_port()) {
+ r_sequence = true;
+ r_real_slot = 0;
return true;
}
+ r_real_slot = p_slot - (p_node->has_input_sequence_port() ? 1 : 0);
+ r_sequence = false;
- r_real_slot=p_slot-(p_node->has_input_sequence_port()?1:0);
- r_sequence=false;
-
- return r_real_slot<p_node->get_input_value_port_count();
-
+ return r_real_slot < p_node->get_input_value_port_count();
}
-
void VisualScriptEditor::_begin_node_move() {
undo_redo->create_action("Move Node(s)");
@@ -2492,164 +2335,151 @@ void VisualScriptEditor::_end_node_move() {
undo_redo->commit_action();
}
-void VisualScriptEditor::_move_node(String func,int p_id,const Vector2& p_to) {
-
+void VisualScriptEditor::_move_node(String func, int p_id, const Vector2 &p_to) {
-
- if (func==String(edited_func)) {
- Node* node = graph->get_node(itos(p_id));
+ if (func == String(edited_func)) {
+ Node *node = graph->get_node(itos(p_id));
if (node && node->cast_to<GraphNode>())
node->cast_to<GraphNode>()->set_offset(p_to);
}
- script->set_node_pos(edited_func,p_id,p_to/EDSCALE);
+ script->set_node_pos(edited_func, p_id, p_to / EDSCALE);
}
-void VisualScriptEditor::_node_moved(Vector2 p_from,Vector2 p_to, int p_id) {
+void VisualScriptEditor::_node_moved(Vector2 p_from, Vector2 p_to, int p_id) {
- undo_redo->add_do_method(this,"_move_node",String(edited_func),p_id,p_to);
- undo_redo->add_undo_method(this,"_move_node",String(edited_func),p_id,p_from);
+ undo_redo->add_do_method(this, "_move_node", String(edited_func), p_id, p_to);
+ undo_redo->add_undo_method(this, "_move_node", String(edited_func), p_id, p_from);
}
void VisualScriptEditor::_remove_node(int p_id) {
-
undo_redo->create_action("Remove VisualScript Node");
- undo_redo->add_do_method(script.ptr(),"remove_node",edited_func,p_id);
- undo_redo->add_undo_method(script.ptr(),"add_node",edited_func,p_id,script->get_node(edited_func,p_id),script->get_node_pos(edited_func,p_id));
-
+ undo_redo->add_do_method(script.ptr(), "remove_node", edited_func, p_id);
+ undo_redo->add_undo_method(script.ptr(), "add_node", edited_func, p_id, script->get_node(edited_func, p_id), script->get_node_pos(edited_func, p_id));
List<VisualScript::SequenceConnection> sequence_conns;
- script->get_sequence_connection_list(edited_func,&sequence_conns);
-
+ script->get_sequence_connection_list(edited_func, &sequence_conns);
- for (List<VisualScript::SequenceConnection>::Element *E=sequence_conns.front();E;E=E->next()) {
+ 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",edited_func,E->get().from_node,E->get().from_output,E->get().to_node);
+ if (E->get().from_node == p_id || E->get().to_node == p_id) {
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, E->get().from_node, E->get().from_output, E->get().to_node);
}
}
List<VisualScript::DataConnection> data_conns;
- script->get_data_connection_list(edited_func,&data_conns);
+ script->get_data_connection_list(edited_func, &data_conns);
- for (List<VisualScript::DataConnection>::Element *E=data_conns.front();E;E=E->next()) {
+ 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",edited_func,E->get().from_node,E->get().from_port,E->get().to_node,E->get().to_port);
+ if (E->get().from_node == p_id || E->get().to_node == p_id) {
+ undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, E->get().from_node, E->get().from_port, E->get().to_node, E->get().to_port);
}
}
- undo_redo->add_do_method(this,"_update_graph");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
}
+void VisualScriptEditor::_node_ports_changed(const String &p_func, int p_id) {
-void VisualScriptEditor::_node_ports_changed(const String& p_func,int p_id) {
-
- if (p_func!=String(edited_func))
+ if (p_func != String(edited_func))
return;
_update_graph(p_id);
}
-void VisualScriptEditor::_graph_connected(const String& p_from,int p_from_slot,const String& p_to,int p_to_slot) {
+void VisualScriptEditor::_graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
- Ref<VisualScriptNode> from_node = script->get_node(edited_func,p_from.to_int());
+ Ref<VisualScriptNode> from_node = script->get_node(edited_func, 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
- Ref<VisualScriptNode> to_node = script->get_node(edited_func,p_to.to_int());
+ Ref<VisualScriptNode> to_node = script->get_node(edited_func, 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);
-
+ ERR_FAIL_COND(from_seq != to_seq);
undo_redo->create_action("Connect Nodes");
if (from_seq) {
- undo_redo->add_do_method(script.ptr(),"sequence_connect",edited_func,p_from.to_int(),from_port,p_to.to_int());
- undo_redo->add_undo_method(script.ptr(),"sequence_disconnect",edited_func,p_from.to_int(),from_port,p_to.to_int());
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int());
} else {
- undo_redo->add_do_method(script.ptr(),"data_connect",edited_func,p_from.to_int(),from_port,p_to.to_int(),to_port);
- undo_redo->add_undo_method(script.ptr(),"data_disconnect",edited_func,p_from.to_int(),from_port,p_to.to_int(),to_port);
+ undo_redo->add_do_method(script.ptr(), "data_connect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port);
//update nodes in sgraph
- 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", 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->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){
+void VisualScriptEditor::_graph_disconnected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot) {
- Ref<VisualScriptNode> from_node = script->get_node(edited_func,p_from.to_int());
+ Ref<VisualScriptNode> from_node = script->get_node(edited_func, 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
- Ref<VisualScriptNode> to_node = script->get_node(edited_func,p_to.to_int());
+ Ref<VisualScriptNode> to_node = script->get_node(edited_func, 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);
-
+ ERR_FAIL_COND(from_seq != to_seq);
undo_redo->create_action("Connect Nodes");
if (from_seq) {
- undo_redo->add_do_method(script.ptr(),"sequence_disconnect",edited_func,p_from.to_int(),from_port,p_to.to_int());
- undo_redo->add_undo_method(script.ptr(),"sequence_connect",edited_func,p_from.to_int(),from_port,p_to.to_int());
+ undo_redo->add_do_method(script.ptr(), "sequence_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int());
+ undo_redo->add_undo_method(script.ptr(), "sequence_connect", edited_func, p_from.to_int(), from_port, p_to.to_int());
} else {
- undo_redo->add_do_method(script.ptr(),"data_disconnect",edited_func,p_from.to_int(),from_port,p_to.to_int(),to_port);
- undo_redo->add_undo_method(script.ptr(),"data_connect",edited_func,p_from.to_int(),from_port,p_to.to_int(),to_port);
+ undo_redo->add_do_method(script.ptr(), "data_disconnect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port);
+ undo_redo->add_undo_method(script.ptr(), "data_connect", edited_func, p_from.to_int(), from_port, p_to.to_int(), to_port);
//update nodes in sgraph
- 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", 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->add_do_method(this, "_update_graph_connections");
+ undo_redo->add_undo_method(this, "_update_graph_connections");
undo_redo->commit_action();
}
+void VisualScriptEditor::_graph_connect_to_empty(const String &p_from, int p_from_slot, const Vector2 &p_release_pos) {
-
-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);
+ Node *node = graph->get_node(p_from);
if (!node)
return;
@@ -2657,54 +2487,50 @@ void VisualScriptEditor::_graph_connect_to_empty(const String& p_from,int p_from
if (!gn)
return;
- Ref<VisualScriptNode> vsn = script->get_node(edited_func,p_from.to_int());
+ Ref<VisualScriptNode> vsn = script->get_node(edited_func, p_from.to_int());
if (!vsn.is_valid())
return;
- if (p_from_slot<vsn->get_output_sequence_port_count()) {
+ if (p_from_slot < vsn->get_output_sequence_port_count()) {
port_action_popup->clear();
- port_action_popup->add_item(TTR("Condition"),CREATE_COND);
- port_action_popup->add_item(TTR("Sequence"),CREATE_SEQUENCE);
- port_action_popup->add_item(TTR("Switch"),CREATE_SWITCH);
- port_action_popup->add_item(TTR("Iterator"),CREATE_ITERATOR);
- port_action_popup->add_item(TTR("While"),CREATE_WHILE);
- port_action_popup->add_item(TTR("Return"),CREATE_RETURN);
+ port_action_popup->add_item(TTR("Condition"), CREATE_COND);
+ port_action_popup->add_item(TTR("Sequence"), CREATE_SEQUENCE);
+ port_action_popup->add_item(TTR("Switch"), CREATE_SWITCH);
+ port_action_popup->add_item(TTR("Iterator"), CREATE_ITERATOR);
+ port_action_popup->add_item(TTR("While"), CREATE_WHILE);
+ port_action_popup->add_item(TTR("Return"), CREATE_RETURN);
- port_action_node=p_from.to_int();
- port_action_output=p_from_slot;
+ port_action_node = p_from.to_int();
+ port_action_output = p_from_slot;
} else {
port_action_popup->clear();
- port_action_popup->add_item(TTR("Call"),CREATE_CALL);
- port_action_popup->add_item(TTR("Get"),CREATE_GET);
- port_action_popup->add_item(TTR("Set"),CREATE_SET);
-
-
- port_action_output=p_from_slot-vsn->get_output_sequence_port_count();
- port_action_node=p_from.to_int();
-
+ port_action_popup->add_item(TTR("Call"), CREATE_CALL);
+ port_action_popup->add_item(TTR("Get"), CREATE_GET);
+ port_action_popup->add_item(TTR("Set"), CREATE_SET);
+ port_action_output = p_from_slot - vsn->get_output_sequence_port_count();
+ port_action_node = p_from.to_int();
}
- port_action_pos=p_release_pos;
- port_action_popup->set_size(Size2(1,1));
- port_action_popup->set_pos(graph->get_global_pos()+p_release_pos);
+ port_action_pos = p_release_pos;
+ port_action_popup->set_size(Size2(1, 1));
+ port_action_popup->set_pos(graph->get_global_pos() + p_release_pos);
port_action_popup->popup();
}
-VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_node,int p_output,Set<int> &visited_nodes) {
-
+VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_node, int p_output, Set<int> &visited_nodes) {
VisualScriptNode::TypeGuess tg;
- tg.type=Variant::NIL;
+ tg.type = Variant::NIL;
if (visited_nodes.has(p_node))
return tg; //no loop
visited_nodes.insert(p_node);
- Ref<VisualScriptNode> node = script->get_node(edited_func,p_node);
+ Ref<VisualScriptNode> node = script->get_node(edited_func, p_node);
if (!node.is_valid()) {
@@ -2713,40 +2539,39 @@ VisualScriptNode::TypeGuess VisualScriptEditor::_guess_output_type(int p_node,i
Vector<VisualScriptNode::TypeGuess> in_guesses;
- for(int i=0;i<node->get_input_value_port_count();i++) {
+ for (int i = 0; i < node->get_input_value_port_count(); i++) {
PropertyInfo pi = node->get_input_value_port_info(i);
VisualScriptNode::TypeGuess g;
- g.type=pi.type;
+ g.type = pi.type;
- if (g.type==Variant::NIL || g.type==Variant::OBJECT) {
+ if (g.type == Variant::NIL || g.type == Variant::OBJECT) {
//any or object input, must further guess what this is
int from_node;
int from_port;
- if (script->get_input_value_port_connection_source(edited_func,p_node,i,&from_node,&from_port)) {
+ if (script->get_input_value_port_connection_source(edited_func, p_node, i, &from_node, &from_port)) {
- g = _guess_output_type(from_node,from_port,visited_nodes);
+ 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) {
+ 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();
+ g.type = Variant::OBJECT;
+ g.GDCLASS = obj->get_class();
+ g.script = obj->get_script();
}
}
}
-
}
in_guesses.push_back(g);
}
- return node->guess_output_type(in_guesses.ptr(),p_output);
+ return node->guess_output_type(in_guesses.ptr(), p_output);
}
void VisualScriptEditor::_port_action_menu(int p_option) {
@@ -2754,29 +2579,29 @@ 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();
- ofs = ofs.snapped(Vector2(snap,snap));
+ ofs = ofs.snapped(Vector2(snap, snap));
}
- ofs/=EDSCALE;
+ ofs /= EDSCALE;
- bool seq_connect=false;
+ bool seq_connect = false;
Ref<VisualScriptNode> vnode;
Set<int> vn;
- switch(p_option) {
+ switch (p_option) {
case CREATE_CALL: {
Ref<VisualScriptFunctionCall> n;
n.instance();
- vnode=n;
+ vnode = n;
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node,port_action_output,vn);
+ VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- if (tg.type==Variant::OBJECT) {
+ if (tg.type == Variant::OBJECT) {
n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_INSTANCE);
- if (tg.GDCLASS!=StringName()) {
+ if (tg.GDCLASS != StringName()) {
n->set_base_type(tg.GDCLASS);
} else {
n->set_base_type("Object");
@@ -2789,29 +2614,25 @@ void VisualScriptEditor::_port_action_menu(int p_option) {
new_connect_node_select->select_method_from_base_type(n->get_base_type());
}
-
} else {
n->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE);
n->set_basic_type(tg.type);
new_connect_node_select->select_method_from_basic_type(tg.type);
}
-
-
} break;
case CREATE_SET: {
Ref<VisualScriptPropertySet> n;
n.instance();
- vnode=n;
-
+ vnode = n;
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node,port_action_output,vn);
+ VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- if (tg.type==Variant::OBJECT) {
+ if (tg.type == Variant::OBJECT) {
n->set_call_mode(VisualScriptPropertySet::CALL_MODE_INSTANCE);
- if (tg.GDCLASS!=StringName()) {
+ if (tg.GDCLASS != StringName()) {
n->set_base_type(tg.GDCLASS);
} else {
n->set_base_type("Object");
@@ -2824,25 +2645,24 @@ void VisualScriptEditor::_port_action_menu(int p_option) {
new_connect_node_select->select_property_from_base_type(n->get_base_type());
}
-
} else {
n->set_call_mode(VisualScriptPropertySet::CALL_MODE_BASIC_TYPE);
n->set_basic_type(tg.type);
- new_connect_node_select->select_property_from_basic_type(tg.type,tg.ev_type);
+ new_connect_node_select->select_property_from_basic_type(tg.type, tg.ev_type);
}
} break;
case CREATE_GET: {
Ref<VisualScriptPropertyGet> n;
n.instance();
- vnode=n;
+ vnode = n;
- VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node,port_action_output,vn);
+ VisualScriptNode::TypeGuess tg = _guess_output_type(port_action_node, port_action_output, vn);
- if (tg.type==Variant::OBJECT) {
+ if (tg.type == Variant::OBJECT) {
n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_INSTANCE);
- if (tg.GDCLASS!=StringName()) {
+ if (tg.GDCLASS != StringName()) {
n->set_base_type(tg.GDCLASS);
} else {
n->set_base_type("Object");
@@ -2855,11 +2675,10 @@ void VisualScriptEditor::_port_action_menu(int p_option) {
new_connect_node_select->select_property_from_base_type(n->get_base_type());
}
-
} else {
n->set_call_mode(VisualScriptPropertyGet::CALL_MODE_BASIC_TYPE);
n->set_basic_type(tg.type);
- new_connect_node_select->select_property_from_basic_type(tg.type,tg.ev_type);
+ new_connect_node_select->select_property_from_basic_type(tg.type, tg.ev_type);
}
} break;
@@ -2867,147 +2686,139 @@ void VisualScriptEditor::_port_action_menu(int p_option) {
Ref<VisualScriptCondition> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
case CREATE_SEQUENCE: {
Ref<VisualScriptSequence> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
case CREATE_SWITCH: {
Ref<VisualScriptSwitch> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
case CREATE_ITERATOR: {
Ref<VisualScriptIterator> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
case CREATE_WHILE: {
Ref<VisualScriptWhile> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
case CREATE_RETURN: {
Ref<VisualScriptReturn> n;
n.instance();
- vnode=n;
- seq_connect=true;
+ vnode = n;
+ seq_connect = true;
} break;
-
}
int new_id = script->get_available_id();
undo_redo->create_action(TTR("Add Node"));
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,vnode,ofs);
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, vnode, ofs);
if (seq_connect) {
- undo_redo->add_do_method(script.ptr(),"sequence_connect",edited_func,port_action_node,port_action_output,new_id);
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, port_action_node, port_action_output, new_id);
}
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
- undo_redo->add_do_method(this,"_update_graph",new_id);
- undo_redo->add_undo_method(this,"_update_graph",new_id);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, 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();
- port_action_new_node=new_id;
-
+ port_action_new_node = new_id;
}
-void VisualScriptEditor::_selected_connect_node_method_or_setget(const String& p_text) {
+void VisualScriptEditor::_selected_connect_node_method_or_setget(const String &p_text) {
- Ref<VisualScriptNode> vsn = script->get_node(edited_func,port_action_new_node);
+ Ref<VisualScriptNode> vsn = script->get_node(edited_func, port_action_new_node);
if (vsn->cast_to<VisualScriptFunctionCall>()) {
Ref<VisualScriptFunctionCall> vsfc = vsn;
vsfc->set_function(p_text);
- script->data_connect(edited_func,port_action_node,port_action_output,port_action_new_node,0);
+ script->data_connect(edited_func, port_action_node, port_action_output, port_action_new_node, 0);
}
if (vsn->cast_to<VisualScriptPropertySet>()) {
Ref<VisualScriptPropertySet> vsp = vsn;
vsp->set_property(p_text);
- script->data_connect(edited_func,port_action_node,port_action_output,port_action_new_node,0);
+ script->data_connect(edited_func, port_action_node, port_action_output, port_action_new_node, 0);
}
if (vsn->cast_to<VisualScriptPropertyGet>()) {
Ref<VisualScriptPropertyGet> vsp = vsn;
vsp->set_property(p_text);
- script->data_connect(edited_func,port_action_node,port_action_output,port_action_new_node,0);
+ script->data_connect(edited_func, port_action_node, port_action_output, port_action_new_node, 0);
}
_update_graph(port_action_new_node);
_update_graph_connections();
-
}
-
void VisualScriptEditor::_default_value_changed() {
-
- Ref<VisualScriptNode> vsn = script->get_node(edited_func,editing_id);
+ Ref<VisualScriptNode> vsn = script->get_node(edited_func, editing_id);
if (vsn.is_null())
return;
undo_redo->create_action("Change Input Value");
- undo_redo->add_do_method(vsn.ptr(),"set_default_input_value",editing_input,default_value_edit->get_variant());
- undo_redo->add_undo_method(vsn.ptr(),"set_default_input_value",editing_input,vsn->get_default_input_value(editing_input));
+ undo_redo->add_do_method(vsn.ptr(), "set_default_input_value", editing_input, default_value_edit->get_variant());
+ undo_redo->add_undo_method(vsn.ptr(), "set_default_input_value", editing_input, vsn->get_default_input_value(editing_input));
- undo_redo->add_do_method(this,"_update_graph",editing_id);
- undo_redo->add_undo_method(this,"_update_graph",editing_id);
+ undo_redo->add_do_method(this, "_update_graph", editing_id);
+ undo_redo->add_undo_method(this, "_update_graph", editing_id);
undo_redo->commit_action();
-
}
-void VisualScriptEditor::_default_value_edited(Node * p_button,int p_id,int p_input_port) {
+void VisualScriptEditor::_default_value_edited(Node *p_button, int p_id, int p_input_port) {
- Ref<VisualScriptNode> vsn = script->get_node(edited_func,p_id);
+ Ref<VisualScriptNode> vsn = script->get_node(edited_func, 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) {
+ if (pinfo.type != Variant::NIL && existing.get_type() != pinfo.type) {
Variant::CallError ce;
- const Variant *existingp=&existing;
- existing = Variant::construct(pinfo.type,&existingp,1,ce,false);
-
+ const Variant *existingp = &existing;
+ existing = Variant::construct(pinfo.type, &existingp, 1, ce, false);
}
- default_value_edit->set_pos(p_button->cast_to<Control>()->get_global_pos()+Vector2(0,p_button->cast_to<Control>()->get_size().y));
- default_value_edit->set_size(Size2(1,1));
- if (default_value_edit->edit(NULL,pinfo.name,pinfo.type,existing,pinfo.hint,pinfo.hint_string)) {
- if (pinfo.hint==PROPERTY_HINT_MULTILINE_TEXT)
+ default_value_edit->set_pos(p_button->cast_to<Control>()->get_global_pos() + Vector2(0, p_button->cast_to<Control>()->get_size().y));
+ default_value_edit->set_size(Size2(1, 1));
+ if (default_value_edit->edit(NULL, pinfo.name, pinfo.type, existing, pinfo.hint, pinfo.hint_string)) {
+ if (pinfo.hint == PROPERTY_HINT_MULTILINE_TEXT)
default_value_edit->popup_centered_ratio();
else
default_value_edit->popup();
}
editing_id = p_id;
- editing_input=p_input_port;
-
+ editing_input = p_input_port;
}
-void VisualScriptEditor::_show_hint(const String& p_hint) {
+void VisualScriptEditor::_show_hint(const String &p_hint) {
hint_text->set_text(p_hint);
hint_text->show();
@@ -3019,38 +2830,38 @@ void VisualScriptEditor::_hide_timer() {
hint_text->hide();
}
-void VisualScriptEditor::_node_filter_changed(const String& p_text) {
+void VisualScriptEditor::_node_filter_changed(const String &p_text) {
_update_available_nodes();
}
-void VisualScriptEditor::_notification(int p_what) {
+void VisualScriptEditor::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
- node_filter_icon->set_texture(Control::get_icon("Zoom","EditorIcons"));
+ if (p_what == NOTIFICATION_READY) {
+ node_filter_icon->set_texture(Control::get_icon("Zoom", "EditorIcons"));
}
}
-void VisualScriptEditor::_graph_ofs_changed(const Vector2& p_ofs) {
+void VisualScriptEditor::_graph_ofs_changed(const Vector2 &p_ofs) {
if (updating_graph)
return;
- updating_graph=true;
+ updating_graph = true;
if (script->has_function(edited_func)) {
- script->set_function_scroll(edited_func,graph->get_scroll_ofs()/EDSCALE);
+ script->set_function_scroll(edited_func, graph->get_scroll_ofs() / EDSCALE);
script->set_edited(true);
}
- updating_graph=false;
+ updating_graph = false;
}
-void VisualScriptEditor::_comment_node_resized(const Vector2& p_new_size,int p_node) {
+void VisualScriptEditor::_comment_node_resized(const Vector2 &p_new_size, int p_node) {
if (updating_graph)
return;
- Ref<VisualScriptComment> vsc = script->get_node(edited_func,p_node);
+ Ref<VisualScriptComment> vsc = script->get_node(edited_func, p_node);
if (vsc.is_null())
return;
@@ -3061,38 +2872,36 @@ void VisualScriptEditor::_comment_node_resized(const Vector2& p_new_size,int p_n
if (!gn)
return;
- updating_graph=true;
+ updating_graph = true;
graph->set_block_minimum_size_adjust(true); //faster resize
- undo_redo->create_action("Resize Comment",UndoRedo::MERGE_ENDS);
- undo_redo->add_do_method(vsc.ptr(),"set_size",p_new_size/EDSCALE);
- undo_redo->add_undo_method(vsc.ptr(),"set_size",vsc->get_size());
+ undo_redo->create_action("Resize Comment", UndoRedo::MERGE_ENDS);
+ undo_redo->add_do_method(vsc.ptr(), "set_size", p_new_size / EDSCALE);
+ undo_redo->add_undo_method(vsc.ptr(), "set_size", vsc->get_size());
undo_redo->commit_action();
gn->set_custom_minimum_size(p_new_size); //for this time since graph update is blocked
- gn->set_size(Size2(1,1));
+ gn->set_size(Size2(1, 1));
graph->set_block_minimum_size_adjust(false);
- updating_graph=false;
-
-
+ updating_graph = false;
}
void VisualScriptEditor::_menu_option(int p_what) {
- switch(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++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
if (gn->is_selected()) {
int id = String(gn->get_name()).to_int();
- Ref<VisualScriptNode> vsn = script->get_node(edited_func,id);
+ Ref<VisualScriptNode> vsn = script->get_node(edited_func, id);
if (vsn.is_valid()) {
vsn->set_breakpoint(!vsn->is_breakpoint());
reselect.push_back(gn->get_name());
@@ -3103,7 +2912,7 @@ void VisualScriptEditor::_menu_option(int p_what) {
_update_graph();
- for(List<String>::Element *E=reselect.front();E;E=E->next()) {
+ for (List<String>::Element *E = reselect.front(); E; E = E->next()) {
GraphNode *gn = graph->get_node(E->get())->cast_to<GraphNode>();
gn->set_selected(true);
}
@@ -3124,22 +2933,21 @@ void VisualScriptEditor::_menu_option(int p_what) {
clipboard->data_connections.clear();
clipboard->sequence_connections.clear();
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
if (gn->is_selected()) {
int id = String(gn->get_name()).to_int();
- Ref<VisualScriptNode> node = script->get_node(edited_func,id);
+ Ref<VisualScriptNode> node = script->get_node(edited_func, id);
if (node->cast_to<VisualScriptFunction>()) {
EditorNode::get_singleton()->show_warning("Can't copy the function node.");
return;
}
if (node.is_valid()) {
- clipboard->nodes[id]=node->duplicate();
- clipboard->nodes_positions[id]=script->get_node_pos(edited_func,id);
+ clipboard->nodes[id] = node->duplicate();
+ clipboard->nodes_positions[id] = script->get_node_pos(edited_func, id);
}
-
}
}
}
@@ -3149,9 +2957,9 @@ void VisualScriptEditor::_menu_option(int p_what) {
List<VisualScript::SequenceConnection> sequence_connections;
- script->get_sequence_connection_list(edited_func,&sequence_connections);
+ script->get_sequence_connection_list(edited_func, &sequence_connections);
- for (List<VisualScript::SequenceConnection>::Element *E=sequence_connections.front();E;E=E->next()) {
+ 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)) {
@@ -3161,9 +2969,9 @@ void VisualScriptEditor::_menu_option(int p_what) {
List<VisualScript::DataConnection> data_connections;
- script->get_data_connection_list(edited_func,&data_connections);
+ script->get_data_connection_list(edited_func, &data_connections);
- for (List<VisualScript::DataConnection>::Element *E=data_connections.front();E;E=E->next()) {
+ 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)) {
@@ -3171,11 +2979,10 @@ void VisualScriptEditor::_menu_option(int p_what) {
}
}
- if (p_what==EDIT_CUT_NODES) {
+ if (p_what == EDIT_CUT_NODES) {
_on_nodes_delete(); // oh yeah, also delete on cut
}
-
} break;
case EDIT_PASTE_NODES: {
if (!script->has_function(edited_func))
@@ -3186,10 +2993,10 @@ void VisualScriptEditor::_menu_option(int p_what) {
break;
}
- Map<int,int> remap;
+ Map<int, int> remap;
undo_redo->create_action("Paste VisualScript Nodes");
- int idc=script->get_available_id()+1;
+ int idc = script->get_available_id() + 1;
Set<int> to_select;
@@ -3197,137 +3004,118 @@ void VisualScriptEditor::_menu_option(int p_what) {
{
List<int> nodes;
- script->get_node_list(edited_func,&nodes);
- for (List<int>::Element *E=nodes.front();E;E=E->next()) {
- Vector2 pos = script->get_node_pos(edited_func,E->get()).snapped(Vector2(2,2));
+ script->get_node_list(edited_func, &nodes);
+ for (List<int>::Element *E = nodes.front(); E; E = E->next()) {
+ Vector2 pos = script->get_node_pos(edited_func, E->get()).snapped(Vector2(2, 2));
existing_positions.insert(pos);
}
}
- for (Map<int,Ref<VisualScriptNode> >::Element *E=clipboard->nodes.front();E;E=E->next()) {
-
+ for (Map<int, Ref<VisualScriptNode> >::Element *E = clipboard->nodes.front(); E; E = E->next()) {
Ref<VisualScriptNode> node = E->get()->duplicate();
int new_id = idc++;
to_select.insert(new_id);
- remap[E->key()]=new_id;
+ remap[E->key()] = new_id;
Vector2 paste_pos = clipboard->nodes_positions[E->key()];
- while(existing_positions.has(paste_pos.snapped(Vector2(2,2)))) {
- paste_pos+=Vector2(20,20)*EDSCALE;
+ while (existing_positions.has(paste_pos.snapped(Vector2(2, 2)))) {
+ paste_pos += Vector2(20, 20) * EDSCALE;
}
-
- undo_redo->add_do_method(script.ptr(),"add_node",edited_func,new_id,node,paste_pos);
- undo_redo->add_undo_method(script.ptr(),"remove_node",edited_func,new_id);
-
+ undo_redo->add_do_method(script.ptr(), "add_node", edited_func, new_id, node, paste_pos);
+ undo_redo->add_undo_method(script.ptr(), "remove_node", edited_func, 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",edited_func,remap[E->get().from_node],E->get().from_output,remap[E->get().to_node]);
- undo_redo->add_undo_method(script.ptr(),"sequence_disconnect",edited_func,remap[E->get().from_node],E->get().from_output,remap[E->get().to_node]);
+ for (Set<VisualScript::SequenceConnection>::Element *E = clipboard->sequence_connections.front(); E; E = E->next()) {
+ undo_redo->add_do_method(script.ptr(), "sequence_connect", edited_func, remap[E->get().from_node], E->get().from_output, remap[E->get().to_node]);
+ undo_redo->add_undo_method(script.ptr(), "sequence_disconnect", edited_func, 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",edited_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",edited_func,remap[E->get().from_node],E->get().from_port,remap[E->get().to_node],E->get().to_port);
+ for (Set<VisualScript::DataConnection>::Element *E = clipboard->data_connections.front(); E; E = E->next()) {
+ undo_redo->add_do_method(script.ptr(), "data_connect", edited_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", edited_func, 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");
- undo_redo->add_undo_method(this,"_update_graph");
+ undo_redo->add_do_method(this, "_update_graph");
+ undo_redo->add_undo_method(this, "_update_graph");
undo_redo->commit_action();
- for(int i=0;i<graph->get_child_count();i++) {
+ for (int i = 0; i < graph->get_child_count(); i++) {
GraphNode *gn = graph->get_child(i)->cast_to<GraphNode>();
if (gn) {
int id = gn->get_name().operator String().to_int();
gn->set_selected(to_select.has(id));
-
}
}
} break;
-
-
}
}
void VisualScriptEditor::_bind_methods() {
- ClassDB::bind_method("_member_button",&VisualScriptEditor::_member_button);
- ClassDB::bind_method("_member_edited",&VisualScriptEditor::_member_edited);
- ClassDB::bind_method("_member_selected",&VisualScriptEditor::_member_selected);
- ClassDB::bind_method("_update_members",&VisualScriptEditor::_update_members);
- ClassDB::bind_method("_change_base_type",&VisualScriptEditor::_change_base_type);
- ClassDB::bind_method("_change_base_type_callback",&VisualScriptEditor::_change_base_type_callback);
- ClassDB::bind_method("_override_pressed",&VisualScriptEditor::_override_pressed);
- ClassDB::bind_method("_node_selected",&VisualScriptEditor::_node_selected);
- ClassDB::bind_method("_node_moved",&VisualScriptEditor::_node_moved);
- ClassDB::bind_method("_move_node",&VisualScriptEditor::_move_node);
- ClassDB::bind_method("_begin_node_move",&VisualScriptEditor::_begin_node_move);
- ClassDB::bind_method("_end_node_move",&VisualScriptEditor::_end_node_move);
- ClassDB::bind_method("_remove_node",&VisualScriptEditor::_remove_node);
- ClassDB::bind_method("_update_graph",&VisualScriptEditor::_update_graph,DEFVAL(-1));
- ClassDB::bind_method("_node_ports_changed",&VisualScriptEditor::_node_ports_changed);
- ClassDB::bind_method("_available_node_doubleclicked",&VisualScriptEditor::_available_node_doubleclicked);
- ClassDB::bind_method("_default_value_edited",&VisualScriptEditor::_default_value_edited);
- ClassDB::bind_method("_default_value_changed",&VisualScriptEditor::_default_value_changed);
- ClassDB::bind_method("_menu_option",&VisualScriptEditor::_menu_option);
- ClassDB::bind_method("_graph_ofs_changed",&VisualScriptEditor::_graph_ofs_changed);
- ClassDB::bind_method("_center_on_node",&VisualScriptEditor::_center_on_node);
- ClassDB::bind_method("_comment_node_resized",&VisualScriptEditor::_comment_node_resized);
- ClassDB::bind_method("_button_resource_previewed",&VisualScriptEditor::_button_resource_previewed);
- ClassDB::bind_method("_port_action_menu",&VisualScriptEditor::_port_action_menu);
- ClassDB::bind_method("_selected_connect_node_method_or_setget",&VisualScriptEditor::_selected_connect_node_method_or_setget);
- ClassDB::bind_method("_expression_text_changed",&VisualScriptEditor::_expression_text_changed);
-
-
-
-
- ClassDB::bind_method("get_drag_data_fw",&VisualScriptEditor::get_drag_data_fw);
- ClassDB::bind_method("can_drop_data_fw",&VisualScriptEditor::can_drop_data_fw);
- ClassDB::bind_method("drop_data_fw",&VisualScriptEditor::drop_data_fw);
-
- ClassDB::bind_method("_input",&VisualScriptEditor::_input);
- ClassDB::bind_method("_on_nodes_delete",&VisualScriptEditor::_on_nodes_delete);
- ClassDB::bind_method("_on_nodes_duplicate",&VisualScriptEditor::_on_nodes_duplicate);
-
- ClassDB::bind_method("_hide_timer",&VisualScriptEditor::_hide_timer);
-
- ClassDB::bind_method("_graph_connected",&VisualScriptEditor::_graph_connected);
- ClassDB::bind_method("_graph_disconnected",&VisualScriptEditor::_graph_disconnected);
- ClassDB::bind_method("_graph_connect_to_empty",&VisualScriptEditor::_graph_connect_to_empty);
-
- ClassDB::bind_method("_update_graph_connections",&VisualScriptEditor::_update_graph_connections);
- ClassDB::bind_method("_node_filter_changed",&VisualScriptEditor::_node_filter_changed);
-
- ClassDB::bind_method("_selected_method",&VisualScriptEditor::_selected_method);
- ClassDB::bind_method("_draw_color_over_button",&VisualScriptEditor::_draw_color_over_button);
-
-
-
-
+ ClassDB::bind_method("_member_button", &VisualScriptEditor::_member_button);
+ ClassDB::bind_method("_member_edited", &VisualScriptEditor::_member_edited);
+ ClassDB::bind_method("_member_selected", &VisualScriptEditor::_member_selected);
+ ClassDB::bind_method("_update_members", &VisualScriptEditor::_update_members);
+ ClassDB::bind_method("_change_base_type", &VisualScriptEditor::_change_base_type);
+ ClassDB::bind_method("_change_base_type_callback", &VisualScriptEditor::_change_base_type_callback);
+ ClassDB::bind_method("_override_pressed", &VisualScriptEditor::_override_pressed);
+ ClassDB::bind_method("_node_selected", &VisualScriptEditor::_node_selected);
+ ClassDB::bind_method("_node_moved", &VisualScriptEditor::_node_moved);
+ ClassDB::bind_method("_move_node", &VisualScriptEditor::_move_node);
+ ClassDB::bind_method("_begin_node_move", &VisualScriptEditor::_begin_node_move);
+ ClassDB::bind_method("_end_node_move", &VisualScriptEditor::_end_node_move);
+ ClassDB::bind_method("_remove_node", &VisualScriptEditor::_remove_node);
+ ClassDB::bind_method("_update_graph", &VisualScriptEditor::_update_graph, DEFVAL(-1));
+ ClassDB::bind_method("_node_ports_changed", &VisualScriptEditor::_node_ports_changed);
+ ClassDB::bind_method("_available_node_doubleclicked", &VisualScriptEditor::_available_node_doubleclicked);
+ ClassDB::bind_method("_default_value_edited", &VisualScriptEditor::_default_value_edited);
+ ClassDB::bind_method("_default_value_changed", &VisualScriptEditor::_default_value_changed);
+ ClassDB::bind_method("_menu_option", &VisualScriptEditor::_menu_option);
+ ClassDB::bind_method("_graph_ofs_changed", &VisualScriptEditor::_graph_ofs_changed);
+ ClassDB::bind_method("_center_on_node", &VisualScriptEditor::_center_on_node);
+ ClassDB::bind_method("_comment_node_resized", &VisualScriptEditor::_comment_node_resized);
+ ClassDB::bind_method("_button_resource_previewed", &VisualScriptEditor::_button_resource_previewed);
+ ClassDB::bind_method("_port_action_menu", &VisualScriptEditor::_port_action_menu);
+ ClassDB::bind_method("_selected_connect_node_method_or_setget", &VisualScriptEditor::_selected_connect_node_method_or_setget);
+ ClassDB::bind_method("_expression_text_changed", &VisualScriptEditor::_expression_text_changed);
+
+ ClassDB::bind_method("get_drag_data_fw", &VisualScriptEditor::get_drag_data_fw);
+ ClassDB::bind_method("can_drop_data_fw", &VisualScriptEditor::can_drop_data_fw);
+ ClassDB::bind_method("drop_data_fw", &VisualScriptEditor::drop_data_fw);
+
+ ClassDB::bind_method("_input", &VisualScriptEditor::_input);
+ ClassDB::bind_method("_on_nodes_delete", &VisualScriptEditor::_on_nodes_delete);
+ ClassDB::bind_method("_on_nodes_duplicate", &VisualScriptEditor::_on_nodes_duplicate);
+
+ ClassDB::bind_method("_hide_timer", &VisualScriptEditor::_hide_timer);
+
+ ClassDB::bind_method("_graph_connected", &VisualScriptEditor::_graph_connected);
+ ClassDB::bind_method("_graph_disconnected", &VisualScriptEditor::_graph_disconnected);
+ ClassDB::bind_method("_graph_connect_to_empty", &VisualScriptEditor::_graph_connect_to_empty);
+
+ ClassDB::bind_method("_update_graph_connections", &VisualScriptEditor::_update_graph_connections);
+ ClassDB::bind_method("_node_filter_changed", &VisualScriptEditor::_node_filter_changed);
+
+ ClassDB::bind_method("_selected_method", &VisualScriptEditor::_selected_method);
+ ClassDB::bind_method("_draw_color_over_button", &VisualScriptEditor::_draw_color_over_button);
}
-
-
VisualScriptEditor::VisualScriptEditor() {
if (!clipboard) {
- clipboard = memnew( Clipboard );
+ clipboard = memnew(Clipboard);
}
- updating_graph=false;
+ updating_graph = false;
- edit_menu = memnew( MenuButton );
+ edit_menu = memnew(MenuButton);
edit_menu->set_text(TTR("Edit"));
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/delete_selected"), EDIT_DELETE_NODES);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/toggle_breakpoint"), EDIT_TOGGLE_BREAKPOINT);
@@ -3337,101 +3125,98 @@ VisualScriptEditor::VisualScriptEditor() {
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/cut_nodes"), EDIT_CUT_NODES);
edit_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("visual_script_editor/paste_nodes"), EDIT_PASTE_NODES);
- edit_menu->get_popup()->connect("id_pressed",this,"_menu_option");
+ edit_menu->get_popup()->connect("id_pressed", this, "_menu_option");
- main_hsplit = memnew( HSplitContainer );
+ main_hsplit = memnew(HSplitContainer);
add_child(main_hsplit);
main_hsplit->set_area_as_parent_rect();
- left_vsplit = memnew( VSplitContainer );
+ left_vsplit = memnew(VSplitContainer);
main_hsplit->add_child(left_vsplit);
- VBoxContainer *left_vb = memnew( VBoxContainer );
+ VBoxContainer *left_vb = memnew(VBoxContainer);
left_vsplit->add_child(left_vb);
left_vb->set_v_size_flags(SIZE_EXPAND_FILL);
- left_vb->set_custom_minimum_size(Size2(230,1)*EDSCALE);
+ left_vb->set_custom_minimum_size(Size2(230, 1) * EDSCALE);
- base_type_select = memnew( Button );
- left_vb->add_margin_child(TTR("Base Type:"),base_type_select);
- base_type_select->connect("pressed",this,"_change_base_type");
+ base_type_select = memnew(Button);
+ left_vb->add_margin_child(TTR("Base Type:"), base_type_select);
+ base_type_select->connect("pressed", this, "_change_base_type");
- members = memnew( Tree );
- left_vb->add_margin_child(TTR("Members:"),members,true);
+ members = memnew(Tree);
+ left_vb->add_margin_child(TTR("Members:"), members, true);
members->set_hide_root(true);
- members->connect("button_pressed",this,"_member_button");
- members->connect("item_edited",this,"_member_edited");
- members->connect("cell_selected",this,"_member_selected",varray(),CONNECT_DEFERRED);
+ members->connect("button_pressed", this, "_member_button");
+ members->connect("item_edited", this, "_member_edited");
+ members->connect("cell_selected", this, "_member_selected", varray(), CONNECT_DEFERRED);
members->set_single_select_cell_editing_only_when_already_selected(true);
members->set_hide_folding(true);
members->set_drag_forwarding(this);
-
- VBoxContainer *left_vb2 = memnew( VBoxContainer );
+ VBoxContainer *left_vb2 = memnew(VBoxContainer);
left_vsplit->add_child(left_vb2);
left_vb2->set_v_size_flags(SIZE_EXPAND_FILL);
-
- VBoxContainer *vbc_nodes = memnew( VBoxContainer );
- HBoxContainer *hbc_nodes = memnew( HBoxContainer );
- node_filter = memnew (LineEdit);
- node_filter->connect("text_changed",this,"_node_filter_changed");
+ VBoxContainer *vbc_nodes = memnew(VBoxContainer);
+ HBoxContainer *hbc_nodes = memnew(HBoxContainer);
+ node_filter = memnew(LineEdit);
+ node_filter->connect("text_changed", this, "_node_filter_changed");
hbc_nodes->add_child(node_filter);
node_filter->set_h_size_flags(SIZE_EXPAND_FILL);
- node_filter_icon = memnew( TextureRect );
+ node_filter_icon = memnew(TextureRect);
node_filter_icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
hbc_nodes->add_child(node_filter_icon);
vbc_nodes->add_child(hbc_nodes);
- nodes = memnew( Tree );
+ nodes = memnew(Tree);
vbc_nodes->add_child(nodes);
nodes->set_v_size_flags(SIZE_EXPAND_FILL);
- left_vb2->add_margin_child(TTR("Available Nodes:"),vbc_nodes,true);
+ left_vb2->add_margin_child(TTR("Available Nodes:"), vbc_nodes, true);
nodes->set_hide_root(true);
- nodes->connect("item_activated",this,"_available_node_doubleclicked");
+ nodes->connect("item_activated", this, "_available_node_doubleclicked");
nodes->set_drag_forwarding(this);
- graph = memnew( GraphEdit );
+ graph = memnew(GraphEdit);
main_hsplit->add_child(graph);
graph->set_h_size_flags(SIZE_EXPAND_FILL);
- graph->connect("node_selected",this,"_node_selected");
- graph->connect("_begin_node_move",this,"_begin_node_move");
- graph->connect("_end_node_move",this,"_end_node_move");
- graph->connect("delete_nodes_request",this,"_on_nodes_delete");
- graph->connect("duplicate_nodes_request",this,"_on_nodes_duplicate");
+ graph->connect("node_selected", this, "_node_selected");
+ graph->connect("_begin_node_move", this, "_begin_node_move");
+ graph->connect("_end_node_move", this, "_end_node_move");
+ graph->connect("delete_nodes_request", this, "_on_nodes_delete");
+ graph->connect("duplicate_nodes_request", this, "_on_nodes_duplicate");
graph->set_drag_forwarding(this);
graph->hide();
- graph->connect("scroll_offset_changed",this,"_graph_ofs_changed");
+ graph->connect("scroll_offset_changed", this, "_graph_ofs_changed");
- select_func_text = memnew( Label );
+ select_func_text = memnew(Label);
select_func_text->set_text(TTR("Select or create a function to edit graph"));
select_func_text->set_align(Label::ALIGN_CENTER);
select_func_text->set_valign(Label::VALIGN_CENTER);
select_func_text->set_h_size_flags(SIZE_EXPAND_FILL);
main_hsplit->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 = 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_align(Label::ALIGN_CENTER);
hint_text->set_valign(Label::VALIGN_CENTER);
graph->add_child(hint_text);
- hint_text_timer = memnew( Timer );
+ hint_text_timer = memnew(Timer);
hint_text_timer->set_wait_time(4);
- hint_text_timer->connect("timeout",this,"_hide_timer");
+ hint_text_timer->connect("timeout", this, "_hide_timer");
add_child(hint_text_timer);
//allowed casts (connections)
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- graph->add_valid_connection_type(Variant::NIL,i);
- graph->add_valid_connection_type(i,Variant::NIL);
- for(int j=0;j<Variant::VARIANT_MAX;j++) {
- if (Variant::can_convert(Variant::Type(i),Variant::Type(j))) {
- graph->add_valid_connection_type(i,j);
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ graph->add_valid_connection_type(Variant::NIL, i);
+ graph->add_valid_connection_type(i, Variant::NIL);
+ for (int j = 0; j < Variant::VARIANT_MAX; j++) {
+ if (Variant::can_convert(Variant::Type(i), Variant::Type(j))) {
+ graph->add_valid_connection_type(i, j);
}
}
@@ -3440,68 +3225,66 @@ VisualScriptEditor::VisualScriptEditor() {
graph->add_valid_left_disconnect_type(TYPE_SEQUENCE);
- graph->connect("connection_request",this,"_graph_connected");
- graph->connect("disconnection_request",this,"_graph_disconnected");
- graph->connect("connection_to_empty",this,"_graph_connect_to_empty");
+ graph->connect("connection_request", this, "_graph_connected");
+ graph->connect("disconnection_request", this, "_graph_disconnected");
+ graph->connect("connection_to_empty", this, "_graph_connect_to_empty");
- edit_signal_dialog = memnew( AcceptDialog );
+ edit_signal_dialog = memnew(AcceptDialog);
edit_signal_dialog->get_ok()->set_text(TTR("Close"));
add_child(edit_signal_dialog);
edit_signal_dialog->set_title(TTR("Edit Signal Arguments:"));
- signal_editor = memnew( VisualScriptEditorSignalEdit );
- edit_signal_edit = memnew( PropertyEditor );
+ signal_editor = memnew(VisualScriptEditorSignalEdit);
+ edit_signal_edit = memnew(PropertyEditor);
edit_signal_edit->hide_top_label();
edit_signal_dialog->add_child(edit_signal_edit);
edit_signal_edit->edit(signal_editor);
- edit_variable_dialog = memnew( AcceptDialog );
+ edit_variable_dialog = memnew(AcceptDialog);
edit_variable_dialog->get_ok()->set_text(TTR("Close"));
add_child(edit_variable_dialog);
edit_variable_dialog->set_title(TTR("Edit Variable:"));
- variable_editor = memnew( VisualScriptEditorVariableEdit );
- edit_variable_edit = memnew( PropertyEditor );
+ variable_editor = memnew(VisualScriptEditorVariableEdit);
+ edit_variable_edit = memnew(PropertyEditor);
edit_variable_edit->hide_top_label();
edit_variable_dialog->add_child(edit_variable_edit);
edit_variable_edit->edit(variable_editor);
- select_base_type=memnew(CreateDialog);
+ select_base_type = memnew(CreateDialog);
select_base_type->set_base_type("Object"); //anything goes
- select_base_type->connect("create",this,"_change_base_type_callback");
+ select_base_type->connect("create", this, "_change_base_type_callback");
select_base_type->get_ok()->set_text(TTR("Change"));
add_child(select_base_type);
undo_redo = EditorNode::get_singleton()->get_undo_redo();
- new_function_menu = memnew( PopupMenu );
- new_function_menu->connect("id_pressed",this,"_override_pressed");
+ new_function_menu = memnew(PopupMenu);
+ new_function_menu->connect("id_pressed", this, "_override_pressed");
add_child(new_function_menu);
- updating_members=false;
+ updating_members = false;
set_process_input(true); //for revert on drag
set_process_unhandled_input(true); //for revert on drag
- default_value_edit= memnew( CustomPropertyEditor);
+ default_value_edit = memnew(CustomPropertyEditor);
add_child(default_value_edit);
- default_value_edit->connect("variant_changed",this,"_default_value_changed");
+ default_value_edit->connect("variant_changed", this, "_default_value_changed");
- method_select = memnew( PropertySelector );
+ method_select = memnew(PropertySelector);
add_child(method_select);
- method_select->connect("selected",this,"_selected_method");
- error_line=-1;
+ method_select->connect("selected", this, "_selected_method");
+ error_line = -1;
- new_connect_node_select = memnew( PropertySelector );
+ new_connect_node_select = memnew(PropertySelector);
add_child(new_connect_node_select);
- new_connect_node_select->connect("selected",this,"_selected_connect_node_method_or_setget");
+ new_connect_node_select->connect("selected", this, "_selected_connect_node_method_or_setget");
- port_action_popup = memnew( PopupMenu );
+ port_action_popup = memnew(PopupMenu);
add_child(port_action_popup);
- port_action_popup->connect("id_pressed",this,"_port_action_menu");
-
-
+ port_action_popup->connect("id_pressed", this, "_port_action_menu");
}
VisualScriptEditor::~VisualScriptEditor() {
@@ -3511,17 +3294,16 @@ VisualScriptEditor::~VisualScriptEditor() {
memdelete(variable_editor);
}
-static ScriptEditorBase * create_editor(const Ref<Script>& p_script) {
+static ScriptEditorBase *create_editor(const Ref<Script> &p_script) {
if (p_script->cast_to<VisualScript>()) {
- return memnew( VisualScriptEditor );
+ return memnew(VisualScriptEditor);
}
return NULL;
}
-
-VisualScriptEditor::Clipboard *VisualScriptEditor::clipboard=NULL;
+VisualScriptEditor::Clipboard *VisualScriptEditor::clipboard = NULL;
void VisualScriptEditor::free_clipboard() {
if (clipboard)
@@ -3531,30 +3313,25 @@ void VisualScriptEditor::free_clipboard() {
static void register_editor_callback() {
ScriptEditor::register_create_script_editor_function(create_editor);
- EditorSettings::get_singleton()->set("editors/visual_script/color_functions",Color(1,0.9,0.9));
- EditorSettings::get_singleton()->set("editors/visual_script/color_data",Color(0.9,1.0,0.9));
- EditorSettings::get_singleton()->set("editors/visual_script/color_operators",Color(0.9,0.9,1.0));
- EditorSettings::get_singleton()->set("editors/visual_script/color_flow_control",Color(1.0,1.0,0.8));
- EditorSettings::get_singleton()->set("editors/visual_script/color_custom",Color(0.8,1.0,1.0));
- EditorSettings::get_singleton()->set("editors/visual_script/color_constants",Color(1.0,0.8,1.0));
-
+ EditorSettings::get_singleton()->set("editors/visual_script/color_functions", Color(1, 0.9, 0.9));
+ EditorSettings::get_singleton()->set("editors/visual_script/color_data", Color(0.9, 1.0, 0.9));
+ EditorSettings::get_singleton()->set("editors/visual_script/color_operators", Color(0.9, 0.9, 1.0));
+ EditorSettings::get_singleton()->set("editors/visual_script/color_flow_control", Color(1.0, 1.0, 0.8));
+ EditorSettings::get_singleton()->set("editors/visual_script/color_custom", Color(0.8, 1.0, 1.0));
+ EditorSettings::get_singleton()->set("editors/visual_script/color_constants", Color(1.0, 0.8, 1.0));
ED_SHORTCUT("visual_script_editor/delete_selected", TTR("Delete Selected"));
ED_SHORTCUT("visual_script_editor/toggle_breakpoint", TTR("Toggle Breakpoint"), KEY_F9);
- ED_SHORTCUT("visual_script_editor/find_node_type", TTR("Find Node Type"), KEY_MASK_CMD+KEY_F);
- ED_SHORTCUT("visual_script_editor/copy_nodes", TTR("Copy Nodes"), KEY_MASK_CMD+KEY_C);
- ED_SHORTCUT("visual_script_editor/cut_nodes", TTR("Cut Nodes"), KEY_MASK_CMD+KEY_X);
- ED_SHORTCUT("visual_script_editor/paste_nodes", TTR("Paste Nodes"), KEY_MASK_CMD+KEY_V);
-
+ ED_SHORTCUT("visual_script_editor/find_node_type", TTR("Find Node Type"), KEY_MASK_CMD + KEY_F);
+ ED_SHORTCUT("visual_script_editor/copy_nodes", TTR("Copy Nodes"), KEY_MASK_CMD + KEY_C);
+ ED_SHORTCUT("visual_script_editor/cut_nodes", TTR("Cut Nodes"), KEY_MASK_CMD + KEY_X);
+ ED_SHORTCUT("visual_script_editor/paste_nodes", TTR("Paste Nodes"), KEY_MASK_CMD + KEY_V);
}
void VisualScriptEditor::register_editor() {
//too early to register stuff here, request a callback
EditorNode::add_plugin_init_callback(register_editor_callback);
-
-
-
}
#endif
diff --git a/modules/visual_script/visual_script_editor.h b/modules/visual_script/visual_script_editor.h
index cdaef8d0ce..5ece1c9e2c 100644
--- a/modules/visual_script/visual_script_editor.h
+++ b/modules/visual_script/visual_script_editor.h
@@ -29,26 +29,23 @@
#ifndef VISUALSCRIPT_EDITOR_H
#define VISUALSCRIPT_EDITOR_H
+#include "editor/create_dialog.h"
#include "editor/plugins/script_editor_plugin.h"
-#include "visual_script.h"
#include "editor/property_editor.h"
-#include "scene/gui/graph_edit.h"
-#include "editor/create_dialog.h"
#include "editor/property_selector.h"
+#include "scene/gui/graph_edit.h"
+#include "visual_script.h"
class VisualScriptEditorSignalEdit;
class VisualScriptEditorVariableEdit;
-
#ifdef TOOLS_ENABLED
-
class VisualScriptEditor : public ScriptEditorBase {
- GDCLASS(VisualScriptEditor,ScriptEditorBase)
+ GDCLASS(VisualScriptEditor, ScriptEditorBase)
enum {
- TYPE_SEQUENCE=1000,
- INDEX_BASE_SEQUENCE=1024
-
+ TYPE_SEQUENCE = 1000,
+ INDEX_BASE_SEQUENCE = 1024
};
@@ -115,7 +112,7 @@ class VisualScriptEditor : public ScriptEditorBase {
bool updating_graph;
- void _show_hint(const String& p_hint);
+ void _show_hint(const String &p_hint);
void _hide_timer();
CreateDialog *select_base_type;
@@ -124,18 +121,17 @@ class VisualScriptEditor : public ScriptEditorBase {
String name;
Variant::Type ret;
bool ret_variant;
- Vector< Pair<Variant::Type,String> > args;
+ Vector<Pair<Variant::Type, String> > args;
};
- Map<int,VirtualInMenu> virtuals_in_menu;
+ Map<int, VirtualInMenu> virtuals_in_menu;
PopupMenu *new_function_menu;
-
StringName edited_func;
void _update_graph_connections();
- void _update_graph(int p_only_id=-1);
+ void _update_graph(int p_only_id = -1);
bool updating_members;
@@ -143,12 +139,12 @@ class VisualScriptEditor : public ScriptEditorBase {
StringName selected;
- String _validate_name(const String& p_name) const;
+ String _validate_name(const String &p_name) const;
struct Clipboard {
- Map<int,Ref<VisualScriptNode> > nodes;
- Map<int,Vector2 > nodes_positions;
+ Map<int, Ref<VisualScriptNode> > nodes;
+ Map<int, Vector2> nodes_positions;
Set<VisualScript::SequenceConnection> sequence_connections;
Set<VisualScript::DataConnection> data_connections;
@@ -164,15 +160,14 @@ class VisualScriptEditor : public ScriptEditorBase {
Vector2 port_action_pos;
int port_action_new_node;
void _port_action_menu(int p_option);
- void _selected_connect_node_method_or_setget(const String& p_text);
-
+ void _selected_connect_node_method_or_setget(const String &p_text);
int error_line;
- void _node_selected(Node* p_node);
+ void _node_selected(Node *p_node);
void _center_on_node(int p_id);
- void _node_filter_changed(const String& p_text);
+ void _node_filter_changed(const String &p_text);
void _change_base_type_callback();
void _change_base_type();
void _member_selected();
@@ -181,82 +176,78 @@ class VisualScriptEditor : public ScriptEditorBase {
void _begin_node_move();
void _end_node_move();
- void _move_node(String func,int p_id,const Vector2& p_to);
+ void _move_node(String func, int p_id, const Vector2 &p_to);
- void _node_moved(Vector2 p_from,Vector2 p_to, int p_id);
+ void _node_moved(Vector2 p_from, Vector2 p_to, int p_id);
void _remove_node(int p_id);
- void _graph_connected(const String& p_from,int p_from_slot,const String& p_to,int p_to_slot);
- 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 _graph_connected(const String &p_from, int p_from_slot, const String &p_to, int p_to_slot);
+ 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(const String &p_func, int p_id);
void _available_node_doubleclicked();
void _update_available_nodes();
void _member_button(Object *p_item, int p_column, int p_button);
- void _expression_text_changed(const String& p_text,int p_id);
-
+ void _expression_text_changed(const String &p_text, int p_id);
String revert_on_drag;
- void _input(const InputEvent& p_event);
+ void _input(const InputEvent &p_event);
void _on_nodes_delete();
void _on_nodes_duplicate();
- Variant get_drag_data_fw(const Point2& p_point,Control* p_from);
- bool can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const;
- void drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from);
-
+ Variant get_drag_data_fw(const Point2 &p_point, Control *p_from);
+ bool can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
+ void drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
int editing_id;
int editing_input;
void _default_value_changed();
- void _default_value_edited(Node * p_button,int p_id,int p_input_port);
+ void _default_value_edited(Node *p_button, int p_id, int p_input_port);
void _menu_option(int p_what);
- void _graph_ofs_changed(const Vector2& p_ofs);
- void _comment_node_resized(const Vector2& p_new_size,int p_node);
+ void _graph_ofs_changed(const Vector2 &p_ofs);
+ void _comment_node_resized(const Vector2 &p_new_size, int p_node);
int selecting_method_id;
- void _selected_method(const String& p_method);
+ void _selected_method(const String &p_method);
- void _draw_color_over_button(Object* obj,Color p_color);
- void _button_resource_previewed(const String& p_path,const Ref<Texture>& p_preview,Variant p_ud);
-
- VisualScriptNode::TypeGuess _guess_output_type(int p_port_action_node,int p_port_action_output,Set<int> &visited_nodes);
+ void _draw_color_over_button(Object *obj, Color p_color);
+ void _button_resource_previewed(const String &p_path, const Ref<Texture> &p_preview, Variant p_ud);
+ VisualScriptNode::TypeGuess _guess_output_type(int p_port_action_node, int p_port_action_output, Set<int> &visited_nodes);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
virtual void apply_code();
virtual Ref<Script> get_edited_script() const;
virtual Vector<String> get_functions();
- virtual void set_edited_script(const Ref<Script>& p_script);
+ virtual void set_edited_script(const Ref<Script> &p_script);
virtual void reload_text();
virtual String get_name();
virtual Ref<Texture> get_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_edit_state(const Variant &p_state);
+ virtual void goto_line(int p_line, bool p_with_error = false);
virtual void trim_trailing_whitespace();
virtual void ensure_focus();
virtual void tag_saved_version();
virtual void reload(bool p_soft);
virtual void get_breakpoints(List<int> *p_breakpoints);
- virtual bool goto_method(const String& p_method);
- virtual void add_callback(const String& p_function,PoolStringArray p_args);
+ virtual bool goto_method(const String &p_method);
+ virtual void add_callback(const String &p_function, PoolStringArray p_args);
virtual void update_settings();
virtual void set_debugger_active(bool p_active);
- virtual void set_tooltip_request_func(String p_method,Object* p_obj);
+ virtual void set_tooltip_request_func(String p_method, Object *p_obj);
virtual Control *get_edit_menu();
virtual bool can_lose_focus_on_node_selection() { return false; }
diff --git a/modules/visual_script/visual_script_expression.cpp b/modules/visual_script/visual_script_expression.cpp
index 3d15e696ef..741b422848 100644
--- a/modules/visual_script/visual_script_expression.cpp
+++ b/modules/visual_script/visual_script_expression.cpp
@@ -28,41 +28,40 @@
/*************************************************************************/
#include "visual_script_expression.h"
+bool VisualScriptExpression::_set(const StringName &p_name, const Variant &p_value) {
-bool VisualScriptExpression::_set(const StringName& p_name, const Variant& p_value) {
-
- if (String(p_name)=="expression") {
- expression=p_value;
- expression_dirty=true;
+ if (String(p_name) == "expression") {
+ expression = p_value;
+ expression_dirty = true;
ports_changed_notify();
return true;
}
- if (String(p_name)=="out_type") {
- output_type=Variant::Type(int(p_value));
- expression_dirty=true;
+ if (String(p_name) == "out_type") {
+ output_type = Variant::Type(int(p_value));
+ expression_dirty = true;
ports_changed_notify();
return true;
}
- if (String(p_name)=="sequenced") {
- sequenced=p_value;
+ if (String(p_name) == "sequenced") {
+ sequenced = p_value;
ports_changed_notify();
return true;
}
- if (String(p_name)=="input_count") {
+ if (String(p_name) == "input_count") {
- int from=inputs.size();
+ int from = inputs.size();
inputs.resize(int(p_value));
- for(int i=from;i<inputs.size();i++) {
- inputs[i].name=String::chr('a'+i);
- if (from==0) {
- inputs[i].type=output_type;
+ for (int i = from; i < inputs.size(); i++) {
+ inputs[i].name = String::chr('a' + i);
+ if (from == 0) {
+ inputs[i].type = output_type;
} else {
- inputs[i].type=inputs[from-1].type;
+ inputs[i].type = inputs[from - 1].type;
}
}
- expression_dirty=true;
+ expression_dirty = true;
ports_changed_notify();
_change_notify();
return true;
@@ -70,66 +69,64 @@ bool VisualScriptExpression::_set(const StringName& p_name, const Variant& p_val
if (String(p_name).begins_with("input/")) {
- int idx=String(p_name).get_slice("/",1).to_int();
- ERR_FAIL_INDEX_V(idx,inputs.size(),false);
+ int idx = String(p_name).get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, inputs.size(), false);
- String what=String(p_name).get_slice("/",2);
+ String what = String(p_name).get_slice("/", 2);
- if (what=="type") {
+ if (what == "type") {
- inputs[idx].type=Variant::Type(int(p_value));
- } else if (what=="name") {
+ inputs[idx].type = Variant::Type(int(p_value));
+ } else if (what == "name") {
- inputs[idx].name=p_value;
+ inputs[idx].name = p_value;
} else {
return false;
}
- expression_dirty=true;
+ expression_dirty = true;
ports_changed_notify();
return true;
}
-
return false;
-
}
-bool VisualScriptExpression::_get(const StringName& p_name,Variant &r_ret) const {
+bool VisualScriptExpression::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name)=="expression") {
- r_ret=expression;
+ if (String(p_name) == "expression") {
+ r_ret = expression;
return true;
}
- if (String(p_name)=="out_type") {
- r_ret=output_type;
+ if (String(p_name) == "out_type") {
+ r_ret = output_type;
return true;
}
- if (String(p_name)=="sequenced") {
- r_ret=sequenced;
+ if (String(p_name) == "sequenced") {
+ r_ret = sequenced;
return true;
}
- if (String(p_name)=="input_count") {
- r_ret=inputs.size();
+ if (String(p_name) == "input_count") {
+ r_ret = inputs.size();
return true;
}
if (String(p_name).begins_with("input/")) {
- int idx=String(p_name).get_slice("/",1).to_int();
- ERR_FAIL_INDEX_V(idx,inputs.size(),false);
+ int idx = String(p_name).get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, inputs.size(), false);
- String what=String(p_name).get_slice("/",2);
+ String what = String(p_name).get_slice("/", 2);
- if (what=="type") {
+ if (what == "type") {
- r_ret=inputs[idx].type;
- } else if (what=="name") {
+ r_ret = inputs[idx].type;
+ } else if (what == "name") {
- r_ret=inputs[idx].name;
+ r_ret = inputs[idx].name;
} else {
return false;
}
@@ -137,310 +134,296 @@ bool VisualScriptExpression::_get(const StringName& p_name,Variant &r_ret) const
return true;
}
-
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));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- p_list->push_back(PropertyInfo(Variant::STRING,"expression",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::INT,"out_type",PROPERTY_HINT_ENUM,argt));
- p_list->push_back(PropertyInfo(Variant::INT,"input_count",PROPERTY_HINT_RANGE,"0,64,1"));
- p_list->push_back(PropertyInfo(Variant::BOOL,"sequenced"));
+ p_list->push_back(PropertyInfo(Variant::STRING, "expression", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::INT, "out_type", PROPERTY_HINT_ENUM, argt));
+ p_list->push_back(PropertyInfo(Variant::INT, "input_count", PROPERTY_HINT_RANGE, "0,64,1"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "sequenced"));
- for(int i=0;i<inputs.size();i++) {
+ 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"));
+ 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;
+ 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{
+String VisualScriptExpression::get_output_sequence_port_text(int p_port) const {
return String();
}
-
-int VisualScriptExpression::get_input_value_port_count() const{
+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 {
-PropertyInfo VisualScriptExpression::get_input_value_port_info(int p_idx) const{
-
- return PropertyInfo(inputs[p_idx].type,inputs[p_idx].name);
+ 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");
+ return PropertyInfo(output_type, "result");
}
-String VisualScriptExpression::get_caption() const{
+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) {
+Error VisualScriptExpression::_get_token(Token &r_token) {
while (true) {
-#define GET_CHAR() (str_ofs>=expression.length()?0:expression[str_ofs++])
+#define GET_CHAR() (str_ofs >= expression.length() ? 0 : expression[str_ofs++])
CharType cchar = GET_CHAR();
- if (cchar==0) {
- r_token.type=TK_EOF;
+ if (cchar == 0) {
+ r_token.type = TK_EOF;
return OK;
}
-
- switch(cchar) {
+ switch (cchar) {
case 0: {
- r_token.type=TK_EOF;
+ r_token.type = TK_EOF;
return OK;
} break;
case '{': {
- r_token.type=TK_CURLY_BRACKET_OPEN;
+ r_token.type = TK_CURLY_BRACKET_OPEN;
return OK;
};
case '}': {
- r_token.type=TK_CURLY_BRACKET_CLOSE;
+ r_token.type = TK_CURLY_BRACKET_CLOSE;
return OK;
};
case '[': {
- r_token.type=TK_BRACKET_OPEN;
+ r_token.type = TK_BRACKET_OPEN;
return OK;
};
case ']': {
- r_token.type=TK_BRACKET_CLOSE;
+ r_token.type = TK_BRACKET_CLOSE;
return OK;
};
case '(': {
- r_token.type=TK_PARENTHESIS_OPEN;
+ r_token.type = TK_PARENTHESIS_OPEN;
return OK;
};
case ')': {
- r_token.type=TK_PARENTHESIS_CLOSE;
+ r_token.type = TK_PARENTHESIS_CLOSE;
return OK;
};
case ',': {
- r_token.type=TK_COMMA;
+ r_token.type = TK_COMMA;
return OK;
};
case ':': {
- r_token.type=TK_COLON;
+ r_token.type = TK_COLON;
return OK;
};
case '.': {
- r_token.type=TK_PERIOD;
+ r_token.type = TK_PERIOD;
return OK;
};
case '=': {
- cchar=GET_CHAR();
- if (cchar=='=') {
- r_token.type=TK_OP_EQUAL;
+ cchar = GET_CHAR();
+ if (cchar == '=') {
+ r_token.type = TK_OP_EQUAL;
} else {
_set_error("Expected '='");
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
return OK;
};
case '!': {
- if (expression[str_ofs]=='=') {
- r_token.type=TK_OP_NOT_EQUAL;
+ if (expression[str_ofs] == '=') {
+ r_token.type = TK_OP_NOT_EQUAL;
str_ofs++;
} else {
- r_token.type=TK_OP_NOT;
+ r_token.type = TK_OP_NOT;
}
return OK;
};
case '>': {
- if (expression[str_ofs]=='=') {
- r_token.type=TK_OP_GREATER_EQUAL;
+ if (expression[str_ofs] == '=') {
+ r_token.type = TK_OP_GREATER_EQUAL;
str_ofs++;
- } else if (expression[str_ofs]=='>') {
- r_token.type=TK_OP_SHIFT_RIGHT;
+ } else if (expression[str_ofs] == '>') {
+ r_token.type = TK_OP_SHIFT_RIGHT;
str_ofs++;
} else {
- r_token.type=TK_OP_GREATER;
+ r_token.type = TK_OP_GREATER;
}
return OK;
};
case '<': {
- if (expression[str_ofs]=='=') {
- r_token.type=TK_OP_LESS_EQUAL;
+ if (expression[str_ofs] == '=') {
+ r_token.type = TK_OP_LESS_EQUAL;
str_ofs++;
- } else if (expression[str_ofs]=='<') {
- r_token.type=TK_OP_SHIFT_LEFT;
+ } else if (expression[str_ofs] == '<') {
+ r_token.type = TK_OP_SHIFT_LEFT;
str_ofs++;
} else {
- r_token.type=TK_OP_LESS;
+ r_token.type = TK_OP_LESS;
}
return OK;
};
case '+': {
- r_token.type=TK_OP_ADD;
+ r_token.type = TK_OP_ADD;
return OK;
};
case '-': {
- r_token.type=TK_OP_SUB;
+ r_token.type = TK_OP_SUB;
return OK;
};
case '/': {
- r_token.type=TK_OP_DIV;
+ r_token.type = TK_OP_DIV;
return OK;
};
case '*': {
- r_token.type=TK_OP_MUL;
+ r_token.type = TK_OP_MUL;
return OK;
};
case '%': {
- r_token.type=TK_OP_MOD;
+ r_token.type = TK_OP_MOD;
return OK;
};
case '&': {
- if (expression[str_ofs]=='&') {
- r_token.type=TK_OP_AND;
+ if (expression[str_ofs] == '&') {
+ r_token.type = TK_OP_AND;
str_ofs++;
} else {
- r_token.type=TK_OP_BIT_AND;
+ r_token.type = TK_OP_BIT_AND;
}
return OK;
};
case '|': {
- if (expression[str_ofs]=='|') {
- r_token.type=TK_OP_OR;
+ if (expression[str_ofs] == '|') {
+ r_token.type = TK_OP_OR;
str_ofs++;
} else {
- r_token.type=TK_OP_BIT_OR;
+ r_token.type = TK_OP_BIT_OR;
}
return OK;
};
case '^': {
- r_token.type=TK_OP_BIT_XOR;
+ r_token.type = TK_OP_BIT_XOR;
return OK;
};
case '~': {
- r_token.type=TK_OP_BIT_INVERT;
+ r_token.type = TK_OP_BIT_INVERT;
return OK;
};
case '"': {
-
String str;
- while(true) {
+ while (true) {
- CharType ch=GET_CHAR();
+ CharType ch = GET_CHAR();
- if (ch==0) {
+ if (ch == 0) {
_set_error("Unterminated String");
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
- } else if (ch=='"') {
+ } else if (ch == '"') {
break;
- } else if (ch=='\\') {
+ } else if (ch == '\\') {
//escaped characters...
CharType next = GET_CHAR();
- if (next==0) {
+ if (next == 0) {
_set_error("Unterminated String");
- r_token.type=TK_ERROR;
- return ERR_PARSE_ERROR;
+ r_token.type = TK_ERROR;
+ return ERR_PARSE_ERROR;
}
- CharType res=0;
+ CharType res = 0;
- switch(next) {
+ 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': {
//hexnumbarh - oct is deprecated
-
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
CharType c = GET_CHAR();
- if (c==0) {
+ if (c == 0) {
_set_error("Unterminated String");
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
- if (!((c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'))) {
+ 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;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
CharType v;
- 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;
+ 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 {
ERR_PRINT("BUG");
- v=0;
+ v = 0;
}
- res<<=4;
- res|=v;
-
-
+ res <<= 4;
+ res |= v;
}
-
-
} break;
//case '\"': res='\"'; break;
//case '\\': res='\\'; break;
@@ -452,408 +435,397 @@ Error VisualScriptExpression::_get_token(Token& r_token) {
} break;
}
- str+=res;
+ str += res;
} else {
- str+=ch;
+ str += ch;
}
}
- r_token.type=TK_CONSTANT;
- r_token.value=str;
+ r_token.type = TK_CONSTANT;
+ r_token.value = str;
return OK;
} break;
default: {
- if (cchar<=32) {
+ if (cchar <= 32) {
break;
}
- if (cchar=='-' || (cchar>='0' && cchar<='9')) {
+ if (cchar == '-' || (cchar >= '0' && cchar <= '9')) {
//a number
-
String num;
#define READING_SIGN 0
#define READING_INT 1
#define READING_DEC 2
#define READING_EXP 3
#define READING_DONE 4
- int reading=READING_INT;
-
- if (cchar=='-') {
- num+='-';
- cchar=GET_CHAR();
+ int reading = READING_INT;
+ if (cchar == '-') {
+ num += '-';
+ cchar = GET_CHAR();
}
-
-
CharType c = cchar;
- bool exp_sign=false;
- bool exp_beg=false;
- bool is_float=false;
+ bool exp_sign = false;
+ bool exp_beg = false;
+ bool is_float = false;
- while(true) {
+ while (true) {
- switch(reading) {
+ switch (reading) {
case READING_INT: {
- if (c>='0' && c<='9') {
+ if (c >= '0' && c <= '9') {
//pass
- } else if (c=='.') {
- reading=READING_DEC;
- is_float=true;
- } else if (c=='e') {
- reading=READING_EXP;
+ } else if (c == '.') {
+ reading = READING_DEC;
+ is_float = true;
+ } else if (c == 'e') {
+ reading = READING_EXP;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
case READING_DEC: {
- if (c>='0' && c<='9') {
+ if (c >= '0' && c <= '9') {
- } else if (c=='e') {
- reading=READING_EXP;
+ } else if (c == 'e') {
+ reading = READING_EXP;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
case READING_EXP: {
- if (c>='0' && c<='9') {
- exp_beg=true;
+ if (c >= '0' && c <= '9') {
+ exp_beg = true;
- } else if ((c=='-' || c=='+') && !exp_sign && !exp_beg) {
- if (c=='-')
- is_float=true;
- exp_sign=true;
+ } else if ((c == '-' || c == '+') && !exp_sign && !exp_beg) {
+ if (c == '-')
+ is_float = true;
+ exp_sign = true;
} else {
- reading=READING_DONE;
+ reading = READING_DONE;
}
- } break;
+ } break;
}
- if (reading==READING_DONE)
+ if (reading == READING_DONE)
break;
- num+=String::chr(c);
+ num += String::chr(c);
c = GET_CHAR();
-
-
}
str_ofs--;
- r_token.type=TK_CONSTANT;
+ r_token.type = TK_CONSTANT;
if (is_float)
- r_token.value=num.to_double();
+ r_token.value = num.to_double();
else
- r_token.value=num.to_int();
+ r_token.value = num.to_int();
return OK;
- } else if ((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_') {
+ } else if ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_') {
String id;
- bool first=true;
+ bool first = true;
- while((cchar>='A' && cchar<='Z') || (cchar>='a' && cchar<='z') || cchar=='_' || (!first && cchar>='0' && cchar<='9')) {
+ while ((cchar >= 'A' && cchar <= 'Z') || (cchar >= 'a' && cchar <= 'z') || cchar == '_' || (!first && cchar >= '0' && cchar <= '9')) {
- id+=String::chr(cchar);
- cchar=GET_CHAR();
- first=false;
+ id += String::chr(cchar);
+ cchar = GET_CHAR();
+ first = false;
}
str_ofs--; //go back one
- if (id=="in") {
- r_token.type=TK_OP_IN;
- } else if (id=="null") {
- r_token.type=TK_CONSTANT;
- r_token.value=Variant();
- } else if (id=="true") {
- r_token.type=TK_CONSTANT;
- r_token.value=true;
- } else if (id=="false") {
- r_token.type=TK_CONSTANT;
- r_token.value=false;
- } else if (id=="PI") {
- r_token.type=TK_CONSTANT;
- r_token.value=Math_PI;
+ if (id == "in") {
+ r_token.type = TK_OP_IN;
+ } else if (id == "null") {
+ r_token.type = TK_CONSTANT;
+ r_token.value = Variant();
+ } else if (id == "true") {
+ r_token.type = TK_CONSTANT;
+ r_token.value = true;
+ } else if (id == "false") {
+ r_token.type = TK_CONSTANT;
+ r_token.value = false;
+ } else if (id == "PI") {
+ r_token.type = TK_CONSTANT;
+ r_token.value = Math_PI;
} else if (id == "INF") {
r_token.type = TK_CONSTANT;
r_token.value = Math_INF;
} else if (id == "NAN") {
r_token.type = TK_CONSTANT;
r_token.value = Math_NAN;
- } else if (id=="not") {
- r_token.type=TK_OP_NOT;
- } else if (id=="or") {
- r_token.type=TK_OP_OR;
- } else if (id=="and") {
- r_token.type=TK_OP_AND;
- } else if (id=="self") {
- r_token.type=TK_SELF;
+ } else if (id == "not") {
+ r_token.type = TK_OP_NOT;
+ } else if (id == "or") {
+ r_token.type = TK_OP_OR;
+ } else if (id == "and") {
+ r_token.type = TK_OP_AND;
+ } 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;
- r_token.value=i;
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (id == Variant::get_type_name(Variant::Type(i))) {
+ r_token.type = TK_BASIC_TYPE;
+ r_token.value = i;
return OK;
break;
}
}
VisualScriptBuiltinFunc::BuiltinFunc bifunc = VisualScriptBuiltinFunc::find_function(id);
- if (bifunc!=VisualScriptBuiltinFunc::FUNC_MAX) {
- r_token.type=TK_BUILTIN_FUNC;
- r_token.value=bifunc;
+ if (bifunc != VisualScriptBuiltinFunc::FUNC_MAX) {
+ r_token.type = TK_BUILTIN_FUNC;
+ r_token.value = bifunc;
return OK;
}
- r_token.type=TK_IDENTIFIER;
- r_token.value=id;
+ r_token.type = TK_IDENTIFIER;
+ r_token.value = id;
}
return OK;
} else {
_set_error("Unexpected character.");
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
}
}
}
- r_token.type=TK_ERROR;
+ r_token.type = TK_ERROR;
return ERR_PARSE_ERROR;
}
-const char* VisualScriptExpression::token_name[TK_MAX]={
-"CURLY BRACKET OPEN",
-"CURLY BRACKET CLOSE",
-"BRACKET OPEN",
-"BRACKET CLOSE",
-"PARENTHESIS OPEN",
-"PARENTHESIS CLOSE",
-"IDENTIFIER",
-"BUILTIN FUNC",
-"SELF",
-"CONSTANT",
-"BASIC TYPE",
-"COLON",
-"COMMA",
-"PERIOD",
-"OP IN",
-"OP EQUAL",
-"OP NOT EQUAL",
-"OP LESS",
-"OP LESS EQUAL",
-"OP GREATER",
-"OP GREATER EQUAL",
-"OP AND",
-"OP OR",
-"OP NOT",
-"OP ADD",
-"OP SUB",
-"OP MUL",
-"OP DIV",
-"OP MOD",
-"OP SHIFT LEFT",
-"OP SHIFT RIGHT",
-"OP BIT AND",
-"OP BIT OR",
-"OP BIT XOR",
-"OP BIT INVERT",
-"EOF",
-"ERROR"
+const char *VisualScriptExpression::token_name[TK_MAX] = {
+ "CURLY BRACKET OPEN",
+ "CURLY BRACKET CLOSE",
+ "BRACKET OPEN",
+ "BRACKET CLOSE",
+ "PARENTHESIS OPEN",
+ "PARENTHESIS CLOSE",
+ "IDENTIFIER",
+ "BUILTIN FUNC",
+ "SELF",
+ "CONSTANT",
+ "BASIC TYPE",
+ "COLON",
+ "COMMA",
+ "PERIOD",
+ "OP IN",
+ "OP EQUAL",
+ "OP NOT EQUAL",
+ "OP LESS",
+ "OP LESS EQUAL",
+ "OP GREATER",
+ "OP GREATER EQUAL",
+ "OP AND",
+ "OP OR",
+ "OP NOT",
+ "OP ADD",
+ "OP SUB",
+ "OP MUL",
+ "OP DIV",
+ "OP MOD",
+ "OP SHIFT LEFT",
+ "OP SHIFT RIGHT",
+ "OP BIT AND",
+ "OP BIT OR",
+ "OP BIT XOR",
+ "OP BIT INVERT",
+ "EOF",
+ "ERROR"
};
-VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
-
+VisualScriptExpression::ENode *VisualScriptExpression::_parse_expression() {
Vector<Expression> expression;
- while(true) {
+ while (true) {
//keep appending stuff to expression
- ENode*expr=NULL;
+ ENode *expr = NULL;
Token tk;
_get_token(tk);
if (error_set)
return NULL;
-
-
- switch(tk.type) {
+ switch (tk.type) {
case TK_CURLY_BRACKET_OPEN: {
//a dictionary
DictionaryNode *dn = alloc_node<DictionaryNode>();
+ while (true) {
- while(true) {
-
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_CURLY_BRACKET_CLOSE) {
+ if (tk.type == TK_CURLY_BRACKET_CLOSE) {
break;
}
- str_ofs=cofs; //revert
+ str_ofs = cofs; //revert
//parse an expression
- ENode* expr=_parse_expression();
+ ENode *expr = _parse_expression();
if (!expr)
return NULL;
dn->dict.push_back(expr);
_get_token(tk);
- if (tk.type!=TK_COLON) {
+ if (tk.type != TK_COLON) {
_set_error("Expected ':'");
return NULL;
}
- expr=_parse_expression();
+ expr = _parse_expression();
if (!expr)
return NULL;
dn->dict.push_back(expr);
- cofs=str_ofs;
+ cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good
- } else if (tk.type==TK_CURLY_BRACKET_CLOSE) {
- str_ofs=cofs;
+ } else if (tk.type == TK_CURLY_BRACKET_CLOSE) {
+ str_ofs = cofs;
} else {
_set_error("Expected ',' or '}'");
}
}
- expr=dn;
+ expr = dn;
} break;
case TK_BRACKET_OPEN: {
//an array
ArrayNode *an = alloc_node<ArrayNode>();
+ while (true) {
- while(true) {
-
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_BRACKET_CLOSE) {
+ if (tk.type == TK_BRACKET_CLOSE) {
break;
}
- str_ofs=cofs; //revert
+ str_ofs = cofs; //revert
//parse an expression
- ENode* expr=_parse_expression();
+ ENode *expr = _parse_expression();
if (!expr)
return NULL;
an->array.push_back(expr);
- cofs=str_ofs;
+ cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good
- } else if (tk.type==TK_BRACKET_CLOSE) {
- str_ofs=cofs;
+ } else if (tk.type == TK_BRACKET_CLOSE) {
+ str_ofs = cofs;
} else {
_set_error("Expected ',' or ']'");
}
}
- expr=an;
+ expr = an;
} break;
case TK_PARENTHESIS_OPEN: {
//a suexpression
- ENode* e=_parse_expression();
+ ENode *e = _parse_expression();
if (error_set)
return NULL;
_get_token(tk);
- if (tk.type!=TK_PARENTHESIS_CLOSE) {
+ if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')'");
return NULL;
}
- expr=e;
+ expr = e;
} break;
case TK_IDENTIFIER: {
String what = tk.value;
- int index=-1;
- for(int i=0;i<inputs.size();i++) {
- if (what==inputs[i].name) {
- index=i;
+ int index = -1;
+ for (int i = 0; i < inputs.size(); i++) {
+ if (what == inputs[i].name) {
+ index = i;
break;
}
}
- if (index!=-1) {
+ if (index != -1) {
InputNode *input = alloc_node<InputNode>();
- input->index=index;
- expr=input;
+ input->index = index;
+ expr = input;
} else {
- _set_error("Invalid input identifier '"+what+"'. For script variables, use self (locals are for inputs)."+what);
+ _set_error("Invalid input identifier '" + what + "'. For script variables, use self (locals are for inputs)." + what);
return NULL;
}
} break;
case TK_SELF: {
SelfNode *self = alloc_node<SelfNode>();
- expr=self;
+ expr = self;
} break;
case TK_CONSTANT: {
ConstantNode *constant = alloc_node<ConstantNode>();
- constant->value=tk.value;
- expr=constant;
+ constant->value = tk.value;
+ expr = constant;
} break;
case TK_BASIC_TYPE: {
//constructor..
Variant::Type bt = Variant::Type(int(tk.value));
_get_token(tk);
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '('");
return NULL;
}
ConstructorNode *constructor = alloc_node<ConstructorNode>();
- constructor->data_type=bt;
+ constructor->data_type = bt;
- while(true) {
+ while (true) {
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
break;
}
- str_ofs=cofs; //revert
+ str_ofs = cofs; //revert
//parse an expression
- ENode* expr=_parse_expression();
+ ENode *expr = _parse_expression();
if (!expr)
return NULL;
constructor->arguments.push_back(expr);
- cofs=str_ofs;
+ cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good
- } else if (tk.type==TK_PARENTHESIS_CLOSE) {
- str_ofs=cofs;
+ } else if (tk.type == TK_PARENTHESIS_CLOSE) {
+ str_ofs = cofs;
} else {
_set_error("Expected ',' or ')'");
}
}
- expr=constructor;
+ expr = constructor;
} break;
case TK_BUILTIN_FUNC: {
@@ -861,35 +833,35 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
Variant::Type bt = Variant::Type(int(tk.value));
_get_token(tk);
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '('");
return NULL;
}
BuiltinFuncNode *bifunc = alloc_node<BuiltinFuncNode>();
- bifunc->func=VisualScriptBuiltinFunc::BuiltinFunc(int(tk.value));
+ bifunc->func = VisualScriptBuiltinFunc::BuiltinFunc(int(tk.value));
- while(true) {
+ while (true) {
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
break;
}
- str_ofs=cofs; //revert
+ str_ofs = cofs; //revert
//parse an expression
- ENode* expr=_parse_expression();
+ ENode *expr = _parse_expression();
if (!expr)
return NULL;
bifunc->arguments.push_back(expr);
- cofs=str_ofs;
+ cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good
- } else if (tk.type==TK_PARENTHESIS_CLOSE) {
- str_ofs=cofs;
+ } else if (tk.type == TK_PARENTHESIS_CLOSE) {
+ str_ofs = cofs;
} else {
_set_error("Expected ',' or ')'");
}
@@ -897,25 +869,25 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
int expected_args = VisualScriptBuiltinFunc::get_func_argument_count(bifunc->func);
if (bifunc->arguments.size() != expected_args) {
- _set_error("Builtin func '"+VisualScriptBuiltinFunc::get_func_name(bifunc->func)+"' expects "+itos(expected_args)+" arguments.");
+ _set_error("Builtin func '" + VisualScriptBuiltinFunc::get_func_name(bifunc->func) + "' expects " + itos(expected_args) + " arguments.");
}
- expr=bifunc;
+ expr = bifunc;
} break;
case TK_OP_SUB: {
Expression e;
- e.is_op=true;
- e.op=Variant::OP_NEGATE;
+ e.is_op = true;
+ e.op = Variant::OP_NEGATE;
expression.push_back(e);
continue;
} break;
case TK_OP_NOT: {
Expression e;
- e.is_op=true;
- e.op=Variant::OP_NOT;
+ e.is_op = true;
+ e.op = Variant::OP_NOT;
expression.push_back(e);
continue;
} break;
@@ -924,100 +896,98 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
_set_error("Expected expression.");
return NULL;
} break;
-
}
//before going to operators, must check indexing!
- while(true) {
- int cofs2=str_ofs;
+ while (true) {
+ int cofs2 = str_ofs;
_get_token(tk);
if (error_set)
return NULL;
- bool done=false;
+ bool done = false;
- switch(tk.type) {
+ switch (tk.type) {
case TK_BRACKET_OPEN: {
//value indexing
IndexNode *index = alloc_node<IndexNode>();
- index->base=expr;
+ index->base = expr;
- ENode* what=_parse_expression();
+ ENode *what = _parse_expression();
if (!what)
return NULL;
- index->index=what;
+ index->index = what;
_get_token(tk);
- if (tk.type!=TK_BRACKET_CLOSE) {
+ if (tk.type != TK_BRACKET_CLOSE) {
_set_error("Expected ']' at end of index.");
return NULL;
}
- expr=index;
+ expr = index;
} break;
case TK_PERIOD: {
//named indexing or function call
_get_token(tk);
- if (tk.type!=TK_IDENTIFIER) {
+ if (tk.type != TK_IDENTIFIER) {
_set_error("Expected identifier after '.'");
return NULL;
}
- StringName identifier=tk.value;
+ StringName identifier = tk.value;
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_PARENTHESIS_OPEN) {
+ if (tk.type == TK_PARENTHESIS_OPEN) {
//function call
CallNode *func_call = alloc_node<CallNode>();
- func_call->method=identifier;
- func_call->base=expr;
+ func_call->method = identifier;
+ func_call->base = expr;
- while(true) {
+ while (true) {
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
break;
}
- str_ofs=cofs; //revert
+ str_ofs = cofs; //revert
//parse an expression
- ENode* expr=_parse_expression();
+ ENode *expr = _parse_expression();
if (!expr)
return NULL;
func_call->arguments.push_back(expr);
- cofs=str_ofs;
+ cofs = str_ofs;
_get_token(tk);
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good
- } else if (tk.type==TK_PARENTHESIS_CLOSE) {
- str_ofs=cofs;
+ } else if (tk.type == TK_PARENTHESIS_CLOSE) {
+ str_ofs = cofs;
} else {
_set_error("Expected ',' or ')'");
}
}
- expr=func_call;
+ expr = func_call;
} else {
//named indexing
- str_ofs=cofs;
+ str_ofs = cofs;
NamedIndexNode *index = alloc_node<NamedIndexNode>();
- index->base=expr;
- index->name=identifier;
- expr=index;
-
+ index->base = expr;
+ index->name = identifier;
+ expr = index;
}
} break;
default: {
- str_ofs=cofs2;
- done=true;
+ str_ofs = cofs2;
+ done = true;
} break;
}
@@ -1028,74 +998,68 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
//push expression
{
Expression e;
- e.is_op=false;
- e.node=expr;
+ e.is_op = false;
+ e.node = expr;
expression.push_back(e);
}
//ok finally look for an operator
-
- int cofs=str_ofs;
+ int cofs = str_ofs;
_get_token(tk);
if (error_set)
return NULL;
-
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_SUBSTRACT; 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;
+ 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_SUBSTRACT; 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: {};
}
- if (op==Variant::OP_MAX) { //stop appending stuff
- str_ofs=cofs;
+ if (op == Variant::OP_MAX) { //stop appending stuff
+ str_ofs = cofs;
break;
}
//push operator and go on
{
Expression e;
- e.is_op=true;
- e.op=op;
+ e.is_op = true;
+ e.op = op;
expression.push_back(e);
}
}
-
/* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
+ while (expression.size() > 1) {
- while(expression.size()>1) {
-
- int next_op=-1;
- int min_priority=0xFFFFF;
- bool is_unary=false;
-
- for(int i=0;i<expression.size();i++) {
-
+ 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) {
@@ -1104,77 +1068,80 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
int priority;
- bool unary=false;
-
- switch(expression[i].op) {
-
+ bool unary = false;
- case Variant::OP_BIT_NEGATE: priority=0; unary=true; break;
- case Variant::OP_NEGATE: priority=1; unary=true; break;
+ switch (expression[i].op) {
- case Variant::OP_MULTIPLY: priority=2; break;
- case Variant::OP_DIVIDE: priority=2; break;
- case Variant::OP_MODULE: priority=2; break;
+ case Variant::OP_BIT_NEGATE:
+ priority = 0;
+ unary = true;
+ break;
+ case Variant::OP_NEGATE:
+ priority = 1;
+ unary = true;
+ break;
- case Variant::OP_ADD: priority=3; break;
- case Variant::OP_SUBSTRACT: priority=3; 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_SHIFT_LEFT: priority=4; break;
- case Variant::OP_SHIFT_RIGHT: priority=4; break;
+ case Variant::OP_ADD: priority = 3; break;
+ case Variant::OP_SUBSTRACT: priority = 3; 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_SHIFT_LEFT: priority = 4; break;
+ case Variant::OP_SHIFT_RIGHT: priority = 4; 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_BIT_AND: priority = 5; break;
+ case Variant::OP_BIT_XOR: priority = 6; break;
+ case Variant::OP_BIT_OR: priority = 7; break;
- case Variant::OP_EQUAL: priority=8; break;
- case Variant::OP_NOT_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_IN: priority=10; break;
+ case Variant::OP_EQUAL: priority = 8; break;
+ case Variant::OP_NOT_EQUAL: priority = 8; 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_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;
default: {
- _set_error("Parser bug, invalid operator in expression: "+itos(expression[i].op));
+ _set_error("Parser bug, invalid operator in expression: " + itos(expression[i].op));
return NULL;
}
-
}
- if (priority<min_priority) {
+ if (priority < min_priority) {
// < is used for left to right (default)
// <= is used for right to left
- next_op=i;
- min_priority=priority;
- is_unary=unary;
+ next_op = i;
+ min_priority = priority;
+ is_unary = unary;
}
-
}
- if (next_op==-1) {
-
+ if (next_op == -1) {
_set_error("Yet another parser bug....");
- ERR_FAIL_COND_V(next_op==-1,NULL);
+ ERR_FAIL_COND_V(next_op == -1, NULL);
}
-
// OK! create operator..
if (is_unary) {
- int expr_pos=next_op;
- while(expression[expr_pos].is_op) {
+ int expr_pos = next_op;
+ while (expression[expr_pos].is_op) {
expr_pos++;
- if (expr_pos==expression.size()) {
+ if (expr_pos == expression.size()) {
//can happen..
_set_error("Unexpected end of expression..");
return NULL;
@@ -1182,35 +1149,34 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
}
//consecutively do unary opeators
- for(int i=expr_pos-1;i>=next_op;i--) {
+ 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;
- op->nodes[1]=NULL;
- expression[i].is_op=false;
- expression[i].node=op;
- expression.remove(i+1);
+ op->op = expression[i].op;
+ op->nodes[0] = expression[i + 1].node;
+ op->nodes[1] = NULL;
+ expression[i].is_op = false;
+ expression[i].node = op;
+ expression.remove(i + 1);
}
-
} else {
- if (next_op <1 || next_op>=(expression.size()-1)) {
+ if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[next_op].op;
+ op->op = expression[next_op].op;
- if (expression[next_op-1].is_op) {
+ if (expression[next_op - 1].is_op) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
- if (expression[next_op+1].is_op) {
+ 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 an unary op in a valid combination,
@@ -1220,12 +1186,11 @@ VisualScriptExpression::ENode* VisualScriptExpression::_parse_expression() {
return NULL;
}
-
- op->nodes[0]=expression[next_op-1].node; //expression goes as left
- op->nodes[1]=expression[next_op+1].node; //next expression goes as right
+ op->nodes[0] = expression[next_op - 1].node; //expression goes as left
+ op->nodes[1] = expression[next_op + 1].node; //next expression goes as right
//replace all 3 nodes by this operator and make it an expression
- expression[next_op-1].node=op;
+ expression[next_op - 1].node = op;
expression.remove(next_op);
expression.remove(next_op);
}
@@ -1241,250 +1206,239 @@ bool VisualScriptExpression::_compile_expression() {
if (nodes) {
memdelete(nodes);
- nodes=NULL;
- root=NULL;
-
+ nodes = NULL;
+ root = NULL;
}
- error_str=String();
- error_set=false;
- str_ofs=0;
+ error_str = String();
+ error_set = false;
+ str_ofs = 0;
- root=_parse_expression();
+ root = _parse_expression();
if (error_set) {
- root=NULL;
+ root = NULL;
if (nodes) {
memdelete(nodes);
}
- nodes=NULL;
+ nodes = NULL;
return true;
}
- expression_dirty=false;
+ expression_dirty = false;
return false;
}
-
class VisualScriptNodeInstanceExpression : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
VisualScriptExpression *expression;
//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,Variant::CallError &ce) {
+ virtual bool _execute(const Variant **p_inputs, VisualScriptExpression::ENode *p_node, Variant &r_ret, String &r_error_str, Variant::CallError &ce) {
- switch(p_node->type) {
- case VisualScriptExpression::ENode::TYPE_INPUT: {
+ 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];
+ const VisualScriptExpression::InputNode *in = static_cast<const VisualScriptExpression::InputNode *>(p_node);
+ r_ret = *p_inputs[in->index];
} break;
- case VisualScriptExpression::ENode::TYPE_CONSTANT: {
+ case VisualScriptExpression::ENode::TYPE_CONSTANT: {
- const VisualScriptExpression::ConstantNode *c = static_cast<const VisualScriptExpression::ConstantNode*>(p_node);
- r_ret=c->value;
+ const VisualScriptExpression::ConstantNode *c = static_cast<const VisualScriptExpression::ConstantNode *>(p_node);
+ r_ret = c->value;
} break;
- case VisualScriptExpression::ENode::TYPE_SELF: {
+ case VisualScriptExpression::ENode::TYPE_SELF: {
- r_ret=instance->get_owner_ptr();
+ r_ret = instance->get_owner_ptr();
} break;
- case VisualScriptExpression::ENode::TYPE_OPERATOR: {
+ case VisualScriptExpression::ENode::TYPE_OPERATOR: {
-
- const VisualScriptExpression::OperatorNode *op = static_cast<const VisualScriptExpression::OperatorNode*>(p_node);
+ 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);
+ bool ret = _execute(p_inputs, op->nodes[0], a, r_error_str, ce);
if (ret)
return true;
Variant b;
if (op->nodes[1]) {
- ret = _execute(p_inputs,op->nodes[1],b,r_error_str,ce);
+ ret = _execute(p_inputs, op->nodes[1], b, r_error_str, ce);
if (ret)
return true;
}
- bool valid=true;
- Variant::evaluate(op->op,a,b,r_ret,valid);
+ bool valid = true;
+ Variant::evaluate(op->op, a, b, r_ret, valid);
if (!valid) {
- r_error_str="Invalid operands to operator "+Variant::get_operator_name(op->op)+": "+Variant::get_type_name(a.get_type())+" and "+Variant::get_type_name(b.get_type())+".";
+ r_error_str = "Invalid operands to operator " + Variant::get_operator_name(op->op) + ": " + Variant::get_type_name(a.get_type()) + " and " + Variant::get_type_name(b.get_type()) + ".";
return true;
}
} break;
- case VisualScriptExpression::ENode::TYPE_INDEX: {
+ case VisualScriptExpression::ENode::TYPE_INDEX: {
- const VisualScriptExpression::IndexNode *index = static_cast<const VisualScriptExpression::IndexNode*>(p_node);
+ 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);
+ bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
if (ret)
return true;
Variant idx;
- ret = _execute(p_inputs,index->index,idx,r_error_str,ce);
+ ret = _execute(p_inputs, index->index, idx, r_error_str, ce);
if (ret)
return true;
bool valid;
- r_ret=base.get(idx,&valid);
+ r_ret = base.get(idx, &valid);
if (!valid) {
- r_error_str="Invalid index of type "+Variant::get_type_name(idx.get_type())+" for base of type "+Variant::get_type_name(base.get_type())+".";
+ r_error_str = "Invalid index of type " + Variant::get_type_name(idx.get_type()) + " for base of type " + Variant::get_type_name(base.get_type()) + ".";
return true;
}
-
-
} break;
- case VisualScriptExpression::ENode::TYPE_NAMED_INDEX: {
+ case VisualScriptExpression::ENode::TYPE_NAMED_INDEX: {
- const VisualScriptExpression::NamedIndexNode *index = static_cast<const VisualScriptExpression::NamedIndexNode*>(p_node);
+ 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);
+ bool ret = _execute(p_inputs, index->base, base, r_error_str, ce);
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())+".";
+ r_error_str = "Invalid index '" + String(index->name) + "' for base of type " + Variant::get_type_name(base.get_type()) + ".";
return true;
}
} break;
- case VisualScriptExpression::ENode::TYPE_ARRAY: {
- const VisualScriptExpression::ArrayNode *array = static_cast<const VisualScriptExpression::ArrayNode*>(p_node);
+ case VisualScriptExpression::ENode::TYPE_ARRAY: {
+ const VisualScriptExpression::ArrayNode *array = static_cast<const VisualScriptExpression::ArrayNode *>(p_node);
Array arr;
arr.resize(array->array.size());
- for (int i=0;i<array->array.size();i++) {
+ for (int i = 0; i < array->array.size(); i++) {
Variant value;
- bool ret = _execute(p_inputs,array->array[i],value,r_error_str,ce);
+ bool ret = _execute(p_inputs, array->array[i], value, r_error_str, ce);
if (ret)
return true;
- arr[i]=value;
+ arr[i] = value;
}
- r_ret=arr;
+ r_ret = arr;
} break;
- case VisualScriptExpression::ENode::TYPE_DICTIONARY: {
- const VisualScriptExpression::DictionaryNode *dictionary = static_cast<const VisualScriptExpression::DictionaryNode*>(p_node);
+ case VisualScriptExpression::ENode::TYPE_DICTIONARY: {
+ const VisualScriptExpression::DictionaryNode *dictionary = static_cast<const VisualScriptExpression::DictionaryNode *>(p_node);
Dictionary d;
- for (int i=0;i<dictionary->dict.size();i+=2) {
+ 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);
+ bool ret = _execute(p_inputs, dictionary->dict[i + 0], key, r_error_str, ce);
if (ret)
return true;
Variant value;
- ret = _execute(p_inputs,dictionary->dict[i+1],value,r_error_str,ce);
+ ret = _execute(p_inputs, dictionary->dict[i + 1], value, r_error_str, ce);
if (ret)
return true;
- d[key]=value;
+ d[key] = value;
}
- r_ret=d;
+ r_ret = d;
} break;
- case VisualScriptExpression::ENode::TYPE_CONSTRUCTOR: {
+ case VisualScriptExpression::ENode::TYPE_CONSTRUCTOR: {
- const VisualScriptExpression::ConstructorNode *constructor = static_cast<const VisualScriptExpression::ConstructorNode*>(p_node);
+ const VisualScriptExpression::ConstructorNode *constructor = static_cast<const VisualScriptExpression::ConstructorNode *>(p_node);
Vector<Variant> arr;
- Vector<const Variant*> argp;
+ Vector<const Variant *> argp;
arr.resize(constructor->arguments.size());
argp.resize(constructor->arguments.size());
- for (int i=0;i<constructor->arguments.size();i++) {
+ for (int i = 0; i < constructor->arguments.size(); i++) {
Variant value;
- bool ret = _execute(p_inputs,constructor->arguments[i],value,r_error_str,ce);
+ bool ret = _execute(p_inputs, constructor->arguments[i], value, r_error_str, ce);
if (ret)
return true;
- arr[i]=value;
- argp[i]=&arr[i];
+ arr[i] = value;
+ argp[i] = &arr[i];
}
+ r_ret = Variant::construct(constructor->data_type, argp.ptr(), argp.size(), ce);
- r_ret=Variant::construct(constructor->data_type,argp.ptr(),argp.size(),ce);
-
- if (ce.error!=Variant::CallError::CALL_OK) {
- r_error_str="Invalid arguments to construct '"+Variant::get_type_name(constructor->data_type)+"'.";
+ if (ce.error != Variant::CallError::CALL_OK) {
+ r_error_str = "Invalid arguments to construct '" + Variant::get_type_name(constructor->data_type) + "'.";
return true;
}
-
} break;
- case VisualScriptExpression::ENode::TYPE_BUILTIN_FUNC: {
+ case VisualScriptExpression::ENode::TYPE_BUILTIN_FUNC: {
- const VisualScriptExpression::BuiltinFuncNode *bifunc = static_cast<const VisualScriptExpression::BuiltinFuncNode*>(p_node);
+ const VisualScriptExpression::BuiltinFuncNode *bifunc = static_cast<const VisualScriptExpression::BuiltinFuncNode *>(p_node);
Vector<Variant> arr;
- Vector<const Variant*> argp;
+ Vector<const Variant *> argp;
arr.resize(bifunc->arguments.size());
argp.resize(bifunc->arguments.size());
- for (int i=0;i<bifunc->arguments.size();i++) {
+ for (int i = 0; i < bifunc->arguments.size(); i++) {
Variant value;
- bool ret = _execute(p_inputs,bifunc->arguments[i],value,r_error_str,ce);
+ bool ret = _execute(p_inputs, bifunc->arguments[i], value, r_error_str, ce);
if (ret)
return true;
- arr[i]=value;
- argp[i]=&arr[i];
+ arr[i] = value;
+ argp[i] = &arr[i];
}
+ VisualScriptBuiltinFunc::exec_func(bifunc->func, argp.ptr(), &r_ret, ce, r_error_str);
- VisualScriptBuiltinFunc::exec_func(bifunc->func,argp.ptr(),&r_ret,ce,r_error_str);
-
- if (ce.error!=Variant::CallError::CALL_OK) {
- r_error_str="Builtin Call Failed. "+r_error_str;
+ if (ce.error != Variant::CallError::CALL_OK) {
+ r_error_str = "Builtin Call Failed. " + r_error_str;
return true;
}
} break;
- case VisualScriptExpression::ENode::TYPE_CALL: {
-
- const VisualScriptExpression::CallNode *call = static_cast<const VisualScriptExpression::CallNode*>(p_node);
+ 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);
+ bool ret = _execute(p_inputs, call->base, base, r_error_str, ce);
if (ret)
return true;
Vector<Variant> arr;
- Vector<const Variant*> argp;
+ Vector<const Variant *> argp;
arr.resize(call->arguments.size());
argp.resize(call->arguments.size());
- for (int i=0;i<call->arguments.size();i++) {
+ for (int i = 0; i < call->arguments.size(); i++) {
Variant value;
- bool ret = _execute(p_inputs,call->arguments[i],value,r_error_str,ce);
+ bool ret = _execute(p_inputs, call->arguments[i], value, r_error_str, ce);
if (ret)
return true;
- arr[i]=value;
- argp[i]=&arr[i];
+ arr[i] = value;
+ argp[i] = &arr[i];
}
+ r_ret = base.call(call->method, argp.ptr(), argp.size(), ce);
- r_ret=base.call(call->method,argp.ptr(),argp.size(),ce);
-
- if (ce.error!=Variant::CallError::CALL_OK) {
- r_error_str="On call to '"+String(call->method)+"':";
+ if (ce.error != Variant::CallError::CALL_OK) {
+ r_error_str = "On call to '" + String(call->method) + "':";
return true;
}
@@ -1493,53 +1447,47 @@ public:
return false;
}
- virtual int step(const Variant** p_inputs,Variant** p_outputs,StartMode p_start_mode,Variant* p_working_mem,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
if (!expression->root || expression->error_set) {
- r_error_str=expression->error_str;
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = expression->error_str;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
-
- bool error = _execute(p_inputs,expression->root,*p_outputs[0],r_error_str,r_error);
- if (error && r_error.error==Variant::CallError::CALL_OK) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ bool error = _execute(p_inputs, expression->root, *p_outputs[0], r_error_str, r_error);
+ if (error && r_error.error == Variant::CallError::CALL_OK) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
#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=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ 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 = Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
#endif
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptExpression::instance(VisualScriptInstance* p_instance){
+VisualScriptNodeInstance *VisualScriptExpression::instance(VisualScriptInstance *p_instance) {
_compile_expression();
- VisualScriptNodeInstanceExpression *instance = memnew( VisualScriptNodeInstanceExpression );
- instance->instance=p_instance;
- instance->expression=this;
+ VisualScriptNodeInstanceExpression *instance = memnew(VisualScriptNodeInstanceExpression);
+ instance->instance = p_instance;
+ instance->expression = this;
return instance;
}
-
-VisualScriptExpression::VisualScriptExpression()
-{
- output_type=Variant::NIL;
- expression_dirty=true;
- error_set=true;
- root=NULL;
- nodes=NULL;
- sequenced=false;
+VisualScriptExpression::VisualScriptExpression() {
+ output_type = Variant::NIL;
+ expression_dirty = true;
+ error_set = true;
+ root = NULL;
+ nodes = NULL;
+ sequenced = false;
}
VisualScriptExpression::~VisualScriptExpression() {
@@ -1549,9 +1497,7 @@ VisualScriptExpression::~VisualScriptExpression() {
}
}
-
void register_visual_script_expression_node() {
- VisualScriptLanguage::singleton->add_register_func("operators/expression",create_node_generic<VisualScriptExpression>);
-
+ 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 5bd960f60c..59a7d9fba0 100644
--- a/modules/visual_script/visual_script_expression.h
+++ b/modules/visual_script/visual_script_expression.h
@@ -34,15 +34,15 @@
class VisualScriptExpression : public VisualScriptNode {
- GDCLASS(VisualScriptExpression,VisualScriptNode)
-friend class VisualScriptNodeInstanceExpression;
+ GDCLASS(VisualScriptExpression, VisualScriptNode)
+ friend class VisualScriptNodeInstanceExpression;
struct Input {
Variant::Type type;
String name;
- Input() { type=Variant::NIL; }
+ Input() { type = Variant::NIL; }
};
Vector<Input> inputs;
@@ -97,28 +97,25 @@ friend class VisualScriptNodeInstanceExpression;
TK_MAX
};
- static const char* token_name[TK_MAX];
+ static const char *token_name[TK_MAX];
struct Token {
TokenType type;
Variant value;
};
-
- void _set_error(const String& p_err) {
+ void _set_error(const String &p_err) {
if (error_set)
return;
- error_str=p_err;
- error_set=true;
+ error_str = p_err;
+ error_set = true;
}
- Error _get_token(Token& r_token);
+ Error _get_token(Token &r_token);
String error_str;
bool error_set;
-
-
struct ENode {
enum Type {
@@ -139,8 +136,12 @@ friend class VisualScriptNodeInstanceExpression;
Type type;
- ENode() { next=NULL; }
- virtual ~ENode() { if (next) { memdelete(next); } }
+ ENode() { next = NULL; }
+ virtual ~ENode() {
+ if (next) {
+ memdelete(next);
+ }
+ }
};
struct Expression {
@@ -152,22 +153,21 @@ friend class VisualScriptNodeInstanceExpression;
};
};
- ENode* _parse_expression();
+ ENode *_parse_expression();
struct InputNode : public ENode {
int index;
InputNode() {
- type=TYPE_INPUT;
+ type = TYPE_INPUT;
}
};
-
struct ConstantNode : public ENode {
Variant value;
ConstantNode() {
- type=TYPE_CONSTANT;
+ type = TYPE_CONSTANT;
}
};
@@ -175,119 +175,104 @@ friend class VisualScriptNodeInstanceExpression;
Variant::Operator op;
- ENode* nodes[2];
+ ENode *nodes[2];
OperatorNode() {
- type=TYPE_OPERATOR;
+ type = TYPE_OPERATOR;
}
};
struct SelfNode : public ENode {
-
SelfNode() {
- type=TYPE_SELF;
+ type = TYPE_SELF;
}
};
struct IndexNode : public ENode {
- ENode*base;
- ENode*index;
+ ENode *base;
+ ENode *index;
IndexNode() {
- type=TYPE_INDEX;
+ type = TYPE_INDEX;
}
};
struct NamedIndexNode : public ENode {
- ENode*base;
+ ENode *base;
StringName name;
NamedIndexNode() {
- type=TYPE_NAMED_INDEX;
+ type = TYPE_NAMED_INDEX;
}
-
};
struct ConstructorNode : public ENode {
Variant::Type data_type;
- Vector<ENode*> arguments;
+ Vector<ENode *> arguments;
ConstructorNode() {
- type=TYPE_CONSTRUCTOR;
+ type = TYPE_CONSTRUCTOR;
}
};
struct CallNode : public ENode {
- ENode*base;
+ ENode *base;
StringName method;
- Vector<ENode*> arguments;
+ Vector<ENode *> arguments;
CallNode() {
- type=TYPE_CALL;
+ type = TYPE_CALL;
}
-
};
struct ArrayNode : public ENode {
- Vector<ENode*> array;
+ Vector<ENode *> array;
ArrayNode() {
- type=TYPE_ARRAY;
+ type = TYPE_ARRAY;
}
-
};
struct DictionaryNode : public ENode {
- Vector<ENode*> dict;
+ Vector<ENode *> dict;
DictionaryNode() {
- type=TYPE_DICTIONARY;
+ type = TYPE_DICTIONARY;
}
-
};
struct BuiltinFuncNode : public ENode {
VisualScriptBuiltinFunc::BuiltinFunc func;
- Vector<ENode*> arguments;
+ Vector<ENode *> arguments;
BuiltinFuncNode() {
- type=TYPE_BUILTIN_FUNC;
+ type = TYPE_BUILTIN_FUNC;
}
};
- template<class T>
- T* alloc_node() {
- T* node = memnew(T);
- node->next=nodes;
- nodes=node;
+ template <class T>
+ T *alloc_node() {
+ T *node = memnew(T);
+ node->next = nodes;
+ nodes = node;
return node;
}
ENode *root;
ENode *nodes;
-
-
-
-
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ 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 String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -295,14 +280,12 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "operators"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptExpression();
~VisualScriptExpression();
};
-
void register_visual_script_expression_node();
-
#endif // VISUALSCRIPTEXPRESSION_H
diff --git a/modules/visual_script/visual_script_flow_control.cpp b/modules/visual_script/visual_script_flow_control.cpp
index 8aff96b70c..78847fb588 100644
--- a/modules/visual_script/visual_script_flow_control.cpp
+++ b/modules/visual_script/visual_script_flow_control.cpp
@@ -28,9 +28,8 @@
/*************************************************************************/
#include "visual_script_flow_control.h"
-#include "os/keyboard.h"
#include "global_config.h"
-
+#include "os/keyboard.h"
//////////////////////////////////////////
////////////////RETURN////////////////////
@@ -41,16 +40,16 @@ int VisualScriptReturn::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptReturn::has_input_sequence_port() const{
+bool VisualScriptReturn::has_input_sequence_port() const {
return true;
}
-int VisualScriptReturn::get_input_value_port_count() const{
+int VisualScriptReturn::get_input_value_port_count() const {
- return with_value?1:0;
+ return with_value ? 1 : 0;
}
-int VisualScriptReturn::get_output_value_port_count() const{
+int VisualScriptReturn::get_output_value_port_count() const {
return 0;
}
@@ -60,14 +59,14 @@ 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 VisualScriptReturn::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="result";
- pinfo.type=type;
+ pinfo.name = "result";
+ pinfo.type = type;
return pinfo;
}
-PropertyInfo VisualScriptReturn::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptReturn::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
@@ -83,23 +82,22 @@ String VisualScriptReturn::get_text() const {
void VisualScriptReturn::set_return_type(Variant::Type p_type) {
- if (type==p_type)
+ if (type == p_type)
return;
- type=p_type;
+ type = p_type;
ports_changed_notify();
-
}
-Variant::Type VisualScriptReturn::get_return_type() const{
+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;
+ with_value = p_enable;
ports_changed_notify();
}
@@ -110,24 +108,22 @@ bool VisualScriptReturn::is_return_value_enabled() const {
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);
- ClassDB::bind_method(D_METHOD("is_return_value_enabled"),&VisualScriptReturn::is_return_value_enabled);
+ 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);
+ ClassDB::bind_method(D_METHOD("is_return_value_enabled"), &VisualScriptReturn::is_return_value_enabled);
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"return_value/enabled"),"set_enable_return_value","is_return_value_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"return_value/type",PROPERTY_HINT_ENUM,argt),"set_return_type","get_return_type");
-
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "return_value/enabled"), "set_enable_return_value", "is_return_value_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "return_value/type", PROPERTY_HINT_ENUM, argt), "set_return_type", "get_return_type");
}
class VisualScriptNodeInstanceReturn : public VisualScriptNodeInstance {
public:
-
VisualScriptReturn *node;
VisualScriptInstance *instance;
bool with_value;
@@ -136,7 +132,7 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
if (with_value) {
*p_working_mem = *p_inputs[0];
@@ -146,27 +142,25 @@ public:
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptReturn::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptReturn::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceReturn * instance = memnew(VisualScriptNodeInstanceReturn );
- instance->node=this;
- instance->instance=p_instance;
- instance->with_value=with_value;
+ VisualScriptNodeInstanceReturn *instance = memnew(VisualScriptNodeInstanceReturn);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->with_value = with_value;
return instance;
}
VisualScriptReturn::VisualScriptReturn() {
- with_value=false;
- type=Variant::NIL;
+ with_value = false;
+ type = Variant::NIL;
}
-template<bool with_value>
-static Ref<VisualScriptNode> create_return_node(const String& p_name) {
+template <bool with_value>
+static Ref<VisualScriptNode> create_return_node(const String &p_name) {
Ref<VisualScriptReturn> node;
node.instance();
@@ -174,8 +168,6 @@ static Ref<VisualScriptNode> create_return_node(const String& p_name) {
return node;
}
-
-
//////////////////////////////////////////
////////////////CONDITION/////////////////
//////////////////////////////////////////
@@ -185,38 +177,38 @@ int VisualScriptCondition::get_output_sequence_port_count() const {
return 3;
}
-bool VisualScriptCondition::has_input_sequence_port() const{
+bool VisualScriptCondition::has_input_sequence_port() const {
return true;
}
-int VisualScriptCondition::get_input_value_port_count() const{
+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
return "done";
}
-PropertyInfo VisualScriptCondition::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptCondition::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="cond";
- pinfo.type=Variant::BOOL;
+ pinfo.name = "cond";
+ pinfo.type = Variant::BOOL;
return pinfo;
}
-PropertyInfo VisualScriptCondition::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptCondition::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
@@ -230,16 +222,11 @@ String VisualScriptCondition::get_text() const {
return "if (cond) is: ";
}
-
void VisualScriptCondition::_bind_methods() {
-
-
-
}
class VisualScriptNodeInstanceCondition : public VisualScriptNodeInstance {
public:
-
VisualScriptCondition *node;
VisualScriptInstance *instance;
@@ -247,33 +234,28 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::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())
return 0 | STEP_FLAG_PUSH_STACK_BIT;
else
return 1 | STEP_FLAG_PUSH_STACK_BIT;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptCondition::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptCondition::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceCondition * instance = memnew(VisualScriptNodeInstanceCondition );
- instance->node=this;
- instance->instance=p_instance;
+ VisualScriptNodeInstanceCondition *instance = memnew(VisualScriptNodeInstanceCondition);
+ instance->node = this;
+ instance->instance = p_instance;
return instance;
}
VisualScriptCondition::VisualScriptCondition() {
-
}
-
-
//////////////////////////////////////////
////////////////WHILE/////////////////
//////////////////////////////////////////
@@ -283,36 +265,36 @@ int VisualScriptWhile::get_output_sequence_port_count() const {
return 2;
}
-bool VisualScriptWhile::has_input_sequence_port() const{
+bool VisualScriptWhile::has_input_sequence_port() const {
return true;
}
-int VisualScriptWhile::get_input_value_port_count() const{
+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
return "exit";
}
-PropertyInfo VisualScriptWhile::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptWhile::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="cond";
- pinfo.type=Variant::BOOL;
+ pinfo.name = "cond";
+ pinfo.type = Variant::BOOL;
return pinfo;
}
-PropertyInfo VisualScriptWhile::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptWhile::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
@@ -326,16 +308,11 @@ String VisualScriptWhile::get_text() const {
return "while (cond): ";
}
-
void VisualScriptWhile::_bind_methods() {
-
-
-
}
class VisualScriptNodeInstanceWhile : public VisualScriptNodeInstance {
public:
-
VisualScriptWhile *node;
VisualScriptInstance *instance;
@@ -343,32 +320,27 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
bool keep_going = p_inputs[0]->operator bool();
if (keep_going)
- return 0|STEP_FLAG_PUSH_STACK_BIT;
+ return 0 | STEP_FLAG_PUSH_STACK_BIT;
else
return 1;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptWhile::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptWhile::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceWhile * instance = memnew(VisualScriptNodeInstanceWhile );
- instance->node=this;
- instance->instance=p_instance;
+ VisualScriptNodeInstanceWhile *instance = memnew(VisualScriptNodeInstanceWhile);
+ instance->node = this;
+ instance->instance = p_instance;
return instance;
}
VisualScriptWhile::VisualScriptWhile() {
-
}
-
-
//////////////////////////////////////////
////////////////ITERATOR/////////////////
//////////////////////////////////////////
@@ -378,39 +350,39 @@ int VisualScriptIterator::get_output_sequence_port_count() const {
return 2;
}
-bool VisualScriptIterator::has_input_sequence_port() const{
+bool VisualScriptIterator::has_input_sequence_port() const {
return true;
}
-int VisualScriptIterator::get_input_value_port_count() const{
+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
return "exit";
}
-PropertyInfo VisualScriptIterator::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptIterator::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="input";
- pinfo.type=Variant::NIL;
+ pinfo.name = "input";
+ pinfo.type = Variant::NIL;
return pinfo;
}
-PropertyInfo VisualScriptIterator::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptIterator::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="elem";
- pinfo.type=Variant::NIL;
+ pinfo.name = "elem";
+ pinfo.type = Variant::NIL;
return pinfo;
}
String VisualScriptIterator::get_caption() const {
@@ -423,16 +395,11 @@ String VisualScriptIterator::get_text() const {
return "for (elem) in (input): ";
}
-
void VisualScriptIterator::_bind_methods() {
-
-
-
}
class VisualScriptNodeInstanceIterator : public VisualScriptNodeInstance {
public:
-
VisualScriptIterator *node;
VisualScriptInstance *instance;
@@ -440,77 +407,68 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_start_mode==START_MODE_BEGIN_SEQUENCE) {
- p_working_mem[0]=*p_inputs[0];
+ if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
+ p_working_mem[0] = *p_inputs[0];
bool valid;
- bool can_iter = p_inputs[0]->iter_init(p_working_mem[1],valid);
+ bool can_iter = p_inputs[0]->iter_init(p_working_mem[1], valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Input type not iterable: ")+Variant::get_type_name(p_inputs[0]->get_type());
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Input type not iterable: ") + Variant::get_type_name(p_inputs[0]->get_type());
return 0;
}
if (!can_iter)
return 1; //nothing to iterate
-
- *p_outputs[0]=p_working_mem[0].iter_get( p_working_mem[1],valid);
+ *p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Iterator became invalid");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Iterator became invalid");
return 0;
}
-
} else { //continue sequence
bool valid;
- bool can_iter = p_working_mem[0].iter_next(p_working_mem[1],valid);
+ bool can_iter = p_working_mem[0].iter_next(p_working_mem[1], valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Iterator became invalid: ")+Variant::get_type_name(p_inputs[0]->get_type());
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Iterator became invalid: ") + Variant::get_type_name(p_inputs[0]->get_type());
return 0;
}
if (!can_iter)
return 1; //nothing to iterate
-
- *p_outputs[0]=p_working_mem[0].iter_get( p_working_mem[1],valid);
+ *p_outputs[0] = p_working_mem[0].iter_get(p_working_mem[1], valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Iterator became invalid");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Iterator became invalid");
return 0;
}
-
}
- return 0|STEP_FLAG_PUSH_STACK_BIT; //go around
+ return 0 | STEP_FLAG_PUSH_STACK_BIT; //go around
}
-
-
};
-VisualScriptNodeInstance* VisualScriptIterator::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptIterator::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIterator * instance = memnew(VisualScriptNodeInstanceIterator );
- instance->node=this;
- instance->instance=p_instance;
+ VisualScriptNodeInstanceIterator *instance = memnew(VisualScriptNodeInstanceIterator);
+ instance->node = this;
+ instance->instance = p_instance;
return instance;
}
VisualScriptIterator::VisualScriptIterator() {
-
}
-
-
//////////////////////////////////////////
////////////////SEQUENCE/////////////////
//////////////////////////////////////////
@@ -520,30 +478,30 @@ int VisualScriptSequence::get_output_sequence_port_count() const {
return steps;
}
-bool VisualScriptSequence::has_input_sequence_port() const{
+bool VisualScriptSequence::has_input_sequence_port() const {
return true;
}
-int VisualScriptSequence::get_input_value_port_count() const{
+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);
+ return itos(p_port + 1);
}
-PropertyInfo VisualScriptSequence::get_input_value_port_info(int p_idx) const{
+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");
+PropertyInfo VisualScriptSequence::get_output_value_port_info(int p_idx) const {
+ return PropertyInfo(Variant::INT, "current");
}
String VisualScriptSequence::get_caption() const {
@@ -557,13 +515,12 @@ String VisualScriptSequence::get_text() const {
void VisualScriptSequence::set_steps(int p_steps) {
- ERR_FAIL_COND(p_steps<1);
- if (steps==p_steps)
+ ERR_FAIL_COND(p_steps < 1);
+ if (steps == p_steps)
return;
- steps=p_steps;
+ steps = p_steps;
ports_changed_notify();
-
}
int VisualScriptSequence::get_steps() const {
@@ -573,16 +530,14 @@ int VisualScriptSequence::get_steps() const {
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);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"steps",PROPERTY_HINT_RANGE,"1,64,1"),"set_steps","get_steps");
+ ClassDB::bind_method(D_METHOD("set_steps", "steps"), &VisualScriptSequence::set_steps);
+ ClassDB::bind_method(D_METHOD("get_steps"), &VisualScriptSequence::get_steps);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "steps", PROPERTY_HINT_RANGE, "1,64,1"), "set_steps", "get_steps");
}
class VisualScriptNodeInstanceSequence : public VisualScriptNodeInstance {
public:
-
VisualScriptSequence *node;
VisualScriptInstance *instance;
int steps;
@@ -591,89 +546,83 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_start_mode==START_MODE_BEGIN_SEQUENCE) {
+ if (p_start_mode == START_MODE_BEGIN_SEQUENCE) {
- p_working_mem[0]=0;
+ p_working_mem[0] = 0;
}
int step = p_working_mem[0];
- *p_outputs[0]=step;
+ *p_outputs[0] = step;
- if (step+1==steps)
+ if (step + 1 == steps)
return step;
else {
- p_working_mem[0]=step+1;
- return step|STEP_FLAG_PUSH_STACK_BIT;
+ p_working_mem[0] = step + 1;
+ return step | STEP_FLAG_PUSH_STACK_BIT;
}
-
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSequence::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSequence::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSequence * instance = memnew(VisualScriptNodeInstanceSequence );
- instance->node=this;
- instance->instance=p_instance;
- instance->steps=steps;
+ VisualScriptNodeInstanceSequence *instance = memnew(VisualScriptNodeInstanceSequence);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->steps = steps;
return instance;
}
VisualScriptSequence::VisualScriptSequence() {
- steps=1;
+ steps = 1;
}
-
//////////////////////////////////////////
////////////////EVENT TYPE FILTER///////////
//////////////////////////////////////////
int VisualScriptSwitch::get_output_sequence_port_count() const {
- return case_values.size()+1;
+ return case_values.size() + 1;
}
-bool VisualScriptSwitch::has_input_sequence_port() const{
+bool VisualScriptSwitch::has_input_sequence_port() const {
return true;
}
-int VisualScriptSwitch::get_input_value_port_count() const{
-
+int VisualScriptSwitch::get_input_value_port_count() const {
- return case_values.size()+1;
+ 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{
+PropertyInfo VisualScriptSwitch::get_input_value_port_info(int p_idx) const {
- if (p_idx<case_values.size()) {
- return PropertyInfo(case_values[p_idx].type," =");
+ if (p_idx < case_values.size()) {
+ return PropertyInfo(case_values[p_idx].type, " =");
} else
- return PropertyInfo(Variant::NIL,"input");
+ return PropertyInfo(Variant::NIL, "input");
}
-PropertyInfo VisualScriptSwitch::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSwitch::get_output_value_port_info(int p_idx) const {
return PropertyInfo();
}
-
String VisualScriptSwitch::get_caption() const {
return "Switch";
@@ -684,47 +633,43 @@ String VisualScriptSwitch::get_text() const {
return "'input' is:";
}
-
class VisualScriptNodeInstanceSwitch : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
int case_count;
//virtual int get_working_memory_size() const { return 0; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_start_mode==START_MODE_CONTINUE_SEQUENCE) {
+ if (p_start_mode == START_MODE_CONTINUE_SEQUENCE) {
return case_count; //exit
}
- for(int i=0;i<case_count;i++) {
+ for (int i = 0; i < case_count; i++) {
- if (*p_inputs[i]==*p_inputs[case_count]) {
- return i|STEP_FLAG_PUSH_STACK_BIT;
+ if (*p_inputs[i] == *p_inputs[case_count]) {
+ return i | STEP_FLAG_PUSH_STACK_BIT;
}
}
return case_count;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSwitch::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSwitch::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSwitch * instance = memnew(VisualScriptNodeInstanceSwitch );
- instance->instance=p_instance;
- instance->case_count=case_values.size();
+ VisualScriptNodeInstanceSwitch *instance = memnew(VisualScriptNodeInstanceSwitch);
+ instance->instance = p_instance;
+ instance->case_count = case_values.size();
return instance;
}
-bool VisualScriptSwitch::_set(const StringName& p_name, const Variant& p_value) {
+bool VisualScriptSwitch::_set(const StringName &p_name, const Variant &p_value) {
- if (String(p_name)=="case_count") {
+ if (String(p_name) == "case_count") {
case_values.resize(p_value);
_change_notify();
ports_changed_notify();
@@ -733,10 +678,10 @@ 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);
+ int idx = String(p_name).get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, case_values.size(), false);
- case_values[idx].type=Variant::Type(int(p_value));
+ case_values[idx].type = Variant::Type(int(p_value));
_change_notify();
ports_changed_notify();
@@ -746,71 +691,63 @@ bool VisualScriptSwitch::_set(const StringName& p_name, const Variant& p_value)
return false;
}
-bool VisualScriptSwitch::_get(const StringName& p_name,Variant &r_ret) const {
+bool VisualScriptSwitch::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name)=="case_count") {
- r_ret=case_values.size();
+ 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);
+ int idx = String(p_name).get_slice("/", 1).to_int();
+ ERR_FAIL_INDEX_V(idx, case_values.size(), false);
- r_ret=case_values[idx].type;
+ r_ret = case_values[idx].type;
return true;
}
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"));
+ p_list->push_back(PropertyInfo(Variant::INT, "case_count", PROPERTY_HINT_RANGE, "0,128"));
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- for(int i=0;i<case_values.size();i++) {
- p_list->push_back(PropertyInfo(Variant::INT,"case/"+itos(i),PROPERTY_HINT_ENUM,argt));
+ for (int i = 0; i < case_values.size(); i++) {
+ p_list->push_back(PropertyInfo(Variant::INT, "case/" + itos(i), PROPERTY_HINT_ENUM, argt));
}
}
-
void VisualScriptSwitch::_bind_methods() {
-
-
}
VisualScriptSwitch::VisualScriptSwitch() {
-
-
}
//////////////////////////////////////////
////////////////EVENT ACTION FILTER///////////
//////////////////////////////////////////
-
int VisualScriptInputFilter::get_output_sequence_port_count() const {
return filters.size();
}
-bool VisualScriptInputFilter::has_input_sequence_port() const{
+bool VisualScriptInputFilter::has_input_sequence_port() const {
return true;
}
-int VisualScriptInputFilter::get_input_value_port_count() const{
-
+int VisualScriptInputFilter::get_input_value_port_count() const {
return 1;
}
-int VisualScriptInputFilter::get_output_value_port_count() const{
+int VisualScriptInputFilter::get_output_value_port_count() const {
return 1;
}
@@ -819,60 +756,60 @@ String VisualScriptInputFilter::get_output_sequence_port_text(int p_port) const
String text;
- switch(filters[p_port].type) {
+ switch (filters[p_port].type) {
case InputEvent::NONE: {
- text="None";
+ text = "None";
} break;
case InputEvent::KEY: {
InputEventKey k = filters[p_port].key;
- if (k.scancode==0 && k.unicode==0) {
- text="No Key";
+ if (k.scancode == 0 && k.unicode == 0) {
+ text = "No Key";
} else {
- if (k.scancode!=0) {
- text="KeyCode: "+keycode_get_string(k.scancode);
- } else if (k.unicode!=0) {
- text="Uniode: "+String::chr(k.unicode);
+ if (k.scancode != 0) {
+ text = "KeyCode: " + keycode_get_string(k.scancode);
+ } else if (k.unicode != 0) {
+ text = "Uniode: " + String::chr(k.unicode);
}
if (k.pressed)
- text+=", Pressed";
+ text += ", Pressed";
else
- text+=", Released";
+ text += ", Released";
if (k.echo)
- text+=", Echo";
+ text += ", Echo";
if (k.mod.alt)
- text="Alt+"+text;
+ text = "Alt+" + text;
if (k.mod.shift)
- text="Shift+"+text;
+ text = "Shift+" + text;
if (k.mod.control)
- text="Ctrl+"+text;
+ text = "Ctrl+" + text;
if (k.mod.meta)
- text="Meta+"+text;
+ text = "Meta+" + text;
}
} break;
case InputEvent::MOUSE_MOTION: {
InputEventMouseMotion mm = filters[p_port].mouse_motion;
- text="Mouse Motion";
+ text = "Mouse Motion";
String b = "Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight";
- for(int i=0;i<7;i++) {
- if (mm.button_mask&(1<<i)) {
- text=b.get_slice(",",i)+"+"+text;
+ for (int i = 0; i < 7; i++) {
+ if (mm.button_mask & (1 << i)) {
+ text = b.get_slice(",", i) + "+" + text;
}
}
if (mm.mod.alt)
- text="Alt+"+text;
+ text = "Alt+" + text;
if (mm.mod.shift)
- text="Shift+"+text;
+ text = "Shift+" + text;
if (mm.mod.control)
- text="Ctrl+"+text;
+ text = "Ctrl+" + text;
if (mm.mod.meta)
- text="Meta+"+text;
+ text = "Meta+" + text;
} break;
case InputEvent::MOUSE_BUTTON: {
@@ -880,106 +817,99 @@ String VisualScriptInputFilter::get_output_sequence_port_text(int p_port) const
String b = "Any,Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight";
- text=b.get_slice(",",mb.button_index)+" Mouse Button";
+ text = b.get_slice(",", mb.button_index) + " Mouse Button";
if (mb.pressed)
- text+=", Pressed";
+ text += ", Pressed";
else
- text+=", Released";
+ text += ", Released";
if (mb.doubleclick)
- text+=", DblClick";
+ text += ", DblClick";
if (mb.mod.alt)
- text="Alt+"+text;
+ text = "Alt+" + text;
if (mb.mod.shift)
- text="Shift+"+text;
+ text = "Shift+" + text;
if (mb.mod.control)
- text="Ctrl+"+text;
+ text = "Ctrl+" + text;
if (mb.mod.meta)
- text="Meta+"+text;
-
+ text = "Meta+" + text;
} break;
case InputEvent::JOYPAD_MOTION: {
InputEventJoypadMotion jm = filters[p_port].joy_motion;
- text="JoyMotion Axis "+itos(jm.axis>>1);
- if (jm.axis&1)
- text+=" > "+rtos(jm.axis_value);
+ text = "JoyMotion Axis " + itos(jm.axis >> 1);
+ if (jm.axis & 1)
+ text += " > " + rtos(jm.axis_value);
else
- text+=" < "+rtos(-jm.axis_value);
+ text += " < " + rtos(-jm.axis_value);
} break;
case InputEvent::JOYPAD_BUTTON: {
InputEventJoypadButton jb = filters[p_port].joy_button;
- text="JoyButton "+itos(jb.button_index);
+ text = "JoyButton " + itos(jb.button_index);
if (jb.pressed)
- text+=", Pressed";
+ text += ", Pressed";
else
- text+=", Released";
+ text += ", Released";
} break;
case InputEvent::SCREEN_TOUCH: {
InputEventScreenTouch sd = filters[p_port].screen_touch;
- text="Touch Finger "+itos(sd.index);
+ text = "Touch Finger " + itos(sd.index);
if (sd.pressed)
- text+=", Pressed";
+ text += ", Pressed";
else
- text+=", Released";
+ text += ", Released";
} break;
case InputEvent::SCREEN_DRAG: {
InputEventScreenDrag sd = filters[p_port].screen_drag;
- text="Drag Finger "+itos(sd.index);
+ text = "Drag Finger " + itos(sd.index);
} break;
case InputEvent::ACTION: {
-
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- int index=1;
+ int index = 1;
- text="No Action";
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ text = "No Action";
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
-
- if (filters[p_port].action.action==index) {
- text="Action "+pi.name.substr(pi.name.find("/")+1,pi.name.length());
+ if (filters[p_port].action.action == index) {
+ text = "Action " + pi.name.substr(pi.name.find("/") + 1, pi.name.length());
break;
}
index++;
}
if (filters[p_port].action.pressed)
- text+=", Pressed";
+ text += ", Pressed";
else
- text+=", Released";
-
+ text += ", Released";
} break;
}
-
-
- return text+" - "+itos(p_port);
+ return text + " - " + itos(p_port);
}
-PropertyInfo VisualScriptInputFilter::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptInputFilter::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::INPUT_EVENT,"event");
+ return PropertyInfo(Variant::INPUT_EVENT, "event");
}
-PropertyInfo VisualScriptInputFilter::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptInputFilter::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::INPUT_EVENT,"");
+ return PropertyInfo(Variant::INPUT_EVENT, "");
}
-
String VisualScriptInputFilter::get_caption() const {
return "InputFilter";
@@ -990,94 +920,90 @@ String VisualScriptInputFilter::get_text() const {
return "";
}
+bool VisualScriptInputFilter::_set(const StringName &p_name, const Variant &p_value) {
-
-bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_value) {
-
- if (p_name=="filter_count") {
+ if (p_name == "filter_count") {
filters.resize(p_value);
_change_notify();
ports_changed_notify();
return true;
}
-
if (String(p_name).begins_with("filter_")) {
- int idx = String(p_name).replace_first("filters_","").get_slice("/",0).to_int();
-
- ERR_FAIL_INDEX_V(idx,filters.size(),false);
-
- String what = String(p_name).get_slice("/",1);
-
-
- if (what=="type") {
- filters[idx]=InputEvent();
- filters[idx].type=InputEvent::Type(int(p_value));
- if (filters[idx].type==InputEvent::JOYPAD_MOTION) {
- filters[idx].joy_motion.axis_value=0.5; //for treshold
- } else if (filters[idx].type==InputEvent::KEY) {
- filters[idx].key.pressed=true; //put these as true to make it more user friendly
- } else if (filters[idx].type==InputEvent::MOUSE_BUTTON) {
- filters[idx].mouse_button.pressed=true;
- } else if (filters[idx].type==InputEvent::JOYPAD_BUTTON) {
- filters[idx].joy_button.pressed=true;
- } else if (filters[idx].type==InputEvent::SCREEN_TOUCH) {
- filters[idx].screen_touch.pressed=true;
- } else if (filters[idx].type==InputEvent::ACTION) {
- filters[idx].action.pressed=true;
+ int idx = String(p_name).replace_first("filters_", "").get_slice("/", 0).to_int();
+
+ ERR_FAIL_INDEX_V(idx, filters.size(), false);
+
+ String what = String(p_name).get_slice("/", 1);
+
+ if (what == "type") {
+ filters[idx] = InputEvent();
+ filters[idx].type = InputEvent::Type(int(p_value));
+ if (filters[idx].type == InputEvent::JOYPAD_MOTION) {
+ filters[idx].joy_motion.axis_value = 0.5; //for treshold
+ } else if (filters[idx].type == InputEvent::KEY) {
+ filters[idx].key.pressed = true; //put these as true to make it more user friendly
+ } else if (filters[idx].type == InputEvent::MOUSE_BUTTON) {
+ filters[idx].mouse_button.pressed = true;
+ } else if (filters[idx].type == InputEvent::JOYPAD_BUTTON) {
+ filters[idx].joy_button.pressed = true;
+ } else if (filters[idx].type == InputEvent::SCREEN_TOUCH) {
+ filters[idx].screen_touch.pressed = true;
+ } else if (filters[idx].type == InputEvent::ACTION) {
+ filters[idx].action.pressed = true;
}
_change_notify();
ports_changed_notify();
return true;
}
- if (what=="device") {
- filters[idx].device=p_value;
+ if (what == "device") {
+ filters[idx].device = p_value;
ports_changed_notify();
return true;
}
- switch(filters[idx].type) {
+ switch (filters[idx].type) {
case InputEvent::KEY: {
- if (what=="scancode") {
+ if (what == "scancode") {
String sc = p_value;
- if (sc==String()) {
- filters[idx].key.scancode=0;
+ if (sc == String()) {
+ filters[idx].key.scancode = 0;
} else {
- filters[idx].key.scancode=find_keycode(p_value);
+ filters[idx].key.scancode = find_keycode(p_value);
}
- } else if (what=="unicode") {
+ } else if (what == "unicode") {
String uc = p_value;
- if (uc==String()) {
- filters[idx].key.unicode=0;
+ if (uc == String()) {
+ filters[idx].key.unicode = 0;
} else {
- filters[idx].key.unicode=uc[0];
+ filters[idx].key.unicode = uc[0];
}
- } else if (what=="pressed") {
+ } else if (what == "pressed") {
- filters[idx].key.pressed=p_value;
- } else if (what=="echo") {
+ filters[idx].key.pressed = p_value;
+ } else if (what == "echo") {
- filters[idx].key.echo=p_value;
+ filters[idx].key.echo = p_value;
- } else if (what=="mod_alt") {
- filters[idx].key.mod.alt=p_value;
+ } else if (what == "mod_alt") {
+ filters[idx].key.mod.alt = p_value;
- } else if (what=="mod_shift") {
- filters[idx].key.mod.shift=p_value;
+ } else if (what == "mod_shift") {
+ filters[idx].key.mod.shift = p_value;
- } else if (what=="mod_ctrl") {
- filters[idx].key.mod.control=p_value;
+ } else if (what == "mod_ctrl") {
+ filters[idx].key.mod.control = p_value;
- } else if (what=="mod_meta") {
- filters[idx].key.mod.meta=p_value;
+ } else if (what == "mod_meta") {
+ filters[idx].key.mod.meta = p_value;
} else {
return false;
}
@@ -1087,21 +1013,20 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
} break;
case InputEvent::MOUSE_MOTION: {
+ if (what == "button_mask") {
+ filters[idx].mouse_motion.button_mask = p_value;
- if (what=="button_mask") {
- filters[idx].mouse_motion.button_mask=p_value;
-
- } else if (what=="mod_alt") {
- filters[idx].mouse_motion.mod.alt=p_value;
+ } else if (what == "mod_alt") {
+ filters[idx].mouse_motion.mod.alt = p_value;
- } else if (what=="mod_shift") {
- filters[idx].mouse_motion.mod.shift=p_value;
+ } else if (what == "mod_shift") {
+ filters[idx].mouse_motion.mod.shift = p_value;
- } else if (what=="mod_ctrl") {
- filters[idx].mouse_motion.mod.control=p_value;
+ } else if (what == "mod_ctrl") {
+ filters[idx].mouse_motion.mod.control = p_value;
- } else if (what=="mod_meta") {
- filters[idx].mouse_motion.mod.meta=p_value;
+ } else if (what == "mod_meta") {
+ filters[idx].mouse_motion.mod.meta = p_value;
} else {
return false;
}
@@ -1112,24 +1037,24 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
} break;
case InputEvent::MOUSE_BUTTON: {
- if (what=="button_index") {
- filters[idx].mouse_button.button_index=p_value;
- } else if (what=="pressed") {
- filters[idx].mouse_button.pressed=p_value;
- } else if (what=="doubleclicked") {
- filters[idx].mouse_button.doubleclick=p_value;
+ if (what == "button_index") {
+ filters[idx].mouse_button.button_index = p_value;
+ } else if (what == "pressed") {
+ filters[idx].mouse_button.pressed = p_value;
+ } else if (what == "doubleclicked") {
+ filters[idx].mouse_button.doubleclick = p_value;
- } else if (what=="mod_alt") {
- filters[idx].mouse_button.mod.alt=p_value;
+ } else if (what == "mod_alt") {
+ filters[idx].mouse_button.mod.alt = p_value;
- } else if (what=="mod_shift") {
- filters[idx].mouse_button.mod.shift=p_value;
+ } else if (what == "mod_shift") {
+ filters[idx].mouse_button.mod.shift = p_value;
- } else if (what=="mod_ctrl") {
- filters[idx].mouse_button.mod.control=p_value;
+ } else if (what == "mod_ctrl") {
+ filters[idx].mouse_button.mod.control = p_value;
- } else if (what=="mod_meta") {
- filters[idx].mouse_button.mod.meta=p_value;
+ } else if (what == "mod_meta") {
+ filters[idx].mouse_button.mod.meta = p_value;
} else {
return false;
}
@@ -1139,26 +1064,25 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
} break;
case InputEvent::JOYPAD_MOTION: {
- if (what=="axis") {
- filters[idx].joy_motion.axis=int(p_value)<<1|filters[idx].joy_motion.axis;
- } else if (what=="mode") {
- filters[idx].joy_motion.axis|=int(p_value);
- } else if (what=="treshold") {
- filters[idx].joy_motion.axis_value=p_value;
+ if (what == "axis") {
+ filters[idx].joy_motion.axis = int(p_value) << 1 | filters[idx].joy_motion.axis;
+ } else if (what == "mode") {
+ filters[idx].joy_motion.axis |= int(p_value);
+ } else if (what == "treshold") {
+ filters[idx].joy_motion.axis_value = p_value;
} else {
return false;
}
ports_changed_notify();
return true;
-
} break;
case InputEvent::JOYPAD_BUTTON: {
- if (what=="button_index") {
- filters[idx].joy_button.button_index=p_value;
- } else if (what=="pressed") {
- filters[idx].joy_button.pressed=p_value;
+ if (what == "button_index") {
+ filters[idx].joy_button.button_index = p_value;
+ } else if (what == "pressed") {
+ filters[idx].joy_button.pressed = p_value;
} else {
return false;
}
@@ -1168,10 +1092,10 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
} break;
case InputEvent::SCREEN_TOUCH: {
- if (what=="finger_index") {
- filters[idx].screen_touch.index=p_value;
- } else if (what=="pressed") {
- filters[idx].screen_touch.pressed=p_value;
+ if (what == "finger_index") {
+ filters[idx].screen_touch.index = p_value;
+ } else if (what == "pressed") {
+ filters[idx].screen_touch.pressed = p_value;
} else {
return false;
}
@@ -1179,8 +1103,8 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
return true;
} break;
case InputEvent::SCREEN_DRAG: {
- if (what=="finger_index") {
- filters[idx].screen_drag.index=p_value;
+ if (what == "finger_index") {
+ filters[idx].screen_drag.index = p_value;
} else {
return false;
}
@@ -1189,23 +1113,22 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
} break;
case InputEvent::ACTION: {
-
- if (what=="action_name") {
+ if (what == "action_name") {
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- int index=1;
+ int index = 1;
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
- if (name==String(p_value)) {
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
+ if (name == String(p_value)) {
- filters[idx].action.action=index;
+ filters[idx].action.action = index;
ports_changed_notify();
return true;
}
@@ -1213,92 +1136,87 @@ bool VisualScriptInputFilter::_set(const StringName& p_name, const Variant& p_va
index++;
}
- filters[idx].action.action=0;
+ filters[idx].action.action = 0;
ports_changed_notify();
return false;
- } else if (what=="pressed") {
+ } else if (what == "pressed") {
- filters[idx].action.pressed=p_value;
+ filters[idx].action.pressed = p_value;
ports_changed_notify();
return true;
}
-
} break;
-
}
}
return false;
}
-bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) const{
+bool VisualScriptInputFilter::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name=="filter_count") {
- r_ret=filters.size();
+ if (p_name == "filter_count") {
+ r_ret = filters.size();
return true;
}
-
if (String(p_name).begins_with("filter_")) {
- int idx = String(p_name).replace_first("filters_","").get_slice("/",0).to_int();
-
- ERR_FAIL_INDEX_V(idx,filters.size(),false);
+ int idx = String(p_name).replace_first("filters_", "").get_slice("/", 0).to_int();
- String what = String(p_name).get_slice("/",1);
+ ERR_FAIL_INDEX_V(idx, filters.size(), false);
+ String what = String(p_name).get_slice("/", 1);
- if (what=="type") {
- r_ret=filters[idx].type;
+ if (what == "type") {
+ r_ret = filters[idx].type;
return true;
}
- if (what=="device") {
- r_ret=filters[idx].device;
+ if (what == "device") {
+ r_ret = filters[idx].device;
return true;
}
- switch(filters[idx].type) {
+ switch (filters[idx].type) {
case InputEvent::KEY: {
- if (what=="scancode") {
- if (filters[idx].key.scancode==0)
- r_ret=String();
+ if (what == "scancode") {
+ if (filters[idx].key.scancode == 0)
+ r_ret = String();
else {
- r_ret=keycode_get_string(filters[idx].key.scancode);
+ r_ret = keycode_get_string(filters[idx].key.scancode);
}
- } else if (what=="unicode") {
+ } else if (what == "unicode") {
-
- if (filters[idx].key.unicode==0) {
- r_ret=String();
+ if (filters[idx].key.unicode == 0) {
+ r_ret = String();
} else {
- CharType str[2]={ (CharType)filters[idx].key.unicode, 0};
- r_ret=String(str);
+ CharType str[2] = { (CharType)filters[idx].key.unicode, 0 };
+ r_ret = String(str);
}
- } else if (what=="pressed") {
+ } else if (what == "pressed") {
- r_ret=filters[idx].key.pressed;
- } else if (what=="echo") {
+ r_ret = filters[idx].key.pressed;
+ } else if (what == "echo") {
- r_ret=filters[idx].key.echo;
+ r_ret = filters[idx].key.echo;
- } else if (what=="mod_alt") {
- r_ret=filters[idx].key.mod.alt;
+ } else if (what == "mod_alt") {
+ r_ret = filters[idx].key.mod.alt;
- } else if (what=="mod_shift") {
- r_ret=filters[idx].key.mod.shift;
+ } else if (what == "mod_shift") {
+ r_ret = filters[idx].key.mod.shift;
- } else if (what=="mod_ctrl") {
- r_ret=filters[idx].key.mod.control;
+ } else if (what == "mod_ctrl") {
+ r_ret = filters[idx].key.mod.control;
- } else if (what=="mod_meta") {
- r_ret=filters[idx].key.mod.meta;
+ } else if (what == "mod_meta") {
+ r_ret = filters[idx].key.mod.meta;
} else {
return false;
}
@@ -1307,21 +1225,20 @@ bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) cons
} break;
case InputEvent::MOUSE_MOTION: {
+ if (what == "button_mask") {
+ r_ret = filters[idx].mouse_motion.button_mask;
- if (what=="button_mask") {
- r_ret=filters[idx].mouse_motion.button_mask;
-
- } else if (what=="mod_alt") {
- r_ret=filters[idx].mouse_motion.mod.alt;
+ } else if (what == "mod_alt") {
+ r_ret = filters[idx].mouse_motion.mod.alt;
- } else if (what=="mod_shift") {
- r_ret=filters[idx].mouse_motion.mod.shift;
+ } else if (what == "mod_shift") {
+ r_ret = filters[idx].mouse_motion.mod.shift;
- } else if (what=="mod_ctrl") {
- r_ret=filters[idx].mouse_motion.mod.control;
+ } else if (what == "mod_ctrl") {
+ r_ret = filters[idx].mouse_motion.mod.control;
- } else if (what=="mod_meta") {
- r_ret=filters[idx].mouse_motion.mod.meta;
+ } else if (what == "mod_meta") {
+ r_ret = filters[idx].mouse_motion.mod.meta;
} else {
return false;
}
@@ -1331,24 +1248,24 @@ bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) cons
} break;
case InputEvent::MOUSE_BUTTON: {
- if (what=="button_index") {
- r_ret=filters[idx].mouse_button.button_index;
- } else if (what=="pressed") {
- r_ret=filters[idx].mouse_button.pressed;
- } else if (what=="doubleclicked") {
- r_ret=filters[idx].mouse_button.doubleclick;
+ if (what == "button_index") {
+ r_ret = filters[idx].mouse_button.button_index;
+ } else if (what == "pressed") {
+ r_ret = filters[idx].mouse_button.pressed;
+ } else if (what == "doubleclicked") {
+ r_ret = filters[idx].mouse_button.doubleclick;
- } else if (what=="mod_alt") {
- r_ret=filters[idx].mouse_button.mod.alt;
+ } else if (what == "mod_alt") {
+ r_ret = filters[idx].mouse_button.mod.alt;
- } else if (what=="mod_shift") {
- r_ret=filters[idx].mouse_button.mod.shift;
+ } else if (what == "mod_shift") {
+ r_ret = filters[idx].mouse_button.mod.shift;
- } else if (what=="mod_ctrl") {
- r_ret=filters[idx].mouse_button.mod.control;
+ } else if (what == "mod_ctrl") {
+ r_ret = filters[idx].mouse_button.mod.control;
- } else if (what=="mod_meta") {
- r_ret=filters[idx].mouse_button.mod.meta;
+ } else if (what == "mod_meta") {
+ r_ret = filters[idx].mouse_button.mod.meta;
} else {
return false;
}
@@ -1357,25 +1274,24 @@ bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) cons
} break;
case InputEvent::JOYPAD_MOTION: {
- if (what=="axis_index") {
- r_ret=filters[idx].joy_motion.axis>>1;
- } else if (what=="mode") {
- r_ret=filters[idx].joy_motion.axis&1;
- } else if (what=="treshold") {
- r_ret=filters[idx].joy_motion.axis_value;
+ if (what == "axis_index") {
+ r_ret = filters[idx].joy_motion.axis >> 1;
+ } else if (what == "mode") {
+ r_ret = filters[idx].joy_motion.axis & 1;
+ } else if (what == "treshold") {
+ r_ret = filters[idx].joy_motion.axis_value;
} else {
return false;
}
return true;
-
} break;
case InputEvent::JOYPAD_BUTTON: {
- if (what=="button_index") {
- r_ret=filters[idx].joy_button.button_index;
- } else if (what=="pressed") {
- r_ret=filters[idx].joy_button.pressed;
+ if (what == "button_index") {
+ r_ret = filters[idx].joy_button.button_index;
+ } else if (what == "pressed") {
+ r_ret = filters[idx].joy_button.pressed;
} else {
return false;
}
@@ -1384,18 +1300,18 @@ bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) cons
} break;
case InputEvent::SCREEN_TOUCH: {
- if (what=="finger_index") {
- r_ret=filters[idx].screen_touch.index;
- } else if (what=="pressed") {
- r_ret=filters[idx].screen_touch.pressed;
+ if (what == "finger_index") {
+ r_ret = filters[idx].screen_touch.index;
+ } else if (what == "pressed") {
+ r_ret = filters[idx].screen_touch.pressed;
} else {
return false;
}
return true;
} break;
case InputEvent::SCREEN_DRAG: {
- if (what=="finger_index") {
- r_ret=filters[idx].screen_drag.index;
+ if (what == "finger_index") {
+ r_ret = filters[idx].screen_drag.index;
} else {
return false;
}
@@ -1403,45 +1319,41 @@ bool VisualScriptInputFilter::_get(const StringName& p_name,Variant &r_ret) cons
} break;
case InputEvent::ACTION: {
-
- if (what=="action_name") {
+ if (what == "action_name") {
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
- int index=1;
+ int index = 1;
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
-
- if (filters[idx].action.action==index) {
- r_ret=pi.name.substr(pi.name.find("/")+1,pi.name.length());
+ if (filters[idx].action.action == index) {
+ r_ret = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
return true;
}
index++;
}
- r_ret="None"; //no index
+ r_ret = "None"; //no index
return false;
- } else if (what=="pressed") {
+ } else if (what == "pressed") {
- r_ret=filters[idx].action.pressed;
+ r_ret = filters[idx].action.pressed;
return true;
}
-
} break;
-
}
}
return false;
}
-static const char* event_type_names[InputEvent::TYPE_MAX]={
+static const char *event_type_names[InputEvent::TYPE_MAX] = {
"None",
"Key",
"MouseMotion",
@@ -1453,186 +1365,175 @@ static const char* event_type_names[InputEvent::TYPE_MAX]={
"Action"
};
-void VisualScriptInputFilter::_get_property_list( List<PropertyInfo> *p_list) const {
+void VisualScriptInputFilter::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back(PropertyInfo(Variant::INT,"filter_count",PROPERTY_HINT_RANGE,"0,64"));
+ p_list->push_back(PropertyInfo(Variant::INT, "filter_count", PROPERTY_HINT_RANGE, "0,64"));
String et;
- for(int i=0;i<InputEvent::TYPE_MAX;i++) {
- if (i>0)
- et+=",";
+ for (int i = 0; i < InputEvent::TYPE_MAX; i++) {
+ if (i > 0)
+ et += ",";
- et+=event_type_names[i];
+ et += event_type_names[i];
}
String kc;
String actions;
+ for (int i = 0; i < filters.size(); i++) {
-
- for(int i=0;i<filters.size();i++) {
-
- String base = "filter_"+itos(i)+"/";
- p_list->push_back(PropertyInfo(Variant::INT,base+"type",PROPERTY_HINT_ENUM,et));
- p_list->push_back(PropertyInfo(Variant::INT,base+"device"));
- switch(filters[i].type) {
+ String base = "filter_" + itos(i) + "/";
+ p_list->push_back(PropertyInfo(Variant::INT, base + "type", PROPERTY_HINT_ENUM, et));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "device"));
+ switch (filters[i].type) {
case InputEvent::NONE: {
} break;
case InputEvent::KEY: {
- if (kc==String()) {
+ if (kc == String()) {
int kcc = keycode_get_count();
- kc="None";
- for(int i=0;i<kcc;i++) {
- kc+=",";
- kc+=String(keycode_get_name_by_index(i));
+ kc = "None";
+ for (int i = 0; i < kcc; i++) {
+ kc += ",";
+ kc += String(keycode_get_name_by_index(i));
}
}
- p_list->push_back(PropertyInfo(Variant::STRING,base+"scancode",PROPERTY_HINT_ENUM,kc));
- p_list->push_back(PropertyInfo(Variant::STRING,base+"unicode"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"pressed"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"echo"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_alt"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_shift"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_ctrl"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_meta"));
-
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "scancode", PROPERTY_HINT_ENUM, kc));
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "unicode"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "pressed"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "echo"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_alt"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_shift"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_ctrl"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_meta"));
} break;
case InputEvent::MOUSE_MOTION: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"button_mask",PROPERTY_HINT_FLAGS,"Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_alt"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_shift"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_ctrl"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_meta"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "button_mask", PROPERTY_HINT_FLAGS, "Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_alt"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_shift"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_ctrl"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_meta"));
} break;
case InputEvent::MOUSE_BUTTON: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"button_index",PROPERTY_HINT_ENUM,"Any,Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"pressed"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"doubleclicked"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_alt"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_shift"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_ctrl"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"mod_meta"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "button_index", PROPERTY_HINT_ENUM, "Any,Left,Right,Middle,WheelUp,WheelDown,WheelLeft,WheelRight"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "pressed"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "doubleclicked"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_alt"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_shift"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_ctrl"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "mod_meta"));
} break;
case InputEvent::JOYPAD_MOTION: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"axis_index"));
- p_list->push_back(PropertyInfo(Variant::INT,base+"mode",PROPERTY_HINT_ENUM,"Min,Max"));
- p_list->push_back(PropertyInfo(Variant::REAL,base+"treshold",PROPERTY_HINT_RANGE,"0,1,0.01"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "axis_index"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "mode", PROPERTY_HINT_ENUM, "Min,Max"));
+ p_list->push_back(PropertyInfo(Variant::REAL, base + "treshold", PROPERTY_HINT_RANGE, "0,1,0.01"));
} break;
case InputEvent::JOYPAD_BUTTON: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"button_index"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"pressed"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "button_index"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "pressed"));
} break;
case InputEvent::SCREEN_TOUCH: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"finger_index"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"pressed"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "finger_index"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "pressed"));
} break;
case InputEvent::SCREEN_DRAG: {
- p_list->push_back(PropertyInfo(Variant::INT,base+"finger_index"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "finger_index"));
} break;
case InputEvent::ACTION: {
+ if (actions == String()) {
-
- if (actions==String()) {
-
- actions="None";
+ actions = "None";
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
Vector<String> al;
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
-
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
al.push_back(name);
}
- for(int i=0;i<al.size();i++) {
- actions+=",";
- actions+=al[i];
+ for (int i = 0; i < al.size(); i++) {
+ actions += ",";
+ actions += al[i];
}
}
- p_list->push_back(PropertyInfo(Variant::STRING,base+"action_name",PROPERTY_HINT_ENUM,actions));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"pressed"));
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "action_name", PROPERTY_HINT_ENUM, actions));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "pressed"));
} break;
-
}
}
}
class VisualScriptNodeInstanceInputFilter : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
Vector<InputEvent> filters;
//virtual int get_working_memory_size() const { return 0; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_inputs[0]->get_type()!=Variant::INPUT_EVENT) {
- r_error_str="Input value not of type event";
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ if (p_inputs[0]->get_type() != Variant::INPUT_EVENT) {
+ r_error_str = "Input value not of type event";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
InputEvent event = *p_inputs[0];
-
- for(int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
const InputEvent &ie = filters[i];
- if (ie.type!=event.type)
+ if (ie.type != event.type)
continue;
- bool match=false;
+ bool match = false;
- switch(ie.type) {
+ switch (ie.type) {
case InputEvent::NONE: {
- match=true;
+ match = true;
} break;
case InputEvent::KEY: {
InputEventKey k = ie.key;
InputEventKey k2 = event.key;
- if (k.scancode==0 && k.unicode==0 && k2.scancode==0 && k2.unicode==0) {
- match=true;
+ if (k.scancode == 0 && k.unicode == 0 && k2.scancode == 0 && k2.unicode == 0) {
+ match = true;
} else {
- if ( (k.scancode!=0 && k.scancode==k2.scancode) || (k.unicode!=0 && k.unicode==k2.unicode)) {
+ if ((k.scancode != 0 && k.scancode == k2.scancode) || (k.unicode != 0 && k.unicode == k2.unicode)) {
//key valid
if (
- k.pressed==k2.pressed &&
- k.echo==k2.echo &&
- k.mod == k2.mod
- ) {
- match=true;
+ k.pressed == k2.pressed &&
+ k.echo == k2.echo &&
+ k.mod == k2.mod) {
+ match = true;
}
}
-
}
} break;
@@ -1640,10 +1541,9 @@ public:
InputEventMouseMotion mm = ie.mouse_motion;
InputEventMouseMotion mm2 = event.mouse_motion;
- if ( mm.button_mask==mm2.button_mask &&
- mm.mod==mm2.mod
- ) {
- match=true;
+ if (mm.button_mask == mm2.button_mask &&
+ mm.mod == mm2.mod) {
+ match = true;
}
} break;
@@ -1652,56 +1552,53 @@ public:
InputEventMouseButton mb = ie.mouse_button;
InputEventMouseButton mb2 = event.mouse_button;
- if ( mb.button_index==mb2.button_index &&
- mb.pressed==mb2.pressed &&
- mb.doubleclick==mb2.doubleclick &&
- mb.mod==mb2.mod) {
- match=true;
+ if (mb.button_index == mb2.button_index &&
+ mb.pressed == mb2.pressed &&
+ mb.doubleclick == mb2.doubleclick &&
+ mb.mod == mb2.mod) {
+ match = true;
}
-
} break;
case InputEvent::JOYPAD_MOTION: {
InputEventJoypadMotion jm = ie.joy_motion;
InputEventJoypadMotion jm2 = event.joy_motion;
- int axis = jm.axis>>1;
+ int axis = jm.axis >> 1;
- if (axis==jm2.axis) {
+ if (axis == jm2.axis) {
- if (jm.axis&1) {
+ if (jm.axis & 1) {
//greater
if (jm2.axis_value > jm.axis_value) {
- match=true;
+ match = true;
}
} else {
//less
if (jm2.axis_value < -jm.axis_value) {
- match=true;
+ match = true;
}
}
}
-
} break;
case InputEvent::JOYPAD_BUTTON: {
InputEventJoypadButton jb = ie.joy_button;
InputEventJoypadButton jb2 = event.joy_button;
- if ( jb.button_index==jb2.button_index &&
- jb.pressed == jb2.pressed
- ) {
- match=true;
+ if (jb.button_index == jb2.button_index &&
+ jb.pressed == jb2.pressed) {
+ match = true;
}
} break;
case InputEvent::SCREEN_TOUCH: {
InputEventScreenTouch st = ie.screen_touch;
InputEventScreenTouch st2 = event.screen_touch;
- if ( st.index==st2.index &&
- st.pressed==st2.pressed) {
- match=true;
+ if (st.index == st2.index &&
+ st.pressed == st2.pressed) {
+ match = true;
}
} break;
@@ -1709,8 +1606,8 @@ public:
InputEventScreenDrag sd = ie.screen_drag;
InputEventScreenDrag sd2 = event.screen_drag;
- if (sd.index==sd2.index) {
- match=true;
+ if (sd.index == sd2.index) {
+ match = true;
}
} break;
case InputEvent::ACTION: {
@@ -1718,88 +1615,72 @@ public:
InputEventAction ia = ie.action;
InputEventAction ia2 = event.action;
- if ( ia.action==ia2.action &&
- ia.pressed==ia2.pressed) {
- match=true;
+ if (ia.action == ia2.action &&
+ ia.pressed == ia2.pressed) {
+ match = true;
}
} break;
-
}
*p_outputs[0] = event;
if (match)
return i; //go through match output
-
}
return STEP_NO_ADVANCE_BIT; //none found, don't advance
-
-
}
-
-
};
+VisualScriptNodeInstance *VisualScriptInputFilter::instance(VisualScriptInstance *p_instance) {
-VisualScriptNodeInstance* VisualScriptInputFilter::instance(VisualScriptInstance* p_instance) {
-
- VisualScriptNodeInstanceInputFilter * instance = memnew(VisualScriptNodeInstanceInputFilter );
- instance->instance=p_instance;
- instance->filters=filters;
+ VisualScriptNodeInstanceInputFilter *instance = memnew(VisualScriptNodeInstanceInputFilter);
+ instance->instance = p_instance;
+ instance->filters = filters;
return instance;
}
-
-
-
VisualScriptInputFilter::VisualScriptInputFilter() {
-
-
}
-
//////////////////////////////////////////
////////////////TYPE CAST///////////
//////////////////////////////////////////
-
int VisualScriptTypeCast::get_output_sequence_port_count() const {
return 2;
}
-bool VisualScriptTypeCast::has_input_sequence_port() const{
+bool VisualScriptTypeCast::has_input_sequence_port() const {
return true;
}
-int VisualScriptTypeCast::get_input_value_port_count() const{
-
+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";
+ return p_port == 0 ? "yes" : "no";
}
-PropertyInfo VisualScriptTypeCast::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptTypeCast::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"instance");
+ return PropertyInfo(Variant::OBJECT, "instance");
}
-PropertyInfo VisualScriptTypeCast::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptTypeCast::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"");
+ return PropertyInfo(Variant::OBJECT, "");
}
-
String VisualScriptTypeCast::get_caption() const {
return "TypeCast";
@@ -1807,47 +1688,44 @@ String VisualScriptTypeCast::get_caption() const {
String VisualScriptTypeCast::get_text() const {
- if (script!=String())
- return "Is "+script.get_file()+"?";
+ if (script != String())
+ return "Is " + script.get_file() + "?";
else
- return "Is "+base_type+"?";
+ return "Is " + base_type + "?";
}
-void VisualScriptTypeCast::set_base_type(const StringName& p_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;
+ base_type = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptTypeCast::get_base_type() const{
+StringName VisualScriptTypeCast::get_base_type() const {
return base_type;
}
-void VisualScriptTypeCast::set_base_script(const String& p_path){
+void VisualScriptTypeCast::set_base_script(const String &p_path) {
- if (script==p_path)
+ if (script == p_path)
return;
- script=p_path;
+ script = p_path;
_change_notify();
ports_changed_notify();
-
}
-String VisualScriptTypeCast::get_base_script() const{
+String VisualScriptTypeCast::get_base_script() const {
return script;
}
-
class VisualScriptNodeInstanceTypeCast : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
StringName base_type;
String script;
@@ -1855,19 +1733,19 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
Object *obj = *p_inputs[0];
- *p_outputs[0]=Variant();
+ *p_outputs[0] = Variant();
if (!obj) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Instance is null";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Instance is null";
return 0;
}
- if (script!=String()) {
+ if (script != String()) {
Ref<Script> obj_script = obj->get_script();
if (!obj_script.is_valid()) {
@@ -1880,90 +1758,79 @@ public:
}
Ref<Script> cast_script = Ref<Resource>(ResourceCache::get(script));
if (!cast_script.is_valid()) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Script path is not a script: "+script;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Script path is not a script: " + script;
return 1;
}
- while(obj_script.is_valid()) {
+ while (obj_script.is_valid()) {
- if (cast_script==obj_script) {
- *p_outputs[0]=*p_inputs[0]; //copy
+ if (cast_script == obj_script) {
+ *p_outputs[0] = *p_inputs[0]; //copy
return 0; // it is the script, yey
}
- obj_script=obj_script->get_base_script();
+ obj_script = obj_script->get_base_script();
}
return 1; //not found sorry
}
- if (ClassDB::is_parent_class(obj->get_class_name(),base_type)) {
- *p_outputs[0]=*p_inputs[0]; //copy
+ if (ClassDB::is_parent_class(obj->get_class_name(), base_type)) {
+ *p_outputs[0] = *p_inputs[0]; //copy
return 0;
} else
return 1;
-
}
-
-
};
-VisualScriptNodeInstance* VisualScriptTypeCast::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptTypeCast::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceTypeCast * instance = memnew(VisualScriptNodeInstanceTypeCast );
- instance->instance=p_instance;
- instance->base_type=base_type;
- instance->script=script;
+ VisualScriptNodeInstanceTypeCast *instance = memnew(VisualScriptNodeInstanceTypeCast);
+ instance->instance = p_instance;
+ instance->base_type = base_type;
+ instance->script = script;
return instance;
}
-
-
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);
-
- ClassDB::bind_method(D_METHOD("set_base_script","path"),&VisualScriptTypeCast::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"),&VisualScriptTypeCast::get_base_script);
+ 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);
+ ClassDB::bind_method(D_METHOD("set_base_script", "path"), &VisualScriptTypeCast::set_base_script);
+ ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptTypeCast::get_base_script);
List<String> script_extensions;
- for(int i=0;i>ScriptServer::get_language_count();i++) {
+ for (int i = 0; i > ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
}
String script_ext_hint;
- for (List<String>::Element *E=script_extensions.front();E;E=E->next()) {
- if (script_ext_hint!=String())
- script_ext_hint+=",";
- script_ext_hint+="*."+E->get();
+ for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
+ if (script_ext_hint != String())
+ script_ext_hint += ",";
+ script_ext_hint += "*." + E->get();
}
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"function/base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/base_script",PROPERTY_HINT_FILE,script_ext_hint),"set_base_script","get_base_script");
-
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "function/base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
}
VisualScriptTypeCast::VisualScriptTypeCast() {
- base_type="Object";
+ 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>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/while",create_node_generic<VisualScriptWhile>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/iterator",create_node_generic<VisualScriptIterator>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/sequence",create_node_generic<VisualScriptSequence>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/switch",create_node_generic<VisualScriptSwitch>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/input_filter",create_node_generic<VisualScriptInputFilter>);
- VisualScriptLanguage::singleton->add_register_func("flow_control/type_cast",create_node_generic<VisualScriptTypeCast>);
-
-
-
+ 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>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/while", create_node_generic<VisualScriptWhile>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/iterator", create_node_generic<VisualScriptIterator>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/sequence", create_node_generic<VisualScriptSequence>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/switch", create_node_generic<VisualScriptSwitch>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/input_filter", create_node_generic<VisualScriptInputFilter>);
+ VisualScriptLanguage::singleton->add_register_func("flow_control/type_cast", create_node_generic<VisualScriptTypeCast>);
}
diff --git a/modules/visual_script/visual_script_flow_control.h b/modules/visual_script/visual_script_flow_control.h
index 8406bb5a5b..1739f67b5b 100644
--- a/modules/visual_script/visual_script_flow_control.h
+++ b/modules/visual_script/visual_script_flow_control.h
@@ -33,27 +33,23 @@
class VisualScriptReturn : public VisualScriptNode {
- GDCLASS(VisualScriptReturn,VisualScriptNode)
-
+ GDCLASS(VisualScriptReturn, VisualScriptNode)
Variant::Type type;
bool with_value;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -67,35 +63,27 @@ 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);
VisualScriptReturn();
};
-
class VisualScriptCondition : public VisualScriptNode {
- GDCLASS(VisualScriptCondition,VisualScriptNode)
-
-
+ GDCLASS(VisualScriptCondition, VisualScriptNode)
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -103,35 +91,27 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
-
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptCondition();
};
-
class VisualScriptWhile : public VisualScriptNode {
- GDCLASS(VisualScriptWhile,VisualScriptNode)
-
-
+ GDCLASS(VisualScriptWhile, VisualScriptNode)
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -139,36 +119,27 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
-
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptWhile();
};
-
-
class VisualScriptIterator : public VisualScriptNode {
- GDCLASS(VisualScriptIterator,VisualScriptNode)
-
-
+ GDCLASS(VisualScriptIterator, VisualScriptNode)
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -176,37 +147,29 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
-
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptIterator();
};
-
-
class VisualScriptSequence : public VisualScriptNode {
- GDCLASS(VisualScriptSequence,VisualScriptNode)
-
+ GDCLASS(VisualScriptSequence, VisualScriptNode)
int steps;
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -217,47 +180,41 @@ public:
void set_steps(int p_steps);
int get_steps() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptSequence();
};
-
-
-
class VisualScriptSwitch : public VisualScriptNode {
- GDCLASS(VisualScriptSwitch,VisualScriptNode)
+ GDCLASS(VisualScriptSwitch, VisualScriptNode)
struct Case {
Variant::Type type;
- Case() { type=Variant::NIL; }
+ Case() { type = Variant::NIL; }
};
Vector<Case> case_values;
-friend class VisualScriptNodeInstanceSwitch;
-protected:
+ friend class VisualScriptNodeInstanceSwitch;
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
virtual bool has_mixed_input_and_sequence_ports() const { return true; }
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -265,40 +222,31 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptSwitch();
};
-
-
-
class VisualScriptInputFilter : public VisualScriptNode {
- GDCLASS(VisualScriptInputFilter,VisualScriptNode)
+ GDCLASS(VisualScriptInputFilter, VisualScriptNode)
Vector<InputEvent> filters;
-
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ 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 String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -306,40 +254,30 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptInputFilter();
};
-
-
-
-
class VisualScriptTypeCast : public VisualScriptNode {
- GDCLASS(VisualScriptTypeCast,VisualScriptNode)
-
+ GDCLASS(VisualScriptTypeCast, VisualScriptNode)
StringName base_type;
String script;
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -347,23 +285,17 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
- void set_base_type(const StringName& p_type);
+ void set_base_type(const StringName &p_type);
StringName get_base_type() const;
- void set_base_script(const String& p_path);
+ void set_base_script(const String &p_path);
String get_base_script() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptTypeCast();
};
-
-
-
void register_visual_script_flow_control_nodes();
-
-
#endif // VISUAL_SCRIPT_FLOW_CONTROL_H
diff --git a/modules/visual_script/visual_script_func_nodes.cpp b/modules/visual_script/visual_script_func_nodes.cpp
index c9ed49ee5c..3cd20050ce 100644
--- a/modules/visual_script/visual_script_func_nodes.cpp
+++ b/modules/visual_script/visual_script_func_nodes.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "visual_script_func_nodes.h"
-#include "scene/main/scene_main_loop.h"
+#include "global_config.h"
+#include "io/resource_loader.h"
#include "os/os.h"
#include "scene/main/node.h"
+#include "scene/main/scene_main_loop.h"
#include "visual_script_nodes.h"
-#include "io/resource_loader.h"
-#include "global_config.h"
//////////////////////////////////////////
////////////////CALL//////////////////////
@@ -41,33 +41,33 @@
int VisualScriptFunctionCall::get_output_sequence_port_count() const {
- if (method_cache.flags&METHOD_FLAG_CONST || call_mode==CALL_MODE_BASIC_TYPE)
+ if (method_cache.flags & METHOD_FLAG_CONST || call_mode == CALL_MODE_BASIC_TYPE)
return 0;
else
return 1;
}
-bool VisualScriptFunctionCall::has_input_sequence_port() const{
+bool VisualScriptFunctionCall::has_input_sequence_port() const {
- if (method_cache.flags&METHOD_FLAG_CONST || call_mode==CALL_MODE_BASIC_TYPE)
+ if (method_cache.flags & METHOD_FLAG_CONST || call_mode == CALL_MODE_BASIC_TYPE)
return false;
else
return true;
}
#ifdef TOOLS_ENABLED
-static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const Ref<Script> &script) {
+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 NULL;
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);
+ 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)
return n;
}
@@ -83,7 +83,7 @@ Node *VisualScriptFunctionCall::_get_base_node() const {
if (!script.is_valid())
return NULL;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return NULL;
@@ -97,7 +97,7 @@ Node *VisualScriptFunctionCall::_get_base_node() const {
if (!edited_scene)
return NULL;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return NULL;
@@ -116,55 +116,51 @@ 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)
return path->get_class();
-
}
return base_type;
}
+int VisualScriptFunctionCall::get_input_value_port_count() const {
-int VisualScriptFunctionCall::get_input_value_port_count() const{
-
- if (call_mode==CALL_MODE_BASIC_TYPE) {
-
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- Vector<StringName> names = Variant::get_method_argument_names(basic_type,function);
- return names.size() + (rpc_call_mode>=RPC_RELIABLE_TO_ID?1:0) + 1;
+ Vector<StringName> names = Variant::get_method_argument_names(basic_type, function);
+ return names.size() + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) + 1;
} else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
+ MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
- return mb->get_argument_count() + (call_mode==CALL_MODE_INSTANCE?1:0) + (rpc_call_mode>=RPC_RELIABLE_TO_ID?1:0) - use_default_args;
+ return mb->get_argument_count() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - use_default_args;
}
- return method_cache.arguments.size() + (call_mode==CALL_MODE_INSTANCE?1:0) + (rpc_call_mode>=RPC_RELIABLE_TO_ID?1:0) - use_default_args;
+ return method_cache.arguments.size() + (call_mode == CALL_MODE_INSTANCE ? 1 : 0) + (rpc_call_mode >= RPC_RELIABLE_TO_ID ? 1 : 0) - use_default_args;
}
-
}
-int VisualScriptFunctionCall::get_output_value_port_count() const{
+int VisualScriptFunctionCall::get_output_value_port_count() const {
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- bool returns=false;
- Variant::get_method_return_type(basic_type,function,&returns);
- return returns?1:0;
+ bool returns = false;
+ Variant::get_method_return_type(basic_type, function, &returns);
+ return returns ? 1 : 0;
} else {
int ret;
- MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
+ MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
ret = mb->has_return() ? 1 : 0;
} else
ret = 1; //it is assumed that script always returns something
- if (call_mode==CALL_MODE_INSTANCE) {
+ if (call_mode == CALL_MODE_INSTANCE) {
ret++;
}
@@ -177,46 +173,44 @@ String VisualScriptFunctionCall::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) const{
+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) {
+ if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
+ if (p_idx == 0) {
PropertyInfo pi;
- pi.type=(call_mode==CALL_MODE_INSTANCE?Variant::OBJECT:basic_type);
- pi.name=(call_mode==CALL_MODE_INSTANCE?String("instance"):Variant::get_type_name(basic_type).to_lower());
+ pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
+ pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
return pi;
} else {
p_idx--;
}
}
- if (rpc_call_mode>=RPC_RELIABLE_TO_ID) {
+ if (rpc_call_mode >= RPC_RELIABLE_TO_ID) {
- if (p_idx==0) {
- return PropertyInfo(Variant::INT,"peer_id");
+ if (p_idx == 0) {
+ return PropertyInfo(Variant::INT, "peer_id");
} else {
p_idx--;
}
-
}
#ifdef DEBUG_METHODS_ENABLED
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ 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]);
+ 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]);
} else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
+ MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
return mb->get_argument_info(p_idx);
}
- if (p_idx>=0 && p_idx < method_cache.arguments.size()) {
+ if (p_idx >= 0 && p_idx < method_cache.arguments.size()) {
return method_cache.arguments[p_idx];
}
@@ -225,23 +219,20 @@ PropertyInfo VisualScriptFunctionCall::get_input_value_port_info(int p_idx) cons
#else
return PropertyInfo();
#endif
-
}
-PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) const{
-
+PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) const {
#ifdef DEBUG_METHODS_ENABLED
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
-
- return PropertyInfo(Variant::get_method_return_type(basic_type,function),"");
+ return PropertyInfo(Variant::get_method_return_type(basic_type, function), "");
} else {
- if (call_mode==CALL_MODE_INSTANCE) {
- if (p_idx==0) {
- return PropertyInfo(Variant::OBJECT,"pass");
+ if (call_mode == CALL_MODE_INSTANCE) {
+ if (p_idx == 0) {
+ return PropertyInfo(Variant::OBJECT, "pass");
} else {
p_idx--;
}
@@ -259,24 +250,21 @@ PropertyInfo VisualScriptFunctionCall::get_output_value_port_info(int p_idx) con
//}
- if (call_mode==CALL_MODE_INSTANCE) {
- ret.name="return";
+ if (call_mode == CALL_MODE_INSTANCE) {
+ ret.name = "return";
} else {
- ret.name="";
+ ret.name = "";
}
return ret;
-
-
}
#else
return PropertyInfo();
#endif
}
-
String VisualScriptFunctionCall::get_caption() const {
- static const char*cname[5]= {
+ static const char *cname[5] = {
"CallSelf",
"CallNode",
"CallInstance",
@@ -287,7 +275,7 @@ String VisualScriptFunctionCall::get_caption() const {
String caption = cname[call_mode];
if (rpc_call_mode) {
- caption+=" (RPC)";
+ caption += " (RPC)";
}
return caption;
@@ -295,57 +283,54 @@ String VisualScriptFunctionCall::get_caption() const {
String VisualScriptFunctionCall::get_text() const {
- if (call_mode==CALL_MODE_SELF)
- return " "+String(function)+"()";
- if (call_mode==CALL_MODE_SINGLETON)
- return String(singleton)+":"+String(function)+"()";
- 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)
- return " ["+String(base_path.simplified())+"]."+String(function)+"()";
+ if (call_mode == CALL_MODE_SELF)
+ return " " + String(function) + "()";
+ if (call_mode == CALL_MODE_SINGLETON)
+ return String(singleton) + ":" + String(function) + "()";
+ 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)
+ return " [" + String(base_path.simplified()) + "]." + String(function) + "()";
else
- return " "+base_type+"."+String(function)+"()";
-
+ return " " + base_type + "." + String(function) + "()";
}
-
void VisualScriptFunctionCall::set_basic_type(Variant::Type p_type) {
- if (basic_type==p_type)
+ if (basic_type == p_type)
return;
- basic_type=p_type;
-
+ basic_type = p_type;
_change_notify();
ports_changed_notify();
}
-Variant::Type VisualScriptFunctionCall::get_basic_type() const{
+Variant::Type VisualScriptFunctionCall::get_basic_type() const {
return basic_type;
}
-void VisualScriptFunctionCall::set_base_type(const StringName& p_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;
+ base_type = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptFunctionCall::get_base_type() const{
+StringName VisualScriptFunctionCall::get_base_type() const {
return base_type;
}
-void VisualScriptFunctionCall::set_base_script(const String& p_path) {
+void VisualScriptFunctionCall::set_base_script(const String &p_path) {
- if (base_script==p_path)
+ if (base_script == p_path)
return;
- base_script=p_path;
+ base_script = p_path;
_change_notify();
ports_changed_notify();
}
@@ -355,15 +340,15 @@ String VisualScriptFunctionCall::get_base_script() const {
return base_script;
}
-void VisualScriptFunctionCall::set_singleton(const StringName& p_path) {
+void VisualScriptFunctionCall::set_singleton(const StringName &p_path) {
- if (singleton==p_path)
+ if (singleton == p_path)
return;
- singleton=p_path;
+ singleton = p_path;
Object *obj = GlobalConfig::get_singleton()->get_singleton_object(singleton);
if (obj) {
- base_type=obj->get_class();
+ base_type = obj->get_class();
}
_change_notify();
@@ -375,40 +360,38 @@ StringName VisualScriptFunctionCall::get_singleton() const {
return singleton;
}
-
-
void VisualScriptFunctionCall::_update_method_cache() {
StringName type;
Ref<Script> script;
- if (call_mode==CALL_MODE_NODE_PATH) {
+ if (call_mode == CALL_MODE_NODE_PATH) {
- Node* node=_get_base_node();
+ Node *node = _get_base_node();
if (node) {
- type=node->get_class();
- base_type=type; //cache, too
+ type = node->get_class();
+ base_type = type; //cache, too
script = node->get_script();
}
- } else if (call_mode==CALL_MODE_SELF) {
+ } 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();
+ type = get_visual_script()->get_instance_base_type();
+ base_type = type; //cache, too
+ script = get_visual_script();
}
- } else if (call_mode==CALL_MODE_SINGLETON) {
+ } else if (call_mode == CALL_MODE_SINGLETON) {
Object *obj = GlobalConfig::get_singleton()->get_singleton_object(singleton);
if (obj) {
- type=obj->get_class();
- script=obj->get_script();
+ type = obj->get_class();
+ script = obj->get_script();
}
- } else if (call_mode==CALL_MODE_INSTANCE) {
+ } else if (call_mode == CALL_MODE_INSTANCE) {
- type=base_type;
- if (base_script!=String()) {
+ type = base_type;
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
@@ -417,20 +400,19 @@ void VisualScriptFunctionCall::_update_method_cache() {
if (ResourceCache::has(base_script)) {
- script = Ref<Resource>( ResourceCache::get(base_script) );
+ script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
}
}
}
-
//print_line("BASE: "+String(type)+" FUNC: "+String(function));
- MethodBind *mb = ClassDB::get_method(type,function);
+ MethodBind *mb = ClassDB::get_method(type, function);
if (mb) {
- use_default_args=mb->get_default_argument_count();
+ use_default_args = mb->get_default_argument_count();
method_cache = MethodInfo();
- for(int i=0;i<mb->get_argument_count();i++) {
+ for (int i = 0; i < mb->get_argument_count(); i++) {
#ifdef DEBUG_METHODS_ENABLED
method_cache.arguments.push_back(mb->get_argument_info(i));
#else
@@ -439,7 +421,7 @@ void VisualScriptFunctionCall::_update_method_cache() {
}
if (mb->is_const()) {
- method_cache.flags|=METHOD_FLAG_CONST;
+ method_cache.flags |= METHOD_FLAG_CONST;
}
#ifdef DEBUG_METHODS_ENABLED
@@ -449,50 +431,47 @@ void VisualScriptFunctionCall::_update_method_cache() {
if (mb->is_vararg()) {
//for vararg just give it 10 arguments (should be enough for most use cases)
- for(int i=0;i<10;i++) {
- method_cache.arguments.push_back(PropertyInfo(Variant::NIL,"arg"+itos(i)));
+ for (int i = 0; i < 10; i++) {
+ method_cache.arguments.push_back(PropertyInfo(Variant::NIL, "arg" + itos(i)));
use_default_args++;
}
}
} else if (script.is_valid() && script->has_method(function)) {
method_cache = script->get_method_info(function);
- use_default_args=method_cache.default_arguments.size();
+ use_default_args = method_cache.default_arguments.size();
}
}
-void VisualScriptFunctionCall::set_function(const StringName& p_type){
+void VisualScriptFunctionCall::set_function(const StringName &p_type) {
- if (function==p_type)
+ if (function == p_type)
return;
- function=p_type;
+ function = p_type;
- if (call_mode==CALL_MODE_BASIC_TYPE) {
- use_default_args = Variant::get_method_default_arguments(basic_type,function).size();
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
+ use_default_args = Variant::get_method_default_arguments(basic_type, function).size();
} else {
//update all caches
_update_method_cache();
-
}
-
_change_notify();
ports_changed_notify();
}
StringName VisualScriptFunctionCall::get_function() const {
-
return function;
}
-void VisualScriptFunctionCall::set_base_path(const NodePath& p_type) {
+void VisualScriptFunctionCall::set_base_path(const NodePath &p_type) {
- if (base_path==p_type)
+ if (base_path == p_type)
return;
- base_path=p_type;
+ base_path = p_type;
_change_notify();
ports_changed_notify();
}
@@ -502,16 +481,14 @@ 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;
+ call_mode = p_mode;
_change_notify();
ports_changed_notify();
-
}
VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() const {
@@ -520,39 +497,35 @@ VisualScriptFunctionCall::CallMode VisualScriptFunctionCall::get_call_mode() con
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;
+ 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;
+ rpc_call_mode = p_mode;
ports_changed_notify();
_change_notify();
}
-VisualScriptFunctionCall::RPCCallMode VisualScriptFunctionCall::get_rpc_call_mode() const{
+VisualScriptFunctionCall::RPCCallMode VisualScriptFunctionCall::get_rpc_call_mode() const {
return rpc_call_mode;
}
-
-int VisualScriptFunctionCall::get_use_default_args() const{
+int VisualScriptFunctionCall::get_use_default_args() const {
return use_default_args;
}
-
void VisualScriptFunctionCall::set_validate(bool p_amount) {
- validate=p_amount;
+ validate = p_amount;
}
bool VisualScriptFunctionCall::get_validate() const {
@@ -560,11 +533,9 @@ bool VisualScriptFunctionCall::get_validate() const {
return validate;
}
-
-void VisualScriptFunctionCall::_set_argument_cache(const Dictionary& p_cache) {
+void VisualScriptFunctionCall::_set_argument_cache(const Dictionary &p_cache) {
//so everything works in case all else fails
- method_cache=MethodInfo::from_dict(p_cache);
-
+ method_cache = MethodInfo::from_dict(p_cache);
}
Dictionary VisualScriptFunctionCall::_get_argument_cache() const {
@@ -572,84 +543,82 @@ Dictionary VisualScriptFunctionCall::_get_argument_cache() const {
return method_cache;
}
-void VisualScriptFunctionCall::_validate_property(PropertyInfo& property) const {
+void VisualScriptFunctionCall::_validate_property(PropertyInfo &property) const {
- if (property.name=="function/base_type") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "function/base_type") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
- if (property.name=="function/base_script") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=0;
+ if (property.name == "function/base_script") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = 0;
}
}
- if (property.name=="function/basic_type") {
- if (call_mode!=CALL_MODE_BASIC_TYPE) {
- property.usage=0;
+ if (property.name == "function/basic_type") {
+ if (call_mode != CALL_MODE_BASIC_TYPE) {
+ property.usage = 0;
}
}
- if (property.name=="function/singleton") {
- if (call_mode!=CALL_MODE_SINGLETON) {
- property.usage=0;
+ if (property.name == "function/singleton") {
+ if (call_mode != CALL_MODE_SINGLETON) {
+ property.usage = 0;
} else {
List<GlobalConfig::Singleton> names;
GlobalConfig::get_singleton()->get_singletons(&names);
- property.hint=PROPERTY_HINT_ENUM;
+ property.hint = PROPERTY_HINT_ENUM;
String sl;
- for (List<GlobalConfig::Singleton>::Element *E=names.front();E;E=E->next()) {
- if (sl!=String())
- sl+=",";
- sl+=E->get().name;
+ for (List<GlobalConfig::Singleton>::Element *E = names.front(); E; E = E->next()) {
+ if (sl != String())
+ sl += ",";
+ sl += E->get().name;
}
- property.hint_string=sl;
-
+ property.hint_string = sl;
}
}
- if (property.name=="function/node_path") {
- if (call_mode!=CALL_MODE_NODE_PATH) {
- property.usage=0;
+ if (property.name == "function/node_path") {
+ 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
+ property.hint_string = bnode->get_path(); //convert to loong string
} else {
-
}
}
}
- if (property.name=="function/function") {
+ if (property.name == "function/function") {
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint=PROPERTY_HINT_METHOD_OF_VARIANT_TYPE;
- property.hint_string=Variant::get_type_name(basic_type);
+ property.hint = PROPERTY_HINT_METHOD_OF_VARIANT_TYPE;
+ property.hint_string = Variant::get_type_name(basic_type);
- } else if (call_mode==CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint=PROPERTY_HINT_METHOD_OF_SCRIPT;
- property.hint_string=itos(get_visual_script()->get_instance_ID());
- } else if (call_mode==CALL_MODE_SINGLETON) {
+ } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
+ 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 = GlobalConfig::get_singleton()->get_singleton_object(singleton);
if (obj) {
- property.hint=PROPERTY_HINT_METHOD_OF_INSTANCE;
- property.hint_string=itos(obj->get_instance_ID());
+ 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
+ property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
+ property.hint_string = base_type; //should be cached
}
- } else if (call_mode==CALL_MODE_INSTANCE) {
- property.hint=PROPERTY_HINT_METHOD_OF_BASE_TYPE;
- property.hint_string=base_type;
+ } else if (call_mode == CALL_MODE_INSTANCE) {
+ property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
+ property.hint_string = base_type;
- if (base_script!=String()) {
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
ScriptServer::edit_request_func(base_script); //make sure it's loaded
@@ -657,143 +626,134 @@ void VisualScriptFunctionCall::_validate_property(PropertyInfo& property) const
if (ResourceCache::has(base_script)) {
- Ref<Script> script = Ref<Resource>( ResourceCache::get(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());
+ property.hint = PROPERTY_HINT_METHOD_OF_SCRIPT;
+ property.hint_string = itos(script->get_instance_ID());
}
}
}
- } else if (call_mode==CALL_MODE_NODE_PATH) {
+ } else if (call_mode == CALL_MODE_NODE_PATH) {
Node *node = _get_base_node();
if (node) {
- property.hint=PROPERTY_HINT_METHOD_OF_INSTANCE;
- property.hint_string=itos(node->get_instance_ID());
+ property.hint = PROPERTY_HINT_METHOD_OF_INSTANCE;
+ property.hint_string = itos(node->get_instance_ID());
} else {
- property.hint=PROPERTY_HINT_METHOD_OF_BASE_TYPE;
- property.hint_string=get_base_type();
+ property.hint = PROPERTY_HINT_METHOD_OF_BASE_TYPE;
+ property.hint_string = get_base_type();
}
-
}
-
}
- if (property.name=="function/use_default_args") {
+ if (property.name == "function/use_default_args") {
- property.hint=PROPERTY_HINT_RANGE;
+ property.hint = PROPERTY_HINT_RANGE;
- int mc=0;
+ int mc = 0;
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- mc = Variant::get_method_default_arguments(basic_type,function).size();
+ mc = Variant::get_method_default_arguments(basic_type, function).size();
} else {
- MethodBind *mb = ClassDB::get_method(_get_base_type(),function);
+ MethodBind *mb = ClassDB::get_method(_get_base_type(), function);
if (mb) {
- mc=mb->get_default_argument_count();
+ mc = mb->get_default_argument_count();
}
}
- if (mc==0) {
- property.usage=0; //do not show
+ if (mc == 0) {
+ property.usage = 0; //do not show
} else {
- property.hint_string="0,"+itos(mc)+",1";
+ property.hint_string = "0," + itos(mc) + ",1";
}
}
- if (property.name=="rpc/call_mode") {
- if (call_mode==CALL_MODE_BASIC_TYPE) {
- property.usage=0;
+ if (property.name == "rpc/call_mode") {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
+ property.usage = 0;
}
}
-
}
-
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_base_script","base_script"),&VisualScriptFunctionCall::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"),&VisualScriptFunctionCall::get_base_script);
+ ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptFunctionCall::set_base_script);
+ ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptFunctionCall::get_base_script);
- ClassDB::bind_method(D_METHOD("set_basic_type","basic_type"),&VisualScriptFunctionCall::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"),&VisualScriptFunctionCall::get_basic_type);
+ ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptFunctionCall::set_basic_type);
+ ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptFunctionCall::get_basic_type);
- ClassDB::bind_method(D_METHOD("set_singleton","singleton"),&VisualScriptFunctionCall::set_singleton);
- ClassDB::bind_method(D_METHOD("get_singleton"),&VisualScriptFunctionCall::get_singleton);
+ ClassDB::bind_method(D_METHOD("set_singleton", "singleton"), &VisualScriptFunctionCall::set_singleton);
+ ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptFunctionCall::get_singleton);
- ClassDB::bind_method(D_METHOD("set_function","function"),&VisualScriptFunctionCall::set_function);
- ClassDB::bind_method(D_METHOD("get_function"),&VisualScriptFunctionCall::get_function);
+ ClassDB::bind_method(D_METHOD("set_function", "function"), &VisualScriptFunctionCall::set_function);
+ ClassDB::bind_method(D_METHOD("get_function"), &VisualScriptFunctionCall::get_function);
- ClassDB::bind_method(D_METHOD("set_call_mode","mode"),&VisualScriptFunctionCall::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"),&VisualScriptFunctionCall::get_call_mode);
+ ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptFunctionCall::set_call_mode);
+ ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptFunctionCall::get_call_mode);
- ClassDB::bind_method(D_METHOD("set_base_path","base_path"),&VisualScriptFunctionCall::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"),&VisualScriptFunctionCall::get_base_path);
+ ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptFunctionCall::set_base_path);
+ ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptFunctionCall::get_base_path);
- ClassDB::bind_method(D_METHOD("set_use_default_args","amount"),&VisualScriptFunctionCall::set_use_default_args);
- ClassDB::bind_method(D_METHOD("get_use_default_args"),&VisualScriptFunctionCall::get_use_default_args);
+ ClassDB::bind_method(D_METHOD("set_use_default_args", "amount"), &VisualScriptFunctionCall::set_use_default_args);
+ ClassDB::bind_method(D_METHOD("get_use_default_args"), &VisualScriptFunctionCall::get_use_default_args);
- ClassDB::bind_method(D_METHOD("_set_argument_cache","argument_cache"),&VisualScriptFunctionCall::_set_argument_cache);
- ClassDB::bind_method(D_METHOD("_get_argument_cache"),&VisualScriptFunctionCall::_get_argument_cache);
+ ClassDB::bind_method(D_METHOD("_set_argument_cache", "argument_cache"), &VisualScriptFunctionCall::_set_argument_cache);
+ ClassDB::bind_method(D_METHOD("_get_argument_cache"), &VisualScriptFunctionCall::_get_argument_cache);
- ClassDB::bind_method(D_METHOD("set_rpc_call_mode","mode"),&VisualScriptFunctionCall::set_rpc_call_mode);
- ClassDB::bind_method(D_METHOD("get_rpc_call_mode"),&VisualScriptFunctionCall::get_rpc_call_mode);
+ ClassDB::bind_method(D_METHOD("set_rpc_call_mode", "mode"), &VisualScriptFunctionCall::set_rpc_call_mode);
+ ClassDB::bind_method(D_METHOD("get_rpc_call_mode"), &VisualScriptFunctionCall::get_rpc_call_mode);
- ClassDB::bind_method(D_METHOD("set_validate","enable"),&VisualScriptFunctionCall::set_validate);
- ClassDB::bind_method(D_METHOD("get_validate"),&VisualScriptFunctionCall::get_validate);
+ ClassDB::bind_method(D_METHOD("set_validate", "enable"), &VisualScriptFunctionCall::set_validate);
+ ClassDB::bind_method(D_METHOD("get_validate"), &VisualScriptFunctionCall::get_validate);
String bt;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (i>0)
- bt+=",";
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (i > 0)
+ bt += ",";
- bt+=Variant::get_type_name(Variant::Type(i));
+ bt += Variant::get_type_name(Variant::Type(i));
}
-
List<String> script_extensions;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
}
String script_ext_hint;
- for (List<String>::Element *E=script_extensions.front();E;E=E->next()) {
- if (script_ext_hint!=String())
- script_ext_hint+=",";
- script_ext_hint+="*."+E->get();
- }
-
-
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"function/call_mode",PROPERTY_HINT_ENUM,"Self,Node Path,Instance,Basic Type,Singleton"),"set_call_mode","get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"function/base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"function/base_script",PROPERTY_HINT_FILE,script_ext_hint),"set_base_script","get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"function/singleton"),"set_singleton","get_singleton");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"function/basic_type",PROPERTY_HINT_ENUM,bt),"set_basic_type","get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"function/node_path",PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE),"set_base_path","get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"function/argument_cache",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_argument_cache","_get_argument_cache");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"function/function"),"set_function","get_function"); //when set, if loaded properly, will override argument count.
- ADD_PROPERTY(PropertyInfo(Variant::INT,"function/use_default_args"),"set_use_default_args","get_use_default_args");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"function/validate"),"set_validate","get_validate");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"rpc/call_mode",PROPERTY_HINT_ENUM,"Disabled,Reliable,Unreliable,ReliableToID,UnreliableToID"),"set_rpc_call_mode","get_rpc_call_mode"); //when set, if loaded properly, will override argument count.
-
- BIND_CONSTANT( CALL_MODE_SELF );
- BIND_CONSTANT( CALL_MODE_NODE_PATH);
- BIND_CONSTANT( CALL_MODE_INSTANCE);
- BIND_CONSTANT( CALL_MODE_BASIC_TYPE );
+ for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
+ if (script_ext_hint != String())
+ script_ext_hint += ",";
+ script_ext_hint += "*." + E->get();
+ }
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "function/call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type,Singleton"), "set_call_mode", "get_call_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "function/base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "function/base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "function/singleton"), "set_singleton", "get_singleton");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "function/basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "function/node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "function/argument_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_argument_cache", "_get_argument_cache");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "function/function"), "set_function", "get_function"); //when set, if loaded properly, will override argument count.
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "function/use_default_args"), "set_use_default_args", "get_use_default_args");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "function/validate"), "set_validate", "get_validate");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "rpc/call_mode", PROPERTY_HINT_ENUM, "Disabled,Reliable,Unreliable,ReliableToID,UnreliableToID"), "set_rpc_call_mode", "get_rpc_call_mode"); //when set, if loaded properly, will override argument count.
+
+ BIND_CONSTANT(CALL_MODE_SELF);
+ BIND_CONSTANT(CALL_MODE_NODE_PATH);
+ BIND_CONSTANT(CALL_MODE_INSTANCE);
+ BIND_CONSTANT(CALL_MODE_BASIC_TYPE);
}
class VisualScriptNodeInstanceFunctionCall : public VisualScriptNodeInstance {
public:
-
-
VisualScriptFunctionCall::CallMode call_mode;
NodePath node_path;
int input_args;
@@ -806,80 +766,76 @@ public:
VisualScriptFunctionCall *node;
VisualScriptInstance *instance;
-
-
//virtual int get_working_memory_size() const { return 0; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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) {
+ _FORCE_INLINE_ bool call_rpc(Object *p_base, const Variant **p_args, int p_argcount) {
if (!p_base)
return false;
- Node * node = p_base->cast_to<Node>();
+ Node *node = p_base->cast_to<Node>();
if (!node)
return false;
- int to_id=0;
- bool reliable=true;
+ int to_id = 0;
+ bool reliable = true;
- if (rpc_mode>=VisualScriptFunctionCall::RPC_RELIABLE_TO_ID) {
+ if (rpc_mode >= VisualScriptFunctionCall::RPC_RELIABLE_TO_ID) {
to_id = *p_args[0];
- p_args+=1;
- p_argcount-=1;
- if (rpc_mode==VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) {
- reliable=false;
+ p_args += 1;
+ p_argcount -= 1;
+ if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE_TO_ID) {
+ reliable = false;
}
- } else if (rpc_mode==VisualScriptFunctionCall::RPC_UNRELIABLE) {
- reliable=false;
+ } else if (rpc_mode == VisualScriptFunctionCall::RPC_UNRELIABLE) {
+ reliable = false;
}
- node->rpcp(to_id,!reliable,function,p_args,p_argcount);
+ node->rpcp(to_id, !reliable, function, p_args, p_argcount);
return true;
}
- virtual int step(const Variant** p_inputs,Variant** p_outputs,StartMode p_start_mode,Variant* p_working_mem,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
-
- switch(call_mode) {
+ switch (call_mode) {
case VisualScriptFunctionCall::CALL_MODE_SELF: {
- Object *object=instance->get_owner_ptr();
+ Object *object = instance->get_owner_ptr();
if (rpc_mode) {
- call_rpc(object,p_inputs,input_args);
+ call_rpc(object, p_inputs, input_args);
} else if (returns) {
- *p_outputs[0] = object->call(function,p_inputs,input_args,r_error);
+ *p_outputs[0] = object->call(function, p_inputs, input_args, r_error);
} else {
- object->call(function,p_inputs,input_args,r_error);
+ object->call(function, p_inputs, input_args, r_error);
}
} break;
case VisualScriptFunctionCall::CALL_MODE_NODE_PATH: {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Base object is not a Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Base object is not a Node!";
return 0;
}
- Node* another = node->get_node(node_path);
+ Node *another = node->get_node(node_path);
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Path does not lead Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Path does not lead Node!";
return 0;
}
if (rpc_mode) {
- call_rpc(node,p_inputs,input_args);
+ call_rpc(node, p_inputs, input_args);
} else if (returns) {
- *p_outputs[0] = another->call(function,p_inputs,input_args,r_error);
+ *p_outputs[0] = another->call(function, p_inputs, input_args, r_error);
} else {
- another->call(function,p_inputs,input_args,r_error);
+ another->call(function, p_inputs, input_args, r_error);
}
} break;
@@ -891,98 +847,90 @@ public:
if (rpc_mode) {
Object *obj = v;
if (obj) {
- call_rpc(obj,p_inputs+1,input_args-1);
+ call_rpc(obj, p_inputs + 1, input_args - 1);
}
} else if (returns) {
- if (call_mode==VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
- *p_outputs[1] = v.call(function,p_inputs+1,input_args,r_error);
+ if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
+ *p_outputs[1] = v.call(function, p_inputs + 1, input_args, r_error);
} else {
- *p_outputs[0] = v.call(function,p_inputs+1,input_args,r_error);
+ *p_outputs[0] = v.call(function, p_inputs + 1, input_args, r_error);
}
} else {
- v.call(function,p_inputs+1,input_args,r_error);
+ v.call(function, p_inputs + 1, input_args, r_error);
}
- if (call_mode==VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
- *p_outputs[0]=*p_inputs[0];
+ if (call_mode == VisualScriptFunctionCall::CALL_MODE_INSTANCE) {
+ *p_outputs[0] = *p_inputs[0];
}
} break;
case VisualScriptFunctionCall::CALL_MODE_SINGLETON: {
- Object *object=GlobalConfig::get_singleton()->get_singleton_object(singleton);
+ Object *object = GlobalConfig::get_singleton()->get_singleton_object(singleton);
if (!object) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid singleton name: '"+String(singleton)+"'";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid singleton name: '" + String(singleton) + "'";
return 0;
}
if (rpc_mode) {
- call_rpc(object,p_inputs,input_args);
+ call_rpc(object, p_inputs, input_args);
} else if (returns) {
- *p_outputs[0] = object->call(function,p_inputs,input_args,r_error);
+ *p_outputs[0] = object->call(function, p_inputs, input_args, r_error);
} else {
- object->call(function,p_inputs,input_args,r_error);
+ object->call(function, p_inputs, input_args, r_error);
}
} break;
-
}
if (!validate) {
//ignore call errors if validation is disabled
- r_error.error=Variant::CallError::CALL_OK;
- r_error_str=String();
+ r_error.error = Variant::CallError::CALL_OK;
+ r_error_str = String();
}
return 0;
-
}
-
-
};
-VisualScriptNodeInstance* VisualScriptFunctionCall::instance(VisualScriptInstance* p_instance) {
-
- VisualScriptNodeInstanceFunctionCall * instance = memnew(VisualScriptNodeInstanceFunctionCall );
- instance->node=this;
- instance->instance=p_instance;
- instance->singleton=singleton;
- instance->function=function;
- instance->call_mode=call_mode;
- instance->returns=get_output_value_port_count();
- instance->node_path=base_path;
- instance->input_args = get_input_value_port_count() - ( (call_mode==CALL_MODE_BASIC_TYPE || call_mode==CALL_MODE_INSTANCE) ? 1: 0 );
- instance->rpc_mode=rpc_call_mode;
- instance->validate=validate;
+VisualScriptNodeInstance *VisualScriptFunctionCall::instance(VisualScriptInstance *p_instance) {
+
+ VisualScriptNodeInstanceFunctionCall *instance = memnew(VisualScriptNodeInstanceFunctionCall);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->singleton = singleton;
+ instance->function = function;
+ instance->call_mode = call_mode;
+ instance->returns = get_output_value_port_count();
+ instance->node_path = base_path;
+ instance->input_args = get_input_value_port_count() - ((call_mode == CALL_MODE_BASIC_TYPE || call_mode == CALL_MODE_INSTANCE) ? 1 : 0);
+ instance->rpc_mode = rpc_call_mode;
+ instance->validate = validate;
return instance;
}
+VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-VisualScriptFunctionCall::TypeGuess VisualScriptFunctionCall::guess_output_type(TypeGuess* p_inputs, int p_output) const {
-
- if (p_output==0 && call_mode==CALL_MODE_INSTANCE) {
+ if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
return p_inputs[0];
}
- return VisualScriptNode::guess_output_type(p_inputs,p_output);
-
+ return VisualScriptNode::guess_output_type(p_inputs, p_output);
}
VisualScriptFunctionCall::VisualScriptFunctionCall() {
- validate=true;
- call_mode=CALL_MODE_SELF;
- basic_type=Variant::NIL;
- use_default_args=0;
- base_type="Object";
- rpc_call_mode=RPC_DISABLED;
-
-
+ validate = true;
+ call_mode = CALL_MODE_SELF;
+ basic_type = Variant::NIL;
+ use_default_args = 0;
+ base_type = "Object";
+ rpc_call_mode = RPC_DISABLED;
}
-template<VisualScriptFunctionCall::CallMode cmode>
-static Ref<VisualScriptNode> create_function_call_node(const String& p_name) {
+template <VisualScriptFunctionCall::CallMode cmode>
+static Ref<VisualScriptNode> create_function_call_node(const String &p_name) {
Ref<VisualScriptFunctionCall> node;
node.instance();
@@ -990,12 +938,11 @@ static Ref<VisualScriptNode> create_function_call_node(const String& p_name) {
return node;
}
-
//////////////////////////////////////////
////////////////SET//////////////////////
//////////////////////////////////////////
-static const char* event_type_names[InputEvent::TYPE_MAX]={
+static const char *event_type_names[InputEvent::TYPE_MAX] = {
"None",
"Key",
"MouseMotion",
@@ -1007,15 +954,14 @@ static const char* event_type_names[InputEvent::TYPE_MAX]={
"Action"
};
-
int VisualScriptPropertySet::get_output_sequence_port_count() const {
- return call_mode!=CALL_MODE_BASIC_TYPE ? 1 : 0;
+ return call_mode != CALL_MODE_BASIC_TYPE ? 1 : 0;
}
-bool VisualScriptPropertySet::has_input_sequence_port() const{
+bool VisualScriptPropertySet::has_input_sequence_port() const {
- return call_mode!=CALL_MODE_BASIC_TYPE ? true : false;
+ return call_mode != CALL_MODE_BASIC_TYPE ? true : false;
}
Node *VisualScriptPropertySet::_get_base_node() const {
@@ -1025,7 +971,7 @@ Node *VisualScriptPropertySet::_get_base_node() const {
if (!script.is_valid())
return NULL;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return NULL;
@@ -1039,7 +985,7 @@ Node *VisualScriptPropertySet::_get_base_node() const {
if (!edited_scene)
return NULL;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return NULL;
@@ -1058,27 +1004,26 @@ 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)
return path->get_class();
-
}
return base_type;
}
-int VisualScriptPropertySet::get_input_value_port_count() const{
+int VisualScriptPropertySet::get_input_value_port_count() const {
- int pc = (call_mode==CALL_MODE_BASIC_TYPE || call_mode==CALL_MODE_INSTANCE)?2:1;
+ 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;
+ 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 {
@@ -1086,39 +1031,37 @@ String VisualScriptPropertySet::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptPropertySet::get_input_value_port_info(int p_idx) const {
- if (call_mode==CALL_MODE_INSTANCE || call_mode==CALL_MODE_BASIC_TYPE) {
- if (p_idx==0) {
+ if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
+ if (p_idx == 0) {
PropertyInfo pi;
- pi.type=(call_mode==CALL_MODE_INSTANCE?Variant::OBJECT:basic_type);
- pi.name=(call_mode==CALL_MODE_INSTANCE?String("instance"):Variant::get_type_name(basic_type).to_lower());
+ pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
+ pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
return pi;
} else {
p_idx--;
}
}
- PropertyInfo pinfo=type_cache;
- pinfo.name="value";
+ PropertyInfo pinfo = type_cache;
+ pinfo.name = "value";
return pinfo;
}
-PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) const{
- if (call_mode==CALL_MODE_BASIC_TYPE) {
- return PropertyInfo(basic_type,"out");
- } else if (call_mode==CALL_MODE_INSTANCE) {
- return PropertyInfo(Variant::OBJECT,"pass");
+PropertyInfo VisualScriptPropertySet::get_output_value_port_info(int p_idx) const {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
+ return PropertyInfo(basic_type, "out");
+ } else if (call_mode == CALL_MODE_INSTANCE) {
+ return PropertyInfo(Variant::OBJECT, "pass");
} else {
return PropertyInfo();
}
-
}
-
String VisualScriptPropertySet::get_caption() const {
- static const char*cname[4]= {
+ static const char *cname[4] = {
"SelfSet",
"NodeSet",
"InstanceSet",
@@ -1132,58 +1075,55 @@ String VisualScriptPropertySet::get_text() const {
String prop;
- if (call_mode==CALL_MODE_BASIC_TYPE)
- prop=Variant::get_type_name(basic_type)+"."+property;
- else if (call_mode==CALL_MODE_NODE_PATH)
- prop=String(base_path)+":"+property;
- else if (call_mode==CALL_MODE_SELF)
- prop=property;
- else if (call_mode==CALL_MODE_INSTANCE)
- prop=String(base_type)+":"+property;
+ if (call_mode == CALL_MODE_BASIC_TYPE)
+ prop = Variant::get_type_name(basic_type) + "." + property;
+ else if (call_mode == CALL_MODE_NODE_PATH)
+ prop = String(base_path) + ":" + property;
+ else if (call_mode == CALL_MODE_SELF)
+ prop = property;
+ else if (call_mode == CALL_MODE_INSTANCE)
+ prop = String(base_type) + ":" + property;
return prop;
-
}
void VisualScriptPropertySet::_update_base_type() {
//cache it because this information may not be available on load
- if (call_mode==CALL_MODE_NODE_PATH) {
+ if (call_mode == CALL_MODE_NODE_PATH) {
- Node* node=_get_base_node();
+ Node *node = _get_base_node();
if (node) {
- base_type=node->get_class();
+ base_type = node->get_class();
}
- } else if (call_mode==CALL_MODE_SELF) {
+ } else if (call_mode == CALL_MODE_SELF) {
if (get_visual_script().is_valid()) {
- base_type=get_visual_script()->get_instance_base_type();
+ base_type = get_visual_script()->get_instance_base_type();
}
}
-
}
void VisualScriptPropertySet::set_basic_type(Variant::Type p_type) {
- if (basic_type==p_type)
+ if (basic_type == p_type)
return;
- basic_type=p_type;
-
+ basic_type = p_type;
_change_notify();
_update_base_type();
ports_changed_notify();
}
-Variant::Type VisualScriptPropertySet::get_basic_type() const{
+Variant::Type VisualScriptPropertySet::get_basic_type() const {
return basic_type;
}
void VisualScriptPropertySet::set_event_type(InputEvent::Type p_type) {
- if (event_type==p_type)
+ if (event_type == p_type)
return;
- event_type=p_type;
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ event_type = p_type;
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
_update_cache();
}
_change_notify();
@@ -1191,34 +1131,32 @@ void VisualScriptPropertySet::set_event_type(InputEvent::Type p_type) {
ports_changed_notify();
}
-InputEvent::Type VisualScriptPropertySet::get_event_type() const{
+InputEvent::Type VisualScriptPropertySet::get_event_type() const {
return event_type;
}
+void VisualScriptPropertySet::set_base_type(const StringName &p_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();
+ base_type = p_type;
+ _change_notify();
ports_changed_notify();
}
-StringName VisualScriptPropertySet::get_base_type() const{
+StringName VisualScriptPropertySet::get_base_type() const {
return base_type;
}
+void VisualScriptPropertySet::set_base_script(const String &p_path) {
-void VisualScriptPropertySet::set_base_script(const String& p_path) {
-
- if (base_script==p_path)
+ if (base_script == p_path)
return;
- base_script=p_path;
+ base_script = p_path;
_change_notify();
ports_changed_notify();
}
@@ -1228,10 +1166,8 @@ String VisualScriptPropertySet::get_base_script() const {
return base_script;
}
-
void VisualScriptPropertySet::_update_cache() {
-
if (!OS::get_singleton()->get_main_loop())
return;
if (!OS::get_singleton()->get_main_loop()->cast_to<SceneTree>())
@@ -1240,57 +1176,56 @@ void VisualScriptPropertySet::_update_cache() {
if (!OS::get_singleton()->get_main_loop()->cast_to<SceneTree>()->is_editor_hint()) //only update cache if editor exists, it's pointless otherwise
return;
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
//not super efficient..
Variant v;
- if (basic_type==Variant::INPUT_EVENT) {
+ if (basic_type == Variant::INPUT_EVENT) {
InputEvent ev;
- ev.type=event_type;
- v=ev;
+ ev.type = event_type;
+ v = ev;
} else {
Variant::CallError ce;
- v = Variant::construct(basic_type,NULL,0,ce);
+ v = Variant::construct(basic_type, NULL, 0, ce);
}
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().name==property) {
+ if (E->get().name == property) {
- type_cache=E->get();
+ type_cache = E->get();
}
}
} else {
-
StringName type;
Ref<Script> script;
- Node *node=NULL;
+ Node *node = NULL;
- if (call_mode==CALL_MODE_NODE_PATH) {
+ if (call_mode == CALL_MODE_NODE_PATH) {
- node=_get_base_node();
+ node = _get_base_node();
if (node) {
- type=node->get_class();
- base_type=type; //cache, too
+ type = node->get_class();
+ base_type = type; //cache, too
script = node->get_script();
}
- } else if (call_mode==CALL_MODE_SELF) {
+ } 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();
+ type = get_visual_script()->get_instance_base_type();
+ base_type = type; //cache, too
+ script = get_visual_script();
}
- } else if (call_mode==CALL_MODE_INSTANCE) {
+ } else if (call_mode == CALL_MODE_INSTANCE) {
- type=base_type;
- if (base_script!=String()) {
+ type = base_type;
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
@@ -1299,7 +1234,7 @@ void VisualScriptPropertySet::_update_cache() {
if (ResourceCache::has(base_script)) {
- script = Ref<Resource>( ResourceCache::get(base_script) );
+ script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
}
@@ -1308,12 +1243,11 @@ void VisualScriptPropertySet::_update_cache() {
List<PropertyInfo> pinfo;
-
if (node) {
node->get_property_list(&pinfo);
} else {
- ClassDB::get_property_list(type,&pinfo);
+ ClassDB::get_property_list(type, &pinfo);
}
if (script.is_valid()) {
@@ -1321,39 +1255,37 @@ void VisualScriptPropertySet::_update_cache() {
script->get_script_property_list(&pinfo);
}
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().name==property) {
- type_cache=E->get();
+ if (E->get().name == property) {
+ type_cache = E->get();
return;
}
}
-
}
}
-void VisualScriptPropertySet::set_property(const StringName& p_type){
+void VisualScriptPropertySet::set_property(const StringName &p_type) {
- if (property==p_type)
+ if (property == p_type)
return;
- property=p_type;
+ property = p_type;
_update_cache();
- _change_notify();
+ _change_notify();
ports_changed_notify();
}
StringName VisualScriptPropertySet::get_property() const {
-
return property;
}
-void VisualScriptPropertySet::set_base_path(const NodePath& p_type) {
+void VisualScriptPropertySet::set_base_path(const NodePath &p_type) {
- if (base_path==p_type)
+ if (base_path == p_type)
return;
- base_path=p_type;
+ base_path = p_type;
_update_base_type();
_change_notify();
ports_changed_notify();
@@ -1364,28 +1296,23 @@ 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;
+ call_mode = p_mode;
_update_base_type();
_change_notify();
ports_changed_notify();
-
}
VisualScriptPropertySet::CallMode VisualScriptPropertySet::get_call_mode() const {
return call_mode;
}
-
-
-
void VisualScriptPropertySet::_set_type_cache(const Dictionary &p_type) {
- type_cache=PropertyInfo::from_dict(p_type);
+ type_cache = PropertyInfo::from_dict(p_type);
}
Dictionary VisualScriptPropertySet::_get_type_cache() const {
@@ -1393,61 +1320,60 @@ Dictionary VisualScriptPropertySet::_get_type_cache() const {
return type_cache;
}
-void VisualScriptPropertySet::_validate_property(PropertyInfo& property) const {
+void VisualScriptPropertySet::_validate_property(PropertyInfo &property) const {
- if (property.name=="property/base_type") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "property/base_type") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
- if (property.name=="property/base_script") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=0;
+ if (property.name == "property/base_script") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = 0;
}
}
- if (property.name=="property/basic_type") {
- if (call_mode!=CALL_MODE_BASIC_TYPE) {
- property.usage=0;
+ if (property.name == "property/basic_type") {
+ if (call_mode != CALL_MODE_BASIC_TYPE) {
+ property.usage = 0;
}
}
- if (property.name=="property/event_type") {
- if (call_mode!=CALL_MODE_BASIC_TYPE || basic_type!=Variant::INPUT_EVENT) {
- property.usage=0;
+ if (property.name == "property/event_type") {
+ if (call_mode != CALL_MODE_BASIC_TYPE || basic_type != Variant::INPUT_EVENT) {
+ property.usage = 0;
}
}
- if (property.name=="property/node_path") {
- if (call_mode!=CALL_MODE_NODE_PATH) {
- property.usage=0;
+ if (property.name == "property/node_path") {
+ 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
+ property.hint_string = bnode->get_path(); //convert to loong string
} else {
-
}
}
}
- if (property.name=="property/property") {
+ if (property.name == "property/property") {
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
- property.hint_string=Variant::get_type_name(basic_type);
+ property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
+ property.hint_string = Variant::get_type_name(basic_type);
- } else if (call_mode==CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string=itos(get_visual_script()->get_instance_ID());
- } else if (call_mode==CALL_MODE_INSTANCE) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string=base_type;
+ } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
+ property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
+ property.hint_string = itos(get_visual_script()->get_instance_ID());
+ } else if (call_mode == CALL_MODE_INSTANCE) {
+ property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
+ property.hint_string = base_type;
- if (base_script!=String()) {
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
ScriptServer::edit_request_func(base_script); //make sure it's loaded
@@ -1455,106 +1381,98 @@ void VisualScriptPropertySet::_validate_property(PropertyInfo& property) const {
if (ResourceCache::has(base_script)) {
- Ref<Script> script = Ref<Resource>( ResourceCache::get(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());
+ property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
+ property.hint_string = itos(script->get_instance_ID());
}
}
}
- } else if (call_mode==CALL_MODE_NODE_PATH) {
+ } else if (call_mode == CALL_MODE_NODE_PATH) {
Node *node = _get_base_node();
if (node) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_INSTANCE;
- property.hint_string=itos(node->get_instance_ID());
+ property.hint = PROPERTY_HINT_PROPERTY_OF_INSTANCE;
+ property.hint_string = itos(node->get_instance_ID());
} else {
- property.hint=PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string=get_base_type();
+ property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
+ property.hint_string = get_base_type();
}
-
}
-
}
-
}
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_base_script","base_script"),&VisualScriptPropertySet::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"),&VisualScriptPropertySet::get_base_script);
+ ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertySet::set_base_script);
+ ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertySet::get_base_script);
- ClassDB::bind_method(D_METHOD("set_basic_type","basic_type"),&VisualScriptPropertySet::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"),&VisualScriptPropertySet::get_basic_type);
+ ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertySet::set_basic_type);
+ ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertySet::get_basic_type);
- ClassDB::bind_method(D_METHOD("_set_type_cache","type_cache"),&VisualScriptPropertySet::_set_type_cache);
- ClassDB::bind_method(D_METHOD("_get_type_cache"),&VisualScriptPropertySet::_get_type_cache);
+ ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertySet::_set_type_cache);
+ ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertySet::_get_type_cache);
- ClassDB::bind_method(D_METHOD("set_event_type","event_type"),&VisualScriptPropertySet::set_event_type);
- ClassDB::bind_method(D_METHOD("get_event_type"),&VisualScriptPropertySet::get_event_type);
+ ClassDB::bind_method(D_METHOD("set_event_type", "event_type"), &VisualScriptPropertySet::set_event_type);
+ ClassDB::bind_method(D_METHOD("get_event_type"), &VisualScriptPropertySet::get_event_type);
- ClassDB::bind_method(D_METHOD("set_property","property"),&VisualScriptPropertySet::set_property);
- ClassDB::bind_method(D_METHOD("get_property"),&VisualScriptPropertySet::get_property);
-
- ClassDB::bind_method(D_METHOD("set_call_mode","mode"),&VisualScriptPropertySet::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"),&VisualScriptPropertySet::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path","base_path"),&VisualScriptPropertySet::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"),&VisualScriptPropertySet::get_base_path);
+ ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertySet::set_property);
+ ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertySet::get_property);
+ ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertySet::set_call_mode);
+ ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertySet::get_call_mode);
+ ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertySet::set_base_path);
+ ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertySet::get_base_path);
String bt;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (i>0)
- bt+=",";
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (i > 0)
+ bt += ",";
- bt+=Variant::get_type_name(Variant::Type(i));
+ bt += Variant::get_type_name(Variant::Type(i));
}
String et;
- for(int i=0;i<InputEvent::TYPE_MAX;i++) {
- if (i>0)
- et+=",";
+ for (int i = 0; i < InputEvent::TYPE_MAX; i++) {
+ if (i > 0)
+ et += ",";
- et+=event_type_names[i];
+ et += event_type_names[i];
}
List<String> script_extensions;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
}
String script_ext_hint;
- for (List<String>::Element *E=script_extensions.front();E;E=E->next()) {
- if (script_ext_hint!=String())
- script_ext_hint+=",";
- script_ext_hint+="*."+E->get();
+ for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
+ if (script_ext_hint != String())
+ script_ext_hint += ",";
+ script_ext_hint += "*." + E->get();
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/set_mode",PROPERTY_HINT_ENUM,"Self,Node Path,Instance,Basic Type"),"set_call_mode","get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/base_script",PROPERTY_HINT_FILE,script_ext_hint),"set_base_script","get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/type_cache",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_type_cache","_get_type_cache");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/basic_type",PROPERTY_HINT_ENUM,bt),"set_basic_type","get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/event_type",PROPERTY_HINT_ENUM,et),"set_event_type","get_event_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"property/node_path",PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE),"set_base_path","get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/property"),"set_property","get_property");
-
- BIND_CONSTANT( CALL_MODE_SELF );
- BIND_CONSTANT( CALL_MODE_NODE_PATH);
- BIND_CONSTANT( CALL_MODE_INSTANCE);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_type_cache", "_get_type_cache");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/event_type", PROPERTY_HINT_ENUM, et), "set_event_type", "get_event_type");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "property/node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/property"), "set_property", "get_property");
+ BIND_CONSTANT(CALL_MODE_SELF);
+ BIND_CONSTANT(CALL_MODE_NODE_PATH);
+ BIND_CONSTANT(CALL_MODE_INSTANCE);
}
class VisualScriptNodeInstancePropertySet : public VisualScriptNodeInstance {
public:
-
-
VisualScriptPropertySet::CallMode call_mode;
NodePath node_path;
StringName property;
@@ -1562,53 +1480,50 @@ public:
VisualScriptPropertySet *node;
VisualScriptInstance *instance;
-
-
//virtual int get_working_memory_size() const { return 0; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
-
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- switch(call_mode) {
+ switch (call_mode) {
case VisualScriptPropertySet::CALL_MODE_SELF: {
- Object *object=instance->get_owner_ptr();
+ Object *object = instance->get_owner_ptr();
bool valid;
- object->set(property,*p_inputs[0],&valid);
+ object->set(property, *p_inputs[0], &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid set value '"+String(*p_inputs[0])+"' on property '"+String(property)+"' of type "+object->get_class();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + object->get_class();
}
} break;
case VisualScriptPropertySet::CALL_MODE_NODE_PATH: {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Base object is not a Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Base object is not a Node!";
return 0;
}
- Node* another = node->get_node(node_path);
+ Node *another = node->get_node(node_path);
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Path does not lead Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Path does not lead Node!";
return 0;
}
bool valid;
- another->set(property,*p_inputs[0],&valid);
+ another->set(property, *p_inputs[0], &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid set value '"+String(*p_inputs[0])+"' on property '"+String(property)+"' of type "+another->get_class();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid set value '" + String(*p_inputs[0]) + "' on property '" + String(property) + "' of type " + another->get_class();
}
} break;
@@ -1619,58 +1534,50 @@ public:
bool valid;
- v.set(property,*p_inputs[1],&valid);
+ v.set(property, *p_inputs[1], &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid set value '"+String(*p_inputs[1])+"' ("+Variant::get_type_name(p_inputs[1]->get_type())+") on property '"+String(property)+"' of type "+Variant::get_type_name(v.get_type());
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid set value '" + String(*p_inputs[1]) + "' (" + Variant::get_type_name(p_inputs[1]->get_type()) + ") on property '" + String(property) + "' of type " + Variant::get_type_name(v.get_type());
}
- *p_outputs[0]=v;
+ *p_outputs[0] = v;
} break;
-
}
return 0;
-
}
-
-
};
-VisualScriptNodeInstance* VisualScriptPropertySet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptPropertySet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePropertySet * instance = memnew(VisualScriptNodeInstancePropertySet );
- instance->node=this;
- instance->instance=p_instance;
- instance->property=property;
- instance->call_mode=call_mode;
- instance->node_path=base_path;
+ VisualScriptNodeInstancePropertySet *instance = memnew(VisualScriptNodeInstancePropertySet);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->property = property;
+ instance->call_mode = call_mode;
+ instance->node_path = base_path;
return instance;
}
+VisualScriptPropertySet::TypeGuess VisualScriptPropertySet::guess_output_type(TypeGuess *p_inputs, int p_output) const {
-
-VisualScriptPropertySet::TypeGuess VisualScriptPropertySet::guess_output_type(TypeGuess* p_inputs, int p_output) const {
-
- if (p_output==0 && call_mode==CALL_MODE_INSTANCE) {
+ if (p_output == 0 && call_mode == CALL_MODE_INSTANCE) {
return p_inputs[0];
}
- return VisualScriptNode::guess_output_type(p_inputs,p_output);
-
+ return VisualScriptNode::guess_output_type(p_inputs, p_output);
}
VisualScriptPropertySet::VisualScriptPropertySet() {
- call_mode=CALL_MODE_SELF;
- base_type="Object";
- basic_type=Variant::NIL;
- event_type=InputEvent::NONE;
-
+ call_mode = CALL_MODE_SELF;
+ base_type = "Object";
+ basic_type = Variant::NIL;
+ event_type = InputEvent::NONE;
}
-template<VisualScriptPropertySet::CallMode cmode>
-static Ref<VisualScriptNode> create_property_set_node(const String& p_name) {
+template <VisualScriptPropertySet::CallMode cmode>
+static Ref<VisualScriptNode> create_property_set_node(const String &p_name) {
Ref<VisualScriptPropertySet> node;
node.instance();
@@ -1678,35 +1585,33 @@ static Ref<VisualScriptNode> create_property_set_node(const String& p_name) {
return node;
}
-
//////////////////////////////////////////
////////////////GET//////////////////////
//////////////////////////////////////////
int VisualScriptPropertyGet::get_output_sequence_port_count() const {
- return 0;// (call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?0:1;
+ return 0; // (call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?0:1;
}
-bool VisualScriptPropertyGet::has_input_sequence_port() const{
+bool VisualScriptPropertyGet::has_input_sequence_port() const {
- return false;//(call_mode==CALL_MODE_SELF || call_mode==CALL_MODE_NODE_PATH)?false:true;
+ 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) {
+ if (call_mode == CALL_MODE_NODE_PATH) {
- Node* node=_get_base_node();
+ Node *node = _get_base_node();
if (node) {
- base_type=node->get_class();
+ base_type = node->get_class();
}
- } else if (call_mode==CALL_MODE_SELF) {
+ } else if (call_mode == CALL_MODE_SELF) {
if (get_visual_script().is_valid()) {
- base_type=get_visual_script()->get_instance_base_type();
+ base_type = get_visual_script()->get_instance_base_type();
}
}
-
}
Node *VisualScriptPropertyGet::_get_base_node() const {
@@ -1715,7 +1620,7 @@ Node *VisualScriptPropertyGet::_get_base_node() const {
if (!script.is_valid())
return NULL;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return NULL;
@@ -1729,7 +1634,7 @@ Node *VisualScriptPropertyGet::_get_base_node() const {
if (!edited_scene)
return NULL;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return NULL;
@@ -1748,25 +1653,22 @@ 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)
return path->get_class();
-
}
return base_type;
}
+int VisualScriptPropertyGet::get_input_value_port_count() const {
-int VisualScriptPropertyGet::get_input_value_port_count() const{
-
- return (call_mode==CALL_MODE_BASIC_TYPE || call_mode==CALL_MODE_INSTANCE)?1:0;
-
+ 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;
}
@@ -1776,31 +1678,29 @@ String VisualScriptPropertyGet::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptPropertyGet::get_input_value_port_info(int p_idx) const{
+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) {
+ if (call_mode == CALL_MODE_INSTANCE || call_mode == CALL_MODE_BASIC_TYPE) {
+ if (p_idx == 0) {
PropertyInfo pi;
- pi.type=(call_mode==CALL_MODE_INSTANCE?Variant::OBJECT:basic_type);
- pi.name=(call_mode==CALL_MODE_INSTANCE?String("instance"):Variant::get_type_name(basic_type).to_lower());
+ pi.type = (call_mode == CALL_MODE_INSTANCE ? Variant::OBJECT : basic_type);
+ pi.name = (call_mode == CALL_MODE_INSTANCE ? String("instance") : Variant::get_type_name(basic_type).to_lower());
return pi;
} else {
p_idx--;
}
}
return PropertyInfo();
-
}
-PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptPropertyGet::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type_cache,"value");
+ return PropertyInfo(type_cache, "value");
}
-
String VisualScriptPropertyGet::get_caption() const {
- static const char*cname[4]= {
+ static const char *cname[4] = {
"SelfGet",
"NodeGet",
"InstanceGet",
@@ -1814,39 +1714,39 @@ String VisualScriptPropertyGet::get_text() const {
String prop;
- if (call_mode==CALL_MODE_BASIC_TYPE)
- prop=Variant::get_type_name(basic_type)+"."+property;
- else if (call_mode==CALL_MODE_NODE_PATH)
- prop=String(base_path)+":"+property;
- else if (call_mode==CALL_MODE_SELF)
- prop=property;
- else if (call_mode==CALL_MODE_INSTANCE)
- prop=String(base_type)+":"+property;
+ if (call_mode == CALL_MODE_BASIC_TYPE)
+ prop = Variant::get_type_name(basic_type) + "." + property;
+ else if (call_mode == CALL_MODE_NODE_PATH)
+ prop = String(base_path) + ":" + property;
+ else if (call_mode == CALL_MODE_SELF)
+ prop = property;
+ else if (call_mode == CALL_MODE_INSTANCE)
+ prop = String(base_type) + ":" + property;
return prop;
}
-void VisualScriptPropertyGet::set_base_type(const StringName& p_type) {
+void VisualScriptPropertyGet::set_base_type(const StringName &p_type) {
- if (base_type==p_type)
+ if (base_type == p_type)
return;
- base_type=p_type;
+ base_type = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptPropertyGet::get_base_type() const{
+StringName VisualScriptPropertyGet::get_base_type() const {
return base_type;
}
-void VisualScriptPropertyGet::set_base_script(const String& p_path) {
+void VisualScriptPropertyGet::set_base_script(const String &p_path) {
- if (base_script==p_path)
+ if (base_script == p_path)
return;
- base_script=p_path;
+ base_script = p_path;
_change_notify();
ports_changed_notify();
}
@@ -1856,62 +1756,59 @@ String VisualScriptPropertyGet::get_base_script() const {
return base_script;
}
-
void VisualScriptPropertyGet::_update_cache() {
-
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
//not super efficient..
Variant v;
- if (basic_type==Variant::INPUT_EVENT) {
+ if (basic_type == Variant::INPUT_EVENT) {
InputEvent ev;
- ev.type=event_type;
- v=ev;
+ ev.type = event_type;
+ v = ev;
} else {
Variant::CallError ce;
- v = Variant::construct(basic_type,NULL,0,ce);
+ v = Variant::construct(basic_type, NULL, 0, ce);
}
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
- if (E->get().name==property) {
+ if (E->get().name == property) {
- type_cache=E->get().type;
+ type_cache = E->get().type;
return;
}
}
} else {
-
StringName type;
Ref<Script> script;
- Node *node=NULL;
+ Node *node = NULL;
- if (call_mode==CALL_MODE_NODE_PATH) {
+ if (call_mode == CALL_MODE_NODE_PATH) {
- node=_get_base_node();
+ node = _get_base_node();
if (node) {
- type=node->get_class();
- base_type=type; //cache, too
+ type = node->get_class();
+ base_type = type; //cache, too
script = node->get_script();
}
- } else if (call_mode==CALL_MODE_SELF) {
+ } 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();
+ type = get_visual_script()->get_instance_base_type();
+ base_type = type; //cache, too
+ script = get_visual_script();
}
- } else if (call_mode==CALL_MODE_INSTANCE) {
+ } else if (call_mode == CALL_MODE_INSTANCE) {
- type=base_type;
- if (base_script!=String()) {
+ type = base_type;
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
@@ -1920,53 +1817,51 @@ void VisualScriptPropertyGet::_update_cache() {
if (ResourceCache::has(base_script)) {
- script = Ref<Resource>( ResourceCache::get(base_script) );
+ script = Ref<Resource>(ResourceCache::get(base_script));
} else {
return;
}
}
}
-
- bool valid=false;
+ bool valid = false;
Variant::Type type_ret;
- type_ret=ClassDB::get_property_type(base_type,property,&valid);
+ type_ret = ClassDB::get_property_type(base_type, property, &valid);
if (valid) {
- type_cache=type_ret;
+ type_cache = type_ret;
return; //all dandy
}
if (node) {
- Variant prop = node->get(property,&valid);
+ Variant prop = node->get(property, &valid);
if (valid) {
- type_cache=prop.get_type();
+ type_cache = prop.get_type();
return; //all dandy again
}
}
if (script.is_valid()) {
- type_ret=script->get_static_property_type(property,&valid);
+ type_ret = script->get_static_property_type(property, &valid);
if (valid) {
- type_cache=type_ret;
+ type_cache = type_ret;
return; //all dandy
}
}
}
}
-void VisualScriptPropertyGet::set_property(const StringName& p_type){
+void VisualScriptPropertyGet::set_property(const StringName &p_type) {
- if (property==p_type)
+ if (property == p_type)
return;
- property=p_type;
-
+ property = p_type;
_update_cache();
_change_notify();
@@ -1974,16 +1869,15 @@ void VisualScriptPropertyGet::set_property(const StringName& p_type){
}
StringName VisualScriptPropertyGet::get_property() const {
-
return property;
}
-void VisualScriptPropertyGet::set_base_path(const NodePath& p_type) {
+void VisualScriptPropertyGet::set_base_path(const NodePath &p_type) {
- if (base_path==p_type)
+ if (base_path == p_type)
return;
- base_path=p_type;
+ base_path = p_type;
_change_notify();
_update_base_type();
ports_changed_notify();
@@ -1994,48 +1888,42 @@ 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;
+ call_mode = p_mode;
_change_notify();
_update_base_type();
ports_changed_notify();
-
}
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;
-
+ basic_type = p_type;
_change_notify();
ports_changed_notify();
}
-Variant::Type VisualScriptPropertyGet::get_basic_type() const{
+Variant::Type VisualScriptPropertyGet::get_basic_type() const {
return basic_type;
}
-
void VisualScriptPropertyGet::set_event_type(InputEvent::Type p_type) {
- if (event_type==p_type)
+ if (event_type == p_type)
return;
- event_type=p_type;
- if(call_mode==CALL_MODE_BASIC_TYPE) {
+ event_type = p_type;
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
_update_cache();
}
_change_notify();
@@ -2043,14 +1931,13 @@ void VisualScriptPropertyGet::set_event_type(InputEvent::Type p_type) {
ports_changed_notify();
}
-InputEvent::Type VisualScriptPropertyGet::get_event_type() const{
+InputEvent::Type VisualScriptPropertyGet::get_event_type() const {
return event_type;
}
-
void VisualScriptPropertyGet::_set_type_cache(Variant::Type p_type) {
- type_cache=p_type;
+ type_cache = p_type;
}
Variant::Type VisualScriptPropertyGet::_get_type_cache() const {
@@ -2058,61 +1945,59 @@ Variant::Type VisualScriptPropertyGet::_get_type_cache() const {
return type_cache;
}
+void VisualScriptPropertyGet::_validate_property(PropertyInfo &property) const {
-void VisualScriptPropertyGet::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="property/base_type") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "property/base_type") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
- if (property.name=="property/base_script") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=0;
+ if (property.name == "property/base_script") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = 0;
}
}
- if (property.name=="property/basic_type") {
- if (call_mode!=CALL_MODE_BASIC_TYPE) {
- property.usage=0;
+ if (property.name == "property/basic_type") {
+ if (call_mode != CALL_MODE_BASIC_TYPE) {
+ property.usage = 0;
}
}
- if (property.name=="property/event_type") {
- if (call_mode!=CALL_MODE_BASIC_TYPE || basic_type!=Variant::INPUT_EVENT) {
- property.usage=0;
+ if (property.name == "property/event_type") {
+ if (call_mode != CALL_MODE_BASIC_TYPE || basic_type != Variant::INPUT_EVENT) {
+ property.usage = 0;
}
}
- if (property.name=="property/node_path") {
- if (call_mode!=CALL_MODE_NODE_PATH) {
- property.usage=0;
+ if (property.name == "property/node_path") {
+ 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
+ property.hint_string = bnode->get_path(); //convert to loong string
} else {
-
}
}
}
- if (property.name=="property/property") {
+ if (property.name == "property/property") {
- if (call_mode==CALL_MODE_BASIC_TYPE) {
+ if (call_mode == CALL_MODE_BASIC_TYPE) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
- property.hint_string=Variant::get_type_name(basic_type);
+ property.hint = PROPERTY_HINT_PROPERTY_OF_VARIANT_TYPE;
+ property.hint_string = Variant::get_type_name(basic_type);
- } else if (call_mode==CALL_MODE_SELF && get_visual_script().is_valid()) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_SCRIPT;
- property.hint_string=itos(get_visual_script()->get_instance_ID());
- } else if (call_mode==CALL_MODE_INSTANCE) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string=base_type;
+ } else if (call_mode == CALL_MODE_SELF && get_visual_script().is_valid()) {
+ property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
+ property.hint_string = itos(get_visual_script()->get_instance_ID());
+ } else if (call_mode == CALL_MODE_INSTANCE) {
+ property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
+ property.hint_string = base_type;
- if (base_script!=String()) {
+ if (base_script != String()) {
if (!ResourceCache::has(base_script) && ScriptServer::edit_request_func) {
ScriptServer::edit_request_func(base_script); //make sure it's loaded
@@ -2120,103 +2005,97 @@ void VisualScriptPropertyGet::_validate_property(PropertyInfo& property) const {
if (ResourceCache::has(base_script)) {
- Ref<Script> script = Ref<Resource>( ResourceCache::get(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());
+ property.hint = PROPERTY_HINT_PROPERTY_OF_SCRIPT;
+ property.hint_string = itos(script->get_instance_ID());
}
}
}
- } else if (call_mode==CALL_MODE_NODE_PATH) {
+ } else if (call_mode == CALL_MODE_NODE_PATH) {
Node *node = _get_base_node();
if (node) {
- property.hint=PROPERTY_HINT_PROPERTY_OF_INSTANCE;
- property.hint_string=itos(node->get_instance_ID());
+ property.hint = PROPERTY_HINT_PROPERTY_OF_INSTANCE;
+ property.hint_string = itos(node->get_instance_ID());
} else {
- property.hint=PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
- property.hint_string=get_base_type();
+ property.hint = PROPERTY_HINT_PROPERTY_OF_BASE_TYPE;
+ property.hint_string = get_base_type();
}
-
}
-
}
-
}
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);
-
- ClassDB::bind_method(D_METHOD("set_base_script","base_script"),&VisualScriptPropertyGet::set_base_script);
- ClassDB::bind_method(D_METHOD("get_base_script"),&VisualScriptPropertyGet::get_base_script);
+ 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);
- ClassDB::bind_method(D_METHOD("set_basic_type","basic_type"),&VisualScriptPropertyGet::set_basic_type);
- ClassDB::bind_method(D_METHOD("get_basic_type"),&VisualScriptPropertyGet::get_basic_type);
+ ClassDB::bind_method(D_METHOD("set_base_script", "base_script"), &VisualScriptPropertyGet::set_base_script);
+ ClassDB::bind_method(D_METHOD("get_base_script"), &VisualScriptPropertyGet::get_base_script);
- ClassDB::bind_method(D_METHOD("_set_type_cache","type_cache"),&VisualScriptPropertyGet::_set_type_cache);
- ClassDB::bind_method(D_METHOD("_get_type_cache"),&VisualScriptPropertyGet::_get_type_cache);
+ ClassDB::bind_method(D_METHOD("set_basic_type", "basic_type"), &VisualScriptPropertyGet::set_basic_type);
+ ClassDB::bind_method(D_METHOD("get_basic_type"), &VisualScriptPropertyGet::get_basic_type);
- ClassDB::bind_method(D_METHOD("set_event_type","event_type"),&VisualScriptPropertyGet::set_event_type);
- ClassDB::bind_method(D_METHOD("get_event_type"),&VisualScriptPropertyGet::get_event_type);
+ ClassDB::bind_method(D_METHOD("_set_type_cache", "type_cache"), &VisualScriptPropertyGet::_set_type_cache);
+ ClassDB::bind_method(D_METHOD("_get_type_cache"), &VisualScriptPropertyGet::_get_type_cache);
+ ClassDB::bind_method(D_METHOD("set_event_type", "event_type"), &VisualScriptPropertyGet::set_event_type);
+ ClassDB::bind_method(D_METHOD("get_event_type"), &VisualScriptPropertyGet::get_event_type);
- ClassDB::bind_method(D_METHOD("set_property","property"),&VisualScriptPropertyGet::set_property);
- ClassDB::bind_method(D_METHOD("get_property"),&VisualScriptPropertyGet::get_property);
+ ClassDB::bind_method(D_METHOD("set_property", "property"), &VisualScriptPropertyGet::set_property);
+ ClassDB::bind_method(D_METHOD("get_property"), &VisualScriptPropertyGet::get_property);
- ClassDB::bind_method(D_METHOD("set_call_mode","mode"),&VisualScriptPropertyGet::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"),&VisualScriptPropertyGet::get_call_mode);
+ ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptPropertyGet::set_call_mode);
+ ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptPropertyGet::get_call_mode);
- ClassDB::bind_method(D_METHOD("set_base_path","base_path"),&VisualScriptPropertyGet::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"),&VisualScriptPropertyGet::get_base_path);
+ ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptPropertyGet::set_base_path);
+ ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptPropertyGet::get_base_path);
String bt;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (i>0)
- bt+=",";
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (i > 0)
+ bt += ",";
- bt+=Variant::get_type_name(Variant::Type(i));
+ bt += Variant::get_type_name(Variant::Type(i));
}
String et;
- for(int i=0;i<InputEvent::TYPE_MAX;i++) {
- if (i>0)
- et+=",";
+ for (int i = 0; i < InputEvent::TYPE_MAX; i++) {
+ if (i > 0)
+ et += ",";
- et+=event_type_names[i];
+ et += event_type_names[i];
}
List<String> script_extensions;
- for(int i=0;i<ScriptServer::get_language_count();i++) {
+ for (int i = 0; i < ScriptServer::get_language_count(); i++) {
ScriptServer::get_language(i)->get_recognized_extensions(&script_extensions);
}
String script_ext_hint;
- for (List<String>::Element *E=script_extensions.front();E;E=E->next()) {
- if (script_ext_hint!=String())
- script_ext_hint+=",";
- script_ext_hint+="."+E->get();
+ for (List<String>::Element *E = script_extensions.front(); E; E = E->next()) {
+ if (script_ext_hint != String())
+ script_ext_hint += ",";
+ script_ext_hint += "." + E->get();
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/set_mode",PROPERTY_HINT_ENUM,"Self,Node Path,Instance,Basic Type"),"set_call_mode","get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/base_script",PROPERTY_HINT_FILE,script_ext_hint),"set_base_script","get_base_script");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/type_cache",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_type_cache","_get_type_cache");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/basic_type",PROPERTY_HINT_ENUM,bt),"set_basic_type","get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"property/event_type",PROPERTY_HINT_ENUM,et),"set_event_type","get_event_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"property/node_path",PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE),"set_base_path","get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"property/property"),"set_property","get_property");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/set_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance,Basic Type"), "set_call_mode", "get_call_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/base_script", PROPERTY_HINT_FILE, script_ext_hint), "set_base_script", "get_base_script");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/type_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_type_cache", "_get_type_cache");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/basic_type", PROPERTY_HINT_ENUM, bt), "set_basic_type", "get_basic_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "property/event_type", PROPERTY_HINT_ENUM, et), "set_event_type", "get_event_type");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "property/node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "property/property"), "set_property", "get_property");
- BIND_CONSTANT( CALL_MODE_SELF );
- BIND_CONSTANT( CALL_MODE_NODE_PATH);
- BIND_CONSTANT( CALL_MODE_INSTANCE);
+ BIND_CONSTANT(CALL_MODE_SELF);
+ BIND_CONSTANT(CALL_MODE_NODE_PATH);
+ BIND_CONSTANT(CALL_MODE_INSTANCE);
}
class VisualScriptNodeInstancePropertyGet : public VisualScriptNodeInstance {
public:
-
-
VisualScriptPropertyGet::CallMode call_mode;
NodePath node_path;
StringName property;
@@ -2224,51 +2103,47 @@ public:
VisualScriptPropertyGet *node;
VisualScriptInstance *instance;
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- virtual int step(const Variant** p_inputs,Variant** p_outputs,StartMode p_start_mode,Variant* p_working_mem,Variant::CallError& r_error,String& r_error_str) {
-
-
-
- switch(call_mode) {
+ switch (call_mode) {
case VisualScriptPropertyGet::CALL_MODE_SELF: {
- Object *object=instance->get_owner_ptr();
+ Object *object = instance->get_owner_ptr();
bool valid;
- *p_outputs[0] = object->get(property,&valid);
+ *p_outputs[0] = object->get(property, &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Invalid index property name.");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Invalid index property name.");
return 0;
}
} break;
case VisualScriptPropertyGet::CALL_MODE_NODE_PATH: {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Base object is not a Node!");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Base object is not a Node!");
return 0;
}
- Node* another = node->get_node(node_path);
+ Node *another = node->get_node(node_path);
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Path does not lead Node!");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Path does not lead Node!");
return 0;
}
bool valid;
-
- *p_outputs[0] = another->get(property,&valid);
+ *p_outputs[0] = another->get(property, &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=vformat(RTR("Invalid index property name '%s' in node %s."),String(property),another->get_name());
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = vformat(RTR("Invalid index property name '%s' in node %s."), String(property), another->get_name());
return 0;
}
@@ -2278,48 +2153,42 @@ public:
bool valid;
Variant v = *p_inputs[0];
- *p_outputs[0] = v.get(property,&valid);
+ *p_outputs[0] = v.get(property, &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("Invalid index property name.");
-
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Invalid index property name.");
}
};
}
return 0;
}
-
-
-
-
};
-VisualScriptNodeInstance* VisualScriptPropertyGet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptPropertyGet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePropertyGet * instance = memnew(VisualScriptNodeInstancePropertyGet );
- instance->node=this;
- instance->instance=p_instance;
- instance->property=property;
- instance->call_mode=call_mode;
- instance->node_path=base_path;
+ VisualScriptNodeInstancePropertyGet *instance = memnew(VisualScriptNodeInstancePropertyGet);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->property = property;
+ instance->call_mode = call_mode;
+ instance->node_path = base_path;
return instance;
}
VisualScriptPropertyGet::VisualScriptPropertyGet() {
- call_mode=CALL_MODE_SELF;
- base_type="Object";
- basic_type=Variant::NIL;
- event_type=InputEvent::NONE;
- type_cache=Variant::NIL;
-
+ call_mode = CALL_MODE_SELF;
+ base_type = "Object";
+ basic_type = Variant::NIL;
+ event_type = InputEvent::NONE;
+ type_cache = Variant::NIL;
}
-template<VisualScriptPropertyGet::CallMode cmode>
-static Ref<VisualScriptNode> create_property_get_node(const String& p_name) {
+template <VisualScriptPropertyGet::CallMode cmode>
+static Ref<VisualScriptNode> create_property_get_node(const String &p_name) {
Ref<VisualScriptPropertyGet> node;
node.instance();
@@ -2327,7 +2196,6 @@ static Ref<VisualScriptNode> create_property_get_node(const String& p_name) {
return node;
}
-
//////////////////////////////////////////
////////////////EMIT//////////////////////
//////////////////////////////////////////
@@ -2337,13 +2205,12 @@ int VisualScriptEmitSignal::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptEmitSignal::has_input_sequence_port() const{
+bool VisualScriptEmitSignal::has_input_sequence_port() const {
return true;
}
-
-int VisualScriptEmitSignal::get_input_value_port_count() const{
+int VisualScriptEmitSignal::get_input_value_port_count() const {
Ref<VisualScript> vs = get_visual_script();
if (vs.is_valid()) {
@@ -2355,9 +2222,8 @@ int VisualScriptEmitSignal::get_input_value_port_count() const{
}
return 0;
-
}
-int VisualScriptEmitSignal::get_output_value_port_count() const{
+int VisualScriptEmitSignal::get_output_value_port_count() const {
return 0;
}
@@ -2366,7 +2232,7 @@ String VisualScriptEmitSignal::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const {
Ref<VisualScript> vs = get_visual_script();
if (vs.is_valid()) {
@@ -2374,19 +2240,17 @@ PropertyInfo VisualScriptEmitSignal::get_input_value_port_info(int p_idx) const{
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));
+ return PropertyInfo(vs->custom_signal_get_argument_type(name, p_idx), vs->custom_signal_get_argument_name(name, p_idx));
}
return PropertyInfo();
-
}
-PropertyInfo VisualScriptEmitSignal::get_output_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 "EmitSignal";
@@ -2394,35 +2258,28 @@ String VisualScriptEmitSignal::get_caption() const {
String VisualScriptEmitSignal::get_text() const {
- return "emit "+String(name);
+ return "emit " + String(name);
}
+void VisualScriptEmitSignal::set_signal(const StringName &p_type) {
-
-void VisualScriptEmitSignal::set_signal(const StringName& p_type){
-
- if (name==p_type)
+ if (name == p_type)
return;
- name=p_type;
+ name = p_type;
_change_notify();
ports_changed_notify();
}
StringName VisualScriptEmitSignal::get_signal() const {
-
return name;
}
+void VisualScriptEmitSignal::_validate_property(PropertyInfo &property) const {
-void VisualScriptEmitSignal::_validate_property(PropertyInfo& property) const {
-
-
-
- if (property.name=="signal/signal") {
- property.hint=PROPERTY_HINT_ENUM;
-
+ if (property.name == "signal/signal") {
+ property.hint = PROPERTY_HINT_ENUM;
List<StringName> sigs;
@@ -2430,37 +2287,30 @@ void VisualScriptEmitSignal::_validate_property(PropertyInfo& property) const {
if (vs.is_valid()) {
vs->get_custom_signal_list(&sigs);
-
}
String ml;
- for (List<StringName>::Element *E=sigs.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = sigs.front(); E; E = E->next()) {
- if (ml!=String())
- ml+=",";
- ml+=E->get();
+ if (ml != String())
+ ml += ",";
+ ml += E->get();
}
- property.hint_string=ml;
+ property.hint_string = ml;
}
-
}
-
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);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"signal/signal"),"set_signal","get_signal");
-
+ ClassDB::bind_method(D_METHOD("set_signal", "name"), &VisualScriptEmitSignal::set_signal);
+ ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptEmitSignal::get_signal);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal/signal"), "set_signal", "get_signal");
}
class VisualScriptNodeInstanceEmitSignal : public VisualScriptNodeInstance {
public:
-
VisualScriptEmitSignal *node;
VisualScriptInstance *instance;
int argcount;
@@ -2470,57 +2320,50 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
-
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
Object *obj = instance->get_owner_ptr();
- obj->emit_signal(name,p_inputs,argcount);
-
+ obj->emit_signal(name, p_inputs, argcount);
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptEmitSignal::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptEmitSignal::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceEmitSignal * instance = memnew(VisualScriptNodeInstanceEmitSignal );
- instance->node=this;
- instance->instance=p_instance;
- instance->name=name;
- instance->argcount=get_input_value_port_count();
+ VisualScriptNodeInstanceEmitSignal *instance = memnew(VisualScriptNodeInstanceEmitSignal);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->name = name;
+ instance->argcount = get_input_value_port_count();
return instance;
}
VisualScriptEmitSignal::VisualScriptEmitSignal() {
}
-
-
-static Ref<VisualScriptNode> create_basic_type_call_node(const String& p_name) {
+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>());
+ ERR_FAIL_COND_V(path.size() < 4, Ref<VisualScriptNode>());
String base_type = path[2];
String method = path[3];
Ref<VisualScriptFunctionCall> node;
node.instance();
- Variant::Type type=Variant::VARIANT_MAX;
+ Variant::Type type = Variant::VARIANT_MAX;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- if (Variant::get_type_name(Variant::Type(i))==base_type) {
- type=Variant::Type(i);
+ if (Variant::get_type_name(Variant::Type(i)) == base_type) {
+ type = Variant::Type(i);
break;
}
}
- ERR_FAIL_COND_V(type==Variant::VARIANT_MAX,Ref<VisualScriptNode>());
-
+ ERR_FAIL_COND_V(type == Variant::VARIANT_MAX, Ref<VisualScriptNode>());
node->set_call_mode(VisualScriptFunctionCall::CALL_MODE_BASIC_TYPE);
node->set_basic_type(type);
@@ -2529,29 +2372,27 @@ static Ref<VisualScriptNode> create_basic_type_call_node(const String& p_name) {
return node;
}
-
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>);
+ 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>);
//VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_self",create_script_call_node<VisualScriptScriptCall::CALL_MODE_SELF>);
//VisualScriptLanguage::singleton->add_register_func("functions/call_script/call_node",create_script_call_node<VisualScriptScriptCall::CALL_MODE_NODE_PATH>);
- VisualScriptLanguage::singleton->add_register_func("functions/emit_signal",create_node_generic<VisualScriptEmitSignal>);
-
+ VisualScriptLanguage::singleton->add_register_func("functions/emit_signal", create_node_generic<VisualScriptEmitSignal>);
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
Variant::Type t = Variant::Type(i);
String type_name = Variant::get_type_name(t);
Variant::CallError ce;
- Variant vt = Variant::construct(t,NULL,0,ce);
+ Variant vt = Variant::construct(t, NULL, 0, ce);
List<MethodInfo> ml;
vt.get_method_list(&ml);
- for (List<MethodInfo>::Element *E=ml.front();E;E=E->next()) {
- VisualScriptLanguage::singleton->add_register_func("functions/by_type/"+type_name+"/"+E->get().name,create_basic_type_call_node);
+ for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) {
+ VisualScriptLanguage::singleton->add_register_func("functions/by_type/" + type_name + "/" + E->get().name, create_basic_type_call_node);
}
}
}
diff --git a/modules/visual_script/visual_script_func_nodes.h b/modules/visual_script/visual_script_func_nodes.h
index 7c1d4511cb..3f82edc5f0 100644
--- a/modules/visual_script/visual_script_func_nodes.h
+++ b/modules/visual_script/visual_script_func_nodes.h
@@ -31,10 +31,9 @@
#include "visual_script.h"
-
class VisualScriptFunctionCall : public VisualScriptNode {
- GDCLASS(VisualScriptFunctionCall,VisualScriptNode)
+ GDCLASS(VisualScriptFunctionCall, VisualScriptNode)
public:
enum CallMode {
CALL_MODE_SELF,
@@ -53,7 +52,6 @@ public:
};
private:
-
CallMode call_mode;
StringName base_type;
String base_script;
@@ -65,34 +63,29 @@ private:
StringName singleton;
bool validate;
-
Node *_get_base_node() const;
StringName _get_base_type() const;
MethodInfo method_cache;
void _update_method_cache();
- void _set_argument_cache(const Dictionary& p_args);
+ void _set_argument_cache(const Dictionary &p_args);
Dictionary _get_argument_cache() const;
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -103,22 +96,21 @@ public:
void set_basic_type(Variant::Type p_type);
Variant::Type get_basic_type() const;
- void set_base_type(const StringName& p_type);
+ void set_base_type(const StringName &p_type);
StringName get_base_type() const;
- void set_base_script(const String& p_path);
+ void set_base_script(const String &p_path);
String get_base_script() const;
- void set_singleton(const StringName& p_type);
+ void set_singleton(const StringName &p_type);
StringName get_singleton() const;
- void set_function(const StringName& p_type);
+ void set_function(const StringName &p_type);
StringName get_function() const;
- void set_base_path(const NodePath& p_type);
+ void set_base_path(const NodePath &p_type);
NodePath get_base_path() const;
-
void set_call_mode(CallMode p_mode);
CallMode get_call_mode() const;
@@ -131,21 +123,19 @@ public:
void set_rpc_call_mode(RPCCallMode p_mode);
RPCCallMode get_rpc_call_mode() 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);
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptFunctionCall();
};
-VARIANT_ENUM_CAST(VisualScriptFunctionCall::CallMode );
-VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode );
-
+VARIANT_ENUM_CAST(VisualScriptFunctionCall::CallMode);
+VARIANT_ENUM_CAST(VisualScriptFunctionCall::RPCCallMode);
class VisualScriptPropertySet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertySet,VisualScriptNode)
+ GDCLASS(VisualScriptPropertySet, VisualScriptNode)
public:
enum CallMode {
CALL_MODE_SELF,
@@ -153,14 +143,13 @@ public:
CALL_MODE_INSTANCE,
CALL_MODE_BASIC_TYPE,
-
};
-private:
+private:
PropertyInfo type_cache;
CallMode call_mode;
- Variant::Type basic_type;
+ Variant::Type basic_type;
StringName base_type;
String base_script;
NodePath base_path;
@@ -174,28 +163,23 @@ private:
void _update_cache();
- void _set_type_cache(const Dictionary& p_type);
+ void _set_type_cache(const Dictionary &p_type);
Dictionary _get_type_cache() const;
-
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -203,10 +187,10 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "functions"; }
- void set_base_type(const StringName& p_type);
+ void set_base_type(const StringName &p_type);
StringName get_base_type() const;
- void set_base_script(const String& p_path);
+ void set_base_script(const String &p_path);
String get_base_script() const;
void set_basic_type(Variant::Type p_type);
@@ -215,28 +199,26 @@ public:
void set_event_type(InputEvent::Type p_type);
InputEvent::Type get_event_type() const;
- void set_property(const StringName& p_type);
+ void set_property(const StringName &p_type);
StringName get_property() const;
- void set_base_path(const NodePath& p_type);
+ void set_base_path(const NodePath &p_type);
NodePath get_base_path() const;
void set_call_mode(CallMode p_mode);
CallMode get_call_mode() 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);
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptPropertySet();
};
-VARIANT_ENUM_CAST(VisualScriptPropertySet::CallMode );
-
+VARIANT_ENUM_CAST(VisualScriptPropertySet::CallMode);
class VisualScriptPropertyGet : public VisualScriptNode {
- GDCLASS(VisualScriptPropertyGet,VisualScriptNode)
+ GDCLASS(VisualScriptPropertyGet, VisualScriptNode)
public:
enum CallMode {
CALL_MODE_SELF,
@@ -245,8 +227,8 @@ public:
CALL_MODE_BASIC_TYPE,
};
-private:
+private:
Variant::Type type_cache;
CallMode call_mode;
@@ -267,23 +249,19 @@ private:
Variant::Type _get_type_cache() const;
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -291,10 +269,10 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "functions"; }
- void set_base_type(const StringName& p_type);
+ void set_base_type(const StringName &p_type);
StringName get_base_type() const;
- void set_base_script(const String& p_path);
+ void set_base_script(const String &p_path);
String get_base_script() const;
void set_basic_type(Variant::Type p_type);
@@ -303,55 +281,43 @@ public:
void set_event_type(InputEvent::Type p_type);
InputEvent::Type get_event_type() const;
- void set_property(const StringName& p_type);
+ void set_property(const StringName &p_type);
StringName get_property() const;
- void set_base_path(const NodePath& p_type);
+ void set_base_path(const NodePath &p_type);
NodePath get_base_path() const;
void set_call_mode(CallMode p_mode);
CallMode get_call_mode() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptPropertyGet();
};
-
-
-
-
-VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode );
-
-
+VARIANT_ENUM_CAST(VisualScriptPropertyGet::CallMode);
class VisualScriptEmitSignal : public VisualScriptNode {
- GDCLASS(VisualScriptEmitSignal,VisualScriptNode)
+ GDCLASS(VisualScriptEmitSignal, VisualScriptNode)
private:
-
StringName name;
-
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -359,19 +325,14 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "functions"; }
- void set_signal(const StringName& p_type);
+ void set_signal(const StringName &p_type);
StringName get_signal() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
-
-
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptEmitSignal();
};
-
-
void register_visual_script_func_nodes();
#endif // VISUAL_SCRIPT_FUNC_NODES_H
diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp
index 824dfe88a9..68bd1e6d4c 100644
--- a/modules/visual_script/visual_script_nodes.cpp
+++ b/modules/visual_script/visual_script_nodes.cpp
@@ -28,157 +28,146 @@
/*************************************************************************/
#include "visual_script_nodes.h"
-#include "global_constants.h"
#include "global_config.h"
-#include "scene/main/scene_main_loop.h"
+#include "global_constants.h"
+#include "os/input.h"
#include "os/os.h"
#include "scene/main/node.h"
-#include "os/input.h"
+#include "scene/main/scene_main_loop.h"
//////////////////////////////////////////
////////////////FUNCTION//////////////////
//////////////////////////////////////////
+bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value) {
-bool VisualScriptFunction::_set(const StringName& p_name, const Variant& p_value) {
-
-
- if (p_name=="argument_count") {
+ if (p_name == "argument_count") {
- int new_argc=p_value;
+ int new_argc = p_value;
int argc = arguments.size();
- if (argc==new_argc)
+ if (argc == new_argc)
return true;
arguments.resize(new_argc);
- for(int i=argc;i<new_argc;i++) {
- arguments[i].name="arg"+itos(i+1);
- arguments[i].type=Variant::NIL;
+ for (int i = argc; i < new_argc; i++) {
+ arguments[i].name = "arg" + itos(i + 1);
+ arguments[i].type = Variant::NIL;
}
ports_changed_notify();
_change_notify();
return true;
}
if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/",1).to_int()-1;
- ERR_FAIL_INDEX_V(idx,arguments.size(),false);
- String what = String(p_name).get_slice("/",2);
- if (what=="type") {
+ int idx = String(p_name).get_slice("/", 1).to_int() - 1;
+ ERR_FAIL_INDEX_V(idx, arguments.size(), false);
+ String what = String(p_name).get_slice("/", 2);
+ if (what == "type") {
Variant::Type new_type = Variant::Type(int(p_value));
- arguments[idx].type=new_type;
+ arguments[idx].type = new_type;
ports_changed_notify();
return true;
}
- if (what=="name") {
+ if (what == "name") {
- arguments[idx].name=p_value;
+ arguments[idx].name = p_value;
ports_changed_notify();
return true;
}
-
-
}
- if (p_name=="stack/stackless") {
+ if (p_name == "stack/stackless") {
set_stack_less(p_value);
return true;
}
- if (p_name=="stack/size") {
- stack_size=p_value;
+ if (p_name == "stack/size") {
+ stack_size = p_value;
return true;
}
- if (p_name=="rpc/mode") {
- rpc_mode=ScriptInstance::RPCMode(int(p_value));
+ if (p_name == "rpc/mode") {
+ rpc_mode = ScriptInstance::RPCMode(int(p_value));
return true;
}
return false;
}
-bool VisualScriptFunction::_get(const StringName& p_name,Variant &r_ret) const {
+bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const {
-
- if (p_name=="argument_count") {
+ if (p_name == "argument_count") {
r_ret = arguments.size();
return true;
}
if (String(p_name).begins_with("argument/")) {
- int idx = String(p_name).get_slice("/",1).to_int()-1;
- ERR_FAIL_INDEX_V(idx,arguments.size(),false);
- String what = String(p_name).get_slice("/",2);
- if (what=="type") {
+ int idx = String(p_name).get_slice("/", 1).to_int() - 1;
+ ERR_FAIL_INDEX_V(idx, arguments.size(), false);
+ String what = String(p_name).get_slice("/", 2);
+ if (what == "type") {
r_ret = arguments[idx].type;
return true;
}
- if (what=="name") {
+ if (what == "name") {
r_ret = arguments[idx].name;
return true;
}
-
-
-
}
- if (p_name=="stack/stackless") {
- r_ret=stack_less;
+ if (p_name == "stack/stackless") {
+ r_ret = stack_less;
return true;
}
- if (p_name=="stack/size") {
- r_ret=stack_size;
+ if (p_name == "stack/size") {
+ r_ret = stack_size;
return true;
}
- if (p_name=="rpc/mode") {
- r_ret=rpc_mode;
+ if (p_name == "rpc/mode") {
+ r_ret = rpc_mode;
return true;
}
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++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ 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++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- for(int i=0;i<arguments.size();i++) {
- p_list->push_back(PropertyInfo(Variant::INT,"argument/"+itos(i+1)+"/type",PROPERTY_HINT_ENUM,argt));
- p_list->push_back(PropertyInfo(Variant::STRING,"argument/"+itos(i+1)+"/name"));
+ for (int i = 0; i < arguments.size(); i++) {
+ p_list->push_back(PropertyInfo(Variant::INT, "argument/" + itos(i + 1) + "/type", PROPERTY_HINT_ENUM, argt));
+ p_list->push_back(PropertyInfo(Variant::STRING, "argument/" + itos(i + 1) + "/name"));
}
if (!stack_less) {
- p_list->push_back(PropertyInfo(Variant::INT,"stack/size",PROPERTY_HINT_RANGE,"1,100000"));
+ p_list->push_back(PropertyInfo(Variant::INT, "stack/size", PROPERTY_HINT_RANGE, "1,100000"));
}
- p_list->push_back(PropertyInfo(Variant::BOOL,"stack/stackless"));
- p_list->push_back(PropertyInfo(Variant::INT,"rpc/mode",PROPERTY_HINT_ENUM,"Disabled,Remote,Sync,Master,Slave"));
-
+ p_list->push_back(PropertyInfo(Variant::BOOL, "stack/stackless"));
+ p_list->push_back(PropertyInfo(Variant::INT, "rpc/mode", PROPERTY_HINT_ENUM, "Disabled,Remote,Sync,Master,Slave"));
}
-
int VisualScriptFunction::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptFunction::has_input_sequence_port() const{
+bool VisualScriptFunction::has_input_sequence_port() const {
return false;
}
-int VisualScriptFunction::get_input_value_port_count() const{
+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();
}
@@ -188,17 +177,17 @@ String VisualScriptFunction::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const {
ERR_FAIL_V(PropertyInfo());
return 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());
+ ERR_FAIL_INDEX_V(p_idx, arguments.size(), PropertyInfo());
PropertyInfo out;
- out.type=arguments[p_idx].type;
- out.name=arguments[p_idx].name;
+ out.type = arguments[p_idx].type;
+ out.name = arguments[p_idx].name;
return out;
}
@@ -212,53 +201,48 @@ 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){
+void VisualScriptFunction::add_argument(Variant::Type p_type, const String &p_name, int p_index) {
Argument arg;
- arg.name=p_name;
- arg.type=p_type;
- if (p_index>=0)
- arguments.insert(p_index,arg);
+ arg.name = p_name;
+ arg.type = p_type;
+ if (p_index >= 0)
+ arguments.insert(p_index, arg);
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());
+ ERR_FAIL_INDEX(p_argidx, arguments.size());
- arguments[p_argidx].type=p_type;
+ arguments[p_argidx].type = p_type;
ports_changed_notify();
}
Variant::Type VisualScriptFunction::get_argument_type(int p_argidx) const {
- ERR_FAIL_INDEX_V(p_argidx,arguments.size(),Variant::NIL);
+ 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());
+ ERR_FAIL_INDEX(p_argidx, arguments.size());
- arguments[p_argidx].name=p_name;
+ arguments[p_argidx].name = p_name;
ports_changed_notify();
-
}
String VisualScriptFunction::get_argument_name(int p_argidx) const {
- ERR_FAIL_INDEX_V(p_argidx,arguments.size(),String());
+ ERR_FAIL_INDEX_V(p_argidx, arguments.size(), String());
return arguments[p_argidx].name;
-
}
void VisualScriptFunction::remove_argument(int p_argidx) {
- ERR_FAIL_INDEX(p_argidx,arguments.size());
+ ERR_FAIL_INDEX(p_argidx, arguments.size());
arguments.remove(p_argidx);
ports_changed_notify();
-
}
int VisualScriptFunction::get_argument_count() const {
@@ -266,68 +250,62 @@ int VisualScriptFunction::get_argument_count() const {
return arguments.size();
}
-
void VisualScriptFunction::set_rpc_mode(ScriptInstance::RPCMode p_mode) {
- rpc_mode=p_mode;
+ rpc_mode = p_mode;
}
ScriptInstance::RPCMode VisualScriptFunction::get_rpc_mode() const {
return rpc_mode;
}
-
class VisualScriptNodeInstanceFunction : public VisualScriptNodeInstance {
public:
-
VisualScriptFunction *node;
VisualScriptInstance *instance;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
int ac = node->get_argument_count();
- for(int i=0;i<ac;i++) {
+ for (int i = 0; i < ac; i++) {
#ifdef DEBUG_ENABLED
Variant::Type expected = node->get_argument_type(i);
- if (expected!=Variant::NIL) {
- if (!Variant::can_convert_strict(p_inputs[i]->get_type(),expected)) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.expected=expected;
- r_error.argument=i;
+ if (expected != Variant::NIL) {
+ if (!Variant::can_convert_strict(p_inputs[i]->get_type(), expected)) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.expected = expected;
+ r_error.argument = i;
return 0;
}
}
#endif
- *p_outputs[i]=*p_inputs[i];
+ *p_outputs[i] = *p_inputs[i];
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptFunction::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceFunction * instance = memnew(VisualScriptNodeInstanceFunction );
- instance->node=this;
- instance->instance=p_instance;
+ VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction);
+ instance->node = this;
+ instance->instance = p_instance;
return instance;
}
VisualScriptFunction::VisualScriptFunction() {
- stack_size=256;
- stack_less=false;
- rpc_mode=ScriptInstance::RPC_MODE_DISABLED;
+ stack_size = 256;
+ stack_less = false;
+ rpc_mode = ScriptInstance::RPC_MODE_DISABLED;
}
-
void VisualScriptFunction::set_stack_less(bool p_enable) {
- stack_less=p_enable;
+ stack_less = p_enable;
_change_notify();
}
@@ -337,8 +315,8 @@ bool VisualScriptFunction::is_stack_less() const {
void VisualScriptFunction::set_stack_size(int p_size) {
- ERR_FAIL_COND(p_size <1 || p_size>100000);
- stack_size=p_size;
+ ERR_FAIL_COND(p_size < 1 || p_size > 100000);
+ stack_size = p_size;
}
int VisualScriptFunction::get_stack_size() const {
@@ -346,7 +324,6 @@ int VisualScriptFunction::get_stack_size() const {
return stack_size;
}
-
//////////////////////////////////////////
////////////////OPERATOR//////////////////
//////////////////////////////////////////
@@ -356,16 +333,16 @@ int VisualScriptOperator::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptOperator::has_input_sequence_port() const{
+bool VisualScriptOperator::has_input_sequence_port() const {
return false;
}
-int VisualScriptOperator::get_input_value_port_count() const{
+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;
+ 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;
}
@@ -375,51 +352,51 @@ String VisualScriptOperator::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const{
+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,
- {Variant::NIL,Variant::NIL}, //OP_LESS,
- {Variant::NIL,Variant::NIL}, //OP_LESS_EQUAL,
- {Variant::NIL,Variant::NIL}, //OP_GREATER,
- {Variant::NIL,Variant::NIL}, //OP_GREATER_EQUAL,
+ static const Variant::Type port_types[Variant::OP_MAX][2] = {
+ { Variant::NIL, Variant::NIL }, //OP_EQUAL,
+ { Variant::NIL, Variant::NIL }, //OP_NOT_EQUAL,
+ { Variant::NIL, Variant::NIL }, //OP_LESS,
+ { Variant::NIL, Variant::NIL }, //OP_LESS_EQUAL,
+ { Variant::NIL, Variant::NIL }, //OP_GREATER,
+ { Variant::NIL, Variant::NIL }, //OP_GREATER_EQUAL,
//mathematic
- {Variant::NIL,Variant::NIL}, //OP_ADD,
- {Variant::NIL,Variant::NIL}, //OP_SUBSTRACT,
- {Variant::NIL,Variant::NIL}, //OP_MULTIPLY,
- {Variant::NIL,Variant::NIL}, //OP_DIVIDE,
- {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,
+ { Variant::NIL, Variant::NIL }, //OP_ADD,
+ { Variant::NIL, Variant::NIL }, //OP_SUBSTRACT,
+ { Variant::NIL, Variant::NIL }, //OP_MULTIPLY,
+ { Variant::NIL, Variant::NIL }, //OP_DIVIDE,
+ { 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,
- {Variant::INT,Variant::INT}, //OP_BIT_AND,
- {Variant::INT,Variant::INT}, //OP_BIT_OR,
- {Variant::INT,Variant::INT}, //OP_BIT_XOR,
- {Variant::INT,Variant::INT}, //OP_BIT_NEGATE,
+ { Variant::INT, Variant::INT }, //OP_SHIFT_LEFT,
+ { Variant::INT, Variant::INT }, //OP_SHIFT_RIGHT,
+ { Variant::INT, Variant::INT }, //OP_BIT_AND,
+ { Variant::INT, Variant::INT }, //OP_BIT_OR,
+ { Variant::INT, Variant::INT }, //OP_BIT_XOR,
+ { Variant::INT, Variant::INT }, //OP_BIT_NEGATE,
//logic
- {Variant::BOOL,Variant::BOOL}, //OP_AND,
- {Variant::BOOL,Variant::BOOL}, //OP_OR,
- {Variant::BOOL,Variant::BOOL}, //OP_XOR,
- {Variant::BOOL,Variant::BOOL}, //OP_NOT,
+ { Variant::BOOL, Variant::BOOL }, //OP_AND,
+ { Variant::BOOL, Variant::BOOL }, //OP_OR,
+ { Variant::BOOL, Variant::BOOL }, //OP_XOR,
+ { Variant::BOOL, Variant::BOOL }, //OP_NOT,
//containment
- {Variant::NIL,Variant::NIL} //OP_IN,
+ { Variant::NIL, Variant::NIL } //OP_IN,
};
- ERR_FAIL_INDEX_V(p_idx,Variant::OP_MAX,PropertyInfo());
+ ERR_FAIL_INDEX_V(p_idx, Variant::OP_MAX, PropertyInfo());
PropertyInfo pinfo;
- pinfo.name=p_idx==0?"A":"B";
- pinfo.type=port_types[op][p_idx];
- if (pinfo.type==Variant::NIL)
- pinfo.type=typed;
+ pinfo.name = p_idx == 0 ? "A" : "B";
+ pinfo.type = port_types[op][p_idx];
+ 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]={
+PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const {
+ static const Variant::Type port_types[Variant::OP_MAX] = {
//comparation
Variant::BOOL, //OP_EQUAL,
Variant::BOOL, //OP_NOT_EQUAL,
@@ -453,15 +430,14 @@ 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)
- pinfo.type=typed;
+ pinfo.name = "";
+ pinfo.type = port_types[op];
+ if (pinfo.type == Variant::NIL)
+ pinfo.type = typed;
return pinfo;
-
}
-static const char* op_names[]={
+static const char *op_names[] = {
//comparation
"Equal", //OP_EQUAL,
"NotEqual", //OP_NOT_EQUAL,
@@ -496,14 +472,12 @@ static const char* op_names[]={
String VisualScriptOperator::get_caption() const {
-
-
return op_names[op];
}
String VisualScriptOperator::get_text() const {
- static const wchar_t* op_names[]={
+ static const wchar_t *op_names[] = {
//comparation
L"A = B", //OP_EQUAL,
L"A \u2260 B", //OP_NOT_EQUAL,
@@ -539,24 +513,23 @@ String VisualScriptOperator::get_text() const {
void VisualScriptOperator::set_operator(Variant::Operator p_op) {
- if (op==p_op)
+ if (op == p_op)
return;
- op=p_op;
+ op = p_op;
ports_changed_notify();
-
}
-Variant::Operator VisualScriptOperator::get_operator() const{
+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;
+ typed = p_op;
ports_changed_notify();
}
@@ -565,87 +538,80 @@ 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);
+ ClassDB::bind_method(D_METHOD("set_operator", "op"), &VisualScriptOperator::set_operator);
+ ClassDB::bind_method(D_METHOD("get_operator"), &VisualScriptOperator::get_operator);
- ClassDB::bind_method(D_METHOD("set_typed","type"),&VisualScriptOperator::set_typed);
- ClassDB::bind_method(D_METHOD("get_typed"),&VisualScriptOperator::get_typed);
+ ClassDB::bind_method(D_METHOD("set_typed", "type"), &VisualScriptOperator::set_typed);
+ ClassDB::bind_method(D_METHOD("get_typed"), &VisualScriptOperator::get_typed);
String types;
- for(int i=0;i<Variant::OP_MAX;i++) {
- if (i>0)
- types+=",";
- types+=op_names[i];
+ for (int i = 0; i < Variant::OP_MAX; i++) {
+ if (i > 0)
+ types += ",";
+ types += op_names[i];
}
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"operator_value/type",PROPERTY_HINT_ENUM,types),"set_operator","get_operator");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"typed_value/typed",PROPERTY_HINT_ENUM,argt),"set_typed","get_typed");
-
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "operator_value/type", PROPERTY_HINT_ENUM, types), "set_operator", "get_operator");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "typed_value/typed", PROPERTY_HINT_ENUM, argt), "set_typed", "get_typed");
}
class VisualScriptNodeInstanceOperator : public VisualScriptNodeInstance {
public:
-
bool unary;
Variant::Operator op;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
bool valid;
if (unary) {
- Variant::evaluate(op,*p_inputs[0],Variant(),*p_outputs[0],valid);
+ 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);
+ Variant::evaluate(op, *p_inputs[0], *p_inputs[1], *p_outputs[0], valid);
}
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- if (p_outputs[0]->get_type()==Variant::STRING) {
- r_error_str=*p_outputs[0];
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ if (p_outputs[0]->get_type() == Variant::STRING) {
+ r_error_str = *p_outputs[0];
} else {
if (unary)
- r_error_str=String(op_names[op])+RTR(": Invalid argument of type: ")+Variant::get_type_name(p_inputs[0]->get_type());
+ r_error_str = String(op_names[op]) + RTR(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type());
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());
+ 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());
}
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptOperator::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceOperator * instance = memnew(VisualScriptNodeInstanceOperator );
- instance->unary=get_input_value_port_count()==1;
- instance->op=op;
+ VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator);
+ instance->unary = get_input_value_port_count() == 1;
+ instance->op = op;
return instance;
}
VisualScriptOperator::VisualScriptOperator() {
- op=Variant::OP_ADD;
- typed=Variant::NIL;
+ op = Variant::OP_ADD;
+ typed = Variant::NIL;
}
-
-
-template<Variant::Operator OP>
-static Ref<VisualScriptNode> create_op_node(const String& p_name) {
+template <Variant::Operator OP>
+static Ref<VisualScriptNode> create_op_node(const String &p_name) {
Ref<VisualScriptOperator> node;
node.instance();
@@ -662,16 +628,16 @@ int VisualScriptVariableGet::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptVariableGet::has_input_sequence_port() const{
+bool VisualScriptVariableGet::has_input_sequence_port() const {
return false;
}
-int VisualScriptVariableGet::get_input_value_port_count() const{
+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;
}
@@ -681,25 +647,24 @@ String VisualScriptVariableGet::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptVariableGet::get_input_value_port_info(int p_idx) const{
+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 VisualScriptVariableGet::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="value";
+ pinfo.name = "value";
if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
- pinfo.type=vinfo.type;
- pinfo.hint=vinfo.hint;
- pinfo.hint_string=vinfo.hint_string;
+ pinfo.type = vinfo.type;
+ pinfo.hint = vinfo.hint;
+ pinfo.hint_string = vinfo.hint_string;
}
return pinfo;
}
-
String VisualScriptVariableGet::get_caption() const {
return "Variable";
@@ -712,83 +677,73 @@ String VisualScriptVariableGet::get_text() const {
void VisualScriptVariableGet::set_variable(StringName p_variable) {
- if (variable==p_variable)
+ if (variable == p_variable)
return;
- variable=p_variable;
+ variable = p_variable;
ports_changed_notify();
-
}
-StringName VisualScriptVariableGet::get_variable() const{
+StringName VisualScriptVariableGet::get_variable() const {
return variable;
}
-void VisualScriptVariableGet::_validate_property(PropertyInfo& property) const {
+void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const {
- if (property.name=="variable/name" && get_visual_script().is_valid()) {
+ if (property.name == "variable/name" && get_visual_script().is_valid()) {
Ref<VisualScript> vs = get_visual_script();
List<StringName> vars;
vs->get_variable_list(&vars);
String vhint;
- for (List<StringName>::Element *E=vars.front();E;E=E->next()) {
- if (vhint!=String())
- vhint+=",";
+ for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
+ if (vhint != String())
+ vhint += ",";
- vhint+=E->get().operator String();
+ vhint += E->get().operator String();
}
- property.hint=PROPERTY_HINT_ENUM;
- property.hint_string=vhint;
+ property.hint = PROPERTY_HINT_ENUM;
+ property.hint_string = vhint;
}
}
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);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"variable/name"),"set_variable","get_variable");
+ ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableGet::set_variable);
+ ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableGet::get_variable);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "variable/name"), "set_variable", "get_variable");
}
class VisualScriptNodeInstanceVariableGet : public VisualScriptNodeInstance {
public:
-
VisualScriptVariableGet *node;
VisualScriptInstance *instance;
StringName variable;
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- virtual int step(const Variant** p_inputs,Variant** p_outputs,StartMode p_start_mode,Variant* p_working_mem,Variant::CallError& r_error,String& r_error_str) {
-
- if (instance->get_variable(variable,p_outputs[0])==false) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("VariableGet not found in script: ")+"'"+String(variable)+"'";
+ if (instance->get_variable(variable, p_outputs[0]) == false) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("VariableGet not found in script: ") + "'" + String(variable) + "'";
return false;
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptVariableGet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptVariableGet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceVariableGet * instance = memnew(VisualScriptNodeInstanceVariableGet );
- instance->node=this;
- instance->instance=p_instance;
- instance->variable=variable;
+ VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->variable = variable;
return instance;
}
VisualScriptVariableGet::VisualScriptVariableGet() {
-
-
}
-
//////////////////////////////////////////
////////////////VARIABLE SET//////////////////
//////////////////////////////////////////
@@ -798,16 +753,16 @@ int VisualScriptVariableSet::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptVariableSet::has_input_sequence_port() const{
+bool VisualScriptVariableSet::has_input_sequence_port() const {
return true;
}
-int VisualScriptVariableSet::get_input_value_port_count() const{
+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;
}
@@ -817,25 +772,24 @@ 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 VisualScriptVariableSet::get_input_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="set";
+ pinfo.name = "set";
if (get_visual_script().is_valid() && get_visual_script()->has_variable(variable)) {
PropertyInfo vinfo = get_visual_script()->get_variable_info(variable);
- pinfo.type=vinfo.type;
- pinfo.hint=vinfo.hint;
- pinfo.hint_string=vinfo.hint_string;
+ pinfo.type = vinfo.type;
+ pinfo.hint = vinfo.hint;
+ pinfo.hint_string = vinfo.hint_string;
}
return pinfo;
}
-PropertyInfo VisualScriptVariableSet::get_output_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 "VariableSet";
@@ -848,87 +802,76 @@ String VisualScriptVariableSet::get_text() const {
void VisualScriptVariableSet::set_variable(StringName p_variable) {
- if (variable==p_variable)
+ if (variable == p_variable)
return;
- variable=p_variable;
+ variable = p_variable;
ports_changed_notify();
-
}
-StringName VisualScriptVariableSet::get_variable() const{
+StringName VisualScriptVariableSet::get_variable() const {
return variable;
}
-void VisualScriptVariableSet::_validate_property(PropertyInfo& property) const {
+void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const {
- if (property.name=="variable/name" && get_visual_script().is_valid()) {
+ if (property.name == "variable/name" && get_visual_script().is_valid()) {
Ref<VisualScript> vs = get_visual_script();
List<StringName> vars;
vs->get_variable_list(&vars);
String vhint;
- for (List<StringName>::Element *E=vars.front();E;E=E->next()) {
- if (vhint!=String())
- vhint+=",";
+ for (List<StringName>::Element *E = vars.front(); E; E = E->next()) {
+ if (vhint != String())
+ vhint += ",";
- vhint+=E->get().operator String();
+ vhint += E->get().operator String();
}
- property.hint=PROPERTY_HINT_ENUM;
- property.hint_string=vhint;
+ property.hint = PROPERTY_HINT_ENUM;
+ property.hint_string = vhint;
}
}
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);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"variable/name"),"set_variable","get_variable");
+ ClassDB::bind_method(D_METHOD("set_variable", "name"), &VisualScriptVariableSet::set_variable);
+ ClassDB::bind_method(D_METHOD("get_variable"), &VisualScriptVariableSet::get_variable);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "variable/name"), "set_variable", "get_variable");
}
class VisualScriptNodeInstanceVariableSet : public VisualScriptNodeInstance {
public:
-
VisualScriptVariableSet *node;
VisualScriptInstance *instance;
StringName variable;
//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,Variant::CallError& r_error,String& r_error_str) {
-
- if (instance->set_variable(variable,*p_inputs[0])==false) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
+ if (instance->set_variable(variable, *p_inputs[0]) == false) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str=RTR("VariableSet not found in script: ")+"'"+String(variable)+"'";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("VariableSet not found in script: ") + "'" + String(variable) + "'";
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptVariableSet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptVariableSet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceVariableSet * instance = memnew(VisualScriptNodeInstanceVariableSet );
- instance->node=this;
- instance->instance=p_instance;
- instance->variable=variable;
+ VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->variable = variable;
return instance;
}
VisualScriptVariableSet::VisualScriptVariableSet() {
-
-
}
-
-
//////////////////////////////////////////
////////////////CONSTANT//////////////////
//////////////////////////////////////////
@@ -938,16 +881,16 @@ int VisualScriptConstant::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptConstant::has_input_sequence_port() const{
+bool VisualScriptConstant::has_input_sequence_port() const {
return false;
}
-int VisualScriptConstant::get_input_value_port_count() const{
+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;
}
@@ -957,20 +900,19 @@ String VisualScriptConstant::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptConstant::get_input_value_port_info(int p_idx) const{
+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 VisualScriptConstant::get_output_value_port_info(int p_idx) const {
PropertyInfo pinfo;
- pinfo.name="get";
- pinfo.type=type;
+ pinfo.name = "get";
+ pinfo.type = type;
return pinfo;
}
-
String VisualScriptConstant::get_caption() const {
return "Constant";
@@ -983,90 +925,82 @@ String VisualScriptConstant::get_text() const {
void VisualScriptConstant::set_constant_type(Variant::Type p_type) {
- if (type==p_type)
+ if (type == p_type)
return;
- type=p_type;
+ type = p_type;
ports_changed_notify();
Variant::CallError ce;
- value=Variant::construct(type,NULL,0,ce);
+ value = Variant::construct(type, NULL, 0, ce);
_change_notify();
-
}
-Variant::Type VisualScriptConstant::get_constant_type() const{
+Variant::Type VisualScriptConstant::get_constant_type() const {
return type;
}
-void VisualScriptConstant::set_constant_value(Variant p_value){
+void VisualScriptConstant::set_constant_value(Variant p_value) {
- if (value==p_value)
+ if (value == p_value)
return;
- value=p_value;
+ 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 {
-
+void VisualScriptConstant::_validate_property(PropertyInfo &property) const {
- if (property.name=="constant/value") {
- property.type=type;
- if (type==Variant::NIL)
- property.usage=0; //do not save if nil
+ if (property.name == "constant/value") {
+ property.type = type;
+ 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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_constant_value","value"),&VisualScriptConstant::set_constant_value);
- ClassDB::bind_method(D_METHOD("get_constant_value"),&VisualScriptConstant::get_constant_value);
+ ClassDB::bind_method(D_METHOD("set_constant_value", "value"), &VisualScriptConstant::set_constant_value);
+ ClassDB::bind_method(D_METHOD("get_constant_value"), &VisualScriptConstant::get_constant_value);
- String argt="Null";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Null";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"constant/type",PROPERTY_HINT_ENUM,argt),"set_constant_type","get_constant_type");
- ADD_PROPERTY(PropertyInfo(Variant::NIL,"constant/value"),"set_constant_value","get_constant_value");
-
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "constant/type", PROPERTY_HINT_ENUM, argt), "set_constant_type", "get_constant_type");
+ ADD_PROPERTY(PropertyInfo(Variant::NIL, "constant/value"), "set_constant_value", "get_constant_value");
}
class VisualScriptNodeInstanceConstant : public VisualScriptNodeInstance {
public:
-
Variant constant;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_outputs[0]=constant;
+ *p_outputs[0] = constant;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptConstant::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptConstant::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceConstant * instance = memnew(VisualScriptNodeInstanceConstant );
- instance->constant=value;
+ VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant);
+ instance->constant = value;
return instance;
}
VisualScriptConstant::VisualScriptConstant() {
- type=Variant::NIL;
-
+ type = Variant::NIL;
}
//////////////////////////////////////////
@@ -1078,16 +1012,16 @@ int VisualScriptPreload::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptPreload::has_input_sequence_port() const{
+bool VisualScriptPreload::has_input_sequence_port() const {
return false;
}
-int VisualScriptPreload::get_input_value_port_count() const{
+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;
}
@@ -1097,23 +1031,22 @@ String VisualScriptPreload::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptPreload::get_input_value_port_info(int p_idx) const{
+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 VisualScriptPreload::get_output_value_port_info(int p_idx) const {
- PropertyInfo pinfo=PropertyInfo(Variant::OBJECT,"res");
+ PropertyInfo pinfo = PropertyInfo(Variant::OBJECT, "res");
if (preload.is_valid()) {
- pinfo.hint=PROPERTY_HINT_RESOURCE_TYPE;
- pinfo.hint_string=preload->get_class();
+ pinfo.hint = PROPERTY_HINT_RESOURCE_TYPE;
+ pinfo.hint_string = preload->get_class();
}
return pinfo;
}
-
String VisualScriptPreload::get_caption() const {
return "Preload";
@@ -1124,7 +1057,7 @@ String VisualScriptPreload::get_text() const {
if (preload.is_valid()) {
if (preload->get_path().is_resource_file()) {
return preload->get_path();
- } else if (preload->get_name()!=String()) {
+ } else if (preload->get_name() != String()) {
return preload->get_name();
} else {
return preload->get_class();
@@ -1134,61 +1067,49 @@ String VisualScriptPreload::get_text() const {
}
}
+void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) {
-void VisualScriptPreload::set_preload(const Ref<Resource>& p_preload){
-
- if (preload==p_preload)
+ if (preload == p_preload)
return;
- preload=p_preload;
+ preload = p_preload;
ports_changed_notify();
}
-Ref<Resource> VisualScriptPreload::get_preload() const{
+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);
- ClassDB::bind_method(D_METHOD("set_preload","resource"),&VisualScriptPreload::set_preload);
- ClassDB::bind_method(D_METHOD("get_preload"),&VisualScriptPreload::get_preload);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"resource",PROPERTY_HINT_RESOURCE_TYPE,"Resource"),"set_preload","get_preload");
-
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), "set_preload", "get_preload");
}
class VisualScriptNodeInstancePreload : public VisualScriptNodeInstance {
public:
-
Ref<Resource> preload;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_outputs[0]=preload;
+ *p_outputs[0] = preload;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptPreload::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptPreload::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstancePreload * instance = memnew(VisualScriptNodeInstancePreload );
- instance->preload=preload;
+ VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload);
+ instance->preload = preload;
return instance;
}
VisualScriptPreload::VisualScriptPreload() {
-
}
-
-
-
//////////////////////////////////////////
////////////////INDEX////////////////////
//////////////////////////////////////////
@@ -1198,16 +1119,16 @@ int VisualScriptIndexGet::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptIndexGet::has_input_sequence_port() const{
+bool VisualScriptIndexGet::has_input_sequence_port() const {
return false;
}
-int VisualScriptIndexGet::get_input_value_port_count() const{
+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;
}
@@ -1217,22 +1138,20 @@ String VisualScriptIndexGet::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const {
- if (p_idx==0) {
- return PropertyInfo(Variant::NIL,"base");
+ if (p_idx == 0) {
+ return PropertyInfo(Variant::NIL, "base");
} else {
- return PropertyInfo(Variant::NIL,"index");
-
+ return PropertyInfo(Variant::NIL, "index");
}
}
-PropertyInfo VisualScriptIndexGet::get_output_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 "IndexGet";
@@ -1243,37 +1162,29 @@ String VisualScriptIndexGet::get_text() const {
return String("get");
}
-
class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance {
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
bool valid;
- *p_outputs[0] = p_inputs[0]->get(*p_inputs[1],&valid);
+ *p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid get: "+p_inputs[0]->get_construct_string();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid get: " + p_inputs[0]->get_construct_string();
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptIndexGet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptIndexGet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIndexGet * instance = memnew(VisualScriptNodeInstanceIndexGet );
+ VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet);
return instance;
}
VisualScriptIndexGet::VisualScriptIndexGet() {
-
-
-
}
//////////////////////////////////////////
@@ -1285,16 +1196,16 @@ int VisualScriptIndexSet::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptIndexSet::has_input_sequence_port() const{
+bool VisualScriptIndexSet::has_input_sequence_port() const {
return true;
}
-int VisualScriptIndexSet::get_input_value_port_count() const{
+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;
}
@@ -1304,25 +1215,23 @@ String VisualScriptIndexSet::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const{
+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){
- return PropertyInfo(Variant::NIL,"index");
+ if (p_idx == 0) {
+ return PropertyInfo(Variant::NIL, "base");
+ } else if (p_idx == 1) {
+ return PropertyInfo(Variant::NIL, "index");
} else {
- return PropertyInfo(Variant::NIL,"value");
-
+ return PropertyInfo(Variant::NIL, "value");
}
}
-PropertyInfo VisualScriptIndexSet::get_output_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 "IndexSet";
@@ -1333,41 +1242,32 @@ String VisualScriptIndexSet::get_text() const {
return String("set");
}
-
class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance {
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
bool valid;
- *p_outputs[0]=*p_inputs[0];
- p_outputs[0]->set(*p_inputs[1],*p_inputs[2],&valid);
+ *p_outputs[0] = *p_inputs[0];
+ p_outputs[0]->set(*p_inputs[1], *p_inputs[2], &valid);
if (!valid) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Invalid set: "+p_inputs[1]->get_construct_string();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid set: " + p_inputs[1]->get_construct_string();
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptIndexSet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptIndexSet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceIndexSet * instance = memnew(VisualScriptNodeInstanceIndexSet );
+ VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet);
return instance;
}
VisualScriptIndexSet::VisualScriptIndexSet() {
-
-
-
}
-
//////////////////////////////////////////
////////////////GLOBALCONSTANT///////////
//////////////////////////////////////////
@@ -1377,16 +1277,16 @@ int VisualScriptGlobalConstant::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptGlobalConstant::has_input_sequence_port() const{
+bool VisualScriptGlobalConstant::has_input_sequence_port() const {
return false;
}
-int VisualScriptGlobalConstant::get_input_value_port_count() const{
+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;
}
@@ -1396,17 +1296,16 @@ String VisualScriptGlobalConstant::get_output_sequence_port_text(int p_port) con
return String();
}
-PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::REAL,"value");
+ return PropertyInfo(Variant::REAL, "value");
}
-
String VisualScriptGlobalConstant::get_caption() const {
return "GlobalConst";
@@ -1419,7 +1318,7 @@ String VisualScriptGlobalConstant::get_text() const {
void VisualScriptGlobalConstant::set_global_constant(int p_which) {
- index=p_which;
+ index = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1428,49 +1327,44 @@ int VisualScriptGlobalConstant::get_global_constant() {
return index;
}
-
class VisualScriptNodeInstanceGlobalConstant : public VisualScriptNodeInstance {
public:
-
int index;
//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,Variant::CallError& r_error,String& r_error_str) {
-
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
*p_outputs[0] = GlobalConstants::get_global_constant_value(index);
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptGlobalConstant::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptGlobalConstant::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceGlobalConstant * instance = memnew(VisualScriptNodeInstanceGlobalConstant );
- instance->index=index;
+ 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);
+ 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++) {
+ for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
- if (i>0)
- cc+=",";
- cc+=GlobalConstants::get_global_constant_name(i);
+ if (i > 0)
+ cc += ",";
+ cc += GlobalConstants::get_global_constant_name(i);
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"constant",PROPERTY_HINT_ENUM,cc),"set_global_constant","get_global_constant");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_global_constant", "get_global_constant");
}
VisualScriptGlobalConstant::VisualScriptGlobalConstant() {
- index=0;
+ index = 0;
}
//////////////////////////////////////////
@@ -1482,16 +1376,16 @@ int VisualScriptClassConstant::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptClassConstant::has_input_sequence_port() const{
+bool VisualScriptClassConstant::has_input_sequence_port() const {
return false;
}
-int VisualScriptClassConstant::get_input_value_port_count() const{
+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;
}
@@ -1501,17 +1395,16 @@ String VisualScriptClassConstant::get_output_sequence_port_text(int p_port) cons
return String();
}
-PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::INT,"value");
+ return PropertyInfo(Variant::INT, "value");
}
-
String VisualScriptClassConstant::get_caption() const {
return "ClassConst";
@@ -1519,12 +1412,12 @@ String VisualScriptClassConstant::get_caption() const {
String VisualScriptClassConstant::get_text() const {
- return String(base_type)+"."+String(name);
+ return String(base_type) + "." + String(name);
}
-void VisualScriptClassConstant::set_class_constant(const StringName& p_which) {
+void VisualScriptClassConstant::set_class_constant(const StringName &p_which) {
- name=p_which;
+ name = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1533,10 +1426,9 @@ StringName VisualScriptClassConstant::get_class_constant() {
return name;
}
+void VisualScriptClassConstant::set_base_type(const StringName &p_which) {
-void VisualScriptClassConstant::set_base_type(const StringName& p_which) {
-
- base_type=p_which;
+ base_type = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1547,67 +1439,63 @@ StringName VisualScriptClassConstant::get_base_type() {
class VisualScriptNodeInstanceClassConstant : public VisualScriptNodeInstance {
public:
-
int value;
bool valid;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
if (!valid) {
- r_error_str="Invalid constant name, pick a valid class constant.";
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid constant name, pick a valid class constant.";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
*p_outputs[0] = value;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptClassConstant::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptClassConstant::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceClassConstant * instance = memnew(VisualScriptNodeInstanceClassConstant );
- instance->value=ClassDB::get_integer_constant(base_type,name,&instance->valid);
+ VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant);
+ instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid);
return instance;
}
-void VisualScriptClassConstant::_validate_property(PropertyInfo& property) const {
+void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const {
- if (property.name=="constant") {
+ if (property.name == "constant") {
List<String> constants;
- ClassDB::get_integer_constant_list(base_type,&constants,true);
+ ClassDB::get_integer_constant_list(base_type, &constants, true);
- property.hint_string="";
- for(List<String>::Element *E=constants.front();E;E=E->next()) {
- if (property.hint_string!=String()) {
- property.hint_string+=",";
+ property.hint_string = "";
+ for (List<String>::Element *E = constants.front(); E; E = E->next()) {
+ if (property.hint_string != String()) {
+ property.hint_string += ",";
}
- property.hint_string+=E->get();
+ property.hint_string += E->get();
}
}
}
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_base_type","name"),&VisualScriptClassConstant::set_base_type);
- ClassDB::bind_method(D_METHOD("get_base_type"),&VisualScriptClassConstant::get_base_type);
+ ClassDB::bind_method(D_METHOD("set_base_type", "name"), &VisualScriptClassConstant::set_base_type);
+ ClassDB::bind_method(D_METHOD("get_base_type"), &VisualScriptClassConstant::get_base_type);
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"constant",PROPERTY_HINT_ENUM,""),"set_class_constant","get_class_constant");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant", PROPERTY_HINT_ENUM, ""), "set_class_constant", "get_class_constant");
}
VisualScriptClassConstant::VisualScriptClassConstant() {
- base_type="Object";
+ base_type = "Object";
}
-
//////////////////////////////////////////
////////////////BASICTYPECONSTANT///////////
//////////////////////////////////////////
@@ -1617,16 +1505,16 @@ int VisualScriptBasicTypeConstant::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptBasicTypeConstant::has_input_sequence_port() const{
+bool VisualScriptBasicTypeConstant::has_input_sequence_port() const {
return false;
}
-int VisualScriptBasicTypeConstant::get_input_value_port_count() const{
+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;
}
@@ -1636,17 +1524,16 @@ String VisualScriptBasicTypeConstant::get_output_sequence_port_text(int p_port)
return String();
}
-PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::INT,"value");
+ return PropertyInfo(Variant::INT, "value");
}
-
String VisualScriptBasicTypeConstant::get_caption() const {
return "BasicConst";
@@ -1654,12 +1541,12 @@ String VisualScriptBasicTypeConstant::get_caption() const {
String VisualScriptBasicTypeConstant::get_text() const {
- return Variant::get_type_name(type)+"."+String(name);
+ return Variant::get_type_name(type) + "." + String(name);
}
-void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName& p_which) {
+void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName &p_which) {
- name=p_which;
+ name = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1668,10 +1555,9 @@ StringName VisualScriptBasicTypeConstant::get_basic_type_constant() const {
return name;
}
-
void VisualScriptBasicTypeConstant::set_basic_type(Variant::Type p_which) {
- type=p_which;
+ type = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1682,85 +1568,77 @@ Variant::Type VisualScriptBasicTypeConstant::get_basic_type() const {
class VisualScriptNodeInstanceBasicTypeConstant : public VisualScriptNodeInstance {
public:
-
int value;
bool valid;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
if (!valid) {
- r_error_str="Invalid constant name, pick a valid basic type constant.";
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Invalid constant name, pick a valid basic type constant.";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
}
*p_outputs[0] = value;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptBasicTypeConstant::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceBasicTypeConstant * instance = memnew(VisualScriptNodeInstanceBasicTypeConstant );
- instance->value=Variant::get_numeric_constant_value(type,name,&instance->valid);
+ VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant);
+ instance->value = Variant::get_numeric_constant_value(type, name, &instance->valid);
return instance;
}
-void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo& property) const {
+void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) const {
- if (property.name=="constant") {
+ if (property.name == "constant") {
List<StringName> constants;
- Variant::get_numeric_constants_for_type(type,&constants);
+ Variant::get_numeric_constants_for_type(type, &constants);
- if (constants.size()==0) {
- property.usage=0;
+ if (constants.size() == 0) {
+ property.usage = 0;
return;
}
- property.hint_string="";
- for(List<StringName>::Element *E=constants.front();E;E=E->next()) {
- if (property.hint_string!=String()) {
- property.hint_string+=",";
+ property.hint_string = "";
+ for (List<StringName>::Element *E = constants.front(); E; E = E->next()) {
+ if (property.hint_string != String()) {
+ property.hint_string += ",";
}
- property.hint_string+=String(E->get());
+ property.hint_string += String(E->get());
}
-
}
}
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);
-
- ClassDB::bind_method(D_METHOD("set_basic_type_constant","name"),&VisualScriptBasicTypeConstant::set_basic_type_constant);
- ClassDB::bind_method(D_METHOD("get_basic_type_constant"),&VisualScriptBasicTypeConstant::get_basic_type_constant);
+ 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);
+ ClassDB::bind_method(D_METHOD("set_basic_type_constant", "name"), &VisualScriptBasicTypeConstant::set_basic_type_constant);
+ ClassDB::bind_method(D_METHOD("get_basic_type_constant"), &VisualScriptBasicTypeConstant::get_basic_type_constant);
- String argt="Null";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Null";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"basic_type",PROPERTY_HINT_ENUM,argt),"set_basic_type","get_basic_type");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"constant",PROPERTY_HINT_ENUM,""),"set_basic_type_constant","get_basic_type_constant");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "basic_type", PROPERTY_HINT_ENUM, argt), "set_basic_type", "get_basic_type");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant", PROPERTY_HINT_ENUM, ""), "set_basic_type_constant", "get_basic_type_constant");
}
VisualScriptBasicTypeConstant::VisualScriptBasicTypeConstant() {
- type=Variant::NIL;
+ type = Variant::NIL;
}
-
-
//////////////////////////////////////////
////////////////MATHCONSTANT///////////
//////////////////////////////////////////
-
-const char* VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX]={
+const char *VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX] = {
"One",
"PI",
"PIx2",
@@ -1771,33 +1649,32 @@ const char* VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX]={
"NAN"
};
-double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX]={
+double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = {
1.0,
Math_PI,
- Math_PI*2,
- Math_PI*0.5,
+ Math_PI * 2,
+ Math_PI * 0.5,
2.71828182845904523536,
Math::sqrt(2.0),
Math_INF,
Math_NAN
};
-
int VisualScriptMathConstant::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptMathConstant::has_input_sequence_port() const{
+bool VisualScriptMathConstant::has_input_sequence_port() const {
return false;
}
-int VisualScriptMathConstant::get_input_value_port_count() const{
+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;
}
@@ -1807,17 +1684,16 @@ String VisualScriptMathConstant::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::REAL,"value");
+ return PropertyInfo(Variant::REAL, "value");
}
-
String VisualScriptMathConstant::get_caption() const {
return "MathConst";
@@ -1830,7 +1706,7 @@ String VisualScriptMathConstant::get_text() const {
void VisualScriptMathConstant::set_math_constant(MathConstant p_which) {
- constant=p_which;
+ constant = p_which;
_change_notify();
ports_changed_notify();
}
@@ -1841,50 +1717,44 @@ VisualScriptMathConstant::MathConstant VisualScriptMathConstant::get_math_consta
class VisualScriptNodeInstanceMathConstant : public VisualScriptNodeInstance {
public:
-
float value;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_outputs[0]=value;
+ *p_outputs[0] = value;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptMathConstant::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptMathConstant::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceMathConstant * instance = memnew(VisualScriptNodeInstanceMathConstant );
- instance->value=const_value[constant];
+ 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);
+ 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++) {
+ for (int i = 0; i < MATH_CONSTANT_MAX; i++) {
- if (i>0)
- cc+=",";
- cc+=const_name[i];
+ if (i > 0)
+ cc += ",";
+ cc += const_name[i];
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"constant",PROPERTY_HINT_ENUM,cc),"set_math_constant","get_math_constant");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "constant", PROPERTY_HINT_ENUM, cc), "set_math_constant", "get_math_constant");
}
VisualScriptMathConstant::VisualScriptMathConstant() {
- constant=MATH_CONSTANT_ONE;
+ constant = MATH_CONSTANT_ONE;
}
-
-
//////////////////////////////////////////
////////////////GLOBALSINGLETON///////////
//////////////////////////////////////////
@@ -1894,16 +1764,16 @@ int VisualScriptEngineSingleton::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptEngineSingleton::has_input_sequence_port() const{
+bool VisualScriptEngineSingleton::has_input_sequence_port() const {
return false;
}
-int VisualScriptEngineSingleton::get_input_value_port_count() const{
+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;
}
@@ -1913,17 +1783,16 @@ String VisualScriptEngineSingleton::get_output_sequence_port_text(int p_port) co
return String();
}
-PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"instance");
+ return PropertyInfo(Variant::OBJECT, "instance");
}
-
String VisualScriptEngineSingleton::get_caption() const {
return "EngineSingleton";
@@ -1934,9 +1803,9 @@ String VisualScriptEngineSingleton::get_text() const {
return singleton;
}
-void VisualScriptEngineSingleton::set_singleton(const String& p_string) {
+void VisualScriptEngineSingleton::set_singleton(const String &p_string) {
- singleton=p_string;
+ singleton = p_string;
_change_notify();
ports_changed_notify();
@@ -1946,48 +1815,43 @@ String VisualScriptEngineSingleton::get_singleton() {
return singleton;
}
-
-
class VisualScriptNodeInstanceEngineSingleton : public VisualScriptNodeInstance {
public:
-
- Object* singleton;
+ Object *singleton;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_outputs[0]=singleton;
+ *p_outputs[0] = singleton;
return 0;
}
-
};
-VisualScriptNodeInstance* VisualScriptEngineSingleton::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptEngineSingleton::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceEngineSingleton * instance = memnew(VisualScriptNodeInstanceEngineSingleton );
- instance->singleton=GlobalConfig::get_singleton()->get_singleton_object(singleton);
+ VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton);
+ instance->singleton = GlobalConfig::get_singleton()->get_singleton_object(singleton);
return instance;
}
-VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess* p_inputs, int p_output) const {
+VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess *p_inputs, int p_output) const {
- Object *obj=GlobalConfig::get_singleton()->get_singleton_object(singleton);
+ Object *obj = GlobalConfig::get_singleton()->get_singleton_object(singleton);
TypeGuess tg;
- tg.type=Variant::OBJECT;
+ tg.type = Variant::OBJECT;
if (obj) {
- tg.GDCLASS=obj->get_class();
- tg.script=obj->get_script();
+ tg.GDCLASS = obj->get_class();
+ tg.script = obj->get_script();
}
return tg;
}
-
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);
+ ClassDB::bind_method(D_METHOD("set_singleton", "name"), &VisualScriptEngineSingleton::set_singleton);
+ ClassDB::bind_method(D_METHOD("get_singleton"), &VisualScriptEngineSingleton::get_singleton);
String cc;
@@ -1995,25 +1859,23 @@ void VisualScriptEngineSingleton::_bind_methods() {
GlobalConfig::get_singleton()->get_singletons(&singletons);
- for (List<GlobalConfig::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")
+ for (List<GlobalConfig::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")
continue; //skip these, too simple named
- if (cc!=String())
- cc+=",";
- cc+=E->get().name;
+ if (cc != String())
+ cc += ",";
+ cc += E->get().name;
}
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"constant",PROPERTY_HINT_ENUM,cc),"set_singleton","get_singleton");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "constant", PROPERTY_HINT_ENUM, cc), "set_singleton", "get_singleton");
}
VisualScriptEngineSingleton::VisualScriptEngineSingleton() {
- singleton=String();
+ singleton = String();
}
-
-
//////////////////////////////////////////
////////////////GETNODE///////////
//////////////////////////////////////////
@@ -2023,16 +1885,16 @@ int VisualScriptSceneNode::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptSceneNode::has_input_sequence_port() const{
+bool VisualScriptSceneNode::has_input_sequence_port() const {
return false;
}
-int VisualScriptSceneNode::get_input_value_port_count() const{
+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;
}
@@ -2042,17 +1904,16 @@ String VisualScriptSceneNode::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"node");
+ return PropertyInfo(Variant::OBJECT, "node");
}
-
String VisualScriptSceneNode::get_caption() const {
return "SceneNode";
@@ -2063,9 +1924,9 @@ String VisualScriptSceneNode::get_text() const {
return path.simplified();
}
-void VisualScriptSceneNode::set_node_path(const NodePath& p_path) {
+void VisualScriptSceneNode::set_node_path(const NodePath &p_path) {
- path=p_path;
+ path = p_path;
_change_notify();
ports_changed_notify();
}
@@ -2074,68 +1935,59 @@ NodePath VisualScriptSceneNode::get_node_path() {
return path;
}
-
class VisualScriptNodeInstanceSceneNode : public VisualScriptNodeInstance {
public:
-
VisualScriptSceneNode *node;
VisualScriptInstance *instance;
NodePath path;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Base object is not a Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Base object is not a Node!";
return 0;
}
-
-
- Node* another = node->get_node(path);
+ Node *another = node->get_node(path);
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Path does not lead Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Path does not lead Node!";
return 0;
}
- *p_outputs[0]=another;
+ *p_outputs[0] = another;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSceneNode::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSceneNode * instance = memnew(VisualScriptNodeInstanceSceneNode );
- instance->node=this;
- instance->instance=p_instance;
- instance->path=path;
+ VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->path = path;
return instance;
}
-
-
-
#ifdef TOOLS_ENABLED
-static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const Ref<Script> &script) {
+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 NULL;
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);
+ 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)
return n;
}
@@ -2145,19 +1997,18 @@ static Node* _find_script_node(Node* p_edited_scene,Node* p_current_node,const R
#endif
-VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess* p_inputs, int p_output) const {
-
+VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
- tg.type=Variant::OBJECT;
- tg.GDCLASS="Node";
+ tg.type = Variant::OBJECT;
+ tg.GDCLASS = "Node";
#ifdef TOOLS_ENABLED
Ref<Script> script = get_visual_script();
if (!script.is_valid())
return tg;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return tg;
@@ -2171,33 +2022,31 @@ VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGu
if (!edited_scene)
return tg;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return tg;
- Node* another = script_node->get_node(path);
+ Node *another = script_node->get_node(path);
if (another) {
- tg.GDCLASS=another->get_class();
- tg.script=another->get_script();
+ tg.GDCLASS = another->get_class();
+ tg.script = another->get_script();
}
#endif
return tg;
-
}
-
-void VisualScriptSceneNode::_validate_property(PropertyInfo& property) const {
+void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const {
#ifdef TOOLS_ENABLED
- if (property.name=="node_path") {
+ if (property.name == "node_path") {
Ref<Script> script = get_visual_script();
if (!script.is_valid())
return;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return;
@@ -2211,30 +2060,29 @@ void VisualScriptSceneNode::_validate_property(PropertyInfo& property) const {
if (!edited_scene)
return;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return;
- property.hint_string=script_node->get_path();
+ property.hint_string = script_node->get_path();
}
#endif
}
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);
+ 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);
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"node_path",PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE),"set_node_path","get_node_path");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_node_path", "get_node_path");
}
VisualScriptSceneNode::VisualScriptSceneNode() {
- path=String(".");
+ path = String(".");
}
-
//////////////////////////////////////////
////////////////SceneTree///////////
//////////////////////////////////////////
@@ -2244,16 +2092,16 @@ int VisualScriptSceneTree::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptSceneTree::has_input_sequence_port() const{
+bool VisualScriptSceneTree::has_input_sequence_port() const {
return false;
}
-int VisualScriptSceneTree::get_input_value_port_count() const{
+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;
}
@@ -2263,17 +2111,16 @@ String VisualScriptSceneTree::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"instance");
+ return PropertyInfo(Variant::OBJECT, "instance");
}
-
String VisualScriptSceneTree::get_caption() const {
return "SceneTree";
@@ -2284,68 +2131,60 @@ String VisualScriptSceneTree::get_text() const {
return "";
}
-
class VisualScriptNodeInstanceSceneTree : public VisualScriptNodeInstance {
public:
-
VisualScriptSceneTree *node;
VisualScriptInstance *instance;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Base object is not a Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Base object is not a Node!";
return 0;
}
- SceneTree* tree = node->get_tree();
+ SceneTree *tree = node->get_tree();
if (!tree) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Attempt to get SceneTree while node is not in the active tree.";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Attempt to get SceneTree while node is not in the active tree.";
return 0;
}
- *p_outputs[0]=tree;
+ *p_outputs[0] = tree;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSceneTree::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSceneTree * instance = memnew(VisualScriptNodeInstanceSceneTree );
- instance->node=this;
- instance->instance=p_instance;
+ VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree);
+ instance->node = this;
+ instance->instance = p_instance;
return instance;
}
-VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess* p_inputs, int p_output) const {
+VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const {
TypeGuess tg;
- tg.type=Variant::OBJECT;
- tg.GDCLASS="SceneTree";
+ tg.type = Variant::OBJECT;
+ tg.GDCLASS = "SceneTree";
return tg;
}
-void VisualScriptSceneTree::_validate_property(PropertyInfo& property) const {
-
+void VisualScriptSceneTree::_validate_property(PropertyInfo &property) const {
}
void VisualScriptSceneTree::_bind_methods() {
-
}
VisualScriptSceneTree::VisualScriptSceneTree() {
-
}
-
//////////////////////////////////////////
////////////////RESPATH///////////
//////////////////////////////////////////
@@ -2355,16 +2194,16 @@ int VisualScriptResourcePath::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptResourcePath::has_input_sequence_port() const{
+bool VisualScriptResourcePath::has_input_sequence_port() const {
return false;
}
-int VisualScriptResourcePath::get_input_value_port_count() const{
+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;
}
@@ -2374,17 +2213,16 @@ String VisualScriptResourcePath::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::STRING,"path");
+ return PropertyInfo(Variant::STRING, "path");
}
-
String VisualScriptResourcePath::get_caption() const {
return "ResourcePath";
@@ -2395,9 +2233,9 @@ String VisualScriptResourcePath::get_text() const {
return path;
}
-void VisualScriptResourcePath::set_resource_path(const String& p_path) {
+void VisualScriptResourcePath::set_resource_path(const String &p_path) {
- path=p_path;
+ path = p_path;
_change_notify();
ports_changed_notify();
}
@@ -2406,47 +2244,39 @@ String VisualScriptResourcePath::get_resource_path() {
return path;
}
-
class VisualScriptNodeInstanceResourcePath : public VisualScriptNodeInstance {
public:
-
String path;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
*p_outputs[0] = path;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptResourcePath::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptResourcePath::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceResourcePath * instance = memnew(VisualScriptNodeInstanceResourcePath );
- instance->path=path;
+ 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);
+ 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);
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"path",PROPERTY_HINT_FILE),"set_resource_path","get_resource_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "path", PROPERTY_HINT_FILE), "set_resource_path", "get_resource_path");
}
VisualScriptResourcePath::VisualScriptResourcePath() {
- path="";
+ path = "";
}
-
-
//////////////////////////////////////////
////////////////SELF///////////
//////////////////////////////////////////
@@ -2456,16 +2286,16 @@ int VisualScriptSelf::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptSelf::has_input_sequence_port() const{
+bool VisualScriptSelf::has_input_sequence_port() const {
return false;
}
-int VisualScriptSelf::get_input_value_port_count() const{
+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;
}
@@ -2475,17 +2305,16 @@ String VisualScriptSelf::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(Variant::OBJECT,"instance");
+ return PropertyInfo(Variant::OBJECT, "instance");
}
-
String VisualScriptSelf::get_caption() const {
return "Self";
@@ -2499,56 +2328,46 @@ String VisualScriptSelf::get_text() const {
return "";
}
-
class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
*p_outputs[0] = instance->get_owner_ptr();
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSelf::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSelf::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSelf * instance = memnew(VisualScriptNodeInstanceSelf );
- instance->instance=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 {
+VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const {
VisualScriptSceneNode::TypeGuess tg;
- tg.type=Variant::OBJECT;
- tg.GDCLASS="Object";
+ tg.type = Variant::OBJECT;
+ tg.GDCLASS = "Object";
Ref<Script> script = get_visual_script();
if (!script.is_valid())
return tg;
- tg.GDCLASS=script->get_instance_base_type();
- tg.script=script;
+ tg.GDCLASS = script->get_instance_base_type();
+ tg.script = script;
return tg;
-
-
}
-
void VisualScriptSelf::_bind_methods() {
-
}
VisualScriptSelf::VisualScriptSelf() {
-
-
}
//////////////////////////////////////////
@@ -2563,7 +2382,7 @@ int VisualScriptCustomNode::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptCustomNode::has_input_sequence_port() 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");
@@ -2571,14 +2390,14 @@ bool VisualScriptCustomNode::has_input_sequence_port() const{
return false;
}
-int VisualScriptCustomNode::get_input_value_port_count() 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");
@@ -2589,37 +2408,36 @@ 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);
+ return get_script_instance()->call("_get_output_sequence_port_text", p_port);
}
return String();
}
-PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) 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)));
+ info.type = Variant::Type(int(get_script_instance()->call("_get_input_value_port_type", p_idx)));
}
if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_name")) {
- info.name=get_script_instance()->call("_get_input_value_port_name",p_idx);
+ info.name = get_script_instance()->call("_get_input_value_port_name", p_idx);
}
return info;
}
-PropertyInfo VisualScriptCustomNode::get_output_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)));
+ info.type = Variant::Type(int(get_script_instance()->call("_get_output_value_port_type", p_idx)));
}
if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_name")) {
- info.name=get_script_instance()->call("_get_output_value_port_name",p_idx);
+ info.name = get_script_instance()->call("_get_output_value_port_name", p_idx);
}
return info;
}
-
String VisualScriptCustomNode::get_caption() const {
if (get_script_instance() && get_script_instance()->has_method("_get_caption")) {
@@ -2646,21 +2464,20 @@ String VisualScriptCustomNode::get_category() const {
class VisualScriptNodeInstanceCustomNode : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
VisualScriptCustomNode *node;
int in_count;
int out_count;
int work_mem_size;
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::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)) {
- r_error_str=RTR("Custom node has no _step() method, can't process graph.");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Custom node has no _step() method, can't process graph.");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
#endif
@@ -2670,111 +2487,102 @@ public:
in_values.resize(in_count);
- for(int i=0;i<in_count;i++) {
- in_values[i]=p_inputs[i];
+ for (int i = 0; i < in_count; i++) {
+ in_values[i] = p_inputs[i];
}
out_values.resize(in_count);
work_mem.resize(work_mem_size);
- for(int i=0;i<work_mem_size;i++) {
- work_mem[i]=p_working_mem[i];
+ for (int i = 0; i < work_mem_size; i++) {
+ work_mem[i] = p_working_mem[i];
}
int ret_out;
- Variant ret = node->get_script_instance()->call(VisualScriptLanguage::singleton->_step,in_values,out_values,p_start_mode,work_mem);
- if (ret.get_type()==Variant::STRING) {
- r_error_str=ret;
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ Variant ret = node->get_script_instance()->call(VisualScriptLanguage::singleton->_step, in_values, out_values, p_start_mode, work_mem);
+ if (ret.get_type() == Variant::STRING) {
+ r_error_str = ret;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
} else if (ret.is_num()) {
- ret_out=ret;
+ ret_out = ret;
} else {
- r_error_str=RTR("Invalid return value from _step(), must be integer (seq out), or string (error).");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = RTR("Invalid return value from _step(), must be integer (seq out), or string (error).");
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
- for(int i=0;i<out_count;i++) {
- if (i<out_values.size()) {
- *p_outputs[i]=out_values[i];
+ for (int i = 0; i < out_count; i++) {
+ if (i < out_values.size()) {
+ *p_outputs[i] = out_values[i];
}
}
- for(int i=0;i<work_mem_size;i++) {
- if (i<work_mem.size()) {
- p_working_mem[i]=work_mem[i];
+ for (int i = 0; i < work_mem_size; i++) {
+ if (i < work_mem.size()) {
+ p_working_mem[i] = work_mem[i];
}
}
return ret_out;
-
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptCustomNode::instance(VisualScriptInstance* p_instance) {
-
- VisualScriptNodeInstanceCustomNode * instance = memnew(VisualScriptNodeInstanceCustomNode );
- instance->instance=p_instance;
- instance->in_count=get_input_value_port_count();
- instance->out_count=get_output_value_port_count();
+VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance *p_instance) {
+ VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode);
+ instance->instance = p_instance;
+ instance->in_count = get_input_value_port_count();
+ instance->out_count = get_output_value_port_count();
if (get_script_instance() && get_script_instance()->has_method("_get_working_memory_size")) {
instance->work_mem_size = get_script_instance()->call("_get_working_memory_size");
} else {
- instance->work_mem_size=0;
+ instance->work_mem_size = 0;
}
return instance;
}
-
-
void VisualScriptCustomNode::_bind_methods() {
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_output_sequence_port_count") );
- BIND_VMETHOD( MethodInfo(Variant::BOOL,"_has_input_sequence_port") );
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_sequence_port_count"));
+ BIND_VMETHOD(MethodInfo(Variant::BOOL, "_has_input_sequence_port"));
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_output_sequence_port_text",PropertyInfo(Variant::INT,"idx")) );
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_input_value_port_count") );
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_output_value_port_count") );
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_output_sequence_port_text", PropertyInfo(Variant::INT, "idx")));
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_input_value_port_count"));
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_value_port_count"));
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_input_value_port_type",PropertyInfo(Variant::INT,"idx")) );
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_input_value_port_name",PropertyInfo(Variant::INT,"idx")) );
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_input_value_port_type", PropertyInfo(Variant::INT, "idx")));
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_input_value_port_name", PropertyInfo(Variant::INT, "idx")));
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_output_value_port_type",PropertyInfo(Variant::INT,"idx")) );
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_output_value_port_name",PropertyInfo(Variant::INT,"idx")) );
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_output_value_port_type", PropertyInfo(Variant::INT, "idx")));
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_output_value_port_name", PropertyInfo(Variant::INT, "idx")));
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_caption") );
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_text") );
- BIND_VMETHOD( MethodInfo(Variant::STRING,"_get_category") );
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_caption"));
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_text"));
+ BIND_VMETHOD(MethodInfo(Variant::STRING, "_get_category"));
- BIND_VMETHOD( MethodInfo(Variant::INT,"_get_working_memory_size") );
- BIND_VMETHOD( MethodInfo(Variant::NIL,"_step:Variant",PropertyInfo(Variant::ARRAY,"inputs"),PropertyInfo(Variant::ARRAY,"outputs"),PropertyInfo(Variant::INT,"start_mode"),PropertyInfo(Variant::ARRAY,"working_mem")) );
+ BIND_VMETHOD(MethodInfo(Variant::INT, "_get_working_memory_size"));
+ BIND_VMETHOD(MethodInfo(Variant::NIL, "_step:Variant", PropertyInfo(Variant::ARRAY, "inputs"), PropertyInfo(Variant::ARRAY, "outputs"), PropertyInfo(Variant::INT, "start_mode"), PropertyInfo(Variant::ARRAY, "working_mem")));
- BIND_CONSTANT( START_MODE_BEGIN_SEQUENCE );
- BIND_CONSTANT( START_MODE_CONTINUE_SEQUENCE );
- BIND_CONSTANT( START_MODE_RESUME_YIELD );
-
- BIND_CONSTANT( STEP_PUSH_STACK_BIT );
- BIND_CONSTANT( STEP_GO_BACK_BIT );
- BIND_CONSTANT( STEP_NO_ADVANCE_BIT );
- BIND_CONSTANT( STEP_EXIT_FUNCTION_BIT );
- BIND_CONSTANT( STEP_YIELD_BIT );
+ BIND_CONSTANT(START_MODE_BEGIN_SEQUENCE);
+ BIND_CONSTANT(START_MODE_CONTINUE_SEQUENCE);
+ BIND_CONSTANT(START_MODE_RESUME_YIELD);
+ BIND_CONSTANT(STEP_PUSH_STACK_BIT);
+ BIND_CONSTANT(STEP_GO_BACK_BIT);
+ BIND_CONSTANT(STEP_NO_ADVANCE_BIT);
+ BIND_CONSTANT(STEP_EXIT_FUNCTION_BIT);
+ BIND_CONSTANT(STEP_YIELD_BIT);
}
VisualScriptCustomNode::VisualScriptCustomNode() {
-
-
}
//////////////////////////////////////////
@@ -2786,12 +2594,12 @@ int VisualScriptSubCall::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptSubCall::has_input_sequence_port() const{
+bool VisualScriptSubCall::has_input_sequence_port() const {
return true;
}
-int VisualScriptSubCall::get_input_value_port_count() const{
+int VisualScriptSubCall::get_input_value_port_count() const {
Ref<Script> script = get_script();
@@ -2803,7 +2611,7 @@ int VisualScriptSubCall::get_input_value_port_count() const{
return 0;
}
-int VisualScriptSubCall::get_output_value_port_count() const{
+int VisualScriptSubCall::get_output_value_port_count() const {
return 1;
}
@@ -2813,7 +2621,7 @@ String VisualScriptSubCall::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const{
+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)) {
@@ -2825,7 +2633,7 @@ PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const{
return PropertyInfo();
}
-PropertyInfo VisualScriptSubCall::get_output_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)) {
@@ -2835,18 +2643,16 @@ PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const{
return PropertyInfo();
}
-
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())
return script->get_path().get_file();
@@ -2862,53 +2668,45 @@ String VisualScriptSubCall::get_category() const {
class VisualScriptNodeInstanceSubCall : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
VisualScriptSubCall *subcall;
int input_args;
bool valid;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::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=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Node requires a script with a _subcall(<args>) method to work.";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
- *p_outputs[0]=subcall->call(VisualScriptLanguage::singleton->_subcall,p_inputs,input_args,r_error_str);
+ *p_outputs[0] = subcall->call(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error_str);
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptSubCall::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceSubCall * instance = memnew(VisualScriptNodeInstanceSubCall );
- instance->instance=p_instance;
+ VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall);
+ instance->instance = p_instance;
Ref<Script> script = get_script();
if (script.is_valid() && script->has_method(VisualScriptLanguage::singleton->_subcall)) {
- instance->valid=true;
- instance->input_args=get_input_value_port_count();
+ instance->valid = true;
+ instance->input_args = get_input_value_port_count();
} else {
- instance->valid=false;
+ instance->valid = false;
}
return instance;
}
-
-
void VisualScriptSubCall::_bind_methods() {
- BIND_VMETHOD( MethodInfo(Variant::NIL,"_subcall",PropertyInfo(Variant::NIL,"arguments:Variant")) );
-
+ BIND_VMETHOD(MethodInfo(Variant::NIL, "_subcall", PropertyInfo(Variant::NIL, "arguments:Variant")));
}
VisualScriptSubCall::VisualScriptSubCall() {
-
-
}
//////////////////////////////////////////
@@ -2920,15 +2718,15 @@ int VisualScriptComment::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptComment::has_input_sequence_port() const{
+bool VisualScriptComment::has_input_sequence_port() const {
return false;
}
-int VisualScriptComment::get_input_value_port_count() const{
+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;
}
@@ -2938,69 +2736,63 @@ String VisualScriptComment::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptComment::get_output_value_port_info(int p_idx) const{
+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) {
-
+void VisualScriptComment::set_title(const String &p_title) {
- if (title==p_title)
+ if (title == p_title)
return;
- title=p_title;
+ title = p_title;
ports_changed_notify();
}
-String VisualScriptComment::get_title() const{
+String VisualScriptComment::get_title() const {
return title;
}
-void VisualScriptComment::set_description(const String& p_description){
+void VisualScriptComment::set_description(const String &p_description) {
- if (description==p_description)
+ if (description == p_description)
return;
- description=p_description;
+ 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){
+void VisualScriptComment::set_size(const Size2 &p_size) {
- if (size==p_size)
+ if (size == p_size)
return;
- size=p_size;
+ 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";
@@ -3008,54 +2800,45 @@ String VisualScriptComment::get_category() const {
class VisualScriptNodeInstanceComment : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
//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,Variant::CallError& r_error,String& r_error_str) {
-
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptComment::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptComment::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceComment * instance = memnew(VisualScriptNodeInstanceComment );
- instance->instance=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);
- ClassDB::bind_method(D_METHOD("set_title","title"),&VisualScriptComment::set_title);
- ClassDB::bind_method(D_METHOD("get_title"),&VisualScriptComment::get_title);
+ ClassDB::bind_method(D_METHOD("set_description", "description"), &VisualScriptComment::set_description);
+ ClassDB::bind_method(D_METHOD("get_description"), &VisualScriptComment::get_description);
- ClassDB::bind_method(D_METHOD("set_description","description"),&VisualScriptComment::set_description);
- ClassDB::bind_method(D_METHOD("get_description"),&VisualScriptComment::get_description);
-
- ClassDB::bind_method(D_METHOD("set_size","size"),&VisualScriptComment::set_size);
- ClassDB::bind_method(D_METHOD("get_size"),&VisualScriptComment::get_size);
-
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"title"),"set_title","get_title");
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"description",PROPERTY_HINT_MULTILINE_TEXT),"set_description","get_description");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"size"),"set_size","get_size");
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &VisualScriptComment::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &VisualScriptComment::get_size);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "title"), "set_title", "get_title");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "description", PROPERTY_HINT_MULTILINE_TEXT), "set_description", "get_description");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size");
}
VisualScriptComment::VisualScriptComment() {
- title="Comment";
- size=Size2(150,150);
+ title = "Comment";
+ size = Size2(150, 150);
}
-
//////////////////////////////////////////
////////////////Constructor///////////
//////////////////////////////////////////
@@ -3065,15 +2848,15 @@ int VisualScriptConstructor::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptConstructor::has_input_sequence_port() const{
+bool VisualScriptConstructor::has_input_sequence_port() const {
return false;
}
-int VisualScriptConstructor::get_input_value_port_count() const{
+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;
}
@@ -3083,29 +2866,26 @@ String VisualScriptConstructor::get_output_sequence_port_text(int p_port) const
return "";
}
-PropertyInfo VisualScriptConstructor::get_input_value_port_info(int p_idx) const{
+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{
+PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(type,"value");
+ return PropertyInfo(type, "value");
}
-
String VisualScriptConstructor::get_caption() const {
return "Construct";
}
-
String VisualScriptConstructor::get_text() const {
- return "new "+Variant::get_type_name(type)+"()";
+ return "new " + Variant::get_type_name(type) + "()";
}
-
String VisualScriptConstructor::get_category() const {
return "functions";
@@ -3113,10 +2893,10 @@ String VisualScriptConstructor::get_category() const {
void VisualScriptConstructor::set_constructor_type(Variant::Type p_type) {
- if (type==p_type)
+ if (type == p_type)
return;
- type=p_type;
+ type = p_type;
ports_changed_notify();
}
@@ -3125,9 +2905,9 @@ Variant::Type VisualScriptConstructor::get_constructor_type() const {
return type;
}
-void VisualScriptConstructor::set_constructor(const Dictionary& p_info) {
+void VisualScriptConstructor::set_constructor(const Dictionary &p_info) {
- constructor=MethodInfo::from_dict(p_info);
+ constructor = MethodInfo::from_dict(p_info);
ports_changed_notify();
}
@@ -3136,65 +2916,57 @@ Dictionary VisualScriptConstructor::get_constructor() const {
return constructor;
}
-
class VisualScriptNodeInstanceConstructor : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
Variant::Type type;
int argcount;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
Variant::CallError ce;
- *p_outputs[0]=Variant::construct(type,p_inputs,argcount,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
- r_error_str="Invalid arguments for constructor";
+ *p_outputs[0] = Variant::construct(type, p_inputs, argcount, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
+ r_error_str = "Invalid arguments for constructor";
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptConstructor::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceConstructor * instance = memnew(VisualScriptNodeInstanceConstructor );
- instance->instance=p_instance;
- instance->type=type;
- instance->argcount=constructor.arguments.size();
+ VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor);
+ instance->instance = p_instance;
+ instance->type = type;
+ instance->argcount = constructor.arguments.size();
return instance;
}
-
-
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);
-
- ClassDB::bind_method(D_METHOD("set_constructor","constructor"),&VisualScriptConstructor::set_constructor);
- ClassDB::bind_method(D_METHOD("get_constructor"),&VisualScriptConstructor::get_constructor);
+ 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);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"type",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_constructor_type","get_constructor_type");
- ADD_PROPERTY( PropertyInfo(Variant::DICTIONARY,"constructor",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_constructor","get_constructor");
+ ClassDB::bind_method(D_METHOD("set_constructor", "constructor"), &VisualScriptConstructor::set_constructor);
+ ClassDB::bind_method(D_METHOD("get_constructor"), &VisualScriptConstructor::get_constructor);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_constructor_type", "get_constructor_type");
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "constructor", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_constructor", "get_constructor");
}
VisualScriptConstructor::VisualScriptConstructor() {
- type=Variant::NIL;
-
+ type = Variant::NIL;
}
-static Map<String,Pair<Variant::Type,MethodInfo> > constructor_map;
+static Map<String, Pair<Variant::Type, MethodInfo> > constructor_map;
-static Ref<VisualScriptNode> create_constructor_node(const String& p_name) {
+static Ref<VisualScriptNode> create_constructor_node(const String &p_name) {
- ERR_FAIL_COND_V(!constructor_map.has(p_name),Ref<VisualScriptNode>());
+ ERR_FAIL_COND_V(!constructor_map.has(p_name), Ref<VisualScriptNode>());
Ref<VisualScriptConstructor> vsc;
vsc.instance();
@@ -3213,15 +2985,15 @@ int VisualScriptLocalVar::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptLocalVar::has_input_sequence_port() const{
+bool VisualScriptLocalVar::has_input_sequence_port() const {
return false;
}
-int VisualScriptLocalVar::get_input_value_port_count() const{
+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;
}
@@ -3231,42 +3003,37 @@ String VisualScriptLocalVar::get_output_sequence_port_text(int p_port) const {
return "";
}
-PropertyInfo VisualScriptLocalVar::get_input_value_port_info(int p_idx) const{
+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,"get");
+ return PropertyInfo(type, "get");
}
-
String VisualScriptLocalVar::get_caption() const {
return "LocalVarGet";
}
-
String VisualScriptLocalVar::get_text() const {
return name;
}
-
String VisualScriptLocalVar::get_category() const {
return "data";
}
+void VisualScriptLocalVar::set_var_name(const StringName &p_name) {
-void VisualScriptLocalVar::set_var_name(const StringName& p_name) {
-
- if (name==p_name)
+ if (name == p_name)
return;
- name=p_name;
+ name = p_name;
ports_changed_notify();
-
}
StringName VisualScriptLocalVar::get_var_name() const {
@@ -3276,7 +3043,7 @@ StringName VisualScriptLocalVar::get_var_name() const {
void VisualScriptLocalVar::set_var_type(Variant::Type p_type) {
- type=p_type;
+ type = p_type;
ports_changed_notify();
}
@@ -3285,59 +3052,49 @@ Variant::Type VisualScriptLocalVar::get_var_type() const {
return type;
}
-
class VisualScriptNodeInstanceLocalVar : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
StringName name;
-
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_outputs[0]=*p_working_mem;
+ *p_outputs[0] = *p_working_mem;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptLocalVar::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceLocalVar * instance = memnew(VisualScriptNodeInstanceLocalVar );
- instance->instance=p_instance;
- instance->name=name;
+ VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar);
+ instance->instance = p_instance;
+ instance->name = name;
return instance;
}
-
-
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_var_type","type"),&VisualScriptLocalVar::set_var_type);
- ClassDB::bind_method(D_METHOD("get_var_type"),&VisualScriptLocalVar::get_var_type);
+ ClassDB::bind_method(D_METHOD("set_var_type", "type"), &VisualScriptLocalVar::set_var_type);
+ ClassDB::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVar::get_var_type);
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"variable/name"),"set_var_name","get_var_name");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"variable/type",PROPERTY_HINT_ENUM,argt),"set_var_type","get_var_type");
-
-
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "variable/name"), "set_var_name", "get_var_name");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "variable/type", PROPERTY_HINT_ENUM, argt), "set_var_type", "get_var_type");
}
VisualScriptLocalVar::VisualScriptLocalVar() {
- name="new_local";
- type=Variant::NIL;
-
+ name = "new_local";
+ type = Variant::NIL;
}
//////////////////////////////////////////
@@ -3349,15 +3106,15 @@ int VisualScriptLocalVarSet::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptLocalVarSet::has_input_sequence_port() const{
+bool VisualScriptLocalVarSet::has_input_sequence_port() const {
return true;
}
-int VisualScriptLocalVarSet::get_input_value_port_count() const{
+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;
}
@@ -3367,42 +3124,37 @@ String VisualScriptLocalVarSet::get_output_sequence_port_text(int p_port) const
return "";
}
-PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(type,"set");
+ 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");
+ return PropertyInfo(type, "get");
}
-
String VisualScriptLocalVarSet::get_caption() const {
return "LocalVarSet";
}
-
String VisualScriptLocalVarSet::get_text() const {
return name;
}
-
String VisualScriptLocalVarSet::get_category() const {
return "data";
}
+void VisualScriptLocalVarSet::set_var_name(const StringName &p_name) {
-void VisualScriptLocalVarSet::set_var_name(const StringName& p_name) {
-
- if (name==p_name)
+ if (name == p_name)
return;
- name=p_name;
+ name = p_name;
ports_changed_notify();
-
}
StringName VisualScriptLocalVarSet::get_var_name() const {
@@ -3412,7 +3164,7 @@ StringName VisualScriptLocalVarSet::get_var_name() const {
void VisualScriptLocalVarSet::set_var_type(Variant::Type p_type) {
- type=p_type;
+ type = p_type;
ports_changed_notify();
}
@@ -3421,63 +3173,52 @@ Variant::Type VisualScriptLocalVarSet::get_var_type() const {
return type;
}
-
class VisualScriptNodeInstanceLocalVarSet : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
StringName name;
-
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- *p_working_mem=*p_inputs[0];
- *p_outputs[0]=*p_working_mem;
+ *p_working_mem = *p_inputs[0];
+ *p_outputs[0] = *p_working_mem;
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptLocalVarSet::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceLocalVarSet * instance = memnew(VisualScriptNodeInstanceLocalVarSet );
- instance->instance=p_instance;
- instance->name=name;
+ VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet);
+ instance->instance = p_instance;
+ instance->name = name;
return instance;
}
-
-
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_var_type","type"),&VisualScriptLocalVarSet::set_var_type);
- ClassDB::bind_method(D_METHOD("get_var_type"),&VisualScriptLocalVarSet::get_var_type);
+ ClassDB::bind_method(D_METHOD("set_var_type", "type"), &VisualScriptLocalVarSet::set_var_type);
+ ClassDB::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVarSet::get_var_type);
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"variable/name"),"set_var_name","get_var_name");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"variable/type",PROPERTY_HINT_ENUM,argt),"set_var_type","get_var_type");
-
-
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "variable/name"), "set_var_name", "get_var_name");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "variable/type", PROPERTY_HINT_ENUM, argt), "set_var_type", "get_var_type");
}
VisualScriptLocalVarSet::VisualScriptLocalVarSet() {
- name="new_local";
- type=Variant::NIL;
-
+ name = "new_local";
+ type = Variant::NIL;
}
-
//////////////////////////////////////////
////////////////LocalVar///////////
//////////////////////////////////////////
@@ -3487,15 +3228,15 @@ int VisualScriptInputAction::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptInputAction::has_input_sequence_port() const{
+bool VisualScriptInputAction::has_input_sequence_port() const {
return false;
}
-int VisualScriptInputAction::get_input_value_port_count() const{
+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;
}
@@ -3505,58 +3246,52 @@ String VisualScriptInputAction::get_output_sequence_port_text(int p_port) const
return "";
}
-PropertyInfo VisualScriptInputAction::get_input_value_port_info(int p_idx) const{
+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 {
- return PropertyInfo(Variant::BOOL,"pressed");
+ return PropertyInfo(Variant::BOOL, "pressed");
}
-
String VisualScriptInputAction::get_caption() const {
-
return "Action";
}
-
String VisualScriptInputAction::get_text() const {
- switch(mode) {
+ switch (mode) {
case MODE_PRESSED: {
return name;
} break;
case MODE_RELEASED: {
- return "not "+name;
+ return "not " + name;
} break;
case MODE_JUST_PRESSED: {
- return String(name)+" "+TTR("just pressed");
+ return String(name) + " " + TTR("just pressed");
} break;
case MODE_JUST_RELEASED: {
- return String(name)+" "+TTR("just released");
+ return String(name) + " " + TTR("just released");
} break;
}
return String();
}
-
String VisualScriptInputAction::get_category() const {
return "data";
}
+void VisualScriptInputAction::set_action_name(const StringName &p_name) {
-void VisualScriptInputAction::set_action_name(const StringName& p_name) {
-
- if (name==p_name)
+ if (name == p_name)
return;
- name=p_name;
+ name = p_name;
ports_changed_notify();
-
}
StringName VisualScriptInputAction::get_action_name() const {
@@ -3566,119 +3301,106 @@ StringName VisualScriptInputAction::get_action_name() const {
void VisualScriptInputAction::set_action_mode(Mode p_mode) {
- if (mode==p_mode)
+ if (mode == p_mode)
return;
- mode=p_mode;
+ mode = p_mode;
ports_changed_notify();
-
}
VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const {
return mode;
}
-
class VisualScriptNodeInstanceInputAction : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
StringName action;
VisualScriptInputAction::Mode mode;
-
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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- switch(mode) {
+ switch (mode) {
case VisualScriptInputAction::MODE_PRESSED: {
- *p_outputs[0]=Input::get_singleton()->is_action_pressed(action);
+ *p_outputs[0] = Input::get_singleton()->is_action_pressed(action);
} break;
case VisualScriptInputAction::MODE_RELEASED: {
- *p_outputs[0]=!Input::get_singleton()->is_action_pressed(action);
+ *p_outputs[0] = !Input::get_singleton()->is_action_pressed(action);
} break;
case VisualScriptInputAction::MODE_JUST_PRESSED: {
- *p_outputs[0]=Input::get_singleton()->is_action_just_pressed(action);
+ *p_outputs[0] = Input::get_singleton()->is_action_just_pressed(action);
} break;
- case VisualScriptInputAction:: MODE_JUST_RELEASED: {
- *p_outputs[0]=Input::get_singleton()->is_action_just_released(action);
+ case VisualScriptInputAction::MODE_JUST_RELEASED: {
+ *p_outputs[0] = Input::get_singleton()->is_action_just_released(action);
} break;
-
}
-
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptInputAction::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceInputAction * instance = memnew(VisualScriptNodeInstanceInputAction );
- instance->instance=p_instance;
- instance->action=name;
- instance->mode=mode;
+ VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction);
+ instance->instance = p_instance;
+ instance->action = name;
+ instance->mode = mode;
return instance;
}
-void VisualScriptInputAction::_validate_property(PropertyInfo& property) const {
+void VisualScriptInputAction::_validate_property(PropertyInfo &property) const {
+ if (property.name == "action") {
- if (property.name=="action") {
-
- property.hint=PROPERTY_HINT_ENUM;
+ property.hint = PROPERTY_HINT_ENUM;
String actions;
List<PropertyInfo> pinfo;
GlobalConfig::get_singleton()->get_property_list(&pinfo);
Vector<String> al;
- for(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
- const PropertyInfo &pi=E->get();
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
+ const PropertyInfo &pi = E->get();
if (!pi.name.begins_with("input/"))
continue;
- String name = pi.name.substr(pi.name.find("/")+1,pi.name.length());
-
+ String name = pi.name.substr(pi.name.find("/") + 1, pi.name.length());
al.push_back(name);
}
al.sort();
- for(int i=0;i<al.size();i++) {
- if (actions!=String())
- actions+=",";
- actions+=al[i];
+ for (int i = 0; i < al.size(); i++) {
+ if (actions != String())
+ actions += ",";
+ actions += al[i];
}
- property.hint_string=actions;
+ property.hint_string = actions;
}
}
-
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);
-
- ClassDB::bind_method(D_METHOD("set_action_mode","mode"),&VisualScriptInputAction::set_action_mode);
- ClassDB::bind_method(D_METHOD("get_action_mode"),&VisualScriptInputAction::get_action_mode);
+ 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);
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"action"),"set_action_name","get_action_name");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Pressed,Released,JustPressed,JustReleased"),"set_action_mode","get_action_mode");
+ ClassDB::bind_method(D_METHOD("set_action_mode", "mode"), &VisualScriptInputAction::set_action_mode);
+ ClassDB::bind_method(D_METHOD("get_action_mode"), &VisualScriptInputAction::get_action_mode);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "action"), "set_action_name", "get_action_name");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Pressed,Released,JustPressed,JustReleased"), "set_action_mode", "get_action_mode");
}
VisualScriptInputAction::VisualScriptInputAction() {
- name="";
- mode=MODE_PRESSED;
-
+ name = "";
+ mode = MODE_PRESSED;
}
//////////////////////////////////////////
@@ -3690,15 +3412,15 @@ int VisualScriptDeconstruct::get_output_sequence_port_count() const {
return 0;
}
-bool VisualScriptDeconstruct::has_input_sequence_port() const{
+bool VisualScriptDeconstruct::has_input_sequence_port() const {
return false;
}
-int VisualScriptDeconstruct::get_input_value_port_count() const{
+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();
}
@@ -3708,29 +3430,26 @@ String VisualScriptDeconstruct::get_output_sequence_port_text(int p_port) const
return "";
}
-PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const {
- return PropertyInfo(type,"value");
+ return PropertyInfo(type, "value");
}
-PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const {
- return PropertyInfo(elements[p_idx].type,elements[p_idx].name);
+ return PropertyInfo(elements[p_idx].type, elements[p_idx].name);
}
-
String VisualScriptDeconstruct::get_caption() const {
return "Deconstruct";
}
-
String VisualScriptDeconstruct::get_text() const {
- return "from "+Variant::get_type_name(type)+":";
+ return "from " + Variant::get_type_name(type) + ":";
}
-
String VisualScriptDeconstruct::get_category() const {
return "functions";
@@ -3740,33 +3459,33 @@ void VisualScriptDeconstruct::_update_elements() {
elements.clear();
Variant v;
- if (type==Variant::INPUT_EVENT) {
+ if (type == Variant::INPUT_EVENT) {
InputEvent ie;
- ie.type=input_type;
- v=ie;
+ ie.type = input_type;
+ v = ie;
} else {
Variant::CallError ce;
- v = Variant::construct(type,NULL,0,ce);
+ v = Variant::construct(type, NULL, 0, ce);
}
List<PropertyInfo> pinfo;
v.get_property_list(&pinfo);
- for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
Element e;
- e.name=E->get().name;
- e.type=E->get().type;
+ e.name = E->get().name;
+ e.type = E->get().type;
elements.push_back(e);
}
}
void VisualScriptDeconstruct::set_deconstruct_type(Variant::Type p_type) {
- if (type==p_type)
+ if (type == p_type)
return;
- type=p_type;
+ type = p_type;
_update_elements();
ports_changed_notify();
_change_notify(); //to make input appear/disappear
@@ -3779,10 +3498,10 @@ Variant::Type VisualScriptDeconstruct::get_deconstruct_type() const {
void VisualScriptDeconstruct::set_deconstruct_input_type(InputEvent::Type p_input_type) {
- if (input_type==p_input_type)
+ if (input_type == p_input_type)
return;
- input_type=p_input_type;
+ input_type = p_input_type;
_update_elements();
ports_changed_notify();
}
@@ -3792,20 +3511,20 @@ InputEvent::Type VisualScriptDeconstruct::get_deconstruct_input_type() const {
return input_type;
}
-void VisualScriptDeconstruct::_set_elem_cache(const Array& p_elements) {
+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++) {
- elements[i].name=p_elements[i*2+0];
- elements[i].type=Variant::Type(int(p_elements[i*2+1]));
+ ERR_FAIL_COND(p_elements.size() % 2 == 1);
+ elements.resize(p_elements.size() / 2);
+ for (int i = 0; i < elements.size(); i++) {
+ elements[i].name = p_elements[i * 2 + 0];
+ elements[i].type = Variant::Type(int(p_elements[i * 2 + 1]));
}
}
Array VisualScriptDeconstruct::_get_elem_cache() const {
Array ret;
- for(int i=0;i<elements.size();i++) {
+ for (int i = 0; i < elements.size(); i++) {
ret.push_back(elements[i].name);
ret.push_back(elements[i].type);
}
@@ -3814,183 +3533,168 @@ Array VisualScriptDeconstruct::_get_elem_cache() const {
class VisualScriptNodeInstanceDeconstruct : public VisualScriptNodeInstance {
public:
-
- VisualScriptInstance* instance;
+ VisualScriptInstance *instance;
Vector<StringName> outputs;
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- Variant in=*p_inputs[0];
+ Variant in = *p_inputs[0];
- for(int i=0;i<outputs.size();i++) {
+ for (int i = 0; i < outputs.size(); i++) {
bool valid;
- *p_outputs[i]=in.get(outputs[i],&valid);
+ *p_outputs[i] = in.get(outputs[i], &valid);
if (!valid) {
- r_error_str="Can't obtain element '"+String(outputs[i])+"' from "+Variant::get_type_name(in.get_type());
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Can't obtain element '" + String(outputs[i]) + "' from " + Variant::get_type_name(in.get_type());
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
-
}
return 0;
}
-
-
};
-VisualScriptNodeInstance* VisualScriptDeconstruct::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptDeconstruct::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceDeconstruct * instance = memnew(VisualScriptNodeInstanceDeconstruct );
- instance->instance=p_instance;
+ VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct);
+ instance->instance = p_instance;
instance->outputs.resize(elements.size());
- for(int i=0;i<elements.size();i++) {
- instance->outputs[i]=elements[i].name;
+ for (int i = 0; i < elements.size(); i++) {
+ instance->outputs[i] = elements[i].name;
}
return instance;
}
+void VisualScriptDeconstruct::_validate_property(PropertyInfo &property) const {
-
-void VisualScriptDeconstruct::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="input_type") {
- if (type!=Variant::INPUT_EVENT) {
- property.usage=0;
+ if (property.name == "input_type") {
+ if (type != Variant::INPUT_EVENT) {
+ property.usage = 0;
}
}
}
-
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);
+ 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);
- ClassDB::bind_method(D_METHOD("set_deconstruct_input_type","input_type"),&VisualScriptDeconstruct::set_deconstruct_input_type);
- ClassDB::bind_method(D_METHOD("get_deconstruct_input_type"),&VisualScriptDeconstruct::get_deconstruct_input_type);
+ ClassDB::bind_method(D_METHOD("set_deconstruct_input_type", "input_type"), &VisualScriptDeconstruct::set_deconstruct_input_type);
+ ClassDB::bind_method(D_METHOD("get_deconstruct_input_type"), &VisualScriptDeconstruct::get_deconstruct_input_type);
- ClassDB::bind_method(D_METHOD("_set_elem_cache","_cache"),&VisualScriptDeconstruct::_set_elem_cache);
- ClassDB::bind_method(D_METHOD("_get_elem_cache"),&VisualScriptDeconstruct::_get_elem_cache);
+ ClassDB::bind_method(D_METHOD("_set_elem_cache", "_cache"), &VisualScriptDeconstruct::_set_elem_cache);
+ ClassDB::bind_method(D_METHOD("_get_elem_cache"), &VisualScriptDeconstruct::_get_elem_cache);
- String argt="Any";
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
- argt+=","+Variant::get_type_name(Variant::Type(i));
+ String argt = "Any";
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
+ argt += "," + Variant::get_type_name(Variant::Type(i));
}
- String iet="None,Key,MouseMotion,MouseButton,JoypadMotion,JoypadButton,ScreenTouch,ScreenDrag,Action";
-
- ADD_PROPERTY( PropertyInfo(Variant::INT,"type",PROPERTY_HINT_ENUM,argt),"set_deconstruct_type","get_deconstruct_type");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"input_type",PROPERTY_HINT_ENUM,iet),"set_deconstruct_input_type","get_deconstruct_input_type");
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"elem_cache",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_elem_cache","_get_elem_cache");
+ String iet = "None,Key,MouseMotion,MouseButton,JoypadMotion,JoypadButton,ScreenTouch,ScreenDrag,Action";
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type", PROPERTY_HINT_ENUM, argt), "set_deconstruct_type", "get_deconstruct_type");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "input_type", PROPERTY_HINT_ENUM, iet), "set_deconstruct_input_type", "get_deconstruct_input_type");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "elem_cache", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_elem_cache", "_get_elem_cache");
}
VisualScriptDeconstruct::VisualScriptDeconstruct() {
- type=Variant::NIL;
- input_type=InputEvent::NONE;
-
+ type = Variant::NIL;
+ input_type = InputEvent::NONE;
}
-
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>);
- VisualScriptLanguage::singleton->add_register_func("data/scene_node",create_node_generic<VisualScriptSceneNode>);
- VisualScriptLanguage::singleton->add_register_func("data/scene_tree",create_node_generic<VisualScriptSceneTree>);
- VisualScriptLanguage::singleton->add_register_func("data/resource_path",create_node_generic<VisualScriptResourcePath>);
- VisualScriptLanguage::singleton->add_register_func("data/self",create_node_generic<VisualScriptSelf>);
- VisualScriptLanguage::singleton->add_register_func("data/comment",create_node_generic<VisualScriptComment>);
- VisualScriptLanguage::singleton->add_register_func("data/get_local_variable",create_node_generic<VisualScriptLocalVar>);
- VisualScriptLanguage::singleton->add_register_func("data/set_local_variable",create_node_generic<VisualScriptLocalVarSet>);
- VisualScriptLanguage::singleton->add_register_func("data/preload",create_node_generic<VisualScriptPreload>);
- VisualScriptLanguage::singleton->add_register_func("data/action",create_node_generic<VisualScriptInputAction>);
-
- VisualScriptLanguage::singleton->add_register_func("constants/constant",create_node_generic<VisualScriptConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/math_constant",create_node_generic<VisualScriptMathConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/class_constant",create_node_generic<VisualScriptClassConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/global_constant",create_node_generic<VisualScriptGlobalConstant>);
- VisualScriptLanguage::singleton->add_register_func("constants/basic_type_constant",create_node_generic<VisualScriptBasicTypeConstant>);
-
- VisualScriptLanguage::singleton->add_register_func("custom/custom_node",create_node_generic<VisualScriptCustomNode>);
- VisualScriptLanguage::singleton->add_register_func("custom/sub_call",create_node_generic<VisualScriptSubCall>);
-
- VisualScriptLanguage::singleton->add_register_func("index/get_index",create_node_generic<VisualScriptIndexGet>);
- VisualScriptLanguage::singleton->add_register_func("index/set_index",create_node_generic<VisualScriptIndexSet>);
-
-
- VisualScriptLanguage::singleton->add_register_func("operators/compare/equal",create_op_node<Variant::OP_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/not_equal",create_op_node<Variant::OP_NOT_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/less",create_op_node<Variant::OP_LESS>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/less_equal",create_op_node<Variant::OP_LESS_EQUAL>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/greater",create_op_node<Variant::OP_GREATER>);
- VisualScriptLanguage::singleton->add_register_func("operators/compare/greater_equal",create_op_node<Variant::OP_GREATER_EQUAL>);
+ 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>);
+ VisualScriptLanguage::singleton->add_register_func("data/scene_node", create_node_generic<VisualScriptSceneNode>);
+ VisualScriptLanguage::singleton->add_register_func("data/scene_tree", create_node_generic<VisualScriptSceneTree>);
+ VisualScriptLanguage::singleton->add_register_func("data/resource_path", create_node_generic<VisualScriptResourcePath>);
+ VisualScriptLanguage::singleton->add_register_func("data/self", create_node_generic<VisualScriptSelf>);
+ VisualScriptLanguage::singleton->add_register_func("data/comment", create_node_generic<VisualScriptComment>);
+ VisualScriptLanguage::singleton->add_register_func("data/get_local_variable", create_node_generic<VisualScriptLocalVar>);
+ VisualScriptLanguage::singleton->add_register_func("data/set_local_variable", create_node_generic<VisualScriptLocalVarSet>);
+ VisualScriptLanguage::singleton->add_register_func("data/preload", create_node_generic<VisualScriptPreload>);
+ VisualScriptLanguage::singleton->add_register_func("data/action", create_node_generic<VisualScriptInputAction>);
+
+ VisualScriptLanguage::singleton->add_register_func("constants/constant", create_node_generic<VisualScriptConstant>);
+ VisualScriptLanguage::singleton->add_register_func("constants/math_constant", create_node_generic<VisualScriptMathConstant>);
+ VisualScriptLanguage::singleton->add_register_func("constants/class_constant", create_node_generic<VisualScriptClassConstant>);
+ VisualScriptLanguage::singleton->add_register_func("constants/global_constant", create_node_generic<VisualScriptGlobalConstant>);
+ VisualScriptLanguage::singleton->add_register_func("constants/basic_type_constant", create_node_generic<VisualScriptBasicTypeConstant>);
+
+ VisualScriptLanguage::singleton->add_register_func("custom/custom_node", create_node_generic<VisualScriptCustomNode>);
+ VisualScriptLanguage::singleton->add_register_func("custom/sub_call", create_node_generic<VisualScriptSubCall>);
+
+ VisualScriptLanguage::singleton->add_register_func("index/get_index", create_node_generic<VisualScriptIndexGet>);
+ VisualScriptLanguage::singleton->add_register_func("index/set_index", create_node_generic<VisualScriptIndexSet>);
+
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/equal", create_op_node<Variant::OP_EQUAL>);
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/not_equal", create_op_node<Variant::OP_NOT_EQUAL>);
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/less", create_op_node<Variant::OP_LESS>);
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/less_equal", create_op_node<Variant::OP_LESS_EQUAL>);
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/greater", create_op_node<Variant::OP_GREATER>);
+ VisualScriptLanguage::singleton->add_register_func("operators/compare/greater_equal", create_op_node<Variant::OP_GREATER_EQUAL>);
//mathematic
- VisualScriptLanguage::singleton->add_register_func("operators/math/add",create_op_node<Variant::OP_ADD>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/subtract",create_op_node<Variant::OP_SUBSTRACT>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/multiply",create_op_node<Variant::OP_MULTIPLY>);
- VisualScriptLanguage::singleton->add_register_func("operators/math/divide",create_op_node<Variant::OP_DIVIDE>);
- 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>);
+ VisualScriptLanguage::singleton->add_register_func("operators/math/add", create_op_node<Variant::OP_ADD>);
+ VisualScriptLanguage::singleton->add_register_func("operators/math/subtract", create_op_node<Variant::OP_SUBSTRACT>);
+ VisualScriptLanguage::singleton->add_register_func("operators/math/multiply", create_op_node<Variant::OP_MULTIPLY>);
+ VisualScriptLanguage::singleton->add_register_func("operators/math/divide", create_op_node<Variant::OP_DIVIDE>);
+ 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>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_and",create_op_node<Variant::OP_BIT_AND>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_or",create_op_node<Variant::OP_BIT_OR>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_xor",create_op_node<Variant::OP_BIT_XOR>);
- VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_negate",create_op_node<Variant::OP_BIT_NEGATE>);
+ 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>);
+ VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_and", create_op_node<Variant::OP_BIT_AND>);
+ VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_or", create_op_node<Variant::OP_BIT_OR>);
+ VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_xor", create_op_node<Variant::OP_BIT_XOR>);
+ VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_negate", create_op_node<Variant::OP_BIT_NEGATE>);
//logic
- VisualScriptLanguage::singleton->add_register_func("operators/logic/and",create_op_node<Variant::OP_AND>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/or",create_op_node<Variant::OP_OR>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/xor",create_op_node<Variant::OP_XOR>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/not",create_op_node<Variant::OP_NOT>);
- VisualScriptLanguage::singleton->add_register_func("operators/logic/in",create_op_node<Variant::OP_IN>);
+ VisualScriptLanguage::singleton->add_register_func("operators/logic/and", create_op_node<Variant::OP_AND>);
+ VisualScriptLanguage::singleton->add_register_func("operators/logic/or", create_op_node<Variant::OP_OR>);
+ VisualScriptLanguage::singleton->add_register_func("operators/logic/xor", create_op_node<Variant::OP_XOR>);
+ VisualScriptLanguage::singleton->add_register_func("operators/logic/not", create_op_node<Variant::OP_NOT>);
+ VisualScriptLanguage::singleton->add_register_func("operators/logic/in", create_op_node<Variant::OP_IN>);
- VisualScriptLanguage::singleton->add_register_func("functions/deconstruct",create_node_generic<VisualScriptDeconstruct>);
+ VisualScriptLanguage::singleton->add_register_func("functions/deconstruct", create_node_generic<VisualScriptDeconstruct>);
- for(int i=1;i<Variant::VARIANT_MAX;i++) {
+ for (int i = 1; i < Variant::VARIANT_MAX; i++) {
List<MethodInfo> constructors;
- Variant::get_constructor_list(Variant::Type(i),&constructors);
+ Variant::get_constructor_list(Variant::Type(i), &constructors);
- for(List<MethodInfo>::Element *E=constructors.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = constructors.front(); E; E = E->next()) {
- if (E->get().arguments.size()>0) {
+ 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++) {
- if (j>0)
- name+=", ";
- if (E->get().arguments.size()==1)
- name+=Variant::get_type_name(E->get().arguments[j].type);
+ String name = "functions/constructors/" + Variant::get_type_name(Variant::Type(i)) + " ( ";
+ for (int j = 0; j < E->get().arguments.size(); j++) {
+ if (j > 0)
+ name += ", ";
+ if (E->get().arguments.size() == 1)
+ name += Variant::get_type_name(E->get().arguments[j].type);
else
- name+=E->get().arguments[j].name;
+ name += E->get().arguments[j].name;
}
- name+=") ";
+ name += ") ";
- VisualScriptLanguage::singleton->add_register_func(name,create_constructor_node);
- Pair<Variant::Type,MethodInfo> pair;
- pair.first=Variant::Type(i);
- pair.second=E->get();
- constructor_map[name]=pair;
+ VisualScriptLanguage::singleton->add_register_func(name, create_constructor_node);
+ Pair<Variant::Type, MethodInfo> pair;
+ pair.first = Variant::Type(i);
+ pair.second = E->get();
+ constructor_map[name] = pair;
}
}
}
}
-
-
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 2e7fb0536c..b2fc115660 100644
--- a/modules/visual_script/visual_script_nodes.h
+++ b/modules/visual_script/visual_script_nodes.h
@@ -33,8 +33,7 @@
class VisualScriptFunction : public VisualScriptNode {
- GDCLASS(VisualScriptFunction,VisualScriptNode)
-
+ GDCLASS(VisualScriptFunction, VisualScriptNode)
struct Argument {
String name;
@@ -47,26 +46,20 @@ class VisualScriptFunction : public VisualScriptNode {
int stack_size;
ScriptInstance::RPCMode rpc_mode;
-
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ 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 String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -74,15 +67,14 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "flow_control"; }
- void add_argument(Variant::Type p_type,const String& p_name,int p_index=-1);
- void set_argument_type(int p_argidx,Variant::Type p_type);
+ void add_argument(Variant::Type p_type, const String &p_name, int p_index = -1);
+ void set_argument_type(int p_argidx, Variant::Type p_type);
Variant::Type get_argument_type(int p_argidx) const;
- void set_argument_name(int p_argidx,const String& p_name);
+ void set_argument_name(int p_argidx, const String &p_name);
String get_argument_name(int p_argidx) const;
void remove_argument(int p_argidx);
int get_argument_count() const;
-
void set_stack_less(bool p_enable);
bool is_stack_less() const;
@@ -92,35 +84,30 @@ public:
void set_rpc_mode(ScriptInstance::RPCMode p_mode);
ScriptInstance::RPCMode get_rpc_mode() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptFunction();
};
-
class VisualScriptOperator : public VisualScriptNode {
- GDCLASS(VisualScriptOperator,VisualScriptNode)
-
+ GDCLASS(VisualScriptOperator, VisualScriptNode)
Variant::Type typed;
Variant::Operator op;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -134,35 +121,30 @@ 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);
VisualScriptOperator();
};
-
class VisualScriptVariableGet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableGet,VisualScriptNode)
-
+ GDCLASS(VisualScriptVariableGet, VisualScriptNode)
StringName variable;
-protected:
- virtual void _validate_property(PropertyInfo& property) const;
+protected:
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -173,35 +155,30 @@ public:
void set_variable(StringName p_var);
StringName get_variable() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptVariableGet();
};
-
class VisualScriptVariableSet : public VisualScriptNode {
- GDCLASS(VisualScriptVariableSet,VisualScriptNode)
-
+ GDCLASS(VisualScriptVariableSet, VisualScriptNode)
StringName variable;
-protected:
- virtual void _validate_property(PropertyInfo& property) const;
+protected:
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -212,36 +189,31 @@ public:
void set_variable(StringName p_var);
StringName get_variable() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptVariableSet();
};
-
class VisualScriptConstant : public VisualScriptNode {
- GDCLASS(VisualScriptConstant,VisualScriptNode)
-
+ GDCLASS(VisualScriptConstant, VisualScriptNode)
Variant::Type type;
Variant value;
+
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -255,36 +227,29 @@ 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);
VisualScriptConstant();
};
-
-
class VisualScriptPreload : public VisualScriptNode {
- GDCLASS(VisualScriptPreload,VisualScriptNode)
-
+ GDCLASS(VisualScriptPreload, VisualScriptNode)
Ref<Resource> preload;
-protected:
+protected:
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -292,32 +257,27 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "data"; }
- void set_preload(const Ref<Resource>& p_value);
+ void set_preload(const Ref<Resource> &p_value);
Ref<Resource> get_preload() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptPreload();
};
class VisualScriptIndexGet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexGet,VisualScriptNode)
-
+ GDCLASS(VisualScriptIndexGet, VisualScriptNode)
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -325,30 +285,24 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "operators"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptIndexGet();
};
-
class VisualScriptIndexSet : public VisualScriptNode {
- GDCLASS(VisualScriptIndexSet,VisualScriptNode)
-
+ GDCLASS(VisualScriptIndexSet, VisualScriptNode)
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -356,33 +310,28 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "operators"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptIndexSet();
};
-
-
class VisualScriptGlobalConstant : public VisualScriptNode {
- GDCLASS(VisualScriptGlobalConstant,VisualScriptNode)
+ GDCLASS(VisualScriptGlobalConstant, VisualScriptNode)
int index;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -393,35 +342,31 @@ public:
void set_global_constant(int p_which);
int get_global_constant();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptGlobalConstant();
};
-
class VisualScriptClassConstant : public VisualScriptNode {
- GDCLASS(VisualScriptClassConstant,VisualScriptNode)
+ GDCLASS(VisualScriptClassConstant, VisualScriptNode)
StringName base_type;
StringName name;
+
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -429,40 +374,37 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "constants"; }
- void set_class_constant(const StringName& p_which);
+ void set_class_constant(const StringName &p_which);
StringName get_class_constant();
- void set_base_type(const StringName& p_which);
+ void set_base_type(const StringName &p_which);
StringName get_base_type();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptClassConstant();
};
class VisualScriptBasicTypeConstant : public VisualScriptNode {
- GDCLASS(VisualScriptBasicTypeConstant,VisualScriptNode)
+ GDCLASS(VisualScriptBasicTypeConstant, VisualScriptNode)
Variant::Type type;
StringName name;
+
protected:
static void _bind_methods();
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -470,24 +412,21 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "constants"; }
- void set_basic_type_constant(const StringName& p_which);
+ void set_basic_type_constant(const StringName &p_which);
StringName get_basic_type_constant() const;
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);
VisualScriptBasicTypeConstant();
};
-
-
class VisualScriptMathConstant : public VisualScriptNode {
- GDCLASS(VisualScriptMathConstant,VisualScriptNode)
+ GDCLASS(VisualScriptMathConstant, VisualScriptNode)
public:
-
enum MathConstant {
MATH_CONSTANT_ONE,
MATH_CONSTANT_PI,
@@ -501,24 +440,22 @@ public:
};
private:
- static const char* const_name[MATH_CONSTANT_MAX];
+ static const char *const_name[MATH_CONSTANT_MAX];
static double const_value[MATH_CONSTANT_MAX];
MathConstant constant;
+
protected:
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -529,33 +466,30 @@ public:
void set_math_constant(MathConstant p_which);
MathConstant get_math_constant();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptMathConstant();
};
-VARIANT_ENUM_CAST( VisualScriptMathConstant::MathConstant )
+VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant)
class VisualScriptEngineSingleton : public VisualScriptNode {
- GDCLASS(VisualScriptEngineSingleton,VisualScriptNode)
+ GDCLASS(VisualScriptEngineSingleton, VisualScriptNode)
String singleton;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -566,38 +500,32 @@ public:
void set_singleton(const String &p_string);
String get_singleton();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
- virtual TypeGuess guess_output_type(TypeGuess* p_inputs, int p_output) const;
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptEngineSingleton();
};
-
-
-
class VisualScriptSceneNode : public VisualScriptNode {
- GDCLASS(VisualScriptSceneNode,VisualScriptNode)
+ GDCLASS(VisualScriptSceneNode, VisualScriptNode)
NodePath path;
+
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -608,37 +536,30 @@ public:
void set_node_path(const NodePath &p_path);
NodePath get_node_path();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
- virtual TypeGuess guess_output_type(TypeGuess* p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptSceneNode();
};
-
-
-
class VisualScriptSceneTree : public VisualScriptNode {
- GDCLASS(VisualScriptSceneTree,VisualScriptNode)
-
+ GDCLASS(VisualScriptSceneTree, VisualScriptNode)
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -646,36 +567,31 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "data"; }
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
- virtual TypeGuess guess_output_type(TypeGuess* p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptSceneTree();
};
-
-
class VisualScriptResourcePath : public VisualScriptNode {
- GDCLASS(VisualScriptResourcePath,VisualScriptNode)
+ GDCLASS(VisualScriptResourcePath, VisualScriptNode)
String path;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -686,33 +602,27 @@ public:
void set_resource_path(const String &p_path);
String get_resource_path();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptResourcePath();
};
-
class VisualScriptSelf : public VisualScriptNode {
- GDCLASS(VisualScriptSelf,VisualScriptNode)
-
+ GDCLASS(VisualScriptSelf, VisualScriptNode)
protected:
-
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -720,25 +630,21 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "data"; }
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
-
- virtual TypeGuess guess_output_type(TypeGuess* p_inputs, int p_output) const;
+ virtual TypeGuess guess_output_type(TypeGuess *p_inputs, int p_output) const;
VisualScriptSelf();
};
+class VisualScriptCustomNode : public VisualScriptNode {
-class VisualScriptCustomNode: public VisualScriptNode {
-
- GDCLASS(VisualScriptCustomNode,VisualScriptNode)
-
+ GDCLASS(VisualScriptCustomNode, VisualScriptNode)
protected:
-
static void _bind_methods();
-public:
+public:
enum StartMode { //replicated for step
START_MODE_BEGIN_SEQUENCE,
START_MODE_CONTINUE_SEQUENCE,
@@ -746,26 +652,23 @@ public:
};
enum { //replicated for step
- STEP_SHIFT=1<<24,
- STEP_MASK=STEP_SHIFT-1,
- STEP_PUSH_STACK_BIT=STEP_SHIFT, //push bit to stack
- STEP_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_SHIFT = 1 << 24,
+ STEP_MASK = STEP_SHIFT - 1,
+ STEP_PUSH_STACK_BIT = STEP_SHIFT, //push bit to stack
+ STEP_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)
};
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -773,32 +676,27 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptCustomNode();
};
-class VisualScriptSubCall: public VisualScriptNode {
-
- GDCLASS(VisualScriptSubCall,VisualScriptNode)
+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 String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -806,34 +704,31 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptSubCall();
};
-class VisualScriptComment: public VisualScriptNode {
-
- GDCLASS(VisualScriptComment,VisualScriptNode)
+class VisualScriptComment : public VisualScriptNode {
+ GDCLASS(VisualScriptComment, VisualScriptNode)
String title;
String description;
Size2 size;
-protected:
+protected:
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -841,44 +736,39 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- void set_title(const String& p_title);
+ void set_title(const String &p_title);
String get_title() const;
- void set_description(const String& p_description);
+ void set_description(const String &p_description);
String get_description() const;
- void set_size(const Size2& p_size);
+ void set_size(const Size2 &p_size);
Size2 get_size() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptComment();
};
-class VisualScriptConstructor: public VisualScriptNode {
-
- GDCLASS(VisualScriptConstructor,VisualScriptNode)
+class VisualScriptConstructor : public VisualScriptNode {
+ GDCLASS(VisualScriptConstructor, VisualScriptNode)
Variant::Type type;
MethodInfo constructor;
protected:
-
-
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -889,39 +779,33 @@ public:
void set_constructor_type(Variant::Type p_type);
Variant::Type get_constructor_type() const;
- void set_constructor(const Dictionary& p_info);
+ void set_constructor(const Dictionary &p_info);
Dictionary get_constructor() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptConstructor();
};
+class VisualScriptLocalVar : public VisualScriptNode {
-
-
-class VisualScriptLocalVar: public VisualScriptNode {
-
- GDCLASS(VisualScriptLocalVar,VisualScriptNode)
+ GDCLASS(VisualScriptLocalVar, VisualScriptNode)
StringName name;
Variant::Type type;
protected:
-
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -929,39 +813,36 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- void set_var_name(const StringName& p_name);
+ void set_var_name(const StringName &p_name);
StringName get_var_name() const;
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);
VisualScriptLocalVar();
};
-class VisualScriptLocalVarSet: public VisualScriptNode {
+class VisualScriptLocalVarSet : public VisualScriptNode {
- GDCLASS(VisualScriptLocalVarSet,VisualScriptNode)
+ GDCLASS(VisualScriptLocalVarSet, VisualScriptNode)
StringName name;
Variant::Type type;
protected:
-
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -969,22 +850,20 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- void set_var_name(const StringName& p_name);
+ void set_var_name(const StringName &p_name);
StringName get_var_name() const;
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);
VisualScriptLocalVarSet();
};
+class VisualScriptInputAction : public VisualScriptNode {
-
-class VisualScriptInputAction: public VisualScriptNode {
-
- GDCLASS(VisualScriptInputAction,VisualScriptNode)
+ GDCLASS(VisualScriptInputAction, VisualScriptNode)
public:
enum Mode {
MODE_PRESSED,
@@ -997,22 +876,19 @@ public:
Mode mode;
protected:
-
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -1020,57 +896,51 @@ public:
virtual String get_text() const;
virtual String get_category() const;
- void set_action_name(const StringName& p_name);
+ void set_action_name(const StringName &p_name);
StringName get_action_name() const;
void set_action_mode(Mode p_mode);
Mode get_action_mode() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptInputAction();
};
-VARIANT_ENUM_CAST( VisualScriptInputAction::Mode )
-
-class VisualScriptDeconstruct: public VisualScriptNode {
+VARIANT_ENUM_CAST(VisualScriptInputAction::Mode)
- GDCLASS(VisualScriptDeconstruct,VisualScriptNode)
+class VisualScriptDeconstruct : public VisualScriptNode {
+ GDCLASS(VisualScriptDeconstruct, VisualScriptNode)
struct Element {
StringName name;
Variant::Type type;
};
-
Vector<Element> elements;
void _update_elements();
Variant::Type type;
InputEvent::Type input_type;
- void _set_elem_cache(const Array& p_elements);
+ 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;
protected:
-
-
static void _bind_methods();
+
public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -1084,12 +954,11 @@ public:
void set_deconstruct_input_type(InputEvent::Type p_input_type);
InputEvent::Type get_deconstruct_input_type() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptDeconstruct();
};
-
void register_visual_script_nodes();
void unregister_visual_script_nodes();
diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp
index 35335fd9bc..919ced74b9 100644
--- a/modules/visual_script/visual_script_yield_nodes.cpp
+++ b/modules/visual_script/visual_script_yield_nodes.cpp
@@ -28,9 +28,9 @@
/*************************************************************************/
#include "visual_script_yield_nodes.h"
-#include "scene/main/scene_main_loop.h"
#include "os/os.h"
#include "scene/main/node.h"
+#include "scene/main/scene_main_loop.h"
#include "visual_script_nodes.h"
//////////////////////////////////////////
@@ -42,16 +42,16 @@ int VisualScriptYield::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptYield::has_input_sequence_port() const{
+bool VisualScriptYield::has_input_sequence_port() const {
return true;
}
-int VisualScriptYield::get_input_value_port_count() const{
+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;
}
@@ -61,20 +61,19 @@ String VisualScriptYield::get_output_sequence_port_text(int p_port) const {
return String();
}
-PropertyInfo VisualScriptYield::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptYield::get_input_value_port_info(int p_idx) const {
return PropertyInfo();
}
-PropertyInfo VisualScriptYield::get_output_value_port_info(int p_idx) const{
+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";
+ return yield_mode == YIELD_RETURN ? "Yield" : "Wait";
}
String VisualScriptYield::get_text() const {
@@ -82,17 +81,15 @@ String VisualScriptYield::get_text() const {
switch (yield_mode) {
case YIELD_RETURN: return ""; break;
case YIELD_FRAME: return "Next Frame"; break;
- case YIELD_FIXED_FRAME: return "Next Fixed Frame"; break;
- case YIELD_WAIT: return rtos(wait_time)+" sec(s)"; break;
+ case YIELD_FIXED_FRAME: return "Next Fixed Frame"; break;
+ case YIELD_WAIT: return rtos(wait_time) + " sec(s)"; break;
}
return String();
}
-
class VisualScriptNodeInstanceYield : public VisualScriptNodeInstance {
public:
-
VisualScriptYield::YieldMode mode;
float wait_time;
@@ -100,18 +97,17 @@ public:
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_start_mode==START_MODE_RESUME_YIELD) {
+ if (p_start_mode == START_MODE_RESUME_YIELD) {
return 0; //resuming yield
} else {
//yield
-
SceneTree *tree = OS::get_singleton()->get_main_loop()->cast_to<SceneTree>();
if (!tree) {
- r_error_str="Main Loop is not SceneTree";
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Main Loop is not SceneTree";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return 0;
}
@@ -119,99 +115,92 @@ public:
state.instance();
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_FIXED_FRAME: state->connect_to_signal(tree,"fixed_frame",Array()); break;
- case VisualScriptYield::YIELD_WAIT: state->connect_to_signal(tree->create_timer(wait_time).ptr(),"timeout",Array()); break;
-
+ 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_FIXED_FRAME: state->connect_to_signal(tree, "fixed_frame", Array()); break;
+ case VisualScriptYield::YIELD_WAIT: state->connect_to_signal(tree->create_timer(wait_time).ptr(), "timeout", Array()); break;
}
- *p_working_mem=state;
+ *p_working_mem = state;
return ret;
}
}
-
};
-VisualScriptNodeInstance* VisualScriptYield::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptYield::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceYield * instance = memnew(VisualScriptNodeInstanceYield );
+ VisualScriptNodeInstanceYield *instance = memnew(VisualScriptNodeInstanceYield);
//instance->instance=p_instance;
- instance->mode=yield_mode;
- instance->wait_time=wait_time;
+ instance->mode = yield_mode;
+ instance->wait_time = wait_time;
return instance;
}
void VisualScriptYield::set_yield_mode(YieldMode p_mode) {
- if (yield_mode==p_mode)
+ if (yield_mode == p_mode)
return;
- yield_mode=p_mode;
+ yield_mode = p_mode;
ports_changed_notify();
_change_notify();
}
-VisualScriptYield::YieldMode VisualScriptYield::get_yield_mode(){
+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;
+ wait_time = p_time;
ports_changed_notify();
-
}
-float VisualScriptYield::get_wait_time(){
+float VisualScriptYield::get_wait_time() {
return wait_time;
}
+void VisualScriptYield::_validate_property(PropertyInfo &property) const {
-void VisualScriptYield::_validate_property(PropertyInfo& property) const {
-
-
- if (property.name=="wait_time") {
- if (yield_mode!=YIELD_WAIT) {
- property.usage=0;
+ if (property.name == "wait_time") {
+ if (yield_mode != YIELD_WAIT) {
+ property.usage = 0;
}
}
}
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);
-
- ClassDB::bind_method(D_METHOD("set_wait_time","sec"),&VisualScriptYield::set_wait_time);
- ClassDB::bind_method(D_METHOD("get_wait_time"),&VisualScriptYield::get_wait_time);
+ 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);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Frame,FixedFrame,Time",PROPERTY_USAGE_NOEDITOR),"set_yield_mode","get_yield_mode");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wait_time"),"set_wait_time","get_wait_time");
+ ClassDB::bind_method(D_METHOD("set_wait_time", "sec"), &VisualScriptYield::set_wait_time);
+ ClassDB::bind_method(D_METHOD("get_wait_time"), &VisualScriptYield::get_wait_time);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Frame,FixedFrame,Time", PROPERTY_USAGE_NOEDITOR), "set_yield_mode", "get_yield_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wait_time"), "set_wait_time", "get_wait_time");
- BIND_CONSTANT( YIELD_FRAME );
- BIND_CONSTANT( YIELD_FIXED_FRAME );
- BIND_CONSTANT( YIELD_WAIT );
-
+ BIND_CONSTANT(YIELD_FRAME);
+ BIND_CONSTANT(YIELD_FIXED_FRAME);
+ BIND_CONSTANT(YIELD_WAIT);
}
VisualScriptYield::VisualScriptYield() {
- yield_mode=YIELD_FRAME;
- wait_time=1;
-
+ yield_mode = YIELD_FRAME;
+ wait_time = 1;
}
-
-template<VisualScriptYield::YieldMode MODE>
-static Ref<VisualScriptNode> create_yield_node(const String& p_name) {
+template <VisualScriptYield::YieldMode MODE>
+static Ref<VisualScriptNode> create_yield_node(const String &p_name) {
Ref<VisualScriptYield> node;
node.instance();
@@ -228,24 +217,24 @@ int VisualScriptYieldSignal::get_output_sequence_port_count() const {
return 1;
}
-bool VisualScriptYieldSignal::has_input_sequence_port() const{
+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) {
+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 NULL;
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);
+ 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)
return n;
}
@@ -261,7 +250,7 @@ Node *VisualScriptYieldSignal::_get_base_node() const {
if (!script.is_valid())
return NULL;
- MainLoop * main_loop = OS::get_singleton()->get_main_loop();
+ MainLoop *main_loop = OS::get_singleton()->get_main_loop();
if (!main_loop)
return NULL;
@@ -275,7 +264,7 @@ Node *VisualScriptYieldSignal::_get_base_node() const {
if (!edited_scene)
return NULL;
- Node* script_node = _find_script_node(edited_scene,edited_scene,script);
+ Node *script_node = _find_script_node(edited_scene, edited_scene, script);
if (!script_node)
return NULL;
@@ -294,36 +283,32 @@ 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)
return path->get_class();
-
}
return base_type;
}
-int VisualScriptYieldSignal::get_input_value_port_count() const{
+int VisualScriptYieldSignal::get_input_value_port_count() const {
- if (call_mode==CALL_MODE_INSTANCE)
+ if (call_mode == CALL_MODE_INSTANCE)
return 1;
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 {
@@ -331,30 +316,27 @@ String VisualScriptYieldSignal::get_output_sequence_port_text(int p_port) const
return String();
}
-PropertyInfo VisualScriptYieldSignal::get_input_value_port_info(int p_idx) const{
+PropertyInfo VisualScriptYieldSignal::get_input_value_port_info(int p_idx) const {
- if (call_mode==CALL_MODE_INSTANCE)
- return PropertyInfo(Variant::OBJECT,"instance");
+ if (call_mode == CALL_MODE_INSTANCE)
+ return PropertyInfo(Variant::OBJECT, "instance");
else
return PropertyInfo();
-
}
-PropertyInfo VisualScriptYieldSignal::get_output_value_port_info(int p_idx) const{
+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());
+ 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]= {
+ static const char *cname[3] = {
"WaitSignal",
"WaitNodeSignal",
"WaitInstanceSigna;",
@@ -365,52 +347,49 @@ String VisualScriptYieldSignal::get_caption() const {
String VisualScriptYieldSignal::get_text() const {
- if (call_mode==CALL_MODE_SELF)
- return " "+String(signal)+"()";
+ if (call_mode == CALL_MODE_SELF)
+ return " " + String(signal) + "()";
else
- return " "+_get_base_type()+"."+String(signal)+"()";
-
+ return " " + _get_base_type() + "." + String(signal) + "()";
}
+void VisualScriptYieldSignal::set_base_type(const StringName &p_type) {
-void VisualScriptYieldSignal::set_base_type(const StringName& p_type) {
-
- if (base_type==p_type)
+ if (base_type == p_type)
return;
- base_type=p_type;
+ base_type = p_type;
_change_notify();
ports_changed_notify();
}
-StringName VisualScriptYieldSignal::get_base_type() const{
+StringName VisualScriptYieldSignal::get_base_type() const {
return base_type;
}
-void VisualScriptYieldSignal::set_signal(const StringName& p_type){
+void VisualScriptYieldSignal::set_signal(const StringName &p_type) {
- if (signal==p_type)
+ if (signal == p_type)
return;
- signal=p_type;
+ signal = p_type;
_change_notify();
ports_changed_notify();
}
StringName VisualScriptYieldSignal::get_signal() const {
-
return signal;
}
-void VisualScriptYieldSignal::set_base_path(const NodePath& p_type) {
+void VisualScriptYieldSignal::set_base_path(const NodePath &p_type) {
- if (base_path==p_type)
+ if (base_path == p_type)
return;
- base_path=p_type;
+ base_path = p_type;
_change_notify();
ports_changed_notify();
@@ -421,17 +400,15 @@ 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;
+ call_mode = p_mode;
_change_notify();
ports_changed_notify();
-
}
VisualScriptYieldSignal::CallMode VisualScriptYieldSignal::get_call_mode() const {
@@ -439,102 +416,89 @@ VisualScriptYieldSignal::CallMode VisualScriptYieldSignal::get_call_mode() const
return call_mode;
}
+void VisualScriptYieldSignal::_validate_property(PropertyInfo &property) const {
-void VisualScriptYieldSignal::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="signal/base_type") {
- if (call_mode!=CALL_MODE_INSTANCE) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "signal/base_type") {
+ if (call_mode != CALL_MODE_INSTANCE) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
-
- if (property.name=="signal/node_path") {
- if (call_mode!=CALL_MODE_NODE_PATH) {
- property.usage=0;
+ if (property.name == "signal/node_path") {
+ 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
+ property.hint_string = bnode->get_path(); //convert to loong string
} else {
-
}
}
}
- if (property.name=="signal/signal") {
- property.hint=PROPERTY_HINT_ENUM;
-
+ if (property.name == "signal/signal") {
+ property.hint = PROPERTY_HINT_ENUM;
List<MethodInfo> methods;
- ClassDB::get_signal_list(_get_base_type(),&methods);
+ ClassDB::get_signal_list(_get_base_type(), &methods);
List<String> mstring;
- for (List<MethodInfo>::Element *E=methods.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = methods.front(); E; E = E->next()) {
if (E->get().name.begins_with("_"))
continue;
- mstring.push_back(E->get().name.get_slice(":",0));
+ mstring.push_back(E->get().name.get_slice(":", 0));
}
mstring.sort();
String ml;
- for (List<String>::Element *E=mstring.front();E;E=E->next()) {
+ for (List<String>::Element *E = mstring.front(); E; E = E->next()) {
- if (ml!=String())
- ml+=",";
- ml+=E->get();
+ if (ml != String())
+ ml += ",";
+ ml += E->get();
}
- property.hint_string=ml;
+ property.hint_string = ml;
}
-
-
}
-
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);
-
- ClassDB::bind_method(D_METHOD("set_signal","signal"),&VisualScriptYieldSignal::set_signal);
- ClassDB::bind_method(D_METHOD("get_signal"),&VisualScriptYieldSignal::get_signal);
+ 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);
- ClassDB::bind_method(D_METHOD("set_call_mode","mode"),&VisualScriptYieldSignal::set_call_mode);
- ClassDB::bind_method(D_METHOD("get_call_mode"),&VisualScriptYieldSignal::get_call_mode);
-
- ClassDB::bind_method(D_METHOD("set_base_path","base_path"),&VisualScriptYieldSignal::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"),&VisualScriptYieldSignal::get_base_path);
+ ClassDB::bind_method(D_METHOD("set_signal", "signal"), &VisualScriptYieldSignal::set_signal);
+ ClassDB::bind_method(D_METHOD("get_signal"), &VisualScriptYieldSignal::get_signal);
+ ClassDB::bind_method(D_METHOD("set_call_mode", "mode"), &VisualScriptYieldSignal::set_call_mode);
+ ClassDB::bind_method(D_METHOD("get_call_mode"), &VisualScriptYieldSignal::get_call_mode);
+ ClassDB::bind_method(D_METHOD("set_base_path", "base_path"), &VisualScriptYieldSignal::set_base_path);
+ ClassDB::bind_method(D_METHOD("get_base_path"), &VisualScriptYieldSignal::get_base_path);
String bt;
- for(int i=0;i<Variant::VARIANT_MAX;i++) {
- if (i>0)
- bt+=",";
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ if (i > 0)
+ bt += ",";
- bt+=Variant::get_type_name(Variant::Type(i));
+ bt += Variant::get_type_name(Variant::Type(i));
}
- ADD_PROPERTY(PropertyInfo(Variant::INT,"signal/call_mode",PROPERTY_HINT_ENUM,"Self,Node Path,Instance"),"set_call_mode","get_call_mode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"signal/base_type",PROPERTY_HINT_TYPE_STRING,"Object"),"set_base_type","get_base_type");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"signal/node_path",PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE),"set_base_path","get_base_path");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"signal/signal"),"set_signal","get_signal");
-
-
- BIND_CONSTANT( CALL_MODE_SELF );
- BIND_CONSTANT( CALL_MODE_NODE_PATH);
- BIND_CONSTANT( CALL_MODE_INSTANCE);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "signal/call_mode", PROPERTY_HINT_ENUM, "Self,Node Path,Instance"), "set_call_mode", "get_call_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal/base_type", PROPERTY_HINT_TYPE_STRING, "Object"), "set_base_type", "get_base_type");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "signal/node_path", PROPERTY_HINT_NODE_PATH_TO_EDITED_NODE), "set_base_path", "get_base_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "signal/signal"), "set_signal", "get_signal");
+ BIND_CONSTANT(CALL_MODE_SELF);
+ BIND_CONSTANT(CALL_MODE_NODE_PATH);
+ BIND_CONSTANT(CALL_MODE_INSTANCE);
}
class VisualScriptNodeInstanceYieldSignal : public VisualScriptNodeInstance {
public:
-
-
VisualScriptYieldSignal::CallMode call_mode;
NodePath node_path;
int output_args;
@@ -543,97 +507,88 @@ public:
VisualScriptYieldSignal *node;
VisualScriptInstance *instance;
-
-
virtual int get_working_memory_size() const { return 1; }
//virtual bool is_output_port_unsequenced(int p_idx) const { return false; }
//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,Variant::CallError& r_error,String& r_error_str) {
+ virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Variant::CallError &r_error, String &r_error_str) {
- if (p_start_mode==START_MODE_RESUME_YIELD) {
+ if (p_start_mode == START_MODE_RESUME_YIELD) {
return 0; //resuming yield
} else {
//yield
- Object * object;
+ Object *object;
- switch(call_mode) {
+ switch (call_mode) {
case VisualScriptYieldSignal::CALL_MODE_SELF: {
- object=instance->get_owner_ptr();
+ object = instance->get_owner_ptr();
} break;
case VisualScriptYieldSignal::CALL_MODE_NODE_PATH: {
- Node* node = instance->get_owner_ptr()->cast_to<Node>();
+ Node *node = instance->get_owner_ptr()->cast_to<Node>();
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Base object is not a Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Base object is not a Node!";
return 0;
}
- Node* another = node->get_node(node_path);
+ Node *another = node->get_node(node_path);
if (!node) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Path does not lead Node!";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Path does not lead Node!";
return 0;
}
- object=another;
+ object = another;
} break;
case VisualScriptYieldSignal::CALL_MODE_INSTANCE: {
object = *p_inputs[0];
if (!object) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- r_error_str="Supplied instance input is null.";
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error_str = "Supplied instance input is null.";
return 0;
-
}
} break;
-
}
Ref<VisualScriptFunctionState> state;
state.instance();
- state->connect_to_signal(object,signal,Array());
+ state->connect_to_signal(object, signal, Array());
- *p_working_mem=state;
+ *p_working_mem = state;
return STEP_YIELD_BIT;
}
-
-
}
-
-
};
-VisualScriptNodeInstance* VisualScriptYieldSignal::instance(VisualScriptInstance* p_instance) {
+VisualScriptNodeInstance *VisualScriptYieldSignal::instance(VisualScriptInstance *p_instance) {
- VisualScriptNodeInstanceYieldSignal * instance = memnew(VisualScriptNodeInstanceYieldSignal );
- instance->node=this;
- instance->instance=p_instance;
- instance->signal=signal;
- instance->call_mode=call_mode;
- instance->node_path=base_path;
+ VisualScriptNodeInstanceYieldSignal *instance = memnew(VisualScriptNodeInstanceYieldSignal);
+ instance->node = this;
+ instance->instance = p_instance;
+ instance->signal = signal;
+ instance->call_mode = call_mode;
+ instance->node_path = base_path;
instance->output_args = get_output_value_port_count();
return instance;
}
VisualScriptYieldSignal::VisualScriptYieldSignal() {
- call_mode=CALL_MODE_SELF;
- base_type="Object";
-
+ call_mode = CALL_MODE_SELF;
+ base_type = "Object";
}
-template<VisualScriptYieldSignal::CallMode cmode>
-static Ref<VisualScriptNode> create_yield_signal_node(const String& p_name) {
+template <VisualScriptYieldSignal::CallMode cmode>
+static Ref<VisualScriptNode> create_yield_signal_node(const String &p_name) {
Ref<VisualScriptYieldSignal> node;
node.instance();
@@ -643,12 +598,10 @@ 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_fixed_frame",create_yield_node<VisualScriptYield::YIELD_FIXED_FRAME>);
- VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_time",create_yield_node<VisualScriptYield::YIELD_WAIT>);
-
-
- VisualScriptLanguage::singleton->add_register_func("functions/yield",create_yield_node<VisualScriptYield::YIELD_RETURN>);
- VisualScriptLanguage::singleton->add_register_func("functions/yield_signal",create_node_generic<VisualScriptYieldSignal>);
+ VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_frame", create_yield_node<VisualScriptYield::YIELD_FRAME>);
+ VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_fixed_frame", create_yield_node<VisualScriptYield::YIELD_FIXED_FRAME>);
+ VisualScriptLanguage::singleton->add_register_func("functions/wait/wait_time", create_yield_node<VisualScriptYield::YIELD_WAIT>);
+ VisualScriptLanguage::singleton->add_register_func("functions/yield", create_yield_node<VisualScriptYield::YIELD_RETURN>);
+ VisualScriptLanguage::singleton->add_register_func("functions/yield_signal", create_node_generic<VisualScriptYieldSignal>);
}
diff --git a/modules/visual_script/visual_script_yield_nodes.h b/modules/visual_script/visual_script_yield_nodes.h
index 80ac879aad..35f72cdfad 100644
--- a/modules/visual_script/visual_script_yield_nodes.h
+++ b/modules/visual_script/visual_script_yield_nodes.h
@@ -33,9 +33,8 @@
class VisualScriptYield : public VisualScriptNode {
- GDCLASS(VisualScriptYield,VisualScriptNode)
+ GDCLASS(VisualScriptYield, VisualScriptNode)
public:
-
enum YieldMode {
YIELD_RETURN,
YIELD_FRAME,
@@ -43,30 +42,25 @@ public:
YIELD_WAIT
};
-private:
+private:
YieldMode yield_mode;
float wait_time;
-
protected:
-
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -80,15 +74,15 @@ public:
void set_wait_time(float p_time);
float get_wait_time();
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptYield();
};
-VARIANT_ENUM_CAST( VisualScriptYield::YieldMode )
+VARIANT_ENUM_CAST(VisualScriptYield::YieldMode)
class VisualScriptYieldSignal : public VisualScriptNode {
- GDCLASS(VisualScriptYieldSignal,VisualScriptNode)
+ GDCLASS(VisualScriptYieldSignal, VisualScriptNode)
public:
enum CallMode {
CALL_MODE_SELF,
@@ -96,8 +90,8 @@ public:
CALL_MODE_INSTANCE,
};
-private:
+private:
CallMode call_mode;
StringName base_type;
NodePath base_path;
@@ -106,25 +100,20 @@ private:
Node *_get_base_node() const;
StringName _get_base_type() const;
-
protected:
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
public:
-
virtual int get_output_sequence_port_count() const;
virtual bool has_input_sequence_port() const;
-
virtual String get_output_sequence_port_text(int p_port) const;
-
virtual int get_input_value_port_count() const;
virtual int get_output_value_port_count() const;
-
virtual PropertyInfo get_input_value_port_info(int p_idx) const;
virtual PropertyInfo get_output_value_port_info(int p_idx) const;
@@ -132,24 +121,24 @@ public:
virtual String get_text() const;
virtual String get_category() const { return "functions"; }
- void set_base_type(const StringName& p_type);
+ void set_base_type(const StringName &p_type);
StringName get_base_type() const;
- void set_signal(const StringName& p_type);
+ void set_signal(const StringName &p_type);
StringName get_signal() const;
- void set_base_path(const NodePath& p_type);
+ void set_base_path(const NodePath &p_type);
NodePath get_base_path() const;
void set_call_mode(CallMode p_mode);
CallMode get_call_mode() const;
- virtual VisualScriptNodeInstance* instance(VisualScriptInstance* p_instance);
+ virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance);
VisualScriptYieldSignal();
};
-VARIANT_ENUM_CAST(VisualScriptYieldSignal::CallMode );
+VARIANT_ENUM_CAST(VisualScriptYieldSignal::CallMode);
void register_visual_script_yield_nodes();
diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp
index 98920954a4..88c8ecc0df 100644
--- a/modules/vorbis/audio_stream_ogg_vorbis.cpp
+++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp
@@ -28,60 +28,57 @@
/*************************************************************************/
#include "audio_stream_ogg_vorbis.h"
-
-
-size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst,size_t p_data, size_t p_count, void *_f) {
+size_t AudioStreamPlaybackOGGVorbis::_ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f) {
//printf("read to %p, %i bytes, %i nmemb, %p\n",p_dst,p_data,p_count,_f);
- FileAccess *fa=(FileAccess*)_f;
- size_t read_total = p_data*p_count;
+ FileAccess *fa = (FileAccess *)_f;
+ size_t read_total = p_data * p_count;
if (fa->eof_reached())
return 0;
- uint8_t *dst=(uint8_t*)p_dst;
+ uint8_t *dst = (uint8_t *)p_dst;
int read = fa->get_buffer(dst, read_total);
return read;
}
-int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f,ogg_int64_t offs, int whence) {
+int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f, ogg_int64_t offs, int whence) {
- //printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence);
+//printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence);
#ifdef SEEK_SET
//printf("seek set defined\n");
- FileAccess *fa=(FileAccess*)_f;
+ FileAccess *fa = (FileAccess *)_f;
- if (whence==SEEK_SET) {
+ if (whence == SEEK_SET) {
fa->seek(offs);
- } else if (whence==SEEK_CUR) {
+ } else if (whence == SEEK_CUR) {
- fa->seek(fa->get_pos()+offs);
- } else if (whence==SEEK_END) {
+ fa->seek(fa->get_pos() + offs);
+ } else if (whence == SEEK_END) {
fa->seek_end(offs);
} else {
ERR_PRINT("BUG, wtf was whence set to?\n");
}
- int ret=fa->eof_reached()?-1:0;
+ int ret = fa->eof_reached() ? -1 : 0;
//printf("returning %i\n",ret);
return ret;
#else
return -1; // no seeking
#endif
-
}
int AudioStreamPlaybackOGGVorbis::_ov_close_func(void *_f) {
//printf("close %p\n",_f);
if (!_f)
return 0;
- FileAccess *fa=(FileAccess*)_f;
+ FileAccess *fa = (FileAccess *)_f;
if (fa->is_open())
fa->close();
return 0;
@@ -90,40 +87,38 @@ long AudioStreamPlaybackOGGVorbis::_ov_tell_func(void *_f) {
//printf("close %p\n",_f);
- FileAccess *fa=(FileAccess*)_f;
+ FileAccess *fa = (FileAccess *)_f;
return fa->get_pos();
}
-
-
-int AudioStreamPlaybackOGGVorbis::mix(int16_t* p_bufer,int p_frames) {
+int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_bufer, int p_frames) {
if (!playing)
return 0;
- int total=p_frames;
+ int total = p_frames;
while (true) {
int todo = p_frames;
- if (todo==0 || todo<MIN_MIX) {
+ if (todo == 0 || todo < MIN_MIX) {
break;
}
- //printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t));
+//printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t));
- #ifdef BIG_ENDIAN_ENABLED
- long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 1, 2, 1, &current_section);
- #else
- long ret=ov_read(&vf,(char*)p_bufer,todo*stream_channels*sizeof(int16_t), 0, 2, 1, &current_section);
- #endif
+#ifdef BIG_ENDIAN_ENABLED
+ long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 1, 2, 1, &current_section);
+#else
+ long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 0, 2, 1, &current_section);
+#endif
- if (ret<0) {
+ if (ret < 0) {
playing = false;
- ERR_EXPLAIN("Error reading OGG Vorbis File: "+file);
- ERR_BREAK(ret<0);
- } else if (ret==0) { // end of song, reload?
+ ERR_EXPLAIN("Error reading OGG Vorbis File: " + file);
+ ERR_BREAK(ret < 0);
+ } else if (ret == 0) { // end of song, reload?
ov_clear(&vf);
@@ -131,65 +126,59 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t* p_bufer,int p_frames) {
if (!has_loop()) {
- playing=false;
- repeats=1;
+ playing = false;
+ repeats = 1;
break;
}
- f=FileAccess::open(file,FileAccess::READ);
+ f = FileAccess::open(file, FileAccess::READ);
- int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
- if (errv!=0) {
- playing=false;
+ int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks);
+ if (errv != 0) {
+ playing = false;
break; // :(
}
if (loop_restart_time) {
- bool ok = ov_time_seek(&vf,loop_restart_time)==0;
+ bool ok = ov_time_seek(&vf, loop_restart_time) == 0;
if (!ok) {
- playing=false;
+ playing = false;
//ERR_EXPLAIN("loop restart time rejected");
ERR_PRINT("loop restart time rejected")
}
- frames_mixed=stream_srate*loop_restart_time;
+ frames_mixed = stream_srate * loop_restart_time;
} else {
- frames_mixed=0;
+ frames_mixed = 0;
}
repeats++;
continue;
-
}
- ret/=stream_channels;
- ret/=sizeof(int16_t);
-
- frames_mixed+=ret;
+ ret /= stream_channels;
+ ret /= sizeof(int16_t);
- p_bufer+=ret*stream_channels;
- p_frames-=ret;
+ frames_mixed += ret;
+ p_bufer += ret * stream_channels;
+ p_frames -= ret;
}
- return total-p_frames;
-
+ return total - p_frames;
}
-
-
void AudioStreamPlaybackOGGVorbis::play(float p_from) {
if (playing)
stop();
- if (_load_stream()!=OK)
+ if (_load_stream() != OK)
return;
-
- frames_mixed=0;
- playing=true;
- if (p_from>0) {
+ frames_mixed = 0;
+ playing = true;
+ if (p_from > 0) {
seek_pos(p_from);
}
}
@@ -199,7 +188,7 @@ void AudioStreamPlaybackOGGVorbis::_close_file() {
if (f) {
memdelete(f);
- f=NULL;
+ f = NULL;
}
}
@@ -209,39 +198,35 @@ bool AudioStreamPlaybackOGGVorbis::is_playing() const {
void AudioStreamPlaybackOGGVorbis::stop() {
_clear_stream();
- playing=false;
+ playing = false;
//_clear();
}
-
-
float AudioStreamPlaybackOGGVorbis::get_pos() const {
int32_t frames = int32_t(frames_mixed);
if (frames < 0)
- frames=0;
+ frames = 0;
return double(frames) / stream_srate;
}
void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) {
-
-
if (!playing)
return;
- bool ok = ov_time_seek(&vf,p_time)==0;
+ bool ok = ov_time_seek(&vf, p_time) == 0;
ERR_FAIL_COND(!ok);
- frames_mixed=stream_srate*p_time;
+ frames_mixed = stream_srate * p_time;
}
-String AudioStreamPlaybackOGGVorbis::get_stream_name() const {
+String AudioStreamPlaybackOGGVorbis::get_stream_name() const {
return "";
}
void AudioStreamPlaybackOGGVorbis::set_loop(bool p_enable) {
- loops=p_enable;
+ loops = p_enable;
}
bool AudioStreamPlaybackOGGVorbis::has_loop() const {
@@ -253,99 +238,103 @@ int AudioStreamPlaybackOGGVorbis::get_loop_count() const {
return repeats;
}
+Error AudioStreamPlaybackOGGVorbis::set_file(const String &p_file) {
-Error AudioStreamPlaybackOGGVorbis::set_file(const String& p_file) {
-
- file=p_file;
- stream_valid=false;
+ file = p_file;
+ stream_valid = false;
Error err;
- f=FileAccess::open(file,FileAccess::READ,&err);
+ f = FileAccess::open(file, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V( err, err );
+ ERR_FAIL_COND_V(err, err);
}
- int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
- switch(errv) {
+ int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks);
+ switch (errv) {
case OV_EREAD: { // - A read from media returned an error.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CANT_READ );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CANT_READ);
} break;
- case OV_EVERSION: // - Vorbis version mismatch.
+ case OV_EVERSION: // - Vorbis version mismatch.
case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
} break;
case OV_EBADHEADER: { // - Invalid Vorbis bitstream header.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CORRUPT );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CORRUPT);
} break;
case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_BUG );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_BUG);
} break;
}
- const vorbis_info *vinfo=ov_info(&vf,-1);
- stream_channels=vinfo->channels;
- stream_srate=vinfo->rate;
- length = ov_time_total(&vf,-1);
+ const vorbis_info *vinfo = ov_info(&vf, -1);
+ stream_channels = vinfo->channels;
+ stream_srate = vinfo->rate;
+ length = ov_time_total(&vf, -1);
ov_clear(&vf);
memdelete(f);
- f=NULL;
- stream_valid=true;
-
+ f = NULL;
+ stream_valid = true;
return OK;
}
-Error AudioStreamPlaybackOGGVorbis::_load_stream() {
+Error AudioStreamPlaybackOGGVorbis::_load_stream() {
- ERR_FAIL_COND_V(!stream_valid,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!stream_valid, ERR_UNCONFIGURED);
_clear_stream();
- if (file=="")
+ if (file == "")
return ERR_INVALID_DATA;
Error err;
- f=FileAccess::open(file,FileAccess::READ,&err);
+ f = FileAccess::open(file, FileAccess::READ, &err);
if (err) {
- ERR_FAIL_COND_V( err, err );
+ ERR_FAIL_COND_V(err, err);
}
- int errv = ov_open_callbacks(f,&vf,NULL,0,_ov_callbacks);
- switch(errv) {
+ int errv = ov_open_callbacks(f, &vf, NULL, 0, _ov_callbacks);
+ switch (errv) {
case OV_EREAD: { // - A read from media returned an error.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CANT_READ );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CANT_READ);
} break;
- case OV_EVERSION: // - Vorbis version mismatch.
+ case OV_EVERSION: // - Vorbis version mismatch.
case OV_ENOTVORBIS: { // - Bitstream is not Vorbis data.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_UNRECOGNIZED );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_UNRECOGNIZED);
} break;
case OV_EBADHEADER: { // - Invalid Vorbis bitstream header.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_FILE_CORRUPT );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_FILE_CORRUPT);
} break;
case OV_EFAULT: { // - Internal logic fault; indicates a bug or heap/stack corruption.
- memdelete(f); f=NULL;
- ERR_FAIL_V( ERR_BUG );
+ memdelete(f);
+ f = NULL;
+ ERR_FAIL_V(ERR_BUG);
} break;
}
- repeats=0;
- stream_loaded=true;
-
+ repeats = 0;
+ stream_loaded = true;
return OK;
}
-
float AudioStreamPlaybackOGGVorbis::get_length() const {
if (!stream_loaded) {
- if (const_cast<AudioStreamPlaybackOGGVorbis*>(this)->_load_stream()!=OK)
+ if (const_cast<AudioStreamPlaybackOGGVorbis *>(this)->_load_stream() != OK)
return 0;
}
return length;
@@ -359,14 +348,14 @@ void AudioStreamPlaybackOGGVorbis::_clear_stream() {
ov_clear(&vf);
_close_file();
- stream_loaded=false;
+ stream_loaded = false;
//stream_channels=1;
- playing=false;
+ playing = false;
}
void AudioStreamPlaybackOGGVorbis::set_paused(bool p_paused) {
- paused=p_paused;
+ paused = p_paused;
}
bool AudioStreamPlaybackOGGVorbis::is_paused(bool p_paused) const {
@@ -374,39 +363,34 @@ bool AudioStreamPlaybackOGGVorbis::is_paused(bool p_paused) const {
return paused;
}
-
AudioStreamPlaybackOGGVorbis::AudioStreamPlaybackOGGVorbis() {
- loops=false;
- playing=false;
- _ov_callbacks.read_func=_ov_read_func;
- _ov_callbacks.seek_func=_ov_seek_func;
- _ov_callbacks.close_func=_ov_close_func;
- _ov_callbacks.tell_func=_ov_tell_func;
+ loops = false;
+ playing = false;
+ _ov_callbacks.read_func = _ov_read_func;
+ _ov_callbacks.seek_func = _ov_seek_func;
+ _ov_callbacks.close_func = _ov_close_func;
+ _ov_callbacks.tell_func = _ov_tell_func;
f = NULL;
- stream_loaded=false;
- stream_valid=false;
- repeats=0;
- paused=true;
- stream_channels=0;
- stream_srate=0;
- current_section=0;
- length=0;
- loop_restart_time=0;
+ stream_loaded = false;
+ stream_valid = false;
+ repeats = 0;
+ paused = true;
+ stream_channels = 0;
+ stream_srate = 0;
+ current_section = 0;
+ length = 0;
+ loop_restart_time = 0;
}
-
AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() {
_clear_stream();
-
}
-
-
-RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=OK;
+ *r_error = OK;
AudioStreamOGGVorbis *ogg_stream = memnew(AudioStreamOGGVorbis);
ogg_stream->set_file(p_path);
@@ -419,12 +403,11 @@ void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List<St
}
String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="ogg")
+ if (p_path.get_extension().to_lower() == "ogg")
return "AudioStreamOGGVorbis";
return "";
}
-bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String& p_type) const {
- return (p_type=="AudioStream" || p_type=="AudioStreamOGG" || p_type=="AudioStreamOGGVorbis");
+bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String &p_type) const {
+ return (p_type == "AudioStream" || p_type == "AudioStreamOGG" || p_type == "AudioStreamOGGVorbis");
}
-
diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h
index bc2bfa2ae6..a13e934f2a 100644
--- a/modules/vorbis/audio_stream_ogg_vorbis.h
+++ b/modules/vorbis/audio_stream_ogg_vorbis.h
@@ -38,18 +38,18 @@
class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback {
- GDCLASS(AudioStreamPlaybackOGGVorbis,AudioStreamPlayback);
+ GDCLASS(AudioStreamPlaybackOGGVorbis, AudioStreamPlayback);
enum {
- MIN_MIX=1024
+ MIN_MIX = 1024
};
FileAccess *f;
ov_callbacks _ov_callbacks;
float length;
- static size_t _ov_read_func(void *p_dst,size_t p_data, size_t p_count, void *_f);
- static int _ov_seek_func(void *_f,ogg_int64_t offs, int whence);
+ static size_t _ov_read_func(void *p_dst, size_t p_data, size_t p_count, void *_f);
+ static int _ov_seek_func(void *_f, ogg_int64_t offs, int whence);
static int _ov_close_func(void *_f);
static long _ov_tell_func(void *_f);
@@ -63,7 +63,6 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback {
int stream_srate;
int current_section;
-
bool paused;
bool loops;
int repeats;
@@ -75,17 +74,14 @@ class AudioStreamPlaybackOGGVorbis : public AudioStreamPlayback {
bool stream_valid;
float loop_restart_time;
-
public:
+ Error set_file(const String &p_file);
-
- Error set_file(const String& p_file);
-
- virtual void play(float p_from=0);
+ virtual void play(float p_from = 0);
virtual void stop();
virtual bool is_playing() const;
- virtual void set_loop_restart_time(float p_time) { loop_restart_time=p_time; }
+ virtual void set_loop_restart_time(float p_time) { loop_restart_time = p_time; }
virtual void set_paused(bool p_paused);
virtual bool is_paused(bool p_paused) const;
@@ -106,37 +102,34 @@ public:
virtual int get_mix_rate() const { return stream_srate; }
virtual int get_minimum_buffer_size() const { return 0; }
- virtual int mix(int16_t* p_bufer,int p_frames);
+ virtual int mix(int16_t *p_bufer, int p_frames);
AudioStreamPlaybackOGGVorbis();
~AudioStreamPlaybackOGGVorbis();
};
-
class AudioStreamOGGVorbis : public AudioStream {
- GDCLASS(AudioStreamOGGVorbis,AudioStream);
+ GDCLASS(AudioStreamOGGVorbis, AudioStream);
String file;
-public:
+public:
Ref<AudioStreamPlayback> instance_playback() {
- Ref<AudioStreamPlaybackOGGVorbis> pb = memnew( AudioStreamPlaybackOGGVorbis );
+ Ref<AudioStreamPlaybackOGGVorbis> pb = memnew(AudioStreamPlaybackOGGVorbis);
pb->set_file(file);
return pb;
}
- void set_file(const String& p_file) { file=p_file; }
-
+ void set_file(const String &p_file) { file = p_file; }
};
class ResourceFormatLoaderAudioStreamOGGVorbis : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
};
-
#endif // AUDIO_STREAM_OGG_H
diff --git a/modules/vorbis/register_types.cpp b/modules/vorbis/register_types.cpp
index de929d9350..b405acd16b 100644
--- a/modules/vorbis/register_types.cpp
+++ b/modules/vorbis/register_types.cpp
@@ -34,12 +34,12 @@ static ResourceFormatLoaderAudioStreamOGGVorbis *vorbis_stream_loader = NULL;
void register_vorbis_types() {
- vorbis_stream_loader = memnew( ResourceFormatLoaderAudioStreamOGGVorbis );
+ vorbis_stream_loader = memnew(ResourceFormatLoaderAudioStreamOGGVorbis);
ResourceLoader::add_resource_format_loader(vorbis_stream_loader);
ClassDB::register_class<AudioStreamOGGVorbis>();
}
void unregister_vorbis_types() {
- memdelete( vorbis_stream_loader );
+ memdelete(vorbis_stream_loader);
}
diff --git a/modules/webm/video_stream_webm.cpp b/modules/webm/video_stream_webm.cpp
index d4995ad798..8d6fbdfe75 100644
--- a/modules/webm/video_stream_webm.cpp
+++ b/modules/webm/video_stream_webm.cpp
@@ -28,14 +28,14 @@
/*************************************************************************/
#include "video_stream_webm.h"
-#include "VPXDecoder.hpp"
#include "OpusVorbisDecoder.hpp"
+#include "VPXDecoder.hpp"
-#include "mkvparser/mkvparser.h"
#include "../theora/yuv2rgb.h"
+#include "mkvparser/mkvparser.h"
-#include "os/file_access.h"
#include "global_config.h"
+#include "os/file_access.h"
#include <string.h>
@@ -85,22 +85,21 @@ private:
/**/
-VideoStreamPlaybackWebm::VideoStreamPlaybackWebm() :
- audio_track(0),
- webm(NULL),
- video(NULL),
- audio(NULL),
- video_frames(NULL), audio_frame(NULL),
- video_frames_pos(0), video_frames_capacity(0),
- num_decoded_samples(0), samples_offset(-1),
- mix_callback(NULL),
- mix_udata(NULL),
- playing(false), paused(false),
- delay_compensation(0.0),
- time(0.0), video_frame_delay(0.0), video_pos(0.0),
- texture(memnew(ImageTexture)),
- pcm(NULL)
-{}
+VideoStreamPlaybackWebm::VideoStreamPlaybackWebm()
+ : audio_track(0),
+ webm(NULL),
+ video(NULL),
+ audio(NULL),
+ video_frames(NULL), audio_frame(NULL),
+ video_frames_pos(0), video_frames_capacity(0),
+ num_decoded_samples(0), samples_offset(-1),
+ mix_callback(NULL),
+ mix_udata(NULL),
+ playing(false), paused(false),
+ delay_compensation(0.0),
+ time(0.0), video_frame_delay(0.0), video_pos(0.0),
+ texture(memnew(ImageTexture)),
+ pcm(NULL) {}
VideoStreamPlaybackWebm::~VideoStreamPlaybackWebm() {
delete_pointers();
@@ -299,22 +298,22 @@ void VideoStreamPlaybackWebm::update(float p_delta) {
if (image.chromaShiftW == 1 && image.chromaShiftH == 1) {
yuv420_2_rgb8888(w.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
-// 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);
+ // 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.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
-// 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);
+ // 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.ptr(), image.planes[0], image.planes[2], image.planes[1], image.w, image.h, image.linesize[0], image.linesize[1], image.w << 2, 0);
-// 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);
+ // 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;
+ // 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;
}
if (converted)
@@ -361,8 +360,7 @@ int VideoStreamPlaybackWebm::get_mix_rate() const {
return 0;
}
-inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const
-{
+inline bool VideoStreamPlaybackWebm::has_enough_video_frames() const {
if (video_frames_pos > 0) {
const double audio_delay = AudioServer::get_singleton()->get_output_delay();
@@ -423,9 +421,8 @@ String ResourceFormatLoaderVideoStreamWebm::get_resource_type(const String &p_pa
/**/
-VideoStreamWebm::VideoStreamWebm() :
- audio_track(0)
-{}
+VideoStreamWebm::VideoStreamWebm()
+ : audio_track(0) {}
Ref<VideoStreamPlayback> VideoStreamWebm::instance_playback() {
diff --git a/modules/webm/video_stream_webm.h b/modules/webm/video_stream_webm.h
index cb4ef53f6d..2b62cf48b6 100644
--- a/modules/webm/video_stream_webm.h
+++ b/modules/webm/video_stream_webm.h
@@ -26,8 +26,8 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "scene/resources/video_stream.h"
#include "io/resource_loader.h"
+#include "scene/resources/video_stream.h"
class WebMFrame;
class WebMDemuxer;
diff --git a/modules/webp/image_loader_webp.cpp b/modules/webp/image_loader_webp.cpp
index 3508c6a663..829e77873a 100644
--- a/modules/webp/image_loader_webp.cpp
+++ b/modules/webp/image_loader_webp.cpp
@@ -29,59 +29,59 @@
#include "image_loader_webp.h"
#include "io/marshalls.h"
-#include "print_string.h"
#include "os/os.h"
+#include "print_string.h"
#include <stdlib.h>
#include <webp/decode.h>
#include <webp/encode.h>
-static PoolVector<uint8_t> _webp_lossy_pack(const Image& p_image,float p_quality) {
+static PoolVector<uint8_t> _webp_lossy_pack(const Image &p_image, float p_quality) {
- ERR_FAIL_COND_V(p_image.empty(),PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(p_image.empty(), PoolVector<uint8_t>());
- Image img=p_image;
+ Image img = p_image;
if (img.detect_alpha())
img.convert(Image::FORMAT_RGBA8);
else
img.convert(Image::FORMAT_RGB8);
- Size2 s(img.get_width(),img.get_height());
+ Size2 s(img.get_width(), img.get_height());
PoolVector<uint8_t> data = img.get_data();
PoolVector<uint8_t>::Read r = data.read();
- uint8_t *dst_buff=NULL;
- size_t dst_size=0;
- if (img.get_format()==Image::FORMAT_RGB8) {
+ uint8_t *dst_buff = NULL;
+ size_t dst_size = 0;
+ if (img.get_format() == Image::FORMAT_RGB8) {
- dst_size = WebPEncodeRGB(r.ptr(),s.width,s.height,3*s.width,CLAMP(p_quality*100.0,0,100.0),&dst_buff);
+ dst_size = WebPEncodeRGB(r.ptr(), s.width, s.height, 3 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff);
} else {
- dst_size = WebPEncodeRGBA(r.ptr(),s.width,s.height,4*s.width,CLAMP(p_quality*100.0,0,100.0),&dst_buff);
+ dst_size = WebPEncodeRGBA(r.ptr(), s.width, s.height, 4 * s.width, CLAMP(p_quality * 100.0, 0, 100.0), &dst_buff);
}
- ERR_FAIL_COND_V(dst_size==0,PoolVector<uint8_t>());
+ ERR_FAIL_COND_V(dst_size == 0, PoolVector<uint8_t>());
PoolVector<uint8_t> dst;
- dst.resize(4+dst_size);
+ dst.resize(4 + dst_size);
PoolVector<uint8_t>::Write w = dst.write();
- w[0]='W';
- w[1]='E';
- w[2]='B';
- w[3]='P';
- copymem(&w[4],dst_buff,dst_size);
+ w[0] = 'W';
+ w[1] = 'E';
+ w[2] = 'B';
+ w[3] = 'P';
+ copymem(&w[4], dst_buff, dst_size);
free(dst_buff);
- w=PoolVector<uint8_t>::Write();
+ w = PoolVector<uint8_t>::Write();
return dst;
}
-static Image _webp_lossy_unpack(const PoolVector<uint8_t>& p_buffer) {
+static Image _webp_lossy_unpack(const PoolVector<uint8_t> &p_buffer) {
- int size = p_buffer.size()-4;
- ERR_FAIL_COND_V(size<=0,Image());
+ int size = p_buffer.size() - 4;
+ ERR_FAIL_COND_V(size <= 0, Image());
PoolVector<uint8_t>::Read r = p_buffer.read();
- ERR_FAIL_COND_V(r[0]!='W' || r[1]!='E' || r[2]!='B' || r[3]!='P',Image());
+ ERR_FAIL_COND_V(r[0] != 'W' || r[1] != 'E' || r[2] != 'B' || r[3] != 'P', Image());
WebPBitstreamFeatures features;
- if (WebPGetFeatures(&r[4],size,&features)!=VP8_STATUS_OK) {
+ if (WebPGetFeatures(&r[4], size, &features) != VP8_STATUS_OK) {
ERR_EXPLAIN("Error unpacking WEBP image:");
ERR_FAIL_V(Image());
}
@@ -91,31 +91,27 @@ static Image _webp_lossy_unpack(const PoolVector<uint8_t>& p_buffer) {
//print_line("alpha: "+itos(features.has_alpha));
PoolVector<uint8_t> dst_image;
- int datasize = features.width*features.height*(features.has_alpha?4:3);
+ int datasize = features.width * features.height * (features.has_alpha ? 4 : 3);
dst_image.resize(datasize);
PoolVector<uint8_t>::Write dst_w = dst_image.write();
- bool errdec=false;
- if (features.has_alpha) {
- errdec = WebPDecodeRGBAInto(&r[4],size,dst_w.ptr(),datasize,4*features.width)==NULL;
+ bool errdec = false;
+ if (features.has_alpha) {
+ errdec = WebPDecodeRGBAInto(&r[4], size, dst_w.ptr(), datasize, 4 * features.width) == NULL;
} else {
- errdec = WebPDecodeRGBInto(&r[4],size,dst_w.ptr(),datasize,3*features.width)==NULL;
-
+ errdec = WebPDecodeRGBInto(&r[4], size, dst_w.ptr(), datasize, 3 * features.width) == NULL;
}
//ERR_EXPLAIN("Error decoding webp! - "+p_file);
- ERR_FAIL_COND_V(errdec,Image());
+ ERR_FAIL_COND_V(errdec, Image());
dst_w = PoolVector<uint8_t>::Write();
- return Image(features.width,features.height,0,features.has_alpha?Image::FORMAT_RGBA8:Image::FORMAT_RGB8,dst_image);
-
+ return Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
}
-
-Error ImageLoaderWEBP::load_image(Image *p_image,FileAccess *f) {
-
+Error ImageLoaderWEBP::load_image(Image *p_image, FileAccess *f) {
uint32_t size = f->get_len();
PoolVector<uint8_t> src_image;
@@ -124,60 +120,53 @@ Error ImageLoaderWEBP::load_image(Image *p_image,FileAccess *f) {
WebPBitstreamFeatures features;
PoolVector<uint8_t>::Write src_w = src_image.write();
- f->get_buffer(src_w.ptr(),size);
+ f->get_buffer(src_w.ptr(), size);
ERR_FAIL_COND_V(f->eof_reached(), ERR_FILE_EOF);
- if (WebPGetFeatures(src_w.ptr(),size,&features)!=VP8_STATUS_OK) {
+ if (WebPGetFeatures(src_w.ptr(), size, &features) != VP8_STATUS_OK) {
f->close();
//ERR_EXPLAIN("Error decoding WEBP image: "+p_file);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- print_line("width: "+itos(features.width));
- print_line("height: "+itos(features.height));
- print_line("alpha: "+itos(features.has_alpha));
+ print_line("width: " + itos(features.width));
+ print_line("height: " + itos(features.height));
+ print_line("alpha: " + itos(features.has_alpha));
src_w = PoolVector<uint8_t>::Write();
PoolVector<uint8_t> dst_image;
- int datasize = features.width*features.height*(features.has_alpha?4:3);
+ int datasize = features.width * features.height * (features.has_alpha ? 4 : 3);
dst_image.resize(datasize);
PoolVector<uint8_t>::Read src_r = src_image.read();
PoolVector<uint8_t>::Write dst_w = dst_image.write();
-
- bool errdec=false;
- if (features.has_alpha) {
- errdec = WebPDecodeRGBAInto(src_r.ptr(),size,dst_w.ptr(),datasize,4*features.width)==NULL;
+ bool errdec = false;
+ if (features.has_alpha) {
+ errdec = WebPDecodeRGBAInto(src_r.ptr(), size, dst_w.ptr(), datasize, 4 * features.width) == NULL;
} else {
- errdec = WebPDecodeRGBInto(src_r.ptr(),size,dst_w.ptr(),datasize,3*features.width)==NULL;
-
+ errdec = WebPDecodeRGBInto(src_r.ptr(), size, dst_w.ptr(), datasize, 3 * features.width) == NULL;
}
//ERR_EXPLAIN("Error decoding webp! - "+p_file);
- ERR_FAIL_COND_V(errdec,ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(errdec, ERR_FILE_CORRUPT);
src_r = PoolVector<uint8_t>::Read();
dst_w = PoolVector<uint8_t>::Write();
- *p_image = Image(features.width,features.height,0,features.has_alpha?Image::FORMAT_RGBA8:Image::FORMAT_RGB8,dst_image);
-
+ *p_image = Image(features.width, features.height, 0, features.has_alpha ? Image::FORMAT_RGBA8 : Image::FORMAT_RGB8, dst_image);
return OK;
-
}
void ImageLoaderWEBP::get_recognized_extensions(List<String> *p_extensions) const {
-
+
p_extensions->push_back("webp");
}
-
ImageLoaderWEBP::ImageLoaderWEBP() {
- Image::lossy_packer=_webp_lossy_pack;
- Image::lossy_unpacker=_webp_lossy_unpack;
+ Image::lossy_packer = _webp_lossy_pack;
+ Image::lossy_unpacker = _webp_lossy_unpack;
}
-
-
diff --git a/modules/webp/image_loader_webp.h b/modules/webp/image_loader_webp.h
index eb1b32ac95..ccf22bae13 100644
--- a/modules/webp/image_loader_webp.h
+++ b/modules/webp/image_loader_webp.h
@@ -36,14 +36,10 @@
*/
class ImageLoaderWEBP : public ImageFormatLoader {
-
public:
-
- virtual Error load_image(Image *p_image,FileAccess *f);
- virtual void get_recognized_extensions(List<String> *p_extensions) const;
+ virtual Error load_image(Image *p_image, FileAccess *f);
+ virtual void get_recognized_extensions(List<String> *p_extensions) const;
ImageLoaderWEBP();
};
-
-
#endif
diff --git a/modules/webp/register_types.cpp b/modules/webp/register_types.cpp
index 7a4e35dc4c..8a708aae6a 100644
--- a/modules/webp/register_types.cpp
+++ b/modules/webp/register_types.cpp
@@ -34,11 +34,11 @@ static ImageLoaderWEBP *image_loader_webp = NULL;
void register_webp_types() {
- image_loader_webp = memnew( ImageLoaderWEBP );
+ image_loader_webp = memnew(ImageLoaderWEBP);
ImageLoader::add_image_format_loader(image_loader_webp);
}
void unregister_webp_types() {
- memdelete( image_loader_webp );
+ memdelete(image_loader_webp);
}
diff --git a/platform/android/audio_driver_jandroid.cpp b/platform/android/audio_driver_jandroid.cpp
index 415223c1da..5e30289310 100644
--- a/platform/android/audio_driver_jandroid.cpp
+++ b/platform/android/audio_driver_jandroid.cpp
@@ -34,34 +34,32 @@
#ifndef ANDROID_NATIVE_ACTIVITY
-AudioDriverAndroid* AudioDriverAndroid::s_ad=NULL;
+AudioDriverAndroid *AudioDriverAndroid::s_ad = NULL;
jobject AudioDriverAndroid::io;
jmethodID AudioDriverAndroid::_init_audio;
jmethodID AudioDriverAndroid::_write_buffer;
jmethodID AudioDriverAndroid::_quit;
jmethodID AudioDriverAndroid::_pause;
-bool AudioDriverAndroid::active=false;
+bool AudioDriverAndroid::active = false;
jclass AudioDriverAndroid::cls;
-int AudioDriverAndroid::audioBufferFrames=0;
-int AudioDriverAndroid::mix_rate=44100;
-bool AudioDriverAndroid::quit=false;
+int AudioDriverAndroid::audioBufferFrames = 0;
+int AudioDriverAndroid::mix_rate = 44100;
+bool AudioDriverAndroid::quit = false;
jobject AudioDriverAndroid::audioBuffer = NULL;
-void* AudioDriverAndroid::audioBufferPinned = NULL;
-Mutex *AudioDriverAndroid::mutex=NULL;
-int32_t* AudioDriverAndroid::audioBuffer32=NULL;
+void *AudioDriverAndroid::audioBufferPinned = NULL;
+Mutex *AudioDriverAndroid::mutex = NULL;
+int32_t *AudioDriverAndroid::audioBuffer32 = NULL;
-
-const char* AudioDriverAndroid::get_name() const {
+const char *AudioDriverAndroid::get_name() const {
return "Android";
}
-
-Error AudioDriverAndroid::init(){
+Error AudioDriverAndroid::init() {
mutex = Mutex::create();
-/*
+ /*
// TODO: pass in/return a (Java) device ID, also whether we're opening for input or output
this->spec.samples = Android_JNI_OpenAudioDevice(this->spec.freq, this->spec.format == AUDIO_U8 ? 0 : 1, this->spec.channels, this->spec.samples);
SDL_CalculateAudioSpec(&this->spec);
@@ -75,76 +73,68 @@ Error AudioDriverAndroid::init(){
//Android_JNI_SetupThread();
-
- // __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
-
+ // __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
JNIEnv *env = ThreadAndroid::get_env();
- int mix_rate = GLOBAL_DEF("audio/mix_rate",44100);
+ int mix_rate = GLOBAL_DEF("audio/mix_rate", 44100);
- int latency = GLOBAL_DEF("audio/output_latency",25);
- latency=50;
- unsigned int buffer_size = nearest_power_of_2( latency * mix_rate / 1000 );
+ int latency = GLOBAL_DEF("audio/output_latency", 25);
+ latency = 50;
+ unsigned int buffer_size = nearest_power_of_2(latency * mix_rate / 1000);
if (OS::get_singleton()->is_stdout_verbose()) {
- print_line("audio buffer size: "+itos(buffer_size));
+ print_line("audio buffer size: " + itos(buffer_size));
}
- __android_log_print(ANDROID_LOG_INFO,"godot","Initializing audio! params: %i,%i ",mix_rate,buffer_size);
- audioBuffer = env->CallObjectMethod(io,_init_audio, mix_rate, buffer_size);
-
+ __android_log_print(ANDROID_LOG_INFO, "godot", "Initializing audio! params: %i,%i ", mix_rate, buffer_size);
+ audioBuffer = env->CallObjectMethod(io, _init_audio, mix_rate, buffer_size);
- ERR_FAIL_COND_V( audioBuffer == NULL, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(audioBuffer == NULL, ERR_INVALID_PARAMETER);
audioBuffer = env->NewGlobalRef(audioBuffer);
jboolean isCopy = JNI_FALSE;
audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
- audioBuffer32 = memnew_arr(int32_t,audioBufferFrames);
+ audioBuffer32 = memnew_arr(int32_t, audioBufferFrames);
return OK;
}
-void AudioDriverAndroid::start(){
- active=true;
-
+void AudioDriverAndroid::start() {
+ active = true;
}
-void AudioDriverAndroid::setup( jobject p_io) {
+void AudioDriverAndroid::setup(jobject p_io) {
JNIEnv *env = ThreadAndroid::get_env();
- io=p_io;
+ io = p_io;
jclass c = env->GetObjectClass(io);
cls = (jclass)env->NewGlobalRef(c);
-
- __android_log_print(ANDROID_LOG_INFO,"godot","starting to attempt get methods");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "starting to attempt get methods");
_init_audio = env->GetMethodID(cls, "audioInit", "(II)Ljava/lang/Object;");
- if(_init_audio != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _init_audio ok!!");
+ if (_init_audio != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _init_audio ok!!");
} else {
- __android_log_print(ANDROID_LOG_INFO,"godot","audioinit ok!");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "audioinit ok!");
}
_write_buffer = env->GetMethodID(cls, "audioWriteShortBuffer", "([S)V");
- if(_write_buffer != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _write_buffer ok!!");
+ if (_write_buffer != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _write_buffer ok!!");
}
-
_quit = env->GetMethodID(cls, "audioQuit", "()V");
- if(_quit != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _quit ok!!");
+ if (_quit != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _quit ok!!");
}
_pause = env->GetMethodID(cls, "audioPause", "(Z)V");
- if(_quit != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _pause ok!!");
+ if (_quit != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _pause ok!!");
}
-
-
}
void AudioDriverAndroid::thread_func(JNIEnv *env) {
@@ -152,48 +142,44 @@ void AudioDriverAndroid::thread_func(JNIEnv *env) {
jclass cls = env->FindClass("org/godotengine/godot/Godot");
if (cls) {
- cls=(jclass)env->NewGlobalRef(cls);
- __android_log_print(ANDROID_LOG_INFO,"godot","*******CLASS FOUND!!!");
+ cls = (jclass)env->NewGlobalRef(cls);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******CLASS FOUND!!!");
}
jfieldID fid = env->GetStaticFieldID(cls, "io", "Lorg/godotengine/godot/GodotIO;");
- jobject ob = env->GetStaticObjectField(cls,fid);
+ jobject ob = env->GetStaticObjectField(cls, fid);
jobject gob = env->NewGlobalRef(ob);
jclass c = env->GetObjectClass(gob);
jclass lcls = (jclass)env->NewGlobalRef(c);
_write_buffer = env->GetMethodID(lcls, "audioWriteShortBuffer", "([S)V");
- if(_write_buffer != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _write_buffer ok!!");
+ if (_write_buffer != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _write_buffer ok!!");
}
- while(!quit) {
-
+ while (!quit) {
- int16_t* ptr = (int16_t*)audioBufferPinned;
+ int16_t *ptr = (int16_t *)audioBufferPinned;
int fc = audioBufferFrames;
- if (!s_ad->active || mutex->try_lock()!=OK) {
+ if (!s_ad->active || mutex->try_lock() != OK) {
- for(int i=0;i<fc;i++) {
- ptr[i]=0;
+ for (int i = 0; i < fc; i++) {
+ ptr[i] = 0;
}
} else {
-
- s_ad->audio_server_process(fc/2,audioBuffer32);
+ s_ad->audio_server_process(fc / 2, audioBuffer32);
mutex->unlock();
- for(int i=0;i<fc;i++) {
+ for (int i = 0; i < fc; i++) {
- ptr[i]=audioBuffer32[i]>>16;
+ ptr[i] = audioBuffer32[i] >> 16;
}
-
}
env->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)ptr, JNI_COMMIT);
env->CallVoidMethod(gob, _write_buffer, (jshortArray)audioBuffer);
}
-
}
int AudioDriverAndroid::get_mix_rate() const {
@@ -201,16 +187,15 @@ int AudioDriverAndroid::get_mix_rate() const {
return mix_rate;
}
-AudioDriver::SpeakerMode AudioDriverAndroid::get_speaker_mode() const{
+AudioDriver::SpeakerMode AudioDriverAndroid::get_speaker_mode() const {
return SPEAKER_MODE_STEREO;
}
-void AudioDriverAndroid::lock(){
+void AudioDriverAndroid::lock() {
if (mutex)
mutex->lock();
-
}
void AudioDriverAndroid::unlock() {
@@ -219,7 +204,7 @@ void AudioDriverAndroid::unlock() {
mutex->unlock();
}
-void AudioDriverAndroid::finish(){
+void AudioDriverAndroid::finish() {
JNIEnv *env = ThreadAndroid::get_env();
env->CallVoidMethod(io, _quit);
@@ -230,21 +215,19 @@ void AudioDriverAndroid::finish(){
audioBufferPinned = NULL;
}
- active=false;
+ active = false;
}
void AudioDriverAndroid::set_pause(bool p_pause) {
JNIEnv *env = ThreadAndroid::get_env();
- env->CallVoidMethod(io, _pause,p_pause);
-
+ env->CallVoidMethod(io, _pause, p_pause);
}
AudioDriverAndroid::AudioDriverAndroid() {
- s_ad=this;
- active=false;
-
+ s_ad = this;
+ active = false;
}
#endif
diff --git a/platform/android/audio_driver_jandroid.h b/platform/android/audio_driver_jandroid.h
index f485df2001..4b5131cdc0 100644
--- a/platform/android/audio_driver_jandroid.h
+++ b/platform/android/audio_driver_jandroid.h
@@ -37,9 +37,8 @@
class AudioDriverAndroid : public AudioDriver {
-
static Mutex *mutex;
- static AudioDriverAndroid* s_ad;
+ static AudioDriverAndroid *s_ad;
static jobject io;
static jmethodID _init_audio;
static jmethodID _write_buffer;
@@ -51,21 +50,19 @@ class AudioDriverAndroid : public AudioDriver {
static jclass cls;
static jobject audioBuffer;
- static void* audioBufferPinned;
- static int32_t* audioBuffer32;
+ static void *audioBufferPinned;
+ static int32_t *audioBuffer32;
static int audioBufferFrames;
static int mix_rate;
-
public:
-
void set_singleton();
- virtual const char* get_name() const;
+ virtual const char *get_name() const;
virtual Error init();
virtual void start();
- virtual int get_mix_rate() const ;
+ virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
virtual void lock();
virtual void unlock();
@@ -73,7 +70,7 @@ public:
virtual void set_pause(bool p_pause);
- static void setup( jobject act);
+ static void setup(jobject act);
static void thread_func(JNIEnv *env);
AudioDriverAndroid();
diff --git a/platform/android/audio_driver_opensl.cpp b/platform/android/audio_driver_opensl.cpp
index 2ec80f23c3..bba98dd623 100644
--- a/platform/android/audio_driver_opensl.cpp
+++ b/platform/android/audio_driver_opensl.cpp
@@ -35,48 +35,45 @@
/* Structure for passing information to callback function */
-
void AudioDriverOpenSL::_buffer_callback(
- SLAndroidSimpleBufferQueueItf queueItf
- /* SLuint32 eventFlags,
+ SLAndroidSimpleBufferQueueItf queueItf
+ /* SLuint32 eventFlags,
const void * pBuffer,
SLuint32 bufferSize,
SLuint32 dataUsed*/) {
- bool mix=true;
+ bool mix = true;
if (pause) {
- mix=false;
+ mix = false;
} else if (mutex) {
- mix = mutex->try_lock()==OK;
+ mix = mutex->try_lock() == OK;
}
if (mix) {
- audio_server_process(buffer_size,mixdown_buffer);
+ audio_server_process(buffer_size, mixdown_buffer);
} else {
- int32_t* src_buff=mixdown_buffer;
- for(int i=0;i<buffer_size*2;i++) {
- src_buff[i]=0;
+ int32_t *src_buff = mixdown_buffer;
+ for (int i = 0; i < buffer_size * 2; i++) {
+ src_buff[i] = 0;
}
}
if (mutex && mix)
mutex->unlock();
+ const int32_t *src_buff = mixdown_buffer;
- const int32_t* src_buff=mixdown_buffer;
-
- int16_t *ptr = (int16_t*)buffers[last_free];
- last_free=(last_free+1)%BUFFER_COUNT;
+ int16_t *ptr = (int16_t *)buffers[last_free];
+ last_free = (last_free + 1) % BUFFER_COUNT;
- for(int i=0;i<buffer_size*2;i++) {
+ for (int i = 0; i < buffer_size * 2; i++) {
- ptr[i]=src_buff[i]>>16;
+ ptr[i] = src_buff[i] >> 16;
}
- (*queueItf)->Enqueue(queueItf, ptr, 4 * buffer_size);
-
+ (*queueItf)->Enqueue(queueItf, ptr, 4 * buffer_size);
#if 0
SLresult res;
@@ -95,25 +92,22 @@ void AudioDriverOpenSL::_buffer_callback(
}
void AudioDriverOpenSL::_buffer_callbacks(
- SLAndroidSimpleBufferQueueItf queueItf,
- /*SLuint32 eventFlags,
+ SLAndroidSimpleBufferQueueItf queueItf,
+ /*SLuint32 eventFlags,
const void * pBuffer,
SLuint32 bufferSize,
SLuint32 dataUsed,*/
- void *pContext) {
-
+ void *pContext) {
- AudioDriverOpenSL *ad = (AudioDriverOpenSL*)pContext;
+ AudioDriverOpenSL *ad = (AudioDriverOpenSL *)pContext;
//ad->_buffer_callback(queueItf,eventFlags,pBuffer,bufferSize,dataUsed);
ad->_buffer_callback(queueItf);
-
}
+AudioDriverOpenSL *AudioDriverOpenSL::s_ad = NULL;
-AudioDriverOpenSL* AudioDriverOpenSL::s_ad=NULL;
-
-const char* AudioDriverOpenSL::get_name() const {
+const char *AudioDriverOpenSL::get_name() const {
return "Android";
}
@@ -177,23 +171,23 @@ int AudioDriverOpenSL::thread_func(SceSize args, void *argp) {
}
#endif
-Error AudioDriverOpenSL::init(){
+Error AudioDriverOpenSL::init() {
SLresult
- res;
+ res;
SLEngineOption EngineOption[] = {
- (SLuint32) SL_ENGINEOPTION_THREADSAFE,
- (SLuint32) SL_BOOLEAN_TRUE
+ (SLuint32)SL_ENGINEOPTION_THREADSAFE,
+ (SLuint32)SL_BOOLEAN_TRUE
};
- res = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL);
- if (res!=SL_RESULT_SUCCESS) {
+ res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL);
+ if (res != SL_RESULT_SUCCESS) {
ERR_EXPLAIN("Could not Initialize OpenSL");
ERR_FAIL_V(ERR_INVALID_PARAMETER);
}
res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE);
- if (res!=SL_RESULT_SUCCESS) {
+ if (res != SL_RESULT_SUCCESS) {
ERR_EXPLAIN("Could not Realize OpenSL");
ERR_FAIL_V(ERR_INVALID_PARAMETER);
@@ -202,37 +196,33 @@ Error AudioDriverOpenSL::init(){
print_line("OpenSL Init OK!");
return OK;
-
}
-void AudioDriverOpenSL::start(){
-
+void AudioDriverOpenSL::start() {
mutex = Mutex::create();
- active=false;
-
+ active = false;
SLint32 numOutputs = 0;
SLuint32 deviceID = 0;
SLresult res;
-
buffer_size = 1024;
- for(int i=0;i<BUFFER_COUNT;i++) {
+ for (int i = 0; i < BUFFER_COUNT; i++) {
- buffers[i]=memnew_arr( int16_t,buffer_size*2 );
- memset(buffers[i],0,buffer_size*4);
+ buffers[i] = memnew_arr(int16_t, buffer_size * 2);
+ memset(buffers[i], 0, buffer_size * 4);
}
- mixdown_buffer = memnew_arr( int32_t,buffer_size* 2);
+ mixdown_buffer = memnew_arr(int32_t, buffer_size * 2);
/* Callback context for the buffer queue callback function */
/* Get the SL Engine Interface which is implicit */
- res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void*)&EngineItf);
+ res = (*sl)->GetInterface(sl, SL_IID_ENGINE, (void *)&EngineItf);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
/* Initialize arrays required[] and iidArray[] */
SLboolean required[MAX_NUMBER_INTERFACES];
SLInterfaceID iidArray[MAX_NUMBER_INTERFACES];
@@ -254,20 +244,18 @@ void AudioDriverOpenSL::start(){
#else
{
- const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB};
- const SLboolean req[1] = {SL_BOOLEAN_FALSE};
- res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0,
- ids, req);
+ const SLInterfaceID ids[1] = { SL_IID_ENVIRONMENTALREVERB };
+ const SLboolean req[1] = { SL_BOOLEAN_FALSE };
+ res = (*EngineItf)->CreateOutputMix(EngineItf, &OutputMix, 0, ids, req);
}
-
#endif
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
- // Realizing the Output Mix object in synchronous mode.
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
+ // Realizing the Output Mix object in synchronous mode.
res = (*OutputMix)->Realize(OutputMix, SL_BOOLEAN_FALSE);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
- SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_COUNT};
+ SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, BUFFER_COUNT };
//bufferQueue.locatorType = SL_DATALOCATOR_BUFFERQUEUE;
//bufferQueue.numBuffers = BUFFER_COUNT; /* Four buffers in our buffer queue */
/* Setup the format of the content in the buffer queue */
@@ -285,10 +273,9 @@ void AudioDriverOpenSL::start(){
audioSource.pFormat = (void *)&pcm;
audioSource.pLocator = (void *)&loc_bufq;
-
/* Setup the data sink structure */
locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX;
- locator_outputmix.outputMix= OutputMix;
+ locator_outputmix.outputMix = OutputMix;
audioSink.pLocator = (void *)&locator_outputmix;
audioSink.pFormat = NULL;
/* Initialize the context for Buffer queue callbacks */
@@ -302,27 +289,25 @@ void AudioDriverOpenSL::start(){
/* Create the music player */
{
- const SLInterfaceID ids[2] = {SL_IID_BUFFERQUEUE, SL_IID_EFFECTSEND};
- const SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
+ const SLInterfaceID ids[2] = { SL_IID_BUFFERQUEUE, SL_IID_EFFECTSEND };
+ const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE };
- res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player,
- &audioSource, &audioSink, 1, ids, req);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ res = (*EngineItf)->CreateAudioPlayer(EngineItf, &player, &audioSource, &audioSink, 1, ids, req);
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
}
/* Realizing the player in synchronous mode. */
res = (*player)->Realize(player, SL_BOOLEAN_FALSE);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
/* Get seek and play interfaces */
- res = (*player)->GetInterface(player, SL_IID_PLAY, (void*)&playItf);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ res = (*player)->GetInterface(player, SL_IID_PLAY, (void *)&playItf);
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
res = (*player)->GetInterface(player, SL_IID_BUFFERQUEUE,
- (void*)&bufferQueueItf);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ (void *)&bufferQueueItf);
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
/* Setup to receive buffer queue event callbacks */
- res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf,
- _buffer_callbacks, this);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
- /* Before we start set volume to -3dB (-300mB) */
+ res = (*bufferQueueItf)->RegisterCallback(bufferQueueItf, _buffer_callbacks, this);
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
+/* Before we start set volume to -3dB (-300mB) */
#if 0
res = (*OutputMix)->GetInterface(OutputMix, SL_IID_VOLUME,
(void*)&volumeItf);
@@ -332,19 +317,17 @@ void AudioDriverOpenSL::start(){
res = (*volumeItf)->SetVolumeLevel(volumeItf, -300);
ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
#endif
- last_free=0;
+ last_free = 0;
#if 1
//fill up buffers
- for(int i=0;i<BUFFER_COUNT;i++) {
+ for (int i = 0; i < BUFFER_COUNT; i++) {
/* Enqueue a few buffers to get the ball rolling */
- res = (*bufferQueueItf)->Enqueue(bufferQueueItf, buffers[i],
- 4 * buffer_size); /* Size given in */
-
+ res = (*bufferQueueItf)->Enqueue(bufferQueueItf, buffers[i], 4 * buffer_size); /* Size given in */
}
#endif
res = (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
- ERR_FAIL_COND( res !=SL_RESULT_SUCCESS );
+ ERR_FAIL_COND(res != SL_RESULT_SUCCESS);
#if 0
res = (*bufferQueueItf)->GetState(bufferQueueItf, &state);
@@ -362,7 +345,7 @@ void AudioDriverOpenSL::start(){
(*OutputMix)->Destroy(OutputMix);
#endif
- active=true;
+ active = true;
}
int AudioDriverOpenSL::get_mix_rate() const {
@@ -370,34 +353,31 @@ int AudioDriverOpenSL::get_mix_rate() const {
return 44100;
}
-AudioDriver::SpeakerMode AudioDriverOpenSL::get_speaker_mode() const{
+AudioDriver::SpeakerMode AudioDriverOpenSL::get_speaker_mode() const {
return SPEAKER_MODE_STEREO;
}
-void AudioDriverOpenSL::lock(){
+void AudioDriverOpenSL::lock() {
if (active && mutex)
mutex->lock();
-
}
void AudioDriverOpenSL::unlock() {
if (active && mutex)
mutex->unlock();
-
}
-void AudioDriverOpenSL::finish(){
+void AudioDriverOpenSL::finish() {
(*sl)->Destroy(sl);
-
}
void AudioDriverOpenSL::set_pause(bool p_pause) {
- pause=p_pause;
+ pause = p_pause;
if (active) {
if (pause) {
@@ -408,13 +388,8 @@ void AudioDriverOpenSL::set_pause(bool p_pause) {
}
}
-
-AudioDriverOpenSL::AudioDriverOpenSL()
-{
- s_ad=this;
- mutex=Mutex::create();//NULL;
- pause=false;
+AudioDriverOpenSL::AudioDriverOpenSL() {
+ s_ad = this;
+ mutex = Mutex::create(); //NULL;
+ pause = false;
}
-
-
-
diff --git a/platform/android/audio_driver_opensl.h b/platform/android/audio_driver_opensl.h
index 1baaa95052..306589aa23 100644
--- a/platform/android/audio_driver_opensl.h
+++ b/platform/android/audio_driver_opensl.h
@@ -29,8 +29,8 @@
#ifndef AUDIO_DRIVER_OPENSL_H
#define AUDIO_DRIVER_OPENSL_H
-#include "servers/audio_server.h"
#include "os/mutex.h"
+#include "servers/audio_server.h"
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
@@ -42,18 +42,16 @@ class AudioDriverOpenSL : public AudioDriver {
enum {
- BUFFER_COUNT=2
+ BUFFER_COUNT = 2
};
bool pause;
-
uint32_t buffer_size;
int16_t *buffers[BUFFER_COUNT];
int32_t *mixdown_buffer;
int last_free;
-
SLPlayItf playItf;
SLObjectItf sl;
SLEngineItf EngineItf;
@@ -67,31 +65,31 @@ class AudioDriverOpenSL : public AudioDriver {
SLDataLocator_OutputMix locator_outputmix;
SLBufferQueueState state;
- static AudioDriverOpenSL* s_ad;
+ static AudioDriverOpenSL *s_ad;
void _buffer_callback(
- SLAndroidSimpleBufferQueueItf queueItf
- /* SLuint32 eventFlags,
+ SLAndroidSimpleBufferQueueItf queueItf
+ /* SLuint32 eventFlags,
const void * pBuffer,
SLuint32 bufferSize,
SLuint32 dataUsed*/);
static void _buffer_callbacks(
- SLAndroidSimpleBufferQueueItf queueItf,
- /*SLuint32 eventFlags,
+ SLAndroidSimpleBufferQueueItf queueItf,
+ /*SLuint32 eventFlags,
const void * pBuffer,
SLuint32 bufferSize,
SLuint32 dataUsed,*/
- void *pContext);
-public:
+ void *pContext);
+public:
void set_singleton();
- virtual const char* get_name() const;
+ virtual const char *get_name() const;
virtual Error init();
virtual void start();
- virtual int get_mix_rate() const ;
+ virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
virtual void lock();
virtual void unlock();
@@ -103,4 +101,3 @@ public:
};
#endif // AUDIO_DRIVER_ANDROID_H
-
diff --git a/platform/android/dir_access_android.cpp b/platform/android/dir_access_android.cpp
index 82b2761bb0..989bd02bd9 100644
--- a/platform/android/dir_access_android.cpp
+++ b/platform/android/dir_access_android.cpp
@@ -30,8 +30,6 @@
#include "dir_access_android.h"
#include "file_access_android.h"
-
-
DirAccess *DirAccessAndroid::create_fs() {
return memnew(DirAccessAndroid);
@@ -41,36 +39,33 @@ Error DirAccessAndroid::list_dir_begin() {
list_dir_end();
- AAssetDir* aad = AAssetManager_openDir(FileAccessAndroid::asset_manager,current_dir.utf8().get_data());
+ AAssetDir *aad = AAssetManager_openDir(FileAccessAndroid::asset_manager, current_dir.utf8().get_data());
if (!aad)
return ERR_CANT_OPEN; //nothing
-
return OK;
}
-String DirAccessAndroid::get_next(){
+String DirAccessAndroid::get_next() {
- const char* fn= AAssetDir_getNextFileName(aad);
+ const char *fn = AAssetDir_getNextFileName(aad);
if (!fn)
return "";
String s;
s.parse_utf8(fn);
- current=s;
+ current = s;
return s;
-
-
}
-bool DirAccessAndroid::current_is_dir() const{
+bool DirAccessAndroid::current_is_dir() const {
String sd;
- if (current_dir=="")
- sd=current;
+ if (current_dir == "")
+ sd = current;
else
- sd=current_dir+"/"+current;
+ sd = current_dir + "/" + current;
- AAssetDir* aad2 = AAssetManager_openDir(FileAccessAndroid::asset_manager,sd.utf8().get_data());
+ AAssetDir *aad2 = AAssetManager_openDir(FileAccessAndroid::asset_manager, sd.utf8().get_data());
if (aad2) {
AAssetDir_close(aad2);
@@ -78,56 +73,54 @@ bool DirAccessAndroid::current_is_dir() const{
}
return false;
-
}
-bool DirAccessAndroid::current_is_hidden() const{
- return current!="." && current!=".." && current.begins_with(".");
+bool DirAccessAndroid::current_is_hidden() const {
+ return current != "." && current != ".." && current.begins_with(".");
}
-void DirAccessAndroid::list_dir_end(){
+void DirAccessAndroid::list_dir_end() {
- if (aad==NULL)
+ if (aad == NULL)
return;
AAssetDir_close(aad);
- aad=NULL;
-
+ aad = NULL;
}
-int DirAccessAndroid::get_drive_count(){
+int DirAccessAndroid::get_drive_count() {
return 0;
}
-String DirAccessAndroid::get_drive(int p_drive){
+String DirAccessAndroid::get_drive(int p_drive) {
return "";
}
-Error DirAccessAndroid::change_dir(String p_dir){
+Error DirAccessAndroid::change_dir(String p_dir) {
- p_dir=p_dir.simplify_path();
+ p_dir = p_dir.simplify_path();
- if (p_dir=="" || p_dir=="." || (p_dir==".." && current_dir==""))
+ if (p_dir == "" || p_dir == "." || (p_dir == ".." && current_dir == ""))
return OK;
String new_dir;
if (p_dir.begins_with("/"))
- new_dir=p_dir.substr(1,p_dir.length());
+ new_dir = p_dir.substr(1, p_dir.length());
else if (p_dir.begins_with("res://"))
- new_dir=p_dir.substr(6,p_dir.length());
- else //relative
- new_dir=new_dir+"/"+p_dir;
+ new_dir = p_dir.substr(6, p_dir.length());
+ else //relative
+ new_dir = new_dir + "/" + p_dir;
-//test if newdir exists
- new_dir=new_dir.simplify_path();
+ //test if newdir exists
+ new_dir = new_dir.simplify_path();
- AAssetDir* aad = AAssetManager_openDir(FileAccessAndroid::asset_manager,new_dir.utf8().get_data());
+ AAssetDir *aad = AAssetManager_openDir(FileAccessAndroid::asset_manager, new_dir.utf8().get_data());
if (aad) {
- current_dir=new_dir;
+ current_dir = new_dir;
AAssetDir_close(aad);
return OK;
}
@@ -135,21 +128,20 @@ Error DirAccessAndroid::change_dir(String p_dir){
return ERR_INVALID_PARAMETER;
}
-String DirAccessAndroid::get_current_dir(){
+String DirAccessAndroid::get_current_dir() {
- return "/"+current_dir;
+ return "/" + current_dir;
}
-
-bool DirAccessAndroid::file_exists(String p_file){
+bool DirAccessAndroid::file_exists(String p_file) {
String sd;
- if (current_dir=="")
- sd=p_file;
+ if (current_dir == "")
+ sd = p_file;
else
- sd=current_dir+"/"+p_file;
+ sd = current_dir + "/" + p_file;
- AAsset *a=AAssetManager_open(FileAccessAndroid::asset_manager,sd.utf8().get_data(),AASSET_MODE_STREAMING);
+ AAsset *a = AAssetManager_open(FileAccessAndroid::asset_manager, sd.utf8().get_data(), AASSET_MODE_STREAMING);
if (a) {
AAsset_close(a);
return true;
@@ -158,18 +150,17 @@ bool DirAccessAndroid::file_exists(String p_file){
return false;
}
-
-Error DirAccessAndroid::make_dir(String p_dir){
+Error DirAccessAndroid::make_dir(String p_dir) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
-Error DirAccessAndroid::rename(String p_from, String p_to){
+Error DirAccessAndroid::rename(String p_from, String p_to) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
-Error DirAccessAndroid::remove(String p_name){
+Error DirAccessAndroid::remove(String p_name) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
@@ -182,12 +173,12 @@ size_t DirAccessAndroid::get_space_left() {
void DirAccessAndroid::make_default() {
- instance_func=create_fs;
+ instance_func = create_fs;
}
DirAccessAndroid::DirAccessAndroid() {
- aad=NULL;
+ aad = NULL;
}
DirAccessAndroid::~DirAccessAndroid() {
diff --git a/platform/android/dir_access_android.h b/platform/android/dir_access_android.h
index 72611ceb59..640800584a 100644
--- a/platform/android/dir_access_android.h
+++ b/platform/android/dir_access_android.h
@@ -32,23 +32,20 @@
#ifdef ANDROID_NATIVE_ACTIVITY
#include "os/dir_access.h"
-#include <stdio.h>
#include <android/asset_manager.h>
#include <android/log.h>
#include <android_native_app_glue.h>
+#include <stdio.h>
+class DirAccessAndroid : public DirAccess {
-
-class DirAccessAndroid : public DirAccess {
-
- AAssetDir* aad;
+ AAssetDir *aad;
String current_dir;
String current;
static DirAccess *create_fs();
public:
-
virtual Error list_dir_begin(); ///< This starts dir listing
virtual String get_next();
virtual bool current_is_dir() const;
@@ -61,10 +58,8 @@ public:
virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success
virtual String get_current_dir(); ///< return current dir location
-
virtual bool file_exists(String p_file);
-
virtual Error make_dir(String p_dir);
virtual Error rename(String p_from, String p_to);
diff --git a/platform/android/dir_access_jandroid.cpp b/platform/android/dir_access_jandroid.cpp
index 2528b18248..68446302ff 100644
--- a/platform/android/dir_access_jandroid.cpp
+++ b/platform/android/dir_access_jandroid.cpp
@@ -30,17 +30,15 @@
#include "dir_access_jandroid.h"
#include "file_access_jandroid.h"
-#include "thread_jandroid.h"
#include "print_string.h"
+#include "thread_jandroid.h"
-
-jobject DirAccessJAndroid::io=NULL;
-jclass DirAccessJAndroid::cls=NULL;
-jmethodID DirAccessJAndroid::_dir_open=NULL;
-jmethodID DirAccessJAndroid::_dir_next=NULL;
-jmethodID DirAccessJAndroid::_dir_close=NULL;
-jmethodID DirAccessJAndroid::_dir_is_dir=NULL;
-
+jobject DirAccessJAndroid::io = NULL;
+jclass DirAccessJAndroid::cls = NULL;
+jmethodID DirAccessJAndroid::_dir_open = NULL;
+jmethodID DirAccessJAndroid::_dir_next = NULL;
+jmethodID DirAccessJAndroid::_dir_close = NULL;
+jmethodID DirAccessJAndroid::_dir_is_dir = NULL;
DirAccess *DirAccessJAndroid::create_fs() {
@@ -53,118 +51,113 @@ Error DirAccessJAndroid::list_dir_begin() {
JNIEnv *env = ThreadAndroid::get_env();
jstring js = env->NewStringUTF(current_dir.utf8().get_data());
- int res = env->CallIntMethod(io,_dir_open,js);
- if (res<=0)
+ int res = env->CallIntMethod(io, _dir_open, js);
+ if (res <= 0)
return ERR_CANT_OPEN;
- id=res;
+ id = res;
return OK;
}
-String DirAccessJAndroid::get_next(){
+String DirAccessJAndroid::get_next() {
- ERR_FAIL_COND_V(id==0,"");
+ ERR_FAIL_COND_V(id == 0, "");
JNIEnv *env = ThreadAndroid::get_env();
- jstring str= (jstring)env->CallObjectMethod(io,_dir_next,id);
+ jstring str = (jstring)env->CallObjectMethod(io, _dir_next, id);
if (!str)
return "";
- String ret = String::utf8(env->GetStringUTFChars( (jstring)str, NULL ));
+ String ret = String::utf8(env->GetStringUTFChars((jstring)str, NULL));
env->DeleteLocalRef((jobject)str);
return ret;
-
}
-bool DirAccessJAndroid::current_is_dir() const{
-
+bool DirAccessJAndroid::current_is_dir() const {
JNIEnv *env = ThreadAndroid::get_env();
- return env->CallBooleanMethod(io,_dir_is_dir,id);
-
+ return env->CallBooleanMethod(io, _dir_is_dir, id);
}
bool DirAccessJAndroid::current_is_hidden() const {
- return current!="." && current!=".." && current.begins_with(".");
+ return current != "." && current != ".." && current.begins_with(".");
}
-void DirAccessJAndroid::list_dir_end(){
+void DirAccessJAndroid::list_dir_end() {
- if (id==0)
+ if (id == 0)
return;
JNIEnv *env = ThreadAndroid::get_env();
- env->CallVoidMethod(io,_dir_close,id);
- id=0;
-
-
+ env->CallVoidMethod(io, _dir_close, id);
+ id = 0;
}
-int DirAccessJAndroid::get_drive_count(){
+int DirAccessJAndroid::get_drive_count() {
return 0;
}
-String DirAccessJAndroid::get_drive(int p_drive){
+String DirAccessJAndroid::get_drive(int p_drive) {
return "";
}
-Error DirAccessJAndroid::change_dir(String p_dir){
+Error DirAccessJAndroid::change_dir(String p_dir) {
JNIEnv *env = ThreadAndroid::get_env();
- p_dir=p_dir.simplify_path();
+ p_dir = p_dir.simplify_path();
- if (p_dir=="" || p_dir=="." || (p_dir==".." && current_dir==""))
+ if (p_dir == "" || p_dir == "." || (p_dir == ".." && current_dir == ""))
return OK;
String new_dir;
- if (p_dir!="res://" && p_dir.length()>1 && p_dir.ends_with("/"))
- p_dir=p_dir.substr(0,p_dir.length()-1);
+ if (p_dir != "res://" && p_dir.length() > 1 && p_dir.ends_with("/"))
+ p_dir = p_dir.substr(0, p_dir.length() - 1);
if (p_dir.begins_with("/"))
- new_dir=p_dir.substr(1,p_dir.length());
+ new_dir = p_dir.substr(1, p_dir.length());
else if (p_dir.begins_with("res://"))
- new_dir=p_dir.substr(6,p_dir.length());
- else if (current_dir=="")
- new_dir=p_dir;
+ new_dir = p_dir.substr(6, p_dir.length());
+ else if (current_dir == "")
+ new_dir = p_dir;
else
- new_dir=current_dir.plus_file(p_dir);
+ new_dir = current_dir.plus_file(p_dir);
//print_line("new dir is: "+new_dir);
-//test if newdir exists
- new_dir=new_dir.simplify_path();
+ //test if newdir exists
+ new_dir = new_dir.simplify_path();
jstring js = env->NewStringUTF(new_dir.utf8().get_data());
- int res = env->CallIntMethod(io,_dir_open,js);
+ int res = env->CallIntMethod(io, _dir_open, js);
env->DeleteLocalRef(js);
- if (res<=0)
+ if (res <= 0)
return ERR_INVALID_PARAMETER;
- env->CallVoidMethod(io,_dir_close,res);
+ env->CallVoidMethod(io, _dir_close, res);
- current_dir=new_dir;
+ current_dir = new_dir;
return OK;
}
-String DirAccessJAndroid::get_current_dir(){
+String DirAccessJAndroid::get_current_dir() {
- return "res://"+current_dir;
+ return "res://" + current_dir;
}
-bool DirAccessJAndroid::file_exists(String p_file){
+bool DirAccessJAndroid::file_exists(String p_file) {
JNIEnv *env = ThreadAndroid::get_env();
String sd;
- if (current_dir=="")
- sd=p_file;
+ if (current_dir == "")
+ sd = p_file;
else
- sd=current_dir.plus_file(p_file);
+ sd = current_dir.plus_file(p_file);
FileAccessJAndroid *f = memnew(FileAccessJAndroid);
bool exists = f->file_exists(sd);
@@ -179,45 +172,44 @@ bool DirAccessJAndroid::dir_exists(String p_dir) {
String sd;
-
- if (current_dir=="")
- sd=p_dir;
+ if (current_dir == "")
+ sd = p_dir;
else {
if (p_dir.is_rel_path())
- sd=current_dir.plus_file(p_dir);
+ sd = current_dir.plus_file(p_dir);
else
- sd=fix_path(p_dir);
+ sd = fix_path(p_dir);
}
- String path=sd.simplify_path();
+ String path = sd.simplify_path();
if (path.begins_with("/"))
- path=path.substr(1,path.length());
+ path = path.substr(1, path.length());
else if (path.begins_with("res://"))
- path=path.substr(6,path.length());
+ path = path.substr(6, path.length());
jstring js = env->NewStringUTF(path.utf8().get_data());
- int res = env->CallIntMethod(io,_dir_open,js);
+ int res = env->CallIntMethod(io, _dir_open, js);
env->DeleteLocalRef(js);
- if (res<=0)
+ if (res <= 0)
return false;
- env->CallVoidMethod(io,_dir_close,res);
+ env->CallVoidMethod(io, _dir_close, res);
return true;
}
-Error DirAccessJAndroid::make_dir(String p_dir){
+Error DirAccessJAndroid::make_dir(String p_dir) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
-Error DirAccessJAndroid::rename(String p_from, String p_to){
+Error DirAccessJAndroid::rename(String p_from, String p_to) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
-Error DirAccessJAndroid::remove(String p_name){
+Error DirAccessJAndroid::remove(String p_name) {
ERR_FAIL_V(ERR_UNAVAILABLE);
}
@@ -228,42 +220,39 @@ size_t DirAccessJAndroid::get_space_left() {
return 0;
}
-
-void DirAccessJAndroid::setup( jobject p_io) {
-
+void DirAccessJAndroid::setup(jobject p_io) {
JNIEnv *env = ThreadAndroid::get_env();
- io=p_io;
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP7");
+ io = p_io;
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP7");
jclass c = env->GetObjectClass(io);
cls = (jclass)env->NewGlobalRef(c);
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP8");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP8");
_dir_open = env->GetMethodID(cls, "dir_open", "(Ljava/lang/String;)I");
- if(_dir_open != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _dir_open ok!!");
+ if (_dir_open != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _dir_open ok!!");
}
_dir_next = env->GetMethodID(cls, "dir_next", "(I)Ljava/lang/String;");
- if(_dir_next != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _dir_next ok!!");
+ if (_dir_next != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _dir_next ok!!");
}
_dir_close = env->GetMethodID(cls, "dir_close", "(I)V");
- if(_dir_close != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _dir_close ok!!");
+ if (_dir_close != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _dir_close ok!!");
}
_dir_is_dir = env->GetMethodID(cls, "dir_is_dir", "(I)Z");
- if(_dir_is_dir != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _dir_is_dir ok!!");
+ if (_dir_is_dir != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _dir_is_dir ok!!");
}
//(*env)->CallVoidMethod(env,obj,aMethodID, myvar);
}
-
DirAccessJAndroid::DirAccessJAndroid() {
- id=0;
+ id = 0;
}
DirAccessJAndroid::~DirAccessJAndroid() {
diff --git a/platform/android/dir_access_jandroid.h b/platform/android/dir_access_jandroid.h
index 5db32b945c..096858ddf7 100644
--- a/platform/android/dir_access_jandroid.h
+++ b/platform/android/dir_access_jandroid.h
@@ -31,13 +31,11 @@
#ifndef ANDROID_NATIVE_ACTIVITY
-
#include "java_glue.h"
#include "os/dir_access.h"
#include <stdio.h>
-
-class DirAccessJAndroid : public DirAccess {
+class DirAccessJAndroid : public DirAccess {
//AAssetDir* aad;
@@ -57,7 +55,6 @@ class DirAccessJAndroid : public DirAccess {
static DirAccess *create_fs();
public:
-
virtual Error list_dir_begin(); ///< This starts dir listing
virtual String get_next();
virtual bool current_is_dir() const;
@@ -70,7 +67,6 @@ public:
virtual Error change_dir(String p_dir); ///< can be relative or absolute, return false on success
virtual String get_current_dir(); ///< return current dir location
-
virtual bool file_exists(String p_file);
virtual bool dir_exists(String p_dir);
@@ -82,8 +78,7 @@ public:
//virtual FileType get_file_type() const;
size_t get_space_left();
-
- static void setup( jobject io);
+ static void setup(jobject io);
DirAccessJAndroid();
~DirAccessJAndroid();
diff --git a/platform/android/export/export.cpp b/platform/android/export/export.cpp
index 3fc822860d..31fa4c18bd 100644
--- a/platform/android/export/export.cpp
+++ b/platform/android/export/export.cpp
@@ -26,17 +26,17 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "version.h"
#include "export.h"
-#include "editor/editor_settings.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
-#include "io/zip_io.h"
-#include "io/marshalls.h"
+#include "editor/editor_settings.h"
#include "global_config.h"
+#include "io/marshalls.h"
+#include "io/zip_io.h"
#include "os/file_access.h"
#include "os/os.h"
#include "platform/android/logo.h"
+#include "version.h"
#include <string.h>
#if 0
@@ -938,11 +938,6 @@ void EditorExportPlatformAndroid::_fix_manifest(Vector<uint8_t>& p_manifest,bool
p_manifest=ret;
-
-
-
-
-
#if 0
uint32_t header[9];
for(int i=0;i<9;i++) {
@@ -972,7 +967,6 @@ void EditorExportPlatformAndroid::_fix_manifest(Vector<uint8_t>& p_manifest,bool
string_table[i]=ucstring.ptr();
}
-
#endif
}
@@ -1917,4 +1911,3 @@ void register_android_exporter() {
EditorImportExport::get_singleton()->add_export_platform(exporter);
#endif
}
-
diff --git a/platform/android/file_access_android.cpp b/platform/android/file_access_android.cpp
index 2828d3c074..4426af4dad 100644
--- a/platform/android/file_access_android.cpp
+++ b/platform/android/file_access_android.cpp
@@ -29,40 +29,34 @@
#include "file_access_android.h"
#include "print_string.h"
-
-
-
-AAssetManager *FileAccessAndroid::asset_manager=NULL;
-
+AAssetManager *FileAccessAndroid::asset_manager = NULL;
/*void FileAccessAndroid::make_default() {
create_func=create_android;
}*/
-FileAccess* FileAccessAndroid::create_android() {
+FileAccess *FileAccessAndroid::create_android() {
return memnew(FileAccessAndroid);
}
+Error FileAccessAndroid::_open(const String &p_path, int p_mode_flags) {
-Error FileAccessAndroid::_open(const String& p_path, int p_mode_flags) {
-
- String path=fix_path(p_path).simplify_path();
+ String path = fix_path(p_path).simplify_path();
if (path.begins_with("/"))
- path=path.substr(1,path.length());
+ path = path.substr(1, path.length());
else if (path.begins_with("res://"))
- path=path.substr(6,path.length());
+ path = path.substr(6, path.length());
-
- ERR_FAIL_COND_V(p_mode_flags&FileAccess::WRITE,ERR_UNAVAILABLE); //can't write on android..
- a=AAssetManager_open(asset_manager,path.utf8().get_data(),AASSET_MODE_STREAMING);
+ ERR_FAIL_COND_V(p_mode_flags & FileAccess::WRITE, ERR_UNAVAILABLE); //can't write on android..
+ a = AAssetManager_open(asset_manager, path.utf8().get_data(), AASSET_MODE_STREAMING);
if (!a)
return ERR_CANT_OPEN;
//ERR_FAIL_COND_V(!a,ERR_FILE_NOT_FOUND);
- len=AAsset_getLength(a);
- pos=0;
- eof=false;
+ len = AAsset_getLength(a);
+ pos = 0;
+ eof = false;
return OK;
}
@@ -72,34 +66,32 @@ void FileAccessAndroid::close() {
if (!a)
return;
AAsset_close(a);
- a=NULL;
+ a = NULL;
}
bool FileAccessAndroid::is_open() const {
- return a!=NULL;
+ return a != NULL;
}
void FileAccessAndroid::seek(size_t p_position) {
ERR_FAIL_COND(!a);
- AAsset_seek(a,p_position,SEEK_SET);
- pos=p_position;
- if (pos>len) {
- pos=len;
- eof=true;
+ AAsset_seek(a, p_position, SEEK_SET);
+ pos = p_position;
+ if (pos > len) {
+ pos = len;
+ eof = true;
} else {
- eof=false;
+ eof = false;
}
-
}
void FileAccessAndroid::seek_end(int64_t p_position) {
ERR_FAIL_COND(!a);
- AAsset_seek(a,p_position,SEEK_END);
- pos=len+p_position;
-
+ AAsset_seek(a, p_position, SEEK_END);
+ pos = len + p_position;
}
size_t FileAccessAndroid::get_pos() const {
@@ -119,79 +111,67 @@ bool FileAccessAndroid::eof_reached() const {
uint8_t FileAccessAndroid::get_8() const {
-
- if (pos>=len) {
- eof=true;
+ if (pos >= len) {
+ eof = true;
return 0;
}
-
uint8_t byte;
- AAsset_read(a,&byte,1);
+ AAsset_read(a, &byte, 1);
pos++;
return byte;
-
}
int FileAccessAndroid::get_buffer(uint8_t *p_dst, int p_length) const {
+ off_t r = AAsset_read(a, p_dst, p_length);
- off_t r = AAsset_read(a,p_dst,p_length);
-
- if (pos+p_length >len ) {
- eof=true;
+ if (pos + p_length > len) {
+ eof = true;
}
- if (r>=0) {
+ if (r >= 0) {
- pos+=r;
- if (pos>len) {
- pos=len;
+ pos += r;
+ if (pos > len) {
+ pos = len;
}
-
}
return r;
-
}
Error FileAccessAndroid::get_error() const {
- return eof?ERR_FILE_EOF:OK; //not sure what else it may happen
+ return eof ? ERR_FILE_EOF : OK; //not sure what else it may happen
}
void FileAccessAndroid::store_8(uint8_t p_dest) {
ERR_FAIL();
-
}
-bool FileAccessAndroid::file_exists(const String& p_path) {
+bool FileAccessAndroid::file_exists(const String &p_path) {
- String path=fix_path(p_path).simplify_path();
+ String path = fix_path(p_path).simplify_path();
if (path.begins_with("/"))
- path=path.substr(1,path.length());
+ path = path.substr(1, path.length());
else if (path.begins_with("res://"))
- path=path.substr(6,path.length());
+ path = path.substr(6, path.length());
- AAsset *at=AAssetManager_open(asset_manager,path.utf8().get_data(),AASSET_MODE_STREAMING);
+ AAsset *at = AAssetManager_open(asset_manager, path.utf8().get_data(), AASSET_MODE_STREAMING);
if (!at)
return false;
AAsset_close(at);
return true;
-
}
-
FileAccessAndroid::FileAccessAndroid() {
- a=NULL;
- eof=false;
+ a = NULL;
+ eof = false;
}
-
-FileAccessAndroid::~FileAccessAndroid()
-{
+FileAccessAndroid::~FileAccessAndroid() {
close();
}
-
diff --git a/platform/android/file_access_android.h b/platform/android/file_access_android.h
index 3d54eb2027..de131f19bc 100644
--- a/platform/android/file_access_android.h
+++ b/platform/android/file_access_android.h
@@ -29,33 +29,29 @@
#ifndef FILE_ACCESS_ANDROID_H
#define FILE_ACCESS_ANDROID_H
-
-
#include "os/file_access.h"
-#include <stdio.h>
#include <android/asset_manager.h>
#include <android/log.h>
+#include <stdio.h>
//#include <android_native_app_glue.h>
-
class FileAccessAndroid : public FileAccess {
- static FileAccess* create_android();
+ static FileAccess *create_android();
mutable AAsset *a;
mutable size_t len;
mutable size_t pos;
mutable bool eof;
public:
-
static AAssetManager *asset_manager;
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -68,9 +64,9 @@ public:
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_path); ///< return true if a file exists
+ virtual bool file_exists(const String &p_path); ///< return true if a file exists
- virtual uint64_t _get_modified_time(const String& p_file) { return 0; }
+ virtual uint64_t _get_modified_time(const String &p_file) { return 0; }
//static void make_default();
@@ -79,4 +75,3 @@ public:
};
#endif // FILE_ACCESS_ANDROID_H
-
diff --git a/platform/android/file_access_jandroid.cpp b/platform/android/file_access_jandroid.cpp
index a4e9c191e9..b3624e9f26 100644
--- a/platform/android/file_access_jandroid.cpp
+++ b/platform/android/file_access_jandroid.cpp
@@ -30,51 +30,46 @@
#include "file_access_jandroid.h"
#include "os/os.h"
-#include <unistd.h>
#include "thread_jandroid.h"
+#include <unistd.h>
-jobject FileAccessJAndroid::io=NULL;
+jobject FileAccessJAndroid::io = NULL;
jclass FileAccessJAndroid::cls;
-jmethodID FileAccessJAndroid::_file_open=0;
-jmethodID FileAccessJAndroid::_file_get_size=0;
-jmethodID FileAccessJAndroid::_file_seek=0;
-jmethodID FileAccessJAndroid::_file_read=0;
-jmethodID FileAccessJAndroid::_file_tell=0;
-jmethodID FileAccessJAndroid::_file_eof=0;
-jmethodID FileAccessJAndroid::_file_close=0;
-
+jmethodID FileAccessJAndroid::_file_open = 0;
+jmethodID FileAccessJAndroid::_file_get_size = 0;
+jmethodID FileAccessJAndroid::_file_seek = 0;
+jmethodID FileAccessJAndroid::_file_read = 0;
+jmethodID FileAccessJAndroid::_file_tell = 0;
+jmethodID FileAccessJAndroid::_file_eof = 0;
+jmethodID FileAccessJAndroid::_file_close = 0;
-FileAccess* FileAccessJAndroid::create_jandroid() {
+FileAccess *FileAccessJAndroid::create_jandroid() {
return memnew(FileAccessJAndroid);
}
-Error FileAccessJAndroid::_open(const String& p_path, int p_mode_flags) {
+Error FileAccessJAndroid::_open(const String &p_path, int p_mode_flags) {
if (is_open())
close();
- String path=fix_path(p_path).simplify_path();
+ String path = fix_path(p_path).simplify_path();
if (path.begins_with("/"))
- path=path.substr(1,path.length());
+ path = path.substr(1, path.length());
else if (path.begins_with("res://"))
- path=path.substr(6,path.length());
+ path = path.substr(6, path.length());
JNIEnv *env = ThreadAndroid::get_env();
-
-
jstring js = env->NewStringUTF(path.utf8().get_data());
- int res = env->CallIntMethod(io,_file_open,js,p_mode_flags&WRITE?true:false);
+ int res = env->CallIntMethod(io, _file_open, js, p_mode_flags & WRITE ? true : false);
env->DeleteLocalRef(js);
- OS::get_singleton()->print("fopen: '%s' ret %i\n",path.utf8().get_data(),res);
+ OS::get_singleton()->print("fopen: '%s' ret %i\n", path.utf8().get_data(), res);
-
- if (res<=0)
+ if (res <= 0)
return ERR_FILE_CANT_OPEN;
- id=res;
-
+ id = res;
return OK;
}
@@ -86,14 +81,13 @@ void FileAccessJAndroid::close() {
JNIEnv *env = ThreadAndroid::get_env();
- env->CallVoidMethod(io,_file_close,id);
- id=0;
-
+ env->CallVoidMethod(io, _file_close, id);
+ id = 0;
}
bool FileAccessJAndroid::is_open() const {
- return id!=0;
+ return id != 0;
}
void FileAccessJAndroid::seek(size_t p_position) {
@@ -101,7 +95,7 @@ void FileAccessJAndroid::seek(size_t p_position) {
JNIEnv *env = ThreadAndroid::get_env();
ERR_FAIL_COND(!is_open());
- env->CallVoidMethod(io,_file_seek,id,p_position);
+ env->CallVoidMethod(io, _file_seek, id, p_position);
}
void FileAccessJAndroid::seek_end(int64_t p_position) {
@@ -109,56 +103,50 @@ void FileAccessJAndroid::seek_end(int64_t p_position) {
ERR_FAIL_COND(!is_open());
seek(get_len());
-
}
size_t FileAccessJAndroid::get_pos() const {
JNIEnv *env = ThreadAndroid::get_env();
- ERR_FAIL_COND_V(!is_open(),0);
- return env->CallIntMethod(io,_file_tell,id);
-
+ ERR_FAIL_COND_V(!is_open(), 0);
+ return env->CallIntMethod(io, _file_tell, id);
}
size_t FileAccessJAndroid::get_len() const {
JNIEnv *env = ThreadAndroid::get_env();
- ERR_FAIL_COND_V(!is_open(),0);
- return env->CallIntMethod(io,_file_get_size,id);
-
+ ERR_FAIL_COND_V(!is_open(), 0);
+ return env->CallIntMethod(io, _file_get_size, id);
}
bool FileAccessJAndroid::eof_reached() const {
JNIEnv *env = ThreadAndroid::get_env();
- ERR_FAIL_COND_V(!is_open(),0);
- return env->CallIntMethod(io,_file_eof,id);
-
+ ERR_FAIL_COND_V(!is_open(), 0);
+ return env->CallIntMethod(io, _file_eof, id);
}
uint8_t FileAccessJAndroid::get_8() const {
- ERR_FAIL_COND_V(!is_open(),0);
+ ERR_FAIL_COND_V(!is_open(), 0);
uint8_t byte;
- get_buffer(&byte,1);
+ get_buffer(&byte, 1);
return byte;
}
int FileAccessJAndroid::get_buffer(uint8_t *p_dst, int p_length) const {
- ERR_FAIL_COND_V(!is_open(),0);
- if (p_length==0)
+ ERR_FAIL_COND_V(!is_open(), 0);
+ if (p_length == 0)
return 0;
JNIEnv *env = ThreadAndroid::get_env();
- jbyteArray jca = (jbyteArray)env->CallObjectMethod(io,_file_read,id,p_length);
-
+ jbyteArray jca = (jbyteArray)env->CallObjectMethod(io, _file_read, id, p_length);
int len = env->GetArrayLength(jca);
- env->GetByteArrayRegion(jca,0,len,(jbyte*)p_dst);
+ env->GetByteArrayRegion(jca, 0, len, (jbyte *)p_dst);
env->DeleteLocalRef((jobject)jca);
return len;
-
}
Error FileAccessJAndroid::get_error() const {
@@ -169,80 +157,76 @@ Error FileAccessJAndroid::get_error() const {
}
void FileAccessJAndroid::store_8(uint8_t p_dest) {
-
}
-bool FileAccessJAndroid::file_exists(const String& p_path) {
+bool FileAccessJAndroid::file_exists(const String &p_path) {
JNIEnv *env = ThreadAndroid::get_env();
- String path=fix_path(p_path).simplify_path();
+ String path = fix_path(p_path).simplify_path();
if (path.begins_with("/"))
- path=path.substr(1,path.length());
+ path = path.substr(1, path.length());
else if (path.begins_with("res://"))
- path=path.substr(6,path.length());
+ path = path.substr(6, path.length());
jstring js = env->NewStringUTF(path.utf8().get_data());
- int res = env->CallIntMethod(io,_file_open,js,false);
- if (res<=0) {
+ int res = env->CallIntMethod(io, _file_open, js, false);
+ if (res <= 0) {
env->DeleteLocalRef(js);
return false;
}
- env->CallVoidMethod(io,_file_close,res);
+ env->CallVoidMethod(io, _file_close, res);
env->DeleteLocalRef(js);
return true;
-
}
+void FileAccessJAndroid::setup(jobject p_io) {
-void FileAccessJAndroid::setup( jobject p_io) {
-
- io=p_io;
+ io = p_io;
JNIEnv *env = ThreadAndroid::get_env();
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP5");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP5");
jclass c = env->GetObjectClass(io);
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP6");
- cls=(jclass)env->NewGlobalRef(c);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP6");
+ cls = (jclass)env->NewGlobalRef(c);
_file_open = env->GetMethodID(cls, "file_open", "(Ljava/lang/String;Z)I");
- if(_file_open != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_open ok!!");
+ if (_file_open != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_open ok!!");
}
_file_get_size = env->GetMethodID(cls, "file_get_size", "(I)I");
- if(_file_get_size != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_get_size ok!!");
+ if (_file_get_size != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_get_size ok!!");
}
_file_tell = env->GetMethodID(cls, "file_tell", "(I)I");
- if(_file_tell != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_tell ok!!");
+ if (_file_tell != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_tell ok!!");
}
_file_eof = env->GetMethodID(cls, "file_eof", "(I)Z");
- if(_file_eof != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_eof ok!!");
+ if (_file_eof != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_eof ok!!");
}
_file_seek = env->GetMethodID(cls, "file_seek", "(II)V");
- if(_file_seek != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_seek ok!!");
+ if (_file_seek != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_seek ok!!");
}
_file_read = env->GetMethodID(cls, "file_read", "(II)[B");
- if(_file_read != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_read ok!!");
+ if (_file_read != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_read ok!!");
}
_file_close = env->GetMethodID(cls, "file_close", "(I)V");
- if(_file_close != 0) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*******GOT METHOD _file_close ok!!");
+ if (_file_close != 0) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******GOT METHOD _file_close ok!!");
}
//(*env)->CallVoidMethod(env,obj,aMethodID, myvar);
}
-
FileAccessJAndroid::FileAccessJAndroid() {
- id=0;
+ id = 0;
}
FileAccessJAndroid::~FileAccessJAndroid() {
@@ -251,5 +235,4 @@ FileAccessJAndroid::~FileAccessJAndroid() {
close();
}
-
#endif
diff --git a/platform/android/file_access_jandroid.h b/platform/android/file_access_jandroid.h
index 38f441ea71..b78d5e603c 100644
--- a/platform/android/file_access_jandroid.h
+++ b/platform/android/file_access_jandroid.h
@@ -47,17 +47,15 @@ class FileAccessJAndroid : public FileAccess {
static jmethodID _file_close;
int id;
- static FileAccess* create_jandroid();
-
+ static FileAccess *create_jandroid();
public:
-
- virtual Error _open(const String& p_path, int p_mode_flags); ///< open a file
+ virtual Error _open(const String &p_path, int p_mode_flags); ///< open a file
virtual void close(); ///< close a file
virtual bool is_open() const; ///< true when file is open
virtual void seek(size_t p_position); ///< seek to a given position
- virtual void seek_end(int64_t p_position=0); ///< seek from the end of file
+ virtual void seek_end(int64_t p_position = 0); ///< seek from the end of file
virtual size_t get_pos() const; ///< get position in the file
virtual size_t get_len() const; ///< get size of the file
@@ -70,13 +68,11 @@ public:
virtual void store_8(uint8_t p_dest); ///< store a byte
- virtual bool file_exists(const String& p_path); ///< return true if a file exists
-
-
+ virtual bool file_exists(const String &p_path); ///< return true if a file exists
- static void setup( jobject io);
+ static void setup(jobject io);
- virtual uint64_t _get_modified_time(const String& p_file) { return 0; }
+ virtual uint64_t _get_modified_time(const String &p_file) { return 0; }
FileAccessJAndroid();
~FileAccessJAndroid();
diff --git a/platform/android/globals/global_defaults.cpp b/platform/android/globals/global_defaults.cpp
index 01daac9260..60d7d8cb6b 100644
--- a/platform/android/globals/global_defaults.cpp
+++ b/platform/android/globals/global_defaults.cpp
@@ -29,10 +29,9 @@
#include "global_defaults.h"
#include "global_config.h"
-
void register_android_global_defaults() {
-/* GLOBAL_DEF("rasterizer.Android/use_fragment_lighting",false);
+ /* GLOBAL_DEF("rasterizer.Android/use_fragment_lighting",false);
GLOBAL_DEF("rasterizer.Android/fp16_framebuffer",false);
GLOBAL_DEF("display.Android/driver","GLES2");
//GLOBAL_DEF("rasterizer.Android/trilinear_mipmap_filter",false);
diff --git a/platform/android/godot_android.cpp b/platform/android/godot_android.cpp
index 83d5a413c0..9d300940b0 100644
--- a/platform/android/godot_android.cpp
+++ b/platform/android/godot_android.cpp
@@ -28,139 +28,130 @@
/*************************************************************************/
#ifdef ANDROID_NATIVE_ACTIVITY
-#include <jni.h>
#include <errno.h>
+#include <jni.h>
#include <EGL/egl.h>
#include <GLES2/gl2.h>
+#include "file_access_android.h"
+#include "global_config.h"
+#include "main/main.h"
+#include "os_android.h"
+#include <android/log.h>
#include <android/sensor.h>
#include <android/window.h>
-#include <android/log.h>
#include <android_native_app_glue.h>
-#include "file_access_android.h"
+#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-#include <stdlib.h>
-#include "os_android.h"
-#include "global_config.h"
-#include "main/main.h"
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "godot", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "godot", __VA_ARGS__))
-
extern "C" {
- JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerSingleton(JNIEnv * env, jobject obj, jstring name,jobject p_object);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerMethod(JNIEnv * env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args);
- JNIEXPORT jstring JNICALL Java_org_godotengine_godot_Godot_getGlobal(JNIEnv * env, jobject obj, jstring path);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerSingleton(JNIEnv *env, jobject obj, jstring name, jobject p_object);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerMethod(JNIEnv *env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args);
+JNIEXPORT jstring JNICALL Java_org_godotengine_godot_Godot_getGlobal(JNIEnv *env, jobject obj, jstring path);
};
class JNISingleton : public Object {
- GDCLASS( JNISingleton, Object );
-
+ GDCLASS(JNISingleton, Object);
struct MethodData {
-
jmethodID method;
Variant::Type ret_type;
Vector<Variant::Type> argtypes;
};
jobject instance;
- Map<StringName,MethodData> method_map;
+ Map<StringName, MethodData> method_map;
JNIEnv *env;
public:
+ void update_env(JNIEnv *p_env) { env = p_env; }
- void update_env(JNIEnv *p_env) { env=p_env; }
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+ print_line("attempt to call " + String(p_method));
- print_line("attempt to call "+String(p_method));
+ r_error.error = Variant::CallError::CALL_OK;
- r_error.error=Variant::CallError::CALL_OK;
-
- Map<StringName,MethodData >::Element *E=method_map.find(p_method);
+ Map<StringName, MethodData>::Element *E = method_map.find(p_method);
if (!E) {
print_line("no exists");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
}
-
int ac = E->get().argtypes.size();
- if (ac<p_argcount) {
+ if (ac < p_argcount) {
print_line("fewargs");
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=ac;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = ac;
return Variant();
}
- if (ac>p_argcount) {
+ if (ac > p_argcount) {
print_line("manyargs");
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=ac;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = ac;
return Variant();
}
+ for (int i = 0; i < p_argcount; i++) {
+ if (!Variant::can_convert(p_args[i]->get_type(), E->get().argtypes[i])) {
- for(int i=0;i<p_argcount;i++) {
-
- if (!Variant::can_convert(p_args[i]->get_type(),E->get().argtypes[i])) {
-
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=i;
- r_error.expected=E->get().argtypes[i];
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = i;
+ r_error.expected = E->get().argtypes[i];
}
}
-
- jvalue *v=NULL;
+ jvalue *v = NULL;
if (p_argcount) {
- v=(jvalue*)alloca( sizeof(jvalue)*p_argcount );
+ v = (jvalue *)alloca(sizeof(jvalue) * p_argcount);
}
- for(int i=0;i<p_argcount;i++) {
-
+ for (int i = 0; i < p_argcount; i++) {
- switch(E->get().argtypes[i]) {
+ switch (E->get().argtypes[i]) {
case Variant::BOOL: {
- v[i].z=*p_args[i];
+ v[i].z = *p_args[i];
} break;
case Variant::INT: {
- v[i].i=*p_args[i];
+ v[i].i = *p_args[i];
} break;
case Variant::REAL: {
- v[i].f=*p_args[i];
+ v[i].f = *p_args[i];
} break;
case Variant::STRING: {
String s = *p_args[i];
jstring jStr = env->NewStringUTF(s.utf8().get_data());
- v[i].l=jStr;
+ v[i].l = jStr;
} break;
case Variant::STRING_ARRAY: {
PoolVector<String> sarray = *p_args[i];
- jobjectArray arr = env->NewObjectArray(sarray.size(),env->FindClass("java/lang/String"),env->NewStringUTF(""));
+ jobjectArray arr = env->NewObjectArray(sarray.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));
- for(int j=0;j<sarray.size();j++) {
+ for (int j = 0; j < sarray.size(); j++) {
- env->SetObjectArrayElement(arr,j,env->NewStringUTF( sarray[i].utf8().get_data() ));
+ env->SetObjectArrayElement(arr, j, env->NewStringUTF(sarray[i].utf8().get_data()));
}
- v[i].l=arr;
+ v[i].l = arr;
} break;
case Variant::INT_ARRAY: {
@@ -168,8 +159,8 @@ public:
PoolVector<int> array = *p_args[i];
jintArray arr = env->NewIntArray(array.size());
PoolVector<int>::Read r = array.read();
- env->SetIntArrayRegion(arr,0,array.size(),r.ptr());
- v[i].l=arr;
+ env->SetIntArrayRegion(arr, 0, array.size(), r.ptr());
+ v[i].l = arr;
} break;
case Variant::REAL_ARRAY: {
@@ -177,15 +168,14 @@ public:
PoolVector<float> array = *p_args[i];
jfloatArray arr = env->NewFloatArray(array.size());
PoolVector<float>::Read r = array.read();
- env->SetFloatArrayRegion(arr,0,array.size(),r.ptr());
- v[i].l=arr;
+ env->SetFloatArrayRegion(arr, 0, array.size(), r.ptr());
+ v[i].l = arr;
} break;
default: {
ERR_FAIL_V(Variant());
} break;
-
}
}
@@ -193,78 +183,76 @@ public:
Variant ret;
- switch(E->get().ret_type) {
+ switch (E->get().ret_type) {
case Variant::NIL: {
-
print_line("call void");
- env->CallVoidMethodA(instance,E->get().method,v);
+ env->CallVoidMethodA(instance, E->get().method, v);
} break;
case Variant::BOOL: {
- ret = env->CallBooleanMethodA(instance,E->get().method,v);
+ ret = env->CallBooleanMethodA(instance, E->get().method, v);
print_line("call bool");
} break;
case Variant::INT: {
- ret = env->CallIntMethodA(instance,E->get().method,v);
+ ret = env->CallIntMethodA(instance, E->get().method, v);
print_line("call int");
} break;
case Variant::REAL: {
- ret = env->CallFloatMethodA(instance,E->get().method,v);
+ ret = env->CallFloatMethodA(instance, E->get().method, v);
} break;
case Variant::STRING: {
- jobject o = env->CallObjectMethodA(instance,E->get().method,v);
- String singname = env->GetStringUTFChars((jstring)o, NULL );
+ jobject o = env->CallObjectMethodA(instance, E->get().method, v);
+ String singname = env->GetStringUTFChars((jstring)o, NULL);
} break;
case Variant::STRING_ARRAY: {
- jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance, E->get().method, v);
int stringCount = env->GetArrayLength(arr);
PoolVector<String> sarr;
- for (int i=0; i<stringCount; i++) {
- jstring string = (jstring) env->GetObjectArrayElement(arr, i);
+ for (int i = 0; i < stringCount; i++) {
+ jstring string = (jstring)env->GetObjectArrayElement(arr, i);
const char *rawString = env->GetStringUTFChars(string, 0);
sarr.push_back(String(rawString));
}
- ret=sarr;
+ ret = sarr;
} break;
case Variant::INT_ARRAY: {
- jintArray arr = (jintArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jintArray arr = (jintArray)env->CallObjectMethodA(instance, E->get().method, v);
int fCount = env->GetArrayLength(arr);
PoolVector<int> sarr;
sarr.resize(fCount);
PoolVector<int>::Write w = sarr.write();
- env->GetIntArrayRegion(arr,0,fCount,w.ptr());
+ env->GetIntArrayRegion(arr, 0, fCount, w.ptr());
w = PoolVector<int>::Write();
- ret=sarr;
+ ret = sarr;
} break;
case Variant::REAL_ARRAY: {
- jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance, E->get().method, v);
int fCount = env->GetArrayLength(arr);
PoolVector<float> sarr;
sarr.resize(fCount);
PoolVector<float>::Write w = sarr.write();
- env->GetFloatArrayRegion(arr,0,fCount,w.ptr());
+ env->GetFloatArrayRegion(arr, 0, fCount, w.ptr());
w = PoolVector<float>::Write();
- ret=sarr;
+ ret = sarr;
} break;
default: {
-
print_line("failure..");
ERR_FAIL_V(Variant());
} break;
@@ -275,270 +263,251 @@ public:
return ret;
}
-
jobject get_instance() const {
return instance;
}
void set_instance(jobject p_instance) {
- instance=p_instance;
+ instance = p_instance;
}
-
- void add_method(const StringName& p_name, jmethodID p_method,const Vector<Variant::Type>& p_args, Variant::Type p_ret_type) {
+ void add_method(const StringName &p_name, jmethodID p_method, const Vector<Variant::Type> &p_args, Variant::Type p_ret_type) {
MethodData md;
- md.method=p_method;
- md.argtypes=p_args;
- md.ret_type=p_ret_type;
- method_map[p_name]=md;
-
+ md.method = p_method;
+ md.argtypes = p_args;
+ md.ret_type = p_ret_type;
+ method_map[p_name] = md;
}
-
JNISingleton() {}
-
};
//JNIEnv *JNISingleton::env=NULL;
-static HashMap<String,JNISingleton*> jni_singletons;
-
+static HashMap<String, JNISingleton *> jni_singletons;
struct engine {
- struct android_app* app;
- OS_Android *os;
- JNIEnv *jni;
-
- ASensorManager* sensorManager;
- const ASensor* accelerometerSensor;
- const ASensor* magnetometerSensor;
- const ASensor* gyroscopeSensor;
- ASensorEventQueue* sensorEventQueue;
-
- bool display_active;
- bool requested_quit;
- int animating;
- EGLDisplay display;
- EGLSurface surface;
- EGLContext context;
- int32_t width;
- int32_t height;
-
+ struct android_app *app;
+ OS_Android *os;
+ JNIEnv *jni;
+
+ ASensorManager *sensorManager;
+ const ASensor *accelerometerSensor;
+ const ASensor *magnetometerSensor;
+ const ASensor *gyroscopeSensor;
+ ASensorEventQueue *sensorEventQueue;
+
+ bool display_active;
+ bool requested_quit;
+ int animating;
+ EGLDisplay display;
+ EGLSurface surface;
+ EGLContext context;
+ int32_t width;
+ int32_t height;
};
/**
* Initialize an EGL context for the current display.
*/
-static int engine_init_display(struct engine* engine,bool p_gl2) {
- // initialize OpenGL ES and EGL
+static int engine_init_display(struct engine *engine, bool p_gl2) {
+ // initialize OpenGL ES and EGL
- /*
+ /*
* Here specify the attributes of the desired configuration.
* Below, we select an EGLConfig with at least 8 bits per color
* component compatible with on-screen windows
*/
- const EGLint gl2_attribs[] = {
- // EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
- EGL_BLUE_SIZE, 4,
- EGL_GREEN_SIZE, 4,
- EGL_RED_SIZE, 4,
- EGL_ALPHA_SIZE, 0,
- EGL_DEPTH_SIZE, 16,
- EGL_STENCIL_SIZE, EGL_DONT_CARE,
- EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
- EGL_NONE
- };
-
- const EGLint gl1_attribs[] = {
- // EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
- EGL_BLUE_SIZE, 4,
- EGL_GREEN_SIZE, 4,
- EGL_RED_SIZE, 4,
- EGL_ALPHA_SIZE, 0,
- EGL_DEPTH_SIZE, 16,
- EGL_STENCIL_SIZE, EGL_DONT_CARE,
- EGL_NONE
- };
-
- const EGLint *attribs=p_gl2?gl2_attribs:gl1_attribs;
-
-
- EGLint w, h, dummy, format;
- EGLint numConfigs;
- EGLConfig config;
- EGLSurface surface;
- EGLContext context;
-
- EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
-
- eglInitialize(display, 0, 0);
-
-
- /* Here, the application chooses the configuration it desires. In this
+ const EGLint gl2_attribs[] = {
+ // EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+ EGL_BLUE_SIZE, 4,
+ EGL_GREEN_SIZE, 4,
+ EGL_RED_SIZE, 4,
+ EGL_ALPHA_SIZE, 0,
+ EGL_DEPTH_SIZE, 16,
+ EGL_STENCIL_SIZE, EGL_DONT_CARE,
+ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+ EGL_NONE
+ };
+
+ const EGLint gl1_attribs[] = {
+ // EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+ EGL_BLUE_SIZE, 4,
+ EGL_GREEN_SIZE, 4,
+ EGL_RED_SIZE, 4,
+ EGL_ALPHA_SIZE, 0,
+ EGL_DEPTH_SIZE, 16,
+ EGL_STENCIL_SIZE, EGL_DONT_CARE,
+ EGL_NONE
+ };
+
+ const EGLint *attribs = p_gl2 ? gl2_attribs : gl1_attribs;
+
+ EGLint w, h, dummy, format;
+ EGLint numConfigs;
+ EGLConfig config;
+ EGLSurface surface;
+ EGLContext context;
+
+ EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
+
+ eglInitialize(display, 0, 0);
+
+ /* Here, the application chooses the configuration it desires. In this
* sample, we have a very simplified selection process, where we pick
* the first EGLConfig that matches our criteria */
- eglChooseConfig(display, attribs, &config, 1, &numConfigs);
+ eglChooseConfig(display, attribs, &config, 1, &numConfigs);
- LOGI("Num configs: %i\n",numConfigs);
+ LOGI("Num configs: %i\n", numConfigs);
- /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
+ /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
* As soon as we picked a EGLConfig, we can safely reconfigure the
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
- eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
+ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
- ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
- //ANativeWindow_setFlags(engine->app->window, 0, 0, format|);
+ ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
+ //ANativeWindow_setFlags(engine->app->window, 0, 0, format|);
- surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
+ surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
- const EGLint context_attribs[] = {
- EGL_CONTEXT_CLIENT_VERSION,2,
- EGL_NONE
- };
- context = eglCreateContext(display, config, EGL_NO_CONTEXT, p_gl2?context_attribs:NULL);
-
- if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
- LOGW("Unable to eglMakeCurrent");
- return -1;
- }
+ const EGLint context_attribs[] = {
+ EGL_CONTEXT_CLIENT_VERSION, 2,
+ EGL_NONE
+ };
+ context = eglCreateContext(display, config, EGL_NO_CONTEXT, p_gl2 ? context_attribs : NULL);
- eglQuerySurface(display, surface, EGL_WIDTH, &w);
- eglQuerySurface(display, surface, EGL_HEIGHT, &h);
- print_line("INIT VIDEO MODE: "+itos(w)+","+itos(h));
+ if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
+ LOGW("Unable to eglMakeCurrent");
+ return -1;
+ }
- //engine->os->set_egl_extensions(eglQueryString(display,EGL_EXTENSIONS));
- engine->os->init_video_mode(w,h);
+ eglQuerySurface(display, surface, EGL_WIDTH, &w);
+ eglQuerySurface(display, surface, EGL_HEIGHT, &h);
+ print_line("INIT VIDEO MODE: " + itos(w) + "," + itos(h));
+ //engine->os->set_egl_extensions(eglQueryString(display,EGL_EXTENSIONS));
+ engine->os->init_video_mode(w, h);
- engine->display = display;
- engine->context = context;
- engine->surface = surface;
- engine->width = w;
- engine->height = h;
- engine->display_active=true;
+ engine->display = display;
+ engine->context = context;
+ engine->surface = surface;
+ engine->width = w;
+ engine->height = h;
+ engine->display_active = true;
- //engine->state.angle = 0;
+ //engine->state.angle = 0;
- // Initialize GL state.
- //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
- glEnable(GL_CULL_FACE);
- // glShadeModel(GL_SMOOTH);
- glDisable(GL_DEPTH_TEST);
- LOGI("GL Version: %s - %s %s\n", glGetString(GL_VERSION),glGetString(GL_VENDOR), glGetString(GL_RENDERER));
+ // Initialize GL state.
+ //glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
+ glEnable(GL_CULL_FACE);
+ // glShadeModel(GL_SMOOTH);
+ glDisable(GL_DEPTH_TEST);
+ LOGI("GL Version: %s - %s %s\n", glGetString(GL_VERSION), glGetString(GL_VENDOR), glGetString(GL_RENDERER));
- return 0;
+ return 0;
}
+static void engine_draw_frame(struct engine *engine) {
+ if (engine->display == NULL) {
+ // No display.
+ return;
+ }
-static void engine_draw_frame(struct engine* engine) {
- if (engine->display == NULL) {
- // No display.
- return;
- }
-
- // Just fill the screen with a color.
- //glClearColor(0,1,0,1);
- //glClear(GL_COLOR_BUFFER_BIT);
- if (engine->os && engine->os->main_loop_iterate()==true) {
+ // Just fill the screen with a color.
+ //glClearColor(0,1,0,1);
+ //glClear(GL_COLOR_BUFFER_BIT);
+ if (engine->os && engine->os->main_loop_iterate() == true) {
- engine->requested_quit=true;
- return; //should exit instead
- }
+ engine->requested_quit = true;
+ return; //should exit instead
+ }
- eglSwapBuffers(engine->display, engine->surface);
+ eglSwapBuffers(engine->display, engine->surface);
}
-
-static void engine_term_display(struct engine* engine) {
- if (engine->display != EGL_NO_DISPLAY) {
- eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
- if (engine->context != EGL_NO_CONTEXT) {
- eglDestroyContext(engine->display, engine->context);
- }
- if (engine->surface != EGL_NO_SURFACE) {
- eglDestroySurface(engine->display, engine->surface);
+static void engine_term_display(struct engine *engine) {
+ if (engine->display != EGL_NO_DISPLAY) {
+ eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
+ if (engine->context != EGL_NO_CONTEXT) {
+ eglDestroyContext(engine->display, engine->context);
+ }
+ if (engine->surface != EGL_NO_SURFACE) {
+ eglDestroySurface(engine->display, engine->surface);
+ }
+ eglTerminate(engine->display);
}
- eglTerminate(engine->display);
- }
-
- engine->animating = 0;
- engine->display = EGL_NO_DISPLAY;
- engine->context = EGL_NO_CONTEXT;
- engine->surface = EGL_NO_SURFACE;
- engine->display_active=false;
+ engine->animating = 0;
+ engine->display = EGL_NO_DISPLAY;
+ engine->context = EGL_NO_CONTEXT;
+ engine->surface = EGL_NO_SURFACE;
+ engine->display_active = false;
}
/**
* Process the next input event.
*/
-static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
- struct engine* engine = (struct engine*)app->userData;
+static int32_t engine_handle_input(struct android_app *app, AInputEvent *event) {
+ struct engine *engine = (struct engine *)app->userData;
if (!engine->os)
return 0;
- switch(AInputEvent_getType(event)) {
+ switch (AInputEvent_getType(event)) {
case AINPUT_EVENT_TYPE_KEY: {
int ac = AKeyEvent_getAction(event);
- switch(ac) {
+ switch (ac) {
case AKEY_EVENT_ACTION_DOWN: {
int32_t code = AKeyEvent_getKeyCode(event);
- if (code==AKEYCODE_BACK) {
+ if (code == AKEYCODE_BACK) {
//AInputQueue_finishEvent(AInputQueue* queue, AInputEvent* event, int handled);
if (engine->os)
engine->os->main_loop_request_quit();
return 1;
-
}
-
} break;
case AKEY_EVENT_ACTION_UP: {
-
} break;
}
-
} break;
case AINPUT_EVENT_TYPE_MOTION: {
-
Vector<OS_Android::TouchPos> touchvec;
int pc = AMotionEvent_getPointerCount(event);
touchvec.resize(pc);
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
- touchvec[i].pos.x=AMotionEvent_getX(event,i);
- touchvec[i].pos.y=AMotionEvent_getY(event,i);
- touchvec[i].id=AMotionEvent_getPointerId(event,i);
+ touchvec[i].pos.x = AMotionEvent_getX(event, i);
+ touchvec[i].pos.y = AMotionEvent_getY(event, i);
+ touchvec[i].id = AMotionEvent_getPointerId(event, i);
}
-
//System.out.printf("gaction: %d\n",event.getAction());
- int pidx=(AMotionEvent_getAction(event)&AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)>>8;
- switch(AMotionEvent_getAction(event)&AMOTION_EVENT_ACTION_MASK) {
+ int pidx = (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> 8;
+ switch (AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK) {
case AMOTION_EVENT_ACTION_DOWN: {
- engine->os->process_touch(0,0,touchvec);
+ engine->os->process_touch(0, 0, touchvec);
//System.out.printf("action down at: %f,%f\n", event.getX(),event.getY());
} break;
case AMOTION_EVENT_ACTION_MOVE: {
- engine->os->process_touch(1,0,touchvec);
+ engine->os->process_touch(1, 0, touchvec);
/*
for(int i=0;i<event.getPointerCount();i++) {
System.out.printf("%d - moved to: %f,%f\n",i, event.getX(i),event.getY(i));
@@ -547,16 +516,16 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
} break;
case AMOTION_EVENT_ACTION_POINTER_UP: {
- engine->os->process_touch(4,pidx,touchvec);
+ engine->os->process_touch(4, pidx, touchvec);
//System.out.printf("%d - s.up at: %f,%f\n",pointer_idx, event.getX(pointer_idx),event.getY(pointer_idx));
} break;
case AMOTION_EVENT_ACTION_POINTER_DOWN: {
- engine->os->process_touch(3,pidx,touchvec);
+ engine->os->process_touch(3, pidx, touchvec);
//System.out.printf("%d - s.down at: %f,%f\n",pointer_idx, event.getX(pointer_idx),event.getY(pointer_idx));
} break;
case AMOTION_EVENT_ACTION_CANCEL:
case AMOTION_EVENT_ACTION_UP: {
- engine->os->process_touch(2,0,touchvec);
+ engine->os->process_touch(2, 0, touchvec);
/*
for(int i=0;i<event.getPointerCount();i++) {
System.out.printf("%d - up! %f,%f\n",i, event.getX(i),event.getY(i));
@@ -567,34 +536,33 @@ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event)
return 1;
} break;
-
}
- return 0;
+ return 0;
}
/**
* Process the next main command.
*/
-static void _gfx_init(void *ud,bool p_gl2) {
+static void _gfx_init(void *ud, bool p_gl2) {
- struct engine* engine = (struct engine*)ud;
- engine_init_display(engine,p_gl2);
+ struct engine *engine = (struct engine *)ud;
+ engine_init_display(engine, p_gl2);
}
-static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
- struct engine* engine = (struct engine*)app->userData;
- // LOGI("**** CMD %i\n",cmd);
- switch (cmd) {
- case APP_CMD_SAVE_STATE:
- // The system has asked us to save our current state. Do so.
- //engine->app->savedState = malloc(sizeof(struct saved_state));
- //*((struct saved_state*)engine->app->savedState) = engine->state;
- //engine->app->savedStateSize = sizeof(struct saved_state);
- break;
- case APP_CMD_CONFIG_CHANGED:
- case APP_CMD_WINDOW_RESIZED: {
+static void engine_handle_cmd(struct android_app *app, int32_t cmd) {
+ struct engine *engine = (struct engine *)app->userData;
+ // LOGI("**** CMD %i\n",cmd);
+ switch (cmd) {
+ case APP_CMD_SAVE_STATE:
+ // The system has asked us to save our current state. Do so.
+ //engine->app->savedState = malloc(sizeof(struct saved_state));
+ //*((struct saved_state*)engine->app->savedState) = engine->state;
+ //engine->app->savedStateSize = sizeof(struct saved_state);
+ break;
+ case APP_CMD_CONFIG_CHANGED:
+ case APP_CMD_WINDOW_RESIZED: {
#if 0
// android blows
@@ -610,26 +578,22 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
}
#else
- if (engine->display_active) {
+ if (engine->display_active) {
-
- EGLint w,h;
- eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
- eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
- // if (w==engine->os->get_video_mode().width && h==engine->os->get_video_mode().height)
+ EGLint w, h;
+ eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
+ eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
+ // if (w==engine->os->get_video_mode().width && h==engine->os->get_video_mode().height)
// break;
- engine_term_display(engine);
-
-
- }
-
+ engine_term_display(engine);
+ }
- engine->os->reload_gfx();
- engine_draw_frame(engine);
- engine->animating=1;
+ engine->os->reload_gfx();
+ engine_draw_frame(engine);
+ engine->animating = 1;
- /*
+/*
EGLint w,h;
eglQuerySurface(engine->display, engine->surface, EGL_WIDTH, &w);
eglQuerySurface(engine->display, engine->surface, EGL_HEIGHT, &h);
@@ -640,309 +604,285 @@ static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
#endif
- } break;
- case APP_CMD_INIT_WINDOW:
- //The window is being shown, get it ready.
- //LOGI("INIT WINDOW");
- if (engine->app->window != NULL) {
+ } break;
+ case APP_CMD_INIT_WINDOW:
+ //The window is being shown, get it ready.
+ //LOGI("INIT WINDOW");
+ if (engine->app->window != NULL) {
- if (engine->os==NULL) {
+ if (engine->os == NULL) {
- //do initialization here, when there's OpenGL! hackish but the only way
- engine->os = new OS_Android(_gfx_init,engine);
+ //do initialization here, when there's OpenGL! hackish but the only way
+ engine->os = new OS_Android(_gfx_init, engine);
- //char *args[]={"-test","gui",NULL};
- __android_log_print(ANDROID_LOG_INFO,"godot","pre asdasd setup...");
+ //char *args[]={"-test","gui",NULL};
+ __android_log_print(ANDROID_LOG_INFO, "godot", "pre asdasd setup...");
#if 0
Error err = Main::setup("apk",2,args);
#else
- Error err = Main::setup("apk",0,NULL);
-
- String modules = GlobalConfig::get_singleton()->get("android/modules");
- Vector<String> mods = modules.split(",",false);
- mods.push_back("GodotOS");
- __android_log_print(ANDROID_LOG_INFO,"godot","mod count: %i",mods.size());
-
- if (mods.size()) {
+ Error err = Main::setup("apk", 0, NULL);
- jclass activityClass = engine->jni->FindClass("android/app/NativeActivity");
+ String modules = GlobalConfig::get_singleton()->get("android/modules");
+ Vector<String> mods = modules.split(",", false);
+ mods.push_back("GodotOS");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "mod count: %i", mods.size());
- jmethodID getClassLoader = engine->jni->GetMethodID(activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
+ if (mods.size()) {
- jobject cls = engine->jni->CallObjectMethod(app->activity->clazz, getClassLoader);
+ jclass activityClass = engine->jni->FindClass("android/app/NativeActivity");
- jclass classLoader = engine->jni->FindClass("java/lang/ClassLoader");
+ jmethodID getClassLoader = engine->jni->GetMethodID(activityClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
- jmethodID findClass = engine->jni->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
+ jobject cls = engine->jni->CallObjectMethod(app->activity->clazz, getClassLoader);
+ jclass classLoader = engine->jni->FindClass("java/lang/ClassLoader");
- static JNINativeMethod methods[] = {
- {"registerSingleton", "(Ljava/lang/String;Ljava/lang/Object;)V",(void *)&Java_org_godotengine_godot_Godot_registerSingleton},
- {"registerMethod", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V",(void *)&Java_org_godotengine_godot_Godot_registerMethod},
- {"getGlobal", "(Ljava/lang/String;)Ljava/lang/String;", (void *)&Java_org_godotengine_godot_Godot_getGlobal},
- };
+ jmethodID findClass = engine->jni->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
- jstring gstrClassName = engine->jni->NewStringUTF("org/godotengine/godot/Godot");
- jclass GodotClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, gstrClassName);
+ static JNINativeMethod methods[] = {
+ { "registerSingleton", "(Ljava/lang/String;Ljava/lang/Object;)V", (void *)&Java_org_godotengine_godot_Godot_registerSingleton },
+ { "registerMethod", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)V", (void *)&Java_org_godotengine_godot_Godot_registerMethod },
+ { "getGlobal", "(Ljava/lang/String;)Ljava/lang/String;", (void *)&Java_org_godotengine_godot_Godot_getGlobal },
+ };
- __android_log_print(ANDROID_LOG_INFO,"godot","godot ****^*^*?^*^*class data %x",GodotClass);
+ jstring gstrClassName = engine->jni->NewStringUTF("org/godotengine/godot/Godot");
+ jclass GodotClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, gstrClassName);
- engine->jni->RegisterNatives(GodotClass,methods,sizeof(methods)/sizeof(methods[0]));
+ __android_log_print(ANDROID_LOG_INFO, "godot", "godot ****^*^*?^*^*class data %x", GodotClass);
- for (int i=0;i<mods.size();i++) {
+ engine->jni->RegisterNatives(GodotClass, methods, sizeof(methods) / sizeof(methods[0]));
- String m = mods[i];
- //jclass singletonClass = engine->jni->FindClass(m.utf8().get_data());
+ for (int i = 0; i < mods.size(); i++) {
- jstring strClassName = engine->jni->NewStringUTF(m.utf8().get_data());
- jclass singletonClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, strClassName);
+ String m = mods[i];
+ //jclass singletonClass = engine->jni->FindClass(m.utf8().get_data());
- __android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class data %x",singletonClass);
- jmethodID initialize = engine->jni->GetStaticMethodID(singletonClass, "initialize", "(Landroid/app/Activity;)Lorg/godotengine/godot/Godot$SingletonBase;");
-
-
- jobject obj = engine->jni->CallStaticObjectMethod(singletonClass,initialize,app->activity->clazz);
- __android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class instance %x",obj);
- jobject gob = engine->jni->NewGlobalRef(obj);
+ jstring strClassName = engine->jni->NewStringUTF(m.utf8().get_data());
+ jclass singletonClass = (jclass)engine->jni->CallObjectMethod(cls, findClass, strClassName);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "****^*^*?^*^*class data %x", singletonClass);
+ jmethodID initialize = engine->jni->GetStaticMethodID(singletonClass, "initialize", "(Landroid/app/Activity;)Lorg/godotengine/godot/Godot$SingletonBase;");
+ jobject obj = engine->jni->CallStaticObjectMethod(singletonClass, initialize, app->activity->clazz);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "****^*^*?^*^*class instance %x", obj);
+ jobject gob = engine->jni->NewGlobalRef(obj);
+ }
}
- }
-
#endif
+ if (!Main::start())
+ return; //should exit instead and print the error
- if (!Main::start())
- return; //should exit instead and print the error
+ engine->os->main_loop_begin();
+ } else {
+ //i guess recreate resources?
+ engine->os->reload_gfx();
+ }
- engine->os->main_loop_begin();
- } else {
- //i guess recreate resources?
- engine->os->reload_gfx();
+ engine->animating = 1;
+ engine_draw_frame(engine);
}
-
-
- engine->animating=1;
+ break;
+ case APP_CMD_TERM_WINDOW:
+ // The window is being hidden or closed, clean it up.
+ //LOGI("TERM WINDOW");
+ engine_term_display(engine);
+ break;
+ case APP_CMD_GAINED_FOCUS:
+ // When our app gains focus, we start monitoring the accelerometer.
+ if (engine->accelerometerSensor != NULL) {
+ ASensorEventQueue_enableSensor(engine->sensorEventQueue,
+ engine->accelerometerSensor);
+ // We'd like to get 60 events per second (in us).
+ ASensorEventQueue_setEventRate(engine->sensorEventQueue,
+ engine->accelerometerSensor, (1000L / 60) * 1000);
+ }
+ // Also start monitoring the magnetometer.
+ if (engine->magnetometerSensor != NULL) {
+ ASensorEventQueue_enableSensor(engine->sensorEventQueue,
+ engine->magnetometerSensor);
+ // We'd like to get 60 events per second (in us).
+ ASensorEventQueue_setEventRate(engine->sensorEventQueue,
+ engine->magnetometerSensor, (1000L / 60) * 1000);
+ }
+ // And the gyroscope.
+ if (engine->gyroscopeSensor != NULL) {
+ ASensorEventQueue_enableSensor(engine->sensorEventQueue,
+ engine->gyroscopeSensor);
+ // We'd like to get 60 events per second (in us).
+ ASensorEventQueue_setEventRate(engine->sensorEventQueue,
+ engine->gyroscopeSensor, (1000L / 60) * 1000);
+ }
+ engine->animating = 1;
+ break;
+ case APP_CMD_LOST_FOCUS:
+ // When our app loses focus, we stop monitoring the sensors.
+ // This is to avoid consuming battery while not being used.
+ if (engine->accelerometerSensor != NULL) {
+ ASensorEventQueue_disableSensor(engine->sensorEventQueue,
+ engine->accelerometerSensor);
+ }
+ if (engine->magnetometerSensor != NULL) {
+ ASensorEventQueue_disableSensor(engine->sensorEventQueue,
+ engine->magnetometerSensor);
+ }
+ if (engine->gyroscopeSensor != NULL) {
+ ASensorEventQueue_disableSensor(engine->sensorEventQueue,
+ engine->gyroscopeSensor);
+ }
+ // Also stop animating.
+ engine->animating = 0;
engine_draw_frame(engine);
- }
- break;
- case APP_CMD_TERM_WINDOW:
- // The window is being hidden or closed, clean it up.
- //LOGI("TERM WINDOW");
- engine_term_display(engine);
- break;
- case APP_CMD_GAINED_FOCUS:
- // When our app gains focus, we start monitoring the accelerometer.
- if (engine->accelerometerSensor != NULL) {
- ASensorEventQueue_enableSensor(engine->sensorEventQueue,
- engine->accelerometerSensor);
- // We'd like to get 60 events per second (in us).
- ASensorEventQueue_setEventRate(engine->sensorEventQueue,
- engine->accelerometerSensor, (1000L/60)*1000);
-
- }
- // Also start monitoring the magnetometer.
- if (engine->magnetometerSensor != NULL) {
- ASensorEventQueue_enableSensor(engine->sensorEventQueue,
- engine->magnetometerSensor);
- // We'd like to get 60 events per second (in us).
- ASensorEventQueue_setEventRate(engine->sensorEventQueue,
- engine->magnetometerSensor, (1000L/60)*1000);
-
- }
- // And the gyroscope.
- if (engine->gyroscopeSensor != NULL) {
- ASensorEventQueue_enableSensor(engine->sensorEventQueue,
- engine->gyroscopeSensor);
- // We'd like to get 60 events per second (in us).
- ASensorEventQueue_setEventRate(engine->sensorEventQueue,
- engine->gyroscopeSensor, (1000L/60)*1000);
-
- }
- engine->animating = 1;
- break;
- case APP_CMD_LOST_FOCUS:
- // When our app loses focus, we stop monitoring the sensors.
- // This is to avoid consuming battery while not being used.
- if (engine->accelerometerSensor != NULL) {
- ASensorEventQueue_disableSensor(engine->sensorEventQueue,
- engine->accelerometerSensor);
- }
- if (engine->magnetometerSensor != NULL) {
- ASensorEventQueue_disableSensor(engine->sensorEventQueue,
- engine->magnetometerSensor);
- }
- if (engine->gyroscopeSensor != NULL) {
- ASensorEventQueue_disableSensor(engine->sensorEventQueue,
- engine->gyroscopeSensor);
- }
- // Also stop animating.
- engine->animating = 0;
- engine_draw_frame(engine);
- break;
- }
+ break;
+ }
}
-void android_main(struct android_app* state) {
- struct engine engine;
- // Make sure glue isn't stripped.
- app_dummy();
-
- memset(&engine, 0, sizeof(engine));
- state->userData = &engine;
- state->onAppCmd = engine_handle_cmd;
- state->onInputEvent = engine_handle_input;
- engine.app = state;
- engine.requested_quit=false;
- engine.os=NULL;
- engine.display_active=false;
-
- FileAccessAndroid::asset_manager=state->activity->assetManager;
-
- // Prepare to monitor sensors
- engine.sensorManager = ASensorManager_getInstance();
- engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
- ASENSOR_TYPE_ACCELEROMETER);
- engine.magnetometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
- ASENSOR_TYPE_MAGNETIC_FIELD);
- engine.gyroscopeSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
- ASENSOR_TYPE_GYROSCOPE);
- engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
- state->looper, LOOPER_ID_USER, NULL, NULL);
-
-
- ANativeActivity_setWindowFlags(state->activity,AWINDOW_FLAG_FULLSCREEN|AWINDOW_FLAG_KEEP_SCREEN_ON,0);
+void android_main(struct android_app *state) {
+ struct engine engine;
+ // Make sure glue isn't stripped.
+ app_dummy();
+
+ memset(&engine, 0, sizeof(engine));
+ state->userData = &engine;
+ state->onAppCmd = engine_handle_cmd;
+ state->onInputEvent = engine_handle_input;
+ engine.app = state;
+ engine.requested_quit = false;
+ engine.os = NULL;
+ engine.display_active = false;
+
+ FileAccessAndroid::asset_manager = state->activity->assetManager;
+
+ // Prepare to monitor sensors
+ engine.sensorManager = ASensorManager_getInstance();
+ engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
+ ASENSOR_TYPE_ACCELEROMETER);
+ engine.magnetometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
+ ASENSOR_TYPE_MAGNETIC_FIELD);
+ engine.gyroscopeSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
+ ASENSOR_TYPE_GYROSCOPE);
+ engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
+ state->looper, LOOPER_ID_USER, NULL, NULL);
+
+ ANativeActivity_setWindowFlags(state->activity, AWINDOW_FLAG_FULLSCREEN | AWINDOW_FLAG_KEEP_SCREEN_ON, 0);
state->activity->vm->AttachCurrentThread(&engine.jni, NULL);
+ // loop waiting for stuff to do.
+ while (1) {
+ // Read all pending events.
+ int ident;
+ int events;
+ struct android_poll_source *source;
- // loop waiting for stuff to do.
-
- while (1) {
- // Read all pending events.
- int ident;
- int events;
- struct android_poll_source* source;
-
- // If not animating, we will block forever waiting for events.
- // If animating, we loop until all events are read, then continue
- // to draw the next frame of animation.
-
- int nullmax=50;
- while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
- (void**)&source)) >= 0) {
+ // If not animating, we will block forever waiting for events.
+ // If animating, we loop until all events are read, then continue
+ // to draw the next frame of animation.
- // Process this event.
+ int nullmax = 50;
+ while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
+ (void **)&source)) >= 0) {
- if (source != NULL) {
- // LOGI("process\n");
- source->process(state, source);
- } else {
- nullmax--;
- if (nullmax<0)
- break;
- }
-
- // If a sensor has data, process it now.
- // LOGI("events\n");
- if (ident == LOOPER_ID_USER) {
- if (engine.accelerometerSensor != NULL || engine.magnetometerSensor != NULL || engine.gyroscopeSensor != NULL) {
- ASensorEvent event;
- while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
- &event, 1) > 0) {
-
-
- if (engine.os) {
- if (event.acceleration != NULL) {
- engine.os->process_accelerometer(Vector3(event.acceleration.x, event.acceleration.y,
- event.acceleration.z));
- }
- if (event.magnetic != NULL) {
- engine.os->process_magnetometer(Vector3(event.magnetic.x, event.magnetic.y,
- event.magnetic.z));
- }
- if (event.vector != NULL) {
- engine.os->process_gyroscope(Vector3(event.vector.x, event.vector.y,
- event.vector.z));
- }
- }
-
- }
- }
- }
-
- // Check if we are exiting.
- if (state->destroyRequested != 0) {
- if (engine.os) {
- engine.os->main_loop_request_quit();
- }
- state->destroyRequested=0;
- }
-
- if (engine.requested_quit) {
- engine_term_display(&engine);
- exit(0);
- return;
- }
+ // Process this event.
- // LOGI("end\n");
+ if (source != NULL) {
+ // LOGI("process\n");
+ source->process(state, source);
+ } else {
+ nullmax--;
+ if (nullmax < 0)
+ break;
+ }
+ // If a sensor has data, process it now.
+ // LOGI("events\n");
+ if (ident == LOOPER_ID_USER) {
+ if (engine.accelerometerSensor != NULL || engine.magnetometerSensor != NULL || engine.gyroscopeSensor != NULL) {
+ ASensorEvent event;
+ while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
+ &event, 1) > 0) {
+
+ if (engine.os) {
+ if (event.acceleration != NULL) {
+ engine.os->process_accelerometer(Vector3(event.acceleration.x, event.acceleration.y,
+ event.acceleration.z));
+ }
+ if (event.magnetic != NULL) {
+ engine.os->process_magnetometer(Vector3(event.magnetic.x, event.magnetic.y,
+ event.magnetic.z));
+ }
+ if (event.vector != NULL) {
+ engine.os->process_gyroscope(Vector3(event.vector.x, event.vector.y,
+ event.vector.z));
+ }
+ }
+ }
+ }
+ }
- }
+ // Check if we are exiting.
+ if (state->destroyRequested != 0) {
+ if (engine.os) {
+ engine.os->main_loop_request_quit();
+ }
+ state->destroyRequested = 0;
+ }
- // LOGI("engine animating? %i\n",engine.animating);
+ if (engine.requested_quit) {
+ engine_term_display(&engine);
+ exit(0);
+ return;
+ }
- if (engine.animating) {
- //do os render
+ // LOGI("end\n");
+ }
- engine_draw_frame(&engine);
- //LOGI("TERM WINDOW");
+ // LOGI("engine animating? %i\n",engine.animating);
- }
- }
+ if (engine.animating) {
+ //do os render
+ engine_draw_frame(&engine);
+ //LOGI("TERM WINDOW");
+ }
+ }
}
+JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerSingleton(JNIEnv *env, jobject obj, jstring name, jobject p_object) {
-
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerSingleton(JNIEnv * env, jobject obj, jstring name,jobject p_object){
-
- String singname = env->GetStringUTFChars( name, NULL );
- JNISingleton *s = memnew( JNISingleton );
+ String singname = env->GetStringUTFChars(name, NULL);
+ JNISingleton *s = memnew(JNISingleton);
s->update_env(env);
s->set_instance(env->NewGlobalRef(p_object));
- jni_singletons[singname]=s;
-
- GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton(singname,s));
+ jni_singletons[singname] = s;
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton(singname, s));
}
-
-static Variant::Type get_jni_type(const String& p_type) {
+static Variant::Type get_jni_type(const String &p_type) {
static struct {
const char *name;
Variant::Type type;
- } _type_to_vtype[]={
- {"void",Variant::NIL},
- {"boolean",Variant::BOOL},
- {"int",Variant::INT},
- {"float",Variant::REAL},
- {"java.lang.String",Variant::STRING},
- {"[I",Variant::INT_ARRAY},
- {"[F",Variant::REAL_ARRAY},
- {"[Ljava.lang.String;",Variant::STRING_ARRAY},
- {NULL,Variant::NIL}
+ } _type_to_vtype[] = {
+ { "void", Variant::NIL },
+ { "boolean", Variant::BOOL },
+ { "int", Variant::INT },
+ { "float", Variant::REAL },
+ { "java.lang.String", Variant::STRING },
+ { "[I", Variant::INT_ARRAY },
+ { "[F", Variant::REAL_ARRAY },
+ { "[Ljava.lang.String;", Variant::STRING_ARRAY },
+ { NULL, Variant::NIL }
};
- int idx=0;
+ int idx = 0;
while (_type_to_vtype[idx].name) {
- if (p_type==_type_to_vtype[idx].name)
+ if (p_type == _type_to_vtype[idx].name)
return _type_to_vtype[idx].type;
idx++;
@@ -951,88 +891,78 @@ static Variant::Type get_jni_type(const String& p_type) {
return Variant::NIL;
}
-
-static const char* get_jni_sig(const String& p_type) {
+static const char *get_jni_sig(const String &p_type) {
static struct {
const char *name;
const char *sig;
- } _type_to_vtype[]={
- {"void","V"},
- {"boolean","Z"},
- {"int","I"},
- {"float","F"},
- {"java.lang.String","Ljava/lang/String;"},
- {"[I","[I"},
- {"[F","[F"},
- {"[Ljava.lang.String;","[Ljava/lang/String;"},
- {NULL,"V"}
+ } _type_to_vtype[] = {
+ { "void", "V" },
+ { "boolean", "Z" },
+ { "int", "I" },
+ { "float", "F" },
+ { "java.lang.String", "Ljava/lang/String;" },
+ { "[I", "[I" },
+ { "[F", "[F" },
+ { "[Ljava.lang.String;", "[Ljava/lang/String;" },
+ { NULL, "V" }
};
- int idx=0;
+ int idx = 0;
while (_type_to_vtype[idx].name) {
- if (p_type==_type_to_vtype[idx].name)
+ if (p_type == _type_to_vtype[idx].name)
return _type_to_vtype[idx].sig;
idx++;
}
-
return "";
}
-JNIEXPORT jstring JNICALL Java_org_godotengine_godot_Godot_getGlobal(JNIEnv * env, jobject obj, jstring path) {
+JNIEXPORT jstring JNICALL Java_org_godotengine_godot_Godot_getGlobal(JNIEnv *env, jobject obj, jstring path) {
- String js = env->GetStringUTFChars( path, NULL );
+ String js = env->GetStringUTFChars(path, NULL);
return env->NewStringUTF(GlobalConfig::get_singleton()->get(js).operator String().utf8().get_data());
-
-
}
+JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerMethod(JNIEnv *env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args) {
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_Godot_registerMethod(JNIEnv * env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args){
-
- String singname = env->GetStringUTFChars( sname, NULL );
+ String singname = env->GetStringUTFChars(sname, NULL);
ERR_FAIL_COND(!jni_singletons.has(singname));
JNISingleton *s = jni_singletons.get(singname);
-
- String mname = env->GetStringUTFChars( name, NULL );
- String retval = env->GetStringUTFChars( ret, NULL );
+ String mname = env->GetStringUTFChars(name, NULL);
+ String retval = env->GetStringUTFChars(ret, NULL);
Vector<Variant::Type> types;
- String cs="(";
-
+ String cs = "(";
int stringCount = env->GetArrayLength(args);
- print_line("Singl: "+singname+" Method: "+mname+" RetVal: "+retval);
- for (int i=0; i<stringCount; i++) {
+ print_line("Singl: " + singname + " Method: " + mname + " RetVal: " + retval);
+ for (int i = 0; i < stringCount; i++) {
- jstring string = (jstring) env->GetObjectArrayElement(args, i);
+ jstring string = (jstring)env->GetObjectArrayElement(args, i);
const char *rawString = env->GetStringUTFChars(string, 0);
types.push_back(get_jni_type(String(rawString)));
- cs+=get_jni_sig(String(rawString));
+ cs += get_jni_sig(String(rawString));
}
- cs+=")";
- cs+=get_jni_sig(retval);
+ cs += ")";
+ cs += get_jni_sig(retval);
jclass cls = env->GetObjectClass(s->get_instance());
- print_line("METHOD: "+mname+" sig: "+cs);
+ print_line("METHOD: " + mname + " sig: " + cs);
jmethodID mid = env->GetMethodID(cls, mname.ascii().get_data(), cs.ascii().get_data());
if (!mid) {
- print_line("FAILED GETTING METHOID "+mname);
+ print_line("FAILED GETTING METHOID " + mname);
}
- s->add_method(mname,mid,types,get_jni_type(retval));
-
-
+ s->add_method(mname, mid, types, get_jni_type(retval));
}
#endif
diff --git a/platform/android/java_class_wrapper.cpp b/platform/android/java_class_wrapper.cpp
index 2923ef6a91..eb208f0ee0 100644
--- a/platform/android/java_class_wrapper.cpp
+++ b/platform/android/java_class_wrapper.cpp
@@ -29,56 +29,55 @@
#include "java_class_wrapper.h"
#include "thread_jandroid.h"
+bool JavaClass::_call_method(JavaObject *p_instance, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error, Variant &ret) {
-bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error,Variant& ret) {
-
- Map<StringName,List<MethodInfo> >::Element *M=methods.find(p_method);
+ Map<StringName, List<MethodInfo> >::Element *M = methods.find(p_method);
if (!M)
return false;
JNIEnv *env = ThreadAndroid::get_env();
- MethodInfo *method=NULL;
- for (List<MethodInfo>::Element *E=M->get().front();E;E=E->next()) {
+ MethodInfo *method = NULL;
+ for (List<MethodInfo>::Element *E = M->get().front(); E; E = E->next()) {
if (!p_instance && !E->get()._static) {
- r_error.error=Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+ r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
continue;
}
int pc = E->get().param_types.size();
- if (pc>p_argcount) {
+ if (pc > p_argcount) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=pc;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = pc;
continue;
}
- if (pc<p_argcount) {
+ if (pc < p_argcount) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=pc;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = pc;
continue;
}
- uint32_t *ptypes=E->get().param_types.ptr();
- bool valid=true;
+ uint32_t *ptypes = E->get().param_types.ptr();
+ bool valid = true;
- for(int i=0;i<pc;i++) {
+ for (int i = 0; i < pc; i++) {
- Variant::Type arg_expected=Variant::NIL;
- switch(ptypes[i]) {
+ Variant::Type arg_expected = Variant::NIL;
+ switch (ptypes[i]) {
case ARG_TYPE_VOID: {
//bug?
} break;
case ARG_TYPE_BOOLEAN: {
- if (p_args[i]->get_type()!=Variant::BOOL)
- arg_expected=Variant::BOOL;
+ if (p_args[i]->get_type() != Variant::BOOL)
+ arg_expected = Variant::BOOL;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_BYTE:
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_CHAR:
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_SHORT:
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_INT:
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_LONG:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_BYTE:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_CHAR:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_SHORT:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_INT:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_LONG:
case ARG_TYPE_BYTE:
case ARG_TYPE_CHAR:
case ARG_TYPE_SHORT:
@@ -86,127 +85,119 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
case ARG_TYPE_LONG: {
if (!p_args[i]->is_num())
- arg_expected=Variant::INT;
+ arg_expected = Variant::INT;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_FLOAT:
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_DOUBLE:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_FLOAT:
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_DOUBLE:
case ARG_TYPE_FLOAT:
case ARG_TYPE_DOUBLE: {
if (!p_args[i]->is_num())
- arg_expected=Variant::REAL;
+ arg_expected = Variant::REAL;
} break;
case ARG_TYPE_STRING: {
- if (p_args[i]->get_type()!=Variant::STRING)
- arg_expected=Variant::STRING;
+ if (p_args[i]->get_type() != Variant::STRING)
+ arg_expected = Variant::STRING;
} break;
case ARG_TYPE_CLASS: {
- if (p_args[i]->get_type()!=Variant::OBJECT)
- arg_expected=Variant::OBJECT;
+ if (p_args[i]->get_type() != Variant::OBJECT)
+ arg_expected = Variant::OBJECT;
else {
Ref<Reference> ref = *p_args[i];
if (!ref.is_null()) {
- if (ref->cast_to<JavaObject>() ) {
+ if (ref->cast_to<JavaObject>()) {
- Ref<JavaObject> jo=ref;
+ Ref<JavaObject> jo = ref;
//could be faster
jclass c = env->FindClass(E->get().param_sigs[i].operator String().utf8().get_data());
- if (!c || !env->IsInstanceOf(jo->instance,c)) {
+ if (!c || !env->IsInstanceOf(jo->instance, c)) {
- arg_expected=Variant::OBJECT;
+ arg_expected = Variant::OBJECT;
} else {
//ok
}
} else {
- arg_expected=Variant::OBJECT;
+ arg_expected = Variant::OBJECT;
}
-
}
}
} break;
default: {
- if (p_args[i]->get_type()!=Variant::ARRAY)
- arg_expected=Variant::ARRAY;
+ if (p_args[i]->get_type() != Variant::ARRAY)
+ arg_expected = Variant::ARRAY;
} break;
-
}
- if (arg_expected!=Variant::NIL) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=i;
- r_error.expected=arg_expected;
- valid=false;
+ if (arg_expected != Variant::NIL) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = i;
+ r_error.expected = arg_expected;
+ valid = false;
break;
-
}
-
}
if (!valid)
continue;
-
- method=&E->get();
+ method = &E->get();
break;
-
}
if (!method)
return true; //no version convinces
+ r_error.error = Variant::CallError::CALL_OK;
-
- r_error.error=Variant::CallError::CALL_OK;
-
- jvalue *argv=NULL;
+ jvalue *argv = NULL;
if (method->param_types.size()) {
- argv=(jvalue*)alloca( sizeof(jvalue)*method->param_types.size() );
+ argv = (jvalue *)alloca(sizeof(jvalue) * method->param_types.size());
}
List<jobject> to_free;
- for(int i=0;i<method->param_types.size();i++) {
+ for (int i = 0; i < method->param_types.size(); i++) {
- switch(method->param_types[i]) {
- case ARG_TYPE_VOID: {
+ switch (method->param_types[i]) {
+ case ARG_TYPE_VOID: {
//can't happen
- argv[i].l=NULL; //I hope this works
+ argv[i].l = NULL; //I hope this works
} break;
case ARG_TYPE_BOOLEAN: {
- argv[i].z=*p_args[i];
+ argv[i].z = *p_args[i];
} break;
case ARG_TYPE_BYTE: {
- argv[i].b=*p_args[i];
+ argv[i].b = *p_args[i];
} break;
case ARG_TYPE_CHAR: {
- argv[i].c=*p_args[i];
+ argv[i].c = *p_args[i];
} break;
case ARG_TYPE_SHORT: {
- argv[i].s=*p_args[i];
+ argv[i].s = *p_args[i];
} break;
case ARG_TYPE_INT: {
- argv[i].i=*p_args[i];
+ argv[i].i = *p_args[i];
} break;
case ARG_TYPE_LONG: {
- argv[i].j=*p_args[i];
+ argv[i].j = *p_args[i];
} break;
case ARG_TYPE_FLOAT: {
- argv[i].f=*p_args[i];
+ argv[i].f = *p_args[i];
} break;
case ARG_TYPE_DOUBLE: {
- argv[i].d=*p_args[i];
+ argv[i].d = *p_args[i];
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_BOOLEAN: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_BOOLEAN: {
jclass bclass = env->FindClass("java/lang/Boolean");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(Z)V");
jvalue val;
@@ -215,7 +206,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_BYTE: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_BYTE: {
jclass bclass = env->FindClass("java/lang/Byte");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(B)V");
jvalue val;
@@ -224,7 +215,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_CHAR: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_CHAR: {
jclass bclass = env->FindClass("java/lang/Character");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(C)V");
jvalue val;
@@ -233,7 +224,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_SHORT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_SHORT: {
jclass bclass = env->FindClass("java/lang/Short");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(S)V");
jvalue val;
@@ -242,7 +233,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_INT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_INT: {
jclass bclass = env->FindClass("java/lang/Integer");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(I)V");
jvalue val;
@@ -251,7 +242,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_LONG: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_LONG: {
jclass bclass = env->FindClass("java/lang/Long");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(J)V");
jvalue val;
@@ -260,7 +251,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_FLOAT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_FLOAT: {
jclass bclass = env->FindClass("java/lang/Float");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(F)V");
jvalue val;
@@ -269,7 +260,7 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
argv[i].l = obj;
to_free.push_back(obj);
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_TYPE_DOUBLE: {
+ case ARG_NUMBER_CLASS_BIT | ARG_TYPE_DOUBLE: {
jclass bclass = env->FindClass("java/lang/Double");
jmethodID ctor = env->GetMethodID(bclass, "<init>", "(D)V");
jvalue val;
@@ -281,217 +272,214 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
case ARG_TYPE_STRING: {
String s = *p_args[i];
jstring jStr = env->NewStringUTF(s.utf8().get_data());
- argv[i].l=jStr;
+ argv[i].l = jStr;
to_free.push_back(jStr);
} break;
case ARG_TYPE_CLASS: {
- Ref<JavaObject> jo=*p_args[i];
+ Ref<JavaObject> jo = *p_args[i];
if (jo.is_valid()) {
- argv[i].l=jo->instance;
+ argv[i].l = jo->instance;
} else {
- argv[i].l=NULL; //I hope this works
+ argv[i].l = NULL; //I hope this works
}
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_BOOLEAN: {
+ case ARG_ARRAY_BIT | ARG_TYPE_BOOLEAN: {
Array arr = *p_args[i];
jbooleanArray a = env->NewBooleanArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jboolean val = arr[j];
- env->SetBooleanArrayRegion(a,j,1,&val);
+ env->SetBooleanArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_BYTE: {
+ case ARG_ARRAY_BIT | ARG_TYPE_BYTE: {
Array arr = *p_args[i];
jbyteArray a = env->NewByteArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jbyte val = arr[j];
- env->SetByteArrayRegion(a,j,1,&val);
+ env->SetByteArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
-
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_CHAR: {
+ case ARG_ARRAY_BIT | ARG_TYPE_CHAR: {
Array arr = *p_args[i];
jcharArray a = env->NewCharArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jchar val = arr[j];
- env->SetCharArrayRegion(a,j,1,&val);
+ env->SetCharArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_SHORT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_SHORT: {
Array arr = *p_args[i];
jshortArray a = env->NewShortArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jshort val = arr[j];
- env->SetShortArrayRegion(a,j,1,&val);
+ env->SetShortArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_INT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_INT: {
Array arr = *p_args[i];
jintArray a = env->NewIntArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jint val = arr[j];
- env->SetIntArrayRegion(a,j,1,&val);
+ env->SetIntArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_LONG: {
+ case ARG_ARRAY_BIT | ARG_TYPE_LONG: {
Array arr = *p_args[i];
jlongArray a = env->NewLongArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jlong val = arr[j];
- env->SetLongArrayRegion(a,j,1,&val);
+ env->SetLongArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_FLOAT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_FLOAT: {
Array arr = *p_args[i];
jfloatArray a = env->NewFloatArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jfloat val = arr[j];
- env->SetFloatArrayRegion(a,j,1,&val);
+ env->SetFloatArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
-
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_DOUBLE: {
+ case ARG_ARRAY_BIT | ARG_TYPE_DOUBLE: {
Array arr = *p_args[i];
jdoubleArray a = env->NewDoubleArray(arr.size());
- for(int j=0;j<arr.size();j++) {
+ for (int j = 0; j < arr.size(); j++) {
jdouble val = arr[j];
- env->SetDoubleArrayRegion(a,j,1,&val);
+ env->SetDoubleArrayRegion(a, j, 1, &val);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_STRING: {
+ case ARG_ARRAY_BIT | ARG_TYPE_STRING: {
Array arr = *p_args[i];
- jobjectArray a = env->NewObjectArray(arr.size(),env->FindClass("java/lang/String"),NULL);
- for(int j=0;j<arr.size();j++) {
+ jobjectArray a = env->NewObjectArray(arr.size(), env->FindClass("java/lang/String"), NULL);
+ for (int j = 0; j < arr.size(); j++) {
String s = arr[j];
jstring jStr = env->NewStringUTF(s.utf8().get_data());
- env->SetObjectArrayElement(a,j,jStr);
+ env->SetObjectArrayElement(a, j, jStr);
to_free.push_back(jStr);
}
- argv[i].l=a;
+ argv[i].l = a;
to_free.push_back(a);
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_CLASS: {
+ case ARG_ARRAY_BIT | ARG_TYPE_CLASS: {
- argv[i].l=NULL;
+ argv[i].l = NULL;
} break;
}
}
- r_error.error=Variant::CallError::CALL_OK;
- bool success=true;
-
- switch(method->return_type) {
+ r_error.error = Variant::CallError::CALL_OK;
+ bool success = true;
+ switch (method->return_type) {
case ARG_TYPE_VOID: {
if (method->_static) {
- env->CallStaticVoidMethodA(_class,method->method,argv);
+ env->CallStaticVoidMethodA(_class, method->method, argv);
} else {
- env->CallVoidMethodA(p_instance->instance,method->method,argv);
+ env->CallVoidMethodA(p_instance->instance, method->method, argv);
}
- ret=Variant();
+ ret = Variant();
} break;
case ARG_TYPE_BOOLEAN: {
if (method->_static) {
- ret=env->CallStaticBooleanMethodA(_class,method->method,argv);
+ ret = env->CallStaticBooleanMethodA(_class, method->method, argv);
} else {
- ret=env->CallBooleanMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallBooleanMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_BYTE: {
if (method->_static) {
- ret=env->CallStaticByteMethodA(_class,method->method,argv);
+ ret = env->CallStaticByteMethodA(_class, method->method, argv);
} else {
- ret=env->CallByteMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallByteMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_CHAR: {
if (method->_static) {
- ret=env->CallStaticCharMethodA(_class,method->method,argv);
+ ret = env->CallStaticCharMethodA(_class, method->method, argv);
} else {
- ret=env->CallCharMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallCharMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_SHORT: {
if (method->_static) {
- ret=env->CallStaticShortMethodA(_class,method->method,argv);
+ ret = env->CallStaticShortMethodA(_class, method->method, argv);
} else {
- ret=env->CallShortMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallShortMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_INT: {
if (method->_static) {
- ret=env->CallStaticIntMethodA(_class,method->method,argv);
+ ret = env->CallStaticIntMethodA(_class, method->method, argv);
} else {
- ret=env->CallIntMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallIntMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_LONG: {
if (method->_static) {
- ret=env->CallStaticLongMethodA(_class,method->method,argv);
+ ret = env->CallStaticLongMethodA(_class, method->method, argv);
} else {
- ret=env->CallLongMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallLongMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_FLOAT: {
if (method->_static) {
- ret=env->CallStaticFloatMethodA(_class,method->method,argv);
+ ret = env->CallStaticFloatMethodA(_class, method->method, argv);
} else {
- ret=env->CallFloatMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallFloatMethodA(p_instance->instance, method->method, argv);
}
} break;
case ARG_TYPE_DOUBLE: {
if (method->_static) {
- ret=env->CallStaticDoubleMethodA(_class,method->method,argv);
+ ret = env->CallStaticDoubleMethodA(_class, method->method, argv);
} else {
- ret=env->CallDoubleMethodA(p_instance->instance,method->method,argv);
+ ret = env->CallDoubleMethodA(p_instance->instance, method->method, argv);
}
} break;
@@ -499,375 +487,366 @@ bool JavaClass::_call_method(JavaObject* p_instance,const StringName& p_method,c
jobject obj;
if (method->_static) {
- obj=env->CallStaticObjectMethodA(_class,method->method,argv);
+ obj = env->CallStaticObjectMethodA(_class, method->method, argv);
} else {
- obj=env->CallObjectMethodA(p_instance->instance,method->method,argv);
+ obj = env->CallObjectMethodA(p_instance->instance, method->method, argv);
}
if (!obj) {
- ret=Variant();
+ ret = Variant();
} else {
- if (!_convert_object_to_variant(env, obj, ret,method->return_type)) {
- ret=Variant();
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
- success=false;
+ if (!_convert_object_to_variant(env, obj, ret, method->return_type)) {
+ ret = Variant();
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ success = false;
}
env->DeleteLocalRef(obj);
}
} break;
-
}
- for(List<jobject>::Element *E=to_free.front();E;E=E->next()) {
+ for (List<jobject>::Element *E = to_free.front(); E; E = E->next()) {
env->DeleteLocalRef(E->get());
}
return success;
}
-Variant JavaClass::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+Variant JavaClass::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
Variant ret;
- bool found = _call_method(NULL,p_method,p_args,p_argcount,r_error,ret);
+ bool found = _call_method(NULL, p_method, p_args, p_argcount, r_error, ret);
if (found) {
return ret;
}
- return Reference::call(p_method,p_args,p_argcount,r_error);
+ return Reference::call(p_method, p_args, p_argcount, r_error);
}
JavaClass::JavaClass() {
-
}
/////////////////////
-Variant JavaObject::call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error){
+Variant JavaObject::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
return Variant();
}
-JavaObject::JavaObject(const Ref<JavaClass>& p_base,jobject *p_instance) {
-
+JavaObject::JavaObject(const Ref<JavaClass> &p_base, jobject *p_instance) {
}
-JavaObject::~JavaObject(){
-
+JavaObject::~JavaObject() {
}
-
////////////////////
void JavaClassWrapper::_bind_methods() {
- ClassDB::bind_method(D_METHOD("wrap:JavaClass","name"),&JavaClassWrapper::wrap);
+ ClassDB::bind_method(D_METHOD("wrap:JavaClass", "name"), &JavaClassWrapper::wrap);
}
-
-bool JavaClassWrapper::_get_type_sig(JNIEnv *env,jobject obj,uint32_t& sig,String&strsig) {
+bool JavaClassWrapper::_get_type_sig(JNIEnv *env, jobject obj, uint32_t &sig, String &strsig) {
jstring name2 = (jstring)env->CallObjectMethod(obj, Class_getName);
- String str_type = env->GetStringUTFChars( name2, NULL );
- print_line("name: "+str_type);
+ String str_type = env->GetStringUTFChars(name2, NULL);
+ print_line("name: " + str_type);
env->DeleteLocalRef(name2);
- uint32_t t=0;
+ uint32_t t = 0;
if (str_type.begins_with("[")) {
- t=JavaClass::ARG_ARRAY_BIT;
- strsig="[";
- str_type=str_type.substr(1,str_type.length()-1);
+ t = JavaClass::ARG_ARRAY_BIT;
+ strsig = "[";
+ str_type = str_type.substr(1, str_type.length() - 1);
if (str_type.begins_with("[")) {
- print_line("Nested arrays not supported for type: "+str_type);
+ print_line("Nested arrays not supported for type: " + str_type);
return false;
}
if (str_type.begins_with("L")) {
- str_type=str_type.substr(1,str_type.length()-2); //ok it's a class
+ str_type = str_type.substr(1, str_type.length() - 2); //ok it's a class
}
}
- if (str_type=="void" || str_type=="V") {
- t|=JavaClass::ARG_TYPE_VOID;
- strsig+="V";
- } else if (str_type=="boolean" || str_type=="Z") {
- t|=JavaClass::ARG_TYPE_BOOLEAN;
- strsig+="Z";
- } else if (str_type=="byte" || str_type=="B") {
- t|=JavaClass::ARG_TYPE_BYTE;
- strsig+="B";
- } else if (str_type=="char" || str_type=="C") {
- t|=JavaClass::ARG_TYPE_CHAR;
- strsig+="C";
- } else if (str_type=="short" || str_type=="S") {
- t|=JavaClass::ARG_TYPE_SHORT;
- strsig+="S";
- } else if (str_type=="int" || str_type=="I") {
- t|=JavaClass::ARG_TYPE_INT;
- strsig+="I";
- } else if (str_type=="long" || str_type=="J") {
- t|=JavaClass::ARG_TYPE_LONG;
- strsig+="J";
- } else if (str_type=="float" || str_type=="F") {
- t|=JavaClass::ARG_TYPE_FLOAT;
- strsig+="F";
- } else if (str_type=="double" || str_type=="D") {
- t|=JavaClass::ARG_TYPE_DOUBLE;
- strsig+="D";
- } else if (str_type=="java.lang.String") {
- t|=JavaClass::ARG_TYPE_STRING;
- strsig+="Ljava/lang/String;";
- } else if (str_type=="java.lang.Boolean") {
- t|=JavaClass::ARG_TYPE_BOOLEAN|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Boolean;";
- } else if (str_type=="java.lang.Byte") {
- t|=JavaClass::ARG_TYPE_BYTE|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Byte;";
- } else if (str_type=="java.lang.Character") {
- t|=JavaClass::ARG_TYPE_CHAR|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Character;";
- } else if (str_type=="java.lang.Short") {
- t|=JavaClass::ARG_TYPE_SHORT|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Short;";
- } else if (str_type=="java.lang.Integer") {
- t|=JavaClass::ARG_TYPE_INT|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Integer;";
- } else if (str_type=="java.lang.Long") {
- t|=JavaClass::ARG_TYPE_LONG|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Long;";
- } else if (str_type=="java.lang.Float") {
- t|=JavaClass::ARG_TYPE_FLOAT|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Float;";
- } else if (str_type=="java.lang.Double") {
- t|=JavaClass::ARG_TYPE_DOUBLE|JavaClass::ARG_NUMBER_CLASS_BIT;
- strsig+="Ljava/lang/Double;";
+ if (str_type == "void" || str_type == "V") {
+ t |= JavaClass::ARG_TYPE_VOID;
+ strsig += "V";
+ } else if (str_type == "boolean" || str_type == "Z") {
+ t |= JavaClass::ARG_TYPE_BOOLEAN;
+ strsig += "Z";
+ } else if (str_type == "byte" || str_type == "B") {
+ t |= JavaClass::ARG_TYPE_BYTE;
+ strsig += "B";
+ } else if (str_type == "char" || str_type == "C") {
+ t |= JavaClass::ARG_TYPE_CHAR;
+ strsig += "C";
+ } else if (str_type == "short" || str_type == "S") {
+ t |= JavaClass::ARG_TYPE_SHORT;
+ strsig += "S";
+ } else if (str_type == "int" || str_type == "I") {
+ t |= JavaClass::ARG_TYPE_INT;
+ strsig += "I";
+ } else if (str_type == "long" || str_type == "J") {
+ t |= JavaClass::ARG_TYPE_LONG;
+ strsig += "J";
+ } else if (str_type == "float" || str_type == "F") {
+ t |= JavaClass::ARG_TYPE_FLOAT;
+ strsig += "F";
+ } else if (str_type == "double" || str_type == "D") {
+ t |= JavaClass::ARG_TYPE_DOUBLE;
+ strsig += "D";
+ } else if (str_type == "java.lang.String") {
+ t |= JavaClass::ARG_TYPE_STRING;
+ strsig += "Ljava/lang/String;";
+ } else if (str_type == "java.lang.Boolean") {
+ t |= JavaClass::ARG_TYPE_BOOLEAN | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Boolean;";
+ } else if (str_type == "java.lang.Byte") {
+ t |= JavaClass::ARG_TYPE_BYTE | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Byte;";
+ } else if (str_type == "java.lang.Character") {
+ t |= JavaClass::ARG_TYPE_CHAR | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Character;";
+ } else if (str_type == "java.lang.Short") {
+ t |= JavaClass::ARG_TYPE_SHORT | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Short;";
+ } else if (str_type == "java.lang.Integer") {
+ t |= JavaClass::ARG_TYPE_INT | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Integer;";
+ } else if (str_type == "java.lang.Long") {
+ t |= JavaClass::ARG_TYPE_LONG | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Long;";
+ } else if (str_type == "java.lang.Float") {
+ t |= JavaClass::ARG_TYPE_FLOAT | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Float;";
+ } else if (str_type == "java.lang.Double") {
+ t |= JavaClass::ARG_TYPE_DOUBLE | JavaClass::ARG_NUMBER_CLASS_BIT;
+ strsig += "Ljava/lang/Double;";
} else {
//a class likely
- strsig+="L"+str_type.replace(".","/")+";";
- t|=JavaClass::ARG_TYPE_CLASS;
+ strsig += "L" + str_type.replace(".", "/") + ";";
+ t |= JavaClass::ARG_TYPE_CLASS;
}
- sig=t;
-
+ sig = t;
return true;
-
}
-bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& var,uint32_t p_sig) {
+bool JavaClass::_convert_object_to_variant(JNIEnv *env, jobject obj, Variant &var, uint32_t p_sig) {
if (!obj) {
- var=Variant(); //seems null is just null...
+ var = Variant(); //seems null is just null...
return true;
}
-
- switch(p_sig) {
+ switch (p_sig) {
case ARG_TYPE_VOID: {
return Variant();
} break;
- case ARG_TYPE_BOOLEAN|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_BOOLEAN | ARG_NUMBER_CLASS_BIT: {
var = env->CallBooleanMethod(obj, JavaClassWrapper::singleton->Boolean_booleanValue);
return true;
} break;
- case ARG_TYPE_BYTE|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_BYTE | ARG_NUMBER_CLASS_BIT: {
var = env->CallByteMethod(obj, JavaClassWrapper::singleton->Byte_byteValue);
return true;
} break;
- case ARG_TYPE_CHAR|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_CHAR | ARG_NUMBER_CLASS_BIT: {
var = env->CallCharMethod(obj, JavaClassWrapper::singleton->Character_characterValue);
return true;
} break;
- case ARG_TYPE_SHORT|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_SHORT | ARG_NUMBER_CLASS_BIT: {
var = env->CallShortMethod(obj, JavaClassWrapper::singleton->Short_shortValue);
return true;
} break;
- case ARG_TYPE_INT|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_INT | ARG_NUMBER_CLASS_BIT: {
var = env->CallIntMethod(obj, JavaClassWrapper::singleton->Integer_integerValue);
return true;
} break;
- case ARG_TYPE_LONG|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_LONG | ARG_NUMBER_CLASS_BIT: {
var = env->CallLongMethod(obj, JavaClassWrapper::singleton->Long_longValue);
return true;
} break;
- case ARG_TYPE_FLOAT|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_FLOAT | ARG_NUMBER_CLASS_BIT: {
var = env->CallFloatMethod(obj, JavaClassWrapper::singleton->Float_floatValue);
return true;
} break;
- case ARG_TYPE_DOUBLE|ARG_NUMBER_CLASS_BIT: {
+ case ARG_TYPE_DOUBLE | ARG_NUMBER_CLASS_BIT: {
var = env->CallDoubleMethod(obj, JavaClassWrapper::singleton->Double_doubleValue);
return true;
} break;
case ARG_TYPE_STRING: {
- var = String::utf8(env->GetStringUTFChars( (jstring)obj, NULL ));
+ var = String::utf8(env->GetStringUTFChars((jstring)obj, NULL));
return true;
} break;
case ARG_TYPE_CLASS: {
return false;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_VOID: {
+ case ARG_ARRAY_BIT | ARG_TYPE_VOID: {
var = Array(); // ?
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_BOOLEAN: {
+ case ARG_ARRAY_BIT | ARG_TYPE_BOOLEAN: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jboolean val;
- env->GetBooleanArrayRegion((jbooleanArray)arr,0,1,&val);
+ env->GetBooleanArrayRegion((jbooleanArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_BYTE: {
+ case ARG_ARRAY_BIT | ARG_TYPE_BYTE: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jbyte val;
- env->GetByteArrayRegion((jbyteArray)arr,0,1,&val);
+ env->GetByteArrayRegion((jbyteArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_CHAR: {
+ case ARG_ARRAY_BIT | ARG_TYPE_CHAR: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jchar val;
- env->GetCharArrayRegion((jcharArray)arr,0,1,&val);
+ env->GetCharArrayRegion((jcharArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_SHORT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_SHORT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jshort val;
- env->GetShortArrayRegion((jshortArray)arr,0,1,&val);
+ env->GetShortArrayRegion((jshortArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_INT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_INT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jint val;
- env->GetIntArrayRegion((jintArray)arr,0,1,&val);
+ env->GetIntArrayRegion((jintArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_LONG: {
+ case ARG_ARRAY_BIT | ARG_TYPE_LONG: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jlong val;
- env->GetLongArrayRegion((jlongArray)arr,0,1,&val);
+ env->GetLongArrayRegion((jlongArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_FLOAT: {
+ case ARG_ARRAY_BIT | ARG_TYPE_FLOAT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jfloat val;
- env->GetFloatArrayRegion((jfloatArray)arr,0,1,&val);
+ env->GetFloatArrayRegion((jfloatArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_DOUBLE: {
+ case ARG_ARRAY_BIT | ARG_TYPE_DOUBLE: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jdouble val;
- env->GetDoubleArrayRegion((jdoubleArray)arr,0,1,&val);
+ env->GetDoubleArrayRegion((jdoubleArray)arr, 0, 1, &val);
ret.push_back(val);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_BOOLEAN: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_BOOLEAN: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -875,23 +854,22 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
bool val = env->CallBooleanMethod(o, JavaClassWrapper::singleton->Boolean_booleanValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_BYTE: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_BYTE: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -899,22 +877,21 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
int val = env->CallByteMethod(o, JavaClassWrapper::singleton->Byte_byteValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_CHAR: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_CHAR: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -922,22 +899,21 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
int val = env->CallCharMethod(o, JavaClassWrapper::singleton->Character_characterValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_SHORT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_SHORT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -945,22 +921,21 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
int val = env->CallShortMethod(o, JavaClassWrapper::singleton->Short_shortValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_INT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_INT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -968,22 +943,21 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
int val = env->CallIntMethod(o, JavaClassWrapper::singleton->Integer_integerValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_LONG: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_LONG: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -991,22 +965,21 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
int64_t val = env->CallLongMethod(o, JavaClassWrapper::singleton->Long_longValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_FLOAT: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_FLOAT: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -1014,21 +987,20 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
float val = env->CallFloatMethod(o, JavaClassWrapper::singleton->Float_floatValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_NUMBER_CLASS_BIT|ARG_ARRAY_BIT|ARG_TYPE_DOUBLE: {
+ case ARG_NUMBER_CLASS_BIT | ARG_ARRAY_BIT | ARG_TYPE_DOUBLE: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
@@ -1036,58 +1008,53 @@ bool JavaClass::_convert_object_to_variant(JNIEnv * env, jobject obj, Variant& v
else {
double val = env->CallDoubleMethod(o, JavaClassWrapper::singleton->Double_doubleValue);
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_STRING: {
+ case ARG_ARRAY_BIT | ARG_TYPE_STRING: {
Array ret;
jobjectArray arr = (jobjectArray)obj;
int count = env->GetArrayLength(arr);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject o = env->GetObjectArrayElement(arr, i);
if (!o)
ret.push_back(Variant());
else {
- String val = String::utf8(env->GetStringUTFChars( (jstring)o, NULL ));
+ String val = String::utf8(env->GetStringUTFChars((jstring)o, NULL));
ret.push_back(val);
-
}
env->DeleteLocalRef(o);
}
- var=ret;
+ var = ret;
return true;
} break;
- case ARG_ARRAY_BIT|ARG_TYPE_CLASS: {
+ case ARG_ARRAY_BIT | ARG_TYPE_CLASS: {
} break;
}
return false;
-
}
-
-Ref<JavaClass> JavaClassWrapper::wrap(const String& p_class) {
+Ref<JavaClass> JavaClassWrapper::wrap(const String &p_class) {
if (class_cache.has(p_class))
return class_cache[p_class];
-
JNIEnv *env = ThreadAndroid::get_env();
jclass bclass = env->FindClass(p_class.utf8().get_data());
- ERR_FAIL_COND_V(!bclass,Ref<JavaClass>());
+ ERR_FAIL_COND_V(!bclass, Ref<JavaClass>());
//jmethodID getDeclaredMethods = env->GetMethodID(bclass,"getDeclaredMethods", "()[Ljava/lang/reflect/Method;");
@@ -1095,130 +1062,121 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String& p_class) {
jobjectArray methods = (jobjectArray)env->CallObjectMethod(bclass, getDeclaredMethods);
- ERR_FAIL_COND_V(!methods,Ref<JavaClass>());
+ ERR_FAIL_COND_V(!methods, Ref<JavaClass>());
-
- Ref<JavaClass> java_class = memnew( JavaClass );
+ Ref<JavaClass> java_class = memnew(JavaClass);
int count = env->GetArrayLength(methods);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject obj = env->GetObjectArrayElement(methods, i);
ERR_CONTINUE(!obj);
-
jstring name = (jstring)env->CallObjectMethod(obj, getName);
- String str_method = env->GetStringUTFChars( name, NULL );
+ String str_method = env->GetStringUTFChars(name, NULL);
env->DeleteLocalRef(name);
Vector<String> params;
- jint mods = env->CallIntMethod(obj,getModifiers);
+ jint mods = env->CallIntMethod(obj, getModifiers);
- if (!(mods&0x0001)) {
+ if (!(mods & 0x0001)) {
env->DeleteLocalRef(obj);
continue; //not public bye
}
-
-
jobjectArray param_types = (jobjectArray)env->CallObjectMethod(obj, getParameterTypes);
- int count2=env->GetArrayLength(param_types);
+ int count2 = env->GetArrayLength(param_types);
if (!java_class->methods.has(str_method)) {
- java_class->methods[str_method]=List<JavaClass::MethodInfo>();
+ java_class->methods[str_method] = List<JavaClass::MethodInfo>();
}
JavaClass::MethodInfo mi;
- mi._static = (mods&0x8)!=0;
- bool valid=true;
- String signature="(";
+ mi._static = (mods & 0x8) != 0;
+ bool valid = true;
+ String signature = "(";
- for(int j=0;j<count2;j++) {
+ for (int j = 0; j < count2; j++) {
jobject obj2 = env->GetObjectArrayElement(param_types, j);
String strsig;
- uint32_t sig=0;
- if (!_get_type_sig(env,obj2,sig,strsig)) {
- valid=false;
+ uint32_t sig = 0;
+ if (!_get_type_sig(env, obj2, sig, strsig)) {
+ valid = false;
env->DeleteLocalRef(obj2);
break;
}
- signature+=strsig;
+ signature += strsig;
mi.param_types.push_back(sig);
mi.param_sigs.push_back(strsig);
env->DeleteLocalRef(obj2);
-
}
if (!valid) {
- print_line("Method Can't be bound (unsupported arguments): "+p_class+"::"+str_method);
+ print_line("Method Can't be bound (unsupported arguments): " + p_class + "::" + str_method);
env->DeleteLocalRef(obj);
env->DeleteLocalRef(param_types);
continue;
}
- signature+=")";
+ signature += ")";
jobject return_type = (jobject)env->CallObjectMethod(obj, getReturnType);
-
String strsig;
- uint32_t sig=0;
- if (!_get_type_sig(env,return_type,sig,strsig)) {
- print_line("Method Can't be bound (unsupported return type): "+p_class+"::"+str_method);
+ uint32_t sig = 0;
+ if (!_get_type_sig(env, return_type, sig, strsig)) {
+ print_line("Method Can't be bound (unsupported return type): " + p_class + "::" + str_method);
env->DeleteLocalRef(obj);
env->DeleteLocalRef(param_types);
env->DeleteLocalRef(return_type);
continue;
}
- signature+=strsig;
- mi.return_type=sig;
+ signature += strsig;
+ mi.return_type = sig;
- print_line("METHOD: "+str_method+" SIG: "+signature+" static: "+itos(mi._static));
+ print_line("METHOD: " + str_method + " SIG: " + signature + " static: " + itos(mi._static));
- bool discard=false;
+ bool discard = false;
- for(List<JavaClass::MethodInfo>::Element *E=java_class->methods[str_method].front();E;E=E->next()) {
+ for (List<JavaClass::MethodInfo>::Element *E = java_class->methods[str_method].front(); E; E = E->next()) {
- float new_likeliness=0;
- float existing_likeliness=0;
+ float new_likeliness = 0;
+ float existing_likeliness = 0;
- if (E->get().param_types.size()!=mi.param_types.size())
+ if (E->get().param_types.size() != mi.param_types.size())
continue;
- bool valid=true;
- for(int j=0;j<E->get().param_types.size();j++) {
+ bool valid = true;
+ for (int j = 0; j < E->get().param_types.size(); j++) {
Variant::Type _new;
float new_l;
Variant::Type existing;
float existing_l;
- JavaClass::_convert_to_variant_type(E->get().param_types[j],existing,existing_l);
- JavaClass::_convert_to_variant_type(mi.param_types[j],_new,new_l);
- if (_new!=existing) {
- valid=false;
+ JavaClass::_convert_to_variant_type(E->get().param_types[j], existing, existing_l);
+ JavaClass::_convert_to_variant_type(mi.param_types[j], _new, new_l);
+ if (_new != existing) {
+ valid = false;
break;
}
- new_likeliness+=new_l;
- existing_likeliness=existing_l;
-
+ new_likeliness += new_l;
+ existing_likeliness = existing_l;
}
if (!valid)
continue;
- if (new_likeliness>existing_likeliness) {
+ if (new_likeliness > existing_likeliness) {
java_class->methods[str_method].erase(E);
print_line("replace old");
break;
} else {
- discard=true;
+ discard = true;
print_line("old is better");
}
-
-
}
if (!discard) {
@@ -1236,12 +1194,8 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String& p_class) {
env->DeleteLocalRef(param_types);
env->DeleteLocalRef(return_type);
-
-
-
//args[i] = _jobject_to_variant(env, obj);
//print_line("\targ"+itos(i)+": "+Variant::get_type_name(args[i].get_type()));
-
};
env->DeleteLocalRef(methods);
@@ -1250,33 +1204,32 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String& p_class) {
count = env->GetArrayLength(fields);
- for (int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
jobject obj = env->GetObjectArrayElement(fields, i);
ERR_CONTINUE(!obj);
jstring name = (jstring)env->CallObjectMethod(obj, Field_getName);
- String str_field = env->GetStringUTFChars( name, NULL );
+ String str_field = env->GetStringUTFChars(name, NULL);
env->DeleteLocalRef(name);
- print_line("FIELD: "+str_field);
- int mods = env->CallIntMethod(obj,Field_getModifiers);
- if ((mods&0x8) && (mods&0x10) && (mods&0x1)) { //static final public!
+ print_line("FIELD: " + str_field);
+ int mods = env->CallIntMethod(obj, Field_getModifiers);
+ if ((mods & 0x8) && (mods & 0x10) && (mods & 0x1)) { //static final public!
- jobject objc = env->CallObjectMethod(obj, Field_get,NULL);
+ jobject objc = env->CallObjectMethod(obj, Field_get, NULL);
if (objc) {
-
uint32_t sig;
String strsig;
jclass cl = env->GetObjectClass(objc);
- if (JavaClassWrapper::_get_type_sig(env,cl,sig,strsig)) {
+ if (JavaClassWrapper::_get_type_sig(env, cl, sig, strsig)) {
- if ((sig&JavaClass::ARG_TYPE_MASK)<=JavaClass::ARG_TYPE_STRING) {
+ if ((sig & JavaClass::ARG_TYPE_MASK) <= JavaClass::ARG_TYPE_STRING) {
Variant value;
- if (JavaClass::_convert_object_to_variant(env,objc,value,sig)) {
+ if (JavaClass::_convert_object_to_variant(env, objc, value, sig)) {
- java_class->constant_map[str_field]=value;
+ java_class->constant_map[str_field] = value;
}
}
}
@@ -1284,49 +1237,46 @@ Ref<JavaClass> JavaClassWrapper::wrap(const String& p_class) {
env->DeleteLocalRef(cl);
}
-
env->DeleteLocalRef(objc);
-
}
env->DeleteLocalRef(obj);
}
env->DeleteLocalRef(fields);
-
return Ref<JavaClass>();
}
-JavaClassWrapper *JavaClassWrapper::singleton=NULL;
+JavaClassWrapper *JavaClassWrapper::singleton = NULL;
JavaClassWrapper::JavaClassWrapper(jobject p_activity) {
- singleton=this;
+ singleton = this;
JNIEnv *env = ThreadAndroid::get_env();
jclass activityClass = env->FindClass("org/godotengine/godot/Godot");
- jmethodID getClassLoader = env->GetMethodID(activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
+ jmethodID getClassLoader = env->GetMethodID(activityClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
classLoader = env->CallObjectMethod(p_activity, getClassLoader);
- classLoader=(jclass)env->NewGlobalRef(classLoader);
+ classLoader = (jclass)env->NewGlobalRef(classLoader);
jclass classLoaderClass = env->FindClass("java/lang/ClassLoader");
findClass = env->GetMethodID(classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
jclass bclass = env->FindClass("java/lang/Class");
- getDeclaredMethods = env->GetMethodID(bclass,"getDeclaredMethods", "()[Ljava/lang/reflect/Method;");
- getFields = env->GetMethodID(bclass,"getFields", "()[Ljava/lang/reflect/Field;");
- Class_getName = env->GetMethodID(bclass,"getName", "()Ljava/lang/String;");
+ getDeclaredMethods = env->GetMethodID(bclass, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;");
+ getFields = env->GetMethodID(bclass, "getFields", "()[Ljava/lang/reflect/Field;");
+ Class_getName = env->GetMethodID(bclass, "getName", "()Ljava/lang/String;");
//
bclass = env->FindClass("java/lang/reflect/Method");
- getParameterTypes = env->GetMethodID(bclass,"getParameterTypes", "()[Ljava/lang/Class;");
- getReturnType = env->GetMethodID(bclass,"getReturnType", "()Ljava/lang/Class;");
- getName = env->GetMethodID(bclass,"getName", "()Ljava/lang/String;");
- getModifiers = env->GetMethodID(bclass,"getModifiers", "()I");
+ getParameterTypes = env->GetMethodID(bclass, "getParameterTypes", "()[Ljava/lang/Class;");
+ getReturnType = env->GetMethodID(bclass, "getReturnType", "()Ljava/lang/Class;");
+ getName = env->GetMethodID(bclass, "getName", "()Ljava/lang/String;");
+ getModifiers = env->GetMethodID(bclass, "getModifiers", "()I");
///
bclass = env->FindClass("java/lang/reflect/Field");
- Field_getName = env->GetMethodID(bclass,"getName", "()Ljava/lang/String;");
- Field_getModifiers = env->GetMethodID(bclass,"getModifiers", "()I");
- Field_get = env->GetMethodID(bclass,"get", "(Ljava/lang/Object;)Ljava/lang/Object;");
+ Field_getName = env->GetMethodID(bclass, "getName", "()Ljava/lang/String;");
+ Field_getModifiers = env->GetMethodID(bclass, "getModifiers", "()I");
+ Field_get = env->GetMethodID(bclass, "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
// each
bclass = env->FindClass("java/lang/Boolean");
Boolean_booleanValue = env->GetMethodID(bclass, "booleanValue", "()Z");
@@ -1351,5 +1301,4 @@ JavaClassWrapper::JavaClassWrapper(jobject p_activity) {
bclass = env->FindClass("java/lang/Double");
Double_doubleValue = env->GetMethodID(bclass, "doubleValue", "()D");
-
}
diff --git a/platform/android/java_class_wrapper.h b/platform/android/java_class_wrapper.h
index f0156563b2..dcc9973446 100644
--- a/platform/android/java_class_wrapper.h
+++ b/platform/android/java_class_wrapper.h
@@ -30,14 +30,14 @@
#define JAVA_CLASS_WRAPPER_H
#include "reference.h"
-#include <jni.h>
#include <android/log.h>
+#include <jni.h>
class JavaObject;
class JavaClass : public Reference {
- GDCLASS(JavaClass,Reference);
+ GDCLASS(JavaClass, Reference);
enum ArgumentType {
@@ -52,13 +52,12 @@ class JavaClass : public Reference {
ARG_TYPE_DOUBLE,
ARG_TYPE_STRING, //special case
ARG_TYPE_CLASS,
- ARG_ARRAY_BIT=1<<16,
- ARG_NUMBER_CLASS_BIT=1<<17,
- ARG_TYPE_MASK=(1<<16)-1
+ ARG_ARRAY_BIT = 1 << 16,
+ ARG_NUMBER_CLASS_BIT = 1 << 17,
+ ARG_TYPE_MASK = (1 << 16) - 1
};
-
- Map<StringName,Variant> constant_map;
+ Map<StringName, Variant> constant_map;
struct MethodInfo {
@@ -67,94 +66,126 @@ class JavaClass : public Reference {
Vector<StringName> param_sigs;
uint32_t return_type;
jmethodID method;
-
};
- _FORCE_INLINE_ static void _convert_to_variant_type(int p_sig, Variant::Type& r_type, float& likelyhood) {
-
- likelyhood=1.0;
- r_type=Variant::NIL;
-
- switch(p_sig) {
-
- case ARG_TYPE_VOID: r_type=Variant::NIL; break;
- case ARG_TYPE_BOOLEAN|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_BOOLEAN: r_type=Variant::BOOL; break;
- case ARG_TYPE_BYTE|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_BYTE: r_type=Variant::INT; likelyhood=0.1; break;
- case ARG_TYPE_CHAR|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_CHAR: r_type=Variant::INT; likelyhood=0.2; break;
- case ARG_TYPE_SHORT|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_SHORT: r_type=Variant::INT; likelyhood=0.3; break;
- case ARG_TYPE_INT|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_INT: r_type=Variant::INT; likelyhood=1.0; break;
- case ARG_TYPE_LONG|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_LONG: r_type=Variant::INT; likelyhood=0.5; break;
- case ARG_TYPE_FLOAT|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_FLOAT: r_type=Variant::REAL; likelyhood=1.0; break;
- case ARG_TYPE_DOUBLE|ARG_NUMBER_CLASS_BIT:
- case ARG_TYPE_DOUBLE: r_type=Variant::REAL; likelyhood=0.5; break;
- case ARG_TYPE_STRING: r_type=Variant::STRING; break;
- case ARG_TYPE_CLASS: r_type=Variant::OBJECT; break;
- case ARG_ARRAY_BIT|ARG_TYPE_VOID: r_type=Variant::NIL; break;
- case ARG_ARRAY_BIT|ARG_TYPE_BOOLEAN: r_type=Variant::ARRAY; break;
- case ARG_ARRAY_BIT|ARG_TYPE_BYTE: r_type=Variant::POOL_BYTE_ARRAY; likelyhood=1.0; break;
- case ARG_ARRAY_BIT|ARG_TYPE_CHAR: r_type=Variant::POOL_BYTE_ARRAY; likelyhood=0.5; break;
- case ARG_ARRAY_BIT|ARG_TYPE_SHORT: r_type=Variant::POOL_INT_ARRAY; likelyhood=0.3; break;
- case ARG_ARRAY_BIT|ARG_TYPE_INT: r_type=Variant::POOL_INT_ARRAY; likelyhood=1.0; break;
- case ARG_ARRAY_BIT|ARG_TYPE_LONG: r_type=Variant::POOL_INT_ARRAY; likelyhood=0.5; break;
- case ARG_ARRAY_BIT|ARG_TYPE_FLOAT: r_type=Variant::POOL_REAL_ARRAY; likelyhood=1.0; break;
- case ARG_ARRAY_BIT|ARG_TYPE_DOUBLE: r_type=Variant::POOL_REAL_ARRAY; likelyhood=0.5; break;
- case ARG_ARRAY_BIT|ARG_TYPE_STRING: r_type=Variant::POOL_STRING_ARRAY; break;
- case ARG_ARRAY_BIT|ARG_TYPE_CLASS: r_type=Variant::ARRAY; break;
+ _FORCE_INLINE_ static void _convert_to_variant_type(int p_sig, Variant::Type &r_type, float &likelyhood) {
+
+ likelyhood = 1.0;
+ r_type = Variant::NIL;
+
+ switch (p_sig) {
+
+ case ARG_TYPE_VOID: r_type = Variant::NIL; break;
+ case ARG_TYPE_BOOLEAN | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_BOOLEAN: r_type = Variant::BOOL; break;
+ case ARG_TYPE_BYTE | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_BYTE:
+ r_type = Variant::INT;
+ likelyhood = 0.1;
+ break;
+ case ARG_TYPE_CHAR | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_CHAR:
+ r_type = Variant::INT;
+ likelyhood = 0.2;
+ break;
+ case ARG_TYPE_SHORT | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_SHORT:
+ r_type = Variant::INT;
+ likelyhood = 0.3;
+ break;
+ case ARG_TYPE_INT | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_INT:
+ r_type = Variant::INT;
+ likelyhood = 1.0;
+ break;
+ case ARG_TYPE_LONG | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_LONG:
+ r_type = Variant::INT;
+ likelyhood = 0.5;
+ break;
+ case ARG_TYPE_FLOAT | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_FLOAT:
+ r_type = Variant::REAL;
+ likelyhood = 1.0;
+ break;
+ case ARG_TYPE_DOUBLE | ARG_NUMBER_CLASS_BIT:
+ case ARG_TYPE_DOUBLE:
+ r_type = Variant::REAL;
+ likelyhood = 0.5;
+ break;
+ case ARG_TYPE_STRING: r_type = Variant::STRING; break;
+ case ARG_TYPE_CLASS: r_type = Variant::OBJECT; break;
+ case ARG_ARRAY_BIT | ARG_TYPE_VOID: r_type = Variant::NIL; break;
+ case ARG_ARRAY_BIT | ARG_TYPE_BOOLEAN: r_type = Variant::ARRAY; break;
+ case ARG_ARRAY_BIT | ARG_TYPE_BYTE:
+ r_type = Variant::POOL_BYTE_ARRAY;
+ likelyhood = 1.0;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_CHAR:
+ r_type = Variant::POOL_BYTE_ARRAY;
+ likelyhood = 0.5;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_SHORT:
+ r_type = Variant::POOL_INT_ARRAY;
+ likelyhood = 0.3;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_INT:
+ r_type = Variant::POOL_INT_ARRAY;
+ likelyhood = 1.0;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_LONG:
+ r_type = Variant::POOL_INT_ARRAY;
+ likelyhood = 0.5;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_FLOAT:
+ r_type = Variant::POOL_REAL_ARRAY;
+ likelyhood = 1.0;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_DOUBLE:
+ r_type = Variant::POOL_REAL_ARRAY;
+ likelyhood = 0.5;
+ break;
+ case ARG_ARRAY_BIT | ARG_TYPE_STRING: r_type = Variant::POOL_STRING_ARRAY; break;
+ case ARG_ARRAY_BIT | ARG_TYPE_CLASS: r_type = Variant::ARRAY; break;
}
}
- _FORCE_INLINE_ static bool _convert_object_to_variant(JNIEnv * env, jobject obj, Variant& var,uint32_t p_sig);
+ _FORCE_INLINE_ static bool _convert_object_to_variant(JNIEnv *env, jobject obj, Variant &var, uint32_t p_sig);
+ bool _call_method(JavaObject *p_instance, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error, Variant &ret);
-
- bool _call_method(JavaObject* p_instance,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error,Variant& ret);
-
-friend class JavaClassWrapper;
- Map<StringName,List<MethodInfo> > methods;
+ friend class JavaClassWrapper;
+ Map<StringName, List<MethodInfo> > methods;
jclass _class;
public:
-
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error);
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
JavaClass();
-
};
-
class JavaObject : public Reference {
- GDCLASS(JavaObject,Reference);
+ GDCLASS(JavaObject, Reference);
Ref<JavaClass> base_class;
-friend class JavaClass;
+ friend class JavaClass;
jobject instance;
public:
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error);
-
- JavaObject(const Ref<JavaClass>& p_base,jobject *p_instance);
+ JavaObject(const Ref<JavaClass> &p_base, jobject *p_instance);
~JavaObject();
-
};
-
class JavaClassWrapper : public Object {
- GDCLASS(JavaClassWrapper,Object);
+ GDCLASS(JavaClassWrapper, Object);
-
- Map<String,Ref<JavaClass> > class_cache;
-friend class JavaClass;
+ Map<String, Ref<JavaClass> > class_cache;
+ friend class JavaClass;
jclass activityClass;
jmethodID findClass;
jmethodID getDeclaredMethods;
@@ -177,20 +208,19 @@ friend class JavaClass;
jmethodID Double_doubleValue;
jobject classLoader;
- bool _get_type_sig(JNIEnv *env, jobject obj, uint32_t& sig, String&strsig);
+ bool _get_type_sig(JNIEnv *env, jobject obj, uint32_t &sig, String &strsig);
static JavaClassWrapper *singleton;
protected:
-
static void _bind_methods();
-public:
+public:
static JavaClassWrapper *get_singleton() { return singleton; }
- Ref<JavaClass> wrap(const String& p_class);
+ Ref<JavaClass> wrap(const String &p_class);
- JavaClassWrapper(jobject p_activity=NULL);
+ JavaClassWrapper(jobject p_activity = NULL);
};
#endif // JAVA_CLASS_WRAPPER_H
diff --git a/platform/android/java_glue.cpp b/platform/android/java_glue.cpp
index 41558cf86a..4016b44434 100644
--- a/platform/android/java_glue.cpp
+++ b/platform/android/java_glue.cpp
@@ -29,38 +29,35 @@
#ifndef ANDROID_NATIVE_ACTIVITY
#include "java_glue.h"
-#include "os_android.h"
-#include "main/main.h"
-#include <unistd.h>
-#include "file_access_jandroid.h"
-#include "file_access_android.h"
-#include "dir_access_jandroid.h"
+#include "android/asset_manager_jni.h"
#include "audio_driver_jandroid.h"
-#include "global_config.h"
-#include "thread_jandroid.h"
#include "core/os/keyboard.h"
+#include "dir_access_jandroid.h"
+#include "file_access_android.h"
+#include "file_access_jandroid.h"
+#include "global_config.h"
#include "java_class_wrapper.h"
-#include "android/asset_manager_jni.h"
#include "main/input_default.h"
+#include "main/main.h"
+#include "os_android.h"
+#include "thread_jandroid.h"
+#include <unistd.h>
-static JavaClassWrapper *java_class_wrapper=NULL;
-static OS_Android *os_android=NULL;
-
+static JavaClassWrapper *java_class_wrapper = NULL;
+static OS_Android *os_android = NULL;
struct jvalret {
jobject obj;
jvalue val;
- jvalret() { obj=NULL; }
-
-
+ jvalret() { obj = NULL; }
};
-jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_arg, bool force_jobject = false) {
+jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant *p_arg, bool force_jobject = false) {
jvalret v;
- switch(p_type) {
+ switch (p_type) {
case Variant::BOOL: {
@@ -71,11 +68,10 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
val.z = (bool)(*p_arg);
jobject obj = env->NewObjectA(bclass, ctor, &val);
v.val.l = obj;
- v.obj=obj;
+ v.obj = obj;
env->DeleteLocalRef(bclass);
} else {
- v.val.z=*p_arg;
-
+ v.val.z = *p_arg;
};
} break;
case Variant::INT: {
@@ -88,12 +84,11 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
val.i = (int)(*p_arg);
jobject obj = env->NewObjectA(bclass, ctor, &val);
v.val.l = obj;
- v.obj=obj;
+ v.obj = obj;
env->DeleteLocalRef(bclass);
} else {
- v.val.i=*p_arg;
-
+ v.val.i = *p_arg;
};
} break;
case Variant::REAL: {
@@ -106,33 +101,33 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
val.d = (double)(*p_arg);
jobject obj = env->NewObjectA(bclass, ctor, &val);
v.val.l = obj;
- v.obj=obj;
+ v.obj = obj;
env->DeleteLocalRef(bclass);
} else {
- v.val.f=*p_arg;
+ v.val.f = *p_arg;
};
} break;
case Variant::STRING: {
String s = *p_arg;
jstring jStr = env->NewStringUTF(s.utf8().get_data());
- v.val.l=jStr;
- v.obj=jStr;
+ v.val.l = jStr;
+ v.obj = jStr;
} break;
case Variant::POOL_STRING_ARRAY: {
PoolVector<String> sarray = *p_arg;
- jobjectArray arr = env->NewObjectArray(sarray.size(),env->FindClass("java/lang/String"),env->NewStringUTF(""));
+ jobjectArray arr = env->NewObjectArray(sarray.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));
- for(int j=0;j<sarray.size();j++) {
+ for (int j = 0; j < sarray.size(); j++) {
- jstring str = env->NewStringUTF( sarray[j].utf8().get_data() );
- env->SetObjectArrayElement(arr,j,str);
+ jstring str = env->NewStringUTF(sarray[j].utf8().get_data());
+ env->SetObjectArrayElement(arr, j, str);
env->DeleteLocalRef(str);
}
- v.val.l=arr;
- v.obj=arr;
+ v.val.l = arr;
+ v.obj = arr;
} break;
@@ -146,7 +141,7 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
Array keys = dict.keys();
jobjectArray jkeys = env->NewObjectArray(keys.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));
- for (int j=0; j<keys.size(); j++) {
+ for (int j = 0; j < keys.size(); j++) {
jstring str = env->NewStringUTF(String(keys[j]).utf8().get_data());
env->SetObjectArrayElement(jkeys, j, str);
env->DeleteLocalRef(str);
@@ -160,7 +155,7 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
jobjectArray jvalues = env->NewObjectArray(keys.size(), env->FindClass("java/lang/Object"), NULL);
- for (int j=0; j<keys.size(); j++) {
+ for (int j = 0; j < keys.size(); j++) {
Variant var = dict[keys[j]];
jvalret v = _variant_to_jvalue(env, var.get_type(), &var, true);
env->SetObjectArrayElement(jvalues, j, v.val.l);
@@ -176,7 +171,7 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
env->DeleteLocalRef(dclass);
v.val.l = jdict;
- v.obj=jdict;
+ v.obj = jdict;
} break;
case Variant::POOL_INT_ARRAY: {
@@ -184,18 +179,18 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
PoolVector<int> array = *p_arg;
jintArray arr = env->NewIntArray(array.size());
PoolVector<int>::Read r = array.read();
- env->SetIntArrayRegion(arr,0,array.size(),r.ptr());
- v.val.l=arr;
- v.obj=arr;
+ env->SetIntArrayRegion(arr, 0, array.size(), r.ptr());
+ v.val.l = arr;
+ v.obj = arr;
} break;
case Variant::POOL_BYTE_ARRAY: {
PoolVector<uint8_t> array = *p_arg;
jbyteArray arr = env->NewByteArray(array.size());
PoolVector<uint8_t>::Read r = array.read();
- env->SetByteArrayRegion(arr,0,array.size(),reinterpret_cast<const signed char*>(r.ptr()));
- v.val.l=arr;
- v.obj=arr;
+ env->SetByteArrayRegion(arr, 0, array.size(), reinterpret_cast<const signed char *>(r.ptr()));
+ v.val.l = arr;
+ v.obj = arr;
} break;
case Variant::POOL_REAL_ARRAY: {
@@ -203,57 +198,53 @@ jvalret _variant_to_jvalue(JNIEnv *env, Variant::Type p_type, const Variant* p_a
PoolVector<float> array = *p_arg;
jfloatArray arr = env->NewFloatArray(array.size());
PoolVector<float>::Read r = array.read();
- env->SetFloatArrayRegion(arr,0,array.size(),r.ptr());
- v.val.l=arr;
- v.obj=arr;
+ env->SetFloatArrayRegion(arr, 0, array.size(), r.ptr());
+ v.val.l = arr;
+ v.obj = arr;
} break;
default: {
v.val.i = 0;
} break;
-
}
return v;
}
-String _get_class_name(JNIEnv * env, jclass cls, bool* array) {
+String _get_class_name(JNIEnv *env, jclass cls, bool *array) {
jclass cclass = env->FindClass("java/lang/Class");
jmethodID getName = env->GetMethodID(cclass, "getName", "()Ljava/lang/String;");
- jstring clsName=(jstring) env->CallObjectMethod(cls, getName);
+ jstring clsName = (jstring)env->CallObjectMethod(cls, getName);
if (array) {
jmethodID isArray = env->GetMethodID(cclass, "isArray", "()Z");
jboolean isarr = env->CallBooleanMethod(cls, isArray);
(*array) = isarr ? true : false;
}
- String name = env->GetStringUTFChars( clsName, NULL );
+ String name = env->GetStringUTFChars(clsName, NULL);
env->DeleteLocalRef(clsName);
return name;
-
}
-
-Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
+Variant _jobject_to_variant(JNIEnv *env, jobject obj) {
if (obj == NULL) {
return Variant();
}
-
+
jclass c = env->GetObjectClass(obj);
bool array;
String name = _get_class_name(env, c, &array);
//print_line("name is " + name + ", array "+Variant(array));
- print_line("ARGNAME: "+name);
+ print_line("ARGNAME: " + name);
if (name == "java.lang.String") {
- return String::utf8(env->GetStringUTFChars( (jstring)obj, NULL ));
+ return String::utf8(env->GetStringUTFChars((jstring)obj, NULL));
};
-
if (name == "[Ljava.lang.String;") {
jobjectArray arr = (jobjectArray)obj;
@@ -261,11 +252,10 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
//print_line("String array! " + String::num(stringCount));
PoolVector<String> sarr;
- for (int i=0; i<stringCount; i++) {
- jstring string = (jstring) env->GetObjectArrayElement(arr, i);
+ for (int i = 0; i < stringCount; i++) {
+ jstring string = (jstring)env->GetObjectArrayElement(arr, i);
sarr.push_back(String::utf8(env->GetStringUTFChars(string, NULL)));
env->DeleteLocalRef(string);
-
}
return sarr;
@@ -294,7 +284,7 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
sarr.resize(fCount);
PoolVector<int>::Write w = sarr.write();
- env->GetIntArrayRegion(arr,0,fCount,w.ptr());
+ env->GetIntArrayRegion(arr, 0, fCount, w.ptr());
w = PoolVector<int>::Write();
return sarr;
};
@@ -307,7 +297,7 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
sarr.resize(fCount);
PoolVector<uint8_t>::Write w = sarr.write();
- env->GetByteArrayRegion(arr,0,fCount,reinterpret_cast<signed char*>(w.ptr()));
+ env->GetByteArrayRegion(arr, 0, fCount, reinterpret_cast<signed char *>(w.ptr()));
w = PoolVector<uint8_t>::Write();
return sarr;
};
@@ -329,12 +319,11 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
PoolRealArray::Write w = sarr.write();
- for (int i=0; i<fCount; i++) {
+ for (int i = 0; i < fCount; i++) {
double n;
env->GetDoubleArrayRegion(arr, i, 1, &n);
w.ptr()[i] = n;
-
};
return sarr;
};
@@ -346,38 +335,34 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
PoolRealArray sarr;
sarr.resize(fCount);
-
PoolRealArray::Write w = sarr.write();
- for (int i=0; i<fCount; i++) {
+ for (int i = 0; i < fCount; i++) {
float n;
env->GetFloatArrayRegion(arr, i, 1, &n);
w.ptr()[i] = n;
-
};
return sarr;
};
-
if (name == "[Ljava.lang.Object;") {
jobjectArray arr = (jobjectArray)obj;
int objCount = env->GetArrayLength(arr);
Array varr(true);
- for (int i=0; i<objCount; i++) {
+ for (int i = 0; i < objCount; i++) {
jobject jobj = env->GetObjectArrayElement(arr, i);
Variant v = _jobject_to_variant(env, jobj);
varr.push_back(v);
env->DeleteLocalRef(jobj);
-
}
return varr;
};
- if (name == "java.util.HashMap" || name == "org.godotengine.godot.Dictionary") {
+ if (name == "java.util.HashMap" || name == "org.godotengine.godot.Dictionary") {
Dictionary ret(true);
jclass oclass = c;
@@ -394,12 +379,11 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
env->DeleteLocalRef(arr);
//print_line("adding " + String::num(keys.size()) + " to Dictionary!");
- for (int i=0; i<keys.size(); i++) {
+ for (int i = 0; i < keys.size(); i++) {
ret[keys[i]] = vals[i];
};
-
return ret;
};
@@ -410,84 +394,77 @@ Variant _jobject_to_variant(JNIEnv * env, jobject obj) {
class JNISingleton : public Object {
- GDCLASS( JNISingleton, Object );
-
+ GDCLASS(JNISingleton, Object);
struct MethodData {
-
jmethodID method;
Variant::Type ret_type;
Vector<Variant::Type> argtypes;
};
jobject instance;
- Map<StringName,MethodData> method_map;
+ Map<StringName, MethodData> method_map;
public:
-
- virtual Variant call(const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+ virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
//print_line("attempt to call "+String(p_method));
- ERR_FAIL_COND_V(!instance,Variant());
+ ERR_FAIL_COND_V(!instance, Variant());
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
- Map<StringName,MethodData >::Element *E=method_map.find(p_method);
+ Map<StringName, MethodData>::Element *E = method_map.find(p_method);
if (!E) {
print_line("no exists");
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_METHOD;
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_METHOD;
return Variant();
}
-
-
int ac = E->get().argtypes.size();
- if (ac<p_argcount) {
+ if (ac < p_argcount) {
print_line("fewargs");
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=ac;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = ac;
return Variant();
}
- if (ac>p_argcount) {
+ if (ac > p_argcount) {
print_line("manyargs");
- r_error.error=Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
- r_error.argument=ac;
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
+ r_error.argument = ac;
return Variant();
}
+ for (int i = 0; i < p_argcount; i++) {
- for(int i=0;i<p_argcount;i++) {
+ if (!Variant::can_convert(p_args[i]->get_type(), E->get().argtypes[i])) {
- if (!Variant::can_convert(p_args[i]->get_type(),E->get().argtypes[i])) {
-
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=i;
- r_error.expected=E->get().argtypes[i];
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = i;
+ r_error.expected = E->get().argtypes[i];
}
}
-
- jvalue *v=NULL;
+ jvalue *v = NULL;
if (p_argcount) {
- v=(jvalue*)alloca( sizeof(jvalue)*p_argcount );
+ v = (jvalue *)alloca(sizeof(jvalue) * p_argcount);
}
JNIEnv *env = ThreadAndroid::get_env();
int res = env->PushLocalFrame(16);
- ERR_FAIL_COND_V(res!=0,Variant());
+ ERR_FAIL_COND_V(res != 0, Variant());
//print_line("argcount "+String::num(p_argcount));
List<jobject> to_erase;
- for(int i=0;i<p_argcount;i++) {
+ for (int i = 0; i < p_argcount; i++) {
jvalret vr = _variant_to_jvalue(env, E->get().argtypes[i], p_args[i]);
v[i] = vr.val;
@@ -499,37 +476,36 @@ public:
Variant ret;
- switch(E->get().ret_type) {
+ switch (E->get().ret_type) {
case Variant::NIL: {
-
//print_line("call void");
- env->CallVoidMethodA(instance,E->get().method,v);
+ env->CallVoidMethodA(instance, E->get().method, v);
} break;
case Variant::BOOL: {
- ret = env->CallBooleanMethodA(instance,E->get().method,v)==JNI_TRUE;
+ ret = env->CallBooleanMethodA(instance, E->get().method, v) == JNI_TRUE;
//print_line("call bool");
} break;
case Variant::INT: {
- ret = env->CallIntMethodA(instance,E->get().method,v);
+ ret = env->CallIntMethodA(instance, E->get().method, v);
//print_line("call int");
} break;
case Variant::REAL: {
- ret = env->CallFloatMethodA(instance,E->get().method,v);
+ ret = env->CallFloatMethodA(instance, E->get().method, v);
} break;
case Variant::STRING: {
- jobject o = env->CallObjectMethodA(instance,E->get().method,v);
+ jobject o = env->CallObjectMethodA(instance, E->get().method, v);
ret = String::utf8(env->GetStringUTFChars((jstring)o, NULL));
env->DeleteLocalRef(o);
} break;
case Variant::POOL_STRING_ARRAY: {
- jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jobjectArray arr = (jobjectArray)env->CallObjectMethodA(instance, E->get().method, v);
ret = _jobject_to_variant(env, arr);
@@ -537,30 +513,30 @@ public:
} break;
case Variant::POOL_INT_ARRAY: {
- jintArray arr = (jintArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jintArray arr = (jintArray)env->CallObjectMethodA(instance, E->get().method, v);
int fCount = env->GetArrayLength(arr);
PoolVector<int> sarr;
sarr.resize(fCount);
PoolVector<int>::Write w = sarr.write();
- env->GetIntArrayRegion(arr,0,fCount,w.ptr());
+ env->GetIntArrayRegion(arr, 0, fCount, w.ptr());
w = PoolVector<int>::Write();
- ret=sarr;
+ ret = sarr;
env->DeleteLocalRef(arr);
} break;
case Variant::POOL_REAL_ARRAY: {
- jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance,E->get().method,v);
+ jfloatArray arr = (jfloatArray)env->CallObjectMethodA(instance, E->get().method, v);
int fCount = env->GetArrayLength(arr);
PoolVector<float> sarr;
sarr.resize(fCount);
PoolVector<float>::Write w = sarr.write();
- env->GetFloatArrayRegion(arr,0,fCount,w.ptr());
+ env->GetFloatArrayRegion(arr, 0, fCount, w.ptr());
w = PoolVector<float>::Write();
- ret=sarr;
+ ret = sarr;
env->DeleteLocalRef(arr);
} break;
@@ -574,7 +550,6 @@ public:
} break;
default: {
-
print_line("failure..");
env->PopLocalFrame(NULL);
ERR_FAIL_V(Variant());
@@ -592,42 +567,35 @@ public:
return ret;
}
-
jobject get_instance() const {
return instance;
}
void set_instance(jobject p_instance) {
- instance=p_instance;
+ instance = p_instance;
}
-
- void add_method(const StringName& p_name, jmethodID p_method,const Vector<Variant::Type>& p_args, Variant::Type p_ret_type) {
+ void add_method(const StringName &p_name, jmethodID p_method, const Vector<Variant::Type> &p_args, Variant::Type p_ret_type) {
MethodData md;
- md.method=p_method;
- md.argtypes=p_args;
- md.ret_type=p_ret_type;
- method_map[p_name]=md;
-
+ md.method = p_method;
+ md.argtypes = p_args;
+ md.ret_type = p_ret_type;
+ method_map[p_name] = md;
}
-
JNISingleton() {
- instance=NULL;
-
+ instance = NULL;
}
-
};
-
struct TST {
int a;
TST() {
- a=5;
+ a = 5;
}
};
@@ -643,114 +611,111 @@ struct JAndroidPointerEvent {
static List<JAndroidPointerEvent> pointer_events;
static List<InputEvent> key_events;
static List<OS_Android::JoypadEvent> joy_events;
-static bool initialized=false;
-static Mutex *input_mutex=NULL;
-static Mutex *suspend_mutex=NULL;
-static int step=0;
-static bool resized=false;
-static bool resized_reload=false;
-static bool go_back_request=false;
+static bool initialized = false;
+static Mutex *input_mutex = NULL;
+static Mutex *suspend_mutex = NULL;
+static int step = 0;
+static bool resized = false;
+static bool resized_reload = false;
+static bool go_back_request = false;
static Size2 new_size;
static Vector3 accelerometer;
static Vector3 magnetometer;
static Vector3 gyroscope;
-static HashMap<String,JNISingleton*> jni_singletons;
+static HashMap<String, JNISingleton *> jni_singletons;
static jobject godot_io;
static Vector<int> joy_device_ids;
-typedef void (*GFXInitFunc)(void *ud,bool gl2);
+typedef void (*GFXInitFunc)(void *ud, bool gl2);
-static jmethodID _on_video_init=0;
+static jmethodID _on_video_init = 0;
static jobject _godot_instance;
-static jmethodID _openURI=0;
-static jmethodID _getDataDir=0;
-static jmethodID _getLocale=0;
-static jmethodID _getModel=0;
-static jmethodID _getScreenDPI=0;
-static jmethodID _showKeyboard=0;
-static jmethodID _hideKeyboard=0;
-static jmethodID _setScreenOrientation=0;
-static jmethodID _getUniqueID=0;
-static jmethodID _getSystemDir=0;
-static jmethodID _playVideo=0;
-static jmethodID _isVideoPlaying=0;
-static jmethodID _pauseVideo=0;
-static jmethodID _stopVideo=0;
-static jmethodID _setKeepScreenOn=0;
-static jmethodID _alertDialog=0;
-
-static void _gfx_init_func(void* ud, bool gl2) {
-
+static jmethodID _openURI = 0;
+static jmethodID _getDataDir = 0;
+static jmethodID _getLocale = 0;
+static jmethodID _getModel = 0;
+static jmethodID _getScreenDPI = 0;
+static jmethodID _showKeyboard = 0;
+static jmethodID _hideKeyboard = 0;
+static jmethodID _setScreenOrientation = 0;
+static jmethodID _getUniqueID = 0;
+static jmethodID _getSystemDir = 0;
+static jmethodID _playVideo = 0;
+static jmethodID _isVideoPlaying = 0;
+static jmethodID _pauseVideo = 0;
+static jmethodID _stopVideo = 0;
+static jmethodID _setKeepScreenOn = 0;
+static jmethodID _alertDialog = 0;
+
+static void _gfx_init_func(void *ud, bool gl2) {
}
-
-static int _open_uri(const String& p_uri) {
+static int _open_uri(const String &p_uri) {
JNIEnv *env = ThreadAndroid::get_env();
jstring jStr = env->NewStringUTF(p_uri.utf8().get_data());
- return env->CallIntMethod(godot_io,_openURI,jStr) ;
+ return env->CallIntMethod(godot_io, _openURI, jStr);
}
static String _get_data_dir() {
JNIEnv *env = ThreadAndroid::get_env();
- jstring s =(jstring)env->CallObjectMethod(godot_io,_getDataDir);
- return String(env->GetStringUTFChars( s, NULL ));
+ jstring s = (jstring)env->CallObjectMethod(godot_io, _getDataDir);
+ return String(env->GetStringUTFChars(s, NULL));
}
static String _get_locale() {
JNIEnv *env = ThreadAndroid::get_env();
- jstring s =(jstring)env->CallObjectMethod(godot_io,_getLocale);
- return String(env->GetStringUTFChars( s, NULL ));
+ jstring s = (jstring)env->CallObjectMethod(godot_io, _getLocale);
+ return String(env->GetStringUTFChars(s, NULL));
}
static String _get_model() {
- JNIEnv *env = ThreadAndroid::get_env();
- jstring s =(jstring)env->CallObjectMethod(godot_io,_getModel);
- return String(env->GetStringUTFChars( s, NULL ));
+ JNIEnv *env = ThreadAndroid::get_env();
+ jstring s = (jstring)env->CallObjectMethod(godot_io, _getModel);
+ return String(env->GetStringUTFChars(s, NULL));
}
static int _get_screen_dpi() {
JNIEnv *env = ThreadAndroid::get_env();
- return env->CallIntMethod(godot_io,_getScreenDPI);
+ return env->CallIntMethod(godot_io, _getScreenDPI);
}
static String _get_unique_id() {
- JNIEnv *env = ThreadAndroid::get_env();
- jstring s =(jstring)env->CallObjectMethod(godot_io,_getUniqueID);
- return String(env->GetStringUTFChars( s, NULL ));
+ JNIEnv *env = ThreadAndroid::get_env();
+ jstring s = (jstring)env->CallObjectMethod(godot_io, _getUniqueID);
+ return String(env->GetStringUTFChars(s, NULL));
}
-static void _show_vk(const String& p_existing) {
+static void _show_vk(const String &p_existing) {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
jstring jStr = env->NewStringUTF(p_existing.utf8().get_data());
env->CallVoidMethod(godot_io, _showKeyboard, jStr);
}
static void _set_screen_orient(int p_orient) {
- JNIEnv* env = ThreadAndroid::get_env();
- env->CallVoidMethod(godot_io, _setScreenOrientation, p_orient );
+ JNIEnv *env = ThreadAndroid::get_env();
+ env->CallVoidMethod(godot_io, _setScreenOrientation, p_orient);
}
static String _get_system_dir(int p_dir) {
JNIEnv *env = ThreadAndroid::get_env();
- jstring s =(jstring)env->CallObjectMethod(godot_io,_getSystemDir,p_dir);
- return String(env->GetStringUTFChars( s, NULL ));
+ jstring s = (jstring)env->CallObjectMethod(godot_io, _getSystemDir, p_dir);
+ return String(env->GetStringUTFChars(s, NULL));
}
-
static void _hide_vk() {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
env->CallVoidMethod(godot_io, _hideKeyboard);
}
@@ -759,52 +724,50 @@ static void _hide_vk() {
// virtual void native_video_pause();
// virtual void native_video_stop();
-static void _play_video(const String& p_path) {
-
+static void _play_video(const String &p_path) {
}
static bool _is_video_playing() {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
return env->CallBooleanMethod(godot_io, _isVideoPlaying);
//return false;
}
static void _pause_video() {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
env->CallVoidMethod(godot_io, _pauseVideo);
}
static void _stop_video() {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
env->CallVoidMethod(godot_io, _stopVideo);
}
static void _set_keep_screen_on(bool p_enabled) {
- JNIEnv* env = ThreadAndroid::get_env();
+ JNIEnv *env = ThreadAndroid::get_env();
env->CallVoidMethod(_godot_instance, _setKeepScreenOn, p_enabled);
}
-static void _alert(const String& p_message, const String& p_title) {
- JNIEnv* env = ThreadAndroid::get_env();
+static void _alert(const String &p_message, const String &p_title) {
+ JNIEnv *env = ThreadAndroid::get_env();
jstring jStrMessage = env->NewStringUTF(p_message.utf8().get_data());
jstring jStrTitle = env->NewStringUTF(p_title.utf8().get_data());
env->CallVoidMethod(_godot_instance, _alertDialog, jStrMessage, jStrTitle);
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv * env, jobject obj, jobject activity,jboolean p_need_reload_hook, jobjectArray p_cmdline,jobject p_asset_manager) {
-
- __android_log_print(ANDROID_LOG_INFO,"godot","**INIT EVENT! - %p\n",env);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *env, jobject obj, jobject activity, jboolean p_need_reload_hook, jobjectArray p_cmdline, jobject p_asset_manager) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "**INIT EVENT! - %p\n", env);
- initialized=true;
+ initialized = true;
JavaVM *jvm;
env->GetJavaVM(&jvm);
- _godot_instance=env->NewGlobalRef(activity);
+ _godot_instance = env->NewGlobalRef(activity);
//_godot_instance=activity;
- __android_log_print(ANDROID_LOG_INFO,"godot","***************** HELLO FROM JNI!!!!!!!!");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "***************** HELLO FROM JNI!!!!!!!!");
{
//setup IO Object
@@ -812,41 +775,41 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv * e
jclass cls = env->FindClass("org/godotengine/godot/Godot");
if (cls) {
- cls=(jclass)env->NewGlobalRef(cls);
- __android_log_print(ANDROID_LOG_INFO,"godot","*******CLASS FOUND!!!");
+ cls = (jclass)env->NewGlobalRef(cls);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*******CLASS FOUND!!!");
}
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP2, %p",cls);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP2, %p", cls);
jfieldID fid = env->GetStaticFieldID(cls, "io", "Lorg/godotengine/godot/GodotIO;");
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP3 %i",fid);
- jobject ob = env->GetStaticObjectField(cls,fid);
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP4, %p",ob);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP3 %i", fid);
+ jobject ob = env->GetStaticObjectField(cls, fid);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP4, %p", ob);
jobject gob = env->NewGlobalRef(ob);
- __android_log_print(ANDROID_LOG_INFO,"godot","STEP4.5, %p",gob);
- godot_io=gob;
+ __android_log_print(ANDROID_LOG_INFO, "godot", "STEP4.5, %p", gob);
+ godot_io = gob;
_on_video_init = env->GetMethodID(cls, "onVideoInit", "(Z)V");
- _setKeepScreenOn = env->GetMethodID(cls,"setKeepScreenOn","(Z)V");
- _alertDialog = env->GetMethodID(cls,"alert","(Ljava/lang/String;Ljava/lang/String;)V");
+ _setKeepScreenOn = env->GetMethodID(cls, "setKeepScreenOn", "(Z)V");
+ _alertDialog = env->GetMethodID(cls, "alert", "(Ljava/lang/String;Ljava/lang/String;)V");
jclass clsio = env->FindClass("org/godotengine/godot/Godot");
if (cls) {
jclass c = env->GetObjectClass(gob);
- _openURI = env->GetMethodID(c,"openURI","(Ljava/lang/String;)I");
- _getDataDir = env->GetMethodID(c,"getDataDir","()Ljava/lang/String;");
- _getLocale = env->GetMethodID(c,"getLocale","()Ljava/lang/String;");
- _getModel = env->GetMethodID(c,"getModel","()Ljava/lang/String;");
- _getScreenDPI = env->GetMethodID(c, "getScreenDPI","()I");
- _getUniqueID = env->GetMethodID(c,"getUniqueID","()Ljava/lang/String;");
- _showKeyboard = env->GetMethodID(c,"showKeyboard","(Ljava/lang/String;)V");
- _hideKeyboard = env->GetMethodID(c,"hideKeyboard","()V");
- _setScreenOrientation = env->GetMethodID(c,"setScreenOrientation","(I)V");
- _getSystemDir = env->GetMethodID(c,"getSystemDir","(I)Ljava/lang/String;");
- _playVideo = env->GetMethodID(c,"playVideo","(Ljava/lang/String;)V");
- _isVideoPlaying = env->GetMethodID(c,"isVideoPlaying","()Z");
- _pauseVideo = env->GetMethodID(c,"pauseVideo","()V");
- _stopVideo = env->GetMethodID(c,"stopVideo","()V");
+ _openURI = env->GetMethodID(c, "openURI", "(Ljava/lang/String;)I");
+ _getDataDir = env->GetMethodID(c, "getDataDir", "()Ljava/lang/String;");
+ _getLocale = env->GetMethodID(c, "getLocale", "()Ljava/lang/String;");
+ _getModel = env->GetMethodID(c, "getModel", "()Ljava/lang/String;");
+ _getScreenDPI = env->GetMethodID(c, "getScreenDPI", "()I");
+ _getUniqueID = env->GetMethodID(c, "getUniqueID", "()Ljava/lang/String;");
+ _showKeyboard = env->GetMethodID(c, "showKeyboard", "(Ljava/lang/String;)V");
+ _hideKeyboard = env->GetMethodID(c, "hideKeyboard", "()V");
+ _setScreenOrientation = env->GetMethodID(c, "setScreenOrientation", "(I)V");
+ _getSystemDir = env->GetMethodID(c, "getSystemDir", "(I)Ljava/lang/String;");
+ _playVideo = env->GetMethodID(c, "playVideo", "(Ljava/lang/String;)V");
+ _isVideoPlaying = env->GetMethodID(c, "isVideoPlaying", "()Z");
+ _pauseVideo = env->GetMethodID(c, "pauseVideo", "()V");
+ _stopVideo = env->GetMethodID(c, "stopVideo", "()V");
}
ThreadAndroid::make_default(jvm);
@@ -856,89 +819,84 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv * e
jobject amgr = env->NewGlobalRef(p_asset_manager);
- FileAccessAndroid::asset_manager=AAssetManager_fromJava(env,amgr);
+ FileAccessAndroid::asset_manager = AAssetManager_fromJava(env, amgr);
#endif
DirAccessJAndroid::setup(gob);
AudioDriverAndroid::setup(gob);
}
-
- const char ** cmdline=NULL;
- int cmdlen=0;
- bool use_apk_expansion=false;
+ const char **cmdline = NULL;
+ int cmdlen = 0;
+ bool use_apk_expansion = false;
if (p_cmdline) {
cmdlen = env->GetArrayLength(p_cmdline);
if (cmdlen) {
- cmdline = (const char**)malloc((env->GetArrayLength(p_cmdline)+1)*sizeof(const char*));
- cmdline[cmdlen]=NULL;
+ cmdline = (const char **)malloc((env->GetArrayLength(p_cmdline) + 1) * sizeof(const char *));
+ cmdline[cmdlen] = NULL;
- for (int i=0; i<cmdlen; i++) {
+ for (int i = 0; i < cmdlen; i++) {
- jstring string = (jstring) env->GetObjectArrayElement(p_cmdline, i);
+ jstring string = (jstring)env->GetObjectArrayElement(p_cmdline, i);
const char *rawString = env->GetStringUTFChars(string, 0);
if (!rawString) {
- __android_log_print(ANDROID_LOG_INFO,"godot","cmdline arg %i is null\n",i);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "cmdline arg %i is null\n", i);
} else {
//__android_log_print(ANDROID_LOG_INFO,"godot","cmdline arg %i is: %s\n",i,rawString);
- if (strcmp(rawString,"-main_pack")==0)
- use_apk_expansion=true;
+ if (strcmp(rawString, "-main_pack") == 0)
+ use_apk_expansion = true;
}
- cmdline[i]=rawString;
+ cmdline[i] = rawString;
}
}
}
- __android_log_print(ANDROID_LOG_INFO,"godot","CMDLINE LEN %i - APK EXPANSION %I\n",cmdlen,int(use_apk_expansion));
+ __android_log_print(ANDROID_LOG_INFO, "godot", "CMDLINE LEN %i - APK EXPANSION %I\n", cmdlen, int(use_apk_expansion));
- os_android = new OS_Android(_gfx_init_func,env,_open_uri,_get_data_dir,_get_locale, _get_model, _get_screen_dpi, _show_vk, _hide_vk,_set_screen_orient,_get_unique_id, _get_system_dir, _play_video,_is_video_playing, _pause_video, _stop_video, _set_keep_screen_on, _alert, use_apk_expansion);
+ os_android = new OS_Android(_gfx_init_func, env, _open_uri, _get_data_dir, _get_locale, _get_model, _get_screen_dpi, _show_vk, _hide_vk, _set_screen_orient, _get_unique_id, _get_system_dir, _play_video, _is_video_playing, _pause_video, _stop_video, _set_keep_screen_on, _alert, use_apk_expansion);
os_android->set_need_reload_hooks(p_need_reload_hook);
char wd[500];
- getcwd(wd,500);
+ getcwd(wd, 500);
- __android_log_print(ANDROID_LOG_INFO,"godot","test construction %i\n",tst.a);
- __android_log_print(ANDROID_LOG_INFO,"godot","running from dir %s\n",wd);
-
- __android_log_print(ANDROID_LOG_INFO,"godot","**SETUP");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "test construction %i\n", tst.a);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "running from dir %s\n", wd);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "**SETUP");
#if 0
char *args[]={"-test","render",NULL};
__android_log_print(ANDROID_LOG_INFO,"godot","pre asdasd setup...");
Error err = Main::setup("apk",2,args,false);
#else
- Error err = Main::setup("apk",cmdlen,(char**)cmdline,false);
+ Error err = Main::setup("apk", cmdlen, (char **)cmdline, false);
#endif
- if (err!=OK) {
- __android_log_print(ANDROID_LOG_INFO,"godot","*****UNABLE TO SETUP");
+ if (err != OK) {
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*****UNABLE TO SETUP");
return; //should exit instead and print the error
}
- __android_log_print(ANDROID_LOG_INFO,"godot","*****SETUP OK");
+ __android_log_print(ANDROID_LOG_INFO, "godot", "*****SETUP OK");
//video driver is determined here, because once initialized, it cant be changed
String vd = GlobalConfig::get_singleton()->get("display/driver");
+ env->CallVoidMethod(_godot_instance, _on_video_init, (jboolean) true);
- env->CallVoidMethod(_godot_instance, _on_video_init, (jboolean)true);
-
- __android_log_print(ANDROID_LOG_INFO,"godot","**START");
-
- input_mutex=Mutex::create();
- suspend_mutex=Mutex::create();
-
+ __android_log_print(ANDROID_LOG_INFO, "godot", "**START");
+ input_mutex = Mutex::create();
+ suspend_mutex = Mutex::create();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv * env, jobject obj, jint width, jint height, jboolean reload) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jobject obj, jint width, jint height, jboolean reload) {
- __android_log_print(ANDROID_LOG_INFO,"godot","^_^_^_^_^ resize %lld, %i, %i\n",Thread::get_caller_ID(),width,height);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "^_^_^_^_^ resize %lld, %i, %i\n", Thread::get_caller_ID(), width, height);
if (os_android)
- os_android->set_display_size(Size2(width,height));
+ os_android->set_display_size(Size2(width, height));
/*input_mutex->lock();
resized=true;
@@ -946,12 +904,11 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv * env,
resized_reload=true;
new_size=Size2(width,height);
input_mutex->unlock();*/
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv * env, jobject obj,bool p_32_bits) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jobject obj, bool p_32_bits) {
- __android_log_print(ANDROID_LOG_INFO,"godot","^_^_^_^_^ newcontext %lld\n",Thread::get_caller_ID());
+ __android_log_print(ANDROID_LOG_INFO, "godot", "^_^_^_^_^ newcontext %lld\n", Thread::get_caller_ID());
if (os_android) {
os_android->set_context_is_16_bits(!p_32_bits);
@@ -961,24 +918,21 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv * e
os_android->reload_gfx();
}
-
}
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv * env, jobject obj) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_back(JNIEnv *env, jobject obj) {
input_mutex->lock();
- go_back_request=true;
+ go_back_request = true;
input_mutex->unlock();
-
}
static void _initialize_java_modules() {
String modules = GlobalConfig::get_singleton()->get("android/modules");
- Vector<String> mods = modules.split(",",false);
- print_line("ANDROID MODULES : " + modules);
- __android_log_print(ANDROID_LOG_INFO,"godot","mod count: %i",mods.size());
+ Vector<String> mods = modules.split(",", false);
+ print_line("ANDROID MODULES : " + modules);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "mod count: %i", mods.size());
if (mods.size()) {
@@ -986,7 +940,7 @@ static void _initialize_java_modules() {
jclass activityClass = env->FindClass("org/godotengine/godot/Godot");
- jmethodID getClassLoader = env->GetMethodID(activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;");
+ jmethodID getClassLoader = env->GetMethodID(activityClass, "getClassLoader", "()Ljava/lang/ClassLoader;");
jobject cls = env->CallObjectMethod(_godot_instance, getClassLoader);
//cls=env->NewGlobalRef(cls);
@@ -996,52 +950,43 @@ static void _initialize_java_modules() {
jmethodID findClass = env->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
- for (int i=0;i<mods.size();i++) {
+ for (int i = 0; i < mods.size(); i++) {
String m = mods[i];
//jclass singletonClass = env->FindClass(m.utf8().get_data());
- print_line("LOADING MODULE: "+m);
+ print_line("LOADING MODULE: " + m);
jstring strClassName = env->NewStringUTF(m.utf8().get_data());
jclass singletonClass = (jclass)env->CallObjectMethod(cls, findClass, strClassName);
if (!singletonClass) {
- ERR_EXPLAIN("Couldn't find singleton for class: "+m);
+ ERR_EXPLAIN("Couldn't find singleton for class: " + m);
ERR_CONTINUE(!singletonClass);
}
//singletonClass=(jclass)env->NewGlobalRef(singletonClass);
- __android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class data %x",singletonClass);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "****^*^*?^*^*class data %x", singletonClass);
jmethodID initialize = env->GetStaticMethodID(singletonClass, "initialize", "(Landroid/app/Activity;)Lorg/godotengine/godot/Godot$SingletonBase;");
if (!initialize) {
- ERR_EXPLAIN("Couldn't find proper initialize function 'public static Godot.SingletonBase Class::initialize(Activity p_activity)' initializer for singleton class: "+m);
+ ERR_EXPLAIN("Couldn't find proper initialize function 'public static Godot.SingletonBase Class::initialize(Activity p_activity)' initializer for singleton class: " + m);
ERR_CONTINUE(!initialize);
-
}
- jobject obj = env->CallStaticObjectMethod(singletonClass,initialize,_godot_instance);
- __android_log_print(ANDROID_LOG_INFO,"godot","****^*^*?^*^*class instance %x",obj);
+ jobject obj = env->CallStaticObjectMethod(singletonClass, initialize, _godot_instance);
+ __android_log_print(ANDROID_LOG_INFO, "godot", "****^*^*?^*^*class instance %x", obj);
jobject gob = env->NewGlobalRef(obj);
-
-
}
-
}
-
}
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jobject obj)
-{
-
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jobject obj) {
ThreadAndroid::setup_thread();
//__android_log_print(ANDROID_LOG_INFO,"godot","**STEP EVENT! - %p-%i\n",env,Thread::get_caller_ID());
-
suspend_mutex->lock();
input_mutex->lock();
//first time step happens, initialize
@@ -1049,8 +994,8 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jo
// ugly hack to initialize the rest of the engine
// because of the way android forces you to do everything with threads
- java_class_wrapper = memnew( JavaClassWrapper(_godot_instance ));
- GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("JavaClassWrapper",java_class_wrapper));
+ java_class_wrapper = memnew(JavaClassWrapper(_godot_instance));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("JavaClassWrapper", java_class_wrapper));
_initialize_java_modules();
Main::setup2();
@@ -1071,10 +1016,10 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jo
++step;
}
- while(pointer_events.size()) {
+ while (pointer_events.size()) {
- JAndroidPointerEvent jpe=pointer_events.front()->get();
- os_android->process_touch(jpe.what,jpe.pointer,jpe.points);
+ JAndroidPointerEvent jpe = pointer_events.front()->get();
+ os_android->process_touch(jpe.what, jpe.pointer, jpe.points);
pointer_events.pop_front();
}
@@ -1098,10 +1043,9 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jo
if (go_back_request) {
os_android->main_loop_request_go_back();
- go_back_request=false;
+ go_back_request = false;
}
-
input_mutex->unlock();
os_android->process_accelerometer(accelerometer);
@@ -1110,41 +1054,36 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jo
os_android->process_gyroscope(gyroscope);
- if (os_android->main_loop_iterate()==true) {
+ if (os_android->main_loop_iterate() == true) {
jclass cls = env->FindClass("org/godotengine/godot/Godot");
jmethodID _finish = env->GetMethodID(cls, "forceQuit", "()V");
env->CallVoidMethod(_godot_instance, _finish);
- __android_log_print(ANDROID_LOG_INFO,"godot","**FINISH REQUEST!!! - %p-%i\n",env,Thread::get_caller_ID());
-
+ __android_log_print(ANDROID_LOG_INFO, "godot", "**FINISH REQUEST!!! - %p-%i\n", env, Thread::get_caller_ID());
}
suspend_mutex->unlock();
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv * env, jobject obj, jint ev,jint pointer, jint count, jintArray positions) {
-
-
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv *env, jobject obj, jint ev, jint pointer, jint count, jintArray positions) {
//__android_log_print(ANDROID_LOG_INFO,"godot","**TOUCH EVENT! - %p-%i\n",env,Thread::get_caller_ID());
-
Vector<OS_Android::TouchPos> points;
- for(int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
jint p[3];
- env->GetIntArrayRegion(positions,i*3,3,p);
+ env->GetIntArrayRegion(positions, i * 3, 3, p);
OS_Android::TouchPos tp;
- tp.pos=Point2(p[1],p[2]);
- tp.id=p[0];
+ tp.pos = Point2(p[1], p[2]);
+ tp.id = p[0];
points.push_back(tp);
}
JAndroidPointerEvent jpe;
- jpe.pointer=pointer;
- jpe.points=points;
- jpe.what=ev;
+ jpe.pointer = pointer;
+ jpe.points = points;
+ jpe.what = ev;
input_mutex->lock();
@@ -1155,127 +1094,126 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv * env, j
if (os_android)
os_android->process_touch(ev,pointer,points);
*/
-
}
/*
* Android Key codes.
*/
enum {
- AKEYCODE_UNKNOWN = 0,
- AKEYCODE_SOFT_LEFT = 1,
- AKEYCODE_SOFT_RIGHT = 2,
- AKEYCODE_HOME = 3,
- AKEYCODE_BACK = 4,
- AKEYCODE_CALL = 5,
- AKEYCODE_ENDCALL = 6,
- AKEYCODE_0 = 7,
- AKEYCODE_1 = 8,
- AKEYCODE_2 = 9,
- AKEYCODE_3 = 10,
- AKEYCODE_4 = 11,
- AKEYCODE_5 = 12,
- AKEYCODE_6 = 13,
- AKEYCODE_7 = 14,
- AKEYCODE_8 = 15,
- AKEYCODE_9 = 16,
- AKEYCODE_STAR = 17,
- AKEYCODE_POUND = 18,
- AKEYCODE_DPAD_UP = 19,
- AKEYCODE_DPAD_DOWN = 20,
- AKEYCODE_DPAD_LEFT = 21,
- AKEYCODE_DPAD_RIGHT = 22,
- AKEYCODE_DPAD_CENTER = 23,
- AKEYCODE_VOLUME_UP = 24,
- AKEYCODE_VOLUME_DOWN = 25,
- AKEYCODE_POWER = 26,
- AKEYCODE_CAMERA = 27,
- AKEYCODE_CLEAR = 28,
- AKEYCODE_A = 29,
- AKEYCODE_B = 30,
- AKEYCODE_C = 31,
- AKEYCODE_D = 32,
- AKEYCODE_E = 33,
- AKEYCODE_F = 34,
- AKEYCODE_G = 35,
- AKEYCODE_H = 36,
- AKEYCODE_I = 37,
- AKEYCODE_J = 38,
- AKEYCODE_K = 39,
- AKEYCODE_L = 40,
- AKEYCODE_M = 41,
- AKEYCODE_N = 42,
- AKEYCODE_O = 43,
- AKEYCODE_P = 44,
- AKEYCODE_Q = 45,
- AKEYCODE_R = 46,
- AKEYCODE_S = 47,
- AKEYCODE_T = 48,
- AKEYCODE_U = 49,
- AKEYCODE_V = 50,
- AKEYCODE_W = 51,
- AKEYCODE_X = 52,
- AKEYCODE_Y = 53,
- AKEYCODE_Z = 54,
- AKEYCODE_COMMA = 55,
- AKEYCODE_PERIOD = 56,
- AKEYCODE_ALT_LEFT = 57,
- AKEYCODE_ALT_RIGHT = 58,
- AKEYCODE_SHIFT_LEFT = 59,
- AKEYCODE_SHIFT_RIGHT = 60,
- AKEYCODE_TAB = 61,
- AKEYCODE_SPACE = 62,
- AKEYCODE_SYM = 63,
- AKEYCODE_EXPLORER = 64,
- AKEYCODE_ENVELOPE = 65,
- AKEYCODE_ENTER = 66,
- AKEYCODE_DEL = 67,
- AKEYCODE_GRAVE = 68,
- AKEYCODE_MINUS = 69,
- AKEYCODE_EQUALS = 70,
- AKEYCODE_LEFT_BRACKET = 71,
- AKEYCODE_RIGHT_BRACKET = 72,
- AKEYCODE_BACKSLASH = 73,
- AKEYCODE_SEMICOLON = 74,
- AKEYCODE_APOSTROPHE = 75,
- AKEYCODE_SLASH = 76,
- AKEYCODE_AT = 77,
- AKEYCODE_NUM = 78,
- AKEYCODE_HEADSETHOOK = 79,
- AKEYCODE_FOCUS = 80, // *Camera* focus
- AKEYCODE_PLUS = 81,
- AKEYCODE_MENU = 82,
- AKEYCODE_NOTIFICATION = 83,
- AKEYCODE_SEARCH = 84,
- AKEYCODE_MEDIA_PLAY_PAUSE= 85,
- AKEYCODE_MEDIA_STOP = 86,
- AKEYCODE_MEDIA_NEXT = 87,
- AKEYCODE_MEDIA_PREVIOUS = 88,
- AKEYCODE_MEDIA_REWIND = 89,
- AKEYCODE_MEDIA_FAST_FORWARD = 90,
- AKEYCODE_MUTE = 91,
- AKEYCODE_PAGE_UP = 92,
- AKEYCODE_PAGE_DOWN = 93,
- AKEYCODE_PICTSYMBOLS = 94,
- AKEYCODE_SWITCH_CHARSET = 95,
- AKEYCODE_BUTTON_A = 96,
- AKEYCODE_BUTTON_B = 97,
- AKEYCODE_BUTTON_C = 98,
- AKEYCODE_BUTTON_X = 99,
- AKEYCODE_BUTTON_Y = 100,
- AKEYCODE_BUTTON_Z = 101,
- AKEYCODE_BUTTON_L1 = 102,
- AKEYCODE_BUTTON_R1 = 103,
- AKEYCODE_BUTTON_L2 = 104,
- AKEYCODE_BUTTON_R2 = 105,
- AKEYCODE_BUTTON_THUMBL = 106,
- AKEYCODE_BUTTON_THUMBR = 107,
- AKEYCODE_BUTTON_START = 108,
- AKEYCODE_BUTTON_SELECT = 109,
- AKEYCODE_BUTTON_MODE = 110,
-
- // NOTE: If you add a new keycode here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
+ AKEYCODE_UNKNOWN = 0,
+ AKEYCODE_SOFT_LEFT = 1,
+ AKEYCODE_SOFT_RIGHT = 2,
+ AKEYCODE_HOME = 3,
+ AKEYCODE_BACK = 4,
+ AKEYCODE_CALL = 5,
+ AKEYCODE_ENDCALL = 6,
+ AKEYCODE_0 = 7,
+ AKEYCODE_1 = 8,
+ AKEYCODE_2 = 9,
+ AKEYCODE_3 = 10,
+ AKEYCODE_4 = 11,
+ AKEYCODE_5 = 12,
+ AKEYCODE_6 = 13,
+ AKEYCODE_7 = 14,
+ AKEYCODE_8 = 15,
+ AKEYCODE_9 = 16,
+ AKEYCODE_STAR = 17,
+ AKEYCODE_POUND = 18,
+ AKEYCODE_DPAD_UP = 19,
+ AKEYCODE_DPAD_DOWN = 20,
+ AKEYCODE_DPAD_LEFT = 21,
+ AKEYCODE_DPAD_RIGHT = 22,
+ AKEYCODE_DPAD_CENTER = 23,
+ AKEYCODE_VOLUME_UP = 24,
+ AKEYCODE_VOLUME_DOWN = 25,
+ AKEYCODE_POWER = 26,
+ AKEYCODE_CAMERA = 27,
+ AKEYCODE_CLEAR = 28,
+ AKEYCODE_A = 29,
+ AKEYCODE_B = 30,
+ AKEYCODE_C = 31,
+ AKEYCODE_D = 32,
+ AKEYCODE_E = 33,
+ AKEYCODE_F = 34,
+ AKEYCODE_G = 35,
+ AKEYCODE_H = 36,
+ AKEYCODE_I = 37,
+ AKEYCODE_J = 38,
+ AKEYCODE_K = 39,
+ AKEYCODE_L = 40,
+ AKEYCODE_M = 41,
+ AKEYCODE_N = 42,
+ AKEYCODE_O = 43,
+ AKEYCODE_P = 44,
+ AKEYCODE_Q = 45,
+ AKEYCODE_R = 46,
+ AKEYCODE_S = 47,
+ AKEYCODE_T = 48,
+ AKEYCODE_U = 49,
+ AKEYCODE_V = 50,
+ AKEYCODE_W = 51,
+ AKEYCODE_X = 52,
+ AKEYCODE_Y = 53,
+ AKEYCODE_Z = 54,
+ AKEYCODE_COMMA = 55,
+ AKEYCODE_PERIOD = 56,
+ AKEYCODE_ALT_LEFT = 57,
+ AKEYCODE_ALT_RIGHT = 58,
+ AKEYCODE_SHIFT_LEFT = 59,
+ AKEYCODE_SHIFT_RIGHT = 60,
+ AKEYCODE_TAB = 61,
+ AKEYCODE_SPACE = 62,
+ AKEYCODE_SYM = 63,
+ AKEYCODE_EXPLORER = 64,
+ AKEYCODE_ENVELOPE = 65,
+ AKEYCODE_ENTER = 66,
+ AKEYCODE_DEL = 67,
+ AKEYCODE_GRAVE = 68,
+ AKEYCODE_MINUS = 69,
+ AKEYCODE_EQUALS = 70,
+ AKEYCODE_LEFT_BRACKET = 71,
+ AKEYCODE_RIGHT_BRACKET = 72,
+ AKEYCODE_BACKSLASH = 73,
+ AKEYCODE_SEMICOLON = 74,
+ AKEYCODE_APOSTROPHE = 75,
+ AKEYCODE_SLASH = 76,
+ AKEYCODE_AT = 77,
+ AKEYCODE_NUM = 78,
+ AKEYCODE_HEADSETHOOK = 79,
+ AKEYCODE_FOCUS = 80, // *Camera* focus
+ AKEYCODE_PLUS = 81,
+ AKEYCODE_MENU = 82,
+ AKEYCODE_NOTIFICATION = 83,
+ AKEYCODE_SEARCH = 84,
+ AKEYCODE_MEDIA_PLAY_PAUSE = 85,
+ AKEYCODE_MEDIA_STOP = 86,
+ AKEYCODE_MEDIA_NEXT = 87,
+ AKEYCODE_MEDIA_PREVIOUS = 88,
+ AKEYCODE_MEDIA_REWIND = 89,
+ AKEYCODE_MEDIA_FAST_FORWARD = 90,
+ AKEYCODE_MUTE = 91,
+ AKEYCODE_PAGE_UP = 92,
+ AKEYCODE_PAGE_DOWN = 93,
+ AKEYCODE_PICTSYMBOLS = 94,
+ AKEYCODE_SWITCH_CHARSET = 95,
+ AKEYCODE_BUTTON_A = 96,
+ AKEYCODE_BUTTON_B = 97,
+ AKEYCODE_BUTTON_C = 98,
+ AKEYCODE_BUTTON_X = 99,
+ AKEYCODE_BUTTON_Y = 100,
+ AKEYCODE_BUTTON_Z = 101,
+ AKEYCODE_BUTTON_L1 = 102,
+ AKEYCODE_BUTTON_R1 = 103,
+ AKEYCODE_BUTTON_L2 = 104,
+ AKEYCODE_BUTTON_R2 = 105,
+ AKEYCODE_BUTTON_THUMBL = 106,
+ AKEYCODE_BUTTON_THUMBR = 107,
+ AKEYCODE_BUTTON_START = 108,
+ AKEYCODE_BUTTON_SELECT = 109,
+ AKEYCODE_BUTTON_MODE = 110,
+
+ // NOTE: If you add a new keycode here you must also add it to several other files.
+ // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
};
struct _WinTranslatePair {
@@ -1284,96 +1222,96 @@ struct _WinTranslatePair {
unsigned int keycode;
};
-
-static _WinTranslatePair _ak_to_keycode[]={
-{ KEY_TAB, AKEYCODE_TAB },
-{ KEY_ENTER, AKEYCODE_ENTER },
-{ KEY_SHIFT, AKEYCODE_SHIFT_LEFT },
-{ KEY_SHIFT, AKEYCODE_SHIFT_RIGHT },
-{ KEY_ALT, AKEYCODE_ALT_LEFT },
-{ KEY_ALT, AKEYCODE_ALT_RIGHT },
-{ KEY_MENU, AKEYCODE_MENU },
-{ KEY_PAUSE, AKEYCODE_MEDIA_PLAY_PAUSE },
-{ KEY_ESCAPE, AKEYCODE_BACK },
-{ KEY_SPACE, AKEYCODE_SPACE },
-{ KEY_PAGEUP, AKEYCODE_PAGE_UP },
-{ KEY_PAGEDOWN, AKEYCODE_PAGE_DOWN },
-{ KEY_HOME, AKEYCODE_HOME },//(0x24)
-{ KEY_LEFT, AKEYCODE_DPAD_LEFT },
-{ KEY_UP, AKEYCODE_DPAD_UP },
-{ KEY_RIGHT, AKEYCODE_DPAD_RIGHT },
-{ KEY_DOWN, AKEYCODE_DPAD_DOWN},
-{ KEY_PERIODCENTERED, AKEYCODE_DPAD_CENTER },
-{ KEY_BACKSPACE, AKEYCODE_DEL},
-{ KEY_0, AKEYCODE_0 },////0 key
-{ KEY_1, AKEYCODE_1 },////1 key
-{ KEY_2, AKEYCODE_2 },////2 key
-{ KEY_3, AKEYCODE_3 },////3 key
-{ KEY_4, AKEYCODE_4 },////4 key
-{ KEY_5, AKEYCODE_5 },////5 key
-{ KEY_6, AKEYCODE_6 },////6 key
-{ KEY_7, AKEYCODE_7 },////7 key
-{ KEY_8, AKEYCODE_8 },////8 key
-{ KEY_9, AKEYCODE_9 },////9 key
-{ KEY_A, AKEYCODE_A },////A key
-{ KEY_B, AKEYCODE_B },////B key
-{ KEY_C, AKEYCODE_C },////C key
-{ KEY_D, AKEYCODE_D },////D key
-{ KEY_E, AKEYCODE_E },////E key
-{ KEY_F, AKEYCODE_F },////F key
-{ KEY_G, AKEYCODE_G },////G key
-{ KEY_H, AKEYCODE_H },////H key
-{ KEY_I, AKEYCODE_I },////I key
-{ KEY_J, AKEYCODE_J },////J key
-{ KEY_K, AKEYCODE_K },////K key
-{ KEY_L, AKEYCODE_L },////L key
-{ KEY_M, AKEYCODE_M },////M key
-{ KEY_N, AKEYCODE_N },////N key
-{ KEY_O, AKEYCODE_O },////O key
-{ KEY_P, AKEYCODE_P },////P key
-{ KEY_Q, AKEYCODE_Q },////Q key
-{ KEY_R, AKEYCODE_R },////R key
-{ KEY_S, AKEYCODE_S },////S key
-{ KEY_T, AKEYCODE_T },////T key
-{ KEY_U, AKEYCODE_U },////U key
-{ KEY_V, AKEYCODE_V },////V key
-{ KEY_W, AKEYCODE_W },////W key
-{ KEY_X, AKEYCODE_X },////X key
-{ KEY_Y, AKEYCODE_Y },////Y key
-{ KEY_Z, AKEYCODE_Z },////Z key
-{ KEY_HOMEPAGE, AKEYCODE_EXPLORER},
-{ KEY_LAUNCH0, AKEYCODE_BUTTON_A},
-{ KEY_LAUNCH1, AKEYCODE_BUTTON_B},
-{ KEY_LAUNCH2, AKEYCODE_BUTTON_C},
-{ KEY_LAUNCH3, AKEYCODE_BUTTON_X},
-{ KEY_LAUNCH4, AKEYCODE_BUTTON_Y},
-{ KEY_LAUNCH5, AKEYCODE_BUTTON_Z},
-{ KEY_LAUNCH6, AKEYCODE_BUTTON_L1},
-{ KEY_LAUNCH7, AKEYCODE_BUTTON_R1},
-{ KEY_LAUNCH8, AKEYCODE_BUTTON_L2},
-{ KEY_LAUNCH9, AKEYCODE_BUTTON_R2},
-{ KEY_LAUNCHA, AKEYCODE_BUTTON_THUMBL},
-{ KEY_LAUNCHB, AKEYCODE_BUTTON_THUMBR},
-{ KEY_LAUNCHC, AKEYCODE_BUTTON_START},
-{ KEY_LAUNCHD, AKEYCODE_BUTTON_SELECT},
-{ KEY_LAUNCHE, AKEYCODE_BUTTON_MODE},
-{ KEY_VOLUMEMUTE, AKEYCODE_MUTE},
-{ KEY_VOLUMEDOWN, AKEYCODE_VOLUME_DOWN},
-{ KEY_VOLUMEUP, AKEYCODE_VOLUME_UP},
-{ KEY_BACK, AKEYCODE_MEDIA_REWIND },
-{ KEY_FORWARD, AKEYCODE_MEDIA_FAST_FORWARD },
-{ KEY_MEDIANEXT, AKEYCODE_MEDIA_NEXT },
-{ KEY_MEDIAPREVIOUS, AKEYCODE_MEDIA_PREVIOUS },
-{ KEY_MEDIASTOP, AKEYCODE_MEDIA_STOP },
-{ KEY_PLUS, AKEYCODE_PLUS },
-{ KEY_EQUAL, AKEYCODE_EQUALS},// the '+' key
-{ KEY_COMMA, AKEYCODE_COMMA},// the ',' key
-{ KEY_MINUS, AKEYCODE_MINUS},// the '-' key
-{ KEY_SLASH, AKEYCODE_SLASH},// the '/?' key
-{ KEY_BACKSLASH, AKEYCODE_BACKSLASH},
-{ KEY_BRACKETLEFT, AKEYCODE_LEFT_BRACKET},
-{ KEY_BRACKETRIGHT, AKEYCODE_RIGHT_BRACKET},
-{ KEY_UNKNOWN, 0} };
+static _WinTranslatePair _ak_to_keycode[] = {
+ { KEY_TAB, AKEYCODE_TAB },
+ { KEY_ENTER, AKEYCODE_ENTER },
+ { KEY_SHIFT, AKEYCODE_SHIFT_LEFT },
+ { KEY_SHIFT, AKEYCODE_SHIFT_RIGHT },
+ { KEY_ALT, AKEYCODE_ALT_LEFT },
+ { KEY_ALT, AKEYCODE_ALT_RIGHT },
+ { KEY_MENU, AKEYCODE_MENU },
+ { KEY_PAUSE, AKEYCODE_MEDIA_PLAY_PAUSE },
+ { KEY_ESCAPE, AKEYCODE_BACK },
+ { KEY_SPACE, AKEYCODE_SPACE },
+ { KEY_PAGEUP, AKEYCODE_PAGE_UP },
+ { KEY_PAGEDOWN, AKEYCODE_PAGE_DOWN },
+ { KEY_HOME, AKEYCODE_HOME }, //(0x24)
+ { KEY_LEFT, AKEYCODE_DPAD_LEFT },
+ { KEY_UP, AKEYCODE_DPAD_UP },
+ { KEY_RIGHT, AKEYCODE_DPAD_RIGHT },
+ { KEY_DOWN, AKEYCODE_DPAD_DOWN },
+ { KEY_PERIODCENTERED, AKEYCODE_DPAD_CENTER },
+ { KEY_BACKSPACE, AKEYCODE_DEL },
+ { KEY_0, AKEYCODE_0 }, ////0 key
+ { KEY_1, AKEYCODE_1 }, ////1 key
+ { KEY_2, AKEYCODE_2 }, ////2 key
+ { KEY_3, AKEYCODE_3 }, ////3 key
+ { KEY_4, AKEYCODE_4 }, ////4 key
+ { KEY_5, AKEYCODE_5 }, ////5 key
+ { KEY_6, AKEYCODE_6 }, ////6 key
+ { KEY_7, AKEYCODE_7 }, ////7 key
+ { KEY_8, AKEYCODE_8 }, ////8 key
+ { KEY_9, AKEYCODE_9 }, ////9 key
+ { KEY_A, AKEYCODE_A }, ////A key
+ { KEY_B, AKEYCODE_B }, ////B key
+ { KEY_C, AKEYCODE_C }, ////C key
+ { KEY_D, AKEYCODE_D }, ////D key
+ { KEY_E, AKEYCODE_E }, ////E key
+ { KEY_F, AKEYCODE_F }, ////F key
+ { KEY_G, AKEYCODE_G }, ////G key
+ { KEY_H, AKEYCODE_H }, ////H key
+ { KEY_I, AKEYCODE_I }, ////I key
+ { KEY_J, AKEYCODE_J }, ////J key
+ { KEY_K, AKEYCODE_K }, ////K key
+ { KEY_L, AKEYCODE_L }, ////L key
+ { KEY_M, AKEYCODE_M }, ////M key
+ { KEY_N, AKEYCODE_N }, ////N key
+ { KEY_O, AKEYCODE_O }, ////O key
+ { KEY_P, AKEYCODE_P }, ////P key
+ { KEY_Q, AKEYCODE_Q }, ////Q key
+ { KEY_R, AKEYCODE_R }, ////R key
+ { KEY_S, AKEYCODE_S }, ////S key
+ { KEY_T, AKEYCODE_T }, ////T key
+ { KEY_U, AKEYCODE_U }, ////U key
+ { KEY_V, AKEYCODE_V }, ////V key
+ { KEY_W, AKEYCODE_W }, ////W key
+ { KEY_X, AKEYCODE_X }, ////X key
+ { KEY_Y, AKEYCODE_Y }, ////Y key
+ { KEY_Z, AKEYCODE_Z }, ////Z key
+ { KEY_HOMEPAGE, AKEYCODE_EXPLORER },
+ { KEY_LAUNCH0, AKEYCODE_BUTTON_A },
+ { KEY_LAUNCH1, AKEYCODE_BUTTON_B },
+ { KEY_LAUNCH2, AKEYCODE_BUTTON_C },
+ { KEY_LAUNCH3, AKEYCODE_BUTTON_X },
+ { KEY_LAUNCH4, AKEYCODE_BUTTON_Y },
+ { KEY_LAUNCH5, AKEYCODE_BUTTON_Z },
+ { KEY_LAUNCH6, AKEYCODE_BUTTON_L1 },
+ { KEY_LAUNCH7, AKEYCODE_BUTTON_R1 },
+ { KEY_LAUNCH8, AKEYCODE_BUTTON_L2 },
+ { KEY_LAUNCH9, AKEYCODE_BUTTON_R2 },
+ { KEY_LAUNCHA, AKEYCODE_BUTTON_THUMBL },
+ { KEY_LAUNCHB, AKEYCODE_BUTTON_THUMBR },
+ { KEY_LAUNCHC, AKEYCODE_BUTTON_START },
+ { KEY_LAUNCHD, AKEYCODE_BUTTON_SELECT },
+ { KEY_LAUNCHE, AKEYCODE_BUTTON_MODE },
+ { KEY_VOLUMEMUTE, AKEYCODE_MUTE },
+ { KEY_VOLUMEDOWN, AKEYCODE_VOLUME_DOWN },
+ { KEY_VOLUMEUP, AKEYCODE_VOLUME_UP },
+ { KEY_BACK, AKEYCODE_MEDIA_REWIND },
+ { KEY_FORWARD, AKEYCODE_MEDIA_FAST_FORWARD },
+ { KEY_MEDIANEXT, AKEYCODE_MEDIA_NEXT },
+ { KEY_MEDIAPREVIOUS, AKEYCODE_MEDIA_PREVIOUS },
+ { KEY_MEDIASTOP, AKEYCODE_MEDIA_STOP },
+ { KEY_PLUS, AKEYCODE_PLUS },
+ { KEY_EQUAL, AKEYCODE_EQUALS }, // the '+' key
+ { KEY_COMMA, AKEYCODE_COMMA }, // the ',' key
+ { KEY_MINUS, AKEYCODE_MINUS }, // the '-' key
+ { KEY_SLASH, AKEYCODE_SLASH }, // the '/?' key
+ { KEY_BACKSLASH, AKEYCODE_BACKSLASH },
+ { KEY_BRACKETLEFT, AKEYCODE_LEFT_BRACKET },
+ { KEY_BRACKETRIGHT, AKEYCODE_RIGHT_BRACKET },
+ { KEY_UNKNOWN, 0 }
+};
/*
TODO: map these android key:
AKEYCODE_SOFT_LEFT = 1,
@@ -1401,20 +1339,19 @@ TODO: map these android key:
*/
static unsigned int android_get_keysym(unsigned int p_code) {
- for(int i=0;_ak_to_keycode[i].keysym!=KEY_UNKNOWN;i++) {
+ for (int i = 0; _ak_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
- if (_ak_to_keycode[i].keycode==p_code) {
+ if (_ak_to_keycode[i].keycode == p_code) {
//print_line("outcode: " + _ak_to_keycode[i].keysym);
return _ak_to_keycode[i].keysym;
}
}
-
return KEY_UNKNOWN;
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv * env, jobject obj, jint p_device, jint p_button, jboolean p_pressed) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv *env, jobject obj, jint p_device, jint p_button, jboolean p_pressed) {
OS_Android::JoypadEvent jevent;
jevent.device = p_device;
@@ -1427,7 +1364,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv * en
input_mutex->unlock();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv * env, jobject obj, jint p_device, jint p_axis, jfloat p_value) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv *env, jobject obj, jint p_device, jint p_axis, jfloat p_value) {
OS_Android::JoypadEvent jevent;
jevent.device = p_device;
@@ -1440,18 +1377,22 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv * env,
input_mutex->unlock();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv * env, jobject obj, jint p_device, jint p_hat_x, jint p_hat_y) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv *env, jobject obj, jint p_device, jint p_hat_x, jint p_hat_y) {
OS_Android::JoypadEvent jevent;
jevent.device = p_device;
jevent.type = OS_Android::JOY_EVENT_HAT;
int hat = 0;
if (p_hat_x != 0) {
- if (p_hat_x < 0) hat |= InputDefault::HAT_MASK_LEFT;
- else hat |= InputDefault::HAT_MASK_RIGHT;
+ if (p_hat_x < 0)
+ hat |= InputDefault::HAT_MASK_LEFT;
+ else
+ hat |= InputDefault::HAT_MASK_RIGHT;
}
if (p_hat_y != 0) {
- if (p_hat_y < 0) hat |= InputDefault::HAT_MASK_UP;
- else hat |= InputDefault::HAT_MASK_DOWN;
+ if (p_hat_y < 0)
+ hat |= InputDefault::HAT_MASK_UP;
+ else
+ hat |= InputDefault::HAT_MASK_DOWN;
}
jevent.hat = hat;
input_mutex->lock();
@@ -1459,14 +1400,14 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv * env,
input_mutex->unlock();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv * env, jobject obj, jint p_device, jboolean p_connected, jstring p_name) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv *env, jobject obj, jint p_device, jboolean p_connected, jstring p_name) {
if (os_android) {
- String name = env->GetStringUTFChars( p_name, NULL );
+ String name = env->GetStringUTFChars(p_name, NULL);
os_android->joy_connection_changed(p_device, p_connected, name);
}
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv * env, jobject obj, jint p_scancode, jint p_unicode_char, jboolean p_pressed) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv *env, jobject obj, jint p_scancode, jint p_unicode_char, jboolean p_pressed) {
InputEvent ievent;
ievent.type = InputEvent::KEY;
@@ -1479,56 +1420,51 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv * env, job
print_line("Scancode: " + String::num(p_scancode) + ":" + String::num(ievent.key.scancode) + " Unicode: " + String::num(val));
- ievent.key.mod.shift=false;
- ievent.key.mod.alt=false;
- ievent.key.mod.control=false;
- ievent.key.echo=false;
+ ievent.key.mod.shift = false;
+ ievent.key.mod.alt = false;
+ ievent.key.mod.control = false;
+ ievent.key.echo = false;
- if (val == '\n')
- {
+ if (val == '\n') {
ievent.key.scancode = KEY_ENTER;
- }else if (val == 61448) {
+ } else if (val == 61448) {
ievent.key.scancode = KEY_BACKSPACE;
ievent.key.unicode = KEY_BACKSPACE;
} else if (val == 61453) {
ievent.key.scancode = KEY_ENTER;
ievent.key.unicode = KEY_ENTER;
- } else if (p_scancode==4) {
+ } else if (p_scancode == 4) {
- go_back_request=true;
- }
+ go_back_request = true;
+ }
input_mutex->lock();
key_events.push_back(ievent);
input_mutex->unlock();
}
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z) {
input_mutex->lock();
- accelerometer=Vector3(x,y,z);
+ accelerometer = Vector3(x, y, z);
input_mutex->unlock();
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnetometer(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnetometer(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z) {
input_mutex->lock();
- magnetometer=Vector3(x,y,z);
+ magnetometer = Vector3(x, y, z);
input_mutex->unlock();
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z) {
input_mutex->lock();
- gyroscope=Vector3(x,y,z);
+ gyroscope = Vector3(x, y, z);
input_mutex->unlock();
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv * env, jobject obj){
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv *env, jobject obj) {
if (!suspend_mutex)
return;
@@ -1540,7 +1476,7 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv * env,
suspend_mutex->unlock();
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv * env, jobject obj){
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv *env, jobject obj) {
if (!suspend_mutex)
return;
@@ -1550,58 +1486,50 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv * env
os_android->main_loop_focusout();
suspend_mutex->unlock();
-
}
-
-
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_audio(JNIEnv * env, jobject obj) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_audio(JNIEnv *env, jobject obj) {
ThreadAndroid::setup_thread();
AudioDriverAndroid::thread_func(env);
-
-
}
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_singleton(JNIEnv *env, jobject obj, jstring name, jobject p_object) {
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_singleton(JNIEnv * env, jobject obj, jstring name,jobject p_object){
-
- String singname = env->GetStringUTFChars( name, NULL );
- JNISingleton *s = memnew( JNISingleton );
+ String singname = env->GetStringUTFChars(name, NULL);
+ JNISingleton *s = memnew(JNISingleton);
s->set_instance(env->NewGlobalRef(p_object));
- jni_singletons[singname]=s;
-
- GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton(singname,s));
- GlobalConfig::get_singleton()->set(singname,s);
+ jni_singletons[singname] = s;
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton(singname, s));
+ GlobalConfig::get_singleton()->set(singname, s);
}
-
-static Variant::Type get_jni_type(const String& p_type) {
+static Variant::Type get_jni_type(const String &p_type) {
static struct {
const char *name;
Variant::Type type;
- } _type_to_vtype[]={
- {"void",Variant::NIL},
- {"boolean",Variant::BOOL},
- {"int",Variant::INT},
- {"float",Variant::REAL},
- {"double", Variant::REAL},
- {"java.lang.String",Variant::STRING},
- {"[I",Variant::POOL_INT_ARRAY},
- {"[B",Variant::POOL_BYTE_ARRAY},
- {"[F",Variant::POOL_REAL_ARRAY},
- {"[Ljava.lang.String;",Variant::POOL_STRING_ARRAY},
- {"org.godotengine.godot.Dictionary", Variant::DICTIONARY},
- {NULL,Variant::NIL}
+ } _type_to_vtype[] = {
+ { "void", Variant::NIL },
+ { "boolean", Variant::BOOL },
+ { "int", Variant::INT },
+ { "float", Variant::REAL },
+ { "double", Variant::REAL },
+ { "java.lang.String", Variant::STRING },
+ { "[I", Variant::POOL_INT_ARRAY },
+ { "[B", Variant::POOL_BYTE_ARRAY },
+ { "[F", Variant::POOL_REAL_ARRAY },
+ { "[Ljava.lang.String;", Variant::POOL_STRING_ARRAY },
+ { "org.godotengine.godot.Dictionary", Variant::DICTIONARY },
+ { NULL, Variant::NIL }
};
- int idx=0;
+ int idx = 0;
while (_type_to_vtype[idx].name) {
- if (p_type==_type_to_vtype[idx].name)
+ if (p_type == _type_to_vtype[idx].name)
return _type_to_vtype[idx].type;
idx++;
@@ -1610,145 +1538,131 @@ static Variant::Type get_jni_type(const String& p_type) {
return Variant::NIL;
}
-
-static const char* get_jni_sig(const String& p_type) {
-
+static const char *get_jni_sig(const String &p_type) {
static struct {
const char *name;
const char *sig;
- } _type_to_vtype[]={
- {"void","V"},
- {"boolean","Z"},
- {"int","I"},
- {"float","F"},
- {"double","D"},
- {"java.lang.String","Ljava/lang/String;"},
- {"org.godotengine.godot.Dictionary", "Lorg/godotengine/godot/Dictionary;"},
- {"[I","[I"},
- {"[B","[B"},
- {"[F","[F"},
- {"[Ljava.lang.String;","[Ljava/lang/String;"},
- {NULL,"V"}
+ } _type_to_vtype[] = {
+ { "void", "V" },
+ { "boolean", "Z" },
+ { "int", "I" },
+ { "float", "F" },
+ { "double", "D" },
+ { "java.lang.String", "Ljava/lang/String;" },
+ { "org.godotengine.godot.Dictionary", "Lorg/godotengine/godot/Dictionary;" },
+ { "[I", "[I" },
+ { "[B", "[B" },
+ { "[F", "[F" },
+ { "[Ljava.lang.String;", "[Ljava/lang/String;" },
+ { NULL, "V" }
};
- int idx=0;
+ int idx = 0;
while (_type_to_vtype[idx].name) {
- if (p_type==_type_to_vtype[idx].name)
+ if (p_type == _type_to_vtype[idx].name)
return _type_to_vtype[idx].sig;
idx++;
}
-
return "Ljava/lang/Object;";
}
-JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv * env, jobject obj, jstring path) {
+JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv *env, jobject obj, jstring path) {
- String js = env->GetStringUTFChars( path, NULL );
+ String js = env->GetStringUTFChars(path, NULL);
return env->NewStringUTF(GlobalConfig::get_singleton()->get(js).operator String().utf8().get_data());
-
-
}
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_method(JNIEnv *env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args) {
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_method(JNIEnv * env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args){
-
- String singname = env->GetStringUTFChars( sname, NULL );
+ String singname = env->GetStringUTFChars(sname, NULL);
ERR_FAIL_COND(!jni_singletons.has(singname));
JNISingleton *s = jni_singletons.get(singname);
-
- String mname = env->GetStringUTFChars( name, NULL );
- String retval = env->GetStringUTFChars( ret, NULL );
+ String mname = env->GetStringUTFChars(name, NULL);
+ String retval = env->GetStringUTFChars(ret, NULL);
Vector<Variant::Type> types;
- String cs="(";
-
+ String cs = "(";
int stringCount = env->GetArrayLength(args);
- print_line("Singl: "+singname+" Method: "+mname+" RetVal: "+retval);
- for (int i=0; i<stringCount; i++) {
+ print_line("Singl: " + singname + " Method: " + mname + " RetVal: " + retval);
+ for (int i = 0; i < stringCount; i++) {
- jstring string = (jstring) env->GetObjectArrayElement(args, i);
+ jstring string = (jstring)env->GetObjectArrayElement(args, i);
const char *rawString = env->GetStringUTFChars(string, 0);
types.push_back(get_jni_type(String(rawString)));
- cs+=get_jni_sig(String(rawString));
+ cs += get_jni_sig(String(rawString));
}
- cs+=")";
- cs+=get_jni_sig(retval);
+ cs += ")";
+ cs += get_jni_sig(retval);
jclass cls = env->GetObjectClass(s->get_instance());
- print_line("METHOD: "+mname+" sig: "+cs);
+ print_line("METHOD: " + mname + " sig: " + cs);
jmethodID mid = env->GetMethodID(cls, mname.ascii().get_data(), cs.ascii().get_data());
if (!mid) {
- print_line("FAILED GETTING METHOID "+mname);
+ print_line("FAILED GETTING METHOID " + mname);
}
- s->add_method(mname,mid,types,get_jni_type(retval));
-
-
+ s->add_method(mname, mid, types, get_jni_type(retval));
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv * env, jobject p_obj, jint ID, jstring method, jobjectArray params) {
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jobject p_obj, jint ID, jstring method, jobjectArray params) {
- Object* obj = ObjectDB::get_instance(ID);
+ Object *obj = ObjectDB::get_instance(ID);
ERR_FAIL_COND(!obj);
int res = env->PushLocalFrame(16);
- ERR_FAIL_COND(res!=0);
-
- String str_method = env->GetStringUTFChars( method, NULL );
+ ERR_FAIL_COND(res != 0);
+ String str_method = env->GetStringUTFChars(method, NULL);
int count = env->GetArrayLength(params);
- Variant* vlist = (Variant*)alloca(sizeof(Variant) * count);
- Variant** vptr = (Variant**)alloca(sizeof(Variant*) * count);
- for (int i=0; i<count; i++) {
+ Variant *vlist = (Variant *)alloca(sizeof(Variant) * count);
+ Variant **vptr = (Variant **)alloca(sizeof(Variant *) * count);
+ for (int i = 0; i < count; i++) {
jobject obj = env->GetObjectArrayElement(params, i);
Variant v;
if (obj)
- v=_jobject_to_variant(env, obj);
+ v = _jobject_to_variant(env, obj);
memnew_placement(&vlist[i], Variant);
vlist[i] = v;
vptr[i] = &vlist[i];
env->DeleteLocalRef(obj);
-
};
Variant::CallError err;
- obj->call(str_method, (const Variant**)vptr, count, err);
+ obj->call(str_method, (const Variant **)vptr, count, err);
// something
env->PopLocalFrame(NULL);
-
}
-JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv * env, jobject p_obj, jint ID, jstring method, jobjectArray params) {
-
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jobject p_obj, jint ID, jstring method, jobjectArray params) {
- Object* obj = ObjectDB::get_instance(ID);
+ Object *obj = ObjectDB::get_instance(ID);
ERR_FAIL_COND(!obj);
int res = env->PushLocalFrame(16);
- ERR_FAIL_COND(res!=0);
+ ERR_FAIL_COND(res != 0);
- String str_method = env->GetStringUTFChars( method, NULL );
+ String str_method = env->GetStringUTFChars(method, NULL);
int count = env->GetArrayLength(params);
Variant args[VARIANT_ARG_MAX];
- //print_line("Java->GD call: "+obj->get_type()+"::"+str_method+" argc "+itos(count));
+ //print_line("Java->GD call: "+obj->get_type()+"::"+str_method+" argc "+itos(count));
- for (int i=0; i<MIN(count,VARIANT_ARG_MAX); i++) {
+ for (int i = 0; i < MIN(count, VARIANT_ARG_MAX); i++) {
jobject obj = env->GetObjectArrayElement(params, i);
if (obj)
@@ -1756,15 +1670,11 @@ JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *
env->DeleteLocalRef(obj);
//print_line("\targ"+itos(i)+": "+Variant::get_type_name(args[i].get_type()));
-
};
-
-
- obj->call_deferred(str_method, args[0],args[1],args[2],args[3],args[4]);
+ obj->call_deferred(str_method, args[0], args[1], args[2], args[3], args[4]);
// something
env->PopLocalFrame(NULL);
-
}
//Main::cleanup();
diff --git a/platform/android/java_glue.h b/platform/android/java_glue.h
index bc4628b9d4..51a2031867 100644
--- a/platform/android/java_glue.h
+++ b/platform/android/java_glue.h
@@ -31,35 +31,33 @@
#ifndef JAVA_GLUE_H
#define JAVA_GLUE_H
-#include <jni.h>
#include <android/log.h>
-
+#include <jni.h>
extern "C" {
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv * env, jobject obj, jobject activity,jboolean p_need_reload_hook, jobjectArray p_cmdline,jobject p_asset_manager);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv * env, jobject obj, jint width, jint height, jboolean reload);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv * env, jobject obj, bool p_32_bits);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv * env, jobject obj);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_quit(JNIEnv * env, jobject obj);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv * env, jobject obj, jint ev,jint pointer, jint count, jintArray positions);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv * env, jobject obj, jint p_scancode, jint p_unicode_char, jboolean p_pressed);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv * env, jobject obj, jint p_device, jint p_button, jboolean p_pressed);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv * env, jobject obj, jint p_device, jint p_axis, jfloat p_value);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv * env, jobject obj, jint p_device, jint p_hat_x, jint p_hat_y);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv * env, jobject obj, jint p_device, jboolean p_connected, jstring p_name);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_audio(JNIEnv * env, jobject obj);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnetometer(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv * env, jobject obj, jfloat x, jfloat y, jfloat z);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv * env, jobject obj);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv * env, jobject obj);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_singleton(JNIEnv * env, jobject obj, jstring name,jobject p_object);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_method(JNIEnv * env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args);
- JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv * env, jobject obj, jstring path);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv * env, jobject obj, jint ID, jstring method, jobjectArray params);
- JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv * env, jobject obj, jint ID, jstring method, jobjectArray params);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_initialize(JNIEnv *env, jobject obj, jobject activity, jboolean p_need_reload_hook, jobjectArray p_cmdline, jobject p_asset_manager);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_resize(JNIEnv *env, jobject obj, jint width, jint height, jboolean reload);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_newcontext(JNIEnv *env, jobject obj, bool p_32_bits);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_step(JNIEnv *env, jobject obj);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_quit(JNIEnv *env, jobject obj);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_touch(JNIEnv *env, jobject obj, jint ev, jint pointer, jint count, jintArray positions);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_key(JNIEnv *env, jobject obj, jint p_scancode, jint p_unicode_char, jboolean p_pressed);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joybutton(JNIEnv *env, jobject obj, jint p_device, jint p_button, jboolean p_pressed);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyaxis(JNIEnv *env, jobject obj, jint p_device, jint p_axis, jfloat p_value);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyhat(JNIEnv *env, jobject obj, jint p_device, jint p_hat_x, jint p_hat_y);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_joyconnectionchanged(JNIEnv *env, jobject obj, jint p_device, jboolean p_connected, jstring p_name);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_audio(JNIEnv *env, jobject obj);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_accelerometer(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_magnetometer(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_gyroscope(JNIEnv *env, jobject obj, jfloat x, jfloat y, jfloat z);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusin(JNIEnv *env, jobject obj);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_focusout(JNIEnv *env, jobject obj);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_singleton(JNIEnv *env, jobject obj, jstring name, jobject p_object);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_method(JNIEnv *env, jobject obj, jstring sname, jstring name, jstring ret, jobjectArray args);
+JNIEXPORT jstring JNICALL Java_org_godotengine_godot_GodotLib_getGlobal(JNIEnv *env, jobject obj, jstring path);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_callobject(JNIEnv *env, jobject obj, jint ID, jstring method, jobjectArray params);
+JNIEXPORT void JNICALL Java_org_godotengine_godot_GodotLib_calldeferred(JNIEnv *env, jobject obj, jint ID, jstring method, jobjectArray params);
}
-
#endif
#endif // JAVA_GLUE_H
diff --git a/platform/android/os_android.cpp b/platform/android/os_android.cpp
index a10f27424c..60719f6d42 100644
--- a/platform/android/os_android.cpp
+++ b/platform/android/os_android.cpp
@@ -28,22 +28,22 @@
/*************************************************************************/
#include "os_android.h"
-#include "drivers/gles2/rasterizer_gles2.h"
+#include "core/global_config.h"
#include "core/io/file_access_buffered_fa.h"
-#include "drivers/unix/file_access_unix.h"
+#include "drivers/gles2/rasterizer_gles2.h"
#include "drivers/unix/dir_access_unix.h"
+#include "drivers/unix/file_access_unix.h"
+#include "file_access_android.h"
+#include "main/main.h"
#include "servers/visual/visual_server_raster.h"
#include "servers/visual/visual_server_wrap_mt.h"
-#include "main/main.h"
-#include "file_access_android.h"
-#include "core/global_config.h"
#ifdef ANDROID_NATIVE_ACTIVITY
-#include "file_access_android.h"
#include "dir_access_android.h"
+#include "file_access_android.h"
#else
-#include "file_access_jandroid.h"
#include "dir_access_jandroid.h"
+#include "file_access_jandroid.h"
#endif
int OS_Android::get_video_driver_count() const {
@@ -51,7 +51,7 @@ int OS_Android::get_video_driver_count() const {
return 1;
}
-const char * OS_Android::get_video_driver_name(int p_driver) const {
+const char *OS_Android::get_video_driver_name(int p_driver) const {
return "GLES2";
}
@@ -66,7 +66,7 @@ int OS_Android::get_audio_driver_count() const {
return 1;
}
-const char * OS_Android::get_audio_driver_name(int p_driver) const {
+const char *OS_Android::get_audio_driver_name(int p_driver) const {
return "Android";
}
@@ -108,35 +108,31 @@ void OS_Android::initialize_core() {
DirAccess::make_default<DirAccessUnix>(DirAccess::ACCESS_FILESYSTEM);
#endif
-
}
-void OS_Android::set_opengl_extensions(const char* p_gl_extensions) {
+void OS_Android::set_opengl_extensions(const char *p_gl_extensions) {
ERR_FAIL_COND(!p_gl_extensions);
- gl_extensions=p_gl_extensions;
+ gl_extensions = p_gl_extensions;
}
-void OS_Android::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
-
-
- use_gl2=p_video_driver!=1;
+void OS_Android::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
+ use_gl2 = p_video_driver != 1;
if (gfx_init_func)
- gfx_init_func(gfx_init_ud,use_gl2);
+ gfx_init_func(gfx_init_ud, use_gl2);
AudioDriverManager::add_driver(&audio_driver_android);
-
- RasterizerGLES2 *rasterizer_gles22=memnew( RasterizerGLES2(false,use_reload_hooks,false,use_reload_hooks ) );
+ RasterizerGLES2 *rasterizer_gles22 = memnew(RasterizerGLES2(false, use_reload_hooks, false, use_reload_hooks));
if (gl_extensions)
rasterizer_gles22->set_extensions(gl_extensions);
rasterizer = rasterizer_gles22;
rasterizer->set_force_16_bits_fbo(use_16bits_fbo);
- visual_server = memnew( VisualServerRaster(rasterizer) );
+ visual_server = memnew(VisualServerRaster(rasterizer));
if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
visual_server = memnew(VisualServerWrapMT(visual_server, false));
@@ -146,26 +142,26 @@ void OS_Android::initialize(const VideoMode& p_desired,int p_video_driver,int p_
AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
- if (AudioDriverManager::get_driver(p_audio_driver)->init()!=OK) {
+ if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
ERR_PRINT("Initializing audio failed.");
}
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
//physics_2d_server = memnew( Physics2DServerSW );
physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
physics_2d_server->init();
- input = memnew( InputDefault );
+ input = memnew(InputDefault);
input->set_fallback_mapping("Default Android Gamepad");
-
- power_manager = memnew( power_android );
+
+ power_manager = memnew(power_android);
}
-void OS_Android::set_main_loop( MainLoop * p_main_loop ) {
+void OS_Android::set_main_loop(MainLoop *p_main_loop) {
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
input->set_main_loop(p_main_loop);
#if 0
@@ -204,12 +200,11 @@ void OS_Android::set_main_loop( MainLoop * p_main_loop ) {
}
#endif
-
}
void OS_Android::delete_main_loop() {
- memdelete( main_loop );
+ memdelete(main_loop);
}
void OS_Android::finalize() {
@@ -217,29 +212,26 @@ void OS_Android::finalize() {
memdelete(input);
}
+void OS_Android::vprint(const char *p_format, va_list p_list, bool p_stderr) {
-void OS_Android::vprint(const char* p_format, va_list p_list, bool p_stderr) {
-
- __android_log_vprint(p_stderr?ANDROID_LOG_ERROR:ANDROID_LOG_INFO,"godot",p_format,p_list);
+ __android_log_vprint(p_stderr ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "godot", p_format, p_list);
}
-void OS_Android::print(const char *p_format, ... ) {
+void OS_Android::print(const char *p_format, ...) {
va_list argp;
va_start(argp, p_format);
- __android_log_vprint(ANDROID_LOG_INFO,"godot",p_format,argp);
+ __android_log_vprint(ANDROID_LOG_INFO, "godot", p_format, argp);
va_end(argp);
-
}
-void OS_Android::alert(const String& p_alert,const String& p_title) {
+void OS_Android::alert(const String &p_alert, const String &p_title) {
- print("ALERT: %s\n",p_alert.utf8().get_data());
+ print("ALERT: %s\n", p_alert.utf8().get_data());
if (alert_func)
alert_func(p_alert, p_title);
}
-
void OS_Android::set_mouse_show(bool p_show) {
//android has no mouse...
@@ -265,16 +257,14 @@ int OS_Android::get_mouse_button_state() const {
return 0;
}
-void OS_Android::set_window_title(const String& p_title) {
-
+void OS_Android::set_window_title(const String &p_title) {
}
//interesting byt not yet
//void set_clipboard(const String& p_text);
//String get_clipboard() const;
-void OS_Android::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
-
+void OS_Android::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
}
OS::VideoMode OS_Android::get_video_mode(int p_screen) const {
@@ -282,7 +272,7 @@ OS::VideoMode OS_Android::get_video_mode(int p_screen) const {
return default_videomode;
}
-void OS_Android::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
+void OS_Android::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
p_list->push_back(default_videomode);
}
@@ -297,7 +287,7 @@ void OS_Android::set_keep_screen_on(bool p_enabled) {
Size2 OS_Android::get_window_size() const {
- return Vector2(default_videomode.width,default_videomode.height);
+ return Vector2(default_videomode.width, default_videomode.height);
}
String OS_Android::get_name() {
@@ -337,7 +327,6 @@ void OS_Android::main_loop_end() {
if (main_loop)
main_loop->finish();
-
}
void OS_Android::main_loop_focusout() {
@@ -345,34 +334,32 @@ void OS_Android::main_loop_focusout() {
if (main_loop)
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
audio_driver_android.set_pause(true);
-
}
-void OS_Android::main_loop_focusin(){
+void OS_Android::main_loop_focusin() {
if (main_loop)
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
audio_driver_android.set_pause(false);
-
}
void OS_Android::process_joy_event(OS_Android::JoypadEvent p_event) {
switch (p_event.type) {
- case JOY_EVENT_BUTTON:
- last_id = input->joy_button(last_id, p_event.device, p_event.index, p_event.pressed);
- break;
- case JOY_EVENT_AXIS:
- InputDefault::JoyAxis value;
- value.min = -1;
- value.value = p_event.value;
- last_id = input->joy_axis(last_id, p_event.device, p_event.index, value);
- break;
- case JOY_EVENT_HAT:
- last_id = input->joy_hat(last_id, p_event.device, p_event.hat);
- break;
- default:
- return;
+ case JOY_EVENT_BUTTON:
+ last_id = input->joy_button(last_id, p_event.device, p_event.index, p_event.pressed);
+ break;
+ case JOY_EVENT_AXIS:
+ InputDefault::JoyAxis value;
+ value.min = -1;
+ value.value = p_event.value;
+ last_id = input->joy_axis(last_id, p_event.device, p_event.index, value);
+ break;
+ case JOY_EVENT_HAT:
+ last_id = input->joy_hat(last_id, p_event.device, p_event.hat);
+ break;
+ default:
+ return;
}
}
@@ -382,163 +369,152 @@ void OS_Android::process_event(InputEvent p_event) {
input->parse_input_event(p_event);
}
-
-void OS_Android::process_touch(int p_what,int p_pointer, const Vector<TouchPos>& p_points) {
+void OS_Android::process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points) {
//print_line("ev: "+itos(p_what)+" pnt: "+itos(p_pointer)+" pointc: "+itos(p_points.size()));
- switch(p_what) {
+ switch (p_what) {
case 0: { //gesture begin
if (touch.size()) {
//end all if exist
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=false;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = false;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
input->parse_input_event(ev);
-
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
-
}
}
touch.resize(p_points.size());
- for(int i=0;i<p_points.size();i++) {
- touch[i].id=p_points[i].id;
- touch[i].pos=p_points[i].pos;
+ for (int i = 0; i < p_points.size(); i++) {
+ touch[i].id = p_points[i].id;
+ touch[i].pos = p_points[i].pos;
}
{
//send mouse
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=true;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
- last_mouse=touch[0].pos;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = true;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
+ last_mouse = touch[0].pos;
input->parse_input_event(ev);
}
-
//send touch
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=true;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = true;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
}
} break;
case 1: { //motion
-
if (p_points.size()) {
//send mouse, should look for point 0?
InputEvent ev;
- ev.type=InputEvent::MOUSE_MOTION;
- ev.ID=last_id++;
- ev.mouse_motion.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_motion.x=p_points[0].pos.x;
- ev.mouse_motion.y=p_points[0].pos.y;
- input->set_mouse_pos(Point2(ev.mouse_motion.x,ev.mouse_motion.y));
- ev.mouse_motion.speed_x=input->get_last_mouse_speed().x;
- ev.mouse_motion.speed_y=input->get_last_mouse_speed().y;
- ev.mouse_motion.relative_x=p_points[0].pos.x-last_mouse.x;
- ev.mouse_motion.relative_y=p_points[0].pos.y-last_mouse.y;
- last_mouse=p_points[0].pos;
+ ev.type = InputEvent::MOUSE_MOTION;
+ ev.ID = last_id++;
+ ev.mouse_motion.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_motion.x = p_points[0].pos.x;
+ ev.mouse_motion.y = p_points[0].pos.y;
+ input->set_mouse_pos(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
+ ev.mouse_motion.speed_x = input->get_last_mouse_speed().x;
+ ev.mouse_motion.speed_y = input->get_last_mouse_speed().y;
+ ev.mouse_motion.relative_x = p_points[0].pos.x - last_mouse.x;
+ ev.mouse_motion.relative_y = p_points[0].pos.y - last_mouse.y;
+ last_mouse = p_points[0].pos;
input->parse_input_event(ev);
}
- ERR_FAIL_COND(touch.size()!=p_points.size());
+ ERR_FAIL_COND(touch.size() != p_points.size());
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
- int idx=-1;
- for(int j=0;j<p_points.size();j++) {
+ int idx = -1;
+ for (int j = 0; j < p_points.size(); j++) {
- if (touch[i].id==p_points[j].id) {
- idx=j;
+ if (touch[i].id == p_points[j].id) {
+ idx = j;
break;
}
-
}
- ERR_CONTINUE(idx==-1);
+ ERR_CONTINUE(idx == -1);
- if (touch[i].pos==p_points[idx].pos)
+ if (touch[i].pos == p_points[idx].pos)
continue; //no move unncesearily
InputEvent ev;
- ev.type=InputEvent::SCREEN_DRAG;
- ev.ID=last_id++;
- ev.screen_drag.index=touch[i].id;
- ev.screen_drag.x=p_points[idx].pos.x;
- ev.screen_drag.y=p_points[idx].pos.y;
- ev.screen_drag.relative_x=p_points[idx].pos.x - touch[i].pos.x;
- ev.screen_drag.relative_y=p_points[idx].pos.y - touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_DRAG;
+ ev.ID = last_id++;
+ ev.screen_drag.index = touch[i].id;
+ ev.screen_drag.x = p_points[idx].pos.x;
+ ev.screen_drag.y = p_points[idx].pos.y;
+ ev.screen_drag.relative_x = p_points[idx].pos.x - touch[i].pos.x;
+ ev.screen_drag.relative_y = p_points[idx].pos.y - touch[i].pos.y;
input->parse_input_event(ev);
- touch[i].pos=p_points[idx].pos;
+ touch[i].pos = p_points[idx].pos;
}
-
} break;
case 2: { //release
-
-
if (touch.size()) {
//end all if exist
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=false;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = false;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
input->parse_input_event(ev);
-
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
-
}
touch.clear();
}
@@ -546,38 +522,33 @@ void OS_Android::process_touch(int p_what,int p_pointer, const Vector<TouchPos>&
} break;
case 3: { // add tuchi
+ ERR_FAIL_INDEX(p_pointer, p_points.size());
-
-
-
- ERR_FAIL_INDEX(p_pointer,p_points.size());
-
- TouchPos tp=p_points[p_pointer];
+ TouchPos tp = p_points[p_pointer];
touch.push_back(tp);
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=tp.id;
- ev.screen_touch.pressed=true;
- ev.screen_touch.x=tp.pos.x;
- ev.screen_touch.y=tp.pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = tp.id;
+ ev.screen_touch.pressed = true;
+ ev.screen_touch.x = tp.pos.x;
+ ev.screen_touch.y = tp.pos.y;
input->parse_input_event(ev);
} break;
case 4: {
-
- for(int i=0;i<touch.size();i++) {
- if (touch[i].id==p_pointer) {
+ for (int i = 0; i < touch.size(); i++) {
+ if (touch[i].id == p_pointer) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
touch.remove(i);
i--;
@@ -585,22 +556,20 @@ void OS_Android::process_touch(int p_what,int p_pointer, const Vector<TouchPos>&
}
} break;
-
}
-
}
-void OS_Android::process_accelerometer(const Vector3& p_accelerometer) {
+void OS_Android::process_accelerometer(const Vector3 &p_accelerometer) {
input->set_accelerometer(p_accelerometer);
}
-void OS_Android::process_magnetometer(const Vector3& p_magnetometer) {
+void OS_Android::process_magnetometer(const Vector3 &p_magnetometer) {
input->set_magnetometer(p_magnetometer);
}
-void OS_Android::process_gyroscope(const Vector3& p_gyroscope) {
+void OS_Android::process_gyroscope(const Vector3 &p_gyroscope) {
input->set_gyroscope(p_gyroscope);
}
@@ -615,7 +584,7 @@ bool OS_Android::has_virtual_keyboard() const {
return true;
}
-void OS_Android::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) {
+void OS_Android::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
if (show_virtual_keyboard_func) {
show_virtual_keyboard_func(p_existing_text);
@@ -636,13 +605,12 @@ void OS_Android::hide_virtual_keyboard() {
};
}
+void OS_Android::init_video_mode(int p_video_width, int p_video_height) {
-void OS_Android::init_video_mode(int p_video_width,int p_video_height) {
-
- default_videomode.width=p_video_width;
- default_videomode.height=p_video_height;
- default_videomode.fullscreen=true;
- default_videomode.resizable=false;
+ default_videomode.width = p_video_width;
+ default_videomode.height = p_video_height;
+ default_videomode.fullscreen = true;
+ default_videomode.resizable = false;
}
void OS_Android::main_loop_request_go_back() {
@@ -653,14 +621,14 @@ void OS_Android::main_loop_request_go_back() {
void OS_Android::set_display_size(Size2 p_size) {
- default_videomode.width=p_size.x;
- default_videomode.height=p_size.y;
+ default_videomode.width = p_size.x;
+ default_videomode.height = p_size.y;
}
void OS_Android::reload_gfx() {
if (gfx_init_func)
- gfx_init_func(gfx_init_ud,use_gl2);
+ gfx_init_func(gfx_init_ud, use_gl2);
if (rasterizer)
rasterizer->reload_vram();
}
@@ -668,7 +636,7 @@ void OS_Android::reload_gfx() {
Error OS_Android::shell_open(String p_uri) {
if (open_uri_func)
- return open_uri_func(p_uri)?ERR_CANT_OPEN:OK;
+ return open_uri_func(p_uri) ? ERR_CANT_OPEN : OK;
return ERR_UNAVAILABLE;
}
@@ -686,9 +654,9 @@ String OS_Android::get_locale() const {
String OS_Android::get_model_name() const {
- if (get_model_func)
- return get_model_func();
- return OS_Unix::get_model_name();
+ if (get_model_func)
+ return get_model_func();
+ return OS_Unix::get_model_name();
}
int OS_Android::get_screen_dpi(int p_screen) const {
@@ -701,27 +669,27 @@ int OS_Android::get_screen_dpi(int p_screen) const {
void OS_Android::set_need_reload_hooks(bool p_needs_them) {
- use_reload_hooks=p_needs_them;
+ use_reload_hooks = p_needs_them;
}
String OS_Android::get_data_dir() const {
- if (data_dir_cache!=String())
+ if (data_dir_cache != String())
return data_dir_cache;
if (get_data_dir_func) {
- String data_dir=get_data_dir_func();
+ String data_dir = get_data_dir_func();
//store current dir
char real_current_dir_name[2048];
- getcwd(real_current_dir_name,2048);
+ getcwd(real_current_dir_name, 2048);
//go to data dir
chdir(data_dir.utf8().get_data());
//get actual data dir, so we resolve potential symlink (Android 6.0+ seems to use symlink)
char data_current_dir_name[2048];
- getcwd(data_current_dir_name,2048);
+ getcwd(data_current_dir_name, 2048);
//cache by parsing utf8
data_dir_cache.parse_utf8(data_current_dir_name);
@@ -732,19 +700,16 @@ String OS_Android::get_data_dir() const {
return data_dir_cache;
}
-
return ".";
//return GlobalConfig::get_singleton()->get_singleton_object("GodotOS")->call("get_data_dir");
}
-
void OS_Android::set_screen_orientation(ScreenOrientation p_orientation) {
if (set_screen_orientation_func)
set_screen_orientation_func(p_orientation);
}
-
String OS_Android::get_unique_ID() const {
if (get_unique_id_func)
@@ -755,13 +720,13 @@ String OS_Android::get_unique_ID() const {
Error OS_Android::native_video_play(String p_path, float p_volume) {
if (video_play_func)
video_play_func(p_path);
- return OK;
+ return OK;
}
bool OS_Android::native_video_is_playing() {
if (video_is_playing_func)
return video_is_playing_func();
- return false;
+ return false;
}
void OS_Android::native_video_pause() {
@@ -783,7 +748,7 @@ void OS_Android::native_video_stop() {
void OS_Android::set_context_is_16_bits(bool p_is_16) {
- use_16bits_fbo=p_is_16;
+ use_16bits_fbo = p_is_16;
if (rasterizer)
rasterizer->set_force_16_bits_fbo(p_is_16);
}
@@ -800,29 +765,29 @@ String OS_Android::get_joy_guid(int p_device) const {
return input->get_joy_guid_remapped(p_device);
}
-OS_Android::OS_Android(GFXInitFunc p_gfx_init_func,void*p_gfx_init_ud, OpenURIFunc p_open_uri_func, GetDataDirFunc p_get_data_dir_func,GetLocaleFunc p_get_locale_func,GetModelFunc p_get_model_func, GetScreenDPIFunc p_get_screen_dpi_func, ShowVirtualKeyboardFunc p_show_vk, HideVirtualKeyboardFunc p_hide_vk, SetScreenOrientationFunc p_screen_orient,GetUniqueIDFunc p_get_unique_id,GetSystemDirFunc p_get_sdir_func, VideoPlayFunc p_video_play_func, VideoIsPlayingFunc p_video_is_playing_func, VideoPauseFunc p_video_pause_func, VideoStopFunc p_video_stop_func, SetKeepScreenOnFunc p_set_keep_screen_on_func, AlertFunc p_alert_func, bool p_use_apk_expansion) {
+OS_Android::OS_Android(GFXInitFunc p_gfx_init_func, void *p_gfx_init_ud, OpenURIFunc p_open_uri_func, GetDataDirFunc p_get_data_dir_func, GetLocaleFunc p_get_locale_func, GetModelFunc p_get_model_func, GetScreenDPIFunc p_get_screen_dpi_func, ShowVirtualKeyboardFunc p_show_vk, HideVirtualKeyboardFunc p_hide_vk, SetScreenOrientationFunc p_screen_orient, GetUniqueIDFunc p_get_unique_id, GetSystemDirFunc p_get_sdir_func, VideoPlayFunc p_video_play_func, VideoIsPlayingFunc p_video_is_playing_func, VideoPauseFunc p_video_pause_func, VideoStopFunc p_video_stop_func, SetKeepScreenOnFunc p_set_keep_screen_on_func, AlertFunc p_alert_func, bool p_use_apk_expansion) {
- use_apk_expansion=p_use_apk_expansion;
- default_videomode.width=800;
- default_videomode.height=600;
- default_videomode.fullscreen=true;
- default_videomode.resizable=false;
+ use_apk_expansion = p_use_apk_expansion;
+ default_videomode.width = 800;
+ default_videomode.height = 600;
+ default_videomode.fullscreen = true;
+ default_videomode.resizable = false;
- gfx_init_func=p_gfx_init_func;
- gfx_init_ud=p_gfx_init_ud;
- main_loop=NULL;
- last_id=1;
- gl_extensions=NULL;
- rasterizer=NULL;
- use_gl2=false;
+ gfx_init_func = p_gfx_init_func;
+ gfx_init_ud = p_gfx_init_ud;
+ main_loop = NULL;
+ last_id = 1;
+ gl_extensions = NULL;
+ rasterizer = NULL;
+ use_gl2 = false;
- open_uri_func=p_open_uri_func;
- get_data_dir_func=p_get_data_dir_func;
- get_locale_func=p_get_locale_func;
- get_model_func=p_get_model_func;
+ open_uri_func = p_open_uri_func;
+ get_data_dir_func = p_get_data_dir_func;
+ get_locale_func = p_get_locale_func;
+ get_model_func = p_get_model_func;
get_screen_dpi_func = p_get_screen_dpi_func;
- get_unique_id_func=p_get_unique_id;
- get_system_dir_func=p_get_sdir_func;
+ get_unique_id_func = p_get_unique_id;
+ get_system_dir_func = p_get_sdir_func;
video_play_func = p_video_play_func;
video_is_playing_func = p_video_is_playing_func;
@@ -832,13 +797,11 @@ OS_Android::OS_Android(GFXInitFunc p_gfx_init_func,void*p_gfx_init_ud, OpenURIFu
show_virtual_keyboard_func = p_show_vk;
hide_virtual_keyboard_func = p_hide_vk;
- set_screen_orientation_func=p_screen_orient;
+ set_screen_orientation_func = p_screen_orient;
set_keep_screen_on_func = p_set_keep_screen_on_func;
alert_func = p_alert_func;
- use_reload_hooks=false;
-
+ use_reload_hooks = false;
}
OS_Android::~OS_Android() {
-
}
diff --git a/platform/android/os_android.h b/platform/android/os_android.h
index ead3969744..2c0be8e3c1 100644
--- a/platform/android/os_android.h
+++ b/platform/android/os_android.h
@@ -29,47 +29,46 @@
#ifndef OS_ANDROID_H
#define OS_ANDROID_H
-#include "os/input.h"
+#include "audio_driver_jandroid.h"
+#include "audio_driver_opensl.h"
#include "drivers/unix/os_unix.h"
+#include "main/input_default.h"
+#include "os/input.h"
#include "os/main_loop.h"
#include "power_android.h"
-#include "servers/physics/physics_server_sw.h"
#include "servers/audio_server.h"
+#include "servers/physics/physics_server_sw.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
#include "servers/visual/rasterizer.h"
-#include "main/input_default.h"
-#include "audio_driver_jandroid.h"
-#include "audio_driver_opensl.h"
#ifdef ANDROID_NATIVE_ACTIVITY
-#include <android/sensor.h>
#include <android/log.h>
+#include <android/sensor.h>
#include <android_native_app_glue.h>
#endif
-typedef void (*GFXInitFunc)(void *ud,bool gl2);
-typedef int (*OpenURIFunc)(const String&);
+typedef void (*GFXInitFunc)(void *ud, bool gl2);
+typedef int (*OpenURIFunc)(const String &);
typedef String (*GetDataDirFunc)();
typedef String (*GetLocaleFunc)();
typedef String (*GetModelFunc)();
typedef int (*GetScreenDPIFunc)();
typedef String (*GetUniqueIDFunc)();
-typedef void (*ShowVirtualKeyboardFunc)(const String&);
+typedef void (*ShowVirtualKeyboardFunc)(const String &);
typedef void (*HideVirtualKeyboardFunc)();
typedef void (*SetScreenOrientationFunc)(int);
typedef String (*GetSystemDirFunc)(int);
-typedef void (*VideoPlayFunc)(const String&);
+typedef void (*VideoPlayFunc)(const String &);
typedef bool (*VideoIsPlayingFunc)();
typedef void (*VideoPauseFunc)();
typedef void (*VideoStopFunc)();
typedef void (*SetKeepScreenOnFunc)(bool p_enabled);
-typedef void (*AlertFunc)(const String&, const String&);
+typedef void (*AlertFunc)(const String &, const String &);
class OS_Android : public OS_Unix {
public:
-
struct TouchPos {
int id;
Point2 pos;
@@ -92,13 +91,12 @@ public:
};
private:
-
Vector<TouchPos> touch;
Point2 last_mouse;
unsigned int last_id;
GFXInitFunc gfx_init_func;
- void*gfx_init_ud;
+ void *gfx_init_ud;
bool use_gl2;
bool use_reload_hooks;
@@ -119,11 +117,11 @@ private:
AudioDriverOpenSL audio_driver_android;
#endif
- const char* gl_extensions;
+ const char *gl_extensions;
InputDefault *input;
VideoMode default_videomode;
- MainLoop * main_loop;
+ MainLoop *main_loop;
OpenURIFunc open_uri_func;
GetDataDirFunc get_data_dir_func;
@@ -146,47 +144,44 @@ private:
power_android *power_manager;
public:
-
// functions used by main to initialize/deintialize the OS
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
virtual void finalize();
-
typedef int64_t ProcessID;
- static OS* get_singleton();
-
- virtual void vprint(const char* p_format, va_list p_list, bool p_stderr=false);
- virtual void print(const char *p_format, ... );
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
+ static OS *get_singleton();
+ virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false);
+ virtual void print(const char *p_format, ...);
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
//virtual void set_clipboard(const String& p_text);
//virtual String get_clipboard() const;
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual void set_keep_screen_on(bool p_enabled);
@@ -209,10 +204,10 @@ public:
virtual bool has_touchscreen_ui_hint() const;
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect=Rect2());
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2());
virtual void hide_virtual_keyboard();
- void set_opengl_extensions(const char* p_gl_extensions);
+ void set_opengl_extensions(const char *p_gl_extensions);
void set_display_size(Size2 p_size);
void reload_gfx();
@@ -226,20 +221,19 @@ public:
virtual String get_resource_dir() const;
virtual String get_locale() const;
virtual String get_model_name() const;
- virtual int get_screen_dpi(int p_screen=0) const;
+ virtual int get_screen_dpi(int p_screen = 0) const;
virtual String get_unique_ID() const;
virtual String get_system_dir(SystemDir p_dir) const;
-
- void process_accelerometer(const Vector3& p_accelerometer);
- void process_magnetometer(const Vector3& p_magnetometer);
- void process_gyroscope(const Vector3& p_gyroscope);
- void process_touch(int p_what,int p_pointer, const Vector<TouchPos>& p_points);
+ void process_accelerometer(const Vector3 &p_accelerometer);
+ void process_magnetometer(const Vector3 &p_magnetometer);
+ void process_gyroscope(const Vector3 &p_gyroscope);
+ void process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points);
void process_joy_event(JoypadEvent p_event);
void process_event(InputEvent p_event);
- void init_video_mode(int p_video_width,int p_video_height);
+ void init_video_mode(int p_video_width, int p_video_height);
virtual Error native_video_play(String p_path, float p_volume);
virtual bool native_video_is_playing();
@@ -250,9 +244,8 @@ public:
virtual String get_joy_guid(int p_device) const;
void joy_connection_changed(int p_device, bool p_connected, String p_name);
- OS_Android(GFXInitFunc p_gfx_init_func,void*p_gfx_init_ud, OpenURIFunc p_open_uri_func, GetDataDirFunc p_get_data_dir_func,GetLocaleFunc p_get_locale_func,GetModelFunc p_get_model_func, GetScreenDPIFunc p_get_screen_dpi_func, ShowVirtualKeyboardFunc p_show_vk, HideVirtualKeyboardFunc p_hide_vk, SetScreenOrientationFunc p_screen_orient,GetUniqueIDFunc p_get_unique_id,GetSystemDirFunc p_get_sdir_func, VideoPlayFunc p_video_play_func, VideoIsPlayingFunc p_video_is_playing_func, VideoPauseFunc p_video_pause_func, VideoStopFunc p_video_stop_func, SetKeepScreenOnFunc p_set_keep_screen_on_func, AlertFunc p_alert_func, bool p_use_apk_expansion);
+ OS_Android(GFXInitFunc p_gfx_init_func, void *p_gfx_init_ud, OpenURIFunc p_open_uri_func, GetDataDirFunc p_get_data_dir_func, GetLocaleFunc p_get_locale_func, GetModelFunc p_get_model_func, GetScreenDPIFunc p_get_screen_dpi_func, ShowVirtualKeyboardFunc p_show_vk, HideVirtualKeyboardFunc p_hide_vk, SetScreenOrientationFunc p_screen_orient, GetUniqueIDFunc p_get_unique_id, GetSystemDirFunc p_get_sdir_func, VideoPlayFunc p_video_play_func, VideoIsPlayingFunc p_video_is_playing_func, VideoPauseFunc p_video_pause_func, VideoStopFunc p_video_stop_func, SetKeepScreenOnFunc p_set_keep_screen_on_func, AlertFunc p_alert_func, bool p_use_apk_expansion);
~OS_Android();
-
};
#endif
diff --git a/platform/android/power_android.cpp b/platform/android/power_android.cpp
index dc3a4ec90c..aa37dc51e2 100644
--- a/platform/android/power_android.cpp
+++ b/platform/android/power_android.cpp
@@ -32,51 +32,45 @@
#include "power_android.h"
static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder) {
- if (refholder->m_env) {
- JNIEnv* env = refholder->m_env;
- (*env)->PopLocalFrame(env, NULL);
- --s_active;
- }
+ if (refholder->m_env) {
+ JNIEnv *env = refholder->m_env;
+ (*env)->PopLocalFrame(env, NULL);
+ --s_active;
+ }
}
-static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func)
-{
- struct LocalReferenceHolder refholder;
- refholder.m_env = NULL;
- refholder.m_func = func;
- return refholder;
+static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func) {
+ struct LocalReferenceHolder refholder;
+ refholder.m_env = NULL;
+ refholder.m_func = func;
+ return refholder;
}
-static bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env)
-{
- const int capacity = 16;
- if ((*env)->PushLocalFrame(env, capacity) < 0) {
- return false;
- }
- ++s_active;
- refholder->m_env = env;
- return true;
+static bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env) {
+ const int capacity = 16;
+ if ((*env)->PushLocalFrame(env, capacity) < 0) {
+ return false;
+ }
+ ++s_active;
+ refholder->m_env = env;
+ return true;
}
-
-static SDL_bool LocalReferenceHolder_IsActive(void)
-{
- return s_active > 0;
+static SDL_bool LocalReferenceHolder_IsActive(void) {
+ return s_active > 0;
}
-ANativeWindow* Android_JNI_GetNativeWindow(void)
-{
- ANativeWindow* anw;
- jobject s;
- JNIEnv *env = Android_JNI_GetEnv();
-
- s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
- anw = ANativeWindow_fromSurface(env, s);
- (*env)->DeleteLocalRef(env, s);
-
- return anw;
-}
+ANativeWindow *Android_JNI_GetNativeWindow(void) {
+ ANativeWindow *anw;
+ jobject s;
+ JNIEnv *env = Android_JNI_GetEnv();
+ s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
+ anw = ANativeWindow_fromSurface(env, s);
+ (*env)->DeleteLocalRef(env, s);
+
+ return anw;
+}
/*
* CODE CHUNK IMPORTED FROM SDL 2.0
@@ -84,11 +78,10 @@ ANativeWindow* Android_JNI_GetNativeWindow(void)
* returns truthy or falsy value in plugged, charged and battery
* returns the value in seconds and percent or -1 if not available
*/
-int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
-{
+int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seconds, int *percent) {
env = Android_JNI_GetEnv();
refs = LocalReferenceHolder_Setup(__FUNCTION__);
-
+
if (!LocalReferenceHolder_Init(&refs, env)) {
LocalReferenceHolder_Cleanup(&refs);
return -1;
@@ -105,17 +98,17 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
(*env)->DeleteLocalRef(env, filter);
cls = (*env)->GetObjectClass(env, intent);
imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
- // Watch out for C89 scoping rules because of the macro
-#define GET_INT_EXTRA(var, key) \
- int var; \
- iname = (*env)->NewStringUTF(env, key); \
+// Watch out for C89 scoping rules because of the macro
+#define GET_INT_EXTRA(var, key) \
+ int var; \
+ iname = (*env)->NewStringUTF(env, key); \
var = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
(*env)->DeleteLocalRef(env, iname);
bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
- // Watch out for C89 scoping rules because of the macro
-#define GET_BOOL_EXTRA(var, key) \
- int var; \
- bname = (*env)->NewStringUTF(env, key); \
+// Watch out for C89 scoping rules because of the macro
+#define GET_BOOL_EXTRA(var, key) \
+ int var; \
+ bname = (*env)->NewStringUTF(env, key); \
var = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
(*env)->DeleteLocalRef(env, bname);
if (plugged) {
@@ -167,11 +160,10 @@ int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seco
}
(*env)->DeleteLocalRef(env, intent);
LocalReferenceHolder_Cleanup(&refs);
-
+
return 0;
}
-
bool power_android::GetPowerInfo_Android() {
int battery;
int plugged;
@@ -203,8 +195,7 @@ bool power_android::GetPowerInfo_Android() {
PowerState power_android::get_power_state() {
if (GetPowerInfo_Android()) {
return power_state;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN");
return POWERSTATE_UNKNOWN;
}
@@ -213,8 +204,7 @@ PowerState power_android::get_power_state() {
int power_android::get_power_seconds_left() {
if (GetPowerInfo_Android()) {
return nsecs_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
@@ -223,15 +213,14 @@ int power_android::get_power_seconds_left() {
int power_android::get_power_percent_left() {
if (GetPowerInfo_Android()) {
return percent_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
}
-power_android::power_android() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+power_android::power_android()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
power_android::~power_android() {
diff --git a/platform/android/power_android.h b/platform/android/power_android.h
index c59bdf3888..df4983bbf3 100644
--- a/platform/android/power_android.h
+++ b/platform/android/power_android.h
@@ -35,15 +35,14 @@
class power_android {
-struct LocalReferenceHolder
-{
- JNIEnv *m_env;
- const char *m_func;
-};
+ struct LocalReferenceHolder {
+ JNIEnv *m_env;
+ const char *m_func;
+ };
private:
static struct LocalReferenceHolder refs;
- static JNIEnv* env;
+ static JNIEnv *env;
static jmethodID mid;
static jobject context;
static jstring action;
@@ -55,7 +54,6 @@ private:
static jstring bname;
static jmethodID bmid;
-
int nsecs_left;
int percent_left;
PowerState power_state;
@@ -64,9 +62,7 @@ private:
bool UpdatePowerInfo();
public:
-
static int s_active;
-
power_android();
virtual ~power_android();
diff --git a/platform/android/thread_jandroid.cpp b/platform/android/thread_jandroid.cpp
index aa40d995d9..854cdb1e34 100644
--- a/platform/android/thread_jandroid.cpp
+++ b/platform/android/thread_jandroid.cpp
@@ -36,29 +36,29 @@ Thread::ID ThreadAndroid::get_ID() const {
return id;
}
-Thread* ThreadAndroid::create_thread_jandroid() {
+Thread *ThreadAndroid::create_thread_jandroid() {
- return memnew( ThreadAndroid );
+ return memnew(ThreadAndroid);
}
void *ThreadAndroid::thread_callback(void *userdata) {
- ThreadAndroid *t=reinterpret_cast<ThreadAndroid*>(userdata);
+ ThreadAndroid *t = reinterpret_cast<ThreadAndroid *>(userdata);
setup_thread();
ScriptServer::thread_enter(); //scripts may need to attach a stack
- t->id=(ID)pthread_self();
+ t->id = (ID)pthread_self();
t->callback(t->user);
ScriptServer::thread_exit();
return NULL;
}
-Thread* ThreadAndroid::create_func_jandroid(ThreadCreateCallback p_callback,void *p_user,const Settings&) {
+Thread *ThreadAndroid::create_func_jandroid(ThreadCreateCallback p_callback, void *p_user, const Settings &) {
- ThreadAndroid *tr= memnew(ThreadAndroid);
- tr->callback=p_callback;
- tr->user=p_user;
+ ThreadAndroid *tr = memnew(ThreadAndroid);
+ tr->callback = p_callback;
+ tr->user = p_user;
pthread_attr_init(&tr->pthread_attr);
- pthread_attr_setdetachstate(&tr->pthread_attr, PTHREAD_CREATE_JOINABLE);
+ pthread_attr_setdetachstate(&tr->pthread_attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&tr->pthread, &tr->pthread_attr, thread_callback, tr);
@@ -70,29 +70,28 @@ Thread::ID ThreadAndroid::get_thread_ID_func_jandroid() {
return (ID)pthread_self();
}
-void ThreadAndroid::wait_to_finish_func_jandroid(Thread* p_thread) {
+void ThreadAndroid::wait_to_finish_func_jandroid(Thread *p_thread) {
- ThreadAndroid *tp=static_cast<ThreadAndroid*>(p_thread);
+ ThreadAndroid *tp = static_cast<ThreadAndroid *>(p_thread);
ERR_FAIL_COND(!tp);
- ERR_FAIL_COND(tp->pthread==0);
+ ERR_FAIL_COND(tp->pthread == 0);
- pthread_join(tp->pthread,NULL);
- tp->pthread=0;
+ pthread_join(tp->pthread, NULL);
+ tp->pthread = 0;
}
-void ThreadAndroid::_thread_destroyed(void* value) {
+void ThreadAndroid::_thread_destroyed(void *value) {
/* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
- JNIEnv *env = (JNIEnv*) value;
+ JNIEnv *env = (JNIEnv *)value;
if (env != NULL) {
java_vm->DetachCurrentThread();
pthread_setspecific(jvm_key, NULL);
}
-
}
pthread_key_t ThreadAndroid::jvm_key;
-JavaVM* ThreadAndroid::java_vm=NULL;
+JavaVM *ThreadAndroid::java_vm = NULL;
void ThreadAndroid::setup_thread() {
@@ -100,19 +99,17 @@ void ThreadAndroid::setup_thread() {
return; //already setup
JNIEnv *env;
java_vm->AttachCurrentThread(&env, NULL);
- pthread_setspecific(jvm_key, (void*) env);
-
+ pthread_setspecific(jvm_key, (void *)env);
}
-void ThreadAndroid::make_default(JavaVM* p_java_vm) {
+void ThreadAndroid::make_default(JavaVM *p_java_vm) {
- java_vm=p_java_vm;
- create_func=create_func_jandroid;
- get_thread_ID_func=get_thread_ID_func_jandroid;
- wait_to_finish_func=wait_to_finish_func_jandroid;
+ java_vm = p_java_vm;
+ create_func = create_func_jandroid;
+ get_thread_ID_func = get_thread_ID_func_jandroid;
+ wait_to_finish_func = wait_to_finish_func_jandroid;
pthread_key_create(&jvm_key, _thread_destroyed);
setup_thread();
-
}
JNIEnv *ThreadAndroid::get_env() {
@@ -121,20 +118,15 @@ JNIEnv *ThreadAndroid::get_env() {
setup_thread();
}
- JNIEnv *env=NULL;
+ JNIEnv *env = NULL;
int status = java_vm->AttachCurrentThread(&env, NULL);
return env;
}
-
ThreadAndroid::ThreadAndroid() {
- pthread=0;
+ pthread = 0;
}
-
ThreadAndroid::~ThreadAndroid() {
-
}
-
-
diff --git a/platform/android/thread_jandroid.h b/platform/android/thread_jandroid.h
index 6f52b730f1..a8d8a4d8b1 100644
--- a/platform/android/thread_jandroid.h
+++ b/platform/android/thread_jandroid.h
@@ -33,11 +33,10 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-#include <sys/types.h>
-#include <pthread.h>
#include "os/thread.h"
#include <jni.h>
+#include <pthread.h>
+#include <sys/types.h>
class ThreadAndroid : public Thread {
@@ -47,36 +46,28 @@ class ThreadAndroid : public Thread {
void *user;
ID id;
- static Thread* create_thread_jandroid();
-
+ static Thread *create_thread_jandroid();
static void *thread_callback(void *userdata);
- static Thread* create_func_jandroid(ThreadCreateCallback p_callback,void *,const Settings&);
+ static Thread *create_func_jandroid(ThreadCreateCallback p_callback, void *, const Settings &);
static ID get_thread_ID_func_jandroid();
- static void wait_to_finish_func_jandroid(Thread* p_thread);
+ static void wait_to_finish_func_jandroid(Thread *p_thread);
- static void _thread_destroyed(void* value);
+ static void _thread_destroyed(void *value);
ThreadAndroid();
static pthread_key_t jvm_key;
- static JavaVM* java_vm;
-public:
-
-
-
+ static JavaVM *java_vm;
+public:
virtual ID get_ID() const;
- static void make_default(JavaVM* p_java_vm);
+ static void make_default(JavaVM *p_java_vm);
static void setup_thread();
static JNIEnv *get_env();
-
~ThreadAndroid();
-
};
-
-
#endif
diff --git a/platform/bb10/audio_driver_bb10.cpp b/platform/bb10/audio_driver_bb10.cpp
index b6ea0bc267..5416fc5f02 100644
--- a/platform/bb10/audio_driver_bb10.cpp
+++ b/platform/bb10/audio_driver_bb10.cpp
@@ -34,11 +34,11 @@ Error AudioDriverBB10::init() {
return init(NULL);
};
-Error AudioDriverBB10::init(const char* p_name) {
+Error AudioDriverBB10::init(const char *p_name) {
- active=false;
- thread_exited=false;
- exit_thread=false;
+ active = false;
+ thread_exited = false;
+ exit_thread = false;
pcm_open = false;
samples_in = NULL;
samples_out = NULL;
@@ -46,11 +46,11 @@ Error AudioDriverBB10::init(const char* p_name) {
mix_rate = 44100;
speaker_mode = SPEAKER_MODE_STEREO;
- char* dev_name;
+ char *dev_name;
if (p_name == NULL) {
dev_name = "pcmPreferred";
} else {
- dev_name = (char *) p_name;
+ dev_name = (char *)p_name;
}
printf("******** reconnecting to device %s\n", dev_name);
int ret = snd_pcm_open_name(&pcm_handle, dev_name, SND_PCM_OPEN_PLAYBACK);
@@ -58,7 +58,7 @@ Error AudioDriverBB10::init(const char* p_name) {
pcm_open = true;
snd_pcm_channel_info_t cinfo;
- zeromem(&cinfo, sizeof (cinfo));
+ zeromem(&cinfo, sizeof(cinfo));
cinfo.channel = SND_PCM_CHANNEL_PLAYBACK;
snd_pcm_plugin_info(pcm_handle, &cinfo);
@@ -117,9 +117,9 @@ Error AudioDriverBB10::init(const char* p_name) {
return OK;
};
-void AudioDriverBB10::thread_func(void* p_udata) {
+void AudioDriverBB10::thread_func(void *p_udata) {
- AudioDriverBB10* ad = (AudioDriverBB10*)p_udata;
+ AudioDriverBB10 *ad = (AudioDriverBB10 *)p_udata;
int channels = speaker_mode;
int frame_count = ad->sample_buf_count / channels;
@@ -127,10 +127,9 @@ void AudioDriverBB10::thread_func(void* p_udata) {
while (!ad->exit_thread) {
-
if (!ad->active) {
- for (int i=0; i < ad->sample_buf_count; i++) {
+ for (int i = 0; i < ad->sample_buf_count; i++) {
ad->samples_out[i] = 0;
};
@@ -142,20 +141,19 @@ void AudioDriverBB10::thread_func(void* p_udata) {
ad->unlock();
- for(int i=0;i<frame_count*channels;i++) {
+ for (int i = 0; i < frame_count * channels; i++) {
- ad->samples_out[i]=ad->samples_in[i]>>16;
+ ad->samples_out[i] = ad->samples_in[i] >> 16;
}
};
-
int todo = bytes_out;
int total = 0;
while (todo) {
- uint8_t* src = (uint8_t*)ad->samples_out;
- int wrote = snd_pcm_plugin_write(ad->pcm_handle, (void*)(src + total), todo);
+ uint8_t *src = (uint8_t *)ad->samples_out;
+ int wrote = snd_pcm_plugin_write(ad->pcm_handle, (void *)(src + total), todo);
if (wrote < 0) {
// error?
break;
@@ -179,7 +177,7 @@ void AudioDriverBB10::thread_func(void* p_udata) {
break;
};
if (status.status == SND_PCM_STATUS_READY ||
- status.status == SND_PCM_STATUS_UNDERRUN) {
+ status.status == SND_PCM_STATUS_UNDERRUN) {
snd_pcm_plugin_prepare(ad->pcm_handle, SND_PCM_CHANNEL_PLAYBACK);
} else {
break;
@@ -188,9 +186,9 @@ void AudioDriverBB10::thread_func(void* p_udata) {
};
};
- snd_pcm_plugin_flush (ad->pcm_handle, SND_PCM_CHANNEL_PLAYBACK);
+ snd_pcm_plugin_flush(ad->pcm_handle, SND_PCM_CHANNEL_PLAYBACK);
- ad->thread_exited=true;
+ ad->thread_exited = true;
printf("**************** audio thread exit\n");
};
@@ -253,4 +251,3 @@ AudioDriverBB10::~AudioDriverBB10() {
memdelete(mutex);
mutex = NULL;
};
-
diff --git a/platform/bb10/audio_driver_bb10.h b/platform/bb10/audio_driver_bb10.h
index efb98b1b91..2a0ed9c545 100644
--- a/platform/bb10/audio_driver_bb10.h
+++ b/platform/bb10/audio_driver_bb10.h
@@ -28,23 +28,23 @@
/*************************************************************************/
#include "servers/audio_server.h"
-#include "core/os/thread.h"
#include "core/os/mutex.h"
+#include "core/os/thread.h"
#include <sys/asoundlib.h>
class AudioDriverBB10 : public AudioDriver {
- Thread* thread;
- Mutex* mutex;
+ Thread *thread;
+ Mutex *mutex;
- snd_pcm_t* pcm_handle;
+ snd_pcm_t *pcm_handle;
- int32_t* samples_in;
- int16_t* samples_out;
+ int32_t *samples_in;
+ int16_t *samples_out;
int sample_buf_count;
- static void thread_func(void* p_udata);
+ static void thread_func(void *p_udata);
int mix_rate;
SpeakerMode speaker_mode;
@@ -58,13 +58,12 @@ class AudioDriverBB10 : public AudioDriver {
bool pcm_open;
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "BB10";
};
virtual Error init();
- virtual Error init(const char* p_name);
+ virtual Error init(const char *p_name);
virtual void start();
virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
@@ -75,4 +74,3 @@ public:
AudioDriverBB10();
~AudioDriverBB10();
};
-
diff --git a/platform/bb10/export/export.cpp b/platform/bb10/export/export.cpp
index cf8e2fcc0a..c958bf7ff4 100644
--- a/platform/bb10/export/export.cpp
+++ b/platform/bb10/export/export.cpp
@@ -26,18 +26,18 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "version.h"
#include "export.h"
-#include "editor/editor_settings.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
-#include "io/zip_io.h"
-#include "io/marshalls.h"
+#include "editor/editor_settings.h"
#include "global_config.h"
+#include "io/marshalls.h"
+#include "io/xml_parser.h"
+#include "io/zip_io.h"
#include "os/file_access.h"
#include "os/os.h"
#include "platform/bb10/logo.h"
-#include "io/xml_parser.h"
+#include "version.h"
#define MAX_DEVICES 5
#if 0
@@ -826,5 +826,3 @@ void register_bb10_exporter() {
#endif
}
-
-
diff --git a/platform/bb10/godot_bb10.cpp b/platform/bb10/godot_bb10.cpp
index 4b8270b495..e1826450a6 100644
--- a/platform/bb10/godot_bb10.cpp
+++ b/platform/bb10/godot_bb10.cpp
@@ -31,12 +31,12 @@
#include <unistd.h>
-int main(int argc, char* argv[]) {
+int main(int argc, char *argv[]) {
OSBB10 os;
- Error err = Main::setup(argv[0],argc-1,&argv[1]);
- if (err!=OK)
+ Error err = Main::setup(argv[0], argc - 1, &argv[1]);
+ if (err != OK)
return 255;
if (Main::start())
@@ -45,4 +45,3 @@ int main(int argc, char* argv[]) {
return os.get_exit_code();
}
-
diff --git a/platform/bb10/os_bb10.cpp b/platform/bb10/os_bb10.cpp
index bf7bfb6909..80e846d3cd 100644
--- a/platform/bb10/os_bb10.cpp
+++ b/platform/bb10/os_bb10.cpp
@@ -28,37 +28,37 @@
/*************************************************************************/
#include "os_bb10.h"
-#include "drivers/gles2/rasterizer_gles2.h"
-#include "servers/visual/visual_server_raster.h"
-#include "core/os/dir_access.h"
-#include "core/global_config.h"
-#include "main/main.h"
#include "bbutil.h"
+#include "core/global_config.h"
+#include "core/os/dir_access.h"
#include "core/os/keyboard.h"
+#include "drivers/gles2/rasterizer_gles2.h"
+#include "main/main.h"
+#include "servers/visual/visual_server_raster.h"
-#include <stdlib.h>
-#include <stdbool.h>
#include <assert.h>
+#include <bps/accelerometer.h>
+#include <bps/audiodevice.h>
#include <bps/bps.h>
-#include <bps/screen.h>
#include <bps/navigator.h>
-#include <bps/accelerometer.h>
#include <bps/orientation.h>
+#include <bps/screen.h>
#include <bps/virtualkeyboard.h>
-#include <bps/audiodevice.h>
+#include <stdbool.h>
+#include <stdlib.h>
#ifdef BB10_SCORELOOP_ENABLED
#include "modules/scoreloop/scoreloop_bb10.h"
#endif
static char launch_dir[512];
-char* launch_dir_ptr;
+char *launch_dir_ptr;
int OSBB10::get_video_driver_count() const {
return 1;
}
-const char * OSBB10::get_video_driver_name(int p_driver) const {
+const char *OSBB10::get_video_driver_name(int p_driver) const {
return "GLES2";
}
@@ -72,26 +72,26 @@ int OSBB10::get_audio_driver_count() const {
return 1;
}
-const char * OSBB10::get_audio_driver_name(int p_driver) const {
+const char *OSBB10::get_audio_driver_name(int p_driver) const {
return "BB10";
}
-void OSBB10::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OSBB10::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
data_dir = getenv("HOME");
//Create a screen context that will be used to create an EGL surface to to receive libscreen events
- screen_create_context(&screen_cxt,0);
+ screen_create_context(&screen_cxt, 0);
//Initialize BPS library
bps_initialize();
//Use utility code to initialize EGL for 2D rendering with GL ES 1.1
enum RENDERING_API api = GL_ES_2;
- #ifdef BB10_LGLES_OVERRIDE
+#ifdef BB10_LGLES_OVERRIDE
api = GL_ES_1;
- #endif
+#endif
if (EXIT_SUCCESS != bbutil_init(screen_cxt, api)) {
bbutil_terminate();
screen_destroy_context(screen_cxt);
@@ -116,9 +116,9 @@ void OSBB10::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
virtualkeyboard_request_events(0);
audiodevice_request_events(0);
- #ifdef DEBUG_ENABLED
+#ifdef DEBUG_ENABLED
bps_set_verbosity(3);
- #endif
+#endif
accel_supported = accelerometer_is_supported();
if (accel_supported)
@@ -126,13 +126,13 @@ void OSBB10::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
pitch = 0;
roll = 0;
- #ifdef BB10_LGLES_OVERRIDE
- rasterizer = memnew( RasterizerGLES1(false) );
- #else
- rasterizer = memnew( RasterizerGLES2(false, false) );
- #endif
+#ifdef BB10_LGLES_OVERRIDE
+ rasterizer = memnew(RasterizerGLES1(false));
+#else
+ rasterizer = memnew(RasterizerGLES2(false, false));
+#endif
- visual_server = memnew( VisualServerRaster(rasterizer) );
+ visual_server = memnew(VisualServerRaster(rasterizer));
visual_server->init();
visual_server->cursor_set_visible(false, 0);
@@ -140,39 +140,38 @@ void OSBB10::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
audio_driver->set_singleton();
audio_driver->init(NULL);
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
- physics_2d_server = memnew( Physics2DServerSW );
+ physics_2d_server = memnew(Physics2DServerSW);
physics_2d_server->init();
- input = memnew( InputDefault );
-
- power_manager = memnew( PowerBB10 );
+ input = memnew(InputDefault);
+
+ power_manager = memnew(PowerBB10);
- #ifdef PAYMENT_SERVICE_ENABLED
+#ifdef PAYMENT_SERVICE_ENABLED
payment_service = memnew(PaymentService);
Globals::get_singleton()->add_singleton(Globals::Singleton("InAppStore", payment_service));
- #endif
-
+#endif
}
-void OSBB10::set_main_loop( MainLoop * p_main_loop ) {
+void OSBB10::set_main_loop(MainLoop *p_main_loop) {
input->set_main_loop(p_main_loop);
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
}
void OSBB10::delete_main_loop() {
- memdelete( main_loop );
+ memdelete(main_loop);
main_loop = NULL;
}
void OSBB10::finalize() {
- if(main_loop)
+ if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
/*
if (debugger_connection_console) {
@@ -190,9 +189,9 @@ void OSBB10::finalize() {
physics_2d_server->finish();
memdelete(physics_2d_server);
- #ifdef PAYMENT_SERVICE_ENABLED
+#ifdef PAYMENT_SERVICE_ENABLED
memdelete(payment_service);
- #endif
+#endif
memdelete(input);
@@ -225,16 +224,14 @@ int OSBB10::get_mouse_button_state() const {
return 0;
}
-void OSBB10::set_window_title(const String& p_title) {
-
-
+void OSBB10::set_window_title(const String &p_title) {
}
//interesting byt not yet
//void set_clipboard(const String& p_text);
//String get_clipboard() const;
-void OSBB10::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
+void OSBB10::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
default_videomode = p_video_mode;
}
@@ -243,7 +240,7 @@ OS::VideoMode OSBB10::get_video_mode(int p_screen) const {
return default_videomode;
}
-void OSBB10::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
+void OSBB10::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
p_list->push_back(default_videomode);
}
@@ -278,128 +275,125 @@ void OSBB10::handle_screen_event(bps_event_t *event) {
int pos[2];
switch (screen_val) {
- case SCREEN_EVENT_MTOUCH_TOUCH:
- case SCREEN_EVENT_MTOUCH_RELEASE: {
-
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_POSITION, pos);
-
- InputEvent ievent;
- ievent.type = InputEvent::SCREEN_TOUCH;
- ievent.ID = ++last_id;
- ievent.device = 0;
- ievent.screen_touch.pressed = (screen_val == SCREEN_EVENT_MTOUCH_TOUCH);
- ievent.screen_touch.x = pos[0];
- ievent.screen_touch.y = pos[1];
- Point2 mpos(ievent.screen_touch.x, ievent.screen_touch.y);
+ case SCREEN_EVENT_MTOUCH_TOUCH:
+ case SCREEN_EVENT_MTOUCH_RELEASE: {
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pos[0]);
- ievent.screen_touch.index = pos[0];
-
- last_touch_x[pos[0]] = ievent.screen_touch.x;
- last_touch_y[pos[0]] = ievent.screen_touch.y;
-
- input->parse_input_event( ievent );
-
- if (ievent.screen_touch.index == 0) {
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_POSITION, pos);
InputEvent ievent;
- ievent.type = InputEvent::MOUSE_BUTTON;
+ ievent.type = InputEvent::SCREEN_TOUCH;
ievent.ID = ++last_id;
ievent.device = 0;
- ievent.mouse_button.pressed = (screen_val == SCREEN_EVENT_MTOUCH_TOUCH);
- ievent.mouse_button.button_index = BUTTON_LEFT;
- ievent.mouse_button.doubleclick = 0;
- ievent.mouse_button.x = ievent.mouse_button.global_x = mpos.x;
- ievent.mouse_button.y = ievent.mouse_button.global_y = mpos.y;
- input->parse_input_event( ievent );
- };
-
+ ievent.screen_touch.pressed = (screen_val == SCREEN_EVENT_MTOUCH_TOUCH);
+ ievent.screen_touch.x = pos[0];
+ ievent.screen_touch.y = pos[1];
+ Point2 mpos(ievent.screen_touch.x, ievent.screen_touch.y);
+
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pos[0]);
+ ievent.screen_touch.index = pos[0];
+
+ last_touch_x[pos[0]] = ievent.screen_touch.x;
+ last_touch_y[pos[0]] = ievent.screen_touch.y;
+
+ input->parse_input_event(ievent);
+
+ if (ievent.screen_touch.index == 0) {
+
+ InputEvent ievent;
+ ievent.type = InputEvent::MOUSE_BUTTON;
+ ievent.ID = ++last_id;
+ ievent.device = 0;
+ ievent.mouse_button.pressed = (screen_val == SCREEN_EVENT_MTOUCH_TOUCH);
+ ievent.mouse_button.button_index = BUTTON_LEFT;
+ ievent.mouse_button.doubleclick = 0;
+ ievent.mouse_button.x = ievent.mouse_button.global_x = mpos.x;
+ ievent.mouse_button.y = ievent.mouse_button.global_y = mpos.y;
+ input->parse_input_event(ievent);
+ };
- } break;
- case SCREEN_EVENT_MTOUCH_MOVE: {
+ } break;
+ case SCREEN_EVENT_MTOUCH_MOVE: {
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_POSITION, pos);
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_POSITION, pos);
- InputEvent ievent;
- ievent.type = InputEvent::SCREEN_DRAG;
- ievent.ID = ++last_id;
- ievent.device = 0;
- ievent.screen_drag.x = pos[0];
- ievent.screen_drag.y = pos[1];
+ InputEvent ievent;
+ ievent.type = InputEvent::SCREEN_DRAG;
+ ievent.ID = ++last_id;
+ ievent.device = 0;
+ ievent.screen_drag.x = pos[0];
+ ievent.screen_drag.y = pos[1];
- /*
+ /*
screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_SOURCE_POSITION, pos);
ievent.screen_drag.relative_x = ievent.screen_drag.x - pos[0];
ievent.screen_drag.relative_y = ievent.screen_drag.y - pos[1];
*/
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pos[0]);
- ievent.screen_drag.index = pos[0];
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pos[0]);
+ ievent.screen_drag.index = pos[0];
+
+ ievent.screen_drag.relative_x = ievent.screen_drag.x - last_touch_x[ievent.screen_drag.index];
+ ievent.screen_drag.relative_y = ievent.screen_drag.y - last_touch_y[ievent.screen_drag.index];
+
+ last_touch_x[ievent.screen_drag.index] = ievent.screen_drag.x;
+ last_touch_y[ievent.screen_drag.index] = ievent.screen_drag.y;
+ Point2 mpos(ievent.screen_drag.x, ievent.screen_drag.y);
+ Point2 mrel(ievent.screen_drag.relative_x, ievent.screen_drag.relative_y);
- ievent.screen_drag.relative_x = ievent.screen_drag.x - last_touch_x[ievent.screen_drag.index];
- ievent.screen_drag.relative_y = ievent.screen_drag.y - last_touch_y[ievent.screen_drag.index];
+ input->parse_input_event(ievent);
- last_touch_x[ievent.screen_drag.index] = ievent.screen_drag.x;
- last_touch_y[ievent.screen_drag.index] = ievent.screen_drag.y;
+ if (ievent.screen_touch.index == 0) {
- Point2 mpos(ievent.screen_drag.x, ievent.screen_drag.y);
- Point2 mrel(ievent.screen_drag.relative_x, ievent.screen_drag.relative_y);
+ InputEvent ievent;
+ ievent.type = InputEvent::MOUSE_MOTION;
+ ievent.ID = ++last_id;
+ ievent.device = 0;
+ ievent.mouse_motion.x = ievent.mouse_motion.global_x = mpos.x;
+ ievent.mouse_motion.y = ievent.mouse_motion.global_y = mpos.y;
+ input->set_mouse_pos(Point2(ievent.mouse_motion.x, ievent.mouse_motion.y));
+ ievent.mouse_motion.speed_x = input->get_last_mouse_speed().x;
+ ievent.mouse_motion.speed_y = input->get_last_mouse_speed().y;
+ ievent.mouse_motion.relative_x = mrel.x;
+ ievent.mouse_motion.relative_y = mrel.y;
+ ievent.mouse_motion.button_mask = 1; // pressed
- input->parse_input_event( ievent );
+ input->parse_input_event(ievent);
+ };
+ } break;
- if (ievent.screen_touch.index == 0) {
+ case SCREEN_EVENT_KEYBOARD: {
InputEvent ievent;
- ievent.type = InputEvent::MOUSE_MOTION;
+ ievent.type = InputEvent::KEY;
ievent.ID = ++last_id;
ievent.device = 0;
- ievent.mouse_motion.x = ievent.mouse_motion.global_x = mpos.x;
- ievent.mouse_motion.y = ievent.mouse_motion.global_y = mpos.y;
- input->set_mouse_pos(Point2(ievent.mouse_motion.x,ievent.mouse_motion.y));
- ievent.mouse_motion.speed_x=input->get_last_mouse_speed().x;
- ievent.mouse_motion.speed_y=input->get_last_mouse_speed().y;
- ievent.mouse_motion.relative_x = mrel.x;
- ievent.mouse_motion.relative_y = mrel.y;
- ievent.mouse_motion.button_mask = 1; // pressed
-
- input->parse_input_event( ievent );
- };
- } break;
-
- case SCREEN_EVENT_KEYBOARD: {
-
- InputEvent ievent;
- ievent.type = InputEvent::KEY;
- ievent.ID = ++last_id;
- ievent.device = 0;
- int val = 0;
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SCAN, &val);
- ievent.key.scancode = val;
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &val);
- ievent.key.unicode = val;
- if (val == 61448) {
- ievent.key.scancode = KEY_BACKSPACE;
- ievent.key.unicode = KEY_BACKSPACE;
- };
- if (val == 61453) {
- ievent.key.scancode = KEY_ENTER;
- ievent.key.unicode = KEY_ENTER;
- };
-
- int flags;
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);
- ievent.key.pressed = flags & 1; // bit 1 is pressed apparently
+ int val = 0;
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SCAN, &val);
+ ievent.key.scancode = val;
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &val);
+ ievent.key.unicode = val;
+ if (val == 61448) {
+ ievent.key.scancode = KEY_BACKSPACE;
+ ievent.key.unicode = KEY_BACKSPACE;
+ };
+ if (val == 61453) {
+ ievent.key.scancode = KEY_ENTER;
+ ievent.key.unicode = KEY_ENTER;
+ };
- int mod;
- screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_MODIFIERS, &mod);
+ int flags;
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);
+ ievent.key.pressed = flags & 1; // bit 1 is pressed apparently
- input->parse_input_event( ievent );
- } break;
+ int mod;
+ screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_MODIFIERS, &mod);
- default:
- break;
+ input->parse_input_event(ievent);
+ } break;
+ default:
+ break;
}
};
@@ -419,8 +413,7 @@ void OSBB10::handle_accelerometer() {
//input->set_accelerometer(Vector3(force_y, flip_accelerometer?force_x:(-force_x), force_z));
};
-
-void OSBB10::_resize(bps_event_t* event) {
+void OSBB10::_resize(bps_event_t *event) {
int angle = navigator_event_get_orientation_angle(event);
bbutil_rotate_screen_surface(angle);
@@ -449,16 +442,16 @@ void OSBB10::process_events() {
if (!event) break;
- #ifdef BB10_SCORELOOP_ENABLED
- ScoreloopBB10* sc = Globals::get_singleton()->get_singleton_object("Scoreloop")->cast_to<ScoreloopBB10>();
+#ifdef BB10_SCORELOOP_ENABLED
+ ScoreloopBB10 *sc = Globals::get_singleton()->get_singleton_object("Scoreloop")->cast_to<ScoreloopBB10>();
if (sc->handle_event(event))
continue;
- #endif
+#endif
- #ifdef PAYMENT_SERVICE_ENABLED
+#ifdef PAYMENT_SERVICE_ENABLED
if (payment_service->handle_event(event))
continue;
- #endif
+#endif
int domain = bps_event_get_domain(event);
if (domain == screen_get_domain()) {
@@ -473,7 +466,7 @@ void OSBB10::process_events() {
bps_event_destroy(event);
exit(0);
return;
- /*
+ /*
} else if (bps_event_get_code(event) == NAVIGATOR_ORIENTATION_CHECK) {
int angle = navigator_event_get_orientation_angle(event);
@@ -504,7 +497,7 @@ void OSBB10::process_events() {
};
} else if (domain == audiodevice_get_domain()) {
- const char * audiodevice_path = audiodevice_event_get_path(event);
+ const char *audiodevice_path = audiodevice_event_get_path(event);
printf("************* got audiodevice event, path %s\n", audiodevice_path);
audio_driver->finish();
audio_driver->init(audiodevice_path);
@@ -520,7 +513,7 @@ bool OSBB10::has_virtual_keyboard() const {
return true;
};
-void OSBB10::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) {
+void OSBB10::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
virtualkeyboard_show();
};
@@ -551,11 +544,10 @@ void OSBB10::run() {
};
*/
-
while (true) {
process_events(); // get rid of pending events
- if (Main::iteration()==true)
+ if (Main::iteration() == true)
break;
bbutil_swap();
//#ifdef DEBUG_ENABLED
@@ -564,7 +556,6 @@ void OSBB10::run() {
};
main_loop->finish();
-
};
bool OSBB10::has_touchscreen_ui_hint() const {
@@ -574,7 +565,7 @@ bool OSBB10::has_touchscreen_ui_hint() const {
Error OSBB10::shell_open(String p_uri) {
- char* msg = NULL;
+ char *msg = NULL;
int ret = navigator_invoke(p_uri.utf8().get_data(), &msg);
return ret == BPS_SUCCESS ? OK : FAILED;
@@ -603,15 +594,14 @@ int OSBB10::get_power_percent_left() {
OSBB10::OSBB10() {
- main_loop=NULL;
- last_id=1;
+ main_loop = NULL;
+ last_id = 1;
minimized = false;
fullscreen = true;
flip_accelerometer = true;
fullscreen_mixer_volume = 1;
fullscreen_stream_volume = 1;
-
printf("godot bb10!\n");
getcwd(launch_dir, sizeof(launch_dir));
printf("launch dir %s\n", launch_dir);
@@ -620,7 +610,4 @@ OSBB10::OSBB10() {
}
OSBB10::~OSBB10() {
-
-
}
-
diff --git a/platform/bb10/os_bb10.h b/platform/bb10/os_bb10.h
index 678b8c9fc2..313f9c9e6b 100644
--- a/platform/bb10/os_bb10.h
+++ b/platform/bb10/os_bb10.h
@@ -29,22 +29,22 @@
#ifndef OS_BB10_H
#define OS_BB10_H
-#include "os/input.h"
+#include "audio_driver_bb10.h"
#include "drivers/unix/os_unix.h"
-#include "os/main_loop.h"
#include "main/input_default.h"
-#include "servers/physics/physics_server_sw.h"
+#include "os/input.h"
+#include "os/main_loop.h"
+#include "payment_service.h"
+#include "power_bb10.h"
#include "servers/audio_server.h"
+#include "servers/physics/physics_server_sw.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/visual/rasterizer.h"
-#include "audio_driver_bb10.h"
-#include "payment_service.h"
-#include "power_bb10.h"
-#include <screen/screen.h>
-#include <sys/platform.h>
#include <bps/event.h>
+#include <screen/screen.h>
#include <stdint.h>
+#include <sys/platform.h>
class OSBB10 : public OS_Unix {
@@ -58,15 +58,15 @@ class OSBB10 : public OS_Unix {
VisualServer *visual_server;
PhysicsServer *physics_server;
Physics2DServer *physics_2d_server;
- AudioDriverBB10* audio_driver;
+ AudioDriverBB10 *audio_driver;
PowerBB10 *power_manager;
#ifdef PAYMENT_SERVICE_ENABLED
- PaymentService* payment_service;
+ PaymentService *payment_service;
#endif
VideoMode default_videomode;
- MainLoop * main_loop;
+ MainLoop *main_loop;
void process_events();
@@ -87,48 +87,47 @@ class OSBB10 : public OS_Unix {
String data_dir;
InputDefault *input;
-public:
+public:
// functions used by main to initialize/deintialize the OS
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual String get_data_dir() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
virtual void finalize();
typedef int64_t ProcessID;
- static OS* get_singleton();
+ static OS *get_singleton();
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
//virtual void set_clipboard(const String& p_text);
//virtual String get_clipboard() const;
-
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect);
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect);
virtual void hide_virtual_keyboard();
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual Size2 get_window_size() const;
virtual String get_name();
@@ -150,8 +149,6 @@ public:
OSBB10();
~OSBB10();
-
};
#endif
-
diff --git a/platform/bb10/payment_service.cpp b/platform/bb10/payment_service.cpp
index 131c9712a5..e78326e8b1 100644
--- a/platform/bb10/payment_service.cpp
+++ b/platform/bb10/payment_service.cpp
@@ -31,18 +31,18 @@
#include "payment_service.h"
#include "bbutil.h"
-#include <string.h>
#include <errno.h>
+#include <string.h>
#include <unistd.h>
-extern char* launch_dir_ptr;
+extern char *launch_dir_ptr;
void PaymentService::_bind_methods() {
- ClassDB::bind_method(D_METHOD("request_product_info"),&PaymentService::request_product_info);
- ClassDB::bind_method(D_METHOD("purchase"),&PaymentService::purchase);
+ ClassDB::bind_method(D_METHOD("request_product_info"), &PaymentService::request_product_info);
+ ClassDB::bind_method(D_METHOD("purchase"), &PaymentService::purchase);
- ClassDB::bind_method(D_METHOD("get_pending_event_count"),&PaymentService::get_pending_event_count);
- ClassDB::bind_method(D_METHOD("pop_pending_event"),&PaymentService::pop_pending_event);
+ ClassDB::bind_method(D_METHOD("get_pending_event_count"), &PaymentService::get_pending_event_count);
+ ClassDB::bind_method(D_METHOD("pop_pending_event"), &PaymentService::pop_pending_event);
};
Error PaymentService::request_product_info(Variant p_params) {
@@ -55,16 +55,16 @@ Error PaymentService::purchase(Variant p_params) {
Dictionary params = p_params;
ERR_FAIL_COND_V((!params.has("product_id")) && (!params.has("product_sku")), ERR_INVALID_PARAMETER);
- char* id = NULL;
- char* sku = NULL;
+ char *id = NULL;
+ char *sku = NULL;
- CharString p_id = params.has("product_id")?String(params["product_id"]).ascii():CharString();
- CharString p_sku = params.has("product_sku")?String(params["product_sku"]).ascii():CharString();
+ CharString p_id = params.has("product_id") ? String(params["product_id"]).ascii() : CharString();
+ CharString p_sku = params.has("product_sku") ? String(params["product_sku"]).ascii() : CharString();
unsigned int request_id;
chdir(launch_dir_ptr);
int ret = paymentservice_purchase_request(params.has("product_sku") ? NULL : p_id.get_data(),
- params.has("product_sku") ? p_sku.get_data() : NULL,
- NULL, NULL, NULL, NULL, get_window_group_id(), &request_id);
+ params.has("product_sku") ? p_sku.get_data() : NULL,
+ NULL, NULL, NULL, NULL, get_window_group_id(), &request_id);
chdir("app/native");
if (ret != BPS_SUCCESS) {
@@ -76,8 +76,7 @@ Error PaymentService::purchase(Variant p_params) {
return OK;
};
-
-bool PaymentService::handle_event(bps_event_t* p_event) {
+bool PaymentService::handle_event(bps_event_t *p_event) {
if (bps_event_get_domain(p_event) != paymentservice_get_domain()) {
return false;
@@ -91,12 +90,12 @@ bool PaymentService::handle_event(bps_event_t* p_event) {
res = bps_event_get_code(p_event);
if (res == PURCHASE_RESPONSE) {
dict["type"] = "purchase";
- const char* pid = paymentservice_event_get_digital_good_id(p_event, 0);
- dict["product_id"] = String(pid?pid:"");
+ const char *pid = paymentservice_event_get_digital_good_id(p_event, 0);
+ dict["product_id"] = String(pid ? pid : "");
};
} else {
- const char* desc = paymentservice_event_get_error_text(p_event);
+ const char *desc = paymentservice_event_get_error_text(p_event);
if (strcmp(desc, "alreadyPurchased") == 0) {
dict["result"] = "ok";
} else {
@@ -142,9 +141,8 @@ PaymentService::PaymentService() {
#endif
};
-PaymentService::~PaymentService() {
+PaymentService::~PaymentService(){
};
-
#endif
diff --git a/platform/bb10/payment_service.h b/platform/bb10/payment_service.h
index b31a954ef8..d5b4cc3d60 100644
--- a/platform/bb10/payment_service.h
+++ b/platform/bb10/payment_service.h
@@ -46,24 +46,18 @@ class PaymentService : public Object {
List<Variant> pending_events;
public:
-
Error request_product_info(Variant p_params);
Error purchase(Variant p_params);
int get_pending_event_count();
Variant pop_pending_event();
- bool handle_event(bps_event_t* p_event);
+ bool handle_event(bps_event_t *p_event);
PaymentService();
~PaymentService();
};
-
-
#endif
-
#endif
-
-
diff --git a/platform/bb10/power_bb10.cpp b/platform/bb10/power_bb10.cpp
index 5cd84d6246..29c1fe370d 100644
--- a/platform/bb10/power_bb10.cpp
+++ b/platform/bb10/power_bb10.cpp
@@ -31,7 +31,6 @@
#include "core/error_macros.h"
-
bool PowerBB10::UpdatePowerInfo() {
return false;
@@ -40,8 +39,7 @@ bool PowerBB10::UpdatePowerInfo() {
PowerState PowerBB10::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN");
return POWERSTATE_UNKNOWN;
}
@@ -50,8 +48,7 @@ PowerState PowerBB10::get_power_state() {
int PowerBB10::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
@@ -60,17 +57,15 @@ int PowerBB10::get_power_seconds_left() {
int PowerBB10::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
}
-PowerBB10::PowerBB10() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+PowerBB10::PowerBB10()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
PowerBB10::~PowerBB10() {
}
-
diff --git a/platform/bb10/power_bb10.h b/platform/bb10/power_bb10.h
index 0e6eb53d03..6c13f6e997 100644
--- a/platform/bb10/power_bb10.h
+++ b/platform/bb10/power_bb10.h
@@ -37,6 +37,7 @@ private:
PowerState power_state;
bool UpdatePowerInfo();
+
public:
PowerBB10();
virtual ~PowerBB10();
diff --git a/platform/haiku/audio_driver_media_kit.cpp b/platform/haiku/audio_driver_media_kit.cpp
index bd485214c8..0f969d25ab 100644
--- a/platform/haiku/audio_driver_media_kit.cpp
+++ b/platform/haiku/audio_driver_media_kit.cpp
@@ -32,7 +32,7 @@
#include "global_config.h"
-int32_t* AudioDriverMediaKit::samples_in = NULL;
+int32_t *AudioDriverMediaKit::samples_in = NULL;
Error AudioDriverMediaKit::init() {
active = false;
@@ -54,12 +54,11 @@ Error AudioDriverMediaKit::init() {
format.buffer_size = buffer_size * sizeof(int32_t) * channels;
player = new BSoundPlayer(
- &format,
- "godot_sound_server",
- AudioDriverMediaKit::PlayBuffer,
- NULL,
- this
- );
+ &format,
+ "godot_sound_server",
+ AudioDriverMediaKit::PlayBuffer,
+ NULL,
+ this);
if (player->InitCheck() != B_OK) {
fprintf(stderr, "MediaKit ERR: can not create a BSoundPlayer instance\n");
@@ -72,9 +71,9 @@ Error AudioDriverMediaKit::init() {
return OK;
}
-void AudioDriverMediaKit::PlayBuffer(void* cookie, void* buffer, size_t size, const media_raw_audio_format& format) {
- AudioDriverMediaKit* ad = (AudioDriverMediaKit*) cookie;
- int32_t* buf = (int32_t*) buffer;
+void AudioDriverMediaKit::PlayBuffer(void *cookie, void *buffer, size_t size, const media_raw_audio_format &format) {
+ AudioDriverMediaKit *ad = (AudioDriverMediaKit *)cookie;
+ int32_t *buf = (int32_t *)buffer;
if (!ad->active) {
for (unsigned int i = 0; i < ad->buffer_size * ad->channels; i++) {
@@ -136,7 +135,6 @@ AudioDriverMediaKit::AudioDriverMediaKit() {
}
AudioDriverMediaKit::~AudioDriverMediaKit() {
-
}
#endif
diff --git a/platform/haiku/audio_driver_media_kit.h b/platform/haiku/audio_driver_media_kit.h
index ce760f8dd7..e9282c8471 100644
--- a/platform/haiku/audio_driver_media_kit.h
+++ b/platform/haiku/audio_driver_media_kit.h
@@ -30,19 +30,19 @@
#ifdef MEDIA_KIT_ENABLED
-#include "core/os/thread.h"
#include "core/os/mutex.h"
+#include "core/os/thread.h"
-#include <kernel/image.h> // needed for image_id
#include <SoundPlayer.h>
+#include <kernel/image.h> // needed for image_id
class AudioDriverMediaKit : public AudioDriver {
- Mutex* mutex;
+ Mutex *mutex;
- BSoundPlayer* player;
- static int32_t* samples_in;
+ BSoundPlayer *player;
+ static int32_t *samples_in;
- static void PlayBuffer(void* cookie, void* buffer, size_t size, const media_raw_audio_format& format);
+ static void PlayBuffer(void *cookie, void *buffer, size_t size, const media_raw_audio_format &format);
unsigned int mix_rate;
SpeakerMode speaker_mode;
@@ -52,8 +52,7 @@ class AudioDriverMediaKit : public AudioDriver {
bool active;
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "MediaKit";
};
diff --git a/platform/haiku/context_gl_haiku.cpp b/platform/haiku/context_gl_haiku.cpp
index c43e3f3928..f345928005 100644
--- a/platform/haiku/context_gl_haiku.cpp
+++ b/platform/haiku/context_gl_haiku.cpp
@@ -30,12 +30,12 @@
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
-ContextGL_Haiku::ContextGL_Haiku(HaikuDirectWindow* p_window) {
+ContextGL_Haiku::ContextGL_Haiku(HaikuDirectWindow *p_window) {
window = p_window;
uint32 type = BGL_RGB | BGL_DOUBLE | BGL_DEPTH;
view = new HaikuGLView(window->Bounds(), type);
-
+
use_vsync = false;
}
diff --git a/platform/haiku/context_gl_haiku.h b/platform/haiku/context_gl_haiku.h
index 1fd62e89ba..c0030fad41 100644
--- a/platform/haiku/context_gl_haiku.h
+++ b/platform/haiku/context_gl_haiku.h
@@ -38,13 +38,13 @@
class ContextGL_Haiku : public ContextGL {
private:
- HaikuGLView* view;
- HaikuDirectWindow* window;
-
+ HaikuGLView *view;
+ HaikuDirectWindow *window;
+
bool use_vsync;
public:
- ContextGL_Haiku(HaikuDirectWindow* p_window);
+ ContextGL_Haiku(HaikuDirectWindow *p_window);
~ContextGL_Haiku();
virtual Error initialize();
@@ -53,7 +53,7 @@ public:
virtual void swap_buffers();
virtual int get_window_width();
virtual int get_window_height();
-
+
virtual void set_use_vsync(bool p_use);
virtual bool is_using_vsync() const;
};
diff --git a/platform/haiku/godot_haiku.cpp b/platform/haiku/godot_haiku.cpp
index fccfa4336f..47cfbe55d7 100644
--- a/platform/haiku/godot_haiku.cpp
+++ b/platform/haiku/godot_haiku.cpp
@@ -29,10 +29,10 @@
#include "main/main.h"
#include "os_haiku.h"
-int main(int argc, char* argv[]) {
+int main(int argc, char *argv[]) {
OS_Haiku os;
- Error error = Main::setup(argv[0], argc-1, &argv[1]);
+ Error error = Main::setup(argv[0], argc - 1, &argv[1]);
if (error != OK) {
return 255;
}
diff --git a/platform/haiku/haiku_application.cpp b/platform/haiku/haiku_application.cpp
index 1f35c6f58e..f675d4216d 100644
--- a/platform/haiku/haiku_application.cpp
+++ b/platform/haiku/haiku_application.cpp
@@ -29,7 +29,5 @@
#include "haiku_application.h"
HaikuApplication::HaikuApplication()
- : BApplication("application/x-vnd.godot")
-{
-
+ : BApplication("application/x-vnd.godot") {
}
diff --git a/platform/haiku/haiku_application.h b/platform/haiku/haiku_application.h
index d85e6e4829..7fbce5dcbc 100644
--- a/platform/haiku/haiku_application.h
+++ b/platform/haiku/haiku_application.h
@@ -29,13 +29,12 @@
#ifndef HAIKU_APPLICATION_H
#define HAIKU_APPLICATION_H
-#include <kernel/image.h> // needed for image_id
#include <Application.h>
+#include <kernel/image.h> // needed for image_id
-class HaikuApplication : public BApplication
-{
+class HaikuApplication : public BApplication {
public:
- HaikuApplication();
+ HaikuApplication();
};
#endif
diff --git a/platform/haiku/haiku_direct_window.cpp b/platform/haiku/haiku_direct_window.cpp
index e7ff65e3ba..bc2dbb9b8f 100644
--- a/platform/haiku/haiku_direct_window.cpp
+++ b/platform/haiku/haiku_direct_window.cpp
@@ -28,43 +28,41 @@
/*************************************************************************/
#include <UnicodeChar.h>
-#include "main/main.h"
-#include "os/keyboard.h"
#include "haiku_direct_window.h"
#include "key_mapping_haiku.h"
+#include "main/main.h"
+#include "os/keyboard.h"
HaikuDirectWindow::HaikuDirectWindow(BRect p_frame)
- : BDirectWindow(p_frame, "Godot", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE)
-{
+ : BDirectWindow(p_frame, "Godot", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE) {
last_mouse_pos_valid = false;
last_buttons_state = 0;
last_button_mask = 0;
last_key_modifier_state = 0;
}
-
HaikuDirectWindow::~HaikuDirectWindow() {
delete update_runner;
}
-void HaikuDirectWindow::SetHaikuGLView(HaikuGLView* p_view) {
+void HaikuDirectWindow::SetHaikuGLView(HaikuGLView *p_view) {
view = p_view;
}
void HaikuDirectWindow::StartMessageRunner() {
update_runner = new BMessageRunner(BMessenger(this),
- new BMessage(REDRAW_MSG), 1000000/30 /* 30 fps */);
+ new BMessage(REDRAW_MSG), 1000000 / 30 /* 30 fps */);
}
void HaikuDirectWindow::StopMessageRunner() {
delete update_runner;
}
-void HaikuDirectWindow::SetInput(InputDefault* p_input) {
+void HaikuDirectWindow::SetInput(InputDefault *p_input) {
input = p_input;
}
-void HaikuDirectWindow::SetMainLoop(MainLoop* p_main_loop) {
+void HaikuDirectWindow::SetMainLoop(MainLoop *p_main_loop) {
main_loop = p_main_loop;
}
@@ -73,12 +71,12 @@ bool HaikuDirectWindow::QuitRequested() {
return false;
}
-void HaikuDirectWindow::DirectConnected(direct_buffer_info* info) {
+void HaikuDirectWindow::DirectConnected(direct_buffer_info *info) {
view->DirectConnected(info);
view->EnableDirectMode(true);
}
-void HaikuDirectWindow::MessageReceived(BMessage* message) {
+void HaikuDirectWindow::MessageReceived(BMessage *message) {
switch (message->what) {
case REDRAW_MSG:
if (Main::iteration() == true) {
@@ -92,7 +90,7 @@ void HaikuDirectWindow::MessageReceived(BMessage* message) {
}
}
-void HaikuDirectWindow::DispatchMessage(BMessage* message, BHandler* handler) {
+void HaikuDirectWindow::DispatchMessage(BMessage *message, BHandler *handler) {
switch (message->what) {
case B_MOUSE_DOWN:
case B_MOUSE_UP:
@@ -133,7 +131,7 @@ void HaikuDirectWindow::DispatchMessage(BMessage* message, BHandler* handler) {
}
}
-void HaikuDirectWindow::HandleMouseButton(BMessage* message) {
+void HaikuDirectWindow::HandleMouseButton(BMessage *message) {
BPoint where;
if (message->FindPoint("where", &where) != B_OK) {
return;
@@ -185,14 +183,14 @@ void HaikuDirectWindow::HandleMouseButton(BMessage* message) {
int32 clicks = message->FindInt32("clicks");
if (clicks > 1) {
- mouse_event.mouse_button.doubleclick=true;
+ mouse_event.mouse_button.doubleclick = true;
}
}
input->parse_input_event(mouse_event);
}
-void HaikuDirectWindow::HandleMouseMoved(BMessage* message) {
+void HaikuDirectWindow::HandleMouseMoved(BMessage *message) {
BPoint where;
if (message->FindPoint("where", &where) != B_OK) {
return;
@@ -232,7 +230,7 @@ void HaikuDirectWindow::HandleMouseMoved(BMessage* message) {
input->parse_input_event(motion_event);
}
-void HaikuDirectWindow::HandleMouseWheelChanged(BMessage* message) {
+void HaikuDirectWindow::HandleMouseWheelChanged(BMessage *message) {
float wheel_delta_y = 0;
if (message->FindFloat("be:wheel_delta_y", &wheel_delta_y) != B_OK) {
return;
@@ -259,7 +257,7 @@ void HaikuDirectWindow::HandleMouseWheelChanged(BMessage* message) {
input->parse_input_event(mouse_event);
}
-void HaikuDirectWindow::HandleKeyboardEvent(BMessage* message) {
+void HaikuDirectWindow::HandleKeyboardEvent(BMessage *message) {
int32 raw_char = 0;
int32 key = 0;
int32 modifiers = 0;
@@ -286,21 +284,21 @@ void HaikuDirectWindow::HandleKeyboardEvent(BMessage* message) {
event.key.echo = message->HasInt32("be:key_repeat");
event.key.unicode = 0;
- const char* bytes = NULL;
+ const char *bytes = NULL;
if (message->FindString("bytes", &bytes) == B_OK) {
event.key.unicode = BUnicodeChar::FromUTF8(&bytes);
}
//make it consistent accross platforms.
- if (event.key.scancode==KEY_BACKTAB) {
- event.key.scancode=KEY_TAB;
- event.key.mod.shift=true;
+ if (event.key.scancode == KEY_BACKTAB) {
+ event.key.scancode = KEY_TAB;
+ event.key.mod.shift = true;
}
input->parse_input_event(event);
}
-void HaikuDirectWindow::HandleKeyboardModifierEvent(BMessage* message) {
+void HaikuDirectWindow::HandleKeyboardModifierEvent(BMessage *message) {
int32 old_modifiers = 0;
int32 modifiers = 0;
@@ -327,7 +325,7 @@ void HaikuDirectWindow::HandleKeyboardModifierEvent(BMessage* message) {
input->parse_input_event(event);
}
-void HaikuDirectWindow::HandleWindowResized(BMessage* message) {
+void HaikuDirectWindow::HandleWindowResized(BMessage *message) {
int32 width = 0;
int32 height = 0;
diff --git a/platform/haiku/haiku_direct_window.h b/platform/haiku/haiku_direct_window.h
index 49785f79cb..7fcea7a6f6 100644
--- a/platform/haiku/haiku_direct_window.h
+++ b/platform/haiku/haiku_direct_window.h
@@ -29,8 +29,8 @@
#ifndef HAIKU_DIRECT_WINDOW_H
#define HAIKU_DIRECT_WINDOW_H
-#include <kernel/image.h> // needed for image_id
#include <DirectWindow.h>
+#include <kernel/image.h> // needed for image_id
#include "core/os/os.h"
#include "main/input_default.h"
@@ -41,8 +41,7 @@
#define LOCKGL_MSG 'glck'
#define UNLOCKGL_MSG 'ulck'
-class HaikuDirectWindow : public BDirectWindow
-{
+class HaikuDirectWindow : public BDirectWindow {
private:
unsigned int event_id;
Point2i last_mouse_position;
@@ -50,19 +49,19 @@ private:
uint32 last_buttons_state;
uint32 last_key_modifier_state;
int last_button_mask;
- OS::VideoMode* current_video_mode;
+ OS::VideoMode *current_video_mode;
- MainLoop* main_loop;
- InputDefault* input;
- HaikuGLView* view;
- BMessageRunner* update_runner;
+ MainLoop *main_loop;
+ InputDefault *input;
+ HaikuGLView *view;
+ BMessageRunner *update_runner;
- void HandleMouseButton(BMessage* message);
- void HandleMouseMoved(BMessage* message);
- void HandleMouseWheelChanged(BMessage* message);
- void HandleWindowResized(BMessage* message);
- void HandleKeyboardEvent(BMessage* message);
- void HandleKeyboardModifierEvent(BMessage* message);
+ void HandleMouseButton(BMessage *message);
+ void HandleMouseMoved(BMessage *message);
+ void HandleMouseWheelChanged(BMessage *message);
+ void HandleWindowResized(BMessage *message);
+ void HandleKeyboardEvent(BMessage *message);
+ void HandleKeyboardModifierEvent(BMessage *message);
inline InputModifierState GetKeyModifierState(uint32 p_state);
inline int GetMouseButtonState(uint32 p_state);
@@ -70,16 +69,16 @@ public:
HaikuDirectWindow(BRect p_frame);
~HaikuDirectWindow();
- void SetHaikuGLView(HaikuGLView* p_view);
+ void SetHaikuGLView(HaikuGLView *p_view);
void StartMessageRunner();
void StopMessageRunner();
- void SetInput(InputDefault* p_input);
- void SetMainLoop(MainLoop* p_main_loop);
- inline void SetVideoMode(OS::VideoMode* video_mode) { current_video_mode = video_mode; };
+ void SetInput(InputDefault *p_input);
+ void SetMainLoop(MainLoop *p_main_loop);
+ inline void SetVideoMode(OS::VideoMode *video_mode) { current_video_mode = video_mode; };
virtual bool QuitRequested();
- virtual void DirectConnected(direct_buffer_info* info);
- virtual void MessageReceived(BMessage* message);
- virtual void DispatchMessage(BMessage* message, BHandler* handler);
+ virtual void DirectConnected(direct_buffer_info *info);
+ virtual void MessageReceived(BMessage *message);
+ virtual void DispatchMessage(BMessage *message, BHandler *handler);
inline Point2i GetLastMousePosition() { return last_mouse_position; };
inline int GetLastButtonMask() { return last_button_mask; };
diff --git a/platform/haiku/haiku_gl_view.cpp b/platform/haiku/haiku_gl_view.cpp
index 66c143ea67..ded15e12a7 100644
--- a/platform/haiku/haiku_gl_view.cpp
+++ b/platform/haiku/haiku_gl_view.cpp
@@ -26,12 +26,11 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "main/main.h"
#include "haiku_gl_view.h"
+#include "main/main.h"
HaikuGLView::HaikuGLView(BRect frame, uint32 type)
- : BGLView(frame, "GodotGLView", B_FOLLOW_ALL_SIDES, 0, type)
-{
+ : BGLView(frame, "GodotGLView", B_FOLLOW_ALL_SIDES, 0, type) {
}
void HaikuGLView::AttachedToWindow(void) {
diff --git a/platform/haiku/haiku_gl_view.h b/platform/haiku/haiku_gl_view.h
index 6d64aab42e..f06bc64794 100644
--- a/platform/haiku/haiku_gl_view.h
+++ b/platform/haiku/haiku_gl_view.h
@@ -29,11 +29,10 @@
#ifndef HAIKU_GL_VIEW_H
#define HAIKU_GL_VIEW_H
-#include <kernel/image.h> // needed for image_id
#include <GLView.h>
+#include <kernel/image.h> // needed for image_id
-class HaikuGLView : public BGLView
-{
+class HaikuGLView : public BGLView {
public:
HaikuGLView(BRect frame, uint32 type);
virtual void AttachedToWindow(void);
diff --git a/platform/haiku/key_mapping_haiku.cpp b/platform/haiku/key_mapping_haiku.cpp
index f41a77c3fb..1bc3467914 100644
--- a/platform/haiku/key_mapping_haiku.cpp
+++ b/platform/haiku/key_mapping_haiku.cpp
@@ -136,7 +136,7 @@ static _HaikuTranslatePair _hb_to_keycode[] = {
{ KEY_Y, (0x79) },
{ KEY_Z, (0x7A) },
-/*
+ /*
{ KEY_PLAY, VK_PLAY},// (0xFA)
{ KEY_STANDBY,VK_SLEEP },//(0x5F)
{ KEY_BACK,VK_BROWSER_BACK},// (0xA6)
@@ -177,22 +177,48 @@ static _HaikuTranslatePair _hb_to_keycode[] = {
};
unsigned int KeyMappingHaiku::get_keysym(int32 raw_char, int32 key) {
- if (raw_char == B_INSERT && key == 0x64) { return KEY_KP_0; }
- if (raw_char == B_END && key == 0x58) { return KEY_KP_1; }
- if (raw_char == B_DOWN_ARROW && key == 0x59) { return KEY_KP_2; }
- if (raw_char == B_PAGE_DOWN && key == 0x5A) { return KEY_KP_3; }
- if (raw_char == B_LEFT_ARROW && key == 0x48) { return KEY_KP_4; }
- if (raw_char == 0x35 && key == 0x49) { return KEY_KP_5; }
- if (raw_char == B_RIGHT_ARROW && key == 0x4A) { return KEY_KP_6; }
- if (raw_char == B_HOME && key == 0x37) { return KEY_KP_7; }
- if (raw_char == B_UP_ARROW && key == 0x38) { return KEY_KP_8; }
- if (raw_char == B_PAGE_UP && key == 0x39) { return KEY_KP_9; }
- if (raw_char == 0x2F && key == 0x23) { return KEY_KP_DIVIDE; }
- if (raw_char == 0x2D && key == 0x25) { return KEY_KP_SUBTRACT; }
- if (raw_char == B_DELETE && key == 0x65) { return KEY_KP_PERIOD; }
+ if (raw_char == B_INSERT && key == 0x64) {
+ return KEY_KP_0;
+ }
+ if (raw_char == B_END && key == 0x58) {
+ return KEY_KP_1;
+ }
+ if (raw_char == B_DOWN_ARROW && key == 0x59) {
+ return KEY_KP_2;
+ }
+ if (raw_char == B_PAGE_DOWN && key == 0x5A) {
+ return KEY_KP_3;
+ }
+ if (raw_char == B_LEFT_ARROW && key == 0x48) {
+ return KEY_KP_4;
+ }
+ if (raw_char == 0x35 && key == 0x49) {
+ return KEY_KP_5;
+ }
+ if (raw_char == B_RIGHT_ARROW && key == 0x4A) {
+ return KEY_KP_6;
+ }
+ if (raw_char == B_HOME && key == 0x37) {
+ return KEY_KP_7;
+ }
+ if (raw_char == B_UP_ARROW && key == 0x38) {
+ return KEY_KP_8;
+ }
+ if (raw_char == B_PAGE_UP && key == 0x39) {
+ return KEY_KP_9;
+ }
+ if (raw_char == 0x2F && key == 0x23) {
+ return KEY_KP_DIVIDE;
+ }
+ if (raw_char == 0x2D && key == 0x25) {
+ return KEY_KP_SUBTRACT;
+ }
+ if (raw_char == B_DELETE && key == 0x65) {
+ return KEY_KP_PERIOD;
+ }
if (raw_char == 0x10) {
- for(int i = 0; _fn_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
+ for (int i = 0; _fn_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
if (_fn_to_keycode[i].keycode == key) {
return _fn_to_keycode[i].keysym;
}
@@ -201,7 +227,7 @@ unsigned int KeyMappingHaiku::get_keysym(int32 raw_char, int32 key) {
return KEY_UNKNOWN;
}
- for(int i = 0; _hb_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
+ for (int i = 0; _hb_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
if (_hb_to_keycode[i].keycode == raw_char) {
return _hb_to_keycode[i].keysym;
}
@@ -211,7 +237,7 @@ unsigned int KeyMappingHaiku::get_keysym(int32 raw_char, int32 key) {
}
unsigned int KeyMappingHaiku::get_modifier_keysym(int32 key) {
- for(int i = 0; _mod_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
+ for (int i = 0; _mod_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
if ((_mod_to_keycode[i].keycode & key) != 0) {
return _mod_to_keycode[i].keysym;
}
diff --git a/platform/haiku/key_mapping_haiku.h b/platform/haiku/key_mapping_haiku.h
index 81f5569fd0..0f2e2e64bd 100644
--- a/platform/haiku/key_mapping_haiku.h
+++ b/platform/haiku/key_mapping_haiku.h
@@ -29,9 +29,8 @@
#ifndef KEY_MAPPING_HAIKU_H
#define KEY_MAPPING_HAIKU_H
-class KeyMappingHaiku
-{
- KeyMappingHaiku() {};
+class KeyMappingHaiku {
+ KeyMappingHaiku(){};
public:
static unsigned int get_keysym(int32 raw_char, int32 key);
diff --git a/platform/haiku/os_haiku.cpp b/platform/haiku/os_haiku.cpp
index b9b95ddacd..0853fac393 100644
--- a/platform/haiku/os_haiku.cpp
+++ b/platform/haiku/os_haiku.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include <Screen.h>
-#include "servers/visual/visual_server_raster.h"
-#include "servers/visual/visual_server_wrap_mt.h"
#include "drivers/gles2/rasterizer_gles2.h"
#include "servers/physics/physics_server_sw.h"
+#include "servers/visual/visual_server_raster.h"
+#include "servers/visual/visual_server_wrap_mt.h"
//#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
#include "main/main.h"
#include "os_haiku.h"
-
OS_Haiku::OS_Haiku() {
#ifdef MEDIA_KIT_ENABLED
AudioDriverManager::add_driver(&driver_media_kit);
@@ -53,8 +52,8 @@ void OS_Haiku::run() {
context_gl->release_current();
// TODO: clean up
- BMessenger* bms = new BMessenger(window);
- BMessage* msg = new BMessage();
+ BMessenger *bms = new BMessenger(window);
+ BMessage *msg = new BMessage();
bms->SendMessage(LOCKGL_MSG, msg);
window->StartMessageRunner();
@@ -76,7 +75,7 @@ int OS_Haiku::get_video_driver_count() const {
return 1;
}
-const char* OS_Haiku::get_video_driver_name(int p_driver) const {
+const char *OS_Haiku::get_video_driver_name(int p_driver) const {
return "GLES2";
}
@@ -84,7 +83,7 @@ OS::VideoMode OS_Haiku::get_default_video_mode() const {
return OS::VideoMode(800, 600, false);
}
-void OS_Haiku::initialize(const VideoMode& p_desired, int p_video_driver, int p_audio_driver) {
+void OS_Haiku::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
main_loop = NULL;
current_video_mode = p_desired;
@@ -143,8 +142,8 @@ void OS_Haiku::initialize(const VideoMode& p_desired, int p_video_driver, int p_
if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
ERR_PRINT("Initializing audio failed.");
}
-
- power_manager = memnew( PowerHaiku );
+
+ power_manager = memnew(PowerHaiku);
}
void OS_Haiku::finalize() {
@@ -171,13 +170,13 @@ void OS_Haiku::finalize() {
#endif
}
-void OS_Haiku::set_main_loop(MainLoop* p_main_loop) {
+void OS_Haiku::set_main_loop(MainLoop *p_main_loop) {
main_loop = p_main_loop;
input->set_main_loop(p_main_loop);
window->SetMainLoop(p_main_loop);
}
-MainLoop* OS_Haiku::get_main_loop() const {
+MainLoop *OS_Haiku::get_main_loop() const {
return main_loop;
}
@@ -235,7 +234,7 @@ void OS_Haiku::set_current_screen(int p_screen) {
Point2 OS_Haiku::get_screen_position(int p_screen) const {
// TODO: make this work with the p_screen parameter
- BScreen* screen = new BScreen(window);
+ BScreen *screen = new BScreen(window);
BRect frame = screen->Frame();
delete screen;
return Point2i(frame.left, frame.top);
@@ -243,13 +242,13 @@ Point2 OS_Haiku::get_screen_position(int p_screen) const {
Size2 OS_Haiku::get_screen_size(int p_screen) const {
// TODO: make this work with the p_screen parameter
- BScreen* screen = new BScreen(window);
+ BScreen *screen = new BScreen(window);
BRect frame = screen->Frame();
delete screen;
return Size2i(frame.IntegerWidth() + 1, frame.IntegerHeight() + 1);
}
-void OS_Haiku::set_window_title(const String& p_title) {
+void OS_Haiku::set_window_title(const String &p_title) {
window->SetTitle(p_title.utf8().get_data());
}
@@ -269,7 +268,7 @@ Point2 OS_Haiku::get_window_position() const {
return Point2i(point.x, point.y);
}
-void OS_Haiku::set_window_position(const Point2& p_position) {
+void OS_Haiku::set_window_position(const Point2 &p_position) {
window->MoveTo(p_position.x, p_position.y);
}
@@ -316,7 +315,7 @@ bool OS_Haiku::is_window_maximized() const {
return !window->IsMinimized();
}
-void OS_Haiku::set_video_mode(const VideoMode& p_video_mode, int p_screen) {
+void OS_Haiku::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
ERR_PRINT("set_video_mode() NOT IMPLEMENTED");
}
diff --git a/platform/haiku/os_haiku.h b/platform/haiku/os_haiku.h
index 2c84e95ac3..827814c7e9 100644
--- a/platform/haiku/os_haiku.h
+++ b/platform/haiku/os_haiku.h
@@ -29,52 +29,51 @@
#ifndef OS_HAIKU_H
#define OS_HAIKU_H
-#include "drivers/unix/os_unix.h"
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
-#include "servers/physics_server.h"
-#include "servers/physics_2d/physics_2d_server_sw.h"
-#include "servers/audio_server.h"
-#include "main/input_default.h"
#include "audio_driver_media_kit.h"
#include "context_gl_haiku.h"
+#include "drivers/unix/os_unix.h"
#include "haiku_application.h"
#include "haiku_direct_window.h"
+#include "main/input_default.h"
#include "power_haiku.h"
-
+#include "servers/audio_server.h"
+#include "servers/physics_2d/physics_2d_server_sw.h"
+#include "servers/physics_server.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
class OS_Haiku : public OS_Unix {
private:
- HaikuApplication* app;
- HaikuDirectWindow* window;
- MainLoop* main_loop;
- InputDefault* input;
- Rasterizer* rasterizer;
- VisualServer* visual_server;
+ HaikuApplication *app;
+ HaikuDirectWindow *window;
+ MainLoop *main_loop;
+ InputDefault *input;
+ Rasterizer *rasterizer;
+ VisualServer *visual_server;
VideoMode current_video_mode;
- PhysicsServer* physics_server;
- Physics2DServer* physics_2d_server;
- PowerHaiku* power_manager;
+ PhysicsServer *physics_server;
+ Physics2DServer *physics_2d_server;
+ PowerHaiku *power_manager;
#ifdef MEDIA_KIT_ENABLED
AudioDriverMediaKit driver_media_kit;
#endif
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
- ContextGL_Haiku* context_gl;
+ ContextGL_Haiku *context_gl;
#endif
virtual void delete_main_loop();
protected:
virtual int get_video_driver_count() const;
- virtual const char* get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
- virtual void initialize(const VideoMode& p_desired, int p_video_driver, int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
virtual void finalize();
- virtual void set_main_loop(MainLoop* p_main_loop);
+ virtual void set_main_loop(MainLoop *p_main_loop);
public:
OS_Haiku();
@@ -82,7 +81,7 @@ public:
virtual String get_name();
- virtual MainLoop* get_main_loop() const;
+ virtual MainLoop *get_main_loop() const;
virtual bool can_draw() const;
virtual void release_rendering_thread();
@@ -96,13 +95,13 @@ public:
virtual int get_screen_count() const;
virtual int get_current_screen() const;
virtual void set_current_screen(int p_screen);
- virtual Point2 get_screen_position(int p_screen=0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
- virtual void set_window_title(const String& p_title);
+ virtual Point2 get_screen_position(int p_screen = 0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
+ virtual void set_window_title(const String &p_title);
virtual Size2 get_window_size() const;
virtual void set_window_size(const Size2 p_size);
virtual Point2 get_window_position() const;
- virtual void set_window_position(const Point2& p_position);
+ virtual void set_window_position(const Point2 &p_position);
virtual void set_window_fullscreen(bool p_enabled);
virtual bool is_window_fullscreen() const;
virtual void set_window_resizable(bool p_enabled);
@@ -112,11 +111,11 @@ public:
virtual void set_window_maximized(bool p_enabled);
virtual bool is_window_maximized() const;
- virtual void set_video_mode(const VideoMode& p_video_mode, int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual String get_executable_path() const;
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
diff --git a/platform/haiku/power_haiku.cpp b/platform/haiku/power_haiku.cpp
index 6a54c7b360..d70aad9d5f 100644
--- a/platform/haiku/power_haiku.cpp
+++ b/platform/haiku/power_haiku.cpp
@@ -39,8 +39,7 @@ bool PowerHaiku::UpdatePowerInfo() {
PowerState PowerHaiku::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN");
return POWERSTATE_UNKNOWN;
}
@@ -49,8 +48,7 @@ PowerState PowerHaiku::get_power_state() {
int PowerX11::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
@@ -59,15 +57,14 @@ int PowerX11::get_power_seconds_left() {
int PowerX11::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
}
-PowerHaiku::PowerHaiku() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+PowerHaiku::PowerHaiku()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
PowerHaiku::~PowerHaiku() {
diff --git a/platform/haiku/power_haiku.h b/platform/haiku/power_haiku.h
index b46cfa3454..8e7b050cd6 100644
--- a/platform/haiku/power_haiku.h
+++ b/platform/haiku/power_haiku.h
@@ -37,6 +37,7 @@ private:
PowerState power_state;
bool UpdatePowerInfo();
+
public:
PowerHaiku();
virtual ~PowerHaiku();
diff --git a/platform/iphone/app_delegate.h b/platform/iphone/app_delegate.h
index 1b2ca42ab6..eaa74946ee 100644
--- a/platform/iphone/app_delegate.h
+++ b/platform/iphone/app_delegate.h
@@ -26,19 +26,19 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#import <UIKit/UIKit.h>
#import "gl_view.h"
#import "view_controller.h"
+#import <UIKit/UIKit.h>
#import <CoreMotion/CoreMotion.h>
@interface AppDelegate : NSObject <UIApplicationDelegate, GLViewDelegate> {
//@property (strong, nonatomic) UIWindow *window;
- ViewController* view_controller;
+ ViewController *view_controller;
};
-@property (strong, nonatomic) UIWindow *window;
+@property(strong, nonatomic) UIWindow *window;
-+ (ViewController*)getViewController;
++ (ViewController *)getViewController;
@end
diff --git a/platform/iphone/audio_driver_iphone.cpp b/platform/iphone/audio_driver_iphone.cpp
index eda3897841..eff91fa40f 100644
--- a/platform/iphone/audio_driver_iphone.cpp
+++ b/platform/iphone/audio_driver_iphone.cpp
@@ -41,9 +41,9 @@ Error AudioDriverIphone::init() {
strdesc.mFramesPerPacket = 1;
strdesc.mBitsPerChannel = 16;
strdesc.mBytesPerFrame =
- strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
+ strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
strdesc.mBytesPerPacket =
- strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
+ strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
OSStatus result = noErr;
AURenderCallbackStruct callback;
@@ -55,7 +55,7 @@ Error AudioDriverIphone::init() {
zeromem(&desc, sizeof(desc));
desc.componentType = kAudioUnitType_Output;
- desc.componentSubType = kAudioUnitSubType_RemoteIO; /* !!! FIXME: ? */
+ desc.componentSubType = kAudioUnitSubType_RemoteIO; /* !!! FIXME: ? */
comp = AudioComponentFindNext(NULL, &desc);
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
@@ -64,16 +64,16 @@ Error AudioDriverIphone::init() {
ERR_FAIL_COND_V(comp == NULL, FAILED);
result = AudioUnitSetProperty(audio_unit,
- kAudioUnitProperty_StreamFormat,
- scope, bus, &strdesc, sizeof(strdesc));
+ kAudioUnitProperty_StreamFormat,
+ scope, bus, &strdesc, sizeof(strdesc));
ERR_FAIL_COND_V(result != noErr, FAILED);
zeromem(&callback, sizeof(AURenderCallbackStruct));
callback.inputProc = &AudioDriverIphone::output_callback;
callback.inputProcRefCon = this;
result = AudioUnitSetProperty(audio_unit,
- kAudioUnitProperty_SetRenderCallback,
- scope, bus, &callback, sizeof(callback));
+ kAudioUnitProperty_SetRenderCallback,
+ scope, bus, &callback, sizeof(callback));
ERR_FAIL_COND_V(result != noErr, FAILED);
result = AudioUnitInitialize(audio_unit);
@@ -90,14 +90,13 @@ Error AudioDriverIphone::init() {
};
OSStatus AudioDriverIphone::output_callback(void *inRefCon,
- AudioUnitRenderActionFlags * ioActionFlags,
- const AudioTimeStamp * inTimeStamp,
- UInt32 inBusNumber, UInt32 inNumberFrames,
- AudioBufferList * ioData) {
-
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList *ioData) {
AudioBuffer *abuf;
- AudioDriverIphone* ad = (AudioDriverIphone*)inRefCon;
+ AudioDriverIphone *ad = (AudioDriverIphone *)inRefCon;
bool mix = true;
@@ -107,7 +106,6 @@ OSStatus AudioDriverIphone::output_callback(void *inRefCon,
mix = ad->mutex->try_lock() == OK;
};
-
if (!mix) {
for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
abuf = &ioData->mBuffers[i];
@@ -122,7 +120,7 @@ OSStatus AudioDriverIphone::output_callback(void *inRefCon,
abuf = &ioData->mBuffers[i];
frames_left = inNumberFrames;
- int16_t* out = (int16_t*)abuf->mData;
+ int16_t *out = (int16_t *)abuf->mData;
while (frames_left) {
@@ -131,9 +129,9 @@ OSStatus AudioDriverIphone::output_callback(void *inRefCon,
ad->audio_server_process(frames, ad->samples_in);
//ad->unlock();
- for(int i = 0; i < frames * ad->channels; i++) {
+ for (int i = 0; i < frames * ad->channels; i++) {
- out[i] = ad->samples_in[i]>>16;
+ out[i] = ad->samples_in[i] >> 16;
}
frames_left -= frames;
@@ -175,12 +173,11 @@ void AudioDriverIphone::finish() {
memdelete_arr(samples_in);
};
-
AudioDriverIphone::AudioDriverIphone() {
- mutex=Mutex::create();//NULL;
+ mutex = Mutex::create(); //NULL;
};
-AudioDriverIphone::~AudioDriverIphone() {
+AudioDriverIphone::~AudioDriverIphone(){
};
diff --git a/platform/iphone/audio_driver_iphone.h b/platform/iphone/audio_driver_iphone.h
index 4c0cbfcb22..8a0d92e070 100644
--- a/platform/iphone/audio_driver_iphone.h
+++ b/platform/iphone/audio_driver_iphone.h
@@ -38,19 +38,17 @@ class AudioDriverIphone : public AudioDriver {
Mutex *mutex;
int channels;
- int32_t* samples_in;
- int buffer_frames;
+ int32_t *samples_in;
+ int buffer_frames;
static OSStatus output_callback(void *inRefCon,
- AudioUnitRenderActionFlags * ioActionFlags,
- const AudioTimeStamp * inTimeStamp,
- UInt32 inBusNumber, UInt32 inNumberFrames,
- AudioBufferList * ioData);
-
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList *ioData);
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "IPhone";
};
@@ -65,4 +63,3 @@ public:
AudioDriverIphone();
~AudioDriverIphone();
};
-
diff --git a/platform/iphone/game_center.h b/platform/iphone/game_center.h
index abbeaaf86f..a732a97a4c 100644
--- a/platform/iphone/game_center.h
+++ b/platform/iphone/game_center.h
@@ -37,7 +37,7 @@ class GameCenter : public Object {
GDCLASS(GameCenter, Object);
- static GameCenter* instance;
+ static GameCenter *instance;
static void _bind_methods();
List<Variant> pending_events;
@@ -45,7 +45,6 @@ class GameCenter : public Object {
bool connected;
public:
-
Error connect();
bool is_connected();
@@ -61,13 +60,12 @@ public:
int get_pending_event_count();
Variant pop_pending_event();
- static GameCenter* get_singleton();
+ static GameCenter *get_singleton();
GameCenter();
~GameCenter();
};
-
#endif
#endif
diff --git a/platform/iphone/gl_view.h b/platform/iphone/gl_view.h
index 49e7810f08..555e34a895 100755..100644
--- a/platform/iphone/gl_view.h
+++ b/platform/iphone/gl_view.h
@@ -27,18 +27,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#import <UIKit/UIKit.h>
+#import <AVFoundation/AVFoundation.h>
+#import <MediaPlayer/MediaPlayer.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
-#import <MediaPlayer/MediaPlayer.h>
-#import <AVFoundation/AVFoundation.h>
+#import <UIKit/UIKit.h>
@protocol GLViewDelegate;
-@interface GLView : UIView<UIKeyInput>
-{
- @private
+@interface GLView : UIView <UIKeyInput> {
+@private
// The pixel dimensions of the backbuffer
GLint backingWidth;
GLint backingHeight;
@@ -83,9 +82,9 @@
@property(strong, nonatomic) MPMoviePlayerController *moviePlayerController;
@property(strong, nonatomic) UIWindow *backgroundWindow;
--(void)startAnimation;
--(void)stopAnimation;
--(void)drawView;
+- (void)startAnimation;
+- (void)stopAnimation;
+- (void)drawView;
- (BOOL)canBecomeFirstResponder;
@@ -99,23 +98,23 @@
- (BOOL)createFramebuffer;
- (void)destroyFramebuffer;
-- (void)audioRouteChangeListenerCallback:(NSNotification*)notification;
+- (void)audioRouteChangeListenerCallback:(NSNotification *)notification;
@property NSTimeInterval animationInterval;
@property(nonatomic, assign) BOOL useCADisplayLink;
@end
-@protocol GLViewDelegate<NSObject>
+@protocol GLViewDelegate <NSObject>
@required
// Draw with OpenGL ES
--(void)drawView:(GLView*)view;
+- (void)drawView:(GLView *)view;
@optional
// Called whenever you need to do some initialization before rendering.
--(void)setupView:(GLView*)view;
+- (void)setupView:(GLView *)view;
@end
diff --git a/platform/iphone/globals/global_defaults.cpp b/platform/iphone/globals/global_defaults.cpp
index bf716c36f0..b3067dc0c4 100755..100644
--- a/platform/iphone/globals/global_defaults.cpp
+++ b/platform/iphone/globals/global_defaults.cpp
@@ -29,7 +29,6 @@
#include "global_defaults.h"
#include "global_config.h"
-
void register_iphone_global_defaults() {
/*GLOBAL_DEF("rasterizer.iOS/use_fragment_lighting",false);
diff --git a/platform/iphone/godot_iphone.cpp b/platform/iphone/godot_iphone.cpp
index 27804e5c03..626c78fdf4 100644
--- a/platform/iphone/godot_iphone.cpp
+++ b/platform/iphone/godot_iphone.cpp
@@ -26,36 +26,36 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "os_iphone.h"
#include "main/main.h"
+#include "os_iphone.h"
#include <stdio.h>
-#include <unistd.h>
#include <string.h>
+#include <unistd.h>
-static OSIPhone* os = NULL;
+static OSIPhone *os = NULL;
extern "C" {
-int add_path(int p_argc, char** p_args);
-int add_cmdline(int p_argc, char** p_args);
+int add_path(int p_argc, char **p_args);
+int add_cmdline(int p_argc, char **p_args);
};
-int iphone_main(int, int, int, char**);
+int iphone_main(int, int, int, char **);
-int iphone_main(int width, int height, int argc, char** argv) {
+int iphone_main(int width, int height, int argc, char **argv) {
int len = strlen(argv[0]);
- while (len--){
+ while (len--) {
if (argv[0][len] == '/') break;
}
- if (len>=0) {
- char path[512];
- memcpy(path, argv[0], len>sizeof(path)?sizeof(path):len);
- path[len]=0;
- printf("Path: %s\n", path);
- chdir(path);
+ if (len >= 0) {
+ char path[512];
+ memcpy(path, argv[0], len > sizeof(path) ? sizeof(path) : len);
+ path[len] = 0;
+ printf("Path: %s\n", path);
+ chdir(path);
}
printf("godot_iphone %s\n", argv[0]);
@@ -64,8 +64,8 @@ int iphone_main(int width, int height, int argc, char** argv) {
printf("cwd %s\n", cwd);
os = new OSIPhone(width, height);
- char* fargv[64];
- for (int i=0; i<argc; i++) {
+ char *fargv[64];
+ for (int i = 0; i < argc; i++) {
fargv[i] = argv[i];
};
fargv[argc] = NULL;
@@ -73,15 +73,14 @@ int iphone_main(int width, int height, int argc, char** argv) {
argc = add_cmdline(argc, fargv);
printf("os created\n");
- Error err = Main::setup(fargv[0], argc - 1, &fargv[1], false);
+ Error err = Main::setup(fargv[0], argc - 1, &fargv[1], false);
printf("setup %i\n", err);
- if (err!=OK)
+ if (err != OK)
return 255;
return 0;
};
-
void iphone_finish() {
printf("iphone_finish\n");
diff --git a/platform/iphone/icloud.h b/platform/iphone/icloud.h
index ba50c4be15..743a9a5de3 100644
--- a/platform/iphone/icloud.h
+++ b/platform/iphone/icloud.h
@@ -33,18 +33,16 @@
#include "core/object.h"
-
class ICloud : public Object {
GDCLASS(ICloud, Object);
- static ICloud* instance;
+ static ICloud *instance;
static void _bind_methods();
List<Variant> pending_events;
public:
-
Error remove_key(Variant p_param);
Variant set_key_values(Variant p_param);
Variant get_key_value(Variant p_param);
@@ -54,13 +52,12 @@ public:
int get_pending_event_count();
Variant pop_pending_event();
- static ICloud* get_singleton();
+ static ICloud *get_singleton();
ICloud();
~ICloud();
};
-
#endif
#endif
diff --git a/platform/iphone/in_app_store.h b/platform/iphone/in_app_store.h
index 59a745c0f7..b2ed6f70e4 100644
--- a/platform/iphone/in_app_store.h
+++ b/platform/iphone/in_app_store.h
@@ -37,25 +37,24 @@ class InAppStore : public Object {
GDCLASS(InAppStore, Object);
- static InAppStore* instance;
+ static InAppStore *instance;
static void _bind_methods();
List<Variant> pending_events;
public:
-
Error request_product_info(Variant p_params);
Error purchase(Variant p_params);
int get_pending_event_count();
Variant pop_pending_event();
void finish_transaction(String product_id);
- void set_auto_finish_transaction(bool b);
+ void set_auto_finish_transaction(bool b);
void _post_event(Variant p_event);
void _record_purchase(String product_id);
- static InAppStore* get_singleton();
+ static InAppStore *get_singleton();
InAppStore();
~InAppStore();
@@ -63,6 +62,4 @@ public:
#endif
-
#endif
-
diff --git a/platform/iphone/ios.h b/platform/iphone/ios.h
index 345bf127f2..e5baf8f4d2 100644
--- a/platform/iphone/ios.h
+++ b/platform/iphone/ios.h
@@ -38,11 +38,9 @@ class iOS : public Object {
static void _bind_methods();
public:
-
String get_rate_url(int p_app_id) const;
iOS();
-
};
#endif
diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp
index 816e456838..57862131f9 100644
--- a/platform/iphone/os_iphone.cpp
+++ b/platform/iphone/os_iphone.cpp
@@ -34,13 +34,13 @@
#include "servers/visual/visual_server_raster.h"
//#include "servers/visual/visual_server_wrap_mt.h"
-#include "main/main.h"
#include "audio_driver_iphone.h"
+#include "main/main.h"
+#include "core/global_config.h"
+#include "core/io/file_access_pack.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
-#include "core/io/file_access_pack.h"
-#include "core/global_config.h"
#include "sem_iphone.h"
@@ -51,17 +51,16 @@ int OSIPhone::get_video_driver_count() const {
return 1;
};
-const char * OSIPhone::get_video_driver_name(int p_driver) const {
+const char *OSIPhone::get_video_driver_name(int p_driver) const {
return "GLES2";
};
-OSIPhone* OSIPhone::get_singleton() {
+OSIPhone *OSIPhone::get_singleton() {
- return (OSIPhone*)OS::get_singleton();
+ return (OSIPhone *)OS::get_singleton();
};
-
OS::VideoMode OSIPhone::get_default_video_mode() const {
return video_mode;
@@ -76,7 +75,7 @@ extern int gl_view_base_fb; // from gl_view.mm
void OSIPhone::set_data_dir(String p_dir) {
- DirAccess* da = DirAccess::open(p_dir);
+ DirAccess *da = DirAccess::open(p_dir);
data_dir = da->get_current_dir();
printf("setting data dir to %ls from %ls\n", data_dir.c_str(), p_dir.c_str());
@@ -99,19 +98,19 @@ void OSIPhone::initialize_core() {
SemaphoreIphone::make_default();
};
-void OSIPhone::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OSIPhone::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
supported_orientations = 0;
- supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal", true)?1:0) << LandscapeLeft);
- supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal_flipped", false)?1:0) << LandscapeRight);
- supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical", false)?1:0) << PortraitDown);
- supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical_flipped", false)?1:0) << PortraitUp);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal", true) ? 1 : 0) << LandscapeLeft);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal_flipped", false) ? 1 : 0) << LandscapeRight);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical", false) ? 1 : 0) << PortraitDown);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical_flipped", false) ? 1 : 0) << PortraitUp);
RasterizerGLES3::register_config();
RasterizerGLES3::make_current();
RasterizerStorageGLES3::system_fbo = gl_view_base_fb;
- visual_server = memnew( VisualServerRaster() );
+ visual_server = memnew(VisualServerRaster());
/*
FIXME: Reimplement threaded rendering? Or remove?
if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
@@ -127,15 +126,15 @@ void OSIPhone::initialize(const VideoMode& p_desired,int p_video_driver,int p_au
audio_driver->init();
// init physics servers
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
//physics_2d_server = memnew( Physics2DServerSW );
physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
physics_2d_server->init();
- input = memnew( InputDefault );
+ input = memnew(InputDefault);
- /*
+/*
#ifdef IOS_SCORELOOP_ENABLED
scoreloop = memnew(ScoreloopIOS);
GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Scoreloop", scoreloop));
@@ -157,7 +156,7 @@ void OSIPhone::initialize(const VideoMode& p_desired,int p_video_driver,int p_au
#ifdef ICLOUD_ENABLED
icloud = memnew(ICloud);
GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("ICloud", icloud));
- //icloud->connect();
+//icloud->connect();
#endif
GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("iOS", memnew(iOS)));
};
@@ -167,8 +166,7 @@ MainLoop *OSIPhone::get_main_loop() const {
return main_loop;
};
-
-void OSIPhone::set_main_loop( MainLoop * p_main_loop ) {
+void OSIPhone::set_main_loop(MainLoop *p_main_loop) {
main_loop = p_main_loop;
@@ -178,14 +176,13 @@ void OSIPhone::set_main_loop( MainLoop * p_main_loop ) {
}
};
-
bool OSIPhone::iterate() {
if (!main_loop)
return true;
if (main_loop) {
- for (int i=0; i<event_count; i++) {
+ for (int i = 0; i < event_count; i++) {
input->parse_input_event(event_queue[i]);
};
@@ -213,10 +210,10 @@ void OSIPhone::mouse_button(int p_idx, int p_x, int p_y, bool p_pressed, bool p_
InputEvent ev;
ev.type = InputEvent::SCREEN_TOUCH;
ev.ID = ++last_event_id;
- ev.screen_touch.index=p_idx;
- ev.screen_touch.pressed=p_pressed;
- ev.screen_touch.x=p_x;
- ev.screen_touch.y=p_y;
+ ev.screen_touch.index = p_idx;
+ ev.screen_touch.pressed = p_pressed;
+ ev.screen_touch.x = p_x;
+ ev.screen_touch.y = p_y;
queue_event(ev);
};
@@ -238,7 +235,7 @@ void OSIPhone::mouse_button(int p_idx, int p_x, int p_y, bool p_pressed, bool p_
//mouse_list.pressed[p_idx] = p_pressed;
- input->set_mouse_pos(Point2(ev.mouse_motion.x,ev.mouse_motion.y));
+ input->set_mouse_pos(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
ev.mouse_button.button_index = BUTTON_LEFT;
ev.mouse_button.doubleclick = p_doubleclick;
ev.mouse_button.pressed = p_pressed;
@@ -252,11 +249,11 @@ void OSIPhone::mouse_move(int p_idx, int p_prev_x, int p_prev_y, int p_x, int p_
if (!GLOBAL_DEF("debug/disable_touch", false)) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_DRAG;
+ ev.type = InputEvent::SCREEN_DRAG;
ev.ID = ++last_event_id;
- ev.screen_drag.index=p_idx;
- ev.screen_drag.x=p_x;
- ev.screen_drag.y=p_y;
+ ev.screen_drag.index = p_idx;
+ ev.screen_drag.x = p_x;
+ ev.screen_drag.y = p_y;
ev.screen_drag.relative_x = p_x - p_prev_x;
ev.screen_drag.relative_y = p_y - p_prev_y;
queue_event(ev);
@@ -283,25 +280,25 @@ void OSIPhone::mouse_move(int p_idx, int p_prev_x, int p_prev_y, int p_x, int p_
ev.mouse_motion.relative_y = ev.mouse_motion.y - p_prev_x;
};
- input->set_mouse_pos(Point2(ev.mouse_motion.x,ev.mouse_motion.y));
- ev.mouse_motion.speed_x=input->get_last_mouse_speed().x;
- ev.mouse_motion.speed_y=input->get_last_mouse_speed().y;
+ input->set_mouse_pos(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
+ ev.mouse_motion.speed_x = input->get_last_mouse_speed().x;
+ ev.mouse_motion.speed_y = input->get_last_mouse_speed().y;
ev.mouse_motion.button_mask = 1; // pressed
queue_event(ev);
};
};
-void OSIPhone::queue_event(const InputEvent& p_event) {
+void OSIPhone::queue_event(const InputEvent &p_event) {
- ERR_FAIL_INDEX( event_count, MAX_EVENTS );
+ ERR_FAIL_INDEX(event_count, MAX_EVENTS);
event_queue[event_count++] = p_event;
};
void OSIPhone::touches_cancelled() {
- for (int i=0; i<MAX_MOUSE_COUNT; i++) {
+ for (int i = 0; i < MAX_MOUSE_COUNT; i++) {
if (mouse_list.pressed[i]) {
@@ -379,12 +376,12 @@ void OSIPhone::delete_main_loop() {
void OSIPhone::finalize() {
- if(main_loop) // should not happen?
+ if (main_loop) // should not happen?
memdelete(main_loop);
visual_server->finish();
memdelete(visual_server);
-// memdelete(rasterizer);
+ // memdelete(rasterizer);
physics_server->finish();
memdelete(physics_server);
@@ -393,11 +390,10 @@ void OSIPhone::finalize() {
memdelete(physics_2d_server);
memdelete(input);
-
};
-void OSIPhone::set_mouse_show(bool p_show) { };
-void OSIPhone::set_mouse_grab(bool p_grab) { };
+void OSIPhone::set_mouse_show(bool p_show){};
+void OSIPhone::set_mouse_grab(bool p_grab){};
bool OSIPhone::is_mouse_grab_enabled() const {
@@ -414,9 +410,9 @@ int OSIPhone::get_mouse_button_state() const {
return mouse_list.pressed[0];
};
-void OSIPhone::set_window_title(const String& p_title) { };
+void OSIPhone::set_window_title(const String &p_title){};
-void OSIPhone::set_video_mode(const VideoMode& p_video_mode, int p_screen) {
+void OSIPhone::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
video_mode = p_video_mode;
};
@@ -454,7 +450,7 @@ extern void _hide_keyboard();
extern Error _shell_open(String p_uri);
extern void _set_keep_screen_on(bool p_enabled);
-void OSIPhone::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) {
+void OSIPhone::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
_show_keyboard(p_existing_text);
};
@@ -471,8 +467,7 @@ void OSIPhone::set_keep_screen_on(bool p_enabled) {
_set_keep_screen_on(p_enabled);
};
-void OSIPhone::set_cursor_shape(CursorShape p_shape) {
-
+void OSIPhone::set_cursor_shape(CursorShape p_shape){
};
@@ -496,8 +491,7 @@ bool OSIPhone::has_touchscreen_ui_hint() const {
return true;
}
-void OSIPhone::set_locale(String p_locale)
-{
+void OSIPhone::set_locale(String p_locale) {
locale_code = p_locale;
}
@@ -513,7 +507,7 @@ extern void _stop_video();
extern void _focus_out_video();
Error OSIPhone::native_video_play(String p_path, float p_volume, String p_audio_track, String p_subtitle_track) {
- FileAccess* f = FileAccess::open(p_path, FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
bool exists = f && f->is_open();
String tempFile = get_data_dir();
@@ -533,18 +527,18 @@ Error OSIPhone::native_video_play(String p_path, float p_volume, String p_audio_
memdelete(f);
print("Playing video: %S\n", p_path.c_str());
- if (_play_video(p_path, p_volume, p_audio_track, p_subtitle_track) )
+ if (_play_video(p_path, p_volume, p_audio_track, p_subtitle_track))
return OK;
return FAILED;
}
bool OSIPhone::native_video_is_playing() const {
- return _is_video_playing();
+ return _is_video_playing();
}
void OSIPhone::native_video_pause() {
if (native_video_is_playing())
- _pause_video();
+ _pause_video();
}
void OSIPhone::native_video_unpause() {
@@ -557,7 +551,7 @@ void OSIPhone::native_video_focus_out() {
void OSIPhone::native_video_stop() {
if (native_video_is_playing())
- _stop_video();
+ _stop_video();
}
OSIPhone::OSIPhone(int width, int height) {
@@ -576,7 +570,6 @@ OSIPhone::OSIPhone(int width, int height) {
};
OSIPhone::~OSIPhone() {
-
}
#endif
diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h
index 65dcc884bb..36261a62c2 100644
--- a/platform/iphone/os_iphone.h
+++ b/platform/iphone/os_iphone.h
@@ -31,20 +31,19 @@
#ifndef OS_IPHONE_H
#define OS_IPHONE_H
-#include "os/input.h"
#include "drivers/unix/os_unix.h"
+#include "os/input.h"
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
+#include "game_center.h"
+#include "icloud.h"
+#include "in_app_store.h"
+#include "main/input_default.h"
+#include "servers/audio_server.h"
#include "servers/physics/physics_server_sw.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
-#include "servers/audio_server.h"
-#include "main/input_default.h"
-#include "game_center.h"
-#include "in_app_store.h"
-#include "icloud.h"
-
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
class AudioDriverIphone;
// class RasterizerGLES2;
@@ -52,55 +51,53 @@ class AudioDriverIphone;
class OSIPhone : public OS_Unix {
public:
-
enum Orientations {
PortraitDown,
PortraitUp,
LandscapeLeft,
LandscapeRight,
};
-private:
+private:
enum {
- MAX_MOUSE_COUNT = 8,
- MAX_EVENTS = 64,
+ MAX_MOUSE_COUNT = 8,
+ MAX_EVENTS = 64,
};
uint8_t supported_orientations;
-// Rasterizer *rasterizer;
-// RasterizerGLES2* rasterizer_gles22;
+ // Rasterizer *rasterizer;
+ // RasterizerGLES2* rasterizer_gles22;
VisualServer *visual_server;
- PhysicsServer* physics_server;
+ PhysicsServer *physics_server;
Physics2DServer *physics_2d_server;
- AudioDriverIphone* audio_driver;
+ AudioDriverIphone *audio_driver;
#ifdef GAME_CENTER_ENABLED
- GameCenter* game_center;
+ GameCenter *game_center;
#endif
#ifdef STOREKIT_ENABLED
- InAppStore* store_kit;
+ InAppStore *store_kit;
#endif
#ifdef ICLOUD_ENABLED
- ICloud* icloud;
+ ICloud *icloud;
#endif
MainLoop *main_loop;
VideoMode video_mode;
-
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual MainLoop *get_main_loop() const;
virtual void delete_main_loop();
@@ -111,7 +108,7 @@ private:
bool pressed[MAX_MOUSE_COUNT];
MouseList() {
- for (int i=0; i<MAX_MOUSE_COUNT; i++)
+ for (int i = 0; i < MAX_MOUSE_COUNT; i++)
pressed[i] = false;
};
};
@@ -123,7 +120,7 @@ private:
InputEvent event_queue[MAX_EVENTS];
int event_count;
int last_event_id;
- void queue_event(const InputEvent& p_event);
+ void queue_event(const InputEvent &p_event);
String data_dir;
String unique_ID;
@@ -132,7 +129,6 @@ private:
InputDefault *input;
public:
-
bool iterate();
uint8_t get_orientations() const;
@@ -149,25 +145,25 @@ public:
void update_magnetometer(float p_x, float p_y, float p_z);
void update_gyroscope(float p_x, float p_y, float p_z);
- static OSIPhone* get_singleton();
+ static OSIPhone *get_singleton();
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual void set_keep_screen_on(bool p_enabled);
virtual bool can_draw() const;
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect=Rect2());
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2());
virtual void hide_virtual_keyboard();
virtual void set_cursor_shape(CursorShape p_shape);
diff --git a/platform/iphone/platform_refcount.h b/platform/iphone/platform_refcount.h
index d32fb4514c..6cfdc49369 100644
--- a/platform/iphone/platform_refcount.h
+++ b/platform/iphone/platform_refcount.h
@@ -31,15 +31,15 @@
#ifdef IPHONE_ENABLED
#define REFCOUNT_T int
-#define REFCOUNT_GET_T int const volatile&
+#define REFCOUNT_GET_T int const volatile &
#include <libkern/OSAtomic.h>
-inline int atomic_conditional_increment(volatile int* v) {
- return (*v==0)? 0 : OSAtomicIncrement32(v);
+inline int atomic_conditional_increment(volatile int *v) {
+ return (*v == 0) ? 0 : OSAtomicIncrement32(v);
}
-inline int atomic_decrement(volatile int* v) {
+inline int atomic_decrement(volatile int *v) {
return OSAtomicDecrement32(v);
}
diff --git a/platform/iphone/power_iphone.cpp b/platform/iphone/power_iphone.cpp
index db555f30c2..7b1f9246f4 100644
--- a/platform/iphone/power_iphone.cpp
+++ b/platform/iphone/power_iphone.cpp
@@ -33,12 +33,10 @@ bool PowerState::UpdatePowerInfo() {
return false;
}
-
PowerState PowerIphone::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
return POWERSTATE_UNKNOWN;
}
}
@@ -46,8 +44,7 @@ PowerState PowerIphone::get_power_state() {
int PowerIphone::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
return -1;
}
}
@@ -55,15 +52,14 @@ int PowerIphone::get_power_seconds_left() {
int PowerIphone::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
return -1;
}
}
-PowerIphone::PowerIphone() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
+PowerIphone::PowerIphone()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
// TODO Auto-generated constructor stub
-
}
PowerIphone::~PowerIphone() {
diff --git a/platform/iphone/rasterizer_iphone.cpp b/platform/iphone/rasterizer_iphone.cpp
index b8f3dd0d05..1a619f4305 100644
--- a/platform/iphone/rasterizer_iphone.cpp
+++ b/platform/iphone/rasterizer_iphone.cpp
@@ -29,13 +29,13 @@
#ifdef IPHONE_ENABLED
#include "rasterizer_iphone.h"
-#include "os/os.h"
#include "global_config.h"
+#include "os/os.h"
#include <stdio.h>
-_FORCE_INLINE_ static void _gl_load_transform(const Transform& tr) {
+_FORCE_INLINE_ static void _gl_load_transform(const Transform &tr) {
- GLfloat matrix[16]={ /* build a 16x16 matrix */
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
tr.basis.elements[0][0],
tr.basis.elements[1][0],
tr.basis.elements[2][0],
@@ -57,9 +57,9 @@ _FORCE_INLINE_ static void _gl_load_transform(const Transform& tr) {
glLoadMatrixf(matrix);
};
-_FORCE_INLINE_ static void _gl_mult_transform(const Transform& tr) {
+_FORCE_INLINE_ static void _gl_mult_transform(const Transform &tr) {
- GLfloat matrix[16]={ /* build a 16x16 matrix */
+ GLfloat matrix[16] = { /* build a 16x16 matrix */
tr.basis.elements[0][0],
tr.basis.elements[1][0],
tr.basis.elements[2][0],
@@ -81,42 +81,41 @@ _FORCE_INLINE_ static void _gl_mult_transform(const Transform& tr) {
glMultMatrixf(matrix);
};
-static const GLenum prim_type[]={GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+static const GLenum prim_type[] = { GL_POINTS, GL_LINES, GL_TRIANGLES, GL_TRIANGLE_FAN };
-static void _draw_primitive(int p_points, const float *p_vertices, const float *p_normals, const float* p_colors, const float *p_uvs,const Plane *p_tangents=NULL,int p_instanced=1) {
+static void _draw_primitive(int p_points, const float *p_vertices, const float *p_normals, const float *p_colors, const float *p_uvs, const Plane *p_tangents = NULL, int p_instanced = 1) {
ERR_FAIL_COND(!p_vertices);
- ERR_FAIL_COND(p_points <1 || p_points>4);
+ ERR_FAIL_COND(p_points < 1 || p_points > 4);
GLenum type = prim_type[p_points - 1];
-
if (!p_colors) {
glColor4f(1, 1, 1, 1);
};
glEnableClientState(GL_VERTEX_ARRAY);
- glVertexPointer(3, GL_FLOAT, 0, (GLvoid*)p_vertices);
+ glVertexPointer(3, GL_FLOAT, 0, (GLvoid *)p_vertices);
if (p_normals) {
- glEnableClientState(GL_NORMAL_ARRAY);
- glNormalPointer(GL_FLOAT, 0, (GLvoid*)p_normals);
+ glEnableClientState(GL_NORMAL_ARRAY);
+ glNormalPointer(GL_FLOAT, 0, (GLvoid *)p_normals);
};
if (p_colors) {
- glEnableClientState(GL_COLOR_ARRAY);
- glColorPointer(4,GL_FLOAT, 0, p_colors);
+ glEnableClientState(GL_COLOR_ARRAY);
+ glColorPointer(4, GL_FLOAT, 0, p_colors);
};
if (p_uvs) {
- glClientActiveTexture(GL_TEXTURE0);
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glTexCoordPointer(2, GL_FLOAT, 0, p_uvs);
+ glClientActiveTexture(GL_TEXTURE0);
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ glTexCoordPointer(2, GL_FLOAT, 0, p_uvs);
};
- glDrawArrays( type, 0, p_points);
+ glDrawArrays(type, 0, p_points);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
@@ -124,61 +123,61 @@ static void _draw_primitive(int p_points, const float *p_vertices, const float *
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
};
-
/* TEXTURE API */
-static Image _get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,int &r_gl_components,bool &r_has_alpha_cache) {
+static Image _get_gl_image_and_format(const Image &p_image, Image::Format p_format, uint32_t p_flags, GLenum &r_gl_format, int &r_gl_components, bool &r_has_alpha_cache) {
- r_has_alpha_cache=false;
- Image image=p_image;
+ r_has_alpha_cache = false;
+ Image image = p_image;
- switch(p_format) {
+ switch (p_format) {
case Image::FORMAT_L8: {
- r_gl_components=1;
- r_gl_format=GL_LUMINANCE;
+ r_gl_components = 1;
+ r_gl_format = GL_LUMINANCE;
} break;
case Image::FORMAT_INTENSITY: {
image.convert(Image::FORMAT_RGBA8);
- r_gl_components=4;
- r_gl_format=GL_RGBA;
- r_has_alpha_cache=true;
+ r_gl_components = 4;
+ r_gl_format = GL_RGBA;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_LA8: {
image.convert(Image::FORMAT_RGBA8);
- r_gl_components=4;
- r_gl_format=GL_RGBA;
- r_has_alpha_cache=true;
+ r_gl_components = 4;
+ r_gl_format = GL_RGBA;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_INDEXED: {
image.convert(Image::FORMAT_RGB8);
- r_gl_components=3;
- r_gl_format=GL_RGB;
+ r_gl_components = 3;
+ r_gl_format = GL_RGB;
} break;
case Image::FORMAT_INDEXED_ALPHA: {
image.convert(Image::FORMAT_RGBA8);
- r_gl_components=4;
- r_gl_format=GL_RGB;
- r_has_alpha_cache=true;
+ r_gl_components = 4;
+ r_gl_format = GL_RGB;
+ r_has_alpha_cache = true;
} break;
case Image::FORMAT_RGB8: {
- r_gl_components=3; r_gl_format=GL_RGB;
+ r_gl_components = 3;
+ r_gl_format = GL_RGB;
} break;
case Image::FORMAT_RGBA8: {
- r_gl_components=4;
- r_gl_format=GL_RGBA;
- r_has_alpha_cache=true;
+ r_gl_components = 4;
+ r_gl_format = GL_RGBA;
+ r_has_alpha_cache = true;
} break;
default: {
@@ -192,45 +191,43 @@ static Image _get_gl_image_and_format(const Image& p_image, Image::Format p_form
RID RasterizerIPhone::texture_create() {
Texture *texture = memnew(Texture);
- ERR_FAIL_COND_V(!texture,RID());
+ ERR_FAIL_COND_V(!texture, RID());
glGenTextures(1, &texture->tex_id);
- texture->active=false;
-
- return texture_owner.make_rid( texture );
+ texture->active = false;
+ return texture_owner.make_rid(texture);
}
-void RasterizerIPhone::texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags) {
+void RasterizerIPhone::texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags) {
bool has_alpha_cache;
int components;
GLenum format;
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
- texture->width=p_width;
- texture->height=p_height;
- texture->format=p_format;
- texture->flags=p_flags;
+ texture->width = p_width;
+ texture->height = p_height;
+ texture->format = p_format;
+ texture->flags = p_flags;
//texture->target = (p_flags & VS::TEXTURE_FLAG_CUBEMAP) ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
texture->target = GL_TEXTURE_2D;
- _get_gl_image_and_format(Image(),texture->format,texture->flags,format,components,has_alpha_cache);
+ _get_gl_image_and_format(Image(), texture->format, texture->flags, format, components, has_alpha_cache);
- texture->gl_components_cache=components;
- texture->gl_format_cache=format;
- texture->format_has_alpha=has_alpha_cache;
- texture->has_alpha=false; //by default it doesn't have alpha unless something with alpha is blitteds
+ texture->gl_components_cache = components;
+ texture->gl_format_cache = format;
+ texture->format_has_alpha = has_alpha_cache;
+ texture->has_alpha = false; //by default it doesn't have alpha unless something with alpha is blitteds
glBindTexture(texture->target, texture->tex_id);
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS) {
- glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS) {
+ glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
}
-
- if (texture->target==GL_TEXTURE_2D) {
- glTexImage2D(texture->target, 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE,NULL);
+ if (texture->target == GL_TEXTURE_2D) {
+ glTexImage2D(texture->target, 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE, NULL);
}
/*
@@ -241,138 +238,131 @@ void RasterizerIPhone::texture_allocate(RID p_texture,int p_width, int p_height,
}
*/
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtering
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS) {
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS) {
//glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
};
}
+ if (texture->flags & VS::TEXTURE_FLAG_REPEAT /* && texture->target != GL_TEXTURE_CUBE_MAP*/) {
-
- if (texture->flags&VS::TEXTURE_FLAG_REPEAT /* && texture->target != GL_TEXTURE_CUBE_MAP*/) {
-
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
- texture->active=true;
+ texture->active = true;
}
-void RasterizerIPhone::texture_blit_rect(RID p_texture,int p_x,int p_y, const Image& p_image,VS::CubeMapSide p_cube_side) {
+void RasterizerIPhone::texture_blit_rect(RID p_texture, int p_x, int p_y, const Image &p_image, VS::CubeMapSide p_cube_side) {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
ERR_FAIL_COND(!texture->active);
- ERR_FAIL_COND(texture->format != p_image.get_format() );
+ ERR_FAIL_COND(texture->format != p_image.get_format());
int components;
GLenum format;
bool alpha;
- Image img = _get_gl_image_and_format(p_image, p_image.get_format(),texture->flags,format,components,alpha);
+ Image img = _get_gl_image_and_format(p_image, p_image.get_format(), texture->flags, format, components, alpha);
if (img.detect_alpha())
- texture->has_alpha=true;
+ texture->has_alpha = true;
GLenum blit_target = GL_TEXTURE_2D; //(texture->target == GL_TEXTURE_CUBE_MAP)?_cube_side_enum[p_cube_side]:GL_TEXTURE_2D;
PoolVector<uint8_t>::Read read = img.get_data().read();
glBindTexture(texture->target, texture->tex_id);
- glTexSubImage2D( blit_target, 0, p_x,p_y,img.get_width(),img.get_height(),format,GL_UNSIGNED_BYTE,read.ptr() );
+ glTexSubImage2D(blit_target, 0, p_x, p_y, img.get_width(), img.get_height(), format, GL_UNSIGNED_BYTE, read.ptr());
//glGenerateMipmap( texture->target );
}
-Image RasterizerIPhone::texture_get_rect(RID p_texture,int p_x,int p_y,int p_width, int p_height,VS::CubeMapSide p_cube_side) const {
-
+Image RasterizerIPhone::texture_get_rect(RID p_texture, int p_x, int p_y, int p_width, int p_height, VS::CubeMapSide p_cube_side) const {
return Image();
}
-void RasterizerIPhone::texture_set_flags(RID p_texture,uint32_t p_flags) {
+void RasterizerIPhone::texture_set_flags(RID p_texture, uint32_t p_flags) {
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
glBindTexture(texture->target, texture->tex_id);
uint32_t cube = texture->flags & VS::TEXTURE_FLAG_CUBEMAP;
- texture->flags=p_flags|cube; // can't remove a cube from being a cube
+ texture->flags = p_flags | cube; // can't remove a cube from being a cube
- if (texture->flags&VS::TEXTURE_FLAG_REPEAT /*&& texture->target != GL_TEXTURE_CUBE_MAP*/) {
+ if (texture->flags & VS::TEXTURE_FLAG_REPEAT /*&& texture->target != GL_TEXTURE_CUBE_MAP*/) {
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
- glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
//glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
- glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameterf(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
+ if (texture->flags & VS::TEXTURE_FLAG_FILTER) {
- if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
-
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
- if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS)
- glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering
+ if (texture->flags & VS::TEXTURE_FLAG_MIPMAPS)
+ glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
} else {
- glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // nearest
+ glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // nearest
}
}
uint32_t RasterizerIPhone::texture_get_flags(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->flags;
-
}
Image::Format RasterizerIPhone::texture_get_format(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,Image::FORMAT_L8);
+ ERR_FAIL_COND_V(!texture, Image::FORMAT_L8);
return texture->format;
}
uint32_t RasterizerIPhone::texture_get_width(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->width;
}
uint32_t RasterizerIPhone::texture_get_height(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->height;
}
bool RasterizerIPhone::texture_has_alpha(RID p_texture) const {
- Texture * texture = texture_owner.get(p_texture);
+ Texture *texture = texture_owner.get(p_texture);
- ERR_FAIL_COND_V(!texture,0);
+ ERR_FAIL_COND_V(!texture, 0);
return texture->has_alpha;
-
}
/* SHADER API */
@@ -382,97 +372,68 @@ RID RasterizerIPhone::shader_create() {
return RID();
}
-void RasterizerIPhone::shader_node_add(RID p_shader,VS::ShaderNodeType p_type,int p_id) {
-
-
+void RasterizerIPhone::shader_node_add(RID p_shader, VS::ShaderNodeType p_type, int p_id) {
}
-void RasterizerIPhone::shader_node_remove(RID p_shader,int p_id) {
-
-
+void RasterizerIPhone::shader_node_remove(RID p_shader, int p_id) {
}
void RasterizerIPhone::shader_node_change_type(RID p_shader, int p_id, VS::ShaderNodeType p_type) {
-
-
}
-void RasterizerIPhone::shader_node_set_param(RID p_shader, int p_id, const Variant& p_value) {
-
-
+void RasterizerIPhone::shader_node_set_param(RID p_shader, int p_id, const Variant &p_value) {
}
-void RasterizerIPhone::shader_get_node_list(RID p_shader,List<int> *p_node_list) const {
-
-
+void RasterizerIPhone::shader_get_node_list(RID p_shader, List<int> *p_node_list) const {
}
-VS::ShaderNodeType RasterizerIPhone::shader_node_get_type(RID p_shader,int p_id) const {
-
+VS::ShaderNodeType RasterizerIPhone::shader_node_get_type(RID p_shader, int p_id) const {
return VS::NODE_ADD;
}
-Variant RasterizerIPhone::shader_node_get_param(RID p_shader,int p_id) const {
+Variant RasterizerIPhone::shader_node_get_param(RID p_shader, int p_id) const {
return Variant();
}
-void RasterizerIPhone::shader_connect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) {
-
-
+void RasterizerIPhone::shader_connect(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot) {
}
-bool RasterizerIPhone::shader_is_connected(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) const {
+bool RasterizerIPhone::shader_is_connected(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot) const {
return false;
}
-void RasterizerIPhone::shader_disconnect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) {
-
-
+void RasterizerIPhone::shader_disconnect(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot) {
}
-void RasterizerIPhone::shader_get_connections(RID p_shader,List<VS::ShaderConnection> *p_connections) const {
-
-
+void RasterizerIPhone::shader_get_connections(RID p_shader, List<VS::ShaderConnection> *p_connections) const {
}
void RasterizerIPhone::shader_clear(RID p_shader) {
-
-
}
/* COMMON MATERIAL API */
-void RasterizerIPhone::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value) {
-
-
+void RasterizerIPhone::material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) {
}
-Variant RasterizerIPhone::material_get_param(RID p_material, const StringName& p_param) const {
+Variant RasterizerIPhone::material_get_param(RID p_material, const StringName &p_param) const {
return Variant();
}
void RasterizerIPhone::material_get_param_list(RID p_material, List<String> *p_param_list) const {
-
-
}
-void RasterizerIPhone::material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled) {
-
-
+void RasterizerIPhone::material_set_flag(RID p_material, VS::MaterialFlag p_flag, bool p_enabled) {
}
-bool RasterizerIPhone::material_get_flag(RID p_material,VS::MaterialFlag p_flag) const {
+bool RasterizerIPhone::material_get_flag(RID p_material, VS::MaterialFlag p_flag) const {
return false;
}
-void RasterizerIPhone::material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode) {
-
-
+void RasterizerIPhone::material_set_blend_mode(RID p_material, VS::MaterialBlendMode p_mode) {
}
VS::MaterialBlendMode RasterizerIPhone::material_get_blend_mode(RID p_material) const {
return VS::MATERIAL_BLEND_MODE_ADD;
}
-void RasterizerIPhone::material_set_line_width(RID p_material,float p_line_width) {
-
-
+void RasterizerIPhone::material_set_line_width(RID p_material, float p_line_width) {
}
float RasterizerIPhone::material_get_line_width(RID p_material) const {
@@ -483,78 +444,78 @@ float RasterizerIPhone::material_get_line_width(RID p_material) const {
RID RasterizerIPhone::material_create() {
- return material_owner.make_rid( memnew( Material ) );
+ return material_owner.make_rid(memnew(Material));
}
-void RasterizerIPhone::fixed_material_set_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter, const Variant& p_value) {
+void RasterizerIPhone::fixed_material_set_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter, const Variant &p_value) {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
m->parameters[p_parameter] = p_value;
}
-Variant RasterizerIPhone::fixed_material_get_parameter(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const {
+Variant RasterizerIPhone::fixed_material_get_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, Variant());
ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, Variant());
return m->parameters[p_parameter];
}
-void RasterizerIPhone::fixed_material_set_texture(RID p_material,VS::FixedSpatialMaterialParam p_parameter, RID p_texture) {
+void RasterizerIPhone::fixed_material_set_texture(RID p_material, VS::FixedSpatialMaterialParam p_parameter, RID p_texture) {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
m->textures[p_parameter] = p_texture;
}
-RID RasterizerIPhone::fixed_material_get_texture(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const {
+RID RasterizerIPhone::fixed_material_get_texture(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, RID());
ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, Variant());
return m->textures[p_parameter];
}
-void RasterizerIPhone::fixed_material_set_detail_blend_mode(RID p_material,VS::MaterialBlendMode p_mode) {
+void RasterizerIPhone::fixed_material_set_detail_blend_mode(RID p_material, VS::MaterialBlendMode p_mode) {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
m->detail_blend_mode = p_mode;
}
VS::MaterialBlendMode RasterizerIPhone::fixed_material_get_detail_blend_mode(RID p_material) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, VS::MATERIAL_BLEND_MODE_MIX);
return m->detail_blend_mode;
}
-void RasterizerIPhone::fixed_material_set_texcoord_mode(RID p_material,VS::FixedSpatialMaterialParam p_parameter, VS::FixedSpatialMaterialTexCoordMode p_mode) {
+void RasterizerIPhone::fixed_material_set_texcoord_mode(RID p_material, VS::FixedSpatialMaterialParam p_parameter, VS::FixedSpatialMaterialTexCoordMode p_mode) {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
m->texcoord_mode[p_parameter] = p_mode;
}
-VS::FixedSpatialMaterialTexCoordMode RasterizerIPhone::fixed_material_get_texcoord_mode(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const {
+VS::FixedSpatialMaterialTexCoordMode RasterizerIPhone::fixed_material_get_texcoord_mode(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, VS::FIXED_MATERIAL_TEXCOORD_TEXGEN);
ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, VS::FIXED_MATERIAL_TEXCOORD_UV);
return m->texcoord_mode[p_parameter]; // for now
}
-void RasterizerIPhone::fixed_material_set_texgen_mode(RID p_material,VS::FixedSpatialMaterialTexGenMode p_mode) {
+void RasterizerIPhone::fixed_material_set_texgen_mode(RID p_material, VS::FixedSpatialMaterialTexGenMode p_mode) {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
m->texgen_mode = p_mode;
@@ -562,23 +523,22 @@ void RasterizerIPhone::fixed_material_set_texgen_mode(RID p_material,VS::FixedSp
VS::FixedSpatialMaterialTexGenMode RasterizerIPhone::fixed_material_get_texgen_mode(RID p_material) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, VS::FIXED_MATERIAL_TEXGEN_SPHERE);
return m->texgen_mode;
};
+void RasterizerIPhone::fixed_material_set_uv_transform(RID p_material, const Transform &p_transform) {
-void RasterizerIPhone::fixed_material_set_uv_transform(RID p_material,const Transform& p_transform) {
-
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND(!m);
m->uv_transform = p_transform;
}
Transform RasterizerIPhone::fixed_material_get_uv_transform(RID p_material) const {
- Material *m=material_owner.get( p_material );
+ Material *m = material_owner.get(p_material);
ERR_FAIL_COND_V(!m, Transform());
return m->uv_transform;
@@ -591,529 +551,505 @@ RID RasterizerIPhone::shader_material_create() const {
return RID();
}
-void RasterizerIPhone::shader_material_set_vertex_shader(RID p_material,RID p_shader,bool p_owned) {
-
-
+void RasterizerIPhone::shader_material_set_vertex_shader(RID p_material, RID p_shader, bool p_owned) {
}
RID RasterizerIPhone::shader_material_get_vertex_shader(RID p_material) const {
return RID();
}
-void RasterizerIPhone::shader_material_set_fragment_shader(RID p_material,RID p_shader,bool p_owned) {
-
-
+void RasterizerIPhone::shader_material_set_fragment_shader(RID p_material, RID p_shader, bool p_owned) {
}
RID RasterizerIPhone::shader_material_get_fragment_shader(RID p_material) const {
return RID();
}
-
/* MESH API */
RID RasterizerIPhone::mesh_create() {
-
- return mesh_owner.make_rid( memnew( Mesh ) );
+ return mesh_owner.make_rid(memnew(Mesh));
}
-void RasterizerIPhone::mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,uint32_t p_format,int p_array_len,int p_index_array_len) {
+void RasterizerIPhone::mesh_add_surface(RID p_mesh, VS::PrimitiveType p_primitive, uint32_t p_format, int p_array_len, int p_index_array_len) {
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_COND((p_format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory
- ERR_FAIL_COND( p_array_len<=0 );
- ERR_FAIL_COND( p_index_array_len==0 );
- ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX );
+ ERR_FAIL_COND((p_format & VS::ARRAY_FORMAT_VERTEX) == 0); // mandatory
+ ERR_FAIL_COND(p_array_len <= 0);
+ ERR_FAIL_COND(p_index_array_len == 0);
+ ERR_FAIL_INDEX(p_primitive, VS::PRIMITIVE_MAX);
- Surface *surface = memnew( Surface );
- ERR_FAIL_COND( !surface );
+ Surface *surface = memnew(Surface);
+ ERR_FAIL_COND(!surface);
- int total_elem_size=0;
+ int total_elem_size = 0;
- bool use_VBO=true; //glGenBuffersARB!=NULL; // TODO detect if it's in there
- if (p_format&VS::ARRAY_FORMAT_WEIGHTS) {
+ bool use_VBO = true; //glGenBuffersARB!=NULL; // TODO detect if it's in there
+ if (p_format & VS::ARRAY_FORMAT_WEIGHTS) {
- use_VBO=false;
+ use_VBO = false;
}
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
- for (int i=0;i<VS::ARRAY_MAX;i++) {
-
+ Surface::ArrayData &ad = surface->array[i];
+ ad.size = 0;
+ ad.configured = false;
+ ad.ofs = 0;
+ int elem_size = 0;
+ int elem_count = 0;
- Surface::ArrayData&ad=surface->array[i];
- ad.size=0;
- ad.configured=false;
- ad.ofs=0;
- int elem_size=0;
- int elem_count=0;
-
- if (!(p_format&(1<<i))) // no array
+ if (!(p_format & (1 << i))) // no array
continue;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX:
case VS::ARRAY_NORMAL: {
- elem_size=3*sizeof(GLfloat); // vertex
- elem_count=3;
+ elem_size = 3 * sizeof(GLfloat); // vertex
+ elem_count = 3;
} break;
case VS::ARRAY_TANGENT: {
- elem_size=4*sizeof(GLfloat); // vertex
- elem_count=4;
+ elem_size = 4 * sizeof(GLfloat); // vertex
+ elem_count = 4;
} break;
case VS::ARRAY_COLOR: {
- elem_size=4; /* RGBA */
- elem_count=4;
+ elem_size = 4; /* RGBA */
+ elem_count = 4;
} break;
case VS::ARRAY_TEX_UV: {
- elem_size=2*sizeof(GLfloat);
- elem_count=2;
+ elem_size = 2 * sizeof(GLfloat);
+ elem_count = 2;
} break;
case VS::ARRAY_WEIGHTS:
case VS::ARRAY_BONES: {
- elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLfloat);
- elem_count=VS::ARRAY_WEIGHTS_SIZE;
+ elem_size = VS::ARRAY_WEIGHTS_SIZE * sizeof(GLfloat);
+ elem_count = VS::ARRAY_WEIGHTS_SIZE;
} break;
case VS::ARRAY_INDEX: {
- if (p_index_array_len<=0) {
+ if (p_index_array_len <= 0) {
ERR_PRINT("p_index_array_len==NO_INDEX_ARRAY");
break;
}
/* determine wether using 8 or 16 bits indices */
- if (p_index_array_len>(1<<8)) {
+ if (p_index_array_len > (1 << 8)) {
- elem_size=2;
+ elem_size = 2;
} else {
- elem_size=1;
+ elem_size = 1;
}
if (use_VBO) {
- glGenBuffers(1,&surface->index_id);
- ERR_FAIL_COND(surface->index_id==0);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
- glBufferData(GL_ELEMENT_ARRAY_BUFFER,p_index_array_len*elem_size,NULL,GL_STATIC_DRAW);
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &surface->index_id);
+ ERR_FAIL_COND(surface->index_id == 0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, p_index_array_len * elem_size, NULL, GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //unbind
} else {
- surface->index_array_local = (uint8_t*)memalloc(p_index_array_len*elem_size);
+ surface->index_array_local = (uint8_t *)memalloc(p_index_array_len * elem_size);
};
- surface->index_array_len=p_index_array_len; // only way it can exist
- ad.ofs=0;
- ad.size=elem_size;
- ad.configured=false;
- ad.components=1;
+ surface->index_array_len = p_index_array_len; // only way it can exist
+ ad.ofs = 0;
+ ad.size = elem_size;
+ ad.configured = false;
+ ad.components = 1;
continue;
} break;
default: {
- ERR_FAIL( );
+ ERR_FAIL();
}
}
- ad.ofs=total_elem_size;
- ad.size=elem_size;
- ad.components=elem_count;
- total_elem_size+=elem_size;
- ad.configured=false;
+ ad.ofs = total_elem_size;
+ ad.size = elem_size;
+ ad.components = elem_count;
+ total_elem_size += elem_size;
+ ad.configured = false;
}
- surface->stride=total_elem_size;
- surface->array_len=p_array_len;
- surface->format=p_format;
- surface->primitive=p_primitive;
-
+ surface->stride = total_elem_size;
+ surface->array_len = p_array_len;
+ surface->format = p_format;
+ surface->primitive = p_primitive;
/* bind the bigass buffers */
if (use_VBO) {
- glGenBuffers(1,&surface->vertex_id);
- ERR_FAIL_COND(surface->vertex_id==0);
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
- glBufferData(GL_ARRAY_BUFFER,surface->array_len*surface->stride,NULL,GL_STATIC_DRAW);
- glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ glGenBuffers(1, &surface->vertex_id);
+ ERR_FAIL_COND(surface->vertex_id == 0);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER, surface->array_len * surface->stride, NULL, GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER, 0); //unbind
} else {
- surface->array_local = (uint8_t*)memalloc(surface->array_len*surface->stride);
+ surface->array_local = (uint8_t *)memalloc(surface->array_len * surface->stride);
};
mesh->surfaces.push_back(surface);
}
-Error RasterizerIPhone::mesh_surface_set_array(RID p_mesh, int p_surface,VS::ArrayType p_type,const Variant& p_array) {
+Error RasterizerIPhone::mesh_surface_set_array(RID p_mesh, int p_surface, VS::ArrayType p_type, const Variant &p_array) {
- ERR_FAIL_INDEX_V(p_type, VS::ARRAY_MAX, ERR_INVALID_PARAMETER );
+ ERR_FAIL_INDEX_V(p_type, VS::ARRAY_MAX, ERR_INVALID_PARAMETER);
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,ERR_INVALID_PARAMETER);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), ERR_INVALID_PARAMETER );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), ERR_INVALID_PARAMETER);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(!surface, ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V( surface->array[p_type].size==0, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(surface->array[p_type].size == 0, ERR_INVALID_PARAMETER);
- Surface::ArrayData &a=surface->array[p_type];
+ Surface::ArrayData &a = surface->array[p_type];
- switch(p_type) {
+ switch (p_type) {
case VS::ARRAY_INDEX: {
- ERR_FAIL_COND_V( surface->index_array_len<=0, ERR_INVALID_DATA );
- ERR_FAIL_COND_V( p_array.get_type() != Variant::INT_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(surface->index_array_len <= 0, ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::INT_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<int> indices = p_array;
- ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER );
- ERR_FAIL_COND_V( indices.size() != surface->index_array_len, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(indices.size() == 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(indices.size() != surface->index_array_len, ERR_INVALID_PARAMETER);
/* determine wether using 16 or 32 bits indices */
if (surface->index_array_local == 0) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surface->index_id);
};
PoolVector<int>::Read read = indices.read();
- const int *src=read.ptr();
+ const int *src = read.ptr();
- for (int i=0;i<surface->index_array_len;i++) {
+ for (int i = 0; i < surface->index_array_len; i++) {
if (surface->index_array_local) {
- if (a.size<=(1<<8)) {
- uint8_t v=src[i];
+ if (a.size <= (1 << 8)) {
+ uint8_t v = src[i];
- copymem(&surface->array_local[i*a.size], &v, a.size);
+ copymem(&surface->array_local[i * a.size], &v, a.size);
} else {
- uint16_t v=src[i];
+ uint16_t v = src[i];
- copymem(&surface->array_local[i*a.size], &v, a.size);
+ copymem(&surface->array_local[i * a.size], &v, a.size);
}
} else {
- if (a.size<=(1<<8)) {
- uint8_t v=src[i];
+ if (a.size <= (1 << 8)) {
+ uint8_t v = src[i];
- glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, i*a.size, a.size, &v );
+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, i * a.size, a.size, &v);
} else {
- uint16_t v=src[i];
-
- glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, i*a.size, a.size, &v );
+ uint16_t v = src[i];
+ glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, i * a.size, a.size, &v);
}
};
}
if (surface->index_array_local == 0) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
};
- a.configured=true;
+ a.configured = true;
return OK;
} break;
case VS::ARRAY_VERTEX:
case VS::ARRAY_NORMAL: {
- ERR_FAIL_COND_V( p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector3> array = p_array;
- ERR_FAIL_COND_V( array.size() != surface->array_len, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(array.size() != surface->array_len, ERR_INVALID_PARAMETER);
if (surface->array_local == 0) {
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
};
PoolVector<Vector3>::Read read = array.read();
- const Vector3* src=read.ptr();
+ const Vector3 *src = read.ptr();
// setting vertices means regenerating the AABB
- if (p_type==VS::ARRAY_VERTEX)
- surface->aabb=AABB();
-
- for (int i=0;i<surface->array_len;i++) {
+ if (p_type == VS::ARRAY_VERTEX)
+ surface->aabb = AABB();
+ for (int i = 0; i < surface->array_len; i++) {
- GLfloat vector[3]={ src[i].x, src[i].y, src[i].z };
+ GLfloat vector[3] = { src[i].x, src[i].y, src[i].z };
if (surface->array_local == 0) {
- glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , vector );
+ glBufferSubData(GL_ARRAY_BUFFER, a.ofs + i * surface->stride, a.size, vector);
} else {
- copymem(&surface->array_local[a.ofs+i*surface->stride], vector, a.size);
+ copymem(&surface->array_local[a.ofs + i * surface->stride], vector, a.size);
}
- if (p_type==VS::ARRAY_VERTEX) {
+ if (p_type == VS::ARRAY_VERTEX) {
- if (i==0) {
+ if (i == 0) {
- surface->aabb=AABB(src[i],Vector3());
+ surface->aabb = AABB(src[i], Vector3());
} else {
- surface->aabb.expand_to( src[i] );
+ surface->aabb.expand_to(src[i]);
}
}
}
if (surface->array_local == 0) {
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
};
} break;
case VS::ARRAY_TANGENT: {
- ERR_FAIL_COND_V( p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_array;
- ERR_FAIL_COND_V( array.size() != surface->array_len*4, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(array.size() != surface->array_len * 4, ERR_INVALID_PARAMETER);
if (surface->array_local == 0) {
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
};
-
PoolVector<real_t>::Read read = array.read();
- const real_t* src = read.ptr();
+ const real_t *src = read.ptr();
- for (int i=0;i<surface->array_len;i++) {
+ for (int i = 0; i < surface->array_len; i++) {
- GLfloat xyzw[4]={
- src[i*4+0],
- src[i*4+1],
- src[i*4+2],
- src[i*4+3]
+ GLfloat xyzw[4] = {
+ src[i * 4 + 0],
+ src[i * 4 + 1],
+ src[i * 4 + 2],
+ src[i * 4 + 3]
};
if (surface->array_local == 0) {
- glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , xyzw );
+ glBufferSubData(GL_ARRAY_BUFFER, a.ofs + i * surface->stride, a.size, xyzw);
} else {
- copymem(&surface->array_local[a.ofs+i*surface->stride], xyzw, a.size);
+ copymem(&surface->array_local[a.ofs + i * surface->stride], xyzw, a.size);
};
-
}
if (surface->array_local == 0) {
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
};
} break;
case VS::ARRAY_COLOR: {
- ERR_FAIL_COND_V( p_array.get_type() != Variant::COLOR_ARRAY, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::COLOR_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Color> array = p_array;
- ERR_FAIL_COND_V( array.size() != surface->array_len, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(array.size() != surface->array_len, ERR_INVALID_PARAMETER);
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
-
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
PoolVector<Color>::Read read = array.read();
- const Color* src = read.ptr();
- surface->has_alpha_cache=false;
+ const Color *src = read.ptr();
+ surface->has_alpha_cache = false;
- for (int i=0;i<surface->array_len;i++) {
+ for (int i = 0; i < surface->array_len; i++) {
- if (src[i].a<0.98) // tolerate alpha a bit, for crappy exporters
- surface->has_alpha_cache=true;
- uint8_t colors[4]={ src[i].r * 255.0 , src[i].g * 255.0, src[i].b * 255.0, src[i].a * 255.0 };
+ if (src[i].a < 0.98) // tolerate alpha a bit, for crappy exporters
+ surface->has_alpha_cache = true;
+ uint8_t colors[4] = { src[i].r * 255.0, src[i].g * 255.0, src[i].b * 255.0, src[i].a * 255.0 };
// I'm not sure if this is correct, endianness-wise, i should re-check the GL spec
if (surface->array_local == 0)
- glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , colors );
+ glBufferSubData(GL_ARRAY_BUFFER, a.ofs + i * surface->stride, a.size, colors);
else
- copymem(&surface->array_local[a.ofs+i*surface->stride], colors, a.size);
-
+ copymem(&surface->array_local[a.ofs + i * surface->stride], colors, a.size);
}
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,0);
-
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
} break;
case VS::ARRAY_TEX_UV: {
- ERR_FAIL_COND_V( p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector3> array = p_array;
- ERR_FAIL_COND_V( array.size() != surface->array_len , ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(array.size() != surface->array_len, ERR_INVALID_PARAMETER);
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
PoolVector<Vector3>::Read read = array.read();
- const Vector3 * src=read.ptr();
+ const Vector3 *src = read.ptr();
- for (int i=0;i<surface->array_len;i++) {
+ for (int i = 0; i < surface->array_len; i++) {
- GLfloat uv[2]={ src[i].x , src[i].y };
+ GLfloat uv[2] = { src[i].x, src[i].y };
if (surface->array_local == 0)
- glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , uv );
+ glBufferSubData(GL_ARRAY_BUFFER, a.ofs + i * surface->stride, a.size, uv);
else
- copymem(&surface->array_local[a.ofs+i*surface->stride], uv, a.size);
-
+ copymem(&surface->array_local[a.ofs + i * surface->stride], uv, a.size);
}
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
} break;
case VS::ARRAY_BONES:
case VS::ARRAY_WEIGHTS: {
-
- ERR_FAIL_COND_V( p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_array;
- ERR_FAIL_COND_V( array.size() != surface->array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(array.size() != surface->array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER);
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBindBuffer(GL_ARRAY_BUFFER, surface->vertex_id);
PoolVector<real_t>::Read read = array.read();
- const real_t * src = read.ptr();
+ const real_t *src = read.ptr();
- for (int i=0;i<surface->array_len;i++) {
+ for (int i = 0; i < surface->array_len; i++) {
GLfloat data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++)
- data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++)
+ data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j];
if (surface->array_local == 0)
- glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , data );
+ glBufferSubData(GL_ARRAY_BUFFER, a.ofs + i * surface->stride, a.size, data);
else
- copymem(&surface->array_local[a.ofs+i*surface->stride], data, a.size);
-
-
+ copymem(&surface->array_local[a.ofs + i * surface->stride], data, a.size);
}
if (surface->array_local == 0)
- glBindBuffer(GL_ARRAY_BUFFER,0);
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
} break;
- default: { ERR_FAIL_V(ERR_INVALID_PARAMETER);}
+ default: { ERR_FAIL_V(ERR_INVALID_PARAMETER); }
}
- a.configured=true;
+ a.configured = true;
return OK;
}
-Variant RasterizerIPhone::mesh_surface_get_array(RID p_mesh, int p_surface,VS::ArrayType p_type) const {
+Variant RasterizerIPhone::mesh_surface_get_array(RID p_mesh, int p_surface, VS::ArrayType p_type) const {
return Variant();
}
-void RasterizerIPhone::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned) {
+void RasterizerIPhone::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material, bool p_owned) {
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_surface, mesh->surfaces.size() );
+ ERR_FAIL_INDEX(p_surface, mesh->surfaces.size());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND( !surface);
+ ERR_FAIL_COND(!surface);
if (surface->material_owned && surface->material.is_valid())
free(surface->material);
- surface->material_owned=p_owned;
+ surface->material_owned = p_owned;
- surface->material=p_material;
+ surface->material = p_material;
}
RID RasterizerIPhone::mesh_surface_get_material(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,RID());
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID() );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, RID());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID());
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, RID() );
+ ERR_FAIL_COND_V(!surface, RID());
return surface->material;
}
int RasterizerIPhone::mesh_surface_get_array_len(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, -1 );
+ ERR_FAIL_COND_V(!surface, -1);
return surface->array_len;
}
int RasterizerIPhone::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
- Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, -1 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1);
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V(!surface, -1);
- return surface->index_array_len;
+ return surface->index_array_len;
}
uint32_t RasterizerIPhone::mesh_surface_get_format(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,0);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0 );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, 0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, 0 );
+ ERR_FAIL_COND_V(!surface, 0);
return surface->format;
}
VS::PrimitiveType RasterizerIPhone::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,VS::PRIMITIVE_POINTS);
- ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_POINTS );
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, VS::PRIMITIVE_POINTS);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_POINTS);
Surface *surface = mesh->surfaces[p_surface];
- ERR_FAIL_COND_V( !surface, VS::PRIMITIVE_POINTS );
+ ERR_FAIL_COND_V(!surface, VS::PRIMITIVE_POINTS);
return surface->primitive;
}
-void RasterizerIPhone::mesh_erase_surface(RID p_mesh,int p_index) {
+void RasterizerIPhone::mesh_erase_surface(RID p_mesh, int p_index) {
- Mesh *mesh = mesh_owner.get( p_mesh );
+ Mesh *mesh = mesh_owner.get(p_mesh);
ERR_FAIL_COND(!mesh);
- ERR_FAIL_INDEX(p_index, mesh->surfaces.size() );
+ ERR_FAIL_INDEX(p_index, mesh->surfaces.size());
Surface *surface = mesh->surfaces[p_index];
- ERR_FAIL_COND( !surface);
+ ERR_FAIL_COND(!surface);
- memdelete( mesh->surfaces[p_index] );
+ memdelete(mesh->surfaces[p_index]);
mesh->surfaces.remove(p_index);
-
}
int RasterizerIPhone::mesh_get_surface_count(RID p_mesh) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,-1);
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, -1);
return mesh->surfaces.size();
}
AABB RasterizerIPhone::mesh_get_aabb(RID p_mesh) const {
- Mesh *mesh = mesh_owner.get( p_mesh );
- ERR_FAIL_COND_V(!mesh,AABB());
+ Mesh *mesh = mesh_owner.get(p_mesh);
+ ERR_FAIL_COND_V(!mesh, AABB());
AABB aabb;
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
- if (i==0)
- aabb=mesh->surfaces[i]->aabb;
+ if (i == 0)
+ aabb = mesh->surfaces[i]->aabb;
else
aabb.merge_with(mesh->surfaces[i]->aabb);
}
@@ -1128,30 +1064,20 @@ RID RasterizerIPhone::multimesh_create() {
return RID();
}
-void RasterizerIPhone::multimesh_set_instance_count(RID p_multimesh,int p_count) {
-
-
+void RasterizerIPhone::multimesh_set_instance_count(RID p_multimesh, int p_count) {
}
int RasterizerIPhone::multimesh_get_instance_count(RID p_multimesh) const {
return 0;
}
-void RasterizerIPhone::multimesh_set_mesh(RID p_multimesh,RID p_mesh) {
-
-
+void RasterizerIPhone::multimesh_set_mesh(RID p_multimesh, RID p_mesh) {
}
-void RasterizerIPhone::multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb) {
-
-
+void RasterizerIPhone::multimesh_set_aabb(RID p_multimesh, const AABB &p_aabb) {
}
-void RasterizerIPhone::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform) {
-
-
+void RasterizerIPhone::multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) {
}
-void RasterizerIPhone::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color) {
-
-
+void RasterizerIPhone::multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) {
}
RID RasterizerIPhone::multimesh_get_mesh(RID p_multimesh) const {
@@ -1163,11 +1089,11 @@ AABB RasterizerIPhone::multimesh_get_aabb(RID p_multimesh) const {
return AABB();
}
-Transform RasterizerIPhone::multimesh_instance_get_transform(RID p_multimesh,int p_index) const {
+Transform RasterizerIPhone::multimesh_instance_get_transform(RID p_multimesh, int p_index) const {
return Transform();
}
-Color RasterizerIPhone::multimesh_instance_get_color(RID p_multimesh,int p_index) const {
+Color RasterizerIPhone::multimesh_instance_get_color(RID p_multimesh, int p_index) const {
return Color();
}
@@ -1178,17 +1104,11 @@ RID RasterizerIPhone::poly_create() {
return RID();
}
-void RasterizerIPhone::poly_set_material(RID p_poly, RID p_material,bool p_owned) {
-
-
+void RasterizerIPhone::poly_set_material(RID p_poly, RID p_material, bool p_owned) {
}
-void RasterizerIPhone::poly_add_primitive(RID p_poly, const Vector<Vector3>& p_points,const Vector<Vector3>& p_normals,const Vector<Color>& p_colors,const Vector<Vector3>& p_uvs) {
-
-
+void RasterizerIPhone::poly_add_primitive(RID p_poly, const Vector<Vector3> &p_points, const Vector<Vector3> &p_normals, const Vector<Color> &p_colors, const Vector<Vector3> &p_uvs) {
}
void RasterizerIPhone::poly_clear(RID p_poly) {
-
-
}
AABB RasterizerIPhone::poly_get_aabb(RID p_poly) const {
@@ -1196,7 +1116,6 @@ AABB RasterizerIPhone::poly_get_aabb(RID p_poly) const {
return AABB();
}
-
/* PARTICLES API */
RID RasterizerIPhone::particles_create() {
@@ -1205,8 +1124,6 @@ RID RasterizerIPhone::particles_create() {
}
void RasterizerIPhone::particles_set_amount(RID p_particles, int p_amount) {
-
-
}
int RasterizerIPhone::particles_get_amount(RID p_particles) const {
@@ -1214,8 +1131,6 @@ int RasterizerIPhone::particles_get_amount(RID p_particles) const {
}
void RasterizerIPhone::particles_set_emitting(RID p_particles, bool p_emitting) {
-
-
}
bool RasterizerIPhone::particles_is_emitting(RID p_particles) const {
@@ -1223,45 +1138,35 @@ bool RasterizerIPhone::particles_is_emitting(RID p_particles) const {
return false;
}
-void RasterizerIPhone::particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility) {
-
-
+void RasterizerIPhone::particles_set_visibility_aabb(RID p_particles, const AABB &p_visibility) {
}
AABB RasterizerIPhone::particles_get_visibility_aabb(RID p_particles) const {
return AABB();
}
-void RasterizerIPhone::particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents) {
-
-
+void RasterizerIPhone::particles_set_emission_half_extents(RID p_particles, const Vector3 &p_half_extents) {
}
Vector3 RasterizerIPhone::particles_get_emission_half_extents(RID p_particles) const {
return Vector3();
}
-void RasterizerIPhone::particles_set_gravity_normal(RID p_particles, const Vector3& p_normal) {
-
-
+void RasterizerIPhone::particles_set_gravity_normal(RID p_particles, const Vector3 &p_normal) {
}
Vector3 RasterizerIPhone::particles_get_gravity_normal(RID p_particles) const {
return Vector3();
}
-void RasterizerIPhone::particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value) {
-
-
+void RasterizerIPhone::particles_set_variable(RID p_particles, VS::ParticleVariable p_variable, float p_value) {
}
float RasterizerIPhone::particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const {
return 0;
}
-void RasterizerIPhone::particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness) {
-
-
+void RasterizerIPhone::particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable, float p_randomness) {
}
float RasterizerIPhone::particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const {
@@ -1269,8 +1174,6 @@ float RasterizerIPhone::particles_get_randomness(RID p_particles, VS::ParticleVa
}
void RasterizerIPhone::particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos) {
-
-
}
float RasterizerIPhone::particles_get_color_phase_pos(RID p_particles, int p_phase) const {
@@ -1278,17 +1181,13 @@ float RasterizerIPhone::particles_get_color_phase_pos(RID p_particles, int p_pha
}
void RasterizerIPhone::particles_set_color_phases(RID p_particles, int p_phases) {
-
-
}
int RasterizerIPhone::particles_get_color_phases(RID p_particles) const {
return 0;
}
-void RasterizerIPhone::particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color) {
-
-
+void RasterizerIPhone::particles_set_color_phase_color(RID p_particles, int p_phase, const Color &p_color) {
}
Color RasterizerIPhone::particles_get_color_phase_color(RID p_particles, int p_phase) const {
@@ -1296,35 +1195,27 @@ Color RasterizerIPhone::particles_get_color_phase_color(RID p_particles, int p_p
}
void RasterizerIPhone::particles_set_attractors(RID p_particles, int p_attractors) {
-
-
}
int RasterizerIPhone::particles_get_attractors(RID p_particles) const {
return 0;
}
-void RasterizerIPhone::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos) {
-
-
+void RasterizerIPhone::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3 &p_pos) {
}
-Vector3 RasterizerIPhone::particles_get_attractor_pos(RID p_particles,int p_attractor) const {
+Vector3 RasterizerIPhone::particles_get_attractor_pos(RID p_particles, int p_attractor) const {
return Vector3();
}
void RasterizerIPhone::particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force) {
-
-
}
-float RasterizerIPhone::particles_get_attractor_strength(RID p_particles,int p_attractor) const {
+float RasterizerIPhone::particles_get_attractor_strength(RID p_particles, int p_attractor) const {
return 0;
}
-void RasterizerIPhone::particles_set_material(RID p_particles, RID p_material,bool p_owned) {
-
-
+void RasterizerIPhone::particles_set_material(RID p_particles, RID p_material, bool p_owned) {
}
RID RasterizerIPhone::particles_get_material(RID p_particles) const {
@@ -1344,30 +1235,22 @@ RID RasterizerIPhone::beam_create() {
}
void RasterizerIPhone::beam_set_point_count(RID p_beam, int p_count) {
-
-
}
int RasterizerIPhone::beam_get_point_count(RID p_beam) const {
return 0;
}
void RasterizerIPhone::beam_clear(RID p_beam) {
-
-
}
-void RasterizerIPhone::beam_set_point(RID p_beam,int p_point,Vector3& p_pos) {
-
-
+void RasterizerIPhone::beam_set_point(RID p_beam, int p_point, Vector3 &p_pos) {
}
-Vector3 RasterizerIPhone::beam_get_point(RID p_beam,int p_point) const {
+Vector3 RasterizerIPhone::beam_get_point(RID p_beam, int p_point) const {
return Vector3();
}
-void RasterizerIPhone::beam_set_primitive(RID p_beam,VS::BeamPrimitive p_primitive) {
-
-
+void RasterizerIPhone::beam_set_primitive(RID p_beam, VS::BeamPrimitive p_primitive) {
}
VS::BeamPrimitive RasterizerIPhone::beam_get_primitive(RID p_beam) const {
@@ -1376,8 +1259,6 @@ VS::BeamPrimitive RasterizerIPhone::beam_get_primitive(RID p_beam) const {
}
void RasterizerIPhone::beam_set_material(RID p_beam, RID p_material) {
-
-
}
RID RasterizerIPhone::beam_get_material(RID p_beam) const {
@@ -1392,154 +1273,151 @@ AABB RasterizerIPhone::beam_get_aabb(RID p_particles) const {
RID RasterizerIPhone::skeleton_create() {
- Skeleton *skeleton = memnew( Skeleton );
- ERR_FAIL_COND_V(!skeleton,RID());
- return skeleton_owner.make_rid( skeleton );
+ Skeleton *skeleton = memnew(Skeleton);
+ ERR_FAIL_COND_V(!skeleton, RID());
+ return skeleton_owner.make_rid(skeleton);
}
-void RasterizerIPhone::skeleton_resize(RID p_skeleton,int p_bones) {
+void RasterizerIPhone::skeleton_resize(RID p_skeleton, int p_bones) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND(!skeleton);
if (p_bones == skeleton->bones.size()) {
return;
};
- ERR_FAIL_COND( p_bones<0 || p_bones>256);
+ ERR_FAIL_COND(p_bones < 0 || p_bones > 256);
skeleton->bones.resize(p_bones);
-
}
int RasterizerIPhone::skeleton_get_bone_count(RID p_skeleton) const {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND_V(!skeleton, -1);
return skeleton->bones.size();
}
-void RasterizerIPhone::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform) {
+void RasterizerIPhone::skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND(!skeleton);
- ERR_FAIL_INDEX( p_bone, skeleton->bones.size() );
+ ERR_FAIL_INDEX(p_bone, skeleton->bones.size());
skeleton->bones[p_bone] = p_transform;
}
-Transform RasterizerIPhone::skeleton_bone_get_transform(RID p_skeleton,int p_bone) {
+Transform RasterizerIPhone::skeleton_bone_get_transform(RID p_skeleton, int p_bone) {
- Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ Skeleton *skeleton = skeleton_owner.get(p_skeleton);
ERR_FAIL_COND_V(!skeleton, Transform());
- ERR_FAIL_INDEX_V( p_bone, skeleton->bones.size(), Transform() );
+ ERR_FAIL_INDEX_V(p_bone, skeleton->bones.size(), Transform());
// something
return skeleton->bones[p_bone];
}
-
/* LIGHT API */
RID RasterizerIPhone::light_create(VS::LightType p_type) {
- Light *light = memnew( Light );
- light->type=p_type;
+ Light *light = memnew(Light);
+ light->type = p_type;
return light_owner.make_rid(light);
}
VS::LightType RasterizerIPhone::light_get_type(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI);
+ ERR_FAIL_COND_V(!light, VS::LIGHT_OMNI);
return light->type;
}
-void RasterizerIPhone::light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color) {
+void RasterizerIPhone::light_set_color(RID p_light, VS::LightColor p_type, const Color &p_color) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- ERR_FAIL_INDEX( p_type, 3 );
- light->colors[p_type]=p_color;
+ ERR_FAIL_INDEX(p_type, 3);
+ light->colors[p_type] = p_color;
}
-Color RasterizerIPhone::light_get_color(RID p_light,VS::LightColor p_type) const {
+Color RasterizerIPhone::light_get_color(RID p_light, VS::LightColor p_type) const {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND_V(!light, Color());
- ERR_FAIL_INDEX_V( p_type, 3, Color() );
+ ERR_FAIL_INDEX_V(p_type, 3, Color());
return light->colors[p_type];
}
-void RasterizerIPhone::light_set_shadow(RID p_light,bool p_enabled) {
+void RasterizerIPhone::light_set_shadow(RID p_light, bool p_enabled) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->shadow_enabled=p_enabled;
+ light->shadow_enabled = p_enabled;
}
bool RasterizerIPhone::light_has_shadow(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,false);
+ ERR_FAIL_COND_V(!light, false);
return light->shadow_enabled;
}
-void RasterizerIPhone::light_set_volumetric(RID p_light,bool p_enabled) {
+void RasterizerIPhone::light_set_volumetric(RID p_light, bool p_enabled) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->volumetric_enabled=p_enabled;
-
+ light->volumetric_enabled = p_enabled;
}
bool RasterizerIPhone::light_is_volumetric(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,false);
+ ERR_FAIL_COND_V(!light, false);
return light->volumetric_enabled;
}
-void RasterizerIPhone::light_set_projector(RID p_light,RID p_texture) {
+void RasterizerIPhone::light_set_projector(RID p_light, RID p_texture) {
Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- light->projector=p_texture;
+ light->projector = p_texture;
}
RID RasterizerIPhone::light_get_projector(RID p_light) const {
Light *light = light_owner.get(p_light);
- ERR_FAIL_COND_V(!light,RID());
+ ERR_FAIL_COND_V(!light, RID());
return light->projector;
}
void RasterizerIPhone::light_set_var(RID p_light, VS::LightParam p_var, float p_value) {
- Light * light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND(!light);
- ERR_FAIL_INDEX( p_var, VS::LIGHT_PARAM_MAX );
+ ERR_FAIL_INDEX(p_var, VS::LIGHT_PARAM_MAX);
- light->vars[p_var]=p_value;
+ light->vars[p_var] = p_value;
}
float RasterizerIPhone::light_get_var(RID p_light, VS::LightParam p_var) const {
- Light * light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,0);
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, 0);
- ERR_FAIL_INDEX_V( p_var, VS::LIGHT_PARAM_MAX,0 );
+ ERR_FAIL_INDEX_V(p_var, VS::LIGHT_PARAM_MAX, 0);
return light->vars[p_var];
}
AABB RasterizerIPhone::light_get_aabb(RID p_light) const {
- Light *light = light_owner.get( p_light );
- ERR_FAIL_COND_V(!light,AABB());
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, AABB());
- switch( light->type ) {
+ switch (light->type) {
case VS::LIGHT_SPOT: {
- float len=light->vars[VS::LIGHT_PARAM_RADIUS];
- float size=Math::tan(Math::deg2rad(light->vars[VS::LIGHT_PARAM_SPOT_ANGLE]))*len;
- return AABB( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) );
+ float len = light->vars[VS::LIGHT_PARAM_RADIUS];
+ float size = Math::tan(Math::deg2rad(light->vars[VS::LIGHT_PARAM_SPOT_ANGLE])) * len;
+ return AABB(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
} break;
case VS::LIGHT_OMNI: {
float r = light->vars[VS::LIGHT_PARAM_RADIUS];
- return AABB( -Vector3(r,r,r), Vector3(r,r,r)*2 );
+ return AABB(-Vector3(r, r, r), Vector3(r, r, r) * 2);
} break;
case VS::LIGHT_DIRECTIONAL: {
@@ -1548,37 +1426,34 @@ AABB RasterizerIPhone::light_get_aabb(RID p_light) const {
default: {}
}
- ERR_FAIL_V( AABB() );
+ ERR_FAIL_V(AABB());
}
-
RID RasterizerIPhone::light_instance_create(RID p_light) {
- Light *light = light_owner.get( p_light );
+ Light *light = light_owner.get(p_light);
ERR_FAIL_COND_V(!light, RID());
- LightInstance *light_instance = memnew( LightInstance );
+ LightInstance *light_instance = memnew(LightInstance);
- light_instance->light=p_light;
- light_instance->base=light;
- light_instance->last_pass=0;
+ light_instance->light = p_light;
+ light_instance->base = light;
+ light_instance->last_pass = 0;
- return light_instance_owner.make_rid( light_instance );
+ return light_instance_owner.make_rid(light_instance);
}
-void RasterizerIPhone::light_instance_set_transform(RID p_light_instance,const Transform& p_transform) {
+void RasterizerIPhone::light_instance_set_transform(RID p_light_instance, const Transform &p_transform) {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!lighti);
- lighti->transform=p_transform;
-
+ lighti->transform = p_transform;
}
void RasterizerIPhone::light_instance_set_active_hint(RID p_light_instance) {
- LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ LightInstance *lighti = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!lighti);
- lighti->last_pass=frame;
-
+ lighti->last_pass = frame;
}
bool RasterizerIPhone::light_instance_has_shadow(RID p_light_instance) const {
@@ -1596,9 +1471,7 @@ int RasterizerIPhone::light_instance_get_shadow_passes(RID p_light_instance) con
return 0;
}
-void RasterizerIPhone::light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near,float p_far, const CameraMatrix& p_camera, const Transform& p_transform) {
-
-
+void RasterizerIPhone::light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near, float p_far, const CameraMatrix &p_camera, const Transform &p_transform) {
}
/* PARTICLES INSTANCE */
@@ -1607,32 +1480,30 @@ RID RasterizerIPhone::particles_instance_create(RID p_particles) {
return RID();
}
-void RasterizerIPhone::particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform) {
-
-
+void RasterizerIPhone::particles_instance_set_transform(RID p_particles_instance, const Transform &p_transform) {
}
/* RENDER API */
/* all calls (inside begin/end shadow) are always warranted to be in the following order: */
-static GLfloat rtri; // Angle For The Triangle ( NEW )
-static GLfloat rquad; // Angle For The Quad ( NEW )
+static GLfloat rtri; // Angle For The Triangle ( NEW )
+static GLfloat rquad; // Angle For The Quad ( NEW )
void RasterizerIPhone::begin_frame() {
- window_size = Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height );
+ window_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
- double time = (OS::get_singleton()->get_ticks_usec()/1000); // get msec
- time/=1000.0; // make secs
- time_delta=time-last_time;
- last_time=time;
+ double time = (OS::get_singleton()->get_ticks_usec() / 1000); // get msec
+ time /= 1000.0; // make secs
+ time_delta = time - last_time;
+ last_time = time;
frame++;
- glClearColor(0,0,1,1);
+ glClearColor(0, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
- /* nehe ?*/
+/* nehe ?*/
- #if 0
+#if 0
glViewport(0,0,window_size.width,window_size.height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
@@ -1723,50 +1594,46 @@ void RasterizerIPhone::begin_frame() {
rtri+=0.2f; // Increase The Rotation Variable For The Triangle ( NEW )
rquad-=0.15f; // Decrease The Rotation Variable For The Quad ( NEW )
- #endif
-
+#endif
}
-void RasterizerIPhone::set_viewport(const VS::ViewportRect& p_viewport) {
-
+void RasterizerIPhone::set_viewport(const VS::ViewportRect &p_viewport) {
- viewport=p_viewport;
- canvas_transform=Transform();
+ viewport = p_viewport;
+ canvas_transform = Transform();
canvas_transform.translate(-(viewport.width / 2.0f), -(viewport.height / 2.0f), 0.0f);
- canvas_transform.scale( Vector3( 2.0f / viewport.width, -2.0f / viewport.height, 1.0f ) );
+ canvas_transform.scale(Vector3(2.0f / viewport.width, -2.0f / viewport.height, 1.0f));
- glViewport( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
+ glViewport(viewport.x, window_size.height - (viewport.height + viewport.y), viewport.width, viewport.height);
}
-void RasterizerIPhone::begin_scene(RID p_fx,VS::ScenarioDebugMode p_debug) {
+void RasterizerIPhone::begin_scene(RID p_fx, VS::ScenarioDebugMode p_debug) {
opaque_render_list.clear();
alpha_render_list.clear();
- light_instance_count=0;
+ light_instance_count = 0;
scene_fx = p_fx.is_valid() ? fx_owner.get(p_fx) : NULL;
};
-void RasterizerIPhone::begin_shadow_map( RID p_light_instance, int p_shadow_pass ) {
-
-
+void RasterizerIPhone::begin_shadow_map(RID p_light_instance, int p_shadow_pass) {
}
-void RasterizerIPhone::set_camera(const Transform& p_world,const CameraMatrix& p_projection) {
+void RasterizerIPhone::set_camera(const Transform &p_world, const CameraMatrix &p_projection) {
- camera_transform=p_world;
- camera_transform_inverse=camera_transform.inverse();
- camera_projection=p_projection;
- camera_plane = Plane( camera_transform.origin, camera_transform.basis.get_axis(2) );
- camera_z_near=camera_projection.get_z_near();
-camera_z_far=camera_projection.get_z_far();
- camera_projection.get_viewport_size(camera_vp_size.x,camera_vp_size.y);
+ camera_transform = p_world;
+ camera_transform_inverse = camera_transform.inverse();
+ camera_projection = p_projection;
+ camera_plane = Plane(camera_transform.origin, camera_transform.basis.get_axis(2));
+ camera_z_near = camera_projection.get_z_near();
+ camera_z_far = camera_projection.get_z_far();
+ camera_projection.get_viewport_size(camera_vp_size.x, camera_vp_size.y);
}
-void RasterizerIPhone::add_light( RID p_light_instance ) {
+void RasterizerIPhone::add_light(RID p_light_instance) {
#define LIGHT_FADE_TRESHOLD 0.05
- ERR_FAIL_COND( light_instance_count >= MAX_LIGHTS );
+ ERR_FAIL_COND(light_instance_count >= MAX_LIGHTS);
LightInstance *li = light_instance_owner.get(p_light_instance);
ERR_FAIL_COND(!li);
@@ -1776,200 +1643,193 @@ void RasterizerIPhone::add_light( RID p_light_instance ) {
// actually, not really a hash, but helps to sort the lights
// and avoid recompiling redudant shader versions
- li->hash_aux=li->base->type;
+ li->hash_aux = li->base->type;
if (li->base->shadow_enabled)
- li->hash_aux|=(1<<3);
+ li->hash_aux |= (1 << 3);
- if (li->base->projector.is_valid())
- li->hash_aux|=(1<<4);
+ if (li->base->projector.is_valid())
+ li->hash_aux |= (1 << 4);
- if (li->base->shadow_enabled && li->base->volumetric_enabled)
- li->hash_aux|=(1<<5);
+ if (li->base->shadow_enabled && li->base->volumetric_enabled)
+ li->hash_aux |= (1 << 5);
- switch(li->base->type) {
+ switch (li->base->type) {
case VisualServer::LIGHT_DIRECTIONAL: {
Vector3 dir = li->transform.basis.get_axis(2);
- li->light_vector.x=dir.x;
- li->light_vector.y=dir.y;
- li->light_vector.z=dir.z;
+ li->light_vector.x = dir.x;
+ li->light_vector.y = dir.y;
+ li->light_vector.z = dir.z;
} break;
case VisualServer::LIGHT_OMNI: {
- float radius = li->base->vars[VisualServer::LIGHT_PARAM_RADIUS];
- if (radius==0)
- radius=0.0001;
- li->linear_att=(1/LIGHT_FADE_TRESHOLD)/radius;
- li->light_vector.x=li->transform.origin.x;
- li->light_vector.y=li->transform.origin.y;
- li->light_vector.z=li->transform.origin.z;
+ float radius = li->base->vars[VisualServer::LIGHT_PARAM_RADIUS];
+ if (radius == 0)
+ radius = 0.0001;
+ li->linear_att = (1 / LIGHT_FADE_TRESHOLD) / radius;
+ li->light_vector.x = li->transform.origin.x;
+ li->light_vector.y = li->transform.origin.y;
+ li->light_vector.z = li->transform.origin.z;
} break;
case VisualServer::LIGHT_SPOT: {
float radius = li->base->vars[VisualServer::LIGHT_PARAM_RADIUS];
- if (radius==0)
- radius=0.0001;
- li->linear_att=(1/LIGHT_FADE_TRESHOLD)/radius;
- li->light_vector.x=li->transform.origin.x;
- li->light_vector.y=li->transform.origin.y;
- li->light_vector.z=li->transform.origin.z;
+ if (radius == 0)
+ radius = 0.0001;
+ li->linear_att = (1 / LIGHT_FADE_TRESHOLD) / radius;
+ li->light_vector.x = li->transform.origin.x;
+ li->light_vector.y = li->transform.origin.y;
+ li->light_vector.z = li->transform.origin.z;
Vector3 dir = -li->transform.basis.get_axis(2);
- li->spot_vector.x=dir.x;
- li->spot_vector.y=dir.y;
- li->spot_vector.z=dir.z;
+ li->spot_vector.x = dir.x;
+ li->spot_vector.y = dir.y;
+ li->spot_vector.z = dir.z;
} break;
- }
+ }
- light_instances[light_instance_count++]=li;
+ light_instances[light_instance_count++] = li;
}
-void RasterizerIPhone::_add_geometry( const Geometry* p_geometry, const Transform& p_world, uint32_t p_vertex_format, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides,const Skeleton* p_skeleton, GeometryOwner *p_owner) {
+void RasterizerIPhone::_add_geometry(const Geometry *p_geometry, const Transform &p_world, uint32_t p_vertex_format, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides, const Skeleton *p_skeleton, GeometryOwner *p_owner) {
- Material *m=NULL;
+ Material *m = NULL;
- if (p_geometry->material.is_valid())
- m=material_owner.get( p_geometry->material );
+ if (p_geometry->material.is_valid())
+ m = material_owner.get(p_geometry->material);
- if (!m) {
- m=material_owner.get( default_material );
- }
+ if (!m) {
+ m = material_owner.get(default_material);
+ }
ERR_FAIL_COND(!m);
LightInstance *lights[RenderList::MAX_LIGHTS];
- int light_count=0;
+ int light_count = 0;
- RenderList *render_list=&opaque_render_list;
- if (p_geometry->has_alpha || m->detail_blend_mode!=VS::MATERIAL_BLEND_MODE_MIX) {
+ RenderList *render_list = &opaque_render_list;
+ if (p_geometry->has_alpha || m->detail_blend_mode != VS::MATERIAL_BLEND_MODE_MIX) {
render_list = &alpha_render_list;
};
if (!m->flags[VS::MATERIAL_FLAG_UNSHADED]) {
- light_count=p_light_count;
- for(int i=0;i<light_count;i++) {
- lights[i]=light_instance_owner.get( p_light_instances[i] );
+ light_count = p_light_count;
+ for (int i = 0; i < light_count; i++) {
+ lights[i] = light_instance_owner.get(p_light_instances[i]);
}
}
- render_list->add_element( p_geometry, m, p_world, lights, light_count, p_material_overrides,p_skeleton, camera_plane.distance(p_world.origin), p_owner );
+ render_list->add_element(p_geometry, m, p_world, lights, light_count, p_material_overrides, p_skeleton, camera_plane.distance(p_world.origin), p_owner);
}
-void RasterizerIPhone::add_mesh( RID p_mesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides, RID p_skeleton) {
+void RasterizerIPhone::add_mesh(RID p_mesh, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides, RID p_skeleton) {
Mesh *mesh = mesh_owner.get(p_mesh);
int ssize = mesh->surfaces.size();
- for (int i=0;i<ssize;i++) {
+ for (int i = 0; i < ssize; i++) {
Surface *s = mesh->surfaces[i];
- Skeleton *sk = p_skeleton.is_valid()?skeleton_owner.get(p_skeleton):NULL;
+ Skeleton *sk = p_skeleton.is_valid() ? skeleton_owner.get(p_skeleton) : NULL;
- _add_geometry(s,*p_world,s->format,p_light_instances,p_light_count,p_material_overrides,sk,NULL);
+ _add_geometry(s, *p_world, s->format, p_light_instances, p_light_count, p_material_overrides, sk, NULL);
}
- mesh->last_pass=frame;
+ mesh->last_pass = frame;
}
-void RasterizerIPhone::add_multimesh( RID p_multimesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
-
-
+void RasterizerIPhone::add_multimesh(RID p_multimesh, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides) {
}
-void RasterizerIPhone::add_poly( RID p_poly, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
+void RasterizerIPhone::add_poly(RID p_poly, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides) {
Poly *p = poly_owner.get(p_poly);
if (!p->primitives.empty()) {
const Poly::Primitive *pp = &p->primitives[0];
- uint32_t format=VisualServer::ARRAY_FORMAT_VERTEX;
+ uint32_t format = VisualServer::ARRAY_FORMAT_VERTEX;
if (!pp->normals.empty())
- format|=VisualServer::ARRAY_FORMAT_NORMAL;
+ format |= VisualServer::ARRAY_FORMAT_NORMAL;
if (!pp->colors.empty())
- format|=VisualServer::ARRAY_FORMAT_COLOR;
+ format |= VisualServer::ARRAY_FORMAT_COLOR;
if (!pp->uvs.empty())
- format|=VisualServer::ARRAY_TEX_UV;
+ format |= VisualServer::ARRAY_TEX_UV;
- _add_geometry(p,*p_world,format,p_light_instances,p_light_count,p_material_overrides,NULL, NULL);
+ _add_geometry(p, *p_world, format, p_light_instances, p_light_count, p_material_overrides, NULL, NULL);
}
}
-void RasterizerIPhone::add_beam( RID p_beam, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
-
-
+void RasterizerIPhone::add_beam(RID p_beam, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides) {
}
-void RasterizerIPhone::add_particles( RID p_particle_instance, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
-
-
+void RasterizerIPhone::add_particles(RID p_particle_instance, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides) {
}
-void RasterizerIPhone::_setup_material(const Geometry *p_geometry,const Material *p_material) {
+void RasterizerIPhone::_setup_material(const Geometry *p_geometry, const Material *p_material) {
if (p_material->flags[VS::MATERIAL_FLAG_DOUBLE_SIDED])
glDisable(GL_CULL_FACE);
else {
glEnable(GL_CULL_FACE);
- glCullFace( (p_material->flags[VS::MATERIAL_FLAG_INVERT_FACES])?GL_FRONT:GL_BACK);
+ glCullFace((p_material->flags[VS::MATERIAL_FLAG_INVERT_FACES]) ? GL_FRONT : GL_BACK);
}
glEnable(GL_COLOR_MATERIAL); /* unused, unless color array */
//glColorMaterial( GL_FRONT_AND_BACK, GL_DIFFUSE );
- glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
///ambient @TODO offer global ambient group option
- float ambient_rgba[4]={
+ float ambient_rgba[4] = {
1,
1,
1,
1.0
};
- glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient_rgba);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient_rgba);
///diffuse
- const Color &diffuse_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_DIFFUSE];
- float diffuse_rgba[4]={
+ const Color &diffuse_color = p_material->parameters[VS::FIXED_MATERIAL_PARAM_DIFFUSE];
+ float diffuse_rgba[4] = {
(float)diffuse_color.r,
- (float)diffuse_color.g,
- (float)diffuse_color.b,
- (float)diffuse_color.a
+ (float)diffuse_color.g,
+ (float)diffuse_color.b,
+ (float)diffuse_color.a
};
- glColor4f( diffuse_rgba[0],diffuse_rgba[1],diffuse_rgba[2],diffuse_rgba[3]);
+ glColor4f(diffuse_rgba[0], diffuse_rgba[1], diffuse_rgba[2], diffuse_rgba[3]);
- glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse_rgba);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse_rgba);
//specular
- const Color &specular_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR];
- float specular_rgba[4]={
+ const Color &specular_color = p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR];
+ float specular_rgba[4] = {
(float)specular_color.r,
(float)specular_color.g,
(float)specular_color.b,
1.0
};
- glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular_rgba);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular_rgba);
- const Color &emission_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_EMISSION];
- float emission_rgba[4]={
+ const Color &emission_color = p_material->parameters[VS::FIXED_MATERIAL_PARAM_EMISSION];
+ float emission_rgba[4] = {
(float)emission_color.r,
(float)emission_color.g,
(float)emission_color.b,
1.0
};
- glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,emission_rgba);
+ glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emission_rgba);
- glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR_EXP]);
+ glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR_EXP]);
if (p_material->flags[VS::MATERIAL_FLAG_UNSHADED]) {
glDisable(GL_LIGHTING);
@@ -1987,26 +1847,24 @@ void RasterizerIPhone::_setup_material(const Geometry *p_geometry,const Material
*/
if (p_material->textures[VS::FIXED_MATERIAL_PARAM_DIFFUSE]) {
- Texture *texture = texture_owner.get( p_material->textures[VS::FIXED_MATERIAL_PARAM_DIFFUSE] );
+ Texture *texture = texture_owner.get(p_material->textures[VS::FIXED_MATERIAL_PARAM_DIFFUSE]);
ERR_FAIL_COND(!texture);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
- glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
};
};
-void RasterizerIPhone::_setup_light(LightInstance* p_instance, int p_idx) {
+void RasterizerIPhone::_setup_light(LightInstance *p_instance, int p_idx) {
- Light* ld = p_instance->base;
+ Light *ld = p_instance->base;
int glid = GL_LIGHT0 + p_idx;
- glLightfv(glid , GL_AMBIENT, ld->colors[VS::LIGHT_COLOR_AMBIENT].components );
- glLightfv(glid, GL_DIFFUSE, ld->colors[VS::LIGHT_COLOR_DIFFUSE].components );
- glLightfv(glid, GL_SPECULAR, ld->colors[VS::LIGHT_COLOR_SPECULAR].components );
-
-
+ glLightfv(glid, GL_AMBIENT, ld->colors[VS::LIGHT_COLOR_AMBIENT].components);
+ glLightfv(glid, GL_DIFFUSE, ld->colors[VS::LIGHT_COLOR_DIFFUSE].components);
+ glLightfv(glid, GL_SPECULAR, ld->colors[VS::LIGHT_COLOR_SPECULAR].components);
- switch(ld->type) {
+ switch (ld->type) {
case VS::LIGHT_DIRECTIONAL: {
/* This doesnt have attenuation */
@@ -2014,75 +1872,72 @@ void RasterizerIPhone::_setup_light(LightInstance* p_instance, int p_idx) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
- Vector3 v(0.0,0.0,-1.0); // directional lights point up by default
- v = p_instance->transform.get_basis().xform( v );
- v = camera_transform_inverse.get_basis().xform( v );
+ Vector3 v(0.0, 0.0, -1.0); // directional lights point up by default
+ v = p_instance->transform.get_basis().xform(v);
+ v = camera_transform_inverse.get_basis().xform(v);
v.normalize(); // this sucks, so it will be optimized at some point
v = -v;
- float lightpos[4]={v.x,v.y,v.z,0.0};
+ float lightpos[4] = { v.x, v.y, v.z, 0.0 };
- glLightfv(glid,GL_POSITION,lightpos); //at modelview
+ glLightfv(glid, GL_POSITION, lightpos); //at modelview
glPopMatrix();
} break;
case VS::LIGHT_OMNI: {
- glLightf(glid,GL_SPOT_CUTOFF,180.0);
- glLightf(glid,GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
- glLightf(glid,GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
- glLightf(glid,GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
+ glLightf(glid, GL_SPOT_CUTOFF, 180.0);
+ glLightf(glid, GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
+ glLightf(glid, GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
+ glLightf(glid, GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
Vector3 pos = p_instance->transform.get_origin();
pos = camera_transform_inverse.xform(pos);
- float lightpos[4]={pos.x,pos.y,pos.z,1.0};
- glLightfv(glid,GL_POSITION,lightpos); //at modelview
+ float lightpos[4] = { pos.x, pos.y, pos.z, 1.0 };
+ glLightfv(glid, GL_POSITION, lightpos); //at modelview
glPopMatrix();
} break;
case VS::LIGHT_SPOT: {
- glLightf(glid,GL_SPOT_CUTOFF, ld->vars[VS::LIGHT_PARAM_SPOT_ANGLE]);
- glLightf(glid,GL_SPOT_EXPONENT, ld->vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]);
- glLightf(glid,GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
- glLightf(glid,GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
- glLightf(glid,GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
-
+ glLightf(glid, GL_SPOT_CUTOFF, ld->vars[VS::LIGHT_PARAM_SPOT_ANGLE]);
+ glLightf(glid, GL_SPOT_EXPONENT, ld->vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]);
+ glLightf(glid, GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
+ glLightf(glid, GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
+ glLightf(glid, GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
- Vector3 v(0.0,0.0,-1.0); // directional lights point up by default
- v = p_instance->transform.get_basis().xform( v );
- v = camera_transform_inverse.get_basis().xform( v );
+ Vector3 v(0.0, 0.0, -1.0); // directional lights point up by default
+ v = p_instance->transform.get_basis().xform(v);
+ v = camera_transform_inverse.get_basis().xform(v);
v.normalize(); // this sucks, so it will be optimized at some point
- float lightdir[4]={v.x, v.y, v.z, 1.0};
- glLightfv(glid,GL_SPOT_DIRECTION,lightdir); //at modelview
+ float lightdir[4] = { v.x, v.y, v.z, 1.0 };
+ glLightfv(glid, GL_SPOT_DIRECTION, lightdir); //at modelview
v = p_instance->transform.get_origin();
v = camera_transform_inverse.xform(v);
- float lightpos[4]={v.x,v.y,v.z,1.0};
- glLightfv(glid,GL_POSITION,lightpos); //at modelview
-
+ float lightpos[4] = { v.x, v.y, v.z, 1.0 };
+ glLightfv(glid, GL_POSITION, lightpos); //at modelview
glPopMatrix();
-
} break;
default: break;
}
};
-void RasterizerIPhone::_setup_lights(LightInstance **p_lights,int p_light_count) {
+void RasterizerIPhone::_setup_lights(LightInstance **p_lights, int p_light_count) {
- for (int i=0; i<MAX_LIGHTS; i++) {
+ for (int i = 0; i < MAX_LIGHTS; i++) {
- if (i<p_light_count) {
+ if (i < p_light_count) {
glEnable(GL_LIGHT0 + i);
_setup_light(p_lights[i], i);
} else {
@@ -2104,16 +1959,15 @@ static const int gl_client_states[] = {
-1, // ARRAY_INDEX
};
-void RasterizerIPhone::_setup_geometry(const Geometry *p_geometry, const Material* p_material) {
+void RasterizerIPhone::_setup_geometry(const Geometry *p_geometry, const Material *p_material) {
-
- switch(p_geometry->type) {
+ switch (p_geometry->type) {
case Geometry::GEOMETRY_SURFACE: {
- Surface *surf = (Surface*)p_geometry;
- uint8_t *base=0;
- bool use_VBO = (surf->array_local==0);
+ Surface *surf = (Surface *)p_geometry;
+ uint8_t *base = 0;
+ bool use_VBO = (surf->array_local == 0);
if (!use_VBO) {
@@ -2125,17 +1979,17 @@ void RasterizerIPhone::_setup_geometry(const Geometry *p_geometry, const Materia
glBindBuffer(GL_ARRAY_BUFFER, surf->vertex_id);
};
- const Surface::ArrayData* a=surf->array;
- for (int i=0;i<VS::ARRAY_MAX;i++) {
+ const Surface::ArrayData *a = surf->array;
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
- const Surface::ArrayData& ad=surf->array[i];
- if (ad.size==0) {
+ const Surface::ArrayData &ad = surf->array[i];
+ if (ad.size == 0) {
if (gl_client_states[i] != -1) {
glDisableClientState(gl_client_states[i]);
};
continue; // this one is disabled.
}
- ERR_CONTINUE( !ad.configured );
+ ERR_CONTINUE(!ad.configured);
if (gl_client_states[i] != -1) {
glEnableClientState(gl_client_states[i]);
@@ -2143,55 +1997,52 @@ void RasterizerIPhone::_setup_geometry(const Geometry *p_geometry, const Materia
switch (i) {
- case VS::ARRAY_VERTEX:
- if (!use_VBO)
- glVertexPointer(3,GL_FLOAT,surf->stride,(GLvoid*)&base[a->ofs]);
- else
- if (surf->array[VS::ARRAY_BONES].size)
+ case VS::ARRAY_VERTEX:
+ if (!use_VBO)
+ glVertexPointer(3, GL_FLOAT, surf->stride, (GLvoid *)&base[a->ofs]);
+ else if (surf->array[VS::ARRAY_BONES].size)
glVertexPointer(3, GL_FLOAT, 0, skinned_buffer);
else
- glVertexPointer(3,GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
- break;
+ glVertexPointer(3, GL_FLOAT, surf->stride, (GLvoid *)a->ofs);
+ break;
- case VS::ARRAY_NORMAL:
- if (use_VBO)
- glNormalPointer(GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
- else
- glNormalPointer(GL_FLOAT,surf->stride,(GLvoid*)&base[a->ofs]);
- break;
- case VS::ARRAY_TANGENT:
- break;
- case VS::ARRAY_COLOR:
- if (use_VBO)
- glColorPointer(4,GL_UNSIGNED_BYTE,surf->stride,(GLvoid*)a->ofs);
- else
- glColorPointer(4,GL_UNSIGNED_BYTE,surf->stride,(GLvoid*)&base[a->ofs]);
- break;
- case VS::ARRAY_TEX_UV:
- case VS::ARRAY_TEX_UV2:
- if (use_VBO)
- glTexCoordPointer(2,GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
- else
- glTexCoordPointer(2,GL_FLOAT,surf->stride,&base[a->ofs]);
- break;
- case VS::ARRAY_BONES:
- case VS::ARRAY_WEIGHTS:
- case VS::ARRAY_INDEX:
- break;
+ case VS::ARRAY_NORMAL:
+ if (use_VBO)
+ glNormalPointer(GL_FLOAT, surf->stride, (GLvoid *)a->ofs);
+ else
+ glNormalPointer(GL_FLOAT, surf->stride, (GLvoid *)&base[a->ofs]);
+ break;
+ case VS::ARRAY_TANGENT:
+ break;
+ case VS::ARRAY_COLOR:
+ if (use_VBO)
+ glColorPointer(4, GL_UNSIGNED_BYTE, surf->stride, (GLvoid *)a->ofs);
+ else
+ glColorPointer(4, GL_UNSIGNED_BYTE, surf->stride, (GLvoid *)&base[a->ofs]);
+ break;
+ case VS::ARRAY_TEX_UV:
+ case VS::ARRAY_TEX_UV2:
+ if (use_VBO)
+ glTexCoordPointer(2, GL_FLOAT, surf->stride, (GLvoid *)a->ofs);
+ else
+ glTexCoordPointer(2, GL_FLOAT, surf->stride, &base[a->ofs]);
+ break;
+ case VS::ARRAY_BONES:
+ case VS::ARRAY_WEIGHTS:
+ case VS::ARRAY_INDEX:
+ break;
};
}
-
// process skeleton here
} break;
default: break;
-
};
};
-static const GLenum gl_primitive[]={
+static const GLenum gl_primitive[] = {
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
@@ -2201,64 +2052,60 @@ static const GLenum gl_primitive[]={
GL_TRIANGLE_FAN
};
-void RasterizerIPhone::_render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton) {
-
+void RasterizerIPhone::_render(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton) {
- switch(p_geometry->type) {
+ switch (p_geometry->type) {
case Geometry::GEOMETRY_SURFACE: {
+ Surface *s = (Surface *)p_geometry;
- Surface *s = (Surface*)p_geometry;
-
- if (s->index_array_len>0) {
+ if (s->index_array_len > 0) {
if (s->index_array_local) {
- glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->index_array_len>(1<<8))?GL_UNSIGNED_SHORT:GL_UNSIGNED_BYTE, s->index_array_local);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->index_array_len > (1 << 8)) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE, s->index_array_local);
} else {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
- glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->index_array_len>(1<<8))?GL_UNSIGNED_SHORT:GL_UNSIGNED_BYTE,0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, s->index_id);
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->index_array_len > (1 << 8)) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE, 0);
}
-
} else {
- glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
-
+ glDrawArrays(gl_primitive[s->primitive], 0, s->array_len);
};
} break;
- default: break;
+ default: break;
};
};
void RasterizerIPhone::_render_list_forward(RenderList *p_render_list) {
- const Material *prev_material=NULL;
- uint64_t prev_light_hash=0;
- const Skeleton *prev_skeleton=NULL;
- const Geometry *prev_geometry=NULL;
- const ParamOverrideMap* prev_overrides=NULL; // make it diferent than NULL
+ const Material *prev_material = NULL;
+ uint64_t prev_light_hash = 0;
+ const Skeleton *prev_skeleton = NULL;
+ const Geometry *prev_geometry = NULL;
+ const ParamOverrideMap *prev_overrides = NULL; // make it diferent than NULL
- Geometry::Type prev_geometry_type=Geometry::GEOMETRY_INVALID;
+ Geometry::Type prev_geometry_type = Geometry::GEOMETRY_INVALID;
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(&camera_projection.matrix[0][0]);
- for (int i=0;i<p_render_list->element_count;i++) {
+ for (int i = 0; i < p_render_list->element_count; i++) {
RenderList::Element *e = p_render_list->elements[i];
const Material *material = e->material;
uint64_t light_hash = e->light_hash;
const Skeleton *skeleton = e->skeleton;
const Geometry *geometry = e->geometry;
- const ParamOverrideMap* material_overrides=e->material_overrides;
+ const ParamOverrideMap *material_overrides = e->material_overrides;
- if (material!=prev_material || geometry->type!=prev_geometry_type) {
- _setup_material(e->geometry,material);
+ if (material != prev_material || geometry->type != prev_geometry_type) {
+ _setup_material(e->geometry, material);
//_setup_material_overrides(e->material,NULL,material_overrides);
//_setup_material_skeleton(material,skeleton);
} else {
@@ -2268,18 +2115,18 @@ void RasterizerIPhone::_render_list_forward(RenderList *p_render_list) {
//_setup_material_overrides(e->material,prev_overrides,material_overrides);
}
- if (prev_skeleton!=skeleton) {
+ if (prev_skeleton != skeleton) {
//_setup_material_skeleton(material,skeleton);
};
}
- if (geometry!=prev_geometry || geometry->type!=prev_geometry_type) {
+ if (geometry != prev_geometry || geometry->type != prev_geometry_type) {
_setup_geometry(geometry, material);
};
- if (i==0 || light_hash!=prev_light_hash)
- _setup_lights(e->lights,e->light_count);
+ if (i == 0 || light_hash != prev_light_hash)
+ _setup_lights(e->lights, e->light_count);
glMatrixMode(GL_MODELVIEW);
_gl_load_transform(camera_transform_inverse);
@@ -2287,12 +2134,12 @@ void RasterizerIPhone::_render_list_forward(RenderList *p_render_list) {
_render(geometry, material, skeleton);
- prev_material=material;
- prev_skeleton=skeleton;
- prev_geometry=geometry;
- prev_light_hash=e->light_hash;
- prev_geometry_type=geometry->type;
- prev_overrides=material_overrides;
+ prev_material = material;
+ prev_skeleton = skeleton;
+ prev_geometry = geometry;
+ prev_light_hash = e->light_hash;
+ prev_geometry_type = geometry->type;
+ prev_overrides = material_overrides;
}
};
@@ -2309,12 +2156,8 @@ void RasterizerIPhone::end_scene() {
alpha_render_list.sort_z();
_render_list_forward(&alpha_render_list);
-
-
}
void RasterizerIPhone::end_shadow_map() {
-
-
}
void RasterizerIPhone::end_frame() {
@@ -2337,11 +2180,9 @@ void RasterizerIPhone::canvas_begin() {
glLoadIdentity();
}
void RasterizerIPhone::canvas_set_transparency(float p_transparency) {
-
-
}
-void RasterizerIPhone::canvas_set_rect(const Rect2& p_rect, bool p_clip) {
+void RasterizerIPhone::canvas_set_rect(const Rect2 &p_rect, bool p_clip) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
@@ -2351,177 +2192,166 @@ void RasterizerIPhone::canvas_set_rect(const Rect2& p_rect, bool p_clip) {
if (p_clip) {
glEnable(GL_SCISSOR_TEST);
- glScissor(viewport.x+p_rect.pos.x,viewport.y+ (viewport.height-(p_rect.pos.y+p_rect.size.height)),
- p_rect.size.width,p_rect.size.height);
+ glScissor(viewport.x + p_rect.pos.x, viewport.y + (viewport.height - (p_rect.pos.y + p_rect.size.height)),
+ p_rect.size.width, p_rect.size.height);
} else {
glDisable(GL_SCISSOR_TEST);
}
-
-
}
-void RasterizerIPhone::canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width) {
+void RasterizerIPhone::canvas_draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width) {
glColor4f(1, 1, 1, 1);
- float verts[6]={
- p_from.x,p_from.y,0,
- p_to.x,p_to.y,0
+ float verts[6] = {
+ p_from.x, p_from.y, 0,
+ p_to.x, p_to.y, 0
};
- float colors[]={
+ float colors[] = {
p_color.r, p_color.g, p_color.b, p_color.a,
p_color.r, p_color.g, p_color.b, p_color.a,
};
glLineWidth(p_width);
- _draw_primitive(2,verts,0,colors,0);
+ _draw_primitive(2, verts, 0, colors, 0);
}
-static void _draw_textured_quad(const Rect2& p_rect, const Rect2& p_src_region, const Size2& p_tex_size ) {
+static void _draw_textured_quad(const Rect2 &p_rect, const Rect2 &p_src_region, const Size2 &p_tex_size) {
- float texcoords[]= {
- p_src_region.pos.x/p_tex_size.width,
- p_src_region.pos.y/p_tex_size.height,
+ float texcoords[] = {
+ p_src_region.pos.x / p_tex_size.width,
+ p_src_region.pos.y / p_tex_size.height,
- (p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
- p_src_region.pos.y/p_tex_size.height,
+ (p_src_region.pos.x + p_src_region.size.width) / p_tex_size.width,
+ p_src_region.pos.y / p_tex_size.height,
- (p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
- (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height,
+ (p_src_region.pos.x + p_src_region.size.width) / p_tex_size.width,
+ (p_src_region.pos.y + p_src_region.size.height) / p_tex_size.height,
- p_src_region.pos.x/p_tex_size.width,
- (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height,
+ p_src_region.pos.x / p_tex_size.width,
+ (p_src_region.pos.y + p_src_region.size.height) / p_tex_size.height,
};
- float coords[]= {
+ float coords[] = {
p_rect.pos.x, p_rect.pos.y, 0,
- p_rect.pos.x+p_rect.size.width, p_rect.pos.y, 0,
- p_rect.pos.x+p_rect.size.width, p_rect.pos.y+p_rect.size.height, 0,
- p_rect.pos.x,p_rect.pos.y+p_rect.size.height, 0
+ p_rect.pos.x + p_rect.size.width, p_rect.pos.y, 0,
+ p_rect.pos.x + p_rect.size.width, p_rect.pos.y + p_rect.size.height, 0,
+ p_rect.pos.x, p_rect.pos.y + p_rect.size.height, 0
};
- _draw_primitive(4,coords,0,0,texcoords);
+ _draw_primitive(4, coords, 0, 0, texcoords);
}
-static void _draw_quad(const Rect2& p_rect) {
+static void _draw_quad(const Rect2 &p_rect) {
- float coords[]= {
- p_rect.pos.x,p_rect.pos.y, 0,
- p_rect.pos.x+p_rect.size.width,p_rect.pos.y, 0,
- p_rect.pos.x+p_rect.size.width,p_rect.pos.y+p_rect.size.height, 0,
- p_rect.pos.x,p_rect.pos.y+p_rect.size.height, 0
+ float coords[] = {
+ p_rect.pos.x, p_rect.pos.y, 0,
+ p_rect.pos.x + p_rect.size.width, p_rect.pos.y, 0,
+ p_rect.pos.x + p_rect.size.width, p_rect.pos.y + p_rect.size.height, 0,
+ p_rect.pos.x, p_rect.pos.y + p_rect.size.height, 0
};
- _draw_primitive(4,coords,0,0,0);
-
+ _draw_primitive(4, coords, 0, 0, 0);
}
-void RasterizerIPhone::canvas_draw_rect(const Rect2& p_rect, bool p_region, const Rect2& p_source,bool p_tile,RID p_texture,const Color& p_modulate) {
+void RasterizerIPhone::canvas_draw_rect(const Rect2 &p_rect, bool p_region, const Rect2 &p_source, bool p_tile, RID p_texture, const Color &p_modulate) {
glColor4f(p_modulate.r, p_modulate.g, p_modulate.b, p_modulate.a);
- if ( p_texture.is_valid() ) {
+ if (p_texture.is_valid()) {
glEnable(GL_TEXTURE_2D);
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
if (!p_region) {
- Rect2 region = Rect2(0,0,texture->width,texture->height);
- _draw_textured_quad(p_rect,region,region.size);
+ Rect2 region = Rect2(0, 0, texture->width, texture->height);
+ _draw_textured_quad(p_rect, region, region.size);
} else {
- _draw_textured_quad(p_rect, p_source, Size2(texture->width,texture->height) );
-
+ _draw_textured_quad(p_rect, p_source, Size2(texture->width, texture->height));
}
} else {
- _draw_quad( p_rect );
-
+ _draw_quad(p_rect);
}
-
-
}
-void RasterizerIPhone::canvas_draw_style_box(const Rect2& p_rect, const Rect2& p_src_region, RID p_texture,const float *p_margin, bool p_draw_center) {
+void RasterizerIPhone::canvas_draw_style_box(const Rect2 &p_rect, const Rect2 &p_src_region, RID p_texture, const float *p_margin, bool p_draw_center) {
glColor4f(1, 1, 1, 1);
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
ERR_FAIL_COND(!texture);
glEnable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D,texture->tex_id );
-
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
Rect2 region = p_src_region;
- if (region.size.width <= 0 )
- region.size.width = texture->width;
+ if (region.size.width <= 0)
+ region.size.width = texture->width;
if (region.size.height <= 0)
- region.size.height = texture->height;
+ region.size.height = texture->height;
/* CORNERS */
_draw_textured_quad( // top left
- Rect2( p_rect.pos, Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
- Rect2( region.pos, Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
+ Rect2(p_rect.pos, Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP])),
+ Rect2(region.pos, Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // top right
- Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
- Rect2( Point2(region.pos.x+region.size.width-p_margin[MARGIN_RIGHT], region.pos.y), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
-
+ Rect2(Point2(p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_TOP])),
+ Rect2(Point2(region.pos.x + region.size.width - p_margin[MARGIN_RIGHT], region.pos.y), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom left
- Rect2( Point2(p_rect.pos.x,p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(region.pos.x, region.pos.y+region.size.height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(p_rect.pos.x, p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(region.pos.x, region.pos.y + region.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT], p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom right
- Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(region.pos.x+region.size.width-p_margin[MARGIN_RIGHT], region.pos.y+region.size.height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
-
- Rect2 rect_center( p_rect.pos+Point2( p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2( p_rect.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], p_rect.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+ Rect2(Point2(p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(region.pos.x + region.size.width - p_margin[MARGIN_RIGHT], region.pos.y + region.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT], p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
- Rect2 src_center( Point2(region.pos.x+p_margin[MARGIN_LEFT], region.pos.y+p_margin[MARGIN_TOP]), Size2(region.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], region.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+ Rect2 rect_center(p_rect.pos + Point2(p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2(p_rect.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], p_rect.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM]));
+ Rect2 src_center(Point2(region.pos.x + p_margin[MARGIN_LEFT], region.pos.y + p_margin[MARGIN_TOP]), Size2(region.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], region.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM]));
_draw_textured_quad( // top
- Rect2( Point2(rect_center.pos.x,p_rect.pos.y),Size2(rect_center.size.width,p_margin[MARGIN_TOP])),
- Rect2( Point2(src_center.pos.x,region.pos.y), Size2(src_center.size.width,p_margin[MARGIN_TOP])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x, p_rect.pos.y), Size2(rect_center.size.width, p_margin[MARGIN_TOP])),
+ Rect2(Point2(src_center.pos.x, region.pos.y), Size2(src_center.size.width, p_margin[MARGIN_TOP])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // bottom
- Rect2( Point2(rect_center.pos.x,rect_center.pos.y+rect_center.size.height),Size2(rect_center.size.width,p_margin[MARGIN_BOTTOM])),
- Rect2( Point2(src_center.pos.x,src_center.pos.y+src_center.size.height), Size2(src_center.size.width,p_margin[MARGIN_BOTTOM])),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x, rect_center.pos.y + rect_center.size.height), Size2(rect_center.size.width, p_margin[MARGIN_BOTTOM])),
+ Rect2(Point2(src_center.pos.x, src_center.pos.y + src_center.size.height), Size2(src_center.size.width, p_margin[MARGIN_BOTTOM])),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // left
- Rect2( Point2(p_rect.pos.x,rect_center.pos.y),Size2(p_margin[MARGIN_LEFT],rect_center.size.height)),
- Rect2( Point2(region.pos.x,region.pos.y+p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_LEFT],src_center.size.height)),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(p_rect.pos.x, rect_center.pos.y), Size2(p_margin[MARGIN_LEFT], rect_center.size.height)),
+ Rect2(Point2(region.pos.x, region.pos.y + p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_LEFT], src_center.size.height)),
+ Size2(texture->width, texture->height));
_draw_textured_quad( // right
- Rect2( Point2(rect_center.pos.x+rect_center.size.width,rect_center.pos.y),Size2(p_margin[MARGIN_RIGHT],rect_center.size.height)),
- Rect2( Point2(src_center.pos.x+src_center.size.width,region.pos.y+p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_RIGHT],src_center.size.height)),
- Size2( texture->width, texture->height ) );
+ Rect2(Point2(rect_center.pos.x + rect_center.size.width, rect_center.pos.y), Size2(p_margin[MARGIN_RIGHT], rect_center.size.height)),
+ Rect2(Point2(src_center.pos.x + src_center.size.width, region.pos.y + p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_RIGHT], src_center.size.height)),
+ Size2(texture->width, texture->height));
if (p_draw_center) {
_draw_textured_quad(
- rect_center,
- src_center,
- Size2( texture->width, texture->height ));
+ rect_center,
+ src_center,
+ Size2(texture->width, texture->height));
}
-
}
-void RasterizerIPhone::canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) {
+void RasterizerIPhone::canvas_draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture) {
- ERR_FAIL_COND(p_points.size()<1);
+ ERR_FAIL_COND(p_points.size() < 1);
float verts[12];
float uvs[8];
float colors[16];
@@ -2529,22 +2359,22 @@ void RasterizerIPhone::canvas_draw_primitive(const Vector<Point2>& p_points, con
glColor4f(1, 1, 1, 1);
int idx = 0;
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
- verts[idx++]=p_points[i].x;
- verts[idx++]=p_points[i].y;
- verts[idx++]=0;
+ verts[idx++] = p_points[i].x;
+ verts[idx++] = p_points[i].y;
+ verts[idx++] = 0;
}
idx = 0;
- for(int i=0;i<p_uvs.size();i++) {
+ for (int i = 0; i < p_uvs.size(); i++) {
uvs[idx++] = p_uvs[i].x;
uvs[idx++] = p_uvs[i].y;
}
idx = 0;
- for (int i=0; i<p_colors.size(); i++) {
+ for (int i = 0; i < p_colors.size(); i++) {
colors[idx++] = p_colors[i].r;
colors[idx++] = p_colors[i].g;
@@ -2554,15 +2384,14 @@ void RasterizerIPhone::canvas_draw_primitive(const Vector<Point2>& p_points, con
if (p_texture.is_valid()) {
glEnable(GL_TEXTURE_2D);
- Texture *texture = texture_owner.get( p_texture );
+ Texture *texture = texture_owner.get(p_texture);
if (texture) {
glActiveTexture(GL_TEXTURE0);
- glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+ glBindTexture(GL_TEXTURE_2D, texture->tex_id);
}
}
- _draw_primitive(p_points.size(),&verts[0],NULL,p_colors.size()?&colors[0]:NULL,p_uvs.size()?uvs:NULL);
-
+ _draw_primitive(p_points.size(), &verts[0], NULL, p_colors.size() ? &colors[0] : NULL, p_uvs.size() ? uvs : NULL);
}
/* FX */
@@ -2571,50 +2400,42 @@ RID RasterizerIPhone::fx_create() {
return RID();
}
-void RasterizerIPhone::fx_get_effects(RID p_fx,List<String> *p_effects) const {
-
-
+void RasterizerIPhone::fx_get_effects(RID p_fx, List<String> *p_effects) const {
}
-void RasterizerIPhone::fx_set_active(RID p_fx,const String& p_effect, bool p_active) {
-
-
+void RasterizerIPhone::fx_set_active(RID p_fx, const String &p_effect, bool p_active) {
}
-bool RasterizerIPhone::fx_is_active(RID p_fx,const String& p_effect) const {
+bool RasterizerIPhone::fx_is_active(RID p_fx, const String &p_effect) const {
return false;
}
-void RasterizerIPhone::fx_get_effect_params(RID p_fx,const String& p_effect,List<PropertyInfo> *p_params) const {
-
-
+void RasterizerIPhone::fx_get_effect_params(RID p_fx, const String &p_effect, List<PropertyInfo> *p_params) const {
}
-Variant RasterizerIPhone::fx_get_effect_param(RID p_fx,const String& p_effect,const String& p_param) const {
+Variant RasterizerIPhone::fx_get_effect_param(RID p_fx, const String &p_effect, const String &p_param) const {
return Variant();
}
-void RasterizerIPhone::fx_set_effect_param(RID p_fx,const String& p_effect, const String& p_param, const Variant& p_pvalue) {
-
-
+void RasterizerIPhone::fx_set_effect_param(RID p_fx, const String &p_effect, const String &p_param, const Variant &p_pvalue) {
}
/*MISC*/
-bool RasterizerIPhone::is_texture(const RID& p_rid) const {
+bool RasterizerIPhone::is_texture(const RID &p_rid) const {
return texture_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_material(const RID& p_rid) const {
+bool RasterizerIPhone::is_material(const RID &p_rid) const {
return material_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_mesh(const RID& p_rid) const {
+bool RasterizerIPhone::is_mesh(const RID &p_rid) const {
return mesh_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_multimesh(const RID& p_rid) const {
+bool RasterizerIPhone::is_multimesh(const RID &p_rid) const {
return false;
}
-bool RasterizerIPhone::is_poly(const RID& p_rid) const {
+bool RasterizerIPhone::is_poly(const RID &p_rid) const {
return poly_owner.owns(p_rid);
}
@@ -2628,46 +2449,46 @@ bool RasterizerIPhone::is_beam(const RID &p_beam) const {
return false;
}
-bool RasterizerIPhone::is_light(const RID& p_rid) const {
+bool RasterizerIPhone::is_light(const RID &p_rid) const {
return light_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_light_instance(const RID& p_rid) const {
+bool RasterizerIPhone::is_light_instance(const RID &p_rid) const {
return light_instance_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_particles_instance(const RID& p_rid) const {
+bool RasterizerIPhone::is_particles_instance(const RID &p_rid) const {
return false;
}
-bool RasterizerIPhone::is_skeleton(const RID& p_rid) const {
+bool RasterizerIPhone::is_skeleton(const RID &p_rid) const {
return skeleton_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_fx(const RID& p_rid) const {
+bool RasterizerIPhone::is_fx(const RID &p_rid) const {
return fx_owner.owns(p_rid);
}
-bool RasterizerIPhone::is_shader(const RID& p_rid) const {
+bool RasterizerIPhone::is_shader(const RID &p_rid) const {
return false;
}
-void RasterizerIPhone::free(const RID& p_rid) const {
+void RasterizerIPhone::free(const RID &p_rid) const {
if (texture_owner.owns(p_rid)) {
// delete the texture
Texture *texture = texture_owner.get(p_rid);
- glDeleteTextures( 1,&texture->tex_id );
+ glDeleteTextures(1, &texture->tex_id);
texture_owner.free(p_rid);
memdelete(texture);
} else if (material_owner.owns(p_rid)) {
- Material *material = material_owner.get( p_rid );
+ Material *material = material_owner.get(p_rid);
ERR_FAIL_COND(!material);
material_owner.free(p_rid);
@@ -2677,7 +2498,7 @@ void RasterizerIPhone::free(const RID& p_rid) const {
Mesh *mesh = mesh_owner.get(p_rid);
ERR_FAIL_COND(!mesh);
- for (int i=0;i<mesh->surfaces.size();i++) {
+ for (int i = 0; i < mesh->surfaces.size(); i++) {
Surface *surface = mesh->surfaces[i];
if (surface->array_local != 0) {
@@ -2688,11 +2509,11 @@ void RasterizerIPhone::free(const RID& p_rid) const {
};
if (surface->vertex_id)
- glDeleteBuffers(1,&surface->vertex_id);
+ glDeleteBuffers(1, &surface->vertex_id);
if (surface->index_id)
- glDeleteBuffers(1,&surface->index_id);
+ glDeleteBuffers(1, &surface->index_id);
- memdelete( surface );
+ memdelete(surface);
};
mesh->surfaces.clear();
@@ -2702,7 +2523,7 @@ void RasterizerIPhone::free(const RID& p_rid) const {
} else if (skeleton_owner.owns(p_rid)) {
- Skeleton *skeleton = skeleton_owner.get( p_rid );
+ Skeleton *skeleton = skeleton_owner.get(p_rid);
ERR_FAIL_COND(!skeleton)
skeleton_owner.free(p_rid);
@@ -2710,7 +2531,7 @@ void RasterizerIPhone::free(const RID& p_rid) const {
} else if (light_owner.owns(p_rid)) {
- Light *light = light_owner.get( p_rid );
+ Light *light = light_owner.get(p_rid);
ERR_FAIL_COND(!light)
light_owner.free(p_rid);
@@ -2718,20 +2539,19 @@ void RasterizerIPhone::free(const RID& p_rid) const {
} else if (light_instance_owner.owns(p_rid)) {
- LightInstance *light_instance = light_instance_owner.get( p_rid );
+ LightInstance *light_instance = light_instance_owner.get(p_rid);
ERR_FAIL_COND(!light_instance);
light_instance_owner.free(p_rid);
- memdelete( light_instance );
+ memdelete(light_instance);
} else if (fx_owner.owns(p_rid)) {
- FX *fx = fx_owner.get( p_rid );
+ FX *fx = fx_owner.get(p_rid);
ERR_FAIL_COND(!fx);
fx_owner.free(p_rid);
- memdelete( fx );
-
+ memdelete(fx);
};
}
@@ -2745,10 +2565,9 @@ void RasterizerIPhone::init() {
}
void RasterizerIPhone::finish() {
-
}
- int RasterizerIPhone::get_render_info(VS::RenderInfo p_info) {
+int RasterizerIPhone::get_render_info(VS::RenderInfo p_info) {
return false;
}
@@ -2758,9 +2577,8 @@ RasterizerIPhone::RasterizerIPhone() {
frame = 0;
};
-RasterizerIPhone::~RasterizerIPhone() {
+RasterizerIPhone::~RasterizerIPhone(){
};
-
#endif
diff --git a/platform/iphone/rasterizer_iphone.h b/platform/iphone/rasterizer_iphone.h
index 299a11e895..02cb985dc8 100644
--- a/platform/iphone/rasterizer_iphone.h
+++ b/platform/iphone/rasterizer_iphone.h
@@ -33,12 +33,12 @@
#include "servers/visual/rasterizer.h"
+#include "camera_matrix.h"
#include "image.h"
-#include "rid.h"
-#include "servers/visual_server.h"
#include "list.h"
#include "map.h"
-#include "camera_matrix.h"
+#include "rid.h"
+#include "servers/visual_server.h"
#include "sort.h"
#include <ES1/gl.h>
@@ -57,7 +57,7 @@ class RasterizerIPhone : public Rasterizer {
struct Texture {
uint32_t flags;
- int width,height;
+ int width, height;
Image::Format format;
GLenum target;
@@ -72,21 +72,21 @@ class RasterizerIPhone : public Rasterizer {
Texture() {
- flags=width=height=0;
- tex_id=0;
- format=Image::FORMAT_L8;
- gl_components_cache=0;
- format_has_alpha=false;
- has_alpha=false;
- active=false;
- mipmap_dirty=true;
+ flags = width = height = 0;
+ tex_id = 0;
+ format = Image::FORMAT_L8;
+ gl_components_cache = 0;
+ format_has_alpha = false;
+ has_alpha = false;
+ active = false;
+ mipmap_dirty = true;
}
~Texture() {
- if (tex_id!=0) {
+ if (tex_id != 0) {
- glDeleteTextures(1,&tex_id);
+ glDeleteTextures(1, &tex_id);
}
}
};
@@ -108,16 +108,16 @@ class RasterizerIPhone : public Rasterizer {
Material() {
- flags[VS::MATERIAL_FLAG_VISIBLE]=true;
- flags[VS::MATERIAL_FLAG_DOUBLE_SIDED]=false;
- flags[VS::MATERIAL_FLAG_INVERT_FACES]=false;
- flags[VS::MATERIAL_FLAG_UNSHADED]=false;
- flags[VS::MATERIAL_FLAG_WIREFRAME]=false;
+ flags[VS::MATERIAL_FLAG_VISIBLE] = true;
+ flags[VS::MATERIAL_FLAG_DOUBLE_SIDED] = false;
+ flags[VS::MATERIAL_FLAG_INVERT_FACES] = false;
+ flags[VS::MATERIAL_FLAG_UNSHADED] = false;
+ flags[VS::MATERIAL_FLAG_WIREFRAME] = false;
parameters[VS::FIXED_MATERIAL_PARAM_DIFFUSE] = Color(0.8, 0.8, 0.8);
parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR_EXP] = 12;
- for (int i=0; i<VisualServer::FIXED_MATERIAL_PARAM_MAX; i++) {
+ for (int i = 0; i < VisualServer::FIXED_MATERIAL_PARAM_MAX; i++) {
texcoord_mode[i] = VS::FIXED_MATERIAL_TEXCOORD_UV;
};
detail_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
@@ -126,7 +126,6 @@ class RasterizerIPhone : public Rasterizer {
};
mutable RID_Owner<Material> material_owner;
-
struct Geometry {
enum Type {
@@ -146,8 +145,12 @@ class RasterizerIPhone : public Rasterizer {
Vector3 scale;
Vector3 uv_scale;
- Geometry() : scale(1, 1, 1) { has_alpha=false; material_owned = false; }
- virtual ~Geometry() {};
+ Geometry()
+ : scale(1, 1, 1) {
+ has_alpha = false;
+ material_owned = false;
+ }
+ virtual ~Geometry(){};
};
struct GeometryOwner {
@@ -155,15 +158,18 @@ class RasterizerIPhone : public Rasterizer {
virtual ~GeometryOwner() {}
};
-
struct Surface : public Geometry {
struct ArrayData {
- uint32_t ofs,size;
+ uint32_t ofs, size;
bool configured;
int components;
- ArrayData() { ofs=0; size=0; configured=false; }
+ ArrayData() {
+ ofs = 0;
+ size = 0;
+ configured = false;
+ }
};
ArrayData array[VS::ARRAY_MAX];
@@ -196,34 +202,32 @@ class RasterizerIPhone : public Rasterizer {
Surface() {
- array_len=0;
- type=GEOMETRY_SURFACE;
- primitive=VS::PRIMITIVE_POINTS;
- index_array_len=VS::NO_INDEX_ARRAY;
- format=0;
- stride=0;
+ array_len = 0;
+ type = GEOMETRY_SURFACE;
+ primitive = VS::PRIMITIVE_POINTS;
+ index_array_len = VS::NO_INDEX_ARRAY;
+ format = 0;
+ stride = 0;
array_local = index_array_local = 0;
vertex_id = index_id = 0;
- active=false;
+ active = false;
}
~Surface() {
-
}
};
-
struct Mesh {
bool active;
- Vector<Surface*> surfaces;
+ Vector<Surface *> surfaces;
mutable uint64_t last_pass;
Mesh() {
- last_pass=0;
- active=false;
+ last_pass = 0;
+ active = false;
}
};
mutable RID_Owner<Mesh> mesh_owner;
@@ -236,29 +240,25 @@ class RasterizerIPhone : public Rasterizer {
Vector<Vector3> normals;
Vector<Vector3> uvs;
Vector<Color> colors;
-
};
AABB aabb;
List<Primitive> primitives;
Poly() {
- type=GEOMETRY_POLY;
+ type = GEOMETRY_POLY;
}
};
mutable RID_Owner<Poly> poly_owner;
-
struct Skeleton {
Vector<Transform> bones;
-
};
mutable RID_Owner<Skeleton> skeleton_owner;
-
struct Light {
VS::LightType type;
@@ -269,19 +269,18 @@ class RasterizerIPhone : public Rasterizer {
bool volumetric_enabled;
Color volumetric_color;
-
Light() {
- vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]=1;
- vars[VS::LIGHT_PARAM_SPOT_ANGLE]=45;
- vars[VS::LIGHT_PARAM_ATTENUATION]=1.0;
- vars[VS::LIGHT_PARAM_ENERGY]=1.0;
- vars[VS::LIGHT_PARAM_RADIUS]=1.0;
- colors[VS::LIGHT_COLOR_AMBIENT]=Color(0,0,0);
- colors[VS::LIGHT_COLOR_DIFFUSE]=Color(1,1,1);
- colors[VS::LIGHT_COLOR_SPECULAR]=Color(1,1,1);
- shadow_enabled=false;
- volumetric_enabled=false;
+ vars[VS::LIGHT_PARAM_SPOT_ATTENUATION] = 1;
+ vars[VS::LIGHT_PARAM_SPOT_ANGLE] = 45;
+ vars[VS::LIGHT_PARAM_ATTENUATION] = 1.0;
+ vars[VS::LIGHT_PARAM_ENERGY] = 1.0;
+ vars[VS::LIGHT_PARAM_RADIUS] = 1.0;
+ colors[VS::LIGHT_COLOR_AMBIENT] = Color(0, 0, 0);
+ colors[VS::LIGHT_COLOR_DIFFUSE] = Color(1, 1, 1);
+ colors[VS::LIGHT_COLOR_SPECULAR] = Color(1, 1, 1);
+ shadow_enabled = false;
+ volumetric_enabled = false;
}
};
@@ -302,7 +301,6 @@ class RasterizerIPhone : public Rasterizer {
uint64_t last_pass;
Transform transform;
-
CameraMatrix projection;
Vector<SplitInfo> splits;
@@ -321,8 +319,8 @@ class RasterizerIPhone : public Rasterizer {
struct RenderList {
enum {
- MAX_ELEMENTS=4096,
- MAX_LIGHTS=4
+ MAX_ELEMENTS = 4096,
+ MAX_LIGHTS = 4
};
struct Element {
@@ -330,28 +328,27 @@ class RasterizerIPhone : public Rasterizer {
float depth;
const Skeleton *skeleton;
Transform transform;
- LightInstance* lights[MAX_LIGHTS];
+ LightInstance *lights[MAX_LIGHTS];
int light_count;
const Geometry *geometry;
const Material *material;
uint64_t light_hash;
GeometryOwner *owner;
- const ParamOverrideMap* material_overrides;
+ const ParamOverrideMap *material_overrides;
};
-
Element _elements[MAX_ELEMENTS];
Element *elements[MAX_ELEMENTS];
int element_count;
void clear() {
- element_count=0;
+ element_count = 0;
}
struct SortZ {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
return A->depth > B->depth;
}
@@ -359,37 +356,37 @@ class RasterizerIPhone : public Rasterizer {
void sort_z() {
- SortArray<Element*,SortZ> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortZ> sorter;
+ sorter.sort(elements, element_count);
}
struct SortSkel {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->geometry < B->geometry)
return true;
else if (A->geometry > B->geometry)
return false;
- else return (!A->skeleton && B->skeleton);
+ else
+ return (!A->skeleton && B->skeleton);
}
};
void sort_skel() {
- SortArray<Element*,SortSkel> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortSkel> sorter;
+ sorter.sort(elements, element_count);
}
struct SortMat {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->geometry == B->geometry) {
if (A->material == B->material) {
-
return (A->material_overrides < B->material_overrides);
} else {
@@ -404,13 +401,13 @@ class RasterizerIPhone : public Rasterizer {
void sort_mat() {
- SortArray<Element*,SortMat> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMat> sorter;
+ sorter.sort(elements, element_count);
}
struct SortMatLight {
- _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+ _FORCE_INLINE_ bool operator()(const Element *A, const Element *B) const {
if (A->geometry == B->geometry) {
@@ -419,7 +416,7 @@ class RasterizerIPhone : public Rasterizer {
if (A->light_hash == B->light_hash)
return (A->material_overrides < B->material_overrides);
else
- return A->light_hash<B->light_hash;
+ return A->light_hash < B->light_hash;
} else {
return (A->material < B->material);
@@ -433,57 +430,54 @@ class RasterizerIPhone : public Rasterizer {
void sort_mat_light() {
- SortArray<Element*,SortMatLight> sorter;
- sorter.sort(elements,element_count);
+ SortArray<Element *, SortMatLight> sorter;
+ sorter.sort(elements, element_count);
}
struct LISort {
- _FORCE_INLINE_ bool operator ()(const LightInstance *A, const LightInstance *B) const {
+ _FORCE_INLINE_ bool operator()(const LightInstance *A, const LightInstance *B) const {
return (A->hash_aux < B->hash_aux);
}
};
- _FORCE_INLINE_ void add_element( const Geometry *p_geometry, const Material* p_material,const Transform& p_transform, LightInstance **p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides, const Skeleton *p_skeleton, float p_depth, GeometryOwner *p_owner=NULL) {
+ _FORCE_INLINE_ void add_element(const Geometry *p_geometry, const Material *p_material, const Transform &p_transform, LightInstance **p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides, const Skeleton *p_skeleton, float p_depth, GeometryOwner *p_owner = NULL) {
-
- ERR_FAIL_COND( element_count >= MAX_ELEMENTS );
+ ERR_FAIL_COND(element_count >= MAX_ELEMENTS);
Element *e = elements[element_count++];
- e->geometry=p_geometry;
- e->material=p_material;
- e->transform=p_transform;
- e->skeleton=p_skeleton;
- e->light_hash=0;
- e->light_count=p_light_count;
- e->owner=p_owner;
- e->material_overrides=p_material_overrides;
+ e->geometry = p_geometry;
+ e->material = p_material;
+ e->transform = p_transform;
+ e->skeleton = p_skeleton;
+ e->light_hash = 0;
+ e->light_count = p_light_count;
+ e->owner = p_owner;
+ e->material_overrides = p_material_overrides;
- if (e->light_count>0) {
+ if (e->light_count > 0) {
- SortArray<LightInstance*,LISort> light_sort;
- light_sort.sort(p_light_instances,p_light_count);
+ SortArray<LightInstance *, LISort> light_sort;
+ light_sort.sort(p_light_instances, p_light_count);
//@TODO OPTIOMIZE
- for (int i=0;i<p_light_count;i++) {
+ for (int i = 0; i < p_light_count; i++) {
- e->lights[i]=p_light_instances[i];
+ e->lights[i] = p_light_instances[i];
- if (i==0)
- e->light_hash=hash_djb2_one_64( make_uint64_t(e->lights[i]) );
+ if (i == 0)
+ e->light_hash = hash_djb2_one_64(make_uint64_t(e->lights[i]));
else
- e->light_hash=hash_djb2_one_64( make_uint64_t(e->lights[i]),e->light_hash);
+ e->light_hash = hash_djb2_one_64(make_uint64_t(e->lights[i]), e->light_hash);
}
-
}
-
}
RenderList() {
- for (int i=0;i<MAX_ELEMENTS;i++)
- elements[i]=&_elements[i]; // assign elements
+ for (int i = 0; i < MAX_ELEMENTS; i++)
+ elements[i] = &_elements[i]; // assign elements
}
};
@@ -532,11 +526,9 @@ class RasterizerIPhone : public Rasterizer {
float edge_size;
FX();
-
};
mutable RID_Owner<FX> fx_owner;
-
FX *scene_fx;
CameraMatrix camera_projection;
Transform camera_transform;
@@ -547,16 +539,15 @@ class RasterizerIPhone : public Rasterizer {
Plane camera_plane;
- void _add_geometry( const Geometry* p_geometry, const Transform& p_world, uint32_t p_vertex_format, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides,const Skeleton* p_skeleton,GeometryOwner *p_owner);
+ void _add_geometry(const Geometry *p_geometry, const Transform &p_world, uint32_t p_vertex_format, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides, const Skeleton *p_skeleton, GeometryOwner *p_owner);
void _render_list_forward(RenderList *p_render_list);
- void _setup_light(LightInstance* p_instance, int p_idx);
- void _setup_lights(LightInstance **p_lights,int p_light_count);
- void _setup_material(const Geometry *p_geometry,const Material *p_material);
-
- void _setup_geometry(const Geometry *p_geometry, const Material* p_material);
- void _render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton);
+ void _setup_light(LightInstance *p_instance, int p_idx);
+ void _setup_lights(LightInstance **p_lights, int p_light_count);
+ void _setup_material(const Geometry *p_geometry, const Material *p_material);
+ void _setup_geometry(const Geometry *p_geometry, const Material *p_material);
+ void _render(const Geometry *p_geometry, const Material *p_material, const Skeleton *p_skeleton);
/*********/
/* FRAME */
@@ -570,14 +561,13 @@ class RasterizerIPhone : public Rasterizer {
uint64_t frame;
public:
-
/* TEXTURE API */
virtual RID texture_create();
- virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT);
- virtual void texture_blit_rect(RID p_texture,int p_x,int p_y, const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT);
- virtual Image texture_get_rect(RID p_texture,int p_x,int p_y,int p_width, int p_height,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const;
- virtual void texture_set_flags(RID p_texture,uint32_t p_flags);
+ virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = VS::TEXTURE_FLAGS_DEFAULT);
+ virtual void texture_blit_rect(RID p_texture, int p_x, int p_y, const Image &p_image, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT);
+ virtual Image texture_get_rect(RID p_texture, int p_x, int p_y, int p_width, int p_height, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) const;
+ virtual void texture_set_flags(RID p_texture, uint32_t p_flags);
virtual uint32_t texture_get_flags(RID p_texture) const;
virtual Image::Format texture_get_format(RID p_texture) const;
virtual uint32_t texture_get_width(RID p_texture) const;
@@ -588,81 +578,80 @@ public:
virtual RID shader_create();
- virtual void shader_node_add(RID p_shader,VS::ShaderNodeType p_type,int p_id);
- virtual void shader_node_remove(RID p_shader,int p_id);
+ virtual void shader_node_add(RID p_shader, VS::ShaderNodeType p_type, int p_id);
+ virtual void shader_node_remove(RID p_shader, int p_id);
virtual void shader_node_change_type(RID p_shader, int p_id, VS::ShaderNodeType p_type);
- virtual void shader_node_set_param(RID p_shader, int p_id, const Variant& p_value);
+ virtual void shader_node_set_param(RID p_shader, int p_id, const Variant &p_value);
- virtual void shader_get_node_list(RID p_shader,List<int> *p_node_list) const;
- virtual VS::ShaderNodeType shader_node_get_type(RID p_shader,int p_id) const;
- virtual Variant shader_node_get_param(RID p_shader,int p_id) const;
+ virtual void shader_get_node_list(RID p_shader, List<int> *p_node_list) const;
+ virtual VS::ShaderNodeType shader_node_get_type(RID p_shader, int p_id) const;
+ virtual Variant shader_node_get_param(RID p_shader, int p_id) const;
- virtual void shader_connect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot);
- virtual bool shader_is_connected(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) const;
- virtual void shader_disconnect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot);
+ virtual void shader_connect(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot);
+ virtual bool shader_is_connected(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot) const;
+ virtual void shader_disconnect(RID p_shader, int p_src_id, int p_src_slot, int p_dst_id, int p_dst_slot);
- virtual void shader_get_connections(RID p_shader,List<VS::ShaderConnection> *p_connections) const;
+ virtual void shader_get_connections(RID p_shader, List<VS::ShaderConnection> *p_connections) const;
virtual void shader_clear(RID p_shader);
/* COMMON MATERIAL API */
- virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value);
- virtual Variant material_get_param(RID p_material, const StringName& p_param) const;
+ virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value);
+ virtual Variant material_get_param(RID p_material, const StringName &p_param) const;
virtual void material_get_param_list(RID p_material, List<String> *p_param_list) const;
- virtual void material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled);
- virtual bool material_get_flag(RID p_material,VS::MaterialFlag p_flag) const;
+ virtual void material_set_flag(RID p_material, VS::MaterialFlag p_flag, bool p_enabled);
+ virtual bool material_get_flag(RID p_material, VS::MaterialFlag p_flag) const;
- virtual void material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode);
+ virtual void material_set_blend_mode(RID p_material, VS::MaterialBlendMode p_mode);
virtual VS::MaterialBlendMode material_get_blend_mode(RID p_material) const;
- virtual void material_set_line_width(RID p_material,float p_line_width);
+ virtual void material_set_line_width(RID p_material, float p_line_width);
virtual float material_get_line_width(RID p_material) const;
/* FIXED MATERIAL */
virtual RID material_create();
- virtual void fixed_material_set_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter, const Variant& p_value);
- virtual Variant fixed_material_get_parameter(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const;
+ virtual void fixed_material_set_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter, const Variant &p_value);
+ virtual Variant fixed_material_get_parameter(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const;
- virtual void fixed_material_set_texture(RID p_material,VS::FixedSpatialMaterialParam p_parameter, RID p_texture);
- virtual RID fixed_material_get_texture(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const;
+ virtual void fixed_material_set_texture(RID p_material, VS::FixedSpatialMaterialParam p_parameter, RID p_texture);
+ virtual RID fixed_material_get_texture(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const;
- virtual void fixed_material_set_detail_blend_mode(RID p_material,VS::MaterialBlendMode p_mode);
+ virtual void fixed_material_set_detail_blend_mode(RID p_material, VS::MaterialBlendMode p_mode);
virtual VS::MaterialBlendMode fixed_material_get_detail_blend_mode(RID p_material) const;
- virtual void fixed_material_set_texgen_mode(RID p_material,VS::FixedSpatialMaterialTexGenMode p_mode);
+ virtual void fixed_material_set_texgen_mode(RID p_material, VS::FixedSpatialMaterialTexGenMode p_mode);
virtual VS::FixedSpatialMaterialTexGenMode fixed_material_get_texgen_mode(RID p_material) const;
- virtual void fixed_material_set_texcoord_mode(RID p_material,VS::FixedSpatialMaterialParam p_parameter, VS::FixedSpatialMaterialTexCoordMode p_mode);
- virtual VS::FixedSpatialMaterialTexCoordMode fixed_material_get_texcoord_mode(RID p_material,VS::FixedSpatialMaterialParam p_parameter) const;
+ virtual void fixed_material_set_texcoord_mode(RID p_material, VS::FixedSpatialMaterialParam p_parameter, VS::FixedSpatialMaterialTexCoordMode p_mode);
+ virtual VS::FixedSpatialMaterialTexCoordMode fixed_material_get_texcoord_mode(RID p_material, VS::FixedSpatialMaterialParam p_parameter) const;
- virtual void fixed_material_set_uv_transform(RID p_material,const Transform& p_transform);
+ virtual void fixed_material_set_uv_transform(RID p_material, const Transform &p_transform);
virtual Transform fixed_material_get_uv_transform(RID p_material) const;
/* SHADER MATERIAL */
virtual RID shader_material_create() const;
- virtual void shader_material_set_vertex_shader(RID p_material,RID p_shader,bool p_owned=false);
+ virtual void shader_material_set_vertex_shader(RID p_material, RID p_shader, bool p_owned = false);
virtual RID shader_material_get_vertex_shader(RID p_material) const;
- virtual void shader_material_set_fragment_shader(RID p_material,RID p_shader,bool p_owned=false);
+ virtual void shader_material_set_fragment_shader(RID p_material, RID p_shader, bool p_owned = false);
virtual RID shader_material_get_fragment_shader(RID p_material) const;
-
/* MESH API */
virtual RID mesh_create();
- virtual void mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,uint32_t p_format,int p_array_len,int p_index_array_len=VS::NO_INDEX_ARRAY);
+ virtual void mesh_add_surface(RID p_mesh, VS::PrimitiveType p_primitive, uint32_t p_format, int p_array_len, int p_index_array_len = VS::NO_INDEX_ARRAY);
- virtual Error mesh_surface_set_array(RID p_mesh, int p_surface,VS::ArrayType p_type,const Variant& p_array) ;
- virtual Variant mesh_surface_get_array(RID p_mesh, int p_surface,VS::ArrayType p_type) const;
+ virtual Error mesh_surface_set_array(RID p_mesh, int p_surface, VS::ArrayType p_type, const Variant &p_array);
+ virtual Variant mesh_surface_get_array(RID p_mesh, int p_surface, VS::ArrayType p_type) const;
- virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned=false);
+ virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material, bool p_owned = false);
virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const;
virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const;
@@ -670,7 +659,7 @@ public:
virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const;
virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const;
- virtual void mesh_erase_surface(RID p_mesh,int p_index);
+ virtual void mesh_erase_surface(RID p_mesh, int p_index);
virtual int mesh_get_surface_count(RID p_mesh) const;
virtual AABB mesh_get_aabb(RID p_mesh) const;
@@ -679,30 +668,29 @@ public:
virtual RID multimesh_create();
- virtual void multimesh_set_instance_count(RID p_multimesh,int p_count);
+ virtual void multimesh_set_instance_count(RID p_multimesh, int p_count);
virtual int multimesh_get_instance_count(RID p_multimesh) const;
- virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh);
- virtual void multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb);
- virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform);
- virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color);
+ virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh);
+ virtual void multimesh_set_aabb(RID p_multimesh, const AABB &p_aabb);
+ virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform);
+ virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color);
virtual RID multimesh_get_mesh(RID p_multimesh) const;
virtual AABB multimesh_get_aabb(RID p_multimesh) const;
- virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const;
- virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const;
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const;
+ virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const;
/* POLY API */
virtual RID poly_create();
- virtual void poly_set_material(RID p_poly, RID p_material,bool p_owned=false);
- virtual void poly_add_primitive(RID p_poly, const Vector<Vector3>& p_points,const Vector<Vector3>& p_normals,const Vector<Color>& p_colors,const Vector<Vector3>& p_uvs);
+ virtual void poly_set_material(RID p_poly, RID p_material, bool p_owned = false);
+ virtual void poly_add_primitive(RID p_poly, const Vector<Vector3> &p_points, const Vector<Vector3> &p_normals, const Vector<Color> &p_colors, const Vector<Vector3> &p_uvs);
virtual void poly_clear(RID p_poly);
virtual AABB poly_get_aabb(RID p_poly) const;
-
/* PARTICLES API */
virtual RID particles_create();
@@ -713,19 +701,19 @@ public:
virtual void particles_set_emitting(RID p_particles, bool p_emitting);
virtual bool particles_is_emitting(RID p_particles) const;
- virtual void particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility);
+ virtual void particles_set_visibility_aabb(RID p_particles, const AABB &p_visibility);
virtual AABB particles_get_visibility_aabb(RID p_particles) const;
- virtual void particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents);
+ virtual void particles_set_emission_half_extents(RID p_particles, const Vector3 &p_half_extents);
virtual Vector3 particles_get_emission_half_extents(RID p_particles) const;
- virtual void particles_set_gravity_normal(RID p_particles, const Vector3& p_normal);
+ virtual void particles_set_gravity_normal(RID p_particles, const Vector3 &p_normal);
virtual Vector3 particles_get_gravity_normal(RID p_particles) const;
- virtual void particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value);
+ virtual void particles_set_variable(RID p_particles, VS::ParticleVariable p_variable, float p_value);
virtual float particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const;
- virtual void particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness);
+ virtual void particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable, float p_randomness);
virtual float particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const;
virtual void particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos);
@@ -734,19 +722,19 @@ public:
virtual void particles_set_color_phases(RID p_particles, int p_phases);
virtual int particles_get_color_phases(RID p_particles) const;
- virtual void particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color);
+ virtual void particles_set_color_phase_color(RID p_particles, int p_phase, const Color &p_color);
virtual Color particles_get_color_phase_color(RID p_particles, int p_phase) const;
virtual void particles_set_attractors(RID p_particles, int p_attractors);
virtual int particles_get_attractors(RID p_particles) const;
- virtual void particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos);
- virtual Vector3 particles_get_attractor_pos(RID p_particles,int p_attractor) const;
+ virtual void particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3 &p_pos);
+ virtual Vector3 particles_get_attractor_pos(RID p_particles, int p_attractor) const;
virtual void particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force);
- virtual float particles_get_attractor_strength(RID p_particles,int p_attractor) const;
+ virtual float particles_get_attractor_strength(RID p_particles, int p_attractor) const;
- virtual void particles_set_material(RID p_particles, RID p_material,bool p_owned=false);
+ virtual void particles_set_material(RID p_particles, RID p_material, bool p_owned = false);
virtual RID particles_get_material(RID p_particles) const;
virtual AABB particles_get_aabb(RID p_particles) const;
@@ -758,10 +746,10 @@ public:
virtual int beam_get_point_count(RID p_beam) const;
virtual void beam_clear(RID p_beam);
- virtual void beam_set_point(RID p_beam,int p_point,Vector3& p_pos);
- virtual Vector3 beam_get_point(RID p_beam,int p_point) const;
+ virtual void beam_set_point(RID p_beam, int p_point, Vector3 &p_pos);
+ virtual Vector3 beam_get_point(RID p_beam, int p_point) const;
- virtual void beam_set_primitive(RID p_beam,VS::BeamPrimitive p_primitive);
+ virtual void beam_set_primitive(RID p_beam, VS::BeamPrimitive p_primitive);
virtual VS::BeamPrimitive beam_get_primitive(RID p_beam) const;
virtual void beam_set_material(RID p_beam, RID p_material);
@@ -771,27 +759,26 @@ public:
/* SKELETON API */
virtual RID skeleton_create();
- virtual void skeleton_resize(RID p_skeleton,int p_bones);
+ virtual void skeleton_resize(RID p_skeleton, int p_bones);
virtual int skeleton_get_bone_count(RID p_skeleton) const;
- virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform);
- virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone);
-
+ virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform);
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone);
/* LIGHT API */
virtual RID light_create(VS::LightType p_type);
virtual VS::LightType light_get_type(RID p_light) const;
- virtual void light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color);
- virtual Color light_get_color(RID p_light,VS::LightColor p_type) const;
+ virtual void light_set_color(RID p_light, VS::LightColor p_type, const Color &p_color);
+ virtual Color light_get_color(RID p_light, VS::LightColor p_type) const;
- virtual void light_set_shadow(RID p_light,bool p_enabled);
+ virtual void light_set_shadow(RID p_light, bool p_enabled);
virtual bool light_has_shadow(RID p_light) const;
- virtual void light_set_volumetric(RID p_light,bool p_enabled);
+ virtual void light_set_volumetric(RID p_light, bool p_enabled);
virtual bool light_is_volumetric(RID p_light) const;
- virtual void light_set_projector(RID p_light,RID p_texture);
+ virtual void light_set_projector(RID p_light, RID p_texture);
virtual RID light_get_projector(RID p_light) const;
virtual void light_set_var(RID p_light, VS::LightParam p_var, float p_value);
@@ -799,43 +786,42 @@ public:
virtual AABB light_get_aabb(RID p_poly) const;
-
virtual RID light_instance_create(RID p_light);
- virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform);
+ virtual void light_instance_set_transform(RID p_light_instance, const Transform &p_transform);
virtual void light_instance_set_active_hint(RID p_light_instance);
virtual bool light_instance_has_shadow(RID p_light_instance) const;
virtual bool light_instance_assign_shadow(RID p_light_instance);
virtual ShadowType light_instance_get_shadow_type(RID p_light_instance) const;
virtual int light_instance_get_shadow_passes(RID p_light_instance) const;
- virtual void light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near,float p_far, const CameraMatrix& p_camera, const Transform& p_transform);
+ virtual void light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near, float p_far, const CameraMatrix &p_camera, const Transform &p_transform);
/* PARTICLES INSTANCE */
virtual RID particles_instance_create(RID p_particles);
- virtual void particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform);
+ virtual void particles_instance_set_transform(RID p_particles_instance, const Transform &p_transform);
/* RENDER API */
/* all calls (inside begin/end shadow) are always warranted to be in the following order: */
virtual void begin_frame();
- virtual void set_viewport(const VS::ViewportRect& p_viewport);
+ virtual void set_viewport(const VS::ViewportRect &p_viewport);
- virtual void begin_scene(RID p_fx=RID(),VS::ScenarioDebugMode p_debug=VS::SCENARIO_DEBUG_DISABLED);
- virtual void begin_shadow_map( RID p_light_instance, int p_shadow_pass );
+ virtual void begin_scene(RID p_fx = RID(), VS::ScenarioDebugMode p_debug = VS::SCENARIO_DEBUG_DISABLED);
+ virtual void begin_shadow_map(RID p_light_instance, int p_shadow_pass);
- virtual void set_camera(const Transform& p_world,const CameraMatrix& p_projection);
+ virtual void set_camera(const Transform &p_world, const CameraMatrix &p_projection);
- virtual void add_light( RID p_light_instance ); ///< all "add_light" calls happen before add_geometry calls
+ virtual void add_light(RID p_light_instance); ///< all "add_light" calls happen before add_geometry calls
- typedef Map<StringName,Variant> ParamOverrideMap;
+ typedef Map<StringName, Variant> ParamOverrideMap;
- virtual void add_mesh( RID p_mesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL, RID p_skeleton=RID());
- virtual void add_multimesh( RID p_multimesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
- virtual void add_poly( RID p_poly, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
- virtual void add_beam( RID p_beam, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
- virtual void add_particles( RID p_particle_instance, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
+ virtual void add_mesh(RID p_mesh, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides = NULL, RID p_skeleton = RID());
+ virtual void add_multimesh(RID p_multimesh, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides = NULL);
+ virtual void add_poly(RID p_poly, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides = NULL);
+ virtual void add_beam(RID p_beam, const Transform *p_world, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides = NULL);
+ virtual void add_particles(RID p_particle_instance, const RID *p_light_instances, int p_light_count, const ParamOverrideMap *p_material_overrides = NULL);
virtual void end_scene();
virtual void end_shadow_map();
@@ -846,40 +832,40 @@ public:
virtual void canvas_begin();
virtual void canvas_set_transparency(float p_transparency);
- virtual void canvas_set_rect(const Rect2& p_rect, bool p_clip);
- virtual void canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width);
- virtual void canvas_draw_rect(const Rect2& p_rect, bool p_region, const Rect2& p_source,bool p_tile,RID p_texture,const Color& p_modulate);
- virtual void canvas_draw_style_box(const Rect2& p_rect, RID p_texture,const float *p_margins, bool p_draw_center=true);
- virtual void canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture);
+ virtual void canvas_set_rect(const Rect2 &p_rect, bool p_clip);
+ virtual void canvas_draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width);
+ virtual void canvas_draw_rect(const Rect2 &p_rect, bool p_region, const Rect2 &p_source, bool p_tile, RID p_texture, const Color &p_modulate);
+ virtual void canvas_draw_style_box(const Rect2 &p_rect, RID p_texture, const float *p_margins, bool p_draw_center = true);
+ virtual void canvas_draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture);
/* FX */
virtual RID fx_create();
- virtual void fx_get_effects(RID p_fx,List<String> *p_effects) const;
- virtual void fx_set_active(RID p_fx,const String& p_effect, bool p_active);
- virtual bool fx_is_active(RID p_fx,const String& p_effect) const;
- virtual void fx_get_effect_params(RID p_fx,const String& p_effect,List<PropertyInfo> *p_params) const;
- virtual Variant fx_get_effect_param(RID p_fx,const String& p_effect,const String& p_param) const;
- virtual void fx_set_effect_param(RID p_fx,const String& p_effect, const String& p_param, const Variant& p_pvalue);
+ virtual void fx_get_effects(RID p_fx, List<String> *p_effects) const;
+ virtual void fx_set_active(RID p_fx, const String &p_effect, bool p_active);
+ virtual bool fx_is_active(RID p_fx, const String &p_effect) const;
+ virtual void fx_get_effect_params(RID p_fx, const String &p_effect, List<PropertyInfo> *p_params) const;
+ virtual Variant fx_get_effect_param(RID p_fx, const String &p_effect, const String &p_param) const;
+ virtual void fx_set_effect_param(RID p_fx, const String &p_effect, const String &p_param, const Variant &p_pvalue);
/*MISC*/
- virtual bool is_texture(const RID& p_rid) const;
- virtual bool is_material(const RID& p_rid) const;
- virtual bool is_mesh(const RID& p_rid) const;
- virtual bool is_multimesh(const RID& p_rid) const;
- virtual bool is_poly(const RID& p_rid) const;
+ virtual bool is_texture(const RID &p_rid) const;
+ virtual bool is_material(const RID &p_rid) const;
+ virtual bool is_mesh(const RID &p_rid) const;
+ virtual bool is_multimesh(const RID &p_rid) const;
+ virtual bool is_poly(const RID &p_rid) const;
virtual bool is_particles(const RID &p_beam) const;
virtual bool is_beam(const RID &p_beam) const;
- virtual bool is_light(const RID& p_rid) const;
- virtual bool is_light_instance(const RID& p_rid) const;
- virtual bool is_particles_instance(const RID& p_rid) const;
- virtual bool is_skeleton(const RID& p_rid) const;
- virtual bool is_fx(const RID& p_rid) const;
- virtual bool is_shader(const RID& p_rid) const;
+ virtual bool is_light(const RID &p_rid) const;
+ virtual bool is_light_instance(const RID &p_rid) const;
+ virtual bool is_particles_instance(const RID &p_rid) const;
+ virtual bool is_skeleton(const RID &p_rid) const;
+ virtual bool is_fx(const RID &p_rid) const;
+ virtual bool is_shader(const RID &p_rid) const;
- virtual void free(const RID& p_rid) const;
+ virtual void free(const RID &p_rid) const;
virtual void init();
virtual void finish();
diff --git a/platform/iphone/sem_iphone.cpp b/platform/iphone/sem_iphone.cpp
index d8913feb5f..e74c696607 100644
--- a/platform/iphone/sem_iphone.cpp
+++ b/platform/iphone/sem_iphone.cpp
@@ -28,16 +28,15 @@
/*************************************************************************/
#include "sem_iphone.h"
-#include <unistd.h>
#include <fcntl.h>
+#include <unistd.h>
-void cgsem_init(cgsem_t*);
-void cgsem_post(cgsem_t*);
-void cgsem_wait(cgsem_t*);
-void cgsem_destroy(cgsem_t*);
+void cgsem_init(cgsem_t *);
+void cgsem_post(cgsem_t *);
+void cgsem_wait(cgsem_t *);
+void cgsem_destroy(cgsem_t *);
-void cgsem_init(cgsem_t *cgsem)
-{
+void cgsem_init(cgsem_t *cgsem) {
int flags, fd, i;
pipe(cgsem->pipefd);
@@ -52,31 +51,26 @@ void cgsem_init(cgsem_t *cgsem)
}
}
-void cgsem_post(cgsem_t *cgsem)
-{
+void cgsem_post(cgsem_t *cgsem) {
const char buf = 1;
write(cgsem->pipefd[1], &buf, 1);
}
-void cgsem_wait(cgsem_t *cgsem)
-{
+void cgsem_wait(cgsem_t *cgsem) {
char buf;
read(cgsem->pipefd[0], &buf, 1);
}
-void cgsem_destroy(cgsem_t *cgsem)
-{
+void cgsem_destroy(cgsem_t *cgsem) {
close(cgsem->pipefd[1]);
close(cgsem->pipefd[0]);
}
-
#include "os/memory.h"
#include <errno.h>
-
Error SemaphoreIphone::wait() {
cgsem_wait(&sem);
@@ -94,15 +88,14 @@ int SemaphoreIphone::get() const {
return 0;
}
-
Semaphore *SemaphoreIphone::create_semaphore_iphone() {
- return memnew( SemaphoreIphone );
+ return memnew(SemaphoreIphone);
}
void SemaphoreIphone::make_default() {
- create_func=create_semaphore_iphone;
+ create_func = create_semaphore_iphone;
}
SemaphoreIphone::SemaphoreIphone() {
@@ -110,11 +103,7 @@ SemaphoreIphone::SemaphoreIphone() {
cgsem_init(&sem);
}
-
SemaphoreIphone::~SemaphoreIphone() {
cgsem_destroy(&sem);
}
-
-
-
diff --git a/platform/iphone/sem_iphone.h b/platform/iphone/sem_iphone.h
index e00dd8f3dd..8a87ab47ca 100644
--- a/platform/iphone/sem_iphone.h
+++ b/platform/iphone/sem_iphone.h
@@ -44,7 +44,6 @@ class SemaphoreIphone : public Semaphore {
static Semaphore *create_semaphore_iphone();
public:
-
virtual Error wait();
virtual Error post();
virtual int get() const;
@@ -53,8 +52,6 @@ public:
SemaphoreIphone();
~SemaphoreIphone();
-
};
-
#endif
diff --git a/platform/iphone/view_controller.h b/platform/iphone/view_controller.h
index f919c06af2..ca05818040 100644
--- a/platform/iphone/view_controller.h
+++ b/platform/iphone/view_controller.h
@@ -26,11 +26,10 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
+#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <GKGameCenterControllerDelegate> {
-
};
- (BOOL)shouldAutorotateToInterfaceOrientation:
diff --git a/platform/javascript/audio_driver_javascript.cpp b/platform/javascript/audio_driver_javascript.cpp
index bff01d7c37..80bc7047ae 100644
--- a/platform/javascript/audio_driver_javascript.cpp
+++ b/platform/javascript/audio_driver_javascript.cpp
@@ -37,21 +37,17 @@
//AudioDriverJavaScript* AudioDriverJavaScript::s_ad=NULL;
-const char* AudioDriverJavaScript::get_name() const {
+const char *AudioDriverJavaScript::get_name() const {
return "JavaScript";
}
-Error AudioDriverJavaScript::init(){
+Error AudioDriverJavaScript::init() {
return OK;
-
}
-void AudioDriverJavaScript::start(){
-
-
-
+void AudioDriverJavaScript::start() {
}
int AudioDriverJavaScript::get_mix_rate() const {
@@ -59,18 +55,17 @@ int AudioDriverJavaScript::get_mix_rate() const {
return 44100;
}
-AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const{
+AudioDriver::SpeakerMode AudioDriverJavaScript::get_speaker_mode() const {
return SPEAKER_MODE_STEREO;
}
-void AudioDriverJavaScript::lock(){
+void AudioDriverJavaScript::lock() {
/*
if (active && mutex)
mutex->lock();
*/
-
}
void AudioDriverJavaScript::unlock() {
@@ -79,16 +74,10 @@ void AudioDriverJavaScript::unlock() {
if (active && mutex)
mutex->unlock();
*/
-
}
-void AudioDriverJavaScript::finish(){
-
+void AudioDriverJavaScript::finish() {
}
-AudioDriverJavaScript::AudioDriverJavaScript()
-{
+AudioDriverJavaScript::AudioDriverJavaScript() {
}
-
-
-
diff --git a/platform/javascript/audio_driver_javascript.h b/platform/javascript/audio_driver_javascript.h
index 4c2064663a..ca5dba7e5c 100644
--- a/platform/javascript/audio_driver_javascript.h
+++ b/platform/javascript/audio_driver_javascript.h
@@ -35,20 +35,17 @@
class AudioDriverJavaScript : public AudioDriver {
public:
-
- virtual const char* get_name() const;
+ virtual const char *get_name() const;
virtual Error init();
virtual void start();
- virtual int get_mix_rate() const ;
+ virtual int get_mix_rate() const;
virtual SpeakerMode get_speaker_mode() const;
virtual void lock();
virtual void unlock();
virtual void finish();
-
AudioDriverJavaScript();
};
-
#endif
diff --git a/platform/javascript/audio_server_javascript.cpp b/platform/javascript/audio_server_javascript.cpp
index bb238ede0c..7dfd562402 100644
--- a/platform/javascript/audio_server_javascript.cpp
+++ b/platform/javascript/audio_server_javascript.cpp
@@ -767,7 +767,7 @@ void AudioServerJavascript::driver_process_chunk(int p_frames) {
int32_t stream_vol_scale=(stream_volume*stream_volume_scale*E->get()->volume_scale)*(1<<STREAM_SCALE_BITS);
-#define STRSCALE(m_val) ((((m_val>>STREAM_SCALE_BITS)*stream_vol_scale)>>8)/8388608.0)
+#define STRSCALE(m_val) ((((m_val >> STREAM_SCALE_BITS) * stream_vol_scale) >> 8) / 8388608.0)
switch(channels) {
case 1: {
diff --git a/platform/javascript/dom_keys.h b/platform/javascript/dom_keys.h
index 5ef212ce4a..53a2705577 100644
--- a/platform/javascript/dom_keys.h
+++ b/platform/javascript/dom_keys.h
@@ -236,7 +236,7 @@ int dom2godot_scancode(int dom_keycode) {
return KEY_F1 + (dom_keycode - DOM_VK_F1);
}
- switch(dom_keycode) {
+ switch (dom_keycode) {
//case DOM_VK_CANCEL: return KEY_UNKNOWN;
case DOM_VK_HELP: return KEY_HELP;
case DOM_VK_BACK_SPACE: return KEY_BACKSPACE;
@@ -258,7 +258,8 @@ int dom2godot_scancode(int dom_keycode) {
return KEY_ALT;
case DOM_VK_PAUSE: return KEY_PAUSE;
- case DOM_VK_CAPS_LOCK: return KEY_CAPSLOCK;
+ case DOM_VK_CAPS_LOCK:
+ return KEY_CAPSLOCK;
/*
case DOM_VK_KANA: return KEY_UNKNOWN;
@@ -270,7 +271,8 @@ int dom2godot_scancode(int dom_keycode) {
case DOM_VK_KANJI: return KEY_UNKNOWN;
*/
- case DOM_VK_ESCAPE: return KEY_ESCAPE;
+ case DOM_VK_ESCAPE:
+ return KEY_ESCAPE;
/*
case DOM_VK_CONVERT: return KEY_UNKNOWN;
case DOM_VK_NONCONVERT: return KEY_UNKNOWN;
@@ -286,7 +288,8 @@ int dom2godot_scancode(int dom_keycode) {
case DOM_VK_LEFT: return KEY_LEFT;
case DOM_VK_UP: return KEY_UP;
case DOM_VK_RIGHT: return KEY_RIGHT;
- case DOM_VK_DOWN: return KEY_DOWN;
+ case DOM_VK_DOWN:
+ return KEY_DOWN;
//case DOM_VK_SELECT: return KEY_UNKNOWN;
@@ -303,15 +306,18 @@ int dom2godot_scancode(int dom_keycode) {
return KEY_META;
case DOM_VK_CONTEXT_MENU: return KEY_MENU;
- case DOM_VK_SLEEP: return KEY_STANDBY;
+ case DOM_VK_SLEEP:
+ return KEY_STANDBY;
// these are numpad keys according to MDN
case DOM_VK_MULTIPLY: return KEY_KP_MULTIPLY;
case DOM_VK_ADD: return KEY_KP_ADD;
- case DOM_VK_SEPARATOR: return KEY_KP_PERIOD; // good enough?
+ case DOM_VK_SEPARATOR:
+ return KEY_KP_PERIOD; // good enough?
case DOM_VK_SUBTRACT: return KEY_KP_SUBTRACT;
case DOM_VK_DECIMAL: return KEY_KP_PERIOD;
- case DOM_VK_DIVIDE: return KEY_KP_DIVIDE;
+ case DOM_VK_DIVIDE:
+ return KEY_KP_DIVIDE;
/*
case DOM_VK_F17: return KEY_UNKNOWN;
@@ -325,7 +331,8 @@ int dom2godot_scancode(int dom_keycode) {
*/
case DOM_VK_NUM_LOCK: return KEY_NUMLOCK;
- case DOM_VK_SCROLL_LOCK: return KEY_SCROLLLOCK;
+ case DOM_VK_SCROLL_LOCK:
+ return KEY_SCROLLLOCK;
/*
case DOM_VK_WIN_OEM_FJ_JISHO: return KEY_UNKNOWN;
@@ -364,7 +371,8 @@ int dom2godot_scancode(int dom_keycode) {
case DOM_VK_OPEN_BRACKET: return KEY_BRACKETLEFT;
case DOM_VK_BACK_SLASH: return KEY_BACKSLASH;
case DOM_VK_CLOSE_BRACKET: return KEY_BRACKETRIGHT;
- case DOM_VK_QUOTE: return KEY_APOSTROPHE;
+ case DOM_VK_QUOTE:
+ return KEY_APOSTROPHE;
// rest is OEM/unusual
diff --git a/platform/javascript/export/export.cpp b/platform/javascript/export/export.cpp
index b9ef63fe2f..4fdb6f39c8 100644
--- a/platform/javascript/export/export.cpp
+++ b/platform/javascript/export/export.cpp
@@ -26,19 +26,18 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "version.h"
#include "export.h"
-#include "editor/editor_settings.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
-#include "io/zip_io.h"
-#include "io/marshalls.h"
+#include "editor/editor_settings.h"
#include "global_config.h"
+#include "io/marshalls.h"
+#include "io/zip_io.h"
#include "os/file_access.h"
#include "os/os.h"
#include "platform/javascript/logo.h"
#include "string.h"
-
+#include "version.h"
#if 0
class EditorExportPlatformJavaScript : public EditorExportPlatform {
@@ -420,11 +419,6 @@ EditorExportPlatformJavaScript::~EditorExportPlatformJavaScript() {
#endif
void register_javascript_exporter() {
-
//Ref<EditorExportPlatformJavaScript> exporter = Ref<EditorExportPlatformJavaScript>( memnew(EditorExportPlatformJavaScript) );
//EditorImportExport::get_singleton()->add_export_platform(exporter);
-
-
}
-
-
diff --git a/platform/javascript/javascript_eval.cpp b/platform/javascript/javascript_eval.cpp
index d84c8bf040..897c2276bb 100644
--- a/platform/javascript/javascript_eval.cpp
+++ b/platform/javascript/javascript_eval.cpp
@@ -31,16 +31,20 @@
#include "javascript_eval.h"
#include "emscripten.h"
-JavaScript *JavaScript::singleton=NULL;
+JavaScript *JavaScript::singleton = NULL;
JavaScript *JavaScript::get_singleton() {
return singleton;
}
-Variant JavaScript::eval(const String& p_code, bool p_use_global_exec_context) {
+Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
- union { int i; double d; char* s; } js_data[4];
+ union {
+ int i;
+ double d;
+ char *s;
+ } js_data[4];
/* clang-format off */
Variant::Type return_type = static_cast<Variant::Type>(EM_ASM_INT({
@@ -127,21 +131,20 @@ Variant JavaScript::eval(const String& p_code, bool p_use_global_exec_context) {
}, js_data, sizeof *js_data, p_code.utf8().get_data(), p_use_global_exec_context));
/* clang-format on */
- switch(return_type) {
+ switch (return_type) {
case Variant::BOOL:
return !!js_data->i;
case Variant::INT:
return js_data->i;
case Variant::REAL:
return js_data->d;
- case Variant::STRING:
- {
- String str = String::utf8(js_data->s);
- /* clang-format off */
+ case Variant::STRING: {
+ String str = String::utf8(js_data->s);
+ /* clang-format off */
EM_ASM_({ _free($0); }, js_data->s);
- /* clang-format on */
- return str;
- }
+ /* clang-format on */
+ return str;
+ }
case Variant::VECTOR2:
return Vector2(js_data[0].d, js_data[1].d);
case Variant::VECTOR3:
@@ -149,7 +152,7 @@ Variant JavaScript::eval(const String& p_code, bool p_use_global_exec_context) {
case Variant::RECT2:
return Rect2(js_data[0].d, js_data[1].d, js_data[2].d, js_data[3].d);
case Variant::COLOR:
- return Color(js_data[0].d/255., js_data[1].d/255., js_data[2].d/255., js_data[3].d);
+ return Color(js_data[0].d / 255., js_data[1].d / 255., js_data[2].d / 255., js_data[3].d);
}
return Variant();
}
@@ -166,7 +169,6 @@ JavaScript::JavaScript() {
}
JavaScript::~JavaScript() {
-
}
#endif // JAVASCRIPT_EVAL_ENABLED
diff --git a/platform/javascript/javascript_eval.h b/platform/javascript/javascript_eval.h
index 679224d519..0050b855d8 100644
--- a/platform/javascript/javascript_eval.h
+++ b/platform/javascript/javascript_eval.h
@@ -35,16 +35,15 @@
class JavaScript : public Object {
private:
- GDCLASS( JavaScript, Object );
+ GDCLASS(JavaScript, Object);
static JavaScript *singleton;
-
protected:
static void _bind_methods();
public:
- Variant eval(const String& p_code, bool p_use_global_exec_context = false);
+ Variant eval(const String &p_code, bool p_use_global_exec_context = false);
static JavaScript *get_singleton();
JavaScript();
diff --git a/platform/javascript/javascript_main.cpp b/platform/javascript/javascript_main.cpp
index 076f93f0df..00e531baa1 100644
--- a/platform/javascript/javascript_main.cpp
+++ b/platform/javascript/javascript_main.cpp
@@ -26,92 +26,88 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include <GL/glut.h>
-#include "os_javascript.h"
-#include "main/main.h"
-#include "io/resource_loader.h"
#include "emscripten.h"
+#include "io/resource_loader.h"
+#include "main/main.h"
+#include "os_javascript.h"
+#include <GL/glut.h>
#include <string.h>
-OS_JavaScript *os=NULL;
+OS_JavaScript *os = NULL;
-static void _gfx_init(void *ud,bool gl2,int w, int h,bool fs) {
+static void _gfx_init(void *ud, bool gl2, int w, int h, bool fs) {
glutInitWindowSize(w, h);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("godot");
-
}
-static uint32_t _mouse_button_mask=0;
+static uint32_t _mouse_button_mask = 0;
static void _glut_mouse_button(int button, int state, int x, int y) {
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- switch(button) {
- case GLUT_LEFT_BUTTON: ev.mouse_button.button_index=BUTTON_LEFT; break;
- case GLUT_MIDDLE_BUTTON: ev.mouse_button.button_index=BUTTON_MIDDLE; break;
- case GLUT_RIGHT_BUTTON: ev.mouse_button.button_index=BUTTON_RIGHT; break;
- case 3: ev.mouse_button.button_index=BUTTON_WHEEL_UP; break;
- case 4: ev.mouse_button.button_index=BUTTON_WHEEL_DOWN; break;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ switch (button) {
+ case GLUT_LEFT_BUTTON: ev.mouse_button.button_index = BUTTON_LEFT; break;
+ case GLUT_MIDDLE_BUTTON: ev.mouse_button.button_index = BUTTON_MIDDLE; break;
+ case GLUT_RIGHT_BUTTON: ev.mouse_button.button_index = BUTTON_RIGHT; break;
+ case 3: ev.mouse_button.button_index = BUTTON_WHEEL_UP; break;
+ case 4: ev.mouse_button.button_index = BUTTON_WHEEL_DOWN; break;
}
+ ev.mouse_button.pressed = state == GLUT_DOWN;
+ ev.mouse_button.x = x;
+ ev.mouse_button.y = y;
+ ev.mouse_button.global_x = x;
+ ev.mouse_button.global_y = y;
- ev.mouse_button.pressed=state==GLUT_DOWN;
- ev.mouse_button.x=x;
- ev.mouse_button.y=y;
- ev.mouse_button.global_x=x;
- ev.mouse_button.global_y=y;
-
- if (ev.mouse_button.button_index<4) {
+ if (ev.mouse_button.button_index < 4) {
if (ev.mouse_button.pressed) {
- _mouse_button_mask |= 1 << (ev.mouse_button.button_index-1);
+ _mouse_button_mask |= 1 << (ev.mouse_button.button_index - 1);
} else {
- _mouse_button_mask &= ~(1 << (ev.mouse_button.button_index-1));
+ _mouse_button_mask &= ~(1 << (ev.mouse_button.button_index - 1));
}
}
- ev.mouse_button.button_mask=_mouse_button_mask;
+ ev.mouse_button.button_mask = _mouse_button_mask;
uint32_t m = glutGetModifiers();
- ev.mouse_button.mod.alt=(m&GLUT_ACTIVE_ALT)!=0;
- ev.mouse_button.mod.shift=(m&GLUT_ACTIVE_SHIFT)!=0;
- ev.mouse_button.mod.control=(m&GLUT_ACTIVE_CTRL)!=0;
+ ev.mouse_button.mod.alt = (m & GLUT_ACTIVE_ALT) != 0;
+ ev.mouse_button.mod.shift = (m & GLUT_ACTIVE_SHIFT) != 0;
+ ev.mouse_button.mod.control = (m & GLUT_ACTIVE_CTRL) != 0;
os->push_input(ev);
- if (ev.mouse_button.button_index==BUTTON_WHEEL_UP || ev.mouse_button.button_index==BUTTON_WHEEL_DOWN) {
+ if (ev.mouse_button.button_index == BUTTON_WHEEL_UP || ev.mouse_button.button_index == BUTTON_WHEEL_DOWN) {
// GLUT doesn't send release events for mouse wheel, so send manually
- ev.mouse_button.pressed=false;
+ ev.mouse_button.pressed = false;
os->push_input(ev);
}
}
-
-static int _glut_prev_x=0;
-static int _glut_prev_y=0;
+static int _glut_prev_x = 0;
+static int _glut_prev_y = 0;
static void _glut_mouse_motion(int x, int y) {
InputEvent ev;
- ev.type=InputEvent::MOUSE_MOTION;
- ev.mouse_motion.button_mask=_mouse_button_mask;
- ev.mouse_motion.x=x;
- ev.mouse_motion.y=y;
- ev.mouse_motion.global_x=x;
- ev.mouse_motion.global_y=y;
- ev.mouse_motion.relative_x=x-_glut_prev_x;
- ev.mouse_motion.relative_y=y-_glut_prev_y;
- _glut_prev_x=x;
- _glut_prev_y=y;
+ ev.type = InputEvent::MOUSE_MOTION;
+ ev.mouse_motion.button_mask = _mouse_button_mask;
+ ev.mouse_motion.x = x;
+ ev.mouse_motion.y = y;
+ ev.mouse_motion.global_x = x;
+ ev.mouse_motion.global_y = y;
+ ev.mouse_motion.relative_x = x - _glut_prev_x;
+ ev.mouse_motion.relative_y = y - _glut_prev_y;
+ _glut_prev_x = x;
+ _glut_prev_y = y;
uint32_t m = glutGetModifiers();
- ev.mouse_motion.mod.alt=(m&GLUT_ACTIVE_ALT)!=0;
- ev.mouse_motion.mod.shift=(m&GLUT_ACTIVE_SHIFT)!=0;
- ev.mouse_motion.mod.control=(m&GLUT_ACTIVE_CTRL)!=0;
+ ev.mouse_motion.mod.alt = (m & GLUT_ACTIVE_ALT) != 0;
+ ev.mouse_motion.mod.shift = (m & GLUT_ACTIVE_SHIFT) != 0;
+ ev.mouse_motion.mod.control = (m & GLUT_ACTIVE_CTRL) != 0;
os->push_input(ev);
-
}
static void _gfx_idle() {
@@ -119,47 +115,43 @@ static void _gfx_idle() {
glutPostRedisplay();
}
-int start_step=0;
+int start_step = 0;
static void _godot_draw(void) {
- if (start_step==1) {
- start_step=2;
+ if (start_step == 1) {
+ start_step = 2;
Main::start();
- os->main_loop_begin();
+ os->main_loop_begin();
}
- if (start_step==2) {
+ if (start_step == 2) {
os->main_loop_iterate();
}
glutSwapBuffers();
}
-
-
extern "C" {
void main_after_fs_sync() {
- start_step=1;
+ start_step = 1;
}
-
}
int main(int argc, char *argv[]) {
-
/* Initialize the window */
printf("let it go dude!\n");
glutInit(&argc, argv);
- os = new OS_JavaScript(_gfx_init,NULL,NULL);
+ os = new OS_JavaScript(_gfx_init, NULL, NULL);
#if 0
char *args[]={"-test","gui","-v",NULL};
Error err = Main::setup("apk",3,args);
#else
- char *args[]={"-main_pack","data.pck",NULL}; //pass location of main pack manually, because it wont get an executable name
- Error err = Main::setup("",2,args);
+ char *args[] = { "-main_pack", "data.pck", NULL }; //pass location of main pack manually, because it wont get an executable name
+ Error err = Main::setup("", 2, args);
#endif
ResourceLoader::set_abort_on_missing_resources(false); //ease up compatibility
@@ -168,13 +160,11 @@ int main(int argc, char *argv[]) {
glutMotionFunc(_glut_mouse_motion);
glutPassiveMotionFunc(_glut_mouse_motion);
-
-
- /* Set up glut callback functions */
- glutIdleFunc (_gfx_idle);
-// glutReshapeFunc(gears_reshape);
+ /* Set up glut callback functions */
+ glutIdleFunc(_gfx_idle);
+ // glutReshapeFunc(gears_reshape);
glutDisplayFunc(_godot_draw);
- //glutSpecialFunc(gears_special);
+ //glutSpecialFunc(gears_special);
//mount persistent file system
/* clang-format off */
@@ -200,12 +190,9 @@ int main(int argc, char *argv[]) {
glutMainLoop();
-
-
return 0;
}
-
/*
*
*09] <azakai|2__> reduz: yes, define TOTAL_MEMORY on Module. for example var Module = { TOTAL_MEMORY: 12345.. }; before the main
diff --git a/platform/javascript/os_javascript.cpp b/platform/javascript/os_javascript.cpp
index d570d64acf..83072c30aa 100644
--- a/platform/javascript/os_javascript.cpp
+++ b/platform/javascript/os_javascript.cpp
@@ -28,24 +28,24 @@
/*************************************************************************/
#include "os_javascript.h"
-#include "drivers/gles3/rasterizer_gles3.h"
+#include "core/global_config.h"
#include "core/io/file_access_buffered_fa.h"
-#include "drivers/unix/file_access_unix.h"
+#include "dom_keys.h"
+#include "drivers/gles3/rasterizer_gles3.h"
#include "drivers/unix/dir_access_unix.h"
-#include "servers/visual/visual_server_raster.h"
+#include "drivers/unix/file_access_unix.h"
#include "main/main.h"
-#include "core/global_config.h"
-#include "dom_keys.h"
+#include "servers/visual/visual_server_raster.h"
-#include <stdlib.h>
#include <emscripten.h>
+#include <stdlib.h>
int OS_JavaScript::get_video_driver_count() const {
return 1;
}
-const char * OS_JavaScript::get_video_driver_name(int p_driver) const {
+const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
return "GLES3";
}
@@ -60,7 +60,7 @@ int OS_JavaScript::get_audio_driver_count() const {
return 1;
}
-const char * OS_JavaScript::get_audio_driver_name(int p_driver) const {
+const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
return "JavaScript";
}
@@ -69,20 +69,19 @@ void OS_JavaScript::initialize_core() {
OS_Unix::initialize_core();
FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
-
}
-void OS_JavaScript::set_opengl_extensions(const char* p_gl_extensions) {
+void OS_JavaScript::set_opengl_extensions(const char *p_gl_extensions) {
ERR_FAIL_COND(!p_gl_extensions);
- gl_extensions=p_gl_extensions;
+ gl_extensions = p_gl_extensions;
}
static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) {
- ERR_FAIL_COND_V(event_type!=EMSCRIPTEN_EVENT_RESIZE, false);
+ ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false);
- OS_JavaScript* os = static_cast<OS_JavaScript*>(user_data);
+ OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
// the order in which _browser_resize_callback and
// _fullscreen_change_callback are called is browser-dependent,
@@ -102,13 +101,13 @@ static Size2 _windowed_size;
static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) {
- ERR_FAIL_COND_V(event_type!=EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false);
+ ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false);
- OS_JavaScript* os = static_cast<OS_JavaScript*>(user_data);
+ OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
String id = String::utf8(event->id);
// empty id is canvas
- if (id.empty() || id=="canvas") {
+ if (id.empty() || id == "canvas") {
OS::VideoMode vm = os->get_video_mode();
// this event property is the only reliable information on
@@ -120,8 +119,7 @@ static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFulls
vm.height = event->screenHeight;
os->set_video_mode(vm);
emscripten_set_canvas_size(vm.width, vm.height);
- }
- else {
+ } else {
os->set_video_mode(vm);
if (!os->is_window_maximized()) {
os->set_window_size(_windowed_size);
@@ -144,12 +142,12 @@ static InputEvent _setup_key_event(const EmscriptenKeyboardEvent *emscripten_eve
String unicode = String::utf8(emscripten_event->key);
// check if empty or multi-character (e.g. `CapsLock`)
- if (unicode.length()!=1) {
+ if (unicode.length() != 1) {
// might be empty as well, but better than nonsense
unicode = String::utf8(emscripten_event->charValue);
}
- if (unicode.length()==1) {
- ev.key.unicode=unicode[0];
+ if (unicode.length() == 1) {
+ ev.key.unicode = unicode[0];
}
return ev;
@@ -159,59 +157,58 @@ static InputEvent deferred_key_event;
static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
- ERR_FAIL_COND_V(event_type!=EMSCRIPTEN_EVENT_KEYDOWN, false);
+ ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false);
InputEvent ev = _setup_key_event(key_event);
ev.key.pressed = true;
- if (ev.key.unicode==0 && keycode_has_unicode(ev.key.scancode)) {
+ if (ev.key.unicode == 0 && keycode_has_unicode(ev.key.scancode)) {
// defer to keypress event for legacy unicode retrieval
deferred_key_event = ev;
return false; // do not suppress keypress event
}
- static_cast<OS_JavaScript*>(user_data)->push_input(ev);
+ static_cast<OS_JavaScript *>(user_data)->push_input(ev);
return true;
}
static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
- ERR_FAIL_COND_V(event_type!=EMSCRIPTEN_EVENT_KEYPRESS, false);
+ ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false);
deferred_key_event.key.unicode = key_event->charCode;
- static_cast<OS_JavaScript*>(user_data)->push_input(deferred_key_event);
+ static_cast<OS_JavaScript *>(user_data)->push_input(deferred_key_event);
return true;
}
static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
- ERR_FAIL_COND_V(event_type!=EMSCRIPTEN_EVENT_KEYUP, false);
+ ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false);
InputEvent ev = _setup_key_event(key_event);
ev.key.pressed = false;
- static_cast<OS_JavaScript*>(user_data)->push_input(ev);
- return ev.key.scancode!=KEY_UNKNOWN && ev.key.scancode!=0;
-
+ static_cast<OS_JavaScript *>(user_data)->push_input(ev);
+ return ev.key.scancode != KEY_UNKNOWN && ev.key.scancode != 0;
}
static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) {
- OS_JavaScript *os = (OS_JavaScript*) OS::get_singleton();
+ OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton();
if (os) {
return os->joy_connection_changed(p_type, p_event);
}
return false;
}
-void OS_JavaScript::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
print_line("Init OS");
if (gfx_init_func)
- gfx_init_func(gfx_init_ud,use_gl2,p_desired.width,p_desired.height,p_desired.fullscreen);
+ gfx_init_func(gfx_init_ud, use_gl2, p_desired.width, p_desired.height, p_desired.fullscreen);
// nothing to do here, can't fulfil fullscreen request due to
// browser security, window size is already set from HTML
- video_mode=p_desired;
- video_mode.fullscreen=false;
- _windowed_size=get_window_size();
+ video_mode = p_desired;
+ video_mode.fullscreen = false;
+ _windowed_size = get_window_size();
// find locale, emscripten only sets "C"
char locale_ptr[16];
@@ -248,24 +245,29 @@ void OS_JavaScript::initialize(const VideoMode& p_desired,int p_video_driver,int
print_line("Init VS");
- visual_server = memnew( VisualServerRaster() );
+ visual_server = memnew(VisualServerRaster());
visual_server->cursor_set_visible(false, 0);
print_line("Init Physicsserver");
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
- physics_2d_server = memnew( Physics2DServerSW );
+ physics_2d_server = memnew(Physics2DServerSW);
physics_2d_server->init();
- input = memnew( InputDefault );
-
- power_manager = memnew( PowerJavascript );
+ input = memnew(InputDefault);
+
+ power_manager = memnew(PowerJavascript);
-#define EM_CHECK(ev) if (result!=EMSCRIPTEN_RESULT_SUCCESS)\
+#define EM_CHECK(ev) \
+ if (result != EMSCRIPTEN_RESULT_SUCCESS) \
ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
-#define SET_EM_CALLBACK(ev, cb) result = emscripten_set_##ev##_callback(NULL, this, true, &cb); EM_CHECK(ev)
-#define SET_EM_CALLBACK_NODATA(ev, cb) result = emscripten_set_##ev##_callback(NULL, true, &cb); EM_CHECK(ev)
+#define SET_EM_CALLBACK(ev, cb) \
+ result = emscripten_set_##ev##_callback(NULL, this, true, &cb); \
+ EM_CHECK(ev)
+#define SET_EM_CALLBACK_NODATA(ev, cb) \
+ result = emscripten_set_##ev##_callback(NULL, true, &cb); \
+ EM_CHECK(ev)
EMSCRIPTEN_RESULT result;
SET_EM_CALLBACK(keydown, _keydown_callback)
@@ -288,16 +290,15 @@ void OS_JavaScript::initialize(const VideoMode& p_desired,int p_video_driver,int
visual_server->init();
}
-void OS_JavaScript::set_main_loop( MainLoop * p_main_loop ) {
+void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
input->set_main_loop(p_main_loop);
-
}
void OS_JavaScript::delete_main_loop() {
- memdelete( main_loop );
+ memdelete(main_loop);
}
void OS_JavaScript::finalize() {
@@ -305,7 +306,7 @@ void OS_JavaScript::finalize() {
memdelete(input);
}
-void OS_JavaScript::alert(const String& p_alert,const String& p_title) {
+void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
/* clang-format off */
EM_ASM_({
@@ -314,7 +315,6 @@ void OS_JavaScript::alert(const String& p_alert,const String& p_title) {
/* clang-format on */
}
-
void OS_JavaScript::set_mouse_show(bool p_show) {
//javascript has no mouse...
@@ -341,7 +341,7 @@ int OS_JavaScript::get_mouse_button_state() const {
return last_button_mask;
}
-void OS_JavaScript::set_window_title(const String& p_title) {
+void OS_JavaScript::set_window_title(const String &p_title) {
/* clang-format off */
EM_ASM_({
@@ -354,7 +354,7 @@ void OS_JavaScript::set_window_title(const String& p_title) {
//void set_clipboard(const String& p_text);
//String get_clipboard() const;
-void OS_JavaScript::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
+void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
video_mode = p_video_mode;
}
@@ -366,11 +366,11 @@ OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
Size2 OS_JavaScript::get_screen_size(int p_screen) const {
- ERR_FAIL_COND_V(p_screen!=0, Size2());
+ ERR_FAIL_COND_V(p_screen != 0, Size2());
EmscriptenFullscreenChangeEvent ev;
EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
- ERR_FAIL_COND_V(result!=EMSCRIPTEN_RESULT_SUCCESS, Size2());
+ ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
return Size2(ev.screenWidth, ev.screenHeight);
}
@@ -389,7 +389,7 @@ void OS_JavaScript::set_window_size(const Size2 p_size) {
Size2 OS_JavaScript::get_window_size() const {
int canvas[3];
- emscripten_get_canvas_size(canvas, canvas+1, canvas+2);
+ emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
return Size2(canvas[0], canvas[1]);
}
@@ -401,23 +401,21 @@ void OS_JavaScript::set_window_maximized(bool p_enabled) {
if (is_window_fullscreen()) {
// _browser_resize callback will set canvas size
set_window_fullscreen(false);
- }
- else {
+ } else {
/* clang-format off */
video_mode.width = EM_ASM_INT_V(return window.innerWidth);
video_mode.height = EM_ASM_INT_V(return window.innerHeight);
/* clang-format on */
emscripten_set_canvas_size(video_mode.width, video_mode.height);
}
- }
- else {
+ } else {
set_window_size(_windowed_size);
}
}
void OS_JavaScript::set_window_fullscreen(bool p_enable) {
- if (p_enable==is_window_fullscreen()) {
+ if (p_enable == is_window_fullscreen()) {
return;
}
@@ -428,10 +426,9 @@ void OS_JavaScript::set_window_fullscreen(bool p_enable) {
/* clang-format off */
EM_ASM(Module.requestFullscreen(false, false););
/* clang-format on */
- }
- else {
+ } else {
result = emscripten_exit_fullscreen();
- if (result!=EMSCRIPTEN_RESULT_SUCCESS) {
+ if (result != EMSCRIPTEN_RESULT_SUCCESS) {
ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
}
}
@@ -442,7 +439,7 @@ bool OS_JavaScript::is_window_fullscreen() const {
return video_mode.fullscreen;
}
-void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
+void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
Size2 screen = get_screen_size();
p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
@@ -478,14 +475,14 @@ bool OS_JavaScript::main_loop_iterate() {
if (!main_loop)
return false;
- if (time_to_save_sync>=0) {
+ if (time_to_save_sync >= 0) {
int64_t newtime = get_ticks_msec();
int64_t elapsed = newtime - last_sync_time;
- last_sync_time=newtime;
+ last_sync_time = newtime;
- time_to_save_sync-=elapsed;
+ time_to_save_sync -= elapsed;
- if (time_to_save_sync<0) {
+ if (time_to_save_sync < 0) {
//time to sync, for real
/* clang-format off */
EM_ASM(
@@ -495,8 +492,6 @@ bool OS_JavaScript::main_loop_iterate() {
);
/* clang-format on */
}
-
-
}
process_joypads();
return Main::iteration();
@@ -506,7 +501,6 @@ void OS_JavaScript::main_loop_end() {
if (main_loop)
main_loop->finish();
-
}
void OS_JavaScript::main_loop_focusout() {
@@ -514,186 +508,173 @@ void OS_JavaScript::main_loop_focusout() {
if (main_loop)
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
//audio_driver_javascript.set_pause(true);
-
}
-void OS_JavaScript::main_loop_focusin(){
+void OS_JavaScript::main_loop_focusin() {
if (main_loop)
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
//audio_driver_javascript.set_pause(false);
-
}
-void OS_JavaScript::push_input(const InputEvent& p_ev) {
+void OS_JavaScript::push_input(const InputEvent &p_ev) {
InputEvent ev = p_ev;
- ev.ID=last_id++;
- if (ev.type==InputEvent::MOUSE_MOTION) {
+ ev.ID = last_id++;
+ if (ev.type == InputEvent::MOUSE_MOTION) {
input->set_mouse_pos(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
- }
- else if (ev.type==InputEvent::MOUSE_BUTTON) {
+ } else if (ev.type == InputEvent::MOUSE_BUTTON) {
last_button_mask = ev.mouse_button.button_mask;
}
input->parse_input_event(p_ev);
}
-void OS_JavaScript::process_touch(int p_what,int p_pointer, const Vector<TouchPos>& p_points) {
+void OS_JavaScript::process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points) {
//print_line("ev: "+itos(p_what)+" pnt: "+itos(p_pointer)+" pointc: "+itos(p_points.size()));
- switch(p_what) {
+ switch (p_what) {
case 0: { //gesture begin
if (touch.size()) {
//end all if exist
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=false;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = false;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
input->parse_input_event(ev);
-
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
-
}
}
touch.resize(p_points.size());
- for(int i=0;i<p_points.size();i++) {
- touch[i].id=p_points[i].id;
- touch[i].pos=p_points[i].pos;
+ for (int i = 0; i < p_points.size(); i++) {
+ touch[i].id = p_points[i].id;
+ touch[i].pos = p_points[i].pos;
}
{
//send mouse
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=true;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
- last_mouse=touch[0].pos;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = true;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
+ last_mouse = touch[0].pos;
input->parse_input_event(ev);
}
-
//send touch
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=true;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = true;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
}
} break;
case 1: { //motion
-
if (p_points.size()) {
//send mouse, should look for point 0?
InputEvent ev;
- ev.type=InputEvent::MOUSE_MOTION;
- ev.ID=last_id++;
- ev.mouse_motion.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_motion.x=p_points[0].pos.x;
- ev.mouse_motion.y=p_points[0].pos.y;
- input->set_mouse_pos(Point2(ev.mouse_motion.x,ev.mouse_motion.y));
- ev.mouse_motion.speed_x=input->get_last_mouse_speed().x;
- ev.mouse_motion.speed_y=input->get_last_mouse_speed().y;
- ev.mouse_motion.relative_x=p_points[0].pos.x-last_mouse.x;
- ev.mouse_motion.relative_y=p_points[0].pos.y-last_mouse.y;
- last_mouse=p_points[0].pos;
+ ev.type = InputEvent::MOUSE_MOTION;
+ ev.ID = last_id++;
+ ev.mouse_motion.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_motion.x = p_points[0].pos.x;
+ ev.mouse_motion.y = p_points[0].pos.y;
+ input->set_mouse_pos(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
+ ev.mouse_motion.speed_x = input->get_last_mouse_speed().x;
+ ev.mouse_motion.speed_y = input->get_last_mouse_speed().y;
+ ev.mouse_motion.relative_x = p_points[0].pos.x - last_mouse.x;
+ ev.mouse_motion.relative_y = p_points[0].pos.y - last_mouse.y;
+ last_mouse = p_points[0].pos;
input->parse_input_event(ev);
}
- ERR_FAIL_COND(touch.size()!=p_points.size());
+ ERR_FAIL_COND(touch.size() != p_points.size());
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
- int idx=-1;
- for(int j=0;j<p_points.size();j++) {
+ int idx = -1;
+ for (int j = 0; j < p_points.size(); j++) {
- if (touch[i].id==p_points[j].id) {
- idx=j;
+ if (touch[i].id == p_points[j].id) {
+ idx = j;
break;
}
-
}
- ERR_CONTINUE(idx==-1);
+ ERR_CONTINUE(idx == -1);
- if (touch[i].pos==p_points[idx].pos)
+ if (touch[i].pos == p_points[idx].pos)
continue; //no move unncesearily
InputEvent ev;
- ev.type=InputEvent::SCREEN_DRAG;
- ev.ID=last_id++;
- ev.screen_drag.index=touch[i].id;
- ev.screen_drag.x=p_points[idx].pos.x;
- ev.screen_drag.y=p_points[idx].pos.y;
- ev.screen_drag.relative_x=p_points[idx].pos.x - touch[i].pos.x;
- ev.screen_drag.relative_y=p_points[idx].pos.y - touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_DRAG;
+ ev.ID = last_id++;
+ ev.screen_drag.index = touch[i].id;
+ ev.screen_drag.x = p_points[idx].pos.x;
+ ev.screen_drag.y = p_points[idx].pos.y;
+ ev.screen_drag.relative_x = p_points[idx].pos.x - touch[i].pos.x;
+ ev.screen_drag.relative_y = p_points[idx].pos.y - touch[i].pos.y;
input->parse_input_event(ev);
- touch[i].pos=p_points[idx].pos;
+ touch[i].pos = p_points[idx].pos;
}
-
} break;
case 2: { //release
-
-
if (touch.size()) {
//end all if exist
InputEvent ev;
- ev.type=InputEvent::MOUSE_BUTTON;
- ev.ID=last_id++;
- ev.mouse_button.button_index=BUTTON_LEFT;
- ev.mouse_button.button_mask=BUTTON_MASK_LEFT;
- ev.mouse_button.pressed=false;
- ev.mouse_button.x=touch[0].pos.x;
- ev.mouse_button.y=touch[0].pos.y;
- ev.mouse_button.global_x=touch[0].pos.x;
- ev.mouse_button.global_y=touch[0].pos.y;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.ID = last_id++;
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.button_mask = BUTTON_MASK_LEFT;
+ ev.mouse_button.pressed = false;
+ ev.mouse_button.x = touch[0].pos.x;
+ ev.mouse_button.y = touch[0].pos.y;
+ ev.mouse_button.global_x = touch[0].pos.x;
+ ev.mouse_button.global_y = touch[0].pos.y;
input->parse_input_event(ev);
-
- for(int i=0;i<touch.size();i++) {
+ for (int i = 0; i < touch.size(); i++) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
-
}
touch.clear();
}
@@ -701,38 +682,33 @@ void OS_JavaScript::process_touch(int p_what,int p_pointer, const Vector<TouchPo
} break;
case 3: { // add tuchi
+ ERR_FAIL_INDEX(p_pointer, p_points.size());
-
-
-
- ERR_FAIL_INDEX(p_pointer,p_points.size());
-
- TouchPos tp=p_points[p_pointer];
+ TouchPos tp = p_points[p_pointer];
touch.push_back(tp);
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=tp.id;
- ev.screen_touch.pressed=true;
- ev.screen_touch.x=tp.pos.x;
- ev.screen_touch.y=tp.pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = tp.id;
+ ev.screen_touch.pressed = true;
+ ev.screen_touch.x = tp.pos.x;
+ ev.screen_touch.y = tp.pos.y;
input->parse_input_event(ev);
} break;
case 4: {
-
- for(int i=0;i<touch.size();i++) {
- if (touch[i].id==p_pointer) {
+ for (int i = 0; i < touch.size(); i++) {
+ if (touch[i].id == p_pointer) {
InputEvent ev;
- ev.type=InputEvent::SCREEN_TOUCH;
- ev.ID=last_id++;
- ev.screen_touch.index=touch[i].id;
- ev.screen_touch.pressed=false;
- ev.screen_touch.x=touch[i].pos.x;
- ev.screen_touch.y=touch[i].pos.y;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = last_id++;
+ ev.screen_touch.index = touch[i].id;
+ ev.screen_touch.pressed = false;
+ ev.screen_touch.x = touch[i].pos.x;
+ ev.screen_touch.y = touch[i].pos.y;
input->parse_input_event(ev);
touch.remove(i);
i--;
@@ -740,12 +716,10 @@ void OS_JavaScript::process_touch(int p_what,int p_pointer, const Vector<TouchPo
}
} break;
-
}
-
}
-void OS_JavaScript::process_accelerometer(const Vector3& p_accelerometer) {
+void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
input->set_accelerometer(p_accelerometer);
}
@@ -790,12 +764,12 @@ String OS_JavaScript::get_executable_path() const {
return String();
}
-void OS_JavaScript::_close_notification_funcs(const String& p_file,int p_flags) {
+void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
- print_line("close "+p_file+" flags "+itos(p_flags));
- if (p_file.begins_with("/userfs") && p_flags&FileAccess::WRITE) {
- static_cast<OS_JavaScript*>(get_singleton())->last_sync_time=OS::get_singleton()->get_ticks_msec();
- static_cast<OS_JavaScript*>(get_singleton())->time_to_save_sync=5000; //five seconds since last save
+ print_line("close " + p_file + " flags " + itos(p_flags));
+ if (p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
+ static_cast<OS_JavaScript *>(get_singleton())->last_sync_time = OS::get_singleton()->get_ticks_msec();
+ static_cast<OS_JavaScript *>(get_singleton())->time_to_save_sync = 5000; //five seconds since last save
}
}
@@ -817,8 +791,7 @@ void OS_JavaScript::process_joypads() {
jx.min = 0;
jx.value = value;
last_id = input->joy_axis(last_id, i, j, jx);
- }
- else {
+ } else {
last_id = input->joy_button(last_id, i, j, value);
}
}
@@ -840,8 +813,7 @@ bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEv
if (String(p_event->mapping) == "standard")
guid = "Default HTML5 Gamepad";
input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
- }
- else {
+ } else {
input->joy_connection_changed(p_event->index, false, "");
}
return true;
@@ -867,22 +839,20 @@ int OS_JavaScript::get_power_percent_left() {
return power_manager->get_power_percent_left();
}
-OS_JavaScript::OS_JavaScript(GFXInitFunc p_gfx_init_func,void*p_gfx_init_ud, GetDataDirFunc p_get_data_dir_func) {
- gfx_init_func=p_gfx_init_func;
- gfx_init_ud=p_gfx_init_ud;
- last_button_mask=0;
- main_loop=NULL;
- last_id=1;
- gl_extensions=NULL;
- window_maximized=false;
+OS_JavaScript::OS_JavaScript(GFXInitFunc p_gfx_init_func, void *p_gfx_init_ud, GetDataDirFunc p_get_data_dir_func) {
+ gfx_init_func = p_gfx_init_func;
+ gfx_init_ud = p_gfx_init_ud;
+ last_button_mask = 0;
+ main_loop = NULL;
+ last_id = 1;
+ gl_extensions = NULL;
+ window_maximized = false;
- get_data_dir_func=p_get_data_dir_func;
- FileAccessUnix::close_notification_func=_close_notification_funcs;
+ get_data_dir_func = p_get_data_dir_func;
+ FileAccessUnix::close_notification_func = _close_notification_funcs;
- time_to_save_sync=-1;
+ time_to_save_sync = -1;
}
OS_JavaScript::~OS_JavaScript() {
-
-
}
diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h
index 5f6051bedb..b16918b2da 100644
--- a/platform/javascript/os_javascript.h
+++ b/platform/javascript/os_javascript.h
@@ -29,40 +29,38 @@
#ifndef OS_JAVASCRIPT_H
#define OS_JAVASCRIPT_H
-#include "os/input.h"
+#include "audio_driver_javascript.h"
+#include "audio_server_javascript.h"
#include "drivers/unix/os_unix.h"
+#include "javascript_eval.h"
+#include "main/input_default.h"
+#include "os/input.h"
#include "os/main_loop.h"
#include "power_javascript.h"
-#include "servers/physics/physics_server_sw.h"
#include "servers/audio_server.h"
+#include "servers/physics/physics_server_sw.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/visual/rasterizer.h"
-#include "audio_server_javascript.h"
-#include "audio_driver_javascript.h"
-#include "main/input_default.h"
-#include "javascript_eval.h"
#include <emscripten/html5.h>
-typedef void (*GFXInitFunc)(void *ud,bool gl2,int w, int h, bool fs);
+typedef void (*GFXInitFunc)(void *ud, bool gl2, int w, int h, bool fs);
typedef String (*GetDataDirFunc)();
class OS_JavaScript : public OS_Unix {
public:
-
struct TouchPos {
int id;
Point2 pos;
};
private:
-
Vector<TouchPos> touch;
Point2 last_mouse;
int last_button_mask;
unsigned int last_id;
GFXInitFunc gfx_init_func;
- void*gfx_init_ud;
+ void *gfx_init_ud;
bool use_gl2;
@@ -73,72 +71,69 @@ private:
PhysicsServer *physics_server;
Physics2DServer *physics_2d_server;
AudioDriverJavaScript audio_driver_javascript;
- const char* gl_extensions;
+ const char *gl_extensions;
InputDefault *input;
bool window_maximized;
VideoMode video_mode;
- MainLoop * main_loop;
+ MainLoop *main_loop;
GetDataDirFunc get_data_dir_func;
PowerJavascript *power_manager;
#ifdef JAVASCRIPT_EVAL_ENABLED
- JavaScript* javascript_eval;
+ JavaScript *javascript_eval;
#endif
- static void _close_notification_funcs(const String& p_file,int p_flags);
+ static void _close_notification_funcs(const String &p_file, int p_flags);
void process_joypads();
public:
-
// functions used by main to initialize/deintialize the OS
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
virtual void finalize();
-
typedef int64_t ProcessID;
//static OS* get_singleton();
- virtual void print_error(const char* p_function, const char* p_file, int p_line, const char *p_code, const char* p_rationale, ErrorType p_type) {
+ virtual void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
OS::print_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
}
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
-
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
//virtual void set_clipboard(const String& p_text);
//virtual String get_clipboard() const;
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
virtual void set_window_size(const Size2);
virtual Size2 get_window_size() const;
@@ -163,28 +158,27 @@ public:
virtual bool has_touchscreen_ui_hint() const;
- void set_opengl_extensions(const char* p_gl_extensions);
+ void set_opengl_extensions(const char *p_gl_extensions);
virtual Error shell_open(String p_uri);
virtual String get_data_dir() const;
String get_executable_path() const;
virtual String get_resource_dir() const;
- void process_accelerometer(const Vector3& p_accelerometer);
- void process_touch(int p_what,int p_pointer, const Vector<TouchPos>& p_points);
- void push_input(const InputEvent& p_ev);
+ void process_accelerometer(const Vector3 &p_accelerometer);
+ void process_touch(int p_what, int p_pointer, const Vector<TouchPos> &p_points);
+ void push_input(const InputEvent &p_ev);
virtual bool is_joy_known(int p_device);
virtual String get_joy_guid(int p_device) const;
bool joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event);
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
- OS_JavaScript(GFXInitFunc p_gfx_init_func,void*p_gfx_init_ud, GetDataDirFunc p_get_data_dir_func);
+ OS_JavaScript(GFXInitFunc p_gfx_init_func, void *p_gfx_init_ud, GetDataDirFunc p_get_data_dir_func);
~OS_JavaScript();
-
};
#endif
diff --git a/platform/javascript/power_javascript.cpp b/platform/javascript/power_javascript.cpp
index 9d2d0364aa..d734999917 100644
--- a/platform/javascript/power_javascript.cpp
+++ b/platform/javascript/power_javascript.cpp
@@ -27,10 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-
-#include "core/error_macros.h"
#include "power_javascript.h"
-
+#include "core/error_macros.h"
bool PowerJavascript::UpdatePowerInfo() {
// TODO Javascript implementation
@@ -40,8 +38,7 @@ bool PowerJavascript::UpdatePowerInfo() {
PowerState PowerJavascript::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to POWERSTATE_UNKNOWN");
return POWERSTATE_UNKNOWN;
}
@@ -50,8 +47,7 @@ PowerState PowerJavascript::get_power_state() {
int PowerJavascript::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
@@ -60,16 +56,14 @@ int PowerJavascript::get_power_seconds_left() {
int PowerJavascript::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
WARN_PRINT("Power management is not implemented on this platform, defaulting to -1");
return -1;
}
}
-
-PowerJavascript::PowerJavascript() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+PowerJavascript::PowerJavascript()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
PowerJavascript::~PowerJavascript() {
diff --git a/platform/javascript/power_javascript.h b/platform/javascript/power_javascript.h
index bdef2be7e1..53c702b98e 100644
--- a/platform/javascript/power_javascript.h
+++ b/platform/javascript/power_javascript.h
@@ -27,7 +27,6 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-
#ifndef PLATFORM_JAVASCRIPT_POWER_JAVASCRIPT_H_
#define PLATFORM_JAVASCRIPT_POWER_JAVASCRIPT_H_
diff --git a/platform/osx/audio_driver_osx.cpp b/platform/osx/audio_driver_osx.cpp
index 4ad3a5b8fc..7ef0669656 100644
--- a/platform/osx/audio_driver_osx.cpp
+++ b/platform/osx/audio_driver_osx.cpp
@@ -43,9 +43,9 @@ Error AudioDriverOSX::init() {
strdesc.mFramesPerPacket = 1;
strdesc.mBitsPerChannel = 16;
strdesc.mBytesPerFrame =
- strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
+ strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
strdesc.mBytesPerPacket =
- strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
+ strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
OSStatus result = noErr;
AURenderCallbackStruct callback;
@@ -57,7 +57,7 @@ Error AudioDriverOSX::init() {
zeromem(&desc, sizeof(desc));
desc.componentType = kAudioUnitType_Output;
- desc.componentSubType = 0; /* !!! FIXME: ? */
+ desc.componentSubType = 0; /* !!! FIXME: ? */
comp = AudioComponentFindNext(NULL, &desc);
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
@@ -66,16 +66,16 @@ Error AudioDriverOSX::init() {
ERR_FAIL_COND_V(comp == NULL, FAILED);
result = AudioUnitSetProperty(audio_unit,
- kAudioUnitProperty_StreamFormat,
- scope, bus, &strdesc, sizeof(strdesc));
+ kAudioUnitProperty_StreamFormat,
+ scope, bus, &strdesc, sizeof(strdesc));
ERR_FAIL_COND_V(result != noErr, FAILED);
zeromem(&callback, sizeof(AURenderCallbackStruct));
callback.inputProc = &AudioDriverOSX::output_callback;
callback.inputProcRefCon = this;
result = AudioUnitSetProperty(audio_unit,
- kAudioUnitProperty_SetRenderCallback,
- scope, bus, &callback, sizeof(callback));
+ kAudioUnitProperty_SetRenderCallback,
+ scope, bus, &callback, sizeof(callback));
ERR_FAIL_COND_V(result != noErr, FAILED);
result = AudioUnitInitialize(audio_unit);
@@ -92,14 +92,13 @@ Error AudioDriverOSX::init() {
};
OSStatus AudioDriverOSX::output_callback(void *inRefCon,
- AudioUnitRenderActionFlags * ioActionFlags,
- const AudioTimeStamp * inTimeStamp,
- UInt32 inBusNumber, UInt32 inNumberFrames,
- AudioBufferList * ioData) {
-
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList *ioData) {
AudioBuffer *abuf;
- AudioDriverOSX* ad = (AudioDriverOSX*)inRefCon;
+ AudioDriverOSX *ad = (AudioDriverOSX *)inRefCon;
bool mix = true;
@@ -109,7 +108,6 @@ OSStatus AudioDriverOSX::output_callback(void *inRefCon,
mix = ad->mutex->try_lock() == OK;
};
-
if (!mix) {
for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
abuf = &ioData->mBuffers[i];
@@ -124,7 +122,7 @@ OSStatus AudioDriverOSX::output_callback(void *inRefCon,
abuf = &ioData->mBuffers[i];
frames_left = inNumberFrames;
- int16_t* out = (int16_t*)abuf->mData;
+ int16_t *out = (int16_t *)abuf->mData;
while (frames_left) {
@@ -133,9 +131,9 @@ OSStatus AudioDriverOSX::output_callback(void *inRefCon,
ad->audio_server_process(frames, ad->samples_in);
//ad->unlock();
- for(int i = 0; i < frames * ad->channels; i++) {
+ for (int i = 0; i < frames * ad->channels; i++) {
- out[i] = ad->samples_in[i]>>16;
+ out[i] = ad->samples_in[i] >> 16;
}
frames_left -= frames;
@@ -180,10 +178,10 @@ void AudioDriverOSX::finish() {
AudioDriverOSX::AudioDriverOSX() {
- mutex=Mutex::create();//NULL;
+ mutex = Mutex::create(); //NULL;
};
-AudioDriverOSX::~AudioDriverOSX() {
+AudioDriverOSX::~AudioDriverOSX(){
};
diff --git a/platform/osx/audio_driver_osx.h b/platform/osx/audio_driver_osx.h
index 9e9bb63726..b030570a6e 100644
--- a/platform/osx/audio_driver_osx.h
+++ b/platform/osx/audio_driver_osx.h
@@ -42,19 +42,17 @@ class AudioDriverOSX : public AudioDriver {
Mutex *mutex;
int channels;
- int32_t* samples_in;
- int buffer_frames;
+ int32_t *samples_in;
+ int buffer_frames;
static OSStatus output_callback(void *inRefCon,
- AudioUnitRenderActionFlags * ioActionFlags,
- const AudioTimeStamp * inTimeStamp,
- UInt32 inBusNumber, UInt32 inNumberFrames,
- AudioBufferList * ioData);
-
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList *ioData);
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "AudioUnit";
};
diff --git a/platform/osx/context_gl_osx.cpp b/platform/osx/context_gl_osx.cpp
index d0819bbfb6..0737e3d3c6 100644
--- a/platform/osx/context_gl_osx.cpp
+++ b/platform/osx/context_gl_osx.cpp
@@ -31,58 +31,58 @@
#ifdef OSX_ENABLED
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
#include <stdio.h>
-#include <unistd.h>
#include <stdlib.h>
+#include <unistd.h>
-#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
-#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
void ContextGL_OSX::release_current() {
- aglSetCurrentContext( context );
+ aglSetCurrentContext(context);
}
void ContextGL_OSX::make_current() {
- aglSetCurrentContext( NULL );
+ aglSetCurrentContext(NULL);
}
void ContextGL_OSX::swap_buffers() {
- aglSwapBuffers( context );
+ aglSwapBuffers(context);
}
Error ContextGL_OSX::initialize() {
- if ( (Ptr) kUnresolvedCFragSymbolAddress == (Ptr) aglChoosePixelFormat )
+ if ((Ptr)kUnresolvedCFragSymbolAddress == (Ptr)aglChoosePixelFormat)
return FAILED;
GLint attributes[] = { AGL_RGBA,
- AGL_DOUBLEBUFFER,
- AGL_DEPTH_SIZE, 32,
- AGL_NO_RECOVERY,
- AGL_NONE,
- AGL_NONE };
+ AGL_DOUBLEBUFFER,
+ AGL_DEPTH_SIZE, 32,
+ AGL_NO_RECOVERY,
+ AGL_NONE,
+ AGL_NONE };
AGLPixelFormat format = NULL;
- format = aglChoosePixelFormat( NULL, 0, attributes );
+ format = aglChoosePixelFormat(NULL, 0, attributes);
- if ( !format )
+ if (!format)
return FAILED;
- context = aglCreateContext( format, 0 );
+ context = aglCreateContext(format, 0);
- if ( !context )
+ if (!context)
return FAILED;
- aglDestroyPixelFormat( format );
+ aglDestroyPixelFormat(format);
- aglSetWindowRef( context, window );
+ aglSetWindowRef(context, window);
GLint swapInterval = 1;
- aglSetInteger( context, AGL_SWAP_INTERVAL, &swapInterval );
+ aglSetInteger(context, AGL_SWAP_INTERVAL, &swapInterval);
- aglSetCurrentContext( context );
+ aglSetCurrentContext(context);
return OK;
}
@@ -92,13 +92,11 @@ ContextGL_OSX::ContextGL_OSX(WindowRef p_window) {
window = p_window;
}
-
ContextGL_OSX::~ContextGL_OSX() {
if (context)
aglDestroyContext(context);
}
-
#endif
#endif
diff --git a/platform/osx/context_gl_osx.h b/platform/osx/context_gl_osx.h
index 6a02aa23d1..66da8b1ecf 100644
--- a/platform/osx/context_gl_osx.h
+++ b/platform/osx/context_gl_osx.h
@@ -36,8 +36,8 @@
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
-#include "os/os.h"
#include "drivers/gl_context/context_gl.h"
+#include "os/os.h"
#include <AGL/agl.h>
#include <Carbon/Carbon.h>
@@ -47,7 +47,6 @@ class ContextGL_OSX : public ContextGL {
WindowRef window;
public:
-
virtual void release_current();
virtual void make_current();
virtual void swap_buffers();
@@ -56,7 +55,6 @@ public:
ContextGL_OSX(WindowRef window);
~ContextGL_OSX();
-
};
#endif
diff --git a/platform/osx/dir_access_osx.h b/platform/osx/dir_access_osx.h
index c30d380dd3..56a8e057dd 100644
--- a/platform/osx/dir_access_osx.h
+++ b/platform/osx/dir_access_osx.h
@@ -31,26 +31,21 @@
#if defined(UNIX_ENABLED) || defined(LIBC_FILEIO_ENABLED)
-#include <sys/types.h>
+#include <dirent.h>
#include <sys/stat.h>
+#include <sys/types.h>
#include <unistd.h>
-#include <dirent.h>
-#include "os/dir_access.h"
#include "drivers/unix/dir_access_unix.h"
-
+#include "os/dir_access.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class DirAccessOSX : public DirAccessUnix {
protected:
-
- virtual String fix_unicode_name(const char* p_name) const;
-
+ virtual String fix_unicode_name(const char *p_name) const;
};
-
-
#endif //UNIX ENABLED
#endif
diff --git a/platform/osx/export/export.cpp b/platform/osx/export/export.cpp
index 4af2aaca63..ba4ef0300c 100644
--- a/platform/osx/export/export.cpp
+++ b/platform/osx/export/export.cpp
@@ -26,19 +26,19 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "version.h"
#include "export.h"
-#include "editor/editor_settings.h"
#include "editor/editor_export.h"
#include "editor/editor_node.h"
-#include "io/zip_io.h"
+#include "editor/editor_settings.h"
+#include "global_config.h"
#include "io/marshalls.h"
#include "io/resource_saver.h"
-#include "global_config.h"
+#include "io/zip_io.h"
#include "os/file_access.h"
#include "os/os.h"
#include "platform/osx/logo.h"
#include "string.h"
+#include "version.h"
#if 0
class EditorExportPlatformOSX : public EditorExportPlatform {
@@ -543,7 +543,4 @@ void register_osx_exporter() {
Ref<EditorExportPlatformOSX> exporter = Ref<EditorExportPlatformOSX>( memnew(EditorExportPlatformOSX) );
EditorImportExport::get_singleton()->add_export_platform(exporter);
#endif
-
}
-
-
diff --git a/platform/osx/joypad_osx.cpp b/platform/osx/joypad_osx.cpp
index 98bcc8dc73..c2b0e1f052 100644
--- a/platform/osx/joypad_osx.cpp
+++ b/platform/osx/joypad_osx.cpp
@@ -32,7 +32,7 @@
#define GODOT_JOY_LOOP_RUN_MODE CFSTR("GodotJoypad")
-static JoypadOSX* self = NULL;
+static JoypadOSX *self = NULL;
joypad::joypad() {
device_ref = NULL;
@@ -83,7 +83,7 @@ int joypad::get_hid_element_state(rec_element *p_element) const {
if (p_element && p_element->ref) {
IOHIDValueRef valueRef;
if (IOHIDDeviceGetValue(device_ref, p_element->ref, &valueRef) == kIOReturnSuccess) {
- value = (SInt32) IOHIDValueGetIntegerValue(valueRef);
+ value = (SInt32)IOHIDValueGetIntegerValue(valueRef);
/* record min and max for auto calibration */
if (value < p_element->min) {
@@ -106,91 +106,89 @@ void joypad::add_hid_element(IOHIDElementRef p_element) {
Vector<rec_element> *list = NULL;
switch (IOHIDElementGetType(p_element)) {
- case kIOHIDElementTypeInput_Misc:
- case kIOHIDElementTypeInput_Button:
- case kIOHIDElementTypeInput_Axis: {
- switch (usagePage) {
- case kHIDPage_GenericDesktop:
- switch (usage) {
- case kHIDUsage_GD_X:
- case kHIDUsage_GD_Y:
- case kHIDUsage_GD_Z:
- case kHIDUsage_GD_Rx:
- case kHIDUsage_GD_Ry:
- case kHIDUsage_GD_Rz:
- case kHIDUsage_GD_Slider:
- case kHIDUsage_GD_Dial:
- case kHIDUsage_GD_Wheel:
- if (!has_element(cookie, &axis_elements)) {
- list = &axis_elements;
- }
- break;
-
- case kHIDUsage_GD_Hatswitch:
- if (!has_element(cookie, &hat_elements)) {
- list = &hat_elements;
- }
- break;
- case kHIDUsage_GD_DPadUp:
- case kHIDUsage_GD_DPadDown:
- case kHIDUsage_GD_DPadRight:
- case kHIDUsage_GD_DPadLeft:
- case kHIDUsage_GD_Start:
- case kHIDUsage_GD_Select:
- if (!has_element(cookie, &button_elements)) {
- list = &button_elements;
- }
- break;
+ case kIOHIDElementTypeInput_Misc:
+ case kIOHIDElementTypeInput_Button:
+ case kIOHIDElementTypeInput_Axis: {
+ switch (usagePage) {
+ case kHIDPage_GenericDesktop:
+ switch (usage) {
+ case kHIDUsage_GD_X:
+ case kHIDUsage_GD_Y:
+ case kHIDUsage_GD_Z:
+ case kHIDUsage_GD_Rx:
+ case kHIDUsage_GD_Ry:
+ case kHIDUsage_GD_Rz:
+ case kHIDUsage_GD_Slider:
+ case kHIDUsage_GD_Dial:
+ case kHIDUsage_GD_Wheel:
+ if (!has_element(cookie, &axis_elements)) {
+ list = &axis_elements;
+ }
+ break;
+
+ case kHIDUsage_GD_Hatswitch:
+ if (!has_element(cookie, &hat_elements)) {
+ list = &hat_elements;
+ }
+ break;
+ case kHIDUsage_GD_DPadUp:
+ case kHIDUsage_GD_DPadDown:
+ case kHIDUsage_GD_DPadRight:
+ case kHIDUsage_GD_DPadLeft:
+ case kHIDUsage_GD_Start:
+ case kHIDUsage_GD_Select:
+ if (!has_element(cookie, &button_elements)) {
+ list = &button_elements;
+ }
+ break;
+ }
+ break;
+
+ case kHIDPage_Simulation:
+ switch (usage) {
+ case kHIDUsage_Sim_Rudder:
+ case kHIDUsage_Sim_Throttle:
+ if (!has_element(cookie, &axis_elements)) {
+ list = &axis_elements;
+ }
+ break;
+
+ default:
+ break;
+ }
+ break;
+
+ case kHIDPage_Button:
+ case kHIDPage_Consumer:
+ if (!has_element(cookie, &button_elements)) {
+ list = &button_elements;
+ }
+ break;
+
+ default:
+ break;
}
- break;
-
- case kHIDPage_Simulation:
- switch (usage) {
- case kHIDUsage_Sim_Rudder:
- case kHIDUsage_Sim_Throttle:
- if (!has_element(cookie, &axis_elements)) {
- list = &axis_elements;
- }
- break;
-
- default:
- break;
- }
- break;
+ } break;
- case kHIDPage_Button:
- case kHIDPage_Consumer:
- if (!has_element(cookie, &button_elements)) {
- list = &button_elements;
+ case kIOHIDElementTypeCollection: {
+ CFArrayRef array = IOHIDElementGetChildren(p_element);
+ if (array) {
+ add_hid_elements(array);
}
- break;
+ } break;
default:
break;
- }
- }
- break;
-
- case kIOHIDElementTypeCollection: {
- CFArrayRef array = IOHIDElementGetChildren(p_element);
- if (array) {
- add_hid_elements(array);
- }
- }
- break;
-
- default:
- break;
}
- if (list) { /* add to list */
+ if (list) { /* add to list */
rec_element element;
element.ref = p_element;
element.usage = usage;
- element.min = (SInt32) IOHIDElementGetLogicalMin(p_element);
- element.max = (SInt32) IOHIDElementGetLogicalMax(p_element);
+ element.min = (SInt32)IOHIDElementGetLogicalMin(p_element);
+ element.max = (SInt32)IOHIDElementGetLogicalMax(p_element);
element.cookie = IOHIDElementGetCookie(p_element);
list->push_back(element);
list->sort_custom<rec_element::Comparator>();
@@ -199,21 +197,20 @@ void joypad::add_hid_element(IOHIDElementRef p_element) {
}
static void hid_element_added(const void *p_value, void *p_parameter) {
- joypad *joy = (joypad*) p_parameter;
- joy->add_hid_element((IOHIDElementRef) p_value);
+ joypad *joy = (joypad *)p_parameter;
+ joy->add_hid_element((IOHIDElementRef)p_value);
}
void joypad::add_hid_elements(CFArrayRef p_array) {
CFRange range = { 0, CFArrayGetCount(p_array) };
- CFArrayApplyFunction(p_array, range,hid_element_added,this);
+ CFArrayApplyFunction(p_array, range, hid_element_added, this);
}
static void joypad_removed_callback(void *ctx, IOReturn result, void *sender) {
- int id = (intptr_t) ctx;
+ int id = (intptr_t)ctx;
self->_device_removed(id);
}
-
static void joypad_added_callback(void *ctx, IOReturn res, void *sender, IOHIDDeviceRef ioHIDDeviceObject) {
self->_device_added(res, ioHIDDeviceObject);
}
@@ -224,7 +221,7 @@ static bool is_joypad(IOHIDDeviceRef p_device_ref) {
int usage = 0;
refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsagePageKey));
if (refCF) {
- CFNumberGetValue((CFNumberRef) refCF, kCFNumberSInt32Type, &usage_page);
+ CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage_page);
}
if (usage_page != kHIDPage_GenericDesktop) {
return false;
@@ -232,11 +229,11 @@ static bool is_joypad(IOHIDDeviceRef p_device_ref) {
refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDPrimaryUsageKey));
if (refCF) {
- CFNumberGetValue((CFNumberRef) refCF, kCFNumberSInt32Type, &usage);
+ CFNumberGetValue((CFNumberRef)refCF, kCFNumberSInt32Type, &usage);
}
if ((usage != kHIDUsage_GD_Joystick &&
- usage != kHIDUsage_GD_GamePad &&
- usage != kHIDUsage_GD_MultiAxisController)) {
+ usage != kHIDUsage_GD_GamePad &&
+ usage != kHIDUsage_GD_MultiAxisController)) {
return false;
}
return true;
@@ -255,7 +252,7 @@ void JoypadOSX::_device_added(IOReturn p_res, IOHIDDeviceRef p_device) {
if (IOHIDDeviceGetService != NULL) {
#endif
const io_service_t ioservice = IOHIDDeviceGetService(p_device);
- if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK) && new_joypad.config_force_feedback(ioservice)) {
+ if ((ioservice) && (FFIsForceFeedback(ioservice) == FF_OK) && new_joypad.config_force_feedback(ioservice)) {
new_joypad.ffservice = ioservice;
}
#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060
@@ -263,7 +260,7 @@ void JoypadOSX::_device_added(IOReturn p_res, IOHIDDeviceRef p_device) {
#endif
device_list.push_back(new_joypad);
}
- IOHIDDeviceRegisterRemovalCallback(p_device, joypad_removed_callback, (void*) (intptr_t) new_joypad.id);
+ IOHIDDeviceRegisterRemovalCallback(p_device, joypad_removed_callback, (void *)(intptr_t)new_joypad.id);
IOHIDDeviceScheduleWithRunLoop(p_device, CFRunLoopGetCurrent(), GODOT_JOY_LOOP_RUN_MODE);
}
@@ -279,17 +276,17 @@ void JoypadOSX::_device_removed(int p_id) {
static String _hex_str(uint8_t p_byte) {
- static const char* dict = "0123456789abcdef";
+ static const char *dict = "0123456789abcdef";
char ret[3];
ret[2] = 0;
- ret[0] = dict[p_byte>>4];
+ ret[0] = dict[p_byte >> 4];
ret[1] = dict[p_byte & 0xF];
return ret;
}
-bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad* p_joy) {
+bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad *p_joy) {
CFTypeRef refCF = NULL;
@@ -301,7 +298,7 @@ bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad* p_joy) {
if (!refCF) {
refCF = IOHIDDeviceGetProperty(p_device_ref, CFSTR(kIOHIDManufacturerKey));
}
- if ((!refCF) || (!CFStringGetCString((CFStringRef) refCF, c_name, sizeof (c_name), kCFStringEncodingUTF8))) {
+ if ((!refCF) || (!CFStringGetCString((CFStringRef)refCF, c_name, sizeof(c_name), kCFStringEncodingUTF8))) {
name = "Unidentified Joypad";
}
name = c_name;
@@ -322,15 +319,16 @@ bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad* p_joy) {
}
if (vendor && product_id) {
char uid[128];
- sprintf(uid, "%04x%08x%04x%08x", OSSwapHostToBigInt32(vendor),0, OSSwapHostToBigInt32(product_id), 0);
+ sprintf(uid, "%04x%08x%04x%08x", OSSwapHostToBigInt32(vendor), 0, OSSwapHostToBigInt32(product_id), 0);
input->joy_connection_changed(id, true, name, uid);
- }
- else {
+ } else {
//bluetooth device
String guid = "05000000";
for (int i = 0; i < 12; i++) {
- if (i < name.size()) guid += _hex_str(name[i]);
- else guid += "00";
+ if (i < name.size())
+ guid += _hex_str(name[i]);
+ else
+ guid += "00";
}
input->joy_connection_changed(id, true, name, guid);
}
@@ -344,7 +342,13 @@ bool JoypadOSX::configure_joypad(IOHIDDeviceRef p_device_ref, joypad* p_joy) {
return true;
}
-#define FF_ERR() { if (ret != FF_OK) { FFReleaseDevice(ff_device); return false; } }
+#define FF_ERR() \
+ { \
+ if (ret != FF_OK) { \
+ FFReleaseDevice(ff_device); \
+ return false; \
+ } \
+ }
bool joypad::config_force_feedback(io_service_t p_service) {
HRESULT ret = FFCreateDevice(p_service, &ff_device);
@@ -376,8 +380,8 @@ bool joypad::check_ff_features() {
ret = FFDeviceGetForceFeedbackProperty(ff_device, FFPROP_FFGAIN, &val, sizeof(val));
if (ret != FF_OK) return false;
int num_axes = features.numFfAxes;
- ff_axes = (DWORD*) memalloc(sizeof(DWORD) * num_axes);
- ff_directions = (LONG*) memalloc(sizeof(LONG) * num_axes);
+ ff_axes = (DWORD *)memalloc(sizeof(DWORD) * num_axes);
+ ff_directions = (LONG *)memalloc(sizeof(LONG) * num_axes);
for (int i = 0; i < num_axes; i++) {
ff_axes[i] = features.ffAxes[i];
@@ -401,39 +405,39 @@ static int process_hat_value(int p_min, int p_max, int p_value) {
}
switch (value) {
- case 0:
- hat_value = InputDefault::HAT_MASK_UP;
- break;
- case 1:
- hat_value = InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_RIGHT;
- break;
- case 2:
- hat_value = InputDefault::HAT_MASK_RIGHT;
- break;
- case 3:
- hat_value = InputDefault::HAT_MASK_DOWN | InputDefault::HAT_MASK_RIGHT;
- break;
- case 4:
- hat_value = InputDefault::HAT_MASK_DOWN;
- break;
- case 5:
- hat_value = InputDefault::HAT_MASK_DOWN | InputDefault::HAT_MASK_LEFT;
- break;
- case 6:
- hat_value = InputDefault::HAT_MASK_LEFT;
- break;
- case 7:
- hat_value = InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_LEFT;
- break;
- default:
- hat_value = InputDefault::HAT_MASK_CENTER;
- break;
+ case 0:
+ hat_value = InputDefault::HAT_MASK_UP;
+ break;
+ case 1:
+ hat_value = InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_RIGHT;
+ break;
+ case 2:
+ hat_value = InputDefault::HAT_MASK_RIGHT;
+ break;
+ case 3:
+ hat_value = InputDefault::HAT_MASK_DOWN | InputDefault::HAT_MASK_RIGHT;
+ break;
+ case 4:
+ hat_value = InputDefault::HAT_MASK_DOWN;
+ break;
+ case 5:
+ hat_value = InputDefault::HAT_MASK_DOWN | InputDefault::HAT_MASK_LEFT;
+ break;
+ case 6:
+ hat_value = InputDefault::HAT_MASK_LEFT;
+ break;
+ case 7:
+ hat_value = InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_LEFT;
+ break;
+ default:
+ hat_value = InputDefault::HAT_MASK_CENTER;
+ break;
}
return hat_value;
}
void JoypadOSX::poll_joypads() const {
- while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE,0,TRUE) == kCFRunLoopRunHandledSource) {
+ while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
/* no-op. Pending callbacks will fire. */
}
}
@@ -443,18 +447,18 @@ static const InputDefault::JoyAxis axis_correct(int p_value, int p_min, int p_ma
if (p_min < 0) {
jx.min = -1;
if (p_value < 0) {
- jx.value = (float) -p_value / p_min;
- }
- else jx.value = (float) p_value / p_max;
+ jx.value = (float)-p_value / p_min;
+ } else
+ jx.value = (float)p_value / p_max;
}
if (p_min == 0) {
jx.min = 0;
- jx.value = 0.0f + (float) p_value / p_max;
+ jx.value = 0.0f + (float)p_value / p_max;
}
return jx;
}
-uint32_t JoypadOSX::process_joypads(uint32_t p_last_id){
+uint32_t JoypadOSX::process_joypads(uint32_t p_last_id) {
poll_joypads();
for (int i = 0; i < device_list.size(); i++) {
@@ -467,7 +471,7 @@ uint32_t JoypadOSX::process_joypads(uint32_t p_last_id){
}
for (int j = 0; j < joy.button_elements.size(); j++) {
int value = joy.get_hid_element_state(&joy.button_elements[j]);
- p_last_id = input->joy_button(p_last_id, joy.id, j, (value>=1));
+ p_last_id = input->joy_button(p_last_id, joy.id, j, (value >= 1));
}
for (int j = 0; j < joy.hat_elements.size(); j++) {
rec_element &elem = joy.hat_elements[j];
@@ -483,8 +487,7 @@ uint32_t JoypadOSX::process_joypads(uint32_t p_last_id){
float duration = input->get_joy_vibration_duration(joy.id);
if (strength.x == 0 && strength.y == 0) {
joypad_vibration_stop(joy.id, timestamp);
- }
- else {
+ } else {
float gain = MAX(strength.x, strength.y);
joypad_vibration_start(joy.id, gain, duration, timestamp);
}
@@ -504,7 +507,7 @@ void JoypadOSX::joypad_vibration_start(int p_id, float p_magnitude, float p_dura
}
void JoypadOSX::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
- joypad* joy = &device_list[get_joy_index(p_id)];
+ joypad *joy = &device_list[get_joy_index(p_id)];
joy->ff_timestamp = p_timestamp;
FFEffectStop(joy->ff_object);
}
@@ -525,13 +528,12 @@ bool JoypadOSX::have_device(IOHIDDeviceRef p_device) const {
return false;
}
-static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 usage, int *okay)
-{
+static CFDictionaryRef create_match_dictionary(const UInt32 page, const UInt32 usage, int *okay) {
CFDictionaryRef retval = NULL;
CFNumberRef pageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &page);
CFNumberRef usageNumRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &usage);
- const void *keys[2] = { (void *) CFSTR(kIOHIDDeviceUsagePageKey), (void *) CFSTR(kIOHIDDeviceUsageKey) };
- const void *vals[2] = { (void *) pageNumRef, (void *) usageNumRef };
+ const void *keys[2] = { (void *)CFSTR(kIOHIDDeviceUsagePageKey), (void *)CFSTR(kIOHIDDeviceUsageKey) };
+ const void *vals[2] = { (void *)pageNumRef, (void *)usageNumRef };
if (pageNumRef && usageNumRef) {
retval = CFDictionaryCreate(kCFAllocatorDefault, keys, vals, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
@@ -561,28 +563,27 @@ void JoypadOSX::config_hid_manager(CFArrayRef p_matching_array) const {
IOHIDManagerRegisterDeviceMatchingCallback(hid_manager, joypad_added_callback, NULL);
IOHIDManagerScheduleWithRunLoop(hid_manager, runloop, GODOT_JOY_LOOP_RUN_MODE);
- while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE,0,TRUE) == kCFRunLoopRunHandledSource) {
+ while (CFRunLoopRunInMode(GODOT_JOY_LOOP_RUN_MODE, 0, TRUE) == kCFRunLoopRunHandledSource) {
/* no-op. Callback fires once per existing device. */
}
}
-JoypadOSX::JoypadOSX()
-{
+JoypadOSX::JoypadOSX() {
self = this;
- input = (InputDefault*)Input::get_singleton();
+ input = (InputDefault *)Input::get_singleton();
int okay = 1;
const void *vals[] = {
- (void *) create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay),
- (void *) create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay),
- (void *) create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay),
+ (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_Joystick, &okay),
+ (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_GamePad, &okay),
+ (void *)create_match_dictionary(kHIDPage_GenericDesktop, kHIDUsage_GD_MultiAxisController, &okay),
};
- const size_t n_elements = sizeof(vals)/sizeof(vals[0]);
+ const size_t n_elements = sizeof(vals) / sizeof(vals[0]);
CFArrayRef array = okay ? CFArrayCreate(kCFAllocatorDefault, vals, n_elements, &kCFTypeArrayCallBacks) : NULL;
for (int i = 0; i < n_elements; i++) {
if (vals[i]) {
- CFRelease((CFTypeRef) vals[i]);
+ CFRelease((CFTypeRef)vals[i]);
}
}
@@ -606,4 +607,3 @@ JoypadOSX::~JoypadOSX() {
CFRelease(hid_manager);
hid_manager = NULL;
}
-
diff --git a/platform/osx/joypad_osx.h b/platform/osx/joypad_osx.h
index 71a0335316..dabd1b8aec 100644
--- a/platform/osx/joypad_osx.h
+++ b/platform/osx/joypad_osx.h
@@ -34,9 +34,9 @@
#else
#include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
#endif
-#include <IOKit/hid/IOHIDLib.h>
#include <ForceFeedback/ForceFeedback.h>
#include <ForceFeedback/ForceFeedbackConstants.h>
+#include <IOKit/hid/IOHIDLib.h>
#include "main/input_default.h"
@@ -63,7 +63,7 @@ struct joypad {
int id;
- io_service_t ffservice; /* Interface for force feedback, 0 = no ff */
+ io_service_t ffservice; /* Interface for force feedback, 0 = no ff */
FFCONSTANTFORCE ff_constant_force;
FFDeviceObjectReference ff_device;
FFEffectObjectReference ff_object;
diff --git a/platform/osx/os_osx.h b/platform/osx/os_osx.h
index 9941774b40..2c7ad09b89 100644
--- a/platform/osx/os_osx.h
+++ b/platform/osx/os_osx.h
@@ -29,22 +29,21 @@
#ifndef OS_OSX_H
#define OS_OSX_H
-
-#include "os/input.h"
-#include "joypad_osx.h"
-#include "power_osx.h"
#include "drivers/unix/os_unix.h"
+#include "joypad_osx.h"
#include "main/input_default.h"
+#include "os/input.h"
+#include "power_osx.h"
#include "servers/visual_server.h"
// #include "servers/visual/visual_server_wrap_mt.h"
-#include "servers/visual/rasterizer.h"
-#include "servers/physics_server.h"
-#include "servers/audio_server.h"
-#include "drivers/rtaudio/audio_driver_rtaudio.h"
#include "drivers/alsa/audio_driver_alsa.h"
+#include "drivers/rtaudio/audio_driver_rtaudio.h"
+#include "platform/osx/audio_driver_osx.h"
+#include "servers/audio_server.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
-#include "platform/osx/audio_driver_osx.h"
+#include "servers/physics_server.h"
+#include "servers/visual/rasterizer.h"
#include <ApplicationServices/ApplicationServices.h>
//bitch
@@ -56,7 +55,7 @@
class OS_OSX : public OS_Unix {
public:
bool force_quit;
-// rasterizer seems to no longer be given to visual server, its using GLES3 directly?
+ // rasterizer seems to no longer be given to visual server, its using GLES3 directly?
//Rasterizer *rasterizer;
VisualServer *visual_server;
@@ -80,8 +79,8 @@ public:
void process_events();
- void* framework;
-// pthread_key_t current;
+ void *framework;
+ // pthread_key_t current;
bool mouse_grab;
Point2 mouse_pos;
uint32_t last_id;
@@ -108,60 +107,58 @@ public:
Size2 window_size;
int current_screen;
Rect2 restore_rect;
-
+
power_osx *power_manager;
float _mouse_scale(float p_scale) {
- if (display_scale>1.0)
+ if (display_scale > 1.0)
return p_scale;
else
return 1.0;
}
float display_scale;
-protected:
+protected:
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
virtual void finalize();
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
public:
-
-
- static OS_OSX* singleton;
+ static OS_OSX *singleton;
void wm_minimized(bool p_minimized);
virtual String get_name();
- virtual void alert(const String& p_alert, const String& p_title="ALERT!");
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
virtual void set_cursor_shape(CursorShape p_shape);
virtual void set_mouse_show(bool p_show);
virtual void set_mouse_grab(bool p_grab);
virtual bool is_mouse_grab_enabled() const;
- virtual void warp_mouse_pos(const Point2& p_to);
+ virtual void warp_mouse_pos(const Point2 &p_to);
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
virtual Size2 get_window_size() const;
- virtual void set_icon(const Image& p_icon);
+ virtual void set_icon(const Image &p_icon);
virtual MainLoop *get_main_loop() const;
virtual bool can_draw() const;
- virtual void set_clipboard(const String& p_text);
+ virtual void set_clipboard(const String &p_text);
virtual String get_clipboard() const;
virtual void release_rendering_thread();
@@ -169,13 +166,13 @@ public:
virtual void swap_buffers();
Error shell_open(String p_uri);
- void push_input(const InputEvent& p_event);
+ void push_input(const InputEvent &p_event);
String get_locale() const;
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual String get_executable_path() const;
@@ -186,12 +183,12 @@ public:
virtual int get_screen_count() const;
virtual int get_current_screen() const;
virtual void set_current_screen(int p_screen);
- virtual Point2 get_screen_position(int p_screen=0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
- virtual int get_screen_dpi(int p_screen=0) const;
+ virtual Point2 get_screen_position(int p_screen = 0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
+ virtual int get_screen_dpi(int p_screen = 0) const;
virtual Point2 get_window_position() const;
- virtual void set_window_position(const Point2& p_position);
+ virtual void set_window_position(const Point2 &p_position);
virtual void set_window_size(const Size2 p_size);
virtual void set_window_fullscreen(bool p_enabled);
virtual bool is_window_fullscreen() const;
@@ -203,15 +200,15 @@ public:
virtual bool is_window_maximized() const;
virtual void request_attention();
virtual String get_joy_guid(int p_device) const;
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
void run();
- void set_mouse_mode(MouseMode p_mode);
- MouseMode get_mouse_mode() const;
+ void set_mouse_mode(MouseMode p_mode);
+ MouseMode get_mouse_mode() const;
OS_OSX();
};
diff --git a/platform/osx/power_osx.cpp b/platform/osx/power_osx.cpp
index 5c8f067f24..de9bcaf6fc 100644
--- a/platform/osx/power_osx.cpp
+++ b/platform/osx/power_osx.cpp
@@ -29,20 +29,19 @@
#include "power_osx.h"
#include <CoreFoundation/CoreFoundation.h>
-#include <IOKit/ps/IOPowerSources.h>
#include <IOKit/ps/IOPSKeys.h>
+#include <IOKit/ps/IOPowerSources.h>
// CODE CHUNK IMPORTED FROM SDL 2.0
/* CoreFoundation is so verbose... */
-#define STRMATCH(a,b) (CFStringCompare(a, b, 0) == kCFCompareEqualTo)
-#define GETVAL(k,v) \
- CFDictionaryGetValueIfPresent(dict, CFSTR(k), (const void **) v)
+#define STRMATCH(a, b) (CFStringCompare(a, b, 0) == kCFCompareEqualTo)
+#define GETVAL(k, v) \
+ CFDictionaryGetValueIfPresent(dict, CFSTR(k), (const void **)v)
/* Note that AC power sources also include a laptop battery it is charging. */
-void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_battery, bool * charging)
-{
- CFStringRef strval; /* don't CFRelease() this. */
+void power_osx::checkps(CFDictionaryRef dict, bool *have_ac, bool *have_battery, bool *charging) {
+ CFStringRef strval; /* don't CFRelease() this. */
CFBooleanRef bval;
CFNumberRef numval;
bool charge = false;
@@ -53,7 +52,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
int pct = -1;
if ((GETVAL(kIOPSIsPresentKey, &bval)) && (bval == kCFBooleanFalse)) {
- return; /* nothing to see here. */
+ return; /* nothing to see here. */
}
if (!GETVAL(kIOPSPowerSourceStateKey, &strval)) {
@@ -63,7 +62,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
if (STRMATCH(strval, CFSTR(kIOPSACPowerValue))) {
is_ac = *have_ac = true;
} else if (!STRMATCH(strval, CFSTR(kIOPSBatteryPowerValue))) {
- return; /* not a battery? */
+ return; /* not a battery? */
}
if ((GETVAL(kIOPSIsChargingKey, &bval)) && (bval == kCFBooleanTrue)) {
@@ -75,7 +74,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
CFNumberGetValue(numval, kCFNumberSInt32Type, &val);
if (val > 0) {
*have_battery = true;
- maxpct = (int) val;
+ maxpct = (int)val;
}
}
@@ -84,7 +83,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
CFNumberGetValue(numval, kCFNumberSInt32Type, &val);
if (val > 0) {
*have_battery = true;
- maxpct = (int) val;
+ maxpct = (int)val;
}
}
@@ -93,24 +92,24 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
CFNumberGetValue(numval, kCFNumberSInt32Type, &val);
/* Mac OS X reports 0 minutes until empty if you're plugged in. :( */
- if ((val == 0) && (is_ac)) {
- val = -1; /* !!! FIXME: calc from timeToFull and capacity? */
- }
+ if ((val == 0) && (is_ac)) {
+ val = -1; /* !!! FIXME: calc from timeToFull and capacity? */
+ }
- secs = (int) val;
- if (secs > 0) {
- secs *= 60; /* value is in minutes, so convert to seconds. */
- }
+ secs = (int)val;
+ if (secs > 0) {
+ secs *= 60; /* value is in minutes, so convert to seconds. */
+ }
}
if (GETVAL(kIOPSCurrentCapacityKey, &numval)) {
SInt32 val = -1;
CFNumberGetValue(numval, kCFNumberSInt32Type, &val);
- pct = (int) val;
+ pct = (int)val;
}
if ((pct > 0) && (maxpct > 0)) {
- pct = (int) ((((double) pct) / ((double) maxpct)) * 100.0);
+ pct = (int)((((double)pct) / ((double)maxpct)) * 100.0);
}
if (pct > 100) {
@@ -123,7 +122,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
*/
if ((secs < 0) && (nsecs_left < 0)) {
if ((pct < 0) && (percent_left < 0)) {
- choose = true; /* at least we know there's a battery. */
+ choose = true; /* at least we know there's a battery. */
}
if (pct > percent_left) {
choose = true;
@@ -143,8 +142,7 @@ void power_osx::checkps(CFDictionaryRef dict, bool * have_ac, bool * have_batter
#undef STRMATCH
// CODE CHUNK IMPORTED FROM SDL 2.0
-bool power_osx::GetPowerInfo_MacOSX()
-{
+bool power_osx::GetPowerInfo_MacOSX() {
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
nsecs_left = -1;
@@ -161,7 +159,7 @@ bool power_osx::GetPowerInfo_MacOSX()
const CFIndex total = CFArrayGetCount(list);
CFIndex i;
for (i = 0; i < total; i++) {
- CFTypeRef ps = (CFTypeRef) CFArrayGetValueAtIndex(list, i);
+ CFTypeRef ps = (CFTypeRef)CFArrayGetValueAtIndex(list, i);
CFDictionaryRef dict = IOPSGetPowerSourceDescription(blob, ps);
if (dict != NULL) {
checkps(dict, &have_ac, &have_battery, &charging);
@@ -183,11 +181,9 @@ bool power_osx::GetPowerInfo_MacOSX()
CFRelease(blob);
}
- return true; /* always the definitive answer on Mac OS X. */
+ return true; /* always the definitive answer on Mac OS X. */
}
-
-
bool power_osx::UpdatePowerInfo() {
if (GetPowerInfo_MacOSX()) {
return true;
@@ -195,12 +191,10 @@ bool power_osx::UpdatePowerInfo() {
return false;
}
-
PowerState power_osx::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
return POWERSTATE_UNKNOWN;
}
}
@@ -208,8 +202,7 @@ PowerState power_osx::get_power_state() {
int power_osx::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
return -1;
}
}
@@ -217,17 +210,14 @@ int power_osx::get_power_seconds_left() {
int power_osx::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
return -1;
}
}
-
-power_osx::power_osx() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+power_osx::power_osx()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
power_osx::~power_osx() {
-
}
diff --git a/platform/osx/power_osx.h b/platform/osx/power_osx.h
index a4aee31117..c638dc675a 100644
--- a/platform/osx/power_osx.h
+++ b/platform/osx/power_osx.h
@@ -41,7 +41,7 @@ private:
int nsecs_left;
int percent_left;
PowerState power_state;
- void checkps(CFDictionaryRef dict, bool * have_ac, bool * have_battery, bool * charging);
+ void checkps(CFDictionaryRef dict, bool *have_ac, bool *have_battery, bool *charging);
bool GetPowerInfo_MacOSX(/*PowerState * state, int *seconds, int *percent*/);
bool UpdatePowerInfo();
diff --git a/platform/osx/sem_osx.cpp b/platform/osx/sem_osx.cpp
index ca710d8b1e..069e3a5153 100644
--- a/platform/osx/sem_osx.cpp
+++ b/platform/osx/sem_osx.cpp
@@ -28,11 +28,10 @@
/*************************************************************************/
#include "sem_osx.h"
-#include <unistd.h>
#include <fcntl.h>
+#include <unistd.h>
-void cgsem_init(cgsem_t *cgsem)
-{
+void cgsem_init(cgsem_t *cgsem) {
int flags, fd, i;
pipe(cgsem->pipefd);
@@ -47,31 +46,26 @@ void cgsem_init(cgsem_t *cgsem)
}
}
-void cgsem_post(cgsem_t *cgsem)
-{
+void cgsem_post(cgsem_t *cgsem) {
const char buf = 1;
write(cgsem->pipefd[1], &buf, 1);
}
-void cgsem_wait(cgsem_t *cgsem)
-{
+void cgsem_wait(cgsem_t *cgsem) {
char buf;
read(cgsem->pipefd[0], &buf, 1);
}
-void cgsem_destroy(cgsem_t *cgsem)
-{
+void cgsem_destroy(cgsem_t *cgsem) {
close(cgsem->pipefd[1]);
close(cgsem->pipefd[0]);
}
-
#include "os/memory.h"
#include <errno.h>
-
Error SemaphoreOSX::wait() {
cgsem_wait(&sem);
@@ -89,15 +83,14 @@ int SemaphoreOSX::get() const {
return 0;
}
-
Semaphore *SemaphoreOSX::create_semaphore_osx() {
- return memnew( SemaphoreOSX );
+ return memnew(SemaphoreOSX);
}
void SemaphoreOSX::make_default() {
- create_func=create_semaphore_osx;
+ create_func = create_semaphore_osx;
}
SemaphoreOSX::SemaphoreOSX() {
@@ -105,11 +98,7 @@ SemaphoreOSX::SemaphoreOSX() {
cgsem_init(&sem);
}
-
SemaphoreOSX::~SemaphoreOSX() {
cgsem_destroy(&sem);
}
-
-
-
diff --git a/platform/osx/sem_osx.h b/platform/osx/sem_osx.h
index da2fac434c..a30f3fcc98 100644
--- a/platform/osx/sem_osx.h
+++ b/platform/osx/sem_osx.h
@@ -44,7 +44,6 @@ class SemaphoreOSX : public Semaphore {
static Semaphore *create_semaphore_osx();
public:
-
virtual Error wait();
virtual Error post();
virtual int get() const;
@@ -53,8 +52,6 @@ public:
SemaphoreOSX();
~SemaphoreOSX();
-
};
-
#endif
diff --git a/platform/server/godot_server.cpp b/platform/server/godot_server.cpp
index 37e73d663d..d06ade4a57 100644
--- a/platform/server/godot_server.cpp
+++ b/platform/server/godot_server.cpp
@@ -29,12 +29,12 @@
#include "main/main.h"
#include "os_server.h"
-int main(int argc, char* argv[]) {
+int main(int argc, char *argv[]) {
OS_Server os;
- Error err = Main::setup(argv[0],argc-1,&argv[1]);
- if (err!=OK)
+ Error err = Main::setup(argv[0], argc - 1, &argv[1]);
+ if (err != OK)
return 255;
if (Main::start())
diff --git a/platform/server/os_server.cpp b/platform/server/os_server.cpp
index ee80080b4e..f44d976bd6 100644
--- a/platform/server/os_server.cpp
+++ b/platform/server/os_server.cpp
@@ -29,10 +29,10 @@
//#include "servers/visual/visual_server_raster.h"
//#include "servers/visual/rasterizer_dummy.h"
#include "os_server.h"
-#include <stdio.h>
-#include <stdlib.h>
#include "print_string.h"
#include "servers/physics/physics_server_sw.h"
+#include <stdio.h>
+#include <stdlib.h>
#include "main/main.h"
@@ -42,20 +42,20 @@ int OS_Server::get_video_driver_count() const {
return 1;
}
-const char * OS_Server::get_video_driver_name(int p_driver) const {
+const char *OS_Server::get_video_driver_name(int p_driver) const {
return "Dummy";
}
OS::VideoMode OS_Server::get_default_video_mode() const {
- return OS::VideoMode(800,600,false);
+ return OS::VideoMode(800, 600, false);
}
-void OS_Server::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OS_Server::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
- args=OS::get_singleton()->get_cmdline_args();
- current_videomode=p_desired;
- main_loop=NULL;
+ args = OS::get_singleton()->get_cmdline_args();
+ current_videomode = p_desired;
+ main_loop = NULL;
//rasterizer = memnew( RasterizerDummy );
@@ -63,40 +63,37 @@ void OS_Server::initialize(const VideoMode& p_desired,int p_video_driver,int p_a
AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
- if (AudioDriverManager::get_driver(p_audio_driver)->init()!=OK) {
+ if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
ERR_PRINT("Initializing audio failed.");
}
- sample_manager = memnew( SampleManagerMallocSW );
- audio_server = memnew( AudioServerSW(sample_manager) );
+ sample_manager = memnew(SampleManagerMallocSW);
+ audio_server = memnew(AudioServerSW(sample_manager));
audio_server->init();
- spatial_sound_server = memnew( SpatialSoundServerSW );
+ spatial_sound_server = memnew(SpatialSoundServerSW);
spatial_sound_server->init();
- spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
+ spatial_sound_2d_server = memnew(SpatialSound2DServerSW);
spatial_sound_2d_server->init();
-
ERR_FAIL_COND(!visual_server);
visual_server->init();
//
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
- physics_2d_server = memnew( Physics2DServerSW );
+ physics_2d_server = memnew(Physics2DServerSW);
physics_2d_server->init();
- input = memnew( InputDefault );
+ input = memnew(InputDefault);
_ensure_data_dir();
-
-
}
void OS_Server::finalize() {
- if(main_loop)
+ if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
spatial_sound_server->finish();
memdelete(spatial_sound_server);
@@ -130,12 +127,10 @@ void OS_Server::finalize() {
}
void OS_Server::set_mouse_show(bool p_show) {
-
-
}
void OS_Server::set_mouse_grab(bool p_grab) {
- grab=p_grab;
+ grab = p_grab;
}
bool OS_Server::is_mouse_grab_enabled() const {
@@ -152,14 +147,10 @@ Point2 OS_Server::get_mouse_pos() const {
return Point2();
}
-void OS_Server::set_window_title(const String& p_title) {
-
-
+void OS_Server::set_window_title(const String &p_title) {
}
-void OS_Server::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
-
-
+void OS_Server::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
}
OS::VideoMode OS_Server::get_video_mode(int p_screen) const {
@@ -168,15 +159,12 @@ OS::VideoMode OS_Server::get_video_mode(int p_screen) const {
Size2 OS_Server::get_window_size() const {
- return Vector2(current_videomode.width,current_videomode.height) ;
+ return Vector2(current_videomode.width, current_videomode.height);
}
-void OS_Server::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
-
-
+void OS_Server::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
}
-
MainLoop *OS_Server::get_main_loop() const {
return main_loop;
@@ -186,12 +174,12 @@ void OS_Server::delete_main_loop() {
if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
}
-void OS_Server::set_main_loop( MainLoop * p_main_loop ) {
+void OS_Server::set_main_loop(MainLoop *p_main_loop) {
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
input->set_main_loop(p_main_loop);
}
@@ -200,21 +188,15 @@ bool OS_Server::can_draw() const {
return false; //can never draw
};
-
String OS_Server::get_name() {
return "Server";
}
-
-
void OS_Server::move_window_to_foreground() {
-
}
void OS_Server::set_cursor_shape(CursorShape p_shape) {
-
-
}
PowerState OS_Server::get_power_state() {
@@ -240,7 +222,7 @@ void OS_Server::run() {
while (!force_quit) {
- if (Main::iteration()==true)
+ if (Main::iteration() == true)
break;
};
@@ -251,6 +233,5 @@ OS_Server::OS_Server() {
AudioDriverManager::add_driver(&driver_dummy);
//adriver here
- grab=false;
-
+ grab = false;
};
diff --git a/platform/server/os_server.h b/platform/server/os_server.h
index a035076726..7484d70e06 100644
--- a/platform/server/os_server.h
+++ b/platform/server/os_server.h
@@ -29,16 +29,16 @@
#ifndef OS_SERVER_H
#define OS_SERVER_H
-#include "main/input_default.h"
+#include "../x11/power_x11.h"
+#include "drivers/rtaudio/audio_driver_rtaudio.h"
#include "drivers/unix/os_unix.h"
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
+#include "main/input_default.h"
#include "servers/audio/audio_driver_dummy.h"
-#include "servers/physics_server.h"
#include "servers/audio_server.h"
-#include "drivers/rtaudio/audio_driver_rtaudio.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
-#include "../x11/power_x11.h"
+#include "servers/physics_server.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
//bitch
#undef CursorShape
@@ -66,24 +66,20 @@ class OS_Server : public OS_Unix {
bool force_quit;
InputDefault *input;
-
- PowerX11 *power_manager;
-
+ PowerX11 *power_manager;
protected:
-
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
virtual void finalize();
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
public:
-
virtual String get_name();
virtual void set_cursor_shape(CursorShape p_shape);
@@ -93,22 +89,22 @@ public:
virtual bool is_mouse_grab_enabled() const;
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
virtual MainLoop *get_main_loop() const;
virtual bool can_draw() const;
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual Size2 get_window_size() const;
virtual void move_window_to_foreground();
void run();
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
diff --git a/platform/uwp/app.cpp b/platform/uwp/app.cpp
index 0bae148c6b..35b25b1de5 100644
--- a/platform/uwp/app.cpp
+++ b/platform/uwp/app.cpp
@@ -32,10 +32,10 @@
#include "app.h"
-#include "main/main.h"
#include "core/os/dir_access.h"
#include "core/os/file_access.h"
#include "core/os/keyboard.h"
+#include "main/main.h"
#include "platform/windows/key_mapping_win.h"
@@ -56,126 +56,113 @@ using namespace Microsoft::WRL;
using namespace GodotUWP;
// Helper to convert a length in device-independent pixels (DIPs) to a length in physical pixels.
-inline float ConvertDipsToPixels(float dips, float dpi)
-{
- static const float dipsPerInch = 96.0f;
- return floor(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
+inline float ConvertDipsToPixels(float dips, float dpi) {
+ static const float dipsPerInch = 96.0f;
+ return floor(dips * dpi / dipsPerInch + 0.5f); // Round to nearest integer.
}
// Implementation of the IFrameworkViewSource interface, necessary to run our app.
-ref class GodotUWPViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
-{
+ref class GodotUWPViewSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource {
public:
- virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView()
- {
- return ref new App();
- }
+ virtual Windows::ApplicationModel::Core::IFrameworkView ^ CreateView() {
+ return ref new App();
+ }
};
// The main function creates an IFrameworkViewSource for our app, and runs the app.
-[Platform::MTAThread]
-int main(Platform::Array<Platform::String^>^)
-{
- auto godotApplicationSource = ref new GodotUWPViewSource();
- CoreApplication::Run(godotApplicationSource);
- return 0;
+[Platform::MTAThread] int main(Platform::Array<Platform::String ^> ^) {
+ auto godotApplicationSource = ref new GodotUWPViewSource();
+ CoreApplication::Run(godotApplicationSource);
+ return 0;
}
-App::App() :
- mWindowClosed(false),
- mWindowVisible(true),
- mWindowWidth(0),
- mWindowHeight(0),
- mEglDisplay(EGL_NO_DISPLAY),
- mEglContext(EGL_NO_CONTEXT),
- mEglSurface(EGL_NO_SURFACE),
- number_of_contacts(0)
-{
+App::App()
+ : mWindowClosed(false),
+ mWindowVisible(true),
+ mWindowWidth(0),
+ mWindowHeight(0),
+ mEglDisplay(EGL_NO_DISPLAY),
+ mEglContext(EGL_NO_CONTEXT),
+ mEglSurface(EGL_NO_SURFACE),
+ number_of_contacts(0) {
}
// The first method called when the IFrameworkView is being created.
-void App::Initialize(CoreApplicationView^ applicationView)
-{
- // Register event handlers for app lifecycle. This example includes Activated, so that we
- // can make the CoreWindow active and start rendering on the window.
- applicationView->Activated +=
- ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
+void App::Initialize(CoreApplicationView ^ applicationView) {
+ // Register event handlers for app lifecycle. This example includes Activated, so that we
+ // can make the CoreWindow active and start rendering on the window.
+ applicationView->Activated +=
+ ref new TypedEventHandler<CoreApplicationView ^, IActivatedEventArgs ^>(this, &App::OnActivated);
- // Logic for other event handlers could go here.
- // Information about the Suspending and Resuming event handlers can be found here:
- // http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994930.aspx
+ // Logic for other event handlers could go here.
+ // Information about the Suspending and Resuming event handlers can be found here:
+ // http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh994930.aspx
os = new OSUWP;
-
}
// Called when the CoreWindow object is created (or re-created).
-void App::SetWindow(CoreWindow^ p_window)
-{
+void App::SetWindow(CoreWindow ^ p_window) {
window = p_window;
- window->VisibilityChanged +=
- ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &App::OnVisibilityChanged);
+ window->VisibilityChanged +=
+ ref new TypedEventHandler<CoreWindow ^, VisibilityChangedEventArgs ^>(this, &App::OnVisibilityChanged);
- window->Closed +=
- ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::OnWindowClosed);
+ window->Closed +=
+ ref new TypedEventHandler<CoreWindow ^, CoreWindowEventArgs ^>(this, &App::OnWindowClosed);
- window->SizeChanged +=
- ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &App::OnWindowSizeChanged);
+ window->SizeChanged +=
+ ref new TypedEventHandler<CoreWindow ^, WindowSizeChangedEventArgs ^>(this, &App::OnWindowSizeChanged);
#if !(WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- // Disable all pointer visual feedback for better performance when touching.
- // This is not supported on Windows Phone applications.
- auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
- pointerVisualizationSettings->IsContactFeedbackEnabled = false;
- pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
+ // Disable all pointer visual feedback for better performance when touching.
+ // This is not supported on Windows Phone applications.
+ auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
+ pointerVisualizationSettings->IsContactFeedbackEnabled = false;
+ pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
#endif
-
window->PointerPressed +=
- ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerPressed);
+ ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerPressed);
window->PointerMoved +=
- ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerMoved);
+ ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerMoved);
window->PointerReleased +=
- ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerReleased);
+ ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerReleased);
window->PointerWheelChanged +=
- ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &App::OnPointerWheelChanged);
+ ref new TypedEventHandler<CoreWindow ^, PointerEventArgs ^>(this, &App::OnPointerWheelChanged);
mouseChangedNotifier = SignalNotifier::AttachToEvent(L"os_mouse_mode_changed", ref new SignalHandler(
- this, &App::OnMouseModeChanged
- ));
+ this, &App::OnMouseModeChanged));
mouseChangedNotifier->Enable();
window->CharacterReceived +=
- ref new TypedEventHandler<CoreWindow^, CharacterReceivedEventArgs^>(this, &App::OnCharacterReceived);
+ ref new TypedEventHandler<CoreWindow ^, CharacterReceivedEventArgs ^>(this, &App::OnCharacterReceived);
window->KeyDown +=
- ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyDown);
+ ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyDown);
window->KeyUp +=
- ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &App::OnKeyUp);
-
+ ref new TypedEventHandler<CoreWindow ^, KeyEventArgs ^>(this, &App::OnKeyUp);
unsigned int argc;
- char** argv = get_command_line(&argc);
+ char **argv = get_command_line(&argc);
Main::setup("uwp", argc, argv, false);
// The CoreWindow has been created, so EGL can be initialized.
- ContextEGL* context = memnew(ContextEGL(window));
+ ContextEGL *context = memnew(ContextEGL(window));
os->set_gl_context(context);
UpdateWindowSize(Size(window->Bounds.Width, window->Bounds.Height));
Main::setup2();
}
-static int _get_button(Windows::UI::Input::PointerPoint ^pt) {
+static int _get_button(Windows::UI::Input::PointerPoint ^ pt) {
using namespace Windows::UI::Input;
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
return BUTTON_LEFT;
#else
- switch (pt->Properties->PointerUpdateKind)
- {
+ switch (pt->Properties->PointerUpdateKind) {
case PointerUpdateKind::LeftButtonPressed:
case PointerUpdateKind::LeftButtonReleased:
return BUTTON_LEFT;
@@ -204,7 +191,7 @@ static int _get_button(Windows::UI::Input::PointerPoint ^pt) {
return 0;
};
-static bool _is_touch(Windows::UI::Input::PointerPoint ^pointerPoint) {
+static bool _is_touch(Windows::UI::Input::PointerPoint ^ pointerPoint) {
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
return true;
#else
@@ -219,20 +206,18 @@ static bool _is_touch(Windows::UI::Input::PointerPoint ^pointerPoint) {
#endif
}
-
-static Windows::Foundation::Point _get_pixel_position(CoreWindow^ window, Windows::Foundation::Point rawPosition, OS* os) {
+static Windows::Foundation::Point _get_pixel_position(CoreWindow ^ window, Windows::Foundation::Point rawPosition, OS *os) {
Windows::Foundation::Point outputPosition;
- // Compute coordinates normalized from 0..1.
- // If the coordinates need to be sized to the SDL window,
- // we'll do that after.
- #if 1 || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
+// Compute coordinates normalized from 0..1.
+// If the coordinates need to be sized to the SDL window,
+// we'll do that after.
+#if 1 || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
outputPosition.X = rawPosition.X / window->Bounds.Width;
outputPosition.Y = rawPosition.Y / window->Bounds.Height;
- #else
- switch (DisplayProperties::CurrentOrientation)
- {
+#else
+ switch (DisplayProperties::CurrentOrientation) {
case DisplayOrientations::Portrait:
outputPosition.X = rawPosition.X / window->Bounds.Width;
outputPosition.Y = rawPosition.Y / window->Bounds.Height;
@@ -252,7 +237,7 @@ static Windows::Foundation::Point _get_pixel_position(CoreWindow^ window, Window
default:
break;
}
- #endif
+#endif
OS::VideoMode vm = os->get_video_mode();
outputPosition.X *= vm.width;
@@ -266,9 +251,9 @@ static int _get_finger(uint32_t p_touch_id) {
return p_touch_id % 31; // for now
};
-void App::pointer_event(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args, bool p_pressed, bool p_is_wheel) {
+void App::pointer_event(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args, bool p_pressed, bool p_is_wheel) {
- Windows::UI::Input::PointerPoint ^point = args->CurrentPoint;
+ Windows::UI::Input::PointerPoint ^ point = args->CurrentPoint;
Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);
int but = _get_button(point);
if (_is_touch(point)) {
@@ -314,56 +299,51 @@ void App::pointer_event(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core
os->input_event(event);
};
-
-void App::OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {
+void App::OnPointerPressed(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
number_of_contacts++;
pointer_event(sender, args, true);
};
-
-void App::OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {
+void App::OnPointerReleased(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
number_of_contacts--;
pointer_event(sender, args, false);
};
-void App::OnPointerWheelChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {
+void App::OnPointerWheelChanged(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
pointer_event(sender, args, true, true);
}
-void App::OnMouseModeChanged(Windows::System::Threading::Core::SignalNotifier^ signalNotifier, bool timedOut) {
+void App::OnMouseModeChanged(Windows::System::Threading::Core::SignalNotifier ^ signalNotifier, bool timedOut) {
OS::MouseMode mode = os->get_mouse_mode();
- SignalNotifier^ notifier = mouseChangedNotifier;
+ SignalNotifier ^ notifier = mouseChangedNotifier;
window->Dispatcher->RunAsync(
- CoreDispatcherPriority::High,
- ref new DispatchedHandler(
- [mode, notifier, this]() {
- if (mode == OS::MOUSE_MODE_CAPTURED) {
+ CoreDispatcherPriority::High,
+ ref new DispatchedHandler(
+ [mode, notifier, this]() {
+ if (mode == OS::MOUSE_MODE_CAPTURED) {
- this->MouseMovedToken = MouseDevice::GetForCurrentView()->MouseMoved +=
- ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &App::OnMouseMoved);
+ this->MouseMovedToken = MouseDevice::GetForCurrentView()->MouseMoved +=
+ ref new TypedEventHandler<MouseDevice ^, MouseEventArgs ^>(this, &App::OnMouseMoved);
- } else {
+ } else {
- MouseDevice::GetForCurrentView()->MouseMoved -= MouseMovedToken;
+ MouseDevice::GetForCurrentView()->MouseMoved -= MouseMovedToken;
+ }
- }
-
- notifier->Enable();
- }));
+ notifier->Enable();
+ }));
ResetEvent(os->mouse_mode_changed);
-
-
}
-void App::OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args) {
+void App::OnPointerMoved(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args) {
- Windows::UI::Input::PointerPoint ^point = args->CurrentPoint;
+ Windows::UI::Input::PointerPoint ^ point = args->CurrentPoint;
Windows::Foundation::Point pos = _get_pixel_position(window, point->Position, os);
if (point->IsInContact && _is_touch(point)) {
@@ -400,7 +380,6 @@ void App::OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Cor
last_mouse_pos = pos;
os->input_event(event);
-
}
void App::OnMouseMoved(MouseDevice ^ mouse_device, MouseEventArgs ^ args) {
@@ -428,8 +407,7 @@ void App::OnMouseMoved(MouseDevice ^ mouse_device, MouseEventArgs ^ args) {
os->input_event(event);
}
-void App::key_event(Windows::UI::Core::CoreWindow^ sender, bool p_pressed, Windows::UI::Core::KeyEventArgs^ key_args, Windows::UI::Core::CharacterReceivedEventArgs^ char_args)
-{
+void App::key_event(Windows::UI::Core::CoreWindow ^ sender, bool p_pressed, Windows::UI::Core::KeyEventArgs ^ key_args, Windows::UI::Core::CharacterReceivedEventArgs ^ char_args) {
OSUWP::KeyEvent ke;
@@ -442,9 +420,9 @@ void App::key_event(Windows::UI::Core::CoreWindow^ sender, bool p_pressed, Windo
ke.mod_state = mod;
ke.pressed = p_pressed;
-
+
if (key_args != nullptr) {
-
+
ke.type = OSUWP::KeyEvent::MessageType::KEY_EVENT_MESSAGE;
ke.unicode = 0;
ke.scancode = KeyMappingWindows::get_keysym((unsigned int)key_args->VirtualKey);
@@ -459,92 +437,78 @@ void App::key_event(Windows::UI::Core::CoreWindow^ sender, bool p_pressed, Windo
}
os->queue_key_event(ke);
-
}
-void App::OnKeyDown(CoreWindow^ sender, KeyEventArgs^ args)
-{
+void App::OnKeyDown(CoreWindow ^ sender, KeyEventArgs ^ args) {
key_event(sender, true, args);
}
-void App::OnKeyUp(CoreWindow^ sender, KeyEventArgs^ args)
-{
+void App::OnKeyUp(CoreWindow ^ sender, KeyEventArgs ^ args) {
key_event(sender, false, args);
}
-void App::OnCharacterReceived(CoreWindow^ sender, CharacterReceivedEventArgs^ args)
-{
+void App::OnCharacterReceived(CoreWindow ^ sender, CharacterReceivedEventArgs ^ args) {
key_event(sender, true, nullptr, args);
}
-
// Initializes scene resources
-void App::Load(Platform::String^ entryPoint)
-{
-
+void App::Load(Platform::String ^ entryPoint) {
}
// This method is called after the window becomes active.
-void App::Run()
-{
+void App::Run() {
if (Main::start())
os->run();
}
// Terminate events do not cause Uninitialize to be called. It will be called if your IFrameworkView
// class is torn down while the app is in the foreground.
-void App::Uninitialize()
-{
+void App::Uninitialize() {
Main::cleanup();
delete os;
}
// Application lifecycle event handler.
-void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
-{
- // Run() won't start until the CoreWindow is activated.
- CoreWindow::GetForCurrentThread()->Activate();
+void App::OnActivated(CoreApplicationView ^ applicationView, IActivatedEventArgs ^ args) {
+ // Run() won't start until the CoreWindow is activated.
+ CoreWindow::GetForCurrentThread()->Activate();
}
// Window event handlers.
-void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
-{
- mWindowVisible = args->Visible;
+void App::OnVisibilityChanged(CoreWindow ^ sender, VisibilityChangedEventArgs ^ args) {
+ mWindowVisible = args->Visible;
}
-void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
-{
- mWindowClosed = true;
+void App::OnWindowClosed(CoreWindow ^ sender, CoreWindowEventArgs ^ args) {
+ mWindowClosed = true;
}
-void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
-{
+void App::OnWindowSizeChanged(CoreWindow ^ sender, WindowSizeChangedEventArgs ^ args) {
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
- // On Windows 8.1, apps are resized when they are snapped alongside other apps, or when the device is rotated.
- // The default framebuffer will be automatically resized when either of these occur.
- // In particular, on a 90 degree rotation, the default framebuffer's width and height will switch.
- UpdateWindowSize(args->Size);
+ // On Windows 8.1, apps are resized when they are snapped alongside other apps, or when the device is rotated.
+ // The default framebuffer will be automatically resized when either of these occur.
+ // In particular, on a 90 degree rotation, the default framebuffer's width and height will switch.
+ UpdateWindowSize(args->Size);
#else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
- // On Windows Phone 8.1, the window size changes when the device is rotated.
- // The default framebuffer will not be automatically resized when this occurs.
- // It is therefore up to the app to handle rotation-specific logic in its rendering code.
+ // On Windows Phone 8.1, the window size changes when the device is rotated.
+ // The default framebuffer will not be automatically resized when this occurs.
+ // It is therefore up to the app to handle rotation-specific logic in its rendering code.
//os->screen_size_changed();
UpdateWindowSize(args->Size);
#endif
}
-void App::UpdateWindowSize(Size size)
-{
+void App::UpdateWindowSize(Size size) {
float dpi;
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
- DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
+ DisplayInformation ^ currentDisplayInformation = DisplayInformation::GetForCurrentView();
dpi = currentDisplayInformation->LogicalDpi;
#else if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
dpi = DisplayProperties::LogicalDpi;
#endif
Size pixelSize(ConvertDipsToPixels(size.Width, dpi), ConvertDipsToPixels(size.Height, dpi));
- mWindowWidth = static_cast<GLsizei>(pixelSize.Width);
- mWindowHeight = static_cast<GLsizei>(pixelSize.Height);
+ mWindowWidth = static_cast<GLsizei>(pixelSize.Width);
+ mWindowHeight = static_cast<GLsizei>(pixelSize.Height);
OS::VideoMode vm;
vm.width = mWindowWidth;
@@ -554,12 +518,12 @@ void App::UpdateWindowSize(Size size)
os->set_video_mode(vm);
}
-char** App::get_command_line(unsigned int* out_argc) {
+char **App::get_command_line(unsigned int *out_argc) {
- static char* fail_cl[] = { "-path", "game", NULL };
+ static char *fail_cl[] = { "-path", "game", NULL };
*out_argc = 2;
- FILE* f = _wfopen(L"__cl__.cl", L"rb");
+ FILE *f = _wfopen(L"__cl__.cl", L"rb");
if (f == NULL) {
@@ -573,12 +537,12 @@ char** App::get_command_line(unsigned int* out_argc) {
uint8_t len[4];
int r = fread(len, sizeof(uint8_t), 4, f);
- Platform::Collections::Vector<Platform::String^> cl;
+ Platform::Collections::Vector<Platform::String ^> cl;
if (r < 4) {
fclose(f);
wprintf(L"Wrong cmdline length.");
- return(fail_cl);
+ return (fail_cl);
}
int argc = READ_LE_4(len);
@@ -590,7 +554,7 @@ char** App::get_command_line(unsigned int* out_argc) {
if (r < 4) {
fclose(f);
wprintf(L"Wrong cmdline param length.");
- return(fail_cl);
+ return (fail_cl);
}
int strlen = READ_LE_4(len);
@@ -598,17 +562,17 @@ char** App::get_command_line(unsigned int* out_argc) {
if (strlen > CMD_MAX_LEN) {
fclose(f);
wprintf(L"Wrong command length.");
- return(fail_cl);
+ return (fail_cl);
}
- char* arg = new char[strlen + 1];
+ char *arg = new char[strlen + 1];
r = fread(arg, sizeof(char), strlen, f);
arg[strlen] = '\0';
if (r == strlen) {
int warg_size = MultiByteToWideChar(CP_UTF8, 0, arg, -1, NULL, 0);
- wchar_t* warg = new wchar_t[warg_size];
+ wchar_t *warg = new wchar_t[warg_size];
MultiByteToWideChar(CP_UTF8, 0, arg, -1, warg, warg_size);
@@ -619,7 +583,7 @@ char** App::get_command_line(unsigned int* out_argc) {
delete[] arg;
fclose(f);
wprintf(L"Error reading command.");
- return(fail_cl);
+ return (fail_cl);
}
}
@@ -628,17 +592,16 @@ char** App::get_command_line(unsigned int* out_argc) {
fclose(f);
- char** ret = new char*[cl.Size + 1];
+ char **ret = new char *[cl.Size + 1];
for (int i = 0; i < cl.Size; i++) {
int arg_size = WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, NULL, 0, NULL, NULL);
- char* arg = new char[arg_size];
+ char *arg = new char[arg_size];
WideCharToMultiByte(CP_UTF8, 0, cl.GetAt(i)->Data(), -1, arg, arg_size, NULL, NULL);
ret[i] = arg;
-
}
ret[cl.Size] = NULL;
*out_argc = cl.Size;
diff --git a/platform/uwp/export/export.cpp b/platform/uwp/export/export.cpp
index 52a22a1942..a9b26056fc 100644
--- a/platform/uwp/export/export.cpp
+++ b/platform/uwp/export/export.cpp
@@ -66,21 +66,21 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*************************************************************************/
#if 0
-#include "version.h"
#include "export.h"
-#include "object.h"
+#include "bind/core_bind.h"
#include "editor/editor_import_export.h"
#include "editor/editor_node.h"
-#include "platform/uwp/logo.h"
-#include "os/file_access.h"
-#include "io/zip.h"
-#include "io/unzip.h"
-#include "io/zip_io.h"
-#include "io/sha256.h"
-#include "io/base64.h"
-#include "bind/core_bind.h"
#include "global_config.h"
+#include "io/base64.h"
#include "io/marshalls.h"
+#include "io/sha256.h"
+#include "io/unzip.h"
+#include "io/zip.h"
+#include "io/zip_io.h"
+#include "object.h"
+#include "os/file_access.h"
+#include "platform/uwp/logo.h"
+#include "version.h"
#include <zlib.h>
@@ -120,14 +120,14 @@ static const char* uwp_device_capabilites[] = {
};
#ifdef OPENSSL_ENABLED
-#include <openssl/bio.h>
#include <openssl/asn1.h>
-#include <openssl/pkcs7.h>
-#include <openssl/pkcs12.h>
-#include <openssl/err.h>
#include <openssl/asn1t.h>
-#include <openssl/x509.h>
+#include <openssl/bio.h>
+#include <openssl/err.h>
#include <openssl/ossl_typ.h>
+#include <openssl/pkcs12.h>
+#include <openssl/pkcs7.h>
+#include <openssl/x509.h>
namespace asn1 {
// https://msdn.microsoft.com/en-us/gg463180.aspx
@@ -2391,4 +2391,3 @@ void register_uwp_exporter() {
EditorImportExport::get_singleton()->add_export_platform(exporter);
#endif
}
-
diff --git a/platform/uwp/gl_context_egl.cpp b/platform/uwp/gl_context_egl.cpp
index c9c03db8a1..6c9efc26b4 100644
--- a/platform/uwp/gl_context_egl.cpp
+++ b/platform/uwp/gl_context_egl.cpp
@@ -62,8 +62,7 @@ void ContextEGL::reset() {
void ContextEGL::swap_buffers() {
- if (eglSwapBuffers(mEglDisplay, mEglSurface) != EGL_TRUE)
- {
+ if (eglSwapBuffers(mEglDisplay, mEglSurface) != EGL_TRUE) {
cleanup();
window = CoreWindow::GetForCurrentThread();
@@ -102,69 +101,61 @@ Error ContextEGL::initialize() {
try {
const EGLint displayAttributes[] =
- {
- /*EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
+ {
+ /*EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
EGL_PLATFORM_ANGLE_MAX_VERSION_MAJOR_ANGLE, 9,
EGL_PLATFORM_ANGLE_MAX_VERSION_MINOR_ANGLE, 3,
EGL_NONE,*/
- // These are the default display attributes, used to request ANGLE's D3D11 renderer.
- // eglInitialize will only succeed with these attributes if the hardware supports D3D11 Feature Level 10_0+.
- EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
-
- // EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices.
- // Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it.
- //EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
-
- // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that enables ANGLE to automatically call
- // the IDXGIDevice3::Trim method on behalf of the application when it gets suspended.
- // Calling IDXGIDevice3::Trim when an application is suspended is a Windows Store application certification requirement.
- EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
- EGL_NONE,
- };
+ // These are the default display attributes, used to request ANGLE's D3D11 renderer.
+ // eglInitialize will only succeed with these attributes if the hardware supports D3D11 Feature Level 10_0+.
+ EGL_PLATFORM_ANGLE_TYPE_ANGLE, EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE,
+
+ // EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER is an optimization that can have large performance benefits on mobile devices.
+ // Its syntax is subject to change, though. Please update your Visual Studio templates if you experience compilation issues with it.
+ //EGL_ANGLE_DISPLAY_ALLOW_RENDER_TO_BACK_BUFFER, EGL_TRUE,
+
+ // EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE is an option that enables ANGLE to automatically call
+ // the IDXGIDevice3::Trim method on behalf of the application when it gets suspended.
+ // Calling IDXGIDevice3::Trim when an application is suspended is a Windows Store application certification requirement.
+ EGL_PLATFORM_ANGLE_ENABLE_AUTOMATIC_TRIM_ANGLE, EGL_TRUE,
+ EGL_NONE,
+ };
PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT"));
- if (!eglGetPlatformDisplayEXT)
- {
+ if (!eglGetPlatformDisplayEXT) {
throw Exception::CreateException(E_FAIL, L"Failed to get function eglGetPlatformDisplayEXT");
}
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, displayAttributes);
- if (display == EGL_NO_DISPLAY)
- {
+ if (display == EGL_NO_DISPLAY) {
throw Exception::CreateException(E_FAIL, L"Failed to get default EGL display");
}
- if (eglInitialize(display, &majorVersion, &minorVersion) == EGL_FALSE)
- {
+ if (eglInitialize(display, &majorVersion, &minorVersion) == EGL_FALSE) {
throw Exception::CreateException(E_FAIL, L"Failed to initialize EGL");
}
- if (eglGetConfigs(display, NULL, 0, &numConfigs) == EGL_FALSE)
- {
+ if (eglGetConfigs(display, NULL, 0, &numConfigs) == EGL_FALSE) {
throw Exception::CreateException(E_FAIL, L"Failed to get EGLConfig count");
}
- if (eglChooseConfig(display, configAttribList, &config, 1, &numConfigs) == EGL_FALSE)
- {
+ if (eglChooseConfig(display, configAttribList, &config, 1, &numConfigs) == EGL_FALSE) {
throw Exception::CreateException(E_FAIL, L"Failed to choose first EGLConfig count");
}
- surface = eglCreateWindowSurface(display, config, reinterpret_cast<IInspectable*>(window), surfaceAttribList);
- if (surface == EGL_NO_SURFACE)
- {
+ surface = eglCreateWindowSurface(display, config, reinterpret_cast<IInspectable *>(window), surfaceAttribList);
+ if (surface == EGL_NO_SURFACE) {
throw Exception::CreateException(E_FAIL, L"Failed to create EGL fullscreen surface");
}
context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs);
- if (context == EGL_NO_CONTEXT)
- {
+ if (context == EGL_NO_CONTEXT) {
throw Exception::CreateException(E_FAIL, L"Failed to create EGL context");
}
- if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE)
- {
+ if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
throw Exception::CreateException(E_FAIL, L"Failed to make fullscreen EGLSurface current");
}
} catch (...) {
@@ -175,38 +166,34 @@ Error ContextEGL::initialize() {
mEglSurface = surface;
mEglContext = context;
- eglQuerySurface(display,surface,EGL_WIDTH,&width);
- eglQuerySurface(display,surface,EGL_HEIGHT,&height);
+ eglQuerySurface(display, surface, EGL_WIDTH, &width);
+ eglQuerySurface(display, surface, EGL_HEIGHT, &height);
return OK;
};
void ContextEGL::cleanup() {
- if (mEglDisplay != EGL_NO_DISPLAY && mEglSurface != EGL_NO_SURFACE)
- {
+ if (mEglDisplay != EGL_NO_DISPLAY && mEglSurface != EGL_NO_SURFACE) {
eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = EGL_NO_SURFACE;
}
- if (mEglDisplay != EGL_NO_DISPLAY && mEglContext != EGL_NO_CONTEXT)
- {
+ if (mEglDisplay != EGL_NO_DISPLAY && mEglContext != EGL_NO_CONTEXT) {
eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = EGL_NO_CONTEXT;
}
- if (mEglDisplay != EGL_NO_DISPLAY)
- {
+ if (mEglDisplay != EGL_NO_DISPLAY) {
eglTerminate(mEglDisplay);
mEglDisplay = EGL_NO_DISPLAY;
}
};
-ContextEGL::ContextEGL(CoreWindow^ p_window) :
- mEglDisplay(EGL_NO_DISPLAY),
- mEglContext(EGL_NO_CONTEXT),
- mEglSurface(EGL_NO_SURFACE)
- {
+ContextEGL::ContextEGL(CoreWindow ^ p_window)
+ : mEglDisplay(EGL_NO_DISPLAY),
+ mEglContext(EGL_NO_CONTEXT),
+ mEglSurface(EGL_NO_SURFACE) {
window = p_window;
};
@@ -215,4 +202,3 @@ ContextEGL::~ContextEGL() {
cleanup();
};
-
diff --git a/platform/uwp/gl_context_egl.h b/platform/uwp/gl_context_egl.h
index 858eaa6d12..c397c1206b 100644
--- a/platform/uwp/gl_context_egl.h
+++ b/platform/uwp/gl_context_egl.h
@@ -31,16 +31,16 @@
#include <wrl.h>
-#include "os/os.h"
#include "EGL/egl.h"
-#include "error_list.h"
#include "drivers/gl_context/context_gl.h"
+#include "error_list.h"
+#include "os/os.h"
using namespace Windows::UI::Core;
class ContextEGL : public ContextGL {
- CoreWindow^ window;
+ CoreWindow ^ window;
EGLDisplay mEglDisplay;
EGLContext mEglContext;
@@ -52,7 +52,6 @@ class ContextEGL : public ContextGL {
bool vsync;
public:
-
virtual void release_current();
virtual void make_current();
@@ -69,10 +68,8 @@ public:
void cleanup();
- ContextEGL(CoreWindow^ p_window);
+ ContextEGL(CoreWindow ^ p_window);
~ContextEGL();
-
};
#endif
-
diff --git a/platform/uwp/joypad_uwp.cpp b/platform/uwp/joypad_uwp.cpp
index 7f0837d7be..dd57ed94ae 100644
--- a/platform/uwp/joypad_uwp.cpp
+++ b/platform/uwp/joypad_uwp.cpp
@@ -35,9 +35,9 @@ using namespace Windows::Foundation;
void JoypadUWP::register_events() {
Gamepad::GamepadAdded +=
- ref new EventHandler<Gamepad^>(this, &JoypadUWP::OnGamepadAdded);
+ ref new EventHandler<Gamepad ^>(this, &JoypadUWP::OnGamepadAdded);
Gamepad::GamepadRemoved +=
- ref new EventHandler<Gamepad^>(this, &JoypadUWP::OnGamepadRemoved);
+ ref new EventHandler<Gamepad ^>(this, &JoypadUWP::OnGamepadRemoved);
}
uint32_t JoypadUWP::process_controllers(uint32_t p_last_id) {
@@ -48,26 +48,26 @@ uint32_t JoypadUWP::process_controllers(uint32_t p_last_id) {
switch (controllers[i].type) {
- case ControllerType::GAMEPAD_CONTROLLER: {
+ case ControllerType::GAMEPAD_CONTROLLER: {
- GamepadReading reading = ((Gamepad^)controllers[i].controller_reference)->GetCurrentReading();
+ GamepadReading reading = ((Gamepad ^)controllers[i].controller_reference)->GetCurrentReading();
- int button_mask = (int)GamepadButtons::Menu;
- for (int j = 0; j < 14; j++) {
+ int button_mask = (int)GamepadButtons::Menu;
+ for (int j = 0; j < 14; j++) {
- p_last_id = input->joy_button(p_last_id, controllers[i].id, j,(int)reading.Buttons & button_mask);
- button_mask *= 2;
- }
+ p_last_id = input->joy_button(p_last_id, controllers[i].id, j, (int)reading.Buttons & button_mask);
+ button_mask *= 2;
+ }
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_0, axis_correct(reading.LeftThumbstickX));
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_1, axis_correct(reading.LeftThumbstickY, true));
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_2, axis_correct(reading.RightThumbstickX));
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_3, axis_correct(reading.RightThumbstickY, true));
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_4, axis_correct(reading.LeftTrigger, false, true));
- p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_5, axis_correct(reading.RightTrigger, false, true));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_0, axis_correct(reading.LeftThumbstickX));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_1, axis_correct(reading.LeftThumbstickY, true));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_2, axis_correct(reading.RightThumbstickX));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_3, axis_correct(reading.RightThumbstickY, true));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_4, axis_correct(reading.LeftTrigger, false, true));
+ p_last_id = input->joy_axis(p_last_id, controllers[i].id, JOY_AXIS_5, axis_correct(reading.RightTrigger, false, true));
- break;
- }
+ break;
+ }
}
}
@@ -80,7 +80,7 @@ JoypadUWP::JoypadUWP() {
controllers[i].id = i;
}
-JoypadUWP::JoypadUWP(InputDefault * p_input) {
+JoypadUWP::JoypadUWP(InputDefault *p_input) {
input = p_input;
diff --git a/platform/uwp/joypad_uwp.h b/platform/uwp/joypad_uwp.h
index 5d81ac44c0..e5a961e70e 100644
--- a/platform/uwp/joypad_uwp.h
+++ b/platform/uwp/joypad_uwp.h
@@ -41,10 +41,9 @@ internal:
/* clang-format on */
JoypadUWP();
- JoypadUWP(InputDefault* p_input);
+ JoypadUWP(InputDefault *p_input);
private:
-
enum {
MAX_CONTROLLERS = 4,
};
@@ -57,7 +56,7 @@ private:
struct ControllerDevice {
- Windows::Gaming::Input::IGameController^ controller_reference;
+ Windows::Gaming::Input::IGameController ^ controller_reference;
int id;
bool connected;
@@ -72,10 +71,10 @@ private:
ControllerDevice controllers[MAX_CONTROLLERS];
- InputDefault* input;
+ InputDefault *input;
- void OnGamepadAdded(Platform::Object^ sender, Windows::Gaming::Input::Gamepad^ value);
- void OnGamepadRemoved(Platform::Object^ sender, Windows::Gaming::Input::Gamepad^ value);
+ void OnGamepadAdded(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ value);
+ void OnGamepadRemoved(Platform::Object ^ sender, Windows::Gaming::Input::Gamepad ^ value);
InputDefault::JoyAxis axis_correct(double p_val, bool p_negate = false, bool p_trigger = false) const;
};
diff --git a/platform/uwp/os_uwp.cpp b/platform/uwp/os_uwp.cpp
index eb62164fd5..19ed2b57a3 100644
--- a/platform/uwp/os_uwp.cpp
+++ b/platform/uwp/os_uwp.cpp
@@ -26,28 +26,28 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "drivers/gles2/rasterizer_gles2.h"
#include "os_uwp.h"
-#include "os/memory_pool_dynamic_static.h"
-#include "thread_uwp.h"
-#include "drivers/windows/semaphore_windows.h"
+#include "drivers/gles2/rasterizer_gles2.h"
+#include "drivers/windows/dir_access_windows.h"
+#include "drivers/windows/file_access_windows.h"
#include "drivers/windows/mutex_windows.h"
+#include "drivers/windows/semaphore_windows.h"
#include "main/main.h"
-#include "drivers/windows/file_access_windows.h"
-#include "drivers/windows/dir_access_windows.h"
-#include "servers/visual/visual_server_raster.h"
+#include "os/memory_pool_dynamic_static.h"
#include "servers/audio_server.h"
+#include "servers/visual/visual_server_raster.h"
+#include "thread_uwp.h"
//#include "servers/visual/visual_server_wrap_mt.h"
-#include "os/memory_pool_dynamic_prealloc.h"
+#include "drivers/unix/ip_unix.h"
#include "global_config.h"
#include "io/marshalls.h"
+#include "os/memory_pool_dynamic_prealloc.h"
#include "platform/windows/packet_peer_udp_winsock.h"
#include "platform/windows/stream_peer_winsock.h"
#include "platform/windows/tcp_server_winsock.h"
-#include "drivers/unix/ip_unix.h"
-#include <wrl.h>
#include <ppltasks.h>
+#include <wrl.h>
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
@@ -63,12 +63,11 @@ using namespace Windows::Devices::Sensors;
using namespace Windows::ApplicationModel::DataTransfer;
using namespace concurrency;
-
int OSUWP::get_video_driver_count() const {
return 1;
}
-const char * OSUWP::get_video_driver_name(int p_driver) const {
+const char *OSUWP::get_video_driver_name(int p_driver) const {
return "GLES2";
}
@@ -91,7 +90,7 @@ void OSUWP::set_window_size(const Size2 p_size) {
new_size.Width = p_size.width;
new_size.Height = p_size.height;
- ApplicationView^ view = ApplicationView::GetForCurrentView();
+ ApplicationView ^ view = ApplicationView::GetForCurrentView();
if (view->TryResizeView(new_size)) {
@@ -102,7 +101,7 @@ void OSUWP::set_window_size(const Size2 p_size) {
void OSUWP::set_window_fullscreen(bool p_enabled) {
- ApplicationView^ view = ApplicationView::GetForCurrentView();
+ ApplicationView ^ view = ApplicationView::GetForCurrentView();
video_mode.fullscreen = view->IsFullScreenMode;
@@ -117,7 +116,6 @@ void OSUWP::set_window_fullscreen(bool p_enabled) {
view->ExitFullScreenMode();
video_mode.fullscreen = false;
-
}
}
@@ -143,20 +141,19 @@ int OSUWP::get_audio_driver_count() const {
return AudioDriverManager::get_driver_count();
}
-const char * OSUWP::get_audio_driver_name(int p_driver) const {
+const char *OSUWP::get_audio_driver_name(int p_driver) const {
- AudioDriver* driver = AudioDriverManager::get_driver(p_driver);
- ERR_FAIL_COND_V( !driver, "" );
+ AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
+ ERR_FAIL_COND_V(!driver, "");
return AudioDriverManager::get_driver(p_driver)->get_name();
}
-static MemoryPoolStatic *mempool_static=NULL;
-static MemoryPoolDynamic *mempool_dynamic=NULL;
+static MemoryPoolStatic *mempool_static = NULL;
+static MemoryPoolDynamic *mempool_dynamic = NULL;
void OSUWP::initialize_core() {
-
- last_button_state=0;
+ last_button_state = 0;
//RedirectIOToConsole();
@@ -181,16 +178,16 @@ void OSUWP::initialize_core() {
mempool_static = new MemoryPoolStaticMalloc;
#if 1
- mempool_dynamic = memnew( MemoryPoolDynamicStatic );
+ mempool_dynamic = memnew(MemoryPoolDynamicStatic);
#else
-#define DYNPOOL_SIZE 4*1024*1024
- void * buffer = malloc( DYNPOOL_SIZE );
- mempool_dynamic = memnew( MemoryPoolDynamicPrealloc(buffer,DYNPOOL_SIZE) );
+#define DYNPOOL_SIZE 4 * 1024 * 1024
+ void *buffer = malloc(DYNPOOL_SIZE);
+ mempool_dynamic = memnew(MemoryPoolDynamicPrealloc(buffer, DYNPOOL_SIZE));
#endif
- // We need to know how often the clock is updated
- if( !QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second) )
+ // We need to know how often the clock is updated
+ if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
ticks_per_second = 1000;
// If timeAtGameStart is 0 then we get the time since
// the start of the computer when we call GetGameTime()
@@ -199,7 +196,7 @@ void OSUWP::initialize_core() {
IP_Unix::make_default();
- cursor_shape=CURSOR_ARROW;
+ cursor_shape = CURSOR_ARROW;
}
bool OSUWP::can_draw() const {
@@ -207,8 +204,7 @@ bool OSUWP::can_draw() const {
return !minimized;
};
-
-void OSUWP::set_gl_context(ContextEGL* p_context) {
+void OSUWP::set_gl_context(ContextEGL *p_context) {
gl_context = p_context;
};
@@ -218,10 +214,10 @@ void OSUWP::screen_size_changed() {
gl_context->reset();
};
-void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OSUWP::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
- main_loop=NULL;
- outside=true;
+ main_loop = NULL;
+ outside = true;
gl_context->initialize();
VideoMode vm;
@@ -229,7 +225,7 @@ void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio
vm.height = gl_context->get_window_height();
vm.resizable = false;
- ApplicationView^ view = ApplicationView::GetForCurrentView();
+ ApplicationView ^ view = ApplicationView::GetForCurrentView();
vm.fullscreen = view->IsFullScreenMode;
view->SetDesiredBoundsMode(ApplicationViewBoundsMode::UseVisible);
@@ -262,48 +258,47 @@ void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio
set_video_mode(vm);
gl_context->make_current();
- rasterizer = memnew( RasterizerGLES2 );
+ rasterizer = memnew(RasterizerGLES2);
- visual_server = memnew( VisualServerRaster(rasterizer) );
- if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {
+ visual_server = memnew(VisualServerRaster(rasterizer));
+ if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
- visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
+ visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
}
//
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
- physics_2d_server = memnew( Physics2DServerSW );
+ physics_2d_server = memnew(Physics2DServerSW);
physics_2d_server->init();
visual_server->init();
- input = memnew( InputDefault );
+ input = memnew(InputDefault);
joypad = ref new JoypadUWP(input);
joypad->register_events();
AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
- if (AudioDriverManager::get_driver(p_audio_driver)->init()!=OK) {
+ if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
ERR_PRINT("Initializing audio failed.");
}
- power_manager = memnew ( PowerWinRT );
+ power_manager = memnew(PowerWinRT);
managed_object->update_clipboard();
- Clipboard::ContentChanged += ref new EventHandler<Platform::Object^>(managed_object, &ManagedType::on_clipboard_changed);
+ Clipboard::ContentChanged += ref new EventHandler<Platform::Object ^>(managed_object, &ManagedType::on_clipboard_changed);
accelerometer = Accelerometer::GetDefault();
if (accelerometer != nullptr) {
// 60 FPS
accelerometer->ReportInterval = (1.0f / 60.0f) * 1000;
accelerometer->ReadingChanged +=
- ref new TypedEventHandler<Accelerometer^, AccelerometerReadingChangedEventArgs^>
- (managed_object, &ManagedType::on_accelerometer_reading_changed);
+ ref new TypedEventHandler<Accelerometer ^, AccelerometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_accelerometer_reading_changed);
}
magnetometer = Magnetometer::GetDefault();
@@ -311,8 +306,7 @@ void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio
// 60 FPS
magnetometer->ReportInterval = (1.0f / 60.0f) * 1000;
magnetometer->ReadingChanged +=
- ref new TypedEventHandler<Magnetometer^, MagnetometerReadingChangedEventArgs^>
- (managed_object, &ManagedType::on_magnetometer_reading_changed);
+ ref new TypedEventHandler<Magnetometer ^, MagnetometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_magnetometer_reading_changed);
}
gyrometer = Gyrometer::GetDefault();
@@ -320,8 +314,7 @@ void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio
// 60 FPS
gyrometer->ReportInterval = (1.0f / 60.0f) * 1000;
gyrometer->ReadingChanged +=
- ref new TypedEventHandler<Gyrometer^, GyrometerReadingChangedEventArgs^>
- (managed_object, &ManagedType::on_gyroscope_reading_changed);
+ ref new TypedEventHandler<Gyrometer ^, GyrometerReadingChangedEventArgs ^>(managed_object, &ManagedType::on_gyroscope_reading_changed);
}
_ensure_data_dir();
@@ -330,14 +323,13 @@ void OSUWP::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio
display_request->RequestActive();
set_keep_screen_on(GLOBAL_DEF("display/keep_screen_on", true));
-
}
-void OSUWP::set_clipboard(const String& p_text) {
+void OSUWP::set_clipboard(const String &p_text) {
- DataPackage^ clip = ref new DataPackage();
+ DataPackage ^ clip = ref new DataPackage();
clip->RequestedOperation = DataPackageOperation::Copy;
- clip->SetText(ref new Platform::String((const wchar_t*)p_text.c_str()));
+ clip->SetText(ref new Platform::String((const wchar_t *)p_text.c_str()));
Clipboard::SetContent(clip);
};
@@ -350,14 +342,13 @@ String OSUWP::get_clipboard() const {
return "";
};
-
void OSUWP::input_event(InputEvent &p_event) {
p_event.ID = ++last_id;
input->parse_input_event(p_event);
- if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index>3) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index > 3) {
//send release for mouse wheel
p_event.mouse_button.pressed = false;
@@ -370,21 +361,21 @@ void OSUWP::delete_main_loop() {
if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
}
-void OSUWP::set_main_loop( MainLoop * p_main_loop ) {
+void OSUWP::set_main_loop(MainLoop *p_main_loop) {
input->set_main_loop(p_main_loop);
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
}
void OSUWP::finalize() {
- if(main_loop)
+ if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
visual_server->finish();
memdelete(visual_server);
@@ -410,60 +401,57 @@ void OSUWP::finalize() {
memdelete(physics_2d_server);
joypad = nullptr;
-
}
void OSUWP::finalize_core() {
if (mempool_dynamic)
- memdelete( mempool_dynamic );
+ memdelete(mempool_dynamic);
delete mempool_static;
-
}
-void OSUWP::vprint(const char* p_format, va_list p_list, bool p_stderr) {
+void OSUWP::vprint(const char *p_format, va_list p_list, bool p_stderr) {
- char buf[16384+1];
- int len = vsnprintf(buf,16384,p_format,p_list);
- if (len<=0)
+ char buf[16384 + 1];
+ int len = vsnprintf(buf, 16384, p_format, p_list);
+ if (len <= 0)
return;
- buf[len]=0;
+ buf[len] = 0;
-
- int wlen = MultiByteToWideChar(CP_UTF8,0,buf,len,NULL,0);
- if (wlen<0)
+ int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, NULL, 0);
+ if (wlen < 0)
return;
- wchar_t *wbuf = (wchar_t*)malloc((len+1)*sizeof(wchar_t));
- MultiByteToWideChar(CP_UTF8,0,buf,len,wbuf,wlen);
- wbuf[wlen]=0;
+ wchar_t *wbuf = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
+ MultiByteToWideChar(CP_UTF8, 0, buf, len, wbuf, wlen);
+ wbuf[wlen] = 0;
if (p_stderr)
- fwprintf(stderr,L"%s",wbuf);
+ fwprintf(stderr, L"%s", wbuf);
else
- wprintf(L"%s",wbuf);
+ wprintf(L"%s", wbuf);
free(wbuf);
fflush(stdout);
};
-void OSUWP::alert(const String& p_alert,const String& p_title) {
+void OSUWP::alert(const String &p_alert, const String &p_title) {
- Platform::String^ alert = ref new Platform::String(p_alert.c_str());
- Platform::String^ title = ref new Platform::String(p_title.c_str());
+ Platform::String ^ alert = ref new Platform::String(p_alert.c_str());
+ Platform::String ^ title = ref new Platform::String(p_title.c_str());
- MessageDialog^ msg = ref new MessageDialog(alert, title);
+ MessageDialog ^ msg = ref new MessageDialog(alert, title);
- UICommand^ close = ref new UICommand("Close", ref new UICommandInvokedHandler(managed_object, &OSUWP::ManagedType::alert_close));
+ UICommand ^ close = ref new UICommand("Close", ref new UICommandInvokedHandler(managed_object, &OSUWP::ManagedType::alert_close));
msg->Commands->Append(close);
msg->DefaultCommandIndex = 0;
-
+
managed_object->alert_close_handle = true;
msg->ShowAsync();
}
-void OSUWP::ManagedType::alert_close(IUICommand^ command) {
+void OSUWP::ManagedType::alert_close(IUICommand ^ command) {
alert_close_handle = false;
}
@@ -475,12 +463,11 @@ void OSUWP::ManagedType::on_clipboard_changed(Platform::Object ^ sender, Platfor
void OSUWP::ManagedType::update_clipboard() {
- DataPackageView^ data = Clipboard::GetContent();
+ DataPackageView ^ data = Clipboard::GetContent();
if (data->Contains(StandardDataFormats::Text)) {
- create_task(data->GetTextAsync()).then(
- [this](Platform::String^ clipboard_content) {
+ create_task(data->GetTextAsync()).then([this](Platform::String ^ clipboard_content) {
this->clipboard = clipboard_content;
});
@@ -488,36 +475,33 @@ void OSUWP::ManagedType::update_clipboard() {
}
void OSUWP::ManagedType::on_accelerometer_reading_changed(Accelerometer ^ sender, AccelerometerReadingChangedEventArgs ^ args) {
-
- AccelerometerReading^ reading = args->Reading;
+
+ AccelerometerReading ^ reading = args->Reading;
os->input->set_accelerometer(Vector3(
- reading->AccelerationX,
- reading->AccelerationY,
- reading->AccelerationZ
- ));
+ reading->AccelerationX,
+ reading->AccelerationY,
+ reading->AccelerationZ));
}
void OSUWP::ManagedType::on_magnetometer_reading_changed(Magnetometer ^ sender, MagnetometerReadingChangedEventArgs ^ args) {
- MagnetometerReading^ reading = args->Reading;
+ MagnetometerReading ^ reading = args->Reading;
os->input->set_magnetometer(Vector3(
- reading->MagneticFieldX,
- reading->MagneticFieldY,
- reading->MagneticFieldZ
- ));
+ reading->MagneticFieldX,
+ reading->MagneticFieldY,
+ reading->MagneticFieldZ));
}
void OSUWP::ManagedType::on_gyroscope_reading_changed(Gyrometer ^ sender, GyrometerReadingChangedEventArgs ^ args) {
- GyrometerReading^ reading = args->Reading;
+ GyrometerReading ^ reading = args->Reading;
os->input->set_magnetometer(Vector3(
- reading->AngularVelocityX,
- reading->AngularVelocityY,
- reading->AngularVelocityZ
- ));
+ reading->AngularVelocityX,
+ reading->AngularVelocityY,
+ reading->AngularVelocityZ));
}
void OSUWP::set_mouse_mode(MouseMode p_mode) {
@@ -529,7 +513,6 @@ void OSUWP::set_mouse_mode(MouseMode p_mode) {
} else {
CoreWindow::GetForCurrentThread()->ReleasePointerCapture();
-
}
if (p_mode == MouseMode::MOUSE_MODE_CAPTURED || p_mode == MouseMode::MOUSE_MODE_HIDDEN) {
@@ -546,13 +529,11 @@ void OSUWP::set_mouse_mode(MouseMode p_mode) {
SetEvent(mouse_mode_changed);
}
-OSUWP::MouseMode OSUWP::get_mouse_mode() const{
+OSUWP::MouseMode OSUWP::get_mouse_mode() const {
return mouse_mode;
}
-
-
Point2 OSUWP::get_mouse_pos() const {
return Point2(old_x, old_y);
@@ -563,11 +544,10 @@ int OSUWP::get_mouse_button_state() const {
return last_button_state;
}
-void OSUWP::set_window_title(const String& p_title) {
-
+void OSUWP::set_window_title(const String &p_title) {
}
-void OSUWP::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
+void OSUWP::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
video_mode = p_video_mode;
}
@@ -575,20 +555,18 @@ OS::VideoMode OSUWP::get_video_mode(int p_screen) const {
return video_mode;
}
-void OSUWP::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
-
-
+void OSUWP::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
}
-void OSUWP::print_error(const char* p_function, const char* p_file, int p_line, const char* p_code, const char* p_rationale, ErrorType p_type) {
+void OSUWP::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
- const char* err_details;
+ const char *err_details;
if (p_rationale && p_rationale[0])
err_details = p_rationale;
else
err_details = p_code;
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR:
print("ERROR: %s: %s\n", p_function, err_details);
print(" At: %s:%i\n", p_file, p_line);
@@ -604,7 +582,6 @@ void OSUWP::print_error(const char* p_function, const char* p_file, int p_line,
}
}
-
String OSUWP::get_name() {
return "UWP";
@@ -619,11 +596,11 @@ OS::Date OSUWP::get_date(bool utc) const {
GetLocalTime(&systemtime);
Date date;
- date.day=systemtime.wDay;
- date.month=Month(systemtime.wMonth);
- date.weekday=Weekday(systemtime.wDayOfWeek);
- date.year=systemtime.wYear;
- date.dst=false;
+ date.day = systemtime.wDay;
+ date.month = Month(systemtime.wMonth);
+ date.weekday = Weekday(systemtime.wDayOfWeek);
+ date.year = systemtime.wYear;
+ date.dst = false;
return date;
}
OS::Time OSUWP::get_time(bool utc) const {
@@ -635,9 +612,9 @@ OS::Time OSUWP::get_time(bool utc) const {
GetLocalTime(&systemtime);
Time time;
- time.hour=systemtime.wHour;
- time.min=systemtime.wMinute;
- time.sec=systemtime.wSecond;
+ time.hour = systemtime.wHour;
+ time.min = systemtime.wMinute;
+ time.sec = systemtime.wSecond;
return time;
}
@@ -677,7 +654,7 @@ uint64_t OSUWP::get_unix_time() const {
FILETIME fep;
SystemTimeToFileTime(&ep, &fep);
- return (*(uint64_t*)&ft - *(uint64_t*)&fep) / 10000000;
+ return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
};
void OSUWP::delay_usec(uint32_t p_usec) const {
@@ -686,7 +663,6 @@ void OSUWP::delay_usec(uint32_t p_usec) const {
// no Sleep()
WaitForSingleObjectEx(GetCurrentThread(), msec, false);
-
}
uint64_t OSUWP::get_ticks_usec() const {
@@ -702,15 +678,13 @@ uint64_t OSUWP::get_ticks_usec() const {
return time;
}
-
void OSUWP::process_events() {
last_id = joypad->process_controllers(last_id);
process_key_events();
}
-void OSUWP::process_key_events()
-{
+void OSUWP::process_key_events() {
for (int i = 0; i < key_event_pos; i++) {
@@ -725,13 +699,11 @@ void OSUWP::process_key_events()
iev.key.pressed = kev.pressed;
input_event(iev);
-
}
key_event_pos = 0;
}
-void OSUWP::queue_key_event(KeyEvent & p_event)
-{
+void OSUWP::queue_key_event(KeyEvent &p_event) {
// This merges Char events with the previous Key event, so
// the unicode can be retrieved without sending duplicate events.
if (p_event.type == KeyEvent::MessageType::CHAR_EVENT_MESSAGE && key_event_pos > 0) {
@@ -780,17 +752,17 @@ void OSUWP::set_cursor_shape(CursorShape p_shape) {
cursor_shape = p_shape;
}
-Error OSUWP::execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id,String* r_pipe,int *r_exitcode) {
+Error OSUWP::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode) {
return FAILED;
};
-Error OSUWP::kill(const ProcessID& p_pid) {
+Error OSUWP::kill(const ProcessID &p_pid) {
return FAILED;
};
-Error OSUWP::set_cwd(const String& p_cwd) {
+Error OSUWP::set_cwd(const String &p_cwd) {
return FAILED;
}
@@ -800,17 +772,15 @@ String OSUWP::get_executable_path() const {
return "";
}
-void OSUWP::set_icon(const Image& p_icon) {
-
+void OSUWP::set_icon(const Image &p_icon) {
}
-
-bool OSUWP::has_environment(const String& p_var) const {
+bool OSUWP::has_environment(const String &p_var) const {
return false;
};
-String OSUWP::get_environment(const String& p_var) const {
+String OSUWP::get_environment(const String &p_var) const {
return "";
};
@@ -820,9 +790,7 @@ String OSUWP::get_stdin_string(bool p_block) {
return String();
}
-
void OSUWP::move_window_to_foreground() {
-
}
Error OSUWP::shell_open(String p_uri) {
@@ -830,13 +798,12 @@ Error OSUWP::shell_open(String p_uri) {
return FAILED;
}
-
String OSUWP::get_locale() const {
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP // this should work on phone 8.1, but it doesn't
return "en";
#else
- Platform::String ^language = Windows::Globalization::Language::CurrentInputMethodLanguageTag;
+ Platform::String ^ language = Windows::Globalization::Language::CurrentInputMethodLanguageTag;
return String(language->Data()).replace("-", "_");
#endif
}
@@ -858,7 +825,7 @@ void OSUWP::swap_buffers() {
bool OSUWP::has_touchscreen_ui_hint() const {
- TouchCapabilities^ tc = ref new TouchCapabilities();
+ TouchCapabilities ^ tc = ref new TouchCapabilities();
return tc->TouchPresent != 0 || UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
}
@@ -867,19 +834,18 @@ bool OSUWP::has_virtual_keyboard() const {
return UIViewSettings::GetForCurrentView()->UserInteractionMode == UserInteractionMode::Touch;
}
-void OSUWP::show_virtual_keyboard(const String & p_existing_text, const Rect2 & p_screen_rect) {
+void OSUWP::show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect) {
- InputPane^ pane = InputPane::GetForCurrentView();
+ InputPane ^ pane = InputPane::GetForCurrentView();
pane->TryShow();
}
void OSUWP::hide_virtual_keyboard() {
- InputPane^ pane = InputPane::GetForCurrentView();
+ InputPane ^ pane = InputPane::GetForCurrentView();
pane->TryHide();
}
-
void OSUWP::run() {
if (!main_loop)
@@ -887,35 +853,31 @@ void OSUWP::run() {
main_loop->init();
- uint64_t last_ticks=get_ticks_usec();
+ uint64_t last_ticks = get_ticks_usec();
- int frames=0;
- uint64_t frame=0;
+ int frames = 0;
+ uint64_t frame = 0;
while (!force_quit) {
CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
if (managed_object->alert_close_handle) continue;
process_events(); // get rid of pending events
- if (Main::iteration()==true)
+ if (Main::iteration() == true)
break;
};
main_loop->finish();
-
}
-
-
MainLoop *OSUWP::get_main_loop() const {
return main_loop;
}
-
String OSUWP::get_data_dir() const {
- Windows::Storage::StorageFolder ^data_folder = Windows::Storage::ApplicationData::Current->LocalFolder;
+ Windows::Storage::StorageFolder ^ data_folder = Windows::Storage::ApplicationData::Current->LocalFolder;
return String(data_folder->Path->Data()).replace("\\", "/");
}
@@ -932,24 +894,23 @@ int OSWinrt::get_power_percent_left() {
return power_manager->get_power_percent_left();
}
-
OSUWP::OSUWP() {
- key_event_pos=0;
- force_quit=false;
- alt_mem=false;
- gr_mem=false;
- shift_mem=false;
- control_mem=false;
- meta_mem=false;
+ key_event_pos = 0;
+ force_quit = false;
+ alt_mem = false;
+ gr_mem = false;
+ shift_mem = false;
+ control_mem = false;
+ meta_mem = false;
minimized = false;
- pressrc=0;
- old_invalid=true;
- last_id=0;
- mouse_mode=MOUSE_MODE_VISIBLE;
+ pressrc = 0;
+ old_invalid = true;
+ last_id = 0;
+ mouse_mode = MOUSE_MODE_VISIBLE;
#ifdef STDOUT_FILE
- stdo=fopen("stdout.txt","wb");
+ stdo = fopen("stdout.txt", "wb");
#endif
gl_context = NULL;
@@ -964,12 +925,8 @@ OSUWP::OSUWP() {
AudioDriverManager::add_driver(&audio_driver);
}
-
-OSUWP::~OSUWP()
-{
+OSUWP::~OSUWP() {
#ifdef STDOUT_FILE
fclose(stdo);
#endif
}
-
-
diff --git a/platform/uwp/os_uwp.h b/platform/uwp/os_uwp.h
index 72cc8a7854..ebbb8af39c 100644
--- a/platform/uwp/os_uwp.h
+++ b/platform/uwp/os_uwp.h
@@ -29,26 +29,25 @@
#ifndef OSUWP_H
#define OSUWP_H
-#include "os/input.h"
-#include "os/os.h"
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
-#include "servers/physics/physics_server_sw.h"
-#include "servers/audio_server.h"
-#include "servers/physics_2d/physics_2d_server_sw.h"
-#include "drivers/xaudio2/audio_driver_xaudio2.h"
-#include "gl_context_egl.h"
#include "core/math/math_2d.h"
#include "core/ustring.h"
-#include "main/input_default.h"
+#include "drivers/xaudio2/audio_driver_xaudio2.h"
+#include "gl_context_egl.h"
#include "joypad_uwp.h"
+#include "main/input_default.h"
+#include "os/input.h"
+#include "os/os.h"
#include "power_winrt.h"
+#include "servers/audio_server.h"
+#include "servers/physics/physics_server_sw.h"
+#include "servers/physics_2d/physics_2d_server_sw.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
-#include <windows.h>
-#include <io.h>
#include <fcntl.h>
+#include <io.h>
#include <stdio.h>
-
+#include <windows.h>
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -56,11 +55,9 @@
class OSUWP : public OS {
public:
-
struct KeyEvent {
- enum MessageType
- {
+ enum MessageType {
KEY_EVENT_MESSAGE,
CHAR_EVENT_MESSAGE
};
@@ -72,16 +69,14 @@ public:
unsigned int unicode;
bool echo;
CorePhysicalKeyStatus status;
-
};
private:
-
enum {
JOYPADS_MAX = 8,
JOY_AXIS_COUNT = 6,
MAX_JOY_AXIS = 32768, // I've no idea
- KEY_EVENT_BUFFER_SIZE=512
+ KEY_EVENT_BUFFER_SIZE = 512
};
FILE *stdo;
@@ -89,14 +84,13 @@ private:
KeyEvent key_event_buffer[KEY_EVENT_BUFFER_SIZE];
int key_event_pos;
-
uint64_t ticks_start;
uint64_t ticks_per_second;
bool minimized;
bool old_invalid;
bool outside;
- int old_x,old_y;
+ int old_x, old_y;
Point2i center;
unsigned int last_id;
VisualServer *visual_server;
@@ -105,7 +99,7 @@ private:
Physics2DServer *physics_2d_server;
int pressrc;
- ContextEGL* gl_context;
+ ContextEGL *gl_context;
VideoMode video_mode;
@@ -128,52 +122,52 @@ private:
InputDefault *input;
- JoypadUWP^ joypad;
+ JoypadUWP ^ joypad;
- Windows::System::Display::DisplayRequest^ display_request;
+ Windows::System::Display::DisplayRequest ^ display_request;
void _post_dpad(DWORD p_dpad, int p_device, bool p_pressed);
- void _drag_event(int idx,UINT uMsg, WPARAM wParam, LPARAM lParam);
- void _touch_event(int idx, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ void _drag_event(int idx, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ void _touch_event(int idx, UINT uMsg, WPARAM wParam, LPARAM lParam);
ref class ManagedType {
public:
property bool alert_close_handle;
- property Platform::String^ clipboard;
- void alert_close(Windows::UI::Popups::IUICommand^ command);
- void on_clipboard_changed(Platform::Object^ sender, Platform::Object^ ev);
+ property Platform::String ^ clipboard;
+ void alert_close(Windows::UI::Popups::IUICommand ^ command);
+ void on_clipboard_changed(Platform::Object ^ sender, Platform::Object ^ ev);
void update_clipboard();
- void on_accelerometer_reading_changed(Windows::Devices::Sensors::Accelerometer^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs^ args);
- void on_magnetometer_reading_changed(Windows::Devices::Sensors::Magnetometer^ sender, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs^ args);
- void on_gyroscope_reading_changed(Windows::Devices::Sensors::Gyrometer^ sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs^ args);
+ void on_accelerometer_reading_changed(Windows::Devices::Sensors::Accelerometer ^ sender, Windows::Devices::Sensors::AccelerometerReadingChangedEventArgs ^ args);
+ void on_magnetometer_reading_changed(Windows::Devices::Sensors::Magnetometer ^ sender, Windows::Devices::Sensors::MagnetometerReadingChangedEventArgs ^ args);
+ void on_gyroscope_reading_changed(Windows::Devices::Sensors::Gyrometer ^ sender, Windows::Devices::Sensors::GyrometerReadingChangedEventArgs ^ args);
- /** clang-format breaks this, it does not understand this token. */
- /* clang-format off */
+ /** clang-format breaks this, it does not understand this token. */
+ /* clang-format off */
internal:
ManagedType() { alert_close_handle = false; }
property OSUWP* os;
- /* clang-format on */
+ /* clang-format on */
};
- ManagedType^ managed_object;
- Windows::Devices::Sensors::Accelerometer^ accelerometer;
- Windows::Devices::Sensors::Magnetometer^ magnetometer;
- Windows::Devices::Sensors::Gyrometer^ gyrometer;
+ ManagedType ^ managed_object;
+ Windows::Devices::Sensors::Accelerometer ^ accelerometer;
+ Windows::Devices::Sensors::Magnetometer ^ magnetometer;
+ Windows::Devices::Sensors::Gyrometer ^ gyrometer;
// functions used by main to initialize/deintialize the OS
protected:
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
virtual void finalize();
@@ -184,14 +178,13 @@ protected:
void process_key_events();
public:
-
// Event to send to the app wrapper
HANDLE mouse_mode_changed;
- void print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type);
+ void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type);
- virtual void vprint(const char *p_format, va_list p_list, bool p_stderr=false);
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
+ virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false);
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
String get_stdin_string(bool p_block);
void set_mouse_mode(MouseMode p_mode);
@@ -199,11 +192,11 @@ public:
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual Size2 get_window_size() const;
virtual void set_window_size(const Size2 p_size);
virtual void set_window_fullscreen(bool p_enabled);
@@ -220,22 +213,22 @@ public:
virtual uint64_t get_unix_time() const;
virtual bool can_draw() const;
- virtual Error set_cwd(const String& p_cwd);
+ virtual Error set_cwd(const String &p_cwd);
virtual void delay_usec(uint32_t p_usec) const;
virtual uint64_t get_ticks_usec() const;
- virtual Error execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id=NULL,String* r_pipe=NULL,int *r_exitcode=NULL);
- virtual Error kill(const ProcessID& p_pid);
+ virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL);
+ virtual Error kill(const ProcessID &p_pid);
- virtual bool has_environment(const String& p_var) const;
- virtual String get_environment(const String& p_var) const;
+ virtual bool has_environment(const String &p_var) const;
+ virtual String get_environment(const String &p_var) const;
- virtual void set_clipboard(const String& p_text);
+ virtual void set_clipboard(const String &p_text);
virtual String get_clipboard() const;
void set_cursor_shape(CursorShape p_shape);
- void set_icon(const Image& p_icon);
+ void set_icon(const Image &p_icon);
virtual String get_executable_path() const;
@@ -244,7 +237,7 @@ public:
virtual void move_window_to_foreground();
virtual String get_data_dir() const;
- void set_gl_context(ContextEGL* p_context);
+ void set_gl_context(ContextEGL *p_context);
void screen_size_changed();
virtual void release_rendering_thread();
@@ -254,7 +247,7 @@ public:
virtual bool has_touchscreen_ui_hint() const;
virtual bool has_virtual_keyboard() const;
- virtual void show_virtual_keyboard(const String& p_existing_text, const Rect2& p_screen_rect = Rect2());
+ virtual void show_virtual_keyboard(const String &p_existing_text, const Rect2 &p_screen_rect = Rect2());
virtual void hide_virtual_keyboard();
virtual Error shell_open(String p_uri);
@@ -264,7 +257,7 @@ public:
virtual bool get_swap_ok_cancel() { return true; }
void input_event(InputEvent &p_event);
-
+
virtual PowerState get_power_state();
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
@@ -273,7 +266,6 @@ public:
OSUWP();
~OSUWP();
-
};
#endif
diff --git a/platform/uwp/thread_uwp.cpp b/platform/uwp/thread_uwp.cpp
index 4008a1eeb0..ff079be375 100644
--- a/platform/uwp/thread_uwp.cpp
+++ b/platform/uwp/thread_uwp.cpp
@@ -30,10 +30,9 @@
#include "os/memory.h"
-Thread* ThreadUWP::create_func_uwp(ThreadCreateCallback p_callback,void *p_user,const Settings&) {
-
- ThreadUWP* thread = memnew(ThreadUWP);
+Thread *ThreadUWP::create_func_uwp(ThreadCreateCallback p_callback, void *p_user, const Settings &) {
+ ThreadUWP *thread = memnew(ThreadUWP);
std::thread new_thread(p_callback, p_user);
std::swap(thread->thread, new_thread);
@@ -46,13 +45,12 @@ Thread::ID ThreadUWP::get_thread_ID_func_uwp() {
return std::hash<std::thread::id>()(std::this_thread::get_id());
};
-void ThreadUWP::wait_to_finish_func_uwp(Thread* p_thread) {
+void ThreadUWP::wait_to_finish_func_uwp(Thread *p_thread) {
- ThreadUWP *tp=static_cast<ThreadUWP*>(p_thread);
+ ThreadUWP *tp = static_cast<ThreadUWP *>(p_thread);
tp->thread.join();
};
-
Thread::ID ThreadUWP::get_ID() const {
return std::hash<std::thread::id>()(thread.get_id());
@@ -64,11 +62,10 @@ void ThreadUWP::make_default() {
wait_to_finish_func = wait_to_finish_func_uwp;
};
-ThreadUWP::ThreadUWP() {
+ThreadUWP::ThreadUWP(){
};
-ThreadUWP::~ThreadUWP() {
+ThreadUWP::~ThreadUWP(){
};
-
diff --git a/platform/uwp/thread_uwp.h b/platform/uwp/thread_uwp.h
index 06c19c0139..b4e67c8b5c 100644
--- a/platform/uwp/thread_uwp.h
+++ b/platform/uwp/thread_uwp.h
@@ -39,25 +39,20 @@ class ThreadUWP : public Thread {
std::thread thread;
- static Thread* create_func_uwp(ThreadCreateCallback p_callback,void *,const Settings&);
+ static Thread *create_func_uwp(ThreadCreateCallback p_callback, void *, const Settings &);
static ID get_thread_ID_func_uwp();
- static void wait_to_finish_func_uwp(Thread* p_thread);
+ static void wait_to_finish_func_uwp(Thread *p_thread);
ThreadUWP();
-public:
-
+public:
virtual ID get_ID() const;
static void make_default();
-
~ThreadUWP();
-
};
-
#endif
#endif
-
diff --git a/platform/windows/context_gl_win.cpp b/platform/windows/context_gl_win.cpp
index 7a81dfef77..d737502bf5 100644
--- a/platform/windows/context_gl_win.cpp
+++ b/platform/windows/context_gl_win.cpp
@@ -45,25 +45,21 @@
//#include "drivers/opengl/glwrapper.h"
//#include "ctxgl_procaddr.h"
-#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
-#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
-#define WGL_CONTEXT_FLAGS_ARB 0x2094
+#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define WGL_CONTEXT_FLAGS_ARB 0x2094
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
-typedef HGLRC (APIENTRY* PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*);
-
+typedef HGLRC(APIENTRY *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *);
void ContextGL_Win::release_current() {
-
- wglMakeCurrent(hDC,NULL);
-
+ wglMakeCurrent(hDC, NULL);
}
-
void ContextGL_Win::make_current() {
- wglMakeCurrent(hDC,hRC);
+ wglMakeCurrent(hDC, hRC);
}
int ContextGL_Win::get_window_width() {
@@ -98,10 +94,9 @@ static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) {
void ContextGL_Win::set_use_vsync(bool p_use) {
if (wglSwapIntervalEXT) {
- wglSwapIntervalEXT(p_use?1:0);
+ wglSwapIntervalEXT(p_use ? 1 : 0);
}
- use_vsync=p_use;
-
+ use_vsync = p_use;
}
bool ContextGL_Win::is_using_vsync() const {
@@ -109,112 +104,109 @@ bool ContextGL_Win::is_using_vsync() const {
return use_vsync;
}
-#define _WGL_CONTEXT_DEBUG_BIT_ARB 0x0001
+#define _WGL_CONTEXT_DEBUG_BIT_ARB 0x0001
Error ContextGL_Win::initialize() {
- static PIXELFORMATDESCRIPTOR pfd= {
- sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
+ static PIXELFORMATDESCRIPTOR pfd = {
+ sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1,
- PFD_DRAW_TO_WINDOW | // Format Must Support Window
- PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
- PFD_DOUBLEBUFFER,
+ PFD_DRAW_TO_WINDOW | // Format Must Support Window
+ PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
+ PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
- 0, 0, 0, 0, 0, 0, // Color Bits Ignored
- 0,// No Alpha Buffer
- 0,// Shift Bit Ignored
- 0,// No Accumulation Buffer
- 0, 0, 0, 0,// Accumulation Bits Ignored
- 24,// 24Bit Z-Buffer (Depth Buffer)
- 0,// No Stencil Buffer
- 0,// No Auxiliary Buffer
+ 0, 0, 0, 0, 0, 0, // Color Bits Ignored
+ 0, // No Alpha Buffer
+ 0, // Shift Bit Ignored
+ 0, // No Accumulation Buffer
+ 0, 0, 0, 0, // Accumulation Bits Ignored
+ 24, // 24Bit Z-Buffer (Depth Buffer)
+ 0, // No Stencil Buffer
+ 0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
- 0,// Reserved
- 0, 0, 0 // Layer Masks Ignored
+ 0, // Reserved
+ 0, 0, 0 // Layer Masks Ignored
};
- if (!(hDC=GetDC(hWnd))) {
- MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return FALSE
+ if (!(hDC = GetDC(hWnd))) {
+ MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return FALSE
}
- if (!(pixel_format=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
+ if (!(pixel_format = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
{
- MessageBox(NULL,"Can't Find A Suitable pixel_format.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return FALSE
+ MessageBox(NULL, "Can't Find A Suitable pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return FALSE
}
- if(!SetPixelFormat(hDC,pixel_format,&pfd)) // Are We Able To Set The Pixel Format?
+ if (!SetPixelFormat(hDC, pixel_format, &pfd)) // Are We Able To Set The Pixel Format?
{
- MessageBox(NULL,"Can't Set The pixel_format.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return FALSE
+ MessageBox(NULL, "Can't Set The pixel_format.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return FALSE
}
- if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
+ if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
- MessageBox(NULL,"Can't Create A Temporary GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return FALSE
+ MessageBox(NULL, "Can't Create A Temporary GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return FALSE
}
- wglMakeCurrent(hDC,hRC);
+ wglMakeCurrent(hDC, hRC);
if (opengl_3_context) {
int attribs[] = {
- WGL_CONTEXT_MAJOR_VERSION_ARB, 3,//we want a 3.3 context
- WGL_CONTEXT_MINOR_VERSION_ARB, 3,
- //and it shall be forward compatible so that we can only use up to date functionality
- WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB|_WGL_CONTEXT_DEBUG_BIT_ARB,
- 0}; //zero indicates the end of the array
+ WGL_CONTEXT_MAJOR_VERSION_ARB, 3, //we want a 3.3 context
+ WGL_CONTEXT_MINOR_VERSION_ARB, 3,
+ //and it shall be forward compatible so that we can only use up to date functionality
+ WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | _WGL_CONTEXT_DEBUG_BIT_ARB,
+ 0
+ }; //zero indicates the end of the array
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; //pointer to the method
- wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB");
+ wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
- if(wglCreateContextAttribsARB == NULL) //OpenGL 3.0 is not supported
+ if (wglCreateContextAttribsARB == NULL) //OpenGL 3.0 is not supported
{
- MessageBox(NULL,"Cannot get Proc Adress for CreateContextAttribs", "ERROR",MB_OK|MB_ICONEXCLAMATION);
+ MessageBox(NULL, "Cannot get Proc Adress for CreateContextAttribs", "ERROR", MB_OK | MB_ICONEXCLAMATION);
wglDeleteContext(hRC);
return ERR_CANT_CREATE;
}
HGLRC new_hRC;
- if (!(new_hRC=wglCreateContextAttribsARB(hDC,0, attribs)))
- {
+ if (!(new_hRC = wglCreateContextAttribsARB(hDC, 0, attribs))) {
wglDeleteContext(hRC);
- MessageBox(NULL,"Can't Create An OpenGL 3.3 Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return false
+ MessageBox(NULL, "Can't Create An OpenGL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return false
}
- wglMakeCurrent(hDC,NULL);
+ wglMakeCurrent(hDC, NULL);
wglDeleteContext(hRC);
- hRC=new_hRC;
+ hRC = new_hRC;
- if (!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
+ if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
{
- MessageBox(NULL,"Can't Activate The GL 3.3 Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return ERR_CANT_CREATE; // Return FALSE
+ MessageBox(NULL, "Can't Activate The GL 3.3 Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return ERR_CANT_CREATE; // Return FALSE
}
printf("Activated GL 3.3 context");
}
- wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress ("wglSwapIntervalEXT");
+ wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
//glWrapperInit(wrapper_get_proc_address);
return OK;
}
-ContextGL_Win::ContextGL_Win(HWND hwnd,bool p_opengl_3_context) {
+ContextGL_Win::ContextGL_Win(HWND hwnd, bool p_opengl_3_context) {
- opengl_3_context=p_opengl_3_context;
- hWnd=hwnd;
- use_vsync=false;
+ opengl_3_context = p_opengl_3_context;
+ hWnd = hwnd;
+ use_vsync = false;
}
ContextGL_Win::~ContextGL_Win() {
-
-
}
-
#endif
diff --git a/platform/windows/context_gl_win.h b/platform/windows/context_gl_win.h
index 96b54c6c14..383197ba7f 100644
--- a/platform/windows/context_gl_win.h
+++ b/platform/windows/context_gl_win.h
@@ -42,14 +42,13 @@
#ifndef CONTEXT_GL_WIN_H
#define CONTEXT_GL_WIN_H
-
-#include "os/os.h"
#include "drivers/gl_context/context_gl.h"
#include "error_list.h"
+#include "os/os.h"
#include <windows.h>
-typedef bool (APIENTRY *PFNWGLSWAPINTERVALEXTPROC) (int interval);
+typedef bool(APIENTRY *PFNWGLSWAPINTERVALEXTPROC)(int interval);
class ContextGL_Win : public ContextGL {
@@ -60,11 +59,9 @@ class ContextGL_Win : public ContextGL {
bool opengl_3_context;
bool use_vsync;
-
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT;
-public:
-
+public:
virtual void release_current();
virtual void make_current();
@@ -78,9 +75,8 @@ public:
virtual void set_use_vsync(bool p_use);
virtual bool is_using_vsync() const;
- ContextGL_Win(HWND hwnd,bool p_opengl_3_context);
+ ContextGL_Win(HWND hwnd, bool p_opengl_3_context);
~ContextGL_Win();
-
};
#endif
diff --git a/platform/windows/ctxgl_procaddr.cpp b/platform/windows/ctxgl_procaddr.cpp
index bc8611dce4..79c6f219f3 100644
--- a/platform/windows/ctxgl_procaddr.cpp
+++ b/platform/windows/ctxgl_procaddr.cpp
@@ -31,7 +31,7 @@
#include <GL/gl.h>
#include <stdio.h>
-static PROC _gl_procs[]={
+static PROC _gl_procs[] = {
(PROC)glCullFace,
(PROC)glFrontFace,
(PROC)glHint,
@@ -99,7 +99,7 @@ static PROC _gl_procs[]={
0
};
-static const char* _gl_proc_names[]={
+static const char *_gl_proc_names[] = {
"glCullFace",
"glFrontFace",
"glHint",
@@ -167,15 +167,15 @@ static const char* _gl_proc_names[]={
0
};
-PROC get_gl_proc_address(const char* p_address) {
+PROC get_gl_proc_address(const char *p_address) {
- PROC proc = wglGetProcAddress((const CHAR*)p_address);
+ PROC proc = wglGetProcAddress((const CHAR *)p_address);
if (!proc) {
- int i=0;
- while(_gl_procs[i]) {
+ int i = 0;
+ while (_gl_procs[i]) {
- if (strcmp(p_address,_gl_proc_names[i])==0) {
+ if (strcmp(p_address, _gl_proc_names[i]) == 0) {
return _gl_procs[i];
}
i++;
diff --git a/platform/windows/ctxgl_procaddr.h b/platform/windows/ctxgl_procaddr.h
index 72f39e71ac..da17fbcbbe 100644
--- a/platform/windows/ctxgl_procaddr.h
+++ b/platform/windows/ctxgl_procaddr.h
@@ -32,7 +32,6 @@
#ifdef OPENGL_ENABLED
#include <windows.h>
-
-PROC get_gl_proc_address(const char* p_address);
+PROC get_gl_proc_address(const char *p_address);
#endif
#endif // CTXGL_PROCADDR_H
diff --git a/platform/windows/export/export.cpp b/platform/windows/export/export.cpp
index 44c0acdb2e..bb51474a8c 100644
--- a/platform/windows/export/export.cpp
+++ b/platform/windows/export/export.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "export.h"
-#include "platform/windows/logo.h"
#include "editor/editor_export.h"
+#include "platform/windows/logo.h"
void register_windows_exporter() {
@@ -51,4 +51,3 @@ void register_windows_exporter() {
#endif
}
-
diff --git a/platform/windows/godot_win.cpp b/platform/windows/godot_win.cpp
index 5260f7f641..f8f5fe8231 100644
--- a/platform/windows/godot_win.cpp
+++ b/platform/windows/godot_win.cpp
@@ -26,127 +26,123 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "os_windows.h"
#include "main/main.h"
-#include <stdio.h>
+#include "os_windows.h"
#include <locale.h>
+#include <stdio.h>
+
+PCHAR *
+CommandLineToArgvA(
+ PCHAR CmdLine,
+ int *_argc) {
+ PCHAR *argv;
+ PCHAR _argv;
+ ULONG len;
+ ULONG argc;
+ CHAR a;
+ ULONG i, j;
+
+ BOOLEAN in_QM;
+ BOOLEAN in_TEXT;
+ BOOLEAN in_SPACE;
+
+ len = strlen(CmdLine);
+ i = ((len + 2) / 2) * sizeof(PVOID) + sizeof(PVOID);
+
+ argv = (PCHAR *)GlobalAlloc(GMEM_FIXED,
+ i + (len + 2) * sizeof(CHAR));
+
+ _argv = (PCHAR)(((PUCHAR)argv) + i);
+
+ argc = 0;
+ argv[argc] = _argv;
+ in_QM = FALSE;
+ in_TEXT = FALSE;
+ in_SPACE = TRUE;
+ i = 0;
+ j = 0;
+
+ while ((a = CmdLine[i])) {
+ if (in_QM) {
+ if (a == '\"') {
+ in_QM = FALSE;
+ } else {
+ _argv[j] = a;
+ j++;
+ }
+ } else {
+ switch (a) {
+ case '\"':
+ in_QM = TRUE;
+ in_TEXT = TRUE;
+ if (in_SPACE) {
+ argv[argc] = _argv + j;
+ argc++;
+ }
+ in_SPACE = FALSE;
+ break;
+ case ' ':
+ case '\t':
+ case '\n':
+ case '\r':
+ if (in_TEXT) {
+ _argv[j] = '\0';
+ j++;
+ }
+ in_TEXT = FALSE;
+ in_SPACE = TRUE;
+ break;
+ default:
+ in_TEXT = TRUE;
+ if (in_SPACE) {
+ argv[argc] = _argv + j;
+ argc++;
+ }
+ _argv[j] = a;
+ j++;
+ in_SPACE = FALSE;
+ break;
+ }
+ }
+ i++;
+ }
+ _argv[j] = '\0';
+ argv[argc] = NULL;
+
+ (*_argc) = argc;
+ return argv;
+}
-PCHAR*
- CommandLineToArgvA(
- PCHAR CmdLine,
- int* _argc
- )
- {
- PCHAR* argv;
- PCHAR _argv;
- ULONG len;
- ULONG argc;
- CHAR a;
- ULONG i, j;
-
- BOOLEAN in_QM;
- BOOLEAN in_TEXT;
- BOOLEAN in_SPACE;
-
- len = strlen(CmdLine);
- i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);
-
- argv = (PCHAR*)GlobalAlloc(GMEM_FIXED,
- i + (len+2)*sizeof(CHAR));
-
- _argv = (PCHAR)(((PUCHAR)argv)+i);
-
- argc = 0;
- argv[argc] = _argv;
- in_QM = FALSE;
- in_TEXT = FALSE;
- in_SPACE = TRUE;
- i = 0;
- j = 0;
-
- while( (a = CmdLine[i]) ) {
- if(in_QM) {
- if(a == '\"') {
- in_QM = FALSE;
- } else {
- _argv[j] = a;
- j++;
- }
- } else {
- switch(a) {
- case '\"':
- in_QM = TRUE;
- in_TEXT = TRUE;
- if(in_SPACE) {
- argv[argc] = _argv+j;
- argc++;
- }
- in_SPACE = FALSE;
- break;
- case ' ':
- case '\t':
- case '\n':
- case '\r':
- if(in_TEXT) {
- _argv[j] = '\0';
- j++;
- }
- in_TEXT = FALSE;
- in_SPACE = TRUE;
- break;
- default:
- in_TEXT = TRUE;
- if(in_SPACE) {
- argv[argc] = _argv+j;
- argc++;
- }
- _argv[j] = a;
- j++;
- in_SPACE = FALSE;
- break;
- }
- }
- i++;
- }
- _argv[j] = '\0';
- argv[argc] = NULL;
-
- (*_argc) = argc;
- return argv;
- }
-
-char* wc_to_utf8(const wchar_t* wc) {
- int ulen = WideCharToMultiByte(CP_UTF8,0,wc,-1,NULL,0,NULL,NULL);
- char * ubuf = new char[ulen + 1];
- WideCharToMultiByte(CP_UTF8,0,wc,-1,ubuf,ulen,NULL,NULL);
+char *wc_to_utf8(const wchar_t *wc) {
+ int ulen = WideCharToMultiByte(CP_UTF8, 0, wc, -1, NULL, 0, NULL, NULL);
+ char *ubuf = new char[ulen + 1];
+ WideCharToMultiByte(CP_UTF8, 0, wc, -1, ubuf, ulen, NULL, NULL);
ubuf[ulen] = 0;
return ubuf;
}
-int widechar_main(int argc, wchar_t** argv) {
+int widechar_main(int argc, wchar_t **argv) {
OS_Windows os(NULL);
setlocale(LC_CTYPE, "");
- char ** argv_utf8 = new char*[argc];
+ char **argv_utf8 = new char *[argc];
- for(int i=0; i<argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
argv_utf8[i] = wc_to_utf8(argv[i]);
}
Error err = Main::setup(argv_utf8[0], argc - 1, &argv_utf8[1]);
- if (err!=OK)
+ if (err != OK)
return 255;
-
if (Main::start())
os.run();
Main::cleanup();
-
- for (int i=0; i<argc; ++i) {
+ for (int i = 0; i < argc; ++i) {
delete[] argv_utf8[i];
}
delete[] argv_utf8;
@@ -154,17 +150,17 @@ int widechar_main(int argc, wchar_t** argv) {
return os.get_exit_code();
};
-int main(int _argc, char** _argv) {
+int main(int _argc, char **_argv) {
// _argc and _argv are ignored
// we are going to use the WideChar version of them instead
LPWSTR *wc_argv;
- int argc;
- int result;
+ int argc;
+ int result;
wc_argv = CommandLineToArgvW(GetCommandLineW(), &argc);
- if( NULL == wc_argv ) {
+ if (NULL == wc_argv) {
wprintf(L"CommandLineToArgvW failed\n");
return 0;
}
@@ -177,7 +173,7 @@ int main(int _argc, char** _argv) {
HINSTANCE godot_hinstance = NULL;
-int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
+int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
godot_hinstance = hInstance;
- return main(0,NULL);
+ return main(0, NULL);
}
diff --git a/platform/windows/joypad.cpp b/platform/windows/joypad.cpp
index 4c1eeb425a..2472940ef3 100644
--- a/platform/windows/joypad.cpp
+++ b/platform/windows/joypad.cpp
@@ -27,22 +27,25 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "joypad.h"
-#include <iostream>
-#include <wbemidl.h>
#include <oleauto.h>
+#include <wbemidl.h>
+#include <iostream>
#ifndef __GNUC__
#define __builtin_bswap32 _byteswap_ulong
#endif
-DWORD WINAPI _xinput_get_state(DWORD dwUserIndex, XINPUT_STATE* pState) { return ERROR_DEVICE_NOT_CONNECTED; }
-DWORD WINAPI _xinput_set_state(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration) { return ERROR_DEVICE_NOT_CONNECTED; }
+DWORD WINAPI _xinput_get_state(DWORD dwUserIndex, XINPUT_STATE *pState) {
+ return ERROR_DEVICE_NOT_CONNECTED;
+}
+DWORD WINAPI _xinput_set_state(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration) {
+ return ERROR_DEVICE_NOT_CONNECTED;
+}
JoypadWindows::JoypadWindows() {
-
}
-JoypadWindows::JoypadWindows(InputDefault* _input, HWND* hwnd) {
+JoypadWindows::JoypadWindows(InputDefault *_input, HWND *hwnd) {
input = _input;
hWnd = hwnd;
@@ -57,9 +60,8 @@ JoypadWindows::JoypadWindows(InputDefault* _input, HWND* hwnd) {
for (int i = 0; i < JOYPADS_MAX; i++)
attached_joypads[i] = false;
-
HRESULT result;
- result = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&dinput, NULL);
+ result = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, NULL);
if (FAILED(result)) {
printf("failed init DINPUT: %ld\n", result);
}
@@ -73,7 +75,6 @@ JoypadWindows::~JoypadWindows() {
unload_xinput();
}
-
bool JoypadWindows::have_device(const GUID &p_guid) {
for (int i = 0; i < JOYPADS_MAX; i++) {
@@ -87,7 +88,6 @@ bool JoypadWindows::have_device(const GUID &p_guid) {
return false;
}
-
// adapted from SDL2, works a lot better than the MSDN version
bool JoypadWindows::is_xinput_device(const GUID *p_guid) {
@@ -104,7 +104,7 @@ bool JoypadWindows::is_xinput_device(const GUID *p_guid) {
if (GetRawInputDeviceList(NULL, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == -1) {
return false;
}
- dev_list = (PRAWINPUTDEVICELIST) malloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count);
+ dev_list = (PRAWINPUTDEVICELIST)malloc(sizeof(RAWINPUTDEVICELIST) * dev_list_count);
if (!dev_list) return false;
if (GetRawInputDeviceList(dev_list, &dev_list_count, sizeof(RAWINPUTDEVICELIST)) == -1) {
@@ -119,7 +119,7 @@ bool JoypadWindows::is_xinput_device(const GUID *p_guid) {
UINT nameSize = sizeof(dev_name);
rdi.cbSize = rdiSize;
- if ( (dev_list[i].dwType == RIM_TYPEHID) &&
+ if ((dev_list[i].dwType == RIM_TYPEHID) &&
(GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICEINFO, &rdi, &rdiSize) != (UINT)-1) &&
(MAKELONG(rdi.hid.dwVendorId, rdi.hid.dwProductId) == (LONG)p_guid->Data1) &&
(GetRawInputDeviceInfoA(dev_list[i].hDevice, RIDI_DEVICENAME, &dev_name, &nameSize) != (UINT)-1) &&
@@ -133,7 +133,7 @@ bool JoypadWindows::is_xinput_device(const GUID *p_guid) {
return false;
}
-bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE* instance) {
+bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE *instance) {
HRESULT hr;
int num = input->get_unused_joy_id();
@@ -142,7 +142,7 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE* instance) {
return false;
d_joypads[joypad_count] = dinput_gamepad();
- dinput_gamepad* joy = &d_joypads[joypad_count];
+ dinput_gamepad *joy = &d_joypads[joypad_count];
const DWORD devtype = (instance->dwDevType & 0xFF);
@@ -162,8 +162,8 @@ bool JoypadWindows::setup_dinput_joypad(const DIDEVICEINSTANCE* instance) {
const GUID &guid = instance->guidProduct;
char uid[128];
sprintf(uid, "%08lx%04hx%04hx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx",
- __builtin_bswap32(guid.Data1), guid.Data2, guid.Data3,
- guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
+ __builtin_bswap32(guid.Data1), guid.Data2, guid.Data3,
+ guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
id_to_change = joypad_count;
@@ -216,7 +216,6 @@ void JoypadWindows::setup_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_
dinput_gamepad &joy = d_joypads[p_joy_id];
-
res = IDirectInputDevice8_SetProperty(joy.di_joy, DIPROP_RANGE, &prop_range.diph);
if (FAILED(res))
return;
@@ -235,10 +234,9 @@ void JoypadWindows::setup_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_
}
}
-BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE* instance, void* pContext) {
-
+BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE *instance, void *pContext) {
- JoypadWindows* self = (JoypadWindows*)pContext;
+ JoypadWindows *self = (JoypadWindows *)pContext;
if (self->is_xinput_device(&instance->guidProduct)) {
return DIENUM_CONTINUE;
}
@@ -248,7 +246,7 @@ BOOL CALLBACK JoypadWindows::enumCallback(const DIDEVICEINSTANCE* instance, void
BOOL CALLBACK JoypadWindows::objectsCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context) {
- JoypadWindows* self = (JoypadWindows*)context;
+ JoypadWindows *self = (JoypadWindows *)context;
self->setup_joypad_object(instance, self->id_to_change);
return DIENUM_CONTINUE;
@@ -284,7 +282,7 @@ void JoypadWindows::probe_joypads() {
ZeroMemory(&x_joypads[i].state, sizeof(XINPUT_STATE));
dwResult = xinput_get_state(i, &x_joypads[i].state);
- if ( dwResult == ERROR_SUCCESS) {
+ if (dwResult == ERROR_SUCCESS) {
int id = input->get_unused_joy_id();
if (id != -1 && !x_joypads[i].attached) {
@@ -295,10 +293,9 @@ void JoypadWindows::probe_joypads() {
x_joypads[i].ff_end_timestamp = 0;
x_joypads[i].vibrating = false;
attached_joypads[id] = true;
- input->joy_connection_changed(id, true, "XInput Gamepad","__XINPUT_DEVICE__");
+ input->joy_connection_changed(id, true, "XInput Gamepad", "__XINPUT_DEVICE__");
}
- }
- else if (x_joypads[i].attached) {
+ } else if (x_joypads[i].attached) {
x_joypads[i].attached = false;
attached_joypads[x_joypads[i].id] = false;
@@ -344,12 +341,12 @@ unsigned int JoypadWindows::process_joypads(unsigned int p_last_id) {
button_mask = button_mask * 2;
}
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_0, axis_correct(joy.state.Gamepad.sThumbLX, true));
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_1, axis_correct(joy.state.Gamepad.sThumbLY, true, false, true));
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_2, axis_correct(joy.state.Gamepad.sThumbRX, true));
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_3, axis_correct(joy.state.Gamepad.sThumbRY, true, false, true));
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_4, axis_correct(joy.state.Gamepad.bLeftTrigger, true, true));
- p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_5, axis_correct(joy.state.Gamepad.bRightTrigger, true, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_0, axis_correct(joy.state.Gamepad.sThumbLX, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_1, axis_correct(joy.state.Gamepad.sThumbLY, true, false, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_2, axis_correct(joy.state.Gamepad.sThumbRX, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_3, axis_correct(joy.state.Gamepad.sThumbRY, true, false, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_4, axis_correct(joy.state.Gamepad.bLeftTrigger, true, true));
+ p_last_id = input->joy_axis(p_last_id, joy.id, JOY_AXIS_5, axis_correct(joy.state.Gamepad.bRightTrigger, true, true));
joy.last_packet = joy.state.dwPacketNumber;
}
uint64_t timestamp = input->get_joy_vibration_timestamp(joy.id);
@@ -370,7 +367,7 @@ unsigned int JoypadWindows::process_joypads(unsigned int p_last_id) {
for (int i = 0; i < JOYPADS_MAX; i++) {
- dinput_gamepad* joy = &d_joypads[i];
+ dinput_gamepad *joy = &d_joypads[i];
if (!joy->attached)
continue;
@@ -398,8 +395,7 @@ unsigned int JoypadWindows::process_joypads(unsigned int p_last_id) {
p_last_id = input->joy_button(p_last_id, joy->id, j, true);
joy->last_buttons[j] = true;
}
- }
- else {
+ } else {
if (joy->last_buttons[j]) {
@@ -416,7 +412,7 @@ unsigned int JoypadWindows::process_joypads(unsigned int p_last_id) {
for (int j = 0; j < joy->joy_axis.size(); j++) {
- for (int k=0; k<count; k++) {
+ for (int k = 0; k < count; k++) {
if (joy->joy_axis[j] == axes[k]) {
p_last_id = input->joy_axis(p_last_id, joy->id, j, axis_correct(values[k]));
break;
@@ -438,38 +434,31 @@ unsigned int JoypadWindows::post_hat(unsigned int p_last_id, int p_device, DWORD
dpad_val = InputDefault::HAT_MASK_UP;
- }
- else if (p_dpad == 4500) {
+ } else if (p_dpad == 4500) {
dpad_val = (InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_RIGHT);
- }
- else if (p_dpad == 9000) {
+ } else if (p_dpad == 9000) {
dpad_val = InputDefault::HAT_MASK_RIGHT;
- }
- else if (p_dpad == 13500) {
+ } else if (p_dpad == 13500) {
dpad_val = (InputDefault::HAT_MASK_RIGHT | InputDefault::HAT_MASK_DOWN);
- }
- else if (p_dpad == 18000) {
+ } else if (p_dpad == 18000) {
dpad_val = InputDefault::HAT_MASK_DOWN;
- }
- else if (p_dpad == 22500) {
+ } else if (p_dpad == 22500) {
dpad_val = (InputDefault::HAT_MASK_DOWN | InputDefault::HAT_MASK_LEFT);
- }
- else if (p_dpad == 27000) {
+ } else if (p_dpad == 27000) {
dpad_val = InputDefault::HAT_MASK_LEFT;
- }
- else if (p_dpad == 31500) {
+ } else if (p_dpad == 31500) {
dpad_val = (InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_UP);
}
@@ -494,8 +483,7 @@ InputDefault::JoyAxis JoypadWindows::axis_correct(int p_val, bool p_xinput, bool
jx.min = -1;
if (p_val < 0) {
jx.value = (float)p_val / MAX_JOY_AXIS;
- }
- else {
+ } else {
jx.value = (float)p_val / (MAX_JOY_AXIS - 1);
}
if (p_negate) {
@@ -526,7 +514,7 @@ void JoypadWindows::joypad_vibration_stop_xinput(int p_device, uint64_t p_timest
xinput_gamepad &joy = x_joypads[p_device];
if (joy.attached) {
XINPUT_VIBRATION effect;
- effect.wLeftMotorSpeed = 0;
+ effect.wLeftMotorSpeed = 0;
effect.wRightMotorSpeed = 0;
if (xinput_set_state(p_device, &effect) == ERROR_SUCCESS) {
joy.ff_timestamp = p_timestamp;
@@ -535,12 +523,11 @@ void JoypadWindows::joypad_vibration_stop_xinput(int p_device, uint64_t p_timest
}
}
-
void JoypadWindows::load_xinput() {
xinput_get_state = &_xinput_get_state;
xinput_set_state = &_xinput_set_state;
- xinput_dll = LoadLibrary( "XInput1_4.dll" );
+ xinput_dll = LoadLibrary("XInput1_4.dll");
if (!xinput_dll) {
xinput_dll = LoadLibrary("XInput1_3.dll");
if (!xinput_dll) {
diff --git a/platform/windows/joypad.h b/platform/windows/joypad.h
index d6670c90db..7e4f6ff328 100644
--- a/platform/windows/joypad.h
+++ b/platform/windows/joypad.h
@@ -34,30 +34,28 @@
#include <dinput.h>
#include <xinput.h> // on unix the file is called "xinput.h", on windows I'm sure it won't mind
-#ifndef SAFE_RELEASE // when Windows Media Device M? is not present
+#ifndef SAFE_RELEASE // when Windows Media Device M? is not present
#define SAFE_RELEASE(x) \
-if(x != NULL) \
-{ \
- x->Release(); \
- x = NULL; \
-}
+ if (x != NULL) { \
+ x->Release(); \
+ x = NULL; \
+ }
#endif
#ifndef XUSER_MAX_COUNT
#define XUSER_MAX_COUNT 4
#endif
-class JoypadWindows
-{
+class JoypadWindows {
public:
JoypadWindows();
- JoypadWindows(InputDefault* _input, HWND* hwnd);
+ JoypadWindows(InputDefault *_input, HWND *hwnd);
~JoypadWindows();
void probe_joypads();
unsigned int process_joypads(unsigned int p_last_id);
-private:
+private:
enum {
JOYPADS_MAX = 16,
JOY_AXIS_COUNT = 6,
@@ -110,13 +108,13 @@ private:
}
};
- typedef DWORD (WINAPI *XInputGetState_t) (DWORD dwUserIndex, XINPUT_STATE* pState);
- typedef DWORD (WINAPI *XInputSetState_t) (DWORD dwUserIndex, XINPUT_VIBRATION* pVibration);
+ typedef DWORD(WINAPI *XInputGetState_t)(DWORD dwUserIndex, XINPUT_STATE *pState);
+ typedef DWORD(WINAPI *XInputSetState_t)(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration);
- HWND* hWnd;
+ HWND *hWnd;
HANDLE xinput_dll;
LPDIRECTINPUT8 dinput;
- InputDefault* input;
+ InputDefault *input;
int id_to_change;
int joypad_count;
@@ -124,10 +122,10 @@ private:
dinput_gamepad d_joypads[JOYPADS_MAX];
xinput_gamepad x_joypads[XUSER_MAX_COUNT];
- static BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE* p_instance, void* p_context);
- static BOOL CALLBACK objectsCallback(const DIDEVICEOBJECTINSTANCE* instance, void* context);
+ static BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE *p_instance, void *p_context);
+ static BOOL CALLBACK objectsCallback(const DIDEVICEOBJECTINSTANCE *instance, void *context);
- void setup_joypad_object(const DIDEVICEOBJECTINSTANCE* ob, int p_joy_id);
+ void setup_joypad_object(const DIDEVICEOBJECTINSTANCE *ob, int p_joy_id);
void close_joypad(int id = -1);
void load_xinput();
void unload_xinput();
@@ -135,8 +133,8 @@ private:
unsigned int post_hat(unsigned int p_last_id, int p_device, DWORD p_dpad);
bool have_device(const GUID &p_guid);
- bool is_xinput_device(const GUID* p_guid);
- bool setup_dinput_joypad(const DIDEVICEINSTANCE* instance);
+ bool is_xinput_device(const GUID *p_guid);
+ bool setup_dinput_joypad(const DIDEVICEINSTANCE *instance);
void joypad_vibration_start_xinput(int p_device, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp);
void joypad_vibration_stop_xinput(int p_device, uint64_t p_timestamp);
@@ -146,5 +144,3 @@ private:
};
#endif
-
-
diff --git a/platform/windows/key_mapping_win.cpp b/platform/windows/key_mapping_win.cpp
index 9ab222e9ee..51cdba65d5 100644
--- a/platform/windows/key_mapping_win.cpp
+++ b/platform/windows/key_mapping_win.cpp
@@ -36,202 +36,198 @@ struct _WinTranslatePair {
unsigned int keycode;
};
+static _WinTranslatePair _vk_to_keycode[] = {
-static _WinTranslatePair _vk_to_keycode[]={
+ { KEY_BACKSPACE, VK_BACK }, // (0x08) // backspace
+ { KEY_TAB, VK_TAB }, //(0x09)
-{ KEY_BACKSPACE, VK_BACK },// (0x08) // backspace
-{ KEY_TAB, VK_TAB },//(0x09)
+ //VK_CLEAR (0x0C)
-//VK_CLEAR (0x0C)
+ { KEY_RETURN, VK_RETURN }, //(0x0D)
-{ KEY_RETURN, VK_RETURN },//(0x0D)
+ { KEY_SHIFT, VK_SHIFT }, //(0x10)
-{ KEY_SHIFT, VK_SHIFT },//(0x10)
+ { KEY_CONTROL, VK_CONTROL }, //(0x11)
+
+ { KEY_MENU, VK_MENU }, //(0x12)
+
+ { KEY_PAUSE, VK_PAUSE }, //(0x13)
+
+ { KEY_CAPSLOCK, VK_CAPITAL }, //(0x14)
+
+ { KEY_ESCAPE, VK_ESCAPE }, //(0x1B)
+
+ { KEY_SPACE, VK_SPACE }, //(0x20)
+
+ { KEY_PAGEUP, VK_PRIOR }, //(0x21)
+
+ { KEY_PAGEDOWN, VK_NEXT }, //(0x22)
+
+ { KEY_END, VK_END }, //(0x23)
+
+ { KEY_HOME, VK_HOME }, //(0x24)
+
+ { KEY_LEFT, VK_LEFT }, //(0x25)
+
+ { KEY_UP, VK_UP }, //(0x26)
+
+ { KEY_RIGHT, VK_RIGHT }, //(0x27)
+
+ { KEY_DOWN, VK_DOWN }, // (0x28)
+
+ //VK_SELECT (0x29)
+
+ { KEY_PRINT, VK_PRINT }, // (0x2A)
+
+ //VK_EXECUTE (0x2B)
+
+ { KEY_PRINT, VK_SNAPSHOT }, // (0x2C)
+
+ { KEY_INSERT, VK_INSERT }, // (0x2D)
+
+ { KEY_DELETE, VK_DELETE }, // (0x2E)
+
+ { KEY_HELP, VK_HELP }, // (0x2F)
+
+ { KEY_0, (0x30) }, ////0 key
+ { KEY_1, (0x31) }, ////1 key
+ { KEY_2, (0x32) }, ////2 key
+ { KEY_3, (0x33) }, ////3 key
+ { KEY_4, (0x34) }, ////4 key
+ { KEY_5, (0x35) }, ////5 key
+ { KEY_6, (0x36) }, ////6 key
+ { KEY_7, (0x37) }, ////7 key
+ { KEY_8, (0x38) }, ////8 key
+ { KEY_9, (0x39) }, ////9 key
+ { KEY_A, (0x41) }, ////A key
+ { KEY_B, (0x42) }, ////B key
+ { KEY_C, (0x43) }, ////C key
+ { KEY_D, (0x44) }, ////D key
+ { KEY_E, (0x45) }, ////E key
+ { KEY_F, (0x46) }, ////F key
+ { KEY_G, (0x47) }, ////G key
+ { KEY_H, (0x48) }, ////H key
+ { KEY_I, (0x49) }, ////I key
+ { KEY_J, (0x4A) }, ////J key
+ { KEY_K, (0x4B) }, ////K key
+ { KEY_L, (0x4C) }, ////L key
+ { KEY_M, (0x4D) }, ////M key
+ { KEY_N, (0x4E) }, ////N key
+ { KEY_O, (0x4F) }, ////O key
+ { KEY_P, (0x50) }, ////P key
+ { KEY_Q, (0x51) }, ////Q key
+ { KEY_R, (0x52) }, ////R key
+ { KEY_S, (0x53) }, ////S key
+ { KEY_T, (0x54) }, ////T key
+ { KEY_U, (0x55) }, ////U key
+ { KEY_V, (0x56) }, ////V key
+ { KEY_W, (0x57) }, ////W key
+ { KEY_X, (0x58) }, ////X key
+ { KEY_Y, (0x59) }, ////Y key
+ { KEY_Z, (0x5A) }, ////Z key
-{ KEY_CONTROL, VK_CONTROL },//(0x11)
-
-{ KEY_MENU, VK_MENU },//(0x12)
-
-{ KEY_PAUSE, VK_PAUSE },//(0x13)
-
-{ KEY_CAPSLOCK, VK_CAPITAL },//(0x14)
-
-{ KEY_ESCAPE, VK_ESCAPE },//(0x1B)
-
-{ KEY_SPACE, VK_SPACE },//(0x20)
-
-{ KEY_PAGEUP,VK_PRIOR },//(0x21)
-
-{ KEY_PAGEDOWN, VK_NEXT },//(0x22)
-
-{ KEY_END, VK_END },//(0x23)
-
-{ KEY_HOME, VK_HOME },//(0x24)
-
-{ KEY_LEFT, VK_LEFT },//(0x25)
-
-{ KEY_UP, VK_UP },//(0x26)
-
-{ KEY_RIGHT,VK_RIGHT },//(0x27)
-
-{ KEY_DOWN, VK_DOWN},// (0x28)
-
-//VK_SELECT (0x29)
-
-{ KEY_PRINT, VK_PRINT},// (0x2A)
-
-//VK_EXECUTE (0x2B)
-
-{ KEY_PRINT, VK_SNAPSHOT},// (0x2C)
-
-{ KEY_INSERT, VK_INSERT},// (0x2D)
-
-{ KEY_DELETE, VK_DELETE},// (0x2E)
-
-{ KEY_HELP, VK_HELP},// (0x2F)
-
-
-{ KEY_0, (0x30) },////0 key
-{ KEY_1, (0x31) },////1 key
-{ KEY_2, (0x32) },////2 key
-{ KEY_3, (0x33) },////3 key
-{ KEY_4, (0x34) },////4 key
-{ KEY_5, (0x35) },////5 key
-{ KEY_6, (0x36) },////6 key
-{ KEY_7, (0x37) },////7 key
-{ KEY_8, (0x38) },////8 key
-{ KEY_9, (0x39) },////9 key
-{ KEY_A, (0x41) },////A key
-{ KEY_B, (0x42) },////B key
-{ KEY_C, (0x43) },////C key
-{ KEY_D, (0x44) },////D key
-{ KEY_E, (0x45) },////E key
-{ KEY_F, (0x46) },////F key
-{ KEY_G, (0x47) },////G key
-{ KEY_H, (0x48) },////H key
-{ KEY_I, (0x49) },////I key
-{ KEY_J, (0x4A) },////J key
-{ KEY_K, (0x4B) },////K key
-{ KEY_L, (0x4C) },////L key
-{ KEY_M, (0x4D) },////M key
-{ KEY_N, (0x4E) },////N key
-{ KEY_O, (0x4F) },////O key
-{ KEY_P, (0x50) },////P key
-{ KEY_Q, (0x51) },////Q key
-{ KEY_R, (0x52) },////R key
-{ KEY_S, (0x53) },////S key
-{ KEY_T, (0x54) },////T key
-{ KEY_U, (0x55) },////U key
-{ KEY_V, (0x56) },////V key
-{ KEY_W, (0x57) },////W key
-{ KEY_X, (0x58) },////X key
-{ KEY_Y, (0x59) },////Y key
-{ KEY_Z, (0x5A) },////Z key
-
-{ KEY_MASK_META, VK_LWIN },//(0x5B)
-{ KEY_MASK_META, VK_RWIN },//(0x5C)
-//VK_APPS (0x5D)
-{ KEY_STANDBY,VK_SLEEP },//(0x5F)
-{ KEY_KP_0,VK_NUMPAD0 },//(0x60)
-{ KEY_KP_1,VK_NUMPAD1 },//(0x61)
-{ KEY_KP_2,VK_NUMPAD2 },//(0x62)
-{ KEY_KP_3,VK_NUMPAD3 },//(0x63)
-{ KEY_KP_4,VK_NUMPAD4 },//(0x64)
-{ KEY_KP_5,VK_NUMPAD5 },//(0x65)
-{ KEY_KP_6,VK_NUMPAD6 },//(0x66)
-{ KEY_KP_7,VK_NUMPAD7 },//(0x67)
-{ KEY_KP_8,VK_NUMPAD8 },//(0x68)
-{ KEY_KP_9,VK_NUMPAD9 },//(0x69)
-{ KEY_KP_MULTIPLY,VK_MULTIPLY},// (0x6A)
-{ KEY_KP_ADD,VK_ADD},// (0x6B)
-//VK_SEPARATOR (0x6C)
-{ KEY_KP_SUBTRACT,VK_SUBTRACT},// (0x6D)
-{ KEY_KP_PERIOD,VK_DECIMAL},// (0x6E)
-{ KEY_KP_DIVIDE,VK_DIVIDE},// (0x6F)
-{ KEY_F1,VK_F1},// (0x70)
-{ KEY_F2,VK_F2},// (0x71)
-{ KEY_F3,VK_F3},// (0x72)
-{ KEY_F4,VK_F4},// (0x73)
-{ KEY_F5,VK_F5},// (0x74)
-{ KEY_F6,VK_F6},// (0x75)
-{ KEY_F7,VK_F7},// (0x76)
-{ KEY_F8,VK_F8},// (0x77)
-{ KEY_F9,VK_F9},// (0x78)
-{ KEY_F10,VK_F10},// (0x79)
-{ KEY_F11,VK_F11},// (0x7A)
-{ KEY_F12,VK_F12},// (0x7B)
-{ KEY_F13,VK_F13},// (0x7C)
-{ KEY_F14,VK_F14},// (0x7D)
-{ KEY_F15,VK_F15},// (0x7E)
-{ KEY_F16,VK_F16},// (0x7F)
-{ KEY_NUMLOCK,VK_NUMLOCK},// (0x90)
-{ KEY_SCROLLLOCK,VK_SCROLL},// (0x91)
-{ KEY_SHIFT,VK_LSHIFT},// (0xA0)
-{ KEY_SHIFT,VK_RSHIFT},// (0xA1)
-{ KEY_CONTROL,VK_LCONTROL},// (0xA2)
-{ KEY_CONTROL,VK_RCONTROL},// (0xA3)
-{ KEY_MENU,VK_LMENU},// (0xA4)
-{ KEY_MENU,VK_RMENU},// (0xA5)
-
-
-{ KEY_BACK,VK_BROWSER_BACK},// (0xA6)
-
-{ KEY_FORWARD,VK_BROWSER_FORWARD},// (0xA7)
-
-{ KEY_REFRESH,VK_BROWSER_REFRESH},// (0xA8)
-
-{ KEY_STOP,VK_BROWSER_STOP},// (0xA9)
-
-{ KEY_SEARCH,VK_BROWSER_SEARCH},// (0xAA)
-
-{ KEY_FAVORITES, VK_BROWSER_FAVORITES},// (0xAB)
-
-{ KEY_HOMEPAGE,VK_BROWSER_HOME},// (0xAC)
-
-{ KEY_VOLUMEMUTE,VK_VOLUME_MUTE},// (0xAD)
-
-{ KEY_VOLUMEDOWN,VK_VOLUME_DOWN},// (0xAE)
-
-{ KEY_VOLUMEUP,VK_VOLUME_UP},// (0xAF)
-
-
-{ KEY_MEDIANEXT,VK_MEDIA_NEXT_TRACK},// (0xB0)
-
-{ KEY_MEDIAPREVIOUS,VK_MEDIA_PREV_TRACK},// (0xB1)
-
-{ KEY_MEDIASTOP,VK_MEDIA_STOP},// (0xB2)
-
-//VK_MEDIA_PLAY_PAUSE (0xB3)
-
-{ KEY_LAUNCHMAIL, VK_LAUNCH_MAIL},// (0xB4)
-
-{ KEY_LAUNCHMEDIA,VK_LAUNCH_MEDIA_SELECT},// (0xB5)
-
-{ KEY_LAUNCH0,VK_LAUNCH_APP1},// (0xB6)
-
-{ KEY_LAUNCH1,VK_LAUNCH_APP2},// (0xB7)
-
-{ KEY_SEMICOLON,VK_OEM_1},// (0xBA)
-
-
-{ KEY_EQUAL, VK_OEM_PLUS},// (0xBB) // Windows 2000/XP: For any country/region, the '+' key
-{ KEY_COLON,VK_OEM_COMMA},// (0xBC) // Windows 2000/XP: For any country/region, the ',' key
-{ KEY_MINUS,VK_OEM_MINUS},// (0xBD) // Windows 2000/XP: For any country/region, the '-' key
-{ KEY_PERIOD,VK_OEM_PERIOD},// (0xBE) // Windows 2000/XP: For any country/region, the '.' key
-{ KEY_SLASH,VK_OEM_2},// (0xBF) //Windows 2000/XP: For the US standard keyboard, the '/?' key
-
-{KEY_QUOTELEFT, VK_OEM_3},// (0xC0)
-{KEY_BRACELEFT,VK_OEM_4},// (0xDB)
-{KEY_BACKSLASH,VK_OEM_5},// (0xDC)
-{KEY_BRACERIGHT,VK_OEM_6},// (0xDD)
-{KEY_APOSTROPHE, VK_OEM_7},// (0xDE)
-/*
+ { KEY_MASK_META, VK_LWIN }, //(0x5B)
+ { KEY_MASK_META, VK_RWIN }, //(0x5C)
+ //VK_APPS (0x5D)
+ { KEY_STANDBY, VK_SLEEP }, //(0x5F)
+ { KEY_KP_0, VK_NUMPAD0 }, //(0x60)
+ { KEY_KP_1, VK_NUMPAD1 }, //(0x61)
+ { KEY_KP_2, VK_NUMPAD2 }, //(0x62)
+ { KEY_KP_3, VK_NUMPAD3 }, //(0x63)
+ { KEY_KP_4, VK_NUMPAD4 }, //(0x64)
+ { KEY_KP_5, VK_NUMPAD5 }, //(0x65)
+ { KEY_KP_6, VK_NUMPAD6 }, //(0x66)
+ { KEY_KP_7, VK_NUMPAD7 }, //(0x67)
+ { KEY_KP_8, VK_NUMPAD8 }, //(0x68)
+ { KEY_KP_9, VK_NUMPAD9 }, //(0x69)
+ { KEY_KP_MULTIPLY, VK_MULTIPLY }, // (0x6A)
+ { KEY_KP_ADD, VK_ADD }, // (0x6B)
+ //VK_SEPARATOR (0x6C)
+ { KEY_KP_SUBTRACT, VK_SUBTRACT }, // (0x6D)
+ { KEY_KP_PERIOD, VK_DECIMAL }, // (0x6E)
+ { KEY_KP_DIVIDE, VK_DIVIDE }, // (0x6F)
+ { KEY_F1, VK_F1 }, // (0x70)
+ { KEY_F2, VK_F2 }, // (0x71)
+ { KEY_F3, VK_F3 }, // (0x72)
+ { KEY_F4, VK_F4 }, // (0x73)
+ { KEY_F5, VK_F5 }, // (0x74)
+ { KEY_F6, VK_F6 }, // (0x75)
+ { KEY_F7, VK_F7 }, // (0x76)
+ { KEY_F8, VK_F8 }, // (0x77)
+ { KEY_F9, VK_F9 }, // (0x78)
+ { KEY_F10, VK_F10 }, // (0x79)
+ { KEY_F11, VK_F11 }, // (0x7A)
+ { KEY_F12, VK_F12 }, // (0x7B)
+ { KEY_F13, VK_F13 }, // (0x7C)
+ { KEY_F14, VK_F14 }, // (0x7D)
+ { KEY_F15, VK_F15 }, // (0x7E)
+ { KEY_F16, VK_F16 }, // (0x7F)
+ { KEY_NUMLOCK, VK_NUMLOCK }, // (0x90)
+ { KEY_SCROLLLOCK, VK_SCROLL }, // (0x91)
+ { KEY_SHIFT, VK_LSHIFT }, // (0xA0)
+ { KEY_SHIFT, VK_RSHIFT }, // (0xA1)
+ { KEY_CONTROL, VK_LCONTROL }, // (0xA2)
+ { KEY_CONTROL, VK_RCONTROL }, // (0xA3)
+ { KEY_MENU, VK_LMENU }, // (0xA4)
+ { KEY_MENU, VK_RMENU }, // (0xA5)
+
+ { KEY_BACK, VK_BROWSER_BACK }, // (0xA6)
+
+ { KEY_FORWARD, VK_BROWSER_FORWARD }, // (0xA7)
+
+ { KEY_REFRESH, VK_BROWSER_REFRESH }, // (0xA8)
+
+ { KEY_STOP, VK_BROWSER_STOP }, // (0xA9)
+
+ { KEY_SEARCH, VK_BROWSER_SEARCH }, // (0xAA)
+
+ { KEY_FAVORITES, VK_BROWSER_FAVORITES }, // (0xAB)
+
+ { KEY_HOMEPAGE, VK_BROWSER_HOME }, // (0xAC)
+
+ { KEY_VOLUMEMUTE, VK_VOLUME_MUTE }, // (0xAD)
+
+ { KEY_VOLUMEDOWN, VK_VOLUME_DOWN }, // (0xAE)
+
+ { KEY_VOLUMEUP, VK_VOLUME_UP }, // (0xAF)
+
+ { KEY_MEDIANEXT, VK_MEDIA_NEXT_TRACK }, // (0xB0)
+
+ { KEY_MEDIAPREVIOUS, VK_MEDIA_PREV_TRACK }, // (0xB1)
+
+ { KEY_MEDIASTOP, VK_MEDIA_STOP }, // (0xB2)
+
+ //VK_MEDIA_PLAY_PAUSE (0xB3)
+
+ { KEY_LAUNCHMAIL, VK_LAUNCH_MAIL }, // (0xB4)
+
+ { KEY_LAUNCHMEDIA, VK_LAUNCH_MEDIA_SELECT }, // (0xB5)
+
+ { KEY_LAUNCH0, VK_LAUNCH_APP1 }, // (0xB6)
+
+ { KEY_LAUNCH1, VK_LAUNCH_APP2 }, // (0xB7)
+
+ { KEY_SEMICOLON, VK_OEM_1 }, // (0xBA)
+
+ { KEY_EQUAL, VK_OEM_PLUS }, // (0xBB) // Windows 2000/XP: For any country/region, the '+' key
+ { KEY_COLON, VK_OEM_COMMA }, // (0xBC) // Windows 2000/XP: For any country/region, the ',' key
+ { KEY_MINUS, VK_OEM_MINUS }, // (0xBD) // Windows 2000/XP: For any country/region, the '-' key
+ { KEY_PERIOD, VK_OEM_PERIOD }, // (0xBE) // Windows 2000/XP: For any country/region, the '.' key
+ { KEY_SLASH, VK_OEM_2 }, // (0xBF) //Windows 2000/XP: For the US standard keyboard, the '/?' key
+
+ { KEY_QUOTELEFT, VK_OEM_3 }, // (0xC0)
+ { KEY_BRACELEFT, VK_OEM_4 }, // (0xDB)
+ { KEY_BACKSLASH, VK_OEM_5 }, // (0xDC)
+ { KEY_BRACERIGHT, VK_OEM_6 }, // (0xDD)
+ { KEY_APOSTROPHE, VK_OEM_7 }, // (0xDE)
+ /*
{VK_OEM_8 (0xDF)
{VK_OEM_102 (0xE2) // Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
*/
-//{ KEY_PLAY, VK_PLAY},// (0xFA)
+ //{ KEY_PLAY, VK_PLAY},// (0xFA)
-{KEY_UNKNOWN, 0} };
+ { KEY_UNKNOWN, 0 }
+};
/*
VK_ZOOM (0xFB)
@@ -242,15 +238,14 @@ VK_OEM_CLEAR (0xFE)
unsigned int KeyMappingWindows::get_keysym(unsigned int p_code) {
- for(int i=0;_vk_to_keycode[i].keysym!=KEY_UNKNOWN;i++) {
+ for (int i = 0; _vk_to_keycode[i].keysym != KEY_UNKNOWN; i++) {
- if (_vk_to_keycode[i].keycode==p_code) {
+ if (_vk_to_keycode[i].keycode == p_code) {
//printf("outcode: %x\n",_vk_to_keycode[i].keysym);
return _vk_to_keycode[i].keysym;
}
}
-
return KEY_UNKNOWN;
}
diff --git a/platform/windows/key_mapping_win.h b/platform/windows/key_mapping_win.h
index 2f1b36d9f2..fbc79635c2 100644
--- a/platform/windows/key_mapping_win.h
+++ b/platform/windows/key_mapping_win.h
@@ -29,23 +29,18 @@
#ifndef KEY_MAPPING_WINDOWS_H
#define KEY_MAPPING_WINDOWS_H
-
#include "os/keyboard.h"
#include <windows.h>
#include <winuser.h>
-
class KeyMappingWindows {
- KeyMappingWindows() {};
-public:
+ KeyMappingWindows(){};
+public:
static unsigned int get_keysym(unsigned int p_code);
-
};
-
-
#endif
diff --git a/platform/windows/lang_table.h b/platform/windows/lang_table.h
index bacbf89e85..7fe509d3e0 100644
--- a/platform/windows/lang_table.h
+++ b/platform/windows/lang_table.h
@@ -37,154 +37,154 @@ struct _WinLocale {
int sublang;
};
-static const _WinLocale _win_locales[]={
-{"ar", LANG_ARABIC,SUBLANG_NEUTRAL},
-{"ar_AE", LANG_ARABIC,SUBLANG_ARABIC_UAE},
-{"ar_BH", LANG_ARABIC,SUBLANG_ARABIC_BAHRAIN},
-{"ar_DZ", LANG_ARABIC,SUBLANG_ARABIC_ALGERIA},
-{"ar_EG", LANG_ARABIC,SUBLANG_ARABIC_EGYPT},
-{"ar_IQ", LANG_ARABIC,SUBLANG_ARABIC_IRAQ},
-{"ar_JO", LANG_ARABIC,SUBLANG_ARABIC_JORDAN},
-{"ar_KW", LANG_ARABIC,SUBLANG_ARABIC_KUWAIT},
-{"ar_LB", LANG_ARABIC,SUBLANG_ARABIC_LEBANON},
-{"ar_LY", LANG_ARABIC,SUBLANG_ARABIC_LIBYA},
-{"ar_MA", LANG_ARABIC,SUBLANG_ARABIC_MOROCCO},
-{"ar_OM", LANG_ARABIC,SUBLANG_ARABIC_OMAN},
-{"ar_QA", LANG_ARABIC,SUBLANG_ARABIC_QATAR},
-{"ar_SA", LANG_ARABIC,SUBLANG_ARABIC_SAUDI_ARABIA},
-//no sudan
-{"ar_SY", LANG_ARABIC,SUBLANG_ARABIC_SYRIA},
-{"ar_TN", LANG_ARABIC,SUBLANG_ARABIC_TUNISIA},
-{"ar_YE", LANG_ARABIC,SUBLANG_ARABIC_YEMEN},
-{"be", LANG_BELARUSIAN,SUBLANG_NEUTRAL},
-{"be_BY", LANG_BELARUSIAN,SUBLANG_BELARUSIAN_BELARUS},
-{"bg", LANG_BULGARIAN,SUBLANG_NEUTRAL},
-{"bg_BG", LANG_BULGARIAN,SUBLANG_BULGARIAN_BULGARIA},
-{"ca", LANG_CATALAN,SUBLANG_NEUTRAL},
-{"ca_ES", LANG_CATALAN,SUBLANG_CATALAN_CATALAN},
-{"cs", LANG_CZECH,SUBLANG_NEUTRAL},
-{"cs_CZ", LANG_CZECH,SUBLANG_CZECH_CZECH_REPUBLIC},
-{"da", LANG_DANISH,SUBLANG_NEUTRAL},
-{"da_DK", LANG_DANISH,SUBLANG_DANISH_DENMARK},
-{"de", LANG_GERMAN,SUBLANG_NEUTRAL},
-{"de_AT", LANG_GERMAN,SUBLANG_GERMAN_AUSTRIAN},
-{"de_CH", LANG_GERMAN,SUBLANG_GERMAN_SWISS},
-{"de_DE", LANG_GERMAN,SUBLANG_GERMAN},
-{"de_LU", LANG_GERMAN,SUBLANG_GERMAN_LUXEMBOURG},
-{"el", LANG_GREEK,SUBLANG_NEUTRAL},
-{"el_GR", LANG_GREEK,SUBLANG_GREEK_GREECE},
-//{"en_029", LANG_ENGLISH,SUBLANG_ENGLISH_CARIBBEAN},
-{"en", LANG_ENGLISH,SUBLANG_NEUTRAL},
-{"en_AU", LANG_ENGLISH,SUBLANG_ENGLISH_AUS},
-{"en_CA", LANG_ENGLISH,SUBLANG_ENGLISH_CAN},
-{"en_GB", LANG_ENGLISH,SUBLANG_ENGLISH_UK},
-//{"en_IE", LANG_ENGLISH,SUBLANG_ENGLISH_IRELAND},
-{"en_IN", LANG_ENGLISH,SUBLANG_ENGLISH_INDIA},
-//MT
-{"en_NZ", LANG_ENGLISH,SUBLANG_ENGLISH_NZ},
-{"en_PH", LANG_ENGLISH,SUBLANG_ENGLISH_PHILIPPINES},
-{"en_SG", LANG_ENGLISH,SUBLANG_ENGLISH_SINGAPORE},
-{"en_US", LANG_ENGLISH,SUBLANG_ENGLISH_US},
-{"en_ZA", LANG_ENGLISH,SUBLANG_ENGLISH_SOUTH_AFRICA},
-{"es", LANG_SPANISH,SUBLANG_NEUTRAL},
-{"es_AR", LANG_SPANISH,SUBLANG_SPANISH_ARGENTINA},
-{"es_BO", LANG_SPANISH,SUBLANG_SPANISH_BOLIVIA},
-{"es_CL", LANG_SPANISH,SUBLANG_SPANISH_CHILE},
-{"es_CO", LANG_SPANISH,SUBLANG_SPANISH_COLOMBIA},
-{"es_CR", LANG_SPANISH,SUBLANG_SPANISH_COSTA_RICA},
-{"es_DO", LANG_SPANISH,SUBLANG_SPANISH_DOMINICAN_REPUBLIC},
-{"es_EC", LANG_SPANISH,SUBLANG_SPANISH_ECUADOR},
-{"es_ES", LANG_SPANISH,SUBLANG_SPANISH},
-{"es_GT", LANG_SPANISH,SUBLANG_SPANISH_GUATEMALA},
-{"es_HN", LANG_SPANISH,SUBLANG_SPANISH_HONDURAS},
-{"es_MX", LANG_SPANISH,SUBLANG_SPANISH_MEXICAN},
-{"es_NI", LANG_SPANISH,SUBLANG_SPANISH_NICARAGUA},
-{"es_PA", LANG_SPANISH,SUBLANG_SPANISH_PANAMA},
-{"es_PE", LANG_SPANISH,SUBLANG_SPANISH_PERU},
-{"es_PR", LANG_SPANISH,SUBLANG_SPANISH_PUERTO_RICO},
-{"es_PY", LANG_SPANISH,SUBLANG_SPANISH_PARAGUAY},
-{"es_SV", LANG_SPANISH,SUBLANG_SPANISH_EL_SALVADOR},
-{"es_US", LANG_SPANISH,SUBLANG_SPANISH_US},
-{"es_UY", LANG_SPANISH,SUBLANG_SPANISH_URUGUAY},
-{"es_VE", LANG_SPANISH,SUBLANG_SPANISH_VENEZUELA},
-{"et", LANG_ESTONIAN,SUBLANG_NEUTRAL},
-{"et_EE", LANG_ESTONIAN,SUBLANG_ESTONIAN_ESTONIA},
-{"fi", LANG_FINNISH,SUBLANG_NEUTRAL},
-{"fi_FI", LANG_FINNISH,SUBLANG_FINNISH_FINLAND},
-{"fr", LANG_FRENCH,SUBLANG_NEUTRAL},
-{"fr_BE", LANG_FRENCH,SUBLANG_FRENCH_BELGIAN},
-{"fr_CA", LANG_FRENCH,SUBLANG_FRENCH_CANADIAN},
-{"fr_CH", LANG_FRENCH,SUBLANG_FRENCH_SWISS},
-{"fr_FR", LANG_FRENCH,SUBLANG_FRENCH},
-{"fr_LU", LANG_FRENCH,SUBLANG_FRENCH_LUXEMBOURG},
-{"ga", LANG_IRISH,SUBLANG_NEUTRAL},
-{"ga_IE", LANG_IRISH,SUBLANG_IRISH_IRELAND},
-{"hi", LANG_HINDI,SUBLANG_NEUTRAL},
-{"hi_IN", LANG_HINDI,SUBLANG_HINDI_INDIA},
-{"hr", LANG_CROATIAN,SUBLANG_NEUTRAL},
-{"hr_HR", LANG_CROATIAN,SUBLANG_CROATIAN_CROATIA},
-{"hu", LANG_HUNGARIAN,SUBLANG_NEUTRAL},
-{"hu_HU", LANG_HUNGARIAN,SUBLANG_HUNGARIAN_HUNGARY},
-{"in", LANG_ARMENIAN,SUBLANG_NEUTRAL},
-{"in_ID", LANG_INDONESIAN,SUBLANG_INDONESIAN_INDONESIA},
-{"is", LANG_ICELANDIC,SUBLANG_NEUTRAL},
-{"is_IS", LANG_ICELANDIC,SUBLANG_ICELANDIC_ICELAND},
-{"it", LANG_ITALIAN,SUBLANG_NEUTRAL},
-{"it_CH", LANG_ITALIAN,SUBLANG_ITALIAN_SWISS},
-{"it_IT", LANG_ITALIAN,SUBLANG_ITALIAN},
-{"iw", LANG_HEBREW,SUBLANG_NEUTRAL},
-{"iw_IL", LANG_HEBREW,SUBLANG_HEBREW_ISRAEL},
-{"ja", LANG_JAPANESE,SUBLANG_NEUTRAL},
-{"ja_JP", LANG_JAPANESE,SUBLANG_JAPANESE_JAPAN},
-{"ko", LANG_KOREAN,SUBLANG_NEUTRAL},
-{"ko_KR", LANG_KOREAN,SUBLANG_KOREAN},
-{"lt", LANG_LITHUANIAN,SUBLANG_NEUTRAL},
-//{"lt_LT", LANG_LITHUANIAN,SUBLANG_LITHUANIAN_LITHUANIA},
-{"lv", LANG_LATVIAN,SUBLANG_NEUTRAL},
-{"lv_LV", LANG_LATVIAN,SUBLANG_LATVIAN_LATVIA},
-{"mk", LANG_MACEDONIAN,SUBLANG_NEUTRAL},
-{"mk_MK", LANG_MACEDONIAN,SUBLANG_MACEDONIAN_MACEDONIA},
-{"ms", LANG_MALAY,SUBLANG_NEUTRAL},
-{"ms_MY", LANG_MALAY,SUBLANG_MALAY_MALAYSIA},
-{"mt", LANG_MALTESE,SUBLANG_NEUTRAL},
-{"mt_MT", LANG_MALTESE,SUBLANG_MALTESE_MALTA},
-{"nl", LANG_DUTCH,SUBLANG_NEUTRAL},
-{"nl_BE", LANG_DUTCH,SUBLANG_DUTCH_BELGIAN},
-{"nl_NL", LANG_DUTCH,SUBLANG_DUTCH},
-{"no", LANG_NORWEGIAN,SUBLANG_NEUTRAL},
-{"no_NO", LANG_NORWEGIAN,SUBLANG_NORWEGIAN_BOKMAL},
-{"no_NO_NY", LANG_NORWEGIAN,SUBLANG_NORWEGIAN_NYNORSK},
-{"pl", LANG_POLISH,SUBLANG_NEUTRAL},
-{"pl_PL", LANG_POLISH,SUBLANG_POLISH_POLAND},
-{"pt", LANG_PORTUGUESE,SUBLANG_NEUTRAL},
-{"pt_BR", LANG_PORTUGUESE,SUBLANG_PORTUGUESE_BRAZILIAN},
-{"pt_PT", LANG_PORTUGUESE,SUBLANG_PORTUGUESE},
-{"ro", LANG_ROMANIAN,SUBLANG_NEUTRAL},
-{"ro_RO", LANG_ROMANIAN,SUBLANG_ROMANIAN_ROMANIA},
-{"ru", LANG_RUSSIAN,SUBLANG_NEUTRAL},
-{"ru_RU", LANG_RUSSIAN,SUBLANG_RUSSIAN_RUSSIA},
-{"sk", LANG_SLOVAK,SUBLANG_NEUTRAL},
-{"sk_SK", LANG_SLOVAK,SUBLANG_SLOVAK_SLOVAKIA},
-{"sl", LANG_SLOVENIAN,SUBLANG_NEUTRAL},
-{"sl_SI", LANG_SLOVENIAN,SUBLANG_SLOVENIAN_SLOVENIA},
-{"sq", LANG_ALBANIAN,SUBLANG_NEUTRAL},
-{"sq_AL", LANG_ALBANIAN,SUBLANG_ALBANIAN_ALBANIA},
-{"sr", LANG_SERBIAN_NEUTRAL,SUBLANG_NEUTRAL},
-{"sv", LANG_SWEDISH,SUBLANG_NEUTRAL},
-{"sv_SE", LANG_SWEDISH,SUBLANG_SWEDISH},
-{"th", LANG_THAI,SUBLANG_NEUTRAL},
-{"th_TH", LANG_THAI,SUBLANG_THAI_THAILAND},
-{"tr", LANG_TURKISH,SUBLANG_NEUTRAL},
-{"tr_TR", LANG_TURKISH,SUBLANG_TURKISH_TURKEY},
-{"uk", LANG_UKRAINIAN,SUBLANG_NEUTRAL},
-{"uk_UA", LANG_UKRAINIAN,SUBLANG_UKRAINIAN_UKRAINE},
-{"vi", LANG_VIETNAMESE,SUBLANG_NEUTRAL},
-{"vi_VN", LANG_VIETNAMESE,SUBLANG_VIETNAMESE_VIETNAM},
-{"zh", LANG_CHINESE,SUBLANG_NEUTRAL},
-{"zh_CN", LANG_CHINESE,SUBLANG_CHINESE_SIMPLIFIED},
-{"zh_HK", LANG_CHINESE,SUBLANG_CHINESE_HONGKONG},
-{"zh_SG", LANG_CHINESE,SUBLANG_CHINESE_SINGAPORE},
-{0, 0,0},
+static const _WinLocale _win_locales[] = {
+ { "ar", LANG_ARABIC, SUBLANG_NEUTRAL },
+ { "ar_AE", LANG_ARABIC, SUBLANG_ARABIC_UAE },
+ { "ar_BH", LANG_ARABIC, SUBLANG_ARABIC_BAHRAIN },
+ { "ar_DZ", LANG_ARABIC, SUBLANG_ARABIC_ALGERIA },
+ { "ar_EG", LANG_ARABIC, SUBLANG_ARABIC_EGYPT },
+ { "ar_IQ", LANG_ARABIC, SUBLANG_ARABIC_IRAQ },
+ { "ar_JO", LANG_ARABIC, SUBLANG_ARABIC_JORDAN },
+ { "ar_KW", LANG_ARABIC, SUBLANG_ARABIC_KUWAIT },
+ { "ar_LB", LANG_ARABIC, SUBLANG_ARABIC_LEBANON },
+ { "ar_LY", LANG_ARABIC, SUBLANG_ARABIC_LIBYA },
+ { "ar_MA", LANG_ARABIC, SUBLANG_ARABIC_MOROCCO },
+ { "ar_OM", LANG_ARABIC, SUBLANG_ARABIC_OMAN },
+ { "ar_QA", LANG_ARABIC, SUBLANG_ARABIC_QATAR },
+ { "ar_SA", LANG_ARABIC, SUBLANG_ARABIC_SAUDI_ARABIA },
+ //no sudan
+ { "ar_SY", LANG_ARABIC, SUBLANG_ARABIC_SYRIA },
+ { "ar_TN", LANG_ARABIC, SUBLANG_ARABIC_TUNISIA },
+ { "ar_YE", LANG_ARABIC, SUBLANG_ARABIC_YEMEN },
+ { "be", LANG_BELARUSIAN, SUBLANG_NEUTRAL },
+ { "be_BY", LANG_BELARUSIAN, SUBLANG_BELARUSIAN_BELARUS },
+ { "bg", LANG_BULGARIAN, SUBLANG_NEUTRAL },
+ { "bg_BG", LANG_BULGARIAN, SUBLANG_BULGARIAN_BULGARIA },
+ { "ca", LANG_CATALAN, SUBLANG_NEUTRAL },
+ { "ca_ES", LANG_CATALAN, SUBLANG_CATALAN_CATALAN },
+ { "cs", LANG_CZECH, SUBLANG_NEUTRAL },
+ { "cs_CZ", LANG_CZECH, SUBLANG_CZECH_CZECH_REPUBLIC },
+ { "da", LANG_DANISH, SUBLANG_NEUTRAL },
+ { "da_DK", LANG_DANISH, SUBLANG_DANISH_DENMARK },
+ { "de", LANG_GERMAN, SUBLANG_NEUTRAL },
+ { "de_AT", LANG_GERMAN, SUBLANG_GERMAN_AUSTRIAN },
+ { "de_CH", LANG_GERMAN, SUBLANG_GERMAN_SWISS },
+ { "de_DE", LANG_GERMAN, SUBLANG_GERMAN },
+ { "de_LU", LANG_GERMAN, SUBLANG_GERMAN_LUXEMBOURG },
+ { "el", LANG_GREEK, SUBLANG_NEUTRAL },
+ { "el_GR", LANG_GREEK, SUBLANG_GREEK_GREECE },
+ //{"en_029", LANG_ENGLISH,SUBLANG_ENGLISH_CARIBBEAN},
+ { "en", LANG_ENGLISH, SUBLANG_NEUTRAL },
+ { "en_AU", LANG_ENGLISH, SUBLANG_ENGLISH_AUS },
+ { "en_CA", LANG_ENGLISH, SUBLANG_ENGLISH_CAN },
+ { "en_GB", LANG_ENGLISH, SUBLANG_ENGLISH_UK },
+ //{"en_IE", LANG_ENGLISH,SUBLANG_ENGLISH_IRELAND},
+ { "en_IN", LANG_ENGLISH, SUBLANG_ENGLISH_INDIA },
+ //MT
+ { "en_NZ", LANG_ENGLISH, SUBLANG_ENGLISH_NZ },
+ { "en_PH", LANG_ENGLISH, SUBLANG_ENGLISH_PHILIPPINES },
+ { "en_SG", LANG_ENGLISH, SUBLANG_ENGLISH_SINGAPORE },
+ { "en_US", LANG_ENGLISH, SUBLANG_ENGLISH_US },
+ { "en_ZA", LANG_ENGLISH, SUBLANG_ENGLISH_SOUTH_AFRICA },
+ { "es", LANG_SPANISH, SUBLANG_NEUTRAL },
+ { "es_AR", LANG_SPANISH, SUBLANG_SPANISH_ARGENTINA },
+ { "es_BO", LANG_SPANISH, SUBLANG_SPANISH_BOLIVIA },
+ { "es_CL", LANG_SPANISH, SUBLANG_SPANISH_CHILE },
+ { "es_CO", LANG_SPANISH, SUBLANG_SPANISH_COLOMBIA },
+ { "es_CR", LANG_SPANISH, SUBLANG_SPANISH_COSTA_RICA },
+ { "es_DO", LANG_SPANISH, SUBLANG_SPANISH_DOMINICAN_REPUBLIC },
+ { "es_EC", LANG_SPANISH, SUBLANG_SPANISH_ECUADOR },
+ { "es_ES", LANG_SPANISH, SUBLANG_SPANISH },
+ { "es_GT", LANG_SPANISH, SUBLANG_SPANISH_GUATEMALA },
+ { "es_HN", LANG_SPANISH, SUBLANG_SPANISH_HONDURAS },
+ { "es_MX", LANG_SPANISH, SUBLANG_SPANISH_MEXICAN },
+ { "es_NI", LANG_SPANISH, SUBLANG_SPANISH_NICARAGUA },
+ { "es_PA", LANG_SPANISH, SUBLANG_SPANISH_PANAMA },
+ { "es_PE", LANG_SPANISH, SUBLANG_SPANISH_PERU },
+ { "es_PR", LANG_SPANISH, SUBLANG_SPANISH_PUERTO_RICO },
+ { "es_PY", LANG_SPANISH, SUBLANG_SPANISH_PARAGUAY },
+ { "es_SV", LANG_SPANISH, SUBLANG_SPANISH_EL_SALVADOR },
+ { "es_US", LANG_SPANISH, SUBLANG_SPANISH_US },
+ { "es_UY", LANG_SPANISH, SUBLANG_SPANISH_URUGUAY },
+ { "es_VE", LANG_SPANISH, SUBLANG_SPANISH_VENEZUELA },
+ { "et", LANG_ESTONIAN, SUBLANG_NEUTRAL },
+ { "et_EE", LANG_ESTONIAN, SUBLANG_ESTONIAN_ESTONIA },
+ { "fi", LANG_FINNISH, SUBLANG_NEUTRAL },
+ { "fi_FI", LANG_FINNISH, SUBLANG_FINNISH_FINLAND },
+ { "fr", LANG_FRENCH, SUBLANG_NEUTRAL },
+ { "fr_BE", LANG_FRENCH, SUBLANG_FRENCH_BELGIAN },
+ { "fr_CA", LANG_FRENCH, SUBLANG_FRENCH_CANADIAN },
+ { "fr_CH", LANG_FRENCH, SUBLANG_FRENCH_SWISS },
+ { "fr_FR", LANG_FRENCH, SUBLANG_FRENCH },
+ { "fr_LU", LANG_FRENCH, SUBLANG_FRENCH_LUXEMBOURG },
+ { "ga", LANG_IRISH, SUBLANG_NEUTRAL },
+ { "ga_IE", LANG_IRISH, SUBLANG_IRISH_IRELAND },
+ { "hi", LANG_HINDI, SUBLANG_NEUTRAL },
+ { "hi_IN", LANG_HINDI, SUBLANG_HINDI_INDIA },
+ { "hr", LANG_CROATIAN, SUBLANG_NEUTRAL },
+ { "hr_HR", LANG_CROATIAN, SUBLANG_CROATIAN_CROATIA },
+ { "hu", LANG_HUNGARIAN, SUBLANG_NEUTRAL },
+ { "hu_HU", LANG_HUNGARIAN, SUBLANG_HUNGARIAN_HUNGARY },
+ { "in", LANG_ARMENIAN, SUBLANG_NEUTRAL },
+ { "in_ID", LANG_INDONESIAN, SUBLANG_INDONESIAN_INDONESIA },
+ { "is", LANG_ICELANDIC, SUBLANG_NEUTRAL },
+ { "is_IS", LANG_ICELANDIC, SUBLANG_ICELANDIC_ICELAND },
+ { "it", LANG_ITALIAN, SUBLANG_NEUTRAL },
+ { "it_CH", LANG_ITALIAN, SUBLANG_ITALIAN_SWISS },
+ { "it_IT", LANG_ITALIAN, SUBLANG_ITALIAN },
+ { "iw", LANG_HEBREW, SUBLANG_NEUTRAL },
+ { "iw_IL", LANG_HEBREW, SUBLANG_HEBREW_ISRAEL },
+ { "ja", LANG_JAPANESE, SUBLANG_NEUTRAL },
+ { "ja_JP", LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN },
+ { "ko", LANG_KOREAN, SUBLANG_NEUTRAL },
+ { "ko_KR", LANG_KOREAN, SUBLANG_KOREAN },
+ { "lt", LANG_LITHUANIAN, SUBLANG_NEUTRAL },
+ //{"lt_LT", LANG_LITHUANIAN,SUBLANG_LITHUANIAN_LITHUANIA},
+ { "lv", LANG_LATVIAN, SUBLANG_NEUTRAL },
+ { "lv_LV", LANG_LATVIAN, SUBLANG_LATVIAN_LATVIA },
+ { "mk", LANG_MACEDONIAN, SUBLANG_NEUTRAL },
+ { "mk_MK", LANG_MACEDONIAN, SUBLANG_MACEDONIAN_MACEDONIA },
+ { "ms", LANG_MALAY, SUBLANG_NEUTRAL },
+ { "ms_MY", LANG_MALAY, SUBLANG_MALAY_MALAYSIA },
+ { "mt", LANG_MALTESE, SUBLANG_NEUTRAL },
+ { "mt_MT", LANG_MALTESE, SUBLANG_MALTESE_MALTA },
+ { "nl", LANG_DUTCH, SUBLANG_NEUTRAL },
+ { "nl_BE", LANG_DUTCH, SUBLANG_DUTCH_BELGIAN },
+ { "nl_NL", LANG_DUTCH, SUBLANG_DUTCH },
+ { "no", LANG_NORWEGIAN, SUBLANG_NEUTRAL },
+ { "no_NO", LANG_NORWEGIAN, SUBLANG_NORWEGIAN_BOKMAL },
+ { "no_NO_NY", LANG_NORWEGIAN, SUBLANG_NORWEGIAN_NYNORSK },
+ { "pl", LANG_POLISH, SUBLANG_NEUTRAL },
+ { "pl_PL", LANG_POLISH, SUBLANG_POLISH_POLAND },
+ { "pt", LANG_PORTUGUESE, SUBLANG_NEUTRAL },
+ { "pt_BR", LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN },
+ { "pt_PT", LANG_PORTUGUESE, SUBLANG_PORTUGUESE },
+ { "ro", LANG_ROMANIAN, SUBLANG_NEUTRAL },
+ { "ro_RO", LANG_ROMANIAN, SUBLANG_ROMANIAN_ROMANIA },
+ { "ru", LANG_RUSSIAN, SUBLANG_NEUTRAL },
+ { "ru_RU", LANG_RUSSIAN, SUBLANG_RUSSIAN_RUSSIA },
+ { "sk", LANG_SLOVAK, SUBLANG_NEUTRAL },
+ { "sk_SK", LANG_SLOVAK, SUBLANG_SLOVAK_SLOVAKIA },
+ { "sl", LANG_SLOVENIAN, SUBLANG_NEUTRAL },
+ { "sl_SI", LANG_SLOVENIAN, SUBLANG_SLOVENIAN_SLOVENIA },
+ { "sq", LANG_ALBANIAN, SUBLANG_NEUTRAL },
+ { "sq_AL", LANG_ALBANIAN, SUBLANG_ALBANIAN_ALBANIA },
+ { "sr", LANG_SERBIAN_NEUTRAL, SUBLANG_NEUTRAL },
+ { "sv", LANG_SWEDISH, SUBLANG_NEUTRAL },
+ { "sv_SE", LANG_SWEDISH, SUBLANG_SWEDISH },
+ { "th", LANG_THAI, SUBLANG_NEUTRAL },
+ { "th_TH", LANG_THAI, SUBLANG_THAI_THAILAND },
+ { "tr", LANG_TURKISH, SUBLANG_NEUTRAL },
+ { "tr_TR", LANG_TURKISH, SUBLANG_TURKISH_TURKEY },
+ { "uk", LANG_UKRAINIAN, SUBLANG_NEUTRAL },
+ { "uk_UA", LANG_UKRAINIAN, SUBLANG_UKRAINIAN_UKRAINE },
+ { "vi", LANG_VIETNAMESE, SUBLANG_NEUTRAL },
+ { "vi_VN", LANG_VIETNAMESE, SUBLANG_VIETNAMESE_VIETNAM },
+ { "zh", LANG_CHINESE, SUBLANG_NEUTRAL },
+ { "zh_CN", LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED },
+ { "zh_HK", LANG_CHINESE, SUBLANG_CHINESE_HONGKONG },
+ { "zh_SG", LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE },
+ { 0, 0, 0 },
};
#endif // LANG_TABLE_H
diff --git a/platform/windows/os_windows.cpp b/platform/windows/os_windows.cpp
index 8a347e5f32..2046ae9f44 100644
--- a/platform/windows/os_windows.cpp
+++ b/platform/windows/os_windows.cpp
@@ -30,35 +30,35 @@
#include "os_windows.h"
#include "drivers/gles3/rasterizer_gles3.h"
-#include "drivers/windows/thread_windows.h"
-#include "drivers/windows/semaphore_windows.h"
+#include "drivers/windows/dir_access_windows.h"
+#include "drivers/windows/file_access_windows.h"
#include "drivers/windows/mutex_windows.h"
#include "drivers/windows/rw_lock_windows.h"
-#include "drivers/windows/file_access_windows.h"
-#include "drivers/windows/dir_access_windows.h"
-#include "servers/visual/visual_server_raster.h"
+#include "drivers/windows/semaphore_windows.h"
+#include "drivers/windows/thread_windows.h"
#include "servers/audio_server.h"
+#include "servers/visual/visual_server_raster.h"
//#include "servers/visual/visual_server_wrap_mt.h"
-#include "main/main.h"
-#include "tcp_server_winsock.h"
-#include "packet_peer_udp_winsock.h"
-#include "stream_peer_winsock.h"
-#include "lang_table.h"
#include "global_config.h"
#include "io/marshalls.h"
#include "joypad.h"
+#include "lang_table.h"
+#include "main/main.h"
+#include "packet_peer_udp_winsock.h"
+#include "stream_peer_winsock.h"
+#include "tcp_server_winsock.h"
-#include <shlobj.h>
-#include <regstr.h>
#include <process.h>
+#include <regstr.h>
+#include <shlobj.h>
static const WORD MAX_CONSOLE_LINES = 1500;
extern "C" {
#ifdef _MSC_VER
- _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
+_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
#else
- __attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
+__attribute__((visibility("default"))) DWORD NvOptimusEnablement = 0x00000001;
#endif
}
@@ -88,13 +88,13 @@ void RedirectIOToConsole() {
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
- &coninfo);
+ &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
- coninfo.dwSize);
+ coninfo.dwSize);
// redirect unbuffered STDOUT to the console
@@ -102,11 +102,11 @@ void RedirectIOToConsole() {
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
- fp = _fdopen( hConHandle, "w" );
+ fp = _fdopen(hConHandle, "w");
*stdout = *fp;
- setvbuf( stdout, NULL, _IONBF, 0 );
+ setvbuf(stdout, NULL, _IONBF, 0);
// redirect unbuffered STDIN to the console
@@ -114,11 +114,11 @@ void RedirectIOToConsole() {
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
- fp = _fdopen( hConHandle, "r" );
+ fp = _fdopen(hConHandle, "r");
*stdin = *fp;
- setvbuf( stdin, NULL, _IONBF, 0 );
+ setvbuf(stdin, NULL, _IONBF, 0);
// redirect unbuffered STDERR to the console
@@ -126,11 +126,11 @@ void RedirectIOToConsole() {
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
- fp = _fdopen( hConHandle, "w" );
+ fp = _fdopen(hConHandle, "w");
*stderr = *fp;
- setvbuf( stderr, NULL, _IONBF, 0 );
+ setvbuf(stderr, NULL, _IONBF, 0);
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
@@ -141,37 +141,35 @@ int OS_Windows::get_video_driver_count() const {
return 1;
}
-const char * OS_Windows::get_video_driver_name(int p_driver) const {
+const char *OS_Windows::get_video_driver_name(int p_driver) const {
return "GLES2";
}
OS::VideoMode OS_Windows::get_default_video_mode() const {
- return VideoMode(1024,600,false);
+ return VideoMode(1024, 600, false);
}
int OS_Windows::get_audio_driver_count() const {
return AudioDriverManager::get_driver_count();
}
-const char * OS_Windows::get_audio_driver_name(int p_driver) const {
+const char *OS_Windows::get_audio_driver_name(int p_driver) const {
- AudioDriver* driver = AudioDriverManager::get_driver(p_driver);
- ERR_FAIL_COND_V( !driver, "" );
+ AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
+ ERR_FAIL_COND_V(!driver, "");
return AudioDriverManager::get_driver(p_driver)->get_name();
}
-
void OS_Windows::initialize_core() {
-
- last_button_state=0;
+ last_button_state = 0;
//RedirectIOToConsole();
- maximized=false;
- minimized=false;
- borderless=false;
+ maximized = false;
+ minimized = false;
+ borderless = false;
ThreadWindows::make_default();
SemaphoreWindows::make_default();
@@ -190,9 +188,8 @@ void OS_Windows::initialize_core() {
StreamPeerWinsock::make_default();
PacketPeerUDPWinsock::make_default();
-
- // We need to know how often the clock is updated
- if( !QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second) )
+ // We need to know how often the clock is updated
+ if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticks_per_second))
ticks_per_second = 1000;
// If timeAtGameStart is 0 then we get the time since
// the start of the computer when we call GetGameTime()
@@ -203,9 +200,7 @@ void OS_Windows::initialize_core() {
IP_Unix::make_default();
- cursor_shape=CURSOR_ARROW;
-
-
+ cursor_shape = CURSOR_ARROW;
}
bool OS_Windows::can_draw() const {
@@ -215,20 +210,19 @@ bool OS_Windows::can_draw() const {
#define MI_WP_SIGNATURE 0xFF515700
#define SIGNATURE_MASK 0xFFFFFF00
-#define IsPenEvent(dw) (((dw) & SIGNATURE_MASK) == MI_WP_SIGNATURE)
-
+#define IsPenEvent(dw) (((dw)&SIGNATURE_MASK) == MI_WP_SIGNATURE)
void OS_Windows::_touch_event(bool p_pressed, int p_x, int p_y, int idx) {
InputEvent event;
event.type = InputEvent::SCREEN_TOUCH;
- event.ID=++last_id;
+ event.ID = ++last_id;
event.screen_touch.index = idx;
event.screen_touch.pressed = p_pressed;
- event.screen_touch.x=p_x;
- event.screen_touch.y=p_y;
+ event.screen_touch.x = p_x;
+ event.screen_touch.y = p_y;
if (main_loop) {
input->parse_input_event(event);
@@ -239,41 +233,38 @@ void OS_Windows::_drag_event(int p_x, int p_y, int idx) {
InputEvent event;
event.type = InputEvent::SCREEN_DRAG;
- event.ID=++last_id;
+ event.ID = ++last_id;
event.screen_drag.index = idx;
- event.screen_drag.x=p_x;
- event.screen_drag.y=p_y;
+ event.screen_drag.x = p_x;
+ event.screen_drag.y = p_y;
if (main_loop)
input->parse_input_event(event);
};
-LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
+LRESULT OS_Windows::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
-
- switch (uMsg) // Check For Windows Messages
+ switch (uMsg) // Check For Windows Messages
{
- case WM_SETFOCUS:
- {
+ case WM_SETFOCUS: {
window_has_focus = true;
// Re-capture cursor if we're in one of the capture modes
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
SetCapture(hWnd);
}
break;
}
- case WM_KILLFOCUS:
- {
+ case WM_KILLFOCUS: {
window_has_focus = false;
// Release capture if we're in one of the capture modes
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
ReleaseCapture();
}
break;
}
- case WM_ACTIVATE: // Watch For Window Activate Message
+ case WM_ACTIVATE: // Watch For Window Activate Message
{
minimized = HIWORD(wParam) != 0;
if (!main_loop) {
@@ -282,23 +273,23 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (LOWORD(wParam) == WA_ACTIVE || LOWORD(wParam) == WA_CLICKACTIVE) {
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
- alt_mem=false;
- control_mem=false;
- shift_mem=false;
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED) {
+ alt_mem = false;
+ control_mem = false;
+ shift_mem = false;
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
RECT clipRect;
GetClientRect(hWnd, &clipRect);
- ClientToScreen(hWnd, (POINT*) &clipRect.left);
- ClientToScreen(hWnd, (POINT*) &clipRect.right);
+ ClientToScreen(hWnd, (POINT *)&clipRect.left);
+ ClientToScreen(hWnd, (POINT *)&clipRect.right);
ClipCursor(&clipRect);
SetCapture(hWnd);
}
} else {
main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
- alt_mem=false;
+ alt_mem = false;
};
- return 0; // Return To The Message Loop
+ return 0; // Return To The Message Loop
}
case WM_PAINT:
@@ -306,32 +297,32 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
Main::force_redraw();
break;
- case WM_SYSCOMMAND: // Intercept System Commands
+ case WM_SYSCOMMAND: // Intercept System Commands
{
- switch (wParam) // Check System Calls
+ switch (wParam) // Check System Calls
{
- case SC_SCREENSAVE: // Screensaver Trying To Start?
- case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
- return 0; // Prevent From Happening
+ case SC_SCREENSAVE: // Screensaver Trying To Start?
+ case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
+ return 0; // Prevent From Happening
case SC_KEYMENU:
- if ((lParam>>16)<=0)
+ if ((lParam >> 16) <= 0)
return 0;
}
- break; // Exit
+ break; // Exit
}
- case WM_CLOSE: // Did We Receive A Close Message?
+ case WM_CLOSE: // Did We Receive A Close Message?
{
if (main_loop)
main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
//force_quit=true;
- return 0; // Jump Back
+ return 0; // Jump Back
}
case WM_MOUSELEAVE: {
- old_invalid=true;
- outside=true;
- if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
+ old_invalid = true;
+ outside = true;
+ if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
if (input)
input->set_mouse_in_window(false);
@@ -342,28 +333,27 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (outside) {
//mouse enter
- if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
+ if (main_loop && mouse_mode != MOUSE_MODE_CAPTURED)
main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
if (input)
input->set_mouse_in_window(true);
- CursorShape c=cursor_shape;
- cursor_shape=CURSOR_MAX;
+ CursorShape c = cursor_shape;
+ cursor_shape = CURSOR_MAX;
set_cursor_shape(c);
- outside=false;
+ outside = false;
//Once-Off notification, must call again....
TRACKMOUSEEVENT tme;
- tme.cbSize=sizeof(TRACKMOUSEEVENT);
- tme.dwFlags=TME_LEAVE;
- tme.hwndTrack=hWnd;
- tme.dwHoverTime=HOVER_DEFAULT;
+ tme.cbSize = sizeof(TRACKMOUSEEVENT);
+ tme.dwFlags = TME_LEAVE;
+ tme.hwndTrack = hWnd;
+ tme.dwHoverTime = HOVER_DEFAULT;
TrackMouseEvent(&tme);
-
}
// Don't calculate relative mouse movement if we don't have focus in CAPTURED mode.
- if (!window_has_focus && mouse_mode==MOUSE_MODE_CAPTURED)
+ if (!window_has_focus && mouse_mode == MOUSE_MODE_CAPTURED)
break;
/*
LPARAM extra = GetMessageExtraInfo();
@@ -378,64 +368,60 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
};
*/
-
InputEvent event;
- event.type=InputEvent::MOUSE_MOTION;
- event.ID=++last_id;
- InputEventMouseMotion &mm=event.mouse_motion;
-
- mm.mod.control=(wParam&MK_CONTROL)!=0;
- mm.mod.shift=(wParam&MK_SHIFT)!=0;
- mm.mod.alt=alt_mem;
-
- mm.button_mask|=(wParam&MK_LBUTTON)?(1<<0):0;
- mm.button_mask|=(wParam&MK_RBUTTON)?(1<<1):0;
- mm.button_mask|=(wParam&MK_MBUTTON)?(1<<2):0;
- last_button_state=mm.button_mask;
+ event.type = InputEvent::MOUSE_MOTION;
+ event.ID = ++last_id;
+ InputEventMouseMotion &mm = event.mouse_motion;
+
+ mm.mod.control = (wParam & MK_CONTROL) != 0;
+ mm.mod.shift = (wParam & MK_SHIFT) != 0;
+ mm.mod.alt = alt_mem;
+
+ mm.button_mask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
+ mm.button_mask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
+ mm.button_mask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
+ last_button_state = mm.button_mask;
/*mm.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
mm.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
- mm.x=GET_X_LPARAM(lParam);
- mm.y=GET_Y_LPARAM(lParam);
-
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
+ mm.x = GET_X_LPARAM(lParam);
+ mm.y = GET_Y_LPARAM(lParam);
- Point2i c(video_mode.width/2,video_mode.height/2);
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
+
+ Point2i c(video_mode.width / 2, video_mode.height / 2);
old_x = c.x;
old_y = c.y;
- if (Point2i(mm.x,mm.y)==c) {
- center=c;
+ if (Point2i(mm.x, mm.y) == c) {
+ center = c;
return 0;
}
- Point2i ncenter(mm.x,mm.y);
- center=ncenter;
- POINT pos = { (int) c.x, (int) c.y };
+ Point2i ncenter(mm.x, mm.y);
+ center = ncenter;
+ POINT pos = { (int)c.x, (int)c.y };
ClientToScreen(hWnd, &pos);
SetCursorPos(pos.x, pos.y);
-
}
- input->set_mouse_pos(Point2(mm.x,mm.y));
- mm.speed_x=input->get_last_mouse_speed().x;
- mm.speed_y=input->get_last_mouse_speed().y;
+ input->set_mouse_pos(Point2(mm.x, mm.y));
+ mm.speed_x = input->get_last_mouse_speed().x;
+ mm.speed_y = input->get_last_mouse_speed().y;
if (old_invalid) {
- old_x=mm.x;
- old_y=mm.y;
- old_invalid=false;
+ old_x = mm.x;
+ old_y = mm.y;
+ old_invalid = false;
}
- mm.relative_x=mm.x-old_x;
- mm.relative_y=mm.y-old_y;
- old_x=mm.x;
- old_y=mm.y;
+ mm.relative_x = mm.x - old_x;
+ mm.relative_y = mm.y - old_y;
+ old_x = mm.x;
+ old_y = mm.y;
if (window_has_focus && main_loop)
input->parse_input_event(event);
-
-
} break;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
@@ -447,10 +433,10 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
case WM_MOUSEHWHEEL:
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
- /*case WM_XBUTTONDOWN:
- case WM_XBUTTONUP: */{
+ /*case WM_XBUTTONDOWN:
+ case WM_XBUTTONUP: */ {
- /*
+ /*
LPARAM extra = GetMessageExtraInfo();
if (IsPenEvent(extra)) {
@@ -463,76 +449,74 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
};
*/
- InputEvent event;
- event.type=InputEvent::MOUSE_BUTTON;
- event.ID=++last_id;
- InputEventMouseButton &mb=event.mouse_button;
-
- switch (uMsg) {
- case WM_LBUTTONDOWN: {
- mb.pressed=true;
- mb.button_index=1;
- } break;
- case WM_LBUTTONUP: {
- mb.pressed=false;
- mb.button_index=1;
- } break;
- case WM_MBUTTONDOWN: {
- mb.pressed=true;
- mb.button_index=3;
-
- } break;
- case WM_MBUTTONUP: {
- mb.pressed=false;
- mb.button_index=3;
- } break;
- case WM_RBUTTONDOWN: {
- mb.pressed=true;
- mb.button_index=2;
- } break;
- case WM_RBUTTONUP: {
- mb.pressed=false;
- mb.button_index=2;
- } break;
- case WM_LBUTTONDBLCLK: {
-
- mb.pressed=true;
- mb.button_index=1;
- mb.doubleclick = true;
- } break;
- case WM_RBUTTONDBLCLK: {
-
- mb.pressed=true;
- mb.button_index=2;
- mb.doubleclick = true;
- } break;
- case WM_MOUSEWHEEL: {
-
- mb.pressed=true;
- int motion = (short)HIWORD(wParam);
- if (!motion)
- return 0;
-
-
- if (motion>0)
- mb.button_index= BUTTON_WHEEL_UP;
- else
- mb.button_index= BUTTON_WHEEL_DOWN;
-
-
- } break;
- case WM_MOUSEHWHEEL: {
-
- mb.pressed = true;
- int motion = (short)HIWORD(wParam);
- if (!motion)
- return 0;
-
- if (motion<0)
- mb.button_index = BUTTON_WHEEL_LEFT;
- else
- mb.button_index = BUTTON_WHEEL_RIGHT;
- } break;
+ InputEvent event;
+ event.type = InputEvent::MOUSE_BUTTON;
+ event.ID = ++last_id;
+ InputEventMouseButton &mb = event.mouse_button;
+
+ switch (uMsg) {
+ case WM_LBUTTONDOWN: {
+ mb.pressed = true;
+ mb.button_index = 1;
+ } break;
+ case WM_LBUTTONUP: {
+ mb.pressed = false;
+ mb.button_index = 1;
+ } break;
+ case WM_MBUTTONDOWN: {
+ mb.pressed = true;
+ mb.button_index = 3;
+
+ } break;
+ case WM_MBUTTONUP: {
+ mb.pressed = false;
+ mb.button_index = 3;
+ } break;
+ case WM_RBUTTONDOWN: {
+ mb.pressed = true;
+ mb.button_index = 2;
+ } break;
+ case WM_RBUTTONUP: {
+ mb.pressed = false;
+ mb.button_index = 2;
+ } break;
+ case WM_LBUTTONDBLCLK: {
+
+ mb.pressed = true;
+ mb.button_index = 1;
+ mb.doubleclick = true;
+ } break;
+ case WM_RBUTTONDBLCLK: {
+
+ mb.pressed = true;
+ mb.button_index = 2;
+ mb.doubleclick = true;
+ } break;
+ case WM_MOUSEWHEEL: {
+
+ mb.pressed = true;
+ int motion = (short)HIWORD(wParam);
+ if (!motion)
+ return 0;
+
+ if (motion > 0)
+ mb.button_index = BUTTON_WHEEL_UP;
+ else
+ mb.button_index = BUTTON_WHEEL_DOWN;
+
+ } break;
+ case WM_MOUSEHWHEEL: {
+
+ mb.pressed = true;
+ int motion = (short)HIWORD(wParam);
+ if (!motion)
+ return 0;
+
+ if (motion < 0)
+ mb.button_index = BUTTON_WHEEL_LEFT;
+ else
+ mb.button_index = BUTTON_WHEEL_RIGHT;
+ } break;
/*
case WM_XBUTTONDOWN: {
mb.pressed=true;
@@ -542,75 +526,68 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
mb.pressed=true;
mb.button_index=(HIWORD(wParam)==XBUTTON1)?6:7;
} break;*/
- default: { return 0; }
- }
-
+ default: { return 0; }
+ }
- mb.mod.control=(wParam&MK_CONTROL)!=0;
- mb.mod.shift=(wParam&MK_SHIFT)!=0;
- mb.mod.alt=alt_mem;
- //mb.mod.alt=(wParam&MK_MENU)!=0;
- mb.button_mask|=(wParam&MK_LBUTTON)?(1<<0):0;
- mb.button_mask|=(wParam&MK_RBUTTON)?(1<<1):0;
- mb.button_mask|=(wParam&MK_MBUTTON)?(1<<2):0;
+ mb.mod.control = (wParam & MK_CONTROL) != 0;
+ mb.mod.shift = (wParam & MK_SHIFT) != 0;
+ mb.mod.alt = alt_mem;
+ //mb.mod.alt=(wParam&MK_MENU)!=0;
+ mb.button_mask |= (wParam & MK_LBUTTON) ? (1 << 0) : 0;
+ mb.button_mask |= (wParam & MK_RBUTTON) ? (1 << 1) : 0;
+ mb.button_mask |= (wParam & MK_MBUTTON) ? (1 << 2) : 0;
- last_button_state=mb.button_mask;
- /*
+ last_button_state = mb.button_mask;
+ /*
mb.button_mask|=(wParam&MK_XBUTTON1)?(1<<5):0;
mb.button_mask|=(wParam&MK_XBUTTON2)?(1<<6):0;*/
- mb.x=GET_X_LPARAM(lParam);
- mb.y=GET_Y_LPARAM(lParam);
+ mb.x = GET_X_LPARAM(lParam);
+ mb.y = GET_Y_LPARAM(lParam);
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
- mb.x=old_x;
- mb.y=old_y;
- }
-
- mb.global_x=mb.x;
- mb.global_y=mb.y;
+ mb.x = old_x;
+ mb.y = old_y;
+ }
+ mb.global_x = mb.x;
+ mb.global_y = mb.y;
- if (uMsg != WM_MOUSEWHEEL) {
- if (mb.pressed) {
+ if (uMsg != WM_MOUSEWHEEL) {
+ if (mb.pressed) {
- if (++pressrc>0)
- SetCapture(hWnd);
- } else {
+ if (++pressrc > 0)
+ SetCapture(hWnd);
+ } else {
-
- if (--pressrc<=0) {
- ReleaseCapture();
- pressrc=0;
+ if (--pressrc <= 0) {
+ ReleaseCapture();
+ pressrc = 0;
+ }
}
+ } else if (mouse_mode != MOUSE_MODE_CAPTURED) {
+ // for reasons unknown to mankind, wheel comes in screen cordinates
+ POINT coords;
+ coords.x = mb.x;
+ coords.y = mb.y;
- }
- } else if (mouse_mode!=MOUSE_MODE_CAPTURED) {
- // for reasons unknown to mankind, wheel comes in screen cordinates
- POINT coords;
- coords.x = mb.x;
- coords.y = mb.y;
-
- ScreenToClient(hWnd, &coords);
+ ScreenToClient(hWnd, &coords);
- mb.x = coords.x;
- mb.y = coords.y;
- }
+ mb.x = coords.x;
+ mb.y = coords.y;
+ }
- if (main_loop) {
- input->parse_input_event(event);
- if (mb.pressed && mb.button_index>3) {
- //send release for mouse wheel
- mb.pressed=false;
- event.ID=++last_id;
+ if (main_loop) {
input->parse_input_event(event);
-
+ if (mb.pressed && mb.button_index > 3) {
+ //send release for mouse wheel
+ mb.pressed = false;
+ event.ID = ++last_id;
+ input->parse_input_event(event);
+ }
}
}
-
-
-
- } break;
+ break;
case WM_SIZE: {
int window_w = LOWORD(lParam);
@@ -623,7 +600,7 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
} break;
case WM_ENTERSIZEMOVE: {
- move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM,(TIMERPROC) NULL);
+ move_timer_id = SetTimer(hWnd, 1, USER_TIMER_MINIMUM, (TIMERPROC)NULL);
} break;
case WM_EXITSIZEMOVE: {
KillTimer(hWnd, move_timer_id);
@@ -640,15 +617,14 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
case WM_KEYUP:
case WM_KEYDOWN: {
-
- if (wParam==VK_SHIFT)
- shift_mem=uMsg==WM_KEYDOWN;
- if (wParam==VK_CONTROL)
- control_mem=uMsg==WM_KEYDOWN;
- if (wParam==VK_MENU) {
- alt_mem=(uMsg==WM_KEYDOWN || uMsg==WM_SYSKEYDOWN);
- if (lParam&(1<<24))
- gr_mem=alt_mem;
+ if (wParam == VK_SHIFT)
+ shift_mem = uMsg == WM_KEYDOWN;
+ if (wParam == VK_CONTROL)
+ control_mem = uMsg == WM_KEYDOWN;
+ if (wParam == VK_MENU) {
+ alt_mem = (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN);
+ if (lParam & (1 << 24))
+ gr_mem = alt_mem;
}
/*
@@ -656,7 +632,6 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
meta_mem=uMsg==WM_KEYDOWN;
*/
-
} //fallthrough
case WM_CHAR: {
@@ -664,17 +639,16 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
// Make sure we don't include modifiers for the modifier key itself.
KeyEvent ke;
- ke.mod_state.shift= (wParam != VK_SHIFT) ? shift_mem : false;
- ke.mod_state.alt= (! (wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
- ke.mod_state.control= (wParam != VK_CONTROL) ? control_mem : false;
- ke.mod_state.meta=meta_mem;
- ke.uMsg=uMsg;
-
- if (ke.uMsg==WM_SYSKEYDOWN)
- ke.uMsg=WM_KEYDOWN;
- if (ke.uMsg==WM_SYSKEYUP)
- ke.uMsg=WM_KEYUP;
+ ke.mod_state.shift = (wParam != VK_SHIFT) ? shift_mem : false;
+ ke.mod_state.alt = (!(wParam == VK_MENU && (uMsg == WM_KEYDOWN || uMsg == WM_SYSKEYDOWN))) ? alt_mem : false;
+ ke.mod_state.control = (wParam != VK_CONTROL) ? control_mem : false;
+ ke.mod_state.meta = meta_mem;
+ ke.uMsg = uMsg;
+ if (ke.uMsg == WM_SYSKEYDOWN)
+ ke.uMsg = WM_KEYDOWN;
+ if (ke.uMsg == WM_SYSKEYUP)
+ ke.uMsg = WM_KEYUP;
/*if (ke.uMsg==WM_KEYDOWN && alt_mem && uMsg!=WM_SYSKEYDOWN) {
//altgr hack for intl keyboards, not sure how good it is
@@ -684,10 +658,9 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
print_line("")
}*/
-
- ke.wParam=wParam;
- ke.lParam=lParam;
- key_event_buffer[key_event_pos++]=ke;
+ ke.wParam = wParam;
+ ke.lParam = lParam;
+ key_event_buffer[key_event_pos++] = ke;
} break;
case WM_INPUTLANGCHANGEREQUEST: {
@@ -695,15 +668,15 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
print_line("input lang change");
} break;
- #if WINVER >= 0x0601 // for windows 7
+#if WINVER >= 0x0601 // for windows 7
case WM_TOUCH: {
BOOL bHandled = FALSE;
UINT cInputs = LOWORD(wParam);
PTOUCHINPUT pInputs = memnew_arr(TOUCHINPUT, cInputs);
- if (pInputs){
- if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))){
- for (UINT i=0; i < cInputs; i++){
+ if (pInputs) {
+ if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs, sizeof(TOUCHINPUT))) {
+ for (UINT i = 0; i < cInputs; i++) {
TOUCHINPUT ti = pInputs[i];
//do something with each touch input entry
if (ti.dwFlags & TOUCHEVENTF_MOVE) {
@@ -715,11 +688,11 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
};
}
bHandled = TRUE;
- }else{
- /* handle the error here */
+ } else {
+ /* handle the error here */
}
memdelete_arr(pInputs);
- }else{
+ } else {
/* handle the error here, probably out of memory */
}
if (bHandled) {
@@ -729,22 +702,21 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
} break;
- #endif
+#endif
case WM_DEVICECHANGE: {
joypad->probe_joypads();
} break;
case WM_SETCURSOR: {
- if(LOWORD(lParam) == HTCLIENT) {
- if(window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
+ if (LOWORD(lParam) == HTCLIENT) {
+ if (window_has_focus && (mouse_mode == MOUSE_MODE_HIDDEN || mouse_mode == MOUSE_MODE_CAPTURED)) {
//Hide the cursor
- if(hCursor == NULL)
+ if (hCursor == NULL)
hCursor = SetCursor(NULL);
else
SetCursor(NULL);
- }
- else {
- if(hCursor != NULL) {
+ } else {
+ if (hCursor != NULL) {
SetCursor(hCursor);
hCursor = NULL;
}
@@ -755,30 +727,27 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
case WM_DROPFILES: {
HDROP hDropInfo = NULL;
- hDropInfo = (HDROP) wParam;
- const int buffsize=4096;
+ hDropInfo = (HDROP)wParam;
+ const int buffsize = 4096;
wchar_t buf[buffsize];
- int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF,NULL,0);
+ int fcount = DragQueryFileW(hDropInfo, 0xFFFFFFFF, NULL, 0);
Vector<String> files;
- for(int i=0;i<fcount;i++) {
+ for (int i = 0; i < fcount; i++) {
DragQueryFileW(hDropInfo, i, buf, buffsize);
- String file=buf;
+ String file = buf;
files.push_back(file);
}
if (files.size() && main_loop) {
- main_loop->drop_files(files,0);
+ main_loop->drop_files(files, 0);
}
-
} break;
-
-
default: {
if (user_proc) {
@@ -788,119 +757,102 @@ LRESULT OS_Windows::WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
};
}
- return DefWindowProcW(hWnd,uMsg,wParam,lParam);
-
+ return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
-LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) {
+LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
- OS_Windows *os_win = static_cast<OS_Windows*>(OS::get_singleton());
+ OS_Windows *os_win = static_cast<OS_Windows *>(OS::get_singleton());
if (os_win)
- return os_win->WndProc(hWnd,uMsg,wParam,lParam);
+ return os_win->WndProc(hWnd, uMsg, wParam, lParam);
else
- return DefWindowProcW(hWnd,uMsg,wParam,lParam);
-
+ return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
-
-
void OS_Windows::process_key_events() {
- for(int i=0;i<key_event_pos;i++) {
+ for (int i = 0; i < key_event_pos; i++) {
KeyEvent &ke = key_event_buffer[i];
- switch(ke.uMsg) {
+ switch (ke.uMsg) {
case WM_CHAR: {
- if ((i==0 && ke.uMsg==WM_CHAR) || (i>0 && key_event_buffer[i-1].uMsg==WM_CHAR))
- {
- InputEvent event;
- event.type=InputEvent::KEY;
- event.ID=++last_id;
- InputEventKey &k=event.key;
-
-
- k.mod=ke.mod_state;
- k.pressed=true;
- k.scancode=KeyMappingWindows::get_keysym(ke.wParam);
- k.unicode=ke.wParam;
- if (k.unicode && gr_mem) {
- k.mod.alt=false;
- k.mod.control=false;
- }
+ if ((i == 0 && ke.uMsg == WM_CHAR) || (i > 0 && key_event_buffer[i - 1].uMsg == WM_CHAR)) {
+ InputEvent event;
+ event.type = InputEvent::KEY;
+ event.ID = ++last_id;
+ InputEventKey &k = event.key;
+
+ k.mod = ke.mod_state;
+ k.pressed = true;
+ k.scancode = KeyMappingWindows::get_keysym(ke.wParam);
+ k.unicode = ke.wParam;
+ if (k.unicode && gr_mem) {
+ k.mod.alt = false;
+ k.mod.control = false;
+ }
- if (k.unicode<32)
- k.unicode=0;
+ if (k.unicode < 32)
+ k.unicode = 0;
- input->parse_input_event(event);
- }
+ input->parse_input_event(event);
+ }
//do nothing
} break;
case WM_KEYUP:
case WM_KEYDOWN: {
-
InputEvent event;
- event.type=InputEvent::KEY;
- event.ID=++last_id;
- InputEventKey &k=event.key;
+ event.type = InputEvent::KEY;
+ event.ID = ++last_id;
+ InputEventKey &k = event.key;
+ k.mod = ke.mod_state;
+ k.pressed = (ke.uMsg == WM_KEYDOWN);
- k.mod=ke.mod_state;
- k.pressed=(ke.uMsg==WM_KEYDOWN);
-
- k.scancode=KeyMappingWindows::get_keysym(ke.wParam);
- if (i+1 < key_event_pos && key_event_buffer[i+1].uMsg==WM_CHAR)
- k.unicode=key_event_buffer[i+1].wParam;
+ k.scancode = KeyMappingWindows::get_keysym(ke.wParam);
+ if (i + 1 < key_event_pos && key_event_buffer[i + 1].uMsg == WM_CHAR)
+ k.unicode = key_event_buffer[i + 1].wParam;
if (k.unicode && gr_mem) {
- k.mod.alt=false;
- k.mod.control=false;
+ k.mod.alt = false;
+ k.mod.control = false;
}
- if (k.unicode<32)
- k.unicode=0;
-
-
+ if (k.unicode < 32)
+ k.unicode = 0;
- k.echo=(ke.uMsg==WM_KEYDOWN && (ke.lParam&(1<<30)));
+ k.echo = (ke.uMsg == WM_KEYDOWN && (ke.lParam & (1 << 30)));
input->parse_input_event(event);
-
} break;
}
}
- key_event_pos=0;
+ key_event_pos = 0;
}
-enum _MonitorDpiType
-{
- MDT_Effective_DPI = 0,
- MDT_Angular_DPI = 1,
- MDT_Raw_DPI = 2,
- MDT_Default = MDT_Effective_DPI
+enum _MonitorDpiType {
+ MDT_Effective_DPI = 0,
+ MDT_Angular_DPI = 1,
+ MDT_Raw_DPI = 2,
+ MDT_Default = MDT_Effective_DPI
};
-
-static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType= MDT_Default)
-{
-
+static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType = MDT_Default) {
int dpiX = 96, dpiY = 96;
static HMODULE Shcore = NULL;
- typedef HRESULT (WINAPI* GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT *dpiX, UINT *dpiY);
+ typedef HRESULT(WINAPI * GetDPIForMonitor_t)(HMONITOR hmonitor, _MonitorDpiType dpiType, UINT * dpiX, UINT * dpiY);
static GetDPIForMonitor_t getDPIForMonitor = NULL;
- if (Shcore == NULL)
- {
+ if (Shcore == NULL) {
Shcore = LoadLibraryW(L"Shcore.dll");
getDPIForMonitor = Shcore ? (GetDPIForMonitor_t)GetProcAddress(Shcore, "GetDpiForMonitor") : NULL;
- if ((Shcore == NULL) || (getDPIForMonitor == NULL))
- {
+ if ((Shcore == NULL) || (getDPIForMonitor == NULL)) {
if (Shcore)
FreeLibrary(Shcore);
Shcore = (HMODULE)INVALID_HANDLE_VALUE;
@@ -910,49 +862,41 @@ static int QueryDpiForMonitor(HMONITOR hmon, _MonitorDpiType dpiType= MDT_Defaul
UINT x = 0, y = 0;
HRESULT hr = E_FAIL;
bool bSet = false;
- if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE))
- {
- hr = getDPIForMonitor(hmon, dpiType/*MDT_Effective_DPI*/, &x, &y);
- if (SUCCEEDED(hr) && (x > 0) && (y > 0))
- {
+ if (hmon && (Shcore != (HMODULE)INVALID_HANDLE_VALUE)) {
+ hr = getDPIForMonitor(hmon, dpiType /*MDT_Effective_DPI*/, &x, &y);
+ if (SUCCEEDED(hr) && (x > 0) && (y > 0)) {
dpiX = (int)x;
dpiY = (int)y;
}
- }
- else
- {
+ } else {
static int overallX = 0, overallY = 0;
- if (overallX <= 0 || overallY <= 0)
- {
+ if (overallX <= 0 || overallY <= 0) {
HDC hdc = GetDC(NULL);
- if (hdc)
- {
+ if (hdc) {
overallX = GetDeviceCaps(hdc, LOGPIXELSX);
overallY = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(NULL, hdc);
}
}
- if (overallX > 0 && overallY > 0)
- {
- dpiX = overallX; dpiY = overallY;
+ if (overallX > 0 && overallY > 0) {
+ dpiX = overallX;
+ dpiY = overallY;
}
}
-
- return (dpiX+dpiY)/2;
+ return (dpiX + dpiY) / 2;
}
-
-BOOL CALLBACK OS_Windows::MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
- OS_Windows *self=(OS_Windows*)OS::get_singleton();
+BOOL CALLBACK OS_Windows::MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
+ OS_Windows *self = (OS_Windows *)OS::get_singleton();
MonitorInfo minfo;
- minfo.hMonitor=hMonitor;
- minfo.hdcMonitor=hdcMonitor;
- minfo.rect.pos.x=lprcMonitor->left;
- minfo.rect.pos.y=lprcMonitor->top;
- minfo.rect.size.x=lprcMonitor->right - lprcMonitor->left;
- minfo.rect.size.y=lprcMonitor->bottom - lprcMonitor->top;
+ minfo.hMonitor = hMonitor;
+ minfo.hdcMonitor = hdcMonitor;
+ minfo.rect.pos.x = lprcMonitor->left;
+ minfo.rect.pos.y = lprcMonitor->top;
+ minfo.rect.size.x = lprcMonitor->right - lprcMonitor->left;
+ minfo.rect.size.y = lprcMonitor->bottom - lprcMonitor->top;
minfo.dpi = QueryDpiForMonitor(hMonitor);
@@ -961,59 +905,55 @@ BOOL CALLBACK OS_Windows::MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPR
return TRUE;
}
+void OS_Windows::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
-void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
-
-
+ main_loop = NULL;
+ outside = true;
+ window_has_focus = true;
+ WNDCLASSEXW wc;
- main_loop=NULL;
- outside=true;
- window_has_focus=true;
- WNDCLASSEXW wc;
-
- video_mode=p_desired;
+ video_mode = p_desired;
//printf("**************** desired %s, mode %s\n", p_desired.fullscreen?"true":"false", video_mode.fullscreen?"true":"false");
RECT WindowRect;
- WindowRect.left=0;
- WindowRect.right=video_mode.width;
- WindowRect.top=0;
- WindowRect.bottom=video_mode.height;
+ WindowRect.left = 0;
+ WindowRect.right = video_mode.width;
+ WindowRect.top = 0;
+ WindowRect.bottom = video_mode.height;
- memset(&wc,0,sizeof(WNDCLASSEXW));
- wc.cbSize=sizeof(WNDCLASSEXW);
- wc.style= CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
+ memset(&wc, 0, sizeof(WNDCLASSEXW));
+ wc.cbSize = sizeof(WNDCLASSEXW);
+ wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
wc.lpfnWndProc = (WNDPROC)::WndProc;
wc.cbClsExtra = 0;
- wc.cbWndExtra= 0;
+ wc.cbWndExtra = 0;
//wc.hInstance = hInstance;
wc.hInstance = godot_hinstance ? godot_hinstance : GetModuleHandle(NULL);
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
- wc.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW);
+ wc.hCursor = NULL; //LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = NULL;
- wc.lpszMenuName = NULL;
- wc.lpszClassName = L"Engine";
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = L"Engine";
if (!RegisterClassExW(&wc)) {
- MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
- return; // Return
+ MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return; // Return
}
+ EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, 0);
- EnumDisplayMonitors(NULL,NULL,MonitorEnumProc,0);
-
- print_line("DETECTED MONITORS: "+itos(monitor_info.size()));
- pre_fs_valid=true;
+ print_line("DETECTED MONITORS: " + itos(monitor_info.size()));
+ pre_fs_valid = true;
if (video_mode.fullscreen) {
DEVMODE current;
- memset(&current,0,sizeof(current));
+ memset(&current, 0, sizeof(current));
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &current);
- WindowRect.right = current.dmPelsWidth;
+ WindowRect.right = current.dmPelsWidth;
WindowRect.bottom = current.dmPelsHeight;
-/* DEVMODE dmScreenSettings;
+ /* DEVMODE dmScreenSettings;
memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
dmScreenSettings.dmSize=sizeof(dmScreenSettings);
dmScreenSettings.dmPelsWidth = video_mode.width;
@@ -1026,20 +966,20 @@ void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_
video_mode.fullscreen=false;
}*/
- pre_fs_valid=false;
+ pre_fs_valid = false;
}
- DWORD dwExStyle;
- DWORD dwStyle;
+ DWORD dwExStyle;
+ DWORD dwStyle;
- if (video_mode.fullscreen||video_mode.borderless_window) {
+ if (video_mode.fullscreen || video_mode.borderless_window) {
- dwExStyle=WS_EX_APPWINDOW;
- dwStyle=WS_POPUP;
+ dwExStyle = WS_EX_APPWINDOW;
+ dwStyle = WS_POPUP;
} else {
- dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
- dwStyle=WS_OVERLAPPEDWINDOW;
+ dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
+ dwStyle = WS_OVERLAPPEDWINDOW;
if (!video_mode.resizable) {
dwStyle &= ~WS_THICKFRAME;
dwStyle &= ~WS_MAXIMIZEBOX;
@@ -1048,16 +988,15 @@ void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);
-
- char* windowid = getenv("GODOT_WINDOWID");
+ char *windowid = getenv("GODOT_WINDOWID");
if (windowid) {
- // strtoull on mingw
- #ifdef MINGW_ENABLED
+// strtoull on mingw
+#ifdef MINGW_ENABLED
hWnd = (HWND)strtoull(windowid, NULL, 0);
- #else
+#else
hWnd = (HWND)_strtoui64(windowid, NULL, 0);
- #endif
+#endif
SetLastError(0);
user_proc = (WNDPROC)GetWindowLongPtr(hWnd, GWLP_WNDPROC);
SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)(WNDPROC)::WndProc);
@@ -1070,24 +1009,22 @@ void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_
RECT rect;
if (!GetClientRect(hWnd, &rect)) {
- MessageBoxW(NULL,L"Window Creation Error.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);
- return; // Return FALSE
+ MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return; // Return FALSE
};
video_mode.width = rect.right;
video_mode.height = rect.bottom;
video_mode.fullscreen = false;
} else {
- if (!(hWnd=CreateWindowExW(dwExStyle,L"Engine",L"", dwStyle|WS_CLIPSIBLINGS|WS_CLIPCHILDREN, (GetSystemMetrics(SM_CXSCREEN)-WindowRect.right)/2, (GetSystemMetrics(SM_CYSCREEN)-WindowRect.bottom)/2, WindowRect.right-WindowRect.left,WindowRect.bottom-WindowRect.top, NULL,NULL, hInstance,NULL))) {
- MessageBoxW(NULL,L"Window Creation Error.",L"ERROR",MB_OK|MB_ICONEXCLAMATION);
- return; // Return FALSE
+ if (!(hWnd = CreateWindowExW(dwExStyle, L"Engine", L"", dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2, (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, hInstance, NULL))) {
+ MessageBoxW(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
+ return; // Return FALSE
}
-
-
};
#if defined(OPENGL_ENABLED)
- gl_context = memnew( ContextGL_Win(hWnd,true) );
+ gl_context = memnew(ContextGL_Win(hWnd, true));
gl_context->initialize();
RasterizerGLES3::register_config();
@@ -1095,27 +1032,27 @@ void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_
RasterizerGLES3::make_current();
#endif
- visual_server = memnew( VisualServerRaster );
- // FIXME: Reimplement threaded rendering? Or remove?
+ visual_server = memnew(VisualServerRaster);
+ // FIXME: Reimplement threaded rendering? Or remove?
/*
if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {
visual_server =memnew(VisualServerWrapMT(visual_server,get_render_thread_mode()==RENDER_SEPARATE_THREAD));
}
*/
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
physics_2d_server->init();
if (!is_no_window_mode_enabled()) {
- ShowWindow(hWnd,SW_SHOW); // Show The Window
- SetForegroundWindow(hWnd); // Slightly Higher Priority
- SetFocus(hWnd); // Sets Keyboard Focus To
+ ShowWindow(hWnd, SW_SHOW); // Show The Window
+ SetForegroundWindow(hWnd); // Slightly Higher Priority
+ SetFocus(hWnd); // Sets Keyboard Focus To
}
-/*
+ /*
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
@@ -1131,35 +1068,35 @@ void OS_Windows::initialize(const VideoMode& p_desired,int p_video_driver,int p_
*/
visual_server->init();
- input = memnew( InputDefault );
- joypad = memnew (JoypadWindows(input, &hWnd));
+ input = memnew(InputDefault);
+ joypad = memnew(JoypadWindows(input, &hWnd));
- power_manager = memnew( PowerWindows );
+ power_manager = memnew(PowerWindows);
AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
- if (AudioDriverManager::get_driver(p_audio_driver)->init()!=OK) {
+ if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
ERR_PRINT("Initializing audio failed.");
}
TRACKMOUSEEVENT tme;
- tme.cbSize=sizeof(TRACKMOUSEEVENT);
- tme.dwFlags=TME_LEAVE;
- tme.hwndTrack=hWnd;
- tme.dwHoverTime=HOVER_DEFAULT;
+ tme.cbSize = sizeof(TRACKMOUSEEVENT);
+ tme.dwFlags = TME_LEAVE;
+ tme.hwndTrack = hWnd;
+ tme.dwHoverTime = HOVER_DEFAULT;
TrackMouseEvent(&tme);
//RegisterTouchWindow(hWnd, 0); // Windows 7
_ensure_data_dir();
- DragAcceptFiles(hWnd,true);
+ DragAcceptFiles(hWnd, true);
move_timer_id = 1;
}
-void OS_Windows::set_clipboard(const String& p_text) {
+void OS_Windows::set_clipboard(const String &p_text) {
if (!OpenClipboard(hWnd)) {
ERR_EXPLAIN("Unable to open clipboard.");
@@ -1212,7 +1149,7 @@ String OS_Windows::get_clipboard() const {
LPWSTR ptr = (LPWSTR)GlobalLock(mem);
if (ptr != NULL) {
- ret = String((CharType*)ptr);
+ ret = String((CharType *)ptr);
GlobalUnlock(mem);
};
};
@@ -1225,7 +1162,7 @@ String OS_Windows::get_clipboard() const {
LPTSTR ptr = (LPTSTR)GlobalLock(mem);
if (ptr != NULL) {
- ret.parse_utf8((const char*)ptr);
+ ret.parse_utf8((const char *)ptr);
GlobalUnlock(mem);
};
};
@@ -1236,26 +1173,25 @@ String OS_Windows::get_clipboard() const {
return ret;
};
-
void OS_Windows::delete_main_loop() {
if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
}
-void OS_Windows::set_main_loop( MainLoop * p_main_loop ) {
+void OS_Windows::set_main_loop(MainLoop *p_main_loop) {
input->set_main_loop(p_main_loop);
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
}
void OS_Windows::finalize() {
- if(main_loop)
+ if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
for (int i = 0; i < get_audio_driver_count(); i++) {
AudioDriverManager::get_driver(i)->finish();
@@ -1294,30 +1230,28 @@ void OS_Windows::finalize_core() {
memdelete(process_map);
-
TCPServerWinsock::cleanup();
StreamPeerWinsock::cleanup();
}
-void OS_Windows::vprint(const char* p_format, va_list p_list, bool p_stderr) {
+void OS_Windows::vprint(const char *p_format, va_list p_list, bool p_stderr) {
const unsigned int BUFFER_SIZE = 16384;
- char buf[BUFFER_SIZE+1]; // +1 for the terminating character
- int len = vsnprintf(buf,BUFFER_SIZE,p_format,p_list);
- if (len<=0)
+ char buf[BUFFER_SIZE + 1]; // +1 for the terminating character
+ int len = vsnprintf(buf, BUFFER_SIZE, p_format, p_list);
+ if (len <= 0)
return;
- if(len >= BUFFER_SIZE)
+ if (len >= BUFFER_SIZE)
len = BUFFER_SIZE; // Output is too big, will be truncated
- buf[len]=0;
-
+ buf[len] = 0;
- int wlen = MultiByteToWideChar(CP_UTF8,0,buf,len,NULL,0);
- if (wlen<0)
+ int wlen = MultiByteToWideChar(CP_UTF8, 0, buf, len, NULL, 0);
+ if (wlen < 0)
return;
- wchar_t *wbuf = (wchar_t*)malloc((len+1)*sizeof(wchar_t));
- MultiByteToWideChar(CP_UTF8,0,buf,len,wbuf,wlen);
- wbuf[wlen]=0;
+ wchar_t *wbuf = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
+ MultiByteToWideChar(CP_UTF8, 0, buf, len, wbuf, wlen);
+ wbuf[wlen] = 0;
if (p_stderr)
fwprintf(stderr, L"%ls", wbuf);
@@ -1325,36 +1259,36 @@ void OS_Windows::vprint(const char* p_format, va_list p_list, bool p_stderr) {
wprintf(L"%ls", wbuf);
#ifdef STDOUT_FILE
- //vwfprintf(stdo,p_format,p_list);
+//vwfprintf(stdo,p_format,p_list);
#endif
free(wbuf);
fflush(stdout);
};
-void OS_Windows::alert(const String& p_alert,const String& p_title) {
+void OS_Windows::alert(const String &p_alert, const String &p_title) {
if (!is_no_window_mode_enabled())
MessageBoxW(NULL, p_alert.c_str(), p_title.c_str(), MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
else
- print_line("ALERT: "+p_alert);
+ print_line("ALERT: " + p_alert);
}
void OS_Windows::set_mouse_mode(MouseMode p_mode) {
- if (mouse_mode==p_mode)
+ if (mouse_mode == p_mode)
return;
- mouse_mode=p_mode;
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED) {
+ mouse_mode = p_mode;
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
RECT clipRect;
GetClientRect(hWnd, &clipRect);
- ClientToScreen(hWnd, (POINT*) &clipRect.left);
- ClientToScreen(hWnd, (POINT*) &clipRect.right);
+ ClientToScreen(hWnd, (POINT *)&clipRect.left);
+ ClientToScreen(hWnd, (POINT *)&clipRect.right);
ClipCursor(&clipRect);
- center=Point2i(video_mode.width/2,video_mode.height/2);
- POINT pos = { (int) center.x, (int) center.y };
+ center = Point2i(video_mode.width / 2, video_mode.height / 2);
+ POINT pos = { (int)center.x, (int)center.y };
ClientToScreen(hWnd, &pos);
- if (mouse_mode==MOUSE_MODE_CAPTURED)
+ if (mouse_mode == MOUSE_MODE_CAPTURED)
SetCursorPos(pos.x, pos.y);
} else {
ReleaseCapture();
@@ -1368,28 +1302,25 @@ void OS_Windows::set_mouse_mode(MouseMode p_mode) {
}
}
-OS_Windows::MouseMode OS_Windows::get_mouse_mode() const{
-
+OS_Windows::MouseMode OS_Windows::get_mouse_mode() const {
return mouse_mode;
}
+void OS_Windows::warp_mouse_pos(const Point2 &p_to) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
-void OS_Windows::warp_mouse_pos(const Point2& p_to) {
-
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
-
- old_x=p_to.x;
- old_y=p_to.y;
+ old_x = p_to.x;
+ old_y = p_to.y;
} else {
POINT p;
- p.x=p_to.x;
- p.y=p_to.y;
- ClientToScreen(hWnd,&p);
+ p.x = p_to.x;
+ p.y = p_to.y;
+ ClientToScreen(hWnd, &p);
- SetCursorPos(p.x,p.y);
+ SetCursorPos(p.x, p.y);
}
}
@@ -1403,110 +1334,98 @@ int OS_Windows::get_mouse_button_state() const {
return last_button_state;
}
-void OS_Windows::set_window_title(const String& p_title) {
+void OS_Windows::set_window_title(const String &p_title) {
- SetWindowTextW(hWnd,p_title.c_str());
+ SetWindowTextW(hWnd, p_title.c_str());
}
-void OS_Windows::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
-
-
+void OS_Windows::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
}
OS::VideoMode OS_Windows::get_video_mode(int p_screen) const {
return video_mode;
}
-void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
-
-
+void OS_Windows::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
}
int OS_Windows::get_screen_count() const {
return monitor_info.size();
}
-int OS_Windows::get_current_screen() const{
+int OS_Windows::get_current_screen() const {
- HMONITOR monitor = MonitorFromWindow(hWnd,MONITOR_DEFAULTTONEAREST);
- for(int i=0;i<monitor_info.size();i++) {
- if (monitor_info[i].hMonitor==monitor)
+ HMONITOR monitor = MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST);
+ for (int i = 0; i < monitor_info.size(); i++) {
+ if (monitor_info[i].hMonitor == monitor)
return i;
}
return 0;
}
-void OS_Windows::set_current_screen(int p_screen){
+void OS_Windows::set_current_screen(int p_screen) {
- ERR_FAIL_INDEX(p_screen,monitor_info.size());
+ ERR_FAIL_INDEX(p_screen, monitor_info.size());
Vector2 ofs = get_window_position() - get_screen_position(get_current_screen());
- set_window_position(ofs+get_screen_position(p_screen));
-
+ set_window_position(ofs + get_screen_position(p_screen));
}
-Point2 OS_Windows::get_screen_position(int p_screen) const{
-
- ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),Point2());
- return Vector2( monitor_info[p_screen].rect.pos );
+Point2 OS_Windows::get_screen_position(int p_screen) const {
+ ERR_FAIL_INDEX_V(p_screen, monitor_info.size(), Point2());
+ return Vector2(monitor_info[p_screen].rect.pos);
}
-Size2 OS_Windows::get_screen_size(int p_screen) const{
-
- ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),Point2());
- return Vector2( monitor_info[p_screen].rect.size );
+Size2 OS_Windows::get_screen_size(int p_screen) const {
+ ERR_FAIL_INDEX_V(p_screen, monitor_info.size(), Point2());
+ return Vector2(monitor_info[p_screen].rect.size);
}
int OS_Windows::get_screen_dpi(int p_screen) const {
- ERR_FAIL_INDEX_V(p_screen,monitor_info.size(),72);
- UINT dpix,dpiy;
+ ERR_FAIL_INDEX_V(p_screen, monitor_info.size(), 72);
+ UINT dpix, dpiy;
return monitor_info[p_screen].dpi;
-
}
-Point2 OS_Windows::get_window_position() const{
+Point2 OS_Windows::get_window_position() const {
RECT r;
- GetWindowRect(hWnd,&r);
- return Point2(r.left,r.top);
+ GetWindowRect(hWnd, &r);
+ return Point2(r.left, r.top);
}
-void OS_Windows::set_window_position(const Point2& p_position){
+void OS_Windows::set_window_position(const Point2 &p_position) {
if (video_mode.fullscreen) return;
RECT r;
- GetWindowRect(hWnd,&r);
- MoveWindow(hWnd,p_position.x,p_position.y,r.right-r.left,r.bottom-r.top,TRUE);
-
+ GetWindowRect(hWnd, &r);
+ MoveWindow(hWnd, p_position.x, p_position.y, r.right - r.left, r.bottom - r.top, TRUE);
}
-Size2 OS_Windows::get_window_size() const{
+Size2 OS_Windows::get_window_size() const {
RECT r;
- GetClientRect(hWnd,&r);
- return Vector2(r.right-r.left,r.bottom-r.top);
-
+ GetClientRect(hWnd, &r);
+ return Vector2(r.right - r.left, r.bottom - r.top);
}
-void OS_Windows::set_window_size(const Size2 p_size){
+void OS_Windows::set_window_size(const Size2 p_size) {
- video_mode.width=p_size.width;
- video_mode.height=p_size.height;
+ video_mode.width = p_size.width;
+ video_mode.height = p_size.height;
if (video_mode.fullscreen) {
return;
}
-
RECT crect;
- GetClientRect(hWnd,&crect);
+ GetClientRect(hWnd, &crect);
RECT rect;
- GetWindowRect(hWnd,&rect);
- int dx = (rect.right-rect.left)-(crect.right-crect.left);
- int dy = (rect.bottom-rect.top)-(crect.bottom-crect.top);
-
- rect.right=rect.left+p_size.width+dx;
- rect.bottom=rect.top+p_size.height+dy;
+ GetWindowRect(hWnd, &rect);
+ int dx = (rect.right - rect.left) - (crect.right - crect.left);
+ int dy = (rect.bottom - rect.top) - (crect.bottom - crect.top);
+ rect.right = rect.left + p_size.width + dx;
+ rect.bottom = rect.top + p_size.height + dy;
//print_line("PRE: "+itos(rect.left)+","+itos(rect.top)+","+itos(rect.right-rect.left)+","+itos(rect.bottom-rect.top));
@@ -1518,73 +1437,65 @@ void OS_Windows::set_window_size(const Size2 p_size){
//print_line("POST: "+itos(rect.left)+","+itos(rect.top)+","+itos(rect.right-rect.left)+","+itos(rect.bottom-rect.top));
- MoveWindow(hWnd,rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top,TRUE);
-
+ MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
-void OS_Windows::set_window_fullscreen(bool p_enabled){
+void OS_Windows::set_window_fullscreen(bool p_enabled) {
- if (video_mode.fullscreen==p_enabled)
+ if (video_mode.fullscreen == p_enabled)
return;
-
-
if (p_enabled) {
-
if (pre_fs_valid) {
- GetWindowRect(hWnd,&pre_fs_rect);
+ GetWindowRect(hWnd, &pre_fs_rect);
//print_line("A: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
//MapWindowPoints(hWnd, GetParent(hWnd), (LPPOINT) &pre_fs_rect, 2);
//print_line("B: "+itos(pre_fs_rect.left)+","+itos(pre_fs_rect.top)+","+itos(pre_fs_rect.right-pre_fs_rect.left)+","+itos(pre_fs_rect.bottom-pre_fs_rect.top));
}
-
int cs = get_current_screen();
Point2 pos = get_screen_position(cs);
Size2 size = get_screen_size(cs);
- /* r.left = pos.x;
+ /* r.left = pos.x;
r.top = pos.y;
r.bottom = pos.y+size.y;
r.right = pos.x+size.x;
*/
SetWindowLongPtr(hWnd, GWL_STYLE,
- WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
+ WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE);
MoveWindow(hWnd, pos.x, pos.y, size.width, size.height, TRUE);
- video_mode.fullscreen=true;
-
+ video_mode.fullscreen = true;
} else {
RECT rect;
if (pre_fs_valid) {
- rect=pre_fs_rect;
+ rect = pre_fs_rect;
} else {
- rect.left=0;
- rect.right=video_mode.width;
- rect.top=0;
- rect.bottom=video_mode.height;
+ rect.left = 0;
+ rect.right = video_mode.width;
+ rect.top = 0;
+ rect.bottom = video_mode.height;
}
-
-
if (video_mode.resizable) {
SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
//AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE);
- MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
+ MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
} else {
SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_POPUPWINDOW | WS_VISIBLE);
//AdjustWindowRect(&rect, WS_CAPTION | WS_POPUPWINDOW, FALSE);
- MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
+ MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
- video_mode.fullscreen=false;
- pre_fs_valid=true;
-/*
+ video_mode.fullscreen = false;
+ pre_fs_valid = true;
+ /*
DWORD dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
DWORD dwStyle=WS_OVERLAPPEDWINDOW;
if (!video_mode.resizable) {
@@ -1599,18 +1510,16 @@ void OS_Windows::set_window_fullscreen(bool p_enabled){
}
//MoveWindow(hWnd,r.left,r.top,p_size.x,p_size.y,TRUE);
-
-
}
-bool OS_Windows::is_window_fullscreen() const{
+bool OS_Windows::is_window_fullscreen() const {
return video_mode.fullscreen;
}
-void OS_Windows::set_window_resizable(bool p_enabled){
+void OS_Windows::set_window_resizable(bool p_enabled) {
- if (video_mode.resizable==p_enabled)
+ if (video_mode.resizable == p_enabled)
return;
-/*
+ /*
GetWindowRect(hWnd,&pre_fs_rect);
DWORD dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
DWORD dwStyle=WS_OVERLAPPEDWINDOW;
@@ -1626,56 +1535,52 @@ void OS_Windows::set_window_resizable(bool p_enabled){
SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW | WS_VISIBLE);
} else {
SetWindowLongPtr(hWnd, GWL_STYLE, WS_CAPTION | WS_MINIMIZEBOX | WS_POPUPWINDOW | WS_VISIBLE);
-
}
RECT rect;
- GetWindowRect(hWnd,&rect);
- MoveWindow(hWnd, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
+ GetWindowRect(hWnd, &rect);
+ MoveWindow(hWnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
}
- video_mode.resizable=p_enabled;
-
+ video_mode.resizable = p_enabled;
}
-bool OS_Windows::is_window_resizable() const{
+bool OS_Windows::is_window_resizable() const {
return video_mode.resizable;
}
-void OS_Windows::set_window_minimized(bool p_enabled){
+void OS_Windows::set_window_minimized(bool p_enabled) {
if (p_enabled) {
- maximized=false;
- minimized=true;
- ShowWindow(hWnd,SW_MINIMIZE);
+ maximized = false;
+ minimized = true;
+ ShowWindow(hWnd, SW_MINIMIZE);
} else {
- ShowWindow(hWnd,SW_RESTORE);
- maximized=false;
- minimized=false;
+ ShowWindow(hWnd, SW_RESTORE);
+ maximized = false;
+ minimized = false;
}
}
-bool OS_Windows::is_window_minimized() const{
+bool OS_Windows::is_window_minimized() const {
return minimized;
-
}
-void OS_Windows::set_window_maximized(bool p_enabled){
+void OS_Windows::set_window_maximized(bool p_enabled) {
if (p_enabled) {
- maximized=true;
- minimized=false;
- ShowWindow(hWnd,SW_MAXIMIZE);
+ maximized = true;
+ minimized = false;
+ ShowWindow(hWnd, SW_MAXIMIZE);
} else {
- ShowWindow(hWnd,SW_RESTORE);
- maximized=false;
- minimized=false;
+ ShowWindow(hWnd, SW_RESTORE);
+ maximized = false;
+ minimized = false;
}
}
-bool OS_Windows::is_window_maximized() const{
+bool OS_Windows::is_window_maximized() const {
return maximized;
}
-
void OS_Windows::set_borderless_window(int p_borderless) {
video_mode.borderless_window = p_borderless;
}
@@ -1695,18 +1600,18 @@ void OS_Windows::request_attention() {
FlashWindowEx(&info);
}
-void OS_Windows::print_error(const char* p_function, const char* p_file, int p_line, const char* p_code, const char* p_rationale, ErrorType p_type) {
+void OS_Windows::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
if (!hCon || hCon == INVALID_HANDLE_VALUE) {
- const char* err_details;
+ const char *err_details;
if (p_rationale && p_rationale[0])
err_details = p_rationale;
else
err_details = p_code;
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR:
print("ERROR: %s: %s\n", p_function, err_details);
print(" At: %s:%i\n", p_file, p_line);
@@ -1734,7 +1639,7 @@ void OS_Windows::print_error(const char* p_function, const char* p_file, int p_l
WORD current_bg = sbi.wAttributes & (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
uint32_t basecol = 0;
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR: basecol = FOREGROUND_RED; break;
case ERR_WARNING: basecol = FOREGROUND_RED | FOREGROUND_GREEN; break;
case ERR_SCRIPT: basecol = FOREGROUND_RED | FOREGROUND_BLUE; break;
@@ -1746,7 +1651,7 @@ void OS_Windows::print_error(const char* p_function, const char* p_file, int p_l
if (p_rationale && p_rationale[0]) {
SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR: print("ERROR: "); break;
case ERR_WARNING: print("WARNING: "); break;
case ERR_SCRIPT: print("SCRIPT ERROR: "); break;
@@ -1770,7 +1675,7 @@ void OS_Windows::print_error(const char* p_function, const char* p_file, int p_l
} else {
SetConsoleTextAttribute(hCon, basecol | FOREGROUND_INTENSITY);
- switch(p_type) {
+ switch (p_type) {
case ERR_ERROR: print("ERROR: %s: ", p_function); break;
case ERR_WARNING: print("WARNING: %s: ", p_function); break;
case ERR_SCRIPT: print("SCRIPT ERROR: %s: ", p_function); break;
@@ -1796,7 +1701,6 @@ void OS_Windows::print_error(const char* p_function, const char* p_file, int p_l
}
}
-
String OS_Windows::get_name() {
return "Windows";
@@ -1811,11 +1715,11 @@ OS::Date OS_Windows::get_date(bool utc) const {
GetLocalTime(&systemtime);
Date date;
- date.day=systemtime.wDay;
- date.month=Month(systemtime.wMonth);
- date.weekday=Weekday(systemtime.wDayOfWeek);
- date.year=systemtime.wYear;
- date.dst=false;
+ date.day = systemtime.wDay;
+ date.month = Month(systemtime.wMonth);
+ date.weekday = Weekday(systemtime.wDayOfWeek);
+ date.year = systemtime.wYear;
+ date.dst = false;
return date;
}
OS::Time OS_Windows::get_time(bool utc) const {
@@ -1827,9 +1731,9 @@ OS::Time OS_Windows::get_time(bool utc) const {
GetLocalTime(&systemtime);
Time time;
- time.hour=systemtime.wHour;
- time.min=systemtime.wMinute;
- time.sec=systemtime.wSecond;
+ time.hour = systemtime.wHour;
+ time.min = systemtime.wMinute;
+ time.sec = systemtime.wSecond;
return time;
}
@@ -1869,80 +1773,74 @@ uint64_t OS_Windows::get_unix_time() const {
FILETIME fep;
SystemTimeToFileTime(&ep, &fep);
- return (*(uint64_t*)&ft - *(uint64_t*)&fep) / 10000000;
+ return (*(uint64_t *)&ft - *(uint64_t *)&fep) / 10000000;
};
uint64_t OS_Windows::get_system_time_secs() const {
-
const uint64_t WINDOWS_TICK = 10000000;
const uint64_t SEC_TO_UNIX_EPOCH = 11644473600LL;
SYSTEMTIME st;
GetSystemTime(&st);
FILETIME ft;
- SystemTimeToFileTime(&st,&ft);
+ SystemTimeToFileTime(&st, &ft);
uint64_t ret;
- ret=ft.dwHighDateTime;
- ret<<=32;
- ret|=ft.dwLowDateTime;
+ ret = ft.dwHighDateTime;
+ ret <<= 32;
+ ret |= ft.dwLowDateTime;
return (uint64_t)(ret / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
}
void OS_Windows::delay_usec(uint32_t p_usec) const {
- if (p_usec < 1000)
- Sleep(1);
- else
- Sleep(p_usec / 1000);
-
+ if (p_usec < 1000)
+ Sleep(1);
+ else
+ Sleep(p_usec / 1000);
}
uint64_t OS_Windows::get_ticks_usec() const {
- uint64_t ticks;
- uint64_t time;
- // This is the number of clock ticks since start
- if( !QueryPerformanceCounter((LARGE_INTEGER *)&ticks) )
- ticks = (UINT64)timeGetTime();
- // Divide by frequency to get the time in seconds
- time = ticks * 1000000L / ticks_per_second;
- // Subtract the time at game start to get
- // the time since the game started
- time -= ticks_start;
- return time;
+ uint64_t ticks;
+ uint64_t time;
+ // This is the number of clock ticks since start
+ if (!QueryPerformanceCounter((LARGE_INTEGER *)&ticks))
+ ticks = (UINT64)timeGetTime();
+ // Divide by frequency to get the time in seconds
+ time = ticks * 1000000L / ticks_per_second;
+ // Subtract the time at game start to get
+ // the time since the game started
+ time -= ticks_start;
+ return time;
}
-
void OS_Windows::process_events() {
MSG msg;
last_id = joypad->process_joypads(last_id);
- while(PeekMessageW(&msg,NULL,0,0,PM_REMOVE)) {
-
+ while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
-
}
process_key_events();
-
}
void OS_Windows::set_cursor_shape(CursorShape p_shape) {
- ERR_FAIL_INDEX(p_shape,CURSOR_MAX);
+ ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
- if (cursor_shape==p_shape)
+ if (cursor_shape == p_shape)
return;
- static const LPCTSTR win_cursors[CURSOR_MAX]={
+ static const LPCTSTR win_cursors[CURSOR_MAX] = {
IDC_ARROW,
IDC_IBEAM,
- IDC_HAND,//finger
+ IDC_HAND, //finger
IDC_CROSS,
IDC_WAIT,
IDC_APPSTARTING,
@@ -1959,50 +1857,48 @@ void OS_Windows::set_cursor_shape(CursorShape p_shape) {
IDC_HELP
};
- SetCursor(LoadCursor(hInstance,win_cursors[p_shape]));
- cursor_shape=p_shape;
+ SetCursor(LoadCursor(hInstance, win_cursors[p_shape]));
+ cursor_shape = p_shape;
}
-Error OS_Windows::execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id,String* r_pipe,int *r_exitcode) {
+Error OS_Windows::execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id, String *r_pipe, int *r_exitcode) {
if (p_blocking && r_pipe) {
-
String argss;
- argss="\"\""+p_path+"\"";
-
- for (const List<String>::Element* E=p_arguments.front(); E; E=E->next()) {
+ argss = "\"\"" + p_path + "\"";
+
+ for (const List<String>::Element *E = p_arguments.front(); E; E = E->next()) {
- argss+=String(" \"")+E->get()+"\"";
+ argss += String(" \"") + E->get() + "\"";
}
//print_line("ARGS: "+argss);
//argss+"\"";
//argss+=" 2>nul";
- FILE* f=_wpopen(argss.c_str(),L"r");
+ FILE *f = _wpopen(argss.c_str(), L"r");
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
char buf[65535];
- while(fgets(buf,65535,f)) {
+ while (fgets(buf, 65535, f)) {
- (*r_pipe)+=buf;
+ (*r_pipe) += buf;
}
int rv = _pclose(f);
if (r_exitcode)
- *r_exitcode=rv;
+ *r_exitcode = rv;
return OK;
}
- String cmdline = "\""+p_path+"\"";
- const List<String>::Element* I = p_arguments.front();
+ String cmdline = "\"" + p_path + "\"";
+ const List<String>::Element *I = p_arguments.front();
while (I) {
-
- cmdline += " \""+I->get() + "\"";
+ cmdline += " \"" + I->get() + "\"";
I = I->next();
};
@@ -2010,16 +1906,16 @@ Error OS_Windows::execute(const String& p_path, const List<String>& p_arguments,
//cmdline+="\"";
ProcessInfo pi;
- ZeroMemory( &pi.si, sizeof(pi.si) );
+ ZeroMemory(&pi.si, sizeof(pi.si));
pi.si.cb = sizeof(pi.si);
- ZeroMemory( &pi.pi, sizeof(pi.pi) );
- LPSTARTUPINFOW si_w = (LPSTARTUPINFOW) &pi.si;
+ ZeroMemory(&pi.pi, sizeof(pi.pi));
+ LPSTARTUPINFOW si_w = (LPSTARTUPINFOW)&pi.si;
- print_line("running cmdline: "+cmdline);
+ print_line("running cmdline: " + cmdline);
Vector<CharType> modstr; //windows wants to change this no idea why
modstr.resize(cmdline.size());
- for(int i=0;i<cmdline.size();i++)
- modstr[i]=cmdline[i];
+ for (int i = 0; i < cmdline.size(); i++)
+ modstr[i] = cmdline[i];
int ret = CreateProcessW(NULL, modstr.ptr(), NULL, NULL, 0, NORMAL_PRIORITY_CLASS, NULL, NULL, si_w, &pi.pi);
ERR_FAIL_COND_V(ret == 0, ERR_CANT_FORK);
@@ -2027,7 +1923,7 @@ Error OS_Windows::execute(const String& p_path, const List<String>& p_arguments,
DWORD ret = WaitForSingleObject(pi.pi.hProcess, INFINITE);
if (r_exitcode)
- *r_exitcode=ret;
+ *r_exitcode = ret;
} else {
@@ -2040,7 +1936,7 @@ Error OS_Windows::execute(const String& p_path, const List<String>& p_arguments,
return OK;
};
-Error OS_Windows::kill(const ProcessID& p_pid) {
+Error OS_Windows::kill(const ProcessID &p_pid) {
HANDLE h;
@@ -2054,16 +1950,16 @@ Error OS_Windows::kill(const ProcessID& p_pid) {
int ret = TerminateProcess(h, 0);
- return ret != 0?OK:FAILED;
+ return ret != 0 ? OK : FAILED;
};
int OS_Windows::get_process_ID() const {
return _getpid();
}
-Error OS_Windows::set_cwd(const String& p_cwd) {
+Error OS_Windows::set_cwd(const String &p_cwd) {
- if (_wchdir(p_cwd.c_str())!=0)
+ if (_wchdir(p_cwd.c_str()) != 0)
return ERR_CANT_OPEN;
return OK;
@@ -2072,17 +1968,16 @@ Error OS_Windows::set_cwd(const String& p_cwd) {
String OS_Windows::get_executable_path() const {
wchar_t bufname[4096];
- GetModuleFileNameW(NULL,bufname,4096);
- String s= bufname;
- print_line("EXEC PATHP??: "+s);
+ GetModuleFileNameW(NULL, bufname, 4096);
+ String s = bufname;
+ print_line("EXEC PATHP??: " + s);
return s;
}
-void OS_Windows::set_icon(const Image& p_icon) {
+void OS_Windows::set_icon(const Image &p_icon) {
-
- Image icon=p_icon;
- if (icon.get_format()!=Image::FORMAT_RGBA8)
+ Image icon = p_icon;
+ if (icon.get_format() != Image::FORMAT_RGBA8)
icon.convert(Image::FORMAT_RGBA8);
int w = icon.get_width();
int h = icon.get_height();
@@ -2093,55 +1988,53 @@ void OS_Windows::set_icon(const Image& p_icon) {
v.resize(icon_len);
BYTE *icon_bmp = &v[0];
- encode_uint32(40,&icon_bmp[0]);
- encode_uint32(w,&icon_bmp[4]);
- encode_uint32(h*2,&icon_bmp[8]);
- encode_uint16(1,&icon_bmp[12]);
- encode_uint16(32,&icon_bmp[14]);
- encode_uint32(BI_RGB,&icon_bmp[16]);
- encode_uint32(w*h*4,&icon_bmp[20]);
- encode_uint32(0,&icon_bmp[24]);
- encode_uint32(0,&icon_bmp[28]);
- encode_uint32(0,&icon_bmp[32]);
- encode_uint32(0,&icon_bmp[36]);
-
- uint8_t *wr=&icon_bmp[40];
- PoolVector<uint8_t>::Read r= icon.get_data().read();
-
- for(int i=0;i<h;i++) {
-
- for(int j=0;j<w;j++) {
-
- const uint8_t *rpx = &r[((h-i-1)*w+j)*4];
- uint8_t *wpx = &wr[(i*w+j)*4];
- wpx[0]=rpx[2];
- wpx[1]=rpx[1];
- wpx[2]=rpx[0];
- wpx[3]=rpx[3];
+ encode_uint32(40, &icon_bmp[0]);
+ encode_uint32(w, &icon_bmp[4]);
+ encode_uint32(h * 2, &icon_bmp[8]);
+ encode_uint16(1, &icon_bmp[12]);
+ encode_uint16(32, &icon_bmp[14]);
+ encode_uint32(BI_RGB, &icon_bmp[16]);
+ encode_uint32(w * h * 4, &icon_bmp[20]);
+ encode_uint32(0, &icon_bmp[24]);
+ encode_uint32(0, &icon_bmp[28]);
+ encode_uint32(0, &icon_bmp[32]);
+ encode_uint32(0, &icon_bmp[36]);
+
+ uint8_t *wr = &icon_bmp[40];
+ PoolVector<uint8_t>::Read r = icon.get_data().read();
+
+ for (int i = 0; i < h; i++) {
+
+ for (int j = 0; j < w; j++) {
+
+ const uint8_t *rpx = &r[((h - i - 1) * w + j) * 4];
+ uint8_t *wpx = &wr[(i * w + j) * 4];
+ wpx[0] = rpx[2];
+ wpx[1] = rpx[1];
+ wpx[2] = rpx[0];
+ wpx[3] = rpx[3];
}
}
-
HICON hicon = CreateIconFromResource(icon_bmp, icon_len, TRUE, 0x00030000);
/* Set the icon for the window */
- SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
+ SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hicon);
/* Set the icon in the task manager (should we do this?) */
- SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
+ SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hicon);
}
-
-bool OS_Windows::has_environment(const String& p_var) const {
+bool OS_Windows::has_environment(const String &p_var) const {
return getenv(p_var.utf8().get_data()) != NULL;
};
-String OS_Windows::get_environment(const String& p_var) const {
+String OS_Windows::get_environment(const String &p_var) const {
wchar_t wval[0x7Fff]; // MSDN says 32767 char is the maximum
- int wlen = GetEnvironmentVariableW(p_var.c_str(),wval,0x7Fff);
- if ( wlen > 0 ) {
+ int wlen = GetEnvironmentVariableW(p_var.c_str(), wval, 0x7Fff);
+ if (wlen > 0) {
return wval;
}
return "";
@@ -2151,23 +2044,20 @@ String OS_Windows::get_stdin_string(bool p_block) {
if (p_block) {
char buff[1024];
- return fgets(buff,1024,stdin);
+ return fgets(buff, 1024, stdin);
};
return String();
}
-
void OS_Windows::enable_for_stealing_focus(ProcessID pid) {
AllowSetForegroundWindow(pid);
-
}
void OS_Windows::move_window_to_foreground() {
SetForegroundWindow(hWnd);
-
}
Error OS_Windows::shell_open(String p_uri) {
@@ -2176,38 +2066,35 @@ Error OS_Windows::shell_open(String p_uri) {
return OK;
}
-
String OS_Windows::get_locale() const {
const _WinLocale *wl = &_win_locales[0];
LANGID langid = GetUserDefaultUILanguage();
String neutral;
- int lang = langid&((1<<9)-1);
- int sublang = langid&~((1<<9)-1);
+ int lang = langid & ((1 << 9) - 1);
+ int sublang = langid & ~((1 << 9) - 1);
- while(wl->locale) {
+ while (wl->locale) {
- if (wl->main_lang==lang && wl->sublang==SUBLANG_NEUTRAL)
- neutral=wl->locale;
+ if (wl->main_lang == lang && wl->sublang == SUBLANG_NEUTRAL)
+ neutral = wl->locale;
- if (lang==wl->main_lang && sublang==wl->sublang)
+ if (lang == wl->main_lang && sublang == wl->sublang)
return wl->locale;
-
wl++;
}
- if (neutral!="")
+ if (neutral != "")
return neutral;
return "en";
}
-
OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
-
- unsigned long azerty[] = {
+
+ unsigned long azerty[] = {
0x00020401, // Arabic (102) AZERTY
0x0001080c, // Belgian (Comma)
0x0000080c, // Belgian French
@@ -2240,27 +2127,28 @@ OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
0 // <--- STOP MARK
};
- char name[ KL_NAMELENGTH + 1 ]; name[0] = 0;
- GetKeyboardLayoutNameA( name );
+ char name[KL_NAMELENGTH + 1];
+ name[0] = 0;
+ GetKeyboardLayoutNameA(name);
unsigned long hex = strtoul(name, NULL, 16);
- int i=0;
- while( azerty[i] != 0 ) {
+ int i = 0;
+ while (azerty[i] != 0) {
if (azerty[i] == hex) return LATIN_KEYBOARD_AZERTY;
i++;
}
i = 0;
- while( qwertz[i] != 0 ) {
+ while (qwertz[i] != 0) {
if (qwertz[i] == hex) return LATIN_KEYBOARD_QWERTZ;
i++;
}
-
+
i = 0;
- while( dvorak[i] != 0 ) {
+ while (dvorak[i] != 0) {
if (dvorak[i] == hex) return LATIN_KEYBOARD_DVORAK;
- i++;
+ i++;
}
return LATIN_KEYBOARD_QWERTY;
@@ -2269,7 +2157,6 @@ OS::LatinKeyboardVariant OS_Windows::get_latin_keyboard_variant() const {
void OS_Windows::release_rendering_thread() {
gl_context->release_current();
-
}
void OS_Windows::make_rendering_thread() {
@@ -2282,7 +2169,6 @@ void OS_Windows::swap_buffers() {
gl_context->swap_buffers();
}
-
void OS_Windows::run() {
if (!main_loop)
@@ -2290,24 +2176,21 @@ void OS_Windows::run() {
main_loop->init();
- uint64_t last_ticks=get_ticks_usec();
+ uint64_t last_ticks = get_ticks_usec();
- int frames=0;
- uint64_t frame=0;
+ int frames = 0;
+ uint64_t frame = 0;
while (!force_quit) {
process_events(); // get rid of pending events
- if (Main::iteration()==true)
+ if (Main::iteration() == true)
break;
};
main_loop->finish();
-
}
-
-
MainLoop *OS_Windows::get_main_loop() const {
return main_loop;
@@ -2315,62 +2198,56 @@ MainLoop *OS_Windows::get_main_loop() const {
String OS_Windows::get_system_dir(SystemDir p_dir) const {
-
int id;
-
-
- switch(p_dir) {
+ switch (p_dir) {
case SYSTEM_DIR_DESKTOP: {
- id=CSIDL_DESKTOPDIRECTORY;
+ id = CSIDL_DESKTOPDIRECTORY;
} break;
case SYSTEM_DIR_DCIM: {
- id=CSIDL_MYPICTURES;
+ id = CSIDL_MYPICTURES;
} break;
case SYSTEM_DIR_DOCUMENTS: {
- id=CSIDL_PERSONAL;
+ id = CSIDL_PERSONAL;
} break;
case SYSTEM_DIR_DOWNLOADS: {
- id=0x000C ;
+ id = 0x000C;
} break;
case SYSTEM_DIR_MOVIES: {
- id=CSIDL_MYVIDEO;
+ id = CSIDL_MYVIDEO;
} break;
case SYSTEM_DIR_MUSIC: {
- id=CSIDL_MYMUSIC;
+ id = CSIDL_MYMUSIC;
} break;
case SYSTEM_DIR_PICTURES: {
- id=CSIDL_MYPICTURES;
+ id = CSIDL_MYPICTURES;
} break;
case SYSTEM_DIR_RINGTONES: {
- id=CSIDL_MYMUSIC;
+ id = CSIDL_MYMUSIC;
} break;
}
WCHAR szPath[MAX_PATH];
- HRESULT res = SHGetFolderPathW(NULL,id,NULL,0,szPath);
- ERR_FAIL_COND_V(res!=S_OK,String());
+ HRESULT res = SHGetFolderPathW(NULL, id, NULL, 0, szPath);
+ ERR_FAIL_COND_V(res != S_OK, String());
return String(szPath);
-
}
String OS_Windows::get_data_dir() const {
String an = get_safe_application_name();
- if (an!="") {
+ if (an != "") {
if (has_environment("APPDATA")) {
bool use_godot = GlobalConfig::get_singleton()->get("application/use_shared_user_dir");
if (!use_godot)
- return (OS::get_singleton()->get_environment("APPDATA")+"/"+an).replace("\\","/");
+ return (OS::get_singleton()->get_environment("APPDATA") + "/" + an).replace("\\", "/");
else
- return (OS::get_singleton()->get_environment("APPDATA")+"/Godot/app_userdata/"+an).replace("\\","/");
+ return (OS::get_singleton()->get_environment("APPDATA") + "/Godot/app_userdata/" + an).replace("\\", "/");
}
}
return GlobalConfig::get_singleton()->get_resource_path();
-
-
}
bool OS_Windows::is_joy_known(int p_device) {
@@ -2387,7 +2264,7 @@ void OS_Windows::set_use_vsync(bool p_enable) {
gl_context->set_use_vsync(p_enable);
}
-bool OS_Windows::is_vsync_enabled() const{
+bool OS_Windows::is_vsync_enabled() const {
if (gl_context)
return gl_context->is_using_vsync();
@@ -2407,30 +2284,29 @@ int OS_Windows::get_power_percent_left() {
return power_manager->get_power_percent_left();
}
-bool OS_Windows::check_feature_support(const String& p_feature) {
+bool OS_Windows::check_feature_support(const String &p_feature) {
return VisualServer::get_singleton()->has_os_feature(p_feature);
-
}
OS_Windows::OS_Windows(HINSTANCE _hInstance) {
- key_event_pos=0;
- force_quit=false;
- alt_mem=false;
- gr_mem=false;
- shift_mem=false;
- control_mem=false;
- meta_mem=false;
+ key_event_pos = 0;
+ force_quit = false;
+ alt_mem = false;
+ gr_mem = false;
+ shift_mem = false;
+ control_mem = false;
+ meta_mem = false;
minimized = false;
- hInstance=_hInstance;
- pressrc=0;
- old_invalid=true;
- last_id=0;
- mouse_mode=MOUSE_MODE_VISIBLE;
+ hInstance = _hInstance;
+ pressrc = 0;
+ old_invalid = true;
+ last_id = 0;
+ mouse_mode = MOUSE_MODE_VISIBLE;
#ifdef STDOUT_FILE
- stdo=fopen("stdout.txt","wb");
+ stdo = fopen("stdout.txt", "wb");
#endif
user_proc = NULL;
@@ -2440,15 +2316,10 @@ OS_Windows::OS_Windows(HINSTANCE _hInstance) {
#ifdef XAUDIO2_ENABLED
AudioDriverManager::add_driver(&driver_xaudio2);
#endif
-
}
-
-OS_Windows::~OS_Windows()
-{
+OS_Windows::~OS_Windows() {
#ifdef STDOUT_FILE
fclose(stdo);
#endif
}
-
-
diff --git a/platform/windows/os_windows.h b/platform/windows/os_windows.h
index c8cacac7a2..e7376d6800 100644
--- a/platform/windows/os_windows.h
+++ b/platform/windows/os_windows.h
@@ -29,30 +29,29 @@
#ifndef OS_WINDOWS_H
#define OS_WINDOWS_H
+#include "context_gl_win.h"
+#include "drivers/rtaudio/audio_driver_rtaudio.h"
#include "os/input.h"
#include "os/os.h"
#include "power_windows.h"
-#include "context_gl_win.h"
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
-#include "servers/physics/physics_server_sw.h"
#include "servers/audio_server.h"
-#include "drivers/rtaudio/audio_driver_rtaudio.h"
+#include "servers/physics/physics_server_sw.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
#ifdef XAUDIO2_ENABLED
#include "drivers/xaudio2/audio_driver_xaudio2.h"
#endif
#include "drivers/unix/ip_unix.h"
+#include "key_mapping_win.h"
+#include "main/input_default.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
-#include "main/input_default.h"
-#include "key_mapping_win.h"
-
-#include <windows.h>
-#include <windowsx.h>
-#include <io.h>
#include <fcntl.h>
+#include <io.h>
#include <stdio.h>
+#include <windows.h>
+#include <windowsx.h>
/**
@author Juan Linietsky <reduzio@gmail.com>
@@ -60,33 +59,29 @@
class JoypadWindows;
class OS_Windows : public OS {
- enum {
- KEY_EVENT_BUFFER_SIZE=512
+ enum {
+ KEY_EVENT_BUFFER_SIZE = 512
};
FILE *stdo;
-
struct KeyEvent {
InputModifierState mod_state;
UINT uMsg;
- WPARAM wParam;
- LPARAM lParam;
-
+ WPARAM wParam;
+ LPARAM lParam;
};
KeyEvent key_event_buffer[KEY_EVENT_BUFFER_SIZE];
int key_event_pos;
-
uint64_t ticks_start;
uint64_t ticks_per_second;
-
- bool old_invalid;
- bool outside;
- int old_x,old_y;
+ bool old_invalid;
+ bool outside;
+ int old_x, old_y;
Point2i center;
unsigned int last_id;
#if defined(OPENGL_ENABLED)
@@ -96,8 +91,8 @@ class OS_Windows : public OS {
PhysicsServer *physics_server;
Physics2DServer *physics_2d_server;
int pressrc;
- HDC hDC; // Private GDI Device Context
- HINSTANCE hInstance; // Holds The Instance Of The Application
+ HDC hDC; // Private GDI Device Context
+ HINSTANCE hInstance; // Holds The Instance Of The Application
HWND hWnd;
uint32_t move_timer_id;
@@ -141,17 +136,17 @@ class OS_Windows : public OS {
// functions used by main to initialize/deintialize the OS
protected:
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
virtual void initialize_core();
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
- virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual void set_main_loop(MainLoop *p_main_loop);
virtual void delete_main_loop();
virtual void finalize();
@@ -165,15 +160,13 @@ protected:
STARTUPINFO si;
PROCESS_INFORMATION pi;
};
- Map<ProcessID, ProcessInfo>* process_map;
+ Map<ProcessID, ProcessInfo> *process_map;
struct MonitorInfo {
HMONITOR hMonitor;
HDC hdcMonitor;
Rect2 rect;
int dpi;
-
-
};
bool pre_fs_valid;
@@ -183,40 +176,38 @@ protected:
bool minimized;
bool borderless;
- static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData);
-
+ static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData);
public:
- LRESULT WndProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam);
+ LRESULT WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ void print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type);
- void print_error(const char* p_function,const char* p_file,int p_line,const char *p_code,const char*p_rationale,ErrorType p_type);
-
- virtual void vprint(const char *p_format, va_list p_list, bool p_stderr=false);
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
+ virtual void vprint(const char *p_format, va_list p_list, bool p_stderr = false);
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
String get_stdin_string(bool p_block);
void set_mouse_mode(MouseMode p_mode);
MouseMode get_mouse_mode() const;
- virtual void warp_mouse_pos(const Point2& p_to);
+ virtual void warp_mouse_pos(const Point2 &p_to);
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual int get_screen_count() const;
virtual int get_current_screen() const;
virtual void set_current_screen(int p_screen);
- virtual Point2 get_screen_position(int p_screen=0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
- virtual int get_screen_dpi(int p_screen=0) const;
+ virtual Point2 get_screen_position(int p_screen = 0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
+ virtual int get_screen_dpi(int p_screen = 0) const;
virtual Point2 get_window_position() const;
- virtual void set_window_position(const Point2& p_position);
+ virtual void set_window_position(const Point2 &p_position);
virtual Size2 get_window_size() const;
virtual void set_window_size(const Size2 p_size);
virtual void set_window_fullscreen(bool p_enabled);
@@ -243,35 +234,34 @@ public:
virtual uint64_t get_system_time_secs() const;
virtual bool can_draw() const;
- virtual Error set_cwd(const String& p_cwd);
+ virtual Error set_cwd(const String &p_cwd);
virtual void delay_usec(uint32_t p_usec) const;
virtual uint64_t get_ticks_usec() const;
- virtual Error execute(const String& p_path, const List<String>& p_arguments,bool p_blocking,ProcessID *r_child_id=NULL,String* r_pipe=NULL,int *r_exitcode=NULL);
- virtual Error kill(const ProcessID& p_pid);
+ virtual Error execute(const String &p_path, const List<String> &p_arguments, bool p_blocking, ProcessID *r_child_id = NULL, String *r_pipe = NULL, int *r_exitcode = NULL);
+ virtual Error kill(const ProcessID &p_pid);
virtual int get_process_ID() const;
- virtual bool has_environment(const String& p_var) const;
- virtual String get_environment(const String& p_var) const;
+ virtual bool has_environment(const String &p_var) const;
+ virtual String get_environment(const String &p_var) const;
- virtual void set_clipboard(const String& p_text);
+ virtual void set_clipboard(const String &p_text);
virtual String get_clipboard() const;
void set_cursor_shape(CursorShape p_shape);
- void set_icon(const Image& p_icon);
+ void set_icon(const Image &p_icon);
virtual String get_executable_path() const;
virtual String get_locale() const;
- virtual LatinKeyboardVariant get_latin_keyboard_variant() const;
+ virtual LatinKeyboardVariant get_latin_keyboard_variant() const;
virtual void enable_for_stealing_focus(ProcessID pid);
virtual void move_window_to_foreground();
virtual String get_data_dir() const;
virtual String get_system_dir(SystemDir p_dir) const;
-
virtual void release_rendering_thread();
virtual void make_rendering_thread();
virtual void swap_buffers();
@@ -292,11 +282,10 @@ public:
virtual int get_power_seconds_left();
virtual int get_power_percent_left();
- virtual bool check_feature_support(const String& p_feature);
+ virtual bool check_feature_support(const String &p_feature);
OS_Windows(HINSTANCE _hInstance);
~OS_Windows();
-
};
#endif
diff --git a/platform/windows/packet_peer_udp_winsock.cpp b/platform/windows/packet_peer_udp_winsock.cpp
index 276b9b6634..2df8addece 100644
--- a/platform/windows/packet_peer_udp_winsock.cpp
+++ b/platform/windows/packet_peer_udp_winsock.cpp
@@ -35,19 +35,19 @@
int PacketPeerUDPWinsock::get_available_packet_count() const {
- Error err = const_cast<PacketPeerUDPWinsock*>(this)->_poll(false);
- if (err!=OK)
+ Error err = const_cast<PacketPeerUDPWinsock *>(this)->_poll(false);
+ if (err != OK)
return 0;
return queue_count;
}
-Error PacketPeerUDPWinsock::get_packet(const uint8_t **r_buffer,int &r_buffer_size) const{
+Error PacketPeerUDPWinsock::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const {
- Error err = const_cast<PacketPeerUDPWinsock*>(this)->_poll(false);
- if (err!=OK)
+ Error err = const_cast<PacketPeerUDPWinsock *>(this)->_poll(false);
+ if (err != OK)
return err;
- if (queue_count==0)
+ if (queue_count == 0)
return ERR_UNAVAILABLE;
uint32_t size;
@@ -55,31 +55,30 @@ Error PacketPeerUDPWinsock::get_packet(const uint8_t **r_buffer,int &r_buffer_si
rb.read(&type, 1, true);
if (type == IP::TYPE_IPV4) {
uint8_t ip[4];
- rb.read(ip,4,true);
+ rb.read(ip, 4, true);
packet_ip.set_ipv4(ip);
} else {
uint8_t ip[16];
- rb.read(ip,16,true);
+ rb.read(ip, 16, true);
packet_ip.set_ipv6(ip);
};
- rb.read((uint8_t*)&packet_port,4,true);
- rb.read((uint8_t*)&size,4,true);
- rb.read(packet_buffer,size,true);
+ rb.read((uint8_t *)&packet_port, 4, true);
+ rb.read((uint8_t *)&size, 4, true);
+ rb.read(packet_buffer, size, true);
--queue_count;
- *r_buffer=packet_buffer;
- r_buffer_size=size;
+ *r_buffer = packet_buffer;
+ r_buffer_size = size;
return OK;
-
}
-Error PacketPeerUDPWinsock::put_packet(const uint8_t *p_buffer,int p_buffer_size){
+Error PacketPeerUDPWinsock::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
ERR_FAIL_COND_V(!peer_addr.is_valid(), ERR_UNCONFIGURED);
- if(sock_type==IP::TYPE_NONE)
+ if (sock_type == IP::TYPE_NONE)
sock_type = peer_addr.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
int sock = _get_socket();
- ERR_FAIL_COND_V( sock == -1, FAILED );
+ ERR_FAIL_COND_V(sock == -1, FAILED);
struct sockaddr_storage addr;
size_t addr_size = _set_sockaddr(&addr, peer_addr, peer_port, sock_type);
@@ -87,7 +86,7 @@ Error PacketPeerUDPWinsock::put_packet(const uint8_t *p_buffer,int p_buffer_size
errno = 0;
int err;
- while ( (err = sendto(sock, (const char*)p_buffer, p_buffer_size, 0, (struct sockaddr*)&addr, addr_size)) != p_buffer_size) {
+ while ((err = sendto(sock, (const char *)p_buffer, p_buffer_size, 0, (struct sockaddr *)&addr, addr_size)) != p_buffer_size) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
return FAILED;
@@ -97,21 +96,20 @@ Error PacketPeerUDPWinsock::put_packet(const uint8_t *p_buffer,int p_buffer_size
return OK;
}
-int PacketPeerUDPWinsock::get_max_packet_size() const{
+int PacketPeerUDPWinsock::get_max_packet_size() const {
return 512; // uhm maybe not
}
-
void PacketPeerUDPWinsock::_set_blocking(bool p_blocking) {
//am no windows expert
//hope this is the right thing
- if (blocking==p_blocking)
+ if (blocking == p_blocking)
return;
- blocking=p_blocking;
- unsigned long par = blocking?0:1;
+ blocking = p_blocking;
+ unsigned long par = blocking ? 0 : 1;
if (ioctlsocket(sockfd, FIONBIO, &par)) {
perror("setting non-block mode");
//close();
@@ -121,69 +119,67 @@ void PacketPeerUDPWinsock::_set_blocking(bool p_blocking) {
Error PacketPeerUDPWinsock::listen(int p_port, IP_Address p_bind_address, int p_recv_buffer_size) {
- ERR_FAIL_COND_V(sockfd!=-1,ERR_ALREADY_IN_USE);
- ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(),ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(sockfd != -1, ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER);
sock_type = IP::TYPE_ANY;
- if(p_bind_address.is_valid())
+ if (p_bind_address.is_valid())
sock_type = p_bind_address.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
int sock = _get_socket();
- if (sock == -1 )
+ if (sock == -1)
return ERR_CANT_CREATE;
- struct sockaddr_storage addr = {0};
+ struct sockaddr_storage addr = { 0 };
size_t addr_size = _set_listen_sockaddr(&addr, p_port, sock_type, IP_Address());
- if (bind(sock, (struct sockaddr*)&addr, addr_size) == -1 ) {
+ if (bind(sock, (struct sockaddr *)&addr, addr_size) == -1) {
close();
return ERR_UNAVAILABLE;
}
- blocking=true;
+ blocking = true;
printf("UDP Connection listening on port %i\n", p_port);
rb.resize(nearest_shift(p_recv_buffer_size));
return OK;
}
-void PacketPeerUDPWinsock::close(){
+void PacketPeerUDPWinsock::close() {
if (sockfd != -1)
::closesocket(sockfd);
- sockfd=-1;
+ sockfd = -1;
sock_type = IP::TYPE_NONE;
rb.resize(16);
- queue_count=0;
+ queue_count = 0;
}
-
Error PacketPeerUDPWinsock::wait() {
return _poll(true);
}
Error PacketPeerUDPWinsock::_poll(bool p_wait) {
- if (sockfd==-1) {
+ if (sockfd == -1) {
return FAILED;
}
_set_blocking(p_wait);
-
- struct sockaddr_storage from = {0};
+ struct sockaddr_storage from = { 0 };
int len = sizeof(struct sockaddr_storage);
int ret;
- while ( (ret = recvfrom(sockfd, (char*)recv_buffer, MIN((int)sizeof(recv_buffer),MAX(rb.space_left()-24, 0)), 0, (struct sockaddr*)&from, &len)) > 0) {
+ while ((ret = recvfrom(sockfd, (char *)recv_buffer, MIN((int)sizeof(recv_buffer), MAX(rb.space_left() - 24, 0)), 0, (struct sockaddr *)&from, &len)) > 0) {
uint32_t port = 0;
if (from.ss_family == AF_INET) {
uint8_t type = (uint8_t)IP::TYPE_IPV4;
rb.write(&type, 1);
- struct sockaddr_in* sin_from = (struct sockaddr_in*)&from;
- rb.write((uint8_t*)&sin_from->sin_addr, 4);
+ struct sockaddr_in *sin_from = (struct sockaddr_in *)&from;
+ rb.write((uint8_t *)&sin_from->sin_addr, 4);
port = ntohs(sin_from->sin_port);
} else if (from.ss_family == AF_INET6) {
@@ -191,8 +187,8 @@ Error PacketPeerUDPWinsock::_poll(bool p_wait) {
uint8_t type = (uint8_t)IP::TYPE_IPV6;
rb.write(&type, 1);
- struct sockaddr_in6* s6_from = (struct sockaddr_in6*)&from;
- rb.write((uint8_t*)&s6_from->sin6_addr, 16);
+ struct sockaddr_in6 *s6_from = (struct sockaddr_in6 *)&from;
+ rb.write((uint8_t *)&s6_from->sin6_addr, 16);
port = ntohs(s6_from->sin6_port);
@@ -202,44 +198,39 @@ Error PacketPeerUDPWinsock::_poll(bool p_wait) {
rb.write(&type, 1);
};
- rb.write((uint8_t*)&port, 4);
- rb.write((uint8_t*)&ret, 4);
+ rb.write((uint8_t *)&port, 4);
+ rb.write((uint8_t *)&ret, 4);
rb.write(recv_buffer, ret);
len = sizeof(struct sockaddr_storage);
++queue_count;
};
- if (ret == SOCKET_ERROR){
+ if (ret == SOCKET_ERROR) {
int error = WSAGetLastError();
- if (error == WSAEWOULDBLOCK){
+ if (error == WSAEWOULDBLOCK) {
// Expected when doing non-blocking sockets, retry later.
- }
- else if (error == WSAECONNRESET){
+ } else if (error == WSAECONNRESET) {
// If the remote target does not accept messages, this error may occur, but is harmless.
// Once the remote target gets available, this message will disappear for new messages.
- }
- else
- {
+ } else {
close();
return FAILED;
}
}
-
if (ret == 0) {
close();
return FAILED;
};
-
return OK;
}
-bool PacketPeerUDPWinsock::is_listening() const{
+bool PacketPeerUDPWinsock::is_listening() const {
- return sockfd!=-1;
+ return sockfd != -1;
}
IP_Address PacketPeerUDPWinsock::get_packet_address() const {
@@ -247,14 +238,14 @@ IP_Address PacketPeerUDPWinsock::get_packet_address() const {
return packet_ip;
}
-int PacketPeerUDPWinsock::get_packet_port() const{
+int PacketPeerUDPWinsock::get_packet_port() const {
return packet_port;
}
int PacketPeerUDPWinsock::_get_socket() {
- ERR_FAIL_COND_V(sock_type==IP::TYPE_NONE,-1);
+ ERR_FAIL_COND_V(sock_type == IP::TYPE_NONE, -1);
if (sockfd != -1)
return sockfd;
@@ -264,11 +255,10 @@ int PacketPeerUDPWinsock::_get_socket() {
return sockfd;
}
+void PacketPeerUDPWinsock::set_dest_address(const IP_Address &p_address, int p_port) {
-void PacketPeerUDPWinsock::set_dest_address(const IP_Address& p_address,int p_port) {
-
- peer_addr=p_address;
- peer_port=p_port;
+ peer_addr = p_address;
+ peer_port = p_port;
}
void PacketPeerUDPWinsock::make_default() {
@@ -276,19 +266,17 @@ void PacketPeerUDPWinsock::make_default() {
PacketPeerUDP::_create = PacketPeerUDPWinsock::_create;
};
-
-PacketPeerUDP* PacketPeerUDPWinsock::_create() {
+PacketPeerUDP *PacketPeerUDPWinsock::_create() {
return memnew(PacketPeerUDPWinsock);
};
-
PacketPeerUDPWinsock::PacketPeerUDPWinsock() {
- sockfd=-1;
- packet_port=0;
- queue_count=0;
- peer_port=0;
+ sockfd = -1;
+ packet_port = 0;
+ queue_count = 0;
+ peer_port = 0;
sock_type = IP::TYPE_NONE;
rb.resize(16);
}
diff --git a/platform/windows/packet_peer_udp_winsock.h b/platform/windows/packet_peer_udp_winsock.h
index dcd9da9a79..62107364af 100644
--- a/platform/windows/packet_peer_udp_winsock.h
+++ b/platform/windows/packet_peer_udp_winsock.h
@@ -34,9 +34,8 @@
class PacketPeerUDPWinsock : public PacketPeerUDP {
-
enum {
- PACKET_BUFFER_SIZE=65536
+ PACKET_BUFFER_SIZE = 65536
};
mutable RingBuffer<uint8_t> rb;
@@ -53,7 +52,7 @@ class PacketPeerUDPWinsock : public PacketPeerUDP {
_FORCE_INLINE_ int _get_socket();
- static PacketPeerUDP* _create();
+ static PacketPeerUDP *_create();
bool blocking;
void _set_blocking(bool p_blocking);
@@ -61,14 +60,13 @@ class PacketPeerUDPWinsock : public PacketPeerUDP {
Error _poll(bool p_wait);
public:
-
virtual int get_available_packet_count() const;
- virtual Error get_packet(const uint8_t **r_buffer,int &r_buffer_size) const;
- virtual Error put_packet(const uint8_t *p_buffer,int p_buffer_size);
+ virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) const;
+ virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size);
virtual int get_max_packet_size() const;
- virtual Error listen(int p_port, IP_Address p_bind_address=IP_Address("*"), int p_recv_buffer_size=65536);
+ virtual Error listen(int p_port, IP_Address p_bind_address = IP_Address("*"), int p_recv_buffer_size = 65536);
virtual void close();
virtual Error wait();
virtual bool is_listening() const;
@@ -76,7 +74,7 @@ public:
virtual IP_Address get_packet_address() const;
virtual int get_packet_port() const;
- virtual void set_dest_address(const IP_Address& p_address,int p_port);
+ virtual void set_dest_address(const IP_Address &p_address, int p_port);
static void make_default();
PacketPeerUDPWinsock();
diff --git a/platform/windows/power_windows.cpp b/platform/windows/power_windows.cpp
index 899b620a24..d4641cd4ec 100644
--- a/platform/windows/power_windows.cpp
+++ b/platform/windows/power_windows.cpp
@@ -31,53 +31,50 @@
// CODE CHUNK IMPORTED FROM SDL 2.0
-bool PowerWindows::GetPowerInfo_Windows()
-{
- SYSTEM_POWER_STATUS status;
- bool need_details = FALSE;
+bool PowerWindows::GetPowerInfo_Windows() {
+ SYSTEM_POWER_STATUS status;
+ bool need_details = FALSE;
- /* This API should exist back to Win95. */
- if (!GetSystemPowerStatus(&status))
- {
- /* !!! FIXME: push GetLastError() into GetError() */
- power_state = POWERSTATE_UNKNOWN;
- } else if (status.BatteryFlag == 0xFF) { /* unknown state */
- power_state = POWERSTATE_UNKNOWN;
- } else if (status.BatteryFlag & (1 << 7)) { /* no battery */
- power_state = POWERSTATE_NO_BATTERY;
- } else if (status.BatteryFlag & (1 << 3)) { /* charging */
- power_state = POWERSTATE_CHARGING;
- need_details = TRUE;
- } else if (status.ACLineStatus == 1) {
- power_state = POWERSTATE_CHARGED; /* on AC, not charging. */
- need_details = TRUE;
- } else {
- power_state = POWERSTATE_ON_BATTERY; /* not on AC. */
- need_details = TRUE;
- }
+ /* This API should exist back to Win95. */
+ if (!GetSystemPowerStatus(&status)) {
+ /* !!! FIXME: push GetLastError() into GetError() */
+ power_state = POWERSTATE_UNKNOWN;
+ } else if (status.BatteryFlag == 0xFF) { /* unknown state */
+ power_state = POWERSTATE_UNKNOWN;
+ } else if (status.BatteryFlag & (1 << 7)) { /* no battery */
+ power_state = POWERSTATE_NO_BATTERY;
+ } else if (status.BatteryFlag & (1 << 3)) { /* charging */
+ power_state = POWERSTATE_CHARGING;
+ need_details = TRUE;
+ } else if (status.ACLineStatus == 1) {
+ power_state = POWERSTATE_CHARGED; /* on AC, not charging. */
+ need_details = TRUE;
+ } else {
+ power_state = POWERSTATE_ON_BATTERY; /* not on AC. */
+ need_details = TRUE;
+ }
- percent_left = -1;
- nsecs_left = -1;
- if (need_details) {
- const int pct = (int) status.BatteryLifePercent;
- const int secs = (int) status.BatteryLifeTime;
+ percent_left = -1;
+ nsecs_left = -1;
+ if (need_details) {
+ const int pct = (int)status.BatteryLifePercent;
+ const int secs = (int)status.BatteryLifeTime;
- if (pct != 255) { /* 255 == unknown */
- percent_left = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
- }
- if (secs != 0xFFFFFFFF) { /* ((DWORD)-1) == unknown */
- nsecs_left = secs;
- }
- }
+ if (pct != 255) { /* 255 == unknown */
+ percent_left = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
+ }
+ if (secs != 0xFFFFFFFF) { /* ((DWORD)-1) == unknown */
+ nsecs_left = secs;
+ }
+ }
- return TRUE; /* always the definitive answer on Windows. */
+ return TRUE; /* always the definitive answer on Windows. */
}
PowerState PowerWindows::get_power_state() {
if (GetPowerInfo_Windows()) {
return power_state;
- }
- else {
+ } else {
return POWERSTATE_UNKNOWN;
}
}
@@ -85,8 +82,7 @@ PowerState PowerWindows::get_power_state() {
int PowerWindows::get_power_seconds_left() {
if (GetPowerInfo_Windows()) {
return nsecs_left;
- }
- else {
+ } else {
return -1;
}
}
@@ -94,14 +90,13 @@ int PowerWindows::get_power_seconds_left() {
int PowerWindows::get_power_percent_left() {
if (GetPowerInfo_Windows()) {
return percent_left;
- }
- else {
+ } else {
return -1;
}
}
-PowerWindows::PowerWindows() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
-
+PowerWindows::PowerWindows()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
PowerWindows::~PowerWindows() {
diff --git a/platform/windows/stream_peer_winsock.cpp b/platform/windows/stream_peer_winsock.cpp
index 106eb6a5f5..abf182c72a 100644
--- a/platform/windows/stream_peer_winsock.cpp
+++ b/platform/windows/stream_peer_winsock.cpp
@@ -37,7 +37,7 @@
int winsock_refcount = 0;
-StreamPeerTCP* StreamPeerWinsock::_create() {
+StreamPeerTCP *StreamPeerWinsock::_create() {
return memnew(StreamPeerWinsock);
};
@@ -48,7 +48,7 @@ void StreamPeerWinsock::make_default() {
if (winsock_refcount == 0) {
WSADATA data;
- WSAStartup(MAKEWORD(2,2), &data);
+ WSAStartup(MAKEWORD(2, 2), &data);
};
++winsock_refcount;
};
@@ -62,7 +62,6 @@ void StreamPeerWinsock::cleanup() {
};
};
-
Error StreamPeerWinsock::_block(int p_sockfd, bool p_read, bool p_write) const {
fd_set read, write;
@@ -85,7 +84,7 @@ Error StreamPeerWinsock::_poll_connection() const {
struct sockaddr_storage their_addr;
size_t addr_size = _set_sockaddr(&their_addr, peer_host, peer_port, sock_type);
- if (::connect(sockfd, (struct sockaddr *)&their_addr,addr_size) == SOCKET_ERROR) {
+ if (::connect(sockfd, (struct sockaddr *)&their_addr, addr_size) == SOCKET_ERROR) {
int err = WSAGetLastError();
if (err == WSAEISCONN) {
@@ -108,7 +107,7 @@ Error StreamPeerWinsock::_poll_connection() const {
return OK;
};
-Error StreamPeerWinsock::write(const uint8_t* p_data,int p_bytes, int &r_sent, bool p_block) {
+Error StreamPeerWinsock::write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block) {
if (status == STATUS_NONE || status == STATUS_ERROR) {
@@ -135,7 +134,7 @@ Error StreamPeerWinsock::write(const uint8_t* p_data,int p_bytes, int &r_sent, b
while (data_to_send) {
- int sent_amount = send(sockfd, (const char*)offset, data_to_send, 0);
+ int sent_amount = send(sockfd, (const char *)offset, data_to_send, 0);
if (sent_amount == -1) {
@@ -166,7 +165,7 @@ Error StreamPeerWinsock::write(const uint8_t* p_data,int p_bytes, int &r_sent, b
return OK;
};
-Error StreamPeerWinsock::read(uint8_t* p_buffer, int p_bytes,int &r_received, bool p_block) {
+Error StreamPeerWinsock::read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block) {
if (!is_connected_to_host()) {
@@ -191,7 +190,7 @@ Error StreamPeerWinsock::read(uint8_t* p_buffer, int p_bytes,int &r_received, bo
while (to_read) {
- int read = recv(sockfd, (char*)p_buffer + total_read, to_read, 0);
+ int read = recv(sockfd, (char *)p_buffer + total_read, to_read, 0);
if (read == -1) {
@@ -224,24 +223,24 @@ Error StreamPeerWinsock::read(uint8_t* p_buffer, int p_bytes,int &r_received, bo
return OK;
};
-Error StreamPeerWinsock::put_data(const uint8_t* p_data,int p_bytes) {
+Error StreamPeerWinsock::put_data(const uint8_t *p_data, int p_bytes) {
int total;
return write(p_data, p_bytes, total, true);
};
-Error StreamPeerWinsock::put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent) {
+Error StreamPeerWinsock::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
return write(p_data, p_bytes, r_sent, false);
};
-Error StreamPeerWinsock::get_data(uint8_t* p_buffer, int p_bytes) {
+Error StreamPeerWinsock::get_data(uint8_t *p_buffer, int p_bytes) {
int total;
return read(p_buffer, p_bytes, total, true);
};
-Error StreamPeerWinsock::get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received) {
+Error StreamPeerWinsock::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
return read(p_buffer, p_bytes, r_received, false);
};
@@ -255,7 +254,6 @@ StreamPeerTCP::Status StreamPeerWinsock::get_status() const {
return status;
};
-
bool StreamPeerWinsock::is_connected_to_host() const {
if (status == STATUS_NONE || status == STATUS_ERROR) {
@@ -266,14 +264,14 @@ bool StreamPeerWinsock::is_connected_to_host() const {
return true;
};
- return (sockfd!=INVALID_SOCKET);
+ return (sockfd != INVALID_SOCKET);
};
void StreamPeerWinsock::disconnect_from_host() {
if (sockfd != INVALID_SOCKET)
closesocket(sockfd);
- sockfd=INVALID_SOCKET;
+ sockfd = INVALID_SOCKET;
sock_type = IP::TYPE_NONE;
status = STATUS_NONE;
@@ -291,13 +289,13 @@ void StreamPeerWinsock::set_socket(int p_sockfd, IP_Address p_host, int p_port,
peer_port = p_port;
};
-Error StreamPeerWinsock::connect_to_host(const IP_Address& p_host, uint16_t p_port) {
+Error StreamPeerWinsock::connect_to_host(const IP_Address &p_host, uint16_t p_port) {
- ERR_FAIL_COND_V( !p_host.is_valid(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!p_host.is_valid(), ERR_INVALID_PARAMETER);
sock_type = p_host.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
sockfd = _socket_create(sock_type, SOCK_STREAM, IPPROTO_TCP);
- if (sockfd == INVALID_SOCKET) {
+ if (sockfd == INVALID_SOCKET) {
ERR_PRINT("Socket creation failed!");
disconnect_from_host();
//perror("socket");
@@ -314,7 +312,7 @@ Error StreamPeerWinsock::connect_to_host(const IP_Address& p_host, uint16_t p_po
struct sockaddr_storage their_addr;
size_t addr_size = _set_sockaddr(&their_addr, p_host, p_port, sock_type);
- if (::connect(sockfd, (struct sockaddr *)&their_addr,addr_size) == SOCKET_ERROR) {
+ if (::connect(sockfd, (struct sockaddr *)&their_addr, addr_size) == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
ERR_PRINT("Connection to remote host failed!");
@@ -333,18 +331,17 @@ Error StreamPeerWinsock::connect_to_host(const IP_Address& p_host, uint16_t p_po
};
void StreamPeerWinsock::set_nodelay(bool p_enabled) {
- ERR_FAIL_COND(!is_connected_to_host());
- int flag=p_enabled?1:0;
- setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, sizeof(int));
+ ERR_FAIL_COND(!is_connected_to_host());
+ int flag = p_enabled ? 1 : 0;
+ setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int));
}
int StreamPeerWinsock::get_available_bytes() const {
unsigned long len;
- int ret = ioctlsocket(sockfd,FIONREAD,&len);
- ERR_FAIL_COND_V(ret==-1,0)
+ int ret = ioctlsocket(sockfd, FIONREAD, &len);
+ ERR_FAIL_COND_V(ret == -1, 0)
return len;
-
}
IP_Address StreamPeerWinsock::get_connected_host() const {
@@ -370,5 +367,4 @@ StreamPeerWinsock::~StreamPeerWinsock() {
disconnect_from_host();
};
-
#endif
diff --git a/platform/windows/stream_peer_winsock.h b/platform/windows/stream_peer_winsock.h
index 7cf60fc10e..c8c2dd4feb 100644
--- a/platform/windows/stream_peer_winsock.h
+++ b/platform/windows/stream_peer_winsock.h
@@ -39,7 +39,6 @@
class StreamPeerWinsock : public StreamPeerTCP {
protected:
-
mutable Status status;
IP::Type sock_type;
@@ -52,20 +51,19 @@ protected:
IP_Address peer_host;
int peer_port;
- Error write(const uint8_t* p_data,int p_bytes, int &r_sent, bool p_block);
- Error read(uint8_t* p_buffer, int p_bytes,int &r_received, bool p_block);
+ Error write(const uint8_t *p_data, int p_bytes, int &r_sent, bool p_block);
+ Error read(uint8_t *p_buffer, int p_bytes, int &r_received, bool p_block);
- static StreamPeerTCP* _create();
+ static StreamPeerTCP *_create();
public:
+ virtual Error connect_to_host(const IP_Address &p_host, uint16_t p_port);
- virtual Error connect_to_host(const IP_Address& p_host, uint16_t p_port);
-
- virtual Error put_data(const uint8_t* p_data,int p_bytes);
- virtual Error put_partial_data(const uint8_t* p_data,int p_bytes, int &r_sent);
+ virtual Error put_data(const uint8_t *p_data, int p_bytes);
+ virtual Error put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent);
- virtual Error get_data(uint8_t* p_buffer, int p_bytes);
- virtual Error get_partial_data(uint8_t* p_buffer, int p_bytes,int &r_received);
+ virtual Error get_data(uint8_t *p_buffer, int p_bytes);
+ virtual Error get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received);
virtual int get_available_bytes() const;
@@ -83,7 +81,6 @@ public:
virtual void set_nodelay(bool p_enabled);
-
StreamPeerWinsock();
~StreamPeerWinsock();
};
diff --git a/platform/windows/tcp_server_winsock.cpp b/platform/windows/tcp_server_winsock.cpp
index 883741b115..67713f5d1c 100644
--- a/platform/windows/tcp_server_winsock.cpp
+++ b/platform/windows/tcp_server_winsock.cpp
@@ -37,7 +37,7 @@
extern int winsock_refcount;
-TCP_Server* TCPServerWinsock::_create() {
+TCP_Server *TCPServerWinsock::_create() {
return memnew(TCPServerWinsock);
};
@@ -48,7 +48,7 @@ void TCPServerWinsock::make_default() {
if (winsock_refcount == 0) {
WSADATA data;
- WSAStartup(MAKEWORD(2,2), &data);
+ WSAStartup(MAKEWORD(2, 2), &data);
};
++winsock_refcount;
};
@@ -62,10 +62,9 @@ void TCPServerWinsock::cleanup() {
};
};
+Error TCPServerWinsock::listen(uint16_t p_port, const IP_Address p_bind_address) {
-Error TCPServerWinsock::listen(uint16_t p_port,const IP_Address p_bind_address) {
-
- ERR_FAIL_COND_V(listen_sockfd!=-1,ERR_ALREADY_IN_USE);
+ ERR_FAIL_COND_V(listen_sockfd != -1, ERR_ALREADY_IN_USE);
ERR_FAIL_COND_V(!p_bind_address.is_valid() && !p_bind_address.is_wildcard(), ERR_INVALID_PARAMETER);
int sockfd;
@@ -75,7 +74,6 @@ Error TCPServerWinsock::listen(uint16_t p_port,const IP_Address p_bind_address)
if (p_bind_address.is_valid())
sock_type = p_bind_address.is_ipv4() ? IP::TYPE_IPV4 : IP::TYPE_IPV6;
-
sockfd = _socket_create(sock_type, SOCK_STREAM, IPPROTO_TCP);
ERR_FAIL_COND_V(sockfd == INVALID_SOCKET, FAILED);
@@ -89,13 +87,12 @@ Error TCPServerWinsock::listen(uint16_t p_port,const IP_Address p_bind_address)
struct sockaddr_storage my_addr;
size_t addr_size = _set_listen_sockaddr(&my_addr, p_port, sock_type, p_bind_address);
- int reuse=1;
- if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) {
+ int reuse = 1;
+ if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) {
printf("REUSEADDR failed!");
}
-
if (bind(sockfd, (struct sockaddr *)&my_addr, addr_size) != SOCKET_ERROR) {
if (::listen(sockfd, SOMAXCONN) == SOCKET_ERROR) {
@@ -103,8 +100,7 @@ Error TCPServerWinsock::listen(uint16_t p_port,const IP_Address p_bind_address)
closesocket(sockfd);
ERR_FAIL_V(FAILED);
};
- }
- else {
+ } else {
return ERR_ALREADY_IN_USE;
};
@@ -143,7 +139,6 @@ bool TCPServerWinsock::is_connection_available() const {
return false;
};
-
Ref<StreamPeerTCP> TCPServerWinsock::take_connection() {
if (!is_connection_available()) {
@@ -175,7 +170,6 @@ void TCPServerWinsock::stop() {
sock_type = IP::TYPE_NONE;
};
-
TCPServerWinsock::TCPServerWinsock() {
listen_sockfd = INVALID_SOCKET;
@@ -186,4 +180,3 @@ TCPServerWinsock::~TCPServerWinsock() {
stop();
};
-
diff --git a/platform/windows/tcp_server_winsock.h b/platform/windows/tcp_server_winsock.h
index afbd1e9c87..d7b1aee054 100644
--- a/platform/windows/tcp_server_winsock.h
+++ b/platform/windows/tcp_server_winsock.h
@@ -36,11 +36,10 @@ class TCPServerWinsock : public TCP_Server {
int listen_sockfd;
IP::Type sock_type;
- static TCP_Server* _create();
+ static TCP_Server *_create();
public:
-
- virtual Error listen(uint16_t p_port, const IP_Address p_bind_address=IP_Address("*"));
+ virtual Error listen(uint16_t p_port, const IP_Address p_bind_address = IP_Address("*"));
virtual bool is_connection_available() const;
virtual Ref<StreamPeerTCP> take_connection();
diff --git a/platform/x11/context_gl_x11.cpp b/platform/x11/context_gl_x11.cpp
index caa5e4fc89..41d110a1e1 100644
--- a/platform/x11/context_gl_x11.cpp
+++ b/platform/x11/context_gl_x11.cpp
@@ -31,17 +31,17 @@
#ifdef X11_ENABLED
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
#include <stdio.h>
-#include <unistd.h>
#include <stdlib.h>
+#include <unistd.h>
#define GLX_GLXEXT_PROTOTYPES
#include <GL/glx.h>
#include <GL/glxext.h>
-#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
-#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
+#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
+#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
-typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display*, GLXFBConfig, GLXContext, Bool, const int*);
+typedef GLXContext (*GLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
struct ContextGL_X11_Private {
@@ -60,7 +60,7 @@ void ContextGL_X11::make_current() {
void ContextGL_X11::swap_buffers() {
- glXSwapBuffers(x11_display,x11_window);
+ glXSwapBuffers(x11_display, x11_window);
}
/*
@@ -77,38 +77,35 @@ static GLWrapperFuncPtr wrapper_get_proc_address(const char* p_function) {
}*/
static bool ctxErrorOccurred = false;
-static int ctxErrorHandler( Display *dpy, XErrorEvent *ev )
-{
- ctxErrorOccurred = true;
- return 0;
+static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) {
+ ctxErrorOccurred = true;
+ return 0;
}
Error ContextGL_X11::initialize() {
-
GLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL;
//const char *extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));
- glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte*)"glXCreateContextAttribsARB");
-
- ERR_FAIL_COND_V( !glXCreateContextAttribsARB, ERR_UNCONFIGURED );
+ glXCreateContextAttribsARB = (GLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddress((const GLubyte *)"glXCreateContextAttribsARB");
+ ERR_FAIL_COND_V(!glXCreateContextAttribsARB, ERR_UNCONFIGURED);
static int visual_attribs[] = {
- GLX_RENDER_TYPE, GLX_RGBA_BIT,
- GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
- GLX_DOUBLEBUFFER, true,
- GLX_RED_SIZE, 1,
- GLX_GREEN_SIZE, 1,
- GLX_BLUE_SIZE, 1,
- GLX_DEPTH_SIZE, 24,
- None
+ GLX_RENDER_TYPE, GLX_RGBA_BIT,
+ GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
+ GLX_DOUBLEBUFFER, true,
+ GLX_RED_SIZE, 1,
+ GLX_GREEN_SIZE, 1,
+ GLX_BLUE_SIZE, 1,
+ GLX_DEPTH_SIZE, 24,
+ None
};
int fbcount;
GLXFBConfig *fbc = glXChooseFBConfig(x11_display, DefaultScreen(x11_display), visual_attribs, &fbcount);
- ERR_FAIL_COND_V(!fbc,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!fbc, ERR_UNCONFIGURED);
XVisualInfo *vi = glXGetVisualFromFBConfig(x11_display, fbc[0]);
@@ -127,15 +124,13 @@ Error ContextGL_X11::initialize() {
x11_window = atol(windowid);
} else {
*/
- x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel|CWColormap|CWEventMask, &swa);
- ERR_FAIL_COND_V(!x11_window,ERR_UNCONFIGURED);
- XMapWindow(x11_display, x11_window);
- //};
-
-
- int (*oldHandler)(Display*, XErrorEvent*) =
- XSetErrorHandler(&ctxErrorHandler);
+ x11_window = XCreateWindow(x11_display, RootWindow(x11_display, vi->screen), 0, 0, OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa);
+ ERR_FAIL_COND_V(!x11_window, ERR_UNCONFIGURED);
+ XMapWindow(x11_display, x11_window);
+ //};
+ int (*oldHandler)(Display *, XErrorEvent *) =
+ XSetErrorHandler(&ctxErrorHandler);
if (!opengl_3_context) {
//oldstyle context:
@@ -144,17 +139,17 @@ Error ContextGL_X11::initialize() {
static int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 3,
- GLX_CONTEXT_FLAGS_ARB , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB/*|GLX_CONTEXT_DEBUG_BIT_ARB*/,
+ GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB /*|GLX_CONTEXT_DEBUG_BIT_ARB*/,
None
};
p->glx_context = glXCreateContextAttribsARB(x11_display, fbc[0], NULL, true, context_attribs);
ERR_EXPLAIN("Could not obtain an OpenGL 3.3 context!");
- ERR_FAIL_COND_V(ctxErrorOccurred || !p->glx_context,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(ctxErrorOccurred || !p->glx_context, ERR_UNCONFIGURED);
}
- XSync( x11_display, False );
- XSetErrorHandler( oldHandler );
+ XSync(x11_display, False);
+ XSetErrorHandler(oldHandler);
print_line("ALL IS GOOD");
@@ -168,8 +163,8 @@ Error ContextGL_X11::initialize() {
*/
//glXMakeCurrent(x11_display, None, NULL);
- XFree( vi );
- XFree( fbc );
+ XFree(vi);
+ XFree(fbc);
return OK;
}
@@ -177,14 +172,14 @@ Error ContextGL_X11::initialize() {
int ContextGL_X11::get_window_width() {
XWindowAttributes xwa;
- XGetWindowAttributes(x11_display,x11_window,&xwa);
+ XGetWindowAttributes(x11_display, x11_window, &xwa);
return xwa.width;
}
int ContextGL_X11::get_window_height() {
XWindowAttributes xwa;
- XGetWindowAttributes(x11_display,x11_window,&xwa);
+ XGetWindowAttributes(x11_display, x11_window, &xwa);
return xwa.height;
}
@@ -199,24 +194,22 @@ void ContextGL_X11::set_use_vsync(bool p_use) {
setup = true;
String extensions = glXQueryExtensionsString(x11_display, DefaultScreen(x11_display));
if (extensions.find("GLX_EXT_swap_control") != -1)
- glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalEXT");
+ glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalEXT");
if (extensions.find("GLX_MESA_swap_control") != -1)
- glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalMESA");
+ glXSwapIntervalMESA = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalMESA");
if (extensions.find("GLX_SGI_swap_control") != -1)
- glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalSGI");
+ glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)glXGetProcAddressARB((const GLubyte *)"glXSwapIntervalSGI");
}
- int val = p_use ? 1:0;
+ int val = p_use ? 1 : 0;
if (glXSwapIntervalMESA) {
glXSwapIntervalMESA(val);
- }
- else if (glXSwapIntervalSGI) {
+ } else if (glXSwapIntervalSGI) {
glXSwapIntervalSGI(val);
- }
- else if (glXSwapIntervalEXT) {
+ } else if (glXSwapIntervalEXT) {
GLXDrawable drawable = glXGetCurrentDrawable();
glXSwapIntervalEXT(x11_display, drawable, val);
- }
- else return;
+ } else
+ return;
use_vsync = p_use;
}
bool ContextGL_X11::is_using_vsync() const {
@@ -224,30 +217,28 @@ bool ContextGL_X11::is_using_vsync() const {
return use_vsync;
}
+ContextGL_X11::ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, bool p_opengl_3_context)
+ : x11_window(p_x11_window) {
-ContextGL_X11::ContextGL_X11(::Display *p_x11_display,::Window &p_x11_window,const OS::VideoMode& p_default_video_mode,bool p_opengl_3_context) : x11_window(p_x11_window) {
+ default_video_mode = p_default_video_mode;
+ x11_display = p_x11_display;
- default_video_mode=p_default_video_mode;
- x11_display=p_x11_display;
+ opengl_3_context = p_opengl_3_context;
- opengl_3_context=p_opengl_3_context;
-
- double_buffer=false;
- direct_render=false;
- glx_minor=glx_major=0;
- p = memnew( ContextGL_X11_Private );
- p->glx_context=0;
- use_vsync=false;
+ double_buffer = false;
+ direct_render = false;
+ glx_minor = glx_major = 0;
+ p = memnew(ContextGL_X11_Private);
+ p->glx_context = 0;
+ use_vsync = false;
}
-
ContextGL_X11::~ContextGL_X11() {
release_current();
- glXDestroyContext( x11_display, p->glx_context );
+ glXDestroyContext(x11_display, p->glx_context);
- memdelete( p );
+ memdelete(p);
}
-
#endif
#endif
diff --git a/platform/x11/context_gl_x11.h b/platform/x11/context_gl_x11.h
index efea700224..be0f4c822c 100644
--- a/platform/x11/context_gl_x11.h
+++ b/platform/x11/context_gl_x11.h
@@ -36,10 +36,8 @@
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
-
-
-#include "os/os.h"
#include "drivers/gl_context/context_gl.h"
+#include "os/os.h"
#include <X11/Xlib.h>
struct ContextGL_X11_Private;
@@ -50,14 +48,14 @@ class ContextGL_X11 : public ContextGL {
OS::VideoMode default_video_mode;
//::Colormap x11_colormap;
::Display *x11_display;
- ::Window& x11_window;
+ ::Window &x11_window;
bool double_buffer;
bool direct_render;
- int glx_minor,glx_major;
+ int glx_minor, glx_major;
bool opengl_3_context;
bool use_vsync;
-public:
+public:
virtual void release_current();
virtual void make_current();
virtual void swap_buffers();
@@ -69,9 +67,8 @@ public:
virtual void set_use_vsync(bool p_use);
virtual bool is_using_vsync() const;
- ContextGL_X11(::Display *p_x11_display,::Window &p_x11_window,const OS::VideoMode& p_default_video_mode,bool p_opengl_3_context);
+ ContextGL_X11(::Display *p_x11_display, ::Window &p_x11_window, const OS::VideoMode &p_default_video_mode, bool p_opengl_3_context);
~ContextGL_X11();
-
};
#endif
diff --git a/platform/x11/export/export.cpp b/platform/x11/export/export.cpp
index c40b8f3c1f..2659c771ca 100644
--- a/platform/x11/export/export.cpp
+++ b/platform/x11/export/export.cpp
@@ -27,12 +27,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "export.h"
-#include "platform/x11/logo.h"
#include "editor/editor_export.h"
+#include "platform/x11/logo.h"
#include "scene/resources/texture.h"
-
-
void register_x11_exporter() {
Ref<EditorExportPlatformPC> platform;
@@ -48,7 +46,7 @@ void register_x11_exporter() {
EditorExport::get_singleton()->add_export_platform(platform);
- #if 0
+#if 0
Image img(_x11_logo);
Ref<ImageTexture> logo = memnew( ImageTexture );
logo->create_from_image(img);
@@ -65,6 +63,5 @@ void register_x11_exporter() {
EditorImportExport::get_singleton()->add_export_platform(exporter);
}
- #endif
+#endif
}
-
diff --git a/platform/x11/godot_x11.cpp b/platform/x11/godot_x11.cpp
index adb919c2f1..078baf76ee 100644
--- a/platform/x11/godot_x11.cpp
+++ b/platform/x11/godot_x11.cpp
@@ -26,22 +26,22 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
+#include <unistd.h>
#include "main/main.h"
#include "os_x11.h"
-int main(int argc, char* argv[]) {
+int main(int argc, char *argv[]) {
OS_X11 os;
- char *cwd = (char*)malloc(PATH_MAX);
+ char *cwd = (char *)malloc(PATH_MAX);
getcwd(cwd, PATH_MAX);
- Error err = Main::setup(argv[0],argc-1,&argv[1]);
- if (err!=OK)
+ Error err = Main::setup(argv[0], argc - 1, &argv[1]);
+ if (err != OK)
return 255;
if (Main::start())
diff --git a/platform/x11/joypad_linux.cpp b/platform/x11/joypad_linux.cpp
index bdbd2912a6..62ece58f58 100644
--- a/platform/x11/joypad_linux.cpp
+++ b/platform/x11/joypad_linux.cpp
@@ -31,21 +31,21 @@
#include "joypad_linux.h"
+#include <errno.h>
+#include <fcntl.h>
#include <linux/input.h>
#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
#ifdef UDEV_ENABLED
#include <libudev.h>
#endif
-#define LONG_BITS (sizeof(long) * 8)
-#define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
-#define NBITS(x) ((((x)-1)/LONG_BITS)+1)
+#define LONG_BITS (sizeof(long) * 8)
+#define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
+#define NBITS(x) ((((x)-1) / LONG_BITS) + 1)
#ifdef UDEV_ENABLED
-static const char* ignore_str = "/dev/input/js";
+static const char *ignore_str = "/dev/input/js";
#endif
JoypadLinux::Joypad::Joypad() {
@@ -67,20 +67,19 @@ JoypadLinux::Joypad::~Joypad() {
}
void JoypadLinux::Joypad::reset() {
- dpad = 0;
- fd = -1;
+ dpad = 0;
+ fd = -1;
InputDefault::JoyAxis jx;
jx.min = -1;
jx.value = 0.0f;
- for (int i=0; i < MAX_ABS; i++) {
+ for (int i = 0; i < MAX_ABS; i++) {
abs_map[i] = -1;
curr_axis[i] = jx;
}
}
-JoypadLinux::JoypadLinux(InputDefault *in)
-{
+JoypadLinux::JoypadLinux(InputDefault *in) {
exit_udev = false;
input = in;
joy_mutex = Mutex::create();
@@ -98,7 +97,7 @@ JoypadLinux::~JoypadLinux() {
void JoypadLinux::joy_thread_func(void *p_user) {
if (p_user) {
- JoypadLinux* joy = (JoypadLinux*) p_user;
+ JoypadLinux *joy = (JoypadLinux *)p_user;
joy->run_joypad_thread();
}
return;
@@ -124,16 +123,16 @@ void JoypadLinux::enumerate_joypads(udev *p_udev) {
udev_device *dev;
enumerate = udev_enumerate_new(p_udev);
- udev_enumerate_add_match_subsystem(enumerate,"input");
+ udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_add_match_property(enumerate, "ID_INPUT_JOYPAD", "1");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
- const char* path = udev_list_entry_get_name(dev_list_entry);
+ const char *path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(p_udev, path);
- const char* devnode = udev_device_get_devnode(dev);
+ const char *devnode = udev_device_get_devnode(dev);
if (devnode) {
@@ -168,7 +167,7 @@ void JoypadLinux::monitor_joypads(udev *p_udev) {
tv.tv_sec = 0;
tv.tv_usec = 0;
- ret = select(fd+1, &fds, NULL, NULL, &tv);
+ ret = select(fd + 1, &fds, NULL, NULL, &tv);
/* Check if our file descriptor has received data. */
if (ret > 0 && FD_ISSET(fd, &fds)) {
@@ -180,7 +179,7 @@ void JoypadLinux::monitor_joypads(udev *p_udev) {
joy_mutex->lock();
String action = udev_device_get_action(dev);
- const char* devnode = udev_device_get_devnode(dev);
+ const char *devnode = udev_device_get_devnode(dev);
if (devnode) {
String devnode_str = devnode;
@@ -232,13 +231,13 @@ int JoypadLinux::get_joy_from_path(String p_path) const {
void JoypadLinux::close_joypad(int p_id) {
if (p_id == -1) {
- for (int i=0; i<JOYPADS_MAX; i++) {
+ for (int i = 0; i < JOYPADS_MAX; i++) {
close_joypad(i);
};
return;
- }
- else if (p_id < 0) return;
+ } else if (p_id < 0)
+ return;
Joypad &joy = joypads[p_id];
@@ -253,11 +252,11 @@ void JoypadLinux::close_joypad(int p_id) {
static String _hex_str(uint8_t p_byte) {
- static const char* dict = "0123456789abcdef";
+ static const char *dict = "0123456789abcdef";
char ret[3];
ret[2] = 0;
- ret[0] = dict[p_byte>>4];
+ ret[0] = dict[p_byte >> 4];
ret[1] = dict[p_byte & 0xF];
return ret;
@@ -265,7 +264,7 @@ static String _hex_str(uint8_t p_byte) {
void JoypadLinux::setup_joypad_properties(int p_id) {
- Joypad* joy = &joypads[p_id];
+ Joypad *joy = &joypads[p_id];
unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
@@ -274,7 +273,7 @@ void JoypadLinux::setup_joypad_properties(int p_id) {
int num_axes = 0;
if ((ioctl(joy->fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
- (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
+ (ioctl(joy->fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
return;
}
for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
@@ -332,8 +331,8 @@ void JoypadLinux::open_joypad(const char *p_path) {
attached_devices.push_back(String(p_path));
if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
- (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
- (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
+ (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
+ (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
close(fd);
return;
}
@@ -341,10 +340,10 @@ void JoypadLinux::open_joypad(const char *p_path) {
//check if the device supports basic gamepad events, prevents certain keyboards from
//being detected as joypads
if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
- (test_bit(ABS_X, absbit) || test_bit(ABS_Y, absbit) || test_bit(ABS_HAT0X, absbit) ||
- test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) &&
- (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) ||
- test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit)))) {
+ (test_bit(ABS_X, absbit) || test_bit(ABS_Y, absbit) || test_bit(ABS_HAT0X, absbit) ||
+ test_bit(ABS_GAS, absbit) || test_bit(ABS_RUDDER, absbit)) &&
+ (test_bit(BTN_A, keybit) || test_bit(BTN_THUMBL, keybit) ||
+ test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_1, keybit)))) {
close(fd);
return;
}
@@ -375,13 +374,12 @@ void JoypadLinux::open_joypad(const char *p_path) {
uint16_t product = __bswap_16(inpid.product);
uint16_t version = __bswap_16(inpid.version);
- sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor,0,product,0,version,0);
+ sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
input->joy_connection_changed(joy_num, true, name, uid);
- }
- else {
+ } else {
String uidname = uid;
int uidlen = MIN(name.length(), 11);
- for (int i=0; i<uidlen; i++) {
+ for (int i = 0; i < uidlen; i++) {
uidname = uidname + _hex_str(name[i]);
}
@@ -391,9 +389,8 @@ void JoypadLinux::open_joypad(const char *p_path) {
}
}
-void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp)
-{
- Joypad& joy = joypads[p_id];
+void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
+ Joypad &joy = joypads[p_id];
if (!joy.force_feedback || joy.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
return;
}
@@ -417,15 +414,14 @@ void JoypadLinux::joypad_vibration_start(int p_id, float p_weak_magnitude, float
play.type = EV_FF;
play.code = effect.id;
play.value = 1;
- write(joy.fd, (const void*)&play, sizeof(play));
+ write(joy.fd, (const void *)&play, sizeof(play));
joy.ff_effect_id = effect.id;
joy.ff_effect_timestamp = p_timestamp;
}
-void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp)
-{
- Joypad& joy = joypads[p_id];
+void JoypadLinux::joypad_vibration_stop(int p_id, uint64_t p_timestamp) {
+ Joypad &joy = joypads[p_id];
if (!joy.force_feedback || joy.fd == -1 || joy.ff_effect_id == -1) {
return;
}
@@ -447,13 +443,13 @@ InputDefault::JoyAxis JoypadLinux::axis_correct(const input_absinfo *p_abs, int
if (min < 0) {
jx.min = -1;
if (p_value < 0) {
- jx.value = (float) -p_value / min;
+ jx.value = (float)-p_value / min;
}
- jx.value = (float) p_value / max;
+ jx.value = (float)p_value / max;
}
if (min == 0) {
jx.min = 0;
- jx.value = 0.0f + (float) p_value / max;
+ jx.value = 0.0f + (float)p_value / max;
}
return jx;
}
@@ -463,12 +459,12 @@ uint32_t JoypadLinux::process_joypads(uint32_t p_event_id) {
if (joy_mutex->try_lock() != OK) {
return p_event_id;
}
- for (int i=0; i<JOYPADS_MAX; i++) {
+ for (int i = 0; i < JOYPADS_MAX; i++) {
if (joypads[i].fd == -1) continue;
input_event events[32];
- Joypad* joy = &joypads[i];
+ Joypad *joy = &joypads[i];
int len;
@@ -480,45 +476,49 @@ uint32_t JoypadLinux::process_joypads(uint32_t p_event_id) {
// ev may be tainted and out of MAX_KEY range, which will cause
// joy->key_map[ev.code] to crash
- if( ev.code < 0 || ev.code >= MAX_KEY )
+ if (ev.code < 0 || ev.code >= MAX_KEY)
return p_event_id;
switch (ev.type) {
- case EV_KEY:
- p_event_id = input->joy_button(p_event_id, i, joy->key_map[ev.code], ev.value);
- break;
-
- case EV_ABS:
-
- switch (ev.code) {
- case ABS_HAT0X:
- if (ev.value != 0) {
- if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_LEFT;
- else joy->dpad |= InputDefault::HAT_MASK_RIGHT;
- }
- else joy->dpad &= ~(InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_RIGHT);
-
- p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
+ case EV_KEY:
+ p_event_id = input->joy_button(p_event_id, i, joy->key_map[ev.code], ev.value);
break;
- case ABS_HAT0Y:
- if (ev.value != 0) {
- if (ev.value < 0) joy->dpad |= InputDefault::HAT_MASK_UP;
- else joy->dpad |= InputDefault::HAT_MASK_DOWN;
+ case EV_ABS:
+
+ switch (ev.code) {
+ case ABS_HAT0X:
+ if (ev.value != 0) {
+ if (ev.value < 0)
+ joy->dpad |= InputDefault::HAT_MASK_LEFT;
+ else
+ joy->dpad |= InputDefault::HAT_MASK_RIGHT;
+ } else
+ joy->dpad &= ~(InputDefault::HAT_MASK_LEFT | InputDefault::HAT_MASK_RIGHT);
+
+ p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
+ break;
+
+ case ABS_HAT0Y:
+ if (ev.value != 0) {
+ if (ev.value < 0)
+ joy->dpad |= InputDefault::HAT_MASK_UP;
+ else
+ joy->dpad |= InputDefault::HAT_MASK_DOWN;
+ } else
+ joy->dpad &= ~(InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_DOWN);
+
+ p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
+ break;
+
+ default:
+ if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
+ InputDefault::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
+ joy->curr_axis[joy->abs_map[ev.code]] = value;
+ }
+ break;
}
- else joy->dpad &= ~(InputDefault::HAT_MASK_UP | InputDefault::HAT_MASK_DOWN);
-
- p_event_id = input->joy_hat(p_event_id, i, joy->dpad);
break;
-
- default:
- if (joy->abs_map[ev.code] != -1 && joy->abs_info[ev.code]) {
- InputDefault::JoyAxis value = axis_correct(joy->abs_info[ev.code], ev.value);
- joy->curr_axis[joy->abs_map[ev.code]] = value;
- }
- break;
- }
- break;
}
}
}
diff --git a/platform/x11/joypad_linux.h b/platform/x11/joypad_linux.h
index 310f5c1488..f90ca9319a 100644
--- a/platform/x11/joypad_linux.h
+++ b/platform/x11/joypad_linux.h
@@ -33,23 +33,22 @@
#ifdef JOYDEV_ENABLED
#include "main/input_default.h"
-#include "os/thread.h"
#include "os/mutex.h"
+#include "os/thread.h"
struct input_absinfo;
-class JoypadLinux
-{
+class JoypadLinux {
public:
JoypadLinux(InputDefault *in);
~JoypadLinux();
uint32_t process_joypads(uint32_t p_event_id);
-private:
+private:
enum {
JOYPADS_MAX = 16,
MAX_ABS = 63,
- MAX_KEY = 767, // Hack because <linux/input.h> can't be included here
+ MAX_KEY = 767, // Hack because <linux/input.h> can't be included here
};
struct Joypad {
@@ -90,7 +89,7 @@ private:
#endif
void monitor_joypads();
void run_joypad_thread();
- void open_joypad(const char* path);
+ void open_joypad(const char *path);
void joypad_vibration_start(int p_id, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp);
void joypad_vibration_stop(int p_id, uint64_t p_timestamp);
diff --git a/platform/x11/key_mapping_x11.cpp b/platform/x11/key_mapping_x11.cpp
index d25fe40c4d..4cfcffede0 100644
--- a/platform/x11/key_mapping_x11.cpp
+++ b/platform/x11/key_mapping_x11.cpp
@@ -28,7 +28,6 @@
/*************************************************************************/
#include "key_mapping_x11.h"
-
/***** SCAN CODE CONVERSION ******/
struct _XTranslatePair {
@@ -37,162 +36,161 @@ struct _XTranslatePair {
unsigned int keycode;
};
-static _XTranslatePair _xkeysym_to_keycode[]={
- // misc keys
+static _XTranslatePair _xkeysym_to_keycode[] = {
+ // misc keys
- { XK_Escape, KEY_ESCAPE },
- { XK_Tab, KEY_TAB },
- { XK_ISO_Left_Tab, KEY_BACKTAB },
- { XK_BackSpace, KEY_BACKSPACE },
- { XK_Return, KEY_RETURN },
- { XK_Insert, KEY_INSERT },
- { XK_Delete, KEY_DELETE },
- { XK_Clear, KEY_DELETE },
- { XK_Pause, KEY_PAUSE },
- { XK_Print, KEY_PRINT },
- { XK_Home, KEY_HOME },
- { XK_End, KEY_END },
- { XK_Left, KEY_LEFT },
- { XK_Up, KEY_UP },
- { XK_Right, KEY_RIGHT },
- { XK_Down, KEY_DOWN },
- { XK_Prior, KEY_PAGEUP },
- { XK_Next, KEY_PAGEDOWN },
- { XK_Shift_L, KEY_SHIFT },
- { XK_Shift_R, KEY_SHIFT },
- { XK_Shift_Lock, KEY_SHIFT },
- { XK_Control_L, KEY_CONTROL },
- { XK_Control_R, KEY_CONTROL },
- { XK_Meta_L, KEY_META },
- { XK_Meta_R, KEY_META },
- { XK_Alt_L, KEY_ALT },
- { XK_Alt_R, KEY_ALT },
- { XK_Caps_Lock, KEY_CAPSLOCK },
- { XK_Num_Lock, KEY_NUMLOCK },
- { XK_Scroll_Lock, KEY_SCROLLLOCK },
- { XK_Super_L, KEY_SUPER_L },
- { XK_Super_R, KEY_SUPER_R },
- { XK_Menu, KEY_MENU },
- { XK_Hyper_L, KEY_HYPER_L },
- { XK_Hyper_R, KEY_HYPER_R },
- { XK_Help, KEY_HELP },
- { XK_KP_Space, KEY_SPACE },
- { XK_KP_Tab, KEY_TAB },
- { XK_KP_Enter, KEY_ENTER },
- { XK_Home, KEY_HOME },
- { XK_Left, KEY_LEFT },
- { XK_Up, KEY_UP },
- { XK_Right, KEY_RIGHT },
- { XK_Down, KEY_DOWN },
- { XK_Prior, KEY_PAGEUP },
- { XK_Next, KEY_PAGEDOWN },
- { XK_End, KEY_END },
- { XK_Begin, KEY_CLEAR },
- { XK_Insert, KEY_INSERT },
- { XK_Delete, KEY_DELETE },
+ { XK_Escape, KEY_ESCAPE },
+ { XK_Tab, KEY_TAB },
+ { XK_ISO_Left_Tab, KEY_BACKTAB },
+ { XK_BackSpace, KEY_BACKSPACE },
+ { XK_Return, KEY_RETURN },
+ { XK_Insert, KEY_INSERT },
+ { XK_Delete, KEY_DELETE },
+ { XK_Clear, KEY_DELETE },
+ { XK_Pause, KEY_PAUSE },
+ { XK_Print, KEY_PRINT },
+ { XK_Home, KEY_HOME },
+ { XK_End, KEY_END },
+ { XK_Left, KEY_LEFT },
+ { XK_Up, KEY_UP },
+ { XK_Right, KEY_RIGHT },
+ { XK_Down, KEY_DOWN },
+ { XK_Prior, KEY_PAGEUP },
+ { XK_Next, KEY_PAGEDOWN },
+ { XK_Shift_L, KEY_SHIFT },
+ { XK_Shift_R, KEY_SHIFT },
+ { XK_Shift_Lock, KEY_SHIFT },
+ { XK_Control_L, KEY_CONTROL },
+ { XK_Control_R, KEY_CONTROL },
+ { XK_Meta_L, KEY_META },
+ { XK_Meta_R, KEY_META },
+ { XK_Alt_L, KEY_ALT },
+ { XK_Alt_R, KEY_ALT },
+ { XK_Caps_Lock, KEY_CAPSLOCK },
+ { XK_Num_Lock, KEY_NUMLOCK },
+ { XK_Scroll_Lock, KEY_SCROLLLOCK },
+ { XK_Super_L, KEY_SUPER_L },
+ { XK_Super_R, KEY_SUPER_R },
+ { XK_Menu, KEY_MENU },
+ { XK_Hyper_L, KEY_HYPER_L },
+ { XK_Hyper_R, KEY_HYPER_R },
+ { XK_Help, KEY_HELP },
+ { XK_KP_Space, KEY_SPACE },
+ { XK_KP_Tab, KEY_TAB },
+ { XK_KP_Enter, KEY_ENTER },
+ { XK_Home, KEY_HOME },
+ { XK_Left, KEY_LEFT },
+ { XK_Up, KEY_UP },
+ { XK_Right, KEY_RIGHT },
+ { XK_Down, KEY_DOWN },
+ { XK_Prior, KEY_PAGEUP },
+ { XK_Next, KEY_PAGEDOWN },
+ { XK_End, KEY_END },
+ { XK_Begin, KEY_CLEAR },
+ { XK_Insert, KEY_INSERT },
+ { XK_Delete, KEY_DELETE },
//{ XK_KP_Equal, KEY_EQUAL },
//{ XK_KP_Separator, KEY_COMMA },
- { XK_KP_Decimal, KEY_KP_PERIOD },
- { XK_KP_Delete, KEY_KP_PERIOD },
- { XK_KP_Enter, KEY_KP_ENTER },
- { XK_KP_Multiply, KEY_KP_MULTIPLY},
- { XK_KP_Divide, KEY_KP_DIVIDE},
- { XK_KP_Subtract, KEY_KP_SUBTRACT},
- { XK_KP_Add, KEY_KP_ADD},
- { XK_KP_0, KEY_KP_0},
- { XK_KP_1, KEY_KP_1},
- { XK_KP_2, KEY_KP_2},
- { XK_KP_3, KEY_KP_3},
- { XK_KP_4, KEY_KP_4},
- { XK_KP_5, KEY_KP_5},
- { XK_KP_6, KEY_KP_6},
- { XK_KP_7, KEY_KP_7},
- { XK_KP_8, KEY_KP_8},
- { XK_KP_9, KEY_KP_9},
+ { XK_KP_Decimal, KEY_KP_PERIOD },
+ { XK_KP_Delete, KEY_KP_PERIOD },
+ { XK_KP_Enter, KEY_KP_ENTER },
+ { XK_KP_Multiply, KEY_KP_MULTIPLY },
+ { XK_KP_Divide, KEY_KP_DIVIDE },
+ { XK_KP_Subtract, KEY_KP_SUBTRACT },
+ { XK_KP_Add, KEY_KP_ADD },
+ { XK_KP_0, KEY_KP_0 },
+ { XK_KP_1, KEY_KP_1 },
+ { XK_KP_2, KEY_KP_2 },
+ { XK_KP_3, KEY_KP_3 },
+ { XK_KP_4, KEY_KP_4 },
+ { XK_KP_5, KEY_KP_5 },
+ { XK_KP_6, KEY_KP_6 },
+ { XK_KP_7, KEY_KP_7 },
+ { XK_KP_8, KEY_KP_8 },
+ { XK_KP_9, KEY_KP_9 },
// same but with numlock
- { XK_KP_Insert, KEY_KP_0},
- { XK_KP_End, KEY_KP_1},
- { XK_KP_Down, KEY_KP_2},
- { XK_KP_Page_Down, KEY_KP_3},
- { XK_KP_Left, KEY_KP_4},
- { XK_KP_Begin, KEY_KP_5},
- { XK_KP_Right, KEY_KP_6},
- { XK_KP_Home, KEY_KP_7},
- { XK_KP_Up, KEY_KP_8},
- { XK_KP_Page_Up, KEY_KP_9},
- { XK_F1, KEY_F1},
- { XK_F2, KEY_F2},
- { XK_F3, KEY_F3},
- { XK_F4, KEY_F4},
- { XK_F5, KEY_F5},
- { XK_F6, KEY_F6},
- { XK_F7, KEY_F7},
- { XK_F8, KEY_F8},
- { XK_F9, KEY_F9},
- { XK_F10, KEY_F10},
- { XK_F11, KEY_F11},
- { XK_F12, KEY_F12},
- { XK_F13, KEY_F13},
- { XK_F14, KEY_F14},
- { XK_F15, KEY_F15},
- { XK_F16, KEY_F16},
+ { XK_KP_Insert, KEY_KP_0 },
+ { XK_KP_End, KEY_KP_1 },
+ { XK_KP_Down, KEY_KP_2 },
+ { XK_KP_Page_Down, KEY_KP_3 },
+ { XK_KP_Left, KEY_KP_4 },
+ { XK_KP_Begin, KEY_KP_5 },
+ { XK_KP_Right, KEY_KP_6 },
+ { XK_KP_Home, KEY_KP_7 },
+ { XK_KP_Up, KEY_KP_8 },
+ { XK_KP_Page_Up, KEY_KP_9 },
+ { XK_F1, KEY_F1 },
+ { XK_F2, KEY_F2 },
+ { XK_F3, KEY_F3 },
+ { XK_F4, KEY_F4 },
+ { XK_F5, KEY_F5 },
+ { XK_F6, KEY_F6 },
+ { XK_F7, KEY_F7 },
+ { XK_F8, KEY_F8 },
+ { XK_F9, KEY_F9 },
+ { XK_F10, KEY_F10 },
+ { XK_F11, KEY_F11 },
+ { XK_F12, KEY_F12 },
+ { XK_F13, KEY_F13 },
+ { XK_F14, KEY_F14 },
+ { XK_F15, KEY_F15 },
+ { XK_F16, KEY_F16 },
- // media keys
- { XF86XK_Back, KEY_BACK },
- { XF86XK_Forward, KEY_FORWARD },
- { XF86XK_Stop, KEY_STOP },
- { XF86XK_Refresh, KEY_REFRESH },
- { XF86XK_Favorites, KEY_FAVORITES },
- { XF86XK_AudioMedia, KEY_LAUNCHMEDIA },
- { XF86XK_OpenURL, KEY_OPENURL },
- { XF86XK_HomePage, KEY_HOMEPAGE },
- { XF86XK_Search, KEY_SEARCH },
- { XF86XK_AudioLowerVolume, KEY_VOLUMEDOWN },
- { XF86XK_AudioMute, KEY_VOLUMEMUTE },
- { XF86XK_AudioRaiseVolume, KEY_VOLUMEUP },
- { XF86XK_AudioPlay, KEY_MEDIAPLAY },
- { XF86XK_AudioStop, KEY_MEDIASTOP },
- { XF86XK_AudioPrev, KEY_MEDIAPREVIOUS },
- { XF86XK_AudioNext, KEY_MEDIANEXT },
- { XF86XK_AudioRecord, KEY_MEDIARECORD },
+ // media keys
+ { XF86XK_Back, KEY_BACK },
+ { XF86XK_Forward, KEY_FORWARD },
+ { XF86XK_Stop, KEY_STOP },
+ { XF86XK_Refresh, KEY_REFRESH },
+ { XF86XK_Favorites, KEY_FAVORITES },
+ { XF86XK_AudioMedia, KEY_LAUNCHMEDIA },
+ { XF86XK_OpenURL, KEY_OPENURL },
+ { XF86XK_HomePage, KEY_HOMEPAGE },
+ { XF86XK_Search, KEY_SEARCH },
+ { XF86XK_AudioLowerVolume, KEY_VOLUMEDOWN },
+ { XF86XK_AudioMute, KEY_VOLUMEMUTE },
+ { XF86XK_AudioRaiseVolume, KEY_VOLUMEUP },
+ { XF86XK_AudioPlay, KEY_MEDIAPLAY },
+ { XF86XK_AudioStop, KEY_MEDIASTOP },
+ { XF86XK_AudioPrev, KEY_MEDIAPREVIOUS },
+ { XF86XK_AudioNext, KEY_MEDIANEXT },
+ { XF86XK_AudioRecord, KEY_MEDIARECORD },
- // launch keys
- { XF86XK_Mail, KEY_LAUNCHMAIL },
- { XF86XK_MyComputer, KEY_LAUNCH0 },
- { XF86XK_Calculator, KEY_LAUNCH1 },
- { XF86XK_Standby, KEY_STANDBY },
+ // launch keys
+ { XF86XK_Mail, KEY_LAUNCHMAIL },
+ { XF86XK_MyComputer, KEY_LAUNCH0 },
+ { XF86XK_Calculator, KEY_LAUNCH1 },
+ { XF86XK_Standby, KEY_STANDBY },
- { XF86XK_Launch0, KEY_LAUNCH2 },
- { XF86XK_Launch1, KEY_LAUNCH3 },
- { XF86XK_Launch2, KEY_LAUNCH4 },
- { XF86XK_Launch3, KEY_LAUNCH5 },
- { XF86XK_Launch4, KEY_LAUNCH6 },
- { XF86XK_Launch5, KEY_LAUNCH7 },
- { XF86XK_Launch6, KEY_LAUNCH8 },
- { XF86XK_Launch7, KEY_LAUNCH9 },
- { XF86XK_Launch8, KEY_LAUNCHA },
- { XF86XK_Launch9, KEY_LAUNCHB },
- { XF86XK_LaunchA, KEY_LAUNCHC },
- { XF86XK_LaunchB, KEY_LAUNCHD },
- { XF86XK_LaunchC, KEY_LAUNCHE },
- { XF86XK_LaunchD, KEY_LAUNCHF },
+ { XF86XK_Launch0, KEY_LAUNCH2 },
+ { XF86XK_Launch1, KEY_LAUNCH3 },
+ { XF86XK_Launch2, KEY_LAUNCH4 },
+ { XF86XK_Launch3, KEY_LAUNCH5 },
+ { XF86XK_Launch4, KEY_LAUNCH6 },
+ { XF86XK_Launch5, KEY_LAUNCH7 },
+ { XF86XK_Launch6, KEY_LAUNCH8 },
+ { XF86XK_Launch7, KEY_LAUNCH9 },
+ { XF86XK_Launch8, KEY_LAUNCHA },
+ { XF86XK_Launch9, KEY_LAUNCHB },
+ { XF86XK_LaunchA, KEY_LAUNCHC },
+ { XF86XK_LaunchB, KEY_LAUNCHD },
+ { XF86XK_LaunchC, KEY_LAUNCHE },
+ { XF86XK_LaunchD, KEY_LAUNCHF },
- {0, 0 }
+ { 0, 0 }
};
-
unsigned int KeyMappingX11::get_keycode(KeySym p_keysym) {
// kinda bruteforce.. could optimize.
- if (p_keysym<0x100) // Latin 1, maps 1-1
+ if (p_keysym < 0x100) // Latin 1, maps 1-1
return p_keysym;
// look for special key
- for(int idx=0;_xkeysym_to_keycode[idx].keysym!=0;idx++) {
+ for (int idx = 0; _xkeysym_to_keycode[idx].keysym != 0; idx++) {
- if (_xkeysym_to_keycode[idx].keysym==p_keysym)
- return _xkeysym_to_keycode[idx].keycode;
+ if (_xkeysym_to_keycode[idx].keysym == p_keysym)
+ return _xkeysym_to_keycode[idx].keycode;
}
return 0;
@@ -202,20 +200,19 @@ KeySym KeyMappingX11::get_keysym(unsigned int p_code) {
// kinda bruteforce.. could optimize.
- if (p_code<0x100) // Latin 1, maps 1-1
+ if (p_code < 0x100) // Latin 1, maps 1-1
return p_code;
// look for special key
- for(int idx=0;_xkeysym_to_keycode[idx].keysym!=0;idx++) {
+ for (int idx = 0; _xkeysym_to_keycode[idx].keysym != 0; idx++) {
- if (_xkeysym_to_keycode[idx].keycode==p_code)
- return _xkeysym_to_keycode[idx].keysym;
+ if (_xkeysym_to_keycode[idx].keycode == p_code)
+ return _xkeysym_to_keycode[idx].keysym;
}
return 0;
}
-
/***** UNICODE CONVERSION ******/
// Tables taken from FOX toolkit
@@ -228,7 +225,7 @@ struct _XTranslateUnicodePair {
enum {
- _KEYSYM_MAX=759
+ _KEYSYM_MAX = 759
};
static _XTranslateUnicodePair _xkeysym_to_unicode[_KEYSYM_MAX] = {
@@ -995,32 +992,31 @@ static _XTranslateUnicodePair _xkeysym_to_unicode[_KEYSYM_MAX] = {
unsigned int KeyMappingX11::get_unicode_from_keysym(KeySym p_keysym) {
/* Latin-1 */
- if (p_keysym>=0x20 && p_keysym<=0x7e)
+ if (p_keysym >= 0x20 && p_keysym <= 0x7e)
return p_keysym;
- if (p_keysym>=0xa0 && p_keysym<=0xff)
+ if (p_keysym >= 0xa0 && p_keysym <= 0xff)
return p_keysym;
// keypad to latin1 is easy
- if (p_keysym>=0xffaa && p_keysym<=0xffb9)
- return p_keysym-0xff80;
+ if (p_keysym >= 0xffaa && p_keysym <= 0xffb9)
+ return p_keysym - 0xff80;
/* Unicode (may be present)*/
- if((p_keysym&0xff000000)==0x01000000)
- return p_keysym&0x00ffffff;
+ if ((p_keysym & 0xff000000) == 0x01000000)
+ return p_keysym & 0x00ffffff;
- int middle,low=0,high=_KEYSYM_MAX-1;
+ int middle, low = 0, high = _KEYSYM_MAX - 1;
do {
- middle=(high+low)/2;
- if ( _xkeysym_to_unicode[middle].keysym==p_keysym)
+ middle = (high + low) / 2;
+ if (_xkeysym_to_unicode[middle].keysym == p_keysym)
return _xkeysym_to_unicode[middle].unicode;
- if ( _xkeysym_to_unicode[middle].keysym<=p_keysym )
- low=middle+1;
+ if (_xkeysym_to_unicode[middle].keysym <= p_keysym)
+ low = middle + 1;
else
- high=middle-1;
- } while (high>=low);
+ high = middle - 1;
+ } while (high >= low);
return 0;
-
}
struct _XTranslateUnicodePairReverse {
@@ -1031,7 +1027,7 @@ struct _XTranslateUnicodePairReverse {
enum {
- _UNICODE_MAX=750
+ _UNICODE_MAX = 750
};
static _XTranslateUnicodePairReverse _unicode_to_xkeysym[_UNICODE_MAX] = {
@@ -1791,23 +1787,23 @@ KeySym KeyMappingX11::get_keysym_from_unicode(unsigned int p_unicode) {
/* Latin 1 */
- if (p_unicode>=0x20 && p_unicode<=0x7e)
+ if (p_unicode >= 0x20 && p_unicode <= 0x7e)
return p_unicode;
- if (p_unicode>=0xa0 && p_unicode<=0xff)
+ if (p_unicode >= 0xa0 && p_unicode <= 0xff)
return p_unicode;
- int middle,low=0,high=_UNICODE_MAX-1;
+ int middle, low = 0, high = _UNICODE_MAX - 1;
do {
- middle=(high+low)/2;
- if ( _unicode_to_xkeysym[middle].keysym==p_unicode)
+ middle = (high + low) / 2;
+ if (_unicode_to_xkeysym[middle].keysym == p_unicode)
return _unicode_to_xkeysym[middle].keysym;
- if ( _unicode_to_xkeysym[middle].keysym<=p_unicode )
- low=middle+1;
+ if (_unicode_to_xkeysym[middle].keysym <= p_unicode)
+ low = middle + 1;
else
- high=middle-1;
- } while (high>=low);
+ high = middle - 1;
+ } while (high >= low);
// if not found, let's hope X understands it as unicode
- return p_unicode|0x01000000;
+ return p_unicode | 0x01000000;
}
diff --git a/platform/x11/key_mapping_x11.h b/platform/x11/key_mapping_x11.h
index 9749b2ec2a..8210df06e7 100644
--- a/platform/x11/key_mapping_x11.h
+++ b/platform/x11/key_mapping_x11.h
@@ -32,8 +32,8 @@
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-#include <X11/Xlib.h>
#include <X11/XF86keysym.h>
+#include <X11/Xlib.h>
#define XK_MISCELLANY
#define XK_LATIN1
#define XK_XKB_KEYS
@@ -42,14 +42,13 @@
#include "os/keyboard.h"
class KeyMappingX11 {
- KeyMappingX11() {};
+ KeyMappingX11(){};
+
public:
static unsigned int get_keycode(KeySym p_keysym);
static KeySym get_keysym(unsigned int p_code);
static unsigned int get_unicode_from_keysym(KeySym p_keysym);
static KeySym get_keysym_from_unicode(unsigned int p_unicode);
-
};
-
#endif
diff --git a/platform/x11/os_x11.cpp b/platform/x11/os_x11.cpp
index 689fe076f1..4f79f2fb5d 100644
--- a/platform/x11/os_x11.cpp
+++ b/platform/x11/os_x11.cpp
@@ -26,45 +26,42 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "servers/visual/visual_server_raster.h"
-#include "drivers/gles3/rasterizer_gles3.h"
#include "os_x11.h"
+#include "drivers/gles3/rasterizer_gles3.h"
+#include "errno.h"
#include "key_mapping_x11.h"
+#include "print_string.h"
+#include "servers/physics/physics_server_sw.h"
+#include "servers/visual/visual_server_raster.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include "print_string.h"
-#include "servers/physics/physics_server_sw.h"
-#include "errno.h"
#include "X11/Xutil.h"
#include "X11/Xatom.h"
#include "X11/extensions/Xinerama.h"
// ICCCM
-#define WM_NormalState 1L // window normal state
-#define WM_IconicState 3L // window minimized
+#define WM_NormalState 1L // window normal state
+#define WM_IconicState 3L // window minimized
// EWMH
-#define _NET_WM_STATE_REMOVE 0L // remove/unset property
-#define _NET_WM_STATE_ADD 1L // add/set property
-#define _NET_WM_STATE_TOGGLE 2L // toggle property
+#define _NET_WM_STATE_REMOVE 0L // remove/unset property
+#define _NET_WM_STATE_ADD 1L // add/set property
+#define _NET_WM_STATE_TOGGLE 2L // toggle property
#include "main/main.h"
-
-
-#include <sys/types.h>
-#include <sys/stat.h>
+#include <dlfcn.h>
#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
#include <unistd.h>
-#include <dlfcn.h>
//stupid linux.h
#ifdef KEY_TAB
#undef KEY_TAB
#endif
-
#include <X11/Xatom.h>
#undef CursorShape
@@ -73,75 +70,73 @@ int OS_X11::get_video_driver_count() const {
return 1;
}
-const char * OS_X11::get_video_driver_name(int p_driver) const {
+const char *OS_X11::get_video_driver_name(int p_driver) const {
return "GLES3";
}
OS::VideoMode OS_X11::get_default_video_mode() const {
- return OS::VideoMode(1024,600,false);
+ return OS::VideoMode(1024, 600, false);
}
int OS_X11::get_audio_driver_count() const {
- return AudioDriverManager::get_driver_count();
+ return AudioDriverManager::get_driver_count();
}
const char *OS_X11::get_audio_driver_name(int p_driver) const {
- AudioDriver* driver = AudioDriverManager::get_driver(p_driver);
- ERR_FAIL_COND_V( !driver, "" );
- return AudioDriverManager::get_driver(p_driver)->get_name();
+ AudioDriver *driver = AudioDriverManager::get_driver(p_driver);
+ ERR_FAIL_COND_V(!driver, "");
+ return AudioDriverManager::get_driver(p_driver)->get_name();
}
-void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+void OS_X11::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
- last_button_state=0;
+ last_button_state = 0;
- xmbstring=NULL;
- event_id=0;
- x11_window=0;
- last_click_ms=0;
- args=OS::get_singleton()->get_cmdline_args();
- current_videomode=p_desired;
- main_loop=NULL;
- last_timestamp=0;
- last_mouse_pos_valid=false;
- last_keyrelease_time=0;
+ xmbstring = NULL;
+ event_id = 0;
+ x11_window = 0;
+ last_click_ms = 0;
+ args = OS::get_singleton()->get_cmdline_args();
+ current_videomode = p_desired;
+ main_loop = NULL;
+ last_timestamp = 0;
+ last_mouse_pos_valid = false;
+ last_keyrelease_time = 0;
xdnd_version = 0;
- if (get_render_thread_mode()==RENDER_SEPARATE_THREAD) {
+ if (get_render_thread_mode() == RENDER_SEPARATE_THREAD) {
XInitThreads();
}
/** XLIB INITIALIZATION **/
x11_display = XOpenDisplay(NULL);
- char * modifiers = XSetLocaleModifiers ("@im=none");
- if (modifiers==NULL) {
+ char *modifiers = XSetLocaleModifiers("@im=none");
+ if (modifiers == NULL) {
WARN_PRINT("Error setting locale modifiers");
}
- const char* err;
+ const char *err;
xrr_get_monitors = NULL;
xrr_free_monitors = NULL;
int xrandr_major = 0;
int xrandr_minor = 0;
int event_base, error_base;
- xrandr_ext_ok = XRRQueryExtension(x11_display,&event_base, &error_base);
+ xrandr_ext_ok = XRRQueryExtension(x11_display, &event_base, &error_base);
xrandr_handle = dlopen("libXrandr.so.2", RTLD_LAZY);
if (!xrandr_handle) {
err = dlerror();
fprintf(stderr, "could not load libXrandr.so.2, Error: %s\n", err);
- }
- else {
+ } else {
XRRQueryVersion(x11_display, &xrandr_major, &xrandr_minor);
if (((xrandr_major << 8) | xrandr_minor) >= 0x0105) {
- xrr_get_monitors = (xrr_get_monitors_t) dlsym(xrandr_handle, "XRRGetMonitors");
+ xrr_get_monitors = (xrr_get_monitors_t)dlsym(xrandr_handle, "XRRGetMonitors");
if (!xrr_get_monitors) {
err = dlerror();
fprintf(stderr, "could not find symbol XRRGetMonitors\nError: %s\n", err);
- }
- else {
- xrr_free_monitors = (xrr_free_monitors_t) dlsym(xrandr_handle, "XRRFreeMonitors");
+ } else {
+ xrr_free_monitors = (xrr_free_monitors_t)dlsym(xrandr_handle, "XRRFreeMonitors");
if (!xrr_free_monitors) {
err = dlerror();
fprintf(stderr, "could not find XRRFreeMonitors\nError: %s\n", err);
@@ -151,39 +146,38 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
}
}
- xim = XOpenIM (x11_display, NULL, NULL, NULL);
-
+ xim = XOpenIM(x11_display, NULL, NULL, NULL);
if (xim == NULL) {
WARN_PRINT("XOpenIM failed");
- xim_style=0L;
+ xim_style = 0L;
} else {
- ::XIMStyles *xim_styles=NULL;
- xim_style=0L;
- char *imvalret=NULL;
+ ::XIMStyles *xim_styles = NULL;
+ xim_style = 0L;
+ char *imvalret = NULL;
imvalret = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
if (imvalret != NULL || xim_styles == NULL) {
- fprintf (stderr, "Input method doesn't support any styles\n");
+ fprintf(stderr, "Input method doesn't support any styles\n");
}
if (xim_styles) {
xim_style = 0L;
- for (int i=0;i<xim_styles->count_styles;i++) {
+ for (int i = 0; i < xim_styles->count_styles; i++) {
if (xim_styles->supported_styles[i] ==
- (XIMPreeditNothing | XIMStatusNothing)) {
+ (XIMPreeditNothing | XIMStatusNothing)) {
- xim_style = xim_styles->supported_styles[i];
- break;
- }
+ xim_style = xim_styles->supported_styles[i];
+ break;
+ }
}
- XFree (xim_styles);
+ XFree(xim_styles);
}
- XFree( imvalret );
+ XFree(imvalret);
}
- /*
+/*
char* windowid = getenv("GODOT_WINDOWID");
if (windowid) {
@@ -199,12 +193,11 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
};
*/
- // maybe contextgl wants to be in charge of creating the window
- //print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
+// maybe contextgl wants to be in charge of creating the window
+//print_line("def videomode "+itos(current_videomode.width)+","+itos(current_videomode.height));
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
-
- context_gl = memnew( ContextGL_X11( x11_display, x11_window,current_videomode, true ) );
+ context_gl = memnew(ContextGL_X11(x11_display, x11_window, current_videomode, true));
context_gl->initialize();
RasterizerGLES3::register_config();
@@ -212,7 +205,7 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
RasterizerGLES3::make_current();
#endif
- visual_server = memnew( VisualServerRaster );
+ visual_server = memnew(VisualServerRaster);
#if 0
if (get_render_thread_mode()!=RENDER_THREAD_UNSAFE) {
@@ -221,7 +214,7 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
#endif
// borderless fullscreen window mode
if (current_videomode.fullscreen) {
- // needed for lxde/openbox, possibly others
+ // needed for lxde/openbox, possibly others
Hints hints;
Atom property;
hints.flags = 2;
@@ -257,9 +250,9 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
xsh->flags = PMinSize | PMaxSize;
XWindowAttributes xwa;
if (current_videomode.fullscreen) {
- XGetWindowAttributes(x11_display,DefaultRootWindow(x11_display),&xwa);
+ XGetWindowAttributes(x11_display, DefaultRootWindow(x11_display), &xwa);
} else {
- XGetWindowAttributes(x11_display,x11_window,&xwa);
+ XGetWindowAttributes(x11_display, x11_window, &xwa);
}
xsh->min_width = xwa.width;
xsh->max_width = xwa.width;
@@ -271,52 +264,49 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
AudioDriverManager::get_driver(p_audio_driver)->set_singleton();
- audio_driver_index=p_audio_driver;
- if (AudioDriverManager::get_driver(p_audio_driver)->init()!=OK) {
+ audio_driver_index = p_audio_driver;
+ if (AudioDriverManager::get_driver(p_audio_driver)->init() != OK) {
- bool success=false;
- audio_driver_index=-1;
- for(int i=0;i<AudioDriverManager::get_driver_count();i++) {
- if (i==p_audio_driver)
+ bool success = false;
+ audio_driver_index = -1;
+ for (int i = 0; i < AudioDriverManager::get_driver_count(); i++) {
+ if (i == p_audio_driver)
continue;
AudioDriverManager::get_driver(i)->set_singleton();
- if (AudioDriverManager::get_driver(i)->init()==OK) {
- success=true;
- print_line("Audio Driver Failed: "+String(AudioDriverManager::get_driver(p_audio_driver)->get_name()));
- print_line("Using alternate audio driver: "+String(AudioDriverManager::get_driver(i)->get_name()));
- audio_driver_index=i;
+ if (AudioDriverManager::get_driver(i)->init() == OK) {
+ success = true;
+ print_line("Audio Driver Failed: " + String(AudioDriverManager::get_driver(p_audio_driver)->get_name()));
+ print_line("Using alternate audio driver: " + String(AudioDriverManager::get_driver(i)->get_name()));
+ audio_driver_index = i;
break;
}
}
if (!success) {
ERR_PRINT("Initializing audio failed.");
}
-
}
-
-
ERR_FAIL_COND(!visual_server);
- ERR_FAIL_COND(x11_window==0);
+ ERR_FAIL_COND(x11_window == 0);
XSetWindowAttributes new_attr;
- new_attr.event_mask=KeyPressMask | KeyReleaseMask | ButtonPressMask |
- ButtonReleaseMask | EnterWindowMask |
- LeaveWindowMask | PointerMotionMask |
- Button1MotionMask |
- Button2MotionMask | Button3MotionMask |
- Button4MotionMask | Button5MotionMask |
- ButtonMotionMask | KeymapStateMask |
- ExposureMask | VisibilityChangeMask |
- StructureNotifyMask |
- SubstructureNotifyMask | SubstructureRedirectMask |
- FocusChangeMask | PropertyChangeMask |
- ColormapChangeMask | OwnerGrabButtonMask;
+ new_attr.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask |
+ ButtonReleaseMask | EnterWindowMask |
+ LeaveWindowMask | PointerMotionMask |
+ Button1MotionMask |
+ Button2MotionMask | Button3MotionMask |
+ Button4MotionMask | Button5MotionMask |
+ ButtonMotionMask | KeymapStateMask |
+ ExposureMask | VisibilityChangeMask |
+ StructureNotifyMask |
+ SubstructureNotifyMask | SubstructureRedirectMask |
+ FocusChangeMask | PropertyChangeMask |
+ ColormapChangeMask | OwnerGrabButtonMask;
- XChangeWindowAttributes(x11_display, x11_window,CWEventMask,&new_attr);
+ XChangeWindowAttributes(x11_display, x11_window, CWEventMask, &new_attr);
- XClassHint* classHint;
+ XClassHint *classHint;
/* set the titlebar name */
XStoreName(x11_display, x11_window, "Godot");
@@ -333,39 +323,37 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
wm_delete = XInternAtom(x11_display, "WM_DELETE_WINDOW", true);
XSetWMProtocols(x11_display, x11_window, &wm_delete, 1);
-
if (xim && xim_style) {
- xic = XCreateIC (xim,XNInputStyle, xim_style,XNClientWindow,x11_window,XNFocusWindow, x11_window, (char*)NULL);
+ xic = XCreateIC(xim, XNInputStyle, xim_style, XNClientWindow, x11_window, XNFocusWindow, x11_window, (char *)NULL);
} else {
- xic=NULL;
+ xic = NULL;
WARN_PRINT("XCreateIC couldn't create xic");
-
}
- XcursorSetTheme(x11_display,"default");
+ XcursorSetTheme(x11_display, "default");
cursor_size = XcursorGetDefaultSize(x11_display);
cursor_theme = XcursorGetTheme(x11_display);
if (!cursor_theme) {
print_line("not found theme");
- cursor_theme="default";
+ cursor_theme = "default";
}
- for(int i=0;i<CURSOR_MAX;i++) {
+ for (int i = 0; i < CURSOR_MAX; i++) {
- cursors[i]=None;
- img[i]=NULL;
+ cursors[i] = None;
+ img[i] = NULL;
}
- current_cursor=CURSOR_ARROW;
+ current_cursor = CURSOR_ARROW;
if (cursor_theme) {
//print_line("cursor theme: "+String(cursor_theme));
- for(int i=0;i<CURSOR_MAX;i++) {
+ for (int i = 0; i < CURSOR_MAX; i++) {
- static const char *cursor_file[]={
+ static const char *cursor_file[] = {
"left_ptr",
"xterm",
"hand2",
@@ -385,26 +373,25 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
"question_arrow"
};
- img[i] = XcursorLibraryLoadImage(cursor_file[i],cursor_theme,cursor_size);
+ img[i] = XcursorLibraryLoadImage(cursor_file[i], cursor_theme, cursor_size);
if (img[i]) {
- cursors[i]=XcursorImageLoadCursor(x11_display,img[i]);
+ cursors[i] = XcursorImageLoadCursor(x11_display, img[i]);
//print_line("found cursor: "+String(cursor_file[i])+" id "+itos(cursors[i]));
} else {
if (OS::is_stdout_verbose())
- print_line("failed cursor: "+String(cursor_file[i]));
+ print_line("failed cursor: " + String(cursor_file[i]));
}
}
}
-
{
Pixmap cursormask;
- XGCValues xgc;
- GC gc;
- XColor col;
- Cursor cursor;
+ XGCValues xgc;
+ GC gc;
+ XColor col;
+ Cursor cursor;
- cursormask = XCreatePixmap(x11_display, RootWindow(x11_display,DefaultScreen(x11_display)), 1, 1, 1);
+ cursormask = XCreatePixmap(x11_display, RootWindow(x11_display, DefaultScreen(x11_display)), 1, 1, 1);
xgc.function = GXclear;
gc = XCreateGC(x11_display, cursormask, GCFunction, &xgc);
XFillRectangle(x11_display, cursormask, gc, 0, 0, 1, 1);
@@ -412,25 +399,23 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
col.red = 0;
col.flags = 4;
cursor = XCreatePixmapCursor(x11_display,
- cursormask, cursormask,
- &col, &col, 0, 0);
- XFreePixmap(x11_display, cursormask);
- XFreeGC(x11_display, gc);
-
+ cursormask, cursormask,
+ &col, &col, 0, 0);
+ XFreePixmap(x11_display, cursormask);
+ XFreeGC(x11_display, gc);
- if (cursor == None)
- {
- ERR_PRINT("FAILED CREATING CURSOR");
- }
+ if (cursor == None) {
+ ERR_PRINT("FAILED CREATING CURSOR");
+ }
- null_cursor=cursor;
+ null_cursor = cursor;
}
set_cursor_shape(CURSOR_BUSY);
//Set Xdnd (drag & drop) support
Atom XdndAware = XInternAtom(x11_display, "XdndAware", False);
- Atom version=5;
- XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*)&version, 1);
+ Atom version = 5;
+ XChangeProperty(x11_display, x11_window, XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char *)&version, 1);
xdnd_enter = XInternAtom(x11_display, "XdndEnter", False);
xdnd_position = XInternAtom(x11_display, "XdndPosition", False);
@@ -443,32 +428,32 @@ void OS_X11::initialize(const VideoMode& p_desired,int p_video_driver,int p_audi
visual_server->init();
//
- physics_server = memnew( PhysicsServerSW );
+ physics_server = memnew(PhysicsServerSW);
physics_server->init();
//physics_2d_server = memnew( Physics2DServerSW );
physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
physics_2d_server->init();
- input = memnew( InputDefault );
+ input = memnew(InputDefault);
window_has_focus = true; // Set focus to true at init
#ifdef JOYDEV_ENABLED
- joypad = memnew( JoypadLinux(input));
+ joypad = memnew(JoypadLinux(input));
#endif
_ensure_data_dir();
}
void OS_X11::finalize() {
- if(main_loop)
+ if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
for (int i = 0; i < get_audio_driver_count(); i++) {
AudioDriverManager::get_driver(i)->finish();
}
- /*
+/*
if (debugger_connection_console) {
memdelete(debugger_connection_console);
}
@@ -492,61 +477,58 @@ void OS_X11::finalize() {
if (xrandr_handle)
dlclose(xrandr_handle);
- XUnmapWindow( x11_display, x11_window );
- XDestroyWindow( x11_display, x11_window );
+ XUnmapWindow(x11_display, x11_window);
+ XDestroyWindow(x11_display, x11_window);
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
memdelete(context_gl);
#endif
- for(int i=0;i<CURSOR_MAX;i++) {
- if( cursors[i] != None )
- XFreeCursor( x11_display, cursors[i] );
- if( img[i] != NULL )
- XcursorImageDestroy( img[i] );
+ for (int i = 0; i < CURSOR_MAX; i++) {
+ if (cursors[i] != None)
+ XFreeCursor(x11_display, cursors[i]);
+ if (img[i] != NULL)
+ XcursorImageDestroy(img[i]);
};
- XDestroyIC( xic );
- XCloseIM( xim );
+ XDestroyIC(xic);
+ XCloseIM(xim);
XCloseDisplay(x11_display);
if (xmbstring)
memfree(xmbstring);
-
args.clear();
-
}
-
void OS_X11::set_mouse_mode(MouseMode p_mode) {
- if (p_mode==mouse_mode)
+ if (p_mode == mouse_mode)
return;
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED)
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED)
XUngrabPointer(x11_display, CurrentTime);
// The only modes that show a cursor are VISIBLE and CONFINED
bool showCursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
if (showCursor) {
- XUndefineCursor(x11_display,x11_window); // show cursor
+ XUndefineCursor(x11_display, x11_window); // show cursor
} else {
- XDefineCursor(x11_display,x11_window,null_cursor); // hide cursor
+ XDefineCursor(x11_display, x11_window, null_cursor); // hide cursor
}
- mouse_mode=p_mode;
+ mouse_mode = p_mode;
- if (mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED) {
- while(true) {
+ while (true) {
//flush pending motion events
if (XPending(x11_display) > 0) {
XEvent event;
XPeekEvent(x11_display, &event);
- if (event.type==MotionNotify) {
- XNextEvent(x11_display,&event);
+ if (event.type == MotionNotify) {
+ XNextEvent(x11_display, &event);
} else {
break;
}
@@ -556,30 +538,30 @@ void OS_X11::set_mouse_mode(MouseMode p_mode) {
}
if (XGrabPointer(
- x11_display, x11_window, True,
- ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
- GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) {
+ x11_display, x11_window, True,
+ ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
+ GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime) != GrabSuccess) {
ERR_PRINT("NO GRAB");
}
- center.x = current_videomode.width/2;
- center.y = current_videomode.height/2;
+ center.x = current_videomode.width / 2;
+ center.y = current_videomode.height / 2;
XWarpPointer(x11_display, None, x11_window,
- 0,0,0,0, (int)center.x, (int)center.y);
+ 0, 0, 0, 0, (int)center.x, (int)center.y);
input->set_mouse_pos(center);
} else {
- do_mouse_warp=false;
+ do_mouse_warp = false;
}
XFlush(x11_display);
}
-void OS_X11::warp_mouse_pos(const Point2& p_to) {
+void OS_X11::warp_mouse_pos(const Point2 &p_to) {
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
- last_mouse_pos=p_to;
+ last_mouse_pos = p_to;
} else {
/*XWindowAttributes xwa;
@@ -587,9 +569,8 @@ void OS_X11::warp_mouse_pos(const Point2& p_to) {
printf("%d %d\n", xwa.x, xwa.y); needed? */
XWarpPointer(x11_display, None, x11_window,
- 0,0,0,0, (int)p_to.x , (int)p_to.y);
+ 0, 0, 0, 0, (int)p_to.x, (int)p_to.y);
}
-
}
OS::MouseMode OS_X11::get_mouse_mode() const {
@@ -604,22 +585,22 @@ Point2 OS_X11::get_mouse_pos() const {
return last_mouse_pos;
}
-void OS_X11::set_window_title(const String& p_title) {
- XStoreName(x11_display,x11_window,p_title.utf8().get_data());
+void OS_X11::set_window_title(const String &p_title) {
+ XStoreName(x11_display, x11_window, p_title.utf8().get_data());
Atom _net_wm_name = XInternAtom(x11_display, "_NET_WM_NAME", false);
Atom utf8_string = XInternAtom(x11_display, "UTF8_STRING", false);
- XChangeProperty( x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char*) p_title.utf8().get_data(), p_title.utf8().length());
+ XChangeProperty(x11_display, x11_window, _net_wm_name, utf8_string, 8, PropModeReplace, (unsigned char *)p_title.utf8().get_data(), p_title.utf8().length());
}
-void OS_X11::set_video_mode(const VideoMode& p_video_mode,int p_screen) {
+void OS_X11::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
}
OS::VideoMode OS_X11::get_video_mode(int p_screen) const {
return current_videomode;
}
-void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen) const {
+void OS_X11::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
}
void OS_X11::set_wm_fullscreen(bool p_enabled) {
@@ -638,31 +619,30 @@ void OS_X11::set_wm_fullscreen(bool p_enabled) {
xev.xclient.data.l[2] = 0;
XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
-
}
int OS_X11::get_screen_count() const {
// Using Xinerama Extension
int event_base, error_base;
const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
- if( !ext_okay ) return 0;
+ if (!ext_okay) return 0;
int count;
- XineramaScreenInfo* xsi = XineramaQueryScreens(x11_display, &count);
+ XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
XFree(xsi);
return count;
}
int OS_X11::get_current_screen() const {
- int x,y;
- Window child;
- XTranslateCoordinates( x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
+ int x, y;
+ Window child;
+ XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
int count = get_screen_count();
- for(int i=0; i<count; i++) {
+ for (int i = 0; i < count; i++) {
Point2i pos = get_screen_position(i);
Size2i size = get_screen_size(i);
- if( (x >= pos.x && x <pos.x + size.width) && (y >= pos.y && y < pos.y + size.height) )
+ if ((x >= pos.x && x < pos.x + size.width) && (y >= pos.y && y < pos.y + size.height))
return i;
}
return 0;
@@ -670,16 +650,15 @@ int OS_X11::get_current_screen() const {
void OS_X11::set_current_screen(int p_screen) {
int count = get_screen_count();
- if(p_screen >= count) return;
+ if (p_screen >= count) return;
- if( current_videomode.fullscreen ) {
+ if (current_videomode.fullscreen) {
Point2i position = get_screen_position(p_screen);
Size2i size = get_screen_size(p_screen);
- XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y);
- }
- else {
- if( p_screen != get_current_screen() ) {
+ XMoveResizeWindow(x11_display, x11_window, position.x, position.y, size.x, size.y);
+ } else {
+ if (p_screen != get_current_screen()) {
Point2i position = get_screen_position(p_screen);
XMoveWindow(x11_display, x11_window, position.x, position.y);
}
@@ -690,14 +669,14 @@ Point2 OS_X11::get_screen_position(int p_screen) const {
// Using Xinerama Extension
int event_base, error_base;
const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
- if( !ext_okay ) {
- return Point2i(0,0);
+ if (!ext_okay) {
+ return Point2i(0, 0);
}
int count;
- XineramaScreenInfo* xsi = XineramaQueryScreens(x11_display, &count);
- if( p_screen >= count ) {
- return Point2i(0,0);
+ XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
+ if (p_screen >= count) {
+ return Point2i(0, 0);
}
Point2i position = Point2i(xsi[p_screen].x_org, xsi[p_screen].y_org);
@@ -711,11 +690,11 @@ Size2 OS_X11::get_screen_size(int p_screen) const {
// Using Xinerama Extension
int event_base, error_base;
const Bool ext_okay = XineramaQueryExtension(x11_display, &event_base, &error_base);
- if( !ext_okay ) return Size2i(0,0);
+ if (!ext_okay) return Size2i(0, 0);
int count;
- XineramaScreenInfo* xsi = XineramaQueryScreens(x11_display, &count);
- if( p_screen >= count ) return Size2i(0,0);
+ XineramaScreenInfo *xsi = XineramaQueryScreens(x11_display, &count);
+ if (p_screen >= count) return Size2i(0, 0);
Size2i size = Point2i(xsi[p_screen].width, xsi[p_screen].height);
XFree(xsi);
@@ -734,47 +713,46 @@ int OS_X11::get_screen_dpi(int p_screen) const {
if (xrr_get_monitors) {
xrr_monitor_info *monitors = xrr_get_monitors(x11_display, x11_window, true, &count);
if (p_screen < count) {
- double xdpi = sc.width / (double) monitors[p_screen].mwidth * 25.4;
- double ydpi = sc.height / (double) monitors[p_screen].mheight * 25.4;
+ double xdpi = sc.width / (double)monitors[p_screen].mwidth * 25.4;
+ double ydpi = sc.height / (double)monitors[p_screen].mheight * 25.4;
xrr_free_monitors(monitors);
return (xdpi + ydpi) / 2;
}
xrr_free_monitors(monitors);
- }
- else if (p_screen == 0) {
+ } else if (p_screen == 0) {
XRRScreenSize *sizes = XRRSizes(x11_display, 0, &count);
if (sizes) {
- double xdpi = sc.width / (double) sizes[0].mwidth * 25.4;
- double ydpi = sc.height / (double) sizes[0].mheight * 25.4;
+ double xdpi = sc.width / (double)sizes[0].mwidth * 25.4;
+ double ydpi = sc.height / (double)sizes[0].mheight * 25.4;
return (xdpi + ydpi) / 2;
}
}
}
- int width_mm = DisplayWidthMM(x11_display, p_screen);
+ int width_mm = DisplayWidthMM(x11_display, p_screen);
int height_mm = DisplayHeightMM(x11_display, p_screen);
- double xdpi = (width_mm ? sc.width / (double) width_mm * 25.4 : 0);
- double ydpi = (height_mm ? sc.height / (double) height_mm * 25.4 : 0);
+ double xdpi = (width_mm ? sc.width / (double)width_mm * 25.4 : 0);
+ double ydpi = (height_mm ? sc.height / (double)height_mm * 25.4 : 0);
if (xdpi || xdpi)
- return (xdpi + ydpi)/(xdpi && ydpi ? 2 : 1);
+ return (xdpi + ydpi) / (xdpi && ydpi ? 2 : 1);
//could not get dpi
return 96;
}
Point2 OS_X11::get_window_position() const {
- int x,y;
+ int x, y;
Window child;
- XTranslateCoordinates( x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
+ XTranslateCoordinates(x11_display, x11_window, DefaultRootWindow(x11_display), 0, 0, &x, &y, &child);
int screen = get_current_screen();
Point2i screen_position = get_screen_position(screen);
- return Point2i(x-screen_position.x, y-screen_position.y);
+ return Point2i(x - screen_position.x, y - screen_position.y);
}
-void OS_X11::set_window_position(const Point2& p_position) {
- XMoveWindow(x11_display,x11_window,p_position.x,p_position.y);
+void OS_X11::set_window_position(const Point2 &p_position) {
+ XMoveWindow(x11_display, x11_window, p_position.x, p_position.y);
}
Size2 OS_X11::get_window_size() const {
@@ -820,7 +798,7 @@ void OS_X11::set_window_resizable(bool p_enabled) {
xsh = XAllocSizeHints();
xsh->flags = p_enabled ? 0L : PMinSize | PMaxSize;
- if(!p_enabled) {
+ if (!p_enabled) {
xsh->min_width = size.x;
xsh->max_width = size.x;
xsh->min_height = size.y;
@@ -849,8 +827,8 @@ void OS_X11::set_window_minimized(bool p_enabled) {
XSendEvent(x11_display, DefaultRootWindow(x11_display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev);
- Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
- Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
+ Atom wm_state = XInternAtom(x11_display, "_NET_WM_STATE", False);
+ Atom wm_hidden = XInternAtom(x11_display, "_NET_WM_STATE_HIDDEN", False);
memset(&xev, 0, sizeof(xev));
xev.type = ClientMessage;
@@ -865,31 +843,30 @@ void OS_X11::set_window_minimized(bool p_enabled) {
bool OS_X11::is_window_minimized() const {
// Using ICCCM -- Inter-Client Communication Conventions Manual
- Atom property = XInternAtom(x11_display,"WM_STATE", True);
- Atom type;
- int format;
- unsigned long len;
- unsigned long remaining;
- unsigned char *data = NULL;
-
- int result = XGetWindowProperty(
- x11_display,
- x11_window,
- property,
- 0,
- 32,
- False,
- AnyPropertyType,
- &type,
- &format,
- &len,
- &remaining,
- &data
- );
-
- if( result == Success ) {
- long *state = (long *) data;
- if( state[0] == WM_IconicState )
+ Atom property = XInternAtom(x11_display, "WM_STATE", True);
+ Atom type;
+ int format;
+ unsigned long len;
+ unsigned long remaining;
+ unsigned char *data = NULL;
+
+ int result = XGetWindowProperty(
+ x11_display,
+ x11_window,
+ property,
+ 0,
+ 32,
+ False,
+ AnyPropertyType,
+ &type,
+ &format,
+ &len,
+ &remaining,
+ &data);
+
+ if (result == Success) {
+ long *state = (long *)data;
+ if (state[0] == WM_IconicState)
return true;
}
return false;
@@ -918,7 +895,7 @@ void OS_X11::set_window_maximized(bool p_enabled) {
bool OS_X11::is_window_maximized() const {
// Using EWMH -- Extended Window Manager Hints
- Atom property = XInternAtom(x11_display,"_NET_WM_STATE",False );
+ Atom property = XInternAtom(x11_display, "_NET_WM_STATE", False);
Atom type;
int format;
unsigned long len;
@@ -937,23 +914,22 @@ bool OS_X11::is_window_maximized() const {
&format,
&len,
&remaining,
- &data
- );
+ &data);
- if(result == Success) {
- Atom *atoms = (Atom*) data;
+ if (result == Success) {
+ Atom *atoms = (Atom *)data;
Atom wm_max_horz = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_HORZ", False);
Atom wm_max_vert = XInternAtom(x11_display, "_NET_WM_STATE_MAXIMIZED_VERT", False);
bool found_wm_max_horz = false;
bool found_wm_max_vert = false;
- for( unsigned int i=0; i < len; i++ ) {
- if( atoms[i] == wm_max_horz )
+ for (unsigned int i = 0; i < len; i++) {
+ if (atoms[i] == wm_max_horz)
found_wm_max_horz = true;
- if( atoms[i] == wm_max_vert )
+ if (atoms[i] == wm_max_vert)
found_wm_max_vert = true;
- if( found_wm_max_horz && found_wm_max_vert )
+ if (found_wm_max_horz && found_wm_max_vert)
return true;
}
XFree(atoms);
@@ -987,44 +963,44 @@ InputModifierState OS_X11::get_key_modifier_state(unsigned int p_x11_state) {
InputModifierState state;
- state.shift = (p_x11_state&ShiftMask);
- state.control = (p_x11_state&ControlMask);
- state.alt = (p_x11_state&Mod1Mask /*|| p_x11_state&Mod5Mask*/); //altgr should not count as alt
- state.meta = (p_x11_state&Mod4Mask);
+ state.shift = (p_x11_state & ShiftMask);
+ state.control = (p_x11_state & ControlMask);
+ state.alt = (p_x11_state & Mod1Mask /*|| p_x11_state&Mod5Mask*/); //altgr should not count as alt
+ state.meta = (p_x11_state & Mod4Mask);
return state;
}
unsigned int OS_X11::get_mouse_button_state(unsigned int p_x11_state) {
- unsigned int state=0;
+ unsigned int state = 0;
- if (p_x11_state&Button1Mask) {
+ if (p_x11_state & Button1Mask) {
- state|=1<<0;
+ state |= 1 << 0;
}
- if (p_x11_state&Button3Mask) {
+ if (p_x11_state & Button3Mask) {
- state|=1<<1;
+ state |= 1 << 1;
}
- if (p_x11_state&Button2Mask) {
+ if (p_x11_state & Button2Mask) {
- state|=1<<2;
+ state |= 1 << 2;
}
- if (p_x11_state&Button4Mask) {
+ if (p_x11_state & Button4Mask) {
- state|=1<<3;
+ state |= 1 << 3;
}
- if (p_x11_state&Button5Mask) {
+ if (p_x11_state & Button5Mask) {
- state|=1<<4;
+ state |= 1 << 4;
}
- last_button_state=state;
+ last_button_state = state;
return state;
}
@@ -1052,20 +1028,19 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
// you want to keep.
// This is a real bizarreness and cpu waster.
- KeySym keysym_keycode=0; // keysym used to find a keycode
- KeySym keysym_unicode=0; // keysym used to find unicode
+ KeySym keysym_keycode = 0; // keysym used to find a keycode
+ KeySym keysym_unicode = 0; // keysym used to find unicode
// XLookupString returns keysyms usable as nice scancodes/
- char str[256+1];
+ char str[256 + 1];
XLookupString(xkeyevent, str, 256, &keysym_keycode, NULL);
- // Meanwhile, XLookupString returns keysyms useful for unicode.
-
+ // Meanwhile, XLookupString returns keysyms useful for unicode.
if (!xmbstring) {
// keep a temporary buffer for the string
- xmbstring=(char*)memalloc(sizeof(char)*8);
- xmblen=8;
+ xmbstring = (char *)memalloc(sizeof(char) * 8);
+ xmblen = 8;
}
if (xkeyevent->type == KeyPress && xic) {
@@ -1073,17 +1048,16 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
Status status;
do {
- int mnbytes = XmbLookupString (xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
+ int mnbytes = XmbLookupString(xic, xkeyevent, xmbstring, xmblen - 1, &keysym_unicode, &status);
xmbstring[mnbytes] = '\0';
if (status == XBufferOverflow) {
xmblen = mnbytes + 1;
- xmbstring = (char*)memrealloc (xmbstring, xmblen);
+ xmbstring = (char *)memrealloc(xmbstring, xmblen);
}
} while (status == XBufferOverflow);
}
-
/* Phase 2, obtain a pigui keycode from the keysym */
// KeyMappingX11 just translated the X11 keysym to a PIGUI
@@ -1097,8 +1071,7 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
// It does a binary search on a table to translate
// most properly.
//print_line("keysym_unicode: "+rtos(keysym_unicode));
- unsigned int unicode = keysym_unicode>0? KeyMappingX11::get_unicode_from_keysym(keysym_unicode):0;
-
+ unsigned int unicode = keysym_unicode > 0 ? KeyMappingX11::get_unicode_from_keysym(keysym_unicode) : 0;
/* Phase 4, determine if event must be filtered */
@@ -1112,11 +1085,11 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
bool keypress = xkeyevent->type == KeyPress;
if (xkeyevent->type == KeyPress && xic) {
- if (XFilterEvent((XEvent*)xkeyevent, x11_window))
- return;
+ if (XFilterEvent((XEvent *)xkeyevent, x11_window))
+ return;
}
- if (keycode==0 && unicode==0)
+ if (keycode == 0 && unicode == 0)
return;
/* Phase 5, determine modifier mask */
@@ -1136,12 +1109,11 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
// To detect them, i use XPeekEvent and check that their
// difference in time is below a treshold.
-
if (xkeyevent->type != KeyPress) {
// make sure there are events pending,
// so this call won't block.
- if (XPending(x11_display)>0) {
+ if (XPending(x11_display) > 0) {
XEvent peek_event;
XPeekEvent(x11_display, &peek_event);
@@ -1151,14 +1123,14 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
// is correct, but the xorg developers are
// not very helpful today.
- ::Time tresh=ABS(peek_event.xkey.time-xkeyevent->time);
- if (peek_event.type == KeyPress && tresh<5 ) {
+ ::Time tresh = ABS(peek_event.xkey.time - xkeyevent->time);
+ if (peek_event.type == KeyPress && tresh < 5) {
KeySym rk;
- XLookupString((XKeyEvent*)&peek_event, str, 256, &rk, NULL);
- if (rk==keysym_keycode) {
+ XLookupString((XKeyEvent *)&peek_event, str, 256, &rk, NULL);
+ if (rk == keysym_keycode) {
XEvent event;
XNextEvent(x11_display, &event); //erase next event
- handle_key_event( (XKeyEvent*)&event,true );
+ handle_key_event((XKeyEvent *)&event, true);
return; //ignore current, echo next
}
}
@@ -1169,27 +1141,26 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
// save the time to check for echo when keypress happens
}
-
/* Phase 7, send event to Window */
InputEvent event;
- event.ID=++event_id;
+ event.ID = ++event_id;
event.type = InputEvent::KEY;
- event.device=0;
- event.key.mod=state;
- event.key.pressed=keypress;
+ event.device = 0;
+ event.key.mod = state;
+ event.key.pressed = keypress;
- if (keycode>='a' && keycode<='z')
- keycode-='a'-'A';
+ if (keycode >= 'a' && keycode <= 'z')
+ keycode -= 'a' - 'A';
- event.key.scancode=keycode;
- event.key.unicode=unicode;
- event.key.echo=p_echo;
+ event.key.scancode = keycode;
+ event.key.unicode = unicode;
+ event.key.echo = p_echo;
- if (event.key.scancode==KEY_BACKTAB) {
+ if (event.key.scancode == KEY_BACKTAB) {
//make it consistent accross platforms.
- event.key.scancode=KEY_TAB;
- event.key.mod.shift=true;
+ event.key.scancode = KEY_TAB;
+ event.key.mod.shift = true;
}
//don't set mod state if modifier keys are released by themselves
@@ -1206,63 +1177,61 @@ void OS_X11::handle_key_event(XKeyEvent *p_event, bool p_echo) {
}
//printf("key: %x\n",event.key.scancode);
- input->parse_input_event( event);
+ input->parse_input_event(event);
}
-struct Property
-{
+struct Property {
unsigned char *data;
int format, nitems;
Atom type;
};
-static Property read_property(Display* p_display, Window p_window, Atom p_property) {
+static Property read_property(Display *p_display, Window p_window, Atom p_property) {
Atom actual_type;
int actual_format;
unsigned long nitems;
unsigned long bytes_after;
- unsigned char *ret=0;
+ unsigned char *ret = 0;
int read_bytes = 1024;
//Keep trying to read the property until there are no
//bytes unread.
- do
- {
- if(ret != 0)
+ do {
+ if (ret != 0)
XFree(ret);
XGetWindowProperty(p_display, p_window, p_property, 0, read_bytes, False, AnyPropertyType,
- &actual_type, &actual_format, &nitems, &bytes_after,
- &ret);
+ &actual_type, &actual_format, &nitems, &bytes_after,
+ &ret);
read_bytes *= 2;
- }while(bytes_after != 0);
+ } while (bytes_after != 0);
- Property p = {ret, actual_format, (int)nitems, actual_type};
+ Property p = { ret, actual_format, (int)nitems, actual_type };
return p;
}
-static Atom pick_target_from_list(Display* p_display, Atom *p_list, int p_count) {
+static Atom pick_target_from_list(Display *p_display, Atom *p_list, int p_count) {
- static const char* target_type = "text/uri-list";
+ static const char *target_type = "text/uri-list";
for (int i = 0; i < p_count; i++) {
Atom atom = p_list[i];
if (atom != None && String(XGetAtomName(p_display, atom)) == target_type)
- return atom;
+ return atom;
}
return None;
}
-static Atom pick_target_from_atoms(Display* p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
+static Atom pick_target_from_atoms(Display *p_disp, Atom p_t1, Atom p_t2, Atom p_t3) {
- static const char* target_type = "text/uri-list";
+ static const char *target_type = "text/uri-list";
if (p_t1 != None && String(XGetAtomName(p_disp, p_t1)) == target_type)
return p_t1;
@@ -1279,382 +1248,375 @@ void OS_X11::process_xevents() {
//printf("checking events %i\n", XPending(x11_display));
- do_mouse_warp=false;
-
+ do_mouse_warp = false;
// Is the current mouse mode one where it needs to be grabbed.
- bool mouse_mode_grab = mouse_mode==MOUSE_MODE_CAPTURED || mouse_mode==MOUSE_MODE_CONFINED;
+ bool mouse_mode_grab = mouse_mode == MOUSE_MODE_CAPTURED || mouse_mode == MOUSE_MODE_CONFINED;
while (XPending(x11_display) > 0) {
XEvent event;
XNextEvent(x11_display, &event);
switch (event.type) {
- case Expose:
- Main::force_redraw();
- break;
-
- case NoExpose:
- minimized = true;
- break;
-
- case VisibilityNotify: {
- XVisibilityEvent * visibility = (XVisibilityEvent *)&event;
- minimized = (visibility->state == VisibilityFullyObscured);
- } break;
- case LeaveNotify: {
- if (main_loop && !mouse_mode_grab)
- main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
- if (input)
- input->set_mouse_in_window(false);
+ case Expose:
+ Main::force_redraw();
+ break;
- } break;
- case EnterNotify: {
- if (main_loop && !mouse_mode_grab)
- main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
- if (input)
- input->set_mouse_in_window(true);
- } break;
- case FocusIn:
- minimized = false;
- window_has_focus = true;
- main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
- if (mouse_mode_grab) {
- // Show and update the cursor if confined and the window regained focus.
- if (mouse_mode==MOUSE_MODE_CONFINED)
- XUndefineCursor(x11_display, x11_window);
- else if (mouse_mode==MOUSE_MODE_CAPTURED) // or re-hide it in captured mode
- XDefineCursor(x11_display, x11_window, null_cursor);
-
- XGrabPointer(
- x11_display, x11_window, True,
- ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
- GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime);
- }
- break;
+ case NoExpose:
+ minimized = true;
+ break;
- case FocusOut:
- window_has_focus = false;
- main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
- if (mouse_mode_grab) {
- //dear X11, I try, I really try, but you never work, you do whathever you want.
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
- // Show the cursor if we're in captured mode so it doesn't look weird.
- XUndefineCursor(x11_display, x11_window);
+ case VisibilityNotify: {
+ XVisibilityEvent *visibility = (XVisibilityEvent *)&event;
+ minimized = (visibility->state == VisibilityFullyObscured);
+ } break;
+ case LeaveNotify: {
+ if (main_loop && !mouse_mode_grab)
+ main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
+ if (input)
+ input->set_mouse_in_window(false);
+
+ } break;
+ case EnterNotify: {
+ if (main_loop && !mouse_mode_grab)
+ main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
+ if (input)
+ input->set_mouse_in_window(true);
+ } break;
+ case FocusIn:
+ minimized = false;
+ window_has_focus = true;
+ main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
+ if (mouse_mode_grab) {
+ // Show and update the cursor if confined and the window regained focus.
+ if (mouse_mode == MOUSE_MODE_CONFINED)
+ XUndefineCursor(x11_display, x11_window);
+ else if (mouse_mode == MOUSE_MODE_CAPTURED) // or re-hide it in captured mode
+ XDefineCursor(x11_display, x11_window, null_cursor);
+
+ XGrabPointer(
+ x11_display, x11_window, True,
+ ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
+ GrabModeAsync, GrabModeAsync, x11_window, None, CurrentTime);
}
- XUngrabPointer(x11_display, CurrentTime);
- }
- break;
-
- case ConfigureNotify:
- /* call resizeGLScene only if our window-size changed */
-
- if ((event.xconfigure.width == current_videomode.width) &&
- (event.xconfigure.height == current_videomode.height))
break;
- current_videomode.width=event.xconfigure.width;
- current_videomode.height=event.xconfigure.height;
- break;
- case ButtonPress:
- case ButtonRelease: {
-
- /* exit in case of a mouse button press */
- last_timestamp=event.xbutton.time;
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- event.xbutton.x=last_mouse_pos.x;
- event.xbutton.y=last_mouse_pos.y;
- }
+ case FocusOut:
+ window_has_focus = false;
+ main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
+ if (mouse_mode_grab) {
+ //dear X11, I try, I really try, but you never work, you do whathever you want.
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
+ // Show the cursor if we're in captured mode so it doesn't look weird.
+ XUndefineCursor(x11_display, x11_window);
+ }
+ XUngrabPointer(x11_display, CurrentTime);
+ }
+ break;
- InputEvent mouse_event;
- mouse_event.ID=++event_id;
- mouse_event.type = InputEvent::MOUSE_BUTTON;
- mouse_event.device=0;
- mouse_event.mouse_button.mod = get_key_modifier_state(event.xbutton.state);
- mouse_event.mouse_button.button_mask = get_mouse_button_state(event.xbutton.state);
- mouse_event.mouse_button.x=event.xbutton.x;
- mouse_event.mouse_button.y=event.xbutton.y;
- mouse_event.mouse_button.global_x=event.xbutton.x;
- mouse_event.mouse_button.global_y=event.xbutton.y;
- mouse_event.mouse_button.button_index=event.xbutton.button;
- if (mouse_event.mouse_button.button_index==2)
- mouse_event.mouse_button.button_index=3;
- else if (mouse_event.mouse_button.button_index==3)
- mouse_event.mouse_button.button_index=2;
+ case ConfigureNotify:
+ /* call resizeGLScene only if our window-size changed */
- mouse_event.mouse_button.pressed=(event.type==ButtonPress);
+ if ((event.xconfigure.width == current_videomode.width) &&
+ (event.xconfigure.height == current_videomode.height))
+ break;
- if (event.type==ButtonPress && event.xbutton.button==1) {
+ current_videomode.width = event.xconfigure.width;
+ current_videomode.height = event.xconfigure.height;
+ break;
+ case ButtonPress:
+ case ButtonRelease: {
+
+ /* exit in case of a mouse button press */
+ last_timestamp = event.xbutton.time;
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
+ event.xbutton.x = last_mouse_pos.x;
+ event.xbutton.y = last_mouse_pos.y;
+ }
- uint64_t diff = get_ticks_usec()/1000 - last_click_ms;
+ InputEvent mouse_event;
+ mouse_event.ID = ++event_id;
+ mouse_event.type = InputEvent::MOUSE_BUTTON;
+ mouse_event.device = 0;
+ mouse_event.mouse_button.mod = get_key_modifier_state(event.xbutton.state);
+ mouse_event.mouse_button.button_mask = get_mouse_button_state(event.xbutton.state);
+ mouse_event.mouse_button.x = event.xbutton.x;
+ mouse_event.mouse_button.y = event.xbutton.y;
+ mouse_event.mouse_button.global_x = event.xbutton.x;
+ mouse_event.mouse_button.global_y = event.xbutton.y;
+ mouse_event.mouse_button.button_index = event.xbutton.button;
+ if (mouse_event.mouse_button.button_index == 2)
+ mouse_event.mouse_button.button_index = 3;
+ else if (mouse_event.mouse_button.button_index == 3)
+ mouse_event.mouse_button.button_index = 2;
- if (diff<400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x,event.xbutton.y))<5) {
+ mouse_event.mouse_button.pressed = (event.type == ButtonPress);
- last_click_ms=0;
- last_click_pos = Point2(-100,-100);
- mouse_event.mouse_button.doubleclick=true;
- mouse_event.ID=++event_id;
+ if (event.type == ButtonPress && event.xbutton.button == 1) {
- } else {
- last_click_ms+=diff;
- last_click_pos = Point2(event.xbutton.x,event.xbutton.y);
- }
- }
+ uint64_t diff = get_ticks_usec() / 1000 - last_click_ms;
- input->parse_input_event( mouse_event);
+ if (diff < 400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x, event.xbutton.y)) < 5) {
+ last_click_ms = 0;
+ last_click_pos = Point2(-100, -100);
+ mouse_event.mouse_button.doubleclick = true;
+ mouse_event.ID = ++event_id;
- } break;
- case MotionNotify: {
-
- // FUCK YOU X11 API YOU SERIOUSLY GROSS ME OUT
- // YOU ARE AS GROSS AS LOOKING AT A PUTRID PILE
- // OF POOP STICKING OUT OF A CLOGGED TOILET
- // HOW THE FUCK I AM SUPPOSED TO KNOW WHICH ONE
- // OF THE MOTION NOTIFY EVENTS IS THE ONE GENERATED
- // BY WARPING THE MOUSE POINTER?
- // YOU ARE FORCING ME TO FILTER ONE BY ONE TO FIND IT
- // PLEASE DO ME A FAVOR AND DIE DROWNED IN A FECAL
- // MOUNTAIN BECAUSE THAT'S WHERE YOU BELONG.
-
- while(true) {
- if (mouse_mode==MOUSE_MODE_CAPTURED && event.xmotion.x==current_videomode.width/2 && event.xmotion.y==current_videomode.height/2) {
- //this is likely the warp event since it was warped here
- center=Vector2(event.xmotion.x,event.xmotion.y);
- break;
+ } else {
+ last_click_ms += diff;
+ last_click_pos = Point2(event.xbutton.x, event.xbutton.y);
+ }
}
- if (XPending(x11_display) > 0) {
- XEvent tevent;
- XPeekEvent(x11_display, &tevent);
- if (tevent.type==MotionNotify) {
- XNextEvent(x11_display,&event);
+ input->parse_input_event(mouse_event);
+
+ } break;
+ case MotionNotify: {
+
+ // FUCK YOU X11 API YOU SERIOUSLY GROSS ME OUT
+ // YOU ARE AS GROSS AS LOOKING AT A PUTRID PILE
+ // OF POOP STICKING OUT OF A CLOGGED TOILET
+ // HOW THE FUCK I AM SUPPOSED TO KNOW WHICH ONE
+ // OF THE MOTION NOTIFY EVENTS IS THE ONE GENERATED
+ // BY WARPING THE MOUSE POINTER?
+ // YOU ARE FORCING ME TO FILTER ONE BY ONE TO FIND IT
+ // PLEASE DO ME A FAVOR AND DIE DROWNED IN A FECAL
+ // MOUNTAIN BECAUSE THAT'S WHERE YOU BELONG.
+
+ while (true) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED && event.xmotion.x == current_videomode.width / 2 && event.xmotion.y == current_videomode.height / 2) {
+ //this is likely the warp event since it was warped here
+ center = Vector2(event.xmotion.x, event.xmotion.y);
+ break;
+ }
+
+ if (XPending(x11_display) > 0) {
+ XEvent tevent;
+ XPeekEvent(x11_display, &tevent);
+ if (tevent.type == MotionNotify) {
+ XNextEvent(x11_display, &event);
+ } else {
+ break;
+ }
} else {
break;
}
- } else {
- break;
}
- }
- last_timestamp=event.xmotion.time;
+ last_timestamp = event.xmotion.time;
- // Motion is also simple.
- // A little hack is in order
- // to be able to send relative motion events.
- Point2i pos( event.xmotion.x, event.xmotion.y );
+ // Motion is also simple.
+ // A little hack is in order
+ // to be able to send relative motion events.
+ Point2i pos(event.xmotion.x, event.xmotion.y);
- if (mouse_mode==MOUSE_MODE_CAPTURED) {
+ if (mouse_mode == MOUSE_MODE_CAPTURED) {
#if 1
- //Vector2 c = Point2i(current_videomode.width/2,current_videomode.height/2);
- if (pos==Point2i(current_videomode.width/2,current_videomode.height/2)) {
- //this sucks, it's a hack, etc and is a little inaccurate, etc.
- //but nothing I can do, X11 sucks.
+ //Vector2 c = Point2i(current_videomode.width/2,current_videomode.height/2);
+ if (pos == Point2i(current_videomode.width / 2, current_videomode.height / 2)) {
+ //this sucks, it's a hack, etc and is a little inaccurate, etc.
+ //but nothing I can do, X11 sucks.
- center=pos;
- break;
- }
+ center = pos;
+ break;
+ }
- Point2i new_center = pos;
- pos = last_mouse_pos + ( pos - center );
- center=new_center;
- do_mouse_warp=window_has_focus; // warp the cursor if we're focused in
+ Point2i new_center = pos;
+ pos = last_mouse_pos + (pos - center);
+ center = new_center;
+ do_mouse_warp = window_has_focus; // warp the cursor if we're focused in
#else
- //Dear X11, thanks for making my life miserable
+ //Dear X11, thanks for making my life miserable
- center.x = current_videomode.width/2;
- center.y = current_videomode.height/2;
- pos = last_mouse_pos + ( pos-center );
- if (pos==last_mouse_pos)
- break;
- XWarpPointer(x11_display, None, x11_window,
- 0,0,0,0, (int)center.x, (int)center.y);
+ center.x = current_videomode.width / 2;
+ center.y = current_videomode.height / 2;
+ pos = last_mouse_pos + (pos - center);
+ if (pos == last_mouse_pos)
+ break;
+ XWarpPointer(x11_display, None, x11_window,
+ 0, 0, 0, 0, (int)center.x, (int)center.y);
#endif
- }
-
- if (!last_mouse_pos_valid) {
-
- last_mouse_pos=pos;
- last_mouse_pos_valid=true;
- }
-
- Point2i rel = pos - last_mouse_pos;
-
- InputEvent motion_event;
- motion_event.ID=++event_id;
- motion_event.type=InputEvent::MOUSE_MOTION;
- motion_event.device=0;
-
- motion_event.mouse_motion.mod = get_key_modifier_state(event.xmotion.state);
- motion_event.mouse_motion.button_mask = get_mouse_button_state(event.xmotion.state);
- motion_event.mouse_motion.x=pos.x;
- motion_event.mouse_motion.y=pos.y;
- input->set_mouse_pos(pos);
- motion_event.mouse_motion.global_x=pos.x;
- motion_event.mouse_motion.global_y=pos.y;
- motion_event.mouse_motion.speed_x=input->get_last_mouse_speed().x;
- motion_event.mouse_motion.speed_y=input->get_last_mouse_speed().y;
-
- motion_event.mouse_motion.relative_x=rel.x;
- motion_event.mouse_motion.relative_y=rel.y;
+ }
- last_mouse_pos=pos;
+ if (!last_mouse_pos_valid) {
- // printf("rel: %d,%d\n", rel.x, rel.y );
- // Don't propagate the motion event unless we have focus
- // this is so that the relative motion doesn't get messed up
- // after we regain focus.
- if (window_has_focus || !mouse_mode_grab)
- input->parse_input_event( motion_event);
+ last_mouse_pos = pos;
+ last_mouse_pos_valid = true;
+ }
- } break;
- case KeyPress:
- case KeyRelease: {
+ Point2i rel = pos - last_mouse_pos;
+
+ InputEvent motion_event;
+ motion_event.ID = ++event_id;
+ motion_event.type = InputEvent::MOUSE_MOTION;
+ motion_event.device = 0;
+
+ motion_event.mouse_motion.mod = get_key_modifier_state(event.xmotion.state);
+ motion_event.mouse_motion.button_mask = get_mouse_button_state(event.xmotion.state);
+ motion_event.mouse_motion.x = pos.x;
+ motion_event.mouse_motion.y = pos.y;
+ input->set_mouse_pos(pos);
+ motion_event.mouse_motion.global_x = pos.x;
+ motion_event.mouse_motion.global_y = pos.y;
+ motion_event.mouse_motion.speed_x = input->get_last_mouse_speed().x;
+ motion_event.mouse_motion.speed_y = input->get_last_mouse_speed().y;
+
+ motion_event.mouse_motion.relative_x = rel.x;
+ motion_event.mouse_motion.relative_y = rel.y;
+
+ last_mouse_pos = pos;
+
+ // printf("rel: %d,%d\n", rel.x, rel.y );
+ // Don't propagate the motion event unless we have focus
+ // this is so that the relative motion doesn't get messed up
+ // after we regain focus.
+ if (window_has_focus || !mouse_mode_grab)
+ input->parse_input_event(motion_event);
+
+ } break;
+ case KeyPress:
+ case KeyRelease: {
+
+ last_timestamp = event.xkey.time;
+
+ // key event is a little complex, so
+ // it will be handled in it's own function.
+ handle_key_event((XKeyEvent *)&event);
+ } break;
+ case SelectionRequest: {
+
+ XSelectionRequestEvent *req;
+ XEvent e, respond;
+ e = event;
+
+ req = &(e.xselectionrequest);
+ if (req->target == XA_STRING || req->target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
+ req->target == XInternAtom(x11_display, "UTF8_STRING", 0)) {
+ CharString clip = OS::get_clipboard().utf8();
+ XChangeProperty(x11_display,
+ req->requestor,
+ req->property,
+ req->target,
+ 8,
+ PropModeReplace,
+ (unsigned char *)clip.get_data(),
+ clip.length());
+ respond.xselection.property = req->property;
+ } else if (req->target == XInternAtom(x11_display, "TARGETS", 0)) {
+
+ Atom data[2];
+ data[0] = XInternAtom(x11_display, "UTF8_STRING", 0);
+ data[1] = XA_STRING;
+ XChangeProperty(x11_display, req->requestor, req->property, req->target,
+ 8, PropModeReplace, (unsigned char *)&data,
+ sizeof(data));
+ respond.xselection.property = req->property;
- last_timestamp=event.xkey.time;
+ } else {
+ printf("No String %x\n",
+ (int)req->target);
+ respond.xselection.property = None;
+ }
+ respond.xselection.type = SelectionNotify;
+ respond.xselection.display = req->display;
+ respond.xselection.requestor = req->requestor;
+ respond.xselection.selection = req->selection;
+ respond.xselection.target = req->target;
+ respond.xselection.time = req->time;
+ XSendEvent(x11_display, req->requestor, 0, 0, &respond);
+ XFlush(x11_display);
+ } break;
- // key event is a little complex, so
- // it will be handled in it's own function.
- handle_key_event( (XKeyEvent*)&event );
- } break;
- case SelectionRequest: {
-
- XSelectionRequestEvent *req;
- XEvent e, respond;
- e = event;
-
- req=&(e.xselectionrequest);
- if (req->target == XA_STRING || req->target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
- req->target == XInternAtom(x11_display, "UTF8_STRING", 0))
- {
- CharString clip = OS::get_clipboard().utf8();
- XChangeProperty (x11_display,
- req->requestor,
- req->property,
- req->target,
- 8,
- PropModeReplace,
- (unsigned char*)clip.get_data(),
- clip.length());
- respond.xselection.property=req->property;
- } else if (req->target == XInternAtom(x11_display, "TARGETS", 0)) {
-
- Atom data[2];
- data[0] = XInternAtom(x11_display, "UTF8_STRING", 0);
- data[1] = XA_STRING;
- XChangeProperty (x11_display, req->requestor, req->property, req->target,
- 8, PropModeReplace, (unsigned char *) &data,
- sizeof (data));
- respond.xselection.property=req->property;
+ case SelectionNotify:
- } else {
- printf ("No String %x\n",
- (int)req->target);
- respond.xselection.property= None;
- }
- respond.xselection.type= SelectionNotify;
- respond.xselection.display= req->display;
- respond.xselection.requestor= req->requestor;
- respond.xselection.selection=req->selection;
- respond.xselection.target= req->target;
- respond.xselection.time = req->time;
- XSendEvent (x11_display, req->requestor,0,0,&respond);
- XFlush (x11_display);
- } break;
+ if (event.xselection.target == requested) {
- case SelectionNotify:
+ Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0));
- if (event.xselection.target == requested) {
+ Vector<String> files = String((char *)p.data).split("\n", false);
+ for (int i = 0; i < files.size(); i++) {
+ files[i] = files[i].replace("file://", "").replace("%20", " ").strip_escapes();
+ }
+ main_loop->drop_files(files);
- Property p = read_property(x11_display, x11_window, XInternAtom(x11_display, "PRIMARY", 0));
+ //Reply that all is well.
+ XClientMessageEvent m;
+ memset(&m, 0, sizeof(m));
+ m.type = ClientMessage;
+ m.display = x11_display;
+ m.window = xdnd_source_window;
+ m.message_type = xdnd_finished;
+ m.format = 32;
+ m.data.l[0] = x11_window;
+ m.data.l[1] = 1;
+ m.data.l[2] = xdnd_action_copy; //We only ever copy.
- Vector<String> files = String((char *)p.data).split("\n", false);
- for (int i = 0; i < files.size(); i++) {
- files[i] = files[i].replace("file://", "").replace("%20", " ").strip_escapes();
+ XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent *)&m);
}
- main_loop->drop_files(files);
-
- //Reply that all is well.
- XClientMessageEvent m;
- memset(&m, 0, sizeof(m));
- m.type = ClientMessage;
- m.display = x11_display;
- m.window = xdnd_source_window;
- m.message_type = xdnd_finished;
- m.format=32;
- m.data.l[0] = x11_window;
- m.data.l[1] = 1;
- m.data.l[2] = xdnd_action_copy; //We only ever copy.
-
- XSendEvent(x11_display, xdnd_source_window, False, NoEventMask, (XEvent*)&m);
- }
- break;
+ break;
- case ClientMessage:
+ case ClientMessage:
- if ((unsigned int)event.xclient.data.l[0]==(unsigned int)wm_delete)
- main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
+ if ((unsigned int)event.xclient.data.l[0] == (unsigned int)wm_delete)
+ main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
- else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
+ else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_enter) {
- //File(s) have been dragged over the window, check for supported target (text/uri-list)
- xdnd_version = ( event.xclient.data.l[1] >> 24);
- Window source = event.xclient.data.l[0];
- bool more_than_3 = event.xclient.data.l[1] & 1;
- if (more_than_3) {
- Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
- requested = pick_target_from_list(x11_display, (Atom*)p.data, p.nitems);
- }
- else
- requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2],event.xclient.data.l[3], event.xclient.data.l[4]);
- }
- else if ((unsigned int)event.xclient.message_type == (unsigned int )xdnd_position) {
-
- //xdnd position event, reply with an XDND status message
- //just depending on type of data for now
- XClientMessageEvent m;
- memset(&m, 0, sizeof(m));
- m.type = ClientMessage;
- m.display = event.xclient.display;
- m.window = event.xclient.data.l[0];
- m.message_type = xdnd_status;
- m.format=32;
- m.data.l[0] = x11_window;
- m.data.l[1] = (requested != None);
- m.data.l[2] = 0; //empty rectangle
- m.data.l[3] = 0;
- m.data.l[4] = xdnd_action_copy;
-
- XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
- XFlush(x11_display);
- }
- else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
-
- if (requested != None) {
- xdnd_source_window = event.xclient.data.l[0];
- if(xdnd_version >= 1)
- XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]);
- else
- XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime);
- }
- else {
- //Reply that we're not interested.
+ //File(s) have been dragged over the window, check for supported target (text/uri-list)
+ xdnd_version = (event.xclient.data.l[1] >> 24);
+ Window source = event.xclient.data.l[0];
+ bool more_than_3 = event.xclient.data.l[1] & 1;
+ if (more_than_3) {
+ Property p = read_property(x11_display, source, XInternAtom(x11_display, "XdndTypeList", False));
+ requested = pick_target_from_list(x11_display, (Atom *)p.data, p.nitems);
+ } else
+ requested = pick_target_from_atoms(x11_display, event.xclient.data.l[2], event.xclient.data.l[3], event.xclient.data.l[4]);
+ } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_position) {
+
+ //xdnd position event, reply with an XDND status message
+ //just depending on type of data for now
XClientMessageEvent m;
memset(&m, 0, sizeof(m));
m.type = ClientMessage;
m.display = event.xclient.display;
m.window = event.xclient.data.l[0];
- m.message_type = xdnd_finished;
- m.format=32;
+ m.message_type = xdnd_status;
+ m.format = 32;
m.data.l[0] = x11_window;
- m.data.l[1] = 0;
- m.data.l[2] = None; //Failed.
- XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent*)&m);
+ m.data.l[1] = (requested != None);
+ m.data.l[2] = 0; //empty rectangle
+ m.data.l[3] = 0;
+ m.data.l[4] = xdnd_action_copy;
+
+ XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
+ XFlush(x11_display);
+ } else if ((unsigned int)event.xclient.message_type == (unsigned int)xdnd_drop) {
+
+ if (requested != None) {
+ xdnd_source_window = event.xclient.data.l[0];
+ if (xdnd_version >= 1)
+ XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, event.xclient.data.l[2]);
+ else
+ XConvertSelection(x11_display, xdnd_selection, requested, XInternAtom(x11_display, "PRIMARY", 0), x11_window, CurrentTime);
+ } else {
+ //Reply that we're not interested.
+ XClientMessageEvent m;
+ memset(&m, 0, sizeof(m));
+ m.type = ClientMessage;
+ m.display = event.xclient.display;
+ m.window = event.xclient.data.l[0];
+ m.message_type = xdnd_finished;
+ m.format = 32;
+ m.data.l[0] = x11_window;
+ m.data.l[1] = 0;
+ m.data.l[2] = None; //Failed.
+ XSendEvent(x11_display, event.xclient.data.l[0], False, NoEventMask, (XEvent *)&m);
+ }
}
- }
- break;
- default:
- break;
+ break;
+ default:
+ break;
}
}
@@ -1663,7 +1625,7 @@ void OS_X11::process_xevents() {
if (do_mouse_warp) {
XWarpPointer(x11_display, None, x11_window,
- 0,0,0,0, (int)current_videomode.width/2, (int)current_videomode.height/2);
+ 0, 0, 0, 0, (int)current_videomode.width / 2, (int)current_videomode.height / 2);
/*
Window root, child;
@@ -1687,12 +1649,12 @@ void OS_X11::delete_main_loop() {
if (main_loop)
memdelete(main_loop);
- main_loop=NULL;
+ main_loop = NULL;
}
-void OS_X11::set_main_loop( MainLoop * p_main_loop ) {
+void OS_X11::set_main_loop(MainLoop *p_main_loop) {
- main_loop=p_main_loop;
+ main_loop = p_main_loop;
input->set_main_loop(p_main_loop);
}
@@ -1701,7 +1663,7 @@ bool OS_X11::can_draw() const {
return !minimized;
};
-void OS_X11::set_clipboard(const String& p_text) {
+void OS_X11::set_clipboard(const String &p_text) {
OS::set_clipboard(p_text);
@@ -1709,7 +1671,7 @@ void OS_X11::set_clipboard(const String& p_text) {
XSetSelectionOwner(x11_display, XInternAtom(x11_display, "CLIPBOARD", 0), x11_window, CurrentTime);
};
-static String _get_clipboard(Atom p_source, Window x11_window, ::Display* x11_display, String p_internal_clipboard) {
+static String _get_clipboard(Atom p_source, Window x11_window, ::Display *x11_display, String p_internal_clipboard) {
String ret;
@@ -1718,7 +1680,7 @@ static String _get_clipboard(Atom p_source, Window x11_window, ::Display* x11_di
int format, result;
unsigned long len, bytes_left, dummy;
unsigned char *data;
- Window Sown = XGetSelectionOwner (x11_display, p_source);
+ Window Sown = XGetSelectionOwner(x11_display, p_source);
if (Sown == x11_window) {
@@ -1726,9 +1688,9 @@ static String _get_clipboard(Atom p_source, Window x11_window, ::Display* x11_di
};
if (Sown != None) {
- XConvertSelection (x11_display, p_source, XA_STRING, selection,
- x11_window, CurrentTime);
- XFlush (x11_display);
+ XConvertSelection(x11_display, p_source, XA_STRING, selection,
+ x11_window, CurrentTime);
+ XFlush(x11_display);
while (true) {
XEvent event;
XNextEvent(x11_display, &event);
@@ -1740,31 +1702,30 @@ static String _get_clipboard(Atom p_source, Window x11_window, ::Display* x11_di
//
// Do not get any data, see how much data is there
//
- XGetWindowProperty (x11_display, x11_window,
- selection, // Tricky..
- 0, 0, // offset - len
- 0, // Delete 0==FALSE
- AnyPropertyType, //flag
- &type, // return type
- &format, // return format
- &len, &bytes_left, //that
- &data);
+ XGetWindowProperty(x11_display, x11_window,
+ selection, // Tricky..
+ 0, 0, // offset - len
+ 0, // Delete 0==FALSE
+ AnyPropertyType, //flag
+ &type, // return type
+ &format, // return format
+ &len, &bytes_left, //that
+ &data);
// DATA is There
- if (bytes_left > 0)
- {
- result = XGetWindowProperty (x11_display, x11_window,
- selection, 0,bytes_left,0,
- AnyPropertyType, &type,&format,
- &len, &dummy, &data);
+ if (bytes_left > 0) {
+ result = XGetWindowProperty(x11_display, x11_window,
+ selection, 0, bytes_left, 0,
+ AnyPropertyType, &type, &format,
+ &len, &dummy, &data);
if (result == Success) {
- ret.parse_utf8((const char*)data);
- } else printf ("FAIL\n");
- XFree (data);
+ ret.parse_utf8((const char *)data);
+ } else
+ printf("FAIL\n");
+ XFree(data);
}
}
return ret;
-
}
String OS_X11::get_clipboard() const {
@@ -1789,59 +1750,58 @@ Error OS_X11::shell_open(String p_uri) {
Error ok;
List<String> args;
args.push_back(p_uri);
- ok = execute("/usr/bin/xdg-open",args,false);
- if (ok==OK)
+ ok = execute("/usr/bin/xdg-open", args, false);
+ if (ok == OK)
return OK;
- ok = execute("gnome-open",args,false);
- if (ok==OK)
+ ok = execute("gnome-open", args, false);
+ if (ok == OK)
return OK;
- ok = execute("kde-open",args,false);
+ ok = execute("kde-open", args, false);
return ok;
}
String OS_X11::get_system_dir(SystemDir p_dir) const {
-
String xdgparam;
- switch(p_dir) {
+ switch (p_dir) {
case SYSTEM_DIR_DESKTOP: {
- xdgparam="DESKTOP";
+ xdgparam = "DESKTOP";
} break;
case SYSTEM_DIR_DCIM: {
- xdgparam="PICTURES";
+ xdgparam = "PICTURES";
} break;
case SYSTEM_DIR_DOCUMENTS: {
- xdgparam="DOCUMENTS";
+ xdgparam = "DOCUMENTS";
} break;
case SYSTEM_DIR_DOWNLOADS: {
- xdgparam="DOWNLOAD";
+ xdgparam = "DOWNLOAD";
} break;
case SYSTEM_DIR_MOVIES: {
- xdgparam="VIDEOS";
+ xdgparam = "VIDEOS";
} break;
case SYSTEM_DIR_MUSIC: {
- xdgparam="MUSIC";
+ xdgparam = "MUSIC";
} break;
case SYSTEM_DIR_PICTURES: {
- xdgparam="PICTURES";
+ xdgparam = "PICTURES";
} break;
case SYSTEM_DIR_RINGTONES: {
- xdgparam="MUSIC";
+ xdgparam = "MUSIC";
} break;
}
@@ -1849,38 +1809,36 @@ String OS_X11::get_system_dir(SystemDir p_dir) const {
String pipe;
List<String> arg;
arg.push_back(xdgparam);
- Error err = const_cast<OS_X11*>(this)->execute("/usr/bin/xdg-user-dir",arg,true,NULL,&pipe);
- if (err!=OK)
+ Error err = const_cast<OS_X11 *>(this)->execute("/usr/bin/xdg-user-dir", arg, true, NULL, &pipe);
+ if (err != OK)
return ".";
return pipe.strip_edges();
}
void OS_X11::move_window_to_foreground() {
- XRaiseWindow(x11_display,x11_window);
+ XRaiseWindow(x11_display, x11_window);
}
void OS_X11::set_cursor_shape(CursorShape p_shape) {
- ERR_FAIL_INDEX(p_shape,CURSOR_MAX);
+ ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
- if (p_shape==current_cursor)
+ if (p_shape == current_cursor)
return;
- if (mouse_mode==MOUSE_MODE_VISIBLE) {
- if (cursors[p_shape]!=None)
- XDefineCursor(x11_display,x11_window,cursors[p_shape]);
- else if (cursors[CURSOR_ARROW]!=None)
- XDefineCursor(x11_display,x11_window,cursors[CURSOR_ARROW]);
+ if (mouse_mode == MOUSE_MODE_VISIBLE) {
+ if (cursors[p_shape] != None)
+ XDefineCursor(x11_display, x11_window, cursors[p_shape]);
+ else if (cursors[CURSOR_ARROW] != None)
+ XDefineCursor(x11_display, x11_window, cursors[CURSOR_ARROW]);
}
- current_cursor=p_shape;
+ current_cursor = p_shape;
}
-
void OS_X11::release_rendering_thread() {
context_gl->release_current();
-
}
void OS_X11::make_rendering_thread() {
@@ -1893,7 +1851,7 @@ void OS_X11::swap_buffers() {
context_gl->swap_buffers();
}
-void OS_X11::alert(const String& p_alert,const String& p_title) {
+void OS_X11::alert(const String &p_alert, const String &p_title) {
List<String> args;
args.push_back("-center");
@@ -1901,14 +1859,14 @@ void OS_X11::alert(const String& p_alert,const String& p_title) {
args.push_back(p_title);
args.push_back(p_alert);
- execute("/usr/bin/xmessage",args,true);
+ execute("/usr/bin/xmessage", args, true);
}
-void OS_X11::set_icon(const Image& p_icon) {
+void OS_X11::set_icon(const Image &p_icon) {
Atom net_wm_icon = XInternAtom(x11_display, "_NET_WM_ICON", False);
if (!p_icon.empty()) {
- Image img=p_icon;
+ Image img = p_icon;
img.convert(Image::FORMAT_RGBA8);
int w = img.get_width();
@@ -1917,31 +1875,30 @@ void OS_X11::set_icon(const Image& p_icon) {
// We're using long to have wordsize (32Bit build -> 32 Bits, 64 Bit build -> 64 Bits
Vector<long> pd;
- pd.resize(2+w*h);
+ pd.resize(2 + w * h);
- pd[0]=w;
- pd[1]=h;
+ pd[0] = w;
+ pd[1] = h;
PoolVector<uint8_t>::Read r = img.get_data().read();
- long * wr = &pd[2];
- uint8_t const * pr = r.ptr();
+ long *wr = &pd[2];
+ uint8_t const *pr = r.ptr();
- for(int i=0;i<w*h;i++) {
- long v=0;
+ for (int i = 0; i < w * h; i++) {
+ long v = 0;
// A R G B
- v|=pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
- *wr++=v;
+ v |= pr[3] << 24 | pr[0] << 16 | pr[1] << 8 | pr[2];
+ *wr++ = v;
pr += 4;
}
- XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char*) pd.ptr(), pd.size());
+ XChangeProperty(x11_display, x11_window, net_wm_icon, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)pd.ptr(), pd.size());
} else {
- XDeleteProperty(x11_display, x11_window, net_wm_icon);
+ XDeleteProperty(x11_display, x11_window, net_wm_icon);
}
XFlush(x11_display);
}
-
void OS_X11::run() {
force_quit = false;
@@ -1962,7 +1919,7 @@ void OS_X11::run() {
#ifdef JOYDEV_ENABLED
event_id = joypad->process_joypads(event_id);
#endif
- if (Main::iteration()==true)
+ if (Main::iteration() == true)
break;
};
@@ -1990,10 +1947,9 @@ bool OS_X11::is_vsync_enabled() const {
return true;
}
-
void OS_X11::set_context(int p_context) {
- XClassHint* classHint = NULL;
+ XClassHint *classHint = NULL;
classHint = XAllocClassHint();
if (classHint) {
@@ -2033,12 +1989,12 @@ OS_X11::OS_X11() {
AudioDriverManager::add_driver(&driver_alsa);
#endif
- if(AudioDriverManager::get_driver_count() == 0){
+ if (AudioDriverManager::get_driver_count() == 0) {
WARN_PRINT("No sound driver found... Defaulting to dummy driver");
AudioDriverManager::add_driver(&driver_dummy);
}
minimized = false;
- xim_style=0L;
- mouse_mode=MOUSE_MODE_VISIBLE;
+ xim_style = 0L;
+ mouse_mode = MOUSE_MODE_VISIBLE;
}
diff --git a/platform/x11/os_x11.h b/platform/x11/os_x11.h
index ce2e2df6e9..cbda18c0bc 100644
--- a/platform/x11/os_x11.h
+++ b/platform/x11/os_x11.h
@@ -29,29 +29,28 @@
#ifndef OS_X11_H
#define OS_X11_H
-
-#include "os/input.h"
-#include "drivers/unix/os_unix.h"
#include "context_gl_x11.h"
+#include "drivers/unix/os_unix.h"
+#include "os/input.h"
#include "servers/visual_server.h"
//#include "servers/visual/visual_server_wrap_mt.h"
-#include "servers/visual/rasterizer.h"
-#include "servers/physics_server.h"
-#include "servers/audio_server.h"
-#include "drivers/rtaudio/audio_driver_rtaudio.h"
#include "drivers/alsa/audio_driver_alsa.h"
#include "drivers/pulseaudio/audio_driver_pulseaudio.h"
+#include "drivers/rtaudio/audio_driver_rtaudio.h"
+#include "joypad_linux.h"
+#include "main/input_default.h"
+#include "power_x11.h"
#include "servers/audio/audio_driver_dummy.h"
+#include "servers/audio_server.h"
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "servers/physics_2d/physics_2d_server_wrap_mt.h"
-#include "main/input_default.h"
-#include "joypad_linux.h"
-#include "power_x11.h"
+#include "servers/physics_server.h"
+#include "servers/visual/rasterizer.h"
-#include <X11/keysym.h>
-#include <X11/Xlib.h>
#include <X11/Xcursor/Xcursor.h>
+#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
+#include <X11/keysym.h>
// Hints for X11 fullscreen
typedef struct {
@@ -63,17 +62,17 @@ typedef struct {
} Hints;
typedef struct _xrr_monitor_info {
- Atom name;
- Bool primary;
- Bool automatic;
- int noutput;
- int x;
- int y;
- int width;
- int height;
- int mwidth;
- int mheight;
- RROutput *outputs;
+ Atom name;
+ Bool primary;
+ Bool automatic;
+ int noutput;
+ int x;
+ int y;
+ int width;
+ int height;
+ int mwidth;
+ int mheight;
+ RROutput *outputs;
} xrr_monitor_info;
#undef CursorShape
@@ -93,7 +92,7 @@ class OS_X11 : public OS_Unix {
Atom xdnd_selection;
Atom requested;
- int xdnd_version;
+ int xdnd_version;
#if defined(OPENGL_ENABLED) || defined(LEGACYGL_ENABLED)
ContextGL_X11 *context_gl;
@@ -105,7 +104,7 @@ class OS_X11 : public OS_Unix {
Window x11_window;
Window xdnd_source_window;
MainLoop *main_loop;
- ::Display* x11_display;
+ ::Display *x11_display;
char *xmbstring;
int xmblen;
unsigned long last_timestamp;
@@ -128,7 +127,7 @@ class OS_X11 : public OS_Unix {
MouseMode mouse_mode;
Point2i center;
- void handle_key_event(XKeyEvent *p_event,bool p_echo=false);
+ void handle_key_event(XKeyEvent *p_event, bool p_echo = false);
void process_xevents();
virtual void delete_main_loop();
IP_Unix *ip_unix;
@@ -165,7 +164,7 @@ class OS_X11 : public OS_Unix {
AudioDriverDummy driver_dummy;
Atom net_wm_icon;
-
+
PowerX11 *power_manager;
int audio_driver_index;
@@ -174,30 +173,27 @@ class OS_X11 : public OS_Unix {
//void set_wm_border(bool p_enabled);
void set_wm_fullscreen(bool p_enabled);
- typedef xrr_monitor_info* (*xrr_get_monitors_t)(Display *dpy, Window window, Bool get_active, int *nmonitors);
- typedef void (*xrr_free_monitors_t)(xrr_monitor_info* monitors);
+ typedef xrr_monitor_info *(*xrr_get_monitors_t)(Display *dpy, Window window, Bool get_active, int *nmonitors);
+ typedef void (*xrr_free_monitors_t)(xrr_monitor_info *monitors);
xrr_get_monitors_t xrr_get_monitors;
xrr_free_monitors_t xrr_free_monitors;
void *xrandr_handle;
Bool xrandr_ext_ok;
protected:
-
virtual int get_video_driver_count() const;
- virtual const char * get_video_driver_name(int p_driver) const;
+ virtual const char *get_video_driver_name(int p_driver) const;
virtual VideoMode get_default_video_mode() const;
virtual int get_audio_driver_count() const;
- virtual const char * get_audio_driver_name(int p_driver) const;
+ virtual const char *get_audio_driver_name(int p_driver) const;
- virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+ virtual void initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver);
virtual void finalize();
- virtual void set_main_loop( MainLoop * p_main_loop );
-
+ virtual void set_main_loop(MainLoop *p_main_loop);
public:
-
virtual String get_name();
virtual void set_cursor_shape(CursorShape p_shape);
@@ -205,18 +201,18 @@ public:
void set_mouse_mode(MouseMode p_mode);
MouseMode get_mouse_mode() const;
- virtual void warp_mouse_pos(const Point2& p_to);
+ virtual void warp_mouse_pos(const Point2 &p_to);
virtual Point2 get_mouse_pos() const;
virtual int get_mouse_button_state() const;
- virtual void set_window_title(const String& p_title);
+ virtual void set_window_title(const String &p_title);
- virtual void set_icon(const Image& p_icon);
+ virtual void set_icon(const Image &p_icon);
virtual MainLoop *get_main_loop() const;
virtual bool can_draw() const;
- virtual void set_clipboard(const String& p_text);
+ virtual void set_clipboard(const String &p_text);
virtual String get_clipboard() const;
virtual void release_rendering_thread();
@@ -227,19 +223,18 @@ public:
virtual Error shell_open(String p_uri);
- virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
- virtual VideoMode get_video_mode(int p_screen=0) const;
- virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
-
+ virtual void set_video_mode(const VideoMode &p_video_mode, int p_screen = 0);
+ virtual VideoMode get_video_mode(int p_screen = 0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen = 0) const;
virtual int get_screen_count() const;
virtual int get_current_screen() const;
virtual void set_current_screen(int p_screen);
- virtual Point2 get_screen_position(int p_screen=0) const;
- virtual Size2 get_screen_size(int p_screen=0) const;
- virtual int get_screen_dpi(int p_screen=0) const;
+ virtual Point2 get_screen_position(int p_screen = 0) const;
+ virtual Size2 get_screen_size(int p_screen = 0) const;
+ virtual int get_screen_dpi(int p_screen = 0) const;
virtual Point2 get_window_position() const;
- virtual void set_window_position(const Point2& p_position);
+ virtual void set_window_position(const Point2 &p_position);
virtual Size2 get_window_size() const;
virtual void set_window_size(const Size2 p_size);
virtual void set_window_fullscreen(bool p_enabled);
@@ -253,7 +248,7 @@ public:
virtual void request_attention();
virtual void move_window_to_foreground();
- virtual void alert(const String& p_alert,const String& p_title="ALERT!");
+ virtual void alert(const String &p_alert, const String &p_title = "ALERT!");
virtual bool is_joy_known(int p_device);
virtual String get_joy_guid(int p_device) const;
diff --git a/platform/x11/power_x11.cpp b/platform/x11/power_x11.cpp
index 472a32bb48..2f98d2f335 100644
--- a/platform/x11/power_x11.cpp
+++ b/platform/x11/power_x11.cpp
@@ -32,34 +32,31 @@
#include <stdio.h>
#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
// CODE CHUNK IMPORTED FROM SDL 2.0
-static const char* proc_apm_path = "/proc/apm";
-static const char* proc_acpi_battery_path = "/proc/acpi/battery";
-static const char* proc_acpi_ac_adapter_path = "/proc/acpi/ac_adapter";
-static const char* sys_class_power_supply_path = "/sys/class/power_supply";
+static const char *proc_apm_path = "/proc/apm";
+static const char *proc_acpi_battery_path = "/proc/acpi/battery";
+static const char *proc_acpi_ac_adapter_path = "/proc/acpi/ac_adapter";
+static const char *sys_class_power_supply_path = "/sys/class/power_supply";
-FileAccessRef PowerX11::open_power_file(const char* base, const char* node, const char* key)
-{
+FileAccessRef PowerX11::open_power_file(const char *base, const char *node, const char *key) {
String path = String(base) + String("/") + String(node) + String("/") + String(key);
- FileAccessRef f = FileAccess::open(path,FileAccess::READ);
+ FileAccessRef f = FileAccess::open(path, FileAccess::READ);
return f;
}
-
-bool PowerX11::read_power_file(const char* base, const char* node, const char* key, char* buf, size_t buflen)
-{
+bool PowerX11::read_power_file(const char *base, const char *node, const char *key, char *buf, size_t buflen) {
ssize_t br = 0;
FileAccessRef fd = open_power_file(base, node, key);
if (!fd) {
return false;
}
- br = fd->get_buffer(reinterpret_cast<uint8_t*>(buf), buflen-1);
+ br = fd->get_buffer(reinterpret_cast<uint8_t *>(buf), buflen - 1);
fd->close();
if (br < 0) {
return false;
@@ -68,17 +65,15 @@ bool PowerX11::read_power_file(const char* base, const char* node, const char* k
return true;
}
-
-bool PowerX11::make_proc_acpi_key_val(char **_ptr, char **_key, char **_val)
-{
+bool PowerX11::make_proc_acpi_key_val(char **_ptr, char **_key, char **_val) {
char *ptr = *_ptr;
while (*ptr == ' ') {
- ptr++; /* skip whitespace. */
+ ptr++; /* skip whitespace. */
}
if (*ptr == '\0') {
- return false; /* EOF. */
+ return false; /* EOF. */
}
*_key = ptr;
@@ -88,17 +83,17 @@ bool PowerX11::make_proc_acpi_key_val(char **_ptr, char **_key, char **_val)
}
if (*ptr == '\0') {
- return false; /* (unexpected) EOF. */
+ return false; /* (unexpected) EOF. */
}
- *(ptr++) = '\0'; /* terminate the key. */
+ *(ptr++) = '\0'; /* terminate the key. */
while ((*ptr == ' ') && (*ptr != '\0')) {
- ptr++; /* skip whitespace. */
+ ptr++; /* skip whitespace. */
}
if (*ptr == '\0') {
- return false; /* (unexpected) EOF. */
+ return false; /* (unexpected) EOF. */
}
*_val = ptr;
@@ -108,16 +103,14 @@ bool PowerX11::make_proc_acpi_key_val(char **_ptr, char **_key, char **_val)
}
if (*ptr != '\0') {
- *(ptr++) = '\0'; /* terminate the value. */
+ *(ptr++) = '\0'; /* terminate the value. */
}
- *_ptr = ptr; /* store for next time. */
+ *_ptr = ptr; /* store for next time. */
return true;
}
-void
-PowerX11::check_proc_acpi_battery(const char * node, bool * have_battery, bool * charging)
-{
+void PowerX11::check_proc_acpi_battery(const char *node, bool *have_battery, bool *charging) {
const char *base = proc_acpi_battery_path;
char info[1024];
char state[1024];
@@ -131,10 +124,10 @@ PowerX11::check_proc_acpi_battery(const char * node, bool * have_battery, bool *
int secs = -1;
int pct = -1;
- if (!read_power_file(base, node, "state", state, sizeof (state))) {
+ if (!read_power_file(base, node, "state", state, sizeof(state))) {
return;
} else {
- if (!read_power_file(base, node, "info", info, sizeof (info)))
+ if (!read_power_file(base, node, "info", info, sizeof(info)))
return;
}
@@ -175,7 +168,7 @@ PowerX11::check_proc_acpi_battery(const char * node, bool * have_battery, bool *
}
if ((maximum >= 0) && (remaining >= 0)) {
- pct = (int) ((((float) remaining) / ((float) maximum)) * 100.0f);
+ pct = (int)((((float)remaining) / ((float)maximum)) * 100.0f);
if (pct < 0) {
pct = 0;
} else if (pct > 100) {
@@ -191,7 +184,7 @@ PowerX11::check_proc_acpi_battery(const char * node, bool * have_battery, bool *
*/
if ((secs < 0) && (this->nsecs_left < 0)) {
if ((pct < 0) && (this->percent_left < 0)) {
- choose = true; /* at least we know there's a battery. */
+ choose = true; /* at least we know there's a battery. */
}
if (pct > this->percent_left) {
choose = true;
@@ -207,15 +200,14 @@ PowerX11::check_proc_acpi_battery(const char * node, bool * have_battery, bool *
}
}
-void PowerX11::check_proc_acpi_ac_adapter(const char * node, bool * have_ac)
-{
+void PowerX11::check_proc_acpi_ac_adapter(const char *node, bool *have_ac) {
const char *base = proc_acpi_ac_adapter_path;
char state[256];
char *ptr = NULL;
char *key = NULL;
char *val = NULL;
- if (!read_power_file(base, node, "state", state, sizeof (state))) {
+ if (!read_power_file(base, node, "state", state, sizeof(state))) {
return;
}
@@ -231,9 +223,7 @@ void PowerX11::check_proc_acpi_ac_adapter(const char * node, bool * have_ac)
}
}
-
-bool PowerX11::GetPowerInfo_Linux_proc_acpi()
-{
+bool PowerX11::GetPowerInfo_Linux_proc_acpi() {
String node;
DirAccess *dirp = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
bool have_battery = false;
@@ -244,16 +234,15 @@ bool PowerX11::GetPowerInfo_Linux_proc_acpi()
this->percent_left = -1;
this->power_state = POWERSTATE_UNKNOWN;
-
dirp->change_dir(proc_acpi_battery_path);
dirp->list_dir_begin();
if (dirp == NULL) {
- return false; /* can't use this interface. */
+ return false; /* can't use this interface. */
} else {
node = dirp->get_next();
while (node != "") {
- check_proc_acpi_battery(node.utf8().get_data(), &have_battery, &charging/*, seconds, percent*/);
+ check_proc_acpi_battery(node.utf8().get_data(), &have_battery, &charging /*, seconds, percent*/);
node = dirp->get_next();
}
memdelete(dirp);
@@ -262,7 +251,7 @@ bool PowerX11::GetPowerInfo_Linux_proc_acpi()
dirp->change_dir(proc_acpi_ac_adapter_path);
dirp->list_dir_begin();
if (dirp == NULL) {
- return false; /* can't use this interface. */
+ return false; /* can't use this interface. */
} else {
node = dirp->get_next();
while (node != "") {
@@ -282,16 +271,14 @@ bool PowerX11::GetPowerInfo_Linux_proc_acpi()
this->power_state = POWERSTATE_ON_BATTERY;
}
- return true; /* definitive answer. */
+ return true; /* definitive answer. */
}
-
-bool PowerX11::next_string(char **_ptr, char **_str)
-{
+bool PowerX11::next_string(char **_ptr, char **_str) {
char *ptr = *_ptr;
char *str = *_str;
- while (*ptr == ' ') { /* skip any spaces... */
+ while (*ptr == ' ') { /* skip any spaces... */
ptr++;
}
@@ -311,67 +298,65 @@ bool PowerX11::next_string(char **_ptr, char **_str)
return true;
}
-bool PowerX11::int_string(char *str, int *val)
-{
+bool PowerX11::int_string(char *str, int *val) {
String sval = str;
*val = sval.to_int();
return (*str != '\0');
}
/* http://lxr.linux.no/linux+v2.6.29/drivers/char/apm-emulation.c */
-bool PowerX11::GetPowerInfo_Linux_proc_apm()
-{
+bool PowerX11::GetPowerInfo_Linux_proc_apm() {
bool need_details = false;
int ac_status = 0;
int battery_status = 0;
int battery_flag = 0;
int battery_percent = 0;
int battery_time = 0;
- FileAccessRef fd = FileAccess::open(proc_apm_path,FileAccess::READ);
+ FileAccessRef fd = FileAccess::open(proc_apm_path, FileAccess::READ);
char buf[128];
char *ptr = &buf[0];
char *str = NULL;
ssize_t br;
if (!fd) {
- return false; /* can't use this interface. */
+ return false; /* can't use this interface. */
}
- br = fd->get_buffer(reinterpret_cast<uint8_t*>(buf), sizeof (buf) - 1);
+ br = fd->get_buffer(reinterpret_cast<uint8_t *>(buf), sizeof(buf) - 1);
fd->close();
if (br < 0) {
return false;
}
- buf[br] = '\0'; /* null-terminate the string. */
- if (!next_string(&ptr, &str)) { /* driver version */
+ buf[br] = '\0'; /* null-terminate the string. */
+ if (!next_string(&ptr, &str)) { /* driver version */
return false;
}
- if (!next_string(&ptr, &str)) { /* BIOS version */
+ if (!next_string(&ptr, &str)) { /* BIOS version */
return false;
}
- if (!next_string(&ptr, &str)) { /* APM flags */
+ if (!next_string(&ptr, &str)) { /* APM flags */
return false;
}
- if (!next_string(&ptr, &str)) { /* AC line status */
+ if (!next_string(&ptr, &str)) { /* AC line status */
return false;
} else if (!int_string(str, &ac_status)) {
return false;
}
- if (!next_string(&ptr, &str)) { /* battery status */
+ if (!next_string(&ptr, &str)) { /* battery status */
return false;
} else if (!int_string(str, &battery_status)) {
return false;
}
- if (!next_string(&ptr, &str)) { /* battery flag */
+ if (!next_string(&ptr, &str)) { /* battery flag */
return false;
} else if (!int_string(str, &battery_flag)) {
return false;
}
- if (!next_string(&ptr, &str)) { /* remaining battery life percent */
+ if (!next_string(&ptr, &str)) { /* remaining battery life percent */
return false;
}
String sstr = str;
@@ -382,13 +367,13 @@ bool PowerX11::GetPowerInfo_Linux_proc_apm()
return false;
}
- if (!next_string(&ptr, &str)) { /* remaining battery life time */
+ if (!next_string(&ptr, &str)) { /* remaining battery life time */
return false;
} else if (!int_string(str, &battery_time)) {
return false;
}
- if (!next_string(&ptr, &str)) { /* remaining battery life time units */
+ if (!next_string(&ptr, &str)) { /* remaining battery life time units */
return false;
} else if (String(str) == "min") {
battery_time *= 60;
@@ -396,13 +381,13 @@ bool PowerX11::GetPowerInfo_Linux_proc_apm()
if (battery_flag == 0xFF) { /* unknown state */
this->power_state = POWERSTATE_UNKNOWN;
- } else if (battery_flag & (1 << 7)) { /* no battery */
+ } else if (battery_flag & (1 << 7)) { /* no battery */
this->power_state = POWERSTATE_NO_BATTERY;
- } else if (battery_flag & (1 << 3)) { /* charging */
+ } else if (battery_flag & (1 << 3)) { /* charging */
this->power_state = POWERSTATE_CHARGING;
need_details = true;
} else if (ac_status == 1) {
- this->power_state = POWERSTATE_CHARGED; /* on AC, not charging. */
+ this->power_state = POWERSTATE_CHARGED; /* on AC, not charging. */
need_details = true;
} else {
this->power_state = POWERSTATE_ON_BATTERY;
@@ -415,10 +400,10 @@ bool PowerX11::GetPowerInfo_Linux_proc_apm()
const int pct = battery_percent;
const int secs = battery_time;
- if (pct >= 0) { /* -1 == unknown */
+ if (pct >= 0) { /* -1 == unknown */
this->percent_left = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
}
- if (secs >= 0) { /* -1 == unknown */
+ if (secs >= 0) { /* -1 == unknown */
this->nsecs_left = secs;
}
}
@@ -428,9 +413,8 @@ bool PowerX11::GetPowerInfo_Linux_proc_apm()
/* !!! FIXME: implement d-bus queries to org.freedesktop.UPower. */
-bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, int *seconds, int *percent*/)
-{
- const char* base = sys_class_power_supply_path;
+bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, int *seconds, int *percent*/) {
+ const char *base = sys_class_power_supply_path;
String name;
DirAccess *dirp = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -441,7 +425,7 @@ bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, in
return false;
}
- this->power_state = POWERSTATE_NO_BATTERY; /* assume we're just plugged in. */
+ this->power_state = POWERSTATE_NO_BATTERY; /* assume we're just plugged in. */
this->nsecs_left = -1;
this->percent_left = -1;
@@ -456,24 +440,24 @@ bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, in
if ((name == ".") || (name == "..")) {
name = dirp->get_next();
- continue; //skip these, of course.
+ continue; //skip these, of course.
} else {
- if (!read_power_file(base, name.utf8().get_data(), "type", str, sizeof (str))) {
+ if (!read_power_file(base, name.utf8().get_data(), "type", str, sizeof(str))) {
name = dirp->get_next();
- continue; // Don't know _what_ we're looking at. Give up on it.
+ continue; // Don't know _what_ we're looking at. Give up on it.
} else {
if (String(str) != "Battery\n") {
name = dirp->get_next();
- continue; // we don't care about UPS and such.
+ continue; // we don't care about UPS and such.
}
}
}
/* some drivers don't offer this, so if it's not explicitly reported assume it's present. */
- if (read_power_file(base, name.utf8().get_data(), "present", str, sizeof (str)) && (String(str) == "0\n")) {
+ if (read_power_file(base, name.utf8().get_data(), "present", str, sizeof(str)) && (String(str) == "0\n")) {
st = POWERSTATE_NO_BATTERY;
- } else if (!read_power_file(base, name.utf8().get_data(), "status", str, sizeof (str))) {
- st = POWERSTATE_UNKNOWN; /* uh oh */
+ } else if (!read_power_file(base, name.utf8().get_data(), "status", str, sizeof(str))) {
+ st = POWERSTATE_UNKNOWN; /* uh oh */
} else if (String(str) == "Charging\n") {
st = POWERSTATE_CHARGING;
} else if (String(str) == "Discharging\n") {
@@ -481,21 +465,21 @@ bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, in
} else if ((String(str) == "Full\n") || (String(str) == "Not charging\n")) {
st = POWERSTATE_CHARGED;
} else {
- st = POWERSTATE_UNKNOWN; /* uh oh */
+ st = POWERSTATE_UNKNOWN; /* uh oh */
}
- if (!read_power_file(base, name.utf8().get_data(), "capacity", str, sizeof (str))) {
+ if (!read_power_file(base, name.utf8().get_data(), "capacity", str, sizeof(str))) {
pct = -1;
} else {
pct = String(str).to_int();
pct = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
}
- if (!read_power_file(base, name.utf8().get_data(), "time_to_empty_now", str, sizeof (str))) {
+ if (!read_power_file(base, name.utf8().get_data(), "time_to_empty_now", str, sizeof(str))) {
secs = -1;
} else {
secs = String(str).to_int();
- secs = (secs <= 0) ? -1 : secs; /* 0 == unknown */
+ secs = (secs <= 0) ? -1 : secs; /* 0 == unknown */
}
/*
@@ -504,7 +488,7 @@ bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, in
*/
if ((secs < 0) && (this->nsecs_left < 0)) {
if ((pct < 0) && (this->percent_left < 0)) {
- choose = true; /* at least we know there's a battery. */
+ choose = true; /* at least we know there's a battery. */
} else if (pct > this->percent_left) {
choose = true;
}
@@ -522,26 +506,24 @@ bool PowerX11::GetPowerInfo_Linux_sys_class_power_supply(/*PowerState *state, in
}
memdelete(dirp);
- return true; /* don't look any further*/
+ return true; /* don't look any further*/
}
-
-
-bool PowerX11::UpdatePowerInfo()
-{
- if (GetPowerInfo_Linux_sys_class_power_supply()) { // try method 1
+bool PowerX11::UpdatePowerInfo() {
+ if (GetPowerInfo_Linux_sys_class_power_supply()) { // try method 1
return true;
}
- if (GetPowerInfo_Linux_proc_acpi()) { // try further
+ if (GetPowerInfo_Linux_proc_acpi()) { // try further
return true;
}
- if (GetPowerInfo_Linux_proc_apm()) { // try even further
+ if (GetPowerInfo_Linux_proc_apm()) { // try even further
return true;
}
return false;
}
-PowerX11::PowerX11() : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
+PowerX11::PowerX11()
+ : nsecs_left(-1), percent_left(-1), power_state(POWERSTATE_UNKNOWN) {
}
PowerX11::~PowerX11() {
@@ -550,8 +532,7 @@ PowerX11::~PowerX11() {
PowerState PowerX11::get_power_state() {
if (UpdatePowerInfo()) {
return power_state;
- }
- else {
+ } else {
return POWERSTATE_UNKNOWN;
}
}
@@ -559,8 +540,7 @@ PowerState PowerX11::get_power_state() {
int PowerX11::get_power_seconds_left() {
if (UpdatePowerInfo()) {
return nsecs_left;
- }
- else {
+ } else {
return -1;
}
}
@@ -568,8 +548,7 @@ int PowerX11::get_power_seconds_left() {
int PowerX11::get_power_percent_left() {
if (UpdatePowerInfo()) {
return percent_left;
- }
- else {
+ } else {
return -1;
}
}
diff --git a/platform/x11/power_x11.h b/platform/x11/power_x11.h
index 6efb2de348..7693a5b022 100644
--- a/platform/x11/power_x11.h
+++ b/platform/x11/power_x11.h
@@ -34,7 +34,6 @@
#include "os/file_access.h"
#include "os/power.h"
-
class PowerX11 {
private:
@@ -42,12 +41,11 @@ private:
int percent_left;
PowerState power_state;
-
- FileAccessRef open_power_file(const char* base, const char* node, const char* key);
- bool read_power_file(const char* base, const char* node, const char* key, char* buf, size_t buflen);
+ FileAccessRef open_power_file(const char *base, const char *node, const char *key);
+ bool read_power_file(const char *base, const char *node, const char *key, char *buf, size_t buflen);
bool make_proc_acpi_key_val(char **_ptr, char **_key, char **_val);
- void check_proc_acpi_battery(const char * node, bool * have_battery, bool * charging);
- void check_proc_acpi_ac_adapter(const char * node, bool * have_ac);
+ void check_proc_acpi_battery(const char *node, bool *have_battery, bool *charging);
+ void check_proc_acpi_ac_adapter(const char *node, bool *have_ac);
bool GetPowerInfo_Linux_proc_acpi();
bool next_string(char **_ptr, char **_str);
bool int_string(char *str, int *val);
@@ -55,7 +53,6 @@ private:
bool GetPowerInfo_Linux_sys_class_power_supply();
bool UpdatePowerInfo();
-
public:
PowerX11();
virtual ~PowerX11();
diff --git a/scene/2d/animated_sprite.cpp b/scene/2d/animated_sprite.cpp
index faecbf3e6d..f10bd2f303 100644
--- a/scene/2d/animated_sprite.cpp
+++ b/scene/2d/animated_sprite.cpp
@@ -27,24 +27,19 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "animated_sprite.h"
-#include "scene/scene_string_names.h"
#include "os/os.h"
#include "scene/scene_string_names.h"
-
-
-
+#include "scene/scene_string_names.h"
////////////////////////////
+void SpriteFrames::add_frame(const StringName &p_anim, const Ref<Texture> &p_frame, int p_at_pos) {
-
-void SpriteFrames::add_frame(const StringName &p_anim, const Ref<Texture>& p_frame, int p_at_pos) {
-
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
- if (p_at_pos>=0 && p_at_pos<E->get().frames.size())
- E->get().frames.insert(p_at_pos,p_frame);
+ if (p_at_pos >= 0 && p_at_pos < E->get().frames.size())
+ E->get().frames.insert(p_at_pos, p_frame);
else
E->get().frames.push_back(p_frame);
@@ -52,15 +47,15 @@ void SpriteFrames::add_frame(const StringName &p_anim, const Ref<Texture>& p_fra
}
int SpriteFrames::get_frame_count(const StringName &p_anim) const {
- const Map<StringName,Anim>::Element *E=animations.find(p_anim);
- ERR_FAIL_COND_V(!E,0);
+ const Map<StringName, Anim>::Element *E = animations.find(p_anim);
+ ERR_FAIL_COND_V(!E, 0);
return E->get().frames.size();
}
void SpriteFrames::remove_frame(const StringName &p_anim, int p_idx) {
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().frames.remove(p_idx);
@@ -68,7 +63,7 @@ void SpriteFrames::remove_frame(const StringName &p_anim, int p_idx) {
}
void SpriteFrames::clear(const StringName &p_anim) {
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
E->get().frames.clear();
@@ -81,33 +76,30 @@ void SpriteFrames::clear_all() {
add_animation("default");
}
-
-
-void SpriteFrames::add_animation(const StringName& p_anim) {
+void SpriteFrames::add_animation(const StringName &p_anim) {
ERR_FAIL_COND(animations.has(p_anim));
- animations[p_anim]=Anim();
+ animations[p_anim] = Anim();
}
-bool SpriteFrames::has_animation(const StringName& p_anim) const{
+bool SpriteFrames::has_animation(const StringName &p_anim) const {
return animations.has(p_anim);
}
-void SpriteFrames::remove_animation(const StringName& p_anim){
+void SpriteFrames::remove_animation(const StringName &p_anim) {
animations.erase(p_anim);
}
-void SpriteFrames::rename_animation(const StringName& p_prev,const StringName& p_next) {
+void SpriteFrames::rename_animation(const StringName &p_prev, const StringName &p_next) {
ERR_FAIL_COND(!animations.has(p_prev));
ERR_FAIL_COND(animations.has(p_next));
Anim anim = animations[p_prev];
animations.erase(p_prev);
- animations[p_next]=anim;
-
+ animations[p_next] = anim;
}
Vector<String> SpriteFrames::_get_animation_list() const {
@@ -115,7 +107,7 @@ Vector<String> SpriteFrames::_get_animation_list() const {
Vector<String> ret;
List<StringName> al;
get_animation_list(&al);
- for(List<StringName>::Element *E=al.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = al.front(); E; E = E->next()) {
ret.push_back(E->get());
}
@@ -123,49 +115,47 @@ Vector<String> SpriteFrames::_get_animation_list() const {
return ret;
}
-void SpriteFrames::get_animation_list(List<StringName> *r_animations) const{
+void SpriteFrames::get_animation_list(List<StringName> *r_animations) const {
- for (const Map<StringName,Anim>::Element *E=animations.front();E;E=E->next()) {
+ for (const Map<StringName, Anim>::Element *E = animations.front(); E; E = E->next()) {
r_animations->push_back(E->key());
}
}
-void SpriteFrames::set_animation_speed(const StringName& p_anim,float p_fps){
+void SpriteFrames::set_animation_speed(const StringName &p_anim, float p_fps) {
- ERR_FAIL_COND(p_fps<0);
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+ ERR_FAIL_COND(p_fps < 0);
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
- E->get().speed=p_fps;
+ E->get().speed = p_fps;
}
-float SpriteFrames::get_animation_speed(const StringName& p_anim) const{
+float SpriteFrames::get_animation_speed(const StringName &p_anim) const {
- const Map<StringName,Anim>::Element *E=animations.find(p_anim);
- ERR_FAIL_COND_V(!E,0);
+ const Map<StringName, Anim>::Element *E = animations.find(p_anim);
+ ERR_FAIL_COND_V(!E, 0);
return E->get().speed;
}
-void SpriteFrames::set_animation_loop(const StringName& p_anim,bool p_loop){
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+void SpriteFrames::set_animation_loop(const StringName &p_anim, bool p_loop) {
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
- E->get().loop=p_loop;
+ E->get().loop = p_loop;
}
-bool SpriteFrames::get_animation_loop(const StringName& p_anim) const{
- const Map<StringName,Anim>::Element *E=animations.find(p_anim);
- ERR_FAIL_COND_V(!E,false);
+bool SpriteFrames::get_animation_loop(const StringName &p_anim) const {
+ const Map<StringName, Anim>::Element *E = animations.find(p_anim);
+ ERR_FAIL_COND_V(!E, false);
return E->get().loop;
-
}
-void SpriteFrames::_set_frames(const Array& p_frames) {
+void SpriteFrames::_set_frames(const Array &p_frames) {
clear_all();
- Map<StringName,Anim>::Element *E=animations.find(SceneStringNames::get_singleton()->_default);
+ Map<StringName, Anim>::Element *E = animations.find(SceneStringNames::get_singleton()->_default);
ERR_FAIL_COND(!E);
E->get().frames.resize(p_frames.size());
- for(int i=0;i<E->get().frames.size();i++)
- E->get().frames[i]=p_frames[i];
-
+ for (int i = 0; i < E->get().frames.size(); i++)
+ E->get().frames[i] = p_frames[i];
}
Array SpriteFrames::_get_frames() const {
@@ -175,27 +165,27 @@ Array SpriteFrames::_get_frames() const {
Array SpriteFrames::_get_animations() const {
Array anims;
- for (Map<StringName,Anim>::Element *E=animations.front();E;E=E->next()) {
+ for (Map<StringName, Anim>::Element *E = animations.front(); E; E = E->next()) {
Dictionary d;
- d["name"]=E->key();
- d["speed"]=E->get().speed;
- d["loop"]=E->get().loop;
+ d["name"] = E->key();
+ d["speed"] = E->get().speed;
+ d["loop"] = E->get().loop;
Array frames;
- for(int i=0;i<E->get().frames.size();i++) {
+ for (int i = 0; i < E->get().frames.size(); i++) {
frames.push_back(E->get().frames[i]);
}
- d["frames"]=frames;
+ d["frames"] = frames;
anims.push_back(d);
}
return anims;
}
-void SpriteFrames::_set_animations(const Array& p_animations) {
+void SpriteFrames::_set_animations(const Array &p_animations) {
animations.clear();
- for(int i=0;i<p_animations.size();i++) {
+ for (int i = 0; i < p_animations.size(); i++) {
- Dictionary d=p_animations[i];
+ Dictionary d = p_animations[i];
ERR_CONTINUE(!d.has("name"));
ERR_CONTINUE(!d.has("speed"));
@@ -203,71 +193,57 @@ void SpriteFrames::_set_animations(const Array& p_animations) {
ERR_CONTINUE(!d.has("frames"));
Anim anim;
- anim.speed=d["speed"];
- anim.loop=d["loop"];
- Array frames=d["frames"];
- for(int i=0;i<frames.size();i++) {
+ anim.speed = d["speed"];
+ anim.loop = d["loop"];
+ Array frames = d["frames"];
+ for (int i = 0; i < frames.size(); i++) {
RES res = frames[i];
anim.frames.push_back(res);
}
- animations[d["name"]]=anim;
-
-
+ animations[d["name"]] = anim;
}
}
-
void SpriteFrames::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("add_animation", "anim"), &SpriteFrames::add_animation);
+ ClassDB::bind_method(D_METHOD("has_animation", "anim"), &SpriteFrames::has_animation);
+ ClassDB::bind_method(D_METHOD("remove_animation", "anim"), &SpriteFrames::remove_animation);
+ ClassDB::bind_method(D_METHOD("rename_animation", "anim", "newname"), &SpriteFrames::rename_animation);
- ClassDB::bind_method(D_METHOD("add_animation","anim"),&SpriteFrames::add_animation);
- ClassDB::bind_method(D_METHOD("has_animation","anim"),&SpriteFrames::has_animation);
- ClassDB::bind_method(D_METHOD("remove_animation","anim"),&SpriteFrames::remove_animation);
- ClassDB::bind_method(D_METHOD("rename_animation","anim","newname"),&SpriteFrames::rename_animation);
-
- ClassDB::bind_method(D_METHOD("set_animation_speed","anim","speed"),&SpriteFrames::set_animation_speed);
- ClassDB::bind_method(D_METHOD("get_animation_speed","anim"),&SpriteFrames::get_animation_speed);
-
- ClassDB::bind_method(D_METHOD("set_animation_loop","anim","loop"),&SpriteFrames::set_animation_loop);
- ClassDB::bind_method(D_METHOD("get_animation_loop","anim"),&SpriteFrames::get_animation_loop);
+ ClassDB::bind_method(D_METHOD("set_animation_speed", "anim", "speed"), &SpriteFrames::set_animation_speed);
+ ClassDB::bind_method(D_METHOD("get_animation_speed", "anim"), &SpriteFrames::get_animation_speed);
- ClassDB::bind_method(D_METHOD("add_frame","anim","frame","atpos"),&SpriteFrames::add_frame,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("get_frame_count","anim"),&SpriteFrames::get_frame_count);
- ClassDB::bind_method(D_METHOD("get_frame","anim","idx"),&SpriteFrames::get_frame);
- ClassDB::bind_method(D_METHOD("set_frame","anim","idx","txt"),&SpriteFrames::set_frame);
- ClassDB::bind_method(D_METHOD("remove_frame","anim","idx"),&SpriteFrames::remove_frame);
- ClassDB::bind_method(D_METHOD("clear","anim"),&SpriteFrames::clear);
- ClassDB::bind_method(D_METHOD("clear_all"),&SpriteFrames::clear_all);
+ ClassDB::bind_method(D_METHOD("set_animation_loop", "anim", "loop"), &SpriteFrames::set_animation_loop);
+ ClassDB::bind_method(D_METHOD("get_animation_loop", "anim"), &SpriteFrames::get_animation_loop);
- ClassDB::bind_method(D_METHOD("_set_frames"),&SpriteFrames::_set_frames);
- ClassDB::bind_method(D_METHOD("_get_frames"),&SpriteFrames::_get_frames);
+ ClassDB::bind_method(D_METHOD("add_frame", "anim", "frame", "atpos"), &SpriteFrames::add_frame, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("get_frame_count", "anim"), &SpriteFrames::get_frame_count);
+ ClassDB::bind_method(D_METHOD("get_frame", "anim", "idx"), &SpriteFrames::get_frame);
+ ClassDB::bind_method(D_METHOD("set_frame", "anim", "idx", "txt"), &SpriteFrames::set_frame);
+ ClassDB::bind_method(D_METHOD("remove_frame", "anim", "idx"), &SpriteFrames::remove_frame);
+ ClassDB::bind_method(D_METHOD("clear", "anim"), &SpriteFrames::clear);
+ ClassDB::bind_method(D_METHOD("clear_all"), &SpriteFrames::clear_all);
- ADD_PROPERTYNZ( PropertyInfo(Variant::ARRAY,"frames",PROPERTY_HINT_NONE,"",0),"_set_frames","_get_frames"); //compatibility
+ ClassDB::bind_method(D_METHOD("_set_frames"), &SpriteFrames::_set_frames);
+ ClassDB::bind_method(D_METHOD("_get_frames"), &SpriteFrames::_get_frames);
- ClassDB::bind_method(D_METHOD("_set_animations"),&SpriteFrames::_set_animations);
- ClassDB::bind_method(D_METHOD("_get_animations"),&SpriteFrames::_get_animations);
+ ADD_PROPERTYNZ(PropertyInfo(Variant::ARRAY, "frames", PROPERTY_HINT_NONE, "", 0), "_set_frames", "_get_frames"); //compatibility
- ADD_PROPERTYNZ( PropertyInfo(Variant::ARRAY,"animations",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_animations","_get_animations"); //compatibility
+ ClassDB::bind_method(D_METHOD("_set_animations"), &SpriteFrames::_set_animations);
+ ClassDB::bind_method(D_METHOD("_get_animations"), &SpriteFrames::_get_animations);
+ ADD_PROPERTYNZ(PropertyInfo(Variant::ARRAY, "animations", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_animations", "_get_animations"); //compatibility
}
-
-
-
SpriteFrames::SpriteFrames() {
add_animation(SceneStringNames::get_singleton()->_default);
-
}
-
-
-
-
-
-void AnimatedSprite::edit_set_pivot(const Point2& p_pivot) {
+void AnimatedSprite::edit_set_pivot(const Point2 &p_pivot) {
set_offset(p_pivot);
}
@@ -281,88 +257,85 @@ bool AnimatedSprite::edit_has_pivot() const {
return true;
}
-
-void AnimatedSprite::_validate_property(PropertyInfo& property) const {
+void AnimatedSprite::_validate_property(PropertyInfo &property) const {
if (!frames.is_valid())
return;
- if (property.name=="animation") {
+ if (property.name == "animation") {
- property.hint=PROPERTY_HINT_ENUM;
+ property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
- bool current_found=false;
+ bool current_found = false;
- for (List<StringName>::Element *E=names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
if (E->prev()) {
- property.hint_string+=",";
+ property.hint_string += ",";
}
- property.hint_string+=String(E->get());
- if (animation==E->get()) {
- current_found=true;
+ property.hint_string += String(E->get());
+ if (animation == E->get()) {
+ current_found = true;
}
}
if (!current_found) {
- if (property.hint_string==String()) {
- property.hint_string=String(animation);
+ if (property.hint_string == String()) {
+ property.hint_string = String(animation);
} else {
- property.hint_string=String(animation)+","+property.hint_string;
+ property.hint_string = String(animation) + "," + property.hint_string;
}
}
}
+ if (property.name == "frame") {
- if (property.name=="frame") {
-
- property.hint=PROPERTY_HINT_SPRITE_FRAME;
+ property.hint = PROPERTY_HINT_SPRITE_FRAME;
if (frames->has_animation(animation)) {
- property.hint_string="0,"+itos(frames->get_frame_count(animation)-1)+",1";
+ property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
- property.hint_string="0,0,0";
+ property.hint_string = "0,0,0";
}
}
-
}
void AnimatedSprite::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null())
return;
if (!frames->has_animation(animation))
return;
- if (frame<0)
+ if (frame < 0)
return;
float speed = frames->get_animation_speed(animation);
- if (speed==0)
+ if (speed == 0)
return; //do nothing
float remaining = get_process_delta_time();
- while(remaining) {
+ while (remaining) {
- if (timeout<=0) {
+ if (timeout <= 0) {
- timeout=1.0/speed;
+ timeout = 1.0 / speed;
int fc = frames->get_frame_count(animation);
- if (frame>=fc-1) {
+ if (frame >= fc - 1) {
if (frames->get_animation_loop(animation)) {
- frame=0;
+ frame = 0;
} else {
- frame=fc-1;
+ frame = fc - 1;
}
} else {
frame++;
- if (frame==fc-1) {
+ if (frame == fc - 1) {
emit_signal(SceneStringNames::get_singleton()->animation_finished);
}
}
@@ -371,9 +344,9 @@ void AnimatedSprite::_notification(int p_what) {
_change_notify("frame");
}
- float to_process = MIN(timeout,remaining);
- remaining-=to_process;
- timeout-=to_process;
+ float to_process = MIN(timeout, remaining);
+ remaining -= to_process;
+ timeout -= to_process;
}
} break;
@@ -384,19 +357,17 @@ void AnimatedSprite::_notification(int p_what) {
return;
}
- if (frame<0) {
+ if (frame < 0) {
print_line("no draw frame <0");
return;
}
if (!frames->has_animation(animation)) {
- print_line("no draw no anim: "+String(animation));
+ print_line("no draw no anim: " + String(animation));
return;
}
-
-
- Ref<Texture> texture = frames->get_frame(animation,frame);
+ Ref<Texture> texture = frames->get_frame(animation, frame);
if (texture.is_null()) {
print_line("no draw texture is null");
return;
@@ -413,50 +384,46 @@ void AnimatedSprite::_notification(int p_what) {
Size2i s;
s = texture->get_size();
- Point2 ofs=offset;
+ Point2 ofs = offset;
if (centered)
- ofs-=s/2;
+ ofs -= s / 2;
if (Engine::get_singleton()->get_use_pixel_snap()) {
- ofs=ofs.floor();
+ ofs = ofs.floor();
}
- Rect2 dst_rect(ofs,s);
+ Rect2 dst_rect(ofs, s);
if (hflip)
- dst_rect.size.x=-dst_rect.size.x;
+ dst_rect.size.x = -dst_rect.size.x;
if (vflip)
- dst_rect.size.y=-dst_rect.size.y;
+ dst_rect.size.y = -dst_rect.size.y;
//texture->draw_rect(ci,dst_rect,false,modulate);
- texture->draw_rect_region(ci,dst_rect,Rect2(Vector2(),texture->get_size()));
+ texture->draw_rect_region(ci, dst_rect, Rect2(Vector2(), texture->get_size()));
//VisualServer::get_singleton()->canvas_item_add_texture_rect_region(ci,dst_rect,texture->get_rid(),src_rect,modulate);
} break;
}
-
}
void AnimatedSprite::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames.is_valid())
- frames->disconnect("changed",this,"_res_changed");
- frames=p_frames;
+ frames->disconnect("changed", this, "_res_changed");
+ frames = p_frames;
if (frames.is_valid())
- frames->connect("changed",this,"_res_changed");
+ frames->connect("changed", this, "_res_changed");
if (!frames.is_valid()) {
- frame=0;
+ frame = 0;
} else {
set_frame(frame);
}
-
-
_change_notify();
_reset_timeout();
update();
update_configuration_warning();
-
}
Ref<SpriteFrames> AnimatedSprite::get_sprite_frames() const {
@@ -472,36 +439,30 @@ void AnimatedSprite::set_frame(int p_frame) {
if (frames->has_animation(animation)) {
int limit = frames->get_frame_count(animation);
- if (p_frame>=limit)
- p_frame=limit-1;
-
+ if (p_frame >= limit)
+ p_frame = limit - 1;
}
- if (p_frame<0)
- p_frame=0;
+ if (p_frame < 0)
+ p_frame = 0;
-
- if (frame==p_frame)
+ if (frame == p_frame)
return;
- frame=p_frame;
+ frame = p_frame;
_reset_timeout();
update();
_change_notify("frame");
emit_signal(SceneStringNames::get_singleton()->frame_changed);
-
-
-
}
int AnimatedSprite::get_frame() const {
return frame;
}
-
void AnimatedSprite::set_centered(bool p_center) {
- centered=p_center;
+ centered = p_center;
update();
item_rect_changed();
}
@@ -511,9 +472,9 @@ bool AnimatedSprite::is_centered() const {
return centered;
}
-void AnimatedSprite::set_offset(const Point2& p_offset) {
+void AnimatedSprite::set_offset(const Point2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
update();
item_rect_changed();
_change_notify("offset");
@@ -525,7 +486,7 @@ Point2 AnimatedSprite::get_offset() const {
void AnimatedSprite::set_flip_h(bool p_flip) {
- hflip=p_flip;
+ hflip = p_flip;
update();
}
bool AnimatedSprite::is_flipped_h() const {
@@ -535,7 +496,7 @@ bool AnimatedSprite::is_flipped_h() const {
void AnimatedSprite::set_flip_v(bool p_flip) {
- vflip=p_flip;
+ vflip = p_flip;
update();
}
bool AnimatedSprite::is_flipped_v() const {
@@ -543,29 +504,27 @@ bool AnimatedSprite::is_flipped_v() const {
return vflip;
}
-
-
Rect2 AnimatedSprite::get_item_rect() const {
- if (!frames.is_valid() || !frames->has_animation(animation) || frame<0 || frame>=frames->get_frame_count(animation)) {
+ if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) {
return Node2D::get_item_rect();
}
Ref<Texture> t;
if (animation)
- t = frames->get_frame(animation,frame);
+ t = frames->get_frame(animation, frame);
if (t.is_null())
return Node2D::get_item_rect();
Size2i s = t->get_size();
- Point2 ofs=offset;
+ Point2 ofs = offset;
if (centered)
- ofs-=s/2;
+ ofs -= s / 2;
- if (s==Size2(0,0))
- s=Size2(1,1);
+ if (s == Size2(0, 0))
+ s = Size2(1, 1);
- return Rect2(ofs,s);
+ return Rect2(ofs, s);
}
void AnimatedSprite::_res_changed() {
@@ -578,9 +537,9 @@ void AnimatedSprite::_res_changed() {
void AnimatedSprite::_set_playing(bool p_playing) {
- if (playing==p_playing)
+ if (playing == p_playing)
return;
- playing=p_playing;
+ playing = p_playing;
_reset_timeout();
set_process_internal(playing);
}
@@ -590,14 +549,14 @@ bool AnimatedSprite::_is_playing() const {
return playing;
}
-void AnimatedSprite::play(const StringName& p_animation) {
+void AnimatedSprite::play(const StringName &p_animation) {
if (p_animation)
set_animation(p_animation);
_set_playing(true);
}
-void AnimatedSprite::stop(){
+void AnimatedSprite::stop() {
_set_playing(false);
}
@@ -614,29 +573,28 @@ void AnimatedSprite::_reset_timeout() {
if (frames.is_valid() && frames->has_animation(animation)) {
float speed = frames->get_animation_speed(animation);
- if (speed>0) {
- timeout=1.0/speed;
+ if (speed > 0) {
+ timeout = 1.0 / speed;
} else {
- timeout=0;
+ timeout = 0;
}
} else {
- timeout=0;
+ timeout = 0;
}
-
}
-void AnimatedSprite::set_animation(const StringName& p_animation){
+void AnimatedSprite::set_animation(const StringName &p_animation) {
- if (animation==p_animation)
+ if (animation == p_animation)
return;
- animation=p_animation;
+ animation = p_animation;
_reset_timeout();
set_frame(0);
_change_notify();
update();
}
-StringName AnimatedSprite::get_animation() const{
+StringName AnimatedSprite::get_animation() const {
return animation;
}
@@ -652,65 +610,57 @@ String AnimatedSprite::get_configuration_warning() const {
void AnimatedSprite::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames:SpriteFrames"), &AnimatedSprite::set_sprite_frames);
+ ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"), &AnimatedSprite::get_sprite_frames);
- ClassDB::bind_method(D_METHOD("set_sprite_frames","sprite_frames:SpriteFrames"),&AnimatedSprite::set_sprite_frames);
- ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"),&AnimatedSprite::get_sprite_frames);
-
- ClassDB::bind_method(D_METHOD("set_animation","animation"),&AnimatedSprite::set_animation);
- ClassDB::bind_method(D_METHOD("get_animation"),&AnimatedSprite::get_animation);
-
- ClassDB::bind_method(D_METHOD("_set_playing","playing"),&AnimatedSprite::_set_playing);
- ClassDB::bind_method(D_METHOD("_is_playing"),&AnimatedSprite::_is_playing);
+ ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite::set_animation);
+ ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite::get_animation);
- ClassDB::bind_method(D_METHOD("play","anim"),&AnimatedSprite::play,DEFVAL(StringName()));
- ClassDB::bind_method(D_METHOD("stop"),&AnimatedSprite::stop);
- ClassDB::bind_method(D_METHOD("is_playing"),&AnimatedSprite::is_playing);
+ ClassDB::bind_method(D_METHOD("_set_playing", "playing"), &AnimatedSprite::_set_playing);
+ ClassDB::bind_method(D_METHOD("_is_playing"), &AnimatedSprite::_is_playing);
- ClassDB::bind_method(D_METHOD("set_centered","centered"),&AnimatedSprite::set_centered);
- ClassDB::bind_method(D_METHOD("is_centered"),&AnimatedSprite::is_centered);
+ ClassDB::bind_method(D_METHOD("play", "anim"), &AnimatedSprite::play, DEFVAL(StringName()));
+ ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite::stop);
+ ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite::is_playing);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&AnimatedSprite::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&AnimatedSprite::get_offset);
+ ClassDB::bind_method(D_METHOD("set_centered", "centered"), &AnimatedSprite::set_centered);
+ ClassDB::bind_method(D_METHOD("is_centered"), &AnimatedSprite::is_centered);
- ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&AnimatedSprite::set_flip_h);
- ClassDB::bind_method(D_METHOD("is_flipped_h"),&AnimatedSprite::is_flipped_h);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &AnimatedSprite::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &AnimatedSprite::get_offset);
- ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&AnimatedSprite::set_flip_v);
- ClassDB::bind_method(D_METHOD("is_flipped_v"),&AnimatedSprite::is_flipped_v);
+ ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &AnimatedSprite::set_flip_h);
+ ClassDB::bind_method(D_METHOD("is_flipped_h"), &AnimatedSprite::is_flipped_h);
- ClassDB::bind_method(D_METHOD("set_frame","frame"),&AnimatedSprite::set_frame);
- ClassDB::bind_method(D_METHOD("get_frame"),&AnimatedSprite::get_frame);
+ ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &AnimatedSprite::set_flip_v);
+ ClassDB::bind_method(D_METHOD("is_flipped_v"), &AnimatedSprite::is_flipped_v);
+ ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite::set_frame);
+ ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite::get_frame);
- ClassDB::bind_method(D_METHOD("_res_changed"),&AnimatedSprite::_res_changed);
+ ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite::_res_changed);
ADD_SIGNAL(MethodInfo("frame_changed"));
ADD_SIGNAL(MethodInfo("animation_finished"));
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "frames",PROPERTY_HINT_RESOURCE_TYPE,"SpriteFrames"), "set_sprite_frames","get_sprite_frames");
- ADD_PROPERTY( PropertyInfo( Variant::STRING, "animation"), "set_animation","get_animation");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "playing"), "_set_playing","_is_playing");
- ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered");
- ADD_PROPERTYNZ( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v");
-
-
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v");
}
AnimatedSprite::AnimatedSprite() {
- centered=true;
- hflip=false;
- vflip=false;
-
- frame=0;
- playing=false;
- animation="default";
- timeout=0;
-
+ centered = true;
+ hflip = false;
+ vflip = false;
+ frame = 0;
+ playing = false;
+ animation = "default";
+ timeout = 0;
}
-
-
diff --git a/scene/2d/animated_sprite.h b/scene/2d/animated_sprite.h
index fbeea7f69b..bc0e85b0ca 100644
--- a/scene/2d/animated_sprite.h
+++ b/scene/2d/animated_sprite.h
@@ -32,84 +32,80 @@
#include "scene/2d/node_2d.h"
#include "scene/resources/texture.h"
-
class SpriteFrames : public Resource {
- GDCLASS(SpriteFrames,Resource);
+ GDCLASS(SpriteFrames, Resource);
struct Anim {
float speed;
bool loop;
- Vector< Ref<Texture> > frames;
+ Vector<Ref<Texture> > frames;
- Anim() { loop=true; speed=5; }
+ Anim() {
+ loop = true;
+ speed = 5;
+ }
};
- Map<StringName,Anim> animations;
+ Map<StringName, Anim> animations;
Array _get_frames() const;
- void _set_frames(const Array& p_frames);
+ void _set_frames(const Array &p_frames);
Array _get_animations() const;
- void _set_animations(const Array& p_animations);
+ void _set_animations(const Array &p_animations);
Vector<String> _get_animation_list() const;
protected:
-
static void _bind_methods();
public:
-
- void add_animation(const StringName& p_anim);
- bool has_animation(const StringName& p_anim) const;
- void remove_animation(const StringName& p_anim);
- void rename_animation(const StringName& p_prev,const StringName& p_next);
+ void add_animation(const StringName &p_anim);
+ bool has_animation(const StringName &p_anim) const;
+ void remove_animation(const StringName &p_anim);
+ void rename_animation(const StringName &p_prev, const StringName &p_next);
void get_animation_list(List<StringName> *r_animations) const;
- void set_animation_speed(const StringName& p_anim,float p_fps);
- float get_animation_speed(const StringName& p_anim) const;
+ void set_animation_speed(const StringName &p_anim, float p_fps);
+ float get_animation_speed(const StringName &p_anim) const;
- void set_animation_loop(const StringName& p_anim,bool p_loop);
- bool get_animation_loop(const StringName& p_anim) const;
+ void set_animation_loop(const StringName &p_anim, bool p_loop);
+ bool get_animation_loop(const StringName &p_anim) const;
- void add_frame(const StringName& p_anim,const Ref<Texture>& p_frame,int p_at_pos=-1);
- int get_frame_count(const StringName& p_anim) const;
- _FORCE_INLINE_ Ref<Texture> get_frame(const StringName& p_anim,int p_idx) const {
+ void add_frame(const StringName &p_anim, const Ref<Texture> &p_frame, int p_at_pos = -1);
+ int get_frame_count(const StringName &p_anim) const;
+ _FORCE_INLINE_ Ref<Texture> get_frame(const StringName &p_anim, int p_idx) const {
- const Map<StringName,Anim>::Element *E=animations.find(p_anim);
- ERR_FAIL_COND_V(!E,Ref<Texture>());
- ERR_FAIL_COND_V(p_idx<0,Ref<Texture>());
- if (p_idx>=E->get().frames.size())
+ const Map<StringName, Anim>::Element *E = animations.find(p_anim);
+ ERR_FAIL_COND_V(!E, Ref<Texture>());
+ ERR_FAIL_COND_V(p_idx < 0, Ref<Texture>());
+ if (p_idx >= E->get().frames.size())
return Ref<Texture>();
return E->get().frames[p_idx];
}
- void set_frame(const StringName& p_anim,int p_idx,const Ref<Texture>& p_frame){
- Map<StringName,Anim>::Element *E=animations.find(p_anim);
+ void set_frame(const StringName &p_anim, int p_idx, const Ref<Texture> &p_frame) {
+ Map<StringName, Anim>::Element *E = animations.find(p_anim);
ERR_FAIL_COND(!E);
- ERR_FAIL_COND(p_idx<0);
- if (p_idx>=E->get().frames.size())
+ ERR_FAIL_COND(p_idx < 0);
+ if (p_idx >= E->get().frames.size())
return;
- E->get().frames[p_idx]=p_frame;
+ E->get().frames[p_idx] = p_frame;
}
- void remove_frame(const StringName& p_anim,int p_idx);
- void clear(const StringName& p_anim);
+ void remove_frame(const StringName &p_anim, int p_idx);
+ void clear(const StringName &p_anim);
void clear_all();
-
SpriteFrames();
-
};
-
-
class AnimatedSprite : public Node2D {
- GDCLASS(AnimatedSprite,Node2D);
+ GDCLASS(AnimatedSprite, Node2D);
Ref<SpriteFrames> frames;
bool playing;
@@ -124,35 +120,30 @@ class AnimatedSprite : public Node2D {
bool hflip;
bool vflip;
-
void _res_changed();
void _reset_timeout();
void _set_playing(bool p_playing);
bool _is_playing() const;
-
protected:
-
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
-
- virtual void edit_set_pivot(const Point2& p_pivot);
+ virtual void edit_set_pivot(const Point2 &p_pivot);
virtual Point2 edit_get_pivot() const;
virtual bool edit_has_pivot() const;
void set_sprite_frames(const Ref<SpriteFrames> &p_frames);
Ref<SpriteFrames> get_sprite_frames() const;
- void play(const StringName& p_animation=StringName());
+ void play(const StringName &p_animation = StringName());
void stop();
bool is_playing() const;
- void set_animation(const StringName& p_animation);
+ void set_animation(const StringName &p_animation);
StringName get_animation() const;
void set_frame(int p_frame);
@@ -161,7 +152,7 @@ public:
void set_centered(bool p_center);
bool is_centered() const;
- void set_offset(const Point2& p_offset);
+ void set_offset(const Point2 &p_offset);
Point2 get_offset() const;
void set_flip_h(bool p_flip);
@@ -170,7 +161,7 @@ public:
void set_flip_v(bool p_flip);
bool is_flipped_v() const;
- void set_modulate(const Color& p_color);
+ void set_modulate(const Color &p_color);
Color get_modulate() const;
virtual Rect2 get_item_rect() const;
@@ -179,5 +170,4 @@ public:
AnimatedSprite();
};
-
#endif // ANIMATED_SPRITE_H
diff --git a/scene/2d/area_2d.cpp b/scene/2d/area_2d.cpp
index 55c7716b6b..61e8ee16a2 100644
--- a/scene/2d/area_2d.cpp
+++ b/scene/2d/area_2d.cpp
@@ -31,108 +31,101 @@
#include "servers/physics_2d_server.h"
void Area2D::set_space_override_mode(SpaceOverride p_mode) {
- space_override=p_mode;
- Physics2DServer::get_singleton()->area_set_space_override_mode(get_rid(),Physics2DServer::AreaSpaceOverrideMode(p_mode));
-
-
+ space_override = p_mode;
+ Physics2DServer::get_singleton()->area_set_space_override_mode(get_rid(), Physics2DServer::AreaSpaceOverrideMode(p_mode));
}
-Area2D::SpaceOverride Area2D::get_space_override_mode() const{
+Area2D::SpaceOverride Area2D::get_space_override_mode() const {
return space_override;
}
-void Area2D::set_gravity_is_point(bool p_enabled){
-
- gravity_is_point=p_enabled;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT,p_enabled);
+void Area2D::set_gravity_is_point(bool p_enabled) {
+ gravity_is_point = p_enabled;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT, p_enabled);
}
-bool Area2D::is_gravity_a_point() const{
+bool Area2D::is_gravity_a_point() const {
return gravity_is_point;
}
-void Area2D::set_gravity_distance_scale(real_t p_scale){
-
- gravity_distance_scale=p_scale;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE,p_scale);
+void Area2D::set_gravity_distance_scale(real_t p_scale) {
+ gravity_distance_scale = p_scale;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale);
}
-real_t Area2D::get_gravity_distance_scale() const{
+real_t Area2D::get_gravity_distance_scale() const {
return gravity_distance_scale;
}
-void Area2D::set_gravity_vector(const Vector2& p_vec){
-
- gravity_vec=p_vec;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,p_vec);
+void Area2D::set_gravity_vector(const Vector2 &p_vec) {
+ gravity_vec = p_vec;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY_VECTOR, p_vec);
}
-Vector2 Area2D::get_gravity_vector() const{
+Vector2 Area2D::get_gravity_vector() const {
return gravity_vec;
}
-void Area2D::set_gravity(real_t p_gravity){
+void Area2D::set_gravity(real_t p_gravity) {
- gravity=p_gravity;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_GRAVITY,p_gravity);
+ gravity = p_gravity;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_GRAVITY, p_gravity);
}
-real_t Area2D::get_gravity() const{
+real_t Area2D::get_gravity() const {
return gravity;
}
-void Area2D::set_linear_damp(real_t p_linear_damp){
+void Area2D::set_linear_damp(real_t p_linear_damp) {
- linear_damp=p_linear_damp;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_LINEAR_DAMP,p_linear_damp);
+ linear_damp = p_linear_damp;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_LINEAR_DAMP, p_linear_damp);
}
-real_t Area2D::get_linear_damp() const{
+real_t Area2D::get_linear_damp() const {
return linear_damp;
}
-void Area2D::set_angular_damp(real_t p_angular_damp){
+void Area2D::set_angular_damp(real_t p_angular_damp) {
- angular_damp=p_angular_damp;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_ANGULAR_DAMP,p_angular_damp);
+ angular_damp = p_angular_damp;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_ANGULAR_DAMP, p_angular_damp);
}
-real_t Area2D::get_angular_damp() const{
+real_t Area2D::get_angular_damp() const {
return angular_damp;
}
-void Area2D::set_priority(real_t p_priority){
+void Area2D::set_priority(real_t p_priority) {
- priority=p_priority;
- Physics2DServer::get_singleton()->area_set_param(get_rid(),Physics2DServer::AREA_PARAM_PRIORITY,p_priority);
+ priority = p_priority;
+ Physics2DServer::get_singleton()->area_set_param(get_rid(), Physics2DServer::AREA_PARAM_PRIORITY, p_priority);
}
-real_t Area2D::get_priority() const{
+real_t Area2D::get_priority() const {
return priority;
}
-
void Area2D::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_tree);
- E->get().in_tree=true;
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = true;
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
-
}
void Area2D::_body_exit_tree(ObjectID p_id) {
@@ -140,54 +133,51 @@ void Area2D::_body_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_tree);
- E->get().in_tree=false;
- emit_signal(SceneStringNames::get_singleton()->body_exited,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = false;
+ emit_signal(SceneStringNames::get_singleton()->body_exited, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
-
}
-void Area2D::_body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape) {
+void Area2D::_body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape) {
- bool body_in = p_status==Physics2DServer::AREA_BODY_ADDED;
- ObjectID objid=p_instance;
+ bool body_in = p_status == Physics2DServer::AREA_BODY_ADDED;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,BodyState>::Element *E=body_map.find(objid);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(objid);
ERR_FAIL_COND(!body_in && !E);
- locked=true;
+ locked = true;
if (body_in) {
if (!E) {
- E = body_map.insert(objid,BodyState());
- E->get().rc=0;
- E->get().in_tree=node && node->is_inside_tree();
+ E = body_map.insert(objid, BodyState());
+ E->get().rc = 0;
+ E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
}
}
-
}
E->get().rc++;
if (node)
- E->get().shapes.insert(ShapePair(p_body_shape,p_area_shape));
-
+ E->get().shapes.insert(ShapePair(p_body_shape, p_area_shape));
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_area_shape);
}
} else {
@@ -195,56 +185,48 @@ void Area2D::_body_inout(int p_status,const RID& p_body, int p_instance, int p_b
E->get().rc--;
if (node)
- E->get().shapes.erase(ShapePair(p_body_shape,p_area_shape));
+ E->get().shapes.erase(ShapePair(p_body_shape, p_area_shape));
- bool eraseit=false;
+ bool eraseit = false;
- if (E->get().rc==0) {
+ if (E->get().rc == 0) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
if (E->get().in_tree)
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
-
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
}
- eraseit=true;
-
+ eraseit = true;
}
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_area_shape);
}
if (eraseit)
body_map.erase(E);
-
}
- locked=false;
-
-
+ locked = false;
}
-
-
void Area2D::_area_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,AreaState>::Element *E=area_map.find(p_id);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_tree);
- E->get().in_tree=true;
- emit_signal(SceneStringNames::get_singleton()->area_entered,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = true;
+ emit_signal(SceneStringNames::get_singleton()->area_entered, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_entered,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_entered, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
-
}
void Area2D::_area_exit_tree(ObjectID p_id) {
@@ -252,54 +234,51 @@ void Area2D::_area_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,AreaState>::Element *E=area_map.find(p_id);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_tree);
- E->get().in_tree=false;
- emit_signal(SceneStringNames::get_singleton()->area_exited,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = false;
+ emit_signal(SceneStringNames::get_singleton()->area_exited, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
-
}
-void Area2D::_area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape) {
+void Area2D::_area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape) {
- bool area_in = p_status==Physics2DServer::AREA_BODY_ADDED;
- ObjectID objid=p_instance;
+ bool area_in = p_status == Physics2DServer::AREA_BODY_ADDED;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,AreaState>::Element *E=area_map.find(objid);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(objid);
ERR_FAIL_COND(!area_in && !E);
- locked=true;
+ locked = true;
if (area_in) {
if (!E) {
- E = area_map.insert(objid,AreaState());
- E->get().rc=0;
- E->get().in_tree=node && node->is_inside_tree();
+ E = area_map.insert(objid, AreaState());
+ E->get().rc = 0;
+ E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree, make_binds(objid));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->area_entered, node);
}
}
-
}
E->get().rc++;
if (node)
- E->get().shapes.insert(AreaShapePair(p_area_shape,p_self_shape));
-
+ E->get().shapes.insert(AreaShapePair(p_area_shape, p_self_shape));
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_entered,objid,node,p_area_shape,p_self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_entered, objid, node, p_area_shape, p_self_shape);
}
} else {
@@ -307,39 +286,32 @@ void Area2D::_area_inout(int p_status,const RID& p_area, int p_instance, int p_a
E->get().rc--;
if (node)
- E->get().shapes.erase(AreaShapePair(p_area_shape,p_self_shape));
+ E->get().shapes.erase(AreaShapePair(p_area_shape, p_self_shape));
- bool eraseit=false;
+ bool eraseit = false;
- if (E->get().rc==0) {
+ if (E->get().rc == 0) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree);
if (E->get().in_tree)
- emit_signal(SceneStringNames::get_singleton()->area_exited,obj);
-
+ emit_signal(SceneStringNames::get_singleton()->area_exited, obj);
}
- eraseit=true;
-
+ eraseit = true;
}
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,objid,obj,p_area_shape,p_self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, objid, obj, p_area_shape, p_self_shape);
}
if (eraseit)
area_map.erase(E);
-
}
- locked=false;
-
-
+ locked = false;
}
-
-
void Area2D::_clear_monitoring() {
if (locked) {
@@ -348,39 +320,38 @@ void Area2D::_clear_monitoring() {
ERR_FAIL_COND(locked);
{
- Map<ObjectID,BodyState> bmcopy = body_map;
+ Map<ObjectID, BodyState> bmcopy = body_map;
body_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID,BodyState>::Element *E=bmcopy.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = bmcopy.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_CONTINUE(!node);
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
if (!E->get().in_tree)
continue;
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,E->key(),node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->key(), node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
}
-
}
{
- Map<ObjectID,AreaState> bmcopy = area_map;
+ Map<ObjectID, AreaState> bmcopy = area_map;
area_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID,AreaState>::Element *E=bmcopy.front();E;E=E->next()) {
+ for (Map<ObjectID, AreaState>::Element *E = bmcopy.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
Node *node = obj ? obj->cast_to<Node>() : NULL;
@@ -389,58 +360,53 @@ void Area2D::_clear_monitoring() {
continue;
//ERR_CONTINUE(!node);
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree);
if (!E->get().in_tree)
continue;
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,E->key(),node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E->key(), node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
- emit_signal(SceneStringNames::get_singleton()->area_exited,obj);
+ emit_signal(SceneStringNames::get_singleton()->area_exited, obj);
}
}
-
}
void Area2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_EXIT_TREE: {
_clear_monitoring();
} break;
}
-
}
-
void Area2D::set_monitoring(bool p_enable) {
-
- if (p_enable==monitoring)
+ if (p_enable == monitoring)
return;
if (locked) {
ERR_EXPLAIN("Function blocked during in/out signal. Use call_deferred(\"set_enable_monitoring\",true/false)");
}
ERR_FAIL_COND(locked);
- monitoring=p_enable;
+ monitoring = p_enable;
if (monitoring) {
- Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_body_inout);
- Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_area_inout);
+ Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_body_inout);
+ Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_area_inout);
} else {
- Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(),NULL,StringName());
- Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(),NULL,StringName());
+ Physics2DServer::get_singleton()->area_set_monitor_callback(get_rid(), NULL, StringName());
+ Physics2DServer::get_singleton()->area_set_area_monitor_callback(get_rid(), NULL, StringName());
_clear_monitoring();
-
}
}
@@ -456,12 +422,12 @@ void Area2D::set_monitorable(bool p_enable) {
}
ERR_FAIL_COND(locked);
- if (p_enable==monitorable)
+ if (p_enable == monitorable)
return;
- monitorable=p_enable;
+ monitorable = p_enable;
- Physics2DServer::get_singleton()->area_set_monitorable(get_rid(),monitorable);
+ Physics2DServer::get_singleton()->area_set_monitorable(get_rid(), monitorable);
}
bool Area2D::is_monitorable() const {
@@ -471,18 +437,17 @@ bool Area2D::is_monitorable() const {
Array Area2D::get_overlapping_bodies() const {
- ERR_FAIL_COND_V(!monitoring,Array());
+ ERR_FAIL_COND_V(!monitoring, Array());
Array ret;
ret.resize(body_map.size());
- int idx=0;
- for (const Map<ObjectID,BodyState>::Element *E=body_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, BodyState>::Element *E = body_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
@@ -490,49 +455,44 @@ Array Area2D::get_overlapping_bodies() const {
Array Area2D::get_overlapping_areas() const {
- ERR_FAIL_COND_V(!monitoring,Array());
+ ERR_FAIL_COND_V(!monitoring, Array());
Array ret;
ret.resize(area_map.size());
- int idx=0;
- for (const Map<ObjectID,AreaState>::Element *E=area_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, AreaState>::Element *E = area_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
}
-bool Area2D::overlaps_area(Node* p_area) const {
+bool Area2D::overlaps_area(Node *p_area) const {
- ERR_FAIL_NULL_V(p_area,false);
- const Map<ObjectID,AreaState>::Element *E=area_map.find(p_area->get_instance_ID());
+ ERR_FAIL_NULL_V(p_area, false);
+ const Map<ObjectID, AreaState>::Element *E = area_map.find(p_area->get_instance_ID());
if (!E)
return false;
return E->get().in_tree;
-
-
-
}
-bool Area2D::overlaps_body(Node* p_body) const{
+bool Area2D::overlaps_body(Node *p_body) const {
- ERR_FAIL_NULL_V(p_body,false);
- const Map<ObjectID,BodyState>::Element *E=body_map.find(p_body->get_instance_ID());
+ ERR_FAIL_NULL_V(p_body, false);
+ const Map<ObjectID, BodyState>::Element *E = body_map.find(p_body->get_instance_ID());
if (!E)
return false;
return E->get().in_tree;
-
}
void Area2D::set_collision_mask(uint32_t p_mask) {
- collision_mask=p_mask;
- Physics2DServer::get_singleton()->area_set_collision_mask(get_rid(),p_mask);
+ collision_mask = p_mask;
+ Physics2DServer::get_singleton()->area_set_collision_mask(get_rid(), p_mask);
}
uint32_t Area2D::get_collision_mask() const {
@@ -540,11 +500,10 @@ uint32_t Area2D::get_collision_mask() const {
return collision_mask;
}
-
void Area2D::set_layer_mask(uint32_t p_mask) {
- layer_mask=p_mask;
- Physics2DServer::get_singleton()->area_set_layer_mask(get_rid(),p_mask);
+ layer_mask = p_mask;
+ Physics2DServer::get_singleton()->area_set_layer_mask(get_rid(), p_mask);
}
uint32_t Area2D::get_layer_mask() const {
@@ -556,143 +515,135 @@ void Area2D::set_collision_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_mask(mask);
-
}
-bool Area2D::get_collision_mask_bit(int p_bit) const{
+bool Area2D::get_collision_mask_bit(int p_bit) const {
- return get_collision_mask()&(1<<p_bit);
+ return get_collision_mask() & (1 << p_bit);
}
-
void Area2D::set_layer_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_layer_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_layer_mask(mask);
-
}
-bool Area2D::get_layer_mask_bit(int p_bit) const{
+bool Area2D::get_layer_mask_bit(int p_bit) const {
- return get_layer_mask()&(1<<p_bit);
+ return get_layer_mask() & (1 << p_bit);
}
-
void Area2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_body_enter_tree","id"),&Area2D::_body_enter_tree);
- ClassDB::bind_method(D_METHOD("_body_exit_tree","id"),&Area2D::_body_exit_tree);
-
- ClassDB::bind_method(D_METHOD("_area_enter_tree","id"),&Area2D::_area_enter_tree);
- ClassDB::bind_method(D_METHOD("_area_exit_tree","id"),&Area2D::_area_exit_tree);
-
- ClassDB::bind_method(D_METHOD("set_space_override_mode","enable"),&Area2D::set_space_override_mode);
- ClassDB::bind_method(D_METHOD("get_space_override_mode"),&Area2D::get_space_override_mode);
+ ClassDB::bind_method(D_METHOD("_body_enter_tree", "id"), &Area2D::_body_enter_tree);
+ ClassDB::bind_method(D_METHOD("_body_exit_tree", "id"), &Area2D::_body_exit_tree);
- ClassDB::bind_method(D_METHOD("set_gravity_is_point","enable"),&Area2D::set_gravity_is_point);
- ClassDB::bind_method(D_METHOD("is_gravity_a_point"),&Area2D::is_gravity_a_point);
+ ClassDB::bind_method(D_METHOD("_area_enter_tree", "id"), &Area2D::_area_enter_tree);
+ ClassDB::bind_method(D_METHOD("_area_exit_tree", "id"), &Area2D::_area_exit_tree);
- ClassDB::bind_method(D_METHOD("set_gravity_distance_scale","distance_scale"),&Area2D::set_gravity_distance_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_distance_scale"),&Area2D::get_gravity_distance_scale);
+ ClassDB::bind_method(D_METHOD("set_space_override_mode", "enable"), &Area2D::set_space_override_mode);
+ ClassDB::bind_method(D_METHOD("get_space_override_mode"), &Area2D::get_space_override_mode);
- ClassDB::bind_method(D_METHOD("set_gravity_vector","vector"),&Area2D::set_gravity_vector);
- ClassDB::bind_method(D_METHOD("get_gravity_vector"),&Area2D::get_gravity_vector);
+ ClassDB::bind_method(D_METHOD("set_gravity_is_point", "enable"), &Area2D::set_gravity_is_point);
+ ClassDB::bind_method(D_METHOD("is_gravity_a_point"), &Area2D::is_gravity_a_point);
- ClassDB::bind_method(D_METHOD("set_gravity","gravity"),&Area2D::set_gravity);
- ClassDB::bind_method(D_METHOD("get_gravity"),&Area2D::get_gravity);
+ ClassDB::bind_method(D_METHOD("set_gravity_distance_scale", "distance_scale"), &Area2D::set_gravity_distance_scale);
+ ClassDB::bind_method(D_METHOD("get_gravity_distance_scale"), &Area2D::get_gravity_distance_scale);
- ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&Area2D::set_linear_damp);
- ClassDB::bind_method(D_METHOD("get_linear_damp"),&Area2D::get_linear_damp);
+ ClassDB::bind_method(D_METHOD("set_gravity_vector", "vector"), &Area2D::set_gravity_vector);
+ ClassDB::bind_method(D_METHOD("get_gravity_vector"), &Area2D::get_gravity_vector);
- ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&Area2D::set_angular_damp);
- ClassDB::bind_method(D_METHOD("get_angular_damp"),&Area2D::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &Area2D::set_gravity);
+ ClassDB::bind_method(D_METHOD("get_gravity"), &Area2D::get_gravity);
- ClassDB::bind_method(D_METHOD("set_priority","priority"),&Area2D::set_priority);
- ClassDB::bind_method(D_METHOD("get_priority"),&Area2D::get_priority);
+ ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &Area2D::set_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_linear_damp"), &Area2D::get_linear_damp);
- ClassDB::bind_method(D_METHOD("set_collision_mask","collision_mask"),&Area2D::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"),&Area2D::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &Area2D::set_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_angular_damp"), &Area2D::get_angular_damp);
- ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&Area2D::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&Area2D::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_priority", "priority"), &Area2D::set_priority);
+ ClassDB::bind_method(D_METHOD("get_priority"), &Area2D::get_priority);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&Area2D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&Area2D::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &Area2D::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &Area2D::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_layer_mask_bit","bit","value"),&Area2D::set_layer_mask_bit);
- ClassDB::bind_method(D_METHOD("get_layer_mask_bit","bit"),&Area2D::get_layer_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &Area2D::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &Area2D::get_layer_mask);
- ClassDB::bind_method(D_METHOD("set_monitoring","enable"),&Area2D::set_monitoring);
- ClassDB::bind_method(D_METHOD("is_monitoring"),&Area2D::is_monitoring);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &Area2D::set_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &Area2D::get_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("set_monitorable","enable"),&Area2D::set_monitorable);
- ClassDB::bind_method(D_METHOD("is_monitorable"),&Area2D::is_monitorable);
+ ClassDB::bind_method(D_METHOD("set_layer_mask_bit", "bit", "value"), &Area2D::set_layer_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_layer_mask_bit", "bit"), &Area2D::get_layer_mask_bit);
- ClassDB::bind_method(D_METHOD("get_overlapping_bodies"),&Area2D::get_overlapping_bodies);
- ClassDB::bind_method(D_METHOD("get_overlapping_areas"),&Area2D::get_overlapping_areas);
+ ClassDB::bind_method(D_METHOD("set_monitoring", "enable"), &Area2D::set_monitoring);
+ ClassDB::bind_method(D_METHOD("is_monitoring"), &Area2D::is_monitoring);
- ClassDB::bind_method(D_METHOD("overlaps_body","body"),&Area2D::overlaps_body);
- ClassDB::bind_method(D_METHOD("overlaps_area","area"),&Area2D::overlaps_area);
+ ClassDB::bind_method(D_METHOD("set_monitorable", "enable"), &Area2D::set_monitorable);
+ ClassDB::bind_method(D_METHOD("is_monitorable"), &Area2D::is_monitorable);
- ClassDB::bind_method(D_METHOD("_body_inout"),&Area2D::_body_inout);
- ClassDB::bind_method(D_METHOD("_area_inout"),&Area2D::_area_inout);
+ ClassDB::bind_method(D_METHOD("get_overlapping_bodies"), &Area2D::get_overlapping_bodies);
+ ClassDB::bind_method(D_METHOD("get_overlapping_areas"), &Area2D::get_overlapping_areas);
+ ClassDB::bind_method(D_METHOD("overlaps_body", "body"), &Area2D::overlaps_body);
+ ClassDB::bind_method(D_METHOD("overlaps_area", "area"), &Area2D::overlaps_area);
- ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body",PROPERTY_HINT_RESOURCE_TYPE,"PhysicsBody2D"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"area_shape")));
- ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body",PROPERTY_HINT_RESOURCE_TYPE,"PhysicsBody2D"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"area_shape")));
- ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body",PROPERTY_HINT_RESOURCE_TYPE,"PhysicsBody2D")));
- ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body",PROPERTY_HINT_RESOURCE_TYPE,"PhysicsBody2D")));
+ ClassDB::bind_method(D_METHOD("_body_inout"), &Area2D::_body_inout);
+ ClassDB::bind_method(D_METHOD("_area_inout"), &Area2D::_area_inout);
- ADD_SIGNAL( MethodInfo("area_shape_entered",PropertyInfo(Variant::INT,"area_id"),PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area2D"),PropertyInfo(Variant::INT,"area_shape"),PropertyInfo(Variant::INT,"self_shape")));
- ADD_SIGNAL( MethodInfo("area_shape_exited",PropertyInfo(Variant::INT,"area_id"),PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area2D"),PropertyInfo(Variant::INT,"area_shape"),PropertyInfo(Variant::INT,"self_shape")));
- ADD_SIGNAL( MethodInfo("area_entered",PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area2D")));
- ADD_SIGNAL( MethodInfo("area_exited",PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area2D")));
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsBody2D"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "area_shape")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsBody2D"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "area_shape")));
+ ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsBody2D")));
+ ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsBody2D")));
+ ADD_SIGNAL(MethodInfo("area_shape_entered", PropertyInfo(Variant::INT, "area_id"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area2D"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "self_shape")));
+ ADD_SIGNAL(MethodInfo("area_shape_exited", PropertyInfo(Variant::INT, "area_id"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area2D"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "self_shape")));
+ ADD_SIGNAL(MethodInfo("area_entered", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area2D")));
+ ADD_SIGNAL(MethodInfo("area_exited", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area2D")));
- ADD_PROPERTYNZ( PropertyInfo(Variant::INT,"space_override",PROPERTY_HINT_ENUM,"Disabled,Combine,Combine-Replace,Replace,Replace-Combine"),"set_space_override_mode","get_space_override_mode");
- ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"gravity_point"),"set_gravity_is_point","is_gravity_a_point");
- ADD_PROPERTYNZ( PropertyInfo(Variant::REAL,"gravity_distance_scale", PROPERTY_HINT_RANGE,"0,1024,0.001"),"set_gravity_distance_scale","get_gravity_distance_scale");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"gravity_vec"),"set_gravity_vector","get_gravity_vector");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity",PROPERTY_HINT_RANGE,"-1024,1024,0.001"),"set_gravity","get_gravity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"0,100,0.01"),"set_linear_damp","get_linear_damp");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"0,100,0.01"),"set_angular_damp","get_angular_damp");
- ADD_PROPERTYNZ( PropertyInfo(Variant::INT,"priority",PROPERTY_HINT_RANGE,"0,128,1"),"set_priority","get_priority");
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"monitoring"),"set_monitoring","is_monitoring");
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"monitorable"),"set_monitorable","is_monitorable");
- ADD_GROUP("Collision","collision_");
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"collision_layers",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_layer_mask","get_layer_mask");
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_mask","get_collision_mask");
-
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine"), "set_space_override_mode", "get_space_override_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "gravity_point"), "set_gravity_is_point", "is_gravity_a_point");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "gravity_distance_scale", PROPERTY_HINT_RANGE, "0,1024,0.001"), "set_gravity_distance_scale", "get_gravity_distance_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "gravity_vec"), "set_gravity_vector", "get_gravity_vector");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity", PROPERTY_HINT_RANGE, "-1024,1024,0.001"), "set_gravity", "get_gravity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "0,100,0.01"), "set_linear_damp", "get_linear_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "0,100,0.01"), "set_angular_damp", "get_angular_damp");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,128,1"), "set_priority", "get_priority");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "monitoring"), "set_monitoring", "is_monitoring");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "monitorable"), "set_monitorable", "is_monitorable");
+ ADD_GROUP("Collision", "collision_");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "collision_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_layer_mask", "get_layer_mask");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
}
-Area2D::Area2D() : CollisionObject2D(Physics2DServer::get_singleton()->area_create(),true) {
+Area2D::Area2D()
+ : CollisionObject2D(Physics2DServer::get_singleton()->area_create(), true) {
- space_override=SPACE_OVERRIDE_DISABLED;
+ space_override = SPACE_OVERRIDE_DISABLED;
set_gravity(98);
- set_gravity_vector(Vector2(0,1));
- gravity_is_point=false;
- gravity_distance_scale=0;
- linear_damp=0.1;
- angular_damp=1;
- locked=false;
- priority=0;
- monitoring=false;
- monitorable=false;
- collision_mask=1;
- layer_mask=1;
+ set_gravity_vector(Vector2(0, 1));
+ gravity_is_point = false;
+ gravity_distance_scale = 0;
+ linear_damp = 0.1;
+ angular_damp = 1;
+ locked = false;
+ priority = 0;
+ monitoring = false;
+ monitorable = false;
+ collision_mask = 1;
+ layer_mask = 1;
set_monitoring(true);
set_monitorable(true);
}
Area2D::~Area2D() {
-
-
}
diff --git a/scene/2d/area_2d.h b/scene/2d/area_2d.h
index 68bada707b..2402ff763b 100644
--- a/scene/2d/area_2d.h
+++ b/scene/2d/area_2d.h
@@ -34,9 +34,9 @@
class Area2D : public CollisionObject2D {
- GDCLASS( Area2D, CollisionObject2D );
-public:
+ GDCLASS(Area2D, CollisionObject2D);
+public:
enum SpaceOverride {
SPACE_OVERRIDE_DISABLED,
SPACE_OVERRIDE_COMBINE,
@@ -44,9 +44,8 @@ public:
SPACE_OVERRIDE_REPLACE,
SPACE_OVERRIDE_REPLACE_COMBINE
};
-private:
-
+private:
SpaceOverride space_override;
Vector2 gravity_vec;
real_t gravity;
@@ -61,7 +60,7 @@ private:
bool monitorable;
bool locked;
- void _body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape);
+ void _body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape);
void _body_enter_tree(ObjectID p_id);
void _body_exit_tree(ObjectID p_id);
@@ -70,15 +69,18 @@ private:
int body_shape;
int area_shape;
- bool operator<(const ShapePair& p_sp) const {
- if (body_shape==p_sp.body_shape)
+ bool operator<(const ShapePair &p_sp) const {
+ if (body_shape == p_sp.body_shape)
return area_shape < p_sp.area_shape;
else
return body_shape < p_sp.body_shape;
}
ShapePair() {}
- ShapePair(int p_bs, int p_as) { body_shape=p_bs; area_shape=p_as; }
+ ShapePair(int p_bs, int p_as) {
+ body_shape = p_bs;
+ area_shape = p_as;
+ }
};
struct BodyState {
@@ -88,11 +90,9 @@ private:
VSet<ShapePair> shapes;
};
- Map<ObjectID,BodyState> body_map;
-
+ Map<ObjectID, BodyState> body_map;
-
- void _area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape);
+ void _area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape);
void _area_enter_tree(ObjectID p_id);
void _area_exit_tree(ObjectID p_id);
@@ -101,15 +101,18 @@ private:
int area_shape;
int self_shape;
- bool operator<(const AreaShapePair& p_sp) const {
- if (area_shape==p_sp.area_shape)
+ bool operator<(const AreaShapePair &p_sp) const {
+ if (area_shape == p_sp.area_shape)
return self_shape < p_sp.self_shape;
else
return area_shape < p_sp.area_shape;
}
AreaShapePair() {}
- AreaShapePair(int p_bs, int p_as) { area_shape=p_bs; self_shape=p_as; }
+ AreaShapePair(int p_bs, int p_as) {
+ area_shape = p_bs;
+ self_shape = p_as;
+ }
};
struct AreaState {
@@ -119,16 +122,14 @@ private:
VSet<AreaShapePair> shapes;
};
- Map<ObjectID,AreaState> area_map;
+ Map<ObjectID, AreaState> area_map;
void _clear_monitoring();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_space_override_mode(SpaceOverride p_mode);
SpaceOverride get_space_override_mode() const;
@@ -138,7 +139,7 @@ public:
void set_gravity_distance_scale(real_t p_scale);
real_t get_gravity_distance_scale() const;
- void set_gravity_vector(const Vector2& p_vec);
+ void set_gravity_vector(const Vector2 &p_vec);
Vector2 get_gravity_vector() const;
void set_gravity(real_t p_gravity);
@@ -174,8 +175,8 @@ public:
Array get_overlapping_bodies() const; //function for script
Array get_overlapping_areas() const; //function for script
- bool overlaps_area(Node* p_area) const;
- bool overlaps_body(Node* p_body) const;
+ bool overlaps_area(Node *p_area) const;
+ bool overlaps_body(Node *p_body) const;
Area2D();
~Area2D();
diff --git a/scene/2d/back_buffer_copy.cpp b/scene/2d/back_buffer_copy.cpp
index eaa33fe70a..5a79cee6d0 100644
--- a/scene/2d/back_buffer_copy.cpp
+++ b/scene/2d/back_buffer_copy.cpp
@@ -30,22 +30,21 @@
void BackBufferCopy::_update_copy_mode() {
- switch(copy_mode) {
+ switch (copy_mode) {
case COPY_MODE_DISABLED: {
- VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),false,Rect2());
+ VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), false, Rect2());
} break;
case COPY_MODE_RECT: {
- VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),true,rect);
+ VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), true, rect);
} break;
case COPY_MODE_VIEWPORT: {
- VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(),true,Rect2());
+ VS::get_singleton()->canvas_item_set_copy_to_backbuffer(get_canvas_item(), true, Rect2());
} break;
-
}
}
@@ -54,50 +53,47 @@ Rect2 BackBufferCopy::get_item_rect() const {
return rect;
}
-void BackBufferCopy::set_rect(const Rect2& p_rect) {
+void BackBufferCopy::set_rect(const Rect2 &p_rect) {
- rect=p_rect;
+ rect = p_rect;
_update_copy_mode();
}
-Rect2 BackBufferCopy::get_rect() const{
+Rect2 BackBufferCopy::get_rect() const {
return rect;
}
-void BackBufferCopy::set_copy_mode(CopyMode p_mode){
+void BackBufferCopy::set_copy_mode(CopyMode p_mode) {
- copy_mode=p_mode;
+ copy_mode = p_mode;
_update_copy_mode();
}
-BackBufferCopy::CopyMode BackBufferCopy::get_copy_mode() const{
+BackBufferCopy::CopyMode BackBufferCopy::get_copy_mode() const {
return copy_mode;
}
-
void BackBufferCopy::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_rect","rect"),&BackBufferCopy::set_rect);
- ClassDB::bind_method(D_METHOD("get_rect"),&BackBufferCopy::get_rect);
+ ClassDB::bind_method(D_METHOD("set_rect", "rect"), &BackBufferCopy::set_rect);
+ ClassDB::bind_method(D_METHOD("get_rect"), &BackBufferCopy::get_rect);
- ClassDB::bind_method(D_METHOD("set_copy_mode","copy_mode"),&BackBufferCopy::set_copy_mode);
- ClassDB::bind_method(D_METHOD("get_copy_mode"),&BackBufferCopy::get_copy_mode);
+ ClassDB::bind_method(D_METHOD("set_copy_mode", "copy_mode"), &BackBufferCopy::set_copy_mode);
+ ClassDB::bind_method(D_METHOD("get_copy_mode"), &BackBufferCopy::get_copy_mode);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"copy_mode",PROPERTY_HINT_ENUM,"Disabled,Rect,Viewport"),"set_copy_mode","get_copy_mode");
- ADD_PROPERTY( PropertyInfo(Variant::RECT2,"rect"),"set_rect","get_rect");
-
- BIND_CONSTANT( COPY_MODE_DISABLED );
- BIND_CONSTANT( COPY_MODE_RECT );
- BIND_CONSTANT( COPY_MODE_VIEWPORT );
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "copy_mode", PROPERTY_HINT_ENUM, "Disabled,Rect,Viewport"), "set_copy_mode", "get_copy_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "rect"), "set_rect", "get_rect");
+ BIND_CONSTANT(COPY_MODE_DISABLED);
+ BIND_CONSTANT(COPY_MODE_RECT);
+ BIND_CONSTANT(COPY_MODE_VIEWPORT);
}
-BackBufferCopy::BackBufferCopy(){
+BackBufferCopy::BackBufferCopy() {
- rect=Rect2(-100,-100,200,200);
- copy_mode=COPY_MODE_RECT;
+ rect = Rect2(-100, -100, 200, 200);
+ copy_mode = COPY_MODE_RECT;
_update_copy_mode();
}
-BackBufferCopy::~BackBufferCopy(){
-
+BackBufferCopy::~BackBufferCopy() {
}
diff --git a/scene/2d/back_buffer_copy.h b/scene/2d/back_buffer_copy.h
index 22387f3e9d..b4f83e7db1 100644
--- a/scene/2d/back_buffer_copy.h
+++ b/scene/2d/back_buffer_copy.h
@@ -32,27 +32,26 @@
#include "scene/2d/node_2d.h"
class BackBufferCopy : public Node2D {
- GDCLASS( BackBufferCopy,Node2D);
+ GDCLASS(BackBufferCopy, Node2D);
+
public:
enum CopyMode {
COPY_MODE_DISABLED,
COPY_MODE_RECT,
COPY_MODE_VIEWPORT
};
-private:
+private:
Rect2 rect;
CopyMode copy_mode;
void _update_copy_mode();
protected:
-
static void _bind_methods();
public:
-
- void set_rect(const Rect2& p_rect);
+ void set_rect(const Rect2 &p_rect);
Rect2 get_rect() const;
void set_copy_mode(CopyMode p_mode);
diff --git a/scene/2d/camera_2d.cpp b/scene/2d/camera_2d.cpp
index 9ae2315867..f8388cdcc5 100644
--- a/scene/2d/camera_2d.cpp
+++ b/scene/2d/camera_2d.cpp
@@ -27,14 +27,13 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "camera_2d.h"
+#include "core/math/math_funcs.h"
#include "scene/scene_string_names.h"
#include "servers/visual_server.h"
-#include "core/math/math_funcs.h"
#include <editor/editor_node.h>
void Camera2D::_update_scroll() {
-
if (!is_inside_tree())
return;
@@ -45,16 +44,15 @@ void Camera2D::_update_scroll() {
if (current) {
- ERR_FAIL_COND( custom_viewport && !ObjectDB::get_instance(custom_viewport_id) );
+ ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));
Transform2D xform = get_camera_transform();
if (viewport) {
- viewport->set_canvas_transform( xform );
+ viewport->set_canvas_transform(xform);
}
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_camera_moved",xform);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_camera_moved", xform);
};
-
}
void Camera2D::set_zoom(const Vector2 &p_zoom) {
@@ -70,31 +68,28 @@ Vector2 Camera2D::get_zoom() const {
return zoom;
};
-
-Transform2D Camera2D::get_camera_transform() {
+Transform2D Camera2D::get_camera_transform() {
if (!get_tree())
return Transform2D();
- ERR_FAIL_COND_V( custom_viewport && !ObjectDB::get_instance(custom_viewport_id), Transform2D() );
+ ERR_FAIL_COND_V(custom_viewport && !ObjectDB::get_instance(custom_viewport_id), Transform2D());
Size2 screen_size = viewport->get_visible_rect().size;
-
Point2 new_camera_pos = get_global_transform().get_origin();
Point2 ret_camera_pos;
if (!first) {
-
- if (anchor_mode==ANCHOR_MODE_DRAG_CENTER) {
+ if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) {
if (h_drag_enabled && !get_tree()->is_editor_hint()) {
- camera_pos.x = MIN( camera_pos.x, (new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT]));
- camera_pos.x = MAX( camera_pos.x, (new_camera_pos.x - screen_size.x * 0.5 * drag_margin[MARGIN_LEFT]));
+ camera_pos.x = MIN(camera_pos.x, (new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT]));
+ camera_pos.x = MAX(camera_pos.x, (new_camera_pos.x - screen_size.x * 0.5 * drag_margin[MARGIN_LEFT]));
} else {
- if (h_ofs<0) {
+ if (h_ofs < 0) {
camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs;
} else {
camera_pos.x = new_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs;
@@ -103,33 +98,33 @@ Transform2D Camera2D::get_camera_transform() {
if (v_drag_enabled && !get_tree()->is_editor_hint()) {
- camera_pos.y = MIN( camera_pos.y, (new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM]));
- camera_pos.y = MAX( camera_pos.y, (new_camera_pos.y - screen_size.y * 0.5 * drag_margin[MARGIN_TOP]));
+ camera_pos.y = MIN(camera_pos.y, (new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM]));
+ camera_pos.y = MAX(camera_pos.y, (new_camera_pos.y - screen_size.y * 0.5 * drag_margin[MARGIN_TOP]));
} else {
- if (v_ofs<0) {
+ if (v_ofs < 0) {
camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs;
} else {
camera_pos.y = new_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs;
}
}
- } else if (anchor_mode==ANCHOR_MODE_FIXED_TOP_LEFT){
+ } else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) {
- camera_pos=new_camera_pos;
+ camera_pos = new_camera_pos;
}
- Point2 screen_offset = (anchor_mode==ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());
- Rect2 screen_rect(-screen_offset+camera_pos,screen_size*zoom);
-
- if (offset!=Vector2())
- screen_rect.pos+=offset;
-
+ Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());
+ Rect2 screen_rect(-screen_offset + camera_pos, screen_size * zoom);
+
+ if (offset != Vector2())
+ screen_rect.pos += offset;
+
if (limit_smoothing_enabled) {
if (screen_rect.pos.x < limit[MARGIN_LEFT])
camera_pos.x -= screen_rect.pos.x - limit[MARGIN_LEFT];
-
+
if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT])
camera_pos.x -= screen_rect.pos.x + screen_rect.size.x - limit[MARGIN_RIGHT];
@@ -142,35 +137,31 @@ Transform2D Camera2D::get_camera_transform() {
if (smoothing_enabled && !get_tree()->is_editor_hint()) {
- float c = smoothing*get_fixed_process_delta_time();
- smoothed_camera_pos = ((camera_pos-smoothed_camera_pos)*c)+smoothed_camera_pos;
- ret_camera_pos=smoothed_camera_pos;
+ float c = smoothing * get_fixed_process_delta_time();
+ smoothed_camera_pos = ((camera_pos - smoothed_camera_pos) * c) + smoothed_camera_pos;
+ ret_camera_pos = smoothed_camera_pos;
//camera_pos=camera_pos*(1.0-smoothing)+new_camera_pos*smoothing;
} else {
- ret_camera_pos=smoothed_camera_pos=camera_pos;
-
+ ret_camera_pos = smoothed_camera_pos = camera_pos;
}
-
-
} else {
- ret_camera_pos=smoothed_camera_pos=camera_pos=new_camera_pos;
- first=false;
+ ret_camera_pos = smoothed_camera_pos = camera_pos = new_camera_pos;
+ first = false;
}
-
- Point2 screen_offset = (anchor_mode==ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());
+ Point2 screen_offset = (anchor_mode == ANCHOR_MODE_DRAG_CENTER ? (screen_size * 0.5 * zoom) : Point2());
float angle = get_global_transform().get_rotation();
- if(rotating){
+ if (rotating) {
screen_offset = screen_offset.rotated(angle);
}
- Rect2 screen_rect(-screen_offset+ret_camera_pos,screen_size*zoom);
+ Rect2 screen_rect(-screen_offset + ret_camera_pos, screen_size * zoom);
if (screen_rect.pos.x < limit[MARGIN_LEFT])
screen_rect.pos.x = limit[MARGIN_LEFT];
-
+
if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT])
screen_rect.pos.x = limit[MARGIN_RIGHT] - screen_rect.size.x;
@@ -178,38 +169,34 @@ Transform2D Camera2D::get_camera_transform() {
screen_rect.pos.y = limit[MARGIN_BOTTOM] - screen_rect.size.y;
if (screen_rect.pos.y < limit[MARGIN_TOP])
- screen_rect.pos.y =limit[MARGIN_TOP];
-
-
- if (offset!=Vector2()) {
+ screen_rect.pos.y = limit[MARGIN_TOP];
- screen_rect.pos+=offset;
+ if (offset != Vector2()) {
+
+ screen_rect.pos += offset;
if (screen_rect.pos.x + screen_rect.size.x > limit[MARGIN_RIGHT])
screen_rect.pos.x = limit[MARGIN_RIGHT] - screen_rect.size.x;
if (screen_rect.pos.y + screen_rect.size.y > limit[MARGIN_BOTTOM])
screen_rect.pos.y = limit[MARGIN_BOTTOM] - screen_rect.size.y;
-
if (screen_rect.pos.x < limit[MARGIN_LEFT])
- screen_rect.pos.x=limit[MARGIN_LEFT];
+ screen_rect.pos.x = limit[MARGIN_LEFT];
if (screen_rect.pos.y < limit[MARGIN_TOP])
- screen_rect.pos.y =limit[MARGIN_TOP];
-
+ screen_rect.pos.y = limit[MARGIN_TOP];
}
- camera_screen_center=screen_rect.pos+screen_rect.size*0.5;
+ camera_screen_center = screen_rect.pos + screen_rect.size * 0.5;
Transform2D xform;
- if(rotating){
+ if (rotating) {
xform.set_rotation(angle);
}
xform.scale_basis(zoom);
- xform.set_origin(screen_rect.pos/*.floor()*/);
+ xform.set_origin(screen_rect.pos /*.floor()*/);
-
-/*
+ /*
if (0) {
xform = get_global_transform() * xform;
@@ -219,15 +206,12 @@ Transform2D Camera2D::get_camera_transform() {
}
*/
-
return (xform).affine_inverse();
}
-
-
void Camera2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_FIXED_PROCESS: {
@@ -236,48 +220,45 @@ void Camera2D::_notification(int p_what) {
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
-
if (!is_fixed_processing())
_update_scroll();
} break;
case NOTIFICATION_ENTER_TREE: {
-
if (custom_viewport && ObjectDB::get_instance(custom_viewport_id)) {
- viewport=custom_viewport;
+ viewport = custom_viewport;
} else {
- viewport=get_viewport();
+ viewport = get_viewport();
}
canvas = get_canvas();
RID vp = viewport->get_viewport_rid();
- group_name = "__cameras_"+itos(vp.get_id());
- canvas_group_name ="__cameras_c"+itos(canvas.get_id());
+ group_name = "__cameras_" + itos(vp.get_id());
+ canvas_group_name = "__cameras_c" + itos(canvas.get_id());
add_to_group(group_name);
add_to_group(canvas_group_name);
- if(get_tree()->is_editor_hint()) {
+ if (get_tree()->is_editor_hint()) {
set_fixed_process(false);
}
_update_scroll();
- first=true;
-
+ first = true;
} break;
case NOTIFICATION_EXIT_TREE: {
- if (is_current()) {
+ if (is_current()) {
if (viewport && !(custom_viewport && !ObjectDB::get_instance(custom_viewport_id))) {
- viewport->set_canvas_transform( Transform2D() );
+ viewport->set_canvas_transform(Transform2D());
}
}
remove_from_group(group_name);
remove_from_group(canvas_group_name);
- viewport=NULL;
+ viewport = NULL;
} break;
case NOTIFICATION_DRAW: {
@@ -287,44 +268,43 @@ void Camera2D::_notification(int p_what) {
Color area_axis_color(0.5, 0.42, 0.87, 0.63);
float area_axis_width = 1;
- if(current)
+ if (current)
area_axis_width = 3;
Transform2D inv_camera_transform = get_camera_transform().affine_inverse();
Size2 screen_size = get_viewport_rect().size;
- Vector2 screen_endpoints[4]= {
+ Vector2 screen_endpoints[4] = {
inv_camera_transform.xform(Vector2(0, 0)),
- inv_camera_transform.xform(Vector2(screen_size.width,0)),
+ inv_camera_transform.xform(Vector2(screen_size.width, 0)),
inv_camera_transform.xform(Vector2(screen_size.width, screen_size.height)),
inv_camera_transform.xform(Vector2(0, screen_size.height))
};
Transform2D inv_transform = get_global_transform().affine_inverse(); // undo global space
- for(int i=0;i<4;i++) {
- draw_line(inv_transform.xform(screen_endpoints[i]), inv_transform.xform(screen_endpoints[(i+1)%4]), area_axis_color, area_axis_width);
+ for (int i = 0; i < 4; i++) {
+ draw_line(inv_transform.xform(screen_endpoints[i]), inv_transform.xform(screen_endpoints[(i + 1) % 4]), area_axis_color, area_axis_width);
}
} break;
}
}
-void Camera2D::set_offset(const Vector2& p_offset) {
+void Camera2D::set_offset(const Vector2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
_update_scroll();
-
}
-Vector2 Camera2D::get_offset() const{
+Vector2 Camera2D::get_offset() const {
return offset;
}
-void Camera2D::set_anchor_mode(AnchorMode p_anchor_mode){
+void Camera2D::set_anchor_mode(AnchorMode p_anchor_mode) {
- anchor_mode=p_anchor_mode;
+ anchor_mode = p_anchor_mode;
_update_scroll();
}
@@ -333,9 +313,9 @@ Camera2D::AnchorMode Camera2D::get_anchor_mode() const {
return anchor_mode;
}
-void Camera2D::set_rotating(bool p_rotating){
+void Camera2D::set_rotating(bool p_rotating) {
- rotating=p_rotating;
+ rotating = p_rotating;
_update_scroll();
}
@@ -344,25 +324,23 @@ bool Camera2D::is_rotating() const {
return rotating;
}
-
void Camera2D::_make_current(Object *p_which) {
- if (p_which==this) {
+ if (p_which == this) {
- current=true;
+ current = true;
_update_scroll();
} else {
- current=false;
+ current = false;
}
}
-
void Camera2D::_set_current(bool p_current) {
if (p_current)
make_current();
- current=p_current;
+ current = p_current;
}
bool Camera2D::is_current() const {
@@ -373,33 +351,30 @@ bool Camera2D::is_current() const {
void Camera2D::make_current() {
if (!is_inside_tree()) {
- current=true;
+ current = true;
} else {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_make_current",this);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", this);
}
}
void Camera2D::clear_current() {
- current=false;
+ current = false;
if (is_inside_tree()) {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,group_name,"_make_current",(Object*)(NULL));
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, group_name, "_make_current", (Object *)(NULL));
}
-
}
+void Camera2D::set_limit(Margin p_margin, int p_limit) {
-void Camera2D::set_limit(Margin p_margin,int p_limit) {
-
- ERR_FAIL_INDEX(p_margin,4);
- limit[p_margin]=p_limit;
+ ERR_FAIL_INDEX(p_margin, 4);
+ limit[p_margin] = p_limit;
}
-int Camera2D::get_limit(Margin p_margin) const{
+int Camera2D::get_limit(Margin p_margin) const {
- ERR_FAIL_INDEX_V(p_margin,4,0);
+ ERR_FAIL_INDEX_V(p_margin, 4, 0);
return limit[p_margin];
-
}
void Camera2D::set_limit_smoothing_enabled(bool enable) {
@@ -408,34 +383,30 @@ void Camera2D::set_limit_smoothing_enabled(bool enable) {
_update_scroll();
}
-bool Camera2D::is_limit_smoothing_enabled() const{
+bool Camera2D::is_limit_smoothing_enabled() const {
return limit_smoothing_enabled;
}
-void Camera2D::set_drag_margin(Margin p_margin,float p_drag_margin) {
+void Camera2D::set_drag_margin(Margin p_margin, float p_drag_margin) {
- ERR_FAIL_INDEX(p_margin,4);
- drag_margin[p_margin]=p_drag_margin;
+ ERR_FAIL_INDEX(p_margin, 4);
+ drag_margin[p_margin] = p_drag_margin;
}
-float Camera2D::get_drag_margin(Margin p_margin) const{
+float Camera2D::get_drag_margin(Margin p_margin) const {
- ERR_FAIL_INDEX_V(p_margin,4,0);
+ ERR_FAIL_INDEX_V(p_margin, 4, 0);
return drag_margin[p_margin];
-
}
-
Vector2 Camera2D::get_camera_pos() const {
-
return camera_pos;
}
void Camera2D::force_update_scroll() {
-
_update_scroll();
}
@@ -447,25 +418,25 @@ void Camera2D::reset_smoothing() {
void Camera2D::align() {
- ERR_FAIL_COND( custom_viewport && !ObjectDB::get_instance(custom_viewport_id) );
+ ERR_FAIL_COND(custom_viewport && !ObjectDB::get_instance(custom_viewport_id));
Size2 screen_size = viewport->get_visible_rect().size;
Point2 current_camera_pos = get_global_transform().get_origin();
- if (anchor_mode==ANCHOR_MODE_DRAG_CENTER) {
- if (h_ofs<0) {
+ if (anchor_mode == ANCHOR_MODE_DRAG_CENTER) {
+ if (h_ofs < 0) {
camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_RIGHT] * h_ofs;
} else {
camera_pos.x = current_camera_pos.x + screen_size.x * 0.5 * drag_margin[MARGIN_LEFT] * h_ofs;
}
- if (v_ofs<0) {
+ if (v_ofs < 0) {
camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_TOP] * v_ofs;
} else {
camera_pos.y = current_camera_pos.y + screen_size.y * 0.5 * drag_margin[MARGIN_BOTTOM] * v_ofs;
}
- } else if (anchor_mode==ANCHOR_MODE_FIXED_TOP_LEFT){
+ } else if (anchor_mode == ANCHOR_MODE_FIXED_TOP_LEFT) {
- camera_pos=current_camera_pos;
+ camera_pos = current_camera_pos;
}
_update_scroll();
@@ -473,77 +444,73 @@ void Camera2D::align() {
void Camera2D::set_follow_smoothing(float p_speed) {
- smoothing=p_speed;
- if (smoothing>0 && !(is_inside_tree() && get_tree()->is_editor_hint()))
+ smoothing = p_speed;
+ if (smoothing > 0 && !(is_inside_tree() && get_tree()->is_editor_hint()))
set_fixed_process(true);
else
set_fixed_process(false);
}
-float Camera2D::get_follow_smoothing() const{
+float Camera2D::get_follow_smoothing() const {
return smoothing;
}
Point2 Camera2D::get_camera_screen_center() const {
- return camera_screen_center;
+ return camera_screen_center;
}
-
void Camera2D::set_h_drag_enabled(bool p_enabled) {
- h_drag_enabled=p_enabled;
+ h_drag_enabled = p_enabled;
}
-bool Camera2D::is_h_drag_enabled() const{
+bool Camera2D::is_h_drag_enabled() const {
- return h_drag_enabled;
+ return h_drag_enabled;
}
-void Camera2D::set_v_drag_enabled(bool p_enabled){
+void Camera2D::set_v_drag_enabled(bool p_enabled) {
- v_drag_enabled=p_enabled;
+ v_drag_enabled = p_enabled;
}
-bool Camera2D::is_v_drag_enabled() const{
+bool Camera2D::is_v_drag_enabled() const {
- return v_drag_enabled;
+ return v_drag_enabled;
}
void Camera2D::set_v_offset(float p_offset) {
- v_ofs=p_offset;
+ v_ofs = p_offset;
}
-float Camera2D::get_v_offset() const{
+float Camera2D::get_v_offset() const {
- return v_ofs;
+ return v_ofs;
}
-void Camera2D::set_h_offset(float p_offset){
+void Camera2D::set_h_offset(float p_offset) {
- h_ofs=p_offset;
+ h_ofs = p_offset;
}
-float Camera2D::get_h_offset() const{
+float Camera2D::get_h_offset() const {
- return h_ofs;
+ return h_ofs;
}
-
void Camera2D::_set_old_smoothing(float p_val) {
//compatibility
- if (p_val>0) {
- smoothing_enabled=true;
+ if (p_val > 0) {
+ smoothing_enabled = true;
set_follow_smoothing(p_val);
}
-
}
void Camera2D::set_enable_follow_smoothing(bool p_enabled) {
- smoothing_enabled=p_enabled;
-
+ smoothing_enabled = p_enabled;
}
bool Camera2D::is_follow_smoothing_enabled() const {
@@ -558,161 +525,154 @@ void Camera2D::set_custom_viewport(Node *p_viewport) {
remove_from_group(canvas_group_name);
}
- custom_viewport=p_viewport->cast_to<Viewport>();
+ custom_viewport = p_viewport->cast_to<Viewport>();
if (custom_viewport) {
- custom_viewport_id=custom_viewport->get_instance_ID();
+ custom_viewport_id = custom_viewport->get_instance_ID();
} else {
- custom_viewport_id=0;
+ custom_viewport_id = 0;
}
if (is_inside_tree()) {
if (custom_viewport)
- viewport=custom_viewport;
+ viewport = custom_viewport;
else
- viewport=get_viewport();
+ viewport = get_viewport();
RID vp = viewport->get_viewport_rid();
- group_name = "__cameras_"+itos(vp.get_id());
- canvas_group_name ="__cameras_c"+itos(canvas.get_id());
+ group_name = "__cameras_" + itos(vp.get_id());
+ canvas_group_name = "__cameras_c" + itos(canvas.get_id());
add_to_group(group_name);
add_to_group(canvas_group_name);
}
-
}
-Node* Camera2D::get_custom_viewport() const {
+Node *Camera2D::get_custom_viewport() const {
return custom_viewport;
}
-
void Camera2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&Camera2D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&Camera2D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Camera2D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Camera2D::get_offset);
- ClassDB::bind_method(D_METHOD("set_anchor_mode","anchor_mode"),&Camera2D::set_anchor_mode);
- ClassDB::bind_method(D_METHOD("get_anchor_mode"),&Camera2D::get_anchor_mode);
+ ClassDB::bind_method(D_METHOD("set_anchor_mode", "anchor_mode"), &Camera2D::set_anchor_mode);
+ ClassDB::bind_method(D_METHOD("get_anchor_mode"), &Camera2D::get_anchor_mode);
- ClassDB::bind_method(D_METHOD("set_rotating","rotating"),&Camera2D::set_rotating);
- ClassDB::bind_method(D_METHOD("is_rotating"),&Camera2D::is_rotating);
+ ClassDB::bind_method(D_METHOD("set_rotating", "rotating"), &Camera2D::set_rotating);
+ ClassDB::bind_method(D_METHOD("is_rotating"), &Camera2D::is_rotating);
- ClassDB::bind_method(D_METHOD("make_current"),&Camera2D::make_current);
- ClassDB::bind_method(D_METHOD("clear_current"),&Camera2D::clear_current);
- ClassDB::bind_method(D_METHOD("_make_current"),&Camera2D::_make_current);
+ ClassDB::bind_method(D_METHOD("make_current"), &Camera2D::make_current);
+ ClassDB::bind_method(D_METHOD("clear_current"), &Camera2D::clear_current);
+ ClassDB::bind_method(D_METHOD("_make_current"), &Camera2D::_make_current);
- ClassDB::bind_method(D_METHOD("_update_scroll"),&Camera2D::_update_scroll);
+ ClassDB::bind_method(D_METHOD("_update_scroll"), &Camera2D::_update_scroll);
- ClassDB::bind_method(D_METHOD("_set_current","current"),&Camera2D::_set_current);
- ClassDB::bind_method(D_METHOD("is_current"),&Camera2D::is_current);
+ ClassDB::bind_method(D_METHOD("_set_current", "current"), &Camera2D::_set_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &Camera2D::is_current);
- ClassDB::bind_method(D_METHOD("set_limit","margin","limit"),&Camera2D::set_limit);
- ClassDB::bind_method(D_METHOD("get_limit","margin"),&Camera2D::get_limit);
+ ClassDB::bind_method(D_METHOD("set_limit", "margin", "limit"), &Camera2D::set_limit);
+ ClassDB::bind_method(D_METHOD("get_limit", "margin"), &Camera2D::get_limit);
- ClassDB::bind_method(D_METHOD("set_limit_smoothing_enabled","limit_smoothing_enabled"),&Camera2D::set_limit_smoothing_enabled);
- ClassDB::bind_method(D_METHOD("is_limit_smoothing_enabled"),&Camera2D::is_limit_smoothing_enabled);
+ ClassDB::bind_method(D_METHOD("set_limit_smoothing_enabled", "limit_smoothing_enabled"), &Camera2D::set_limit_smoothing_enabled);
+ ClassDB::bind_method(D_METHOD("is_limit_smoothing_enabled"), &Camera2D::is_limit_smoothing_enabled);
- ClassDB::bind_method(D_METHOD("set_v_drag_enabled","enabled"),&Camera2D::set_v_drag_enabled);
- ClassDB::bind_method(D_METHOD("is_v_drag_enabled"),&Camera2D::is_v_drag_enabled);
+ ClassDB::bind_method(D_METHOD("set_v_drag_enabled", "enabled"), &Camera2D::set_v_drag_enabled);
+ ClassDB::bind_method(D_METHOD("is_v_drag_enabled"), &Camera2D::is_v_drag_enabled);
- ClassDB::bind_method(D_METHOD("set_h_drag_enabled","enabled"),&Camera2D::set_h_drag_enabled);
- ClassDB::bind_method(D_METHOD("is_h_drag_enabled"),&Camera2D::is_h_drag_enabled);
+ ClassDB::bind_method(D_METHOD("set_h_drag_enabled", "enabled"), &Camera2D::set_h_drag_enabled);
+ ClassDB::bind_method(D_METHOD("is_h_drag_enabled"), &Camera2D::is_h_drag_enabled);
- ClassDB::bind_method(D_METHOD("set_v_offset","ofs"),&Camera2D::set_v_offset);
- ClassDB::bind_method(D_METHOD("get_v_offset"),&Camera2D::get_v_offset);
+ ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera2D::set_v_offset);
+ ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera2D::get_v_offset);
- ClassDB::bind_method(D_METHOD("set_h_offset","ofs"),&Camera2D::set_h_offset);
- ClassDB::bind_method(D_METHOD("get_h_offset"),&Camera2D::get_h_offset);
+ ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera2D::set_h_offset);
+ ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera2D::get_h_offset);
- ClassDB::bind_method(D_METHOD("set_drag_margin","margin","drag_margin"),&Camera2D::set_drag_margin);
- ClassDB::bind_method(D_METHOD("get_drag_margin","margin"),&Camera2D::get_drag_margin);
+ ClassDB::bind_method(D_METHOD("set_drag_margin", "margin", "drag_margin"), &Camera2D::set_drag_margin);
+ ClassDB::bind_method(D_METHOD("get_drag_margin", "margin"), &Camera2D::get_drag_margin);
- ClassDB::bind_method(D_METHOD("get_camera_pos"),&Camera2D::get_camera_pos);
- ClassDB::bind_method(D_METHOD("get_camera_screen_center"),&Camera2D::get_camera_screen_center);
+ ClassDB::bind_method(D_METHOD("get_camera_pos"), &Camera2D::get_camera_pos);
+ ClassDB::bind_method(D_METHOD("get_camera_screen_center"), &Camera2D::get_camera_screen_center);
- ClassDB::bind_method(D_METHOD("set_zoom","zoom"),&Camera2D::set_zoom);
- ClassDB::bind_method(D_METHOD("get_zoom"),&Camera2D::get_zoom);
+ ClassDB::bind_method(D_METHOD("set_zoom", "zoom"), &Camera2D::set_zoom);
+ ClassDB::bind_method(D_METHOD("get_zoom"), &Camera2D::get_zoom);
- ClassDB::bind_method(D_METHOD("set_custom_viewport","viewport:Viewport"),&Camera2D::set_custom_viewport);
- ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"),&Camera2D::get_custom_viewport);
+ ClassDB::bind_method(D_METHOD("set_custom_viewport", "viewport:Viewport"), &Camera2D::set_custom_viewport);
+ ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"), &Camera2D::get_custom_viewport);
- ClassDB::bind_method(D_METHOD("set_follow_smoothing","follow_smoothing"),&Camera2D::set_follow_smoothing);
- ClassDB::bind_method(D_METHOD("get_follow_smoothing"),&Camera2D::get_follow_smoothing);
+ ClassDB::bind_method(D_METHOD("set_follow_smoothing", "follow_smoothing"), &Camera2D::set_follow_smoothing);
+ ClassDB::bind_method(D_METHOD("get_follow_smoothing"), &Camera2D::get_follow_smoothing);
- ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing","follow_smoothing"),&Camera2D::set_enable_follow_smoothing);
- ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"),&Camera2D::is_follow_smoothing_enabled);
+ ClassDB::bind_method(D_METHOD("set_enable_follow_smoothing", "follow_smoothing"), &Camera2D::set_enable_follow_smoothing);
+ ClassDB::bind_method(D_METHOD("is_follow_smoothing_enabled"), &Camera2D::is_follow_smoothing_enabled);
- ClassDB::bind_method(D_METHOD("force_update_scroll"),&Camera2D::force_update_scroll);
- ClassDB::bind_method(D_METHOD("reset_smoothing"),&Camera2D::reset_smoothing);
- ClassDB::bind_method(D_METHOD("align"),&Camera2D::align);
+ ClassDB::bind_method(D_METHOD("force_update_scroll"), &Camera2D::force_update_scroll);
+ ClassDB::bind_method(D_METHOD("reset_smoothing"), &Camera2D::reset_smoothing);
+ ClassDB::bind_method(D_METHOD("align"), &Camera2D::align);
- ClassDB::bind_method(D_METHOD("_set_old_smoothing","follow_smoothing"),&Camera2D::_set_old_smoothing);
+ ClassDB::bind_method(D_METHOD("_set_old_smoothing", "follow_smoothing"), &Camera2D::_set_old_smoothing);
- ADD_PROPERTYNZ( PropertyInfo(Variant::VECTOR2,"offset"),"set_offset","get_offset");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"anchor_mode",PROPERTY_HINT_ENUM,"Fixed TopLeft,Drag Center"),"set_anchor_mode","get_anchor_mode");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"rotating"),"set_rotating","is_rotating");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"current"),"_set_current","is_current");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"zoom"),"set_zoom","get_zoom") ;
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "anchor_mode", PROPERTY_HINT_ENUM, "Fixed TopLeft,Drag Center"), "set_anchor_mode", "get_anchor_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rotating"), "set_rotating", "is_rotating");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "current"), "_set_current", "is_current");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "zoom"), "set_zoom", "get_zoom");
- ADD_GROUP("Limit","limit_");
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_left"),"set_limit","get_limit",MARGIN_LEFT);
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_top"),"set_limit","get_limit",MARGIN_TOP);
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_right"),"set_limit","get_limit",MARGIN_RIGHT);
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"limit_bottom"),"set_limit","get_limit",MARGIN_BOTTOM);
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"limit_smoothed"),"set_limit_smoothing_enabled","is_limit_smoothing_enabled") ;
+ ADD_GROUP("Limit", "limit_");
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_left"), "set_limit", "get_limit", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_top"), "set_limit", "get_limit", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_right"), "set_limit", "get_limit", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "limit_bottom"), "set_limit", "get_limit", MARGIN_BOTTOM);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "limit_smoothed"), "set_limit_smoothing_enabled", "is_limit_smoothing_enabled");
- ADD_GROUP("Draw Margin","draw_margin_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"drag_margin_h_enabled"),"set_h_drag_enabled","is_h_drag_enabled") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"drag_margin_v_enabled"),"set_v_drag_enabled","is_v_drag_enabled") ;
+ ADD_GROUP("Draw Margin", "draw_margin_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_h_enabled"), "set_h_drag_enabled", "is_h_drag_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "drag_margin_v_enabled"), "set_v_drag_enabled", "is_v_drag_enabled");
- ADD_GROUP("Smoothing","smoothing_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"smoothing_enabled"),"set_enable_follow_smoothing","is_follow_smoothing_enabled") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"smoothing_speed"),"set_follow_smoothing","get_follow_smoothing") ;
+ ADD_GROUP("Smoothing", "smoothing_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smoothing_enabled"), "set_enable_follow_smoothing", "is_follow_smoothing_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "smoothing_speed"), "set_follow_smoothing", "get_follow_smoothing");
- ADD_GROUP("Drag Margin","drag_margin_");
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_left",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_LEFT);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_top",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_TOP);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_right",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_RIGHT);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"drag_margin_bottom",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drag_margin","get_drag_margin",MARGIN_BOTTOM);
-
-
- BIND_CONSTANT( ANCHOR_MODE_DRAG_CENTER );
- BIND_CONSTANT( ANCHOR_MODE_FIXED_TOP_LEFT );
+ ADD_GROUP("Drag Margin", "drag_margin_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_left", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_top", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_right", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "drag_margin_bottom", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drag_margin", "get_drag_margin", MARGIN_BOTTOM);
+ BIND_CONSTANT(ANCHOR_MODE_DRAG_CENTER);
+ BIND_CONSTANT(ANCHOR_MODE_FIXED_TOP_LEFT);
}
Camera2D::Camera2D() {
-
-
- anchor_mode=ANCHOR_MODE_DRAG_CENTER;
- rotating=false;
- current=false;
- limit[MARGIN_LEFT]=-10000000;
- limit[MARGIN_TOP]=-10000000;
- limit[MARGIN_RIGHT]=10000000;
- limit[MARGIN_BOTTOM]=10000000;
-
- drag_margin[MARGIN_LEFT]=0.2;
- drag_margin[MARGIN_TOP]=0.2;
- drag_margin[MARGIN_RIGHT]=0.2;
- drag_margin[MARGIN_BOTTOM]=0.2;
- camera_pos=Vector2();
- first=true;
- smoothing_enabled=false;
- limit_smoothing_enabled=false;
- custom_viewport=NULL;
- custom_viewport_id=0;
-
- smoothing=5.0;
+ anchor_mode = ANCHOR_MODE_DRAG_CENTER;
+ rotating = false;
+ current = false;
+ limit[MARGIN_LEFT] = -10000000;
+ limit[MARGIN_TOP] = -10000000;
+ limit[MARGIN_RIGHT] = 10000000;
+ limit[MARGIN_BOTTOM] = 10000000;
+
+ drag_margin[MARGIN_LEFT] = 0.2;
+ drag_margin[MARGIN_TOP] = 0.2;
+ drag_margin[MARGIN_RIGHT] = 0.2;
+ drag_margin[MARGIN_BOTTOM] = 0.2;
+ camera_pos = Vector2();
+ first = true;
+ smoothing_enabled = false;
+ limit_smoothing_enabled = false;
+ custom_viewport = NULL;
+ custom_viewport_id = 0;
+
+ smoothing = 5.0;
zoom = Vector2(1, 1);
- h_drag_enabled=true;
- v_drag_enabled=true;
- h_ofs=0;
- v_ofs=0;
+ h_drag_enabled = true;
+ v_drag_enabled = true;
+ h_ofs = 0;
+ v_ofs = 0;
set_notify_transform(true);
-
}
diff --git a/scene/2d/camera_2d.h b/scene/2d/camera_2d.h
index 85d90b225a..44cdb5cd99 100644
--- a/scene/2d/camera_2d.h
+++ b/scene/2d/camera_2d.h
@@ -32,12 +32,11 @@
#include "scene/2d/node_2d.h"
#include "scene/main/viewport.h"
-
class Camera2D : public Node2D {
- GDCLASS( Camera2D, Node2D );
-public:
+ GDCLASS(Camera2D, Node2D);
+public:
enum AnchorMode {
ANCHOR_MODE_FIXED_TOP_LEFT,
ANCHOR_MODE_DRAG_CENTER
@@ -78,14 +77,14 @@ protected:
void _set_current(bool p_current);
void _set_old_smoothing(float p_enable);
-protected:
+protected:
virtual Transform2D get_camera_transform();
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_offset(const Vector2& p_offset);
+public:
+ void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
void set_anchor_mode(AnchorMode p_anchor_mode);
@@ -94,7 +93,7 @@ public:
void set_rotating(bool p_rotating);
bool is_rotating() const;
- void set_limit(Margin p_margin,int p_limit);
+ void set_limit(Margin p_margin, int p_limit);
int get_limit(Margin p_margin) const;
void set_limit_smoothing_enabled(bool enable);
@@ -106,7 +105,7 @@ public:
void set_v_drag_enabled(bool p_enabled);
bool is_v_drag_enabled() const;
- void set_drag_margin(Margin p_margin,float p_drag_margin);
+ void set_drag_margin(Margin p_margin, float p_drag_margin);
float get_drag_margin(Margin p_margin) const;
void set_v_offset(float p_offset);
@@ -125,13 +124,13 @@ public:
void clear_current();
bool is_current() const;
- void set_zoom(const Vector2& p_zoom);
+ void set_zoom(const Vector2 &p_zoom);
Vector2 get_zoom() const;
Point2 get_camera_screen_center() const;
void set_custom_viewport(Node *p_viewport);
- Node* get_custom_viewport() const;
+ Node *get_custom_viewport() const;
Vector2 get_camera_pos() const;
void force_update_scroll();
diff --git a/scene/2d/canvas_item.cpp b/scene/2d/canvas_item.cpp
index 4f7acf7f97..b52dd8d660 100644
--- a/scene/2d/canvas_item.cpp
+++ b/scene/2d/canvas_item.cpp
@@ -27,35 +27,34 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "canvas_item.h"
-#include "servers/visual_server.h"
-#include "scene/main/viewport.h"
-#include "scene/main/canvas_layer.h"
#include "message_queue.h"
-#include "scene/scene_string_names.h"
+#include "os/input.h"
+#include "scene/main/canvas_layer.h"
+#include "scene/main/viewport.h"
#include "scene/resources/font.h"
-#include "scene/resources/texture.h"
#include "scene/resources/style_box.h"
-#include "os/input.h"
+#include "scene/resources/texture.h"
+#include "scene/scene_string_names.h"
+#include "servers/visual_server.h"
-bool CanvasItemMaterial::_set(const StringName& p_name, const Variant& p_value) {
+bool CanvasItemMaterial::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name==SceneStringNames::get_singleton()->shader_shader) {
+ if (p_name == SceneStringNames::get_singleton()->shader_shader) {
set_shader(p_value);
return true;
} else {
if (shader.is_valid()) {
-
StringName pr = shader->remap_param(p_name);
if (!pr) {
String n = p_name;
- if (n.find("param/")==0) { //backwards compatibility
- pr = n.substr(6,n.length());
+ if (n.find("param/") == 0) { //backwards compatibility
+ pr = n.substr(6, n.length());
}
}
if (pr) {
- VisualServer::get_singleton()->material_set_param(_get_material(),pr,p_value);
+ VisualServer::get_singleton()->material_set_param(_get_material(), pr, p_value);
return true;
}
}
@@ -64,12 +63,11 @@ bool CanvasItemMaterial::_set(const StringName& p_name, const Variant& p_value)
return false;
}
-bool CanvasItemMaterial::_get(const StringName& p_name,Variant &r_ret) const {
+bool CanvasItemMaterial::_get(const StringName &p_name, Variant &r_ret) const {
+ if (p_name == SceneStringNames::get_singleton()->shader_shader) {
- if (p_name==SceneStringNames::get_singleton()->shader_shader) {
-
- r_ret=get_shader();
+ r_ret = get_shader();
return true;
} else {
@@ -78,128 +76,103 @@ bool CanvasItemMaterial::_get(const StringName& p_name,Variant &r_ret) const {
StringName pr = shader->remap_param(p_name);
if (pr) {
- r_ret=VisualServer::get_singleton()->material_get_param(_get_material(),pr);
+ r_ret = VisualServer::get_singleton()->material_get_param(_get_material(), pr);
return true;
}
}
-
}
-
return false;
}
+void CanvasItemMaterial::_get_property_list(List<PropertyInfo> *p_list) const {
-void CanvasItemMaterial::_get_property_list( List<PropertyInfo> *p_list) const {
-
- p_list->push_back( PropertyInfo( Variant::OBJECT, "shader/shader", PROPERTY_HINT_RESOURCE_TYPE,"CanvasItemShader,CanvasItemShaderGraph" ) );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "shader/shader", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemShader,CanvasItemShaderGraph"));
if (!shader.is_null()) {
shader->get_param_list(p_list);
}
-
}
-void CanvasItemMaterial::set_shader(const Ref<Shader>& p_shader) {
+void CanvasItemMaterial::set_shader(const Ref<Shader> &p_shader) {
- ERR_FAIL_COND(p_shader.is_valid() && p_shader->get_mode()!=Shader::MODE_CANVAS_ITEM);
+ ERR_FAIL_COND(p_shader.is_valid() && p_shader->get_mode() != Shader::MODE_CANVAS_ITEM);
- shader=p_shader;
+ shader = p_shader;
RID rid;
if (shader.is_valid())
- rid=shader->get_rid();
+ rid = shader->get_rid();
- VS::get_singleton()->material_set_shader(_get_material(),rid);
+ VS::get_singleton()->material_set_shader(_get_material(), rid);
_change_notify(); //properties for shader exposed
emit_changed();
}
-Ref<Shader> CanvasItemMaterial::get_shader() const{
+Ref<Shader> CanvasItemMaterial::get_shader() const {
return shader;
}
-void CanvasItemMaterial::set_shader_param(const StringName& p_param,const Variant& p_value){
+void CanvasItemMaterial::set_shader_param(const StringName &p_param, const Variant &p_value) {
- VS::get_singleton()->material_set_param(_get_material(),p_param,p_value);
+ VS::get_singleton()->material_set_param(_get_material(), p_param, p_value);
}
-Variant CanvasItemMaterial::get_shader_param(const StringName& p_param) const{
+Variant CanvasItemMaterial::get_shader_param(const StringName &p_param) const {
- return VS::get_singleton()->material_get_param(_get_material(),p_param);
+ return VS::get_singleton()->material_get_param(_get_material(), p_param);
}
-
-
void CanvasItemMaterial::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shader","shader:Shader"),&CanvasItemMaterial::set_shader);
- ClassDB::bind_method(D_METHOD("get_shader:Shader"),&CanvasItemMaterial::get_shader);
- ClassDB::bind_method(D_METHOD("set_shader_param","param","value"),&CanvasItemMaterial::set_shader_param);
- ClassDB::bind_method(D_METHOD("get_shader_param","param"),&CanvasItemMaterial::get_shader_param);
-
-
-
+ ClassDB::bind_method(D_METHOD("set_shader", "shader:Shader"), &CanvasItemMaterial::set_shader);
+ ClassDB::bind_method(D_METHOD("get_shader:Shader"), &CanvasItemMaterial::get_shader);
+ ClassDB::bind_method(D_METHOD("set_shader_param", "param", "value"), &CanvasItemMaterial::set_shader_param);
+ ClassDB::bind_method(D_METHOD("get_shader_param", "param"), &CanvasItemMaterial::get_shader_param);
}
-void CanvasItemMaterial::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
+void CanvasItemMaterial::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
String f = p_function.operator String();
- if ((f=="get_shader_param" || f=="set_shader_param") && p_idx==0) {
+ if ((f == "get_shader_param" || f == "set_shader_param") && p_idx == 0) {
if (shader.is_valid()) {
List<PropertyInfo> pl;
shader->get_param_list(&pl);
- for (List<PropertyInfo>::Element *E=pl.front();E;E=E->next()) {
- r_options->push_back("\""+E->get().name.replace_first("shader_param/","")+"\"");
+ for (List<PropertyInfo>::Element *E = pl.front(); E; E = E->next()) {
+ r_options->push_back("\"" + E->get().name.replace_first("shader_param/", "") + "\"");
}
}
}
- Resource::get_argument_options(p_function,p_idx,r_options);
+ Resource::get_argument_options(p_function, p_idx, r_options);
}
CanvasItemMaterial::CanvasItemMaterial() {
-
-
-
}
-CanvasItemMaterial::~CanvasItemMaterial(){
-
-
+CanvasItemMaterial::~CanvasItemMaterial() {
}
-
-
-
-
-
-
-
///////////////////////////////////////////////////////////////////
-
-
bool CanvasItem::is_visible_in_tree() const {
if (!is_inside_tree())
return false;
- const CanvasItem *p=this;
+ const CanvasItem *p = this;
- while(p) {
+ while (p) {
if (!p->visible)
return false;
- p=p->get_parent_item();
+ p = p->get_parent_item();
}
-
return true;
}
-
void CanvasItem::_propagate_visibility_changed(bool p_visible) {
notification(NOTIFICATION_VISIBILITY_CHANGED);
@@ -210,16 +183,15 @@ void CanvasItem::_propagate_visibility_changed(bool p_visible) {
emit_signal(SceneStringNames::get_singleton()->hide);
_block();
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- CanvasItem *c=get_child(i)->cast_to<CanvasItem>();
+ CanvasItem *c = get_child(i)->cast_to<CanvasItem>();
if (c && c->visible) //should the toplevels stop propagation? i think so but..
c->_propagate_visibility_changed(p_visible);
}
_unblock();
-
}
void CanvasItem::show() {
@@ -227,8 +199,8 @@ void CanvasItem::show() {
if (visible)
return;
- visible=true;
- VisualServer::get_singleton()->canvas_item_set_visible(canvas_item,true);
+ visible = true;
+ VisualServer::get_singleton()->canvas_item_set_visible(canvas_item, true);
if (!is_inside_tree())
return;
@@ -237,14 +209,13 @@ void CanvasItem::show() {
_change_notify("visibility/visible");
}
-
void CanvasItem::hide() {
if (!visible)
return;
- visible=false;
- VisualServer::get_singleton()->canvas_item_set_visible(canvas_item,false);
+ visible = false;
+ VisualServer::get_singleton()->canvas_item_set_visible(canvas_item, false);
if (!is_inside_tree())
return;
@@ -255,35 +226,28 @@ void CanvasItem::hide() {
Variant CanvasItem::edit_get_state() const {
-
return Variant();
}
-void CanvasItem::edit_set_state(const Variant& p_state) {
-
-
+void CanvasItem::edit_set_state(const Variant &p_state) {
}
-void CanvasItem::edit_set_rect(const Rect2& p_edit_rect) {
+void CanvasItem::edit_set_rect(const Rect2 &p_edit_rect) {
//used by editors, implement at will
}
void CanvasItem::edit_rotate(float p_rot) {
-
-
}
Size2 CanvasItem::edit_get_minimum_size() const {
- return Size2(-1,-1); //no limit
+ return Size2(-1, -1); //no limit
}
void CanvasItem::_update_callback() {
-
-
if (!is_inside_tree()) {
- pending_update=false;
+ pending_update = false;
return;
}
@@ -292,33 +256,32 @@ void CanvasItem::_update_callback() {
if (is_visible_in_tree()) { //todo optimize this!!
if (first_draw) {
notification(NOTIFICATION_VISIBILITY_CHANGED);
- first_draw=false;
+ first_draw = false;
}
- drawing=true;
+ drawing = true;
notification(NOTIFICATION_DRAW);
emit_signal(SceneStringNames::get_singleton()->draw);
if (get_script_instance()) {
Variant::CallError err;
- get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_draw,NULL,0);
+ get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_draw, NULL, 0);
}
- drawing=false;
-
+ drawing = false;
}
//todo updating = false
- pending_update=false; // don't change to false until finished drawing (avoid recursive update)
+ pending_update = false; // don't change to false until finished drawing (avoid recursive update)
}
Transform2D CanvasItem::get_global_transform_with_canvas() const {
const CanvasItem *ci = this;
Transform2D xform;
- const CanvasItem *last_valid=NULL;
+ const CanvasItem *last_valid = NULL;
- while(ci) {
+ while (ci) {
- last_valid=ci;
+ last_valid = ci;
xform = ci->get_transform() * xform;
- ci=ci->get_parent_item();
+ ci = ci->get_parent_item();
}
if (last_valid->canvas_layer)
@@ -331,7 +294,6 @@ Transform2D CanvasItem::get_global_transform_with_canvas() const {
Transform2D CanvasItem::get_global_transform() const {
-
if (global_invalid) {
const CanvasItem *pi = get_parent_item();
@@ -340,11 +302,10 @@ Transform2D CanvasItem::get_global_transform() const {
else
global_transform = get_transform();
- global_invalid=false;
+ global_invalid = false;
}
return global_transform;
-
}
void CanvasItem::_toplevel_raise_self() {
@@ -353,40 +314,37 @@ void CanvasItem::_toplevel_raise_self() {
return;
if (canvas_layer)
- VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,canvas_layer->get_sort_index());
+ VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, canvas_layer->get_sort_index());
else
- VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_viewport()->gui_get_canvas_sort_index());
-
-
+ VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_viewport()->gui_get_canvas_sort_index());
}
-
void CanvasItem::_enter_canvas() {
if ((!get_parent() || !get_parent()->cast_to<CanvasItem>()) || toplevel) {
Node *n = this;
- canvas_layer=NULL;
+ canvas_layer = NULL;
- while(n) {
+ while (n) {
canvas_layer = n->cast_to<CanvasLayer>();
if (canvas_layer) {
break;
}
- n=n->get_parent();
+ n = n->get_parent();
}
RID canvas;
if (canvas_layer)
- canvas=canvas_layer->get_world_2d()->get_canvas();
+ canvas = canvas_layer->get_world_2d()->get_canvas();
else
- canvas=get_viewport()->find_world_2d()->get_canvas();
+ canvas = get_viewport()->find_world_2d()->get_canvas();
- VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,canvas);
+ VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, canvas);
- group = "root_canvas"+itos(canvas.get_id());
+ group = "root_canvas" + itos(canvas.get_id());
add_to_group(group);
if (canvas_layer)
@@ -394,44 +352,40 @@ void CanvasItem::_enter_canvas() {
else
get_viewport()->gui_reset_canvas_sort_index();
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE,group,"_toplevel_raise_self");
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE, group, "_toplevel_raise_self");
} else {
CanvasItem *parent = get_parent_item();
- canvas_layer=parent->canvas_layer;
- VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,parent->get_canvas_item());
- VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_index());
+ canvas_layer = parent->canvas_layer;
+ VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, parent->get_canvas_item());
+ VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index());
}
- pending_update=false;
+ pending_update = false;
update();
notification(NOTIFICATION_ENTER_CANVAS);
-
}
void CanvasItem::_exit_canvas() {
- notification(NOTIFICATION_EXIT_CANVAS,true); //reverse the notification
- VisualServer::get_singleton()->canvas_item_set_parent(canvas_item,RID());
- canvas_layer=NULL;
- group="";
-
+ notification(NOTIFICATION_EXIT_CANVAS, true); //reverse the notification
+ VisualServer::get_singleton()->canvas_item_set_parent(canvas_item, RID());
+ canvas_layer = NULL;
+ group = "";
}
-
void CanvasItem::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- first_draw=true;
+ first_draw = true;
if (get_parent()) {
CanvasItem *ci = get_parent()->cast_to<CanvasItem>();
if (ci)
- C=ci->children_items.push_back(this);
+ C = ci->children_items.push_back(this);
}
_enter_canvas();
if (!block_transform_notify && !xform_change.in_list()) {
@@ -443,15 +397,14 @@ void CanvasItem::_notification(int p_what) {
if (!is_inside_tree())
break;
- if (group!="") {
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE,group,"_toplevel_raise_self");
+ if (group != "") {
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_UNIQUE, group, "_toplevel_raise_self");
} else {
CanvasItem *p = get_parent_item();
ERR_FAIL_COND(!p);
- VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item,get_index());
+ VisualServer::get_singleton()->canvas_item_set_draw_index(canvas_item, get_index());
}
-
} break;
case NOTIFICATION_EXIT_TREE: {
if (xform_change.in_list())
@@ -459,22 +412,20 @@ void CanvasItem::_notification(int p_what) {
_exit_canvas();
if (C) {
get_parent()->cast_to<CanvasItem>()->children_items.erase(C);
- C=NULL;
+ C = NULL;
}
- global_invalid=true;
+ global_invalid = true;
} break;
case NOTIFICATION_DRAW: {
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
-
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
emit_signal(SceneStringNames::get_singleton()->visibility_changed);
} break;
-
}
}
@@ -490,7 +441,6 @@ bool CanvasItem::is_visible() const {
return visible;
}
-
void CanvasItem::update() {
if (!is_inside_tree())
@@ -498,35 +448,33 @@ void CanvasItem::update() {
if (pending_update)
return;
- pending_update=true;
+ pending_update = true;
- MessageQueue::get_singleton()->push_call(this,"_update_callback");
+ MessageQueue::get_singleton()->push_call(this, "_update_callback");
}
-void CanvasItem::set_modulate(const Color& p_modulate) {
-
- modulate=p_modulate;
- VisualServer::get_singleton()->canvas_item_set_modulate(canvas_item,modulate);
+void CanvasItem::set_modulate(const Color &p_modulate) {
+ modulate = p_modulate;
+ VisualServer::get_singleton()->canvas_item_set_modulate(canvas_item, modulate);
}
Color CanvasItem::get_modulate() const {
return modulate;
}
-
void CanvasItem::set_as_toplevel(bool p_toplevel) {
- if (toplevel==p_toplevel)
+ if (toplevel == p_toplevel)
return;
if (!is_inside_tree()) {
- toplevel=p_toplevel;
+ toplevel = p_toplevel;
return;
}
_exit_canvas();
- toplevel=p_toplevel;
+ toplevel = p_toplevel;
_enter_canvas();
}
@@ -547,31 +495,27 @@ CanvasItem *CanvasItem::get_parent_item() const {
return parent->cast_to<CanvasItem>();
}
+void CanvasItem::set_self_modulate(const Color &p_self_modulate) {
-void CanvasItem::set_self_modulate(const Color& p_self_modulate) {
-
- self_modulate=p_self_modulate;
- VisualServer::get_singleton()->canvas_item_set_self_modulate(canvas_item,self_modulate);
-
+ self_modulate = p_self_modulate;
+ VisualServer::get_singleton()->canvas_item_set_self_modulate(canvas_item, self_modulate);
}
Color CanvasItem::get_self_modulate() const {
return self_modulate;
}
-
void CanvasItem::set_light_mask(int p_light_mask) {
- light_mask=p_light_mask;
- VS::get_singleton()->canvas_item_set_light_mask(canvas_item,p_light_mask);
+ light_mask = p_light_mask;
+ VS::get_singleton()->canvas_item_set_light_mask(canvas_item, p_light_mask);
}
-int CanvasItem::get_light_mask() const{
+int CanvasItem::get_light_mask() const {
return light_mask;
}
-
void CanvasItem::item_rect_changed(bool p_size_changed) {
if (p_size_changed)
@@ -579,40 +523,37 @@ void CanvasItem::item_rect_changed(bool p_size_changed) {
emit_signal(SceneStringNames::get_singleton()->item_rect_changed);
}
-
-void CanvasItem::draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) {
+void CanvasItem::draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
- VisualServer::get_singleton()->canvas_item_add_line(canvas_item,p_from,p_to,p_color,p_width,p_antialiased);
+ VisualServer::get_singleton()->canvas_item_add_line(canvas_item, p_from, p_to, p_color, p_width, p_antialiased);
}
-void CanvasItem::draw_rect(const Rect2& p_rect, const Color& p_color) {
+void CanvasItem::draw_rect(const Rect2 &p_rect, const Color &p_color) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
- VisualServer::get_singleton()->canvas_item_add_rect(canvas_item,p_rect,p_color);
-
+ VisualServer::get_singleton()->canvas_item_add_rect(canvas_item, p_rect, p_color);
}
-void CanvasItem::draw_circle(const Point2& p_pos, float p_radius, const Color& p_color) {
+void CanvasItem::draw_circle(const Point2 &p_pos, float p_radius, const Color &p_color) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
- VisualServer::get_singleton()->canvas_item_add_circle(canvas_item,p_pos,p_radius,p_color);
-
+ VisualServer::get_singleton()->canvas_item_add_circle(canvas_item, p_pos, p_radius, p_color);
}
-void CanvasItem::draw_texture(const Ref<Texture>& p_texture,const Point2& p_pos,const Color& p_modulate) {
+void CanvasItem::draw_texture(const Ref<Texture> &p_texture, const Point2 &p_pos, const Color &p_modulate) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -621,10 +562,10 @@ void CanvasItem::draw_texture(const Ref<Texture>& p_texture,const Point2& p_pos,
ERR_FAIL_COND(p_texture.is_null());
- p_texture->draw(canvas_item,p_pos,p_modulate);
+ p_texture->draw(canvas_item, p_pos, p_modulate);
}
-void CanvasItem::draw_texture_rect(const Ref<Texture>& p_texture,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) {
+void CanvasItem::draw_texture_rect(const Ref<Texture> &p_texture, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -632,20 +573,19 @@ void CanvasItem::draw_texture_rect(const Ref<Texture>& p_texture,const Rect2& p_
}
ERR_FAIL_COND(p_texture.is_null());
- p_texture->draw_rect(canvas_item,p_rect,p_tile,p_modulate,p_transpose);
-
+ p_texture->draw_rect(canvas_item, p_rect, p_tile, p_modulate, p_transpose);
}
-void CanvasItem::draw_texture_rect_region(const Ref<Texture>& p_texture,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) {
+void CanvasItem::draw_texture_rect_region(const Ref<Texture> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
ERR_FAIL_COND(p_texture.is_null());
- p_texture->draw_rect_region(canvas_item,p_rect,p_src_rect,p_modulate,p_transpose);
+ p_texture->draw_rect_region(canvas_item, p_rect, p_src_rect, p_modulate, p_transpose);
}
-void CanvasItem::draw_style_box(const Ref<StyleBox>& p_style_box,const Rect2& p_rect) {
+void CanvasItem::draw_style_box(const Ref<StyleBox> &p_style_box, const Rect2 &p_rect) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
@@ -653,10 +593,9 @@ void CanvasItem::draw_style_box(const Ref<StyleBox>& p_style_box,const Rect2& p_
ERR_FAIL_COND(p_style_box.is_null());
- p_style_box->draw(canvas_item,p_rect);
-
+ p_style_box->draw(canvas_item, p_rect);
}
-void CanvasItem::draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, Ref<Texture> p_texture,float p_width) {
+void CanvasItem::draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture> p_texture, float p_width) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -665,32 +604,31 @@ void CanvasItem::draw_primitive(const Vector<Point2>& p_points, const Vector<Col
RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
- VisualServer::get_singleton()->canvas_item_add_primitive(canvas_item,p_points,p_colors,p_uvs,rid,p_width);
+ VisualServer::get_singleton()->canvas_item_add_primitive(canvas_item, p_points, p_colors, p_uvs, rid, p_width);
}
-void CanvasItem::draw_set_transform(const Point2& p_offset, float p_rot, const Size2& p_scale) {
+void CanvasItem::draw_set_transform(const Point2 &p_offset, float p_rot, const Size2 &p_scale) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
- Transform2D xform(p_rot,p_offset);
+ Transform2D xform(p_rot, p_offset);
xform.scale_basis(p_scale);
- VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item,xform);
+ VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item, xform);
}
-void CanvasItem::draw_set_transform_matrix(const Transform2D& p_matrix) {
+void CanvasItem::draw_set_transform_matrix(const Transform2D &p_matrix) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL();
}
- VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item,p_matrix);
-
+ VisualServer::get_singleton()->canvas_item_add_set_transform(canvas_item, p_matrix);
}
-void CanvasItem::draw_polygon(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, Ref<Texture> p_texture) {
+void CanvasItem::draw_polygon(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture> p_texture) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -699,12 +637,10 @@ void CanvasItem::draw_polygon(const Vector<Point2>& p_points, const Vector<Color
RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
- VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item,p_points,p_colors,p_uvs,rid);
-
-
+ VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item, p_points, p_colors, p_uvs, rid);
}
-void CanvasItem::draw_colored_polygon(const Vector<Point2>& p_points, const Color& p_color,const Vector<Point2>& p_uvs, Ref<Texture> p_texture) {
+void CanvasItem::draw_colored_polygon(const Vector<Point2> &p_points, const Color &p_color, const Vector<Point2> &p_uvs, Ref<Texture> p_texture) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -715,10 +651,10 @@ void CanvasItem::draw_colored_polygon(const Vector<Point2>& p_points, const Colo
colors.push_back(p_color);
RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
- VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item,p_points,colors,p_uvs,rid);
+ VisualServer::get_singleton()->canvas_item_add_polygon(canvas_item, p_points, colors, p_uvs, rid);
}
-void CanvasItem::draw_string(const Ref<Font>& p_font,const Point2& p_pos, const String& p_text,const Color& p_modulate,int p_clip_w) {
+void CanvasItem::draw_string(const Ref<Font> &p_font, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
@@ -726,31 +662,28 @@ void CanvasItem::draw_string(const Ref<Font>& p_font,const Point2& p_pos, const
}
ERR_FAIL_COND(p_font.is_null());
- p_font->draw(canvas_item,p_pos,p_text,p_modulate,p_clip_w);
-
+ p_font->draw(canvas_item, p_pos, p_text, p_modulate, p_clip_w);
}
-float CanvasItem::draw_char(const Ref<Font>& p_font,const Point2& p_pos, const String& p_char,const String& p_next,const Color& p_modulate) {
+float CanvasItem::draw_char(const Ref<Font> &p_font, const Point2 &p_pos, const String &p_char, const String &p_next, const Color &p_modulate) {
if (!drawing) {
ERR_EXPLAIN("Drawing is only allowed inside NOTIFICATION_DRAW, _draw() function or 'draw' signal.");
ERR_FAIL_V(0);
}
- ERR_FAIL_COND_V(p_char.length()!=1,0);
- ERR_FAIL_COND_V(p_font.is_null(),0);
-
- return p_font->draw_char(canvas_item,p_pos,p_char[0],p_next.c_str()[0],p_modulate);
+ ERR_FAIL_COND_V(p_char.length() != 1, 0);
+ ERR_FAIL_COND_V(p_font.is_null(), 0);
+ return p_font->draw_char(canvas_item, p_pos, p_char[0], p_next.c_str()[0], p_modulate);
}
-
void CanvasItem::_notify_transform(CanvasItem *p_node) {
if (/*p_node->xform_change.in_list() &&*/ p_node->global_invalid)
return; //nothing to do
- p_node->global_invalid=true;
+ p_node->global_invalid = true;
if (p_node->notify_transform && !p_node->xform_change.in_list()) {
if (!p_node->block_transform_notify) {
@@ -759,51 +692,46 @@ void CanvasItem::_notify_transform(CanvasItem *p_node) {
}
}
+ for (List<CanvasItem *>::Element *E = p_node->children_items.front(); E; E = E->next()) {
- for(List<CanvasItem*>::Element *E=p_node->children_items.front();E;E=E->next()) {
-
- CanvasItem* ci=E->get();
+ CanvasItem *ci = E->get();
if (ci->toplevel)
continue;
_notify_transform(ci);
}
}
-
Rect2 CanvasItem::get_viewport_rect() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Rect2());
+ ERR_FAIL_COND_V(!is_inside_tree(), Rect2());
return get_viewport()->get_visible_rect();
}
RID CanvasItem::get_canvas() const {
- ERR_FAIL_COND_V(!is_inside_tree(),RID());
+ ERR_FAIL_COND_V(!is_inside_tree(), RID());
if (canvas_layer)
return canvas_layer->get_world_2d()->get_canvas();
else
return get_viewport()->find_world_2d()->get_canvas();
-
-
}
CanvasItem *CanvasItem::get_toplevel() const {
- CanvasItem *ci=const_cast<CanvasItem*>(this);
- while(!ci->toplevel && ci->get_parent() && ci->get_parent()->cast_to<CanvasItem>()) {
- ci=ci->get_parent()->cast_to<CanvasItem>();
+ CanvasItem *ci = const_cast<CanvasItem *>(this);
+ while (!ci->toplevel && ci->get_parent() && ci->get_parent()->cast_to<CanvasItem>()) {
+ ci = ci->get_parent()->cast_to<CanvasItem>();
}
return ci;
}
-
Ref<World2D> CanvasItem::get_world_2d() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Ref<World2D>());
+ ERR_FAIL_COND_V(!is_inside_tree(), Ref<World2D>());
- CanvasItem *tl=get_toplevel();
+ CanvasItem *tl = get_toplevel();
if (tl->canvas_layer) {
return tl->canvas_layer->get_world_2d();
@@ -812,17 +740,16 @@ Ref<World2D> CanvasItem::get_world_2d() const {
} else {
return Ref<World2D>();
}
-
}
RID CanvasItem::get_viewport_rid() const {
- ERR_FAIL_COND_V(!is_inside_tree(),RID());
+ ERR_FAIL_COND_V(!is_inside_tree(), RID());
return get_viewport()->get_viewport_rid();
}
void CanvasItem::set_block_transform_notify(bool p_enable) {
- block_transform_notify=p_enable;
+ block_transform_notify = p_enable;
}
bool CanvasItem::is_block_transform_notify_enabled() const {
@@ -832,205 +759,196 @@ bool CanvasItem::is_block_transform_notify_enabled() const {
void CanvasItem::set_draw_behind_parent(bool p_enable) {
- if (behind==p_enable)
+ if (behind == p_enable)
return;
- behind=p_enable;
- VisualServer::get_singleton()->canvas_item_set_draw_behind_parent(canvas_item,behind);
-
+ behind = p_enable;
+ VisualServer::get_singleton()->canvas_item_set_draw_behind_parent(canvas_item, behind);
}
-bool CanvasItem::is_draw_behind_parent_enabled() const{
+bool CanvasItem::is_draw_behind_parent_enabled() const {
return behind;
}
-void CanvasItem::set_material(const Ref<CanvasItemMaterial>& p_material) {
-
+void CanvasItem::set_material(const Ref<CanvasItemMaterial> &p_material) {
- material=p_material;
+ material = p_material;
RID rid;
if (material.is_valid())
- rid=material->get_rid();
- VS::get_singleton()->canvas_item_set_material(canvas_item,rid);
+ rid = material->get_rid();
+ VS::get_singleton()->canvas_item_set_material(canvas_item, rid);
_change_notify(); //properties for material exposed
}
void CanvasItem::set_use_parent_material(bool p_use_parent_material) {
- use_parent_material=p_use_parent_material;
- VS::get_singleton()->canvas_item_set_use_parent_material(canvas_item,p_use_parent_material);
+ use_parent_material = p_use_parent_material;
+ VS::get_singleton()->canvas_item_set_use_parent_material(canvas_item, p_use_parent_material);
}
-bool CanvasItem::get_use_parent_material() const{
+bool CanvasItem::get_use_parent_material() const {
return use_parent_material;
}
-Ref<CanvasItemMaterial> CanvasItem::get_material() const{
+Ref<CanvasItemMaterial> CanvasItem::get_material() const {
return material;
}
-Vector2 CanvasItem::make_canvas_pos_local(const Vector2& screen_point) const {
+Vector2 CanvasItem::make_canvas_pos_local(const Vector2 &screen_point) const {
- ERR_FAIL_COND_V(!is_inside_tree(),screen_point);
+ ERR_FAIL_COND_V(!is_inside_tree(), screen_point);
- Transform2D local_matrix = (get_canvas_transform() *
- get_global_transform()).affine_inverse();
+ Transform2D local_matrix = (get_canvas_transform() *
+ get_global_transform())
+ .affine_inverse();
return local_matrix.xform(screen_point);
}
-InputEvent CanvasItem::make_input_local(const InputEvent& p_event) const {
-
- ERR_FAIL_COND_V(!is_inside_tree(),p_event);
+InputEvent CanvasItem::make_input_local(const InputEvent &p_event) const {
- return p_event.xform_by( (get_canvas_transform() * get_global_transform()).affine_inverse() );
+ ERR_FAIL_COND_V(!is_inside_tree(), p_event);
+ return p_event.xform_by((get_canvas_transform() * get_global_transform()).affine_inverse());
}
-
Vector2 CanvasItem::get_global_mouse_pos() const {
- ERR_FAIL_COND_V(!get_viewport(),Vector2());
- return get_canvas_transform().affine_inverse().xform( get_viewport()->get_mouse_pos() );
+ ERR_FAIL_COND_V(!get_viewport(), Vector2());
+ return get_canvas_transform().affine_inverse().xform(get_viewport()->get_mouse_pos());
}
-Vector2 CanvasItem::get_local_mouse_pos() const{
+Vector2 CanvasItem::get_local_mouse_pos() const {
- ERR_FAIL_COND_V(!get_viewport(),Vector2());
+ ERR_FAIL_COND_V(!get_viewport(), Vector2());
- return get_global_transform().affine_inverse().xform( get_global_mouse_pos() );
+ return get_global_transform().affine_inverse().xform(get_global_mouse_pos());
}
-
void CanvasItem::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_toplevel_raise_self"),&CanvasItem::_toplevel_raise_self);
- ClassDB::bind_method(D_METHOD("_update_callback"),&CanvasItem::_update_callback);
+ ClassDB::bind_method(D_METHOD("_toplevel_raise_self"), &CanvasItem::_toplevel_raise_self);
+ ClassDB::bind_method(D_METHOD("_update_callback"), &CanvasItem::_update_callback);
- ClassDB::bind_method(D_METHOD("edit_set_state","state"),&CanvasItem::edit_set_state);
- ClassDB::bind_method(D_METHOD("edit_get_state:Variant"),&CanvasItem::edit_get_state);
- ClassDB::bind_method(D_METHOD("edit_set_rect","rect"),&CanvasItem::edit_set_rect);
- ClassDB::bind_method(D_METHOD("edit_rotate","degrees"),&CanvasItem::edit_rotate);
+ ClassDB::bind_method(D_METHOD("edit_set_state", "state"), &CanvasItem::edit_set_state);
+ ClassDB::bind_method(D_METHOD("edit_get_state:Variant"), &CanvasItem::edit_get_state);
+ ClassDB::bind_method(D_METHOD("edit_set_rect", "rect"), &CanvasItem::edit_set_rect);
+ ClassDB::bind_method(D_METHOD("edit_rotate", "degrees"), &CanvasItem::edit_rotate);
- ClassDB::bind_method(D_METHOD("get_item_rect"),&CanvasItem::get_item_rect);
- ClassDB::bind_method(D_METHOD("get_item_and_children_rect"),&CanvasItem::get_item_and_children_rect);
+ ClassDB::bind_method(D_METHOD("get_item_rect"), &CanvasItem::get_item_rect);
+ ClassDB::bind_method(D_METHOD("get_item_and_children_rect"), &CanvasItem::get_item_and_children_rect);
//ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform);
- ClassDB::bind_method(D_METHOD("get_canvas_item"),&CanvasItem::get_canvas_item);
+ ClassDB::bind_method(D_METHOD("get_canvas_item"), &CanvasItem::get_canvas_item);
- ClassDB::bind_method(D_METHOD("set_visible"),&CanvasItem::set_visible);
- ClassDB::bind_method(D_METHOD("is_visible"),&CanvasItem::is_visible);
- ClassDB::bind_method(D_METHOD("is_visible_in_tree"),&CanvasItem::is_visible_in_tree);
- ClassDB::bind_method(D_METHOD("show"),&CanvasItem::show);
- ClassDB::bind_method(D_METHOD("hide"),&CanvasItem::hide);
+ ClassDB::bind_method(D_METHOD("set_visible"), &CanvasItem::set_visible);
+ ClassDB::bind_method(D_METHOD("is_visible"), &CanvasItem::is_visible);
+ ClassDB::bind_method(D_METHOD("is_visible_in_tree"), &CanvasItem::is_visible_in_tree);
+ ClassDB::bind_method(D_METHOD("show"), &CanvasItem::show);
+ ClassDB::bind_method(D_METHOD("hide"), &CanvasItem::hide);
- ClassDB::bind_method(D_METHOD("update"),&CanvasItem::update);
+ ClassDB::bind_method(D_METHOD("update"), &CanvasItem::update);
- ClassDB::bind_method(D_METHOD("set_as_toplevel","enable"),&CanvasItem::set_as_toplevel);
- ClassDB::bind_method(D_METHOD("is_set_as_toplevel"),&CanvasItem::is_set_as_toplevel);
+ ClassDB::bind_method(D_METHOD("set_as_toplevel", "enable"), &CanvasItem::set_as_toplevel);
+ ClassDB::bind_method(D_METHOD("is_set_as_toplevel"), &CanvasItem::is_set_as_toplevel);
- ClassDB::bind_method(D_METHOD("set_light_mask","light_mask"),&CanvasItem::set_light_mask);
- ClassDB::bind_method(D_METHOD("get_light_mask"),&CanvasItem::get_light_mask);
+ ClassDB::bind_method(D_METHOD("set_light_mask", "light_mask"), &CanvasItem::set_light_mask);
+ ClassDB::bind_method(D_METHOD("get_light_mask"), &CanvasItem::get_light_mask);
- ClassDB::bind_method(D_METHOD("set_modulate","modulate"),&CanvasItem::set_modulate);
- ClassDB::bind_method(D_METHOD("get_modulate"),&CanvasItem::get_modulate);
- ClassDB::bind_method(D_METHOD("set_self_modulate","self_modulate"),&CanvasItem::set_self_modulate);
- ClassDB::bind_method(D_METHOD("get_self_modulate"),&CanvasItem::get_self_modulate);
+ ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &CanvasItem::set_modulate);
+ ClassDB::bind_method(D_METHOD("get_modulate"), &CanvasItem::get_modulate);
+ ClassDB::bind_method(D_METHOD("set_self_modulate", "self_modulate"), &CanvasItem::set_self_modulate);
+ ClassDB::bind_method(D_METHOD("get_self_modulate"), &CanvasItem::get_self_modulate);
- ClassDB::bind_method(D_METHOD("set_draw_behind_parent","enable"),&CanvasItem::set_draw_behind_parent);
- ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"),&CanvasItem::is_draw_behind_parent_enabled);
+ ClassDB::bind_method(D_METHOD("set_draw_behind_parent", "enable"), &CanvasItem::set_draw_behind_parent);
+ ClassDB::bind_method(D_METHOD("is_draw_behind_parent_enabled"), &CanvasItem::is_draw_behind_parent_enabled);
- ClassDB::bind_method(D_METHOD("_set_on_top","on_top"),&CanvasItem::_set_on_top);
- ClassDB::bind_method(D_METHOD("_is_on_top"),&CanvasItem::_is_on_top);
+ ClassDB::bind_method(D_METHOD("_set_on_top", "on_top"), &CanvasItem::_set_on_top);
+ ClassDB::bind_method(D_METHOD("_is_on_top"), &CanvasItem::_is_on_top);
//ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform);
- ClassDB::bind_method(D_METHOD("draw_line","from","to","color","width","antialiased"),&CanvasItem::draw_line,DEFVAL(1.0),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_rect","rect","color"),&CanvasItem::draw_rect);
- ClassDB::bind_method(D_METHOD("draw_circle","pos","radius","color"),&CanvasItem::draw_circle);
- ClassDB::bind_method(D_METHOD("draw_texture","texture:Texture","pos","modulate"),&CanvasItem::draw_texture,DEFVAL(Color(1,1,1,1)));
- ClassDB::bind_method(D_METHOD("draw_texture_rect","texture:Texture","rect","tile","modulate","transpose"),&CanvasItem::draw_texture_rect,DEFVAL(Color(1,1,1)),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_texture_rect_region","texture:Texture","rect","src_rect","modulate","transpose"),&CanvasItem::draw_texture_rect_region,DEFVAL(Color(1,1,1)),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_style_box","style_box:StyleBox","rect"),&CanvasItem::draw_style_box);
- ClassDB::bind_method(D_METHOD("draw_primitive","points","colors","uvs","texture:Texture","width"),&CanvasItem::draw_primitive,DEFVAL(Variant()),DEFVAL(1.0));
- ClassDB::bind_method(D_METHOD("draw_polygon","points","colors","uvs","texture:Texture"),&CanvasItem::draw_polygon,DEFVAL(PoolVector2Array()),DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("draw_colored_polygon","points","color","uvs","texture:Texture"),&CanvasItem::draw_colored_polygon,DEFVAL(PoolVector2Array()),DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("draw_string","font:Font","pos","text","modulate","clip_w"),&CanvasItem::draw_string,DEFVAL(Color(1,1,1)),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("draw_char","font:Font","pos","char","next","modulate"),&CanvasItem::draw_char,DEFVAL(Color(1,1,1)));
-
- ClassDB::bind_method(D_METHOD("draw_set_transform","pos","rot","scale"),&CanvasItem::draw_set_transform);
- ClassDB::bind_method(D_METHOD("draw_set_transform_matrix","xform"),&CanvasItem::draw_set_transform_matrix);
- ClassDB::bind_method(D_METHOD("get_transform"),&CanvasItem::get_transform);
- ClassDB::bind_method(D_METHOD("get_global_transform"),&CanvasItem::get_global_transform);
- ClassDB::bind_method(D_METHOD("get_global_transform_with_canvas"),&CanvasItem::get_global_transform_with_canvas);
- ClassDB::bind_method(D_METHOD("get_viewport_transform"),&CanvasItem::get_viewport_transform);
- ClassDB::bind_method(D_METHOD("get_viewport_rect"),&CanvasItem::get_viewport_rect);
- ClassDB::bind_method(D_METHOD("get_canvas_transform"),&CanvasItem::get_canvas_transform);
- ClassDB::bind_method(D_METHOD("get_local_mouse_pos"),&CanvasItem::get_local_mouse_pos);
- ClassDB::bind_method(D_METHOD("get_global_mouse_pos"),&CanvasItem::get_global_mouse_pos);
- ClassDB::bind_method(D_METHOD("get_canvas"),&CanvasItem::get_canvas);
- ClassDB::bind_method(D_METHOD("get_world_2d"),&CanvasItem::get_world_2d);
+ ClassDB::bind_method(D_METHOD("draw_line", "from", "to", "color", "width", "antialiased"), &CanvasItem::draw_line, DEFVAL(1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_rect", "rect", "color"), &CanvasItem::draw_rect);
+ ClassDB::bind_method(D_METHOD("draw_circle", "pos", "radius", "color"), &CanvasItem::draw_circle);
+ ClassDB::bind_method(D_METHOD("draw_texture", "texture:Texture", "pos", "modulate"), &CanvasItem::draw_texture, DEFVAL(Color(1, 1, 1, 1)));
+ ClassDB::bind_method(D_METHOD("draw_texture_rect", "texture:Texture", "rect", "tile", "modulate", "transpose"), &CanvasItem::draw_texture_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_texture_rect_region", "texture:Texture", "rect", "src_rect", "modulate", "transpose"), &CanvasItem::draw_texture_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_style_box", "style_box:StyleBox", "rect"), &CanvasItem::draw_style_box);
+ ClassDB::bind_method(D_METHOD("draw_primitive", "points", "colors", "uvs", "texture:Texture", "width"), &CanvasItem::draw_primitive, DEFVAL(Variant()), DEFVAL(1.0));
+ ClassDB::bind_method(D_METHOD("draw_polygon", "points", "colors", "uvs", "texture:Texture"), &CanvasItem::draw_polygon, DEFVAL(PoolVector2Array()), DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("draw_colored_polygon", "points", "color", "uvs", "texture:Texture"), &CanvasItem::draw_colored_polygon, DEFVAL(PoolVector2Array()), DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("draw_string", "font:Font", "pos", "text", "modulate", "clip_w"), &CanvasItem::draw_string, DEFVAL(Color(1, 1, 1)), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("draw_char", "font:Font", "pos", "char", "next", "modulate"), &CanvasItem::draw_char, DEFVAL(Color(1, 1, 1)));
+
+ ClassDB::bind_method(D_METHOD("draw_set_transform", "pos", "rot", "scale"), &CanvasItem::draw_set_transform);
+ ClassDB::bind_method(D_METHOD("draw_set_transform_matrix", "xform"), &CanvasItem::draw_set_transform_matrix);
+ ClassDB::bind_method(D_METHOD("get_transform"), &CanvasItem::get_transform);
+ ClassDB::bind_method(D_METHOD("get_global_transform"), &CanvasItem::get_global_transform);
+ ClassDB::bind_method(D_METHOD("get_global_transform_with_canvas"), &CanvasItem::get_global_transform_with_canvas);
+ ClassDB::bind_method(D_METHOD("get_viewport_transform"), &CanvasItem::get_viewport_transform);
+ ClassDB::bind_method(D_METHOD("get_viewport_rect"), &CanvasItem::get_viewport_rect);
+ ClassDB::bind_method(D_METHOD("get_canvas_transform"), &CanvasItem::get_canvas_transform);
+ ClassDB::bind_method(D_METHOD("get_local_mouse_pos"), &CanvasItem::get_local_mouse_pos);
+ ClassDB::bind_method(D_METHOD("get_global_mouse_pos"), &CanvasItem::get_global_mouse_pos);
+ ClassDB::bind_method(D_METHOD("get_canvas"), &CanvasItem::get_canvas);
+ ClassDB::bind_method(D_METHOD("get_world_2d"), &CanvasItem::get_world_2d);
//ClassDB::bind_method(D_METHOD("get_viewport"),&CanvasItem::get_viewport);
- ClassDB::bind_method(D_METHOD("set_material","material:CanvasItemMaterial"),&CanvasItem::set_material);
- ClassDB::bind_method(D_METHOD("get_material:CanvasItemMaterial"),&CanvasItem::get_material);
+ ClassDB::bind_method(D_METHOD("set_material", "material:CanvasItemMaterial"), &CanvasItem::set_material);
+ ClassDB::bind_method(D_METHOD("get_material:CanvasItemMaterial"), &CanvasItem::get_material);
- ClassDB::bind_method(D_METHOD("set_use_parent_material","enable"),&CanvasItem::set_use_parent_material);
- ClassDB::bind_method(D_METHOD("get_use_parent_material"),&CanvasItem::get_use_parent_material);
+ ClassDB::bind_method(D_METHOD("set_use_parent_material", "enable"), &CanvasItem::set_use_parent_material);
+ ClassDB::bind_method(D_METHOD("get_use_parent_material"), &CanvasItem::get_use_parent_material);
- ClassDB::bind_method(D_METHOD("set_notify_local_transform","enable"),&CanvasItem::set_notify_local_transform);
- ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"),&CanvasItem::is_local_transform_notification_enabled);
+ ClassDB::bind_method(D_METHOD("set_notify_local_transform", "enable"), &CanvasItem::set_notify_local_transform);
+ ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"), &CanvasItem::is_local_transform_notification_enabled);
- ClassDB::bind_method(D_METHOD("set_notify_transform","enable"),&CanvasItem::set_notify_transform);
- ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"),&CanvasItem::is_transform_notification_enabled);
+ ClassDB::bind_method(D_METHOD("set_notify_transform", "enable"), &CanvasItem::set_notify_transform);
+ ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"), &CanvasItem::is_transform_notification_enabled);
- ClassDB::bind_method(D_METHOD("make_canvas_pos_local","screen_point"),
+ ClassDB::bind_method(D_METHOD("make_canvas_pos_local", "screen_point"),
&CanvasItem::make_canvas_pos_local);
- ClassDB::bind_method(D_METHOD("make_input_local","event"),&CanvasItem::make_input_local);
+ ClassDB::bind_method(D_METHOD("make_input_local", "event"), &CanvasItem::make_input_local);
BIND_VMETHOD(MethodInfo("_draw"));
- ADD_GROUP("Visibility","");
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"visible"), "set_visible","is_visible") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::COLOR,"modulate"), "set_modulate","get_modulate") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::COLOR,"self_modulate"), "set_self_modulate","get_self_modulate") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"show_behind_parent"), "set_draw_behind_parent","is_draw_behind_parent_enabled") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"show_on_top",PROPERTY_HINT_NONE,"",0), "_set_on_top","_is_on_top") ; //compatibility
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"light_mask",PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask","get_light_mask") ;
-
- ADD_GROUP("Material","");
- ADD_PROPERTYNZ( PropertyInfo(Variant::OBJECT,"material",PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial"), "set_material","get_material") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::BOOL,"use_parent_material"), "set_use_parent_material","get_use_parent_material") ;
+ ADD_GROUP("Visibility", "");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible");
+ ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
+ ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "self_modulate"), "set_self_modulate", "get_self_modulate");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "show_behind_parent"), "set_draw_behind_parent", "is_draw_behind_parent_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_on_top", PROPERTY_HINT_NONE, "", 0), "_set_on_top", "_is_on_top"); //compatibility
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_light_mask", "get_light_mask");
+
+ ADD_GROUP("Material", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial"), "set_material", "get_material");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "use_parent_material"), "set_use_parent_material", "get_use_parent_material");
//exporting these two things doesn't really make much sense i think
//ADD_PROPERTY( PropertyInfo(Variant::BOOL,"transform/toplevel"), "set_as_toplevel","is_set_as_toplevel") ;
//ADD_PROPERTY(PropertyInfo(Variant::BOOL,"transform/notify"),"set_transform_notify","is_transform_notify_enabled");
- ADD_SIGNAL( MethodInfo("draw") );
- ADD_SIGNAL( MethodInfo("visibility_changed") );
- ADD_SIGNAL( MethodInfo("hide") );
- ADD_SIGNAL( MethodInfo("item_rect_changed") );
-
-
-
- BIND_CONSTANT( BLEND_MODE_MIX );
- BIND_CONSTANT( BLEND_MODE_ADD );
- BIND_CONSTANT( BLEND_MODE_SUB );
- BIND_CONSTANT( BLEND_MODE_MUL );
- BIND_CONSTANT( BLEND_MODE_PREMULT_ALPHA );
-
-
- BIND_CONSTANT( NOTIFICATION_DRAW);
- BIND_CONSTANT( NOTIFICATION_VISIBILITY_CHANGED );
- BIND_CONSTANT( NOTIFICATION_ENTER_CANVAS );
- BIND_CONSTANT( NOTIFICATION_EXIT_CANVAS );
- BIND_CONSTANT( NOTIFICATION_TRANSFORM_CHANGED );
+ ADD_SIGNAL(MethodInfo("draw"));
+ ADD_SIGNAL(MethodInfo("visibility_changed"));
+ ADD_SIGNAL(MethodInfo("hide"));
+ ADD_SIGNAL(MethodInfo("item_rect_changed"));
+ BIND_CONSTANT(BLEND_MODE_MIX);
+ BIND_CONSTANT(BLEND_MODE_ADD);
+ BIND_CONSTANT(BLEND_MODE_SUB);
+ BIND_CONSTANT(BLEND_MODE_MUL);
+ BIND_CONSTANT(BLEND_MODE_PREMULT_ALPHA);
+ BIND_CONSTANT(NOTIFICATION_DRAW);
+ BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED);
+ BIND_CONSTANT(NOTIFICATION_ENTER_CANVAS);
+ BIND_CONSTANT(NOTIFICATION_EXIT_CANVAS);
+ BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED);
}
Transform2D CanvasItem::get_canvas_transform() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Transform2D());
+ ERR_FAIL_COND_V(!is_inside_tree(), Transform2D());
if (canvas_layer)
return canvas_layer->get_transform();
@@ -1038,12 +956,11 @@ Transform2D CanvasItem::get_canvas_transform() const {
return get_parent()->cast_to<CanvasItem>()->get_canvas_transform();
else
return get_viewport()->get_canvas_transform();
-
}
Transform2D CanvasItem::get_viewport_transform() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Transform2D());
+ ERR_FAIL_COND_V(!is_inside_tree(), Transform2D());
if (canvas_layer) {
@@ -1056,21 +973,18 @@ Transform2D CanvasItem::get_viewport_transform() const {
} else {
return get_viewport()->get_final_transform() * get_viewport()->get_canvas_transform();
}
-
}
-
void CanvasItem::set_notify_local_transform(bool p_enable) {
- notify_local_transform=p_enable;
+ notify_local_transform = p_enable;
}
bool CanvasItem::is_local_transform_notification_enabled() const {
return notify_local_transform;
}
-
void CanvasItem::set_notify_transform(bool p_enable) {
- notify_transform=p_enable;
+ notify_transform = p_enable;
}
bool CanvasItem::is_transform_notification_enabled() const {
@@ -1085,14 +999,12 @@ int CanvasItem::get_canvas_layer() const {
return 0;
}
-
Rect2 CanvasItem::get_item_and_children_rect() const {
Rect2 rect = get_item_rect();
-
- for(int i=0;i<get_child_count();i++) {
- CanvasItem *c=get_child(i)->cast_to<CanvasItem>();
+ for (int i = 0; i < get_child_count(); i++) {
+ CanvasItem *c = get_child(i)->cast_to<CanvasItem>();
if (c) {
Rect2 sir = c->get_transform().xform(c->get_item_and_children_rect());
rect = rect.merge(sir);
@@ -1102,29 +1014,28 @@ Rect2 CanvasItem::get_item_and_children_rect() const {
return rect;
}
-CanvasItem::CanvasItem() : xform_change(this) {
+CanvasItem::CanvasItem()
+ : xform_change(this) {
-
- canvas_item=VisualServer::get_singleton()->canvas_item_create();
- visible=true;
- pending_update=false;
- modulate=Color(1,1,1,1);
- self_modulate=Color(1,1,1,1);
- toplevel=false;
- first_draw=false;
- drawing=false;
- behind=false;
- block_transform_notify=false;
+ canvas_item = VisualServer::get_singleton()->canvas_item_create();
+ visible = true;
+ pending_update = false;
+ modulate = Color(1, 1, 1, 1);
+ self_modulate = Color(1, 1, 1, 1);
+ toplevel = false;
+ first_draw = false;
+ drawing = false;
+ behind = false;
+ block_transform_notify = false;
//viewport=NULL;
- canvas_layer=NULL;
- use_parent_material=false;
- global_invalid=true;
- notify_local_transform=false;
- notify_transform=false;
- light_mask=1;
-
- C=NULL;
-
+ canvas_layer = NULL;
+ use_parent_material = false;
+ global_invalid = true;
+ notify_local_transform = false;
+ notify_transform = false;
+ light_mask = 1;
+
+ C = NULL;
}
CanvasItem::~CanvasItem() {
diff --git a/scene/2d/canvas_item.h b/scene/2d/canvas_item.h
index 9688b873c0..a188ce495a 100644
--- a/scene/2d/canvas_item.h
+++ b/scene/2d/canvas_item.h
@@ -30,10 +30,10 @@
#define CANVAS_ITEM_H
#include "scene/main/node.h"
-#include "scene/resources/texture.h"
#include "scene/main/scene_main_loop.h"
-#include "scene/resources/shader.h"
#include "scene/resources/material.h"
+#include "scene/resources/shader.h"
+#include "scene/resources/texture.h"
class CanvasLayer;
class Viewport;
@@ -43,8 +43,9 @@ class StyleBox;
class CanvasItemMaterial : public Material {
- GDCLASS(CanvasItemMaterial,Material);
+ GDCLASS(CanvasItemMaterial, Material);
Ref<Shader> shader;
+
public:
/*enum ShadingMode {
SHADING_NORMAL,
@@ -53,34 +54,30 @@ public:
};*/
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
- void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
+ void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
public:
-
- void set_shader(const Ref<Shader>& p_shader);
+ void set_shader(const Ref<Shader> &p_shader);
Ref<Shader> get_shader() const;
- void set_shader_param(const StringName& p_param,const Variant& p_value);
- Variant get_shader_param(const StringName& p_param) const;
+ void set_shader_param(const StringName &p_param, const Variant &p_value);
+ Variant get_shader_param(const StringName &p_param) const;
CanvasItemMaterial();
~CanvasItemMaterial();
};
-
-
-
class CanvasItem : public Node {
- GDCLASS( CanvasItem, Node );
-public:
+ GDCLASS(CanvasItem, Node);
+public:
enum BlendMode {
BLEND_MODE_MIX, //default
@@ -91,20 +88,18 @@ public:
};
private:
-
mutable SelfList<Node> xform_change;
RID canvas_item;
String group;
-
CanvasLayer *canvas_layer;
Color modulate;
Color self_modulate;
- List<CanvasItem*> children_items;
- List<CanvasItem*>::Element *C;
+ List<CanvasItem *> children_items;
+ List<CanvasItem *>::Element *C;
int light_mask;
@@ -124,12 +119,10 @@ private:
mutable Transform2D global_transform;
mutable bool global_invalid;
-
void _toplevel_raise_self();
void _propagate_visibility_changed(bool p_visible);
-
void _update_callback();
void _enter_canvas();
@@ -141,32 +134,34 @@ private:
bool _is_on_top() const { return !is_draw_behind_parent_enabled(); }
protected:
+ _FORCE_INLINE_ void _notify_transform() {
+ if (!is_inside_tree()) return;
+ _notify_transform(this);
+ if (!block_transform_notify && notify_local_transform) notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
+ }
- _FORCE_INLINE_ void _notify_transform() { if (!is_inside_tree()) return; _notify_transform(this); if (!block_transform_notify && notify_local_transform) notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED); }
-
- void item_rect_changed(bool p_size_changed=true);
+ void item_rect_changed(bool p_size_changed = true);
void _notification(int p_what);
static void _bind_methods();
-public:
-
+public:
enum {
- NOTIFICATION_TRANSFORM_CHANGED=SceneTree::NOTIFICATION_TRANSFORM_CHANGED, //unique
- NOTIFICATION_DRAW=30,
- NOTIFICATION_VISIBILITY_CHANGED=31,
- NOTIFICATION_ENTER_CANVAS=32,
- NOTIFICATION_EXIT_CANVAS=33,
- NOTIFICATION_LOCAL_TRANSFORM_CHANGED=35,
- NOTIFICATION_WORLD_2D_CHANGED=36,
+ NOTIFICATION_TRANSFORM_CHANGED = SceneTree::NOTIFICATION_TRANSFORM_CHANGED, //unique
+ NOTIFICATION_DRAW = 30,
+ NOTIFICATION_VISIBILITY_CHANGED = 31,
+ NOTIFICATION_ENTER_CANVAS = 32,
+ NOTIFICATION_EXIT_CANVAS = 33,
+ NOTIFICATION_LOCAL_TRANSFORM_CHANGED = 35,
+ NOTIFICATION_WORLD_2D_CHANGED = 36,
};
/* EDITOR */
virtual Variant edit_get_state() const;
- virtual void edit_set_state(const Variant& p_state);
- virtual void edit_set_rect(const Rect2& p_edit_rect);
+ virtual void edit_set_state(const Variant &p_state);
+ virtual void edit_set_rect(const Rect2 &p_edit_rect);
virtual void edit_rotate(float p_rot);
virtual Size2 edit_get_minimum_size() const;
@@ -183,30 +178,30 @@ public:
virtual void set_light_mask(int p_light_mask);
int get_light_mask() const;
- void set_modulate(const Color& p_modulate);
+ void set_modulate(const Color &p_modulate);
Color get_modulate() const;
- void set_self_modulate(const Color& p_self_modulate);
+ void set_self_modulate(const Color &p_self_modulate);
Color get_self_modulate() const;
/* DRAWING API */
- void draw_line(const Point2& p_from, const Point2& p_to, const Color& p_color, float p_width=1.0, bool p_antialiased=false);
- void draw_rect(const Rect2& p_rect, const Color& p_color);
- void draw_circle(const Point2& p_pos, float p_radius, const Color& p_color);
- void draw_texture(const Ref<Texture>& p_texture, const Point2& p_pos, const Color &p_modulate=Color(1,1,1,1));
- void draw_texture_rect(const Ref<Texture>& p_texture, const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false);
- void draw_texture_rect_region(const Ref<Texture>& p_texture,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false);
- void draw_style_box(const Ref<StyleBox>& p_style_box,const Rect2& p_rect);
- void draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, Ref<Texture> p_texture=Ref<Texture>(),float p_width=1);
- void draw_polygon(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), Ref<Texture> p_texture=Ref<Texture>());
- void draw_colored_polygon(const Vector<Point2>& p_points, const Color& p_color,const Vector<Point2>& p_uvs=Vector<Point2>(), Ref<Texture> p_texture=Ref<Texture>());
+ void draw_line(const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false);
+ void draw_rect(const Rect2 &p_rect, const Color &p_color);
+ void draw_circle(const Point2 &p_pos, float p_radius, const Color &p_color);
+ void draw_texture(const Ref<Texture> &p_texture, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1, 1));
+ void draw_texture_rect(const Ref<Texture> &p_texture, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false);
+ void draw_texture_rect_region(const Ref<Texture> &p_texture, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false);
+ void draw_style_box(const Ref<StyleBox> &p_style_box, const Rect2 &p_rect);
+ void draw_primitive(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, Ref<Texture> p_texture = Ref<Texture>(), float p_width = 1);
+ void draw_polygon(const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), Ref<Texture> p_texture = Ref<Texture>());
+ void draw_colored_polygon(const Vector<Point2> &p_points, const Color &p_color, const Vector<Point2> &p_uvs = Vector<Point2>(), Ref<Texture> p_texture = Ref<Texture>());
- void draw_string(const Ref<Font>& p_font, const Point2& p_pos, const String& p_text,const Color& p_modulate=Color(1,1,1),int p_clip_w=-1);
- float draw_char(const Ref<Font>& p_font,const Point2& p_pos, const String& p_char,const String& p_next="",const Color& p_modulate=Color(1,1,1));
+ void draw_string(const Ref<Font> &p_font, const Point2 &p_pos, const String &p_text, const Color &p_modulate = Color(1, 1, 1), int p_clip_w = -1);
+ float draw_char(const Ref<Font> &p_font, const Point2 &p_pos, const String &p_char, const String &p_next = "", const Color &p_modulate = Color(1, 1, 1));
- void draw_set_transform(const Point2& p_offset, float p_rot, const Size2& p_scale);
- void draw_set_transform_matrix(const Transform2D& p_matrix);
+ void draw_set_transform(const Point2 &p_offset, float p_rot, const Size2 &p_scale);
+ void draw_set_transform_matrix(const Transform2D &p_matrix);
/* RECT / TRANSFORM */
@@ -218,8 +213,8 @@ public:
CanvasItem *get_parent_item() const;
- virtual Rect2 get_item_rect() const=0;
- virtual Transform2D get_transform() const=0;
+ virtual Rect2 get_item_rect() const = 0;
+ virtual Transform2D get_transform() const = 0;
virtual Transform2D get_global_transform() const;
virtual Transform2D get_global_transform_with_canvas() const;
@@ -232,7 +227,6 @@ public:
void set_block_transform_notify(bool p_enable);
bool is_block_transform_notify_enabled() const;
-
Transform2D get_canvas_transform() const;
Transform2D get_viewport_transform() const;
Rect2 get_viewport_rect() const;
@@ -240,14 +234,14 @@ public:
RID get_canvas() const;
Ref<World2D> get_world_2d() const;
- void set_material(const Ref<CanvasItemMaterial>& p_material);
+ void set_material(const Ref<CanvasItemMaterial> &p_material);
Ref<CanvasItemMaterial> get_material() const;
void set_use_parent_material(bool p_use_parent_material);
bool get_use_parent_material() const;
- InputEvent make_input_local(const InputEvent& pevent) const;
- Vector2 make_canvas_pos_local(const Vector2& screen_point) const;
+ InputEvent make_input_local(const InputEvent &pevent) const;
+ Vector2 make_canvas_pos_local(const Vector2 &screen_point) const;
Vector2 get_global_mouse_pos() const;
Vector2 get_local_mouse_pos() const;
@@ -264,6 +258,6 @@ public:
~CanvasItem();
};
-VARIANT_ENUM_CAST( CanvasItem::BlendMode );
+VARIANT_ENUM_CAST(CanvasItem::BlendMode);
#endif // CANVAS_ITEM_H
diff --git a/scene/2d/canvas_modulate.cpp b/scene/2d/canvas_modulate.cpp
index ecc11ea60f..a0e3061c85 100644
--- a/scene/2d/canvas_modulate.cpp
+++ b/scene/2d/canvas_modulate.cpp
@@ -28,52 +28,48 @@
/*************************************************************************/
#include "canvas_modulate.h"
-
void CanvasModulate::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_CANVAS) {
+ if (p_what == NOTIFICATION_ENTER_CANVAS) {
if (is_visible_in_tree()) {
- VS::get_singleton()->canvas_set_modulate(get_canvas(),color);
- add_to_group("_canvas_modulate_"+itos(get_canvas().get_id()));
+ VS::get_singleton()->canvas_set_modulate(get_canvas(), color);
+ add_to_group("_canvas_modulate_" + itos(get_canvas().get_id()));
}
-
-
- } else if (p_what==NOTIFICATION_EXIT_CANVAS) {
+ } else if (p_what == NOTIFICATION_EXIT_CANVAS) {
if (is_visible_in_tree()) {
- VS::get_singleton()->canvas_set_modulate(get_canvas(),Color(1,1,1,1));
- remove_from_group("_canvas_modulate_"+itos(get_canvas().get_id()));
+ VS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1));
+ remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id()));
}
- } else if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (is_visible_in_tree()) {
- VS::get_singleton()->canvas_set_modulate(get_canvas(),color);
- add_to_group("_canvas_modulate_"+itos(get_canvas().get_id()));
+ VS::get_singleton()->canvas_set_modulate(get_canvas(), color);
+ add_to_group("_canvas_modulate_" + itos(get_canvas().get_id()));
} else {
- VS::get_singleton()->canvas_set_modulate(get_canvas(),Color(1,1,1,1));
- remove_from_group("_canvas_modulate_"+itos(get_canvas().get_id()));
+ VS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1));
+ remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id()));
}
update_configuration_warning();
}
}
-void CanvasModulate::_bind_methods(){
+void CanvasModulate::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_color","color"),&CanvasModulate::set_color);
- ClassDB::bind_method(D_METHOD("get_color"),&CanvasModulate::get_color);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &CanvasModulate::set_color);
+ ClassDB::bind_method(D_METHOD("get_color"), &CanvasModulate::get_color);
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"color"),"set_color","get_color");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
}
+void CanvasModulate::set_color(const Color &p_color) {
-void CanvasModulate::set_color(const Color& p_color){
-
- color=p_color;
+ color = p_color;
if (is_inside_tree()) {
- VS::get_singleton()->canvas_set_modulate(get_canvas(),color);
+ VS::get_singleton()->canvas_set_modulate(get_canvas(), color);
}
}
Color CanvasModulate::get_color() const {
@@ -86,23 +82,19 @@ String CanvasModulate::get_configuration_warning() const {
if (!is_visible_in_tree() || !is_inside_tree())
return String();
- List<Node*> nodes;
- get_tree()->get_nodes_in_group("_canvas_modulate_"+itos(get_canvas().get_id()),&nodes);
+ List<Node *> nodes;
+ get_tree()->get_nodes_in_group("_canvas_modulate_" + itos(get_canvas().get_id()), &nodes);
- if (nodes.size()>1) {
+ if (nodes.size() > 1) {
return TTR("Only one visible CanvasModulate is allowed per scene (or set of instanced scenes). The first created one will work, while the rest will be ignored.");
}
return String();
}
-CanvasModulate::CanvasModulate()
-{
- color=Color(1,1,1,1);
+CanvasModulate::CanvasModulate() {
+ color = Color(1, 1, 1, 1);
}
-CanvasModulate::~CanvasModulate()
-{
-
+CanvasModulate::~CanvasModulate() {
}
-
diff --git a/scene/2d/canvas_modulate.h b/scene/2d/canvas_modulate.h
index a0bb27b1c5..8e62b5ccb9 100644
--- a/scene/2d/canvas_modulate.h
+++ b/scene/2d/canvas_modulate.h
@@ -33,15 +33,16 @@
class CanvasModulate : public Node2D {
- GDCLASS(CanvasModulate,Node2D);
+ GDCLASS(CanvasModulate, Node2D);
Color color;
+
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_color(const Color& p_color);
+public:
+ void set_color(const Color &p_color);
Color get_color() const;
String get_configuration_warning() const;
diff --git a/scene/2d/collision_object_2d.cpp b/scene/2d/collision_object_2d.cpp
index f9e1cc0bd7..1242599d46 100644
--- a/scene/2d/collision_object_2d.cpp
+++ b/scene/2d/collision_object_2d.cpp
@@ -27,16 +27,16 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "collision_object_2d.h"
-#include "servers/physics_2d_server.h"
#include "scene/scene_string_names.h"
+#include "servers/physics_2d_server.h"
void CollisionObject2D::_update_shapes_from_children() {
shapes.clear();
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Node* n = get_child(i);
- n->call("_add_to_collision_object",this);
+ Node *n = get_child(i);
+ n->call("_add_to_collision_object", this);
}
_update_shapes();
@@ -44,24 +44,24 @@ void CollisionObject2D::_update_shapes_from_children() {
void CollisionObject2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (area)
- Physics2DServer::get_singleton()->area_set_transform(rid,get_global_transform());
+ Physics2DServer::get_singleton()->area_set_transform(rid, get_global_transform());
else
- Physics2DServer::get_singleton()->body_set_state(rid,Physics2DServer::BODY_STATE_TRANSFORM,get_global_transform());
+ Physics2DServer::get_singleton()->body_set_state(rid, Physics2DServer::BODY_STATE_TRANSFORM, get_global_transform());
RID space = get_world_2d()->get_space();
if (area) {
- Physics2DServer::get_singleton()->area_set_space(rid,space);
+ Physics2DServer::get_singleton()->area_set_space(rid, space);
} else
- Physics2DServer::get_singleton()->body_set_space(rid,space);
+ Physics2DServer::get_singleton()->body_set_space(rid, space);
_update_pickable();
- //get space
+ //get space
}
case NOTIFICATION_VISIBILITY_CHANGED: {
@@ -71,17 +71,17 @@ void CollisionObject2D::_notification(int p_what) {
case NOTIFICATION_TRANSFORM_CHANGED: {
if (area)
- Physics2DServer::get_singleton()->area_set_transform(rid,get_global_transform());
+ Physics2DServer::get_singleton()->area_set_transform(rid, get_global_transform());
else
- Physics2DServer::get_singleton()->body_set_state(rid,Physics2DServer::BODY_STATE_TRANSFORM,get_global_transform());
+ Physics2DServer::get_singleton()->body_set_state(rid, Physics2DServer::BODY_STATE_TRANSFORM, get_global_transform());
} break;
case NOTIFICATION_EXIT_TREE: {
if (area) {
- Physics2DServer::get_singleton()->area_set_space(rid,RID());
+ Physics2DServer::get_singleton()->area_set_space(rid, RID());
} else
- Physics2DServer::get_singleton()->body_set_space(rid,RID());
+ Physics2DServer::get_singleton()->body_set_space(rid, RID());
} break;
}
@@ -97,84 +97,80 @@ void CollisionObject2D::_update_shapes() {
else
Physics2DServer::get_singleton()->body_clear_shapes(rid);
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
if (shapes[i].shape.is_null())
continue;
if (area)
- Physics2DServer::get_singleton()->area_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform);
+ Physics2DServer::get_singleton()->area_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform);
else {
- Physics2DServer::get_singleton()->body_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform);
+ Physics2DServer::get_singleton()->body_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform);
if (shapes[i].trigger)
- Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid,i,shapes[i].trigger);
+ Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid, i, shapes[i].trigger);
}
}
}
-
-bool CollisionObject2D::_set(const StringName& p_name, const Variant& p_value) {
- String name=p_name;
+bool CollisionObject2D::_set(const StringName &p_name, const Variant &p_value) {
+ String name = p_name;
if (name.begins_with("shapes/")) {
- int idx=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="shape") {
- if (idx>=shapes.size())
+ int idx = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "shape") {
+ if (idx >= shapes.size())
add_shape(RefPtr(p_value));
else
- set_shape(idx,RefPtr(p_value));
- } else if (what=="transform")
- set_shape_transform(idx,p_value);
- else if (what=="trigger")
- set_shape_as_trigger(idx,p_value);
+ set_shape(idx, RefPtr(p_value));
+ } else if (what == "transform")
+ set_shape_transform(idx, p_value);
+ else if (what == "trigger")
+ set_shape_as_trigger(idx, p_value);
} else
return false;
return true;
-
-
}
-bool CollisionObject2D::_get(const StringName& p_name,Variant &r_ret) const {
+bool CollisionObject2D::_get(const StringName &p_name, Variant &r_ret) const {
- String name=p_name;
+ String name = p_name;
if (name.begins_with("shapes/")) {
- int idx=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="shape")
- r_ret= get_shape(idx);
- else if (what=="transform")
- r_ret= get_shape_transform(idx);
- else if (what=="trigger")
- r_ret= is_shape_set_as_trigger(idx);
+ int idx = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "shape")
+ r_ret = get_shape(idx);
+ else if (what == "transform")
+ r_ret = get_shape_transform(idx);
+ else if (what == "trigger")
+ r_ret = is_shape_set_as_trigger(idx);
} else
return false;
return true;
}
-void CollisionObject2D::_get_property_list( List<PropertyInfo> *p_list) const {
+void CollisionObject2D::_get_property_list(List<PropertyInfo> *p_list) const {
//p_list->push_back( PropertyInfo(Variant::INT,"shape_count",PROPERTY_HINT_RANGE,"0,256,1",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
- for(int i=0;i<shapes.size();i++) {
- String path="shapes/"+itos(i)+"/";
- p_list->push_back( PropertyInfo(Variant::OBJECT,path+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
- p_list->push_back( PropertyInfo(Variant::TRANSFORM,path+"transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
- p_list->push_back( PropertyInfo(Variant::BOOL,path+"trigger",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
+ for (int i = 0; i < shapes.size(); i++) {
+ String path = "shapes/" + itos(i) + "/";
+ p_list->push_back(PropertyInfo(Variant::OBJECT, path + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM, path + "transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
+ p_list->push_back(PropertyInfo(Variant::BOOL, path + "trigger", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
}
}
-
void CollisionObject2D::set_pickable(bool p_enabled) {
- if (pickable==p_enabled)
+ if (pickable == p_enabled)
return;
- pickable=p_enabled;
+ pickable = p_enabled;
_update_pickable();
}
@@ -183,12 +179,12 @@ bool CollisionObject2D::is_pickable() const {
return pickable;
}
-void CollisionObject2D::_input_event(Node *p_viewport, const InputEvent& p_input_event, int p_shape) {
+void CollisionObject2D::_input_event(Node *p_viewport, const InputEvent &p_input_event, int p_shape) {
if (get_script_instance()) {
- get_script_instance()->call(SceneStringNames::get_singleton()->_input_event,p_viewport,p_input_event,p_shape);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_input_event, p_viewport, p_input_event, p_shape);
}
- emit_signal(SceneStringNames::get_singleton()->input_event,p_viewport,p_input_event,p_shape);
+ emit_signal(SceneStringNames::get_singleton()->input_event, p_viewport, p_input_event, p_shape);
}
void CollisionObject2D::_mouse_enter() {
@@ -199,14 +195,12 @@ void CollisionObject2D::_mouse_enter() {
emit_signal(SceneStringNames::get_singleton()->mouse_entered);
}
-
void CollisionObject2D::_mouse_exit() {
if (get_script_instance()) {
get_script_instance()->call(SceneStringNames::get_singleton()->_mouse_exit);
}
emit_signal(SceneStringNames::get_singleton()->mouse_exited);
-
}
void CollisionObject2D::_update_pickable() {
@@ -214,105 +208,99 @@ void CollisionObject2D::_update_pickable() {
return;
bool pickable = this->pickable && is_inside_tree() && is_visible_in_tree();
if (area)
- Physics2DServer::get_singleton()->area_set_pickable(rid,pickable);
+ Physics2DServer::get_singleton()->area_set_pickable(rid, pickable);
else
- Physics2DServer::get_singleton()->body_set_pickable(rid,pickable);
+ Physics2DServer::get_singleton()->body_set_pickable(rid, pickable);
}
void CollisionObject2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_shape","shape:Shape2D","transform"),&CollisionObject2D::add_shape,DEFVAL(Transform2D()));
- ClassDB::bind_method(D_METHOD("get_shape_count"),&CollisionObject2D::get_shape_count);
- ClassDB::bind_method(D_METHOD("set_shape","shape_idx","shape:Shape"),&CollisionObject2D::set_shape);
- ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject2D::set_shape_transform);
- ClassDB::bind_method(D_METHOD("set_shape_as_trigger","shape_idx","enable"),&CollisionObject2D::set_shape_as_trigger);
- ClassDB::bind_method(D_METHOD("get_shape:Shape2D","shape_idx"),&CollisionObject2D::get_shape);
- ClassDB::bind_method(D_METHOD("get_shape_transform","shape_idx"),&CollisionObject2D::get_shape_transform);
- ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger","shape_idx"),&CollisionObject2D::is_shape_set_as_trigger);
- ClassDB::bind_method(D_METHOD("remove_shape","shape_idx"),&CollisionObject2D::remove_shape);
- ClassDB::bind_method(D_METHOD("clear_shapes"),&CollisionObject2D::clear_shapes);
- ClassDB::bind_method(D_METHOD("get_rid"),&CollisionObject2D::get_rid);
-
- ClassDB::bind_method(D_METHOD("set_pickable","enabled"),&CollisionObject2D::set_pickable);
- ClassDB::bind_method(D_METHOD("is_pickable"),&CollisionObject2D::is_pickable);
-
- BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::OBJECT,"viewport"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::INT,"shape_idx")));
-
- ADD_SIGNAL( MethodInfo("input_event",PropertyInfo(Variant::OBJECT,"viewport"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::INT,"shape_idx")));
- ADD_SIGNAL( MethodInfo("mouse_entered"));
- ADD_SIGNAL( MethodInfo("mouse_exited"));
-
- ADD_GROUP("Pickable","input_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"input_pickable"),"set_pickable","is_pickable");
- ADD_GROUP("","");
-
+ ClassDB::bind_method(D_METHOD("add_shape", "shape:Shape2D", "transform"), &CollisionObject2D::add_shape, DEFVAL(Transform2D()));
+ ClassDB::bind_method(D_METHOD("get_shape_count"), &CollisionObject2D::get_shape_count);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape_idx", "shape:Shape"), &CollisionObject2D::set_shape);
+ ClassDB::bind_method(D_METHOD("set_shape_transform", "shape_idx", "transform"), &CollisionObject2D::set_shape_transform);
+ ClassDB::bind_method(D_METHOD("set_shape_as_trigger", "shape_idx", "enable"), &CollisionObject2D::set_shape_as_trigger);
+ ClassDB::bind_method(D_METHOD("get_shape:Shape2D", "shape_idx"), &CollisionObject2D::get_shape);
+ ClassDB::bind_method(D_METHOD("get_shape_transform", "shape_idx"), &CollisionObject2D::get_shape_transform);
+ ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger", "shape_idx"), &CollisionObject2D::is_shape_set_as_trigger);
+ ClassDB::bind_method(D_METHOD("remove_shape", "shape_idx"), &CollisionObject2D::remove_shape);
+ ClassDB::bind_method(D_METHOD("clear_shapes"), &CollisionObject2D::clear_shapes);
+ ClassDB::bind_method(D_METHOD("get_rid"), &CollisionObject2D::get_rid);
+
+ ClassDB::bind_method(D_METHOD("set_pickable", "enabled"), &CollisionObject2D::set_pickable);
+ ClassDB::bind_method(D_METHOD("is_pickable"), &CollisionObject2D::is_pickable);
+
+ BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::OBJECT, "viewport"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::INT, "shape_idx")));
+
+ ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "viewport"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::INT, "shape_idx")));
+ ADD_SIGNAL(MethodInfo("mouse_entered"));
+ ADD_SIGNAL(MethodInfo("mouse_exited"));
+
+ ADD_GROUP("Pickable", "input_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_pickable"), "set_pickable", "is_pickable");
+ ADD_GROUP("", "");
}
-
-void CollisionObject2D::add_shape(const Ref<Shape2D>& p_shape, const Transform2D& p_transform) {
+void CollisionObject2D::add_shape(const Ref<Shape2D> &p_shape, const Transform2D &p_transform) {
ERR_FAIL_COND(p_shape.is_null());
ShapeData sdata;
- sdata.shape=p_shape;
- sdata.xform=p_transform;
- sdata.trigger=false;
+ sdata.shape = p_shape;
+ sdata.xform = p_transform;
+ sdata.trigger = false;
if (area)
- Physics2DServer::get_singleton()->area_add_shape(get_rid(),p_shape->get_rid(),p_transform);
+ Physics2DServer::get_singleton()->area_add_shape(get_rid(), p_shape->get_rid(), p_transform);
else
- Physics2DServer::get_singleton()->body_add_shape(get_rid(),p_shape->get_rid(),p_transform);
+ Physics2DServer::get_singleton()->body_add_shape(get_rid(), p_shape->get_rid(), p_transform);
shapes.push_back(sdata);
-
}
int CollisionObject2D::get_shape_count() const {
return shapes.size();
-
}
-void CollisionObject2D::set_shape(int p_shape_idx, const Ref<Shape2D>& p_shape) {
+void CollisionObject2D::set_shape(int p_shape_idx, const Ref<Shape2D> &p_shape) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
ERR_FAIL_COND(p_shape.is_null());
- shapes[p_shape_idx].shape=p_shape;
+ shapes[p_shape_idx].shape = p_shape;
if (area)
- Physics2DServer::get_singleton()->area_set_shape(get_rid(),p_shape_idx,p_shape->get_rid());
+ Physics2DServer::get_singleton()->area_set_shape(get_rid(), p_shape_idx, p_shape->get_rid());
else
- Physics2DServer::get_singleton()->body_set_shape(get_rid(),p_shape_idx,p_shape->get_rid());
+ Physics2DServer::get_singleton()->body_set_shape(get_rid(), p_shape_idx, p_shape->get_rid());
//_update_shapes();
}
-void CollisionObject2D::set_shape_transform(int p_shape_idx, const Transform2D& p_transform) {
+void CollisionObject2D::set_shape_transform(int p_shape_idx, const Transform2D &p_transform) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
- shapes[p_shape_idx].xform=p_transform;
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
+ shapes[p_shape_idx].xform = p_transform;
if (area)
- Physics2DServer::get_singleton()->area_set_shape_transform(get_rid(),p_shape_idx,p_transform);
+ Physics2DServer::get_singleton()->area_set_shape_transform(get_rid(), p_shape_idx, p_transform);
else
- Physics2DServer::get_singleton()->body_set_shape_transform(get_rid(),p_shape_idx,p_transform);
+ Physics2DServer::get_singleton()->body_set_shape_transform(get_rid(), p_shape_idx, p_transform);
//_update_shapes();
}
Ref<Shape2D> CollisionObject2D::get_shape(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Ref<Shape2D>());
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Ref<Shape2D>());
return shapes[p_shape_idx].shape;
-
}
Transform2D CollisionObject2D::get_shape_transform(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Transform2D());
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Transform2D());
return shapes[p_shape_idx].xform;
-
}
void CollisionObject2D::remove_shape(int p_shape_idx) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
shapes.remove(p_shape_idx);
_update_shapes();
@@ -320,18 +308,17 @@ void CollisionObject2D::remove_shape(int p_shape_idx) {
void CollisionObject2D::set_shape_as_trigger(int p_shape_idx, bool p_trigger) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
- shapes[p_shape_idx].trigger=p_trigger;
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
+ shapes[p_shape_idx].trigger = p_trigger;
if (!area && rid.is_valid()) {
- Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid,p_shape_idx,p_trigger);
-
+ Physics2DServer::get_singleton()->body_set_shape_as_trigger(rid, p_shape_idx, p_trigger);
}
}
bool CollisionObject2D::is_shape_set_as_trigger(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),false);
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), false);
return shapes[p_shape_idx].trigger;
}
@@ -342,32 +329,25 @@ void CollisionObject2D::clear_shapes() {
_update_shapes();
}
-
CollisionObject2D::CollisionObject2D(RID p_rid, bool p_area) {
- rid=p_rid;
- area=p_area;
- pickable=true;
+ rid = p_rid;
+ area = p_area;
+ pickable = true;
set_notify_transform(true);
if (p_area) {
- Physics2DServer::get_singleton()->area_attach_object_instance_ID(rid,get_instance_ID());
+ Physics2DServer::get_singleton()->area_attach_object_instance_ID(rid, get_instance_ID());
} else {
- Physics2DServer::get_singleton()->body_attach_object_instance_ID(rid,get_instance_ID());
+ Physics2DServer::get_singleton()->body_attach_object_instance_ID(rid, get_instance_ID());
}
-
-
}
-
CollisionObject2D::CollisionObject2D() {
-
//owner=
set_notify_transform(true);
-
-
}
CollisionObject2D::~CollisionObject2D() {
diff --git a/scene/2d/collision_object_2d.h b/scene/2d/collision_object_2d.h
index 429b4fafe6..e6ea0f42d3 100644
--- a/scene/2d/collision_object_2d.h
+++ b/scene/2d/collision_object_2d.h
@@ -34,7 +34,7 @@
class CollisionObject2D : public Node2D {
- GDCLASS( CollisionObject2D, Node2D );
+ GDCLASS(CollisionObject2D, Node2D);
bool area;
RID rid;
@@ -46,42 +46,38 @@ class CollisionObject2D : public Node2D {
bool trigger;
ShapeData() {
- trigger=false;
+ trigger = false;
}
};
-
Vector<ShapeData> shapes;
void _update_shapes();
-friend class CollisionShape2D;
-friend class CollisionPolygon2D;
+ friend class CollisionShape2D;
+ friend class CollisionPolygon2D;
void _update_shapes_from_children();
-protected:
+protected:
CollisionObject2D(RID p_rid, bool p_area);
void _notification(int p_what);
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
void _update_pickable();
-friend class Viewport;
- void _input_event(Node *p_viewport, const InputEvent& p_input_event, int p_shape);
+ friend class Viewport;
+ void _input_event(Node *p_viewport, const InputEvent &p_input_event, int p_shape);
void _mouse_enter();
void _mouse_exit();
public:
-
-
-
- void add_shape(const Ref<Shape2D>& p_shape, const Transform2D& p_transform=Transform2D());
+ void add_shape(const Ref<Shape2D> &p_shape, const Transform2D &p_transform = Transform2D());
int get_shape_count() const;
- void set_shape(int p_shape_idx, const Ref<Shape2D>& p_shape);
- void set_shape_transform(int p_shape_idx, const Transform2D& p_transform);
+ void set_shape(int p_shape_idx, const Ref<Shape2D> &p_shape);
+ void set_shape_transform(int p_shape_idx, const Transform2D &p_transform);
Ref<Shape2D> get_shape(int p_shape_idx) const;
Transform2D get_shape_transform(int p_shape_idx) const;
void set_shape_as_trigger(int p_shape_idx, bool p_trigger);
diff --git a/scene/2d/collision_polygon_2d.cpp b/scene/2d/collision_polygon_2d.cpp
index 85241a79e0..abc044f10f 100644
--- a/scene/2d/collision_polygon_2d.cpp
+++ b/scene/2d/collision_polygon_2d.cpp
@@ -39,57 +39,54 @@ void CollisionPolygon2D::_add_to_collision_object(Object *p_obj) {
CollisionObject2D *co = p_obj->cast_to<CollisionObject2D>();
ERR_FAIL_COND(!co);
- if (polygon.size()==0)
+ if (polygon.size() == 0)
return;
- bool solids=build_mode==BUILD_SOLIDS;
+ bool solids = build_mode == BUILD_SOLIDS;
if (solids) {
//here comes the sun, lalalala
//decompose concave into multiple convex polygons and add them
- Vector< Vector<Vector2> > decomp = _decompose_in_convex();
- shape_from=co->get_shape_count();
- for(int i=0;i<decomp.size();i++) {
- Ref<ConvexPolygonShape2D> convex = memnew( ConvexPolygonShape2D );
+ Vector<Vector<Vector2> > decomp = _decompose_in_convex();
+ shape_from = co->get_shape_count();
+ for (int i = 0; i < decomp.size(); i++) {
+ Ref<ConvexPolygonShape2D> convex = memnew(ConvexPolygonShape2D);
convex->set_points(decomp[i]);
- co->add_shape(convex,get_transform());
+ co->add_shape(convex, get_transform());
if (trigger)
- co->set_shape_as_trigger(co->get_shape_count()-1,true);
-
+ co->set_shape_as_trigger(co->get_shape_count() - 1, true);
}
- shape_to=co->get_shape_count()-1;
- if (shape_to<shape_from) {
- shape_from=-1;
- shape_to=-1;
+ shape_to = co->get_shape_count() - 1;
+ if (shape_to < shape_from) {
+ shape_from = -1;
+ shape_to = -1;
}
} else {
- Ref<ConcavePolygonShape2D> concave = memnew( ConcavePolygonShape2D );
+ Ref<ConcavePolygonShape2D> concave = memnew(ConcavePolygonShape2D);
PoolVector<Vector2> segments;
- segments.resize(polygon.size()*2);
- PoolVector<Vector2>::Write w=segments.write();
+ segments.resize(polygon.size() * 2);
+ PoolVector<Vector2>::Write w = segments.write();
- for(int i=0;i<polygon.size();i++) {
- w[(i<<1)+0]=polygon[i];
- w[(i<<1)+1]=polygon[(i+1)%polygon.size()];
+ for (int i = 0; i < polygon.size(); i++) {
+ w[(i << 1) + 0] = polygon[i];
+ w[(i << 1) + 1] = polygon[(i + 1) % polygon.size()];
}
- w=PoolVector<Vector2>::Write();
+ w = PoolVector<Vector2>::Write();
concave->set_segments(segments);
- co->add_shape(concave,get_transform());
+ co->add_shape(concave, get_transform());
if (trigger)
- co->set_shape_as_trigger(co->get_shape_count()-1,true);
-
- shape_from=co->get_shape_count()-1;
- shape_to=co->get_shape_count()-1;
+ co->set_shape_as_trigger(co->get_shape_count() - 1, true);
+ shape_from = co->get_shape_count() - 1;
+ shape_to = co->get_shape_count() - 1;
}
-
//co->add_shape(shape,get_transform());
}
@@ -106,41 +103,41 @@ void CollisionPolygon2D::_update_parent() {
co->_update_shapes_from_children();
}
-Vector< Vector<Vector2> > CollisionPolygon2D::_decompose_in_convex() {
+Vector<Vector<Vector2> > CollisionPolygon2D::_decompose_in_convex() {
- Vector< Vector<Vector2> > decomp;
+ Vector<Vector<Vector2> > decomp;
#if 0
//fast but imprecise triangulator, gave us problems
decomp = Geometry::decompose_polygon(polygon);
#else
- List<TriangulatorPoly> in_poly,out_poly;
+ List<TriangulatorPoly> in_poly, out_poly;
TriangulatorPoly inp;
inp.Init(polygon.size());
- for(int i=0;i<polygon.size();i++) {
- inp.GetPoint(i)=polygon[i];
+ for (int i = 0; i < polygon.size(); i++) {
+ inp.GetPoint(i) = polygon[i];
}
inp.SetOrientation(TRIANGULATOR_CCW);
in_poly.push_back(inp);
TriangulatorPartition tpart;
- if (tpart.ConvexPartition_HM(&in_poly,&out_poly)==0) { //failed!
+ if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed!
ERR_PRINT("Convex decomposing failed!");
return decomp;
}
decomp.resize(out_poly.size());
- int idx=0;
+ int idx = 0;
- for(List<TriangulatorPoly>::Element*I = out_poly.front();I;I=I->next()) {
+ for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
- TriangulatorPoly& tp = I->get();
+ TriangulatorPoly &tp = I->get();
decomp[idx].resize(tp.GetNumPoints());
- for(int i=0;i<tp.GetNumPoints();i++) {
+ for (int i = 0; i < tp.GetNumPoints(); i++) {
- decomp[idx][i]=tp.GetPoint(i);
+ decomp[idx][i] = tp.GetPoint(i);
}
idx++;
@@ -153,20 +150,19 @@ Vector< Vector<Vector2> > CollisionPolygon2D::_decompose_in_convex() {
void CollisionPolygon2D::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- unparenting=false;
- can_update_body=get_tree()->is_editor_hint();
+ unparenting = false;
+ can_update_body = get_tree()->is_editor_hint();
if (!get_tree()->is_editor_hint()) {
//display above all else
set_z_as_relative(false);
- set_z(VS::CANVAS_ITEM_Z_MAX-1);
+ set_z(VS::CANVAS_ITEM_Z_MAX - 1);
}
} break;
case NOTIFICATION_EXIT_TREE: {
- can_update_body=false;
+ can_update_body = false;
} break;
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
@@ -174,14 +170,13 @@ void CollisionPolygon2D::_notification(int p_what) {
break;
if (can_update_body) {
_update_parent();
- } else if (shape_from>=0 && shape_to>=0) {
+ } else if (shape_from >= 0 && shape_to >= 0) {
CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
- for(int i=shape_from;i<=shape_to;i++) {
- co->set_shape_transform(i,get_transform());
+ for (int i = shape_from; i <= shape_to; i++) {
+ co->set_shape_transform(i, get_transform());
}
}
-
} break;
case NOTIFICATION_DRAW: {
@@ -190,55 +185,52 @@ void CollisionPolygon2D::_notification(int p_what) {
break;
}
-
- for(int i=0;i<polygon.size();i++) {
+ for (int i = 0; i < polygon.size(); i++) {
Vector2 p = polygon[i];
- Vector2 n = polygon[(i+1)%polygon.size()];
- draw_line(p,n,Color(0.9,0.2,0.0,0.8),3);
+ Vector2 n = polygon[(i + 1) % polygon.size()];
+ draw_line(p, n, Color(0.9, 0.2, 0.0, 0.8), 3);
}
#define DEBUG_DECOMPOSE
-#if defined(TOOLS_ENABLED) && defined (DEBUG_DECOMPOSE)
+#if defined(TOOLS_ENABLED) && defined(DEBUG_DECOMPOSE)
- Vector< Vector<Vector2> > decomp = _decompose_in_convex();
+ Vector<Vector<Vector2> > decomp = _decompose_in_convex();
- Color c(0.4,0.9,0.1);
- for(int i=0;i<decomp.size();i++) {
+ Color c(0.4, 0.9, 0.1);
+ for (int i = 0; i < decomp.size(); i++) {
- c.set_hsv( Math::fmod(c.get_h() + 0.738,1),c.get_s(),c.get_v(),0.5);
- draw_colored_polygon(decomp[i],c);
+ c.set_hsv(Math::fmod(c.get_h() + 0.738, 1), c.get_s(), c.get_v(), 0.5);
+ draw_colored_polygon(decomp[i], c);
}
#else
- draw_colored_polygon(polygon,get_tree()->get_debug_collisions_color());
+ draw_colored_polygon(polygon, get_tree()->get_debug_collisions_color());
#endif
-
} break;
case NOTIFICATION_UNPARENTED: {
unparenting = true;
_update_parent();
} break;
-
}
}
-void CollisionPolygon2D::set_polygon(const Vector<Point2>& p_polygon) {
+void CollisionPolygon2D::set_polygon(const Vector<Point2> &p_polygon) {
- polygon=p_polygon;
+ polygon = p_polygon;
if (can_update_body) {
- for(int i=0;i<polygon.size();i++) {
- if (i==0)
- aabb=Rect2(polygon[i],Size2());
+ for (int i = 0; i < polygon.size(); i++) {
+ if (i == 0)
+ aabb = Rect2(polygon[i], Size2());
else
aabb.expand_to(polygon[i]);
}
- if (aabb==Rect2()) {
+ if (aabb == Rect2()) {
- aabb=Rect2(-10,-10,20,20);
+ aabb = Rect2(-10, -10, 20, 20);
} else {
- aabb.pos-=aabb.size*0.3;
- aabb.size+=aabb.size*0.6;
+ aabb.pos -= aabb.size * 0.3;
+ aabb.size += aabb.size * 0.6;
}
_update_parent();
}
@@ -253,12 +245,12 @@ Vector<Point2> CollisionPolygon2D::get_polygon() const {
void CollisionPolygon2D::set_build_mode(BuildMode p_mode) {
- ERR_FAIL_INDEX(p_mode,2);
- build_mode=p_mode;
+ ERR_FAIL_INDEX(p_mode, 2);
+ build_mode = p_mode;
_update_parent();
}
-CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const{
+CollisionPolygon2D::BuildMode CollisionPolygon2D::get_build_mode() const {
return build_mode;
}
@@ -270,32 +262,30 @@ Rect2 CollisionPolygon2D::get_item_rect() const {
void CollisionPolygon2D::set_trigger(bool p_trigger) {
- trigger=p_trigger;
+ trigger = p_trigger;
_update_parent();
- if (!can_update_body && is_inside_tree() && shape_from>=0 && shape_to>=0) {
+ if (!can_update_body && is_inside_tree() && shape_from >= 0 && shape_to >= 0) {
CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
- for(int i=shape_from;i<=shape_to;i++) {
- co->set_shape_as_trigger(i,p_trigger);
+ for (int i = shape_from; i <= shape_to; i++) {
+ co->set_shape_as_trigger(i, p_trigger);
}
-
}
}
-bool CollisionPolygon2D::is_trigger() const{
+bool CollisionPolygon2D::is_trigger() const {
return trigger;
}
+void CollisionPolygon2D::_set_shape_range(const Vector2 &p_range) {
-void CollisionPolygon2D::_set_shape_range(const Vector2& p_range) {
-
- shape_from=p_range.x;
- shape_to=p_range.y;
+ shape_from = p_range.x;
+ shape_to = p_range.y;
}
Vector2 CollisionPolygon2D::_get_shape_range() const {
- return Vector2(shape_from,shape_to);
+ return Vector2(shape_from, shape_to);
}
String CollisionPolygon2D::get_configuration_warning() const {
@@ -306,7 +296,6 @@ String CollisionPolygon2D::get_configuration_warning() const {
if (polygon.empty()) {
return TTR("An empty CollisionPolygon2D has no effect on collision.");
-
}
return String();
@@ -314,38 +303,36 @@ String CollisionPolygon2D::get_configuration_warning() const {
void CollisionPolygon2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionPolygon2D::_add_to_collision_object);
- ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&CollisionPolygon2D::set_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon"),&CollisionPolygon2D::get_polygon);
-
- ClassDB::bind_method(D_METHOD("set_build_mode","build_mode"),&CollisionPolygon2D::set_build_mode);
- ClassDB::bind_method(D_METHOD("get_build_mode"),&CollisionPolygon2D::get_build_mode);
+ ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionPolygon2D::_add_to_collision_object);
+ ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon2D::set_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon2D::get_polygon);
- ClassDB::bind_method(D_METHOD("set_trigger","trigger"),&CollisionPolygon2D::set_trigger);
- ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionPolygon2D::is_trigger);
+ ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon2D::set_build_mode);
+ ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon2D::get_build_mode);
- ClassDB::bind_method(D_METHOD("_set_shape_range","shape_range"),&CollisionPolygon2D::_set_shape_range);
- ClassDB::bind_method(D_METHOD("_get_shape_range"),&CollisionPolygon2D::_get_shape_range);
+ ClassDB::bind_method(D_METHOD("set_trigger", "trigger"), &CollisionPolygon2D::set_trigger);
+ ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionPolygon2D::is_trigger);
- ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"),&CollisionPolygon2D::get_collision_object_first_shape);
- ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"),&CollisionPolygon2D::get_collision_object_last_shape);
+ ClassDB::bind_method(D_METHOD("_set_shape_range", "shape_range"), &CollisionPolygon2D::_set_shape_range);
+ ClassDB::bind_method(D_METHOD("_get_shape_range"), &CollisionPolygon2D::_get_shape_range);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"build_mode",PROPERTY_HINT_ENUM,"Solids,Segments"),"set_build_mode","get_build_mode");
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"shape_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_shape_range","_get_shape_range");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger");
+ ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"), &CollisionPolygon2D::get_collision_object_first_shape);
+ ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"), &CollisionPolygon2D::get_collision_object_last_shape);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Segments"), "set_build_mode", "get_build_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "shape_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_shape_range", "_get_shape_range");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger");
}
CollisionPolygon2D::CollisionPolygon2D() {
- aabb=Rect2(-10,-10,20,20);
- build_mode=BUILD_SOLIDS;
- trigger=false;
- unparenting=false;
- shape_from=-1;
- shape_to=-1;
- can_update_body=false;
+ aabb = Rect2(-10, -10, 20, 20);
+ build_mode = BUILD_SOLIDS;
+ trigger = false;
+ unparenting = false;
+ shape_from = -1;
+ shape_to = -1;
+ can_update_body = false;
set_notify_local_transform(true);
-
}
diff --git a/scene/2d/collision_polygon_2d.h b/scene/2d/collision_polygon_2d.h
index dda850b41d..f1f31a2854 100644
--- a/scene/2d/collision_polygon_2d.h
+++ b/scene/2d/collision_polygon_2d.h
@@ -32,21 +32,17 @@
#include "scene/2d/node_2d.h"
#include "scene/resources/shape_2d.h"
-
-
class CollisionPolygon2D : public Node2D {
- GDCLASS(CollisionPolygon2D,Node2D);
-public:
+ GDCLASS(CollisionPolygon2D, Node2D);
+public:
enum BuildMode {
BUILD_SOLIDS,
BUILD_SEGMENTS,
};
protected:
-
-
Rect2 aabb;
BuildMode build_mode;
Vector<Point2> polygon;
@@ -60,24 +56,23 @@ protected:
int shape_from;
int shape_to;
- void _set_shape_range(const Vector2& p_range);
+ void _set_shape_range(const Vector2 &p_range);
Vector2 _get_shape_range() const;
- Vector< Vector<Vector2> > _decompose_in_convex();
+ Vector<Vector<Vector2> > _decompose_in_convex();
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_trigger(bool p_trigger);
bool is_trigger() const;
void set_build_mode(BuildMode p_mode);
BuildMode get_build_mode() const;
- void set_polygon(const Vector<Point2>& p_polygon);
+ void set_polygon(const Vector<Point2> &p_polygon);
Vector<Point2> get_polygon() const;
virtual Rect2 get_item_rect() const;
@@ -90,6 +85,6 @@ public:
CollisionPolygon2D();
};
-VARIANT_ENUM_CAST( CollisionPolygon2D::BuildMode );
+VARIANT_ENUM_CAST(CollisionPolygon2D::BuildMode);
#endif // COLLISION_POLYGON_2D_H
diff --git a/scene/2d/collision_shape_2d.cpp b/scene/2d/collision_shape_2d.cpp
index 37a49577b5..39e0017e92 100644
--- a/scene/2d/collision_shape_2d.cpp
+++ b/scene/2d/collision_shape_2d.cpp
@@ -28,14 +28,13 @@
/*************************************************************************/
#include "collision_shape_2d.h"
#include "collision_object_2d.h"
-#include "scene/resources/segment_shape_2d.h"
-#include "scene/resources/shape_line_2d.h"
-#include "scene/resources/circle_shape_2d.h"
-#include "scene/resources/rectangle_shape_2d.h"
#include "scene/resources/capsule_shape_2d.h"
-#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/circle_shape_2d.h"
#include "scene/resources/concave_polygon_shape_2d.h"
-
+#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/rectangle_shape_2d.h"
+#include "scene/resources/segment_shape_2d.h"
+#include "scene/resources/shape_line_2d.h"
void CollisionShape2D::_add_to_collision_object(Object *p_obj) {
@@ -44,12 +43,10 @@ void CollisionShape2D::_add_to_collision_object(Object *p_obj) {
CollisionObject2D *co = p_obj->cast_to<CollisionObject2D>();
ERR_FAIL_COND(!co);
- update_shape_index=co->get_shape_count();
- co->add_shape(shape,get_transform());
+ update_shape_index = co->get_shape_count();
+ co->add_shape(shape, get_transform());
if (trigger)
- co->set_shape_as_trigger(co->get_shape_count()-1,true);
-
-
+ co->set_shape_as_trigger(co->get_shape_count() - 1, true);
}
void CollisionShape2D::_shape_changed() {
@@ -60,7 +57,6 @@ void CollisionShape2D::_shape_changed() {
void CollisionShape2D::_update_parent() {
-
Node *parent = get_parent();
if (!parent)
return;
@@ -72,15 +68,15 @@ void CollisionShape2D::_update_parent() {
void CollisionShape2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- unparenting=false;
- can_update_body=get_tree()->is_editor_hint();
+ unparenting = false;
+ can_update_body = get_tree()->is_editor_hint();
if (!get_tree()->is_editor_hint()) {
//display above all else
set_z_as_relative(false);
- set_z(VS::CANVAS_ITEM_Z_MAX-1);
+ set_z(VS::CANVAS_ITEM_Z_MAX - 1);
}
} break;
@@ -90,18 +86,17 @@ void CollisionShape2D::_notification(int p_what) {
break;
if (can_update_body) {
_update_parent();
- } else if (update_shape_index>=0){
+ } else if (update_shape_index >= 0) {
CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
if (co) {
- co->set_shape_transform(update_shape_index,get_transform());
+ co->set_shape_transform(update_shape_index, get_transform());
}
-
}
} break;
case NOTIFICATION_EXIT_TREE: {
- can_update_body=false;
+ can_update_body = false;
} break;
/*
@@ -122,16 +117,13 @@ void CollisionShape2D::_notification(int p_what) {
break;
}
- rect=Rect2();
-
-
-
- Color draw_col=get_tree()->get_debug_collisions_color();
- shape->draw(get_canvas_item(),draw_col);
+ rect = Rect2();
+ Color draw_col = get_tree()->get_debug_collisions_color();
+ shape->draw(get_canvas_item(), draw_col);
- rect=shape->get_rect();
- rect=rect.grow(3);
+ rect = shape->get_rect();
+ rect = rect.grow(3);
} break;
case NOTIFICATION_UNPARENTED: {
@@ -139,25 +131,24 @@ void CollisionShape2D::_notification(int p_what) {
_update_parent();
} break;
}
-
}
-void CollisionShape2D::set_shape(const Ref<Shape2D>& p_shape) {
+void CollisionShape2D::set_shape(const Ref<Shape2D> &p_shape) {
if (shape.is_valid())
- shape->disconnect("changed",this,"_shape_changed");
- shape=p_shape;
+ shape->disconnect("changed", this, "_shape_changed");
+ shape = p_shape;
update();
if (is_inside_tree() && can_update_body)
_update_parent();
- if (is_inside_tree() && !can_update_body && update_shape_index>=0) {
+ if (is_inside_tree() && !can_update_body && update_shape_index >= 0) {
CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
if (co) {
- co->set_shape(update_shape_index,p_shape);
+ co->set_shape(update_shape_index, p_shape);
}
}
if (shape.is_valid())
- shape->connect("changed",this,"_shape_changed");
+ shape->connect("changed", this, "_shape_changed");
update_configuration_warning();
}
@@ -174,30 +165,28 @@ Rect2 CollisionShape2D::get_item_rect() const {
void CollisionShape2D::set_trigger(bool p_trigger) {
- trigger=p_trigger;
+ trigger = p_trigger;
if (can_update_body) {
_update_parent();
- } else if (is_inside_tree() && update_shape_index>=0){
+ } else if (is_inside_tree() && update_shape_index >= 0) {
CollisionObject2D *co = get_parent()->cast_to<CollisionObject2D>();
if (co) {
- co->set_shape_as_trigger(update_shape_index,p_trigger);
+ co->set_shape_as_trigger(update_shape_index, p_trigger);
}
}
}
-bool CollisionShape2D::is_trigger() const{
+bool CollisionShape2D::is_trigger() const {
return trigger;
}
-
void CollisionShape2D::_set_update_shape_index(int p_index) {
-
- update_shape_index=p_index;
+ update_shape_index = p_index;
}
-int CollisionShape2D::_get_update_shape_index() const{
+int CollisionShape2D::_get_update_shape_index() const {
return update_shape_index;
}
@@ -215,33 +204,31 @@ String CollisionShape2D::get_configuration_warning() const {
return String();
}
-
void CollisionShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shape","shape"),&CollisionShape2D::set_shape);
- ClassDB::bind_method(D_METHOD("get_shape"),&CollisionShape2D::get_shape);
- ClassDB::bind_method(D_METHOD("_shape_changed"),&CollisionShape2D::_shape_changed);
- ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionShape2D::_add_to_collision_object);
- ClassDB::bind_method(D_METHOD("set_trigger","enable"),&CollisionShape2D::set_trigger);
- ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionShape2D::is_trigger);
-
- ClassDB::bind_method(D_METHOD("_set_update_shape_index","index"),&CollisionShape2D::_set_update_shape_index);
- ClassDB::bind_method(D_METHOD("_get_update_shape_index"),&CollisionShape2D::_get_update_shape_index);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape"), &CollisionShape2D::set_shape);
+ ClassDB::bind_method(D_METHOD("get_shape"), &CollisionShape2D::get_shape);
+ ClassDB::bind_method(D_METHOD("_shape_changed"), &CollisionShape2D::_shape_changed);
+ ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionShape2D::_add_to_collision_object);
+ ClassDB::bind_method(D_METHOD("set_trigger", "enable"), &CollisionShape2D::set_trigger);
+ ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionShape2D::is_trigger);
- ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"),&CollisionShape2D::get_collision_object_shape_index);
+ ClassDB::bind_method(D_METHOD("_set_update_shape_index", "index"), &CollisionShape2D::_set_update_shape_index);
+ ClassDB::bind_method(D_METHOD("_get_update_shape_index"), &CollisionShape2D::_get_update_shape_index);
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D"),"set_shape","get_shape");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index");
+ ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"), &CollisionShape2D::get_collision_object_shape_index);
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index");
}
CollisionShape2D::CollisionShape2D() {
- rect=Rect2(-Point2(10,10),Point2(20,20));
+ rect = Rect2(-Point2(10, 10), Point2(20, 20));
set_notify_local_transform(true);
- trigger=false;
+ trigger = false;
unparenting = false;
can_update_body = false;
- update_shape_index=-1;
+ update_shape_index = -1;
}
diff --git a/scene/2d/collision_shape_2d.h b/scene/2d/collision_shape_2d.h
index b5cc789416..a3395cdc1e 100644
--- a/scene/2d/collision_shape_2d.h
+++ b/scene/2d/collision_shape_2d.h
@@ -34,7 +34,7 @@
class CollisionShape2D : public Node2D {
- GDCLASS(CollisionShape2D,Node2D);
+ GDCLASS(CollisionShape2D, Node2D);
Ref<Shape2D> shape;
Rect2 rect;
bool trigger;
@@ -47,15 +47,14 @@ class CollisionShape2D : public Node2D {
int _get_update_shape_index() const;
protected:
-
void _update_parent();
void _notification(int p_what);
static void _bind_methods();
void _add_to_collision_object(Object *p_obj);
-public:
- void set_shape(const Ref<Shape2D>& p_shape);
+public:
+ void set_shape(const Ref<Shape2D> &p_shape);
Ref<Shape2D> get_shape() const;
virtual Rect2 get_item_rect() const;
void set_trigger(bool p_trigger);
diff --git a/scene/2d/joints_2d.cpp b/scene/2d/joints_2d.cpp
index 6754eb3981..96ef714f1b 100644
--- a/scene/2d/joints_2d.cpp
+++ b/scene/2d/joints_2d.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "joints_2d.h"
-#include "servers/physics_2d_server.h"
#include "physics_body_2d.h"
+#include "servers/physics_2d_server.h"
void Joint2D::_update_joint() {
@@ -39,49 +39,41 @@ void Joint2D::_update_joint() {
Physics2DServer::get_singleton()->free(joint);
}
- joint=RID();
-
+ joint = RID();
joint = _configure_joint();
- Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint,Physics2DServer::JOINT_PARAM_BIAS,bias);
-
-
+ Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint, Physics2DServer::JOINT_PARAM_BIAS, bias);
}
+void Joint2D::set_node_a(const NodePath &p_node_a) {
-void Joint2D::set_node_a(const NodePath& p_node_a) {
-
-
- if (a==p_node_a)
+ if (a == p_node_a)
return;
- a=p_node_a;
+ a = p_node_a;
_update_joint();
}
-NodePath Joint2D::get_node_a() const{
+NodePath Joint2D::get_node_a() const {
return a;
}
-void Joint2D::set_node_b(const NodePath& p_node_b){
+void Joint2D::set_node_b(const NodePath &p_node_b) {
- if (b==p_node_b)
+ if (b == p_node_b)
return;
- b=p_node_b;
+ b = p_node_b;
_update_joint();
-
}
-NodePath Joint2D::get_node_b() const{
-
+NodePath Joint2D::get_node_b() const {
return b;
}
-
void Joint2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
_update_joint();
@@ -90,70 +82,61 @@ void Joint2D::_notification(int p_what) {
if (joint.is_valid()) {
Physics2DServer::get_singleton()->free(joint);
- joint=RID();
+ joint = RID();
}
} break;
-
}
-
}
void Joint2D::set_bias(real_t p_bias) {
- bias=p_bias;
+ bias = p_bias;
if (joint.is_valid())
- Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint,Physics2DServer::JOINT_PARAM_BIAS,bias);
+ Physics2DServer::get_singleton()->get_singleton()->joint_set_param(joint, Physics2DServer::JOINT_PARAM_BIAS, bias);
}
-real_t Joint2D::get_bias() const{
-
+real_t Joint2D::get_bias() const {
return bias;
}
void Joint2D::set_exclude_nodes_from_collision(bool p_enable) {
- if (exclude_from_collision==p_enable)
+ if (exclude_from_collision == p_enable)
return;
- exclude_from_collision=p_enable;
+ exclude_from_collision = p_enable;
_update_joint();
}
-bool Joint2D::get_exclude_nodes_from_collision() const{
+bool Joint2D::get_exclude_nodes_from_collision() const {
return exclude_from_collision;
}
-
void Joint2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_node_a", "node"), &Joint2D::set_node_a);
+ ClassDB::bind_method(D_METHOD("get_node_a"), &Joint2D::get_node_a);
- ClassDB::bind_method( D_METHOD("set_node_a","node"), &Joint2D::set_node_a );
- ClassDB::bind_method( D_METHOD("get_node_a"), &Joint2D::get_node_a );
-
- ClassDB::bind_method( D_METHOD("set_node_b","node"), &Joint2D::set_node_b );
- ClassDB::bind_method( D_METHOD("get_node_b"), &Joint2D::get_node_b );
+ ClassDB::bind_method(D_METHOD("set_node_b", "node"), &Joint2D::set_node_b);
+ ClassDB::bind_method(D_METHOD("get_node_b"), &Joint2D::get_node_b);
- ClassDB::bind_method( D_METHOD("set_bias","bias"), &Joint2D::set_bias );
- ClassDB::bind_method( D_METHOD("get_bias"), &Joint2D::get_bias );
-
- ClassDB::bind_method( D_METHOD("set_exclude_nodes_from_collision","enable"), &Joint2D::set_exclude_nodes_from_collision );
- ClassDB::bind_method( D_METHOD("get_exclude_nodes_from_collision"), &Joint2D::get_exclude_nodes_from_collision );
-
- ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "node_a"), "set_node_a","get_node_a") ;
- ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "node_b"), "set_node_b","get_node_b") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "bias",PROPERTY_HINT_RANGE,"0,0.9,0.001"), "set_bias","get_bias") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "disable_collision"), "set_exclude_nodes_from_collision","get_exclude_nodes_from_collision") ;
+ ClassDB::bind_method(D_METHOD("set_bias", "bias"), &Joint2D::set_bias);
+ ClassDB::bind_method(D_METHOD("get_bias"), &Joint2D::get_bias);
+ ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint2D::set_exclude_nodes_from_collision);
+ ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint2D::get_exclude_nodes_from_collision);
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_a"), "set_node_a", "get_node_a");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "node_b"), "set_node_b", "get_node_b");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0,0.9,0.001"), "set_bias", "get_bias");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disable_collision"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision");
}
-
-
Joint2D::Joint2D() {
- bias=0;
- exclude_from_collision=true;
+ bias = 0;
+ exclude_from_collision = true;
}
///////////////////////////////////////////////////////////////////////////////
@@ -162,7 +145,7 @@ Joint2D::Joint2D() {
void PinJoint2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (!is_inside_tree())
@@ -172,50 +155,46 @@ void PinJoint2D::_notification(int p_what) {
break;
}
-
- draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(0,-10),Point2(0,+10),Color(0.7,0.6,0.0,0.5),3);
+ draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(0, -10), Point2(0, +10), Color(0.7, 0.6, 0.0, 0.5), 3);
} break;
}
-
}
RID PinJoint2D::_configure_joint() {
- Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL;
- Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL;
+ Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL;
+ Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL;
if (!node_a && !node_b)
return RID();
- PhysicsBody2D *body_a=node_a ? node_a->cast_to<PhysicsBody2D>() : (PhysicsBody2D*)NULL;
- PhysicsBody2D *body_b=node_b ? node_b->cast_to<PhysicsBody2D>() : (PhysicsBody2D*)NULL;
+ PhysicsBody2D *body_a = node_a ? node_a->cast_to<PhysicsBody2D>() : (PhysicsBody2D *)NULL;
+ PhysicsBody2D *body_b = node_b ? node_b->cast_to<PhysicsBody2D>() : (PhysicsBody2D *)NULL;
if (!body_a && !body_b)
return RID();
if (!body_a) {
- SWAP(body_a,body_b);
+ SWAP(body_a, body_b);
} else if (body_b) {
//add a collision exception between both
if (get_exclude_nodes_from_collision())
- Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
else
- Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid());
}
- RID pj = Physics2DServer::get_singleton()->pin_joint_create(get_global_transform().get_origin(),body_a->get_rid(),body_b?body_b->get_rid():RID());
+ RID pj = Physics2DServer::get_singleton()->pin_joint_create(get_global_transform().get_origin(), body_a->get_rid(), body_b ? body_b->get_rid() : RID());
Physics2DServer::get_singleton()->pin_joint_set_param(pj, Physics2DServer::PIN_JOINT_SOFTNESS, softness);
return pj;
-
}
void PinJoint2D::set_softness(real_t p_softness) {
- softness=p_softness;
+ softness = p_softness;
update();
if (get_joint().is_valid())
Physics2DServer::get_singleton()->pin_joint_set_param(get_joint(), Physics2DServer::PIN_JOINT_SOFTNESS, p_softness);
-
}
real_t PinJoint2D::get_softness() const {
@@ -225,10 +204,10 @@ real_t PinJoint2D::get_softness() const {
void PinJoint2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_softness","softness"), &PinJoint2D::set_softness);
+ ClassDB::bind_method(D_METHOD("set_softness", "softness"), &PinJoint2D::set_softness);
ClassDB::bind_method(D_METHOD("get_softness"), &PinJoint2D::get_softness);
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "softness", PROPERTY_HINT_EXP_RANGE,"0.00,16,0.01"), "set_softness", "get_softness");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "softness", PROPERTY_HINT_EXP_RANGE, "0.00,16,0.01"), "set_softness", "get_softness");
}
PinJoint2D::PinJoint2D() {
@@ -236,16 +215,13 @@ PinJoint2D::PinJoint2D() {
softness = 0;
}
-
-
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
-
void GrooveJoint2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (!is_inside_tree())
break;
@@ -254,48 +230,44 @@ void GrooveJoint2D::_notification(int p_what) {
break;
}
- draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(-10,length),Point2(+10,length),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(0,0),Point2(0,length),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(-10,initial_offset),Point2(+10,initial_offset),Color(0.8,0.8,0.9,0.5),5);
+ draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(-10, length), Point2(+10, length), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(0, 0), Point2(0, length), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(-10, initial_offset), Point2(+10, initial_offset), Color(0.8, 0.8, 0.9, 0.5), 5);
} break;
}
}
-RID GrooveJoint2D::_configure_joint(){
+RID GrooveJoint2D::_configure_joint() {
-
- Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL;
- Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL;
+ Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL;
+ Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL;
if (!node_a || !node_b)
return RID();
- PhysicsBody2D *body_a=node_a->cast_to<PhysicsBody2D>();
- PhysicsBody2D *body_b=node_b->cast_to<PhysicsBody2D>();
+ PhysicsBody2D *body_a = node_a->cast_to<PhysicsBody2D>();
+ PhysicsBody2D *body_b = node_b->cast_to<PhysicsBody2D>();
if (!body_a || !body_b)
return RID();
-
if (get_exclude_nodes_from_collision())
- Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
else
- Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid());
Transform2D gt = get_global_transform();
Vector2 groove_A1 = gt.get_origin();
- Vector2 groove_A2 = gt.xform( Vector2(0,length) );
- Vector2 anchor_B = gt.xform( Vector2(0,initial_offset) );
-
+ Vector2 groove_A2 = gt.xform(Vector2(0, length));
+ Vector2 anchor_B = gt.xform(Vector2(0, initial_offset));
- return Physics2DServer::get_singleton()->groove_joint_create(groove_A1,groove_A2,anchor_B,body_a->get_rid(),body_b->get_rid());
+ return Physics2DServer::get_singleton()->groove_joint_create(groove_A1, groove_A2, anchor_B, body_a->get_rid(), body_b->get_rid());
}
-
void GrooveJoint2D::set_length(real_t p_length) {
- length=p_length;
+ length = p_length;
update();
}
@@ -304,10 +276,9 @@ real_t GrooveJoint2D::get_length() const {
return length;
}
-
void GrooveJoint2D::set_initial_offset(real_t p_initial_offset) {
- initial_offset=p_initial_offset;
+ initial_offset = p_initial_offset;
update();
}
@@ -316,38 +287,30 @@ real_t GrooveJoint2D::get_initial_offset() const {
return initial_offset;
}
-
-
void GrooveJoint2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_length", "length"), &GrooveJoint2D::set_length);
+ ClassDB::bind_method(D_METHOD("get_length"), &GrooveJoint2D::get_length);
+ ClassDB::bind_method(D_METHOD("set_initial_offset", "offset"), &GrooveJoint2D::set_initial_offset);
+ ClassDB::bind_method(D_METHOD("get_initial_offset"), &GrooveJoint2D::get_initial_offset);
- ClassDB::bind_method(D_METHOD("set_length","length"),&GrooveJoint2D::set_length);
- ClassDB::bind_method(D_METHOD("get_length"),&GrooveJoint2D::get_length);
- ClassDB::bind_method(D_METHOD("set_initial_offset","offset"),&GrooveJoint2D::set_initial_offset);
- ClassDB::bind_method(D_METHOD("get_initial_offset"),&GrooveJoint2D::get_initial_offset);
-
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_length","get_length");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "initial_offset", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_initial_offset","get_initial_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_length", "get_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "initial_offset", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_initial_offset", "get_initial_offset");
}
GrooveJoint2D::GrooveJoint2D() {
- length=50;
- initial_offset=25;
+ length = 50;
+ initial_offset = 25;
}
-
-
-
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
-
-
void DampedSpringJoint2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (!is_inside_tree())
@@ -357,50 +320,48 @@ void DampedSpringJoint2D::_notification(int p_what) {
break;
}
- draw_line(Point2(-10,0),Point2(+10,0),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(-10,length),Point2(+10,length),Color(0.7,0.6,0.0,0.5),3);
- draw_line(Point2(0,0),Point2(0,length),Color(0.7,0.6,0.0,0.5),3);
+ draw_line(Point2(-10, 0), Point2(+10, 0), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(-10, length), Point2(+10, length), Color(0.7, 0.6, 0.0, 0.5), 3);
+ draw_line(Point2(0, 0), Point2(0, length), Color(0.7, 0.6, 0.0, 0.5), 3);
} break;
}
}
-RID DampedSpringJoint2D::_configure_joint(){
-
+RID DampedSpringJoint2D::_configure_joint() {
- Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL;
- Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL;
+ Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL;
+ Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL;
if (!node_a || !node_b)
return RID();
- PhysicsBody2D *body_a=node_a->cast_to<PhysicsBody2D>();
- PhysicsBody2D *body_b=node_b->cast_to<PhysicsBody2D>();
+ PhysicsBody2D *body_a = node_a->cast_to<PhysicsBody2D>();
+ PhysicsBody2D *body_b = node_b->cast_to<PhysicsBody2D>();
if (!body_a || !body_b)
return RID();
if (get_exclude_nodes_from_collision())
- Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
else
- Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(),body_b->get_rid());
+ Physics2DServer::get_singleton()->body_remove_collision_exception(body_a->get_rid(), body_b->get_rid());
Transform2D gt = get_global_transform();
Vector2 anchor_A = gt.get_origin();
- Vector2 anchor_B = gt.xform( Vector2(0,length) );
+ Vector2 anchor_B = gt.xform(Vector2(0, length));
- RID dsj = Physics2DServer::get_singleton()->damped_spring_joint_create(anchor_A,anchor_B,body_a->get_rid(),body_b->get_rid());
+ RID dsj = Physics2DServer::get_singleton()->damped_spring_joint_create(anchor_A, anchor_B, body_a->get_rid(), body_b->get_rid());
if (rest_length)
- Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_REST_LENGTH,rest_length);
- Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_STIFFNESS,stiffness);
- Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj,Physics2DServer::DAMPED_STRING_DAMPING,damping);
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_REST_LENGTH, rest_length);
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_STIFFNESS, stiffness);
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(dsj, Physics2DServer::DAMPED_STRING_DAMPING, damping);
return dsj;
}
-
void DampedSpringJoint2D::set_length(real_t p_length) {
- length=p_length;
+ length = p_length;
update();
}
@@ -411,11 +372,10 @@ real_t DampedSpringJoint2D::get_length() const {
void DampedSpringJoint2D::set_rest_length(real_t p_rest_length) {
- rest_length=p_rest_length;
+ rest_length = p_rest_length;
update();
if (get_joint().is_valid())
- Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_REST_LENGTH,p_rest_length?p_rest_length:length);
-
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_REST_LENGTH, p_rest_length ? p_rest_length : length);
}
real_t DampedSpringJoint2D::get_rest_length() const {
@@ -425,10 +385,10 @@ real_t DampedSpringJoint2D::get_rest_length() const {
void DampedSpringJoint2D::set_stiffness(real_t p_stiffness) {
- stiffness=p_stiffness;
+ stiffness = p_stiffness;
update();
if (get_joint().is_valid())
- Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_STIFFNESS,p_stiffness);
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_STIFFNESS, p_stiffness);
}
real_t DampedSpringJoint2D::get_stiffness() const {
@@ -438,10 +398,10 @@ real_t DampedSpringJoint2D::get_stiffness() const {
void DampedSpringJoint2D::set_damping(real_t p_damping) {
- damping=p_damping;
+ damping = p_damping;
update();
if (get_joint().is_valid())
- Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(),Physics2DServer::DAMPED_STRING_DAMPING,p_damping);
+ Physics2DServer::get_singleton()->damped_string_joint_set_param(get_joint(), Physics2DServer::DAMPED_STRING_DAMPING, p_damping);
}
real_t DampedSpringJoint2D::get_damping() const {
@@ -449,30 +409,27 @@ real_t DampedSpringJoint2D::get_damping() const {
return damping;
}
-
void DampedSpringJoint2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_length", "length"), &DampedSpringJoint2D::set_length);
+ ClassDB::bind_method(D_METHOD("get_length"), &DampedSpringJoint2D::get_length);
+ ClassDB::bind_method(D_METHOD("set_rest_length", "rest_length"), &DampedSpringJoint2D::set_rest_length);
+ ClassDB::bind_method(D_METHOD("get_rest_length"), &DampedSpringJoint2D::get_rest_length);
+ ClassDB::bind_method(D_METHOD("set_stiffness", "stiffness"), &DampedSpringJoint2D::set_stiffness);
+ ClassDB::bind_method(D_METHOD("get_stiffness"), &DampedSpringJoint2D::get_stiffness);
+ ClassDB::bind_method(D_METHOD("set_damping", "damping"), &DampedSpringJoint2D::set_damping);
+ ClassDB::bind_method(D_METHOD("get_damping"), &DampedSpringJoint2D::get_damping);
- ClassDB::bind_method(D_METHOD("set_length","length"),&DampedSpringJoint2D::set_length);
- ClassDB::bind_method(D_METHOD("get_length"),&DampedSpringJoint2D::get_length);
- ClassDB::bind_method(D_METHOD("set_rest_length","rest_length"),&DampedSpringJoint2D::set_rest_length);
- ClassDB::bind_method(D_METHOD("get_rest_length"),&DampedSpringJoint2D::get_rest_length);
- ClassDB::bind_method(D_METHOD("set_stiffness","stiffness"),&DampedSpringJoint2D::set_stiffness);
- ClassDB::bind_method(D_METHOD("get_stiffness"),&DampedSpringJoint2D::get_stiffness);
- ClassDB::bind_method(D_METHOD("set_damping","damping"),&DampedSpringJoint2D::set_damping);
- ClassDB::bind_method(D_METHOD("get_damping"),&DampedSpringJoint2D::get_damping);
-
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE,"1,65535,1"), "set_length","get_length");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "rest_length", PROPERTY_HINT_EXP_RANGE,"0,65535,1"), "set_rest_length","get_rest_length");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "stiffness", PROPERTY_HINT_EXP_RANGE,"0.1,64,0.1"), "set_stiffness","get_stiffness");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "damping", PROPERTY_HINT_EXP_RANGE,"0.01,16,0.01"), "set_damping","get_damping");
-
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_EXP_RANGE, "1,65535,1"), "set_length", "get_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "rest_length", PROPERTY_HINT_EXP_RANGE, "0,65535,1"), "set_rest_length", "get_rest_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "stiffness", PROPERTY_HINT_EXP_RANGE, "0.1,64,0.1"), "set_stiffness", "get_stiffness");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping", PROPERTY_HINT_EXP_RANGE, "0.01,16,0.01"), "set_damping", "get_damping");
}
DampedSpringJoint2D::DampedSpringJoint2D() {
- length=50;
- rest_length=0;
- stiffness=20;
- damping=1;
+ length = 50;
+ rest_length = 0;
+ stiffness = 20;
+ damping = 1;
}
diff --git a/scene/2d/joints_2d.h b/scene/2d/joints_2d.h
index 3b3eec6bd6..c172620461 100644
--- a/scene/2d/joints_2d.h
+++ b/scene/2d/joints_2d.h
@@ -29,12 +29,11 @@
#ifndef JOINTS_2D_H
#define JOINTS_2D_H
-
#include "node_2d.h"
class Joint2D : public Node2D {
- GDCLASS(Joint2D,Node2D);
+ GDCLASS(Joint2D, Node2D);
RID joint;
@@ -44,21 +43,19 @@ class Joint2D : public Node2D {
bool exclude_from_collision;
-
protected:
-
void _update_joint();
void _notification(int p_what);
- virtual RID _configure_joint()=0;
+ virtual RID _configure_joint() = 0;
static void _bind_methods();
-public:
- void set_node_a(const NodePath& p_node_a);
+public:
+ void set_node_a(const NodePath &p_node_a);
NodePath get_node_a() const;
- void set_node_b(const NodePath& p_node_b);
+ void set_node_b(const NodePath &p_node_b);
NodePath get_node_b() const;
void set_bias(real_t p_bias);
@@ -69,23 +66,20 @@ public:
RID get_joint() const { return joint; }
Joint2D();
-
};
-
class PinJoint2D : public Joint2D {
- GDCLASS(PinJoint2D,Joint2D);
+ GDCLASS(PinJoint2D, Joint2D);
real_t softness;
protected:
-
void _notification(int p_what);
virtual RID _configure_joint();
static void _bind_methods();
-public:
+public:
void set_softness(real_t p_stiffness);
real_t get_softness() const;
@@ -94,18 +88,17 @@ public:
class GrooveJoint2D : public Joint2D {
- GDCLASS(GrooveJoint2D,Joint2D);
+ GDCLASS(GrooveJoint2D, Joint2D);
real_t length;
real_t initial_offset;
protected:
-
void _notification(int p_what);
virtual RID _configure_joint();
static void _bind_methods();
-public:
+public:
void set_length(real_t p_length);
real_t get_length() const;
@@ -117,7 +110,7 @@ public:
class DampedSpringJoint2D : public Joint2D {
- GDCLASS(DampedSpringJoint2D,Joint2D);
+ GDCLASS(DampedSpringJoint2D, Joint2D);
real_t stiffness;
real_t damping;
@@ -125,12 +118,11 @@ class DampedSpringJoint2D : public Joint2D {
real_t length;
protected:
-
void _notification(int p_what);
virtual RID _configure_joint();
static void _bind_methods();
-public:
+public:
void set_length(real_t p_length);
real_t get_length() const;
@@ -146,5 +138,4 @@ public:
DampedSpringJoint2D();
};
-
#endif // JOINTS_2D_H
diff --git a/scene/2d/light_2d.cpp b/scene/2d/light_2d.cpp
index d7f5a890e8..7cf98c8c09 100644
--- a/scene/2d/light_2d.cpp
+++ b/scene/2d/light_2d.cpp
@@ -29,10 +29,9 @@
#include "light_2d.h"
#include "servers/visual_server.h"
-void Light2D::edit_set_pivot(const Point2& p_pivot) {
+void Light2D::edit_set_pivot(const Point2 &p_pivot) {
set_texture_offset(p_pivot);
-
}
Point2 Light2D::edit_get_pivot() const {
@@ -47,49 +46,47 @@ bool Light2D::edit_has_pivot() const {
Rect2 Light2D::get_item_rect() const {
if (texture.is_null())
- return Rect2(0,0,1,1);
+ return Rect2(0, 0, 1, 1);
Size2i s;
- s = texture->get_size()*_scale;
- Point2i ofs=texture_offset;
- ofs-=s/2;
+ s = texture->get_size() * _scale;
+ Point2i ofs = texture_offset;
+ ofs -= s / 2;
- if (s==Size2(0,0))
- s=Size2(1,1);
+ if (s == Size2(0, 0))
+ s = Size2(1, 1);
- return Rect2(ofs,s);
+ return Rect2(ofs, s);
}
-
void Light2D::_update_light_visibility() {
if (!is_inside_tree())
return;
- bool editor_ok=true;
+ bool editor_ok = true;
#ifdef TOOLS_ENABLED
if (editor_only) {
if (!get_tree()->is_editor_hint()) {
- editor_ok=false;
+ editor_ok = false;
} else {
- editor_ok = (get_tree()->get_edited_scene_root() && (this==get_tree()->get_edited_scene_root() || get_owner()==get_tree()->get_edited_scene_root()));
+ editor_ok = (get_tree()->get_edited_scene_root() && (this == get_tree()->get_edited_scene_root() || get_owner() == get_tree()->get_edited_scene_root()));
}
}
#else
if (editor_only) {
- editor_ok=false;
+ editor_ok = false;
}
#endif
- VS::get_singleton()->canvas_light_set_enabled(canvas_light,enabled && is_visible_in_tree() && editor_ok);
+ VS::get_singleton()->canvas_light_set_enabled(canvas_light, enabled && is_visible_in_tree() && editor_ok);
}
-void Light2D::set_enabled( bool p_enabled) {
-
+void Light2D::set_enabled(bool p_enabled) {
- enabled=p_enabled;
+ enabled = p_enabled;
_update_light_visibility();
}
@@ -100,22 +97,22 @@ bool Light2D::is_enabled() const {
void Light2D::set_editor_only(bool p_editor_only) {
- editor_only=p_editor_only;
+ editor_only = p_editor_only;
_update_light_visibility();
}
-bool Light2D::is_editor_only() const{
+bool Light2D::is_editor_only() const {
return editor_only;
}
-void Light2D::set_texture( const Ref<Texture>& p_texture) {
+void Light2D::set_texture(const Ref<Texture> &p_texture) {
- texture=p_texture;
+ texture = p_texture;
if (texture.is_valid())
- VS::get_singleton()->canvas_light_set_texture(canvas_light,texture->get_rid());
+ VS::get_singleton()->canvas_light_set_texture(canvas_light, texture->get_rid());
else
- VS::get_singleton()->canvas_light_set_texture(canvas_light,RID());
+ VS::get_singleton()->canvas_light_set_texture(canvas_light, RID());
update_configuration_warning();
}
@@ -125,12 +122,11 @@ Ref<Texture> Light2D::get_texture() const {
return texture;
}
-void Light2D::set_texture_offset( const Vector2& p_offset) {
+void Light2D::set_texture_offset(const Vector2 &p_offset) {
- texture_offset=p_offset;
- VS::get_singleton()->canvas_light_set_texture_offset(canvas_light,texture_offset);
+ texture_offset = p_offset;
+ VS::get_singleton()->canvas_light_set_texture_offset(canvas_light, texture_offset);
item_rect_changed();
-
}
Vector2 Light2D::get_texture_offset() const {
@@ -138,108 +134,94 @@ Vector2 Light2D::get_texture_offset() const {
return texture_offset;
}
-void Light2D::set_color( const Color& p_color) {
-
- color=p_color;
- VS::get_singleton()->canvas_light_set_color(canvas_light,color);
+void Light2D::set_color(const Color &p_color) {
+ color = p_color;
+ VS::get_singleton()->canvas_light_set_color(canvas_light, color);
}
Color Light2D::get_color() const {
return color;
}
-void Light2D::set_height( float p_height) {
-
- height=p_height;
- VS::get_singleton()->canvas_light_set_height(canvas_light,height);
+void Light2D::set_height(float p_height) {
+ height = p_height;
+ VS::get_singleton()->canvas_light_set_height(canvas_light, height);
}
-
float Light2D::get_height() const {
return height;
}
-void Light2D::set_energy( float p_energy) {
-
- energy=p_energy;
- VS::get_singleton()->canvas_light_set_energy(canvas_light,energy);
+void Light2D::set_energy(float p_energy) {
+ energy = p_energy;
+ VS::get_singleton()->canvas_light_set_energy(canvas_light, energy);
}
-
float Light2D::get_energy() const {
return energy;
}
+void Light2D::set_texture_scale(float p_scale) {
-
-void Light2D::set_texture_scale( float p_scale) {
-
- _scale=p_scale;
- VS::get_singleton()->canvas_light_set_scale(canvas_light,_scale);
+ _scale = p_scale;
+ VS::get_singleton()->canvas_light_set_scale(canvas_light, _scale);
item_rect_changed();
-
}
-
float Light2D::get_texture_scale() const {
return _scale;
}
-void Light2D::set_z_range_min( int p_min_z) {
-
- z_min=p_min_z;
- VS::get_singleton()->canvas_light_set_z_range(canvas_light,z_min,z_max);
+void Light2D::set_z_range_min(int p_min_z) {
+ z_min = p_min_z;
+ VS::get_singleton()->canvas_light_set_z_range(canvas_light, z_min, z_max);
}
int Light2D::get_z_range_min() const {
return z_min;
}
-void Light2D::set_z_range_max( int p_max_z) {
-
- z_max=p_max_z;
- VS::get_singleton()->canvas_light_set_z_range(canvas_light,z_min,z_max);
+void Light2D::set_z_range_max(int p_max_z) {
+ z_max = p_max_z;
+ VS::get_singleton()->canvas_light_set_z_range(canvas_light, z_min, z_max);
}
int Light2D::get_z_range_max() const {
return z_max;
}
-void Light2D::set_layer_range_min( int p_min_layer) {
-
- layer_min=p_min_layer;
- VS::get_singleton()->canvas_light_set_layer_range(canvas_light,layer_min,layer_max);
+void Light2D::set_layer_range_min(int p_min_layer) {
+ layer_min = p_min_layer;
+ VS::get_singleton()->canvas_light_set_layer_range(canvas_light, layer_min, layer_max);
}
int Light2D::get_layer_range_min() const {
return layer_min;
}
-void Light2D::set_layer_range_max( int p_max_layer) {
-
- layer_max=p_max_layer;
- VS::get_singleton()->canvas_light_set_layer_range(canvas_light,layer_min,layer_max);
+void Light2D::set_layer_range_max(int p_max_layer) {
+ layer_max = p_max_layer;
+ VS::get_singleton()->canvas_light_set_layer_range(canvas_light, layer_min, layer_max);
}
int Light2D::get_layer_range_max() const {
return layer_max;
}
-void Light2D::set_item_cull_mask( int p_mask) {
-
- item_mask=p_mask;
- VS::get_singleton()->canvas_light_set_item_cull_mask(canvas_light,item_mask);
+void Light2D::set_item_cull_mask(int p_mask) {
+ item_mask = p_mask;
+ VS::get_singleton()->canvas_light_set_item_cull_mask(canvas_light, item_mask);
}
int Light2D::get_item_cull_mask() const {
@@ -247,11 +229,10 @@ int Light2D::get_item_cull_mask() const {
return item_mask;
}
-void Light2D::set_item_shadow_cull_mask( int p_mask) {
-
- item_shadow_mask=p_mask;
- VS::get_singleton()->canvas_light_set_item_shadow_cull_mask(canvas_light,item_shadow_mask);
+void Light2D::set_item_shadow_cull_mask(int p_mask) {
+ item_shadow_mask = p_mask;
+ VS::get_singleton()->canvas_light_set_item_shadow_cull_mask(canvas_light, item_shadow_mask);
}
int Light2D::get_item_shadow_cull_mask() const {
@@ -259,10 +240,10 @@ int Light2D::get_item_shadow_cull_mask() const {
return item_shadow_mask;
}
-void Light2D::set_mode( Mode p_mode ) {
+void Light2D::set_mode(Mode p_mode) {
- mode=p_mode;
- VS::get_singleton()->canvas_light_set_mode(canvas_light,VS::CanvasLightMode(p_mode));
+ mode = p_mode;
+ VS::get_singleton()->canvas_light_set_mode(canvas_light, VS::CanvasLightMode(p_mode));
}
Light2D::Mode Light2D::get_mode() const {
@@ -270,21 +251,20 @@ Light2D::Mode Light2D::get_mode() const {
return mode;
}
-void Light2D::set_shadow_enabled( bool p_enabled) {
-
- shadow=p_enabled;
- VS::get_singleton()->canvas_light_set_shadow_enabled(canvas_light,shadow);
+void Light2D::set_shadow_enabled(bool p_enabled) {
+ shadow = p_enabled;
+ VS::get_singleton()->canvas_light_set_shadow_enabled(canvas_light, shadow);
}
bool Light2D::is_shadow_enabled() const {
return shadow;
}
-void Light2D::set_shadow_buffer_size( int p_size ) {
+void Light2D::set_shadow_buffer_size(int p_size) {
- shadow_buffer_size=p_size;
- VS::get_singleton()->canvas_light_set_shadow_buffer_size(canvas_light,shadow_buffer_size);
+ shadow_buffer_size = p_size;
+ VS::get_singleton()->canvas_light_set_shadow_buffer_size(canvas_light, shadow_buffer_size);
}
int Light2D::get_shadow_buffer_size() const {
@@ -292,21 +272,20 @@ int Light2D::get_shadow_buffer_size() const {
return shadow_buffer_size;
}
-void Light2D::set_shadow_gradient_length( float p_multiplier) {
+void Light2D::set_shadow_gradient_length(float p_multiplier) {
- shadow_gradient_length=p_multiplier;
- VS::get_singleton()->canvas_light_set_shadow_gradient_length(canvas_light,p_multiplier);
+ shadow_gradient_length = p_multiplier;
+ VS::get_singleton()->canvas_light_set_shadow_gradient_length(canvas_light, p_multiplier);
}
-float Light2D::get_shadow_gradient_length() const{
+float Light2D::get_shadow_gradient_length() const {
return shadow_gradient_length;
}
-
-void Light2D::set_shadow_filter( ShadowFilter p_filter) {
- shadow_filter=p_filter;
- VS::get_singleton()->canvas_light_set_shadow_filter(canvas_light,VS::CanvasLightShadowFilter(p_filter ));
+void Light2D::set_shadow_filter(ShadowFilter p_filter) {
+ shadow_filter = p_filter;
+ VS::get_singleton()->canvas_light_set_shadow_filter(canvas_light, VS::CanvasLightShadowFilter(p_filter));
}
Light2D::ShadowFilter Light2D::get_shadow_filter() const {
@@ -314,42 +293,37 @@ Light2D::ShadowFilter Light2D::get_shadow_filter() const {
return shadow_filter;
}
-
-
-void Light2D::set_shadow_color( const Color& p_shadow_color) {
- shadow_color=p_shadow_color;
- VS::get_singleton()->canvas_light_set_shadow_color(canvas_light,shadow_color);
+void Light2D::set_shadow_color(const Color &p_shadow_color) {
+ shadow_color = p_shadow_color;
+ VS::get_singleton()->canvas_light_set_shadow_color(canvas_light, shadow_color);
}
Color Light2D::get_shadow_color() const {
return shadow_color;
}
-
-
void Light2D::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- VS::get_singleton()->canvas_light_attach_to_canvas( canvas_light, get_canvas() );
+ VS::get_singleton()->canvas_light_attach_to_canvas(canvas_light, get_canvas());
_update_light_visibility();
}
- if (p_what==NOTIFICATION_TRANSFORM_CHANGED) {
+ if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
- VS::get_singleton()->canvas_light_set_transform( canvas_light, get_global_transform());
+ VS::get_singleton()->canvas_light_set_transform(canvas_light, get_global_transform());
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
_update_light_visibility();
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
- VS::get_singleton()->canvas_light_attach_to_canvas( canvas_light, RID() );
+ VS::get_singleton()->canvas_light_attach_to_canvas(canvas_light, RID());
_update_light_visibility();
}
-
}
String Light2D::get_configuration_warning() const {
@@ -361,126 +335,119 @@ String Light2D::get_configuration_warning() const {
return String();
}
-
void Light2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &Light2D::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &Light2D::is_enabled);
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&Light2D::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&Light2D::is_enabled);
-
- ClassDB::bind_method(D_METHOD("set_editor_only","editor_only"), &Light2D::set_editor_only );
- ClassDB::bind_method(D_METHOD("is_editor_only"), &Light2D::is_editor_only );
-
- ClassDB::bind_method(D_METHOD("set_texture","texture"),&Light2D::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture"),&Light2D::get_texture);
-
- ClassDB::bind_method(D_METHOD("set_texture_offset","texture_offset"),&Light2D::set_texture_offset);
- ClassDB::bind_method(D_METHOD("get_texture_offset"),&Light2D::get_texture_offset);
-
- ClassDB::bind_method(D_METHOD("set_color","color"),&Light2D::set_color);
- ClassDB::bind_method(D_METHOD("get_color"),&Light2D::get_color);
-
- ClassDB::bind_method(D_METHOD("set_height","height"),&Light2D::set_height);
- ClassDB::bind_method(D_METHOD("get_height"),&Light2D::get_height);
-
- ClassDB::bind_method(D_METHOD("set_energy","energy"),&Light2D::set_energy);
- ClassDB::bind_method(D_METHOD("get_energy"),&Light2D::get_energy);
+ ClassDB::bind_method(D_METHOD("set_editor_only", "editor_only"), &Light2D::set_editor_only);
+ ClassDB::bind_method(D_METHOD("is_editor_only"), &Light2D::is_editor_only);
- ClassDB::bind_method(D_METHOD("set_texture_scale","texture_scale"),&Light2D::set_texture_scale);
- ClassDB::bind_method(D_METHOD("get_texture_scale"),&Light2D::get_texture_scale);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &Light2D::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &Light2D::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &Light2D::set_texture_offset);
+ ClassDB::bind_method(D_METHOD("get_texture_offset"), &Light2D::get_texture_offset);
- ClassDB::bind_method(D_METHOD("set_z_range_min","z"),&Light2D::set_z_range_min);
- ClassDB::bind_method(D_METHOD("get_z_range_min"),&Light2D::get_z_range_min);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &Light2D::set_color);
+ ClassDB::bind_method(D_METHOD("get_color"), &Light2D::get_color);
- ClassDB::bind_method(D_METHOD("set_z_range_max","z"),&Light2D::set_z_range_max);
- ClassDB::bind_method(D_METHOD("get_z_range_max"),&Light2D::get_z_range_max);
+ ClassDB::bind_method(D_METHOD("set_height", "height"), &Light2D::set_height);
+ ClassDB::bind_method(D_METHOD("get_height"), &Light2D::get_height);
- ClassDB::bind_method(D_METHOD("set_layer_range_min","layer"),&Light2D::set_layer_range_min);
- ClassDB::bind_method(D_METHOD("get_layer_range_min"),&Light2D::get_layer_range_min);
+ ClassDB::bind_method(D_METHOD("set_energy", "energy"), &Light2D::set_energy);
+ ClassDB::bind_method(D_METHOD("get_energy"), &Light2D::get_energy);
- ClassDB::bind_method(D_METHOD("set_layer_range_max","layer"),&Light2D::set_layer_range_max);
- ClassDB::bind_method(D_METHOD("get_layer_range_max"),&Light2D::get_layer_range_max);
+ ClassDB::bind_method(D_METHOD("set_texture_scale", "texture_scale"), &Light2D::set_texture_scale);
+ ClassDB::bind_method(D_METHOD("get_texture_scale"), &Light2D::get_texture_scale);
+ ClassDB::bind_method(D_METHOD("set_z_range_min", "z"), &Light2D::set_z_range_min);
+ ClassDB::bind_method(D_METHOD("get_z_range_min"), &Light2D::get_z_range_min);
- ClassDB::bind_method(D_METHOD("set_item_cull_mask","item_cull_mask"),&Light2D::set_item_cull_mask);
- ClassDB::bind_method(D_METHOD("get_item_cull_mask"),&Light2D::get_item_cull_mask);
+ ClassDB::bind_method(D_METHOD("set_z_range_max", "z"), &Light2D::set_z_range_max);
+ ClassDB::bind_method(D_METHOD("get_z_range_max"), &Light2D::get_z_range_max);
- ClassDB::bind_method(D_METHOD("set_item_shadow_cull_mask","item_shadow_cull_mask"),&Light2D::set_item_shadow_cull_mask);
- ClassDB::bind_method(D_METHOD("get_item_shadow_cull_mask"),&Light2D::get_item_shadow_cull_mask);
+ ClassDB::bind_method(D_METHOD("set_layer_range_min", "layer"), &Light2D::set_layer_range_min);
+ ClassDB::bind_method(D_METHOD("get_layer_range_min"), &Light2D::get_layer_range_min);
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&Light2D::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&Light2D::get_mode);
+ ClassDB::bind_method(D_METHOD("set_layer_range_max", "layer"), &Light2D::set_layer_range_max);
+ ClassDB::bind_method(D_METHOD("get_layer_range_max"), &Light2D::get_layer_range_max);
- ClassDB::bind_method(D_METHOD("set_shadow_enabled","enabled"),&Light2D::set_shadow_enabled);
- ClassDB::bind_method(D_METHOD("is_shadow_enabled"),&Light2D::is_shadow_enabled);
+ ClassDB::bind_method(D_METHOD("set_item_cull_mask", "item_cull_mask"), &Light2D::set_item_cull_mask);
+ ClassDB::bind_method(D_METHOD("get_item_cull_mask"), &Light2D::get_item_cull_mask);
- ClassDB::bind_method(D_METHOD("set_shadow_buffer_size","size"),&Light2D::set_shadow_buffer_size);
- ClassDB::bind_method(D_METHOD("get_shadow_buffer_size"),&Light2D::get_shadow_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_item_shadow_cull_mask", "item_shadow_cull_mask"), &Light2D::set_item_shadow_cull_mask);
+ ClassDB::bind_method(D_METHOD("get_item_shadow_cull_mask"), &Light2D::get_item_shadow_cull_mask);
- ClassDB::bind_method(D_METHOD("set_shadow_gradient_length","multiplier"),&Light2D::set_shadow_gradient_length);
- ClassDB::bind_method(D_METHOD("get_shadow_gradient_length"),&Light2D::get_shadow_gradient_length);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &Light2D::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &Light2D::get_mode);
- ClassDB::bind_method(D_METHOD("set_shadow_filter","filter"),&Light2D::set_shadow_filter);
- ClassDB::bind_method(D_METHOD("get_shadow_filter"),&Light2D::get_shadow_filter);
+ ClassDB::bind_method(D_METHOD("set_shadow_enabled", "enabled"), &Light2D::set_shadow_enabled);
+ ClassDB::bind_method(D_METHOD("is_shadow_enabled"), &Light2D::is_shadow_enabled);
- ClassDB::bind_method(D_METHOD("set_shadow_color","shadow_color"),&Light2D::set_shadow_color);
- ClassDB::bind_method(D_METHOD("get_shadow_color"),&Light2D::get_shadow_color);
+ ClassDB::bind_method(D_METHOD("set_shadow_buffer_size", "size"), &Light2D::set_shadow_buffer_size);
+ ClassDB::bind_method(D_METHOD("get_shadow_buffer_size"), &Light2D::get_shadow_buffer_size);
+ ClassDB::bind_method(D_METHOD("set_shadow_gradient_length", "multiplier"), &Light2D::set_shadow_gradient_length);
+ ClassDB::bind_method(D_METHOD("get_shadow_gradient_length"), &Light2D::get_shadow_gradient_length);
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "editor_only"),"set_editor_only","is_editor_only");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"offset"),"set_texture_offset","get_texture_offset");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"scale",PROPERTY_HINT_RANGE,"0.01,50,0.01"),"set_texture_scale","get_texture_scale");
- ADD_PROPERTY( PropertyInfo(Variant::COLOR,"color"),"set_color","get_color");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_RANGE,"0.01,100,0.01"),"set_energy","get_energy");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Add,Sub,Mix,Mask"),"set_mode","get_mode");
- ADD_GROUP("Range","range_");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"range_height",PROPERTY_HINT_RANGE,"-100,100,0.1"),"set_height","get_height");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"range_z_min",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z_range_min","get_z_range_min");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"range_z_max",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z_range_max","get_z_range_max");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"range_layer_min",PROPERTY_HINT_RANGE,"-512,512,1"),"set_layer_range_min","get_layer_range_min");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"range_layer_max",PROPERTY_HINT_RANGE,"-512,512,1"),"set_layer_range_max","get_layer_range_max");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"range_item_cull_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_item_cull_mask","get_item_cull_mask");
+ ClassDB::bind_method(D_METHOD("set_shadow_filter", "filter"), &Light2D::set_shadow_filter);
+ ClassDB::bind_method(D_METHOD("get_shadow_filter"), &Light2D::get_shadow_filter);
- ADD_GROUP("Shadow","shadow_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"shadow_enabled"),"set_shadow_enabled","is_shadow_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::COLOR,"shadow_color"),"set_shadow_color","get_shadow_color");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"shadow_buffer_size",PROPERTY_HINT_RANGE,"32,16384,1"),"set_shadow_buffer_size","get_shadow_buffer_size");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"shadow_gradient_length",PROPERTY_HINT_RANGE,"1,4096,0.1"),"set_shadow_gradient_length","get_shadow_gradient_length");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"shadow_filter",PROPERTY_HINT_ENUM,"None,PCF3,PCF5,PCF9,PCF13"),"set_shadow_filter","get_shadow_filter");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"shadow_item_cull_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_item_shadow_cull_mask","get_item_shadow_cull_mask");
+ ClassDB::bind_method(D_METHOD("set_shadow_color", "shadow_color"), &Light2D::set_shadow_color);
+ ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light2D::get_shadow_color);
- BIND_CONSTANT( MODE_ADD );
- BIND_CONSTANT( MODE_SUB );
- BIND_CONSTANT( MODE_MIX );
- BIND_CONSTANT( MODE_MASK );
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_texture_offset", "get_texture_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "scale", PROPERTY_HINT_RANGE, "0.01,50,0.01"), "set_texture_scale", "get_texture_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_RANGE, "0.01,100,0.01"), "set_energy", "get_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Add,Sub,Mix,Mask"), "set_mode", "get_mode");
+ ADD_GROUP("Range", "range_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_height", PROPERTY_HINT_RANGE, "-100,100,0.1"), "set_height", "get_height");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "range_z_min", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_range_min", "get_z_range_min");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "range_z_max", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z_range_max", "get_z_range_max");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "range_layer_min", PROPERTY_HINT_RANGE, "-512,512,1"), "set_layer_range_min", "get_layer_range_min");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "range_layer_max", PROPERTY_HINT_RANGE, "-512,512,1"), "set_layer_range_max", "get_layer_range_max");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "range_item_cull_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_item_cull_mask", "get_item_cull_mask");
+ ADD_GROUP("Shadow", "shadow_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_enabled"), "set_shadow_enabled", "is_shadow_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color"), "set_shadow_color", "get_shadow_color");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_buffer_size", PROPERTY_HINT_RANGE, "32,16384,1"), "set_shadow_buffer_size", "get_shadow_buffer_size");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "shadow_gradient_length", PROPERTY_HINT_RANGE, "1,4096,0.1"), "set_shadow_gradient_length", "get_shadow_gradient_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "shadow_filter", PROPERTY_HINT_ENUM, "None,PCF3,PCF5,PCF9,PCF13"), "set_shadow_filter", "get_shadow_filter");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_item_cull_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_item_shadow_cull_mask", "get_item_shadow_cull_mask");
+ BIND_CONSTANT(MODE_ADD);
+ BIND_CONSTANT(MODE_SUB);
+ BIND_CONSTANT(MODE_MIX);
+ BIND_CONSTANT(MODE_MASK);
}
Light2D::Light2D() {
- canvas_light=VisualServer::get_singleton()->canvas_light_create();
- enabled=true;
- editor_only=false;
- shadow=false;
- color=Color(1,1,1);
- height=0;
- _scale=1.0;
- z_min=-1024;
- z_max=1024;
- layer_min=0;
- layer_max=0;
- item_mask=1;
- item_shadow_mask=1;
- mode=MODE_ADD;
- shadow_buffer_size=2048;
- shadow_gradient_length=0;
- energy=1.0;
- shadow_color=Color(0,0,0,0);
- shadow_filter=SHADOW_FILTER_NONE;
+ canvas_light = VisualServer::get_singleton()->canvas_light_create();
+ enabled = true;
+ editor_only = false;
+ shadow = false;
+ color = Color(1, 1, 1);
+ height = 0;
+ _scale = 1.0;
+ z_min = -1024;
+ z_max = 1024;
+ layer_min = 0;
+ layer_max = 0;
+ item_mask = 1;
+ item_shadow_mask = 1;
+ mode = MODE_ADD;
+ shadow_buffer_size = 2048;
+ shadow_gradient_length = 0;
+ energy = 1.0;
+ shadow_color = Color(0, 0, 0, 0);
+ shadow_filter = SHADOW_FILTER_NONE;
set_notify_transform(true);
}
diff --git a/scene/2d/light_2d.h b/scene/2d/light_2d.h
index 2bdcca5d01..e9f0e069d4 100644
--- a/scene/2d/light_2d.h
+++ b/scene/2d/light_2d.h
@@ -33,7 +33,8 @@
class Light2D : public Node2D {
- GDCLASS(Light2D,Node2D);
+ GDCLASS(Light2D, Node2D);
+
public:
enum Mode {
MODE_ADD,
@@ -73,80 +74,77 @@ private:
Vector2 texture_offset;
ShadowFilter shadow_filter;
-
void _update_light_visibility();
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
-
- virtual void edit_set_pivot(const Point2& p_pivot);
+public:
+ virtual void edit_set_pivot(const Point2 &p_pivot);
virtual Point2 edit_get_pivot() const;
virtual bool edit_has_pivot() const;
- void set_enabled( bool p_enabled);
+ void set_enabled(bool p_enabled);
bool is_enabled() const;
void set_editor_only(bool p_editor_only);
bool is_editor_only() const;
- void set_texture( const Ref<Texture>& p_texture);
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
- void set_texture_offset( const Vector2& p_offset);
+ void set_texture_offset(const Vector2 &p_offset);
Vector2 get_texture_offset() const;
- void set_color( const Color& p_color);
+ void set_color(const Color &p_color);
Color get_color() const;
- void set_height( float p_height);
+ void set_height(float p_height);
float get_height() const;
- void set_energy( float p_energy);
+ void set_energy(float p_energy);
float get_energy() const;
- void set_texture_scale( float p_scale);
+ void set_texture_scale(float p_scale);
float get_texture_scale() const;
- void set_z_range_min( int p_min_z);
+ void set_z_range_min(int p_min_z);
int get_z_range_min() const;
- void set_z_range_max( int p_max_z);
+ void set_z_range_max(int p_max_z);
int get_z_range_max() const;
- void set_layer_range_min( int p_min_layer);
+ void set_layer_range_min(int p_min_layer);
int get_layer_range_min() const;
- void set_layer_range_max( int p_max_layer);
+ void set_layer_range_max(int p_max_layer);
int get_layer_range_max() const;
- void set_item_cull_mask( int p_mask);
+ void set_item_cull_mask(int p_mask);
int get_item_cull_mask() const;
- void set_item_shadow_cull_mask( int p_mask);
+ void set_item_shadow_cull_mask(int p_mask);
int get_item_shadow_cull_mask() const;
- void set_mode( Mode p_mode );
+ void set_mode(Mode p_mode);
Mode get_mode() const;
- void set_shadow_enabled( bool p_enabled);
+ void set_shadow_enabled(bool p_enabled);
bool is_shadow_enabled() const;
- void set_shadow_buffer_size( int p_size );
+ void set_shadow_buffer_size(int p_size);
int get_shadow_buffer_size() const;
- void set_shadow_gradient_length( float p_multiplier);
+ void set_shadow_gradient_length(float p_multiplier);
float get_shadow_gradient_length() const;
- void set_shadow_filter( ShadowFilter p_filter);
+ void set_shadow_filter(ShadowFilter p_filter);
ShadowFilter get_shadow_filter() const;
- void set_shadow_color( const Color& p_shadow_color);
+ void set_shadow_color(const Color &p_shadow_color);
Color get_shadow_color() const;
-
virtual Rect2 get_item_rect() const;
String get_configuration_warning() const;
@@ -158,5 +156,4 @@ public:
VARIANT_ENUM_CAST(Light2D::Mode);
VARIANT_ENUM_CAST(Light2D::ShadowFilter);
-
#endif // LIGHT_2D_H
diff --git a/scene/2d/light_occluder_2d.cpp b/scene/2d/light_occluder_2d.cpp
index 6a024fe330..401bbcedb2 100644
--- a/scene/2d/light_occluder_2d.cpp
+++ b/scene/2d/light_occluder_2d.cpp
@@ -28,80 +28,74 @@
/*************************************************************************/
#include "light_occluder_2d.h"
+void OccluderPolygon2D::set_polygon(const PoolVector<Vector2> &p_polygon) {
-void OccluderPolygon2D::set_polygon(const PoolVector<Vector2>& p_polygon) {
-
- polygon=p_polygon;
- VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon,p_polygon,closed);
+ polygon = p_polygon;
+ VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon, p_polygon, closed);
emit_changed();
}
-PoolVector<Vector2> OccluderPolygon2D::get_polygon() const{
+PoolVector<Vector2> OccluderPolygon2D::get_polygon() const {
return polygon;
}
void OccluderPolygon2D::set_closed(bool p_closed) {
- if (closed==p_closed)
+ if (closed == p_closed)
return;
- closed=p_closed;
+ closed = p_closed;
if (polygon.size())
- VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon,polygon,closed);
+ VS::get_singleton()->canvas_occluder_polygon_set_shape(occ_polygon, polygon, closed);
emit_changed();
}
-bool OccluderPolygon2D::is_closed() const{
+bool OccluderPolygon2D::is_closed() const {
return closed;
}
-void OccluderPolygon2D::set_cull_mode(CullMode p_mode){
+void OccluderPolygon2D::set_cull_mode(CullMode p_mode) {
- cull=p_mode;
- VS::get_singleton()->canvas_occluder_polygon_set_cull_mode(occ_polygon,VS::CanvasOccluderPolygonCullMode(p_mode));
+ cull = p_mode;
+ VS::get_singleton()->canvas_occluder_polygon_set_cull_mode(occ_polygon, VS::CanvasOccluderPolygonCullMode(p_mode));
}
-OccluderPolygon2D::CullMode OccluderPolygon2D::get_cull_mode() const{
+OccluderPolygon2D::CullMode OccluderPolygon2D::get_cull_mode() const {
return cull;
}
-
RID OccluderPolygon2D::get_rid() const {
return occ_polygon;
}
-
-
void OccluderPolygon2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_closed", "closed"), &OccluderPolygon2D::set_closed);
+ ClassDB::bind_method(D_METHOD("is_closed"), &OccluderPolygon2D::is_closed);
- ClassDB::bind_method(D_METHOD("set_closed","closed"),&OccluderPolygon2D::set_closed);
- ClassDB::bind_method(D_METHOD("is_closed"),&OccluderPolygon2D::is_closed);
+ ClassDB::bind_method(D_METHOD("set_cull_mode", "cull_mode"), &OccluderPolygon2D::set_cull_mode);
+ ClassDB::bind_method(D_METHOD("get_cull_mode"), &OccluderPolygon2D::get_cull_mode);
- ClassDB::bind_method(D_METHOD("set_cull_mode","cull_mode"),&OccluderPolygon2D::set_cull_mode);
- ClassDB::bind_method(D_METHOD("get_cull_mode"),&OccluderPolygon2D::get_cull_mode);
+ ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &OccluderPolygon2D::set_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon"), &OccluderPolygon2D::get_polygon);
- ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&OccluderPolygon2D::set_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon"),&OccluderPolygon2D::get_polygon);
-
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"closed"),"set_closed","is_closed");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"cull_mode",PROPERTY_HINT_ENUM,"Disabled,ClockWise,CounterClockWise"),"set_cull_mode","get_cull_mode");
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "closed"), "set_closed", "is_closed");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cull_mode", PROPERTY_HINT_ENUM, "Disabled,ClockWise,CounterClockWise"), "set_cull_mode", "get_cull_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon");
BIND_CONSTANT(CULL_DISABLED);
BIND_CONSTANT(CULL_CLOCKWISE);
BIND_CONSTANT(CULL_COUNTER_CLOCKWISE);
}
-
OccluderPolygon2D::OccluderPolygon2D() {
- occ_polygon=VS::get_singleton()->canvas_occluder_polygon_create();
- closed=true;
- cull=CULL_DISABLED;
+ occ_polygon = VS::get_singleton()->canvas_occluder_polygon_create();
+ closed = true;
+ cull = CULL_DISABLED;
}
OccluderPolygon2D::~OccluderPolygon2D() {
@@ -116,26 +110,24 @@ void LightOccluder2D::_poly_changed() {
}
#endif
-
void LightOccluder2D::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_CANVAS) {
-
- VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder,get_canvas());
- VS::get_singleton()->canvas_light_occluder_set_transform(occluder,get_global_transform());
- VS::get_singleton()->canvas_light_occluder_set_enabled(occluder,is_visible_in_tree());
+ if (p_what == NOTIFICATION_ENTER_CANVAS) {
+ VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder, get_canvas());
+ VS::get_singleton()->canvas_light_occluder_set_transform(occluder, get_global_transform());
+ VS::get_singleton()->canvas_light_occluder_set_enabled(occluder, is_visible_in_tree());
}
- if (p_what==NOTIFICATION_TRANSFORM_CHANGED) {
+ if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
- VS::get_singleton()->canvas_light_occluder_set_transform(occluder,get_global_transform());
+ VS::get_singleton()->canvas_light_occluder_set_transform(occluder, get_global_transform());
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- VS::get_singleton()->canvas_light_occluder_set_enabled(occluder,is_visible_in_tree());
+ VS::get_singleton()->canvas_light_occluder_set_enabled(occluder, is_visible_in_tree());
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (get_tree()->is_editor_hint()) {
@@ -146,15 +138,15 @@ void LightOccluder2D::_notification(int p_what) {
if (poly.size()) {
if (occluder_polygon->is_closed()) {
Vector<Color> color;
- color.push_back(Color(0,0,0,0.6));
- draw_polygon(Variant(poly),color);
+ color.push_back(Color(0, 0, 0, 0.6));
+ draw_polygon(Variant(poly), color);
} else {
- int ps=poly.size();
+ int ps = poly.size();
PoolVector<Vector2>::Read r = poly.read();
- for(int i=0;i<ps-1;i++) {
+ for (int i = 0; i < ps - 1; i++) {
- draw_line(r[i],r[i+1],Color(0,0,0,0.6),3);
+ draw_line(r[i], r[i + 1], Color(0, 0, 0, 0.6), 3);
}
}
}
@@ -162,34 +154,30 @@ void LightOccluder2D::_notification(int p_what) {
}
}
+ if (p_what == NOTIFICATION_EXIT_CANVAS) {
- if (p_what==NOTIFICATION_EXIT_CANVAS) {
-
- VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder,RID());
+ VS::get_singleton()->canvas_light_occluder_attach_to_canvas(occluder, RID());
}
-
-
}
-void LightOccluder2D::set_occluder_polygon(const Ref<OccluderPolygon2D>& p_polygon) {
+void LightOccluder2D::set_occluder_polygon(const Ref<OccluderPolygon2D> &p_polygon) {
#ifdef DEBUG_ENABLED
if (occluder_polygon.is_valid())
- occluder_polygon->disconnect("changed",this,"_poly_changed");
+ occluder_polygon->disconnect("changed", this, "_poly_changed");
#endif
- occluder_polygon=p_polygon;
+ occluder_polygon = p_polygon;
if (occluder_polygon.is_valid())
- VS::get_singleton()->canvas_light_occluder_set_polygon(occluder,occluder_polygon->get_rid());
+ VS::get_singleton()->canvas_light_occluder_set_polygon(occluder, occluder_polygon->get_rid());
else
- VS::get_singleton()->canvas_light_occluder_set_polygon(occluder,RID());
+ VS::get_singleton()->canvas_light_occluder_set_polygon(occluder, RID());
#ifdef DEBUG_ENABLED
if (occluder_polygon.is_valid())
- occluder_polygon->connect("changed",this,"_poly_changed");
+ occluder_polygon->connect("changed", this, "_poly_changed");
update();
#endif
-
}
Ref<OccluderPolygon2D> LightOccluder2D::get_occluder_polygon() const {
@@ -199,23 +187,22 @@ Ref<OccluderPolygon2D> LightOccluder2D::get_occluder_polygon() const {
void LightOccluder2D::set_occluder_light_mask(int p_mask) {
- mask=p_mask;
- VS::get_singleton()->canvas_light_occluder_set_light_mask(occluder,mask);
+ mask = p_mask;
+ VS::get_singleton()->canvas_light_occluder_set_light_mask(occluder, mask);
}
-int LightOccluder2D::get_occluder_light_mask() const{
+int LightOccluder2D::get_occluder_light_mask() const {
return mask;
}
-
String LightOccluder2D::get_configuration_warning() const {
if (!occluder_polygon.is_valid()) {
return TTR("An occluder polygon must be set (or drawn) for this occluder to take effect.");
}
- if (occluder_polygon.is_valid() && occluder_polygon->get_polygon().size()==0) {
+ if (occluder_polygon.is_valid() && occluder_polygon->get_polygon().size() == 0) {
return TTR("The occluder polygon for this occluder is empty. Please draw a polygon!");
}
@@ -224,24 +211,24 @@ String LightOccluder2D::get_configuration_warning() const {
void LightOccluder2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_occluder_polygon","polygon:OccluderPolygon2D"),&LightOccluder2D::set_occluder_polygon);
- ClassDB::bind_method(D_METHOD("get_occluder_polygon:OccluderPolygon2D"),&LightOccluder2D::get_occluder_polygon);
+ ClassDB::bind_method(D_METHOD("set_occluder_polygon", "polygon:OccluderPolygon2D"), &LightOccluder2D::set_occluder_polygon);
+ ClassDB::bind_method(D_METHOD("get_occluder_polygon:OccluderPolygon2D"), &LightOccluder2D::get_occluder_polygon);
- ClassDB::bind_method(D_METHOD("set_occluder_light_mask","mask"),&LightOccluder2D::set_occluder_light_mask);
- ClassDB::bind_method(D_METHOD("get_occluder_light_mask"),&LightOccluder2D::get_occluder_light_mask);
+ ClassDB::bind_method(D_METHOD("set_occluder_light_mask", "mask"), &LightOccluder2D::set_occluder_light_mask);
+ ClassDB::bind_method(D_METHOD("get_occluder_light_mask"), &LightOccluder2D::get_occluder_light_mask);
#ifdef DEBUG_ENABLED
- ClassDB::bind_method("_poly_changed",&LightOccluder2D::_poly_changed);
+ ClassDB::bind_method("_poly_changed", &LightOccluder2D::_poly_changed);
#endif
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"occluder",PROPERTY_HINT_RESOURCE_TYPE,"OccluderPolygon2D"),"set_occluder_polygon","get_occluder_polygon");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"light_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_occluder_light_mask","get_occluder_light_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "occluder", PROPERTY_HINT_RESOURCE_TYPE, "OccluderPolygon2D"), "set_occluder_polygon", "get_occluder_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_occluder_light_mask", "get_occluder_light_mask");
}
LightOccluder2D::LightOccluder2D() {
- occluder=VS::get_singleton()->canvas_light_occluder_create();
- mask=1;
+ occluder = VS::get_singleton()->canvas_light_occluder_create();
+ mask = 1;
set_notify_transform(true);
}
@@ -249,4 +236,3 @@ LightOccluder2D::~LightOccluder2D() {
VS::get_singleton()->free(occluder);
}
-
diff --git a/scene/2d/light_occluder_2d.h b/scene/2d/light_occluder_2d.h
index 777785cd1d..26135334fc 100644
--- a/scene/2d/light_occluder_2d.h
+++ b/scene/2d/light_occluder_2d.h
@@ -33,28 +33,26 @@
class OccluderPolygon2D : public Resource {
- GDCLASS(OccluderPolygon2D,Resource);
-public:
+ GDCLASS(OccluderPolygon2D, Resource);
+public:
enum CullMode {
CULL_DISABLED,
CULL_CLOCKWISE,
CULL_COUNTER_CLOCKWISE
};
-private:
-
+private:
RID occ_polygon;
PoolVector<Vector2> polygon;
bool closed;
CullMode cull;
protected:
-
static void _bind_methods();
-public:
- void set_polygon(const PoolVector<Vector2>& p_polygon);
+public:
+ void set_polygon(const PoolVector<Vector2> &p_polygon);
PoolVector<Vector2> get_polygon() const;
void set_closed(bool p_closed);
@@ -66,13 +64,12 @@ public:
virtual RID get_rid() const;
OccluderPolygon2D();
~OccluderPolygon2D();
-
};
VARIANT_ENUM_CAST(OccluderPolygon2D::CullMode);
class LightOccluder2D : public Node2D {
- GDCLASS(LightOccluder2D,Node2D);
+ GDCLASS(LightOccluder2D, Node2D);
RID occluder;
bool enabled;
@@ -86,9 +83,9 @@ class LightOccluder2D : public Node2D {
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_occluder_polygon(const Ref<OccluderPolygon2D>& p_polygon);
+public:
+ void set_occluder_polygon(const Ref<OccluderPolygon2D> &p_polygon);
Ref<OccluderPolygon2D> get_occluder_polygon() const;
void set_occluder_light_mask(int p_mask);
diff --git a/scene/2d/line_2d.cpp b/scene/2d/line_2d.cpp
index 059711549f..cd9b8e8cb9 100644
--- a/scene/2d/line_2d.cpp
+++ b/scene/2d/line_2d.cpp
@@ -30,19 +30,18 @@
#include "core_string_names.h"
-
// Needed so we can bind functions
VARIANT_ENUM_CAST(LineJointMode)
VARIANT_ENUM_CAST(LineCapMode)
VARIANT_ENUM_CAST(LineTextureMode)
-
-Line2D::Line2D() : Node2D() {
+Line2D::Line2D()
+ : Node2D() {
_joint_mode = LINE_JOINT_SHARP;
_begin_cap_mode = LINE_CAP_NONE;
_end_cap_mode = LINE_CAP_NONE;
_width = 10;
- _default_color = Color(0.4,0.5,1);
+ _default_color = Color(0.4, 0.5, 1);
_sharp_limit = 2.f;
_round_precision = 8;
}
@@ -53,7 +52,7 @@ void Line2D::set_points(const PoolVector<Vector2> &p_points) {
}
void Line2D::set_width(float width) {
- if(width < 0.0)
+ if (width < 0.0)
width = 0.0;
_width = width;
update();
@@ -99,17 +98,17 @@ Color Line2D::get_default_color() const {
return _default_color;
}
-void Line2D::set_gradient(const Ref<ColorRamp>& gradient) {
+void Line2D::set_gradient(const Ref<ColorRamp> &gradient) {
// Cleanup previous connection if any
- if(_gradient.is_valid()) {
+ if (_gradient.is_valid()) {
(**_gradient).disconnect(CoreStringNames::get_singleton()->changed, this, "_gradient_changed");
}
_gradient = gradient;
// Connect to the gradient so the line will update when the ColorRamp is changed
- if(_gradient.is_valid()) {
+ if (_gradient.is_valid()) {
(**_gradient).connect(CoreStringNames::get_singleton()->changed, this, "_gradient_changed");
}
@@ -120,7 +119,7 @@ Ref<ColorRamp> Line2D::get_gradient() const {
return _gradient;
}
-void Line2D::set_texture(const Ref<Texture>& texture) {
+void Line2D::set_texture(const Ref<Texture> &texture) {
_texture = texture;
update();
}
@@ -166,15 +165,15 @@ LineCapMode Line2D::get_end_cap_mode() const {
}
void Line2D::_notification(int p_what) {
- switch(p_what) {
- case NOTIFICATION_DRAW:
- _draw();
- break;
+ switch (p_what) {
+ case NOTIFICATION_DRAW:
+ _draw();
+ break;
}
}
void Line2D::set_sharp_limit(float limit) {
- if(limit < 0.f)
+ if (limit < 0.f)
limit = 0.f;
_sharp_limit = limit;
update();
@@ -185,7 +184,7 @@ float Line2D::get_sharp_limit() const {
}
void Line2D::set_round_precision(int precision) {
- if(precision < 1)
+ if (precision < 1)
precision = 1;
_round_precision = precision;
update();
@@ -196,16 +195,17 @@ int Line2D::get_round_precision() const {
}
void Line2D::_draw() {
- if(_points.size() <= 1 || _width == 0.f)
+ if (_points.size() <= 1 || _width == 0.f)
return;
// TODO Is this really needed?
// Copy points for faster access
Vector<Vector2> points;
points.resize(_points.size());
- int len = points.size(); {
+ int len = points.size();
+ {
PoolVector<Vector2>::Read points_read = _points.read();
- for(int i = 0; i < len; ++i) {
+ for (int i = 0; i < len; ++i) {
points[i] = points_read[i];
}
}
@@ -226,36 +226,36 @@ void Line2D::_draw() {
lb.build();
RID texture_rid;
- if(_texture.is_valid())
+ if (_texture.is_valid())
texture_rid = (**_texture).get_rid();
VS::get_singleton()->canvas_item_add_triangle_array(
- get_canvas_item(),
- lb.indices,
- lb.vertices,
- lb.colors,
- lb.uvs,
- texture_rid);
+ get_canvas_item(),
+ lb.indices,
+ lb.vertices,
+ lb.colors,
+ lb.uvs,
+ texture_rid);
// DEBUG
// Draw wireframe
-// if(lb.indices.size() % 3 == 0) {
-// Color col(0,0,0);
-// for(int i = 0; i < lb.indices.size(); i += 3) {
-// int vi = lb.indices[i];
-// int lbvsize = lb.vertices.size();
-// Vector2 a = lb.vertices[lb.indices[i]];
-// Vector2 b = lb.vertices[lb.indices[i+1]];
-// Vector2 c = lb.vertices[lb.indices[i+2]];
-// draw_line(a, b, col);
-// draw_line(b, c, col);
-// draw_line(c, a, col);
-// }
-// for(int i = 0; i < lb.vertices.size(); ++i) {
-// Vector2 p = lb.vertices[i];
-// draw_rect(Rect2(p.x-1, p.y-1, 2, 2), Color(0,0,0,0.5));
-// }
-// }
+ // if(lb.indices.size() % 3 == 0) {
+ // Color col(0,0,0);
+ // for(int i = 0; i < lb.indices.size(); i += 3) {
+ // int vi = lb.indices[i];
+ // int lbvsize = lb.vertices.size();
+ // Vector2 a = lb.vertices[lb.indices[i]];
+ // Vector2 b = lb.vertices[lb.indices[i+1]];
+ // Vector2 c = lb.vertices[lb.indices[i+2]];
+ // draw_line(a, b, col);
+ // draw_line(b, c, col);
+ // draw_line(c, a, col);
+ // }
+ // for(int i = 0; i < lb.vertices.size(); ++i) {
+ // Vector2 p = lb.vertices[i];
+ // draw_rect(Rect2(p.x-1, p.y-1, 2, 2), Color(0,0,0,0.5));
+ // }
+ // }
}
void Line2D::_gradient_changed() {
@@ -265,10 +265,10 @@ void Line2D::_gradient_changed() {
// static
void Line2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_points","points"), &Line2D::set_points);
+ ClassDB::bind_method(D_METHOD("set_points", "points"), &Line2D::set_points);
ClassDB::bind_method(D_METHOD("get_points"), &Line2D::get_points);
- ClassDB::bind_method(D_METHOD("set_point_pos","i", "pos"), &Line2D::set_point_pos);
+ ClassDB::bind_method(D_METHOD("set_point_pos", "i", "pos"), &Line2D::set_point_pos);
ClassDB::bind_method(D_METHOD("get_point_pos", "i"), &Line2D::get_point_pos);
ClassDB::bind_method(D_METHOD("get_point_count"), &Line2D::get_point_count);
@@ -276,7 +276,7 @@ void Line2D::_bind_methods() {
ClassDB::bind_method(D_METHOD("add_point", "pos"), &Line2D::add_point);
ClassDB::bind_method(D_METHOD("remove_point", "i"), &Line2D::remove_point);
- ClassDB::bind_method(D_METHOD("set_width","width"), &Line2D::set_width);
+ ClassDB::bind_method(D_METHOD("set_width", "width"), &Line2D::set_width);
ClassDB::bind_method(D_METHOD("get_width"), &Line2D::get_width);
ClassDB::bind_method(D_METHOD("set_default_color", "color"), &Line2D::set_default_color);
@@ -309,12 +309,12 @@ void Line2D::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "points"), "set_points", "get_points");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "width"), "set_width", "get_width");
ADD_PROPERTY(PropertyInfo(Variant::COLOR, "default_color"), "set_default_color", "get_default_color");
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "gradient", PROPERTY_HINT_RESOURCE_TYPE, "ColorRamp"), "set_gradient", "get_gradient");
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "texture_mode", PROPERTY_HINT_ENUM, "None,Tile" ), "set_texture_mode","get_texture_mode");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "joint_mode", PROPERTY_HINT_ENUM, "Sharp,Bevel,Round" ), "set_joint_mode","get_joint_mode");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "begin_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round" ), "set_begin_cap_mode","get_begin_cap_mode");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "end_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round" ), "set_end_cap_mode","get_end_cap_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "gradient", PROPERTY_HINT_RESOURCE_TYPE, "ColorRamp"), "set_gradient", "get_gradient");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "texture_mode", PROPERTY_HINT_ENUM, "None,Tile"), "set_texture_mode", "get_texture_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "joint_mode", PROPERTY_HINT_ENUM, "Sharp,Bevel,Round"), "set_joint_mode", "get_joint_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "begin_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round"), "set_begin_cap_mode", "get_begin_cap_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "end_cap_mode", PROPERTY_HINT_ENUM, "None,Box,Round"), "set_end_cap_mode", "get_end_cap_mode");
ADD_PROPERTY(PropertyInfo(Variant::REAL, "sharp_limit"), "set_sharp_limit", "get_sharp_limit");
ADD_PROPERTY(PropertyInfo(Variant::INT, "round_precision"), "set_round_precision", "get_round_precision");
@@ -330,7 +330,4 @@ void Line2D::_bind_methods() {
BIND_CONSTANT(LINE_TEXTURE_TILE);
ClassDB::bind_method(D_METHOD("_gradient_changed"), &Line2D::_gradient_changed);
-
}
-
-
diff --git a/scene/2d/line_2d.h b/scene/2d/line_2d.h
index 5435c7489f..2cd71e9727 100644
--- a/scene/2d/line_2d.h
+++ b/scene/2d/line_2d.h
@@ -29,9 +29,8 @@
#ifndef LINE2D_H
#define LINE2D_H
-#include "node_2d.h"
#include "line_builder.h"
-
+#include "node_2d.h"
class Line2D : public Node2D {
@@ -40,7 +39,7 @@ class Line2D : public Node2D {
public:
Line2D();
- void set_points(const PoolVector<Vector2> & p_points);
+ void set_points(const PoolVector<Vector2> &p_points);
PoolVector<Vector2> get_points() const;
void set_point_pos(int i, Vector2 pos);
@@ -57,10 +56,10 @@ public:
void set_default_color(Color color);
Color get_default_color() const;
- void set_gradient(const Ref<ColorRamp>& gradient);
+ void set_gradient(const Ref<ColorRamp> &gradient);
Ref<ColorRamp> get_gradient() const;
- void set_texture(const Ref<Texture>& texture);
+ void set_texture(const Ref<Texture> &texture);
Ref<Texture> get_texture() const;
void set_texture_mode(const LineTextureMode mode);
@@ -102,7 +101,6 @@ private:
LineTextureMode _texture_mode;
float _sharp_limit;
int _round_precision;
-
};
#endif // LINE2D_H
diff --git a/scene/2d/line_builder.cpp b/scene/2d/line_builder.cpp
index 69543f004d..0912f6cfe8 100644
--- a/scene/2d/line_builder.cpp
+++ b/scene/2d/line_builder.cpp
@@ -40,19 +40,18 @@ enum SegmentIntersectionResult {
static SegmentIntersectionResult segment_intersection(
Vector2 a, Vector2 b, Vector2 c, Vector2 d,
- Vector2 * out_intersection)
-{
+ Vector2 *out_intersection) {
// http://paulbourke.net/geometry/pointlineplane/ <-- Good stuff
Vector2 cd = d - c;
Vector2 ab = b - a;
- float div = cd.y*ab.x - cd.x*ab.y;
+ float div = cd.y * ab.x - cd.x * ab.y;
- if(Math::abs(div) > 0.001f) {
- float ua = (cd.x * (a.y-c.y) - cd.y * (a.x-c.x)) / div;
- float ub = (ab.x * (a.y-c.y) - ab.y * (a.x-c.x)) / div;
+ if (Math::abs(div) > 0.001f) {
+ float ua = (cd.x * (a.y - c.y) - cd.y * (a.x - c.x)) / div;
+ float ub = (ab.x * (a.y - c.y) - ab.y * (a.x - c.x)) / div;
*out_intersection = a + ua * ab;
- if(ua >= 0.f && ua <= 1.f &&
- ub >= 0.f && ub <= 1.f)
+ if (ua >= 0.f && ua <= 1.f &&
+ ub >= 0.f && ub <= 1.f)
return SEGMENT_INTERSECT;
return SEGMENT_NO_INTERSECT;
}
@@ -62,30 +61,29 @@ static SegmentIntersectionResult segment_intersection(
// TODO I'm pretty sure there is an even faster way to swap things
template <typename T>
-static inline void swap(T & a, T & b) {
+static inline void swap(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
-static float calculate_total_distance(const Vector<Vector2> & points) {
+static float calculate_total_distance(const Vector<Vector2> &points) {
float d = 0.f;
- for(int i = 1; i < points.size(); ++i) {
- d += points[i].distance_to(points[i-1]);
+ for (int i = 1; i < points.size(); ++i) {
+ d += points[i].distance_to(points[i - 1]);
}
return d;
}
-static inline Vector2 rotate90(const Vector2 & v) {
+static inline Vector2 rotate90(const Vector2 &v) {
// Note: the 2D referential is X-right, Y-down
return Vector2(v.y, -v.x);
}
-static inline Vector2 interpolate(const Rect2 & r, const Vector2 & v) {
+static inline Vector2 interpolate(const Rect2 &r, const Vector2 &v) {
return Vector2(
- Math::lerp(r.get_pos().x, r.get_pos().x + r.get_size().x, v.x),
- Math::lerp(r.get_pos().y, r.get_pos().y + r.get_size().y, v.y)
- );
+ Math::lerp(r.get_pos().x, r.get_pos().x + r.get_size().x, v.x),
+ Math::lerp(r.get_pos().y, r.get_pos().y + r.get_size().y, v.y));
}
//----------------------------------------------------------------------------
@@ -95,7 +93,7 @@ static inline Vector2 interpolate(const Rect2 & r, const Vector2 & v) {
LineBuilder::LineBuilder() {
joint_mode = LINE_JOINT_SHARP;
width = 10;
- default_color = Color(0.4,0.5,1);
+ default_color = Color(0.4, 0.5, 1);
gradient = NULL;
sharp_limit = 2.f;
round_precision = 8;
@@ -107,7 +105,6 @@ LineBuilder::LineBuilder() {
_last_index[1] = 0;
}
-
void LineBuilder::clear_output() {
vertices.clear();
colors.clear();
@@ -117,13 +114,13 @@ void LineBuilder::clear_output() {
void LineBuilder::build() {
// Need at least 2 points to draw a line
- if(points.size() < 2) {
+ if (points.size() < 2) {
clear_output();
return;
}
const float hw = width / 2.f;
- const float hw_sq = hw*hw;
+ const float hw_sq = hw * hw;
const float sharp_limit_sq = sharp_limit * sharp_limit;
const int len = points.size();
@@ -144,9 +141,9 @@ void LineBuilder::build() {
float total_distance;
_interpolate_color = gradient != NULL;
bool distance_required = _interpolate_color || texture_mode == LINE_TEXTURE_TILE;
- if(distance_required)
+ if (distance_required)
total_distance = calculate_total_distance(points);
- if(_interpolate_color)
+ if (_interpolate_color)
color0 = gradient->get_color(0);
else
colors.push_back(default_color);
@@ -155,7 +152,7 @@ void LineBuilder::build() {
float uvx1 = 0.f;
// Begin cap
- if(begin_cap_mode == LINE_CAP_BOX) {
+ if (begin_cap_mode == LINE_CAP_BOX) {
// Push back first vertices a little bit
pos_up0 -= f0 * hw;
pos_down0 -= f0 * hw;
@@ -163,9 +160,8 @@ void LineBuilder::build() {
total_distance += width;
current_distance0 += hw;
current_distance1 = current_distance0;
- }
- else if(begin_cap_mode == LINE_CAP_ROUND) {
- if(texture_mode == LINE_TEXTURE_TILE) {
+ } else if (begin_cap_mode == LINE_CAP_ROUND) {
+ if (texture_mode == LINE_TEXTURE_TILE) {
uvx0 = 0.5f;
}
new_arc(pos0, pos_up0 - pos0, -Math_PI, color0, Rect2(0.f, 0.f, 1.f, 1.f));
@@ -188,10 +184,10 @@ void LineBuilder::build() {
// (not the same implementation but visuals help a lot)
// For each additional segment
- for(int i = 1; i < len-1; ++i) {
+ for (int i = 1; i < len - 1; ++i) {
pos1 = points[i];
- Vector2 pos2 = points[i+1];
+ Vector2 pos2 = points[i + 1];
Vector2 f1 = (pos2 - pos1).normalized();
Vector2 u1 = rotate90(f1);
@@ -201,11 +197,10 @@ void LineBuilder::build() {
const Orientation orientation = (dp > 0.f ? UP : DOWN);
Vector2 inner_normal0, inner_normal1;
- if(orientation == UP) {
+ if (orientation == UP) {
inner_normal0 = u0 * hw;
inner_normal1 = u1 * hw;
- }
- else {
+ } else {
inner_normal0 = -u0 * hw;
inner_normal1 = -u1 * hw;
}
@@ -225,11 +220,11 @@ void LineBuilder::build() {
// Find inner intersection at the joint
Vector2 corner_pos_in, corner_pos_out;
SegmentIntersectionResult intersection_result = segment_intersection(
- pos0 + inner_normal0, pos1 + inner_normal0,
- pos1 + inner_normal1, pos2 + inner_normal1,
- &corner_pos_in);
+ pos0 + inner_normal0, pos1 + inner_normal0,
+ pos1 + inner_normal1, pos2 + inner_normal1,
+ &corner_pos_in);
- if(intersection_result == SEGMENT_INTERSECT)
+ if (intersection_result == SEGMENT_INTERSECT)
// Inner parts of the segments intersect
corner_pos_out = 2.f * pos1 - corner_pos_in;
else {
@@ -239,11 +234,10 @@ void LineBuilder::build() {
}
Vector2 corner_pos_up, corner_pos_down;
- if(orientation == UP) {
+ if (orientation == UP) {
corner_pos_up = corner_pos_in;
corner_pos_down = corner_pos_out;
- }
- else {
+ } else {
corner_pos_up = corner_pos_out;
corner_pos_down = corner_pos_in;
}
@@ -251,30 +245,27 @@ void LineBuilder::build() {
LineJointMode current_joint_mode = joint_mode;
Vector2 pos_up1, pos_down1;
- if(intersection_result == SEGMENT_INTERSECT) {
+ if (intersection_result == SEGMENT_INTERSECT) {
// Fallback on bevel if sharp angle is too high (because it would produce very long miters)
- if(current_joint_mode == LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) / hw_sq > sharp_limit_sq) {
+ if (current_joint_mode == LINE_JOINT_SHARP && corner_pos_out.distance_squared_to(pos1) / hw_sq > sharp_limit_sq) {
current_joint_mode = LINE_JOINT_BEVEL;
}
- if(current_joint_mode == LINE_JOINT_SHARP) {
+ if (current_joint_mode == LINE_JOINT_SHARP) {
// In this case, we won't create joint geometry,
// The previous and next line quads will directly share an edge.
pos_up1 = corner_pos_up;
pos_down1 = corner_pos_down;
- }
- else {
+ } else {
// Bevel or round
- if(orientation == UP) {
+ if (orientation == UP) {
pos_up1 = corner_pos_up;
pos_down1 = pos1 - u0 * hw;
- }
- else {
+ } else {
pos_up1 = pos1 + u0 * hw;
pos_down1 = corner_pos_down;
}
}
- }
- else {
+ } else {
// No intersection: fallback
pos_up1 = corner_pos_up;
pos_down1 = corner_pos_down;
@@ -282,13 +273,13 @@ void LineBuilder::build() {
// Add current line body quad
// Triangles are clockwise
- if(distance_required) {
+ if (distance_required) {
current_distance1 += pos0.distance_to(pos1);
}
- if(_interpolate_color) {
+ if (_interpolate_color) {
color1 = gradient->get_color_at_offset(current_distance1 / total_distance);
}
- if(texture_mode == LINE_TEXTURE_TILE) {
+ if (texture_mode == LINE_TEXTURE_TILE) {
uvx0 = current_distance0 / width;
uvx1 = current_distance1 / width;
}
@@ -301,30 +292,27 @@ void LineBuilder::build() {
f0 = f1;
pos0 = pos1;
current_distance0 = current_distance1;
- if(intersection_result == SEGMENT_INTERSECT) {
- if(current_joint_mode == LINE_JOINT_SHARP) {
+ if (intersection_result == SEGMENT_INTERSECT) {
+ if (current_joint_mode == LINE_JOINT_SHARP) {
pos_up0 = pos_up1;
pos_down0 = pos_down1;
- }
- else {
- if(orientation == UP) {
+ } else {
+ if (orientation == UP) {
pos_up0 = corner_pos_up;
pos_down0 = pos1 - u1 * hw;
- }
- else {
+ } else {
pos_up0 = pos1 + u1 * hw;
pos_down0 = corner_pos_down;
}
}
- }
- else {
+ } else {
pos_up0 = pos1 + u1 * hw;
pos_down0 = pos1 - u1 * hw;
}
// From this point, bu0 and bd0 concern the next segment
// Add joint geometry
- if(current_joint_mode != LINE_JOINT_SHARP) {
+ if (current_joint_mode != LINE_JOINT_SHARP) {
// ________________ cbegin
// / \
@@ -335,25 +323,23 @@ void LineBuilder::build() {
// | |
Vector2 cbegin, cend;
- if(orientation == UP) {
+ if (orientation == UP) {
cbegin = pos_down1;
cend = pos_down0;
- }
- else {
+ } else {
cbegin = pos_up1;
cend = pos_up0;
}
- if(current_joint_mode == LINE_JOINT_BEVEL) {
+ if (current_joint_mode == LINE_JOINT_BEVEL) {
strip_add_tri(cend, orientation);
- }
- else if(current_joint_mode == LINE_JOINT_ROUND) {
+ } else if (current_joint_mode == LINE_JOINT_ROUND) {
Vector2 vbegin = cbegin - pos1;
Vector2 vend = cend - pos1;
strip_add_arc(pos1, vend.angle_to(vbegin), orientation);
}
- if(intersection_result != SEGMENT_INTERSECT)
+ if (intersection_result != SEGMENT_INTERSECT)
// In this case the joint is too fucked up to be re-used,
// start again the strip with fallback points
strip_begin(pos_up0, pos_down0, color1, uvx1);
@@ -362,34 +348,34 @@ void LineBuilder::build() {
// Last (or only) segment
- pos1 = points[points.size()-1];
+ pos1 = points[points.size() - 1];
Vector2 pos_up1 = pos1 + u0 * hw;
Vector2 pos_down1 = pos1 - u0 * hw;
// End cap (box)
- if(end_cap_mode == LINE_CAP_BOX) {
+ if (end_cap_mode == LINE_CAP_BOX) {
pos_up1 += f0 * hw;
pos_down1 += f0 * hw;
}
- if(distance_required) {
+ if (distance_required) {
current_distance1 += pos0.distance_to(pos1);
}
- if(_interpolate_color) {
- color1 = gradient->get_color(gradient->get_points_count()-1);
+ if (_interpolate_color) {
+ color1 = gradient->get_color(gradient->get_points_count() - 1);
}
- if(texture_mode == LINE_TEXTURE_TILE) {
+ if (texture_mode == LINE_TEXTURE_TILE) {
uvx1 = current_distance1 / width;
}
strip_add_quad(pos_up1, pos_down1, color1, uvx1);
// End cap (round)
- if(end_cap_mode == LINE_CAP_ROUND) {
+ if (end_cap_mode == LINE_CAP_ROUND) {
// Note: color is not used in case we don't interpolate...
- Color color = _interpolate_color ? gradient->get_color(gradient->get_points_count()-1) : Color(0,0,0);
- new_arc(pos1, pos_up1 - pos1, Math_PI, color, Rect2(uvx1-0.5f, 0.f, 1.f, 1.f));
+ Color color = _interpolate_color ? gradient->get_color(gradient->get_points_count() - 1) : Color(0, 0, 0);
+ new_arc(pos1, pos_up1 - pos1, Math_PI, color, Rect2(uvx1 - 0.5f, 0.f, 1.f, 1.f));
}
}
@@ -399,18 +385,18 @@ void LineBuilder::strip_begin(Vector2 up, Vector2 down, Color color, float uvx)
vertices.push_back(up);
vertices.push_back(down);
- if(_interpolate_color) {
+ if (_interpolate_color) {
colors.push_back(color);
colors.push_back(color);
}
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
uvs.push_back(Vector2(uvx, 0.f));
uvs.push_back(Vector2(uvx, 1.f));
}
_last_index[UP] = vi;
- _last_index[DOWN] = vi+1;
+ _last_index[DOWN] = vi + 1;
}
void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uvx) {
@@ -421,14 +407,14 @@ void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uv
vertices.push_back(up);
vertices.push_back(down);
- if(_interpolate_color) {
+ if (_interpolate_color) {
colors.push_back(color);
colors.push_back(color);
colors.push_back(color);
colors.push_back(color);
}
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
uvs.push_back(uvs[_last_index[UP]]);
uvs.push_back(uvs[_last_index[DOWN]]);
uvs.push_back(Vector2(uvx, UP));
@@ -436,14 +422,14 @@ void LineBuilder::strip_new_quad(Vector2 up, Vector2 down, Color color, float uv
}
indices.push_back(vi);
- indices.push_back(vi+3);
- indices.push_back(vi+1);
+ indices.push_back(vi + 3);
+ indices.push_back(vi + 1);
indices.push_back(vi);
- indices.push_back(vi+2);
- indices.push_back(vi+3);
+ indices.push_back(vi + 2);
+ indices.push_back(vi + 3);
- _last_index[UP] = vi+2;
- _last_index[DOWN] = vi+3;
+ _last_index[UP] = vi + 2;
+ _last_index[DOWN] = vi + 3;
}
void LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uvx) {
@@ -452,25 +438,25 @@ void LineBuilder::strip_add_quad(Vector2 up, Vector2 down, Color color, float uv
vertices.push_back(up);
vertices.push_back(down);
- if(_interpolate_color) {
+ if (_interpolate_color) {
colors.push_back(color);
colors.push_back(color);
}
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
uvs.push_back(Vector2(uvx, 0.f));
uvs.push_back(Vector2(uvx, 1.f));
}
indices.push_back(_last_index[UP]);
- indices.push_back(vi+1);
+ indices.push_back(vi + 1);
indices.push_back(_last_index[DOWN]);
indices.push_back(_last_index[UP]);
indices.push_back(vi);
- indices.push_back(vi+1);
+ indices.push_back(vi + 1);
_last_index[UP] = vi;
- _last_index[DOWN] = vi+1;
+ _last_index[DOWN] = vi + 1;
}
void LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) {
@@ -478,13 +464,13 @@ void LineBuilder::strip_add_tri(Vector2 up, Orientation orientation) {
vertices.push_back(up);
- if(_interpolate_color) {
- colors.push_back(colors[colors.size()-1]);
+ if (_interpolate_color) {
+ colors.push_back(colors[colors.size() - 1]);
}
Orientation opposite_orientation = orientation == UP ? DOWN : UP;
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
// UVs are just one slice of the texture all along
// (otherwise we can't share the bottom vertice)
uvs.push_back(uvs[_last_index[opposite_orientation]]);
@@ -508,15 +494,15 @@ void LineBuilder::strip_add_arc(Vector2 center, float angle_delta, Orientation o
float angle_step = Math_PI / static_cast<float>(round_precision);
float steps = Math::abs(angle_delta) / angle_step;
- if(angle_delta < 0.f)
+ if (angle_delta < 0.f)
angle_step = -angle_step;
float t = vbegin.angle_to(Vector2(1, 0));
float end_angle = t + angle_delta;
- Vector2 rpos(0,0);
+ Vector2 rpos(0, 0);
// Arc vertices
- for(int ti = 0; ti < steps; ++ti, t += angle_step) {
+ for (int ti = 0; ti < steps; ++ti, t += angle_step) {
rpos = center + Vector2(Math::cos(t), Math::sin(t)) * radius;
strip_add_tri(rpos, orientation);
}
@@ -535,34 +521,34 @@ void LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Col
float angle_step = Math_PI / static_cast<float>(round_precision);
float steps = Math::abs(angle_delta) / angle_step;
- if(angle_delta < 0.f)
+ if (angle_delta < 0.f)
angle_step = -angle_step;
float t = vbegin.angle_to(Vector2(1, 0));
float end_angle = t + angle_delta;
- Vector2 rpos(0,0);
+ Vector2 rpos(0, 0);
float tt_begin = -Math_PI / 2.f;
float tt = tt_begin;
// Center vertice
int vi = vertices.size();
vertices.push_back(center);
- if(_interpolate_color)
+ if (_interpolate_color)
colors.push_back(color);
- if(texture_mode != LINE_TEXTURE_NONE)
+ if (texture_mode != LINE_TEXTURE_NONE)
uvs.push_back(interpolate(uv_rect, Vector2(0.5f, 0.5f)));
// Arc vertices
- for(int ti = 0; ti < steps; ++ti, t += angle_step) {
+ for (int ti = 0; ti < steps; ++ti, t += angle_step) {
Vector2 sc = Vector2(Math::cos(t), Math::sin(t));
rpos = center + sc * radius;
vertices.push_back(rpos);
- if(_interpolate_color)
+ if (_interpolate_color)
colors.push_back(color);
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));
- uvs.push_back(interpolate(uv_rect, 0.5f*(tsc+Vector2(1.f,1.f))));
+ uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));
tt += angle_step;
}
}
@@ -571,21 +557,19 @@ void LineBuilder::new_arc(Vector2 center, Vector2 vbegin, float angle_delta, Col
Vector2 sc = Vector2(Math::cos(end_angle), Math::sin(end_angle));
rpos = center + sc * radius;
vertices.push_back(rpos);
- if(_interpolate_color)
+ if (_interpolate_color)
colors.push_back(color);
- if(texture_mode != LINE_TEXTURE_NONE) {
+ if (texture_mode != LINE_TEXTURE_NONE) {
tt = tt_begin + angle_delta;
Vector2 tsc = Vector2(Math::cos(tt), Math::sin(tt));
- uvs.push_back(interpolate(uv_rect, 0.5f*(tsc+Vector2(1.f,1.f))));
+ uvs.push_back(interpolate(uv_rect, 0.5f * (tsc + Vector2(1.f, 1.f))));
}
// Make up triangles
int vi0 = vi;
- for(int ti = 0; ti < steps; ++ti) {
+ for (int ti = 0; ti < steps; ++ti) {
indices.push_back(vi0);
indices.push_back(++vi);
- indices.push_back(vi+1);
+ indices.push_back(vi + 1);
}
}
-
-
diff --git a/scene/2d/line_builder.h b/scene/2d/line_builder.h
index 3fc9e4bb85..43fd281d99 100644
--- a/scene/2d/line_builder.h
+++ b/scene/2d/line_builder.h
@@ -29,8 +29,8 @@
#ifndef LINE_BUILDER_H
#define LINE_BUILDER_H
-#include "math_2d.h"
#include "color.h"
+#include "math_2d.h"
#include "scene/resources/color_ramp.h"
enum LineJointMode {
@@ -61,7 +61,7 @@ public:
LineCapMode end_cap_mode;
float width;
Color default_color;
- ColorRamp* gradient;
+ ColorRamp *gradient;
LineTextureMode texture_mode;
float sharp_limit;
int round_precision;
@@ -97,8 +97,6 @@ private:
private:
bool _interpolate_color;
int _last_index[2]; // Index of last up and down vertices of the strip
-
};
-
#endif // LINE_BUILDER_H
diff --git a/scene/2d/navigation2d.cpp b/scene/2d/navigation2d.cpp
index 7f48749dc3..f0280a2f81 100644
--- a/scene/2d/navigation2d.cpp
+++ b/scene/2d/navigation2d.cpp
@@ -33,61 +33,59 @@
void Navigation2D::_navpoly_link(int p_id) {
ERR_FAIL_COND(!navpoly_map.has(p_id));
- NavMesh &nm=navpoly_map[p_id];
+ NavMesh &nm = navpoly_map[p_id];
ERR_FAIL_COND(nm.linked);
- PoolVector<Vector2> vertices=nm.navpoly->get_vertices();
+ PoolVector<Vector2> vertices = nm.navpoly->get_vertices();
int len = vertices.size();
- if (len==0)
+ if (len == 0)
return;
- PoolVector<Vector2>::Read r=vertices.read();
+ PoolVector<Vector2>::Read r = vertices.read();
- for(int i=0;i<nm.navpoly->get_polygon_count();i++) {
+ for (int i = 0; i < nm.navpoly->get_polygon_count(); i++) {
//build
- List<Polygon>::Element *P=nm.polygons.push_back(Polygon());
- Polygon &p=P->get();
- p.owner=&nm;
+ List<Polygon>::Element *P = nm.polygons.push_back(Polygon());
+ Polygon &p = P->get();
+ p.owner = &nm;
Vector<int> poly = nm.navpoly->get_polygon(i);
- int plen=poly.size();
- const int *indices=poly.ptr();
- bool valid=true;
+ int plen = poly.size();
+ const int *indices = poly.ptr();
+ bool valid = true;
p.edges.resize(plen);
Vector2 center;
- float sum=0;
+ float sum = 0;
- for(int j=0;j<plen;j++) {
+ for (int j = 0; j < plen; j++) {
int idx = indices[j];
- if (idx<0 || idx>=len) {
- valid=false;
+ if (idx < 0 || idx >= len) {
+ valid = false;
break;
}
Polygon::Edge e;
- Vector2 ep=nm.xform.xform(r[idx]);
- center+=ep;
- e.point=_get_point(ep);
- p.edges[j]=e;
-
- int idxn = indices[(j+1)%plen];
- if (idxn<0 || idxn>=len) {
- valid=false;
+ Vector2 ep = nm.xform.xform(r[idx]);
+ center += ep;
+ e.point = _get_point(ep);
+ p.edges[j] = e;
+
+ int idxn = indices[(j + 1) % plen];
+ if (idxn < 0 || idxn >= len) {
+ valid = false;
break;
}
Vector2 epn = nm.xform.xform(r[idxn]);
- sum+=(epn.x-ep.x)*(epn.y+ep.y);
-
-
+ sum += (epn.x - ep.x) * (epn.y + ep.y);
}
- p.clockwise=sum>0;
+ p.clockwise = sum > 0;
if (!valid) {
nm.polygons.pop_back();
@@ -95,106 +93,103 @@ void Navigation2D::_navpoly_link(int p_id) {
continue;
}
- p.center=center/plen;
+ p.center = center / plen;
//connect
- for(int j=0;j<plen;j++) {
+ for (int j = 0; j < plen; j++) {
- int next = (j+1)%plen;
- EdgeKey ek(p.edges[j].point,p.edges[next].point);
+ int next = (j + 1) % plen;
+ EdgeKey ek(p.edges[j].point, p.edges[next].point);
- Map<EdgeKey,Connection>::Element *C=connections.find(ek);
+ Map<EdgeKey, Connection>::Element *C = connections.find(ek);
if (!C) {
Connection c;
- c.A=&p;
- c.A_edge=j;
- c.B=NULL;
- c.B_edge=-1;
- connections[ek]=c;
+ c.A = &p;
+ c.A_edge = j;
+ c.B = NULL;
+ c.B_edge = -1;
+ connections[ek] = c;
} else {
- if (C->get().B!=NULL) {
+ if (C->get().B != NULL) {
ConnectionPending pending;
- pending.polygon=&p;
- pending.edge=j;
- p.edges[j].P=C->get().pending.push_back(pending);
+ pending.polygon = &p;
+ pending.edge = j;
+ p.edges[j].P = C->get().pending.push_back(pending);
continue;
//print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b));
}
- C->get().B=&p;
- C->get().B_edge=j;
- C->get().A->edges[C->get().A_edge].C=&p;
- C->get().A->edges[C->get().A_edge].C_edge=j;
- p.edges[j].C=C->get().A;
- p.edges[j].C_edge=C->get().A_edge;
+ C->get().B = &p;
+ C->get().B_edge = j;
+ C->get().A->edges[C->get().A_edge].C = &p;
+ C->get().A->edges[C->get().A_edge].C_edge = j;
+ p.edges[j].C = C->get().A;
+ p.edges[j].C_edge = C->get().A_edge;
//connection successful.
}
}
}
- nm.linked=true;
-
+ nm.linked = true;
}
-
void Navigation2D::_navpoly_unlink(int p_id) {
ERR_FAIL_COND(!navpoly_map.has(p_id));
- NavMesh &nm=navpoly_map[p_id];
+ NavMesh &nm = navpoly_map[p_id];
ERR_FAIL_COND(!nm.linked);
//print_line("UNLINK");
- for (List<Polygon>::Element *E=nm.polygons.front();E;E=E->next()) {
-
+ for (List<Polygon>::Element *E = nm.polygons.front(); E; E = E->next()) {
- Polygon &p=E->get();
+ Polygon &p = E->get();
int ec = p.edges.size();
- Polygon::Edge *edges=p.edges.ptr();
+ Polygon::Edge *edges = p.edges.ptr();
- for(int i=0;i<ec;i++) {
- int next = (i+1)%ec;
+ for (int i = 0; i < ec; i++) {
+ int next = (i + 1) % ec;
- EdgeKey ek(edges[i].point,edges[next].point);
- Map<EdgeKey,Connection>::Element *C=connections.find(ek);
+ EdgeKey ek(edges[i].point, edges[next].point);
+ Map<EdgeKey, Connection>::Element *C = connections.find(ek);
ERR_CONTINUE(!C);
if (edges[i].P) {
C->get().pending.erase(edges[i].P);
- edges[i].P=NULL;
+ edges[i].P = NULL;
} else if (C->get().B) {
//disconnect
- C->get().B->edges[C->get().B_edge].C=NULL;
- C->get().B->edges[C->get().B_edge].C_edge=-1;
- C->get().A->edges[C->get().A_edge].C=NULL;
- C->get().A->edges[C->get().A_edge].C_edge=-1;
+ C->get().B->edges[C->get().B_edge].C = NULL;
+ C->get().B->edges[C->get().B_edge].C_edge = -1;
+ C->get().A->edges[C->get().A_edge].C = NULL;
+ C->get().A->edges[C->get().A_edge].C_edge = -1;
- if (C->get().A==&E->get()) {
+ if (C->get().A == &E->get()) {
- C->get().A=C->get().B;
- C->get().A_edge=C->get().B_edge;
+ C->get().A = C->get().B;
+ C->get().A_edge = C->get().B_edge;
}
- C->get().B=NULL;
- C->get().B_edge=-1;
+ C->get().B = NULL;
+ C->get().B_edge = -1;
if (C->get().pending.size()) {
//reconnect if something is pending
ConnectionPending cp = C->get().pending.front()->get();
C->get().pending.pop_front();
- C->get().B=cp.polygon;
- C->get().B_edge=cp.edge;
- C->get().A->edges[C->get().A_edge].C=cp.polygon;
- C->get().A->edges[C->get().A_edge].C_edge=cp.edge;
- cp.polygon->edges[cp.edge].C=C->get().A;
- cp.polygon->edges[cp.edge].C_edge=C->get().A_edge;
- cp.polygon->edges[cp.edge].P=NULL;
+ C->get().B = cp.polygon;
+ C->get().B_edge = cp.edge;
+ C->get().A->edges[C->get().A_edge].C = cp.polygon;
+ C->get().A->edges[C->get().A_edge].C_edge = cp.edge;
+ cp.polygon->edges[cp.edge].C = C->get().A;
+ cp.polygon->edges[cp.edge].C_edge = C->get().A_edge;
+ cp.polygon->edges[cp.edge].P = NULL;
}
} else {
@@ -206,46 +201,39 @@ void Navigation2D::_navpoly_unlink(int p_id) {
nm.polygons.clear();
- nm.linked=false;
-
-
+ nm.linked = false;
}
-
-int Navigation2D::navpoly_create(const Ref<NavigationPolygon>& p_mesh, const Transform2D& p_xform, Object *p_owner) {
+int Navigation2D::navpoly_create(const Ref<NavigationPolygon> &p_mesh, const Transform2D &p_xform, Object *p_owner) {
int id = last_id++;
NavMesh nm;
- nm.linked=false;
- nm.navpoly=p_mesh;
- nm.xform=p_xform;
- nm.owner=p_owner;
- navpoly_map[id]=nm;
+ nm.linked = false;
+ nm.navpoly = p_mesh;
+ nm.xform = p_xform;
+ nm.owner = p_owner;
+ navpoly_map[id] = nm;
_navpoly_link(id);
return id;
}
-void Navigation2D::navpoly_set_transform(int p_id, const Transform2D& p_xform){
+void Navigation2D::navpoly_set_transform(int p_id, const Transform2D &p_xform) {
ERR_FAIL_COND(!navpoly_map.has(p_id));
- NavMesh &nm=navpoly_map[p_id];
- if (nm.xform==p_xform)
+ NavMesh &nm = navpoly_map[p_id];
+ if (nm.xform == p_xform)
return; //bleh
_navpoly_unlink(p_id);
- nm.xform=p_xform;
+ nm.xform = p_xform;
_navpoly_link(p_id);
-
-
-
}
-void Navigation2D::navpoly_remove(int p_id){
+void Navigation2D::navpoly_remove(int p_id) {
ERR_FAIL_COND(!navpoly_map.has(p_id));
_navpoly_unlink(p_id);
navpoly_map.erase(p_id);
-
}
#if 0
void Navigation2D::_clip_path(Vector<Vector2>& path, Polygon *from_poly, const Vector2& p_to_point, Polygon* p_to_poly) {
@@ -284,96 +272,91 @@ void Navigation2D::_clip_path(Vector<Vector2>& path, Polygon *from_poly, const V
}
#endif
-Vector<Vector2> Navigation2D::get_simple_path(const Vector2& p_start, const Vector2& p_end, bool p_optimize) {
+Vector<Vector2> Navigation2D::get_simple_path(const Vector2 &p_start, const Vector2 &p_end, bool p_optimize) {
-
- Polygon *begin_poly=NULL;
- Polygon *end_poly=NULL;
+ Polygon *begin_poly = NULL;
+ Polygon *end_poly = NULL;
Vector2 begin_point;
Vector2 end_point;
- float begin_d=1e20;
- float end_d=1e20;
+ float begin_d = 1e20;
+ float end_d = 1e20;
//look for point inside triangle
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
-
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
+ Polygon &p = F->get();
if (begin_d || end_d) {
- for(int i=2;i<p.edges.size();i++) {
+ for (int i = 2; i < p.edges.size(); i++) {
- if (begin_d>0) {
+ if (begin_d > 0) {
- if (Geometry::is_point_in_triangle(p_start,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {
+ if (Geometry::is_point_in_triangle(p_start, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) {
- begin_poly=&p;
- begin_point=p_start;
- begin_d=0;
- if (end_d==0)
+ begin_poly = &p;
+ begin_point = p_start;
+ begin_d = 0;
+ if (end_d == 0)
break;
-
}
}
- if (end_d>0) {
+ if (end_d > 0) {
- if (Geometry::is_point_in_triangle(p_end,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {
+ if (Geometry::is_point_in_triangle(p_end, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) {
- end_poly=&p;
- end_point=p_end;
- end_d=0;
- if (begin_d==0)
+ end_poly = &p;
+ end_point = p_end;
+ end_d = 0;
+ if (begin_d == 0)
break;
}
}
-
}
}
- p.prev_edge=-1;
+ p.prev_edge = -1;
}
}
//start or end not inside triangle.. look for closest segment :|
if (begin_d || end_d) {
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
+ Polygon &p = F->get();
int es = p.edges.size();
- for(int i=0;i<es;i++) {
+ for (int i = 0; i < es; i++) {
- Vector2 edge[2]={
+ Vector2 edge[2] = {
_get_vertex(p.edges[i].point),
- _get_vertex(p.edges[(i+1)%es].point)
+ _get_vertex(p.edges[(i + 1) % es].point)
};
-
- if (begin_d>0) {
- Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_start,edge);
+ if (begin_d > 0) {
+ Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_start, edge);
float d = spoint.distance_to(p_start);
- if (d<begin_d) {
- begin_poly=&p;
- begin_point=spoint;
- begin_d=d;
+ if (d < begin_d) {
+ begin_poly = &p;
+ begin_point = spoint;
+ begin_d = d;
}
}
- if (end_d>0) {
- Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_end,edge);
+ if (end_d > 0) {
+ Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_end, edge);
float d = spoint.distance_to(p_end);
- if (d<end_d) {
- end_poly=&p;
- end_point=spoint;
- end_d=d;
+ if (d < end_d) {
+ end_poly = &p;
+ end_point = spoint;
+ end_d = d;
}
}
}
@@ -386,96 +369,91 @@ Vector<Vector2> Navigation2D::get_simple_path(const Vector2& p_start, const Vect
return Vector<Vector2>(); //no path
}
- if (begin_poly==end_poly) {
+ if (begin_poly == end_poly) {
Vector<Vector2> path;
path.resize(2);
- path[0]=begin_point;
- path[1]=end_point;
+ path[0] = begin_point;
+ path[1] = end_point;
//print_line("Direct Path");
return path;
}
+ bool found_route = false;
- bool found_route=false;
-
- List<Polygon*> open_list;
+ List<Polygon *> open_list;
- begin_poly->entry=p_start;
+ begin_poly->entry = p_start;
- for(int i=0;i<begin_poly->edges.size();i++) {
+ for (int i = 0; i < begin_poly->edges.size(); i++) {
if (begin_poly->edges[i].C) {
- begin_poly->edges[i].C->prev_edge=begin_poly->edges[i].C_edge;
+ begin_poly->edges[i].C->prev_edge = begin_poly->edges[i].C_edge;
#ifdef USE_ENTRY_POINT
- Vector2 edge[2]={
+ Vector2 edge[2] = {
_get_vertex(begin_poly->edges[i].point),
- _get_vertex(begin_poly->edges[(i+1)%begin_poly->edges.size()].point)
+ _get_vertex(begin_poly->edges[(i + 1) % begin_poly->edges.size()].point)
};
- Vector2 entry = Geometry::get_closest_point_to_segment_2d(begin_poly->entry,edge);
+ Vector2 entry = Geometry::get_closest_point_to_segment_2d(begin_poly->entry, edge);
begin_poly->edges[i].C->distance = begin_poly->entry.distance_to(entry);
- begin_poly->edges[i].C->entry=entry;
+ begin_poly->edges[i].C->entry = entry;
#else
- begin_poly->edges[i].C->distance=begin_poly->center.distance_to(begin_poly->edges[i].C->center);
+ begin_poly->edges[i].C->distance = begin_poly->center.distance_to(begin_poly->edges[i].C->center);
#endif
open_list.push_back(begin_poly->edges[i].C);
- if (begin_poly->edges[i].C==end_poly) {
- found_route=true;
+ if (begin_poly->edges[i].C == end_poly) {
+ found_route = true;
}
}
}
+ while (!found_route) {
- while(!found_route) {
-
- if (open_list.size()==0) {
+ if (open_list.size() == 0) {
//print_line("NOU OPEN LIST");
break;
}
//check open list
- List<Polygon*>::Element *least_cost_poly=NULL;
- float least_cost=1e30;
+ List<Polygon *>::Element *least_cost_poly = NULL;
+ float least_cost = 1e30;
//this could be faster (cache previous results)
- for (List<Polygon*>::Element *E=open_list.front();E;E=E->next()) {
-
- Polygon *p=E->get();
+ for (List<Polygon *>::Element *E = open_list.front(); E; E = E->next()) {
+ Polygon *p = E->get();
- float cost=p->distance;
- cost+=p->center.distance_to(end_point);
+ float cost = p->distance;
+ cost += p->center.distance_to(end_point);
- if (cost<least_cost) {
+ if (cost < least_cost) {
- least_cost_poly=E;
- least_cost=cost;
+ least_cost_poly = E;
+ least_cost = cost;
}
}
-
- Polygon *p=least_cost_poly->get();
+ Polygon *p = least_cost_poly->get();
//open the neighbours for search
int es = p->edges.size();
- for(int i=0;i<es;i++) {
+ for (int i = 0; i < es; i++) {
-
- Polygon::Edge &e=p->edges[i];
+ Polygon::Edge &e = p->edges[i];
if (!e.C)
continue;
#ifdef USE_ENTRY_POINT
- Vector2 edge[2]={
+ Vector2 edge[2] = {
_get_vertex(p->edges[i].point),
- _get_vertex(p->edges[(i+1)%es].point)
+ _get_vertex(p->edges[(i + 1) % es].point)
};
- Vector2 edge_entry = Geometry::get_closest_point_to_segment_2d(p->entry,edge);
+ Vector2 edge_entry = Geometry::get_closest_point_to_segment_2d(p->entry, edge);
float distance = p->entry.distance_to(edge_entry) + p->distance;
#else
@@ -484,36 +462,33 @@ Vector<Vector2> Navigation2D::get_simple_path(const Vector2& p_start, const Vect
#endif
-
- if (e.C->prev_edge!=-1) {
+ if (e.C->prev_edge != -1) {
//oh this was visited already, can we win the cost?
- if (e.C->distance>distance) {
+ if (e.C->distance > distance) {
- e.C->prev_edge=e.C_edge;
- e.C->distance=distance;
+ e.C->prev_edge = e.C_edge;
+ e.C->distance = distance;
#ifdef USE_ENTRY_POINT
- e.C->entry=edge_entry;
+ e.C->entry = edge_entry;
#endif
}
} else {
//add to open neighbours
- e.C->prev_edge=e.C_edge;
- e.C->distance=distance;
+ e.C->prev_edge = e.C_edge;
+ e.C->distance = distance;
#ifdef USE_ENTRY_POINT
- e.C->entry=edge_entry;
+ e.C->entry = edge_entry;
#endif
open_list.push_back(e.C);
- if (e.C==end_poly) {
+ if (e.C == end_poly) {
//oh my reached end! stop algorithm
- found_route=true;
+ found_route = true;
break;
-
}
-
}
}
@@ -552,40 +527,40 @@ debug path
if (p_optimize) {
//string pulling
- Vector2 apex_point=end_point;
- Vector2 portal_left=apex_point;
- Vector2 portal_right=apex_point;
- Polygon *left_poly=end_poly;
- Polygon *right_poly=end_poly;
- Polygon *p=end_poly;
+ Vector2 apex_point = end_point;
+ Vector2 portal_left = apex_point;
+ Vector2 portal_right = apex_point;
+ Polygon *left_poly = end_poly;
+ Polygon *right_poly = end_poly;
+ Polygon *p = end_poly;
path.push_back(end_point);
- while(p) {
+ while (p) {
Vector2 left;
Vector2 right;
//#define CLOCK_TANGENT(m_a,m_b,m_c) ( ((m_a)-(m_c)).cross((m_a)-(m_b)) )
-#define CLOCK_TANGENT(m_a,m_b,m_c) ((((m_a).x - (m_c).x) * ((m_b).y - (m_c).y) - ((m_b).x - (m_c).x) * ((m_a).y - (m_c).y)))
+#define CLOCK_TANGENT(m_a, m_b, m_c) ((((m_a).x - (m_c).x) * ((m_b).y - (m_c).y) - ((m_b).x - (m_c).x) * ((m_a).y - (m_c).y)))
- if (p==begin_poly) {
- left=begin_point;
- right=begin_point;
+ if (p == begin_poly) {
+ left = begin_point;
+ right = begin_point;
} else {
int prev = p->prev_edge;
- int prev_n = (p->prev_edge+1)%p->edges.size();
+ int prev_n = (p->prev_edge + 1) % p->edges.size();
left = _get_vertex(p->edges[prev].point);
right = _get_vertex(p->edges[prev_n].point);
if (p->clockwise) {
- SWAP(left,right);
+ SWAP(left, right);
}
/*if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5) < 0){
SWAP(left,right);
}*/
}
- bool skip=false;
+ bool skip = false;
/*
print_line("-----\nAPEX: "+(apex_point-end_point));
@@ -603,221 +578,202 @@ debug path
print_line("\tRight Test: "+rtos(CLOCK_TANGENT(apex_point,right,portal_left)));
*/
-
- if (CLOCK_TANGENT(apex_point,portal_left,left) >= 0){
+ if (CLOCK_TANGENT(apex_point, portal_left, left) >= 0) {
//process
- if (portal_left.distance_squared_to(apex_point)<CMP_EPSILON || CLOCK_TANGENT(apex_point,left,portal_right) > 0) {
- left_poly=p;
- portal_left=left;
+ if (portal_left.distance_squared_to(apex_point) < CMP_EPSILON || CLOCK_TANGENT(apex_point, left, portal_right) > 0) {
+ left_poly = p;
+ portal_left = left;
//print_line("***ADVANCE LEFT");
} else {
- apex_point=portal_right;
- p=right_poly;
- left_poly=p;
- portal_left=apex_point;
- portal_right=apex_point;
- if (path[path.size()-1].distance_to(apex_point)>CMP_EPSILON)
+ apex_point = portal_right;
+ p = right_poly;
+ left_poly = p;
+ portal_left = apex_point;
+ portal_right = apex_point;
+ if (path[path.size() - 1].distance_to(apex_point) > CMP_EPSILON)
path.push_back(apex_point);
- skip=true;
+ skip = true;
//print_line("addpoint left");
//print_line("***CLIP LEFT");
}
}
- if (!skip && CLOCK_TANGENT(apex_point,portal_right,right) <= 0){
+ if (!skip && CLOCK_TANGENT(apex_point, portal_right, right) <= 0) {
//process
- if (portal_right.distance_squared_to(apex_point)<CMP_EPSILON || CLOCK_TANGENT(apex_point,right,portal_left) < 0) {
- right_poly=p;
- portal_right=right;
+ if (portal_right.distance_squared_to(apex_point) < CMP_EPSILON || CLOCK_TANGENT(apex_point, right, portal_left) < 0) {
+ right_poly = p;
+ portal_right = right;
//print_line("***ADVANCE RIGHT");
} else {
- apex_point=portal_left;
- p=left_poly;
- right_poly=p;
- portal_right=apex_point;
- portal_left=apex_point;
- if (path[path.size()-1].distance_to(apex_point)>CMP_EPSILON)
+ apex_point = portal_left;
+ p = left_poly;
+ right_poly = p;
+ portal_right = apex_point;
+ portal_left = apex_point;
+ if (path[path.size() - 1].distance_to(apex_point) > CMP_EPSILON)
path.push_back(apex_point);
//print_line("addpoint right");
//print_line("***CLIP RIGHT");
-
}
}
- if (p!=begin_poly)
- p=p->edges[p->prev_edge].C;
+ if (p != begin_poly)
+ p = p->edges[p->prev_edge].C;
else
- p=NULL;
-
+ p = NULL;
}
- if (path[path.size()-1].distance_to(begin_point)>CMP_EPSILON)
+ if (path[path.size() - 1].distance_to(begin_point) > CMP_EPSILON)
path.push_back(begin_point);
path.invert();
-
-
-
} else {
//midpoints
- Polygon *p=end_poly;
+ Polygon *p = end_poly;
path.push_back(end_point);
- while(true) {
+ while (true) {
int prev = p->prev_edge;
- int prev_n = (p->prev_edge+1)%p->edges.size();
- Vector2 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point))*0.5;
+ int prev_n = (p->prev_edge + 1) % p->edges.size();
+ Vector2 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point)) * 0.5;
path.push_back(point);
p = p->edges[prev].C;
- if (p==begin_poly)
+ if (p == begin_poly)
break;
}
path.push_back(begin_point);
-
path.invert();
}
return path;
}
-
return Vector<Vector2>();
-
}
+Vector2 Navigation2D::get_closest_point(const Vector2 &p_point) {
-Vector2 Navigation2D::get_closest_point(const Vector2& p_point) {
-
- Vector2 closest_point=Vector2();
- float closest_point_d=1e20;
+ Vector2 closest_point = Vector2();
+ float closest_point_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- if (Geometry::is_point_in_triangle(p_point,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {
+ if (Geometry::is_point_in_triangle(p_point, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) {
return p_point; //inside triangle, nothing else to discuss
}
-
}
}
}
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
+ Polygon &p = F->get();
int es = p.edges.size();
- for(int i=0;i<es;i++) {
+ for (int i = 0; i < es; i++) {
- Vector2 edge[2]={
+ Vector2 edge[2] = {
_get_vertex(p.edges[i].point),
- _get_vertex(p.edges[(i+1)%es].point)
+ _get_vertex(p.edges[(i + 1) % es].point)
};
-
- Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_point,edge);
+ Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_point, edge);
float d = spoint.distance_squared_to(p_point);
- if (d<closest_point_d) {
+ if (d < closest_point_d) {
- closest_point=spoint;
- closest_point_d=d;
+ closest_point = spoint;
+ closest_point_d = d;
}
}
}
}
return closest_point;
-
}
-Object* Navigation2D::get_closest_point_owner(const Vector2& p_point) {
+Object *Navigation2D::get_closest_point_owner(const Vector2 &p_point) {
- Object *owner=NULL;
- Vector2 closest_point=Vector2();
- float closest_point_d=1e20;
+ Object *owner = NULL;
+ Vector2 closest_point = Vector2();
+ float closest_point_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- if (Geometry::is_point_in_triangle(p_point,_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point))) {
+ if (Geometry::is_point_in_triangle(p_point, _get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point))) {
E->get().owner;
}
-
}
}
}
- for (Map<int,NavMesh>::Element*E=navpoly_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navpoly_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
+ Polygon &p = F->get();
int es = p.edges.size();
- for(int i=0;i<es;i++) {
+ for (int i = 0; i < es; i++) {
- Vector2 edge[2]={
+ Vector2 edge[2] = {
_get_vertex(p.edges[i].point),
- _get_vertex(p.edges[(i+1)%es].point)
+ _get_vertex(p.edges[(i + 1) % es].point)
};
-
- Vector2 spoint=Geometry::get_closest_point_to_segment_2d(p_point,edge);
+ Vector2 spoint = Geometry::get_closest_point_to_segment_2d(p_point, edge);
float d = spoint.distance_squared_to(p_point);
- if (d<closest_point_d) {
+ if (d < closest_point_d) {
- closest_point=spoint;
- closest_point_d=d;
- owner=E->get().owner;
+ closest_point = spoint;
+ closest_point_d = d;
+ owner = E->get().owner;
}
}
}
}
return owner;
-
}
-
void Navigation2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("navpoly_create","mesh:NavigationPolygon","xform","owner"),&Navigation2D::navpoly_create,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("navpoly_set_transform","id","xform"),&Navigation2D::navpoly_set_transform);
- ClassDB::bind_method(D_METHOD("navpoly_remove","id"),&Navigation2D::navpoly_remove);
-
- ClassDB::bind_method(D_METHOD("get_simple_path","start","end","optimize"),&Navigation2D::get_simple_path,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("get_closest_point","to_point"),&Navigation2D::get_closest_point);
- ClassDB::bind_method(D_METHOD("get_closest_point_owner","to_point"),&Navigation2D::get_closest_point_owner);
+ ClassDB::bind_method(D_METHOD("navpoly_create", "mesh:NavigationPolygon", "xform", "owner"), &Navigation2D::navpoly_create, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("navpoly_set_transform", "id", "xform"), &Navigation2D::navpoly_set_transform);
+ ClassDB::bind_method(D_METHOD("navpoly_remove", "id"), &Navigation2D::navpoly_remove);
+ ClassDB::bind_method(D_METHOD("get_simple_path", "start", "end", "optimize"), &Navigation2D::get_simple_path, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Navigation2D::get_closest_point);
+ ClassDB::bind_method(D_METHOD("get_closest_point_owner", "to_point"), &Navigation2D::get_closest_point_owner);
}
Navigation2D::Navigation2D() {
- ERR_FAIL_COND( sizeof(Point)!=8 );
- cell_size=1; // one pixel
- last_id=1;
-
+ ERR_FAIL_COND(sizeof(Point) != 8);
+ cell_size = 1; // one pixel
+ last_id = 1;
}
diff --git a/scene/2d/navigation2d.h b/scene/2d/navigation2d.h
index 63827ebb6d..afa565518d 100644
--- a/scene/2d/navigation2d.h
+++ b/scene/2d/navigation2d.h
@@ -29,45 +29,42 @@
#ifndef NAVIGATION_2D_H
#define NAVIGATION_2D_H
-#include "scene/2d/node_2d.h"
#include "scene/2d/navigation_polygon.h"
+#include "scene/2d/node_2d.h"
class Navigation2D : public Node2D {
- GDCLASS( Navigation2D, Node2D);
-
+ GDCLASS(Navigation2D, Node2D);
union Point {
struct {
- int64_t x:32;
- int64_t y:32;
+ int64_t x : 32;
+ int64_t y : 32;
};
uint64_t key;
- bool operator<(const Point& p_key) const { return key < p_key.key; }
+ bool operator<(const Point &p_key) const { return key < p_key.key; }
};
-
struct EdgeKey {
Point a;
Point b;
- bool operator<(const EdgeKey& p_key) const {
- return (a.key==p_key.a.key)?(b.key<p_key.b.key):(a.key<p_key.a.key);
+ bool operator<(const EdgeKey &p_key) const {
+ return (a.key == p_key.a.key) ? (b.key < p_key.b.key) : (a.key < p_key.a.key);
};
- EdgeKey(const Point& p_a=Point(),const Point& p_b=Point()) {
- a=p_a;
- b=p_b;
+ EdgeKey(const Point &p_a = Point(), const Point &p_b = Point()) {
+ a = p_a;
+ b = p_b;
if (a.key > b.key) {
- SWAP(a,b);
+ SWAP(a, b);
}
}
};
-
struct NavMesh;
struct Polygon;
@@ -84,7 +81,11 @@ class Navigation2D : public Node2D {
Polygon *C; //connection
int C_edge;
List<ConnectionPending>::Element *P;
- Edge() { C=NULL; C_edge=-1; P=NULL; }
+ Edge() {
+ C = NULL;
+ C_edge = -1;
+ P = NULL;
+ }
};
Vector<Edge> edges;
@@ -100,7 +101,6 @@ class Navigation2D : public Node2D {
NavMesh *owner;
};
-
struct Connection {
Polygon *A;
@@ -110,11 +110,15 @@ class Navigation2D : public Node2D {
List<ConnectionPending> pending;
- Connection() { A=NULL; B=NULL; A_edge=-1; B_edge=-1;}
+ Connection() {
+ A = NULL;
+ B = NULL;
+ A_edge = -1;
+ B_edge = -1;
+ }
};
- Map<EdgeKey,Connection> connections;
-
+ Map<EdgeKey, Connection> connections;
struct NavMesh {
@@ -123,57 +127,48 @@ class Navigation2D : public Node2D {
bool linked;
Ref<NavigationPolygon> navpoly;
List<Polygon> polygons;
-
};
+ _FORCE_INLINE_ Point _get_point(const Vector2 &p_pos) const {
-
- _FORCE_INLINE_ Point _get_point(const Vector2& p_pos) const {
-
- int x = int(Math::floor(p_pos.x/cell_size));
- int y = int(Math::floor(p_pos.y/cell_size));
+ int x = int(Math::floor(p_pos.x / cell_size));
+ int y = int(Math::floor(p_pos.y / cell_size));
Point p;
- p.key=0;
- p.x=x;
- p.y=y;
+ p.key = 0;
+ p.x = x;
+ p.y = y;
return p;
-
}
- _FORCE_INLINE_ Vector2 _get_vertex(const Point& p_point) const {
+ _FORCE_INLINE_ Vector2 _get_vertex(const Point &p_point) const {
- return Vector2(p_point.x,p_point.y)*cell_size;
+ return Vector2(p_point.x, p_point.y) * cell_size;
}
-
-
void _navpoly_link(int p_id);
void _navpoly_unlink(int p_id);
float cell_size;
- Map<int,NavMesh> navpoly_map;
+ Map<int, NavMesh> navpoly_map;
int last_id;
#if 0
void _clip_path(Vector<Vector2>& path,Polygon *from_poly, const Vector2& p_to_point, Polygon* p_to_poly);
#endif
protected:
-
static void _bind_methods();
public:
-
//API should be as dynamic as possible
- int navpoly_create(const Ref<NavigationPolygon>& p_mesh,const Transform2D& p_xform,Object* p_owner=NULL);
- void navpoly_set_transform(int p_id, const Transform2D& p_xform);
+ int navpoly_create(const Ref<NavigationPolygon> &p_mesh, const Transform2D &p_xform, Object *p_owner = NULL);
+ void navpoly_set_transform(int p_id, const Transform2D &p_xform);
void navpoly_remove(int p_id);
- Vector<Vector2> get_simple_path(const Vector2& p_start, const Vector2& p_end,bool p_optimize=true);
- Vector2 get_closest_point(const Vector2& p_point);
- Object* get_closest_point_owner(const Vector2& p_point);
+ Vector<Vector2> get_simple_path(const Vector2 &p_start, const Vector2 &p_end, bool p_optimize = true);
+ Vector2 get_closest_point(const Vector2 &p_point);
+ Object *get_closest_point_owner(const Vector2 &p_point);
Navigation2D();
};
-
#endif // Navigation2D2D_H
diff --git a/scene/2d/navigation_polygon.cpp b/scene/2d/navigation_polygon.cpp
index 9dbbd34ae9..570bd00a5b 100644
--- a/scene/2d/navigation_polygon.cpp
+++ b/scene/2d/navigation_polygon.cpp
@@ -27,26 +27,25 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "navigation_polygon.h"
+#include "core_string_names.h"
#include "navigation2d.h"
#include "triangulator.h"
-#include "core_string_names.h"
-void NavigationPolygon::set_vertices(const PoolVector<Vector2>& p_vertices) {
+void NavigationPolygon::set_vertices(const PoolVector<Vector2> &p_vertices) {
- vertices=p_vertices;
+ vertices = p_vertices;
}
-PoolVector<Vector2> NavigationPolygon::get_vertices() const{
+PoolVector<Vector2> NavigationPolygon::get_vertices() const {
return vertices;
}
-
-void NavigationPolygon::_set_polygons(const Array& p_array) {
+void NavigationPolygon::_set_polygons(const Array &p_array) {
polygons.resize(p_array.size());
- for(int i=0;i<p_array.size();i++) {
- polygons[i].indices=p_array[i];
+ for (int i = 0; i < p_array.size(); i++) {
+ polygons[i].indices = p_array[i];
}
}
@@ -54,18 +53,18 @@ Array NavigationPolygon::_get_polygons() const {
Array ret;
ret.resize(polygons.size());
- for(int i=0;i<ret.size();i++) {
- ret[i]=polygons[i].indices;
+ for (int i = 0; i < ret.size(); i++) {
+ ret[i] = polygons[i].indices;
}
return ret;
}
-void NavigationPolygon::_set_outlines(const Array& p_array) {
+void NavigationPolygon::_set_outlines(const Array &p_array) {
outlines.resize(p_array.size());
- for(int i=0;i<p_array.size();i++) {
- outlines[i]=p_array[i];
+ for (int i = 0; i < p_array.size(); i++) {
+ outlines[i] = p_array[i];
}
}
@@ -73,132 +72,125 @@ Array NavigationPolygon::_get_outlines() const {
Array ret;
ret.resize(outlines.size());
- for(int i=0;i<ret.size();i++) {
- ret[i]=outlines[i];
+ for (int i = 0; i < ret.size(); i++) {
+ ret[i] = outlines[i];
}
return ret;
}
-
-void NavigationPolygon::add_polygon(const Vector<int>& p_polygon){
+void NavigationPolygon::add_polygon(const Vector<int> &p_polygon) {
Polygon polygon;
- polygon.indices=p_polygon;
+ polygon.indices = p_polygon;
polygons.push_back(polygon);
-
}
-void NavigationPolygon::add_outline_at_index(const PoolVector<Vector2>& p_outline,int p_index) {
+void NavigationPolygon::add_outline_at_index(const PoolVector<Vector2> &p_outline, int p_index) {
- outlines.insert(p_index,p_outline);
+ outlines.insert(p_index, p_outline);
}
-int NavigationPolygon::get_polygon_count() const{
+int NavigationPolygon::get_polygon_count() const {
return polygons.size();
}
-Vector<int> NavigationPolygon::get_polygon(int p_idx){
+Vector<int> NavigationPolygon::get_polygon(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,polygons.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector<int>());
return polygons[p_idx].indices;
}
-void NavigationPolygon::clear_polygons(){
+void NavigationPolygon::clear_polygons() {
polygons.clear();
}
-void NavigationPolygon::add_outline(const PoolVector<Vector2>& p_outline) {
+void NavigationPolygon::add_outline(const PoolVector<Vector2> &p_outline) {
outlines.push_back(p_outline);
}
-int NavigationPolygon::get_outline_count() const{
+int NavigationPolygon::get_outline_count() const {
return outlines.size();
}
-void NavigationPolygon::set_outline(int p_idx,const PoolVector<Vector2>& p_outline) {
- ERR_FAIL_INDEX(p_idx,outlines.size());
- outlines[p_idx]=p_outline;
+void NavigationPolygon::set_outline(int p_idx, const PoolVector<Vector2> &p_outline) {
+ ERR_FAIL_INDEX(p_idx, outlines.size());
+ outlines[p_idx] = p_outline;
}
void NavigationPolygon::remove_outline(int p_idx) {
- ERR_FAIL_INDEX(p_idx,outlines.size());
+ ERR_FAIL_INDEX(p_idx, outlines.size());
outlines.remove(p_idx);
-
}
PoolVector<Vector2> NavigationPolygon::get_outline(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,outlines.size(),PoolVector<Vector2>());
+ ERR_FAIL_INDEX_V(p_idx, outlines.size(), PoolVector<Vector2>());
return outlines[p_idx];
}
-void NavigationPolygon::clear_outlines(){
+void NavigationPolygon::clear_outlines() {
outlines.clear();
}
-void NavigationPolygon::make_polygons_from_outlines(){
+void NavigationPolygon::make_polygons_from_outlines() {
- List<TriangulatorPoly> in_poly,out_poly;
+ List<TriangulatorPoly> in_poly, out_poly;
- Vector2 outside_point(-1e10,-1e10);
+ Vector2 outside_point(-1e10, -1e10);
- for(int i=0;i<outlines.size();i++) {
+ for (int i = 0; i < outlines.size(); i++) {
PoolVector<Vector2> ol = outlines[i];
int olsize = ol.size();
- if (olsize<3)
+ if (olsize < 3)
continue;
- PoolVector<Vector2>::Read r=ol.read();
- for(int j=0;j<olsize;j++) {
- outside_point.x = MAX( r[j].x, outside_point.x );
- outside_point.y = MAX( r[j].y, outside_point.y );
+ PoolVector<Vector2>::Read r = ol.read();
+ for (int j = 0; j < olsize; j++) {
+ outside_point.x = MAX(r[j].x, outside_point.x);
+ outside_point.y = MAX(r[j].y, outside_point.y);
}
-
}
- outside_point+=Vector2(0.7239784,0.819238); //avoid precision issues
+ outside_point += Vector2(0.7239784, 0.819238); //avoid precision issues
-
-
- for(int i=0;i<outlines.size();i++) {
+ for (int i = 0; i < outlines.size(); i++) {
PoolVector<Vector2> ol = outlines[i];
int olsize = ol.size();
- if (olsize<3)
+ if (olsize < 3)
continue;
- PoolVector<Vector2>::Read r=ol.read();
+ PoolVector<Vector2>::Read r = ol.read();
- int interscount=0;
+ int interscount = 0;
//test if this is an outer outline
- for(int k=0;k<outlines.size();k++) {
+ for (int k = 0; k < outlines.size(); k++) {
- if (i==k)
+ if (i == k)
continue; //no self intersect
PoolVector<Vector2> ol2 = outlines[k];
int olsize2 = ol2.size();
- if (olsize2<3)
+ if (olsize2 < 3)
continue;
- PoolVector<Vector2>::Read r2=ol2.read();
+ PoolVector<Vector2>::Read r2 = ol2.read();
- for(int l=0;l<olsize2;l++) {
+ for (int l = 0; l < olsize2; l++) {
- if (Geometry::segment_intersects_segment_2d(r[0],outside_point,r2[l],r2[(l+1)%olsize2],NULL)) {
+ if (Geometry::segment_intersects_segment_2d(r[0], outside_point, r2[l], r2[(l + 1) % olsize2], NULL)) {
interscount++;
}
}
-
}
- bool outer = (interscount%2)==0;
+ bool outer = (interscount % 2) == 0;
TriangulatorPoly tp;
tp.Init(olsize);
- for(int j=0;j<olsize;j++) {
- tp[j]=r[j];
+ for (int j = 0; j < olsize; j++) {
+ tp[j] = r[j];
}
if (outer)
@@ -211,9 +203,8 @@ void NavigationPolygon::make_polygons_from_outlines(){
in_poly.push_back(tp);
}
-
TriangulatorPartition tpart;
- if (tpart.ConvexPartition_HM(&in_poly,&out_poly)==0) { //failed!
+ if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { //failed!
print_line("convex partition failed!");
return;
}
@@ -221,18 +212,18 @@ void NavigationPolygon::make_polygons_from_outlines(){
polygons.clear();
vertices.resize(0);
- Map<Vector2,int> points;
- for(List<TriangulatorPoly>::Element*I = out_poly.front();I;I=I->next()) {
+ Map<Vector2, int> points;
+ for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
- TriangulatorPoly& tp = I->get();
+ TriangulatorPoly &tp = I->get();
struct Polygon p;
- for(int i=0;i<tp.GetNumPoints();i++) {
+ for (int i = 0; i < tp.GetNumPoints(); i++) {
- Map<Vector2,int>::Element *E=points.find(tp[i]);
+ Map<Vector2, int>::Element *E = points.find(tp[i]);
if (!E) {
- E=points.insert(tp[i],vertices.size());
+ E = points.insert(tp[i], vertices.size());
vertices.push_back(tp[i]);
}
p.indices.push_back(E->get());
@@ -244,56 +235,53 @@ void NavigationPolygon::make_polygons_from_outlines(){
emit_signal(CoreStringNames::get_singleton()->changed);
}
-
void NavigationPolygon::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_vertices","vertices"),&NavigationPolygon::set_vertices);
- ClassDB::bind_method(D_METHOD("get_vertices"),&NavigationPolygon::get_vertices);
+ ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationPolygon::set_vertices);
+ ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationPolygon::get_vertices);
- ClassDB::bind_method(D_METHOD("add_polygon","polygon"),&NavigationPolygon::add_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon_count"),&NavigationPolygon::get_polygon_count);
- ClassDB::bind_method(D_METHOD("get_polygon","idx"),&NavigationPolygon::get_polygon);
- ClassDB::bind_method(D_METHOD("clear_polygons"),&NavigationPolygon::clear_polygons);
+ ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationPolygon::add_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationPolygon::get_polygon_count);
+ ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationPolygon::get_polygon);
+ ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationPolygon::clear_polygons);
- ClassDB::bind_method(D_METHOD("add_outline","outline"),&NavigationPolygon::add_outline);
- ClassDB::bind_method(D_METHOD("add_outline_at_index","outline","index"),&NavigationPolygon::add_outline_at_index);
- ClassDB::bind_method(D_METHOD("get_outline_count"),&NavigationPolygon::get_outline_count);
- ClassDB::bind_method(D_METHOD("set_outline","idx","outline"),&NavigationPolygon::set_outline);
- ClassDB::bind_method(D_METHOD("get_outline","idx"),&NavigationPolygon::get_outline);
- ClassDB::bind_method(D_METHOD("remove_outline","idx"),&NavigationPolygon::remove_outline);
- ClassDB::bind_method(D_METHOD("clear_outlines"),&NavigationPolygon::clear_outlines);
- ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"),&NavigationPolygon::make_polygons_from_outlines);
+ ClassDB::bind_method(D_METHOD("add_outline", "outline"), &NavigationPolygon::add_outline);
+ ClassDB::bind_method(D_METHOD("add_outline_at_index", "outline", "index"), &NavigationPolygon::add_outline_at_index);
+ ClassDB::bind_method(D_METHOD("get_outline_count"), &NavigationPolygon::get_outline_count);
+ ClassDB::bind_method(D_METHOD("set_outline", "idx", "outline"), &NavigationPolygon::set_outline);
+ ClassDB::bind_method(D_METHOD("get_outline", "idx"), &NavigationPolygon::get_outline);
+ ClassDB::bind_method(D_METHOD("remove_outline", "idx"), &NavigationPolygon::remove_outline);
+ ClassDB::bind_method(D_METHOD("clear_outlines"), &NavigationPolygon::clear_outlines);
+ ClassDB::bind_method(D_METHOD("make_polygons_from_outlines"), &NavigationPolygon::make_polygons_from_outlines);
- ClassDB::bind_method(D_METHOD("_set_polygons","polygons"),&NavigationPolygon::_set_polygons);
- ClassDB::bind_method(D_METHOD("_get_polygons"),&NavigationPolygon::_get_polygons);
+ ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationPolygon::_set_polygons);
+ ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationPolygon::_get_polygons);
- ClassDB::bind_method(D_METHOD("_set_outlines","outlines"),&NavigationPolygon::_set_outlines);
- ClassDB::bind_method(D_METHOD("_get_outlines"),&NavigationPolygon::_get_outlines);
+ ClassDB::bind_method(D_METHOD("_set_outlines", "outlines"), &NavigationPolygon::_set_outlines);
+ ClassDB::bind_method(D_METHOD("_get_outlines"), &NavigationPolygon::_get_outlines);
- ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"vertices",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_vertices","get_vertices");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"polygons",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_polygons","_get_polygons");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"outlines",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_outlines","_get_outlines");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_vertices", "get_vertices");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_polygons", "_get_polygons");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "outlines", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_outlines", "_get_outlines");
}
NavigationPolygon::NavigationPolygon() {
-
-
}
void NavigationPolygonInstance::set_enabled(bool p_enabled) {
- if (enabled==p_enabled)
+ if (enabled == p_enabled)
return;
- enabled=p_enabled;
+ enabled = p_enabled;
if (!is_inside_tree())
return;
if (!enabled) {
- if (nav_id!=-1) {
+ if (nav_id != -1) {
navigation->navpoly_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
} else {
@@ -301,10 +289,9 @@ void NavigationPolygonInstance::set_enabled(bool p_enabled) {
if (navpoly.is_valid()) {
- nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this);
+ nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this);
}
}
-
}
if (get_tree()->is_editor_hint() || get_tree()->is_debugging_navigation_hint())
@@ -315,41 +302,37 @@ void NavigationPolygonInstance::set_enabled(bool p_enabled) {
bool NavigationPolygonInstance::is_enabled() const {
-
return enabled;
}
-
/////////////////////////////
-
void NavigationPolygonInstance::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- Node2D *c=this;
- while(c) {
+ Node2D *c = this;
+ while (c) {
- navigation=c->cast_to<Navigation2D>();
+ navigation = c->cast_to<Navigation2D>();
if (navigation) {
if (enabled && navpoly.is_valid()) {
- nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this);
+ nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this);
}
break;
}
- c=c->get_parent()->cast_to<Node2D>();
+ c = c->get_parent()->cast_to<Node2D>();
}
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
- if (navigation && nav_id!=-1) {
- navigation->navpoly_set_transform(nav_id,get_relative_transform_to_parent(navigation));
+ if (navigation && nav_id != -1) {
+ navigation->navpoly_set_transform(nav_id, get_relative_transform_to_parent(navigation));
}
} break;
@@ -357,28 +340,27 @@ void NavigationPolygonInstance::_notification(int p_what) {
if (navigation) {
- if (nav_id!=-1) {
+ if (nav_id != -1) {
navigation->navpoly_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
}
- navigation=NULL;
+ navigation = NULL;
} break;
case NOTIFICATION_DRAW: {
if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_navigation_hint()) && navpoly.is_valid()) {
- PoolVector<Vector2> verts=navpoly->get_vertices();
+ PoolVector<Vector2> verts = navpoly->get_vertices();
int vsize = verts.size();
- if (vsize<3)
+ if (vsize < 3)
return;
-
Color color;
if (enabled) {
- color=get_tree()->get_debug_navigation_color();
+ color = get_tree()->get_debug_navigation_color();
} else {
- color=get_tree()->get_debug_navigation_disabled_color();
+ color = get_tree()->get_debug_navigation_disabled_color();
}
Vector<Color> colors;
Vector<Vector2> vertices;
@@ -386,66 +368,61 @@ void NavigationPolygonInstance::_notification(int p_what) {
colors.resize(vsize);
{
PoolVector<Vector2>::Read vr = verts.read();
- for(int i=0;i<vsize;i++) {
- vertices[i]=vr[i];
- colors[i]=color;
+ for (int i = 0; i < vsize; i++) {
+ vertices[i] = vr[i];
+ colors[i] = color;
}
}
Vector<int> indices;
-
- for(int i=0;i<navpoly->get_polygon_count();i++) {
+ for (int i = 0; i < navpoly->get_polygon_count(); i++) {
Vector<int> polygon = navpoly->get_polygon(i);
- for(int j=2;j<polygon.size();j++) {
+ for (int j = 2; j < polygon.size(); j++) {
- int kofs[3]={0,j-1,j};
- for(int k=0;k<3;k++) {
+ int kofs[3] = { 0, j - 1, j };
+ for (int k = 0; k < 3; k++) {
- int idx = polygon[ kofs[k] ];
- ERR_FAIL_INDEX(idx,vsize);
+ int idx = polygon[kofs[k]];
+ ERR_FAIL_INDEX(idx, vsize);
indices.push_back(idx);
}
}
}
- VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(),indices,vertices,colors);
-
+ VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, vertices, colors);
}
} break;
-
}
}
+void NavigationPolygonInstance::set_navigation_polygon(const Ref<NavigationPolygon> &p_navpoly) {
-void NavigationPolygonInstance::set_navigation_polygon(const Ref<NavigationPolygon>& p_navpoly) {
-
- if (p_navpoly==navpoly)
+ if (p_navpoly == navpoly)
return;
- if (navigation && nav_id!=-1) {
+ if (navigation && nav_id != -1) {
navigation->navpoly_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
if (navpoly.is_valid()) {
- navpoly->disconnect(CoreStringNames::get_singleton()->changed,this,"_navpoly_changed");
+ navpoly->disconnect(CoreStringNames::get_singleton()->changed, this, "_navpoly_changed");
}
- navpoly=p_navpoly;
+ navpoly = p_navpoly;
if (navpoly.is_valid()) {
- navpoly->connect(CoreStringNames::get_singleton()->changed,this,"_navpoly_changed");
+ navpoly->connect(CoreStringNames::get_singleton()->changed, this, "_navpoly_changed");
}
if (navigation && navpoly.is_valid() && enabled) {
- nav_id = navigation->navpoly_create(navpoly,get_relative_transform_to_parent(navigation),this);
+ nav_id = navigation->navpoly_create(navpoly, get_relative_transform_to_parent(navigation), this);
}
//update_gizmo();
_change_notify("navpoly");
update_configuration_warning();
-
}
-Ref<NavigationPolygon> NavigationPolygonInstance::get_navigation_polygon() const{
+Ref<NavigationPolygon> NavigationPolygonInstance::get_navigation_polygon() const {
return navpoly;
}
@@ -456,7 +433,6 @@ void NavigationPolygonInstance::_navpoly_changed() {
update();
}
-
String NavigationPolygonInstance::get_configuration_warning() const {
if (!is_visible_in_tree() || !is_inside_tree())
@@ -465,14 +441,14 @@ String NavigationPolygonInstance::get_configuration_warning() const {
if (!navpoly.is_valid()) {
return TTR("A NavigationPolygon resource must be set or created for this node to work. Please set a property or draw a polygon.");
}
- const Node2D *c=this;
- while(c) {
+ const Node2D *c = this;
+ while (c) {
if (c->cast_to<Navigation2D>()) {
return String();
}
- c=c->get_parent()->cast_to<Node2D>();
+ c = c->get_parent()->cast_to<Node2D>();
}
return TTR("NavigationPolygonInstance must be a child or grandchild to a Navigation2D node. It only provides navigation data.");
@@ -480,23 +456,22 @@ String NavigationPolygonInstance::get_configuration_warning() const {
void NavigationPolygonInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_navigation_polygon","navpoly:NavigationPolygon"),&NavigationPolygonInstance::set_navigation_polygon);
- ClassDB::bind_method(D_METHOD("get_navigation_polygon:NavigationPolygon"),&NavigationPolygonInstance::get_navigation_polygon);
+ ClassDB::bind_method(D_METHOD("set_navigation_polygon", "navpoly:NavigationPolygon"), &NavigationPolygonInstance::set_navigation_polygon);
+ ClassDB::bind_method(D_METHOD("get_navigation_polygon:NavigationPolygon"), &NavigationPolygonInstance::get_navigation_polygon);
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&NavigationPolygonInstance::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&NavigationPolygonInstance::is_enabled);
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationPolygonInstance::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationPolygonInstance::is_enabled);
- ClassDB::bind_method(D_METHOD("_navpoly_changed"),&NavigationPolygonInstance::_navpoly_changed);
+ ClassDB::bind_method(D_METHOD("_navpoly_changed"), &NavigationPolygonInstance::_navpoly_changed);
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"navpoly",PROPERTY_HINT_RESOURCE_TYPE,"NavigationPolygon"),"set_navigation_polygon","get_navigation_polygon");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navpoly", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon"), "set_navigation_polygon", "get_navigation_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
}
NavigationPolygonInstance::NavigationPolygonInstance() {
- navigation=NULL;
- nav_id=-1;
- enabled=true;
+ navigation = NULL;
+ nav_id = -1;
+ enabled = true;
set_notify_transform(true);
-
}
diff --git a/scene/2d/navigation_polygon.h b/scene/2d/navigation_polygon.h
index 7f1762b6f5..6bc3b903c7 100644
--- a/scene/2d/navigation_polygon.h
+++ b/scene/2d/navigation_polygon.h
@@ -31,41 +31,36 @@
#include "scene/2d/node_2d.h"
+class NavigationPolygon : public Resource {
-class NavigationPolygon : public Resource {
-
- GDCLASS( NavigationPolygon, Resource );
+ GDCLASS(NavigationPolygon, Resource);
PoolVector<Vector2> vertices;
struct Polygon {
Vector<int> indices;
};
Vector<Polygon> polygons;
- Vector< PoolVector<Vector2> > outlines;
+ Vector<PoolVector<Vector2> > outlines;
protected:
-
static void _bind_methods();
- void _set_polygons(const Array& p_array);
+ void _set_polygons(const Array &p_array);
Array _get_polygons() const;
- void _set_outlines(const Array& p_array);
+ void _set_outlines(const Array &p_array);
Array _get_outlines() const;
public:
-
-
-
- void set_vertices(const PoolVector<Vector2>& p_vertices);
+ void set_vertices(const PoolVector<Vector2> &p_vertices);
PoolVector<Vector2> get_vertices() const;
- void add_polygon(const Vector<int>& p_polygon);
+ void add_polygon(const Vector<int> &p_polygon);
int get_polygon_count() const;
- void add_outline(const PoolVector<Vector2>& p_outline);
- void add_outline_at_index(const PoolVector<Vector2>& p_outline,int p_index);
- void set_outline(int p_idx,const PoolVector<Vector2>& p_outline);
+ void add_outline(const PoolVector<Vector2> &p_outline);
+ void add_outline_at_index(const PoolVector<Vector2> &p_outline, int p_index);
+ void set_outline(int p_idx, const PoolVector<Vector2> &p_outline);
PoolVector<Vector2> get_outline(int p_idx) const;
void remove_outline(int p_idx);
int get_outline_count() const;
@@ -79,12 +74,11 @@ public:
NavigationPolygon();
};
-
class Navigation2D;
class NavigationPolygonInstance : public Node2D {
- GDCLASS(NavigationPolygonInstance,Node2D);
+ GDCLASS(NavigationPolygonInstance, Node2D);
bool enabled;
int nav_id;
@@ -94,15 +88,14 @@ class NavigationPolygonInstance : public Node2D {
void _navpoly_changed();
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
- void set_navigation_polygon(const Ref<NavigationPolygon>& p_navpoly);
+ void set_navigation_polygon(const Ref<NavigationPolygon> &p_navpoly);
Ref<NavigationPolygon> get_navigation_polygon() const;
String get_configuration_warning() const;
@@ -110,5 +103,4 @@ public:
NavigationPolygonInstance();
};
-
#endif // NAVIGATIONPOLYGON_H
diff --git a/scene/2d/node_2d.cpp b/scene/2d/node_2d.cpp
index 710f9731c5..1ba6ec46cf 100644
--- a/scene/2d/node_2d.cpp
+++ b/scene/2d/node_2d.cpp
@@ -28,15 +28,12 @@
/*************************************************************************/
#include "node_2d.h"
-#include "servers/visual_server.h"
+#include "message_queue.h"
#include "scene/gui/control.h"
#include "scene/main/viewport.h"
-#include "message_queue.h"
-
-
-void Node2D::edit_set_pivot(const Point2& p_pivot) {
-
+#include "servers/visual_server.h"
+void Node2D::edit_set_pivot(const Point2 &p_pivot) {
}
Point2 Node2D::edit_get_pivot() const {
@@ -56,12 +53,11 @@ Variant Node2D::edit_get_state() const {
state.push_back(get_scale());
return state;
-
}
-void Node2D::edit_set_state(const Variant& p_state) {
+void Node2D::edit_set_state(const Variant &p_state) {
Array state = p_state;
- ERR_FAIL_COND( state.size() != 3);
+ ERR_FAIL_COND(state.size() != 3);
pos = state[0];
angle = state[1];
@@ -70,89 +66,82 @@ void Node2D::edit_set_state(const Variant& p_state) {
_change_notify("transform/rot");
_change_notify("transform/scale");
_change_notify("transform/pos");
-
}
-void Node2D::edit_set_rect(const Rect2& p_edit_rect) {
+void Node2D::edit_set_rect(const Rect2 &p_edit_rect) {
Rect2 r = get_item_rect();
Vector2 zero_offset;
- if (r.size.x!=0)
+ if (r.size.x != 0)
zero_offset.x = -r.pos.x / r.size.x;
- if (r.size.y!=0)
+ if (r.size.y != 0)
zero_offset.y = -r.pos.y / r.size.y;
- Size2 new_scale(1,1);
+ Size2 new_scale(1, 1);
- if (r.size.x!=0)
+ if (r.size.x != 0)
new_scale.x = p_edit_rect.size.x / r.size.x;
- if (r.size.y!=0)
+ if (r.size.y != 0)
new_scale.y = p_edit_rect.size.y / r.size.y;
- Point2 new_pos = p_edit_rect.pos + p_edit_rect.size*zero_offset;//p_edit_rect.pos - r.pos;
+ Point2 new_pos = p_edit_rect.pos + p_edit_rect.size * zero_offset; //p_edit_rect.pos - r.pos;
Transform2D postxf;
- postxf.set_rotation_and_scale(angle,_scale);
+ postxf.set_rotation_and_scale(angle, _scale);
new_pos = postxf.xform(new_pos);
- pos+=new_pos;
- _scale*=new_scale;
+ pos += new_pos;
+ _scale *= new_scale;
_update_transform();
_change_notify("transform/scale");
_change_notify("transform/pos");
-
}
-
void Node2D::edit_rotate(float p_rot) {
- angle+=p_rot;
+ angle += p_rot;
_update_transform();
_change_notify("transform/rot");
}
-
void Node2D::_update_xform_values() {
- pos=_mat.elements[2];
- angle=_mat.get_rotation();
- _scale=_mat.get_scale();
- _xform_dirty=false;
+ pos = _mat.elements[2];
+ angle = _mat.get_rotation();
+ _scale = _mat.get_scale();
+ _xform_dirty = false;
}
void Node2D::_update_transform() {
- Transform2D mat(angle,pos);
- _mat.set_rotation_and_scale(angle,_scale);
- _mat.elements[2]=pos;
+ Transform2D mat(angle, pos);
+ _mat.set_rotation_and_scale(angle, _scale);
+ _mat.elements[2] = pos;
- VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(),_mat);
+ VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat);
if (!is_inside_tree())
return;
-
_notify_transform();
}
-void Node2D::set_position(const Point2& p_pos) {
+void Node2D::set_position(const Point2 &p_pos) {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
- pos=p_pos;
+ ((Node2D *)this)->_update_xform_values();
+ pos = p_pos;
_update_transform();
_change_notify("transform/pos");
-
-
}
void Node2D::set_rotation(float p_radians) {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
- angle=p_radians;
+ ((Node2D *)this)->_update_xform_values();
+ angle = p_radians;
_update_transform();
_change_notify("transform/rot");
}
@@ -170,29 +159,28 @@ void Node2D::_set_rotd(float p_degrees) {
set_rotation_in_degrees(p_degrees);
}
-void Node2D::set_scale(const Size2& p_scale) {
+void Node2D::set_scale(const Size2 &p_scale) {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
- _scale=p_scale;
- if (_scale.x==0)
- _scale.x=CMP_EPSILON;
- if (_scale.y==0)
- _scale.y=CMP_EPSILON;
+ ((Node2D *)this)->_update_xform_values();
+ _scale = p_scale;
+ if (_scale.x == 0)
+ _scale.x = CMP_EPSILON;
+ if (_scale.y == 0)
+ _scale.y = CMP_EPSILON;
_update_transform();
_change_notify("transform/scale");
-
}
Point2 Node2D::get_position() const {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
+ ((Node2D *)this)->_update_xform_values();
return pos;
}
float Node2D::get_rotation() const {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
+ ((Node2D *)this)->_update_xform_values();
return angle;
}
@@ -209,16 +197,14 @@ float Node2D::_get_rotd() const {
}
Size2 Node2D::get_scale() const {
if (_xform_dirty)
- ((Node2D*)this)->_update_xform_values();
+ ((Node2D *)this)->_update_xform_values();
return _scale;
}
-
void Node2D::_notification(int p_what) {
- switch(p_what) {
-
+ switch (p_what) {
}
}
@@ -231,59 +217,57 @@ Rect2 Node2D::get_item_rect() const {
if (get_script_instance()) {
Variant::CallError err;
- Rect2 r = get_script_instance()->call("_get_item_rect",NULL,0,err);
- if (err.error==Variant::CallError::CALL_OK)
+ Rect2 r = get_script_instance()->call("_get_item_rect", NULL, 0, err);
+ if (err.error == Variant::CallError::CALL_OK)
return r;
}
- return Rect2(Point2(-32,-32),Size2(64,64));
+ return Rect2(Point2(-32, -32), Size2(64, 64));
}
void Node2D::rotate(float p_radians) {
- set_rotation( get_rotation() + p_radians);
+ set_rotation(get_rotation() + p_radians);
}
-void Node2D::translate(const Vector2& p_amount) {
+void Node2D::translate(const Vector2 &p_amount) {
- set_position( get_position() + p_amount );
+ set_position(get_position() + p_amount);
}
-void Node2D::global_translate(const Vector2& p_amount) {
+void Node2D::global_translate(const Vector2 &p_amount) {
- set_global_position( get_global_position() + p_amount );
+ set_global_position(get_global_position() + p_amount);
}
-void Node2D::scale(const Size2& p_amount) {
+void Node2D::scale(const Size2 &p_amount) {
- set_scale( get_scale() * p_amount );
+ set_scale(get_scale() * p_amount);
}
-
-void Node2D::move_x(float p_delta,bool p_scaled){
+void Node2D::move_x(float p_delta, bool p_scaled) {
Transform2D t = get_transform();
Vector2 m = t[0];
if (!p_scaled)
m.normalize();
- set_position(t[2]+m*p_delta);
+ set_position(t[2] + m * p_delta);
}
-void Node2D::move_y(float p_delta,bool p_scaled){
+void Node2D::move_y(float p_delta, bool p_scaled) {
Transform2D t = get_transform();
Vector2 m = t[1];
if (!p_scaled)
m.normalize();
- set_position(t[2]+m*p_delta);
+ set_position(t[2] + m * p_delta);
}
-
Point2 Node2D::get_global_position() const {
return get_global_transform().get_origin();
}
-void Node2D::set_global_position(const Point2& p_pos) {
+void Node2D::set_global_position(const Point2 &p_pos) {
Transform2D inv;
CanvasItem *pi = get_parent_item();
@@ -295,7 +279,6 @@ void Node2D::set_global_position(const Point2& p_pos) {
}
}
-
float Node2D::get_global_rotation() const {
return get_global_transform().get_rotation();
@@ -312,7 +295,6 @@ void Node2D::set_global_rotation(float p_radians) {
}
}
-
float Node2D::get_global_rotation_in_degrees() const {
return Math::rad2deg(get_global_rotation());
@@ -323,13 +305,12 @@ void Node2D::set_global_rotation_in_degrees(float p_degrees) {
set_global_rotation(Math::deg2rad(p_degrees));
}
-
Size2 Node2D::get_global_scale() const {
return get_global_transform().get_scale();
}
-void Node2D::set_global_scale(const Size2& p_scale) {
+void Node2D::set_global_scale(const Size2 &p_scale) {
CanvasItem *pi = get_parent_item();
if (pi) {
@@ -338,16 +319,14 @@ void Node2D::set_global_scale(const Size2& p_scale) {
} else {
set_scale(p_scale);
}
-
}
+void Node2D::set_transform(const Transform2D &p_transform) {
-void Node2D::set_transform(const Transform2D& p_transform) {
+ _mat = p_transform;
+ _xform_dirty = true;
- _mat=p_transform;
- _xform_dirty=true;
-
- VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(),_mat);
+ VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), _mat);
if (!is_inside_tree())
return;
@@ -355,32 +334,29 @@ void Node2D::set_transform(const Transform2D& p_transform) {
_notify_transform();
}
-void Node2D::set_global_transform(const Transform2D& p_transform) {
+void Node2D::set_global_transform(const Transform2D &p_transform) {
CanvasItem *pi = get_parent_item();
if (pi)
- set_transform( pi->get_global_transform().affine_inverse() * p_transform);
+ set_transform(pi->get_global_transform().affine_inverse() * p_transform);
else
set_transform(p_transform);
-
-
}
void Node2D::set_z(int p_z) {
- ERR_FAIL_COND(p_z<VS::CANVAS_ITEM_Z_MIN);
- ERR_FAIL_COND(p_z>VS::CANVAS_ITEM_Z_MAX);
- z=p_z;
- VS::get_singleton()->canvas_item_set_z(get_canvas_item(),z);
-
+ ERR_FAIL_COND(p_z < VS::CANVAS_ITEM_Z_MIN);
+ ERR_FAIL_COND(p_z > VS::CANVAS_ITEM_Z_MAX);
+ z = p_z;
+ VS::get_singleton()->canvas_item_set_z(get_canvas_item(), z);
}
void Node2D::set_z_as_relative(bool p_enabled) {
- if (z_relative==p_enabled)
+ if (z_relative == p_enabled)
return;
- z_relative=p_enabled;
- VS::get_singleton()->canvas_item_set_z_as_relative_to_parent(get_canvas_item(),p_enabled);
+ z_relative = p_enabled;
+ VS::get_singleton()->canvas_item_set_z_as_relative_to_parent(get_canvas_item(), p_enabled);
}
bool Node2D::is_z_relative() const {
@@ -388,115 +364,106 @@ bool Node2D::is_z_relative() const {
return z_relative;
}
-
-int Node2D::get_z() const{
+int Node2D::get_z() const {
return z;
}
Transform2D Node2D::get_relative_transform_to_parent(const Node *p_parent) const {
- if (p_parent==this)
+ if (p_parent == this)
return Transform2D();
Node2D *parent_2d = get_parent()->cast_to<Node2D>();
- ERR_FAIL_COND_V(!parent_2d,Transform2D());
- if (p_parent==parent_2d)
+ ERR_FAIL_COND_V(!parent_2d, Transform2D());
+ if (p_parent == parent_2d)
return get_transform();
else
return parent_2d->get_relative_transform_to_parent(p_parent) * get_transform();
}
-
-void Node2D::look_at(const Vector2& p_pos) {
+void Node2D::look_at(const Vector2 &p_pos) {
rotate(get_angle_to(p_pos));
}
-float Node2D::get_angle_to(const Vector2& p_pos) const {
+float Node2D::get_angle_to(const Vector2 &p_pos) const {
return (get_global_transform().affine_inverse().xform(p_pos)).angle();
}
void Node2D::_bind_methods() {
-
// TODO: Obsolete those two methods (old name) properly (GH-4397)
- ClassDB::bind_method(D_METHOD("_get_rotd"),&Node2D::_get_rotd);
- ClassDB::bind_method(D_METHOD("_set_rotd","degrees"),&Node2D::_set_rotd);
-
- ClassDB::bind_method(D_METHOD("set_position","pos"),&Node2D::set_position);
- ClassDB::bind_method(D_METHOD("set_rotation","radians"),&Node2D::set_rotation);
- ClassDB::bind_method(D_METHOD("set_rotation_in_degrees","degrees"),&Node2D::set_rotation_in_degrees);
- ClassDB::bind_method(D_METHOD("set_scale","scale"),&Node2D::set_scale);
-
- ClassDB::bind_method(D_METHOD("get_position"),&Node2D::get_position);
- ClassDB::bind_method(D_METHOD("get_rotation"),&Node2D::get_rotation);
- ClassDB::bind_method(D_METHOD("get_rotation_in_degrees"),&Node2D::get_rotation_in_degrees);
- ClassDB::bind_method(D_METHOD("get_scale"),&Node2D::get_scale);
+ ClassDB::bind_method(D_METHOD("_get_rotd"), &Node2D::_get_rotd);
+ ClassDB::bind_method(D_METHOD("_set_rotd", "degrees"), &Node2D::_set_rotd);
- ClassDB::bind_method(D_METHOD("rotate","radians"),&Node2D::rotate);
- ClassDB::bind_method(D_METHOD("move_local_x","delta","scaled"),&Node2D::move_x,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("move_local_y","delta","scaled"),&Node2D::move_y,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("translate","offset"),&Node2D::translate);
- ClassDB::bind_method(D_METHOD("global_translate","offset"),&Node2D::global_translate);
- ClassDB::bind_method(D_METHOD("scale","ratio"),&Node2D::scale);
+ ClassDB::bind_method(D_METHOD("set_position", "pos"), &Node2D::set_position);
+ ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &Node2D::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation_in_degrees", "degrees"), &Node2D::set_rotation_in_degrees);
+ ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Node2D::set_scale);
- ClassDB::bind_method(D_METHOD("set_global_position","pos"),&Node2D::set_global_position);
- ClassDB::bind_method(D_METHOD("get_global_position"),&Node2D::get_global_position);
- ClassDB::bind_method(D_METHOD("set_global_rotation","radians"),&Node2D::set_global_rotation);
- ClassDB::bind_method(D_METHOD("get_global_rotation"),&Node2D::get_global_rotation);
- ClassDB::bind_method(D_METHOD("set_global_rotation_in_degrees","degrees"),&Node2D::set_global_rotation_in_degrees);
- ClassDB::bind_method(D_METHOD("get_global_rotation_in_degrees"),&Node2D::get_global_rotation_in_degrees);
- ClassDB::bind_method(D_METHOD("set_global_scale","scale"),&Node2D::set_global_scale);
- ClassDB::bind_method(D_METHOD("get_global_scale"),&Node2D::get_global_scale);
+ ClassDB::bind_method(D_METHOD("get_position"), &Node2D::get_position);
+ ClassDB::bind_method(D_METHOD("get_rotation"), &Node2D::get_rotation);
+ ClassDB::bind_method(D_METHOD("get_rotation_in_degrees"), &Node2D::get_rotation_in_degrees);
+ ClassDB::bind_method(D_METHOD("get_scale"), &Node2D::get_scale);
- ClassDB::bind_method(D_METHOD("set_transform","xform"),&Node2D::set_transform);
- ClassDB::bind_method(D_METHOD("set_global_transform","xform"),&Node2D::set_global_transform);
+ ClassDB::bind_method(D_METHOD("rotate", "radians"), &Node2D::rotate);
+ ClassDB::bind_method(D_METHOD("move_local_x", "delta", "scaled"), &Node2D::move_x, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("move_local_y", "delta", "scaled"), &Node2D::move_y, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("translate", "offset"), &Node2D::translate);
+ ClassDB::bind_method(D_METHOD("global_translate", "offset"), &Node2D::global_translate);
+ ClassDB::bind_method(D_METHOD("scale", "ratio"), &Node2D::scale);
- ClassDB::bind_method(D_METHOD("look_at","point"),&Node2D::look_at);
- ClassDB::bind_method(D_METHOD("get_angle_to","point"),&Node2D::get_angle_to);
+ ClassDB::bind_method(D_METHOD("set_global_position", "pos"), &Node2D::set_global_position);
+ ClassDB::bind_method(D_METHOD("get_global_position"), &Node2D::get_global_position);
+ ClassDB::bind_method(D_METHOD("set_global_rotation", "radians"), &Node2D::set_global_rotation);
+ ClassDB::bind_method(D_METHOD("get_global_rotation"), &Node2D::get_global_rotation);
+ ClassDB::bind_method(D_METHOD("set_global_rotation_in_degrees", "degrees"), &Node2D::set_global_rotation_in_degrees);
+ ClassDB::bind_method(D_METHOD("get_global_rotation_in_degrees"), &Node2D::get_global_rotation_in_degrees);
+ ClassDB::bind_method(D_METHOD("set_global_scale", "scale"), &Node2D::set_global_scale);
+ ClassDB::bind_method(D_METHOD("get_global_scale"), &Node2D::get_global_scale);
- ClassDB::bind_method(D_METHOD("set_z","z"),&Node2D::set_z);
- ClassDB::bind_method(D_METHOD("get_z"),&Node2D::get_z);
+ ClassDB::bind_method(D_METHOD("set_transform", "xform"), &Node2D::set_transform);
+ ClassDB::bind_method(D_METHOD("set_global_transform", "xform"), &Node2D::set_global_transform);
- ClassDB::bind_method(D_METHOD("set_z_as_relative","enable"),&Node2D::set_z_as_relative);
- ClassDB::bind_method(D_METHOD("is_z_relative"),&Node2D::is_z_relative);
+ ClassDB::bind_method(D_METHOD("look_at", "point"), &Node2D::look_at);
+ ClassDB::bind_method(D_METHOD("get_angle_to", "point"), &Node2D::get_angle_to);
- ClassDB::bind_method(D_METHOD("edit_set_pivot","pivot"),&Node2D::edit_set_pivot);
+ ClassDB::bind_method(D_METHOD("set_z", "z"), &Node2D::set_z);
+ ClassDB::bind_method(D_METHOD("get_z"), &Node2D::get_z);
- ClassDB::bind_method(D_METHOD("get_relative_transform_to_parent","parent"),&Node2D::get_relative_transform_to_parent);
+ ClassDB::bind_method(D_METHOD("set_z_as_relative", "enable"), &Node2D::set_z_as_relative);
+ ClassDB::bind_method(D_METHOD("is_z_relative"), &Node2D::is_z_relative);
- ADD_GROUP("Transform","");
- ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"position"),"set_position","get_position");
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"rotation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_rotation","get_rotation");
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"rotation_deg",PROPERTY_HINT_RANGE,"-1440,1440,0.1",PROPERTY_USAGE_EDITOR),"set_rotation_in_degrees","get_rotation_in_degrees");
- ADD_PROPERTYNO(PropertyInfo(Variant::VECTOR2,"scale"),"set_scale","get_scale");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D,"transform",PROPERTY_HINT_NONE,"",0),"set_transform","get_transform");
+ ClassDB::bind_method(D_METHOD("edit_set_pivot", "pivot"), &Node2D::edit_set_pivot);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_position",PROPERTY_HINT_NONE,"",0),"set_global_position","get_global_position");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_rotation",PROPERTY_HINT_NONE,"",0),"set_global_rotation","get_global_rotation");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_rotation_deg",PROPERTY_HINT_NONE,"",0),"set_global_rotation_in_degrees","get_global_rotation_in_degrees");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"global_scale",PROPERTY_HINT_NONE,"",0),"set_global_scale","get_global_scale");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D,"global_transform",PROPERTY_HINT_NONE,"",0),"set_global_transform","get_global_transform");
+ ClassDB::bind_method(D_METHOD("get_relative_transform_to_parent", "parent"), &Node2D::get_relative_transform_to_parent);
- ADD_GROUP("Z","");
- ADD_PROPERTYNZ(PropertyInfo(Variant::INT,"z",PROPERTY_HINT_RANGE,itos(VS::CANVAS_ITEM_Z_MIN)+","+itos(VS::CANVAS_ITEM_Z_MAX)+",1"),"set_z","get_z");
- ADD_PROPERTYNO(PropertyInfo(Variant::BOOL,"z_as_relative"),"set_z_as_relative","is_z_relative");
+ ADD_GROUP("Transform", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "position"), "set_position", "get_position");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "rotation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_rotation", "get_rotation");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "rotation_deg", PROPERTY_HINT_RANGE, "-1440,1440,0.1", PROPERTY_USAGE_EDITOR), "set_rotation_in_degrees", "get_rotation_in_degrees");
+ ADD_PROPERTYNO(PropertyInfo(Variant::VECTOR2, "scale"), "set_scale", "get_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "transform", PROPERTY_HINT_NONE, "", 0), "set_transform", "get_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_position", PROPERTY_HINT_NONE, "", 0), "set_global_position", "get_global_position");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_rotation", PROPERTY_HINT_NONE, "", 0), "set_global_rotation", "get_global_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_rotation_deg", PROPERTY_HINT_NONE, "", 0), "set_global_rotation_in_degrees", "get_global_rotation_in_degrees");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "global_scale", PROPERTY_HINT_NONE, "", 0), "set_global_scale", "get_global_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "global_transform", PROPERTY_HINT_NONE, "", 0), "set_global_transform", "get_global_transform");
+ ADD_GROUP("Z", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "z", PROPERTY_HINT_RANGE, itos(VS::CANVAS_ITEM_Z_MIN) + "," + itos(VS::CANVAS_ITEM_Z_MAX) + ",1"), "set_z", "get_z");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "z_as_relative"), "set_z_as_relative", "is_z_relative");
}
-
Node2D::Node2D() {
-
- angle=0;
- _scale=Vector2(1,1);
- _xform_dirty=false;
- z=0;
- z_relative=true;
-
+ angle = 0;
+ _scale = Vector2(1, 1);
+ _xform_dirty = false;
+ z = 0;
+ z_relative = true;
}
-
diff --git a/scene/2d/node_2d.h b/scene/2d/node_2d.h
index 2cceef0f06..b9c6894333 100644
--- a/scene/2d/node_2d.h
+++ b/scene/2d/node_2d.h
@@ -33,7 +33,7 @@
class Node2D : public CanvasItem {
- GDCLASS(Node2D, CanvasItem );
+ GDCLASS(Node2D, CanvasItem);
Point2 pos;
float angle;
@@ -54,32 +54,30 @@ class Node2D : public CanvasItem {
void _update_xform_values();
protected:
-
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
virtual Variant edit_get_state() const;
- virtual void edit_set_state(const Variant& p_state);
- virtual void edit_set_rect(const Rect2& p_edit_rect);
+ virtual void edit_set_state(const Variant &p_state);
+ virtual void edit_set_rect(const Rect2 &p_edit_rect);
virtual void edit_rotate(float p_rot);
- virtual void edit_set_pivot(const Point2& p_pivot);
+ virtual void edit_set_pivot(const Point2 &p_pivot);
virtual Point2 edit_get_pivot() const;
virtual bool edit_has_pivot() const;
- void set_position(const Point2& p_pos);
+ void set_position(const Point2 &p_pos);
void set_rotation(float p_radians);
void set_rotation_in_degrees(float p_degrees);
- void set_scale(const Size2& p_scale);
+ void set_scale(const Size2 &p_scale);
void rotate(float p_radians);
- void move_x(float p_delta,bool p_scaled=false);
- void move_y(float p_delta,bool p_scaled=false);
- void translate(const Vector2& p_amount);
- void global_translate(const Vector2& p_amount);
- void scale(const Size2& p_amount);
+ void move_x(float p_delta, bool p_scaled = false);
+ void move_y(float p_delta, bool p_scaled = false);
+ void translate(const Vector2 &p_amount);
+ void global_translate(const Vector2 &p_amount);
+ void scale(const Size2 &p_amount);
Point2 get_position() const;
float get_rotation() const;
@@ -92,18 +90,18 @@ public:
Size2 get_global_scale() const;
virtual Rect2 get_item_rect() const;
- void set_transform(const Transform2D& p_transform);
- void set_global_transform(const Transform2D& p_transform);
- void set_global_position(const Point2& p_pos);
+ void set_transform(const Transform2D &p_transform);
+ void set_global_transform(const Transform2D &p_transform);
+ void set_global_position(const Point2 &p_pos);
void set_global_rotation(float p_radians);
void set_global_rotation_in_degrees(float p_degrees);
- void set_global_scale(const Size2& p_scale);
+ void set_global_scale(const Size2 &p_scale);
void set_z(int p_z);
int get_z() const;
- void look_at(const Vector2& p_pos);
- float get_angle_to(const Vector2& p_pos) const;
+ void look_at(const Vector2 &p_pos);
+ float get_angle_to(const Vector2 &p_pos) const;
void set_z_as_relative(bool p_enabled);
bool is_z_relative() const;
diff --git a/scene/2d/parallax_background.cpp b/scene/2d/parallax_background.cpp
index 9336dc51af..17bc26aa7f 100644
--- a/scene/2d/parallax_background.cpp
+++ b/scene/2d/parallax_background.cpp
@@ -29,16 +29,13 @@
#include "parallax_background.h"
#include "parallax_layer.h"
-
-
void ParallaxBackground::_notification(int p_what) {
- switch(p_what) {
-
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- group_name = "__cameras_"+itos(get_viewport().get_id());
+ group_name = "__cameras_" + itos(get_viewport().get_id());
add_to_group(group_name);
} break;
@@ -47,31 +44,27 @@ void ParallaxBackground::_notification(int p_what) {
remove_from_group(group_name);
} break;
}
-
}
-void ParallaxBackground::_camera_moved(const Transform2D& p_transform) {
-
+void ParallaxBackground::_camera_moved(const Transform2D &p_transform) {
set_scroll_offset(p_transform.get_origin());
- set_scroll_scale(p_transform.get_scale().dot(Vector2(0.5,0.5)));
+ set_scroll_scale(p_transform.get_scale().dot(Vector2(0.5, 0.5)));
}
-
void ParallaxBackground::set_scroll_scale(float p_scale) {
- scale=p_scale;
+ scale = p_scale;
}
-float ParallaxBackground::get_scroll_scale() const{
+float ParallaxBackground::get_scroll_scale() const {
return scale;
}
+void ParallaxBackground::set_scroll_offset(const Point2 &p_ofs) {
-void ParallaxBackground::set_scroll_offset(const Point2& p_ofs) {
-
- offset=p_ofs;
+ offset = p_ofs;
_update_scroll();
}
@@ -81,7 +74,7 @@ void ParallaxBackground::_update_scroll() {
if (!is_inside_tree())
return;
- Vector2 ofs = base_offset+offset*base_scale;
+ Vector2 ofs = base_offset + offset * base_scale;
Size2 vps = get_viewport_size();
@@ -89,26 +82,25 @@ void ParallaxBackground::_update_scroll() {
if (limit_begin.x < limit_end.x) {
if (ofs.x < limit_begin.x)
- ofs.x=limit_begin.x;
- else if (ofs.x+vps.x > limit_end.x)
- ofs.x=limit_end.x-vps.x;
+ ofs.x = limit_begin.x;
+ else if (ofs.x + vps.x > limit_end.x)
+ ofs.x = limit_end.x - vps.x;
}
-
if (limit_begin.y < limit_end.y) {
if (ofs.y < limit_begin.y)
- ofs.y=limit_begin.y;
- else if (ofs.y+vps.y > limit_end.y)
- ofs.y=limit_end.y-vps.y;
+ ofs.y = limit_begin.y;
+ else if (ofs.y + vps.y > limit_end.y)
+ ofs.y = limit_end.y - vps.y;
}
ofs = -ofs;
- final_offset=ofs;
+ final_offset = ofs;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- ParallaxLayer *l=get_child(i)->cast_to<ParallaxLayer>();
+ ParallaxLayer *l = get_child(i)->cast_to<ParallaxLayer>();
if (!l)
continue;
@@ -124,32 +116,31 @@ Point2 ParallaxBackground::get_scroll_offset() const {
return offset;
}
-void ParallaxBackground::set_scroll_base_offset(const Point2& p_ofs) {
+void ParallaxBackground::set_scroll_base_offset(const Point2 &p_ofs) {
- base_offset=p_ofs;
+ base_offset = p_ofs;
_update_scroll();
}
-Point2 ParallaxBackground::get_scroll_base_offset() const{
+Point2 ParallaxBackground::get_scroll_base_offset() const {
return base_offset;
}
-void ParallaxBackground::set_scroll_base_scale(const Point2& p_ofs) {
+void ParallaxBackground::set_scroll_base_scale(const Point2 &p_ofs) {
- base_scale=p_ofs;
+ base_scale = p_ofs;
_update_scroll();
}
-Point2 ParallaxBackground::get_scroll_base_scale() const{
+Point2 ParallaxBackground::get_scroll_base_scale() const {
return base_scale;
}
+void ParallaxBackground::set_limit_begin(const Point2 &p_ofs) {
-void ParallaxBackground::set_limit_begin(const Point2& p_ofs) {
-
- limit_begin=p_ofs;
+ limit_begin = p_ofs;
_update_scroll();
}
@@ -158,11 +149,10 @@ Point2 ParallaxBackground::get_limit_begin() const {
return limit_begin;
}
-void ParallaxBackground::set_limit_end(const Point2& p_ofs) {
+void ParallaxBackground::set_limit_end(const Point2 &p_ofs) {
- limit_end=p_ofs;
+ limit_end = p_ofs;
_update_scroll();
-
}
Point2 ParallaxBackground::get_limit_end() const {
@@ -170,16 +160,14 @@ Point2 ParallaxBackground::get_limit_end() const {
return limit_end;
}
-void ParallaxBackground::set_ignore_camera_zoom(bool ignore){
-
- ignore_camera_zoom = ignore;
+void ParallaxBackground::set_ignore_camera_zoom(bool ignore) {
+ ignore_camera_zoom = ignore;
}
-bool ParallaxBackground::is_ignore_camera_zoom(){
-
- return ignore_camera_zoom;
+bool ParallaxBackground::is_ignore_camera_zoom() {
+ return ignore_camera_zoom;
}
Vector2 ParallaxBackground::get_final_offset() const {
@@ -189,38 +177,32 @@ Vector2 ParallaxBackground::get_final_offset() const {
void ParallaxBackground::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_camera_moved"),&ParallaxBackground::_camera_moved);
- ClassDB::bind_method(D_METHOD("set_scroll_offset","ofs"),&ParallaxBackground::set_scroll_offset);
- ClassDB::bind_method(D_METHOD("get_scroll_offset"),&ParallaxBackground::get_scroll_offset);
- ClassDB::bind_method(D_METHOD("set_scroll_base_offset","ofs"),&ParallaxBackground::set_scroll_base_offset);
- ClassDB::bind_method(D_METHOD("get_scroll_base_offset"),&ParallaxBackground::get_scroll_base_offset);
- ClassDB::bind_method(D_METHOD("set_scroll_base_scale","scale"),&ParallaxBackground::set_scroll_base_scale);
- ClassDB::bind_method(D_METHOD("get_scroll_base_scale"),&ParallaxBackground::get_scroll_base_scale);
- ClassDB::bind_method(D_METHOD("set_limit_begin","ofs"),&ParallaxBackground::set_limit_begin);
- ClassDB::bind_method(D_METHOD("get_limit_begin"),&ParallaxBackground::get_limit_begin);
- ClassDB::bind_method(D_METHOD("set_limit_end","ofs"),&ParallaxBackground::set_limit_end);
- ClassDB::bind_method(D_METHOD("get_limit_end"),&ParallaxBackground::get_limit_end);
- ClassDB::bind_method(D_METHOD("set_ignore_camera_zoom","ignore"), &ParallaxBackground::set_ignore_camera_zoom);
- ClassDB::bind_method(D_METHOD("is_ignore_camera_zoom"), &ParallaxBackground::is_ignore_camera_zoom);
-
-
- ADD_GROUP("Scroll","scroll_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_offset"),"set_scroll_offset","get_scroll_offset");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_base_offset"),"set_scroll_base_offset","get_scroll_base_offset");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_base_scale"),"set_scroll_base_scale","get_scroll_base_scale");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_limit_begin"),"set_limit_begin","get_limit_begin");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scroll_limit_end"),"set_limit_end","get_limit_end");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "scroll_ignore_camera_zoom"), "set_ignore_camera_zoom", "is_ignore_camera_zoom");
-
+ ClassDB::bind_method(D_METHOD("_camera_moved"), &ParallaxBackground::_camera_moved);
+ ClassDB::bind_method(D_METHOD("set_scroll_offset", "ofs"), &ParallaxBackground::set_scroll_offset);
+ ClassDB::bind_method(D_METHOD("get_scroll_offset"), &ParallaxBackground::get_scroll_offset);
+ ClassDB::bind_method(D_METHOD("set_scroll_base_offset", "ofs"), &ParallaxBackground::set_scroll_base_offset);
+ ClassDB::bind_method(D_METHOD("get_scroll_base_offset"), &ParallaxBackground::get_scroll_base_offset);
+ ClassDB::bind_method(D_METHOD("set_scroll_base_scale", "scale"), &ParallaxBackground::set_scroll_base_scale);
+ ClassDB::bind_method(D_METHOD("get_scroll_base_scale"), &ParallaxBackground::get_scroll_base_scale);
+ ClassDB::bind_method(D_METHOD("set_limit_begin", "ofs"), &ParallaxBackground::set_limit_begin);
+ ClassDB::bind_method(D_METHOD("get_limit_begin"), &ParallaxBackground::get_limit_begin);
+ ClassDB::bind_method(D_METHOD("set_limit_end", "ofs"), &ParallaxBackground::set_limit_end);
+ ClassDB::bind_method(D_METHOD("get_limit_end"), &ParallaxBackground::get_limit_end);
+ ClassDB::bind_method(D_METHOD("set_ignore_camera_zoom", "ignore"), &ParallaxBackground::set_ignore_camera_zoom);
+ ClassDB::bind_method(D_METHOD("is_ignore_camera_zoom"), &ParallaxBackground::is_ignore_camera_zoom);
+
+ ADD_GROUP("Scroll", "scroll_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_offset"), "set_scroll_offset", "get_scroll_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_base_offset"), "set_scroll_base_offset", "get_scroll_base_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_base_scale"), "set_scroll_base_scale", "get_scroll_base_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_limit_begin"), "set_limit_begin", "get_limit_begin");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scroll_limit_end"), "set_limit_end", "get_limit_end");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_ignore_camera_zoom"), "set_ignore_camera_zoom", "is_ignore_camera_zoom");
}
-
-
-
-
ParallaxBackground::ParallaxBackground() {
- base_scale=Vector2(1,1);
- scale=1.0;
+ base_scale = Vector2(1, 1);
+ scale = 1.0;
set_layer(-1); //behind all by default
}
diff --git a/scene/2d/parallax_background.h b/scene/2d/parallax_background.h
index caef4962e8..5914c21c95 100644
--- a/scene/2d/parallax_background.h
+++ b/scene/2d/parallax_background.h
@@ -29,13 +29,13 @@
#ifndef PARALLAX_BACKGROUND_H
#define PARALLAX_BACKGROUND_H
-#include "scene/main/canvas_layer.h"
-#include "scene/2d/node_2d.h"
#include "scene/2d/camera_2d.h"
+#include "scene/2d/node_2d.h"
+#include "scene/main/canvas_layer.h"
class ParallaxBackground : public CanvasLayer {
- GDCLASS( ParallaxBackground, CanvasLayer );
+ GDCLASS(ParallaxBackground, CanvasLayer);
Point2 offset;
float scale;
@@ -48,30 +48,30 @@ class ParallaxBackground : public CanvasLayer {
bool ignore_camera_zoom;
void _update_scroll();
-protected:
- void _camera_moved(const Transform2D& p_transform);
+protected:
+ void _camera_moved(const Transform2D &p_transform);
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_scroll_offset(const Point2& p_ofs);
+public:
+ void set_scroll_offset(const Point2 &p_ofs);
Point2 get_scroll_offset() const;
void set_scroll_scale(float p_ofs);
float get_scroll_scale() const;
- void set_scroll_base_offset(const Point2& p_ofs);
+ void set_scroll_base_offset(const Point2 &p_ofs);
Point2 get_scroll_base_offset() const;
- void set_scroll_base_scale(const Point2& p_ofs);
+ void set_scroll_base_scale(const Point2 &p_ofs);
Point2 get_scroll_base_scale() const;
- void set_limit_begin(const Point2& p_ofs);
+ void set_limit_begin(const Point2 &p_ofs);
Point2 get_limit_begin() const;
- void set_limit_end(const Point2& p_ofs);
+ void set_limit_end(const Point2 &p_ofs);
Point2 get_limit_end() const;
void set_ignore_camera_zoom(bool ignore);
diff --git a/scene/2d/parallax_layer.cpp b/scene/2d/parallax_layer.cpp
index 37d8fb52f1..2387234607 100644
--- a/scene/2d/parallax_layer.cpp
+++ b/scene/2d/parallax_layer.cpp
@@ -29,42 +29,38 @@
#include "parallax_layer.h"
#include "parallax_background.h"
-void ParallaxLayer::set_motion_scale(const Size2& p_scale) {
-
- motion_scale=p_scale;
+void ParallaxLayer::set_motion_scale(const Size2 &p_scale) {
+ motion_scale = p_scale;
ParallaxBackground *pb = get_parent()->cast_to<ParallaxBackground>();
if (is_inside_tree() && pb) {
Vector2 ofs = pb->get_final_offset();
float scale = pb->get_scroll_scale();
- set_base_offset_and_scale(ofs,scale);
+ set_base_offset_and_scale(ofs, scale);
}
-
}
Size2 ParallaxLayer::get_motion_scale() const {
return motion_scale;
-
}
-void ParallaxLayer::set_motion_offset(const Size2& p_offset) {
+void ParallaxLayer::set_motion_offset(const Size2 &p_offset) {
- motion_offset=p_offset;
+ motion_offset = p_offset;
ParallaxBackground *pb = get_parent()->cast_to<ParallaxBackground>();
if (is_inside_tree() && pb) {
Vector2 ofs = pb->get_final_offset();
float scale = pb->get_scroll_scale();
- set_base_offset_and_scale(ofs,scale);
+ set_base_offset_and_scale(ofs, scale);
}
}
Size2 ParallaxLayer::get_motion_offset() const {
return motion_offset;
-
}
void ParallaxLayer::_update_mirroring() {
@@ -77,68 +73,61 @@ void ParallaxLayer::_update_mirroring() {
RID c = pb->get_world_2d()->get_canvas();
RID ci = get_canvas_item();
- VisualServer::get_singleton()->canvas_set_item_mirroring(c,ci,mirroring);
+ VisualServer::get_singleton()->canvas_set_item_mirroring(c, ci, mirroring);
}
-
}
-void ParallaxLayer::set_mirroring(const Size2& p_mirroring) {
+void ParallaxLayer::set_mirroring(const Size2 &p_mirroring) {
- mirroring=p_mirroring;
- if (mirroring.x<0)
- mirroring.x=0;
- if (mirroring.y<0)
- mirroring.y=0;
+ mirroring = p_mirroring;
+ if (mirroring.x < 0)
+ mirroring.x = 0;
+ if (mirroring.y < 0)
+ mirroring.y = 0;
_update_mirroring();
-
}
-Size2 ParallaxLayer::get_mirroring() const{
+Size2 ParallaxLayer::get_mirroring() const {
return mirroring;
}
-
-
void ParallaxLayer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- orig_offset=get_position();
- orig_scale=get_scale();
+ orig_offset = get_position();
+ orig_scale = get_scale();
_update_mirroring();
} break;
}
}
-void ParallaxLayer::set_base_offset_and_scale(const Point2& p_offset,float p_scale) {
+void ParallaxLayer::set_base_offset_and_scale(const Point2 &p_offset, float p_scale) {
if (!is_inside_tree())
return;
if (get_tree()->is_editor_hint())
return;
- Point2 new_ofs = ((orig_offset+p_offset)*motion_scale)*p_scale+motion_offset;
+ Point2 new_ofs = ((orig_offset + p_offset) * motion_scale) * p_scale + motion_offset;
if (mirroring.x) {
- double den = mirroring.x*p_scale;
- new_ofs.x -= den*ceil(new_ofs.x/den);
+ double den = mirroring.x * p_scale;
+ new_ofs.x -= den * ceil(new_ofs.x / den);
}
if (mirroring.y) {
- double den = mirroring.y*p_scale;
- new_ofs.y -= den*ceil(new_ofs.y/den);
+ double den = mirroring.y * p_scale;
+ new_ofs.y -= den * ceil(new_ofs.y / den);
}
set_position(new_ofs);
- set_scale(Vector2(1,1)*p_scale);
-
-
+ set_scale(Vector2(1, 1) * p_scale);
}
-
String ParallaxLayer::get_configuration_warning() const {
if (!get_parent() || !get_parent()->cast_to<ParallaxBackground>()) {
@@ -150,23 +139,19 @@ String ParallaxLayer::get_configuration_warning() const {
void ParallaxLayer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_motion_scale","scale"),&ParallaxLayer::set_motion_scale);
- ClassDB::bind_method(D_METHOD("get_motion_scale"),&ParallaxLayer::get_motion_scale);
- ClassDB::bind_method(D_METHOD("set_motion_offset","offset"),&ParallaxLayer::set_motion_offset);
- ClassDB::bind_method(D_METHOD("get_motion_offset"),&ParallaxLayer::get_motion_offset);
- ClassDB::bind_method(D_METHOD("set_mirroring","mirror"),&ParallaxLayer::set_mirroring);
- ClassDB::bind_method(D_METHOD("get_mirroring"),&ParallaxLayer::get_mirroring);
-
- ADD_GROUP("Motion","motion_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_scale"),"set_motion_scale","get_motion_scale");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_offset"),"set_motion_offset","get_motion_offset");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"motion_mirroring"),"set_mirroring","get_mirroring");
-
+ ClassDB::bind_method(D_METHOD("set_motion_scale", "scale"), &ParallaxLayer::set_motion_scale);
+ ClassDB::bind_method(D_METHOD("get_motion_scale"), &ParallaxLayer::get_motion_scale);
+ ClassDB::bind_method(D_METHOD("set_motion_offset", "offset"), &ParallaxLayer::set_motion_offset);
+ ClassDB::bind_method(D_METHOD("get_motion_offset"), &ParallaxLayer::get_motion_offset);
+ ClassDB::bind_method(D_METHOD("set_mirroring", "mirror"), &ParallaxLayer::set_mirroring);
+ ClassDB::bind_method(D_METHOD("get_mirroring"), &ParallaxLayer::get_mirroring);
+
+ ADD_GROUP("Motion", "motion_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_scale"), "set_motion_scale", "get_motion_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_offset"), "set_motion_offset", "get_motion_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "motion_mirroring"), "set_mirroring", "get_mirroring");
}
-
-
-ParallaxLayer::ParallaxLayer()
-{
- motion_scale=Size2(1,1);
+ParallaxLayer::ParallaxLayer() {
+ motion_scale = Size2(1, 1);
}
diff --git a/scene/2d/parallax_layer.h b/scene/2d/parallax_layer.h
index 1b3d67af5e..01293e85ac 100644
--- a/scene/2d/parallax_layer.h
+++ b/scene/2d/parallax_layer.h
@@ -33,7 +33,7 @@
class ParallaxLayer : public Node2D {
- GDCLASS( ParallaxLayer, Node2D );
+ GDCLASS(ParallaxLayer, Node2D);
Point2 orig_offset;
Point2 orig_scale;
@@ -43,22 +43,20 @@ class ParallaxLayer : public Node2D {
void _update_mirroring();
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_motion_offset(const Size2& p_scale);
+ void set_motion_offset(const Size2 &p_scale);
Size2 get_motion_offset() const;
- void set_motion_scale(const Size2& p_scale);
+ void set_motion_scale(const Size2 &p_scale);
Size2 get_motion_scale() const;
- void set_mirroring(const Size2& p_mirroring);
+ void set_mirroring(const Size2 &p_mirroring);
Size2 get_mirroring() const;
- void set_base_offset_and_scale(const Point2& p_offsetf,float p_scale);
+ void set_base_offset_and_scale(const Point2 &p_offsetf, float p_scale);
virtual String get_configuration_warning() const;
ParallaxLayer();
diff --git a/scene/2d/particles_2d.cpp b/scene/2d/particles_2d.cpp
index 77ace0348a..c9d5bebe56 100644
--- a/scene/2d/particles_2d.cpp
+++ b/scene/2d/particles_2d.cpp
@@ -29,11 +29,9 @@
#include "particles_2d.h"
#include "scene/scene_string_names.h"
-
-
void ParticleAttractor2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -46,16 +44,16 @@ void ParticleAttractor2D::_notification(int p_what) {
return;
Vector2 pv;
- float dr = MIN(disable_radius,radius);
- for(int i=0;i<=32;i++) {
- Vector2 v(Math::sin(i/32.0*Math_PI*2),Math::cos(i/32.0*Math_PI*2));
- if (i>0) {
- draw_line(pv*radius,v*radius,Color(0,0,0.5,0.9));
- if (dr>0) {
- draw_line(pv*dr,v*dr,Color(0.5,0,0.0,0.9));
+ float dr = MIN(disable_radius, radius);
+ for (int i = 0; i <= 32; i++) {
+ Vector2 v(Math::sin(i / 32.0 * Math_PI * 2), Math::cos(i / 32.0 * Math_PI * 2));
+ if (i > 0) {
+ draw_line(pv * radius, v * radius, Color(0, 0, 0.5, 0.9));
+ if (dr > 0) {
+ draw_line(pv * dr, v * dr, Color(0.5, 0, 0.0, 0.9));
}
}
- pv=v;
+ pv = v;
}
} break;
@@ -72,7 +70,7 @@ void ParticleAttractor2D::_owner_exited() {
ERR_FAIL_COND(!owner);
owner->attractors.erase(this);
- owner=NULL;
+ owner = NULL;
}
void ParticleAttractor2D::_update_owner() {
@@ -93,63 +91,59 @@ void ParticleAttractor2D::_update_owner() {
_set_owner(pn);
}
-void ParticleAttractor2D::_set_owner(Particles2D* p_owner) {
+void ParticleAttractor2D::_set_owner(Particles2D *p_owner) {
- if (owner==p_owner)
+ if (owner == p_owner)
return;
if (owner) {
- owner->disconnect("tree_exited",this,"_owner_exited");
+ owner->disconnect("tree_exited", this, "_owner_exited");
owner->attractors.erase(this);
- owner=NULL;
+ owner = NULL;
}
- owner=p_owner;
+ owner = p_owner;
if (owner) {
- owner->connect("tree_exited",this,"_owner_exited",varray(),CONNECT_ONESHOT);
+ owner->connect("tree_exited", this, "_owner_exited", varray(), CONNECT_ONESHOT);
owner->attractors.insert(this);
}
}
void ParticleAttractor2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&ParticleAttractor2D::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&ParticleAttractor2D::is_enabled);
-
- ClassDB::bind_method(D_METHOD("set_radius","radius"),&ParticleAttractor2D::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&ParticleAttractor2D::get_radius);
-
- ClassDB::bind_method(D_METHOD("set_disable_radius","radius"),&ParticleAttractor2D::set_disable_radius);
- ClassDB::bind_method(D_METHOD("get_disable_radius"),&ParticleAttractor2D::get_disable_radius);
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &ParticleAttractor2D::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &ParticleAttractor2D::is_enabled);
- ClassDB::bind_method(D_METHOD("set_gravity","gravity"),&ParticleAttractor2D::set_gravity);
- ClassDB::bind_method(D_METHOD("get_gravity"),&ParticleAttractor2D::get_gravity);
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &ParticleAttractor2D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &ParticleAttractor2D::get_radius);
- ClassDB::bind_method(D_METHOD("set_absorption","absorption"),&ParticleAttractor2D::set_absorption);
- ClassDB::bind_method(D_METHOD("get_absorption"),&ParticleAttractor2D::get_absorption);
+ ClassDB::bind_method(D_METHOD("set_disable_radius", "radius"), &ParticleAttractor2D::set_disable_radius);
+ ClassDB::bind_method(D_METHOD("get_disable_radius"), &ParticleAttractor2D::get_disable_radius);
- ClassDB::bind_method(D_METHOD("set_particles_path","path"),&ParticleAttractor2D::set_particles_path);
- ClassDB::bind_method(D_METHOD("get_particles_path"),&ParticleAttractor2D::get_particles_path);
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.1,16000,0.1"),"set_radius","get_radius");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"disable_radius",PROPERTY_HINT_RANGE,"0.1,16000,0.1"),"set_disable_radius","get_disable_radius");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"gravity",PROPERTY_HINT_RANGE,"-512,512,0.01"),"set_gravity","get_gravity");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"absorption",PROPERTY_HINT_RANGE,"0,512,0.01"),"set_absorption","get_absorption");
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"particles_path",PROPERTY_HINT_RESOURCE_TYPE,"Particles2D"),"set_particles_path","get_particles_path");
+ ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &ParticleAttractor2D::set_gravity);
+ ClassDB::bind_method(D_METHOD("get_gravity"), &ParticleAttractor2D::get_gravity);
+ ClassDB::bind_method(D_METHOD("set_absorption", "absorption"), &ParticleAttractor2D::set_absorption);
+ ClassDB::bind_method(D_METHOD("get_absorption"), &ParticleAttractor2D::get_absorption);
+ ClassDB::bind_method(D_METHOD("set_particles_path", "path"), &ParticleAttractor2D::set_particles_path);
+ ClassDB::bind_method(D_METHOD("get_particles_path"), &ParticleAttractor2D::get_particles_path);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.1,16000,0.1"), "set_radius", "get_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "disable_radius", PROPERTY_HINT_RANGE, "0.1,16000,0.1"), "set_disable_radius", "get_disable_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity", PROPERTY_HINT_RANGE, "-512,512,0.01"), "set_gravity", "get_gravity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "absorption", PROPERTY_HINT_RANGE, "0,512,0.01"), "set_absorption", "get_absorption");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "particles_path", PROPERTY_HINT_RESOURCE_TYPE, "Particles2D"), "set_particles_path", "get_particles_path");
}
-
void ParticleAttractor2D::set_enabled(bool p_enabled) {
- enabled=p_enabled;
+ enabled = p_enabled;
}
-bool ParticleAttractor2D::is_enabled() const{
+bool ParticleAttractor2D::is_enabled() const {
return enabled;
}
@@ -177,8 +171,7 @@ float ParticleAttractor2D::get_disable_radius() const {
void ParticleAttractor2D::set_gravity(float p_gravity) {
- gravity=p_gravity;
-
+ gravity = p_gravity;
}
float ParticleAttractor2D::get_gravity() const {
@@ -187,8 +180,7 @@ float ParticleAttractor2D::get_gravity() const {
void ParticleAttractor2D::set_absorption(float p_absorption) {
- absorption=p_absorption;
-
+ absorption = p_absorption;
}
float ParticleAttractor2D::get_absorption() const {
@@ -197,7 +189,7 @@ float ParticleAttractor2D::get_absorption() const {
void ParticleAttractor2D::set_particles_path(NodePath p_path) {
- path=p_path;
+ path = p_path;
_update_owner();
update_configuration_warning();
}
@@ -217,13 +209,13 @@ String ParticleAttractor2D::get_configuration_warning() const {
ParticleAttractor2D::ParticleAttractor2D() {
- owner=NULL;
- radius=50;
- disable_radius=0;
- gravity=100;
- absorption=0;
- path=String("..");
- enabled=true;
+ owner = NULL;
+ radius = 50;
+ disable_radius = 0;
+ gravity = 100;
+ absorption = 0;
+ path = String("..");
+ enabled = true;
}
/****************************************/
@@ -236,12 +228,12 @@ _FORCE_INLINE_ static float _rand_from_seed(uint64_t *seed) {
void Particles2D::_process_particles(float p_delta) {
- if (particles.size()==0 || lifetime==0)
+ if (particles.size() == 0 || lifetime == 0)
return;
- p_delta*=time_scale;
+ p_delta *= time_scale;
- float frame_time=p_delta;
+ float frame_time = p_delta;
if (emit_timeout > 0) {
time_to_live -= frame_time;
@@ -252,114 +244,110 @@ void Particles2D::_process_particles(float p_delta) {
};
};
- float next_time = time+frame_time;
+ float next_time = time + frame_time;
if (next_time > lifetime)
- next_time=Math::fmod(next_time,lifetime);
-
+ next_time = Math::fmod(next_time, lifetime);
- Particle *pdata=&particles[0];
- int particle_count=particles.size();
+ Particle *pdata = &particles[0];
+ int particle_count = particles.size();
Transform2D xform;
if (!local_space)
- xform=get_global_transform();
+ xform = get_global_transform();
- active_count=0;
+ active_count = 0;
PoolVector<Point2>::Read r;
- int emission_point_count=0;
+ int emission_point_count = 0;
if (emission_points.size()) {
- emission_point_count=emission_points.size();
- r=emission_points.read();
+ emission_point_count = emission_points.size();
+ r = emission_points.read();
}
- int attractor_count=0;
- AttractorCache *attractor_ptr=NULL;
+ int attractor_count = 0;
+ AttractorCache *attractor_ptr = NULL;
if (attractors.size()) {
- if (attractors.size()!=attractor_cache.size()) {
+ if (attractors.size() != attractor_cache.size()) {
attractor_cache.resize(attractors.size());
}
- int idx=0;
+ int idx = 0;
Transform2D m;
if (local_space) {
- m= get_global_transform().affine_inverse();
+ m = get_global_transform().affine_inverse();
}
- for (Set<ParticleAttractor2D*>::Element *E=attractors.front();E;E=E->next()) {
+ for (Set<ParticleAttractor2D *>::Element *E = attractors.front(); E; E = E->next()) {
- attractor_cache[idx].pos=m.xform( E->get()->get_global_position() );
- attractor_cache[idx].attractor=E->get();
+ attractor_cache[idx].pos = m.xform(E->get()->get_global_position());
+ attractor_cache[idx].attractor = E->get();
idx++;
}
- attractor_ptr=attractor_cache.ptr();
- attractor_count=attractor_cache.size();
+ attractor_ptr = attractor_cache.ptr();
+ attractor_count = attractor_cache.size();
}
- for(int i=0;i<particle_count;i++) {
+ for (int i = 0; i < particle_count; i++) {
- Particle &p=pdata[i];
+ Particle &p = pdata[i];
float restart_time = (i * lifetime / particle_count) * explosiveness;
- bool restart=false;
+ bool restart = false;
- if ( next_time < time ) {
+ if (next_time < time) {
- if (restart_time > time || restart_time < next_time )
- restart=true;
+ if (restart_time > time || restart_time < next_time)
+ restart = true;
- } else if (restart_time > time && restart_time < next_time ) {
- restart=true;
+ } else if (restart_time > time && restart_time < next_time) {
+ restart = true;
}
if (restart) {
-
if (emitting) {
- p.pos=emissor_offset;
+ p.pos = emissor_offset;
if (emission_point_count) {
-
- Vector2 ep = r[Math::rand()%emission_point_count];
+ Vector2 ep = r[Math::rand() % emission_point_count];
if (!local_space) {
- p.pos=xform.xform(p.pos+ep*extents);
+ p.pos = xform.xform(p.pos + ep * extents);
} else {
- p.pos+=ep*extents;
+ p.pos += ep * extents;
}
} else {
if (!local_space) {
- p.pos=xform.xform(p.pos+Vector2(Math::random(-extents.x,extents.x),Math::random(-extents.y,extents.y)));
+ p.pos = xform.xform(p.pos + Vector2(Math::random(-extents.x, extents.x), Math::random(-extents.y, extents.y)));
} else {
- p.pos+=Vector2(Math::random(-extents.x,extents.x),Math::random(-extents.y,extents.y));
+ p.pos += Vector2(Math::random(-extents.x, extents.x), Math::random(-extents.y, extents.y));
}
}
- p.seed=Math::rand() % 12345678;
- uint64_t rand_seed=p.seed*(i+1);
+ p.seed = Math::rand() % 12345678;
+ uint64_t rand_seed = p.seed * (i + 1);
- float angle = Math::deg2rad(param[PARAM_DIRECTION]+_rand_from_seed(&rand_seed)*param[PARAM_SPREAD]);
+ float angle = Math::deg2rad(param[PARAM_DIRECTION] + _rand_from_seed(&rand_seed) * param[PARAM_SPREAD]);
- p.velocity=Vector2( Math::sin(angle), Math::cos(angle) );
+ p.velocity = Vector2(Math::sin(angle), Math::cos(angle));
if (!local_space) {
p.velocity = xform.basis_xform(p.velocity).normalized();
}
- p.velocity*=param[PARAM_LINEAR_VELOCITY]+param[PARAM_LINEAR_VELOCITY]*_rand_from_seed(&rand_seed)*randomness[PARAM_LINEAR_VELOCITY];
- p.velocity+=initial_velocity;
- p.active=true;
- p.rot=Math::deg2rad(param[PARAM_INITIAL_ANGLE]+param[PARAM_INITIAL_ANGLE]*randomness[PARAM_INITIAL_ANGLE]*_rand_from_seed(&rand_seed));
+ p.velocity *= param[PARAM_LINEAR_VELOCITY] + param[PARAM_LINEAR_VELOCITY] * _rand_from_seed(&rand_seed) * randomness[PARAM_LINEAR_VELOCITY];
+ p.velocity += initial_velocity;
+ p.active = true;
+ p.rot = Math::deg2rad(param[PARAM_INITIAL_ANGLE] + param[PARAM_INITIAL_ANGLE] * randomness[PARAM_INITIAL_ANGLE] * _rand_from_seed(&rand_seed));
active_count++;
- p.frame=Math::fmod(param[PARAM_ANIM_INITIAL_POS]+randomness[PARAM_ANIM_INITIAL_POS]*_rand_from_seed(&rand_seed),1.0f);
-
+ p.frame = Math::fmod(param[PARAM_ANIM_INITIAL_POS] + randomness[PARAM_ANIM_INITIAL_POS] * _rand_from_seed(&rand_seed), 1.0f);
} else {
- p.active=false;
+ p.active = false;
}
} else {
@@ -367,136 +355,122 @@ void Particles2D::_process_particles(float p_delta) {
if (!p.active)
continue;
- uint64_t rand_seed=p.seed*(i+1);
+ uint64_t rand_seed = p.seed * (i + 1);
Vector2 force;
//apply gravity
- float gravity_dir = Math::deg2rad( param[PARAM_GRAVITY_DIRECTION]+180*randomness[PARAM_GRAVITY_DIRECTION]*_rand_from_seed(&rand_seed));
- force+=Vector2( Math::sin(gravity_dir), Math::cos(gravity_dir) ) * (param[PARAM_GRAVITY_STRENGTH]+param[PARAM_GRAVITY_STRENGTH]*randomness[PARAM_GRAVITY_STRENGTH]*_rand_from_seed(&rand_seed));
+ float gravity_dir = Math::deg2rad(param[PARAM_GRAVITY_DIRECTION] + 180 * randomness[PARAM_GRAVITY_DIRECTION] * _rand_from_seed(&rand_seed));
+ force += Vector2(Math::sin(gravity_dir), Math::cos(gravity_dir)) * (param[PARAM_GRAVITY_STRENGTH] + param[PARAM_GRAVITY_STRENGTH] * randomness[PARAM_GRAVITY_STRENGTH] * _rand_from_seed(&rand_seed));
//apply radial
Vector2 rvec = (p.pos - emissor_offset).normalized();
- force+=rvec*(param[PARAM_RADIAL_ACCEL]+param[PARAM_RADIAL_ACCEL]*randomness[PARAM_RADIAL_ACCEL]*_rand_from_seed(&rand_seed));
+ force += rvec * (param[PARAM_RADIAL_ACCEL] + param[PARAM_RADIAL_ACCEL] * randomness[PARAM_RADIAL_ACCEL] * _rand_from_seed(&rand_seed));
//apply orbit
- float orbitvel = (param[PARAM_ORBIT_VELOCITY]+param[PARAM_ORBIT_VELOCITY]*randomness[PARAM_ORBIT_VELOCITY]*_rand_from_seed(&rand_seed));
- if (orbitvel!=0) {
+ float orbitvel = (param[PARAM_ORBIT_VELOCITY] + param[PARAM_ORBIT_VELOCITY] * randomness[PARAM_ORBIT_VELOCITY] * _rand_from_seed(&rand_seed));
+ if (orbitvel != 0) {
Vector2 rel = p.pos - xform.elements[2];
- Transform2D rot(orbitvel*frame_time,Vector2());
+ Transform2D rot(orbitvel * frame_time, Vector2());
p.pos = rot.xform(rel) + xform.elements[2];
-
}
- Vector2 tvec=rvec.tangent();
- force+=tvec*(param[PARAM_TANGENTIAL_ACCEL]+param[PARAM_TANGENTIAL_ACCEL]*randomness[PARAM_TANGENTIAL_ACCEL]*_rand_from_seed(&rand_seed));
+ Vector2 tvec = rvec.tangent();
+ force += tvec * (param[PARAM_TANGENTIAL_ACCEL] + param[PARAM_TANGENTIAL_ACCEL] * randomness[PARAM_TANGENTIAL_ACCEL] * _rand_from_seed(&rand_seed));
- for(int j=0;j<attractor_count;j++) {
+ for (int j = 0; j < attractor_count; j++) {
Vector2 vec = (attractor_ptr[j].pos - p.pos);
float vl = vec.length();
- if (!attractor_ptr[j].attractor->enabled || vl==0 || vl > attractor_ptr[j].attractor->radius)
+ if (!attractor_ptr[j].attractor->enabled || vl == 0 || vl > attractor_ptr[j].attractor->radius)
continue;
-
-
- force+=vec*attractor_ptr[j].attractor->gravity;
+ force += vec * attractor_ptr[j].attractor->gravity;
float fvl = p.velocity.length();
if (fvl && attractor_ptr[j].attractor->absorption) {
Vector2 target = vec.normalized();
- p.velocity = p.velocity.normalized().linear_interpolate(target,MIN(frame_time*attractor_ptr[j].attractor->absorption,1))*fvl;
+ p.velocity = p.velocity.normalized().linear_interpolate(target, MIN(frame_time * attractor_ptr[j].attractor->absorption, 1)) * fvl;
}
if (attractor_ptr[j].attractor->disable_radius && vl < attractor_ptr[j].attractor->disable_radius) {
- p.active=false;
+ p.active = false;
}
}
- p.velocity+=force*frame_time;
+ p.velocity += force * frame_time;
if (param[PARAM_DAMPING]) {
- float dmp = param[PARAM_DAMPING]+param[PARAM_DAMPING]*randomness[PARAM_DAMPING]*_rand_from_seed(&rand_seed);
+ float dmp = param[PARAM_DAMPING] + param[PARAM_DAMPING] * randomness[PARAM_DAMPING] * _rand_from_seed(&rand_seed);
float v = p.velocity.length();
v -= dmp * frame_time;
- if (v<=0) {
- p.velocity=Vector2();
+ if (v <= 0) {
+ p.velocity = Vector2();
} else {
- p.velocity=p.velocity.normalized() * v;
+ p.velocity = p.velocity.normalized() * v;
}
-
}
- p.pos+=p.velocity*frame_time;
- p.rot+=Math::lerp(param[PARAM_SPIN_VELOCITY],param[PARAM_SPIN_VELOCITY]*randomness[PARAM_SPIN_VELOCITY]*_rand_from_seed(&rand_seed),randomness[PARAM_SPIN_VELOCITY])*frame_time;
- float anim_spd=param[PARAM_ANIM_SPEED_SCALE]+param[PARAM_ANIM_SPEED_SCALE]*randomness[PARAM_ANIM_SPEED_SCALE]*_rand_from_seed(&rand_seed);
- p.frame=Math::fposmod(p.frame+(frame_time/lifetime)*anim_spd,1.0f);
+ p.pos += p.velocity * frame_time;
+ p.rot += Math::lerp(param[PARAM_SPIN_VELOCITY], param[PARAM_SPIN_VELOCITY] * randomness[PARAM_SPIN_VELOCITY] * _rand_from_seed(&rand_seed), randomness[PARAM_SPIN_VELOCITY]) * frame_time;
+ float anim_spd = param[PARAM_ANIM_SPEED_SCALE] + param[PARAM_ANIM_SPEED_SCALE] * randomness[PARAM_ANIM_SPEED_SCALE] * _rand_from_seed(&rand_seed);
+ p.frame = Math::fposmod(p.frame + (frame_time / lifetime) * anim_spd, 1.0f);
active_count++;
-
}
-
-
}
-
-
- time=Math::fmod( time+frame_time, lifetime );
- if (!emitting && active_count==0) {
+ time = Math::fmod(time + frame_time, lifetime);
+ if (!emitting && active_count == 0) {
emit_signal(SceneStringNames::get_singleton()->emission_finished);
set_process(false);
set_fixed_process(false);
}
update();
-
-
}
-
void Particles2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_PROCESS: {
- _process_particles( get_process_delta_time() );
+ _process_particles(get_process_delta_time());
} break;
case NOTIFICATION_FIXED_PROCESS: {
- _process_particles( get_fixed_process_delta_time() );
+ _process_particles(get_fixed_process_delta_time());
} break;
case NOTIFICATION_ENTER_TREE: {
- float ppt=preprocess;
- while(ppt>0) {
+ float ppt = preprocess;
+ while (ppt > 0) {
_process_particles(0.1);
- ppt-=0.1;
+ ppt -= 0.1;
}
} break;
case NOTIFICATION_DRAW: {
-
- if (particles.size()==0 || lifetime==0)
+ if (particles.size() == 0 || lifetime == 0)
return;
- RID ci=get_canvas_item();
- Size2 size(1,1);
+ RID ci = get_canvas_item();
+ Size2 size(1, 1);
Point2 center;
- int total_frames=1;
+ int total_frames = 1;
if (!texture.is_null()) {
- size=texture->get_size();
- size.x/=h_frames;
- size.y/=v_frames;
- total_frames=h_frames*v_frames;
+ size = texture->get_size();
+ size.x /= h_frames;
+ size.y /= v_frames;
+ total_frames = h_frames * v_frames;
}
+ float time_pos = (time / lifetime);
- float time_pos=(time/lifetime);
-
- Particle *pdata=&particles[0];
- int particle_count=particles.size();
+ Particle *pdata = &particles[0];
+ int particle_count = particles.size();
RID texrid;
@@ -505,64 +479,61 @@ void Particles2D::_notification(int p_what) {
Transform2D invxform;
if (!local_space)
- invxform=get_global_transform().affine_inverse();
+ invxform = get_global_transform().affine_inverse();
int start_particle = (int)(time * (float)particle_count / lifetime);
- for (int id=0;id<particle_count;++id) {
+ for (int id = 0; id < particle_count; ++id) {
int i = start_particle + id;
if (i >= particle_count) {
i -= particle_count;
}
- Particle &p=pdata[i];
+ Particle &p = pdata[i];
if (!p.active)
continue;
- float ptime = ((float)i / particle_count)*explosiveness;
+ float ptime = ((float)i / particle_count) * explosiveness;
- if (ptime<time_pos)
- ptime=time_pos-ptime;
+ if (ptime < time_pos)
+ ptime = time_pos - ptime;
else
- ptime=(1.0-ptime)+time_pos;
+ ptime = (1.0 - ptime) + time_pos;
- uint64_t rand_seed=p.seed*(i+1);
+ uint64_t rand_seed = p.seed * (i + 1);
Color color;
- if(color_ramp.is_valid())
- {
+ if (color_ramp.is_valid()) {
color = color_ramp->get_color_at_offset(ptime);
- } else
- {
+ } else {
color = default_color;
}
-
{
- float huerand=_rand_from_seed(&rand_seed);
+ float huerand = _rand_from_seed(&rand_seed);
float huerot = param[PARAM_HUE_VARIATION] + randomness[PARAM_HUE_VARIATION] * huerand;
if (Math::abs(huerot) > CMP_EPSILON) {
- float h=color.get_h();
- float s=color.get_s();
- float v=color.get_v();
- float a=color.a;
+ float h = color.get_h();
+ float s = color.get_s();
+ float v = color.get_v();
+ float a = color.a;
//float preh=h;
- h+=huerot;
- h=Math::abs(Math::fposmod(h,1.0f));
+ h += huerot;
+ h = Math::abs(Math::fposmod(h, 1.0f));
//print_line("rand: "+rtos(randomness[PARAM_HUE_VARIATION])+" rand: "+rtos(huerand));
//print_line(itos(i)+":hue: "+rtos(preh)+" + "+rtos(huerot)+" = "+rtos(h));
- color.set_hsv(h,s,v);
- color.a=a;
+ color.set_hsv(h, s, v);
+ color.a = a;
}
}
- float initial_size = param[PARAM_INITIAL_SIZE]+param[PARAM_INITIAL_SIZE]*_rand_from_seed(&rand_seed)*randomness[PARAM_INITIAL_SIZE];
- float final_size = param[PARAM_FINAL_SIZE]+param[PARAM_FINAL_SIZE]*_rand_from_seed(&rand_seed)*randomness[PARAM_FINAL_SIZE];
+ float initial_size = param[PARAM_INITIAL_SIZE] + param[PARAM_INITIAL_SIZE] * _rand_from_seed(&rand_seed) * randomness[PARAM_INITIAL_SIZE];
+ float final_size = param[PARAM_FINAL_SIZE] + param[PARAM_FINAL_SIZE] * _rand_from_seed(&rand_seed) * randomness[PARAM_FINAL_SIZE];
- float size_mult=initial_size*(1.0-ptime) + final_size*ptime;
+ float size_mult = initial_size * (1.0 - ptime) + final_size * ptime;
//Size2 rectsize=size * size_mult;
//rectsize=rectsize.floor();
@@ -574,57 +545,49 @@ void Particles2D::_notification(int p_what) {
if (p.rot) {
xform.set_rotation(p.rot);
- xform.translate(-size*size_mult/2.0);
- xform.elements[2]+=p.pos;
+ xform.translate(-size * size_mult / 2.0);
+ xform.elements[2] += p.pos;
} else {
- xform.elements[2]=-size*size_mult/2.0;
- xform.elements[2]+=p.pos;
+ xform.elements[2] = -size * size_mult / 2.0;
+ xform.elements[2] += p.pos;
}
if (!local_space) {
xform = invxform * xform;
}
+ xform.scale_basis(Size2(size_mult, size_mult));
- xform.scale_basis(Size2(size_mult,size_mult));
-
-
- VisualServer::get_singleton()->canvas_item_add_set_transform(ci,xform);
-
+ VisualServer::get_singleton()->canvas_item_add_set_transform(ci, xform);
if (texrid.is_valid()) {
Rect2 src_rect;
- src_rect.size=size;
+ src_rect.size = size;
- if (total_frames>1) {
- int frame = Math::fast_ftoi(Math::floor(p.frame*total_frames)) % total_frames;
- src_rect.pos.x = size.x * (frame%h_frames);
- src_rect.pos.y = size.y * (frame/h_frames);
+ if (total_frames > 1) {
+ int frame = Math::fast_ftoi(Math::floor(p.frame * total_frames)) % total_frames;
+ src_rect.pos.x = size.x * (frame % h_frames);
+ src_rect.pos.y = size.y * (frame / h_frames);
}
if (flip_h)
- src_rect.size.x=-src_rect.size.x;
+ src_rect.size.x = -src_rect.size.x;
if (flip_v)
- src_rect.size.y=-src_rect.size.y;
+ src_rect.size.y = -src_rect.size.y;
- texture->draw_rect_region(ci,Rect2(Point2(),size),src_rect,color);
+ texture->draw_rect_region(ci, Rect2(Point2(), size), src_rect, color);
//VisualServer::get_singleton()->canvas_item_add_texture_rect(ci,r,texrid,false,color);
} else {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2(),size),color);
-
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(), size), color);
}
-
}
-
} break;
-
}
-
}
-static const char* _particlesframe_property_names[Particles2D::PARAM_MAX]={
+static const char *_particlesframe_property_names[Particles2D::PARAM_MAX] = {
"params/direction",
"params/spread",
"params/linear_velocity",
@@ -643,7 +606,7 @@ static const char* _particlesframe_property_names[Particles2D::PARAM_MAX]={
"params/anim_initial_pos",
};
-static const char* _particlesframe_property_rnames[Particles2D::PARAM_MAX]={
+static const char *_particlesframe_property_rnames[Particles2D::PARAM_MAX] = {
"randomness/direction",
"randomness/spread",
"randomness/linear_velocity",
@@ -662,7 +625,7 @@ static const char* _particlesframe_property_rnames[Particles2D::PARAM_MAX]={
"randomness/anim_initial_pos",
};
-static const char* _particlesframe_property_ranges[Particles2D::PARAM_MAX]={
+static const char *_particlesframe_property_ranges[Particles2D::PARAM_MAX] = {
"0,360,0.01",
"0,180,0.01",
"-1024,1024,0.01",
@@ -681,21 +644,20 @@ static const char* _particlesframe_property_ranges[Particles2D::PARAM_MAX]={
"0,1,0.01",
};
-
void Particles2D::set_emitting(bool p_emitting) {
- if (emitting==p_emitting)
+ if (emitting == p_emitting)
return;
if (p_emitting) {
- if (active_count==0)
- time=0;
- set_process(process_mode==PROCESS_IDLE);
- set_fixed_process(process_mode==PROCESS_FIXED);
+ if (active_count == 0)
+ time = 0;
+ set_process(process_mode == PROCESS_IDLE);
+ set_fixed_process(process_mode == PROCESS_FIXED);
time_to_live = emit_timeout;
};
- emitting=p_emitting;
+ emitting = p_emitting;
_change_notify("config/emitting");
}
@@ -706,10 +668,10 @@ bool Particles2D::is_emitting() const {
void Particles2D::set_process_mode(ProcessMode p_mode) {
- process_mode=p_mode;
- const bool should_process=emitting || active_count!=0;
- set_process(should_process && process_mode==PROCESS_IDLE);
- set_fixed_process(should_process && process_mode==PROCESS_FIXED);
+ process_mode = p_mode;
+ const bool should_process = emitting || active_count != 0;
+ set_process(should_process && process_mode == PROCESS_IDLE);
+ set_fixed_process(should_process && process_mode == PROCESS_FIXED);
}
Particles2D::ProcessMode Particles2D::get_process_mode() const {
@@ -719,7 +681,7 @@ Particles2D::ProcessMode Particles2D::get_process_mode() const {
void Particles2D::set_amount(int p_amount) {
- ERR_FAIL_INDEX(p_amount,1024+1);
+ ERR_FAIL_INDEX(p_amount, 1024 + 1);
particles.resize(p_amount);
}
@@ -741,9 +703,9 @@ float Particles2D::get_emit_timeout() const {
void Particles2D::set_lifetime(float p_lifetime) {
- ERR_FAIL_INDEX(p_lifetime,3600+1);
+ ERR_FAIL_INDEX(p_lifetime, 3600 + 1);
- lifetime=p_lifetime;
+ lifetime = p_lifetime;
}
float Particles2D::get_lifetime() const {
@@ -752,7 +714,7 @@ float Particles2D::get_lifetime() const {
void Particles2D::set_time_scale(float p_time_scale) {
- time_scale=p_time_scale;
+ time_scale = p_time_scale;
}
float Particles2D::get_time_scale() const {
@@ -761,42 +723,39 @@ float Particles2D::get_time_scale() const {
void Particles2D::set_pre_process_time(float p_pre_process_time) {
- preprocess=p_pre_process_time;
+ preprocess = p_pre_process_time;
}
-float Particles2D::get_pre_process_time() const{
+float Particles2D::get_pre_process_time() const {
return preprocess;
}
-
void Particles2D::set_param(Parameter p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- param[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ param[p_param] = p_value;
}
float Particles2D::get_param(Parameter p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return param[p_param];
}
void Particles2D::set_randomness(Parameter p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- randomness[p_param]=p_value;
-
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ randomness[p_param] = p_value;
}
-float Particles2D::get_randomness(Parameter p_param) const {
+float Particles2D::get_randomness(Parameter p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return randomness[p_param];
-
}
-void Particles2D::set_texture(const Ref<Texture>& p_texture) {
+void Particles2D::set_texture(const Ref<Texture> &p_texture) {
- texture=p_texture;
+ texture = p_texture;
}
Ref<Texture> Particles2D::get_texture() const {
@@ -804,7 +763,7 @@ Ref<Texture> Particles2D::get_texture() const {
return texture;
}
-void Particles2D::set_color(const Color& p_color) {
+void Particles2D::set_color(const Color &p_color) {
default_color = p_color;
}
@@ -814,10 +773,9 @@ Color Particles2D::get_color() const {
return default_color;
}
+void Particles2D::set_color_ramp(const Ref<ColorRamp> &p_color_ramp) {
-void Particles2D::set_color_ramp(const Ref<ColorRamp>& p_color_ramp) {
-
- color_ramp=p_color_ramp;
+ color_ramp = p_color_ramp;
}
Ref<ColorRamp> Particles2D::get_color_ramp() const {
@@ -825,9 +783,9 @@ Ref<ColorRamp> Particles2D::get_color_ramp() const {
return color_ramp;
}
-void Particles2D::set_emissor_offset(const Point2& p_offset) {
+void Particles2D::set_emissor_offset(const Point2 &p_offset) {
- emissor_offset=p_offset;
+ emissor_offset = p_offset;
}
Point2 Particles2D::get_emissor_offset() const {
@@ -835,10 +793,9 @@ Point2 Particles2D::get_emissor_offset() const {
return emissor_offset;
}
-
void Particles2D::set_use_local_space(bool p_use) {
- local_space=p_use;
+ local_space = p_use;
}
bool Particles2D::is_using_local_space() const {
@@ -851,12 +808,10 @@ void Particles2D::set_color_phases(int p_phases) {
//Create color ramp if we have 2 or more phases.
//Otherwise first phase phase will be assigned to default color.
- if(p_phases > 1 && color_ramp.is_null())
- {
- color_ramp = Ref<ColorRamp>(memnew (ColorRamp()));
+ if (p_phases > 1 && color_ramp.is_null()) {
+ color_ramp = Ref<ColorRamp>(memnew(ColorRamp()));
}
- if(color_ramp.is_valid())
- {
+ if (color_ramp.is_valid()) {
color_ramp->get_points().resize(p_phases);
}
}
@@ -864,24 +819,21 @@ void Particles2D::set_color_phases(int p_phases) {
//Deprecated.
int Particles2D::get_color_phases() const {
- if(color_ramp.is_valid())
- {
+ if (color_ramp.is_valid()) {
return color_ramp->get_points_count();
}
return 0;
}
//Deprecated. Converts color phases to color ramp
-void Particles2D::set_color_phase_color(int p_phase,const Color& p_color) {
+void Particles2D::set_color_phase_color(int p_phase, const Color &p_color) {
- ERR_FAIL_INDEX(p_phase,MAX_COLOR_PHASES);
- if(color_ramp.is_valid())
- {
- if(color_ramp->get_points_count() > p_phase)
+ ERR_FAIL_INDEX(p_phase, MAX_COLOR_PHASES);
+ if (color_ramp.is_valid()) {
+ if (color_ramp->get_points_count() > p_phase)
color_ramp->set_color(p_phase, p_color);
- } else
- {
- if(p_phase == 0)
+ } else {
+ if (p_phase == 0)
default_color = p_color;
}
}
@@ -889,20 +841,18 @@ void Particles2D::set_color_phase_color(int p_phase,const Color& p_color) {
//Deprecated.
Color Particles2D::get_color_phase_color(int p_phase) const {
- ERR_FAIL_INDEX_V(p_phase,MAX_COLOR_PHASES,Color());
- if(color_ramp.is_valid())
- {
+ ERR_FAIL_INDEX_V(p_phase, MAX_COLOR_PHASES, Color());
+ if (color_ramp.is_valid()) {
return color_ramp->get_color(p_phase);
}
- return Color(0,0,0,1);
+ return Color(0, 0, 0, 1);
}
//Deprecated. Converts color phases to color ramp
-void Particles2D::set_color_phase_pos(int p_phase,float p_pos) {
- ERR_FAIL_INDEX(p_phase,MAX_COLOR_PHASES);
- ERR_FAIL_COND(p_pos<0.0 || p_pos>1.0);
- if(color_ramp.is_valid() && color_ramp->get_points_count() > p_phase)
- {
+void Particles2D::set_color_phase_pos(int p_phase, float p_pos) {
+ ERR_FAIL_INDEX(p_phase, MAX_COLOR_PHASES);
+ ERR_FAIL_COND(p_pos < 0.0 || p_pos > 1.0);
+ if (color_ramp.is_valid() && color_ramp->get_points_count() > p_phase) {
return color_ramp->set_offset(p_phase, p_pos);
}
}
@@ -910,17 +860,16 @@ void Particles2D::set_color_phase_pos(int p_phase,float p_pos) {
//Deprecated.
float Particles2D::get_color_phase_pos(int p_phase) const {
- ERR_FAIL_INDEX_V(p_phase,MAX_COLOR_PHASES,0);
- if(color_ramp.is_valid())
- {
+ ERR_FAIL_INDEX_V(p_phase, MAX_COLOR_PHASES, 0);
+ if (color_ramp.is_valid()) {
return color_ramp->get_offset(p_phase);
}
return 0;
}
-void Particles2D::set_emission_half_extents(const Vector2& p_extents) {
+void Particles2D::set_emission_half_extents(const Vector2 &p_extents) {
- extents=p_extents;
+ extents = p_extents;
}
Vector2 Particles2D::get_emission_half_extents() const {
@@ -928,278 +877,269 @@ Vector2 Particles2D::get_emission_half_extents() const {
return extents;
}
-void Particles2D::set_initial_velocity(const Vector2& p_velocity) {
-
+void Particles2D::set_initial_velocity(const Vector2 &p_velocity) {
- initial_velocity=p_velocity;
+ initial_velocity = p_velocity;
}
-Vector2 Particles2D::get_initial_velocity() const{
+Vector2 Particles2D::get_initial_velocity() const {
return initial_velocity;
}
-
void Particles2D::pre_process(float p_delta) {
_process_particles(p_delta);
}
-
void Particles2D::set_explosiveness(float p_value) {
- explosiveness=p_value;
+ explosiveness = p_value;
}
-float Particles2D::get_explosiveness() const{
+float Particles2D::get_explosiveness() const {
return explosiveness;
}
void Particles2D::set_flip_h(bool p_flip) {
- flip_h=p_flip;
+ flip_h = p_flip;
}
-bool Particles2D::is_flipped_h() const{
+bool Particles2D::is_flipped_h() const {
return flip_h;
}
-void Particles2D::set_flip_v(bool p_flip){
+void Particles2D::set_flip_v(bool p_flip) {
- flip_v=p_flip;
+ flip_v = p_flip;
}
-bool Particles2D::is_flipped_v() const{
+bool Particles2D::is_flipped_v() const {
return flip_v;
}
void Particles2D::set_h_frames(int p_frames) {
- ERR_FAIL_COND(p_frames<1);
- h_frames=p_frames;
+ ERR_FAIL_COND(p_frames < 1);
+ h_frames = p_frames;
}
-int Particles2D::get_h_frames() const{
+int Particles2D::get_h_frames() const {
return h_frames;
}
-void Particles2D::set_v_frames(int p_frames){
+void Particles2D::set_v_frames(int p_frames) {
- ERR_FAIL_COND(p_frames<1);
- v_frames=p_frames;
+ ERR_FAIL_COND(p_frames < 1);
+ v_frames = p_frames;
}
-int Particles2D::get_v_frames() const{
+int Particles2D::get_v_frames() const {
return v_frames;
}
+void Particles2D::set_emission_points(const PoolVector<Vector2> &p_points) {
-
-void Particles2D::set_emission_points(const PoolVector<Vector2>& p_points) {
-
- emission_points=p_points;
+ emission_points = p_points;
}
-PoolVector<Vector2> Particles2D::get_emission_points() const{
+PoolVector<Vector2> Particles2D::get_emission_points() const {
return emission_points;
}
void Particles2D::reset() {
- for(int i=0;i<particles.size();i++) {
- particles[i].active=false;
+ for (int i = 0; i < particles.size(); i++) {
+ particles[i].active = false;
}
- time=0;
- active_count=0;
+ time = 0;
+ active_count = 0;
}
void Particles2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_emitting","active"),&Particles2D::set_emitting);
- ClassDB::bind_method(D_METHOD("is_emitting"),&Particles2D::is_emitting);
+ ClassDB::bind_method(D_METHOD("set_emitting", "active"), &Particles2D::set_emitting);
+ ClassDB::bind_method(D_METHOD("is_emitting"), &Particles2D::is_emitting);
- ClassDB::bind_method(D_METHOD("set_process_mode","mode"),&Particles2D::set_process_mode);
- ClassDB::bind_method(D_METHOD("get_process_mode"),&Particles2D::get_process_mode);
+ ClassDB::bind_method(D_METHOD("set_process_mode", "mode"), &Particles2D::set_process_mode);
+ ClassDB::bind_method(D_METHOD("get_process_mode"), &Particles2D::get_process_mode);
- ClassDB::bind_method(D_METHOD("set_amount","amount"),&Particles2D::set_amount);
- ClassDB::bind_method(D_METHOD("get_amount"),&Particles2D::get_amount);
+ ClassDB::bind_method(D_METHOD("set_amount", "amount"), &Particles2D::set_amount);
+ ClassDB::bind_method(D_METHOD("get_amount"), &Particles2D::get_amount);
- ClassDB::bind_method(D_METHOD("set_lifetime","lifetime"),&Particles2D::set_lifetime);
- ClassDB::bind_method(D_METHOD("get_lifetime"),&Particles2D::get_lifetime);
+ ClassDB::bind_method(D_METHOD("set_lifetime", "lifetime"), &Particles2D::set_lifetime);
+ ClassDB::bind_method(D_METHOD("get_lifetime"), &Particles2D::get_lifetime);
- ClassDB::bind_method(D_METHOD("set_time_scale","time_scale"),&Particles2D::set_time_scale);
- ClassDB::bind_method(D_METHOD("get_time_scale"),&Particles2D::get_time_scale);
+ ClassDB::bind_method(D_METHOD("set_time_scale", "time_scale"), &Particles2D::set_time_scale);
+ ClassDB::bind_method(D_METHOD("get_time_scale"), &Particles2D::get_time_scale);
- ClassDB::bind_method(D_METHOD("set_pre_process_time","time"),&Particles2D::set_pre_process_time);
- ClassDB::bind_method(D_METHOD("get_pre_process_time"),&Particles2D::get_pre_process_time);
+ ClassDB::bind_method(D_METHOD("set_pre_process_time", "time"), &Particles2D::set_pre_process_time);
+ ClassDB::bind_method(D_METHOD("get_pre_process_time"), &Particles2D::get_pre_process_time);
- ClassDB::bind_method(D_METHOD("set_emit_timeout","value"),&Particles2D::set_emit_timeout);
- ClassDB::bind_method(D_METHOD("get_emit_timeout"),&Particles2D::get_emit_timeout);
+ ClassDB::bind_method(D_METHOD("set_emit_timeout", "value"), &Particles2D::set_emit_timeout);
+ ClassDB::bind_method(D_METHOD("get_emit_timeout"), &Particles2D::get_emit_timeout);
- ClassDB::bind_method(D_METHOD("set_param","param","value"),&Particles2D::set_param);
- ClassDB::bind_method(D_METHOD("get_param","param"),&Particles2D::get_param);
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &Particles2D::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &Particles2D::get_param);
- ClassDB::bind_method(D_METHOD("set_randomness","param","value"),&Particles2D::set_randomness);
- ClassDB::bind_method(D_METHOD("get_randomness","param"),&Particles2D::get_randomness);
+ ClassDB::bind_method(D_METHOD("set_randomness", "param", "value"), &Particles2D::set_randomness);
+ ClassDB::bind_method(D_METHOD("get_randomness", "param"), &Particles2D::get_randomness);
- ClassDB::bind_method(D_METHOD("set_texture:Texture","texture"),&Particles2D::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture:Texture"),&Particles2D::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture:Texture", "texture"), &Particles2D::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture"), &Particles2D::get_texture);
- ClassDB::bind_method(D_METHOD("set_color","color"),&Particles2D::set_color);
- ClassDB::bind_method(D_METHOD("get_color"),&Particles2D::get_color);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &Particles2D::set_color);
+ ClassDB::bind_method(D_METHOD("get_color"), &Particles2D::get_color);
- ClassDB::bind_method(D_METHOD("set_color_ramp:ColorRamp","color_ramp"),&Particles2D::set_color_ramp);
- ClassDB::bind_method(D_METHOD("get_color_ramp:ColorRamp"),&Particles2D::get_color_ramp);
+ ClassDB::bind_method(D_METHOD("set_color_ramp:ColorRamp", "color_ramp"), &Particles2D::set_color_ramp);
+ ClassDB::bind_method(D_METHOD("get_color_ramp:ColorRamp"), &Particles2D::get_color_ramp);
- ClassDB::bind_method(D_METHOD("set_emissor_offset","offset"),&Particles2D::set_emissor_offset);
- ClassDB::bind_method(D_METHOD("get_emissor_offset"),&Particles2D::get_emissor_offset);
+ ClassDB::bind_method(D_METHOD("set_emissor_offset", "offset"), &Particles2D::set_emissor_offset);
+ ClassDB::bind_method(D_METHOD("get_emissor_offset"), &Particles2D::get_emissor_offset);
- ClassDB::bind_method(D_METHOD("set_flip_h","enable"),&Particles2D::set_flip_h);
- ClassDB::bind_method(D_METHOD("is_flipped_h"),&Particles2D::is_flipped_h);
+ ClassDB::bind_method(D_METHOD("set_flip_h", "enable"), &Particles2D::set_flip_h);
+ ClassDB::bind_method(D_METHOD("is_flipped_h"), &Particles2D::is_flipped_h);
- ClassDB::bind_method(D_METHOD("set_flip_v","enable"),&Particles2D::set_flip_v);
- ClassDB::bind_method(D_METHOD("is_flipped_v"),&Particles2D::is_flipped_v);
+ ClassDB::bind_method(D_METHOD("set_flip_v", "enable"), &Particles2D::set_flip_v);
+ ClassDB::bind_method(D_METHOD("is_flipped_v"), &Particles2D::is_flipped_v);
- ClassDB::bind_method(D_METHOD("set_h_frames","enable"),&Particles2D::set_h_frames);
- ClassDB::bind_method(D_METHOD("get_h_frames"),&Particles2D::get_h_frames);
+ ClassDB::bind_method(D_METHOD("set_h_frames", "enable"), &Particles2D::set_h_frames);
+ ClassDB::bind_method(D_METHOD("get_h_frames"), &Particles2D::get_h_frames);
- ClassDB::bind_method(D_METHOD("set_v_frames","enable"),&Particles2D::set_v_frames);
- ClassDB::bind_method(D_METHOD("get_v_frames"),&Particles2D::get_v_frames);
+ ClassDB::bind_method(D_METHOD("set_v_frames", "enable"), &Particles2D::set_v_frames);
+ ClassDB::bind_method(D_METHOD("get_v_frames"), &Particles2D::get_v_frames);
- ClassDB::bind_method(D_METHOD("set_emission_half_extents","extents"),&Particles2D::set_emission_half_extents);
- ClassDB::bind_method(D_METHOD("get_emission_half_extents"),&Particles2D::get_emission_half_extents);
+ ClassDB::bind_method(D_METHOD("set_emission_half_extents", "extents"), &Particles2D::set_emission_half_extents);
+ ClassDB::bind_method(D_METHOD("get_emission_half_extents"), &Particles2D::get_emission_half_extents);
- ClassDB::bind_method(D_METHOD("set_color_phases","phases"),&Particles2D::set_color_phases);
- ClassDB::bind_method(D_METHOD("get_color_phases"),&Particles2D::get_color_phases);
+ ClassDB::bind_method(D_METHOD("set_color_phases", "phases"), &Particles2D::set_color_phases);
+ ClassDB::bind_method(D_METHOD("get_color_phases"), &Particles2D::get_color_phases);
- ClassDB::bind_method(D_METHOD("set_color_phase_color","phase","color"),&Particles2D::set_color_phase_color);
- ClassDB::bind_method(D_METHOD("get_color_phase_color","phase"),&Particles2D::get_color_phase_color);
+ ClassDB::bind_method(D_METHOD("set_color_phase_color", "phase", "color"), &Particles2D::set_color_phase_color);
+ ClassDB::bind_method(D_METHOD("get_color_phase_color", "phase"), &Particles2D::get_color_phase_color);
- ClassDB::bind_method(D_METHOD("set_color_phase_pos","phase","pos"),&Particles2D::set_color_phase_pos);
- ClassDB::bind_method(D_METHOD("get_color_phase_pos","phase"),&Particles2D::get_color_phase_pos);
+ ClassDB::bind_method(D_METHOD("set_color_phase_pos", "phase", "pos"), &Particles2D::set_color_phase_pos);
+ ClassDB::bind_method(D_METHOD("get_color_phase_pos", "phase"), &Particles2D::get_color_phase_pos);
- ClassDB::bind_method(D_METHOD("pre_process","time"),&Particles2D::pre_process);
- ClassDB::bind_method(D_METHOD("reset"),&Particles2D::reset);
+ ClassDB::bind_method(D_METHOD("pre_process", "time"), &Particles2D::pre_process);
+ ClassDB::bind_method(D_METHOD("reset"), &Particles2D::reset);
- ClassDB::bind_method(D_METHOD("set_use_local_space","enable"),&Particles2D::set_use_local_space);
- ClassDB::bind_method(D_METHOD("is_using_local_space"),&Particles2D::is_using_local_space);
+ ClassDB::bind_method(D_METHOD("set_use_local_space", "enable"), &Particles2D::set_use_local_space);
+ ClassDB::bind_method(D_METHOD("is_using_local_space"), &Particles2D::is_using_local_space);
- ClassDB::bind_method(D_METHOD("set_initial_velocity","velocity"),&Particles2D::set_initial_velocity);
- ClassDB::bind_method(D_METHOD("get_initial_velocity"),&Particles2D::get_initial_velocity);
+ ClassDB::bind_method(D_METHOD("set_initial_velocity", "velocity"), &Particles2D::set_initial_velocity);
+ ClassDB::bind_method(D_METHOD("get_initial_velocity"), &Particles2D::get_initial_velocity);
- ClassDB::bind_method(D_METHOD("set_explosiveness","amount"),&Particles2D::set_explosiveness);
- ClassDB::bind_method(D_METHOD("get_explosiveness"),&Particles2D::get_explosiveness);
+ ClassDB::bind_method(D_METHOD("set_explosiveness", "amount"), &Particles2D::set_explosiveness);
+ ClassDB::bind_method(D_METHOD("get_explosiveness"), &Particles2D::get_explosiveness);
- ClassDB::bind_method(D_METHOD("set_emission_points","points"),&Particles2D::set_emission_points);
- ClassDB::bind_method(D_METHOD("get_emission_points"),&Particles2D::get_emission_points);
+ ClassDB::bind_method(D_METHOD("set_emission_points", "points"), &Particles2D::set_emission_points);
+ ClassDB::bind_method(D_METHOD("get_emission_points"), &Particles2D::get_emission_points);
ADD_SIGNAL(MethodInfo("emission_finished"));
- ADD_PROPERTY(PropertyInfo(Variant::INT,"config/amount",PROPERTY_HINT_EXP_RANGE,"1,1024"),"set_amount","get_amount") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"config/lifetime",PROPERTY_HINT_EXP_RANGE,"0.1,3600,0.1"),"set_lifetime","get_lifetime") ;
- ADD_PROPERTYNO(PropertyInfo(Variant::REAL,"config/time_scale",PROPERTY_HINT_EXP_RANGE,"0.01,128,0.01"),"set_time_scale","get_time_scale") ;
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"config/preprocess",PROPERTY_HINT_EXP_RANGE,"0.1,3600,0.1"),"set_pre_process_time","get_pre_process_time") ;
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"config/emit_timeout",PROPERTY_HINT_RANGE,"0,3600,0.1"),"set_emit_timeout","get_emit_timeout") ;
- ADD_PROPERTYNO(PropertyInfo(Variant::BOOL,"config/emitting"),"set_emitting","is_emitting") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"config/process_mode",PROPERTY_HINT_ENUM, "Fixed,Idle"),"set_process_mode","get_process_mode");
- ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"config/offset"),"set_emissor_offset","get_emissor_offset");
- ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"config/half_extents"),"set_emission_half_extents","get_emission_half_extents");
- ADD_PROPERTYNO(PropertyInfo(Variant::BOOL,"config/local_space"),"set_use_local_space","is_using_local_space");
- ADD_PROPERTYNO(PropertyInfo(Variant::REAL,"config/explosiveness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_explosiveness","get_explosiveness");
- ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL,"config/flip_h"),"set_flip_h","is_flipped_h");
- ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL,"config/flip_v"),"set_flip_v","is_flipped_v");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"config/texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture");
- ADD_PROPERTYNO(PropertyInfo(Variant::INT,"config/h_frames",PROPERTY_HINT_RANGE,"1,512,1"),"set_h_frames","get_h_frames");
- ADD_PROPERTYNO(PropertyInfo(Variant::INT,"config/v_frames",PROPERTY_HINT_RANGE,"1,512,1"),"set_v_frames","get_v_frames");
-
-
- for(int i=0;i<PARAM_MAX;i++) {
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,_particlesframe_property_names[i],PROPERTY_HINT_RANGE,_particlesframe_property_ranges[i]),"set_param","get_param",i);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "config/amount", PROPERTY_HINT_EXP_RANGE, "1,1024"), "set_amount", "get_amount");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "config/lifetime", PROPERTY_HINT_EXP_RANGE, "0.1,3600,0.1"), "set_lifetime", "get_lifetime");
+ ADD_PROPERTYNO(PropertyInfo(Variant::REAL, "config/time_scale", PROPERTY_HINT_EXP_RANGE, "0.01,128,0.01"), "set_time_scale", "get_time_scale");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "config/preprocess", PROPERTY_HINT_EXP_RANGE, "0.1,3600,0.1"), "set_pre_process_time", "get_pre_process_time");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "config/emit_timeout", PROPERTY_HINT_RANGE, "0,3600,0.1"), "set_emit_timeout", "get_emit_timeout");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "config/emitting"), "set_emitting", "is_emitting");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "config/process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_process_mode", "get_process_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "config/offset"), "set_emissor_offset", "get_emissor_offset");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "config/half_extents"), "set_emission_half_extents", "get_emission_half_extents");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "config/local_space"), "set_use_local_space", "is_using_local_space");
+ ADD_PROPERTYNO(PropertyInfo(Variant::REAL, "config/explosiveness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_explosiveness", "get_explosiveness");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "config/flip_h"), "set_flip_h", "is_flipped_h");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "config/flip_v"), "set_flip_v", "is_flipped_v");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "config/texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "config/h_frames", PROPERTY_HINT_RANGE, "1,512,1"), "set_h_frames", "get_h_frames");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "config/v_frames", PROPERTY_HINT_RANGE, "1,512,1"), "set_v_frames", "get_v_frames");
+
+ for (int i = 0; i < PARAM_MAX; i++) {
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, _particlesframe_property_names[i], PROPERTY_HINT_RANGE, _particlesframe_property_ranges[i]), "set_param", "get_param", i);
}
- for(int i=0;i<PARAM_MAX;i++) {
- ADD_PROPERTYINZ(PropertyInfo(Variant::REAL,_particlesframe_property_rnames[i],PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_randomness","get_randomness",i);
+ for (int i = 0; i < PARAM_MAX; i++) {
+ ADD_PROPERTYINZ(PropertyInfo(Variant::REAL, _particlesframe_property_rnames[i], PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_randomness", "get_randomness", i);
}
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "color_phases/count",PROPERTY_HINT_RANGE,"0,4,1", 0), "set_color_phases", "get_color_phases");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "color_phases/count", PROPERTY_HINT_RANGE, "0,4,1", 0), "set_color_phases", "get_color_phases");
//Backward compatibility. They will be converted to color ramp
- for(int i=0;i<MAX_COLOR_PHASES;i++) {
- String phase="phase_"+itos(i)+"/";
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, phase+"pos", PROPERTY_HINT_RANGE,"0,1,0.01", 0),"set_color_phase_pos","get_color_phase_pos",i );
- ADD_PROPERTYI( PropertyInfo( Variant::COLOR, phase+"color", PROPERTY_HINT_NONE, "", 0),"set_color_phase_color","get_color_phase_color",i );
+ for (int i = 0; i < MAX_COLOR_PHASES; i++) {
+ String phase = "phase_" + itos(i) + "/";
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, phase + "pos", PROPERTY_HINT_RANGE, "0,1,0.01", 0), "set_color_phase_pos", "get_color_phase_pos", i);
+ ADD_PROPERTYI(PropertyInfo(Variant::COLOR, phase + "color", PROPERTY_HINT_NONE, "", 0), "set_color_phase_color", "get_color_phase_color", i);
}
- ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "color/color"),"set_color","get_color");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"color/color_ramp",PROPERTY_HINT_RESOURCE_TYPE,"ColorRamp"),"set_color_ramp","get_color_ramp");
-
- ADD_PROPERTYNZ(PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"emission_points",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_emission_points","get_emission_points");
+ ADD_PROPERTYNO(PropertyInfo(Variant::COLOR, "color/color"), "set_color", "get_color");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "color/color_ramp", PROPERTY_HINT_RESOURCE_TYPE, "ColorRamp"), "set_color_ramp", "get_color_ramp");
- BIND_CONSTANT( PARAM_DIRECTION );
- BIND_CONSTANT( PARAM_SPREAD );
- BIND_CONSTANT( PARAM_LINEAR_VELOCITY );
- BIND_CONSTANT( PARAM_SPIN_VELOCITY );
- BIND_CONSTANT( PARAM_ORBIT_VELOCITY );
- BIND_CONSTANT( PARAM_GRAVITY_DIRECTION );
- BIND_CONSTANT( PARAM_GRAVITY_STRENGTH );
- BIND_CONSTANT( PARAM_RADIAL_ACCEL );
- BIND_CONSTANT( PARAM_TANGENTIAL_ACCEL );
- BIND_CONSTANT( PARAM_DAMPING );
- BIND_CONSTANT( PARAM_INITIAL_ANGLE );
- BIND_CONSTANT( PARAM_INITIAL_SIZE );
- BIND_CONSTANT( PARAM_FINAL_SIZE );
- BIND_CONSTANT( PARAM_HUE_VARIATION );
- BIND_CONSTANT( PARAM_ANIM_SPEED_SCALE );
- BIND_CONSTANT( PARAM_ANIM_INITIAL_POS );
- BIND_CONSTANT( PARAM_MAX );
+ ADD_PROPERTYNZ(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "emission_points", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_emission_points", "get_emission_points");
- BIND_CONSTANT( MAX_COLOR_PHASES );
+ BIND_CONSTANT(PARAM_DIRECTION);
+ BIND_CONSTANT(PARAM_SPREAD);
+ BIND_CONSTANT(PARAM_LINEAR_VELOCITY);
+ BIND_CONSTANT(PARAM_SPIN_VELOCITY);
+ BIND_CONSTANT(PARAM_ORBIT_VELOCITY);
+ BIND_CONSTANT(PARAM_GRAVITY_DIRECTION);
+ BIND_CONSTANT(PARAM_GRAVITY_STRENGTH);
+ BIND_CONSTANT(PARAM_RADIAL_ACCEL);
+ BIND_CONSTANT(PARAM_TANGENTIAL_ACCEL);
+ BIND_CONSTANT(PARAM_DAMPING);
+ BIND_CONSTANT(PARAM_INITIAL_ANGLE);
+ BIND_CONSTANT(PARAM_INITIAL_SIZE);
+ BIND_CONSTANT(PARAM_FINAL_SIZE);
+ BIND_CONSTANT(PARAM_HUE_VARIATION);
+ BIND_CONSTANT(PARAM_ANIM_SPEED_SCALE);
+ BIND_CONSTANT(PARAM_ANIM_INITIAL_POS);
+ BIND_CONSTANT(PARAM_MAX);
+ BIND_CONSTANT(MAX_COLOR_PHASES);
}
Particles2D::Particles2D() {
- for(int i=0;i<PARAM_MAX;i++) {
+ for (int i = 0; i < PARAM_MAX; i++) {
- param[i]=0;
- randomness[i]=0;
+ param[i] = 0;
+ randomness[i] = 0;
}
-
- set_param(PARAM_SPREAD,10);
- set_param(PARAM_LINEAR_VELOCITY,20);
- set_param(PARAM_GRAVITY_STRENGTH,9.8);
- set_param(PARAM_RADIAL_ACCEL,0);
- set_param(PARAM_TANGENTIAL_ACCEL,0);
- set_param(PARAM_INITIAL_ANGLE,0.0);
- set_param(PARAM_INITIAL_SIZE,1.0);
- set_param(PARAM_FINAL_SIZE,1.0);
- set_param(PARAM_ANIM_SPEED_SCALE,1.0);
-
- set_color(Color(1,1,1,1));
-
- time=0;
- lifetime=2;
- emitting=false;
+ set_param(PARAM_SPREAD, 10);
+ set_param(PARAM_LINEAR_VELOCITY, 20);
+ set_param(PARAM_GRAVITY_STRENGTH, 9.8);
+ set_param(PARAM_RADIAL_ACCEL, 0);
+ set_param(PARAM_TANGENTIAL_ACCEL, 0);
+ set_param(PARAM_INITIAL_ANGLE, 0.0);
+ set_param(PARAM_INITIAL_SIZE, 1.0);
+ set_param(PARAM_FINAL_SIZE, 1.0);
+ set_param(PARAM_ANIM_SPEED_SCALE, 1.0);
+
+ set_color(Color(1, 1, 1, 1));
+
+ time = 0;
+ lifetime = 2;
+ emitting = false;
particles.resize(32);
- active_count=-1;
+ active_count = -1;
set_emitting(true);
- process_mode=PROCESS_IDLE;
- local_space=true;
- preprocess=0;
- time_scale=1.0;
-
+ process_mode = PROCESS_IDLE;
+ local_space = true;
+ preprocess = 0;
+ time_scale = 1.0;
- flip_h=false;
- flip_v=false;
+ flip_h = false;
+ flip_v = false;
- v_frames=1;
- h_frames=1;
+ v_frames = 1;
+ h_frames = 1;
emit_timeout = 0;
time_to_live = 0;
- explosiveness=1.0;
+ explosiveness = 1.0;
}
diff --git a/scene/2d/particles_2d.h b/scene/2d/particles_2d.h
index c6ababe3be..0cf4063cef 100644
--- a/scene/2d/particles_2d.h
+++ b/scene/2d/particles_2d.h
@@ -30,16 +30,15 @@
#define PARTICLES_FRAME_H
#include "scene/2d/node_2d.h"
-#include "scene/resources/texture.h"
#include "scene/resources/color_ramp.h"
+#include "scene/resources/texture.h"
class Particles2D;
class ParticleAttractor2D : public Node2D {
- GDCLASS(ParticleAttractor2D,Node2D);
+ GDCLASS(ParticleAttractor2D, Node2D);
-
-friend class Particles2D;
+ friend class Particles2D;
bool enabled;
float radius;
float disable_radius;
@@ -51,12 +50,12 @@ friend class Particles2D;
void _update_owner();
void _owner_exited();
- void _set_owner(Particles2D* p_owner);
+ void _set_owner(Particles2D *p_owner);
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
@@ -80,13 +79,11 @@ public:
ParticleAttractor2D();
};
-
-
class Particles2D : public Node2D {
GDCLASS(Particles2D, Node2D);
-public:
+public:
enum Parameter {
PARAM_DIRECTION,
PARAM_SPREAD,
@@ -108,7 +105,7 @@ public:
};
enum {
- MAX_COLOR_PHASES=4
+ MAX_COLOR_PHASES = 4
};
enum ProcessMode {
@@ -117,7 +114,6 @@ public:
};
private:
-
float param[PARAM_MAX];
float randomness[PARAM_MAX];
@@ -128,7 +124,12 @@ private:
float rot;
float frame;
uint64_t seed;
- Particle() { active=false; seed=123465789; rot=0; frame=0;}
+ Particle() {
+ active = false;
+ seed = 123465789;
+ rot = 0;
+ frame = 0;
+ }
};
Vector<Particle> particles;
@@ -170,17 +171,15 @@ private:
Ref<ColorRamp> color_ramp;
void _process_particles(float p_delta);
-friend class ParticleAttractor2D;
+ friend class ParticleAttractor2D;
- Set<ParticleAttractor2D*> attractors;
+ Set<ParticleAttractor2D *> attractors;
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
void set_emitting(bool p_emitting);
bool is_emitting() const;
@@ -202,7 +201,7 @@ public:
void set_emit_timeout(float p_timeout);
float get_emit_timeout() const;
- void set_emission_half_extents(const Vector2& p_extents);
+ void set_emission_half_extents(const Vector2 &p_extents);
Vector2 get_emission_half_extents() const;
void set_param(Parameter p_param, float p_value);
@@ -220,7 +219,6 @@ public:
void set_flip_v(bool p_flip);
bool is_flipped_v() const;
-
void set_h_frames(int p_frames);
int get_h_frames() const;
@@ -230,31 +228,31 @@ public:
void set_color_phases(int p_phases);
int get_color_phases() const;
- void set_color_phase_color(int p_phase,const Color& p_color);
+ void set_color_phase_color(int p_phase, const Color &p_color);
Color get_color_phase_color(int p_phase) const;
- void set_color_phase_pos(int p_phase,float p_pos);
+ void set_color_phase_pos(int p_phase, float p_pos);
float get_color_phase_pos(int p_phase) const;
- void set_texture(const Ref<Texture>& p_texture);
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
- void set_color(const Color& p_color);
+ void set_color(const Color &p_color);
Color get_color() const;
- void set_color_ramp(const Ref<ColorRamp>& p_texture);
+ void set_color_ramp(const Ref<ColorRamp> &p_texture);
Ref<ColorRamp> get_color_ramp() const;
- void set_emissor_offset(const Point2& p_offset);
+ void set_emissor_offset(const Point2 &p_offset);
Point2 get_emissor_offset() const;
void set_use_local_space(bool p_use);
bool is_using_local_space() const;
- void set_initial_velocity(const Vector2& p_velocity);
+ void set_initial_velocity(const Vector2 &p_velocity);
Vector2 get_initial_velocity() const;
- void set_emission_points(const PoolVector<Vector2>& p_points);
+ void set_emission_points(const PoolVector<Vector2> &p_points);
PoolVector<Vector2> get_emission_points() const;
void pre_process(float p_delta);
@@ -263,7 +261,7 @@ public:
Particles2D();
};
-VARIANT_ENUM_CAST( Particles2D::ProcessMode );
-VARIANT_ENUM_CAST( Particles2D::Parameter );
+VARIANT_ENUM_CAST(Particles2D::ProcessMode);
+VARIANT_ENUM_CAST(Particles2D::Parameter);
#endif // PARTICLES_FRAME_H
diff --git a/scene/2d/path_2d.cpp b/scene/2d/path_2d.cpp
index 63531ae599..9e8be7fa1a 100644
--- a/scene/2d/path_2d.cpp
+++ b/scene/2d/path_2d.cpp
@@ -31,23 +31,23 @@
void Path2D::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW && curve.is_valid()) {
+ if (p_what == NOTIFICATION_DRAW && curve.is_valid()) {
//draw the curve!!
if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_navigation_hint()) {
return;
}
- for(int i=0;i<curve->get_point_count();i++) {
+ for (int i = 0; i < curve->get_point_count(); i++) {
- Vector2 prev_p=curve->get_point_pos(i);
+ Vector2 prev_p = curve->get_point_pos(i);
- for(int j=1;j<=8;j++) {
+ for (int j = 1; j <= 8; j++) {
- real_t frac = j/8.0;
- Vector2 p = curve->interpolate(i,frac);
- draw_line(prev_p,p,Color(0.5,0.6,1.0,0.7),2);
- prev_p=p;
+ real_t frac = j / 8.0;
+ Vector2 p = curve->interpolate(i, frac);
+ draw_line(prev_p, p, Color(0.5, 0.6, 1.0, 0.7), 2);
+ prev_p = p;
}
}
}
@@ -55,98 +55,89 @@ void Path2D::_notification(int p_what) {
void Path2D::_curve_changed() {
-
if (is_inside_tree() && get_tree()->is_editor_hint())
update();
-
}
-
-void Path2D::set_curve(const Ref<Curve2D>& p_curve) {
+void Path2D::set_curve(const Ref<Curve2D> &p_curve) {
if (curve.is_valid()) {
- curve->disconnect("changed",this,"_curve_changed");
+ curve->disconnect("changed", this, "_curve_changed");
}
- curve=p_curve;
+ curve = p_curve;
if (curve.is_valid()) {
- curve->connect("changed",this,"_curve_changed");
+ curve->connect("changed", this, "_curve_changed");
}
_curve_changed();
-
}
-Ref<Curve2D> Path2D::get_curve() const{
+Ref<Curve2D> Path2D::get_curve() const {
return curve;
}
void Path2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_curve","curve:Curve2D"),&Path2D::set_curve);
- ClassDB::bind_method(D_METHOD("get_curve:Curve2D","curve"),&Path2D::get_curve);
- ClassDB::bind_method(D_METHOD("_curve_changed"),&Path2D::_curve_changed);
+ ClassDB::bind_method(D_METHOD("set_curve", "curve:Curve2D"), &Path2D::set_curve);
+ ClassDB::bind_method(D_METHOD("get_curve:Curve2D", "curve"), &Path2D::get_curve);
+ ClassDB::bind_method(D_METHOD("_curve_changed"), &Path2D::_curve_changed);
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve2D"), "set_curve","get_curve");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve2D"), "set_curve", "get_curve");
}
Path2D::Path2D() {
- set_curve(Ref<Curve2D>( memnew( Curve2D ))); //create one by default
+ set_curve(Ref<Curve2D>(memnew(Curve2D))); //create one by default
}
/////////////////////////////////////////////////////////////////////////////////
-
void PathFollow2D::_update_transform() {
-
if (!path)
return;
- Ref<Curve2D> c =path->get_curve();
+ Ref<Curve2D> c = path->get_curve();
if (!c.is_valid())
return;
-
float o = offset;
if (loop)
- o=Math::fposmod(o,c->get_baked_length());
+ o = Math::fposmod(o, c->get_baked_length());
- Vector2 pos = c->interpolate_baked(o,cubic);
+ Vector2 pos = c->interpolate_baked(o, cubic);
if (rotate) {
- Vector2 n = (c->interpolate_baked(o+lookahead,cubic)-pos).normalized();
+ Vector2 n = (c->interpolate_baked(o + lookahead, cubic) - pos).normalized();
Vector2 t = -n.tangent();
- pos+=n*h_offset;
- pos+=t*v_offset;
+ pos += n * h_offset;
+ pos += t * v_offset;
set_rotation(t.angle());
} else {
- pos.x+=h_offset;
- pos.y+=v_offset;
+ pos.x += h_offset;
+ pos.y += v_offset;
}
set_position(pos);
-
}
void PathFollow2D::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- Node *parent=get_parent();
+ Node *parent = get_parent();
if (parent) {
- path=parent->cast_to<Path2D>();
+ path = parent->cast_to<Path2D>();
if (path) {
_update_transform();
}
@@ -155,16 +146,14 @@ void PathFollow2D::_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_TREE: {
-
- path=NULL;
+ path = NULL;
} break;
}
-
}
void PathFollow2D::set_cubic_interpolation(bool p_enable) {
- cubic=p_enable;
+ cubic = p_enable;
}
bool PathFollow2D::get_cubic_interpolation() const {
@@ -172,24 +161,23 @@ bool PathFollow2D::get_cubic_interpolation() const {
return cubic;
}
+bool PathFollow2D::_set(const StringName &p_name, const Variant &p_value) {
-bool PathFollow2D::_set(const StringName& p_name, const Variant& p_value) {
-
- if (p_name==SceneStringNames::get_singleton()->offset) {
+ if (p_name == SceneStringNames::get_singleton()->offset) {
set_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->unit_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->unit_offset) {
set_unit_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->rotate) {
+ } else if (p_name == SceneStringNames::get_singleton()->rotate) {
set_rotate(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->v_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->v_offset) {
set_v_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->h_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->h_offset) {
set_h_offset(p_value);
- } else if (String(p_name)=="cubic_interp") {
+ } else if (String(p_name) == "cubic_interp") {
set_cubic_interpolation(p_value);
- } else if (String(p_name)=="loop") {
+ } else if (String(p_name) == "loop") {
set_loop(p_value);
- } else if (String(p_name)=="lookahead") {
+ } else if (String(p_name) == "lookahead") {
set_lookahead(p_value);
} else
return false;
@@ -197,46 +185,44 @@ bool PathFollow2D::_set(const StringName& p_name, const Variant& p_value) {
return true;
}
-bool PathFollow2D::_get(const StringName& p_name,Variant &r_ret) const{
-
- if (p_name==SceneStringNames::get_singleton()->offset) {
- r_ret=get_offset();
- } else if (p_name==SceneStringNames::get_singleton()->unit_offset) {
- r_ret=get_unit_offset();
- } else if (p_name==SceneStringNames::get_singleton()->rotate) {
- r_ret=is_rotating();
- } else if (p_name==SceneStringNames::get_singleton()->v_offset) {
- r_ret=get_v_offset();
- } else if (p_name==SceneStringNames::get_singleton()->h_offset) {
- r_ret=get_h_offset();
- } else if (String(p_name)=="cubic_interp") {
- r_ret=cubic;
- } else if (String(p_name)=="loop") {
- r_ret=loop;
- } else if (String(p_name)=="lookahead") {
- r_ret=lookahead;
+bool PathFollow2D::_get(const StringName &p_name, Variant &r_ret) const {
+
+ if (p_name == SceneStringNames::get_singleton()->offset) {
+ r_ret = get_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->unit_offset) {
+ r_ret = get_unit_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->rotate) {
+ r_ret = is_rotating();
+ } else if (p_name == SceneStringNames::get_singleton()->v_offset) {
+ r_ret = get_v_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->h_offset) {
+ r_ret = get_h_offset();
+ } else if (String(p_name) == "cubic_interp") {
+ r_ret = cubic;
+ } else if (String(p_name) == "loop") {
+ r_ret = loop;
+ } else if (String(p_name) == "lookahead") {
+ r_ret = lookahead;
} else
return false;
return true;
-
}
-void PathFollow2D::_get_property_list( List<PropertyInfo> *p_list) const{
+void PathFollow2D::_get_property_list(List<PropertyInfo> *p_list) const {
- float max=10000;
+ float max = 10000;
if (path && path->get_curve().is_valid())
- max=path->get_curve()->get_baked_length();
- p_list->push_back( PropertyInfo( Variant::REAL, "offset", PROPERTY_HINT_RANGE,"0,"+rtos(max)+",0.01"));
- p_list->push_back( PropertyInfo( Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE,"0,1,0.0001",PROPERTY_USAGE_EDITOR));
- p_list->push_back( PropertyInfo( Variant::REAL, "h_offset") );
- p_list->push_back( PropertyInfo( Variant::REAL, "v_offset") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "rotate") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "cubic_interp"));
- p_list->push_back( PropertyInfo( Variant::BOOL, "loop"));
- p_list->push_back( PropertyInfo( Variant::REAL, "lookahead",PROPERTY_HINT_RANGE,"0.001,1024.0,0.001"));
+ max = path->get_curve()->get_baked_length();
+ p_list->push_back(PropertyInfo(Variant::REAL, "offset", PROPERTY_HINT_RANGE, "0," + rtos(max) + ",0.01"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::REAL, "h_offset"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "v_offset"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "rotate"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "cubic_interp"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "loop"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "lookahead", PROPERTY_HINT_RANGE, "0.001,1024.0,0.001"));
}
-
String PathFollow2D::get_configuration_warning() const {
if (!is_visible_in_tree() || !is_inside_tree())
@@ -247,51 +233,46 @@ String PathFollow2D::get_configuration_warning() const {
}
return String();
-
}
void PathFollow2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&PathFollow2D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&PathFollow2D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow2D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow2D::get_offset);
- ClassDB::bind_method(D_METHOD("set_h_offset","h_offset"),&PathFollow2D::set_h_offset);
- ClassDB::bind_method(D_METHOD("get_h_offset"),&PathFollow2D::get_h_offset);
+ ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow2D::set_h_offset);
+ ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow2D::get_h_offset);
- ClassDB::bind_method(D_METHOD("set_v_offset","v_offset"),&PathFollow2D::set_v_offset);
- ClassDB::bind_method(D_METHOD("get_v_offset"),&PathFollow2D::get_v_offset);
+ ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow2D::set_v_offset);
+ ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow2D::get_v_offset);
- ClassDB::bind_method(D_METHOD("set_unit_offset","unit_offset"),&PathFollow2D::set_unit_offset);
- ClassDB::bind_method(D_METHOD("get_unit_offset"),&PathFollow2D::get_unit_offset);
+ ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow2D::set_unit_offset);
+ ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow2D::get_unit_offset);
- ClassDB::bind_method(D_METHOD("set_rotate","enable"),&PathFollow2D::set_rotate);
- ClassDB::bind_method(D_METHOD("is_rotating"),&PathFollow2D::is_rotating);
-
- ClassDB::bind_method(D_METHOD("set_cubic_interpolation","enable"),&PathFollow2D::set_cubic_interpolation);
- ClassDB::bind_method(D_METHOD("get_cubic_interpolation"),&PathFollow2D::get_cubic_interpolation);
-
- ClassDB::bind_method(D_METHOD("set_loop","loop"),&PathFollow2D::set_loop);
- ClassDB::bind_method(D_METHOD("has_loop"),&PathFollow2D::has_loop);
+ ClassDB::bind_method(D_METHOD("set_rotate", "enable"), &PathFollow2D::set_rotate);
+ ClassDB::bind_method(D_METHOD("is_rotating"), &PathFollow2D::is_rotating);
+ ClassDB::bind_method(D_METHOD("set_cubic_interpolation", "enable"), &PathFollow2D::set_cubic_interpolation);
+ ClassDB::bind_method(D_METHOD("get_cubic_interpolation"), &PathFollow2D::get_cubic_interpolation);
+ ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow2D::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow2D::has_loop);
}
void PathFollow2D::set_offset(float p_offset) {
- offset=p_offset;
+ offset = p_offset;
if (path)
_update_transform();
_change_notify("offset");
_change_notify("unit_offset");
-
}
void PathFollow2D::set_h_offset(float p_h_offset) {
- h_offset=p_h_offset;
+ h_offset = p_h_offset;
if (path)
_update_transform();
-
}
float PathFollow2D::get_h_offset() const {
@@ -301,10 +282,9 @@ float PathFollow2D::get_h_offset() const {
void PathFollow2D::set_v_offset(float p_v_offset) {
- v_offset=p_v_offset;
+ v_offset = p_v_offset;
if (path)
_update_transform();
-
}
float PathFollow2D::get_v_offset() const {
@@ -312,8 +292,7 @@ float PathFollow2D::get_v_offset() const {
return v_offset;
}
-
-float PathFollow2D::get_offset() const{
+float PathFollow2D::get_offset() const {
return offset;
}
@@ -321,32 +300,30 @@ float PathFollow2D::get_offset() const{
void PathFollow2D::set_unit_offset(float p_unit_offset) {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length())
- set_offset(p_unit_offset*path->get_curve()->get_baked_length());
-
+ set_offset(p_unit_offset * path->get_curve()->get_baked_length());
}
-float PathFollow2D::get_unit_offset() const{
+float PathFollow2D::get_unit_offset() const {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length())
- return get_offset()/path->get_curve()->get_baked_length();
+ return get_offset() / path->get_curve()->get_baked_length();
else
return 0;
}
void PathFollow2D::set_lookahead(float p_lookahead) {
- lookahead=p_lookahead;
-
+ lookahead = p_lookahead;
}
-float PathFollow2D::get_lookahead() const{
+float PathFollow2D::get_lookahead() const {
return lookahead;
}
void PathFollow2D::set_rotate(bool p_rotate) {
- rotate=p_rotate;
+ rotate = p_rotate;
_update_transform();
}
@@ -357,23 +334,22 @@ bool PathFollow2D::is_rotating() const {
void PathFollow2D::set_loop(bool p_loop) {
- loop=p_loop;
+ loop = p_loop;
}
-bool PathFollow2D::has_loop() const{
+bool PathFollow2D::has_loop() const {
return loop;
}
-
PathFollow2D::PathFollow2D() {
- offset=0;
- h_offset=0;
- v_offset=0;
- path=NULL;
- rotate=true;
- cubic=true;
- loop=true;
- lookahead=4;
+ offset = 0;
+ h_offset = 0;
+ v_offset = 0;
+ path = NULL;
+ rotate = true;
+ cubic = true;
+ loop = true;
+ lookahead = 4;
}
diff --git a/scene/2d/path_2d.h b/scene/2d/path_2d.h
index 4fc26dbf9b..7357b6810e 100644
--- a/scene/2d/path_2d.h
+++ b/scene/2d/path_2d.h
@@ -29,39 +29,33 @@
#ifndef PATH_2D_H
#define PATH_2D_H
-#include "scene/resources/curve.h"
#include "scene/2d/node_2d.h"
+#include "scene/resources/curve.h"
class Path2D : public Node2D {
- GDCLASS( Path2D, Node2D );
+ GDCLASS(Path2D, Node2D);
Ref<Curve2D> curve;
void _curve_changed();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_curve(const Ref<Curve2D>& p_curve);
+public:
+ void set_curve(const Ref<Curve2D> &p_curve);
Ref<Curve2D> get_curve() const;
-
Path2D();
};
-
-
class PathFollow2D : public Node2D {
- GDCLASS(PathFollow2D,Node2D);
-public:
-
+ GDCLASS(PathFollow2D, Node2D);
+public:
private:
Path2D *path;
real_t offset;
@@ -74,17 +68,15 @@ private:
void _update_transform();
-
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_offset(float p_offset);
float get_offset() const;
@@ -114,5 +106,4 @@ public:
PathFollow2D();
};
-
#endif // PATH_2D_H
diff --git a/scene/2d/path_texture.cpp b/scene/2d/path_texture.cpp
index 626928a244..60efccec3d 100644
--- a/scene/2d/path_texture.cpp
+++ b/scene/2d/path_texture.cpp
@@ -28,65 +28,61 @@
/*************************************************************************/
#include "path_texture.h"
+void PathTexture::set_begin_texture(const Ref<Texture> &p_texture) {
-void PathTexture::set_begin_texture(const Ref<Texture>& p_texture) {
-
- begin=p_texture;
+ begin = p_texture;
update();
}
-Ref<Texture> PathTexture::get_begin_texture() const{
+Ref<Texture> PathTexture::get_begin_texture() const {
return begin;
}
-void PathTexture::set_repeat_texture(const Ref<Texture>& p_texture){
+void PathTexture::set_repeat_texture(const Ref<Texture> &p_texture) {
- repeat=p_texture;
+ repeat = p_texture;
update();
-
}
-Ref<Texture> PathTexture::get_repeat_texture() const{
+Ref<Texture> PathTexture::get_repeat_texture() const {
return repeat;
}
-void PathTexture::set_end_texture(const Ref<Texture>& p_texture){
+void PathTexture::set_end_texture(const Ref<Texture> &p_texture) {
- end=p_texture;
+ end = p_texture;
update();
}
-Ref<Texture> PathTexture::get_end_texture() const{
+Ref<Texture> PathTexture::get_end_texture() const {
return end;
}
-void PathTexture::set_subdivisions(int p_amount){
+void PathTexture::set_subdivisions(int p_amount) {
- ERR_FAIL_INDEX(p_amount,32);
- subdivs=p_amount;
+ ERR_FAIL_INDEX(p_amount, 32);
+ subdivs = p_amount;
update();
-
}
-int PathTexture::get_subdivisions() const{
+int PathTexture::get_subdivisions() const {
return subdivs;
}
-void PathTexture::set_overlap(int p_amount){
+void PathTexture::set_overlap(int p_amount) {
- overlap=p_amount;
+ overlap = p_amount;
update();
}
-int PathTexture::get_overlap() const{
+int PathTexture::get_overlap() const {
return overlap;
}
-
PathTexture::PathTexture() {
- overlap=0;
- subdivs=1;
+ overlap = 0;
+ subdivs = 1;
}
diff --git a/scene/2d/path_texture.h b/scene/2d/path_texture.h
index cc502a2fa4..8d5adc49c8 100644
--- a/scene/2d/path_texture.h
+++ b/scene/2d/path_texture.h
@@ -32,22 +32,22 @@
#include "scene/2d/node_2d.h"
class PathTexture : public Node2D {
- GDCLASS( PathTexture, Node2D );
+ GDCLASS(PathTexture, Node2D);
Ref<Texture> begin;
Ref<Texture> repeat;
Ref<Texture> end;
int subdivs;
bool overlap;
-public:
- void set_begin_texture(const Ref<Texture>& p_texture);
+public:
+ void set_begin_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_begin_texture() const;
- void set_repeat_texture(const Ref<Texture>& p_texture);
+ void set_repeat_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_repeat_texture() const;
- void set_end_texture(const Ref<Texture>& p_texture);
+ void set_end_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_end_texture() const;
void set_subdivisions(int p_amount);
diff --git a/scene/2d/physics_body_2d.cpp b/scene/2d/physics_body_2d.cpp
index 0ffaf81e3d..88845a7290 100644
--- a/scene/2d/physics_body_2d.cpp
+++ b/scene/2d/physics_body_2d.cpp
@@ -31,7 +31,7 @@
void PhysicsBody2D::_notification(int p_what) {
-/*
+ /*
switch(p_what) {
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -43,78 +43,74 @@ void PhysicsBody2D::_notification(int p_what) {
*/
}
-void PhysicsBody2D::set_one_way_collision_direction(const Vector2& p_dir) {
+void PhysicsBody2D::set_one_way_collision_direction(const Vector2 &p_dir) {
- one_way_collision_direction=p_dir;
- Physics2DServer::get_singleton()->body_set_one_way_collision_direction(get_rid(),p_dir);
+ one_way_collision_direction = p_dir;
+ Physics2DServer::get_singleton()->body_set_one_way_collision_direction(get_rid(), p_dir);
}
-Vector2 PhysicsBody2D::get_one_way_collision_direction() const{
+Vector2 PhysicsBody2D::get_one_way_collision_direction() const {
return one_way_collision_direction;
}
-
void PhysicsBody2D::set_one_way_collision_max_depth(float p_depth) {
- one_way_collision_max_depth=p_depth;
- Physics2DServer::get_singleton()->body_set_one_way_collision_max_depth(get_rid(),p_depth);
-
+ one_way_collision_max_depth = p_depth;
+ Physics2DServer::get_singleton()->body_set_one_way_collision_max_depth(get_rid(), p_depth);
}
-float PhysicsBody2D::get_one_way_collision_max_depth() const{
+float PhysicsBody2D::get_one_way_collision_max_depth() const {
return one_way_collision_max_depth;
}
-
void PhysicsBody2D::_set_layers(uint32_t p_mask) {
set_collision_layer(p_mask);
set_collision_mask(p_mask);
}
-uint32_t PhysicsBody2D::_get_layers() const{
+uint32_t PhysicsBody2D::_get_layers() const {
return get_collision_layer();
}
void PhysicsBody2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_collision_layer","mask"),&PhysicsBody2D::set_collision_layer);
- ClassDB::bind_method(D_METHOD("get_collision_layer"),&PhysicsBody2D::get_collision_layer);
- ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&PhysicsBody2D::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"),&PhysicsBody2D::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_layer", "mask"), &PhysicsBody2D::set_collision_layer);
+ ClassDB::bind_method(D_METHOD("get_collision_layer"), &PhysicsBody2D::get_collision_layer);
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &PhysicsBody2D::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &PhysicsBody2D::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &PhysicsBody2D::set_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &PhysicsBody2D::get_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&PhysicsBody2D::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&PhysicsBody2D::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &PhysicsBody2D::set_collision_layer_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &PhysicsBody2D::get_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("set_collision_layer_bit","bit","value"),&PhysicsBody2D::set_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("get_collision_layer_bit","bit"),&PhysicsBody2D::get_collision_layer_bit);
+ ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody2D::_set_layers);
+ ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody2D::_get_layers);
+ ClassDB::bind_method(D_METHOD("set_one_way_collision_direction", "dir"), &PhysicsBody2D::set_one_way_collision_direction);
+ ClassDB::bind_method(D_METHOD("get_one_way_collision_direction"), &PhysicsBody2D::get_one_way_collision_direction);
+ ClassDB::bind_method(D_METHOD("set_one_way_collision_max_depth", "depth"), &PhysicsBody2D::set_one_way_collision_max_depth);
+ ClassDB::bind_method(D_METHOD("get_one_way_collision_max_depth"), &PhysicsBody2D::get_one_way_collision_max_depth);
+ ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body:PhysicsBody2D"), &PhysicsBody2D::add_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body:PhysicsBody2D"), &PhysicsBody2D::remove_collision_exception_with);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_2D_PHYSICS, "", 0), "_set_layers", "_get_layers"); //for backwards compat
- ClassDB::bind_method(D_METHOD("_set_layers","mask"),&PhysicsBody2D::_set_layers);
- ClassDB::bind_method(D_METHOD("_get_layers"),&PhysicsBody2D::_get_layers);
- ClassDB::bind_method(D_METHOD("set_one_way_collision_direction","dir"),&PhysicsBody2D::set_one_way_collision_direction);
- ClassDB::bind_method(D_METHOD("get_one_way_collision_direction"),&PhysicsBody2D::get_one_way_collision_direction);
- ClassDB::bind_method(D_METHOD("set_one_way_collision_max_depth","depth"),&PhysicsBody2D::set_one_way_collision_max_depth);
- ClassDB::bind_method(D_METHOD("get_one_way_collision_max_depth"),&PhysicsBody2D::get_one_way_collision_max_depth);
- ClassDB::bind_method(D_METHOD("add_collision_exception_with","body:PhysicsBody2D"),&PhysicsBody2D::add_collision_exception_with);
- ClassDB::bind_method(D_METHOD("remove_collision_exception_with","body:PhysicsBody2D"),&PhysicsBody2D::remove_collision_exception_with);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"layers",PROPERTY_HINT_LAYERS_2D_PHYSICS,"",0),"_set_layers","_get_layers"); //for backwards compat
-
- ADD_GROUP("Collision","collision_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_layer",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_layer","get_collision_layer");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_mask","get_collision_mask");
- ADD_GROUP("","");
- ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2,"one_way_collision/direction"),"set_one_way_collision_direction","get_one_way_collision_direction");
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL,"one_way_collision/max_depth"),"set_one_way_collision_max_depth","get_one_way_collision_max_depth");
+ ADD_GROUP("Collision", "collision_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_layer", "get_collision_layer");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
+ ADD_GROUP("", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "one_way_collision/direction"), "set_one_way_collision_direction", "get_one_way_collision_direction");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "one_way_collision/max_depth"), "set_one_way_collision_max_depth", "get_one_way_collision_max_depth");
}
void PhysicsBody2D::set_collision_layer(uint32_t p_mask) {
- mask=p_mask;
- Physics2DServer::get_singleton()->body_set_layer_mask(get_rid(),p_mask);
+ mask = p_mask;
+ Physics2DServer::get_singleton()->body_set_layer_mask(get_rid(), p_mask);
}
uint32_t PhysicsBody2D::get_collision_layer() const {
@@ -124,8 +120,8 @@ uint32_t PhysicsBody2D::get_collision_layer() const {
void PhysicsBody2D::set_collision_mask(uint32_t p_mask) {
- collision_mask=p_mask;
- Physics2DServer::get_singleton()->body_set_collision_mask(get_rid(),p_mask);
+ collision_mask = p_mask;
+ Physics2DServer::get_singleton()->body_set_collision_mask(get_rid(), p_mask);
}
uint32_t PhysicsBody2D::get_collision_mask() const {
@@ -137,44 +133,41 @@ void PhysicsBody2D::set_collision_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_mask(mask);
-
}
-bool PhysicsBody2D::get_collision_mask_bit(int p_bit) const{
+bool PhysicsBody2D::get_collision_mask_bit(int p_bit) const {
- return get_collision_mask()&(1<<p_bit);
+ return get_collision_mask() & (1 << p_bit);
}
-
void PhysicsBody2D::set_collision_layer_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_layer();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_layer(mask);
-
}
-bool PhysicsBody2D::get_collision_layer_bit(int p_bit) const{
+bool PhysicsBody2D::get_collision_layer_bit(int p_bit) const {
- return get_collision_layer()&(1<<p_bit);
+ return get_collision_layer() & (1 << p_bit);
}
-PhysicsBody2D::PhysicsBody2D(Physics2DServer::BodyMode p_mode) : CollisionObject2D( Physics2DServer::get_singleton()->body_create(p_mode), false) {
+PhysicsBody2D::PhysicsBody2D(Physics2DServer::BodyMode p_mode)
+ : CollisionObject2D(Physics2DServer::get_singleton()->body_create(p_mode), false) {
- mask=1;
- collision_mask=1;
+ mask = 1;
+ collision_mask = 1;
set_one_way_collision_max_depth(0);
set_pickable(false);
-
}
-void PhysicsBody2D::add_collision_exception_with(Node* p_node) {
+void PhysicsBody2D::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody2D *physics_body = p_node->cast_to<PhysicsBody2D>();
@@ -182,11 +175,10 @@ void PhysicsBody2D::add_collision_exception_with(Node* p_node) {
ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type");
}
ERR_FAIL_COND(!physics_body);
- Physics2DServer::get_singleton()->body_add_collision_exception(get_rid(),physics_body->get_rid());
-
+ Physics2DServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid());
}
-void PhysicsBody2D::remove_collision_exception_with(Node* p_node) {
+void PhysicsBody2D::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody2D *physics_body = p_node->cast_to<PhysicsBody2D>();
@@ -194,20 +186,19 @@ void PhysicsBody2D::remove_collision_exception_with(Node* p_node) {
ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type");
}
ERR_FAIL_COND(!physics_body);
- Physics2DServer::get_singleton()->body_remove_collision_exception(get_rid(),physics_body->get_rid());
+ Physics2DServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid());
}
-void StaticBody2D::set_constant_linear_velocity(const Vector2& p_vel) {
-
- constant_linear_velocity=p_vel;
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_LINEAR_VELOCITY,constant_linear_velocity);
+void StaticBody2D::set_constant_linear_velocity(const Vector2 &p_vel) {
+ constant_linear_velocity = p_vel;
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity);
}
void StaticBody2D::set_constant_angular_velocity(real_t p_vel) {
- constant_angular_velocity=p_vel;
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_ANGULAR_VELOCITY,constant_angular_velocity);
+ constant_angular_velocity = p_vel;
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity);
}
Vector2 StaticBody2D::get_constant_linear_velocity() const {
@@ -242,91 +233,80 @@ void StaticBody2D::_update_xform() {
}
#endif
+void StaticBody2D::set_friction(real_t p_friction) {
-void StaticBody2D::set_friction(real_t p_friction){
-
- ERR_FAIL_COND(p_friction<0 || p_friction>1);
-
- friction=p_friction;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_FRICTION,friction);
+ ERR_FAIL_COND(p_friction < 0 || p_friction > 1);
+ friction = p_friction;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction);
}
-real_t StaticBody2D::get_friction() const{
+real_t StaticBody2D::get_friction() const {
return friction;
}
-void StaticBody2D::set_bounce(real_t p_bounce){
+void StaticBody2D::set_bounce(real_t p_bounce) {
- ERR_FAIL_COND(p_bounce<0 || p_bounce>1);
-
- bounce=p_bounce;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_BOUNCE,bounce);
+ ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1);
+ bounce = p_bounce;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce);
}
-real_t StaticBody2D::get_bounce() const{
+real_t StaticBody2D::get_bounce() const {
return bounce;
}
void StaticBody2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_constant_linear_velocity","vel"),&StaticBody2D::set_constant_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_constant_angular_velocity","vel"),&StaticBody2D::set_constant_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"),&StaticBody2D::get_constant_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"),&StaticBody2D::get_constant_angular_velocity);
- ClassDB::bind_method(D_METHOD("set_friction","friction"),&StaticBody2D::set_friction);
- ClassDB::bind_method(D_METHOD("get_friction"),&StaticBody2D::get_friction);
+ ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "vel"), &StaticBody2D::set_constant_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "vel"), &StaticBody2D::set_constant_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"), &StaticBody2D::get_constant_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"), &StaticBody2D::get_constant_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_friction", "friction"), &StaticBody2D::set_friction);
+ ClassDB::bind_method(D_METHOD("get_friction"), &StaticBody2D::get_friction);
- ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&StaticBody2D::set_bounce);
- ClassDB::bind_method(D_METHOD("get_bounce"),&StaticBody2D::get_bounce);
+ ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody2D::set_bounce);
+ ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody2D::get_bounce);
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"constant_linear_velocity"),"set_constant_linear_velocity","get_constant_linear_velocity");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"constant_angular_velocity"),"set_constant_angular_velocity","get_constant_angular_velocity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce");
}
-StaticBody2D::StaticBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) {
-
- constant_angular_velocity=0;
- bounce=0;
- friction=1;
-
+StaticBody2D::StaticBody2D()
+ : PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) {
+ constant_angular_velocity = 0;
+ bounce = 0;
+ friction = 1;
}
StaticBody2D::~StaticBody2D() {
-
}
-
-
-
void RigidBody2D::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_scene);
- contact_monitor->locked=true;
-
- E->get().in_scene=true;
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ contact_monitor->locked = true;
+ E->get().in_scene = true;
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
}
- contact_monitor->locked=false;
-
-
+ contact_monitor->locked = false;
}
void RigidBody2D::_body_exit_tree(ObjectID p_id) {
@@ -334,33 +314,32 @@ void RigidBody2D::_body_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_scene);
- E->get().in_scene=false;
+ E->get().in_scene = false;
- contact_monitor->locked=true;
+ contact_monitor->locked = true;
- emit_signal(SceneStringNames::get_singleton()->body_exited,node);
+ emit_signal(SceneStringNames::get_singleton()->body_exited, node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
}
- contact_monitor->locked=false;
-
+ contact_monitor->locked = false;
}
-void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape) {
+void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape) {
- bool body_in = p_status==1;
- ObjectID objid=p_instance;
+ bool body_in = p_status == 1;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(objid);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(objid);
/*if (obj) {
if (body_in)
@@ -374,14 +353,14 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap
if (body_in) {
if (!E) {
- E = contact_monitor->body_map.insert(objid,BodyState());
+ E = contact_monitor->body_map.insert(objid, BodyState());
//E->get().rc=0;
- E->get().in_scene=node && node->is_inside_tree();
+ E->get().in_scene = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid));
if (E->get().in_scene) {
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
}
}
@@ -389,11 +368,10 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap
}
if (node)
- E->get().shapes.insert(ShapePair(p_body_shape,p_local_shape));
-
+ E->get().shapes.insert(ShapePair(p_body_shape, p_local_shape));
if (E->get().in_scene) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_local_shape);
}
} else {
@@ -401,31 +379,27 @@ void RigidBody2D::_body_inout(int p_status, ObjectID p_instance, int p_body_shap
//E->get().rc--;
if (node)
- E->get().shapes.erase(ShapePair(p_body_shape,p_local_shape));
+ E->get().shapes.erase(ShapePair(p_body_shape, p_local_shape));
bool in_scene = E->get().in_scene;
if (E->get().shapes.empty()) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
if (in_scene)
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
-
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
}
contact_monitor->body_map.erase(E);
}
if (node && in_scene) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_local_shape);
}
-
}
-
}
-
struct _RigidBody2DInOut {
ObjectID id;
@@ -433,62 +407,60 @@ struct _RigidBody2DInOut {
int local_shape;
};
+bool RigidBody2D::_test_motion(const Vector2 &p_motion, float p_margin, const Ref<Physics2DTestMotionResult> &p_result) {
-bool RigidBody2D::_test_motion(const Vector2& p_motion,float p_margin,const Ref<Physics2DTestMotionResult>& p_result) {
-
- Physics2DServer::MotionResult *r=NULL;
+ Physics2DServer::MotionResult *r = NULL;
if (p_result.is_valid())
- r=p_result->get_result_ptr();
- return Physics2DServer::get_singleton()->body_test_motion(get_rid(),get_global_transform(),p_motion,p_margin,r);
-
+ r = p_result->get_result_ptr();
+ return Physics2DServer::get_singleton()->body_test_motion(get_rid(), get_global_transform(), p_motion, p_margin, r);
}
void RigidBody2D::_direct_state_changed(Object *p_state) {
- //eh.. fuck
+//eh.. fuck
#ifdef DEBUG_ENABLED
- state=p_state->cast_to<Physics2DDirectBodyState>();
+ state = p_state->cast_to<Physics2DDirectBodyState>();
#else
- state=(Physics2DDirectBodyState*)p_state; //trust it
+ state = (Physics2DDirectBodyState *)p_state; //trust it
#endif
set_block_transform_notify(true); // don't want notify (would feedback loop)
- if (mode!=MODE_KINEMATIC)
+ if (mode != MODE_KINEMATIC)
set_global_transform(state->get_transform());
- linear_velocity=state->get_linear_velocity();
- angular_velocity=state->get_angular_velocity();
- if(sleeping!=state->is_sleeping()) {
- sleeping=state->is_sleeping();
+ linear_velocity = state->get_linear_velocity();
+ angular_velocity = state->get_angular_velocity();
+ if (sleeping != state->is_sleeping()) {
+ sleeping = state->is_sleeping();
emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed);
}
if (get_script_instance())
- get_script_instance()->call("_integrate_forces",state);
+ get_script_instance()->call("_integrate_forces", state);
set_block_transform_notify(false); // want it back
if (contact_monitor) {
- contact_monitor->locked=true;
+ contact_monitor->locked = true;
//untag all
- int rc=0;
- for( Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ int rc = 0;
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- E->get().shapes[i].tagged=false;
+ E->get().shapes[i].tagged = false;
rc++;
}
}
- _RigidBody2DInOut *toadd=(_RigidBody2DInOut*)alloca(state->get_contact_count()*sizeof(_RigidBody2DInOut));
- int toadd_count=0;//state->get_contact_count();
- RigidBody2D_RemoveAction *toremove=(RigidBody2D_RemoveAction*)alloca(rc*sizeof(RigidBody2D_RemoveAction));
- int toremove_count=0;
+ _RigidBody2DInOut *toadd = (_RigidBody2DInOut *)alloca(state->get_contact_count() * sizeof(_RigidBody2DInOut));
+ int toadd_count = 0; //state->get_contact_count();
+ RigidBody2D_RemoveAction *toremove = (RigidBody2D_RemoveAction *)alloca(rc * sizeof(RigidBody2D_RemoveAction));
+ int toremove_count = 0;
//put the ones to add
- for(int i=0;i<state->get_contact_count();i++) {
+ for (int i = 0; i < state->get_contact_count(); i++) {
ObjectID obj = state->get_contact_collider_id(i);
int local_shape = state->get_contact_local_shape(i);
@@ -496,270 +468,250 @@ void RigidBody2D::_direct_state_changed(Object *p_state) {
//bool found=false;
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(obj);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(obj);
if (!E) {
- toadd[toadd_count].local_shape=local_shape;
- toadd[toadd_count].id=obj;
- toadd[toadd_count].shape=shape;
+ toadd[toadd_count].local_shape = local_shape;
+ toadd[toadd_count].id = obj;
+ toadd[toadd_count].shape = shape;
toadd_count++;
continue;
}
- ShapePair sp( shape,local_shape );
+ ShapePair sp(shape, local_shape);
int idx = E->get().shapes.find(sp);
- if (idx==-1) {
+ if (idx == -1) {
- toadd[toadd_count].local_shape=local_shape;
- toadd[toadd_count].id=obj;
- toadd[toadd_count].shape=shape;
+ toadd[toadd_count].local_shape = local_shape;
+ toadd[toadd_count].id = obj;
+ toadd[toadd_count].shape = shape;
toadd_count++;
continue;
}
- E->get().shapes[idx].tagged=true;
+ E->get().shapes[idx].tagged = true;
}
//put the ones to remove
- for( Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
if (!E->get().shapes[i].tagged) {
- toremove[toremove_count].body_id=E->key();
- toremove[toremove_count].pair=E->get().shapes[i];
+ toremove[toremove_count].body_id = E->key();
+ toremove[toremove_count].pair = E->get().shapes[i];
toremove_count++;
}
}
}
-
//process remotions
+ for (int i = 0; i < toremove_count; i++) {
- for(int i=0;i<toremove_count;i++) {
-
- _body_inout(0,toremove[i].body_id,toremove[i].pair.body_shape,toremove[i].pair.local_shape);
+ _body_inout(0, toremove[i].body_id, toremove[i].pair.body_shape, toremove[i].pair.local_shape);
}
//process aditions
+ for (int i = 0; i < toadd_count; i++) {
- for(int i=0;i<toadd_count;i++) {
-
- _body_inout(1,toadd[i].id,toadd[i].shape,toadd[i].local_shape);
+ _body_inout(1, toadd[i].id, toadd[i].shape, toadd[i].local_shape);
}
- contact_monitor->locked=false;
-
+ contact_monitor->locked = false;
}
-
-
- state=NULL;
+ state = NULL;
}
-
void RigidBody2D::set_mode(Mode p_mode) {
- mode=p_mode;
- switch(p_mode) {
+ mode = p_mode;
+ switch (p_mode) {
case MODE_RIGID: {
- Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_RIGID);
+ Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_RIGID);
} break;
case MODE_STATIC: {
- Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_STATIC);
+ Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_STATIC);
} break;
case MODE_KINEMATIC: {
- Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_KINEMATIC);
+ Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_KINEMATIC);
} break;
case MODE_CHARACTER: {
- Physics2DServer::get_singleton()->body_set_mode(get_rid(),Physics2DServer::BODY_MODE_CHARACTER);
+ Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_CHARACTER);
} break;
-
}
}
-RigidBody2D::Mode RigidBody2D::get_mode() const{
+RigidBody2D::Mode RigidBody2D::get_mode() const {
return mode;
}
-void RigidBody2D::set_mass(real_t p_mass){
+void RigidBody2D::set_mass(real_t p_mass) {
- ERR_FAIL_COND(p_mass<=0);
- mass=p_mass;
+ ERR_FAIL_COND(p_mass <= 0);
+ mass = p_mass;
_change_notify("mass");
_change_notify("weight");
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_MASS,mass);
-
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_MASS, mass);
}
-real_t RigidBody2D::get_mass() const{
+real_t RigidBody2D::get_mass() const {
return mass;
}
void RigidBody2D::set_inertia(real_t p_inertia) {
- ERR_FAIL_COND(p_inertia<=0);
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_INERTIA,p_inertia);
+ ERR_FAIL_COND(p_inertia <= 0);
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA, p_inertia);
}
-real_t RigidBody2D::get_inertia() const{
+real_t RigidBody2D::get_inertia() const {
- return Physics2DServer::get_singleton()->body_get_param(get_rid(),Physics2DServer::BODY_PARAM_INERTIA);
+ return Physics2DServer::get_singleton()->body_get_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA);
}
-void RigidBody2D::set_weight(real_t p_weight){
+void RigidBody2D::set_weight(real_t p_weight) {
- set_mass(p_weight/9.8);
+ set_mass(p_weight / 9.8);
}
-real_t RigidBody2D::get_weight() const{
+real_t RigidBody2D::get_weight() const {
- return mass*9.8;
+ return mass * 9.8;
}
+void RigidBody2D::set_friction(real_t p_friction) {
-void RigidBody2D::set_friction(real_t p_friction){
-
- ERR_FAIL_COND(p_friction<0 || p_friction>1);
-
- friction=p_friction;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_FRICTION,friction);
+ ERR_FAIL_COND(p_friction < 0 || p_friction > 1);
+ friction = p_friction;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, friction);
}
-real_t RigidBody2D::get_friction() const{
+real_t RigidBody2D::get_friction() const {
return friction;
}
-void RigidBody2D::set_bounce(real_t p_bounce){
+void RigidBody2D::set_bounce(real_t p_bounce) {
- ERR_FAIL_COND(p_bounce<0 || p_bounce>1);
-
- bounce=p_bounce;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_BOUNCE,bounce);
+ ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1);
+ bounce = p_bounce;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, bounce);
}
-real_t RigidBody2D::get_bounce() const{
+real_t RigidBody2D::get_bounce() const {
return bounce;
}
+void RigidBody2D::set_gravity_scale(real_t p_gravity_scale) {
-void RigidBody2D::set_gravity_scale(real_t p_gravity_scale){
-
- gravity_scale=p_gravity_scale;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_GRAVITY_SCALE,gravity_scale);
-
+ gravity_scale = p_gravity_scale;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_GRAVITY_SCALE, gravity_scale);
}
-real_t RigidBody2D::get_gravity_scale() const{
+real_t RigidBody2D::get_gravity_scale() const {
return gravity_scale;
}
-void RigidBody2D::set_linear_damp(real_t p_linear_damp){
-
- ERR_FAIL_COND(p_linear_damp<-1);
- linear_damp=p_linear_damp;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_LINEAR_DAMP,linear_damp);
+void RigidBody2D::set_linear_damp(real_t p_linear_damp) {
+ ERR_FAIL_COND(p_linear_damp < -1);
+ linear_damp = p_linear_damp;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_LINEAR_DAMP, linear_damp);
}
-real_t RigidBody2D::get_linear_damp() const{
+real_t RigidBody2D::get_linear_damp() const {
return linear_damp;
}
-void RigidBody2D::set_angular_damp(real_t p_angular_damp){
-
- ERR_FAIL_COND(p_angular_damp<-1);
- angular_damp=p_angular_damp;
- Physics2DServer::get_singleton()->body_set_param(get_rid(),Physics2DServer::BODY_PARAM_ANGULAR_DAMP,angular_damp);
+void RigidBody2D::set_angular_damp(real_t p_angular_damp) {
+ ERR_FAIL_COND(p_angular_damp < -1);
+ angular_damp = p_angular_damp;
+ Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_ANGULAR_DAMP, angular_damp);
}
-real_t RigidBody2D::get_angular_damp() const{
+real_t RigidBody2D::get_angular_damp() const {
return angular_damp;
}
-void RigidBody2D::set_axis_velocity(const Vector2& p_axis) {
+void RigidBody2D::set_axis_velocity(const Vector2 &p_axis) {
- Vector2 v = state? state->get_linear_velocity() : linear_velocity;
+ Vector2 v = state ? state->get_linear_velocity() : linear_velocity;
Vector2 axis = p_axis.normalized();
- v-=axis*axis.dot(v);
- v+=p_axis;
+ v -= axis * axis.dot(v);
+ v += p_axis;
if (state) {
set_linear_velocity(v);
} else {
- Physics2DServer::get_singleton()->body_set_axis_velocity(get_rid(),p_axis);
- linear_velocity=v;
+ Physics2DServer::get_singleton()->body_set_axis_velocity(get_rid(), p_axis);
+ linear_velocity = v;
}
}
-void RigidBody2D::set_linear_velocity(const Vector2& p_velocity){
+void RigidBody2D::set_linear_velocity(const Vector2 &p_velocity) {
- linear_velocity=p_velocity;
+ linear_velocity = p_velocity;
if (state)
state->set_linear_velocity(linear_velocity);
else {
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_LINEAR_VELOCITY,linear_velocity);
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
}
-
}
-Vector2 RigidBody2D::get_linear_velocity() const{
+Vector2 RigidBody2D::get_linear_velocity() const {
return linear_velocity;
}
-void RigidBody2D::set_angular_velocity(real_t p_velocity){
+void RigidBody2D::set_angular_velocity(real_t p_velocity) {
- angular_velocity=p_velocity;
+ angular_velocity = p_velocity;
if (state)
state->set_angular_velocity(angular_velocity);
else
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_ANGULAR_VELOCITY,angular_velocity);
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
}
-real_t RigidBody2D::get_angular_velocity() const{
+real_t RigidBody2D::get_angular_velocity() const {
return angular_velocity;
}
-void RigidBody2D::set_use_custom_integrator(bool p_enable){
+void RigidBody2D::set_use_custom_integrator(bool p_enable) {
- if (custom_integrator==p_enable)
+ if (custom_integrator == p_enable)
return;
- custom_integrator=p_enable;
- Physics2DServer::get_singleton()->body_set_omit_force_integration(get_rid(),p_enable);
-
-
+ custom_integrator = p_enable;
+ Physics2DServer::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable);
}
-bool RigidBody2D::is_using_custom_integrator(){
+bool RigidBody2D::is_using_custom_integrator() {
return custom_integrator;
}
void RigidBody2D::set_sleeping(bool p_sleeping) {
- sleeping=p_sleeping;
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_SLEEPING,sleeping);
-
+ sleeping = p_sleeping;
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_SLEEPING, sleeping);
}
void RigidBody2D::set_can_sleep(bool p_active) {
- can_sleep=p_active;
- Physics2DServer::get_singleton()->body_set_state(get_rid(),Physics2DServer::BODY_STATE_CAN_SLEEP,p_active);
+ can_sleep = p_active;
+ Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_CAN_SLEEP, p_active);
}
bool RigidBody2D::is_able_to_sleep() const {
@@ -774,21 +726,21 @@ bool RigidBody2D::is_sleeping() const {
void RigidBody2D::set_max_contacts_reported(int p_amount) {
- max_contacts_reported=p_amount;
- Physics2DServer::get_singleton()->body_set_max_contacts_reported(get_rid(),p_amount);
+ max_contacts_reported = p_amount;
+ Physics2DServer::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount);
}
-int RigidBody2D::get_max_contacts_reported() const{
+int RigidBody2D::get_max_contacts_reported() const {
return max_contacts_reported;
}
-void RigidBody2D::apply_impulse(const Vector2& p_offset, const Vector2& p_impulse) {
+void RigidBody2D::apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse) {
- Physics2DServer::get_singleton()->body_apply_impulse(get_rid(),p_offset,p_impulse);
+ Physics2DServer::get_singleton()->body_apply_impulse(get_rid(), p_offset, p_impulse);
}
-void RigidBody2D::set_applied_force(const Vector2& p_force) {
+void RigidBody2D::set_applied_force(const Vector2 &p_force) {
Physics2DServer::get_singleton()->body_set_applied_force(get_rid(), p_force);
};
@@ -808,16 +760,15 @@ float RigidBody2D::get_applied_torque() const {
return Physics2DServer::get_singleton()->body_get_applied_torque(get_rid());
};
-void RigidBody2D::add_force(const Vector2& p_offset, const Vector2& p_force) {
+void RigidBody2D::add_force(const Vector2 &p_offset, const Vector2 &p_force) {
- Physics2DServer::get_singleton()->body_add_force(get_rid(),p_offset,p_force);
+ Physics2DServer::get_singleton()->body_add_force(get_rid(), p_offset, p_force);
}
void RigidBody2D::set_continuous_collision_detection_mode(CCDMode p_mode) {
- ccd_mode=p_mode;
- Physics2DServer::get_singleton()->body_set_continuous_collision_detection_mode(get_rid(),Physics2DServer::CCDMode(p_mode));
-
+ ccd_mode = p_mode;
+ Physics2DServer::get_singleton()->body_set_continuous_collision_detection_mode(get_rid(), Physics2DServer::CCDMode(p_mode));
}
RigidBody2D::CCDMode RigidBody2D::get_continuous_collision_detection_mode() const {
@@ -825,22 +776,20 @@ RigidBody2D::CCDMode RigidBody2D::get_continuous_collision_detection_mode() cons
return ccd_mode;
}
-
Array RigidBody2D::get_colliding_bodies() const {
- ERR_FAIL_COND_V(!contact_monitor,Array());
+ ERR_FAIL_COND_V(!contact_monitor, Array());
Array ret;
ret.resize(contact_monitor->body_map.size());
- int idx=0;
- for (const Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
@@ -848,7 +797,7 @@ Array RigidBody2D::get_colliding_bodies() const {
void RigidBody2D::set_contact_monitor(bool p_enabled) {
- if (p_enabled==is_contact_monitor_enabled())
+ if (p_enabled == is_contact_monitor_enabled())
return;
if (!p_enabled) {
@@ -858,180 +807,173 @@ void RigidBody2D::set_contact_monitor(bool p_enabled) {
}
ERR_FAIL_COND(contact_monitor->locked);
- for(Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
//clean up mess
}
- memdelete( contact_monitor );
- contact_monitor=NULL;
+ memdelete(contact_monitor);
+ contact_monitor = NULL;
} else {
- contact_monitor = memnew( ContactMonitor );
- contact_monitor->locked=false;
+ contact_monitor = memnew(ContactMonitor);
+ contact_monitor->locked = false;
}
-
}
bool RigidBody2D::is_contact_monitor_enabled() const {
- return contact_monitor!=NULL;
+ return contact_monitor != NULL;
}
-
-
void RigidBody2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&RigidBody2D::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&RigidBody2D::get_mode);
-
- ClassDB::bind_method(D_METHOD("set_mass","mass"),&RigidBody2D::set_mass);
- ClassDB::bind_method(D_METHOD("get_mass"),&RigidBody2D::get_mass);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody2D::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody2D::get_mode);
- ClassDB::bind_method(D_METHOD("get_inertia"),&RigidBody2D::get_inertia);
- ClassDB::bind_method(D_METHOD("set_inertia","inertia"),&RigidBody2D::set_inertia);
+ ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody2D::set_mass);
+ ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody2D::get_mass);
- ClassDB::bind_method(D_METHOD("set_weight","weight"),&RigidBody2D::set_weight);
- ClassDB::bind_method(D_METHOD("get_weight"),&RigidBody2D::get_weight);
+ ClassDB::bind_method(D_METHOD("get_inertia"), &RigidBody2D::get_inertia);
+ ClassDB::bind_method(D_METHOD("set_inertia", "inertia"), &RigidBody2D::set_inertia);
- ClassDB::bind_method(D_METHOD("set_friction","friction"),&RigidBody2D::set_friction);
- ClassDB::bind_method(D_METHOD("get_friction"),&RigidBody2D::get_friction);
+ ClassDB::bind_method(D_METHOD("set_weight", "weight"), &RigidBody2D::set_weight);
+ ClassDB::bind_method(D_METHOD("get_weight"), &RigidBody2D::get_weight);
- ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&RigidBody2D::set_bounce);
- ClassDB::bind_method(D_METHOD("get_bounce"),&RigidBody2D::get_bounce);
+ ClassDB::bind_method(D_METHOD("set_friction", "friction"), &RigidBody2D::set_friction);
+ ClassDB::bind_method(D_METHOD("get_friction"), &RigidBody2D::get_friction);
- ClassDB::bind_method(D_METHOD("set_gravity_scale","gravity_scale"),&RigidBody2D::set_gravity_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_scale"),&RigidBody2D::get_gravity_scale);
+ ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody2D::set_bounce);
+ ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody2D::get_bounce);
- ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&RigidBody2D::set_linear_damp);
- ClassDB::bind_method(D_METHOD("get_linear_damp"),&RigidBody2D::get_linear_damp);
+ ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody2D::set_gravity_scale);
+ ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody2D::get_gravity_scale);
- ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&RigidBody2D::set_angular_damp);
- ClassDB::bind_method(D_METHOD("get_angular_damp"),&RigidBody2D::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody2D::set_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody2D::get_linear_damp);
- ClassDB::bind_method(D_METHOD("set_linear_velocity","linear_velocity"),&RigidBody2D::set_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"),&RigidBody2D::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody2D::set_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody2D::get_angular_damp);
- ClassDB::bind_method(D_METHOD("set_angular_velocity","angular_velocity"),&RigidBody2D::set_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_angular_velocity"),&RigidBody2D::get_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody2D::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody2D::get_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_max_contacts_reported","amount"),&RigidBody2D::set_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("get_max_contacts_reported"),&RigidBody2D::get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody2D::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody2D::get_angular_velocity);
- ClassDB::bind_method(D_METHOD("set_use_custom_integrator","enable"),&RigidBody2D::set_use_custom_integrator);
- ClassDB::bind_method(D_METHOD("is_using_custom_integrator"),&RigidBody2D::is_using_custom_integrator);
+ ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody2D::set_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody2D::get_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("set_contact_monitor","enabled"),&RigidBody2D::set_contact_monitor);
- ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"),&RigidBody2D::is_contact_monitor_enabled);
+ ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody2D::set_use_custom_integrator);
+ ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody2D::is_using_custom_integrator);
- ClassDB::bind_method(D_METHOD("set_continuous_collision_detection_mode","mode"),&RigidBody2D::set_continuous_collision_detection_mode);
- ClassDB::bind_method(D_METHOD("get_continuous_collision_detection_mode"),&RigidBody2D::get_continuous_collision_detection_mode);
+ ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody2D::set_contact_monitor);
+ ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody2D::is_contact_monitor_enabled);
- ClassDB::bind_method(D_METHOD("set_axis_velocity","axis_velocity"),&RigidBody2D::set_axis_velocity);
- ClassDB::bind_method(D_METHOD("apply_impulse","offset","impulse"),&RigidBody2D::apply_impulse);
+ ClassDB::bind_method(D_METHOD("set_continuous_collision_detection_mode", "mode"), &RigidBody2D::set_continuous_collision_detection_mode);
+ ClassDB::bind_method(D_METHOD("get_continuous_collision_detection_mode"), &RigidBody2D::get_continuous_collision_detection_mode);
- ClassDB::bind_method(D_METHOD("set_applied_force","force"),&RigidBody2D::set_applied_force);
- ClassDB::bind_method(D_METHOD("get_applied_force"),&RigidBody2D::get_applied_force);
+ ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody2D::set_axis_velocity);
+ ClassDB::bind_method(D_METHOD("apply_impulse", "offset", "impulse"), &RigidBody2D::apply_impulse);
- ClassDB::bind_method(D_METHOD("set_applied_torque","torque"),&RigidBody2D::set_applied_torque);
- ClassDB::bind_method(D_METHOD("get_applied_torque"),&RigidBody2D::get_applied_torque);
+ ClassDB::bind_method(D_METHOD("set_applied_force", "force"), &RigidBody2D::set_applied_force);
+ ClassDB::bind_method(D_METHOD("get_applied_force"), &RigidBody2D::get_applied_force);
- ClassDB::bind_method(D_METHOD("add_force","offset","force"),&RigidBody2D::add_force);
+ ClassDB::bind_method(D_METHOD("set_applied_torque", "torque"), &RigidBody2D::set_applied_torque);
+ ClassDB::bind_method(D_METHOD("get_applied_torque"), &RigidBody2D::get_applied_torque);
- ClassDB::bind_method(D_METHOD("set_sleeping","sleeping"),&RigidBody2D::set_sleeping);
- ClassDB::bind_method(D_METHOD("is_sleeping"),&RigidBody2D::is_sleeping);
+ ClassDB::bind_method(D_METHOD("add_force", "offset", "force"), &RigidBody2D::add_force);
- ClassDB::bind_method(D_METHOD("set_can_sleep","able_to_sleep"),&RigidBody2D::set_can_sleep);
- ClassDB::bind_method(D_METHOD("is_able_to_sleep"),&RigidBody2D::is_able_to_sleep);
+ ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody2D::set_sleeping);
+ ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody2D::is_sleeping);
- ClassDB::bind_method(D_METHOD("test_motion","motion","margin","result:Physics2DTestMotionResult"),&RigidBody2D::_test_motion,DEFVAL(0.08),DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody2D::set_can_sleep);
+ ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody2D::is_able_to_sleep);
- ClassDB::bind_method(D_METHOD("_direct_state_changed"),&RigidBody2D::_direct_state_changed);
- ClassDB::bind_method(D_METHOD("_body_enter_tree"),&RigidBody2D::_body_enter_tree);
- ClassDB::bind_method(D_METHOD("_body_exit_tree"),&RigidBody2D::_body_exit_tree);
+ ClassDB::bind_method(D_METHOD("test_motion", "motion", "margin", "result:Physics2DTestMotionResult"), &RigidBody2D::_test_motion, DEFVAL(0.08), DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("get_colliding_bodies"),&RigidBody2D::get_colliding_bodies);
+ ClassDB::bind_method(D_METHOD("_direct_state_changed"), &RigidBody2D::_direct_state_changed);
+ ClassDB::bind_method(D_METHOD("_body_enter_tree"), &RigidBody2D::_body_enter_tree);
+ ClassDB::bind_method(D_METHOD("_body_exit_tree"), &RigidBody2D::_body_exit_tree);
- BIND_VMETHOD(MethodInfo("_integrate_forces",PropertyInfo(Variant::OBJECT,"state:Physics2DDirectBodyState")));
+ ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody2D::get_colliding_bodies);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Rigid,Static,Character,Kinematic"),"set_mode","get_mode");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01"),"set_mass","get_mass");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"weight",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01",PROPERTY_USAGE_EDITOR),"set_weight","get_weight");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity_scale",PROPERTY_HINT_RANGE,"-128,128,0.01"),"set_gravity_scale","get_gravity_scale");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"custom_integrator"),"set_use_custom_integrator","is_using_custom_integrator");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"continuous_cd",PROPERTY_HINT_ENUM,"Disabled,Cast Ray,Cast Shape"),"set_continuous_collision_detection_mode","get_continuous_collision_detection_mode");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"contacts_reported"),"set_max_contacts_reported","get_max_contacts_reported");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"contact_monitor"),"set_contact_monitor","is_contact_monitor_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"sleeping"),"set_sleeping","is_sleeping");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"can_sleep"),"set_can_sleep","is_able_to_sleep");
- ADD_GROUP("Linear","linear_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"linear_velocity"),"set_linear_velocity","get_linear_velocity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_linear_damp","get_linear_damp");
- ADD_GROUP("Angular","angular_");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_velocity"),"set_angular_velocity","get_angular_velocity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_angular_damp","get_angular_damp");
+ BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state:Physics2DDirectBodyState")));
- ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape")));
- ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape")));
- ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body")));
- ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body")));
- ADD_SIGNAL( MethodInfo("sleeping_state_changed"));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "continuous_cd", PROPERTY_HINT_ENUM, "Disabled,Cast Ray,Cast Shape"), "set_continuous_collision_detection_mode", "get_continuous_collision_detection_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported"), "set_max_contacts_reported", "get_max_contacts_reported");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
+ ADD_GROUP("Linear", "linear_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "linear_velocity"), "set_linear_velocity", "get_linear_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_linear_damp", "get_linear_damp");
+ ADD_GROUP("Angular", "angular_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_velocity"), "set_angular_velocity", "get_angular_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_angular_damp", "get_angular_damp");
- BIND_CONSTANT( MODE_STATIC );
- BIND_CONSTANT( MODE_KINEMATIC );
- BIND_CONSTANT( MODE_RIGID );
- BIND_CONSTANT( MODE_CHARACTER );
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("sleeping_state_changed"));
- BIND_CONSTANT( CCD_MODE_DISABLED );
- BIND_CONSTANT( CCD_MODE_CAST_RAY );
- BIND_CONSTANT( CCD_MODE_CAST_SHAPE );
+ BIND_CONSTANT(MODE_STATIC);
+ BIND_CONSTANT(MODE_KINEMATIC);
+ BIND_CONSTANT(MODE_RIGID);
+ BIND_CONSTANT(MODE_CHARACTER);
+ BIND_CONSTANT(CCD_MODE_DISABLED);
+ BIND_CONSTANT(CCD_MODE_CAST_RAY);
+ BIND_CONSTANT(CCD_MODE_CAST_SHAPE);
}
-RigidBody2D::RigidBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_RIGID) {
+RigidBody2D::RigidBody2D()
+ : PhysicsBody2D(Physics2DServer::BODY_MODE_RIGID) {
- mode=MODE_RIGID;
+ mode = MODE_RIGID;
- bounce=0;
- mass=1;
- friction=1;
+ bounce = 0;
+ mass = 1;
+ friction = 1;
- gravity_scale=1;
- linear_damp=-1;
- angular_damp=-1;
+ gravity_scale = 1;
+ linear_damp = -1;
+ angular_damp = -1;
- max_contacts_reported=0;
- state=NULL;
+ max_contacts_reported = 0;
+ state = NULL;
- angular_velocity=0;
- sleeping=false;
- ccd_mode=CCD_MODE_DISABLED;
+ angular_velocity = 0;
+ sleeping = false;
+ ccd_mode = CCD_MODE_DISABLED;
- custom_integrator=false;
- contact_monitor=NULL;
- can_sleep=true;
+ custom_integrator = false;
+ contact_monitor = NULL;
+ can_sleep = true;
- Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed");
+ Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
}
RigidBody2D::~RigidBody2D() {
if (contact_monitor)
- memdelete( contact_monitor );
-
-
-
+ memdelete(contact_monitor);
}
//////////////////////////
-
Variant KinematicBody2D::_get_collider() const {
- ObjectID oid=get_collider();
- if (oid==0)
+ ObjectID oid = get_collider();
+ if (oid == 0)
return Variant();
Object *obj = ObjectDB::get_instance(oid);
if (!obj)
@@ -1048,10 +990,9 @@ Variant KinematicBody2D::_get_collider() const {
void KinematicBody2D::revert_motion() {
Transform2D gt = get_global_transform();
- gt.elements[2]-=travel;
- travel=Vector2();
+ gt.elements[2] -= travel;
+ travel = Vector2();
set_global_transform(gt);
-
}
Vector2 KinematicBody2D::get_travel() const {
@@ -1059,26 +1000,24 @@ Vector2 KinematicBody2D::get_travel() const {
return travel;
}
-Vector2 KinematicBody2D::move(const Vector2& p_motion) {
+Vector2 KinematicBody2D::move(const Vector2 &p_motion) {
#if 1
Transform2D gt = get_global_transform();
Physics2DServer::MotionResult result;
- colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(),gt,p_motion,margin,&result);
-
- collider_metadata=result.collider_metadata;
- collider_shape=result.collider_shape;
- collider_vel=result.collider_velocity;
- collision=result.collision_point;
- normal=result.collision_normal;
- collider=result.collider_id;
+ colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(), gt, p_motion, margin, &result);
+ collider_metadata = result.collider_metadata;
+ collider_shape = result.collider_shape;
+ collider_vel = result.collider_velocity;
+ collision = result.collision_point;
+ normal = result.collision_normal;
+ collider = result.collider_id;
- gt.elements[2]+=result.motion;
+ gt.elements[2] += result.motion;
set_global_transform(gt);
- travel=result.motion;
-
+ travel = result.motion;
return result.remainder;
@@ -1090,43 +1029,41 @@ Vector2 KinematicBody2D::move(const Vector2& p_motion) {
//this took about a week to get right..
//but is it right? who knows at this point..
- colliding=false;
- ERR_FAIL_COND_V(!is_inside_tree(),Vector2());
+ colliding = false;
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector2());
Physics2DDirectSpaceState *dss = Physics2DServer::get_singleton()->space_get_direct_state(get_world_2d()->get_space());
- ERR_FAIL_COND_V(!dss,Vector2());
- const int max_shapes=32;
- Vector2 sr[max_shapes*2];
+ ERR_FAIL_COND_V(!dss, Vector2());
+ const int max_shapes = 32;
+ Vector2 sr[max_shapes * 2];
int res_shapes;
Set<RID> exclude;
exclude.insert(get_rid());
-
//recover first
- int recover_attempts=4;
+ int recover_attempts = 4;
- bool collided=false;
- uint32_t mask=0;
+ bool collided = false;
+ uint32_t mask = 0;
if (true)
- mask|=Physics2DDirectSpaceState::TYPE_MASK_STATIC_BODY;
+ mask |= Physics2DDirectSpaceState::TYPE_MASK_STATIC_BODY;
if (true)
- mask|=Physics2DDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
+ mask |= Physics2DDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
if (true)
- mask|=Physics2DDirectSpaceState::TYPE_MASK_RIGID_BODY;
+ mask |= Physics2DDirectSpaceState::TYPE_MASK_RIGID_BODY;
if (true)
- mask|=Physics2DDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
+ mask |= Physics2DDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
//print_line("margin: "+rtos(margin));
do {
//motion recover
- for(int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
if (is_shape_set_as_trigger(i))
continue;
- if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i),Vector2(),margin,sr,max_shapes,res_shapes,exclude,get_layer_mask(),mask))
- collided=true;
-
+ if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), Vector2(), margin, sr, max_shapes, res_shapes, exclude, get_layer_mask(), mask))
+ collided = true;
}
if (!collided)
@@ -1134,10 +1071,10 @@ Vector2 KinematicBody2D::move(const Vector2& p_motion) {
Vector2 recover_motion;
- for(int i=0;i<res_shapes;i++) {
+ for (int i = 0; i < res_shapes; i++) {
- Vector2 a = sr[i*2+0];
- Vector2 b = sr[i*2+1];
+ Vector2 a = sr[i * 2 + 0];
+ Vector2 b = sr[i * 2 + 1];
float d = a.distance_to(b);
@@ -1145,145 +1082,133 @@ Vector2 KinematicBody2D::move(const Vector2& p_motion) {
if (d<margin)
continue;
*/
- recover_motion+=(b-a)*0.4;
+ recover_motion += (b - a) * 0.4;
}
- if (recover_motion==Vector2()) {
- collided=false;
+ if (recover_motion == Vector2()) {
+ collided = false;
break;
}
-
-
Transform2D gt = get_global_transform();
- gt.elements[2]+=recover_motion;
+ gt.elements[2] += recover_motion;
set_global_transform(gt);
recover_attempts--;
} while (recover_attempts);
-
//move second
float safe = 1.0;
float unsafe = 1.0;
- int best_shape=-1;
+ int best_shape = -1;
- for(int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
if (is_shape_set_as_trigger(i))
continue;
- float lsafe,lunsafe;
- bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0,lsafe,lunsafe,exclude,get_layer_mask(),mask);
+ float lsafe, lunsafe;
+ bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0, lsafe, lunsafe, exclude, get_layer_mask(), mask);
//print_line("shape: "+itos(i)+" travel:"+rtos(ltravel));
if (!valid) {
- safe=0;
- unsafe=0;
- best_shape=i; //sadly it's the best
+ safe = 0;
+ unsafe = 0;
+ best_shape = i; //sadly it's the best
break;
}
- if (lsafe==1.0) {
+ if (lsafe == 1.0) {
continue;
}
if (lsafe < safe) {
- safe=lsafe;
- unsafe=lunsafe;
- best_shape=i;
+ safe = lsafe;
+ unsafe = lunsafe;
+ best_shape = i;
}
}
-
//print_line("best shape: "+itos(best_shape)+" motion "+p_motion);
- if (safe>=1) {
+ if (safe >= 1) {
//not collided
- colliding=false;
-
+ colliding = false;
} else {
//it collided, let's get the rest info in unsafe advance
Transform2D ugt = get_global_transform();
- ugt.elements[2]+=p_motion*unsafe;
+ ugt.elements[2] += p_motion * unsafe;
Physics2DDirectSpaceState::ShapeRestInfo rest_info;
- bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt*get_shape_transform(best_shape), Vector2(), margin,&rest_info,exclude,get_layer_mask(),mask);
+ bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt * get_shape_transform(best_shape), Vector2(), margin, &rest_info, exclude, get_layer_mask(), mask);
if (!c2) {
//should not happen, but floating point precision is so weird..
- colliding=false;
+ colliding = false;
} else {
-
//print_line("Travel: "+rtos(travel));
- colliding=true;
- collision=rest_info.point;
- normal=rest_info.normal;
- collider=rest_info.collider_id;
- collider_vel=rest_info.linear_velocity;
- collider_shape=rest_info.shape;
- collider_metadata=rest_info.metadata;
+ colliding = true;
+ collision = rest_info.point;
+ normal = rest_info.normal;
+ collider = rest_info.collider_id;
+ collider_vel = rest_info.linear_velocity;
+ collider_shape = rest_info.shape;
+ collider_metadata = rest_info.metadata;
}
-
}
- Vector2 motion=p_motion*safe;
+ Vector2 motion = p_motion * safe;
Transform2D gt = get_global_transform();
- gt.elements[2]+=motion;
+ gt.elements[2] += motion;
set_global_transform(gt);
- return p_motion-motion;
+ return p_motion - motion;
#endif
}
+Vector2 KinematicBody2D::move_and_slide(const Vector2 &p_linear_velocity, const Vector2 &p_floor_direction, float p_slope_stop_min_velocity, int p_max_bounces) {
-
-Vector2 KinematicBody2D::move_and_slide(const Vector2& p_linear_velocity,const Vector2& p_floor_direction,float p_slope_stop_min_velocity,int p_max_bounces) {
-
- Vector2 motion = (move_and_slide_floor_velocity+p_linear_velocity)*get_fixed_process_delta_time();
+ Vector2 motion = (move_and_slide_floor_velocity + p_linear_velocity) * get_fixed_process_delta_time();
Vector2 lv = p_linear_velocity;
- move_and_slide_on_floor=false;
- move_and_slide_on_ceiling=false;
- move_and_slide_on_wall=false;
+ move_and_slide_on_floor = false;
+ move_and_slide_on_ceiling = false;
+ move_and_slide_on_wall = false;
move_and_slide_colliders.clear();
- move_and_slide_floor_velocity=Vector2();
+ move_and_slide_floor_velocity = Vector2();
- while(p_max_bounces) {
+ while (p_max_bounces) {
- motion=move(motion);
+ motion = move(motion);
if (is_colliding()) {
-
- if (p_floor_direction==Vector2()) {
+ if (p_floor_direction == Vector2()) {
//all is a wall
- move_and_slide_on_wall=true;
+ move_and_slide_on_wall = true;
} else {
- if ( get_collision_normal().dot(p_floor_direction) > Math::cos(Math::deg2rad((float)45))) { //floor
-
+ if (get_collision_normal().dot(p_floor_direction) > Math::cos(Math::deg2rad((float)45))) { //floor
- move_and_slide_on_floor=true;
- move_and_slide_floor_velocity=get_collider_velocity();
+ move_and_slide_on_floor = true;
+ move_and_slide_floor_velocity = get_collider_velocity();
- if (get_travel().length()<1 && ABS((lv.x-move_and_slide_floor_velocity.x))<p_slope_stop_min_velocity) {
+ if (get_travel().length() < 1 && ABS((lv.x - move_and_slide_floor_velocity.x)) < p_slope_stop_min_velocity) {
revert_motion();
return Vector2();
}
- } else if ( get_collision_normal().dot(p_floor_direction) < Math::cos(Math::deg2rad((float)45))) { //ceiling
- move_and_slide_on_ceiling=true;
+ } else if (get_collision_normal().dot(p_floor_direction) < Math::cos(Math::deg2rad((float)45))) { //ceiling
+ move_and_slide_on_ceiling = true;
} else {
- move_and_slide_on_wall=true;
+ move_and_slide_on_wall = true;
}
-
}
- motion=get_collision_normal().slide(motion);
- lv=get_collision_normal().slide(lv);
+ motion = get_collision_normal().slide(motion);
+ lv = get_collision_normal().slide(lv);
Variant collider = _get_collider();
- if (collider.get_type()!=Variant::NIL) {
+ if (collider.get_type() != Variant::NIL) {
move_and_slide_colliders.push_back(collider);
}
@@ -1292,7 +1217,7 @@ Vector2 KinematicBody2D::move_and_slide(const Vector2& p_linear_velocity,const V
}
p_max_bounces--;
- if (motion==Vector2())
+ if (motion == Vector2())
break;
}
@@ -1303,45 +1228,41 @@ bool KinematicBody2D::is_move_and_slide_on_floor() const {
return move_and_slide_on_floor;
}
-bool KinematicBody2D::is_move_and_slide_on_wall() const{
+bool KinematicBody2D::is_move_and_slide_on_wall() const {
return move_and_slide_on_wall;
}
-bool KinematicBody2D::is_move_and_slide_on_ceiling() const{
+bool KinematicBody2D::is_move_and_slide_on_ceiling() const {
return move_and_slide_on_ceiling;
}
-Array KinematicBody2D::get_move_and_slide_colliders() const{
+Array KinematicBody2D::get_move_and_slide_colliders() const {
return move_and_slide_colliders;
}
-Vector2 KinematicBody2D::move_to(const Vector2& p_position) {
+Vector2 KinematicBody2D::move_to(const Vector2 &p_position) {
- return move(p_position-get_global_position());
+ return move(p_position - get_global_position());
}
-bool KinematicBody2D::test_move(const Transform2D& p_from,const Vector2& p_motion) {
-
- ERR_FAIL_COND_V(!is_inside_tree(),false);
-
- return Physics2DServer::get_singleton()->body_test_motion(get_rid(),p_from,p_motion,margin);
+bool KinematicBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion) {
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
+ return Physics2DServer::get_singleton()->body_test_motion(get_rid(), p_from, p_motion, margin);
}
Vector2 KinematicBody2D::get_collision_pos() const {
- ERR_FAIL_COND_V(!colliding,Vector2());
+ ERR_FAIL_COND_V(!colliding, Vector2());
return collision;
-
}
Vector2 KinematicBody2D::get_collision_normal() const {
- ERR_FAIL_COND_V(!colliding,Vector2());
+ ERR_FAIL_COND_V(!colliding, Vector2());
return normal;
-
}
Vector2 KinematicBody2D::get_collider_velocity() const {
@@ -1351,88 +1272,79 @@ Vector2 KinematicBody2D::get_collider_velocity() const {
ObjectID KinematicBody2D::get_collider() const {
- ERR_FAIL_COND_V(!colliding,0);
+ ERR_FAIL_COND_V(!colliding, 0);
return collider;
}
-
int KinematicBody2D::get_collider_shape() const {
- ERR_FAIL_COND_V(!colliding,0);
+ ERR_FAIL_COND_V(!colliding, 0);
return collider_shape;
}
Variant KinematicBody2D::get_collider_metadata() const {
- ERR_FAIL_COND_V(!colliding,0);
+ ERR_FAIL_COND_V(!colliding, 0);
return collider_metadata;
-
}
-
-bool KinematicBody2D::is_colliding() const{
+bool KinematicBody2D::is_colliding() const {
return colliding;
}
void KinematicBody2D::set_collision_margin(float p_margin) {
- margin=p_margin;
+ margin = p_margin;
}
-float KinematicBody2D::get_collision_margin() const{
+float KinematicBody2D::get_collision_margin() const {
return margin;
}
void KinematicBody2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("move", "rel_vec"), &KinematicBody2D::move);
+ ClassDB::bind_method(D_METHOD("move_to", "position"), &KinematicBody2D::move_to);
+ ClassDB::bind_method(D_METHOD("move_and_slide", "linear_velocity", "floor_normal", "slope_stop_min_velocity", "max_bounces"), &KinematicBody2D::move_and_slide, DEFVAL(Vector2(0, 0)), DEFVAL(5), DEFVAL(4));
- ClassDB::bind_method(D_METHOD("move","rel_vec"),&KinematicBody2D::move);
- ClassDB::bind_method(D_METHOD("move_to","position"),&KinematicBody2D::move_to);
- ClassDB::bind_method(D_METHOD("move_and_slide","linear_velocity","floor_normal","slope_stop_min_velocity","max_bounces"),&KinematicBody2D::move_and_slide,DEFVAL(Vector2(0,0)),DEFVAL(5),DEFVAL(4));
-
- ClassDB::bind_method(D_METHOD("test_move","from","rel_vec"),&KinematicBody2D::test_move);
- ClassDB::bind_method(D_METHOD("get_travel"),&KinematicBody2D::get_travel);
- ClassDB::bind_method(D_METHOD("revert_motion"),&KinematicBody2D::revert_motion);
-
- ClassDB::bind_method(D_METHOD("is_colliding"),&KinematicBody2D::is_colliding);
+ ClassDB::bind_method(D_METHOD("test_move", "from", "rel_vec"), &KinematicBody2D::test_move);
+ ClassDB::bind_method(D_METHOD("get_travel"), &KinematicBody2D::get_travel);
+ ClassDB::bind_method(D_METHOD("revert_motion"), &KinematicBody2D::revert_motion);
- ClassDB::bind_method(D_METHOD("get_collision_pos"),&KinematicBody2D::get_collision_pos);
- ClassDB::bind_method(D_METHOD("get_collision_normal"),&KinematicBody2D::get_collision_normal);
- ClassDB::bind_method(D_METHOD("get_collider_velocity"),&KinematicBody2D::get_collider_velocity);
- ClassDB::bind_method(D_METHOD("get_collider:Variant"),&KinematicBody2D::_get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_shape"),&KinematicBody2D::get_collider_shape);
- ClassDB::bind_method(D_METHOD("get_collider_metadata:Variant"),&KinematicBody2D::get_collider_metadata);
- ClassDB::bind_method(D_METHOD("get_move_and_slide_colliders"),&KinematicBody2D::get_move_and_slide_colliders);
- ClassDB::bind_method(D_METHOD("is_move_and_slide_on_floor"),&KinematicBody2D::is_move_and_slide_on_floor);
- ClassDB::bind_method(D_METHOD("is_move_and_slide_on_ceiling"),&KinematicBody2D::is_move_and_slide_on_ceiling);
- ClassDB::bind_method(D_METHOD("is_move_and_slide_on_wall"),&KinematicBody2D::is_move_and_slide_on_wall);
+ ClassDB::bind_method(D_METHOD("is_colliding"), &KinematicBody2D::is_colliding);
- ClassDB::bind_method(D_METHOD("set_collision_margin","pixels"),&KinematicBody2D::set_collision_margin);
- ClassDB::bind_method(D_METHOD("get_collision_margin","pixels"),&KinematicBody2D::get_collision_margin);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision/margin",PROPERTY_HINT_RANGE,"0.001,256,0.001"),"set_collision_margin","get_collision_margin");
+ ClassDB::bind_method(D_METHOD("get_collision_pos"), &KinematicBody2D::get_collision_pos);
+ ClassDB::bind_method(D_METHOD("get_collision_normal"), &KinematicBody2D::get_collision_normal);
+ ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicBody2D::get_collider_velocity);
+ ClassDB::bind_method(D_METHOD("get_collider:Variant"), &KinematicBody2D::_get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicBody2D::get_collider_shape);
+ ClassDB::bind_method(D_METHOD("get_collider_metadata:Variant"), &KinematicBody2D::get_collider_metadata);
+ ClassDB::bind_method(D_METHOD("get_move_and_slide_colliders"), &KinematicBody2D::get_move_and_slide_colliders);
+ ClassDB::bind_method(D_METHOD("is_move_and_slide_on_floor"), &KinematicBody2D::is_move_and_slide_on_floor);
+ ClassDB::bind_method(D_METHOD("is_move_and_slide_on_ceiling"), &KinematicBody2D::is_move_and_slide_on_ceiling);
+ ClassDB::bind_method(D_METHOD("is_move_and_slide_on_wall"), &KinematicBody2D::is_move_and_slide_on_wall);
+ ClassDB::bind_method(D_METHOD("set_collision_margin", "pixels"), &KinematicBody2D::set_collision_margin);
+ ClassDB::bind_method(D_METHOD("get_collision_margin", "pixels"), &KinematicBody2D::get_collision_margin);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision/margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_collision_margin", "get_collision_margin");
}
-KinematicBody2D::KinematicBody2D() : PhysicsBody2D(Physics2DServer::BODY_MODE_KINEMATIC){
-
- colliding=false;
- collider=0;
+KinematicBody2D::KinematicBody2D()
+ : PhysicsBody2D(Physics2DServer::BODY_MODE_KINEMATIC) {
- collider_shape=0;
+ colliding = false;
+ collider = 0;
- margin=0.08;
+ collider_shape = 0;
- move_and_slide_on_floor=false;
- move_and_slide_on_ceiling=false;
- move_and_slide_on_wall=false;
+ margin = 0.08;
+ move_and_slide_on_floor = false;
+ move_and_slide_on_ceiling = false;
+ move_and_slide_on_wall = false;
}
-KinematicBody2D::~KinematicBody2D() {
-
-
+KinematicBody2D::~KinematicBody2D() {
}
-
diff --git a/scene/2d/physics_body_2d.h b/scene/2d/physics_body_2d.h
index 5b7db35fe8..e51b512302 100644
--- a/scene/2d/physics_body_2d.h
+++ b/scene/2d/physics_body_2d.h
@@ -33,57 +33,52 @@
#include "servers/physics_2d_server.h"
#include "vset.h"
-
class PhysicsBody2D : public CollisionObject2D {
- GDCLASS(PhysicsBody2D,CollisionObject2D);
+ GDCLASS(PhysicsBody2D, CollisionObject2D);
uint32_t mask;
uint32_t collision_mask;
Vector2 one_way_collision_direction;
float one_way_collision_max_depth;
-
void _set_layers(uint32_t p_mask);
uint32_t _get_layers() const;
protected:
-
void _notification(int p_what);
PhysicsBody2D(Physics2DServer::BodyMode p_mode);
static void _bind_methods();
-public:
+public:
void set_collision_layer(uint32_t p_mask);
uint32_t get_collision_layer() const;
void set_collision_mask(uint32_t p_mask);
uint32_t get_collision_mask() const;
-
void set_collision_mask_bit(int p_bit, bool p_value);
bool get_collision_mask_bit(int p_bit) const;
void set_collision_layer_bit(int p_bit, bool p_value);
bool get_collision_layer_bit(int p_bit) const;
- void add_collision_exception_with(Node* p_node); //must be physicsbody
- void remove_collision_exception_with(Node* p_node);
+ void add_collision_exception_with(Node *p_node); //must be physicsbody
+ void remove_collision_exception_with(Node *p_node);
- void set_one_way_collision_direction(const Vector2& p_dir);
+ void set_one_way_collision_direction(const Vector2 &p_dir);
Vector2 get_one_way_collision_direction() const;
void set_one_way_collision_max_depth(float p_dir);
float get_one_way_collision_max_depth() const;
PhysicsBody2D();
-
};
class StaticBody2D : public PhysicsBody2D {
- GDCLASS(StaticBody2D,PhysicsBody2D);
+ GDCLASS(StaticBody2D, PhysicsBody2D);
Vector2 constant_linear_velocity;
real_t constant_angular_velocity;
@@ -91,21 +86,17 @@ class StaticBody2D : public PhysicsBody2D {
real_t bounce;
real_t friction;
-
protected:
-
static void _bind_methods();
public:
-
void set_friction(real_t p_friction);
real_t get_friction() const;
void set_bounce(real_t p_bounce);
real_t get_bounce() const;
-
- void set_constant_linear_velocity(const Vector2& p_vel);
+ void set_constant_linear_velocity(const Vector2 &p_vel);
void set_constant_angular_velocity(real_t p_vel);
Vector2 get_constant_linear_velocity() const;
@@ -113,14 +104,13 @@ public:
StaticBody2D();
~StaticBody2D();
-
};
class RigidBody2D : public PhysicsBody2D {
- GDCLASS(RigidBody2D,PhysicsBody2D);
-public:
+ GDCLASS(RigidBody2D, PhysicsBody2D);
+public:
enum Mode {
MODE_RIGID,
MODE_STATIC,
@@ -135,7 +125,6 @@ public:
};
private:
-
bool can_sleep;
Physics2DDirectBodyState *state;
Mode mode;
@@ -151,35 +140,34 @@ private:
real_t angular_velocity;
bool sleeping;
-
int max_contacts_reported;
bool custom_integrator;
CCDMode ccd_mode;
-
struct ShapePair {
int body_shape;
int local_shape;
bool tagged;
- bool operator<(const ShapePair& p_sp) const {
- if (body_shape==p_sp.body_shape)
+ bool operator<(const ShapePair &p_sp) const {
+ if (body_shape == p_sp.body_shape)
return local_shape < p_sp.local_shape;
else
return body_shape < p_sp.body_shape;
}
ShapePair() {}
- ShapePair(int p_bs, int p_ls) { body_shape=p_bs; local_shape=p_ls; }
+ ShapePair(int p_bs, int p_ls) {
+ body_shape = p_bs;
+ local_shape = p_ls;
+ }
};
struct RigidBody2D_RemoveAction {
-
ObjectID body_id;
ShapePair pair;
-
};
struct BodyState {
@@ -191,26 +179,22 @@ private:
struct ContactMonitor {
bool locked;
- Map<ObjectID,BodyState> body_map;
-
+ Map<ObjectID, BodyState> body_map;
};
-
ContactMonitor *contact_monitor;
void _body_enter_tree(ObjectID p_id);
void _body_exit_tree(ObjectID p_id);
-
- void _body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape);
+ void _body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape);
void _direct_state_changed(Object *p_state);
- bool _test_motion(const Vector2& p_motion,float p_margin=0.08,const Ref<Physics2DTestMotionResult>& p_result=Ref<Physics2DTestMotionResult>());
+ bool _test_motion(const Vector2 &p_motion, float p_margin = 0.08, const Ref<Physics2DTestMotionResult> &p_result = Ref<Physics2DTestMotionResult>());
protected:
-
static void _bind_methods();
-public:
+public:
void set_mode(Mode p_mode);
Mode get_mode() const;
@@ -238,10 +222,10 @@ public:
void set_angular_damp(real_t p_angular_damp);
real_t get_angular_damp() const;
- void set_linear_velocity(const Vector2& p_velocity);
+ void set_linear_velocity(const Vector2 &p_velocity);
Vector2 get_linear_velocity() const;
- void set_axis_velocity(const Vector2& p_axis);
+ void set_axis_velocity(const Vector2 &p_axis);
void set_angular_velocity(real_t p_velocity);
real_t get_angular_velocity() const;
@@ -264,33 +248,28 @@ public:
void set_continuous_collision_detection_mode(CCDMode p_mode);
CCDMode get_continuous_collision_detection_mode() const;
- void apply_impulse(const Vector2& p_offset, const Vector2& p_impulse);
+ void apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse);
- void set_applied_force(const Vector2& p_force);
+ void set_applied_force(const Vector2 &p_force);
Vector2 get_applied_force() const;
void set_applied_torque(const float p_torque);
float get_applied_torque() const;
- void add_force(const Vector2& p_offset, const Vector2& p_force);
-
-
+ void add_force(const Vector2 &p_offset, const Vector2 &p_force);
Array get_colliding_bodies() const; //function for script
RigidBody2D();
~RigidBody2D();
-
};
VARIANT_ENUM_CAST(RigidBody2D::Mode);
VARIANT_ENUM_CAST(RigidBody2D::CCDMode);
-
-
class KinematicBody2D : public PhysicsBody2D {
- GDCLASS(KinematicBody2D,PhysicsBody2D);
+ GDCLASS(KinematicBody2D, PhysicsBody2D);
float margin;
bool colliding;
@@ -311,15 +290,15 @@ class KinematicBody2D : public PhysicsBody2D {
Variant _get_collider() const;
_FORCE_INLINE_ bool _ignores_mode(Physics2DServer::BodyMode) const;
-protected:
+protected:
static void _bind_methods();
-public:
- Vector2 move(const Vector2& p_motion);
- Vector2 move_to(const Vector2& p_position);
+public:
+ Vector2 move(const Vector2 &p_motion);
+ Vector2 move_to(const Vector2 &p_position);
- bool test_move(const Transform2D &p_from, const Vector2& p_motion);
+ bool test_move(const Transform2D &p_from, const Vector2 &p_motion);
bool is_colliding() const;
Vector2 get_travel() const;
@@ -335,17 +314,14 @@ public:
void set_collision_margin(float p_margin);
float get_collision_margin() const;
- Vector2 move_and_slide(const Vector2& p_linear_velocity, const Vector2& p_floor_direction=Vector2(0,0), float p_slope_stop_min_velocity=5, int p_max_bounces=4);
+ Vector2 move_and_slide(const Vector2 &p_linear_velocity, const Vector2 &p_floor_direction = Vector2(0, 0), float p_slope_stop_min_velocity = 5, int p_max_bounces = 4);
bool is_move_and_slide_on_floor() const;
bool is_move_and_slide_on_wall() const;
bool is_move_and_slide_on_ceiling() const;
Array get_move_and_slide_colliders() const;
-
KinematicBody2D();
~KinematicBody2D();
-
};
-
#endif // PHYSICS_BODY_2D_H
diff --git a/scene/2d/polygon_2d.cpp b/scene/2d/polygon_2d.cpp
index ec6729844b..1d54fd1538 100644
--- a/scene/2d/polygon_2d.cpp
+++ b/scene/2d/polygon_2d.cpp
@@ -30,29 +30,25 @@
Rect2 Polygon2D::get_item_rect() const {
-
- if (rect_cache_dirty){
- int l =polygon.size();
+ if (rect_cache_dirty) {
+ int l = polygon.size();
PoolVector<Vector2>::Read r = polygon.read();
- item_rect=Rect2();
- for(int i=0;i<l;i++) {
+ item_rect = Rect2();
+ for (int i = 0; i < l; i++) {
Vector2 pos = r[i] + offset;
- if (i==0)
- item_rect.pos=pos;
+ if (i == 0)
+ item_rect.pos = pos;
else
item_rect.expand_to(pos);
}
- item_rect=item_rect.grow(20);
- rect_cache_dirty=false;
+ item_rect = item_rect.grow(20);
+ rect_cache_dirty = false;
}
-
return item_rect;
-
-
}
-void Polygon2D::edit_set_pivot(const Point2& p_pivot) {
+void Polygon2D::edit_set_pivot(const Point2 &p_pivot) {
set_offset(p_pivot);
}
@@ -68,12 +64,11 @@ bool Polygon2D::edit_has_pivot() const {
void Polygon2D::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
- if (polygon.size()<3)
+ if (polygon.size() < 3)
return;
Vector<Vector2> points;
@@ -84,162 +79,155 @@ void Polygon2D::_notification(int p_what) {
int len = points.size();
{
- PoolVector<Vector2>::Read polyr =polygon.read();
- for(int i=0;i<len;i++) {
- points[i]=polyr[i]+offset;
+ PoolVector<Vector2>::Read polyr = polygon.read();
+ for (int i = 0; i < len; i++) {
+ points[i] = polyr[i] + offset;
}
}
if (invert) {
Rect2 bounds;
- int highest_idx=-1;
- float highest_y=-1e20;
- float sum=0;
+ int highest_idx = -1;
+ float highest_y = -1e20;
+ float sum = 0;
- for(int i=0;i<len;i++) {
- if (i==0)
- bounds.pos=points[i];
+ for (int i = 0; i < len; i++) {
+ if (i == 0)
+ bounds.pos = points[i];
else
bounds.expand_to(points[i]);
- if (points[i].y>highest_y) {
- highest_idx=i;
- highest_y=points[i].y;
+ if (points[i].y > highest_y) {
+ highest_idx = i;
+ highest_y = points[i].y;
}
- int ni=(i+1)%len;
- sum+=(points[ni].x-points[i].x)*(points[ni].y+points[i].y);
+ int ni = (i + 1) % len;
+ sum += (points[ni].x - points[i].x) * (points[ni].y + points[i].y);
}
- bounds=bounds.grow(invert_border);
+ bounds = bounds.grow(invert_border);
- Vector2 ep[7]={
- Vector2(points[highest_idx].x,points[highest_idx].y+invert_border),
- Vector2(bounds.pos+bounds.size),
- Vector2(bounds.pos+Vector2(bounds.size.x,0)),
+ Vector2 ep[7] = {
+ Vector2(points[highest_idx].x, points[highest_idx].y + invert_border),
+ Vector2(bounds.pos + bounds.size),
+ Vector2(bounds.pos + Vector2(bounds.size.x, 0)),
Vector2(bounds.pos),
- Vector2(bounds.pos+Vector2(0,bounds.size.y)),
- Vector2(points[highest_idx].x-CMP_EPSILON,points[highest_idx].y+invert_border),
- Vector2(points[highest_idx].x-CMP_EPSILON,points[highest_idx].y),
+ Vector2(bounds.pos + Vector2(0, bounds.size.y)),
+ Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y + invert_border),
+ Vector2(points[highest_idx].x - CMP_EPSILON, points[highest_idx].y),
};
-
- if (sum>0) {
- SWAP(ep[1],ep[4]);
- SWAP(ep[2],ep[3]);
- SWAP(ep[5],ep[0]);
- SWAP(ep[6],points[highest_idx]);
+ if (sum > 0) {
+ SWAP(ep[1], ep[4]);
+ SWAP(ep[2], ep[3]);
+ SWAP(ep[5], ep[0]);
+ SWAP(ep[6], points[highest_idx]);
}
- points.resize(points.size()+7);
- for(int i=points.size()-1;i>=highest_idx+7;i--) {
+ points.resize(points.size() + 7);
+ for (int i = points.size() - 1; i >= highest_idx + 7; i--) {
- points[i]=points[i-7];
+ points[i] = points[i - 7];
}
- for(int i=0;i<7;i++) {
+ for (int i = 0; i < 7; i++) {
- points[highest_idx+i+1]=ep[i];
+ points[highest_idx + i + 1] = ep[i];
}
-
- len=points.size();
-
+ len = points.size();
}
if (texture.is_valid()) {
- Transform2D texmat(tex_rot,tex_ofs);
+ Transform2D texmat(tex_rot, tex_ofs);
texmat.scale(tex_scale);
- Size2 tex_size=Vector2(1,1);
+ Size2 tex_size = Vector2(1, 1);
- tex_size=texture->get_size();
+ tex_size = texture->get_size();
uvs.resize(points.size());
- if (points.size()==uv.size()) {
+ if (points.size() == uv.size()) {
PoolVector<Vector2>::Read uvr = uv.read();
- for(int i=0;i<len;i++) {
- uvs[i]=texmat.xform(uvr[i])/tex_size;
+ for (int i = 0; i < len; i++) {
+ uvs[i] = texmat.xform(uvr[i]) / tex_size;
}
} else {
- for(int i=0;i<len;i++) {
- uvs[i]=texmat.xform(points[i])/tex_size;
+ for (int i = 0; i < len; i++) {
+ uvs[i] = texmat.xform(points[i]) / tex_size;
}
}
-
}
-
Vector<Color> colors;
- int color_len=vertex_colors.size();
+ int color_len = vertex_colors.size();
colors.resize(len);
{
- PoolVector<Color>::Read color_r=vertex_colors.read();
- for(int i=0;i<color_len && i<len;i++){
- colors[i]=color_r[i];
+ PoolVector<Color>::Read color_r = vertex_colors.read();
+ for (int i = 0; i < color_len && i < len; i++) {
+ colors[i] = color_r[i];
}
- for(int i=color_len;i<len;i++){
- colors[i]=color;
+ for (int i = color_len; i < len; i++) {
+ colors[i] = color;
}
}
Vector<int> indices = Geometry::triangulate_polygon(points);
- VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(),indices,points,colors,uvs,texture.is_valid()?texture->get_rid():RID());
+ VS::get_singleton()->canvas_item_add_triangle_array(get_canvas_item(), indices, points, colors, uvs, texture.is_valid() ? texture->get_rid() : RID());
} break;
}
}
-
-void Polygon2D::set_polygon(const PoolVector<Vector2>& p_polygon) {
- polygon=p_polygon;
- rect_cache_dirty=true;
+void Polygon2D::set_polygon(const PoolVector<Vector2> &p_polygon) {
+ polygon = p_polygon;
+ rect_cache_dirty = true;
update();
}
-PoolVector<Vector2> Polygon2D::get_polygon() const{
+PoolVector<Vector2> Polygon2D::get_polygon() const {
return polygon;
}
+void Polygon2D::set_uv(const PoolVector<Vector2> &p_uv) {
-void Polygon2D::set_uv(const PoolVector<Vector2>& p_uv) {
-
- uv=p_uv;
+ uv = p_uv;
update();
}
-PoolVector<Vector2> Polygon2D::get_uv() const{
+PoolVector<Vector2> Polygon2D::get_uv() const {
return uv;
}
-void Polygon2D::set_color(const Color& p_color){
+void Polygon2D::set_color(const Color &p_color) {
- color=p_color;
+ color = p_color;
update();
}
-Color Polygon2D::get_color() const{
+Color Polygon2D::get_color() const {
return color;
}
-void Polygon2D::set_vertex_colors(const PoolVector<Color>& p_colors){
+void Polygon2D::set_vertex_colors(const PoolVector<Color> &p_colors) {
- vertex_colors=p_colors;
+ vertex_colors = p_colors;
update();
}
-PoolVector<Color> Polygon2D::get_vertex_colors() const{
+PoolVector<Color> Polygon2D::get_vertex_colors() const {
return vertex_colors;
}
-void Polygon2D::set_texture(const Ref<Texture>& p_texture){
+void Polygon2D::set_texture(const Ref<Texture> &p_texture) {
- texture=p_texture;
+ texture = p_texture;
/*if (texture.is_valid()) {
uint32_t flags=texture->get_flags();
@@ -251,77 +239,74 @@ void Polygon2D::set_texture(const Ref<Texture>& p_texture){
}*/
update();
}
-Ref<Texture> Polygon2D::get_texture() const{
+Ref<Texture> Polygon2D::get_texture() const {
return texture;
}
+void Polygon2D::set_texture_offset(const Vector2 &p_offset) {
-void Polygon2D::set_texture_offset(const Vector2& p_offset){
-
- tex_ofs=p_offset;
+ tex_ofs = p_offset;
update();
}
-Vector2 Polygon2D::get_texture_offset() const{
+Vector2 Polygon2D::get_texture_offset() const {
return tex_ofs;
}
-void Polygon2D::set_texture_rotation(float p_rot){
+void Polygon2D::set_texture_rotation(float p_rot) {
- tex_rot=p_rot;
+ tex_rot = p_rot;
update();
}
-float Polygon2D::get_texture_rotation() const{
+float Polygon2D::get_texture_rotation() const {
return tex_rot;
}
-
-void Polygon2D::_set_texture_rotationd(float p_rot){
+void Polygon2D::_set_texture_rotationd(float p_rot) {
set_texture_rotation(Math::deg2rad(p_rot));
}
-float Polygon2D::_get_texture_rotationd() const{
+float Polygon2D::_get_texture_rotationd() const {
return Math::rad2deg(get_texture_rotation());
}
+void Polygon2D::set_texture_scale(const Size2 &p_scale) {
-void Polygon2D::set_texture_scale(const Size2& p_scale){
-
- tex_scale=p_scale;
+ tex_scale = p_scale;
update();
}
-Size2 Polygon2D::get_texture_scale() const{
+Size2 Polygon2D::get_texture_scale() const {
return tex_scale;
}
-void Polygon2D::set_invert(bool p_invert){
+void Polygon2D::set_invert(bool p_invert) {
- invert=p_invert;
+ invert = p_invert;
update();
}
-bool Polygon2D::get_invert() const{
+bool Polygon2D::get_invert() const {
return invert;
}
-void Polygon2D::set_invert_border(float p_invert_border){
+void Polygon2D::set_invert_border(float p_invert_border) {
- invert_border=p_invert_border;
+ invert_border = p_invert_border;
update();
}
-float Polygon2D::get_invert_border() const{
+float Polygon2D::get_invert_border() const {
return invert_border;
}
-void Polygon2D::set_offset(const Vector2& p_offset) {
+void Polygon2D::set_offset(const Vector2 &p_offset) {
- offset=p_offset;
- rect_cache_dirty=true;
+ offset = p_offset;
+ rect_cache_dirty = true;
update();
}
@@ -330,73 +315,68 @@ Vector2 Polygon2D::get_offset() const {
return offset;
}
-
void Polygon2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&Polygon2D::set_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon"),&Polygon2D::get_polygon);
-
- ClassDB::bind_method(D_METHOD("set_uv","uv"),&Polygon2D::set_uv);
- ClassDB::bind_method(D_METHOD("get_uv"),&Polygon2D::get_uv);
-
- ClassDB::bind_method(D_METHOD("set_color","color"),&Polygon2D::set_color);
- ClassDB::bind_method(D_METHOD("get_color"),&Polygon2D::get_color);
-
- ClassDB::bind_method(D_METHOD("set_vertex_colors","vertex_colors"),&Polygon2D::set_vertex_colors);
- ClassDB::bind_method(D_METHOD("get_vertex_colors"),&Polygon2D::get_vertex_colors);
-
- ClassDB::bind_method(D_METHOD("set_texture","texture"),&Polygon2D::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture"),&Polygon2D::get_texture);
+ ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &Polygon2D::set_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon"), &Polygon2D::get_polygon);
- ClassDB::bind_method(D_METHOD("set_texture_offset","texture_offset"),&Polygon2D::set_texture_offset);
- ClassDB::bind_method(D_METHOD("get_texture_offset"),&Polygon2D::get_texture_offset);
+ ClassDB::bind_method(D_METHOD("set_uv", "uv"), &Polygon2D::set_uv);
+ ClassDB::bind_method(D_METHOD("get_uv"), &Polygon2D::get_uv);
- ClassDB::bind_method(D_METHOD("set_texture_rotation","texture_rotation"),&Polygon2D::set_texture_rotation);
- ClassDB::bind_method(D_METHOD("get_texture_rotation"),&Polygon2D::get_texture_rotation);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &Polygon2D::set_color);
+ ClassDB::bind_method(D_METHOD("get_color"), &Polygon2D::get_color);
- ClassDB::bind_method(D_METHOD("_set_texture_rotationd","texture_rotation"),&Polygon2D::_set_texture_rotationd);
- ClassDB::bind_method(D_METHOD("_get_texture_rotationd"),&Polygon2D::_get_texture_rotationd);
+ ClassDB::bind_method(D_METHOD("set_vertex_colors", "vertex_colors"), &Polygon2D::set_vertex_colors);
+ ClassDB::bind_method(D_METHOD("get_vertex_colors"), &Polygon2D::get_vertex_colors);
- ClassDB::bind_method(D_METHOD("set_texture_scale","texture_scale"),&Polygon2D::set_texture_scale);
- ClassDB::bind_method(D_METHOD("get_texture_scale"),&Polygon2D::get_texture_scale);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &Polygon2D::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &Polygon2D::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture_offset", "texture_offset"), &Polygon2D::set_texture_offset);
+ ClassDB::bind_method(D_METHOD("get_texture_offset"), &Polygon2D::get_texture_offset);
- ClassDB::bind_method(D_METHOD("set_invert","invert"),&Polygon2D::set_invert);
- ClassDB::bind_method(D_METHOD("get_invert"),&Polygon2D::get_invert);
+ ClassDB::bind_method(D_METHOD("set_texture_rotation", "texture_rotation"), &Polygon2D::set_texture_rotation);
+ ClassDB::bind_method(D_METHOD("get_texture_rotation"), &Polygon2D::get_texture_rotation);
- ClassDB::bind_method(D_METHOD("set_invert_border","invert_border"),&Polygon2D::set_invert_border);
- ClassDB::bind_method(D_METHOD("get_invert_border"),&Polygon2D::get_invert_border);
+ ClassDB::bind_method(D_METHOD("_set_texture_rotationd", "texture_rotation"), &Polygon2D::_set_texture_rotationd);
+ ClassDB::bind_method(D_METHOD("_get_texture_rotationd"), &Polygon2D::_get_texture_rotationd);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&Polygon2D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&Polygon2D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_texture_scale", "texture_scale"), &Polygon2D::set_texture_scale);
+ ClassDB::bind_method(D_METHOD("get_texture_scale"), &Polygon2D::get_texture_scale);
+ ClassDB::bind_method(D_METHOD("set_invert", "invert"), &Polygon2D::set_invert);
+ ClassDB::bind_method(D_METHOD("get_invert"), &Polygon2D::get_invert);
+ ClassDB::bind_method(D_METHOD("set_invert_border", "invert_border"), &Polygon2D::set_invert_border);
+ ClassDB::bind_method(D_METHOD("get_invert_border"), &Polygon2D::get_invert_border);
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon");
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"uv"),"set_uv","get_uv");
- ADD_PROPERTY( PropertyInfo(Variant::COLOR,"color"),"set_color","get_color");
- ADD_PROPERTY( PropertyInfo(Variant::POOL_COLOR_ARRAY,"vertex_colors"),"set_vertex_colors","get_vertex_colors");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"offset"),"set_offset","get_offset");
- ADD_GROUP("Texture","");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture");
- ADD_GROUP("Texture","texture_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"texture_offset"),"set_texture_offset","get_texture_offset");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"texture_scale"),"set_texture_scale","get_texture_scale");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"texture_rotation",PROPERTY_HINT_RANGE,"-1440,1440,0.1"),"_set_texture_rotationd","_get_texture_rotationd");
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Polygon2D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Polygon2D::get_offset);
- ADD_GROUP("Invert","invert_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"invert_enable"),"set_invert","get_invert");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"invert_border",PROPERTY_HINT_RANGE,"0.1,16384,0.1"),"set_invert_border","get_invert_border");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "uv"), "set_uv", "get_uv");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY, "vertex_colors"), "set_vertex_colors", "get_vertex_colors");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_GROUP("Texture", "");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_GROUP("Texture", "texture_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "texture_offset"), "set_texture_offset", "get_texture_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "texture_scale"), "set_texture_scale", "get_texture_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "texture_rotation", PROPERTY_HINT_RANGE, "-1440,1440,0.1"), "_set_texture_rotationd", "_get_texture_rotationd");
+ ADD_GROUP("Invert", "invert_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "invert_enable"), "set_invert", "get_invert");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "invert_border", PROPERTY_HINT_RANGE, "0.1,16384,0.1"), "set_invert_border", "get_invert_border");
}
Polygon2D::Polygon2D() {
- invert=0;
- invert_border=100;
- tex_rot=0;
- tex_tile=true;
- tex_scale=Vector2(1,1);
- color=Color(1,1,1);
- rect_cache_dirty=true;
+ invert = 0;
+ invert_border = 100;
+ tex_rot = 0;
+ tex_tile = true;
+ tex_scale = Vector2(1, 1);
+ color = Color(1, 1, 1);
+ rect_cache_dirty = true;
}
diff --git a/scene/2d/polygon_2d.h b/scene/2d/polygon_2d.h
index 8434dae40c..50968f3de4 100644
--- a/scene/2d/polygon_2d.h
+++ b/scene/2d/polygon_2d.h
@@ -33,7 +33,7 @@
class Polygon2D : public Node2D {
- GDCLASS(Polygon2D,Node2D);
+ GDCLASS(Polygon2D, Node2D);
PoolVector<Vector2> polygon;
PoolVector<Vector2> uv;
@@ -55,33 +55,32 @@ class Polygon2D : public Node2D {
float _get_texture_rotationd() const;
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_polygon(const PoolVector<Vector2>& p_polygon);
+public:
+ void set_polygon(const PoolVector<Vector2> &p_polygon);
PoolVector<Vector2> get_polygon() const;
- void set_uv(const PoolVector<Vector2>& p_uv);
+ void set_uv(const PoolVector<Vector2> &p_uv);
PoolVector<Vector2> get_uv() const;
- void set_color(const Color& p_color);
+ void set_color(const Color &p_color);
Color get_color() const;
- void set_vertex_colors(const PoolVector<Color>& p_colors);
+ void set_vertex_colors(const PoolVector<Color> &p_colors);
PoolVector<Color> get_vertex_colors() const;
- void set_texture(const Ref<Texture>& p_texture);
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
- void set_texture_offset(const Vector2& p_offset);
+ void set_texture_offset(const Vector2 &p_offset);
Vector2 get_texture_offset() const;
void set_texture_rotation(float p_rot);
float get_texture_rotation() const;
- void set_texture_scale(const Size2& p_scale);
+ void set_texture_scale(const Size2 &p_scale);
Size2 get_texture_scale() const;
void set_invert(bool p_rot);
@@ -90,12 +89,12 @@ public:
void set_invert_border(float p_border);
float get_invert_border() const;
- void set_offset(const Vector2& p_offset);
+ void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
//editor stuff
- virtual void edit_set_pivot(const Point2& p_pivot);
+ virtual void edit_set_pivot(const Point2 &p_pivot);
virtual Point2 edit_get_pivot() const;
virtual bool edit_has_pivot() const;
diff --git a/scene/2d/position_2d.cpp b/scene/2d/position_2d.cpp
index a25be18cb9..39fc6352e9 100644
--- a/scene/2d/position_2d.cpp
+++ b/scene/2d/position_2d.cpp
@@ -31,19 +31,18 @@
void Position2D::_draw_cross() {
- draw_line(Point2(-10,0),Point2(+10,0),Color(1,0.5,0.5));
- draw_line(Point2(0,-10),Point2(0,+10),Color(0.5,1,0.5));
-
+ draw_line(Point2(-10, 0), Point2(+10, 0), Color(1, 0.5, 0.5));
+ draw_line(Point2(0, -10), Point2(0, +10), Color(0.5, 1, 0.5));
}
Rect2 Position2D::get_item_rect() const {
- return Rect2(Point2(-10,-10),Size2(20,20));
+ return Rect2(Point2(-10, -10), Size2(20, 20));
}
void Position2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -57,9 +56,7 @@ void Position2D::_notification(int p_what) {
} break;
}
-
}
-Position2D::Position2D()
-{
+Position2D::Position2D() {
}
diff --git a/scene/2d/position_2d.h b/scene/2d/position_2d.h
index fb68c265b3..a9ead3d87f 100644
--- a/scene/2d/position_2d.h
+++ b/scene/2d/position_2d.h
@@ -29,19 +29,18 @@
#ifndef POSITION_2D_H
#define POSITION_2D_H
-
#include "scene/2d/node_2d.h"
class Position2D : public Node2D {
- GDCLASS(Position2D,Node2D)
+ GDCLASS(Position2D, Node2D)
void _draw_cross();
-protected:
+protected:
void _notification(int p_what);
-public:
+public:
virtual Rect2 get_item_rect() const;
Position2D();
};
diff --git a/scene/2d/ray_cast_2d.cpp b/scene/2d/ray_cast_2d.cpp
index 72247811dc..83a0717acf 100644
--- a/scene/2d/ray_cast_2d.cpp
+++ b/scene/2d/ray_cast_2d.cpp
@@ -27,26 +27,25 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "ray_cast_2d.h"
-#include "servers/physics_2d_server.h"
#include "collision_object_2d.h"
#include "physics_body_2d.h"
+#include "servers/physics_2d_server.h"
-void RayCast2D::set_cast_to(const Vector2& p_point) {
+void RayCast2D::set_cast_to(const Vector2 &p_point) {
- cast_to=p_point;
+ cast_to = p_point;
if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_collisions_hint()))
update();
-
}
-Vector2 RayCast2D::get_cast_to() const{
+Vector2 RayCast2D::get_cast_to() const {
return cast_to;
}
void RayCast2D::set_layer_mask(uint32_t p_mask) {
- layer_mask=p_mask;
+ layer_mask = p_mask;
}
uint32_t RayCast2D::get_layer_mask() const {
@@ -56,7 +55,7 @@ uint32_t RayCast2D::get_layer_mask() const {
void RayCast2D::set_type_mask(uint32_t p_mask) {
- type_mask=p_mask;
+ type_mask = p_mask;
}
uint32_t RayCast2D::get_type_mask() const {
@@ -64,13 +63,13 @@ uint32_t RayCast2D::get_type_mask() const {
return type_mask;
}
-bool RayCast2D::is_colliding() const{
+bool RayCast2D::is_colliding() const {
return collided;
}
-Object *RayCast2D::get_collider() const{
+Object *RayCast2D::get_collider() const {
- if (against==0)
+ if (against == 0)
return NULL;
return ObjectDB::get_instance(against);
@@ -80,61 +79,55 @@ int RayCast2D::get_collider_shape() const {
return against_shape;
}
-Vector2 RayCast2D::get_collision_point() const{
+Vector2 RayCast2D::get_collision_point() const {
return collision_point;
}
-Vector2 RayCast2D::get_collision_normal() const{
+Vector2 RayCast2D::get_collision_normal() const {
return collision_normal;
}
-
void RayCast2D::set_enabled(bool p_enabled) {
- enabled=p_enabled;
+ enabled = p_enabled;
if (is_inside_tree() && !get_tree()->is_editor_hint())
set_fixed_process(p_enabled);
if (!p_enabled)
- collided=false;
-
+ collided = false;
}
-
bool RayCast2D::is_enabled() const {
-
return enabled;
}
void RayCast2D::set_exclude_parent_body(bool p_exclude_parent_body) {
- if (exclude_parent_body==p_exclude_parent_body)
+ if (exclude_parent_body == p_exclude_parent_body)
return;
- exclude_parent_body=p_exclude_parent_body;
+ exclude_parent_body = p_exclude_parent_body;
if (!is_inside_tree())
return;
-
-
if (get_parent()->cast_to<PhysicsBody2D>()) {
if (exclude_parent_body)
- exclude.insert( get_parent()->cast_to<PhysicsBody2D>()->get_rid() );
+ exclude.insert(get_parent()->cast_to<PhysicsBody2D>()->get_rid());
else
- exclude.erase( get_parent()->cast_to<PhysicsBody2D>()->get_rid() );
+ exclude.erase(get_parent()->cast_to<PhysicsBody2D>()->get_rid());
}
}
-bool RayCast2D::get_exclude_parent_body() const{
+bool RayCast2D::get_exclude_parent_body() const {
return exclude_parent_body;
}
void RayCast2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -145,9 +138,9 @@ void RayCast2D::_notification(int p_what) {
if (get_parent()->cast_to<PhysicsBody2D>()) {
if (exclude_parent_body)
- exclude.insert( get_parent()->cast_to<PhysicsBody2D>()->get_rid() );
+ exclude.insert(get_parent()->cast_to<PhysicsBody2D>()->get_rid());
else
- exclude.erase( get_parent()->cast_to<PhysicsBody2D>()->get_rid() );
+ exclude.erase(get_parent()->cast_to<PhysicsBody2D>()->get_rid());
}
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -159,29 +152,28 @@ void RayCast2D::_notification(int p_what) {
case NOTIFICATION_DRAW: {
- if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint())
+ if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint())
break;
Transform2D xf;
xf.rotate(cast_to.angle());
- xf.translate(Vector2(0,cast_to.length()));
+ xf.translate(Vector2(0, cast_to.length()));
//Vector2 tip = Vector2(0,s->get_length());
- Color dcol=get_tree()->get_debug_collisions_color();//0.9,0.2,0.2,0.4);
- draw_line(Vector2(),cast_to,dcol,3);
+ Color dcol = get_tree()->get_debug_collisions_color(); //0.9,0.2,0.2,0.4);
+ draw_line(Vector2(), cast_to, dcol, 3);
Vector<Vector2> pts;
- float tsize=4;
- pts.push_back(xf.xform(Vector2(0,tsize)));
- pts.push_back(xf.xform(Vector2(0.707*tsize,0)));
- pts.push_back(xf.xform(Vector2(-0.707*tsize,0)));
+ float tsize = 4;
+ pts.push_back(xf.xform(Vector2(0, tsize)));
+ pts.push_back(xf.xform(Vector2(0.707 * tsize, 0)));
+ pts.push_back(xf.xform(Vector2(-0.707 * tsize, 0)));
Vector<Color> cols;
- for(int i=0;i<3;i++)
+ for (int i = 0; i < 3; i++)
cols.push_back(dcol);
- draw_primitive(pts,cols,Vector<Vector2>()); //small arrow
+ draw_primitive(pts, cols, Vector<Vector2>()); //small arrow
} break;
-
case NOTIFICATION_FIXED_PROCESS: {
if (!enabled)
@@ -189,35 +181,34 @@ void RayCast2D::_notification(int p_what) {
_update_raycast_state();
-
} break;
}
}
void RayCast2D::_update_raycast_state() {
Ref<World2D> w2d = get_world_2d();
- ERR_FAIL_COND( w2d.is_null() );
+ ERR_FAIL_COND(w2d.is_null());
Physics2DDirectSpaceState *dss = Physics2DServer::get_singleton()->space_get_direct_state(w2d->get_space());
- ERR_FAIL_COND( !dss );
+ ERR_FAIL_COND(!dss);
Transform2D gt = get_global_transform();
Vector2 to = cast_to;
- if (to==Vector2())
- to=Vector2(0,0.01);
+ if (to == Vector2())
+ to = Vector2(0, 0.01);
Physics2DDirectSpaceState::RayResult rr;
- if (dss->intersect_ray(gt.get_origin(),gt.xform(to),rr,exclude,layer_mask,type_mask)) {
+ if (dss->intersect_ray(gt.get_origin(), gt.xform(to), rr, exclude, layer_mask, type_mask)) {
- collided=true;
- against=rr.collider_id;
- collision_point=rr.position;
- collision_normal=rr.normal;
- against_shape=rr.shape;
+ collided = true;
+ against = rr.collider_id;
+ collision_point = rr.position;
+ collision_normal = rr.normal;
+ against_shape = rr.shape;
} else {
- collided=false;
+ collided = false;
}
}
@@ -225,90 +216,87 @@ void RayCast2D::force_raycast_update() {
_update_raycast_state();
}
-void RayCast2D::add_exception_rid(const RID& p_rid) {
+void RayCast2D::add_exception_rid(const RID &p_rid) {
exclude.insert(p_rid);
}
-void RayCast2D::add_exception(const Object* p_object){
+void RayCast2D::add_exception(const Object *p_object) {
ERR_FAIL_NULL(p_object);
- CollisionObject2D *co=((Object*)p_object)->cast_to<CollisionObject2D>();
+ CollisionObject2D *co = ((Object *)p_object)->cast_to<CollisionObject2D>();
if (!co)
return;
add_exception_rid(co->get_rid());
}
-void RayCast2D::remove_exception_rid(const RID& p_rid) {
+void RayCast2D::remove_exception_rid(const RID &p_rid) {
exclude.erase(p_rid);
}
-void RayCast2D::remove_exception(const Object* p_object){
+void RayCast2D::remove_exception(const Object *p_object) {
ERR_FAIL_NULL(p_object);
- CollisionObject2D *co=((Object*)p_object)->cast_to<CollisionObject2D>();
+ CollisionObject2D *co = ((Object *)p_object)->cast_to<CollisionObject2D>();
if (!co)
return;
remove_exception_rid(co->get_rid());
}
-
-void RayCast2D::clear_exceptions(){
+void RayCast2D::clear_exceptions() {
exclude.clear();
}
-
void RayCast2D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &RayCast2D::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &RayCast2D::is_enabled);
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&RayCast2D::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&RayCast2D::is_enabled);
-
- ClassDB::bind_method(D_METHOD("set_cast_to","local_point"),&RayCast2D::set_cast_to);
- ClassDB::bind_method(D_METHOD("get_cast_to"),&RayCast2D::get_cast_to);
+ ClassDB::bind_method(D_METHOD("set_cast_to", "local_point"), &RayCast2D::set_cast_to);
+ ClassDB::bind_method(D_METHOD("get_cast_to"), &RayCast2D::get_cast_to);
- ClassDB::bind_method(D_METHOD("is_colliding"),&RayCast2D::is_colliding);
- ClassDB::bind_method(D_METHOD("force_raycast_update"),&RayCast2D::force_raycast_update);
+ ClassDB::bind_method(D_METHOD("is_colliding"), &RayCast2D::is_colliding);
+ ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast2D::force_raycast_update);
- ClassDB::bind_method(D_METHOD("get_collider"),&RayCast2D::get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_shape"),&RayCast2D::get_collider_shape);
- ClassDB::bind_method(D_METHOD("get_collision_point"),&RayCast2D::get_collision_point);
- ClassDB::bind_method(D_METHOD("get_collision_normal"),&RayCast2D::get_collision_normal);
+ ClassDB::bind_method(D_METHOD("get_collider"), &RayCast2D::get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast2D::get_collider_shape);
+ ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast2D::get_collision_point);
+ ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast2D::get_collision_normal);
- ClassDB::bind_method(D_METHOD("add_exception_rid","rid"),&RayCast2D::add_exception_rid);
- ClassDB::bind_method(D_METHOD("add_exception","node"),&RayCast2D::add_exception);
+ ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &RayCast2D::add_exception_rid);
+ ClassDB::bind_method(D_METHOD("add_exception", "node"), &RayCast2D::add_exception);
- ClassDB::bind_method(D_METHOD("remove_exception_rid","rid"),&RayCast2D::remove_exception_rid);
- ClassDB::bind_method(D_METHOD("remove_exception","node"),&RayCast2D::remove_exception);
+ ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &RayCast2D::remove_exception_rid);
+ ClassDB::bind_method(D_METHOD("remove_exception", "node"), &RayCast2D::remove_exception);
- ClassDB::bind_method(D_METHOD("clear_exceptions"),&RayCast2D::clear_exceptions);
+ ClassDB::bind_method(D_METHOD("clear_exceptions"), &RayCast2D::clear_exceptions);
- ClassDB::bind_method(D_METHOD("set_layer_mask","mask"),&RayCast2D::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&RayCast2D::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &RayCast2D::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &RayCast2D::get_layer_mask);
- ClassDB::bind_method(D_METHOD("set_type_mask","mask"),&RayCast2D::set_type_mask);
- ClassDB::bind_method(D_METHOD("get_type_mask"),&RayCast2D::get_type_mask);
+ ClassDB::bind_method(D_METHOD("set_type_mask", "mask"), &RayCast2D::set_type_mask);
+ ClassDB::bind_method(D_METHOD("get_type_mask"), &RayCast2D::get_type_mask);
- ClassDB::bind_method(D_METHOD("set_exclude_parent_body","mask"),&RayCast2D::set_exclude_parent_body);
- ClassDB::bind_method(D_METHOD("get_exclude_parent_body"),&RayCast2D::get_exclude_parent_body);
+ ClassDB::bind_method(D_METHOD("set_exclude_parent_body", "mask"), &RayCast2D::set_exclude_parent_body);
+ ClassDB::bind_method(D_METHOD("get_exclude_parent_body"), &RayCast2D::get_exclude_parent_body);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"exclude_parent"),"set_exclude_parent_body","get_exclude_parent_body");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"cast_to"),"set_cast_to","get_cast_to");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"layer_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_layer_mask","get_layer_mask");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"type_mask",PROPERTY_HINT_FLAGS,"Static,Kinematic,Rigid,Character,Area"),"set_type_mask","get_type_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exclude_parent"), "set_exclude_parent_body", "get_exclude_parent_body");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "cast_to"), "set_cast_to", "get_cast_to");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layer_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_layer_mask", "get_layer_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type_mask", PROPERTY_HINT_FLAGS, "Static,Kinematic,Rigid,Character,Area"), "set_type_mask", "get_type_mask");
}
RayCast2D::RayCast2D() {
- enabled=false;
- against=0;
- collided=false;
- against_shape=0;
- layer_mask=1;
- type_mask=Physics2DDirectSpaceState::TYPE_MASK_COLLISION;
- cast_to=Vector2(0,50);
- exclude_parent_body=true;
+ enabled = false;
+ against = 0;
+ collided = false;
+ against_shape = 0;
+ layer_mask = 1;
+ type_mask = Physics2DDirectSpaceState::TYPE_MASK_COLLISION;
+ cast_to = Vector2(0, 50);
+ exclude_parent_body = true;
}
diff --git a/scene/2d/ray_cast_2d.h b/scene/2d/ray_cast_2d.h
index 3e7a39ffde..6a59ef963b 100644
--- a/scene/2d/ray_cast_2d.h
+++ b/scene/2d/ray_cast_2d.h
@@ -33,8 +33,7 @@
class RayCast2D : public Node2D {
- GDCLASS(RayCast2D,Node2D);
-
+ GDCLASS(RayCast2D, Node2D);
bool enabled;
bool collided;
@@ -47,19 +46,18 @@ class RayCast2D : public Node2D {
uint32_t type_mask;
bool exclude_parent_body;
-
Vector2 cast_to;
-protected:
+protected:
void _notification(int p_what);
void _update_raycast_state();
static void _bind_methods();
-public:
+public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
- void set_cast_to(const Vector2& p_point);
+ void set_cast_to(const Vector2 &p_point);
Vector2 get_cast_to() const;
void set_layer_mask(uint32_t p_mask);
@@ -79,10 +77,10 @@ public:
Vector2 get_collision_point() const;
Vector2 get_collision_normal() const;
- void add_exception_rid(const RID& p_rid);
- void add_exception(const Object* p_object);
- void remove_exception_rid(const RID& p_rid);
- void remove_exception(const Object* p_object);
+ void add_exception_rid(const RID &p_rid);
+ void add_exception(const Object *p_object);
+ void remove_exception_rid(const RID &p_rid);
+ void remove_exception(const Object *p_object);
void clear_exceptions();
RayCast2D();
diff --git a/scene/2d/remote_transform_2d.cpp b/scene/2d/remote_transform_2d.cpp
index e1f360c0c1..210f64ae23 100644
--- a/scene/2d/remote_transform_2d.cpp
+++ b/scene/2d/remote_transform_2d.cpp
@@ -31,20 +31,19 @@
void RemoteTransform2D::_update_cache() {
- cache=0;
+ cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
- if (!node || this==node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
+ if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
- cache=node->get_instance_ID();
+ cache = node->get_instance_ID();
}
}
void RemoteTransform2D::_update_remote() {
-
if (!is_inside_tree())
return;
@@ -62,14 +61,13 @@ void RemoteTransform2D::_update_remote() {
if (!n->is_inside_tree())
return;
- //todo make faster
+ //todo make faster
n->set_global_transform(get_global_transform());
-
}
void RemoteTransform2D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
@@ -83,30 +81,26 @@ void RemoteTransform2D::_notification(int p_what) {
if (cache) {
_update_remote();
-
}
} break;
-
}
}
+void RemoteTransform2D::set_remote_node(const NodePath &p_remote_node) {
-void RemoteTransform2D::set_remote_node(const NodePath& p_remote_node) {
-
- remote_node=p_remote_node;
+ remote_node = p_remote_node;
if (is_inside_tree())
_update_cache();
update_configuration_warning();
}
-NodePath RemoteTransform2D::get_remote_node() const{
+NodePath RemoteTransform2D::get_remote_node() const {
return remote_node;
}
-
String RemoteTransform2D::get_configuration_warning() const {
if (!has_node(remote_node) || !get_node(remote_node) || !get_node(remote_node)->cast_to<Node2D>()) {
@@ -118,16 +112,14 @@ String RemoteTransform2D::get_configuration_warning() const {
void RemoteTransform2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_remote_node","path"),&RemoteTransform2D::set_remote_node);
- ClassDB::bind_method(D_METHOD("get_remote_node"),&RemoteTransform2D::get_remote_node);
+ ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform2D::set_remote_node);
+ ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform2D::get_remote_node);
- ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"remote_path"),"set_remote_node","get_remote_node");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path"), "set_remote_node", "get_remote_node");
}
RemoteTransform2D::RemoteTransform2D() {
- cache=0;
+ cache = 0;
set_notify_transform(true);
}
-
-
diff --git a/scene/2d/remote_transform_2d.h b/scene/2d/remote_transform_2d.h
index 52c28ffd4f..aa1b214314 100644
--- a/scene/2d/remote_transform_2d.h
+++ b/scene/2d/remote_transform_2d.h
@@ -30,7 +30,7 @@
class RemoteTransform2D : public Node2D {
- GDCLASS(RemoteTransform2D,Node2D);
+ GDCLASS(RemoteTransform2D, Node2D);
NodePath remote_node;
@@ -40,12 +40,11 @@ class RemoteTransform2D : public Node2D {
void _update_cache();
//void _node_exited_scene();
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
- void set_remote_node(const NodePath& p_remote_node);
+public:
+ void set_remote_node(const NodePath &p_remote_node);
NodePath get_remote_node() const;
virtual String get_configuration_warning() const;
diff --git a/scene/2d/screen_button.cpp b/scene/2d/screen_button.cpp
index 4b607e9261..9b9fa6cfa8 100644
--- a/scene/2d/screen_button.cpp
+++ b/scene/2d/screen_button.cpp
@@ -27,45 +27,45 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "screen_button.h"
-#include "os/os.h"
#include "input_map.h"
#include "os/input.h"
+#include "os/os.h"
-void TouchScreenButton::set_texture(const Ref<Texture>& p_texture) {
+void TouchScreenButton::set_texture(const Ref<Texture> &p_texture) {
- texture=p_texture;
+ texture = p_texture;
update();
}
-Ref<Texture> TouchScreenButton::get_texture() const{
+Ref<Texture> TouchScreenButton::get_texture() const {
return texture;
}
-void TouchScreenButton::set_texture_pressed(const Ref<Texture>& p_texture_pressed) {
+void TouchScreenButton::set_texture_pressed(const Ref<Texture> &p_texture_pressed) {
- texture_pressed=p_texture_pressed;
+ texture_pressed = p_texture_pressed;
update();
}
-Ref<Texture> TouchScreenButton::get_texture_pressed() const{
+Ref<Texture> TouchScreenButton::get_texture_pressed() const {
return texture_pressed;
}
-void TouchScreenButton::set_bitmask(const Ref<BitMap>& p_bitmask){
+void TouchScreenButton::set_bitmask(const Ref<BitMap> &p_bitmask) {
- bitmask=p_bitmask;
+ bitmask = p_bitmask;
}
-Ref<BitMap> TouchScreenButton::get_bitmask() const{
+Ref<BitMap> TouchScreenButton::get_bitmask() const {
return bitmask;
}
-void TouchScreenButton::set_shape(const Ref<Shape2D>& p_shape){
+void TouchScreenButton::set_shape(const Ref<Shape2D> &p_shape) {
- shape=p_shape;
+ shape = p_shape;
if (!is_inside_tree())
return;
@@ -74,14 +74,14 @@ void TouchScreenButton::set_shape(const Ref<Shape2D>& p_shape){
update();
}
-Ref<Shape2D> TouchScreenButton::get_shape() const{
+Ref<Shape2D> TouchScreenButton::get_shape() const {
return shape;
}
void TouchScreenButton::set_shape_centered(bool p_shape_centered) {
- shape_centered=p_shape_centered;
+ shape_centered = p_shape_centered;
if (!is_inside_tree())
return;
@@ -97,50 +97,50 @@ bool TouchScreenButton::is_shape_centered() const {
void TouchScreenButton::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (!is_inside_tree())
return;
- if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility==VISIBILITY_TOUCHSCREEN_ONLY)
+ if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY)
return;
- if (finger_pressed!=-1) {
+ if (finger_pressed != -1) {
if (texture_pressed.is_valid())
- draw_texture(texture_pressed,Point2());
+ draw_texture(texture_pressed, Point2());
else if (texture.is_valid())
- draw_texture(texture,Point2());
+ draw_texture(texture, Point2());
} else {
if (texture.is_valid())
- draw_texture(texture,Point2());
+ draw_texture(texture, Point2());
}
if (!get_tree()->is_editor_hint() && !get_tree()->is_debugging_collisions_hint())
return;
if (shape.is_valid()) {
- Color draw_col=get_tree()->get_debug_collisions_color();
- Vector2 pos=shape_centered ? get_item_rect().size*0.5f : Vector2();
+ Color draw_col = get_tree()->get_debug_collisions_color();
+ Vector2 pos = shape_centered ? get_item_rect().size * 0.5f : Vector2();
draw_set_transform_matrix(get_canvas_transform().translated(pos));
- shape->draw(get_canvas_item(),draw_col);
+ shape->draw(get_canvas_item(), draw_col);
}
} break;
case NOTIFICATION_ENTER_TREE: {
- if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility==VISIBILITY_TOUCHSCREEN_ONLY)
+ if (!get_tree()->is_editor_hint() && !OS::get_singleton()->has_touchscreen_ui_hint() && visibility == VISIBILITY_TOUCHSCREEN_ONLY)
return;
update();
if (!get_tree()->is_editor_hint())
set_process_input(true);
- if (action.operator String()!="" && InputMap::get_singleton()->has_action(action)) {
- action_id=InputMap::get_singleton()->get_action_id(action);
+ if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) {
+ action_id = InputMap::get_singleton()->get_action_id(action);
} else {
- action_id=-1;
+ action_id = -1;
}
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -149,26 +149,24 @@ void TouchScreenButton::_notification(int p_what) {
} break;
case NOTIFICATION_PAUSED: {
// So the button can be pressed again even though the release gets unhandled because of coming during pause
- allow_repress=true;
+ allow_repress = true;
}
}
}
+bool TouchScreenButton::is_pressed() const {
-bool TouchScreenButton::is_pressed() const{
-
- return finger_pressed!=-1;
+ return finger_pressed != -1;
}
-void TouchScreenButton::set_action(const String& p_action) {
+void TouchScreenButton::set_action(const String &p_action) {
- action=p_action;
- if (action.operator String()!="" && InputMap::get_singleton()->has_action(action)) {
- action_id=InputMap::get_singleton()->get_action_id(action);
+ action = p_action;
+ if (action.operator String() != "" && InputMap::get_singleton()->has_action(action)) {
+ action_id = InputMap::get_singleton()->get_action_id(action);
} else {
- action_id=-1;
+ action_id = -1;
}
-
}
String TouchScreenButton::get_action() const {
@@ -176,7 +174,7 @@ String TouchScreenButton::get_action() const {
return action;
}
-void TouchScreenButton::_input(const InputEvent& p_event) {
+void TouchScreenButton::_input(const InputEvent &p_event) {
if (!get_tree())
return;
@@ -186,94 +184,88 @@ void TouchScreenButton::_input(const InputEvent& p_event) {
if (passby_press) {
- if (p_event.type==InputEvent::SCREEN_TOUCH && !p_event.screen_touch.pressed && finger_pressed==p_event.screen_touch.index) {
+ if (p_event.type == InputEvent::SCREEN_TOUCH && !p_event.screen_touch.pressed && finger_pressed == p_event.screen_touch.index) {
_release();
}
- if ((p_event.type==InputEvent::SCREEN_TOUCH && p_event.screen_touch.pressed)|| p_event.type==InputEvent::SCREEN_DRAG) {
+ if ((p_event.type == InputEvent::SCREEN_TOUCH && p_event.screen_touch.pressed) || p_event.type == InputEvent::SCREEN_DRAG) {
- if (finger_pressed==-1 || p_event.screen_touch.index==finger_pressed) {
+ if (finger_pressed == -1 || p_event.screen_touch.index == finger_pressed) {
- Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x,p_event.screen_touch.y));
+ Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x, p_event.screen_touch.y));
- bool touched=false;
+ bool touched = false;
if (bitmask.is_valid()) {
- if (Rect2(Point2(),bitmask->get_size()).has_point(coord)) {
+ if (Rect2(Point2(), bitmask->get_size()).has_point(coord)) {
if (bitmask->get_bit(coord))
- touched=true;
+ touched = true;
}
} else {
if (texture.is_valid())
- touched=Rect2(Point2(),texture->get_size()).has_point(coord);
+ touched = Rect2(Point2(), texture->get_size()).has_point(coord);
}
-
-
if (touched) {
- if (finger_pressed==-1) {
+ if (finger_pressed == -1) {
_press(p_event.screen_touch.index);
}
} else {
- if (finger_pressed!=-1) {
+ if (finger_pressed != -1) {
_release();
}
}
-
}
-
-
}
} else {
- if (p_event.type==InputEvent::SCREEN_TOUCH) {
+ if (p_event.type == InputEvent::SCREEN_TOUCH) {
if (p_event.screen_touch.pressed) {
if (!is_visible_in_tree())
return;
- const bool can_press=finger_pressed==-1 || allow_repress;
+ const bool can_press = finger_pressed == -1 || allow_repress;
if (!can_press)
return; //already fingering
- Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x,p_event.screen_touch.y));
+ Point2 coord = (get_global_transform_with_canvas()).affine_inverse().xform(Point2(p_event.screen_touch.x, p_event.screen_touch.y));
Rect2 item_rect = get_item_rect();
- bool touched=false;
- bool check_rect=true;
+ bool touched = false;
+ bool check_rect = true;
if (shape.is_valid()) {
- check_rect=false;
- Transform2D xform=shape_centered ? Transform2D().translated(get_item_rect().size*0.5f) : Transform2D();
- touched=shape->collide(xform, unit_rect, Transform2D(0, coord + Vector2(0.5,0.5)));
+ check_rect = false;
+ Transform2D xform = shape_centered ? Transform2D().translated(get_item_rect().size * 0.5f) : Transform2D();
+ touched = shape->collide(xform, unit_rect, Transform2D(0, coord + Vector2(0.5, 0.5)));
}
if (bitmask.is_valid()) {
- check_rect=false;
- if (!touched && Rect2(Point2(),bitmask->get_size()).has_point(coord)) {
+ check_rect = false;
+ if (!touched && Rect2(Point2(), bitmask->get_size()).has_point(coord)) {
if (bitmask->get_bit(coord))
- touched=true;
+ touched = true;
}
}
if (!touched && check_rect) {
if (!texture.is_null())
- touched=item_rect.has_point(coord);
+ touched = item_rect.has_point(coord);
}
-
if (touched) {
_press(p_event.screen_touch.index);
}
} else {
- if (p_event.screen_touch.index==finger_pressed) {
+ if (p_event.screen_touch.index == finger_pressed) {
_release();
}
}
@@ -283,17 +275,17 @@ void TouchScreenButton::_input(const InputEvent& p_event) {
void TouchScreenButton::_press(int p_finger_pressed) {
- finger_pressed=p_finger_pressed;
- allow_repress=false;
+ finger_pressed = p_finger_pressed;
+ allow_repress = false;
- if (action_id!=-1) {
+ if (action_id != -1) {
Input::get_singleton()->action_press(action);
InputEvent ie;
- ie.type=InputEvent::ACTION;
- ie.ID=0;
- ie.action.action=action_id;
- ie.action.pressed=true;
+ ie.type = InputEvent::ACTION;
+ ie.ID = 0;
+ ie.action.action = action_id;
+ ie.action.pressed = true;
get_tree()->input_event(ie);
}
@@ -303,17 +295,17 @@ void TouchScreenButton::_press(int p_finger_pressed) {
void TouchScreenButton::_release(bool p_exiting_tree) {
- finger_pressed=-1;
+ finger_pressed = -1;
- if (action_id!=-1) {
+ if (action_id != -1) {
Input::get_singleton()->action_release(action);
if (!p_exiting_tree) {
InputEvent ie;
- ie.type=InputEvent::ACTION;
- ie.ID=0;
- ie.action.action=action_id;
- ie.action.pressed=false;
+ ie.type = InputEvent::ACTION;
+ ie.ID = 0;
+ ie.action.action = action_id;
+ ie.action.pressed = false;
get_tree()->input_event(ie);
}
}
@@ -327,18 +319,17 @@ void TouchScreenButton::_release(bool p_exiting_tree) {
Rect2 TouchScreenButton::get_item_rect() const {
if (texture.is_null())
- return Rect2(0,0,1,1);
+ return Rect2(0, 0, 1, 1);
/*
if (texture.is_null())
return CanvasItem::get_item_rect();
*/
- return Rect2(Size2(),texture->get_size());
+ return Rect2(Size2(), texture->get_size());
}
-
void TouchScreenButton::set_visibility_mode(VisibilityMode p_mode) {
- visibility=p_mode;
+ visibility = p_mode;
update();
}
@@ -349,70 +340,65 @@ TouchScreenButton::VisibilityMode TouchScreenButton::get_visibility_mode() const
void TouchScreenButton::set_passby_press(bool p_enable) {
- passby_press=p_enable;
+ passby_press = p_enable;
}
-bool TouchScreenButton::is_passby_press_enabled() const{
+bool TouchScreenButton::is_passby_press_enabled() const {
return passby_press;
}
-
-
void TouchScreenButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_texture","texture"),&TouchScreenButton::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture"),&TouchScreenButton::get_texture);
-
- ClassDB::bind_method(D_METHOD("set_texture_pressed","texture_pressed"),&TouchScreenButton::set_texture_pressed);
- ClassDB::bind_method(D_METHOD("get_texture_pressed"),&TouchScreenButton::get_texture_pressed);
-
- ClassDB::bind_method(D_METHOD("set_bitmask","bitmask"),&TouchScreenButton::set_bitmask);
- ClassDB::bind_method(D_METHOD("get_bitmask"),&TouchScreenButton::get_bitmask);
-
- ClassDB::bind_method(D_METHOD("set_shape","shape"),&TouchScreenButton::set_shape);
- ClassDB::bind_method(D_METHOD("get_shape"),&TouchScreenButton::get_shape);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TouchScreenButton::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &TouchScreenButton::get_texture);
- ClassDB::bind_method(D_METHOD("set_shape_centered","bool"),&TouchScreenButton::set_shape_centered);
- ClassDB::bind_method(D_METHOD("is_shape_centered"),&TouchScreenButton::is_shape_centered);
+ ClassDB::bind_method(D_METHOD("set_texture_pressed", "texture_pressed"), &TouchScreenButton::set_texture_pressed);
+ ClassDB::bind_method(D_METHOD("get_texture_pressed"), &TouchScreenButton::get_texture_pressed);
- ClassDB::bind_method(D_METHOD("set_action","action"),&TouchScreenButton::set_action);
- ClassDB::bind_method(D_METHOD("get_action"),&TouchScreenButton::get_action);
+ ClassDB::bind_method(D_METHOD("set_bitmask", "bitmask"), &TouchScreenButton::set_bitmask);
+ ClassDB::bind_method(D_METHOD("get_bitmask"), &TouchScreenButton::get_bitmask);
- ClassDB::bind_method(D_METHOD("set_visibility_mode","mode"),&TouchScreenButton::set_visibility_mode);
- ClassDB::bind_method(D_METHOD("get_visibility_mode"),&TouchScreenButton::get_visibility_mode);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape"), &TouchScreenButton::set_shape);
+ ClassDB::bind_method(D_METHOD("get_shape"), &TouchScreenButton::get_shape);
- ClassDB::bind_method(D_METHOD("set_passby_press","enabled"),&TouchScreenButton::set_passby_press);
- ClassDB::bind_method(D_METHOD("is_passby_press_enabled"),&TouchScreenButton::is_passby_press_enabled);
+ ClassDB::bind_method(D_METHOD("set_shape_centered", "bool"), &TouchScreenButton::set_shape_centered);
+ ClassDB::bind_method(D_METHOD("is_shape_centered"), &TouchScreenButton::is_shape_centered);
- ClassDB::bind_method(D_METHOD("is_pressed"),&TouchScreenButton::is_pressed);
+ ClassDB::bind_method(D_METHOD("set_action", "action"), &TouchScreenButton::set_action);
+ ClassDB::bind_method(D_METHOD("get_action"), &TouchScreenButton::get_action);
- ClassDB::bind_method(D_METHOD("_input"),&TouchScreenButton::_input);
+ ClassDB::bind_method(D_METHOD("set_visibility_mode", "mode"), &TouchScreenButton::set_visibility_mode);
+ ClassDB::bind_method(D_METHOD("get_visibility_mode"), &TouchScreenButton::get_visibility_mode);
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"pressed",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture_pressed","get_texture_pressed");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"bitmask",PROPERTY_HINT_RESOURCE_TYPE,"BitMap"),"set_bitmask","get_bitmask");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D"),"set_shape","get_shape");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"shape_centered"),"set_shape_centered","is_shape_centered");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"passby_press"),"set_passby_press","is_passby_press_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"action"),"set_action","get_action");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"visibility_mode",PROPERTY_HINT_ENUM,"Always,TouchScreen Only"),"set_visibility_mode","get_visibility_mode");
+ ClassDB::bind_method(D_METHOD("set_passby_press", "enabled"), &TouchScreenButton::set_passby_press);
+ ClassDB::bind_method(D_METHOD("is_passby_press_enabled"), &TouchScreenButton::is_passby_press_enabled);
- ADD_SIGNAL( MethodInfo("pressed" ) );
- ADD_SIGNAL( MethodInfo("released" ) );
+ ClassDB::bind_method(D_METHOD("is_pressed"), &TouchScreenButton::is_pressed);
+ ClassDB::bind_method(D_METHOD("_input"), &TouchScreenButton::_input);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture_pressed", "get_texture_pressed");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "bitmask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_bitmask", "get_bitmask");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D"), "set_shape", "get_shape");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shape_centered"), "set_shape_centered", "is_shape_centered");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "passby_press"), "set_passby_press", "is_passby_press_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "action"), "set_action", "get_action");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_mode", PROPERTY_HINT_ENUM, "Always,TouchScreen Only"), "set_visibility_mode", "get_visibility_mode");
+ ADD_SIGNAL(MethodInfo("pressed"));
+ ADD_SIGNAL(MethodInfo("released"));
}
TouchScreenButton::TouchScreenButton() {
- finger_pressed=-1;
- allow_repress=false;
- action_id=-1;
- passby_press=false;
- visibility=VISIBILITY_ALWAYS;
- shape_centered=true;
- unit_rect=Ref<RectangleShape2D>(memnew(RectangleShape2D));
- unit_rect->set_extents(Vector2(0.5,0.5));
+ finger_pressed = -1;
+ allow_repress = false;
+ action_id = -1;
+ passby_press = false;
+ visibility = VISIBILITY_ALWAYS;
+ shape_centered = true;
+ unit_rect = Ref<RectangleShape2D>(memnew(RectangleShape2D));
+ unit_rect->set_extents(Vector2(0.5, 0.5));
}
diff --git a/scene/2d/screen_button.h b/scene/2d/screen_button.h
index 8ce378c660..d648920b21 100644
--- a/scene/2d/screen_button.h
+++ b/scene/2d/screen_button.h
@@ -30,15 +30,15 @@
#define SCREEN_BUTTON_H
#include "scene/2d/node_2d.h"
-#include "scene/resources/texture.h"
#include "scene/resources/bit_mask.h"
#include "scene/resources/rectangle_shape_2d.h"
+#include "scene/resources/texture.h"
class TouchScreenButton : public Node2D {
- GDCLASS(TouchScreenButton,Node2D);
-public:
+ GDCLASS(TouchScreenButton, Node2D);
+public:
enum VisibilityMode {
VISIBILITY_ALWAYS,
VISIBILITY_TOUCHSCREEN_ONLY
@@ -61,34 +61,32 @@ private:
VisibilityMode visibility;
- void _input(const InputEvent& p_Event);
+ void _input(const InputEvent &p_Event);
void _press(int p_finger_pressed);
- void _release(bool p_exiting_tree=false);
+ void _release(bool p_exiting_tree = false);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
- void set_texture(const Ref<Texture>& p_texture);
+public:
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
- void set_texture_pressed(const Ref<Texture>& p_texture_pressed);
+ void set_texture_pressed(const Ref<Texture> &p_texture_pressed);
Ref<Texture> get_texture_pressed() const;
- void set_bitmask(const Ref<BitMap>& p_bitmask);
+ void set_bitmask(const Ref<BitMap> &p_bitmask);
Ref<BitMap> get_bitmask() const;
- void set_shape(const Ref<Shape2D>& p_shape);
+ void set_shape(const Ref<Shape2D> &p_shape);
Ref<Shape2D> get_shape() const;
void set_shape_centered(bool p_shape_centered);
bool is_shape_centered() const;
- void set_action(const String& p_action);
+ void set_action(const String &p_action);
String get_action() const;
void set_passby_press(bool p_enable);
@@ -101,7 +99,6 @@ public:
Rect2 get_item_rect() const;
-
TouchScreenButton();
};
diff --git a/scene/2d/sprite.cpp b/scene/2d/sprite.cpp
index 26c2756acd..41ea6a39e5 100644
--- a/scene/2d/sprite.cpp
+++ b/scene/2d/sprite.cpp
@@ -28,14 +28,13 @@
/*************************************************************************/
#include "sprite.h"
#include "core/core_string_names.h"
-#include "scene/scene_string_names.h"
-#include "scene/main/viewport.h"
#include "os/os.h"
+#include "scene/main/viewport.h"
+#include "scene/scene_string_names.h"
-void Sprite::edit_set_pivot(const Point2& p_pivot) {
+void Sprite::edit_set_pivot(const Point2 &p_pivot) {
set_offset(p_pivot);
-
}
Point2 Sprite::edit_get_pivot() const {
@@ -49,16 +48,13 @@ bool Sprite::edit_has_pivot() const {
void Sprite::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
if (texture.is_null())
return;
-
-
-
RID ci = get_canvas_item();
/*
@@ -71,52 +67,51 @@ void Sprite::_notification(int p_what) {
if (region) {
- s=region_rect.size;
- src_rect=region_rect;
+ s = region_rect.size;
+ src_rect = region_rect;
} else {
s = Size2(texture->get_size());
- s=s/Size2(hframes,vframes);
-
- src_rect.size=s;
- src_rect.pos.x+=float(frame%hframes)*s.x;
- src_rect.pos.y+=float(frame/hframes)*s.y;
+ s = s / Size2(hframes, vframes);
+ src_rect.size = s;
+ src_rect.pos.x += float(frame % hframes) * s.x;
+ src_rect.pos.y += float(frame / hframes) * s.y;
}
- Point2 ofs=offset;
+ Point2 ofs = offset;
if (centered)
- ofs-=s/2;
+ ofs -= s / 2;
if (Engine::get_singleton()->get_use_pixel_snap()) {
- ofs=ofs.floor();
+ ofs = ofs.floor();
}
- Rect2 dst_rect(ofs,s);
+ Rect2 dst_rect(ofs, s);
if (hflip)
- dst_rect.size.x=-dst_rect.size.x;
+ dst_rect.size.x = -dst_rect.size.x;
if (vflip)
- dst_rect.size.y=-dst_rect.size.y;
+ dst_rect.size.y = -dst_rect.size.y;
- texture->draw_rect_region(ci,dst_rect,src_rect);
+ texture->draw_rect_region(ci, dst_rect, src_rect);
} break;
}
}
-void Sprite::set_texture(const Ref<Texture>& p_texture) {
+void Sprite::set_texture(const Ref<Texture> &p_texture) {
- if (p_texture==texture)
+ if (p_texture == texture)
return;
#ifdef DEBUG_ENABLED
if (texture.is_valid()) {
- texture->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->update);
+ texture->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->update);
}
#endif
- texture=p_texture;
+ texture = p_texture;
#ifdef DEBUG_ENABLED
if (texture.is_valid()) {
texture->set_flags(texture->get_flags()); //remove repeat from texture, it looks bad in sprites
- texture->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->update);
+ texture->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->update);
}
#endif
update();
@@ -131,7 +126,7 @@ Ref<Texture> Sprite::get_texture() const {
void Sprite::set_centered(bool p_center) {
- centered=p_center;
+ centered = p_center;
update();
item_rect_changed();
}
@@ -141,9 +136,9 @@ bool Sprite::is_centered() const {
return centered;
}
-void Sprite::set_offset(const Point2& p_offset) {
+void Sprite::set_offset(const Point2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
update();
item_rect_changed();
_change_notify("offset");
@@ -155,7 +150,7 @@ Point2 Sprite::get_offset() const {
void Sprite::set_flip_h(bool p_flip) {
- hflip=p_flip;
+ hflip = p_flip;
update();
}
bool Sprite::is_flipped_h() const {
@@ -165,7 +160,7 @@ bool Sprite::is_flipped_h() const {
void Sprite::set_flip_v(bool p_flip) {
- vflip=p_flip;
+ vflip = p_flip;
update();
}
bool Sprite::is_flipped_v() const {
@@ -175,24 +170,24 @@ bool Sprite::is_flipped_v() const {
void Sprite::set_region(bool p_region) {
- if (p_region==region)
+ if (p_region == region)
return;
- region=p_region;
+ region = p_region;
update();
}
-bool Sprite::is_region() const{
+bool Sprite::is_region() const {
return region;
}
-void Sprite::set_region_rect(const Rect2& p_region_rect) {
+void Sprite::set_region_rect(const Rect2 &p_region_rect) {
- if (region_rect==p_region_rect)
+ if (region_rect == p_region_rect)
return;
- region_rect=p_region_rect;
+ region_rect = p_region_rect;
if (region)
item_rect_changed();
@@ -207,12 +202,12 @@ Rect2 Sprite::get_region_rect() const {
void Sprite::set_frame(int p_frame) {
- ERR_FAIL_INDEX(p_frame,vframes*hframes);
+ ERR_FAIL_INDEX(p_frame, vframes * hframes);
if (frame != p_frame)
item_rect_changed();
- frame=p_frame;
+ frame = p_frame;
_change_notify("frame");
emit_signal(SceneStringNames::get_singleton()->frame_changed);
@@ -225,8 +220,8 @@ int Sprite::get_frame() const {
void Sprite::set_vframes(int p_amount) {
- ERR_FAIL_COND(p_amount<1);
- vframes=p_amount;
+ ERR_FAIL_COND(p_amount < 1);
+ vframes = p_amount;
update();
item_rect_changed();
_change_notify("frame");
@@ -238,8 +233,8 @@ int Sprite::get_vframes() const {
void Sprite::set_hframes(int p_amount) {
- ERR_FAIL_COND(p_amount<1);
- hframes=p_amount;
+ ERR_FAIL_COND(p_amount < 1);
+ hframes = p_amount;
update();
item_rect_changed();
_change_notify("frame");
@@ -249,12 +244,10 @@ int Sprite::get_hframes() const {
return hframes;
}
-
-
Rect2 Sprite::get_item_rect() const {
if (texture.is_null())
- return Rect2(0,0,1,1);
+ return Rect2(0, 0, 1, 1);
/*
if (texture.is_null())
return CanvasItem::get_item_rect();
@@ -264,99 +257,92 @@ Rect2 Sprite::get_item_rect() const {
if (region) {
- s=region_rect.size;
+ s = region_rect.size;
} else {
s = texture->get_size();
- s=s/Point2(hframes,vframes);
+ s = s / Point2(hframes, vframes);
}
- Point2 ofs=offset;
+ Point2 ofs = offset;
if (centered)
- ofs-=s/2;
+ ofs -= s / 2;
- if (s==Size2(0,0))
- s=Size2(1,1);
+ if (s == Size2(0, 0))
+ s = Size2(1, 1);
- return Rect2(ofs,s);
+ return Rect2(ofs, s);
}
+void Sprite::_validate_property(PropertyInfo &property) const {
+ if (property.name == "frame") {
-void Sprite::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="frame") {
-
- property.hint=PROPERTY_HINT_SPRITE_FRAME;
+ property.hint = PROPERTY_HINT_SPRITE_FRAME;
- property.hint_string="0,"+itos(vframes*hframes-1)+",1";
+ property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
}
}
void Sprite::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&Sprite::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture:Texture"),&Sprite::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &Sprite::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture"), &Sprite::get_texture);
- ClassDB::bind_method(D_METHOD("set_centered","centered"),&Sprite::set_centered);
- ClassDB::bind_method(D_METHOD("is_centered"),&Sprite::is_centered);
+ ClassDB::bind_method(D_METHOD("set_centered", "centered"), &Sprite::set_centered);
+ ClassDB::bind_method(D_METHOD("is_centered"), &Sprite::is_centered);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&Sprite::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&Sprite::get_offset);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Sprite::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Sprite::get_offset);
- ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&Sprite::set_flip_h);
- ClassDB::bind_method(D_METHOD("is_flipped_h"),&Sprite::is_flipped_h);
+ ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &Sprite::set_flip_h);
+ ClassDB::bind_method(D_METHOD("is_flipped_h"), &Sprite::is_flipped_h);
- ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&Sprite::set_flip_v);
- ClassDB::bind_method(D_METHOD("is_flipped_v"),&Sprite::is_flipped_v);
+ ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &Sprite::set_flip_v);
+ ClassDB::bind_method(D_METHOD("is_flipped_v"), &Sprite::is_flipped_v);
- ClassDB::bind_method(D_METHOD("set_region","enabled"),&Sprite::set_region);
- ClassDB::bind_method(D_METHOD("is_region"),&Sprite::is_region);
+ ClassDB::bind_method(D_METHOD("set_region", "enabled"), &Sprite::set_region);
+ ClassDB::bind_method(D_METHOD("is_region"), &Sprite::is_region);
- ClassDB::bind_method(D_METHOD("set_region_rect","rect"),&Sprite::set_region_rect);
- ClassDB::bind_method(D_METHOD("get_region_rect"),&Sprite::get_region_rect);
+ ClassDB::bind_method(D_METHOD("set_region_rect", "rect"), &Sprite::set_region_rect);
+ ClassDB::bind_method(D_METHOD("get_region_rect"), &Sprite::get_region_rect);
- ClassDB::bind_method(D_METHOD("set_frame","frame"),&Sprite::set_frame);
- ClassDB::bind_method(D_METHOD("get_frame"),&Sprite::get_frame);
+ ClassDB::bind_method(D_METHOD("set_frame", "frame"), &Sprite::set_frame);
+ ClassDB::bind_method(D_METHOD("get_frame"), &Sprite::get_frame);
- ClassDB::bind_method(D_METHOD("set_vframes","vframes"),&Sprite::set_vframes);
- ClassDB::bind_method(D_METHOD("get_vframes"),&Sprite::get_vframes);
+ ClassDB::bind_method(D_METHOD("set_vframes", "vframes"), &Sprite::set_vframes);
+ ClassDB::bind_method(D_METHOD("get_vframes"), &Sprite::get_vframes);
- ClassDB::bind_method(D_METHOD("set_hframes","hframes"),&Sprite::set_hframes);
- ClassDB::bind_method(D_METHOD("get_hframes"),&Sprite::get_hframes);
+ ClassDB::bind_method(D_METHOD("set_hframes", "hframes"), &Sprite::set_hframes);
+ ClassDB::bind_method(D_METHOD("get_hframes"), &Sprite::get_hframes);
ADD_SIGNAL(MethodInfo("frame_changed"));
ADD_SIGNAL(MethodInfo("texture_changed"));
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_texture","get_texture");
- ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered");
- ADD_PROPERTYNZ( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v");
- ADD_PROPERTYNO( PropertyInfo( Variant::INT, "vframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_vframes","get_vframes");
- ADD_PROPERTYNO( PropertyInfo( Variant::INT, "hframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_hframes","get_hframes");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "region"), "set_region","is_region");
- ADD_PROPERTYNZ( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect");
-
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "region"), "set_region", "is_region");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
}
Sprite::Sprite() {
- centered=true;
- hflip=false;
- vflip=false;
- region=false;
-
- frame=0;
+ centered = true;
+ hflip = false;
+ vflip = false;
+ region = false;
- vframes=1;
- hframes=1;
+ frame = 0;
+ vframes = 1;
+ hframes = 1;
}
-
-
-
//////////////////////////// VPSPRITE
///
///
diff --git a/scene/2d/sprite.h b/scene/2d/sprite.h
index ab4487ef7b..c4bc800647 100644
--- a/scene/2d/sprite.h
+++ b/scene/2d/sprite.h
@@ -32,10 +32,9 @@
#include "scene/2d/node_2d.h"
#include "scene/resources/texture.h"
-
class Sprite : public Node2D {
- GDCLASS( Sprite, Node2D );
+ GDCLASS(Sprite, Node2D);
Ref<Texture> texture;
@@ -52,29 +51,25 @@ class Sprite : public Node2D {
int vframes;
int hframes;
-
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
- virtual void edit_set_pivot(const Point2& p_pivot);
+ virtual void edit_set_pivot(const Point2 &p_pivot);
virtual Point2 edit_get_pivot() const;
virtual bool edit_has_pivot() const;
- void set_texture(const Ref<Texture>& p_texture);
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
void set_centered(bool p_center);
bool is_centered() const;
- void set_offset(const Point2& p_offset);
+ void set_offset(const Point2 &p_offset);
Point2 get_offset() const;
void set_flip_h(bool p_flip);
@@ -86,7 +81,7 @@ public:
void set_region(bool p_region);
bool is_region() const;
- void set_region_rect(const Rect2& p_region_rect);
+ void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
void set_frame(int p_frame);
diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp
index f89a72e1b9..02b41fbd0c 100644
--- a/scene/2d/tile_map.cpp
+++ b/scene/2d/tile_map.cpp
@@ -28,11 +28,9 @@
/*************************************************************************/
#include "tile_map.h"
#include "io/marshalls.h"
-#include "servers/physics_2d_server.h"
#include "method_bind_ext.inc"
#include "os/os.h"
-
-
+#include "servers/physics_2d_server.h"
int TileMap::_get_quadrant_size() const {
@@ -44,51 +42,49 @@ int TileMap::_get_quadrant_size() const {
void TileMap::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- Node2D *c=this;
- while(c) {
+ Node2D *c = this;
+ while (c) {
- navigation=c->cast_to<Navigation2D>();
+ navigation = c->cast_to<Navigation2D>();
if (navigation) {
break;
}
- c=c->get_parent()->cast_to<Node2D>();
+ c = c->get_parent()->cast_to<Node2D>();
}
- pending_update=true;
+ pending_update = true;
_update_dirty_quadrants();
RID space = get_world_2d()->get_space();
_update_quadrant_transform();
_update_quadrant_space(space);
-
} break;
case NOTIFICATION_EXIT_TREE: {
_update_quadrant_space(RID());
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
+ Quadrant &q = E->get();
if (navigation) {
- for(Map<PosKey,Quadrant::NavPoly>::Element *E=q.navpoly_ids.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::NavPoly>::Element *E = q.navpoly_ids.front(); E; E = E->next()) {
navigation->navpoly_remove(E->get().id);
}
q.navpoly_ids.clear();
}
- for(Map<PosKey,Quadrant::Occluder>::Element *E=q.occluder_instances.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::Occluder>::Element *E = q.occluder_instances.front(); E; E = E->next()) {
VS::get_singleton()->free(E->get().id);
}
q.occluder_instances.clear();
}
- navigation=NULL;
-
+ navigation = NULL;
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -100,12 +96,12 @@ void TileMap::_notification(int p_what) {
}
}
-void TileMap::_update_quadrant_space(const RID& p_space) {
+void TileMap::_update_quadrant_space(const RID &p_space) {
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- Physics2DServer::get_singleton()->body_set_space(q.body,p_space);
+ Quadrant &q = E->get();
+ Physics2DServer::get_singleton()->body_set_space(q.body, p_space);
}
}
@@ -120,43 +116,42 @@ void TileMap::_update_quadrant_transform() {
if (navigation)
nav_rel = get_relative_transform_to_parent(navigation);
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
+ Quadrant &q = E->get();
Transform2D xform;
- xform.set_origin( q.pos );
+ xform.set_origin(q.pos);
xform = global_transform * xform;
- Physics2DServer::get_singleton()->body_set_state(q.body,Physics2DServer::BODY_STATE_TRANSFORM,xform);
+ Physics2DServer::get_singleton()->body_set_state(q.body, Physics2DServer::BODY_STATE_TRANSFORM, xform);
if (navigation) {
- for(Map<PosKey,Quadrant::NavPoly>::Element *E=q.navpoly_ids.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::NavPoly>::Element *E = q.navpoly_ids.front(); E; E = E->next()) {
- navigation->navpoly_set_transform(E->get().id,nav_rel * E->get().xform);
+ navigation->navpoly_set_transform(E->get().id, nav_rel * E->get().xform);
}
}
- for(Map<PosKey,Quadrant::Occluder>::Element *E=q.occluder_instances.front();E;E=E->next()) {
- VS::get_singleton()->canvas_light_occluder_set_transform(E->get().id,global_transform * E->get().xform);
+ for (Map<PosKey, Quadrant::Occluder>::Element *E = q.occluder_instances.front(); E; E = E->next()) {
+ VS::get_singleton()->canvas_light_occluder_set_transform(E->get().id, global_transform * E->get().xform);
}
}
}
-void TileMap::set_tileset(const Ref<TileSet>& p_tileset) {
+void TileMap::set_tileset(const Ref<TileSet> &p_tileset) {
if (tile_set.is_valid())
- tile_set->disconnect("changed",this,"_recreate_quadrants");
+ tile_set->disconnect("changed", this, "_recreate_quadrants");
_clear_quadrants();
- tile_set=p_tileset;
+ tile_set = p_tileset;
if (tile_set.is_valid())
- tile_set->connect("changed",this,"_recreate_quadrants");
+ tile_set->connect("changed", this, "_recreate_quadrants");
else
clear();
_recreate_quadrants();
emit_signal("settings_changed");
-
}
Ref<TileSet> TileMap::get_tileset() const {
@@ -166,14 +161,12 @@ Ref<TileSet> TileMap::get_tileset() const {
void TileMap::set_cell_size(Size2 p_size) {
- ERR_FAIL_COND(p_size.x<1 || p_size.y<1);
+ ERR_FAIL_COND(p_size.x < 1 || p_size.y < 1);
_clear_quadrants();
- cell_size=p_size;
+ cell_size = p_size;
_recreate_quadrants();
emit_signal("settings_changed");
-
-
}
Size2 TileMap::get_cell_size() const {
@@ -181,13 +174,12 @@ Size2 TileMap::get_cell_size() const {
}
void TileMap::set_quadrant_size(int p_size) {
- ERR_FAIL_COND(p_size<1);
+ ERR_FAIL_COND(p_size < 1);
_clear_quadrants();
- quadrant_size=p_size;
+ quadrant_size = p_size;
_recreate_quadrants();
emit_signal("settings_changed");
-
}
int TileMap::get_quadrant_size() const {
@@ -196,11 +188,9 @@ int TileMap::get_quadrant_size() const {
void TileMap::set_center_x(bool p_enable) {
- center_x=p_enable;
+ center_x = p_enable;
_recreate_quadrants();
emit_signal("settings_changed");
-
-
}
bool TileMap::get_center_x() const {
@@ -208,24 +198,22 @@ bool TileMap::get_center_x() const {
}
void TileMap::set_center_y(bool p_enable) {
- center_y=p_enable;
+ center_y = p_enable;
_recreate_quadrants();
emit_signal("settings_changed");
-
}
bool TileMap::get_center_y() const {
return center_y;
}
-void TileMap::_fix_cell_transform(Transform2D& xform,const Cell& p_cell, const Vector2& p_offset, const Size2 &p_sc) {
+void TileMap::_fix_cell_transform(Transform2D &xform, const Cell &p_cell, const Vector2 &p_offset, const Size2 &p_sc) {
- Size2 s=p_sc;
+ Size2 s = p_sc;
Vector2 offset = p_offset;
-
- if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT)
- offset.y+=cell_size.y;
+ if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT)
+ offset.y += cell_size.y;
if (s.y > s.x) {
if ((p_cell.flip_h && (p_cell.flip_v || p_cell.transpose)) || (p_cell.flip_v && !p_cell.transpose))
@@ -242,26 +230,25 @@ void TileMap::_fix_cell_transform(Transform2D& xform,const Cell& p_cell, const V
SWAP(s.x, s.y);
}
if (p_cell.flip_h) {
- xform.elements[0].x=-xform.elements[0].x;
- xform.elements[1].x=-xform.elements[1].x;
- if (tile_origin==TILE_ORIGIN_TOP_LEFT || tile_origin==TILE_ORIGIN_BOTTOM_LEFT)
- offset.x=s.x-offset.x;
+ xform.elements[0].x = -xform.elements[0].x;
+ xform.elements[1].x = -xform.elements[1].x;
+ if (tile_origin == TILE_ORIGIN_TOP_LEFT || tile_origin == TILE_ORIGIN_BOTTOM_LEFT)
+ offset.x = s.x - offset.x;
}
if (p_cell.flip_v) {
- xform.elements[0].y=-xform.elements[0].y;
- xform.elements[1].y=-xform.elements[1].y;
- if (tile_origin==TILE_ORIGIN_TOP_LEFT)
- offset.y=s.y-offset.y;
- else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) {
- if(p_cell.transpose)
- offset.y+=s.y;
+ xform.elements[0].y = -xform.elements[0].y;
+ xform.elements[1].y = -xform.elements[1].y;
+ if (tile_origin == TILE_ORIGIN_TOP_LEFT)
+ offset.y = s.y - offset.y;
+ else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) {
+ if (p_cell.transpose)
+ offset.y += s.y;
else
- offset.y-=s.y;
+ offset.y -= s.y;
}
}
- xform.elements[2].x+=offset.x;
- xform.elements[2].y+=offset.y;
-
+ xform.elements[2].x += offset.x;
+ xform.elements[2].y += offset.y;
}
void TileMap::_update_dirty_quadrants() {
@@ -276,26 +263,26 @@ void TileMap::_update_dirty_quadrants() {
VisualServer *vs = VisualServer::get_singleton();
Physics2DServer *ps = Physics2DServer::get_singleton();
Vector2 tofs = get_cell_draw_offset();
- Vector2 tcenter = cell_size/2;
+ Vector2 tcenter = cell_size / 2;
Transform2D nav_rel;
if (navigation)
nav_rel = get_relative_transform_to_parent(navigation);
Vector2 qofs;
- SceneTree *st=SceneTree::get_singleton();
+ SceneTree *st = SceneTree::get_singleton();
Color debug_collision_color;
bool debug_shapes = st && st->is_debugging_collisions_hint();
if (debug_shapes) {
- debug_collision_color=st->get_debug_collisions_color();
+ debug_collision_color = st->get_debug_collisions_color();
}
while (dirty_quadrant_list.first()) {
Quadrant &q = *dirty_quadrant_list.first()->self();
- for (List<RID>::Element *E=q.canvas_items.front();E;E=E->next()) {
+ for (List<RID>::Element *E = q.canvas_items.front(); E; E = E->next()) {
vs->free(E->get());
}
@@ -303,17 +290,17 @@ void TileMap::_update_dirty_quadrants() {
q.canvas_items.clear();
ps->body_clear_shapes(q.body);
- int shape_idx=0;
+ int shape_idx = 0;
if (navigation) {
- for(Map<PosKey,Quadrant::NavPoly>::Element *E=q.navpoly_ids.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::NavPoly>::Element *E = q.navpoly_ids.front(); E; E = E->next()) {
navigation->navpoly_remove(E->get().id);
}
q.navpoly_ids.clear();
}
- for(Map<PosKey,Quadrant::Occluder>::Element *E=q.occluder_instances.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::Occluder>::Element *E = q.occluder_instances.front(); E; E = E->next()) {
VS::get_singleton()->free(E->get().id);
}
q.occluder_instances.clear();
@@ -321,10 +308,10 @@ void TileMap::_update_dirty_quadrants() {
RID prev_canvas_item;
RID prev_debug_canvas_item;
- for(int i=0;i<q.cells.size();i++) {
+ for (int i = 0; i < q.cells.size(); i++) {
- Map<PosKey,Cell>::Element *E=tile_map.find( q.cells[i] );
- Cell &c=E->get();
+ Map<PosKey, Cell>::Element *E = tile_map.find(q.cells[i]);
+ Cell &c = E->get();
//moment of truth
if (!tile_set->has_tile(c.id))
continue;
@@ -342,57 +329,55 @@ void TileMap::_update_dirty_quadrants() {
RID canvas_item;
RID debug_canvas_item;
- if (prev_canvas_item==RID() || prev_material!=mat) {
+ if (prev_canvas_item == RID() || prev_material != mat) {
- canvas_item=vs->canvas_item_create();
+ canvas_item = vs->canvas_item_create();
if (mat.is_valid())
- vs->canvas_item_set_material(canvas_item,mat->get_rid());
- vs->canvas_item_set_parent( canvas_item, get_canvas_item() );
+ vs->canvas_item_set_material(canvas_item, mat->get_rid());
+ vs->canvas_item_set_parent(canvas_item, get_canvas_item());
Transform2D xform;
- xform.set_origin( q.pos );
- vs->canvas_item_set_transform( canvas_item, xform );
- vs->canvas_item_set_light_mask(canvas_item,get_light_mask());
+ xform.set_origin(q.pos);
+ vs->canvas_item_set_transform(canvas_item, xform);
+ vs->canvas_item_set_light_mask(canvas_item, get_light_mask());
q.canvas_items.push_back(canvas_item);
if (debug_shapes) {
- debug_canvas_item=vs->canvas_item_create();
- vs->canvas_item_set_parent( debug_canvas_item, canvas_item );
- vs->canvas_item_set_z_as_relative_to_parent(debug_canvas_item,false);
- vs->canvas_item_set_z(debug_canvas_item,VS::CANVAS_ITEM_Z_MAX-1);
+ debug_canvas_item = vs->canvas_item_create();
+ vs->canvas_item_set_parent(debug_canvas_item, canvas_item);
+ vs->canvas_item_set_z_as_relative_to_parent(debug_canvas_item, false);
+ vs->canvas_item_set_z(debug_canvas_item, VS::CANVAS_ITEM_Z_MAX - 1);
q.canvas_items.push_back(debug_canvas_item);
- prev_debug_canvas_item=debug_canvas_item;
+ prev_debug_canvas_item = debug_canvas_item;
}
- prev_canvas_item=canvas_item;
- prev_material=mat;
+ prev_canvas_item = canvas_item;
+ prev_material = mat;
} else {
- canvas_item=prev_canvas_item;
+ canvas_item = prev_canvas_item;
if (debug_shapes) {
- debug_canvas_item=prev_debug_canvas_item;
+ debug_canvas_item = prev_debug_canvas_item;
}
}
-
-
Rect2 r = tile_set->tile_get_region(c.id);
Size2 s = tex->get_size();
- if (r==Rect2())
+ if (r == Rect2())
s = tex->get_size();
else {
s = r.size;
- r.pos.x+=fp_adjust;
- r.pos.y+=fp_adjust;
- r.size.x-=fp_adjust*2.0;
- r.size.y-=fp_adjust*2.0;
+ r.pos.x += fp_adjust;
+ r.pos.y += fp_adjust;
+ r.size.x -= fp_adjust * 2.0;
+ r.size.y -= fp_adjust * 2.0;
}
Rect2 rect;
- rect.pos=offset.floor();
- rect.size=s;
+ rect.pos = offset.floor();
+ rect.size = s;
if (rect.size.y > rect.size.x) {
if ((c.flip_h && (c.flip_v || c.transpose)) || (c.flip_v && !c.transpose))
@@ -402,75 +387,72 @@ void TileMap::_update_dirty_quadrants() {
tile_ofs.x += rect.size.x - rect.size.y;
}
- /* rect.size.x+=fp_adjust;
+ /* rect.size.x+=fp_adjust;
rect.size.y+=fp_adjust;*/
if (c.transpose)
SWAP(tile_ofs.x, tile_ofs.y);
if (c.flip_h) {
- rect.size.x=-rect.size.x;
- tile_ofs.x=-tile_ofs.x;
+ rect.size.x = -rect.size.x;
+ tile_ofs.x = -tile_ofs.x;
}
if (c.flip_v) {
- rect.size.y=-rect.size.y;
- tile_ofs.y=-tile_ofs.y;
+ rect.size.y = -rect.size.y;
+ tile_ofs.y = -tile_ofs.y;
}
Vector2 center_ofs;
- if (tile_origin==TILE_ORIGIN_TOP_LEFT) {
- rect.pos+=tile_ofs;
-
- } else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT) {
-
- rect.pos+=tile_ofs;
-
- if(c.transpose)
- {
- if(c.flip_h)
- rect.pos.x-=cell_size.x;
+ if (tile_origin == TILE_ORIGIN_TOP_LEFT) {
+ rect.pos += tile_ofs;
+
+ } else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT) {
+
+ rect.pos += tile_ofs;
+
+ if (c.transpose) {
+ if (c.flip_h)
+ rect.pos.x -= cell_size.x;
else
- rect.pos.x+=cell_size.x;
+ rect.pos.x += cell_size.x;
} else {
- if(c.flip_v)
- rect.pos.y-=cell_size.y;
+ if (c.flip_v)
+ rect.pos.y -= cell_size.y;
else
- rect.pos.y+=cell_size.y;
+ rect.pos.y += cell_size.y;
}
-
- } else if (tile_origin==TILE_ORIGIN_CENTER) {
- rect.pos+=tcenter;
- Vector2 center = (s/2) - tile_ofs;
- center_ofs=tcenter-(s/2);
+ } else if (tile_origin == TILE_ORIGIN_CENTER) {
+ rect.pos += tcenter;
+
+ Vector2 center = (s / 2) - tile_ofs;
+ center_ofs = tcenter - (s / 2);
if (c.flip_h)
- rect.pos.x-=s.x-center.x;
+ rect.pos.x -= s.x - center.x;
else
- rect.pos.x-=center.x;
+ rect.pos.x -= center.x;
if (c.flip_v)
- rect.pos.y-=s.y-center.y;
+ rect.pos.y -= s.y - center.y;
else
- rect.pos.y-=center.y;
+ rect.pos.y -= center.y;
}
-
Color modulate = tile_set->tile_get_modulate(c.id);
Color self_modulate = get_self_modulate();
- modulate = Color(modulate.r*self_modulate.r, modulate.g*self_modulate.g,
- modulate.b*self_modulate.b, modulate.a*self_modulate.a);
- if (r==Rect2()) {
- tex->draw_rect(canvas_item,rect,false,modulate,c.transpose);
+ modulate = Color(modulate.r * self_modulate.r, modulate.g * self_modulate.g,
+ modulate.b * self_modulate.b, modulate.a * self_modulate.a);
+ if (r == Rect2()) {
+ tex->draw_rect(canvas_item, rect, false, modulate, c.transpose);
} else {
- tex->draw_rect_region(canvas_item,rect,r,modulate,c.transpose);
+ tex->draw_rect_region(canvas_item, rect, r, modulate, c.transpose);
}
- Vector< Ref<Shape2D> > shapes = tile_set->tile_get_shapes(c.id);
-
+ Vector<Ref<Shape2D> > shapes = tile_set->tile_get_shapes(c.id);
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
Ref<Shape2D> shape = shapes[i];
if (shape.is_valid()) {
@@ -479,21 +461,19 @@ void TileMap::_update_dirty_quadrants() {
Transform2D xform;
xform.set_origin(offset.floor());
- _fix_cell_transform(xform,c,shape_ofs+center_ofs,s);
+ _fix_cell_transform(xform, c, shape_ofs + center_ofs, s);
if (debug_canvas_item.is_valid()) {
- vs->canvas_item_add_set_transform(debug_canvas_item,xform);
- shape->draw(debug_canvas_item,debug_collision_color);
-
+ vs->canvas_item_add_set_transform(debug_canvas_item, xform);
+ shape->draw(debug_canvas_item, debug_collision_color);
}
- ps->body_add_shape(q.body,shape->get_rid(),xform);
- ps->body_set_shape_metadata(q.body,shape_idx++,Vector2(E->key().x,E->key().y));
-
+ ps->body_add_shape(q.body, shape->get_rid(), xform);
+ ps->body_set_shape_metadata(q.body, shape_idx++, Vector2(E->key().x, E->key().y));
}
}
if (debug_canvas_item.is_valid()) {
- vs->canvas_item_add_set_transform(debug_canvas_item,Transform2D());
+ vs->canvas_item_add_set_transform(debug_canvas_item, Transform2D());
}
if (navigation) {
@@ -501,145 +481,134 @@ void TileMap::_update_dirty_quadrants() {
if (navpoly.is_valid()) {
Vector2 npoly_ofs = tile_set->tile_get_navigation_polygon_offset(c.id);
Transform2D xform;
- xform.set_origin(offset.floor()+q.pos);
- _fix_cell_transform(xform,c,npoly_ofs+center_ofs,s);
+ xform.set_origin(offset.floor() + q.pos);
+ _fix_cell_transform(xform, c, npoly_ofs + center_ofs, s);
-
- int pid = navigation->navpoly_create(navpoly,nav_rel * xform);
+ int pid = navigation->navpoly_create(navpoly, nav_rel * xform);
Quadrant::NavPoly np;
- np.id=pid;
- np.xform=xform;
- q.navpoly_ids[E->key()]=np;
+ np.id = pid;
+ np.xform = xform;
+ q.navpoly_ids[E->key()] = np;
}
}
-
- Ref<OccluderPolygon2D> occluder=tile_set->tile_get_light_occluder(c.id);
+ Ref<OccluderPolygon2D> occluder = tile_set->tile_get_light_occluder(c.id);
if (occluder.is_valid()) {
Vector2 occluder_ofs = tile_set->tile_get_occluder_offset(c.id);
Transform2D xform;
- xform.set_origin(offset.floor()+q.pos);
- _fix_cell_transform(xform,c,occluder_ofs+center_ofs,s);
+ xform.set_origin(offset.floor() + q.pos);
+ _fix_cell_transform(xform, c, occluder_ofs + center_ofs, s);
RID orid = VS::get_singleton()->canvas_light_occluder_create();
- VS::get_singleton()->canvas_light_occluder_set_transform(orid,get_global_transform() * xform);
- VS::get_singleton()->canvas_light_occluder_set_polygon(orid,occluder->get_rid());
- VS::get_singleton()->canvas_light_occluder_attach_to_canvas(orid,get_canvas());
- VS::get_singleton()->canvas_light_occluder_set_light_mask(orid,occluder_light_mask);
+ VS::get_singleton()->canvas_light_occluder_set_transform(orid, get_global_transform() * xform);
+ VS::get_singleton()->canvas_light_occluder_set_polygon(orid, occluder->get_rid());
+ VS::get_singleton()->canvas_light_occluder_attach_to_canvas(orid, get_canvas());
+ VS::get_singleton()->canvas_light_occluder_set_light_mask(orid, occluder_light_mask);
Quadrant::Occluder oc;
- oc.xform=xform;
- oc.id=orid;
- q.occluder_instances[E->key()]=oc;
+ oc.xform = xform;
+ oc.id = orid;
+ q.occluder_instances[E->key()] = oc;
}
}
- dirty_quadrant_list.remove( dirty_quadrant_list.first() );
- quadrant_order_dirty=true;
+ dirty_quadrant_list.remove(dirty_quadrant_list.first());
+ quadrant_order_dirty = true;
}
-
-
- pending_update=false;
+ pending_update = false;
if (quadrant_order_dirty) {
- int index=-0x80000000; //always must be drawn below children
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ int index = -0x80000000; //always must be drawn below children
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- for (List<RID>::Element *E=q.canvas_items.front();E;E=E->next()) {
+ Quadrant &q = E->get();
+ for (List<RID>::Element *E = q.canvas_items.front(); E; E = E->next()) {
- VS::get_singleton()->canvas_item_set_draw_index(E->get(),index++);
+ VS::get_singleton()->canvas_item_set_draw_index(E->get(), index++);
}
}
- quadrant_order_dirty=false;
+ quadrant_order_dirty = false;
}
_recompute_rect_cache();
-
}
void TileMap::_recompute_rect_cache() {
-
#ifdef DEBUG_ENABLED
if (!rect_cache_dirty)
return;
Rect2 r_total;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
-
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
Rect2 r;
- r.pos=_map_to_world(E->key().x*_get_quadrant_size(), E->key().y*_get_quadrant_size());
- r.expand_to( _map_to_world(E->key().x*_get_quadrant_size()+_get_quadrant_size(), E->key().y*_get_quadrant_size()) );
- r.expand_to( _map_to_world(E->key().x*_get_quadrant_size()+_get_quadrant_size(), E->key().y*_get_quadrant_size()+_get_quadrant_size()) );
- r.expand_to( _map_to_world(E->key().x*_get_quadrant_size(), E->key().y*_get_quadrant_size()+_get_quadrant_size()) );
- if (E==quadrant_map.front())
- r_total=r;
+ r.pos = _map_to_world(E->key().x * _get_quadrant_size(), E->key().y * _get_quadrant_size());
+ r.expand_to(_map_to_world(E->key().x * _get_quadrant_size() + _get_quadrant_size(), E->key().y * _get_quadrant_size()));
+ r.expand_to(_map_to_world(E->key().x * _get_quadrant_size() + _get_quadrant_size(), E->key().y * _get_quadrant_size() + _get_quadrant_size()));
+ r.expand_to(_map_to_world(E->key().x * _get_quadrant_size(), E->key().y * _get_quadrant_size() + _get_quadrant_size()));
+ if (E == quadrant_map.front())
+ r_total = r;
else
- r_total=r_total.merge(r);
-
+ r_total = r_total.merge(r);
}
- if (r_total==Rect2()) {
- rect_cache=Rect2(-10,-10,20,20);
+ if (r_total == Rect2()) {
+ rect_cache = Rect2(-10, -10, 20, 20);
} else {
- rect_cache=r_total.grow(MAX(cell_size.x,cell_size.y)*_get_quadrant_size());
+ rect_cache = r_total.grow(MAX(cell_size.x, cell_size.y) * _get_quadrant_size());
}
item_rect_changed();
- rect_cache_dirty=false;
+ rect_cache_dirty = false;
#endif
-
-
}
-Map<TileMap::PosKey,TileMap::Quadrant>::Element *TileMap::_create_quadrant(const PosKey& p_qk) {
+Map<TileMap::PosKey, TileMap::Quadrant>::Element *TileMap::_create_quadrant(const PosKey &p_qk) {
Transform2D xform;
//xform.set_origin(Point2(p_qk.x,p_qk.y)*cell_size*quadrant_size);
Quadrant q;
- q.pos = _map_to_world(p_qk.x*_get_quadrant_size(),p_qk.y*_get_quadrant_size());
- q.pos+=get_cell_draw_offset();
- if (tile_origin==TILE_ORIGIN_CENTER)
- q.pos+=cell_size/2;
- else if (tile_origin==TILE_ORIGIN_BOTTOM_LEFT)
- q.pos.y+=cell_size.y;
-
-
- xform.set_origin( q.pos );
+ q.pos = _map_to_world(p_qk.x * _get_quadrant_size(), p_qk.y * _get_quadrant_size());
+ q.pos += get_cell_draw_offset();
+ if (tile_origin == TILE_ORIGIN_CENTER)
+ q.pos += cell_size / 2;
+ else if (tile_origin == TILE_ORIGIN_BOTTOM_LEFT)
+ q.pos.y += cell_size.y;
+
+ xform.set_origin(q.pos);
//q.canvas_item = VisualServer::get_singleton()->canvas_item_create();
- q.body=Physics2DServer::get_singleton()->body_create(use_kinematic?Physics2DServer::BODY_MODE_KINEMATIC:Physics2DServer::BODY_MODE_STATIC);
- Physics2DServer::get_singleton()->body_attach_object_instance_ID(q.body,get_instance_ID());
- Physics2DServer::get_singleton()->body_set_layer_mask(q.body,collision_layer);
- Physics2DServer::get_singleton()->body_set_collision_mask(q.body,collision_mask);
- Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_FRICTION,friction);
- Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_BOUNCE,bounce);
+ q.body = Physics2DServer::get_singleton()->body_create(use_kinematic ? Physics2DServer::BODY_MODE_KINEMATIC : Physics2DServer::BODY_MODE_STATIC);
+ Physics2DServer::get_singleton()->body_attach_object_instance_ID(q.body, get_instance_ID());
+ Physics2DServer::get_singleton()->body_set_layer_mask(q.body, collision_layer);
+ Physics2DServer::get_singleton()->body_set_collision_mask(q.body, collision_mask);
+ Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_FRICTION, friction);
+ Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_BOUNCE, bounce);
if (is_inside_tree()) {
xform = get_global_transform() * xform;
RID space = get_world_2d()->get_space();
- Physics2DServer::get_singleton()->body_set_space(q.body,space);
+ Physics2DServer::get_singleton()->body_set_space(q.body, space);
}
- Physics2DServer::get_singleton()->body_set_state(q.body,Physics2DServer::BODY_STATE_TRANSFORM,xform);
+ Physics2DServer::get_singleton()->body_set_state(q.body, Physics2DServer::BODY_STATE_TRANSFORM, xform);
- rect_cache_dirty=true;
- quadrant_order_dirty=true;
- return quadrant_map.insert(p_qk,q);
+ rect_cache_dirty = true;
+ quadrant_order_dirty = true;
+ return quadrant_map.insert(p_qk, q);
}
-void TileMap::_erase_quadrant(Map<PosKey,Quadrant>::Element *Q) {
+void TileMap::_erase_quadrant(Map<PosKey, Quadrant>::Element *Q) {
- Quadrant &q=Q->get();
+ Quadrant &q = Q->get();
Physics2DServer::get_singleton()->free(q.body);
- for (List<RID>::Element *E=q.canvas_items.front();E;E=E->next()) {
+ for (List<RID>::Element *E = q.canvas_items.front(); E; E = E->next()) {
VisualServer::get_singleton()->free(E->get());
}
@@ -648,58 +617,58 @@ void TileMap::_erase_quadrant(Map<PosKey,Quadrant>::Element *Q) {
dirty_quadrant_list.remove(&q.dirty_list);
if (navigation) {
- for(Map<PosKey,Quadrant::NavPoly>::Element *E=q.navpoly_ids.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::NavPoly>::Element *E = q.navpoly_ids.front(); E; E = E->next()) {
navigation->navpoly_remove(E->get().id);
}
q.navpoly_ids.clear();
}
- for(Map<PosKey,Quadrant::Occluder>::Element *E=q.occluder_instances.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant::Occluder>::Element *E = q.occluder_instances.front(); E; E = E->next()) {
VS::get_singleton()->free(E->get().id);
}
q.occluder_instances.clear();
quadrant_map.erase(Q);
- rect_cache_dirty=true;
+ rect_cache_dirty = true;
}
-void TileMap::_make_quadrant_dirty(Map<PosKey,Quadrant>::Element *Q) {
+void TileMap::_make_quadrant_dirty(Map<PosKey, Quadrant>::Element *Q) {
- Quadrant &q=Q->get();
+ Quadrant &q = Q->get();
if (!q.dirty_list.in_list())
dirty_quadrant_list.add(&q.dirty_list);
if (pending_update)
return;
- pending_update=true;
+ pending_update = true;
if (!is_inside_tree())
return;
call_deferred("_update_dirty_quadrants");
}
-void TileMap::set_cellv(const Vector2& p_pos,int p_tile,bool p_flip_x,bool p_flip_y,bool p_transpose) {
+void TileMap::set_cellv(const Vector2 &p_pos, int p_tile, bool p_flip_x, bool p_flip_y, bool p_transpose) {
- set_cell(p_pos.x,p_pos.y,p_tile,p_flip_x,p_flip_y,p_transpose);
+ set_cell(p_pos.x, p_pos.y, p_tile, p_flip_x, p_flip_y, p_transpose);
}
-void TileMap::set_cell(int p_x,int p_y,int p_tile,bool p_flip_x,bool p_flip_y,bool p_transpose) {
+void TileMap::set_cell(int p_x, int p_y, int p_tile, bool p_flip_x, bool p_flip_y, bool p_transpose) {
- PosKey pk(p_x,p_y);
+ PosKey pk(p_x, p_y);
- Map<PosKey,Cell>::Element *E=tile_map.find(pk);
- if (!E && p_tile==INVALID_CELL)
+ Map<PosKey, Cell>::Element *E = tile_map.find(pk);
+ if (!E && p_tile == INVALID_CELL)
return; //nothing to do
- PosKey qk(p_x/_get_quadrant_size(),p_y/_get_quadrant_size());
- if (p_tile==INVALID_CELL) {
+ PosKey qk(p_x / _get_quadrant_size(), p_y / _get_quadrant_size());
+ if (p_tile == INVALID_CELL) {
//erase existing
tile_map.erase(pk);
- Map<PosKey,Quadrant>::Element *Q = quadrant_map.find(qk);
+ Map<PosKey, Quadrant>::Element *Q = quadrant_map.find(qk);
ERR_FAIL_COND(!Q);
- Quadrant &q=Q->get();
+ Quadrant &q = Q->get();
q.cells.erase(pk);
- if (q.cells.size()==0)
+ if (q.cells.size() == 0)
_erase_quadrant(Q);
else
_make_quadrant_dirty(Q);
@@ -707,79 +676,75 @@ void TileMap::set_cell(int p_x,int p_y,int p_tile,bool p_flip_x,bool p_flip_y,bo
return;
}
- Map<PosKey,Quadrant>::Element *Q = quadrant_map.find(qk);
+ Map<PosKey, Quadrant>::Element *Q = quadrant_map.find(qk);
if (!E) {
- E=tile_map.insert(pk,Cell());
+ E = tile_map.insert(pk, Cell());
if (!Q) {
- Q=_create_quadrant(qk);
+ Q = _create_quadrant(qk);
}
- Quadrant &q=Q->get();
+ Quadrant &q = Q->get();
q.cells.insert(pk);
} else {
ERR_FAIL_COND(!Q); // quadrant should exist...
- if (E->get().id==p_tile && E->get().flip_h==p_flip_x && E->get().flip_v==p_flip_y && E->get().transpose==p_transpose)
+ if (E->get().id == p_tile && E->get().flip_h == p_flip_x && E->get().flip_v == p_flip_y && E->get().transpose == p_transpose)
return; //nothing changed
-
}
-
Cell &c = E->get();
- c.id=p_tile;
- c.flip_h=p_flip_x;
- c.flip_v=p_flip_y;
- c.transpose=p_transpose;
+ c.id = p_tile;
+ c.flip_h = p_flip_x;
+ c.flip_v = p_flip_y;
+ c.transpose = p_transpose;
_make_quadrant_dirty(Q);
- used_size_cache_dirty=true;
-
+ used_size_cache_dirty = true;
}
-int TileMap::get_cellv(const Vector2& p_pos) const {
- return get_cell(p_pos.x,p_pos.y);
+int TileMap::get_cellv(const Vector2 &p_pos) const {
+ return get_cell(p_pos.x, p_pos.y);
}
-int TileMap::get_cell(int p_x,int p_y) const {
+int TileMap::get_cell(int p_x, int p_y) const {
- PosKey pk(p_x,p_y);
+ PosKey pk(p_x, p_y);
- const Map<PosKey,Cell>::Element *E=tile_map.find(pk);
+ const Map<PosKey, Cell>::Element *E = tile_map.find(pk);
if (!E)
return INVALID_CELL;
return E->get().id;
-
}
-bool TileMap::is_cell_x_flipped(int p_x,int p_y) const {
+bool TileMap::is_cell_x_flipped(int p_x, int p_y) const {
- PosKey pk(p_x,p_y);
+ PosKey pk(p_x, p_y);
- const Map<PosKey,Cell>::Element *E=tile_map.find(pk);
+ const Map<PosKey, Cell>::Element *E = tile_map.find(pk);
if (!E)
return false;
return E->get().flip_h;
}
-bool TileMap::is_cell_y_flipped(int p_x,int p_y) const {
+bool TileMap::is_cell_y_flipped(int p_x, int p_y) const {
- PosKey pk(p_x,p_y);
+ PosKey pk(p_x, p_y);
- const Map<PosKey,Cell>::Element *E=tile_map.find(pk);
+ const Map<PosKey, Cell>::Element *E = tile_map.find(pk);
if (!E)
return false;
return E->get().flip_v;
}
-bool TileMap::is_cell_transposed(int p_x,int p_y) const {
+bool TileMap::is_cell_transposed(int p_x, int p_y) const {
- PosKey pk(p_x,p_y);
+ PosKey pk(p_x, p_y);
- const Map<PosKey,Cell>::Element *E=tile_map.find(pk);
+ const Map<PosKey, Cell>::Element *E = tile_map.find(pk);
if (!E)
return false;
@@ -787,34 +752,29 @@ bool TileMap::is_cell_transposed(int p_x,int p_y) const {
return E->get().transpose;
}
-
void TileMap::_recreate_quadrants() {
_clear_quadrants();
- for (Map<PosKey,Cell>::Element *E=tile_map.front();E;E=E->next()) {
+ for (Map<PosKey, Cell>::Element *E = tile_map.front(); E; E = E->next()) {
- PosKey qk(E->key().x/_get_quadrant_size(),E->key().y/_get_quadrant_size());
+ PosKey qk(E->key().x / _get_quadrant_size(), E->key().y / _get_quadrant_size());
- Map<PosKey,Quadrant>::Element *Q=quadrant_map.find(qk);
+ Map<PosKey, Quadrant>::Element *Q = quadrant_map.find(qk);
if (!Q) {
- Q=_create_quadrant(qk);
+ Q = _create_quadrant(qk);
dirty_quadrant_list.add(&Q->get().dirty_list);
}
Q->get().cells.insert(E->key());
_make_quadrant_dirty(Q);
}
-
-
-
}
-
void TileMap::_clear_quadrants() {
while (quadrant_map.size()) {
- _erase_quadrant( quadrant_map.front() );
+ _erase_quadrant(quadrant_map.front());
}
}
@@ -822,107 +782,101 @@ void TileMap::clear() {
_clear_quadrants();
tile_map.clear();
- used_size_cache_dirty=true;
+ used_size_cache_dirty = true;
}
-void TileMap::_set_tile_data(const PoolVector<int>& p_data) {
+void TileMap::_set_tile_data(const PoolVector<int> &p_data) {
- int c=p_data.size();
+ int c = p_data.size();
PoolVector<int>::Read r = p_data.read();
+ for (int i = 0; i < c; i += 2) {
- for(int i=0;i<c;i+=2) {
-
- const uint8_t *ptr=(const uint8_t*)&r[i];
+ const uint8_t *ptr = (const uint8_t *)&r[i];
uint8_t local[8];
- for(int j=0;j<8;j++)
- local[j]=ptr[j];
+ for (int j = 0; j < 8; j++)
+ local[j] = ptr[j];
#ifdef BIG_ENDIAN_ENABLED
-
- SWAP(local[0],local[3]);
- SWAP(local[1],local[2]);
- SWAP(local[4],local[7]);
- SWAP(local[5],local[6]);
+ SWAP(local[0], local[3]);
+ SWAP(local[1], local[2]);
+ SWAP(local[4], local[7]);
+ SWAP(local[5], local[6]);
#endif
int16_t x = decode_uint16(&local[0]);
int16_t y = decode_uint16(&local[2]);
uint32_t v = decode_uint32(&local[4]);
- bool flip_h = v&(1<<29);
- bool flip_v = v&(1<<30);
- bool transpose = v&(1<<31);
- v&=(1<<29)-1;
+ bool flip_h = v & (1 << 29);
+ bool flip_v = v & (1 << 30);
+ bool transpose = v & (1 << 31);
+ v &= (1 << 29) - 1;
/*
if (x<-20 || y <-20 || x>4000 || y>4000)
continue;
*/
- set_cell(x,y,v,flip_h,flip_v,transpose);
-
+ set_cell(x, y, v, flip_h, flip_v, transpose);
}
-
}
PoolVector<int> TileMap::_get_tile_data() const {
PoolVector<int> data;
- data.resize(tile_map.size()*2);
+ data.resize(tile_map.size() * 2);
PoolVector<int>::Write w = data.write();
- int idx=0;
- for(const Map<PosKey,Cell>::Element *E=tile_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<PosKey, Cell>::Element *E = tile_map.front(); E; E = E->next()) {
- uint8_t *ptr = (uint8_t*)&w[idx];
- encode_uint16(E->key().x,&ptr[0]);
- encode_uint16(E->key().y,&ptr[2]);
+ uint8_t *ptr = (uint8_t *)&w[idx];
+ encode_uint16(E->key().x, &ptr[0]);
+ encode_uint16(E->key().y, &ptr[2]);
uint32_t val = E->get().id;
if (E->get().flip_h)
- val|=(1<<29);
+ val |= (1 << 29);
if (E->get().flip_v)
- val|=(1<<30);
+ val |= (1 << 30);
if (E->get().transpose)
- val|=(1<<31);
+ val |= (1 << 31);
- encode_uint32(val,&ptr[4]);
- idx+=2;
+ encode_uint32(val, &ptr[4]);
+ idx += 2;
}
-
w = PoolVector<int>::Write();
return data;
-
}
Rect2 TileMap::get_item_rect() const {
- const_cast<TileMap*>(this)->_update_dirty_quadrants();
+ const_cast<TileMap *>(this)->_update_dirty_quadrants();
return rect_cache;
}
void TileMap::set_collision_layer(uint32_t p_layer) {
- collision_layer=p_layer;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ collision_layer = p_layer;
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- Physics2DServer::get_singleton()->body_set_layer_mask(q.body,collision_layer);
+ Quadrant &q = E->get();
+ Physics2DServer::get_singleton()->body_set_layer_mask(q.body, collision_layer);
}
}
void TileMap::set_collision_mask(uint32_t p_mask) {
- collision_mask=p_mask;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ collision_mask = p_mask;
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- Physics2DServer::get_singleton()->body_set_collision_mask(q.body,collision_mask);
+ Quadrant &q = E->get();
+ Physics2DServer::get_singleton()->body_set_collision_mask(q.body, collision_mask);
}
}
-bool TileMap::get_collision_use_kinematic() const{
+bool TileMap::get_collision_use_kinematic() const {
return use_kinematic;
}
@@ -930,42 +884,39 @@ bool TileMap::get_collision_use_kinematic() const{
void TileMap::set_collision_use_kinematic(bool p_use_kinematic) {
_clear_quadrants();
- use_kinematic=p_use_kinematic;
+ use_kinematic = p_use_kinematic;
_recreate_quadrants();
}
void TileMap::set_collision_friction(float p_friction) {
- friction=p_friction;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ friction = p_friction;
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_FRICTION,p_friction);
+ Quadrant &q = E->get();
+ Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_FRICTION, p_friction);
}
-
}
-float TileMap::get_collision_friction() const{
+float TileMap::get_collision_friction() const {
return friction;
}
-void TileMap::set_collision_bounce(float p_bounce){
+void TileMap::set_collision_bounce(float p_bounce) {
- bounce=p_bounce;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ bounce = p_bounce;
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- Quadrant &q=E->get();
- Physics2DServer::get_singleton()->body_set_param(q.body,Physics2DServer::BODY_PARAM_BOUNCE,p_bounce);
+ Quadrant &q = E->get();
+ Physics2DServer::get_singleton()->body_set_param(q.body, Physics2DServer::BODY_PARAM_BOUNCE, p_bounce);
}
-
}
-float TileMap::get_collision_bounce() const{
+float TileMap::get_collision_bounce() const {
return bounce;
}
-
uint32_t TileMap::get_collision_layer() const {
return collision_layer;
@@ -979,7 +930,7 @@ uint32_t TileMap::get_collision_mask() const {
void TileMap::set_mode(Mode p_mode) {
_clear_quadrants();
- mode=p_mode;
+ mode = p_mode;
_recreate_quadrants();
emit_signal("settings_changed");
}
@@ -991,7 +942,7 @@ TileMap::Mode TileMap::get_mode() const {
void TileMap::set_half_offset(HalfOffset p_half_offset) {
_clear_quadrants();
- half_offset=p_half_offset;
+ half_offset = p_half_offset;
_recreate_quadrants();
emit_signal("settings_changed");
}
@@ -999,20 +950,19 @@ void TileMap::set_half_offset(HalfOffset p_half_offset) {
void TileMap::set_tile_origin(TileOrigin p_tile_origin) {
_clear_quadrants();
- tile_origin=p_tile_origin;
+ tile_origin = p_tile_origin;
_recreate_quadrants();
emit_signal("settings_changed");
}
-TileMap::TileOrigin TileMap::get_tile_origin() const{
+TileMap::TileOrigin TileMap::get_tile_origin() const {
return tile_origin;
}
-
Vector2 TileMap::get_cell_draw_offset() const {
- switch(mode) {
+ switch (mode) {
case MODE_SQUARE: {
@@ -1020,22 +970,21 @@ Vector2 TileMap::get_cell_draw_offset() const {
} break;
case MODE_ISOMETRIC: {
- return Vector2(-cell_size.x*0.5,0);
+ return Vector2(-cell_size.x * 0.5, 0);
} break;
case MODE_CUSTOM: {
Vector2 min;
- min.x = MIN(custom_transform[0].x,min.x);
- min.y = MIN(custom_transform[0].y,min.y);
- min.x = MIN(custom_transform[1].x,min.x);
- min.y = MIN(custom_transform[1].y,min.y);
+ min.x = MIN(custom_transform[0].x, min.x);
+ min.y = MIN(custom_transform[0].y, min.y);
+ min.x = MIN(custom_transform[1].x, min.x);
+ min.y = MIN(custom_transform[1].y, min.y);
return min;
} break;
}
return Vector2();
-
}
TileMap::HalfOffset TileMap::get_half_offset() const {
@@ -1044,13 +993,13 @@ TileMap::HalfOffset TileMap::get_half_offset() const {
Transform2D TileMap::get_cell_transform() const {
- switch(mode) {
+ switch (mode) {
case MODE_SQUARE: {
Transform2D m;
- m[0]*=cell_size.x;
- m[1]*=cell_size.y;
+ m[0] *= cell_size.x;
+ m[1] *= cell_size.y;
return m;
} break;
case MODE_ISOMETRIC: {
@@ -1058,8 +1007,8 @@ Transform2D TileMap::get_cell_transform() const {
//isometric only makes sense when y is positive in both x and y vectors, otherwise
//the drawing of tiles will overlap
Transform2D m;
- m[0]=Vector2(cell_size.x*0.5,cell_size.y*0.5);
- m[1]=Vector2(-cell_size.x*0.5,cell_size.y*0.5);
+ m[0] = Vector2(cell_size.x * 0.5, cell_size.y * 0.5);
+ m[1] = Vector2(-cell_size.x * 0.5, cell_size.y * 0.5);
return m;
} break;
@@ -1072,35 +1021,34 @@ Transform2D TileMap::get_cell_transform() const {
return Transform2D();
}
-void TileMap::set_custom_transform(const Transform2D& p_xform) {
+void TileMap::set_custom_transform(const Transform2D &p_xform) {
_clear_quadrants();
- custom_transform=p_xform;
+ custom_transform = p_xform;
_recreate_quadrants();
emit_signal("settings_changed");
-
}
-Transform2D TileMap::get_custom_transform() const{
+Transform2D TileMap::get_custom_transform() const {
return custom_transform;
}
-Vector2 TileMap::_map_to_world(int x,int y,bool p_ignore_ofs) const {
+Vector2 TileMap::_map_to_world(int x, int y, bool p_ignore_ofs) const {
- Vector2 ret = get_cell_transform().xform(Vector2(x,y));
+ Vector2 ret = get_cell_transform().xform(Vector2(x, y));
if (!p_ignore_ofs) {
- switch(half_offset) {
+ switch (half_offset) {
case HALF_OFFSET_X: {
- if (ABS(y)&1) {
+ if (ABS(y) & 1) {
- ret+=get_cell_transform()[0]*0.5;
+ ret += get_cell_transform()[0] * 0.5;
}
} break;
case HALF_OFFSET_Y: {
- if (ABS(x)&1) {
- ret+=get_cell_transform()[1]*0.5;
+ if (ABS(x) & 1) {
+ ret += get_cell_transform()[1] * 0.5;
}
} break;
default: {}
@@ -1108,25 +1056,24 @@ Vector2 TileMap::_map_to_world(int x,int y,bool p_ignore_ofs) const {
}
return ret;
}
-Vector2 TileMap::map_to_world(const Vector2& p_pos,bool p_ignore_ofs) const {
+Vector2 TileMap::map_to_world(const Vector2 &p_pos, bool p_ignore_ofs) const {
- return _map_to_world(p_pos.x,p_pos.y,p_ignore_ofs);
+ return _map_to_world(p_pos.x, p_pos.y, p_ignore_ofs);
}
-Vector2 TileMap::world_to_map(const Vector2& p_pos) const{
+Vector2 TileMap::world_to_map(const Vector2 &p_pos) const {
Vector2 ret = get_cell_transform().affine_inverse().xform(p_pos);
-
- switch(half_offset) {
+ switch (half_offset) {
case HALF_OFFSET_X: {
- if ( ret.y > 0 ? int(ret.y)&1 : (int(ret.y)-1)&1 ) {
- ret.x-=0.5;
+ if (ret.y > 0 ? int(ret.y) & 1 : (int(ret.y) - 1) & 1) {
+ ret.x -= 0.5;
}
} break;
case HALF_OFFSET_Y: {
- if ( ret.x > 0 ? int(ret.x)&1 : (int(ret.x)-1)&1) {
- ret.y-=0.5;
+ if (ret.x > 0 ? int(ret.x) & 1 : (int(ret.x) - 1) & 1) {
+ ret.y -= 0.5;
}
} break;
default: {}
@@ -1138,11 +1085,10 @@ Vector2 TileMap::world_to_map(const Vector2& p_pos) const{
void TileMap::set_y_sort_mode(bool p_enable) {
_clear_quadrants();
- y_sort_mode=p_enable;
- VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),y_sort_mode);
+ y_sort_mode = p_enable;
+ VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), y_sort_mode);
_recreate_quadrants();
emit_signal("settings_changed");
-
}
bool TileMap::is_y_sort_mode_enabled() const {
@@ -1154,11 +1100,11 @@ Array TileMap::get_used_cells() const {
Array a;
a.resize(tile_map.size());
- int i=0;
- for (Map<PosKey,Cell>::Element *E=tile_map.front();E;E=E->next()) {
+ int i = 0;
+ for (Map<PosKey, Cell>::Element *E = tile_map.front(); E; E = E->next()) {
- Vector2 p (E->key().x,E->key().y);
- a[i++]=p;
+ Vector2 p(E->key().x, E->key().y);
+ a[i++] = p;
}
return a;
@@ -1167,14 +1113,14 @@ Array TileMap::get_used_cells() const {
Rect2 TileMap::get_used_rect() { // Not const because of cache
if (used_size_cache_dirty) {
- if(tile_map.size() > 0) {
+ if (tile_map.size() > 0) {
used_size_cache = Rect2(tile_map.front()->key().x, tile_map.front()->key().y, 0, 0);
- for (Map<PosKey,Cell>::Element *E=tile_map.front();E;E=E->next()) {
+ for (Map<PosKey, Cell>::Element *E = tile_map.front(); E; E = E->next()) {
used_size_cache.expand_to(Vector2(E->key().x, E->key().y));
}
- used_size_cache.size += Vector2(1,1);
+ used_size_cache.size += Vector2(1, 1);
} else {
used_size_cache = Rect2();
}
@@ -1185,19 +1131,18 @@ Rect2 TileMap::get_used_rect() { // Not const because of cache
return used_size_cache;
}
-
void TileMap::set_occluder_light_mask(int p_mask) {
- occluder_light_mask=p_mask;
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ occluder_light_mask = p_mask;
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- for (Map<PosKey,Quadrant::Occluder>::Element *F=E->get().occluder_instances.front();F;F=F->next()) {
- VisualServer::get_singleton()->canvas_light_occluder_set_light_mask(F->get().id,occluder_light_mask);
+ for (Map<PosKey, Quadrant::Occluder>::Element *F = E->get().occluder_instances.front(); F; F = F->next()) {
+ VisualServer::get_singleton()->canvas_light_occluder_set_light_mask(F->get().id, occluder_light_mask);
}
}
}
-int TileMap::get_occluder_light_mask() const{
+int TileMap::get_occluder_light_mask() const {
return occluder_light_mask;
}
@@ -1205,154 +1150,150 @@ int TileMap::get_occluder_light_mask() const{
void TileMap::set_light_mask(int p_light_mask) {
CanvasItem::set_light_mask(p_light_mask);
- for (Map<PosKey,Quadrant>::Element *E=quadrant_map.front();E;E=E->next()) {
+ for (Map<PosKey, Quadrant>::Element *E = quadrant_map.front(); E; E = E->next()) {
- for (List<RID>::Element *F=E->get().canvas_items.front();F;F=F->next()) {
- VisualServer::get_singleton()->canvas_item_set_light_mask(F->get(),get_light_mask());
+ for (List<RID>::Element *F = E->get().canvas_items.front(); F; F = F->next()) {
+ VisualServer::get_singleton()->canvas_item_set_light_mask(F->get(), get_light_mask());
}
}
}
void TileMap::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_tileset", "tileset:TileSet"), &TileMap::set_tileset);
+ ClassDB::bind_method(D_METHOD("get_tileset:TileSet"), &TileMap::get_tileset);
- ClassDB::bind_method(D_METHOD("set_tileset","tileset:TileSet"),&TileMap::set_tileset);
- ClassDB::bind_method(D_METHOD("get_tileset:TileSet"),&TileMap::get_tileset);
-
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&TileMap::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&TileMap::get_mode);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &TileMap::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &TileMap::get_mode);
- ClassDB::bind_method(D_METHOD("set_half_offset","half_offset"),&TileMap::set_half_offset);
- ClassDB::bind_method(D_METHOD("get_half_offset"),&TileMap::get_half_offset);
+ ClassDB::bind_method(D_METHOD("set_half_offset", "half_offset"), &TileMap::set_half_offset);
+ ClassDB::bind_method(D_METHOD("get_half_offset"), &TileMap::get_half_offset);
- ClassDB::bind_method(D_METHOD("set_custom_transform","custom_transform"),&TileMap::set_custom_transform);
- ClassDB::bind_method(D_METHOD("get_custom_transform"),&TileMap::get_custom_transform);
+ ClassDB::bind_method(D_METHOD("set_custom_transform", "custom_transform"), &TileMap::set_custom_transform);
+ ClassDB::bind_method(D_METHOD("get_custom_transform"), &TileMap::get_custom_transform);
- ClassDB::bind_method(D_METHOD("set_cell_size","size"),&TileMap::set_cell_size);
- ClassDB::bind_method(D_METHOD("get_cell_size"),&TileMap::get_cell_size);
+ ClassDB::bind_method(D_METHOD("set_cell_size", "size"), &TileMap::set_cell_size);
+ ClassDB::bind_method(D_METHOD("get_cell_size"), &TileMap::get_cell_size);
- ClassDB::bind_method(D_METHOD("_set_old_cell_size","size"),&TileMap::_set_old_cell_size);
- ClassDB::bind_method(D_METHOD("_get_old_cell_size"),&TileMap::_get_old_cell_size);
+ ClassDB::bind_method(D_METHOD("_set_old_cell_size", "size"), &TileMap::_set_old_cell_size);
+ ClassDB::bind_method(D_METHOD("_get_old_cell_size"), &TileMap::_get_old_cell_size);
- ClassDB::bind_method(D_METHOD("set_quadrant_size","size"),&TileMap::set_quadrant_size);
- ClassDB::bind_method(D_METHOD("get_quadrant_size"),&TileMap::get_quadrant_size);
+ ClassDB::bind_method(D_METHOD("set_quadrant_size", "size"), &TileMap::set_quadrant_size);
+ ClassDB::bind_method(D_METHOD("get_quadrant_size"), &TileMap::get_quadrant_size);
- ClassDB::bind_method(D_METHOD("set_tile_origin","origin"),&TileMap::set_tile_origin);
- ClassDB::bind_method(D_METHOD("get_tile_origin"),&TileMap::get_tile_origin);
+ ClassDB::bind_method(D_METHOD("set_tile_origin", "origin"), &TileMap::set_tile_origin);
+ ClassDB::bind_method(D_METHOD("get_tile_origin"), &TileMap::get_tile_origin);
- ClassDB::bind_method(D_METHOD("set_center_x","enable"),&TileMap::set_center_x);
- ClassDB::bind_method(D_METHOD("get_center_x"),&TileMap::get_center_x);
+ ClassDB::bind_method(D_METHOD("set_center_x", "enable"), &TileMap::set_center_x);
+ ClassDB::bind_method(D_METHOD("get_center_x"), &TileMap::get_center_x);
- ClassDB::bind_method(D_METHOD("set_center_y","enable"),&TileMap::set_center_y);
- ClassDB::bind_method(D_METHOD("get_center_y"),&TileMap::get_center_y);
+ ClassDB::bind_method(D_METHOD("set_center_y", "enable"), &TileMap::set_center_y);
+ ClassDB::bind_method(D_METHOD("get_center_y"), &TileMap::get_center_y);
- ClassDB::bind_method(D_METHOD("set_y_sort_mode","enable"),&TileMap::set_y_sort_mode);
- ClassDB::bind_method(D_METHOD("is_y_sort_mode_enabled"),&TileMap::is_y_sort_mode_enabled);
+ ClassDB::bind_method(D_METHOD("set_y_sort_mode", "enable"), &TileMap::set_y_sort_mode);
+ ClassDB::bind_method(D_METHOD("is_y_sort_mode_enabled"), &TileMap::is_y_sort_mode_enabled);
- ClassDB::bind_method(D_METHOD("set_collision_use_kinematic","use_kinematic"),&TileMap::set_collision_use_kinematic);
- ClassDB::bind_method(D_METHOD("get_collision_use_kinematic"),&TileMap::get_collision_use_kinematic);
+ ClassDB::bind_method(D_METHOD("set_collision_use_kinematic", "use_kinematic"), &TileMap::set_collision_use_kinematic);
+ ClassDB::bind_method(D_METHOD("get_collision_use_kinematic"), &TileMap::get_collision_use_kinematic);
- ClassDB::bind_method(D_METHOD("set_collision_layer","mask"),&TileMap::set_collision_layer);
- ClassDB::bind_method(D_METHOD("get_collision_layer"),&TileMap::get_collision_layer);
+ ClassDB::bind_method(D_METHOD("set_collision_layer", "mask"), &TileMap::set_collision_layer);
+ ClassDB::bind_method(D_METHOD("get_collision_layer"), &TileMap::get_collision_layer);
- ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&TileMap::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"),&TileMap::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &TileMap::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &TileMap::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_collision_friction","value"),&TileMap::set_collision_friction);
- ClassDB::bind_method(D_METHOD("get_collision_friction"),&TileMap::get_collision_friction);
+ ClassDB::bind_method(D_METHOD("set_collision_friction", "value"), &TileMap::set_collision_friction);
+ ClassDB::bind_method(D_METHOD("get_collision_friction"), &TileMap::get_collision_friction);
- ClassDB::bind_method(D_METHOD("set_collision_bounce","value"),&TileMap::set_collision_bounce);
- ClassDB::bind_method(D_METHOD("get_collision_bounce"),&TileMap::get_collision_bounce);
+ ClassDB::bind_method(D_METHOD("set_collision_bounce", "value"), &TileMap::set_collision_bounce);
+ ClassDB::bind_method(D_METHOD("get_collision_bounce"), &TileMap::get_collision_bounce);
- ClassDB::bind_method(D_METHOD("set_occluder_light_mask","mask"),&TileMap::set_occluder_light_mask);
- ClassDB::bind_method(D_METHOD("get_occluder_light_mask"),&TileMap::get_occluder_light_mask);
+ ClassDB::bind_method(D_METHOD("set_occluder_light_mask", "mask"), &TileMap::set_occluder_light_mask);
+ ClassDB::bind_method(D_METHOD("get_occluder_light_mask"), &TileMap::get_occluder_light_mask);
- ClassDB::bind_method(D_METHOD("set_cell","x","y","tile","flip_x","flip_y","transpose"),&TileMap::set_cell,DEFVAL(false),DEFVAL(false),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("set_cellv","pos","tile","flip_x","flip_y","transpose"),&TileMap::set_cellv,DEFVAL(false),DEFVAL(false),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_cell","x","y"),&TileMap::get_cell);
- ClassDB::bind_method(D_METHOD("get_cellv","pos"),&TileMap::get_cellv);
- ClassDB::bind_method(D_METHOD("is_cell_x_flipped","x","y"),&TileMap::is_cell_x_flipped);
- ClassDB::bind_method(D_METHOD("is_cell_y_flipped","x","y"),&TileMap::is_cell_y_flipped);
- ClassDB::bind_method(D_METHOD("is_cell_transposed","x","y"),&TileMap::is_cell_transposed);
+ ClassDB::bind_method(D_METHOD("set_cell", "x", "y", "tile", "flip_x", "flip_y", "transpose"), &TileMap::set_cell, DEFVAL(false), DEFVAL(false), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("set_cellv", "pos", "tile", "flip_x", "flip_y", "transpose"), &TileMap::set_cellv, DEFVAL(false), DEFVAL(false), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_cell", "x", "y"), &TileMap::get_cell);
+ ClassDB::bind_method(D_METHOD("get_cellv", "pos"), &TileMap::get_cellv);
+ ClassDB::bind_method(D_METHOD("is_cell_x_flipped", "x", "y"), &TileMap::is_cell_x_flipped);
+ ClassDB::bind_method(D_METHOD("is_cell_y_flipped", "x", "y"), &TileMap::is_cell_y_flipped);
+ ClassDB::bind_method(D_METHOD("is_cell_transposed", "x", "y"), &TileMap::is_cell_transposed);
- ClassDB::bind_method(D_METHOD("clear"),&TileMap::clear);
+ ClassDB::bind_method(D_METHOD("clear"), &TileMap::clear);
- ClassDB::bind_method(D_METHOD("get_used_cells"),&TileMap::get_used_cells);
- ClassDB::bind_method(D_METHOD("get_used_rect"),&TileMap::get_used_rect);
+ ClassDB::bind_method(D_METHOD("get_used_cells"), &TileMap::get_used_cells);
+ ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMap::get_used_rect);
- ClassDB::bind_method(D_METHOD("map_to_world","mappos","ignore_half_ofs"),&TileMap::map_to_world,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("world_to_map","worldpos"),&TileMap::world_to_map);
+ ClassDB::bind_method(D_METHOD("map_to_world", "mappos", "ignore_half_ofs"), &TileMap::map_to_world, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("world_to_map", "worldpos"), &TileMap::world_to_map);
- ClassDB::bind_method(D_METHOD("_clear_quadrants"),&TileMap::_clear_quadrants);
- ClassDB::bind_method(D_METHOD("_recreate_quadrants"),&TileMap::_recreate_quadrants);
- ClassDB::bind_method(D_METHOD("_update_dirty_quadrants"),&TileMap::_update_dirty_quadrants);
+ ClassDB::bind_method(D_METHOD("_clear_quadrants"), &TileMap::_clear_quadrants);
+ ClassDB::bind_method(D_METHOD("_recreate_quadrants"), &TileMap::_recreate_quadrants);
+ ClassDB::bind_method(D_METHOD("_update_dirty_quadrants"), &TileMap::_update_dirty_quadrants);
- ClassDB::bind_method(D_METHOD("_set_tile_data"),&TileMap::_set_tile_data);
- ClassDB::bind_method(D_METHOD("_get_tile_data"),&TileMap::_get_tile_data);
+ ClassDB::bind_method(D_METHOD("_set_tile_data"), &TileMap::_set_tile_data);
+ ClassDB::bind_method(D_METHOD("_get_tile_data"), &TileMap::_get_tile_data);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Square,Isometric,Custom"),"set_mode","get_mode");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"tile_set",PROPERTY_HINT_RESOURCE_TYPE,"TileSet"),"set_tileset","get_tileset");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Square,Isometric,Custom"), "set_mode", "get_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tileset", "get_tileset");
- ADD_GROUP("Cell","cell_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"cell_size",PROPERTY_HINT_RANGE,"1,8192,1"),"set_cell_size","get_cell_size");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_quadrant_size",PROPERTY_HINT_RANGE,"1,128,1"),"set_quadrant_size","get_quadrant_size");
- ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM2D,"cell_custom_transform"),"set_custom_transform","get_custom_transform");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_half_offset",PROPERTY_HINT_ENUM,"Offset X,Offset Y,Disabled"),"set_half_offset","get_half_offset");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"cell_tile_origin",PROPERTY_HINT_ENUM,"Top Left,Center,Bottom Left"),"set_tile_origin","get_tile_origin");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"cell_y_sort"),"set_y_sort_mode","is_y_sort_mode_enabled");
+ ADD_GROUP("Cell", "cell_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "cell_size", PROPERTY_HINT_RANGE, "1,8192,1"), "set_cell_size", "get_cell_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_quadrant_size", PROPERTY_HINT_RANGE, "1,128,1"), "set_quadrant_size", "get_quadrant_size");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM2D, "cell_custom_transform"), "set_custom_transform", "get_custom_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_half_offset", PROPERTY_HINT_ENUM, "Offset X,Offset Y,Disabled"), "set_half_offset", "get_half_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_tile_origin", PROPERTY_HINT_ENUM, "Top Left,Center,Bottom Left"), "set_tile_origin", "get_tile_origin");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "cell_y_sort"), "set_y_sort_mode", "is_y_sort_mode_enabled");
- ADD_GROUP("Collision","collision_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collision_use_kinematic",PROPERTY_HINT_NONE,""),"set_collision_use_kinematic","get_collision_use_kinematic");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision_friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_collision_friction","get_collision_friction");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision_bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_collision_bounce","get_collision_bounce");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_layers",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_layer","get_collision_layer");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_2D_PHYSICS),"set_collision_mask","get_collision_mask");
+ ADD_GROUP("Collision", "collision_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_use_kinematic", PROPERTY_HINT_NONE, ""), "set_collision_use_kinematic", "get_collision_use_kinematic");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision_friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_friction", "get_collision_friction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision_bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_collision_bounce", "get_collision_bounce");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layers", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_layer", "get_collision_layer");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_collision_mask", "get_collision_mask");
- ADD_GROUP("Occluder","occluder_");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"occluder_light_mask",PROPERTY_HINT_LAYERS_2D_RENDER),"set_occluder_light_mask","get_occluder_light_mask");
- ADD_GROUP("","");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"tile_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_tile_data","_get_tile_data");
+ ADD_GROUP("Occluder", "occluder_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "occluder_light_mask", PROPERTY_HINT_LAYERS_2D_RENDER), "set_occluder_light_mask", "get_occluder_light_mask");
+ ADD_GROUP("", "");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_tile_data", "_get_tile_data");
ADD_SIGNAL(MethodInfo("settings_changed"));
- BIND_CONSTANT( INVALID_CELL );
- BIND_CONSTANT( MODE_SQUARE );
- BIND_CONSTANT( MODE_ISOMETRIC );
- BIND_CONSTANT( MODE_CUSTOM );
- BIND_CONSTANT( HALF_OFFSET_X );
- BIND_CONSTANT( HALF_OFFSET_Y );
- BIND_CONSTANT( HALF_OFFSET_DISABLED );
- BIND_CONSTANT( TILE_ORIGIN_TOP_LEFT );
- BIND_CONSTANT( TILE_ORIGIN_CENTER );
- BIND_CONSTANT( TILE_ORIGIN_BOTTOM_LEFT );
-
+ BIND_CONSTANT(INVALID_CELL);
+ BIND_CONSTANT(MODE_SQUARE);
+ BIND_CONSTANT(MODE_ISOMETRIC);
+ BIND_CONSTANT(MODE_CUSTOM);
+ BIND_CONSTANT(HALF_OFFSET_X);
+ BIND_CONSTANT(HALF_OFFSET_Y);
+ BIND_CONSTANT(HALF_OFFSET_DISABLED);
+ BIND_CONSTANT(TILE_ORIGIN_TOP_LEFT);
+ BIND_CONSTANT(TILE_ORIGIN_CENTER);
+ BIND_CONSTANT(TILE_ORIGIN_BOTTOM_LEFT);
}
TileMap::TileMap() {
-
-
- rect_cache_dirty=true;
- used_size_cache_dirty=true;
- pending_update=false;
- quadrant_order_dirty=false;
- quadrant_size=16;
- cell_size=Size2(64,64);
- center_x=false;
- center_y=false;
- collision_layer=1;
- collision_mask=1;
- friction=1;
- bounce=0;
- mode=MODE_SQUARE;
- half_offset=HALF_OFFSET_DISABLED;
- use_kinematic=false;
- navigation=NULL;
- y_sort_mode=false;
- occluder_light_mask=1;
-
- fp_adjust=0.00001;
- tile_origin=TILE_ORIGIN_TOP_LEFT;
+ rect_cache_dirty = true;
+ used_size_cache_dirty = true;
+ pending_update = false;
+ quadrant_order_dirty = false;
+ quadrant_size = 16;
+ cell_size = Size2(64, 64);
+ center_x = false;
+ center_y = false;
+ collision_layer = 1;
+ collision_mask = 1;
+ friction = 1;
+ bounce = 0;
+ mode = MODE_SQUARE;
+ half_offset = HALF_OFFSET_DISABLED;
+ use_kinematic = false;
+ navigation = NULL;
+ y_sort_mode = false;
+ occluder_light_mask = 1;
+
+ fp_adjust = 0.00001;
+ tile_origin = TILE_ORIGIN_TOP_LEFT;
set_notify_transform(true);
}
diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h
index c581aa8056..f52adcd510 100644
--- a/scene/2d/tile_map.h
+++ b/scene/2d/tile_map.h
@@ -29,17 +29,17 @@
#ifndef TILE_MAP_H
#define TILE_MAP_H
-#include "scene/2d/node_2d.h"
#include "scene/2d/navigation2d.h"
+#include "scene/2d/node_2d.h"
#include "scene/resources/tile_set.h"
#include "self_list.h"
#include "vset.h"
class TileMap : public Node2D {
- GDCLASS( TileMap, Node2D );
-public:
+ GDCLASS(TileMap, Node2D);
+public:
enum Mode {
MODE_SQUARE,
MODE_ISOMETRIC,
@@ -58,20 +58,17 @@ public:
TILE_ORIGIN_BOTTOM_LEFT
};
-
private:
-
Ref<TileSet> tile_set;
Size2i cell_size;
int quadrant_size;
- bool center_x,center_y;
+ bool center_x, center_y;
Mode mode;
Transform2D custom_transform;
HalfOffset half_offset;
bool use_kinematic;
Navigation2D *navigation;
-
union PosKey {
struct {
@@ -81,29 +78,32 @@ private:
uint32_t key;
//using a more precise comparison so the regions can be sorted later
- bool operator<(const PosKey& p_k) const { return (y==p_k.y) ? x < p_k.x : y < p_k.y; }
-
- PosKey(int16_t p_x, int16_t p_y) { x=p_x; y=p_y; }
- PosKey() { x=0; y=0; }
-
+ bool operator<(const PosKey &p_k) const { return (y == p_k.y) ? x < p_k.x : y < p_k.y; }
+
+ PosKey(int16_t p_x, int16_t p_y) {
+ x = p_x;
+ y = p_y;
+ }
+ PosKey() {
+ x = 0;
+ y = 0;
+ }
};
-
union Cell {
struct {
- int32_t id:24;
- bool flip_h:1;
- bool flip_v:1;
- bool transpose:1;
+ int32_t id : 24;
+ bool flip_h : 1;
+ bool flip_v : 1;
+ bool transpose : 1;
};
uint32_t _u32t;
- Cell() { _u32t=0; }
+ Cell() { _u32t = 0; }
};
-
- Map<PosKey,Cell> tile_map;
+ Map<PosKey, Cell> tile_map;
struct Quadrant {
Vector2 pos;
@@ -122,18 +122,33 @@ private:
Transform2D xform;
};
-
- Map<PosKey,NavPoly> navpoly_ids;
- Map<PosKey,Occluder> occluder_instances;
+ Map<PosKey, NavPoly> navpoly_ids;
+ Map<PosKey, Occluder> occluder_instances;
VSet<PosKey> cells;
- void operator=(const Quadrant& q) { pos=q.pos; canvas_items=q.canvas_items; body=q.body; cells=q.cells; navpoly_ids=q.navpoly_ids; occluder_instances=q.occluder_instances; }
- Quadrant(const Quadrant& q) : dirty_list(this) { pos=q.pos; canvas_items=q.canvas_items; body=q.body; cells=q.cells; occluder_instances=q.occluder_instances; navpoly_ids=q.navpoly_ids;}
- Quadrant() : dirty_list(this) {}
+ void operator=(const Quadrant &q) {
+ pos = q.pos;
+ canvas_items = q.canvas_items;
+ body = q.body;
+ cells = q.cells;
+ navpoly_ids = q.navpoly_ids;
+ occluder_instances = q.occluder_instances;
+ }
+ Quadrant(const Quadrant &q)
+ : dirty_list(this) {
+ pos = q.pos;
+ canvas_items = q.canvas_items;
+ body = q.body;
+ cells = q.cells;
+ occluder_instances = q.occluder_instances;
+ navpoly_ids = q.navpoly_ids;
+ }
+ Quadrant()
+ : dirty_list(this) {}
};
- Map<PosKey,Quadrant> quadrant_map;
+ Map<PosKey, Quadrant> quadrant_map;
SelfList<Quadrant>::List dirty_quadrant_list;
@@ -155,43 +170,38 @@ private:
int occluder_light_mask;
- void _fix_cell_transform(Transform2D& xform, const Cell& p_cell, const Vector2 &p_offset, const Size2 &p_sc);
+ void _fix_cell_transform(Transform2D &xform, const Cell &p_cell, const Vector2 &p_offset, const Size2 &p_sc);
- Map<PosKey,Quadrant>::Element *_create_quadrant(const PosKey& p_qk);
- void _erase_quadrant(Map<PosKey,Quadrant>::Element *Q);
- void _make_quadrant_dirty(Map<PosKey,Quadrant>::Element *Q);
+ Map<PosKey, Quadrant>::Element *_create_quadrant(const PosKey &p_qk);
+ void _erase_quadrant(Map<PosKey, Quadrant>::Element *Q);
+ void _make_quadrant_dirty(Map<PosKey, Quadrant>::Element *Q);
void _recreate_quadrants();
void _clear_quadrants();
void _update_dirty_quadrants();
- void _update_quadrant_space(const RID& p_space);
+ void _update_quadrant_space(const RID &p_space);
void _update_quadrant_transform();
void _recompute_rect_cache();
_FORCE_INLINE_ int _get_quadrant_size() const;
-
- void _set_tile_data(const PoolVector<int>& p_data);
+ void _set_tile_data(const PoolVector<int> &p_data);
PoolVector<int> _get_tile_data() const;
- void _set_old_cell_size(int p_size) { set_cell_size(Size2(p_size,p_size)); }
+ void _set_old_cell_size(int p_size) { set_cell_size(Size2(p_size, p_size)); }
int _get_old_cell_size() const { return cell_size.x; }
- _FORCE_INLINE_ Vector2 _map_to_world(int p_x,int p_y,bool p_ignore_ofs=false) const;
+ _FORCE_INLINE_ Vector2 _map_to_world(int p_x, int p_y, bool p_ignore_ofs = false) const;
protected:
-
-
void _notification(int p_what);
static void _bind_methods();
public:
-
enum {
- INVALID_CELL=-1
+ INVALID_CELL = -1
};
-
- void set_tileset(const Ref<TileSet>& p_tileset);
+ void set_tileset(const Ref<TileSet> &p_tileset);
Ref<TileSet> get_tileset() const;
void set_cell_size(Size2 p_size);
@@ -205,14 +215,14 @@ public:
void set_center_y(bool p_enable);
bool get_center_y() const;
- void set_cell(int p_x,int p_y,int p_tile,bool p_flip_x=false,bool p_flip_y=false,bool p_transpose=false);
- int get_cell(int p_x,int p_y) const;
- bool is_cell_x_flipped(int p_x,int p_y) const;
- bool is_cell_y_flipped(int p_x,int p_y) const;
- bool is_cell_transposed(int p_x,int p_y) const;
+ void set_cell(int p_x, int p_y, int p_tile, bool p_flip_x = false, bool p_flip_y = false, bool p_transpose = false);
+ int get_cell(int p_x, int p_y) const;
+ bool is_cell_x_flipped(int p_x, int p_y) const;
+ bool is_cell_y_flipped(int p_x, int p_y) const;
+ bool is_cell_transposed(int p_x, int p_y) const;
- void set_cellv(const Vector2& p_pos,int p_tile,bool p_flip_x=false,bool p_flip_y=false,bool p_transpose=false);
- int get_cellv(const Vector2& p_pos) const;
+ void set_cellv(const Vector2 &p_pos, int p_tile, bool p_flip_x = false, bool p_flip_y = false, bool p_transpose = false);
+ int get_cellv(const Vector2 &p_pos) const;
Rect2 get_item_rect() const;
@@ -240,14 +250,14 @@ public:
void set_tile_origin(TileOrigin p_tile_origin);
TileOrigin get_tile_origin() const;
- void set_custom_transform(const Transform2D& p_xform);
+ void set_custom_transform(const Transform2D &p_xform);
Transform2D get_custom_transform() const;
Transform2D get_cell_transform() const;
Vector2 get_cell_draw_offset() const;
- Vector2 map_to_world(const Vector2& p_pos, bool p_ignore_ofs=false) const;
- Vector2 world_to_map(const Vector2& p_pos) const;
+ Vector2 map_to_world(const Vector2 &p_pos, bool p_ignore_ofs = false) const;
+ Vector2 world_to_map(const Vector2 &p_pos) const;
void set_y_sort_mode(bool p_enable);
bool is_y_sort_mode_enabled() const;
diff --git a/scene/2d/visibility_notifier_2d.cpp b/scene/2d/visibility_notifier_2d.cpp
index 64ab333e48..f20a995d5f 100644
--- a/scene/2d/visibility_notifier_2d.cpp
+++ b/scene/2d/visibility_notifier_2d.cpp
@@ -28,14 +28,14 @@
/*************************************************************************/
#include "visibility_notifier_2d.h"
-#include "scene/scene_string_names.h"
-#include "scene/2d/physics_body_2d.h"
+#include "particles_2d.h"
#include "scene/2d/animated_sprite.h"
+#include "scene/2d/physics_body_2d.h"
#include "scene/animation/animation_player.h"
#include "scene/scene_string_names.h"
-#include "particles_2d.h"
+#include "scene/scene_string_names.h"
-void VisibilityNotifier2D::_enter_viewport(Viewport* p_viewport) {
+void VisibilityNotifier2D::_enter_viewport(Viewport *p_viewport) {
ERR_FAIL_COND(viewports.has(p_viewport));
viewports.insert(p_viewport);
@@ -43,16 +43,15 @@ void VisibilityNotifier2D::_enter_viewport(Viewport* p_viewport) {
if (is_inside_tree() && get_tree()->is_editor_hint())
return;
- if (viewports.size()==1) {
+ if (viewports.size() == 1) {
emit_signal(SceneStringNames::get_singleton()->screen_entered);
_screen_enter();
}
- emit_signal(SceneStringNames::get_singleton()->viewport_entered,p_viewport);
-
+ emit_signal(SceneStringNames::get_singleton()->viewport_entered, p_viewport);
}
-void VisibilityNotifier2D::_exit_viewport(Viewport* p_viewport){
+void VisibilityNotifier2D::_exit_viewport(Viewport *p_viewport) {
ERR_FAIL_COND(!viewports.has(p_viewport));
viewports.erase(p_viewport);
@@ -60,20 +59,19 @@ void VisibilityNotifier2D::_exit_viewport(Viewport* p_viewport){
if (is_inside_tree() && get_tree()->is_editor_hint())
return;
- emit_signal(SceneStringNames::get_singleton()->viewport_exited,p_viewport);
- if (viewports.size()==0) {
+ emit_signal(SceneStringNames::get_singleton()->viewport_exited, p_viewport);
+ if (viewports.size() == 0) {
emit_signal(SceneStringNames::get_singleton()->screen_exited);
_screen_exit();
}
}
+void VisibilityNotifier2D::set_rect(const Rect2 &p_rect) {
-void VisibilityNotifier2D::set_rect(const Rect2& p_rect){
-
- rect=p_rect;
+ rect = p_rect;
if (is_inside_tree()) {
- get_world_2d()->_update_notifier(this,get_global_transform().xform(rect));
+ get_world_2d()->_update_notifier(this, get_global_transform().xform(rect));
if (get_tree()->is_editor_hint()) {
update();
item_rect_changed();
@@ -88,31 +86,29 @@ Rect2 VisibilityNotifier2D::get_item_rect() const {
return rect;
}
-Rect2 VisibilityNotifier2D::get_rect() const{
+Rect2 VisibilityNotifier2D::get_rect() const {
return rect;
}
-
void VisibilityNotifier2D::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
//get_world_2d()->
- get_world_2d()->_register_notifier(this,get_global_transform().xform(rect));
+ get_world_2d()->_register_notifier(this, get_global_transform().xform(rect));
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
//get_world_2d()->
- get_world_2d()->_update_notifier(this,get_global_transform().xform(rect));
+ get_world_2d()->_update_notifier(this, get_global_transform().xform(rect));
} break;
case NOTIFICATION_DRAW: {
if (get_tree()->is_editor_hint()) {
- draw_rect(rect,Color(1,0.5,1,0.2));
+ draw_rect(rect, Color(1, 0.5, 1, 0.2));
}
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -124,43 +120,36 @@ void VisibilityNotifier2D::_notification(int p_what) {
bool VisibilityNotifier2D::is_on_screen() const {
- return viewports.size()>0;
+ return viewports.size() > 0;
}
-void VisibilityNotifier2D::_bind_methods(){
+void VisibilityNotifier2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_rect","rect"),&VisibilityNotifier2D::set_rect);
- ClassDB::bind_method(D_METHOD("get_rect"),&VisibilityNotifier2D::get_rect);
- ClassDB::bind_method(D_METHOD("is_on_screen"),&VisibilityNotifier2D::is_on_screen);
+ ClassDB::bind_method(D_METHOD("set_rect", "rect"), &VisibilityNotifier2D::set_rect);
+ ClassDB::bind_method(D_METHOD("get_rect"), &VisibilityNotifier2D::get_rect);
+ ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibilityNotifier2D::is_on_screen);
- ADD_PROPERTY( PropertyInfo(Variant::RECT2,"rect"),"set_rect","get_rect");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "rect"), "set_rect", "get_rect");
- ADD_SIGNAL( MethodInfo("viewport_entered",PropertyInfo(Variant::OBJECT,"viewport",PROPERTY_HINT_RESOURCE_TYPE,"Viewport")) );
- ADD_SIGNAL( MethodInfo("viewport_exited",PropertyInfo(Variant::OBJECT,"viewport",PROPERTY_HINT_RESOURCE_TYPE,"Viewport")) );
- ADD_SIGNAL( MethodInfo("screen_entered"));
- ADD_SIGNAL( MethodInfo("screen_exited"));
+ ADD_SIGNAL(MethodInfo("viewport_entered", PropertyInfo(Variant::OBJECT, "viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport")));
+ ADD_SIGNAL(MethodInfo("viewport_exited", PropertyInfo(Variant::OBJECT, "viewport", PROPERTY_HINT_RESOURCE_TYPE, "Viewport")));
+ ADD_SIGNAL(MethodInfo("screen_entered"));
+ ADD_SIGNAL(MethodInfo("screen_exited"));
}
-
VisibilityNotifier2D::VisibilityNotifier2D() {
- rect=Rect2(-10,-10,20,20);
+ rect = Rect2(-10, -10, 20, 20);
set_notify_transform(true);
}
-
-
-
-
//////////////////////////////////////
-
void VisibilityEnabler2D::_screen_enter() {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
-
- _change_node_state(E->key(),true);
+ _change_node_state(E->key(), true);
}
if (enabler[ENABLER_PARENT_FIXED_PROCESS] && get_parent())
@@ -168,14 +157,14 @@ void VisibilityEnabler2D::_screen_enter() {
if (enabler[ENABLER_PARENT_PROCESS] && get_parent())
get_parent()->set_process(true);
- visible=true;
+ visible = true;
}
-void VisibilityEnabler2D::_screen_exit(){
+void VisibilityEnabler2D::_screen_exit() {
- for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- _change_node_state(E->key(),false);
+ _change_node_state(E->key(), false);
}
if (enabler[ENABLER_PARENT_FIXED_PROCESS] && get_parent())
@@ -183,23 +172,21 @@ void VisibilityEnabler2D::_screen_exit(){
if (enabler[ENABLER_PARENT_PROCESS] && get_parent())
get_parent()->set_process(false);
- visible=false;
+ visible = false;
}
-void VisibilityEnabler2D::_find_nodes(Node* p_node) {
+void VisibilityEnabler2D::_find_nodes(Node *p_node) {
-
- bool add=false;
+ bool add = false;
Variant meta;
if (enabler[ENABLER_FREEZE_BODIES]) {
RigidBody2D *rb2d = p_node->cast_to<RigidBody2D>();
- if (rb2d && ((rb2d->get_mode()==RigidBody2D::MODE_CHARACTER || (rb2d->get_mode()==RigidBody2D::MODE_RIGID && !rb2d->is_able_to_sleep())))) {
-
+ if (rb2d && ((rb2d->get_mode() == RigidBody2D::MODE_CHARACTER || (rb2d->get_mode() == RigidBody2D::MODE_RIGID && !rb2d->is_able_to_sleep())))) {
- add=true;
- meta=rb2d->get_mode();
+ add = true;
+ meta = rb2d->get_mode();
}
}
@@ -207,59 +194,53 @@ void VisibilityEnabler2D::_find_nodes(Node* p_node) {
AnimationPlayer *ap = p_node->cast_to<AnimationPlayer>();
if (ap) {
- add=true;
+ add = true;
}
-
}
if (enabler[ENABLER_PAUSE_ANIMATED_SPRITES]) {
AnimatedSprite *as = p_node->cast_to<AnimatedSprite>();
if (as) {
- add=true;
+ add = true;
}
-
}
-
if (enabler[ENABLER_PAUSE_PARTICLES]) {
Particles2D *ps = p_node->cast_to<Particles2D>();
if (ps) {
- add=true;
+ add = true;
}
-
}
if (add) {
- p_node->connect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed",varray(p_node),CONNECT_ONESHOT);
- nodes[p_node]=meta;
- _change_node_state(p_node,false);
+ p_node->connect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed", varray(p_node), CONNECT_ONESHOT);
+ nodes[p_node] = meta;
+ _change_node_state(p_node, false);
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
Node *c = p_node->get_child(i);
- if (c->get_filename()!=String())
+ if (c->get_filename() != String())
continue; //skip, instance
_find_nodes(c);
}
-
}
-void VisibilityEnabler2D::_notification(int p_what){
+void VisibilityEnabler2D::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
if (get_tree()->is_editor_hint())
return;
-
Node *from = this;
//find where current scene starts
- while(from->get_parent() && from->get_filename()==String())
- from=from->get_parent();
+ while (from->get_parent() && from->get_filename() == String())
+ from = from->get_parent();
_find_nodes(from);
@@ -267,29 +248,25 @@ void VisibilityEnabler2D::_notification(int p_what){
get_parent()->set_fixed_process(false);
if (enabler[ENABLER_PARENT_PROCESS] && get_parent())
get_parent()->set_process(false);
-
-
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (get_tree()->is_editor_hint())
return;
-
- for (Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
if (!visible)
- _change_node_state(E->key(),true);
- E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed");
+ _change_node_state(E->key(), true);
+ E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed");
}
nodes.clear();
-
}
}
-void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {
+void VisibilityEnabler2D::_change_node_state(Node *p_node, bool p_enabled) {
ERR_FAIL_COND(!nodes.has(p_node));
@@ -302,7 +279,7 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {
}
{
- AnimationPlayer *ap=p_node->cast_to<AnimationPlayer>();
+ AnimationPlayer *ap = p_node->cast_to<AnimationPlayer>();
if (ap) {
@@ -310,7 +287,7 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {
}
}
{
- AnimatedSprite *as=p_node->cast_to<AnimatedSprite>();
+ AnimatedSprite *as = p_node->cast_to<AnimatedSprite>();
if (as) {
@@ -322,81 +299,72 @@ void VisibilityEnabler2D::_change_node_state(Node* p_node,bool p_enabled) {
}
{
- Particles2D *ps=p_node->cast_to<Particles2D>();
+ Particles2D *ps = p_node->cast_to<Particles2D>();
if (ps) {
ps->set_emitting(p_enabled);
}
}
-
}
-
-void VisibilityEnabler2D::_node_removed(Node* p_node) {
+void VisibilityEnabler2D::_node_removed(Node *p_node) {
if (!visible)
- _change_node_state(p_node,true);
+ _change_node_state(p_node, true);
//changed to one shot, not needed
//p_node->disconnect(SceneStringNames::get_singleton()->exit_scene,this,"_node_removed");
nodes.erase(p_node);
-
}
String VisibilityEnabler2D::get_configuration_warning() const {
#ifdef TOOLS_ENABLED
- if (is_inside_tree() && get_parent() && (get_parent()->get_filename()==String() && get_parent()!=get_tree()->get_edited_scene_root())) {
+ if (is_inside_tree() && get_parent() && (get_parent()->get_filename() == String() && get_parent() != get_tree()->get_edited_scene_root())) {
return TTR("VisibilityEnable2D works best when used with the edited scene root directly as parent.");
}
#endif
return String();
}
-
-void VisibilityEnabler2D::_bind_methods(){
-
- ClassDB::bind_method(D_METHOD("set_enabler","enabler","enabled"),&VisibilityEnabler2D::set_enabler);
- ClassDB::bind_method(D_METHOD("is_enabler_enabled","enabler"),&VisibilityEnabler2D::is_enabler_enabled);
- ClassDB::bind_method(D_METHOD("_node_removed"),&VisibilityEnabler2D::_node_removed);
-
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animations"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS );
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"freeze_bodies"),"set_enabler","is_enabler_enabled", ENABLER_FREEZE_BODIES);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_particles"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_PARTICLES);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animated_sprites"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATED_SPRITES);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"process_parent"),"set_enabler","is_enabler_enabled", ENABLER_PARENT_PROCESS);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"fixed_process_parent"),"set_enabler","is_enabler_enabled", ENABLER_PARENT_FIXED_PROCESS);
-
- BIND_CONSTANT( ENABLER_FREEZE_BODIES );
- BIND_CONSTANT( ENABLER_PAUSE_ANIMATIONS );
- BIND_CONSTANT( ENABLER_PAUSE_PARTICLES );
- BIND_CONSTANT( ENABLER_PAUSE_ANIMATED_SPRITES );
- BIND_CONSTANT( ENABLER_PARENT_PROCESS );
- BIND_CONSTANT( ENABLER_PARENT_FIXED_PROCESS );
- BIND_CONSTANT( ENABLER_MAX);
+void VisibilityEnabler2D::_bind_methods() {
+
+ ClassDB::bind_method(D_METHOD("set_enabler", "enabler", "enabled"), &VisibilityEnabler2D::set_enabler);
+ ClassDB::bind_method(D_METHOD("is_enabler_enabled", "enabler"), &VisibilityEnabler2D::is_enabler_enabled);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &VisibilityEnabler2D::_node_removed);
+
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animations"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "freeze_bodies"), "set_enabler", "is_enabler_enabled", ENABLER_FREEZE_BODIES);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_particles"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_PARTICLES);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animated_sprites"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATED_SPRITES);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "process_parent"), "set_enabler", "is_enabler_enabled", ENABLER_PARENT_PROCESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "fixed_process_parent"), "set_enabler", "is_enabler_enabled", ENABLER_PARENT_FIXED_PROCESS);
+
+ BIND_CONSTANT(ENABLER_FREEZE_BODIES);
+ BIND_CONSTANT(ENABLER_PAUSE_ANIMATIONS);
+ BIND_CONSTANT(ENABLER_PAUSE_PARTICLES);
+ BIND_CONSTANT(ENABLER_PAUSE_ANIMATED_SPRITES);
+ BIND_CONSTANT(ENABLER_PARENT_PROCESS);
+ BIND_CONSTANT(ENABLER_PARENT_FIXED_PROCESS);
+ BIND_CONSTANT(ENABLER_MAX);
}
-void VisibilityEnabler2D::set_enabler(Enabler p_enabler,bool p_enable){
-
- ERR_FAIL_INDEX(p_enabler,ENABLER_MAX);
- enabler[p_enabler]=p_enable;
+void VisibilityEnabler2D::set_enabler(Enabler p_enabler, bool p_enable) {
+ ERR_FAIL_INDEX(p_enabler, ENABLER_MAX);
+ enabler[p_enabler] = p_enable;
}
-bool VisibilityEnabler2D::is_enabler_enabled(Enabler p_enabler) const{
+bool VisibilityEnabler2D::is_enabler_enabled(Enabler p_enabler) const {
- ERR_FAIL_INDEX_V(p_enabler,ENABLER_MAX,false);
+ ERR_FAIL_INDEX_V(p_enabler, ENABLER_MAX, false);
return enabler[p_enabler];
-
}
VisibilityEnabler2D::VisibilityEnabler2D() {
- for(int i=0;i<ENABLER_MAX;i++)
- enabler[i]=true;
- enabler[ENABLER_PARENT_PROCESS]=false;
- enabler[ENABLER_PARENT_FIXED_PROCESS]=false;
-
- visible=false;
+ for (int i = 0; i < ENABLER_MAX; i++)
+ enabler[i] = true;
+ enabler[ENABLER_PARENT_PROCESS] = false;
+ enabler[ENABLER_PARENT_FIXED_PROCESS] = false;
+ visible = false;
}
-
-
diff --git a/scene/2d/visibility_notifier_2d.h b/scene/2d/visibility_notifier_2d.h
index a896e270fe..aa49497404 100644
--- a/scene/2d/visibility_notifier_2d.h
+++ b/scene/2d/visibility_notifier_2d.h
@@ -34,27 +34,26 @@
class Viewport;
class VisibilityNotifier2D : public Node2D {
- GDCLASS(VisibilityNotifier2D,Node2D);
+ GDCLASS(VisibilityNotifier2D, Node2D);
- Set<Viewport*> viewports;
+ Set<Viewport *> viewports;
Rect2 rect;
protected:
-friend class SpatialIndexer2D;
-
- void _enter_viewport(Viewport* p_viewport);
- void _exit_viewport(Viewport* p_viewport);
+ friend class SpatialIndexer2D;
+ void _enter_viewport(Viewport *p_viewport);
+ void _exit_viewport(Viewport *p_viewport);
virtual void _screen_enter() {}
virtual void _screen_exit() {}
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_rect(const Rect2& p_rect);
+public:
+ void set_rect(const Rect2 &p_rect);
Rect2 get_rect() const;
bool is_on_screen() const;
@@ -64,12 +63,11 @@ public:
VisibilityNotifier2D();
};
-
class VisibilityEnabler2D : public VisibilityNotifier2D {
- GDCLASS(VisibilityEnabler2D,VisibilityNotifier2D);
-public:
+ GDCLASS(VisibilityEnabler2D, VisibilityNotifier2D);
+public:
enum Enabler {
ENABLER_PAUSE_ANIMATIONS,
ENABLER_FREEZE_BODIES,
@@ -81,35 +79,31 @@ public:
};
protected:
-
virtual void _screen_enter();
virtual void _screen_exit();
bool visible;
- void _find_nodes(Node* p_node);
+ void _find_nodes(Node *p_node);
- Map<Node*,Variant> nodes;
- void _node_removed(Node* p_node);
+ Map<Node *, Variant> nodes;
+ void _node_removed(Node *p_node);
bool enabler[ENABLER_MAX];
- void _change_node_state(Node* p_node,bool p_enabled);
+ void _change_node_state(Node *p_node, bool p_enabled);
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_enabler(Enabler p_enabler,bool p_enable);
+ void set_enabler(Enabler p_enabler, bool p_enable);
bool is_enabler_enabled(Enabler p_enabler) const;
String get_configuration_warning() const;
VisibilityEnabler2D();
-
};
VARIANT_ENUM_CAST(VisibilityEnabler2D::Enabler);
-
#endif // VISIBILITY_NOTIFIER_2D_H
diff --git a/scene/2d/y_sort.cpp b/scene/2d/y_sort.cpp
index cb9a494e87..760139287c 100644
--- a/scene/2d/y_sort.cpp
+++ b/scene/2d/y_sort.cpp
@@ -28,12 +28,10 @@
/*************************************************************************/
#include "y_sort.h"
-
-
void YSort::set_sort_enabled(bool p_enabled) {
- sort_enabled=p_enabled;
- VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),sort_enabled);
+ sort_enabled = p_enabled;
+ VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), sort_enabled);
}
bool YSort::is_sort_enabled() const {
@@ -43,16 +41,15 @@ bool YSort::is_sort_enabled() const {
void YSort::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_sort_enabled","enabled"),&YSort::set_sort_enabled);
- ClassDB::bind_method(D_METHOD("is_sort_enabled"),&YSort::is_sort_enabled);
+ ClassDB::bind_method(D_METHOD("set_sort_enabled", "enabled"), &YSort::set_sort_enabled);
+ ClassDB::bind_method(D_METHOD("is_sort_enabled"), &YSort::is_sort_enabled);
- ADD_GROUP("Sort","sort_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"sort_enabled"),"set_sort_enabled","is_sort_enabled");
+ ADD_GROUP("Sort", "sort_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sort_enabled"), "set_sort_enabled", "is_sort_enabled");
}
-
YSort::YSort() {
- sort_enabled=true;
- VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(),true);
+ sort_enabled = true;
+ VS::get_singleton()->canvas_item_set_sort_children_by_y(get_canvas_item(), true);
}
diff --git a/scene/2d/y_sort.h b/scene/2d/y_sort.h
index ebfe695da1..c919788498 100644
--- a/scene/2d/y_sort.h
+++ b/scene/2d/y_sort.h
@@ -32,11 +32,11 @@
#include "scene/2d/node_2d.h"
class YSort : public Node2D {
- GDCLASS(YSort,Node2D);
+ GDCLASS(YSort, Node2D);
bool sort_enabled;
static void _bind_methods();
-public:
+public:
void set_sort_enabled(bool p_enabled);
bool is_sort_enabled() const;
YSort();
diff --git a/scene/3d/area.cpp b/scene/3d/area.cpp
index 92ac091fc5..c42ca2f3f0 100644
--- a/scene/3d/area.cpp
+++ b/scene/3d/area.cpp
@@ -31,164 +31,152 @@
#include "servers/physics_server.h"
void Area::set_space_override_mode(SpaceOverride p_mode) {
- space_override=p_mode;
- PhysicsServer::get_singleton()->area_set_space_override_mode(get_rid(),PhysicsServer::AreaSpaceOverrideMode(p_mode));
-
-
+ space_override = p_mode;
+ PhysicsServer::get_singleton()->area_set_space_override_mode(get_rid(), PhysicsServer::AreaSpaceOverrideMode(p_mode));
}
-Area::SpaceOverride Area::get_space_override_mode() const{
+Area::SpaceOverride Area::get_space_override_mode() const {
return space_override;
}
-void Area::set_gravity_is_point(bool p_enabled){
-
- gravity_is_point=p_enabled;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT,p_enabled);
+void Area::set_gravity_is_point(bool p_enabled) {
+ gravity_is_point = p_enabled;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT, p_enabled);
}
-bool Area::is_gravity_a_point() const{
+bool Area::is_gravity_a_point() const {
return gravity_is_point;
}
-void Area::set_gravity_distance_scale(real_t p_scale){
-
- gravity_distance_scale=p_scale;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE,p_scale);
+void Area::set_gravity_distance_scale(real_t p_scale) {
+ gravity_distance_scale = p_scale;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE, p_scale);
}
-real_t Area::get_gravity_distance_scale() const{
+real_t Area::get_gravity_distance_scale() const {
return gravity_distance_scale;
}
-void Area::set_gravity_vector(const Vector3& p_vec){
-
- gravity_vec=p_vec;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY_VECTOR,p_vec);
+void Area::set_gravity_vector(const Vector3 &p_vec) {
+ gravity_vec = p_vec;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY_VECTOR, p_vec);
}
-Vector3 Area::get_gravity_vector() const{
+Vector3 Area::get_gravity_vector() const {
return gravity_vec;
}
-void Area::set_gravity(real_t p_gravity){
+void Area::set_gravity(real_t p_gravity) {
- gravity=p_gravity;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_GRAVITY,p_gravity);
+ gravity = p_gravity;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_GRAVITY, p_gravity);
}
-real_t Area::get_gravity() const{
+real_t Area::get_gravity() const {
return gravity;
}
-void Area::set_linear_damp(real_t p_linear_damp){
+void Area::set_linear_damp(real_t p_linear_damp) {
- linear_damp=p_linear_damp;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_LINEAR_DAMP,p_linear_damp);
+ linear_damp = p_linear_damp;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_LINEAR_DAMP, p_linear_damp);
}
-real_t Area::get_linear_damp() const{
+real_t Area::get_linear_damp() const {
return linear_damp;
}
-void Area::set_angular_damp(real_t p_angular_damp){
+void Area::set_angular_damp(real_t p_angular_damp) {
- angular_damp=p_angular_damp;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_ANGULAR_DAMP,p_angular_damp);
+ angular_damp = p_angular_damp;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_ANGULAR_DAMP, p_angular_damp);
}
-real_t Area::get_angular_damp() const{
+real_t Area::get_angular_damp() const {
return angular_damp;
}
-void Area::set_priority(real_t p_priority){
+void Area::set_priority(real_t p_priority) {
- priority=p_priority;
- PhysicsServer::get_singleton()->area_set_param(get_rid(),PhysicsServer::AREA_PARAM_PRIORITY,p_priority);
+ priority = p_priority;
+ PhysicsServer::get_singleton()->area_set_param(get_rid(), PhysicsServer::AREA_PARAM_PRIORITY, p_priority);
}
-real_t Area::get_priority() const{
+real_t Area::get_priority() const {
return priority;
}
-
void Area::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_tree);
- E->get().in_tree=true;
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = true;
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
-
}
void Area::_body_exit_tree(ObjectID p_id) {
-
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_tree);
- E->get().in_tree=false;
- emit_signal(SceneStringNames::get_singleton()->body_exited,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = false;
+ emit_signal(SceneStringNames::get_singleton()->body_exited, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
-
}
-void Area::_body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape) {
-
+void Area::_body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape) {
- bool body_in = p_status==PhysicsServer::AREA_BODY_ADDED;
- ObjectID objid=p_instance;
+ bool body_in = p_status == PhysicsServer::AREA_BODY_ADDED;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,BodyState>::Element *E=body_map.find(objid);
+ Map<ObjectID, BodyState>::Element *E = body_map.find(objid);
ERR_FAIL_COND(!body_in && !E);
- locked=true;
+ locked = true;
if (body_in) {
if (!E) {
- E = body_map.insert(objid,BodyState());
- E->get().rc=0;
- E->get().in_tree=node && node->is_inside_tree();
+ E = body_map.insert(objid, BodyState());
+ E->get().rc = 0;
+ E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
}
}
-
}
E->get().rc++;
if (node)
- E->get().shapes.insert(ShapePair(p_body_shape,p_area_shape));
-
+ E->get().shapes.insert(ShapePair(p_body_shape, p_area_shape));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_area_shape);
}
} else {
@@ -196,38 +184,32 @@ void Area::_body_inout(int p_status,const RID& p_body, int p_instance, int p_bod
E->get().rc--;
if (node)
- E->get().shapes.erase(ShapePair(p_body_shape,p_area_shape));
+ E->get().shapes.erase(ShapePair(p_body_shape, p_area_shape));
- bool eraseit=false;
+ bool eraseit = false;
- if (E->get().rc==0) {
+ if (E->get().rc == 0) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
if (E->get().in_tree)
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
-
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
}
- eraseit=true;
-
+ eraseit = true;
}
if (node && E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_area_shape);
}
if (eraseit)
body_map.erase(E);
-
}
- locked=false;
-
-
+ locked = false;
}
-
void Area::_clear_monitoring() {
if (locked) {
@@ -236,11 +218,11 @@ void Area::_clear_monitoring() {
ERR_FAIL_COND(locked);
{
- Map<ObjectID,BodyState> bmcopy = body_map;
+ Map<ObjectID, BodyState> bmcopy = body_map;
body_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID,BodyState>::Element *E=bmcopy.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = bmcopy.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
Node *node = obj ? obj->cast_to<Node>() : NULL;
@@ -248,26 +230,25 @@ void Area::_clear_monitoring() {
if (!E->get().in_tree)
continue;
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,E->key(),node,E->get().shapes[i].body_shape,E->get().shapes[i].area_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->key(), node, E->get().shapes[i].body_shape, E->get().shapes[i].area_shape);
}
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
}
-
}
{
- Map<ObjectID,AreaState> bmcopy = area_map;
+ Map<ObjectID, AreaState> bmcopy = area_map;
area_map.clear();
//disconnect all monitored stuff
- for (Map<ObjectID,AreaState>::Element *E=bmcopy.front();E;E=E->next()) {
+ for (Map<ObjectID, AreaState>::Element *E = bmcopy.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
Node *node = obj ? obj->cast_to<Node>() : NULL;
@@ -275,22 +256,21 @@ void Area::_clear_monitoring() {
if (!E->get().in_tree)
continue;
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,E->key(),node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, E->key(), node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
- emit_signal(SceneStringNames::get_singleton()->area_exited,obj);
+ emit_signal(SceneStringNames::get_singleton()->area_exited, obj);
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree);
}
}
-
}
void Area::_notification(int p_what) {
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
_clear_monitoring();
}
}
@@ -302,41 +282,38 @@ void Area::set_monitoring(bool p_enable) {
}
ERR_FAIL_COND(locked);
- if (p_enable==monitoring)
+ if (p_enable == monitoring)
return;
- monitoring=p_enable;
+ monitoring = p_enable;
if (monitoring) {
- PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_body_inout);
- PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(),this,SceneStringNames::get_singleton()->_area_inout);
+ PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_body_inout);
+ PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(), this, SceneStringNames::get_singleton()->_area_inout);
} else {
- PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(),NULL,StringName());
- PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(),NULL,StringName());
+ PhysicsServer::get_singleton()->area_set_monitor_callback(get_rid(), NULL, StringName());
+ PhysicsServer::get_singleton()->area_set_area_monitor_callback(get_rid(), NULL, StringName());
_clear_monitoring();
-
}
}
-
void Area::_area_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,AreaState>::Element *E=area_map.find(p_id);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_tree);
- E->get().in_tree=true;
- emit_signal(SceneStringNames::get_singleton()->area_entered,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = true;
+ emit_signal(SceneStringNames::get_singleton()->area_entered, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_entered,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_entered, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
-
}
void Area::_area_exit_tree(ObjectID p_id) {
@@ -344,56 +321,51 @@ void Area::_area_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,AreaState>::Element *E=area_map.find(p_id);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_tree);
- E->get().in_tree=false;
- emit_signal(SceneStringNames::get_singleton()->area_exited,node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ E->get().in_tree = false;
+ emit_signal(SceneStringNames::get_singleton()->area_exited, node);
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,p_id,node,E->get().shapes[i].area_shape,E->get().shapes[i].self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, p_id, node, E->get().shapes[i].area_shape, E->get().shapes[i].self_shape);
}
-
}
-void Area::_area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape) {
-
+void Area::_area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape) {
- bool area_in = p_status==PhysicsServer::AREA_BODY_ADDED;
- ObjectID objid=p_instance;
+ bool area_in = p_status == PhysicsServer::AREA_BODY_ADDED;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,AreaState>::Element *E=area_map.find(objid);
+ Map<ObjectID, AreaState>::Element *E = area_map.find(objid);
ERR_FAIL_COND(!area_in && !E);
- locked=true;
+ locked = true;
if (area_in) {
if (!E) {
- E = area_map.insert(objid,AreaState());
- E->get().rc=0;
- E->get().in_tree=node && node->is_inside_tree();
+ E = area_map.insert(objid, AreaState());
+ E->get().rc = 0;
+ E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree, make_binds(objid));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_entered,node);
-
+ emit_signal(SceneStringNames::get_singleton()->area_entered, node);
}
}
-
}
E->get().rc++;
if (node)
- E->get().shapes.insert(AreaShapePair(p_area_shape,p_self_shape));
-
+ E->get().shapes.insert(AreaShapePair(p_area_shape, p_self_shape));
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_entered,objid,node,p_area_shape,p_self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_entered, objid, node, p_area_shape, p_self_shape);
}
} else {
@@ -401,36 +373,31 @@ void Area::_area_inout(int p_status,const RID& p_area, int p_instance, int p_are
E->get().rc--;
if (node)
- E->get().shapes.erase(AreaShapePair(p_area_shape,p_self_shape));
+ E->get().shapes.erase(AreaShapePair(p_area_shape, p_self_shape));
- bool eraseit=false;
+ bool eraseit = false;
- if (E->get().rc==0) {
+ if (E->get().rc == 0) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_area_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_area_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_area_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_area_exit_tree);
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_exited,obj);
+ emit_signal(SceneStringNames::get_singleton()->area_exited, obj);
}
-
}
- eraseit=true;
-
+ eraseit = true;
}
if (!node || E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->area_shape_exited,objid,obj,p_area_shape,p_self_shape);
+ emit_signal(SceneStringNames::get_singleton()->area_shape_exited, objid, obj, p_area_shape, p_self_shape);
}
if (eraseit)
area_map.erase(E);
-
}
- locked=false;
-
-
+ locked = false;
}
bool Area::is_monitoring() const {
@@ -438,21 +405,19 @@ bool Area::is_monitoring() const {
return monitoring;
}
-
Array Area::get_overlapping_bodies() const {
- ERR_FAIL_COND_V(!monitoring,Array());
+ ERR_FAIL_COND_V(!monitoring, Array());
Array ret;
ret.resize(body_map.size());
- int idx=0;
- for (const Map<ObjectID,BodyState>::Element *E=body_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, BodyState>::Element *E = body_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
@@ -465,12 +430,12 @@ void Area::set_monitorable(bool p_enable) {
}
ERR_FAIL_COND(locked);
- if (p_enable==monitorable)
+ if (p_enable == monitorable)
return;
- monitorable=p_enable;
+ monitorable = p_enable;
- PhysicsServer::get_singleton()->area_set_monitorable(get_rid(),monitorable);
+ PhysicsServer::get_singleton()->area_set_monitorable(get_rid(), monitorable);
}
bool Area::is_monitorable() const {
@@ -478,51 +443,45 @@ bool Area::is_monitorable() const {
return monitorable;
}
-
Array Area::get_overlapping_areas() const {
- ERR_FAIL_COND_V(!monitoring,Array());
+ ERR_FAIL_COND_V(!monitoring, Array());
Array ret;
ret.resize(area_map.size());
- int idx=0;
- for (const Map<ObjectID,AreaState>::Element *E=area_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, AreaState>::Element *E = area_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
}
-bool Area::overlaps_area(Node* p_area) const {
+bool Area::overlaps_area(Node *p_area) const {
- ERR_FAIL_NULL_V(p_area,false);
- const Map<ObjectID,AreaState>::Element *E=area_map.find(p_area->get_instance_ID());
+ ERR_FAIL_NULL_V(p_area, false);
+ const Map<ObjectID, AreaState>::Element *E = area_map.find(p_area->get_instance_ID());
if (!E)
return false;
return E->get().in_tree;
-
-
-
}
-bool Area::overlaps_body(Node* p_body) const{
+bool Area::overlaps_body(Node *p_body) const {
- ERR_FAIL_NULL_V(p_body,false);
- const Map<ObjectID,BodyState>::Element *E=body_map.find(p_body->get_instance_ID());
+ ERR_FAIL_NULL_V(p_body, false);
+ const Map<ObjectID, BodyState>::Element *E = body_map.find(p_body->get_instance_ID());
if (!E)
return false;
return E->get().in_tree;
-
}
void Area::set_collision_mask(uint32_t p_mask) {
- collision_mask=p_mask;
- PhysicsServer::get_singleton()->area_set_collision_mask(get_rid(),p_mask);
+ collision_mask = p_mask;
+ PhysicsServer::get_singleton()->area_set_collision_mask(get_rid(), p_mask);
}
uint32_t Area::get_collision_mask() const {
@@ -531,8 +490,8 @@ uint32_t Area::get_collision_mask() const {
}
void Area::set_layer_mask(uint32_t p_mask) {
- layer_mask=p_mask;
- PhysicsServer::get_singleton()->area_set_layer_mask(get_rid(),p_mask);
+ layer_mask = p_mask;
+ PhysicsServer::get_singleton()->area_set_layer_mask(get_rid(), p_mask);
}
uint32_t Area::get_layer_mask() const {
@@ -544,144 +503,135 @@ void Area::set_collision_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_mask(mask);
-
}
-bool Area::get_collision_mask_bit(int p_bit) const{
+bool Area::get_collision_mask_bit(int p_bit) const {
- return get_collision_mask()&(1<<p_bit);
+ return get_collision_mask() & (1 << p_bit);
}
-
void Area::set_layer_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_layer_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_layer_mask(mask);
-
}
-bool Area::get_layer_mask_bit(int p_bit) const{
+bool Area::get_layer_mask_bit(int p_bit) const {
- return get_layer_mask()&(1<<p_bit);
+ return get_layer_mask() & (1 << p_bit);
}
-
void Area::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_body_enter_tree","id"),&Area::_body_enter_tree);
- ClassDB::bind_method(D_METHOD("_body_exit_tree","id"),&Area::_body_exit_tree);
+ ClassDB::bind_method(D_METHOD("_body_enter_tree", "id"), &Area::_body_enter_tree);
+ ClassDB::bind_method(D_METHOD("_body_exit_tree", "id"), &Area::_body_exit_tree);
- ClassDB::bind_method(D_METHOD("_area_enter_tree","id"),&Area::_area_enter_tree);
- ClassDB::bind_method(D_METHOD("_area_exit_tree","id"),&Area::_area_exit_tree);
+ ClassDB::bind_method(D_METHOD("_area_enter_tree", "id"), &Area::_area_enter_tree);
+ ClassDB::bind_method(D_METHOD("_area_exit_tree", "id"), &Area::_area_exit_tree);
- ClassDB::bind_method(D_METHOD("set_space_override_mode","enable"),&Area::set_space_override_mode);
- ClassDB::bind_method(D_METHOD("get_space_override_mode"),&Area::get_space_override_mode);
+ ClassDB::bind_method(D_METHOD("set_space_override_mode", "enable"), &Area::set_space_override_mode);
+ ClassDB::bind_method(D_METHOD("get_space_override_mode"), &Area::get_space_override_mode);
- ClassDB::bind_method(D_METHOD("set_gravity_is_point","enable"),&Area::set_gravity_is_point);
- ClassDB::bind_method(D_METHOD("is_gravity_a_point"),&Area::is_gravity_a_point);
+ ClassDB::bind_method(D_METHOD("set_gravity_is_point", "enable"), &Area::set_gravity_is_point);
+ ClassDB::bind_method(D_METHOD("is_gravity_a_point"), &Area::is_gravity_a_point);
- ClassDB::bind_method(D_METHOD("set_gravity_distance_scale","distance_scale"),&Area::set_gravity_distance_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_distance_scale"),&Area::get_gravity_distance_scale);
+ ClassDB::bind_method(D_METHOD("set_gravity_distance_scale", "distance_scale"), &Area::set_gravity_distance_scale);
+ ClassDB::bind_method(D_METHOD("get_gravity_distance_scale"), &Area::get_gravity_distance_scale);
- ClassDB::bind_method(D_METHOD("set_gravity_vector","vector"),&Area::set_gravity_vector);
- ClassDB::bind_method(D_METHOD("get_gravity_vector"),&Area::get_gravity_vector);
+ ClassDB::bind_method(D_METHOD("set_gravity_vector", "vector"), &Area::set_gravity_vector);
+ ClassDB::bind_method(D_METHOD("get_gravity_vector"), &Area::get_gravity_vector);
- ClassDB::bind_method(D_METHOD("set_gravity","gravity"),&Area::set_gravity);
- ClassDB::bind_method(D_METHOD("get_gravity"),&Area::get_gravity);
+ ClassDB::bind_method(D_METHOD("set_gravity", "gravity"), &Area::set_gravity);
+ ClassDB::bind_method(D_METHOD("get_gravity"), &Area::get_gravity);
- ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&Area::set_angular_damp);
- ClassDB::bind_method(D_METHOD("get_angular_damp"),&Area::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &Area::set_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_angular_damp"), &Area::get_angular_damp);
- ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&Area::set_linear_damp);
- ClassDB::bind_method(D_METHOD("get_linear_damp"),&Area::get_linear_damp);
+ ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &Area::set_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_linear_damp"), &Area::get_linear_damp);
- ClassDB::bind_method(D_METHOD("set_priority","priority"),&Area::set_priority);
- ClassDB::bind_method(D_METHOD("get_priority"),&Area::get_priority);
+ ClassDB::bind_method(D_METHOD("set_priority", "priority"), &Area::set_priority);
+ ClassDB::bind_method(D_METHOD("get_priority"), &Area::get_priority);
- ClassDB::bind_method(D_METHOD("set_collision_mask","collision_mask"),&Area::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"),&Area::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "collision_mask"), &Area::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &Area::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&Area::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&Area::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &Area::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &Area::get_layer_mask);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&Area::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&Area::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &Area::set_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &Area::get_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("set_layer_mask_bit","bit","value"),&Area::set_layer_mask_bit);
- ClassDB::bind_method(D_METHOD("get_layer_mask_bit","bit"),&Area::get_layer_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_layer_mask_bit", "bit", "value"), &Area::set_layer_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_layer_mask_bit", "bit"), &Area::get_layer_mask_bit);
- ClassDB::bind_method(D_METHOD("set_monitorable","enable"),&Area::set_monitorable);
- ClassDB::bind_method(D_METHOD("is_monitorable"),&Area::is_monitorable);
+ ClassDB::bind_method(D_METHOD("set_monitorable", "enable"), &Area::set_monitorable);
+ ClassDB::bind_method(D_METHOD("is_monitorable"), &Area::is_monitorable);
+ ClassDB::bind_method(D_METHOD("set_monitoring", "enable"), &Area::set_monitoring);
+ ClassDB::bind_method(D_METHOD("is_monitoring"), &Area::is_monitoring);
- ClassDB::bind_method(D_METHOD("set_monitoring","enable"),&Area::set_monitoring);
- ClassDB::bind_method(D_METHOD("is_monitoring"),&Area::is_monitoring);
+ ClassDB::bind_method(D_METHOD("get_overlapping_bodies"), &Area::get_overlapping_bodies);
+ ClassDB::bind_method(D_METHOD("get_overlapping_areas"), &Area::get_overlapping_areas);
- ClassDB::bind_method(D_METHOD("get_overlapping_bodies"),&Area::get_overlapping_bodies);
- ClassDB::bind_method(D_METHOD("get_overlapping_areas"),&Area::get_overlapping_areas);
+ ClassDB::bind_method(D_METHOD("overlaps_body", "body"), &Area::overlaps_body);
+ ClassDB::bind_method(D_METHOD("overlaps_area", "area"), &Area::overlaps_area);
- ClassDB::bind_method(D_METHOD("overlaps_body","body"),&Area::overlaps_body);
- ClassDB::bind_method(D_METHOD("overlaps_area","area"),&Area::overlaps_area);
+ ClassDB::bind_method(D_METHOD("_body_inout"), &Area::_body_inout);
+ ClassDB::bind_method(D_METHOD("_area_inout"), &Area::_area_inout);
- ClassDB::bind_method(D_METHOD("_body_inout"),&Area::_body_inout);
- ClassDB::bind_method(D_METHOD("_area_inout"),&Area::_area_inout);
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "area_shape")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "area_shape")));
+ ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("area_shape_entered", PropertyInfo(Variant::INT, "area_id"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "self_shape")));
+ ADD_SIGNAL(MethodInfo("area_shape_exited", PropertyInfo(Variant::INT, "area_id"), PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area"), PropertyInfo(Variant::INT, "area_shape"), PropertyInfo(Variant::INT, "self_shape")));
+ ADD_SIGNAL(MethodInfo("area_entered", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area")));
+ ADD_SIGNAL(MethodInfo("area_exited", PropertyInfo(Variant::OBJECT, "area", PROPERTY_HINT_RESOURCE_TYPE, "Area")));
- ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"area_shape")));
- ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"area_shape")));
- ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body")));
- ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body")));
-
- ADD_SIGNAL( MethodInfo("area_shape_entered",PropertyInfo(Variant::INT,"area_id"),PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area"),PropertyInfo(Variant::INT,"area_shape"),PropertyInfo(Variant::INT,"self_shape")));
- ADD_SIGNAL( MethodInfo("area_shape_exited",PropertyInfo(Variant::INT,"area_id"),PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area"),PropertyInfo(Variant::INT,"area_shape"),PropertyInfo(Variant::INT,"self_shape")));
- ADD_SIGNAL( MethodInfo("area_entered",PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area")));
- ADD_SIGNAL( MethodInfo("area_exited",PropertyInfo(Variant::OBJECT,"area",PROPERTY_HINT_RESOURCE_TYPE,"Area")));
-
- ADD_PROPERTY( PropertyInfo(Variant::INT,"space_override",PROPERTY_HINT_ENUM,"Disabled,Combine,Combine-Replace,Replace,Replace-Combine"),"set_space_override_mode","get_space_override_mode");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"gravity_point"),"set_gravity_is_point","is_gravity_a_point");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity_distance_scale", PROPERTY_HINT_RANGE,"0,1024,0.001"),"set_gravity_distance_scale","get_gravity_distance_scale");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"gravity_vec"),"set_gravity_vector","get_gravity_vector");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),"set_gravity","get_gravity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"0,1024,0.001"),"set_linear_damp","get_linear_damp");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"0,1024,0.001"),"set_angular_damp","get_angular_damp");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"priority",PROPERTY_HINT_RANGE,"0,128,1"),"set_priority","get_priority");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"monitoring"),"set_monitoring","is_monitoring");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"monitorable"),"set_monitorable","is_monitorable");
- ADD_GROUP("Collision","collision_");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_layers",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_layer_mask","get_layer_mask");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_collision_mask","get_collision_mask");
-
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "space_override", PROPERTY_HINT_ENUM, "Disabled,Combine,Combine-Replace,Replace,Replace-Combine"), "set_space_override_mode", "get_space_override_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gravity_point"), "set_gravity_is_point", "is_gravity_a_point");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_distance_scale", PROPERTY_HINT_RANGE, "0,1024,0.001"), "set_gravity_distance_scale", "get_gravity_distance_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "gravity_vec"), "set_gravity_vector", "get_gravity_vector");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_gravity", "get_gravity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "0,1024,0.001"), "set_linear_damp", "get_linear_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "0,1024,0.001"), "set_angular_damp", "get_angular_damp");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "priority", PROPERTY_HINT_RANGE, "0,128,1"), "set_priority", "get_priority");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "monitoring"), "set_monitoring", "is_monitoring");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "monitorable"), "set_monitorable", "is_monitorable");
+ ADD_GROUP("Collision", "collision_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layers", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_layer_mask", "get_layer_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
}
-Area::Area() : CollisionObject(PhysicsServer::get_singleton()->area_create(),true) {
+Area::Area()
+ : CollisionObject(PhysicsServer::get_singleton()->area_create(), true) {
- space_override=SPACE_OVERRIDE_DISABLED;
+ space_override = SPACE_OVERRIDE_DISABLED;
set_gravity(9.8);
- locked=false;
- set_gravity_vector(Vector3(0,-1,0));
- gravity_is_point=false;
- gravity_distance_scale=0;
- linear_damp=0.1;
- angular_damp=1;
- priority=0;
- monitoring=false;
- collision_mask=1;
- layer_mask=1;
+ locked = false;
+ set_gravity_vector(Vector3(0, -1, 0));
+ gravity_is_point = false;
+ gravity_distance_scale = 0;
+ linear_damp = 0.1;
+ angular_damp = 1;
+ priority = 0;
+ monitoring = false;
+ collision_mask = 1;
+ layer_mask = 1;
set_ray_pickable(false);
set_monitoring(true);
set_monitorable(true);
-
}
Area::~Area() {
-
-
}
diff --git a/scene/3d/area.h b/scene/3d/area.h
index 7956846505..a50f101ec1 100644
--- a/scene/3d/area.h
+++ b/scene/3d/area.h
@@ -34,9 +34,9 @@
class Area : public CollisionObject {
- GDCLASS( Area, CollisionObject );
-public:
+ GDCLASS(Area, CollisionObject);
+public:
enum SpaceOverride {
SPACE_OVERRIDE_DISABLED,
SPACE_OVERRIDE_COMBINE,
@@ -44,9 +44,8 @@ public:
SPACE_OVERRIDE_REPLACE,
SPACE_OVERRIDE_REPLACE_COMBINE
};
-private:
-
+private:
SpaceOverride space_override;
Vector3 gravity_vec;
real_t gravity;
@@ -61,8 +60,7 @@ private:
bool monitorable;
bool locked;
-
- void _body_inout(int p_status,const RID& p_body, int p_instance, int p_body_shape,int p_area_shape);
+ void _body_inout(int p_status, const RID &p_body, int p_instance, int p_body_shape, int p_area_shape);
void _body_enter_tree(ObjectID p_id);
void _body_exit_tree(ObjectID p_id);
@@ -71,15 +69,18 @@ private:
int body_shape;
int area_shape;
- bool operator<(const ShapePair& p_sp) const {
- if (body_shape==p_sp.body_shape)
+ bool operator<(const ShapePair &p_sp) const {
+ if (body_shape == p_sp.body_shape)
return area_shape < p_sp.area_shape;
else
return body_shape < p_sp.body_shape;
}
ShapePair() {}
- ShapePair(int p_bs, int p_as) { body_shape=p_bs; area_shape=p_as; }
+ ShapePair(int p_bs, int p_as) {
+ body_shape = p_bs;
+ area_shape = p_as;
+ }
};
struct BodyState {
@@ -89,10 +90,9 @@ private:
VSet<ShapePair> shapes;
};
- Map<ObjectID,BodyState> body_map;
+ Map<ObjectID, BodyState> body_map;
-
- void _area_inout(int p_status,const RID& p_area, int p_instance, int p_area_shape,int p_self_shape);
+ void _area_inout(int p_status, const RID &p_area, int p_instance, int p_area_shape, int p_self_shape);
void _area_enter_tree(ObjectID p_id);
void _area_exit_tree(ObjectID p_id);
@@ -101,15 +101,18 @@ private:
int area_shape;
int self_shape;
- bool operator<(const AreaShapePair& p_sp) const {
- if (area_shape==p_sp.area_shape)
+ bool operator<(const AreaShapePair &p_sp) const {
+ if (area_shape == p_sp.area_shape)
return self_shape < p_sp.self_shape;
else
return area_shape < p_sp.area_shape;
}
AreaShapePair() {}
- AreaShapePair(int p_bs, int p_as) { area_shape=p_bs; self_shape=p_as; }
+ AreaShapePair(int p_bs, int p_as) {
+ area_shape = p_bs;
+ self_shape = p_as;
+ }
};
struct AreaState {
@@ -119,16 +122,14 @@ private:
VSet<AreaShapePair> shapes;
};
- Map<ObjectID,AreaState> area_map;
+ Map<ObjectID, AreaState> area_map;
void _clear_monitoring();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_space_override_mode(SpaceOverride p_mode);
SpaceOverride get_space_override_mode() const;
@@ -138,7 +139,7 @@ public:
void set_gravity_distance_scale(real_t p_scale);
real_t get_gravity_distance_scale() const;
- void set_gravity_vector(const Vector3& p_vec);
+ void set_gravity_vector(const Vector3 &p_vec);
Vector3 get_gravity_vector() const;
void set_gravity(real_t p_gravity);
@@ -174,9 +175,8 @@ public:
Array get_overlapping_bodies() const;
Array get_overlapping_areas() const; //function for script
- bool overlaps_area(Node* p_area) const;
- bool overlaps_body(Node* p_body) const;
-
+ bool overlaps_area(Node *p_area) const;
+ bool overlaps_body(Node *p_body) const;
Area();
~Area();
diff --git a/scene/3d/baked_light_instance.cpp b/scene/3d/baked_light_instance.cpp
index e20d8faafd..ac424475ea 100644
--- a/scene/3d/baked_light_instance.cpp
+++ b/scene/3d/baked_light_instance.cpp
@@ -27,200 +27,226 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "baked_light_instance.h"
-#include "scene/scene_string_names.h"
-#include "mesh_instance.h"
#include "light.h"
#include "math.h"
+#include "mesh_instance.h"
+#include "scene/scene_string_names.h"
-#define FINDMINMAX(x0,x1,x2,min,max) \
- min = max = x0; \
- if(x1<min) min=x1;\
- if(x1>max) max=x1;\
- if(x2<min) min=x2;\
- if(x2>max) max=x2;
-
-static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox)
-{
- int q;
- Vector3 vmin,vmax;
- for(q=0;q<=2;q++)
- {
- if(normal[q]>0.0f)
- {
- vmin[q]=-maxbox[q];
- vmax[q]=maxbox[q];
- }
- else
- {
- vmin[q]=maxbox[q];
- vmax[q]=-maxbox[q];
- }
- }
- if(normal.dot(vmin)+d>0.0f) return false;
- if(normal.dot(vmax)+d>=0.0f) return true;
-
- return false;
-}
+#define FINDMINMAX(x0, x1, x2, min, max) \
+ min = max = x0; \
+ if (x1 < min) min = x1; \
+ if (x1 > max) max = x1; \
+ if (x2 < min) min = x2; \
+ if (x2 > max) max = x2;
+
+static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) {
+ int q;
+ Vector3 vmin, vmax;
+ for (q = 0; q <= 2; q++) {
+ if (normal[q] > 0.0f) {
+ vmin[q] = -maxbox[q];
+ vmax[q] = maxbox[q];
+ } else {
+ vmin[q] = maxbox[q];
+ vmax[q] = -maxbox[q];
+ }
+ }
+ if (normal.dot(vmin) + d > 0.0f) return false;
+ if (normal.dot(vmax) + d >= 0.0f) return true;
+ return false;
+}
/*======================== X-tests ========================*/
-#define AXISTEST_X01(a, b, fa, fb) \
- p0 = a*v0.y - b*v0.z; \
- p2 = a*v2.y - b*v2.z; \
- if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
- rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_X2(a, b, fa, fb) \
- p0 = a*v0.y - b*v0.z; \
- p1 = a*v1.y - b*v1.z; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
+#define AXISTEST_X01(a, b, fa, fb) \
+ p0 = a * v0.y - b * v0.z; \
+ p2 = a * v2.y - b * v2.z; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_X2(a, b, fa, fb) \
+ p0 = a * v0.y - b * v0.z; \
+ p1 = a * v1.y - b * v1.z; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
/*======================== Y-tests ========================*/
-#define AXISTEST_Y02(a, b, fa, fb) \
- p0 = -a*v0.x + b*v0.z; \
- p2 = -a*v2.x + b*v2.z; \
- if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_Y1(a, b, fa, fb) \
- p0 = -a*v0.x + b*v0.z; \
- p1 = -a*v1.x + b*v1.z; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
+#define AXISTEST_Y02(a, b, fa, fb) \
+ p0 = -a * v0.x + b * v0.z; \
+ p2 = -a * v2.x + b * v2.z; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_Y1(a, b, fa, fb) \
+ p0 = -a * v0.x + b * v0.z; \
+ p1 = -a * v1.x + b * v1.z; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
/*======================== Z-tests ========================*/
-#define AXISTEST_Z12(a, b, fa, fb) \
- p1 = a*v1.x - b*v1.y; \
- p2 = a*v2.x - b*v2.y; \
- if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_Z0(a, b, fa, fb) \
- p0 = a*v0.x - b*v0.y; \
- p1 = a*v1.x - b*v1.y; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
- if(min>rad || max<-rad) return false;
-
-static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) {
-
- /* use separating axis theorem to test overlap between triangle and box */
- /* need to test for overlap in these directions: */
- /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
- /* we do not even need to test these) */
- /* 2) normal of the triangle */
- /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
- /* this gives 3x3=9 more tests */
- Vector3 v0,v1,v2;
- float min,max,d,p0,p1,p2,rad,fex,fey,fez;
- Vector3 normal,e0,e1,e2;
-
- /* This is the fastest branch on Sun */
- /* move everything so that the boxcenter is in (0,0,0) */
-
- v0=triverts[0]-boxcenter;
- v1=triverts[1]-boxcenter;
- v2=triverts[2]-boxcenter;
-
- /* compute triangle edges */
- e0=v1-v0; /* tri edge 0 */
- e1=v2-v1; /* tri edge 1 */
- e2=v0-v2; /* tri edge 2 */
-
- /* Bullet 3: */
- /* test the 9 tests first (this was faster) */
- fex = Math::abs(e0.x);
- fey = Math::abs(e0.y);
- fez = Math::abs(e0.z);
- AXISTEST_X01(e0.z, e0.y, fez, fey);
- AXISTEST_Y02(e0.z, e0.x, fez, fex);
- AXISTEST_Z12(e0.y, e0.x, fey, fex);
-
- fex = Math::abs(e1.x);
- fey = Math::abs(e1.y);
- fez = Math::abs(e1.z);
- AXISTEST_X01(e1.z, e1.y, fez, fey);
- AXISTEST_Y02(e1.z, e1.x, fez, fex);
- AXISTEST_Z0(e1.y, e1.x, fey, fex);
-
- fex = Math::abs(e2.x);
- fey = Math::abs(e2.y);
- fez = Math::abs(e2.z);
- AXISTEST_X2(e2.z, e2.y, fez, fey);
- AXISTEST_Y1(e2.z, e2.x, fez, fex);
- AXISTEST_Z12(e2.y, e2.x, fey, fex);
-
- /* Bullet 1: */
- /* first test overlap in the {x,y,z}-directions */
- /* find min, max of the triangle each direction, and test for overlap in */
- /* that direction -- this is equivalent to testing a minimal AABB around */
- /* the triangle against the AABB */
-
- /* test in X-direction */
- FINDMINMAX(v0.x,v1.x,v2.x,min,max);
- if(min>boxhalfsize.x || max<-boxhalfsize.x) return false;
-
- /* test in Y-direction */
- FINDMINMAX(v0.y,v1.y,v2.y,min,max);
- if(min>boxhalfsize.y || max<-boxhalfsize.y) return false;
-
- /* test in Z-direction */
- FINDMINMAX(v0.z,v1.z,v2.z,min,max);
- if(min>boxhalfsize.z || max<-boxhalfsize.z) return false;
-
- /* Bullet 2: */
- /* test if the box intersects the plane of the triangle */
- /* compute plane equation of triangle: normal*x+d=0 */
- normal=e0.cross(e1);
- d=-normal.dot(v0); /* plane eq: normal.x+d=0 */
- if(!planeBoxOverlap(normal,d,boxhalfsize)) return false;
-
- return true; /* box and triangle overlaps */
+#define AXISTEST_Z12(a, b, fa, fb) \
+ p1 = a * v1.x - b * v1.y; \
+ p2 = a * v2.x - b * v2.y; \
+ if (p2 < p1) { \
+ min = p2; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p2; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_Z0(a, b, fa, fb) \
+ p0 = a * v0.x - b * v0.y; \
+ p1 = a * v1.x - b * v1.y; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
+ if (min > rad || max < -rad) return false;
+
+static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) {
+
+ /* use separating axis theorem to test overlap between triangle and box */
+ /* need to test for overlap in these directions: */
+ /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
+ /* we do not even need to test these) */
+ /* 2) normal of the triangle */
+ /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
+ /* this gives 3x3=9 more tests */
+ Vector3 v0, v1, v2;
+ float min, max, d, p0, p1, p2, rad, fex, fey, fez;
+ Vector3 normal, e0, e1, e2;
+
+ /* This is the fastest branch on Sun */
+ /* move everything so that the boxcenter is in (0,0,0) */
+
+ v0 = triverts[0] - boxcenter;
+ v1 = triverts[1] - boxcenter;
+ v2 = triverts[2] - boxcenter;
+
+ /* compute triangle edges */
+ e0 = v1 - v0; /* tri edge 0 */
+ e1 = v2 - v1; /* tri edge 1 */
+ e2 = v0 - v2; /* tri edge 2 */
+
+ /* Bullet 3: */
+ /* test the 9 tests first (this was faster) */
+ fex = Math::abs(e0.x);
+ fey = Math::abs(e0.y);
+ fez = Math::abs(e0.z);
+ AXISTEST_X01(e0.z, e0.y, fez, fey);
+ AXISTEST_Y02(e0.z, e0.x, fez, fex);
+ AXISTEST_Z12(e0.y, e0.x, fey, fex);
+
+ fex = Math::abs(e1.x);
+ fey = Math::abs(e1.y);
+ fez = Math::abs(e1.z);
+ AXISTEST_X01(e1.z, e1.y, fez, fey);
+ AXISTEST_Y02(e1.z, e1.x, fez, fex);
+ AXISTEST_Z0(e1.y, e1.x, fey, fex);
+
+ fex = Math::abs(e2.x);
+ fey = Math::abs(e2.y);
+ fez = Math::abs(e2.z);
+ AXISTEST_X2(e2.z, e2.y, fez, fey);
+ AXISTEST_Y1(e2.z, e2.x, fez, fex);
+ AXISTEST_Z12(e2.y, e2.x, fey, fex);
+
+ /* Bullet 1: */
+ /* first test overlap in the {x,y,z}-directions */
+ /* find min, max of the triangle each direction, and test for overlap in */
+ /* that direction -- this is equivalent to testing a minimal AABB around */
+ /* the triangle against the AABB */
+
+ /* test in X-direction */
+ FINDMINMAX(v0.x, v1.x, v2.x, min, max);
+ if (min > boxhalfsize.x || max < -boxhalfsize.x) return false;
+
+ /* test in Y-direction */
+ FINDMINMAX(v0.y, v1.y, v2.y, min, max);
+ if (min > boxhalfsize.y || max < -boxhalfsize.y) return false;
+
+ /* test in Z-direction */
+ FINDMINMAX(v0.z, v1.z, v2.z, min, max);
+ if (min > boxhalfsize.z || max < -boxhalfsize.z) return false;
+
+ /* Bullet 2: */
+ /* test if the box intersects the plane of the triangle */
+ /* compute plane equation of triangle: normal*x+d=0 */
+ normal = e0.cross(e1);
+ d = -normal.dot(v0); /* plane eq: normal.x+d=0 */
+ if (!planeBoxOverlap(normal, d, boxhalfsize)) return false;
+
+ return true; /* box and triangle overlaps */
}
-
-Vector<Color> BakedLight::_get_bake_texture(Image &p_image,const Color& p_color) {
+Vector<Color> BakedLight::_get_bake_texture(Image &p_image, const Color &p_color) {
Vector<Color> ret;
if (p_image.empty()) {
- ret.resize(bake_texture_size*bake_texture_size);
- for(int i=0;i<bake_texture_size*bake_texture_size;i++) {
- ret[i]=p_color;
+ ret.resize(bake_texture_size * bake_texture_size);
+ for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
+ ret[i] = p_color;
}
return ret;
}
p_image.convert(Image::FORMAT_RGBA8);
- p_image.resize(bake_texture_size,bake_texture_size,Image::INTERPOLATE_CUBIC);
-
+ p_image.resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
PoolVector<uint8_t>::Read r = p_image.get_data().read();
- ret.resize(bake_texture_size*bake_texture_size);
+ ret.resize(bake_texture_size * bake_texture_size);
- for(int i=0;i<bake_texture_size*bake_texture_size;i++) {
+ for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
Color c;
- c.r = r[i*4+0]/255.0;
- c.g = r[i*4+1]/255.0;
- c.b = r[i*4+2]/255.0;
- c.a = r[i*4+3]/255.0;
- ret[i]=c;
-
+ c.r = r[i * 4 + 0] / 255.0;
+ c.g = r[i * 4 + 1] / 255.0;
+ c.b = r[i * 4 + 2] / 255.0;
+ c.a = r[i * 4 + 3] / 255.0;
+ ret[i] = c;
}
return ret;
}
-
BakedLight::MaterialCache BakedLight::_get_material_cache(Ref<Material> p_material) {
//this way of obtaining materials is inaccurate and also does not support some compressed formats very well
@@ -236,7 +262,6 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref<Material> p_materi
if (mat.is_valid()) {
-
Ref<ImageTexture> albedo_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_ALBEDO);
Image img_albedo;
@@ -245,14 +270,14 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref<Material> p_materi
img_albedo = albedo_tex->get_data();
}
- mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo());
+ mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo());
Ref<ImageTexture> emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION);
Color emission_col = mat->get_emission();
- emission_col.r*=mat->get_emission_energy();
- emission_col.g*=mat->get_emission_energy();
- emission_col.b*=mat->get_emission_energy();
+ emission_col.r *= mat->get_emission_energy();
+ emission_col.g *= mat->get_emission_energy();
+ emission_col.b *= mat->get_emission_energy();
Image img_emission;
@@ -261,503 +286,465 @@ BakedLight::MaterialCache BakedLight::_get_material_cache(Ref<Material> p_materi
img_emission = emission_tex->get_data();
}
- mc.emission=_get_bake_texture(img_emission,emission_col);
+ mc.emission = _get_bake_texture(img_emission, emission_col);
} else {
Image empty;
- mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7));
- mc.emission=_get_bake_texture(empty,Color(0,0,0));
-
-
+ mc.albedo = _get_bake_texture(empty, Color(0.7, 0.7, 0.7));
+ mc.emission = _get_bake_texture(empty, Color(0, 0, 0));
}
- material_cache[p_material]=mc;
+ material_cache[p_material] = mc;
return mc;
-
-
}
+static _FORCE_INLINE_ Vector2 get_uv(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv) {
-
-static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) {
-
- if (p_pos.distance_squared_to(p_vtx[0])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2)
return p_uv[0];
- if (p_pos.distance_squared_to(p_vtx[1])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2)
return p_uv[1];
- if (p_pos.distance_squared_to(p_vtx[2])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2)
return p_uv[2];
Vector3 v0 = p_vtx[1] - p_vtx[0];
Vector3 v1 = p_vtx[2] - p_vtx[0];
Vector3 v2 = p_pos - p_vtx[0];
- float d00 = v0.dot( v0);
- float d01 = v0.dot( v1);
- float d11 = v1.dot( v1);
- float d20 = v2.dot( v0);
- float d21 = v2.dot( v1);
+ float d00 = v0.dot(v0);
+ float d01 = v0.dot(v1);
+ float d11 = v1.dot(v1);
+ float d20 = v2.dot(v0);
+ float d21 = v2.dot(v1);
float denom = (d00 * d11 - d01 * d01);
- if (denom==0)
+ if (denom == 0)
return p_uv[0];
float v = (d11 * d20 - d01 * d21) / denom;
float w = (d00 * d21 - d01 * d20) / denom;
float u = 1.0f - v - w;
- return p_uv[0]*u + p_uv[1]*v + p_uv[2]*w;
+ return p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
}
-void BakedLight::_plot_face(int p_idx, int p_level, const Vector3 *p_vtx, const Vector2* p_uv, const MaterialCache& p_material, const Rect3 &p_aabb) {
-
+void BakedLight::_plot_face(int p_idx, int p_level, const Vector3 *p_vtx, const Vector2 *p_uv, const MaterialCache &p_material, const Rect3 &p_aabb) {
-
- if (p_level==cell_subdiv-1) {
+ if (p_level == cell_subdiv - 1) {
//plot the face by guessing it's albedo and emission value
//find best axis to map to, for scanning values
int closest_axis;
float closest_dot;
- Vector3 normal = Plane(p_vtx[0],p_vtx[1],p_vtx[2]).normal;
+ Vector3 normal = Plane(p_vtx[0], p_vtx[1], p_vtx[2]).normal;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1.0;
- float dot=ABS(normal.dot(axis));
- if (i==0 || dot>closest_dot) {
- closest_axis=i;
- closest_dot=dot;
+ axis[i] = 1.0;
+ float dot = ABS(normal.dot(axis));
+ if (i == 0 || dot > closest_dot) {
+ closest_axis = i;
+ closest_dot = dot;
}
}
Vector3 axis;
- axis[closest_axis]=1.0;
+ axis[closest_axis] = 1.0;
Vector3 t1;
- t1[(closest_axis+1)%3]=1.0;
+ t1[(closest_axis + 1) % 3] = 1.0;
Vector3 t2;
- t2[(closest_axis+2)%3]=1.0;
+ t2[(closest_axis + 2) % 3] = 1.0;
- t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width);
- t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width);
+ t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
+ t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
Color albedo_accum;
Color emission_accum;
- float alpha=0.0;
+ float alpha = 0.0;
//map to a grid average in the best axis for this face
- for(int i=0;i<color_scan_cell_width;i++) {
+ for (int i = 0; i < color_scan_cell_width; i++) {
- Vector3 ofs_i=float(i)*t1;
+ Vector3 ofs_i = float(i) * t1;
- for(int j=0;j<color_scan_cell_width;j++) {
+ for (int j = 0; j < color_scan_cell_width; j++) {
- Vector3 ofs_j=float(j)*t2;
+ Vector3 ofs_j = float(j) * t2;
- Vector3 from = p_aabb.pos+ofs_i+ofs_j;
+ Vector3 from = p_aabb.pos + ofs_i + ofs_j;
Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
- Vector3 half = (to-from)*0.5;
+ Vector3 half = (to - from) * 0.5;
//is in this cell?
- if (!fast_tri_box_overlap(from+half,half,p_vtx)) {
+ if (!fast_tri_box_overlap(from + half, half, p_vtx)) {
continue; //face does not span this cell
}
//go from -size to +size*2 to avoid skipping collisions
- Vector3 ray_from = from + (t1+t2)*0.5 - axis * p_aabb.size[closest_axis];
- Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis]*2;
+ Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
+ Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
Vector3 intersection;
- if (!Geometry::ray_intersects_triangle(ray_from,ray_to,p_vtx[0],p_vtx[1],p_vtx[2],&intersection)) {
+ if (!Geometry::ray_intersects_triangle(ray_from, ray_to, p_vtx[0], p_vtx[1], p_vtx[2], &intersection)) {
//no intersect? look in edges
- float closest_dist=1e20;
- for(int j=0;j<3;j++) {
+ float closest_dist = 1e20;
+ for (int j = 0; j < 3; j++) {
Vector3 c;
Vector3 inters;
- Geometry::get_closest_points_between_segments(p_vtx[j],p_vtx[(j+1)%3],ray_from,ray_to,inters,c);
- float d=c.distance_to(intersection);
- if (j==0 || d<closest_dist) {
- closest_dist=d;
- intersection=inters;
+ Geometry::get_closest_points_between_segments(p_vtx[j], p_vtx[(j + 1) % 3], ray_from, ray_to, inters, c);
+ float d = c.distance_to(intersection);
+ if (j == 0 || d < closest_dist) {
+ closest_dist = d;
+ intersection = inters;
}
}
}
- Vector2 uv = get_uv(intersection,p_vtx,p_uv);
-
+ Vector2 uv = get_uv(intersection, p_vtx, p_uv);
- int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1);
- int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1);
+ int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
- int ofs = uv_y*bake_texture_size+uv_x;
- albedo_accum.r+=p_material.albedo[ofs].r;
- albedo_accum.g+=p_material.albedo[ofs].g;
- albedo_accum.b+=p_material.albedo[ofs].b;
- albedo_accum.a+=p_material.albedo[ofs].a;
-
- emission_accum.r+=p_material.emission[ofs].r;
- emission_accum.g+=p_material.emission[ofs].g;
- emission_accum.b+=p_material.emission[ofs].b;
- alpha+=1.0;
+ int ofs = uv_y * bake_texture_size + uv_x;
+ albedo_accum.r += p_material.albedo[ofs].r;
+ albedo_accum.g += p_material.albedo[ofs].g;
+ albedo_accum.b += p_material.albedo[ofs].b;
+ albedo_accum.a += p_material.albedo[ofs].a;
+ emission_accum.r += p_material.emission[ofs].r;
+ emission_accum.g += p_material.emission[ofs].g;
+ emission_accum.b += p_material.emission[ofs].b;
+ alpha += 1.0;
}
}
-
- if (alpha==0) {
+ if (alpha == 0) {
//could not in any way get texture information.. so use closest point to center
- Face3 f( p_vtx[0],p_vtx[1],p_vtx[2]);
- Vector3 inters = f.get_closest_point_to(p_aabb.pos+p_aabb.size*0.5);
+ Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
+ Vector3 inters = f.get_closest_point_to(p_aabb.pos + p_aabb.size * 0.5);
- Vector2 uv = get_uv(inters,p_vtx,p_uv);
+ Vector2 uv = get_uv(inters, p_vtx, p_uv);
- int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1);
- int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1);
+ int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
- int ofs = uv_y*bake_texture_size+uv_x;
+ int ofs = uv_y * bake_texture_size + uv_x;
- alpha = 1.0/(color_scan_cell_width*color_scan_cell_width);
+ alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
- albedo_accum.r=p_material.albedo[ofs].r*alpha;
- albedo_accum.g=p_material.albedo[ofs].g*alpha;
- albedo_accum.b=p_material.albedo[ofs].b*alpha;
- albedo_accum.a=p_material.albedo[ofs].a*alpha;
-
- emission_accum.r=p_material.emission[ofs].r*alpha;
- emission_accum.g=p_material.emission[ofs].g*alpha;
- emission_accum.b=p_material.emission[ofs].b*alpha;
+ albedo_accum.r = p_material.albedo[ofs].r * alpha;
+ albedo_accum.g = p_material.albedo[ofs].g * alpha;
+ albedo_accum.b = p_material.albedo[ofs].b * alpha;
+ albedo_accum.a = p_material.albedo[ofs].a * alpha;
+ emission_accum.r = p_material.emission[ofs].r * alpha;
+ emission_accum.g = p_material.emission[ofs].g * alpha;
+ emission_accum.b = p_material.emission[ofs].b * alpha;
zero_alphas++;
} else {
- float accdiv = 1.0/(color_scan_cell_width*color_scan_cell_width);
- alpha*=accdiv;
+ float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
+ alpha *= accdiv;
- albedo_accum.r*=accdiv;
- albedo_accum.g*=accdiv;
- albedo_accum.b*=accdiv;
- albedo_accum.a*=accdiv;
+ albedo_accum.r *= accdiv;
+ albedo_accum.g *= accdiv;
+ albedo_accum.b *= accdiv;
+ albedo_accum.a *= accdiv;
- emission_accum.r*=accdiv;
- emission_accum.g*=accdiv;
- emission_accum.b*=accdiv;
+ emission_accum.r *= accdiv;
+ emission_accum.g *= accdiv;
+ emission_accum.b *= accdiv;
}
//put this temporarily here, corrected in a later step
- bake_cells_write[p_idx].albedo[0]+=albedo_accum.r;
- bake_cells_write[p_idx].albedo[1]+=albedo_accum.g;
- bake_cells_write[p_idx].albedo[2]+=albedo_accum.b;
- bake_cells_write[p_idx].light[0]+=emission_accum.r;
- bake_cells_write[p_idx].light[1]+=emission_accum.g;
- bake_cells_write[p_idx].light[2]+=emission_accum.b;
- bake_cells_write[p_idx].alpha+=alpha;
-
- static const Vector3 side_normals[6]={
+ bake_cells_write[p_idx].albedo[0] += albedo_accum.r;
+ bake_cells_write[p_idx].albedo[1] += albedo_accum.g;
+ bake_cells_write[p_idx].albedo[2] += albedo_accum.b;
+ bake_cells_write[p_idx].light[0] += emission_accum.r;
+ bake_cells_write[p_idx].light[1] += emission_accum.g;
+ bake_cells_write[p_idx].light[2] += emission_accum.b;
+ bake_cells_write[p_idx].alpha += alpha;
+
+ static const Vector3 side_normals[6] = {
Vector3(-1, 0, 0),
- Vector3( 1, 0, 0),
- Vector3( 0,-1, 0),
- Vector3( 0, 1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0, 1),
+ Vector3(1, 0, 0),
+ Vector3(0, -1, 0),
+ Vector3(0, 1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, 1),
};
- for(int i=0;i<6;i++) {
- if (normal.dot(side_normals[i])>CMP_EPSILON) {
- bake_cells_write[p_idx].used_sides|=(1<<i);
+ for (int i = 0; i < 6; i++) {
+ if (normal.dot(side_normals[i]) > CMP_EPSILON) {
+ bake_cells_write[p_idx].used_sides |= (1 << i);
}
}
-
} else {
//go down
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- Rect3 aabb=p_aabb;
- aabb.size*=0.5;
+ Rect3 aabb = p_aabb;
+ aabb.size *= 0.5;
- if (i&1)
- aabb.pos.x+=aabb.size.x;
- if (i&2)
- aabb.pos.y+=aabb.size.y;
- if (i&4)
- aabb.pos.z+=aabb.size.z;
+ if (i & 1)
+ aabb.pos.x += aabb.size.x;
+ if (i & 2)
+ aabb.pos.y += aabb.size.y;
+ if (i & 4)
+ aabb.pos.z += aabb.size.z;
{
- Rect3 test_aabb=aabb;
+ Rect3 test_aabb = aabb;
//test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
- Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test
+ Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
- if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) {
- //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
+ if (!fast_tri_box_overlap(test_aabb.pos + qsize, qsize, p_vtx)) {
+ //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
//does not fit in child, go on
continue;
}
-
}
- if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY) {
+ if (bake_cells_write[p_idx].childs[i] == CHILD_EMPTY) {
//sub cell must be created
- if (bake_cells_used==(1<<bake_cells_alloc)) {
+ if (bake_cells_used == (1 << bake_cells_alloc)) {
//exhausted cells, creating more space
bake_cells_alloc++;
- bake_cells_write=PoolVector<BakeCell>::Write();
- bake_cells.resize(1<<bake_cells_alloc);
- bake_cells_write=bake_cells.write();
+ bake_cells_write = PoolVector<BakeCell>::Write();
+ bake_cells.resize(1 << bake_cells_alloc);
+ bake_cells_write = bake_cells.write();
}
- bake_cells_write[p_idx].childs[i]=bake_cells_used;
- bake_cells_level_used[p_level+1]++;
+ bake_cells_write[p_idx].childs[i] = bake_cells_used;
+ bake_cells_level_used[p_level + 1]++;
bake_cells_used++;
-
-
}
-
- _plot_face(bake_cells_write[p_idx].childs[i],p_level+1,p_vtx,p_uv,p_material,aabb);
+ _plot_face(bake_cells_write[p_idx].childs[i], p_level + 1, p_vtx, p_uv, p_material, aabb);
}
}
}
+void BakedLight::_fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z) {
-
-void BakedLight::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z) {
-
-
-
- if (p_level==cell_subdiv-1) {
-
+ if (p_level == cell_subdiv - 1) {
float alpha = bake_cells_write[p_idx].alpha;
- bake_cells_write[p_idx].albedo[0]/=alpha;
- bake_cells_write[p_idx].albedo[1]/=alpha;
- bake_cells_write[p_idx].albedo[2]/=alpha;
+ bake_cells_write[p_idx].albedo[0] /= alpha;
+ bake_cells_write[p_idx].albedo[1] /= alpha;
+ bake_cells_write[p_idx].albedo[2] /= alpha;
//transfer emission to light
- bake_cells_write[p_idx].light[0]/=alpha;
- bake_cells_write[p_idx].light[1]/=alpha;
- bake_cells_write[p_idx].light[2]/=alpha;
+ bake_cells_write[p_idx].light[0] /= alpha;
+ bake_cells_write[p_idx].light[1] /= alpha;
+ bake_cells_write[p_idx].light[2] /= alpha;
- bake_cells_write[p_idx].alpha=1.0;
+ bake_cells_write[p_idx].alpha = 1.0;
//remove neighbours from used sides
- for(int n=0;n<6;n++) {
+ for (int n = 0; n < 6; n++) {
- int ofs[3]={0,0,0};
+ int ofs[3] = { 0, 0, 0 };
- ofs[n/2]=(n&1)?1:-1;
+ ofs[n / 2] = (n & 1) ? 1 : -1;
//convert to x,y,z on this level
- int x=p_x;
- int y=p_y;
- int z=p_z;
-
- x+=ofs[0];
- y+=ofs[1];
- z+=ofs[2];
+ int x = p_x;
+ int y = p_y;
+ int z = p_z;
- int ofs_x=0;
- int ofs_y=0;
- int ofs_z=0;
- int size = 1<<p_level;
- int half=size/2;
+ x += ofs[0];
+ y += ofs[1];
+ z += ofs[2];
+ int ofs_x = 0;
+ int ofs_y = 0;
+ int ofs_z = 0;
+ int size = 1 << p_level;
+ int half = size / 2;
- if (x<0 || x>=size || y<0 || y>=size || z<0 || z>=size) {
+ if (x < 0 || x >= size || y < 0 || y >= size || z < 0 || z >= size) {
//neighbour is out, can't use it
- bake_cells_write[p_idx].used_sides&=~(1<<uint32_t(n));
+ bake_cells_write[p_idx].used_sides &= ~(1 << uint32_t(n));
continue;
}
- uint32_t neighbour=0;
+ uint32_t neighbour = 0;
- for(int i=0;i<cell_subdiv-1;i++) {
+ for (int i = 0; i < cell_subdiv - 1; i++) {
BakeCell *bc = &bake_cells_write[neighbour];
int child = 0;
if (x >= ofs_x + half) {
- child|=1;
- ofs_x+=half;
+ child |= 1;
+ ofs_x += half;
}
if (y >= ofs_y + half) {
- child|=2;
- ofs_y+=half;
+ child |= 2;
+ ofs_y += half;
}
if (z >= ofs_z + half) {
- child|=4;
- ofs_z+=half;
+ child |= 4;
+ ofs_z += half;
}
neighbour = bc->childs[child];
- if (neighbour==CHILD_EMPTY) {
+ if (neighbour == CHILD_EMPTY) {
break;
}
- half>>=1;
+ half >>= 1;
}
- if (neighbour!=CHILD_EMPTY) {
- bake_cells_write[p_idx].used_sides&=~(1<<uint32_t(n));
+ if (neighbour != CHILD_EMPTY) {
+ bake_cells_write[p_idx].used_sides &= ~(1 << uint32_t(n));
}
}
} else {
-
//go down
- float alpha_average=0;
- int half = cells_per_axis >> (p_level+1);
- for(int i=0;i<8;i++) {
+ float alpha_average = 0;
+ int half = cells_per_axis >> (p_level + 1);
+ for (int i = 0; i < 8; i++) {
uint32_t child = bake_cells_write[p_idx].childs[i];
- if (child==CHILD_EMPTY)
+ if (child == CHILD_EMPTY)
continue;
+ int nx = p_x;
+ int ny = p_y;
+ int nz = p_z;
- int nx=p_x;
- int ny=p_y;
- int nz=p_z;
+ if (i & 1)
+ nx += half;
+ if (i & 2)
+ ny += half;
+ if (i & 4)
+ nz += half;
- if (i&1)
- nx+=half;
- if (i&2)
- ny+=half;
- if (i&4)
- nz+=half;
-
- _fixup_plot(child,p_level+1,nx,ny,nz);
- alpha_average+=bake_cells_write[child].alpha;
+ _fixup_plot(child, p_level + 1, nx, ny, nz);
+ alpha_average += bake_cells_write[child].alpha;
}
- bake_cells_write[p_idx].alpha=alpha_average/8.0;
- bake_cells_write[p_idx].light[0]=0;
- bake_cells_write[p_idx].light[1]=0;
- bake_cells_write[p_idx].light[2]=0;
- bake_cells_write[p_idx].albedo[0]=0;
- bake_cells_write[p_idx].albedo[1]=0;
- bake_cells_write[p_idx].albedo[2]=0;
-
+ bake_cells_write[p_idx].alpha = alpha_average / 8.0;
+ bake_cells_write[p_idx].light[0] = 0;
+ bake_cells_write[p_idx].light[1] = 0;
+ bake_cells_write[p_idx].light[2] = 0;
+ bake_cells_write[p_idx].albedo[0] = 0;
+ bake_cells_write[p_idx].albedo[1] = 0;
+ bake_cells_write[p_idx].albedo[2] = 0;
}
//clean up light
- bake_cells_write[p_idx].light_pass=0;
+ bake_cells_write[p_idx].light_pass = 0;
//find neighbours
-
-
-
}
+void BakedLight::_bake_add_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh) {
-void BakedLight::_bake_add_mesh(const Transform& p_xform,Ref<Mesh>& p_mesh) {
-
+ for (int i = 0; i < p_mesh->get_surface_count(); i++) {
- for(int i=0;i<p_mesh->get_surface_count();i++) {
-
- if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES)
+ if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
continue; //only triangles
MaterialCache material = _get_material_cache(p_mesh->surface_get_material(i));
Array a = p_mesh->surface_get_arrays(i);
-
PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
PoolVector<Vector2>::Read uvr;
PoolVector<int> index = a[Mesh::ARRAY_INDEX];
- bool read_uv=false;
+ bool read_uv = false;
if (uv.size()) {
- uvr=uv.read();
- read_uv=true;
+ uvr = uv.read();
+ read_uv = true;
}
if (index.size()) {
- int facecount = index.size()/3;
- PoolVector<int>::Read ir=index.read();
+ int facecount = index.size() / 3;
+ PoolVector<int>::Read ir = index.read();
- for(int j=0;j<facecount;j++) {
+ for (int j = 0; j < facecount; j++) {
Vector3 vtxs[3];
Vector2 uvs[3];
- for(int k=0;k<3;k++) {
- vtxs[k]=p_xform.xform(vr[ir[j*3+k]]);
+ for (int k = 0; k < 3; k++) {
+ vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
}
if (read_uv) {
- for(int k=0;k<3;k++) {
- uvs[k]=uvr[ir[j*3+k]];
+ for (int k = 0; k < 3; k++) {
+ uvs[k] = uvr[ir[j * 3 + k]];
}
}
//plot face
- _plot_face(0,0,vtxs,uvs,material,bounds);
+ _plot_face(0, 0, vtxs, uvs, material, bounds);
}
-
-
} else {
- int facecount = vertices.size()/3;
+ int facecount = vertices.size() / 3;
- for(int j=0;j<facecount;j++) {
+ for (int j = 0; j < facecount; j++) {
Vector3 vtxs[3];
Vector2 uvs[3];
- for(int k=0;k<3;k++) {
- vtxs[k]=p_xform.xform(vr[j*3+k]);
+ for (int k = 0; k < 3; k++) {
+ vtxs[k] = p_xform.xform(vr[j * 3 + k]);
}
if (read_uv) {
- for(int k=0;k<3;k++) {
- uvs[k]=uvr[j*3+k];
+ for (int k = 0; k < 3; k++) {
+ uvs[k] = uvr[j * 3 + k];
}
}
//plot face
- _plot_face(0,0,vtxs,uvs,material,bounds);
+ _plot_face(0, 0, vtxs, uvs, material, bounds);
}
-
}
}
}
+void BakedLight::_bake_add_to_aabb(const Transform &p_xform, Ref<Mesh> &p_mesh, bool &first) {
+ for (int i = 0; i < p_mesh->get_surface_count(); i++) {
-void BakedLight::_bake_add_to_aabb(const Transform& p_xform,Ref<Mesh>& p_mesh,bool &first) {
-
- for(int i=0;i<p_mesh->get_surface_count();i++) {
-
- if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES)
+ if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
continue; //only triangles
Array a = p_mesh->surface_get_arrays(i);
PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
int vc = vertices.size();
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
if (first) {
- bounds.pos=p_xform.xform(vr[0]);
- first=false;
+ bounds.pos = p_xform.xform(vr[0]);
+ first = false;
}
-
- for(int j=0;j<vc;j++) {
+ for (int j = 0; j < vc; j++) {
bounds.expand_to(p_xform.xform(vr[j]));
}
}
@@ -765,25 +752,24 @@ void BakedLight::_bake_add_to_aabb(const Transform& p_xform,Ref<Mesh>& p_mesh,bo
void BakedLight::bake() {
+ bake_cells_alloc = 16;
+ bake_cells.resize(1 << bake_cells_alloc);
+ bake_cells_used = 1;
+ cells_per_axis = (1 << (cell_subdiv - 1));
+ zero_alphas = 0;
- bake_cells_alloc=16;
- bake_cells.resize(1<<bake_cells_alloc);
- bake_cells_used=1;
- cells_per_axis=(1<<(cell_subdiv-1));
- zero_alphas=0;
-
- bool aabb_first=true;
+ bool aabb_first = true;
print_line("Generating AABB");
bake_cells_level_used.resize(cell_subdiv);
- for(int i=0;i<cell_subdiv;i++) {
- bake_cells_level_used[i]=0;
+ for (int i = 0; i < cell_subdiv; i++) {
+ bake_cells_level_used[i] = 0;
}
- int count=0;
- for (Set<GeometryInstance*>::Element *E=geometries.front();E;E=E->next()) {
+ int count = 0;
+ for (Set<GeometryInstance *>::Element *E = geometries.front(); E; E = E->next()) {
- print_line("aabb geom "+itos(count)+"/"+itos(geometries.size()));
+ print_line("aabb geom " + itos(count) + "/" + itos(geometries.size()));
GeometryInstance *geom = E->get();
@@ -793,22 +779,22 @@ void BakedLight::bake() {
Ref<Mesh> mesh = mesh_instance->get_mesh();
if (mesh.is_valid()) {
- _bake_add_to_aabb(geom->get_relative_transform(this),mesh,aabb_first);
+ _bake_add_to_aabb(geom->get_relative_transform(this), mesh, aabb_first);
}
}
count++;
}
- print_line("AABB: "+bounds);
+ print_line("AABB: " + bounds);
ERR_FAIL_COND(aabb_first);
bake_cells_write = bake_cells.write();
- count=0;
+ count = 0;
- for (Set<GeometryInstance*>::Element *E=geometries.front();E;E=E->next()) {
+ for (Set<GeometryInstance *>::Element *E = geometries.front(); E; E = E->next()) {
GeometryInstance *geom = E->get();
- print_line("plot geom "+itos(count)+"/"+itos(geometries.size()));
+ print_line("plot geom " + itos(count) + "/" + itos(geometries.size()));
if (geom->cast_to<MeshInstance>()) {
@@ -816,127 +802,107 @@ void BakedLight::bake() {
Ref<Mesh> mesh = mesh_instance->get_mesh();
if (mesh.is_valid()) {
- _bake_add_mesh(geom->get_relative_transform(this),mesh);
+ _bake_add_mesh(geom->get_relative_transform(this), mesh);
}
}
count++;
}
+ _fixup_plot(0, 0, 0, 0, 0);
- _fixup_plot(0, 0,0,0,0);
-
-
- bake_cells_write=PoolVector<BakeCell>::Write();
+ bake_cells_write = PoolVector<BakeCell>::Write();
bake_cells.resize(bake_cells_used);
-
-
- print_line("total bake cells used: "+itos(bake_cells_used));
- for(int i=0;i<cell_subdiv;i++) {
- print_line("level "+itos(i)+": "+itos(bake_cells_level_used[i]));
+ print_line("total bake cells used: " + itos(bake_cells_used));
+ for (int i = 0; i < cell_subdiv; i++) {
+ print_line("level " + itos(i) + ": " + itos(bake_cells_level_used[i]));
}
- print_line("zero alphas: "+itos(zero_alphas));
-
-
-
+ print_line("zero alphas: " + itos(zero_alphas));
}
+void BakedLight::_bake_directional(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 &p_dir, const Color &p_color, int p_sign) {
-
-void BakedLight::_bake_directional(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3& p_dir,const Color& p_color,int p_sign) {
-
-
-
-
- if (p_level==cell_subdiv-1) {
+ if (p_level == cell_subdiv - 1) {
Vector3 end;
- end.x = float(p_x+0.5) / cells_per_axis;
- end.y = float(p_y+0.5) / cells_per_axis;
- end.z = float(p_z+0.5) / cells_per_axis;
+ end.x = float(p_x + 0.5) / cells_per_axis;
+ end.y = float(p_y + 0.5) / cells_per_axis;
+ end.z = float(p_z + 0.5) / cells_per_axis;
- end = bounds.pos + bounds.size*end;
+ end = bounds.pos + bounds.size * end;
- float max_ray_len = (bounds.size).length()*1.2;
+ float max_ray_len = (bounds.size).length() * 1.2;
- Vector3 begin = end + max_ray_len*-p_dir;
+ Vector3 begin = end + max_ray_len * -p_dir;
//clip begin
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (ABS(p_dir[i])<CMP_EPSILON) {
+ if (ABS(p_dir[i]) < CMP_EPSILON) {
continue; // parallel to axis, don't clip
}
Plane p;
- p.normal[i]=1.0;
- p.d=bounds.pos[i];
- if (p_dir[i]<0) {
- p.d+=bounds.size[i];
+ p.normal[i] = 1.0;
+ p.d = bounds.pos[i];
+ if (p_dir[i] < 0) {
+ p.d += bounds.size[i];
}
Vector3 inters;
- if (p.intersects_segment(end,begin,&inters)) {
- begin=inters;
+ if (p.intersects_segment(end, begin, &inters)) {
+ begin = inters;
}
-
}
+ int idx = _plot_ray(begin, end);
- int idx = _plot_ray(begin,end);
-
- if (idx>=0 && light_pass!=bake_cells_write[idx].light_pass) {
+ if (idx >= 0 && light_pass != bake_cells_write[idx].light_pass) {
//hit something, add or remove light to it
- Color albedo = Color(bake_cells_write[idx].albedo[0],bake_cells_write[idx].albedo[1],bake_cells_write[idx].albedo[2]);
- bake_cells_write[idx].light[0]+=albedo.r*p_color.r*p_sign;
- bake_cells_write[idx].light[1]+=albedo.g*p_color.g*p_sign;
- bake_cells_write[idx].light[2]+=albedo.b*p_color.b*p_sign;
- bake_cells_write[idx].light_pass=light_pass;
-
+ Color albedo = Color(bake_cells_write[idx].albedo[0], bake_cells_write[idx].albedo[1], bake_cells_write[idx].albedo[2]);
+ bake_cells_write[idx].light[0] += albedo.r * p_color.r * p_sign;
+ bake_cells_write[idx].light[1] += albedo.g * p_color.g * p_sign;
+ bake_cells_write[idx].light[2] += albedo.b * p_color.b * p_sign;
+ bake_cells_write[idx].light_pass = light_pass;
}
-
} else {
- int half = cells_per_axis >> (p_level+1);
+ int half = cells_per_axis >> (p_level + 1);
//go down
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
uint32_t child = bake_cells_write[p_idx].childs[i];
- if (child==CHILD_EMPTY)
+ if (child == CHILD_EMPTY)
continue;
- int nx=p_x;
- int ny=p_y;
- int nz=p_z;
-
- if (i&1)
- nx+=half;
- if (i&2)
- ny+=half;
- if (i&4)
- nz+=half;
+ int nx = p_x;
+ int ny = p_y;
+ int nz = p_z;
+ if (i & 1)
+ nx += half;
+ if (i & 2)
+ ny += half;
+ if (i & 4)
+ nz += half;
- _bake_directional(child,p_level+1,nx,ny,nz,p_dir,p_color,p_sign);
+ _bake_directional(child, p_level + 1, nx, ny, nz, p_dir, p_color, p_sign);
}
}
}
-
-
-
-void BakedLight::_bake_light(Light* p_light) {
+void BakedLight::_bake_light(Light *p_light) {
if (p_light->cast_to<DirectionalLight>()) {
- DirectionalLight * dl = p_light->cast_to<DirectionalLight>();
+ DirectionalLight *dl = p_light->cast_to<DirectionalLight>();
Transform rel_xf = dl->get_relative_transform(this);
@@ -944,91 +910,79 @@ void BakedLight::_bake_light(Light* p_light) {
Color color = dl->get_color();
float nrg = dl->get_param(Light::PARAM_ENERGY);
- color.r*=nrg;
- color.g*=nrg;
- color.b*=nrg;
+ color.r *= nrg;
+ color.g *= nrg;
+ color.b *= nrg;
light_pass++;
- _bake_directional(0,0,0,0,0,light_dir,color,1);
-
+ _bake_directional(0, 0, 0, 0, 0, light_dir, color, 1);
}
}
-
-void BakedLight::_upscale_light(int p_idx,int p_level) {
-
+void BakedLight::_upscale_light(int p_idx, int p_level) {
//go down
- float light_accum[3]={0,0,0};
- float alpha_accum=0;
+ float light_accum[3] = { 0, 0, 0 };
+ float alpha_accum = 0;
- bool check_children = p_level < (cell_subdiv -2);
+ bool check_children = p_level < (cell_subdiv - 2);
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
uint32_t child = bake_cells_write[p_idx].childs[i];
- if (child==CHILD_EMPTY)
+ if (child == CHILD_EMPTY)
continue;
if (check_children) {
- _upscale_light(child,p_level+1);
+ _upscale_light(child, p_level + 1);
}
- light_accum[0]+=bake_cells_write[child].light[0];
- light_accum[1]+=bake_cells_write[child].light[1];
- light_accum[2]+=bake_cells_write[child].light[2];
- alpha_accum+=bake_cells_write[child].alpha;
-
+ light_accum[0] += bake_cells_write[child].light[0];
+ light_accum[1] += bake_cells_write[child].light[1];
+ light_accum[2] += bake_cells_write[child].light[2];
+ alpha_accum += bake_cells_write[child].alpha;
}
- bake_cells_write[p_idx].light[0]=light_accum[0]/8.0;
- bake_cells_write[p_idx].light[1]=light_accum[1]/8.0;
- bake_cells_write[p_idx].light[2]=light_accum[2]/8.0;
- bake_cells_write[p_idx].alpha=alpha_accum/8.0;
-
+ bake_cells_write[p_idx].light[0] = light_accum[0] / 8.0;
+ bake_cells_write[p_idx].light[1] = light_accum[1] / 8.0;
+ bake_cells_write[p_idx].light[2] = light_accum[2] / 8.0;
+ bake_cells_write[p_idx].alpha = alpha_accum / 8.0;
}
-
void BakedLight::bake_lights() {
- ERR_FAIL_COND(bake_cells.size()==0);
+ ERR_FAIL_COND(bake_cells.size() == 0);
bake_cells_write = bake_cells.write();
- for(Set<Light*>::Element *E=lights.front();E;E=E->next()) {
+ for (Set<Light *>::Element *E = lights.front(); E; E = E->next()) {
_bake_light(E->get());
}
+ _upscale_light(0, 0);
- _upscale_light(0,0);
-
- bake_cells_write=PoolVector<BakeCell>::Write();
-
+ bake_cells_write = PoolVector<BakeCell>::Write();
}
+Color BakedLight::_cone_trace(const Vector3 &p_from, const Vector3 &p_dir, float p_half_angle) {
+ Color color(0, 0, 0, 0);
+ float tha = Math::tan(p_half_angle); //tan half angle
+ Vector3 from = (p_from - bounds.pos) / bounds.size; //convert to 0..1
+ from /= cells_per_axis; //convert to voxels of size 1
+ Vector3 dir = (p_dir / bounds.size).normalized();
-Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float p_half_angle) {
-
-
- Color color(0,0,0,0);
- float tha = Math::tan(p_half_angle);//tan half angle
- Vector3 from =(p_from-bounds.pos)/bounds.size; //convert to 0..1
- from/=cells_per_axis; //convert to voxels of size 1
- Vector3 dir = (p_dir/bounds.size).normalized();
-
- float max_dist = Vector3(cells_per_axis,cells_per_axis,cells_per_axis).length();
+ float max_dist = Vector3(cells_per_axis, cells_per_axis, cells_per_axis).length();
float dist = 1.0;
// self occlusion in flat surfaces
- float alpha=0;
+ float alpha = 0;
-
- while(dist < max_dist && alpha < 0.95) {
+ while (dist < max_dist && alpha < 0.95) {
#if 0
// smallest sample diameter possible is the voxel size
@@ -1149,56 +1103,55 @@ Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float
float diameter = 1.0;
Vector3 sample_pos = from + dist * dir;
- Color m(0,0,0,0);
+ Color m(0, 0, 0, 0);
{
int x = Math::floor(sample_pos.x);
int y = Math::floor(sample_pos.y);
int z = Math::floor(sample_pos.z);
- int ofs_x=0;
- int ofs_y=0;
- int ofs_z=0;
+ int ofs_x = 0;
+ int ofs_y = 0;
+ int ofs_z = 0;
int size = cells_per_axis;
- int half=size/2;
+ int half = size / 2;
- bool outside=x<0 || x>=size || y<0 || y>=size || z<0 || z>=size;
+ bool outside = x < 0 || x >= size || y < 0 || y >= size || z < 0 || z >= size;
if (!outside) {
+ uint32_t cell = 0;
- uint32_t cell=0;
-
- for(int i=0;i<cell_subdiv-1;i++) {
+ for (int i = 0; i < cell_subdiv - 1; i++) {
BakeCell *bc = &bake_cells_write[cell];
int child = 0;
if (x >= ofs_x + half) {
- child|=1;
- ofs_x+=half;
+ child |= 1;
+ ofs_x += half;
}
if (y >= ofs_y + half) {
- child|=2;
- ofs_y+=half;
+ child |= 2;
+ ofs_y += half;
}
if (z >= ofs_z + half) {
- child|=4;
- ofs_z+=half;
+ child |= 4;
+ ofs_z += half;
}
cell = bc->childs[child];
- if (cell==CHILD_EMPTY)
+ if (cell == CHILD_EMPTY)
break;
- half>>=1;
+ half >>= 1;
}
- if (cell!=CHILD_EMPTY) {
+ if (cell != CHILD_EMPTY) {
- m.r=bake_cells_write[cell].light[0];
- m.g=bake_cells_write[cell].light[1];
- m.b=bake_cells_write[cell].light[2];
- m.a=bake_cells_write[cell].alpha;
+ m.r = bake_cells_write[cell].light[0];
+ m.g = bake_cells_write[cell].light[1];
+ m.b = bake_cells_write[cell].light[2];
+ m.a = bake_cells_write[cell].alpha;
}
}
}
@@ -1219,72 +1172,64 @@ Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float
return color;
}
+void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x, int p_y, int p_z) {
-
-void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z) {
-
-
-
-
- if (p_level==cell_subdiv-1) {
+ if (p_level == cell_subdiv - 1) {
const int NUM_CONES = 6;
Vector3 cone_directions[6] = {
- Vector3(1, 0, 0),
- Vector3(0.5, 0.866025, 0),
- Vector3( 0.5, 0.267617, 0.823639),
- Vector3( 0.5, -0.700629, 0.509037),
- Vector3( 0.5, -0.700629, -0.509037),
- Vector3( 0.5, 0.267617, -0.823639)
- };
- float coneWeights[6] = {0.25, 0.15, 0.15, 0.15, 0.15, 0.15};
-
- Vector3 pos = (Vector3(p_x,p_y,p_z)/float(cells_per_axis))*bounds.size+bounds.pos;
- Vector3 voxel_size = bounds.size/float(cells_per_axis);
- pos+=voxel_size*0.5;
+ Vector3(1, 0, 0),
+ Vector3(0.5, 0.866025, 0),
+ Vector3(0.5, 0.267617, 0.823639),
+ Vector3(0.5, -0.700629, 0.509037),
+ Vector3(0.5, -0.700629, -0.509037),
+ Vector3(0.5, 0.267617, -0.823639)
+ };
+ float coneWeights[6] = { 0.25, 0.15, 0.15, 0.15, 0.15, 0.15 };
+
+ Vector3 pos = (Vector3(p_x, p_y, p_z) / float(cells_per_axis)) * bounds.size + bounds.pos;
+ Vector3 voxel_size = bounds.size / float(cells_per_axis);
+ pos += voxel_size * 0.5;
Color accum;
- bake_cells_write[p_idx].light[0]=0;
- bake_cells_write[p_idx].light[1]=0;
- bake_cells_write[p_idx].light[2]=0;
+ bake_cells_write[p_idx].light[0] = 0;
+ bake_cells_write[p_idx].light[1] = 0;
+ bake_cells_write[p_idx].light[2] = 0;
- int freepix=0;
- for(int i=0;i<6;i++) {
+ int freepix = 0;
+ for (int i = 0; i < 6; i++) {
- if (!(bake_cells_write[p_idx].used_sides&(1<<i)))
+ if (!(bake_cells_write[p_idx].used_sides & (1 << i)))
continue;
- if ((i&1)==0)
- bake_cells_write[p_idx].light[i/2]=1.0;
+ if ((i & 1) == 0)
+ bake_cells_write[p_idx].light[i / 2] = 1.0;
freepix++;
continue;
- int ofs = i/2;
+ int ofs = i / 2;
Vector3 dir;
- if ((i&1)==0)
- dir[ofs]=1.0;
+ if ((i & 1) == 0)
+ dir[ofs] = 1.0;
else
- dir[ofs]=-1.0;
-
- for(int j=0;j<1;j++) {
+ dir[ofs] = -1.0;
+ for (int j = 0; j < 1; j++) {
Vector3 cone_dir;
- cone_dir.x = cone_directions[j][(ofs+0)%3];
- cone_dir.y = cone_directions[j][(ofs+1)%3];
- cone_dir.z = cone_directions[j][(ofs+2)%3];
+ cone_dir.x = cone_directions[j][(ofs + 0) % 3];
+ cone_dir.y = cone_directions[j][(ofs + 1) % 3];
+ cone_dir.z = cone_directions[j][(ofs + 2) % 3];
- cone_dir[ofs]*=dir[ofs];
+ cone_dir[ofs] *= dir[ofs];
- Color res = _cone_trace(pos+dir*voxel_size,cone_dir,Math::deg2rad(29.9849));
- accum.r+=res.r;//*coneWeights[j];
- accum.g+=res.g;//*coneWeights[j];
- accum.b+=res.b;//*coneWeights[j];
+ Color res = _cone_trace(pos + dir * voxel_size, cone_dir, Math::deg2rad(29.9849));
+ accum.r += res.r; //*coneWeights[j];
+ accum.g += res.g; //*coneWeights[j];
+ accum.b += res.b; //*coneWeights[j];
}
-
-
}
#if 0
if (freepix==0) {
@@ -1333,108 +1278,101 @@ void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z)
//bake_cells_write[p_idx].radiance[1]=accum.g;
//bake_cells_write[p_idx].radiance[2]=accum.b;
-
} else {
- int half = cells_per_axis >> (p_level+1);
+ int half = cells_per_axis >> (p_level + 1);
//go down
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
uint32_t child = bake_cells_write[p_idx].childs[i];
- if (child==CHILD_EMPTY)
+ if (child == CHILD_EMPTY)
continue;
- int nx=p_x;
- int ny=p_y;
- int nz=p_z;
-
- if (i&1)
- nx+=half;
- if (i&2)
- ny+=half;
- if (i&4)
- nz+=half;
+ int nx = p_x;
+ int ny = p_y;
+ int nz = p_z;
+ if (i & 1)
+ nx += half;
+ if (i & 2)
+ ny += half;
+ if (i & 4)
+ nz += half;
- _bake_radiance(child,p_level+1,nx,ny,nz);
+ _bake_radiance(child, p_level + 1, nx, ny, nz);
}
}
}
void BakedLight::bake_radiance() {
- ERR_FAIL_COND(bake_cells.size()==0);
+ ERR_FAIL_COND(bake_cells.size() == 0);
bake_cells_write = bake_cells.write();
- _bake_radiance(0,0,0,0,0);
-
- bake_cells_write=PoolVector<BakeCell>::Write();
+ _bake_radiance(0, 0, 0, 0, 0);
+ bake_cells_write = PoolVector<BakeCell>::Write();
}
-int BakedLight::_find_cell(int x,int y, int z) {
-
+int BakedLight::_find_cell(int x, int y, int z) {
- uint32_t cell=0;
+ uint32_t cell = 0;
- int ofs_x=0;
- int ofs_y=0;
- int ofs_z=0;
+ int ofs_x = 0;
+ int ofs_y = 0;
+ int ofs_z = 0;
int size = cells_per_axis;
- int half=size/2;
+ int half = size / 2;
- if (x<0 || x>=size)
+ if (x < 0 || x >= size)
return -1;
- if (y<0 || y>=size)
+ if (y < 0 || y >= size)
return -1;
- if (z<0 || z>=size)
+ if (z < 0 || z >= size)
return -1;
- for(int i=0;i<cell_subdiv-1;i++) {
+ for (int i = 0; i < cell_subdiv - 1; i++) {
BakeCell *bc = &bake_cells_write[cell];
int child = 0;
if (x >= ofs_x + half) {
- child|=1;
- ofs_x+=half;
+ child |= 1;
+ ofs_x += half;
}
if (y >= ofs_y + half) {
- child|=2;
- ofs_y+=half;
+ child |= 2;
+ ofs_y += half;
}
if (z >= ofs_z + half) {
- child|=4;
- ofs_z+=half;
+ child |= 4;
+ ofs_z += half;
}
cell = bc->childs[child];
- if (cell==CHILD_EMPTY)
+ if (cell == CHILD_EMPTY)
return -1;
- half>>=1;
+ half >>= 1;
}
return cell;
-
}
-
-int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) {
+int BakedLight::_plot_ray(const Vector3 &p_from, const Vector3 &p_to) {
Vector3 from = (p_from - bounds.pos) / bounds.size;
Vector3 to = (p_to - bounds.pos) / bounds.size;
- int x1 = Math::floor(from.x*cells_per_axis);
- int y1 = Math::floor(from.y*cells_per_axis);
- int z1 = Math::floor(from.z*cells_per_axis);
-
- int x2 = Math::floor(to.x*cells_per_axis);
- int y2 = Math::floor(to.y*cells_per_axis);
- int z2 = Math::floor(to.z*cells_per_axis);
+ int x1 = Math::floor(from.x * cells_per_axis);
+ int y1 = Math::floor(from.y * cells_per_axis);
+ int z1 = Math::floor(from.z * cells_per_axis);
+ int x2 = Math::floor(to.x * cells_per_axis);
+ int y2 = Math::floor(to.y * cells_per_axis);
+ int z2 = Math::floor(to.z * cells_per_axis);
int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2;
int point[3];
@@ -1459,8 +1397,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) {
err_1 = dy2 - l;
err_2 = dz2 - l;
for (i = 0; i < l; i++) {
- int cell = _find_cell(point[0],point[1],point[2]);
- if (cell>=0)
+ int cell = _find_cell(point[0], point[1], point[2]);
+ if (cell >= 0)
return cell;
if (err_1 > 0) {
@@ -1479,8 +1417,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) {
err_1 = dx2 - m;
err_2 = dz2 - m;
for (i = 0; i < m; i++) {
- int cell = _find_cell(point[0],point[1],point[2]);
- if (cell>=0)
+ int cell = _find_cell(point[0], point[1], point[2]);
+ if (cell >= 0)
return cell;
if (err_1 > 0) {
point[0] += x_inc;
@@ -1498,8 +1436,8 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) {
err_1 = dy2 - n;
err_2 = dx2 - n;
for (i = 0; i < n; i++) {
- int cell = _find_cell(point[0],point[1],point[2]);
- if (cell>=0)
+ int cell = _find_cell(point[0], point[1], point[2]);
+ if (cell >= 0)
return cell;
if (err_1 > 0) {
@@ -1515,14 +1453,12 @@ int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) {
point[2] += z_inc;
}
}
- return _find_cell(point[0],point[1],point[2]);
-
+ return _find_cell(point[0], point[1], point[2]);
}
-
void BakedLight::set_cell_subdiv(int p_subdiv) {
- cell_subdiv=p_subdiv;
+ cell_subdiv = p_subdiv;
//VS::get_singleton()->baked_light_set_subdivision(baked_light,p_subdiv);
}
@@ -1532,77 +1468,67 @@ int BakedLight::get_cell_subdiv() const {
return cell_subdiv;
}
-
-
Rect3 BakedLight::get_aabb() const {
- return Rect3(Vector3(0,0,0),Vector3(1,1,1));
+ return Rect3(Vector3(0, 0, 0), Vector3(1, 1, 1));
}
PoolVector<Face3> BakedLight::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
}
-
String BakedLight::get_configuration_warning() const {
return String();
}
+void BakedLight::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, DebugMode p_mode, Ref<MultiMesh> &p_multimesh, int &idx) {
-void BakedLight::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,DebugMode p_mode,Ref<MultiMesh> &p_multimesh,int &idx) {
+ if (p_level == cell_subdiv - 1) {
-
- if (p_level==cell_subdiv-1) {
-
- Vector3 center = p_aabb.pos+p_aabb.size*0.5;
+ Vector3 center = p_aabb.pos + p_aabb.size * 0.5;
Transform xform;
- xform.origin=center;
- xform.basis.scale(p_aabb.size*0.5);
- p_multimesh->set_instance_transform(idx,xform);
+ xform.origin = center;
+ xform.basis.scale(p_aabb.size * 0.5);
+ p_multimesh->set_instance_transform(idx, xform);
Color col;
- switch(p_mode) {
+ switch (p_mode) {
case DEBUG_ALBEDO: {
- col=Color(bake_cells_write[p_idx].albedo[0],bake_cells_write[p_idx].albedo[1],bake_cells_write[p_idx].albedo[2]);
+ col = Color(bake_cells_write[p_idx].albedo[0], bake_cells_write[p_idx].albedo[1], bake_cells_write[p_idx].albedo[2]);
} break;
case DEBUG_LIGHT: {
- col=Color(bake_cells_write[p_idx].light[0],bake_cells_write[p_idx].light[1],bake_cells_write[p_idx].light[2]);
- Color colr=Color(bake_cells_write[p_idx].radiance[0],bake_cells_write[p_idx].radiance[1],bake_cells_write[p_idx].radiance[2]);
- col.r+=colr.r;
- col.g+=colr.g;
- col.b+=colr.b;
+ col = Color(bake_cells_write[p_idx].light[0], bake_cells_write[p_idx].light[1], bake_cells_write[p_idx].light[2]);
+ Color colr = Color(bake_cells_write[p_idx].radiance[0], bake_cells_write[p_idx].radiance[1], bake_cells_write[p_idx].radiance[2]);
+ col.r += colr.r;
+ col.g += colr.g;
+ col.b += colr.b;
} break;
-
}
- p_multimesh->set_instance_color(idx,col);
-
+ p_multimesh->set_instance_color(idx, col);
idx++;
} else {
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY)
+ if (bake_cells_write[p_idx].childs[i] == CHILD_EMPTY)
continue;
- Rect3 aabb=p_aabb;
- aabb.size*=0.5;
+ Rect3 aabb = p_aabb;
+ aabb.size *= 0.5;
- if (i&1)
- aabb.pos.x+=aabb.size.x;
- if (i&2)
- aabb.pos.y+=aabb.size.y;
- if (i&4)
- aabb.pos.z+=aabb.size.z;
+ if (i & 1)
+ aabb.pos.x += aabb.size.x;
+ if (i & 2)
+ aabb.pos.y += aabb.size.y;
+ if (i & 4)
+ aabb.pos.z += aabb.size.z;
- _debug_mesh(bake_cells_write[p_idx].childs[i],p_level+1,aabb,p_mode,p_multimesh,idx);
+ _debug_mesh(bake_cells_write[p_idx].childs[i], p_level + 1, aabb, p_mode, p_multimesh, idx);
}
-
}
-
}
-
void BakedLight::create_debug_mesh(DebugMode p_mode) {
Ref<MultiMesh> mm;
@@ -1610,13 +1536,11 @@ void BakedLight::create_debug_mesh(DebugMode p_mode) {
mm->set_transform_format(MultiMesh::TRANSFORM_3D);
mm->set_color_format(MultiMesh::COLOR_8BIT);
- mm->set_instance_count(bake_cells_level_used[cell_subdiv-1]);
+ mm->set_instance_count(bake_cells_level_used[cell_subdiv - 1]);
Ref<Mesh> mesh;
mesh.instance();
-
-
{
Array arr;
arr.resize(Mesh::ARRAY_MAX);
@@ -1624,83 +1548,76 @@ void BakedLight::create_debug_mesh(DebugMode p_mode) {
PoolVector<Vector3> vertices;
PoolVector<Color> colors;
- int vtx_idx=0;
- #define ADD_VTX(m_idx);\
- vertices.push_back( face_points[m_idx] );\
- colors.push_back( Color(1,1,1,1) );\
- vtx_idx++;\
-
- for (int i=0;i<6;i++) {
+ int vtx_idx = 0;
+#define ADD_VTX(m_idx) \
+ ; \
+ vertices.push_back(face_points[m_idx]); \
+ colors.push_back(Color(1, 1, 1, 1)); \
+ vtx_idx++;
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
}
- //tri 1
+ //tri 1
ADD_VTX(0);
ADD_VTX(1);
ADD_VTX(2);
- //tri 2
+ //tri 2
ADD_VTX(2);
ADD_VTX(3);
ADD_VTX(0);
-
}
-
- arr[Mesh::ARRAY_VERTEX]=vertices;
- arr[Mesh::ARRAY_COLOR]=colors;
- mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr);
+ arr[Mesh::ARRAY_VERTEX] = vertices;
+ arr[Mesh::ARRAY_COLOR] = colors;
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
}
{
Ref<FixedSpatialMaterial> fsm;
fsm.instance();
- fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
- fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- fsm->set_albedo(Color(1,1,1,1));
+ fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
+ fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ fsm->set_albedo(Color(1, 1, 1, 1));
- mesh->surface_set_material(0,fsm);
+ mesh->surface_set_material(0, fsm);
}
mm->set_mesh(mesh);
-
bake_cells_write = bake_cells.write();
+ int idx = 0;
+ _debug_mesh(0, 0, bounds, p_mode, mm, idx);
+ print_line("written: " + itos(idx) + " total: " + itos(bake_cells_level_used[cell_subdiv - 1]));
- int idx=0;
- _debug_mesh(0,0,bounds,p_mode,mm,idx);
-
- print_line("written: "+itos(idx)+" total: "+itos(bake_cells_level_used[cell_subdiv-1]));
-
-
- MultiMeshInstance *mmi = memnew( MultiMeshInstance );
+ MultiMeshInstance *mmi = memnew(MultiMeshInstance);
mmi->set_multimesh(mm);
add_child(mmi);
#ifdef TOOLS_ENABLED
- if (get_tree()->get_edited_scene_root()==this){
+ if (get_tree()->get_edited_scene_root() == this) {
mmi->set_owner(this);
} else {
mmi->set_owner(get_owner());
-
}
#else
mmi->set_owner(get_owner());
@@ -1715,45 +1632,41 @@ void BakedLight::_debug_mesh_light() {
create_debug_mesh(DEBUG_LIGHT);
}
-
void BakedLight::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_cell_subdiv","steps"),&BakedLight::set_cell_subdiv);
- ClassDB::bind_method(D_METHOD("get_cell_subdiv"),&BakedLight::get_cell_subdiv);
-
- ClassDB::bind_method(D_METHOD("bake"),&BakedLight::bake);
- ClassDB::set_method_flags(get_class_static(),_scs_create("bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("set_cell_subdiv", "steps"), &BakedLight::set_cell_subdiv);
+ ClassDB::bind_method(D_METHOD("get_cell_subdiv"), &BakedLight::get_cell_subdiv);
- ClassDB::bind_method(D_METHOD("bake_lights"),&BakedLight::bake_lights);
- ClassDB::set_method_flags(get_class_static(),_scs_create("bake_lights"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("bake"), &BakedLight::bake);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("bake_radiance"),&BakedLight::bake_radiance);
- ClassDB::set_method_flags(get_class_static(),_scs_create("bake_radiance"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("bake_lights"), &BakedLight::bake_lights);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("bake_lights"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("debug_mesh_albedo"),&BakedLight::_debug_mesh_albedo);
- ClassDB::set_method_flags(get_class_static(),_scs_create("debug_mesh_albedo"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("bake_radiance"), &BakedLight::bake_radiance);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("bake_radiance"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("debug_mesh_albedo"), &BakedLight::_debug_mesh_albedo);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("debug_mesh_albedo"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("debug_mesh_light"),&BakedLight::_debug_mesh_light);
- ClassDB::set_method_flags(get_class_static(),_scs_create("debug_mesh_light"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"cell_subdiv"),"set_cell_subdiv","get_cell_subdiv");
- ADD_SIGNAL( MethodInfo("baked_light_changed"));
+ ClassDB::bind_method(D_METHOD("debug_mesh_light"), &BakedLight::_debug_mesh_light);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("debug_mesh_light"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cell_subdiv"), "set_cell_subdiv", "get_cell_subdiv");
+ ADD_SIGNAL(MethodInfo("baked_light_changed"));
}
BakedLight::BakedLight() {
//baked_light=VisualServer::get_singleton()->baked_light_create();
- VS::get_singleton()->instance_set_base(get_instance(),baked_light);
+ VS::get_singleton()->instance_set_base(get_instance(), baked_light);
- cell_subdiv=8;
- bake_texture_size=128;
- color_scan_cell_width=8;
- light_pass=0;
+ cell_subdiv = 8;
+ bake_texture_size = 128;
+ color_scan_cell_width = 8;
+ light_pass = 0;
}
-
BakedLight::~BakedLight() {
VS::get_singleton()->free(baked_light);
diff --git a/scene/3d/baked_light_instance.h b/scene/3d/baked_light_instance.h
index 2fda26ecea..2180f8b175 100644
--- a/scene/3d/baked_light_instance.h
+++ b/scene/3d/baked_light_instance.h
@@ -29,16 +29,15 @@
#ifndef BAKED_LIGHT_INSTANCE_H
#define BAKED_LIGHT_INSTANCE_H
+#include "scene/3d/multimesh_instance.h"
#include "scene/3d/visual_instance.h"
#include "scene/resources/baked_light.h"
-#include "scene/3d/multimesh_instance.h"
-
class BakedLightBaker;
class Light;
class BakedLight : public VisualInstance {
- GDCLASS(BakedLight,VisualInstance);
+ GDCLASS(BakedLight, VisualInstance);
public:
enum DebugMode {
@@ -53,10 +52,9 @@ private:
int cells_per_axis;
enum {
- CHILD_EMPTY=0xFFFFFFFF,
+ CHILD_EMPTY = 0xFFFFFFFF,
};
-
/* BAKE DATA */
struct BakeCell {
@@ -70,22 +68,21 @@ private:
uint32_t light_pass; //used for baking light
BakeCell() {
- for(int i=0;i<8;i++) {
- childs[i]=0xFFFFFFFF;
+ for (int i = 0; i < 8; i++) {
+ childs[i] = 0xFFFFFFFF;
}
- for(int i=0;i<3;i++) {
- light[i]=0;
- albedo[i]=0;
- radiance[i]=0;
+ for (int i = 0; i < 3; i++) {
+ light[i] = 0;
+ albedo[i] = 0;
+ radiance[i] = 0;
}
- alpha=0;
- light_pass=0;
- used_sides=0;
+ alpha = 0;
+ light_pass = 0;
+ used_sides = 0;
}
};
-
int bake_texture_size;
int color_scan_cell_width;
@@ -95,12 +92,9 @@ private:
Vector<Color> emission;
};
-
Vector<Color> _get_bake_texture(Image &p_image, const Color &p_color);
-
-
- Map<Ref<Material>,MaterialCache> material_cache;
+ Map<Ref<Material>, MaterialCache> material_cache;
MaterialCache _get_material_cache(Ref<Material> p_material);
int bake_cells_alloc;
@@ -110,42 +104,38 @@ private:
PoolVector<BakeCell> bake_cells;
PoolVector<BakeCell>::Write bake_cells_write;
-
-
- void _plot_face(int p_idx,int p_level,const Vector3 *p_vtx,const Vector2* p_uv, const MaterialCache& p_material,const Rect3& p_aabb);
+ void _plot_face(int p_idx, int p_level, const Vector3 *p_vtx, const Vector2 *p_uv, const MaterialCache &p_material, const Rect3 &p_aabb);
void _fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z);
- void _bake_add_mesh(const Transform& p_xform,Ref<Mesh>& p_mesh);
- void _bake_add_to_aabb(const Transform& p_xform,Ref<Mesh>& p_mesh,bool &first);
+ void _bake_add_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh);
+ void _bake_add_to_aabb(const Transform &p_xform, Ref<Mesh> &p_mesh, bool &first);
- void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,DebugMode p_mode,Ref<MultiMesh> &p_multimesh,int &idx);
+ void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, DebugMode p_mode, Ref<MultiMesh> &p_multimesh, int &idx);
void _debug_mesh_albedo();
void _debug_mesh_light();
-
- _FORCE_INLINE_ int _find_cell(int x,int y, int z);
- int _plot_ray(const Vector3& p_from, const Vector3& p_to);
+ _FORCE_INLINE_ int _find_cell(int x, int y, int z);
+ int _plot_ray(const Vector3 &p_from, const Vector3 &p_to);
uint32_t light_pass;
+ void _bake_directional(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 &p_dir, const Color &p_color, int p_sign);
+ void _upscale_light(int p_idx, int p_level);
+ void _bake_light(Light *p_light);
- void _bake_directional(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3& p_dir,const Color& p_color,int p_sign);
- void _upscale_light(int p_idx,int p_level);
- void _bake_light(Light* p_light);
+ Color _cone_trace(const Vector3 &p_from, const Vector3 &p_dir, float p_half_angle);
+ void _bake_radiance(int p_idx, int p_level, int p_x, int p_y, int p_z);
- Color _cone_trace(const Vector3& p_from, const Vector3& p_dir, float p_half_angle);
- void _bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z);
+ friend class GeometryInstance;
-friend class GeometryInstance;
+ Set<GeometryInstance *> geometries;
+ friend class Light;
- Set<GeometryInstance*> geometries;
-friend class Light;
+ Set<Light *> lights;
- Set<Light*> lights;
protected:
-
static void _bind_methods();
-public:
+public:
void set_cell_subdiv(int p_subdiv);
int get_cell_subdiv() const;
@@ -153,7 +143,6 @@ public:
void bake_lights();
void bake_radiance();
-
void create_debug_mesh(DebugMode p_mode);
virtual Rect3 get_aabb() const;
@@ -165,7 +154,6 @@ public:
~BakedLight();
};
-
#if 0
class BakedLightSampler : public VisualInstance {
GDCLASS(BakedLightSampler,VisualInstance);
diff --git a/scene/3d/body_shape.cpp b/scene/3d/body_shape.cpp
index af3fe3c0a4..8403806570 100644
--- a/scene/3d/body_shape.cpp
+++ b/scene/3d/body_shape.cpp
@@ -27,14 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "body_shape.h"
-#include "servers/visual_server.h"
-#include "scene/resources/sphere_shape.h"
-#include "scene/resources/ray_shape.h"
#include "scene/resources/box_shape.h"
#include "scene/resources/capsule_shape.h"
-#include "scene/resources/convex_polygon_shape.h"
#include "scene/resources/concave_polygon_shape.h"
+#include "scene/resources/convex_polygon_shape.h"
#include "scene/resources/plane_shape.h"
+#include "scene/resources/ray_shape.h"
+#include "scene/resources/sphere_shape.h"
+#include "servers/visual_server.h"
//TODO: Implement CylinderShape and HeightMapShape?
#include "mesh_instance.h"
#include "physics_body.h"
@@ -48,7 +48,6 @@ void CollisionShape::_update_body() {
return;
if (get_parent() && get_parent()->cast_to<CollisionObject>())
get_parent()->cast_to<CollisionObject>()->_update_shapes_from_children();
-
}
void CollisionShape::make_convex_from_brothers() {
@@ -57,12 +56,12 @@ void CollisionShape::make_convex_from_brothers() {
if (!p)
return;
- for(int i=0;i<p->get_child_count();i++) {
+ for (int i = 0; i < p->get_child_count(); i++) {
Node *n = p->get_child(i);
if (n->cast_to<MeshInstance>()) {
- MeshInstance *mi=n->cast_to<MeshInstance>();
+ MeshInstance *mi = n->cast_to<MeshInstance>();
Ref<Mesh> m = mi->get_mesh();
if (m.is_valid()) {
@@ -71,7 +70,6 @@ void CollisionShape::make_convex_from_brothers() {
}
}
}
-
}
/*
@@ -302,32 +300,32 @@ void CollisionShape::_update_indicator() {
}
*/
-void CollisionShape::_add_to_collision_object(Object* p_cshape) {
+void CollisionShape::_add_to_collision_object(Object *p_cshape) {
if (unparenting)
return;
- CollisionObject *co=p_cshape->cast_to<CollisionObject>();
+ CollisionObject *co = p_cshape->cast_to<CollisionObject>();
ERR_FAIL_COND(!co);
if (shape.is_valid()) {
- update_shape_index=co->get_shape_count();
- co->add_shape(shape,get_transform());
+ update_shape_index = co->get_shape_count();
+ co->add_shape(shape, get_transform());
if (trigger)
- co->set_shape_as_trigger( co->get_shape_count() -1, true );
+ co->set_shape_as_trigger(co->get_shape_count() - 1, true);
} else {
- update_shape_index=-1;
+ update_shape_index = -1;
}
}
void CollisionShape::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- unparenting=false;
- can_update_body=get_tree()->is_editor_hint();
+ unparenting = false;
+ can_update_body = get_tree()->is_editor_hint();
set_notify_local_transform(!can_update_body);
if (get_tree()->is_debugging_collisions_hint()) {
@@ -343,19 +341,19 @@ void CollisionShape::_notification(int p_what) {
}
} break;
case NOTIFICATION_EXIT_TREE: {
- /* if (indicator_instance.is_valid()) {
+ /* if (indicator_instance.is_valid()) {
VisualServer::get_singleton()->free(indicator_instance);
indicator_instance=RID();
}*/
- can_update_body=false;
+ can_update_body = false;
set_notify_local_transform(false);
if (debug_shape) {
debug_shape->queue_delete();
- debug_shape=NULL;
+ debug_shape = NULL;
}
} break;
case NOTIFICATION_UNPARENTED: {
- unparenting=true;
+ unparenting = true;
if (can_update_body && updating_body)
_update_body();
} break;
@@ -365,34 +363,29 @@ void CollisionShape::_notification(int p_what) {
} break;
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
- if (!can_update_body && update_shape_index>=0) {
+ if (!can_update_body && update_shape_index >= 0) {
CollisionObject *co = get_parent()->cast_to<CollisionObject>();
if (co) {
- co->set_shape_transform(update_shape_index,get_transform());
+ co->set_shape_transform(update_shape_index, get_transform());
}
}
} break;
-
}
}
-
void CollisionShape::resource_changed(RES res) {
update_gizmo();
-
-
}
void CollisionShape::_set_update_shape_index(int p_index) {
-
- update_shape_index=p_index;
+ update_shape_index = p_index;
}
-int CollisionShape::_get_update_shape_index() const{
+int CollisionShape::_get_update_shape_index() const {
return update_shape_index;
}
@@ -410,45 +403,42 @@ String CollisionShape::get_configuration_warning() const {
return String();
}
-
void CollisionShape::_bind_methods() {
//not sure if this should do anything
- ClassDB::bind_method(D_METHOD("resource_changed","resource"),&CollisionShape::resource_changed);
- ClassDB::bind_method(D_METHOD("set_shape","shape"),&CollisionShape::set_shape);
- ClassDB::bind_method(D_METHOD("get_shape"),&CollisionShape::get_shape);
- ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionShape::_add_to_collision_object);
- ClassDB::bind_method(D_METHOD("set_trigger","enable"),&CollisionShape::set_trigger);
- ClassDB::bind_method(D_METHOD("is_trigger"),&CollisionShape::is_trigger);
- ClassDB::bind_method(D_METHOD("make_convex_from_brothers"),&CollisionShape::make_convex_from_brothers);
- ClassDB::set_method_flags("CollisionShape","make_convex_from_brothers",METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("_set_update_shape_index","index"),&CollisionShape::_set_update_shape_index);
- ClassDB::bind_method(D_METHOD("_get_update_shape_index"),&CollisionShape::_get_update_shape_index);
+ ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &CollisionShape::resource_changed);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape"), &CollisionShape::set_shape);
+ ClassDB::bind_method(D_METHOD("get_shape"), &CollisionShape::get_shape);
+ ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionShape::_add_to_collision_object);
+ ClassDB::bind_method(D_METHOD("set_trigger", "enable"), &CollisionShape::set_trigger);
+ ClassDB::bind_method(D_METHOD("is_trigger"), &CollisionShape::is_trigger);
+ ClassDB::bind_method(D_METHOD("make_convex_from_brothers"), &CollisionShape::make_convex_from_brothers);
+ ClassDB::set_method_flags("CollisionShape", "make_convex_from_brothers", METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("_set_update_shape_index", "index"), &CollisionShape::_set_update_shape_index);
+ ClassDB::bind_method(D_METHOD("_get_update_shape_index"), &CollisionShape::_get_update_shape_index);
- ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"),&CollisionShape::get_collision_object_shape_index);
+ ClassDB::bind_method(D_METHOD("get_collision_object_shape_index"), &CollisionShape::get_collision_object_shape_index);
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape"), "set_shape", "get_shape");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"trigger"),"set_trigger","is_trigger");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape"), "set_shape", "get_shape");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "trigger"), "set_trigger", "is_trigger");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "_update_shape_index", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_update_shape_index", "_get_update_shape_index");
}
-
void CollisionShape::set_shape(const Ref<Shape> &p_shape) {
if (!shape.is_null())
shape->unregister_owner(this);
- shape=p_shape;
+ shape = p_shape;
if (!shape.is_null())
shape->register_owner(this);
update_gizmo();
if (updating_body) {
_update_body();
- } else if (can_update_body && update_shape_index>=0 && is_inside_tree()){
+ } else if (can_update_body && update_shape_index >= 0 && is_inside_tree()) {
CollisionObject *co = get_parent()->cast_to<CollisionObject>();
if (co) {
- co->set_shape(update_shape_index,p_shape);
+ co->set_shape(update_shape_index, p_shape);
}
-
}
}
@@ -457,9 +447,8 @@ Ref<Shape> CollisionShape::get_shape() const {
return shape;
}
-
void CollisionShape::set_updating_body(bool p_update) {
- updating_body=p_update;
+ updating_body = p_update;
}
bool CollisionShape::is_updating_body() const {
@@ -469,31 +458,31 @@ bool CollisionShape::is_updating_body() const {
void CollisionShape::set_trigger(bool p_trigger) {
- trigger=p_trigger;
- if (updating_body) {
- _update_body();
- } else if (can_update_body && update_shape_index>=0 && is_inside_tree()){
- CollisionObject *co = get_parent()->cast_to<CollisionObject>();
- if (co) {
- co->set_shape_as_trigger(update_shape_index,p_trigger);
- }
- }
+ trigger = p_trigger;
+ if (updating_body) {
+ _update_body();
+ } else if (can_update_body && update_shape_index >= 0 && is_inside_tree()) {
+ CollisionObject *co = get_parent()->cast_to<CollisionObject>();
+ if (co) {
+ co->set_shape_as_trigger(update_shape_index, p_trigger);
+ }
+ }
}
-bool CollisionShape::is_trigger() const{
+bool CollisionShape::is_trigger() const {
- return trigger;
+ return trigger;
}
CollisionShape::CollisionShape() {
//indicator = VisualServer::get_singleton()->mesh_create();
- updating_body=true;
- unparenting=false;
- update_shape_index=-1;
- trigger=false;
- can_update_body=false;
- debug_shape=NULL;
+ updating_body = true;
+ unparenting = false;
+ update_shape_index = -1;
+ trigger = false;
+ can_update_body = false;
+ debug_shape = NULL;
}
CollisionShape::~CollisionShape() {
@@ -504,10 +493,9 @@ CollisionShape::~CollisionShape() {
void CollisionShape::_create_debug_shape() {
-
if (debug_shape) {
debug_shape->queue_delete();
- debug_shape=NULL;
+ debug_shape = NULL;
}
Ref<Shape> s = get_shape();
@@ -515,37 +503,35 @@ void CollisionShape::_create_debug_shape() {
if (s.is_null())
return;
-
Ref<Mesh> mesh = s->get_debug_mesh();
- MeshInstance *mi = memnew( MeshInstance );
+ MeshInstance *mi = memnew(MeshInstance);
mi->set_mesh(mesh);
add_child(mi);
- debug_shape=mi;
-
+ debug_shape = mi;
}
#if 0
#include "body_volume.h"
-#include "scene/3d/physics_body.h"
#include "geometry.h"
+#include "scene/3d/physics_body.h"
-#define ADD_TRIANGLE( m_a, m_b, m_c, m_color)\
-{\
- Vector<Vector3> points;\
- points.resize(3);\
- points[0]=m_a;\
- points[1]=m_b;\
- points[2]=m_c;\
- Vector<Color> colors;\
- colors.resize(3);\
- colors[0]=m_color;\
- colors[1]=m_color;\
- colors[2]=m_color;\
- vs->poly_add_primitive(p_indicator,points,Vector<Vector3>(),colors,Vector<Vector3>());\
-}
+#define ADD_TRIANGLE(m_a, m_b, m_c, m_color) \
+ { \
+ Vector<Vector3> points; \
+ points.resize(3); \
+ points[0] = m_a; \
+ points[1] = m_b; \
+ points[2] = m_c; \
+ Vector<Color> colors; \
+ colors.resize(3); \
+ colors[0] = m_color; \
+ colors[1] = m_color; \
+ colors[2] = m_color; \
+ vs->poly_add_primitive(p_indicator, points, Vector<Vector3>(), colors, Vector<Vector3>()); \
+ }
void CollisionShape::_notification(int p_what) {
diff --git a/scene/3d/body_shape.h b/scene/3d/body_shape.h
index a7c3678251..137a6cd9fc 100644
--- a/scene/3d/body_shape.h
+++ b/scene/3d/body_shape.h
@@ -34,7 +34,7 @@
class CollisionShape : public Spatial {
- GDCLASS( CollisionShape, Spatial );
+ GDCLASS(CollisionShape, Spatial);
OBJ_CATEGORY("3D Physics Nodes");
Ref<Shape> shape;
@@ -50,7 +50,7 @@ class CollisionShape : public Spatial {
RID indicator_instance;
*/
- Node* debug_shape;
+ Node *debug_shape;
void resource_changed(RES res);
@@ -63,7 +63,7 @@ class CollisionShape : public Spatial {
int update_shape_index;
void _update_body();
- void _add_to_collision_object(Object* p_cshape);
+ void _add_to_collision_object(Object *p_cshape);
void _set_update_shape_index(int p_index);
int _get_update_shape_index() const;
@@ -71,12 +71,10 @@ class CollisionShape : public Spatial {
void _create_debug_shape();
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
void make_convex_from_brothers();
void set_shape(const Ref<Shape> &p_shape);
@@ -90,7 +88,6 @@ public:
int get_collision_object_shape_index() const { return _get_update_shape_index(); }
-
String get_configuration_warning() const;
CollisionShape();
@@ -98,4 +95,3 @@ public:
};
#endif // BODY_VOLUME_H
-
diff --git a/scene/3d/bone_attachment.cpp b/scene/3d/bone_attachment.cpp
index 1a2680e3b8..d8cb2dfdac 100644
--- a/scene/3d/bone_attachment.cpp
+++ b/scene/3d/bone_attachment.cpp
@@ -28,19 +28,19 @@
/*************************************************************************/
#include "bone_attachment.h"
-bool BoneAttachment::_get(const StringName& p_name,Variant &r_ret) const {
+bool BoneAttachment::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name)=="bone_name") {
+ if (String(p_name) == "bone_name") {
- r_ret=get_bone_name();
+ r_ret = get_bone_name();
return true;
}
return false;
}
-bool BoneAttachment::_set(const StringName& p_name, const Variant& p_value){
+bool BoneAttachment::_set(const StringName &p_name, const Variant &p_value) {
- if (String(p_name)=="bone_name") {
+ if (String(p_name) == "bone_name") {
set_bone_name(p_value);
return true;
@@ -48,40 +48,37 @@ bool BoneAttachment::_set(const StringName& p_name, const Variant& p_value){
return false;
}
-void BoneAttachment::_get_property_list( List<PropertyInfo>* p_list ) const{
+void BoneAttachment::_get_property_list(List<PropertyInfo> *p_list) const {
- Skeleton *parent=NULL;
- if(get_parent())
- parent=get_parent()->cast_to<Skeleton>();
+ Skeleton *parent = NULL;
+ if (get_parent())
+ parent = get_parent()->cast_to<Skeleton>();
if (parent) {
String names;
- for(int i=0;i<parent->get_bone_count();i++) {
- if(i>0)
- names+=",";
- names+=parent->get_bone_name(i);
+ for (int i = 0; i < parent->get_bone_count(); i++) {
+ if (i > 0)
+ names += ",";
+ names += parent->get_bone_name(i);
}
- p_list->push_back(PropertyInfo(Variant::STRING,"bone_name",PROPERTY_HINT_ENUM,names));
+ p_list->push_back(PropertyInfo(Variant::STRING, "bone_name", PROPERTY_HINT_ENUM, names));
} else {
- p_list->push_back(PropertyInfo(Variant::STRING,"bone_name"));
-
+ p_list->push_back(PropertyInfo(Variant::STRING, "bone_name"));
}
-
}
-
void BoneAttachment::_check_bind() {
if (get_parent() && get_parent()->cast_to<Skeleton>()) {
Skeleton *sk = get_parent()->cast_to<Skeleton>();
int idx = sk->find_bone(bone_name);
- if (idx!=-1) {
- sk->bind_child_node_to_bone(idx,this);
+ if (idx != -1) {
+ sk->bind_child_node_to_bone(idx, this);
set_transform(sk->get_bone_global_pose(idx));
- bound=true;
+ bound = true;
}
}
}
@@ -93,33 +90,33 @@ void BoneAttachment::_check_unbind() {
if (get_parent() && get_parent()->cast_to<Skeleton>()) {
Skeleton *sk = get_parent()->cast_to<Skeleton>();
int idx = sk->find_bone(bone_name);
- if (idx!=-1) {
- sk->unbind_child_node_from_bone(idx,this);
+ if (idx != -1) {
+ sk->unbind_child_node_from_bone(idx, this);
}
}
- bound=false;
+ bound = false;
}
}
-void BoneAttachment::set_bone_name(const String& p_name) {
+void BoneAttachment::set_bone_name(const String &p_name) {
if (is_inside_tree())
_check_unbind();
- bone_name=p_name;
+ bone_name = p_name;
if (is_inside_tree())
_check_bind();
}
-String BoneAttachment::get_bone_name() const{
+String BoneAttachment::get_bone_name() const {
return bone_name;
}
void BoneAttachment::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -132,13 +129,11 @@ void BoneAttachment::_notification(int p_what) {
}
}
-BoneAttachment::BoneAttachment()
-{
- bound=false;
-
+BoneAttachment::BoneAttachment() {
+ bound = false;
}
-void BoneAttachment::_bind_methods(){
- ClassDB::bind_method(D_METHOD("set_bone_name","bone_name"),&BoneAttachment::set_bone_name);
- ClassDB::bind_method(D_METHOD("get_bone_name"),&BoneAttachment::get_bone_name);
+void BoneAttachment::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_bone_name", "bone_name"), &BoneAttachment::set_bone_name);
+ ClassDB::bind_method(D_METHOD("get_bone_name"), &BoneAttachment::get_bone_name);
}
diff --git a/scene/3d/bone_attachment.h b/scene/3d/bone_attachment.h
index 9bcbb82865..194d6b4f94 100644
--- a/scene/3d/bone_attachment.h
+++ b/scene/3d/bone_attachment.h
@@ -33,25 +33,24 @@
class BoneAttachment : public Spatial {
- GDCLASS(BoneAttachment,Spatial);
+ GDCLASS(BoneAttachment, Spatial);
bool bound;
String bone_name;
void _check_bind();
void _check_unbind();
-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_list ) const;
+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_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_bone_name(const String& p_name);
+ void set_bone_name(const String &p_name);
String get_bone_name() const;
BoneAttachment();
diff --git a/scene/3d/camera.cpp b/scene/3d/camera.cpp
index 2e04f2d8bc..540edd8a2a 100644
--- a/scene/3d/camera.cpp
+++ b/scene/3d/camera.cpp
@@ -32,10 +32,7 @@
#include "scene/resources/material.h"
#include "scene/resources/surface_tool.h"
-
void Camera::_update_audio_listener_state() {
-
-
}
void Camera::_request_camera_update() {
@@ -45,60 +42,56 @@ void Camera::_request_camera_update() {
void Camera::_update_camera_mode() {
-
- force_change=true;
- switch(mode) {
+ force_change = true;
+ switch (mode) {
case PROJECTION_PERSPECTIVE: {
-
- set_perspective(fov,near,far);
+ set_perspective(fov, near, far);
} break;
case PROJECTION_ORTHOGONAL: {
- set_orthogonal(size,near,far);
+ set_orthogonal(size, near, far);
} break;
-
}
-
}
-bool Camera::_set(const StringName& p_name, const Variant& p_value) {
+bool Camera::_set(const StringName &p_name, const Variant &p_value) {
- bool changed_all=false;
- if (p_name=="projection") {
+ bool changed_all = false;
+ if (p_name == "projection") {
int proj = p_value;
- if (proj==PROJECTION_PERSPECTIVE)
- mode=PROJECTION_PERSPECTIVE;
- if (proj==PROJECTION_ORTHOGONAL)
- mode=PROJECTION_ORTHOGONAL;
-
- changed_all=true;
- } else if (p_name=="fov" || p_name=="fovy" || p_name=="fovx")
- fov=p_value;
- else if (p_name=="size" || p_name=="sizex" || p_name=="sizey")
- size=p_value;
- else if (p_name=="near")
- near=p_value;
- else if (p_name=="far")
- far=p_value;
- else if (p_name=="keep_aspect")
+ if (proj == PROJECTION_PERSPECTIVE)
+ mode = PROJECTION_PERSPECTIVE;
+ if (proj == PROJECTION_ORTHOGONAL)
+ mode = PROJECTION_ORTHOGONAL;
+
+ changed_all = true;
+ } else if (p_name == "fov" || p_name == "fovy" || p_name == "fovx")
+ fov = p_value;
+ else if (p_name == "size" || p_name == "sizex" || p_name == "sizey")
+ size = p_value;
+ else if (p_name == "near")
+ near = p_value;
+ else if (p_name == "far")
+ far = p_value;
+ else if (p_name == "keep_aspect")
set_keep_aspect_mode(KeepAspect(int(p_value)));
- else if (p_name=="vaspect")
- set_keep_aspect_mode(p_value?KEEP_WIDTH:KEEP_HEIGHT);
- else if (p_name=="h_offset")
- h_offset=p_value;
- else if (p_name=="v_offset")
- v_offset=p_value;
- else if (p_name=="current") {
+ else if (p_name == "vaspect")
+ set_keep_aspect_mode(p_value ? KEEP_WIDTH : KEEP_HEIGHT);
+ else if (p_name == "h_offset")
+ h_offset = p_value;
+ else if (p_name == "v_offset")
+ v_offset = p_value;
+ else if (p_name == "current") {
if (p_value.operator bool()) {
make_current();
} else {
clear_current();
}
- } else if (p_name=="cull_mask") {
+ } else if (p_name == "cull_mask") {
set_cull_mask(p_value);
- } else if (p_name=="environment") {
+ } else if (p_name == "environment") {
set_environment(p_value);
} else
return false;
@@ -107,88 +100,84 @@ bool Camera::_set(const StringName& p_name, const Variant& p_value) {
if (changed_all)
_change_notify();
return true;
-
}
-bool Camera::_get(const StringName& p_name,Variant &r_ret) const {
-
- if (p_name=="projection") {
- r_ret= mode;
- } else if (p_name=="fov" || p_name=="fovy" || p_name=="fovx")
- r_ret= fov;
- else if (p_name=="size" || p_name=="sizex" || p_name=="sizey")
- r_ret= size;
- else if (p_name=="near")
- r_ret= near;
- else if (p_name=="far")
- r_ret= far;
- else if (p_name=="keep_aspect")
- r_ret= int(keep_aspect);
- else if (p_name=="current") {
+bool Camera::_get(const StringName &p_name, Variant &r_ret) const {
+
+ if (p_name == "projection") {
+ r_ret = mode;
+ } else if (p_name == "fov" || p_name == "fovy" || p_name == "fovx")
+ r_ret = fov;
+ else if (p_name == "size" || p_name == "sizex" || p_name == "sizey")
+ r_ret = size;
+ else if (p_name == "near")
+ r_ret = near;
+ else if (p_name == "far")
+ r_ret = far;
+ else if (p_name == "keep_aspect")
+ r_ret = int(keep_aspect);
+ else if (p_name == "current") {
if (is_inside_tree() && get_tree()->is_node_being_edited(this)) {
- r_ret=current;
+ r_ret = current;
} else {
- r_ret=is_current();
+ r_ret = is_current();
}
- } else if (p_name=="cull_mask") {
- r_ret=get_cull_mask();
- } else if (p_name=="h_offset") {
- r_ret=get_h_offset();
- } else if (p_name=="v_offset") {
- r_ret=get_v_offset();
- } else if (p_name=="environment") {
- r_ret=get_environment();
+ } else if (p_name == "cull_mask") {
+ r_ret = get_cull_mask();
+ } else if (p_name == "h_offset") {
+ r_ret = get_h_offset();
+ } else if (p_name == "v_offset") {
+ r_ret = get_v_offset();
+ } else if (p_name == "environment") {
+ r_ret = get_environment();
} else
return false;
return true;
}
-void Camera::_get_property_list( List<PropertyInfo> *p_list) const {
+void Camera::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo( Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal") );
+ p_list->push_back(PropertyInfo(Variant::INT, "projection", PROPERTY_HINT_ENUM, "Perspective,Orthogonal"));
- switch(mode) {
+ switch (mode) {
case PROJECTION_PERSPECTIVE: {
- p_list->push_back( PropertyInfo( Variant::REAL, "fov" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_NOEDITOR) );
- if (keep_aspect==KEEP_WIDTH)
- p_list->push_back( PropertyInfo( Variant::REAL, "fovx" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_EDITOR) );
+ p_list->push_back(PropertyInfo(Variant::REAL, "fov", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_NOEDITOR));
+ if (keep_aspect == KEEP_WIDTH)
+ p_list->push_back(PropertyInfo(Variant::REAL, "fovx", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_EDITOR));
else
- p_list->push_back( PropertyInfo( Variant::REAL, "fovy" , PROPERTY_HINT_RANGE, "1,179,0.1",PROPERTY_USAGE_EDITOR) );
-
+ p_list->push_back(PropertyInfo(Variant::REAL, "fovy", PROPERTY_HINT_RANGE, "1,179,0.1", PROPERTY_USAGE_EDITOR));
} break;
case PROJECTION_ORTHOGONAL: {
- p_list->push_back( PropertyInfo( Variant::REAL, "size" , PROPERTY_HINT_RANGE, "1,16384,0.01",PROPERTY_USAGE_NOEDITOR ) );
- if (keep_aspect==KEEP_WIDTH)
- p_list->push_back( PropertyInfo( Variant::REAL, "sizex" , PROPERTY_HINT_RANGE, "0.1,16384,0.01",PROPERTY_USAGE_EDITOR) );
+ p_list->push_back(PropertyInfo(Variant::REAL, "size", PROPERTY_HINT_RANGE, "1,16384,0.01", PROPERTY_USAGE_NOEDITOR));
+ if (keep_aspect == KEEP_WIDTH)
+ p_list->push_back(PropertyInfo(Variant::REAL, "sizex", PROPERTY_HINT_RANGE, "0.1,16384,0.01", PROPERTY_USAGE_EDITOR));
else
- p_list->push_back( PropertyInfo( Variant::REAL, "sizey" , PROPERTY_HINT_RANGE, "0.1,16384,0.01",PROPERTY_USAGE_EDITOR) );
+ p_list->push_back(PropertyInfo(Variant::REAL, "sizey", PROPERTY_HINT_RANGE, "0.1,16384,0.01", PROPERTY_USAGE_EDITOR));
} break;
-
}
- p_list->push_back( PropertyInfo( Variant::REAL, "near" , PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01") );
- p_list->push_back( PropertyInfo( Variant::REAL, "far" , PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01") );
- p_list->push_back( PropertyInfo( Variant::INT, "keep_aspect",PROPERTY_HINT_ENUM,"Keep Width,Keep Height") );
- p_list->push_back( PropertyInfo( Variant::BOOL, "current" ) );
- p_list->push_back( PropertyInfo( Variant::INT, "cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER ) );
- p_list->push_back( PropertyInfo( Variant::OBJECT, "environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment" ) );
- p_list->push_back( PropertyInfo( Variant::REAL, "h_offset" ) );
- p_list->push_back( PropertyInfo( Variant::REAL, "v_offset" ) );
-
+ p_list->push_back(PropertyInfo(Variant::REAL, "near", PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "far", PROPERTY_HINT_EXP_RANGE, "0.01,4096.0,0.01"));
+ p_list->push_back(PropertyInfo(Variant::INT, "keep_aspect", PROPERTY_HINT_ENUM, "Keep Width,Keep Height"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "current"));
+ p_list->push_back(PropertyInfo(Variant::INT, "cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "h_offset"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "v_offset"));
}
void Camera::_update_camera() {
Transform tr = get_camera_transform();
- tr.origin+=tr.basis.get_axis(1)*v_offset;
- tr.origin+=tr.basis.get_axis(0)*h_offset;
- VisualServer::get_singleton()->camera_set_transform( camera, tr );
+ tr.origin += tr.basis.get_axis(1) * v_offset;
+ tr.origin += tr.basis.get_axis(0) * h_offset;
+ VisualServer::get_singleton()->camera_set_transform(camera, tr);
// here goes listener stuff
/*
@@ -198,28 +187,23 @@ void Camera::_update_camera() {
if (is_inside_tree() && is_current()) {
get_viewport()->_camera_transform_changed_notify();
-
}
if (is_current() && get_world().is_valid()) {
get_world()->_update_camera(this);
}
-
-
}
void Camera::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
-
bool first_camera = get_viewport()->_camera_add(this);
if (!get_tree()->is_node_being_edited(this) && (current || first_camera))
make_current();
-
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -230,16 +214,15 @@ void Camera::_notification(int p_what) {
if (!get_tree()->is_node_being_edited(this)) {
if (is_current()) {
clear_current();
- current=true; //keep it true
+ current = true; //keep it true
} else {
- current=false;
+ current = false;
}
}
get_viewport()->_camera_remove(this);
-
} break;
case NOTIFICATION_BECAME_CURRENT: {
if (get_world().is_valid()) {
@@ -251,13 +234,9 @@ void Camera::_notification(int p_what) {
get_world()->_remove_camera(this);
}
} break;
-
-
}
-
}
-
Transform Camera::get_camera_transform() const {
return get_global_transform().orthonormalized();
@@ -265,31 +244,31 @@ Transform Camera::get_camera_transform() const {
void Camera::set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far) {
- if (!force_change && fov==p_fovy_degrees && p_z_near==near && p_z_far==far && mode==PROJECTION_PERSPECTIVE)
+ if (!force_change && fov == p_fovy_degrees && p_z_near == near && p_z_far == far && mode == PROJECTION_PERSPECTIVE)
return;
- fov=p_fovy_degrees;
- near=p_z_near;
- far=p_z_far;
- mode=PROJECTION_PERSPECTIVE;
+ fov = p_fovy_degrees;
+ near = p_z_near;
+ far = p_z_far;
+ mode = PROJECTION_PERSPECTIVE;
- VisualServer::get_singleton()->camera_set_perspective(camera,fov,near,far);
+ VisualServer::get_singleton()->camera_set_perspective(camera, fov, near, far);
update_gizmo();
- force_change=false;
+ force_change = false;
}
void Camera::set_orthogonal(float p_size, float p_z_near, float p_z_far) {
- if (!force_change && size==p_size && p_z_near==near && p_z_far==far && mode==PROJECTION_ORTHOGONAL)
+ if (!force_change && size == p_size && p_z_near == near && p_z_far == far && mode == PROJECTION_ORTHOGONAL)
return;
size = p_size;
- near=p_z_near;
- far=p_z_far;
- mode=PROJECTION_ORTHOGONAL;
- force_change=false;
+ near = p_z_near;
+ far = p_z_far;
+ mode = PROJECTION_ORTHOGONAL;
+ force_change = false;
- VisualServer::get_singleton()->camera_set_orthogonal(camera,size,near,far);
+ VisualServer::get_singleton()->camera_set_orthogonal(camera, size, near, far);
update_gizmo();
}
@@ -300,7 +279,7 @@ RID Camera::get_camera() const {
void Camera::make_current() {
- current=true;
+ current = true;
if (!is_inside_tree())
return;
@@ -310,55 +289,47 @@ void Camera::make_current() {
//get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,camera_group,"_camera_make_current",this);
}
-
-
-
void Camera::clear_current() {
- current=false;
+ current = false;
if (!is_inside_tree())
return;
- if (get_viewport()->get_camera()==this) {
+ if (get_viewport()->get_camera() == this) {
get_viewport()->_camera_set(NULL);
get_viewport()->_camera_make_next_current(this);
}
-
}
bool Camera::is_current() const {
if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
- return get_viewport()->get_camera()==this;
+ return get_viewport()->get_camera() == this;
} else
return current;
return false;
}
-
bool Camera::_can_gizmo_scale() const {
return false;
}
-
-
-Vector3 Camera::project_ray_normal(const Point2& p_pos) const {
+Vector3 Camera::project_ray_normal(const Point2 &p_pos) const {
Vector3 ray = project_local_ray_normal(p_pos);
return get_camera_transform().basis.xform(ray).normalized();
};
-Vector3 Camera::project_local_ray_normal(const Point2& p_pos) const {
+Vector3 Camera::project_local_ray_normal(const Point2 &p_pos) const {
if (!is_inside_tree()) {
ERR_EXPLAIN("Camera is not inside scene.");
- ERR_FAIL_COND_V(!is_inside_tree(),Vector3());
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector3());
}
-
#if 0
Size2 viewport_size = get_viewport()->get_visible_rect().size;
Vector2 cpos = p_pos;
@@ -370,26 +341,25 @@ Vector3 Camera::project_local_ray_normal(const Point2& p_pos) const {
Vector3 ray;
- if (mode==PROJECTION_ORTHOGONAL) {
+ if (mode == PROJECTION_ORTHOGONAL) {
- ray=Vector3(0,0,-1);
+ ray = Vector3(0, 0, -1);
} else {
CameraMatrix cm;
- cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
- float screen_w,screen_h;
- cm.get_viewport_size(screen_w,screen_h);
- ray=Vector3( ((cpos.x/viewport_size.width)*2.0-1.0)*screen_w, ((1.0-(cpos.y/viewport_size.height))*2.0-1.0)*screen_h,-near).normalized();
+ cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
+ float screen_w, screen_h;
+ cm.get_viewport_size(screen_w, screen_h);
+ ray = Vector3(((cpos.x / viewport_size.width) * 2.0 - 1.0) * screen_w, ((1.0 - (cpos.y / viewport_size.height)) * 2.0 - 1.0) * screen_h, -near).normalized();
}
return ray;
};
-
-Vector3 Camera::project_ray_origin(const Point2& p_pos) const {
+Vector3 Camera::project_ray_origin(const Point2 &p_pos) const {
if (!is_inside_tree()) {
ERR_EXPLAIN("Camera is not inside scene.");
- ERR_FAIL_COND_V(!is_inside_tree(),Vector3());
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector3());
}
#if 0
@@ -401,7 +371,7 @@ Vector3 Camera::project_ray_origin(const Point2& p_pos) const {
Vector2 cpos = get_viewport()->get_camera_coords(p_pos);
#endif
- ERR_FAIL_COND_V( viewport_size.y == 0, Vector3() );
+ ERR_FAIL_COND_V(viewport_size.y == 0, Vector3());
//float aspect = viewport_size.x / viewport_size.y;
if (mode == PROJECTION_PERSPECTIVE) {
@@ -410,91 +380,84 @@ Vector3 Camera::project_ray_origin(const Point2& p_pos) const {
} else {
Vector2 pos = cpos / viewport_size;
- float vsize,hsize;
- if (keep_aspect==KEEP_WIDTH) {
- vsize = size/viewport_size.aspect();
+ float vsize, hsize;
+ if (keep_aspect == KEEP_WIDTH) {
+ vsize = size / viewport_size.aspect();
hsize = size;
} else {
- hsize = size*viewport_size.aspect();
+ hsize = size * viewport_size.aspect();
vsize = size;
-
}
-
-
Vector3 ray;
- ray.x = pos.x * (hsize) - hsize/2;
- ray.y = (1.0 - pos.y) * (vsize) - vsize/2;
+ ray.x = pos.x * (hsize)-hsize / 2;
+ ray.y = (1.0 - pos.y) * (vsize)-vsize / 2;
ray.z = -near;
ray = get_camera_transform().xform(ray);
return ray;
};
};
-bool Camera::is_position_behind(const Vector3& p_pos) const {
+bool Camera::is_position_behind(const Vector3 &p_pos) const {
Transform t = get_global_transform();
Vector3 eyedir = -get_global_transform().basis.get_axis(2).normalized();
- return eyedir.dot(p_pos) < (eyedir.dot(t.origin)+near);
+ return eyedir.dot(p_pos) < (eyedir.dot(t.origin) + near);
}
-Point2 Camera::unproject_position(const Vector3& p_pos) const {
+Point2 Camera::unproject_position(const Vector3 &p_pos) const {
if (!is_inside_tree()) {
ERR_EXPLAIN("Camera is not inside scene.");
- ERR_FAIL_COND_V(!is_inside_tree(),Vector2());
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector2());
}
Size2 viewport_size = get_viewport()->get_visible_rect().size;
CameraMatrix cm;
-
- if (mode==PROJECTION_ORTHOGONAL)
- cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
+ if (mode == PROJECTION_ORTHOGONAL)
+ cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
else
- cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
-
- Plane p(get_camera_transform().xform_inv(p_pos),1.0);
+ cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
- p=cm.xform4(p);
- p.normal/=p.d;
+ Plane p(get_camera_transform().xform_inv(p_pos), 1.0);
+ p = cm.xform4(p);
+ p.normal /= p.d;
Point2 res;
- res.x = (p.normal.x * 0.5 + 0.5) * viewport_size.x;
- res.y = (-p.normal.y * 0.5 + 0.5) * viewport_size.y;
+ res.x = (p.normal.x * 0.5 + 0.5) * viewport_size.x;
+ res.y = (-p.normal.y * 0.5 + 0.5) * viewport_size.y;
return res;
-
}
-Vector3 Camera::project_position(const Point2& p_point) const {
+Vector3 Camera::project_position(const Point2 &p_point) const {
if (!is_inside_tree()) {
ERR_EXPLAIN("Camera is not inside scene.");
- ERR_FAIL_COND_V(!is_inside_tree(),Vector3());
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector3());
}
Size2 viewport_size = get_viewport()->get_visible_rect().size;
CameraMatrix cm;
- if (mode==PROJECTION_ORTHOGONAL)
- cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
+ if (mode == PROJECTION_ORTHOGONAL)
+ cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
else
- cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
+ cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
Size2 vp_size;
- cm.get_viewport_size(vp_size.x,vp_size.y);
+ cm.get_viewport_size(vp_size.x, vp_size.y);
Vector2 point;
- point.x = (p_point.x/viewport_size.x) * 2.0 - 1.0;
- point.y = (1.0-(p_point.y/viewport_size.y)) * 2.0 - 1.0;
- point*=vp_size;
-
- Vector3 p(point.x,point.y,-near);
+ point.x = (p_point.x / viewport_size.x) * 2.0 - 1.0;
+ point.y = (1.0 - (p_point.y / viewport_size.y)) * 2.0 - 1.0;
+ point *= vp_size;
+ Vector3 p(point.x, point.y, -near);
return get_camera_transform().xform(p);
}
@@ -516,13 +479,13 @@ void Camera::_camera_make_current(Node *p_camera) {
}
*/
-void Camera::set_environment(const Ref<Environment>& p_environment) {
+void Camera::set_environment(const Ref<Environment> &p_environment) {
- environment=p_environment;
+ environment = p_environment;
if (environment.is_valid())
- VS::get_singleton()->camera_set_environment(camera,environment->get_rid());
+ VS::get_singleton()->camera_set_environment(camera, environment->get_rid());
else
- VS::get_singleton()->camera_set_environment(camera,RID());
+ VS::get_singleton()->camera_set_environment(camera, RID());
}
Ref<Environment> Camera::get_environment() const {
@@ -530,59 +493,55 @@ Ref<Environment> Camera::get_environment() const {
return environment;
}
-
void Camera::set_keep_aspect_mode(KeepAspect p_aspect) {
- keep_aspect=p_aspect;
- VisualServer::get_singleton()->camera_set_use_vertical_aspect(camera,p_aspect==KEEP_WIDTH);
+ keep_aspect = p_aspect;
+ VisualServer::get_singleton()->camera_set_use_vertical_aspect(camera, p_aspect == KEEP_WIDTH);
_change_notify();
}
-Camera::KeepAspect Camera::get_keep_aspect_mode() const{
+Camera::KeepAspect Camera::get_keep_aspect_mode() const {
return keep_aspect;
}
-
-
void Camera::_bind_methods() {
- ClassDB::bind_method(D_METHOD("project_ray_normal","screen_point"), &Camera::project_ray_normal);
- ClassDB::bind_method(D_METHOD("project_local_ray_normal","screen_point"), &Camera::project_local_ray_normal);
- ClassDB::bind_method(D_METHOD("project_ray_origin","screen_point"), &Camera::project_ray_origin);
- ClassDB::bind_method(D_METHOD("unproject_position","world_point"), &Camera::unproject_position);
- ClassDB::bind_method(D_METHOD("is_position_behind","world_point"), &Camera::is_position_behind);
- ClassDB::bind_method(D_METHOD("project_position","screen_point"), &Camera::project_position);
- ClassDB::bind_method(D_METHOD("set_perspective","fov","z_near","z_far"),&Camera::set_perspective );
- ClassDB::bind_method(D_METHOD("set_orthogonal","size","z_near","z_far"),&Camera::set_orthogonal );
- ClassDB::bind_method(D_METHOD("make_current"),&Camera::make_current );
- ClassDB::bind_method(D_METHOD("clear_current"),&Camera::clear_current );
- ClassDB::bind_method(D_METHOD("is_current"),&Camera::is_current );
- ClassDB::bind_method(D_METHOD("get_camera_transform"),&Camera::get_camera_transform );
- ClassDB::bind_method(D_METHOD("get_fov"),&Camera::get_fov );
- ClassDB::bind_method(D_METHOD("get_size"),&Camera::get_size );
- ClassDB::bind_method(D_METHOD("get_zfar"),&Camera::get_zfar );
- ClassDB::bind_method(D_METHOD("get_znear"),&Camera::get_znear );
- ClassDB::bind_method(D_METHOD("get_projection"),&Camera::get_projection );
- ClassDB::bind_method(D_METHOD("set_h_offset","ofs"),&Camera::set_h_offset );
- ClassDB::bind_method(D_METHOD("get_h_offset"),&Camera::get_h_offset );
- ClassDB::bind_method(D_METHOD("set_v_offset","ofs"),&Camera::set_v_offset );
- ClassDB::bind_method(D_METHOD("get_v_offset"),&Camera::get_v_offset );
- ClassDB::bind_method(D_METHOD("set_cull_mask","mask"),&Camera::set_cull_mask );
- ClassDB::bind_method(D_METHOD("get_cull_mask"),&Camera::get_cull_mask );
- ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&Camera::set_environment );
- ClassDB::bind_method(D_METHOD("get_environment:Environment"),&Camera::get_environment );
- ClassDB::bind_method(D_METHOD("set_keep_aspect_mode","mode"),&Camera::set_keep_aspect_mode );
- ClassDB::bind_method(D_METHOD("get_keep_aspect_mode"),&Camera::get_keep_aspect_mode );
+ ClassDB::bind_method(D_METHOD("project_ray_normal", "screen_point"), &Camera::project_ray_normal);
+ ClassDB::bind_method(D_METHOD("project_local_ray_normal", "screen_point"), &Camera::project_local_ray_normal);
+ ClassDB::bind_method(D_METHOD("project_ray_origin", "screen_point"), &Camera::project_ray_origin);
+ ClassDB::bind_method(D_METHOD("unproject_position", "world_point"), &Camera::unproject_position);
+ ClassDB::bind_method(D_METHOD("is_position_behind", "world_point"), &Camera::is_position_behind);
+ ClassDB::bind_method(D_METHOD("project_position", "screen_point"), &Camera::project_position);
+ ClassDB::bind_method(D_METHOD("set_perspective", "fov", "z_near", "z_far"), &Camera::set_perspective);
+ ClassDB::bind_method(D_METHOD("set_orthogonal", "size", "z_near", "z_far"), &Camera::set_orthogonal);
+ ClassDB::bind_method(D_METHOD("make_current"), &Camera::make_current);
+ ClassDB::bind_method(D_METHOD("clear_current"), &Camera::clear_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &Camera::is_current);
+ ClassDB::bind_method(D_METHOD("get_camera_transform"), &Camera::get_camera_transform);
+ ClassDB::bind_method(D_METHOD("get_fov"), &Camera::get_fov);
+ ClassDB::bind_method(D_METHOD("get_size"), &Camera::get_size);
+ ClassDB::bind_method(D_METHOD("get_zfar"), &Camera::get_zfar);
+ ClassDB::bind_method(D_METHOD("get_znear"), &Camera::get_znear);
+ ClassDB::bind_method(D_METHOD("get_projection"), &Camera::get_projection);
+ ClassDB::bind_method(D_METHOD("set_h_offset", "ofs"), &Camera::set_h_offset);
+ ClassDB::bind_method(D_METHOD("get_h_offset"), &Camera::get_h_offset);
+ ClassDB::bind_method(D_METHOD("set_v_offset", "ofs"), &Camera::set_v_offset);
+ ClassDB::bind_method(D_METHOD("get_v_offset"), &Camera::get_v_offset);
+ ClassDB::bind_method(D_METHOD("set_cull_mask", "mask"), &Camera::set_cull_mask);
+ ClassDB::bind_method(D_METHOD("get_cull_mask"), &Camera::get_cull_mask);
+ ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &Camera::set_environment);
+ ClassDB::bind_method(D_METHOD("get_environment:Environment"), &Camera::get_environment);
+ ClassDB::bind_method(D_METHOD("set_keep_aspect_mode", "mode"), &Camera::set_keep_aspect_mode);
+ ClassDB::bind_method(D_METHOD("get_keep_aspect_mode"), &Camera::get_keep_aspect_mode);
//ClassDB::bind_method(D_METHOD("_camera_make_current"),&Camera::_camera_make_current );
- BIND_CONSTANT( PROJECTION_PERSPECTIVE );
- BIND_CONSTANT( PROJECTION_ORTHOGONAL );
-
- BIND_CONSTANT( KEEP_WIDTH );
- BIND_CONSTANT( KEEP_HEIGHT );
+ BIND_CONSTANT(PROJECTION_PERSPECTIVE);
+ BIND_CONSTANT(PROJECTION_ORTHOGONAL);
+ BIND_CONSTANT(KEEP_WIDTH);
+ BIND_CONSTANT(KEEP_HEIGHT);
}
float Camera::get_fov() const {
@@ -605,7 +564,6 @@ float Camera::get_zfar() const {
return far;
}
-
Camera::Projection Camera::get_projection() const {
return mode;
@@ -613,37 +571,32 @@ Camera::Projection Camera::get_projection() const {
void Camera::set_cull_mask(uint32_t p_layers) {
- layers=p_layers;
- VisualServer::get_singleton()->camera_set_cull_mask(camera,layers);
+ layers = p_layers;
+ VisualServer::get_singleton()->camera_set_cull_mask(camera, layers);
}
-uint32_t Camera::get_cull_mask() const{
+uint32_t Camera::get_cull_mask() const {
return layers;
}
-
Vector<Plane> Camera::get_frustum() const {
- ERR_FAIL_COND_V(!is_inside_world(),Vector<Plane>());
+ ERR_FAIL_COND_V(!is_inside_world(), Vector<Plane>());
Size2 viewport_size = get_viewport()->get_visible_rect().size;
CameraMatrix cm;
- if (mode==PROJECTION_PERSPECTIVE)
- cm.set_perspective(fov,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
+ if (mode == PROJECTION_PERSPECTIVE)
+ cm.set_perspective(fov, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
else
- cm.set_orthogonal(size,viewport_size.aspect(),near,far,keep_aspect==KEEP_WIDTH);
+ cm.set_orthogonal(size, viewport_size.aspect(), near, far, keep_aspect == KEEP_WIDTH);
return cm.get_projection_planes(get_camera_transform());
-
}
-
-
-
void Camera::set_v_offset(float p_offset) {
- v_offset=p_offset;
+ v_offset = p_offset;
_update_camera();
}
@@ -653,7 +606,7 @@ float Camera::get_v_offset() const {
}
void Camera::set_h_offset(float p_offset) {
- h_offset=p_offset;
+ h_offset = p_offset;
_update_camera();
}
@@ -662,32 +615,27 @@ float Camera::get_h_offset() const {
return h_offset;
}
-
Camera::Camera() {
camera = VisualServer::get_singleton()->camera_create();
- size=1;
- fov=0;
- near=0;
- far=0;
- current=false;
- force_change=false;
- mode=PROJECTION_PERSPECTIVE;
- set_perspective(60.0,0.1,100.0);
- keep_aspect=KEEP_HEIGHT;
- layers=0xfffff;
- v_offset=0;
- h_offset=0;
- VisualServer::get_singleton()->camera_set_cull_mask(camera,layers);
+ size = 1;
+ fov = 0;
+ near = 0;
+ far = 0;
+ current = false;
+ force_change = false;
+ mode = PROJECTION_PERSPECTIVE;
+ set_perspective(60.0, 0.1, 100.0);
+ keep_aspect = KEEP_HEIGHT;
+ layers = 0xfffff;
+ v_offset = 0;
+ h_offset = 0;
+ VisualServer::get_singleton()->camera_set_cull_mask(camera, layers);
//active=false;
set_notify_transform(true);
}
-
Camera::~Camera() {
VisualServer::get_singleton()->free(camera);
-
}
-
-
diff --git a/scene/3d/camera.h b/scene/3d/camera.h
index 5301c06ee5..3c31b6beeb 100644
--- a/scene/3d/camera.h
+++ b/scene/3d/camera.h
@@ -29,7 +29,6 @@
#ifndef CAMERA_H
#define CAMERA_H
-
#include "scene/3d/spatial.h"
#include "scene/main/viewport.h"
#include "scene/resources/environment.h"
@@ -38,7 +37,8 @@
*/
class Camera : public Spatial {
- GDCLASS( Camera, Spatial );
+ GDCLASS(Camera, Spatial);
+
public:
enum Projection {
@@ -52,7 +52,6 @@ public:
};
private:
-
bool force_change;
bool current;
@@ -60,7 +59,7 @@ private:
float fov;
float size;
- float near,far;
+ float near, far;
float v_offset;
float h_offset;
KeepAspect keep_aspect;
@@ -76,30 +75,27 @@ private:
virtual bool _can_gizmo_scale() const;
-
-
//void _camera_make_current(Node *p_camera);
-friend class Viewport;
+ friend class Viewport;
void _update_audio_listener_state();
-protected:
+protected:
void _update_camera();
virtual void _request_camera_update();
void _update_camera_mode();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
enum {
- NOTIFICATION_BECAME_CURRENT=50,
- NOTIFICATION_LOST_CURRENT=51
+ NOTIFICATION_BECAME_CURRENT = 50,
+ NOTIFICATION_LOST_CURRENT = 51
};
void set_perspective(float p_fovy_degrees, float p_z_near, float p_z_far);
@@ -119,39 +115,35 @@ public:
virtual Transform get_camera_transform() const;
- Vector3 project_ray_normal(const Point2& p_point) const;
- Vector3 project_ray_origin(const Point2& p_point) const;
- Vector3 project_local_ray_normal(const Point2& p_point) const;
- Point2 unproject_position(const Vector3& p_pos) const;
- bool is_position_behind(const Vector3& p_pos) const;
- Vector3 project_position(const Point2& p_point) const;
+ Vector3 project_ray_normal(const Point2 &p_point) const;
+ Vector3 project_ray_origin(const Point2 &p_point) const;
+ Vector3 project_local_ray_normal(const Point2 &p_point) const;
+ Point2 unproject_position(const Vector3 &p_pos) const;
+ bool is_position_behind(const Vector3 &p_pos) const;
+ Vector3 project_position(const Point2 &p_point) const;
void set_cull_mask(uint32_t p_layers);
uint32_t get_cull_mask() const;
Vector<Plane> get_frustum() const;
- void set_environment(const Ref<Environment>& p_environment);
+ void set_environment(const Ref<Environment> &p_environment);
Ref<Environment> get_environment() const;
void set_keep_aspect_mode(KeepAspect p_aspect);
KeepAspect get_keep_aspect_mode() const;
-
void set_v_offset(float p_offset);
float get_v_offset() const;
void set_h_offset(float p_offset);
float get_h_offset() const;
-
Camera();
~Camera();
-
};
-
-VARIANT_ENUM_CAST( Camera::Projection );
-VARIANT_ENUM_CAST( Camera::KeepAspect );
+VARIANT_ENUM_CAST(Camera::Projection);
+VARIANT_ENUM_CAST(Camera::KeepAspect);
#endif
diff --git a/scene/3d/character_camera.cpp b/scene/3d/character_camera.cpp
index 424a7fc79c..edd97eaa6d 100644
--- a/scene/3d/character_camera.cpp
+++ b/scene/3d/character_camera.cpp
@@ -237,7 +237,6 @@ void CharacterCamera::_compute_camera() {
new_pos = character_pos + rel_n * l;
-
#endif
follow_pos=new_pos;
diff --git a/scene/3d/character_camera.h b/scene/3d/character_camera.h
index 5fde8c342e..464fa5c235 100644
--- a/scene/3d/character_camera.h
+++ b/scene/3d/character_camera.h
@@ -29,7 +29,6 @@
#ifndef CHARACTER_CAMERA_H
#define CHARACTER_CAMERA_H
-
#include "scene/3d/camera.h"
#if 0
class CharacterCamera : public Camera {
diff --git a/scene/3d/collision_object.cpp b/scene/3d/collision_object.cpp
index 32e60f0d57..c3e19c4b81 100644
--- a/scene/3d/collision_object.cpp
+++ b/scene/3d/collision_object.cpp
@@ -27,15 +27,15 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "collision_object.h"
-#include "servers/physics_server.h"
#include "scene/scene_string_names.h"
+#include "servers/physics_server.h"
void CollisionObject::_update_shapes_from_children() {
shapes.clear();
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Node* n = get_child(i);
- n->call("_add_to_collision_object",this);
+ Node *n = get_child(i);
+ n->call("_add_to_collision_object", this);
}
_update_shapes();
@@ -43,31 +43,31 @@ void CollisionObject::_update_shapes_from_children() {
void CollisionObject::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
if (area)
- PhysicsServer::get_singleton()->area_set_transform(rid,get_global_transform());
+ PhysicsServer::get_singleton()->area_set_transform(rid, get_global_transform());
else
- PhysicsServer::get_singleton()->body_set_state(rid,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform());
+ PhysicsServer::get_singleton()->body_set_state(rid, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
RID space = get_world()->get_space();
if (area) {
- PhysicsServer::get_singleton()->area_set_space(rid,space);
+ PhysicsServer::get_singleton()->area_set_space(rid, space);
} else
- PhysicsServer::get_singleton()->body_set_space(rid,space);
+ PhysicsServer::get_singleton()->body_set_space(rid, space);
_update_pickable();
- //get space
+ //get space
};
case NOTIFICATION_TRANSFORM_CHANGED: {
if (area)
- PhysicsServer::get_singleton()->area_set_transform(rid,get_global_transform());
+ PhysicsServer::get_singleton()->area_set_transform(rid, get_global_transform());
else
- PhysicsServer::get_singleton()->body_set_state(rid,PhysicsServer::BODY_STATE_TRANSFORM,get_global_transform());
+ PhysicsServer::get_singleton()->body_set_state(rid, PhysicsServer::BODY_STATE_TRANSFORM, get_global_transform());
} break;
case NOTIFICATION_VISIBILITY_CHANGED: {
@@ -78,9 +78,9 @@ void CollisionObject::_notification(int p_what) {
case NOTIFICATION_EXIT_WORLD: {
if (area) {
- PhysicsServer::get_singleton()->area_set_space(rid,RID());
+ PhysicsServer::get_singleton()->area_set_space(rid, RID());
} else
- PhysicsServer::get_singleton()->body_set_space(rid,RID());
+ PhysicsServer::get_singleton()->body_set_space(rid, RID());
} break;
}
@@ -96,25 +96,24 @@ void CollisionObject::_update_shapes() {
else
PhysicsServer::get_singleton()->body_clear_shapes(rid);
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
if (shapes[i].shape.is_null())
continue;
if (area)
- PhysicsServer::get_singleton()->area_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform);
+ PhysicsServer::get_singleton()->area_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform);
else {
- PhysicsServer::get_singleton()->body_add_shape(rid,shapes[i].shape->get_rid(),shapes[i].xform);
+ PhysicsServer::get_singleton()->body_add_shape(rid, shapes[i].shape->get_rid(), shapes[i].xform);
if (shapes[i].trigger)
- PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid,i,shapes[i].trigger);
+ PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid, i, shapes[i].trigger);
}
}
}
+bool CollisionObject::_set(const StringName &p_name, const Variant &p_value) {
+ String name = p_name;
-bool CollisionObject::_set(const StringName& p_name, const Variant& p_value) {
- String name=p_name;
-
- if (name=="shape_count") {
+ if (name == "shape_count") {
shapes.resize(p_value);
_update_shapes();
@@ -122,40 +121,37 @@ bool CollisionObject::_set(const StringName& p_name, const Variant& p_value) {
} else if (name.begins_with("shapes/")) {
- int idx=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="shape")
- set_shape(idx,RefPtr(p_value));
- else if (what=="transform")
- set_shape_transform(idx,p_value);
- else if (what=="trigger")
- set_shape_as_trigger(idx,p_value);
-
+ int idx = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "shape")
+ set_shape(idx, RefPtr(p_value));
+ else if (what == "transform")
+ set_shape_transform(idx, p_value);
+ else if (what == "trigger")
+ set_shape_as_trigger(idx, p_value);
} else
return false;
return true;
-
-
}
-bool CollisionObject::_get(const StringName& p_name,Variant &r_ret) const {
+bool CollisionObject::_get(const StringName &p_name, Variant &r_ret) const {
- String name=p_name;
+ String name = p_name;
- if (name=="shape_count") {
- r_ret= shapes.size();
+ if (name == "shape_count") {
+ r_ret = shapes.size();
} else if (name.begins_with("shapes/")) {
- int idx=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- if (what=="shape")
- r_ret= get_shape(idx);
- else if (what=="transform")
- r_ret= get_shape_transform(idx);
- else if (what=="trigger")
- r_ret= is_shape_set_as_trigger(idx);
+ int idx = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ if (what == "shape")
+ r_ret = get_shape(idx);
+ else if (what == "transform")
+ r_ret = get_shape_transform(idx);
+ else if (what == "trigger")
+ r_ret = is_shape_set_as_trigger(idx);
} else
return false;
@@ -163,26 +159,24 @@ bool CollisionObject::_get(const StringName& p_name,Variant &r_ret) const {
return true;
}
-void CollisionObject::_get_property_list( List<PropertyInfo> *p_list) const {
+void CollisionObject::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo(Variant::INT,"shape_count",PROPERTY_HINT_RANGE,"0,256,1",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
-
- for(int i=0;i<shapes.size();i++) {
- String path="shapes/"+itos(i)+"/";
- p_list->push_back( PropertyInfo(Variant::OBJECT,path+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
- p_list->push_back( PropertyInfo(Variant::TRANSFORM,path+"transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
- p_list->push_back( PropertyInfo(Variant::BOOL,path+"trigger",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR|PROPERTY_USAGE_NO_INSTANCE_STATE) );
+ p_list->push_back(PropertyInfo(Variant::INT, "shape_count", PROPERTY_HINT_RANGE, "0,256,1", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
+ for (int i = 0; i < shapes.size(); i++) {
+ String path = "shapes/" + itos(i) + "/";
+ p_list->push_back(PropertyInfo(Variant::OBJECT, path + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM, path + "transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
+ p_list->push_back(PropertyInfo(Variant::BOOL, path + "trigger", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_NO_INSTANCE_STATE));
}
}
-
-void CollisionObject::_input_event(Node *p_camera, const InputEvent& p_input_event, const Vector3& p_pos, const Vector3& p_normal, int p_shape) {
+void CollisionObject::_input_event(Node *p_camera, const InputEvent &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape) {
if (get_script_instance()) {
- get_script_instance()->call(SceneStringNames::get_singleton()->_input_event,p_camera,p_input_event,p_pos,p_normal,p_shape);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_input_event, p_camera, p_input_event, p_pos, p_normal, p_shape);
}
- emit_signal(SceneStringNames::get_singleton()->input_event,p_camera,p_input_event,p_pos,p_normal,p_shape);
+ emit_signal(SceneStringNames::get_singleton()->input_event, p_camera, p_input_event, p_pos, p_normal, p_shape);
}
void CollisionObject::_mouse_enter() {
@@ -193,14 +187,12 @@ void CollisionObject::_mouse_enter() {
emit_signal(SceneStringNames::get_singleton()->mouse_entered);
}
-
void CollisionObject::_mouse_exit() {
if (get_script_instance()) {
get_script_instance()->call(SceneStringNames::get_singleton()->_mouse_exit);
}
emit_signal(SceneStringNames::get_singleton()->mouse_exited);
-
}
void CollisionObject::_update_pickable() {
@@ -208,16 +200,15 @@ void CollisionObject::_update_pickable() {
return;
bool pickable = ray_pickable && is_inside_tree() && is_visible_in_tree();
if (area)
- PhysicsServer::get_singleton()->area_set_ray_pickable(rid,pickable);
+ PhysicsServer::get_singleton()->area_set_ray_pickable(rid, pickable);
else
- PhysicsServer::get_singleton()->body_set_ray_pickable(rid,pickable);
+ PhysicsServer::get_singleton()->body_set_ray_pickable(rid, pickable);
}
void CollisionObject::set_ray_pickable(bool p_ray_pickable) {
- ray_pickable=p_ray_pickable;
+ ray_pickable = p_ray_pickable;
_update_pickable();
-
}
bool CollisionObject::is_ray_pickable() const {
@@ -225,80 +216,74 @@ bool CollisionObject::is_ray_pickable() const {
return ray_pickable;
}
-
void CollisionObject::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_shape","shape:Shape","transform"),&CollisionObject::add_shape,DEFVAL(Transform()));
- ClassDB::bind_method(D_METHOD("get_shape_count"),&CollisionObject::get_shape_count);
- ClassDB::bind_method(D_METHOD("set_shape","shape_idx","shape:Shape"),&CollisionObject::set_shape);
- ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform);
-// ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform);
- ClassDB::bind_method(D_METHOD("set_shape_as_trigger","shape_idx","enable"),&CollisionObject::set_shape_as_trigger);
- ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger","shape_idx"),&CollisionObject::is_shape_set_as_trigger);
- ClassDB::bind_method(D_METHOD("get_shape:Shape","shape_idx"),&CollisionObject::get_shape);
- ClassDB::bind_method(D_METHOD("get_shape_transform","shape_idx"),&CollisionObject::get_shape_transform);
- ClassDB::bind_method(D_METHOD("remove_shape","shape_idx"),&CollisionObject::remove_shape);
- ClassDB::bind_method(D_METHOD("clear_shapes"),&CollisionObject::clear_shapes);
- ClassDB::bind_method(D_METHOD("set_ray_pickable","ray_pickable"),&CollisionObject::set_ray_pickable);
- ClassDB::bind_method(D_METHOD("is_ray_pickable"),&CollisionObject::is_ray_pickable);
- ClassDB::bind_method(D_METHOD("set_capture_input_on_drag","enable"),&CollisionObject::set_capture_input_on_drag);
- ClassDB::bind_method(D_METHOD("get_capture_input_on_drag"),&CollisionObject::get_capture_input_on_drag);
- ClassDB::bind_method(D_METHOD("get_rid"),&CollisionObject::get_rid);
- BIND_VMETHOD( MethodInfo("_input_event",PropertyInfo(Variant::OBJECT,"camera"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::VECTOR3,"click_pos"),PropertyInfo(Variant::VECTOR3,"click_normal"),PropertyInfo(Variant::INT,"shape_idx")));
-
- ADD_SIGNAL( MethodInfo("input_event",PropertyInfo(Variant::OBJECT,"camera"),PropertyInfo(Variant::INPUT_EVENT,"event"),PropertyInfo(Variant::VECTOR3,"click_pos"),PropertyInfo(Variant::VECTOR3,"click_normal"),PropertyInfo(Variant::INT,"shape_idx")));
- ADD_SIGNAL( MethodInfo("mouse_entered"));
- ADD_SIGNAL( MethodInfo("mouse_exited"));
-
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"input_ray_pickable"),"set_ray_pickable","is_ray_pickable");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"input_capture_on_drag"),"set_capture_input_on_drag","get_capture_input_on_drag");
+ ClassDB::bind_method(D_METHOD("add_shape", "shape:Shape", "transform"), &CollisionObject::add_shape, DEFVAL(Transform()));
+ ClassDB::bind_method(D_METHOD("get_shape_count"), &CollisionObject::get_shape_count);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape_idx", "shape:Shape"), &CollisionObject::set_shape);
+ ClassDB::bind_method(D_METHOD("set_shape_transform", "shape_idx", "transform"), &CollisionObject::set_shape_transform);
+ // ClassDB::bind_method(D_METHOD("set_shape_transform","shape_idx","transform"),&CollisionObject::set_shape_transform);
+ ClassDB::bind_method(D_METHOD("set_shape_as_trigger", "shape_idx", "enable"), &CollisionObject::set_shape_as_trigger);
+ ClassDB::bind_method(D_METHOD("is_shape_set_as_trigger", "shape_idx"), &CollisionObject::is_shape_set_as_trigger);
+ ClassDB::bind_method(D_METHOD("get_shape:Shape", "shape_idx"), &CollisionObject::get_shape);
+ ClassDB::bind_method(D_METHOD("get_shape_transform", "shape_idx"), &CollisionObject::get_shape_transform);
+ ClassDB::bind_method(D_METHOD("remove_shape", "shape_idx"), &CollisionObject::remove_shape);
+ ClassDB::bind_method(D_METHOD("clear_shapes"), &CollisionObject::clear_shapes);
+ ClassDB::bind_method(D_METHOD("set_ray_pickable", "ray_pickable"), &CollisionObject::set_ray_pickable);
+ ClassDB::bind_method(D_METHOD("is_ray_pickable"), &CollisionObject::is_ray_pickable);
+ ClassDB::bind_method(D_METHOD("set_capture_input_on_drag", "enable"), &CollisionObject::set_capture_input_on_drag);
+ ClassDB::bind_method(D_METHOD("get_capture_input_on_drag"), &CollisionObject::get_capture_input_on_drag);
+ ClassDB::bind_method(D_METHOD("get_rid"), &CollisionObject::get_rid);
+ BIND_VMETHOD(MethodInfo("_input_event", PropertyInfo(Variant::OBJECT, "camera"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::VECTOR3, "click_pos"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx")));
+
+ ADD_SIGNAL(MethodInfo("input_event", PropertyInfo(Variant::OBJECT, "camera"), PropertyInfo(Variant::INPUT_EVENT, "event"), PropertyInfo(Variant::VECTOR3, "click_pos"), PropertyInfo(Variant::VECTOR3, "click_normal"), PropertyInfo(Variant::INT, "shape_idx")));
+ ADD_SIGNAL(MethodInfo("mouse_entered"));
+ ADD_SIGNAL(MethodInfo("mouse_exited"));
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_ray_pickable"), "set_ray_pickable", "is_ray_pickable");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "input_capture_on_drag"), "set_capture_input_on_drag", "get_capture_input_on_drag");
}
-
-void CollisionObject::add_shape(const Ref<Shape>& p_shape, const Transform& p_transform) {
+void CollisionObject::add_shape(const Ref<Shape> &p_shape, const Transform &p_transform) {
ShapeData sdata;
- sdata.shape=p_shape;
- sdata.xform=p_transform;
+ sdata.shape = p_shape;
+ sdata.xform = p_transform;
shapes.push_back(sdata);
_update_shapes();
-
}
int CollisionObject::get_shape_count() const {
return shapes.size();
-
}
-void CollisionObject::set_shape(int p_shape_idx, const Ref<Shape>& p_shape) {
+void CollisionObject::set_shape(int p_shape_idx, const Ref<Shape> &p_shape) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
- shapes[p_shape_idx].shape=p_shape;
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
+ shapes[p_shape_idx].shape = p_shape;
_update_shapes();
}
-void CollisionObject::set_shape_transform(int p_shape_idx, const Transform& p_transform) {
+void CollisionObject::set_shape_transform(int p_shape_idx, const Transform &p_transform) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
- shapes[p_shape_idx].xform=p_transform;
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
+ shapes[p_shape_idx].xform = p_transform;
_update_shapes();
}
Ref<Shape> CollisionObject::get_shape(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Ref<Shape>());
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Ref<Shape>());
return shapes[p_shape_idx].shape;
-
}
Transform CollisionObject::get_shape_transform(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),Transform());
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), Transform());
return shapes[p_shape_idx].xform;
-
}
void CollisionObject::remove_shape(int p_shape_idx) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
shapes.remove(p_shape_idx);
_update_shapes();
@@ -313,41 +298,38 @@ void CollisionObject::clear_shapes() {
void CollisionObject::set_shape_as_trigger(int p_shape_idx, bool p_trigger) {
- ERR_FAIL_INDEX(p_shape_idx,shapes.size());
- shapes[p_shape_idx].trigger=p_trigger;
- if (!area && rid.is_valid()) {
-
- PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid,p_shape_idx,p_trigger);
+ ERR_FAIL_INDEX(p_shape_idx, shapes.size());
+ shapes[p_shape_idx].trigger = p_trigger;
+ if (!area && rid.is_valid()) {
- }
+ PhysicsServer::get_singleton()->body_set_shape_as_trigger(rid, p_shape_idx, p_trigger);
+ }
}
bool CollisionObject::is_shape_set_as_trigger(int p_shape_idx) const {
- ERR_FAIL_INDEX_V(p_shape_idx,shapes.size(),false);
- return shapes[p_shape_idx].trigger;
+ ERR_FAIL_INDEX_V(p_shape_idx, shapes.size(), false);
+ return shapes[p_shape_idx].trigger;
}
CollisionObject::CollisionObject(RID p_rid, bool p_area) {
- rid=p_rid;
- area=p_area;
- capture_input_on_drag=false;
- ray_pickable=true;
+ rid = p_rid;
+ area = p_area;
+ capture_input_on_drag = false;
+ ray_pickable = true;
set_notify_transform(true);
if (p_area) {
- PhysicsServer::get_singleton()->area_attach_object_instance_ID(rid,get_instance_ID());
+ PhysicsServer::get_singleton()->area_attach_object_instance_ID(rid, get_instance_ID());
} else {
- PhysicsServer::get_singleton()->body_attach_object_instance_ID(rid,get_instance_ID());
+ PhysicsServer::get_singleton()->body_attach_object_instance_ID(rid, get_instance_ID());
}
//set_transform_notify(true);
-
}
void CollisionObject::set_capture_input_on_drag(bool p_capture) {
- capture_input_on_drag=p_capture;
-
+ capture_input_on_drag = p_capture;
}
bool CollisionObject::get_capture_input_on_drag() const {
@@ -355,12 +337,10 @@ bool CollisionObject::get_capture_input_on_drag() const {
return capture_input_on_drag;
}
-
CollisionObject::CollisionObject() {
-
- capture_input_on_drag=false;
- ray_pickable=true;
+ capture_input_on_drag = false;
+ ray_pickable = true;
set_notify_transform(true);
//owner=
diff --git a/scene/3d/collision_object.h b/scene/3d/collision_object.h
index b89b7e3361..9b124cf277 100644
--- a/scene/3d/collision_object.h
+++ b/scene/3d/collision_object.h
@@ -34,7 +34,7 @@
class CollisionObject : public Spatial {
- GDCLASS( CollisionObject, Spatial );
+ GDCLASS(CollisionObject, Spatial);
bool area;
RID rid;
@@ -42,12 +42,11 @@ class CollisionObject : public Spatial {
struct ShapeData {
Transform xform;
Ref<Shape> shape;
- bool trigger;
-
- ShapeData() {
- trigger=false;
- }
+ bool trigger;
+ ShapeData() {
+ trigger = false;
+ }
};
bool capture_input_on_drag;
@@ -57,30 +56,28 @@ class CollisionObject : public Spatial {
void _update_pickable();
void _update_shapes();
-friend class CollisionShape;
-friend class CollisionPolygon;
+ friend class CollisionShape;
+ friend class CollisionPolygon;
void _update_shapes_from_children();
-protected:
+protected:
CollisionObject(RID p_rid, bool p_area);
void _notification(int p_what);
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
-friend class Viewport;
- virtual void _input_event(Node* p_camera,const InputEvent& p_input_event,const Vector3& p_pos, const Vector3& p_normal, int p_shape);
+ friend class Viewport;
+ virtual void _input_event(Node *p_camera, const InputEvent &p_input_event, const Vector3 &p_pos, const Vector3 &p_normal, int p_shape);
virtual void _mouse_enter();
virtual void _mouse_exit();
public:
-
-
- void add_shape(const Ref<Shape>& p_shape, const Transform& p_transform=Transform());
+ void add_shape(const Ref<Shape> &p_shape, const Transform &p_transform = Transform());
int get_shape_count() const;
- void set_shape(int p_shape_idx, const Ref<Shape>& p_shape);
- void set_shape_transform(int p_shape_idx, const Transform& p_transform);
+ void set_shape(int p_shape_idx, const Ref<Shape> &p_shape);
+ void set_shape_transform(int p_shape_idx, const Transform &p_transform);
Ref<Shape> get_shape(int p_shape_idx) const;
Transform get_shape_transform(int p_shape_idx) const;
void remove_shape(int p_shape_idx);
@@ -94,7 +91,6 @@ public:
void set_capture_input_on_drag(bool p_capture);
bool get_capture_input_on_drag() const;
-
_FORCE_INLINE_ RID get_rid() const { return rid; }
CollisionObject();
diff --git a/scene/3d/collision_polygon.cpp b/scene/3d/collision_polygon.cpp
index 82637c2488..12dab067d0 100644
--- a/scene/3d/collision_polygon.cpp
+++ b/scene/3d/collision_polygon.cpp
@@ -40,44 +40,43 @@ void CollisionPolygon::_add_to_collision_object(Object *p_obj) {
CollisionObject *co = p_obj->cast_to<CollisionObject>();
ERR_FAIL_COND(!co);
- if (polygon.size()==0)
+ if (polygon.size() == 0)
return;
- bool solids=build_mode==BUILD_SOLIDS;
+ bool solids = build_mode == BUILD_SOLIDS;
- Vector< Vector<Vector2> > decomp = Geometry::decompose_polygon(polygon);
- if (decomp.size()==0)
+ Vector<Vector<Vector2> > decomp = Geometry::decompose_polygon(polygon);
+ if (decomp.size() == 0)
return;
if (true || solids) {
//here comes the sun, lalalala
//decompose concave into multiple convex polygons and add them
- shape_from=co->get_shape_count();
- for(int i=0;i<decomp.size();i++) {
- Ref<ConvexPolygonShape> convex = memnew( ConvexPolygonShape );
+ shape_from = co->get_shape_count();
+ for (int i = 0; i < decomp.size(); i++) {
+ Ref<ConvexPolygonShape> convex = memnew(ConvexPolygonShape);
PoolVector<Vector3> cp;
int cs = decomp[i].size();
- cp.resize(cs*2);
+ cp.resize(cs * 2);
{
PoolVector<Vector3>::Write w = cp.write();
- int idx=0;
- for(int j=0;j<cs;j++) {
+ int idx = 0;
+ for (int j = 0; j < cs; j++) {
Vector2 d = decomp[i][j];
- w[idx++]=Vector3(d.x,d.y,depth*0.5);
- w[idx++]=Vector3(d.x,d.y,-depth*0.5);
+ w[idx++] = Vector3(d.x, d.y, depth * 0.5);
+ w[idx++] = Vector3(d.x, d.y, -depth * 0.5);
}
}
convex->set_points(cp);
- co->add_shape(convex,get_transform());
-
+ co->add_shape(convex, get_transform());
}
- shape_to=co->get_shape_count()-1;
- if (shape_to<shape_from) {
- shape_from=-1;
- shape_to=-1;
+ shape_to = co->get_shape_count() - 1;
+ if (shape_to < shape_from) {
+ shape_from = -1;
+ shape_to = -1;
}
} else {
@@ -100,9 +99,7 @@ void CollisionPolygon::_add_to_collision_object(Object *p_obj) {
#endif
}
-
//co->add_shape(shape,get_transform());
-
}
void CollisionPolygon::_update_parent() {
@@ -119,29 +116,28 @@ void CollisionPolygon::_update_parent() {
co->_update_shapes_from_children();
}
-void CollisionPolygon::_set_shape_range(const Vector2& p_range) {
+void CollisionPolygon::_set_shape_range(const Vector2 &p_range) {
- shape_from=p_range.x;
- shape_to=p_range.y;
+ shape_from = p_range.x;
+ shape_to = p_range.y;
}
Vector2 CollisionPolygon::_get_shape_range() const {
- return Vector2(shape_from,shape_to);
+ return Vector2(shape_from, shape_to);
}
void CollisionPolygon::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- can_update_body=get_tree()->is_editor_hint();
+ can_update_body = get_tree()->is_editor_hint();
set_notify_local_transform(!can_update_body);
//indicator_instance = VisualServer::get_singleton()->instance_create2(indicator,get_world()->get_scenario());
} break;
case NOTIFICATION_EXIT_TREE: {
- can_update_body=false;
+ can_update_body = false;
set_notify_local_transform(false);
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -154,12 +150,12 @@ void CollisionPolygon::_notification(int p_what) {
} break;
case NOTIFICATION_LOCAL_TRANSFORM_CHANGED: {
- if (!can_update_body && shape_from>=0 && shape_to>=0) {
+ if (!can_update_body && shape_from >= 0 && shape_to >= 0) {
CollisionObject *co = get_parent()->cast_to<CollisionObject>();
if (co) {
- for(int i=shape_from;i<=shape_to;i++) {
- co->set_shape_transform(i,get_transform());
+ for (int i = shape_from; i <= shape_to; i++) {
+ co->set_shape_transform(i, get_transform());
}
}
}
@@ -190,31 +186,29 @@ void CollisionPolygon::_notification(int p_what) {
}
}
-void CollisionPolygon::set_polygon(const Vector<Point2>& p_polygon) {
+void CollisionPolygon::set_polygon(const Vector<Point2> &p_polygon) {
- polygon=p_polygon;
+ polygon = p_polygon;
if (can_update_body) {
- for(int i=0;i<polygon.size();i++) {
+ for (int i = 0; i < polygon.size(); i++) {
- Vector3 p1(polygon[i].x,polygon[i].y,depth*0.5);
+ Vector3 p1(polygon[i].x, polygon[i].y, depth * 0.5);
- if (i==0)
- aabb=Rect3(p1,Vector3());
+ if (i == 0)
+ aabb = Rect3(p1, Vector3());
else
aabb.expand_to(p1);
- Vector3 p2(polygon[i].x,polygon[i].y,-depth*0.5);
+ Vector3 p2(polygon[i].x, polygon[i].y, -depth * 0.5);
aabb.expand_to(p2);
-
-
}
- if (aabb==Rect3()) {
+ if (aabb == Rect3()) {
- aabb=Rect3(Vector3(-1,-1,-1),Vector3(2,2,2));
+ aabb = Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2));
} else {
- aabb.pos-=aabb.size*0.3;
- aabb.size+=aabb.size*0.6;
+ aabb.pos -= aabb.size * 0.3;
+ aabb.size += aabb.size * 0.6;
}
_update_parent();
}
@@ -228,14 +222,14 @@ Vector<Point2> CollisionPolygon::get_polygon() const {
void CollisionPolygon::set_build_mode(BuildMode p_mode) {
- ERR_FAIL_INDEX(p_mode,2);
- build_mode=p_mode;
+ ERR_FAIL_INDEX(p_mode, 2);
+ build_mode = p_mode;
if (!can_update_body)
return;
_update_parent();
}
-CollisionPolygon::BuildMode CollisionPolygon::get_build_mode() const{
+CollisionPolygon::BuildMode CollisionPolygon::get_build_mode() const {
return build_mode;
}
@@ -247,7 +241,7 @@ Rect3 CollisionPolygon::get_item_rect() const {
void CollisionPolygon::set_depth(float p_depth) {
- depth=p_depth;
+ depth = p_depth;
if (!can_update_body)
return;
_update_parent();
@@ -267,7 +261,6 @@ String CollisionPolygon::get_configuration_warning() const {
if (polygon.empty()) {
return TTR("An empty CollisionPolygon has no effect on collision.");
-
}
return String();
@@ -275,37 +268,36 @@ String CollisionPolygon::get_configuration_warning() const {
void CollisionPolygon::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_add_to_collision_object"),&CollisionPolygon::_add_to_collision_object);
+ ClassDB::bind_method(D_METHOD("_add_to_collision_object"), &CollisionPolygon::_add_to_collision_object);
- ClassDB::bind_method(D_METHOD("set_build_mode","build_mode"),&CollisionPolygon::set_build_mode);
- ClassDB::bind_method(D_METHOD("get_build_mode"),&CollisionPolygon::get_build_mode);
+ ClassDB::bind_method(D_METHOD("set_build_mode", "build_mode"), &CollisionPolygon::set_build_mode);
+ ClassDB::bind_method(D_METHOD("get_build_mode"), &CollisionPolygon::get_build_mode);
- ClassDB::bind_method(D_METHOD("set_depth","depth"),&CollisionPolygon::set_depth);
- ClassDB::bind_method(D_METHOD("get_depth"),&CollisionPolygon::get_depth);
+ ClassDB::bind_method(D_METHOD("set_depth", "depth"), &CollisionPolygon::set_depth);
+ ClassDB::bind_method(D_METHOD("get_depth"), &CollisionPolygon::get_depth);
- ClassDB::bind_method(D_METHOD("set_polygon","polygon"),&CollisionPolygon::set_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon"),&CollisionPolygon::get_polygon);
+ ClassDB::bind_method(D_METHOD("set_polygon", "polygon"), &CollisionPolygon::set_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon"), &CollisionPolygon::get_polygon);
- ClassDB::bind_method(D_METHOD("_set_shape_range","shape_range"),&CollisionPolygon::_set_shape_range);
- ClassDB::bind_method(D_METHOD("_get_shape_range"),&CollisionPolygon::_get_shape_range);
+ ClassDB::bind_method(D_METHOD("_set_shape_range", "shape_range"), &CollisionPolygon::_set_shape_range);
+ ClassDB::bind_method(D_METHOD("_get_shape_range"), &CollisionPolygon::_get_shape_range);
- ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"),&CollisionPolygon::get_collision_object_first_shape);
- ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"),&CollisionPolygon::get_collision_object_last_shape);
+ ClassDB::bind_method(D_METHOD("get_collision_object_first_shape"), &CollisionPolygon::get_collision_object_first_shape);
+ ClassDB::bind_method(D_METHOD("get_collision_object_last_shape"), &CollisionPolygon::get_collision_object_last_shape);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"build_mode",PROPERTY_HINT_ENUM,"Solids,Triangles"),"set_build_mode","get_build_mode");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"depth"),"set_depth","get_depth");
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"polygon"),"set_polygon","get_polygon");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"shape_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_shape_range","_get_shape_range");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "build_mode", PROPERTY_HINT_ENUM, "Solids,Triangles"), "set_build_mode", "get_build_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "depth"), "set_depth", "get_depth");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "polygon"), "set_polygon", "get_polygon");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "shape_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_shape_range", "_get_shape_range");
}
CollisionPolygon::CollisionPolygon() {
- shape_from=-1;
- shape_to=-1;
- can_update_body=false;
-
- aabb=Rect3(Vector3(-1,-1,-1),Vector3(2,2,2));
- build_mode=BUILD_SOLIDS;
- depth=1.0;
+ shape_from = -1;
+ shape_to = -1;
+ can_update_body = false;
+ aabb = Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2));
+ build_mode = BUILD_SOLIDS;
+ depth = 1.0;
}
diff --git a/scene/3d/collision_polygon.h b/scene/3d/collision_polygon.h
index 693cf0640a..fee146a87e 100644
--- a/scene/3d/collision_polygon.h
+++ b/scene/3d/collision_polygon.h
@@ -32,27 +32,22 @@
#include "scene/3d/spatial.h"
#include "scene/resources/shape.h"
-
-
class CollisionPolygon : public Spatial {
- GDCLASS(CollisionPolygon,Spatial);
-public:
+ GDCLASS(CollisionPolygon, Spatial);
+public:
enum BuildMode {
BUILD_SOLIDS,
BUILD_TRIANGLES,
};
protected:
-
-
float depth;
Rect3 aabb;
BuildMode build_mode;
Vector<Point2> polygon;
-
void _add_to_collision_object(Object *p_obj);
void _update_parent();
@@ -60,22 +55,21 @@ protected:
int shape_from;
int shape_to;
- void _set_shape_range(const Vector2& p_range);
+ void _set_shape_range(const Vector2 &p_range);
Vector2 _get_shape_range() const;
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_build_mode(BuildMode p_mode);
BuildMode get_build_mode() const;
void set_depth(float p_depth);
float get_depth() const;
- void set_polygon(const Vector<Point2>& p_polygon);
+ void set_polygon(const Vector<Point2> &p_polygon);
Vector<Point2> get_polygon() const;
virtual Rect3 get_item_rect() const;
@@ -88,5 +82,5 @@ public:
CollisionPolygon();
};
-VARIANT_ENUM_CAST( CollisionPolygon::BuildMode );
+VARIANT_ENUM_CAST(CollisionPolygon::BuildMode);
#endif // COLLISION_POLYGON_H
diff --git a/scene/3d/gi_probe.cpp b/scene/3d/gi_probe.cpp
index b22795e74d..cb1292a9d1 100644
--- a/scene/3d/gi_probe.cpp
+++ b/scene/3d/gi_probe.cpp
@@ -30,180 +30,158 @@
#include "mesh_instance.h"
+void GIProbeData::set_bounds(const Rect3 &p_bounds) {
-void GIProbeData::set_bounds(const Rect3& p_bounds) {
-
- VS::get_singleton()->gi_probe_set_bounds(probe,p_bounds);
+ VS::get_singleton()->gi_probe_set_bounds(probe, p_bounds);
}
-Rect3 GIProbeData::get_bounds() const{
+Rect3 GIProbeData::get_bounds() const {
return VS::get_singleton()->gi_probe_get_bounds(probe);
}
void GIProbeData::set_cell_size(float p_size) {
- VS::get_singleton()->gi_probe_set_cell_size(probe,p_size);
-
+ VS::get_singleton()->gi_probe_set_cell_size(probe, p_size);
}
float GIProbeData::get_cell_size() const {
return VS::get_singleton()->gi_probe_get_cell_size(probe);
-
}
-void GIProbeData::set_to_cell_xform(const Transform& p_xform) {
-
- VS::get_singleton()->gi_probe_set_to_cell_xform(probe,p_xform);
+void GIProbeData::set_to_cell_xform(const Transform &p_xform) {
+ VS::get_singleton()->gi_probe_set_to_cell_xform(probe, p_xform);
}
Transform GIProbeData::get_to_cell_xform() const {
return VS::get_singleton()->gi_probe_get_to_cell_xform(probe);
-
}
+void GIProbeData::set_dynamic_data(const PoolVector<int> &p_data) {
-void GIProbeData::set_dynamic_data(const PoolVector<int>& p_data){
-
- VS::get_singleton()->gi_probe_set_dynamic_data(probe,p_data);
-
+ VS::get_singleton()->gi_probe_set_dynamic_data(probe, p_data);
}
-PoolVector<int> GIProbeData::get_dynamic_data() const{
+PoolVector<int> GIProbeData::get_dynamic_data() const {
return VS::get_singleton()->gi_probe_get_dynamic_data(probe);
}
-void GIProbeData::set_dynamic_range(int p_range){
-
- VS::get_singleton()->gi_probe_set_dynamic_range(probe,p_range);
+void GIProbeData::set_dynamic_range(int p_range) {
+ VS::get_singleton()->gi_probe_set_dynamic_range(probe, p_range);
}
void GIProbeData::set_energy(float p_range) {
- VS::get_singleton()->gi_probe_set_energy(probe,p_range);
+ VS::get_singleton()->gi_probe_set_energy(probe, p_range);
}
-float GIProbeData::get_energy() const{
+float GIProbeData::get_energy() const {
return VS::get_singleton()->gi_probe_get_energy(probe);
-
}
-
void GIProbeData::set_bias(float p_range) {
- VS::get_singleton()->gi_probe_set_bias(probe,p_range);
+ VS::get_singleton()->gi_probe_set_bias(probe, p_range);
}
-float GIProbeData::get_bias() const{
+float GIProbeData::get_bias() const {
return VS::get_singleton()->gi_probe_get_bias(probe);
-
}
-
void GIProbeData::set_propagation(float p_range) {
- VS::get_singleton()->gi_probe_set_propagation(probe,p_range);
+ VS::get_singleton()->gi_probe_set_propagation(probe, p_range);
}
-float GIProbeData::get_propagation() const{
+float GIProbeData::get_propagation() const {
return VS::get_singleton()->gi_probe_get_propagation(probe);
-
}
-
void GIProbeData::set_interior(bool p_enable) {
- VS::get_singleton()->gi_probe_set_interior(probe,p_enable);
-
+ VS::get_singleton()->gi_probe_set_interior(probe, p_enable);
}
-bool GIProbeData::is_interior() const{
+bool GIProbeData::is_interior() const {
return VS::get_singleton()->gi_probe_is_interior(probe);
}
-
-bool GIProbeData::is_compressed() const{
+bool GIProbeData::is_compressed() const {
return VS::get_singleton()->gi_probe_is_compressed(probe);
}
-
void GIProbeData::set_compress(bool p_enable) {
- VS::get_singleton()->gi_probe_set_compress(probe,p_enable);
-
+ VS::get_singleton()->gi_probe_set_compress(probe, p_enable);
}
-int GIProbeData::get_dynamic_range() const{
-
+int GIProbeData::get_dynamic_range() const {
return VS::get_singleton()->gi_probe_get_dynamic_range(probe);
}
-
RID GIProbeData::get_rid() const {
return probe;
}
-
void GIProbeData::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_bounds","bounds"),&GIProbeData::set_bounds);
- ClassDB::bind_method(D_METHOD("get_bounds"),&GIProbeData::get_bounds);
+ ClassDB::bind_method(D_METHOD("set_bounds", "bounds"), &GIProbeData::set_bounds);
+ ClassDB::bind_method(D_METHOD("get_bounds"), &GIProbeData::get_bounds);
- ClassDB::bind_method(D_METHOD("set_cell_size","cell_size"),&GIProbeData::set_cell_size);
- ClassDB::bind_method(D_METHOD("get_cell_size"),&GIProbeData::get_cell_size);
+ ClassDB::bind_method(D_METHOD("set_cell_size", "cell_size"), &GIProbeData::set_cell_size);
+ ClassDB::bind_method(D_METHOD("get_cell_size"), &GIProbeData::get_cell_size);
- ClassDB::bind_method(D_METHOD("set_to_cell_xform","to_cell_xform"),&GIProbeData::set_to_cell_xform);
- ClassDB::bind_method(D_METHOD("get_to_cell_xform"),&GIProbeData::get_to_cell_xform);
+ ClassDB::bind_method(D_METHOD("set_to_cell_xform", "to_cell_xform"), &GIProbeData::set_to_cell_xform);
+ ClassDB::bind_method(D_METHOD("get_to_cell_xform"), &GIProbeData::get_to_cell_xform);
- ClassDB::bind_method(D_METHOD("set_dynamic_data","dynamic_data"),&GIProbeData::set_dynamic_data);
- ClassDB::bind_method(D_METHOD("get_dynamic_data"),&GIProbeData::get_dynamic_data);
+ ClassDB::bind_method(D_METHOD("set_dynamic_data", "dynamic_data"), &GIProbeData::set_dynamic_data);
+ ClassDB::bind_method(D_METHOD("get_dynamic_data"), &GIProbeData::get_dynamic_data);
- ClassDB::bind_method(D_METHOD("set_dynamic_range","dynamic_range"),&GIProbeData::set_dynamic_range);
- ClassDB::bind_method(D_METHOD("get_dynamic_range"),&GIProbeData::get_dynamic_range);
+ ClassDB::bind_method(D_METHOD("set_dynamic_range", "dynamic_range"), &GIProbeData::set_dynamic_range);
+ ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbeData::get_dynamic_range);
- ClassDB::bind_method(D_METHOD("set_energy","energy"),&GIProbeData::set_energy);
- ClassDB::bind_method(D_METHOD("get_energy"),&GIProbeData::get_energy);
+ ClassDB::bind_method(D_METHOD("set_energy", "energy"), &GIProbeData::set_energy);
+ ClassDB::bind_method(D_METHOD("get_energy"), &GIProbeData::get_energy);
- ClassDB::bind_method(D_METHOD("set_bias","bias"),&GIProbeData::set_bias);
- ClassDB::bind_method(D_METHOD("get_bias"),&GIProbeData::get_bias);
+ ClassDB::bind_method(D_METHOD("set_bias", "bias"), &GIProbeData::set_bias);
+ ClassDB::bind_method(D_METHOD("get_bias"), &GIProbeData::get_bias);
- ClassDB::bind_method(D_METHOD("set_propagation","propagation"),&GIProbeData::set_propagation);
- ClassDB::bind_method(D_METHOD("get_propagation"),&GIProbeData::get_propagation);
+ ClassDB::bind_method(D_METHOD("set_propagation", "propagation"), &GIProbeData::set_propagation);
+ ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbeData::get_propagation);
- ClassDB::bind_method(D_METHOD("set_interior","interior"),&GIProbeData::set_interior);
- ClassDB::bind_method(D_METHOD("is_interior"),&GIProbeData::is_interior);
+ ClassDB::bind_method(D_METHOD("set_interior", "interior"), &GIProbeData::set_interior);
+ ClassDB::bind_method(D_METHOD("is_interior"), &GIProbeData::is_interior);
- ClassDB::bind_method(D_METHOD("set_compress","compress"),&GIProbeData::set_compress);
- ClassDB::bind_method(D_METHOD("is_compressed"),&GIProbeData::is_compressed);
+ ClassDB::bind_method(D_METHOD("set_compress", "compress"), &GIProbeData::set_compress);
+ ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbeData::is_compressed);
- ADD_PROPERTY(PropertyInfo(Variant::RECT3,"bounds",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_bounds","get_bounds");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"cell_size",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_cell_size","get_cell_size");
- ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM,"to_cell_xform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_to_cell_xform","get_to_cell_xform");
-
- ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY,"dynamic_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_dynamic_data","get_dynamic_data");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_dynamic_range","get_dynamic_range");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_energy","get_energy");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_bias","get_bias");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"propagation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_propagation","get_propagation");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"interior",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_interior","is_interior");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"compress",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_compress","is_compressed");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT3, "bounds", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bounds", "get_bounds");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "cell_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_cell_size", "get_cell_size");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "to_cell_xform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_to_cell_xform", "get_to_cell_xform");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "dynamic_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_data", "get_dynamic_data");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_dynamic_range", "get_dynamic_range");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_energy", "get_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_bias", "get_bias");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_propagation", "get_propagation");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_interior", "is_interior");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_compress", "is_compressed");
}
GIProbeData::GIProbeData() {
- probe=VS::get_singleton()->gi_probe_create();
+ probe = VS::get_singleton()->gi_probe_create();
}
GIProbeData::~GIProbeData() {
@@ -211,20 +189,18 @@ GIProbeData::~GIProbeData() {
VS::get_singleton()->free(probe);
}
-
//////////////////////
//////////////////////
-
-void GIProbe::set_probe_data(const Ref<GIProbeData>& p_data) {
+void GIProbe::set_probe_data(const Ref<GIProbeData> &p_data) {
if (p_data.is_valid()) {
- VS::get_singleton()->instance_set_base(get_instance(),p_data->get_rid());
+ VS::get_singleton()->instance_set_base(get_instance(), p_data->get_rid());
} else {
- VS::get_singleton()->instance_set_base(get_instance(),RID());
+ VS::get_singleton()->instance_set_base(get_instance(), RID());
}
- probe_data=p_data;
+ probe_data = p_data;
}
Ref<GIProbeData> GIProbe::get_probe_data() const {
@@ -234,8 +210,8 @@ Ref<GIProbeData> GIProbe::get_probe_data() const {
void GIProbe::set_subdiv(Subdiv p_subdiv) {
- ERR_FAIL_INDEX(p_subdiv,SUBDIV_MAX);
- subdiv=p_subdiv;
+ ERR_FAIL_INDEX(p_subdiv, SUBDIV_MAX);
+ subdiv = p_subdiv;
update_gizmo();
}
@@ -244,9 +220,9 @@ GIProbe::Subdiv GIProbe::get_subdiv() const {
return subdiv;
}
-void GIProbe::set_extents(const Vector3& p_extents) {
+void GIProbe::set_extents(const Vector3 &p_extents) {
- extents=p_extents;
+ extents = p_extents;
update_gizmo();
}
@@ -257,7 +233,7 @@ Vector3 GIProbe::get_extents() const {
void GIProbe::set_dynamic_range(int p_dynamic_range) {
- dynamic_range=p_dynamic_range;
+ dynamic_range = p_dynamic_range;
}
int GIProbe::get_dynamic_range() const {
@@ -266,7 +242,7 @@ int GIProbe::get_dynamic_range() const {
void GIProbe::set_energy(float p_energy) {
- energy=p_energy;
+ energy = p_energy;
if (probe_data.is_valid()) {
probe_data->set_energy(energy);
}
@@ -278,7 +254,7 @@ float GIProbe::get_energy() const {
void GIProbe::set_bias(float p_bias) {
- bias=p_bias;
+ bias = p_bias;
if (probe_data.is_valid()) {
probe_data->set_bias(bias);
}
@@ -290,7 +266,7 @@ float GIProbe::get_bias() const {
void GIProbe::set_propagation(float p_propagation) {
- propagation=p_propagation;
+ propagation = p_propagation;
if (probe_data.is_valid()) {
probe_data->set_propagation(propagation);
}
@@ -302,7 +278,7 @@ float GIProbe::get_propagation() const {
void GIProbe::set_interior(bool p_enable) {
- interior=p_enable;
+ interior = p_enable;
if (probe_data.is_valid()) {
probe_data->set_interior(p_enable);
}
@@ -313,10 +289,9 @@ bool GIProbe::is_interior() const {
return interior;
}
-
void GIProbe::set_compress(bool p_enable) {
- compress=p_enable;
+ compress = p_enable;
if (probe_data.is_valid()) {
probe_data->set_compress(p_enable);
}
@@ -327,263 +302,287 @@ bool GIProbe::is_compressed() const {
return compress;
}
-
#include "math.h"
-#define FINDMINMAX(x0,x1,x2,min,max) \
- min = max = x0; \
- if(x1<min) min=x1;\
- if(x1>max) max=x1;\
- if(x2<min) min=x2;\
- if(x2>max) max=x2;
-
-static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox)
-{
- int q;
- Vector3 vmin,vmax;
- for(q=0;q<=2;q++)
- {
- if(normal[q]>0.0f)
- {
- vmin[q]=-maxbox[q];
- vmax[q]=maxbox[q];
- }
- else
- {
- vmin[q]=maxbox[q];
- vmax[q]=-maxbox[q];
- }
- }
- if(normal.dot(vmin)+d>0.0f) return false;
- if(normal.dot(vmax)+d>=0.0f) return true;
-
- return false;
-}
+#define FINDMINMAX(x0, x1, x2, min, max) \
+ min = max = x0; \
+ if (x1 < min) min = x1; \
+ if (x1 > max) max = x1; \
+ if (x2 < min) min = x2; \
+ if (x2 > max) max = x2;
+
+static bool planeBoxOverlap(Vector3 normal, float d, Vector3 maxbox) {
+ int q;
+ Vector3 vmin, vmax;
+ for (q = 0; q <= 2; q++) {
+ if (normal[q] > 0.0f) {
+ vmin[q] = -maxbox[q];
+ vmax[q] = maxbox[q];
+ } else {
+ vmin[q] = maxbox[q];
+ vmax[q] = -maxbox[q];
+ }
+ }
+ if (normal.dot(vmin) + d > 0.0f) return false;
+ if (normal.dot(vmax) + d >= 0.0f) return true;
+ return false;
+}
/*======================== X-tests ========================*/
-#define AXISTEST_X01(a, b, fa, fb) \
- p0 = a*v0.y - b*v0.z; \
- p2 = a*v2.y - b*v2.z; \
- if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
- rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_X2(a, b, fa, fb) \
- p0 = a*v0.y - b*v0.z; \
- p1 = a*v1.y - b*v1.z; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
+#define AXISTEST_X01(a, b, fa, fb) \
+ p0 = a * v0.y - b * v0.z; \
+ p2 = a * v2.y - b * v2.z; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_X2(a, b, fa, fb) \
+ p0 = a * v0.y - b * v0.z; \
+ p1 = a * v1.y - b * v1.z; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
/*======================== Y-tests ========================*/
-#define AXISTEST_Y02(a, b, fa, fb) \
- p0 = -a*v0.x + b*v0.z; \
- p2 = -a*v2.x + b*v2.z; \
- if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_Y1(a, b, fa, fb) \
- p0 = -a*v0.x + b*v0.z; \
- p1 = -a*v1.x + b*v1.z; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
- if(min>rad || max<-rad) return false;
+#define AXISTEST_Y02(a, b, fa, fb) \
+ p0 = -a * v0.x + b * v0.z; \
+ p2 = -a * v2.x + b * v2.z; \
+ if (p0 < p2) { \
+ min = p0; \
+ max = p2; \
+ } else { \
+ min = p2; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_Y1(a, b, fa, fb) \
+ p0 = -a * v0.x + b * v0.z; \
+ p1 = -a * v1.x + b * v1.z; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \
+ if (min > rad || max < -rad) return false;
/*======================== Z-tests ========================*/
-#define AXISTEST_Z12(a, b, fa, fb) \
- p1 = a*v1.x - b*v1.y; \
- p2 = a*v2.x - b*v2.y; \
- if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
- if(min>rad || max<-rad) return false;
-
-#define AXISTEST_Z0(a, b, fa, fb) \
- p0 = a*v0.x - b*v0.y; \
- p1 = a*v1.x - b*v1.y; \
- if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \
- rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
- if(min>rad || max<-rad) return false;
-
-static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) {
-
- /* use separating axis theorem to test overlap between triangle and box */
- /* need to test for overlap in these directions: */
- /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
- /* we do not even need to test these) */
- /* 2) normal of the triangle */
- /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
- /* this gives 3x3=9 more tests */
- Vector3 v0,v1,v2;
- float min,max,d,p0,p1,p2,rad,fex,fey,fez;
- Vector3 normal,e0,e1,e2;
-
- /* This is the fastest branch on Sun */
- /* move everything so that the boxcenter is in (0,0,0) */
-
- v0=triverts[0]-boxcenter;
- v1=triverts[1]-boxcenter;
- v2=triverts[2]-boxcenter;
-
- /* compute triangle edges */
- e0=v1-v0; /* tri edge 0 */
- e1=v2-v1; /* tri edge 1 */
- e2=v0-v2; /* tri edge 2 */
-
- /* Bullet 3: */
- /* test the 9 tests first (this was faster) */
- fex = Math::abs(e0.x);
- fey = Math::abs(e0.y);
- fez = Math::abs(e0.z);
- AXISTEST_X01(e0.z, e0.y, fez, fey);
- AXISTEST_Y02(e0.z, e0.x, fez, fex);
- AXISTEST_Z12(e0.y, e0.x, fey, fex);
-
- fex = Math::abs(e1.x);
- fey = Math::abs(e1.y);
- fez = Math::abs(e1.z);
- AXISTEST_X01(e1.z, e1.y, fez, fey);
- AXISTEST_Y02(e1.z, e1.x, fez, fex);
- AXISTEST_Z0(e1.y, e1.x, fey, fex);
-
- fex = Math::abs(e2.x);
- fey = Math::abs(e2.y);
- fez = Math::abs(e2.z);
- AXISTEST_X2(e2.z, e2.y, fez, fey);
- AXISTEST_Y1(e2.z, e2.x, fez, fex);
- AXISTEST_Z12(e2.y, e2.x, fey, fex);
-
- /* Bullet 1: */
- /* first test overlap in the {x,y,z}-directions */
- /* find min, max of the triangle each direction, and test for overlap in */
- /* that direction -- this is equivalent to testing a minimal AABB around */
- /* the triangle against the AABB */
-
- /* test in X-direction */
- FINDMINMAX(v0.x,v1.x,v2.x,min,max);
- if(min>boxhalfsize.x || max<-boxhalfsize.x) return false;
-
- /* test in Y-direction */
- FINDMINMAX(v0.y,v1.y,v2.y,min,max);
- if(min>boxhalfsize.y || max<-boxhalfsize.y) return false;
-
- /* test in Z-direction */
- FINDMINMAX(v0.z,v1.z,v2.z,min,max);
- if(min>boxhalfsize.z || max<-boxhalfsize.z) return false;
-
- /* Bullet 2: */
- /* test if the box intersects the plane of the triangle */
- /* compute plane equation of triangle: normal*x+d=0 */
- normal=e0.cross(e1);
- d=-normal.dot(v0); /* plane eq: normal.x+d=0 */
- if(!planeBoxOverlap(normal,d,boxhalfsize)) return false;
-
- return true; /* box and triangle overlaps */
+#define AXISTEST_Z12(a, b, fa, fb) \
+ p1 = a * v1.x - b * v1.y; \
+ p2 = a * v2.x - b * v2.y; \
+ if (p2 < p1) { \
+ min = p2; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p2; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
+ if (min > rad || max < -rad) return false;
+
+#define AXISTEST_Z0(a, b, fa, fb) \
+ p0 = a * v0.x - b * v0.y; \
+ p1 = a * v1.x - b * v1.y; \
+ if (p0 < p1) { \
+ min = p0; \
+ max = p1; \
+ } else { \
+ min = p1; \
+ max = p0; \
+ } \
+ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \
+ if (min > rad || max < -rad) return false;
+
+static bool fast_tri_box_overlap(const Vector3 &boxcenter, const Vector3 boxhalfsize, const Vector3 *triverts) {
+
+ /* use separating axis theorem to test overlap between triangle and box */
+ /* need to test for overlap in these directions: */
+ /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */
+ /* we do not even need to test these) */
+ /* 2) normal of the triangle */
+ /* 3) crossproduct(edge from tri, {x,y,z}-directin) */
+ /* this gives 3x3=9 more tests */
+ Vector3 v0, v1, v2;
+ float min, max, d, p0, p1, p2, rad, fex, fey, fez;
+ Vector3 normal, e0, e1, e2;
+
+ /* This is the fastest branch on Sun */
+ /* move everything so that the boxcenter is in (0,0,0) */
+
+ v0 = triverts[0] - boxcenter;
+ v1 = triverts[1] - boxcenter;
+ v2 = triverts[2] - boxcenter;
+
+ /* compute triangle edges */
+ e0 = v1 - v0; /* tri edge 0 */
+ e1 = v2 - v1; /* tri edge 1 */
+ e2 = v0 - v2; /* tri edge 2 */
+
+ /* Bullet 3: */
+ /* test the 9 tests first (this was faster) */
+ fex = Math::abs(e0.x);
+ fey = Math::abs(e0.y);
+ fez = Math::abs(e0.z);
+ AXISTEST_X01(e0.z, e0.y, fez, fey);
+ AXISTEST_Y02(e0.z, e0.x, fez, fex);
+ AXISTEST_Z12(e0.y, e0.x, fey, fex);
+
+ fex = Math::abs(e1.x);
+ fey = Math::abs(e1.y);
+ fez = Math::abs(e1.z);
+ AXISTEST_X01(e1.z, e1.y, fez, fey);
+ AXISTEST_Y02(e1.z, e1.x, fez, fex);
+ AXISTEST_Z0(e1.y, e1.x, fey, fex);
+
+ fex = Math::abs(e2.x);
+ fey = Math::abs(e2.y);
+ fez = Math::abs(e2.z);
+ AXISTEST_X2(e2.z, e2.y, fez, fey);
+ AXISTEST_Y1(e2.z, e2.x, fez, fex);
+ AXISTEST_Z12(e2.y, e2.x, fey, fex);
+
+ /* Bullet 1: */
+ /* first test overlap in the {x,y,z}-directions */
+ /* find min, max of the triangle each direction, and test for overlap in */
+ /* that direction -- this is equivalent to testing a minimal AABB around */
+ /* the triangle against the AABB */
+
+ /* test in X-direction */
+ FINDMINMAX(v0.x, v1.x, v2.x, min, max);
+ if (min > boxhalfsize.x || max < -boxhalfsize.x) return false;
+
+ /* test in Y-direction */
+ FINDMINMAX(v0.y, v1.y, v2.y, min, max);
+ if (min > boxhalfsize.y || max < -boxhalfsize.y) return false;
+
+ /* test in Z-direction */
+ FINDMINMAX(v0.z, v1.z, v2.z, min, max);
+ if (min > boxhalfsize.z || max < -boxhalfsize.z) return false;
+
+ /* Bullet 2: */
+ /* test if the box intersects the plane of the triangle */
+ /* compute plane equation of triangle: normal*x+d=0 */
+ normal = e0.cross(e1);
+ d = -normal.dot(v0); /* plane eq: normal.x+d=0 */
+ if (!planeBoxOverlap(normal, d, boxhalfsize)) return false;
+
+ return true; /* box and triangle overlaps */
}
+static _FORCE_INLINE_ Vector2 get_uv(const Vector3 &p_pos, const Vector3 *p_vtx, const Vector2 *p_uv) {
-
-static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) {
-
- if (p_pos.distance_squared_to(p_vtx[0])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[0]) < CMP_EPSILON2)
return p_uv[0];
- if (p_pos.distance_squared_to(p_vtx[1])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[1]) < CMP_EPSILON2)
return p_uv[1];
- if (p_pos.distance_squared_to(p_vtx[2])<CMP_EPSILON2)
+ if (p_pos.distance_squared_to(p_vtx[2]) < CMP_EPSILON2)
return p_uv[2];
Vector3 v0 = p_vtx[1] - p_vtx[0];
Vector3 v1 = p_vtx[2] - p_vtx[0];
Vector3 v2 = p_pos - p_vtx[0];
- float d00 = v0.dot( v0);
- float d01 = v0.dot( v1);
- float d11 = v1.dot( v1);
- float d20 = v2.dot( v0);
- float d21 = v2.dot( v1);
+ float d00 = v0.dot(v0);
+ float d01 = v0.dot(v1);
+ float d11 = v1.dot(v1);
+ float d20 = v2.dot(v0);
+ float d21 = v2.dot(v1);
float denom = (d00 * d11 - d01 * d01);
- if (denom==0)
+ if (denom == 0)
return p_uv[0];
float v = (d11 * d20 - d01 * d21) / denom;
float w = (d00 * d21 - d01 * d20) / denom;
float u = 1.0f - v - w;
- return p_uv[0]*u + p_uv[1]*v + p_uv[2]*w;
+ return p_uv[0] * u + p_uv[1] * v + p_uv[2] * w;
}
-void GIProbe::_plot_face(int p_idx, int p_level,int p_x,int p_y,int p_z, const Vector3 *p_vtx, const Vector2* p_uv, const Baker::MaterialCache& p_material, const Rect3 &p_aabb,Baker *p_baker) {
-
-
+void GIProbe::_plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector2 *p_uv, const Baker::MaterialCache &p_material, const Rect3 &p_aabb, Baker *p_baker) {
- if (p_level==p_baker->cell_subdiv-1) {
+ if (p_level == p_baker->cell_subdiv - 1) {
//plot the face by guessing it's albedo and emission value
//find best axis to map to, for scanning values
int closest_axis;
float closest_dot;
- Plane plane = Plane(p_vtx[0],p_vtx[1],p_vtx[2]);
+ Plane plane = Plane(p_vtx[0], p_vtx[1], p_vtx[2]);
Vector3 normal = plane.normal;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1.0;
- float dot=ABS(normal.dot(axis));
- if (i==0 || dot>closest_dot) {
- closest_axis=i;
- closest_dot=dot;
+ axis[i] = 1.0;
+ float dot = ABS(normal.dot(axis));
+ if (i == 0 || dot > closest_dot) {
+ closest_axis = i;
+ closest_dot = dot;
}
}
-
Vector3 axis;
- axis[closest_axis]=1.0;
+ axis[closest_axis] = 1.0;
Vector3 t1;
- t1[(closest_axis+1)%3]=1.0;
+ t1[(closest_axis + 1) % 3] = 1.0;
Vector3 t2;
- t2[(closest_axis+2)%3]=1.0;
+ t2[(closest_axis + 2) % 3] = 1.0;
- t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width);
- t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width);
+ t1 *= p_aabb.size[(closest_axis + 1) % 3] / float(color_scan_cell_width);
+ t2 *= p_aabb.size[(closest_axis + 2) % 3] / float(color_scan_cell_width);
Color albedo_accum;
Color emission_accum;
Vector3 normal_accum;
- float alpha=0.0;
+ float alpha = 0.0;
//map to a grid average in the best axis for this face
- for(int i=0;i<color_scan_cell_width;i++) {
+ for (int i = 0; i < color_scan_cell_width; i++) {
- Vector3 ofs_i=float(i)*t1;
+ Vector3 ofs_i = float(i) * t1;
- for(int j=0;j<color_scan_cell_width;j++) {
+ for (int j = 0; j < color_scan_cell_width; j++) {
- Vector3 ofs_j=float(j)*t2;
+ Vector3 ofs_j = float(j) * t2;
- Vector3 from = p_aabb.pos+ofs_i+ofs_j;
+ Vector3 from = p_aabb.pos + ofs_i + ofs_j;
Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis];
- Vector3 half = (to-from)*0.5;
+ Vector3 half = (to - from) * 0.5;
//is in this cell?
- if (!fast_tri_box_overlap(from+half,half,p_vtx)) {
+ if (!fast_tri_box_overlap(from + half, half, p_vtx)) {
continue; //face does not span this cell
}
//go from -size to +size*2 to avoid skipping collisions
- Vector3 ray_from = from + (t1+t2)*0.5 - axis * p_aabb.size[closest_axis];
- Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis]*2;
+ Vector3 ray_from = from + (t1 + t2) * 0.5 - axis * p_aabb.size[closest_axis];
+ Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis] * 2;
- if (normal.dot(ray_from-ray_to)<0) {
- SWAP(ray_from,ray_to);
+ if (normal.dot(ray_from - ray_to) < 0) {
+ SWAP(ray_from, ray_to);
}
Vector3 intersection;
- if (!plane.intersects_segment(ray_from,ray_to,&intersection)) {
+ if (!plane.intersects_segment(ray_from, ray_to, &intersection)) {
if (ABS(plane.distance_to(ray_from)) < ABS(plane.distance_to(ray_to))) {
intersection = plane.project(ray_from);
} else {
@@ -592,96 +591,91 @@ void GIProbe::_plot_face(int p_idx, int p_level,int p_x,int p_y,int p_z, const V
}
}
- intersection=Face3(p_vtx[0],p_vtx[1],p_vtx[2]).get_closest_point_to(intersection);
-
- Vector2 uv = get_uv(intersection,p_vtx,p_uv);
+ intersection = Face3(p_vtx[0], p_vtx[1], p_vtx[2]).get_closest_point_to(intersection);
+ Vector2 uv = get_uv(intersection, p_vtx, p_uv);
- int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1);
- int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1);
+ int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
- int ofs = uv_y*bake_texture_size+uv_x;
- albedo_accum.r+=p_material.albedo[ofs].r;
- albedo_accum.g+=p_material.albedo[ofs].g;
- albedo_accum.b+=p_material.albedo[ofs].b;
- albedo_accum.a+=p_material.albedo[ofs].a;
+ int ofs = uv_y * bake_texture_size + uv_x;
+ albedo_accum.r += p_material.albedo[ofs].r;
+ albedo_accum.g += p_material.albedo[ofs].g;
+ albedo_accum.b += p_material.albedo[ofs].b;
+ albedo_accum.a += p_material.albedo[ofs].a;
- emission_accum.r+=p_material.emission[ofs].r;
- emission_accum.g+=p_material.emission[ofs].g;
- emission_accum.b+=p_material.emission[ofs].b;
+ emission_accum.r += p_material.emission[ofs].r;
+ emission_accum.g += p_material.emission[ofs].g;
+ emission_accum.b += p_material.emission[ofs].b;
- normal_accum+=normal;
-
- alpha+=1.0;
+ normal_accum += normal;
+ alpha += 1.0;
}
}
-
- if (alpha==0) {
+ if (alpha == 0) {
//could not in any way get texture information.. so use closest point to center
- Face3 f( p_vtx[0],p_vtx[1],p_vtx[2]);
- Vector3 inters = f.get_closest_point_to(p_aabb.pos+p_aabb.size*0.5);
+ Face3 f(p_vtx[0], p_vtx[1], p_vtx[2]);
+ Vector3 inters = f.get_closest_point_to(p_aabb.pos + p_aabb.size * 0.5);
- Vector2 uv = get_uv(inters,p_vtx,p_uv);
+ Vector2 uv = get_uv(inters, p_vtx, p_uv);
- int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1);
- int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1);
+ int uv_x = CLAMP(Math::fposmod(uv.x, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
+ int uv_y = CLAMP(Math::fposmod(uv.y, 1.0f) * bake_texture_size, 0, bake_texture_size - 1);
- int ofs = uv_y*bake_texture_size+uv_x;
+ int ofs = uv_y * bake_texture_size + uv_x;
- alpha = 1.0/(color_scan_cell_width*color_scan_cell_width);
+ alpha = 1.0 / (color_scan_cell_width * color_scan_cell_width);
- albedo_accum.r=p_material.albedo[ofs].r*alpha;
- albedo_accum.g=p_material.albedo[ofs].g*alpha;
- albedo_accum.b=p_material.albedo[ofs].b*alpha;
- albedo_accum.a=p_material.albedo[ofs].a*alpha;
+ albedo_accum.r = p_material.albedo[ofs].r * alpha;
+ albedo_accum.g = p_material.albedo[ofs].g * alpha;
+ albedo_accum.b = p_material.albedo[ofs].b * alpha;
+ albedo_accum.a = p_material.albedo[ofs].a * alpha;
- emission_accum.r=p_material.emission[ofs].r*alpha;
- emission_accum.g=p_material.emission[ofs].g*alpha;
- emission_accum.b=p_material.emission[ofs].b*alpha;
-
- normal_accum*=alpha;
+ emission_accum.r = p_material.emission[ofs].r * alpha;
+ emission_accum.g = p_material.emission[ofs].g * alpha;
+ emission_accum.b = p_material.emission[ofs].b * alpha;
+ normal_accum *= alpha;
} else {
- float accdiv = 1.0/(color_scan_cell_width*color_scan_cell_width);
- alpha*=accdiv;
-
- albedo_accum.r*=accdiv;
- albedo_accum.g*=accdiv;
- albedo_accum.b*=accdiv;
- albedo_accum.a*=accdiv;
+ float accdiv = 1.0 / (color_scan_cell_width * color_scan_cell_width);
+ alpha *= accdiv;
- emission_accum.r*=accdiv;
- emission_accum.g*=accdiv;
- emission_accum.b*=accdiv;
+ albedo_accum.r *= accdiv;
+ albedo_accum.g *= accdiv;
+ albedo_accum.b *= accdiv;
+ albedo_accum.a *= accdiv;
- normal_accum*=accdiv;
+ emission_accum.r *= accdiv;
+ emission_accum.g *= accdiv;
+ emission_accum.b *= accdiv;
+ normal_accum *= accdiv;
}
//put this temporarily here, corrected in a later step
- p_baker->bake_cells[p_idx].albedo[0]+=albedo_accum.r;
- p_baker->bake_cells[p_idx].albedo[1]+=albedo_accum.g;
- p_baker->bake_cells[p_idx].albedo[2]+=albedo_accum.b;
- p_baker->bake_cells[p_idx].emission[0]+=emission_accum.r;
- p_baker->bake_cells[p_idx].emission[1]+=emission_accum.g;
- p_baker->bake_cells[p_idx].emission[2]+=emission_accum.b;
- p_baker->bake_cells[p_idx].normal[0]+=normal_accum.x;
- p_baker->bake_cells[p_idx].normal[1]+=normal_accum.y;
- p_baker->bake_cells[p_idx].normal[2]+=normal_accum.z;
- p_baker->bake_cells[p_idx].alpha+=alpha;
-
- static const Vector3 side_normals[6]={
+ p_baker->bake_cells[p_idx].albedo[0] += albedo_accum.r;
+ p_baker->bake_cells[p_idx].albedo[1] += albedo_accum.g;
+ p_baker->bake_cells[p_idx].albedo[2] += albedo_accum.b;
+ p_baker->bake_cells[p_idx].emission[0] += emission_accum.r;
+ p_baker->bake_cells[p_idx].emission[1] += emission_accum.g;
+ p_baker->bake_cells[p_idx].emission[2] += emission_accum.b;
+ p_baker->bake_cells[p_idx].normal[0] += normal_accum.x;
+ p_baker->bake_cells[p_idx].normal[1] += normal_accum.y;
+ p_baker->bake_cells[p_idx].normal[2] += normal_accum.z;
+ p_baker->bake_cells[p_idx].alpha += alpha;
+
+ static const Vector3 side_normals[6] = {
Vector3(-1, 0, 0),
- Vector3( 1, 0, 0),
- Vector3( 0,-1, 0),
- Vector3( 0, 1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0, 1),
+ Vector3(1, 0, 0),
+ Vector3(0, -1, 0),
+ Vector3(0, 1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, 1),
};
/*
@@ -691,104 +685,95 @@ void GIProbe::_plot_face(int p_idx, int p_level,int p_x,int p_y,int p_z, const V
}
}*/
-
} else {
//go down
- int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1);
- for(int i=0;i<8;i++) {
+ int half = (1 << (p_baker->cell_subdiv - 1)) >> (p_level + 1);
+ for (int i = 0; i < 8; i++) {
- Rect3 aabb=p_aabb;
- aabb.size*=0.5;
+ Rect3 aabb = p_aabb;
+ aabb.size *= 0.5;
- int nx=p_x;
- int ny=p_y;
- int nz=p_z;
+ int nx = p_x;
+ int ny = p_y;
+ int nz = p_z;
- if (i&1) {
- aabb.pos.x+=aabb.size.x;
- nx+=half;
+ if (i & 1) {
+ aabb.pos.x += aabb.size.x;
+ nx += half;
}
- if (i&2) {
- aabb.pos.y+=aabb.size.y;
- ny+=half;
+ if (i & 2) {
+ aabb.pos.y += aabb.size.y;
+ ny += half;
}
- if (i&4) {
- aabb.pos.z+=aabb.size.z;
- nz+=half;
+ if (i & 4) {
+ aabb.pos.z += aabb.size.z;
+ nz += half;
}
//make sure to not plot beyond limits
- if (nx<0 || nx>=p_baker->axis_cell_size[0] || ny<0 || ny>=p_baker->axis_cell_size[1] || nz<0 || nz>=p_baker->axis_cell_size[2])
+ if (nx < 0 || nx >= p_baker->axis_cell_size[0] || ny < 0 || ny >= p_baker->axis_cell_size[1] || nz < 0 || nz >= p_baker->axis_cell_size[2])
continue;
{
- Rect3 test_aabb=aabb;
+ Rect3 test_aabb = aabb;
//test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time
- Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test
+ Vector3 qsize = test_aabb.size * 0.5; //quarter size, for fast aabb test
- if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) {
- //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
+ if (!fast_tri_box_overlap(test_aabb.pos + qsize, qsize, p_vtx)) {
+ //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) {
//does not fit in child, go on
continue;
}
-
}
- if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY) {
+ if (p_baker->bake_cells[p_idx].childs[i] == Baker::CHILD_EMPTY) {
//sub cell must be created
uint32_t child_idx = p_baker->bake_cells.size();
- p_baker->bake_cells[p_idx].childs[i]=child_idx;
- p_baker->bake_cells.resize( p_baker->bake_cells.size() + 1);
- p_baker->bake_cells[child_idx].level=p_level+1;
-
+ p_baker->bake_cells[p_idx].childs[i] = child_idx;
+ p_baker->bake_cells.resize(p_baker->bake_cells.size() + 1);
+ p_baker->bake_cells[child_idx].level = p_level + 1;
}
-
- _plot_face(p_baker->bake_cells[p_idx].childs[i],p_level+1,nx,ny,nz,p_vtx,p_uv,p_material,aabb,p_baker);
+ _plot_face(p_baker->bake_cells[p_idx].childs[i], p_level + 1, nx, ny, nz, p_vtx, p_uv, p_material, aabb, p_baker);
}
}
}
+void GIProbe::_fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, Baker *p_baker) {
-
-void GIProbe::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker *p_baker) {
-
-
-
- if (p_level==p_baker->cell_subdiv-1) {
+ if (p_level == p_baker->cell_subdiv - 1) {
p_baker->leaf_voxel_count++;
float alpha = p_baker->bake_cells[p_idx].alpha;
- p_baker->bake_cells[p_idx].albedo[0]/=alpha;
- p_baker->bake_cells[p_idx].albedo[1]/=alpha;
- p_baker->bake_cells[p_idx].albedo[2]/=alpha;
+ p_baker->bake_cells[p_idx].albedo[0] /= alpha;
+ p_baker->bake_cells[p_idx].albedo[1] /= alpha;
+ p_baker->bake_cells[p_idx].albedo[2] /= alpha;
//transfer emission to light
- p_baker->bake_cells[p_idx].emission[0]/=alpha;
- p_baker->bake_cells[p_idx].emission[1]/=alpha;
- p_baker->bake_cells[p_idx].emission[2]/=alpha;
+ p_baker->bake_cells[p_idx].emission[0] /= alpha;
+ p_baker->bake_cells[p_idx].emission[1] /= alpha;
+ p_baker->bake_cells[p_idx].emission[2] /= alpha;
- p_baker->bake_cells[p_idx].normal[0]/=alpha;
- p_baker->bake_cells[p_idx].normal[1]/=alpha;
- p_baker->bake_cells[p_idx].normal[2]/=alpha;
+ p_baker->bake_cells[p_idx].normal[0] /= alpha;
+ p_baker->bake_cells[p_idx].normal[1] /= alpha;
+ p_baker->bake_cells[p_idx].normal[2] /= alpha;
- Vector3 n(p_baker->bake_cells[p_idx].normal[0],p_baker->bake_cells[p_idx].normal[1],p_baker->bake_cells[p_idx].normal[2]);
- if (n.length()<0.01) {
+ Vector3 n(p_baker->bake_cells[p_idx].normal[0], p_baker->bake_cells[p_idx].normal[1], p_baker->bake_cells[p_idx].normal[2]);
+ if (n.length() < 0.01) {
//too much fight over normal, zero it
- p_baker->bake_cells[p_idx].normal[0]=0;
- p_baker->bake_cells[p_idx].normal[1]=0;
- p_baker->bake_cells[p_idx].normal[2]=0;
+ p_baker->bake_cells[p_idx].normal[0] = 0;
+ p_baker->bake_cells[p_idx].normal[1] = 0;
+ p_baker->bake_cells[p_idx].normal[2] = 0;
} else {
n.normalize();
- p_baker->bake_cells[p_idx].normal[0]=n.x;
- p_baker->bake_cells[p_idx].normal[1]=n.y;
- p_baker->bake_cells[p_idx].normal[2]=n.z;
+ p_baker->bake_cells[p_idx].normal[0] = n.x;
+ p_baker->bake_cells[p_idx].normal[1] = n.y;
+ p_baker->bake_cells[p_idx].normal[2] = n.z;
}
-
- p_baker->bake_cells[p_idx].alpha=1.0;
+ p_baker->bake_cells[p_idx].alpha = 1.0;
/*
//remove neighbours from used sides
@@ -856,60 +841,54 @@ void GIProbe::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker
*/
} else {
-
//go down
- float alpha_average=0;
- int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1);
- for(int i=0;i<8;i++) {
+ float alpha_average = 0;
+ int half = (1 << (p_baker->cell_subdiv - 1)) >> (p_level + 1);
+ for (int i = 0; i < 8; i++) {
uint32_t child = p_baker->bake_cells[p_idx].childs[i];
- if (child==Baker::CHILD_EMPTY)
+ if (child == Baker::CHILD_EMPTY)
continue;
+ int nx = p_x;
+ int ny = p_y;
+ int nz = p_z;
- int nx=p_x;
- int ny=p_y;
- int nz=p_z;
-
- if (i&1)
- nx+=half;
- if (i&2)
- ny+=half;
- if (i&4)
- nz+=half;
+ if (i & 1)
+ nx += half;
+ if (i & 2)
+ ny += half;
+ if (i & 4)
+ nz += half;
- _fixup_plot(child,p_level+1,nx,ny,nz,p_baker);
- alpha_average+=p_baker->bake_cells[child].alpha;
+ _fixup_plot(child, p_level + 1, nx, ny, nz, p_baker);
+ alpha_average += p_baker->bake_cells[child].alpha;
}
- p_baker->bake_cells[p_idx].alpha=alpha_average/8.0;
- p_baker->bake_cells[p_idx].emission[0]=0;
- p_baker->bake_cells[p_idx].emission[1]=0;
- p_baker->bake_cells[p_idx].emission[2]=0;
- p_baker->bake_cells[p_idx].normal[0]=0;
- p_baker->bake_cells[p_idx].normal[1]=0;
- p_baker->bake_cells[p_idx].normal[2]=0;
- p_baker->bake_cells[p_idx].albedo[0]=0;
- p_baker->bake_cells[p_idx].albedo[1]=0;
- p_baker->bake_cells[p_idx].albedo[2]=0;
-
+ p_baker->bake_cells[p_idx].alpha = alpha_average / 8.0;
+ p_baker->bake_cells[p_idx].emission[0] = 0;
+ p_baker->bake_cells[p_idx].emission[1] = 0;
+ p_baker->bake_cells[p_idx].emission[2] = 0;
+ p_baker->bake_cells[p_idx].normal[0] = 0;
+ p_baker->bake_cells[p_idx].normal[1] = 0;
+ p_baker->bake_cells[p_idx].normal[2] = 0;
+ p_baker->bake_cells[p_idx].albedo[0] = 0;
+ p_baker->bake_cells[p_idx].albedo[1] = 0;
+ p_baker->bake_cells[p_idx].albedo[2] = 0;
}
-
}
-
-
-Vector<Color> GIProbe::_get_bake_texture(Image &p_image,const Color& p_color) {
+Vector<Color> GIProbe::_get_bake_texture(Image &p_image, const Color &p_color) {
Vector<Color> ret;
if (p_image.empty()) {
- ret.resize(bake_texture_size*bake_texture_size);
- for(int i=0;i<bake_texture_size*bake_texture_size;i++) {
- ret[i]=p_color;
+ ret.resize(bake_texture_size * bake_texture_size);
+ for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
+ ret[i] = p_color;
}
return ret;
@@ -920,27 +899,24 @@ Vector<Color> GIProbe::_get_bake_texture(Image &p_image,const Color& p_color) {
p_image.decompress();
}
p_image.convert(Image::FORMAT_RGBA8);
- p_image.resize(bake_texture_size,bake_texture_size,Image::INTERPOLATE_CUBIC);
-
+ p_image.resize(bake_texture_size, bake_texture_size, Image::INTERPOLATE_CUBIC);
PoolVector<uint8_t>::Read r = p_image.get_data().read();
- ret.resize(bake_texture_size*bake_texture_size);
+ ret.resize(bake_texture_size * bake_texture_size);
- for(int i=0;i<bake_texture_size*bake_texture_size;i++) {
+ for (int i = 0; i < bake_texture_size * bake_texture_size; i++) {
Color c;
- c.r = r[i*4+0]/255.0;
- c.g = r[i*4+1]/255.0;
- c.b = r[i*4+2]/255.0;
- c.a = r[i*4+3]/255.0;
- ret[i]=c;
-
+ c.r = r[i * 4 + 0] / 255.0;
+ c.g = r[i * 4 + 1] / 255.0;
+ c.b = r[i * 4 + 2] / 255.0;
+ c.a = r[i * 4 + 3] / 255.0;
+ ret[i] = c;
}
return ret;
}
-
-GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref<Material> p_material,Baker *p_baker) {
+GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref<Material> p_material, Baker *p_baker) {
//this way of obtaining materials is inaccurate and also does not support some compressed formats very well
Ref<FixedSpatialMaterial> mat = p_material;
@@ -962,17 +938,16 @@ GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref<Material> p_mater
img_albedo = albedo_tex->get_data();
} else {
-
}
- mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo());
+ mc.albedo = _get_bake_texture(img_albedo, mat->get_albedo());
Ref<ImageTexture> emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION);
Color emission_col = mat->get_emission();
- emission_col.r*=mat->get_emission_energy();
- emission_col.g*=mat->get_emission_energy();
- emission_col.b*=mat->get_emission_energy();
+ emission_col.r *= mat->get_emission_energy();
+ emission_col.g *= mat->get_emission_energy();
+ emission_col.b *= mat->get_emission_energy();
Image img_emission;
@@ -981,122 +956,110 @@ GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref<Material> p_mater
img_emission = emission_tex->get_data();
}
- mc.emission=_get_bake_texture(img_emission,emission_col);
+ mc.emission = _get_bake_texture(img_emission, emission_col);
} else {
Image empty;
- mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7));
- mc.emission=_get_bake_texture(empty,Color(0,0,0));
-
-
+ mc.albedo = _get_bake_texture(empty, Color(0.7, 0.7, 0.7));
+ mc.emission = _get_bake_texture(empty, Color(0, 0, 0));
}
- p_baker->material_cache[p_material]=mc;
+ p_baker->material_cache[p_material] = mc;
return mc;
-
-
}
-void GIProbe::_plot_mesh(const Transform& p_xform, Ref<Mesh>& p_mesh, Baker *p_baker, const Vector<Ref<Material> > &p_materials, const Ref<Material> &p_override_material) {
+void GIProbe::_plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, Baker *p_baker, const Vector<Ref<Material> > &p_materials, const Ref<Material> &p_override_material) {
+ for (int i = 0; i < p_mesh->get_surface_count(); i++) {
- for(int i=0;i<p_mesh->get_surface_count();i++) {
-
- if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES)
+ if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
continue; //only triangles
Ref<Material> src_material;
if (p_override_material.is_valid()) {
- src_material=p_override_material;
- } else if (i<p_materials.size() && p_materials[i].is_valid()) {
- src_material=p_materials[i];
+ src_material = p_override_material;
+ } else if (i < p_materials.size() && p_materials[i].is_valid()) {
+ src_material = p_materials[i];
} else {
- src_material=p_mesh->surface_get_material(i);
-
+ src_material = p_mesh->surface_get_material(i);
}
- Baker::MaterialCache material = _get_material_cache(src_material,p_baker);
+ Baker::MaterialCache material = _get_material_cache(src_material, p_baker);
Array a = p_mesh->surface_get_arrays(i);
-
PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV];
PoolVector<Vector2>::Read uvr;
PoolVector<int> index = a[Mesh::ARRAY_INDEX];
- bool read_uv=false;
+ bool read_uv = false;
if (uv.size()) {
- uvr=uv.read();
- read_uv=true;
+ uvr = uv.read();
+ read_uv = true;
}
if (index.size()) {
- int facecount = index.size()/3;
- PoolVector<int>::Read ir=index.read();
+ int facecount = index.size() / 3;
+ PoolVector<int>::Read ir = index.read();
- for(int j=0;j<facecount;j++) {
+ for (int j = 0; j < facecount; j++) {
Vector3 vtxs[3];
Vector2 uvs[3];
- for(int k=0;k<3;k++) {
- vtxs[k]=p_xform.xform(vr[ir[j*3+k]]);
+ for (int k = 0; k < 3; k++) {
+ vtxs[k] = p_xform.xform(vr[ir[j * 3 + k]]);
}
if (read_uv) {
- for(int k=0;k<3;k++) {
- uvs[k]=uvr[ir[j*3+k]];
+ for (int k = 0; k < 3; k++) {
+ uvs[k] = uvr[ir[j * 3 + k]];
}
}
//test against original bounds
- if (!fast_tri_box_overlap(-extents,extents*2,vtxs))
+ if (!fast_tri_box_overlap(-extents, extents * 2, vtxs))
continue;
//plot
- _plot_face(0,0,0,0,0,vtxs,uvs,material,p_baker->po2_bounds,p_baker);
+ _plot_face(0, 0, 0, 0, 0, vtxs, uvs, material, p_baker->po2_bounds, p_baker);
}
-
-
} else {
- int facecount = vertices.size()/3;
+ int facecount = vertices.size() / 3;
- for(int j=0;j<facecount;j++) {
+ for (int j = 0; j < facecount; j++) {
Vector3 vtxs[3];
Vector2 uvs[3];
- for(int k=0;k<3;k++) {
- vtxs[k]=p_xform.xform(vr[j*3+k]);
+ for (int k = 0; k < 3; k++) {
+ vtxs[k] = p_xform.xform(vr[j * 3 + k]);
}
if (read_uv) {
- for(int k=0;k<3;k++) {
- uvs[k]=uvr[j*3+k];
+ for (int k = 0; k < 3; k++) {
+ uvs[k] = uvr[j * 3 + k];
}
}
//test against original bounds
- if (!fast_tri_box_overlap(-extents,extents*2,vtxs))
+ if (!fast_tri_box_overlap(-extents, extents * 2, vtxs))
continue;
//plot face
- _plot_face(0,0,0,0,0,vtxs,uvs,material,p_baker->po2_bounds,p_baker);
+ _plot_face(0, 0, 0, 0, 0, vtxs, uvs, material, p_baker->po2_bounds, p_baker);
}
-
}
}
}
-
-
-void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){
+void GIProbe::_find_meshes(Node *p_at_node, Baker *p_baker) {
MeshInstance *mi = p_at_node->cast_to<MeshInstance>();
if (mi && mi->get_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT)) {
@@ -1107,16 +1070,15 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){
Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform();
- if (Rect3(-extents,extents*2).intersects(xf.xform(aabb))) {
+ if (Rect3(-extents, extents * 2).intersects(xf.xform(aabb))) {
Baker::PlotMesh pm;
- pm.local_xform=xf;
- pm.mesh=mesh;
- for(int i=0;i<mesh->get_surface_count();i++) {
+ pm.local_xform = xf;
+ pm.mesh = mesh;
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
pm.instance_materials.push_back(mi->get_surface_material(i));
}
- pm.override_material=mi->get_material_override();
+ pm.override_material = mi->get_material_override();
p_baker->mesh_list.push_back(pm);
-
}
}
}
@@ -1125,10 +1087,10 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){
Spatial *s = p_at_node->cast_to<Spatial>();
Array meshes = p_at_node->call("get_meshes");
- for(int i=0;i<meshes.size();i+=2) {
+ for (int i = 0; i < meshes.size(); i += 2) {
Transform mxf = meshes[i];
- Ref<Mesh> mesh = meshes[i+1];
+ Ref<Mesh> mesh = meshes[i + 1];
if (!mesh.is_valid())
continue;
@@ -1136,166 +1098,151 @@ void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){
Transform xf = get_global_transform().affine_inverse() * (s->get_global_transform() * mxf);
- if (Rect3(-extents,extents*2).intersects(xf.xform(aabb))) {
+ if (Rect3(-extents, extents * 2).intersects(xf.xform(aabb))) {
Baker::PlotMesh pm;
- pm.local_xform=xf;
- pm.mesh=mesh;
+ pm.local_xform = xf;
+ pm.mesh = mesh;
p_baker->mesh_list.push_back(pm);
-
}
}
}
- for(int i=0;i<p_at_node->get_child_count();i++) {
+ for (int i = 0; i < p_at_node->get_child_count(); i++) {
Node *child = p_at_node->get_child(i);
if (!child->get_owner())
continue; //maybe a helper
- _find_meshes(child,p_baker);
-
+ _find_meshes(child, p_baker);
}
}
-
-
-
-void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){
+void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug) {
Baker baker;
- static const int subdiv_value[SUBDIV_MAX]={7,8,9,10};
+ static const int subdiv_value[SUBDIV_MAX] = { 7, 8, 9, 10 };
- baker.cell_subdiv=subdiv_value[subdiv];
+ baker.cell_subdiv = subdiv_value[subdiv];
baker.bake_cells.resize(1);
//find out the actual real bounds, power of 2, which gets the highest subdivision
- baker.po2_bounds=Rect3(-extents,extents*2.0);
+ baker.po2_bounds = Rect3(-extents, extents * 2.0);
int longest_axis = baker.po2_bounds.get_longest_axis_index();
- baker.axis_cell_size[longest_axis]=(1<<(baker.cell_subdiv-1));
- baker.leaf_voxel_count=0;
+ baker.axis_cell_size[longest_axis] = (1 << (baker.cell_subdiv - 1));
+ baker.leaf_voxel_count = 0;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (i==longest_axis)
+ if (i == longest_axis)
continue;
- baker.axis_cell_size[i]=baker.axis_cell_size[longest_axis];
+ baker.axis_cell_size[i] = baker.axis_cell_size[longest_axis];
float axis_size = baker.po2_bounds.size[longest_axis];
//shrink until fit subdiv
- while (axis_size/2.0 >= baker.po2_bounds.size[i]) {
- axis_size/=2.0;
- baker.axis_cell_size[i]>>=1;
+ while (axis_size / 2.0 >= baker.po2_bounds.size[i]) {
+ axis_size /= 2.0;
+ baker.axis_cell_size[i] >>= 1;
}
- baker.po2_bounds.size[i]=baker.po2_bounds.size[longest_axis];
+ baker.po2_bounds.size[i] = baker.po2_bounds.size[longest_axis];
}
-
-
Transform to_bounds;
- to_bounds.basis.scale(Vector3(baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis]));
- to_bounds.origin=baker.po2_bounds.pos;
+ to_bounds.basis.scale(Vector3(baker.po2_bounds.size[longest_axis], baker.po2_bounds.size[longest_axis], baker.po2_bounds.size[longest_axis]));
+ to_bounds.origin = baker.po2_bounds.pos;
Transform to_grid;
- to_grid.basis.scale(Vector3(baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis]));
+ to_grid.basis.scale(Vector3(baker.axis_cell_size[longest_axis], baker.axis_cell_size[longest_axis], baker.axis_cell_size[longest_axis]));
baker.to_cell_space = to_grid * to_bounds.affine_inverse();
+ _find_meshes(p_from_node ? p_from_node : get_parent(), &baker);
- _find_meshes(p_from_node?p_from_node:get_parent(),&baker);
-
-
+ int pmc = 0;
- int pmc=0;
+ for (List<Baker::PlotMesh>::Element *E = baker.mesh_list.front(); E; E = E->next()) {
- for(List<Baker::PlotMesh>::Element *E=baker.mesh_list.front();E;E=E->next()) {
+ print_line("plotting mesh " + itos(pmc++) + "/" + itos(baker.mesh_list.size()));
- print_line("plotting mesh "+itos(pmc++)+"/"+itos(baker.mesh_list.size()));
-
- _plot_mesh(E->get().local_xform,E->get().mesh,&baker,E->get().instance_materials,E->get().override_material);
+ _plot_mesh(E->get().local_xform, E->get().mesh, &baker, E->get().instance_materials, E->get().override_material);
}
- _fixup_plot(0,0,0,0,0,&baker);
+ _fixup_plot(0, 0, 0, 0, 0, &baker);
//create the data for visual server
PoolVector<int> data;
- data.resize( 16+(8+1+1+1+1)*baker.bake_cells.size() ); //4 for header, rest for rest.
+ data.resize(16 + (8 + 1 + 1 + 1 + 1) * baker.bake_cells.size()); //4 for header, rest for rest.
{
PoolVector<int>::Write w = data.write();
- uint32_t * w32 = (uint32_t*)w.ptr();
+ uint32_t *w32 = (uint32_t *)w.ptr();
- w32[0]=0;//version
- w32[1]=baker.cell_subdiv; //subdiv
- w32[2]=baker.axis_cell_size[0];
- w32[3]=baker.axis_cell_size[1];
- w32[4]=baker.axis_cell_size[2];
- w32[5]=baker.bake_cells.size();
- w32[6]=baker.leaf_voxel_count;
+ w32[0] = 0; //version
+ w32[1] = baker.cell_subdiv; //subdiv
+ w32[2] = baker.axis_cell_size[0];
+ w32[3] = baker.axis_cell_size[1];
+ w32[4] = baker.axis_cell_size[2];
+ w32[5] = baker.bake_cells.size();
+ w32[6] = baker.leaf_voxel_count;
- int ofs=16;
+ int ofs = 16;
- for(int i=0;i<baker.bake_cells.size();i++) {
+ for (int i = 0; i < baker.bake_cells.size(); i++) {
- for(int j=0;j<8;j++) {
- w32[ofs++]=baker.bake_cells[i].childs[j];
+ for (int j = 0; j < 8; j++) {
+ w32[ofs++] = baker.bake_cells[i].childs[j];
}
{ //albedo
- uint32_t rgba=uint32_t(CLAMP(baker.bake_cells[i].albedo[0]*255.0,0,255))<<16;
- rgba|=uint32_t(CLAMP(baker.bake_cells[i].albedo[1]*255.0,0,255))<<8;
- rgba|=uint32_t(CLAMP(baker.bake_cells[i].albedo[2]*255.0,0,255))<<0;
-
- w32[ofs++]=rgba;
-
+ uint32_t rgba = uint32_t(CLAMP(baker.bake_cells[i].albedo[0] * 255.0, 0, 255)) << 16;
+ rgba |= uint32_t(CLAMP(baker.bake_cells[i].albedo[1] * 255.0, 0, 255)) << 8;
+ rgba |= uint32_t(CLAMP(baker.bake_cells[i].albedo[2] * 255.0, 0, 255)) << 0;
+ w32[ofs++] = rgba;
}
{ //emission
- Vector3 e(baker.bake_cells[i].emission[0],baker.bake_cells[i].emission[1],baker.bake_cells[i].emission[2]);
+ Vector3 e(baker.bake_cells[i].emission[0], baker.bake_cells[i].emission[1], baker.bake_cells[i].emission[2]);
float l = e.length();
- if (l>0) {
+ if (l > 0) {
e.normalize();
- l=CLAMP(l/8.0,0,1.0);
+ l = CLAMP(l / 8.0, 0, 1.0);
}
- uint32_t em=uint32_t(CLAMP(e[0]*255,0,255))<<24;
- em|=uint32_t(CLAMP(e[1]*255,0,255))<<16;
- em|=uint32_t(CLAMP(e[2]*255,0,255))<<8;
- em|=uint32_t(CLAMP(l*255,0,255));
+ uint32_t em = uint32_t(CLAMP(e[0] * 255, 0, 255)) << 24;
+ em |= uint32_t(CLAMP(e[1] * 255, 0, 255)) << 16;
+ em |= uint32_t(CLAMP(e[2] * 255, 0, 255)) << 8;
+ em |= uint32_t(CLAMP(l * 255, 0, 255));
- w32[ofs++]=em;
+ w32[ofs++] = em;
}
//w32[ofs++]=baker.bake_cells[i].used_sides;
{ //normal
- Vector3 n(baker.bake_cells[i].normal[0],baker.bake_cells[i].normal[1],baker.bake_cells[i].normal[2]);
- n=n*Vector3(0.5,0.5,0.5)+Vector3(0.5,0.5,0.5);
- uint32_t norm=0;
-
+ Vector3 n(baker.bake_cells[i].normal[0], baker.bake_cells[i].normal[1], baker.bake_cells[i].normal[2]);
+ n = n * Vector3(0.5, 0.5, 0.5) + Vector3(0.5, 0.5, 0.5);
+ uint32_t norm = 0;
- norm|=uint32_t(CLAMP( n.x*255.0, 0, 255))<<16;
- norm|=uint32_t(CLAMP( n.y*255.0, 0, 255))<<8;
- norm|=uint32_t(CLAMP( n.z*255.0, 0, 255))<<0;
+ norm |= uint32_t(CLAMP(n.x * 255.0, 0, 255)) << 16;
+ norm |= uint32_t(CLAMP(n.y * 255.0, 0, 255)) << 8;
+ norm |= uint32_t(CLAMP(n.z * 255.0, 0, 255)) << 0;
- w32[ofs++]=norm;
+ w32[ofs++] = norm;
}
{
- uint16_t alpha = CLAMP(uint32_t(baker.bake_cells[i].alpha*65535.0),0,65535);
+ uint16_t alpha = CLAMP(uint32_t(baker.bake_cells[i].alpha * 65535.0), 0, 65535);
uint16_t level = baker.bake_cells[i].level;
- w32[ofs++] = (uint32_t(level)<<16)|uint32_t(alpha);
+ w32[ofs++] = (uint32_t(level) << 16) | uint32_t(alpha);
}
-
}
-
}
if (p_create_visual_debug) {
@@ -1304,8 +1251,8 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){
Ref<GIProbeData> probe_data;
probe_data.instance();
- probe_data->set_bounds(Rect3(-extents,extents*2.0));
- probe_data->set_cell_size(baker.po2_bounds.size[longest_axis]/baker.axis_cell_size[longest_axis]);
+ probe_data->set_bounds(Rect3(-extents, extents * 2.0));
+ probe_data->set_cell_size(baker.po2_bounds.size[longest_axis] / baker.axis_cell_size[longest_axis]);
probe_data->set_dynamic_data(data);
probe_data->set_dynamic_range(dynamic_range);
probe_data->set_energy(energy);
@@ -1317,54 +1264,44 @@ void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){
set_probe_data(probe_data);
}
-
-
-
-
-
}
+void GIProbe::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx, Baker *p_baker) {
-void GIProbe::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,Ref<MultiMesh> &p_multimesh,int &idx,Baker *p_baker) {
+ if (p_level == p_baker->cell_subdiv - 1) {
-
- if (p_level==p_baker->cell_subdiv-1) {
-
- Vector3 center = p_aabb.pos+p_aabb.size*0.5;
+ Vector3 center = p_aabb.pos + p_aabb.size * 0.5;
Transform xform;
- xform.origin=center;
- xform.basis.scale(p_aabb.size*0.5);
- p_multimesh->set_instance_transform(idx,xform);
- Color col=Color(p_baker->bake_cells[p_idx].albedo[0],p_baker->bake_cells[p_idx].albedo[1],p_baker->bake_cells[p_idx].albedo[2]);
- p_multimesh->set_instance_color(idx,col);
+ xform.origin = center;
+ xform.basis.scale(p_aabb.size * 0.5);
+ p_multimesh->set_instance_transform(idx, xform);
+ Color col = Color(p_baker->bake_cells[p_idx].albedo[0], p_baker->bake_cells[p_idx].albedo[1], p_baker->bake_cells[p_idx].albedo[2]);
+ p_multimesh->set_instance_color(idx, col);
idx++;
} else {
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
- if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY)
+ if (p_baker->bake_cells[p_idx].childs[i] == Baker::CHILD_EMPTY)
continue;
- Rect3 aabb=p_aabb;
- aabb.size*=0.5;
+ Rect3 aabb = p_aabb;
+ aabb.size *= 0.5;
- if (i&1)
- aabb.pos.x+=aabb.size.x;
- if (i&2)
- aabb.pos.y+=aabb.size.y;
- if (i&4)
- aabb.pos.z+=aabb.size.z;
+ if (i & 1)
+ aabb.pos.x += aabb.size.x;
+ if (i & 2)
+ aabb.pos.y += aabb.size.y;
+ if (i & 4)
+ aabb.pos.z += aabb.size.z;
- _debug_mesh(p_baker->bake_cells[p_idx].childs[i],p_level+1,aabb,p_multimesh,idx,p_baker);
+ _debug_mesh(p_baker->bake_cells[p_idx].childs[i], p_level + 1, aabb, p_multimesh, idx, p_baker);
}
-
}
-
}
-
void GIProbe::_create_debug_mesh(Baker *p_baker) {
Ref<MultiMesh> mm;
@@ -1372,7 +1309,7 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) {
mm->set_transform_format(MultiMesh::TRANSFORM_3D);
mm->set_color_format(MultiMesh::COLOR_8BIT);
- print_line("leaf voxels: "+itos(p_baker->leaf_voxel_count));
+ print_line("leaf voxels: " + itos(p_baker->leaf_voxel_count));
mm->set_instance_count(p_baker->leaf_voxel_count);
Ref<Mesh> mesh;
@@ -1385,76 +1322,72 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) {
PoolVector<Vector3> vertices;
PoolVector<Color> colors;
- int vtx_idx=0;
- #define ADD_VTX(m_idx);\
- vertices.push_back( face_points[m_idx] );\
- colors.push_back( Color(1,1,1,1) );\
- vtx_idx++;\
-
- for (int i=0;i<6;i++) {
+ int vtx_idx = 0;
+#define ADD_VTX(m_idx) \
+ ; \
+ vertices.push_back(face_points[m_idx]); \
+ colors.push_back(Color(1, 1, 1, 1)); \
+ vtx_idx++;
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
}
- //tri 1
+ //tri 1
ADD_VTX(0);
ADD_VTX(1);
ADD_VTX(2);
- //tri 2
+ //tri 2
ADD_VTX(2);
ADD_VTX(3);
ADD_VTX(0);
-
}
-
- arr[Mesh::ARRAY_VERTEX]=vertices;
- arr[Mesh::ARRAY_COLOR]=colors;
- mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr);
+ arr[Mesh::ARRAY_VERTEX] = vertices;
+ arr[Mesh::ARRAY_COLOR] = colors;
+ mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
}
{
Ref<FixedSpatialMaterial> fsm;
fsm.instance();
- fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true);
- fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true);
- fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true);
- fsm->set_albedo(Color(1,1,1,1));
+ fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
+ fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
+ fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED, true);
+ fsm->set_albedo(Color(1, 1, 1, 1));
- mesh->surface_set_material(0,fsm);
+ mesh->surface_set_material(0, fsm);
}
mm->set_mesh(mesh);
+ int idx = 0;
+ _debug_mesh(0, 0, p_baker->po2_bounds, mm, idx, p_baker);
- int idx=0;
- _debug_mesh(0,0,p_baker->po2_bounds,mm,idx,p_baker);
-
- MultiMeshInstance *mmi = memnew( MultiMeshInstance );
+ MultiMeshInstance *mmi = memnew(MultiMeshInstance);
mmi->set_multimesh(mm);
add_child(mmi);
#ifdef TOOLS_ENABLED
- if (get_tree()->get_edited_scene_root()==this){
+ if (get_tree()->get_edited_scene_root() == this) {
mmi->set_owner(this);
} else {
mmi->set_owner(get_owner());
-
}
#else
mmi->set_owner(get_owner());
@@ -1463,12 +1396,12 @@ void GIProbe::_create_debug_mesh(Baker *p_baker) {
void GIProbe::_debug_bake() {
- bake(NULL,true);
+ bake(NULL, true);
}
Rect3 GIProbe::get_aabb() const {
- return Rect3(-extents,extents*2);
+ return Rect3(-extents, extents * 2);
}
PoolVector<Face3> GIProbe::get_faces(uint32_t p_usage_flags) const {
@@ -1478,74 +1411,68 @@ PoolVector<Face3> GIProbe::get_faces(uint32_t p_usage_flags) const {
void GIProbe::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_probe_data","data"),&GIProbe::set_probe_data);
- ClassDB::bind_method(D_METHOD("get_probe_data"),&GIProbe::get_probe_data);
+ ClassDB::bind_method(D_METHOD("set_probe_data", "data"), &GIProbe::set_probe_data);
+ ClassDB::bind_method(D_METHOD("get_probe_data"), &GIProbe::get_probe_data);
- ClassDB::bind_method(D_METHOD("set_subdiv","subdiv"),&GIProbe::set_subdiv);
- ClassDB::bind_method(D_METHOD("get_subdiv"),&GIProbe::get_subdiv);
+ ClassDB::bind_method(D_METHOD("set_subdiv", "subdiv"), &GIProbe::set_subdiv);
+ ClassDB::bind_method(D_METHOD("get_subdiv"), &GIProbe::get_subdiv);
- ClassDB::bind_method(D_METHOD("set_extents","extents"),&GIProbe::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"),&GIProbe::get_extents);
+ ClassDB::bind_method(D_METHOD("set_extents", "extents"), &GIProbe::set_extents);
+ ClassDB::bind_method(D_METHOD("get_extents"), &GIProbe::get_extents);
- ClassDB::bind_method(D_METHOD("set_dynamic_range","max"),&GIProbe::set_dynamic_range);
- ClassDB::bind_method(D_METHOD("get_dynamic_range"),&GIProbe::get_dynamic_range);
+ ClassDB::bind_method(D_METHOD("set_dynamic_range", "max"), &GIProbe::set_dynamic_range);
+ ClassDB::bind_method(D_METHOD("get_dynamic_range"), &GIProbe::get_dynamic_range);
- ClassDB::bind_method(D_METHOD("set_energy","max"),&GIProbe::set_energy);
- ClassDB::bind_method(D_METHOD("get_energy"),&GIProbe::get_energy);
+ ClassDB::bind_method(D_METHOD("set_energy", "max"), &GIProbe::set_energy);
+ ClassDB::bind_method(D_METHOD("get_energy"), &GIProbe::get_energy);
- ClassDB::bind_method(D_METHOD("set_bias","max"),&GIProbe::set_bias);
- ClassDB::bind_method(D_METHOD("get_bias"),&GIProbe::get_bias);
+ ClassDB::bind_method(D_METHOD("set_bias", "max"), &GIProbe::set_bias);
+ ClassDB::bind_method(D_METHOD("get_bias"), &GIProbe::get_bias);
- ClassDB::bind_method(D_METHOD("set_propagation","max"),&GIProbe::set_propagation);
- ClassDB::bind_method(D_METHOD("get_propagation"),&GIProbe::get_propagation);
+ ClassDB::bind_method(D_METHOD("set_propagation", "max"), &GIProbe::set_propagation);
+ ClassDB::bind_method(D_METHOD("get_propagation"), &GIProbe::get_propagation);
- ClassDB::bind_method(D_METHOD("set_interior","enable"),&GIProbe::set_interior);
- ClassDB::bind_method(D_METHOD("is_interior"),&GIProbe::is_interior);
+ ClassDB::bind_method(D_METHOD("set_interior", "enable"), &GIProbe::set_interior);
+ ClassDB::bind_method(D_METHOD("is_interior"), &GIProbe::is_interior);
- ClassDB::bind_method(D_METHOD("set_compress","enable"),&GIProbe::set_compress);
- ClassDB::bind_method(D_METHOD("is_compressed"),&GIProbe::is_compressed);
+ ClassDB::bind_method(D_METHOD("set_compress", "enable"), &GIProbe::set_compress);
+ ClassDB::bind_method(D_METHOD("is_compressed"), &GIProbe::is_compressed);
- ClassDB::bind_method(D_METHOD("bake","from_node","create_visual_debug"),&GIProbe::bake,DEFVAL(Variant()),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("debug_bake"),&GIProbe::_debug_bake);
- ClassDB::set_method_flags(get_class_static(),_scs_create("debug_bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("bake", "from_node", "create_visual_debug"), &GIProbe::bake, DEFVAL(Variant()), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("debug_bake"), &GIProbe::_debug_bake);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("debug_bake"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"subdiv",PROPERTY_HINT_ENUM,"64,128,256,512"),"set_subdiv","get_subdiv");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"extents"),"set_extents","get_extents");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_RANGE,"1,16,1"),"set_dynamic_range","get_dynamic_range");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_energy","get_energy");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"propagation",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_propagation","get_propagation");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_RANGE,"0,4,0.001"),"set_bias","get_bias");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior"),"set_interior","is_interior");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"compress"),"set_compress","is_compressed");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"data",PROPERTY_HINT_RESOURCE_TYPE,"GIProbeData"),"set_probe_data","get_probe_data");
-
-
- BIND_CONSTANT( SUBDIV_64 );
- BIND_CONSTANT( SUBDIV_128 );
- BIND_CONSTANT( SUBDIV_256 );
- BIND_CONSTANT( SUBDIV_MAX );
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "subdiv", PROPERTY_HINT_ENUM, "64,128,256,512"), "set_subdiv", "get_subdiv");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dynamic_range", PROPERTY_HINT_RANGE, "1,16,1"), "set_dynamic_range", "get_dynamic_range");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_energy", "get_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "propagation", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_propagation", "get_propagation");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0,4,0.001"), "set_bias", "get_bias");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior"), "set_interior", "is_interior");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "compress"), "set_compress", "is_compressed");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "data", PROPERTY_HINT_RESOURCE_TYPE, "GIProbeData"), "set_probe_data", "get_probe_data");
+ BIND_CONSTANT(SUBDIV_64);
+ BIND_CONSTANT(SUBDIV_128);
+ BIND_CONSTANT(SUBDIV_256);
+ BIND_CONSTANT(SUBDIV_MAX);
}
GIProbe::GIProbe() {
- subdiv=SUBDIV_128;
- dynamic_range=4;
- energy=1.0;
- bias=0.4;
- propagation=1.0;
- extents=Vector3(10,10,10);
- color_scan_cell_width=4;
- bake_texture_size=128;
- interior=false;
- compress=false;
+ subdiv = SUBDIV_128;
+ dynamic_range = 4;
+ energy = 1.0;
+ bias = 0.4;
+ propagation = 1.0;
+ extents = Vector3(10, 10, 10);
+ color_scan_cell_width = 4;
+ bake_texture_size = 128;
+ interior = false;
+ compress = false;
gi_probe = VS::get_singleton()->gi_probe_create();
-
-
}
GIProbe::~GIProbe() {
-
-
}
diff --git a/scene/3d/gi_probe.h b/scene/3d/gi_probe.h
index a45e80806a..675b41cef9 100644
--- a/scene/3d/gi_probe.h
+++ b/scene/3d/gi_probe.h
@@ -29,32 +29,29 @@
#ifndef GIPROBE_H
#define GIPROBE_H
-#include "scene/3d/visual_instance.h"
#include "multimesh_instance.h"
+#include "scene/3d/visual_instance.h"
class GIProbeData : public Resource {
- GDCLASS(GIProbeData,Resource);
+ GDCLASS(GIProbeData, Resource);
RID probe;
protected:
-
static void _bind_methods();
-public:
-
-
- void set_bounds(const Rect3& p_bounds);
+public:
+ void set_bounds(const Rect3 &p_bounds);
Rect3 get_bounds() const;
void set_cell_size(float p_size);
float get_cell_size() const;
- void set_to_cell_xform(const Transform& p_xform);
+ void set_to_cell_xform(const Transform &p_xform);
Transform get_to_cell_xform() const;
- void set_dynamic_data(const PoolVector<int>& p_data);
+ void set_dynamic_data(const PoolVector<int> &p_data);
PoolVector<int> get_dynamic_data() const;
void set_dynamic_range(int p_range);
@@ -81,12 +78,11 @@ public:
~GIProbeData();
};
+class GIProbe : public VisualInstance {
+ GDCLASS(GIProbe, VisualInstance);
-
-class GIProbe : public VisualInstance {
- GDCLASS(GIProbe,VisualInstance);
public:
- enum Subdiv{
+ enum Subdiv {
SUBDIV_64,
SUBDIV_128,
SUBDIV_256,
@@ -94,13 +90,13 @@ public:
SUBDIV_MAX
};
-private:
+private:
//stuff used for bake
struct Baker {
enum {
- CHILD_EMPTY=0xFFFFFFFF
+ CHILD_EMPTY = 0xFFFFFFFF
};
struct Cell {
@@ -113,18 +109,18 @@ private:
int level;
Cell() {
- for(int i=0;i<8;i++) {
- childs[i]=CHILD_EMPTY;
+ for (int i = 0; i < 8; i++) {
+ childs[i] = CHILD_EMPTY;
}
- for(int i=0;i<3;i++) {
- emission[i]=0;
- albedo[i]=0;
- normal[i]=0;
+ for (int i = 0; i < 3; i++) {
+ emission[i] = 0;
+ albedo[i] = 0;
+ normal[i] = 0;
}
- alpha=0;
- used_sides=0;
- level=0;
+ alpha = 0;
+ used_sides = 0;
+ level = 0;
}
};
@@ -137,13 +133,11 @@ private:
Vector<Color> emission;
};
-
Vector<Color> _get_bake_texture(Image &p_image, const Color &p_color);
- Map<Ref<Material>,MaterialCache> material_cache;
+ Map<Ref<Material>, MaterialCache> material_cache;
MaterialCache _get_material_cache(Ref<Material> p_material);
int leaf_voxel_count;
-
Rect3 po2_bounds;
int axis_cell_size[3];
@@ -159,7 +153,6 @@ private:
List<PlotMesh> mesh_list;
};
-
Ref<GIProbeData> probe_data;
RID gi_probe;
@@ -176,30 +169,29 @@ private:
int color_scan_cell_width;
int bake_texture_size;
- Vector<Color> _get_bake_texture(Image &p_image,const Color& p_color);
- Baker::MaterialCache _get_material_cache(Ref<Material> p_material,Baker *p_baker);
- void _plot_face(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3 *p_vtx, const Vector2* p_uv, const Baker::MaterialCache& p_material, const Rect3 &p_aabb,Baker *p_baker);
- void _plot_mesh(const Transform& p_xform, Ref<Mesh>& p_mesh, Baker *p_baker,const Vector<Ref<Material> >& p_materials,const Ref<Material>& p_override_material);
- void _find_meshes(Node *p_at_node,Baker *p_baker);
- void _fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker *p_baker);
+ Vector<Color> _get_bake_texture(Image &p_image, const Color &p_color);
+ Baker::MaterialCache _get_material_cache(Ref<Material> p_material, Baker *p_baker);
+ void _plot_face(int p_idx, int p_level, int p_x, int p_y, int p_z, const Vector3 *p_vtx, const Vector2 *p_uv, const Baker::MaterialCache &p_material, const Rect3 &p_aabb, Baker *p_baker);
+ void _plot_mesh(const Transform &p_xform, Ref<Mesh> &p_mesh, Baker *p_baker, const Vector<Ref<Material> > &p_materials, const Ref<Material> &p_override_material);
+ void _find_meshes(Node *p_at_node, Baker *p_baker);
+ void _fixup_plot(int p_idx, int p_level, int p_x, int p_y, int p_z, Baker *p_baker);
- void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,Ref<MultiMesh> &p_multimesh,int &idx,Baker *p_baker);
+ void _debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb, Ref<MultiMesh> &p_multimesh, int &idx, Baker *p_baker);
void _create_debug_mesh(Baker *p_baker);
void _debug_bake();
protected:
-
static void _bind_methods();
-public:
- void set_probe_data(const Ref<GIProbeData>& p_data);
+public:
+ void set_probe_data(const Ref<GIProbeData> &p_data);
Ref<GIProbeData> get_probe_data() const;
void set_subdiv(Subdiv p_subdiv);
Subdiv get_subdiv() const;
- void set_extents(const Vector3& p_extents);
+ void set_extents(const Vector3 &p_extents);
Vector3 get_extents() const;
void set_dynamic_range(int p_dynamic_range);
@@ -220,7 +212,7 @@ public:
void set_compress(bool p_enable);
bool is_compressed() const;
- void bake(Node *p_from_node=NULL,bool p_create_visual_debug=false);
+ void bake(Node *p_from_node = NULL, bool p_create_visual_debug = false);
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
diff --git a/scene/3d/immediate_geometry.cpp b/scene/3d/immediate_geometry.cpp
index 6adbbe9ccf..adcc167223 100644
--- a/scene/3d/immediate_geometry.cpp
+++ b/scene/3d/immediate_geometry.cpp
@@ -28,68 +28,60 @@
/*************************************************************************/
#include "immediate_geometry.h"
+void ImmediateGeometry::begin(Mesh::PrimitiveType p_primitive, const Ref<Texture> &p_texture) {
-void ImmediateGeometry::begin(Mesh::PrimitiveType p_primitive,const Ref<Texture>& p_texture) {
-
- VS::get_singleton()->immediate_begin(im,(VS::PrimitiveType)p_primitive,p_texture.is_valid()?p_texture->get_rid():RID());
+ VS::get_singleton()->immediate_begin(im, (VS::PrimitiveType)p_primitive, p_texture.is_valid() ? p_texture->get_rid() : RID());
if (p_texture.is_valid())
cached_textures.push_back(p_texture);
-
}
-void ImmediateGeometry::set_normal(const Vector3& p_normal){
+void ImmediateGeometry::set_normal(const Vector3 &p_normal) {
- VS::get_singleton()->immediate_normal(im,p_normal);
+ VS::get_singleton()->immediate_normal(im, p_normal);
}
-void ImmediateGeometry::set_tangent(const Plane& p_tangent){
-
- VS::get_singleton()->immediate_tangent(im,p_tangent);
+void ImmediateGeometry::set_tangent(const Plane &p_tangent) {
+ VS::get_singleton()->immediate_tangent(im, p_tangent);
}
-void ImmediateGeometry::set_color(const Color& p_color){
-
- VS::get_singleton()->immediate_color(im,p_color);
+void ImmediateGeometry::set_color(const Color &p_color) {
+ VS::get_singleton()->immediate_color(im, p_color);
}
-void ImmediateGeometry::set_uv(const Vector2& p_uv){
-
- VS::get_singleton()->immediate_uv(im,p_uv);
+void ImmediateGeometry::set_uv(const Vector2 &p_uv) {
+ VS::get_singleton()->immediate_uv(im, p_uv);
}
-void ImmediateGeometry::set_uv2(const Vector2& p_uv2){
-
- VS::get_singleton()->immediate_uv2(im,p_uv2);
+void ImmediateGeometry::set_uv2(const Vector2 &p_uv2) {
+ VS::get_singleton()->immediate_uv2(im, p_uv2);
}
-void ImmediateGeometry::add_vertex(const Vector3& p_vertex){
+void ImmediateGeometry::add_vertex(const Vector3 &p_vertex) {
- VS::get_singleton()->immediate_vertex(im,p_vertex);
+ VS::get_singleton()->immediate_vertex(im, p_vertex);
if (empty) {
- aabb.pos=p_vertex;
- aabb.size=Vector3();
- empty=false;
+ aabb.pos = p_vertex;
+ aabb.size = Vector3();
+ empty = false;
} else {
aabb.expand_to(p_vertex);
}
}
-void ImmediateGeometry::end(){
+void ImmediateGeometry::end() {
VS::get_singleton()->immediate_end(im);
-
}
-void ImmediateGeometry::clear(){
+void ImmediateGeometry::clear() {
VS::get_singleton()->immediate_clear(im);
- empty=true;
+ empty = true;
cached_textures.clear();
-
}
Rect3 ImmediateGeometry::get_aabb() const {
@@ -101,44 +93,41 @@ PoolVector<Face3> ImmediateGeometry::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
}
-
-
void ImmediateGeometry::add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv) {
- for(int i = 1; i <= p_lats; i++) {
- double lat0 = Math_PI * (-0.5 + (double) (i - 1) / p_lats);
- double z0 = Math::sin(lat0);
- double zr0 = Math::cos(lat0);
+ for (int i = 1; i <= p_lats; i++) {
+ double lat0 = Math_PI * (-0.5 + (double)(i - 1) / p_lats);
+ double z0 = Math::sin(lat0);
+ double zr0 = Math::cos(lat0);
- double lat1 = Math_PI * (-0.5 + (double) i / p_lats);
+ double lat1 = Math_PI * (-0.5 + (double)i / p_lats);
double z1 = Math::sin(lat1);
double zr1 = Math::cos(lat1);
- for(int j = p_lons; j >= 1; j--) {
+ for (int j = p_lons; j >= 1; j--) {
- double lng0 = 2 * Math_PI * (double) (j - 1) / p_lons;
+ double lng0 = 2 * Math_PI * (double)(j - 1) / p_lons;
double x0 = Math::cos(lng0);
double y0 = Math::sin(lng0);
- double lng1 = 2 * Math_PI * (double) (j) / p_lons;
+ double lng1 = 2 * Math_PI * (double)(j) / p_lons;
double x1 = Math::cos(lng1);
double y1 = Math::sin(lng1);
-
- Vector3 v[4]={
- Vector3(x1 * zr0, z0, y1 *zr0),
- Vector3(x1 * zr1, z1, y1 *zr1),
- Vector3(x0 * zr1, z1, y0 *zr1),
- Vector3(x0 * zr0, z0, y0 *zr0)
+ Vector3 v[4] = {
+ Vector3(x1 * zr0, z0, y1 * zr0),
+ Vector3(x1 * zr1, z1, y1 * zr1),
+ Vector3(x0 * zr1, z1, y0 * zr1),
+ Vector3(x0 * zr0, z0, y0 * zr0)
};
-#define ADD_POINT(m_idx)\
- if (p_add_uv) {\
- set_uv(Vector2(Math::atan2(v[m_idx].x,v[m_idx].z)/Math_PI * 0.5+0.5,v[m_idx].y*0.5+0.5));\
- set_tangent(Plane(Vector3(-v[m_idx].z,v[m_idx].y,v[m_idx].x),1)); \
- }\
- set_normal(v[m_idx]);\
- add_vertex(v[m_idx]*p_radius);
+#define ADD_POINT(m_idx) \
+ if (p_add_uv) { \
+ set_uv(Vector2(Math::atan2(v[m_idx].x, v[m_idx].z) / Math_PI * 0.5 + 0.5, v[m_idx].y * 0.5 + 0.5)); \
+ set_tangent(Plane(Vector3(-v[m_idx].z, v[m_idx].y, v[m_idx].x), 1)); \
+ } \
+ set_normal(v[m_idx]); \
+ add_vertex(v[m_idx] * p_radius);
ADD_POINT(0);
ADD_POINT(1);
@@ -149,37 +138,30 @@ void ImmediateGeometry::add_sphere(int p_lats, int p_lons, float p_radius, bool
ADD_POINT(0);
}
}
-
}
void ImmediateGeometry::_bind_methods() {
- ClassDB::bind_method(D_METHOD("begin","primitive","texture:Texture"),&ImmediateGeometry::begin,DEFVAL(Ref<Texture>()));
- ClassDB::bind_method(D_METHOD("set_normal","normal"),&ImmediateGeometry::set_normal);
- ClassDB::bind_method(D_METHOD("set_tangent","tangent"),&ImmediateGeometry::set_tangent);
- ClassDB::bind_method(D_METHOD("set_color","color"),&ImmediateGeometry::set_color);
- ClassDB::bind_method(D_METHOD("set_uv","uv"),&ImmediateGeometry::set_uv);
- ClassDB::bind_method(D_METHOD("set_uv2","uv"),&ImmediateGeometry::set_uv2);
- ClassDB::bind_method(D_METHOD("add_vertex","pos"),&ImmediateGeometry::add_vertex);
- ClassDB::bind_method(D_METHOD("add_sphere","lats","lons","radius","add_uv"),&ImmediateGeometry::add_sphere,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("end"),&ImmediateGeometry::end);
- ClassDB::bind_method(D_METHOD("clear"),&ImmediateGeometry::clear);
-
+ ClassDB::bind_method(D_METHOD("begin", "primitive", "texture:Texture"), &ImmediateGeometry::begin, DEFVAL(Ref<Texture>()));
+ ClassDB::bind_method(D_METHOD("set_normal", "normal"), &ImmediateGeometry::set_normal);
+ ClassDB::bind_method(D_METHOD("set_tangent", "tangent"), &ImmediateGeometry::set_tangent);
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &ImmediateGeometry::set_color);
+ ClassDB::bind_method(D_METHOD("set_uv", "uv"), &ImmediateGeometry::set_uv);
+ ClassDB::bind_method(D_METHOD("set_uv2", "uv"), &ImmediateGeometry::set_uv2);
+ ClassDB::bind_method(D_METHOD("add_vertex", "pos"), &ImmediateGeometry::add_vertex);
+ ClassDB::bind_method(D_METHOD("add_sphere", "lats", "lons", "radius", "add_uv"), &ImmediateGeometry::add_sphere, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("end"), &ImmediateGeometry::end);
+ ClassDB::bind_method(D_METHOD("clear"), &ImmediateGeometry::clear);
}
-
-
ImmediateGeometry::ImmediateGeometry() {
im = VisualServer::get_singleton()->immediate_create();
set_base(im);
- empty=true;
-
+ empty = true;
}
-
ImmediateGeometry::~ImmediateGeometry() {
VisualServer::get_singleton()->free(im);
-
}
diff --git a/scene/3d/immediate_geometry.h b/scene/3d/immediate_geometry.h
index e385a34da1..6e0123992c 100644
--- a/scene/3d/immediate_geometry.h
+++ b/scene/3d/immediate_geometry.h
@@ -34,8 +34,7 @@
class ImmediateGeometry : public GeometryInstance {
- GDCLASS(ImmediateGeometry,GeometryInstance);
-
+ GDCLASS(ImmediateGeometry, GeometryInstance);
RID im;
//a list of texures drawn need to be kept, to avoid references
@@ -43,28 +42,24 @@ class ImmediateGeometry : public GeometryInstance {
List<Ref<Texture> > cached_textures;
bool empty;
Rect3 aabb;
-protected:
+protected:
static void _bind_methods();
-public:
-
- void begin(Mesh::PrimitiveType p_primitive,const Ref<Texture>& p_texture=Ref<Texture>());
- void set_normal(const Vector3& p_normal);
- void set_tangent(const Plane& p_tangent);
- void set_color(const Color& p_color);
- void set_uv(const Vector2& tex_uv);
- void set_uv2(const Vector2& tex_uv);
+public:
+ void begin(Mesh::PrimitiveType p_primitive, const Ref<Texture> &p_texture = Ref<Texture>());
+ void set_normal(const Vector3 &p_normal);
+ void set_tangent(const Plane &p_tangent);
+ void set_color(const Color &p_color);
+ void set_uv(const Vector2 &tex_uv);
+ void set_uv2(const Vector2 &tex_uv);
- void add_vertex(const Vector3& p_vertex);
+ void add_vertex(const Vector3 &p_vertex);
void end();
void clear();
-
- void add_sphere(int p_lats,int p_lons,float p_radius,bool p_add_uv=true);
-
-
+ void add_sphere(int p_lats, int p_lons, float p_radius, bool p_add_uv = true);
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
diff --git a/scene/3d/interpolated_camera.cpp b/scene/3d/interpolated_camera.cpp
index 15ee971b7e..9723a686c5 100644
--- a/scene/3d/interpolated_camera.cpp
+++ b/scene/3d/interpolated_camera.cpp
@@ -28,10 +28,9 @@
/*************************************************************************/
#include "interpolated_camera.h"
-
void InterpolatedCamera::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (get_tree()->is_editor_hint() && enabled)
@@ -48,32 +47,30 @@ void InterpolatedCamera::_notification(int p_what) {
if (!node)
break;
- float delta = speed*get_process_delta_time();
+ float delta = speed * get_process_delta_time();
Transform target_xform = node->get_global_transform();
Transform local_transform = get_global_transform();
- local_transform = local_transform.interpolate_with(target_xform,delta);
+ local_transform = local_transform.interpolate_with(target_xform, delta);
set_global_transform(local_transform);
if (node->cast_to<Camera>()) {
Camera *cam = node->cast_to<Camera>();
- if (cam->get_projection()==get_projection()) {
+ if (cam->get_projection() == get_projection()) {
- float new_near = Math::lerp(get_znear(),cam->get_znear(),delta);
- float new_far = Math::lerp(get_zfar(),cam->get_zfar(),delta);
+ float new_near = Math::lerp(get_znear(), cam->get_znear(), delta);
+ float new_far = Math::lerp(get_zfar(), cam->get_zfar(), delta);
- if (cam->get_projection()==PROJECTION_ORTHOGONAL) {
+ if (cam->get_projection() == PROJECTION_ORTHOGONAL) {
- float size = Math::lerp(get_size(),cam->get_size(),delta);
- set_orthogonal(size,new_near,new_far);
+ float size = Math::lerp(get_size(), cam->get_size(), delta);
+ set_orthogonal(size, new_near, new_far);
} else {
- float fov = Math::lerp(get_fov(),cam->get_fov(),delta);
- set_perspective(fov,new_near,new_far);
+ float fov = Math::lerp(get_fov(), cam->get_fov(), delta);
+ set_perspective(fov, new_near, new_far);
}
}
}
-
-
}
} break;
@@ -89,25 +86,24 @@ void InterpolatedCamera::_set_target(const Object *p_target) {
void InterpolatedCamera::set_target(const Spatial *p_target) {
ERR_FAIL_NULL(p_target);
- target=get_path_to(p_target);
+ target = get_path_to(p_target);
}
+void InterpolatedCamera::set_target_path(const NodePath &p_path) {
-void InterpolatedCamera::set_target_path(const NodePath& p_path){
-
- target=p_path;
+ target = p_path;
}
-NodePath InterpolatedCamera::get_target_path() const{
+NodePath InterpolatedCamera::get_target_path() const {
return target;
}
void InterpolatedCamera::set_interpolation_enabled(bool p_enable) {
- if (enabled==p_enable)
+ if (enabled == p_enable)
return;
- enabled=p_enable;
+ enabled = p_enable;
if (p_enable) {
if (is_inside_tree() && get_tree()->is_editor_hint())
return;
@@ -123,7 +119,7 @@ bool InterpolatedCamera::is_interpolation_enabled() const {
void InterpolatedCamera::set_speed(real_t p_speed) {
- speed=p_speed;
+ speed = p_speed;
}
real_t InterpolatedCamera::get_speed() const {
@@ -131,27 +127,25 @@ real_t InterpolatedCamera::get_speed() const {
return speed;
}
-
void InterpolatedCamera::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_target_path","target_path"),&InterpolatedCamera::set_target_path);
- ClassDB::bind_method(D_METHOD("get_target_path"),&InterpolatedCamera::get_target_path);
- ClassDB::bind_method(D_METHOD("set_target","target:Camera"),&InterpolatedCamera::_set_target);
+ ClassDB::bind_method(D_METHOD("set_target_path", "target_path"), &InterpolatedCamera::set_target_path);
+ ClassDB::bind_method(D_METHOD("get_target_path"), &InterpolatedCamera::get_target_path);
+ ClassDB::bind_method(D_METHOD("set_target", "target:Camera"), &InterpolatedCamera::_set_target);
- ClassDB::bind_method(D_METHOD("set_speed","speed"),&InterpolatedCamera::set_speed);
- ClassDB::bind_method(D_METHOD("get_speed"),&InterpolatedCamera::get_speed);
+ ClassDB::bind_method(D_METHOD("set_speed", "speed"), &InterpolatedCamera::set_speed);
+ ClassDB::bind_method(D_METHOD("get_speed"), &InterpolatedCamera::get_speed);
- ClassDB::bind_method(D_METHOD("set_interpolation_enabled","target_path"),&InterpolatedCamera::set_interpolation_enabled);
- ClassDB::bind_method(D_METHOD("is_interpolation_enabled"),&InterpolatedCamera::is_interpolation_enabled);
+ ClassDB::bind_method(D_METHOD("set_interpolation_enabled", "target_path"), &InterpolatedCamera::set_interpolation_enabled);
+ ClassDB::bind_method(D_METHOD("is_interpolation_enabled"), &InterpolatedCamera::is_interpolation_enabled);
- ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"target"), "set_target_path", "get_target_path") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"speed"), "set_speed", "get_speed") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"), "set_interpolation_enabled", "is_interpolation_enabled") ;
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "target"), "set_target_path", "get_target_path");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "speed"), "set_speed", "get_speed");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_interpolation_enabled", "is_interpolation_enabled");
}
InterpolatedCamera::InterpolatedCamera() {
- enabled=false;
- speed=1;
-
+ enabled = false;
+ speed = 1;
}
diff --git a/scene/3d/interpolated_camera.h b/scene/3d/interpolated_camera.h
index c78e6935da..ebadf39946 100644
--- a/scene/3d/interpolated_camera.h
+++ b/scene/3d/interpolated_camera.h
@@ -33,21 +33,20 @@
class InterpolatedCamera : public Camera {
- GDCLASS(InterpolatedCamera,Camera);
+ GDCLASS(InterpolatedCamera, Camera);
bool enabled;
real_t speed;
NodePath target;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
void _set_target(const Object *p_target);
public:
-
void set_target(const Spatial *p_target);
- void set_target_path(const NodePath& p_path);
+ void set_target_path(const NodePath &p_path);
NodePath get_target_path() const;
void set_speed(real_t p_speed);
@@ -56,7 +55,6 @@ public:
void set_interpolation_enabled(bool p_enable);
bool is_interpolation_enabled() const;
-
InterpolatedCamera();
};
diff --git a/scene/3d/light.cpp b/scene/3d/light.cpp
index 473bca8d3b..7d01230517 100644
--- a/scene/3d/light.cpp
+++ b/scene/3d/light.cpp
@@ -28,108 +28,99 @@
/*************************************************************************/
#include "light.h"
+#include "baked_light_instance.h"
#include "global_config.h"
#include "scene/resources/surface_tool.h"
-#include "baked_light_instance.h"
-
bool Light::_can_gizmo_scale() const {
return false;
}
-
void Light::set_param(Param p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- param[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ param[p_param] = p_value;
- VS::get_singleton()->light_set_param(light,VS::LightParam(p_param),p_value);
+ VS::get_singleton()->light_set_param(light, VS::LightParam(p_param), p_value);
- if (p_param==PARAM_SPOT_ANGLE || p_param==PARAM_RANGE) {
+ if (p_param == PARAM_SPOT_ANGLE || p_param == PARAM_RANGE) {
update_gizmo();
}
-
-
}
-float Light::get_param(Param p_param) const{
+float Light::get_param(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return param[p_param];
-
}
-void Light::set_shadow(bool p_enable){
-
- shadow=p_enable;
- VS::get_singleton()->light_set_shadow(light,p_enable);
+void Light::set_shadow(bool p_enable) {
+ shadow = p_enable;
+ VS::get_singleton()->light_set_shadow(light, p_enable);
}
-bool Light::has_shadow() const{
+bool Light::has_shadow() const {
return shadow;
}
-void Light::set_negative(bool p_enable){
+void Light::set_negative(bool p_enable) {
- negative=p_enable;
- VS::get_singleton()->light_set_negative(light,p_enable);
+ negative = p_enable;
+ VS::get_singleton()->light_set_negative(light, p_enable);
}
-bool Light::is_negative() const{
+bool Light::is_negative() const {
return negative;
}
-void Light::set_cull_mask(uint32_t p_cull_mask){
-
- cull_mask=p_cull_mask;
- VS::get_singleton()->light_set_cull_mask(light,p_cull_mask);
+void Light::set_cull_mask(uint32_t p_cull_mask) {
+ cull_mask = p_cull_mask;
+ VS::get_singleton()->light_set_cull_mask(light, p_cull_mask);
}
-uint32_t Light::get_cull_mask() const{
+uint32_t Light::get_cull_mask() const {
return cull_mask;
}
-void Light::set_color(const Color& p_color){
+void Light::set_color(const Color &p_color) {
- color=p_color;
- VS::get_singleton()->light_set_color(light,p_color);
+ color = p_color;
+ VS::get_singleton()->light_set_color(light, p_color);
}
-Color Light::get_color() const{
+Color Light::get_color() const {
return color;
}
-void Light::set_shadow_color(const Color& p_shadow_color){
+void Light::set_shadow_color(const Color &p_shadow_color) {
- shadow_color=p_shadow_color;
- VS::get_singleton()->light_set_shadow_color(light,p_shadow_color);
+ shadow_color = p_shadow_color;
+ VS::get_singleton()->light_set_shadow_color(light, p_shadow_color);
}
-Color Light::get_shadow_color() const{
+Color Light::get_shadow_color() const {
return shadow_color;
}
-
Rect3 Light::get_aabb() const {
+ if (type == VisualServer::LIGHT_DIRECTIONAL) {
- if (type==VisualServer::LIGHT_DIRECTIONAL) {
-
- return Rect3( Vector3(-1,-1,-1), Vector3(2, 2, 2 ) );
+ return Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2));
- } else if (type==VisualServer::LIGHT_OMNI) {
+ } else if (type == VisualServer::LIGHT_OMNI) {
- return Rect3( Vector3(-1,-1,-1) * param[PARAM_RANGE], Vector3(2, 2, 2 ) * param[PARAM_RANGE]);
+ return Rect3(Vector3(-1, -1, -1) * param[PARAM_RANGE], Vector3(2, 2, 2) * param[PARAM_RANGE]);
- } else if (type==VisualServer::LIGHT_SPOT) {
+ } else if (type == VisualServer::LIGHT_SPOT) {
- float len=param[PARAM_RANGE];
- float size=Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE]))*len;
- return Rect3( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) );
+ float len = param[PARAM_RANGE];
+ float size = Math::tan(Math::deg2rad(param[PARAM_SPOT_ANGLE])) * len;
+ return Rect3(Vector3(-size, -size, -len), Vector3(size * 2, size * 2, len));
}
return Rect3();
@@ -140,187 +131,169 @@ PoolVector<Face3> Light::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
}
-
-
void Light::_update_visibility() {
if (!is_inside_tree())
return;
-
- bool editor_ok=true;
+ bool editor_ok = true;
#ifdef TOOLS_ENABLED
if (editor_only) {
if (!get_tree()->is_editor_hint()) {
- editor_ok=false;
+ editor_ok = false;
} else {
- editor_ok = (get_tree()->get_edited_scene_root() && (this==get_tree()->get_edited_scene_root() || get_owner()==get_tree()->get_edited_scene_root()));
+ editor_ok = (get_tree()->get_edited_scene_root() && (this == get_tree()->get_edited_scene_root() || get_owner() == get_tree()->get_edited_scene_root()));
}
}
#else
if (editor_only) {
- editor_ok=false;
+ editor_ok = false;
}
#endif
//VS::get_singleton()->instance_light_set_enabled(get_instance(),is_visible_in_tree() && editor_ok);
_change_notify("geometry/visible");
-
}
-
void Light::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
_update_visibility();
-
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
_update_visibility();
Node *node = this;
- while(node) {
+ while (node) {
- baked_light=node->cast_to<BakedLight>();
+ baked_light = node->cast_to<BakedLight>();
if (baked_light) {
baked_light->lights.insert(this);
break;
}
- node=node->get_parent();
+ node = node->get_parent();
}
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (baked_light) {
baked_light->lights.erase(this);
}
}
-
}
-
void Light::set_editor_only(bool p_editor_only) {
- editor_only=p_editor_only;
+ editor_only = p_editor_only;
_update_visibility();
}
-bool Light::is_editor_only() const{
+bool Light::is_editor_only() const {
return editor_only;
}
-
void Light::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("set_editor_only","editor_only"), &Light::set_editor_only );
- ClassDB::bind_method(D_METHOD("is_editor_only"), &Light::is_editor_only );
-
-
- ClassDB::bind_method(D_METHOD("set_param","param","value"), &Light::set_param );
- ClassDB::bind_method(D_METHOD("get_param","param"), &Light::get_param );
-
- ClassDB::bind_method(D_METHOD("set_shadow","enabled"), &Light::set_shadow );
- ClassDB::bind_method(D_METHOD("has_shadow"), &Light::has_shadow );
-
- ClassDB::bind_method(D_METHOD("set_negative","enabled"), &Light::set_negative );
- ClassDB::bind_method(D_METHOD("is_negative"), &Light::is_negative );
-
- ClassDB::bind_method(D_METHOD("set_cull_mask","cull_mask"), &Light::set_cull_mask );
- ClassDB::bind_method(D_METHOD("get_cull_mask"), &Light::get_cull_mask );
-
- ClassDB::bind_method(D_METHOD("set_color","color"), &Light::set_color );
- ClassDB::bind_method(D_METHOD("get_color"), &Light::get_color );
-
- ClassDB::bind_method(D_METHOD("set_shadow_color","shadow_color"), &Light::set_shadow_color );
- ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light::get_shadow_color );
-
- ADD_GROUP("Light","light_");
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "light_color",PROPERTY_HINT_COLOR_NO_ALPHA), "set_color", "get_color");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "light_energy",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_ENERGY);
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "light_negative"), "set_negative", "is_negative");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "light_specular",PROPERTY_HINT_RANGE,"0,1,0.01"), "set_param", "get_param", PARAM_SPECULAR);
- ADD_PROPERTY( PropertyInfo( Variant::INT, "light_cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask");
- ADD_GROUP("Shadow","shadow_");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "shadow_enabled"), "set_shadow", "has_shadow");
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "shadow_color",PROPERTY_HINT_COLOR_NO_ALPHA), "set_shadow_color", "get_shadow_color");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_bias",PROPERTY_HINT_RANGE,"-16,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_contact",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_CONTACT_SHADOW_SIZE);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "shadow_max_distance",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE);
- ADD_GROUP("Editor","");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only");
- ADD_GROUP("","");
-
- BIND_CONSTANT( PARAM_ENERGY );
- BIND_CONSTANT( PARAM_SPECULAR );
- BIND_CONSTANT( PARAM_RANGE );
- BIND_CONSTANT( PARAM_ATTENUATION );
- BIND_CONSTANT( PARAM_SPOT_ANGLE );
- BIND_CONSTANT( PARAM_SPOT_ATTENUATION );
- BIND_CONSTANT( PARAM_CONTACT_SHADOW_SIZE );
- BIND_CONSTANT( PARAM_SHADOW_MAX_DISTANCE );
- BIND_CONSTANT( PARAM_SHADOW_SPLIT_1_OFFSET );
- BIND_CONSTANT( PARAM_SHADOW_SPLIT_2_OFFSET );
- BIND_CONSTANT( PARAM_SHADOW_SPLIT_3_OFFSET );
- BIND_CONSTANT( PARAM_SHADOW_NORMAL_BIAS );
- BIND_CONSTANT( PARAM_SHADOW_BIAS );
- BIND_CONSTANT( PARAM_SHADOW_BIAS_SPLIT_SCALE );
- BIND_CONSTANT( PARAM_MAX );
-
-
+ ClassDB::bind_method(D_METHOD("set_editor_only", "editor_only"), &Light::set_editor_only);
+ ClassDB::bind_method(D_METHOD("is_editor_only"), &Light::is_editor_only);
+
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &Light::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &Light::get_param);
+
+ ClassDB::bind_method(D_METHOD("set_shadow", "enabled"), &Light::set_shadow);
+ ClassDB::bind_method(D_METHOD("has_shadow"), &Light::has_shadow);
+
+ ClassDB::bind_method(D_METHOD("set_negative", "enabled"), &Light::set_negative);
+ ClassDB::bind_method(D_METHOD("is_negative"), &Light::is_negative);
+
+ ClassDB::bind_method(D_METHOD("set_cull_mask", "cull_mask"), &Light::set_cull_mask);
+ ClassDB::bind_method(D_METHOD("get_cull_mask"), &Light::get_cull_mask);
+
+ ClassDB::bind_method(D_METHOD("set_color", "color"), &Light::set_color);
+ ClassDB::bind_method(D_METHOD("get_color"), &Light::get_color);
+
+ ClassDB::bind_method(D_METHOD("set_shadow_color", "shadow_color"), &Light::set_shadow_color);
+ ClassDB::bind_method(D_METHOD("get_shadow_color"), &Light::get_shadow_color);
+
+ ADD_GROUP("Light", "light_");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "light_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_color", "get_color");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "light_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_ENERGY);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "light_negative"), "set_negative", "is_negative");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "light_specular", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_param", "get_param", PARAM_SPECULAR);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "light_cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask");
+ ADD_GROUP("Shadow", "shadow_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "shadow_enabled"), "set_shadow", "has_shadow");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "shadow_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_shadow_color", "get_shadow_color");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_bias", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_contact", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_CONTACT_SHADOW_SIZE);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "shadow_max_distance", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_SHADOW_MAX_DISTANCE);
+ ADD_GROUP("Editor", "");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editor_only"), "set_editor_only", "is_editor_only");
+ ADD_GROUP("", "");
+
+ BIND_CONSTANT(PARAM_ENERGY);
+ BIND_CONSTANT(PARAM_SPECULAR);
+ BIND_CONSTANT(PARAM_RANGE);
+ BIND_CONSTANT(PARAM_ATTENUATION);
+ BIND_CONSTANT(PARAM_SPOT_ANGLE);
+ BIND_CONSTANT(PARAM_SPOT_ATTENUATION);
+ BIND_CONSTANT(PARAM_CONTACT_SHADOW_SIZE);
+ BIND_CONSTANT(PARAM_SHADOW_MAX_DISTANCE);
+ BIND_CONSTANT(PARAM_SHADOW_SPLIT_1_OFFSET);
+ BIND_CONSTANT(PARAM_SHADOW_SPLIT_2_OFFSET);
+ BIND_CONSTANT(PARAM_SHADOW_SPLIT_3_OFFSET);
+ BIND_CONSTANT(PARAM_SHADOW_NORMAL_BIAS);
+ BIND_CONSTANT(PARAM_SHADOW_BIAS);
+ BIND_CONSTANT(PARAM_SHADOW_BIAS_SPLIT_SCALE);
+ BIND_CONSTANT(PARAM_MAX);
}
-
Light::Light(VisualServer::LightType p_type) {
- type=p_type;
- light=VisualServer::get_singleton()->light_create(p_type);
- VS::get_singleton()->instance_set_base(get_instance(),light);
+ type = p_type;
+ light = VisualServer::get_singleton()->light_create(p_type);
+ VS::get_singleton()->instance_set_base(get_instance(), light);
- baked_light=NULL;
+ baked_light = NULL;
- editor_only=false;
- set_color(Color(1,1,1,1));
+ editor_only = false;
+ set_color(Color(1, 1, 1, 1));
set_shadow(false);
set_negative(false);
set_cull_mask(0xFFFFFFFF);
- set_param(PARAM_ENERGY,1);
- set_param(PARAM_SPECULAR,0.5);
- set_param(PARAM_RANGE,5);
- set_param(PARAM_ATTENUATION,1);
- set_param(PARAM_SPOT_ANGLE,45);
- set_param(PARAM_SPOT_ATTENUATION,1);
- set_param(PARAM_CONTACT_SHADOW_SIZE,0);
- set_param(PARAM_SHADOW_MAX_DISTANCE,0);
- set_param(PARAM_SHADOW_SPLIT_1_OFFSET,0.1);
- set_param(PARAM_SHADOW_SPLIT_2_OFFSET,0.2);
- set_param(PARAM_SHADOW_SPLIT_3_OFFSET,0.5);
- set_param(PARAM_SHADOW_NORMAL_BIAS,0.1);
- set_param(PARAM_SHADOW_BIAS,0.1);
- set_param(PARAM_SHADOW_BIAS_SPLIT_SCALE,0.1);
-
+ set_param(PARAM_ENERGY, 1);
+ set_param(PARAM_SPECULAR, 0.5);
+ set_param(PARAM_RANGE, 5);
+ set_param(PARAM_ATTENUATION, 1);
+ set_param(PARAM_SPOT_ANGLE, 45);
+ set_param(PARAM_SPOT_ATTENUATION, 1);
+ set_param(PARAM_CONTACT_SHADOW_SIZE, 0);
+ set_param(PARAM_SHADOW_MAX_DISTANCE, 0);
+ set_param(PARAM_SHADOW_SPLIT_1_OFFSET, 0.1);
+ set_param(PARAM_SHADOW_SPLIT_2_OFFSET, 0.2);
+ set_param(PARAM_SHADOW_SPLIT_3_OFFSET, 0.5);
+ set_param(PARAM_SHADOW_NORMAL_BIAS, 0.1);
+ set_param(PARAM_SHADOW_BIAS, 0.1);
+ set_param(PARAM_SHADOW_BIAS_SPLIT_SCALE, 0.1);
}
-
Light::Light() {
- type=VisualServer::LIGHT_DIRECTIONAL;
+ type = VisualServer::LIGHT_DIRECTIONAL;
ERR_PRINT("Light shouldn't be instanced dircetly, use the subtypes.");
}
-
Light::~Light() {
- VS::get_singleton()->instance_set_base(get_instance(),RID());
+ VS::get_singleton()->instance_set_base(get_instance(), RID());
if (light.is_valid())
VisualServer::get_singleton()->free(light);
@@ -329,8 +302,8 @@ Light::~Light() {
void DirectionalLight::set_shadow_mode(ShadowMode p_mode) {
- shadow_mode=p_mode;
- VS::get_singleton()->light_directional_set_shadow_mode(light,VS::LightDirectionalShadowMode(p_mode));
+ shadow_mode = p_mode;
+ VS::get_singleton()->light_directional_set_shadow_mode(light, VS::LightDirectionalShadowMode(p_mode));
}
DirectionalLight::ShadowMode DirectionalLight::get_shadow_mode() const {
@@ -340,8 +313,8 @@ DirectionalLight::ShadowMode DirectionalLight::get_shadow_mode() const {
void DirectionalLight::set_blend_splits(bool p_enable) {
- blend_splits=p_enable;
- VS::get_singleton()->light_directional_set_blend_splits(light,p_enable);
+ blend_splits = p_enable;
+ VS::get_singleton()->light_directional_set_blend_splits(light, p_enable);
}
bool DirectionalLight::is_blend_splits_enabled() const {
@@ -349,90 +322,83 @@ bool DirectionalLight::is_blend_splits_enabled() const {
return blend_splits;
}
-
void DirectionalLight::_bind_methods() {
- ClassDB::bind_method( D_METHOD("set_shadow_mode","mode"),&DirectionalLight::set_shadow_mode);
- ClassDB::bind_method( D_METHOD("get_shadow_mode"),&DirectionalLight::get_shadow_mode);
+ ClassDB::bind_method(D_METHOD("set_shadow_mode", "mode"), &DirectionalLight::set_shadow_mode);
+ ClassDB::bind_method(D_METHOD("get_shadow_mode"), &DirectionalLight::get_shadow_mode);
- ClassDB::bind_method( D_METHOD("set_blend_splits","enabled"),&DirectionalLight::set_blend_splits);
- ClassDB::bind_method( D_METHOD("is_blend_splits_enabled"),&DirectionalLight::is_blend_splits_enabled);
+ ClassDB::bind_method(D_METHOD("set_blend_splits", "enabled"), &DirectionalLight::set_blend_splits);
+ ClassDB::bind_method(D_METHOD("is_blend_splits_enabled"), &DirectionalLight::is_blend_splits_enabled);
- ADD_GROUP("Directional Shadow","directional_shadow_");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "directional_shadow_mode",PROPERTY_HINT_ENUM,"Orthogonal,PSSM 2 Splits,PSSM 4 Splits"), "set_shadow_mode", "get_shadow_mode");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_1",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_1_OFFSET);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_2",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_2_OFFSET);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_split_3",PROPERTY_HINT_RANGE,"0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_3_OFFSET);
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "directional_shadow_blend_splits"), "set_blend_splits", "is_blend_splits_enabled");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_normal_bias",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_NORMAL_BIAS);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "directional_shadow_bias_split_scale",PROPERTY_HINT_RANGE,"0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS_SPLIT_SCALE);
-
- BIND_CONSTANT( SHADOW_ORTHOGONAL );
- BIND_CONSTANT( SHADOW_PARALLEL_2_SPLITS );
- BIND_CONSTANT( SHADOW_PARALLEL_4_SPLITS );
+ ADD_GROUP("Directional Shadow", "directional_shadow_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "directional_shadow_mode", PROPERTY_HINT_ENUM, "Orthogonal,PSSM 2 Splits,PSSM 4 Splits"), "set_shadow_mode", "get_shadow_mode");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_1", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_1_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_2", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_2_OFFSET);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_split_3", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_param", "get_param", PARAM_SHADOW_SPLIT_3_OFFSET);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "directional_shadow_blend_splits"), "set_blend_splits", "is_blend_splits_enabled");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_normal_bias", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_NORMAL_BIAS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "directional_shadow_bias_split_scale", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_param", "get_param", PARAM_SHADOW_BIAS_SPLIT_SCALE);
+ BIND_CONSTANT(SHADOW_ORTHOGONAL);
+ BIND_CONSTANT(SHADOW_PARALLEL_2_SPLITS);
+ BIND_CONSTANT(SHADOW_PARALLEL_4_SPLITS);
}
-
-DirectionalLight::DirectionalLight() : Light( VisualServer::LIGHT_DIRECTIONAL ) {
+DirectionalLight::DirectionalLight()
+ : Light(VisualServer::LIGHT_DIRECTIONAL) {
set_shadow_mode(SHADOW_PARALLEL_4_SPLITS);
- blend_splits=false;
+ blend_splits = false;
}
void OmniLight::set_shadow_mode(ShadowMode p_mode) {
- shadow_mode=p_mode;
- VS::get_singleton()->light_omni_set_shadow_mode(light,VS::LightOmniShadowMode(p_mode));
+ shadow_mode = p_mode;
+ VS::get_singleton()->light_omni_set_shadow_mode(light, VS::LightOmniShadowMode(p_mode));
}
-OmniLight::ShadowMode OmniLight::get_shadow_mode() const{
+OmniLight::ShadowMode OmniLight::get_shadow_mode() const {
return shadow_mode;
}
-void OmniLight::set_shadow_detail(ShadowDetail p_detail){
+void OmniLight::set_shadow_detail(ShadowDetail p_detail) {
- shadow_detail=p_detail;
- VS::get_singleton()->light_omni_set_shadow_detail(light,VS::LightOmniShadowDetail(p_detail));
+ shadow_detail = p_detail;
+ VS::get_singleton()->light_omni_set_shadow_detail(light, VS::LightOmniShadowDetail(p_detail));
}
-OmniLight::ShadowDetail OmniLight::get_shadow_detail() const{
+OmniLight::ShadowDetail OmniLight::get_shadow_detail() const {
return shadow_detail;
}
-
-
-
void OmniLight::_bind_methods() {
- ClassDB::bind_method( D_METHOD("set_shadow_mode","mode"),&OmniLight::set_shadow_mode);
- ClassDB::bind_method( D_METHOD("get_shadow_mode"),&OmniLight::get_shadow_mode);
-
- ClassDB::bind_method( D_METHOD("set_shadow_detail","detail"),&OmniLight::set_shadow_detail);
- ClassDB::bind_method( D_METHOD("get_shadow_detail"),&OmniLight::get_shadow_detail);
+ ClassDB::bind_method(D_METHOD("set_shadow_mode", "mode"), &OmniLight::set_shadow_mode);
+ ClassDB::bind_method(D_METHOD("get_shadow_mode"), &OmniLight::get_shadow_mode);
- ADD_GROUP("Omni","omni_");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "omni_range",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_RANGE);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "omni_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION);
- ADD_PROPERTY( PropertyInfo( Variant::INT, "omni_shadow_mode",PROPERTY_HINT_ENUM,"Dual Paraboloid,Cube"), "set_shadow_mode", "get_shadow_mode");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "omni_shadow_detail",PROPERTY_HINT_ENUM,"Vertical,Horizontal"), "set_shadow_detail", "get_shadow_detail");
+ ClassDB::bind_method(D_METHOD("set_shadow_detail", "detail"), &OmniLight::set_shadow_detail);
+ ClassDB::bind_method(D_METHOD("get_shadow_detail"), &OmniLight::get_shadow_detail);
+ ADD_GROUP("Omni", "omni_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "omni_range", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_RANGE);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "omni_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "omni_shadow_mode", PROPERTY_HINT_ENUM, "Dual Paraboloid,Cube"), "set_shadow_mode", "get_shadow_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "omni_shadow_detail", PROPERTY_HINT_ENUM, "Vertical,Horizontal"), "set_shadow_detail", "get_shadow_detail");
}
-OmniLight::OmniLight() : Light( VisualServer::LIGHT_OMNI ) {
+OmniLight::OmniLight()
+ : Light(VisualServer::LIGHT_OMNI) {
set_shadow_mode(SHADOW_DUAL_PARABOLOID);
set_shadow_detail(SHADOW_DETAIL_HORIZONTAL);
-
}
void SpotLight::_bind_methods() {
- ADD_GROUP("Spot","spot_");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_range",PROPERTY_HINT_RANGE,"0,65536,0.1"), "set_param", "get_param", PARAM_RANGE);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_angle",PROPERTY_HINT_RANGE,"0,180,0.1"), "set_param", "get_param", PARAM_SPOT_ANGLE);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "spot_angle_attenuation",PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_SPOT_ATTENUATION);
-
+ ADD_GROUP("Spot", "spot_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_range", PROPERTY_HINT_RANGE, "0,65536,0.1"), "set_param", "get_param", PARAM_RANGE);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_ATTENUATION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_angle", PROPERTY_HINT_RANGE, "0,180,0.1"), "set_param", "get_param", PARAM_SPOT_ANGLE);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "spot_angle_attenuation", PROPERTY_HINT_EXP_EASING), "set_param", "get_param", PARAM_SPOT_ATTENUATION);
}
diff --git a/scene/3d/light.h b/scene/3d/light.h
index 4cf0156d5c..fd50f0fcc4 100644
--- a/scene/3d/light.h
+++ b/scene/3d/light.h
@@ -29,7 +29,6 @@
#ifndef LIGHT_H
#define LIGHT_H
-
#include "scene/3d/visual_instance.h"
#include "scene/resources/texture.h"
#include "servers/visual_server.h"
@@ -38,16 +37,14 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class BakedLight;
class Light : public VisualInstance {
- GDCLASS( Light, VisualInstance );
+ GDCLASS(Light, VisualInstance);
OBJ_CATEGORY("3D Light Nodes");
public:
-
enum Param {
PARAM_ENERGY = VS::LIGHT_PARAM_ENERGY,
PARAM_SPECULAR = VS::LIGHT_PARAM_SPECULAR,
@@ -55,7 +52,7 @@ public:
PARAM_ATTENUATION = VS::LIGHT_PARAM_ATTENUATION,
PARAM_SPOT_ANGLE = VS::LIGHT_PARAM_SPOT_ANGLE,
PARAM_SPOT_ATTENUATION = VS::LIGHT_PARAM_SPOT_ATTENUATION,
- PARAM_CONTACT_SHADOW_SIZE= VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE,
+ PARAM_CONTACT_SHADOW_SIZE = VS::LIGHT_PARAM_CONTACT_SHADOW_SIZE,
PARAM_SHADOW_MAX_DISTANCE = VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE,
PARAM_SHADOW_SPLIT_1_OFFSET = VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET,
PARAM_SHADOW_SPLIT_2_OFFSET = VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET,
@@ -67,7 +64,6 @@ public:
};
private:
-
Color color;
float param[PARAM_MAX];
Color shadow_color;
@@ -79,21 +75,19 @@ private:
void _update_visibility();
BakedLight *baked_light;
-// bind helpers
+ // bind helpers
protected:
-
RID light;
virtual bool _can_gizmo_scale() const;
-
+
static void _bind_methods();
void _notification(int p_what);
-
Light(VisualServer::LightType p_type);
-public:
+public:
VS::LightType get_light_type() const { return type; }
void set_editor_only(bool p_editor_only);
@@ -111,30 +105,26 @@ public:
void set_cull_mask(uint32_t p_cull_mask);
uint32_t get_cull_mask() const;
- void set_color(const Color& p_color);
+ void set_color(const Color &p_color);
Color get_color() const;
- void set_shadow_color(const Color& p_shadow_color);
+ void set_shadow_color(const Color &p_shadow_color);
Color get_shadow_color() const;
-
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
Light();
~Light();
-
};
VARIANT_ENUM_CAST(Light::Param);
-
class DirectionalLight : public Light {
- GDCLASS( DirectionalLight, Light );
+ GDCLASS(DirectionalLight, Light);
public:
-
enum ShadowMode {
SHADOW_ORTHOGONAL,
SHADOW_PARALLEL_2_SPLITS,
@@ -142,14 +132,13 @@ public:
};
private:
-
bool blend_splits;
ShadowMode shadow_mode;
protected:
static void _bind_methods();
-public:
+public:
void set_shadow_mode(ShadowMode p_mode);
ShadowMode get_shadow_mode() const;
@@ -163,7 +152,8 @@ VARIANT_ENUM_CAST(DirectionalLight::ShadowMode)
class OmniLight : public Light {
- GDCLASS( OmniLight, Light );
+ GDCLASS(OmniLight, Light);
+
public:
// omni light
enum ShadowMode {
@@ -178,14 +168,13 @@ public:
};
private:
-
ShadowMode shadow_mode;
ShadowDetail shadow_detail;
+
protected:
static void _bind_methods();
public:
-
void set_shadow_mode(ShadowMode p_mode);
ShadowMode get_shadow_mode() const;
@@ -200,14 +189,14 @@ VARIANT_ENUM_CAST(OmniLight::ShadowDetail)
class SpotLight : public Light {
- GDCLASS( SpotLight, Light );
+ GDCLASS(SpotLight, Light);
+
protected:
static void _bind_methods();
-public:
-
- SpotLight() : Light( VisualServer::LIGHT_SPOT ) {}
+public:
+ SpotLight()
+ : Light(VisualServer::LIGHT_SPOT) {}
};
-
#endif
diff --git a/scene/3d/listener.cpp b/scene/3d/listener.cpp
index 578044ad09..fc9326b571 100644
--- a/scene/3d/listener.cpp
+++ b/scene/3d/listener.cpp
@@ -31,8 +31,6 @@
#include "scene/resources/mesh.h"
void Listener::_update_audio_listener_state() {
-
-
}
void Listener::_request_listener_update() {
@@ -40,53 +38,48 @@ void Listener::_request_listener_update() {
_update_listener();
}
-bool Listener::_set(const StringName& p_name, const Variant& p_value) {
+bool Listener::_set(const StringName &p_name, const Variant &p_value) {
if (p_name == "current") {
if (p_value.operator bool()) {
make_current();
- }
- else {
+ } else {
clear_current();
}
- }
- else
+ } else
return false;
return true;
}
-bool Listener::_get(const StringName& p_name,Variant &r_ret) const {
+bool Listener::_get(const StringName &p_name, Variant &r_ret) const {
if (p_name == "current") {
if (is_inside_tree() && get_tree()->is_node_being_edited(this)) {
r_ret = current;
- }
- else {
+ } else {
r_ret = is_current();
}
- }
- else
+ } else
return false;
return true;
}
-void Listener::_get_property_list( List<PropertyInfo> *p_list) const {
+void Listener::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo( Variant::BOOL, "current" ) );
+ p_list->push_back(PropertyInfo(Variant::BOOL, "current"));
}
void Listener::_update_listener() {
if (is_inside_tree() && is_current()) {
get_viewport()->_listener_transform_changed_notify();
-
}
}
void Listener::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
bool first_listener = get_viewport()->_listener_add(this);
@@ -101,24 +94,19 @@ void Listener::_notification(int p_what) {
if (!get_tree()->is_node_being_edited(this)) {
if (is_current()) {
clear_current();
- current=true; //keep it true
+ current = true; //keep it true
} else {
- current=false;
+ current = false;
}
}
get_viewport()->_listener_remove(this);
-
} break;
-
-
}
-
}
-
Transform Listener::get_listener_transform() const {
return get_global_transform().orthonormalized();
@@ -126,7 +114,7 @@ Transform Listener::get_listener_transform() const {
void Listener::make_current() {
- current=true;
+ current = true;
if (!is_inside_tree())
return;
@@ -134,27 +122,23 @@ void Listener::make_current() {
get_viewport()->_listener_set(this);
}
-
-
-
void Listener::clear_current() {
- current=false;
+ current = false;
if (!is_inside_tree())
return;
- if (get_viewport()->get_listener()==this) {
+ if (get_viewport()->get_listener() == this) {
get_viewport()->_listener_set(NULL);
get_viewport()->_listener_make_next_current(this);
}
-
}
bool Listener::is_current() const {
if (is_inside_tree() && !get_tree()->is_node_being_edited(this)) {
- return get_viewport()->get_listener()==this;
+ return get_viewport()->get_listener() == this;
} else
return current;
@@ -174,23 +158,19 @@ RES Listener::_get_gizmo_geometry() const {
void Listener::_bind_methods() {
- ClassDB::bind_method( D_METHOD("make_current"),&Listener::make_current );
- ClassDB::bind_method( D_METHOD("clear_current"),&Listener::clear_current );
- ClassDB::bind_method( D_METHOD("is_current"),&Listener::is_current );
- ClassDB::bind_method( D_METHOD("get_listener_transform"),&Listener::get_listener_transform );
+ ClassDB::bind_method(D_METHOD("make_current"), &Listener::make_current);
+ ClassDB::bind_method(D_METHOD("clear_current"), &Listener::clear_current);
+ ClassDB::bind_method(D_METHOD("is_current"), &Listener::is_current);
+ ClassDB::bind_method(D_METHOD("get_listener_transform"), &Listener::get_listener_transform);
}
Listener::Listener() {
- current=false;
- force_change=false;
+ current = false;
+ force_change = false;
set_notify_transform(true);
//active=false;
}
-
Listener::~Listener() {
-
}
-
-
diff --git a/scene/3d/listener.h b/scene/3d/listener.h
index 3b6e39bec5..4fb2aea072 100644
--- a/scene/3d/listener.h
+++ b/scene/3d/listener.h
@@ -29,15 +29,14 @@
#ifndef LISTENER_H
#define LISTENER_H
-
#include "scene/3d/spatial.h"
#include "scene/main/viewport.h"
class Listener : public Spatial {
GDCLASS(Listener, Spatial);
-private:
+private:
bool force_change;
bool current;
@@ -46,22 +45,21 @@ private:
virtual bool _can_gizmo_scale() const;
virtual RES _get_gizmo_geometry() const;
-friend class Viewport;
+ friend class Viewport;
void _update_audio_listener_state();
-protected:
+protected:
void _update_listener();
virtual void _request_listener_update();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
void make_current();
void clear_current();
bool is_current() const;
@@ -75,7 +73,6 @@ public:
Listener();
~Listener();
-
};
#endif
diff --git a/scene/3d/mesh_instance.cpp b/scene/3d/mesh_instance.cpp
index e6bd69aed2..b61232dbfd 100644
--- a/scene/3d/mesh_instance.cpp
+++ b/scene/3d/mesh_instance.cpp
@@ -28,12 +28,12 @@
/*************************************************************************/
#include "mesh_instance.h"
-#include "skeleton.h"
-#include "physics_body.h"
#include "body_shape.h"
-#include "scene/scene_string_names.h"
#include "core_string_names.h"
-bool MeshInstance::_set(const StringName& p_name, const Variant& p_value) {
+#include "physics_body.h"
+#include "scene/scene_string_names.h"
+#include "skeleton.h"
+bool MeshInstance::_set(const StringName &p_name, const Variant &p_value) {
//this is not _too_ bad performance wise, really. it only arrives here if the property was not set anywhere else.
//add to it that it's probably found on first call to _set anyway.
@@ -41,97 +41,91 @@ bool MeshInstance::_set(const StringName& p_name, const Variant& p_value) {
if (!get_instance().is_valid())
return false;
-
- Map<StringName,BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
+ Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
if (E) {
- E->get().value=p_value;
- VisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(),E->get().idx,E->get().value);
+ E->get().value = p_value;
+ VisualServer::get_singleton()->instance_set_blend_shape_weight(get_instance(), E->get().idx, E->get().value);
return true;
}
if (p_name.operator String().begins_with("material/")) {
- int idx = p_name.operator String().get_slicec('/',1).to_int();
- if (idx>=materials.size() || idx<0)
+ int idx = p_name.operator String().get_slicec('/', 1).to_int();
+ if (idx >= materials.size() || idx < 0)
return false;
- set_surface_material(idx,p_value);
+ set_surface_material(idx, p_value);
return true;
}
return false;
}
-bool MeshInstance::_get(const StringName& p_name,Variant &r_ret) const {
-
+bool MeshInstance::_get(const StringName &p_name, Variant &r_ret) const {
if (!get_instance().is_valid())
return false;
- const Map<StringName,BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
+ const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.find(p_name);
if (E) {
r_ret = E->get().value;
return true;
}
if (p_name.operator String().begins_with("material/")) {
- int idx = p_name.operator String().get_slicec('/',1).to_int();
- if (idx>=materials.size() || idx<0)
+ int idx = p_name.operator String().get_slicec('/', 1).to_int();
+ if (idx >= materials.size() || idx < 0)
return false;
- r_ret=materials[idx];
+ r_ret = materials[idx];
return true;
}
return false;
}
-void MeshInstance::_get_property_list( List<PropertyInfo> *p_list) const {
+void MeshInstance::_get_property_list(List<PropertyInfo> *p_list) const {
List<String> ls;
- for(const Map<StringName,BlendShapeTrack>::Element *E=blend_shape_tracks.front();E;E=E->next()) {
+ for (const Map<StringName, BlendShapeTrack>::Element *E = blend_shape_tracks.front(); E; E = E->next()) {
ls.push_back(E->key());
}
ls.sort();
- for(List<String>::Element *E=ls.front();E;E=E->next()) {
- p_list->push_back( PropertyInfo(Variant::REAL,E->get(),PROPERTY_HINT_RANGE,"0,1,0.01"));
+ for (List<String>::Element *E = ls.front(); E; E = E->next()) {
+ p_list->push_back(PropertyInfo(Variant::REAL, E->get(), PROPERTY_HINT_RANGE, "0,1,0.01"));
}
if (mesh.is_valid()) {
- for(int i=0;i<mesh->get_surface_count();i++) {
- p_list->push_back( PropertyInfo(Variant::OBJECT, "material/"+itos(i), PROPERTY_HINT_RESOURCE_TYPE, "Material"));
+ for (int i = 0; i < mesh->get_surface_count(); i++) {
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "material/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "Material"));
}
}
}
+void MeshInstance::set_mesh(const Ref<Mesh> &p_mesh) {
-
-
-void MeshInstance::set_mesh(const Ref<Mesh>& p_mesh) {
-
- if (mesh==p_mesh)
+ if (mesh == p_mesh)
return;
if (mesh.is_valid()) {
- mesh->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_mesh_changed);
+ mesh->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);
materials.clear();
}
- mesh=p_mesh;
+ mesh = p_mesh;
blend_shape_tracks.clear();
if (mesh.is_valid()) {
-
- for(int i=0;i<mesh->get_blend_shape_count();i++) {
+ for (int i = 0; i < mesh->get_blend_shape_count(); i++) {
BlendShapeTrack mt;
- mt.idx=i;
- mt.value=0;
- blend_shape_tracks["blend_shapes/"+String(mesh->get_blend_shape_name(i))]=mt;
+ mt.idx = i;
+ mt.value = 0;
+ blend_shape_tracks["blend_shapes/" + String(mesh->get_blend_shape_name(i))] = mt;
}
- mesh->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_mesh_changed);
+ mesh->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_mesh_changed);
materials.resize(mesh->get_surface_count());
set_base(mesh->get_rid());
@@ -147,14 +141,14 @@ Ref<Mesh> MeshInstance::get_mesh() const {
return mesh;
}
-void MeshInstance::_resolve_skeleton_path(){
+void MeshInstance::_resolve_skeleton_path() {
if (skeleton_path.is_empty())
return;
- Skeleton *skeleton=get_node(skeleton_path)?get_node(skeleton_path)->cast_to<Skeleton>():NULL;
+ Skeleton *skeleton = get_node(skeleton_path) ? get_node(skeleton_path)->cast_to<Skeleton>() : NULL;
if (skeleton)
- VisualServer::get_singleton()->instance_attach_skeleton( get_instance(), skeleton->get_skeleton() );
+ VisualServer::get_singleton()->instance_attach_skeleton(get_instance(), skeleton->get_skeleton());
}
void MeshInstance::set_skeleton_path(const NodePath &p_skeleton) {
@@ -179,7 +173,7 @@ Rect3 MeshInstance::get_aabb() const {
PoolVector<Face3> MeshInstance::get_faces(uint32_t p_usage_flags) const {
- if (!(p_usage_flags&(FACES_SOLID|FACES_ENCLOSING)))
+ if (!(p_usage_flags & (FACES_SOLID | FACES_ENCLOSING)))
return PoolVector<Face3>();
if (mesh.is_null())
@@ -188,8 +182,7 @@ PoolVector<Face3> MeshInstance::get_faces(uint32_t p_usage_flags) const {
return mesh->get_faces();
}
-
-Node* MeshInstance::create_trimesh_collision_node() {
+Node *MeshInstance::create_trimesh_collision_node() {
if (mesh.is_null())
return NULL;
@@ -198,32 +191,28 @@ Node* MeshInstance::create_trimesh_collision_node() {
if (shape.is_null())
return NULL;
- StaticBody * static_body = memnew( StaticBody );
- static_body->add_shape( shape );
+ StaticBody *static_body = memnew(StaticBody);
+ static_body->add_shape(shape);
return static_body;
-
-
}
void MeshInstance::create_trimesh_collision() {
-
- StaticBody* static_body = create_trimesh_collision_node()->cast_to<StaticBody>();
+ StaticBody *static_body = create_trimesh_collision_node()->cast_to<StaticBody>();
ERR_FAIL_COND(!static_body);
- static_body->set_name( String(get_name()) + "_col" );
+ static_body->set_name(String(get_name()) + "_col");
add_child(static_body);
if (get_owner())
- static_body->set_owner( get_owner() );
- CollisionShape *cshape = memnew( CollisionShape );
+ static_body->set_owner(get_owner());
+ CollisionShape *cshape = memnew(CollisionShape);
cshape->set_shape(static_body->get_shape(0));
static_body->add_child(cshape);
if (get_owner())
- cshape->set_owner( get_owner() );
-
+ cshape->set_owner(get_owner());
}
-Node* MeshInstance::create_convex_collision_node() {
+Node *MeshInstance::create_convex_collision_node() {
if (mesh.is_null())
return NULL;
@@ -232,91 +221,78 @@ Node* MeshInstance::create_convex_collision_node() {
if (shape.is_null())
return NULL;
- StaticBody * static_body = memnew( StaticBody );
- static_body->add_shape( shape );
+ StaticBody *static_body = memnew(StaticBody);
+ static_body->add_shape(shape);
return static_body;
-
-
}
void MeshInstance::create_convex_collision() {
-
- StaticBody* static_body = create_convex_collision_node()->cast_to<StaticBody>();
+ StaticBody *static_body = create_convex_collision_node()->cast_to<StaticBody>();
ERR_FAIL_COND(!static_body);
- static_body->set_name( String(get_name()) + "_col" );
+ static_body->set_name(String(get_name()) + "_col");
add_child(static_body);
if (get_owner())
- static_body->set_owner( get_owner() );
- CollisionShape *cshape = memnew( CollisionShape );
+ static_body->set_owner(get_owner());
+ CollisionShape *cshape = memnew(CollisionShape);
cshape->set_shape(static_body->get_shape(0));
static_body->add_child(cshape);
if (get_owner())
- cshape->set_owner( get_owner() );
-
-
+ cshape->set_owner(get_owner());
}
void MeshInstance::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
_resolve_skeleton_path();
}
}
+void MeshInstance::set_surface_material(int p_surface, const Ref<Material> &p_material) {
-void MeshInstance::set_surface_material(int p_surface,const Ref<Material>& p_material) {
+ ERR_FAIL_INDEX(p_surface, materials.size());
- ERR_FAIL_INDEX(p_surface,materials.size());
-
- materials[p_surface]=p_material;
+ materials[p_surface] = p_material;
if (materials[p_surface].is_valid())
- VS::get_singleton()->instance_set_surface_material(get_instance(),p_surface,materials[p_surface]->get_rid());
+ VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, materials[p_surface]->get_rid());
else
- VS::get_singleton()->instance_set_surface_material(get_instance(),p_surface,RID());
-
+ VS::get_singleton()->instance_set_surface_material(get_instance(), p_surface, RID());
}
Ref<Material> MeshInstance::get_surface_material(int p_surface) const {
- ERR_FAIL_INDEX_V(p_surface,materials.size(),Ref<Material>());
+ ERR_FAIL_INDEX_V(p_surface, materials.size(), Ref<Material>());
return materials[p_surface];
}
-
void MeshInstance::_mesh_changed() {
- materials.resize( mesh->get_surface_count() );
+ materials.resize(mesh->get_surface_count());
}
void MeshInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mesh","mesh:Mesh"),&MeshInstance::set_mesh);
- ClassDB::bind_method(D_METHOD("get_mesh:Mesh"),&MeshInstance::get_mesh);
- ClassDB::bind_method(D_METHOD("set_skeleton_path","skeleton_path:NodePath"),&MeshInstance::set_skeleton_path);
- ClassDB::bind_method(D_METHOD("get_skeleton_path:NodePath"),&MeshInstance::get_skeleton_path);
+ ClassDB::bind_method(D_METHOD("set_mesh", "mesh:Mesh"), &MeshInstance::set_mesh);
+ ClassDB::bind_method(D_METHOD("get_mesh:Mesh"), &MeshInstance::get_mesh);
+ ClassDB::bind_method(D_METHOD("set_skeleton_path", "skeleton_path:NodePath"), &MeshInstance::set_skeleton_path);
+ ClassDB::bind_method(D_METHOD("get_skeleton_path:NodePath"), &MeshInstance::get_skeleton_path);
- ClassDB::bind_method(D_METHOD("create_trimesh_collision"),&MeshInstance::create_trimesh_collision);
- ClassDB::set_method_flags("MeshInstance","create_trimesh_collision",METHOD_FLAGS_DEFAULT);
- ClassDB::bind_method(D_METHOD("create_convex_collision"),&MeshInstance::create_convex_collision);
- ClassDB::set_method_flags("MeshInstance","create_convex_collision",METHOD_FLAGS_DEFAULT);
- ClassDB::bind_method(D_METHOD("_mesh_changed"),&MeshInstance::_mesh_changed);
+ ClassDB::bind_method(D_METHOD("create_trimesh_collision"), &MeshInstance::create_trimesh_collision);
+ ClassDB::set_method_flags("MeshInstance", "create_trimesh_collision", METHOD_FLAGS_DEFAULT);
+ ClassDB::bind_method(D_METHOD("create_convex_collision"), &MeshInstance::create_convex_collision);
+ ClassDB::set_method_flags("MeshInstance", "create_convex_collision", METHOD_FLAGS_DEFAULT);
+ ClassDB::bind_method(D_METHOD("_mesh_changed"), &MeshInstance::_mesh_changed);
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh" ), "set_mesh", "get_mesh");
- ADD_PROPERTY( PropertyInfo (Variant::NODE_PATH, "skeleton"), "set_skeleton_path", "get_skeleton_path");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "skeleton"), "set_skeleton_path", "get_skeleton_path");
}
-MeshInstance::MeshInstance()
-{
- skeleton_path=NodePath("..");
+MeshInstance::MeshInstance() {
+ skeleton_path = NodePath("..");
}
-
MeshInstance::~MeshInstance() {
-
}
-
-
diff --git a/scene/3d/mesh_instance.h b/scene/3d/mesh_instance.h
index 2d1af46980..543f407ca1 100644
--- a/scene/3d/mesh_instance.h
+++ b/scene/3d/mesh_instance.h
@@ -37,7 +37,7 @@
*/
class MeshInstance : public GeometryInstance {
- GDCLASS( MeshInstance, GeometryInstance );
+ GDCLASS(MeshInstance, GeometryInstance);
Ref<Mesh> mesh;
NodePath skeleton_path;
@@ -46,38 +46,40 @@ class MeshInstance : public GeometryInstance {
int idx;
float value;
- BlendShapeTrack() { idx=0; value=0; }
+ BlendShapeTrack() {
+ idx = 0;
+ value = 0;
+ }
};
- Map<StringName,BlendShapeTrack> blend_shape_tracks;
+ Map<StringName, BlendShapeTrack> blend_shape_tracks;
Vector<Ref<Material> > materials;
void _mesh_changed();
void _resolve_skeleton_path();
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_mesh(const Ref<Mesh>& p_mesh);
+public:
+ void set_mesh(const Ref<Mesh> &p_mesh);
Ref<Mesh> get_mesh() const;
- void set_skeleton_path(const NodePath& p_skeleton);
+ void set_skeleton_path(const NodePath &p_skeleton);
NodePath get_skeleton_path();
- void set_surface_material(int p_surface,const Ref<Material>& p_material);
+ void set_surface_material(int p_surface, const Ref<Material> &p_material);
Ref<Material> get_surface_material(int p_surface) const;
- Node* create_trimesh_collision_node();
+ Node *create_trimesh_collision_node();
void create_trimesh_collision();
- Node* create_convex_collision_node();
+ Node *create_convex_collision_node();
void create_convex_collision();
virtual Rect3 get_aabb() const;
diff --git a/scene/3d/multimesh_instance.cpp b/scene/3d/multimesh_instance.cpp
index e1acdfca53..18a747a5b9 100644
--- a/scene/3d/multimesh_instance.cpp
+++ b/scene/3d/multimesh_instance.cpp
@@ -28,27 +28,20 @@
/*************************************************************************/
#include "multimesh_instance.h"
-
-
-
-
void MultiMeshInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_multimesh","multimesh"),&MultiMeshInstance::set_multimesh);
- ClassDB::bind_method(D_METHOD("get_multimesh"),&MultiMeshInstance::get_multimesh);
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"multimesh",PROPERTY_HINT_RESOURCE_TYPE,"MultiMesh"), "set_multimesh", "get_multimesh");
-
-
+ ClassDB::bind_method(D_METHOD("set_multimesh", "multimesh"), &MultiMeshInstance::set_multimesh);
+ ClassDB::bind_method(D_METHOD("get_multimesh"), &MultiMeshInstance::get_multimesh);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multimesh", PROPERTY_HINT_RESOURCE_TYPE, "MultiMesh"), "set_multimesh", "get_multimesh");
}
-void MultiMeshInstance::set_multimesh(const Ref<MultiMesh>& p_multimesh) {
+void MultiMeshInstance::set_multimesh(const Ref<MultiMesh> &p_multimesh) {
- multimesh=p_multimesh;
+ multimesh = p_multimesh;
if (multimesh.is_valid())
set_base(multimesh->get_rid());
else
set_base(RID());
-
}
Ref<MultiMesh> MultiMeshInstance::get_multimesh() const {
@@ -56,8 +49,6 @@ Ref<MultiMesh> MultiMeshInstance::get_multimesh() const {
return multimesh;
}
-
-
PoolVector<Face3> MultiMeshInstance::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
@@ -72,10 +63,7 @@ Rect3 MultiMeshInstance::get_aabb() const {
}
MultiMeshInstance::MultiMeshInstance() {
-
}
MultiMeshInstance::~MultiMeshInstance() {
-
-
}
diff --git a/scene/3d/multimesh_instance.h b/scene/3d/multimesh_instance.h
index 535e4275a3..4a0edb563c 100644
--- a/scene/3d/multimesh_instance.h
+++ b/scene/3d/multimesh_instance.h
@@ -37,21 +37,18 @@
*/
class MultiMeshInstance : public GeometryInstance {
- GDCLASS( MultiMeshInstance, GeometryInstance );
-
+ GDCLASS(MultiMeshInstance, GeometryInstance);
Ref<MultiMesh> multimesh;
-protected:
-
+protected:
static void _bind_methods();
// bind helpers
public:
-
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
- void set_multimesh(const Ref<MultiMesh>& p_multimesh);
+ void set_multimesh(const Ref<MultiMesh> &p_multimesh);
Ref<MultiMesh> get_multimesh() const;
virtual Rect3 get_aabb() const;
@@ -61,4 +58,3 @@ public:
};
#endif // MULTIMESH_INSTANCE_H
-
diff --git a/scene/3d/navigation.cpp b/scene/3d/navigation.cpp
index 5c8fe6bb67..093d217cb0 100644
--- a/scene/3d/navigation.cpp
+++ b/scene/3d/navigation.cpp
@@ -31,60 +31,58 @@
void Navigation::_navmesh_link(int p_id) {
ERR_FAIL_COND(!navmesh_map.has(p_id));
- NavMesh &nm=navmesh_map[p_id];
+ NavMesh &nm = navmesh_map[p_id];
ERR_FAIL_COND(nm.linked);
print_line("LINK");
- PoolVector<Vector3> vertices=nm.navmesh->get_vertices();
+ PoolVector<Vector3> vertices = nm.navmesh->get_vertices();
int len = vertices.size();
- if (len==0)
+ if (len == 0)
return;
- PoolVector<Vector3>::Read r=vertices.read();
+ PoolVector<Vector3>::Read r = vertices.read();
- for(int i=0;i<nm.navmesh->get_polygon_count();i++) {
+ for (int i = 0; i < nm.navmesh->get_polygon_count(); i++) {
//build
- List<Polygon>::Element *P=nm.polygons.push_back(Polygon());
- Polygon &p=P->get();
- p.owner=&nm;
+ List<Polygon>::Element *P = nm.polygons.push_back(Polygon());
+ Polygon &p = P->get();
+ p.owner = &nm;
Vector<int> poly = nm.navmesh->get_polygon(i);
- int plen=poly.size();
- const int *indices=poly.ptr();
- bool valid=true;
+ int plen = poly.size();
+ const int *indices = poly.ptr();
+ bool valid = true;
p.edges.resize(plen);
Vector3 center;
- float sum=0;
+ float sum = 0;
- for(int j=0;j<plen;j++) {
+ for (int j = 0; j < plen; j++) {
int idx = indices[j];
- if (idx<0 || idx>=len) {
- valid=false;
+ if (idx < 0 || idx >= len) {
+ valid = false;
break;
}
Polygon::Edge e;
- Vector3 ep=nm.xform.xform(r[idx]);
- center+=ep;
- e.point=_get_point(ep);
- p.edges[j]=e;
+ Vector3 ep = nm.xform.xform(r[idx]);
+ center += ep;
+ e.point = _get_point(ep);
+ p.edges[j] = e;
- if (j>=2) {
- Vector3 epa = nm.xform.xform(r[indices[j-2]]);
- Vector3 epb = nm.xform.xform(r[indices[j-1]]);
-
- sum+=up.dot((epb-epa).cross(ep-epa));
+ if (j >= 2) {
+ Vector3 epa = nm.xform.xform(r[indices[j - 2]]);
+ Vector3 epb = nm.xform.xform(r[indices[j - 1]]);
+ sum += up.dot((epb - epa).cross(ep - epa));
}
-
}
- p.clockwise=sum>0;
+ p.clockwise = sum > 0;
if (!valid) {
nm.polygons.pop_back();
@@ -93,110 +91,106 @@ void Navigation::_navmesh_link(int p_id) {
}
p.center = center;
- if( plen != 0 ) {
+ if (plen != 0) {
p.center /= plen;
}
-
//connect
- for(int j=0;j<plen;j++) {
+ for (int j = 0; j < plen; j++) {
- int next = (j+1)%plen;
- EdgeKey ek(p.edges[j].point,p.edges[next].point);
+ int next = (j + 1) % plen;
+ EdgeKey ek(p.edges[j].point, p.edges[next].point);
- Map<EdgeKey,Connection>::Element *C=connections.find(ek);
+ Map<EdgeKey, Connection>::Element *C = connections.find(ek);
if (!C) {
Connection c;
- c.A=&p;
- c.A_edge=j;
- c.B=NULL;
- c.B_edge=-1;
- connections[ek]=c;
+ c.A = &p;
+ c.A_edge = j;
+ c.B = NULL;
+ c.B_edge = -1;
+ connections[ek] = c;
} else {
- if (C->get().B!=NULL) {
+ if (C->get().B != NULL) {
ConnectionPending pending;
- pending.polygon=&p;
- pending.edge=j;
- p.edges[j].P=C->get().pending.push_back(pending);
+ pending.polygon = &p;
+ pending.edge = j;
+ p.edges[j].P = C->get().pending.push_back(pending);
continue;
//print_line(String()+_get_vertex(ek.a)+" -> "+_get_vertex(ek.b));
}
//ERR_CONTINUE(C->get().B!=NULL); //wut
- C->get().B=&p;
- C->get().B_edge=j;
- C->get().A->edges[C->get().A_edge].C=&p;
- C->get().A->edges[C->get().A_edge].C_edge=j;
- p.edges[j].C=C->get().A;
- p.edges[j].C_edge=C->get().A_edge;
+ C->get().B = &p;
+ C->get().B_edge = j;
+ C->get().A->edges[C->get().A_edge].C = &p;
+ C->get().A->edges[C->get().A_edge].C_edge = j;
+ p.edges[j].C = C->get().A;
+ p.edges[j].C_edge = C->get().A_edge;
//connection successful.
}
}
}
- nm.linked=true;
-
+ nm.linked = true;
}
-
void Navigation::_navmesh_unlink(int p_id) {
ERR_FAIL_COND(!navmesh_map.has(p_id));
- NavMesh &nm=navmesh_map[p_id];
+ NavMesh &nm = navmesh_map[p_id];
ERR_FAIL_COND(!nm.linked);
print_line("UNLINK");
- for (List<Polygon>::Element *E=nm.polygons.front();E;E=E->next()) {
-
+ for (List<Polygon>::Element *E = nm.polygons.front(); E; E = E->next()) {
- Polygon &p=E->get();
+ Polygon &p = E->get();
int ec = p.edges.size();
- Polygon::Edge *edges=p.edges.ptr();
+ Polygon::Edge *edges = p.edges.ptr();
- for(int i=0;i<ec;i++) {
- int next = (i+1)%ec;
+ for (int i = 0; i < ec; i++) {
+ int next = (i + 1) % ec;
- EdgeKey ek(edges[i].point,edges[next].point);
- Map<EdgeKey,Connection>::Element *C=connections.find(ek);
+ EdgeKey ek(edges[i].point, edges[next].point);
+ Map<EdgeKey, Connection>::Element *C = connections.find(ek);
ERR_CONTINUE(!C);
if (edges[i].P) {
C->get().pending.erase(edges[i].P);
- edges[i].P=NULL;
+ edges[i].P = NULL;
} else if (C->get().B) {
//disconnect
- C->get().B->edges[C->get().B_edge].C=NULL;
- C->get().B->edges[C->get().B_edge].C_edge=-1;
- C->get().A->edges[C->get().A_edge].C=NULL;
- C->get().A->edges[C->get().A_edge].C_edge=-1;
+ C->get().B->edges[C->get().B_edge].C = NULL;
+ C->get().B->edges[C->get().B_edge].C_edge = -1;
+ C->get().A->edges[C->get().A_edge].C = NULL;
+ C->get().A->edges[C->get().A_edge].C_edge = -1;
- if (C->get().A==&E->get()) {
+ if (C->get().A == &E->get()) {
- C->get().A=C->get().B;
- C->get().A_edge=C->get().B_edge;
+ C->get().A = C->get().B;
+ C->get().A_edge = C->get().B_edge;
}
- C->get().B=NULL;
- C->get().B_edge=-1;
+ C->get().B = NULL;
+ C->get().B_edge = -1;
if (C->get().pending.size()) {
//reconnect if something is pending
ConnectionPending cp = C->get().pending.front()->get();
C->get().pending.pop_front();
- C->get().B=cp.polygon;
- C->get().B_edge=cp.edge;
- C->get().A->edges[C->get().A_edge].C=cp.polygon;
- C->get().A->edges[C->get().A_edge].C_edge=cp.edge;
- cp.polygon->edges[cp.edge].C=C->get().A;
- cp.polygon->edges[cp.edge].C_edge=C->get().A_edge;
- cp.polygon->edges[cp.edge].P=NULL;
+ C->get().B = cp.polygon;
+ C->get().B_edge = cp.edge;
+ C->get().A->edges[C->get().A_edge].C = cp.polygon;
+ C->get().A->edges[C->get().A_edge].C_edge = cp.edge;
+ cp.polygon->edges[cp.edge].C = C->get().A;
+ cp.polygon->edges[cp.edge].C_edge = C->get().A_edge;
+ cp.polygon->edges[cp.edge].P = NULL;
}
} else {
@@ -208,76 +202,68 @@ void Navigation::_navmesh_unlink(int p_id) {
nm.polygons.clear();
- nm.linked=false;
-
-
+ nm.linked = false;
}
-
-int Navigation::navmesh_create(const Ref<NavigationMesh>& p_mesh, const Transform& p_xform, Object *p_owner) {
+int Navigation::navmesh_create(const Ref<NavigationMesh> &p_mesh, const Transform &p_xform, Object *p_owner) {
int id = last_id++;
NavMesh nm;
- nm.linked=false;
- nm.navmesh=p_mesh;
- nm.xform=p_xform;
- nm.owner=p_owner;
- navmesh_map[id]=nm;
+ nm.linked = false;
+ nm.navmesh = p_mesh;
+ nm.xform = p_xform;
+ nm.owner = p_owner;
+ navmesh_map[id] = nm;
_navmesh_link(id);
return id;
}
-void Navigation::navmesh_set_transform(int p_id, const Transform& p_xform){
+void Navigation::navmesh_set_transform(int p_id, const Transform &p_xform) {
ERR_FAIL_COND(!navmesh_map.has(p_id));
- NavMesh &nm=navmesh_map[p_id];
- if (nm.xform==p_xform)
+ NavMesh &nm = navmesh_map[p_id];
+ if (nm.xform == p_xform)
return; //bleh
_navmesh_unlink(p_id);
- nm.xform=p_xform;
+ nm.xform = p_xform;
_navmesh_link(p_id);
-
-
-
}
-void Navigation::navmesh_remove(int p_id){
+void Navigation::navmesh_remove(int p_id) {
ERR_FAIL_COND(!navmesh_map.has(p_id));
_navmesh_unlink(p_id);
navmesh_map.erase(p_id);
-
}
-void Navigation::_clip_path(Vector<Vector3>& path, Polygon *from_poly, const Vector3& p_to_point, Polygon* p_to_poly) {
+void Navigation::_clip_path(Vector<Vector3> &path, Polygon *from_poly, const Vector3 &p_to_point, Polygon *p_to_poly) {
- Vector3 from = path[path.size()-1];
+ 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())
+ cut_plane.normal = (from - p_to_point).cross(up);
+ if (cut_plane.normal == Vector3())
return;
cut_plane.normal.normalize();
cut_plane.d = cut_plane.normal.dot(from);
-
- while(from_poly!=p_to_poly) {
+ while (from_poly != p_to_poly) {
int pe = from_poly->prev_edge;
Vector3 a = _get_vertex(from_poly->edges[pe].point);
- Vector3 b = _get_vertex(from_poly->edges[(pe+1)%from_poly->edges.size()].point);
+ Vector3 b = _get_vertex(from_poly->edges[(pe + 1) % from_poly->edges.size()].point);
- from_poly=from_poly->edges[pe].C;
+ from_poly = from_poly->edges[pe].C;
ERR_FAIL_COND(!from_poly);
- if (a.distance_to(b)>CMP_EPSILON) {
+ 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) {
+ 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) {
path.push_back(inters);
}
}
@@ -285,149 +271,138 @@ void Navigation::_clip_path(Vector<Vector3>& path, Polygon *from_poly, const Vec
}
}
-Vector<Vector3> Navigation::get_simple_path(const Vector3& p_start, const Vector3& p_end, bool p_optimize) {
+Vector<Vector3> Navigation::get_simple_path(const Vector3 &p_start, const Vector3 &p_end, bool p_optimize) {
-
- Polygon *begin_poly=NULL;
- Polygon *end_poly=NULL;
+ Polygon *begin_poly = NULL;
+ Polygon *end_poly = NULL;
Vector3 begin_point;
Vector3 end_point;
- float begin_d=1e20;
- float end_d=1e20;
-
+ float begin_d = 1e20;
+ float end_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navmesh_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navmesh_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point));
+ Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point));
Vector3 spoint = f.get_closest_point_to(p_start);
float dpoint = spoint.distance_to(p_start);
- if (dpoint<begin_d) {
- begin_d=dpoint;
- begin_poly=&p;
- begin_point=spoint;
+ if (dpoint < begin_d) {
+ begin_d = dpoint;
+ begin_poly = &p;
+ begin_point = spoint;
}
spoint = f.get_closest_point_to(p_end);
dpoint = spoint.distance_to(p_end);
- if (dpoint<end_d) {
- end_d=dpoint;
- end_poly=&p;
- end_point=spoint;
+ if (dpoint < end_d) {
+ end_d = dpoint;
+ end_poly = &p;
+ end_point = spoint;
}
}
- p.prev_edge=-1;
+ p.prev_edge = -1;
}
}
-
if (!begin_poly || !end_poly) {
//print_line("No Path Path");
return Vector<Vector3>(); //no path
}
-
- if (begin_poly==end_poly) {
+ if (begin_poly == end_poly) {
Vector<Vector3> path;
path.resize(2);
- path[0]=begin_point;
- path[1]=end_point;
+ path[0] = begin_point;
+ path[1] = end_point;
//print_line("Direct Path");
return path;
}
+ bool found_route = false;
- bool found_route=false;
-
- List<Polygon*> open_list;
+ List<Polygon *> open_list;
- for(int i=0;i<begin_poly->edges.size();i++) {
+ for (int i = 0; i < begin_poly->edges.size(); i++) {
if (begin_poly->edges[i].C) {
- begin_poly->edges[i].C->prev_edge=begin_poly->edges[i].C_edge;
- begin_poly->edges[i].C->distance=begin_poly->center.distance_to(begin_poly->edges[i].C->center);
+ begin_poly->edges[i].C->prev_edge = begin_poly->edges[i].C_edge;
+ begin_poly->edges[i].C->distance = begin_poly->center.distance_to(begin_poly->edges[i].C->center);
open_list.push_back(begin_poly->edges[i].C);
- if (begin_poly->edges[i].C==end_poly) {
- found_route=true;
+ if (begin_poly->edges[i].C == end_poly) {
+ found_route = true;
}
}
}
+ while (!found_route) {
- while(!found_route) {
-
- if (open_list.size()==0) {
+ if (open_list.size() == 0) {
//print_line("NOU OPEN LIST");
break;
}
//check open list
- List<Polygon*>::Element *least_cost_poly=NULL;
- float least_cost=1e30;
+ List<Polygon *>::Element *least_cost_poly = NULL;
+ float least_cost = 1e30;
//this could be faster (cache previous results)
- for (List<Polygon*>::Element *E=open_list.front();E;E=E->next()) {
-
- Polygon *p=E->get();
+ for (List<Polygon *>::Element *E = open_list.front(); E; E = E->next()) {
+ Polygon *p = E->get();
- float cost=p->distance;
- cost+=p->center.distance_to(end_point);
+ float cost = p->distance;
+ cost += p->center.distance_to(end_point);
- if (cost<least_cost) {
+ if (cost < least_cost) {
- least_cost_poly=E;
- least_cost=cost;
+ least_cost_poly = E;
+ least_cost = cost;
}
}
-
- Polygon *p=least_cost_poly->get();
+ Polygon *p = least_cost_poly->get();
//open the neighbours for search
- for(int i=0;i<p->edges.size();i++) {
-
+ for (int i = 0; i < p->edges.size(); i++) {
- Polygon::Edge &e=p->edges[i];
+ Polygon::Edge &e = p->edges[i];
if (!e.C)
continue;
float distance = p->center.distance_to(e.C->center) + p->distance;
- if (e.C->prev_edge!=-1) {
+ if (e.C->prev_edge != -1) {
//oh this was visited already, can we win the cost?
- if (e.C->distance>distance) {
+ if (e.C->distance > distance) {
- e.C->prev_edge=e.C_edge;
- e.C->distance=distance;
+ e.C->prev_edge = e.C_edge;
+ e.C->distance = distance;
}
} else {
//add to open neighbours
- e.C->prev_edge=e.C_edge;
- e.C->distance=distance;
+ e.C->prev_edge = e.C_edge;
+ e.C->distance = distance;
open_list.push_back(e.C);
- if (e.C==end_poly) {
+ if (e.C == end_poly) {
//oh my reached end! stop algorithm
- found_route=true;
+ found_route = true;
break;
-
}
-
}
}
@@ -444,174 +419,164 @@ Vector<Vector3> Navigation::get_simple_path(const Vector3& p_start, const Vector
if (p_optimize) {
//string pulling
- Polygon *apex_poly=end_poly;
- Vector3 apex_point=end_point;
- Vector3 portal_left=apex_point;
- Vector3 portal_right=apex_point;
- Polygon *left_poly=end_poly;
- Polygon *right_poly=end_poly;
- Polygon *p=end_poly;
+ Polygon *apex_poly = end_poly;
+ Vector3 apex_point = end_point;
+ Vector3 portal_left = apex_point;
+ Vector3 portal_right = apex_point;
+ Polygon *left_poly = end_poly;
+ Polygon *right_poly = end_poly;
+ Polygon *p = end_poly;
path.push_back(end_point);
- while(p) {
+ while (p) {
Vector3 left;
Vector3 right;
-#define CLOCK_TANGENT(m_a,m_b,m_c) ( ((m_a)-(m_c)).cross((m_a)-(m_b)) )
+#define CLOCK_TANGENT(m_a, m_b, m_c) (((m_a) - (m_c)).cross((m_a) - (m_b)))
- if (p==begin_poly) {
- left=begin_point;
- right=begin_point;
+ if (p == begin_poly) {
+ left = begin_point;
+ right = begin_point;
} else {
int prev = p->prev_edge;
- int prev_n = (p->prev_edge+1)%p->edges.size();
+ int prev_n = (p->prev_edge + 1) % p->edges.size();
left = _get_vertex(p->edges[prev].point);
right = _get_vertex(p->edges[prev_n].point);
//if (CLOCK_TANGENT(apex_point,left,(left+right)*0.5).dot(up) < 0){
if (p->clockwise) {
- SWAP(left,right);
+ SWAP(left, right);
}
}
- bool skip=false;
-
+ bool skip = false;
- if (CLOCK_TANGENT(apex_point,portal_left,left).dot(up) >= 0){
+ if (CLOCK_TANGENT(apex_point, portal_left, left).dot(up) >= 0) {
//process
- if (portal_left==apex_point || CLOCK_TANGENT(apex_point,left,portal_right).dot(up) > 0) {
- left_poly=p;
- portal_left=left;
+ if (portal_left == apex_point || CLOCK_TANGENT(apex_point, left, portal_right).dot(up) > 0) {
+ left_poly = p;
+ portal_left = left;
} else {
- _clip_path(path,apex_poly,portal_right,right_poly);
+ _clip_path(path, apex_poly, portal_right, right_poly);
- apex_point=portal_right;
- p=right_poly;
- left_poly=p;
- apex_poly=p;
- portal_left=apex_point;
- portal_right=apex_point;
+ apex_point = portal_right;
+ p = right_poly;
+ left_poly = p;
+ apex_poly = p;
+ portal_left = apex_point;
+ portal_right = apex_point;
path.push_back(apex_point);
- skip=true;
+ skip = true;
}
}
- if (!skip && CLOCK_TANGENT(apex_point,portal_right,right).dot(up) <= 0){
+ if (!skip && CLOCK_TANGENT(apex_point, portal_right, right).dot(up) <= 0) {
//process
- if (portal_right==apex_point || CLOCK_TANGENT(apex_point,right,portal_left).dot(up) < 0) {
- right_poly=p;
- portal_right=right;
+ if (portal_right == apex_point || CLOCK_TANGENT(apex_point, right, portal_left).dot(up) < 0) {
+ right_poly = p;
+ portal_right = right;
} else {
- _clip_path(path,apex_poly,portal_left,left_poly);
+ _clip_path(path, apex_poly, portal_left, left_poly);
- apex_point=portal_left;
- p=left_poly;
- right_poly=p;
- apex_poly=p;
- portal_right=apex_point;
- portal_left=apex_point;
+ apex_point = portal_left;
+ p = left_poly;
+ right_poly = p;
+ apex_poly = p;
+ portal_right = apex_point;
+ portal_left = apex_point;
path.push_back(apex_point);
}
}
- if (p!=begin_poly)
- p=p->edges[p->prev_edge].C;
+ if (p != begin_poly)
+ p = p->edges[p->prev_edge].C;
else
- p=NULL;
-
+ p = NULL;
}
- if (path[path.size()-1]!=begin_point)
+ if (path[path.size() - 1] != begin_point)
path.push_back(begin_point);
path.invert();
-
-
-
} else {
//midpoints
- Polygon *p=end_poly;
+ Polygon *p = end_poly;
path.push_back(end_point);
- while(true) {
+ while (true) {
int prev = p->prev_edge;
- int prev_n = (p->prev_edge+1)%p->edges.size();
- Vector3 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point))*0.5;
+ int prev_n = (p->prev_edge + 1) % p->edges.size();
+ Vector3 point = (_get_vertex(p->edges[prev].point) + _get_vertex(p->edges[prev_n].point)) * 0.5;
path.push_back(point);
p = p->edges[prev].C;
- if (p==begin_poly)
+ if (p == begin_poly)
break;
}
path.push_back(begin_point);
-
path.invert();
}
return path;
}
-
return Vector<Vector3>();
-
}
-Vector3 Navigation::get_closest_point_to_segment(const Vector3& p_from,const Vector3& p_to,const bool& p_use_collision) {
-
+Vector3 Navigation::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool &p_use_collision) {
- bool use_collision=p_use_collision;
+ bool use_collision = p_use_collision;
Vector3 closest_point;
- float closest_point_d=1e20;
- NavMesh *closest_navmesh=NULL;
+ float closest_point_d = 1e20;
+ NavMesh *closest_navmesh = NULL;
- for (Map<int,NavMesh>::Element*E=navmesh_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navmesh_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point));
+ Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point));
Vector3 inters;
- if (f.intersects_segment(p_from,p_to,&inters)) {
+ if (f.intersects_segment(p_from, p_to, &inters)) {
if (!use_collision) {
- closest_point=inters;
- use_collision=true;
- closest_point_d=p_from.distance_to(inters);
- closest_navmesh=p.owner;
- } else if (closest_point_d > inters.distance_to(p_from)){
-
- closest_point=inters;
- closest_point_d=p_from.distance_to(inters);
- closest_navmesh=p.owner;
+ closest_point = inters;
+ use_collision = true;
+ closest_point_d = p_from.distance_to(inters);
+ closest_navmesh = p.owner;
+ } else if (closest_point_d > inters.distance_to(p_from)) {
+
+ closest_point = inters;
+ closest_point_d = p_from.distance_to(inters);
+ closest_navmesh = p.owner;
}
}
}
if (!use_collision) {
- for(int i=0;i<p.edges.size();i++) {
+ for (int i = 0; i < p.edges.size(); i++) {
- Vector3 a,b;
+ Vector3 a, b;
- Geometry::get_closest_points_between_segments(p_from,p_to,_get_vertex(p.edges[i].point),_get_vertex(p.edges[(i+1)%p.edges.size()].point),a,b);
+ Geometry::get_closest_points_between_segments(p_from, p_to, _get_vertex(p.edges[i].point), _get_vertex(p.edges[(i + 1) % p.edges.size()].point), a, b);
float d = a.distance_to(b);
- if (d<closest_point_d) {
+ if (d < closest_point_d) {
- closest_point_d=d;
- closest_point=b;
- closest_navmesh=p.owner;
+ closest_point_d = d;
+ closest_point = b;
+ closest_navmesh = p.owner;
}
-
}
}
}
@@ -624,132 +589,126 @@ Vector3 Navigation::get_closest_point_to_segment(const Vector3& p_from,const Vec
return closest_point;
}
-Vector3 Navigation::get_closest_point(const Vector3& p_point) {
+Vector3 Navigation::get_closest_point(const Vector3 &p_point) {
Vector3 closest_point;
- float closest_point_d=1e20;
+ float closest_point_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navmesh_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navmesh_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point));
+ Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point));
Vector3 inters = f.get_closest_point_to(p_point);
float d = inters.distance_to(p_point);
- if (d<closest_point_d) {
- closest_point=inters;
- closest_point_d=d;
+ if (d < closest_point_d) {
+ closest_point = inters;
+ closest_point_d = d;
}
}
}
}
return closest_point;
-
}
-Vector3 Navigation::get_closest_point_normal(const Vector3& p_point){
+Vector3 Navigation::get_closest_point_normal(const Vector3 &p_point) {
Vector3 closest_point;
Vector3 closest_normal;
- float closest_point_d=1e20;
+ float closest_point_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navmesh_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navmesh_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point));
+ Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point));
Vector3 inters = f.get_closest_point_to(p_point);
float d = inters.distance_to(p_point);
- if (d<closest_point_d) {
- closest_point=inters;
- closest_point_d=d;
- closest_normal=f.get_plane().normal;
+ if (d < closest_point_d) {
+ closest_point = inters;
+ closest_point_d = d;
+ closest_normal = f.get_plane().normal;
}
}
}
}
return closest_normal;
-
}
-
-Object* Navigation::get_closest_point_owner(const Vector3& p_point){
+Object *Navigation::get_closest_point_owner(const Vector3 &p_point) {
Vector3 closest_point;
- Object *owner=NULL;
- float closest_point_d=1e20;
+ Object *owner = NULL;
+ float closest_point_d = 1e20;
- for (Map<int,NavMesh>::Element*E=navmesh_map.front();E;E=E->next()) {
+ for (Map<int, NavMesh>::Element *E = navmesh_map.front(); E; E = E->next()) {
if (!E->get().linked)
continue;
- for(List<Polygon>::Element *F=E->get().polygons.front();F;F=F->next()) {
+ for (List<Polygon>::Element *F = E->get().polygons.front(); F; F = F->next()) {
- Polygon &p=F->get();
- for(int i=2;i<p.edges.size();i++) {
+ Polygon &p = F->get();
+ for (int i = 2; i < p.edges.size(); i++) {
- Face3 f(_get_vertex(p.edges[0].point),_get_vertex(p.edges[i-1].point),_get_vertex(p.edges[i].point));
+ Face3 f(_get_vertex(p.edges[0].point), _get_vertex(p.edges[i - 1].point), _get_vertex(p.edges[i].point));
Vector3 inters = f.get_closest_point_to(p_point);
float d = inters.distance_to(p_point);
- if (d<closest_point_d) {
- closest_point=inters;
- closest_point_d=d;
- owner=E->get().owner;
+ if (d < closest_point_d) {
+ closest_point = inters;
+ closest_point_d = d;
+ owner = E->get().owner;
}
}
}
}
return owner;
-
}
-void Navigation::set_up_vector(const Vector3& p_up) {
+void Navigation::set_up_vector(const Vector3 &p_up) {
-
- up=p_up;
+ up = p_up;
}
-Vector3 Navigation::get_up_vector() const{
+Vector3 Navigation::get_up_vector() const {
return up;
}
-
void Navigation::_bind_methods() {
- ClassDB::bind_method(D_METHOD("navmesh_create","mesh:NavigationMesh","xform","owner"),&Navigation::navmesh_create,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("navmesh_set_transform","id","xform"),&Navigation::navmesh_set_transform);
- ClassDB::bind_method(D_METHOD("navmesh_remove","id"),&Navigation::navmesh_remove);
+ ClassDB::bind_method(D_METHOD("navmesh_create", "mesh:NavigationMesh", "xform", "owner"), &Navigation::navmesh_create, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("navmesh_set_transform", "id", "xform"), &Navigation::navmesh_set_transform);
+ ClassDB::bind_method(D_METHOD("navmesh_remove", "id"), &Navigation::navmesh_remove);
- ClassDB::bind_method(D_METHOD("get_simple_path","start","end","optimize"),&Navigation::get_simple_path,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("get_closest_point_to_segment","start","end","use_collision"),&Navigation::get_closest_point_to_segment,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_closest_point","to_point"),&Navigation::get_closest_point);
- ClassDB::bind_method(D_METHOD("get_closest_point_normal","to_point"),&Navigation::get_closest_point_normal);
- ClassDB::bind_method(D_METHOD("get_closest_point_owner","to_point"),&Navigation::get_closest_point_owner);
+ ClassDB::bind_method(D_METHOD("get_simple_path", "start", "end", "optimize"), &Navigation::get_simple_path, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("get_closest_point_to_segment", "start", "end", "use_collision"), &Navigation::get_closest_point_to_segment, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_closest_point", "to_point"), &Navigation::get_closest_point);
+ ClassDB::bind_method(D_METHOD("get_closest_point_normal", "to_point"), &Navigation::get_closest_point_normal);
+ ClassDB::bind_method(D_METHOD("get_closest_point_owner", "to_point"), &Navigation::get_closest_point_owner);
- ClassDB::bind_method(D_METHOD("set_up_vector","up"),&Navigation::set_up_vector);
- ClassDB::bind_method(D_METHOD("get_up_vector"),&Navigation::get_up_vector);
+ ClassDB::bind_method(D_METHOD("set_up_vector", "up"), &Navigation::set_up_vector);
+ ClassDB::bind_method(D_METHOD("get_up_vector"), &Navigation::get_up_vector);
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"up_vector"),"set_up_vector","get_up_vector");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "up_vector"), "set_up_vector", "get_up_vector");
}
Navigation::Navigation() {
- ERR_FAIL_COND( sizeof(Point)!=8 );
- cell_size=0.01; //one centimeter
- last_id=1;
- up=Vector3(0,1,0);
+ ERR_FAIL_COND(sizeof(Point) != 8);
+ cell_size = 0.01; //one centimeter
+ last_id = 1;
+ up = Vector3(0, 1, 0);
}
diff --git a/scene/3d/navigation.h b/scene/3d/navigation.h
index 771e12466a..6222d2bad3 100644
--- a/scene/3d/navigation.h
+++ b/scene/3d/navigation.h
@@ -29,46 +29,43 @@
#ifndef NAVIGATION_H
#define NAVIGATION_H
-#include "scene/3d/spatial.h"
#include "scene/3d/navigation_mesh.h"
+#include "scene/3d/spatial.h"
class Navigation : public Spatial {
- GDCLASS( Navigation, Spatial);
-
+ GDCLASS(Navigation, Spatial);
union Point {
struct {
- int64_t x:21;
- int64_t y:22;
- int64_t z:21;
+ int64_t x : 21;
+ int64_t y : 22;
+ int64_t z : 21;
};
uint64_t key;
- bool operator<(const Point& p_key) const { return key < p_key.key; }
+ bool operator<(const Point &p_key) const { return key < p_key.key; }
};
-
struct EdgeKey {
Point a;
Point b;
- bool operator<(const EdgeKey& p_key) const {
- return (a.key==p_key.a.key)?(b.key<p_key.b.key):(a.key<p_key.a.key);
+ bool operator<(const EdgeKey &p_key) const {
+ return (a.key == p_key.a.key) ? (b.key < p_key.b.key) : (a.key < p_key.a.key);
};
- EdgeKey(const Point& p_a=Point(),const Point& p_b=Point()) {
- a=p_a;
- b=p_b;
+ EdgeKey(const Point &p_a = Point(), const Point &p_b = Point()) {
+ a = p_a;
+ b = p_b;
if (a.key > b.key) {
- SWAP(a,b);
+ SWAP(a, b);
}
}
};
-
struct NavMesh;
struct Polygon;
@@ -78,7 +75,6 @@ class Navigation : public Spatial {
int edge;
};
-
struct Polygon {
struct Edge {
@@ -86,7 +82,11 @@ class Navigation : public Spatial {
Polygon *C; //connection
int C_edge;
List<ConnectionPending>::Element *P;
- Edge() { C=NULL; C_edge=-1; P=NULL; }
+ Edge() {
+ C = NULL;
+ C_edge = -1;
+ P = NULL;
+ }
};
Vector<Edge> edges;
@@ -97,11 +97,9 @@ class Navigation : public Spatial {
int prev_edge;
bool clockwise;
-
NavMesh *owner;
};
-
struct Connection {
Polygon *A;
@@ -111,11 +109,15 @@ class Navigation : public Spatial {
List<ConnectionPending> pending;
- Connection() { A=NULL; B=NULL; A_edge=-1; B_edge=-1;}
+ Connection() {
+ A = NULL;
+ B = NULL;
+ A_edge = -1;
+ B_edge = -1;
+ }
};
- Map<EdgeKey,Connection> connections;
-
+ Map<EdgeKey, Connection> connections;
struct NavMesh {
@@ -124,62 +126,54 @@ class Navigation : public Spatial {
bool linked;
Ref<NavigationMesh> navmesh;
List<Polygon> polygons;
-
};
+ _FORCE_INLINE_ Point _get_point(const Vector3 &p_pos) const {
-
- _FORCE_INLINE_ Point _get_point(const Vector3& p_pos) const {
-
- int x = int(Math::floor(p_pos.x/cell_size));
- int y = int(Math::floor(p_pos.y/cell_size));
- int z = int(Math::floor(p_pos.z/cell_size));
+ int x = int(Math::floor(p_pos.x / cell_size));
+ int y = int(Math::floor(p_pos.y / cell_size));
+ int z = int(Math::floor(p_pos.z / cell_size));
Point p;
- p.key=0;
- p.x=x;
- p.y=y;
- p.z=z;
+ p.key = 0;
+ p.x = x;
+ p.y = y;
+ p.z = z;
return p;
-
}
- _FORCE_INLINE_ Vector3 _get_vertex(const Point& p_point) const {
+ _FORCE_INLINE_ Vector3 _get_vertex(const Point &p_point) const {
- return Vector3(p_point.x,p_point.y,p_point.z)*cell_size;
+ return Vector3(p_point.x, p_point.y, p_point.z) * cell_size;
}
-
-
void _navmesh_link(int p_id);
void _navmesh_unlink(int p_id);
float cell_size;
- Map<int,NavMesh> navmesh_map;
+ Map<int, NavMesh> navmesh_map;
int last_id;
Vector3 up;
- void _clip_path(Vector<Vector3>& path,Polygon *from_poly, const Vector3& p_to_point, Polygon* p_to_poly);
+ void _clip_path(Vector<Vector3> &path, Polygon *from_poly, const Vector3 &p_to_point, Polygon *p_to_poly);
protected:
-
static void _bind_methods();
public:
-
- void set_up_vector(const Vector3& p_up);
+ void set_up_vector(const Vector3 &p_up);
Vector3 get_up_vector() const;
//API should be as dynamic as possible
- int navmesh_create(const Ref<NavigationMesh>& p_mesh,const Transform& p_xform,Object* p_owner=NULL);
- void navmesh_set_transform(int p_id, const Transform& p_xform);
+ int navmesh_create(const Ref<NavigationMesh> &p_mesh, const Transform &p_xform, Object *p_owner = NULL);
+ void navmesh_set_transform(int p_id, const Transform &p_xform);
void navmesh_remove(int p_id);
- Vector<Vector3> get_simple_path(const Vector3& p_start, const Vector3& p_end,bool p_optimize=true);
- Vector3 get_closest_point_to_segment(const Vector3& p_from,const Vector3& p_to,const bool& p_use_collision=false);
- Vector3 get_closest_point(const Vector3& p_point);
- Vector3 get_closest_point_normal(const Vector3& p_point);
- Object* get_closest_point_owner(const Vector3& p_point);
+ Vector<Vector3> get_simple_path(const Vector3 &p_start, const Vector3 &p_end, bool p_optimize = true);
+ Vector3 get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool &p_use_collision = false);
+ Vector3 get_closest_point(const Vector3 &p_point);
+ Vector3 get_closest_point_normal(const Vector3 &p_point);
+ Object *get_closest_point_owner(const Vector3 &p_point);
Navigation();
};
diff --git a/scene/3d/navigation_mesh.cpp b/scene/3d/navigation_mesh.cpp
index 8efb9bb333..1059a9b979 100644
--- a/scene/3d/navigation_mesh.cpp
+++ b/scene/3d/navigation_mesh.cpp
@@ -27,23 +27,22 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "navigation_mesh.h"
-#include "navigation.h"
#include "mesh_instance.h"
+#include "navigation.h"
-void NavigationMesh::create_from_mesh(const Ref<Mesh>& p_mesh) {
-
+void NavigationMesh::create_from_mesh(const Ref<Mesh> &p_mesh) {
- vertices=PoolVector<Vector3>();
+ vertices = PoolVector<Vector3>();
clear_polygons();
- for(int i=0;i<p_mesh->get_surface_count();i++) {
+ for (int i = 0; i < p_mesh->get_surface_count(); i++) {
- if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES)
+ if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
continue;
Array arr = p_mesh->surface_get_arrays(i);
PoolVector<Vector3> varr = arr[Mesh::ARRAY_VERTEX];
PoolVector<int> iarr = arr[Mesh::ARRAY_INDEX];
- if (varr.size()==0 || iarr.size()==0)
+ if (varr.size() == 0 || iarr.size() == 0)
continue;
int from = vertices.size();
@@ -51,34 +50,33 @@ void NavigationMesh::create_from_mesh(const Ref<Mesh>& p_mesh) {
int rlen = iarr.size();
PoolVector<int>::Read r = iarr.read();
- for(int j=0;j<rlen;j+=3) {
+ for (int j = 0; j < rlen; j += 3) {
Vector<int> vi;
vi.resize(3);
- vi[0]=r[j+0]+from;
- vi[1]=r[j+1]+from;
- vi[2]=r[j+2]+from;
+ vi[0] = r[j + 0] + from;
+ vi[1] = r[j + 1] + from;
+ vi[2] = r[j + 2] + from;
add_polygon(vi);
}
}
}
-void NavigationMesh::set_vertices(const PoolVector<Vector3>& p_vertices) {
+void NavigationMesh::set_vertices(const PoolVector<Vector3> &p_vertices) {
- vertices=p_vertices;
+ vertices = p_vertices;
}
-PoolVector<Vector3> NavigationMesh::get_vertices() const{
+PoolVector<Vector3> NavigationMesh::get_vertices() const {
return vertices;
}
-
-void NavigationMesh::_set_polygons(const Array& p_array) {
+void NavigationMesh::_set_polygons(const Array &p_array) {
polygons.resize(p_array.size());
- for(int i=0;i<p_array.size();i++) {
- polygons[i].indices=p_array[i];
+ for (int i = 0; i < p_array.size(); i++) {
+ polygons[i].indices = p_array[i];
}
}
@@ -86,31 +84,29 @@ Array NavigationMesh::_get_polygons() const {
Array ret;
ret.resize(polygons.size());
- for(int i=0;i<ret.size();i++) {
- ret[i]=polygons[i].indices;
+ for (int i = 0; i < ret.size(); i++) {
+ ret[i] = polygons[i].indices;
}
return ret;
}
-
-void NavigationMesh::add_polygon(const Vector<int>& p_polygon){
+void NavigationMesh::add_polygon(const Vector<int> &p_polygon) {
Polygon polygon;
- polygon.indices=p_polygon;
+ polygon.indices = p_polygon;
polygons.push_back(polygon);
-
}
-int NavigationMesh::get_polygon_count() const{
+int NavigationMesh::get_polygon_count() const {
return polygons.size();
}
-Vector<int> NavigationMesh::get_polygon(int p_idx){
+Vector<int> NavigationMesh::get_polygon(int p_idx) {
- ERR_FAIL_INDEX_V(p_idx,polygons.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_idx, polygons.size(), Vector<int>());
return polygons[p_idx].indices;
}
-void NavigationMesh::clear_polygons(){
+void NavigationMesh::clear_polygons() {
polygons.clear();
}
@@ -120,64 +116,59 @@ Ref<Mesh> NavigationMesh::get_debug_mesh() {
if (debug_mesh.is_valid())
return debug_mesh;
-
-
PoolVector<Vector3> vertices = get_vertices();
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
List<Face3> faces;
- for(int i=0;i<get_polygon_count();i++) {
+ for (int i = 0; i < get_polygon_count(); i++) {
Vector<int> p = get_polygon(i);
- for(int j=2;j<p.size();j++) {
+ for (int j = 2; j < p.size(); j++) {
Face3 f;
- f.vertex[0]=vr[p[0]];
- f.vertex[1]=vr[p[j-1]];
- f.vertex[2]=vr[p[j]];
+ f.vertex[0] = vr[p[0]];
+ f.vertex[1] = vr[p[j - 1]];
+ f.vertex[2] = vr[p[j]];
faces.push_back(f);
}
}
-
- Map<_EdgeKey,bool> edge_map;
+ Map<_EdgeKey, bool> edge_map;
PoolVector<Vector3> tmeshfaces;
- tmeshfaces.resize(faces.size()*3);
+ tmeshfaces.resize(faces.size() * 3);
{
- PoolVector<Vector3>::Write tw=tmeshfaces.write();
- int tidx=0;
-
+ PoolVector<Vector3>::Write tw = tmeshfaces.write();
+ int tidx = 0;
- for(List<Face3>::Element *E=faces.front();E;E=E->next()) {
+ for (List<Face3>::Element *E = faces.front(); E; E = E->next()) {
const Face3 &f = E->get();
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- tw[tidx++]=f.vertex[j];
+ tw[tidx++] = f.vertex[j];
_EdgeKey ek;
- ek.from=f.vertex[j].snapped(CMP_EPSILON);
- ek.to=f.vertex[(j+1)%3].snapped(CMP_EPSILON);
- if (ek.from<ek.to)
- SWAP(ek.from,ek.to);
+ ek.from = f.vertex[j].snapped(CMP_EPSILON);
+ ek.to = f.vertex[(j + 1) % 3].snapped(CMP_EPSILON);
+ if (ek.from < ek.to)
+ SWAP(ek.from, ek.to);
- Map<_EdgeKey,bool>::Element *E=edge_map.find(ek);
+ Map<_EdgeKey, bool>::Element *E = edge_map.find(ek);
if (E) {
- E->get()=false;
+ E->get() = false;
} else {
- edge_map[ek]=true;
+ edge_map[ek] = true;
}
-
}
}
}
List<Vector3> lines;
- for(Map<_EdgeKey,bool>::Element *E=edge_map.front();E;E=E->next()) {
+ for (Map<_EdgeKey, bool>::Element *E = edge_map.front(); E; E = E->next()) {
if (E->get()) {
lines.push_back(E->key().from);
@@ -189,58 +180,57 @@ Ref<Mesh> NavigationMesh::get_debug_mesh() {
varr.resize(lines.size());
{
PoolVector<Vector3>::Write w = varr.write();
- int idx=0;
- for(List<Vector3>::Element *E=lines.front();E;E=E->next()) {
- w[idx++]=E->get();
+ int idx = 0;
+ for (List<Vector3>::Element *E = lines.front(); E; E = E->next()) {
+ w[idx++] = E->get();
}
}
- debug_mesh = Ref<Mesh>( memnew( Mesh ) );
+ debug_mesh = Ref<Mesh>(memnew(Mesh));
Array arr;
arr.resize(Mesh::ARRAY_MAX);
- arr[Mesh::ARRAY_VERTEX]=varr;
+ arr[Mesh::ARRAY_VERTEX] = varr;
- debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,arr);
+ debug_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, arr);
return debug_mesh;
}
void NavigationMesh::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_vertices","vertices"),&NavigationMesh::set_vertices);
- ClassDB::bind_method(D_METHOD("get_vertices"),&NavigationMesh::get_vertices);
+ ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationMesh::set_vertices);
+ ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationMesh::get_vertices);
- ClassDB::bind_method(D_METHOD("add_polygon","polygon"),&NavigationMesh::add_polygon);
- ClassDB::bind_method(D_METHOD("get_polygon_count"),&NavigationMesh::get_polygon_count);
- ClassDB::bind_method(D_METHOD("get_polygon","idx"),&NavigationMesh::get_polygon);
- ClassDB::bind_method(D_METHOD("clear_polygons"),&NavigationMesh::clear_polygons);
+ ClassDB::bind_method(D_METHOD("add_polygon", "polygon"), &NavigationMesh::add_polygon);
+ ClassDB::bind_method(D_METHOD("get_polygon_count"), &NavigationMesh::get_polygon_count);
+ ClassDB::bind_method(D_METHOD("get_polygon", "idx"), &NavigationMesh::get_polygon);
+ ClassDB::bind_method(D_METHOD("clear_polygons"), &NavigationMesh::clear_polygons);
- ClassDB::bind_method(D_METHOD("_set_polygons","polygons"),&NavigationMesh::_set_polygons);
- ClassDB::bind_method(D_METHOD("_get_polygons"),&NavigationMesh::_get_polygons);
+ ClassDB::bind_method(D_METHOD("_set_polygons", "polygons"), &NavigationMesh::_set_polygons);
+ ClassDB::bind_method(D_METHOD("_get_polygons"), &NavigationMesh::_get_polygons);
- ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"vertices",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_vertices","get_vertices");
- ADD_PROPERTY(PropertyInfo(Variant::ARRAY,"polygons",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_polygons","_get_polygons");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_vertices", "get_vertices");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "polygons", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_polygons", "_get_polygons");
}
NavigationMesh::NavigationMesh() {
-
}
void NavigationMeshInstance::set_enabled(bool p_enabled) {
- if (enabled==p_enabled)
+ if (enabled == p_enabled)
return;
- enabled=p_enabled;
+ enabled = p_enabled;
if (!is_inside_tree())
return;
if (!enabled) {
- if (nav_id!=-1) {
+ if (nav_id != -1) {
navigation->navmesh_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
} else {
@@ -248,20 +238,18 @@ void NavigationMeshInstance::set_enabled(bool p_enabled) {
if (navmesh.is_valid()) {
- nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this);
+ nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this);
}
}
-
}
if (debug_view) {
- MeshInstance *dm=debug_view->cast_to<MeshInstance>();
+ MeshInstance *dm = debug_view->cast_to<MeshInstance>();
if (is_enabled()) {
- dm->set_material_override( get_tree()->get_debug_navigation_material() );
+ dm->set_material_override(get_tree()->get_debug_navigation_material());
} else {
- dm->set_material_override( get_tree()->get_debug_navigation_disabled_material() );
+ dm->set_material_override(get_tree()->get_debug_navigation_disabled_material());
}
-
}
update_gizmo();
@@ -269,104 +257,96 @@ void NavigationMeshInstance::set_enabled(bool p_enabled) {
bool NavigationMeshInstance::is_enabled() const {
-
return enabled;
}
-
/////////////////////////////
-
void NavigationMeshInstance::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- Spatial *c=this;
- while(c) {
+ Spatial *c = this;
+ while (c) {
- navigation=c->cast_to<Navigation>();
+ navigation = c->cast_to<Navigation>();
if (navigation) {
if (enabled && navmesh.is_valid()) {
- nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this);
+ nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this);
}
break;
}
- c=c->get_parent_spatial();
+ c = c->get_parent_spatial();
}
if (navmesh.is_valid() && get_tree()->is_debugging_navigation_hint()) {
- MeshInstance *dm = memnew( MeshInstance );
- dm->set_mesh( navmesh->get_debug_mesh() );
+ MeshInstance *dm = memnew(MeshInstance);
+ dm->set_mesh(navmesh->get_debug_mesh());
if (is_enabled()) {
- dm->set_material_override( get_tree()->get_debug_navigation_material() );
+ dm->set_material_override(get_tree()->get_debug_navigation_material());
} else {
- dm->set_material_override( get_tree()->get_debug_navigation_disabled_material() );
+ dm->set_material_override(get_tree()->get_debug_navigation_disabled_material());
}
add_child(dm);
- debug_view=dm;
+ debug_view = dm;
}
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
- if (navigation && nav_id!=-1) {
- navigation->navmesh_set_transform(nav_id,get_relative_transform(navigation));
+ if (navigation && nav_id != -1) {
+ navigation->navmesh_set_transform(nav_id, get_relative_transform(navigation));
}
-
-
} break;
case NOTIFICATION_EXIT_TREE: {
if (navigation) {
- if (nav_id!=-1) {
+ if (nav_id != -1) {
navigation->navmesh_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
}
if (debug_view) {
debug_view->queue_delete();
- debug_view=NULL;
+ debug_view = NULL;
}
- navigation=NULL;
+ navigation = NULL;
} break;
}
}
+void NavigationMeshInstance::set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh) {
-void NavigationMeshInstance::set_navigation_mesh(const Ref<NavigationMesh>& p_navmesh) {
-
- if (p_navmesh==navmesh)
+ if (p_navmesh == navmesh)
return;
- if (navigation && nav_id!=-1) {
+ if (navigation && nav_id != -1) {
navigation->navmesh_remove(nav_id);
- nav_id=-1;
+ nav_id = -1;
}
- navmesh=p_navmesh;
+ navmesh = p_navmesh;
if (navigation && navmesh.is_valid() && enabled) {
- nav_id = navigation->navmesh_create(navmesh,get_relative_transform(navigation),this);
+ nav_id = navigation->navmesh_create(navmesh, get_relative_transform(navigation), this);
}
-
+
if (debug_view && navmesh.is_valid()) {
- debug_view->cast_to<MeshInstance>()->set_mesh( navmesh->get_debug_mesh() );
+ debug_view->cast_to<MeshInstance>()->set_mesh(navmesh->get_debug_mesh());
}
-
+
update_gizmo();
update_configuration_warning();
-
}
-Ref<NavigationMesh> NavigationMeshInstance::get_navigation_mesh() const{
+Ref<NavigationMesh> NavigationMeshInstance::get_navigation_mesh() const {
return navmesh;
}
@@ -379,37 +359,35 @@ String NavigationMeshInstance::get_configuration_warning() const {
if (!navmesh.is_valid()) {
return TTR("A NavigationMesh resource must be set or created for this node to work.");
}
- const Spatial *c=this;
- while(c) {
+ const Spatial *c = this;
+ while (c) {
if (c->cast_to<Navigation>())
return String();
- c=c->get_parent()->cast_to<Spatial>();
+ c = c->get_parent()->cast_to<Spatial>();
}
return TTR("NavigationMeshInstance must be a child or grandchild to a Navigation node. It only provides navigation data.");
}
-
void NavigationMeshInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_navigation_mesh","navmesh"),&NavigationMeshInstance::set_navigation_mesh);
- ClassDB::bind_method(D_METHOD("get_navigation_mesh"),&NavigationMeshInstance::get_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("set_navigation_mesh", "navmesh"), &NavigationMeshInstance::set_navigation_mesh);
+ ClassDB::bind_method(D_METHOD("get_navigation_mesh"), &NavigationMeshInstance::get_navigation_mesh);
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&NavigationMeshInstance::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&NavigationMeshInstance::is_enabled);
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationMeshInstance::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationMeshInstance::is_enabled);
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"navmesh",PROPERTY_HINT_RESOURCE_TYPE,"NavigationMesh"),"set_navigation_mesh","get_navigation_mesh");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"), "set_navigation_mesh", "get_navigation_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
}
NavigationMeshInstance::NavigationMeshInstance() {
- debug_view=NULL;
- navigation=NULL;
- nav_id=-1;
- enabled=true;
+ debug_view = NULL;
+ navigation = NULL;
+ nav_id = -1;
+ enabled = true;
set_notify_transform(true);
-
}
diff --git a/scene/3d/navigation_mesh.h b/scene/3d/navigation_mesh.h
index e025b7ce8b..fda8923788 100644
--- a/scene/3d/navigation_mesh.h
+++ b/scene/3d/navigation_mesh.h
@@ -34,9 +34,9 @@
class Mesh;
-class NavigationMesh : public Resource {
+class NavigationMesh : public Resource {
- GDCLASS( NavigationMesh, Resource );
+ GDCLASS(NavigationMesh, Resource);
PoolVector<Vector3> vertices;
struct Polygon {
@@ -50,25 +50,22 @@ class NavigationMesh : public Resource {
Vector3 from;
Vector3 to;
- bool operator<(const _EdgeKey& p_with) const { return from==p_with.from ? to < p_with.to : from < p_with.from; }
+ bool operator<(const _EdgeKey &p_with) const { return from == p_with.from ? to < p_with.to : from < p_with.from; }
};
-
protected:
-
static void _bind_methods();
- void _set_polygons(const Array& p_array);
+ void _set_polygons(const Array &p_array);
Array _get_polygons() const;
public:
+ void create_from_mesh(const Ref<Mesh> &p_mesh);
- void create_from_mesh(const Ref<Mesh>& p_mesh);
-
- void set_vertices(const PoolVector<Vector3>& p_vertices);
+ void set_vertices(const PoolVector<Vector3> &p_vertices);
PoolVector<Vector3> get_vertices() const;
- void add_polygon(const Vector<int>& p_polygon);
+ void add_polygon(const Vector<int> &p_polygon);
int get_polygon_count() const;
Vector<int> get_polygon(int p_idx);
void clear_polygons();
@@ -78,12 +75,11 @@ public:
NavigationMesh();
};
-
class Navigation;
class NavigationMeshInstance : public Spatial {
- GDCLASS(NavigationMeshInstance,Spatial);
+ GDCLASS(NavigationMeshInstance, Spatial);
bool enabled;
int nav_id;
@@ -93,17 +89,14 @@ class NavigationMeshInstance : public Spatial {
Node *debug_view;
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
-
+public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
- void set_navigation_mesh(const Ref<NavigationMesh>& p_navmesh);
+ void set_navigation_mesh(const Ref<NavigationMesh> &p_navmesh);
Ref<NavigationMesh> get_navigation_mesh() const;
String get_configuration_warning() const;
@@ -111,5 +104,4 @@ public:
NavigationMeshInstance();
};
-
#endif // NAVIGATION_MESH_H
diff --git a/scene/3d/particles.cpp b/scene/3d/particles.cpp
index 0e0c1e9dc6..ea61253ac7 100644
--- a/scene/3d/particles.cpp
+++ b/scene/3d/particles.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "particles.h"
-#include "servers/visual_server.h"
#include "scene/resources/surface_tool.h"
+#include "servers/visual_server.h"
#if 0
/*
diff --git a/scene/3d/particles.h b/scene/3d/particles.h
index b96bd4e69e..6cb1caad3a 100644
--- a/scene/3d/particles.h
+++ b/scene/3d/particles.h
@@ -29,10 +29,10 @@
#ifndef VISUALINSTANCEPARTICLES_H
#define VISUALINSTANCEPARTICLES_H
+#include "rid.h"
#include "scene/3d/visual_instance.h"
-#include "scene/resources/material.h"
#include "scene/main/timer.h"
-#include "rid.h"
+#include "scene/resources/material.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
diff --git a/scene/3d/path.cpp b/scene/3d/path.cpp
index ead150e40b..457e9e5552 100644
--- a/scene/3d/path.cpp
+++ b/scene/3d/path.cpp
@@ -52,119 +52,108 @@ void Path::_notification(int p_what) {
void Path::_curve_changed() {
-
if (is_inside_tree() && get_tree()->is_editor_hint())
update_gizmo();
}
-
-void Path::set_curve(const Ref<Curve3D>& p_curve) {
+void Path::set_curve(const Ref<Curve3D> &p_curve) {
if (curve.is_valid()) {
- curve->disconnect("changed",this,"_curve_changed");
+ curve->disconnect("changed", this, "_curve_changed");
}
- curve=p_curve;
+ curve = p_curve;
if (curve.is_valid()) {
- curve->connect("changed",this,"_curve_changed");
+ curve->connect("changed", this, "_curve_changed");
}
_curve_changed();
-
}
-Ref<Curve3D> Path::get_curve() const{
+Ref<Curve3D> Path::get_curve() const {
return curve;
}
void Path::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_curve","curve:Curve3D"),&Path::set_curve);
- ClassDB::bind_method(D_METHOD("get_curve:Curve3D","curve"),&Path::get_curve);
- ClassDB::bind_method(D_METHOD("_curve_changed"),&Path::_curve_changed);
+ ClassDB::bind_method(D_METHOD("set_curve", "curve:Curve3D"), &Path::set_curve);
+ ClassDB::bind_method(D_METHOD("get_curve:Curve3D", "curve"), &Path::get_curve);
+ ClassDB::bind_method(D_METHOD("_curve_changed"), &Path::_curve_changed);
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve3D"), "set_curve","get_curve");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve3D"), "set_curve", "get_curve");
}
Path::Path() {
- set_curve(Ref<Curve3D>( memnew( Curve3D ))); //create one by default
+ set_curve(Ref<Curve3D>(memnew(Curve3D))); //create one by default
}
-
//////////////
-
void PathFollow::_update_transform() {
-
if (!path)
return;
- Ref<Curve3D> c =path->get_curve();
+ Ref<Curve3D> c = path->get_curve();
if (!c.is_valid())
return;
-
float o = offset;
if (loop)
- o=Math::fposmod(o,c->get_baked_length());
-
- Vector3 pos = c->interpolate_baked(o,cubic);
- Transform t=get_transform();
+ o = Math::fposmod(o, c->get_baked_length());
+ Vector3 pos = c->interpolate_baked(o, cubic);
+ Transform t = get_transform();
- if (rotation_mode!=ROTATION_NONE) {
+ if (rotation_mode != ROTATION_NONE) {
- Vector3 n = (c->interpolate_baked(o+lookahead,cubic)-pos).normalized();
+ Vector3 n = (c->interpolate_baked(o + lookahead, cubic) - pos).normalized();
- if (rotation_mode==ROTATION_Y) {
+ if (rotation_mode == ROTATION_Y) {
- n.y=0;
+ n.y = 0;
n.normalize();
}
- if (n.length()<CMP_EPSILON) {//nothing, use previous
- n=-t.get_basis().get_axis(2).normalized();
+ if (n.length() < CMP_EPSILON) { //nothing, use previous
+ n = -t.get_basis().get_axis(2).normalized();
}
+ Vector3 up = Vector3(0, 1, 0);
- Vector3 up = Vector3(0,1,0);
-
- if (rotation_mode==ROTATION_XYZ) {
+ if (rotation_mode == ROTATION_XYZ) {
float tilt = c->interpolate_baked_tilt(o);
- if (tilt!=0) {
+ if (tilt != 0) {
- Basis rot(-n,tilt); //remember.. lookat will be znegative.. znegative!! we abide by opengl clan.
- up=rot.xform(up);
+ Basis rot(-n, tilt); //remember.. lookat will be znegative.. znegative!! we abide by opengl clan.
+ up = rot.xform(up);
}
}
- t.set_look_at(pos,pos+n,up);
+ t.set_look_at(pos, pos + n, up);
} else {
- t.origin=pos;
+ t.origin = pos;
}
- t.origin+=t.basis.get_axis(0)*h_offset + t.basis.get_axis(1)*v_offset;
+ t.origin += t.basis.get_axis(0) * h_offset + t.basis.get_axis(1) * v_offset;
set_transform(t);
-
}
void PathFollow::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- Node *parent=get_parent();
+ Node *parent = get_parent();
if (parent) {
- path=parent->cast_to<Path>();
+ path = parent->cast_to<Path>();
if (path) {
_update_transform();
}
@@ -173,16 +162,14 @@ void PathFollow::_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_TREE: {
-
- path=NULL;
+ path = NULL;
} break;
}
-
}
void PathFollow::set_cubic_interpolation(bool p_enable) {
- cubic=p_enable;
+ cubic = p_enable;
}
bool PathFollow::get_cubic_interpolation() const {
@@ -190,24 +177,23 @@ bool PathFollow::get_cubic_interpolation() const {
return cubic;
}
+bool PathFollow::_set(const StringName &p_name, const Variant &p_value) {
-bool PathFollow::_set(const StringName& p_name, const Variant& p_value) {
-
- if (p_name==SceneStringNames::get_singleton()->offset) {
+ if (p_name == SceneStringNames::get_singleton()->offset) {
set_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->unit_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->unit_offset) {
set_unit_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->rotation_mode) {
+ } else if (p_name == SceneStringNames::get_singleton()->rotation_mode) {
set_rotation_mode(RotationMode(p_value.operator int()));
- } else if (p_name==SceneStringNames::get_singleton()->v_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->v_offset) {
set_v_offset(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->h_offset) {
+ } else if (p_name == SceneStringNames::get_singleton()->h_offset) {
set_h_offset(p_value);
- } else if (String(p_name)=="cubic_interp") {
+ } else if (String(p_name) == "cubic_interp") {
set_cubic_interpolation(p_value);
- } else if (String(p_name)=="loop") {
+ } else if (String(p_name) == "loop") {
set_loop(p_value);
- } else if (String(p_name)=="lookahead") {
+ } else if (String(p_name) == "lookahead") {
set_lookahead(p_value);
} else
return false;
@@ -215,92 +201,87 @@ bool PathFollow::_set(const StringName& p_name, const Variant& p_value) {
return true;
}
-bool PathFollow::_get(const StringName& p_name,Variant &r_ret) const{
-
- if (p_name==SceneStringNames::get_singleton()->offset) {
- r_ret=get_offset();
- } else if (p_name==SceneStringNames::get_singleton()->unit_offset) {
- r_ret=get_unit_offset();
- } else if (p_name==SceneStringNames::get_singleton()->rotation_mode) {
- r_ret=get_rotation_mode();
- } else if (p_name==SceneStringNames::get_singleton()->v_offset) {
- r_ret=get_v_offset();
- } else if (p_name==SceneStringNames::get_singleton()->h_offset) {
- r_ret=get_h_offset();
- } else if (String(p_name)=="cubic_interp") {
- r_ret=cubic;
- } else if (String(p_name)=="loop") {
- r_ret=loop;
- } else if (String(p_name)=="lookahead") {
- r_ret=lookahead;
+bool PathFollow::_get(const StringName &p_name, Variant &r_ret) const {
+
+ if (p_name == SceneStringNames::get_singleton()->offset) {
+ r_ret = get_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->unit_offset) {
+ r_ret = get_unit_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->rotation_mode) {
+ r_ret = get_rotation_mode();
+ } else if (p_name == SceneStringNames::get_singleton()->v_offset) {
+ r_ret = get_v_offset();
+ } else if (p_name == SceneStringNames::get_singleton()->h_offset) {
+ r_ret = get_h_offset();
+ } else if (String(p_name) == "cubic_interp") {
+ r_ret = cubic;
+ } else if (String(p_name) == "loop") {
+ r_ret = loop;
+ } else if (String(p_name) == "lookahead") {
+ r_ret = lookahead;
} else
return false;
return true;
-
}
-void PathFollow::_get_property_list( List<PropertyInfo> *p_list) const{
+void PathFollow::_get_property_list(List<PropertyInfo> *p_list) const {
- float max=10000;
+ float max = 10000;
if (path && path->get_curve().is_valid())
- max=path->get_curve()->get_baked_length();
- p_list->push_back( PropertyInfo( Variant::REAL, "offset", PROPERTY_HINT_RANGE,"0,"+rtos(max)+",0.01"));
- p_list->push_back( PropertyInfo( Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE,"0,1,0.0001",PROPERTY_USAGE_EDITOR));
- p_list->push_back( PropertyInfo( Variant::REAL, "h_offset") );
- p_list->push_back( PropertyInfo( Variant::REAL, "v_offset") );
- p_list->push_back( PropertyInfo( Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM,"None,Y,XY,XYZ"));
- p_list->push_back( PropertyInfo( Variant::BOOL, "cubic_interp"));
- p_list->push_back( PropertyInfo( Variant::BOOL, "loop"));
- p_list->push_back( PropertyInfo( Variant::REAL, "lookahead",PROPERTY_HINT_RANGE,"0.001,1024.0,0.001"));
+ max = path->get_curve()->get_baked_length();
+ p_list->push_back(PropertyInfo(Variant::REAL, "offset", PROPERTY_HINT_RANGE, "0," + rtos(max) + ",0.01"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "unit_offset", PROPERTY_HINT_RANGE, "0,1,0.0001", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::REAL, "h_offset"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "v_offset"));
+ p_list->push_back(PropertyInfo(Variant::INT, "rotation_mode", PROPERTY_HINT_ENUM, "None,Y,XY,XYZ"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "cubic_interp"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "loop"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "lookahead", PROPERTY_HINT_RANGE, "0.001,1024.0,0.001"));
}
-
void PathFollow::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&PathFollow::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&PathFollow::get_offset);
-
- ClassDB::bind_method(D_METHOD("set_h_offset","h_offset"),&PathFollow::set_h_offset);
- ClassDB::bind_method(D_METHOD("get_h_offset"),&PathFollow::get_h_offset);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &PathFollow::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &PathFollow::get_offset);
- ClassDB::bind_method(D_METHOD("set_v_offset","v_offset"),&PathFollow::set_v_offset);
- ClassDB::bind_method(D_METHOD("get_v_offset"),&PathFollow::get_v_offset);
+ ClassDB::bind_method(D_METHOD("set_h_offset", "h_offset"), &PathFollow::set_h_offset);
+ ClassDB::bind_method(D_METHOD("get_h_offset"), &PathFollow::get_h_offset);
- ClassDB::bind_method(D_METHOD("set_unit_offset","unit_offset"),&PathFollow::set_unit_offset);
- ClassDB::bind_method(D_METHOD("get_unit_offset"),&PathFollow::get_unit_offset);
+ ClassDB::bind_method(D_METHOD("set_v_offset", "v_offset"), &PathFollow::set_v_offset);
+ ClassDB::bind_method(D_METHOD("get_v_offset"), &PathFollow::get_v_offset);
- ClassDB::bind_method(D_METHOD("set_rotation_mode","rotation_mode"),&PathFollow::set_rotation_mode);
- ClassDB::bind_method(D_METHOD("get_rotation_mode"),&PathFollow::get_rotation_mode);
+ ClassDB::bind_method(D_METHOD("set_unit_offset", "unit_offset"), &PathFollow::set_unit_offset);
+ ClassDB::bind_method(D_METHOD("get_unit_offset"), &PathFollow::get_unit_offset);
- ClassDB::bind_method(D_METHOD("set_cubic_interpolation","enable"),&PathFollow::set_cubic_interpolation);
- ClassDB::bind_method(D_METHOD("get_cubic_interpolation"),&PathFollow::get_cubic_interpolation);
+ ClassDB::bind_method(D_METHOD("set_rotation_mode", "rotation_mode"), &PathFollow::set_rotation_mode);
+ ClassDB::bind_method(D_METHOD("get_rotation_mode"), &PathFollow::get_rotation_mode);
- ClassDB::bind_method(D_METHOD("set_loop","loop"),&PathFollow::set_loop);
- ClassDB::bind_method(D_METHOD("has_loop"),&PathFollow::has_loop);
+ ClassDB::bind_method(D_METHOD("set_cubic_interpolation", "enable"), &PathFollow::set_cubic_interpolation);
+ ClassDB::bind_method(D_METHOD("get_cubic_interpolation"), &PathFollow::get_cubic_interpolation);
- BIND_CONSTANT( ROTATION_NONE );
- BIND_CONSTANT( ROTATION_Y );
- BIND_CONSTANT( ROTATION_XY );
- BIND_CONSTANT( ROTATION_XYZ );
+ ClassDB::bind_method(D_METHOD("set_loop", "loop"), &PathFollow::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &PathFollow::has_loop);
+ BIND_CONSTANT(ROTATION_NONE);
+ BIND_CONSTANT(ROTATION_Y);
+ BIND_CONSTANT(ROTATION_XY);
+ BIND_CONSTANT(ROTATION_XYZ);
}
void PathFollow::set_offset(float p_offset) {
- offset=p_offset;
+ offset = p_offset;
if (path)
_update_transform();
_change_notify("offset");
_change_notify("unit_offset");
-
}
void PathFollow::set_h_offset(float p_h_offset) {
- h_offset=p_h_offset;
+ h_offset = p_h_offset;
if (path)
_update_transform();
-
}
float PathFollow::get_h_offset() const {
@@ -310,10 +291,9 @@ float PathFollow::get_h_offset() const {
void PathFollow::set_v_offset(float p_v_offset) {
- v_offset=p_v_offset;
+ v_offset = p_v_offset;
if (path)
_update_transform();
-
}
float PathFollow::get_v_offset() const {
@@ -321,8 +301,7 @@ float PathFollow::get_v_offset() const {
return v_offset;
}
-
-float PathFollow::get_offset() const{
+float PathFollow::get_offset() const {
return offset;
}
@@ -330,32 +309,30 @@ float PathFollow::get_offset() const{
void PathFollow::set_unit_offset(float p_unit_offset) {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length())
- set_offset(p_unit_offset*path->get_curve()->get_baked_length());
-
+ set_offset(p_unit_offset * path->get_curve()->get_baked_length());
}
-float PathFollow::get_unit_offset() const{
+float PathFollow::get_unit_offset() const {
if (path && path->get_curve().is_valid() && path->get_curve()->get_baked_length())
- return get_offset()/path->get_curve()->get_baked_length();
+ return get_offset() / path->get_curve()->get_baked_length();
else
return 0;
}
void PathFollow::set_lookahead(float p_lookahead) {
- lookahead=p_lookahead;
-
+ lookahead = p_lookahead;
}
-float PathFollow::get_lookahead() const{
+float PathFollow::get_lookahead() const {
return lookahead;
}
void PathFollow::set_rotation_mode(RotationMode p_rotation_mode) {
- rotation_mode=p_rotation_mode;
+ rotation_mode = p_rotation_mode;
_update_transform();
}
@@ -366,23 +343,22 @@ PathFollow::RotationMode PathFollow::get_rotation_mode() const {
void PathFollow::set_loop(bool p_loop) {
- loop=p_loop;
+ loop = p_loop;
}
-bool PathFollow::has_loop() const{
+bool PathFollow::has_loop() const {
return loop;
}
-
PathFollow::PathFollow() {
- offset=0;
- h_offset=0;
- v_offset=0;
- path=NULL;
- rotation_mode=ROTATION_XYZ;
- cubic=true;
- loop=true;
- lookahead=0.1;
+ offset = 0;
+ h_offset = 0;
+ v_offset = 0;
+ path = NULL;
+ rotation_mode = ROTATION_XYZ;
+ cubic = true;
+ loop = true;
+ lookahead = 0.1;
}
diff --git a/scene/3d/path.h b/scene/3d/path.h
index ab6f459ba9..94227799ed 100644
--- a/scene/3d/path.h
+++ b/scene/3d/path.h
@@ -29,36 +29,33 @@
#ifndef PATH_H
#define PATH_H
-#include "scene/resources/curve.h"
#include "scene/3d/spatial.h"
+#include "scene/resources/curve.h"
class Path : public Spatial {
- GDCLASS( Path, Spatial );
+ GDCLASS(Path, Spatial);
Ref<Curve3D> curve;
void _curve_changed();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_curve(const Ref<Curve3D>& p_curve);
+public:
+ void set_curve(const Ref<Curve3D> &p_curve);
Ref<Curve3D> get_curve() const;
-
Path();
};
class PathFollow : public Spatial {
- GDCLASS(PathFollow,Spatial);
-public:
+ GDCLASS(PathFollow, Spatial);
+public:
enum RotationMode {
ROTATION_NONE,
@@ -79,17 +76,15 @@ private:
void _update_transform();
-
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_offset(float p_offset);
float get_offset() const;
diff --git a/scene/3d/physics_body.cpp b/scene/3d/physics_body.cpp
index af514a171f..78a00e4a7f 100644
--- a/scene/3d/physics_body.cpp
+++ b/scene/3d/physics_body.cpp
@@ -31,7 +31,7 @@
void PhysicsBody::_notification(int p_what) {
-/*
+ /*
switch(p_what) {
case NOTIFICATION_TRANSFORM_CHANGED: {
@@ -57,11 +57,10 @@ float PhysicsBody::get_inverse_mass() const {
return 0;
}
-
void PhysicsBody::set_collision_layer(uint32_t p_mask) {
- layer_mask=p_mask;
- PhysicsServer::get_singleton()->body_set_layer_mask(get_rid(),p_mask);
+ layer_mask = p_mask;
+ PhysicsServer::get_singleton()->body_set_layer_mask(get_rid(), p_mask);
}
uint32_t PhysicsBody::get_collision_layer() const {
@@ -71,8 +70,8 @@ uint32_t PhysicsBody::get_collision_layer() const {
void PhysicsBody::set_collision_mask(uint32_t p_mask) {
- collision_mask=p_mask;
- PhysicsServer::get_singleton()->body_set_collision_mask(get_rid(),p_mask);
+ collision_mask = p_mask;
+ PhysicsServer::get_singleton()->body_set_collision_mask(get_rid(), p_mask);
}
uint32_t PhysicsBody::get_collision_mask() const {
@@ -84,36 +83,33 @@ void PhysicsBody::set_collision_mask_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_mask();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_mask(mask);
-
}
-bool PhysicsBody::get_collision_mask_bit(int p_bit) const{
+bool PhysicsBody::get_collision_mask_bit(int p_bit) const {
- return get_collision_mask()&(1<<p_bit);
+ return get_collision_mask() & (1 << p_bit);
}
-
void PhysicsBody::set_collision_layer_bit(int p_bit, bool p_value) {
uint32_t mask = get_collision_layer();
if (p_value)
- mask|=1<<p_bit;
+ mask |= 1 << p_bit;
else
- mask&=~(1<<p_bit);
+ mask &= ~(1 << p_bit);
set_collision_layer(mask);
-
}
-bool PhysicsBody::get_collision_layer_bit(int p_bit) const{
+bool PhysicsBody::get_collision_layer_bit(int p_bit) const {
- return get_collision_layer()&(1<<p_bit);
+ return get_collision_layer() & (1 << p_bit);
}
-void PhysicsBody::add_collision_exception_with(Node* p_node) {
+void PhysicsBody::add_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody *physics_body = p_node->cast_to<PhysicsBody>();
@@ -121,11 +117,10 @@ void PhysicsBody::add_collision_exception_with(Node* p_node) {
ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type");
}
ERR_FAIL_COND(!physics_body);
- PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(),physics_body->get_rid());
-
+ PhysicsServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid());
}
-void PhysicsBody::remove_collision_exception_with(Node* p_node) {
+void PhysicsBody::remove_collision_exception_with(Node *p_node) {
ERR_FAIL_NULL(p_node);
PhysicsBody *physics_body = p_node->cast_to<PhysicsBody>();
@@ -133,7 +128,7 @@ void PhysicsBody::remove_collision_exception_with(Node* p_node) {
ERR_EXPLAIN("Collision exception only works between two objects of PhysicsBody type");
}
ERR_FAIL_COND(!physics_body);
- PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(),physics_body->get_rid());
+ PhysicsServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid());
}
void PhysicsBody::_set_layers(uint32_t p_mask) {
@@ -141,80 +136,73 @@ void PhysicsBody::_set_layers(uint32_t p_mask) {
set_collision_mask(p_mask);
}
-uint32_t PhysicsBody::_get_layers() const{
+uint32_t PhysicsBody::_get_layers() const {
return get_collision_layer();
}
void PhysicsBody::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_collision_layer","layer"),&PhysicsBody::set_collision_layer);
- ClassDB::bind_method(D_METHOD("get_collision_layer"),&PhysicsBody::get_collision_layer);
+ ClassDB::bind_method(D_METHOD("set_collision_layer", "layer"), &PhysicsBody::set_collision_layer);
+ ClassDB::bind_method(D_METHOD("get_collision_layer"), &PhysicsBody::get_collision_layer);
- ClassDB::bind_method(D_METHOD("set_collision_mask","mask"),&PhysicsBody::set_collision_mask);
- ClassDB::bind_method(D_METHOD("get_collision_mask"),&PhysicsBody::get_collision_mask);
+ ClassDB::bind_method(D_METHOD("set_collision_mask", "mask"), &PhysicsBody::set_collision_mask);
+ ClassDB::bind_method(D_METHOD("get_collision_mask"), &PhysicsBody::get_collision_mask);
- ClassDB::bind_method(D_METHOD("set_collision_mask_bit","bit","value"),&PhysicsBody::set_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("get_collision_mask_bit","bit"),&PhysicsBody::get_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_mask_bit", "bit", "value"), &PhysicsBody::set_collision_mask_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_mask_bit", "bit"), &PhysicsBody::get_collision_mask_bit);
- ClassDB::bind_method(D_METHOD("set_collision_layer_bit","bit","value"),&PhysicsBody::set_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("get_collision_layer_bit","bit"),&PhysicsBody::get_collision_layer_bit);
+ ClassDB::bind_method(D_METHOD("set_collision_layer_bit", "bit", "value"), &PhysicsBody::set_collision_layer_bit);
+ ClassDB::bind_method(D_METHOD("get_collision_layer_bit", "bit"), &PhysicsBody::get_collision_layer_bit);
- ClassDB::bind_method(D_METHOD("_set_layers","mask"),&PhysicsBody::_set_layers);
- ClassDB::bind_method(D_METHOD("_get_layers"),&PhysicsBody::_get_layers);
+ ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody::_set_layers);
+ ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody::_get_layers);
- ADD_GROUP("Collision","collision_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_layer",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_collision_layer","get_collision_layer");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"collision_mask",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_collision_mask","get_collision_mask");
+ ADD_GROUP("Collision", "collision_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_layer", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_layer", "get_collision_layer");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_collision_mask", "get_collision_mask");
}
+PhysicsBody::PhysicsBody(PhysicsServer::BodyMode p_mode)
+ : CollisionObject(PhysicsServer::get_singleton()->body_create(p_mode), false) {
-PhysicsBody::PhysicsBody(PhysicsServer::BodyMode p_mode) : CollisionObject( PhysicsServer::get_singleton()->body_create(p_mode), false) {
-
- layer_mask=1;
- collision_mask=1;
-
+ layer_mask = 1;
+ collision_mask = 1;
}
+void StaticBody::set_friction(real_t p_friction) {
-void StaticBody::set_friction(real_t p_friction){
-
- ERR_FAIL_COND(p_friction<0 || p_friction>1);
-
- friction=p_friction;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction);
+ ERR_FAIL_COND(p_friction < 0 || p_friction > 1);
+ friction = p_friction;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction);
}
-real_t StaticBody::get_friction() const{
+real_t StaticBody::get_friction() const {
return friction;
}
-void StaticBody::set_bounce(real_t p_bounce){
-
- ERR_FAIL_COND(p_bounce<0 || p_bounce>1);
+void StaticBody::set_bounce(real_t p_bounce) {
- bounce=p_bounce;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_BOUNCE,bounce);
+ ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1);
+ bounce = p_bounce;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce);
}
-real_t StaticBody::get_bounce() const{
+real_t StaticBody::get_bounce() const {
return bounce;
}
+void StaticBody::set_constant_linear_velocity(const Vector3 &p_vel) {
-
-void StaticBody::set_constant_linear_velocity(const Vector3& p_vel) {
-
- constant_linear_velocity=p_vel;
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_LINEAR_VELOCITY,constant_linear_velocity);
-
+ constant_linear_velocity = p_vel;
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity);
}
-void StaticBody::set_constant_angular_velocity(const Vector3& p_vel) {
+void StaticBody::set_constant_angular_velocity(const Vector3 &p_vel) {
- constant_angular_velocity=p_vel;
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_ANGULAR_VELOCITY,constant_angular_velocity);
+ constant_angular_velocity = p_vel;
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity);
}
Vector3 StaticBody::get_constant_linear_velocity() const {
@@ -226,69 +214,61 @@ Vector3 StaticBody::get_constant_angular_velocity() const {
return constant_angular_velocity;
}
-
-
void StaticBody::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_constant_linear_velocity","vel"),&StaticBody::set_constant_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_constant_angular_velocity","vel"),&StaticBody::set_constant_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"),&StaticBody::get_constant_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"),&StaticBody::get_constant_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "vel"), &StaticBody::set_constant_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "vel"), &StaticBody::set_constant_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"), &StaticBody::get_constant_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"), &StaticBody::get_constant_angular_velocity);
- ClassDB::bind_method(D_METHOD("set_friction","friction"),&StaticBody::set_friction);
- ClassDB::bind_method(D_METHOD("get_friction"),&StaticBody::get_friction);
+ ClassDB::bind_method(D_METHOD("set_friction", "friction"), &StaticBody::set_friction);
+ ClassDB::bind_method(D_METHOD("get_friction"), &StaticBody::get_friction);
- ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&StaticBody::set_bounce);
- ClassDB::bind_method(D_METHOD("get_bounce"),&StaticBody::get_bounce);
+ ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody::set_bounce);
+ ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody::get_bounce);
- ClassDB::bind_method(D_METHOD("add_collision_exception_with","body:PhysicsBody"),&PhysicsBody::add_collision_exception_with);
- ClassDB::bind_method(D_METHOD("remove_collision_exception_with","body:PhysicsBody"),&PhysicsBody::remove_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body:PhysicsBody"), &PhysicsBody::add_collision_exception_with);
+ ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body:PhysicsBody"), &PhysicsBody::remove_collision_exception_with);
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"constant_linear_velocity"),"set_constant_linear_velocity","get_constant_linear_velocity");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"constant_angular_velocity"),"set_constant_angular_velocity","get_constant_angular_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity");
}
-StaticBody::StaticBody() : PhysicsBody(PhysicsServer::BODY_MODE_STATIC) {
+StaticBody::StaticBody()
+ : PhysicsBody(PhysicsServer::BODY_MODE_STATIC) {
- bounce=0;
- friction=1;
+ bounce = 0;
+ friction = 1;
}
StaticBody::~StaticBody() {
-
-
}
-
-
-
void RigidBody::_body_enter_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(E->get().in_tree);
- E->get().in_tree=true;
+ E->get().in_tree = true;
- contact_monitor->locked=true;
+ contact_monitor->locked = true;
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
}
- contact_monitor->locked=false;
-
-
+ contact_monitor->locked = false;
}
void RigidBody::_body_exit_tree(ObjectID p_id) {
@@ -296,58 +276,55 @@ void RigidBody::_body_exit_tree(ObjectID p_id) {
Object *obj = ObjectDB::get_instance(p_id);
Node *node = obj ? obj->cast_to<Node>() : NULL;
ERR_FAIL_COND(!node);
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(p_id);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
ERR_FAIL_COND(!E);
ERR_FAIL_COND(!E->get().in_tree);
- E->get().in_tree=false;
+ E->get().in_tree = false;
- contact_monitor->locked=true;
+ contact_monitor->locked = true;
- emit_signal(SceneStringNames::get_singleton()->body_exited,node);
+ emit_signal(SceneStringNames::get_singleton()->body_exited, node);
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,p_id,node,E->get().shapes[i].body_shape,E->get().shapes[i].local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_id, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
}
- contact_monitor->locked=false;
-
+ contact_monitor->locked = false;
}
-void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape) {
+void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape) {
- bool body_in = p_status==1;
- ObjectID objid=p_instance;
+ bool body_in = p_status == 1;
+ ObjectID objid = p_instance;
Object *obj = ObjectDB::get_instance(objid);
Node *node = obj ? obj->cast_to<Node>() : NULL;
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(objid);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(objid);
ERR_FAIL_COND(!body_in && !E);
if (body_in) {
if (!E) {
- E = contact_monitor->body_map.insert(objid,BodyState());
+ E = contact_monitor->body_map.insert(objid, BodyState());
//E->get().rc=0;
- E->get().in_tree=node && node->is_inside_tree();
+ E->get().in_tree = node && node->is_inside_tree();
if (node) {
- node->connect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree,make_binds(objid));
- node->connect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree,make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid));
+ node->connect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_entered,node);
+ emit_signal(SceneStringNames::get_singleton()->body_entered, node);
}
}
-
}
//E->get().rc++;
if (node)
- E->get().shapes.insert(ShapePair(p_body_shape,p_local_shape));
-
+ E->get().shapes.insert(ShapePair(p_body_shape, p_local_shape));
if (E->get().in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_entered,objid,node,p_body_shape,p_local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_entered, objid, node, p_body_shape, p_local_shape);
}
} else {
@@ -355,31 +332,27 @@ void RigidBody::_body_inout(int p_status, ObjectID p_instance, int p_body_shape,
//E->get().rc--;
if (node)
- E->get().shapes.erase(ShapePair(p_body_shape,p_local_shape));
+ E->get().shapes.erase(ShapePair(p_body_shape, p_local_shape));
bool in_tree = E->get().in_tree;
if (E->get().shapes.empty()) {
if (node) {
- node->disconnect(SceneStringNames::get_singleton()->tree_entered,this,SceneStringNames::get_singleton()->_body_enter_tree);
- node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,SceneStringNames::get_singleton()->_body_exit_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
+ node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, SceneStringNames::get_singleton()->_body_exit_tree);
if (in_tree)
- emit_signal(SceneStringNames::get_singleton()->body_exited,obj);
-
+ emit_signal(SceneStringNames::get_singleton()->body_exited, obj);
}
contact_monitor->body_map.erase(E);
}
if (node && in_tree) {
- emit_signal(SceneStringNames::get_singleton()->body_shape_exited,objid,obj,p_body_shape,p_local_shape);
+ emit_signal(SceneStringNames::get_singleton()->body_shape_exited, objid, obj, p_body_shape, p_local_shape);
}
-
}
-
}
-
struct _RigidBodyInOut {
ObjectID id;
@@ -389,49 +362,49 @@ struct _RigidBodyInOut {
void RigidBody::_direct_state_changed(Object *p_state) {
- //eh.. fuck
+//eh.. fuck
#ifdef DEBUG_ENABLED
- state=p_state->cast_to<PhysicsDirectBodyState>();
+ state = p_state->cast_to<PhysicsDirectBodyState>();
#else
- state=(PhysicsDirectBodyState*)p_state; //trust it
+ state = (PhysicsDirectBodyState *)p_state; //trust it
#endif
set_ignore_transform_notification(true);
set_global_transform(state->get_transform());
- linear_velocity=state->get_linear_velocity();
- angular_velocity=state->get_angular_velocity();
- if(sleeping!=state->is_sleeping()) {
- sleeping=state->is_sleeping();
+ linear_velocity = state->get_linear_velocity();
+ angular_velocity = state->get_angular_velocity();
+ if (sleeping != state->is_sleeping()) {
+ sleeping = state->is_sleeping();
emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed);
}
if (get_script_instance())
- get_script_instance()->call("_integrate_forces",state);
+ get_script_instance()->call("_integrate_forces", state);
set_ignore_transform_notification(false);
if (contact_monitor) {
- contact_monitor->locked=true;
+ contact_monitor->locked = true;
//untag all
- int rc=0;
- for( Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ int rc = 0;
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
- E->get().shapes[i].tagged=false;
+ E->get().shapes[i].tagged = false;
rc++;
}
}
- _RigidBodyInOut *toadd=(_RigidBodyInOut*)alloca(state->get_contact_count()*sizeof(_RigidBodyInOut));
- int toadd_count=0;//state->get_contact_count();
- RigidBody_RemoveAction *toremove=(RigidBody_RemoveAction*)alloca(rc*sizeof(RigidBody_RemoveAction));
- int toremove_count=0;
+ _RigidBodyInOut *toadd = (_RigidBodyInOut *)alloca(state->get_contact_count() * sizeof(_RigidBodyInOut));
+ int toadd_count = 0; //state->get_contact_count();
+ RigidBody_RemoveAction *toremove = (RigidBody_RemoveAction *)alloca(rc * sizeof(RigidBody_RemoveAction));
+ int toremove_count = 0;
//put the ones to add
- for(int i=0;i<state->get_contact_count();i++) {
+ for (int i = 0; i < state->get_contact_count(); i++) {
ObjectID obj = state->get_contact_collider_id(i);
int local_shape = state->get_contact_local_shape(i);
@@ -439,258 +412,239 @@ void RigidBody::_direct_state_changed(Object *p_state) {
//bool found=false;
- Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.find(obj);
+ Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(obj);
if (!E) {
- toadd[toadd_count].local_shape=local_shape;
- toadd[toadd_count].id=obj;
- toadd[toadd_count].shape=shape;
+ toadd[toadd_count].local_shape = local_shape;
+ toadd[toadd_count].id = obj;
+ toadd[toadd_count].shape = shape;
toadd_count++;
continue;
}
- ShapePair sp( shape,local_shape );
+ ShapePair sp(shape, local_shape);
int idx = E->get().shapes.find(sp);
- if (idx==-1) {
+ if (idx == -1) {
- toadd[toadd_count].local_shape=local_shape;
- toadd[toadd_count].id=obj;
- toadd[toadd_count].shape=shape;
+ toadd[toadd_count].local_shape = local_shape;
+ toadd[toadd_count].id = obj;
+ toadd[toadd_count].shape = shape;
toadd_count++;
continue;
}
- E->get().shapes[idx].tagged=true;
+ E->get().shapes[idx].tagged = true;
}
//put the ones to remove
- for( Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
- for(int i=0;i<E->get().shapes.size();i++) {
+ for (int i = 0; i < E->get().shapes.size(); i++) {
if (!E->get().shapes[i].tagged) {
- toremove[toremove_count].body_id=E->key();
- toremove[toremove_count].pair=E->get().shapes[i];
+ toremove[toremove_count].body_id = E->key();
+ toremove[toremove_count].pair = E->get().shapes[i];
toremove_count++;
}
}
}
-
//process remotions
- for(int i=0;i<toremove_count;i++) {
+ for (int i = 0; i < toremove_count; i++) {
- _body_inout(0,toremove[i].body_id,toremove[i].pair.body_shape,toremove[i].pair.local_shape);
+ _body_inout(0, toremove[i].body_id, toremove[i].pair.body_shape, toremove[i].pair.local_shape);
}
//process aditions
- for(int i=0;i<toadd_count;i++) {
+ for (int i = 0; i < toadd_count; i++) {
- _body_inout(1,toadd[i].id,toadd[i].shape,toadd[i].local_shape);
+ _body_inout(1, toadd[i].id, toadd[i].shape, toadd[i].local_shape);
}
- contact_monitor->locked=false;
-
+ contact_monitor->locked = false;
}
-
-
- state=NULL;
+ state = NULL;
}
void RigidBody::_notification(int p_what) {
-
-
}
void RigidBody::set_mode(Mode p_mode) {
- mode=p_mode;
- switch(p_mode) {
+ mode = p_mode;
+ switch (p_mode) {
case MODE_RIGID: {
- PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_RIGID);
+ PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_RIGID);
} break;
case MODE_STATIC: {
- PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_STATIC);
+ PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_STATIC);
} break;
case MODE_CHARACTER: {
- PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_CHARACTER);
+ PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_CHARACTER);
} break;
case MODE_KINEMATIC: {
- PhysicsServer::get_singleton()->body_set_mode(get_rid(),PhysicsServer::BODY_MODE_KINEMATIC);
+ PhysicsServer::get_singleton()->body_set_mode(get_rid(), PhysicsServer::BODY_MODE_KINEMATIC);
} break;
-
}
}
-RigidBody::Mode RigidBody::get_mode() const{
+RigidBody::Mode RigidBody::get_mode() const {
return mode;
}
-void RigidBody::set_mass(real_t p_mass){
+void RigidBody::set_mass(real_t p_mass) {
- ERR_FAIL_COND(p_mass<=0);
- mass=p_mass;
+ ERR_FAIL_COND(p_mass <= 0);
+ mass = p_mass;
_change_notify("mass");
_change_notify("weight");
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_MASS,mass);
-
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_MASS, mass);
}
-real_t RigidBody::get_mass() const{
+real_t RigidBody::get_mass() const {
return mass;
}
-void RigidBody::set_weight(real_t p_weight){
+void RigidBody::set_weight(real_t p_weight) {
- set_mass(p_weight/9.8);
+ set_mass(p_weight / 9.8);
}
-real_t RigidBody::get_weight() const{
+real_t RigidBody::get_weight() const {
- return mass*9.8;
+ return mass * 9.8;
}
+void RigidBody::set_friction(real_t p_friction) {
-void RigidBody::set_friction(real_t p_friction){
-
- ERR_FAIL_COND(p_friction<0 || p_friction>1);
-
- friction=p_friction;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction);
+ ERR_FAIL_COND(p_friction < 0 || p_friction > 1);
+ friction = p_friction;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction);
}
-real_t RigidBody::get_friction() const{
+real_t RigidBody::get_friction() const {
return friction;
}
-void RigidBody::set_bounce(real_t p_bounce){
+void RigidBody::set_bounce(real_t p_bounce) {
- ERR_FAIL_COND(p_bounce<0 || p_bounce>1);
-
- bounce=p_bounce;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_BOUNCE,bounce);
+ ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1);
+ bounce = p_bounce;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_BOUNCE, bounce);
}
-real_t RigidBody::get_bounce() const{
+real_t RigidBody::get_bounce() const {
return bounce;
}
+void RigidBody::set_gravity_scale(real_t p_gravity_scale) {
-void RigidBody::set_gravity_scale(real_t p_gravity_scale){
-
- gravity_scale=p_gravity_scale;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_GRAVITY_SCALE,gravity_scale);
-
+ gravity_scale = p_gravity_scale;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_GRAVITY_SCALE, gravity_scale);
}
-real_t RigidBody::get_gravity_scale() const{
+real_t RigidBody::get_gravity_scale() const {
return gravity_scale;
}
-void RigidBody::set_linear_damp(real_t p_linear_damp){
-
- ERR_FAIL_COND(p_linear_damp<-1);
- linear_damp=p_linear_damp;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_LINEAR_DAMP,linear_damp);
+void RigidBody::set_linear_damp(real_t p_linear_damp) {
+ ERR_FAIL_COND(p_linear_damp < -1);
+ linear_damp = p_linear_damp;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_LINEAR_DAMP, linear_damp);
}
-real_t RigidBody::get_linear_damp() const{
+real_t RigidBody::get_linear_damp() const {
return linear_damp;
}
-void RigidBody::set_angular_damp(real_t p_angular_damp){
-
- ERR_FAIL_COND(p_angular_damp<-1);
- angular_damp=p_angular_damp;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_ANGULAR_DAMP,angular_damp);
+void RigidBody::set_angular_damp(real_t p_angular_damp) {
+ ERR_FAIL_COND(p_angular_damp < -1);
+ angular_damp = p_angular_damp;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_ANGULAR_DAMP, angular_damp);
}
-real_t RigidBody::get_angular_damp() const{
+real_t RigidBody::get_angular_damp() const {
return angular_damp;
}
-void RigidBody::set_axis_velocity(const Vector3& p_axis) {
+void RigidBody::set_axis_velocity(const Vector3 &p_axis) {
- Vector3 v = state? state->get_linear_velocity() : linear_velocity;
+ Vector3 v = state ? state->get_linear_velocity() : linear_velocity;
Vector3 axis = p_axis.normalized();
- v-=axis*axis.dot(v);
- v+=p_axis;
+ v -= axis * axis.dot(v);
+ v += p_axis;
if (state) {
set_linear_velocity(v);
} else {
- PhysicsServer::get_singleton()->body_set_axis_velocity(get_rid(),p_axis);
- linear_velocity=v;
+ PhysicsServer::get_singleton()->body_set_axis_velocity(get_rid(), p_axis);
+ linear_velocity = v;
}
}
-void RigidBody::set_linear_velocity(const Vector3& p_velocity){
+void RigidBody::set_linear_velocity(const Vector3 &p_velocity) {
- linear_velocity=p_velocity;
+ linear_velocity = p_velocity;
if (state)
state->set_linear_velocity(linear_velocity);
else
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_LINEAR_VELOCITY,linear_velocity);
-
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
}
-Vector3 RigidBody::get_linear_velocity() const{
+Vector3 RigidBody::get_linear_velocity() const {
return linear_velocity;
}
-void RigidBody::set_angular_velocity(const Vector3& p_velocity){
+void RigidBody::set_angular_velocity(const Vector3 &p_velocity) {
- angular_velocity=p_velocity;
+ angular_velocity = p_velocity;
if (state)
state->set_angular_velocity(angular_velocity);
else
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_ANGULAR_VELOCITY,angular_velocity);
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
}
-Vector3 RigidBody::get_angular_velocity() const{
+Vector3 RigidBody::get_angular_velocity() const {
return angular_velocity;
}
-void RigidBody::set_use_custom_integrator(bool p_enable){
+void RigidBody::set_use_custom_integrator(bool p_enable) {
- if (custom_integrator==p_enable)
+ if (custom_integrator == p_enable)
return;
- custom_integrator=p_enable;
- PhysicsServer::get_singleton()->body_set_omit_force_integration(get_rid(),p_enable);
-
-
+ custom_integrator = p_enable;
+ PhysicsServer::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable);
}
-bool RigidBody::is_using_custom_integrator(){
+bool RigidBody::is_using_custom_integrator() {
return custom_integrator;
}
void RigidBody::set_sleeping(bool p_sleeping) {
- sleeping=p_sleeping;
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_SLEEPING,sleeping);
-
+ sleeping = p_sleeping;
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_SLEEPING, sleeping);
}
void RigidBody::set_can_sleep(bool p_active) {
- can_sleep=p_active;
- PhysicsServer::get_singleton()->body_set_state(get_rid(),PhysicsServer::BODY_STATE_CAN_SLEEP,p_active);
+ can_sleep = p_active;
+ PhysicsServer::get_singleton()->body_set_state(get_rid(), PhysicsServer::BODY_STATE_CAN_SLEEP, p_active);
}
bool RigidBody::is_able_to_sleep() const {
@@ -705,36 +659,34 @@ bool RigidBody::is_sleeping() const {
void RigidBody::set_max_contacts_reported(int p_amount) {
- max_contacts_reported=p_amount;
- PhysicsServer::get_singleton()->body_set_max_contacts_reported(get_rid(),p_amount);
+ max_contacts_reported = p_amount;
+ PhysicsServer::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount);
}
-int RigidBody::get_max_contacts_reported() const{
+int RigidBody::get_max_contacts_reported() const {
return max_contacts_reported;
}
-void RigidBody::apply_impulse(const Vector3& p_pos, const Vector3& p_impulse) {
+void RigidBody::apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse) {
- PhysicsServer::get_singleton()->body_apply_impulse(get_rid(),p_pos,p_impulse);
+ PhysicsServer::get_singleton()->body_apply_impulse(get_rid(), p_pos, p_impulse);
}
void RigidBody::set_use_continuous_collision_detection(bool p_enable) {
- ccd=p_enable;
- PhysicsServer::get_singleton()->body_set_enable_continuous_collision_detection(get_rid(),p_enable);
+ ccd = p_enable;
+ PhysicsServer::get_singleton()->body_set_enable_continuous_collision_detection(get_rid(), p_enable);
}
bool RigidBody::is_using_continuous_collision_detection() const {
-
return ccd;
}
-
void RigidBody::set_contact_monitor(bool p_enabled) {
- if (p_enabled==is_contact_monitor_enabled())
+ if (p_enabled == is_contact_monitor_enabled())
return;
if (!p_enabled) {
@@ -744,31 +696,29 @@ void RigidBody::set_contact_monitor(bool p_enabled) {
}
ERR_FAIL_COND(contact_monitor->locked);
- for(Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
//clean up mess
}
- memdelete( contact_monitor );
- contact_monitor=NULL;
+ memdelete(contact_monitor);
+ contact_monitor = NULL;
} else {
- contact_monitor = memnew( ContactMonitor );
- contact_monitor->locked=false;
-
+ contact_monitor = memnew(ContactMonitor);
+ contact_monitor->locked = false;
}
-
}
bool RigidBody::is_contact_monitor_enabled() const {
- return contact_monitor!=NULL;
+ return contact_monitor != NULL;
}
void RigidBody::set_axis_lock(AxisLock p_lock) {
- axis_lock=p_lock;
- PhysicsServer::get_singleton()->body_set_axis_lock(get_rid(),PhysicsServer::BodyAxisLock(axis_lock));
+ axis_lock = p_lock;
+ PhysicsServer::get_singleton()->body_set_axis_lock(get_rid(), PhysicsServer::BodyAxisLock(axis_lock));
}
RigidBody::AxisLock RigidBody::get_axis_lock() const {
@@ -776,168 +726,161 @@ RigidBody::AxisLock RigidBody::get_axis_lock() const {
return axis_lock;
}
-
Array RigidBody::get_colliding_bodies() const {
- ERR_FAIL_COND_V(!contact_monitor,Array());
+ ERR_FAIL_COND_V(!contact_monitor, Array());
Array ret;
ret.resize(contact_monitor->body_map.size());
- int idx=0;
- for (const Map<ObjectID,BodyState>::Element *E=contact_monitor->body_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (const Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
Object *obj = ObjectDB::get_instance(E->key());
if (!obj) {
- ret.resize( ret.size() -1 ); //ops
+ ret.resize(ret.size() - 1); //ops
} else {
- ret[idx++]=obj;
+ ret[idx++] = obj;
}
-
}
return ret;
}
-
void RigidBody::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&RigidBody::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&RigidBody::get_mode);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody::get_mode);
- ClassDB::bind_method(D_METHOD("set_mass","mass"),&RigidBody::set_mass);
- ClassDB::bind_method(D_METHOD("get_mass"),&RigidBody::get_mass);
+ ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody::set_mass);
+ ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody::get_mass);
- ClassDB::bind_method(D_METHOD("set_weight","weight"),&RigidBody::set_weight);
- ClassDB::bind_method(D_METHOD("get_weight"),&RigidBody::get_weight);
+ ClassDB::bind_method(D_METHOD("set_weight", "weight"), &RigidBody::set_weight);
+ ClassDB::bind_method(D_METHOD("get_weight"), &RigidBody::get_weight);
- ClassDB::bind_method(D_METHOD("set_friction","friction"),&RigidBody::set_friction);
- ClassDB::bind_method(D_METHOD("get_friction"),&RigidBody::get_friction);
+ ClassDB::bind_method(D_METHOD("set_friction", "friction"), &RigidBody::set_friction);
+ ClassDB::bind_method(D_METHOD("get_friction"), &RigidBody::get_friction);
- ClassDB::bind_method(D_METHOD("set_bounce","bounce"),&RigidBody::set_bounce);
- ClassDB::bind_method(D_METHOD("get_bounce"),&RigidBody::get_bounce);
+ ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody::set_bounce);
+ ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody::get_bounce);
- ClassDB::bind_method(D_METHOD("set_linear_velocity","linear_velocity"),&RigidBody::set_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"),&RigidBody::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody::get_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_angular_velocity","angular_velocity"),&RigidBody::set_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_angular_velocity"),&RigidBody::get_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody::get_angular_velocity);
- ClassDB::bind_method(D_METHOD("set_gravity_scale","gravity_scale"),&RigidBody::set_gravity_scale);
- ClassDB::bind_method(D_METHOD("get_gravity_scale"),&RigidBody::get_gravity_scale);
+ ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody::set_gravity_scale);
+ ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody::get_gravity_scale);
- ClassDB::bind_method(D_METHOD("set_linear_damp","linear_damp"),&RigidBody::set_linear_damp);
- ClassDB::bind_method(D_METHOD("get_linear_damp"),&RigidBody::get_linear_damp);
+ ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody::set_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody::get_linear_damp);
- ClassDB::bind_method(D_METHOD("set_angular_damp","angular_damp"),&RigidBody::set_angular_damp);
- ClassDB::bind_method(D_METHOD("get_angular_damp"),&RigidBody::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody::set_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody::get_angular_damp);
+ ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody::set_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody::get_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("set_max_contacts_reported","amount"),&RigidBody::set_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("get_max_contacts_reported"),&RigidBody::get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody::set_use_custom_integrator);
+ ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody::is_using_custom_integrator);
- ClassDB::bind_method(D_METHOD("set_use_custom_integrator","enable"),&RigidBody::set_use_custom_integrator);
- ClassDB::bind_method(D_METHOD("is_using_custom_integrator"),&RigidBody::is_using_custom_integrator);
+ ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody::set_contact_monitor);
+ ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody::is_contact_monitor_enabled);
- ClassDB::bind_method(D_METHOD("set_contact_monitor","enabled"),&RigidBody::set_contact_monitor);
- ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"),&RigidBody::is_contact_monitor_enabled);
+ ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection", "enable"), &RigidBody::set_use_continuous_collision_detection);
+ ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"), &RigidBody::is_using_continuous_collision_detection);
- ClassDB::bind_method(D_METHOD("set_use_continuous_collision_detection","enable"),&RigidBody::set_use_continuous_collision_detection);
- ClassDB::bind_method(D_METHOD("is_using_continuous_collision_detection"),&RigidBody::is_using_continuous_collision_detection);
+ ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody::set_axis_velocity);
+ ClassDB::bind_method(D_METHOD("apply_impulse", "pos", "impulse"), &RigidBody::apply_impulse);
- ClassDB::bind_method(D_METHOD("set_axis_velocity","axis_velocity"),&RigidBody::set_axis_velocity);
- ClassDB::bind_method(D_METHOD("apply_impulse","pos","impulse"),&RigidBody::apply_impulse);
+ ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody::set_sleeping);
+ ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody::is_sleeping);
- ClassDB::bind_method(D_METHOD("set_sleeping","sleeping"),&RigidBody::set_sleeping);
- ClassDB::bind_method(D_METHOD("is_sleeping"),&RigidBody::is_sleeping);
+ ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody::set_can_sleep);
+ ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody::is_able_to_sleep);
- ClassDB::bind_method(D_METHOD("set_can_sleep","able_to_sleep"),&RigidBody::set_can_sleep);
- ClassDB::bind_method(D_METHOD("is_able_to_sleep"),&RigidBody::is_able_to_sleep);
+ ClassDB::bind_method(D_METHOD("_direct_state_changed"), &RigidBody::_direct_state_changed);
+ ClassDB::bind_method(D_METHOD("_body_enter_tree"), &RigidBody::_body_enter_tree);
+ ClassDB::bind_method(D_METHOD("_body_exit_tree"), &RigidBody::_body_exit_tree);
- ClassDB::bind_method(D_METHOD("_direct_state_changed"),&RigidBody::_direct_state_changed);
- ClassDB::bind_method(D_METHOD("_body_enter_tree"),&RigidBody::_body_enter_tree);
- ClassDB::bind_method(D_METHOD("_body_exit_tree"),&RigidBody::_body_exit_tree);
+ ClassDB::bind_method(D_METHOD("set_axis_lock", "axis_lock"), &RigidBody::set_axis_lock);
+ ClassDB::bind_method(D_METHOD("get_axis_lock"), &RigidBody::get_axis_lock);
- ClassDB::bind_method(D_METHOD("set_axis_lock","axis_lock"),&RigidBody::set_axis_lock);
- ClassDB::bind_method(D_METHOD("get_axis_lock"),&RigidBody::get_axis_lock);
+ ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody::get_colliding_bodies);
- ClassDB::bind_method(D_METHOD("get_colliding_bodies"),&RigidBody::get_colliding_bodies);
+ BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state:PhysicsDirectBodyState")));
- BIND_VMETHOD(MethodInfo("_integrate_forces",PropertyInfo(Variant::OBJECT,"state:PhysicsDirectBodyState")));
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01"), "set_mass", "get_mass");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_friction", "get_friction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_bounce", "get_bounce");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "continuous_cd"), "set_use_continuous_collision_detection", "is_using_continuous_collision_detection");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported"), "set_max_contacts_reported", "get_max_contacts_reported");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "axis_lock", PROPERTY_HINT_ENUM, "Disabled,Lock X,Lock Y,Lock Z"), "set_axis_lock", "get_axis_lock");
+ ADD_GROUP("Linear", "linear_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "linear_velocity"), "set_linear_velocity", "get_linear_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_linear_damp", "get_linear_damp");
+ ADD_GROUP("Angular", "angular_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "angular_velocity"), "set_angular_velocity", "get_angular_velocity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "-1,128,0.01"), "set_angular_damp", "get_angular_damp");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Rigid,Static,Character,Kinematic"),"set_mode","get_mode");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01"),"set_mass","get_mass");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"weight",PROPERTY_HINT_EXP_RANGE,"0.01,65535,0.01",PROPERTY_USAGE_EDITOR),"set_weight","get_weight");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_friction","get_friction");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"bounce",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_bounce","get_bounce");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"gravity_scale",PROPERTY_HINT_RANGE,"-128,128,0.01"),"set_gravity_scale","get_gravity_scale");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"custom_integrator"),"set_use_custom_integrator","is_using_custom_integrator");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"continuous_cd"),"set_use_continuous_collision_detection","is_using_continuous_collision_detection");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"contacts_reported"),"set_max_contacts_reported","get_max_contacts_reported");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"contact_monitor"),"set_contact_monitor","is_contact_monitor_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"sleeping"),"set_sleeping","is_sleeping");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"can_sleep"),"set_can_sleep","is_able_to_sleep");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"axis_lock",PROPERTY_HINT_ENUM,"Disabled,Lock X,Lock Y,Lock Z"),"set_axis_lock","get_axis_lock");
- ADD_GROUP("Linear","linear_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"linear_velocity"),"set_linear_velocity","get_linear_velocity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"linear_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_linear_damp","get_linear_damp");
- ADD_GROUP("Angular","angular_");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"angular_velocity"),"set_angular_velocity","get_angular_velocity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_damp",PROPERTY_HINT_RANGE,"-1,128,0.01"),"set_angular_damp","get_angular_damp");
+ ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::INT, "body_id"), PropertyInfo(Variant::OBJECT, "body"), PropertyInfo(Variant::INT, "body_shape"), PropertyInfo(Variant::INT, "local_shape")));
+ ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body")));
+ ADD_SIGNAL(MethodInfo("sleeping_state_changed"));
- ADD_SIGNAL( MethodInfo("body_shape_entered",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape")));
- ADD_SIGNAL( MethodInfo("body_shape_exited",PropertyInfo(Variant::INT,"body_id"),PropertyInfo(Variant::OBJECT,"body"),PropertyInfo(Variant::INT,"body_shape"),PropertyInfo(Variant::INT,"local_shape")));
- ADD_SIGNAL( MethodInfo("body_entered",PropertyInfo(Variant::OBJECT,"body")));
- ADD_SIGNAL( MethodInfo("body_exited",PropertyInfo(Variant::OBJECT,"body")));
- ADD_SIGNAL( MethodInfo("sleeping_state_changed"));
-
- BIND_CONSTANT( MODE_STATIC );
- BIND_CONSTANT( MODE_KINEMATIC );
- BIND_CONSTANT( MODE_RIGID );
- BIND_CONSTANT( MODE_CHARACTER );
+ BIND_CONSTANT(MODE_STATIC);
+ BIND_CONSTANT(MODE_KINEMATIC);
+ BIND_CONSTANT(MODE_RIGID);
+ BIND_CONSTANT(MODE_CHARACTER);
}
-RigidBody::RigidBody() : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) {
+RigidBody::RigidBody()
+ : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) {
- mode=MODE_RIGID;
+ mode = MODE_RIGID;
- bounce=0;
- mass=1;
- friction=1;
- max_contacts_reported=0;
- state=NULL;
+ bounce = 0;
+ mass = 1;
+ friction = 1;
+ max_contacts_reported = 0;
+ state = NULL;
- gravity_scale=1;
- linear_damp=-1;
- angular_damp=-1;
+ gravity_scale = 1;
+ linear_damp = -1;
+ angular_damp = -1;
//angular_velocity=0;
- sleeping=false;
- ccd=false;
+ sleeping = false;
+ ccd = false;
- custom_integrator=false;
- contact_monitor=NULL;
- can_sleep=true;
+ custom_integrator = false;
+ contact_monitor = NULL;
+ can_sleep = true;
axis_lock = AXIS_LOCK_DISABLED;
- PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed");
+ PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
}
RigidBody::~RigidBody() {
if (contact_monitor)
- memdelete( contact_monitor );
-
-
-
+ memdelete(contact_monitor);
}
//////////////////////////////////////////////////////
//////////////////////////
-
Variant KinematicBody::_get_collider() const {
- ObjectID oid=get_collider();
- if (oid==0)
+ ObjectID oid = get_collider();
+ if (oid == 0)
return Variant();
Object *obj = ObjectDB::get_instance(oid);
if (!obj)
@@ -951,10 +894,9 @@ Variant KinematicBody::_get_collider() const {
return obj;
}
-
bool KinematicBody::_ignores_mode(PhysicsServer::BodyMode p_mode) const {
- switch(p_mode) {
+ switch (p_mode) {
case PhysicsServer::BODY_MODE_STATIC: return !collide_static;
case PhysicsServer::BODY_MODE_KINEMATIC: return !collide_kinematic;
case PhysicsServer::BODY_MODE_RIGID: return !collide_rigid;
@@ -964,7 +906,7 @@ bool KinematicBody::_ignores_mode(PhysicsServer::BodyMode p_mode) const {
return true;
}
-Vector3 KinematicBody::move(const Vector3& p_motion) {
+Vector3 KinematicBody::move(const Vector3 &p_motion) {
//give me back regular physics engine logic
//this is madness
@@ -973,32 +915,30 @@ Vector3 KinematicBody::move(const Vector3& p_motion) {
//this took about a week to get right..
//but is it right? who knows at this point..
-
- colliding=false;
- ERR_FAIL_COND_V(!is_inside_tree(),Vector3());
+ colliding = false;
+ ERR_FAIL_COND_V(!is_inside_tree(), Vector3());
PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(get_world()->get_space());
- ERR_FAIL_COND_V(!dss,Vector3());
- const int max_shapes=32;
- Vector3 sr[max_shapes*2];
+ ERR_FAIL_COND_V(!dss, Vector3());
+ const int max_shapes = 32;
+ Vector3 sr[max_shapes * 2];
int res_shapes;
Set<RID> exclude;
exclude.insert(get_rid());
-
//recover first
- int recover_attempts=4;
+ int recover_attempts = 4;
- bool collided=false;
- uint32_t mask=0;
+ bool collided = false;
+ uint32_t mask = 0;
if (collide_static)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY;
if (collide_kinematic)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
if (collide_rigid)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY;
if (collide_character)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
//print_line("motion: "+p_motion+" margin: "+rtos(margin));
@@ -1010,31 +950,28 @@ Vector3 KinematicBody::move(const Vector3& p_motion) {
do {
//motion recover
- for(int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
if (is_shape_set_as_trigger(i))
continue;
- if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i),m,sr,max_shapes,res_shapes,exclude,get_collision_layer(),mask)) {
- collided=true;
+ if (dss->collide_shape(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), m, sr, max_shapes, res_shapes, exclude, get_collision_layer(), mask)) {
+ collided = true;
}
-
}
-
-
if (!collided)
break;
//print_line("have to recover");
Vector3 recover_motion;
- bool all_outside=true;
- for(int j=0;j<8;j++) {
- for(int i=0;i<res_shapes;i++) {
+ bool all_outside = true;
+ for (int j = 0; j < 8; j++) {
+ for (int i = 0; i < res_shapes; i++) {
- Vector3 a = sr[i*2+0];
- Vector3 b = sr[i*2+1];
- //print_line(String()+a+" -> "+b);
+ Vector3 a = sr[i * 2 + 0];
+ Vector3 b = sr[i * 2 + 1];
+//print_line(String()+a+" -> "+b);
#if 0
float d = a.distance_to(b);
@@ -1045,29 +982,27 @@ Vector3 KinematicBody::move(const Vector3& p_motion) {
recover_motion+=(b-a)*0.2;
#else
float dist = a.distance_to(b);
- if (dist>CMP_EPSILON) {
- Vector3 norm = (b-a).normalized();
- if (dist>margin*0.5)
- all_outside=false;
+ if (dist > CMP_EPSILON) {
+ Vector3 norm = (b - a).normalized();
+ if (dist > margin * 0.5)
+ all_outside = false;
float adv = norm.dot(recover_motion);
//print_line(itos(i)+" dist: "+rtos(dist)+" adv: "+rtos(adv));
- recover_motion+=norm*MAX(dist-adv,0)*0.4;
+ recover_motion += norm * MAX(dist - adv, 0) * 0.4;
}
#endif
-
}
}
-
- if (recover_motion==Vector3()) {
- collided=false;
+ if (recover_motion == Vector3()) {
+ collided = false;
break;
}
//print_line("**** RECOVER: "+recover_motion);
Transform gt = get_global_transform();
- gt.origin+=recover_motion;
+ gt.origin += recover_motion;
set_global_transform(gt);
recover_attempts--;
@@ -1077,133 +1012,127 @@ Vector3 KinematicBody::move(const Vector3& p_motion) {
} while (recover_attempts);
-
//move second
float safe = 1.0;
float unsafe = 1.0;
- int best_shape=-1;
+ int best_shape = -1;
PhysicsDirectSpaceState::ShapeRestInfo rest;
//print_line("pos: "+get_global_transform().origin);
//print_line("motion: "+p_motion);
-
- for(int i=0;i<get_shape_count();i++) {
-
+ for (int i = 0; i < get_shape_count(); i++) {
if (is_shape_set_as_trigger(i))
continue;
- float lsafe,lunsafe;
+ float lsafe, lunsafe;
PhysicsDirectSpaceState::ShapeRestInfo lrest;
- bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion,0, lsafe,lunsafe,exclude,get_collision_layer(),mask,&lrest);
+ bool valid = dss->cast_motion(get_shape(i)->get_rid(), get_global_transform() * get_shape_transform(i), p_motion, 0, lsafe, lunsafe, exclude, get_collision_layer(), mask, &lrest);
//print_line("shape: "+itos(i)+" travel:"+rtos(ltravel));
if (!valid) {
- safe=0;
- unsafe=0;
- best_shape=i; //sadly it's the best
+ safe = 0;
+ unsafe = 0;
+ best_shape = i; //sadly it's the best
//print_line("initial stuck");
break;
}
- if (lsafe==1.0) {
+ if (lsafe == 1.0) {
//print_line("initial free");
continue;
}
if (lsafe < safe) {
//print_line("initial at "+rtos(lsafe));
- safe=lsafe;
- safe=MAX(0,lsafe-0.01);
- unsafe=lunsafe;
- best_shape=i;
- rest=lrest;
+ safe = lsafe;
+ safe = MAX(0, lsafe - 0.01);
+ unsafe = lunsafe;
+ best_shape = i;
+ rest = lrest;
}
}
-
//print_line("best shape: "+itos(best_shape)+" motion "+p_motion);
- if (safe>=1) {
+ if (safe >= 1) {
//not collided
- colliding=false;
+ colliding = false;
} else {
- colliding=true;
+ colliding = true;
- if (true || (safe==0 && unsafe==0)) { //use it always because it's more precise than GJK
+ if (true || (safe == 0 && unsafe == 0)) { //use it always because it's more precise than GJK
//no advance, use rest info from collision
Transform ugt = get_global_transform();
- ugt.origin+=p_motion*unsafe;
+ ugt.origin += p_motion * unsafe;
PhysicsDirectSpaceState::ShapeRestInfo rest_info;
- bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt*get_shape_transform(best_shape), m,&rest,exclude,get_collision_layer(),mask);
+ bool c2 = dss->rest_info(get_shape(best_shape)->get_rid(), ugt * get_shape_transform(best_shape), m, &rest, exclude, get_collision_layer(), mask);
if (!c2) {
//should not happen, but floating point precision is so weird..
- colliding=false;
+ colliding = false;
}
//print_line("Rest Travel: "+rest.normal);
-
}
if (colliding) {
- collision=rest.point;
- normal=rest.normal;
- collider=rest.collider_id;
- collider_vel=rest.linear_velocity;
- collider_shape=rest.shape;
+ collision = rest.point;
+ normal = rest.normal;
+ collider = rest.collider_id;
+ collider_vel = rest.linear_velocity;
+ collider_shape = rest.shape;
}
}
- Vector3 motion=p_motion*safe;
+ Vector3 motion = p_motion * safe;
/*
if (colliding)
motion+=normal*0.001;
*/
Transform gt = get_global_transform();
- gt.origin+=motion;
+ gt.origin += motion;
set_global_transform(gt);
- return p_motion-motion;
-
+ return p_motion - motion;
}
-Vector3 KinematicBody::move_to(const Vector3& p_position) {
+Vector3 KinematicBody::move_to(const Vector3 &p_position) {
- return move(p_position-get_global_transform().origin);
+ return move(p_position - get_global_transform().origin);
}
-bool KinematicBody::can_teleport_to(const Vector3& p_position) {
+bool KinematicBody::can_teleport_to(const Vector3 &p_position) {
- ERR_FAIL_COND_V(!is_inside_tree(),false);
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(get_world()->get_space());
- ERR_FAIL_COND_V(!dss,false);
+ ERR_FAIL_COND_V(!dss, false);
- uint32_t mask=0;
+ uint32_t mask = 0;
if (collide_static)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_STATIC_BODY;
if (collide_kinematic)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_KINEMATIC_BODY;
if (collide_rigid)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_RIGID_BODY;
if (collide_character)
- mask|=PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
+ mask |= PhysicsDirectSpaceState::TYPE_MASK_CHARACTER_BODY;
- Transform xform=get_global_transform();
- xform.origin=p_position;
+ Transform xform = get_global_transform();
+ xform.origin = p_position;
Set<RID> exclude;
exclude.insert(get_rid());
- for(int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
if (is_shape_set_as_trigger(i))
continue;
- bool col = dss->intersect_shape(get_shape(i)->get_rid(), xform * get_shape_transform(i),0,NULL,1,exclude,get_collision_layer(),mask);
+ bool col = dss->intersect_shape(get_shape(i)->get_rid(), xform * get_shape_transform(i), 0, NULL, 1, exclude, get_collision_layer(), mask);
if (col)
return false;
}
@@ -1213,21 +1142,19 @@ bool KinematicBody::can_teleport_to(const Vector3& p_position) {
bool KinematicBody::is_colliding() const {
- ERR_FAIL_COND_V(!is_inside_tree(),false);
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
return colliding;
}
Vector3 KinematicBody::get_collision_pos() const {
- ERR_FAIL_COND_V(!colliding,Vector3());
+ ERR_FAIL_COND_V(!colliding, Vector3());
return collision;
-
}
Vector3 KinematicBody::get_collision_normal() const {
- ERR_FAIL_COND_V(!colliding,Vector3());
+ ERR_FAIL_COND_V(!colliding, Vector3());
return normal;
-
}
Vector3 KinematicBody::get_collider_velocity() const {
@@ -1237,18 +1164,17 @@ Vector3 KinematicBody::get_collider_velocity() const {
ObjectID KinematicBody::get_collider() const {
- ERR_FAIL_COND_V(!colliding,0);
+ ERR_FAIL_COND_V(!colliding, 0);
return collider;
}
int KinematicBody::get_collider_shape() const {
- ERR_FAIL_COND_V(!colliding,-1);
+ ERR_FAIL_COND_V(!colliding, -1);
return collider_shape;
-
}
void KinematicBody::set_collide_with_static_bodies(bool p_enable) {
- collide_static=p_enable;
+ collide_static = p_enable;
}
bool KinematicBody::can_collide_with_static_bodies() const {
@@ -1257,19 +1183,16 @@ bool KinematicBody::can_collide_with_static_bodies() const {
void KinematicBody::set_collide_with_rigid_bodies(bool p_enable) {
- collide_rigid=p_enable;
-
+ collide_rigid = p_enable;
}
bool KinematicBody::can_collide_with_rigid_bodies() const {
-
return collide_rigid;
}
void KinematicBody::set_collide_with_kinematic_bodies(bool p_enable) {
- collide_kinematic=p_enable;
-
+ collide_kinematic = p_enable;
}
bool KinematicBody::can_collide_with_kinematic_bodies() const {
@@ -1278,7 +1201,7 @@ bool KinematicBody::can_collide_with_kinematic_bodies() const {
void KinematicBody::set_collide_with_character_bodies(bool p_enable) {
- collide_character=p_enable;
+ collide_character = p_enable;
}
bool KinematicBody::can_collide_with_character_bodies() const {
@@ -1287,70 +1210,63 @@ bool KinematicBody::can_collide_with_character_bodies() const {
void KinematicBody::set_collision_margin(float p_margin) {
- margin=p_margin;
+ margin = p_margin;
}
-float KinematicBody::get_collision_margin() const{
+float KinematicBody::get_collision_margin() const {
return margin;
}
void KinematicBody::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("move", "rel_vec"), &KinematicBody::move);
+ ClassDB::bind_method(D_METHOD("move_to", "position"), &KinematicBody::move_to);
- ClassDB::bind_method(D_METHOD("move","rel_vec"),&KinematicBody::move);
- ClassDB::bind_method(D_METHOD("move_to","position"),&KinematicBody::move_to);
-
- ClassDB::bind_method(D_METHOD("can_teleport_to","position"),&KinematicBody::can_teleport_to);
-
- ClassDB::bind_method(D_METHOD("is_colliding"),&KinematicBody::is_colliding);
-
- ClassDB::bind_method(D_METHOD("get_collision_pos"),&KinematicBody::get_collision_pos);
- ClassDB::bind_method(D_METHOD("get_collision_normal"),&KinematicBody::get_collision_normal);
- ClassDB::bind_method(D_METHOD("get_collider_velocity"),&KinematicBody::get_collider_velocity);
- ClassDB::bind_method(D_METHOD("get_collider:Variant"),&KinematicBody::_get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_shape"),&KinematicBody::get_collider_shape);
+ ClassDB::bind_method(D_METHOD("can_teleport_to", "position"), &KinematicBody::can_teleport_to);
+ ClassDB::bind_method(D_METHOD("is_colliding"), &KinematicBody::is_colliding);
- ClassDB::bind_method(D_METHOD("set_collide_with_static_bodies","enable"),&KinematicBody::set_collide_with_static_bodies);
- ClassDB::bind_method(D_METHOD("can_collide_with_static_bodies"),&KinematicBody::can_collide_with_static_bodies);
+ ClassDB::bind_method(D_METHOD("get_collision_pos"), &KinematicBody::get_collision_pos);
+ ClassDB::bind_method(D_METHOD("get_collision_normal"), &KinematicBody::get_collision_normal);
+ ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicBody::get_collider_velocity);
+ ClassDB::bind_method(D_METHOD("get_collider:Variant"), &KinematicBody::_get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicBody::get_collider_shape);
- ClassDB::bind_method(D_METHOD("set_collide_with_kinematic_bodies","enable"),&KinematicBody::set_collide_with_kinematic_bodies);
- ClassDB::bind_method(D_METHOD("can_collide_with_kinematic_bodies"),&KinematicBody::can_collide_with_kinematic_bodies);
+ ClassDB::bind_method(D_METHOD("set_collide_with_static_bodies", "enable"), &KinematicBody::set_collide_with_static_bodies);
+ ClassDB::bind_method(D_METHOD("can_collide_with_static_bodies"), &KinematicBody::can_collide_with_static_bodies);
- ClassDB::bind_method(D_METHOD("set_collide_with_rigid_bodies","enable"),&KinematicBody::set_collide_with_rigid_bodies);
- ClassDB::bind_method(D_METHOD("can_collide_with_rigid_bodies"),&KinematicBody::can_collide_with_rigid_bodies);
+ ClassDB::bind_method(D_METHOD("set_collide_with_kinematic_bodies", "enable"), &KinematicBody::set_collide_with_kinematic_bodies);
+ ClassDB::bind_method(D_METHOD("can_collide_with_kinematic_bodies"), &KinematicBody::can_collide_with_kinematic_bodies);
- ClassDB::bind_method(D_METHOD("set_collide_with_character_bodies","enable"),&KinematicBody::set_collide_with_character_bodies);
- ClassDB::bind_method(D_METHOD("can_collide_with_character_bodies"),&KinematicBody::can_collide_with_character_bodies);
+ ClassDB::bind_method(D_METHOD("set_collide_with_rigid_bodies", "enable"), &KinematicBody::set_collide_with_rigid_bodies);
+ ClassDB::bind_method(D_METHOD("can_collide_with_rigid_bodies"), &KinematicBody::can_collide_with_rigid_bodies);
- ClassDB::bind_method(D_METHOD("set_collision_margin","pixels"),&KinematicBody::set_collision_margin);
- ClassDB::bind_method(D_METHOD("get_collision_margin","pixels"),&KinematicBody::get_collision_margin);
-
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/static"),"set_collide_with_static_bodies","can_collide_with_static_bodies");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/kinematic"),"set_collide_with_kinematic_bodies","can_collide_with_kinematic_bodies");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/rigid"),"set_collide_with_rigid_bodies","can_collide_with_rigid_bodies");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collide_with/character"),"set_collide_with_character_bodies","can_collide_with_character_bodies");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"collision/margin",PROPERTY_HINT_RANGE,"0.001,256,0.001"),"set_collision_margin","get_collision_margin");
+ ClassDB::bind_method(D_METHOD("set_collide_with_character_bodies", "enable"), &KinematicBody::set_collide_with_character_bodies);
+ ClassDB::bind_method(D_METHOD("can_collide_with_character_bodies"), &KinematicBody::can_collide_with_character_bodies);
+ ClassDB::bind_method(D_METHOD("set_collision_margin", "pixels"), &KinematicBody::set_collision_margin);
+ ClassDB::bind_method(D_METHOD("get_collision_margin", "pixels"), &KinematicBody::get_collision_margin);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/static"), "set_collide_with_static_bodies", "can_collide_with_static_bodies");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/kinematic"), "set_collide_with_kinematic_bodies", "can_collide_with_kinematic_bodies");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/rigid"), "set_collide_with_rigid_bodies", "can_collide_with_rigid_bodies");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collide_with/character"), "set_collide_with_character_bodies", "can_collide_with_character_bodies");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision/margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_collision_margin", "get_collision_margin");
}
-KinematicBody::KinematicBody() : PhysicsBody(PhysicsServer::BODY_MODE_KINEMATIC){
+KinematicBody::KinematicBody()
+ : PhysicsBody(PhysicsServer::BODY_MODE_KINEMATIC) {
- collide_static=true;
- collide_rigid=true;
- collide_kinematic=true;
- collide_character=true;
+ collide_static = true;
+ collide_rigid = true;
+ collide_kinematic = true;
+ collide_character = true;
- colliding=false;
- collider=0;
- margin=0.001;
- collider_shape=0;
+ colliding = false;
+ collider = 0;
+ margin = 0.001;
+ collider_shape = 0;
}
-KinematicBody::~KinematicBody() {
-
-
+KinematicBody::~KinematicBody() {
}
-
-
diff --git a/scene/3d/physics_body.h b/scene/3d/physics_body.h
index 86be98f81e..1cef946836 100644
--- a/scene/3d/physics_body.h
+++ b/scene/3d/physics_body.h
@@ -33,10 +33,9 @@
#include "servers/physics_server.h"
#include "vset.h"
-
class PhysicsBody : public CollisionObject {
- GDCLASS(PhysicsBody,CollisionObject);
+ GDCLASS(PhysicsBody, CollisionObject);
uint32_t layer_mask;
uint32_t collision_mask;
@@ -45,12 +44,11 @@ class PhysicsBody : public CollisionObject {
uint32_t _get_layers() const;
protected:
-
static void _bind_methods();
void _notification(int p_what);
PhysicsBody(PhysicsServer::BodyMode p_mode);
-public:
+public:
virtual Vector3 get_linear_velocity() const;
virtual Vector3 get_angular_velocity() const;
virtual float get_inverse_mass() const;
@@ -67,18 +65,15 @@ public:
void set_collision_mask_bit(int p_bit, bool p_value);
bool get_collision_mask_bit(int p_bit) const;
- void add_collision_exception_with(Node* p_node); //must be physicsbody
- void remove_collision_exception_with(Node* p_node);
-
-
+ void add_collision_exception_with(Node *p_node); //must be physicsbody
+ void remove_collision_exception_with(Node *p_node);
PhysicsBody();
-
};
class StaticBody : public PhysicsBody {
- GDCLASS(StaticBody,PhysicsBody);
+ GDCLASS(StaticBody, PhysicsBody);
Vector3 constant_linear_velocity;
Vector3 constant_angular_velocity;
@@ -86,37 +81,31 @@ class StaticBody : public PhysicsBody {
real_t bounce;
real_t friction;
-
protected:
-
static void _bind_methods();
public:
-
-
void set_friction(real_t p_friction);
real_t get_friction() const;
void set_bounce(real_t p_bounce);
real_t get_bounce() const;
-
- void set_constant_linear_velocity(const Vector3& p_vel);
- void set_constant_angular_velocity(const Vector3& p_vel);
+ void set_constant_linear_velocity(const Vector3 &p_vel);
+ void set_constant_angular_velocity(const Vector3 &p_vel);
Vector3 get_constant_linear_velocity() const;
Vector3 get_constant_angular_velocity() const;
StaticBody();
~StaticBody();
-
};
class RigidBody : public PhysicsBody {
- GDCLASS(RigidBody,PhysicsBody);
-public:
+ GDCLASS(RigidBody, PhysicsBody);
+public:
enum Mode {
MODE_RIGID,
MODE_STATIC,
@@ -132,7 +121,6 @@ public:
};
private:
-
bool can_sleep;
PhysicsDirectBodyState *state;
Mode mode;
@@ -142,7 +130,7 @@ private:
real_t friction;
Vector3 linear_velocity;
- Vector3 angular_velocity;
+ Vector3 angular_velocity;
real_t gravity_scale;
real_t linear_damp;
real_t angular_damp;
@@ -152,33 +140,32 @@ private:
AxisLock axis_lock;
-
int max_contacts_reported;
bool custom_integrator;
-
struct ShapePair {
int body_shape;
int local_shape;
bool tagged;
- bool operator<(const ShapePair& p_sp) const {
- if (body_shape==p_sp.body_shape)
+ bool operator<(const ShapePair &p_sp) const {
+ if (body_shape == p_sp.body_shape)
return local_shape < p_sp.local_shape;
else
return body_shape < p_sp.body_shape;
}
ShapePair() {}
- ShapePair(int p_bs, int p_ls) { body_shape=p_bs; local_shape=p_ls; }
+ ShapePair(int p_bs, int p_ls) {
+ body_shape = p_bs;
+ local_shape = p_ls;
+ }
};
struct RigidBody_RemoveAction {
-
ObjectID body_id;
ShapePair pair;
-
};
struct BodyState {
@@ -190,33 +177,28 @@ private:
struct ContactMonitor {
bool locked;
- Map<ObjectID,BodyState> body_map;
-
+ Map<ObjectID, BodyState> body_map;
};
-
ContactMonitor *contact_monitor;
void _body_enter_tree(ObjectID p_id);
void _body_exit_tree(ObjectID p_id);
-
- void _body_inout(int p_status, ObjectID p_instance, int p_body_shape,int p_local_shape);
+ void _body_inout(int p_status, ObjectID p_instance, int p_body_shape, int p_local_shape);
void _direct_state_changed(Object *p_state);
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_mode(Mode p_mode);
Mode get_mode() const;
void set_mass(real_t p_mass);
real_t get_mass() const;
- virtual float get_inverse_mass() const { return 1.0/mass; }
+ virtual float get_inverse_mass() const { return 1.0 / mass; }
void set_weight(real_t p_weight);
real_t get_weight() const;
@@ -227,13 +209,13 @@ public:
void set_bounce(real_t p_bounce);
real_t get_bounce() const;
- void set_linear_velocity(const Vector3& p_velocity);
+ void set_linear_velocity(const Vector3 &p_velocity);
Vector3 get_linear_velocity() const;
- void set_axis_velocity(const Vector3& p_axis);
+ void set_axis_velocity(const Vector3 &p_axis);
- void set_angular_velocity(const Vector3&p_velocity);
- Vector3 get_angular_velocity() const;
+ void set_angular_velocity(const Vector3 &p_velocity);
+ Vector3 get_angular_velocity() const;
void set_gravity_scale(real_t p_gravity_scale);
real_t get_gravity_scale() const;
@@ -244,7 +226,6 @@ public:
void set_angular_damp(real_t p_angular_damp);
real_t get_angular_damp() const;
-
void set_use_custom_integrator(bool p_enable);
bool is_using_custom_integrator();
@@ -268,23 +249,18 @@ public:
Array get_colliding_bodies() const;
- void apply_impulse(const Vector3& p_pos, const Vector3& p_impulse);
+ void apply_impulse(const Vector3 &p_pos, const Vector3 &p_impulse);
RigidBody();
~RigidBody();
-
};
VARIANT_ENUM_CAST(RigidBody::Mode);
VARIANT_ENUM_CAST(RigidBody::AxisLock);
-
-
-
-
class KinematicBody : public PhysicsBody {
- GDCLASS(KinematicBody,PhysicsBody);
+ GDCLASS(KinematicBody, PhysicsBody);
float margin;
bool collide_static;
@@ -299,26 +275,24 @@ class KinematicBody : public PhysicsBody {
ObjectID collider;
int collider_shape;
-
-
Variant _get_collider() const;
_FORCE_INLINE_ bool _ignores_mode(PhysicsServer::BodyMode) const;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
enum {
SLIDE_FLAG_FLOOR,
SLIDE_FLAG_WALL,
SLIDE_FLAG_ROOF
};
- Vector3 move(const Vector3& p_motion);
- Vector3 move_to(const Vector3& p_position);
+ Vector3 move(const Vector3 &p_motion);
+ Vector3 move_to(const Vector3 &p_position);
- bool can_teleport_to(const Vector3& p_position);
+ bool can_teleport_to(const Vector3 &p_position);
bool is_colliding() const;
Vector3 get_collision_pos() const;
Vector3 get_collision_normal() const;
@@ -343,7 +317,6 @@ public:
KinematicBody();
~KinematicBody();
-
};
#endif // PHYSICS_BODY__H
diff --git a/scene/3d/physics_joint.cpp b/scene/3d/physics_joint.cpp
index d48d75f464..8c20b003f8 100644
--- a/scene/3d/physics_joint.cpp
+++ b/scene/3d/physics_joint.cpp
@@ -28,101 +28,89 @@
/*************************************************************************/
#include "physics_joint.h"
-
-
void Joint::_update_joint(bool p_only_free) {
-
if (joint.is_valid()) {
if (ba.is_valid() && bb.is_valid()) {
if (exclude_from_collision)
- PhysicsServer::get_singleton()->body_add_collision_exception(ba,bb);
+ PhysicsServer::get_singleton()->body_add_collision_exception(ba, bb);
else
- PhysicsServer::get_singleton()->body_remove_collision_exception(ba,bb);
-
+ PhysicsServer::get_singleton()->body_remove_collision_exception(ba, bb);
}
PhysicsServer::get_singleton()->free(joint);
- joint=RID();
- ba=RID();
- bb=RID();
+ joint = RID();
+ ba = RID();
+ bb = RID();
}
if (p_only_free || !is_inside_tree())
return;
- Node *node_a = has_node( get_node_a() ) ? get_node( get_node_a() ) : (Node*)NULL;
- Node *node_b = has_node( get_node_b() ) ? get_node( get_node_b() ) : (Node*)NULL;
+ Node *node_a = has_node(get_node_a()) ? get_node(get_node_a()) : (Node *)NULL;
+ Node *node_b = has_node(get_node_b()) ? get_node(get_node_b()) : (Node *)NULL;
if (!node_a && !node_b)
return;
- PhysicsBody *body_a=node_a ? node_a->cast_to<PhysicsBody>() : (PhysicsBody*)NULL;
- PhysicsBody *body_b=node_b ? node_b->cast_to<PhysicsBody>() : (PhysicsBody*)NULL;
+ PhysicsBody *body_a = node_a ? node_a->cast_to<PhysicsBody>() : (PhysicsBody *)NULL;
+ PhysicsBody *body_b = node_b ? node_b->cast_to<PhysicsBody>() : (PhysicsBody *)NULL;
if (!body_a && !body_b)
return;
if (!body_a) {
- SWAP(body_a,body_b);
+ SWAP(body_a, body_b);
} else if (body_b) {
//add a collision exception between both
- PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
+ PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
}
- joint = _configure_joint(body_a,body_b);
+ joint = _configure_joint(body_a, body_b);
if (joint.is_valid())
- PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority);
+ PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority);
if (body_b && joint.is_valid()) {
- ba=body_a->get_rid();
- bb=body_b->get_rid();
- PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(),body_b->get_rid());
-
+ ba = body_a->get_rid();
+ bb = body_b->get_rid();
+ PhysicsServer::get_singleton()->body_add_collision_exception(body_a->get_rid(), body_b->get_rid());
}
-
}
+void Joint::set_node_a(const NodePath &p_node_a) {
-void Joint::set_node_a(const NodePath& p_node_a) {
-
-
- if (a==p_node_a)
+ if (a == p_node_a)
return;
- a=p_node_a;
+ a = p_node_a;
_update_joint();
}
-NodePath Joint::get_node_a() const{
+NodePath Joint::get_node_a() const {
return a;
}
-void Joint::set_node_b(const NodePath& p_node_b){
+void Joint::set_node_b(const NodePath &p_node_b) {
- if (b==p_node_b)
+ if (b == p_node_b)
return;
- b=p_node_b;
+ b = p_node_b;
_update_joint();
-
}
-NodePath Joint::get_node_b() const{
-
+NodePath Joint::get_node_b() const {
return b;
}
-
void Joint::set_solver_priority(int p_priority) {
- solver_priority=p_priority;
+ solver_priority = p_priority;
if (joint.is_valid())
- PhysicsServer::get_singleton()->joint_set_solver_priority(joint,solver_priority);
-
+ PhysicsServer::get_singleton()->joint_set_solver_priority(joint, solver_priority);
}
int Joint::get_solver_priority() const {
@@ -130,10 +118,9 @@ int Joint::get_solver_priority() const {
return solver_priority;
}
-
void Joint::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
_update_joint();
@@ -142,95 +129,83 @@ void Joint::_notification(int p_what) {
if (joint.is_valid()) {
_update_joint(true);
//PhysicsServer::get_singleton()->free(joint);
- joint=RID();
+ joint = RID();
}
} break;
-
}
-
}
-
void Joint::set_exclude_nodes_from_collision(bool p_enable) {
- if (exclude_from_collision==p_enable)
+ if (exclude_from_collision == p_enable)
return;
- exclude_from_collision=p_enable;
+ exclude_from_collision = p_enable;
_update_joint();
}
-bool Joint::get_exclude_nodes_from_collision() const{
+bool Joint::get_exclude_nodes_from_collision() const {
return exclude_from_collision;
}
void Joint::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_node_a", "node"), &Joint::set_node_a);
+ ClassDB::bind_method(D_METHOD("get_node_a"), &Joint::get_node_a);
- ClassDB::bind_method( D_METHOD("set_node_a","node"), &Joint::set_node_a );
- ClassDB::bind_method( D_METHOD("get_node_a"), &Joint::get_node_a );
-
- ClassDB::bind_method( D_METHOD("set_node_b","node"), &Joint::set_node_b );
- ClassDB::bind_method( D_METHOD("get_node_b"), &Joint::get_node_b );
-
- ClassDB::bind_method( D_METHOD("set_solver_priority","priority"), &Joint::set_solver_priority );
- ClassDB::bind_method( D_METHOD("get_solver_priority"), &Joint::get_solver_priority );
+ ClassDB::bind_method(D_METHOD("set_node_b", "node"), &Joint::set_node_b);
+ ClassDB::bind_method(D_METHOD("get_node_b"), &Joint::get_node_b);
- ClassDB::bind_method( D_METHOD("set_exclude_nodes_from_collision","enable"), &Joint::set_exclude_nodes_from_collision );
- ClassDB::bind_method( D_METHOD("get_exclude_nodes_from_collision"), &Joint::get_exclude_nodes_from_collision );
-
- ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_a"), "set_node_a","get_node_a") ;
- ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "nodes/node_b"), "set_node_b","get_node_b") ;
- ADD_PROPERTY( PropertyInfo( Variant::INT, "solver/priority",PROPERTY_HINT_RANGE,"1,8,1"), "set_solver_priority","get_solver_priority") ;
-
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision","get_exclude_nodes_from_collision") ;
+ ClassDB::bind_method(D_METHOD("set_solver_priority", "priority"), &Joint::set_solver_priority);
+ ClassDB::bind_method(D_METHOD("get_solver_priority"), &Joint::get_solver_priority);
+ ClassDB::bind_method(D_METHOD("set_exclude_nodes_from_collision", "enable"), &Joint::set_exclude_nodes_from_collision);
+ ClassDB::bind_method(D_METHOD("get_exclude_nodes_from_collision"), &Joint::get_exclude_nodes_from_collision);
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_a"), "set_node_a", "get_node_a");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "nodes/node_b"), "set_node_b", "get_node_b");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "solver/priority", PROPERTY_HINT_RANGE, "1,8,1"), "set_solver_priority", "get_solver_priority");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision/exclude_nodes"), "set_exclude_nodes_from_collision", "get_exclude_nodes_from_collision");
}
-
-
Joint::Joint() {
- exclude_from_collision=true;
- solver_priority=1;
+ exclude_from_collision = true;
+ solver_priority = 1;
set_notify_transform(true);
}
-
///////////////////////////////////
void PinJoint::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_param","param","value"),&PinJoint::set_param);
- ClassDB::bind_method(D_METHOD("get_param","param"),&PinJoint::get_param);
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &PinJoint::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &PinJoint::get_param);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_BIAS );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/damping",PROPERTY_HINT_RANGE,"0.01,8.0,0.01"),"set_param","get_param", PARAM_DAMPING );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/impulse_clamp",PROPERTY_HINT_RANGE,"0.0,64.0,0.01"),"set_param","get_param", PARAM_IMPULSE_CLAMP );
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/damping", PROPERTY_HINT_RANGE, "0.01,8.0,0.01"), "set_param", "get_param", PARAM_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/impulse_clamp", PROPERTY_HINT_RANGE, "0.0,64.0,0.01"), "set_param", "get_param", PARAM_IMPULSE_CLAMP);
- BIND_CONSTANT( PARAM_BIAS );
- BIND_CONSTANT( PARAM_DAMPING );
- BIND_CONSTANT( PARAM_IMPULSE_CLAMP );
+ BIND_CONSTANT(PARAM_BIAS);
+ BIND_CONSTANT(PARAM_DAMPING);
+ BIND_CONSTANT(PARAM_IMPULSE_CLAMP);
}
-void PinJoint::set_param(Param p_param,float p_value){
+void PinJoint::set_param(Param p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,3);
- params[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, 3);
+ params[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(),PhysicsServer::PinJointParam(p_param),p_value);
+ PhysicsServer::get_singleton()->pin_joint_set_param(get_joint(), PhysicsServer::PinJointParam(p_param), p_value);
}
-float PinJoint::get_param(Param p_param) const{
+float PinJoint::get_param(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,3,0);
+ ERR_FAIL_INDEX_V(p_param, 3, 0);
return params[p_param];
}
-
-RID PinJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
-
+RID PinJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {
Vector3 pinpos = get_global_transform().origin;
Vector3 local_a = body_a->get_global_transform().affine_inverse().xform(pinpos);
@@ -239,37 +214,29 @@ RID PinJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
if (body_b)
local_b = body_b->get_global_transform().affine_inverse().xform(pinpos);
else
- local_b=pinpos;
+ local_b = pinpos;
- RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
- for(int i=0;i<3;i++) {
- PhysicsServer::get_singleton()->pin_joint_set_param(j,PhysicsServer::PinJointParam(i),params[i]);
+ RID j = PhysicsServer::get_singleton()->joint_create_pin(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
+ for (int i = 0; i < 3; i++) {
+ PhysicsServer::get_singleton()->pin_joint_set_param(j, PhysicsServer::PinJointParam(i), params[i]);
}
return j;
}
-
PinJoint::PinJoint() {
- params[PARAM_BIAS]=0.3;
- params[PARAM_DAMPING]=1;
- params[PARAM_IMPULSE_CLAMP]=0;
-
+ params[PARAM_BIAS] = 0.3;
+ params[PARAM_DAMPING] = 1;
+ params[PARAM_IMPULSE_CLAMP] = 0;
}
-
-
-
/////////////////////////////////////////////////
-
-
///////////////////////////////////
-
void HingeJoint::_set_upper_limit(float p_limit) {
- set_param(PARAM_LIMIT_UPPER,Math::deg2rad(p_limit));
+ set_param(PARAM_LIMIT_UPPER, Math::deg2rad(p_limit));
}
float HingeJoint::_get_upper_limit() const {
@@ -279,95 +246,87 @@ float HingeJoint::_get_upper_limit() const {
void HingeJoint::_set_lower_limit(float p_limit) {
- set_param(PARAM_LIMIT_LOWER,Math::deg2rad(p_limit));
-
+ set_param(PARAM_LIMIT_LOWER, Math::deg2rad(p_limit));
}
float HingeJoint::_get_lower_limit() const {
return Math::rad2deg(get_param(PARAM_LIMIT_LOWER));
-
}
-
void HingeJoint::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_param","param","value"),&HingeJoint::set_param);
- ClassDB::bind_method(D_METHOD("get_param","param"),&HingeJoint::get_param);
-
- ClassDB::bind_method(D_METHOD("set_flag","flag","enabled"),&HingeJoint::set_flag);
- ClassDB::bind_method(D_METHOD("get_flag","flag"),&HingeJoint::get_flag);
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &HingeJoint::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &HingeJoint::get_param);
- ClassDB::bind_method(D_METHOD("_set_upper_limit","upper_limit"),&HingeJoint::_set_upper_limit);
- ClassDB::bind_method(D_METHOD("_get_upper_limit"),&HingeJoint::_get_upper_limit);
+ ClassDB::bind_method(D_METHOD("set_flag", "flag", "enabled"), &HingeJoint::set_flag);
+ ClassDB::bind_method(D_METHOD("get_flag", "flag"), &HingeJoint::get_flag);
- ClassDB::bind_method(D_METHOD("_set_lower_limit","lower_limit"),&HingeJoint::_set_lower_limit);
- ClassDB::bind_method(D_METHOD("_get_lower_limit"),&HingeJoint::_get_lower_limit);
+ ClassDB::bind_method(D_METHOD("_set_upper_limit", "upper_limit"), &HingeJoint::_set_upper_limit);
+ ClassDB::bind_method(D_METHOD("_get_upper_limit"), &HingeJoint::_get_upper_limit);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_BIAS );
+ ClassDB::bind_method(D_METHOD("_set_lower_limit", "lower_limit"), &HingeJoint::_set_lower_limit);
+ ClassDB::bind_method(D_METHOD("_get_lower_limit"), &HingeJoint::_get_lower_limit);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"angular_limit/enable"),"set_flag","get_flag", FLAG_USE_LIMIT );
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_upper_limit","_get_upper_limit") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_lower_limit","_get_lower_limit") ;
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/bias",PROPERTY_HINT_RANGE,"0.01,0.99,0.01"),"set_param","get_param", PARAM_LIMIT_BIAS );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param","get_param", PARAM_LIMIT_SOFTNESS );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/relaxation",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param","get_param", PARAM_LIMIT_RELAXATION );
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "params/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_BIAS);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"motor/enable"),"set_flag","get_flag", FLAG_ENABLE_MOTOR );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/target_velocity",PROPERTY_HINT_RANGE,"0.01,4096,0.01"),"set_param","get_param", PARAM_MOTOR_TARGET_VELOCITY );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"motor/max_impulse",PROPERTY_HINT_RANGE,"0.01,1024,0.01"),"set_param","get_param", PARAM_MOTOR_MAX_IMPULSE);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit/enable"), "set_flag", "get_flag", FLAG_USE_LIMIT);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit", "_get_upper_limit");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit", "_get_lower_limit");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/bias", PROPERTY_HINT_RANGE, "0.01,0.99,0.01"), "set_param", "get_param", PARAM_LIMIT_BIAS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/relaxation", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param", "get_param", PARAM_LIMIT_RELAXATION);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "motor/enable"), "set_flag", "get_flag", FLAG_ENABLE_MOTOR);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/target_velocity", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_param", "get_param", PARAM_MOTOR_TARGET_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "motor/max_impulse", PROPERTY_HINT_RANGE, "0.01,1024,0.01"), "set_param", "get_param", PARAM_MOTOR_MAX_IMPULSE);
- BIND_CONSTANT( PARAM_BIAS );
- BIND_CONSTANT( PARAM_LIMIT_UPPER );
- BIND_CONSTANT( PARAM_LIMIT_LOWER );
- BIND_CONSTANT( PARAM_LIMIT_BIAS );
- BIND_CONSTANT( PARAM_LIMIT_SOFTNESS );
- BIND_CONSTANT( PARAM_LIMIT_RELAXATION );
- BIND_CONSTANT( PARAM_MOTOR_TARGET_VELOCITY );
- BIND_CONSTANT( PARAM_MOTOR_MAX_IMPULSE );
- BIND_CONSTANT( PARAM_MAX );
-
- BIND_CONSTANT( FLAG_USE_LIMIT );
- BIND_CONSTANT( FLAG_ENABLE_MOTOR );
- BIND_CONSTANT( FLAG_MAX );
+ BIND_CONSTANT(PARAM_BIAS);
+ BIND_CONSTANT(PARAM_LIMIT_UPPER);
+ BIND_CONSTANT(PARAM_LIMIT_LOWER);
+ BIND_CONSTANT(PARAM_LIMIT_BIAS);
+ BIND_CONSTANT(PARAM_LIMIT_SOFTNESS);
+ BIND_CONSTANT(PARAM_LIMIT_RELAXATION);
+ BIND_CONSTANT(PARAM_MOTOR_TARGET_VELOCITY);
+ BIND_CONSTANT(PARAM_MOTOR_MAX_IMPULSE);
+ BIND_CONSTANT(PARAM_MAX);
+ BIND_CONSTANT(FLAG_USE_LIMIT);
+ BIND_CONSTANT(FLAG_ENABLE_MOTOR);
+ BIND_CONSTANT(FLAG_MAX);
}
-void HingeJoint::set_param(Param p_param,float p_value){
+void HingeJoint::set_param(Param p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(),PhysicsServer::HingeJointParam(p_param),p_value);
+ PhysicsServer::get_singleton()->hinge_joint_set_param(get_joint(), PhysicsServer::HingeJointParam(p_param), p_value);
update_gizmo();
-
}
-float HingeJoint::get_param(Param p_param) const{
+float HingeJoint::get_param(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params[p_param];
}
+void HingeJoint::set_flag(Flag p_flag, bool p_value) {
-void HingeJoint::set_flag(Flag p_flag,bool p_value){
-
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- flags[p_flag]=p_value;
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ flags[p_flag] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(),PhysicsServer::HingeJointFlag(p_flag),p_value);
+ PhysicsServer::get_singleton()->hinge_joint_set_flag(get_joint(), PhysicsServer::HingeJointFlag(p_flag), p_value);
update_gizmo();
}
-bool HingeJoint::get_flag(Flag p_flag) const{
+bool HingeJoint::get_flag(Flag p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags[p_flag];
}
-RID HingeJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
-
+RID HingeJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {
Transform gt = get_global_transform();
Transform ainv = body_a->get_global_transform().affine_inverse();
@@ -383,48 +342,39 @@ RID HingeJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
local_b.orthonormalize();
- RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
- for(int i=0;i<PARAM_MAX;i++) {
- PhysicsServer::get_singleton()->hinge_joint_set_param(j,PhysicsServer::HingeJointParam(i),params[i]);
+ RID j = PhysicsServer::get_singleton()->joint_create_hinge(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
+ for (int i = 0; i < PARAM_MAX; i++) {
+ PhysicsServer::get_singleton()->hinge_joint_set_param(j, PhysicsServer::HingeJointParam(i), params[i]);
}
- for(int i=0;i<FLAG_MAX;i++) {
- set_flag(Flag(i),flags[i]);
- PhysicsServer::get_singleton()->hinge_joint_set_flag(j,PhysicsServer::HingeJointFlag(i),flags[i]);
+ for (int i = 0; i < FLAG_MAX; i++) {
+ set_flag(Flag(i), flags[i]);
+ PhysicsServer::get_singleton()->hinge_joint_set_flag(j, PhysicsServer::HingeJointFlag(i), flags[i]);
}
return j;
}
-
HingeJoint::HingeJoint() {
- params[PARAM_BIAS]=0.3;
- params[PARAM_LIMIT_UPPER]=Math_PI*0.5;
- params[PARAM_LIMIT_LOWER]=-Math_PI*0.5;
- params[PARAM_LIMIT_BIAS]=0.3;
- params[PARAM_LIMIT_SOFTNESS]=0.9;
- params[PARAM_LIMIT_RELAXATION]=1.0;
- params[PARAM_MOTOR_TARGET_VELOCITY]=1;
- params[PARAM_MOTOR_MAX_IMPULSE]=1;
-
-
- flags[FLAG_USE_LIMIT]=false;
- flags[FLAG_ENABLE_MOTOR]=false;
+ params[PARAM_BIAS] = 0.3;
+ params[PARAM_LIMIT_UPPER] = Math_PI * 0.5;
+ params[PARAM_LIMIT_LOWER] = -Math_PI * 0.5;
+ params[PARAM_LIMIT_BIAS] = 0.3;
+ params[PARAM_LIMIT_SOFTNESS] = 0.9;
+ params[PARAM_LIMIT_RELAXATION] = 1.0;
+ params[PARAM_MOTOR_TARGET_VELOCITY] = 1;
+ params[PARAM_MOTOR_MAX_IMPULSE] = 1;
+ flags[FLAG_USE_LIMIT] = false;
+ flags[FLAG_ENABLE_MOTOR] = false;
}
-
-
-
/////////////////////////////////////////////////
-
//////////////////////////////////
-
-
void SliderJoint::_set_upper_limit_angular(float p_limit_angular) {
- set_param(PARAM_ANGULAR_LIMIT_UPPER,Math::deg2rad(p_limit_angular));
+ set_param(PARAM_ANGULAR_LIMIT_UPPER, Math::deg2rad(p_limit_angular));
}
float SliderJoint::_get_upper_limit_angular() const {
@@ -434,100 +384,91 @@ float SliderJoint::_get_upper_limit_angular() const {
void SliderJoint::_set_lower_limit_angular(float p_limit_angular) {
- set_param(PARAM_ANGULAR_LIMIT_LOWER,Math::deg2rad(p_limit_angular));
-
+ set_param(PARAM_ANGULAR_LIMIT_LOWER, Math::deg2rad(p_limit_angular));
}
float SliderJoint::_get_lower_limit_angular() const {
return Math::rad2deg(get_param(PARAM_ANGULAR_LIMIT_LOWER));
-
}
-
void SliderJoint::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_param","param","value"),&SliderJoint::set_param);
- ClassDB::bind_method(D_METHOD("get_param","param"),&SliderJoint::get_param);
-
-
- ClassDB::bind_method(D_METHOD("_set_upper_limit_angular","upper_limit_angular"),&SliderJoint::_set_upper_limit_angular);
- ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"),&SliderJoint::_get_upper_limit_angular);
-
- ClassDB::bind_method(D_METHOD("_set_lower_limit_angular","lower_limit_angular"),&SliderJoint::_set_lower_limit_angular);
- ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"),&SliderJoint::_get_lower_limit_angular);
-
-
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/upper_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),"set_param","get_param", PARAM_LINEAR_LIMIT_UPPER);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/lower_distance",PROPERTY_HINT_RANGE,"-1024,1024,0.01"),"set_param","get_param", PARAM_LINEAR_LIMIT_LOWER);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_LIMIT_DAMPING);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_MOTION_DAMPING);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"linear_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_upper_limit_angular","_get_upper_limit_angular") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"angular_limit/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_lower_limit_angular","_get_lower_limit_angular") ;
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_limit/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_LIMIT_DAMPING);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_motion/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_MOTION_DAMPING);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/restitution",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"angular_ortho/damping",PROPERTY_HINT_RANGE,"0,16.0,0.01") ,"set_param","get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING);
-
-
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_UPPER);
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_LOWER);
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS);
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_RESTITUTION);
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_DAMPING);
- BIND_CONSTANT( PARAM_LINEAR_MOTION_SOFTNESS);
- BIND_CONSTANT( PARAM_LINEAR_MOTION_RESTITUTION);
- BIND_CONSTANT( PARAM_LINEAR_MOTION_DAMPING);
- BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
- BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
- BIND_CONSTANT( PARAM_LINEAR_ORTHOGONAL_DAMPING);
-
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_UPPER);
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_LOWER);
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS);
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_RESTITUTION);
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_DAMPING);
- BIND_CONSTANT( PARAM_ANGULAR_MOTION_SOFTNESS);
- BIND_CONSTANT( PARAM_ANGULAR_MOTION_RESTITUTION);
- BIND_CONSTANT( PARAM_ANGULAR_MOTION_DAMPING);
- BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
- BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
- BIND_CONSTANT( PARAM_ANGULAR_ORTHOGONAL_DAMPING);
-
- BIND_CONSTANT( PARAM_MAX);
-}
-
-void SliderJoint::set_param(Param p_param,float p_value){
-
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params[p_param]=p_value;
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &SliderJoint::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &SliderJoint::get_param);
+
+ ClassDB::bind_method(D_METHOD("_set_upper_limit_angular", "upper_limit_angular"), &SliderJoint::_set_upper_limit_angular);
+ ClassDB::bind_method(D_METHOD("_get_upper_limit_angular"), &SliderJoint::_get_upper_limit_angular);
+
+ ClassDB::bind_method(D_METHOD("_set_lower_limit_angular", "lower_limit_angular"), &SliderJoint::_set_lower_limit_angular);
+ ClassDB::bind_method(D_METHOD("_get_lower_limit_angular"), &SliderJoint::_get_lower_limit_angular);
+
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/upper_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_UPPER);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/lower_distance", PROPERTY_HINT_RANGE, "-1024,1024,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_LOWER);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING);
+
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_upper_limit_angular", "_get_upper_limit_angular");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_lower_limit_angular", "_get_lower_limit_angular");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motion/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/restitution", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_ortho/damping", PROPERTY_HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING);
+
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_UPPER);
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_LOWER);
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_RESTITUTION);
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_DAMPING);
+ BIND_CONSTANT(PARAM_LINEAR_MOTION_SOFTNESS);
+ BIND_CONSTANT(PARAM_LINEAR_MOTION_RESTITUTION);
+ BIND_CONSTANT(PARAM_LINEAR_MOTION_DAMPING);
+ BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_SOFTNESS);
+ BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_RESTITUTION);
+ BIND_CONSTANT(PARAM_LINEAR_ORTHOGONAL_DAMPING);
+
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_UPPER);
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_LOWER);
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_RESTITUTION);
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_DAMPING);
+ BIND_CONSTANT(PARAM_ANGULAR_MOTION_SOFTNESS);
+ BIND_CONSTANT(PARAM_ANGULAR_MOTION_RESTITUTION);
+ BIND_CONSTANT(PARAM_ANGULAR_MOTION_DAMPING);
+ BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_SOFTNESS);
+ BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_RESTITUTION);
+ BIND_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_DAMPING);
+
+ BIND_CONSTANT(PARAM_MAX);
+}
+
+void SliderJoint::set_param(Param p_param, float p_value) {
+
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(),PhysicsServer::SliderJointParam(p_param),p_value);
+ PhysicsServer::get_singleton()->slider_joint_set_param(get_joint(), PhysicsServer::SliderJointParam(p_param), p_value);
update_gizmo();
-
}
-float SliderJoint::get_param(Param p_param) const{
+float SliderJoint::get_param(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params[p_param];
}
-
-RID SliderJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
-
+RID SliderJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {
Transform gt = get_global_transform();
Transform ainv = body_a->get_global_transform().affine_inverse();
@@ -543,53 +484,46 @@ RID SliderJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
local_b.orthonormalize();
- RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
- for(int i=0;i<PARAM_MAX;i++) {
- PhysicsServer::get_singleton()->slider_joint_set_param(j,PhysicsServer::SliderJointParam(i),params[i]);
+ RID j = PhysicsServer::get_singleton()->joint_create_slider(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
+ for (int i = 0; i < PARAM_MAX; i++) {
+ PhysicsServer::get_singleton()->slider_joint_set_param(j, PhysicsServer::SliderJointParam(i), params[i]);
}
return j;
}
-
SliderJoint::SliderJoint() {
-
-
- params[ PARAM_LINEAR_LIMIT_UPPER ]=1.0;
- params[ PARAM_LINEAR_LIMIT_LOWER ]=-1.0;
- params[ PARAM_LINEAR_LIMIT_SOFTNESS ]=1.0;
- params[ PARAM_LINEAR_LIMIT_RESTITUTION]=0.7;
- params[ PARAM_LINEAR_LIMIT_DAMPING]=1.0;
- params[ PARAM_LINEAR_MOTION_SOFTNESS ]=1.0;
- params[ PARAM_LINEAR_MOTION_RESTITUTION]=0.7;
- params[ PARAM_LINEAR_MOTION_DAMPING]=0;//1.0;
- params[ PARAM_LINEAR_ORTHOGONAL_SOFTNESS ]=1.0;
- params[ PARAM_LINEAR_ORTHOGONAL_RESTITUTION]=0.7;
- params[ PARAM_LINEAR_ORTHOGONAL_DAMPING]=1.0;
-
- params[ PARAM_ANGULAR_LIMIT_UPPER ]=0 ;
- params[ PARAM_ANGULAR_LIMIT_LOWER ]=0 ;
- params[ PARAM_ANGULAR_LIMIT_SOFTNESS ]=1.0;
- params[ PARAM_ANGULAR_LIMIT_RESTITUTION]=0.7;
- params[ PARAM_ANGULAR_LIMIT_DAMPING]=0;//1.0;
- params[ PARAM_ANGULAR_MOTION_SOFTNESS ]=1.0;
- params[ PARAM_ANGULAR_MOTION_RESTITUTION]=0.7;
- params[ PARAM_ANGULAR_MOTION_DAMPING]=1.0;
- params[ PARAM_ANGULAR_ORTHOGONAL_SOFTNESS ]=1.0;
- params[ PARAM_ANGULAR_ORTHOGONAL_RESTITUTION]=0.7;
- params[ PARAM_ANGULAR_ORTHOGONAL_DAMPING]=1.0;
+ params[PARAM_LINEAR_LIMIT_UPPER] = 1.0;
+ params[PARAM_LINEAR_LIMIT_LOWER] = -1.0;
+ params[PARAM_LINEAR_LIMIT_SOFTNESS] = 1.0;
+ params[PARAM_LINEAR_LIMIT_RESTITUTION] = 0.7;
+ params[PARAM_LINEAR_LIMIT_DAMPING] = 1.0;
+ params[PARAM_LINEAR_MOTION_SOFTNESS] = 1.0;
+ params[PARAM_LINEAR_MOTION_RESTITUTION] = 0.7;
+ params[PARAM_LINEAR_MOTION_DAMPING] = 0; //1.0;
+ params[PARAM_LINEAR_ORTHOGONAL_SOFTNESS] = 1.0;
+ params[PARAM_LINEAR_ORTHOGONAL_RESTITUTION] = 0.7;
+ params[PARAM_LINEAR_ORTHOGONAL_DAMPING] = 1.0;
+
+ params[PARAM_ANGULAR_LIMIT_UPPER] = 0;
+ params[PARAM_ANGULAR_LIMIT_LOWER] = 0;
+ params[PARAM_ANGULAR_LIMIT_SOFTNESS] = 1.0;
+ params[PARAM_ANGULAR_LIMIT_RESTITUTION] = 0.7;
+ params[PARAM_ANGULAR_LIMIT_DAMPING] = 0; //1.0;
+ params[PARAM_ANGULAR_MOTION_SOFTNESS] = 1.0;
+ params[PARAM_ANGULAR_MOTION_RESTITUTION] = 0.7;
+ params[PARAM_ANGULAR_MOTION_DAMPING] = 1.0;
+ params[PARAM_ANGULAR_ORTHOGONAL_SOFTNESS] = 1.0;
+ params[PARAM_ANGULAR_ORTHOGONAL_RESTITUTION] = 0.7;
+ params[PARAM_ANGULAR_ORTHOGONAL_DAMPING] = 1.0;
}
-
-
//////////////////////////////////
-
-
void ConeTwistJoint::_set_swing_span(float p_limit_angular) {
- set_param(PARAM_SWING_SPAN,Math::deg2rad(p_limit_angular));
+ set_param(PARAM_SWING_SPAN, Math::deg2rad(p_limit_angular));
}
float ConeTwistJoint::_get_swing_span() const {
@@ -599,64 +533,56 @@ float ConeTwistJoint::_get_swing_span() const {
void ConeTwistJoint::_set_twist_span(float p_limit_angular) {
- set_param(PARAM_TWIST_SPAN,Math::deg2rad(p_limit_angular));
-
+ set_param(PARAM_TWIST_SPAN, Math::deg2rad(p_limit_angular));
}
float ConeTwistJoint::_get_twist_span() const {
return Math::rad2deg(get_param(PARAM_TWIST_SPAN));
-
}
-
void ConeTwistJoint::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_param","param","value"),&ConeTwistJoint::set_param);
- ClassDB::bind_method(D_METHOD("get_param","param"),&ConeTwistJoint::get_param);
-
+ ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &ConeTwistJoint::set_param);
+ ClassDB::bind_method(D_METHOD("get_param", "param"), &ConeTwistJoint::get_param);
- ClassDB::bind_method(D_METHOD("_set_swing_span","swing_span"),&ConeTwistJoint::_set_swing_span);
- ClassDB::bind_method(D_METHOD("_get_swing_span"),&ConeTwistJoint::_get_swing_span);
+ ClassDB::bind_method(D_METHOD("_set_swing_span", "swing_span"), &ConeTwistJoint::_set_swing_span);
+ ClassDB::bind_method(D_METHOD("_get_swing_span"), &ConeTwistJoint::_get_swing_span);
- ClassDB::bind_method(D_METHOD("_set_twist_span","twist_span"),&ConeTwistJoint::_set_twist_span);
- ClassDB::bind_method(D_METHOD("_get_twist_span"),&ConeTwistJoint::_get_twist_span);
+ ClassDB::bind_method(D_METHOD("_set_twist_span", "twist_span"), &ConeTwistJoint::_set_twist_span);
+ ClassDB::bind_method(D_METHOD("_get_twist_span"), &ConeTwistJoint::_get_twist_span);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "swing_span", PROPERTY_HINT_RANGE, "-180,180,0.1"), "_set_swing_span", "_get_swing_span");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "twist_span", PROPERTY_HINT_RANGE, "-40000,40000,0.1"), "_set_twist_span", "_get_twist_span");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"swing_span",PROPERTY_HINT_RANGE,"-180,180,0.1"),"_set_swing_span","_get_swing_span") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"twist_span",PROPERTY_HINT_RANGE,"-40000,40000,0.1"),"_set_twist_span","_get_twist_span") ;
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "bias", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_BIAS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "softness", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "relaxation", PROPERTY_HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_RELAXATION);
-
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"bias",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_BIAS );
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"softness",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_SOFTNESS);
- ADD_PROPERTYI( PropertyInfo(Variant::REAL,"relaxation",PROPERTY_HINT_RANGE,"0.01,16.0,0.01") ,"set_param","get_param", PARAM_RELAXATION);
-
- BIND_CONSTANT( PARAM_SWING_SPAN );
- BIND_CONSTANT( PARAM_TWIST_SPAN );
- BIND_CONSTANT( PARAM_BIAS );
- BIND_CONSTANT( PARAM_SOFTNESS );
- BIND_CONSTANT( PARAM_RELAXATION );
- BIND_CONSTANT( PARAM_MAX );
+ BIND_CONSTANT(PARAM_SWING_SPAN);
+ BIND_CONSTANT(PARAM_TWIST_SPAN);
+ BIND_CONSTANT(PARAM_BIAS);
+ BIND_CONSTANT(PARAM_SOFTNESS);
+ BIND_CONSTANT(PARAM_RELAXATION);
+ BIND_CONSTANT(PARAM_MAX);
}
-void ConeTwistJoint::set_param(Param p_param,float p_value){
+void ConeTwistJoint::set_param(Param p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(),PhysicsServer::ConeTwistJointParam(p_param),p_value);
+ PhysicsServer::get_singleton()->cone_twist_joint_set_param(get_joint(), PhysicsServer::ConeTwistJointParam(p_param), p_value);
update_gizmo();
}
-float ConeTwistJoint::get_param(Param p_param) const{
+float ConeTwistJoint::get_param(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params[p_param];
}
-
-RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
-
+RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {
Transform gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
@@ -675,311 +601,285 @@ RID ConeTwistJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
local_b.orthonormalize();
- RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
- for(int i=0;i<PARAM_MAX;i++) {
- PhysicsServer::get_singleton()->cone_twist_joint_set_param(j,PhysicsServer::ConeTwistJointParam(i),params[i]);
+ RID j = PhysicsServer::get_singleton()->joint_create_cone_twist(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
+ for (int i = 0; i < PARAM_MAX; i++) {
+ PhysicsServer::get_singleton()->cone_twist_joint_set_param(j, PhysicsServer::ConeTwistJointParam(i), params[i]);
}
return j;
}
-
ConeTwistJoint::ConeTwistJoint() {
-
- params[ PARAM_SWING_SPAN ]=Math_PI*0.25;
- params[ PARAM_TWIST_SPAN ]=Math_PI;
- params[ PARAM_BIAS ]=0.3;
- params[ PARAM_SOFTNESS ]=0.8;
- params[ PARAM_RELAXATION ]=1.0;
-
+ params[PARAM_SWING_SPAN] = Math_PI * 0.25;
+ params[PARAM_TWIST_SPAN] = Math_PI;
+ params[PARAM_BIAS] = 0.3;
+ params[PARAM_SOFTNESS] = 0.8;
+ params[PARAM_RELAXATION] = 1.0;
}
/////////////////////////////////////////////////////////////////////
-
void Generic6DOFJoint::_set_angular_hi_limit_x(float p_limit_angular) {
- set_param_x(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_x(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_hi_limit_x() const{
+float Generic6DOFJoint::_get_angular_hi_limit_x() const {
return Math::rad2deg(get_param_x(PARAM_ANGULAR_UPPER_LIMIT));
-
}
void Generic6DOFJoint::_set_angular_lo_limit_x(float p_limit_angular) {
- set_param_x(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_x(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_lo_limit_x() const{
+float Generic6DOFJoint::_get_angular_lo_limit_x() const {
return Math::rad2deg(get_param_x(PARAM_ANGULAR_LOWER_LIMIT));
-
}
-
void Generic6DOFJoint::_set_angular_hi_limit_y(float p_limit_angular) {
- set_param_y(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_y(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_hi_limit_y() const{
+float Generic6DOFJoint::_get_angular_hi_limit_y() const {
return Math::rad2deg(get_param_y(PARAM_ANGULAR_UPPER_LIMIT));
-
}
void Generic6DOFJoint::_set_angular_lo_limit_y(float p_limit_angular) {
- set_param_y(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_y(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_lo_limit_y() const{
+float Generic6DOFJoint::_get_angular_lo_limit_y() const {
return Math::rad2deg(get_param_y(PARAM_ANGULAR_LOWER_LIMIT));
-
}
-
void Generic6DOFJoint::_set_angular_hi_limit_z(float p_limit_angular) {
- set_param_z(PARAM_ANGULAR_UPPER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_z(PARAM_ANGULAR_UPPER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_hi_limit_z() const{
+float Generic6DOFJoint::_get_angular_hi_limit_z() const {
return Math::rad2deg(get_param_z(PARAM_ANGULAR_UPPER_LIMIT));
-
}
void Generic6DOFJoint::_set_angular_lo_limit_z(float p_limit_angular) {
- set_param_z(PARAM_ANGULAR_LOWER_LIMIT,Math::deg2rad(p_limit_angular));
+ set_param_z(PARAM_ANGULAR_LOWER_LIMIT, Math::deg2rad(p_limit_angular));
}
-float Generic6DOFJoint::_get_angular_lo_limit_z() const{
+float Generic6DOFJoint::_get_angular_lo_limit_z() const {
return Math::rad2deg(get_param_z(PARAM_ANGULAR_LOWER_LIMIT));
-
}
-
-
-void Generic6DOFJoint::_bind_methods(){
-
-
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x","angle"),&Generic6DOFJoint::_set_angular_hi_limit_x);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"),&Generic6DOFJoint::_get_angular_hi_limit_x);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x","angle"),&Generic6DOFJoint::_set_angular_lo_limit_x);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"),&Generic6DOFJoint::_get_angular_lo_limit_x);
-
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y","angle"),&Generic6DOFJoint::_set_angular_hi_limit_y);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"),&Generic6DOFJoint::_get_angular_hi_limit_y);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y","angle"),&Generic6DOFJoint::_set_angular_lo_limit_y);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"),&Generic6DOFJoint::_get_angular_lo_limit_y);
-
- ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z","angle"),&Generic6DOFJoint::_set_angular_hi_limit_z);
- ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"),&Generic6DOFJoint::_get_angular_hi_limit_z);
-
- ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z","angle"),&Generic6DOFJoint::_set_angular_lo_limit_z);
- ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"),&Generic6DOFJoint::_get_angular_lo_limit_z);
-
- ClassDB::bind_method(D_METHOD("set_param_x","param","value"),&Generic6DOFJoint::set_param_x);
- ClassDB::bind_method(D_METHOD("get_param_x","param"),&Generic6DOFJoint::get_param_x);
-
- ClassDB::bind_method(D_METHOD("set_param_y","param","value"),&Generic6DOFJoint::set_param_y);
- ClassDB::bind_method(D_METHOD("get_param_y","param"),&Generic6DOFJoint::get_param_y);
-
- ClassDB::bind_method(D_METHOD("set_param_z","param","value"),&Generic6DOFJoint::set_param_z);
- ClassDB::bind_method(D_METHOD("get_param_z","param"),&Generic6DOFJoint::get_param_z);
-
- ClassDB::bind_method(D_METHOD("set_flag_x","flag","value"),&Generic6DOFJoint::set_flag_x);
- ClassDB::bind_method(D_METHOD("get_flag_x","flag"),&Generic6DOFJoint::get_flag_x);
-
- ClassDB::bind_method(D_METHOD("set_flag_y","flag","value"),&Generic6DOFJoint::set_flag_y);
- ClassDB::bind_method(D_METHOD("get_flag_y","flag"),&Generic6DOFJoint::get_flag_y);
-
- ClassDB::bind_method(D_METHOD("set_flag_z","flag","value"),&Generic6DOFJoint::set_flag_z);
- ClassDB::bind_method(D_METHOD("get_flag_z","flag"),&Generic6DOFJoint::get_flag_z);
-
-
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_LINEAR_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/upper_distance"),"set_param_x","get_param_x",PARAM_LINEAR_UPPER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/lower_distance"),"set_param_x","get_param_x",PARAM_LINEAR_LOWER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_LINEAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_x","_get_angular_hi_limit_x");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_x/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_x","_get_angular_lo_limit_x");
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_x","get_param_x",PARAM_ANGULAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/force_limit"),"set_param_x","get_param_x",PARAM_ANGULAR_FORCE_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_x/erp"),"set_param_x","get_param_x",PARAM_ANGULAR_ERP);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_x/enabled"),"set_flag_x","get_flag_x",FLAG_ENABLE_MOTOR);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/target_velocity"),"set_param_x","get_param_x",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_x/force_limit"),"set_param_x","get_param_x",PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
-
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_LINEAR_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/upper_distance"),"set_param_y","get_param_y",PARAM_LINEAR_UPPER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/lower_distance"),"set_param_y","get_param_y",PARAM_LINEAR_LOWER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_LINEAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_y","_get_angular_hi_limit_y");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_y/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_y","_get_angular_lo_limit_y");
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_y","get_param_y",PARAM_ANGULAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/force_limit"),"set_param_y","get_param_y",PARAM_ANGULAR_FORCE_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_y/erp"),"set_param_y","get_param_y",PARAM_ANGULAR_ERP);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_y/enabled"),"set_flag_y","get_flag_y",FLAG_ENABLE_MOTOR);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/target_velocity"),"set_param_y","get_param_y",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_y/force_limit"),"set_param_y","get_param_y",PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
-
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"linear_limit_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_LINEAR_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/upper_distance"),"set_param_z","get_param_z",PARAM_LINEAR_UPPER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/lower_distance"),"set_param_z","get_param_z",PARAM_LINEAR_LOWER_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"linear_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_LINEAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_limit_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_ANGULAR_LIMIT);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/upper_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_hi_limit_z","_get_angular_hi_limit_z");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"angular_limit_z/lower_angle",PROPERTY_HINT_RANGE,"-180,180,0.01"),"_set_angular_lo_limit_z","_get_angular_lo_limit_z");
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/softness",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_LIMIT_SOFTNESS);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/restitution",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_RESTITUTION);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/damping",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_param_z","get_param_z",PARAM_ANGULAR_DAMPING);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/force_limit"),"set_param_z","get_param_z",PARAM_ANGULAR_FORCE_LIMIT);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_limit_z/erp"),"set_param_z","get_param_z",PARAM_ANGULAR_ERP);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"angular_motor_z/enabled"),"set_flag_z","get_flag_z",FLAG_ENABLE_MOTOR);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/target_velocity"),"set_param_z","get_param_z",PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"angular_motor_z/force_limit"),"set_param_z","get_param_z",PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
-
-
- BIND_CONSTANT( PARAM_LINEAR_LOWER_LIMIT);
- BIND_CONSTANT( PARAM_LINEAR_UPPER_LIMIT);
- BIND_CONSTANT( PARAM_LINEAR_LIMIT_SOFTNESS);
- BIND_CONSTANT( PARAM_LINEAR_RESTITUTION);
- BIND_CONSTANT( PARAM_LINEAR_DAMPING);
- BIND_CONSTANT( PARAM_ANGULAR_LOWER_LIMIT);
- BIND_CONSTANT( PARAM_ANGULAR_UPPER_LIMIT);
- BIND_CONSTANT( PARAM_ANGULAR_LIMIT_SOFTNESS);
- BIND_CONSTANT( PARAM_ANGULAR_DAMPING);
- BIND_CONSTANT( PARAM_ANGULAR_RESTITUTION);
- BIND_CONSTANT( PARAM_ANGULAR_FORCE_LIMIT);
- BIND_CONSTANT( PARAM_ANGULAR_ERP);
- BIND_CONSTANT( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
- BIND_CONSTANT( PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
- BIND_CONSTANT( PARAM_MAX);
-
- BIND_CONSTANT( FLAG_ENABLE_LINEAR_LIMIT);
- BIND_CONSTANT( FLAG_ENABLE_ANGULAR_LIMIT);
- BIND_CONSTANT( FLAG_ENABLE_MOTOR);
- BIND_CONSTANT( FLAG_MAX );
-}
-
-
-void Generic6DOFJoint::set_param_x(Param p_param,float p_value){
-
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params_x[p_param]=p_value;
+void Generic6DOFJoint::_bind_methods() {
+
+ ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_x", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_x);
+ ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_x"), &Generic6DOFJoint::_get_angular_hi_limit_x);
+
+ ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_x", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_x);
+ ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_x"), &Generic6DOFJoint::_get_angular_lo_limit_x);
+
+ ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_y", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_y);
+ ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_y"), &Generic6DOFJoint::_get_angular_hi_limit_y);
+
+ ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_y", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_y);
+ ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_y"), &Generic6DOFJoint::_get_angular_lo_limit_y);
+
+ ClassDB::bind_method(D_METHOD("_set_angular_hi_limit_z", "angle"), &Generic6DOFJoint::_set_angular_hi_limit_z);
+ ClassDB::bind_method(D_METHOD("_get_angular_hi_limit_z"), &Generic6DOFJoint::_get_angular_hi_limit_z);
+
+ ClassDB::bind_method(D_METHOD("_set_angular_lo_limit_z", "angle"), &Generic6DOFJoint::_set_angular_lo_limit_z);
+ ClassDB::bind_method(D_METHOD("_get_angular_lo_limit_z"), &Generic6DOFJoint::_get_angular_lo_limit_z);
+
+ ClassDB::bind_method(D_METHOD("set_param_x", "param", "value"), &Generic6DOFJoint::set_param_x);
+ ClassDB::bind_method(D_METHOD("get_param_x", "param"), &Generic6DOFJoint::get_param_x);
+
+ ClassDB::bind_method(D_METHOD("set_param_y", "param", "value"), &Generic6DOFJoint::set_param_y);
+ ClassDB::bind_method(D_METHOD("get_param_y", "param"), &Generic6DOFJoint::get_param_y);
+
+ ClassDB::bind_method(D_METHOD("set_param_z", "param", "value"), &Generic6DOFJoint::set_param_z);
+ ClassDB::bind_method(D_METHOD("get_param_z", "param"), &Generic6DOFJoint::get_param_z);
+
+ ClassDB::bind_method(D_METHOD("set_flag_x", "flag", "value"), &Generic6DOFJoint::set_flag_x);
+ ClassDB::bind_method(D_METHOD("get_flag_x", "flag"), &Generic6DOFJoint::get_flag_x);
+
+ ClassDB::bind_method(D_METHOD("set_flag_y", "flag", "value"), &Generic6DOFJoint::set_flag_y);
+ ClassDB::bind_method(D_METHOD("get_flag_y", "flag"), &Generic6DOFJoint::get_flag_y);
+
+ ClassDB::bind_method(D_METHOD("set_flag_z", "flag", "value"), &Generic6DOFJoint::set_flag_z);
+ ClassDB::bind_method(D_METHOD("get_flag_z", "flag"), &Generic6DOFJoint::get_flag_z);
+
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_LINEAR_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/upper_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/lower_distance"), "set_param_x", "get_param_x", PARAM_LINEAR_LOWER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_LINEAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_ANGULAR_LIMIT);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_x", "_get_angular_hi_limit_x");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_x/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_x", "_get_angular_lo_limit_x");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_x", "get_param_x", PARAM_ANGULAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_FORCE_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_x/erp"), "set_param_x", "get_param_x", PARAM_ANGULAR_ERP);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_x/enabled"), "set_flag_x", "get_flag_x", FLAG_ENABLE_MOTOR);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/target_velocity"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_x/force_limit"), "set_param_x", "get_param_x", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
+
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_LINEAR_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/upper_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/lower_distance"), "set_param_y", "get_param_y", PARAM_LINEAR_LOWER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_LINEAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_ANGULAR_LIMIT);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_y", "_get_angular_hi_limit_y");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_y/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_y", "_get_angular_lo_limit_y");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_y", "get_param_y", PARAM_ANGULAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_FORCE_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_y/erp"), "set_param_y", "get_param_y", PARAM_ANGULAR_ERP);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_y/enabled"), "set_flag_y", "get_flag_y", FLAG_ENABLE_MOTOR);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/target_velocity"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_y/force_limit"), "set_param_y", "get_param_y", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
+
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "linear_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_LINEAR_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/upper_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_UPPER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/lower_distance"), "set_param_z", "get_param_z", PARAM_LINEAR_LOWER_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "linear_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_LINEAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_limit_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_ANGULAR_LIMIT);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/upper_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_hi_limit_z", "_get_angular_hi_limit_z");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_limit_z/lower_angle", PROPERTY_HINT_RANGE, "-180,180,0.01"), "_set_angular_lo_limit_z", "_get_angular_lo_limit_z");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/softness", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_LIMIT_SOFTNESS);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/restitution", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_RESTITUTION);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/damping", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_param_z", "get_param_z", PARAM_ANGULAR_DAMPING);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_FORCE_LIMIT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_limit_z/erp"), "set_param_z", "get_param_z", PARAM_ANGULAR_ERP);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "angular_motor_z/enabled"), "set_flag_z", "get_flag_z", FLAG_ENABLE_MOTOR);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/target_velocity"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "angular_motor_z/force_limit"), "set_param_z", "get_param_z", PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
+
+ BIND_CONSTANT(PARAM_LINEAR_LOWER_LIMIT);
+ BIND_CONSTANT(PARAM_LINEAR_UPPER_LIMIT);
+ BIND_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(PARAM_LINEAR_RESTITUTION);
+ BIND_CONSTANT(PARAM_LINEAR_DAMPING);
+ BIND_CONSTANT(PARAM_ANGULAR_LOWER_LIMIT);
+ BIND_CONSTANT(PARAM_ANGULAR_UPPER_LIMIT);
+ BIND_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(PARAM_ANGULAR_DAMPING);
+ BIND_CONSTANT(PARAM_ANGULAR_RESTITUTION);
+ BIND_CONSTANT(PARAM_ANGULAR_FORCE_LIMIT);
+ BIND_CONSTANT(PARAM_ANGULAR_ERP);
+ BIND_CONSTANT(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY);
+ BIND_CONSTANT(PARAM_ANGULAR_MOTOR_FORCE_LIMIT);
+ BIND_CONSTANT(PARAM_MAX);
+
+ BIND_CONSTANT(FLAG_ENABLE_LINEAR_LIMIT);
+ BIND_CONSTANT(FLAG_ENABLE_ANGULAR_LIMIT);
+ BIND_CONSTANT(FLAG_ENABLE_MOTOR);
+ BIND_CONSTANT(FLAG_MAX);
+}
+
+void Generic6DOFJoint::set_param_x(Param p_param, float p_value) {
+
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params_x[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);
update_gizmo();
}
-float Generic6DOFJoint::get_param_x(Param p_param) const{
+float Generic6DOFJoint::get_param_x(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params_x[p_param];
}
-void Generic6DOFJoint::set_param_y(Param p_param,float p_value){
+void Generic6DOFJoint::set_param_y(Param p_param, float p_value) {
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params_y[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params_y[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);
update_gizmo();
-
}
-float Generic6DOFJoint::get_param_y(Param p_param) const{
+float Generic6DOFJoint::get_param_y(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params_y[p_param];
}
+void Generic6DOFJoint::set_param_z(Param p_param, float p_value) {
-void Generic6DOFJoint::set_param_z(Param p_param,float p_value){
-
- ERR_FAIL_INDEX(p_param,PARAM_MAX);
- params_z[p_param]=p_value;
+ ERR_FAIL_INDEX(p_param, PARAM_MAX);
+ params_z[p_param] = p_value;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(p_param),p_value);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(p_param), p_value);
update_gizmo();
}
-float Generic6DOFJoint::get_param_z(Param p_param) const{
+float Generic6DOFJoint::get_param_z(Param p_param) const {
- ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0);
+ ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0);
return params_z[p_param];
}
+void Generic6DOFJoint::set_flag_x(Flag p_flag, bool p_enabled) {
-void Generic6DOFJoint::set_flag_x(Flag p_flag,bool p_enabled){
-
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- flags_x[p_flag]=p_enabled;
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ flags_x[p_flag] = p_enabled;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
update_gizmo();
-
}
-bool Generic6DOFJoint::get_flag_x(Flag p_flag) const{
+bool Generic6DOFJoint::get_flag_x(Flag p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags_x[p_flag];
-
}
-void Generic6DOFJoint::set_flag_y(Flag p_flag,bool p_enabled){
+void Generic6DOFJoint::set_flag_y(Flag p_flag, bool p_enabled) {
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- flags_y[p_flag]=p_enabled;
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ flags_y[p_flag] = p_enabled;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
update_gizmo();
}
-bool Generic6DOFJoint::get_flag_y(Flag p_flag) const{
+bool Generic6DOFJoint::get_flag_y(Flag p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags_y[p_flag];
-
}
-void Generic6DOFJoint::set_flag_z(Flag p_flag,bool p_enabled){
+void Generic6DOFJoint::set_flag_z(Flag p_flag, bool p_enabled) {
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- flags_z[p_flag]=p_enabled;
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ flags_z[p_flag] = p_enabled;
if (get_joint().is_valid())
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(),Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(p_flag),p_enabled);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(get_joint(), Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(p_flag), p_enabled);
update_gizmo();
}
-bool Generic6DOFJoint::get_flag_z(Flag p_flag) const{
+bool Generic6DOFJoint::get_flag_z(Flag p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags_z[p_flag];
-
}
-RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b) {
-
+RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) {
Transform gt = get_global_transform();
//Vector3 cone_twistpos = gt.origin;
@@ -998,87 +898,81 @@ RID Generic6DOFJoint::_configure_joint(PhysicsBody *body_a,PhysicsBody *body_b)
local_b.orthonormalize();
- RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(),local_a,body_b?body_b->get_rid():RID(),local_b);
- for(int i=0;i<PARAM_MAX;i++) {
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisParam(i),params_x[i]);
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisParam(i),params_y[i]);
- PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisParam(i),params_z[i]);
+ RID j = PhysicsServer::get_singleton()->joint_create_generic_6dof(body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b);
+ for (int i = 0; i < PARAM_MAX; i++) {
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisParam(i), params_x[i]);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisParam(i), params_y[i]);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_param(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisParam(i), params_z[i]);
}
- for(int i=0;i<FLAG_MAX;i++) {
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_X,PhysicsServer::G6DOFJointAxisFlag(i),flags_x[i]);
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Y,PhysicsServer::G6DOFJointAxisFlag(i),flags_y[i]);
- PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j,Vector3::AXIS_Z,PhysicsServer::G6DOFJointAxisFlag(i),flags_z[i]);
+ for (int i = 0; i < FLAG_MAX; i++) {
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_X, PhysicsServer::G6DOFJointAxisFlag(i), flags_x[i]);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Y, PhysicsServer::G6DOFJointAxisFlag(i), flags_y[i]);
+ PhysicsServer::get_singleton()->generic_6dof_joint_set_flag(j, Vector3::AXIS_Z, PhysicsServer::G6DOFJointAxisFlag(i), flags_z[i]);
}
return j;
}
-
Generic6DOFJoint::Generic6DOFJoint() {
- set_param_x( PARAM_LINEAR_LOWER_LIMIT,0);
- set_param_x( PARAM_LINEAR_UPPER_LIMIT,0);
- set_param_x( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
- set_param_x( PARAM_LINEAR_RESTITUTION,0.5);
- set_param_x( PARAM_LINEAR_DAMPING,1.0);
- set_param_x( PARAM_ANGULAR_LOWER_LIMIT,0);
- set_param_x( PARAM_ANGULAR_UPPER_LIMIT,0);
- set_param_x( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
- set_param_x( PARAM_ANGULAR_DAMPING,1.0f);
- set_param_x( PARAM_ANGULAR_RESTITUTION,0);
- set_param_x( PARAM_ANGULAR_FORCE_LIMIT,0);
- set_param_x( PARAM_ANGULAR_ERP,0.5);
- set_param_x( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
- set_param_x( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
-
- set_flag_x( FLAG_ENABLE_ANGULAR_LIMIT,true);
- set_flag_x( FLAG_ENABLE_LINEAR_LIMIT,true);
- set_flag_x( FLAG_ENABLE_MOTOR,false);
-
- set_param_y( PARAM_LINEAR_LOWER_LIMIT,0);
- set_param_y( PARAM_LINEAR_UPPER_LIMIT,0);
- set_param_y( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
- set_param_y( PARAM_LINEAR_RESTITUTION,0.5);
- set_param_y( PARAM_LINEAR_DAMPING,1.0);
- set_param_y( PARAM_ANGULAR_LOWER_LIMIT,0);
- set_param_y( PARAM_ANGULAR_UPPER_LIMIT,0);
- set_param_y( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
- set_param_y( PARAM_ANGULAR_DAMPING,1.0f);
- set_param_y( PARAM_ANGULAR_RESTITUTION,0);
- set_param_y( PARAM_ANGULAR_FORCE_LIMIT,0);
- set_param_y( PARAM_ANGULAR_ERP,0.5);
- set_param_y( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
- set_param_y( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
-
- set_flag_y( FLAG_ENABLE_ANGULAR_LIMIT,true);
- set_flag_y( FLAG_ENABLE_LINEAR_LIMIT,true);
- set_flag_y( FLAG_ENABLE_MOTOR,false);
-
-
- set_param_z( PARAM_LINEAR_LOWER_LIMIT,0);
- set_param_z( PARAM_LINEAR_UPPER_LIMIT,0);
- set_param_z( PARAM_LINEAR_LIMIT_SOFTNESS,0.7);
- set_param_z( PARAM_LINEAR_RESTITUTION,0.5);
- set_param_z( PARAM_LINEAR_DAMPING,1.0);
- set_param_z( PARAM_ANGULAR_LOWER_LIMIT,0);
- set_param_z( PARAM_ANGULAR_UPPER_LIMIT,0);
- set_param_z( PARAM_ANGULAR_LIMIT_SOFTNESS,0.5f);
- set_param_z( PARAM_ANGULAR_DAMPING,1.0f);
- set_param_z( PARAM_ANGULAR_RESTITUTION,0);
- set_param_z( PARAM_ANGULAR_FORCE_LIMIT,0);
- set_param_z( PARAM_ANGULAR_ERP,0.5);
- set_param_z( PARAM_ANGULAR_MOTOR_TARGET_VELOCITY,0);
- set_param_z( PARAM_ANGULAR_MOTOR_FORCE_LIMIT,300);
-
- set_flag_z( FLAG_ENABLE_ANGULAR_LIMIT,true);
- set_flag_z( FLAG_ENABLE_LINEAR_LIMIT,true);
- set_flag_z( FLAG_ENABLE_MOTOR,false);
-
+ set_param_x(PARAM_LINEAR_LOWER_LIMIT, 0);
+ set_param_x(PARAM_LINEAR_UPPER_LIMIT, 0);
+ set_param_x(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
+ set_param_x(PARAM_LINEAR_RESTITUTION, 0.5);
+ set_param_x(PARAM_LINEAR_DAMPING, 1.0);
+ set_param_x(PARAM_ANGULAR_LOWER_LIMIT, 0);
+ set_param_x(PARAM_ANGULAR_UPPER_LIMIT, 0);
+ set_param_x(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
+ set_param_x(PARAM_ANGULAR_DAMPING, 1.0f);
+ set_param_x(PARAM_ANGULAR_RESTITUTION, 0);
+ set_param_x(PARAM_ANGULAR_FORCE_LIMIT, 0);
+ set_param_x(PARAM_ANGULAR_ERP, 0.5);
+ set_param_x(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
+ set_param_x(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);
+
+ set_flag_x(FLAG_ENABLE_ANGULAR_LIMIT, true);
+ set_flag_x(FLAG_ENABLE_LINEAR_LIMIT, true);
+ set_flag_x(FLAG_ENABLE_MOTOR, false);
+
+ set_param_y(PARAM_LINEAR_LOWER_LIMIT, 0);
+ set_param_y(PARAM_LINEAR_UPPER_LIMIT, 0);
+ set_param_y(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
+ set_param_y(PARAM_LINEAR_RESTITUTION, 0.5);
+ set_param_y(PARAM_LINEAR_DAMPING, 1.0);
+ set_param_y(PARAM_ANGULAR_LOWER_LIMIT, 0);
+ set_param_y(PARAM_ANGULAR_UPPER_LIMIT, 0);
+ set_param_y(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
+ set_param_y(PARAM_ANGULAR_DAMPING, 1.0f);
+ set_param_y(PARAM_ANGULAR_RESTITUTION, 0);
+ set_param_y(PARAM_ANGULAR_FORCE_LIMIT, 0);
+ set_param_y(PARAM_ANGULAR_ERP, 0.5);
+ set_param_y(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
+ set_param_y(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);
+
+ set_flag_y(FLAG_ENABLE_ANGULAR_LIMIT, true);
+ set_flag_y(FLAG_ENABLE_LINEAR_LIMIT, true);
+ set_flag_y(FLAG_ENABLE_MOTOR, false);
+
+ set_param_z(PARAM_LINEAR_LOWER_LIMIT, 0);
+ set_param_z(PARAM_LINEAR_UPPER_LIMIT, 0);
+ set_param_z(PARAM_LINEAR_LIMIT_SOFTNESS, 0.7);
+ set_param_z(PARAM_LINEAR_RESTITUTION, 0.5);
+ set_param_z(PARAM_LINEAR_DAMPING, 1.0);
+ set_param_z(PARAM_ANGULAR_LOWER_LIMIT, 0);
+ set_param_z(PARAM_ANGULAR_UPPER_LIMIT, 0);
+ set_param_z(PARAM_ANGULAR_LIMIT_SOFTNESS, 0.5f);
+ set_param_z(PARAM_ANGULAR_DAMPING, 1.0f);
+ set_param_z(PARAM_ANGULAR_RESTITUTION, 0);
+ set_param_z(PARAM_ANGULAR_FORCE_LIMIT, 0);
+ set_param_z(PARAM_ANGULAR_ERP, 0.5);
+ set_param_z(PARAM_ANGULAR_MOTOR_TARGET_VELOCITY, 0);
+ set_param_z(PARAM_ANGULAR_MOTOR_FORCE_LIMIT, 300);
+
+ set_flag_z(FLAG_ENABLE_ANGULAR_LIMIT, true);
+ set_flag_z(FLAG_ENABLE_LINEAR_LIMIT, true);
+ set_flag_z(FLAG_ENABLE_MOTOR, false);
}
-
-
-
#if 0
void PhysicsJoint::_set(const String& p_name, const Variant& p_value) {
diff --git a/scene/3d/physics_joint.h b/scene/3d/physics_joint.h
index 5debe87d38..90d86d652d 100644
--- a/scene/3d/physics_joint.h
+++ b/scene/3d/physics_joint.h
@@ -29,15 +29,14 @@
#ifndef PHYSICS_JOINT_H
#define PHYSICS_JOINT_H
-#include "scene/3d/spatial.h"
#include "scene/3d/physics_body.h"
-
+#include "scene/3d/spatial.h"
class Joint : public Spatial {
- GDCLASS(Joint,Spatial);
+ GDCLASS(Joint, Spatial);
- RID ba,bb;
+ RID ba, bb;
RID joint;
@@ -47,22 +46,20 @@ class Joint : public Spatial {
int solver_priority;
bool exclude_from_collision;
-
protected:
-
- void _update_joint(bool p_only_free=false);
+ void _update_joint(bool p_only_free = false);
void _notification(int p_what);
- virtual RID _configure_joint(PhysicsBody *body_a,PhysicsBody *body_b)=0;
+ virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b) = 0;
static void _bind_methods();
-public:
- void set_node_a(const NodePath& p_node_a);
+public:
+ void set_node_a(const NodePath &p_node_a);
NodePath get_node_a() const;
- void set_node_b(const NodePath& p_node_b);
+ void set_node_b(const NodePath &p_node_b);
NodePath get_node_b() const;
void set_solver_priority(int p_priority);
@@ -73,31 +70,28 @@ public:
RID get_joint() const { return joint; }
Joint();
-
};
///////////////////////////////////////////
-
class PinJoint : public Joint {
- GDCLASS(PinJoint,Joint);
-public:
+ GDCLASS(PinJoint, Joint);
+public:
enum Param {
- PARAM_BIAS=PhysicsServer::PIN_JOINT_BIAS,
- PARAM_DAMPING=PhysicsServer::PIN_JOINT_DAMPING,
- PARAM_IMPULSE_CLAMP=PhysicsServer::PIN_JOINT_IMPULSE_CLAMP
+ PARAM_BIAS = PhysicsServer::PIN_JOINT_BIAS,
+ PARAM_DAMPING = PhysicsServer::PIN_JOINT_DAMPING,
+ PARAM_IMPULSE_CLAMP = PhysicsServer::PIN_JOINT_IMPULSE_CLAMP
};
protected:
-
float params[3];
virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b);
static void _bind_methods();
-public:
- void set_param(Param p_param,float p_value);
+public:
+ void set_param(Param p_param, float p_value);
float get_param(Param p_param) const;
PinJoint();
@@ -105,34 +99,30 @@ public:
VARIANT_ENUM_CAST(PinJoint::Param);
-
class HingeJoint : public Joint {
- GDCLASS(HingeJoint,Joint);
-public:
+ GDCLASS(HingeJoint, Joint);
+public:
enum Param {
- PARAM_BIAS=PhysicsServer::HINGE_JOINT_BIAS,
- PARAM_LIMIT_UPPER=PhysicsServer::HINGE_JOINT_LIMIT_UPPER,
- PARAM_LIMIT_LOWER=PhysicsServer::HINGE_JOINT_LIMIT_LOWER,
- PARAM_LIMIT_BIAS=PhysicsServer::HINGE_JOINT_LIMIT_BIAS,
- PARAM_LIMIT_SOFTNESS=PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS,
- PARAM_LIMIT_RELAXATION=PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION,
- PARAM_MOTOR_TARGET_VELOCITY=PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY,
- PARAM_MOTOR_MAX_IMPULSE=PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE,
- PARAM_MAX=PhysicsServer::HINGE_JOINT_MAX
+ PARAM_BIAS = PhysicsServer::HINGE_JOINT_BIAS,
+ PARAM_LIMIT_UPPER = PhysicsServer::HINGE_JOINT_LIMIT_UPPER,
+ PARAM_LIMIT_LOWER = PhysicsServer::HINGE_JOINT_LIMIT_LOWER,
+ PARAM_LIMIT_BIAS = PhysicsServer::HINGE_JOINT_LIMIT_BIAS,
+ PARAM_LIMIT_SOFTNESS = PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS,
+ PARAM_LIMIT_RELAXATION = PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION,
+ PARAM_MOTOR_TARGET_VELOCITY = PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY,
+ PARAM_MOTOR_MAX_IMPULSE = PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE,
+ PARAM_MAX = PhysicsServer::HINGE_JOINT_MAX
};
enum Flag {
- FLAG_USE_LIMIT=PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT,
- FLAG_ENABLE_MOTOR=PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR,
- FLAG_MAX=PhysicsServer::HINGE_JOINT_FLAG_MAX
+ FLAG_USE_LIMIT = PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT,
+ FLAG_ENABLE_MOTOR = PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR,
+ FLAG_MAX = PhysicsServer::HINGE_JOINT_FLAG_MAX
};
-
-
protected:
-
float params[PARAM_MAX];
bool flags[FLAG_MAX];
virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b);
@@ -145,11 +135,10 @@ protected:
float _get_lower_limit() const;
public:
-
- void set_param(Param p_param,float p_value);
+ void set_param(Param p_param, float p_value);
float get_param(Param p_param) const;
- void set_flag(Flag p_flag,bool p_value);
+ void set_flag(Flag p_flag, bool p_value);
bool get_flag(Flag p_flag) const;
HingeJoint();
@@ -158,44 +147,40 @@ public:
VARIANT_ENUM_CAST(HingeJoint::Param);
VARIANT_ENUM_CAST(HingeJoint::Flag);
-
class SliderJoint : public Joint {
- GDCLASS(SliderJoint,Joint);
-public:
+ GDCLASS(SliderJoint, Joint);
+public:
enum Param {
- PARAM_LINEAR_LIMIT_UPPER=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER,
- PARAM_LINEAR_LIMIT_LOWER=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER,
- PARAM_LINEAR_LIMIT_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS,
- PARAM_LINEAR_LIMIT_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION,
- PARAM_LINEAR_LIMIT_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING,
- PARAM_LINEAR_MOTION_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS,
- PARAM_LINEAR_MOTION_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION,
- PARAM_LINEAR_MOTION_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING,
- PARAM_LINEAR_ORTHOGONAL_SOFTNESS=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS,
- PARAM_LINEAR_ORTHOGONAL_RESTITUTION=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION,
- PARAM_LINEAR_ORTHOGONAL_DAMPING=PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING,
-
- PARAM_ANGULAR_LIMIT_UPPER=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER,
- PARAM_ANGULAR_LIMIT_LOWER=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER,
- PARAM_ANGULAR_LIMIT_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS,
- PARAM_ANGULAR_LIMIT_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION,
- PARAM_ANGULAR_LIMIT_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING,
- PARAM_ANGULAR_MOTION_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS,
- PARAM_ANGULAR_MOTION_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION,
- PARAM_ANGULAR_MOTION_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING,
- PARAM_ANGULAR_ORTHOGONAL_SOFTNESS=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS,
- PARAM_ANGULAR_ORTHOGONAL_RESTITUTION=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION,
- PARAM_ANGULAR_ORTHOGONAL_DAMPING=PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING,
- PARAM_MAX=PhysicsServer::SLIDER_JOINT_MAX
+ PARAM_LINEAR_LIMIT_UPPER = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER,
+ PARAM_LINEAR_LIMIT_LOWER = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER,
+ PARAM_LINEAR_LIMIT_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS,
+ PARAM_LINEAR_LIMIT_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION,
+ PARAM_LINEAR_LIMIT_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING,
+ PARAM_LINEAR_MOTION_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS,
+ PARAM_LINEAR_MOTION_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION,
+ PARAM_LINEAR_MOTION_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING,
+ PARAM_LINEAR_ORTHOGONAL_SOFTNESS = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS,
+ PARAM_LINEAR_ORTHOGONAL_RESTITUTION = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION,
+ PARAM_LINEAR_ORTHOGONAL_DAMPING = PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING,
+
+ PARAM_ANGULAR_LIMIT_UPPER = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER,
+ PARAM_ANGULAR_LIMIT_LOWER = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER,
+ PARAM_ANGULAR_LIMIT_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS,
+ PARAM_ANGULAR_LIMIT_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION,
+ PARAM_ANGULAR_LIMIT_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING,
+ PARAM_ANGULAR_MOTION_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS,
+ PARAM_ANGULAR_MOTION_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION,
+ PARAM_ANGULAR_MOTION_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING,
+ PARAM_ANGULAR_ORTHOGONAL_SOFTNESS = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS,
+ PARAM_ANGULAR_ORTHOGONAL_RESTITUTION = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION,
+ PARAM_ANGULAR_ORTHOGONAL_DAMPING = PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING,
+ PARAM_MAX = PhysicsServer::SLIDER_JOINT_MAX
};
protected:
-
-
-
void _set_upper_limit_angular(float p_limit_angular);
float _get_upper_limit_angular() const;
@@ -205,25 +190,21 @@ protected:
float params[PARAM_MAX];
virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b);
static void _bind_methods();
-public:
- void set_param(Param p_param,float p_value);
+public:
+ void set_param(Param p_param, float p_value);
float get_param(Param p_param) const;
SliderJoint();
};
-
VARIANT_ENUM_CAST(SliderJoint::Param);
-
-
-
class ConeTwistJoint : public Joint {
- GDCLASS(ConeTwistJoint,Joint);
-public:
+ GDCLASS(ConeTwistJoint, Joint);
+public:
enum Param {
PARAM_SWING_SPAN,
@@ -235,8 +216,6 @@ public:
};
protected:
-
-
void _set_swing_span(float p_limit_angular);
float _get_swing_span() const;
@@ -246,53 +225,48 @@ protected:
float params[PARAM_MAX];
virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b);
static void _bind_methods();
-public:
- void set_param(Param p_param,float p_value);
+public:
+ void set_param(Param p_param, float p_value);
float get_param(Param p_param) const;
ConeTwistJoint();
};
-
VARIANT_ENUM_CAST(ConeTwistJoint::Param);
-
class Generic6DOFJoint : public Joint {
- GDCLASS(Generic6DOFJoint,Joint);
-public:
+ GDCLASS(Generic6DOFJoint, Joint);
+public:
enum Param {
- PARAM_LINEAR_LOWER_LIMIT=PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT,
- PARAM_LINEAR_UPPER_LIMIT=PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT,
- PARAM_LINEAR_LIMIT_SOFTNESS=PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS,
- PARAM_LINEAR_RESTITUTION=PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION,
- PARAM_LINEAR_DAMPING=PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING,
- PARAM_ANGULAR_LOWER_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT,
- PARAM_ANGULAR_UPPER_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT,
- PARAM_ANGULAR_LIMIT_SOFTNESS=PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS,
- PARAM_ANGULAR_DAMPING=PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING,
- PARAM_ANGULAR_RESTITUTION=PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION,
- PARAM_ANGULAR_FORCE_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT,
- PARAM_ANGULAR_ERP=PhysicsServer::G6DOF_JOINT_ANGULAR_ERP,
- PARAM_ANGULAR_MOTOR_TARGET_VELOCITY=PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY,
- PARAM_ANGULAR_MOTOR_FORCE_LIMIT=PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT,
- PARAM_MAX=PhysicsServer::G6DOF_JOINT_MAX,
+ PARAM_LINEAR_LOWER_LIMIT = PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT,
+ PARAM_LINEAR_UPPER_LIMIT = PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT,
+ PARAM_LINEAR_LIMIT_SOFTNESS = PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS,
+ PARAM_LINEAR_RESTITUTION = PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION,
+ PARAM_LINEAR_DAMPING = PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING,
+ PARAM_ANGULAR_LOWER_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT,
+ PARAM_ANGULAR_UPPER_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT,
+ PARAM_ANGULAR_LIMIT_SOFTNESS = PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS,
+ PARAM_ANGULAR_DAMPING = PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING,
+ PARAM_ANGULAR_RESTITUTION = PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION,
+ PARAM_ANGULAR_FORCE_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT,
+ PARAM_ANGULAR_ERP = PhysicsServer::G6DOF_JOINT_ANGULAR_ERP,
+ PARAM_ANGULAR_MOTOR_TARGET_VELOCITY = PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY,
+ PARAM_ANGULAR_MOTOR_FORCE_LIMIT = PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT,
+ PARAM_MAX = PhysicsServer::G6DOF_JOINT_MAX,
};
enum Flag {
- FLAG_ENABLE_LINEAR_LIMIT=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT,
- FLAG_ENABLE_ANGULAR_LIMIT=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT,
- FLAG_ENABLE_MOTOR=PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR,
- FLAG_MAX=PhysicsServer::G6DOF_JOINT_FLAG_MAX
+ FLAG_ENABLE_LINEAR_LIMIT = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT,
+ FLAG_ENABLE_ANGULAR_LIMIT = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT,
+ FLAG_ENABLE_MOTOR = PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR,
+ FLAG_MAX = PhysicsServer::G6DOF_JOINT_FLAG_MAX
};
-
protected:
-
-
void _set_angular_hi_limit_x(float p_limit_angular);
float _get_angular_hi_limit_x() const;
@@ -320,34 +294,32 @@ protected:
virtual RID _configure_joint(PhysicsBody *body_a, PhysicsBody *body_b);
static void _bind_methods();
-public:
- void set_param_x(Param p_param,float p_value);
+public:
+ void set_param_x(Param p_param, float p_value);
float get_param_x(Param p_param) const;
- void set_param_y(Param p_param,float p_value);
+ void set_param_y(Param p_param, float p_value);
float get_param_y(Param p_param) const;
- void set_param_z(Param p_param,float p_value);
+ void set_param_z(Param p_param, float p_value);
float get_param_z(Param p_param) const;
- void set_flag_x(Flag p_flag,bool p_enabled);
+ void set_flag_x(Flag p_flag, bool p_enabled);
bool get_flag_x(Flag p_flag) const;
- void set_flag_y(Flag p_flag,bool p_enabled);
+ void set_flag_y(Flag p_flag, bool p_enabled);
bool get_flag_y(Flag p_flag) const;
- void set_flag_z(Flag p_flag,bool p_enabled);
+ void set_flag_z(Flag p_flag, bool p_enabled);
bool get_flag_z(Flag p_flag) const;
Generic6DOFJoint();
};
-
VARIANT_ENUM_CAST(Generic6DOFJoint::Param);
VARIANT_ENUM_CAST(Generic6DOFJoint::Flag);
-
#if 0
class PhysicsJoint : public Spatial {
diff --git a/scene/3d/portal.cpp b/scene/3d/portal.cpp
index 19f1261238..391a74ec45 100644
--- a/scene/3d/portal.cpp
+++ b/scene/3d/portal.cpp
@@ -27,31 +27,31 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "portal.h"
-#include "servers/visual_server.h"
-#include "scene/resources/surface_tool.h"
#include "global_config.h"
+#include "scene/resources/surface_tool.h"
+#include "servers/visual_server.h"
-bool Portal::_set(const StringName& p_name, const Variant& p_value) {
+bool Portal::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name=="shape") {
- PoolVector<float> src_coords=p_value;
+ if (p_name == "shape") {
+ PoolVector<float> src_coords = p_value;
Vector<Point2> points;
int src_coords_size = src_coords.size();
- ERR_FAIL_COND_V(src_coords_size%2,false);
- points.resize(src_coords_size/2);
- for (int i=0;i<points.size();i++) {
+ ERR_FAIL_COND_V(src_coords_size % 2, false);
+ points.resize(src_coords_size / 2);
+ for (int i = 0; i < points.size(); i++) {
- points[i].x=src_coords[i*2+0];
- points[i].y=src_coords[i*2+1];
+ points[i].x = src_coords[i * 2 + 0];
+ points[i].y = src_coords[i * 2 + 1];
set_shape(points);
}
- } else if (p_name=="enabled") {
+ } else if (p_name == "enabled") {
set_enabled(p_value);
- } else if (p_name=="disable_distance") {
+ } else if (p_name == "disable_distance") {
set_disable_distance(p_value);
- } else if (p_name=="disabled_color") {
+ } else if (p_name == "disabled_color") {
set_disabled_color(p_value);
- } else if (p_name=="connect_range") {
+ } else if (p_name == "connect_range") {
set_connect_range(p_value);
} else
return false;
@@ -59,87 +59,82 @@ bool Portal::_set(const StringName& p_name, const Variant& p_value) {
return true;
}
-bool Portal::_get(const StringName& p_name,Variant &r_ret) const {
+bool Portal::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name=="shape") {
- Vector<Point2> points=get_shape();
+ if (p_name == "shape") {
+ Vector<Point2> points = get_shape();
PoolVector<float> dst_coords;
- dst_coords.resize(points.size()*2);
+ dst_coords.resize(points.size() * 2);
- for (int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
- dst_coords.set(i*2+0,points[i].x);
- dst_coords.set(i*2+1,points[i].y);
+ dst_coords.set(i * 2 + 0, points[i].x);
+ dst_coords.set(i * 2 + 1, points[i].y);
}
- r_ret= dst_coords;
- } else if (p_name=="enabled") {
- r_ret= is_enabled();
- } else if (p_name=="disable_distance") {
- r_ret= get_disable_distance();
- } else if (p_name=="disabled_color") {
- r_ret= get_disabled_color();
- } else if (p_name=="connect_range") {
- r_ret= get_connect_range();
+ r_ret = dst_coords;
+ } else if (p_name == "enabled") {
+ r_ret = is_enabled();
+ } else if (p_name == "disable_distance") {
+ r_ret = get_disable_distance();
+ } else if (p_name == "disabled_color") {
+ r_ret = get_disabled_color();
+ } else if (p_name == "connect_range") {
+ r_ret = get_connect_range();
} else
return false;
return true;
}
-void Portal::_get_property_list( List<PropertyInfo> *p_list) const {
+void Portal::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo( Variant::POOL_REAL_ARRAY, "shape" ) );
- p_list->push_back( PropertyInfo( Variant::BOOL, "enabled" ) );
- p_list->push_back( PropertyInfo( Variant::REAL, "disable_distance",PROPERTY_HINT_RANGE,"0,4096,0.01" ) );
- p_list->push_back( PropertyInfo( Variant::COLOR, "disabled_color") );
- p_list->push_back( PropertyInfo( Variant::REAL, "connect_range",PROPERTY_HINT_RANGE,"0.1,4096,0.01" ) );
+ p_list->push_back(PropertyInfo(Variant::POOL_REAL_ARRAY, "shape"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "enabled"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "disable_distance", PROPERTY_HINT_RANGE, "0,4096,0.01"));
+ p_list->push_back(PropertyInfo(Variant::COLOR, "disabled_color"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "connect_range", PROPERTY_HINT_RANGE, "0.1,4096,0.01"));
}
-
-
-
Rect3 Portal::get_aabb() const {
return aabb;
}
PoolVector<Face3> Portal::get_faces(uint32_t p_usage_flags) const {
- if (!(p_usage_flags&FACES_ENCLOSING))
+ if (!(p_usage_flags & FACES_ENCLOSING))
return PoolVector<Face3>();
Vector<Point2> shape = get_shape();
- if (shape.size()==0)
+ if (shape.size() == 0)
return PoolVector<Face3>();
Vector2 center;
- for (int i=0;i<shape.size();i++) {
-
- center+=shape[i];
+ for (int i = 0; i < shape.size(); i++) {
+ center += shape[i];
}
PoolVector<Face3> ret;
- center/=shape.size();
+ center /= shape.size();
- for (int i=0;i<shape.size();i++) {
+ for (int i = 0; i < shape.size(); i++) {
- int n=(i+1)%shape.size();
+ int n = (i + 1) % shape.size();
Face3 f;
- f.vertex[0]=Vector3( center.x, center.y, 0 );
- f.vertex[1]=Vector3( shape[i].x, shape[i].y, 0 );
- f.vertex[2]=Vector3( shape[n].x, shape[n].y, 0 );
+ f.vertex[0] = Vector3(center.x, center.y, 0);
+ f.vertex[1] = Vector3(shape[i].x, shape[i].y, 0);
+ f.vertex[2] = Vector3(shape[n].x, shape[n].y, 0);
ret.push_back(f);
}
return ret;
}
-void Portal::set_shape(const Vector<Point2>& p_shape) {
-
+void Portal::set_shape(const Vector<Point2> &p_shape) {
VisualServer::get_singleton()->portal_set_shape(portal, p_shape);
- shape=p_shape;
+ shape = p_shape;
update_gizmo();
}
@@ -150,7 +145,7 @@ Vector<Point2> Portal::get_shape() const {
void Portal::set_connect_range(float p_range) {
- connect_range=p_range;
+ connect_range = p_range;
//VisualServer::get_singleton()->portal_set_connect_range(portal,p_range);
}
@@ -159,35 +154,31 @@ float Portal::get_connect_range() const {
return connect_range;
}
-
void Portal::set_enabled(bool p_enabled) {
- enabled=p_enabled;
- VisualServer::get_singleton()->portal_set_enabled(portal,enabled);
+ enabled = p_enabled;
+ VisualServer::get_singleton()->portal_set_enabled(portal, enabled);
}
bool Portal::is_enabled() const {
-
return enabled;
}
void Portal::set_disable_distance(float p_distance) {
- disable_distance=p_distance;
- VisualServer::get_singleton()->portal_set_disable_distance(portal,disable_distance);
-
+ disable_distance = p_distance;
+ VisualServer::get_singleton()->portal_set_disable_distance(portal, disable_distance);
}
float Portal::get_disable_distance() const {
-
return disable_distance;
}
-void Portal::set_disabled_color(const Color& p_disabled_color) {
+void Portal::set_disabled_color(const Color &p_disabled_color) {
- disabled_color=p_disabled_color;
- VisualServer::get_singleton()->portal_set_disabled_color(portal,disabled_color);
+ disabled_color = p_disabled_color;
+ VisualServer::get_singleton()->portal_set_disabled_color(portal, disabled_color);
}
Color Portal::get_disabled_color() const {
@@ -197,47 +188,40 @@ Color Portal::get_disabled_color() const {
void Portal::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shape","points"),&Portal::set_shape);
- ClassDB::bind_method(D_METHOD("get_shape"),&Portal::get_shape);
+ ClassDB::bind_method(D_METHOD("set_shape", "points"), &Portal::set_shape);
+ ClassDB::bind_method(D_METHOD("get_shape"), &Portal::get_shape);
- ClassDB::bind_method(D_METHOD("set_enabled","enable"),&Portal::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&Portal::is_enabled);
+ ClassDB::bind_method(D_METHOD("set_enabled", "enable"), &Portal::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &Portal::is_enabled);
- ClassDB::bind_method(D_METHOD("set_disable_distance","distance"),&Portal::set_disable_distance);
- ClassDB::bind_method(D_METHOD("get_disable_distance"),&Portal::get_disable_distance);
+ ClassDB::bind_method(D_METHOD("set_disable_distance", "distance"), &Portal::set_disable_distance);
+ ClassDB::bind_method(D_METHOD("get_disable_distance"), &Portal::get_disable_distance);
- ClassDB::bind_method(D_METHOD("set_disabled_color","color"),&Portal::set_disabled_color);
- ClassDB::bind_method(D_METHOD("get_disabled_color"),&Portal::get_disabled_color);
-
- ClassDB::bind_method(D_METHOD("set_connect_range","range"),&Portal::set_connect_range);
- ClassDB::bind_method(D_METHOD("get_connect_range"),&Portal::get_connect_range);
+ ClassDB::bind_method(D_METHOD("set_disabled_color", "color"), &Portal::set_disabled_color);
+ ClassDB::bind_method(D_METHOD("get_disabled_color"), &Portal::get_disabled_color);
+ ClassDB::bind_method(D_METHOD("set_connect_range", "range"), &Portal::set_connect_range);
+ ClassDB::bind_method(D_METHOD("get_connect_range"), &Portal::get_connect_range);
}
Portal::Portal() {
portal = VisualServer::get_singleton()->portal_create();
- Vector< Point2 > points;
- points.push_back( Point2( -1, 1 ) );
- points.push_back( Point2( 1, 1 ) );
- points.push_back( Point2( 1, -1 ) );
- points.push_back( Point2( -1, -1 ) );
+ Vector<Point2> points;
+ points.push_back(Point2(-1, 1));
+ points.push_back(Point2(1, 1));
+ points.push_back(Point2(1, -1));
+ points.push_back(Point2(-1, -1));
set_shape(points); // default shape
-
set_connect_range(0.8);
set_disable_distance(50);
set_enabled(true);
set_base(portal);
-
-
}
-
Portal::~Portal() {
VisualServer::get_singleton()->free(portal);
}
-
-
diff --git a/scene/3d/portal.h b/scene/3d/portal.h
index 077924c7e8..018708308f 100644
--- a/scene/3d/portal.h
+++ b/scene/3d/portal.h
@@ -34,14 +34,11 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
/* Portal Logic:
If a portal is placed next (very close to) a similar, opposing portal, they automatically connect,
otherwise, a portal connects to the parent room
*/
-
-
class Portal : public VisualInstance {
GDCLASS(Portal, VisualInstance);
@@ -56,17 +53,14 @@ class Portal : public VisualInstance {
Rect3 aabb;
-
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
@@ -76,10 +70,10 @@ public:
void set_disable_distance(float p_distance);
float get_disable_distance() const;
- void set_disabled_color(const Color& p_disabled_color);
+ void set_disabled_color(const Color &p_disabled_color);
Color get_disabled_color() const;
- void set_shape(const Vector<Point2>& p_shape);
+ void set_shape(const Vector<Point2> &p_shape);
Vector<Point2> get_shape() const;
void set_connect_range(float p_range);
@@ -87,7 +81,6 @@ public:
Portal();
~Portal();
-
};
#endif
diff --git a/scene/3d/position_3d.cpp b/scene/3d/position_3d.cpp
index e7403053b2..ee09ed93a7 100644
--- a/scene/3d/position_3d.cpp
+++ b/scene/3d/position_3d.cpp
@@ -29,7 +29,5 @@
#include "position_3d.h"
#include "scene/resources/mesh.h"
-
-Position3D::Position3D()
-{
+Position3D::Position3D() {
}
diff --git a/scene/3d/position_3d.h b/scene/3d/position_3d.h
index e732c5321e..dae94dfbaf 100644
--- a/scene/3d/position_3d.h
+++ b/scene/3d/position_3d.h
@@ -31,13 +31,11 @@
#include "scene/3d/spatial.h"
-class Position3D : public Spatial {
-
- GDCLASS(Position3D,Spatial);
+class Position3D : public Spatial {
+ GDCLASS(Position3D, Spatial);
public:
-
Position3D();
};
diff --git a/scene/3d/proximity_group.cpp b/scene/3d/proximity_group.cpp
index f0dc8cb2ed..f1225b6901 100644
--- a/scene/3d/proximity_group.cpp
+++ b/scene/3d/proximity_group.cpp
@@ -47,7 +47,7 @@ void ProximityGroup::clear_groups() {
E = E->next();
};
- for (int i=0; i<num; i++) {
+ for (int i = 0; i < num; i++) {
groups.erase(remove_list[i]);
};
@@ -74,7 +74,7 @@ void ProximityGroup::update_groups() {
clear_groups();
};
-void ProximityGroup::add_groups(int* p_cell, String p_base, int p_depth) {
+void ProximityGroup::add_groups(int *p_cell, String p_base, int p_depth) {
p_base = p_base + "|";
if (grid_radius[p_depth] == 0) {
@@ -89,7 +89,7 @@ void ProximityGroup::add_groups(int* p_cell, String p_base, int p_depth) {
int start = p_cell[p_depth] - grid_radius[p_depth];
int end = p_cell[p_depth] + grid_radius[p_depth];
- for (int i=start; i<=end; i++) {
+ for (int i = start; i <= end; i++) {
String gname = p_base + itos(i);
if (p_depth == 2) {
@@ -102,7 +102,7 @@ void ProximityGroup::add_groups(int* p_cell, String p_base, int p_depth) {
void ProximityGroup::_new_group(StringName p_name) {
- const Map<StringName, uint32_t>::Element* E = groups.find(p_name);
+ const Map<StringName, uint32_t>::Element *E = groups.find(p_name);
if (!E) {
add_to_group(p_name);
};
@@ -119,13 +119,13 @@ void ProximityGroup::_notification(int what) {
switch (what) {
- case NOTIFICATION_EXIT_TREE:
- ++group_version;
- clear_groups();
- break;
- case NOTIFICATION_TRANSFORM_CHANGED:
- update_groups();
- break;
+ case NOTIFICATION_EXIT_TREE:
+ ++group_version;
+ clear_groups();
+ break;
+ case NOTIFICATION_TRANSFORM_CHANGED:
+ update_groups();
+ break;
};
};
@@ -138,7 +138,6 @@ void ProximityGroup::broadcast(String p_name, Variant p_params) {
get_tree()->call_group_flags(SceneTree::GROUP_CALL_DEFAULT, E->key(), "_proximity_group_broadcast", p_name, p_params);
E = E->next();
};
-
};
void ProximityGroup::_proximity_group_broadcast(String p_name, Variant p_params) {
@@ -152,13 +151,12 @@ void ProximityGroup::_proximity_group_broadcast(String p_name, Variant p_params)
};
};
-
void ProximityGroup::set_dispatch_mode(int p_mode) {
dispatch_mode = (DispatchMode)p_mode;
};
-void ProximityGroup::set_grid_radius(const Vector3& p_radius) {
+void ProximityGroup::set_grid_radius(const Vector3 &p_radius) {
grid_radius = p_radius;
};
@@ -168,22 +166,20 @@ Vector3 ProximityGroup::get_grid_radius() const {
return grid_radius;
};
-
void ProximityGroup::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_group_name","name"), &ProximityGroup::set_group_name);
- ClassDB::bind_method(D_METHOD("broadcast","name", "parameters"), &ProximityGroup::broadcast);
- ClassDB::bind_method(D_METHOD("set_dispatch_mode","mode"), &ProximityGroup::set_dispatch_mode);
- ClassDB::bind_method(D_METHOD("_proximity_group_broadcast","name","params"), &ProximityGroup::_proximity_group_broadcast);
- ClassDB::bind_method(D_METHOD("set_grid_radius","radius"), &ProximityGroup::set_grid_radius);
+ ClassDB::bind_method(D_METHOD("set_group_name", "name"), &ProximityGroup::set_group_name);
+ ClassDB::bind_method(D_METHOD("broadcast", "name", "parameters"), &ProximityGroup::broadcast);
+ ClassDB::bind_method(D_METHOD("set_dispatch_mode", "mode"), &ProximityGroup::set_dispatch_mode);
+ ClassDB::bind_method(D_METHOD("_proximity_group_broadcast", "name", "params"), &ProximityGroup::_proximity_group_broadcast);
+ ClassDB::bind_method(D_METHOD("set_grid_radius", "radius"), &ProximityGroup::set_grid_radius);
ClassDB::bind_method(D_METHOD("get_grid_radius"), &ProximityGroup::get_grid_radius);
- ADD_PROPERTY( PropertyInfo( Variant::VECTOR3, "grid_radius"), "set_grid_radius", "get_grid_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "grid_radius"), "set_grid_radius", "get_grid_radius");
- ADD_SIGNAL( MethodInfo("broadcast", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::ARRAY, "parameters")) );
+ ADD_SIGNAL(MethodInfo("broadcast", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::ARRAY, "parameters")));
};
-
ProximityGroup::ProximityGroup() {
group_version = 0;
@@ -191,9 +187,8 @@ ProximityGroup::ProximityGroup() {
grid_radius = Vector3(1, 1, 1);
set_notify_transform(true);
-
};
-ProximityGroup::~ProximityGroup() {
+ProximityGroup::~ProximityGroup(){
};
diff --git a/scene/3d/proximity_group.h b/scene/3d/proximity_group.h
index 58d2436975..f40ffe2ffe 100644
--- a/scene/3d/proximity_group.h
+++ b/scene/3d/proximity_group.h
@@ -33,7 +33,7 @@
class ProximityGroup : public Spatial {
- GDCLASS( ProximityGroup, Spatial );
+ GDCLASS(ProximityGroup, Spatial);
OBJ_CATEGORY("3D");
public:
@@ -57,7 +57,7 @@ public:
Vector3 grid_radius;
uint32_t group_version;
- void add_groups(int* p_cell, String p_base, int p_depth);
+ void add_groups(int *p_cell, String p_base, int p_depth);
void _new_group(StringName p_name);
void _proximity_group_broadcast(String p_name, Variant p_params);
@@ -65,12 +65,11 @@ public:
static void _bind_methods();
public:
-
void set_group_name(String p_group_name);
void broadcast(String p_name, Variant p_params);
void set_dispatch_mode(int p_mode);
- void set_grid_radius(const Vector3& p_radius);
+ void set_grid_radius(const Vector3 &p_radius);
Vector3 get_grid_radius() const;
ProximityGroup();
@@ -78,4 +77,3 @@ public:
};
#endif
-
diff --git a/scene/3d/quad.cpp b/scene/3d/quad.cpp
index e740769bd4..e32320681c 100644
--- a/scene/3d/quad.cpp
+++ b/scene/3d/quad.cpp
@@ -35,39 +35,36 @@ void Quad::_update() {
return;
Vector3 normal;
- normal[axis]=1.0;
-
- const int axis_order_1[3]={1,2,0};
- const int axis_order_2[3]={2,0,1};
- const int a1=axis_order_1[axis];
- const int a2=axis_order_2[axis];
-
+ normal[axis] = 1.0;
+ const int axis_order_1[3] = { 1, 2, 0 };
+ const int axis_order_2[3] = { 2, 0, 1 };
+ const int a1 = axis_order_1[axis];
+ const int a2 = axis_order_2[axis];
PoolVector<Vector3> points;
points.resize(4);
PoolVector<Vector3>::Write pointsw = points.write();
- Vector2 s2 = size*0.5;
+ Vector2 s2 = size * 0.5;
Vector2 o = offset;
if (!centered)
- o+=s2;
-
- pointsw[0][a1]=-s2.x+offset.x;
- pointsw[0][a2]=s2.y+offset.y;
+ o += s2;
- pointsw[1][a1]=s2.x+offset.x;
- pointsw[1][a2]=s2.y+offset.y;
+ pointsw[0][a1] = -s2.x + offset.x;
+ pointsw[0][a2] = s2.y + offset.y;
- pointsw[2][a1]=s2.x+offset.x;
- pointsw[2][a2]=-s2.y+offset.y;
+ pointsw[1][a1] = s2.x + offset.x;
+ pointsw[1][a2] = s2.y + offset.y;
- pointsw[3][a1]=-s2.x+offset.x;
- pointsw[3][a2]=-s2.y+offset.y;
+ pointsw[2][a1] = s2.x + offset.x;
+ pointsw[2][a2] = -s2.y + offset.y;
+ pointsw[3][a1] = -s2.x + offset.x;
+ pointsw[3][a2] = -s2.y + offset.y;
- aabb=Rect3(pointsw[0],Vector3());
- for(int i=1;i<4;i++)
+ aabb = Rect3(pointsw[0], Vector3());
+ for (int i = 1; i < 4; i++)
aabb.expand_to(pointsw[i]);
pointsw = PoolVector<Vector3>::Write();
@@ -76,21 +73,19 @@ void Quad::_update() {
normals.resize(4);
PoolVector<Vector3>::Write normalsw = normals.write();
- for(int i=0;i<4;i++)
- normalsw[i]=normal;
-
- normalsw=PoolVector<Vector3>::Write();
-
+ for (int i = 0; i < 4; i++)
+ normalsw[i] = normal;
+ normalsw = PoolVector<Vector3>::Write();
PoolVector<Vector2> uvs;
uvs.resize(4);
PoolVector<Vector2>::Write uvsw = uvs.write();
- uvsw[0]=Vector2(0,0);
- uvsw[1]=Vector2(1,0);
- uvsw[2]=Vector2(1,1);
- uvsw[3]=Vector2(0,1);
+ uvsw[0] = Vector2(0, 0);
+ uvsw[1] = Vector2(1, 0);
+ uvsw[2] = Vector2(1, 1);
+ uvsw[3] = Vector2(0, 1);
uvsw = PoolVector<Vector2>::Write();
@@ -98,90 +93,86 @@ void Quad::_update() {
indices.resize(6);
PoolVector<int>::Write indicesw = indices.write();
- indicesw[0]=0;
- indicesw[1]=1;
- indicesw[2]=2;
- indicesw[3]=2;
- indicesw[4]=3;
- indicesw[5]=0;
+ indicesw[0] = 0;
+ indicesw[1] = 1;
+ indicesw[2] = 2;
+ indicesw[3] = 2;
+ indicesw[4] = 3;
+ indicesw[5] = 0;
- indicesw=PoolVector<int>::Write();
+ indicesw = PoolVector<int>::Write();
Array arr;
arr.resize(VS::ARRAY_MAX);
- arr[VS::ARRAY_VERTEX]=points;
- arr[VS::ARRAY_NORMAL]=normals;
- arr[VS::ARRAY_TEX_UV]=uvs;
- arr[VS::ARRAY_INDEX]=indices;
-
+ arr[VS::ARRAY_VERTEX] = points;
+ arr[VS::ARRAY_NORMAL] = normals;
+ arr[VS::ARRAY_TEX_UV] = uvs;
+ arr[VS::ARRAY_INDEX] = indices;
if (configured) {
- VS::get_singleton()->mesh_remove_surface(mesh,0);
+ VS::get_singleton()->mesh_remove_surface(mesh, 0);
} else {
- configured=true;
+ configured = true;
}
- VS::get_singleton()->mesh_add_surface_from_arrays(mesh,VS::PRIMITIVE_TRIANGLES,arr);
+ VS::get_singleton()->mesh_add_surface_from_arrays(mesh, VS::PRIMITIVE_TRIANGLES, arr);
- pending_update=false;
+ pending_update = false;
}
-
void Quad::set_axis(Vector3::Axis p_axis) {
- axis=p_axis;
+ axis = p_axis;
_update();
}
-Vector3::Axis Quad::get_axis() const{
+Vector3::Axis Quad::get_axis() const {
return axis;
}
-void Quad::set_size(const Vector2& p_size){
+void Quad::set_size(const Vector2 &p_size) {
- size=p_size;
+ size = p_size;
_update();
}
-Vector2 Quad::get_size() const{
+Vector2 Quad::get_size() const {
return size;
}
-void Quad::set_offset(const Vector2& p_offset){
+void Quad::set_offset(const Vector2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
_update();
}
-Vector2 Quad::get_offset() const{
+Vector2 Quad::get_offset() const {
return offset;
}
-void Quad::set_centered(bool p_enabled){
+void Quad::set_centered(bool p_enabled) {
- centered=p_enabled;
+ centered = p_enabled;
_update();
}
-bool Quad::is_centered() const{
+bool Quad::is_centered() const {
return centered;
}
void Quad::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (pending_update)
_update();
-
} break;
case NOTIFICATION_EXIT_TREE: {
- pending_update=true;
-
+ pending_update = true;
} break;
}
@@ -197,38 +188,36 @@ Rect3 Quad::get_aabb() const {
return aabb;
}
-void Quad::_bind_methods(){
+void Quad::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_axis","axis"),&Quad::set_axis);
- ClassDB::bind_method(D_METHOD("get_axis"),&Quad::get_axis);
+ ClassDB::bind_method(D_METHOD("set_axis", "axis"), &Quad::set_axis);
+ ClassDB::bind_method(D_METHOD("get_axis"), &Quad::get_axis);
- ClassDB::bind_method(D_METHOD("set_size","size"),&Quad::set_size);
- ClassDB::bind_method(D_METHOD("get_size"),&Quad::get_size);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &Quad::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &Quad::get_size);
- ClassDB::bind_method(D_METHOD("set_centered","centered"),&Quad::set_centered);
- ClassDB::bind_method(D_METHOD("is_centered"),&Quad::is_centered);
+ ClassDB::bind_method(D_METHOD("set_centered", "centered"), &Quad::set_centered);
+ ClassDB::bind_method(D_METHOD("is_centered"), &Quad::is_centered);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&Quad::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&Quad::get_offset);
-
- ADD_PROPERTY( PropertyInfo( Variant::INT, "axis", PROPERTY_HINT_ENUM,"X,Y,Z" ), "set_axis", "get_axis");
- ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "size" ), "set_size", "get_size");
- ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "offset" ), "set_offset", "get_offset");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "centered" ), "set_centered", "is_centered");
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &Quad::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &Quad::get_offset);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "axis", PROPERTY_HINT_ENUM, "X,Y,Z"), "set_axis", "get_axis");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "size"), "set_size", "get_size");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
}
Quad::Quad() {
- pending_update=true;
- centered=true;
+ pending_update = true;
+ centered = true;
//offset=0;
- size=Vector2(1,1);
- axis=Vector3::AXIS_Z;
- mesh=VisualServer::get_singleton()->mesh_create();
+ size = Vector2(1, 1);
+ axis = Vector3::AXIS_Z;
+ mesh = VisualServer::get_singleton()->mesh_create();
set_base(mesh);
- configured=false;
-
+ configured = false;
}
Quad::~Quad() {
diff --git a/scene/3d/quad.h b/scene/3d/quad.h
index af91d7a1f5..607d7238ed 100644
--- a/scene/3d/quad.h
+++ b/scene/3d/quad.h
@@ -29,13 +29,12 @@
#ifndef QUAD_H
#define QUAD_H
-
-#include "scene/3d/visual_instance.h"
#include "rid.h"
+#include "scene/3d/visual_instance.h"
class Quad : public GeometryInstance {
- GDCLASS(Quad,GeometryInstance);
+ GDCLASS(Quad, GeometryInstance);
Vector3::Axis axis;
bool centered;
@@ -50,18 +49,17 @@ class Quad : public GeometryInstance {
void _update();
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_axis(Vector3::Axis p_axis);
Vector3::Axis get_axis() const;
- void set_size(const Vector2& p_sizze);
+ void set_size(const Vector2 &p_sizze);
Vector2 get_size() const;
- void set_offset(const Vector2& p_offset);
+ void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
void set_centered(bool p_enabled);
@@ -74,5 +72,4 @@ public:
~Quad();
};
-
#endif // QUAD_H
diff --git a/scene/3d/ray_cast.cpp b/scene/3d/ray_cast.cpp
index 6be8b89441..a73114a7c7 100644
--- a/scene/3d/ray_cast.cpp
+++ b/scene/3d/ray_cast.cpp
@@ -28,24 +28,23 @@
/*************************************************************************/
#include "ray_cast.h"
-#include "servers/physics_server.h"
#include "collision_object.h"
-void RayCast::set_cast_to(const Vector3& p_point) {
+#include "servers/physics_server.h"
+void RayCast::set_cast_to(const Vector3 &p_point) {
- cast_to=p_point;
+ cast_to = p_point;
if (is_inside_tree() && (get_tree()->is_editor_hint() || get_tree()->is_debugging_collisions_hint()))
update_gizmo();
-
}
-Vector3 RayCast::get_cast_to() const{
+Vector3 RayCast::get_cast_to() const {
return cast_to;
}
void RayCast::set_layer_mask(uint32_t p_mask) {
- layer_mask=p_mask;
+ layer_mask = p_mask;
}
uint32_t RayCast::get_layer_mask() const {
@@ -55,7 +54,7 @@ uint32_t RayCast::get_layer_mask() const {
void RayCast::set_type_mask(uint32_t p_mask) {
- type_mask=p_mask;
+ type_mask = p_mask;
}
uint32_t RayCast::get_type_mask() const {
@@ -63,13 +62,13 @@ uint32_t RayCast::get_type_mask() const {
return type_mask;
}
-bool RayCast::is_colliding() const{
+bool RayCast::is_colliding() const {
return collided;
}
-Object *RayCast::get_collider() const{
+Object *RayCast::get_collider() const {
- if (against==0)
+ if (against == 0)
return NULL;
return ObjectDB::get_instance(against);
@@ -79,37 +78,32 @@ int RayCast::get_collider_shape() const {
return against_shape;
}
-Vector3 RayCast::get_collision_point() const{
+Vector3 RayCast::get_collision_point() const {
return collision_point;
}
-Vector3 RayCast::get_collision_normal() const{
+Vector3 RayCast::get_collision_normal() const {
return collision_normal;
}
-
void RayCast::set_enabled(bool p_enabled) {
- enabled=p_enabled;
+ enabled = p_enabled;
if (is_inside_tree() && !get_tree()->is_editor_hint())
set_fixed_process(p_enabled);
if (!p_enabled)
- collided=false;
-
+ collided = false;
}
-
bool RayCast::is_enabled() const {
-
return enabled;
}
-
void RayCast::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -118,8 +112,6 @@ void RayCast::_notification(int p_what) {
} else
set_fixed_process(false);
-
-
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -127,7 +119,6 @@ void RayCast::_notification(int p_what) {
set_fixed_process(false);
}
-
} break;
case NOTIFICATION_FIXED_PROCESS: {
@@ -136,35 +127,34 @@ void RayCast::_notification(int p_what) {
_update_raycast_state();
-
} break;
}
}
-void RayCast::_update_raycast_state(){
+void RayCast::_update_raycast_state() {
Ref<World> w3d = get_world();
- ERR_FAIL_COND( w3d.is_null() );
+ ERR_FAIL_COND(w3d.is_null());
PhysicsDirectSpaceState *dss = PhysicsServer::get_singleton()->space_get_direct_state(w3d->get_space());
- ERR_FAIL_COND( !dss );
+ ERR_FAIL_COND(!dss);
Transform gt = get_global_transform();
Vector3 to = cast_to;
- if (to==Vector3())
- to=Vector3(0,0.01,0);
+ if (to == Vector3())
+ to = Vector3(0, 0.01, 0);
PhysicsDirectSpaceState::RayResult rr;
- if (dss->intersect_ray(gt.get_origin(),gt.xform(to),rr,exclude, layer_mask, type_mask)) {
+ if (dss->intersect_ray(gt.get_origin(), gt.xform(to), rr, exclude, layer_mask, type_mask)) {
- collided=true;
- against=rr.collider_id;
- collision_point=rr.position;
- collision_normal=rr.normal;
- against_shape=rr.shape;
+ collided = true;
+ against = rr.collider_id;
+ collision_point = rr.position;
+ collision_normal = rr.normal;
+ against_shape = rr.shape;
} else {
- collided=false;
+ collided = false;
}
}
@@ -172,85 +162,82 @@ void RayCast::force_raycast_update() {
_update_raycast_state();
}
-void RayCast::add_exception_rid(const RID& p_rid) {
+void RayCast::add_exception_rid(const RID &p_rid) {
exclude.insert(p_rid);
}
-void RayCast::add_exception(const Object* p_object){
+void RayCast::add_exception(const Object *p_object) {
ERR_FAIL_NULL(p_object);
- CollisionObject *co=((Object*)p_object)->cast_to<CollisionObject>();
+ CollisionObject *co = ((Object *)p_object)->cast_to<CollisionObject>();
if (!co)
return;
add_exception_rid(co->get_rid());
}
-void RayCast::remove_exception_rid(const RID& p_rid) {
+void RayCast::remove_exception_rid(const RID &p_rid) {
exclude.erase(p_rid);
}
-void RayCast::remove_exception(const Object* p_object){
+void RayCast::remove_exception(const Object *p_object) {
ERR_FAIL_NULL(p_object);
- CollisionObject *co=((Object*)p_object)->cast_to<CollisionObject>();
+ CollisionObject *co = ((Object *)p_object)->cast_to<CollisionObject>();
if (!co)
return;
remove_exception_rid(co->get_rid());
}
-
-void RayCast::clear_exceptions(){
+void RayCast::clear_exceptions() {
exclude.clear();
}
-
void RayCast::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &RayCast::set_enabled);
+ ClassDB::bind_method(D_METHOD("is_enabled"), &RayCast::is_enabled);
- ClassDB::bind_method(D_METHOD("set_enabled","enabled"),&RayCast::set_enabled);
- ClassDB::bind_method(D_METHOD("is_enabled"),&RayCast::is_enabled);
-
- ClassDB::bind_method(D_METHOD("set_cast_to","local_point"),&RayCast::set_cast_to);
- ClassDB::bind_method(D_METHOD("get_cast_to"),&RayCast::get_cast_to);
+ ClassDB::bind_method(D_METHOD("set_cast_to", "local_point"), &RayCast::set_cast_to);
+ ClassDB::bind_method(D_METHOD("get_cast_to"), &RayCast::get_cast_to);
- ClassDB::bind_method(D_METHOD("is_colliding"),&RayCast::is_colliding);
- ClassDB::bind_method(D_METHOD("force_raycast_update"),&RayCast::force_raycast_update);
+ ClassDB::bind_method(D_METHOD("is_colliding"), &RayCast::is_colliding);
+ ClassDB::bind_method(D_METHOD("force_raycast_update"), &RayCast::force_raycast_update);
- ClassDB::bind_method(D_METHOD("get_collider"),&RayCast::get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_shape"),&RayCast::get_collider_shape);
- ClassDB::bind_method(D_METHOD("get_collision_point"),&RayCast::get_collision_point);
- ClassDB::bind_method(D_METHOD("get_collision_normal"),&RayCast::get_collision_normal);
+ ClassDB::bind_method(D_METHOD("get_collider"), &RayCast::get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_shape"), &RayCast::get_collider_shape);
+ ClassDB::bind_method(D_METHOD("get_collision_point"), &RayCast::get_collision_point);
+ ClassDB::bind_method(D_METHOD("get_collision_normal"), &RayCast::get_collision_normal);
- ClassDB::bind_method(D_METHOD("add_exception_rid","rid"),&RayCast::add_exception_rid);
- ClassDB::bind_method(D_METHOD("add_exception","node"),&RayCast::add_exception);
+ ClassDB::bind_method(D_METHOD("add_exception_rid", "rid"), &RayCast::add_exception_rid);
+ ClassDB::bind_method(D_METHOD("add_exception", "node"), &RayCast::add_exception);
- ClassDB::bind_method(D_METHOD("remove_exception_rid","rid"),&RayCast::remove_exception_rid);
- ClassDB::bind_method(D_METHOD("remove_exception","node"),&RayCast::remove_exception);
+ ClassDB::bind_method(D_METHOD("remove_exception_rid", "rid"), &RayCast::remove_exception_rid);
+ ClassDB::bind_method(D_METHOD("remove_exception", "node"), &RayCast::remove_exception);
- ClassDB::bind_method(D_METHOD("clear_exceptions"),&RayCast::clear_exceptions);
+ ClassDB::bind_method(D_METHOD("clear_exceptions"), &RayCast::clear_exceptions);
- ClassDB::bind_method(D_METHOD("set_layer_mask","mask"),&RayCast::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&RayCast::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &RayCast::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &RayCast::get_layer_mask);
- ClassDB::bind_method(D_METHOD("set_type_mask","mask"),&RayCast::set_type_mask);
- ClassDB::bind_method(D_METHOD("get_type_mask"),&RayCast::get_type_mask);
+ ClassDB::bind_method(D_METHOD("set_type_mask", "mask"), &RayCast::set_type_mask);
+ ClassDB::bind_method(D_METHOD("get_type_mask"), &RayCast::get_type_mask);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"enabled"),"set_enabled","is_enabled");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR3,"cast_to"),"set_cast_to","get_cast_to");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"layer_mask",PROPERTY_HINT_LAYERS_3D_PHYSICS),"set_layer_mask","get_layer_mask");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"type_mask",PROPERTY_HINT_FLAGS,"Static,Kinematic,Rigid,Character,Area"),"set_type_mask","get_type_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "cast_to"), "set_cast_to", "get_cast_to");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layer_mask", PROPERTY_HINT_LAYERS_3D_PHYSICS), "set_layer_mask", "get_layer_mask");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "type_mask", PROPERTY_HINT_FLAGS, "Static,Kinematic,Rigid,Character,Area"), "set_type_mask", "get_type_mask");
}
RayCast::RayCast() {
- enabled=false;
- against=0;
- collided=false;
- against_shape=0;
- layer_mask=1;
- type_mask=PhysicsDirectSpaceState::TYPE_MASK_COLLISION;
- cast_to=Vector3(0,-1,0);
+ enabled = false;
+ against = 0;
+ collided = false;
+ against_shape = 0;
+ layer_mask = 1;
+ type_mask = PhysicsDirectSpaceState::TYPE_MASK_COLLISION;
+ cast_to = Vector3(0, -1, 0);
}
diff --git a/scene/3d/ray_cast.h b/scene/3d/ray_cast.h
index 32d24cc962..00a10446a5 100644
--- a/scene/3d/ray_cast.h
+++ b/scene/3d/ray_cast.h
@@ -33,8 +33,7 @@
class RayCast : public Spatial {
- GDCLASS(RayCast,Spatial);
-
+ GDCLASS(RayCast, Spatial);
bool enabled;
bool collided;
@@ -51,16 +50,15 @@ class RayCast : public Spatial {
uint32_t type_mask;
protected:
-
void _notification(int p_what);
void _update_raycast_state();
static void _bind_methods();
-public:
+public:
void set_enabled(bool p_enabled);
bool is_enabled() const;
- void set_cast_to(const Vector3& p_point);
+ void set_cast_to(const Vector3 &p_point);
Vector3 get_cast_to() const;
void set_layer_mask(uint32_t p_mask);
@@ -76,10 +74,10 @@ public:
Vector3 get_collision_point() const;
Vector3 get_collision_normal() const;
- void add_exception_rid(const RID& p_rid);
- void add_exception(const Object* p_object);
- void remove_exception_rid(const RID& p_rid);
- void remove_exception(const Object* p_object);
+ void add_exception_rid(const RID &p_rid);
+ void add_exception(const Object *p_object);
+ void remove_exception_rid(const RID &p_rid);
+ void remove_exception(const Object *p_object);
void clear_exceptions();
RayCast();
diff --git a/scene/3d/reflection_probe.cpp b/scene/3d/reflection_probe.cpp
index db18e70ae1..90dbd51272 100644
--- a/scene/3d/reflection_probe.cpp
+++ b/scene/3d/reflection_probe.cpp
@@ -28,129 +28,119 @@
/*************************************************************************/
#include "reflection_probe.h"
-
void ReflectionProbe::set_intensity(float p_intensity) {
- intensity=p_intensity;
- VS::get_singleton()->reflection_probe_set_intensity(probe,p_intensity);
+ intensity = p_intensity;
+ VS::get_singleton()->reflection_probe_set_intensity(probe, p_intensity);
}
-float ReflectionProbe::get_intensity() const{
+float ReflectionProbe::get_intensity() const {
return intensity;
}
-
void ReflectionProbe::set_interior_ambient(Color p_ambient) {
- interior_ambient=p_ambient;
- VS::get_singleton()->reflection_probe_set_interior_ambient(probe,p_ambient);
+ interior_ambient = p_ambient;
+ VS::get_singleton()->reflection_probe_set_interior_ambient(probe, p_ambient);
}
void ReflectionProbe::set_interior_ambient_energy(float p_energy) {
- interior_ambient_energy=p_energy;
- VS::get_singleton()->reflection_probe_set_interior_ambient_energy(probe,p_energy);
+ interior_ambient_energy = p_energy;
+ VS::get_singleton()->reflection_probe_set_interior_ambient_energy(probe, p_energy);
}
-float ReflectionProbe::get_interior_ambient_energy() const{
+float ReflectionProbe::get_interior_ambient_energy() const {
return interior_ambient_energy;
}
-
-Color ReflectionProbe::get_interior_ambient() const{
+Color ReflectionProbe::get_interior_ambient() const {
return interior_ambient;
}
void ReflectionProbe::set_interior_ambient_probe_contribution(float p_contribution) {
- interior_ambient_probe_contribution=p_contribution;
- VS::get_singleton()->reflection_probe_set_interior_ambient_probe_contribution(probe,p_contribution);
+ interior_ambient_probe_contribution = p_contribution;
+ VS::get_singleton()->reflection_probe_set_interior_ambient_probe_contribution(probe, p_contribution);
}
-float ReflectionProbe::get_interior_ambient_probe_contribution() const{
+float ReflectionProbe::get_interior_ambient_probe_contribution() const {
return interior_ambient_probe_contribution;
}
+void ReflectionProbe::set_max_distance(float p_distance) {
-void ReflectionProbe::set_max_distance(float p_distance){
-
- max_distance=p_distance;
- VS::get_singleton()->reflection_probe_set_max_distance(probe,p_distance);
+ max_distance = p_distance;
+ VS::get_singleton()->reflection_probe_set_max_distance(probe, p_distance);
}
-float ReflectionProbe::get_max_distance() const{
+float ReflectionProbe::get_max_distance() const {
return max_distance;
}
+void ReflectionProbe::set_extents(const Vector3 &p_extents) {
-void ReflectionProbe::set_extents(const Vector3& p_extents){
+ extents = p_extents;
- extents=p_extents;
-
- for(int i=0;i<3;i++) {
- if (extents[i]<0.01) {
- extents[i]=0.01;
+ for (int i = 0; i < 3; i++) {
+ if (extents[i] < 0.01) {
+ extents[i] = 0.01;
}
- if (extents[i]-0.01<ABS(origin_offset[i])) {
- origin_offset[i]=SGN(origin_offset[i])*(extents[i]-0.01);
+ if (extents[i] - 0.01 < ABS(origin_offset[i])) {
+ origin_offset[i] = SGN(origin_offset[i]) * (extents[i] - 0.01);
_change_notify("origin_offset");
}
}
- VS::get_singleton()->reflection_probe_set_extents(probe,extents);
- VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset);
+ VS::get_singleton()->reflection_probe_set_extents(probe, extents);
+ VS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
_change_notify("extents");
update_gizmo();
-
}
-Vector3 ReflectionProbe::get_extents() const{
+Vector3 ReflectionProbe::get_extents() const {
return extents;
}
-void ReflectionProbe::set_origin_offset(const Vector3& p_extents){
+void ReflectionProbe::set_origin_offset(const Vector3 &p_extents) {
- origin_offset=p_extents;
+ origin_offset = p_extents;
- for(int i=0;i<3;i++) {
-
- if (extents[i]-0.01<ABS(origin_offset[i])) {
- origin_offset[i]=SGN(origin_offset[i])*(extents[i]-0.01);
+ for (int i = 0; i < 3; i++) {
+ if (extents[i] - 0.01 < ABS(origin_offset[i])) {
+ origin_offset[i] = SGN(origin_offset[i]) * (extents[i] - 0.01);
}
}
- VS::get_singleton()->reflection_probe_set_extents(probe,extents);
- VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset);
+ VS::get_singleton()->reflection_probe_set_extents(probe, extents);
+ VS::get_singleton()->reflection_probe_set_origin_offset(probe, origin_offset);
_change_notify("origin_offset");
update_gizmo();
}
-Vector3 ReflectionProbe::get_origin_offset() const{
+Vector3 ReflectionProbe::get_origin_offset() const {
return origin_offset;
}
-void ReflectionProbe::set_enable_box_projection(bool p_enable){
-
- box_projection=p_enable;
- VS::get_singleton()->reflection_probe_set_enable_box_projection(probe,p_enable);
+void ReflectionProbe::set_enable_box_projection(bool p_enable) {
+ box_projection = p_enable;
+ VS::get_singleton()->reflection_probe_set_enable_box_projection(probe, p_enable);
}
-bool ReflectionProbe::is_box_projection_enabled() const{
+bool ReflectionProbe::is_box_projection_enabled() const {
return box_projection;
}
-
void ReflectionProbe::set_as_interior(bool p_enable) {
- interior=p_enable;
- VS::get_singleton()->reflection_probe_set_as_interior(probe,interior);
+ interior = p_enable;
+ VS::get_singleton()->reflection_probe_set_as_interior(probe, interior);
_change_notify();
-
}
bool ReflectionProbe::is_set_as_interior() const {
@@ -158,12 +148,10 @@ bool ReflectionProbe::is_set_as_interior() const {
return interior;
}
-
-
void ReflectionProbe::set_enable_shadows(bool p_enable) {
- enable_shadows=p_enable;
- VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_enable);
+ enable_shadows = p_enable;
+ VS::get_singleton()->reflection_probe_set_enable_shadows(probe, p_enable);
}
bool ReflectionProbe::are_shadows_enabled() const {
@@ -172,8 +160,8 @@ bool ReflectionProbe::are_shadows_enabled() const {
void ReflectionProbe::set_cull_mask(uint32_t p_layers) {
- cull_mask=p_layers;
- VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_layers);
+ cull_mask = p_layers;
+ VS::get_singleton()->reflection_probe_set_enable_shadows(probe, p_layers);
}
uint32_t ReflectionProbe::get_cull_mask() const {
@@ -181,20 +169,19 @@ uint32_t ReflectionProbe::get_cull_mask() const {
}
void ReflectionProbe::set_update_mode(UpdateMode p_mode) {
- update_mode=p_mode;
- VS::get_singleton()->reflection_probe_set_update_mode(probe,VS::ReflectionProbeUpdateMode(p_mode));
+ update_mode = p_mode;
+ VS::get_singleton()->reflection_probe_set_update_mode(probe, VS::ReflectionProbeUpdateMode(p_mode));
}
ReflectionProbe::UpdateMode ReflectionProbe::get_update_mode() const {
return update_mode;
}
-
Rect3 ReflectionProbe::get_aabb() const {
Rect3 aabb;
- aabb.pos=-origin_offset;
- aabb.size=origin_offset+extents;
+ aabb.pos = -origin_offset;
+ aabb.size = origin_offset + extents;
return aabb;
}
PoolVector<Face3> ReflectionProbe::get_faces(uint32_t p_usage_flags) const {
@@ -202,92 +189,89 @@ PoolVector<Face3> ReflectionProbe::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
}
-void ReflectionProbe::_validate_property(PropertyInfo& property) const {
+void ReflectionProbe::_validate_property(PropertyInfo &property) const {
- if (property.name=="interior/ambient_color" || property.name=="interior/ambient_energy" || property.name=="interior/ambient_contrib") {
+ if (property.name == "interior/ambient_color" || property.name == "interior/ambient_energy" || property.name == "interior/ambient_contrib") {
if (!interior) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
}
void ReflectionProbe::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_intensity","intensity"),&ReflectionProbe::set_intensity);
- ClassDB::bind_method(D_METHOD("get_intensity"),&ReflectionProbe::get_intensity);
-
- ClassDB::bind_method(D_METHOD("set_interior_ambient","ambient"),&ReflectionProbe::set_interior_ambient);
- ClassDB::bind_method(D_METHOD("get_interior_ambient"),&ReflectionProbe::get_interior_ambient);
-
- ClassDB::bind_method(D_METHOD("set_interior_ambient_energy","ambient_energy"),&ReflectionProbe::set_interior_ambient_energy);
- ClassDB::bind_method(D_METHOD("get_interior_ambient_energy"),&ReflectionProbe::get_interior_ambient_energy);
-
- ClassDB::bind_method(D_METHOD("set_interior_ambient_probe_contribution","ambient_probe_contribution"),&ReflectionProbe::set_interior_ambient_probe_contribution);
- ClassDB::bind_method(D_METHOD("get_interior_ambient_probe_contribution"),&ReflectionProbe::get_interior_ambient_probe_contribution);
+ ClassDB::bind_method(D_METHOD("set_intensity", "intensity"), &ReflectionProbe::set_intensity);
+ ClassDB::bind_method(D_METHOD("get_intensity"), &ReflectionProbe::get_intensity);
- ClassDB::bind_method(D_METHOD("set_max_distance","max_distance"),&ReflectionProbe::set_max_distance);
- ClassDB::bind_method(D_METHOD("get_max_distance"),&ReflectionProbe::get_max_distance);
+ ClassDB::bind_method(D_METHOD("set_interior_ambient", "ambient"), &ReflectionProbe::set_interior_ambient);
+ ClassDB::bind_method(D_METHOD("get_interior_ambient"), &ReflectionProbe::get_interior_ambient);
- ClassDB::bind_method(D_METHOD("set_extents","extents"),&ReflectionProbe::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"),&ReflectionProbe::get_extents);
+ ClassDB::bind_method(D_METHOD("set_interior_ambient_energy", "ambient_energy"), &ReflectionProbe::set_interior_ambient_energy);
+ ClassDB::bind_method(D_METHOD("get_interior_ambient_energy"), &ReflectionProbe::get_interior_ambient_energy);
- ClassDB::bind_method(D_METHOD("set_origin_offset","origin_offset"),&ReflectionProbe::set_origin_offset);
- ClassDB::bind_method(D_METHOD("get_origin_offset"),&ReflectionProbe::get_origin_offset);
+ ClassDB::bind_method(D_METHOD("set_interior_ambient_probe_contribution", "ambient_probe_contribution"), &ReflectionProbe::set_interior_ambient_probe_contribution);
+ ClassDB::bind_method(D_METHOD("get_interior_ambient_probe_contribution"), &ReflectionProbe::get_interior_ambient_probe_contribution);
- ClassDB::bind_method(D_METHOD("set_as_interior","enable"),&ReflectionProbe::set_as_interior);
- ClassDB::bind_method(D_METHOD("is_set_as_interior"),&ReflectionProbe::is_set_as_interior);
+ ClassDB::bind_method(D_METHOD("set_max_distance", "max_distance"), &ReflectionProbe::set_max_distance);
+ ClassDB::bind_method(D_METHOD("get_max_distance"), &ReflectionProbe::get_max_distance);
- ClassDB::bind_method(D_METHOD("set_enable_box_projection","enable"),&ReflectionProbe::set_enable_box_projection);
- ClassDB::bind_method(D_METHOD("is_box_projection_enabled"),&ReflectionProbe::is_box_projection_enabled);
+ ClassDB::bind_method(D_METHOD("set_extents", "extents"), &ReflectionProbe::set_extents);
+ ClassDB::bind_method(D_METHOD("get_extents"), &ReflectionProbe::get_extents);
+ ClassDB::bind_method(D_METHOD("set_origin_offset", "origin_offset"), &ReflectionProbe::set_origin_offset);
+ ClassDB::bind_method(D_METHOD("get_origin_offset"), &ReflectionProbe::get_origin_offset);
- ClassDB::bind_method(D_METHOD("set_enable_shadows","enable"),&ReflectionProbe::set_enable_shadows);
- ClassDB::bind_method(D_METHOD("are_shadows_enabled"),&ReflectionProbe::are_shadows_enabled);
+ ClassDB::bind_method(D_METHOD("set_as_interior", "enable"), &ReflectionProbe::set_as_interior);
+ ClassDB::bind_method(D_METHOD("is_set_as_interior"), &ReflectionProbe::is_set_as_interior);
- ClassDB::bind_method(D_METHOD("set_cull_mask","layers"),&ReflectionProbe::set_cull_mask);
- ClassDB::bind_method(D_METHOD("get_cull_mask"),&ReflectionProbe::get_cull_mask);
+ ClassDB::bind_method(D_METHOD("set_enable_box_projection", "enable"), &ReflectionProbe::set_enable_box_projection);
+ ClassDB::bind_method(D_METHOD("is_box_projection_enabled"), &ReflectionProbe::is_box_projection_enabled);
- ClassDB::bind_method(D_METHOD("set_update_mode","mode"),&ReflectionProbe::set_update_mode);
- ClassDB::bind_method(D_METHOD("get_update_mode"),&ReflectionProbe::get_update_mode);
+ ClassDB::bind_method(D_METHOD("set_enable_shadows", "enable"), &ReflectionProbe::set_enable_shadows);
+ ClassDB::bind_method(D_METHOD("are_shadows_enabled"), &ReflectionProbe::are_shadows_enabled);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"update_mode",PROPERTY_HINT_ENUM,"Once,Always"),"set_update_mode","get_update_mode");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"intensity",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_intensity","get_intensity");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"max_distance",PROPERTY_HINT_RANGE,"0,16384,0.1"),"set_max_distance","get_max_distance");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"extents"),"set_extents","get_extents");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"origin_offset"),"set_origin_offset","get_origin_offset");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"box_projection"),"set_enable_box_projection","is_box_projection_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enable_shadows"),"set_enable_shadows","are_shadows_enabled");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER),"set_cull_mask","get_cull_mask");
+ ClassDB::bind_method(D_METHOD("set_cull_mask", "layers"), &ReflectionProbe::set_cull_mask);
+ ClassDB::bind_method(D_METHOD("get_cull_mask"), &ReflectionProbe::get_cull_mask);
- ADD_GROUP("Interior","interior_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior_enable"),"set_as_interior","is_set_as_interior");
- ADD_PROPERTY( PropertyInfo(Variant::COLOR,"interior_ambient_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_interior_ambient","get_interior_ambient");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_interior_ambient_energy","get_interior_ambient_energy");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_contrib",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_interior_ambient_probe_contribution","get_interior_ambient_probe_contribution");
+ ClassDB::bind_method(D_METHOD("set_update_mode", "mode"), &ReflectionProbe::set_update_mode);
+ ClassDB::bind_method(D_METHOD("get_update_mode"), &ReflectionProbe::get_update_mode);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "update_mode", PROPERTY_HINT_ENUM, "Once,Always"), "set_update_mode", "get_update_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "intensity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_intensity", "get_intensity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "max_distance", PROPERTY_HINT_RANGE, "0,16384,0.1"), "set_max_distance", "get_max_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "extents"), "set_extents", "get_extents");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "origin_offset"), "set_origin_offset", "get_origin_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "box_projection"), "set_enable_box_projection", "is_box_projection_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enable_shadows"), "set_enable_shadows", "are_shadows_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "cull_mask", PROPERTY_HINT_LAYERS_3D_RENDER), "set_cull_mask", "get_cull_mask");
- BIND_CONSTANT( UPDATE_ONCE );
- BIND_CONSTANT( UPDATE_ALWAYS );
+ ADD_GROUP("Interior", "interior_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "interior_enable"), "set_as_interior", "is_set_as_interior");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "interior_ambient_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_interior_ambient", "get_interior_ambient");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "interior_ambient_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_interior_ambient_energy", "get_interior_ambient_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "interior_ambient_contrib", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_interior_ambient_probe_contribution", "get_interior_ambient_probe_contribution");
+ BIND_CONSTANT(UPDATE_ONCE);
+ BIND_CONSTANT(UPDATE_ALWAYS);
}
ReflectionProbe::ReflectionProbe() {
- intensity=1.0;
- interior_ambient=Color(0,0,0);
- interior_ambient_probe_contribution=0;
- interior_ambient_energy=1.0;
- max_distance=0;
- extents=Vector3(1,1,1);
- origin_offset=Vector3(0,0,0);
- box_projection=false;
- interior=false;
- enable_shadows=false;
- cull_mask=(1<<20)-1;
- update_mode=UPDATE_ONCE;
-
- probe=VisualServer::get_singleton()->reflection_probe_create();
- VS::get_singleton()->instance_set_base(get_instance(),probe);
+ intensity = 1.0;
+ interior_ambient = Color(0, 0, 0);
+ interior_ambient_probe_contribution = 0;
+ interior_ambient_energy = 1.0;
+ max_distance = 0;
+ extents = Vector3(1, 1, 1);
+ origin_offset = Vector3(0, 0, 0);
+ box_projection = false;
+ interior = false;
+ enable_shadows = false;
+ cull_mask = (1 << 20) - 1;
+ update_mode = UPDATE_ONCE;
+
+ probe = VisualServer::get_singleton()->reflection_probe_create();
+ VS::get_singleton()->instance_set_base(get_instance(), probe);
}
ReflectionProbe::~ReflectionProbe() {
diff --git a/scene/3d/reflection_probe.h b/scene/3d/reflection_probe.h
index cfda186d87..a2e4a18d68 100644
--- a/scene/3d/reflection_probe.h
+++ b/scene/3d/reflection_probe.h
@@ -30,23 +30,20 @@
#define REFLECTIONPROBE_H
#include "scene/3d/visual_instance.h"
-#include "scene/resources/texture.h"
#include "scene/resources/sky_box.h"
+#include "scene/resources/texture.h"
#include "servers/visual_server.h"
class ReflectionProbe : public VisualInstance {
- GDCLASS(ReflectionProbe,VisualInstance);
+ GDCLASS(ReflectionProbe, VisualInstance);
public:
-
enum UpdateMode {
UPDATE_ONCE,
UPDATE_ALWAYS,
};
-
private:
-
RID probe;
float intensity;
float max_distance;
@@ -63,12 +60,10 @@ private:
UpdateMode update_mode;
protected:
-
static void _bind_methods();
- void _validate_property(PropertyInfo& property) const;
+ void _validate_property(PropertyInfo &property) const;
public:
-
void set_intensity(float p_intensity);
float get_intensity() const;
@@ -84,10 +79,10 @@ public:
void set_max_distance(float p_distance);
float get_max_distance() const;
- void set_extents(const Vector3& p_extents);
+ void set_extents(const Vector3 &p_extents);
Vector3 get_extents() const;
- void set_origin_offset(const Vector3& p_extents);
+ void set_origin_offset(const Vector3 &p_extents);
Vector3 get_origin_offset() const;
void set_as_interior(bool p_enable);
@@ -108,13 +103,10 @@ public:
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
-
-
ReflectionProbe();
~ReflectionProbe();
};
-
-VARIANT_ENUM_CAST( ReflectionProbe::UpdateMode );
+VARIANT_ENUM_CAST(ReflectionProbe::UpdateMode);
#endif // REFLECTIONPROBE_H
diff --git a/scene/3d/remote_transform.cpp b/scene/3d/remote_transform.cpp
index 21ec65f5e0..202206dd02 100644
--- a/scene/3d/remote_transform.cpp
+++ b/scene/3d/remote_transform.cpp
@@ -31,20 +31,19 @@
#include "remote_transform.h"
void RemoteTransform::_update_cache() {
- cache=0;
+ cache = 0;
if (has_node(remote_node)) {
Node *node = get_node(remote_node);
- if (!node || this==node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
+ if (!node || this == node || node->is_a_parent_of(this) || this->is_a_parent_of(node)) {
return;
}
- cache=node->get_instance_ID();
+ cache = node->get_instance_ID();
}
}
void RemoteTransform::_update_remote() {
-
if (!is_inside_tree())
return;
@@ -64,12 +63,11 @@ void RemoteTransform::_update_remote() {
//todo make faster
n->set_global_transform(get_global_transform());
-
}
void RemoteTransform::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_READY: {
@@ -83,30 +81,26 @@ void RemoteTransform::_notification(int p_what) {
if (cache) {
_update_remote();
-
}
} break;
-
}
}
+void RemoteTransform::set_remote_node(const NodePath &p_remote_node) {
-void RemoteTransform::set_remote_node(const NodePath& p_remote_node) {
-
- remote_node=p_remote_node;
+ remote_node = p_remote_node;
if (is_inside_tree())
_update_cache();
update_configuration_warning();
}
-NodePath RemoteTransform::get_remote_node() const{
+NodePath RemoteTransform::get_remote_node() const {
return remote_node;
}
-
String RemoteTransform::get_configuration_warning() const {
if (!has_node(remote_node) || !get_node(remote_node) || !get_node(remote_node)->cast_to<Spatial>()) {
@@ -118,16 +112,14 @@ String RemoteTransform::get_configuration_warning() const {
void RemoteTransform::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_remote_node","path"),&RemoteTransform::set_remote_node);
- ClassDB::bind_method(D_METHOD("get_remote_node"),&RemoteTransform::get_remote_node);
+ ClassDB::bind_method(D_METHOD("set_remote_node", "path"), &RemoteTransform::set_remote_node);
+ ClassDB::bind_method(D_METHOD("get_remote_node"), &RemoteTransform::get_remote_node);
- ADD_PROPERTY( PropertyInfo(Variant::NODE_PATH,"remote_path"),"set_remote_node","get_remote_node");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "remote_path"), "set_remote_node", "get_remote_node");
}
RemoteTransform::RemoteTransform() {
- cache=0;
+ cache = 0;
set_notify_transform(true);
-
}
-
diff --git a/scene/3d/remote_transform.h b/scene/3d/remote_transform.h
index 6bc4763e2d..fdfd959a96 100644
--- a/scene/3d/remote_transform.h
+++ b/scene/3d/remote_transform.h
@@ -31,28 +31,27 @@
#include "scene/3d/spatial.h"
-class RemoteTransform : public Spatial
-{
- GDCLASS(RemoteTransform,Spatial);
-
+class RemoteTransform : public Spatial {
+ GDCLASS(RemoteTransform, Spatial);
+
NodePath remote_node;
ObjectID cache;
void _update_remote();
- void _update_cache();
-
+ void _update_cache();
+
protected:
static void _bind_methods();
void _notification(int p_what);
+
public:
- void set_remote_node(const NodePath& p_remote_node);
+ void set_remote_node(const NodePath &p_remote_node);
NodePath get_remote_node() const;
-
+
virtual String get_configuration_warning() const;
-
- RemoteTransform();
+ RemoteTransform();
};
#endif // REMOTETRANSFORM_H
diff --git a/scene/3d/room_instance.cpp b/scene/3d/room_instance.cpp
index b363c05ef7..3b6ae32d16 100644
--- a/scene/3d/room_instance.cpp
+++ b/scene/3d/room_instance.cpp
@@ -34,44 +34,35 @@
#include "global_config.h"
#include "scene/resources/surface_tool.h"
-
void Room::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
// go find parent level
- Node *parent_room=get_parent();
- level=0;
+ Node *parent_room = get_parent();
+ level = 0;
- while(parent_room) {
+ while (parent_room) {
Room *r = parent_room->cast_to<Room>();
if (r) {
- level=r->level+1;
+ level = r->level + 1;
break;
}
- parent_room=parent_room->get_parent();
+ parent_room = parent_room->get_parent();
}
-
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
} break;
case NOTIFICATION_EXIT_WORLD: {
-
-
- } break;
+ } break;
}
-
}
-
-
-
-
Rect3 Room::get_aabb() const {
if (room.is_null())
@@ -83,12 +74,11 @@ Rect3 Room::get_aabb() const {
PoolVector<Face3> Room::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
-
}
-void Room::set_room( const Ref<RoomBounds>& p_room ) {
+void Room::set_room(const Ref<RoomBounds> &p_room) {
- room=p_room;
+ room = p_room;
update_gizmo();
if (room.is_valid()) {
@@ -101,11 +91,8 @@ void Room::set_room( const Ref<RoomBounds>& p_room ) {
if (!is_inside_tree())
return;
-
propagate_notification(NOTIFICATION_AREA_CHANGED);
update_gizmo();
-
-
}
Ref<RoomBounds> Room::get_room() const {
@@ -113,75 +100,60 @@ Ref<RoomBounds> Room::get_room() const {
return room;
}
-void Room::_parse_node_faces(PoolVector<Face3> &all_faces,const Node *p_node) const {
+void Room::_parse_node_faces(PoolVector<Face3> &all_faces, const Node *p_node) const {
- const VisualInstance *vi=p_node->cast_to<VisualInstance>();
+ const VisualInstance *vi = p_node->cast_to<VisualInstance>();
if (vi) {
- PoolVector<Face3> faces=vi->get_faces(FACES_ENCLOSING);
+ PoolVector<Face3> faces = vi->get_faces(FACES_ENCLOSING);
if (faces.size()) {
- int old_len=all_faces.size();
- all_faces.resize( all_faces.size() + faces.size() );
- int new_len=all_faces.size();
- PoolVector<Face3>::Write all_facesw=all_faces.write();
- Face3 * all_facesptr=all_facesw.ptr();
+ int old_len = all_faces.size();
+ all_faces.resize(all_faces.size() + faces.size());
+ int new_len = all_faces.size();
+ PoolVector<Face3>::Write all_facesw = all_faces.write();
+ Face3 *all_facesptr = all_facesw.ptr();
- PoolVector<Face3>::Read facesr=faces.read();
- const Face3 * facesptr=facesr.ptr();
+ PoolVector<Face3>::Read facesr = faces.read();
+ const Face3 *facesptr = facesr.ptr();
- Transform tr=vi->get_relative_transform(this);
+ Transform tr = vi->get_relative_transform(this);
- for(int i=old_len;i<new_len;i++) {
+ for (int i = old_len; i < new_len; i++) {
- Face3 f=facesptr[i-old_len];
- for (int j=0;j<3;j++)
- f.vertex[j]=tr.xform(f.vertex[j]);
- all_facesptr[i]=f;
+ Face3 f = facesptr[i - old_len];
+ for (int j = 0; j < 3; j++)
+ f.vertex[j] = tr.xform(f.vertex[j]);
+ all_facesptr[i] = f;
}
}
}
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- for (int i=0;i<p_node->get_child_count();i++) {
-
- _parse_node_faces(all_faces,p_node->get_child(i));
+ _parse_node_faces(all_faces, p_node->get_child(i));
}
-
}
-
-
void Room::_bounds_changed() {
update_gizmo();
}
-
-
void Room::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_room","room:Room"),&Room::set_room );
- ClassDB::bind_method(D_METHOD("get_room:Room"),&Room::get_room );
-
-
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "room/room", PROPERTY_HINT_RESOURCE_TYPE, "Area" ), "set_room", "get_room") ;
+ ClassDB::bind_method(D_METHOD("set_room", "room:Room"), &Room::set_room);
+ ClassDB::bind_method(D_METHOD("get_room:Room"), &Room::get_room);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "room/room", PROPERTY_HINT_RESOURCE_TYPE, "Area"), "set_room", "get_room");
}
-
Room::Room() {
-// sound_enabled=false;
-
- level=0;
-
+ // sound_enabled=false;
+ level = 0;
}
-
Room::~Room() {
-
-
}
-
diff --git a/scene/3d/room_instance.h b/scene/3d/room_instance.h
index cbc1b12b7e..68be5eecf2 100644
--- a/scene/3d/room_instance.h
+++ b/scene/3d/room_instance.h
@@ -36,7 +36,6 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
/* RoomInstance Logic:
a) Instances that belong to the room are drawn only if the room is visible (seen through portal, or player inside)
b) Instances that don't belong to any room are considered to belong to the root room (RID empty)
@@ -44,52 +43,38 @@
*/
-
-
-
class Room : public VisualInstance {
- GDCLASS( Room, VisualInstance );
-public:
-
-
-
+ GDCLASS(Room, VisualInstance);
+public:
private:
Ref<RoomBounds> room;
-
int level;
- void _parse_node_faces(PoolVector<Face3> &all_faces,const Node *p_node) const;
-
+ void _parse_node_faces(PoolVector<Face3> &all_faces, const Node *p_node) const;
void _bounds_changed();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
public:
-
enum {
// used to notify portals that the room in which they are has changed.
- NOTIFICATION_AREA_CHANGED=60
+ NOTIFICATION_AREA_CHANGED = 60
};
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
- void set_room( const Ref<RoomBounds>& p_room );
+ void set_room(const Ref<RoomBounds> &p_room);
Ref<RoomBounds> get_room() const;
-
Room();
~Room();
-
};
-
#endif // ROOM_INSTANCE_H
diff --git a/scene/3d/scenario_fx.cpp b/scene/3d/scenario_fx.cpp
index 145242ba7c..92ee608f73 100644
--- a/scene/3d/scenario_fx.cpp
+++ b/scene/3d/scenario_fx.cpp
@@ -28,49 +28,42 @@
/*************************************************************************/
#include "scenario_fx.h"
-
-
void WorldEnvironment::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_ENTER_WORLD) {
+ if (p_what == NOTIFICATION_ENTER_WORLD) {
if (environment.is_valid()) {
if (get_world()->get_environment().is_valid()) {
WARN_PRINT("World already has an environment (Another WorldEnvironment?), overriding.");
}
get_world()->set_environment(environment);
- add_to_group("_world_environment_"+itos(get_world()->get_scenario().get_id()));
-
+ add_to_group("_world_environment_" + itos(get_world()->get_scenario().get_id()));
}
- } else if (p_what==NOTIFICATION_EXIT_WORLD) {
+ } else if (p_what == NOTIFICATION_EXIT_WORLD) {
- if (environment.is_valid() && get_world()->get_environment()==environment) {
+ if (environment.is_valid() && get_world()->get_environment() == environment) {
get_world()->set_environment(Ref<Environment>());
- remove_from_group("_world_environment_"+itos(get_world()->get_scenario().get_id()));
-
+ remove_from_group("_world_environment_" + itos(get_world()->get_scenario().get_id()));
}
}
}
-void WorldEnvironment::set_environment(const Ref<Environment>& p_environment) {
+void WorldEnvironment::set_environment(const Ref<Environment> &p_environment) {
- if (is_inside_world() && environment.is_valid() && get_world()->get_environment()==environment) {
+ if (is_inside_world() && environment.is_valid() && get_world()->get_environment() == environment) {
get_world()->set_environment(Ref<Environment>());
- remove_from_group("_world_environment_"+itos(get_world()->get_scenario().get_id()));
+ remove_from_group("_world_environment_" + itos(get_world()->get_scenario().get_id()));
//clean up
}
-
- environment=p_environment;
+ environment = p_environment;
if (is_inside_world() && environment.is_valid()) {
if (get_world()->get_environment().is_valid()) {
WARN_PRINT("World already has an environment (Another WorldEnvironment?), overriding.");
}
get_world()->set_environment(environment);
- add_to_group("_world_environment_"+itos(get_world()->get_scenario().get_id()));
-
+ add_to_group("_world_environment_" + itos(get_world()->get_scenario().get_id()));
}
update_configuration_warning();
@@ -86,29 +79,22 @@ String WorldEnvironment::get_configuration_warning() const {
if (!is_visible_in_tree() || !is_inside_tree() || !environment.is_valid())
return String();
- List<Node*> nodes;
- get_tree()->get_nodes_in_group("_world_environment_"+itos(get_world()->get_scenario().get_id()),&nodes);
+ List<Node *> nodes;
+ get_tree()->get_nodes_in_group("_world_environment_" + itos(get_world()->get_scenario().get_id()), &nodes);
- if (nodes.size()>1) {
+ if (nodes.size() > 1) {
return TTR("Only one WorldEnvironment is allowed per scene (or set of instanced scenes).");
}
return String();
}
-
void WorldEnvironment::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&WorldEnvironment::set_environment);
- ClassDB::bind_method(D_METHOD("get_environment:Environment"),&WorldEnvironment::get_environment);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment"),"set_environment","get_environment");
-
+ ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &WorldEnvironment::set_environment);
+ ClassDB::bind_method(D_METHOD("get_environment:Environment"), &WorldEnvironment::get_environment);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment"), "set_environment", "get_environment");
}
-
WorldEnvironment::WorldEnvironment() {
-
-
}
-
-
diff --git a/scene/3d/scenario_fx.h b/scene/3d/scenario_fx.h
index ef5b70039c..bbdffdc131 100644
--- a/scene/3d/scenario_fx.h
+++ b/scene/3d/scenario_fx.h
@@ -31,30 +31,27 @@
#include "scene/3d/spatial.h"
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class WorldEnvironment : public Spatial {
- GDCLASS(WorldEnvironment,Spatial );
+ GDCLASS(WorldEnvironment, Spatial);
Ref<Environment> environment;
protected:
-
void _notification(int p_what);
static void _bind_methods();
+
public:
- void set_environment(const Ref<Environment>& p_environment);
+ void set_environment(const Ref<Environment> &p_environment);
Ref<Environment> get_environment() const;
String get_configuration_warning() const;
WorldEnvironment();
-
};
#endif
diff --git a/scene/3d/skeleton.cpp b/scene/3d/skeleton.cpp
index 04e82ba914..3a5453c8ef 100644
--- a/scene/3d/skeleton.cpp
+++ b/scene/3d/skeleton.cpp
@@ -30,50 +30,48 @@
#include "message_queue.h"
-#include "scene/resources/surface_tool.h"
#include "core/global_config.h"
+#include "scene/resources/surface_tool.h"
-
-bool Skeleton::_set(const StringName& p_path, const Variant& p_value) {
+bool Skeleton::_set(const StringName &p_path, const Variant &p_value) {
String path = p_path;
if (!path.begins_with("bones/"))
return false;
- int which=path.get_slicec('/',1).to_int();
- String what=path.get_slicec('/',2);
+ int which = path.get_slicec('/', 1).to_int();
+ String what = path.get_slicec('/', 2);
-
- if (which==bones.size() && what=="name") {
+ if (which == bones.size() && what == "name") {
add_bone(p_value);
return true;
}
- ERR_FAIL_INDEX_V( which, bones.size(), false );
+ ERR_FAIL_INDEX_V(which, bones.size(), false);
- if (what=="parent")
- set_bone_parent(which, p_value );
- else if (what=="rest")
+ if (what == "parent")
+ set_bone_parent(which, p_value);
+ else if (what == "rest")
set_bone_rest(which, p_value);
- else if (what=="enabled")
+ else if (what == "enabled")
set_bone_enabled(which, p_value);
- else if (what=="pose")
+ else if (what == "pose")
set_bone_pose(which, p_value);
- else if (what=="bound_childs") {
- Array children=p_value;
+ else if (what == "bound_childs") {
+ Array children = p_value;
if (is_inside_tree()) {
bones[which].nodes_bound.clear();
- for (int i=0;i<children.size();i++) {
+ for (int i = 0; i < children.size(); i++) {
- NodePath path=children[i];
- ERR_CONTINUE( path.operator String()=="" );
+ NodePath path = children[i];
+ ERR_CONTINUE(path.operator String() == "");
Node *node = get_node(path);
ERR_CONTINUE(!node);
- bind_child_node_to_bone(which,node);
+ bind_child_node_to_bone(which, node);
}
}
} else {
@@ -83,72 +81,70 @@ bool Skeleton::_set(const StringName& p_path, const Variant& p_value) {
return true;
}
-bool Skeleton::_get(const StringName& p_name,Variant &r_ret) const {
+bool Skeleton::_get(const StringName &p_name, Variant &r_ret) const {
- String path=p_name;
+ String path = p_name;
if (!path.begins_with("bones/"))
return false;
- int which=path.get_slicec('/',1).to_int();
- String what=path.get_slicec('/',2);
-
- ERR_FAIL_INDEX_V( which, bones.size(), false );
-
- if (what=="name")
- r_ret=get_bone_name(which);
- else if (what=="parent")
- r_ret=get_bone_parent(which);
- else if (what=="rest")
- r_ret=get_bone_rest(which);
- else if (what=="enabled")
- r_ret=is_bone_enabled(which);
- else if (what=="pose")
- r_ret=get_bone_pose(which);
- else if (what=="bound_childs") {
+ int which = path.get_slicec('/', 1).to_int();
+ String what = path.get_slicec('/', 2);
+
+ ERR_FAIL_INDEX_V(which, bones.size(), false);
+
+ if (what == "name")
+ r_ret = get_bone_name(which);
+ else if (what == "parent")
+ r_ret = get_bone_parent(which);
+ else if (what == "rest")
+ r_ret = get_bone_rest(which);
+ else if (what == "enabled")
+ r_ret = is_bone_enabled(which);
+ else if (what == "pose")
+ r_ret = get_bone_pose(which);
+ else if (what == "bound_childs") {
Array children;
- for (const List<uint32_t>::Element *E=bones[which].nodes_bound.front();E;E=E->next()) {
+ for (const List<uint32_t>::Element *E = bones[which].nodes_bound.front(); E; E = E->next()) {
- Object *obj=ObjectDB::get_instance(E->get());
+ Object *obj = ObjectDB::get_instance(E->get());
ERR_CONTINUE(!obj);
- Node *node=obj->cast_to<Node>();
+ Node *node = obj->cast_to<Node>();
ERR_CONTINUE(!node);
- NodePath path=get_path_to(node);
+ NodePath path = get_path_to(node);
children.push_back(path);
-
}
- r_ret=children;
+ r_ret = children;
} else
return false;
return true;
-
}
-void Skeleton::_get_property_list( List<PropertyInfo>* p_list ) const {
+void Skeleton::_get_property_list(List<PropertyInfo> *p_list) const {
- for (int i=0;i<bones.size();i++) {
+ for (int i = 0; i < bones.size(); i++) {
- String prep="bones/"+itos(i)+"/";
- p_list->push_back( PropertyInfo( Variant::STRING, prep+"name" ) );
- p_list->push_back( PropertyInfo( Variant::INT, prep+"parent" , PROPERTY_HINT_RANGE,"-1,"+itos(i-1)+",1") );
- p_list->push_back( PropertyInfo( Variant::TRANSFORM, prep+"rest" ) );
- p_list->push_back( PropertyInfo( Variant::BOOL, prep+"enabled" ) );
- p_list->push_back( PropertyInfo( Variant::TRANSFORM, prep+"pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ) );
- p_list->push_back( PropertyInfo( Variant::ARRAY, prep+"bound_childs" ) );
+ String prep = "bones/" + itos(i) + "/";
+ p_list->push_back(PropertyInfo(Variant::STRING, prep + "name"));
+ p_list->push_back(PropertyInfo(Variant::INT, prep + "parent", PROPERTY_HINT_RANGE, "-1," + itos(i - 1) + ",1"));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "rest"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, prep + "enabled"));
+ p_list->push_back(PropertyInfo(Variant::TRANSFORM, prep + "pose", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::ARRAY, prep + "bound_childs"));
}
}
void Skeleton::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
if (dirty) {
- dirty=false;
+ dirty = false;
_make_dirty(); // property make it dirty
}
@@ -158,97 +154,95 @@ void Skeleton::_notification(int p_what) {
} break;
case NOTIFICATION_UPDATE_SKELETON: {
+ VisualServer *vs = VisualServer::get_singleton();
+ Bone *bonesptr = &bones[0];
+ int len = bones.size();
- VisualServer *vs=VisualServer::get_singleton();
- Bone *bonesptr=&bones[0];
- int len=bones.size();
-
- vs->skeleton_allocate( skeleton, len ); // if same size, nothin really happens
+ vs->skeleton_allocate(skeleton, len); // if same size, nothin really happens
// pose changed, rebuild cache of inverses
if (rest_global_inverse_dirty) {
// calculate global rests and invert them
- for (int i=0;i<len;i++) {
- Bone &b=bonesptr[i];
- if (b.parent>=0)
- b.rest_global_inverse=bonesptr[b.parent].rest_global_inverse * b.rest;
+ for (int i = 0; i < len; i++) {
+ Bone &b = bonesptr[i];
+ if (b.parent >= 0)
+ b.rest_global_inverse = bonesptr[b.parent].rest_global_inverse * b.rest;
else
- b.rest_global_inverse=b.rest;
+ b.rest_global_inverse = b.rest;
}
- for (int i=0;i<len;i++) {
- Bone &b=bonesptr[i];
+ for (int i = 0; i < len; i++) {
+ Bone &b = bonesptr[i];
b.rest_global_inverse.affine_invert();
}
- rest_global_inverse_dirty=false;
-
+ rest_global_inverse_dirty = false;
}
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- Bone &b=bonesptr[i];
+ Bone &b = bonesptr[i];
if (b.disable_rest) {
if (b.enabled) {
- Transform pose=b.pose;
+ Transform pose = b.pose;
if (b.custom_pose_enable) {
pose = b.custom_pose * pose;
}
- if (b.parent>=0) {
+ if (b.parent >= 0) {
- b.pose_global=bonesptr[b.parent].pose_global * pose;
+ b.pose_global = bonesptr[b.parent].pose_global * pose;
} else {
- b.pose_global=pose;
+ b.pose_global = pose;
}
} else {
- if (b.parent>=0) {
+ if (b.parent >= 0) {
- b.pose_global=bonesptr[b.parent].pose_global;
+ b.pose_global = bonesptr[b.parent].pose_global;
} else {
- b.pose_global=Transform();
+ b.pose_global = Transform();
}
}
} else {
if (b.enabled) {
- Transform pose=b.pose;
+ Transform pose = b.pose;
if (b.custom_pose_enable) {
pose = b.custom_pose * pose;
}
- if (b.parent>=0) {
+ if (b.parent >= 0) {
- b.pose_global=bonesptr[b.parent].pose_global * (b.rest * pose);
+ b.pose_global = bonesptr[b.parent].pose_global * (b.rest * pose);
} else {
- b.pose_global=b.rest * pose;
+ b.pose_global = b.rest * pose;
}
} else {
- if (b.parent>=0) {
+ if (b.parent >= 0) {
- b.pose_global=bonesptr[b.parent].pose_global * b.rest;
+ b.pose_global = bonesptr[b.parent].pose_global * b.rest;
} else {
- b.pose_global=b.rest;
+ b.pose_global = b.rest;
}
}
}
- vs->skeleton_bone_set_transform( skeleton, i, b.pose_global * b.rest_global_inverse );
+ vs->skeleton_bone_set_transform(skeleton, i, b.pose_global * b.rest_global_inverse);
- for(List<uint32_t>::Element *E=b.nodes_bound.front();E;E=E->next()) {
+ for (List<uint32_t>::Element *E = b.nodes_bound.front(); E; E = E->next()) {
- Object *obj=ObjectDB::get_instance(E->get());
+ Object *obj = ObjectDB::get_instance(E->get());
ERR_CONTINUE(!obj);
Spatial *sp = obj->cast_to<Spatial>();
ERR_CONTINUE(!sp);
@@ -256,38 +250,35 @@ void Skeleton::_notification(int p_what) {
}
}
- dirty=false;
+ dirty = false;
} break;
}
}
Transform Skeleton::get_bone_transform(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone,bones.size(),Transform());
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
if (dirty)
- const_cast<Skeleton*>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
+ const_cast<Skeleton *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
return bones[p_bone].pose_global * bones[p_bone].rest_global_inverse;
}
+void Skeleton::set_bone_global_pose(int p_bone, const Transform &p_pose) {
-void Skeleton::set_bone_global_pose(int p_bone,const Transform& p_pose) {
+ ERR_FAIL_INDEX(p_bone, bones.size());
+ if (bones[p_bone].parent == -1) {
- ERR_FAIL_INDEX(p_bone,bones.size());
- if (bones[p_bone].parent==-1) {
-
- set_bone_pose(p_bone,bones[p_bone].rest_global_inverse * p_pose); //fast
+ set_bone_pose(p_bone, bones[p_bone].rest_global_inverse * p_pose); //fast
} else {
set_bone_pose(p_bone, bones[p_bone].rest.affine_inverse() * (get_bone_global_pose(bones[p_bone].parent).affine_inverse() * p_pose)); //slow
-
}
-
}
Transform Skeleton::get_bone_global_pose(int p_bone) const {
- ERR_FAIL_INDEX_V(p_bone,bones.size(),Transform());
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
if (dirty)
- const_cast<Skeleton*>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
+ const_cast<Skeleton *>(this)->notification(NOTIFICATION_UPDATE_SKELETON);
return bones[p_bone].pose_global;
}
@@ -297,28 +288,28 @@ RID Skeleton::get_skeleton() const {
}
// skeleton creation api
-void Skeleton::add_bone(const String& p_name) {
+void Skeleton::add_bone(const String &p_name) {
- ERR_FAIL_COND( p_name=="" || p_name.find(":")!=-1 || p_name.find("/")!=-1 );
+ ERR_FAIL_COND(p_name == "" || p_name.find(":") != -1 || p_name.find("/") != -1);
- for (int i=0;i<bones.size();i++) {
+ for (int i = 0; i < bones.size(); i++) {
- ERR_FAIL_COND( bones[i].name=="p_name");
+ ERR_FAIL_COND(bones[i].name == "p_name");
}
Bone b;
- b.name=p_name;
+ b.name = p_name;
bones.push_back(b);
- rest_global_inverse_dirty=true;
+ rest_global_inverse_dirty = true;
_make_dirty();
update_gizmo();
}
int Skeleton::find_bone(String p_name) const {
- for (int i=0;i<bones.size();i++) {
+ for (int i = 0; i < bones.size(); i++) {
- if (bones[i].name==p_name)
+ if (bones[i].name == p_name)
return i;
}
@@ -326,7 +317,7 @@ int Skeleton::find_bone(String p_name) const {
}
String Skeleton::get_bone_name(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), "" );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), "");
return bones[p_bone].name;
}
@@ -338,248 +329,222 @@ int Skeleton::get_bone_count() const {
void Skeleton::set_bone_parent(int p_bone, int p_parent) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
- ERR_FAIL_COND( p_parent!=-1 && (p_parent<0 || p_parent>=p_bone));
+ ERR_FAIL_INDEX(p_bone, bones.size());
+ ERR_FAIL_COND(p_parent != -1 && (p_parent < 0 || p_parent >= p_bone));
- bones[p_bone].parent=p_parent;
- rest_global_inverse_dirty=true;
+ bones[p_bone].parent = p_parent;
+ rest_global_inverse_dirty = true;
_make_dirty();
}
void Skeleton::unparent_bone_and_rest(int p_bone) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- int parent=bones[p_bone].parent;
- while(parent>=0) {
+ int parent = bones[p_bone].parent;
+ while (parent >= 0) {
bones[p_bone].rest = bones[parent].rest * bones[p_bone].rest;
- parent=bones[parent].parent;
+ parent = bones[parent].parent;
}
- bones[p_bone].parent=-1;
- bones[p_bone].rest_global_inverse=bones[p_bone].rest.affine_inverse(); //same thing
+ bones[p_bone].parent = -1;
+ bones[p_bone].rest_global_inverse = bones[p_bone].rest.affine_inverse(); //same thing
_make_dirty();
-
}
void Skeleton::set_bone_disable_rest(int p_bone, bool p_disable) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
- bones[p_bone].disable_rest=p_disable;
-
+ ERR_FAIL_INDEX(p_bone, bones.size());
+ bones[p_bone].disable_rest = p_disable;
}
bool Skeleton::is_bone_rest_disabled(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), false );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
return bones[p_bone].disable_rest;
}
-
int Skeleton::get_bone_parent(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), -1 );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), -1);
return bones[p_bone].parent;
}
-void Skeleton::set_bone_rest(int p_bone, const Transform& p_rest) {
+void Skeleton::set_bone_rest(int p_bone, const Transform &p_rest) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- bones[p_bone].rest=p_rest;
- rest_global_inverse_dirty=true;
+ bones[p_bone].rest = p_rest;
+ rest_global_inverse_dirty = true;
_make_dirty();
-
}
Transform Skeleton::get_bone_rest(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
return bones[p_bone].rest;
-
}
void Skeleton::set_bone_enabled(int p_bone, bool p_enabled) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- bones[p_bone].enabled=p_enabled;
- rest_global_inverse_dirty=true;
+ bones[p_bone].enabled = p_enabled;
+ rest_global_inverse_dirty = true;
_make_dirty();
}
bool Skeleton::is_bone_enabled(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), false );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), false);
return bones[p_bone].enabled;
-
}
-void Skeleton::bind_child_node_to_bone(int p_bone,Node *p_node) {
+void Skeleton::bind_child_node_to_bone(int p_bone, Node *p_node) {
ERR_FAIL_NULL(p_node);
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- uint32_t id=p_node->get_instance_ID();
+ uint32_t id = p_node->get_instance_ID();
- for (List<uint32_t>::Element *E=bones[p_bone].nodes_bound.front();E;E=E->next()) {
+ for (List<uint32_t>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
- if (E->get()==id)
+ if (E->get() == id)
return; // already here
}
bones[p_bone].nodes_bound.push_back(id);
-
}
-void Skeleton::unbind_child_node_from_bone(int p_bone,Node *p_node) {
+void Skeleton::unbind_child_node_from_bone(int p_bone, Node *p_node) {
ERR_FAIL_NULL(p_node);
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- uint32_t id=p_node->get_instance_ID();
+ uint32_t id = p_node->get_instance_ID();
bones[p_bone].nodes_bound.erase(id);
-
}
-void Skeleton::get_bound_child_nodes_to_bone(int p_bone,List<Node*> *p_bound) const {
+void Skeleton::get_bound_child_nodes_to_bone(int p_bone, List<Node *> *p_bound) const {
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
- for (const List<uint32_t>::Element *E=bones[p_bone].nodes_bound.front();E;E=E->next()) {
+ for (const List<uint32_t>::Element *E = bones[p_bone].nodes_bound.front(); E; E = E->next()) {
- Object *obj=ObjectDB::get_instance(E->get());
+ Object *obj = ObjectDB::get_instance(E->get());
ERR_CONTINUE(!obj);
p_bound->push_back(obj->cast_to<Node>());
}
-
}
void Skeleton::clear_bones() {
bones.clear();
- rest_global_inverse_dirty=true;
+ rest_global_inverse_dirty = true;
_make_dirty();
}
// posing api
-void Skeleton::set_bone_pose(int p_bone, const Transform& p_pose) {
-
- ERR_FAIL_INDEX( p_bone, bones.size() );
- ERR_FAIL_COND( !is_inside_tree() );
+void Skeleton::set_bone_pose(int p_bone, const Transform &p_pose) {
+ ERR_FAIL_INDEX(p_bone, bones.size());
+ ERR_FAIL_COND(!is_inside_tree());
- bones[p_bone].pose=p_pose;
+ bones[p_bone].pose = p_pose;
_make_dirty();
}
Transform Skeleton::get_bone_pose(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
return bones[p_bone].pose;
-
}
-void Skeleton::set_bone_custom_pose(int p_bone, const Transform& p_custom_pose) {
+void Skeleton::set_bone_custom_pose(int p_bone, const Transform &p_custom_pose) {
- ERR_FAIL_INDEX( p_bone, bones.size() );
+ ERR_FAIL_INDEX(p_bone, bones.size());
//ERR_FAIL_COND( !is_inside_scene() );
-
- bones[p_bone].custom_pose_enable=(p_custom_pose!=Transform());
- bones[p_bone].custom_pose=p_custom_pose;
+ bones[p_bone].custom_pose_enable = (p_custom_pose != Transform());
+ bones[p_bone].custom_pose = p_custom_pose;
_make_dirty();
}
Transform Skeleton::get_bone_custom_pose(int p_bone) const {
- ERR_FAIL_INDEX_V( p_bone, bones.size(), Transform() );
+ ERR_FAIL_INDEX_V(p_bone, bones.size(), Transform());
return bones[p_bone].custom_pose;
-
}
-
void Skeleton::_make_dirty() {
if (dirty)
return;
if (!is_inside_tree()) {
- dirty=true;
+ dirty = true;
return;
}
- MessageQueue::get_singleton()->push_notification( this, NOTIFICATION_UPDATE_SKELETON );
- dirty=true;
+ MessageQueue::get_singleton()->push_notification(this, NOTIFICATION_UPDATE_SKELETON);
+ dirty = true;
}
-
-
void Skeleton::localize_rests() {
- for(int i=bones.size()-1;i>=0;i--) {
+ for (int i = bones.size() - 1; i >= 0; i--) {
- if (bones[i].parent>=0)
- set_bone_rest(i,bones[bones[i].parent].rest.affine_inverse() * bones[i].rest);
+ if (bones[i].parent >= 0)
+ set_bone_rest(i, bones[bones[i].parent].rest.affine_inverse() * bones[i].rest);
}
}
-
-
void Skeleton::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("add_bone", "name"), &Skeleton::add_bone);
+ ClassDB::bind_method(D_METHOD("find_bone", "name"), &Skeleton::find_bone);
+ ClassDB::bind_method(D_METHOD("get_bone_name", "bone_idx"), &Skeleton::get_bone_name);
+ ClassDB::bind_method(D_METHOD("get_bone_parent", "bone_idx"), &Skeleton::get_bone_parent);
+ ClassDB::bind_method(D_METHOD("set_bone_parent", "bone_idx", "parent_idx"), &Skeleton::set_bone_parent);
+ ClassDB::bind_method(D_METHOD("get_bone_count"), &Skeleton::get_bone_count);
- ClassDB::bind_method(D_METHOD("add_bone","name"),&Skeleton::add_bone);
- ClassDB::bind_method(D_METHOD("find_bone","name"),&Skeleton::find_bone);
- ClassDB::bind_method(D_METHOD("get_bone_name","bone_idx"),&Skeleton::get_bone_name);
-
- ClassDB::bind_method(D_METHOD("get_bone_parent","bone_idx"),&Skeleton::get_bone_parent);
- ClassDB::bind_method(D_METHOD("set_bone_parent","bone_idx","parent_idx"),&Skeleton::set_bone_parent);
-
- ClassDB::bind_method(D_METHOD("get_bone_count"),&Skeleton::get_bone_count);
+ ClassDB::bind_method(D_METHOD("unparent_bone_and_rest", "bone_idx"), &Skeleton::unparent_bone_and_rest);
- ClassDB::bind_method(D_METHOD("unparent_bone_and_rest","bone_idx"),&Skeleton::unparent_bone_and_rest);
+ ClassDB::bind_method(D_METHOD("get_bone_rest", "bone_idx"), &Skeleton::get_bone_rest);
+ ClassDB::bind_method(D_METHOD("set_bone_rest", "bone_idx", "rest"), &Skeleton::set_bone_rest);
- ClassDB::bind_method(D_METHOD("get_bone_rest","bone_idx"),&Skeleton::get_bone_rest);
- ClassDB::bind_method(D_METHOD("set_bone_rest","bone_idx","rest"),&Skeleton::set_bone_rest);
+ ClassDB::bind_method(D_METHOD("set_bone_disable_rest", "bone_idx", "disable"), &Skeleton::set_bone_disable_rest);
+ ClassDB::bind_method(D_METHOD("is_bone_rest_disabled", "bone_idx"), &Skeleton::is_bone_rest_disabled);
- ClassDB::bind_method(D_METHOD("set_bone_disable_rest","bone_idx","disable"),&Skeleton::set_bone_disable_rest);
- ClassDB::bind_method(D_METHOD("is_bone_rest_disabled","bone_idx"),&Skeleton::is_bone_rest_disabled);
+ ClassDB::bind_method(D_METHOD("bind_child_node_to_bone", "bone_idx", "node:Node"), &Skeleton::bind_child_node_to_bone);
+ ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone", "bone_idx", "node:Node"), &Skeleton::unbind_child_node_from_bone);
+ ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone", "bone_idx"), &Skeleton::_get_bound_child_nodes_to_bone);
- ClassDB::bind_method(D_METHOD("bind_child_node_to_bone","bone_idx","node:Node"),&Skeleton::bind_child_node_to_bone);
- ClassDB::bind_method(D_METHOD("unbind_child_node_from_bone","bone_idx","node:Node"),&Skeleton::unbind_child_node_from_bone);
- ClassDB::bind_method(D_METHOD("get_bound_child_nodes_to_bone","bone_idx"),&Skeleton::_get_bound_child_nodes_to_bone);
+ ClassDB::bind_method(D_METHOD("clear_bones"), &Skeleton::clear_bones);
- ClassDB::bind_method(D_METHOD("clear_bones"),&Skeleton::clear_bones);
+ ClassDB::bind_method(D_METHOD("get_bone_pose", "bone_idx"), &Skeleton::get_bone_pose);
+ ClassDB::bind_method(D_METHOD("set_bone_pose", "bone_idx", "pose"), &Skeleton::set_bone_pose);
- ClassDB::bind_method(D_METHOD("get_bone_pose","bone_idx"),&Skeleton::get_bone_pose);
- ClassDB::bind_method(D_METHOD("set_bone_pose","bone_idx","pose"),&Skeleton::set_bone_pose);
+ ClassDB::bind_method(D_METHOD("set_bone_global_pose", "bone_idx", "pose"), &Skeleton::set_bone_global_pose);
+ ClassDB::bind_method(D_METHOD("get_bone_global_pose", "bone_idx"), &Skeleton::get_bone_global_pose);
- ClassDB::bind_method(D_METHOD("set_bone_global_pose","bone_idx","pose"),&Skeleton::set_bone_global_pose);
- ClassDB::bind_method(D_METHOD("get_bone_global_pose","bone_idx"),&Skeleton::get_bone_global_pose);
+ ClassDB::bind_method(D_METHOD("get_bone_custom_pose", "bone_idx"), &Skeleton::get_bone_custom_pose);
+ ClassDB::bind_method(D_METHOD("set_bone_custom_pose", "bone_idx", "custom_pose"), &Skeleton::set_bone_custom_pose);
- ClassDB::bind_method(D_METHOD("get_bone_custom_pose","bone_idx"),&Skeleton::get_bone_custom_pose);
- ClassDB::bind_method(D_METHOD("set_bone_custom_pose","bone_idx","custom_pose"),&Skeleton::set_bone_custom_pose);
+ ClassDB::bind_method(D_METHOD("get_bone_transform", "bone_idx"), &Skeleton::get_bone_transform);
- ClassDB::bind_method(D_METHOD("get_bone_transform","bone_idx"),&Skeleton::get_bone_transform);
-
- BIND_CONSTANT( NOTIFICATION_UPDATE_SKELETON );
+ BIND_CONSTANT(NOTIFICATION_UPDATE_SKELETON);
}
-
-
Skeleton::Skeleton() {
- rest_global_inverse_dirty=true;
- dirty=false;
- skeleton=VisualServer::get_singleton()->skeleton_create();
+ rest_global_inverse_dirty = true;
+ dirty = false;
+ skeleton = VisualServer::get_singleton()->skeleton_create();
}
-
Skeleton::~Skeleton() {
- VisualServer::get_singleton()->free( skeleton );
+ VisualServer::get_singleton()->free(skeleton);
}
-
-
diff --git a/scene/3d/skeleton.h b/scene/3d/skeleton.h
index 04eb3e9009..7074289724 100644
--- a/scene/3d/skeleton.h
+++ b/scene/3d/skeleton.h
@@ -29,15 +29,15 @@
#ifndef SKELETON_H
#define SKELETON_H
-#include "scene/3d/spatial.h"
#include "rid.h"
+#include "scene/3d/spatial.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class Skeleton : public Spatial {
- GDCLASS( Skeleton, Spatial );
+ GDCLASS(Skeleton, Spatial);
struct Bone {
@@ -58,7 +58,12 @@ class Skeleton : public Spatial {
List<uint32_t> nodes_bound;
- Bone() { parent=-1; enabled=true; custom_pose_enable=false; disable_rest=false; }
+ Bone() {
+ parent = -1;
+ enabled = true;
+ custom_pose_enable = false;
+ disable_rest = false;
+ }
};
bool rest_global_inverse_dirty;
@@ -70,41 +75,37 @@ class Skeleton : public Spatial {
void _make_dirty();
bool dirty;
-//bind helpers
+ //bind helpers
Array _get_bound_child_nodes_to_bone(int p_bone) const {
Array bound;
- List<Node*> childs;
- get_bound_child_nodes_to_bone(p_bone,&childs);
+ List<Node *> childs;
+ get_bound_child_nodes_to_bone(p_bone, &childs);
- for (int i=0;i<childs.size();i++) {
+ for (int i = 0; i < childs.size(); i++) {
- bound.push_back( childs[i] );
+ bound.push_back(childs[i]);
}
return bound;
}
-
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_list ) const;
+ 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_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
enum {
- NOTIFICATION_UPDATE_SKELETON=50
+ NOTIFICATION_UPDATE_SKELETON = 50
};
-
RID get_skeleton() const;
// skeleton creation api
- void add_bone(const String&p_name);
+ void add_bone(const String &p_name);
int find_bone(String p_name) const;
String get_bone_name(int p_bone) const;
@@ -118,35 +119,34 @@ public:
int get_bone_count() const;
- void set_bone_rest(int p_bone, const Transform& p_rest);
+ void set_bone_rest(int p_bone, const Transform &p_rest);
Transform get_bone_rest(int p_bone) const;
Transform get_bone_transform(int p_bone) const;
Transform get_bone_global_pose(int p_bone) const;
- void set_bone_global_pose(int p_bone,const Transform& p_pose);
+ void set_bone_global_pose(int p_bone, const Transform &p_pose);
void set_bone_enabled(int p_bone, bool p_enabled);
bool is_bone_enabled(int p_bone) const;
- void bind_child_node_to_bone(int p_bone,Node *p_node);
- void unbind_child_node_from_bone(int p_bone,Node *p_node);
- void get_bound_child_nodes_to_bone(int p_bone,List<Node*> *p_bound) const;
+ void bind_child_node_to_bone(int p_bone, Node *p_node);
+ void unbind_child_node_from_bone(int p_bone, Node *p_node);
+ void get_bound_child_nodes_to_bone(int p_bone, List<Node *> *p_bound) const;
void clear_bones();
// posing api
- void set_bone_pose(int p_bone, const Transform& p_pose);
+ void set_bone_pose(int p_bone, const Transform &p_pose);
Transform get_bone_pose(int p_bone) const;
- void set_bone_custom_pose(int p_bone, const Transform& p_custom_pose);
+ void set_bone_custom_pose(int p_bone, const Transform &p_custom_pose);
Transform get_bone_custom_pose(int p_bone) const;
void localize_rests(); // used for loaders and tools
Skeleton();
~Skeleton();
-
};
#endif
diff --git a/scene/3d/spatial.cpp b/scene/3d/spatial.cpp
index 58a6a24567..1125a7a4d2 100644
--- a/scene/3d/spatial.cpp
+++ b/scene/3d/spatial.cpp
@@ -28,8 +28,8 @@
/*************************************************************************/
#include "spatial.h"
-#include "scene/main/viewport.h"
#include "message_queue.h"
+#include "scene/main/viewport.h"
#include "scene/scene_string_names.h"
/*
@@ -66,10 +66,7 @@ future: no idea
*/
-
-
SpatialGizmo::SpatialGizmo() {
-
}
void Spatial::_notify_dirty() {
@@ -80,14 +77,12 @@ void Spatial::_notify_dirty() {
}
}
-
-
void Spatial::_update_local_transform() const {
data.local_transform.basis = Basis();
data.local_transform.basis.scale(data.scale);
data.local_transform.basis.rotate(data.rotation);
- data.dirty&=~DIRTY_LOCAL;
+ data.dirty &= ~DIRTY_LOCAL;
}
void Spatial::_propagate_transform_changed(Spatial *p_origin) {
@@ -102,48 +97,46 @@ void Spatial::_propagate_transform_changed(Spatial *p_origin) {
data.children_lock++;
- for (List<Spatial*>::Element *E=data.children.front();E;E=E->next()) {
+ for (List<Spatial *>::Element *E = data.children.front(); E; E = E->next()) {
if (E->get()->data.toplevel_active)
continue; //don't propagate to a toplevel
E->get()->_propagate_transform_changed(p_origin);
}
-
if (data.notify_transform && !data.ignore_notification && !xform_change.in_list()) {
get_tree()->xform_change_list.add(&xform_change);
-
}
- data.dirty|=DIRTY_GLOBAL;
+ data.dirty |= DIRTY_GLOBAL;
data.children_lock--;
}
void Spatial::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
Node *p = get_parent();
if (p)
- data.parent=p->cast_to<Spatial>();
+ data.parent = p->cast_to<Spatial>();
if (data.parent)
- data.C=data.parent->data.children.push_back(this);
+ data.C = data.parent->data.children.push_back(this);
else
- data.C=NULL;
+ data.C = NULL;
if (data.toplevel && !get_tree()->is_editor_hint()) {
if (data.parent) {
data.local_transform = data.parent->get_global_transform() * get_transform();
- data.dirty=DIRTY_VECTORS; //global is always dirty upon entering a scene
+ data.dirty = DIRTY_VECTORS; //global is always dirty upon entering a scene
}
- data.toplevel_active=true;
+ data.toplevel_active = true;
}
- data.dirty|=DIRTY_GLOBAL; //global is always dirty upon entering a scene
+ data.dirty |= DIRTY_GLOBAL; //global is always dirty upon entering a scene
_notify_dirty();
notification(NOTIFICATION_ENTER_WORLD);
@@ -151,38 +144,37 @@ void Spatial::_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_TREE: {
- notification(NOTIFICATION_EXIT_WORLD,true);
+ notification(NOTIFICATION_EXIT_WORLD, true);
if (xform_change.in_list())
get_tree()->xform_change_list.remove(&xform_change);
if (data.C)
data.parent->data.children.erase(data.C);
- data.parent=NULL;
- data.C=NULL;
- data.toplevel_active=false;
+ data.parent = NULL;
+ data.C = NULL;
+ data.toplevel_active = false;
} break;
case NOTIFICATION_ENTER_WORLD: {
- data.inside_world=true;
- data.viewport=NULL;
+ data.inside_world = true;
+ data.viewport = NULL;
Node *parent = get_parent();
- while(parent && !data.viewport) {
- data.viewport=parent->cast_to<Viewport>();
- parent=parent->get_parent();
+ while (parent && !data.viewport) {
+ data.viewport = parent->cast_to<Viewport>();
+ parent = parent->get_parent();
}
ERR_FAIL_COND(!data.viewport);
-
if (get_script_instance()) {
Variant::CallError err;
- get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_enter_world,NULL,0);
+ get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_enter_world, NULL, 0);
}
#ifdef TOOLS_ENABLED
if (get_tree()->is_editor_hint()) {
//get_scene()->call_group(SceneMainLoop::GROUP_CALL_REALTIME,SceneStringNames::get_singleton()->_spatial_editor_group,SceneStringNames::get_singleton()->_request_gizmo,this);
- get_tree()->call_group_flags(0,SceneStringNames::get_singleton()->_spatial_editor_group,SceneStringNames::get_singleton()->_request_gizmo,this);
+ get_tree()->call_group_flags(0, SceneStringNames::get_singleton()->_spatial_editor_group, SceneStringNames::get_singleton()->_request_gizmo, this);
if (!data.gizmo_disabled) {
if (data.gizmo.is_valid())
@@ -203,15 +195,14 @@ void Spatial::_notification(int p_what) {
if (get_script_instance()) {
Variant::CallError err;
- get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_world,NULL,0);
+ get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_world, NULL, 0);
}
- data.viewport=NULL;
- data.inside_world=false;
+ data.viewport = NULL;
+ data.inside_world = false;
} break;
-
case NOTIFICATION_TRANSFORM_CHANGED: {
#ifdef TOOLS_ENABLED
@@ -225,10 +216,10 @@ void Spatial::_notification(int p_what) {
}
}
-void Spatial::set_transform(const Transform& p_transform) {
+void Spatial::set_transform(const Transform &p_transform) {
- data.local_transform=p_transform;
- data.dirty|=DIRTY_VECTORS;
+ data.local_transform = p_transform;
+ data.dirty |= DIRTY_VECTORS;
_change_notify("transform/translation");
_change_notify("transform/rotation");
_change_notify("transform/scale");
@@ -236,23 +227,18 @@ void Spatial::set_transform(const Transform& p_transform) {
if (data.notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
-
-
-
}
-void Spatial::set_global_transform(const Transform& p_transform) {
+void Spatial::set_global_transform(const Transform &p_transform) {
Transform xform =
(data.parent && !data.toplevel_active) ?
- data.parent->get_global_transform().affine_inverse() * p_transform :
- p_transform;
+ data.parent->get_global_transform().affine_inverse() * p_transform :
+ p_transform;
set_transform(xform);
-
}
-
Transform Spatial::get_transform() const {
if (data.dirty & DIRTY_LOCAL) {
@@ -275,13 +261,13 @@ Transform Spatial::get_global_transform() const {
if (data.parent && !data.toplevel_active) {
- data.global_transform=data.parent->get_global_transform() * data.local_transform;
+ data.global_transform = data.parent->get_global_transform() * data.local_transform;
} else {
- data.global_transform=data.local_transform;
+ data.global_transform = data.local_transform;
}
- data.dirty&=~DIRTY_GLOBAL;
+ data.dirty &= ~DIRTY_GLOBAL;
}
return data.global_transform;
@@ -321,88 +307,83 @@ void Spatial::remove_child_notify(Node *p_child) {
Spatial *Spatial::get_parent_spatial() const {
return data.parent;
-
}
Transform Spatial::get_relative_transform(const Node *p_parent) const {
- if (p_parent==this)
+ if (p_parent == this)
return Transform();
- ERR_FAIL_COND_V(!data.parent,Transform());
+ ERR_FAIL_COND_V(!data.parent, Transform());
- if (p_parent==data.parent)
+ if (p_parent == data.parent)
return get_transform();
else
return data.parent->get_relative_transform(p_parent) * get_transform();
-
}
-void Spatial::set_translation(const Vector3& p_translation) {
+void Spatial::set_translation(const Vector3 &p_translation) {
- data.local_transform.origin=p_translation;
+ data.local_transform.origin = p_translation;
_propagate_transform_changed(this);
if (data.notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
-
}
-void Spatial::set_rotation(const Vector3& p_euler_rad){
+void Spatial::set_rotation(const Vector3 &p_euler_rad) {
- if (data.dirty&DIRTY_VECTORS) {
- data.scale=data.local_transform.basis.get_scale();
- data.dirty&=~DIRTY_VECTORS;
+ if (data.dirty & DIRTY_VECTORS) {
+ data.scale = data.local_transform.basis.get_scale();
+ data.dirty &= ~DIRTY_VECTORS;
}
- data.rotation=p_euler_rad;
- data.dirty|=DIRTY_LOCAL;
+ data.rotation = p_euler_rad;
+ data.dirty |= DIRTY_LOCAL;
_propagate_transform_changed(this);
if (data.notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
-
}
-void Spatial::set_rotation_in_degrees(const Vector3& p_euler_deg) {
+void Spatial::set_rotation_in_degrees(const Vector3 &p_euler_deg) {
set_rotation(p_euler_deg * Math_PI / 180.0);
}
-void Spatial::_set_rotation_deg(const Vector3& p_euler_deg) {
+void Spatial::_set_rotation_deg(const Vector3 &p_euler_deg) {
WARN_PRINT("Deprecated method Spatial._set_rotation_deg(): This method was renamed to set_rotation_deg. Please adapt your code accordingly, as the old method will be obsoleted.");
set_rotation_in_degrees(p_euler_deg);
}
-void Spatial::set_scale(const Vector3& p_scale){
+void Spatial::set_scale(const Vector3 &p_scale) {
- if (data.dirty&DIRTY_VECTORS) {
- data.rotation=data.local_transform.basis.get_rotation();
- data.dirty&=~DIRTY_VECTORS;
+ if (data.dirty & DIRTY_VECTORS) {
+ data.rotation = data.local_transform.basis.get_rotation();
+ data.dirty &= ~DIRTY_VECTORS;
}
- data.scale=p_scale;
- data.dirty|=DIRTY_LOCAL;
+ data.scale = p_scale;
+ data.dirty |= DIRTY_LOCAL;
_propagate_transform_changed(this);
if (data.notify_local_transform) {
notification(NOTIFICATION_LOCAL_TRANSFORM_CHANGED);
}
-
}
-Vector3 Spatial::get_translation() const{
+Vector3 Spatial::get_translation() const {
return data.local_transform.origin;
}
-Vector3 Spatial::get_rotation() const{
+Vector3 Spatial::get_rotation() const {
- if (data.dirty&DIRTY_VECTORS) {
- data.scale=data.local_transform.basis.get_scale();
- data.rotation=data.local_transform.basis.get_rotation();
+ if (data.dirty & DIRTY_VECTORS) {
+ data.scale = data.local_transform.basis.get_scale();
+ data.rotation = data.local_transform.basis.get_rotation();
- data.dirty&=~DIRTY_VECTORS;
+ data.dirty &= ~DIRTY_VECTORS;
}
return data.rotation;
@@ -421,19 +402,18 @@ Vector3 Spatial::_get_rotation_deg() const {
return get_rotation_in_degrees();
}
-Vector3 Spatial::get_scale() const{
+Vector3 Spatial::get_scale() const {
- if (data.dirty&DIRTY_VECTORS) {
- data.scale=data.local_transform.basis.get_scale();
- data.rotation=data.local_transform.basis.get_rotation();
+ if (data.dirty & DIRTY_VECTORS) {
+ data.scale = data.local_transform.basis.get_scale();
+ data.rotation = data.local_transform.basis.get_rotation();
- data.dirty&=~DIRTY_VECTORS;
+ data.dirty &= ~DIRTY_VECTORS;
}
return data.scale;
}
-
void Spatial::update_gizmo() {
#ifdef TOOLS_ENABLED
@@ -443,12 +423,12 @@ void Spatial::update_gizmo() {
return;
if (data.gizmo_dirty)
return;
- data.gizmo_dirty=true;
- MessageQueue::get_singleton()->push_call(this,"_update_gizmo");
+ data.gizmo_dirty = true;
+ MessageQueue::get_singleton()->push_call(this, "_update_gizmo");
#endif
}
-void Spatial::set_gizmo(const Ref<SpatialGizmo>& p_gizmo) {
+void Spatial::set_gizmo(const Ref<SpatialGizmo> &p_gizmo) {
#ifdef TOOLS_ENABLED
@@ -456,7 +436,7 @@ void Spatial::set_gizmo(const Ref<SpatialGizmo>& p_gizmo) {
return;
if (data.gizmo.is_valid() && is_inside_world())
data.gizmo->free();
- data.gizmo=p_gizmo;
+ data.gizmo = p_gizmo;
if (data.gizmo.is_valid() && is_inside_world()) {
data.gizmo->create();
@@ -482,7 +462,7 @@ Ref<SpatialGizmo> Spatial::get_gizmo() const {
void Spatial::_update_gizmo() {
- data.gizmo_dirty=false;
+ data.gizmo_dirty = false;
if (data.gizmo.is_valid()) {
if (is_visible_in_tree())
data.gizmo->redraw();
@@ -491,19 +471,18 @@ void Spatial::_update_gizmo() {
}
}
-
void Spatial::set_disable_gizmo(bool p_enabled) {
- data.gizmo_disabled=p_enabled;
+ data.gizmo_disabled = p_enabled;
if (!p_enabled && data.gizmo.is_valid())
- data.gizmo=Ref<SpatialGizmo>();
+ data.gizmo = Ref<SpatialGizmo>();
}
#endif
void Spatial::set_as_toplevel(bool p_enabled) {
- if (data.toplevel==p_enabled)
+ if (data.toplevel == p_enabled)
return;
if (is_inside_tree() && !get_tree()->is_editor_hint()) {
@@ -512,30 +491,28 @@ void Spatial::set_as_toplevel(bool p_enabled) {
else if (data.parent)
set_transform(data.parent->get_global_transform().affine_inverse() * get_global_transform());
- data.toplevel=p_enabled;
- data.toplevel_active=p_enabled;
+ data.toplevel = p_enabled;
+ data.toplevel_active = p_enabled;
} else {
- data.toplevel=p_enabled;
+ data.toplevel = p_enabled;
}
-
}
-bool Spatial::is_set_as_toplevel() const{
+bool Spatial::is_set_as_toplevel() const {
return data.toplevel;
}
Ref<World> Spatial::get_world() const {
- ERR_FAIL_COND_V(!is_inside_world(),Ref<World>());
+ ERR_FAIL_COND_V(!is_inside_world(), Ref<World>());
return data.viewport->find_world();
-
}
#ifdef TOOLS_ENABLED
-void Spatial::set_import_transform(const Transform& p_transform) {
- data.import_transform=p_transform;
+void Spatial::set_import_transform(const Transform &p_transform) {
+ data.import_transform = p_transform;
}
Transform Spatial::get_import_transform() const {
@@ -544,7 +521,6 @@ Transform Spatial::get_import_transform() const {
}
#endif
-
void Spatial::_propagate_visibility_changed() {
notification(NOTIFICATION_VISIBILITY_CHANGED);
@@ -555,22 +531,21 @@ void Spatial::_propagate_visibility_changed() {
_update_gizmo();
#endif
- for (List<Spatial*>::Element*E=data.children.front();E;E=E->next()) {
+ for (List<Spatial *>::Element *E = data.children.front(); E; E = E->next()) {
- Spatial *c=E->get();
+ Spatial *c = E->get();
if (!c || !c->data.visible)
continue;
c->_propagate_visibility_changed();
}
}
-
void Spatial::show() {
if (data.visible)
return;
- data.visible=true;
+ data.visible = true;
if (!is_inside_tree())
return;
@@ -581,35 +556,33 @@ void Spatial::show() {
}
}
-void Spatial::hide(){
+void Spatial::hide() {
if (!data.visible)
return;
bool was_visible = is_visible_in_tree();
- data.visible=false;
+ data.visible = false;
if (!data.parent || was_visible) {
_propagate_visibility_changed();
}
-
}
-bool Spatial::is_visible_in_tree() const{
+bool Spatial::is_visible_in_tree() const {
- const Spatial *s=this;
+ const Spatial *s = this;
- while(s) {
+ while (s) {
if (!s->data.visible) {
return false;
}
- s=s->data.parent;
+ s = s->data.parent;
}
return true;
}
-
void Spatial::set_visible(bool p_visible) {
if (p_visible)
@@ -623,64 +596,57 @@ bool Spatial::is_visible() const {
return data.visible;
}
-void Spatial::rotate(const Vector3& p_normal,float p_radians) {
+void Spatial::rotate(const Vector3 &p_normal, float p_radians) {
- Transform t =get_transform();
- t.basis.rotate(p_normal,p_radians);
+ Transform t = get_transform();
+ t.basis.rotate(p_normal, p_radians);
set_transform(t);
}
void Spatial::rotate_x(float p_radians) {
- Transform t =get_transform();
- t.basis.rotate(Vector3(1,0,0),p_radians);
+ Transform t = get_transform();
+ t.basis.rotate(Vector3(1, 0, 0), p_radians);
set_transform(t);
-
}
-void Spatial::rotate_y(float p_radians){
+void Spatial::rotate_y(float p_radians) {
- Transform t =get_transform();
- t.basis.rotate(Vector3(0,1,0),p_radians);
+ Transform t = get_transform();
+ t.basis.rotate(Vector3(0, 1, 0), p_radians);
set_transform(t);
-
}
-void Spatial::rotate_z(float p_radians){
+void Spatial::rotate_z(float p_radians) {
- Transform t =get_transform();
- t.basis.rotate(Vector3(0,0,1),p_radians);
+ Transform t = get_transform();
+ t.basis.rotate(Vector3(0, 0, 1), p_radians);
set_transform(t);
-
}
-void Spatial::translate(const Vector3& p_offset){
+void Spatial::translate(const Vector3 &p_offset) {
- Transform t =get_transform();
+ Transform t = get_transform();
t.translate(p_offset);
set_transform(t);
-
}
-void Spatial::scale(const Vector3& p_ratio){
+void Spatial::scale(const Vector3 &p_ratio) {
- Transform t =get_transform();
+ Transform t = get_transform();
t.basis.scale(p_ratio);
set_transform(t);
-
}
-void Spatial::global_rotate(const Vector3& p_normal,float p_radians){
+void Spatial::global_rotate(const Vector3 &p_normal, float p_radians) {
- Basis rotation(p_normal,p_radians);
+ Basis rotation(p_normal, p_radians);
Transform t = get_global_transform();
- t.basis= rotation * t.basis;
+ t.basis = rotation * t.basis;
set_global_transform(t);
-
}
-void Spatial::global_translate(const Vector3& p_offset){
+void Spatial::global_translate(const Vector3 &p_offset) {
Transform t = get_global_transform();
- t.origin+=p_offset;
+ t.origin += p_offset;
set_global_transform(t);
-
}
void Spatial::orthonormalize() {
@@ -688,44 +654,40 @@ void Spatial::orthonormalize() {
Transform t = get_transform();
t.orthonormalize();
set_transform(t);
-
}
void Spatial::set_identity() {
set_transform(Transform());
-
}
-
-void Spatial::look_at(const Vector3& p_target, const Vector3& p_up_normal) {
+void Spatial::look_at(const Vector3 &p_target, const Vector3 &p_up_normal) {
Transform lookat;
- lookat.origin=get_global_transform().origin;
- if (lookat.origin==p_target) {
+ lookat.origin = get_global_transform().origin;
+ if (lookat.origin == p_target) {
ERR_EXPLAIN("Node origin and target are in the same position, look_at() failed");
ERR_FAIL();
}
- if (p_up_normal.cross(p_target-lookat.origin)==Vector3()) {
+ if (p_up_normal.cross(p_target - lookat.origin) == Vector3()) {
ERR_EXPLAIN("Up vector and direction between node origin and target are aligned, look_at() failed");
ERR_FAIL();
}
- lookat=lookat.looking_at(p_target,p_up_normal);
+ lookat = lookat.looking_at(p_target, p_up_normal);
set_global_transform(lookat);
}
-void Spatial::look_at_from_pos(const Vector3& p_pos,const Vector3& p_target, const Vector3& p_up_normal) {
+void Spatial::look_at_from_pos(const Vector3 &p_pos, const Vector3 &p_target, const Vector3 &p_up_normal) {
Transform lookat;
- lookat.origin=p_pos;
- lookat=lookat.looking_at(p_target,p_up_normal);
+ lookat.origin = p_pos;
+ lookat = lookat.looking_at(p_target, p_up_normal);
set_global_transform(lookat);
-
}
void Spatial::set_notify_transform(bool p_enable) {
- data.notify_transform=p_enable;
+ data.notify_transform = p_enable;
}
bool Spatial::is_transform_notification_enabled() const {
@@ -733,7 +695,7 @@ bool Spatial::is_transform_notification_enabled() const {
}
void Spatial::set_notify_local_transform(bool p_enable) {
- data.notify_local_transform=p_enable;
+ data.notify_local_transform = p_enable;
}
bool Spatial::is_local_transform_notification_enabled() const {
@@ -742,37 +704,37 @@ bool Spatial::is_local_transform_notification_enabled() const {
void Spatial::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_transform","local"), &Spatial::set_transform);
+ ClassDB::bind_method(D_METHOD("set_transform", "local"), &Spatial::set_transform);
ClassDB::bind_method(D_METHOD("get_transform"), &Spatial::get_transform);
- ClassDB::bind_method(D_METHOD("set_translation","translation"), &Spatial::set_translation);
+ ClassDB::bind_method(D_METHOD("set_translation", "translation"), &Spatial::set_translation);
ClassDB::bind_method(D_METHOD("get_translation"), &Spatial::get_translation);
- ClassDB::bind_method(D_METHOD("set_rotation","rotation_rad"), &Spatial::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation", "rotation_rad"), &Spatial::set_rotation);
ClassDB::bind_method(D_METHOD("get_rotation"), &Spatial::get_rotation);
- ClassDB::bind_method(D_METHOD("set_rotation_deg","rotation_deg"), &Spatial::set_rotation_in_degrees);
+ ClassDB::bind_method(D_METHOD("set_rotation_deg", "rotation_deg"), &Spatial::set_rotation_in_degrees);
ClassDB::bind_method(D_METHOD("get_rotation_deg"), &Spatial::get_rotation_in_degrees);
- ClassDB::bind_method(D_METHOD("set_scale","scale"), &Spatial::set_scale);
+ ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Spatial::set_scale);
ClassDB::bind_method(D_METHOD("get_scale"), &Spatial::get_scale);
- ClassDB::bind_method(D_METHOD("set_global_transform","global"), &Spatial::set_global_transform);
+ ClassDB::bind_method(D_METHOD("set_global_transform", "global"), &Spatial::set_global_transform);
ClassDB::bind_method(D_METHOD("get_global_transform"), &Spatial::get_global_transform);
ClassDB::bind_method(D_METHOD("get_parent_spatial"), &Spatial::get_parent_spatial);
- ClassDB::bind_method(D_METHOD("set_ignore_transform_notification","enabled"), &Spatial::set_ignore_transform_notification);
- ClassDB::bind_method(D_METHOD("set_as_toplevel","enable"), &Spatial::set_as_toplevel);
+ ClassDB::bind_method(D_METHOD("set_ignore_transform_notification", "enabled"), &Spatial::set_ignore_transform_notification);
+ ClassDB::bind_method(D_METHOD("set_as_toplevel", "enable"), &Spatial::set_as_toplevel);
ClassDB::bind_method(D_METHOD("is_set_as_toplevel"), &Spatial::is_set_as_toplevel);
ClassDB::bind_method(D_METHOD("get_world:World"), &Spatial::get_world);
// TODO: Obsolete those two methods (old name) properly (GH-4397)
- ClassDB::bind_method(D_METHOD("_set_rotation_deg","rotation_deg"), &Spatial::_set_rotation_deg);
+ ClassDB::bind_method(D_METHOD("_set_rotation_deg", "rotation_deg"), &Spatial::_set_rotation_deg);
ClassDB::bind_method(D_METHOD("_get_rotation_deg"), &Spatial::_get_rotation_deg);
#ifdef TOOLS_ENABLED
ClassDB::bind_method(D_METHOD("_update_gizmo"), &Spatial::_update_gizmo);
ClassDB::bind_method(D_METHOD("_set_import_transform"), &Spatial::set_import_transform);
ClassDB::bind_method(D_METHOD("_get_import_transform"), &Spatial::get_import_transform);
- ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"_import_transform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_import_transform","_get_import_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM, "_import_transform", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_import_transform", "_get_import_transform");
#endif
ClassDB::bind_method(D_METHOD("update_gizmo"), &Spatial::update_gizmo);
- ClassDB::bind_method(D_METHOD("set_gizmo","gizmo:SpatialGizmo"), &Spatial::set_gizmo);
+ ClassDB::bind_method(D_METHOD("set_gizmo", "gizmo:SpatialGizmo"), &Spatial::set_gizmo);
ClassDB::bind_method(D_METHOD("get_gizmo:SpatialGizmo"), &Spatial::get_gizmo);
ClassDB::bind_method(D_METHOD("set_visible"), &Spatial::set_visible);
@@ -781,84 +743,77 @@ void Spatial::_bind_methods() {
ClassDB::bind_method(D_METHOD("show"), &Spatial::show);
ClassDB::bind_method(D_METHOD("hide"), &Spatial::hide);
- ClassDB::bind_method(D_METHOD("set_notify_local_transform","enable"), &Spatial::set_notify_local_transform);
+ ClassDB::bind_method(D_METHOD("set_notify_local_transform", "enable"), &Spatial::set_notify_local_transform);
ClassDB::bind_method(D_METHOD("is_local_transform_notification_enabled"), &Spatial::is_local_transform_notification_enabled);
- ClassDB::bind_method(D_METHOD("set_notify_transform","enable"), &Spatial::set_notify_transform);
+ ClassDB::bind_method(D_METHOD("set_notify_transform", "enable"), &Spatial::set_notify_transform);
ClassDB::bind_method(D_METHOD("is_transform_notification_enabled"), &Spatial::is_transform_notification_enabled);
- void rotate(const Vector3& p_normal,float p_radians);
+ void rotate(const Vector3 &p_normal, float p_radians);
void rotate_x(float p_radians);
void rotate_y(float p_radians);
void rotate_z(float p_radians);
- void translate(const Vector3& p_offset);
- void scale(const Vector3& p_ratio);
- void global_rotate(const Vector3& p_normal,float p_radians);
- void global_translate(const Vector3& p_offset);
-
- ClassDB::bind_method( D_METHOD("rotate","normal","radians"),&Spatial::rotate );
- ClassDB::bind_method( D_METHOD("global_rotate","normal","radians"),&Spatial::global_rotate );
- ClassDB::bind_method( D_METHOD("rotate_x","radians"),&Spatial::rotate_x );
- ClassDB::bind_method( D_METHOD("rotate_y","radians"),&Spatial::rotate_y );
- ClassDB::bind_method( D_METHOD("rotate_z","radians"),&Spatial::rotate_z );
- ClassDB::bind_method( D_METHOD("translate","offset"),&Spatial::translate );
- ClassDB::bind_method( D_METHOD("global_translate","offset"),&Spatial::global_translate );
- ClassDB::bind_method( D_METHOD("orthonormalize"),&Spatial::orthonormalize );
- ClassDB::bind_method( D_METHOD("set_identity"),&Spatial::set_identity );
-
- ClassDB::bind_method( D_METHOD("look_at","target","up"),&Spatial::look_at );
- ClassDB::bind_method( D_METHOD("look_at_from_pos","pos","target","up"),&Spatial::look_at_from_pos );
-
- BIND_CONSTANT( NOTIFICATION_TRANSFORM_CHANGED );
- BIND_CONSTANT( NOTIFICATION_ENTER_WORLD );
- BIND_CONSTANT( NOTIFICATION_EXIT_WORLD );
- BIND_CONSTANT( NOTIFICATION_VISIBILITY_CHANGED );
+ void translate(const Vector3 &p_offset);
+ void scale(const Vector3 &p_ratio);
+ void global_rotate(const Vector3 &p_normal, float p_radians);
+ void global_translate(const Vector3 &p_offset);
+
+ ClassDB::bind_method(D_METHOD("rotate", "normal", "radians"), &Spatial::rotate);
+ ClassDB::bind_method(D_METHOD("global_rotate", "normal", "radians"), &Spatial::global_rotate);
+ ClassDB::bind_method(D_METHOD("rotate_x", "radians"), &Spatial::rotate_x);
+ ClassDB::bind_method(D_METHOD("rotate_y", "radians"), &Spatial::rotate_y);
+ ClassDB::bind_method(D_METHOD("rotate_z", "radians"), &Spatial::rotate_z);
+ ClassDB::bind_method(D_METHOD("translate", "offset"), &Spatial::translate);
+ ClassDB::bind_method(D_METHOD("global_translate", "offset"), &Spatial::global_translate);
+ ClassDB::bind_method(D_METHOD("orthonormalize"), &Spatial::orthonormalize);
+ ClassDB::bind_method(D_METHOD("set_identity"), &Spatial::set_identity);
+
+ ClassDB::bind_method(D_METHOD("look_at", "target", "up"), &Spatial::look_at);
+ ClassDB::bind_method(D_METHOD("look_at_from_pos", "pos", "target", "up"), &Spatial::look_at_from_pos);
+
+ BIND_CONSTANT(NOTIFICATION_TRANSFORM_CHANGED);
+ BIND_CONSTANT(NOTIFICATION_ENTER_WORLD);
+ BIND_CONSTANT(NOTIFICATION_EXIT_WORLD);
+ BIND_CONSTANT(NOTIFICATION_VISIBILITY_CHANGED);
//ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"transform/global",PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR ), "set_global_transform", "get_global_transform") ;
- ADD_GROUP("Transform","");
- ADD_PROPERTYNZ( PropertyInfo(Variant::TRANSFORM,"transform",PROPERTY_HINT_NONE,""), "set_transform", "get_transform") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::TRANSFORM,"global_transform",PROPERTY_HINT_NONE,"",0), "set_global_transform", "get_global_transform") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"translation",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_translation", "get_translation") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"rotation_deg",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_rotation_deg", "get_rotation_deg") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"rotation",PROPERTY_HINT_NONE,"",0), "set_rotation", "get_rotation") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"scale",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR), "set_scale", "get_scale") ;
- ADD_GROUP("Visibility","");
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"visible"), "set_visible", "is_visible") ;
+ ADD_GROUP("Transform", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::TRANSFORM, "transform", PROPERTY_HINT_NONE, ""), "set_transform", "get_transform");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::TRANSFORM, "global_transform", PROPERTY_HINT_NONE, "", 0), "set_global_transform", "get_global_transform");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "translation", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_translation", "get_translation");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation_deg", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_rotation_deg", "get_rotation_deg");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "rotation", PROPERTY_HINT_NONE, "", 0), "set_rotation", "get_rotation");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "scale", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_scale", "get_scale");
+ ADD_GROUP("Visibility", "");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "visible"), "set_visible", "is_visible");
//ADD_PROPERTY( PropertyInfo(Variant::TRANSFORM,"transform/local"), "set_transform", "get_transform") ;
- ADD_SIGNAL( MethodInfo("visibility_changed" ) );
-
+ ADD_SIGNAL(MethodInfo("visibility_changed"));
}
+Spatial::Spatial()
+ : xform_change(this) {
-Spatial::Spatial() : xform_change(this)
-{
+ data.dirty = DIRTY_NONE;
+ data.children_lock = 0;
- data.dirty=DIRTY_NONE;
- data.children_lock=0;
-
- data.ignore_notification=false;
- data.toplevel=false;
- data.toplevel_active=false;
- data.scale=Vector3(1,1,1);
- data.viewport=NULL;
- data.inside_world=false;
- data.visible=true;
+ data.ignore_notification = false;
+ data.toplevel = false;
+ data.toplevel_active = false;
+ data.scale = Vector3(1, 1, 1);
+ data.viewport = NULL;
+ data.inside_world = false;
+ data.visible = true;
#ifdef TOOLS_ENABLED
- data.gizmo_disabled=false;
- data.gizmo_dirty=false;
+ data.gizmo_disabled = false;
+ data.gizmo_dirty = false;
#endif
- data.notify_local_transform=false;
- data.notify_transform=false;
- data.parent=NULL;
- data.C=NULL;
-
+ data.notify_local_transform = false;
+ data.notify_transform = false;
+ data.parent = NULL;
+ data.C = NULL;
}
-
Spatial::~Spatial() {
-
}
-
-
diff --git a/scene/3d/spatial.h b/scene/3d/spatial.h
index 72daa472bd..e5817883dd 100644
--- a/scene/3d/spatial.h
+++ b/scene/3d/spatial.h
@@ -38,39 +38,34 @@
class SpatialGizmo : public Reference {
- GDCLASS(SpatialGizmo,Reference);
-
+ GDCLASS(SpatialGizmo, Reference);
public:
-
- virtual void create()=0;
- virtual void transform()=0;
- virtual void clear()=0;
- virtual void redraw()=0;
- virtual void free()=0;
+ virtual void create() = 0;
+ virtual void transform() = 0;
+ virtual void clear() = 0;
+ virtual void redraw() = 0;
+ virtual void free() = 0;
SpatialGizmo();
};
-
class Spatial : public Node {
- GDCLASS( Spatial, Node );
+ GDCLASS(Spatial, Node);
OBJ_CATEGORY("3D");
enum TransformDirty {
- DIRTY_NONE=0,
- DIRTY_VECTORS=1,
- DIRTY_LOCAL=2,
- DIRTY_GLOBAL=4
+ DIRTY_NONE = 0,
+ DIRTY_VECTORS = 1,
+ DIRTY_LOCAL = 2,
+ DIRTY_GLOBAL = 4
};
mutable SelfList<Node> xform_change;
struct Data {
-
-
mutable Transform global_transform;
mutable Transform local_transform;
mutable Vector3 rotation;
@@ -80,15 +75,14 @@ class Spatial : public Node {
Viewport *viewport;
-
bool toplevel_active;
bool toplevel;
bool inside_world;
int children_lock;
Spatial *parent;
- List<Spatial*> children;
- List<Spatial*>::Element *C;
+ List<Spatial *> children;
+ List<Spatial *>::Element *C;
bool ignore_notification;
bool notify_local_transform;
@@ -112,15 +106,13 @@ class Spatial : public Node {
void _propagate_transform_changed(Spatial *p_origin);
// Deprecated, should be removed in a future version.
- void _set_rotation_deg(const Vector3& p_euler_deg);
+ void _set_rotation_deg(const Vector3 &p_euler_deg);
Vector3 _get_rotation_deg() const;
void _propagate_visibility_changed();
-
protected:
-
- _FORCE_INLINE_ void set_ignore_transform_notification(bool p_ignore) { data.ignore_notification=p_ignore; }
+ _FORCE_INLINE_ void set_ignore_transform_notification(bool p_ignore) { data.ignore_notification = p_ignore; }
_FORCE_INLINE_ void _update_local_transform() const;
@@ -128,33 +120,31 @@ protected:
static void _bind_methods();
public:
-
enum {
- NOTIFICATION_TRANSFORM_CHANGED=SceneTree::NOTIFICATION_TRANSFORM_CHANGED,
- NOTIFICATION_ENTER_WORLD=41,
- NOTIFICATION_EXIT_WORLD=42,
- NOTIFICATION_VISIBILITY_CHANGED=43,
- NOTIFICATION_LOCAL_TRANSFORM_CHANGED=44,
+ NOTIFICATION_TRANSFORM_CHANGED = SceneTree::NOTIFICATION_TRANSFORM_CHANGED,
+ NOTIFICATION_ENTER_WORLD = 41,
+ NOTIFICATION_EXIT_WORLD = 42,
+ NOTIFICATION_VISIBILITY_CHANGED = 43,
+ NOTIFICATION_LOCAL_TRANSFORM_CHANGED = 44,
};
Spatial *get_parent_spatial() const;
-
Ref<World> get_world() const;
- void set_translation(const Vector3& p_translation);
- void set_rotation(const Vector3& p_euler_rad);
- void set_rotation_in_degrees(const Vector3& p_euler_deg);
- void set_scale(const Vector3& p_scale);
+ void set_translation(const Vector3 &p_translation);
+ void set_rotation(const Vector3 &p_euler_rad);
+ void set_rotation_in_degrees(const Vector3 &p_euler_deg);
+ void set_scale(const Vector3 &p_scale);
Vector3 get_translation() const;
Vector3 get_rotation() const;
Vector3 get_rotation_in_degrees() const;
Vector3 get_scale() const;
- void set_transform(const Transform& p_transform);
- void set_global_transform(const Transform& p_transform);
+ void set_transform(const Transform &p_transform);
+ void set_global_transform(const Transform &p_transform);
Transform get_transform() const;
Transform get_global_transform() const;
@@ -164,24 +154,24 @@ public:
void set_disable_gizmo(bool p_enabled);
void update_gizmo();
- void set_gizmo(const Ref<SpatialGizmo>& p_gizmo);
+ void set_gizmo(const Ref<SpatialGizmo> &p_gizmo);
Ref<SpatialGizmo> get_gizmo() const;
_FORCE_INLINE_ bool is_inside_world() const { return data.inside_world; }
Transform get_relative_transform(const Node *p_parent) const;
- void rotate(const Vector3& p_normal,float p_radians);
+ void rotate(const Vector3 &p_normal, float p_radians);
void rotate_x(float p_radians);
void rotate_y(float p_radians);
void rotate_z(float p_radians);
- void translate(const Vector3& p_offset);
- void scale(const Vector3& p_ratio);
- void global_rotate(const Vector3& p_normal,float p_radians);
- void global_translate(const Vector3& p_offset);
+ void translate(const Vector3 &p_offset);
+ void scale(const Vector3 &p_ratio);
+ void global_rotate(const Vector3 &p_normal, float p_radians);
+ void global_translate(const Vector3 &p_offset);
- void look_at(const Vector3& p_target, const Vector3& p_up_normal);
- void look_at_from_pos(const Vector3& p_pos,const Vector3& p_target, const Vector3& p_up_normal);
+ void look_at(const Vector3 &p_target, const Vector3 &p_up_normal);
+ void look_at_from_pos(const Vector3 &p_pos, const Vector3 &p_target, const Vector3 &p_up_normal);
void set_notify_transform(bool p_enable);
bool is_transform_notification_enabled() const;
@@ -199,13 +189,12 @@ public:
bool is_visible_in_tree() const;
#ifdef TOOLS_ENABLED
- void set_import_transform(const Transform& p_transform) ;
+ void set_import_transform(const Transform &p_transform);
Transform get_import_transform() const;
#endif
Spatial();
~Spatial();
-
};
#endif
diff --git a/scene/3d/spatial_indexer.cpp b/scene/3d/spatial_indexer.cpp
index 6d6c272c25..cddbf9a4e8 100644
--- a/scene/3d/spatial_indexer.cpp
+++ b/scene/3d/spatial_indexer.cpp
@@ -30,8 +30,8 @@
#if 0
-#include "proximity_area.h"
#include "camera.h"
+#include "proximity_area.h"
#include "scene/scene_string_names.h"
void SpatialIndexer::add_camera(Camera* p_camera) {
diff --git a/scene/3d/sprite_3d.cpp b/scene/3d/sprite_3d.cpp
index 5adb7050f8..062e3943b9 100644
--- a/scene/3d/sprite_3d.cpp
+++ b/scene/3d/sprite_3d.cpp
@@ -27,9 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "sprite_3d.h"
-#include "scene/scene_string_names.h"
#include "core_string_names.h"
-
+#include "scene/scene_string_names.h"
Color SpriteBase3D::_get_color_accum() {
@@ -37,15 +36,15 @@ Color SpriteBase3D::_get_color_accum() {
return color_accum;
if (parent_sprite)
- color_accum=parent_sprite->_get_color_accum();
+ color_accum = parent_sprite->_get_color_accum();
else
- color_accum=Color(1,1,1,1);
+ color_accum = Color(1, 1, 1, 1);
- color_accum.r*=modulate.r;
- color_accum.g*=modulate.g;
- color_accum.b*=modulate.b;
- color_accum.a*=modulate.a;
- color_dirty=false;
+ color_accum.r *= modulate.r;
+ color_accum.g *= modulate.g;
+ color_accum.b *= modulate.b;
+ color_accum.a *= modulate.a;
+ color_dirty = false;
return color_accum;
}
@@ -54,10 +53,10 @@ void SpriteBase3D::_propagate_color_changed() {
if (color_dirty)
return;
- color_dirty=true;
+ color_dirty = true;
_queue_update();
- for (List<SpriteBase3D*>::Element *E=children.front();E;E=E->next()) {
+ for (List<SpriteBase3D *>::Element *E = children.front(); E; E = E->next()) {
E->get()->_propagate_color_changed();
}
@@ -65,40 +64,36 @@ void SpriteBase3D::_propagate_color_changed() {
void SpriteBase3D::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
if (!pending_update)
_im_update();
- Node *parent=get_parent();
+ Node *parent = get_parent();
if (parent) {
- parent_sprite=parent->cast_to<SpriteBase3D>();
+ parent_sprite = parent->cast_to<SpriteBase3D>();
if (parent_sprite) {
- pI=parent_sprite->children.push_back(this);
+ pI = parent_sprite->children.push_back(this);
}
}
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (parent_sprite) {
parent_sprite->children.erase(pI);
- pI=NULL;
- parent_sprite=NULL;
+ pI = NULL;
+ parent_sprite = NULL;
}
}
-
}
-
void SpriteBase3D::set_centered(bool p_center) {
- centered=p_center;
+ centered = p_center;
_queue_update();
-
}
bool SpriteBase3D::is_centered() const {
@@ -106,11 +101,10 @@ bool SpriteBase3D::is_centered() const {
return centered;
}
-void SpriteBase3D::set_offset(const Point2& p_offset) {
+void SpriteBase3D::set_offset(const Point2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
_queue_update();
-
}
Point2 SpriteBase3D::get_offset() const {
@@ -119,7 +113,7 @@ Point2 SpriteBase3D::get_offset() const {
void SpriteBase3D::set_flip_h(bool p_flip) {
- hflip=p_flip;
+ hflip = p_flip;
_queue_update();
}
bool SpriteBase3D::is_flipped_h() const {
@@ -129,7 +123,7 @@ bool SpriteBase3D::is_flipped_h() const {
void SpriteBase3D::set_flip_v(bool p_flip) {
- vflip=p_flip;
+ vflip = p_flip;
_queue_update();
}
bool SpriteBase3D::is_flipped_v() const {
@@ -137,24 +131,21 @@ bool SpriteBase3D::is_flipped_v() const {
return vflip;
}
+void SpriteBase3D::set_modulate(const Color &p_color) {
-
-void SpriteBase3D::set_modulate(const Color& p_color) {
-
- modulate=p_color;
+ modulate = p_color;
_propagate_color_changed();
_queue_update();
}
-Color SpriteBase3D::get_modulate() const{
+Color SpriteBase3D::get_modulate() const {
return modulate;
}
-
void SpriteBase3D::set_pixel_size(float p_amount) {
- pixel_size=p_amount;
+ pixel_size = p_amount;
_queue_update();
}
float SpriteBase3D::get_pixel_size() const {
@@ -164,7 +155,7 @@ float SpriteBase3D::get_pixel_size() const {
void SpriteBase3D::set_opacity(float p_amount) {
- opacity=p_amount;
+ opacity = p_amount;
_queue_update();
}
float SpriteBase3D::get_opacity() const {
@@ -172,10 +163,9 @@ float SpriteBase3D::get_opacity() const {
return opacity;
}
-
void SpriteBase3D::set_axis(Vector3::Axis p_axis) {
- axis=p_axis;
+ axis = p_axis;
_queue_update();
}
Vector3::Axis SpriteBase3D::get_axis() const {
@@ -183,30 +173,24 @@ Vector3::Axis SpriteBase3D::get_axis() const {
return axis;
}
-
-
void SpriteBase3D::_im_update() {
-
_draw();
-
- pending_update=false;
+ pending_update = false;
//texture->draw_rect_region(ci,dst_rect,src_rect,modulate);
-
}
-void SpriteBase3D::_queue_update(){
+void SpriteBase3D::_queue_update() {
- if (pending_update)
+ if (pending_update)
return;
- pending_update=true;
+ pending_update = true;
call_deferred(SceneStringNames::get_singleton()->_im_update);
}
-
Rect3 SpriteBase3D::get_aabb() const {
return aabb;
@@ -214,135 +198,119 @@ Rect3 SpriteBase3D::get_aabb() const {
PoolVector<Face3> SpriteBase3D::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
-
}
-void SpriteBase3D::set_draw_flag(DrawFlags p_flag,bool p_enable) {
+void SpriteBase3D::set_draw_flag(DrawFlags p_flag, bool p_enable) {
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- flags[p_flag]=p_enable;
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ flags[p_flag] = p_enable;
_queue_update();
}
-bool SpriteBase3D::get_draw_flag(DrawFlags p_flag) const{
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+bool SpriteBase3D::get_draw_flag(DrawFlags p_flag) const {
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags[p_flag];
}
-void SpriteBase3D::set_alpha_cut_mode(AlphaCutMode p_mode){
+void SpriteBase3D::set_alpha_cut_mode(AlphaCutMode p_mode) {
- ERR_FAIL_INDEX(p_mode,3);
- alpha_cut=p_mode;
+ ERR_FAIL_INDEX(p_mode, 3);
+ alpha_cut = p_mode;
_queue_update();
-
}
-SpriteBase3D::AlphaCutMode SpriteBase3D::get_alpha_cut_mode() const{
+SpriteBase3D::AlphaCutMode SpriteBase3D::get_alpha_cut_mode() const {
return alpha_cut;
}
-
void SpriteBase3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_centered", "centered"), &SpriteBase3D::set_centered);
+ ClassDB::bind_method(D_METHOD("is_centered"), &SpriteBase3D::is_centered);
- ClassDB::bind_method(D_METHOD("set_centered","centered"),&SpriteBase3D::set_centered);
- ClassDB::bind_method(D_METHOD("is_centered"),&SpriteBase3D::is_centered);
-
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&SpriteBase3D::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&SpriteBase3D::get_offset);
-
- ClassDB::bind_method(D_METHOD("set_flip_h","flip_h"),&SpriteBase3D::set_flip_h);
- ClassDB::bind_method(D_METHOD("is_flipped_h"),&SpriteBase3D::is_flipped_h);
-
- ClassDB::bind_method(D_METHOD("set_flip_v","flip_v"),&SpriteBase3D::set_flip_v);
- ClassDB::bind_method(D_METHOD("is_flipped_v"),&SpriteBase3D::is_flipped_v);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &SpriteBase3D::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &SpriteBase3D::get_offset);
+ ClassDB::bind_method(D_METHOD("set_flip_h", "flip_h"), &SpriteBase3D::set_flip_h);
+ ClassDB::bind_method(D_METHOD("is_flipped_h"), &SpriteBase3D::is_flipped_h);
- ClassDB::bind_method(D_METHOD("set_modulate","modulate"),&SpriteBase3D::set_modulate);
- ClassDB::bind_method(D_METHOD("get_modulate"),&SpriteBase3D::get_modulate);
+ ClassDB::bind_method(D_METHOD("set_flip_v", "flip_v"), &SpriteBase3D::set_flip_v);
+ ClassDB::bind_method(D_METHOD("is_flipped_v"), &SpriteBase3D::is_flipped_v);
- ClassDB::bind_method(D_METHOD("set_opacity","opacity"),&SpriteBase3D::set_opacity);
- ClassDB::bind_method(D_METHOD("get_opacity"),&SpriteBase3D::get_opacity);
+ ClassDB::bind_method(D_METHOD("set_modulate", "modulate"), &SpriteBase3D::set_modulate);
+ ClassDB::bind_method(D_METHOD("get_modulate"), &SpriteBase3D::get_modulate);
- ClassDB::bind_method(D_METHOD("set_pixel_size","pixel_size"),&SpriteBase3D::set_pixel_size);
- ClassDB::bind_method(D_METHOD("get_pixel_size"),&SpriteBase3D::get_pixel_size);
+ ClassDB::bind_method(D_METHOD("set_opacity", "opacity"), &SpriteBase3D::set_opacity);
+ ClassDB::bind_method(D_METHOD("get_opacity"), &SpriteBase3D::get_opacity);
- ClassDB::bind_method(D_METHOD("set_axis","axis"),&SpriteBase3D::set_axis);
- ClassDB::bind_method(D_METHOD("get_axis"),&SpriteBase3D::get_axis);
+ ClassDB::bind_method(D_METHOD("set_pixel_size", "pixel_size"), &SpriteBase3D::set_pixel_size);
+ ClassDB::bind_method(D_METHOD("get_pixel_size"), &SpriteBase3D::get_pixel_size);
- ClassDB::bind_method(D_METHOD("set_draw_flag","flag","enabled"),&SpriteBase3D::set_draw_flag);
- ClassDB::bind_method(D_METHOD("get_draw_flag","flag"),&SpriteBase3D::get_draw_flag);
+ ClassDB::bind_method(D_METHOD("set_axis", "axis"), &SpriteBase3D::set_axis);
+ ClassDB::bind_method(D_METHOD("get_axis"), &SpriteBase3D::get_axis);
- ClassDB::bind_method(D_METHOD("set_alpha_cut_mode","mode"),&SpriteBase3D::set_alpha_cut_mode);
- ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"),&SpriteBase3D::get_alpha_cut_mode);
+ ClassDB::bind_method(D_METHOD("set_draw_flag", "flag", "enabled"), &SpriteBase3D::set_draw_flag);
+ ClassDB::bind_method(D_METHOD("get_draw_flag", "flag"), &SpriteBase3D::get_draw_flag);
- ClassDB::bind_method(D_METHOD("get_item_rect"),&SpriteBase3D::get_item_rect);
+ ClassDB::bind_method(D_METHOD("set_alpha_cut_mode", "mode"), &SpriteBase3D::set_alpha_cut_mode);
+ ClassDB::bind_method(D_METHOD("get_alpha_cut_mode"), &SpriteBase3D::get_alpha_cut_mode);
- ClassDB::bind_method(D_METHOD("_queue_update"),&SpriteBase3D::_queue_update);
- ClassDB::bind_method(D_METHOD("_im_update"),&SpriteBase3D::_im_update);
+ ClassDB::bind_method(D_METHOD("get_item_rect"), &SpriteBase3D::get_item_rect);
+ ClassDB::bind_method(D_METHOD("_queue_update"), &SpriteBase3D::_queue_update);
+ ClassDB::bind_method(D_METHOD("_im_update"), &SpriteBase3D::_im_update);
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "centered"), "set_centered","is_centered");
- ADD_PROPERTY( PropertyInfo( Variant::VECTOR2, "offset"), "set_offset","get_offset");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flip_h"), "set_flip_h","is_flipped_h");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flip_v"), "set_flip_v","is_flipped_v");
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "modulate"), "set_modulate","get_modulate");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "opacity",PROPERTY_HINT_RANGE,"0,1,0.01"), "set_opacity","get_opacity");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "pixel_size",PROPERTY_HINT_RANGE,"0.0001,128,0.0001"), "set_pixel_size","get_pixel_size");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "axis",PROPERTY_HINT_ENUM,"X-Axis,Y-Axis,Z-Axis"), "set_axis","get_axis");
- ADD_GROUP("Flags","");
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "transparent"), "set_draw_flag","get_draw_flag",FLAG_TRANSPARENT);
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "shaded"), "set_draw_flag","get_draw_flag",FLAG_SHADED);
- ADD_PROPERTY( PropertyInfo( Variant::INT, "alpha_cut",PROPERTY_HINT_ENUM,"Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode","get_alpha_cut_mode");
-
-
- BIND_CONSTANT( FLAG_TRANSPARENT );
- BIND_CONSTANT( FLAG_SHADED );
- BIND_CONSTANT( FLAG_MAX );
-
- BIND_CONSTANT( ALPHA_CUT_DISABLED );
- BIND_CONSTANT( ALPHA_CUT_DISCARD );
- BIND_CONSTANT( ALPHA_CUT_OPAQUE_PREPASS );
-
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "centered"), "set_centered", "is_centered");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_h"), "set_flip_h", "is_flipped_h");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flip_v"), "set_flip_v", "is_flipped_v");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate"), "set_modulate", "get_modulate");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "opacity", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_opacity", "get_opacity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "pixel_size", PROPERTY_HINT_RANGE, "0.0001,128,0.0001"), "set_pixel_size", "get_pixel_size");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "axis", PROPERTY_HINT_ENUM, "X-Axis,Y-Axis,Z-Axis"), "set_axis", "get_axis");
+ ADD_GROUP("Flags", "");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "transparent"), "set_draw_flag", "get_draw_flag", FLAG_TRANSPARENT);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "shaded"), "set_draw_flag", "get_draw_flag", FLAG_SHADED);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alpha_cut", PROPERTY_HINT_ENUM, "Disabled,Discard,Opaque Pre-Pass"), "set_alpha_cut_mode", "get_alpha_cut_mode");
+ BIND_CONSTANT(FLAG_TRANSPARENT);
+ BIND_CONSTANT(FLAG_SHADED);
+ BIND_CONSTANT(FLAG_MAX);
+ BIND_CONSTANT(ALPHA_CUT_DISABLED);
+ BIND_CONSTANT(ALPHA_CUT_DISCARD);
+ BIND_CONSTANT(ALPHA_CUT_OPAQUE_PREPASS);
}
-
-
-
SpriteBase3D::SpriteBase3D() {
- color_dirty=true;
- centered=true;
- hflip=false;
- vflip=false;
- parent_sprite=NULL;
- pI=NULL;
-
- for(int i=0;i<FLAG_MAX;i++)
- flags[i]=i==FLAG_TRANSPARENT;
-
- axis=Vector3::AXIS_Z;
- pixel_size=0.01;
- modulate=Color(1,1,1,1);
- pending_update=false;
- opacity=1.0;
+ color_dirty = true;
+ centered = true;
+ hflip = false;
+ vflip = false;
+ parent_sprite = NULL;
+ pI = NULL;
+
+ for (int i = 0; i < FLAG_MAX; i++)
+ flags[i] = i == FLAG_TRANSPARENT;
+
+ axis = Vector3::AXIS_Z;
+ pixel_size = 0.01;
+ modulate = Color(1, 1, 1, 1);
+ pending_update = false;
+ opacity = 1.0;
immediate = VisualServer::get_singleton()->immediate_create();
set_base(immediate);
}
-
SpriteBase3D::~SpriteBase3D() {
VisualServer::get_singleton()->free(immediate);
}
-
///////////////////////////////////////////
-
void Sprite3D::_draw() {
RID immediate = get_immediate();
@@ -351,7 +319,7 @@ void Sprite3D::_draw() {
if (!texture.is_valid())
return; //no texuture no life
Vector2 tsize = texture->get_size();
- if (tsize.x==0 || tsize.y==0)
+ if (tsize.x == 0 || tsize.y == 0)
return;
Size2i s;
@@ -359,130 +327,122 @@ void Sprite3D::_draw() {
if (region) {
- s=region_rect.size;
- src_rect=region_rect;
+ s = region_rect.size;
+ src_rect = region_rect;
} else {
s = texture->get_size();
- s=s/Size2i(hframes,vframes);
-
- src_rect.size=s;
- src_rect.pos.x+=(frame%hframes)*s.x;
- src_rect.pos.y+=(frame/hframes)*s.y;
+ s = s / Size2i(hframes, vframes);
+ src_rect.size = s;
+ src_rect.pos.x += (frame % hframes) * s.x;
+ src_rect.pos.y += (frame / hframes) * s.y;
}
- Point2i ofs=get_offset();
+ Point2i ofs = get_offset();
if (is_centered())
- ofs-=s/2;
-
- Rect2i dst_rect(ofs,s);
+ ofs -= s / 2;
+ Rect2i dst_rect(ofs, s);
Rect2 final_rect;
Rect2 final_src_rect;
- if (!texture->get_rect_region(dst_rect,src_rect,final_rect,final_src_rect))
+ if (!texture->get_rect_region(dst_rect, src_rect, final_rect, final_src_rect))
return;
-
- if (final_rect.size.x==0 || final_rect.size.y==0)
+ if (final_rect.size.x == 0 || final_rect.size.y == 0)
return;
- Color color=_get_color_accum();
- color.a*=get_opacity();
+ Color color = _get_color_accum();
+ color.a *= get_opacity();
- float pixel_size=get_pixel_size();
+ float pixel_size = get_pixel_size();
- Vector2 vertices[4]={
+ Vector2 vertices[4] = {
- (final_rect.pos+Vector2(0,final_rect.size.y)) * pixel_size,
- (final_rect.pos+final_rect.size) * pixel_size,
- (final_rect.pos+Vector2(final_rect.size.x,0)) * pixel_size,
+ (final_rect.pos + Vector2(0, final_rect.size.y)) * pixel_size,
+ (final_rect.pos + final_rect.size) * pixel_size,
+ (final_rect.pos + Vector2(final_rect.size.x, 0)) * pixel_size,
final_rect.pos * pixel_size,
-
};
- Vector2 uvs[4]={
+ Vector2 uvs[4] = {
final_src_rect.pos / tsize,
- (final_src_rect.pos+Vector2(final_src_rect.size.x,0)) / tsize,
- (final_src_rect.pos+final_src_rect.size) / tsize,
- (final_src_rect.pos+Vector2(0,final_src_rect.size.y)) / tsize,
+ (final_src_rect.pos + Vector2(final_src_rect.size.x, 0)) / tsize,
+ (final_src_rect.pos + final_src_rect.size) / tsize,
+ (final_src_rect.pos + Vector2(0, final_src_rect.size.y)) / tsize,
};
if (is_flipped_h()) {
- SWAP(uvs[0],uvs[1]);
- SWAP(uvs[2],uvs[3]);
+ SWAP(uvs[0], uvs[1]);
+ SWAP(uvs[2], uvs[3]);
}
if (is_flipped_v()) {
- SWAP(uvs[0],uvs[3]);
- SWAP(uvs[1],uvs[2]);
+ SWAP(uvs[0], uvs[3]);
+ SWAP(uvs[1], uvs[2]);
}
-
Vector3 normal;
int axis = get_axis();
- normal[axis]=1.0;
+ normal[axis] = 1.0;
- RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED),get_draw_flag(FLAG_TRANSPARENT),get_alpha_cut_mode()==ALPHA_CUT_DISCARD,get_alpha_cut_mode()==ALPHA_CUT_OPAQUE_PREPASS);
- VS::get_singleton()->immediate_set_material(immediate,mat);
+ RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED), get_draw_flag(FLAG_TRANSPARENT), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS);
+ VS::get_singleton()->immediate_set_material(immediate, mat);
- VS::get_singleton()->immediate_begin(immediate,VS::PRIMITIVE_TRIANGLE_FAN,texture->get_rid());
+ VS::get_singleton()->immediate_begin(immediate, VS::PRIMITIVE_TRIANGLE_FAN, texture->get_rid());
int x_axis = ((axis + 1) % 3);
int y_axis = ((axis + 2) % 3);
- if (axis!=Vector3::AXIS_Z) {
- SWAP(x_axis,y_axis);
+ if (axis != Vector3::AXIS_Z) {
+ SWAP(x_axis, y_axis);
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
//uvs[i] = Vector2(1.0,1.0)-uvs[i];
//SWAP(vertices[i].x,vertices[i].y);
- if (axis==Vector3::AXIS_Y) {
- vertices[i].y = - vertices[i].y;
- } else if (axis==Vector3::AXIS_X) {
- vertices[i].x = - vertices[i].x;
+ if (axis == Vector3::AXIS_Y) {
+ vertices[i].y = -vertices[i].y;
+ } else if (axis == Vector3::AXIS_X) {
+ vertices[i].x = -vertices[i].x;
}
}
}
Rect3 aabb;
- for(int i=0;i<4;i++) {
- VS::get_singleton()->immediate_normal(immediate,normal);
- VS::get_singleton()->immediate_color(immediate,color);
- VS::get_singleton()->immediate_uv(immediate,uvs[i]);
+ for (int i = 0; i < 4; i++) {
+ VS::get_singleton()->immediate_normal(immediate, normal);
+ VS::get_singleton()->immediate_color(immediate, color);
+ VS::get_singleton()->immediate_uv(immediate, uvs[i]);
Vector3 vtx;
- vtx[x_axis]=vertices[i][0];
- vtx[y_axis]=vertices[i][1];
- VS::get_singleton()->immediate_vertex(immediate,vtx);
- if (i==0) {
- aabb.pos=vtx;
- aabb.size=Vector3();
+ vtx[x_axis] = vertices[i][0];
+ vtx[y_axis] = vertices[i][1];
+ VS::get_singleton()->immediate_vertex(immediate, vtx);
+ if (i == 0) {
+ aabb.pos = vtx;
+ aabb.size = Vector3();
} else {
aabb.expand_to(vtx);
}
}
set_aabb(aabb);
VS::get_singleton()->immediate_end(immediate);
-
-
}
-void Sprite3D::set_texture(const Ref<Texture>& p_texture) {
+void Sprite3D::set_texture(const Ref<Texture> &p_texture) {
- if (p_texture==texture)
+ if (p_texture == texture)
return;
if (texture.is_valid()) {
- texture->disconnect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_queue_update);
+ texture->disconnect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_queue_update);
}
- texture=p_texture;
+ texture = p_texture;
if (texture.is_valid()) {
texture->set_flags(texture->get_flags()); //remove repeat from texture, it looks bad in sprites
- texture->connect(CoreStringNames::get_singleton()->changed,this,SceneStringNames::get_singleton()->_queue_update);
+ texture->connect(CoreStringNames::get_singleton()->changed, this, SceneStringNames::get_singleton()->_queue_update);
}
_queue_update();
-
}
Ref<Texture> Sprite3D::get_texture() const {
@@ -492,22 +452,22 @@ Ref<Texture> Sprite3D::get_texture() const {
void Sprite3D::set_region(bool p_region) {
- if (p_region==region)
+ if (p_region == region)
return;
- region=p_region;
+ region = p_region;
_queue_update();
}
-bool Sprite3D::is_region() const{
+bool Sprite3D::is_region() const {
return region;
}
-void Sprite3D::set_region_rect(const Rect2& p_region_rect) {
+void Sprite3D::set_region_rect(const Rect2 &p_region_rect) {
- bool changed=region_rect!=p_region_rect;
- region_rect=p_region_rect;
+ bool changed = region_rect != p_region_rect;
+ region_rect = p_region_rect;
if (region && changed) {
_queue_update();
}
@@ -520,14 +480,13 @@ Rect2 Sprite3D::get_region_rect() const {
void Sprite3D::set_frame(int p_frame) {
- ERR_FAIL_INDEX(p_frame,vframes*hframes);
+ ERR_FAIL_INDEX(p_frame, vframes * hframes);
if (frame != p_frame)
- frame=p_frame;
+ frame = p_frame;
_queue_update();
emit_signal(SceneStringNames::get_singleton()->frame_changed);
-
}
int Sprite3D::get_frame() const {
@@ -537,8 +496,8 @@ int Sprite3D::get_frame() const {
void Sprite3D::set_vframes(int p_amount) {
- ERR_FAIL_COND(p_amount<1);
- vframes=p_amount;
+ ERR_FAIL_COND(p_amount < 1);
+ vframes = p_amount;
_queue_update();
_change_notify("frame");
}
@@ -549,8 +508,8 @@ int Sprite3D::get_vframes() const {
void Sprite3D::set_hframes(int p_amount) {
- ERR_FAIL_COND(p_amount<1);
- hframes=p_amount;
+ ERR_FAIL_COND(p_amount < 1);
+ hframes = p_amount;
_queue_update();
_change_notify("frame");
}
@@ -562,7 +521,7 @@ int Sprite3D::get_hframes() const {
Rect2 Sprite3D::get_item_rect() const {
if (texture.is_null())
- return Rect2(0,0,1,1);
+ return Rect2(0, 0, 1, 1);
/*
if (texture.is_null())
return CanvasItem::get_item_rect();
@@ -572,72 +531,68 @@ Rect2 Sprite3D::get_item_rect() const {
if (region) {
- s=region_rect.size;
+ s = region_rect.size;
} else {
s = texture->get_size();
- s=s/Point2(hframes,vframes);
+ s = s / Point2(hframes, vframes);
}
- Point2i ofs=get_offset();
+ Point2i ofs = get_offset();
if (is_centered())
- ofs-=s/2;
+ ofs -= s / 2;
- if (s==Size2(0,0))
- s=Size2(1,1);
+ if (s == Size2(0, 0))
+ s = Size2(1, 1);
- return Rect2(ofs,s);
+ return Rect2(ofs, s);
}
+void Sprite3D::_validate_property(PropertyInfo &property) const {
-void Sprite3D::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="frame") {
+ if (property.name == "frame") {
- property.hint=PROPERTY_HINT_SPRITE_FRAME;
+ property.hint = PROPERTY_HINT_SPRITE_FRAME;
- property.hint_string="0,"+itos(vframes*hframes-1)+",1";
+ property.hint_string = "0," + itos(vframes * hframes - 1) + ",1";
}
}
void Sprite3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&Sprite3D::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture:Texture"),&Sprite3D::get_texture);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &Sprite3D::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture"), &Sprite3D::get_texture);
- ClassDB::bind_method(D_METHOD("set_region","enabled"),&Sprite3D::set_region);
- ClassDB::bind_method(D_METHOD("is_region"),&Sprite3D::is_region);
+ ClassDB::bind_method(D_METHOD("set_region", "enabled"), &Sprite3D::set_region);
+ ClassDB::bind_method(D_METHOD("is_region"), &Sprite3D::is_region);
- ClassDB::bind_method(D_METHOD("set_region_rect","rect"),&Sprite3D::set_region_rect);
- ClassDB::bind_method(D_METHOD("get_region_rect"),&Sprite3D::get_region_rect);
+ ClassDB::bind_method(D_METHOD("set_region_rect", "rect"), &Sprite3D::set_region_rect);
+ ClassDB::bind_method(D_METHOD("get_region_rect"), &Sprite3D::get_region_rect);
- ClassDB::bind_method(D_METHOD("set_frame","frame"),&Sprite3D::set_frame);
- ClassDB::bind_method(D_METHOD("get_frame"),&Sprite3D::get_frame);
+ ClassDB::bind_method(D_METHOD("set_frame", "frame"), &Sprite3D::set_frame);
+ ClassDB::bind_method(D_METHOD("get_frame"), &Sprite3D::get_frame);
- ClassDB::bind_method(D_METHOD("set_vframes","vframes"),&Sprite3D::set_vframes);
- ClassDB::bind_method(D_METHOD("get_vframes"),&Sprite3D::get_vframes);
+ ClassDB::bind_method(D_METHOD("set_vframes", "vframes"), &Sprite3D::set_vframes);
+ ClassDB::bind_method(D_METHOD("get_vframes"), &Sprite3D::get_vframes);
- ClassDB::bind_method(D_METHOD("set_hframes","hframes"),&Sprite3D::set_hframes);
- ClassDB::bind_method(D_METHOD("get_hframes"),&Sprite3D::get_hframes);
+ ClassDB::bind_method(D_METHOD("set_hframes", "hframes"), &Sprite3D::set_hframes);
+ ClassDB::bind_method(D_METHOD("get_hframes"), &Sprite3D::get_hframes);
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_texture","get_texture");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "vframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_vframes","get_vframes");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "hframes",PROPERTY_HINT_RANGE,"1,16384,1"), "set_hframes","get_hframes");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "region"), "set_region","is_region");
- ADD_PROPERTY( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "vframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_vframes", "get_vframes");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "hframes", PROPERTY_HINT_RANGE, "1,16384,1"), "set_hframes", "get_hframes");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "region"), "set_region", "is_region");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
ADD_SIGNAL(MethodInfo("frame_changed"));
-
}
Sprite3D::Sprite3D() {
-
- region=false;
- frame=0;
- vframes=1;
- hframes=1;
-
+ region = false;
+ frame = 0;
+ vframes = 1;
+ hframes = 1;
}
////////////////////////////////////////
@@ -853,22 +808,18 @@ AnimatedSprite3D::AnimatedSprite3D() {
frame=0;
}
-
-
#endif
-
void AnimatedSprite3D::_draw() {
RID immediate = get_immediate();
VS::get_singleton()->immediate_clear(immediate);
-
if (frames.is_null()) {
return;
}
- if (frame<0) {
+ if (frame < 0) {
return;
}
@@ -876,195 +827,185 @@ void AnimatedSprite3D::_draw() {
return;
}
-
- Ref<Texture> texture = frames->get_frame(animation,frame);
+ Ref<Texture> texture = frames->get_frame(animation, frame);
if (!texture.is_valid())
return; //no texuture no life
Vector2 tsize = texture->get_size();
- if (tsize.x==0 || tsize.y==0)
+ if (tsize.x == 0 || tsize.y == 0)
return;
- Size2i s=tsize;
+ Size2i s = tsize;
Rect2i src_rect;
- src_rect.size=s;
+ src_rect.size = s;
- Point2i ofs=get_offset();
+ Point2i ofs = get_offset();
if (is_centered())
- ofs-=s/2;
-
- Rect2i dst_rect(ofs,s);
+ ofs -= s / 2;
+ Rect2i dst_rect(ofs, s);
Rect2 final_rect;
Rect2 final_src_rect;
- if (!texture->get_rect_region(dst_rect,src_rect,final_rect,final_src_rect))
+ if (!texture->get_rect_region(dst_rect, src_rect, final_rect, final_src_rect))
return;
-
- if (final_rect.size.x==0 || final_rect.size.y==0)
+ if (final_rect.size.x == 0 || final_rect.size.y == 0)
return;
- Color color=_get_color_accum();
- color.a*=get_opacity();
+ Color color = _get_color_accum();
+ color.a *= get_opacity();
- float pixel_size=get_pixel_size();
+ float pixel_size = get_pixel_size();
- Vector2 vertices[4]={
+ Vector2 vertices[4] = {
- (final_rect.pos+Vector2(0,final_rect.size.y)) * pixel_size,
- (final_rect.pos+final_rect.size) * pixel_size,
- (final_rect.pos+Vector2(final_rect.size.x,0)) * pixel_size,
+ (final_rect.pos + Vector2(0, final_rect.size.y)) * pixel_size,
+ (final_rect.pos + final_rect.size) * pixel_size,
+ (final_rect.pos + Vector2(final_rect.size.x, 0)) * pixel_size,
final_rect.pos * pixel_size,
-
};
- Vector2 uvs[4]={
+ Vector2 uvs[4] = {
final_src_rect.pos / tsize,
- (final_src_rect.pos+Vector2(final_src_rect.size.x,0)) / tsize,
- (final_src_rect.pos+final_src_rect.size) / tsize,
- (final_src_rect.pos+Vector2(0,final_src_rect.size.y)) / tsize,
+ (final_src_rect.pos + Vector2(final_src_rect.size.x, 0)) / tsize,
+ (final_src_rect.pos + final_src_rect.size) / tsize,
+ (final_src_rect.pos + Vector2(0, final_src_rect.size.y)) / tsize,
};
if (is_flipped_h()) {
- SWAP(uvs[0],uvs[1]);
- SWAP(uvs[2],uvs[3]);
+ SWAP(uvs[0], uvs[1]);
+ SWAP(uvs[2], uvs[3]);
}
if (is_flipped_v()) {
- SWAP(uvs[0],uvs[3]);
- SWAP(uvs[1],uvs[2]);
+ SWAP(uvs[0], uvs[3]);
+ SWAP(uvs[1], uvs[2]);
}
-
Vector3 normal;
int axis = get_axis();
- normal[axis]=1.0;
+ normal[axis] = 1.0;
- RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED),get_draw_flag(FLAG_TRANSPARENT),get_alpha_cut_mode()==ALPHA_CUT_DISCARD,get_alpha_cut_mode()==ALPHA_CUT_OPAQUE_PREPASS);
- VS::get_singleton()->immediate_set_material(immediate,mat);
+ RID mat = VS::get_singleton()->material_2d_get(get_draw_flag(FLAG_SHADED), get_draw_flag(FLAG_TRANSPARENT), get_alpha_cut_mode() == ALPHA_CUT_DISCARD, get_alpha_cut_mode() == ALPHA_CUT_OPAQUE_PREPASS);
+ VS::get_singleton()->immediate_set_material(immediate, mat);
- VS::get_singleton()->immediate_begin(immediate,VS::PRIMITIVE_TRIANGLE_FAN,texture->get_rid());
+ VS::get_singleton()->immediate_begin(immediate, VS::PRIMITIVE_TRIANGLE_FAN, texture->get_rid());
int x_axis = ((axis + 1) % 3);
int y_axis = ((axis + 2) % 3);
- if (axis!=Vector3::AXIS_Z) {
- SWAP(x_axis,y_axis);
+ if (axis != Vector3::AXIS_Z) {
+ SWAP(x_axis, y_axis);
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
//uvs[i] = Vector2(1.0,1.0)-uvs[i];
//SWAP(vertices[i].x,vertices[i].y);
- if (axis==Vector3::AXIS_Y) {
- vertices[i].y = - vertices[i].y;
- } else if (axis==Vector3::AXIS_X) {
- vertices[i].x = - vertices[i].x;
+ if (axis == Vector3::AXIS_Y) {
+ vertices[i].y = -vertices[i].y;
+ } else if (axis == Vector3::AXIS_X) {
+ vertices[i].x = -vertices[i].x;
}
}
}
Rect3 aabb;
- for(int i=0;i<4;i++) {
- VS::get_singleton()->immediate_normal(immediate,normal);
- VS::get_singleton()->immediate_color(immediate,color);
- VS::get_singleton()->immediate_uv(immediate,uvs[i]);
+ for (int i = 0; i < 4; i++) {
+ VS::get_singleton()->immediate_normal(immediate, normal);
+ VS::get_singleton()->immediate_color(immediate, color);
+ VS::get_singleton()->immediate_uv(immediate, uvs[i]);
Vector3 vtx;
- vtx[x_axis]=vertices[i][0];
- vtx[y_axis]=vertices[i][1];
- VS::get_singleton()->immediate_vertex(immediate,vtx);
- if (i==0) {
- aabb.pos=vtx;
- aabb.size=Vector3();
+ vtx[x_axis] = vertices[i][0];
+ vtx[y_axis] = vertices[i][1];
+ VS::get_singleton()->immediate_vertex(immediate, vtx);
+ if (i == 0) {
+ aabb.pos = vtx;
+ aabb.size = Vector3();
} else {
aabb.expand_to(vtx);
}
}
set_aabb(aabb);
VS::get_singleton()->immediate_end(immediate);
-
}
-
-
-void AnimatedSprite3D::_validate_property(PropertyInfo& property) const {
+void AnimatedSprite3D::_validate_property(PropertyInfo &property) const {
if (!frames.is_valid())
return;
- if (property.name=="animation") {
+ if (property.name == "animation") {
- property.hint=PROPERTY_HINT_ENUM;
+ property.hint = PROPERTY_HINT_ENUM;
List<StringName> names;
frames->get_animation_list(&names);
names.sort_custom<StringName::AlphCompare>();
- bool current_found=false;
+ bool current_found = false;
- for (List<StringName>::Element *E=names.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
if (E->prev()) {
- property.hint_string+=",";
+ property.hint_string += ",";
}
- property.hint_string+=String(E->get());
- if (animation==E->get()) {
- current_found=true;
+ property.hint_string += String(E->get());
+ if (animation == E->get()) {
+ current_found = true;
}
}
if (!current_found) {
- if (property.hint_string==String()) {
- property.hint_string=String(animation);
+ if (property.hint_string == String()) {
+ property.hint_string = String(animation);
} else {
- property.hint_string=String(animation)+","+property.hint_string;
+ property.hint_string = String(animation) + "," + property.hint_string;
}
}
}
+ if (property.name == "frame") {
- if (property.name=="frame") {
-
- property.hint=PROPERTY_HINT_RANGE;
+ property.hint = PROPERTY_HINT_RANGE;
if (frames->has_animation(animation)) {
- property.hint_string="0,"+itos(frames->get_frame_count(animation)-1)+",1";
+ property.hint_string = "0," + itos(frames->get_frame_count(animation) - 1) + ",1";
} else {
- property.hint_string="0,0,0";
+ property.hint_string = "0,0,0";
}
}
-
}
void AnimatedSprite3D::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_INTERNAL_PROCESS: {
if (frames.is_null())
return;
if (!frames->has_animation(animation))
return;
- if (frame<0)
+ if (frame < 0)
return;
float speed = frames->get_animation_speed(animation);
- if (speed==0)
+ if (speed == 0)
return; //do nothing
float remaining = get_process_delta_time();
- while(remaining) {
+ while (remaining) {
- if (timeout<=0) {
+ if (timeout <= 0) {
- timeout=1.0/speed;
+ timeout = 1.0 / speed;
int fc = frames->get_frame_count(animation);
- if (frame>=fc-1) {
+ if (frame >= fc - 1) {
if (frames->get_animation_loop(animation)) {
- frame=0;
+ frame = 0;
} else {
- frame=fc-1;
+ frame = fc - 1;
}
} else {
frame++;
@@ -1074,9 +1015,9 @@ void AnimatedSprite3D::_notification(int p_what) {
_change_notify("frame");
}
- float to_process = MIN(timeout,remaining);
- remaining-=to_process;
- timeout-=to_process;
+ float to_process = MIN(timeout, remaining);
+ remaining -= to_process;
+ timeout -= to_process;
}
} break;
#if 0
@@ -1137,30 +1078,26 @@ void AnimatedSprite3D::_notification(int p_what) {
} break;
#endif
}
-
}
void AnimatedSprite3D::set_sprite_frames(const Ref<SpriteFrames> &p_frames) {
if (frames.is_valid())
- frames->disconnect("changed",this,"_res_changed");
- frames=p_frames;
+ frames->disconnect("changed", this, "_res_changed");
+ frames = p_frames;
if (frames.is_valid())
- frames->connect("changed",this,"_res_changed");
+ frames->connect("changed", this, "_res_changed");
if (!frames.is_valid()) {
- frame=0;
+ frame = 0;
} else {
set_frame(frame);
}
-
-
_change_notify();
_reset_timeout();
_queue_update();
update_configuration_warning();
-
}
Ref<SpriteFrames> AnimatedSprite3D::get_sprite_frames() const {
@@ -1176,55 +1113,48 @@ void AnimatedSprite3D::set_frame(int p_frame) {
if (frames->has_animation(animation)) {
int limit = frames->get_frame_count(animation);
- if (p_frame>=limit)
- p_frame=limit-1;
-
+ if (p_frame >= limit)
+ p_frame = limit - 1;
}
- if (p_frame<0)
- p_frame=0;
+ if (p_frame < 0)
+ p_frame = 0;
-
- if (frame==p_frame)
+ if (frame == p_frame)
return;
- frame=p_frame;
+ frame = p_frame;
_reset_timeout();
_queue_update();
_change_notify("frame");
emit_signal(SceneStringNames::get_singleton()->frame_changed);
-
-
-
}
int AnimatedSprite3D::get_frame() const {
return frame;
}
-
-
Rect2 AnimatedSprite3D::get_item_rect() const {
- if (!frames.is_valid() || !frames->has_animation(animation) || frame<0 || frame>=frames->get_frame_count(animation)) {
- return Rect2(0,0,1,1);
+ if (!frames.is_valid() || !frames->has_animation(animation) || frame < 0 || frame >= frames->get_frame_count(animation)) {
+ return Rect2(0, 0, 1, 1);
}
Ref<Texture> t;
if (animation)
- t = frames->get_frame(animation,frame);
+ t = frames->get_frame(animation, frame);
if (t.is_null())
- return Rect2(0,0,1,1);
+ return Rect2(0, 0, 1, 1);
Size2i s = t->get_size();
- Point2 ofs=offset;
+ Point2 ofs = offset;
if (centered)
- ofs-=s/2;
+ ofs -= s / 2;
- if (s==Size2(0,0))
- s=Size2(1,1);
+ if (s == Size2(0, 0))
+ s = Size2(1, 1);
- return Rect2(ofs,s);
+ return Rect2(ofs, s);
}
void AnimatedSprite3D::_res_changed() {
@@ -1237,9 +1167,9 @@ void AnimatedSprite3D::_res_changed() {
void AnimatedSprite3D::_set_playing(bool p_playing) {
- if (playing==p_playing)
+ if (playing == p_playing)
return;
- playing=p_playing;
+ playing = p_playing;
_reset_timeout();
set_process_internal(playing);
}
@@ -1249,14 +1179,14 @@ bool AnimatedSprite3D::_is_playing() const {
return playing;
}
-void AnimatedSprite3D::play(const StringName& p_animation) {
+void AnimatedSprite3D::play(const StringName &p_animation) {
if (p_animation)
set_animation(p_animation);
_set_playing(true);
}
-void AnimatedSprite3D::stop(){
+void AnimatedSprite3D::stop() {
_set_playing(false);
}
@@ -1273,29 +1203,28 @@ void AnimatedSprite3D::_reset_timeout() {
if (frames.is_valid() && frames->has_animation(animation)) {
float speed = frames->get_animation_speed(animation);
- if (speed>0) {
- timeout=1.0/speed;
+ if (speed > 0) {
+ timeout = 1.0 / speed;
} else {
- timeout=0;
+ timeout = 0;
}
} else {
- timeout=0;
+ timeout = 0;
}
-
}
-void AnimatedSprite3D::set_animation(const StringName& p_animation){
+void AnimatedSprite3D::set_animation(const StringName &p_animation) {
- if (animation==p_animation)
+ if (animation == p_animation)
return;
- animation=p_animation;
+ animation = p_animation;
_reset_timeout();
set_frame(0);
_change_notify();
_queue_update();
}
-StringName AnimatedSprite3D::get_animation() const{
+StringName AnimatedSprite3D::get_animation() const {
return animation;
}
@@ -1311,44 +1240,36 @@ String AnimatedSprite3D::get_configuration_warning() const {
void AnimatedSprite3D::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_sprite_frames", "sprite_frames:SpriteFrames"), &AnimatedSprite3D::set_sprite_frames);
+ ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"), &AnimatedSprite3D::get_sprite_frames);
- ClassDB::bind_method(D_METHOD("set_sprite_frames","sprite_frames:SpriteFrames"),&AnimatedSprite3D::set_sprite_frames);
- ClassDB::bind_method(D_METHOD("get_sprite_frames:SpriteFrames"),&AnimatedSprite3D::get_sprite_frames);
+ ClassDB::bind_method(D_METHOD("set_animation", "animation"), &AnimatedSprite3D::set_animation);
+ ClassDB::bind_method(D_METHOD("get_animation"), &AnimatedSprite3D::get_animation);
- ClassDB::bind_method(D_METHOD("set_animation","animation"),&AnimatedSprite3D::set_animation);
- ClassDB::bind_method(D_METHOD("get_animation"),&AnimatedSprite3D::get_animation);
+ ClassDB::bind_method(D_METHOD("_set_playing", "playing"), &AnimatedSprite3D::_set_playing);
+ ClassDB::bind_method(D_METHOD("_is_playing"), &AnimatedSprite3D::_is_playing);
- ClassDB::bind_method(D_METHOD("_set_playing","playing"),&AnimatedSprite3D::_set_playing);
- ClassDB::bind_method(D_METHOD("_is_playing"),&AnimatedSprite3D::_is_playing);
+ ClassDB::bind_method(D_METHOD("play", "anim"), &AnimatedSprite3D::play, DEFVAL(StringName()));
+ ClassDB::bind_method(D_METHOD("stop"), &AnimatedSprite3D::stop);
+ ClassDB::bind_method(D_METHOD("is_playing"), &AnimatedSprite3D::is_playing);
- ClassDB::bind_method(D_METHOD("play","anim"),&AnimatedSprite3D::play,DEFVAL(StringName()));
- ClassDB::bind_method(D_METHOD("stop"),&AnimatedSprite3D::stop);
- ClassDB::bind_method(D_METHOD("is_playing"),&AnimatedSprite3D::is_playing);
+ ClassDB::bind_method(D_METHOD("set_frame", "frame"), &AnimatedSprite3D::set_frame);
+ ClassDB::bind_method(D_METHOD("get_frame"), &AnimatedSprite3D::get_frame);
-
- ClassDB::bind_method(D_METHOD("set_frame","frame"),&AnimatedSprite3D::set_frame);
- ClassDB::bind_method(D_METHOD("get_frame"),&AnimatedSprite3D::get_frame);
-
- ClassDB::bind_method(D_METHOD("_res_changed"),&AnimatedSprite3D::_res_changed);
+ ClassDB::bind_method(D_METHOD("_res_changed"), &AnimatedSprite3D::_res_changed);
ADD_SIGNAL(MethodInfo("frame_changed"));
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "frames",PROPERTY_HINT_RESOURCE_TYPE,"SpriteFrames"), "set_sprite_frames","get_sprite_frames");
- ADD_PROPERTY( PropertyInfo( Variant::STRING, "animation"), "set_animation","get_animation");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "frame",PROPERTY_HINT_SPRITE_FRAME), "set_frame","get_frame");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "playing"), "_set_playing","_is_playing");
-
-
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "frames", PROPERTY_HINT_RESOURCE_TYPE, "SpriteFrames"), "set_sprite_frames", "get_sprite_frames");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "animation"), "set_animation", "get_animation");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "frame", PROPERTY_HINT_SPRITE_FRAME), "set_frame", "get_frame");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "playing"), "_set_playing", "_is_playing");
}
AnimatedSprite3D::AnimatedSprite3D() {
- frame=0;
- playing=false;
- animation="default";
- timeout=0;
-
-
+ frame = 0;
+ playing = false;
+ animation = "default";
+ timeout = 0;
}
-
-
diff --git a/scene/3d/sprite_3d.h b/scene/3d/sprite_3d.h
index a14ce40495..d1de4e1b88 100644
--- a/scene/3d/sprite_3d.h
+++ b/scene/3d/sprite_3d.h
@@ -29,15 +29,14 @@
#ifndef SPRITE_3D_H
#define SPRITE_3D_H
-#include "scene/3d/visual_instance.h"
#include "scene/2d/animated_sprite.h"
-
+#include "scene/3d/visual_instance.h"
class SpriteBase3D : public GeometryInstance {
- GDCLASS(SpriteBase3D,GeometryInstance);
-public:
+ GDCLASS(SpriteBase3D, GeometryInstance);
+public:
enum DrawFlags {
FLAG_TRANSPARENT,
FLAG_SHADED,
@@ -52,14 +51,12 @@ public:
};
private:
-
-
bool color_dirty;
Color color_accum;
SpriteBase3D *parent_sprite;
- List<SpriteBase3D*> children;
- List<SpriteBase3D*>::Element *pI;
+ List<SpriteBase3D *> children;
+ List<SpriteBase3D *>::Element *pI;
bool centered;
Point2 offset;
@@ -67,7 +64,6 @@ private:
bool hflip;
bool vflip;
-
Color modulate;
float opacity;
@@ -82,24 +78,22 @@ private:
bool pending_update;
void _im_update();
-
void _propagate_color_changed();
protected:
-
Color _get_color_accum();
void _notification(int p_what);
static void _bind_methods();
- virtual void _draw()=0;
- _FORCE_INLINE_ void set_aabb(const Rect3& p_aabb) { aabb=p_aabb; }
- _FORCE_INLINE_ RID& get_immediate() { return immediate; }
+ virtual void _draw() = 0;
+ _FORCE_INLINE_ void set_aabb(const Rect3 &p_aabb) { aabb = p_aabb; }
+ _FORCE_INLINE_ RID &get_immediate() { return immediate; }
void _queue_update();
-public:
+public:
void set_centered(bool p_center);
bool is_centered() const;
- void set_offset(const Point2& p_offset);
+ void set_offset(const Point2 &p_offset);
Point2 get_offset() const;
void set_flip_h(bool p_flip);
@@ -111,10 +105,10 @@ public:
void set_region(bool p_region);
bool is_region() const;
- void set_region_rect(const Rect2& p_region_rect);
+ void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
- void set_modulate(const Color& p_color);
+ void set_modulate(const Color &p_color);
Color get_modulate() const;
void set_opacity(float p_amount);
@@ -126,13 +120,13 @@ public:
void set_axis(Vector3::Axis p_amount);
Vector3::Axis get_axis() const;
- void set_draw_flag(DrawFlags p_flag,bool p_enable);
+ void set_draw_flag(DrawFlags p_flag, bool p_enable);
bool get_draw_flag(DrawFlags p_flag) const;
void set_alpha_cut_mode(AlphaCutMode p_mode);
AlphaCutMode get_alpha_cut_mode() const;
- virtual Rect2 get_item_rect() const=0;
+ virtual Rect2 get_item_rect() const = 0;
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
@@ -141,13 +135,11 @@ public:
~SpriteBase3D();
};
-
class Sprite3D : public SpriteBase3D {
- GDCLASS(Sprite3D,SpriteBase3D);
+ GDCLASS(Sprite3D, SpriteBase3D);
Ref<Texture> texture;
-
bool region;
Rect2 region_rect;
@@ -155,22 +147,21 @@ class Sprite3D : public SpriteBase3D {
int vframes;
int hframes;
+
protected:
virtual void _draw();
static void _bind_methods();
- virtual void _validate_property(PropertyInfo& property) const;
-public:
-
+ virtual void _validate_property(PropertyInfo &property) const;
-
- void set_texture(const Ref<Texture>& p_texture);
+public:
+ void set_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_texture() const;
void set_region(bool p_region);
bool is_region() const;
- void set_region_rect(const Rect2& p_region_rect);
+ void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
void set_frame(int p_frame);
@@ -219,12 +210,9 @@ public:
};
#endif
-
-
-
class AnimatedSprite3D : public SpriteBase3D {
- GDCLASS(AnimatedSprite3D,SpriteBase3D);
+ GDCLASS(AnimatedSprite3D, SpriteBase3D);
Ref<SpriteFrames> frames;
bool playing;
@@ -247,39 +235,32 @@ class AnimatedSprite3D : public SpriteBase3D {
void _set_playing(bool p_playing);
bool _is_playing() const;
-
protected:
-
virtual void _draw();
static void _bind_methods();
void _notification(int p_what);
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
-
-
void set_sprite_frames(const Ref<SpriteFrames> &p_frames);
Ref<SpriteFrames> get_sprite_frames() const;
- void play(const StringName& p_animation=StringName());
+ void play(const StringName &p_animation = StringName());
void stop();
bool is_playing() const;
- void set_animation(const StringName& p_animation);
+ void set_animation(const StringName &p_animation);
StringName get_animation() const;
void set_frame(int p_frame);
int get_frame() const;
-
virtual Rect2 get_item_rect() const;
virtual String get_configuration_warning() const;
AnimatedSprite3D();
};
-
VARIANT_ENUM_CAST(SpriteBase3D::DrawFlags);
VARIANT_ENUM_CAST(SpriteBase3D::AlphaCutMode);
#endif // SPRITE_3D_H
diff --git a/scene/3d/test_cube.cpp b/scene/3d/test_cube.cpp
index c52e596032..bab1d1e1c8 100644
--- a/scene/3d/test_cube.cpp
+++ b/scene/3d/test_cube.cpp
@@ -29,25 +29,19 @@
#include "test_cube.h"
#include "servers/visual_server.h"
-
-
Rect3 TestCube::get_aabb() const {
- return Rect3( Vector3(-1,-1,-1), Vector3(2, 2, 2 ) );
+ return Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2));
}
PoolVector<Face3> TestCube::get_faces(uint32_t p_usage_flags) const {
return PoolVector<Face3>();
}
-
TestCube::TestCube() {
set_base(VisualServer::get_singleton()->get_test_cube());
}
-
TestCube::~TestCube() {
}
-
-
diff --git a/scene/3d/test_cube.h b/scene/3d/test_cube.h
index 4860bacd8d..d03bea7b68 100644
--- a/scene/3d/test_cube.h
+++ b/scene/3d/test_cube.h
@@ -29,29 +29,24 @@
#ifndef TEST_CUBE_H
#define TEST_CUBE_H
-
-#include "scene/3d/visual_instance.h"
#include "rid.h"
-
+#include "scene/3d/visual_instance.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class TestCube : public GeometryInstance {
- GDCLASS( TestCube, GeometryInstance );
+ GDCLASS(TestCube, GeometryInstance);
RID instance;
-
public:
-
virtual Rect3 get_aabb() const;
virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const;
TestCube();
~TestCube();
-
};
#endif
diff --git a/scene/3d/vehicle_body.cpp b/scene/3d/vehicle_body.cpp
index 4b32c62d14..4a647fe682 100644
--- a/scene/3d/vehicle_body.cpp
+++ b/scene/3d/vehicle_body.cpp
@@ -30,78 +30,70 @@
#define ROLLING_INFLUENCE_FIX
-class btVehicleJacobianEntry
-{
+class btVehicleJacobianEntry {
public:
-
- Vector3 m_linearJointAxis;
- Vector3 m_aJ;
- Vector3 m_bJ;
- Vector3 m_0MinvJt;
- Vector3 m_1MinvJt;
+ Vector3 m_linearJointAxis;
+ Vector3 m_aJ;
+ Vector3 m_bJ;
+ Vector3 m_0MinvJt;
+ Vector3 m_1MinvJt;
//Optimization: can be stored in the w/last component of one of the vectors
- real_t m_Adiag;
+ real_t m_Adiag;
real_t getDiagonal() const { return m_Adiag; }
- btVehicleJacobianEntry() {};
- //constraint between two different rigidbodies
- btVehicleJacobianEntry(
- const Basis& world2A,
- const Basis& world2B,
- const Vector3& rel_pos1,
- const Vector3& rel_pos2,
- const Vector3& jointAxis,
- const Vector3& inertiaInvA,
+ btVehicleJacobianEntry(){};
+ //constraint between two different rigidbodies
+ btVehicleJacobianEntry(
+ const Basis &world2A,
+ const Basis &world2B,
+ const Vector3 &rel_pos1,
+ const Vector3 &rel_pos2,
+ const Vector3 &jointAxis,
+ const Vector3 &inertiaInvA,
const real_t massInvA,
- const Vector3& inertiaInvB,
+ const Vector3 &inertiaInvB,
const real_t massInvB)
- :m_linearJointAxis(jointAxis)
- {
- m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis));
- m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis));
- m_0MinvJt = inertiaInvA * m_aJ;
- m_1MinvJt = inertiaInvB * m_bJ;
- m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
-
- //btAssert(m_Adiag > real_t(0.0));
- }
-
- real_t getRelativeVelocity(const Vector3& linvelA,const Vector3& angvelA,const Vector3& linvelB,const Vector3& angvelB)
- {
- Vector3 linrel = linvelA - linvelB;
- Vector3 angvela = angvelA * m_aJ;
- Vector3 angvelb = angvelB * m_bJ;
- linrel *= m_linearJointAxis;
- angvela += angvelb;
- angvela += linrel;
- real_t rel_vel2 = angvela[0]+angvela[1]+angvela[2];
- return rel_vel2 + CMP_EPSILON;
- }
-
+ : m_linearJointAxis(jointAxis) {
+ m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis));
+ m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis));
+ m_0MinvJt = inertiaInvA * m_aJ;
+ m_1MinvJt = inertiaInvB * m_bJ;
+ m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
+
+ //btAssert(m_Adiag > real_t(0.0));
+ }
+ real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) {
+ Vector3 linrel = linvelA - linvelB;
+ Vector3 angvela = angvelA * m_aJ;
+ Vector3 angvelb = angvelB * m_bJ;
+ linrel *= m_linearJointAxis;
+ angvela += angvelb;
+ angvela += linrel;
+ real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2];
+ return rel_vel2 + CMP_EPSILON;
+ }
};
void VehicleWheel::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
if (!get_parent())
return;
VehicleBody *cb = get_parent()->cast_to<VehicleBody>();
if (!cb)
return;
- body=cb;
- local_xform=get_transform();
+ body = cb;
+ local_xform = get_transform();
cb->wheels.push_back(this);
m_chassisConnectionPointCS = get_transform().origin;
m_wheelDirectionCS = -get_transform().basis.get_axis(Vector3::AXIS_Y).normalized();
m_wheelAxleCS = get_transform().basis.get_axis(Vector3::AXIS_X).normalized();
-
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (!get_parent())
return;
@@ -109,34 +101,27 @@ void VehicleWheel::_notification(int p_what) {
if (!cb)
return;
cb->wheels.erase(this);
- body=NULL;
+ body = NULL;
}
-
}
-
void VehicleWheel::_update(PhysicsDirectBodyState *s) {
-
-
if (m_raycastInfo.m_isInContact)
{
- real_t project= m_raycastInfo.m_contactNormalWS.dot( m_raycastInfo.m_wheelDirectionWS );
- Vector3 chassis_velocity_at_contactPoint;
+ real_t project = m_raycastInfo.m_contactNormalWS.dot(m_raycastInfo.m_wheelDirectionWS);
+ Vector3 chassis_velocity_at_contactPoint;
Vector3 relpos = m_raycastInfo.m_contactPointWS - s->get_transform().origin;
chassis_velocity_at_contactPoint = s->get_linear_velocity() +
- (s->get_angular_velocity()).cross(relpos);// * mPos);
+ (s->get_angular_velocity()).cross(relpos); // * mPos);
- real_t projVel = m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint );
- if ( project >= real_t(-0.1))
- {
+ real_t projVel = m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
+ if (project >= real_t(-0.1)) {
m_suspensionRelativeVelocity = real_t(0.0);
m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
- }
- else
- {
+ } else {
real_t inv = real_t(-1.) / project;
m_suspensionRelativeVelocity = projVel * inv;
m_clippedInvContactDotSuspension = inv;
@@ -144,7 +129,7 @@ void VehicleWheel::_update(PhysicsDirectBodyState *s) {
}
- else // Not in contact : position wheel in a nice (rest length) position
+ else // Not in contact : position wheel in a nice (rest length) position
{
m_raycastInfo.m_suspensionLength = m_suspensionRestLength;
m_suspensionRelativeVelocity = real_t(0.0);
@@ -155,160 +140,150 @@ void VehicleWheel::_update(PhysicsDirectBodyState *s) {
void VehicleWheel::set_radius(float p_radius) {
- m_wheelRadius=p_radius;
+ m_wheelRadius = p_radius;
update_gizmo();
}
-float VehicleWheel::get_radius() const{
+float VehicleWheel::get_radius() const {
return m_wheelRadius;
}
-void VehicleWheel::set_suspension_rest_length(float p_length){
+void VehicleWheel::set_suspension_rest_length(float p_length) {
- m_suspensionRestLength=p_length;
+ m_suspensionRestLength = p_length;
update_gizmo();
}
-float VehicleWheel::get_suspension_rest_length() const{
+float VehicleWheel::get_suspension_rest_length() const {
return m_suspensionRestLength;
}
-void VehicleWheel::set_suspension_travel(float p_length){
+void VehicleWheel::set_suspension_travel(float p_length) {
- m_maxSuspensionTravelCm=p_length/0.01;
+ m_maxSuspensionTravelCm = p_length / 0.01;
}
-float VehicleWheel::get_suspension_travel() const{
+float VehicleWheel::get_suspension_travel() const {
- return m_maxSuspensionTravelCm*0.01;
+ return m_maxSuspensionTravelCm * 0.01;
}
-void VehicleWheel::set_suspension_stiffness(float p_value){
+void VehicleWheel::set_suspension_stiffness(float p_value) {
- m_suspensionStiffness=p_value;
+ m_suspensionStiffness = p_value;
}
-float VehicleWheel::get_suspension_stiffness() const{
+float VehicleWheel::get_suspension_stiffness() const {
return m_suspensionStiffness;
}
-void VehicleWheel::set_suspension_max_force(float p_value){
+void VehicleWheel::set_suspension_max_force(float p_value) {
- m_maxSuspensionForce=p_value;
+ m_maxSuspensionForce = p_value;
}
-float VehicleWheel::get_suspension_max_force() const{
+float VehicleWheel::get_suspension_max_force() const {
return m_maxSuspensionForce;
}
-void VehicleWheel::set_damping_compression(float p_value){
+void VehicleWheel::set_damping_compression(float p_value) {
- m_wheelsDampingCompression=p_value;
+ m_wheelsDampingCompression = p_value;
}
-float VehicleWheel::get_damping_compression() const{
+float VehicleWheel::get_damping_compression() const {
return m_wheelsDampingCompression;
}
-void VehicleWheel::set_damping_relaxation(float p_value){
+void VehicleWheel::set_damping_relaxation(float p_value) {
- m_wheelsDampingRelaxation=p_value;
+ m_wheelsDampingRelaxation = p_value;
}
-float VehicleWheel::get_damping_relaxation() const{
+float VehicleWheel::get_damping_relaxation() const {
return m_wheelsDampingRelaxation;
}
void VehicleWheel::set_friction_slip(float p_value) {
- m_frictionSlip=p_value;
+ m_frictionSlip = p_value;
}
-float VehicleWheel::get_friction_slip() const{
+float VehicleWheel::get_friction_slip() const {
return m_frictionSlip;
}
-
void VehicleWheel::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_radius", "length"), &VehicleWheel::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &VehicleWheel::get_radius);
- ClassDB::bind_method(D_METHOD("set_radius","length"),&VehicleWheel::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&VehicleWheel::get_radius);
-
- ClassDB::bind_method(D_METHOD("set_suspension_rest_length","length"),&VehicleWheel::set_suspension_rest_length);
- ClassDB::bind_method(D_METHOD("get_suspension_rest_length"),&VehicleWheel::get_suspension_rest_length);
-
- ClassDB::bind_method(D_METHOD("set_suspension_travel","length"),&VehicleWheel::set_suspension_travel);
- ClassDB::bind_method(D_METHOD("get_suspension_travel"),&VehicleWheel::get_suspension_travel);
-
- ClassDB::bind_method(D_METHOD("set_suspension_stiffness","length"),&VehicleWheel::set_suspension_stiffness);
- ClassDB::bind_method(D_METHOD("get_suspension_stiffness"),&VehicleWheel::get_suspension_stiffness);
-
- ClassDB::bind_method(D_METHOD("set_suspension_max_force","length"),&VehicleWheel::set_suspension_max_force);
- ClassDB::bind_method(D_METHOD("get_suspension_max_force"),&VehicleWheel::get_suspension_max_force);
+ ClassDB::bind_method(D_METHOD("set_suspension_rest_length", "length"), &VehicleWheel::set_suspension_rest_length);
+ ClassDB::bind_method(D_METHOD("get_suspension_rest_length"), &VehicleWheel::get_suspension_rest_length);
+ ClassDB::bind_method(D_METHOD("set_suspension_travel", "length"), &VehicleWheel::set_suspension_travel);
+ ClassDB::bind_method(D_METHOD("get_suspension_travel"), &VehicleWheel::get_suspension_travel);
- ClassDB::bind_method(D_METHOD("set_damping_compression","length"),&VehicleWheel::set_damping_compression);
- ClassDB::bind_method(D_METHOD("get_damping_compression"),&VehicleWheel::get_damping_compression);
+ ClassDB::bind_method(D_METHOD("set_suspension_stiffness", "length"), &VehicleWheel::set_suspension_stiffness);
+ ClassDB::bind_method(D_METHOD("get_suspension_stiffness"), &VehicleWheel::get_suspension_stiffness);
- ClassDB::bind_method(D_METHOD("set_damping_relaxation","length"),&VehicleWheel::set_damping_relaxation);
- ClassDB::bind_method(D_METHOD("get_damping_relaxation"),&VehicleWheel::get_damping_relaxation);
+ ClassDB::bind_method(D_METHOD("set_suspension_max_force", "length"), &VehicleWheel::set_suspension_max_force);
+ ClassDB::bind_method(D_METHOD("get_suspension_max_force"), &VehicleWheel::get_suspension_max_force);
- ClassDB::bind_method(D_METHOD("set_use_as_traction","enable"),&VehicleWheel::set_use_as_traction);
- ClassDB::bind_method(D_METHOD("is_used_as_traction"),&VehicleWheel::is_used_as_traction);
+ ClassDB::bind_method(D_METHOD("set_damping_compression", "length"), &VehicleWheel::set_damping_compression);
+ ClassDB::bind_method(D_METHOD("get_damping_compression"), &VehicleWheel::get_damping_compression);
- ClassDB::bind_method(D_METHOD("set_use_as_steering","enable"),&VehicleWheel::set_use_as_steering);
- ClassDB::bind_method(D_METHOD("is_used_as_steering"),&VehicleWheel::is_used_as_steering);
+ ClassDB::bind_method(D_METHOD("set_damping_relaxation", "length"), &VehicleWheel::set_damping_relaxation);
+ ClassDB::bind_method(D_METHOD("get_damping_relaxation"), &VehicleWheel::get_damping_relaxation);
- ClassDB::bind_method(D_METHOD("set_friction_slip","length"),&VehicleWheel::set_friction_slip);
- ClassDB::bind_method(D_METHOD("get_friction_slip"),&VehicleWheel::get_friction_slip);
+ ClassDB::bind_method(D_METHOD("set_use_as_traction", "enable"), &VehicleWheel::set_use_as_traction);
+ ClassDB::bind_method(D_METHOD("is_used_as_traction"), &VehicleWheel::is_used_as_traction);
+ ClassDB::bind_method(D_METHOD("set_use_as_steering", "enable"), &VehicleWheel::set_use_as_steering);
+ ClassDB::bind_method(D_METHOD("is_used_as_steering"), &VehicleWheel::is_used_as_steering);
+ ClassDB::bind_method(D_METHOD("set_friction_slip", "length"), &VehicleWheel::set_friction_slip);
+ ClassDB::bind_method(D_METHOD("get_friction_slip"), &VehicleWheel::get_friction_slip);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_as_traction"),"set_use_as_traction","is_used_as_traction");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_as_steering"),"set_use_as_steering","is_used_as_steering");
- ADD_GROUP("Wheel","wheel_");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_radius"),"set_radius","get_radius");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_rest_length"),"set_suspension_rest_length","get_suspension_rest_length");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wheel_friction_slip"),"set_friction_slip","get_friction_slip");
- ADD_GROUP("Suspension","suspension_");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_travel"),"set_suspension_travel","get_suspension_travel");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_stiffness"),"set_suspension_stiffness","get_suspension_stiffness");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"suspension_max_force"),"set_suspension_max_force","get_suspension_max_force");
- ADD_GROUP("Damping","damping_");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping_compression"),"set_damping_compression","get_damping_compression");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping_relaxation"),"set_damping_relaxation","get_damping_relaxation");
-
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_traction"), "set_use_as_traction", "is_used_as_traction");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_as_steering"), "set_use_as_steering", "is_used_as_steering");
+ ADD_GROUP("Wheel", "wheel_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_radius"), "set_radius", "get_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_rest_length"), "set_suspension_rest_length", "get_suspension_rest_length");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wheel_friction_slip"), "set_friction_slip", "get_friction_slip");
+ ADD_GROUP("Suspension", "suspension_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_travel"), "set_suspension_travel", "get_suspension_travel");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_stiffness"), "set_suspension_stiffness", "get_suspension_stiffness");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "suspension_max_force"), "set_suspension_max_force", "get_suspension_max_force");
+ ADD_GROUP("Damping", "damping_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_compression"), "set_damping_compression", "get_damping_compression");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping_relaxation"), "set_damping_relaxation", "get_damping_relaxation");
}
-
void VehicleWheel::set_use_as_traction(bool p_enable) {
- engine_traction=p_enable;
+ engine_traction = p_enable;
}
-bool VehicleWheel::is_used_as_traction() const{
+bool VehicleWheel::is_used_as_traction() const {
return engine_traction;
}
+void VehicleWheel::set_use_as_steering(bool p_enabled) {
-void VehicleWheel::set_use_as_steering(bool p_enabled){
-
- steers=p_enabled;
+ steers = p_enabled;
}
-bool VehicleWheel::is_used_as_steering() const{
+bool VehicleWheel::is_used_as_steering() const {
return steers;
}
-
VehicleWheel::VehicleWheel() {
-
- steers=false;
- engine_traction=false;
+ steers = false;
+ engine_traction = false;
m_steering = real_t(0.);
//m_engineForce = real_t(0.);
@@ -318,7 +293,7 @@ VehicleWheel::VehicleWheel() {
m_rollInfluence = real_t(0.1);
m_suspensionRestLength = 0.15;
- m_wheelRadius = 0.5;//0.28;
+ m_wheelRadius = 0.5; //0.28;
m_suspensionStiffness = 5.88;
m_wheelsDampingCompression = 0.83;
m_wheelsDampingRelaxation = 0.88;
@@ -327,15 +302,14 @@ VehicleWheel::VehicleWheel() {
m_maxSuspensionTravelCm = 500;
m_maxSuspensionForce = 6000;
- m_suspensionRelativeVelocity=0;
- m_clippedInvContactDotSuspension=1.0;
- m_raycastInfo.m_isInContact=false;
+ m_suspensionRelativeVelocity = 0;
+ m_clippedInvContactDotSuspension = 1.0;
+ m_raycastInfo.m_isInContact = false;
- body=NULL;
+ body = NULL;
}
-
-void VehicleBody::_update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBodyState *s) {
+void VehicleBody::_update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s) {
wheel.m_raycastInfo.m_isInContact = false;
@@ -346,31 +320,31 @@ void VehicleBody::_update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBody
}
*/
- wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform( wheel.m_chassisConnectionPointCS );
+ wheel.m_raycastInfo.m_hardPointWS = chassisTrans.xform(wheel.m_chassisConnectionPointCS);
//wheel.m_raycastInfo.m_hardPointWS+=s->get_linear_velocity()*s->get_step();
- wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform( wheel.m_wheelDirectionCS).normalized();
- wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform( wheel.m_wheelAxleCS ).normalized();
+ wheel.m_raycastInfo.m_wheelDirectionWS = chassisTrans.get_basis().xform(wheel.m_wheelDirectionCS).normalized();
+ wheel.m_raycastInfo.m_wheelAxleWS = chassisTrans.get_basis().xform(wheel.m_wheelAxleCS).normalized();
}
-void VehicleBody::_update_wheel(int p_idx,PhysicsDirectBodyState *s) {
+void VehicleBody::_update_wheel(int p_idx, PhysicsDirectBodyState *s) {
- VehicleWheel& wheel = *wheels[p_idx];
- _update_wheel_transform(wheel,s);
+ VehicleWheel &wheel = *wheels[p_idx];
+ _update_wheel_transform(wheel, s);
Vector3 up = -wheel.m_raycastInfo.m_wheelDirectionWS;
- const Vector3& right = wheel.m_raycastInfo.m_wheelAxleWS;
+ const Vector3 &right = wheel.m_raycastInfo.m_wheelAxleWS;
Vector3 fwd = up.cross(right);
fwd = fwd.normalized();
//up = right.cross(fwd);
//up.normalize();
//rotate around steering over de wheelAxleWS
- real_t steering = wheel.steers?m_steeringValue:0.0;
+ real_t steering = wheel.steers ? m_steeringValue : 0.0;
//print_line(itos(p_idx)+": "+rtos(steering));
- Basis steeringMat(up,steering);
+ Basis steeringMat(up, steering);
- Basis rotatingMat(right,-wheel.m_rotation);
+ Basis rotatingMat(right, -wheel.m_rotation);
/*
if (p_idx==1)
@@ -378,82 +352,69 @@ void VehicleBody::_update_wheel(int p_idx,PhysicsDirectBodyState *s) {
*/
Basis basis2(
- right[0],up[0],fwd[0],
- right[1],up[1],fwd[1],
- right[2],up[2],fwd[2]
- );
+ right[0], up[0], fwd[0],
+ right[1], up[1], fwd[1],
+ right[2], up[2], fwd[2]);
wheel.m_worldTransform.set_basis(steeringMat * rotatingMat * basis2);
//wheel.m_worldTransform.set_basis(basis2 * (steeringMat * rotatingMat));
wheel.m_worldTransform.set_origin(
- wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength
- );
-
+ wheel.m_raycastInfo.m_hardPointWS + wheel.m_raycastInfo.m_wheelDirectionWS * wheel.m_raycastInfo.m_suspensionLength);
}
+real_t VehicleBody::_ray_cast(int p_idx, PhysicsDirectBodyState *s) {
-real_t VehicleBody::_ray_cast(int p_idx,PhysicsDirectBodyState *s) {
-
-
- VehicleWheel& wheel = *wheels[p_idx];
-
- _update_wheel_transform(wheel,s);
+ VehicleWheel &wheel = *wheels[p_idx];
+ _update_wheel_transform(wheel, s);
real_t depth = -1;
- real_t raylen = wheel.m_suspensionRestLength+wheel.m_wheelRadius;
+ real_t raylen = wheel.m_suspensionRestLength + wheel.m_wheelRadius;
Vector3 rayvector = wheel.m_raycastInfo.m_wheelDirectionWS * (raylen);
Vector3 source = wheel.m_raycastInfo.m_hardPointWS;
wheel.m_raycastInfo.m_contactPointWS = source + rayvector;
- const Vector3& target = wheel.m_raycastInfo.m_contactPointWS;
- source-=wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS;
+ const Vector3 &target = wheel.m_raycastInfo.m_contactPointWS;
+ source -= wheel.m_wheelRadius * wheel.m_raycastInfo.m_wheelDirectionWS;
real_t param = real_t(0.);
-
PhysicsDirectSpaceState::RayResult rr;
+ PhysicsDirectSpaceState *ss = s->get_space_state();
- PhysicsDirectSpaceState *ss=s->get_space_state();
-
- bool col = ss->intersect_ray(source,target,rr,exclude);
-
+ bool col = ss->intersect_ray(source, target, rr, exclude);
wheel.m_raycastInfo.m_groundObject = 0;
- if (col)
- {
+ if (col) {
//print_line("WHEEL "+itos(p_idx)+" FROM "+source+" TO: "+target);
//print_line("WHEEL "+itos(p_idx)+" COLLIDE? "+itos(col));
- param = source.distance_to(rr.position)/source.distance_to(target);
+ param = source.distance_to(rr.position) / source.distance_to(target);
depth = raylen * param;
- wheel.m_raycastInfo.m_contactNormalWS = rr.normal;
+ wheel.m_raycastInfo.m_contactNormalWS = rr.normal;
wheel.m_raycastInfo.m_isInContact = true;
if (rr.collider)
- wheel.m_raycastInfo.m_groundObject=rr.collider->cast_to<PhysicsBody>();
-
+ wheel.m_raycastInfo.m_groundObject = rr.collider->cast_to<PhysicsBody>();
- real_t hitDistance = param*raylen;
+ real_t hitDistance = param * raylen;
wheel.m_raycastInfo.m_suspensionLength = hitDistance - wheel.m_wheelRadius;
//clamp on max suspension travel
- real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm*real_t(0.01);
- real_t maxSuspensionLength = wheel.m_suspensionRestLength+ wheel.m_maxSuspensionTravelCm*real_t(0.01);
- if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength)
- {
+ real_t minSuspensionLength = wheel.m_suspensionRestLength - wheel.m_maxSuspensionTravelCm * real_t(0.01);
+ real_t maxSuspensionLength = wheel.m_suspensionRestLength + wheel.m_maxSuspensionTravelCm * real_t(0.01);
+ if (wheel.m_raycastInfo.m_suspensionLength < minSuspensionLength) {
wheel.m_raycastInfo.m_suspensionLength = minSuspensionLength;
}
- if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength)
- {
+ if (wheel.m_raycastInfo.m_suspensionLength > maxSuspensionLength) {
wheel.m_raycastInfo.m_suspensionLength = maxSuspensionLength;
}
wheel.m_raycastInfo.m_contactPointWS = rr.position;
- real_t denominator= wheel.m_raycastInfo.m_contactNormalWS.dot( wheel.m_raycastInfo.m_wheelDirectionWS );
+ real_t denominator = wheel.m_raycastInfo.m_contactNormalWS.dot(wheel.m_raycastInfo.m_wheelDirectionWS);
Vector3 chassis_velocity_at_contactPoint;
//Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS-getRigidBody()->getCenterOfMassPosition();
@@ -461,72 +422,58 @@ real_t VehicleBody::_ray_cast(int p_idx,PhysicsDirectBodyState *s) {
//chassis_velocity_at_contactPoint = getRigidBody()->getVelocityInLocalPoint(relpos);
chassis_velocity_at_contactPoint = s->get_linear_velocity() +
- (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS-s->get_transform().origin);// * mPos);
-
+ (s->get_angular_velocity()).cross(wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin); // * mPos);
- real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot( chassis_velocity_at_contactPoint );
+ real_t projVel = wheel.m_raycastInfo.m_contactNormalWS.dot(chassis_velocity_at_contactPoint);
- if ( denominator >= real_t(-0.1))
- {
+ if (denominator >= real_t(-0.1)) {
wheel.m_suspensionRelativeVelocity = real_t(0.0);
wheel.m_clippedInvContactDotSuspension = real_t(1.0) / real_t(0.1);
- }
- else
- {
+ } else {
real_t inv = real_t(-1.) / denominator;
wheel.m_suspensionRelativeVelocity = projVel * inv;
wheel.m_clippedInvContactDotSuspension = inv;
}
- } else
- {
+ } else {
wheel.m_raycastInfo.m_isInContact = false;
//put wheel info as in rest position
wheel.m_raycastInfo.m_suspensionLength = wheel.m_suspensionRestLength;
wheel.m_suspensionRelativeVelocity = real_t(0.0);
- wheel.m_raycastInfo.m_contactNormalWS = - wheel.m_raycastInfo.m_wheelDirectionWS;
+ wheel.m_raycastInfo.m_contactNormalWS = -wheel.m_raycastInfo.m_wheelDirectionWS;
wheel.m_clippedInvContactDotSuspension = real_t(1.0);
}
return depth;
}
-
-void VehicleBody::_update_suspension(PhysicsDirectBodyState *s)
-{
+void VehicleBody::_update_suspension(PhysicsDirectBodyState *s) {
real_t chassisMass = mass;
- for (int w_it=0; w_it<wheels.size(); w_it++)
- {
- VehicleWheel& wheel_info = *wheels[w_it];
-
+ for (int w_it = 0; w_it < wheels.size(); w_it++) {
+ VehicleWheel &wheel_info = *wheels[w_it];
- if ( wheel_info.m_raycastInfo.m_isInContact )
- {
+ if (wheel_info.m_raycastInfo.m_isInContact) {
real_t force;
//Spring
{
- real_t susp_length = wheel_info.m_suspensionRestLength;
- real_t current_length = wheel_info.m_raycastInfo.m_suspensionLength;
+ real_t susp_length = wheel_info.m_suspensionRestLength;
+ real_t current_length = wheel_info.m_raycastInfo.m_suspensionLength;
real_t length_diff = (susp_length - current_length);
- force = wheel_info.m_suspensionStiffness
- * length_diff * wheel_info.m_clippedInvContactDotSuspension;
+ force = wheel_info.m_suspensionStiffness * length_diff * wheel_info.m_clippedInvContactDotSuspension;
}
// Damper
{
real_t projected_rel_vel = wheel_info.m_suspensionRelativeVelocity;
{
- real_t susp_damping;
- if ( projected_rel_vel < real_t(0.0) )
- {
+ real_t susp_damping;
+ if (projected_rel_vel < real_t(0.0)) {
susp_damping = wheel_info.m_wheelsDampingCompression;
- }
- else
- {
+ } else {
susp_damping = wheel_info.m_wheelsDampingRelaxation;
}
force -= susp_damping * projected_rel_vel;
@@ -535,30 +482,23 @@ void VehicleBody::_update_suspension(PhysicsDirectBodyState *s)
// RESULT
wheel_info.m_wheelsSuspensionForce = force * chassisMass;
- if (wheel_info.m_wheelsSuspensionForce < real_t(0.))
- {
+ if (wheel_info.m_wheelsSuspensionForce < real_t(0.)) {
wheel_info.m_wheelsSuspensionForce = real_t(0.);
}
- }
- else
- {
+ } else {
wheel_info.m_wheelsSuspensionForce = real_t(0.0);
}
}
-
}
-
//bilateral constraint between two dynamic objects
-void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3& pos1,
- PhysicsBody* body2, const Vector3& pos2, const Vector3& normal,real_t& impulse)
-{
+void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3 &pos1,
+ PhysicsBody *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse) {
real_t normalLenSqr = normal.length_squared();
//ERR_FAIL_COND( normalLenSqr < real_t(1.1));
- if (normalLenSqr > real_t(1.1))
- {
+ if (normalLenSqr > real_t(1.1)) {
impulse = real_t(0.);
return;
}
@@ -569,16 +509,16 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec
rel_pos2 = pos2 - body2->get_global_transform().origin;
//this jacobian entry could be re-used for all iterations
- Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1);// * mPos);
+ Vector3 vel1 = s->get_linear_velocity() + (s->get_angular_velocity()).cross(rel_pos1); // * mPos);
Vector3 vel2;
if (body2)
- vel2=body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2);
+ vel2 = body2->get_linear_velocity() + body2->get_angular_velocity().cross(rel_pos2);
Vector3 vel = vel1 - vel2;
Basis b2trans;
- float b2invmass=0;
+ float b2invmass = 0;
Vector3 b2lv;
Vector3 b2av;
Vector3 b2invinertia; //todo
@@ -590,24 +530,21 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec
b2av = body2->get_angular_velocity();
}
-
-
btVehicleJacobianEntry jac(s->get_transform().basis.transposed(),
- b2trans,
- rel_pos1,
- rel_pos2,
- normal,
- s->get_inverse_inertia_tensor().get_main_diagonal(),
- 1.0/mass,
- b2invinertia,
- b2invmass);
+ b2trans,
+ rel_pos1,
+ rel_pos2,
+ normal,
+ s->get_inverse_inertia_tensor().get_main_diagonal(),
+ 1.0 / mass,
+ b2invinertia,
+ b2invmass);
real_t rel_vel = jac.getRelativeVelocity(
- s->get_linear_velocity(),
- s->get_transform().basis.transposed().xform(s->get_angular_velocity()),
- b2lv,
- b2trans.xform(b2av));
-
+ s->get_linear_velocity(),
+ s->get_transform().basis.transposed().xform(s->get_angular_velocity()),
+ b2lv,
+ b2trans.xform(b2av));
rel_vel = normal.dot(vel);
@@ -615,32 +552,28 @@ void VehicleBody::_resolve_single_bilateral(PhysicsDirectBodyState *s, const Vec
real_t contactDamping = real_t(0.4);
#define ONLY_USE_LINEAR_MASS
#ifdef ONLY_USE_LINEAR_MASS
- real_t massTerm = real_t(1.) / ((1.0/mass) + b2invmass);
- impulse = - contactDamping * rel_vel * massTerm;
+ real_t massTerm = real_t(1.) / ((1.0 / mass) + b2invmass);
+ impulse = -contactDamping * rel_vel * massTerm;
#else
real_t velocityImpulse = -contactDamping * rel_vel * jacDiagABInv;
impulse = velocityImpulse;
#endif
-
}
-
-
-VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s,PhysicsBody* body1,const Vector3& frictionPosWorld,const Vector3& frictionDirectionWorld, real_t maxImpulse)
- :m_s(s),
- m_body1(body1),
- m_frictionPositionWorld(frictionPosWorld),
- m_frictionDirectionWorld(frictionDirectionWorld),
- m_maxImpulse(maxImpulse)
-{
- float denom0=0;
- float denom1=0;
+VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse)
+ : m_s(s),
+ m_body1(body1),
+ m_frictionPositionWorld(frictionPosWorld),
+ m_frictionDirectionWorld(frictionDirectionWorld),
+ m_maxImpulse(maxImpulse) {
+ float denom0 = 0;
+ float denom1 = 0;
{
Vector3 r0 = frictionPosWorld - s->get_transform().origin;
Vector3 c0 = (r0).cross(frictionDirectionWorld);
Vector3 vec = s->get_inverse_inertia_tensor().xform_inv(c0).cross(r0);
- denom0= s->get_inverse_mass() + frictionDirectionWorld.dot(vec);
+ denom0 = s->get_inverse_mass() + frictionDirectionWorld.dot(vec);
}
/* TODO: Why is this code unused?
@@ -654,30 +587,28 @@ VehicleBody::btVehicleWheelContactPoint::btVehicleWheelContactPoint(PhysicsDirec
}
*/
- real_t relaxation = 1.f;
- m_jacDiagABInv = relaxation/(denom0+denom1);
+ real_t relaxation = 1.f;
+ m_jacDiagABInv = relaxation / (denom0 + denom1);
}
+real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint &contactPoint) {
-real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint& contactPoint) {
-
- real_t j1=0.f;
+ real_t j1 = 0.f;
- const Vector3& contactPosWorld = contactPoint.m_frictionPositionWorld;
+ const Vector3 &contactPosWorld = contactPoint.m_frictionPositionWorld;
Vector3 rel_pos1 = contactPosWorld - contactPoint.m_s->get_transform().origin;
Vector3 rel_pos2;
if (contactPoint.m_body1)
rel_pos2 = contactPosWorld - contactPoint.m_body1->get_global_transform().origin;
- real_t maxImpulse = contactPoint.m_maxImpulse;
+ real_t maxImpulse = contactPoint.m_maxImpulse;
- Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1);// * mPos);
+ Vector3 vel1 = contactPoint.m_s->get_linear_velocity() + (contactPoint.m_s->get_angular_velocity()).cross(rel_pos1); // * mPos);
Vector3 vel2;
if (contactPoint.m_body1) {
- vel2=contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2);
-
+ vel2 = contactPoint.m_body1->get_linear_velocity() + contactPoint.m_body1->get_angular_velocity().cross(rel_pos2);
}
Vector3 vel = vel1 - vel2;
@@ -687,10 +618,9 @@ real_t VehicleBody::_calc_rolling_friction(btVehicleWheelContactPoint& contactPo
// calculate j that moves us to zero relative velocity
j1 = -vrel * contactPoint.m_jacDiagABInv;
- return CLAMP(j1,-maxImpulse,maxImpulse);
+ return CLAMP(j1, -maxImpulse, maxImpulse);
}
-
static const real_t sideFrictionStiffness2 = real_t(1.0);
void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
@@ -706,37 +636,31 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
int numWheelsOnGround = 0;
-
//collapse all those loops into one!
- for (int i=0;i<wheels.size();i++)
- {
- VehicleWheel& wheelInfo = *wheels[i];
+ for (int i = 0; i < wheels.size(); i++) {
+ VehicleWheel &wheelInfo = *wheels[i];
if (wheelInfo.m_raycastInfo.m_isInContact)
numWheelsOnGround++;
m_sideImpulse[i] = real_t(0.);
m_forwardImpulse[i] = real_t(0.);
-
}
{
- for (int i=0;i<wheels.size();i++)
- {
+ for (int i = 0; i < wheels.size(); i++) {
- VehicleWheel& wheelInfo = *wheels[i];
+ VehicleWheel &wheelInfo = *wheels[i];
-
- if (wheelInfo.m_raycastInfo.m_isInContact)
- {
+ if (wheelInfo.m_raycastInfo.m_isInContact) {
//const btTransform& wheelTrans = getWheelTransformWS( i );
- Basis wheelBasis0 = wheelInfo.m_worldTransform.basis;//get_global_transform().basis;
+ Basis wheelBasis0 = wheelInfo.m_worldTransform.basis; //get_global_transform().basis;
m_axle[i] = wheelBasis0.get_axis(Vector3::AXIS_X);
//m_axle[i] = wheelInfo.m_raycastInfo.m_wheelAxleWS;
- const Vector3& surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
+ const Vector3 &surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS;
real_t proj = m_axle[i].dot(surfNormalWS);
m_axle[i] -= surfNormalWS * proj;
m_axle[i] = m_axle[i].normalized();
@@ -744,14 +668,11 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
m_forwardWS[i] = surfNormalWS.cross(m_axle[i]);
m_forwardWS[i].normalize();
-
_resolve_single_bilateral(s, wheelInfo.m_raycastInfo.m_contactPointWS,
- wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
- m_axle[i],m_sideImpulse[i]);
+ wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS,
+ m_axle[i], m_sideImpulse[i]);
m_sideImpulse[i] *= sideFrictionStiffness2;
-
-
}
}
}
@@ -761,57 +682,46 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
bool sliding = false;
{
- for (int wheel =0;wheel <wheels.size();wheel++)
- {
- VehicleWheel& wheelInfo = *wheels[wheel];
-
+ for (int wheel = 0; wheel < wheels.size(); wheel++) {
+ VehicleWheel &wheelInfo = *wheels[wheel];
//class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject;
- real_t rollingFriction = 0.f;
+ real_t rollingFriction = 0.f;
- if (wheelInfo.m_raycastInfo.m_isInContact)
- {
- if (engine_force != 0.f)
- {
- rollingFriction = -engine_force* s->get_step();
- } else
- {
+ if (wheelInfo.m_raycastInfo.m_isInContact) {
+ if (engine_force != 0.f) {
+ rollingFriction = -engine_force * s->get_step();
+ } else {
real_t defaultRollingFrictionImpulse = 0.f;
- float cbrake = MAX(wheelInfo.m_brake,brake);
+ float cbrake = MAX(wheelInfo.m_brake, brake);
real_t maxImpulse = cbrake ? cbrake : defaultRollingFrictionImpulse;
- btVehicleWheelContactPoint contactPt(s,wheelInfo.m_raycastInfo.m_groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,m_forwardWS[wheel],maxImpulse);
+ btVehicleWheelContactPoint contactPt(s, wheelInfo.m_raycastInfo.m_groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, m_forwardWS[wheel], maxImpulse);
rollingFriction = _calc_rolling_friction(contactPt);
}
}
//switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)
-
-
-
m_forwardImpulse[wheel] = real_t(0.);
- wheelInfo.m_skidInfo= real_t(1.);
+ wheelInfo.m_skidInfo = real_t(1.);
- if (wheelInfo.m_raycastInfo.m_isInContact)
- {
- wheelInfo.m_skidInfo= real_t(1.);
+ if (wheelInfo.m_raycastInfo.m_isInContact) {
+ wheelInfo.m_skidInfo = real_t(1.);
real_t maximp = wheelInfo.m_wheelsSuspensionForce * s->get_step() * wheelInfo.m_frictionSlip;
real_t maximpSide = maximp;
real_t maximpSquared = maximp * maximpSide;
+ m_forwardImpulse[wheel] = rollingFriction; //wheelInfo.m_engineForce* timeStep;
- m_forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep;
+ real_t x = (m_forwardImpulse[wheel]) * fwdFactor;
+ real_t y = (m_sideImpulse[wheel]) * sideFactor;
- real_t x = (m_forwardImpulse[wheel] ) * fwdFactor;
- real_t y = (m_sideImpulse[wheel] ) * sideFactor;
+ real_t impulseSquared = (x * x + y * y);
- real_t impulseSquared = (x*x + y*y);
-
- if (impulseSquared > maximpSquared)
- {
+ if (impulseSquared > maximpSquared) {
sliding = true;
real_t factor = maximp / Math::sqrt(impulseSquared);
@@ -819,22 +729,14 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
wheelInfo.m_skidInfo *= factor;
}
}
-
}
}
-
-
-
- if (sliding)
- {
- for (int wheel = 0;wheel < wheels.size(); wheel++)
- {
- if (m_sideImpulse[wheel] != real_t(0.))
- {
- if (wheels[wheel]->m_skidInfo< real_t(1.))
- {
- m_forwardImpulse[wheel] *= wheels[wheel]->m_skidInfo;
+ if (sliding) {
+ for (int wheel = 0; wheel < wheels.size(); wheel++) {
+ if (m_sideImpulse[wheel] != real_t(0.)) {
+ if (wheels[wheel]->m_skidInfo < real_t(1.)) {
+ m_forwardImpulse[wheel] *= wheels[wheel]->m_skidInfo;
m_sideImpulse[wheel] *= wheels[wheel]->m_skidInfo;
}
}
@@ -843,36 +745,32 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
// apply the impulses
{
- for (int wheel = 0;wheel<wheels.size(); wheel++)
- {
- VehicleWheel& wheelInfo = *wheels[wheel];
+ for (int wheel = 0; wheel < wheels.size(); wheel++) {
+ VehicleWheel &wheelInfo = *wheels[wheel];
Vector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS -
- s->get_transform().origin;
+ s->get_transform().origin;
- if (m_forwardImpulse[wheel] != real_t(0.))
- {
- s->apply_impulse(rel_pos,m_forwardWS[wheel]*(m_forwardImpulse[wheel]));
+ if (m_forwardImpulse[wheel] != real_t(0.)) {
+ s->apply_impulse(rel_pos, m_forwardWS[wheel] * (m_forwardImpulse[wheel]));
}
- if (m_sideImpulse[wheel] != real_t(0.))
- {
- PhysicsBody* groundObject = wheelInfo.m_raycastInfo.m_groundObject;
+ if (m_sideImpulse[wheel] != real_t(0.)) {
+ PhysicsBody *groundObject = wheelInfo.m_raycastInfo.m_groundObject;
Vector3 rel_pos2;
if (groundObject) {
- rel_pos2=wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin;
+ rel_pos2 = wheelInfo.m_raycastInfo.m_contactPointWS - groundObject->get_global_transform().origin;
}
-
Vector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel];
#if defined ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
- Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1];//getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
- rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f-wheelInfo.m_rollInfluence));
+ Vector3 vChassisWorldUp = s->get_transform().basis.transposed()[1]; //getRigidBody()->getCenterOfMassTransform().getBasis().getColumn(m_indexUpAxis);
+ rel_pos -= vChassisWorldUp * (vChassisWorldUp.dot(rel_pos) * (1.f - wheelInfo.m_rollInfluence));
#else
rel_pos[1] *= wheelInfo.m_rollInfluence; //?
#endif
- s->apply_impulse(rel_pos,sideImp);
+ s->apply_impulse(rel_pos, sideImp);
//apply friction impulse on the ground
//todo
@@ -880,74 +778,62 @@ void VehicleBody::_update_friction(PhysicsDirectBodyState *s) {
}
}
}
-
-
}
-
void VehicleBody::_direct_state_changed(Object *p_state) {
-
PhysicsDirectBodyState *s = p_state->cast_to<PhysicsDirectBodyState>();
set_ignore_transform_notification(true);
set_global_transform(s->get_transform());
set_ignore_transform_notification(false);
-
float step = s->get_step();
- for(int i=0;i<wheels.size();i++) {
+ for (int i = 0; i < wheels.size(); i++) {
- _update_wheel(i,s);
+ _update_wheel(i, s);
}
+ for (int i = 0; i < wheels.size(); i++) {
- for(int i=0;i<wheels.size();i++) {
-
- _ray_cast(i,s);
+ _ray_cast(i, s);
wheels[i]->set_transform(s->get_transform().inverse() * wheels[i]->m_worldTransform);
}
_update_suspension(s);
- for(int i=0;i<wheels.size();i++) {
+ for (int i = 0; i < wheels.size(); i++) {
//apply suspension force
- VehicleWheel& wheel = *wheels[i];
+ VehicleWheel &wheel = *wheels[i];
real_t suspensionForce = wheel.m_wheelsSuspensionForce;
- if (suspensionForce > wheel.m_maxSuspensionForce)
- {
+ if (suspensionForce > wheel.m_maxSuspensionForce) {
suspensionForce = wheel.m_maxSuspensionForce;
}
Vector3 impulse = wheel.m_raycastInfo.m_contactNormalWS * suspensionForce * step;
Vector3 relpos = wheel.m_raycastInfo.m_contactPointWS - s->get_transform().origin;
- s->apply_impulse(relpos,impulse);
+ s->apply_impulse(relpos, impulse);
//getRigidBody()->applyImpulse(impulse, relpos);
-
}
-
_update_friction(s);
-
- for (int i=0;i<wheels.size();i++)
- {
- VehicleWheel& wheel = *wheels[i];
+ for (int i = 0; i < wheels.size(); i++) {
+ VehicleWheel &wheel = *wheels[i];
Vector3 relpos = wheel.m_raycastInfo.m_hardPointWS - s->get_transform().origin;
- Vector3 vel = s->get_linear_velocity() + (s->get_angular_velocity()).cross(relpos);// * mPos);
+ Vector3 vel = s->get_linear_velocity() + (s->get_angular_velocity()).cross(relpos); // * mPos);
- if (wheel.m_raycastInfo.m_isInContact)
- {
- const Transform& chassisWorldTransform = s->get_transform();
+ if (wheel.m_raycastInfo.m_isInContact) {
+ const Transform &chassisWorldTransform = s->get_transform();
- Vector3 fwd (
- chassisWorldTransform.basis[0][Vector3::AXIS_Z],
- chassisWorldTransform.basis[1][Vector3::AXIS_Z],
- chassisWorldTransform.basis[2][Vector3::AXIS_Z]);
+ Vector3 fwd(
+ chassisWorldTransform.basis[0][Vector3::AXIS_Z],
+ chassisWorldTransform.basis[1][Vector3::AXIS_Z],
+ chassisWorldTransform.basis[2][Vector3::AXIS_Z]);
real_t proj = fwd.dot(wheel.m_raycastInfo.m_contactNormalWS);
fwd -= wheel.m_raycastInfo.m_contactNormalWS * proj;
@@ -957,126 +843,115 @@ void VehicleBody::_direct_state_changed(Object *p_state) {
wheel.m_deltaRotation = (proj2 * step) / (wheel.m_wheelRadius);
wheel.m_rotation += wheel.m_deltaRotation;
- } else
- {
+ } else {
wheel.m_rotation += wheel.m_deltaRotation;
}
- wheel.m_deltaRotation *= real_t(0.99);//damping of rotation when not in contact
-
+ wheel.m_deltaRotation *= real_t(0.99); //damping of rotation when not in contact
}
linear_velocity = s->get_linear_velocity();
}
void VehicleBody::set_mass(real_t p_mass) {
- mass=p_mass;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_MASS,mass);
+ mass = p_mass;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_MASS, mass);
}
-real_t VehicleBody::get_mass() const{
+real_t VehicleBody::get_mass() const {
return mass;
}
-
void VehicleBody::set_friction(real_t p_friction) {
- friction=p_friction;
- PhysicsServer::get_singleton()->body_set_param(get_rid(),PhysicsServer::BODY_PARAM_FRICTION,friction);
+ friction = p_friction;
+ PhysicsServer::get_singleton()->body_set_param(get_rid(), PhysicsServer::BODY_PARAM_FRICTION, friction);
}
-real_t VehicleBody::get_friction() const{
+real_t VehicleBody::get_friction() const {
return friction;
}
void VehicleBody::set_engine_force(float p_force) {
- engine_force=p_force;
+ engine_force = p_force;
}
-float VehicleBody::get_engine_force() const{
+float VehicleBody::get_engine_force() const {
return engine_force;
}
-void VehicleBody::set_brake(float p_brake){
+void VehicleBody::set_brake(float p_brake) {
- brake=p_brake;
+ brake = p_brake;
}
-float VehicleBody::get_brake() const{
+float VehicleBody::get_brake() const {
return brake;
}
-void VehicleBody::set_steering(float p_steering){
+void VehicleBody::set_steering(float p_steering) {
- m_steeringValue=p_steering;
+ m_steeringValue = p_steering;
}
-float VehicleBody::get_steering() const{
+float VehicleBody::get_steering() const {
return m_steeringValue;
}
-Vector3 VehicleBody::get_linear_velocity() const
-{
+Vector3 VehicleBody::get_linear_velocity() const {
return linear_velocity;
}
-void VehicleBody::_bind_methods(){
-
- ClassDB::bind_method(D_METHOD("set_mass","mass"),&VehicleBody::set_mass);
- ClassDB::bind_method(D_METHOD("get_mass"),&VehicleBody::get_mass);
-
- ClassDB::bind_method(D_METHOD("set_friction","friction"),&VehicleBody::set_friction);
- ClassDB::bind_method(D_METHOD("get_friction"),&VehicleBody::get_friction);
+void VehicleBody::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_engine_force","engine_force"),&VehicleBody::set_engine_force);
- ClassDB::bind_method(D_METHOD("get_engine_force"),&VehicleBody::get_engine_force);
+ ClassDB::bind_method(D_METHOD("set_mass", "mass"), &VehicleBody::set_mass);
+ ClassDB::bind_method(D_METHOD("get_mass"), &VehicleBody::get_mass);
- ClassDB::bind_method(D_METHOD("set_brake","brake"),&VehicleBody::set_brake);
- ClassDB::bind_method(D_METHOD("get_brake"),&VehicleBody::get_brake);
+ ClassDB::bind_method(D_METHOD("set_friction", "friction"), &VehicleBody::set_friction);
+ ClassDB::bind_method(D_METHOD("get_friction"), &VehicleBody::get_friction);
- ClassDB::bind_method(D_METHOD("set_steering","steering"),&VehicleBody::set_steering);
- ClassDB::bind_method(D_METHOD("get_steering"),&VehicleBody::get_steering);
+ ClassDB::bind_method(D_METHOD("set_engine_force", "engine_force"), &VehicleBody::set_engine_force);
+ ClassDB::bind_method(D_METHOD("get_engine_force"), &VehicleBody::get_engine_force);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"),&VehicleBody::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_brake", "brake"), &VehicleBody::set_brake);
+ ClassDB::bind_method(D_METHOD("get_brake"), &VehicleBody::get_brake);
- ClassDB::bind_method(D_METHOD("_direct_state_changed"),&VehicleBody::_direct_state_changed);
+ ClassDB::bind_method(D_METHOD("set_steering", "steering"), &VehicleBody::set_steering);
+ ClassDB::bind_method(D_METHOD("get_steering"), &VehicleBody::get_steering);
- ADD_GROUP("Motion","");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"engine_force",PROPERTY_HINT_RANGE,"0.00,1024.0,0.01"),"set_engine_force","get_engine_force");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"brake",PROPERTY_HINT_RANGE,"0.0,1.0,0.01"),"set_brake","get_brake");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"steering",PROPERTY_HINT_RANGE,"-180,180.0,0.01"),"set_steering","get_steering");
- ADD_GROUP("Mass","");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"mass",PROPERTY_HINT_RANGE,"0.01,65536,0.01"),"set_mass","get_mass");
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"friction",PROPERTY_HINT_RANGE,"0.01,1,0.01"),"set_friction","get_friction");
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &VehicleBody::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("_direct_state_changed"), &VehicleBody::_direct_state_changed);
+ ADD_GROUP("Motion", "");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "engine_force", PROPERTY_HINT_RANGE, "0.00,1024.0,0.01"), "set_engine_force", "get_engine_force");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "brake", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_brake", "get_brake");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "steering", PROPERTY_HINT_RANGE, "-180,180.0,0.01"), "set_steering", "get_steering");
+ ADD_GROUP("Mass", "");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_RANGE, "0.01,65536,0.01"), "set_mass", "get_mass");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0.01,1,0.01"), "set_friction", "get_friction");
}
+VehicleBody::VehicleBody()
+ : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) {
-
-VehicleBody::VehicleBody() : PhysicsBody(PhysicsServer::BODY_MODE_RIGID) {
-
-
- m_pitchControl=0;
+ m_pitchControl = 0;
m_currentVehicleSpeedKmHour = real_t(0.);
m_steeringValue = real_t(0.);
- engine_force=0;
- brake=0;
+ engine_force = 0;
+ brake = 0;
+ friction = 1;
-
- friction=1;
-
- ccd=false;
+ ccd = false;
exclude.insert(get_rid());
- PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(),this,"_direct_state_changed");
+ PhysicsServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
set_mass(40);
}
-
diff --git a/scene/3d/vehicle_body.h b/scene/3d/vehicle_body.h
index 273e63d741..55b521cfa6 100644
--- a/scene/3d/vehicle_body.h
+++ b/scene/3d/vehicle_body.h
@@ -35,20 +35,18 @@ class VehicleBody;
class VehicleWheel : public Spatial {
- GDCLASS(VehicleWheel,Spatial);
-
-friend class VehicleBody;
+ GDCLASS(VehicleWheel, Spatial);
+ friend class VehicleBody;
Transform m_worldTransform;
Transform local_xform;
bool engine_traction;
bool steers;
-
- Vector3 m_chassisConnectionPointCS; //const
- Vector3 m_wheelDirectionCS;//const
- Vector3 m_wheelAxleCS; // const or modified by steering
+ Vector3 m_chassisConnectionPointCS; //const
+ Vector3 m_wheelDirectionCS; //const
+ Vector3 m_wheelAxleCS; // const or modified by steering
real_t m_suspensionRestLength;
real_t m_maxSuspensionTravelCm;
@@ -65,30 +63,29 @@ friend class VehicleBody;
//btVector3 m_wheelAxleCS; // const or modified by steering ?
- real_t m_steering;
- real_t m_rotation;
- real_t m_deltaRotation;
- real_t m_rollInfluence;
+ real_t m_steering;
+ real_t m_rotation;
+ real_t m_deltaRotation;
+ real_t m_rollInfluence;
//real_t m_engineForce;
- real_t m_brake;
+ real_t m_brake;
- real_t m_clippedInvContactDotSuspension;
- real_t m_suspensionRelativeVelocity;
+ real_t m_clippedInvContactDotSuspension;
+ real_t m_suspensionRelativeVelocity;
//calculated by suspension
- real_t m_wheelsSuspensionForce;
- real_t m_skidInfo;
-
+ real_t m_wheelsSuspensionForce;
+ real_t m_skidInfo;
struct RaycastInfo {
//set by raycaster
- Vector3 m_contactNormalWS;//contactnormal
- Vector3 m_contactPointWS;//raycast hitpoint
- real_t m_suspensionLength;
- Vector3 m_hardPointWS;//raycast starting point
- Vector3 m_wheelDirectionWS; //direction in worldspace
- Vector3 m_wheelAxleWS; // axle in worldspace
+ Vector3 m_contactNormalWS; //contactnormal
+ Vector3 m_contactPointWS; //raycast hitpoint
+ real_t m_suspensionLength;
+ Vector3 m_hardPointWS; //raycast starting point
+ Vector3 m_wheelDirectionWS; //direction in worldspace
+ Vector3 m_wheelAxleWS; // axle in worldspace
bool m_isInContact;
- PhysicsBody* m_groundObject; //could be general void* ptr
+ PhysicsBody *m_groundObject; //could be general void* ptr
} m_raycastInfo;
void _update(PhysicsDirectBodyState *s);
@@ -98,7 +95,6 @@ protected:
static void _bind_methods();
public:
-
void set_radius(float p_radius);
float get_radius() const;
@@ -130,13 +126,11 @@ public:
bool is_used_as_steering() const;
VehicleWheel();
-
};
-
class VehicleBody : public PhysicsBody {
- GDCLASS(VehicleBody,PhysicsBody);
+ GDCLASS(VehicleBody, PhysicsBody);
real_t mass;
real_t friction;
@@ -145,52 +139,48 @@ class VehicleBody : public PhysicsBody {
float brake;
Vector3 linear_velocity;
- Vector3 angular_velocity;
+ Vector3 angular_velocity;
bool ccd;
- real_t m_pitchControl;
- real_t m_steeringValue;
- real_t m_currentVehicleSpeedKmHour;
+ real_t m_pitchControl;
+ real_t m_steeringValue;
+ real_t m_currentVehicleSpeedKmHour;
Set<RID> exclude;
- Vector<Vector3> m_forwardWS;
- Vector<Vector3> m_axle;
- Vector<real_t> m_forwardImpulse;
- Vector<real_t> m_sideImpulse;
+ Vector<Vector3> m_forwardWS;
+ Vector<Vector3> m_axle;
+ Vector<real_t> m_forwardImpulse;
+ Vector<real_t> m_sideImpulse;
struct btVehicleWheelContactPoint {
PhysicsDirectBodyState *m_s;
- PhysicsBody* m_body1;
- Vector3 m_frictionPositionWorld;
- Vector3 m_frictionDirectionWorld;
- real_t m_jacDiagABInv;
- real_t m_maxImpulse;
+ PhysicsBody *m_body1;
+ Vector3 m_frictionPositionWorld;
+ Vector3 m_frictionDirectionWorld;
+ real_t m_jacDiagABInv;
+ real_t m_maxImpulse;
-
- btVehicleWheelContactPoint(PhysicsDirectBodyState *s,PhysicsBody* body1,const Vector3& frictionPosWorld,const Vector3& frictionDirectionWorld, real_t maxImpulse);
+ btVehicleWheelContactPoint(PhysicsDirectBodyState *s, PhysicsBody *body1, const Vector3 &frictionPosWorld, const Vector3 &frictionDirectionWorld, real_t maxImpulse);
};
- void _resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3& pos1, PhysicsBody* body2, const Vector3& pos2, const Vector3& normal, real_t& impulse);
- real_t _calc_rolling_friction(btVehicleWheelContactPoint& contactPoint);
+ void _resolve_single_bilateral(PhysicsDirectBodyState *s, const Vector3 &pos1, PhysicsBody *body2, const Vector3 &pos2, const Vector3 &normal, real_t &impulse);
+ real_t _calc_rolling_friction(btVehicleWheelContactPoint &contactPoint);
void _update_friction(PhysicsDirectBodyState *s);
void _update_suspension(PhysicsDirectBodyState *s);
- real_t _ray_cast(int p_idx,PhysicsDirectBodyState *s);
- void _update_wheel_transform(VehicleWheel& wheel ,PhysicsDirectBodyState *s);
- void _update_wheel(int p_idx,PhysicsDirectBodyState *s);
-
-
+ real_t _ray_cast(int p_idx, PhysicsDirectBodyState *s);
+ void _update_wheel_transform(VehicleWheel &wheel, PhysicsDirectBodyState *s);
+ void _update_wheel(int p_idx, PhysicsDirectBodyState *s);
-friend class VehicleWheel;
- Vector<VehicleWheel*> wheels;
+ friend class VehicleWheel;
+ Vector<VehicleWheel *> wheels;
static void _bind_methods();
void _direct_state_changed(Object *p_state);
-public:
-
+public:
void set_mass(real_t p_mass);
real_t get_mass() const;
diff --git a/scene/3d/visibility_notifier.cpp b/scene/3d/visibility_notifier.cpp
index 0633846b5a..909ac002b0 100644
--- a/scene/3d/visibility_notifier.cpp
+++ b/scene/3d/visibility_notifier.cpp
@@ -28,71 +28,64 @@
/*************************************************************************/
#include "visibility_notifier.h"
-#include "scene/scene_string_names.h"
#include "scene/3d/physics_body.h"
#include "scene/animation/animation_player.h"
#include "scene/scene_string_names.h"
+#include "scene/scene_string_names.h"
-void VisibilityNotifier::_enter_camera(Camera* p_camera) {
+void VisibilityNotifier::_enter_camera(Camera *p_camera) {
ERR_FAIL_COND(cameras.has(p_camera));
cameras.insert(p_camera);
- if (cameras.size()==1) {
+ if (cameras.size() == 1) {
emit_signal(SceneStringNames::get_singleton()->screen_entered);
_screen_enter();
}
- emit_signal(SceneStringNames::get_singleton()->camera_entered,p_camera);
-
+ emit_signal(SceneStringNames::get_singleton()->camera_entered, p_camera);
}
-void VisibilityNotifier::_exit_camera(Camera* p_camera){
+void VisibilityNotifier::_exit_camera(Camera *p_camera) {
ERR_FAIL_COND(!cameras.has(p_camera));
cameras.erase(p_camera);
- emit_signal(SceneStringNames::get_singleton()->camera_exited,p_camera);
- if (cameras.size()==0) {
+ emit_signal(SceneStringNames::get_singleton()->camera_exited, p_camera);
+ if (cameras.size() == 0) {
emit_signal(SceneStringNames::get_singleton()->screen_exited);
_screen_exit();
-
}
}
+void VisibilityNotifier::set_aabb(const Rect3 &p_aabb) {
-void VisibilityNotifier::set_aabb(const Rect3& p_aabb){
-
- if (aabb==p_aabb)
+ if (aabb == p_aabb)
return;
- aabb=p_aabb;
+ aabb = p_aabb;
if (is_inside_world()) {
- get_world()->_update_notifier(this,get_global_transform().xform(aabb));
+ get_world()->_update_notifier(this, get_global_transform().xform(aabb));
}
_change_notify("aabb");
update_gizmo();
}
-Rect3 VisibilityNotifier::get_aabb() const{
+Rect3 VisibilityNotifier::get_aabb() const {
return aabb;
}
-
void VisibilityNotifier::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
-
- get_world()->_register_notifier(this,get_global_transform().xform(aabb));
+ get_world()->_register_notifier(this, get_global_transform().xform(aabb));
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
-
- get_world()->_update_notifier(this,get_global_transform().xform(aabb));
+ get_world()->_update_notifier(this, get_global_transform().xform(aabb));
} break;
case NOTIFICATION_EXIT_WORLD: {
@@ -101,76 +94,65 @@ void VisibilityNotifier::_notification(int p_what) {
}
}
-
bool VisibilityNotifier::is_on_screen() const {
- return cameras.size()!=0;
+ return cameras.size() != 0;
}
-void VisibilityNotifier::_bind_methods(){
+void VisibilityNotifier::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_aabb","rect"),&VisibilityNotifier::set_aabb);
- ClassDB::bind_method(D_METHOD("get_aabb"),&VisibilityNotifier::get_aabb);
- ClassDB::bind_method(D_METHOD("is_on_screen"),&VisibilityNotifier::is_on_screen);
+ ClassDB::bind_method(D_METHOD("set_aabb", "rect"), &VisibilityNotifier::set_aabb);
+ ClassDB::bind_method(D_METHOD("get_aabb"), &VisibilityNotifier::get_aabb);
+ ClassDB::bind_method(D_METHOD("is_on_screen"), &VisibilityNotifier::is_on_screen);
- ADD_PROPERTY( PropertyInfo(Variant::RECT3,"aabb"),"set_aabb","get_aabb");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT3, "aabb"), "set_aabb", "get_aabb");
- ADD_SIGNAL( MethodInfo("camera_entered",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) );
- ADD_SIGNAL( MethodInfo("camera_exited",PropertyInfo(Variant::OBJECT,"camera",PROPERTY_HINT_RESOURCE_TYPE,"Camera")) );
- ADD_SIGNAL( MethodInfo("screen_entered"));
- ADD_SIGNAL( MethodInfo("screen_exited"));
+ ADD_SIGNAL(MethodInfo("camera_entered", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera")));
+ ADD_SIGNAL(MethodInfo("camera_exited", PropertyInfo(Variant::OBJECT, "camera", PROPERTY_HINT_RESOURCE_TYPE, "Camera")));
+ ADD_SIGNAL(MethodInfo("screen_entered"));
+ ADD_SIGNAL(MethodInfo("screen_exited"));
}
-
VisibilityNotifier::VisibilityNotifier() {
- aabb=Rect3(Vector3(-1,-1,-1),Vector3(2,2,2));
+ aabb = Rect3(Vector3(-1, -1, -1), Vector3(2, 2, 2));
set_notify_transform(true);
-
}
-
-
-
-
//////////////////////////////////////
-
void VisibilityEnabler::_screen_enter() {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
-
- _change_node_state(E->key(),true);
+ _change_node_state(E->key(), true);
}
- visible=true;
+ visible = true;
}
void VisibilityEnabler::_screen_exit() {
- for(Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
- _change_node_state(E->key(),false);
+ _change_node_state(E->key(), false);
}
- visible=false;
+ visible = false;
}
-void VisibilityEnabler::_find_nodes(Node* p_node) {
-
+void VisibilityEnabler::_find_nodes(Node *p_node) {
- bool add=false;
+ bool add = false;
Variant meta;
if (enabler[ENABLER_FREEZE_BODIES]) {
RigidBody *rb = p_node->cast_to<RigidBody>();
- if (rb && ((rb->get_mode()==RigidBody::MODE_CHARACTER || (rb->get_mode()==RigidBody::MODE_RIGID && !rb->is_able_to_sleep())))) {
+ if (rb && ((rb->get_mode() == RigidBody::MODE_CHARACTER || (rb->get_mode() == RigidBody::MODE_RIGID && !rb->is_able_to_sleep())))) {
-
- add=true;
- meta=rb->get_mode();
+ add = true;
+ meta = rb->get_mode();
}
}
@@ -178,63 +160,58 @@ void VisibilityEnabler::_find_nodes(Node* p_node) {
AnimationPlayer *ap = p_node->cast_to<AnimationPlayer>();
if (ap) {
- add=true;
+ add = true;
}
}
if (add) {
- p_node->connect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed",varray(p_node),CONNECT_ONESHOT);
- nodes[p_node]=meta;
- _change_node_state(p_node,false);
+ p_node->connect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed", varray(p_node), CONNECT_ONESHOT);
+ nodes[p_node] = meta;
+ _change_node_state(p_node, false);
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
Node *c = p_node->get_child(i);
- if (c->get_filename()!=String())
+ if (c->get_filename() != String())
continue; //skip, instance
_find_nodes(c);
}
-
}
-void VisibilityEnabler::_notification(int p_what){
+void VisibilityEnabler::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
if (get_tree()->is_editor_hint())
return;
-
Node *from = this;
//find where current scene starts
- while(from->get_parent() && from->get_filename()==String())
- from=from->get_parent();
+ while (from->get_parent() && from->get_filename() == String())
+ from = from->get_parent();
_find_nodes(from);
-
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (get_tree()->is_editor_hint())
return;
-
- for (Map<Node*,Variant>::Element *E=nodes.front();E;E=E->next()) {
+ for (Map<Node *, Variant>::Element *E = nodes.front(); E; E = E->next()) {
if (!visible)
- _change_node_state(E->key(),true);
- E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed");
+ _change_node_state(E->key(), true);
+ E->key()->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed");
}
nodes.clear();
-
}
}
-void VisibilityEnabler::_change_node_state(Node* p_node,bool p_enabled) {
+void VisibilityEnabler::_change_node_state(Node *p_node, bool p_enabled) {
ERR_FAIL_COND(!nodes.has(p_node));
@@ -246,59 +223,52 @@ void VisibilityEnabler::_change_node_state(Node* p_node,bool p_enabled) {
}
{
- AnimationPlayer *ap=p_node->cast_to<AnimationPlayer>();
+ AnimationPlayer *ap = p_node->cast_to<AnimationPlayer>();
if (ap) {
ap->set_active(p_enabled);
}
}
-
}
-
-void VisibilityEnabler::_node_removed(Node* p_node) {
+void VisibilityEnabler::_node_removed(Node *p_node) {
if (!visible)
- _change_node_state(p_node,true);
- p_node->disconnect(SceneStringNames::get_singleton()->tree_exited,this,"_node_removed");
+ _change_node_state(p_node, true);
+ p_node->disconnect(SceneStringNames::get_singleton()->tree_exited, this, "_node_removed");
nodes.erase(p_node);
-
}
-void VisibilityEnabler::_bind_methods(){
+void VisibilityEnabler::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_enabler","enabler","enabled"),&VisibilityEnabler::set_enabler);
- ClassDB::bind_method(D_METHOD("is_enabler_enabled","enabler"),&VisibilityEnabler::is_enabler_enabled);
- ClassDB::bind_method(D_METHOD("_node_removed"),&VisibilityEnabler::_node_removed);
+ ClassDB::bind_method(D_METHOD("set_enabler", "enabler", "enabled"), &VisibilityEnabler::set_enabler);
+ ClassDB::bind_method(D_METHOD("is_enabler_enabled", "enabler"), &VisibilityEnabler::is_enabler_enabled);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &VisibilityEnabler::_node_removed);
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"pause_animations"),"set_enabler","is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS );
- ADD_PROPERTYI( PropertyInfo(Variant::BOOL,"freeze_bodies"),"set_enabler","is_enabler_enabled", ENABLER_FREEZE_BODIES);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "pause_animations"), "set_enabler", "is_enabler_enabled", ENABLER_PAUSE_ANIMATIONS);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "freeze_bodies"), "set_enabler", "is_enabler_enabled", ENABLER_FREEZE_BODIES);
- BIND_CONSTANT( ENABLER_FREEZE_BODIES );
- BIND_CONSTANT( ENABLER_PAUSE_ANIMATIONS );
- BIND_CONSTANT( ENABLER_MAX);
+ BIND_CONSTANT(ENABLER_FREEZE_BODIES);
+ BIND_CONSTANT(ENABLER_PAUSE_ANIMATIONS);
+ BIND_CONSTANT(ENABLER_MAX);
}
-void VisibilityEnabler::set_enabler(Enabler p_enabler,bool p_enable){
-
- ERR_FAIL_INDEX(p_enabler,ENABLER_MAX);
- enabler[p_enabler]=p_enable;
+void VisibilityEnabler::set_enabler(Enabler p_enabler, bool p_enable) {
+ ERR_FAIL_INDEX(p_enabler, ENABLER_MAX);
+ enabler[p_enabler] = p_enable;
}
-bool VisibilityEnabler::is_enabler_enabled(Enabler p_enabler) const{
+bool VisibilityEnabler::is_enabler_enabled(Enabler p_enabler) const {
- ERR_FAIL_INDEX_V(p_enabler,ENABLER_MAX,false);
+ ERR_FAIL_INDEX_V(p_enabler, ENABLER_MAX, false);
return enabler[p_enabler];
-
}
VisibilityEnabler::VisibilityEnabler() {
- for(int i=0;i<ENABLER_MAX;i++)
- enabler[i]=true;
-
- visible=false;
+ for (int i = 0; i < ENABLER_MAX; i++)
+ enabler[i] = true;
+ visible = false;
}
-
diff --git a/scene/3d/visibility_notifier.h b/scene/3d/visibility_notifier.h
index aa53e1bcd1..09c1175bf1 100644
--- a/scene/3d/visibility_notifier.h
+++ b/scene/3d/visibility_notifier.h
@@ -34,39 +34,36 @@
class Camera;
class VisibilityNotifier : public Spatial {
- GDCLASS(VisibilityNotifier,Spatial);
+ GDCLASS(VisibilityNotifier, Spatial);
- Set<Camera*> cameras;
+ Set<Camera *> cameras;
Rect3 aabb;
protected:
-
virtual void _screen_enter() {}
virtual void _screen_exit() {}
void _notification(int p_what);
static void _bind_methods();
-friend class SpatialIndexer;
+ friend class SpatialIndexer;
- void _enter_camera(Camera* p_camera);
- void _exit_camera(Camera* p_camera);
+ void _enter_camera(Camera *p_camera);
+ void _exit_camera(Camera *p_camera);
public:
-
- void set_aabb(const Rect3& p_aabb);
+ void set_aabb(const Rect3 &p_aabb);
Rect3 get_aabb() const;
bool is_on_screen() const;
VisibilityNotifier();
};
-
class VisibilityEnabler : public VisibilityNotifier {
- GDCLASS(VisibilityEnabler,VisibilityNotifier);
-public:
+ GDCLASS(VisibilityEnabler, VisibilityNotifier);
+public:
enum Enabler {
ENABLER_PAUSE_ANIMATIONS,
ENABLER_FREEZE_BODIES,
@@ -74,33 +71,29 @@ public:
};
protected:
-
virtual void _screen_enter();
virtual void _screen_exit();
bool visible;
- void _find_nodes(Node* p_node);
+ void _find_nodes(Node *p_node);
- Map<Node*,Variant> nodes;
- void _node_removed(Node* p_node);
+ Map<Node *, Variant> nodes;
+ void _node_removed(Node *p_node);
bool enabler[ENABLER_MAX];
- void _change_node_state(Node* p_node,bool p_enabled);
+ void _change_node_state(Node *p_node, bool p_enabled);
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_enabler(Enabler p_enabler,bool p_enable);
+ void set_enabler(Enabler p_enabler, bool p_enable);
bool is_enabler_enabled(Enabler p_enabler) const;
VisibilityEnabler();
-
};
VARIANT_ENUM_CAST(VisibilityEnabler::Enabler);
-
#endif // VISIBILITY_NOTIFIER_H
diff --git a/scene/3d/visual_instance.cpp b/scene/3d/visual_instance.cpp
index bbcd54b36b..852881abd4 100644
--- a/scene/3d/visual_instance.cpp
+++ b/scene/3d/visual_instance.cpp
@@ -28,39 +28,37 @@
/*************************************************************************/
#include "visual_instance.h"
-#include "servers/visual_server.h"
#include "room_instance.h"
#include "scene/scene_string_names.h"
+#include "servers/visual_server.h"
#include "skeleton.h"
Rect3 VisualInstance::get_transformed_aabb() const {
- return get_global_transform().xform( get_aabb() );
+ return get_global_transform().xform(get_aabb());
}
-
void VisualInstance::_update_visibility() {
if (!is_inside_tree())
return;
_change_notify("visible");
- VS::get_singleton()->instance_set_visible(get_instance(),is_visible_in_tree());
+ VS::get_singleton()->instance_set_visible(get_instance(), is_visible_in_tree());
}
-
void VisualInstance::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_WORLD: {
// CHECK ROOM
- Spatial * parent = get_parent_spatial();
- Room *room=NULL;
+ Spatial *parent = get_parent_spatial();
+ Room *room = NULL;
bool is_geom = cast_to<GeometryInstance>();
- /* while(parent) {
+ /* while(parent) {
room = parent->cast_to<Room>();
if (room)
@@ -74,11 +72,9 @@ void VisualInstance::_notification(int p_what) {
parent=parent->get_parent_spatial();
}*/
-
-
if (room) {
- VisualServer::get_singleton()->instance_set_room(instance,room->get_instance());
+ VisualServer::get_singleton()->instance_set_room(instance, room->get_instance());
}
// CHECK SKELETON => moving skeleton attaching logic to MeshInstance
/*
@@ -87,21 +83,20 @@ void VisualInstance::_notification(int p_what) {
VisualServer::get_singleton()->instance_attach_skeleton( instance, skeleton->get_skeleton() );
*/
- VisualServer::get_singleton()->instance_set_scenario( instance, get_world()->get_scenario() );
+ VisualServer::get_singleton()->instance_set_scenario(instance, get_world()->get_scenario());
_update_visibility();
-
} break;
case NOTIFICATION_TRANSFORM_CHANGED: {
Transform gt = get_global_transform();
- VisualServer::get_singleton()->instance_set_transform(instance,gt);
+ VisualServer::get_singleton()->instance_set_transform(instance, gt);
} break;
case NOTIFICATION_EXIT_WORLD: {
- VisualServer::get_singleton()->instance_set_scenario( instance, RID() );
- VisualServer::get_singleton()->instance_set_room(instance,RID());
- VisualServer::get_singleton()->instance_attach_skeleton( instance, RID() );
+ VisualServer::get_singleton()->instance_set_scenario(instance, RID());
+ VisualServer::get_singleton()->instance_set_room(instance, RID());
+ VisualServer::get_singleton()->instance_attach_skeleton(instance, RID());
//VS::get_singleton()->instance_geometry_set_baked_light_sampler(instance, RID() );
} break;
@@ -109,7 +104,6 @@ void VisualInstance::_notification(int p_what) {
_update_visibility();
} break;
-
}
}
@@ -125,8 +119,8 @@ RID VisualInstance::_get_visual_instance_rid() const {
void VisualInstance::set_layer_mask(uint32_t p_mask) {
- layers=p_mask;
- VisualServer::get_singleton()->instance_set_layer_mask(instance,p_mask);
+ layers = p_mask;
+ VisualServer::get_singleton()->instance_set_layer_mask(instance, p_mask);
}
uint32_t VisualInstance::get_layer_mask() const {
@@ -134,76 +128,62 @@ uint32_t VisualInstance::get_layer_mask() const {
return layers;
}
-
void VisualInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_get_visual_instance_rid"),&VisualInstance::_get_visual_instance_rid);
- ClassDB::bind_method(D_METHOD("set_base","base"), &VisualInstance::set_base);
- ClassDB::bind_method(D_METHOD("set_layer_mask","mask"), &VisualInstance::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("_get_visual_instance_rid"), &VisualInstance::_get_visual_instance_rid);
+ ClassDB::bind_method(D_METHOD("set_base", "base"), &VisualInstance::set_base);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "mask"), &VisualInstance::set_layer_mask);
ClassDB::bind_method(D_METHOD("get_layer_mask"), &VisualInstance::get_layer_mask);
ClassDB::bind_method(D_METHOD("get_transformed_aabb"), &VisualInstance::get_transformed_aabb);
- ADD_PROPERTY( PropertyInfo( Variant::INT, "layers",PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask");
-
-
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_3D_RENDER), "set_layer_mask", "get_layer_mask");
}
+void VisualInstance::set_base(const RID &p_base) {
-void VisualInstance::set_base(const RID& p_base) {
-
- VisualServer::get_singleton()->instance_set_base(instance,p_base);
+ VisualServer::get_singleton()->instance_set_base(instance, p_base);
}
-
-VisualInstance::VisualInstance()
-{
+VisualInstance::VisualInstance() {
instance = VisualServer::get_singleton()->instance_create();
- VisualServer::get_singleton()->instance_attach_object_instance_ID( instance, get_instance_ID() );
- layers=1;
+ VisualServer::get_singleton()->instance_attach_object_instance_ID(instance, get_instance_ID());
+ layers = 1;
set_notify_transform(true);
}
-
VisualInstance::~VisualInstance() {
VisualServer::get_singleton()->free(instance);
}
+void GeometryInstance::set_material_override(const Ref<Material> &p_material) {
-
-
-void GeometryInstance::set_material_override(const Ref<Material>& p_material) {
-
- material_override=p_material;
- VS::get_singleton()->instance_geometry_set_material_override(get_instance(),p_material.is_valid() ? p_material->get_rid() : RID());
+ material_override = p_material;
+ VS::get_singleton()->instance_geometry_set_material_override(get_instance(), p_material.is_valid() ? p_material->get_rid() : RID());
}
-Ref<Material> GeometryInstance::get_material_override() const{
+Ref<Material> GeometryInstance::get_material_override() const {
return material_override;
}
+void GeometryInstance::set_lod_min_distance(float p_dist) {
-
-void GeometryInstance::set_lod_min_distance(float p_dist){
-
- lod_min_distance=p_dist;
- VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis);
+ lod_min_distance = p_dist;
+ VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
}
-float GeometryInstance::get_lod_min_distance() const{
+float GeometryInstance::get_lod_min_distance() const {
return lod_min_distance;
}
-
void GeometryInstance::set_lod_max_distance(float p_dist) {
- lod_max_distance=p_dist;
- VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis);
-
+ lod_max_distance = p_dist;
+ VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
}
float GeometryInstance::get_lod_max_distance() const {
@@ -211,23 +191,21 @@ float GeometryInstance::get_lod_max_distance() const {
return lod_max_distance;
}
-void GeometryInstance::set_lod_min_hysteresis(float p_dist){
+void GeometryInstance::set_lod_min_hysteresis(float p_dist) {
- lod_min_hysteresis=p_dist;
- VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis);
+ lod_min_hysteresis = p_dist;
+ VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
}
-float GeometryInstance::get_lod_min_hysteresis() const{
+float GeometryInstance::get_lod_min_hysteresis() const {
return lod_min_hysteresis;
}
-
void GeometryInstance::set_lod_max_hysteresis(float p_dist) {
- lod_max_hysteresis=p_dist;
- VS::get_singleton()->instance_geometry_set_draw_range(get_instance(),lod_min_distance,lod_max_distance,lod_min_hysteresis,lod_max_hysteresis);
-
+ lod_max_hysteresis = p_dist;
+ VS::get_singleton()->instance_geometry_set_draw_range(get_instance(), lod_min_distance, lod_max_distance, lod_min_hysteresis, lod_max_hysteresis);
}
float GeometryInstance::get_lod_max_hysteresis() const {
@@ -235,64 +213,53 @@ float GeometryInstance::get_lod_max_hysteresis() const {
return lod_max_hysteresis;
}
-
void GeometryInstance::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_WORLD) {
+ if (p_what == NOTIFICATION_ENTER_WORLD) {
if (flags[FLAG_USE_BAKED_LIGHT]) {
-
}
-
- } else if (p_what==NOTIFICATION_EXIT_WORLD) {
+ } else if (p_what == NOTIFICATION_EXIT_WORLD) {
if (flags[FLAG_USE_BAKED_LIGHT]) {
-
-
}
-
}
-
}
-void GeometryInstance::set_flag(Flags p_flag,bool p_value) {
+void GeometryInstance::set_flag(Flags p_flag, bool p_value) {
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
- if (p_flag==FLAG_CAST_SHADOW) {
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
+ if (p_flag == FLAG_CAST_SHADOW) {
if (p_value == true) {
set_cast_shadows_setting(SHADOW_CASTING_SETTING_ON);
- }
- else {
+ } else {
set_cast_shadows_setting(SHADOW_CASTING_SETTING_OFF);
}
}
- if (flags[p_flag]==p_value)
+ if (flags[p_flag] == p_value)
return;
- flags[p_flag]=p_value;
- VS::get_singleton()->instance_geometry_set_flag(get_instance(),(VS::InstanceFlags)p_flag,p_value);
- if (p_flag==FLAG_USE_BAKED_LIGHT) {
-
+ flags[p_flag] = p_value;
+ VS::get_singleton()->instance_geometry_set_flag(get_instance(), (VS::InstanceFlags)p_flag, p_value);
+ if (p_flag == FLAG_USE_BAKED_LIGHT) {
}
}
-bool GeometryInstance::get_flag(Flags p_flag) const{
+bool GeometryInstance::get_flag(Flags p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
if (p_flag == FLAG_CAST_SHADOW) {
if (shadow_casting_setting == SHADOW_CASTING_SETTING_OFF) {
return false;
- }
- else {
+ } else {
return true;
}
}
return flags[p_flag];
-
}
void GeometryInstance::set_cast_shadows_setting(ShadowCastingSetting p_shadow_casting_setting) {
@@ -307,99 +274,90 @@ GeometryInstance::ShadowCastingSetting GeometryInstance::get_cast_shadows_settin
return shadow_casting_setting;
}
-
-
-
void GeometryInstance::set_extra_cull_margin(float p_margin) {
- ERR_FAIL_COND(p_margin<0);
- extra_cull_margin=p_margin;
- VS::get_singleton()->instance_set_extra_visibility_margin(get_instance(),extra_cull_margin);
+ ERR_FAIL_COND(p_margin < 0);
+ extra_cull_margin = p_margin;
+ VS::get_singleton()->instance_set_extra_visibility_margin(get_instance(), extra_cull_margin);
}
-float GeometryInstance::get_extra_cull_margin() const{
+float GeometryInstance::get_extra_cull_margin() const {
return extra_cull_margin;
}
void GeometryInstance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_material_override","material"), &GeometryInstance::set_material_override);
+ ClassDB::bind_method(D_METHOD("set_material_override", "material"), &GeometryInstance::set_material_override);
ClassDB::bind_method(D_METHOD("get_material_override"), &GeometryInstance::get_material_override);
- ClassDB::bind_method(D_METHOD("set_flag","flag","value"), &GeometryInstance::set_flag);
- ClassDB::bind_method(D_METHOD("get_flag","flag"), &GeometryInstance::get_flag);
+ ClassDB::bind_method(D_METHOD("set_flag", "flag", "value"), &GeometryInstance::set_flag);
+ ClassDB::bind_method(D_METHOD("get_flag", "flag"), &GeometryInstance::get_flag);
ClassDB::bind_method(D_METHOD("set_cast_shadows_setting", "shadow_casting_setting"), &GeometryInstance::set_cast_shadows_setting);
ClassDB::bind_method(D_METHOD("get_cast_shadows_setting"), &GeometryInstance::get_cast_shadows_setting);
- ClassDB::bind_method(D_METHOD("set_lod_max_hysteresis","mode"), &GeometryInstance::set_lod_max_hysteresis);
+ ClassDB::bind_method(D_METHOD("set_lod_max_hysteresis", "mode"), &GeometryInstance::set_lod_max_hysteresis);
ClassDB::bind_method(D_METHOD("get_lod_max_hysteresis"), &GeometryInstance::get_lod_max_hysteresis);
- ClassDB::bind_method(D_METHOD("set_lod_max_distance","mode"), &GeometryInstance::set_lod_max_distance);
+ ClassDB::bind_method(D_METHOD("set_lod_max_distance", "mode"), &GeometryInstance::set_lod_max_distance);
ClassDB::bind_method(D_METHOD("get_lod_max_distance"), &GeometryInstance::get_lod_max_distance);
- ClassDB::bind_method(D_METHOD("set_lod_min_hysteresis","mode"), &GeometryInstance::set_lod_min_hysteresis);
+ ClassDB::bind_method(D_METHOD("set_lod_min_hysteresis", "mode"), &GeometryInstance::set_lod_min_hysteresis);
ClassDB::bind_method(D_METHOD("get_lod_min_hysteresis"), &GeometryInstance::get_lod_min_hysteresis);
- ClassDB::bind_method(D_METHOD("set_lod_min_distance","mode"), &GeometryInstance::set_lod_min_distance);
+ ClassDB::bind_method(D_METHOD("set_lod_min_distance", "mode"), &GeometryInstance::set_lod_min_distance);
ClassDB::bind_method(D_METHOD("get_lod_min_distance"), &GeometryInstance::get_lod_min_distance);
-
- ClassDB::bind_method(D_METHOD("set_extra_cull_margin","margin"), &GeometryInstance::set_extra_cull_margin);
+ ClassDB::bind_method(D_METHOD("set_extra_cull_margin", "margin"), &GeometryInstance::set_extra_cull_margin);
ClassDB::bind_method(D_METHOD("get_extra_cull_margin"), &GeometryInstance::get_extra_cull_margin);
- ClassDB::bind_method(D_METHOD("get_aabb"),&GeometryInstance::get_aabb);
+ ClassDB::bind_method(D_METHOD("get_aabb"), &GeometryInstance::get_aabb);
-
- ADD_GROUP("Geometry","");
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "material_override",PROPERTY_HINT_RESOURCE_TYPE,"Material"), "set_material_override", "get_material_override");
+ ADD_GROUP("Geometry", "");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "material_override", PROPERTY_HINT_RESOURCE_TYPE, "Material"), "set_material_override", "get_material_override");
ADD_PROPERTY(PropertyInfo(Variant::INT, "cast_shadow", PROPERTY_HINT_ENUM, "Off,On,Double-Sided,Shadows Only"), "set_cast_shadows_setting", "get_cast_shadows_setting");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "extra_cull_margin",PROPERTY_HINT_RANGE,"0,16384,0"), "set_extra_cull_margin", "get_extra_cull_margin");
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_as_billboard"), "set_flag", "get_flag",FLAG_BILLBOARD);
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_as_y_billboard"), "set_flag", "get_flag",FLAG_BILLBOARD_FIX_Y);
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_depth_scale"), "set_flag", "get_flag",FLAG_DEPH_SCALE);
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "visible_in_all_rooms"), "set_flag", "get_flag",FLAG_VISIBLE_IN_ALL_ROOMS);
- ADD_PROPERTYI( PropertyInfo( Variant::BOOL, "use_in_baked_light"), "set_flag", "get_flag",FLAG_USE_BAKED_LIGHT);
-
- ADD_GROUP("LOD","lod_");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_min_distance",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_min_distance", "get_lod_min_distance");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_min_hysteresis",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_min_hysteresis", "get_lod_min_hysteresis");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_max_distance",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_max_distance", "get_lod_max_distance");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "lod_max_hysteresis",PROPERTY_HINT_RANGE,"0,32768,0.01"), "set_lod_max_hysteresis", "get_lod_max_hysteresis");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "extra_cull_margin", PROPERTY_HINT_RANGE, "0,16384,0"), "set_extra_cull_margin", "get_extra_cull_margin");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_as_billboard"), "set_flag", "get_flag", FLAG_BILLBOARD);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_as_y_billboard"), "set_flag", "get_flag", FLAG_BILLBOARD_FIX_Y);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_depth_scale"), "set_flag", "get_flag", FLAG_DEPH_SCALE);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "visible_in_all_rooms"), "set_flag", "get_flag", FLAG_VISIBLE_IN_ALL_ROOMS);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "use_in_baked_light"), "set_flag", "get_flag", FLAG_USE_BAKED_LIGHT);
+
+ ADD_GROUP("LOD", "lod_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_distance", "get_lod_min_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_min_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_min_hysteresis", "get_lod_min_hysteresis");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_distance", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_distance", "get_lod_max_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "lod_max_hysteresis", PROPERTY_HINT_RANGE, "0,32768,0.01"), "set_lod_max_hysteresis", "get_lod_max_hysteresis");
//ADD_SIGNAL( MethodInfo("visibility_changed"));
- BIND_CONSTANT(FLAG_CAST_SHADOW );
- BIND_CONSTANT(FLAG_BILLBOARD );
- BIND_CONSTANT(FLAG_BILLBOARD_FIX_Y );
- BIND_CONSTANT(FLAG_DEPH_SCALE );
- BIND_CONSTANT(FLAG_VISIBLE_IN_ALL_ROOMS );
- BIND_CONSTANT(FLAG_MAX );
+ BIND_CONSTANT(FLAG_CAST_SHADOW);
+ BIND_CONSTANT(FLAG_BILLBOARD);
+ BIND_CONSTANT(FLAG_BILLBOARD_FIX_Y);
+ BIND_CONSTANT(FLAG_DEPH_SCALE);
+ BIND_CONSTANT(FLAG_VISIBLE_IN_ALL_ROOMS);
+ BIND_CONSTANT(FLAG_MAX);
BIND_CONSTANT(SHADOW_CASTING_SETTING_OFF);
BIND_CONSTANT(SHADOW_CASTING_SETTING_ON);
BIND_CONSTANT(SHADOW_CASTING_SETTING_DOUBLE_SIDED);
BIND_CONSTANT(SHADOW_CASTING_SETTING_SHADOWS_ONLY);
-
}
GeometryInstance::GeometryInstance() {
- lod_min_distance=0;
- lod_max_distance=0;
- lod_min_hysteresis=0;
- lod_max_hysteresis=0;
+ lod_min_distance = 0;
+ lod_max_distance = 0;
+ lod_min_hysteresis = 0;
+ lod_max_hysteresis = 0;
- for(int i=0;i<FLAG_MAX;i++) {
- flags[i]=false;
+ for (int i = 0; i < FLAG_MAX; i++) {
+ flags[i] = false;
}
+ flags[FLAG_CAST_SHADOW] = true;
- flags[FLAG_CAST_SHADOW]=true;
-
- shadow_casting_setting=SHADOW_CASTING_SETTING_ON;
- extra_cull_margin=0;
+ shadow_casting_setting = SHADOW_CASTING_SETTING_ON;
+ extra_cull_margin = 0;
//VS::get_singleton()->instance_geometry_set_baked_light_texture_index(get_instance(),0);
-
-
}
diff --git a/scene/3d/visual_instance.h b/scene/3d/visual_instance.h
index 5955dae236..9f1cba923f 100644
--- a/scene/3d/visual_instance.h
+++ b/scene/3d/visual_instance.h
@@ -29,85 +29,77 @@
#ifndef VISUAL_INSTANCE_H
#define VISUAL_INSTANCE_H
-#include "scene/3d/spatial.h"
#include "face3.h"
#include "rid.h"
+#include "scene/3d/spatial.h"
#include "scene/resources/material.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class VisualInstance : public Spatial {
- GDCLASS( VisualInstance, Spatial );
+ GDCLASS(VisualInstance, Spatial);
OBJ_CATEGORY("3D Visual Nodes");
RID instance;
uint32_t layers;
-
RID _get_visual_instance_rid() const;
-
-
protected:
-
void _update_visibility();
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
enum GetFacesFlags {
- FACES_SOLID=1, // solid geometry
- FACES_ENCLOSING=2,
- FACES_DYNAMIC=4 // dynamic object geometry
+ FACES_SOLID = 1, // solid geometry
+ FACES_ENCLOSING = 2,
+ FACES_DYNAMIC = 4 // dynamic object geometry
};
RID get_instance() const;
- virtual Rect3 get_aabb() const=0;
- virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const=0;
+ virtual Rect3 get_aabb() const = 0;
+ virtual PoolVector<Face3> get_faces(uint32_t p_usage_flags) const = 0;
virtual Rect3 get_transformed_aabb() const; // helper
- void set_base(const RID& p_base);
+ void set_base(const RID &p_base);
void set_layer_mask(uint32_t p_mask);
uint32_t get_layer_mask() const;
-
VisualInstance();
~VisualInstance();
-
};
class BakedLight;
class GeometryInstance : public VisualInstance {
- GDCLASS( GeometryInstance, VisualInstance );
-public:
+ GDCLASS(GeometryInstance, VisualInstance);
+public:
enum Flags {
- FLAG_CAST_SHADOW=VS::INSTANCE_FLAG_CAST_SHADOW,
- FLAG_BILLBOARD=VS::INSTANCE_FLAG_BILLBOARD,
- FLAG_BILLBOARD_FIX_Y=VS::INSTANCE_FLAG_BILLBOARD_FIX_Y,
- FLAG_DEPH_SCALE=VS::INSTANCE_FLAG_DEPH_SCALE,
- FLAG_VISIBLE_IN_ALL_ROOMS=VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS,
- FLAG_USE_BAKED_LIGHT=VS::INSTANCE_FLAG_USE_BAKED_LIGHT,
- FLAG_MAX=VS::INSTANCE_FLAG_MAX,
+ FLAG_CAST_SHADOW = VS::INSTANCE_FLAG_CAST_SHADOW,
+ FLAG_BILLBOARD = VS::INSTANCE_FLAG_BILLBOARD,
+ FLAG_BILLBOARD_FIX_Y = VS::INSTANCE_FLAG_BILLBOARD_FIX_Y,
+ FLAG_DEPH_SCALE = VS::INSTANCE_FLAG_DEPH_SCALE,
+ FLAG_VISIBLE_IN_ALL_ROOMS = VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS,
+ FLAG_USE_BAKED_LIGHT = VS::INSTANCE_FLAG_USE_BAKED_LIGHT,
+ FLAG_MAX = VS::INSTANCE_FLAG_MAX,
};
-
enum ShadowCastingSetting {
- SHADOW_CASTING_SETTING_OFF=VS::SHADOW_CASTING_SETTING_OFF,
+ SHADOW_CASTING_SETTING_OFF = VS::SHADOW_CASTING_SETTING_OFF,
SHADOW_CASTING_SETTING_ON = VS::SHADOW_CASTING_SETTING_ON,
- SHADOW_CASTING_SETTING_DOUBLE_SIDED=VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED,
- SHADOW_CASTING_SETTING_SHADOWS_ONLY=VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY
+ SHADOW_CASTING_SETTING_DOUBLE_SIDED = VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED,
+ SHADOW_CASTING_SETTING_SHADOWS_ONLY = VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY
};
private:
-
bool flags[FLAG_MAX];
ShadowCastingSetting shadow_casting_setting;
Ref<Material> material_override;
@@ -119,12 +111,11 @@ private:
float extra_cull_margin;
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_flag(Flags p_flag,bool p_value);
+public:
+ void set_flag(Flags p_flag, bool p_value);
bool get_flag(Flags p_flag) const;
void set_cast_shadows_setting(ShadowCastingSetting p_shadow_casting_setting);
@@ -142,7 +133,7 @@ public:
void set_lod_max_hysteresis(float p_dist);
float get_lod_max_hysteresis() const;
- void set_material_override(const Ref<Material>& p_material);
+ void set_material_override(const Ref<Material> &p_material);
Ref<Material> get_material_override() const;
void set_extra_cull_margin(float p_margin);
@@ -151,8 +142,7 @@ public:
GeometryInstance();
};
-VARIANT_ENUM_CAST( GeometryInstance::Flags );
-VARIANT_ENUM_CAST( GeometryInstance::ShadowCastingSetting );
-
+VARIANT_ENUM_CAST(GeometryInstance::Flags);
+VARIANT_ENUM_CAST(GeometryInstance::ShadowCastingSetting);
#endif
diff --git a/scene/animation/animation_cache.cpp b/scene/animation/animation_cache.cpp
index 960356d9cf..93fbde519e 100644
--- a/scene/animation/animation_cache.cpp
+++ b/scene/animation/animation_cache.cpp
@@ -28,8 +28,6 @@
/*************************************************************************/
#include "animation_cache.h"
-
-
void AnimationCache::_node_exit_tree(Node *p_node) {
//it is one shot, so it disconnects upon arrival
@@ -38,47 +36,41 @@ void AnimationCache::_node_exit_tree(Node *p_node) {
connected_nodes.erase(p_node);
- for(int i=0;i<path_cache.size();i++) {
-
+ for (int i = 0; i < path_cache.size(); i++) {
- if (path_cache[i].node!=p_node)
+ if (path_cache[i].node != p_node)
continue;
- path_cache[i].valid=false; //invalidate path cache
+ path_cache[i].valid = false; //invalidate path cache
}
-
}
void AnimationCache::_animation_changed() {
-
_clear_cache();
}
void AnimationCache::_clear_cache() {
- while(connected_nodes.size()) {
+ while (connected_nodes.size()) {
- connected_nodes.front()->get()->disconnect("tree_exited",this,"_node_exit_tree");
+ connected_nodes.front()->get()->disconnect("tree_exited", this, "_node_exit_tree");
connected_nodes.erase(connected_nodes.front());
}
path_cache.clear();
- cache_valid=false;
- cache_dirty=true;
+ cache_valid = false;
+ cache_dirty = true;
}
-
void AnimationCache::_update_cache() {
- cache_valid=false;
+ cache_valid = false;
ERR_FAIL_COND(!root);
ERR_FAIL_COND(!root->is_inside_tree());
ERR_FAIL_COND(animation.is_null());
- for(int i=0;i<animation->get_track_count();i++) {
-
-
+ for (int i = 0; i < animation->get_track_count(); i++) {
NodePath np = animation->track_get_path(i);
@@ -86,146 +78,127 @@ void AnimationCache::_update_cache() {
if (!node) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Invalid Track Path in Animation: "+np);
+ ERR_EXPLAIN("Invalid Track Path in Animation: " + np);
ERR_CONTINUE(!node);
}
-
Path path;
Ref<Resource> res;
if (np.get_subname_count()) {
-
- if (animation->track_get_type(i)==Animation::TYPE_TRANSFORM) {
+ if (animation->track_get_type(i) == Animation::TYPE_TRANSFORM) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Transform tracks can't have a subpath: "+np);
- ERR_CONTINUE(animation->track_get_type(i)==Animation::TYPE_TRANSFORM);
-
+ ERR_EXPLAIN("Transform tracks can't have a subpath: " + np);
+ ERR_CONTINUE(animation->track_get_type(i) == Animation::TYPE_TRANSFORM);
}
RES res;
- for(int j=0;j<np.get_subname_count();j++) {
- res = j==0 ? node->get(np.get_subname(j)) : res->get(np.get_subname(j));
+ for (int j = 0; j < np.get_subname_count(); j++) {
+ res = j == 0 ? node->get(np.get_subname(j)) : res->get(np.get_subname(j));
if (res.is_null())
break;
-
}
if (res.is_null()) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Invalid Track SubPath in Animation: "+np);
+ ERR_EXPLAIN("Invalid Track SubPath in Animation: " + np);
ERR_CONTINUE(res.is_null());
}
- path.resource=res;
- path.object=res.ptr();
+ path.resource = res;
+ path.object = res.ptr();
} else {
-
- if (animation->track_get_type(i)==Animation::TYPE_TRANSFORM) {
+ if (animation->track_get_type(i) == Animation::TYPE_TRANSFORM) {
StringName property = np.get_property();
String ps = property;
-
Spatial *sp = node->cast_to<Spatial>();
if (!sp) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Transform track not of type Spatial: "+np);
+ ERR_EXPLAIN("Transform track not of type Spatial: " + np);
ERR_CONTINUE(!sp);
}
- if (ps!="") {
+ if (ps != "") {
Skeleton *sk = node->cast_to<Skeleton>();
if (!sk) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton!: "+np);
+ ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton!: " + np);
ERR_CONTINUE(!sk);
}
int idx = sk->find_bone(ps);
- if (idx==-1) {
+ if (idx == -1) {
path_cache.push_back(Path());
- ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton Bone!: "+np);
- ERR_CONTINUE(idx==-1);
-
+ ERR_EXPLAIN("Property defined in Transform track, but not a Skeleton Bone!: " + np);
+ ERR_CONTINUE(idx == -1);
}
- path.bone_idx=idx;
- path.skeleton=sk;
-
+ path.bone_idx = idx;
+ path.skeleton = sk;
}
- path.spatial=sp;
-
+ path.spatial = sp;
}
- path.node=node;
- path.object=node;
-
+ path.node = node;
+ path.object = node;
}
- if (animation->track_get_type(i)==Animation::TYPE_VALUE) {
+ if (animation->track_get_type(i) == Animation::TYPE_VALUE) {
- if (np.get_property().operator String()=="") {
+ if (np.get_property().operator String() == "") {
path_cache.push_back(Path());
- ERR_EXPLAIN("Value Track lacks property: "+np);
- ERR_CONTINUE(np.get_property().operator String()=="");
-
+ ERR_EXPLAIN("Value Track lacks property: " + np);
+ ERR_CONTINUE(np.get_property().operator String() == "");
}
- path.property=np.get_property();
+ path.property = np.get_property();
- } else if (animation->track_get_type(i)==Animation::TYPE_METHOD) {
+ } else if (animation->track_get_type(i) == Animation::TYPE_METHOD) {
- if (np.get_property().operator String()!="") {
+ if (np.get_property().operator String() != "") {
path_cache.push_back(Path());
- ERR_EXPLAIN("Method Track has property: "+np);
- ERR_CONTINUE(np.get_property().operator String()!="");
-
+ ERR_EXPLAIN("Method Track has property: " + np);
+ ERR_CONTINUE(np.get_property().operator String() != "");
}
-
}
-
- path.valid=true;
+ path.valid = true;
path_cache.push_back(path);
if (!connected_nodes.has(path.node)) {
connected_nodes.insert(path.node);
- path.node->connect("tree_exited",this,"_node_exit_tree",Node::make_binds(path.node),CONNECT_ONESHOT);
+ path.node->connect("tree_exited", this, "_node_exit_tree", Node::make_binds(path.node), CONNECT_ONESHOT);
}
-
-
-
}
-
-
- cache_dirty=false;
- cache_valid=true;
+ cache_dirty = false;
+ cache_valid = true;
}
-void AnimationCache::set_track_transform(int p_idx,const Transform& p_transform) {
+void AnimationCache::set_track_transform(int p_idx, const Transform &p_transform) {
if (cache_dirty)
_update_cache();
ERR_FAIL_COND(!cache_valid);
- ERR_FAIL_INDEX(p_idx,path_cache.size());
+ ERR_FAIL_INDEX(p_idx, path_cache.size());
Path &p = path_cache[p_idx];
if (!p.valid)
return;
@@ -234,47 +207,42 @@ void AnimationCache::set_track_transform(int p_idx,const Transform& p_transform)
ERR_FAIL_COND(!p.spatial);
if (p.skeleton) {
- p.skeleton->set_bone_pose(p.bone_idx,p_transform);
+ p.skeleton->set_bone_pose(p.bone_idx, p_transform);
} else {
p.spatial->set_transform(p_transform);
}
-
}
-void AnimationCache::set_track_value(int p_idx,const Variant& p_value) {
+void AnimationCache::set_track_value(int p_idx, const Variant &p_value) {
if (cache_dirty)
_update_cache();
ERR_FAIL_COND(!cache_valid);
- ERR_FAIL_INDEX(p_idx,path_cache.size());
+ ERR_FAIL_INDEX(p_idx, path_cache.size());
Path &p = path_cache[p_idx];
if (!p.valid)
return;
ERR_FAIL_COND(!p.object);
- p.object->set(p.property,p_value);
+ p.object->set(p.property, p_value);
}
-
-void AnimationCache::call_track(int p_idx,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error) {
+void AnimationCache::call_track(int p_idx, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
if (cache_dirty)
_update_cache();
-
ERR_FAIL_COND(!cache_valid);
- ERR_FAIL_INDEX(p_idx,path_cache.size());
+ ERR_FAIL_INDEX(p_idx, path_cache.size());
Path &p = path_cache[p_idx];
if (!p.valid)
return;
ERR_FAIL_COND(!p.object);
- p.object->call(p_method,p_args,p_argcount,r_error);
-
+ p.object->call(p_method, p_args, p_argcount, r_error);
}
-
void AnimationCache::set_all(float p_time, float p_delta) {
if (cache_dirty)
@@ -283,104 +251,100 @@ void AnimationCache::set_all(float p_time, float p_delta) {
ERR_FAIL_COND(!cache_valid);
int tc = animation->get_track_count();
- for(int i=0;i<tc;i++) {
+ for (int i = 0; i < tc; i++) {
- switch(animation->track_get_type(i)) {
+ switch (animation->track_get_type(i)) {
case Animation::TYPE_TRANSFORM: {
- Vector3 loc,scale;
+ Vector3 loc, scale;
Quat rot;
- animation->transform_track_interpolate(i,p_time,&loc,&rot,&scale);
- Transform tr( Basis(rot), loc );
+ animation->transform_track_interpolate(i, p_time, &loc, &rot, &scale);
+ Transform tr(Basis(rot), loc);
tr.basis.scale(scale);
- set_track_transform(i,tr);
-
+ set_track_transform(i, tr);
} break;
case Animation::TYPE_VALUE: {
- if (animation->value_track_get_update_mode(i)==Animation::UPDATE_CONTINUOUS || (animation->value_track_get_update_mode(i)==Animation::UPDATE_DISCRETE && p_delta==0)) {
- Variant v = animation->value_track_interpolate(i,p_time);
- set_track_value(i,v);
+ if (animation->value_track_get_update_mode(i) == Animation::UPDATE_CONTINUOUS || (animation->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE && p_delta == 0)) {
+ Variant v = animation->value_track_interpolate(i, p_time);
+ set_track_value(i, v);
} else {
List<int> indices;
- animation->value_track_get_key_indices(i,p_time,p_delta,&indices);
+ animation->value_track_get_key_indices(i, p_time, p_delta, &indices);
- for(List<int>::Element *E=indices.front();E;E=E->next()) {
+ for (List<int>::Element *E = indices.front(); E; E = E->next()) {
- Variant v = animation->track_get_key_value(i,E->get());
- set_track_value(i,v);
+ Variant v = animation->track_get_key_value(i, E->get());
+ set_track_value(i, v);
}
-
}
} break;
case Animation::TYPE_METHOD: {
List<int> indices;
- animation->method_track_get_key_indices(i,p_time,p_delta,&indices);
+ animation->method_track_get_key_indices(i, p_time, p_delta, &indices);
- for(List<int>::Element *E=indices.front();E;E=E->next()) {
+ for (List<int>::Element *E = indices.front(); E; E = E->next()) {
- Vector<Variant> args = animation->method_track_get_params(i,E->get());
- StringName name = animation->method_track_get_name(i,E->get());
+ Vector<Variant> args = animation->method_track_get_params(i, E->get());
+ StringName name = animation->method_track_get_name(i, E->get());
Variant::CallError err;
if (!args.size()) {
- call_track(i,name,NULL,0,err);
+ call_track(i, name, NULL, 0, err);
} else {
- Vector<Variant*> argptrs;
+ Vector<Variant *> argptrs;
argptrs.resize(args.size());
- for(int j=0;j<args.size();j++) {
+ for (int j = 0; j < args.size(); j++) {
- argptrs[j]=&args[j];
+ argptrs[j] = &args[j];
}
- call_track(i,name,(const Variant**)&argptrs[0],args.size(),err);
+ call_track(i, name, (const Variant **)&argptrs[0], args.size(), err);
}
-
}
} break;
default: {}
}
}
-
}
-void AnimationCache::set_animation(const Ref<Animation>& p_animation) {
+void AnimationCache::set_animation(const Ref<Animation> &p_animation) {
_clear_cache();
if (animation.is_valid())
- animation->disconnect("changed",this,"_animation_changed");
+ animation->disconnect("changed", this, "_animation_changed");
- animation=p_animation;
+ animation = p_animation;
if (animation.is_valid())
- animation->connect("changed",this,"_animation_changed");
+ animation->connect("changed", this, "_animation_changed");
}
void AnimationCache::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_node_exit_tree"),&AnimationCache::_node_exit_tree);
- ClassDB::bind_method(D_METHOD("_animation_changed"),&AnimationCache::_animation_changed);
+ ClassDB::bind_method(D_METHOD("_node_exit_tree"), &AnimationCache::_node_exit_tree);
+ ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationCache::_animation_changed);
}
-void AnimationCache::set_root(Node* p_root) {
+void AnimationCache::set_root(Node *p_root) {
_clear_cache();
- root=p_root;
+ root = p_root;
}
AnimationCache::AnimationCache() {
- root=NULL;
- cache_dirty=true;
- cache_valid=false;
+ root = NULL;
+ cache_dirty = true;
+ cache_valid = false;
}
diff --git a/scene/animation/animation_cache.h b/scene/animation/animation_cache.h
index 75e004c811..1668c62519 100644
--- a/scene/animation/animation_cache.h
+++ b/scene/animation/animation_cache.h
@@ -29,12 +29,12 @@
#ifndef ANIMATION_CACHE_H
#define ANIMATION_CACHE_H
-#include "scene/resources/animation.h"
#include "scene/3d/skeleton.h"
+#include "scene/resources/animation.h"
class AnimationCache : public Object {
- GDCLASS(AnimationCache,Object);
+ GDCLASS(AnimationCache, Object);
struct Path {
@@ -47,10 +47,17 @@ class AnimationCache : public Object {
int bone_idx;
StringName property;
bool valid;
- Path() { object=NULL; skeleton=NULL; node=NULL; bone_idx=-1; valid=false; spatial=NULL; }
+ Path() {
+ object = NULL;
+ skeleton = NULL;
+ node = NULL;
+ bone_idx = -1;
+ valid = false;
+ spatial = NULL;
+ }
};
- Set<Node*> connected_nodes;
+ Set<Node *> connected_nodes;
Vector<Path> path_cache;
Node *root;
@@ -65,19 +72,17 @@ class AnimationCache : public Object {
void _animation_changed();
protected:
-
static void _bind_methods();
public:
+ void set_track_transform(int p_idx, const Transform &p_transform);
+ void set_track_value(int p_idx, const Variant &p_value);
+ void call_track(int p_idx, const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error);
- void set_track_transform(int p_idx,const Transform& p_transform);
- void set_track_value(int p_idx,const Variant& p_value);
- void call_track(int p_idx,const StringName& p_method,const Variant** p_args,int p_argcount,Variant::CallError &r_error);
-
- void set_all(float p_time, float p_delta=0);
+ void set_all(float p_time, float p_delta = 0);
- void set_animation(const Ref<Animation>& p_animation);
- void set_root(Node* p_root);
+ void set_animation(const Ref<Animation> &p_animation);
+ void set_root(Node *p_root);
AnimationCache();
};
diff --git a/scene/animation/animation_player.cpp b/scene/animation/animation_player.cpp
index e9f1904fe9..dc9aa1758a 100644
--- a/scene/animation/animation_player.cpp
+++ b/scene/animation/animation_player.cpp
@@ -31,111 +31,104 @@
#include "message_queue.h"
#include "scene/scene_string_names.h"
-bool AnimationPlayer::_set(const StringName& p_name, const Variant& p_value) {
+bool AnimationPlayer::_set(const StringName &p_name, const Variant &p_value) {
- String name=p_name;
+ String name = p_name;
- if (p_name==SceneStringNames::get_singleton()->playback_speed || p_name==SceneStringNames::get_singleton()->speed) { //bw compatibility
+ if (p_name == SceneStringNames::get_singleton()->playback_speed || p_name == SceneStringNames::get_singleton()->speed) { //bw compatibility
set_speed_scale(p_value);
- } else if (p_name==SceneStringNames::get_singleton()->playback_active) {
+ } else if (p_name == SceneStringNames::get_singleton()->playback_active) {
set_active(p_value);
} else if (name.begins_with("playback/play")) {
- String which=p_value;
+ String which = p_value;
-
- if (which=="[stop]")
+ if (which == "[stop]")
stop();
else
play(which);
} else if (name.begins_with("anims/")) {
+ String which = name.get_slicec('/', 1);
- String which=name.get_slicec('/',1);
-
- add_animation(which,p_value);
+ add_animation(which, p_value);
} else if (name.begins_with("next/")) {
+ String which = name.get_slicec('/', 1);
+ animation_set_next(which, p_value);
- String which=name.get_slicec('/',1);
- animation_set_next(which,p_value);
-
- } else if (p_name==SceneStringNames::get_singleton()->blend_times) {
+ } else if (p_name == SceneStringNames::get_singleton()->blend_times) {
- Array array=p_value;
+ Array array = p_value;
int len = array.size();
- ERR_FAIL_COND_V(len%3,false);
+ ERR_FAIL_COND_V(len % 3, false);
+ for (int i = 0; i < len / 3; i++) {
- for(int i=0;i<len/3;i++) {
+ StringName from = array[i * 3 + 0];
+ StringName to = array[i * 3 + 1];
+ float time = array[i * 3 + 2];
- StringName from = array[i*3+0];
- StringName to = array[i*3+1];
- float time = array[i*3+2];
-
- set_blend_time(from,to,time);
+ set_blend_time(from, to, time);
}
- } else if (p_name==SceneStringNames::get_singleton()->autoplay) {
- autoplay=p_value;
+ } else if (p_name == SceneStringNames::get_singleton()->autoplay) {
+ autoplay = p_value;
} else
return false;
return true;
-
}
-bool AnimationPlayer::_get(const StringName& p_name,Variant &r_ret) const {
+bool AnimationPlayer::_get(const StringName &p_name, Variant &r_ret) const {
- String name=p_name;
+ String name = p_name;
- if (name=="playback/speed") { //bw compatibility
+ if (name == "playback/speed") { //bw compatibility
- r_ret=speed_scale;
- } else if (name=="playback/active") {
+ r_ret = speed_scale;
+ } else if (name == "playback/active") {
- r_ret=is_active();
- } else if (name=="playback/play") {
+ r_ret = is_active();
+ } else if (name == "playback/play") {
if (is_active() && is_playing())
- r_ret=playback.assigned;
+ r_ret = playback.assigned;
else
- r_ret="[stop]";
+ r_ret = "[stop]";
} else if (name.begins_with("anims/")) {
- String which=name.get_slicec('/',1);
+ String which = name.get_slicec('/', 1);
- r_ret= get_animation(which).get_ref_ptr();
+ r_ret = get_animation(which).get_ref_ptr();
} else if (name.begins_with("next/")) {
- String which=name.get_slicec('/',1);
+ String which = name.get_slicec('/', 1);
- r_ret= animation_get_next(which);
+ r_ret = animation_get_next(which);
-
- } else if (name=="blend_times") {
+ } else if (name == "blend_times") {
Vector<BlendKey> keys;
- for(Map<BlendKey, float >::Element *E=blend_times.front();E;E=E->next()) {
+ for (Map<BlendKey, float>::Element *E = blend_times.front(); E; E = E->next()) {
keys.ordered_insert(E->key());
}
Array array;
- for(int i=0;i<keys.size();i++) {
+ for (int i = 0; i < keys.size(); i++) {
array.push_back(keys[i].from);
array.push_back(keys[i].to);
array.push_back(blend_times[keys[i]]);
}
- r_ret=array;
- } else if (name=="autoplay") {
- r_ret=autoplay;
-
+ r_ret = array;
+ } else if (name == "autoplay") {
+ r_ret = autoplay;
} else
return false;
@@ -143,26 +136,23 @@ bool AnimationPlayer::_get(const StringName& p_name,Variant &r_ret) const {
return true;
}
-void AnimationPlayer::_get_property_list( List<PropertyInfo> *p_list) const {
-
-
-
+void AnimationPlayer::_get_property_list(List<PropertyInfo> *p_list) const {
List<String> names;
List<PropertyInfo> anim_names;
- for( Map<StringName, AnimationData>::Element *E=animation_set.front();E;E=E->next()) {
+ for (Map<StringName, AnimationData>::Element *E = animation_set.front(); E; E = E->next()) {
- anim_names.push_back( PropertyInfo( Variant::OBJECT, "anims/"+String(E->key()), PROPERTY_HINT_RESOURCE_TYPE, "Animation",PROPERTY_USAGE_NOEDITOR) );
- if (E->get().next!=StringName())
- anim_names.push_back( PropertyInfo( Variant::STRING, "next/"+String(E->key()), PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) );
+ anim_names.push_back(PropertyInfo(Variant::OBJECT, "anims/" + String(E->key()), PROPERTY_HINT_RESOURCE_TYPE, "Animation", PROPERTY_USAGE_NOEDITOR));
+ if (E->get().next != StringName())
+ anim_names.push_back(PropertyInfo(Variant::STRING, "next/" + String(E->key()), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
names.push_back(E->key());
}
anim_names.sort();
- for( List<PropertyInfo>::Element *E=anim_names.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = anim_names.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
@@ -170,34 +160,30 @@ void AnimationPlayer::_get_property_list( List<PropertyInfo> *p_list) const {
names.sort();
names.push_front("[stop]");
String hint;
- for(List<String>::Element *E=names.front();E;E=E->next()) {
+ for (List<String>::Element *E = names.front(); E; E = E->next()) {
- if (E!=names.front())
- hint+=",";
- hint+=E->get();
+ if (E != names.front())
+ hint += ",";
+ hint += E->get();
}
- p_list->push_back( PropertyInfo( Variant::STRING, "playback/play", PROPERTY_HINT_ENUM, hint,PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_ANIMATE_AS_TRIGGER) );
- p_list->push_back( PropertyInfo( Variant::BOOL, "playback/active", PROPERTY_HINT_NONE,"" ) );
- p_list->push_back( PropertyInfo( Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01") );
-
+ p_list->push_back(PropertyInfo(Variant::STRING, "playback/play", PROPERTY_HINT_ENUM, hint, PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ANIMATE_AS_TRIGGER));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "playback/active", PROPERTY_HINT_NONE, ""));
+ p_list->push_back(PropertyInfo(Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01"));
}
-
-
- p_list->push_back( PropertyInfo( Variant::ARRAY, "blend_times", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::STRING, "autoplay", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_NOEDITOR) );
-
+ p_list->push_back(PropertyInfo(Variant::ARRAY, "blend_times", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::STRING, "autoplay", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
}
void AnimationPlayer::advance(float p_time) {
- _animation_process( p_time );
+ _animation_process(p_time);
}
void AnimationPlayer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -218,19 +204,19 @@ void AnimationPlayer::_notification(int p_what) {
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
- if (animation_process_mode==ANIMATION_PROCESS_FIXED)
+ if (animation_process_mode == ANIMATION_PROCESS_FIXED)
break;
if (processing)
- _animation_process( get_process_delta_time() );
+ _animation_process(get_process_delta_time());
} break;
case NOTIFICATION_INTERNAL_FIXED_PROCESS: {
- if (animation_process_mode==ANIMATION_PROCESS_IDLE)
+ if (animation_process_mode == ANIMATION_PROCESS_IDLE)
break;
if (processing)
- _animation_process( get_fixed_process_delta_time() );
+ _animation_process(get_fixed_process_delta_time());
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -240,174 +226,164 @@ void AnimationPlayer::_notification(int p_what) {
}
}
-void AnimationPlayer::_generate_node_caches(AnimationData* p_anim) {
+void AnimationPlayer::_generate_node_caches(AnimationData *p_anim) {
Node *parent = get_node(root);
ERR_FAIL_COND(!parent);
- Animation *a=p_anim->animation.operator->();
+ Animation *a = p_anim->animation.operator->();
- p_anim->node_cache.resize( a->get_track_count() );
+ p_anim->node_cache.resize(a->get_track_count());
- for (int i=0;i<a->get_track_count();i++) {
+ for (int i = 0; i < a->get_track_count(); i++) {
- p_anim->node_cache[i]=NULL;
+ p_anim->node_cache[i] = NULL;
RES resource;
- Node *child = parent->get_node_and_resource(a->track_get_path(i),resource);
+ Node *child = parent->get_node_and_resource(a->track_get_path(i), resource);
if (!child) {
- ERR_EXPLAIN("On Animation: '"+p_anim->name+"', couldn't resolve track: '"+String(a->track_get_path(i))+"'");
+ ERR_EXPLAIN("On Animation: '" + p_anim->name + "', couldn't resolve track: '" + String(a->track_get_path(i)) + "'");
}
ERR_CONTINUE(!child); // couldn't find the child node
- uint32_t id=resource.is_valid()?resource->get_instance_ID():child->get_instance_ID();
- int bone_idx=-1;
+ uint32_t id = resource.is_valid() ? resource->get_instance_ID() : child->get_instance_ID();
+ int bone_idx = -1;
if (a->track_get_path(i).get_property() && child->cast_to<Skeleton>()) {
- bone_idx = child->cast_to<Skeleton>()->find_bone( a->track_get_path(i).get_property() );
- if (bone_idx==-1) {
+ bone_idx = child->cast_to<Skeleton>()->find_bone(a->track_get_path(i).get_property());
+ if (bone_idx == -1) {
continue;
}
}
{
- if (!child->is_connected("tree_exited",this,"_node_removed"))
- child->connect("tree_exited",this,"_node_removed",make_binds(child),CONNECT_ONESHOT);
+ if (!child->is_connected("tree_exited", this, "_node_removed"))
+ child->connect("tree_exited", this, "_node_removed", make_binds(child), CONNECT_ONESHOT);
}
TrackNodeCacheKey key;
- key.id=id;
- key.bone_idx=bone_idx;
-
+ key.id = id;
+ key.bone_idx = bone_idx;
if (node_cache_map.has(key)) {
- p_anim->node_cache[i]=&node_cache_map[key];
+ p_anim->node_cache[i] = &node_cache_map[key];
} else {
+ node_cache_map[key] = TrackNodeCache();
- node_cache_map[key]=TrackNodeCache();
-
- p_anim->node_cache[i]=&node_cache_map[key];
- p_anim->node_cache[i]->path=a->track_get_path(i);
- p_anim->node_cache[i]->node=child;
- p_anim->node_cache[i]->resource=resource;
- p_anim->node_cache[i]->node_2d=child->cast_to<Node2D>();
- if (a->track_get_type(i)==Animation::TYPE_TRANSFORM) {
+ p_anim->node_cache[i] = &node_cache_map[key];
+ p_anim->node_cache[i]->path = a->track_get_path(i);
+ p_anim->node_cache[i]->node = child;
+ p_anim->node_cache[i]->resource = resource;
+ p_anim->node_cache[i]->node_2d = child->cast_to<Node2D>();
+ if (a->track_get_type(i) == Animation::TYPE_TRANSFORM) {
// special cases and caches for transform tracks
// cache spatial
- p_anim->node_cache[i]->spatial=child->cast_to<Spatial>();
+ p_anim->node_cache[i]->spatial = child->cast_to<Spatial>();
// cache skeleton
- p_anim->node_cache[i]->skeleton=child->cast_to<Skeleton>();
+ p_anim->node_cache[i]->skeleton = child->cast_to<Skeleton>();
if (p_anim->node_cache[i]->skeleton) {
- StringName bone_name=a->track_get_path(i).get_property();
- if (bone_name.operator String()!="") {
+ StringName bone_name = a->track_get_path(i).get_property();
+ if (bone_name.operator String() != "") {
- p_anim->node_cache[i]->bone_idx=p_anim->node_cache[i]->skeleton->find_bone(bone_name);
- if (p_anim->node_cache[i]->bone_idx<0) {
+ p_anim->node_cache[i]->bone_idx = p_anim->node_cache[i]->skeleton->find_bone(bone_name);
+ if (p_anim->node_cache[i]->bone_idx < 0) {
// broken track (nonexistent bone)
- p_anim->node_cache[i]->skeleton=NULL;
- p_anim->node_cache[i]->spatial=NULL;
+ p_anim->node_cache[i]->skeleton = NULL;
+ p_anim->node_cache[i]->spatial = NULL;
printf("bone is %ls\n", String(bone_name).c_str());
- ERR_CONTINUE( p_anim->node_cache[i]->bone_idx<0 );
+ ERR_CONTINUE(p_anim->node_cache[i]->bone_idx < 0);
} else {
}
} else {
// no property, just use spatialnode
- p_anim->node_cache[i]->skeleton=NULL;
+ p_anim->node_cache[i]->skeleton = NULL;
}
-
}
}
}
- if (a->track_get_type(i)==Animation::TYPE_VALUE) {
+ if (a->track_get_type(i) == Animation::TYPE_VALUE) {
StringName property = a->track_get_path(i).get_property();
if (!p_anim->node_cache[i]->property_anim.has(property)) {
TrackNodeCache::PropertyAnim pa;
- pa.prop=property;
- pa.object=resource.is_valid()?(Object*)resource.ptr():(Object*)child;
- pa.special=SP_NONE;
- pa.owner=p_anim->node_cache[i];
+ pa.prop = property;
+ pa.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child;
+ pa.special = SP_NONE;
+ pa.owner = p_anim->node_cache[i];
if (false && p_anim->node_cache[i]->node_2d) {
- if (pa.prop==SceneStringNames::get_singleton()->transform_pos)
- pa.special=SP_NODE2D_POS;
- else if (pa.prop==SceneStringNames::get_singleton()->transform_rot)
- pa.special=SP_NODE2D_ROT;
- else if (pa.prop==SceneStringNames::get_singleton()->transform_scale)
- pa.special=SP_NODE2D_SCALE;
+ if (pa.prop == SceneStringNames::get_singleton()->transform_pos)
+ pa.special = SP_NODE2D_POS;
+ else if (pa.prop == SceneStringNames::get_singleton()->transform_rot)
+ pa.special = SP_NODE2D_ROT;
+ else if (pa.prop == SceneStringNames::get_singleton()->transform_scale)
+ pa.special = SP_NODE2D_SCALE;
}
- p_anim->node_cache[i]->property_anim[property]=pa;
+ p_anim->node_cache[i]->property_anim[property] = pa;
}
}
}
}
-
-void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p_time, float p_delta,float p_interp, bool p_allow_discrete) {
+void AnimationPlayer::_animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete) {
if (p_anim->node_cache.size() != p_anim->animation->get_track_count()) {
// animation hasn't been "node-cached"
_generate_node_caches(p_anim);
}
+ ERR_FAIL_COND(p_anim->node_cache.size() != p_anim->animation->get_track_count());
- ERR_FAIL_COND( p_anim->node_cache.size() != p_anim->animation->get_track_count() );
-
-
- Animation *a=p_anim->animation.operator->();
+ Animation *a = p_anim->animation.operator->();
bool can_call = is_inside_tree() && !get_tree()->is_editor_hint();
- for (int i=0;i<a->get_track_count();i++) {
+ for (int i = 0; i < a->get_track_count(); i++) {
- TrackNodeCache *nc=p_anim->node_cache[i];
+ TrackNodeCache *nc = p_anim->node_cache[i];
if (!nc) // no node cache for this track, skip it
continue;
- if (a->track_get_key_count(i)==0)
+ if (a->track_get_key_count(i) == 0)
continue; // do nothing if track is empty
- switch(a->track_get_type(i)) {
+ switch (a->track_get_type(i)) {
case Animation::TYPE_TRANSFORM: {
if (!nc->spatial)
continue;
-
Vector3 loc;
Quat rot;
Vector3 scale;
-
- Error err = a->transform_track_interpolate(i,p_time,&loc,&rot,&scale);
+ Error err = a->transform_track_interpolate(i, p_time, &loc, &rot, &scale);
//ERR_CONTINUE(err!=OK); //used for testing, should be removed
-
- if (err!=OK)
+ if (err != OK)
continue;
- if (nc->accum_pass!=accum_pass) {
- ERR_CONTINUE( cache_update_size >= NODE_CACHE_UPDATE_MAX );
- cache_update[cache_update_size++]=nc;
- nc->accum_pass=accum_pass;
- nc->loc_accum=loc;
- nc->rot_accum=rot;
- nc->scale_accum=scale;
+ if (nc->accum_pass != accum_pass) {
+ ERR_CONTINUE(cache_update_size >= NODE_CACHE_UPDATE_MAX);
+ cache_update[cache_update_size++] = nc;
+ nc->accum_pass = accum_pass;
+ nc->loc_accum = loc;
+ nc->rot_accum = rot;
+ nc->scale_accum = scale;
} else {
- nc->loc_accum=nc->loc_accum.linear_interpolate(loc,p_interp);
- nc->rot_accum=nc->rot_accum.slerp(rot,p_interp);
- nc->scale_accum=nc->scale_accum.linear_interpolate(scale,p_interp);
-
+ nc->loc_accum = nc->loc_accum.linear_interpolate(loc, p_interp);
+ nc->rot_accum = nc->rot_accum.slerp(rot, p_interp);
+ nc->scale_accum = nc->scale_accum.linear_interpolate(scale, p_interp);
}
} break;
@@ -418,82 +394,76 @@ void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p
//StringName property=a->track_get_path(i).get_property();
- Map<StringName,TrackNodeCache::PropertyAnim>::Element *E=nc->property_anim.find(a->track_get_path(i).get_property());
+ Map<StringName, TrackNodeCache::PropertyAnim>::Element *E = nc->property_anim.find(a->track_get_path(i).get_property());
ERR_CONTINUE(!E); //should it continue, or create a new one?
TrackNodeCache::PropertyAnim *pa = &E->get();
+ if (a->value_track_get_update_mode(i) == Animation::UPDATE_CONTINUOUS || (p_delta == 0 && a->value_track_get_update_mode(i) == Animation::UPDATE_DISCRETE)) { //delta == 0 means seek
- if (a->value_track_get_update_mode(i)==Animation::UPDATE_CONTINUOUS || (p_delta==0 && a->value_track_get_update_mode(i)==Animation::UPDATE_DISCRETE)) { //delta == 0 means seek
-
-
- Variant value=a->value_track_interpolate(i,p_time);
+ Variant value = a->value_track_interpolate(i, p_time);
//thanks to trigger mode, this should be solved now..
/*
if (p_delta==0 && value.get_type()==Variant::STRING)
continue; // doing this with strings is messy, should find another way
*/
- if (pa->accum_pass!=accum_pass) {
- ERR_CONTINUE( cache_update_prop_size >= NODE_CACHE_UPDATE_MAX );
- cache_update_prop[cache_update_prop_size++]=pa;
- pa->value_accum=value;
- pa->accum_pass=accum_pass;
+ if (pa->accum_pass != accum_pass) {
+ ERR_CONTINUE(cache_update_prop_size >= NODE_CACHE_UPDATE_MAX);
+ cache_update_prop[cache_update_prop_size++] = pa;
+ pa->value_accum = value;
+ pa->accum_pass = accum_pass;
} else {
- Variant::interpolate(pa->value_accum,value,p_interp,pa->value_accum);
+ Variant::interpolate(pa->value_accum, value, p_interp, pa->value_accum);
}
-
- } else if (p_allow_discrete && p_delta!=0) {
+ } else if (p_allow_discrete && p_delta != 0) {
List<int> indices;
- a->value_track_get_key_indices(i,p_time,p_delta,&indices);
-
+ a->value_track_get_key_indices(i, p_time, p_delta, &indices);
- for(List<int>::Element *F=indices.front();F;F=F->next()) {
+ for (List<int>::Element *F = indices.front(); F; F = F->next()) {
- Variant value=a->track_get_key_value(i,F->get());
- switch(pa->special) {
+ Variant value = a->track_get_key_value(i, F->get());
+ switch (pa->special) {
case SP_NONE: {
bool valid;
- pa->object->set(pa->prop,value,&valid); //you are not speshul
+ pa->object->set(pa->prop, value, &valid); //you are not speshul
#ifdef DEBUG_ENABLED
if (!valid) {
- ERR_PRINTS("Failed setting track value '"+String(pa->owner->path)+"'. Check if property exists or the type of key is valid");
+ ERR_PRINTS("Failed setting track value '" + String(pa->owner->path) + "'. Check if property exists or the type of key is valid");
}
#endif
} break;
case SP_NODE2D_POS: {
#ifdef DEBUG_ENABLED
- if (value.get_type()!=Variant::VECTOR2) {
- ERR_PRINTS("Position key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not of type Vector2()");
+ if (value.get_type() != Variant::VECTOR2) {
+ ERR_PRINTS("Position key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not of type Vector2()");
}
#endif
- static_cast<Node2D*>(pa->object)->set_position(value);
+ static_cast<Node2D *>(pa->object)->set_position(value);
} break;
case SP_NODE2D_ROT: {
#ifdef DEBUG_ENABLED
if (value.is_num()) {
- ERR_PRINTS("Rotation key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not numerical");
+ ERR_PRINTS("Rotation key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not numerical");
}
#endif
- static_cast<Node2D*>(pa->object)->set_rotation(Math::deg2rad((double)value));
+ static_cast<Node2D *>(pa->object)->set_rotation(Math::deg2rad((double)value));
} break;
case SP_NODE2D_SCALE: {
#ifdef DEBUG_ENABLED
- if (value.get_type()!=Variant::VECTOR2) {
- ERR_PRINTS("Scale key at time "+rtos(p_time)+" in Animation Track '"+String(pa->owner->path)+"' not of type Vector2()");
+ if (value.get_type() != Variant::VECTOR2) {
+ ERR_PRINTS("Scale key at time " + rtos(p_time) + " in Animation Track '" + String(pa->owner->path) + "' not of type Vector2()");
}
#endif
- static_cast<Node2D*>(pa->object)->set_scale(value);
+ static_cast<Node2D *>(pa->object)->set_scale(value);
} break;
}
-
}
-
}
} break;
@@ -501,154 +471,142 @@ void AnimationPlayer::_animation_process_animation(AnimationData* p_anim,float p
if (!nc->node)
continue;
- if (p_delta==0)
+ if (p_delta == 0)
continue;
if (!p_allow_discrete)
break;
List<int> indices;
- a->method_track_get_key_indices(i,p_time,p_delta,&indices);
+ a->method_track_get_key_indices(i, p_time, p_delta, &indices);
- for(List<int>::Element *E=indices.front();E;E=E->next()) {
+ for (List<int>::Element *E = indices.front(); E; E = E->next()) {
- StringName method=a->method_track_get_name(i,E->get());
- Vector<Variant> params=a->method_track_get_params(i,E->get());
+ StringName method = a->method_track_get_name(i, E->get());
+ Vector<Variant> params = a->method_track_get_params(i, E->get());
- int s=params.size();
+ int s = params.size();
- ERR_CONTINUE( s > VARIANT_ARG_MAX );
+ ERR_CONTINUE(s > VARIANT_ARG_MAX);
if (can_call) {
MessageQueue::get_singleton()->push_call(
- nc->node,
- method,
- s>=1 ? params[0] : Variant(),
- s>=2 ? params[1] : Variant(),
- s>=3 ? params[2] : Variant(),
- s>=4 ? params[3] : Variant(),
- s>=5 ? params[4] : Variant()
- );
+ nc->node,
+ method,
+ s >= 1 ? params[0] : Variant(),
+ s >= 2 ? params[1] : Variant(),
+ s >= 3 ? params[2] : Variant(),
+ s >= 4 ? params[3] : Variant(),
+ s >= 5 ? params[4] : Variant());
}
}
-
} break;
}
}
}
-void AnimationPlayer::_animation_process_data(PlaybackData &cd,float p_delta,float p_blend) {
+void AnimationPlayer::_animation_process_data(PlaybackData &cd, float p_delta, float p_blend) {
- float delta=p_delta*speed_scale*cd.speed_scale;
- bool backwards=delta<0;
- float next_pos=cd.pos+delta;
+ float delta = p_delta * speed_scale * cd.speed_scale;
+ bool backwards = delta < 0;
+ float next_pos = cd.pos + delta;
- float len=cd.from->animation->get_length();
- bool loop=cd.from->animation->has_loop();
+ float len = cd.from->animation->get_length();
+ bool loop = cd.from->animation->has_loop();
if (!loop) {
- if (next_pos<0)
- next_pos=0;
- else if (next_pos>len)
- next_pos=len;
+ if (next_pos < 0)
+ next_pos = 0;
+ else if (next_pos > len)
+ next_pos = len;
// fix delta
- delta=next_pos-cd.pos;
+ delta = next_pos - cd.pos;
if (&cd == &playback.current) {
- if (!backwards && cd.pos < len && next_pos==len /*&& playback.blend.empty()*/) {
+ if (!backwards && cd.pos < len && next_pos == len /*&& playback.blend.empty()*/) {
//playback finished
- end_notify=true;
+ end_notify = true;
}
- if (backwards && cd.pos > 0 && next_pos==0 /*&& playback.blend.empty()*/) {
+ if (backwards && cd.pos > 0 && next_pos == 0 /*&& playback.blend.empty()*/) {
//playback finished
- end_notify=true;
+ end_notify = true;
}
-
}
} else {
- next_pos=Math::fposmod(next_pos,len);
-
+ next_pos = Math::fposmod(next_pos, len);
}
- cd.pos=next_pos;
-
- _animation_process_animation(cd.from,cd.pos,delta,p_blend,&cd == &playback.current);
-
-
+ cd.pos = next_pos;
+ _animation_process_animation(cd.from, cd.pos, delta, p_blend, &cd == &playback.current);
}
void AnimationPlayer::_animation_process2(float p_delta) {
-
- Playback &c=playback;
+ Playback &c = playback;
accum_pass++;
- _animation_process_data(c.current,p_delta,1.0f);
+ _animation_process_data(c.current, p_delta, 1.0f);
List<Blend>::Element *prev = NULL;
- for (List<Blend>::Element *E=c.blend.back();E;E=prev) {
+ for (List<Blend>::Element *E = c.blend.back(); E; E = prev) {
- Blend& b=E->get();
- float blend=b.blend_left/b.blend_time;
- _animation_process_data(b.data,p_delta,blend);
+ Blend &b = E->get();
+ float blend = b.blend_left / b.blend_time;
+ _animation_process_data(b.data, p_delta, blend);
- b.blend_left-=Math::absf(speed_scale*p_delta);
+ b.blend_left -= Math::absf(speed_scale * p_delta);
prev = E->prev();
- if (b.blend_left<0) {
+ if (b.blend_left < 0) {
c.blend.erase(E);
}
}
-
-
}
void AnimationPlayer::_animation_update_transforms() {
+ for (int i = 0; i < cache_update_size; i++) {
- for (int i=0;i<cache_update_size;i++) {
+ TrackNodeCache *nc = cache_update[i];
- TrackNodeCache *nc=cache_update[i];
-
- ERR_CONTINUE( nc->accum_pass!=accum_pass );
+ ERR_CONTINUE(nc->accum_pass != accum_pass);
if (nc->spatial) {
Transform t;
- t.origin=nc->loc_accum;
- t.basis=nc->rot_accum;
- t.basis.scale( nc->scale_accum );
+ t.origin = nc->loc_accum;
+ t.basis = nc->rot_accum;
+ t.basis.scale(nc->scale_accum);
- if (nc->skeleton && nc->bone_idx>=0) {
+ if (nc->skeleton && nc->bone_idx >= 0) {
- nc->skeleton->set_bone_pose( nc->bone_idx, t );
+ nc->skeleton->set_bone_pose(nc->bone_idx, t);
} else if (nc->spatial) {
nc->spatial->set_transform(t);
}
}
-
}
- cache_update_size=0;
+ cache_update_size = 0;
- for (int i=0;i<cache_update_prop_size;i++) {
+ for (int i = 0; i < cache_update_prop_size; i++) {
- TrackNodeCache::PropertyAnim *pa=cache_update_prop[i];
+ TrackNodeCache::PropertyAnim *pa = cache_update_prop[i];
- ERR_CONTINUE( pa->accum_pass!=accum_pass );
+ ERR_CONTINUE(pa->accum_pass != accum_pass);
#if 1
-/* switch(pa->special) {
+ /* switch(pa->special) {
case SP_NONE: pa->object->set(pa->prop,pa->value_accum); break; //you are not speshul
@@ -657,63 +615,61 @@ void AnimationPlayer::_animation_update_transforms() {
case SP_NODE2D_SCALE: static_cast<Node2D*>(pa->object)->set_scale(pa->value_accum); break;
}*/
- switch(pa->special) {
+ switch (pa->special) {
case SP_NONE: {
bool valid;
- pa->object->set(pa->prop,pa->value_accum,&valid); //you are not speshul
+ pa->object->set(pa->prop, pa->value_accum, &valid); //you are not speshul
#ifdef DEBUG_ENABLED
if (!valid) {
- ERR_PRINTS("Failed setting key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"'. Check if property exists or the type of key is right for the property");
+ ERR_PRINTS("Failed setting key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "'. Check if property exists or the type of key is right for the property");
}
#endif
} break;
case SP_NODE2D_POS: {
#ifdef DEBUG_ENABLED
- if (pa->value_accum.get_type()!=Variant::VECTOR2) {
- ERR_PRINTS("Position key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not of type Vector2()");
+ if (pa->value_accum.get_type() != Variant::VECTOR2) {
+ ERR_PRINTS("Position key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not of type Vector2()");
}
#endif
- static_cast<Node2D*>(pa->object)->set_position(pa->value_accum);
+ static_cast<Node2D *>(pa->object)->set_position(pa->value_accum);
} break;
case SP_NODE2D_ROT: {
#ifdef DEBUG_ENABLED
if (pa->value_accum.is_num()) {
- ERR_PRINTS("Rotation key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not numerical");
+ ERR_PRINTS("Rotation key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not numerical");
}
#endif
- static_cast<Node2D*>(pa->object)->set_rotation(Math::deg2rad((double)pa->value_accum));
+ static_cast<Node2D *>(pa->object)->set_rotation(Math::deg2rad((double)pa->value_accum));
} break;
case SP_NODE2D_SCALE: {
#ifdef DEBUG_ENABLED
- if (pa->value_accum.get_type()!=Variant::VECTOR2) {
- ERR_PRINTS("Scale key at time "+rtos(playback.current.pos)+" in Animation '"+get_current_animation()+"', Track '"+String(pa->owner->path)+"' not of type Vector2()");
+ if (pa->value_accum.get_type() != Variant::VECTOR2) {
+ ERR_PRINTS("Scale key at time " + rtos(playback.current.pos) + " in Animation '" + get_current_animation() + "', Track '" + String(pa->owner->path) + "' not of type Vector2()");
}
#endif
- static_cast<Node2D*>(pa->object)->set_scale(pa->value_accum);
+ static_cast<Node2D *>(pa->object)->set_scale(pa->value_accum);
} break;
}
#else
- pa->object->set(pa->prop,pa->value_accum);
+ pa->object->set(pa->prop, pa->value_accum);
#endif
}
- cache_update_prop_size=0;
+ cache_update_prop_size = 0;
}
void AnimationPlayer::_animation_process(float p_delta) {
-
-
//bool any_active=false;
if (playback.current.from) {
- end_notify=false;
+ end_notify = false;
_animation_process2(p_delta);
_animation_update_transforms();
if (end_notify) {
@@ -722,46 +678,44 @@ void AnimationPlayer::_animation_process(float p_delta) {
play(queued.front()->get());
String new_name = playback.assigned;
queued.pop_front();
- end_notify=false;
+ end_notify = false;
emit_signal(SceneStringNames::get_singleton()->animation_changed, old, new_name);
} else {
- //stop();
+ //stop();
playing = false;
_set_process(false);
- end_notify=false;
- emit_signal(SceneStringNames::get_singleton()->animation_finished,playback.assigned);
+ end_notify = false;
+ emit_signal(SceneStringNames::get_singleton()->animation_finished, playback.assigned);
}
}
} else {
_set_process(false);
}
-
}
-
-Error AnimationPlayer::add_animation(const StringName& p_name, const Ref<Animation>& p_animation) {
+Error AnimationPlayer::add_animation(const StringName &p_name, const Ref<Animation> &p_animation) {
#ifdef DEBUG_ENABLED
- ERR_EXPLAIN("Invalid animation name: "+String(p_name));
- ERR_FAIL_COND_V( String(p_name).find("/")!=-1 || String(p_name).find(":")!=-1 || String(p_name).find(",")!=-1 || String(p_name).find("[")!=-1, ERR_INVALID_PARAMETER );
+ ERR_EXPLAIN("Invalid animation name: " + String(p_name));
+ ERR_FAIL_COND_V(String(p_name).find("/") != -1 || String(p_name).find(":") != -1 || String(p_name).find(",") != -1 || String(p_name).find("[") != -1, ERR_INVALID_PARAMETER);
#endif
- ERR_FAIL_COND_V( p_animation.is_null() , ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_animation.is_null(), ERR_INVALID_PARAMETER);
//print_line("Add anim: "+String(p_name)+" name: "+p_animation->get_name());
if (animation_set.has(p_name)) {
_unref_anim(animation_set[p_name].animation);
- animation_set[p_name].animation=p_animation;
+ animation_set[p_name].animation = p_animation;
clear_caches();
} else {
AnimationData ad;
- ad.animation=p_animation;
- ad.name=p_name;
- animation_set[p_name]=ad;
+ ad.animation = p_animation;
+ ad.name = p_name;
+ animation_set[p_name] = ad;
}
_ref_anim(p_animation);
@@ -769,9 +723,9 @@ Error AnimationPlayer::add_animation(const StringName& p_name, const Ref<Animati
return OK;
}
-void AnimationPlayer::remove_animation(const StringName& p_name) {
+void AnimationPlayer::remove_animation(const StringName &p_name) {
- ERR_FAIL_COND(!animation_set.has(p_name) );
+ ERR_FAIL_COND(!animation_set.has(p_name));
stop_all();
_unref_anim(animation_set[p_name].animation);
@@ -779,154 +733,140 @@ void AnimationPlayer::remove_animation(const StringName& p_name) {
clear_caches();
_change_notify();
-
}
-void AnimationPlayer::_ref_anim(const Ref<Animation>& p_anim) {
+void AnimationPlayer::_ref_anim(const Ref<Animation> &p_anim) {
if (used_anims.has(p_anim))
used_anims[p_anim]++;
else {
- used_anims[p_anim]=1;
- Ref<Animation>(p_anim)->connect("changed",this,"_animation_changed");
+ used_anims[p_anim] = 1;
+ Ref<Animation>(p_anim)->connect("changed", this, "_animation_changed");
}
-
}
-void AnimationPlayer::_unref_anim(const Ref<Animation>& p_anim) {
+void AnimationPlayer::_unref_anim(const Ref<Animation> &p_anim) {
ERR_FAIL_COND(!used_anims.has(p_anim));
-
- int & n = used_anims[p_anim];
+ int &n = used_anims[p_anim];
n--;
- if (n==0) {
+ if (n == 0) {
- Ref<Animation>(p_anim)->disconnect("changed",this,"_animation_changed");
+ Ref<Animation>(p_anim)->disconnect("changed", this, "_animation_changed");
used_anims.erase(p_anim);
}
-
}
+void AnimationPlayer::rename_animation(const StringName &p_name, const StringName &p_new_name) {
-void AnimationPlayer::rename_animation(const StringName& p_name,const StringName& p_new_name) {
-
-
- ERR_FAIL_COND(!animation_set.has(p_name) );
- ERR_FAIL_COND( String(p_new_name).find("/")!=-1 || String(p_new_name).find(":")!=-1 );
- ERR_FAIL_COND( animation_set.has(p_new_name) );
+ ERR_FAIL_COND(!animation_set.has(p_name));
+ ERR_FAIL_COND(String(p_new_name).find("/") != -1 || String(p_new_name).find(":") != -1);
+ ERR_FAIL_COND(animation_set.has(p_new_name));
//print_line("Rename anim: "+String(p_name)+" name: "+String(p_new_name));
stop_all();
AnimationData ad = animation_set[p_name];
- ad.name=p_new_name;
+ ad.name = p_new_name;
animation_set.erase(p_name);
- animation_set[p_new_name]=ad;
+ animation_set[p_new_name] = ad;
List<BlendKey> to_erase;
- Map<BlendKey,float> to_insert;
- for(Map<BlendKey, float >::Element *E=blend_times.front();E;E=E->next()) {
-
- BlendKey bk=E->key();
- BlendKey new_bk=bk;
- bool erase=false;
- if (bk.from==p_name) {
- new_bk.from=p_new_name;
- erase=true;
+ Map<BlendKey, float> to_insert;
+ for (Map<BlendKey, float>::Element *E = blend_times.front(); E; E = E->next()) {
+
+ BlendKey bk = E->key();
+ BlendKey new_bk = bk;
+ bool erase = false;
+ if (bk.from == p_name) {
+ new_bk.from = p_new_name;
+ erase = true;
}
- if (bk.to==p_name) {
- new_bk.to=p_new_name;
- erase=true;
+ if (bk.to == p_name) {
+ new_bk.to = p_new_name;
+ erase = true;
}
if (erase) {
to_erase.push_back(bk);
- to_insert[new_bk]=E->get();
+ to_insert[new_bk] = E->get();
}
}
- while(to_erase.size()) {
+ while (to_erase.size()) {
blend_times.erase(to_erase.front()->get());
to_erase.pop_front();
}
- while(to_insert.size()) {
- blend_times[to_insert.front()->key()]=to_insert.front()->get();
+ while (to_insert.size()) {
+ blend_times[to_insert.front()->key()] = to_insert.front()->get();
to_insert.erase(to_insert.front());
}
- if (autoplay==p_name)
- autoplay=p_new_name;
+ if (autoplay == p_name)
+ autoplay = p_new_name;
clear_caches();
_change_notify();
}
-
-bool AnimationPlayer::has_animation(const StringName& p_name) const {
+bool AnimationPlayer::has_animation(const StringName &p_name) const {
return animation_set.has(p_name);
}
-Ref<Animation> AnimationPlayer::get_animation(const StringName& p_name) const {
+Ref<Animation> AnimationPlayer::get_animation(const StringName &p_name) const {
- ERR_FAIL_COND_V( !animation_set.has(p_name), Ref<Animation>() );
+ ERR_FAIL_COND_V(!animation_set.has(p_name), Ref<Animation>());
- const AnimationData& data = animation_set[p_name];
+ const AnimationData &data = animation_set[p_name];
return data.animation;
-
}
-void AnimationPlayer::get_animation_list( List<StringName> * p_animations) const {
+void AnimationPlayer::get_animation_list(List<StringName> *p_animations) const {
List<String> anims;
- for( Map<StringName, AnimationData>::Element *E=animation_set.front();E;E=E->next()) {
+ for (Map<StringName, AnimationData>::Element *E = animation_set.front(); E; E = E->next()) {
anims.push_back(E->key());
}
anims.sort();
- for(List<String>::Element *E=anims.front();E;E=E->next()) {
+ for (List<String>::Element *E = anims.front(); E; E = E->next()) {
p_animations->push_back(E->get());
}
-
}
-void AnimationPlayer::set_blend_time(const StringName& p_animation1, const StringName& p_animation2, float p_time) {
+void AnimationPlayer::set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time) {
- ERR_FAIL_COND(p_time<0);
+ ERR_FAIL_COND(p_time < 0);
BlendKey bk;
- bk.from=p_animation1;
- bk.to=p_animation2;
- if (p_time==0)
+ bk.from = p_animation1;
+ bk.to = p_animation2;
+ if (p_time == 0)
blend_times.erase(bk);
else
- blend_times[bk]=p_time;
-
+ blend_times[bk] = p_time;
}
-
-float AnimationPlayer::get_blend_time( const StringName& p_animation1, const StringName& p_animation2) const {
+float AnimationPlayer::get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const {
BlendKey bk;
- bk.from=p_animation1;
- bk.to=p_animation2;
+ bk.from = p_animation1;
+ bk.to = p_animation2;
if (blend_times.has(bk))
return blend_times[bk];
else
return 0;
-
-
}
-
-void AnimationPlayer::queue(const StringName& p_name) {
+void AnimationPlayer::queue(const StringName &p_name) {
if (!is_playing())
play(p_name);
@@ -938,73 +878,73 @@ void AnimationPlayer::clear_queue() {
queued.clear();
};
-void AnimationPlayer::play_backwards(const StringName& p_name,float p_custom_blend) {
+void AnimationPlayer::play_backwards(const StringName &p_name, float p_custom_blend) {
- play(p_name,p_custom_blend,-1,true);
+ play(p_name, p_custom_blend, -1, true);
}
-void AnimationPlayer::play(const StringName& p_name, float p_custom_blend, float p_custom_scale,bool p_from_end) {
+void AnimationPlayer::play(const StringName &p_name, float p_custom_blend, float p_custom_scale, bool p_from_end) {
//printf("animation is %ls\n", String(p_name).c_str());
//ERR_FAIL_COND(!is_inside_scene());
- StringName name=p_name;
+ StringName name = p_name;
- if (String(name)=="")
- name=playback.assigned;
+ if (String(name) == "")
+ name = playback.assigned;
if (!animation_set.has(name)) {
- ERR_EXPLAIN("Animation not found: "+name);
+ ERR_EXPLAIN("Animation not found: " + name);
ERR_FAIL();
}
- Playback &c=playback;
+ Playback &c = playback;
if (c.current.from) {
- float blend_time=0;
+ float blend_time = 0;
// find if it can blend
BlendKey bk;
- bk.from=c.current.from->name;
- bk.to=name;
+ bk.from = c.current.from->name;
+ bk.to = name;
- if (p_custom_blend>=0) {
- blend_time=p_custom_blend;
+ if (p_custom_blend >= 0) {
+ blend_time = p_custom_blend;
} else if (blend_times.has(bk)) {
- blend_time=blend_times[bk];
+ blend_time = blend_times[bk];
} else {
- bk.from="*";
+ bk.from = "*";
if (blend_times.has(bk)) {
- blend_time=blend_times[bk];
+ blend_time = blend_times[bk];
} else {
- bk.from=c.current.from->name;
- bk.to="*";
+ bk.from = c.current.from->name;
+ bk.to = "*";
if (blend_times.has(bk)) {
- blend_time=blend_times[bk];
+ blend_time = blend_times[bk];
}
}
}
- if (p_custom_blend<0 && blend_time==0 && default_blend_time)
- blend_time=default_blend_time;
- if (blend_time>0) {
+ if (p_custom_blend < 0 && blend_time == 0 && default_blend_time)
+ blend_time = default_blend_time;
+ if (blend_time > 0) {
Blend b;
- b.data=c.current;
- b.blend_time=b.blend_left=blend_time;
+ b.data = c.current;
+ b.blend_time = b.blend_left = blend_time;
c.blend.push_back(b);
}
}
- c.current.from=&animation_set[name];
- c.current.pos=p_from_end ? c.current.from->animation->get_length() : 0;
- c.current.speed_scale=p_custom_scale;
- c.assigned=p_name;
+ c.current.from = &animation_set[name];
+ c.current.pos = p_from_end ? c.current.from->animation->get_length() : 0;
+ c.current.speed_scale = p_custom_scale;
+ c.assigned = p_name;
if (!end_notify)
queued.clear();
@@ -1013,20 +953,19 @@ void AnimationPlayer::play(const StringName& p_name, float p_custom_blend, float
emit_signal(SceneStringNames::get_singleton()->animation_started, c.assigned);
- if (is_inside_tree() && get_tree()->is_editor_hint())
+ if (is_inside_tree() && get_tree()->is_editor_hint())
return; // no next in this case
-
- StringName next=animation_get_next(p_name);
- if (next!=StringName() && animation_set.has(next)) {
+ StringName next = animation_get_next(p_name);
+ if (next != StringName() && animation_set.has(next)) {
queue(next);
}
}
bool AnimationPlayer::is_playing() const {
- return playing;
- /*
+ return playing;
+ /*
if (playback.current.from==NULL)
return false;
@@ -1040,30 +979,29 @@ bool AnimationPlayer::is_playing() const {
return true;
*/
}
-void AnimationPlayer::set_current_animation(const String& p_anim) {
+void AnimationPlayer::set_current_animation(const String &p_anim) {
if (is_playing()) {
play(p_anim);
} else {
ERR_FAIL_COND(!animation_set.has(p_anim));
- playback.current.pos=0;
- playback.current.from=&animation_set[p_anim];
- playback.assigned=p_anim;
+ playback.current.pos = 0;
+ playback.current.from = &animation_set[p_anim];
+ playback.assigned = p_anim;
}
}
String AnimationPlayer::get_current_animation() const {
return (playback.assigned);
-
}
void AnimationPlayer::stop(bool p_reset) {
- Playback &c=playback;
+ Playback &c = playback;
c.blend.clear();
if (p_reset) {
- c.current.from=NULL;
+ c.current.from = NULL;
}
_set_process(false);
queued.clear();
@@ -1075,22 +1013,18 @@ void AnimationPlayer::stop_all() {
stop();
_set_process(false); // always process when starting an animation
-
}
void AnimationPlayer::set_speed_scale(float p_speed) {
- speed_scale=p_speed;
-
-
+ speed_scale = p_speed;
}
float AnimationPlayer::get_speed_scale() const {
return speed_scale;
}
-void AnimationPlayer::seek(float p_time,bool p_update) {
-
+void AnimationPlayer::seek(float p_time, bool p_update) {
if (!playback.current.from) {
if (playback.assigned)
@@ -1098,13 +1032,13 @@ void AnimationPlayer::seek(float p_time,bool p_update) {
ERR_FAIL_COND(!playback.current.from);
}
- playback.current.pos=p_time;
+ playback.current.pos = p_time;
if (p_update) {
_animation_process(0);
}
}
-void AnimationPlayer::seek_delta(float p_time,float p_delta) {
+void AnimationPlayer::seek_delta(float p_time, float p_delta) {
if (!playback.current.from) {
if (playback.assigned)
@@ -1112,30 +1046,27 @@ void AnimationPlayer::seek_delta(float p_time,float p_delta) {
ERR_FAIL_COND(!playback.current.from);
}
-
- playback.current.pos=p_time-p_delta;
- if (speed_scale!=0.0)
- p_delta/=speed_scale;
+ playback.current.pos = p_time - p_delta;
+ if (speed_scale != 0.0)
+ p_delta /= speed_scale;
_animation_process(p_delta);
//playback.current.pos=p_time;
-
}
bool AnimationPlayer::is_valid() const {
return (playback.current.from);
-
}
float AnimationPlayer::get_current_animation_pos() const {
- ERR_FAIL_COND_V(!playback.current.from,0);
+ ERR_FAIL_COND_V(!playback.current.from, 0);
return playback.current.pos;
}
float AnimationPlayer::get_current_animation_length() const {
- ERR_FAIL_COND_V(!playback.current.from,0);
+ ERR_FAIL_COND_V(!playback.current.from, 0);
return playback.current.from->animation->get_length();
}
@@ -1151,27 +1082,24 @@ void AnimationPlayer::_node_removed(Node *p_node) {
void AnimationPlayer::clear_caches() {
-
node_cache_map.clear();
- for( Map<StringName, AnimationData>::Element *E=animation_set.front();E;E=E->next()) {
+ for (Map<StringName, AnimationData>::Element *E = animation_set.front(); E; E = E->next()) {
E->get().node_cache.clear();
}
- cache_update_size=0;
- cache_update_prop_size=0;
+ cache_update_size = 0;
+ cache_update_prop_size = 0;
}
void AnimationPlayer::set_active(bool p_active) {
- if (active==p_active)
+ if (active == p_active)
return;
- active=p_active;
- _set_process(processing,true);
-
-
+ active = p_active;
+ _set_process(processing, true);
}
bool AnimationPlayer::is_active() const {
@@ -1179,90 +1107,85 @@ bool AnimationPlayer::is_active() const {
return active;
}
-StringName AnimationPlayer::find_animation(const Ref<Animation>& p_animation) const {
+StringName AnimationPlayer::find_animation(const Ref<Animation> &p_animation) const {
- for( Map<StringName, AnimationData>::Element *E=animation_set.front();E;E=E->next()) {
+ for (Map<StringName, AnimationData>::Element *E = animation_set.front(); E; E = E->next()) {
- if (E->get().animation==p_animation)
+ if (E->get().animation == p_animation)
return E->key();
}
return "";
}
-void AnimationPlayer::set_autoplay(const String& p_name) {
+void AnimationPlayer::set_autoplay(const String &p_name) {
- autoplay=p_name;
+ autoplay = p_name;
}
-String AnimationPlayer::get_autoplay() const{
+String AnimationPlayer::get_autoplay() const {
return autoplay;
}
void AnimationPlayer::set_animation_process_mode(AnimationProcessMode p_mode) {
- if (animation_process_mode==p_mode)
+ if (animation_process_mode == p_mode)
return;
bool pr = processing;
if (pr)
_set_process(false);
- animation_process_mode=p_mode;
+ animation_process_mode = p_mode;
if (pr)
_set_process(true);
-
}
-AnimationPlayer::AnimationProcessMode AnimationPlayer::get_animation_process_mode() const{
+AnimationPlayer::AnimationProcessMode AnimationPlayer::get_animation_process_mode() const {
return animation_process_mode;
}
+void AnimationPlayer::_set_process(bool p_process, bool p_force) {
-void AnimationPlayer::_set_process(bool p_process,bool p_force) {
-
- if (processing==p_process && !p_force)
+ if (processing == p_process && !p_force)
return;
- switch(animation_process_mode) {
+ switch (animation_process_mode) {
case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break;
case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break;
}
- processing=p_process;
+ processing = p_process;
}
-void AnimationPlayer::animation_set_next(const StringName& p_animation, const StringName& p_next) {
+void AnimationPlayer::animation_set_next(const StringName &p_animation, const StringName &p_next) {
ERR_FAIL_COND(!animation_set.has(p_animation));
- animation_set[p_animation].next=p_next;
-
+ animation_set[p_animation].next = p_next;
}
-StringName AnimationPlayer::animation_get_next(const StringName& p_animation) const{
+StringName AnimationPlayer::animation_get_next(const StringName &p_animation) const {
if (!animation_set.has(p_animation))
return StringName();
return animation_set[p_animation].next;
-
}
void AnimationPlayer::set_default_blend_time(float p_default) {
- default_blend_time=p_default;
+ default_blend_time = p_default;
}
float AnimationPlayer::get_default_blend_time() const {
- return default_blend_time;
+ return default_blend_time;
}
+void AnimationPlayer::set_root(const NodePath &p_root) {
-void AnimationPlayer::set_root(const NodePath& p_root) {
-
- root=p_root;
+ root = p_root;
clear_caches();
}
@@ -1271,111 +1194,105 @@ NodePath AnimationPlayer::get_root() const {
return root;
}
-void AnimationPlayer::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
+void AnimationPlayer::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
String pf = p_function;
- if (p_function=="play" || p_function=="remove_animation" || p_function=="has_animation" || p_function=="queue") {
+ if (p_function == "play" || p_function == "remove_animation" || p_function == "has_animation" || p_function == "queue") {
List<StringName> al;
get_animation_list(&al);
- for (List<StringName>::Element *E=al.front();E;E=E->next()) {
+ for (List<StringName>::Element *E = al.front(); E; E = E->next()) {
- r_options->push_back("\""+String(E->get())+"\"");
+ r_options->push_back("\"" + String(E->get()) + "\"");
}
}
- Node::get_argument_options(p_function,p_idx,r_options);
+ Node::get_argument_options(p_function, p_idx, r_options);
}
void AnimationPlayer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_node_removed"),&AnimationPlayer::_node_removed);
- ClassDB::bind_method(D_METHOD("_animation_changed"),&AnimationPlayer::_animation_changed);
+ ClassDB::bind_method(D_METHOD("_node_removed"), &AnimationPlayer::_node_removed);
+ ClassDB::bind_method(D_METHOD("_animation_changed"), &AnimationPlayer::_animation_changed);
- ClassDB::bind_method(D_METHOD("add_animation","name","animation:Animation"),&AnimationPlayer::add_animation);
- ClassDB::bind_method(D_METHOD("remove_animation","name"),&AnimationPlayer::remove_animation);
- ClassDB::bind_method(D_METHOD("rename_animation","name","newname"),&AnimationPlayer::rename_animation);
- ClassDB::bind_method(D_METHOD("has_animation","name"),&AnimationPlayer::has_animation);
- ClassDB::bind_method(D_METHOD("get_animation:Animation","name"),&AnimationPlayer::get_animation);
- ClassDB::bind_method(D_METHOD("get_animation_list"),&AnimationPlayer::_get_animation_list);
+ ClassDB::bind_method(D_METHOD("add_animation", "name", "animation:Animation"), &AnimationPlayer::add_animation);
+ ClassDB::bind_method(D_METHOD("remove_animation", "name"), &AnimationPlayer::remove_animation);
+ ClassDB::bind_method(D_METHOD("rename_animation", "name", "newname"), &AnimationPlayer::rename_animation);
+ ClassDB::bind_method(D_METHOD("has_animation", "name"), &AnimationPlayer::has_animation);
+ ClassDB::bind_method(D_METHOD("get_animation:Animation", "name"), &AnimationPlayer::get_animation);
+ ClassDB::bind_method(D_METHOD("get_animation_list"), &AnimationPlayer::_get_animation_list);
ClassDB::bind_method(D_METHOD("animation_set_next", "anim_from", "anim_to"), &AnimationPlayer::animation_set_next);
ClassDB::bind_method(D_METHOD("animation_get_next", "anim_from"), &AnimationPlayer::animation_get_next);
- ClassDB::bind_method(D_METHOD("set_blend_time","anim_from","anim_to","sec"),&AnimationPlayer::set_blend_time);
- ClassDB::bind_method(D_METHOD("get_blend_time","anim_from","anim_to"),&AnimationPlayer::get_blend_time);
+ ClassDB::bind_method(D_METHOD("set_blend_time", "anim_from", "anim_to", "sec"), &AnimationPlayer::set_blend_time);
+ ClassDB::bind_method(D_METHOD("get_blend_time", "anim_from", "anim_to"), &AnimationPlayer::get_blend_time);
- ClassDB::bind_method(D_METHOD("set_default_blend_time","sec"),&AnimationPlayer::set_default_blend_time);
- ClassDB::bind_method(D_METHOD("get_default_blend_time"),&AnimationPlayer::get_default_blend_time);
+ ClassDB::bind_method(D_METHOD("set_default_blend_time", "sec"), &AnimationPlayer::set_default_blend_time);
+ ClassDB::bind_method(D_METHOD("get_default_blend_time"), &AnimationPlayer::get_default_blend_time);
- ClassDB::bind_method(D_METHOD("play","name","custom_blend","custom_speed","from_end"),&AnimationPlayer::play,DEFVAL(""),DEFVAL(-1),DEFVAL(1.0),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("play_backwards","name","custom_blend"),&AnimationPlayer::play_backwards,DEFVAL(""),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("stop","reset"),&AnimationPlayer::stop,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("stop_all"),&AnimationPlayer::stop_all);
- ClassDB::bind_method(D_METHOD("is_playing"),&AnimationPlayer::is_playing);
- ClassDB::bind_method(D_METHOD("set_current_animation","anim"),&AnimationPlayer::set_current_animation);
- ClassDB::bind_method(D_METHOD("get_current_animation"),&AnimationPlayer::get_current_animation);
- ClassDB::bind_method(D_METHOD("queue","name"),&AnimationPlayer::queue);
- ClassDB::bind_method(D_METHOD("clear_queue"),&AnimationPlayer::clear_queue);
+ ClassDB::bind_method(D_METHOD("play", "name", "custom_blend", "custom_speed", "from_end"), &AnimationPlayer::play, DEFVAL(""), DEFVAL(-1), DEFVAL(1.0), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("play_backwards", "name", "custom_blend"), &AnimationPlayer::play_backwards, DEFVAL(""), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("stop", "reset"), &AnimationPlayer::stop, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("stop_all"), &AnimationPlayer::stop_all);
+ ClassDB::bind_method(D_METHOD("is_playing"), &AnimationPlayer::is_playing);
+ ClassDB::bind_method(D_METHOD("set_current_animation", "anim"), &AnimationPlayer::set_current_animation);
+ ClassDB::bind_method(D_METHOD("get_current_animation"), &AnimationPlayer::get_current_animation);
+ ClassDB::bind_method(D_METHOD("queue", "name"), &AnimationPlayer::queue);
+ ClassDB::bind_method(D_METHOD("clear_queue"), &AnimationPlayer::clear_queue);
- ClassDB::bind_method(D_METHOD("set_active","active"),&AnimationPlayer::set_active);
- ClassDB::bind_method(D_METHOD("is_active"),&AnimationPlayer::is_active);
+ ClassDB::bind_method(D_METHOD("set_active", "active"), &AnimationPlayer::set_active);
+ ClassDB::bind_method(D_METHOD("is_active"), &AnimationPlayer::is_active);
- ClassDB::bind_method(D_METHOD("set_speed_scale","speed"),&AnimationPlayer::set_speed_scale);
- ClassDB::bind_method(D_METHOD("get_speed_scale"),&AnimationPlayer::get_speed_scale);
+ ClassDB::bind_method(D_METHOD("set_speed_scale", "speed"), &AnimationPlayer::set_speed_scale);
+ ClassDB::bind_method(D_METHOD("get_speed_scale"), &AnimationPlayer::get_speed_scale);
- ClassDB::bind_method(D_METHOD("set_autoplay","name"),&AnimationPlayer::set_autoplay);
- ClassDB::bind_method(D_METHOD("get_autoplay"),&AnimationPlayer::get_autoplay);
+ ClassDB::bind_method(D_METHOD("set_autoplay", "name"), &AnimationPlayer::set_autoplay);
+ ClassDB::bind_method(D_METHOD("get_autoplay"), &AnimationPlayer::get_autoplay);
- ClassDB::bind_method(D_METHOD("set_root","path"),&AnimationPlayer::set_root);
- ClassDB::bind_method(D_METHOD("get_root"),&AnimationPlayer::get_root);
+ ClassDB::bind_method(D_METHOD("set_root", "path"), &AnimationPlayer::set_root);
+ ClassDB::bind_method(D_METHOD("get_root"), &AnimationPlayer::get_root);
- ClassDB::bind_method(D_METHOD("seek","pos_sec","update"),&AnimationPlayer::seek,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_pos"),&AnimationPlayer::get_current_animation_pos);
+ ClassDB::bind_method(D_METHOD("seek", "pos_sec", "update"), &AnimationPlayer::seek, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_pos"), &AnimationPlayer::get_current_animation_pos);
- ClassDB::bind_method(D_METHOD("find_animation","animation:Animation"),&AnimationPlayer::find_animation);
+ ClassDB::bind_method(D_METHOD("find_animation", "animation:Animation"), &AnimationPlayer::find_animation);
- ClassDB::bind_method(D_METHOD("clear_caches"),&AnimationPlayer::clear_caches);
+ ClassDB::bind_method(D_METHOD("clear_caches"), &AnimationPlayer::clear_caches);
- ClassDB::bind_method(D_METHOD("set_animation_process_mode","mode"),&AnimationPlayer::set_animation_process_mode);
- ClassDB::bind_method(D_METHOD("get_animation_process_mode"),&AnimationPlayer::get_animation_process_mode);
+ ClassDB::bind_method(D_METHOD("set_animation_process_mode", "mode"), &AnimationPlayer::set_animation_process_mode);
+ ClassDB::bind_method(D_METHOD("get_animation_process_mode"), &AnimationPlayer::get_animation_process_mode);
- ClassDB::bind_method(D_METHOD("get_current_animation_pos"),&AnimationPlayer::get_current_animation_pos);
- ClassDB::bind_method(D_METHOD("get_current_animation_length"),&AnimationPlayer::get_current_animation_length);
+ ClassDB::bind_method(D_METHOD("get_current_animation_pos"), &AnimationPlayer::get_current_animation_pos);
+ ClassDB::bind_method(D_METHOD("get_current_animation_length"), &AnimationPlayer::get_current_animation_length);
- ClassDB::bind_method(D_METHOD("advance","delta"),&AnimationPlayer::advance);
+ ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationPlayer::advance);
+ ADD_GROUP("Playback", "playback_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "playback_default_blend_time", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_default_blend_time", "get_default_blend_time");
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_node"), "set_root", "get_root");
- ADD_GROUP("Playback","playback_");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode");
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "playback_default_blend_time", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_default_blend_time", "get_default_blend_time");
- ADD_PROPERTY( PropertyInfo( Variant::NODE_PATH, "root_node"), "set_root", "get_root");
+ ADD_SIGNAL(MethodInfo("animation_finished", PropertyInfo(Variant::STRING, "name")));
+ ADD_SIGNAL(MethodInfo("animation_changed", PropertyInfo(Variant::STRING, "old_name"), PropertyInfo(Variant::STRING, "new_name")));
+ ADD_SIGNAL(MethodInfo("animation_started", PropertyInfo(Variant::STRING, "name")));
- ADD_SIGNAL( MethodInfo("animation_finished", PropertyInfo(Variant::STRING,"name")) );
- ADD_SIGNAL( MethodInfo("animation_changed", PropertyInfo(Variant::STRING,"old_name"), PropertyInfo(Variant::STRING,"new_name")) );
- ADD_SIGNAL( MethodInfo("animation_started", PropertyInfo(Variant::STRING,"name")) );
-
- BIND_CONSTANT( ANIMATION_PROCESS_FIXED );
- BIND_CONSTANT( ANIMATION_PROCESS_IDLE );
+ BIND_CONSTANT(ANIMATION_PROCESS_FIXED);
+ BIND_CONSTANT(ANIMATION_PROCESS_IDLE);
}
AnimationPlayer::AnimationPlayer() {
-
- accum_pass=1;
- cache_update_size=0;
- cache_update_prop_size=0;
- speed_scale=1;
- end_notify=false;
- animation_process_mode=ANIMATION_PROCESS_IDLE;
- processing=false;
- default_blend_time=0;
- root=SceneStringNames::get_singleton()->path_pp;
+ accum_pass = 1;
+ cache_update_size = 0;
+ cache_update_prop_size = 0;
+ speed_scale = 1;
+ end_notify = false;
+ animation_process_mode = ANIMATION_PROCESS_IDLE;
+ processing = false;
+ default_blend_time = 0;
+ root = SceneStringNames::get_singleton()->path_pp;
playing = false;
- active=true;
+ active = true;
}
-
-AnimationPlayer::~AnimationPlayer()
-{
+AnimationPlayer::~AnimationPlayer() {
}
-
-
diff --git a/scene/animation/animation_player.h b/scene/animation/animation_player.h
index 7fab651213..b5679d62f1 100644
--- a/scene/animation/animation_player.h
+++ b/scene/animation/animation_player.h
@@ -29,35 +29,31 @@
#ifndef ANIMATION_PLAYER_H
#define ANIMATION_PLAYER_H
-
-#include "scene/resources/animation.h"
-#include "scene/3d/spatial.h"
-#include "scene/3d/skeleton.h"
#include "scene/2d/node_2d.h"
+#include "scene/3d/skeleton.h"
+#include "scene/3d/spatial.h"
+#include "scene/resources/animation.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class AnimationPlayer : public Node {
- GDCLASS( AnimationPlayer, Node );
+ GDCLASS(AnimationPlayer, Node);
OBJ_CATEGORY("Animation Nodes");
public:
-
enum AnimationProcessMode {
ANIMATION_PROCESS_FIXED,
ANIMATION_PROCESS_IDLE,
};
private:
-
enum {
- NODE_CACHE_UPDATE_MAX=1024,
- BLEND_FROM_MAX=3
+ NODE_CACHE_UPDATE_MAX = 1024,
+ BLEND_FROM_MAX = 3
};
-
enum SpecialProperty {
SP_NONE,
SP_NODE2D_POS,
@@ -71,8 +67,8 @@ private:
uint32_t id;
RES resource;
Node *node;
- Spatial* spatial;
- Node2D* node_2d;
+ Spatial *spatial;
+ Node2D *node_2d;
Skeleton *skeleton;
int bone_idx;
// accumulated transforms
@@ -90,14 +86,22 @@ private:
Object *object;
Variant value_accum;
uint64_t accum_pass;
- PropertyAnim() { accum_pass=0; object=NULL; }
+ PropertyAnim() {
+ accum_pass = 0;
+ object = NULL;
+ }
};
- Map<StringName,PropertyAnim> property_anim;
-
-
- TrackNodeCache() { skeleton=NULL; spatial=NULL; node=NULL; accum_pass=0; bone_idx=-1; node_2d=NULL; }
+ Map<StringName, PropertyAnim> property_anim;
+ TrackNodeCache() {
+ skeleton = NULL;
+ spatial = NULL;
+ node = NULL;
+ accum_pass = 0;
+ bone_idx = -1;
+ node_2d = NULL;
+ }
};
struct TrackNodeCacheKey {
@@ -105,36 +109,34 @@ private:
uint32_t id;
int bone_idx;
- inline bool operator<(const TrackNodeCacheKey& p_right) const {
+ inline bool operator<(const TrackNodeCacheKey &p_right) const {
- if (id<p_right.id)
+ if (id < p_right.id)
return true;
- else if (id>p_right.id)
+ else if (id > p_right.id)
return false;
else
- return bone_idx<p_right.bone_idx;
+ return bone_idx < p_right.bone_idx;
}
};
- Map<TrackNodeCacheKey,TrackNodeCache> node_cache_map;
+ Map<TrackNodeCacheKey, TrackNodeCache> node_cache_map;
- TrackNodeCache* cache_update[NODE_CACHE_UPDATE_MAX];
+ TrackNodeCache *cache_update[NODE_CACHE_UPDATE_MAX];
int cache_update_size;
- TrackNodeCache::PropertyAnim* cache_update_prop[NODE_CACHE_UPDATE_MAX];
+ TrackNodeCache::PropertyAnim *cache_update_prop[NODE_CACHE_UPDATE_MAX];
int cache_update_prop_size;
- Map<Ref<Animation>,int> used_anims;
+ Map<Ref<Animation>, int> used_anims;
uint64_t accum_pass;
- float speed_scale;
- float default_blend_time;
-
+ float speed_scale;
+ float default_blend_time;
struct AnimationData {
String name;
StringName next;
- Vector<TrackNodeCache*> node_cache;
+ Vector<TrackNodeCache *> node_cache;
Ref<Animation> animation;
-
};
Map<StringName, AnimationData> animation_set;
@@ -142,27 +144,23 @@ private:
StringName from;
StringName to;
- bool operator<(const BlendKey& bk) const { return from==bk.from?String(to)<String(bk.to):String(from)<String(bk.from); }
+ bool operator<(const BlendKey &bk) const { return from == bk.from ? String(to) < String(bk.to) : String(from) < String(bk.from); }
};
-
- Map<BlendKey, float > blend_times;
-
+ Map<BlendKey, float> blend_times;
struct PlaybackData {
- AnimationData* from;
+ AnimationData *from;
float pos;
float speed_scale;
PlaybackData() {
- pos=0;
- speed_scale=1.0;
- from=NULL;
-
+ pos = 0;
+ speed_scale = 1.0;
+ from = NULL;
}
-
};
struct Blend {
@@ -174,8 +172,8 @@ private:
Blend() {
- blend_left=0;
- blend_time=0;
+ blend_left = 0;
+ blend_time = 0;
}
};
@@ -197,75 +195,73 @@ private:
NodePath root;
- void _animation_process_animation(AnimationData* p_anim,float p_time, float p_delta,float p_interp, bool p_allow_discrete=true);
+ void _animation_process_animation(AnimationData *p_anim, float p_time, float p_delta, float p_interp, bool p_allow_discrete = true);
- void _generate_node_caches(AnimationData* p_anim);
- void _animation_process_data(PlaybackData &cd,float p_delta,float p_blend);
+ void _generate_node_caches(AnimationData *p_anim);
+ void _animation_process_data(PlaybackData &cd, float p_delta, float p_blend);
void _animation_process2(float p_delta);
void _animation_update_transforms();
void _animation_process(float p_delta);
void _node_removed(Node *p_node);
-// bind helpers
+ // bind helpers
PoolVector<String> _get_animation_list() const {
List<StringName> animations;
get_animation_list(&animations);
PoolVector<String> ret;
- while(animations.size()) {
+ while (animations.size()) {
- ret.push_back( animations.front()->get());
+ ret.push_back(animations.front()->get());
animations.pop_front();
}
return ret;
}
void _animation_changed();
- void _ref_anim(const Ref<Animation>& p_anim);
- void _unref_anim(const Ref<Animation>& p_anim);
+ void _ref_anim(const Ref<Animation> &p_anim);
+ void _unref_anim(const Ref<Animation> &p_anim);
+ void _set_process(bool p_process, bool p_force = false);
- void _set_process(bool p_process,bool p_force=false);
-
- bool playing;
+ bool playing;
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
+ StringName find_animation(const Ref<Animation> &p_animation) const;
- StringName find_animation(const Ref<Animation>& p_animation) const;
-
- Error add_animation(const StringName& p_name, const Ref<Animation>& p_animation);
- void remove_animation(const StringName& p_name);
- void rename_animation(const StringName& p_name,const StringName& p_new_name);
- bool has_animation(const StringName& p_name) const;
- Ref<Animation> get_animation(const StringName& p_name) const;
- void get_animation_list( List<StringName> * p_animations) const;
+ Error add_animation(const StringName &p_name, const Ref<Animation> &p_animation);
+ void remove_animation(const StringName &p_name);
+ void rename_animation(const StringName &p_name, const StringName &p_new_name);
+ bool has_animation(const StringName &p_name) const;
+ Ref<Animation> get_animation(const StringName &p_name) const;
+ void get_animation_list(List<StringName> *p_animations) const;
- void set_blend_time(const StringName& p_animation1, const StringName& p_animation2, float p_time);
- float get_blend_time( const StringName& p_animation1, const StringName& p_animation2) const;
+ void set_blend_time(const StringName &p_animation1, const StringName &p_animation2, float p_time);
+ float get_blend_time(const StringName &p_animation1, const StringName &p_animation2) const;
- void animation_set_next(const StringName& p_animation, const StringName& p_next);
- StringName animation_get_next(const StringName& p_animation) const;
+ void animation_set_next(const StringName &p_animation, const StringName &p_next);
+ StringName animation_get_next(const StringName &p_animation) const;
- void set_default_blend_time(float p_default);
- float get_default_blend_time() const;
+ void set_default_blend_time(float p_default);
+ float get_default_blend_time() const;
- void play(const StringName& p_name=StringName(),float p_custom_blend=-1,float p_custom_scale=1.0,bool p_from_end=false);
- void play_backwards(const StringName& p_name=StringName(),float p_custom_blend=-1);
- void queue(const StringName& p_name);
+ void play(const StringName &p_name = StringName(), float p_custom_blend = -1, float p_custom_scale = 1.0, bool p_from_end = false);
+ void play_backwards(const StringName &p_name = StringName(), float p_custom_blend = -1);
+ void queue(const StringName &p_name);
void clear_queue();
- void stop(bool p_reset=true);
+ void stop(bool p_reset = true);
bool is_playing() const;
String get_current_animation() const;
- void set_current_animation(const String& p_anim);
+ void set_current_animation(const String &p_anim);
void stop_all();
void set_active(bool p_active);
bool is_active() const;
@@ -274,34 +270,30 @@ public:
void set_speed_scale(float p_speed);
float get_speed_scale() const;
- void set_autoplay(const String& pname);
+ void set_autoplay(const String &pname);
String get_autoplay() const;
void set_animation_process_mode(AnimationProcessMode p_mode);
AnimationProcessMode get_animation_process_mode() const;
- void seek(float p_time,bool p_update=false);
- void seek_delta(float p_time,float p_delta);
+ void seek(float p_time, bool p_update = false);
+ void seek_delta(float p_time, float p_delta);
float get_current_animation_pos() const;
float get_current_animation_length() const;
void advance(float p_time);
- void set_root(const NodePath& p_root);
+ void set_root(const NodePath &p_root);
NodePath get_root() const;
void clear_caches(); ///< must be called by hand if an animation was modified after added
- void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
-
+ void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
AnimationPlayer();
~AnimationPlayer();
-
};
-
-VARIANT_ENUM_CAST( AnimationPlayer::AnimationProcessMode );
-
+VARIANT_ENUM_CAST(AnimationPlayer::AnimationProcessMode);
#endif
diff --git a/scene/animation/animation_tree_player.cpp b/scene/animation/animation_tree_player.cpp
index d7e98ddd2b..6f4279526a 100644
--- a/scene/animation/animation_tree_player.cpp
+++ b/scene/animation/animation_tree_player.cpp
@@ -31,7 +31,6 @@
#include "scene/scene_string_names.h"
-
void AnimationTreePlayer::set_animation_process_mode(AnimationProcessMode p_mode) {
if (animation_process_mode == p_mode)
@@ -43,322 +42,312 @@ void AnimationTreePlayer::set_animation_process_mode(AnimationProcessMode p_mode
animation_process_mode = p_mode;
if (pr)
_set_process(true);
-
}
-AnimationTreePlayer::AnimationProcessMode AnimationTreePlayer::get_animation_process_mode() const{
+AnimationTreePlayer::AnimationProcessMode AnimationTreePlayer::get_animation_process_mode() const {
return animation_process_mode;
}
-void AnimationTreePlayer::_set_process(bool p_process, bool p_force)
-{
+void AnimationTreePlayer::_set_process(bool p_process, bool p_force) {
if (processing == p_process && !p_force)
return;
switch (animation_process_mode) {
- case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break;
- case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break;
+ case ANIMATION_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break;
+ case ANIMATION_PROCESS_IDLE: set_process_internal(p_process && active); break;
}
processing = p_process;
}
+bool AnimationTreePlayer::_set(const StringName &p_name, const Variant &p_value) {
-bool AnimationTreePlayer::_set(const StringName& p_name, const Variant& p_value) {
-
- if (String(p_name)=="base_path") {
+ if (String(p_name) == "base_path") {
set_base_path(p_value);
return true;
}
- if (String(p_name)=="master_player") {
+ if (String(p_name) == "master_player") {
set_master_player(p_value);
return true;
}
- if(String(p_name) == SceneStringNames::get_singleton()->playback_active) {
+ if (String(p_name) == SceneStringNames::get_singleton()->playback_active) {
set_active(p_value);
return true;
}
- if (String(p_name)!="data")
+ if (String(p_name) != "data")
return false;
+ Dictionary data = p_value;
- Dictionary data=p_value;
+ Array nodes = data.get_valid("nodes");
- Array nodes=data.get_valid("nodes");
-
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
Dictionary node = nodes[i];
StringName id = node.get_valid("id");
Point2 pos = node.get_valid("pos");
- NodeType nt=NODE_MAX;
+ NodeType nt = NODE_MAX;
String type = node.get_valid("type");
- if (type=="output")
- nt=NODE_OUTPUT;
- else if (type=="animation")
- nt=NODE_ANIMATION;
- else if (type=="oneshot")
- nt=NODE_ONESHOT;
- else if (type=="mix")
- nt=NODE_MIX;
- else if (type=="blend2")
- nt=NODE_BLEND2;
- else if (type=="blend3")
- nt=NODE_BLEND3;
- else if (type=="blend4")
- nt=NODE_BLEND4;
- else if (type=="timescale")
- nt=NODE_TIMESCALE;
- else if (type=="timeseek")
- nt=NODE_TIMESEEK;
- else if (type=="transition")
- nt=NODE_TRANSITION;
-
- ERR_FAIL_COND_V(nt==NODE_MAX,false);
-
- if (nt!=NODE_OUTPUT)
- add_node(nt,id);
- node_set_pos(id,pos);
-
-
- switch(nt) {
+ if (type == "output")
+ nt = NODE_OUTPUT;
+ else if (type == "animation")
+ nt = NODE_ANIMATION;
+ else if (type == "oneshot")
+ nt = NODE_ONESHOT;
+ else if (type == "mix")
+ nt = NODE_MIX;
+ else if (type == "blend2")
+ nt = NODE_BLEND2;
+ else if (type == "blend3")
+ nt = NODE_BLEND3;
+ else if (type == "blend4")
+ nt = NODE_BLEND4;
+ else if (type == "timescale")
+ nt = NODE_TIMESCALE;
+ else if (type == "timeseek")
+ nt = NODE_TIMESEEK;
+ else if (type == "transition")
+ nt = NODE_TRANSITION;
+
+ ERR_FAIL_COND_V(nt == NODE_MAX, false);
+
+ if (nt != NODE_OUTPUT)
+ add_node(nt, id);
+ node_set_pos(id, pos);
+
+ switch (nt) {
case NODE_OUTPUT: {
} break;
case NODE_ANIMATION: {
if (node.has("from"))
- animation_node_set_master_animation(id,node.get_valid("from"));
+ animation_node_set_master_animation(id, node.get_valid("from"));
else
- animation_node_set_animation(id,node.get_valid("animation"));
- Array filters= node.get_valid("filter");
- for(int i=0;i<filters.size();i++) {
+ animation_node_set_animation(id, node.get_valid("animation"));
+ Array filters = node.get_valid("filter");
+ for (int i = 0; i < filters.size(); i++) {
- animation_node_set_filter_path(id,filters[i],true);
+ animation_node_set_filter_path(id, filters[i], true);
}
- } break;
+ } break;
case NODE_ONESHOT: {
- oneshot_node_set_fadein_time(id,node.get_valid("fade_in"));
- oneshot_node_set_fadeout_time(id,node.get_valid("fade_out"));
- oneshot_node_set_mix_mode(id,node.get_valid("mix"));
- oneshot_node_set_autorestart(id,node.get_valid("autorestart"));
- oneshot_node_set_autorestart_delay(id,node.get_valid("autorestart_delay"));
- oneshot_node_set_autorestart_random_delay(id,node.get_valid("autorestart_random_delay"));
- Array filters= node.get_valid("filter");
- for(int i=0;i<filters.size();i++) {
+ oneshot_node_set_fadein_time(id, node.get_valid("fade_in"));
+ oneshot_node_set_fadeout_time(id, node.get_valid("fade_out"));
+ oneshot_node_set_mix_mode(id, node.get_valid("mix"));
+ oneshot_node_set_autorestart(id, node.get_valid("autorestart"));
+ oneshot_node_set_autorestart_delay(id, node.get_valid("autorestart_delay"));
+ oneshot_node_set_autorestart_random_delay(id, node.get_valid("autorestart_random_delay"));
+ Array filters = node.get_valid("filter");
+ for (int i = 0; i < filters.size(); i++) {
- oneshot_node_set_filter_path(id,filters[i],true);
+ oneshot_node_set_filter_path(id, filters[i], true);
}
} break;
case NODE_MIX: {
- mix_node_set_amount(id,node.get_valid("mix"));
+ mix_node_set_amount(id, node.get_valid("mix"));
} break;
case NODE_BLEND2: {
- blend2_node_set_amount(id,node.get_valid("blend"));
- Array filters= node.get_valid("filter");
- for(int i=0;i<filters.size();i++) {
+ blend2_node_set_amount(id, node.get_valid("blend"));
+ Array filters = node.get_valid("filter");
+ for (int i = 0; i < filters.size(); i++) {
- blend2_node_set_filter_path(id,filters[i],true);
+ blend2_node_set_filter_path(id, filters[i], true);
}
} break;
case NODE_BLEND3: {
- blend3_node_set_amount(id,node.get_valid("blend"));
+ blend3_node_set_amount(id, node.get_valid("blend"));
} break;
case NODE_BLEND4: {
- blend4_node_set_amount(id,node.get_valid("blend"));
+ blend4_node_set_amount(id, node.get_valid("blend"));
} break;
case NODE_TIMESCALE: {
- timescale_node_set_scale(id,node.get_valid("scale"));
+ timescale_node_set_scale(id, node.get_valid("scale"));
} break;
case NODE_TIMESEEK: {
} break;
case NODE_TRANSITION: {
- transition_node_set_xfade_time(id,node.get_valid("xfade"));
+ transition_node_set_xfade_time(id, node.get_valid("xfade"));
Array transitions = node.get_valid("transitions");
- transition_node_set_input_count(id,transitions.size());
+ transition_node_set_input_count(id, transitions.size());
- for(int x=0;x<transitions.size();x++) {
+ for (int x = 0; x < transitions.size(); x++) {
- Dictionary d =transitions[x];
+ Dictionary d = transitions[x];
bool aa = d.get_valid("auto_advance");
- transition_node_set_input_auto_advance(id,x,aa);
-
+ transition_node_set_input_auto_advance(id, x, aa);
}
} break;
default: {};
}
-
}
-
Array connections = data.get_valid("connections");
- ERR_FAIL_COND_V(connections.size()%3,false);
+ ERR_FAIL_COND_V(connections.size() % 3, false);
- int cc=connections.size()/3;
+ int cc = connections.size() / 3;
- for(int i=0;i<cc;i++) {
+ for (int i = 0; i < cc; i++) {
- StringName src = connections[i*3+0];
- StringName dst = connections[i*3+1];
- int dst_in = connections[i*3+2];
- connect_nodes(src,dst,dst_in);
+ StringName src = connections[i * 3 + 0];
+ StringName dst = connections[i * 3 + 1];
+ int dst_in = connections[i * 3 + 2];
+ connect_nodes(src, dst, dst_in);
}
set_active(data.get_valid("active"));
set_master_player(data.get_valid("master"));
return true;
-
}
-bool AnimationTreePlayer::_get(const StringName& p_name,Variant &r_ret) const {
+bool AnimationTreePlayer::_get(const StringName &p_name, Variant &r_ret) const {
- if (String(p_name)=="base_path") {
- r_ret=base_path;
+ if (String(p_name) == "base_path") {
+ r_ret = base_path;
return true;
}
- if (String(p_name)=="master_player") {
- r_ret=master;
+ if (String(p_name) == "master_player") {
+ r_ret = master;
return true;
}
if (String(p_name) == "playback/active") {
- r_ret=is_active();
+ r_ret = is_active();
return true;
}
- if (String(p_name)!="data")
+ if (String(p_name) != "data")
return false;
Dictionary data;
Array nodes;
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *n = node_map[E->key()];
Dictionary node;
- node["id"]=E->key();
- node["pos"]=n->pos;
-
- switch(n->type) {
- case NODE_OUTPUT: node["type"]= "output"; break;
- case NODE_ANIMATION: node["type"]= "animation"; break;
- case NODE_ONESHOT: node["type"]= "oneshot"; break;
- case NODE_MIX: node["type"]= "mix"; break;
- case NODE_BLEND2: node["type"]= "blend2"; break;
- case NODE_BLEND3: node["type"]= "blend3"; break;
- case NODE_BLEND4: node["type"]= "blend4"; break;
- case NODE_TIMESCALE: node["type"]= "timescale"; break;
- case NODE_TIMESEEK: node["type"]= "timeseek"; break;
- case NODE_TRANSITION: node["type"]= "transition"; break;
- default: node["type"]= ""; break;
+ node["id"] = E->key();
+ node["pos"] = n->pos;
+
+ switch (n->type) {
+ case NODE_OUTPUT: node["type"] = "output"; break;
+ case NODE_ANIMATION: node["type"] = "animation"; break;
+ case NODE_ONESHOT: node["type"] = "oneshot"; break;
+ case NODE_MIX: node["type"] = "mix"; break;
+ case NODE_BLEND2: node["type"] = "blend2"; break;
+ case NODE_BLEND3: node["type"] = "blend3"; break;
+ case NODE_BLEND4: node["type"] = "blend4"; break;
+ case NODE_TIMESCALE: node["type"] = "timescale"; break;
+ case NODE_TIMESEEK: node["type"] = "timeseek"; break;
+ case NODE_TRANSITION: node["type"] = "transition"; break;
+ default: node["type"] = ""; break;
}
- switch(n->type) {
+ switch (n->type) {
case NODE_OUTPUT: {
} break;
case NODE_ANIMATION: {
- AnimationNode *an = static_cast<AnimationNode*>(n);
- if (master!=NodePath() && an->from!="") {
- node["from"]=an->from;
+ AnimationNode *an = static_cast<AnimationNode *>(n);
+ if (master != NodePath() && an->from != "") {
+ node["from"] = an->from;
} else {
- node["animation"]=an->animation;
+ node["animation"] = an->animation;
}
Array k;
List<NodePath> keys;
an->filter.get_key_list(&keys);
k.resize(keys.size());
- int i=0;
- for(List<NodePath>::Element *E=keys.front();E;E=E->next()) {
- k[i++]=E->get();
+ int i = 0;
+ for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
+ k[i++] = E->get();
}
- node["filter"]=k;
- } break;
+ node["filter"] = k;
+ } break;
case NODE_ONESHOT: {
- OneShotNode *osn = static_cast<OneShotNode*>(n);
- node["fade_in"]=osn->fade_in;
- node["fade_out"]=osn->fade_out;
- node["mix"]=osn->mix;
- node["autorestart"]=osn->autorestart;
- node["autorestart_delay"]=osn->autorestart_delay;
- node["autorestart_random_delay"]=osn->autorestart_random_delay;
+ OneShotNode *osn = static_cast<OneShotNode *>(n);
+ node["fade_in"] = osn->fade_in;
+ node["fade_out"] = osn->fade_out;
+ node["mix"] = osn->mix;
+ node["autorestart"] = osn->autorestart;
+ node["autorestart_delay"] = osn->autorestart_delay;
+ node["autorestart_random_delay"] = osn->autorestart_random_delay;
Array k;
List<NodePath> keys;
osn->filter.get_key_list(&keys);
k.resize(keys.size());
- int i=0;
- for(List<NodePath>::Element *E=keys.front();E;E=E->next()) {
- k[i++]=E->get();
+ int i = 0;
+ for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
+ k[i++] = E->get();
}
- node["filter"]=k;
+ node["filter"] = k;
} break;
case NODE_MIX: {
- MixNode *mn = static_cast<MixNode*>(n);
- node["mix"]=mn->amount;
+ MixNode *mn = static_cast<MixNode *>(n);
+ node["mix"] = mn->amount;
} break;
case NODE_BLEND2: {
- Blend2Node *bn = static_cast<Blend2Node*>(n);
- node["blend"]=bn->value;
+ Blend2Node *bn = static_cast<Blend2Node *>(n);
+ node["blend"] = bn->value;
Array k;
List<NodePath> keys;
bn->filter.get_key_list(&keys);
k.resize(keys.size());
- int i=0;
- for(List<NodePath>::Element *E=keys.front();E;E=E->next()) {
- k[i++]=E->get();
+ int i = 0;
+ for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
+ k[i++] = E->get();
}
- node["filter"]=k;
+ node["filter"] = k;
} break;
case NODE_BLEND3: {
- Blend3Node *bn = static_cast<Blend3Node*>(n);
- node["blend"]=bn->value;
+ Blend3Node *bn = static_cast<Blend3Node *>(n);
+ node["blend"] = bn->value;
} break;
case NODE_BLEND4: {
- Blend4Node *bn = static_cast<Blend4Node*>(n);
- node["blend"]=bn->value;
+ Blend4Node *bn = static_cast<Blend4Node *>(n);
+ node["blend"] = bn->value;
} break;
case NODE_TIMESCALE: {
- TimeScaleNode *tsn = static_cast<TimeScaleNode*>(n);
- node["scale"]=tsn->scale;
+ TimeScaleNode *tsn = static_cast<TimeScaleNode *>(n);
+ node["scale"] = tsn->scale;
} break;
case NODE_TIMESEEK: {
} break;
case NODE_TRANSITION: {
- TransitionNode *tn = static_cast<TransitionNode*>(n);
- node["xfade"]=tn->xfade;
+ TransitionNode *tn = static_cast<TransitionNode *>(n);
+ node["xfade"] = tn->xfade;
Array transitions;
- for(int i=0;i<tn->input_data.size();i++) {
+ for (int i = 0; i < tn->input_data.size(); i++) {
Dictionary d;
- d["auto_advance"]=tn->input_data[i].auto_advance;
+ d["auto_advance"] = tn->input_data[i].auto_advance;
transitions.push_back(d);
-
}
- node["transitions"]=transitions;
+ node["transitions"] = transitions;
} break;
default: {};
@@ -367,39 +356,38 @@ bool AnimationTreePlayer::_get(const StringName& p_name,Variant &r_ret) const {
nodes.push_back(node);
}
- data["nodes"]=nodes;
+ data["nodes"] = nodes;
//connectiosn
List<Connection> connections;
get_connection_list(&connections);
Array connections_arr;
- connections_arr.resize(connections.size()*3);
+ connections_arr.resize(connections.size() * 3);
- int idx=0;
- for (List<Connection>::Element *E=connections.front();E;E=E->next()) {
+ int idx = 0;
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- connections_arr.set(idx+0,E->get().src_node);
- connections_arr.set(idx+1,E->get().dst_node);
- connections_arr.set(idx+2,E->get().dst_input);
+ connections_arr.set(idx + 0, E->get().src_node);
+ connections_arr.set(idx + 1, E->get().dst_node);
+ connections_arr.set(idx + 2, E->get().dst_input);
- idx+=3;
+ idx += 3;
}
- data["connections"]=connections_arr;
- data["active"]=active;
- data["master"]=master;
+ data["connections"] = connections_arr;
+ data["active"] = active;
+ data["master"] = master;
- r_ret=data;
+ r_ret = data;
return true;
-
}
-void AnimationTreePlayer::_get_property_list( List<PropertyInfo> *p_list) const {
+void AnimationTreePlayer::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo(Variant::NODE_PATH,"base_path" ) );
- p_list->push_back( PropertyInfo(Variant::NODE_PATH,"master_player" ) );
- p_list->push_back( PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_NETWORK) );
+ p_list->push_back(PropertyInfo(Variant::NODE_PATH, "base_path"));
+ p_list->push_back(PropertyInfo(Variant::NODE_PATH, "master_player"));
+ p_list->push_back(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_NETWORK));
}
void AnimationTreePlayer::advance(float p_time) {
@@ -409,7 +397,7 @@ void AnimationTreePlayer::advance(float p_time) {
void AnimationTreePlayer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -421,38 +409,37 @@ void AnimationTreePlayer::_notification(int p_what) {
}
} break;
case NOTIFICATION_READY: {
- dirty_caches=true;
- if (master!=NodePath()) {
+ dirty_caches = true;
+ if (master != NodePath()) {
_update_sources();
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
- if (animation_process_mode==ANIMATION_PROCESS_FIXED)
+ if (animation_process_mode == ANIMATION_PROCESS_FIXED)
break;
if (processing)
- _process_animation( get_process_delta_time() );
+ _process_animation(get_process_delta_time());
} break;
case NOTIFICATION_INTERNAL_FIXED_PROCESS: {
- if (animation_process_mode==ANIMATION_PROCESS_IDLE)
+ if (animation_process_mode == ANIMATION_PROCESS_IDLE)
break;
if (processing)
_process_animation(get_fixed_process_delta_time());
} break;
}
-
}
-void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMap<NodePath,float> *p_weights, float p_coeff, const HashMap<NodePath,bool> *p_filter, float p_filtered_coeff) {
+void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMap<NodePath, float> *p_weights, float p_coeff, const HashMap<NodePath, bool> *p_filter, float p_filtered_coeff) {
if (p_filter != NULL) {
List<NodePath> key_list;
p_filter->get_key_list(&key_list);
- for (List<NodePath>::Element *E = key_list.front();E; E=E->next()) {
+ for (List<NodePath>::Element *E = key_list.front(); E; E = E->next()) {
if ((*p_filter)[E->get()]) {
@@ -463,45 +450,43 @@ void AnimationTreePlayer::_compute_weights(float *p_fallback_weight, HashMap<Nod
}
} else if (p_weights->has(E->get())) {
- (*p_weights)[E->get()] *= p_coeff;
+ (*p_weights)[E->get()] *= p_coeff;
}
}
}
List<NodePath> key_list;
p_weights->get_key_list(&key_list);
-
- for (List<NodePath>::Element *E = key_list.front();E;E=E->next()) {
+
+ for (List<NodePath>::Element *E = key_list.front(); E; E = E->next()) {
if (p_filter == NULL || !p_filter->has(E->get())) {
(*p_weights)[E->get()] *= p_coeff;
}
}
*p_fallback_weight *= p_coeff;
-
}
-
-float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode **r_prev_anim, float p_time, bool p_seek, float p_fallback_weight, HashMap<NodePath,float>* p_weights) {
+float AnimationTreePlayer::_process_node(const StringName &p_node, AnimationNode **r_prev_anim, float p_time, bool p_seek, float p_fallback_weight, HashMap<NodePath, float> *p_weights) {
ERR_FAIL_COND_V(!node_map.has(p_node), 0);
- NodeBase *nb=node_map[p_node];
+ NodeBase *nb = node_map[p_node];
//transform to seconds...
- switch(nb->type) {
+ switch (nb->type) {
case NODE_OUTPUT: {
- NodeOut *on = static_cast<NodeOut*>(nb);
+ NodeOut *on = static_cast<NodeOut *>(nb);
HashMap<NodePath, float> weights;
- return _process_node(on->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, &weights);
+ return _process_node(on->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, &weights);
} break;
case NODE_ANIMATION: {
- AnimationNode *an = static_cast<AnimationNode*>(nb);
+ AnimationNode *an = static_cast<AnimationNode *>(nb);
float rem = 0;
if (!an->animation.is_null()) {
@@ -512,11 +497,11 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
//const Animation *a = an->animation.operator->();
if (p_seek) {
- an->time=p_time;
- an->step=0;
+ an->time = p_time;
+ an->step = 0;
} else {
- an->time=MAX(0,an->time+p_time);
- an->step=p_time;
+ an->time = MAX(0, an->time + p_time);
+ an->step = p_time;
}
float anim_size = an->animation->get_length();
@@ -524,16 +509,16 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
if (an->animation->has_loop()) {
if (anim_size)
- an->time=Math::fposmod(an->time,anim_size);
+ an->time = Math::fposmod(an->time, anim_size);
} else if (an->time > anim_size) {
- an->time=anim_size;
+ an->time = anim_size;
}
- an->skip=true;
+ an->skip = true;
- for (List<AnimationNode::TrackRef>::Element *E=an->tref.front();E;E=E->next()) {
+ for (List<AnimationNode::TrackRef>::Element *E = an->tref.front(); E; E = E->next()) {
NodePath track_path = an->animation->track_get_path(E->get().local_track);
if (an->filter.has(track_path) && an->filter[track_path]) {
E->get().weight = 0;
@@ -545,114 +530,111 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
E->get().weight = p_fallback_weight;
}
}
- if (E->get().weight>CMP_EPSILON)
- an->skip=false;
+ if (E->get().weight > CMP_EPSILON)
+ an->skip = false;
}
rem = anim_size - an->time;
-
}
-
if (!(*r_prev_anim))
- active_list=an;
+ active_list = an;
else
- (*r_prev_anim)->next=an;
+ (*r_prev_anim)->next = an;
- an->next=NULL;
- *r_prev_anim=an;
+ an->next = NULL;
+ *r_prev_anim = an;
return rem;
-
} break;
case NODE_ONESHOT: {
- OneShotNode *osn = static_cast<OneShotNode*>(nb);
+ OneShotNode *osn = static_cast<OneShotNode *>(nb);
if (!osn->active) {
//make it as if this node doesn't exist, pass input 0 by.
- return _process_node(osn->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, p_weights);
+ return _process_node(osn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
}
float os_seek = p_seek;
if (p_seek)
- osn->time=p_time;
+ osn->time = p_time;
if (osn->start) {
- osn->time=0;
+ osn->time = 0;
os_seek = true;
}
float blend;
- if (osn->time<osn->fade_in) {
+ if (osn->time < osn->fade_in) {
- if (osn->fade_in>0)
- blend = osn->time/osn->fade_in;
+ if (osn->fade_in > 0)
+ blend = osn->time / osn->fade_in;
else
- blend=0; //wtf
+ blend = 0; //wtf
- } else if (!osn->start && osn->remaining<osn->fade_out) {
+ } else if (!osn->start && osn->remaining < osn->fade_out) {
if (osn->fade_out)
- blend=(osn->remaining/osn->fade_out);
+ blend = (osn->remaining / osn->fade_out);
else
- blend=1.0;
+ blend = 1.0;
} else
- blend=1.0;
+ blend = 1.0;
float main_rem;
float os_rem;
HashMap<NodePath, float> os_weights(*p_weights);
float os_fallback_weight = p_fallback_weight;
- _compute_weights(&p_fallback_weight, p_weights, osn->mix?1.0 : 1.0 - blend, &osn->filter, 1.0);
+ _compute_weights(&p_fallback_weight, p_weights, osn->mix ? 1.0 : 1.0 - blend, &osn->filter, 1.0);
_compute_weights(&os_fallback_weight, &os_weights, blend, &osn->filter, 0.0);
- main_rem = _process_node(osn->inputs[0].node,r_prev_anim,p_time,p_seek, p_fallback_weight, p_weights);
- os_rem = _process_node(osn->inputs[1].node,r_prev_anim,p_time,os_seek, os_fallback_weight, &os_weights);
+ main_rem = _process_node(osn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
+ os_rem = _process_node(osn->inputs[1].node, r_prev_anim, p_time, os_seek, os_fallback_weight, &os_weights);
if (osn->start) {
- osn->remaining=os_rem;
- osn->start=false;
+ osn->remaining = os_rem;
+ osn->start = false;
}
if (!p_seek) {
- osn->time+=p_time;
- osn->remaining=os_rem;
- if (osn->remaining<=0)
- osn->active=false;
+ osn->time += p_time;
+ osn->remaining = os_rem;
+ if (osn->remaining <= 0)
+ osn->active = false;
}
- return MAX(main_rem,osn->remaining);
+ return MAX(main_rem, osn->remaining);
} break;
case NODE_MIX: {
- MixNode *mn = static_cast<MixNode*>(nb);
+ MixNode *mn = static_cast<MixNode *>(nb);
HashMap<NodePath, float> mn_weights(*p_weights);
float mn_fallback_weight = p_fallback_weight;
_compute_weights(&mn_fallback_weight, &mn_weights, mn->amount);
- float rem = _process_node(mn->inputs[0].node,r_prev_anim, p_time,p_seek,p_fallback_weight,p_weights);
- _process_node(mn->inputs[1].node,r_prev_anim,p_time,p_seek,mn_fallback_weight,&mn_weights);
+ float rem = _process_node(mn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
+ _process_node(mn->inputs[1].node, r_prev_anim, p_time, p_seek, mn_fallback_weight, &mn_weights);
return rem;
} break;
case NODE_BLEND2: {
- Blend2Node *bn = static_cast<Blend2Node*>(nb);
+ Blend2Node *bn = static_cast<Blend2Node *>(nb);
HashMap<NodePath, float> bn_weights(*p_weights);
float bn_fallback_weight = p_fallback_weight;
- _compute_weights(&p_fallback_weight,p_weights, 1.0 - bn->value, &bn->filter, 1.0);
- _compute_weights(&bn_fallback_weight,&bn_weights, bn->value, &bn->filter, 0.0);
- float rem = _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
- _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,bn_fallback_weight,&bn_weights);
+ _compute_weights(&p_fallback_weight, p_weights, 1.0 - bn->value, &bn->filter, 1.0);
+ _compute_weights(&bn_fallback_weight, &bn_weights, bn->value, &bn->filter, 0.0);
+ float rem = _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
+ _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, bn_fallback_weight, &bn_weights);
return rem;
} break;
case NODE_BLEND3: {
- Blend3Node *bn = static_cast<Blend3Node*>(nb);
+ Blend3Node *bn = static_cast<Blend3Node *>(nb);
float rem;
float blend, lower_blend, upper_blend;
@@ -670,18 +652,18 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
float upper_fallback_weight = p_fallback_weight;
HashMap<NodePath, float> lower_weights(*p_weights);
float lower_fallback_weight = p_fallback_weight;
- _compute_weights(&upper_fallback_weight,&upper_weights, upper_blend);
- _compute_weights(&p_fallback_weight,p_weights, blend);
- _compute_weights(&lower_fallback_weight,&lower_weights, lower_blend);
+ _compute_weights(&upper_fallback_weight, &upper_weights, upper_blend);
+ _compute_weights(&p_fallback_weight, p_weights, blend);
+ _compute_weights(&lower_fallback_weight, &lower_weights, lower_blend);
- rem = _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
- _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,lower_fallback_weight,&lower_weights);
- _process_node(bn->inputs[2].node,r_prev_anim,p_time,p_seek,upper_fallback_weight,&upper_weights);
+ rem = _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
+ _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, lower_fallback_weight, &lower_weights);
+ _process_node(bn->inputs[2].node, r_prev_anim, p_time, p_seek, upper_fallback_weight, &upper_weights);
return rem;
} break;
case NODE_BLEND4: {
- Blend4Node *bn = static_cast<Blend4Node*>(nb);
+ Blend4Node *bn = static_cast<Blend4Node *>(nb);
HashMap<NodePath, float> weights1(*p_weights);
float fallback_weight1 = p_fallback_weight;
@@ -690,26 +672,26 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
HashMap<NodePath, float> weights3(*p_weights);
float fallback_weight3 = p_fallback_weight;
- _compute_weights(&p_fallback_weight,p_weights, 1.0-bn->value.x);
- _compute_weights(&fallback_weight1,&weights1, bn->value.x);
- _compute_weights(&fallback_weight2,&weights2, 1.0-bn->value.y);
- _compute_weights(&fallback_weight3,&weights3, bn->value.y);
+ _compute_weights(&p_fallback_weight, p_weights, 1.0 - bn->value.x);
+ _compute_weights(&fallback_weight1, &weights1, bn->value.x);
+ _compute_weights(&fallback_weight2, &weights2, 1.0 - bn->value.y);
+ _compute_weights(&fallback_weight3, &weights3, bn->value.y);
- float rem = _process_node(bn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
- _process_node(bn->inputs[1].node,r_prev_anim,p_time,p_seek,fallback_weight1,&weights1);
- float rem2 = _process_node(bn->inputs[2].node,r_prev_anim,p_time,p_seek,fallback_weight2,&weights2);
- _process_node(bn->inputs[3].node,r_prev_anim,p_time,p_seek,fallback_weight3,&weights3);
+ float rem = _process_node(bn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
+ _process_node(bn->inputs[1].node, r_prev_anim, p_time, p_seek, fallback_weight1, &weights1);
+ float rem2 = _process_node(bn->inputs[2].node, r_prev_anim, p_time, p_seek, fallback_weight2, &weights2);
+ _process_node(bn->inputs[3].node, r_prev_anim, p_time, p_seek, fallback_weight3, &weights3);
- return MAX(rem,rem2);
+ return MAX(rem, rem2);
} break;
case NODE_TIMESCALE: {
- TimeScaleNode *tsn = static_cast<TimeScaleNode*>(nb);
+ TimeScaleNode *tsn = static_cast<TimeScaleNode *>(nb);
float rem;
if (p_seek)
- rem = _process_node(tsn->inputs[0].node,r_prev_anim,p_time,true,p_fallback_weight,p_weights);
+ rem = _process_node(tsn->inputs[0].node, r_prev_anim, p_time, true, p_fallback_weight, p_weights);
else
- rem = _process_node(tsn->inputs[0].node,r_prev_anim,p_time*tsn->scale,false,p_fallback_weight,p_weights);
+ rem = _process_node(tsn->inputs[0].node, r_prev_anim, p_time * tsn->scale, false, p_fallback_weight, p_weights);
if (tsn->scale == 0)
return Math_INF;
else
@@ -718,105 +700,96 @@ float AnimationTreePlayer::_process_node(const StringName& p_node,AnimationNode
} break;
case NODE_TIMESEEK: {
- TimeSeekNode *tsn = static_cast<TimeSeekNode*>(nb);
- if (tsn->seek_pos>=0 && !p_seek) {
+ TimeSeekNode *tsn = static_cast<TimeSeekNode *>(nb);
+ if (tsn->seek_pos >= 0 && !p_seek) {
p_time = tsn->seek_pos;
p_seek = true;
}
- tsn->seek_pos=-1;
+ tsn->seek_pos = -1;
- return _process_node(tsn->inputs[0].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
+ return _process_node(tsn->inputs[0].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
- } break;
+ } break;
case NODE_TRANSITION: {
- TransitionNode *tn = static_cast<TransitionNode*>(nb);
+ TransitionNode *tn = static_cast<TransitionNode *>(nb);
HashMap<NodePath, float> prev_weights(*p_weights);
float prev_fallback_weight = p_fallback_weight;
- if (tn->prev<0) { // process current animation, check for transition
+ if (tn->prev < 0) { // process current animation, check for transition
- float rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
+ float rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
if (p_seek)
- tn->time=p_time;
+ tn->time = p_time;
else
- tn->time+=p_time;
+ tn->time += p_time;
if (tn->input_data[tn->current].auto_advance && rem <= tn->xfade) {
- tn->set_current((tn->current+1) % tn->inputs.size());
+ tn->set_current((tn->current + 1) % tn->inputs.size());
}
-
return rem;
- } else { // cross-fading from tn->prev to tn->current
+ } else { // cross-fading from tn->prev to tn->current
-
- float blend = tn->xfade? (tn->prev_xfading/tn->xfade) : 1;
+ float blend = tn->xfade ? (tn->prev_xfading / tn->xfade) : 1;
float rem;
- _compute_weights(&p_fallback_weight,p_weights, 1.0-blend);
- _compute_weights(&prev_fallback_weight,&prev_weights, blend);
+ _compute_weights(&p_fallback_weight, p_weights, 1.0 - blend);
+ _compute_weights(&prev_fallback_weight, &prev_weights, blend);
if (!p_seek && tn->switched) { //just switched, seek to start of current
- rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,0,true,p_fallback_weight,p_weights);
+ rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, 0, true, p_fallback_weight, p_weights);
} else {
- rem = _process_node(tn->inputs[tn->current].node,r_prev_anim,p_time,p_seek,p_fallback_weight,p_weights);
-
+ rem = _process_node(tn->inputs[tn->current].node, r_prev_anim, p_time, p_seek, p_fallback_weight, p_weights);
}
- tn->switched=false;
+ tn->switched = false;
- if (p_seek) { // don't seek prev animation
- _process_node(tn->inputs[tn->prev].node,r_prev_anim,0,false,prev_fallback_weight,&prev_weights);
- tn->time=p_time;
+ if (p_seek) { // don't seek prev animation
+ _process_node(tn->inputs[tn->prev].node, r_prev_anim, 0, false, prev_fallback_weight, &prev_weights);
+ tn->time = p_time;
} else {
- _process_node(tn->inputs[tn->prev].node,r_prev_anim,p_time,false,prev_fallback_weight,&prev_weights);
- tn->time+=p_time;
- tn->prev_xfading-=p_time;
- if (tn->prev_xfading<0) {
+ _process_node(tn->inputs[tn->prev].node, r_prev_anim, p_time, false, prev_fallback_weight, &prev_weights);
+ tn->time += p_time;
+ tn->prev_xfading -= p_time;
+ if (tn->prev_xfading < 0) {
- tn->prev=-1;
+ tn->prev = -1;
}
-
}
return rem;
}
-
} break;
default: {}
}
-
-
return 0;
}
-
void AnimationTreePlayer::_process_animation(float p_delta) {
- if (last_error!=CONNECT_OK)
+ if (last_error != CONNECT_OK)
return;
if (dirty_caches)
_recompute_caches();
-
- active_list=NULL;
- AnimationNode *prev=NULL;
+ active_list = NULL;
+ AnimationNode *prev = NULL;
if (reset_request) {
- _process_node(out_name,&prev, 0, true);
- reset_request=false;
+ _process_node(out_name, &prev, 0, true);
+ reset_request = false;
} else
- _process_node(out_name,&prev, p_delta);
+ _process_node(out_name, &prev, p_delta);
if (dirty_caches) {
//some animation changed.. ignore this pass
@@ -825,19 +798,17 @@ void AnimationTreePlayer::_process_animation(float p_delta) {
//update the tracks..
-
-
/* STEP 1 CLEAR TRACKS */
- for(TrackMap::Element *E=track_map.front();E;E=E->next()) {
+ for (TrackMap::Element *E = track_map.front(); E; E = E->next()) {
Track &t = E->get();
t.loc.zero();
- t.rot=Quat();
- t.scale.x=0;
- t.scale.y=0;
- t.scale.z=0;
+ t.rot = Quat();
+ t.scale.x = 0;
+ t.scale.y = 0;
+ t.scale.z = 0;
t.value = t.object->get(t.property);
t.value.zero();
@@ -845,634 +816,554 @@ void AnimationTreePlayer::_process_animation(float p_delta) {
t.skip = false;
}
-
/* STEP 2 PROCESS ANIMATIONS */
- AnimationNode *anim_list=active_list;
+ AnimationNode *anim_list = active_list;
Quat empty_rot;
-
- while(anim_list) {
+ while (anim_list) {
if (!anim_list->animation.is_null() && !anim_list->skip) {
//check if animation is meaningful
Animation *a = anim_list->animation.operator->();
- for(List<AnimationNode::TrackRef>::Element *E=anim_list->tref.front();E;E=E->next()) {
-
+ for (List<AnimationNode::TrackRef>::Element *E = anim_list->tref.front(); E; E = E->next()) {
AnimationNode::TrackRef &tr = E->get();
- if (tr.track==NULL || tr.local_track<0 || tr.weight < CMP_EPSILON)
+ if (tr.track == NULL || tr.local_track < 0 || tr.weight < CMP_EPSILON)
continue;
- switch(a->track_get_type(tr.local_track)) {
+ switch (a->track_get_type(tr.local_track)) {
case Animation::TYPE_TRANSFORM: { ///< Transform a node or a bone.
Vector3 loc;
Quat rot;
Vector3 scale;
- a->transform_track_interpolate(tr.local_track,anim_list->time,&loc,&rot,&scale);
+ a->transform_track_interpolate(tr.local_track, anim_list->time, &loc, &rot, &scale);
- tr.track->loc+=loc*tr.weight;
+ tr.track->loc += loc * tr.weight;
- scale.x-=1.0;
- scale.y-=1.0;
- scale.z-=1.0;
- tr.track->scale+=scale*tr.weight;
-
- tr.track->rot = tr.track->rot * empty_rot.slerp(rot,tr.weight);
+ scale.x -= 1.0;
+ scale.y -= 1.0;
+ scale.z -= 1.0;
+ tr.track->scale += scale * tr.weight;
+ tr.track->rot = tr.track->rot * empty_rot.slerp(rot, tr.weight);
} break;
case Animation::TYPE_VALUE: { ///< Set a value in a property, can be interpolated.
- if (a->value_track_get_update_mode(tr.local_track)==Animation::UPDATE_CONTINUOUS) {
- Variant value = a->value_track_interpolate(tr.local_track,anim_list->time);
- Variant::blend(tr.track->value,value,tr.weight,tr.track->value);
+ if (a->value_track_get_update_mode(tr.local_track) == Animation::UPDATE_CONTINUOUS) {
+ Variant value = a->value_track_interpolate(tr.local_track, anim_list->time);
+ Variant::blend(tr.track->value, value, tr.weight, tr.track->value);
} else {
- int index = a->track_find_key(tr.local_track,anim_list->time);
+ int index = a->track_find_key(tr.local_track, anim_list->time);
tr.track->value = a->track_get_key_value(tr.local_track, index);
}
} break;
case Animation::TYPE_METHOD: { ///< Call any method on a specific node.
List<int> indices;
- a->method_track_get_key_indices(tr.local_track,anim_list->time,anim_list->step,&indices);
- for(List<int>::Element *E=indices.front();E;E=E->next()) {
+ a->method_track_get_key_indices(tr.local_track, anim_list->time, anim_list->step, &indices);
+ for (List<int>::Element *E = indices.front(); E; E = E->next()) {
- StringName method = a->method_track_get_name(tr.local_track,E->get());
- Vector<Variant> args=a->method_track_get_params(tr.local_track,E->get());
+ StringName method = a->method_track_get_name(tr.local_track, E->get());
+ Vector<Variant> args = a->method_track_get_params(tr.local_track, E->get());
args.resize(VARIANT_ARG_MAX);
- tr.track->object->call(method,args[0],args[1],args[2],args[3],args[4]);
+ tr.track->object->call(method, args[0], args[1], args[2], args[3], args[4]);
}
} break;
}
-
}
}
- anim_list=anim_list->next;
+ anim_list = anim_list->next;
}
/* STEP 3 APPLY TRACKS */
- for(TrackMap::Element *E=track_map.front();E;E=E->next()) {
+ for (TrackMap::Element *E = track_map.front(); E; E = E->next()) {
Track &t = E->get();
if (t.skip || !t.object)
continue;
- if(t.property) { // value track
- t.object->set(t.property,t.value);
+ if (t.property) { // value track
+ t.object->set(t.property, t.value);
continue;
}
Transform xform;
- xform.basis=t.rot;
- xform.origin=t.loc;
+ xform.basis = t.rot;
+ xform.origin = t.loc;
- t.scale.x+=1.0;
- t.scale.y+=1.0;
- t.scale.z+=1.0;
+ t.scale.x += 1.0;
+ t.scale.y += 1.0;
+ t.scale.z += 1.0;
xform.basis.scale(t.scale);
- if (t.bone_idx>=0) {
+ if (t.bone_idx >= 0) {
if (t.skeleton)
- t.skeleton->set_bone_pose(t.bone_idx,xform);
+ t.skeleton->set_bone_pose(t.bone_idx, xform);
} else if (t.spatial) {
t.spatial->set_transform(xform);
}
}
-
-
-
}
+void AnimationTreePlayer::add_node(NodeType p_type, const StringName &p_node) {
-void AnimationTreePlayer::add_node(NodeType p_type, const StringName& p_node) {
+ ERR_FAIL_COND(p_type == NODE_OUTPUT);
+ ERR_FAIL_COND(node_map.has(p_node));
- ERR_FAIL_COND( p_type == NODE_OUTPUT );
- ERR_FAIL_COND( node_map.has(p_node));
+ NodeBase *n = NULL;
- NodeBase *n=NULL;
-
- switch(p_type) {
+ switch (p_type) {
case NODE_ANIMATION: {
- n = memnew( AnimationNode );
+ n = memnew(AnimationNode);
} break;
case NODE_ONESHOT: {
- n = memnew( OneShotNode );
+ n = memnew(OneShotNode);
} break;
case NODE_MIX: {
- n = memnew( MixNode );
+ n = memnew(MixNode);
} break;
case NODE_BLEND2: {
- n = memnew( Blend2Node );
+ n = memnew(Blend2Node);
} break;
case NODE_BLEND3: {
- n = memnew( Blend3Node );
+ n = memnew(Blend3Node);
} break;
case NODE_BLEND4: {
- n = memnew( Blend4Node );
+ n = memnew(Blend4Node);
} break;
case NODE_TIMESCALE: {
- n = memnew( TimeScaleNode );
-
+ n = memnew(TimeScaleNode);
} break;
case NODE_TIMESEEK: {
- n = memnew( TimeSeekNode );
+ n = memnew(TimeSeekNode);
} break;
case NODE_TRANSITION: {
- n = memnew( TransitionNode );
-
+ n = memnew(TransitionNode);
} break;
default: {}
}
//n->name+=" "+itos(p_node);
- node_map[p_node]=n;
+ node_map[p_node] = n;
}
+StringName AnimationTreePlayer::node_get_input_source(const StringName &p_node, int p_input) const {
-StringName AnimationTreePlayer::node_get_input_source(const StringName& p_node,int p_input) const {
-
- ERR_FAIL_COND_V(!node_map.has(p_node),StringName());
- ERR_FAIL_INDEX_V( p_input,node_map[p_node]->inputs.size(),StringName() );
+ ERR_FAIL_COND_V(!node_map.has(p_node), StringName());
+ ERR_FAIL_INDEX_V(p_input, node_map[p_node]->inputs.size(), StringName());
return node_map[p_node]->inputs[p_input].node;
-
}
+int AnimationTreePlayer::node_get_input_count(const StringName &p_node) const {
-int AnimationTreePlayer::node_get_input_count(const StringName& p_node) const {
-
- ERR_FAIL_COND_V(!node_map.has(p_node),-1);
+ ERR_FAIL_COND_V(!node_map.has(p_node), -1);
return node_map[p_node]->inputs.size();
-
}
-#define GET_NODE( m_type, m_cast )\
- ERR_FAIL_COND(!node_map.has(p_node));\
- ERR_EXPLAIN("Invalid parameter for node type.");\
- ERR_FAIL_COND(node_map[p_node]->type!=m_type);\
- m_cast *n = static_cast<m_cast*>( node_map[p_node] );\
-
-
-
-void AnimationTreePlayer::animation_node_set_animation(const StringName& p_node,const Ref<Animation>& p_animation) {
-
- GET_NODE( NODE_ANIMATION, AnimationNode );
- n->animation=p_animation;
- dirty_caches=true;
+#define GET_NODE(m_type, m_cast) \
+ ERR_FAIL_COND(!node_map.has(p_node)); \
+ ERR_EXPLAIN("Invalid parameter for node type."); \
+ ERR_FAIL_COND(node_map[p_node]->type != m_type); \
+ m_cast *n = static_cast<m_cast *>(node_map[p_node]);
+void AnimationTreePlayer::animation_node_set_animation(const StringName &p_node, const Ref<Animation> &p_animation) {
+ GET_NODE(NODE_ANIMATION, AnimationNode);
+ n->animation = p_animation;
+ dirty_caches = true;
}
-void AnimationTreePlayer::animation_node_set_master_animation(const StringName& p_node,const String& p_master_animation) {
+void AnimationTreePlayer::animation_node_set_master_animation(const StringName &p_node, const String &p_master_animation) {
- GET_NODE( NODE_ANIMATION, AnimationNode );
- n->from=p_master_animation;
- dirty_caches=true;
- if (master!=NodePath())
+ GET_NODE(NODE_ANIMATION, AnimationNode);
+ n->from = p_master_animation;
+ dirty_caches = true;
+ if (master != NodePath())
_update_sources();
-
-
}
-void AnimationTreePlayer::animation_node_set_filter_path(const StringName& p_node,const NodePath& p_track_path,bool p_filter) {
+void AnimationTreePlayer::animation_node_set_filter_path(const StringName &p_node, const NodePath &p_track_path, bool p_filter) {
- GET_NODE( NODE_ANIMATION, AnimationNode );
+ GET_NODE(NODE_ANIMATION, AnimationNode);
if (p_filter)
- n->filter[p_track_path]=true;
+ n->filter[p_track_path] = true;
else
n->filter.erase(p_track_path);
-
}
-void AnimationTreePlayer::animation_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const{
+void AnimationTreePlayer::animation_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const {
- GET_NODE( NODE_ANIMATION, AnimationNode );
+ GET_NODE(NODE_ANIMATION, AnimationNode);
n->filter.get_key_list(r_paths);
}
-void AnimationTreePlayer::oneshot_node_set_fadein_time(const StringName& p_node,float p_time) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->fade_in=p_time;
+void AnimationTreePlayer::oneshot_node_set_fadein_time(const StringName &p_node, float p_time) {
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->fade_in = p_time;
}
+void AnimationTreePlayer::oneshot_node_set_fadeout_time(const StringName &p_node, float p_time) {
-void AnimationTreePlayer::oneshot_node_set_fadeout_time(const StringName& p_node,float p_time) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->fade_out=p_time;
-
-
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->fade_out = p_time;
}
-void AnimationTreePlayer::oneshot_node_set_mix_mode(const StringName& p_node,bool p_mix) {
+void AnimationTreePlayer::oneshot_node_set_mix_mode(const StringName &p_node, bool p_mix) {
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->mix=p_mix;
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->mix = p_mix;
}
+void AnimationTreePlayer::oneshot_node_set_autorestart(const StringName &p_node, bool p_active) {
-void AnimationTreePlayer::oneshot_node_set_autorestart(const StringName& p_node,bool p_active) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->autorestart=p_active;
-
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->autorestart = p_active;
}
-void AnimationTreePlayer::oneshot_node_set_autorestart_delay(const StringName& p_node,float p_time) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->autorestart_delay=p_time;
+void AnimationTreePlayer::oneshot_node_set_autorestart_delay(const StringName &p_node, float p_time) {
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->autorestart_delay = p_time;
}
-void AnimationTreePlayer::oneshot_node_set_autorestart_random_delay(const StringName& p_node,float p_time) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->autorestart_random_delay=p_time;
+void AnimationTreePlayer::oneshot_node_set_autorestart_random_delay(const StringName &p_node, float p_time) {
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->autorestart_random_delay = p_time;
}
-void AnimationTreePlayer::oneshot_node_start(const StringName& p_node) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->active=true;
- n->start=true;
+void AnimationTreePlayer::oneshot_node_start(const StringName &p_node) {
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->active = true;
+ n->start = true;
}
+void AnimationTreePlayer::oneshot_node_stop(const StringName &p_node) {
-void AnimationTreePlayer::oneshot_node_stop(const StringName& p_node) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
- n->active=false;
-
+ GET_NODE(NODE_ONESHOT, OneShotNode);
+ n->active = false;
}
+void AnimationTreePlayer::oneshot_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable) {
-void AnimationTreePlayer::oneshot_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable) {
-
- GET_NODE( NODE_ONESHOT, OneShotNode );
+ GET_NODE(NODE_ONESHOT, OneShotNode);
if (p_enable)
- n->filter[p_filter]=true;
+ n->filter[p_filter] = true;
else
n->filter.erase(p_filter);
-
}
-void AnimationTreePlayer::oneshot_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const{
+void AnimationTreePlayer::oneshot_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const {
- GET_NODE( NODE_ONESHOT, OneShotNode );
+ GET_NODE(NODE_ONESHOT, OneShotNode);
n->filter.get_key_list(r_paths);
}
+void AnimationTreePlayer::mix_node_set_amount(const StringName &p_node, float p_amount) {
-void AnimationTreePlayer::mix_node_set_amount(const StringName& p_node,float p_amount) {
-
- GET_NODE( NODE_MIX, MixNode );
- n->amount=p_amount;
-
+ GET_NODE(NODE_MIX, MixNode);
+ n->amount = p_amount;
}
+void AnimationTreePlayer::blend2_node_set_amount(const StringName &p_node, float p_amount) {
-void AnimationTreePlayer::blend2_node_set_amount(const StringName& p_node,float p_amount) {
-
- GET_NODE( NODE_BLEND2, Blend2Node );
- n->value=p_amount;
-
+ GET_NODE(NODE_BLEND2, Blend2Node);
+ n->value = p_amount;
}
-void AnimationTreePlayer::blend2_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable) {
+void AnimationTreePlayer::blend2_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable) {
- GET_NODE( NODE_BLEND2, Blend2Node );
+ GET_NODE(NODE_BLEND2, Blend2Node);
if (p_enable)
- n->filter[p_filter]=true;
+ n->filter[p_filter] = true;
else
n->filter.erase(p_filter);
-
}
-void AnimationTreePlayer::blend2_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const{
+void AnimationTreePlayer::blend2_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const {
- GET_NODE( NODE_BLEND2, Blend2Node );
+ GET_NODE(NODE_BLEND2, Blend2Node);
n->filter.get_key_list(r_paths);
}
+void AnimationTreePlayer::blend3_node_set_amount(const StringName &p_node, float p_amount) {
-void AnimationTreePlayer::blend3_node_set_amount(const StringName& p_node,float p_amount) {
-
- GET_NODE( NODE_BLEND3, Blend3Node );
- n->value=p_amount;
-
+ GET_NODE(NODE_BLEND3, Blend3Node);
+ n->value = p_amount;
}
-void AnimationTreePlayer::blend4_node_set_amount(const StringName& p_node,const Vector2& p_amount) {
-
- GET_NODE( NODE_BLEND4, Blend4Node );
- n->value=p_amount;
+void AnimationTreePlayer::blend4_node_set_amount(const StringName &p_node, const Vector2 &p_amount) {
+ GET_NODE(NODE_BLEND4, Blend4Node);
+ n->value = p_amount;
}
-void AnimationTreePlayer::timescale_node_set_scale(const StringName& p_node,float p_scale) {
-
-
- GET_NODE( NODE_TIMESCALE, TimeScaleNode );
- n->scale=p_scale;
+void AnimationTreePlayer::timescale_node_set_scale(const StringName &p_node, float p_scale) {
+ GET_NODE(NODE_TIMESCALE, TimeScaleNode);
+ n->scale = p_scale;
}
-void AnimationTreePlayer::timeseek_node_seek(const StringName& p_node,float p_pos) {
-
-
- GET_NODE( NODE_TIMESEEK, TimeSeekNode );
- n->seek_pos=p_pos;
+void AnimationTreePlayer::timeseek_node_seek(const StringName &p_node, float p_pos) {
+ GET_NODE(NODE_TIMESEEK, TimeSeekNode);
+ n->seek_pos = p_pos;
}
-void AnimationTreePlayer::transition_node_set_input_count(const StringName& p_node, int p_inputs) {
-
+void AnimationTreePlayer::transition_node_set_input_count(const StringName &p_node, int p_inputs) {
- GET_NODE( NODE_TRANSITION, TransitionNode );
- ERR_FAIL_COND(p_inputs<1);
+ GET_NODE(NODE_TRANSITION, TransitionNode);
+ ERR_FAIL_COND(p_inputs < 1);
n->inputs.resize(p_inputs);
n->input_data.resize(p_inputs);
- last_error=_cycle_test(out_name);
-
+ last_error = _cycle_test(out_name);
}
-void AnimationTreePlayer::transition_node_set_input_auto_advance(const StringName& p_node, int p_input,bool p_auto_advance) {
+void AnimationTreePlayer::transition_node_set_input_auto_advance(const StringName &p_node, int p_input, bool p_auto_advance) {
- GET_NODE( NODE_TRANSITION, TransitionNode );
- ERR_FAIL_INDEX(p_input,n->input_data.size());
-
- n->input_data[p_input].auto_advance=p_auto_advance;
+ GET_NODE(NODE_TRANSITION, TransitionNode);
+ ERR_FAIL_INDEX(p_input, n->input_data.size());
+ n->input_data[p_input].auto_advance = p_auto_advance;
}
-void AnimationTreePlayer::transition_node_set_xfade_time(const StringName& p_node, float p_time) {
-
+void AnimationTreePlayer::transition_node_set_xfade_time(const StringName &p_node, float p_time) {
- GET_NODE( NODE_TRANSITION, TransitionNode );
- n->xfade=p_time;
+ GET_NODE(NODE_TRANSITION, TransitionNode);
+ n->xfade = p_time;
}
void AnimationTreePlayer::TransitionNode::set_current(int p_current) {
- ERR_FAIL_INDEX(p_current,inputs.size());
+ ERR_FAIL_INDEX(p_current, inputs.size());
- if (current==p_current)
+ if (current == p_current)
return;
- prev=current;
- prev_xfading=xfade;
- prev_time=time;
- time=0;
- current=p_current;
- switched=true;
+ prev = current;
+ prev_xfading = xfade;
+ prev_time = time;
+ time = 0;
+ current = p_current;
+ switched = true;
}
-void AnimationTreePlayer::transition_node_set_current(const StringName& p_node, int p_current) {
+void AnimationTreePlayer::transition_node_set_current(const StringName &p_node, int p_current) {
- GET_NODE( NODE_TRANSITION, TransitionNode );
+ GET_NODE(NODE_TRANSITION, TransitionNode);
n->set_current(p_current);
}
-
-void AnimationTreePlayer::node_set_pos(const StringName& p_node, const Vector2& p_pos) {
+void AnimationTreePlayer::node_set_pos(const StringName &p_node, const Vector2 &p_pos) {
ERR_FAIL_COND(!node_map.has(p_node));
- node_map[p_node]->pos=p_pos;
-
+ node_map[p_node]->pos = p_pos;
}
-AnimationTreePlayer::NodeType AnimationTreePlayer::node_get_type(const StringName& p_node) const {
+AnimationTreePlayer::NodeType AnimationTreePlayer::node_get_type(const StringName &p_node) const {
- ERR_FAIL_COND_V(!node_map.has(p_node),NODE_OUTPUT);
+ ERR_FAIL_COND_V(!node_map.has(p_node), NODE_OUTPUT);
return node_map[p_node]->type;
-
}
-Point2 AnimationTreePlayer::node_get_pos(const StringName& p_node) const {
+Point2 AnimationTreePlayer::node_get_pos(const StringName &p_node) const {
- ERR_FAIL_COND_V(!node_map.has(p_node),Point2());
+ ERR_FAIL_COND_V(!node_map.has(p_node), Point2());
return node_map[p_node]->pos;
-
-
}
-#define GET_NODE_V( m_type, m_cast, m_ret )\
- ERR_FAIL_COND_V(!node_map.has(p_node),m_ret);\
- ERR_EXPLAIN("Invalid parameter for node type.");\
- ERR_FAIL_COND_V(node_map[p_node]->type!=m_type,m_ret);\
- m_cast *n = static_cast<m_cast*>( node_map[p_node] );\
+#define GET_NODE_V(m_type, m_cast, m_ret) \
+ ERR_FAIL_COND_V(!node_map.has(p_node), m_ret); \
+ ERR_EXPLAIN("Invalid parameter for node type."); \
+ ERR_FAIL_COND_V(node_map[p_node]->type != m_type, m_ret); \
+ m_cast *n = static_cast<m_cast *>(node_map[p_node]);
-Ref<Animation> AnimationTreePlayer::animation_node_get_animation(const StringName& p_node) const {
+Ref<Animation> AnimationTreePlayer::animation_node_get_animation(const StringName &p_node) const {
GET_NODE_V(NODE_ANIMATION, AnimationNode, Ref<Animation>());
return n->animation;
-
}
-String AnimationTreePlayer::animation_node_get_master_animation(const StringName& p_node) const {
+String AnimationTreePlayer::animation_node_get_master_animation(const StringName &p_node) const {
GET_NODE_V(NODE_ANIMATION, AnimationNode, String());
return n->from;
-
}
-bool AnimationTreePlayer::animation_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const {
+bool AnimationTreePlayer::animation_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const {
- GET_NODE_V(NODE_ANIMATION, AnimationNode, 0 );
+ GET_NODE_V(NODE_ANIMATION, AnimationNode, 0);
return n->filter.has(p_path);
}
-float AnimationTreePlayer::oneshot_node_get_fadein_time(const StringName& p_node) const {
+float AnimationTreePlayer::oneshot_node_get_fadein_time(const StringName &p_node) const {
-
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->fade_in;
-
}
-float AnimationTreePlayer::oneshot_node_get_fadeout_time(const StringName& p_node) const {
+float AnimationTreePlayer::oneshot_node_get_fadeout_time(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->fade_out;
-
}
-bool AnimationTreePlayer::oneshot_node_get_mix_mode(const StringName& p_node) const {
+bool AnimationTreePlayer::oneshot_node_get_mix_mode(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->mix;
-
}
-bool AnimationTreePlayer::oneshot_node_has_autorestart(const StringName& p_node) const {
+bool AnimationTreePlayer::oneshot_node_has_autorestart(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->autorestart;
-
}
-float AnimationTreePlayer::oneshot_node_get_autorestart_delay(const StringName& p_node) const {
+float AnimationTreePlayer::oneshot_node_get_autorestart_delay(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->autorestart_delay;
-
}
-float AnimationTreePlayer::oneshot_node_get_autorestart_random_delay(const StringName& p_node) const {
+float AnimationTreePlayer::oneshot_node_get_autorestart_random_delay(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->autorestart_random_delay;
-
}
-bool AnimationTreePlayer::oneshot_node_is_active(const StringName& p_node) const {
-
+bool AnimationTreePlayer::oneshot_node_is_active(const StringName &p_node) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->active;
-
}
-bool AnimationTreePlayer::oneshot_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const {
+bool AnimationTreePlayer::oneshot_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const {
- GET_NODE_V(NODE_ONESHOT, OneShotNode, 0 );
+ GET_NODE_V(NODE_ONESHOT, OneShotNode, 0);
return n->filter.has(p_path);
}
+float AnimationTreePlayer::mix_node_get_amount(const StringName &p_node) const {
-float AnimationTreePlayer::mix_node_get_amount(const StringName& p_node) const {
-
- GET_NODE_V(NODE_MIX, MixNode, 0 );
+ GET_NODE_V(NODE_MIX, MixNode, 0);
return n->amount;
-
}
-float AnimationTreePlayer::blend2_node_get_amount(const StringName& p_node) const {
+float AnimationTreePlayer::blend2_node_get_amount(const StringName &p_node) const {
- GET_NODE_V(NODE_BLEND2, Blend2Node, 0 );
+ GET_NODE_V(NODE_BLEND2, Blend2Node, 0);
return n->value;
-
}
-bool AnimationTreePlayer::blend2_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const {
+bool AnimationTreePlayer::blend2_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const {
- GET_NODE_V(NODE_BLEND2, Blend2Node, 0 );
+ GET_NODE_V(NODE_BLEND2, Blend2Node, 0);
return n->filter.has(p_path);
}
-float AnimationTreePlayer::blend3_node_get_amount(const StringName& p_node) const {
-
+float AnimationTreePlayer::blend3_node_get_amount(const StringName &p_node) const {
- GET_NODE_V(NODE_BLEND3, Blend3Node, 0 );
+ GET_NODE_V(NODE_BLEND3, Blend3Node, 0);
return n->value;
-
}
-Vector2 AnimationTreePlayer::blend4_node_get_amount(const StringName& p_node) const {
+Vector2 AnimationTreePlayer::blend4_node_get_amount(const StringName &p_node) const {
- GET_NODE_V(NODE_BLEND4, Blend4Node, Vector2() );
+ GET_NODE_V(NODE_BLEND4, Blend4Node, Vector2());
return n->value;
-
}
-float AnimationTreePlayer::timescale_node_get_scale(const StringName& p_node) const {
+float AnimationTreePlayer::timescale_node_get_scale(const StringName &p_node) const {
- GET_NODE_V(NODE_TIMESCALE, TimeScaleNode, 0 );
+ GET_NODE_V(NODE_TIMESCALE, TimeScaleNode, 0);
return n->scale;
-
}
-void AnimationTreePlayer::transition_node_delete_input(const StringName& p_node, int p_input) {
+void AnimationTreePlayer::transition_node_delete_input(const StringName &p_node, int p_input) {
GET_NODE(NODE_TRANSITION, TransitionNode);
- ERR_FAIL_INDEX(p_input,n->inputs.size());
+ ERR_FAIL_INDEX(p_input, n->inputs.size());
- if (n->inputs.size()<=1)
+ if (n->inputs.size() <= 1)
return;
-
n->inputs.remove(p_input);
n->input_data.remove(p_input);
- last_error=_cycle_test(out_name);
+ last_error = _cycle_test(out_name);
}
+int AnimationTreePlayer::transition_node_get_input_count(const StringName &p_node) const {
-int AnimationTreePlayer::transition_node_get_input_count(const StringName& p_node) const {
-
- GET_NODE_V(NODE_TRANSITION, TransitionNode, 0 );
+ GET_NODE_V(NODE_TRANSITION, TransitionNode, 0);
return n->inputs.size();
}
-bool AnimationTreePlayer::transition_node_has_input_auto_advance(const StringName& p_node, int p_input) const {
+bool AnimationTreePlayer::transition_node_has_input_auto_advance(const StringName &p_node, int p_input) const {
- GET_NODE_V(NODE_TRANSITION, TransitionNode, false );
- ERR_FAIL_INDEX_V(p_input,n->inputs.size(),false);
+ GET_NODE_V(NODE_TRANSITION, TransitionNode, false);
+ ERR_FAIL_INDEX_V(p_input, n->inputs.size(), false);
return n->input_data[p_input].auto_advance;
-
}
-float AnimationTreePlayer::transition_node_get_xfade_time(const StringName& p_node) const {
+float AnimationTreePlayer::transition_node_get_xfade_time(const StringName &p_node) const {
- GET_NODE_V(NODE_TRANSITION, TransitionNode, 0 );
+ GET_NODE_V(NODE_TRANSITION, TransitionNode, 0);
return n->xfade;
-
}
-int AnimationTreePlayer::transition_node_get_current(const StringName& p_node) const {
+int AnimationTreePlayer::transition_node_get_current(const StringName &p_node) const {
- GET_NODE_V(NODE_TRANSITION, TransitionNode, -1 );
+ GET_NODE_V(NODE_TRANSITION, TransitionNode, -1);
return n->current;
-
}
- /*misc */
+/*misc */
void AnimationTreePlayer::get_node_list(List<StringName> *p_node_list) const {
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
- p_node_list->push_back( E->key() );
+ p_node_list->push_back(E->key());
}
}
-void AnimationTreePlayer::remove_node(const StringName& p_node) {
+void AnimationTreePlayer::remove_node(const StringName &p_node) {
- ERR_FAIL_COND( !node_map.has(p_node) );
+ ERR_FAIL_COND(!node_map.has(p_node));
ERR_EXPLAIN("Node 0 (output) can't be removed.");
- ERR_FAIL_COND( p_node == out_name );
+ ERR_FAIL_COND(p_node == out_name);
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *nb = E->get();
- for(int i=0;i<nb->inputs.size();i++) {
+ for (int i = 0; i < nb->inputs.size(); i++) {
- if (nb->inputs[i].node==p_node)
- nb->inputs[i].node=StringName();
+ if (nb->inputs[i].node == p_node)
+ nb->inputs[i].node = StringName();
}
}
node_map.erase(p_node);
// compute last error again, just in case
- last_error=_cycle_test(out_name);
- dirty_caches=true;
+ last_error = _cycle_test(out_name);
+ dirty_caches = true;
}
-
-AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringName& p_at_node) {
+AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringName &p_at_node) {
ERR_FAIL_COND_V(!node_map.has(p_at_node), CONNECT_INCOMPLETE);
@@ -1480,11 +1371,10 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringN
if (nb->cycletest)
return CONNECT_CYCLE;
+ nb->cycletest = true;
- nb->cycletest=true;
-
- for(int i=0;i<nb->inputs.size();i++) {
- if (nb->inputs[i].node==StringName())
+ for (int i = 0; i < nb->inputs.size(); i++) {
+ if (nb->inputs[i].node == StringName())
return CONNECT_INCOMPLETE;
ConnectError _err = _cycle_test(nb->inputs[i].node);
@@ -1495,195 +1385,184 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::_cycle_test(const StringN
return CONNECT_OK;
}
+Error AnimationTreePlayer::connect_nodes(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input) {
-Error AnimationTreePlayer::connect_nodes(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input) {
-
- ERR_FAIL_COND_V( !node_map.has(p_src_node) , ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V( !node_map.has(p_dst_node) , ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V( p_src_node==p_dst_node , ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!node_map.has(p_src_node), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(!node_map.has(p_dst_node), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_src_node == p_dst_node, ERR_INVALID_PARAMETER);
//NodeBase *src = node_map[p_src_node];
NodeBase *dst = node_map[p_dst_node];
- ERR_FAIL_INDEX_V( p_dst_input, dst->inputs.size(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_dst_input, dst->inputs.size(), ERR_INVALID_PARAMETER);
//int oldval = dst->inputs[p_dst_input].node;
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *nb = E->get();
- for(int i=0;i<nb->inputs.size();i++) {
+ for (int i = 0; i < nb->inputs.size(); i++) {
- if (nb->inputs[i].node==p_src_node)
- nb->inputs[i].node=StringName();
+ if (nb->inputs[i].node == p_src_node)
+ nb->inputs[i].node = StringName();
}
}
- dst->inputs[p_dst_input].node=p_src_node;
+ dst->inputs[p_dst_input].node = p_src_node;
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *nb = E->get();
- nb->cycletest=false;
+ nb->cycletest = false;
}
- last_error=_cycle_test(out_name);
+ last_error = _cycle_test(out_name);
if (last_error) {
- if (last_error==CONNECT_INCOMPLETE)
+ if (last_error == CONNECT_INCOMPLETE)
return ERR_UNCONFIGURED;
- else if (last_error==CONNECT_CYCLE)
+ else if (last_error == CONNECT_CYCLE)
return ERR_CYCLIC_LINK;
}
- dirty_caches=true;
+ dirty_caches = true;
return OK;
}
-bool AnimationTreePlayer::are_nodes_connected(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input) const {
+bool AnimationTreePlayer::are_nodes_connected(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input) const {
- ERR_FAIL_COND_V( !node_map.has(p_src_node) , false);
- ERR_FAIL_COND_V( !node_map.has(p_dst_node) , false);
- ERR_FAIL_COND_V( p_src_node==p_dst_node , false);
+ ERR_FAIL_COND_V(!node_map.has(p_src_node), false);
+ ERR_FAIL_COND_V(!node_map.has(p_dst_node), false);
+ ERR_FAIL_COND_V(p_src_node == p_dst_node, false);
NodeBase *dst = node_map[p_dst_node];
- return dst->inputs[p_dst_input].node==p_src_node;
-
+ return dst->inputs[p_dst_input].node == p_src_node;
}
-void AnimationTreePlayer::disconnect_nodes(const StringName& p_node, int p_input) {
+void AnimationTreePlayer::disconnect_nodes(const StringName &p_node, int p_input) {
- ERR_FAIL_COND( !node_map.has(p_node));
+ ERR_FAIL_COND(!node_map.has(p_node));
NodeBase *dst = node_map[p_node];
- ERR_FAIL_INDEX(p_input,dst->inputs.size());
- dst->inputs[p_input].node=StringName();
- last_error=CONNECT_INCOMPLETE;
- dirty_caches=true;
+ ERR_FAIL_INDEX(p_input, dst->inputs.size());
+ dst->inputs[p_input].node = StringName();
+ last_error = CONNECT_INCOMPLETE;
+ dirty_caches = true;
}
+void AnimationTreePlayer::get_connection_list(List<Connection> *p_connections) const {
-void AnimationTreePlayer::get_connection_list( List<Connection> *p_connections) const {
-
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *nb = E->get();
- for(int i=0;i<nb->inputs.size();i++) {
+ for (int i = 0; i < nb->inputs.size(); i++) {
- if (nb->inputs[i].node!=StringName()) {
+ if (nb->inputs[i].node != StringName()) {
Connection c;
- c.src_node=nb->inputs[i].node;
- c.dst_node=E->key();
- c.dst_input=i;
+ c.src_node = nb->inputs[i].node;
+ c.dst_node = E->key();
+ c.dst_input = i;
p_connections->push_back(c);
}
}
}
}
-AnimationTreePlayer::Track* AnimationTreePlayer::_find_track(const NodePath& p_path) {
+AnimationTreePlayer::Track *AnimationTreePlayer::_find_track(const NodePath &p_path) {
- Node *parent=get_node(base_path);
- ERR_FAIL_COND_V(!parent,NULL);
+ Node *parent = get_node(base_path);
+ ERR_FAIL_COND_V(!parent, NULL);
RES resource;
- Node *child=parent->get_node_and_resource(p_path,resource);
+ Node *child = parent->get_node_and_resource(p_path, resource);
if (!child) {
- String err = "Animation track references unknown Node: '"+String(p_path)+"'.";
+ String err = "Animation track references unknown Node: '" + String(p_path) + "'.";
WARN_PRINT(err.ascii().get_data());
return NULL;
}
- ObjectID id=child->get_instance_ID();
+ ObjectID id = child->get_instance_ID();
StringName property;
- int bone_idx=-1;
+ int bone_idx = -1;
if (p_path.get_property()) {
if (child->cast_to<Skeleton>())
- bone_idx = child->cast_to<Skeleton>()->find_bone( p_path.get_property() );
- if (bone_idx==-1)
- property=p_path.get_property();
+ bone_idx = child->cast_to<Skeleton>()->find_bone(p_path.get_property());
+ if (bone_idx == -1)
+ property = p_path.get_property();
}
TrackKey key;
- key.id=id;
- key.bone_idx=bone_idx;
- key.property=property;
+ key.id = id;
+ key.bone_idx = bone_idx;
+ key.property = property;
if (!track_map.has(key)) {
Track tr;
- tr.id=id;
- tr.object=resource.is_valid()?(Object*)resource.ptr():(Object*)child;
- tr.skeleton=child->cast_to<Skeleton>();
- tr.spatial=child->cast_to<Spatial>();
- tr.bone_idx=bone_idx;
- tr.property=property;
-
- track_map[key]=tr;
+ tr.id = id;
+ tr.object = resource.is_valid() ? (Object *)resource.ptr() : (Object *)child;
+ tr.skeleton = child->cast_to<Skeleton>();
+ tr.spatial = child->cast_to<Spatial>();
+ tr.bone_idx = bone_idx;
+ tr.property = property;
+
+ track_map[key] = tr;
}
return &track_map[key];
-
}
void AnimationTreePlayer::_recompute_caches() {
track_map.clear();
_recompute_caches(out_name);
- dirty_caches=false;
+ dirty_caches = false;
}
-void AnimationTreePlayer::_recompute_caches(const StringName& p_node) {
+void AnimationTreePlayer::_recompute_caches(const StringName &p_node) {
- ERR_FAIL_COND( !node_map.has(p_node) );
+ ERR_FAIL_COND(!node_map.has(p_node));
NodeBase *nb = node_map[p_node];
- if (nb->type==NODE_ANIMATION) {
+ if (nb->type == NODE_ANIMATION) {
- AnimationNode *an = static_cast<AnimationNode*>(nb);
+ AnimationNode *an = static_cast<AnimationNode *>(nb);
an->tref.clear();
if (!an->animation.is_null()) {
-
Ref<Animation> a = an->animation;
- for(int i=0;i<an->animation->get_track_count();i++) {
-
+ for (int i = 0; i < an->animation->get_track_count(); i++) {
Track *tr = _find_track(a->track_get_path(i));
if (!tr)
continue;
AnimationNode::TrackRef tref;
- tref.local_track=i;
- tref.track=tr;
- tref.weight=0;
+ tref.local_track = i;
+ tref.track = tr;
+ tref.weight = 0;
an->tref.push_back(tref);
-
}
}
}
- for(int i=0;i<nb->inputs.size();i++) {
+ for (int i = 0; i < nb->inputs.size(); i++) {
_recompute_caches(nb->inputs[i].node);
}
-
}
void AnimationTreePlayer::recompute_caches() {
- dirty_caches=true;
-
+ dirty_caches = true;
}
-
-
- /* playback */
+/* playback */
void AnimationTreePlayer::set_active(bool p_active) {
@@ -1699,7 +1578,6 @@ void AnimationTreePlayer::set_active(bool p_active) {
bool AnimationTreePlayer::is_active() const {
return active;
-
}
AnimationTreePlayer::ConnectError AnimationTreePlayer::get_last_error() const {
@@ -1709,33 +1587,31 @@ AnimationTreePlayer::ConnectError AnimationTreePlayer::get_last_error() const {
void AnimationTreePlayer::reset() {
-
- reset_request=true;
+ reset_request = true;
}
+void AnimationTreePlayer::set_base_path(const NodePath &p_path) {
-void AnimationTreePlayer::set_base_path(const NodePath& p_path) {
-
- base_path=p_path;
+ base_path = p_path;
recompute_caches();
}
-NodePath AnimationTreePlayer::get_base_path() const{
+NodePath AnimationTreePlayer::get_base_path() const {
return base_path;
}
-void AnimationTreePlayer::set_master_player(const NodePath& p_path) {
+void AnimationTreePlayer::set_master_player(const NodePath &p_path) {
- if (p_path==master)
+ if (p_path == master)
return;
- master=p_path;
+ master = p_path;
_update_sources();
recompute_caches();
}
-NodePath AnimationTreePlayer::get_master_player() const{
+NodePath AnimationTreePlayer::get_master_player() const {
return master;
}
@@ -1746,25 +1622,24 @@ PoolVector<String> AnimationTreePlayer::_get_node_list() {
get_node_list(&nl);
PoolVector<String> ret;
ret.resize(nl.size());
- int idx=0;
- for(List<StringName>::Element *E=nl.front();E;E=E->next()) {
- ret.set(idx++,E->get());
+ int idx = 0;
+ for (List<StringName>::Element *E = nl.front(); E; E = E->next()) {
+ ret.set(idx++, E->get());
}
return ret;
}
-
void AnimationTreePlayer::_update_sources() {
- if (master==NodePath())
+ if (master == NodePath())
return;
if (!is_inside_tree())
return;
Node *m = get_node(master);
if (!m) {
- master=NodePath();
+ master = NodePath();
ERR_FAIL_COND(!m);
}
@@ -1772,197 +1647,187 @@ void AnimationTreePlayer::_update_sources() {
if (!ap) {
- master=NodePath();
+ master = NodePath();
ERR_FAIL_COND(!ap);
}
- for (Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
- if (E->get()->type==NODE_ANIMATION) {
+ if (E->get()->type == NODE_ANIMATION) {
- AnimationNode *an = static_cast<AnimationNode*>(E->get());
+ AnimationNode *an = static_cast<AnimationNode *>(E->get());
- if (an->from!="") {
+ if (an->from != "") {
an->animation = ap->get_animation(an->from);
}
}
}
-
-
}
-bool AnimationTreePlayer::node_exists(const StringName& p_name) const {
+bool AnimationTreePlayer::node_exists(const StringName &p_name) const {
return (node_map.has(p_name));
}
-Error AnimationTreePlayer::node_rename(const StringName& p_node,const StringName& p_new_name) {
+Error AnimationTreePlayer::node_rename(const StringName &p_node, const StringName &p_new_name) {
- if (p_new_name==p_node)
+ if (p_new_name == p_node)
return OK;
- ERR_FAIL_COND_V(!node_map.has(p_node),ERR_ALREADY_EXISTS);
- ERR_FAIL_COND_V(node_map.has(p_new_name),ERR_ALREADY_EXISTS);
- ERR_FAIL_COND_V(p_new_name==StringName(),ERR_INVALID_DATA);
- ERR_FAIL_COND_V(p_node==out_name,ERR_INVALID_DATA);
- ERR_FAIL_COND_V(p_new_name==out_name,ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(!node_map.has(p_node), ERR_ALREADY_EXISTS);
+ ERR_FAIL_COND_V(node_map.has(p_new_name), ERR_ALREADY_EXISTS);
+ ERR_FAIL_COND_V(p_new_name == StringName(), ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_node == out_name, ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_new_name == out_name, ERR_INVALID_DATA);
- for(Map<StringName,NodeBase*>::Element *E=node_map.front();E;E=E->next()) {
+ for (Map<StringName, NodeBase *>::Element *E = node_map.front(); E; E = E->next()) {
NodeBase *nb = E->get();
- for(int i=0;i<nb->inputs.size();i++) {
+ for (int i = 0; i < nb->inputs.size(); i++) {
- if (nb->inputs[i].node==p_node) {
- nb->inputs[i].node=p_new_name;
+ if (nb->inputs[i].node == p_node) {
+ nb->inputs[i].node = p_new_name;
}
}
}
- node_map[p_new_name]=node_map[p_node];
+ node_map[p_new_name] = node_map[p_node];
node_map.erase(p_node);
return OK;
-
}
-
void AnimationTreePlayer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_node","type","id"),&AnimationTreePlayer::add_node);
-
- ClassDB::bind_method(D_METHOD("node_exists","node"),&AnimationTreePlayer::node_exists);
- ClassDB::bind_method(D_METHOD("node_rename","node","new_name"),&AnimationTreePlayer::node_rename);
-
- ClassDB::bind_method(D_METHOD("node_get_type","id"),&AnimationTreePlayer::node_get_type);
- ClassDB::bind_method(D_METHOD("node_get_input_count","id"),&AnimationTreePlayer::node_get_input_count);
- ClassDB::bind_method(D_METHOD("node_get_input_source","id","idx"),&AnimationTreePlayer::node_get_input_source);
+ ClassDB::bind_method(D_METHOD("add_node", "type", "id"), &AnimationTreePlayer::add_node);
- ClassDB::bind_method(D_METHOD("animation_node_set_animation","id","animation:Animation"),&AnimationTreePlayer::animation_node_set_animation);
- ClassDB::bind_method(D_METHOD("animation_node_get_animation:Animation","id"),&AnimationTreePlayer::animation_node_get_animation);
+ ClassDB::bind_method(D_METHOD("node_exists", "node"), &AnimationTreePlayer::node_exists);
+ ClassDB::bind_method(D_METHOD("node_rename", "node", "new_name"), &AnimationTreePlayer::node_rename);
- ClassDB::bind_method(D_METHOD("animation_node_set_master_animation","id","source"),&AnimationTreePlayer::animation_node_set_master_animation);
- ClassDB::bind_method(D_METHOD("animation_node_get_master_animation","id"),&AnimationTreePlayer::animation_node_get_master_animation);
- ClassDB::bind_method(D_METHOD("animation_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::animation_node_set_filter_path);
+ ClassDB::bind_method(D_METHOD("node_get_type", "id"), &AnimationTreePlayer::node_get_type);
+ ClassDB::bind_method(D_METHOD("node_get_input_count", "id"), &AnimationTreePlayer::node_get_input_count);
+ ClassDB::bind_method(D_METHOD("node_get_input_source", "id", "idx"), &AnimationTreePlayer::node_get_input_source);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_fadein_time","id","time_sec"),&AnimationTreePlayer::oneshot_node_set_fadein_time);
- ClassDB::bind_method(D_METHOD("oneshot_node_get_fadein_time","id"),&AnimationTreePlayer::oneshot_node_get_fadein_time);
+ ClassDB::bind_method(D_METHOD("animation_node_set_animation", "id", "animation:Animation"), &AnimationTreePlayer::animation_node_set_animation);
+ ClassDB::bind_method(D_METHOD("animation_node_get_animation:Animation", "id"), &AnimationTreePlayer::animation_node_get_animation);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_fadeout_time","id","time_sec"),&AnimationTreePlayer::oneshot_node_set_fadeout_time);
- ClassDB::bind_method(D_METHOD("oneshot_node_get_fadeout_time","id"),&AnimationTreePlayer::oneshot_node_get_fadeout_time);
+ ClassDB::bind_method(D_METHOD("animation_node_set_master_animation", "id", "source"), &AnimationTreePlayer::animation_node_set_master_animation);
+ ClassDB::bind_method(D_METHOD("animation_node_get_master_animation", "id"), &AnimationTreePlayer::animation_node_get_master_animation);
+ ClassDB::bind_method(D_METHOD("animation_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::animation_node_set_filter_path);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_fadein_time", "id", "time_sec"), &AnimationTreePlayer::oneshot_node_set_fadein_time);
+ ClassDB::bind_method(D_METHOD("oneshot_node_get_fadein_time", "id"), &AnimationTreePlayer::oneshot_node_get_fadein_time);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart","id","enable"),&AnimationTreePlayer::oneshot_node_set_autorestart);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_delay","id","delay_sec"),&AnimationTreePlayer::oneshot_node_set_autorestart_delay);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_random_delay","id","rand_sec"),&AnimationTreePlayer::oneshot_node_set_autorestart_random_delay);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_fadeout_time", "id", "time_sec"), &AnimationTreePlayer::oneshot_node_set_fadeout_time);
+ ClassDB::bind_method(D_METHOD("oneshot_node_get_fadeout_time", "id"), &AnimationTreePlayer::oneshot_node_get_fadeout_time);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart", "id", "enable"), &AnimationTreePlayer::oneshot_node_set_autorestart);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_delay", "id", "delay_sec"), &AnimationTreePlayer::oneshot_node_set_autorestart_delay);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_autorestart_random_delay", "id", "rand_sec"), &AnimationTreePlayer::oneshot_node_set_autorestart_random_delay);
- ClassDB::bind_method(D_METHOD("oneshot_node_has_autorestart","id"),&AnimationTreePlayer::oneshot_node_has_autorestart);
- ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_delay","id"),&AnimationTreePlayer::oneshot_node_get_autorestart_delay);
- ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_random_delay","id"),&AnimationTreePlayer::oneshot_node_get_autorestart_random_delay);
+ ClassDB::bind_method(D_METHOD("oneshot_node_has_autorestart", "id"), &AnimationTreePlayer::oneshot_node_has_autorestart);
+ ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_delay", "id"), &AnimationTreePlayer::oneshot_node_get_autorestart_delay);
+ ClassDB::bind_method(D_METHOD("oneshot_node_get_autorestart_random_delay", "id"), &AnimationTreePlayer::oneshot_node_get_autorestart_random_delay);
- ClassDB::bind_method(D_METHOD("oneshot_node_start","id"),&AnimationTreePlayer::oneshot_node_start);
- ClassDB::bind_method(D_METHOD("oneshot_node_stop","id"),&AnimationTreePlayer::oneshot_node_stop);
- ClassDB::bind_method(D_METHOD("oneshot_node_is_active","id"),&AnimationTreePlayer::oneshot_node_is_active);
- ClassDB::bind_method(D_METHOD("oneshot_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::oneshot_node_set_filter_path);
+ ClassDB::bind_method(D_METHOD("oneshot_node_start", "id"), &AnimationTreePlayer::oneshot_node_start);
+ ClassDB::bind_method(D_METHOD("oneshot_node_stop", "id"), &AnimationTreePlayer::oneshot_node_stop);
+ ClassDB::bind_method(D_METHOD("oneshot_node_is_active", "id"), &AnimationTreePlayer::oneshot_node_is_active);
+ ClassDB::bind_method(D_METHOD("oneshot_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::oneshot_node_set_filter_path);
- ClassDB::bind_method(D_METHOD("mix_node_set_amount","id","ratio"),&AnimationTreePlayer::mix_node_set_amount);
- ClassDB::bind_method(D_METHOD("mix_node_get_amount","id"),&AnimationTreePlayer::mix_node_get_amount);
+ ClassDB::bind_method(D_METHOD("mix_node_set_amount", "id", "ratio"), &AnimationTreePlayer::mix_node_set_amount);
+ ClassDB::bind_method(D_METHOD("mix_node_get_amount", "id"), &AnimationTreePlayer::mix_node_get_amount);
- ClassDB::bind_method(D_METHOD("blend2_node_set_amount","id","blend"),&AnimationTreePlayer::blend2_node_set_amount);
- ClassDB::bind_method(D_METHOD("blend2_node_get_amount","id"),&AnimationTreePlayer::blend2_node_get_amount);
- ClassDB::bind_method(D_METHOD("blend2_node_set_filter_path","id","path","enable"),&AnimationTreePlayer::blend2_node_set_filter_path);
+ ClassDB::bind_method(D_METHOD("blend2_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend2_node_set_amount);
+ ClassDB::bind_method(D_METHOD("blend2_node_get_amount", "id"), &AnimationTreePlayer::blend2_node_get_amount);
+ ClassDB::bind_method(D_METHOD("blend2_node_set_filter_path", "id", "path", "enable"), &AnimationTreePlayer::blend2_node_set_filter_path);
- ClassDB::bind_method(D_METHOD("blend3_node_set_amount","id","blend"),&AnimationTreePlayer::blend3_node_set_amount);
- ClassDB::bind_method(D_METHOD("blend3_node_get_amount","id"),&AnimationTreePlayer::blend3_node_get_amount);
+ ClassDB::bind_method(D_METHOD("blend3_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend3_node_set_amount);
+ ClassDB::bind_method(D_METHOD("blend3_node_get_amount", "id"), &AnimationTreePlayer::blend3_node_get_amount);
- ClassDB::bind_method(D_METHOD("blend4_node_set_amount","id","blend"),&AnimationTreePlayer::blend4_node_set_amount);
- ClassDB::bind_method(D_METHOD("blend4_node_get_amount","id"),&AnimationTreePlayer::blend4_node_get_amount);
+ ClassDB::bind_method(D_METHOD("blend4_node_set_amount", "id", "blend"), &AnimationTreePlayer::blend4_node_set_amount);
+ ClassDB::bind_method(D_METHOD("blend4_node_get_amount", "id"), &AnimationTreePlayer::blend4_node_get_amount);
- ClassDB::bind_method(D_METHOD("timescale_node_set_scale","id","scale"),&AnimationTreePlayer::timescale_node_set_scale);
- ClassDB::bind_method(D_METHOD("timescale_node_get_scale","id"),&AnimationTreePlayer::timescale_node_get_scale);
+ ClassDB::bind_method(D_METHOD("timescale_node_set_scale", "id", "scale"), &AnimationTreePlayer::timescale_node_set_scale);
+ ClassDB::bind_method(D_METHOD("timescale_node_get_scale", "id"), &AnimationTreePlayer::timescale_node_get_scale);
- ClassDB::bind_method(D_METHOD("timeseek_node_seek","id","pos_sec"),&AnimationTreePlayer::timeseek_node_seek);
+ ClassDB::bind_method(D_METHOD("timeseek_node_seek", "id", "pos_sec"), &AnimationTreePlayer::timeseek_node_seek);
- ClassDB::bind_method(D_METHOD("transition_node_set_input_count","id","count"),&AnimationTreePlayer::transition_node_set_input_count);
- ClassDB::bind_method(D_METHOD("transition_node_get_input_count","id"),&AnimationTreePlayer::transition_node_get_input_count);
- ClassDB::bind_method(D_METHOD("transition_node_delete_input","id","input_idx"),&AnimationTreePlayer::transition_node_delete_input);
+ ClassDB::bind_method(D_METHOD("transition_node_set_input_count", "id", "count"), &AnimationTreePlayer::transition_node_set_input_count);
+ ClassDB::bind_method(D_METHOD("transition_node_get_input_count", "id"), &AnimationTreePlayer::transition_node_get_input_count);
+ ClassDB::bind_method(D_METHOD("transition_node_delete_input", "id", "input_idx"), &AnimationTreePlayer::transition_node_delete_input);
- ClassDB::bind_method(D_METHOD("transition_node_set_input_auto_advance","id","input_idx","enable"),&AnimationTreePlayer::transition_node_set_input_auto_advance);
- ClassDB::bind_method(D_METHOD("transition_node_has_input_auto_advance","id","input_idx"),&AnimationTreePlayer::transition_node_has_input_auto_advance);
+ ClassDB::bind_method(D_METHOD("transition_node_set_input_auto_advance", "id", "input_idx", "enable"), &AnimationTreePlayer::transition_node_set_input_auto_advance);
+ ClassDB::bind_method(D_METHOD("transition_node_has_input_auto_advance", "id", "input_idx"), &AnimationTreePlayer::transition_node_has_input_auto_advance);
- ClassDB::bind_method(D_METHOD("transition_node_set_xfade_time","id","time_sec"),&AnimationTreePlayer::transition_node_set_xfade_time);
- ClassDB::bind_method(D_METHOD("transition_node_get_xfade_time","id"),&AnimationTreePlayer::transition_node_get_xfade_time);
+ ClassDB::bind_method(D_METHOD("transition_node_set_xfade_time", "id", "time_sec"), &AnimationTreePlayer::transition_node_set_xfade_time);
+ ClassDB::bind_method(D_METHOD("transition_node_get_xfade_time", "id"), &AnimationTreePlayer::transition_node_get_xfade_time);
- ClassDB::bind_method(D_METHOD("transition_node_set_current","id","input_idx"),&AnimationTreePlayer::transition_node_set_current);
- ClassDB::bind_method(D_METHOD("transition_node_get_current","id"),&AnimationTreePlayer::transition_node_get_current);
+ ClassDB::bind_method(D_METHOD("transition_node_set_current", "id", "input_idx"), &AnimationTreePlayer::transition_node_set_current);
+ ClassDB::bind_method(D_METHOD("transition_node_get_current", "id"), &AnimationTreePlayer::transition_node_get_current);
+ ClassDB::bind_method(D_METHOD("node_set_pos", "id", "screen_pos"), &AnimationTreePlayer::node_set_pos);
+ ClassDB::bind_method(D_METHOD("node_get_pos", "id"), &AnimationTreePlayer::node_get_pos);
- ClassDB::bind_method(D_METHOD("node_set_pos","id","screen_pos"),&AnimationTreePlayer::node_set_pos);
- ClassDB::bind_method(D_METHOD("node_get_pos","id"),&AnimationTreePlayer::node_get_pos);
+ ClassDB::bind_method(D_METHOD("remove_node", "id"), &AnimationTreePlayer::remove_node);
+ ClassDB::bind_method(D_METHOD("connect_nodes", "id", "dst_id", "dst_input_idx"), &AnimationTreePlayer::connect_nodes);
+ ClassDB::bind_method(D_METHOD("are_nodes_connected", "id", "dst_id", "dst_input_idx"), &AnimationTreePlayer::are_nodes_connected);
+ ClassDB::bind_method(D_METHOD("disconnect_nodes", "id", "dst_input_idx"), &AnimationTreePlayer::disconnect_nodes);
- ClassDB::bind_method(D_METHOD("remove_node","id"),&AnimationTreePlayer::remove_node);
- ClassDB::bind_method(D_METHOD("connect_nodes","id","dst_id","dst_input_idx"),&AnimationTreePlayer::connect_nodes);
- ClassDB::bind_method(D_METHOD("are_nodes_connected","id","dst_id","dst_input_idx"),&AnimationTreePlayer::are_nodes_connected);
- ClassDB::bind_method(D_METHOD("disconnect_nodes","id","dst_input_idx"),&AnimationTreePlayer::disconnect_nodes);
+ ClassDB::bind_method(D_METHOD("set_active", "enabled"), &AnimationTreePlayer::set_active);
+ ClassDB::bind_method(D_METHOD("is_active"), &AnimationTreePlayer::is_active);
- ClassDB::bind_method(D_METHOD("set_active","enabled"),&AnimationTreePlayer::set_active);
- ClassDB::bind_method(D_METHOD("is_active"),&AnimationTreePlayer::is_active);
+ ClassDB::bind_method(D_METHOD("set_base_path", "path"), &AnimationTreePlayer::set_base_path);
+ ClassDB::bind_method(D_METHOD("get_base_path"), &AnimationTreePlayer::get_base_path);
- ClassDB::bind_method(D_METHOD("set_base_path","path"),&AnimationTreePlayer::set_base_path);
- ClassDB::bind_method(D_METHOD("get_base_path"),&AnimationTreePlayer::get_base_path);
+ ClassDB::bind_method(D_METHOD("set_master_player", "nodepath"), &AnimationTreePlayer::set_master_player);
+ ClassDB::bind_method(D_METHOD("get_master_player"), &AnimationTreePlayer::get_master_player);
- ClassDB::bind_method(D_METHOD("set_master_player","nodepath"),&AnimationTreePlayer::set_master_player);
- ClassDB::bind_method(D_METHOD("get_master_player"),&AnimationTreePlayer::get_master_player);
+ ClassDB::bind_method(D_METHOD("get_node_list"), &AnimationTreePlayer::_get_node_list);
- ClassDB::bind_method(D_METHOD("get_node_list"),&AnimationTreePlayer::_get_node_list);
-
- ClassDB::bind_method(D_METHOD("set_animation_process_mode","mode"),&AnimationTreePlayer::set_animation_process_mode);
- ClassDB::bind_method(D_METHOD("get_animation_process_mode"),&AnimationTreePlayer::get_animation_process_mode);
+ ClassDB::bind_method(D_METHOD("set_animation_process_mode", "mode"), &AnimationTreePlayer::set_animation_process_mode);
+ ClassDB::bind_method(D_METHOD("get_animation_process_mode"), &AnimationTreePlayer::get_animation_process_mode);
ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationTreePlayer::advance);
+ ClassDB::bind_method(D_METHOD("reset"), &AnimationTreePlayer::reset);
- ClassDB::bind_method(D_METHOD("reset"),&AnimationTreePlayer::reset);
-
- ClassDB::bind_method(D_METHOD("recompute_caches"),&AnimationTreePlayer::recompute_caches);
+ ClassDB::bind_method(D_METHOD("recompute_caches"), &AnimationTreePlayer::recompute_caches);
- ADD_GROUP("Playback","playback_");
+ ADD_GROUP("Playback", "playback_");
ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_animation_process_mode", "get_animation_process_mode");
- BIND_CONSTANT( NODE_OUTPUT );
- BIND_CONSTANT( NODE_ANIMATION );
- BIND_CONSTANT( NODE_ONESHOT );
- BIND_CONSTANT( NODE_MIX );
- BIND_CONSTANT( NODE_BLEND2 );
- BIND_CONSTANT( NODE_BLEND3 );
- BIND_CONSTANT( NODE_BLEND4 );
- BIND_CONSTANT( NODE_TIMESCALE );
- BIND_CONSTANT( NODE_TIMESEEK );
- BIND_CONSTANT( NODE_TRANSITION );
+ BIND_CONSTANT(NODE_OUTPUT);
+ BIND_CONSTANT(NODE_ANIMATION);
+ BIND_CONSTANT(NODE_ONESHOT);
+ BIND_CONSTANT(NODE_MIX);
+ BIND_CONSTANT(NODE_BLEND2);
+ BIND_CONSTANT(NODE_BLEND3);
+ BIND_CONSTANT(NODE_BLEND4);
+ BIND_CONSTANT(NODE_TIMESCALE);
+ BIND_CONSTANT(NODE_TIMESEEK);
+ BIND_CONSTANT(NODE_TRANSITION);
}
-
AnimationTreePlayer::AnimationTreePlayer() {
- active_list=NULL;
- out = memnew( NodeOut ) ;
- out_name="out";
- out->pos=Point2(40,40);
- node_map.insert( out_name , out);
+ active_list = NULL;
+ out = memnew(NodeOut);
+ out_name = "out";
+ out->pos = Point2(40, 40);
+ node_map.insert(out_name, out);
animation_process_mode = ANIMATION_PROCESS_IDLE;
processing = false;
- active=false;
- dirty_caches=true;
- reset_request=true;
- last_error=CONNECT_INCOMPLETE;
- base_path=String("..");
+ active = false;
+ dirty_caches = true;
+ reset_request = true;
+ last_error = CONNECT_INCOMPLETE;
+ base_path = String("..");
}
-
AnimationTreePlayer::~AnimationTreePlayer() {
- while(node_map.size()) {
- memdelete( node_map.front()->get() );
- node_map.erase( node_map.front() );
+ while (node_map.size()) {
+ memdelete(node_map.front()->get());
+ node_map.erase(node_map.front());
}
}
diff --git a/scene/animation/animation_tree_player.h b/scene/animation/animation_tree_player.h
index 5e118be034..35fce9b15d 100644
--- a/scene/animation/animation_tree_player.h
+++ b/scene/animation/animation_tree_player.h
@@ -29,16 +29,14 @@
#ifndef ANIMATION_TREE_PLAYER_H
#define ANIMATION_TREE_PLAYER_H
-
-#include "scene/resources/animation.h"
-#include "scene/3d/spatial.h"
-#include "scene/3d/skeleton.h"
#include "animation_player.h"
-
+#include "scene/3d/skeleton.h"
+#include "scene/3d/spatial.h"
+#include "scene/resources/animation.h"
class AnimationTreePlayer : public Node {
- GDCLASS( AnimationTreePlayer, Node );
+ GDCLASS(AnimationTreePlayer, Node);
OBJ_CATEGORY("Animation Nodes");
public:
@@ -71,10 +69,9 @@ public:
};
private:
-
enum {
- DISCONNECTED=-1,
+ DISCONNECTED = -1,
};
struct TrackKey {
@@ -83,23 +80,22 @@ private:
StringName property;
int bone_idx;
- inline bool operator<(const TrackKey& p_right) const {
+ inline bool operator<(const TrackKey &p_right) const {
- if (id==p_right.id) {
- if (bone_idx==p_right.bone_idx) {
- return property<p_right.property;
+ if (id == p_right.id) {
+ if (bone_idx == p_right.bone_idx) {
+ return property < p_right.property;
} else
- return bone_idx<p_right.bone_idx;
+ return bone_idx < p_right.bone_idx;
} else
- return id<p_right.id;
+ return id < p_right.id;
}
};
-
struct Track {
uint32_t id;
Object *object;
- Spatial* spatial;
+ Spatial *spatial;
Skeleton *skeleton;
int bone_idx;
StringName property;
@@ -113,12 +109,10 @@ private:
bool skip;
};
-
- typedef Map<TrackKey,Track> TrackMap;
+ typedef Map<TrackKey, Track> TrackMap;
TrackMap track_map;
-
struct Input {
StringName node;
@@ -132,23 +126,24 @@ private:
NodeType type;
Point2 pos;
-
Vector<Input> inputs;
NodeBase() { cycletest = false; };
- virtual ~NodeBase() { cycletest=false; }
+ virtual ~NodeBase() { cycletest = false; }
};
struct NodeOut : public NodeBase {
- NodeOut() { type=NODE_OUTPUT; inputs.resize(1); }
+ NodeOut() {
+ type = NODE_OUTPUT;
+ inputs.resize(1);
+ }
};
struct AnimationNode : public NodeBase {
Ref<Animation> animation;
-
struct TrackRef {
int local_track;
Track *track;
@@ -163,13 +158,17 @@ private:
String from;
bool skip;
- HashMap<NodePath,bool> filter;
+ HashMap<NodePath, bool> filter;
- AnimationNode() { type=NODE_ANIMATION; next=NULL; last_version=0; skip=false; }
+ AnimationNode() {
+ type = NODE_ANIMATION;
+ next = NULL;
+ last_version = 0;
+ skip = false;
+ }
};
-
- struct OneShotNode : public NodeBase {
+ struct OneShotNode : public NodeBase {
bool active;
bool start;
@@ -181,52 +180,84 @@ private:
float autorestart_random_delay;
bool mix;
-
float time;
float remaining;
float autorestart_remaining;
- HashMap<NodePath,bool> filter;
-
- OneShotNode() { type=NODE_ONESHOT; fade_in=0; fade_out=0; inputs.resize(2); autorestart=false; autorestart_delay=1; autorestart_remaining=0; mix=false; active=false; start=false;}
+ HashMap<NodePath, bool> filter;
+
+ OneShotNode() {
+ type = NODE_ONESHOT;
+ fade_in = 0;
+ fade_out = 0;
+ inputs.resize(2);
+ autorestart = false;
+ autorestart_delay = 1;
+ autorestart_remaining = 0;
+ mix = false;
+ active = false;
+ start = false;
+ }
};
struct MixNode : public NodeBase {
float amount;
- MixNode() { type=NODE_MIX; inputs.resize(2); }
+ MixNode() {
+ type = NODE_MIX;
+ inputs.resize(2);
+ }
};
- struct Blend2Node : public NodeBase {
+ struct Blend2Node : public NodeBase {
float value;
- HashMap<NodePath,bool> filter;
- Blend2Node() { type=NODE_BLEND2; value=0; inputs.resize(2); }
+ HashMap<NodePath, bool> filter;
+ Blend2Node() {
+ type = NODE_BLEND2;
+ value = 0;
+ inputs.resize(2);
+ }
};
struct Blend3Node : public NodeBase {
float value;
- Blend3Node() { type=NODE_BLEND3; value=0; inputs.resize(3); }
+ Blend3Node() {
+ type = NODE_BLEND3;
+ value = 0;
+ inputs.resize(3);
+ }
};
struct Blend4Node : public NodeBase {
Point2 value;
- Blend4Node() { type=NODE_BLEND4; inputs.resize(4); }
+ Blend4Node() {
+ type = NODE_BLEND4;
+ inputs.resize(4);
+ }
};
struct TimeScaleNode : public NodeBase {
float scale;
- TimeScaleNode() { type=NODE_TIMESCALE; scale=1; inputs.resize(1); }
+ TimeScaleNode() {
+ type = NODE_TIMESCALE;
+ scale = 1;
+ inputs.resize(1);
+ }
};
struct TimeSeekNode : public NodeBase {
float seek_pos;
- TimeSeekNode() { type=NODE_TIMESEEK; inputs.resize(1); seek_pos=-1; }
+ TimeSeekNode() {
+ type = NODE_TIMESEEK;
+ inputs.resize(1);
+ seek_pos = -1;
+ }
};
struct TransitionNode : public NodeBase {
@@ -234,7 +265,7 @@ private:
struct InputData {
bool auto_advance;
- InputData() { auto_advance=false; }
+ InputData() { auto_advance = false; }
};
Vector<InputData> input_data;
@@ -244,23 +275,30 @@ private:
int prev;
bool switched;
-
float time;
int current;
float xfade;
- TransitionNode() { type=NODE_TRANSITION; xfade=0; inputs.resize(1); input_data.resize(1); current=0; prev=-1; prev_time=0; prev_xfading=0; switched=false; }
+ TransitionNode() {
+ type = NODE_TRANSITION;
+ xfade = 0;
+ inputs.resize(1);
+ input_data.resize(1);
+ current = 0;
+ prev = -1;
+ prev_time = 0;
+ prev_xfading = 0;
+ switched = false;
+ }
void set_current(int p_current);
};
-
void _update_sources();
StringName out_name;
NodeOut *out;
-
NodePath base_path;
NodePath master;
@@ -270,141 +308,132 @@ private:
bool processing;
bool active;
bool dirty_caches;
- Map<StringName,NodeBase*> node_map;
+ Map<StringName, NodeBase *> node_map;
// return time left to finish animation
- float _process_node(const StringName& p_node,AnimationNode **r_prev_anim,float p_step, bool p_seek=false, float p_fallback_weight = 1.0, HashMap<NodePath,float>* p_weights = NULL);
+ float _process_node(const StringName &p_node, AnimationNode **r_prev_anim, float p_step, bool p_seek = false, float p_fallback_weight = 1.0, HashMap<NodePath, float> *p_weights = NULL);
void _process_animation(float p_delta);
bool reset_request;
ConnectError _cycle_test(const StringName &p_at_node);
- Track* _find_track(const NodePath& p_path);
+ Track *_find_track(const NodePath &p_path);
void _recompute_caches();
- void _recompute_caches(const StringName& p_node);
+ void _recompute_caches(const StringName &p_node);
PoolVector<String> _get_node_list();
-
- void _compute_weights(float *p_fallback_weight, HashMap<NodePath,float> *p_weights, float p_coeff, const HashMap<NodePath,bool> *p_filter = NULL, float p_filtered_coeff = 0);
-
-protected:
-
+ void _compute_weights(float *p_fallback_weight, HashMap<NodePath, float> *p_weights, float p_coeff, const HashMap<NodePath, bool> *p_filter = NULL, float p_filtered_coeff = 0);
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
-
public:
+ void add_node(NodeType p_type, const StringName &p_node); // nodes must be >0 node 0 is built-in (exit)
+ bool node_exists(const StringName &p_name) const;
-
- void add_node(NodeType p_type, const StringName& p_node); // nodes must be >0 node 0 is built-in (exit)
- bool node_exists(const StringName& p_name) const;
-
- Error node_rename(const StringName& p_node,const StringName& p_new_name);
- int node_get_input_count(const StringName& p_node) const;
- StringName node_get_input_source(const StringName& p_node,int p_input) const;
+ Error node_rename(const StringName &p_node, const StringName &p_new_name);
+ int node_get_input_count(const StringName &p_node) const;
+ StringName node_get_input_source(const StringName &p_node, int p_input) const;
/* ANIMATION NODE */
- void animation_node_set_animation(const StringName& p_node,const Ref<Animation>& p_animation);
- Ref<Animation> animation_node_get_animation(const StringName& p_node) const;
- void animation_node_set_master_animation(const StringName& p_node,const String& p_master_animation);
- String animation_node_get_master_animation(const StringName& p_node) const;
+ void animation_node_set_animation(const StringName &p_node, const Ref<Animation> &p_animation);
+ Ref<Animation> animation_node_get_animation(const StringName &p_node) const;
+ void animation_node_set_master_animation(const StringName &p_node, const String &p_master_animation);
+ String animation_node_get_master_animation(const StringName &p_node) const;
- void animation_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable);
- void animation_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const;
- bool animation_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const;
+ void animation_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable);
+ void animation_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const;
+ bool animation_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const;
/* ONE SHOT NODE */
- void oneshot_node_set_fadein_time(const StringName& p_node,float p_time);
- void oneshot_node_set_fadeout_time(const StringName& p_node,float p_time);
+ void oneshot_node_set_fadein_time(const StringName &p_node, float p_time);
+ void oneshot_node_set_fadeout_time(const StringName &p_node, float p_time);
- float oneshot_node_get_fadein_time(const StringName& p_node) const;
- float oneshot_node_get_fadeout_time(const StringName& p_node) const;
+ float oneshot_node_get_fadein_time(const StringName &p_node) const;
+ float oneshot_node_get_fadeout_time(const StringName &p_node) const;
- void oneshot_node_set_autorestart(const StringName& p_node,bool p_active);
- void oneshot_node_set_autorestart_delay(const StringName& p_node,float p_time);
- void oneshot_node_set_autorestart_random_delay(const StringName& p_node,float p_time);
+ void oneshot_node_set_autorestart(const StringName &p_node, bool p_active);
+ void oneshot_node_set_autorestart_delay(const StringName &p_node, float p_time);
+ void oneshot_node_set_autorestart_random_delay(const StringName &p_node, float p_time);
- bool oneshot_node_has_autorestart(const StringName& p_node) const;
- float oneshot_node_get_autorestart_delay(const StringName& p_node) const;
- float oneshot_node_get_autorestart_random_delay(const StringName& p_node) const;
+ bool oneshot_node_has_autorestart(const StringName &p_node) const;
+ float oneshot_node_get_autorestart_delay(const StringName &p_node) const;
+ float oneshot_node_get_autorestart_random_delay(const StringName &p_node) const;
- void oneshot_node_set_mix_mode(const StringName& p_node,bool p_enabled);
- bool oneshot_node_get_mix_mode(const StringName& p_node) const;
+ void oneshot_node_set_mix_mode(const StringName &p_node, bool p_enabled);
+ bool oneshot_node_get_mix_mode(const StringName &p_node) const;
- void oneshot_node_start(const StringName& p_node);
- void oneshot_node_stop(const StringName& p_node);
- bool oneshot_node_is_active(const StringName& p_node) const;
-
- void oneshot_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable);
- void oneshot_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const;
- bool oneshot_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const;
+ void oneshot_node_start(const StringName &p_node);
+ void oneshot_node_stop(const StringName &p_node);
+ bool oneshot_node_is_active(const StringName &p_node) const;
+ void oneshot_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable);
+ void oneshot_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const;
+ bool oneshot_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const;
/* MIX/BLEND NODES */
- void mix_node_set_amount(const StringName& p_node,float p_amount);
- float mix_node_get_amount(const StringName& p_node) const;
+ void mix_node_set_amount(const StringName &p_node, float p_amount);
+ float mix_node_get_amount(const StringName &p_node) const;
- void blend2_node_set_amount(const StringName& p_node,float p_amount);
- float blend2_node_get_amount(const StringName& p_node) const;
- void blend2_node_set_filter_path(const StringName& p_node,const NodePath& p_filter,bool p_enable);
- void blend2_node_set_get_filtered_paths(const StringName& p_node,List<NodePath> *r_paths) const;
- bool blend2_node_is_path_filtered(const StringName& p_node,const NodePath& p_path) const;
+ void blend2_node_set_amount(const StringName &p_node, float p_amount);
+ float blend2_node_get_amount(const StringName &p_node) const;
+ void blend2_node_set_filter_path(const StringName &p_node, const NodePath &p_filter, bool p_enable);
+ void blend2_node_set_get_filtered_paths(const StringName &p_node, List<NodePath> *r_paths) const;
+ bool blend2_node_is_path_filtered(const StringName &p_node, const NodePath &p_path) const;
- void blend3_node_set_amount(const StringName& p_node,float p_amount);
- float blend3_node_get_amount(const StringName& p_node) const;
+ void blend3_node_set_amount(const StringName &p_node, float p_amount);
+ float blend3_node_get_amount(const StringName &p_node) const;
- void blend4_node_set_amount(const StringName& p_node,const Point2& p_amount);
- Point2 blend4_node_get_amount(const StringName& p_node) const;
+ void blend4_node_set_amount(const StringName &p_node, const Point2 &p_amount);
+ Point2 blend4_node_get_amount(const StringName &p_node) const;
/* TIMESCALE/TIMESEEK NODES */
- void timescale_node_set_scale(const StringName& p_node,float p_scale);
- float timescale_node_get_scale(const StringName& p_node) const;
+ void timescale_node_set_scale(const StringName &p_node, float p_scale);
+ float timescale_node_get_scale(const StringName &p_node) const;
- void timeseek_node_seek(const StringName& p_node,float p_pos);
+ void timeseek_node_seek(const StringName &p_node, float p_pos);
/* TRANSITION NODE */
- void transition_node_set_input_count(const StringName& p_node, int p_inputs); // used for transition node
- int transition_node_get_input_count(const StringName& p_node) const;
- void transition_node_delete_input(const StringName& p_node, int p_input); // used for transition node
-
- void transition_node_set_input_auto_advance(const StringName& p_node, int p_input,bool p_auto_advance); // used for transition node
- bool transition_node_has_input_auto_advance(const StringName& p_node, int p_input) const;
+ void transition_node_set_input_count(const StringName &p_node, int p_inputs); // used for transition node
+ int transition_node_get_input_count(const StringName &p_node) const;
+ void transition_node_delete_input(const StringName &p_node, int p_input); // used for transition node
- void transition_node_set_xfade_time(const StringName& p_node, float p_time); // used for transition node
- float transition_node_get_xfade_time(const StringName& p_node) const;
+ void transition_node_set_input_auto_advance(const StringName &p_node, int p_input, bool p_auto_advance); // used for transition node
+ bool transition_node_has_input_auto_advance(const StringName &p_node, int p_input) const;
- void transition_node_set_current(const StringName& p_node, int p_current);
- int transition_node_get_current(const StringName& p_node) const;
+ void transition_node_set_xfade_time(const StringName &p_node, float p_time); // used for transition node
+ float transition_node_get_xfade_time(const StringName &p_node) const;
+ void transition_node_set_current(const StringName &p_node, int p_current);
+ int transition_node_get_current(const StringName &p_node) const;
- void node_set_pos(const StringName& p_node, const Vector2& p_pos); //for display
+ void node_set_pos(const StringName &p_node, const Vector2 &p_pos); //for display
/* GETS */
- Point2 node_get_pos(const StringName& p_node) const; //for display
+ Point2 node_get_pos(const StringName &p_node) const; //for display
- NodeType node_get_type(const StringName& p_node) const;
+ NodeType node_get_type(const StringName &p_node) const;
void get_node_list(List<StringName> *p_node_list) const;
- void remove_node(const StringName& p_node);
+ void remove_node(const StringName &p_node);
- Error connect_nodes(const StringName& p_src_node,const StringName& p_dst_node, int p_dst_input);
- bool are_nodes_connected(const StringName& p_src_node,const StringName& p_dst_node, int p_input) const;
- void disconnect_nodes(const StringName& p_src_node, int p_input);
+ Error connect_nodes(const StringName &p_src_node, const StringName &p_dst_node, int p_dst_input);
+ bool are_nodes_connected(const StringName &p_src_node, const StringName &p_dst_node, int p_input) const;
+ void disconnect_nodes(const StringName &p_src_node, int p_input);
- void set_base_path(const NodePath& p_path);
+ void set_base_path(const NodePath &p_path);
NodePath get_base_path() const;
- void set_master_player(const NodePath& p_path);
+ void set_master_player(const NodePath &p_path);
NodePath get_master_player() const;
struct Connection {
@@ -414,7 +443,7 @@ public:
int dst_input;
};
- void get_connection_list( List<Connection> *p_connections) const;
+ void get_connection_list(List<Connection> *p_connections) const;
/* playback */
@@ -436,12 +465,9 @@ public:
AnimationTreePlayer();
~AnimationTreePlayer();
-
};
-VARIANT_ENUM_CAST( AnimationTreePlayer::NodeType );
-VARIANT_ENUM_CAST( AnimationTreePlayer::AnimationProcessMode );
+VARIANT_ENUM_CAST(AnimationTreePlayer::NodeType);
+VARIANT_ENUM_CAST(AnimationTreePlayer::AnimationProcessMode);
#endif // ANIMATION_TREE_PLAYER_H
-
-
diff --git a/scene/animation/tween.cpp b/scene/animation/tween.cpp
index c422e765b5..c455d20b14 100644
--- a/scene/animation/tween.cpp
+++ b/scene/animation/tween.cpp
@@ -29,63 +29,60 @@
#include "tween.h"
#include "method_bind_ext.inc"
-void Tween::_add_pending_command(StringName p_key
- ,const Variant& p_arg1 ,const Variant& p_arg2 ,const Variant& p_arg3 ,const Variant& p_arg4 ,const Variant& p_arg5
- ,const Variant& p_arg6 ,const Variant& p_arg7 ,const Variant& p_arg8 ,const Variant& p_arg9 ,const Variant& p_arg10
-) {
+void Tween::_add_pending_command(StringName p_key, const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5, const Variant &p_arg6, const Variant &p_arg7, const Variant &p_arg8, const Variant &p_arg9, const Variant &p_arg10) {
pending_commands.push_back(PendingCommand());
- PendingCommand& cmd = pending_commands.back()->get();
+ PendingCommand &cmd = pending_commands.back()->get();
cmd.key = p_key;
- int& count = cmd.args;
- if(p_arg10.get_type() != Variant::NIL)
+ int &count = cmd.args;
+ if (p_arg10.get_type() != Variant::NIL)
count = 10;
- else if(p_arg9.get_type() != Variant::NIL)
+ else if (p_arg9.get_type() != Variant::NIL)
count = 9;
- else if(p_arg8.get_type() != Variant::NIL)
+ else if (p_arg8.get_type() != Variant::NIL)
count = 8;
- else if(p_arg7.get_type() != Variant::NIL)
+ else if (p_arg7.get_type() != Variant::NIL)
count = 7;
- else if(p_arg6.get_type() != Variant::NIL)
+ else if (p_arg6.get_type() != Variant::NIL)
count = 6;
- else if(p_arg5.get_type() != Variant::NIL)
+ else if (p_arg5.get_type() != Variant::NIL)
count = 5;
- else if(p_arg4.get_type() != Variant::NIL)
+ else if (p_arg4.get_type() != Variant::NIL)
count = 4;
- else if(p_arg3.get_type() != Variant::NIL)
+ else if (p_arg3.get_type() != Variant::NIL)
count = 3;
- else if(p_arg2.get_type() != Variant::NIL)
+ else if (p_arg2.get_type() != Variant::NIL)
count = 2;
- else if(p_arg1.get_type() != Variant::NIL)
+ else if (p_arg1.get_type() != Variant::NIL)
count = 1;
- if(count > 0)
+ if (count > 0)
cmd.arg[0] = p_arg1;
- if(count > 1)
+ if (count > 1)
cmd.arg[1] = p_arg2;
- if(count > 2)
+ if (count > 2)
cmd.arg[2] = p_arg3;
- if(count > 3)
+ if (count > 3)
cmd.arg[3] = p_arg4;
- if(count > 4)
+ if (count > 4)
cmd.arg[4] = p_arg5;
- if(count > 5)
+ if (count > 5)
cmd.arg[5] = p_arg6;
- if(count > 6)
+ if (count > 6)
cmd.arg[6] = p_arg7;
- if(count > 7)
+ if (count > 7)
cmd.arg[7] = p_arg8;
- if(count > 8)
+ if (count > 8)
cmd.arg[8] = p_arg9;
- if(count > 9)
+ if (count > 9)
cmd.arg[9] = p_arg10;
}
void Tween::_process_pending_commands() {
- for(List<PendingCommand>::Element *E=pending_commands.front();E;E=E->next()) {
+ for (List<PendingCommand>::Element *E = pending_commands.front(); E; E = E->next()) {
- PendingCommand& cmd = E->get();
+ PendingCommand &cmd = E->get();
Variant::CallError err;
Variant *arg[10] = {
&cmd.arg[0],
@@ -99,41 +96,40 @@ void Tween::_process_pending_commands() {
&cmd.arg[8],
&cmd.arg[9],
};
- this->call(cmd.key, (const Variant **) arg, cmd.args, err);
+ this->call(cmd.key, (const Variant **)arg, cmd.args, err);
}
pending_commands.clear();
}
-bool Tween::_set(const StringName& p_name, const Variant& p_value) {
+bool Tween::_set(const StringName &p_name, const Variant &p_value) {
- String name=p_name;
+ String name = p_name;
- if (name=="playback/speed" || name=="speed") { //bw compatibility
+ if (name == "playback/speed" || name == "speed") { //bw compatibility
set_speed_scale(p_value);
- } else if (name=="playback/active") {
+ } else if (name == "playback/active") {
set_active(p_value);
- } else if (name=="playback/repeat") {
+ } else if (name == "playback/repeat") {
set_repeat(p_value);
-
}
return true;
}
-bool Tween::_get(const StringName& p_name,Variant &r_ret) const {
+bool Tween::_get(const StringName &p_name, Variant &r_ret) const {
- String name=p_name;
+ String name = p_name;
- if (name=="playback/speed") { //bw compatibility
+ if (name == "playback/speed") { //bw compatibility
- r_ret=speed_scale;
- } else if (name=="playback/active") {
+ r_ret = speed_scale;
+ } else if (name == "playback/active") {
- r_ret=is_active();
- } else if(name=="playback/repeat") {
+ r_ret = is_active();
+ } else if (name == "playback/repeat") {
- r_ret=is_repeat();
+ r_ret = is_repeat();
}
return true;
@@ -141,14 +137,14 @@ bool Tween::_get(const StringName& p_name,Variant &r_ret) const {
void Tween::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo( Variant::BOOL, "playback/active", PROPERTY_HINT_NONE,"" ) );
- p_list->push_back( PropertyInfo( Variant::BOOL, "playback/repeat", PROPERTY_HINT_NONE,"" ) );
- p_list->push_back( PropertyInfo( Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01") );
+ p_list->push_back(PropertyInfo(Variant::BOOL, "playback/active", PROPERTY_HINT_NONE, ""));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "playback/repeat", PROPERTY_HINT_NONE, ""));
+ p_list->push_back(PropertyInfo(Variant::REAL, "playback/speed", PROPERTY_HINT_RANGE, "-64,64,0.01"));
}
void Tween::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
@@ -163,19 +159,19 @@ void Tween::_notification(int p_what) {
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
- if (tween_process_mode==TWEEN_PROCESS_FIXED)
+ if (tween_process_mode == TWEEN_PROCESS_FIXED)
break;
if (processing)
- _tween_process( get_process_delta_time() );
+ _tween_process(get_process_delta_time());
} break;
case NOTIFICATION_INTERNAL_FIXED_PROCESS: {
- if (tween_process_mode==TWEEN_PROCESS_IDLE)
+ if (tween_process_mode == TWEEN_PROCESS_IDLE)
break;
if (processing)
- _tween_process( get_fixed_process_delta_time() );
+ _tween_process(get_fixed_process_delta_time());
} break;
case NOTIFICATION_EXIT_TREE: {
@@ -186,46 +182,46 @@ void Tween::_notification(int p_what) {
void Tween::_bind_methods() {
- ClassDB::bind_method(D_METHOD("is_active"),&Tween::is_active );
- ClassDB::bind_method(D_METHOD("set_active","active"),&Tween::set_active );
-
- ClassDB::bind_method(D_METHOD("is_repeat"),&Tween::is_repeat );
- ClassDB::bind_method(D_METHOD("set_repeat","repeat"),&Tween::set_repeat );
-
- ClassDB::bind_method(D_METHOD("set_speed_scale","speed"),&Tween::set_speed_scale);
- ClassDB::bind_method(D_METHOD("get_speed_scale"),&Tween::get_speed_scale);
-
- ClassDB::bind_method(D_METHOD("set_tween_process_mode","mode"),&Tween::set_tween_process_mode);
- ClassDB::bind_method(D_METHOD("get_tween_process_mode"),&Tween::get_tween_process_mode);
-
- ClassDB::bind_method(D_METHOD("start"),&Tween::start );
- ClassDB::bind_method(D_METHOD("reset","object","key"),&Tween::reset, DEFVAL("") );
- ClassDB::bind_method(D_METHOD("reset_all"),&Tween::reset_all );
- ClassDB::bind_method(D_METHOD("stop","object","key"),&Tween::stop, DEFVAL("") );
- ClassDB::bind_method(D_METHOD("stop_all"),&Tween::stop_all );
- ClassDB::bind_method(D_METHOD("resume","object","key"),&Tween::resume, DEFVAL("") );
- ClassDB::bind_method(D_METHOD("resume_all"),&Tween::resume_all );
- ClassDB::bind_method(D_METHOD("remove","object","key"),&Tween::remove, DEFVAL("") );
- ClassDB::bind_method(D_METHOD("_remove","object","key","first_only"),&Tween::_remove );
- ClassDB::bind_method(D_METHOD("remove_all"),&Tween::remove_all );
- ClassDB::bind_method(D_METHOD("seek","time"),&Tween::seek );
- ClassDB::bind_method(D_METHOD("tell"),&Tween::tell );
- ClassDB::bind_method(D_METHOD("get_runtime"),&Tween::get_runtime );
-
- ClassDB::bind_method(D_METHOD("interpolate_property","object","property","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::interpolate_property, DEFVAL(0) );
- ClassDB::bind_method(D_METHOD("interpolate_method","object","method","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::interpolate_method, DEFVAL(0) );
- ClassDB::bind_method(D_METHOD("interpolate_callback","object","duration","callback","arg1", "arg2","arg3","arg4","arg5"),&Tween::interpolate_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()) );
- ClassDB::bind_method(D_METHOD("interpolate_deferred_callback","object","duration","callback","arg1","arg2","arg3","arg4","arg5"),&Tween::interpolate_deferred_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()) );
- ClassDB::bind_method(D_METHOD("follow_property","object","property","initial_val","target","target_property","duration","trans_type","ease_type","delay"),&Tween::follow_property, DEFVAL(0) );
- ClassDB::bind_method(D_METHOD("follow_method","object","method","initial_val","target","target_method","duration","trans_type","ease_type","delay"),&Tween::follow_method, DEFVAL(0) );
- ClassDB::bind_method(D_METHOD("targeting_property","object","property","initial","initial_val","final_val","duration","trans_type","ease_type","delay"),&Tween::targeting_property, DEFVAL(0) );
- ClassDB::bind_method(D_METHOD("targeting_method","object","method","initial","initial_method","final_val","duration","trans_type","ease_type","delay"),&Tween::targeting_method, DEFVAL(0) );
-
- ADD_SIGNAL( MethodInfo("tween_started", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key")) );
- ADD_SIGNAL( MethodInfo("tween_step", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key"), PropertyInfo( Variant::REAL,"elapsed"), PropertyInfo( Variant::OBJECT,"value")) );
- ADD_SIGNAL( MethodInfo("tween_completed", PropertyInfo( Variant::OBJECT,"object"), PropertyInfo( Variant::STRING,"key")) );
-
- ADD_PROPERTY( PropertyInfo( Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_tween_process_mode", "get_tween_process_mode");
+ ClassDB::bind_method(D_METHOD("is_active"), &Tween::is_active);
+ ClassDB::bind_method(D_METHOD("set_active", "active"), &Tween::set_active);
+
+ ClassDB::bind_method(D_METHOD("is_repeat"), &Tween::is_repeat);
+ ClassDB::bind_method(D_METHOD("set_repeat", "repeat"), &Tween::set_repeat);
+
+ ClassDB::bind_method(D_METHOD("set_speed_scale", "speed"), &Tween::set_speed_scale);
+ ClassDB::bind_method(D_METHOD("get_speed_scale"), &Tween::get_speed_scale);
+
+ ClassDB::bind_method(D_METHOD("set_tween_process_mode", "mode"), &Tween::set_tween_process_mode);
+ ClassDB::bind_method(D_METHOD("get_tween_process_mode"), &Tween::get_tween_process_mode);
+
+ ClassDB::bind_method(D_METHOD("start"), &Tween::start);
+ ClassDB::bind_method(D_METHOD("reset", "object", "key"), &Tween::reset, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("reset_all"), &Tween::reset_all);
+ ClassDB::bind_method(D_METHOD("stop", "object", "key"), &Tween::stop, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("stop_all"), &Tween::stop_all);
+ ClassDB::bind_method(D_METHOD("resume", "object", "key"), &Tween::resume, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("resume_all"), &Tween::resume_all);
+ ClassDB::bind_method(D_METHOD("remove", "object", "key"), &Tween::remove, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("_remove", "object", "key", "first_only"), &Tween::_remove);
+ ClassDB::bind_method(D_METHOD("remove_all"), &Tween::remove_all);
+ ClassDB::bind_method(D_METHOD("seek", "time"), &Tween::seek);
+ ClassDB::bind_method(D_METHOD("tell"), &Tween::tell);
+ ClassDB::bind_method(D_METHOD("get_runtime"), &Tween::get_runtime);
+
+ ClassDB::bind_method(D_METHOD("interpolate_property", "object", "property", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::interpolate_property, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("interpolate_method", "object", "method", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::interpolate_method, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("interpolate_callback", "object", "duration", "callback", "arg1", "arg2", "arg3", "arg4", "arg5"), &Tween::interpolate_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("interpolate_deferred_callback", "object", "duration", "callback", "arg1", "arg2", "arg3", "arg4", "arg5"), &Tween::interpolate_deferred_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("follow_property", "object", "property", "initial_val", "target", "target_property", "duration", "trans_type", "ease_type", "delay"), &Tween::follow_property, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("follow_method", "object", "method", "initial_val", "target", "target_method", "duration", "trans_type", "ease_type", "delay"), &Tween::follow_method, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("targeting_property", "object", "property", "initial", "initial_val", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::targeting_property, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("targeting_method", "object", "method", "initial", "initial_method", "final_val", "duration", "trans_type", "ease_type", "delay"), &Tween::targeting_method, DEFVAL(0));
+
+ ADD_SIGNAL(MethodInfo("tween_started", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key")));
+ ADD_SIGNAL(MethodInfo("tween_step", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key"), PropertyInfo(Variant::REAL, "elapsed"), PropertyInfo(Variant::OBJECT, "value")));
+ ADD_SIGNAL(MethodInfo("tween_completed", PropertyInfo(Variant::OBJECT, "object"), PropertyInfo(Variant::STRING, "key")));
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "playback_process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_tween_process_mode", "get_tween_process_mode");
BIND_CONSTANT(TWEEN_PROCESS_FIXED);
BIND_CONSTANT(TWEEN_PROCESS_IDLE);
@@ -248,9 +244,9 @@ void Tween::_bind_methods() {
BIND_CONSTANT(EASE_OUT_IN);
}
-Variant& Tween::_get_initial_val(InterpolateData& p_data) {
+Variant &Tween::_get_initial_val(InterpolateData &p_data) {
- switch(p_data.type) {
+ switch (p_data.type) {
case INTER_PROPERTY:
case INTER_METHOD:
case FOLLOW_PROPERTY:
@@ -260,31 +256,30 @@ Variant& Tween::_get_initial_val(InterpolateData& p_data) {
case TARGETING_PROPERTY:
case TARGETING_METHOD: {
- Object *object = ObjectDB::get_instance(p_data.target_id);
- ERR_FAIL_COND_V(object == NULL,p_data.initial_val);
+ Object *object = ObjectDB::get_instance(p_data.target_id);
+ ERR_FAIL_COND_V(object == NULL, p_data.initial_val);
- static Variant initial_val;
- if(p_data.type == TARGETING_PROPERTY) {
+ static Variant initial_val;
+ if (p_data.type == TARGETING_PROPERTY) {
- bool valid = false;
- initial_val = object->get(p_data.target_key, &valid);
- ERR_FAIL_COND_V(!valid,p_data.initial_val);
- } else {
+ bool valid = false;
+ initial_val = object->get(p_data.target_key, &valid);
+ ERR_FAIL_COND_V(!valid, p_data.initial_val);
+ } else {
- Variant::CallError error;
- initial_val = object->call(p_data.target_key, NULL, 0, error);
- ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK,p_data.initial_val);
- }
- return initial_val;
+ Variant::CallError error;
+ initial_val = object->call(p_data.target_key, NULL, 0, error);
+ ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, p_data.initial_val);
}
- break;
+ return initial_val;
+ } break;
}
return p_data.delta_val;
}
-Variant& Tween::_get_delta_val(InterpolateData& p_data) {
+Variant &Tween::_get_delta_val(InterpolateData &p_data) {
- switch(p_data.type) {
+ switch (p_data.type) {
case INTER_PROPERTY:
case INTER_METHOD:
return p_data.delta_val;
@@ -292,72 +287,68 @@ Variant& Tween::_get_delta_val(InterpolateData& p_data) {
case FOLLOW_PROPERTY:
case FOLLOW_METHOD: {
- Object *target = ObjectDB::get_instance(p_data.target_id);
- ERR_FAIL_COND_V(target == NULL,p_data.initial_val);
-
- Variant final_val;
+ Object *target = ObjectDB::get_instance(p_data.target_id);
+ ERR_FAIL_COND_V(target == NULL, p_data.initial_val);
- if(p_data.type == FOLLOW_PROPERTY) {
+ Variant final_val;
- bool valid = false;
- final_val = target->get(p_data.target_key, &valid);
- ERR_FAIL_COND_V(!valid,p_data.initial_val);
- } else {
+ if (p_data.type == FOLLOW_PROPERTY) {
- Variant::CallError error;
- final_val = target->call(p_data.target_key, NULL, 0, error);
- ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK,p_data.initial_val);
- }
+ bool valid = false;
+ final_val = target->get(p_data.target_key, &valid);
+ ERR_FAIL_COND_V(!valid, p_data.initial_val);
+ } else {
- // convert INT to REAL is better for interpolaters
- if(final_val.get_type() == Variant::INT) final_val = final_val.operator real_t();
- _calc_delta_val(p_data.initial_val, final_val, p_data.delta_val);
- return p_data.delta_val;
+ Variant::CallError error;
+ final_val = target->call(p_data.target_key, NULL, 0, error);
+ ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, p_data.initial_val);
}
- break;
+
+ // convert INT to REAL is better for interpolaters
+ if (final_val.get_type() == Variant::INT) final_val = final_val.operator real_t();
+ _calc_delta_val(p_data.initial_val, final_val, p_data.delta_val);
+ return p_data.delta_val;
+ } break;
case TARGETING_PROPERTY:
case TARGETING_METHOD: {
- Variant initial_val = _get_initial_val(p_data);
- // convert INT to REAL is better for interpolaters
- if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
+ Variant initial_val = _get_initial_val(p_data);
+ // convert INT to REAL is better for interpolaters
+ if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
- //_calc_delta_val(p_data.initial_val, p_data.final_val, p_data.delta_val);
- _calc_delta_val(initial_val, p_data.final_val, p_data.delta_val);
- return p_data.delta_val;
- }
- break;
+ //_calc_delta_val(p_data.initial_val, p_data.final_val, p_data.delta_val);
+ _calc_delta_val(initial_val, p_data.final_val, p_data.delta_val);
+ return p_data.delta_val;
+ } break;
}
return p_data.initial_val;
}
-Variant Tween::_run_equation(InterpolateData& p_data) {
+Variant Tween::_run_equation(InterpolateData &p_data) {
- Variant& initial_val = _get_initial_val(p_data);
- Variant& delta_val = _get_delta_val(p_data);
+ Variant &initial_val = _get_initial_val(p_data);
+ Variant &delta_val = _get_delta_val(p_data);
Variant result;
-#define APPLY_EQUATION(element)\
+#define APPLY_EQUATION(element) \
r.element = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, i.element, d.element, p_data.duration);
- switch(initial_val.get_type())
- {
+ switch (initial_val.get_type()) {
- case Variant::BOOL:
- result = ( _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, initial_val, delta_val, p_data.duration)) >= 0.5;
- break;
+ case Variant::BOOL:
+ result = (_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, initial_val, delta_val, p_data.duration)) >= 0.5;
+ break;
- case Variant::INT:
- result = (int) _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (int) initial_val, (int) delta_val, p_data.duration);
- break;
+ case Variant::INT:
+ result = (int)_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (int)initial_val, (int)delta_val, p_data.duration);
+ break;
- case Variant::REAL:
- result = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (real_t) initial_val, (real_t) delta_val, p_data.duration);
- break;
+ case Variant::REAL:
+ result = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (real_t)initial_val, (real_t)delta_val, p_data.duration);
+ break;
- case Variant::VECTOR2:
- {
+ case Variant::VECTOR2: {
Vector2 i = initial_val;
Vector2 d = delta_val;
Vector2 r;
@@ -366,11 +357,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(y);
result = r;
- }
- break;
+ } break;
- case Variant::VECTOR3:
- {
+ case Variant::VECTOR3: {
Vector3 i = initial_val;
Vector3 d = delta_val;
Vector3 r;
@@ -380,11 +369,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(z);
result = r;
- }
- break;
+ } break;
- case Variant::BASIS:
- {
+ case Variant::BASIS: {
Basis i = initial_val;
Basis d = delta_val;
Basis r;
@@ -400,11 +387,9 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(elements[2][2]);
result = r;
- }
- break;
+ } break;
- case Variant::TRANSFORM2D:
- {
+ case Variant::TRANSFORM2D: {
Transform2D i = initial_val;
Transform2D d = delta_val;
Transform2D r;
@@ -417,10 +402,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(elements[2][1]);
result = r;
- }
- break;
- case Variant::QUAT:
- {
+ } break;
+ case Variant::QUAT: {
Quat i = initial_val;
Quat d = delta_val;
Quat r;
@@ -431,10 +414,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(w);
result = r;
- }
- break;
- case Variant::RECT3:
- {
+ } break;
+ case Variant::RECT3: {
Rect3 i = initial_val;
Rect3 d = delta_val;
Rect3 r;
@@ -447,10 +428,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(size.z);
result = r;
- }
- break;
- case Variant::TRANSFORM:
- {
+ } break;
+ case Variant::TRANSFORM: {
Transform i = initial_val;
Transform d = delta_val;
Transform r;
@@ -469,10 +448,8 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(origin.z);
result = r;
- }
- break;
- case Variant::COLOR:
- {
+ } break;
+ case Variant::COLOR: {
Color i = initial_val;
Color d = delta_val;
Color r;
@@ -483,47 +460,44 @@ Variant Tween::_run_equation(InterpolateData& p_data) {
APPLY_EQUATION(a);
result = r;
- }
- break;
+ } break;
};
#undef APPLY_EQUATION
return result;
}
-bool Tween::_apply_tween_value(InterpolateData& p_data, Variant& value) {
+bool Tween::_apply_tween_value(InterpolateData &p_data, Variant &value) {
Object *object = ObjectDB::get_instance(p_data.id);
ERR_FAIL_COND_V(object == NULL, false);
- switch(p_data.type) {
+ switch (p_data.type) {
case INTER_PROPERTY:
case FOLLOW_PROPERTY:
- case TARGETING_PROPERTY:
- {
- bool valid = false;
- object->set(p_data.key,value, &valid);
- return valid;
- }
+ case TARGETING_PROPERTY: {
+ bool valid = false;
+ object->set(p_data.key, value, &valid);
+ return valid;
+ }
case INTER_METHOD:
case FOLLOW_METHOD:
- case TARGETING_METHOD:
- {
- Variant::CallError error;
- if (value.get_type() != Variant::NIL) {
- Variant *arg[1] = { &value };
- object->call(p_data.key, (const Variant **) arg, 1, error);
- } else {
- object->call(p_data.key, NULL, 0, error);
- }
-
- if(error.error == Variant::CallError::CALL_OK)
- return true;
- return false;
+ case TARGETING_METHOD: {
+ Variant::CallError error;
+ if (value.get_type() != Variant::NIL) {
+ Variant *arg[1] = { &value };
+ object->call(p_data.key, (const Variant **)arg, 1, error);
+ } else {
+ object->call(p_data.key, NULL, 0, error);
}
+ if (error.error == Variant::CallError::CALL_OK)
+ return true;
+ return false;
+ }
+
case INTER_CALLBACK:
break;
};
@@ -538,118 +512,122 @@ void Tween::_tween_process(float p_delta) {
return;
p_delta *= speed_scale;
- pending_update ++;
+ pending_update++;
// if repeat and all interpolates was finished then reset all interpolates
- if(repeat) {
+ if (repeat) {
bool all_finished = true;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
- if(!data.finish) {
+ if (!data.finish) {
all_finished = false;
break;
}
}
- if(all_finished)
+ if (all_finished)
reset_all();
}
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
- if(!data.active || data.finish)
+ InterpolateData &data = E->get();
+ if (!data.active || data.finish)
continue;
Object *object = ObjectDB::get_instance(data.id);
- if(object == NULL)
+ if (object == NULL)
continue;
bool prev_delaying = data.elapsed <= data.delay;
data.elapsed += p_delta;
- if(data.elapsed < data.delay)
+ if (data.elapsed < data.delay)
continue;
- else if(prev_delaying) {
+ else if (prev_delaying) {
- emit_signal("tween_started",object,data.key);
+ emit_signal("tween_started", object, data.key);
_apply_tween_value(data, data.initial_val);
}
- if(data.elapsed > (data.delay + data.duration)) {
+ if (data.elapsed > (data.delay + data.duration)) {
data.elapsed = data.delay + data.duration;
data.finish = true;
}
- switch(data.type)
- {
- case INTER_PROPERTY:
- case INTER_METHOD:
- break;
- case INTER_CALLBACK:
- if(data.finish) {
+ switch (data.type) {
+ case INTER_PROPERTY:
+ case INTER_METHOD:
+ break;
+ case INTER_CALLBACK:
+ if (data.finish) {
- Variant::CallError error;
- if (data.call_deferred) {
-
- switch (data.args) {
- case 0:
- object->call_deferred(data.key); break;
- case 1:
- object->call_deferred(data.key, data.arg[0]); break;
- case 2:
- object->call_deferred(data.key, data.arg[0], data.arg[1]); break;
- case 3:
- object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2]); break;
- case 4:
- object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3]); break;
- case 5:
- object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3], data.arg[4]); break;
+ Variant::CallError error;
+ if (data.call_deferred) {
+
+ switch (data.args) {
+ case 0:
+ object->call_deferred(data.key);
+ break;
+ case 1:
+ object->call_deferred(data.key, data.arg[0]);
+ break;
+ case 2:
+ object->call_deferred(data.key, data.arg[0], data.arg[1]);
+ break;
+ case 3:
+ object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2]);
+ break;
+ case 4:
+ object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3]);
+ break;
+ case 5:
+ object->call_deferred(data.key, data.arg[0], data.arg[1], data.arg[2], data.arg[3], data.arg[4]);
+ break;
+ }
+
+ } else {
+ Variant *arg[5] = {
+ &data.arg[0],
+ &data.arg[1],
+ &data.arg[2],
+ &data.arg[3],
+ &data.arg[4],
+ };
+ object->call(data.key, (const Variant **)arg, data.args, error);
}
-
- }
- else {
- Variant *arg[5] = {
- &data.arg[0],
- &data.arg[1],
- &data.arg[2],
- &data.arg[3],
- &data.arg[4],
- };
- object->call(data.key, (const Variant **) arg, data.args, error);
+ if (!repeat)
+ call_deferred("_remove", object, data.key, true);
}
- if (!repeat)
- call_deferred("_remove", object, data.key, true);
- }
- continue;
+ continue;
}
Variant result = _run_equation(data);
- emit_signal("tween_step",object,data.key,data.elapsed,result);
+ emit_signal("tween_step", object, data.key, data.elapsed, result);
_apply_tween_value(data, result);
if (data.finish) {
- emit_signal("tween_completed",object,data.key);
+ emit_signal("tween_completed", object, data.key);
// not repeat mode, remove completed action
if (!repeat)
call_deferred("_remove", object, data.key, true);
}
}
- pending_update --;
+ pending_update--;
}
void Tween::set_tween_process_mode(TweenProcessMode p_mode) {
- if (tween_process_mode==p_mode)
+ if (tween_process_mode == p_mode)
return;
bool pr = processing;
if (pr)
_set_process(false);
- tween_process_mode=p_mode;
+ tween_process_mode = p_mode;
if (pr)
_set_process(true);
}
@@ -659,18 +637,18 @@ Tween::TweenProcessMode Tween::get_tween_process_mode() const {
return tween_process_mode;
}
-void Tween::_set_process(bool p_process,bool p_force) {
+void Tween::_set_process(bool p_process, bool p_force) {
- if (processing==p_process && !p_force)
+ if (processing == p_process && !p_force)
return;
- switch(tween_process_mode) {
+ switch (tween_process_mode) {
case TWEEN_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break;
case TWEEN_PROCESS_IDLE: set_process_internal(p_process && active); break;
}
- processing=p_process;
+ processing = p_process;
}
bool Tween::is_active() const {
@@ -680,11 +658,11 @@ bool Tween::is_active() const {
void Tween::set_active(bool p_active) {
- if (active==p_active)
+ if (active == p_active)
return;
- active=p_active;
- _set_process(processing,true);
+ active = p_active;
+ _set_process(processing, true);
}
bool Tween::is_repeat() const {
@@ -699,7 +677,7 @@ void Tween::set_repeat(bool p_repeat) {
void Tween::set_speed_scale(float p_speed) {
- speed_scale=p_speed;
+ speed_scale = p_speed;
}
float Tween::get_speed_scale() const {
@@ -716,54 +694,54 @@ bool Tween::start() {
bool Tween::reset(Object *p_object, String p_key) {
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
Object *object = ObjectDB::get_instance(data.id);
- if(object == NULL)
+ if (object == NULL)
continue;
- if(object == p_object && (data.key == p_key || p_key == "")) {
+ if (object == p_object && (data.key == p_key || p_key == "")) {
data.elapsed = 0;
data.finish = false;
- if(data.delay == 0)
+ if (data.delay == 0)
_apply_tween_value(data, data.initial_val);
}
}
- pending_update --;
+ pending_update--;
return true;
}
bool Tween::reset_all() {
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
data.elapsed = 0;
data.finish = false;
- if(data.delay == 0)
+ if (data.delay == 0)
_apply_tween_value(data, data.initial_val);
}
- pending_update --;
+ pending_update--;
return true;
}
bool Tween::stop(Object *p_object, String p_key) {
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
Object *object = ObjectDB::get_instance(data.id);
- if(object == NULL)
+ if (object == NULL)
continue;
- if(object == p_object && (data.key == p_key || p_key == ""))
+ if (object == p_object && (data.key == p_key || p_key == ""))
data.active = false;
}
- pending_update --;
+ pending_update--;
return true;
}
@@ -772,13 +750,13 @@ bool Tween::stop_all() {
set_active(false);
_set_process(false);
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
data.active = false;
}
- pending_update --;
+ pending_update--;
return true;
}
@@ -787,17 +765,17 @@ bool Tween::resume(Object *p_object, String p_key) {
set_active(true);
_set_process(true);
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
Object *object = ObjectDB::get_instance(data.id);
- if(object == NULL)
+ if (object == NULL)
continue;
- if(object == p_object && (data.key == p_key || p_key == ""))
+ if (object == p_object && (data.key == p_key || p_key == ""))
data.active = true;
}
- pending_update --;
+ pending_update--;
return true;
}
@@ -806,13 +784,13 @@ bool Tween::resume_all() {
set_active(true);
_set_process(true);
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
data.active = true;
}
- pending_update --;
+ pending_update--;
return true;
}
@@ -823,32 +801,32 @@ bool Tween::remove(Object *p_object, String p_key) {
void Tween::_remove(Object *p_object, String p_key, bool first_only) {
- if(pending_update != 0) {
+ if (pending_update != 0) {
call_deferred("_remove", p_object, p_key, first_only);
return;
}
List<List<InterpolateData>::Element *> for_removal;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
Object *object = ObjectDB::get_instance(data.id);
- if(object == NULL)
+ if (object == NULL)
continue;
- if(object == p_object && (data.key == p_key || p_key == "")) {
+ if (object == p_object && (data.key == p_key || p_key == "")) {
for_removal.push_back(E);
if (first_only) {
break;
}
}
}
- for(List<List<InterpolateData>::Element *>::Element *E=for_removal.front();E;E=E->next()) {
+ for (List<List<InterpolateData>::Element *>::Element *E = for_removal.front(); E; E = E->next()) {
interpolates.erase(E->get());
}
}
bool Tween::remove_all() {
- if(pending_update != 0) {
+ if (pending_update != 0) {
call_deferred("remove_all");
return true;
}
@@ -860,89 +838,87 @@ bool Tween::remove_all() {
bool Tween::seek(real_t p_time) {
- pending_update ++;
- for(List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ pending_update++;
+ for (List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- InterpolateData& data = E->get();
+ InterpolateData &data = E->get();
data.elapsed = p_time;
- if(data.elapsed < data.delay) {
+ if (data.elapsed < data.delay) {
data.finish = false;
continue;
- }
- else if(data.elapsed >= (data.delay + data.duration)) {
+ } else if (data.elapsed >= (data.delay + data.duration)) {
data.finish = true;
data.elapsed = (data.delay + data.duration);
} else
data.finish = false;
- switch(data.type)
- {
- case INTER_PROPERTY:
- case INTER_METHOD:
- break;
- case INTER_CALLBACK:
- continue;
+ switch (data.type) {
+ case INTER_PROPERTY:
+ case INTER_METHOD:
+ break;
+ case INTER_CALLBACK:
+ continue;
}
Variant result = _run_equation(data);
_apply_tween_value(data, result);
}
- pending_update --;
+ pending_update--;
return true;
}
real_t Tween::tell() const {
- pending_update ++;
+ pending_update++;
real_t pos = 0;
- for(const List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ for (const List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- const InterpolateData& data = E->get();
- if(data.elapsed > pos)
+ const InterpolateData &data = E->get();
+ if (data.elapsed > pos)
pos = data.elapsed;
}
- pending_update --;
+ pending_update--;
return pos;
}
real_t Tween::get_runtime() const {
- pending_update ++;
+ pending_update++;
real_t runtime = 0;
- for(const List<InterpolateData>::Element *E=interpolates.front();E;E=E->next()) {
+ for (const List<InterpolateData>::Element *E = interpolates.front(); E; E = E->next()) {
- const InterpolateData& data = E->get();
+ const InterpolateData &data = E->get();
real_t t = data.delay + data.duration;
- if(t > runtime)
+ if (t > runtime)
runtime = t;
}
- pending_update --;
+ pending_update--;
return runtime;
}
-bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final_val, Variant& p_delta_val) {
+bool Tween::_calc_delta_val(const Variant &p_initial_val, const Variant &p_final_val, Variant &p_delta_val) {
- const Variant& initial_val = p_initial_val;
- const Variant& final_val = p_final_val;
- Variant& delta_val = p_delta_val;
+ const Variant &initial_val = p_initial_val;
+ const Variant &final_val = p_final_val;
+ Variant &delta_val = p_delta_val;
- switch(initial_val.get_type()) {
+ switch (initial_val.get_type()) {
case Variant::BOOL:
//delta_val = p_final_val;
- delta_val = (int) p_final_val - (int) p_initial_val;
+ delta_val = (int)p_final_val - (int)p_initial_val;
break;
case Variant::INT:
- delta_val = (int) final_val - (int) initial_val;
+ delta_val = (int)final_val - (int)initial_val;
break;
case Variant::REAL:
- delta_val = (real_t) final_val - (real_t) initial_val;
+ delta_val = (real_t)final_val - (real_t)initial_val;
break;
case Variant::VECTOR2:
@@ -953,11 +929,10 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final
delta_val = final_val.operator Vector3() - initial_val.operator Vector3();
break;
- case Variant::BASIS:
- {
- Basis i = initial_val;
- Basis f = final_val;
- delta_val = Basis(f.elements[0][0] - i.elements[0][0],
+ case Variant::BASIS: {
+ Basis i = initial_val;
+ Basis f = final_val;
+ delta_val = Basis(f.elements[0][0] - i.elements[0][0],
f.elements[0][1] - i.elements[0][1],
f.elements[0][2] - i.elements[0][2],
f.elements[1][0] - i.elements[1][0],
@@ -965,41 +940,34 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final
f.elements[1][2] - i.elements[1][2],
f.elements[2][0] - i.elements[2][0],
f.elements[2][1] - i.elements[2][1],
- f.elements[2][2] - i.elements[2][2]
- );
- }
- break;
+ f.elements[2][2] - i.elements[2][2]);
+ } break;
- case Variant::TRANSFORM2D:
- {
- Transform2D i = initial_val;
- Transform2D f = final_val;
- Transform2D d = Transform2D();
- d[0][0] = f.elements[0][0] - i.elements[0][0];
- d[0][1] = f.elements[0][1] - i.elements[0][1];
- d[1][0] = f.elements[1][0] - i.elements[1][0];
- d[1][1] = f.elements[1][1] - i.elements[1][1];
- d[2][0] = f.elements[2][0] - i.elements[2][0];
- d[2][1] = f.elements[2][1] - i.elements[2][1];
- delta_val = d;
- }
- break;
+ case Variant::TRANSFORM2D: {
+ Transform2D i = initial_val;
+ Transform2D f = final_val;
+ Transform2D d = Transform2D();
+ d[0][0] = f.elements[0][0] - i.elements[0][0];
+ d[0][1] = f.elements[0][1] - i.elements[0][1];
+ d[1][0] = f.elements[1][0] - i.elements[1][0];
+ d[1][1] = f.elements[1][1] - i.elements[1][1];
+ d[2][0] = f.elements[2][0] - i.elements[2][0];
+ d[2][1] = f.elements[2][1] - i.elements[2][1];
+ delta_val = d;
+ } break;
case Variant::QUAT:
delta_val = final_val.operator Quat() - initial_val.operator Quat();
break;
- case Variant::RECT3:
- {
- Rect3 i = initial_val;
- Rect3 f = final_val;
- delta_val = Rect3(f.pos - i.pos, f.size - i.size);
- }
- break;
- case Variant::TRANSFORM:
- {
- Transform i = initial_val;
- Transform f = final_val;
- Transform d;
- d.set(f.basis.elements[0][0] - i.basis.elements[0][0],
+ case Variant::RECT3: {
+ Rect3 i = initial_val;
+ Rect3 f = final_val;
+ delta_val = Rect3(f.pos - i.pos, f.size - i.size);
+ } break;
+ case Variant::TRANSFORM: {
+ Transform i = initial_val;
+ Transform f = final_val;
+ Transform d;
+ d.set(f.basis.elements[0][0] - i.basis.elements[0][0],
f.basis.elements[0][1] - i.basis.elements[0][1],
f.basis.elements[0][2] - i.basis.elements[0][2],
f.basis.elements[1][0] - i.basis.elements[1][0],
@@ -1010,19 +978,15 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final
f.basis.elements[2][2] - i.basis.elements[2][2],
f.origin.x - i.origin.x,
f.origin.y - i.origin.y,
- f.origin.z - i.origin.z
- );
+ f.origin.z - i.origin.z);
- delta_val = d;
- }
- break;
- case Variant::COLOR:
- {
- Color i = initial_val;
- Color f = final_val;
- delta_val = Color(f.r - i.r, f.g - i.g, f.b - i.b, f.a - i.a);
- }
- break;
+ delta_val = d;
+ } break;
+ case Variant::COLOR: {
+ Color i = initial_val;
+ Color f = final_val;
+ delta_val = Color(f.r - i.r, f.g - i.g, f.b - i.b, f.a - i.a);
+ } break;
default:
ERR_PRINT("Invalid param type, except(int/real/vector2/vector/matrix/matrix32/quat/aabb/transform/color)");
@@ -1031,31 +995,14 @@ bool Tween::_calc_delta_val(const Variant& p_initial_val, const Variant& p_final
return true;
}
-bool Tween::interpolate_property(Object *p_object
- , String p_property
- , Variant p_initial_val
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("interpolate_property"
- , p_object
- , p_property
- , p_initial_val
- , p_final_val
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::interpolate_property(Object *p_object, String p_property, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("interpolate_property", p_object, p_property, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
- if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
+ if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
+ if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1066,7 +1013,7 @@ bool Tween::interpolate_property(Object *p_object
ERR_FAIL_COND_V(p_delay < 0, false);
bool prop_valid = false;
- p_object->get(p_property,&prop_valid);
+ p_object->get(p_property, &prop_valid);
ERR_FAIL_COND_V(!prop_valid, false);
InterpolateData data;
@@ -1084,38 +1031,21 @@ bool Tween::interpolate_property(Object *p_object
data.ease_type = p_ease_type;
data.delay = p_delay;
- if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
+ if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
return false;
interpolates.push_back(data);
return true;
}
-bool Tween::interpolate_method(Object *p_object
- , String p_method
- , Variant p_initial_val
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("interpolate_method"
- , p_object
- , p_method
- , p_initial_val
- , p_final_val
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::interpolate_method(Object *p_object, String p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("interpolate_method", p_object, p_method, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
- if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
+ if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
+ if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1143,30 +1073,17 @@ bool Tween::interpolate_method(Object *p_object
data.ease_type = p_ease_type;
data.delay = p_delay;
- if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
+ if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
return false;
interpolates.push_back(data);
return true;
}
-bool Tween::interpolate_callback(Object *p_object
- , real_t p_duration
- , String p_callback
- , VARIANT_ARG_DECLARE
-) {
-
- if(pending_update != 0) {
- _add_pending_command("interpolate_callback"
- , p_object
- , p_duration
- , p_callback
- , p_arg1
- , p_arg2
- , p_arg3
- , p_arg4
- , p_arg5
- );
+bool Tween::interpolate_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) {
+
+ if (pending_update != 0) {
+ _add_pending_command("interpolate_callback", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5);
return true;
}
@@ -1189,19 +1106,19 @@ bool Tween::interpolate_callback(Object *p_object
data.duration = p_duration;
data.delay = 0;
- int args=0;
- if (p_arg5.get_type()!=Variant::NIL)
- args=5;
- else if (p_arg4.get_type()!=Variant::NIL)
- args=4;
- else if (p_arg3.get_type()!=Variant::NIL)
- args=3;
- else if (p_arg2.get_type()!=Variant::NIL)
- args=2;
- else if (p_arg1.get_type()!=Variant::NIL)
- args=1;
+ int args = 0;
+ if (p_arg5.get_type() != Variant::NIL)
+ args = 5;
+ else if (p_arg4.get_type() != Variant::NIL)
+ args = 4;
+ else if (p_arg3.get_type() != Variant::NIL)
+ args = 3;
+ else if (p_arg2.get_type() != Variant::NIL)
+ args = 2;
+ else if (p_arg1.get_type() != Variant::NIL)
+ args = 1;
else
- args=0;
+ args = 0;
data.args = args;
data.arg[0] = p_arg1;
@@ -1210,29 +1127,16 @@ bool Tween::interpolate_callback(Object *p_object
data.arg[3] = p_arg4;
data.arg[4] = p_arg5;
- pending_update ++;
+ pending_update++;
interpolates.push_back(data);
- pending_update --;
+ pending_update--;
return true;
}
-bool Tween::interpolate_deferred_callback(Object *p_object
- , real_t p_duration
- , String p_callback
- , VARIANT_ARG_DECLARE
-) {
-
- if(pending_update != 0) {
- _add_pending_command("interpolate_deferred_callback"
- , p_object
- , p_duration
- , p_callback
- , p_arg1
- , p_arg2
- , p_arg3
- , p_arg4
- , p_arg5
- );
+bool Tween::interpolate_deferred_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) {
+
+ if (pending_update != 0) {
+ _add_pending_command("interpolate_deferred_callback", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5);
return true;
}
ERR_FAIL_COND_V(p_object == NULL, false);
@@ -1254,19 +1158,19 @@ bool Tween::interpolate_deferred_callback(Object *p_object
data.duration = p_duration;
data.delay = 0;
- int args=0;
- if (p_arg5.get_type()!=Variant::NIL)
- args=5;
- else if (p_arg4.get_type()!=Variant::NIL)
- args=4;
- else if (p_arg3.get_type()!=Variant::NIL)
- args=3;
- else if (p_arg2.get_type()!=Variant::NIL)
- args=2;
- else if (p_arg1.get_type()!=Variant::NIL)
- args=1;
+ int args = 0;
+ if (p_arg5.get_type() != Variant::NIL)
+ args = 5;
+ else if (p_arg4.get_type() != Variant::NIL)
+ args = 4;
+ else if (p_arg3.get_type() != Variant::NIL)
+ args = 3;
+ else if (p_arg2.get_type() != Variant::NIL)
+ args = 2;
+ else if (p_arg1.get_type() != Variant::NIL)
+ args = 1;
else
- args=0;
+ args = 0;
data.args = args;
data.arg[0] = p_arg1;
@@ -1275,38 +1179,19 @@ bool Tween::interpolate_deferred_callback(Object *p_object
data.arg[3] = p_arg4;
data.arg[4] = p_arg5;
- pending_update ++;
+ pending_update++;
interpolates.push_back(data);
- pending_update --;
+ pending_update--;
return true;
}
-bool Tween::follow_property(Object *p_object
- , String p_property
- , Variant p_initial_val
- , Object *p_target
- , String p_target_property
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("follow_property"
- , p_object
- , p_property
- , p_initial_val
- , p_target
- , p_target_property
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::follow_property(Object *p_object, String p_property, Variant p_initial_val, Object *p_target, String p_target_property, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("follow_property", p_object, p_property, p_initial_val, p_target, p_target_property, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
+ if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1318,15 +1203,15 @@ bool Tween::follow_property(Object *p_object
ERR_FAIL_COND_V(p_delay < 0, false);
bool prop_valid = false;
- p_object->get(p_property,&prop_valid);
+ p_object->get(p_property, &prop_valid);
ERR_FAIL_COND_V(!prop_valid, false);
bool target_prop_valid = false;
- Variant target_val = p_target->get(p_target_property,&target_prop_valid);
+ Variant target_val = p_target->get(p_target_property, &target_prop_valid);
ERR_FAIL_COND_V(!target_prop_valid, false);
// convert INT to REAL is better for interpolaters
- if(target_val.get_type() == Variant::INT) target_val = target_val.operator real_t();
+ if (target_val.get_type() == Variant::INT) target_val = target_val.operator real_t();
ERR_FAIL_COND_V(target_val.get_type() != p_initial_val.get_type(), false);
InterpolateData data;
@@ -1349,32 +1234,13 @@ bool Tween::follow_property(Object *p_object
return true;
}
-bool Tween::follow_method(Object *p_object
- , String p_method
- , Variant p_initial_val
- , Object *p_target
- , String p_target_method
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("follow_method"
- , p_object
- , p_method
- , p_initial_val
- , p_target
- , p_target_method
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::follow_method(Object *p_object, String p_method, Variant p_initial_val, Object *p_target, String p_target_method, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("follow_method", p_object, p_method, p_initial_val, p_target, p_target_method, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
+ if (p_initial_val.get_type() == Variant::INT) p_initial_val = p_initial_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1395,7 +1261,7 @@ bool Tween::follow_method(Object *p_object
ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, false);
// convert INT to REAL is better for interpolaters
- if(target_val.get_type() == Variant::INT) target_val = target_val.operator real_t();
+ if (target_val.get_type() == Variant::INT) target_val = target_val.operator real_t();
ERR_FAIL_COND_V(target_val.get_type() != p_initial_val.get_type(), false);
InterpolateData data;
@@ -1418,32 +1284,13 @@ bool Tween::follow_method(Object *p_object
return true;
}
-bool Tween::targeting_property(Object *p_object
- , String p_property
- , Object *p_initial
- , String p_initial_property
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("targeting_property"
- , p_object
- , p_property
- , p_initial
- , p_initial_property
- , p_final_val
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::targeting_property(Object *p_object, String p_property, Object *p_initial, String p_initial_property, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("targeting_property", p_object, p_property, p_initial, p_initial_property, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
+ if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1455,15 +1302,15 @@ bool Tween::targeting_property(Object *p_object
ERR_FAIL_COND_V(p_delay < 0, false);
bool prop_valid = false;
- p_object->get(p_property,&prop_valid);
+ p_object->get(p_property, &prop_valid);
ERR_FAIL_COND_V(!prop_valid, false);
bool initial_prop_valid = false;
- Variant initial_val = p_initial->get(p_initial_property,&initial_prop_valid);
+ Variant initial_val = p_initial->get(p_initial_property, &initial_prop_valid);
ERR_FAIL_COND_V(!initial_prop_valid, false);
// convert INT to REAL is better for interpolaters
- if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
+ if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
ERR_FAIL_COND_V(initial_val.get_type() != p_final_val.get_type(), false);
InterpolateData data;
@@ -1483,40 +1330,20 @@ bool Tween::targeting_property(Object *p_object
data.ease_type = p_ease_type;
data.delay = p_delay;
- if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
+ if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
return false;
interpolates.push_back(data);
return true;
}
-
-bool Tween::targeting_method(Object *p_object
- , String p_method
- , Object *p_initial
- , String p_initial_method
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay
-) {
- if(pending_update != 0) {
- _add_pending_command("targeting_method"
- , p_object
- , p_method
- , p_initial
- , p_initial_method
- , p_final_val
- , p_duration
- , p_trans_type
- , p_ease_type
- , p_delay
- );
+bool Tween::targeting_method(Object *p_object, String p_method, Object *p_initial, String p_initial_method, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) {
+ if (pending_update != 0) {
+ _add_pending_command("targeting_method", p_object, p_method, p_initial, p_initial_method, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay);
return true;
}
// convert INT to REAL is better for interpolaters
- if(p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
+ if (p_final_val.get_type() == Variant::INT) p_final_val = p_final_val.operator real_t();
ERR_FAIL_COND_V(p_object == NULL, false);
ERR_FAIL_COND_V(!ObjectDB::instance_validate(p_object), false);
@@ -1537,7 +1364,7 @@ bool Tween::targeting_method(Object *p_object
ERR_FAIL_COND_V(error.error != Variant::CallError::CALL_OK, false);
// convert INT to REAL is better for interpolaters
- if(initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
+ if (initial_val.get_type() == Variant::INT) initial_val = initial_val.operator real_t();
ERR_FAIL_COND_V(initial_val.get_type() != p_final_val.get_type(), false);
InterpolateData data;
@@ -1557,7 +1384,7 @@ bool Tween::targeting_method(Object *p_object
data.ease_type = p_ease_type;
data.delay = p_delay;
- if(!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
+ if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val))
return false;
interpolates.push_back(data);
@@ -1567,14 +1394,13 @@ bool Tween::targeting_method(Object *p_object
Tween::Tween() {
//String autoplay;
- tween_process_mode=TWEEN_PROCESS_IDLE;
- processing=false;
- active=false;
- repeat=false;
- speed_scale=1;
- pending_update=0;
+ tween_process_mode = TWEEN_PROCESS_IDLE;
+ processing = false;
+ active = false;
+ repeat = false;
+ speed_scale = 1;
+ pending_update = 0;
}
Tween::~Tween() {
-
}
diff --git a/scene/animation/tween.h b/scene/animation/tween.h
index 07c2e90da2..84f866f43e 100644
--- a/scene/animation/tween.h
+++ b/scene/animation/tween.h
@@ -31,10 +31,9 @@
#include "scene/main/node.h"
-
class Tween : public Node {
- GDCLASS( Tween, Node );
+ GDCLASS(Tween, Node);
public:
enum TweenProcessMode {
@@ -42,30 +41,30 @@ public:
TWEEN_PROCESS_IDLE,
};
- enum TransitionType {
- TRANS_LINEAR,
- TRANS_SINE,
- TRANS_QUINT,
- TRANS_QUART,
- TRANS_QUAD,
- TRANS_EXPO,
- TRANS_ELASTIC,
- TRANS_CUBIC,
- TRANS_CIRC,
- TRANS_BOUNCE,
- TRANS_BACK,
+ enum TransitionType {
+ TRANS_LINEAR,
+ TRANS_SINE,
+ TRANS_QUINT,
+ TRANS_QUART,
+ TRANS_QUAD,
+ TRANS_EXPO,
+ TRANS_ELASTIC,
+ TRANS_CUBIC,
+ TRANS_CIRC,
+ TRANS_BOUNCE,
+ TRANS_BACK,
TRANS_COUNT,
- };
+ };
- enum EaseType {
- EASE_IN,
- EASE_OUT,
- EASE_IN_OUT,
+ enum EaseType {
+ EASE_IN,
+ EASE_OUT,
+ EASE_IN_OUT,
EASE_OUT_IN,
EASE_COUNT,
- };
+ };
private:
enum InterpolateType {
@@ -117,45 +116,32 @@ private:
};
List<PendingCommand> pending_commands;
- void _add_pending_command(StringName p_key
- ,const Variant& p_arg1=Variant()
- ,const Variant& p_arg2=Variant()
- ,const Variant& p_arg3=Variant()
- ,const Variant& p_arg4=Variant()
- ,const Variant& p_arg5=Variant()
- ,const Variant& p_arg6=Variant()
- ,const Variant& p_arg7=Variant()
- ,const Variant& p_arg8=Variant()
- ,const Variant& p_arg9=Variant()
- ,const Variant& p_arg10=Variant()
- );
+ void _add_pending_command(StringName p_key, const Variant &p_arg1 = Variant(), const Variant &p_arg2 = Variant(), const Variant &p_arg3 = Variant(), const Variant &p_arg4 = Variant(), const Variant &p_arg5 = Variant(), const Variant &p_arg6 = Variant(), const Variant &p_arg7 = Variant(), const Variant &p_arg8 = Variant(), const Variant &p_arg9 = Variant(), const Variant &p_arg10 = Variant());
void _process_pending_commands();
typedef real_t (*interpolater)(real_t t, real_t b, real_t c, real_t d);
static interpolater interpolaters[TRANS_COUNT][EASE_COUNT];
real_t _run_equation(TransitionType p_trans_type, EaseType p_ease_type, real_t t, real_t b, real_t c, real_t d);
- Variant& _get_delta_val(InterpolateData& p_data);
- Variant& _get_initial_val(InterpolateData& p_data);
- Variant _run_equation(InterpolateData& p_data);
- bool _calc_delta_val(const Variant& p_initial_val, const Variant& p_final_val, Variant& p_delta_val);
- bool _apply_tween_value(InterpolateData& p_data, Variant& value);
+ Variant &_get_delta_val(InterpolateData &p_data);
+ Variant &_get_initial_val(InterpolateData &p_data);
+ Variant _run_equation(InterpolateData &p_data);
+ bool _calc_delta_val(const Variant &p_initial_val, const Variant &p_final_val, Variant &p_delta_val);
+ bool _apply_tween_value(InterpolateData &p_data, Variant &value);
void _tween_process(float p_delta);
- void _set_process(bool p_process,bool p_force=false);
+ void _set_process(bool p_process, bool p_force = false);
void _remove(Object *p_node, String p_key, bool first_only);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
bool is_active() const;
void set_active(bool p_active);
@@ -182,89 +168,28 @@ public:
real_t tell() const;
real_t get_runtime() const;
- bool interpolate_property(Object *p_node
- , String p_property
- , Variant p_initial_val
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
-
- bool interpolate_method(Object *p_node
- , String p_method
- , Variant p_initial_val
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
-
- bool interpolate_callback(Object *p_object
- , real_t p_duration
- , String p_callback
- , VARIANT_ARG_DECLARE
- );
-
- bool interpolate_deferred_callback(Object *p_object
- , real_t p_duration
- , String p_callback
- , VARIANT_ARG_DECLARE
- );
-
- bool follow_property(Object *p_node
- , String p_property
- , Variant p_initial_val
- , Object *p_target
- , String p_target_property
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
-
- bool follow_method(Object *p_node
- , String p_method
- , Variant p_initial_val
- , Object *p_target
- , String p_target_method
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
-
- bool targeting_property(Object *p_node
- , String p_property
- , Object *p_initial
- , String p_initial_property
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
-
- bool targeting_method(Object *p_node
- , String p_method
- , Object *p_initial
- , String p_initial_method
- , Variant p_final_val
- , real_t p_duration
- , TransitionType p_trans_type
- , EaseType p_ease_type
- , real_t p_delay = 0
- );
+ bool interpolate_property(Object *p_node, String p_property, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
+
+ bool interpolate_method(Object *p_node, String p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
+
+ bool interpolate_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE);
+
+ bool interpolate_deferred_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE);
+
+ bool follow_property(Object *p_node, String p_property, Variant p_initial_val, Object *p_target, String p_target_property, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
+
+ bool follow_method(Object *p_node, String p_method, Variant p_initial_val, Object *p_target, String p_target_method, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
+
+ bool targeting_property(Object *p_node, String p_property, Object *p_initial, String p_initial_property, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
+
+ bool targeting_method(Object *p_node, String p_method, Object *p_initial, String p_initial_method, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay = 0);
Tween();
~Tween();
};
-VARIANT_ENUM_CAST( Tween::TweenProcessMode );
-VARIANT_ENUM_CAST( Tween::TransitionType );
-VARIANT_ENUM_CAST( Tween::EaseType );
+VARIANT_ENUM_CAST(Tween::TweenProcessMode);
+VARIANT_ENUM_CAST(Tween::TransitionType);
+VARIANT_ENUM_CAST(Tween::EaseType);
#endif
-
diff --git a/scene/animation/tween_interpolaters.cpp b/scene/animation/tween_interpolaters.cpp
index 25a27252f5..ef55b63edd 100644
--- a/scene/animation/tween_interpolaters.cpp
+++ b/scene/animation/tween_interpolaters.cpp
@@ -34,355 +34,278 @@ const real_t pi = 3.1415926535898;
// linear
///////////////////////////////////////////////////////////////////////////
namespace linear {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * t / d + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c * t / d + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- return c * t / d + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ return c * t / d + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- return c * t / d + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ return c * t / d + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * t / d + b;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return c * t / d + b;
+}
};
///////////////////////////////////////////////////////////////////////////
// sine
///////////////////////////////////////////////////////////////////////////
namespace sine {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return -c * cos(t / d * (pi / 2)) + c + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return -c * cos(t / d * (pi / 2)) + c + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- return c * sin(t / d * (pi / 2)) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ return c * sin(t / d * (pi / 2)) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- return -c / 2 * (cos(pi * t / d) - 1) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ return -c / 2 * (cos(pi * t / d) - 1) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// quint
///////////////////////////////////////////////////////////////////////////
namespace quint {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * pow(t / d, 5) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c * pow(t / d, 5) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- return c * (pow(t / d - 1, 5) + 1) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ return c * (pow(t / d - 1, 5) + 1) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- t = t / d * 2;
- if (t < 1) return c / 2 * pow(t, 5) + b;
- return c / 2 * (pow(t - 2, 5) + 2) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ t = t / d * 2;
+ if (t < 1) return c / 2 * pow(t, 5) + b;
+ return c / 2 * (pow(t - 2, 5) + 2) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// quart
///////////////////////////////////////////////////////////////////////////
namespace quart {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * pow(t / d, 4) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c * pow(t / d, 4) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- return -c * (pow(t / d - 1, 4) - 1) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ return -c * (pow(t / d - 1, 4) - 1) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- t = t / d * 2;
- if (t < 1) return c / 2 * pow(t, 4) + b;
- return -c / 2 * (pow(t - 2, 4) - 2) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ t = t / d * 2;
+ if (t < 1) return c / 2 * pow(t, 4) + b;
+ return -c / 2 * (pow(t - 2, 4) - 2) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// quad
///////////////////////////////////////////////////////////////////////////
namespace quad {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * pow(t / d, 2) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c * pow(t / d, 2) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- t = t / d;
- return -c * t * (t - 2) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ t = t / d;
+ return -c * t * (t - 2) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- t = t / d * 2;
- if (t < 1) return c / 2 * pow(t, 2) + b;
- return -c / 2 * ((t - 1) * (t - 3) - 1) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ t = t / d * 2;
+ if (t < 1) return c / 2 * pow(t, 2) + b;
+ return -c / 2 * ((t - 1) * (t - 3) - 1) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// expo
///////////////////////////////////////////////////////////////////////////
namespace expo {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == 0) return b;
- return c * pow(2, 10 * (t / d - 1)) + b - c * 0.001;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ if (t == 0) return b;
+ return c * pow(2, 10 * (t / d - 1)) + b - c * 0.001;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == d) return b + c;
- return c * 1.001 * (-pow(2, -10 * t / d) + 1) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ if (t == d) return b + c;
+ return c * 1.001 * (-pow(2, -10 * t / d) + 1) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == 0) return b;
- if (t == d) return b + c;
- t = t / d * 2;
- if (t < 1) return c / 2 * pow(2, 10 * (t - 1)) + b - c * 0.0005;
- return c / 2 * 1.0005 * (-pow(2, -10 * (t - 1)) + 2) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ if (t == 0) return b;
+ if (t == d) return b + c;
+ t = t / d * 2;
+ if (t < 1) return c / 2 * pow(2, 10 * (t - 1)) + b - c * 0.0005;
+ return c / 2 * 1.0005 * (-pow(2, -10 * (t - 1)) + 2) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// elastic
///////////////////////////////////////////////////////////////////////////
namespace elastic {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == 0) return b;
- if ((t /= d) == 1) return b + c;
- float p = d * 0.3f;
- float a = c;
- float s = p / 4;
- float postFix = a * pow(2,10 * (t -= 1)); // this is a fix, again, with post-increment operators
- return -(postFix * sin((t * d - s) * (2 * pi) / p )) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ if (t == 0) return b;
+ if ((t /= d) == 1) return b + c;
+ float p = d * 0.3f;
+ float a = c;
+ float s = p / 4;
+ float postFix = a * pow(2, 10 * (t -= 1)); // this is a fix, again, with post-increment operators
+ return -(postFix * sin((t * d - s) * (2 * pi) / p)) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == 0) return b;
- if ((t /= d) == 1) return b + c;
- float p = d * 0.3f;
- float a = c;
- float s = p / 4;
- return (a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p ) + c + b);
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ if (t == 0) return b;
+ if ((t /= d) == 1) return b + c;
+ float p = d * 0.3f;
+ float a = c;
+ float s = p / 4;
+ return (a * pow(2, -10 * t) * sin((t * d - s) * (2 * pi) / p) + c + b);
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- if (t == 0) return b;
- if ((t /= d / 2) == 2) return b + c;
- float p = d * (0.3f * 1.5f);
- float a = c;
- float s = p / 4;
-
- if (t < 1) {
- float postFix = a * pow(2, 10 * (t -= 1)); // postIncrement is evil
- return -0.5f * (postFix * sin((t * d - s) * (2 * pi) / p)) + b;
- }
- float postFix = a * pow(2, -10 * (t -= 1)); // postIncrement is evil
- return postFix * sin((t * d - s) * (2 * pi) / p ) * 0.5f + c + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ if (t == 0) return b;
+ if ((t /= d / 2) == 2) return b + c;
+ float p = d * (0.3f * 1.5f);
+ float a = c;
+ float s = p / 4;
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
+ if (t < 1) {
+ float postFix = a * pow(2, 10 * (t -= 1)); // postIncrement is evil
+ return -0.5f * (postFix * sin((t * d - s) * (2 * pi) / p)) + b;
}
+ float postFix = a * pow(2, -10 * (t -= 1)); // postIncrement is evil
+ return postFix * sin((t * d - s) * (2 * pi) / p) * 0.5f + c + b;
+}
+
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// cubic
///////////////////////////////////////////////////////////////////////////
namespace cubic {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c * (t /= d) * t * t + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c * (t /= d) * t * t + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- t = t / d - 1;
- return c * (t * t * t + 1) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ t = t / d - 1;
+ return c * (t * t * t + 1) + b;
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
- return c / 2 * ((t -= 2) * t * t + 2) + b;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
+ return c / 2 * ((t -= 2) * t * t + 2) + b;
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// circ
///////////////////////////////////////////////////////////////////////////
namespace circ {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return -c * (sqrt(1 - (t /= d) * t) - 1) + b; // TODO: ehrich: operation with t is undefined
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return -c * (sqrt(1 - (t /= d) * t) - 1) + b; // TODO: ehrich: operation with t is undefined
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- return c * sqrt(1 - (t = t / d - 1) * t) + b; // TODO: ehrich: operation with t is undefined
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ return c * sqrt(1 - (t = t / d - 1) * t) + b; // TODO: ehrich: operation with t is undefined
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b;
- return c / 2 * (sqrt(1 - t * (t -= 2)) + 1) + b; // TODO: ehrich: operation with t is undefined
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ if ((t /= d / 2) < 1) return -c / 2 * (sqrt(1 - t * t) - 1) + b;
+ return c / 2 * (sqrt(1 - t * (t -= 2)) + 1) + b; // TODO: ehrich: operation with t is undefined
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// bounce
///////////////////////////////////////////////////////////////////////////
namespace bounce {
- static real_t out(real_t t, real_t b, real_t c, real_t d);
+static real_t out(real_t t, real_t b, real_t c, real_t d);
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- return c - out(d - t, 0, c, d) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ return c - out(d - t, 0, c, d) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- if ((t /= d) < (1 / 2.75f)) {
- return c*(7.5625f*t*t) + b;
- } else if (t < (2/2.75f)) {
- float postFix = t-=(1.5f/2.75f);
- return c*(7.5625f*(postFix)*t + .75f) + b;
- } else if (t < (2.5/2.75)) {
- float postFix = t-=(2.25f/2.75f);
- return c*(7.5625f*(postFix)*t + .9375f) + b;
- } else {
- float postFix = t-=(2.625f/2.75f);
- return c*(7.5625f*(postFix)*t + .984375f) + b;
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ if ((t /= d) < (1 / 2.75f)) {
+ return c * (7.5625f * t * t) + b;
+ } else if (t < (2 / 2.75f)) {
+ float postFix = t -= (1.5f / 2.75f);
+ return c * (7.5625f * (postFix)*t + .75f) + b;
+ } else if (t < (2.5 / 2.75)) {
+ float postFix = t -= (2.25f / 2.75f);
+ return c * (7.5625f * (postFix)*t + .9375f) + b;
+ } else {
+ float postFix = t -= (2.625f / 2.75f);
+ return c * (7.5625f * (postFix)*t + .984375f) + b;
}
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? in(t * 2, b, c / 2, d)
- : out((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? in(t * 2, b, c / 2, d) : out((t * 2) - d, b + c / 2, c / 2, d);
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
///////////////////////////////////////////////////////////////////////////
// back
///////////////////////////////////////////////////////////////////////////
namespace back {
- static real_t in(real_t t, real_t b, real_t c, real_t d)
- {
- float s = 1.70158f;
- float postFix = t /= d;
- return c * (postFix) * t * ((s + 1) * t - s) + b;
- }
+static real_t in(real_t t, real_t b, real_t c, real_t d) {
+ float s = 1.70158f;
+ float postFix = t /= d;
+ return c * (postFix)*t * ((s + 1) * t - s) + b;
+}
- static real_t out(real_t t, real_t b, real_t c, real_t d)
- {
- float s = 1.70158f;
- return c * ((t = t / d- 1) * t * ((s + 1) * t + s) + 1) + b; // TODO: ehrich: operation with t is undefined
- }
+static real_t out(real_t t, real_t b, real_t c, real_t d) {
+ float s = 1.70158f;
+ return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; // TODO: ehrich: operation with t is undefined
+}
- static real_t in_out(real_t t, real_t b, real_t c, real_t d)
- {
- float s = 1.70158f;
- if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; // TODO: ehrich: operation with s is undefined
- float postFix = t -= 2;
- return c / 2 * ((postFix) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; // TODO: ehrich: operation with s is undefined
- }
+static real_t in_out(real_t t, real_t b, real_t c, real_t d) {
+ float s = 1.70158f;
+ if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; // TODO: ehrich: operation with s is undefined
+ float postFix = t -= 2;
+ return c / 2 * ((postFix)*t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; // TODO: ehrich: operation with s is undefined
+}
- static real_t out_in(real_t t, real_t b, real_t c, real_t d)
- {
- return (t < d / 2)
- ? out(t * 2, b, c / 2, d)
- : in((t * 2) - d, b + c / 2, c / 2, d)
- ;
- }
+static real_t out_in(real_t t, real_t b, real_t c, real_t d) {
+ return (t < d / 2) ? out(t * 2, b, c / 2, d) : in((t * 2) - d, b + c / 2, c / 2, d);
+}
};
Tween::interpolater Tween::interpolaters[Tween::TRANS_COUNT][Tween::EASE_COUNT] = {
@@ -405,4 +328,3 @@ real_t Tween::_run_equation(TransitionType p_trans_type, EaseType p_ease_type, r
ERR_FAIL_COND_V(cb == NULL, b);
return cb(t, b, c, d);
}
-
diff --git a/scene/audio/audio_player.cpp b/scene/audio/audio_player.cpp
index 97eaea70b1..1ee31a94d8 100644
--- a/scene/audio/audio_player.cpp
+++ b/scene/audio/audio_player.cpp
@@ -28,7 +28,6 @@
/*************************************************************************/
#include "audio_player.h"
-
void AudioPlayer::_mix_audio() {
if (!stream_playback.is_valid()) {
@@ -39,10 +38,9 @@ void AudioPlayer::_mix_audio() {
return;
}
- if (setseek>=0.0) {
+ if (setseek >= 0.0) {
stream_playback->start(setseek);
- setseek=-1.0; //reset seek
-
+ setseek = -1.0; //reset seek
}
int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus);
@@ -52,67 +50,63 @@ void AudioPlayer::_mix_audio() {
int buffer_size = mix_buffer.size();
//mix
- stream_playback->mix(buffer,1.0,buffer_size);
+ stream_playback->mix(buffer, 1.0, buffer_size);
//multiply volume interpolating to avoid clicks if this changes
float vol = Math::db2linear(mix_volume_db);
- float vol_inc = (Math::db2linear(volume_db) - vol)/float(buffer_size);
+ float vol_inc = (Math::db2linear(volume_db) - vol) / float(buffer_size);
- for(int i=0;i<buffer_size;i++) {
- buffer[i]*=vol;
- vol+=vol_inc;
+ for (int i = 0; i < buffer_size; i++) {
+ buffer[i] *= vol;
+ vol += vol_inc;
}
//set volume for next mix
mix_volume_db = volume_db;
- AudioFrame * targets[3]={NULL,NULL,NULL};
+ AudioFrame *targets[3] = { NULL, NULL, NULL };
- if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_MODE_STEREO) {
- targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0);
+ if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_MODE_STEREO) {
+ targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0);
} else {
- switch(mix_target) {
+ switch (mix_target) {
case MIX_TARGET_STEREO: {
- targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1);
+ targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1);
} break;
case MIX_TARGET_SURROUND: {
- targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1);
- targets[1]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,2);
- if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_SURROUND_71) {
- targets[2]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,3);
+ targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 1);
+ targets[1] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 2);
+ if (AudioServer::get_singleton()->get_speaker_mode() == AudioServer::SPEAKER_SURROUND_71) {
+ targets[2] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 3);
}
} break;
case MIX_TARGET_CENTER: {
- targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0);
+ targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index, 0);
} break;
-
}
}
- for(int c=0;c<3;c++) {
+ for (int c = 0; c < 3; c++) {
if (!targets[c])
break;
- for(int i=0;i<buffer_size;i++) {
- targets[c][i]+=buffer[i];
+ for (int i = 0; i < buffer_size; i++) {
+ targets[c][i] += buffer[i];
}
}
-
-
}
void AudioPlayer::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
- AudioServer::get_singleton()->add_callback(_mix_audios,this);
+ AudioServer::get_singleton()->add_callback(_mix_audios, this);
if (autoplay && !get_tree()->is_editor_hint()) {
play();
}
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
- AudioServer::get_singleton()->remove_callback(_mix_audios,this);
+ if (p_what == NOTIFICATION_EXIT_TREE) {
+ AudioServer::get_singleton()->remove_callback(_mix_audios, this);
}
}
@@ -125,12 +119,12 @@ void AudioPlayer::set_stream(Ref<AudioStream> p_stream) {
if (stream_playback.is_valid()) {
stream_playback.unref();
stream.unref();
- active=false;
- setseek=-1;
+ active = false;
+ setseek = -1;
}
- stream=p_stream;
- stream_playback=p_stream->instance_playback();
+ stream = p_stream;
+ stream_playback = p_stream->instance_playback();
if (stream_playback.is_null()) {
stream.unref();
@@ -138,7 +132,6 @@ void AudioPlayer::set_stream(Ref<AudioStream> p_stream) {
}
AudioServer::get_singleton()->unlock();
-
}
Ref<AudioStream> AudioPlayer::get_stream() const {
@@ -148,7 +141,7 @@ Ref<AudioStream> AudioPlayer::get_stream() const {
void AudioPlayer::set_volume_db(float p_volume) {
- volume_db=p_volume;
+ volume_db = p_volume;
}
float AudioPlayer::get_volume_db() const {
@@ -158,26 +151,24 @@ float AudioPlayer::get_volume_db() const {
void AudioPlayer::play(float p_from_pos) {
if (stream_playback.is_valid()) {
- mix_volume_db=volume_db; //reset volume ramp
- setseek=p_from_pos;
- active=true;
+ mix_volume_db = volume_db; //reset volume ramp
+ setseek = p_from_pos;
+ active = true;
}
}
void AudioPlayer::seek(float p_seconds) {
if (stream_playback.is_valid()) {
- setseek=p_seconds;
+ setseek = p_seconds;
}
}
-void AudioPlayer::stop() {
+void AudioPlayer::stop() {
if (stream_playback.is_valid()) {
- active=false;
+ active = false;
}
-
-
}
bool AudioPlayer::is_playing() const {
@@ -189,7 +180,7 @@ bool AudioPlayer::is_playing() const {
return false;
}
-float AudioPlayer::get_pos() {
+float AudioPlayer::get_pos() {
if (stream_playback.is_valid()) {
return stream_playback->get_pos();
@@ -198,39 +189,38 @@ float AudioPlayer::get_pos() {
return 0;
}
-void AudioPlayer::set_bus(const StringName& p_bus) {
+void AudioPlayer::set_bus(const StringName &p_bus) {
//if audio is active, must lock this
AudioServer::get_singleton()->lock();
- bus=p_bus;
+ bus = p_bus;
AudioServer::get_singleton()->unlock();
-
}
StringName AudioPlayer::get_bus() const {
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
- if (AudioServer::get_singleton()->get_bus_name(i)==bus) {
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
+ if (AudioServer::get_singleton()->get_bus_name(i) == bus) {
return bus;
}
}
return "Master";
}
-void AudioPlayer::set_autoplay(bool p_enable) {
+void AudioPlayer::set_autoplay(bool p_enable) {
- autoplay=p_enable;
+ autoplay = p_enable;
}
-bool AudioPlayer::is_autoplay_enabled() {
+bool AudioPlayer::is_autoplay_enabled() {
return autoplay;
}
void AudioPlayer::set_mix_target(MixTarget p_target) {
- mix_target=p_target;
+ mix_target = p_target;
}
-AudioPlayer::MixTarget AudioPlayer::get_mix_target() const{
+AudioPlayer::MixTarget AudioPlayer::get_mix_target() const {
return mix_target;
}
@@ -247,20 +237,19 @@ bool AudioPlayer::_is_active() const {
return active;
}
+void AudioPlayer::_validate_property(PropertyInfo &property) const {
-void AudioPlayer::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="bus") {
+ if (property.name == "bus") {
String options;
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
- if (i>0)
- options+=",";
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
+ if (i > 0)
+ options += ",";
String name = AudioServer::get_singleton()->get_bus_name(i);
- options+=name;
+ options += name;
}
- property.hint_string=options;
+ property.hint_string = options;
}
}
@@ -271,59 +260,52 @@ void AudioPlayer::_bus_layout_changed() {
void AudioPlayer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_stream","stream:AudioStream"),&AudioPlayer::set_stream);
- ClassDB::bind_method(D_METHOD("get_stream"),&AudioPlayer::get_stream);
-
- ClassDB::bind_method(D_METHOD("set_volume_db","volume_db"),&AudioPlayer::set_volume_db);
- ClassDB::bind_method(D_METHOD("get_volume_db"),&AudioPlayer::get_volume_db);
+ ClassDB::bind_method(D_METHOD("set_stream", "stream:AudioStream"), &AudioPlayer::set_stream);
+ ClassDB::bind_method(D_METHOD("get_stream"), &AudioPlayer::get_stream);
- ClassDB::bind_method(D_METHOD("play","from_pos"),&AudioPlayer::play,DEFVAL(0.0));
- ClassDB::bind_method(D_METHOD("seek","to_pos"),&AudioPlayer::seek);
- ClassDB::bind_method(D_METHOD("stop"),&AudioPlayer::stop);
+ ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioPlayer::set_volume_db);
+ ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioPlayer::get_volume_db);
- ClassDB::bind_method(D_METHOD("is_playing"),&AudioPlayer::is_playing);
- ClassDB::bind_method(D_METHOD("get_pos"),&AudioPlayer::get_pos);
+ ClassDB::bind_method(D_METHOD("play", "from_pos"), &AudioPlayer::play, DEFVAL(0.0));
+ ClassDB::bind_method(D_METHOD("seek", "to_pos"), &AudioPlayer::seek);
+ ClassDB::bind_method(D_METHOD("stop"), &AudioPlayer::stop);
- ClassDB::bind_method(D_METHOD("set_bus","bus"),&AudioPlayer::set_bus);
- ClassDB::bind_method(D_METHOD("get_bus"),&AudioPlayer::get_bus);
+ ClassDB::bind_method(D_METHOD("is_playing"), &AudioPlayer::is_playing);
+ ClassDB::bind_method(D_METHOD("get_pos"), &AudioPlayer::get_pos);
- ClassDB::bind_method(D_METHOD("set_autoplay","enable"),&AudioPlayer::set_autoplay);
- ClassDB::bind_method(D_METHOD("is_autoplay_enabled"),&AudioPlayer::is_autoplay_enabled);
+ ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioPlayer::set_bus);
+ ClassDB::bind_method(D_METHOD("get_bus"), &AudioPlayer::get_bus);
- ClassDB::bind_method(D_METHOD("set_mix_target","mix_target"),&AudioPlayer::set_mix_target);
- ClassDB::bind_method(D_METHOD("get_mix_target"),&AudioPlayer::get_mix_target);
+ ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioPlayer::set_autoplay);
+ ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioPlayer::is_autoplay_enabled);
- ClassDB::bind_method(D_METHOD("_set_playing","enable"),&AudioPlayer::_set_playing);
- ClassDB::bind_method(D_METHOD("_is_active"),&AudioPlayer::_is_active);
+ ClassDB::bind_method(D_METHOD("set_mix_target", "mix_target"), &AudioPlayer::set_mix_target);
+ ClassDB::bind_method(D_METHOD("get_mix_target"), &AudioPlayer::get_mix_target);
- ClassDB::bind_method(D_METHOD("_bus_layout_changed"),&AudioPlayer::_bus_layout_changed);
+ ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioPlayer::_set_playing);
+ ClassDB::bind_method(D_METHOD("_is_active"), &AudioPlayer::_is_active);
+ ClassDB::bind_method(D_METHOD("_bus_layout_changed"), &AudioPlayer::_bus_layout_changed);
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"stream",PROPERTY_HINT_RESOURCE_TYPE,"AudioStream"),"set_stream","get_stream") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24"),"set_volume_db","get_volume_db") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"playing",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR),"_set_playing","_is_active" );
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"autoplay"),"set_autoplay","is_autoplay_enabled") ;
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mix_target",PROPERTY_HINT_ENUM,"Stereo,Surround,Center"),"set_mix_target","get_mix_target");
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"bus",PROPERTY_HINT_ENUM,""),"set_bus","get_bus");
-
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24"), "set_volume_db", "get_volume_db");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "_is_active");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_target", PROPERTY_HINT_ENUM, "Stereo,Surround,Center"), "set_mix_target", "get_mix_target");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus");
}
AudioPlayer::AudioPlayer() {
- mix_volume_db=0;
- volume_db=0;
- autoplay=false;
- setseek=-1;
- active=false;
- mix_target=MIX_TARGET_STEREO;
+ mix_volume_db = 0;
+ volume_db = 0;
+ autoplay = false;
+ setseek = -1;
+ active = false;
+ mix_target = MIX_TARGET_STEREO;
- AudioServer::get_singleton()->connect("bus_layout_changed",this,"_bus_layout_changed");
+ AudioServer::get_singleton()->connect("bus_layout_changed", this, "_bus_layout_changed");
}
-
-
AudioPlayer::~AudioPlayer() {
-
-
}
-
diff --git a/scene/audio/audio_player.h b/scene/audio/audio_player.h
index 6e34dfce19..0d78626189 100644
--- a/scene/audio/audio_player.h
+++ b/scene/audio/audio_player.h
@@ -32,18 +32,17 @@
#include "scene/main/node.h"
#include "servers/audio/audio_stream.h"
-
class AudioPlayer : public Node {
- GDCLASS( AudioPlayer, Node )
+ GDCLASS(AudioPlayer, Node)
public:
-
enum MixTarget {
MIX_TARGET_STEREO,
MIX_TARGET_SURROUND,
MIX_TARGET_CENTER
};
+
private:
Ref<AudioStreamPlayback> stream_playback;
Ref<AudioStream> stream;
@@ -60,7 +59,7 @@ private:
MixTarget mix_target;
void _mix_audio();
- static void _mix_audios(void *self) { reinterpret_cast<AudioPlayer*>(self)->_mix_audio(); }
+ static void _mix_audios(void *self) { reinterpret_cast<AudioPlayer *>(self)->_mix_audio(); }
void _set_playing(bool p_enable);
bool _is_active() const;
@@ -68,25 +67,24 @@ private:
void _bus_layout_changed();
protected:
-
- void _validate_property(PropertyInfo& property) const;
+ void _validate_property(PropertyInfo &property) const;
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_stream(Ref<AudioStream> p_stream);
Ref<AudioStream> get_stream() const;
void set_volume_db(float p_volume);
float get_volume_db() const;
- void play(float p_from_pos=0.0);
+ void play(float p_from_pos = 0.0);
void seek(float p_seconds);
void stop();
bool is_playing() const;
float get_pos();
- void set_bus(const StringName& p_bus);
+ void set_bus(const StringName &p_bus);
StringName get_bus() const;
void set_autoplay(bool p_enable);
diff --git a/scene/gui/base_button.cpp b/scene/gui/base_button.cpp
index 79b607e2e6..eceee8e317 100644
--- a/scene/gui/base_button.cpp
+++ b/scene/gui/base_button.cpp
@@ -29,17 +29,16 @@
#include "base_button.h"
#include "os/keyboard.h"
#include "print_string.h"
-#include "scene/scene_string_names.h"
#include "scene/main/viewport.h"
-
+#include "scene/scene_string_names.h"
void BaseButton::_unpress_group() {
if (!button_group.is_valid())
return;
- for (Set<BaseButton*>::Element *E=button_group->buttons.front();E;E=E->next()) {
- if (E->get()==this)
+ for (Set<BaseButton *>::Element *E = button_group->buttons.front(); E; E = E->next()) {
+ if (E->get() == this)
continue;
E->get()->set_pressed(false);
@@ -48,23 +47,22 @@ void BaseButton::_unpress_group() {
void BaseButton::_gui_input(InputEvent p_event) {
-
if (status.disabled) // no interaction with disabled button
return;
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &b=p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
- if ( status.disabled || b.button_index!=1 )
+ if (status.disabled || b.button_index != 1)
return;
if (status.pressing_button)
break;
- if (action_mode==ACTION_MODE_BUTTON_PRESS) {
+ if (action_mode == ACTION_MODE_BUTTON_PRESS) {
if (b.pressed) {
@@ -72,47 +70,43 @@ void BaseButton::_gui_input(InputEvent p_event) {
if (!toggle_mode) { //mouse press attempt
- status.press_attempt=true;
- status.pressing_inside=true;
+ status.press_attempt = true;
+ status.pressing_inside = true;
pressed();
if (get_script_instance()) {
Variant::CallError ce;
- get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce);
}
emit_signal("pressed");
_unpress_group();
-
} else {
- status.pressed=!status.pressed;
+ status.pressed = !status.pressed;
pressed();
if (get_script_instance()) {
Variant::CallError ce;
- get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce);
}
emit_signal("pressed");
_unpress_group();
-
toggled(status.pressed);
- emit_signal("toggled",status.pressed);
-
+ emit_signal("toggled", status.pressed);
}
-
} else {
emit_signal("button_up");
-/* this is pointless if (status.press_attempt && status.pressing_inside) {
+ /* this is pointless if (status.press_attempt && status.pressing_inside) {
//released();
emit_signal("released");
}
*/
- status.press_attempt=false;
+ status.press_attempt = false;
}
update();
break;
@@ -120,59 +114,54 @@ void BaseButton::_gui_input(InputEvent p_event) {
if (b.pressed) {
- status.press_attempt=true;
- status.pressing_inside=true;
+ status.press_attempt = true;
+ status.pressing_inside = true;
emit_signal("button_down");
} else {
emit_signal("button_up");
- if (status.press_attempt &&status.pressing_inside) {
+ if (status.press_attempt && status.pressing_inside) {
if (!toggle_mode) { //mouse press attempt
pressed();
if (get_script_instance()) {
Variant::CallError ce;
- get_script_instance()->call(SceneStringNames::get_singleton()->_pressed,NULL,0,ce);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_pressed, NULL, 0, ce);
}
emit_signal("pressed");
} else {
- status.pressed=!status.pressed;
+ status.pressed = !status.pressed;
pressed();
emit_signal("pressed");
toggled(status.pressed);
- emit_signal("toggled",status.pressed);
+ emit_signal("toggled", status.pressed);
if (get_script_instance()) {
- get_script_instance()->call(SceneStringNames::get_singleton()->_toggled,status.pressed);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_toggled, status.pressed);
}
-
-
}
_unpress_group();
-
-
}
- status.press_attempt=false;
-
+ status.press_attempt = false;
}
update();
} break;
case InputEvent::MOUSE_MOTION: {
- if (status.press_attempt && status.pressing_button==0) {
- bool last_press_inside=status.pressing_inside;
- status.pressing_inside=has_point(Point2(p_event.mouse_motion.x,p_event.mouse_motion.y));
- if (last_press_inside!=status.pressing_inside)
+ if (status.press_attempt && status.pressing_button == 0) {
+ bool last_press_inside = status.pressing_inside;
+ status.pressing_inside = has_point(Point2(p_event.mouse_motion.x, p_event.mouse_motion.y));
+ if (last_press_inside != status.pressing_inside)
update();
}
} break;
@@ -180,7 +169,6 @@ void BaseButton::_gui_input(InputEvent p_event) {
case InputEvent::JOYPAD_BUTTON:
case InputEvent::KEY: {
-
if (p_event.is_echo()) {
break;
}
@@ -189,7 +177,7 @@ void BaseButton::_gui_input(InputEvent p_event) {
break;
}
- if (status.press_attempt && status.pressing_button==0) {
+ if (status.press_attempt && status.pressing_button == 0) {
break;
}
@@ -198,8 +186,8 @@ void BaseButton::_gui_input(InputEvent p_event) {
if (p_event.is_pressed()) {
status.pressing_button++;
- status.press_attempt=true;
- status.pressing_inside=true;
+ status.press_attempt = true;
+ status.pressing_inside = true;
emit_signal("button_down");
} else if (status.press_attempt) {
@@ -210,8 +198,8 @@ void BaseButton::_gui_input(InputEvent p_event) {
if (status.pressing_button)
break;
- status.press_attempt=false;
- status.pressing_inside=false;
+ status.press_attempt = false;
+ status.pressing_inside = false;
emit_signal("button_up");
@@ -221,83 +209,75 @@ void BaseButton::_gui_input(InputEvent p_event) {
emit_signal("pressed");
} else {
- status.pressed=!status.pressed;
+ status.pressed = !status.pressed;
pressed();
emit_signal("pressed");
toggled(status.pressed);
if (get_script_instance()) {
- get_script_instance()->call(SceneStringNames::get_singleton()->_toggled,status.pressed);
+ get_script_instance()->call(SceneStringNames::get_singleton()->_toggled, status.pressed);
}
- emit_signal("toggled",status.pressed);
+ emit_signal("toggled", status.pressed);
}
_unpress_group();
-
}
accept_event();
update();
-
}
}
-
}
}
void BaseButton::_notification(int p_what) {
+ if (p_what == NOTIFICATION_MOUSE_ENTER) {
- if (p_what==NOTIFICATION_MOUSE_ENTER) {
-
- status.hovering=true;
+ status.hovering = true;
update();
}
- if (p_what==NOTIFICATION_MOUSE_EXIT) {
- status.hovering=false;
+ if (p_what == NOTIFICATION_MOUSE_EXIT) {
+ status.hovering = false;
update();
}
- if (p_what==NOTIFICATION_DRAG_BEGIN) {
+ if (p_what == NOTIFICATION_DRAG_BEGIN) {
if (status.press_attempt) {
- status.press_attempt=false;
- status.pressing_button=0;
+ status.press_attempt = false;
+ status.pressing_button = 0;
update();
}
}
-
- if (p_what==NOTIFICATION_FOCUS_ENTER) {
-
- status.hovering=true;
+
+ if (p_what == NOTIFICATION_FOCUS_ENTER) {
+
+ status.hovering = true;
update();
}
- if (p_what==NOTIFICATION_FOCUS_EXIT) {
+ if (p_what == NOTIFICATION_FOCUS_EXIT) {
if (status.pressing_button && status.press_attempt) {
- status.press_attempt=false;
- status.pressing_button=0;
- status.hovering=false;
+ status.press_attempt = false;
+ status.pressing_button = 0;
+ status.hovering = false;
update();
} else if (status.hovering) {
- status.hovering=false;
+ status.hovering = false;
update();
}
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
-
-
+ if (p_what == NOTIFICATION_EXIT_TREE) {
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED && !is_visible_in_tree()) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED && !is_visible_in_tree()) {
if (!toggle_mode) {
status.pressed = false;
@@ -318,12 +298,10 @@ void BaseButton::pressed() {
void BaseButton::toggled(bool p_pressed) {
if (get_script_instance()) {
- get_script_instance()->call("toggled",p_pressed);
+ get_script_instance()->call("toggled", p_pressed);
}
-
}
-
void BaseButton::set_disabled(bool p_disabled) {
status.disabled = p_disabled;
@@ -344,26 +322,25 @@ void BaseButton::set_pressed(bool p_pressed) {
if (!toggle_mode)
return;
- if (status.pressed==p_pressed)
+ if (status.pressed == p_pressed)
return;
_change_notify("pressed");
- status.pressed=p_pressed;
+ status.pressed = p_pressed;
if (p_pressed) {
_unpress_group();
-
}
update();
}
-bool BaseButton::is_pressing() const{
+bool BaseButton::is_pressing() const {
return status.press_attempt;
}
bool BaseButton::is_pressed() const {
- return toggle_mode?status.pressed:status.press_attempt;
+ return toggle_mode ? status.pressed : status.press_attempt;
}
bool BaseButton::is_hovered() const {
@@ -378,8 +355,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const {
};
//print_line("press attempt: "+itos(status.press_attempt)+" hover: "+itos(status.hovering)+" pressed: "+itos(status.pressed));
- if (status.press_attempt==false && status.hovering && !status.pressed) {
-
+ if (status.press_attempt == false && status.hovering && !status.pressed) {
return DRAW_HOVER;
} else {
@@ -388,12 +364,12 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const {
bool pressing;
if (status.press_attempt) {
- pressing=status.pressing_inside;
+ pressing = status.pressing_inside;
if (status.pressed)
- pressing=!pressing;
+ pressing = !pressing;
} else {
- pressing=status.pressed;
+ pressing = status.pressed;
}
if (pressing)
@@ -407,7 +383,7 @@ BaseButton::DrawMode BaseButton::get_draw_mode() const {
void BaseButton::set_toggle_mode(bool p_on) {
- toggle_mode=p_on;
+ toggle_mode = p_on;
}
bool BaseButton::is_toggle_mode() const {
@@ -417,7 +393,7 @@ bool BaseButton::is_toggle_mode() const {
void BaseButton::set_action_mode(ActionMode p_mode) {
- action_mode=p_mode;
+ action_mode = p_mode;
}
BaseButton::ActionMode BaseButton::get_action_mode() const {
@@ -429,7 +405,7 @@ void BaseButton::set_enabled_focus_mode(FocusMode p_mode) {
enabled_focus_mode = p_mode;
if (!status.disabled) {
- set_focus_mode( p_mode );
+ set_focus_mode(p_mode);
}
}
@@ -438,16 +414,16 @@ Control::FocusMode BaseButton::get_enabled_focus_mode() const {
return enabled_focus_mode;
}
-void BaseButton::set_shortcut(const Ref<ShortCut>& p_shortcut) {
+void BaseButton::set_shortcut(const Ref<ShortCut> &p_shortcut) {
if (shortcut.is_null() == p_shortcut.is_null())
return;
- shortcut=p_shortcut;
+ shortcut = p_shortcut;
set_process_unhandled_input(shortcut.is_valid());
}
-Ref<ShortCut> BaseButton:: get_shortcut() const {
+Ref<ShortCut> BaseButton::get_shortcut() const {
return shortcut;
}
@@ -460,41 +436,39 @@ void BaseButton::_unhandled_input(InputEvent p_event) {
if (is_toggle_mode()) {
set_pressed(!is_pressed());
- emit_signal("toggled",is_pressed());
+ emit_signal("toggled", is_pressed());
}
emit_signal("pressed");
}
}
-String BaseButton::get_tooltip(const Point2& p_pos) const {
+String BaseButton::get_tooltip(const Point2 &p_pos) const {
- String tooltip=Control::get_tooltip(p_pos);
+ String tooltip = Control::get_tooltip(p_pos);
if (shortcut.is_valid() && shortcut->is_valid()) {
- if (tooltip.find("$sc")!=-1) {
- tooltip=tooltip.replace_first("$sc","("+shortcut->get_as_text()+")");
+ if (tooltip.find("$sc") != -1) {
+ tooltip = tooltip.replace_first("$sc", "(" + shortcut->get_as_text() + ")");
} else {
- tooltip+=" ("+shortcut->get_as_text()+")";
+ tooltip += " (" + shortcut->get_as_text() + ")";
}
}
return tooltip;
}
-
-void BaseButton::set_button_group(const Ref<ButtonGroup>& p_group) {
+void BaseButton::set_button_group(const Ref<ButtonGroup> &p_group) {
if (button_group.is_valid()) {
button_group->buttons.erase(this);
}
- button_group=p_group;
+ button_group = p_group;
if (button_group.is_valid()) {
button_group->buttons.insert(this);
}
update(); //checkbox changes to radio if set a buttongroup
-
}
Ref<ButtonGroup> BaseButton::get_button_group() const {
@@ -502,103 +476,94 @@ Ref<ButtonGroup> BaseButton::get_button_group() const {
return button_group;
}
-
void BaseButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&BaseButton::_gui_input);
- ClassDB::bind_method(D_METHOD("_unhandled_input"),&BaseButton::_unhandled_input);
- ClassDB::bind_method(D_METHOD("set_pressed","pressed"),&BaseButton::set_pressed);
- ClassDB::bind_method(D_METHOD("is_pressed"),&BaseButton::is_pressed);
- ClassDB::bind_method(D_METHOD("is_hovered"),&BaseButton::is_hovered);
- ClassDB::bind_method(D_METHOD("set_toggle_mode","enabled"),&BaseButton::set_toggle_mode);
- ClassDB::bind_method(D_METHOD("is_toggle_mode"),&BaseButton::is_toggle_mode);
- ClassDB::bind_method(D_METHOD("set_disabled","disabled"),&BaseButton::set_disabled);
- ClassDB::bind_method(D_METHOD("is_disabled"),&BaseButton::is_disabled);
- ClassDB::bind_method(D_METHOD("set_action_mode","mode"),&BaseButton::set_action_mode);
- ClassDB::bind_method(D_METHOD("get_action_mode"),&BaseButton::get_action_mode);
- ClassDB::bind_method(D_METHOD("get_draw_mode"),&BaseButton::get_draw_mode);
- ClassDB::bind_method(D_METHOD("set_enabled_focus_mode","mode"),&BaseButton::set_enabled_focus_mode);
- ClassDB::bind_method(D_METHOD("get_enabled_focus_mode"),&BaseButton::get_enabled_focus_mode);
-
- ClassDB::bind_method(D_METHOD("set_shortcut","shortcut"),&BaseButton::set_shortcut);
- ClassDB::bind_method(D_METHOD("get_shortcut"),&BaseButton::get_shortcut);
-
- ClassDB::bind_method(D_METHOD("set_button_group","button_group"),&BaseButton::set_button_group);
- ClassDB::bind_method(D_METHOD("get_button_group"),&BaseButton::get_button_group);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &BaseButton::_gui_input);
+ ClassDB::bind_method(D_METHOD("_unhandled_input"), &BaseButton::_unhandled_input);
+ ClassDB::bind_method(D_METHOD("set_pressed", "pressed"), &BaseButton::set_pressed);
+ ClassDB::bind_method(D_METHOD("is_pressed"), &BaseButton::is_pressed);
+ ClassDB::bind_method(D_METHOD("is_hovered"), &BaseButton::is_hovered);
+ ClassDB::bind_method(D_METHOD("set_toggle_mode", "enabled"), &BaseButton::set_toggle_mode);
+ ClassDB::bind_method(D_METHOD("is_toggle_mode"), &BaseButton::is_toggle_mode);
+ ClassDB::bind_method(D_METHOD("set_disabled", "disabled"), &BaseButton::set_disabled);
+ ClassDB::bind_method(D_METHOD("is_disabled"), &BaseButton::is_disabled);
+ ClassDB::bind_method(D_METHOD("set_action_mode", "mode"), &BaseButton::set_action_mode);
+ ClassDB::bind_method(D_METHOD("get_action_mode"), &BaseButton::get_action_mode);
+ ClassDB::bind_method(D_METHOD("get_draw_mode"), &BaseButton::get_draw_mode);
+ ClassDB::bind_method(D_METHOD("set_enabled_focus_mode", "mode"), &BaseButton::set_enabled_focus_mode);
+ ClassDB::bind_method(D_METHOD("get_enabled_focus_mode"), &BaseButton::get_enabled_focus_mode);
+
+ ClassDB::bind_method(D_METHOD("set_shortcut", "shortcut"), &BaseButton::set_shortcut);
+ ClassDB::bind_method(D_METHOD("get_shortcut"), &BaseButton::get_shortcut);
+
+ ClassDB::bind_method(D_METHOD("set_button_group", "button_group"), &BaseButton::set_button_group);
+ ClassDB::bind_method(D_METHOD("get_button_group"), &BaseButton::get_button_group);
BIND_VMETHOD(MethodInfo("_pressed"));
- BIND_VMETHOD(MethodInfo("_toggled",PropertyInfo(Variant::BOOL,"pressed")));
-
- ADD_SIGNAL( MethodInfo("pressed" ) );
- ADD_SIGNAL( MethodInfo("button_up") );
- ADD_SIGNAL( MethodInfo("button_down") );
- ADD_SIGNAL( MethodInfo("toggled", PropertyInfo( Variant::BOOL,"pressed") ) );
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "is_pressed"), "set_pressed", "is_pressed");
- ADD_PROPERTYNO( PropertyInfo( Variant::INT, "action_mode",PROPERTY_HINT_ENUM,"Button Press,Button Release"), "set_action_mode", "get_action_mode");
- ADD_PROPERTY( PropertyInfo( Variant::INT,"enabled_focus_mode", PROPERTY_HINT_ENUM, "None,Click,All" ), "set_enabled_focus_mode", "get_enabled_focus_mode") ;
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "shortcut",PROPERTY_HINT_RESOURCE_TYPE,"ShortCut"), "set_shortcut", "get_shortcut");
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "group",PROPERTY_HINT_RESOURCE_TYPE,"ButtonGroup"), "set_button_group", "get_button_group");
-
-
- BIND_CONSTANT( DRAW_NORMAL );
- BIND_CONSTANT( DRAW_PRESSED );
- BIND_CONSTANT( DRAW_HOVER );
- BIND_CONSTANT( DRAW_DISABLED );
-
- BIND_CONSTANT( ACTION_MODE_BUTTON_PRESS );
- BIND_CONSTANT( ACTION_MODE_BUTTON_RELEASE );
-
-
+ BIND_VMETHOD(MethodInfo("_toggled", PropertyInfo(Variant::BOOL, "pressed")));
+
+ ADD_SIGNAL(MethodInfo("pressed"));
+ ADD_SIGNAL(MethodInfo("button_up"));
+ ADD_SIGNAL(MethodInfo("button_down"));
+ ADD_SIGNAL(MethodInfo("toggled", PropertyInfo(Variant::BOOL, "pressed")));
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "disabled"), "set_disabled", "is_disabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "toggle_mode"), "set_toggle_mode", "is_toggle_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "is_pressed"), "set_pressed", "is_pressed");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "action_mode", PROPERTY_HINT_ENUM, "Button Press,Button Release"), "set_action_mode", "get_action_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "enabled_focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_enabled_focus_mode", "get_enabled_focus_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shortcut", PROPERTY_HINT_RESOURCE_TYPE, "ShortCut"), "set_shortcut", "get_shortcut");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "group", PROPERTY_HINT_RESOURCE_TYPE, "ButtonGroup"), "set_button_group", "get_button_group");
+
+ BIND_CONSTANT(DRAW_NORMAL);
+ BIND_CONSTANT(DRAW_PRESSED);
+ BIND_CONSTANT(DRAW_HOVER);
+ BIND_CONSTANT(DRAW_DISABLED);
+
+ BIND_CONSTANT(ACTION_MODE_BUTTON_PRESS);
+ BIND_CONSTANT(ACTION_MODE_BUTTON_RELEASE);
}
BaseButton::BaseButton() {
- toggle_mode=false;
- status.pressed=false;
- status.press_attempt=false;
- status.hovering=false;
- status.pressing_inside=false;
+ toggle_mode = false;
+ status.pressed = false;
+ status.press_attempt = false;
+ status.hovering = false;
+ status.pressing_inside = false;
status.disabled = false;
- status.pressing_button=0;
- set_focus_mode( FOCUS_ALL );
+ status.pressing_button = 0;
+ set_focus_mode(FOCUS_ALL);
enabled_focus_mode = FOCUS_ALL;
- action_mode=ACTION_MODE_BUTTON_RELEASE;
-
+ action_mode = ACTION_MODE_BUTTON_RELEASE;
if (button_group.is_valid()) {
button_group->buttons.erase(this);
}
-
-
}
-BaseButton::~BaseButton()
-{
+BaseButton::~BaseButton() {
}
-void ButtonGroup::get_buttons(List<BaseButton*> *r_buttons) {
+void ButtonGroup::get_buttons(List<BaseButton *> *r_buttons) {
- for (Set<BaseButton*>::Element *E=buttons.front();E;E=E->next()) {
+ for (Set<BaseButton *>::Element *E = buttons.front(); E; E = E->next()) {
r_buttons->push_back(E->get());
}
}
-BaseButton* ButtonGroup::get_pressed_button() {
+BaseButton *ButtonGroup::get_pressed_button() {
- for (Set<BaseButton*>::Element *E=buttons.front();E;E=E->next()) {
+ for (Set<BaseButton *>::Element *E = buttons.front(); E; E = E->next()) {
if (E->get()->is_pressed())
return E->get();
}
return NULL;
-
}
void ButtonGroup::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_pressed_button:BaseButton"),&ButtonGroup::get_pressed_button);
+ ClassDB::bind_method(D_METHOD("get_pressed_button:BaseButton"), &ButtonGroup::get_pressed_button);
}
ButtonGroup::ButtonGroup() {
diff --git a/scene/gui/base_button.h b/scene/gui/base_button.h
index def4ff7536..e382df61c9 100644
--- a/scene/gui/base_button.h
+++ b/scene/gui/base_button.h
@@ -34,21 +34,19 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class ButtonGroup;
class BaseButton : public Control {
- GDCLASS( BaseButton, Control );
-public:
+ GDCLASS(BaseButton, Control);
+public:
enum ActionMode {
ACTION_MODE_BUTTON_PRESS,
ACTION_MODE_BUTTON_RELEASE,
};
private:
-
bool toggle_mode;
FocusMode enabled_focus_mode;
Ref<ShortCut> shortcut;
@@ -66,17 +64,11 @@ private:
} status;
-
Ref<ButtonGroup> button_group;
-
void _unpress_group();
protected:
-
-
-
-
virtual void pressed();
virtual void toggled(bool p_pressed);
static void _bind_methods();
@@ -85,7 +77,6 @@ protected:
void _notification(int p_what);
public:
-
enum DrawMode {
DRAW_NORMAL,
DRAW_PRESSED,
@@ -114,35 +105,33 @@ public:
void set_enabled_focus_mode(FocusMode p_mode);
FocusMode get_enabled_focus_mode() const;
- void set_shortcut(const Ref<ShortCut>& p_shortcut);
+ void set_shortcut(const Ref<ShortCut> &p_shortcut);
Ref<ShortCut> get_shortcut() const;
- virtual String get_tooltip(const Point2& p_pos) const;
+ virtual String get_tooltip(const Point2 &p_pos) const;
- void set_button_group(const Ref<ButtonGroup>& p_group);
+ void set_button_group(const Ref<ButtonGroup> &p_group);
Ref<ButtonGroup> get_button_group() const;
BaseButton();
~BaseButton();
-
};
-VARIANT_ENUM_CAST( BaseButton::DrawMode )
-VARIANT_ENUM_CAST( BaseButton::ActionMode )
-
-
+VARIANT_ENUM_CAST(BaseButton::DrawMode)
+VARIANT_ENUM_CAST(BaseButton::ActionMode)
class ButtonGroup : public Resource {
- GDCLASS(ButtonGroup,Resource)
-friend class BaseButton;
- Set<BaseButton*> buttons;
+ GDCLASS(ButtonGroup, Resource)
+ friend class BaseButton;
+ Set<BaseButton *> buttons;
+
protected:
static void _bind_methods();
-public:
- BaseButton* get_pressed_button();
- void get_buttons(List<BaseButton*> *r_buttons);
+public:
+ BaseButton *get_pressed_button();
+ void get_buttons(List<BaseButton *> *r_buttons);
ButtonGroup();
};
diff --git a/scene/gui/box_container.cpp b/scene/gui/box_container.cpp
index 1f6e0392d8..7c1487c42f 100644
--- a/scene/gui/box_container.cpp
+++ b/scene/gui/box_container.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "box_container.h"
-#include "margin_container.h"
#include "label.h"
+#include "margin_container.h"
struct _MinSizeCache {
@@ -41,110 +41,105 @@ void BoxContainer::_resort() {
/** First pass, determine minimum size AND amount of stretchable elements */
+ Size2i new_size = get_size();
- Size2i new_size=get_size();
+ int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
- int sep=get_constant("separation");//,vertical?"VBoxContainer":"HBoxContainer");
+ bool first = true;
+ int children_count = 0;
+ int stretch_min = 0;
+ int stretch_avail = 0;
+ float stretch_ratio_total = 0;
+ Map<Control *, _MinSizeCache> min_size_cache;
- bool first=true;
- int children_count=0;
- int stretch_min=0;
- int stretch_avail=0;
- float stretch_ratio_total=0;
- Map<Control*,_MinSizeCache> min_size_cache;
-
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
- Size2i size=c->get_combined_minimum_size();
+ Size2i size = c->get_combined_minimum_size();
_MinSizeCache msc;
if (vertical) { /* VERTICAL */
- stretch_min+=size.height;
- msc.min_size=size.height;
- msc.will_stretch=c->get_v_size_flags() & SIZE_EXPAND;
+ stretch_min += size.height;
+ msc.min_size = size.height;
+ msc.will_stretch = c->get_v_size_flags() & SIZE_EXPAND;
} else { /* HORIZONTAL */
- stretch_min+=size.width;
- msc.min_size=size.width;
- msc.will_stretch=c->get_h_size_flags() & SIZE_EXPAND;
+ stretch_min += size.width;
+ msc.min_size = size.width;
+ msc.will_stretch = c->get_h_size_flags() & SIZE_EXPAND;
}
if (msc.will_stretch) {
- stretch_avail+=msc.min_size;
- stretch_ratio_total+=c->get_stretch_ratio();
+ stretch_avail += msc.min_size;
+ stretch_ratio_total += c->get_stretch_ratio();
}
- msc.final_size=msc.min_size;
- min_size_cache[c]=msc;
+ msc.final_size = msc.min_size;
+ min_size_cache[c] = msc;
children_count++;
}
- if (children_count==0)
+ if (children_count == 0)
return;
- int stretch_max = (vertical? new_size.height : new_size.width ) - (children_count-1) * sep;
+ int stretch_max = (vertical ? new_size.height : new_size.width) - (children_count - 1) * sep;
int stretch_diff = stretch_max - stretch_min;
- if (stretch_diff<0) {
+ if (stretch_diff < 0) {
//avoid negative stretch space
- stretch_max=stretch_min;
- stretch_diff=0;
+ stretch_max = stretch_min;
+ stretch_diff = 0;
}
- stretch_avail+=stretch_diff; //available stretch space.
+ stretch_avail += stretch_diff; //available stretch space.
/** Second, pass sucessively to discard elements that can't be stretched, this will run while stretchable
elements exist */
-
bool has_stretched = false;
- while(stretch_ratio_total>0) { // first of all, dont even be here if no stretchable objects exist
+ while (stretch_ratio_total > 0) { // first of all, dont even be here if no stretchable objects exist
has_stretched = true;
- bool refit_successful=true; //assume refit-test will go well
+ bool refit_successful = true; //assume refit-test will go well
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
ERR_FAIL_COND(!min_size_cache.has(c));
- _MinSizeCache &msc=min_size_cache[c];
+ _MinSizeCache &msc = min_size_cache[c];
if (msc.will_stretch) { //wants to stretch
//let's see if it can really stretch
- int final_pixel_size=stretch_avail * c->get_stretch_ratio() / stretch_ratio_total;
- if (final_pixel_size<msc.min_size) {
+ int final_pixel_size = stretch_avail * c->get_stretch_ratio() / stretch_ratio_total;
+ if (final_pixel_size < msc.min_size) {
//if available stretching area is too small for widget,
//then remove it from stretching area
- msc.will_stretch=false;
- stretch_ratio_total-=c->get_stretch_ratio();
- refit_successful=false;
- stretch_avail-=msc.min_size;
- msc.final_size=msc.min_size;
+ msc.will_stretch = false;
+ stretch_ratio_total -= c->get_stretch_ratio();
+ refit_successful = false;
+ stretch_avail -= msc.min_size;
+ msc.final_size = msc.min_size;
break;
} else {
- msc.final_size=final_pixel_size;
+ msc.final_size = final_pixel_size;
}
}
}
if (refit_successful) //uf refit went well, break
break;
-
}
-
/** Final pass, draw and stretch elements **/
-
- int ofs=0;
+ int ofs = 0;
if (!has_stretched) {
switch (align) {
case ALIGN_BEGIN:
@@ -158,70 +153,64 @@ void BoxContainer::_resort() {
}
}
- first=true;
- int idx=0;
+ first = true;
+ int idx = 0;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
- _MinSizeCache &msc=min_size_cache[c];
-
+ _MinSizeCache &msc = min_size_cache[c];
if (first)
- first=false;
+ first = false;
else
- ofs+=sep;
+ ofs += sep;
- int from=ofs;
- int to=ofs+msc.final_size;
+ int from = ofs;
+ int to = ofs + msc.final_size;
-
- if (msc.will_stretch && idx==children_count-1) {
+ if (msc.will_stretch && idx == children_count - 1) {
//adjust so the last one always fits perfect
//compensating for numerical imprecision
- to=vertical?new_size.height:new_size.width;
-
+ to = vertical ? new_size.height : new_size.width;
}
- int size=to-from;
+ int size = to - from;
Rect2 rect;
if (vertical) {
- rect=Rect2(0,from,new_size.width,size);
+ rect = Rect2(0, from, new_size.width, size);
} else {
- rect=Rect2(from,0,size,new_size.height);
-
+ rect = Rect2(from, 0, size, new_size.height);
}
- fit_child_in_rect(c,rect);
+ fit_child_in_rect(c, rect);
- ofs=to;
+ ofs = to;
idx++;
}
-
}
Size2 BoxContainer::get_minimum_size() const {
-
/* Calculate MINIMUM SIZE */
Size2i minimum;
- int sep=get_constant("separation");//,vertical?"VBoxContainer":"HBoxContainer");
+ int sep = get_constant("separation"); //,vertical?"VBoxContainer":"HBoxContainer");
- bool first=true;
+ bool first = true;
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
@@ -231,27 +220,26 @@ Size2 BoxContainer::get_minimum_size() const {
continue;
}
- Size2i size=c->get_combined_minimum_size();
+ Size2i size = c->get_combined_minimum_size();
if (vertical) { /* VERTICAL */
- if ( size.width > minimum.width ) {
- minimum.width=size.width;
+ if (size.width > minimum.width) {
+ minimum.width = size.width;
}
- minimum.height+=size.height+(first?0:sep);
+ minimum.height += size.height + (first ? 0 : sep);
} else { /* HORIZONTAL */
- if ( size.height > minimum.height ) {
- minimum.height=size.height;
+ if (size.height > minimum.height) {
+ minimum.height = size.height;
}
- minimum.width+=size.width+(first?0:sep);
-
+ minimum.width += size.width + (first ? 0 : sep);
}
- first=false;
+ first = false;
}
return minimum;
@@ -259,7 +247,7 @@ Size2 BoxContainer::get_minimum_size() const {
void BoxContainer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
@@ -279,7 +267,7 @@ BoxContainer::AlignMode BoxContainer::get_alignment() const {
void BoxContainer::add_spacer(bool p_begin) {
- Control *c = memnew( Control );
+ Control *c = memnew(Control);
c->set_mouse_filter(MOUSE_FILTER_PASS); //allow spacer to pass mouse events
if (vertical)
@@ -289,12 +277,12 @@ void BoxContainer::add_spacer(bool p_begin) {
add_child(c);
if (p_begin)
- move_child(c,0);
+ move_child(c, 0);
}
BoxContainer::BoxContainer(bool p_vertical) {
- vertical=p_vertical;
+ vertical = p_vertical;
align = ALIGN_BEGIN;
//set_ignore_mouse(true);
set_mouse_filter(MOUSE_FILTER_PASS);
@@ -302,24 +290,23 @@ BoxContainer::BoxContainer(bool p_vertical) {
void BoxContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_spacer","begin"),&BoxContainer::add_spacer);
- ClassDB::bind_method(D_METHOD("get_alignment"),&BoxContainer::get_alignment);
- ClassDB::bind_method(D_METHOD("set_alignment","alignment"),&BoxContainer::set_alignment);
-
- BIND_CONSTANT( ALIGN_BEGIN );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_END );
+ ClassDB::bind_method(D_METHOD("add_spacer", "begin"), &BoxContainer::add_spacer);
+ ClassDB::bind_method(D_METHOD("get_alignment"), &BoxContainer::get_alignment);
+ ClassDB::bind_method(D_METHOD("set_alignment", "alignment"), &BoxContainer::set_alignment);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment","get_alignment") ;
+ BIND_CONSTANT(ALIGN_BEGIN);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_END);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "alignment", PROPERTY_HINT_ENUM, "Begin,Center,End"), "set_alignment", "get_alignment");
}
-MarginContainer* VBoxContainer::add_margin_child(const String& p_label,Control *p_control,bool p_expand) {
+MarginContainer *VBoxContainer::add_margin_child(const String &p_label, Control *p_control, bool p_expand) {
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
l->set_text(p_label);
add_child(l);
- MarginContainer *mc = memnew( MarginContainer );
+ MarginContainer *mc = memnew(MarginContainer);
mc->add_child(p_control);
add_child(mc);
if (p_expand)
diff --git a/scene/gui/box_container.h b/scene/gui/box_container.h
index c428ec132c..04b074896b 100644
--- a/scene/gui/box_container.h
+++ b/scene/gui/box_container.h
@@ -33,10 +33,9 @@
class BoxContainer : public Container {
- GDCLASS(BoxContainer,Container);
+ GDCLASS(BoxContainer, Container);
public:
-
enum AlignMode {
ALIGN_BEGIN,
ALIGN_CENTER,
@@ -48,44 +47,42 @@ private:
AlignMode align;
void _resort();
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void add_spacer(bool p_begin=false);
+public:
+ void add_spacer(bool p_begin = false);
void set_alignment(AlignMode p_align);
AlignMode get_alignment() const;
virtual Size2 get_minimum_size() const;
- BoxContainer(bool p_vertical=false);
+ BoxContainer(bool p_vertical = false);
};
-
class HBoxContainer : public BoxContainer {
- GDCLASS(HBoxContainer,BoxContainer);
+ GDCLASS(HBoxContainer, BoxContainer);
public:
-
- HBoxContainer() : BoxContainer(false) {}
+ HBoxContainer()
+ : BoxContainer(false) {}
};
-
class MarginContainer;
class VBoxContainer : public BoxContainer {
- GDCLASS(VBoxContainer,BoxContainer);
+ GDCLASS(VBoxContainer, BoxContainer);
public:
+ MarginContainer *add_margin_child(const String &p_label, Control *p_control, bool p_expand = false);
- MarginContainer* add_margin_child(const String& p_label,Control *p_control,bool p_expand=false);
-
- VBoxContainer() : BoxContainer(true) {}
+ VBoxContainer()
+ : BoxContainer(true) {}
};
VARIANT_ENUM_CAST(BoxContainer::AlignMode);
diff --git a/scene/gui/button.cpp b/scene/gui/button.cpp
index de2ccfb0b5..23915c51a8 100644
--- a/scene/gui/button.cpp
+++ b/scene/gui/button.cpp
@@ -27,86 +27,83 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "button.h"
-#include "servers/visual_server.h"
#include "print_string.h"
+#include "servers/visual_server.h"
#include "translation.h"
-
Size2 Button::get_minimum_size() const {
- Size2 minsize=get_font("font")->get_string_size( xl_text );
+ Size2 minsize = get_font("font")->get_string_size(xl_text);
if (clip_text)
- minsize.width=0;
+ minsize.width = 0;
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
- _icon=Control::get_icon("icon");
+ _icon = Control::get_icon("icon");
else
- _icon=icon;
+ _icon = icon;
if (!_icon.is_null()) {
- minsize.height=MAX( minsize.height, _icon->get_height() );
- minsize.width+=_icon->get_width();
- if (xl_text!="")
- minsize.width+=get_constant("hseparation");
+ minsize.height = MAX(minsize.height, _icon->get_height());
+ minsize.width += _icon->get_width();
+ if (xl_text != "")
+ minsize.width += get_constant("hseparation");
}
- return get_stylebox("normal" )->get_minimum_size() + minsize;
-
+ return get_stylebox("normal")->get_minimum_size() + minsize;
}
-
void Button::_notification(int p_what) {
- if (p_what==NOTIFICATION_TRANSLATION_CHANGED) {
+ if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
- xl_text=XL_MESSAGE(text);
+ xl_text = XL_MESSAGE(text);
minimum_size_changed();
update();
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Size2 size=get_size();
+ Size2 size = get_size();
Color color;
//print_line(get_text()+": "+itos(is_flat())+" hover "+itos(get_draw_mode()));
Ref<StyleBox> style = get_stylebox("normal");
- switch( get_draw_mode() ) {
+ switch (get_draw_mode()) {
case DRAW_NORMAL: {
style = get_stylebox("normal");
if (!flat)
- style->draw( ci, Rect2(Point2(0,0), size) );
- color=get_color("font_color");
+ style->draw(ci, Rect2(Point2(0, 0), size));
+ color = get_color("font_color");
} break;
case DRAW_PRESSED: {
style = get_stylebox("pressed");
- style->draw( ci, Rect2(Point2(0,0), size) );
+ style->draw(ci, Rect2(Point2(0, 0), size));
if (has_color("font_color_pressed"))
- color=get_color("font_color_pressed");
+ color = get_color("font_color_pressed");
else
- color=get_color("font_color");
+ color = get_color("font_color");
} break;
case DRAW_HOVER: {
style = get_stylebox("hover");
- style->draw( ci, Rect2(Point2(0,0), size) );
- color=get_color("font_color_hover");
+ style->draw(ci, Rect2(Point2(0, 0), size));
+ color = get_color("font_color_hover");
} break;
case DRAW_DISABLED: {
style = get_stylebox("disabled");
- style->draw( ci, Rect2(Point2(0,0), size) );
- color=get_color("font_color_disabled");
+ style->draw(ci, Rect2(Point2(0, 0), size));
+ color = get_color("font_color_disabled");
} break;
}
@@ -114,58 +111,54 @@ void Button::_notification(int p_what) {
if (has_focus()) {
Ref<StyleBox> style = get_stylebox("focus");
- style->draw(ci,Rect2(Point2(),size));
+ style->draw(ci, Rect2(Point2(), size));
}
- Ref<Font> font=get_font("font");
+ Ref<Font> font = get_font("font");
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
- _icon=Control::get_icon("icon");
+ _icon = Control::get_icon("icon");
else
- _icon=icon;
+ _icon = icon;
- Point2 icon_ofs = (!_icon.is_null())?Point2( _icon->get_width() + get_constant("hseparation"), 0):Point2();
- int text_clip=size.width - style->get_minimum_size().width - icon_ofs.width;
- Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size( xl_text ) )/2.0;
+ Point2 icon_ofs = (!_icon.is_null()) ? Point2(_icon->get_width() + get_constant("hseparation"), 0) : Point2();
+ int text_clip = size.width - style->get_minimum_size().width - icon_ofs.width;
+ Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size(xl_text)) / 2.0;
- switch(align) {
+ switch (align) {
case ALIGN_LEFT: {
text_ofs.x = style->get_margin(MARGIN_LEFT) + icon_ofs.x;
- text_ofs.y+=style->get_offset().y;
+ text_ofs.y += style->get_offset().y;
} break;
case ALIGN_CENTER: {
- if (text_ofs.x<0)
- text_ofs.x=0;
- text_ofs+=icon_ofs;
- text_ofs+=style->get_offset();
+ if (text_ofs.x < 0)
+ text_ofs.x = 0;
+ text_ofs += icon_ofs;
+ text_ofs += style->get_offset();
} break;
case ALIGN_RIGHT: {
- text_ofs.x=size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size( xl_text ).x;
- text_ofs.y+=style->get_offset().y;
+ text_ofs.x = size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size(xl_text).x;
+ text_ofs.y += style->get_offset().y;
} break;
}
-
- text_ofs.y+=font->get_ascent();
- font->draw( ci, text_ofs.floor(), xl_text, color,clip_text?text_clip:-1);
+ text_ofs.y += font->get_ascent();
+ font->draw(ci, text_ofs.floor(), xl_text, color, clip_text ? text_clip : -1);
if (!_icon.is_null()) {
- int valign = size.height-style->get_minimum_size().y;
+ int valign = size.height - style->get_minimum_size().y;
- _icon->draw(ci,style->get_offset()+Point2(0, Math::floor( (valign-_icon->get_height())/2.0 ) ),is_disabled()?Color(1,1,1,0.4):Color(1,1,1) );
+ _icon->draw(ci, style->get_offset() + Point2(0, Math::floor((valign - _icon->get_height()) / 2.0)), is_disabled() ? Color(1, 1, 1, 0.4) : Color(1, 1, 1));
}
-
-
-
}
}
-void Button::set_text(const String& p_text) {
+void Button::set_text(const String &p_text) {
- if (text==p_text)
+ if (text == p_text)
return;
- text=p_text;
- xl_text=XL_MESSAGE(p_text);
+ text = p_text;
+ xl_text = XL_MESSAGE(p_text);
update();
_change_notify("text");
minimum_size_changed();
@@ -175,12 +168,11 @@ String Button::get_text() const {
return text;
}
+void Button::set_icon(const Ref<Texture> &p_icon) {
-void Button::set_icon(const Ref<Texture>& p_icon) {
-
- if (icon==p_icon)
+ if (icon == p_icon)
return;
- icon=p_icon;
+ icon = p_icon;
update();
_change_notify("icon");
minimum_size_changed();
@@ -193,7 +185,7 @@ Ref<Texture> Button::get_icon() const {
void Button::set_flat(bool p_flat) {
- flat=p_flat;
+ flat = p_flat;
update();
_change_notify("flat");
}
@@ -205,7 +197,7 @@ bool Button::is_flat() const {
void Button::set_clip_text(bool p_clip_text) {
- clip_text=p_clip_text;
+ clip_text = p_clip_text;
update();
minimum_size_changed();
}
@@ -217,7 +209,7 @@ bool Button::get_clip_text() const {
void Button::set_text_align(TextAlign p_align) {
- align=p_align;
+ align = p_align;
update();
}
@@ -228,41 +220,36 @@ Button::TextAlign Button::get_text_align() const {
void Button::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_text","text"),&Button::set_text);
- ClassDB::bind_method(D_METHOD("get_text"),&Button::get_text);
- ClassDB::bind_method(D_METHOD("set_button_icon","texture:Texture"),&Button::set_icon);
- ClassDB::bind_method(D_METHOD("get_button_icon:Texture"),&Button::get_icon);
- ClassDB::bind_method(D_METHOD("set_flat","enabled"),&Button::set_flat);
- ClassDB::bind_method(D_METHOD("set_clip_text","enabled"),&Button::set_clip_text);
- ClassDB::bind_method(D_METHOD("get_clip_text"),&Button::get_clip_text);
- ClassDB::bind_method(D_METHOD("set_text_align","align"),&Button::set_text_align);
- ClassDB::bind_method(D_METHOD("get_text_align"),&Button::get_text_align);
- ClassDB::bind_method(D_METHOD("is_flat"),&Button::is_flat);
-
- BIND_CONSTANT( ALIGN_LEFT );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_RIGHT );
-
- ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "text", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT_INTL ), "set_text","get_text") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture" ), "set_button_icon","get_button_icon") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flat" ), "set_flat","is_flat") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "clip_text" ), "set_clip_text","get_clip_text") ;
- ADD_PROPERTYNO( PropertyInfo( Variant::INT, "align",PROPERTY_HINT_ENUM,"Left,Center,Right" ), "set_text_align","get_text_align") ;
-
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &Button::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &Button::get_text);
+ ClassDB::bind_method(D_METHOD("set_button_icon", "texture:Texture"), &Button::set_icon);
+ ClassDB::bind_method(D_METHOD("get_button_icon:Texture"), &Button::get_icon);
+ ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &Button::set_flat);
+ ClassDB::bind_method(D_METHOD("set_clip_text", "enabled"), &Button::set_clip_text);
+ ClassDB::bind_method(D_METHOD("get_clip_text"), &Button::get_clip_text);
+ ClassDB::bind_method(D_METHOD("set_text_align", "align"), &Button::set_text_align);
+ ClassDB::bind_method(D_METHOD("get_text_align"), &Button::get_text_align);
+ ClassDB::bind_method(D_METHOD("is_flat"), &Button::is_flat);
+
+ BIND_CONSTANT(ALIGN_LEFT);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_RIGHT);
+
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_button_icon", "get_button_icon");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_text_align", "get_text_align");
}
Button::Button(const String &p_text) {
- flat=false;
- clip_text=false;
+ flat = false;
+ clip_text = false;
set_mouse_filter(MOUSE_FILTER_STOP);
set_text(p_text);
- align=ALIGN_CENTER;
+ align = ALIGN_CENTER;
}
-
-Button::~Button()
-{
+Button::~Button() {
}
-
-
diff --git a/scene/gui/button.h b/scene/gui/button.h
index 2fd3a0cace..38605bd3ef 100644
--- a/scene/gui/button.h
+++ b/scene/gui/button.h
@@ -34,14 +34,11 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
class Button : public BaseButton {
- GDCLASS( Button, BaseButton );
-public:
-
+ GDCLASS(Button, BaseButton);
+public:
enum TextAlign {
ALIGN_LEFT,
ALIGN_CENTER,
@@ -49,7 +46,6 @@ public:
};
private:
-
bool flat;
String text;
String xl_text;
@@ -57,20 +53,18 @@ private:
bool clip_text;
TextAlign align;
-
protected:
-
virtual Size2 get_minimum_size() const;
void _notification(int p_what);
static void _bind_methods();
-public:
-//
+public:
+ //
- void set_text(const String& p_text);
+ void set_text(const String &p_text);
String get_text() const;
- void set_icon(const Ref<Texture>& p_icon);
+ void set_icon(const Ref<Texture> &p_icon);
Ref<Texture> get_icon() const;
void set_flat(bool p_flat);
@@ -82,13 +76,10 @@ public:
void set_text_align(TextAlign p_align);
TextAlign get_text_align() const;
-
- Button(const String& p_text=String());
+ Button(const String &p_text = String());
~Button();
-
};
-
VARIANT_ENUM_CAST(Button::TextAlign);
#endif
diff --git a/scene/gui/button_array.cpp b/scene/gui/button_array.cpp
index 2fd5f0df83..c1cb9ad855 100644
--- a/scene/gui/button_array.cpp
+++ b/scene/gui/button_array.cpp
@@ -28,46 +28,44 @@
/*************************************************************************/
#include "button_array.h"
+bool ButtonArray::_set(const StringName &p_name, const Variant &p_value) {
-bool ButtonArray::_set(const StringName& p_name, const Variant& p_value) {
-
- String n=String(p_name);
+ String n = String(p_name);
if (n.begins_with("button/")) {
- String what = n.get_slicec('/',1);
- if (what=="count") {
- int new_size=p_value;
- if (new_size>0 && buttons.size()==0) {
- selected=0;
+ String what = n.get_slicec('/', 1);
+ if (what == "count") {
+ int new_size = p_value;
+ if (new_size > 0 && buttons.size() == 0) {
+ selected = 0;
}
if (new_size < buttons.size()) {
- if (selected>=new_size)
- selected=new_size-1;
+ if (selected >= new_size)
+ selected = new_size - 1;
}
buttons.resize(new_size);
_change_notify();
minimum_size_changed();
- } else if (what=="align") {
+ } else if (what == "align") {
set_align(Align(p_value.operator int()));
- } else if (what=="selected") {
+ } else if (what == "selected") {
set_selected(p_value);
} else if (what == "min_button_size") {
min_button_size = p_value;
} else {
- int idx=what.to_int();
- ERR_FAIL_INDEX_V(idx,buttons.size(),false);
- String f = n.get_slicec('/',2);
- if (f=="text") {
- buttons[idx].text=p_value;
- buttons[idx].xl_text=XL_MESSAGE(p_value);
- } else if (f=="tooltip")
- buttons[idx].tooltip=p_value;
- else if (f=="icon")
- buttons[idx].icon=p_value;
+ int idx = what.to_int();
+ ERR_FAIL_INDEX_V(idx, buttons.size(), false);
+ String f = n.get_slicec('/', 2);
+ if (f == "text") {
+ buttons[idx].text = p_value;
+ buttons[idx].xl_text = XL_MESSAGE(p_value);
+ } else if (f == "tooltip")
+ buttons[idx].tooltip = p_value;
+ else if (f == "icon")
+ buttons[idx].icon = p_value;
else
return false;
-
}
update();
@@ -75,36 +73,34 @@ bool ButtonArray::_set(const StringName& p_name, const Variant& p_value) {
}
return false;
-
}
-bool ButtonArray::_get(const StringName& p_name,Variant &r_ret) const {
+bool ButtonArray::_get(const StringName &p_name, Variant &r_ret) const {
- String n=String(p_name);
+ String n = String(p_name);
if (n.begins_with("button/")) {
- String what = n.get_slicec('/',1);
- if (what=="count") {
- r_ret=buttons.size();
- } else if (what=="align") {
- r_ret=get_align();
- } else if (what=="selected") {
- r_ret=get_selected();
- } else if (what == "min_button_size"){
+ String what = n.get_slicec('/', 1);
+ if (what == "count") {
+ r_ret = buttons.size();
+ } else if (what == "align") {
+ r_ret = get_align();
+ } else if (what == "selected") {
+ r_ret = get_selected();
+ } else if (what == "min_button_size") {
r_ret = min_button_size;
} else {
- int idx=what.to_int();
- ERR_FAIL_INDEX_V(idx,buttons.size(),false);
- String f = n.get_slicec('/',2);
- if (f=="text")
- r_ret=buttons[idx].text;
- else if (f=="tooltip")
- r_ret=buttons[idx].tooltip;
- else if (f=="icon")
- r_ret=buttons[idx].icon;
+ int idx = what.to_int();
+ ERR_FAIL_INDEX_V(idx, buttons.size(), false);
+ String f = n.get_slicec('/', 2);
+ if (f == "text")
+ r_ret = buttons[idx].text;
+ else if (f == "tooltip")
+ r_ret = buttons[idx].tooltip;
+ else if (f == "icon")
+ r_ret = buttons[idx].icon;
else
return false;
-
}
return true;
@@ -112,24 +108,22 @@ bool ButtonArray::_get(const StringName& p_name,Variant &r_ret) const {
return false;
}
-void ButtonArray::_get_property_list( List<PropertyInfo> *p_list) const {
-
- p_list->push_back( PropertyInfo( Variant::INT, "button/count",PROPERTY_HINT_RANGE,"0,512,1"));
- p_list->push_back( PropertyInfo( Variant::INT, "button/min_button_size",PROPERTY_HINT_RANGE,"0,1024,1"));
- p_list->push_back( PropertyInfo( Variant::INT, "button/align",PROPERTY_HINT_ENUM,"Begin,Center,End,Fill,Expand"));
- for(int i=0;i<buttons.size();i++) {
- String base="button/"+itos(i)+"/";
- p_list->push_back( PropertyInfo( Variant::STRING, base+"text"));
- p_list->push_back( PropertyInfo( Variant::STRING, base+"tooltip"));
- p_list->push_back( PropertyInfo( Variant::OBJECT, base+"icon",PROPERTY_HINT_RESOURCE_TYPE,"Texture"));
+void ButtonArray::_get_property_list(List<PropertyInfo> *p_list) const {
+
+ p_list->push_back(PropertyInfo(Variant::INT, "button/count", PROPERTY_HINT_RANGE, "0,512,1"));
+ p_list->push_back(PropertyInfo(Variant::INT, "button/min_button_size", PROPERTY_HINT_RANGE, "0,1024,1"));
+ p_list->push_back(PropertyInfo(Variant::INT, "button/align", PROPERTY_HINT_ENUM, "Begin,Center,End,Fill,Expand"));
+ for (int i = 0; i < buttons.size(); i++) {
+ String base = "button/" + itos(i) + "/";
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "text"));
+ p_list->push_back(PropertyInfo(Variant::STRING, base + "tooltip"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, base + "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"));
}
- if (buttons.size()>0) {
- p_list->push_back( PropertyInfo( Variant::INT, "button/selected",PROPERTY_HINT_RANGE,"0,"+itos(buttons.size()-1)+",1"));
+ if (buttons.size() > 0) {
+ p_list->push_back(PropertyInfo(Variant::INT, "button/selected", PROPERTY_HINT_RANGE, "0," + itos(buttons.size() - 1) + ",1"));
}
-
}
-
Size2 ButtonArray::get_minimum_size() const {
Ref<StyleBox> style_normal = get_stylebox("normal");
@@ -141,54 +135,51 @@ Size2 ButtonArray::get_minimum_size() const {
Size2 minsize;
- for(int i=0;i<buttons.size();i++) {
+ for (int i = 0; i < buttons.size(); i++) {
- Ref<StyleBox> sb = i==selected ? style_selected : style_normal;
- Ref<Font> f = i==selected ? font_selected : font_normal;
+ Ref<StyleBox> sb = i == selected ? style_selected : style_normal;
+ Ref<Font> f = i == selected ? font_selected : font_normal;
Size2 ms;
ms = f->get_string_size(buttons[i].xl_text);
if (buttons[i].icon.is_valid()) {
Size2 bs = buttons[i].icon->get_size();
- ms.height = MAX(ms.height,bs.height);
- ms.width+=bs.width+icon_sep;
+ ms.height = MAX(ms.height, bs.height);
+ ms.width += bs.width + icon_sep;
}
- ms+=sb->get_minimum_size();
+ ms += sb->get_minimum_size();
- buttons[i]._ms_cache=ms[orientation];
-
- minsize[orientation]+=ms[orientation];
- if (i>0)
- minsize[orientation]+=button_sep;
- minsize[!orientation] = MAX(minsize[!orientation],ms[!orientation]);
+ buttons[i]._ms_cache = ms[orientation];
+ minsize[orientation] += ms[orientation];
+ if (i > 0)
+ minsize[orientation] += button_sep;
+ minsize[!orientation] = MAX(minsize[!orientation], ms[!orientation]);
}
return minsize;
-
-
}
void ButtonArray::_notification(int p_what) {
- switch(p_what) {
- case NOTIFICATION_MOUSE_EXIT:{
- hover=-1;
+ switch (p_what) {
+ case NOTIFICATION_MOUSE_EXIT: {
+ hover = -1;
update();
- }break;
- case NOTIFICATION_READY:{
+ } break;
+ case NOTIFICATION_READY: {
MethodInfo mi;
- mi.name="mouse_sub_enter";
+ mi.name = "mouse_sub_enter";
add_user_signal(mi);
- }break;
+ } break;
case NOTIFICATION_DRAW: {
- Size2 size=get_size();
- Size2 minsize=get_combined_minimum_size();
+ Size2 size = get_size();
+ Size2 minsize = get_combined_minimum_size();
Ref<StyleBox> style_normal = get_stylebox("normal");
Ref<StyleBox> style_selected = get_stylebox("selected");
Ref<StyleBox> style_focus = get_stylebox("focus");
@@ -200,188 +191,174 @@ void ButtonArray::_notification(int p_what) {
Color color_normal = get_color("font_color");
Color color_selected = get_color("font_color_selected");
- int sep=button_sep;
- int ofs=0;
- int expand=0;
+ int sep = button_sep;
+ int ofs = 0;
+ int expand = 0;
- switch(align) {
+ switch (align) {
case ALIGN_BEGIN: {
- ofs=0;
+ ofs = 0;
} break;
case ALIGN_CENTER: {
- ofs=Math::floor((size[orientation] - minsize[orientation])/2);
+ ofs = Math::floor((size[orientation] - minsize[orientation]) / 2);
} break;
case ALIGN_END: {
- ofs=Math::floor((size[orientation] - minsize[orientation]));
+ ofs = Math::floor((size[orientation] - minsize[orientation]));
} break;
case ALIGN_FILL: {
- if (buttons.size()>1)
- sep+=Math::floor((size[orientation]- minsize[orientation])/(buttons.size()-1.0));
- ofs=0;
+ if (buttons.size() > 1)
+ sep += Math::floor((size[orientation] - minsize[orientation]) / (buttons.size() - 1.0));
+ ofs = 0;
} break;
case ALIGN_EXPAND_FILL: {
- ofs=0;
- expand=size[orientation] - minsize[orientation];
+ ofs = 0;
+ expand = size[orientation] - minsize[orientation];
} break;
-
-
-
}
- int op_size = orientation==VERTICAL ? size.width : size.height;
-
+ int op_size = orientation == VERTICAL ? size.width : size.height;
- for(int i=0;i<buttons.size();i++) {
+ for (int i = 0; i < buttons.size(); i++) {
int ms = buttons[i]._ms_cache;
- int s=ms;
- if (expand>0) {
- s+=expand/buttons.size();
+ int s = ms;
+ if (expand > 0) {
+ s += expand / buttons.size();
}
- if(min_button_size != -1 && s < min_button_size){
+ if (min_button_size != -1 && s < min_button_size) {
s = min_button_size;
}
Rect2 r;
- r.pos[orientation]=ofs;
- r.pos[!orientation]=0;
- r.size[orientation]=s;
- r.size[!orientation]=op_size;
+ r.pos[orientation] = ofs;
+ r.pos[!orientation] = 0;
+ r.size[orientation] = s;
+ r.size[!orientation] = op_size;
Ref<Font> f;
Color c;
Point2 sbsize;
Point2 sbofs;
- if (i==selected) {
- draw_style_box(style_selected,r);
- sbsize=style_selected->get_minimum_size();
- sbofs=style_selected->get_offset();
- f=font_selected;
- c=color_selected;
+ if (i == selected) {
+ draw_style_box(style_selected, r);
+ sbsize = style_selected->get_minimum_size();
+ sbofs = style_selected->get_offset();
+ f = font_selected;
+ c = color_selected;
if (has_focus())
- draw_style_box(style_focus,r);
+ draw_style_box(style_focus, r);
} else {
- if (hover==i)
- draw_style_box(style_hover,r);
+ if (hover == i)
+ draw_style_box(style_hover, r);
else if (!flat)
- draw_style_box(style_normal,r);
- sbsize=style_normal->get_minimum_size();
- sbofs=style_normal->get_offset();
- f=font_normal;
- c=color_normal;
+ draw_style_box(style_normal, r);
+ sbsize = style_normal->get_minimum_size();
+ sbofs = style_normal->get_offset();
+ f = font_normal;
+ c = color_normal;
}
Size2 ssize = f->get_string_size(buttons[i].xl_text);
if (buttons[i].icon.is_valid()) {
- ssize.x+=buttons[i].icon->get_width();
+ ssize.x += buttons[i].icon->get_width();
}
- Point2 text_ofs=((r.size-ssize-sbsize)/2.0+Point2(0,f->get_ascent())).floor()+sbofs;
+ Point2 text_ofs = ((r.size - ssize - sbsize) / 2.0 + Point2(0, f->get_ascent())).floor() + sbofs;
if (buttons[i].icon.is_valid()) {
- draw_texture(buttons[i].icon,r.pos+Point2(text_ofs.x,Math::floor((r.size.height-buttons[i].icon->get_height())/2.0)));
- text_ofs.x+=buttons[i].icon->get_width()+icon_sep;
-
+ draw_texture(buttons[i].icon, r.pos + Point2(text_ofs.x, Math::floor((r.size.height - buttons[i].icon->get_height()) / 2.0)));
+ text_ofs.x += buttons[i].icon->get_width() + icon_sep;
}
- draw_string(f,text_ofs+r.pos,buttons[i].xl_text,c);
- buttons[i]._pos_cache=ofs;
- buttons[i]._size_cache=s;
+ draw_string(f, text_ofs + r.pos, buttons[i].xl_text, c);
+ buttons[i]._pos_cache = ofs;
+ buttons[i]._size_cache = s;
- ofs+=s;
- ofs+=sep;
+ ofs += s;
+ ofs += sep;
}
} break;
}
}
-
-void ButtonArray::_gui_input(const InputEvent& p_event) {
+void ButtonArray::_gui_input(const InputEvent &p_event) {
if (
- ( (orientation==HORIZONTAL && p_event.is_action("ui_left") ) ||
- (orientation==VERTICAL && p_event.is_action("ui_up") ) )
- && p_event.is_pressed() && selected>0) {
- set_selected(selected-1);
- accept_event();
- emit_signal("button_selected",selected);
- return;
-
+ ((orientation == HORIZONTAL && p_event.is_action("ui_left")) ||
+ (orientation == VERTICAL && p_event.is_action("ui_up"))) &&
+ p_event.is_pressed() && selected > 0) {
+ set_selected(selected - 1);
+ accept_event();
+ emit_signal("button_selected", selected);
+ return;
}
if (
- ( (orientation==HORIZONTAL && p_event.is_action("ui_right") ) ||
- (orientation==VERTICAL && p_event.is_action("ui_down") ) )
- && p_event.is_pressed() && selected<(buttons.size()-1)) {
- set_selected(selected+1);
- accept_event();
- emit_signal("button_selected",selected);
- return;
-
+ ((orientation == HORIZONTAL && p_event.is_action("ui_right")) ||
+ (orientation == VERTICAL && p_event.is_action("ui_down"))) &&
+ p_event.is_pressed() && selected < (buttons.size() - 1)) {
+ set_selected(selected + 1);
+ accept_event();
+ emit_signal("button_selected", selected);
+ return;
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index==BUTTON_LEFT) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index == BUTTON_LEFT) {
- int ofs = orientation==HORIZONTAL ? p_event.mouse_button.x: p_event.mouse_button.y;
+ int ofs = orientation == HORIZONTAL ? p_event.mouse_button.x : p_event.mouse_button.y;
- for(int i=0;i<buttons.size();i++) {
+ for (int i = 0; i < buttons.size(); i++) {
- if (ofs>=buttons[i]._pos_cache && ofs<buttons[i]._pos_cache+buttons[i]._size_cache) {
+ if (ofs >= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache) {
set_selected(i);
- emit_signal("button_selected",i);
+ emit_signal("button_selected", i);
return;
}
-
}
}
- if (p_event.type==InputEvent::MOUSE_MOTION) {
+ if (p_event.type == InputEvent::MOUSE_MOTION) {
- int ofs = orientation==HORIZONTAL ? p_event.mouse_motion.x: p_event.mouse_motion.y;
- int new_hover=-1;
- for(int i=0;i<buttons.size();i++) {
+ int ofs = orientation == HORIZONTAL ? p_event.mouse_motion.x : p_event.mouse_motion.y;
+ int new_hover = -1;
+ for (int i = 0; i < buttons.size(); i++) {
- if (ofs>=buttons[i]._pos_cache && ofs<buttons[i]._pos_cache+buttons[i]._size_cache) {
+ if (ofs >= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache) {
- new_hover=i;
+ new_hover = i;
break;
}
-
}
- if (new_hover!=hover) {
- hover=new_hover;
+ if (new_hover != hover) {
+ hover = new_hover;
emit_signal("mouse_sub_enter");
update();
}
}
-
-
}
-String ButtonArray::get_tooltip(const Point2& p_pos) const {
+String ButtonArray::get_tooltip(const Point2 &p_pos) const {
- int ofs = orientation==HORIZONTAL ? p_pos.x: p_pos.y;
- for(int i=0;i<buttons.size();i++) {
+ int ofs = orientation == HORIZONTAL ? p_pos.x : p_pos.y;
+ for (int i = 0; i < buttons.size(); i++) {
- if (ofs>=buttons[i]._pos_cache && ofs<buttons[i]._pos_cache+buttons[i]._size_cache)
+ if (ofs >= buttons[i]._pos_cache && ofs < buttons[i]._pos_cache + buttons[i]._size_cache)
return buttons[i].tooltip;
-
}
return Control::get_tooltip(p_pos);
}
void ButtonArray::set_align(Align p_align) {
- align=p_align;
+ align = p_align;
update();
-
}
ButtonArray::Align ButtonArray::get_align() const {
@@ -391,7 +368,7 @@ ButtonArray::Align ButtonArray::get_align() const {
void ButtonArray::set_flat(bool p_flat) {
- flat=p_flat;
+ flat = p_flat;
update();
}
@@ -400,79 +377,74 @@ bool ButtonArray::is_flat() const {
return flat;
}
-
-void ButtonArray::add_button(const String& p_text,const String& p_tooltip) {
+void ButtonArray::add_button(const String &p_text, const String &p_tooltip) {
Button button;
- button.text=p_text;
- button.xl_text=XL_MESSAGE(p_text);
- button.tooltip=p_tooltip;
+ button.text = p_text;
+ button.xl_text = XL_MESSAGE(p_text);
+ button.tooltip = p_tooltip;
buttons.push_back(button);
update();
- if (selected==-1)
- selected=0;
+ if (selected == -1)
+ selected = 0;
minimum_size_changed();
}
-void ButtonArray::add_icon_button(const Ref<Texture>& p_icon,const String& p_text,const String& p_tooltip) {
+void ButtonArray::add_icon_button(const Ref<Texture> &p_icon, const String &p_text, const String &p_tooltip) {
Button button;
- button.text=p_text;
- button.xl_text=XL_MESSAGE(p_text);
- button.icon=p_icon;
- button.tooltip=p_tooltip;
+ button.text = p_text;
+ button.xl_text = XL_MESSAGE(p_text);
+ button.icon = p_icon;
+ button.tooltip = p_tooltip;
buttons.push_back(button);
- if (selected==-1)
- selected=0;
+ if (selected == -1)
+ selected = 0;
update();
-
}
-void ButtonArray::set_button_text(int p_button, const String& p_text) {
+void ButtonArray::set_button_text(int p_button, const String &p_text) {
- ERR_FAIL_INDEX(p_button,buttons.size());
- buttons[p_button].text=p_text;
- buttons[p_button].xl_text=XL_MESSAGE(p_text);
+ ERR_FAIL_INDEX(p_button, buttons.size());
+ buttons[p_button].text = p_text;
+ buttons[p_button].xl_text = XL_MESSAGE(p_text);
update();
minimum_size_changed();
-
}
-void ButtonArray::set_button_tooltip(int p_button, const String& p_text) {
-
- ERR_FAIL_INDEX(p_button,buttons.size());
- buttons[p_button].tooltip=p_text;
+void ButtonArray::set_button_tooltip(int p_button, const String &p_text) {
+ ERR_FAIL_INDEX(p_button, buttons.size());
+ buttons[p_button].tooltip = p_text;
}
-void ButtonArray::set_button_icon(int p_button, const Ref<Texture>& p_icon) {
+void ButtonArray::set_button_icon(int p_button, const Ref<Texture> &p_icon) {
- ERR_FAIL_INDEX(p_button,buttons.size());
- buttons[p_button].icon=p_icon;
+ ERR_FAIL_INDEX(p_button, buttons.size());
+ buttons[p_button].icon = p_icon;
update();
minimum_size_changed();
}
String ButtonArray::get_button_text(int p_button) const {
- ERR_FAIL_INDEX_V(p_button,buttons.size(),"");
+ ERR_FAIL_INDEX_V(p_button, buttons.size(), "");
return buttons[p_button].text;
}
String ButtonArray::get_button_tooltip(int p_button) const {
- ERR_FAIL_INDEX_V(p_button,buttons.size(),"");
+ ERR_FAIL_INDEX_V(p_button, buttons.size(), "");
return buttons[p_button].tooltip;
}
Ref<Texture> ButtonArray::get_button_icon(int p_button) const {
- ERR_FAIL_INDEX_V(p_button,buttons.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_button, buttons.size(), Ref<Texture>());
return buttons[p_button].icon;
-
}
int ButtonArray::get_selected() const {
@@ -487,30 +459,29 @@ int ButtonArray::get_hovered() const {
void ButtonArray::set_selected(int p_selected) {
- ERR_FAIL_INDEX(p_selected,buttons.size());
- selected=p_selected;
+ ERR_FAIL_INDEX(p_selected, buttons.size());
+ selected = p_selected;
update();
-
}
void ButtonArray::erase_button(int p_button) {
- ERR_FAIL_INDEX(p_button,buttons.size());
+ ERR_FAIL_INDEX(p_button, buttons.size());
buttons.remove(p_button);
- if (p_button>=selected)
+ if (p_button >= selected)
selected--;
- if (selected<0)
- selected=0;
- if (selected>=buttons.size())
- selected=buttons.size()-1;
+ if (selected < 0)
+ selected = 0;
+ if (selected >= buttons.size())
+ selected = buttons.size() - 1;
update();
}
-void ButtonArray::clear(){
+void ButtonArray::clear() {
buttons.clear();
- selected=-1;
+ selected = -1;
update();
}
@@ -521,53 +492,50 @@ int ButtonArray::get_button_count() const {
void ButtonArray::get_translatable_strings(List<String> *p_strings) const {
-
- for(int i=0;i<buttons.size();i++) {
+ for (int i = 0; i < buttons.size(); i++) {
p_strings->push_back(buttons[i].text);
p_strings->push_back(buttons[i].tooltip);
}
}
-
void ButtonArray::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_button","text","tooltip"),&ButtonArray::add_button,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("add_icon_button","icon:Texture","text","tooltip"),&ButtonArray::add_icon_button,DEFVAL(""),DEFVAL(""));
- ClassDB::bind_method(D_METHOD("set_button_text","button_idx","text"),&ButtonArray::set_button_text);
- ClassDB::bind_method(D_METHOD("set_button_tooltip","button_idx","text"),&ButtonArray::set_button_tooltip);
- ClassDB::bind_method(D_METHOD("set_button_icon","button_idx","icon:Texture"),&ButtonArray::set_button_icon);
- ClassDB::bind_method(D_METHOD("get_button_text","button_idx"),&ButtonArray::get_button_text);
- ClassDB::bind_method(D_METHOD("get_button_tooltip","button_idx"),&ButtonArray::get_button_tooltip);
- ClassDB::bind_method(D_METHOD("get_button_icon:Texture","button_idx"),&ButtonArray::get_button_icon);
- ClassDB::bind_method(D_METHOD("get_button_count"),&ButtonArray::get_button_count);
- ClassDB::bind_method(D_METHOD("set_flat","enabled"),&ButtonArray::set_flat);
- ClassDB::bind_method(D_METHOD("is_flat"),&ButtonArray::is_flat);
- ClassDB::bind_method(D_METHOD("get_selected"),&ButtonArray::get_selected);
- ClassDB::bind_method(D_METHOD("get_hovered"),&ButtonArray::get_hovered);
- ClassDB::bind_method(D_METHOD("set_selected","button_idx"),&ButtonArray::set_selected);
- ClassDB::bind_method(D_METHOD("erase_button","button_idx"),&ButtonArray::erase_button);
- ClassDB::bind_method(D_METHOD("clear"),&ButtonArray::clear);
-
- ClassDB::bind_method(D_METHOD("_gui_input"),&ButtonArray::_gui_input);
-
- BIND_CONSTANT( ALIGN_BEGIN );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_END );
- BIND_CONSTANT( ALIGN_FILL );
- BIND_CONSTANT( ALIGN_EXPAND_FILL );
-
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "flat" ), "set_flat","is_flat") ;
-
- ADD_SIGNAL( MethodInfo("button_selected",PropertyInfo(Variant::INT,"button_idx")));
-
+ ClassDB::bind_method(D_METHOD("add_button", "text", "tooltip"), &ButtonArray::add_button, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("add_icon_button", "icon:Texture", "text", "tooltip"), &ButtonArray::add_icon_button, DEFVAL(""), DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("set_button_text", "button_idx", "text"), &ButtonArray::set_button_text);
+ ClassDB::bind_method(D_METHOD("set_button_tooltip", "button_idx", "text"), &ButtonArray::set_button_tooltip);
+ ClassDB::bind_method(D_METHOD("set_button_icon", "button_idx", "icon:Texture"), &ButtonArray::set_button_icon);
+ ClassDB::bind_method(D_METHOD("get_button_text", "button_idx"), &ButtonArray::get_button_text);
+ ClassDB::bind_method(D_METHOD("get_button_tooltip", "button_idx"), &ButtonArray::get_button_tooltip);
+ ClassDB::bind_method(D_METHOD("get_button_icon:Texture", "button_idx"), &ButtonArray::get_button_icon);
+ ClassDB::bind_method(D_METHOD("get_button_count"), &ButtonArray::get_button_count);
+ ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &ButtonArray::set_flat);
+ ClassDB::bind_method(D_METHOD("is_flat"), &ButtonArray::is_flat);
+ ClassDB::bind_method(D_METHOD("get_selected"), &ButtonArray::get_selected);
+ ClassDB::bind_method(D_METHOD("get_hovered"), &ButtonArray::get_hovered);
+ ClassDB::bind_method(D_METHOD("set_selected", "button_idx"), &ButtonArray::set_selected);
+ ClassDB::bind_method(D_METHOD("erase_button", "button_idx"), &ButtonArray::erase_button);
+ ClassDB::bind_method(D_METHOD("clear"), &ButtonArray::clear);
+
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ButtonArray::_gui_input);
+
+ BIND_CONSTANT(ALIGN_BEGIN);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_END);
+ BIND_CONSTANT(ALIGN_FILL);
+ BIND_CONSTANT(ALIGN_EXPAND_FILL);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
+
+ ADD_SIGNAL(MethodInfo("button_selected", PropertyInfo(Variant::INT, "button_idx")));
}
ButtonArray::ButtonArray(Orientation p_orientation) {
- orientation=p_orientation;
- selected=-1;
+ orientation = p_orientation;
+ selected = -1;
set_focus_mode(FOCUS_ALL);
- hover=-1;
- flat=false;
+ hover = -1;
+ flat = false;
min_button_size = -1;
}
diff --git a/scene/gui/button_array.h b/scene/gui/button_array.h
index 4865ef0373..dac130e79a 100644
--- a/scene/gui/button_array.h
+++ b/scene/gui/button_array.h
@@ -34,6 +34,7 @@
class ButtonArray : public Control {
GDCLASS(ButtonArray, Control);
+
public:
enum Align {
ALIGN_BEGIN,
@@ -42,8 +43,8 @@ public:
ALIGN_FILL,
ALIGN_EXPAND_FILL
};
-private:
+private:
Orientation orientation;
Align align;
@@ -64,19 +65,17 @@ private:
double min_button_size;
Vector<Button> buttons;
-protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
- void _gui_input(const InputEvent& p_event);
-
+ void _gui_input(const InputEvent &p_event);
void set_align(Align p_align);
Align get_align() const;
@@ -84,13 +83,12 @@ public:
void set_flat(bool p_flat);
bool is_flat() const;
- void add_button(const String& p_button,const String& p_tooltip="");
- void add_icon_button(const Ref<Texture>& p_icon,const String& p_button="",const String& p_tooltip="");
-
- void set_button_text(int p_button, const String& p_text);
- void set_button_tooltip(int p_button, const String& p_text);
- void set_button_icon(int p_button, const Ref<Texture>& p_icon);
+ void add_button(const String &p_button, const String &p_tooltip = "");
+ void add_icon_button(const Ref<Texture> &p_icon, const String &p_button = "", const String &p_tooltip = "");
+ void set_button_text(int p_button, const String &p_text);
+ void set_button_tooltip(int p_button, const String &p_text);
+ void set_button_icon(int p_button, const Ref<Texture> &p_icon);
String get_button_text(int p_button) const;
String get_button_tooltip(int p_button) const;
@@ -108,25 +106,25 @@ public:
virtual Size2 get_minimum_size() const;
virtual void get_translatable_strings(List<String> *p_strings) const;
- virtual String get_tooltip(const Point2& p_pos) const;
-
+ virtual String get_tooltip(const Point2 &p_pos) const;
- ButtonArray(Orientation p_orientation=HORIZONTAL);
+ ButtonArray(Orientation p_orientation = HORIZONTAL);
};
class HButtonArray : public ButtonArray {
- GDCLASS(HButtonArray,ButtonArray);
-public:
+ GDCLASS(HButtonArray, ButtonArray);
- HButtonArray() : ButtonArray(HORIZONTAL) {};
+public:
+ HButtonArray()
+ : ButtonArray(HORIZONTAL){};
};
class VButtonArray : public ButtonArray {
- GDCLASS(VButtonArray,ButtonArray);
-public:
+ GDCLASS(VButtonArray, ButtonArray);
- VButtonArray() : ButtonArray(VERTICAL) {};
+public:
+ VButtonArray()
+ : ButtonArray(VERTICAL){};
};
-
#endif // BUTTON_ARRAY_H
diff --git a/scene/gui/center_container.cpp b/scene/gui/center_container.cpp
index c1c04ced84..9cee8c0cc1 100644
--- a/scene/gui/center_container.cpp
+++ b/scene/gui/center_container.cpp
@@ -28,14 +28,12 @@
/*************************************************************************/
#include "center_container.h"
-
Size2 CenterContainer::get_minimum_size() const {
-
if (use_top_left)
return Size2();
Size2 ms;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -45,22 +43,17 @@ Size2 CenterContainer::get_minimum_size() const {
if (!c->is_visible())
continue;
Size2 minsize = c->get_combined_minimum_size();
- ms.width = MAX(ms.width , minsize.width);
- ms.height = MAX(ms.height , minsize.height);
-
-
+ ms.width = MAX(ms.width, minsize.width);
+ ms.height = MAX(ms.height, minsize.height);
}
return ms;
-
}
-
void CenterContainer::set_use_top_left(bool p_enable) {
- use_top_left=p_enable;
+ use_top_left = p_enable;
queue_sort();
-
}
bool CenterContainer::is_using_top_left() const {
@@ -68,13 +61,12 @@ bool CenterContainer::is_using_top_left() const {
return use_top_left;
}
-
void CenterContainer::_notification(int p_what) {
- if (p_what==NOTIFICATION_SORT_CHILDREN) {
+ if (p_what == NOTIFICATION_SORT_CHILDREN) {
Size2 size = get_size();
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -83,22 +75,21 @@ void CenterContainer::_notification(int p_what) {
continue;
Size2 minsize = c->get_combined_minimum_size();
- Point2 ofs = use_top_left ? (-minsize*0.5).floor() : ((size - minsize)/2.0).floor();
- fit_child_in_rect(c,Rect2(ofs,minsize));
-
+ Point2 ofs = use_top_left ? (-minsize * 0.5).floor() : ((size - minsize) / 2.0).floor();
+ fit_child_in_rect(c, Rect2(ofs, minsize));
}
}
}
void CenterContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_use_top_left","enable"),&CenterContainer::set_use_top_left);
- ClassDB::bind_method(D_METHOD("is_using_top_left"),&CenterContainer::is_using_top_left);
+ ClassDB::bind_method(D_METHOD("set_use_top_left", "enable"), &CenterContainer::set_use_top_left);
+ ClassDB::bind_method(D_METHOD("is_using_top_left"), &CenterContainer::is_using_top_left);
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"use_top_left"),"set_use_top_left","is_using_top_left");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_top_left"), "set_use_top_left", "is_using_top_left");
}
CenterContainer::CenterContainer() {
- use_top_left=false;
+ use_top_left = false;
}
diff --git a/scene/gui/center_container.h b/scene/gui/center_container.h
index 7acc14de19..c2deb823f1 100644
--- a/scene/gui/center_container.h
+++ b/scene/gui/center_container.h
@@ -29,20 +29,19 @@
#ifndef CENTER_CONTAINER_H
#define CENTER_CONTAINER_H
-
#include "scene/gui/container.h"
class CenterContainer : public Container {
- GDCLASS( CenterContainer, Container );
+ GDCLASS(CenterContainer, Container);
bool use_top_left;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_use_top_left(bool p_enable);
bool is_using_top_left() const;
diff --git a/scene/gui/check_box.cpp b/scene/gui/check_box.cpp
index c9803bc654..c7e2f4e7f9 100644
--- a/scene/gui/check_box.cpp
+++ b/scene/gui/check_box.cpp
@@ -28,46 +28,39 @@
/*************************************************************************/
#include "check_box.h"
-#include "servers/visual_server.h"
#include "button_group.h"
-
+#include "servers/visual_server.h"
void CheckBox::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
- RID ci = get_canvas_item();
+ RID ci = get_canvas_item();
- Ref<Texture> on=Control::get_icon(is_radio() ? "radio_checked" : "checked");
- Ref<Texture> off=Control::get_icon(is_radio() ? "radio_unchecked" : "unchecked");
+ Ref<Texture> on = Control::get_icon(is_radio() ? "radio_checked" : "checked");
+ Ref<Texture> off = Control::get_icon(is_radio() ? "radio_unchecked" : "unchecked");
- Vector2 ofs;
- ofs.x = 0;
- ofs.y = int((get_size().height - on->get_height())/2);
+ Vector2 ofs;
+ ofs.x = 0;
+ ofs.y = int((get_size().height - on->get_height()) / 2);
- if (is_pressed())
- on->draw(ci,ofs);
- else
- off->draw(ci,ofs);
-
-
- }
+ if (is_pressed())
+ on->draw(ci, ofs);
+ else
+ off->draw(ci, ofs);
+ }
}
-bool CheckBox::is_radio()
-{
+bool CheckBox::is_radio() {
return get_button_group().is_valid();
}
-CheckBox::CheckBox(const String &p_text):
- Button(p_text)
-{
- set_toggle_mode(true);
- set_text_align(ALIGN_LEFT);
-
+CheckBox::CheckBox(const String &p_text)
+ : Button(p_text) {
+ set_toggle_mode(true);
+ set_text_align(ALIGN_LEFT);
}
-CheckBox::~CheckBox()
-{
+CheckBox::~CheckBox() {
}
diff --git a/scene/gui/check_box.h b/scene/gui/check_box.h
index 6a4893936f..9b682de177 100644
--- a/scene/gui/check_box.h
+++ b/scene/gui/check_box.h
@@ -29,27 +29,22 @@
#ifndef CHECK_BOX_H
#define CHECK_BOX_H
-
#include "scene/gui/button.h"
/**
@author Mariano Suligoy <marianognu.esyrpg@gmail.com>
*/
class CheckBox : public Button {
- GDCLASS( CheckBox, Button );
-
+ GDCLASS(CheckBox, Button);
protected:
- void _notification(int p_what);
-
- bool is_radio();
+ void _notification(int p_what);
+ bool is_radio();
public:
-
- CheckBox(const String& p_text=String());
- ~CheckBox();
-
+ CheckBox(const String &p_text = String());
+ ~CheckBox();
};
#endif
diff --git a/scene/gui/check_button.cpp b/scene/gui/check_button.cpp
index 6404f066e8..6b24e0889a 100644
--- a/scene/gui/check_button.cpp
+++ b/scene/gui/check_button.cpp
@@ -28,45 +28,34 @@
/*************************************************************************/
#include "check_button.h"
-#include "servers/visual_server.h"
#include "print_string.h"
-
+#include "servers/visual_server.h"
void CheckButton::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Ref<Texture> on=Control::get_icon("on");
- Ref<Texture> off=Control::get_icon("off");
+ Ref<Texture> on = Control::get_icon("on");
+ Ref<Texture> off = Control::get_icon("off");
Vector2 ofs;
ofs.x = get_size().width - on->get_width();
- ofs.y = int((get_size().height - on->get_height())/2);
+ ofs.y = int((get_size().height - on->get_height()) / 2);
if (is_pressed())
- on->draw(ci,ofs);
+ on->draw(ci, ofs);
else
- off->draw(ci,ofs);
-
-
+ off->draw(ci, ofs);
}
}
-
CheckButton::CheckButton() {
set_toggle_mode(true);
set_text_align(ALIGN_LEFT);
-
-
}
-
-CheckButton::~CheckButton()
-{
+CheckButton::~CheckButton() {
}
-
-
-
diff --git a/scene/gui/check_button.h b/scene/gui/check_button.h
index 1c5440a25d..adf210a1e1 100644
--- a/scene/gui/check_button.h
+++ b/scene/gui/check_button.h
@@ -29,24 +29,20 @@
#ifndef CHECK_BUTTON_H
#define CHECK_BUTTON_H
-
#include "scene/gui/button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class CheckButton : public Button {
- GDCLASS( CheckButton, Button );
-
+ GDCLASS(CheckButton, Button);
protected:
void _notification(int p_what);
public:
-
CheckButton();
~CheckButton();
-
};
#endif
diff --git a/scene/gui/color_picker.cpp b/scene/gui/color_picker.cpp
index d9da583bf5..0f982167bf 100644
--- a/scene/gui/color_picker.cpp
+++ b/scene/gui/color_picker.cpp
@@ -28,17 +28,15 @@
/*************************************************************************/
#include "color_picker.h"
-#include "scene/gui/separator.h"
-#include "scene/main/viewport.h"
-#include "os/os.h"
#include "os/input.h"
#include "os/keyboard.h"
-
+#include "os/os.h"
+#include "scene/gui/separator.h"
+#include "scene/main/viewport.h"
void ColorPicker::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_THEME_CHANGED: {
//sample->set_texture(get_icon("color_sample"));
@@ -50,8 +48,6 @@ void ColorPicker::_notification(int p_what) {
_update_color();
}
-
-
}
}
@@ -72,16 +68,15 @@ void ColorPicker::_update_controls() {
scroll[3]->hide();
labels[3]->hide();
}
-
}
-void ColorPicker::set_pick_color(const Color& p_color) {
+void ColorPicker::set_pick_color(const Color &p_color) {
- color=p_color;
+ color = p_color;
if (color != last_hsv) {
- h=color.get_h();
- s=color.get_s();
- v=color.get_v();
+ h = color.get_h();
+ s = color.get_s();
+ v = color.get_v();
last_hsv = color;
}
@@ -92,12 +87,11 @@ void ColorPicker::set_pick_color(const Color& p_color) {
uv_edit->get_child(0)->cast_to<Control>()->update();
w_edit->get_child(0)->cast_to<Control>()->update();
_update_color();
-
}
void ColorPicker::set_edit_alpha(bool p_show) {
- edit_alpha=p_show;
+ edit_alpha = p_show;
_update_controls();
if (!is_inside_tree())
@@ -117,19 +111,18 @@ void ColorPicker::_value_changed(double) {
if (updating)
return;
- for(int i=0;i<4;i++) {
- color.components[i] = scroll[i]->get_value()/(raw_mode_enabled?1.0:255.0);
+ for (int i = 0; i < 4; i++) {
+ color.components[i] = scroll[i]->get_value() / (raw_mode_enabled ? 1.0 : 255.0);
}
set_pick_color(color);
_update_text_value();
- emit_signal("color_changed",color);
-
+ emit_signal("color_changed", color);
}
-void ColorPicker::_html_entered(const String& p_html) {
+void ColorPicker::_html_entered(const String &p_html) {
if (updating)
return;
@@ -140,14 +133,14 @@ void ColorPicker::_html_entered(const String& p_html) {
return;
set_pick_color(color);
- emit_signal("color_changed",color);
+ emit_signal("color_changed", color);
}
void ColorPicker::_update_color() {
- updating=true;
+ updating = true;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
scroll[i]->set_max(255);
scroll[i]->set_step(0.01);
if (raw_mode_enabled) {
@@ -162,30 +155,29 @@ void ColorPicker::_update_color() {
_update_text_value();
sample->update();
- updating=false;
+ updating = false;
}
-void ColorPicker::_update_presets()
-{
- Size2 size=bt_add_preset->get_size();
- preset->set_custom_minimum_size(Size2(size.width*presets.size(),size.height));
+void ColorPicker::_update_presets() {
+ Size2 size = bt_add_preset->get_size();
+ preset->set_custom_minimum_size(Size2(size.width * presets.size(), size.height));
PoolVector<uint8_t> img;
- img.resize(size.x*presets.size()*size.y*3);
+ img.resize(size.x * presets.size() * size.y * 3);
{
- PoolVector<uint8_t>::Write w=img.write();
- for (int y=0;y<size.y;y++) {
- for (int x=0;x<size.x*presets.size();x++) {
- int ofs = (y*(size.x*presets.size())+x)*3;
- w[ofs+0]=uint8_t(CLAMP(presets[(int)x/size.x].r*255.0,0,255));
- w[ofs+1]=uint8_t(CLAMP(presets[(int)x/size.x].g*255.0,0,255));
- w[ofs+2]=uint8_t(CLAMP(presets[(int)x/size.x].b*255.0,0,255));
+ PoolVector<uint8_t>::Write w = img.write();
+ for (int y = 0; y < size.y; y++) {
+ for (int x = 0; x < size.x * presets.size(); x++) {
+ int ofs = (y * (size.x * presets.size()) + x) * 3;
+ w[ofs + 0] = uint8_t(CLAMP(presets[(int)x / size.x].r * 255.0, 0, 255));
+ w[ofs + 1] = uint8_t(CLAMP(presets[(int)x / size.x].g * 255.0, 0, 255));
+ w[ofs + 2] = uint8_t(CLAMP(presets[(int)x / size.x].b * 255.0, 0, 255));
}
}
}
- Image i(size.x*presets.size(),size.y, false, Image::FORMAT_RGB8,img);
+ Image i(size.x * presets.size(), size.y, false, Image::FORMAT_RGB8, img);
Ref<ImageTexture> t;
t.instance();
@@ -193,8 +185,7 @@ void ColorPicker::_update_presets()
preset->set_texture(t);
}
-void ColorPicker::_text_type_toggled()
-{
+void ColorPicker::_text_type_toggled() {
if (!get_tree()->is_editor_hint())
return;
text_is_constructor = !text_is_constructor;
@@ -213,25 +204,23 @@ Color ColorPicker::get_pick_color() const {
return color;
}
-void ColorPicker::add_preset(const Color &p_color)
-{
+void ColorPicker::add_preset(const Color &p_color) {
if (presets.find(p_color)) {
presets.move_to_back(presets.find(p_color));
} else {
presets.push_back(p_color);
}
_update_presets();
- if (presets.size()==10)
+ if (presets.size() == 10)
bt_add_preset->hide();
}
-
void ColorPicker::set_raw_mode(bool p_enabled) {
- if (raw_mode_enabled==p_enabled)
+ if (raw_mode_enabled == p_enabled)
return;
- raw_mode_enabled=p_enabled;
- if (btn_mode->is_pressed()!=p_enabled)
+ raw_mode_enabled = p_enabled;
+ if (btn_mode->is_pressed() != p_enabled)
btn_mode->set_pressed(p_enabled);
if (!is_inside_tree())
@@ -246,79 +235,77 @@ bool ColorPicker::is_raw_mode() const {
return raw_mode_enabled;
}
-
void ColorPicker::_update_text_value() {
if (text_is_constructor) {
- String t = "Color("+String::num(color.r)+","+String::num(color.g)+","+String::num(color.b);
- if (edit_alpha && color.a<1)
- t+=(","+String::num(color.a)+")") ;
+ String t = "Color(" + String::num(color.r) + "," + String::num(color.g) + "," + String::num(color.b);
+ if (edit_alpha && color.a < 1)
+ t += ("," + String::num(color.a) + ")");
else
- t+=")";
+ t += ")";
c_text->set_text(t);
} else {
- c_text->set_text(color.to_html(edit_alpha && color.a<1));
+ c_text->set_text(color.to_html(edit_alpha && color.a < 1));
}
}
void ColorPicker::_sample_draw() {
- sample->draw_rect(Rect2(Point2(),Size2(256,20)),color);
+ sample->draw_rect(Rect2(Point2(), Size2(256, 20)), color);
}
-void ColorPicker::_hsv_draw(int p_wich,Control* c)
-{
+void ColorPicker::_hsv_draw(int p_wich, Control *c) {
if (!c)
return;
- if (p_wich==0) {
+ if (p_wich == 0) {
Vector<Point2> points;
points.push_back(Vector2());
- points.push_back(Vector2(c->get_size().x,0));
+ points.push_back(Vector2(c->get_size().x, 0));
points.push_back(c->get_size());
- points.push_back(Vector2(0,c->get_size().y));
+ points.push_back(Vector2(0, c->get_size().y));
Vector<Color> colors;
- colors.push_back(Color(1,1,1));
- colors.push_back(Color(1,1,1));
+ colors.push_back(Color(1, 1, 1));
+ colors.push_back(Color(1, 1, 1));
colors.push_back(Color());
colors.push_back(Color());
- c->draw_polygon(points,colors);
+ c->draw_polygon(points, colors);
Vector<Color> colors2;
Color col = color;
- col.set_hsv(color.get_h(),1,1);
+ col.set_hsv(color.get_h(), 1, 1);
col.a = 0;
colors2.push_back(col);
col.a = 1;
colors2.push_back(col);
- col.set_hsv(color.get_h(),1,0);
+ col.set_hsv(color.get_h(), 1, 0);
colors2.push_back(col);
col.a = 0;
colors2.push_back(col);
- c->draw_polygon(points,colors);
+ c->draw_polygon(points, colors);
int x = CLAMP(c->get_size().x * s, 0, c->get_size().x);
- int y = CLAMP(c->get_size().y-c->get_size().y * v, 0, c->get_size().y);
+ int y = CLAMP(c->get_size().y - c->get_size().y * v, 0, c->get_size().y);
col = color;
- col.a=1;
- c->draw_line(Point2(x,0),Point2(x,c->get_size().y),col.inverted());
- c->draw_line(Point2(0, y),Point2(c->get_size().x, y),col.inverted());
- c->draw_line(Point2(x,y),Point2(x,y),Color(1,1,1),2);
- } else if (p_wich==1) {
- Ref<Texture> hue = get_icon("color_hue","ColorPicker");
- c->draw_texture_rect(hue,Rect2(Point2(),c->get_size()));
- int y=c->get_size().y-c->get_size().y*h;
- Color col=Color();
- col.set_hsv(h,1,1);
- c->draw_line(Point2(0,y),Point2(c->get_size().x,y),col.inverted());
+ col.a = 1;
+ c->draw_line(Point2(x, 0), Point2(x, c->get_size().y), col.inverted());
+ c->draw_line(Point2(0, y), Point2(c->get_size().x, y), col.inverted());
+ c->draw_line(Point2(x, y), Point2(x, y), Color(1, 1, 1), 2);
+ } else if (p_wich == 1) {
+ Ref<Texture> hue = get_icon("color_hue", "ColorPicker");
+ c->draw_texture_rect(hue, Rect2(Point2(), c->get_size()));
+ int y = c->get_size().y - c->get_size().y * h;
+ Color col = Color();
+ col.set_hsv(h, 1, 1);
+ c->draw_line(Point2(0, y), Point2(c->get_size().x, y), col.inverted());
}
}
void ColorPicker::_uv_input(const InputEvent &ev) {
if (ev.type == InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &bev = ev.mouse_button;
- if (bev.pressed && bev.button_index==BUTTON_LEFT) {
+ if (bev.pressed && bev.button_index == BUTTON_LEFT) {
changing_color = true;
- float x = CLAMP((float)bev.x,0,256);
- float y = CLAMP((float)bev.y,0,256);
- s=x/256;
- v=1.0-y/256.0;
- color.set_hsv(h,s,v,color.a);
+ float x = CLAMP((float)bev.x, 0, 256);
+ float y = CLAMP((float)bev.y, 0, 256);
+ s = x / 256;
+ v = 1.0 - y / 256.0;
+ color.set_hsv(h, s, v, color.a);
last_hsv = color;
set_pick_color(color);
_update_color();
@@ -330,11 +317,11 @@ void ColorPicker::_uv_input(const InputEvent &ev) {
const InputEventMouse &bev = ev.mouse_motion;
if (!changing_color)
return;
- float x = CLAMP((float)bev.x,0,256);
- float y = CLAMP((float)bev.y,0,256);
- s=x/256;
- v=1.0-y/256.0;
- color.set_hsv(h,s,v,color.a);
+ float x = CLAMP((float)bev.x, 0, 256);
+ float y = CLAMP((float)bev.y, 0, 256);
+ s = x / 256;
+ v = 1.0 - y / 256.0;
+ color.set_hsv(h, s, v, color.a);
last_hsv = color;
set_pick_color(color);
_update_color();
@@ -345,14 +332,14 @@ void ColorPicker::_uv_input(const InputEvent &ev) {
void ColorPicker::_w_input(const InputEvent &ev) {
if (ev.type == InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &bev = ev.mouse_button;
- if (bev.pressed && bev.button_index==BUTTON_LEFT) {
+ if (bev.pressed && bev.button_index == BUTTON_LEFT) {
changing_color = true;
- h=1-((float)bev.y)/256.0;
+ h = 1 - ((float)bev.y) / 256.0;
} else {
changing_color = false;
}
- color.set_hsv(h,s,v,color.a);
+ color.set_hsv(h, s, v, color.a);
last_hsv = color;
set_pick_color(color);
_update_color();
@@ -361,9 +348,9 @@ void ColorPicker::_w_input(const InputEvent &ev) {
const InputEventMouse &bev = ev.mouse_motion;
if (!changing_color)
return;
- float y = CLAMP((float)bev.y,0,256);
- h=1.0-y/256.0;
- color.set_hsv(h,s,v,color.a);
+ float y = CLAMP((float)bev.y, 0, 256);
+ h = 1.0 - y / 256.0;
+ color.set_hsv(h, s, v, color.a);
last_hsv = color;
set_pick_color(color);
_update_color();
@@ -374,11 +361,11 @@ void ColorPicker::_w_input(const InputEvent &ev) {
void ColorPicker::_preset_input(const InputEvent &ev) {
if (ev.type == InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &bev = ev.mouse_button;
- if (bev.pressed && bev.button_index==BUTTON_LEFT) {
- int index = bev.x/(preset->get_size().x/presets.size());
+ if (bev.pressed && bev.button_index == BUTTON_LEFT) {
+ int index = bev.x / (preset->get_size().x / presets.size());
set_pick_color(presets[index]);
- } else if (bev.pressed && bev.button_index==BUTTON_RIGHT) {
- int index = bev.x/(preset->get_size().x/presets.size());
+ } else if (bev.pressed && bev.button_index == BUTTON_RIGHT) {
+ int index = bev.x / (preset->get_size().x / presets.size());
presets.erase(presets[index]);
_update_presets();
bt_add_preset->show();
@@ -388,42 +375,41 @@ void ColorPicker::_preset_input(const InputEvent &ev) {
} else if (ev.type == InputEvent::MOUSE_MOTION) {
const InputEventMouse &mev = ev.mouse_motion;
int index = mev.x * presets.size();
- if( preset->get_size().x != 0 ) {
+ if (preset->get_size().x != 0) {
index /= preset->get_size().x;
}
- if (index<0 || index >= presets.size())
+ if (index < 0 || index >= presets.size())
return;
- preset->set_tooltip("Color: #"+presets[index].to_html(presets[index].a<1)+"\n"
- "LMB: Set color\n"
- "RMB: Remove preset");
+ preset->set_tooltip("Color: #" + presets[index].to_html(presets[index].a < 1) + "\n"
+ "LMB: Set color\n"
+ "RMB: Remove preset");
}
}
-void ColorPicker::_screen_input(const InputEvent &ev)
-{
- if (ev.type==InputEvent::MOUSE_BUTTON) {
+void ColorPicker::_screen_input(const InputEvent &ev) {
+ if (ev.type == InputEvent::MOUSE_BUTTON) {
const InputEventMouseButton &bev = ev.mouse_button;
- if (bev.button_index==BUTTON_LEFT&&!bev.pressed) {
+ if (bev.button_index == BUTTON_LEFT && !bev.pressed) {
emit_signal("color_changed", color);
screen->hide();
}
- } else if (ev.type==InputEvent::MOUSE_MOTION) {
+ } else if (ev.type == InputEvent::MOUSE_MOTION) {
const InputEventMouse &mev = ev.mouse_motion;
- Viewport *r=get_tree()->get_root();
- if (!r->get_visible_rect().has_point(Point2(mev.global_x,mev.global_y)))
+ Viewport *r = get_tree()->get_root();
+ if (!r->get_visible_rect().has_point(Point2(mev.global_x, mev.global_y)))
return;
- Image img =r->get_screen_capture();
+ Image img = r->get_screen_capture();
if (!img.empty()) {
- last_capture=img;
+ last_capture = img;
r->queue_screen_capture();
}
if (!last_capture.empty()) {
- int pw = last_capture.get_format()==Image::FORMAT_RGBA8?4:3;
- int ofs = (mev.global_y*last_capture.get_width()+mev.global_x)*pw;
+ int pw = last_capture.get_format() == Image::FORMAT_RGBA8 ? 4 : 3;
+ int ofs = (mev.global_y * last_capture.get_width() + mev.global_x) * pw;
PoolVector<uint8_t>::Read r = last_capture.get_data().read();
- Color c( r[ofs+0]/255.0, r[ofs+1]/255.0, r[ofs+2]/255.0 );
+ Color c(r[ofs + 0] / 255.0, r[ofs + 1] / 255.0, r[ofs + 2] / 255.0);
set_pick_color(c);
}
@@ -434,15 +420,14 @@ void ColorPicker::_add_preset_pressed() {
add_preset(color);
}
-void ColorPicker::_screen_pick_pressed()
-{
- Viewport *r=get_tree()->get_root();
+void ColorPicker::_screen_pick_pressed() {
+ Viewport *r = get_tree()->get_root();
if (!screen) {
- screen=memnew( Control );
+ screen = memnew(Control);
r->add_child(screen);
screen->set_as_toplevel(true);
screen->set_area_as_parent_rect();
- screen->connect("gui_input",this,"_screen_input");
+ screen->connect("gui_input", this, "_screen_input");
}
screen->raise();
screen->show_modal();
@@ -451,199 +436,182 @@ void ColorPicker::_screen_pick_pressed()
void ColorPicker::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_pick_color","color"),&ColorPicker::set_pick_color);
- ClassDB::bind_method(D_METHOD("get_pick_color"),&ColorPicker::get_pick_color);
- ClassDB::bind_method(D_METHOD("set_raw_mode","mode"),&ColorPicker::set_raw_mode);
- ClassDB::bind_method(D_METHOD("is_raw_mode"),&ColorPicker::is_raw_mode);
- ClassDB::bind_method(D_METHOD("set_edit_alpha","show"),&ColorPicker::set_edit_alpha);
- ClassDB::bind_method(D_METHOD("is_editing_alpha"),&ColorPicker::is_editing_alpha);
+ ClassDB::bind_method(D_METHOD("set_pick_color", "color"), &ColorPicker::set_pick_color);
+ ClassDB::bind_method(D_METHOD("get_pick_color"), &ColorPicker::get_pick_color);
+ ClassDB::bind_method(D_METHOD("set_raw_mode", "mode"), &ColorPicker::set_raw_mode);
+ ClassDB::bind_method(D_METHOD("is_raw_mode"), &ColorPicker::is_raw_mode);
+ ClassDB::bind_method(D_METHOD("set_edit_alpha", "show"), &ColorPicker::set_edit_alpha);
+ ClassDB::bind_method(D_METHOD("is_editing_alpha"), &ColorPicker::is_editing_alpha);
ClassDB::bind_method(D_METHOD("add_preset"), &ColorPicker::add_preset);
- ClassDB::bind_method(D_METHOD("_value_changed"),&ColorPicker::_value_changed);
- ClassDB::bind_method(D_METHOD("_html_entered"),&ColorPicker::_html_entered);
- ClassDB::bind_method(D_METHOD("_text_type_toggled"),&ColorPicker::_text_type_toggled);
+ ClassDB::bind_method(D_METHOD("_value_changed"), &ColorPicker::_value_changed);
+ ClassDB::bind_method(D_METHOD("_html_entered"), &ColorPicker::_html_entered);
+ ClassDB::bind_method(D_METHOD("_text_type_toggled"), &ColorPicker::_text_type_toggled);
ClassDB::bind_method(D_METHOD("_add_preset_pressed"), &ColorPicker::_add_preset_pressed);
ClassDB::bind_method(D_METHOD("_screen_pick_pressed"), &ColorPicker::_screen_pick_pressed);
- ClassDB::bind_method(D_METHOD("_sample_draw"),&ColorPicker::_sample_draw);
- ClassDB::bind_method(D_METHOD("_hsv_draw"),&ColorPicker::_hsv_draw);
- ClassDB::bind_method(D_METHOD("_uv_input"),&ColorPicker::_uv_input);
- ClassDB::bind_method(D_METHOD("_w_input"),&ColorPicker::_w_input);
- ClassDB::bind_method(D_METHOD("_preset_input"),&ColorPicker::_preset_input);
- ClassDB::bind_method(D_METHOD("_screen_input"),&ColorPicker::_screen_input);
+ ClassDB::bind_method(D_METHOD("_sample_draw"), &ColorPicker::_sample_draw);
+ ClassDB::bind_method(D_METHOD("_hsv_draw"), &ColorPicker::_hsv_draw);
+ ClassDB::bind_method(D_METHOD("_uv_input"), &ColorPicker::_uv_input);
+ ClassDB::bind_method(D_METHOD("_w_input"), &ColorPicker::_w_input);
+ ClassDB::bind_method(D_METHOD("_preset_input"), &ColorPicker::_preset_input);
+ ClassDB::bind_method(D_METHOD("_screen_input"), &ColorPicker::_screen_input);
- ADD_SIGNAL( MethodInfo("color_changed",PropertyInfo(Variant::COLOR,"color")));
+ ADD_SIGNAL(MethodInfo("color_changed", PropertyInfo(Variant::COLOR, "color")));
}
-ColorPicker::ColorPicker() :
- BoxContainer(true) {
+ColorPicker::ColorPicker()
+ : BoxContainer(true) {
- updating=true;
- edit_alpha=true;
+ updating = true;
+ edit_alpha = true;
text_is_constructor = false;
- raw_mode_enabled=false;
- changing_color=false;
- screen=NULL;
+ raw_mode_enabled = false;
+ changing_color = false;
+ screen = NULL;
- HBoxContainer *hb_smpl = memnew( HBoxContainer );
- btn_pick = memnew( ToolButton );
- btn_pick->connect("pressed",this,"_screen_pick_pressed");
+ HBoxContainer *hb_smpl = memnew(HBoxContainer);
+ btn_pick = memnew(ToolButton);
+ btn_pick->connect("pressed", this, "_screen_pick_pressed");
- sample = memnew( TextureRect );
+ sample = memnew(TextureRect);
sample->set_h_size_flags(SIZE_EXPAND_FILL);
- sample->connect("draw",this,"_sample_draw");
+ sample->connect("draw", this, "_sample_draw");
hb_smpl->add_child(sample);
hb_smpl->add_child(btn_pick);
add_child(hb_smpl);
- HBoxContainer *hb_edit = memnew( HBoxContainer );
-
- uv_edit= memnew ( Control );
-
-
+ HBoxContainer *hb_edit = memnew(HBoxContainer);
+ uv_edit = memnew(Control);
uv_edit->connect("gui_input", this, "_uv_input");
uv_edit->set_mouse_filter(MOUSE_FILTER_PASS);
- uv_edit->set_custom_minimum_size(Size2 (256,256));
- Vector<Variant> args=Vector<Variant>();
+ uv_edit->set_custom_minimum_size(Size2(256, 256));
+ Vector<Variant> args = Vector<Variant>();
args.push_back(0);
args.push_back(uv_edit);
- uv_edit->connect("draw",this,"_hsv_draw",args);
+ uv_edit->connect("draw", this, "_hsv_draw", args);
add_child(hb_edit);
- w_edit= memnew( Control );
+ w_edit = memnew(Control);
//w_edit->set_ignore_mouse(false);
- w_edit->set_custom_minimum_size(Size2(30,256));
+ w_edit->set_custom_minimum_size(Size2(30, 256));
w_edit->connect("gui_input", this, "_w_input");
args.clear();
args.push_back(1);
args.push_back(w_edit);
- w_edit->connect("draw",this,"_hsv_draw",args);
-
+ w_edit->connect("draw", this, "_hsv_draw", args);
hb_edit->add_child(uv_edit);
- hb_edit->add_child(memnew( VSeparator ));
+ hb_edit->add_child(memnew(VSeparator));
hb_edit->add_child(w_edit);
- VBoxContainer *vbl = memnew( VBoxContainer );
+ VBoxContainer *vbl = memnew(VBoxContainer);
add_child(vbl);
- add_child(memnew( HSeparator ));
+ add_child(memnew(HSeparator));
- VBoxContainer *vbr = memnew( VBoxContainer );
+ VBoxContainer *vbr = memnew(VBoxContainer);
add_child(vbr);
vbr->set_h_size_flags(SIZE_EXPAND_FILL);
- const char* lt[4] = {"R","G","B","A"};
+ const char *lt[4] = { "R", "G", "B", "A" };
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- HBoxContainer *hbc = memnew( HBoxContainer );
+ HBoxContainer *hbc = memnew(HBoxContainer);
- labels[i]=memnew( Label(lt[i]) );
+ labels[i] = memnew(Label(lt[i]));
hbc->add_child(labels[i]);
- scroll[i]=memnew( HSlider );
+ scroll[i] = memnew(HSlider);
hbc->add_child(scroll[i]);
- values[i]=memnew( SpinBox );
+ values[i] = memnew(SpinBox);
scroll[i]->share(values[i]);
hbc->add_child(values[i]);
-
scroll[i]->set_min(0);
scroll[i]->set_page(0);
scroll[i]->set_h_size_flags(SIZE_EXPAND_FILL);
- scroll[i]->connect("value_changed",this,"_value_changed");
+ scroll[i]->connect("value_changed", this, "_value_changed");
vbr->add_child(hbc);
-
}
- HBoxContainer *hhb = memnew( HBoxContainer );
+ HBoxContainer *hhb = memnew(HBoxContainer);
- btn_mode = memnew( CheckButton );
+ btn_mode = memnew(CheckButton);
btn_mode->set_text("RAW Mode");
btn_mode->connect("toggled", this, "set_raw_mode");
hhb->add_child(btn_mode);
vbr->add_child(hhb);
- text_type = memnew( Button );
+ text_type = memnew(Button);
text_type->set_flat(true);
text_type->connect("pressed", this, "_text_type_toggled");
hhb->add_child(text_type);
- c_text = memnew( LineEdit );
+ c_text = memnew(LineEdit);
hhb->add_child(c_text);
- c_text->connect("text_entered",this,"_html_entered");
+ c_text->connect("text_entered", this, "_html_entered");
text_type->set_text("#");
c_text->set_h_size_flags(SIZE_EXPAND_FILL);
-
_update_controls();
//_update_color();
- updating=false;
-
- set_pick_color(Color(1,1,1));
+ updating = false;
+ set_pick_color(Color(1, 1, 1));
- HBoxContainer *bbc = memnew( HBoxContainer );
+ HBoxContainer *bbc = memnew(HBoxContainer);
add_child(bbc);
- preset = memnew( TextureRect );
+ preset = memnew(TextureRect);
bbc->add_child(preset);
//preset->set_ignore_mouse(false);
preset->connect("gui_input", this, "_preset_input");
- bt_add_preset = memnew ( Button );
+ bt_add_preset = memnew(Button);
bt_add_preset->set_icon(get_icon("add_preset"));
bt_add_preset->set_tooltip("Add current color as a preset");
bt_add_preset->connect("pressed", this, "_add_preset_pressed");
bbc->add_child(bt_add_preset);
}
-
-
-
/////////////////
-
-void ColorPickerButton::_color_changed(const Color& p_color) {
+void ColorPickerButton::_color_changed(const Color &p_color) {
update();
- emit_signal("color_changed",p_color);
+ emit_signal("color_changed", p_color);
}
-
void ColorPickerButton::pressed() {
- Size2 ms = Size2(300, picker->get_combined_minimum_size().height+10);
- popup->set_pos(get_global_pos()-Size2(0,ms.height));
+ Size2 ms = Size2(300, picker->get_combined_minimum_size().height + 10);
+ popup->set_pos(get_global_pos() - Size2(0, ms.height));
popup->set_size(ms);
popup->popup();
picker->set_focus_on_line_edit();
-
-
}
void ColorPickerButton::_notification(int p_what) {
+ if (p_what == NOTIFICATION_DRAW) {
- if (p_what==NOTIFICATION_DRAW) {
-
- Ref<StyleBox> normal = get_stylebox("normal" );
- draw_rect(Rect2(normal->get_offset(),get_size()-normal->get_minimum_size()),picker->get_pick_color());
+ Ref<StyleBox> normal = get_stylebox("normal");
+ draw_rect(Rect2(normal->get_offset(), get_size() - normal->get_minimum_size()), picker->get_pick_color());
}
}
-void ColorPickerButton::set_pick_color(const Color& p_color){
-
+void ColorPickerButton::set_pick_color(const Color &p_color) {
picker->set_pick_color(p_color);
update();
- emit_signal("color_changed",p_color);
+ emit_signal("color_changed", p_color);
}
-Color ColorPickerButton::get_pick_color() const{
+Color ColorPickerButton::get_pick_color() const {
return picker->get_pick_color();
}
@@ -653,37 +621,35 @@ void ColorPickerButton::set_edit_alpha(bool p_show) {
picker->set_edit_alpha(p_show);
}
-bool ColorPickerButton::is_editing_alpha() const{
+bool ColorPickerButton::is_editing_alpha() const {
return picker->is_editing_alpha();
-
}
ColorPicker *ColorPickerButton::get_picker() {
return picker;
}
-void ColorPickerButton::_bind_methods(){
-
- ClassDB::bind_method(D_METHOD("set_pick_color","color"),&ColorPickerButton::set_pick_color);
- ClassDB::bind_method(D_METHOD("get_pick_color"),&ColorPickerButton::get_pick_color);
- ClassDB::bind_method(D_METHOD("get_picker:ColorPicker"),&ColorPickerButton::get_picker);
- ClassDB::bind_method(D_METHOD("set_edit_alpha","show"),&ColorPickerButton::set_edit_alpha);
- ClassDB::bind_method(D_METHOD("is_editing_alpha"),&ColorPickerButton::is_editing_alpha);
- ClassDB::bind_method(D_METHOD("_color_changed"),&ColorPickerButton::_color_changed);
+void ColorPickerButton::_bind_methods() {
- ADD_SIGNAL( MethodInfo("color_changed",PropertyInfo(Variant::COLOR,"color")));
- ADD_PROPERTY( PropertyInfo(Variant::COLOR,"color"),"set_pick_color","get_pick_color") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"edit_alpha"),"set_edit_alpha","is_editing_alpha") ;
+ ClassDB::bind_method(D_METHOD("set_pick_color", "color"), &ColorPickerButton::set_pick_color);
+ ClassDB::bind_method(D_METHOD("get_pick_color"), &ColorPickerButton::get_pick_color);
+ ClassDB::bind_method(D_METHOD("get_picker:ColorPicker"), &ColorPickerButton::get_picker);
+ ClassDB::bind_method(D_METHOD("set_edit_alpha", "show"), &ColorPickerButton::set_edit_alpha);
+ ClassDB::bind_method(D_METHOD("is_editing_alpha"), &ColorPickerButton::is_editing_alpha);
+ ClassDB::bind_method(D_METHOD("_color_changed"), &ColorPickerButton::_color_changed);
+ ADD_SIGNAL(MethodInfo("color_changed", PropertyInfo(Variant::COLOR, "color")));
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_pick_color", "get_pick_color");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "edit_alpha"), "set_edit_alpha", "is_editing_alpha");
}
ColorPickerButton::ColorPickerButton() {
- popup = memnew( PopupPanel );
- picker = memnew( ColorPicker );
+ popup = memnew(PopupPanel);
+ picker = memnew(ColorPicker);
popup->add_child(picker);
- picker->connect("color_changed",this,"_color_changed");
+ picker->connect("color_changed", this, "_color_changed");
add_child(popup);
}
diff --git a/scene/gui/color_picker.h b/scene/gui/color_picker.h
index d9db9c89f7..bd1abeecbe 100644
--- a/scene/gui/color_picker.h
+++ b/scene/gui/color_picker.h
@@ -29,23 +29,22 @@
#ifndef COLOR_PICKER_H
#define COLOR_PICKER_H
-#include "scene/gui/slider.h"
-#include "scene/gui/line_edit.h"
-#include "scene/gui/spin_box.h"
-#include "scene/gui/label.h"
+#include "scene/gui/box_container.h"
#include "scene/gui/button.h"
+#include "scene/gui/check_button.h"
+#include "scene/gui/label.h"
+#include "scene/gui/line_edit.h"
#include "scene/gui/popup.h"
-#include "scene/gui/box_container.h"
+#include "scene/gui/slider.h"
+#include "scene/gui/spin_box.h"
#include "scene/gui/texture_rect.h"
#include "scene/gui/tool_button.h"
-#include "scene/gui/check_button.h"
class ColorPicker : public BoxContainer {
- GDCLASS(ColorPicker,BoxContainer);
+ GDCLASS(ColorPicker, BoxContainer);
private:
-
Control *screen;
Image last_capture;
Control *uv_edit;
@@ -69,10 +68,10 @@ private:
bool raw_mode_enabled;
bool updating;
bool changing_color;
- float h,s,v;
+ float h, s, v;
Color last_hsv;
- void _html_entered(const String& p_html);
+ void _html_entered(const String &p_html);
void _value_changed(double);
void _update_controls();
void _update_color();
@@ -80,28 +79,27 @@ private:
void _update_text_value();
void _text_type_toggled();
void _sample_draw();
- void _hsv_draw(int p_wich,Control *c);
+ void _hsv_draw(int p_wich, Control *c);
- void _uv_input(const InputEvent& p_input);
- void _w_input(const InputEvent& p_input);
- void _preset_input(const InputEvent& p_input);
- void _screen_input(const InputEvent& p_input);
+ void _uv_input(const InputEvent &p_input);
+ void _w_input(const InputEvent &p_input);
+ void _preset_input(const InputEvent &p_input);
+ void _screen_input(const InputEvent &p_input);
void _add_preset_pressed();
void _screen_pick_pressed();
protected:
-
void _notification(int);
static void _bind_methods();
-public:
+public:
void set_edit_alpha(bool p_show);
bool is_editing_alpha() const;
- void set_pick_color(const Color& p_color);
+ void set_pick_color(const Color &p_color);
Color get_pick_color() const;
- void add_preset(const Color& p_color);
+ void add_preset(const Color &p_color);
void set_raw_mode(bool p_enabled);
bool is_raw_mode() const;
@@ -112,21 +110,20 @@ public:
class ColorPickerButton : public Button {
- GDCLASS(ColorPickerButton,Button);
+ GDCLASS(ColorPickerButton, Button);
PopupPanel *popup;
ColorPicker *picker;
- void _color_changed(const Color& p_color);
+ void _color_changed(const Color &p_color);
virtual void pressed();
protected:
-
void _notification(int);
static void _bind_methods();
-public:
- void set_pick_color(const Color& p_color);
+public:
+ void set_pick_color(const Color &p_color);
Color get_pick_color() const;
void set_edit_alpha(bool p_show);
diff --git a/scene/gui/color_ramp_edit.cpp b/scene/gui/color_ramp_edit.cpp
index 81bc5ca9bb..131638bb70 100644
--- a/scene/gui/color_ramp_edit.cpp
+++ b/scene/gui/color_ramp_edit.cpp
@@ -29,74 +29,72 @@
#include "color_ramp_edit.h"
#include "os/keyboard.h"
-ColorRampEdit::ColorRampEdit(){
- grabbed=-1;
- grabbing=false;
+ColorRampEdit::ColorRampEdit() {
+ grabbed = -1;
+ grabbing = false;
set_focus_mode(FOCUS_ALL);
- popup = memnew( PopupPanel );
- picker = memnew( ColorPicker );
+ popup = memnew(PopupPanel);
+ picker = memnew(ColorPicker);
popup->add_child(picker);
add_child(popup);
- checker = Ref<ImageTexture>(memnew( ImageTexture ));
- checker->create_from_image( Image(checker_bg_png),ImageTexture::FLAG_REPEAT );
+ checker = Ref<ImageTexture>(memnew(ImageTexture));
+ checker->create_from_image(Image(checker_bg_png), ImageTexture::FLAG_REPEAT);
}
int ColorRampEdit::_get_point_from_pos(int x) {
int result = -1;
- int total_w = get_size().width-get_size().height-3;
- for(int i=0;i<points.size();i++) {
+ int total_w = get_size().width - get_size().height - 3;
+ for (int i = 0; i < points.size(); i++) {
//Check if we clicked at point
- if (ABS(x-points[i].offset*total_w+1)<(POINT_WIDTH/2+1)) {
- result=i;
+ if (ABS(x - points[i].offset * total_w + 1) < (POINT_WIDTH / 2 + 1)) {
+ result = i;
}
}
return result;
}
void ColorRampEdit::_show_color_picker() {
- if (grabbed==-1)
+ if (grabbed == -1)
return;
- Size2 ms = Size2(350, picker->get_combined_minimum_size().height+10);
+ Size2 ms = Size2(350, picker->get_combined_minimum_size().height + 10);
picker->set_pick_color(points[grabbed].color);
- popup->set_pos(get_global_pos()-Vector2(ms.width-get_size().width,ms.height));
+ popup->set_pos(get_global_pos() - Vector2(ms.width - get_size().width, ms.height));
popup->set_size(ms);
popup->popup();
}
ColorRampEdit::~ColorRampEdit() {
-
}
-void ColorRampEdit::_gui_input(const InputEvent& p_event) {
+void ColorRampEdit::_gui_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && p_event.key.pressed && p_event.key.scancode==KEY_DELETE && grabbed!=-1) {
+ if (p_event.type == InputEvent::KEY && p_event.key.pressed && p_event.key.scancode == KEY_DELETE && grabbed != -1) {
points.remove(grabbed);
- grabbed=-1;
- grabbing=false;
+ grabbed = -1;
+ grabbing = false;
update();
emit_signal("ramp_changed");
accept_event();
}
//Show color picker on double click.
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.doubleclick && p_event.mouse_button.pressed) {
- grabbed=_get_point_from_pos(p_event.mouse_button.x);
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && p_event.mouse_button.doubleclick && p_event.mouse_button.pressed) {
+ grabbed = _get_point_from_pos(p_event.mouse_button.x);
_show_color_picker();
accept_event();
}
//Delete point on right click
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==2 && p_event.mouse_button.pressed) {
- grabbed=_get_point_from_pos(p_event.mouse_button.x);
- if(grabbed != -1)
- {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 2 && p_event.mouse_button.pressed) {
+ grabbed = _get_point_from_pos(p_event.mouse_button.x);
+ if (grabbed != -1) {
points.remove(grabbed);
- grabbed=-1;
- grabbing=false;
+ grabbed = -1;
+ grabbing = false;
update();
emit_signal("ramp_changed");
accept_event();
@@ -104,21 +102,21 @@ void ColorRampEdit::_gui_input(const InputEvent& p_event) {
}
//Hold alt key to duplicate selected color
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.pressed && p_event.key.mod.alt ) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && p_event.mouse_button.pressed && p_event.key.mod.alt) {
int x = p_event.mouse_button.x;
- grabbed=_get_point_from_pos(x);
+ grabbed = _get_point_from_pos(x);
- if( grabbed != -1 ) {
- int total_w = get_size().width-get_size().height-3;
+ if (grabbed != -1) {
+ int total_w = get_size().width - get_size().height - 3;
ColorRamp::Point newPoint = points[grabbed];
- newPoint.offset=CLAMP(x/float(total_w),0,1);
+ newPoint.offset = CLAMP(x / float(total_w), 0, 1);
points.push_back(newPoint);
points.sort();
- for(int i=0;i<points.size();++i) {
- if (points[i].offset==newPoint.offset) {
- grabbed=i;
+ for (int i = 0; i < points.size(); ++i) {
+ if (points[i].offset == newPoint.offset) {
+ grabbed = i;
break;
}
}
@@ -128,91 +126,89 @@ void ColorRampEdit::_gui_input(const InputEvent& p_event) {
}
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && p_event.mouse_button.pressed) {
update();
int x = p_event.mouse_button.x;
- int total_w = get_size().width-get_size().height-3;
+ int total_w = get_size().width - get_size().height - 3;
//Check if color selector was clicked.
- if (x>total_w+3) {
+ if (x > total_w + 3) {
_show_color_picker();
return;
}
- grabbing=true;
+ grabbing = true;
- grabbed=_get_point_from_pos(x);
+ grabbed = _get_point_from_pos(x);
//grab or select
- if (grabbed!=-1) {
+ if (grabbed != -1) {
return;
}
//insert
ColorRamp::Point newPoint;
- newPoint.offset=CLAMP(x/float(total_w),0,1);
+ newPoint.offset = CLAMP(x / float(total_w), 0, 1);
ColorRamp::Point prev;
ColorRamp::Point next;
- int pos=-1;
- for(int i=0;i<points.size();i++) {
- if (points[i].offset<newPoint.offset)
- pos=i;
+ int pos = -1;
+ for (int i = 0; i < points.size(); i++) {
+ if (points[i].offset < newPoint.offset)
+ pos = i;
}
- if (pos==-1) {
+ if (pos == -1) {
- prev.color=Color(0,0,0);
- prev.offset=0;
+ prev.color = Color(0, 0, 0);
+ prev.offset = 0;
if (points.size()) {
- next=points[0];
+ next = points[0];
} else {
- next.color=Color(1,1,1);
- next.offset=1.0;
+ next.color = Color(1, 1, 1);
+ next.offset = 1.0;
}
- } else {
+ } else {
- if (pos==points.size()-1) {
- next.color=Color(1,1,1);
- next.offset=1.0;
+ if (pos == points.size() - 1) {
+ next.color = Color(1, 1, 1);
+ next.offset = 1.0;
} else {
- next=points[pos+1];
+ next = points[pos + 1];
}
- prev=points[pos];
-
+ prev = points[pos];
}
- newPoint.color=prev.color.linear_interpolate(next.color,(newPoint.offset-prev.offset)/(next.offset-prev.offset));
+ newPoint.color = prev.color.linear_interpolate(next.color, (newPoint.offset - prev.offset) / (next.offset - prev.offset));
points.push_back(newPoint);
points.sort();
- for(int i=0;i<points.size();i++) {
- if (points[i].offset==newPoint.offset) {
- grabbed=i;
+ for (int i = 0; i < points.size(); i++) {
+ if (points[i].offset == newPoint.offset) {
+ grabbed = i;
break;
}
}
emit_signal("ramp_changed");
-
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==1 && !p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == 1 && !p_event.mouse_button.pressed) {
if (grabbing) {
- grabbing=false;
+ grabbing = false;
emit_signal("ramp_changed");
}
update();
}
- if (p_event.type==InputEvent::MOUSE_MOTION && grabbing) {
+ if (p_event.type == InputEvent::MOUSE_MOTION && grabbing) {
- int total_w = get_size().width-get_size().height-3;
+ int total_w = get_size().width - get_size().height - 3;
int x = p_event.mouse_motion.x;
- float newofs = CLAMP(x/float(total_w),0,1);
+ float newofs = CLAMP(x / float(total_w), 0, 1);
//Snap to nearest point if holding shift
if (p_event.key.mod.shift) {
@@ -220,7 +216,7 @@ void ColorRampEdit::_gui_input(const InputEvent& p_event) {
float smallest_ofs = snap_treshhold;
bool founded = false;
int nearest_point;
- for(int i=0;i<points.size();++i) {
+ for (int i = 0; i < points.size(); ++i) {
if (i != grabbed) {
float temp_ofs = ABS(points[i].offset - newofs);
if (temp_ofs < smallest_ofs) {
@@ -234,30 +230,30 @@ void ColorRampEdit::_gui_input(const InputEvent& p_event) {
}
if (founded) {
if (points[nearest_point].offset < newofs)
- newofs = points[nearest_point].offset+0.00001;
+ newofs = points[nearest_point].offset + 0.00001;
else
- newofs = points[nearest_point].offset-0.00001;
- newofs = CLAMP(newofs,0,1);
+ newofs = points[nearest_point].offset - 0.00001;
+ newofs = CLAMP(newofs, 0, 1);
}
}
- bool valid=true;
- for(int i=0;i<points.size();i++) {
+ bool valid = true;
+ for (int i = 0; i < points.size(); i++) {
- if (points[i].offset==newofs && i!=grabbed) {
- valid=false;
+ if (points[i].offset == newofs && i != grabbed) {
+ valid = false;
}
}
if (!valid)
return;
- points[grabbed].offset=newofs;
+ points[grabbed].offset = newofs;
points.sort();
- for(int i=0;i<points.size();i++) {
- if (points[i].offset==newofs) {
- grabbed=i;
+ for (int i = 0; i < points.size(); i++) {
+ if (points[i].offset == newofs) {
+ grabbed = i;
break;
}
}
@@ -270,12 +266,12 @@ void ColorRampEdit::_gui_input(const InputEvent& p_event) {
void ColorRampEdit::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
- if (!picker->is_connected("color_changed",this,"_color_changed")) {
- picker->connect("color_changed",this,"_color_changed");
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+ if (!picker->is_connected("color_changed", this, "_color_changed")) {
+ picker->connect("color_changed", this, "_color_changed");
}
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
int w = get_size().x;
int h = get_size().y;
@@ -283,89 +279,86 @@ void ColorRampEdit::_notification(int p_what) {
if (w == 0 || h == 0)
return; //Safety check. We have division by 'h'. And in any case there is nothing to draw with such size
- int total_w = get_size().width-get_size().height-3;
+ int total_w = get_size().width - get_size().height - 3;
//Draw checker pattern for ramp
- _draw_checker(0,0, total_w, h);
+ _draw_checker(0, 0, total_w, h);
//Draw color ramp
ColorRamp::Point prev;
- prev.offset=0;
- if(points.size() == 0)
- prev.color=Color(0,0,0); //Draw black rectangle if we have no points
+ prev.offset = 0;
+ if (points.size() == 0)
+ prev.color = Color(0, 0, 0); //Draw black rectangle if we have no points
else
- prev.color = points[0].color; //Extend color of first point to the beginning.
+ prev.color = points[0].color; //Extend color of first point to the beginning.
- for(int i=-1;i<points.size();i++) {
+ for (int i = -1; i < points.size(); i++) {
ColorRamp::Point next;
//If there is no next point
- if (i+1 == points.size()) {
- if(points.size() == 0)
- next.color=Color(0,0,0); //Draw black rectangle if we have no points
+ if (i + 1 == points.size()) {
+ if (points.size() == 0)
+ next.color = Color(0, 0, 0); //Draw black rectangle if we have no points
else
- next.color=points[i].color; //Extend color of last point to the end.
- next.offset=1;
+ next.color = points[i].color; //Extend color of last point to the end.
+ next.offset = 1;
} else {
- next=points[i+1];
+ next = points[i + 1];
}
- if (prev.offset==next.offset) {
- prev=next;
+ if (prev.offset == next.offset) {
+ prev = next;
continue;
}
Vector<Vector2> points;
Vector<Color> colors;
- points.push_back(Vector2(prev.offset*total_w,h));
- points.push_back(Vector2(prev.offset*total_w,0));
- points.push_back(Vector2(next.offset*total_w,0));
- points.push_back(Vector2(next.offset*total_w,h));
+ points.push_back(Vector2(prev.offset * total_w, h));
+ points.push_back(Vector2(prev.offset * total_w, 0));
+ points.push_back(Vector2(next.offset * total_w, 0));
+ points.push_back(Vector2(next.offset * total_w, h));
colors.push_back(prev.color);
colors.push_back(prev.color);
colors.push_back(next.color);
colors.push_back(next.color);
- draw_primitive(points,colors,Vector<Point2>());
- prev=next;
+ draw_primitive(points, colors, Vector<Point2>());
+ prev = next;
}
//Draw point markers
- for(int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
- Color col = i==grabbed?Color(1,0.0,0.0,0.9):points[i].color.contrasted();
+ Color col = i == grabbed ? Color(1, 0.0, 0.0, 0.9) : points[i].color.contrasted();
col.a = 0.9;
- draw_line(Vector2(points[i].offset*total_w,0),Vector2(points[i].offset*total_w,h/2),col);
- draw_rect(Rect2(points[i].offset*total_w-POINT_WIDTH/2, h/2, POINT_WIDTH, h/2), Color(0.6, 0.6, 0.6, i==grabbed?0.9:0.4));
- draw_line(Vector2(points[i].offset*total_w-POINT_WIDTH/2,h/2),Vector2(points[i].offset*total_w-POINT_WIDTH/2,h-1),col);
- draw_line(Vector2(points[i].offset*total_w+POINT_WIDTH/2,h/2),Vector2(points[i].offset*total_w+POINT_WIDTH/2,h-1),col);
- draw_line(Vector2(points[i].offset*total_w-POINT_WIDTH/2,h/2),Vector2(points[i].offset*total_w+POINT_WIDTH/2,h/2),col);
- draw_line(Vector2(points[i].offset*total_w-POINT_WIDTH/2,h-1),Vector2(points[i].offset*total_w+POINT_WIDTH/2,h-1),col);
-
+ draw_line(Vector2(points[i].offset * total_w, 0), Vector2(points[i].offset * total_w, h / 2), col);
+ draw_rect(Rect2(points[i].offset * total_w - POINT_WIDTH / 2, h / 2, POINT_WIDTH, h / 2), Color(0.6, 0.6, 0.6, i == grabbed ? 0.9 : 0.4));
+ draw_line(Vector2(points[i].offset * total_w - POINT_WIDTH / 2, h / 2), Vector2(points[i].offset * total_w - POINT_WIDTH / 2, h - 1), col);
+ draw_line(Vector2(points[i].offset * total_w + POINT_WIDTH / 2, h / 2), Vector2(points[i].offset * total_w + POINT_WIDTH / 2, h - 1), col);
+ draw_line(Vector2(points[i].offset * total_w - POINT_WIDTH / 2, h / 2), Vector2(points[i].offset * total_w + POINT_WIDTH / 2, h / 2), col);
+ draw_line(Vector2(points[i].offset * total_w - POINT_WIDTH / 2, h - 1), Vector2(points[i].offset * total_w + POINT_WIDTH / 2, h - 1), col);
}
-
//Draw "button" for color selector
- _draw_checker(total_w+3,0, h, h);
- if (grabbed!=-1) {
+ _draw_checker(total_w + 3, 0, h, h);
+ if (grabbed != -1) {
//Draw with selection color
- draw_rect(Rect2(total_w+3,0,h,h),points[grabbed].color);
+ draw_rect(Rect2(total_w + 3, 0, h, h), points[grabbed].color);
} else {
//if no color selected draw grey color with 'X' on top.
- draw_rect(Rect2(total_w+3,0,h,h), Color(0.5, 0.5, 0.5, 1));
- draw_line(Vector2(total_w+3,0),Vector2(total_w+3+h,h),Color(1,1,1,0.6));
- draw_line(Vector2(total_w+3,h),Vector2(total_w+3+h,0),Color(1,1,1,0.6));
+ draw_rect(Rect2(total_w + 3, 0, h, h), Color(0.5, 0.5, 0.5, 1));
+ draw_line(Vector2(total_w + 3, 0), Vector2(total_w + 3 + h, h), Color(1, 1, 1, 0.6));
+ draw_line(Vector2(total_w + 3, h), Vector2(total_w + 3 + h, 0), Color(1, 1, 1, 0.6));
}
//Draw borders around color ramp if in focus
if (has_focus()) {
- draw_line(Vector2(-1,-1),Vector2(total_w+1,-1),Color(1,1,1,0.6));
- draw_line(Vector2(total_w+1,-1),Vector2(total_w+1,h+1),Color(1,1,1,0.6));
- draw_line(Vector2(total_w+1,h+1),Vector2(-1,h+1),Color(1,1,1,0.6));
- draw_line(Vector2(-1,-1),Vector2(-1,h+1),Color(1,1,1,0.6));
+ draw_line(Vector2(-1, -1), Vector2(total_w + 1, -1), Color(1, 1, 1, 0.6));
+ draw_line(Vector2(total_w + 1, -1), Vector2(total_w + 1, h + 1), Color(1, 1, 1, 0.6));
+ draw_line(Vector2(total_w + 1, h + 1), Vector2(-1, h + 1), Color(1, 1, 1, 0.6));
+ draw_line(Vector2(-1, -1), Vector2(-1, h + 1), Color(1, 1, 1, 0.6));
}
-
}
}
@@ -373,9 +366,9 @@ void ColorRampEdit::_draw_checker(int x, int y, int w, int h) {
//Draw it with polygon to insert UVs for scale
Vector<Vector2> backPoints;
backPoints.push_back(Vector2(x, y));
- backPoints.push_back(Vector2(x, y+h));
- backPoints.push_back(Vector2(x+w, y+h));
- backPoints.push_back(Vector2(x+w, y));
+ backPoints.push_back(Vector2(x, y + h));
+ backPoints.push_back(Vector2(x + w, y + h));
+ backPoints.push_back(Vector2(x + w, y));
Vector<Color> colorPoints;
colorPoints.push_back(Color(1, 1, 1, 1));
colorPoints.push_back(Color(1, 1, 1, 1));
@@ -384,35 +377,34 @@ void ColorRampEdit::_draw_checker(int x, int y, int w, int h) {
Vector<Vector2> uvPoints;
//Draw checker pattern pixel-perfect and scale it by 2.
uvPoints.push_back(Vector2(x, y));
- uvPoints.push_back(Vector2(x, y+h*.5f/checker->get_height()));
- uvPoints.push_back(Vector2(x+w*.5f/checker->get_width(), y+h*.5f/checker->get_height()));
- uvPoints.push_back(Vector2(x+w*.5f/checker->get_width(), y));
+ uvPoints.push_back(Vector2(x, y + h * .5f / checker->get_height()));
+ uvPoints.push_back(Vector2(x + w * .5f / checker->get_width(), y + h * .5f / checker->get_height()));
+ uvPoints.push_back(Vector2(x + w * .5f / checker->get_width(), y));
draw_polygon(backPoints, colorPoints, uvPoints, checker);
}
Size2 ColorRampEdit::get_minimum_size() const {
- return Vector2(0,16);
+ return Vector2(0, 16);
}
-void ColorRampEdit::_color_changed(const Color& p_color) {
+void ColorRampEdit::_color_changed(const Color &p_color) {
- if (grabbed==-1)
+ if (grabbed == -1)
return;
- points[grabbed].color=p_color;
+ points[grabbed].color = p_color;
update();
emit_signal("ramp_changed");
-
}
-void ColorRampEdit::set_ramp(const Vector<float>& p_offsets,const Vector<Color>& p_colors) {
+void ColorRampEdit::set_ramp(const Vector<float> &p_offsets, const Vector<Color> &p_colors) {
- ERR_FAIL_COND(p_offsets.size()!=p_colors.size());
+ ERR_FAIL_COND(p_offsets.size() != p_colors.size());
points.clear();
- for(int i=0;i<p_offsets.size();i++) {
+ for (int i = 0; i < p_offsets.size(); i++) {
ColorRamp::Point p;
- p.offset=p_offsets[i];
- p.color=p_colors[i];
+ p.offset = p_offsets[i];
+ p.color = p_colors[i];
points.push_back(p);
}
@@ -422,31 +414,31 @@ void ColorRampEdit::set_ramp(const Vector<float>& p_offsets,const Vector<Color>&
Vector<float> ColorRampEdit::get_offsets() const {
Vector<float> ret;
- for(int i=0;i<points.size();i++)
+ for (int i = 0; i < points.size(); i++)
ret.push_back(points[i].offset);
return ret;
}
Vector<Color> ColorRampEdit::get_colors() const {
Vector<Color> ret;
- for(int i=0;i<points.size();i++)
+ for (int i = 0; i < points.size(); i++)
ret.push_back(points[i].color);
return ret;
}
-void ColorRampEdit::set_points(Vector<ColorRamp::Point>& p_points) {
- if(points.size() != p_points.size())
+void ColorRampEdit::set_points(Vector<ColorRamp::Point> &p_points) {
+ if (points.size() != p_points.size())
grabbed = -1;
points.clear();
points = p_points;
}
-Vector<ColorRamp::Point>& ColorRampEdit::get_points() {
+Vector<ColorRamp::Point> &ColorRampEdit::get_points() {
return points;
}
void ColorRampEdit::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&ColorRampEdit::_gui_input);
- ClassDB::bind_method(D_METHOD("_color_changed"),&ColorRampEdit::_color_changed);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ColorRampEdit::_gui_input);
+ ClassDB::bind_method(D_METHOD("_color_changed"), &ColorRampEdit::_color_changed);
ADD_SIGNAL(MethodInfo("ramp_changed"));
}
diff --git a/scene/gui/color_ramp_edit.h b/scene/gui/color_ramp_edit.h
index c6a20a539d..bb12064ddf 100644
--- a/scene/gui/color_ramp_edit.h
+++ b/scene/gui/color_ramp_edit.h
@@ -29,8 +29,8 @@
#ifndef SCENE_GUI_COLOR_RAMP_EDIT_H_
#define SCENE_GUI_COLOR_RAMP_EDIT_H_
-#include "scene/gui/popup.h"
#include "scene/gui/color_picker.h"
+#include "scene/gui/popup.h"
#include "scene/resources/color_ramp.h"
#include "scene/resources/default_theme/theme_data.h"
@@ -38,7 +38,7 @@
class ColorRampEdit : public Control {
- GDCLASS(ColorRampEdit,Control);
+ GDCLASS(ColorRampEdit, Control);
PopupPanel *popup;
ColorPicker *picker;
@@ -50,21 +50,21 @@ class ColorRampEdit : public Control {
Vector<ColorRamp::Point> points;
void _draw_checker(int x, int y, int w, int h);
- void _color_changed(const Color& p_color);
+ void _color_changed(const Color &p_color);
int _get_point_from_pos(int x);
void _show_color_picker();
protected:
- void _gui_input(const InputEvent& p_event);
+ void _gui_input(const InputEvent &p_event);
void _notification(int p_what);
static void _bind_methods();
public:
- void set_ramp(const Vector<float>& p_offsets,const Vector<Color>& p_colors);
+ void set_ramp(const Vector<float> &p_offsets, const Vector<Color> &p_colors);
Vector<float> get_offsets() const;
Vector<Color> get_colors() const;
- void set_points(Vector<ColorRamp::Point>& p_points);
- Vector<ColorRamp::Point>& get_points();
+ void set_points(Vector<ColorRamp::Point> &p_points);
+ Vector<ColorRamp::Point> &get_points();
virtual Size2 get_minimum_size() const;
ColorRampEdit();
@@ -76,5 +76,4 @@ public:
GDCLASS(ColorRampEditPanel, Panel );
};*/
-
#endif /* SCENE_GUI_COLOR_RAMP_EDIT_H_ */
diff --git a/scene/gui/color_rect.cpp b/scene/gui/color_rect.cpp
index d72dffcae3..7febecc0b9 100644
--- a/scene/gui/color_rect.cpp
+++ b/scene/gui/color_rect.cpp
@@ -28,34 +28,33 @@
/*************************************************************************/
#include "color_rect.h"
+void ColorRect::set_frame_color(const Color &p_color) {
-void ColorRect::set_frame_color(const Color& p_color) {
-
- color=p_color;
+ color = p_color;
update();
}
-Color ColorRect::get_frame_color() const{
+Color ColorRect::get_frame_color() const {
return color;
}
void ColorRect::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
- draw_rect(Rect2(Point2(),get_size()),color);
+ if (p_what == NOTIFICATION_DRAW) {
+ draw_rect(Rect2(Point2(), get_size()), color);
}
}
void ColorRect::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_frame_color","color"),&ColorRect::set_frame_color);
- ClassDB::bind_method(D_METHOD("get_frame_color"),&ColorRect::get_frame_color);
+ ClassDB::bind_method(D_METHOD("set_frame_color", "color"), &ColorRect::set_frame_color);
+ ClassDB::bind_method(D_METHOD("get_frame_color"), &ColorRect::get_frame_color);
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"color"),"set_frame_color","get_frame_color") ;
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_frame_color", "get_frame_color");
}
ColorRect::ColorRect() {
- color=Color(1,1,1);
+ color = Color(1, 1, 1);
}
diff --git a/scene/gui/color_rect.h b/scene/gui/color_rect.h
index 55e413ce27..c6d0164ac9 100644
--- a/scene/gui/color_rect.h
+++ b/scene/gui/color_rect.h
@@ -31,17 +31,17 @@
#include "scene/gui/control.h"
-class ColorRect : public Control {
- GDCLASS(ColorRect,Control)
+class ColorRect : public Control {
+ GDCLASS(ColorRect, Control)
Color color;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- void set_frame_color(const Color& p_color);
+public:
+ void set_frame_color(const Color &p_color);
Color get_frame_color() const;
ColorRect();
diff --git a/scene/gui/container.cpp b/scene/gui/container.cpp
index 655c6e1bbf..811b41863c 100644
--- a/scene/gui/container.cpp
+++ b/scene/gui/container.cpp
@@ -27,9 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "container.h"
-#include "scene/scene_string_names.h"
#include "message_queue.h"
-
+#include "scene/scene_string_names.h"
void Container::_child_minsize_changed() {
@@ -47,12 +46,10 @@ void Container::add_child_notify(Node *p_child) {
if (!control)
return;
- control->connect("size_flags_changed",this,"queue_sort");
- control->connect("minimum_size_changed",this,"_child_minsize_changed");
- control->connect("visibility_changed",this,"_child_minsize_changed");
+ control->connect("size_flags_changed", this, "queue_sort");
+ control->connect("minimum_size_changed", this, "_child_minsize_changed");
+ control->connect("visibility_changed", this, "_child_minsize_changed");
queue_sort();
-
-
}
void Container::move_child_notify(Node *p_child) {
@@ -63,8 +60,6 @@ void Container::move_child_notify(Node *p_child) {
return;
queue_sort();
-
-
}
void Container::remove_child_notify(Node *p_child) {
@@ -75,9 +70,9 @@ void Container::remove_child_notify(Node *p_child) {
if (!control)
return;
- control->disconnect("size_flags_changed",this,"queue_sort");
- control->disconnect("minimum_size_changed",this,"_child_minsize_changed");
- control->disconnect("visibility_changed",this,"_child_minsize_changed");
+ control->disconnect("size_flags_changed", this, "queue_sort");
+ control->disconnect("minimum_size_changed", this, "_child_minsize_changed");
+ control->disconnect("visibility_changed", this, "_child_minsize_changed");
queue_sort();
}
@@ -88,33 +83,33 @@ void Container::_sort_children() {
notification(NOTIFICATION_SORT_CHILDREN);
emit_signal(SceneStringNames::get_singleton()->sort_children);
- pending_sort=false;
+ pending_sort = false;
}
-void Container::fit_child_in_rect(Control *p_child,const Rect2& p_rect) {
+void Container::fit_child_in_rect(Control *p_child, const Rect2 &p_rect) {
- ERR_FAIL_COND(p_child->get_parent()!=this);
+ ERR_FAIL_COND(p_child->get_parent() != this);
Size2 minsize = p_child->get_combined_minimum_size();
- Rect2 r=p_rect;
+ Rect2 r = p_rect;
- if (!(p_child->get_h_size_flags()&SIZE_FILL)) {
- r.size.x=minsize.x;
- r.pos.x += Math::floor((p_rect.size.x - minsize.x)/2);
+ if (!(p_child->get_h_size_flags() & SIZE_FILL)) {
+ r.size.x = minsize.x;
+ r.pos.x += Math::floor((p_rect.size.x - minsize.x) / 2);
}
- if (!(p_child->get_v_size_flags()&SIZE_FILL)) {
- r.size.y=minsize.y;
- r.pos.y += Math::floor((p_rect.size.y - minsize.y)/2);
+ if (!(p_child->get_v_size_flags() & SIZE_FILL)) {
+ r.size.y = minsize.y;
+ r.pos.y += Math::floor((p_rect.size.y - minsize.y) / 2);
}
- for(int i=0;i<4;i++)
- p_child->set_anchor(Margin(i),ANCHOR_BEGIN);
+ for (int i = 0; i < 4; i++)
+ p_child->set_anchor(Margin(i), ANCHOR_BEGIN);
p_child->set_pos(r.pos);
p_child->set_size(r.size);
p_child->set_rotation(0);
- p_child->set_scale(Vector2(1,1));
+ p_child->set_scale(Vector2(1, 1));
}
void Container::queue_sort() {
@@ -125,16 +120,16 @@ void Container::queue_sort() {
if (pending_sort)
return;
- MessageQueue::get_singleton()->push_call(this,"_sort_children");
- pending_sort=true;
+ MessageQueue::get_singleton()->push_call(this, "_sort_children");
+ pending_sort = true;
}
void Container::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
- pending_sort=false;
+ pending_sort = false;
queue_sort();
} break;
case NOTIFICATION_RESIZED: {
@@ -156,17 +151,17 @@ void Container::_notification(int p_what) {
void Container::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_sort_children"),&Container::_sort_children);
- ClassDB::bind_method(D_METHOD("_child_minsize_changed"),&Container::_child_minsize_changed);
+ ClassDB::bind_method(D_METHOD("_sort_children"), &Container::_sort_children);
+ ClassDB::bind_method(D_METHOD("_child_minsize_changed"), &Container::_child_minsize_changed);
- ClassDB::bind_method(D_METHOD("queue_sort"),&Container::queue_sort);
- ClassDB::bind_method(D_METHOD("fit_child_in_rect","child:Control","rect"),&Container::fit_child_in_rect);
+ ClassDB::bind_method(D_METHOD("queue_sort"), &Container::queue_sort);
+ ClassDB::bind_method(D_METHOD("fit_child_in_rect", "child:Control", "rect"), &Container::fit_child_in_rect);
- BIND_CONSTANT( NOTIFICATION_SORT_CHILDREN );
+ BIND_CONSTANT(NOTIFICATION_SORT_CHILDREN);
ADD_SIGNAL(MethodInfo("sort_children"));
}
Container::Container() {
- pending_sort=false;
+ pending_sort = false;
}
diff --git a/scene/gui/container.h b/scene/gui/container.h
index bb47524972..78f647f59d 100644
--- a/scene/gui/container.h
+++ b/scene/gui/container.h
@@ -33,13 +33,13 @@
class Container : public Control {
- GDCLASS(Container,Control);
+ GDCLASS(Container, Control);
bool pending_sort;
void _sort_children();
void _child_minsize_changed();
-protected:
+protected:
void queue_sort();
virtual void add_child_notify(Node *p_child);
virtual void move_child_notify(Node *p_child);
@@ -47,12 +47,13 @@ protected:
void _notification(int p_what);
static void _bind_methods();
+
public:
enum {
- NOTIFICATION_SORT_CHILDREN=50
+ NOTIFICATION_SORT_CHILDREN = 50
};
- void fit_child_in_rect(Control *p_child,const Rect2& p_rect);
+ void fit_child_in_rect(Control *p_child, const Rect2 &p_rect);
Container();
};
diff --git a/scene/gui/control.cpp b/scene/gui/control.cpp
index 496b1e03cf..7779391bae 100644
--- a/scene/gui/control.cpp
+++ b/scene/gui/control.cpp
@@ -27,55 +27,51 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "control.h"
-#include "servers/visual_server.h"
-#include "scene/main/viewport.h"
-#include "scene/main/canvas_layer.h"
#include "global_config.h"
+#include "scene/main/canvas_layer.h"
+#include "scene/main/viewport.h"
+#include "servers/visual_server.h"
-#include "print_string.h"
+#include "message_queue.h"
#include "os/keyboard.h"
#include "os/os.h"
-#include "message_queue.h"
-#include "scene/scene_string_names.h"
-#include "scene/gui/panel.h"
+#include "print_string.h"
#include "scene/gui/label.h"
+#include "scene/gui/panel.h"
+#include "scene/scene_string_names.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
#endif
#include <stdio.h>
-
-
-
Variant Control::edit_get_state() const {
Dictionary s;
- s["rect"]=get_rect();
- s["rot"]=get_rotation();
- s["scale"]=get_scale();
+ s["rect"] = get_rect();
+ s["rot"] = get_rotation();
+ s["scale"] = get_scale();
return s;
-
}
-void Control::edit_set_state(const Variant& p_state) {
+void Control::edit_set_state(const Variant &p_state) {
- Dictionary s=p_state;
+ Dictionary s = p_state;
- Rect2 state=s["rect"];
+ Rect2 state = s["rect"];
set_pos(state.pos);
set_size(state.size);
set_rotation(s["rot"]);
set_scale(s["scale"]);
}
-void Control::set_custom_minimum_size(const Size2& p_custom) {
+void Control::set_custom_minimum_size(const Size2 &p_custom) {
- if (p_custom==data.custom_minimum_size)
+ if (p_custom == data.custom_minimum_size)
return;
- data.custom_minimum_size=p_custom;
+ data.custom_minimum_size = p_custom;
minimum_size_changed();
}
-Size2 Control::get_custom_minimum_size() const{
+Size2 Control::get_custom_minimum_size() const {
return data.custom_minimum_size;
}
@@ -83,8 +79,8 @@ Size2 Control::get_custom_minimum_size() const{
Size2 Control::get_combined_minimum_size() const {
Size2 minsize = get_minimum_size();
- minsize.x = MAX(minsize.x,data.custom_minimum_size.x);
- minsize.y = MAX(minsize.y,data.custom_minimum_size.y);
+ minsize.x = MAX(minsize.x, data.custom_minimum_size.x);
+ minsize.y = MAX(minsize.y, data.custom_minimum_size.y);
return minsize;
}
@@ -93,51 +89,48 @@ Size2 Control::edit_get_minimum_size() const {
return get_combined_minimum_size();
}
-void Control::edit_set_rect(const Rect2& p_edit_rect) {
-
+void Control::edit_set_rect(const Rect2 &p_edit_rect) {
Transform2D postxf;
- postxf.set_rotation_and_scale(data.rotation,data.scale);
+ postxf.set_rotation_and_scale(data.rotation, data.scale);
Vector2 new_pos = postxf.xform(p_edit_rect.pos);
- Vector2 pos = get_pos()+new_pos;
+ Vector2 pos = get_pos() + new_pos;
- Rect2 new_rect=get_rect();
- new_rect.pos=pos.snapped(Vector2(1,1));
- new_rect.size=p_edit_rect.size.snapped(Vector2(1,1));
+ Rect2 new_rect = get_rect();
+ new_rect.pos = pos.snapped(Vector2(1, 1));
+ new_rect.size = p_edit_rect.size.snapped(Vector2(1, 1));
set_pos(new_rect.pos);
set_size(new_rect.size);
-
}
-bool Control::_set(const StringName& p_name, const Variant& p_value) {
+bool Control::_set(const StringName &p_name, const Variant &p_value) {
-
- String name= p_name;
+ String name = p_name;
if (!name.begins_with("custom")) {
return false;
}
- if (p_value.get_type()==Variant::NIL) {
+ if (p_value.get_type() == Variant::NIL) {
if (name.begins_with("custom_icons/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
data.icon_override.erase(dname);
notification(NOTIFICATION_THEME_CHANGED);
update();
} else if (name.begins_with("custom_shaders/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
data.shader_override.erase(dname);
notification(NOTIFICATION_THEME_CHANGED);
update();
} else if (name.begins_with("custom_styles/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
data.style_override.erase(dname);
notification(NOTIFICATION_THEME_CHANGED);
update();
} else if (name.begins_with("custom_fonts/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
if (data.font_override.has(dname)) {
_unref_font(data.font_override[dname]);
}
@@ -145,12 +138,12 @@ bool Control::_set(const StringName& p_name, const Variant& p_value) {
notification(NOTIFICATION_THEME_CHANGED);
update();
} else if (name.begins_with("custom_colors/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
data.color_override.erase(dname);
notification(NOTIFICATION_THEME_CHANGED);
update();
} else if (name.begins_with("custom_constants/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
data.constant_override.erase(dname);
notification(NOTIFICATION_THEME_CHANGED);
update();
@@ -159,34 +152,33 @@ bool Control::_set(const StringName& p_name, const Variant& p_value) {
} else {
if (name.begins_with("custom_icons/")) {
- String dname = name.get_slicec('/',1);
+ String dname = name.get_slicec('/', 1);
notification(NOTIFICATION_THEME_CHANGED);
- add_icon_override(dname,p_value);
+ add_icon_override(dname, p_value);
} else if (name.begins_with("custom_shaders/")) {
- String dname = name.get_slicec('/',1);
- add_shader_override(dname,p_value);
+ String dname = name.get_slicec('/', 1);
+ add_shader_override(dname, p_value);
notification(NOTIFICATION_THEME_CHANGED);
} else if (name.begins_with("custom_styles/")) {
- String dname = name.get_slicec('/',1);
- add_style_override(dname,p_value);
+ String dname = name.get_slicec('/', 1);
+ add_style_override(dname, p_value);
notification(NOTIFICATION_THEME_CHANGED);
} else if (name.begins_with("custom_fonts/")) {
- String dname = name.get_slicec('/',1);
- add_font_override(dname,p_value);
+ String dname = name.get_slicec('/', 1);
+ add_font_override(dname, p_value);
notification(NOTIFICATION_THEME_CHANGED);
} else if (name.begins_with("custom_colors/")) {
- String dname = name.get_slicec('/',1);
- add_color_override(dname,p_value);
+ String dname = name.get_slicec('/', 1);
+ add_color_override(dname, p_value);
notification(NOTIFICATION_THEME_CHANGED);
} else if (name.begins_with("custom_constants/")) {
- String dname = name.get_slicec('/',1);
- add_constant_override(dname,p_value);
+ String dname = name.get_slicec('/', 1);
+ add_constant_override(dname, p_value);
notification(NOTIFICATION_THEME_CHANGED);
} else
return false;
}
return true;
-
}
void Control::_update_minimum_size() {
@@ -194,155 +186,142 @@ void Control::_update_minimum_size() {
if (!is_inside_tree())
return;
- data.pending_min_size_update=false;
+ data.pending_min_size_update = false;
Size2 minsize = get_combined_minimum_size();
if (minsize.x > data.size_cache.x ||
- minsize.y > data.size_cache.y
- ) {
+ minsize.y > data.size_cache.y) {
_size_changed();
}
emit_signal(SceneStringNames::get_singleton()->minimum_size_changed);
-
}
-bool Control::_get(const StringName& p_name,Variant &r_ret) const {
+bool Control::_get(const StringName &p_name, Variant &r_ret) const {
-
- String sname=p_name;
+ String sname = p_name;
if (!sname.begins_with("custom")) {
return false;
-
}
if (sname.begins_with("custom_icons/")) {
- String name = sname.get_slicec('/',1);
+ String name = sname.get_slicec('/', 1);
- r_ret= data.icon_override.has(name)?Variant(data.icon_override[name]):Variant();
+ r_ret = data.icon_override.has(name) ? Variant(data.icon_override[name]) : Variant();
} else if (sname.begins_with("custom_shaders/")) {
- String name = sname.get_slicec('/',1);
+ String name = sname.get_slicec('/', 1);
- r_ret= data.shader_override.has(name)?Variant(data.shader_override[name]):Variant();
+ r_ret = data.shader_override.has(name) ? Variant(data.shader_override[name]) : Variant();
} else if (sname.begins_with("custom_styles/")) {
- String name = sname.get_slicec('/',1);
+ String name = sname.get_slicec('/', 1);
- r_ret= data.style_override.has(name)?Variant(data.style_override[name]):Variant();
+ r_ret = data.style_override.has(name) ? Variant(data.style_override[name]) : Variant();
} else if (sname.begins_with("custom_fonts/")) {
- String name = sname.get_slicec('/',1);
+ String name = sname.get_slicec('/', 1);
- r_ret= data.font_override.has(name)?Variant(data.font_override[name]):Variant();
+ r_ret = data.font_override.has(name) ? Variant(data.font_override[name]) : Variant();
} else if (sname.begins_with("custom_colors/")) {
- String name = sname.get_slicec('/',1);
- r_ret= data.color_override.has(name)?Variant(data.color_override[name]):Variant();
+ String name = sname.get_slicec('/', 1);
+ r_ret = data.color_override.has(name) ? Variant(data.color_override[name]) : Variant();
} else if (sname.begins_with("custom_constants/")) {
- String name = sname.get_slicec('/',1);
+ String name = sname.get_slicec('/', 1);
- r_ret= data.constant_override.has(name)?Variant(data.constant_override[name]):Variant();
+ r_ret = data.constant_override.has(name) ? Variant(data.constant_override[name]) : Variant();
} else
return false;
-
-
return true;
-
-
}
-void Control::_get_property_list( List<PropertyInfo> *p_list) const {
+void Control::_get_property_list(List<PropertyInfo> *p_list) const {
Ref<Theme> theme;
if (data.theme.is_valid()) {
- theme=data.theme;
+ theme = data.theme;
} else {
- theme=Theme::get_default();
+ theme = Theme::get_default();
}
-
{
List<StringName> names;
- theme->get_icon_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_icon_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.icon_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::OBJECT,"custom_icons/"+E->get(),PROPERTY_HINT_RESOURCE_TYPE, "Texture",hint) );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "custom_icons/" + E->get(), PROPERTY_HINT_RESOURCE_TYPE, "Texture", hint));
}
}
{
List<StringName> names;
- theme->get_shader_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_shader_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.shader_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::OBJECT,"custom_shaders/"+E->get(),PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemShader,CanvasItemShaderGraph",hint) );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "custom_shaders/" + E->get(), PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemShader,CanvasItemShaderGraph", hint));
}
}
{
List<StringName> names;
- theme->get_stylebox_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_stylebox_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.style_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::OBJECT,"custom_styles/"+E->get(),PROPERTY_HINT_RESOURCE_TYPE, "StyleBox",hint) );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "custom_styles/" + E->get(), PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", hint));
}
}
{
List<StringName> names;
- theme->get_font_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_font_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.font_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::OBJECT,"custom_fonts/"+E->get(),PROPERTY_HINT_RESOURCE_TYPE, "Font",hint) );
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "custom_fonts/" + E->get(), PROPERTY_HINT_RESOURCE_TYPE, "Font", hint));
}
}
{
List<StringName> names;
- theme->get_color_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_color_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.color_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::COLOR,"custom_colors/"+E->get(),PROPERTY_HINT_NONE, "",hint) );
+ p_list->push_back(PropertyInfo(Variant::COLOR, "custom_colors/" + E->get(), PROPERTY_HINT_NONE, "", hint));
}
}
{
List<StringName> names;
- theme->get_constant_list(get_class_name(),&names);
- for(List<StringName>::Element *E=names.front();E;E=E->next()) {
+ theme->get_constant_list(get_class_name(), &names);
+ for (List<StringName>::Element *E = names.front(); E; E = E->next()) {
- uint32_t hint= PROPERTY_USAGE_EDITOR|PROPERTY_USAGE_CHECKABLE;
+ uint32_t hint = PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_CHECKABLE;
if (data.constant_override.has(E->get()))
- hint|=PROPERTY_USAGE_STORAGE|PROPERTY_USAGE_CHECKED;
+ hint |= PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_CHECKED;
- p_list->push_back( PropertyInfo(Variant::INT,"custom_constants/"+E->get(),PROPERTY_HINT_RANGE, "-16384,16384",hint) );
+ p_list->push_back(PropertyInfo(Variant::INT, "custom_constants/" + E->get(), PROPERTY_HINT_RANGE, "-16384,16384", hint));
}
}
-
-
}
-
Control *Control::get_parent_control() const {
return data.parent;
}
-
-void Control::_resize(const Size2& p_size) {
+void Control::_resize(const Size2 &p_size) {
_size_changed();
}
@@ -351,39 +330,36 @@ void Control::_resize(const Size2& p_size) {
void Control::add_child_notify(Node *p_child) {
- Control *child_c=p_child->cast_to<Control>();
+ Control *child_c = p_child->cast_to<Control>();
if (!child_c)
return;
if (child_c->data.theme.is_null() && data.theme_owner) {
- _propagate_theme_changed(child_c,data.theme_owner); //need to propagate here, since many controls may require setting up stuff
+ _propagate_theme_changed(child_c, data.theme_owner); //need to propagate here, since many controls may require setting up stuff
}
}
void Control::remove_child_notify(Node *p_child) {
- Control *child_c=p_child->cast_to<Control>();
+ Control *child_c = p_child->cast_to<Control>();
if (!child_c)
return;
if (child_c->data.theme_owner && child_c->data.theme.is_null()) {
- _propagate_theme_changed(child_c,NULL);
+ _propagate_theme_changed(child_c, NULL);
}
-
}
void Control::_update_canvas_item_transform() {
- Transform2D xform=Transform2D(data.rotation,get_pos());
+ Transform2D xform = Transform2D(data.rotation, get_pos());
xform.scale_basis(data.scale);
- VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(),xform);
-
+ VisualServer::get_singleton()->canvas_item_set_transform(get_canvas_item(), xform);
}
void Control::_notification(int p_notification) {
-
- switch(p_notification) {
+ switch (p_notification) {
case NOTIFICATION_ENTER_TREE: {
@@ -394,43 +370,40 @@ void Control::_notification(int p_notification) {
get_viewport()->_gui_remove_control(this);
-
} break;
-
case NOTIFICATION_ENTER_CANVAS: {
- data.parent=get_parent()->cast_to<Control>();
+ data.parent = get_parent()->cast_to<Control>();
if (is_set_as_toplevel()) {
- data.SI=get_viewport()->_gui_add_subwindow_control(this);
+ data.SI = get_viewport()->_gui_add_subwindow_control(this);
if (data.theme.is_null() && data.parent && data.parent->data.theme_owner) {
- data.theme_owner=data.parent->data.theme_owner;
+ data.theme_owner = data.parent->data.theme_owner;
notification(NOTIFICATION_THEME_CHANGED);
}
} else {
+ Node *parent = this; //meh
+ Control *parent_control = NULL;
+ bool subwindow = false;
- Node *parent=this; //meh
- Control *parent_control=NULL;
- bool subwindow=false;
+ while (parent) {
- while(parent) {
-
- parent=parent->get_parent();
+ parent = parent->get_parent();
if (!parent)
break;
- CanvasItem *ci =parent->cast_to<CanvasItem>();
+ CanvasItem *ci = parent->cast_to<CanvasItem>();
if (ci && ci->is_set_as_toplevel()) {
- subwindow=true;
+ subwindow = true;
break;
}
- parent_control=parent->cast_to<Control>();
+ parent_control = parent->cast_to<Control>();
if (parent_control) {
break;
@@ -441,33 +414,31 @@ void Control::_notification(int p_notification) {
}
}
-
if (parent_control) {
//do nothing, has a parent control
if (data.theme.is_null() && parent_control->data.theme_owner) {
- data.theme_owner=parent_control->data.theme_owner;
+ data.theme_owner = parent_control->data.theme_owner;
notification(NOTIFICATION_THEME_CHANGED);
}
} else if (subwindow) {
//is a subwindow (process input before other controls for that canvas)
- data.SI=get_viewport()->_gui_add_subwindow_control(this);
+ data.SI = get_viewport()->_gui_add_subwindow_control(this);
} else {
//is a regular root control
- data.RI=get_viewport()->_gui_add_root_control(this);
+ data.RI = get_viewport()->_gui_add_root_control(this);
}
- data.parent_canvas_item=get_parent_item();
+ data.parent_canvas_item = get_parent_item();
if (data.parent_canvas_item) {
- data.parent_canvas_item->connect("item_rect_changed",this,"_size_changed");
- } else {
+ data.parent_canvas_item->connect("item_rect_changed", this, "_size_changed");
+ } else {
//connect viewport
- get_viewport()->connect("size_changed",this,"_size_changed");
+ get_viewport()->connect("size_changed", this, "_size_changed");
}
}
-
/*
if (data.theme.is_null() && data.parent && data.parent->data.theme_owner) {
data.theme_owner=data.parent->data.theme_owner;
@@ -480,31 +451,30 @@ void Control::_notification(int p_notification) {
if (data.parent_canvas_item) {
- data.parent_canvas_item->disconnect("item_rect_changed",this,"_size_changed");
- data.parent_canvas_item=NULL;
+ data.parent_canvas_item->disconnect("item_rect_changed", this, "_size_changed");
+ data.parent_canvas_item = NULL;
} else if (!is_set_as_toplevel()) {
//disconnect viewport
- get_viewport()->disconnect("size_changed",this,"_size_changed");
-
+ get_viewport()->disconnect("size_changed", this, "_size_changed");
}
if (data.MI) {
get_viewport()->_gui_remove_modal_control(data.MI);
- data.MI=NULL;
+ data.MI = NULL;
}
if (data.SI) {
get_viewport()->_gui_remove_subwindow_control(data.SI);
- data.SI=NULL;
+ data.SI = NULL;
}
if (data.RI) {
get_viewport()->_gui_remove_root_control(data.RI);
- data.RI=NULL;
+ data.RI = NULL;
}
- data.parent=NULL;
- data.parent_canvas_item=NULL;
+ data.parent = NULL;
+ data.parent_canvas_item = NULL;
/*
if (data.theme_owner && data.theme.is_null()) {
data.theme_owner=NULL;
@@ -513,21 +483,21 @@ void Control::_notification(int p_notification) {
*/
} break;
- case NOTIFICATION_MOVED_IN_PARENT: {
- // some parents need to know the order of the childrens to draw (like TabContainer)
- // update if necesary
- if (data.parent)
- data.parent->update();
- update();
-
- if (data.SI) {
- get_viewport()->_gui_set_subwindow_order_dirty();
- }
- if (data.RI) {
- get_viewport()->_gui_set_root_order_dirty();
- }
-
- } break;
+ case NOTIFICATION_MOVED_IN_PARENT: {
+ // some parents need to know the order of the childrens to draw (like TabContainer)
+ // update if necesary
+ if (data.parent)
+ data.parent->update();
+ update();
+
+ if (data.SI) {
+ get_viewport()->_gui_set_subwindow_order_dirty();
+ }
+ if (data.RI) {
+ get_viewport()->_gui_set_root_order_dirty();
+ }
+
+ } break;
case NOTIFICATION_RESIZED: {
emit_signal(SceneStringNames::get_singleton()->resized);
@@ -535,8 +505,8 @@ void Control::_notification(int p_notification) {
case NOTIFICATION_DRAW: {
_update_canvas_item_transform();
- VisualServer::get_singleton()->canvas_item_set_custom_rect( get_canvas_item(),!data.disable_visibility_clip, Rect2(Point2(),get_size()));
- VisualServer::get_singleton()->canvas_item_set_clip( get_canvas_item(), data.clip_contents );
+ VisualServer::get_singleton()->canvas_item_set_custom_rect(get_canvas_item(), !data.disable_visibility_clip, Rect2(Point2(), get_size()));
+ VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(), data.clip_contents);
//emit_signal(SceneStringNames::get_singleton()->draw);
} break;
@@ -571,10 +541,10 @@ void Control::_notification(int p_notification) {
if (!is_visible_in_tree()) {
- if(get_viewport() != NULL)
+ if (get_viewport() != NULL)
get_viewport()->_gui_hid_control(this);
- if(is_inside_tree()) {
+ if (is_inside_tree()) {
_modal_stack_remove();
minimum_size_changed();
}
@@ -592,25 +562,21 @@ void Control::_notification(int p_notification) {
get_viewport()->_gui_unfocus_control(this);
} break;
-
-
-
}
}
-
bool Control::clips_input() const {
return false;
}
-bool Control::has_point(const Point2& p_point) const {
+bool Control::has_point(const Point2 &p_point) const {
if (get_script_instance()) {
- Variant v=p_point;
- const Variant *p=&v;
+ Variant v = p_point;
+ const Variant *p = &v;
Variant::CallError ce;
- Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->has_point,&p,1,ce);
- if (ce.error==Variant::CallError::CALL_OK) {
+ Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->has_point, &p, 1, ce);
+ if (ce.error == Variant::CallError::CALL_OK) {
return ret;
}
}
@@ -618,101 +584,95 @@ bool Control::has_point(const Point2& p_point) const {
Ref<StyleBox> mask = get_stylebox("mask");
return mask->test_mask(p_point,Rect2(Point2(),get_size()));
}*/
- return Rect2( Point2(), get_size() ).has_point(p_point);
+ return Rect2(Point2(), get_size()).has_point(p_point);
}
-void Control::set_drag_forwarding(Control* p_target) {
+void Control::set_drag_forwarding(Control *p_target) {
if (p_target)
- data.drag_owner=p_target->get_instance_ID();
+ data.drag_owner = p_target->get_instance_ID();
else
- data.drag_owner=0;
+ data.drag_owner = 0;
}
-Variant Control::get_drag_data(const Point2& p_point) {
+Variant Control::get_drag_data(const Point2 &p_point) {
if (data.drag_owner) {
Object *obj = ObjectDB::get_instance(data.drag_owner);
if (obj) {
Control *c = obj->cast_to<Control>();
- return c->call("get_drag_data_fw",p_point,this);
+ return c->call("get_drag_data_fw", p_point, this);
}
}
if (get_script_instance()) {
- Variant v=p_point;
- const Variant *p=&v;
+ Variant v = p_point;
+ const Variant *p = &v;
Variant::CallError ce;
- Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->get_drag_data,&p,1,ce);
- if (ce.error==Variant::CallError::CALL_OK)
+ Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->get_drag_data, &p, 1, ce);
+ if (ce.error == Variant::CallError::CALL_OK)
return ret;
}
return Variant();
}
-
-bool Control::can_drop_data(const Point2& p_point,const Variant& p_data) const {
+bool Control::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
if (data.drag_owner) {
Object *obj = ObjectDB::get_instance(data.drag_owner);
if (obj) {
Control *c = obj->cast_to<Control>();
- return c->call("can_drop_data_fw",p_point,p_data,this);
+ return c->call("can_drop_data_fw", p_point, p_data, this);
}
}
if (get_script_instance()) {
- Variant v=p_point;
- const Variant *p[2]={&v,&p_data};
+ Variant v = p_point;
+ const Variant *p[2] = { &v, &p_data };
Variant::CallError ce;
- Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->can_drop_data,p,2,ce);
- if (ce.error==Variant::CallError::CALL_OK)
+ Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->can_drop_data, p, 2, ce);
+ if (ce.error == Variant::CallError::CALL_OK)
return ret;
}
return Variant();
-
}
-void Control::drop_data(const Point2& p_point,const Variant& p_data){
+void Control::drop_data(const Point2 &p_point, const Variant &p_data) {
if (data.drag_owner) {
Object *obj = ObjectDB::get_instance(data.drag_owner);
if (obj) {
Control *c = obj->cast_to<Control>();
- c->call("drop_data_fw",p_point,p_data,this);
+ c->call("drop_data_fw", p_point, p_data, this);
return;
}
}
if (get_script_instance()) {
- Variant v=p_point;
- const Variant *p[2]={&v,&p_data};
+ Variant v = p_point;
+ const Variant *p[2] = { &v, &p_data };
Variant::CallError ce;
- Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->drop_data,p,2,ce);
- if (ce.error==Variant::CallError::CALL_OK)
+ Variant ret = get_script_instance()->call(SceneStringNames::get_singleton()->drop_data, p, 2, ce);
+ if (ce.error == Variant::CallError::CALL_OK)
return;
}
}
-void Control::force_drag(const Variant& p_data,Control *p_control) {
+void Control::force_drag(const Variant &p_data, Control *p_control) {
ERR_FAIL_COND(!is_inside_tree());
- ERR_FAIL_COND(p_data.get_type()==Variant::NIL);
-
- get_viewport()->_gui_force_drag(this,p_data,p_control);
+ ERR_FAIL_COND(p_data.get_type() == Variant::NIL);
+ get_viewport()->_gui_force_drag(this, p_data, p_control);
}
void Control::set_drag_preview(Control *p_control) {
ERR_FAIL_COND(!is_inside_tree());
- get_viewport()->_gui_set_drag_preview(this,p_control);
+ get_viewport()->_gui_set_drag_preview(this, p_control);
}
-
-
-
bool Control::is_window_modal_on_top() const {
if (!is_inside_tree())
@@ -726,154 +686,147 @@ uint64_t Control::get_modal_frame() const {
return data.modal_frame;
}
-
-
Size2 Control::get_minimum_size() const {
- ScriptInstance *si = const_cast<Control*>(this)->get_script_instance();
+ ScriptInstance *si = const_cast<Control *>(this)->get_script_instance();
if (si) {
Variant::CallError ce;
- Variant s = si->call(SceneStringNames::get_singleton()->get_minimum_size,NULL,0,ce);
- if (ce.error==Variant::CallError::CALL_OK)
+ Variant s = si->call(SceneStringNames::get_singleton()->get_minimum_size, NULL, 0, ce);
+ if (ce.error == Variant::CallError::CALL_OK)
return s;
}
return Size2();
}
+Ref<Texture> Control::get_icon(const StringName &p_name, const StringName &p_type) const {
-Ref<Texture> Control::get_icon(const StringName& p_name,const StringName& p_type) const {
-
- if (p_type==StringName() || p_type=="") {
+ if (p_type == StringName() || p_type == "") {
- const Ref<Texture>* tex = data.icon_override.getptr(p_name);
+ const Ref<Texture> *tex = data.icon_override.getptr(p_name);
if (tex)
return *tex;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_icon(p_name, class_name ) ) {
- return theme_owner->data.theme->get_icon(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_icon(p_name, class_name)) {
+ return theme_owner->data.theme->get_icon(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->get_icon( p_name, type );
-
+ return Theme::get_default()->get_icon(p_name, type);
}
-Ref<Shader> Control::get_shader(const StringName& p_name,const StringName& p_type) const {
- if (p_type==StringName() || p_type=="") {
+Ref<Shader> Control::get_shader(const StringName &p_name, const StringName &p_type) const {
+ if (p_type == StringName() || p_type == "") {
- const Ref<Shader>* sdr = data.shader_override.getptr(p_name);
+ const Ref<Shader> *sdr = data.shader_override.getptr(p_name);
if (sdr)
return *sdr;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_shader(p_name, class_name ) ) {
- return theme_owner->data.theme->get_shader(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_shader(p_name, class_name)) {
+ return theme_owner->data.theme->get_shader(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->get_shader( p_name, type );
+ return Theme::get_default()->get_shader(p_name, type);
}
-Ref<StyleBox> Control::get_stylebox(const StringName& p_name,const StringName& p_type) const {
+Ref<StyleBox> Control::get_stylebox(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- const Ref<StyleBox>* style = data.style_override.getptr(p_name);
+ if (p_type == StringName() || p_type == "") {
+ const Ref<StyleBox> *style = data.style_override.getptr(p_name);
if (style)
return *style;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_stylebox(p_name, class_name ) ) {
- return theme_owner->data.theme->get_stylebox(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_stylebox(p_name, class_name)) {
+ return theme_owner->data.theme->get_stylebox(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
+ theme_owner = NULL;
}
- return Theme::get_default()->get_stylebox( p_name, type );
-
+ return Theme::get_default()->get_stylebox(p_name, type);
}
-Ref<Font> Control::get_font(const StringName& p_name,const StringName& p_type) const {
+Ref<Font> Control::get_font(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- const Ref<Font>* font = data.font_override.getptr(p_name);
+ if (p_type == StringName() || p_type == "") {
+ const Ref<Font> *font = data.font_override.getptr(p_name);
if (font)
return *font;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_font(p_name, class_name ) ) {
- return theme_owner->data.theme->get_font(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_font(p_name, class_name)) {
+ return theme_owner->data.theme->get_font(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
@@ -881,96 +834,89 @@ Ref<Font> Control::get_font(const StringName& p_name,const StringName& p_type) c
if (theme_owner->data.theme->get_default_theme_font().is_valid())
return theme_owner->data.theme->get_default_theme_font();
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->get_font( p_name, type );
-
+ return Theme::get_default()->get_font(p_name, type);
}
-Color Control::get_color(const StringName& p_name,const StringName& p_type) const {
+Color Control::get_color(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- const Color* color = data.color_override.getptr(p_name);
+ if (p_type == StringName() || p_type == "") {
+ const Color *color = data.color_override.getptr(p_name);
if (color)
return *color;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_color(p_name, class_name ) ) {
- return theme_owner->data.theme->get_color(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_color(p_name, class_name)) {
+ return theme_owner->data.theme->get_color(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->get_color( p_name, type );
-
+ return Theme::get_default()->get_color(p_name, type);
}
-int Control::get_constant(const StringName& p_name,const StringName& p_type) const {
+int Control::get_constant(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- const int* constant = data.constant_override.getptr(p_name);
+ if (p_type == StringName() || p_type == "") {
+ const int *constant = data.constant_override.getptr(p_name);
if (constant)
return *constant;
}
- StringName type = p_type?p_type:get_class_name();
- // try with custom themes
+ StringName type = p_type ? p_type : get_class_name();
+ // try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_constant(p_name, class_name ) ) {
- return theme_owner->data.theme->get_constant(p_name, class_name );
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_constant(p_name, class_name)) {
+ return theme_owner->data.theme->get_constant(p_name, class_name);
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->get_constant( p_name, type );
-
-
+ return Theme::get_default()->get_constant(p_name, type);
}
-bool Control::has_icon_override(const StringName& p_name) const {
+bool Control::has_icon_override(const StringName &p_name) const {
- const Ref<Texture>* tex = data.icon_override.getptr(p_name);
+ const Ref<Texture> *tex = data.icon_override.getptr(p_name);
if (tex)
return true;
else
@@ -979,279 +925,265 @@ bool Control::has_icon_override(const StringName& p_name) const {
bool Control::has_shader_override(const StringName &p_name) const {
- const Ref<Shader>* sdr = data.shader_override.getptr(p_name);
+ const Ref<Shader> *sdr = data.shader_override.getptr(p_name);
if (sdr)
return true;
else
return false;
}
-bool Control::has_stylebox_override(const StringName& p_name) const {
+bool Control::has_stylebox_override(const StringName &p_name) const {
- const Ref<StyleBox>* style = data.style_override.getptr(p_name);
+ const Ref<StyleBox> *style = data.style_override.getptr(p_name);
if (style)
return true;
else
return false;
}
-bool Control::has_font_override(const StringName& p_name) const {
+bool Control::has_font_override(const StringName &p_name) const {
- const Ref<Font>* font = data.font_override.getptr(p_name);
+ const Ref<Font> *font = data.font_override.getptr(p_name);
if (font)
return true;
else
return false;
}
-bool Control::has_color_override(const StringName& p_name) const {
+bool Control::has_color_override(const StringName &p_name) const {
- const Color* color = data.color_override.getptr(p_name);
+ const Color *color = data.color_override.getptr(p_name);
if (color)
return true;
else
return false;
}
-bool Control::has_constant_override(const StringName& p_name) const {
+bool Control::has_constant_override(const StringName &p_name) const {
- const int* constant = data.constant_override.getptr(p_name);
+ const int *constant = data.constant_override.getptr(p_name);
if (constant)
return true;
else
return false;
}
-bool Control::has_icon(const StringName& p_name,const StringName& p_type) const {
+bool Control::has_icon(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
+ if (p_type == StringName() || p_type == "") {
if (has_icon_override(p_name) == true)
return true;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_icon(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_icon(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_icon( p_name, type );
-
+ return Theme::get_default()->has_icon(p_name, type);
}
bool Control::has_shader(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- if (has_shader_override(p_name)==true)
+ if (p_type == StringName() || p_type == "") {
+ if (has_shader_override(p_name) == true)
return true;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_shader(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_shader(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_shader( p_name, type );
-
+ return Theme::get_default()->has_shader(p_name, type);
}
-bool Control::has_stylebox(const StringName& p_name,const StringName& p_type) const {
+bool Control::has_stylebox(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- if (has_stylebox_override(p_name)==true)
+ if (p_type == StringName() || p_type == "") {
+ if (has_stylebox_override(p_name) == true)
return true;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_stylebox(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_stylebox(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_stylebox( p_name, type );
-
+ return Theme::get_default()->has_stylebox(p_name, type);
}
-bool Control::has_font(const StringName& p_name,const StringName& p_type) const {
+bool Control::has_font(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- if (has_font_override(p_name)==true)
+ if (p_type == StringName() || p_type == "") {
+ if (has_font_override(p_name) == true)
return true;
}
-
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_font(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_font(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_font( p_name, type );
-
+ return Theme::get_default()->has_font(p_name, type);
}
-bool Control::has_color(const StringName& p_name, const StringName& p_type) const {
+bool Control::has_color(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
- if (has_color_override(p_name)==true)
+ if (p_type == StringName() || p_type == "") {
+ if (has_color_override(p_name) == true)
return true;
}
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_color(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_color(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_color( p_name, type );
-
+ return Theme::get_default()->has_color(p_name, type);
}
-bool Control::has_constant(const StringName& p_name,const StringName& p_type) const {
+bool Control::has_constant(const StringName &p_name, const StringName &p_type) const {
- if (p_type==StringName() || p_type=="") {
+ if (p_type == StringName() || p_type == "") {
if (has_constant_override(p_name) == true)
return true;
}
-
- StringName type = p_type?p_type:get_class_name();
+ StringName type = p_type ? p_type : get_class_name();
// try with custom themes
Control *theme_owner = data.theme_owner;
- while(theme_owner) {
+ while (theme_owner) {
StringName class_name = type;
- while(class_name!=StringName()) {
- if (theme_owner->data.theme->has_constant(p_name, class_name ) ) {
+ while (class_name != StringName()) {
+ if (theme_owner->data.theme->has_constant(p_name, class_name)) {
return true;
}
class_name = ClassDB::get_parent_class_nocheck(class_name);
}
- Control *parent = theme_owner->get_parent()?theme_owner->get_parent()->cast_to<Control>():NULL;
+ Control *parent = theme_owner->get_parent() ? theme_owner->get_parent()->cast_to<Control>() : NULL;
if (parent)
- theme_owner=parent->data.theme_owner;
+ theme_owner = parent->data.theme_owner;
else
- theme_owner=NULL;
-
+ theme_owner = NULL;
}
- return Theme::get_default()->has_constant( p_name, type );
+ return Theme::get_default()->has_constant(p_name, type);
}
Size2 Control::get_parent_area_size() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Size2());
+ ERR_FAIL_COND_V(!is_inside_tree(), Size2());
Size2 parent_size;
if (data.parent_canvas_item) {
- parent_size=data.parent_canvas_item->get_item_rect().size;
+ parent_size = data.parent_canvas_item->get_item_rect().size;
} else {
- parent_size=get_viewport()->get_visible_rect().size;
+ parent_size = get_viewport()->get_visible_rect().size;
}
return parent_size;
-
}
void Control::_size_changed() {
@@ -1263,38 +1195,38 @@ void Control::_size_changed() {
float margin_pos[4];
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- float area = parent_size[i&1];
- switch(data.anchor[i]) {
+ float area = parent_size[i & 1];
+ switch (data.anchor[i]) {
case ANCHOR_BEGIN: {
- margin_pos[i]=data.margin[i];
+ margin_pos[i] = data.margin[i];
} break;
case ANCHOR_END: {
- margin_pos[i]=area-data.margin[i];
+ margin_pos[i] = area - data.margin[i];
} break;
case ANCHOR_CENTER: {
- margin_pos[i]=(area/2)-data.margin[i];
+ margin_pos[i] = (area / 2) - data.margin[i];
} break;
}
}
- Point2 new_pos_cache=Point2(margin_pos[0],margin_pos[1]).floor();
- Size2 new_size_cache=Point2(margin_pos[2],margin_pos[3]).floor()-new_pos_cache;
- Size2 minimum_size=get_combined_minimum_size();
+ Point2 new_pos_cache = Point2(margin_pos[0], margin_pos[1]).floor();
+ Size2 new_size_cache = Point2(margin_pos[2], margin_pos[3]).floor() - new_pos_cache;
+ Size2 minimum_size = get_combined_minimum_size();
- new_size_cache.x = MAX( minimum_size.x, new_size_cache.x );
- new_size_cache.y = MAX( minimum_size.y, new_size_cache.y );
+ new_size_cache.x = MAX(minimum_size.x, new_size_cache.x);
+ new_size_cache.y = MAX(minimum_size.y, new_size_cache.y);
bool pos_changed = new_pos_cache != data.pos_cache;
bool size_changed = new_size_cache != data.size_cache;
- data.pos_cache=new_pos_cache;
- data.size_cache=new_size_cache;
+ data.pos_cache = new_pos_cache;
+ data.size_cache = new_size_cache;
if (size_changed) {
notification(NOTIFICATION_RESIZED);
@@ -1315,76 +1247,73 @@ float Control::_get_parent_range(int p_idx) const {
if (!is_inside_tree()) {
return 1.0;
+ }
+ if (data.parent_canvas_item) {
- } if (data.parent_canvas_item) {
-
- return data.parent_canvas_item->get_item_rect().size[p_idx&1];
+ return data.parent_canvas_item->get_item_rect().size[p_idx & 1];
} else {
- return get_viewport()->get_visible_rect().size[p_idx&1];
+ return get_viewport()->get_visible_rect().size[p_idx & 1];
}
return 1.0;
}
-
float Control::_get_range(int p_idx) const {
- p_idx&=1;
+ p_idx &= 1;
- float parent_range = _get_parent_range( p_idx );
- float from = _a2s( data.margin[p_idx], data.anchor[p_idx], parent_range );
- float to = _a2s( data.margin[p_idx+2], data.anchor[p_idx+2], parent_range );
+ float parent_range = _get_parent_range(p_idx);
+ float from = _a2s(data.margin[p_idx], data.anchor[p_idx], parent_range);
+ float to = _a2s(data.margin[p_idx + 2], data.anchor[p_idx + 2], parent_range);
- return to-from;
+ return to - from;
}
-float Control::_s2a(float p_val, AnchorType p_anchor,float p_range) const {
+float Control::_s2a(float p_val, AnchorType p_anchor, float p_range) const {
- switch(p_anchor) {
+ switch (p_anchor) {
case ANCHOR_BEGIN: {
return p_val;
} break;
case ANCHOR_END: {
- return p_range-p_val;
+ return p_range - p_val;
} break;
case ANCHOR_CENTER: {
- return (p_range/2)-p_val;
+ return (p_range / 2) - p_val;
} break;
}
return 0;
}
+float Control::_a2s(float p_val, AnchorType p_anchor, float p_range) const {
-float Control::_a2s(float p_val, AnchorType p_anchor,float p_range) const {
-
- switch(p_anchor) {
+ switch (p_anchor) {
case ANCHOR_BEGIN: {
return Math::floor(p_val);
} break;
case ANCHOR_END: {
- return Math::floor(p_range-p_val);
+ return Math::floor(p_range - p_val);
} break;
case ANCHOR_CENTER: {
- return Math::floor((p_range/2)-p_val);
+ return Math::floor((p_range / 2) - p_val);
} break;
}
return 0;
}
-
-void Control::set_anchor(Margin p_margin,AnchorType p_anchor, bool p_keep_margin) {
+void Control::set_anchor(Margin p_margin, AnchorType p_anchor, bool p_keep_margin) {
if (!is_inside_tree()) {
data.anchor[p_margin] = p_anchor;
- } else if(!p_keep_margin) {
+ } else if (!p_keep_margin) {
float pr = _get_parent_range(p_margin);
- float s = _a2s( data.margin[p_margin], data.anchor[p_margin], pr );
+ float s = _a2s(data.margin[p_margin], data.anchor[p_margin], pr);
data.anchor[p_margin] = p_anchor;
- data.margin[p_margin] = _s2a( s, p_anchor, pr );
+ data.margin[p_margin] = _s2a(s, p_anchor, pr);
} else {
data.anchor[p_margin] = p_anchor;
_size_changed();
@@ -1392,34 +1321,29 @@ void Control::set_anchor(Margin p_margin,AnchorType p_anchor, bool p_keep_margin
_change_notify();
}
-void Control::_set_anchor(Margin p_margin,AnchorType p_anchor) {
- #ifdef TOOLS_ENABLED
+void Control::_set_anchor(Margin p_margin, AnchorType p_anchor) {
+#ifdef TOOLS_ENABLED
if (is_inside_tree() && get_tree()->is_editor_hint()) {
set_anchor(p_margin, p_anchor, EDITOR_DEF("editors/2d/keep_margins_when_changing_anchors", false));
} else {
set_anchor(p_margin, p_anchor, false);
}
- #else
+#else
set_anchor(p_margin, p_anchor, false);
- #endif
+#endif
}
-void Control::set_anchor_and_margin(Margin p_margin,AnchorType p_anchor, float p_pos) {
+void Control::set_anchor_and_margin(Margin p_margin, AnchorType p_anchor, float p_pos) {
- set_anchor(p_margin,p_anchor);
- set_margin(p_margin,p_pos);
+ set_anchor(p_margin, p_anchor);
+ set_margin(p_margin, p_pos);
}
-
Control::AnchorType Control::get_anchor(Margin p_margin) const {
return data.anchor[p_margin];
}
-
-
-
-
void Control::_change_notify_margins() {
// this avoids sending the whole object data again on a change
@@ -1429,28 +1353,25 @@ void Control::_change_notify_margins() {
_change_notify("margin/bottom");
_change_notify("rect/pos");
_change_notify("rect/size");
-
}
+void Control::set_margin(Margin p_margin, float p_value) {
-void Control::set_margin(Margin p_margin,float p_value) {
-
- data.margin[p_margin]=p_value;
+ data.margin[p_margin] = p_value;
_size_changed();
-
}
-void Control::set_begin(const Size2& p_point) {
+void Control::set_begin(const Size2 &p_point) {
- data.margin[0]=p_point.x;
- data.margin[1]=p_point.y;
+ data.margin[0] = p_point.x;
+ data.margin[1] = p_point.y;
_size_changed();
}
-void Control::set_end(const Size2& p_point) {
+void Control::set_end(const Size2 &p_point) {
- data.margin[2]=p_point.x;
- data.margin[3]=p_point.y;
+ data.margin[2] = p_point.x;
+ data.margin[3] = p_point.y;
_size_changed();
}
@@ -1461,11 +1382,11 @@ float Control::get_margin(Margin p_margin) const {
Size2 Control::get_begin() const {
- return Size2( data.margin[0], data.margin[1] );
+ return Size2(data.margin[0], data.margin[1]);
}
Size2 Control::get_end() const {
- return Size2( data.margin[2], data.margin[3] );
+ return Size2(data.margin[2], data.margin[3]);
}
Point2 Control::get_global_pos() const {
@@ -1473,7 +1394,7 @@ Point2 Control::get_global_pos() const {
return get_global_transform().get_origin();
}
-void Control::set_global_pos(const Point2& p_point) {
+void Control::set_global_pos(const Point2 &p_point) {
Transform2D inv;
@@ -1485,60 +1406,58 @@ void Control::set_global_pos(const Point2& p_point) {
set_pos(inv.xform(p_point));
}
-void Control::set_pos(const Size2& p_point) {
+void Control::set_pos(const Size2 &p_point) {
float pw = _get_parent_range(0);
float ph = _get_parent_range(1);
- float x = _a2s( data.margin[0], data.anchor[0], pw );
- float y = _a2s( data.margin[1], data.anchor[1], ph );
- float x2 = _a2s( data.margin[2], data.anchor[2], pw );
- float y2 = _a2s( data.margin[3], data.anchor[3], ph );
+ float x = _a2s(data.margin[0], data.anchor[0], pw);
+ float y = _a2s(data.margin[1], data.anchor[1], ph);
+ float x2 = _a2s(data.margin[2], data.anchor[2], pw);
+ float y2 = _a2s(data.margin[3], data.anchor[3], ph);
- Size2 ret = Size2(x2-x,y2-y);
+ Size2 ret = Size2(x2 - x, y2 - y);
Size2 min = get_combined_minimum_size();
- Size2 size = Size2(MAX( min.width, ret.width),MAX( min.height, ret.height));
- float w=size.x;
- float h=size.y;
+ Size2 size = Size2(MAX(min.width, ret.width), MAX(min.height, ret.height));
+ float w = size.x;
+ float h = size.y;
- x=p_point.x;
- y=p_point.y;
+ x = p_point.x;
+ y = p_point.y;
- data.margin[0] = _s2a( x, data.anchor[0], pw );
- data.margin[1] = _s2a( y, data.anchor[1], ph );
- data.margin[2] = _s2a( x+w, data.anchor[2], pw );
- data.margin[3] = _s2a( y+h, data.anchor[3], ph );
+ data.margin[0] = _s2a(x, data.anchor[0], pw);
+ data.margin[1] = _s2a(y, data.anchor[1], ph);
+ data.margin[2] = _s2a(x + w, data.anchor[2], pw);
+ data.margin[3] = _s2a(y + h, data.anchor[3], ph);
_size_changed();
}
-void Control::set_size(const Size2& p_size) {
+void Control::set_size(const Size2 &p_size) {
- Size2 new_size=p_size;
- Size2 min=get_combined_minimum_size();
- if (new_size.x<min.x)
- new_size.x=min.x;
- if (new_size.y<min.y)
- new_size.y=min.y;
+ Size2 new_size = p_size;
+ Size2 min = get_combined_minimum_size();
+ if (new_size.x < min.x)
+ new_size.x = min.x;
+ if (new_size.y < min.y)
+ new_size.y = min.y;
float pw = _get_parent_range(0);
float ph = _get_parent_range(1);
- float x = _a2s( data.margin[0], data.anchor[0], pw );
- float y = _a2s( data.margin[1], data.anchor[1], ph );
+ float x = _a2s(data.margin[0], data.anchor[0], pw);
+ float y = _a2s(data.margin[1], data.anchor[1], ph);
- float w=new_size.width;
- float h=new_size.height;
+ float w = new_size.width;
+ float h = new_size.height;
- data.margin[2] = _s2a( x+w, data.anchor[2], pw );
- data.margin[3] = _s2a( y+h, data.anchor[3], ph );
+ data.margin[2] = _s2a(x + w, data.anchor[2], pw);
+ data.margin[3] = _s2a(y + h, data.anchor[3], ph);
_size_changed();
-
}
-
Size2 Control::get_pos() const {
return data.pos_cache;
@@ -1551,71 +1470,67 @@ Size2 Control::get_size() const {
Rect2 Control::get_global_rect() const {
- return Rect2( get_global_pos(), get_size() );
+ return Rect2(get_global_pos(), get_size());
}
Rect2 Control::get_window_rect() const {
- ERR_FAIL_COND_V(!is_inside_tree(),Rect2());
+ ERR_FAIL_COND_V(!is_inside_tree(), Rect2());
Rect2 gr = get_global_rect();
- gr.pos+=get_viewport()->get_visible_rect().pos;
+ gr.pos += get_viewport()->get_visible_rect().pos;
return gr;
}
-
Rect2 Control::get_rect() const {
- return Rect2(get_pos(),get_size());
+ return Rect2(get_pos(), get_size());
}
Rect2 Control::get_item_rect() const {
- return Rect2(Point2(),get_size());
+ return Rect2(Point2(), get_size());
}
void Control::set_area_as_parent_rect(int p_margin) {
- data.anchor[MARGIN_LEFT]=ANCHOR_BEGIN;
- data.anchor[MARGIN_TOP]=ANCHOR_BEGIN;
- data.anchor[MARGIN_RIGHT]=ANCHOR_END;
- data.anchor[MARGIN_BOTTOM]=ANCHOR_END;
- for(int i=0;i<4;i++)
- data.margin[i]=p_margin;
+ data.anchor[MARGIN_LEFT] = ANCHOR_BEGIN;
+ data.anchor[MARGIN_TOP] = ANCHOR_BEGIN;
+ data.anchor[MARGIN_RIGHT] = ANCHOR_END;
+ data.anchor[MARGIN_BOTTOM] = ANCHOR_END;
+ for (int i = 0; i < 4; i++)
+ data.margin[i] = p_margin;
_size_changed();
-
}
-void Control::add_icon_override(const StringName& p_name, const Ref<Texture>& p_icon) {
+void Control::add_icon_override(const StringName &p_name, const Ref<Texture> &p_icon) {
ERR_FAIL_COND(p_icon.is_null());
- data.icon_override[p_name]=p_icon;
+ data.icon_override[p_name] = p_icon;
notification(NOTIFICATION_THEME_CHANGED);
update();
-
}
void Control::add_shader_override(const StringName &p_name, const Ref<Shader> &p_shader) {
ERR_FAIL_COND(p_shader.is_null());
- data.shader_override[p_name]=p_shader;
+ data.shader_override[p_name] = p_shader;
notification(NOTIFICATION_THEME_CHANGED);
update();
}
-void Control::add_style_override(const StringName& p_name, const Ref<StyleBox>& p_style) {
+void Control::add_style_override(const StringName &p_name, const Ref<StyleBox> &p_style) {
ERR_FAIL_COND(p_style.is_null());
- data.style_override[p_name]=p_style;
+ data.style_override[p_name] = p_style;
notification(NOTIFICATION_THEME_CHANGED);
update();
}
-
-void Control::add_font_override(const StringName& p_name, const Ref<Font>& p_font) {
+void Control::add_font_override(const StringName &p_name, const Ref<Font> &p_font) {
ERR_FAIL_COND(p_font.is_null());
if (data.font_override.has(p_name)) {
_unref_font(data.font_override[p_name]);
}
- data.font_override[p_name]=p_font;
+ data.font_override[p_name] = p_font;
if (p_font.is_valid()) {
_ref_font(p_font);
@@ -1624,26 +1539,25 @@ void Control::add_font_override(const StringName& p_name, const Ref<Font>& p_fon
notification(NOTIFICATION_THEME_CHANGED);
update();
}
-void Control::add_color_override(const StringName& p_name, const Color& p_color) {
+void Control::add_color_override(const StringName &p_name, const Color &p_color) {
- data.color_override[p_name]=p_color;
+ data.color_override[p_name] = p_color;
notification(NOTIFICATION_THEME_CHANGED);
update();
}
-void Control::add_constant_override(const StringName& p_name, int p_constant) {
+void Control::add_constant_override(const StringName &p_name, int p_constant) {
- data.constant_override[p_name]=p_constant;
+ data.constant_override[p_name] = p_constant;
notification(NOTIFICATION_THEME_CHANGED);
update();
}
void Control::set_focus_mode(FocusMode p_focus_mode) {
- if (is_inside_tree() && p_focus_mode == FOCUS_NONE && data.focus_mode!=FOCUS_NONE && has_focus())
+ if (is_inside_tree() && p_focus_mode == FOCUS_NONE && data.focus_mode != FOCUS_NONE && has_focus())
release_focus();
- data.focus_mode=p_focus_mode;
-
+ data.focus_mode = p_focus_mode;
}
static Control *_next_control(Control *p_from) {
@@ -1651,17 +1565,16 @@ static Control *_next_control(Control *p_from) {
if (p_from->is_set_as_toplevel())
return NULL; // can't go above
- Control *parent = p_from->get_parent()?p_from->get_parent()->cast_to<Control>():NULL;
+ Control *parent = p_from->get_parent() ? p_from->get_parent()->cast_to<Control>() : NULL;
if (!parent) {
return NULL;
}
-
int next = p_from->get_position_in_parent();
- ERR_FAIL_INDEX_V(next,parent->get_child_count(),NULL);
- for(int i=(next+1);i<parent->get_child_count();i++) {
+ ERR_FAIL_INDEX_V(next, parent->get_child_count(), NULL);
+ for (int i = (next + 1); i < parent->get_child_count(); i++) {
Control *c = parent->get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree() || c->is_set_as_toplevel())
@@ -1676,24 +1589,22 @@ static Control *_next_control(Control *p_from) {
Control *Control::find_next_valid_focus() const {
- Control *from = const_cast<Control*>(this);
-
- while(true) {
+ Control *from = const_cast<Control *>(this);
+ while (true) {
// find next child
- Control *next_child=NULL;
+ Control *next_child = NULL;
-
- for(int i=0;i<from->get_child_count();i++) {
+ for (int i = 0; i < from->get_child_count(); i++) {
Control *c = from->get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree() || c->is_set_as_toplevel()) {
continue;
}
- next_child=c;
+ next_child = c;
break;
}
@@ -1702,63 +1613,52 @@ Control *Control::find_next_valid_focus() const {
from = next_child;
} else {
- next_child=_next_control(from);
+ next_child = _next_control(from);
if (!next_child) { //nothing else.. go up and find either window or subwindow
- next_child=const_cast<Control*>(this);
- while(next_child && !next_child->is_set_as_toplevel()) {
+ next_child = const_cast<Control *>(this);
+ while (next_child && !next_child->is_set_as_toplevel()) {
if (next_child->get_parent()) {
- next_child=next_child->get_parent()->cast_to<Control>();
+ next_child = next_child->get_parent()->cast_to<Control>();
} else
- next_child=NULL;
-
+ next_child = NULL;
}
if (!next_child) {
- next_child=const_cast<Control*>(this);
- while(next_child) {
+ next_child = const_cast<Control *>(this);
+ while (next_child) {
if (next_child->data.SI || next_child->data.RI)
break;
- next_child=next_child->get_parent_control();
-
+ next_child = next_child->get_parent_control();
}
-
-
}
}
-
}
-
- if (next_child==this) // no next control->
- return (get_focus_mode()==FOCUS_ALL)?next_child:NULL;
+ if (next_child == this) // no next control->
+ return (get_focus_mode() == FOCUS_ALL) ? next_child : NULL;
if (next_child) {
- if (next_child->get_focus_mode()==FOCUS_ALL)
+ if (next_child->get_focus_mode() == FOCUS_ALL)
return next_child;
from = next_child;
- } else break;
+ } else
+ break;
}
return NULL;
-
-
}
-
-
-
static Control *_prev_control(Control *p_from) {
-
- Control *child=NULL;
- for(int i=p_from->get_child_count()-1;i>=0;i--) {
+ Control *child = NULL;
+ for (int i = p_from->get_child_count() - 1; i >= 0; i--) {
Control *c = p_from->get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree() || c->is_set_as_toplevel())
continue;
- child=c;
+ child = c;
break;
}
@@ -1770,72 +1670,57 @@ static Control *_prev_control(Control *p_from) {
}
Control *Control::find_prev_valid_focus() const {
- Control *from = const_cast<Control*>(this);
-
- while(true) {
+ Control *from = const_cast<Control *>(this);
+ while (true) {
// find prev child
+ Control *prev_child = NULL;
- Control *prev_child = NULL;
-
+ if (from->is_set_as_toplevel() || !from->get_parent() || !from->get_parent()->cast_to<Control>()) {
+ //find last of the childs
- if ( from->is_set_as_toplevel() || !from->get_parent() || !from->get_parent()->cast_to<Control>()) {
+ prev_child = _prev_control(from);
- //find last of the childs
-
- prev_child=_prev_control(from);
-
- } else {
-
- for(int i=(from->get_position_in_parent()-1);i>=0;i--) {
-
-
- Control *c = from->get_parent()->get_child(i)->cast_to<Control>();
+ } else {
- if (!c || !c->is_visible_in_tree() || c->is_set_as_toplevel()) {
- continue;
- }
+ for (int i = (from->get_position_in_parent() - 1); i >= 0; i--) {
- prev_child=c;
- break;
+ Control *c = from->get_parent()->get_child(i)->cast_to<Control>();
+ if (!c || !c->is_visible_in_tree() || c->is_set_as_toplevel()) {
+ continue;
}
- if (!prev_child) {
-
-
-
- prev_child = from->get_parent()->cast_to<Control>();
- } else {
-
-
-
- prev_child = _prev_control(prev_child);
- }
+ prev_child = c;
+ break;
}
+ if (!prev_child) {
+ prev_child = from->get_parent()->cast_to<Control>();
+ } else {
+ prev_child = _prev_control(prev_child);
+ }
+ }
- if (prev_child==this) // no prev control->
- return (get_focus_mode()==FOCUS_ALL)?prev_child:NULL;
-
- if (prev_child->get_focus_mode()==FOCUS_ALL)
- return prev_child;
+ if (prev_child == this) // no prev control->
+ return (get_focus_mode() == FOCUS_ALL) ? prev_child : NULL;
- from = prev_child;
+ if (prev_child->get_focus_mode() == FOCUS_ALL)
+ return prev_child;
- }
+ from = prev_child;
+ }
- return NULL;
+ return NULL;
return NULL;
}
-
Control::FocusMode Control::get_focus_mode() const {
return data.focus_mode;
@@ -1847,14 +1732,13 @@ bool Control::has_focus() const {
void Control::grab_focus() {
- if (!is_inside_tree()){
+ if (!is_inside_tree()) {
ERR_FAIL_COND(!is_inside_tree());
}
- if (data.focus_mode==FOCUS_NONE)
+ if (data.focus_mode == FOCUS_NONE)
return;
get_viewport()->_gui_control_grab_focus(this);
-
}
void Control::release_focus() {
@@ -1866,7 +1750,6 @@ void Control::release_focus() {
get_viewport()->_gui_remove_focus();
update();
-
}
bool Control::is_toplevel_control() const {
@@ -1882,105 +1765,94 @@ void Control::show_modal(bool p_exclusive) {
if (is_visible_in_tree())
hide();
- ERR_FAIL_COND( data.MI!=NULL );
+ ERR_FAIL_COND(data.MI != NULL);
show();
raise();
- data.modal_exclusive=p_exclusive;
- data.MI=get_viewport()->_gui_show_modal(this);
- data.modal_frame=Engine::get_singleton()->get_frames_drawn();
-
+ data.modal_exclusive = p_exclusive;
+ data.MI = get_viewport()->_gui_show_modal(this);
+ data.modal_frame = Engine::get_singleton()->get_frames_drawn();
}
void Control::_modal_set_prev_focus_owner(ObjectID p_prev) {
- data.modal_prev_focus_owner=p_prev;
+ data.modal_prev_focus_owner = p_prev;
}
void Control::_modal_stack_remove() {
-
ERR_FAIL_COND(!is_inside_tree());
if (!data.MI)
return;
- get_viewport()->_gui_remove_from_modal_stack(data.MI,data.modal_prev_focus_owner);
-
- data.MI=NULL;
- data.modal_prev_focus_owner=0;
+ get_viewport()->_gui_remove_from_modal_stack(data.MI, data.modal_prev_focus_owner);
+ data.MI = NULL;
+ data.modal_prev_focus_owner = 0;
}
-void Control::_propagate_theme_changed(CanvasItem *p_at,Control *p_owner,bool p_assign) {
+void Control::_propagate_theme_changed(CanvasItem *p_at, Control *p_owner, bool p_assign) {
Control *c = p_at->cast_to<Control>();
- if (c && c!=p_owner && c->data.theme.is_valid()) // has a theme, this can't be propagated
+ if (c && c != p_owner && c->data.theme.is_valid()) // has a theme, this can't be propagated
return;
- for(int i=0;i<p_at->get_child_count();i++) {
+ for (int i = 0; i < p_at->get_child_count(); i++) {
CanvasItem *child = p_at->get_child(i)->cast_to<CanvasItem>();
if (child) {
- _propagate_theme_changed(child,p_owner,p_assign);
+ _propagate_theme_changed(child, p_owner, p_assign);
}
-
}
-
if (c) {
if (p_assign) {
- c->data.theme_owner=p_owner;
+ c->data.theme_owner = p_owner;
}
c->notification(NOTIFICATION_THEME_CHANGED);
c->update();
}
}
-
void Control::_theme_changed() {
- _propagate_theme_changed(this,this,false);
+ _propagate_theme_changed(this, this, false);
}
-void Control::set_theme(const Ref<Theme>& p_theme) {
+void Control::set_theme(const Ref<Theme> &p_theme) {
-
- if (data.theme==p_theme)
+ if (data.theme == p_theme)
return;
if (data.theme.is_valid()) {
- data.theme->disconnect("changed",this,"_theme_changed");
+ data.theme->disconnect("changed", this, "_theme_changed");
}
- data.theme=p_theme;
+ data.theme = p_theme;
if (!p_theme.is_null()) {
- _propagate_theme_changed(this,this);
+ _propagate_theme_changed(this, this);
} else {
- Control *parent = get_parent()?get_parent()->cast_to<Control>():NULL;
+ Control *parent = get_parent() ? get_parent()->cast_to<Control>() : NULL;
if (parent && parent->data.theme_owner) {
- _propagate_theme_changed(this,parent->data.theme_owner);
+ _propagate_theme_changed(this, parent->data.theme_owner);
} else {
- _propagate_theme_changed(this,NULL);
+ _propagate_theme_changed(this, NULL);
}
-
}
if (data.theme.is_valid()) {
- data.theme->connect("changed",this,"_theme_changed");
+ data.theme->connect("changed", this, "_theme_changed");
}
-
}
void Control::accept_event() {
if (is_inside_tree())
get_viewport()->_gui_accept_event();
-
-
}
Ref<Theme> Control::get_theme() const {
@@ -1988,32 +1860,32 @@ Ref<Theme> Control::get_theme() const {
return data.theme;
}
-void Control::set_tooltip(const String& p_tooltip) {
+void Control::set_tooltip(const String &p_tooltip) {
- data.tooltip=p_tooltip;
+ data.tooltip = p_tooltip;
}
-String Control::get_tooltip(const Point2& p_pos) const {
+String Control::get_tooltip(const Point2 &p_pos) const {
return data.tooltip;
}
void Control::set_default_cursor_shape(CursorShape p_shape) {
- data.default_cursor=p_shape;
+ data.default_cursor = p_shape;
}
Control::CursorShape Control::get_default_cursor_shape() const {
return data.default_cursor;
}
-Control::CursorShape Control::get_cursor_shape(const Point2& p_pos) const {
+Control::CursorShape Control::get_cursor_shape(const Point2 &p_pos) const {
return data.default_cursor;
}
Transform2D Control::get_transform() const {
- Transform2D xform=Transform2D(data.rotation,get_pos());
+ Transform2D xform = Transform2D(data.rotation, get_pos());
xform.scale_basis(data.scale);
return xform;
}
@@ -2025,82 +1897,81 @@ String Control::_get_tooltip() const {
void Control::set_focus_neighbour(Margin p_margin, const NodePath &p_neighbour) {
- ERR_FAIL_INDEX(p_margin,4);
- data.focus_neighbour[p_margin]=p_neighbour;
+ ERR_FAIL_INDEX(p_margin, 4);
+ data.focus_neighbour[p_margin] = p_neighbour;
}
NodePath Control::get_focus_neighbour(Margin p_margin) const {
- ERR_FAIL_INDEX_V(p_margin,4,NodePath());
+ ERR_FAIL_INDEX_V(p_margin, 4, NodePath());
return data.focus_neighbour[p_margin];
}
#define MAX_NEIGHBOUR_SEARCH_COUNT 512
-Control *Control::_get_focus_neighbour(Margin p_margin,int p_count) {
+Control *Control::_get_focus_neighbour(Margin p_margin, int p_count) {
if (p_count >= MAX_NEIGHBOUR_SEARCH_COUNT)
return NULL;
if (!data.focus_neighbour[p_margin].is_empty()) {
- Control *c=NULL;
- Node * n = get_node(data.focus_neighbour[p_margin]);
+ Control *c = NULL;
+ Node *n = get_node(data.focus_neighbour[p_margin]);
if (n) {
- c=n->cast_to<Control>();
+ c = n->cast_to<Control>();
if (!c) {
- ERR_EXPLAIN("Next focus node is not a control: "+n->get_name());
+ ERR_EXPLAIN("Next focus node is not a control: " + n->get_name());
ERR_FAIL_V(NULL);
}
} else {
return NULL;
}
- bool valid=true;
+ bool valid = true;
if (!c->is_visible())
- valid=false;
- if (c->get_focus_mode()==FOCUS_NONE)
- valid=false;
+ valid = false;
+ if (c->get_focus_mode() == FOCUS_NONE)
+ valid = false;
if (valid)
return c;
- c=c->_get_focus_neighbour(p_margin,p_count+1);
+ c = c->_get_focus_neighbour(p_margin, p_count + 1);
return c;
}
-
- float dist=1e7;
- Control * result=NULL;
+ float dist = 1e7;
+ Control *result = NULL;
Point2 points[4];
Transform2D xform = get_global_transform();
Rect2 rect = get_item_rect();
- points[0]=xform.xform(rect.pos);
- points[1]=xform.xform(rect.pos + Point2(rect.size.x, 0));
- points[2]=xform.xform(rect.pos + rect.size);
- points[3]=xform.xform(rect.pos + Point2(0, rect.size.y));
+ points[0] = xform.xform(rect.pos);
+ points[1] = xform.xform(rect.pos + Point2(rect.size.x, 0));
+ points[2] = xform.xform(rect.pos + rect.size);
+ points[3] = xform.xform(rect.pos + Point2(0, rect.size.y));
- const Vector2 dir[4]={
- Vector2(-1,0),
- Vector2(0,-1),
- Vector2(1,0),
- Vector2(0,1)
+ const Vector2 dir[4] = {
+ Vector2(-1, 0),
+ Vector2(0, -1),
+ Vector2(1, 0),
+ Vector2(0, 1)
};
- Vector2 vdir=dir[p_margin];
+ Vector2 vdir = dir[p_margin];
- float maxd=-1e7;
+ float maxd = -1e7;
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
float d = vdir.dot(points[i]);
- if (d>maxd)
- maxd=d;
+ if (d > maxd)
+ maxd = d;
}
- Node *base=this;
+ Node *base = this;
while (base) {
@@ -2111,109 +1982,104 @@ Control *Control::_get_focus_neighbour(Margin p_margin,int p_count) {
if (c->data.RI)
break;
}
- base=base->get_parent();
+ base = base->get_parent();
}
if (!base)
return NULL;
- _window_find_focus_neighbour(vdir,base,points,maxd,dist,&result);
+ _window_find_focus_neighbour(vdir, base, points, maxd, dist, &result);
return result;
-
}
-void Control::_window_find_focus_neighbour(const Vector2& p_dir, Node *p_at,const Point2* p_points,float p_min ,float &r_closest_dist,Control **r_closest) {
+void Control::_window_find_focus_neighbour(const Vector2 &p_dir, Node *p_at, const Point2 *p_points, float p_min, float &r_closest_dist, Control **r_closest) {
if (p_at->cast_to<Viewport>())
return; //bye
Control *c = p_at->cast_to<Control>();
- if (c && c !=this && c->get_focus_mode()==FOCUS_ALL && c->is_visible_in_tree()) {
+ if (c && c != this && c->get_focus_mode() == FOCUS_ALL && c->is_visible_in_tree()) {
Point2 points[4];
Transform2D xform = c->get_global_transform();
Rect2 rect = c->get_item_rect();
- points[0]=xform.xform(rect.pos);
- points[1]=xform.xform(rect.pos + Point2(rect.size.x, 0));
- points[2]=xform.xform(rect.pos + rect.size);
- points[3]=xform.xform(rect.pos + Point2(0, rect.size.y));
+ points[0] = xform.xform(rect.pos);
+ points[1] = xform.xform(rect.pos + Point2(rect.size.x, 0));
+ points[2] = xform.xform(rect.pos + rect.size);
+ points[3] = xform.xform(rect.pos + Point2(0, rect.size.y));
+ float min = 1e7;
- float min=1e7;
-
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
float d = p_dir.dot(points[i]);
if (d < min)
- min =d;
+ min = d;
}
+ if (min > (p_min - CMP_EPSILON)) {
- if (min>(p_min-CMP_EPSILON)) {
-
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- Vector2 la=p_points[i];
- Vector2 lb=p_points[(i+1)%4];
+ Vector2 la = p_points[i];
+ Vector2 lb = p_points[(i + 1) % 4];
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- Vector2 fa=points[j];
- Vector2 fb=points[(j+1)%4];
+ Vector2 fa = points[j];
+ Vector2 fb = points[(j + 1) % 4];
- Vector2 pa,pb;
- float d=Geometry::get_closest_points_between_segments(la,lb,fa,fb,pa,pb);
+ Vector2 pa, pb;
+ float d = Geometry::get_closest_points_between_segments(la, lb, fa, fb, pa, pb);
//float d = Geometry::get_closest_distance_between_segments(Vector3(la.x,la.y,0),Vector3(lb.x,lb.y,0),Vector3(fa.x,fa.y,0),Vector3(fb.x,fb.y,0));
- if (d<r_closest_dist) {
- r_closest_dist=d;
- *r_closest=c;
+ if (d < r_closest_dist) {
+ r_closest_dist = d;
+ *r_closest = c;
}
}
}
}
-
}
- for(int i=0;i<p_at->get_child_count();i++) {
+ for (int i = 0; i < p_at->get_child_count(); i++) {
- Node *child=p_at->get_child(i);
+ Node *child = p_at->get_child(i);
Control *childc = child->cast_to<Control>();
if (childc && childc->data.SI)
continue; //subwindow, ignore
- _window_find_focus_neighbour(p_dir,p_at->get_child(i),p_points,p_min,r_closest_dist,r_closest);
+ _window_find_focus_neighbour(p_dir, p_at->get_child(i), p_points, p_min, r_closest_dist, r_closest);
}
}
void Control::set_h_size_flags(int p_flags) {
- if (data.h_size_flags==p_flags)
+ if (data.h_size_flags == p_flags)
return;
- data.h_size_flags=p_flags;
+ data.h_size_flags = p_flags;
emit_signal(SceneStringNames::get_singleton()->size_flags_changed);
}
-int Control::get_h_size_flags() const{
+int Control::get_h_size_flags() const {
return data.h_size_flags;
}
void Control::set_v_size_flags(int p_flags) {
- if (data.v_size_flags==p_flags)
+ if (data.v_size_flags == p_flags)
return;
- data.v_size_flags=p_flags;
+ data.v_size_flags = p_flags;
emit_signal(SceneStringNames::get_singleton()->size_flags_changed);
}
-
void Control::set_stretch_ratio(float p_ratio) {
- if (data.expand==p_ratio)
+ if (data.expand == p_ratio)
return;
- data.expand=p_ratio;
+ data.expand = p_ratio;
emit_signal(SceneStringNames::get_singleton()->size_flags_changed);
}
@@ -2222,13 +2088,11 @@ float Control::get_stretch_ratio() const {
return data.expand;
}
-
void Control::grab_click_focus() {
ERR_FAIL_COND(!is_inside_tree());
get_viewport()->_gui_grab_click_focus(this);
-
}
void Control::minimum_size_changed() {
@@ -2239,9 +2103,8 @@ void Control::minimum_size_changed() {
if (data.pending_min_size_update)
return;
-
- data.pending_min_size_update=true;
- MessageQueue::get_singleton()->push_call(this,"_update_minimum_size");
+ data.pending_min_size_update = true;
+ MessageQueue::get_singleton()->push_call(this, "_update_minimum_size");
if (!is_toplevel_control()) {
Control *pc = get_parent_control();
@@ -2250,37 +2113,34 @@ void Control::minimum_size_changed() {
}
}
-int Control::get_v_size_flags() const{
+int Control::get_v_size_flags() const {
return data.v_size_flags;
}
void Control::set_mouse_filter(MouseFilter p_filter) {
- ERR_FAIL_INDEX(p_filter,3);
- data.mouse_filter=p_filter;
+ ERR_FAIL_INDEX(p_filter, 3);
+ data.mouse_filter = p_filter;
}
-Control::MouseFilter Control::get_mouse_filter() const{
+Control::MouseFilter Control::get_mouse_filter() const {
return data.mouse_filter;
}
-
Control *Control::get_focus_owner() const {
- ERR_FAIL_COND_V(!is_inside_tree(),NULL);
+ ERR_FAIL_COND_V(!is_inside_tree(), NULL);
return get_viewport()->_gui_get_focus_owner();
}
-
-void Control::warp_mouse(const Point2& p_to_pos) {
+void Control::warp_mouse(const Point2 &p_to_pos) {
ERR_FAIL_COND(!is_inside_tree());
get_viewport()->warp_mouse(get_global_transform().xform(p_to_pos));
}
-
bool Control::is_text_field() const {
-/*
+ /*
if (get_script_instance()) {
Variant v=p_point;
const Variant *p[2]={&v,&p_data};
@@ -2290,19 +2150,18 @@ bool Control::is_text_field() const {
return ret;
}
*/
- return false;
+ return false;
}
-
void Control::set_rotation(float p_radians) {
- data.rotation=p_radians;
+ data.rotation = p_radians;
update();
_notify_transform();
_change_notify("rect/rotation");
}
-float Control::get_rotation() const{
+float Control::get_rotation() const {
return data.rotation;
}
@@ -2326,13 +2185,13 @@ float Control::_get_rotation_deg() const {
return get_rotation_deg();
}
//needed to update the control if the font changes..
-void Control::_ref_font( Ref<Font> p_sc) {
+void Control::_ref_font(Ref<Font> p_sc) {
if (!data.font_refcount.has(p_sc)) {
- data.font_refcount[p_sc]=1;
- p_sc->connect("changed",this,"_font_changed");
+ data.font_refcount[p_sc] = 1;
+ p_sc->connect("changed", this, "_font_changed");
} else {
- data.font_refcount[p_sc]+=1;
+ data.font_refcount[p_sc] += 1;
}
}
@@ -2340,53 +2199,53 @@ void Control::_unref_font(Ref<Font> p_sc) {
ERR_FAIL_COND(!data.font_refcount.has(p_sc));
data.font_refcount[p_sc]--;
- if (data.font_refcount[p_sc]==0) {
- p_sc->disconnect("changed",this,"_font_changed");
+ if (data.font_refcount[p_sc] == 0) {
+ p_sc->disconnect("changed", this, "_font_changed");
data.font_refcount.erase(p_sc);
}
}
-void Control::_font_changed(){
+void Control::_font_changed() {
update();
notification(NOTIFICATION_THEME_CHANGED);
minimum_size_changed(); //fonts affect minimum size pretty much almost always
}
-void Control::set_scale(const Vector2& p_scale){
+void Control::set_scale(const Vector2 &p_scale) {
- data.scale=p_scale;
+ data.scale = p_scale;
update();
_notify_transform();
}
-Vector2 Control::get_scale() const{
+Vector2 Control::get_scale() const {
return data.scale;
}
Control *Control::get_root_parent_control() const {
- const CanvasItem *ci=this;
- const Control *root=this;
+ const CanvasItem *ci = this;
+ const Control *root = this;
- while(ci) {
+ while (ci) {
const Control *c = ci->cast_to<Control>();
if (c) {
- root=c;
+ root = c;
if (c->data.RI || c->data.MI || c->is_toplevel_control())
break;
}
- ci=ci->get_parent_item();
+ ci = ci->get_parent_item();
}
- return const_cast<Control*>(root);
+ return const_cast<Control *>(root);
}
void Control::set_block_minimum_size_adjust(bool p_block) {
- data.block_minimum_size_adjust=p_block;
+ data.block_minimum_size_adjust = p_block;
}
bool Control::is_minimum_size_adjust_blocked() const {
@@ -2394,10 +2253,9 @@ bool Control::is_minimum_size_adjust_blocked() const {
return data.block_minimum_size_adjust;
}
-
void Control::set_disable_visibility_clip(bool p_ignore) {
- data.disable_visibility_clip=p_ignore;
+ data.disable_visibility_clip = p_ignore;
update();
}
@@ -2406,34 +2264,32 @@ bool Control::is_visibility_clip_disabled() const {
return data.disable_visibility_clip;
}
-void Control::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
+void Control::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
- Node::get_argument_options(p_function,p_idx,r_options);
+ Node::get_argument_options(p_function, p_idx, r_options);
- if (p_idx==0) {
+ if (p_idx == 0) {
List<StringName> sn;
String pf = p_function;
- if (pf=="add_color_override" || pf=="has_color" || pf=="has_color_override" || pf=="get_color") {
- Theme::get_default()->get_color_list(get_class(),&sn);
- } else if (pf=="add_style_override" || pf=="has_style" || pf=="has_style_override" || pf=="get_style") {
- Theme::get_default()->get_stylebox_list(get_class(),&sn);
- } else if (pf=="add_font_override" || pf=="has_font" || pf=="has_font_override" || pf=="get_font") {
- Theme::get_default()->get_font_list(get_class(),&sn);
- } else if (pf=="add_constant_override" || pf=="has_constant" || pf=="has_constant_override" || pf=="get_constant") {
- Theme::get_default()->get_constant_list(get_class(),&sn);
+ if (pf == "add_color_override" || pf == "has_color" || pf == "has_color_override" || pf == "get_color") {
+ Theme::get_default()->get_color_list(get_class(), &sn);
+ } else if (pf == "add_style_override" || pf == "has_style" || pf == "has_style_override" || pf == "get_style") {
+ Theme::get_default()->get_stylebox_list(get_class(), &sn);
+ } else if (pf == "add_font_override" || pf == "has_font" || pf == "has_font_override" || pf == "get_font") {
+ Theme::get_default()->get_font_list(get_class(), &sn);
+ } else if (pf == "add_constant_override" || pf == "has_constant" || pf == "has_constant_override" || pf == "get_constant") {
+ Theme::get_default()->get_constant_list(get_class(), &sn);
}
sn.sort_custom<StringName::AlphCompare>();
- for (List<StringName>::Element *E=sn.front();E;E=E->next()) {
- r_options->push_back("\""+E->get()+"\"");
+ for (List<StringName>::Element *E = sn.front(); E; E = E->next()) {
+ r_options->push_back("\"" + E->get() + "\"");
}
}
-
-
}
void Control::set_clip_contents(bool p_clip) {
- data.clip_contents=p_clip;
+ data.clip_contents = p_clip;
update();
}
@@ -2442,81 +2298,79 @@ bool Control::is_clipping_contents() {
return data.clip_contents;
}
-
void Control::_bind_methods() {
-
//ClassDB::bind_method(D_METHOD("_window_resize_event"),&Control::_window_resize_event);
- ClassDB::bind_method(D_METHOD("_size_changed"),&Control::_size_changed);
- ClassDB::bind_method(D_METHOD("_update_minimum_size"),&Control::_update_minimum_size);
-
- ClassDB::bind_method(D_METHOD("accept_event"),&Control::accept_event);
- ClassDB::bind_method(D_METHOD("get_minimum_size"),&Control::get_minimum_size);
- ClassDB::bind_method(D_METHOD("get_combined_minimum_size"),&Control::get_combined_minimum_size);
- ClassDB::bind_method(D_METHOD("set_anchor","margin","anchor_mode","keep_margin"),&Control::set_anchor,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("_set_anchor","margin","anchor_mode"),&Control::_set_anchor);
- ClassDB::bind_method(D_METHOD("get_anchor","margin"),&Control::get_anchor);
- ClassDB::bind_method(D_METHOD("set_margin","margin","offset"),&Control::set_margin);
- ClassDB::bind_method(D_METHOD("set_anchor_and_margin","margin","anchor_mode","offset"),&Control::set_anchor_and_margin);
- ClassDB::bind_method(D_METHOD("set_begin","pos"),&Control::set_begin);
- ClassDB::bind_method(D_METHOD("set_end","pos"),&Control::set_end);
- ClassDB::bind_method(D_METHOD("set_pos","pos"),&Control::set_pos);
- ClassDB::bind_method(D_METHOD("set_size","size"),&Control::set_size);
- ClassDB::bind_method(D_METHOD("set_custom_minimum_size","size"),&Control::set_custom_minimum_size);
- ClassDB::bind_method(D_METHOD("set_global_pos","pos"),&Control::set_global_pos);
- ClassDB::bind_method(D_METHOD("set_rotation","radians"),&Control::set_rotation);
- ClassDB::bind_method(D_METHOD("set_rotation_deg","degrees"),&Control::set_rotation_deg);
+ ClassDB::bind_method(D_METHOD("_size_changed"), &Control::_size_changed);
+ ClassDB::bind_method(D_METHOD("_update_minimum_size"), &Control::_update_minimum_size);
+
+ ClassDB::bind_method(D_METHOD("accept_event"), &Control::accept_event);
+ ClassDB::bind_method(D_METHOD("get_minimum_size"), &Control::get_minimum_size);
+ ClassDB::bind_method(D_METHOD("get_combined_minimum_size"), &Control::get_combined_minimum_size);
+ ClassDB::bind_method(D_METHOD("set_anchor", "margin", "anchor_mode", "keep_margin"), &Control::set_anchor, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("_set_anchor", "margin", "anchor_mode"), &Control::_set_anchor);
+ ClassDB::bind_method(D_METHOD("get_anchor", "margin"), &Control::get_anchor);
+ ClassDB::bind_method(D_METHOD("set_margin", "margin", "offset"), &Control::set_margin);
+ ClassDB::bind_method(D_METHOD("set_anchor_and_margin", "margin", "anchor_mode", "offset"), &Control::set_anchor_and_margin);
+ ClassDB::bind_method(D_METHOD("set_begin", "pos"), &Control::set_begin);
+ ClassDB::bind_method(D_METHOD("set_end", "pos"), &Control::set_end);
+ ClassDB::bind_method(D_METHOD("set_pos", "pos"), &Control::set_pos);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &Control::set_size);
+ ClassDB::bind_method(D_METHOD("set_custom_minimum_size", "size"), &Control::set_custom_minimum_size);
+ ClassDB::bind_method(D_METHOD("set_global_pos", "pos"), &Control::set_global_pos);
+ ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &Control::set_rotation);
+ ClassDB::bind_method(D_METHOD("set_rotation_deg", "degrees"), &Control::set_rotation_deg);
// TODO: Obsolete this method (old name) properly (GH-4397)
- ClassDB::bind_method(D_METHOD("_set_rotation_deg","degrees"),&Control::_set_rotation_deg);
- ClassDB::bind_method(D_METHOD("set_scale","scale"),&Control::set_scale);
- ClassDB::bind_method(D_METHOD("get_margin","margin"),&Control::get_margin);
- ClassDB::bind_method(D_METHOD("get_begin"),&Control::get_begin);
- ClassDB::bind_method(D_METHOD("get_end"),&Control::get_end);
- ClassDB::bind_method(D_METHOD("get_pos"),&Control::get_pos);
- ClassDB::bind_method(D_METHOD("get_size"),&Control::get_size);
- ClassDB::bind_method(D_METHOD("get_rotation"),&Control::get_rotation);
- ClassDB::bind_method(D_METHOD("get_rotation_deg"),&Control::get_rotation_deg);
+ ClassDB::bind_method(D_METHOD("_set_rotation_deg", "degrees"), &Control::_set_rotation_deg);
+ ClassDB::bind_method(D_METHOD("set_scale", "scale"), &Control::set_scale);
+ ClassDB::bind_method(D_METHOD("get_margin", "margin"), &Control::get_margin);
+ ClassDB::bind_method(D_METHOD("get_begin"), &Control::get_begin);
+ ClassDB::bind_method(D_METHOD("get_end"), &Control::get_end);
+ ClassDB::bind_method(D_METHOD("get_pos"), &Control::get_pos);
+ ClassDB::bind_method(D_METHOD("get_size"), &Control::get_size);
+ ClassDB::bind_method(D_METHOD("get_rotation"), &Control::get_rotation);
+ ClassDB::bind_method(D_METHOD("get_rotation_deg"), &Control::get_rotation_deg);
// TODO: Obsolete this method (old name) properly (GH-4397)
- ClassDB::bind_method(D_METHOD("_get_rotation_deg"),&Control::_get_rotation_deg);
- ClassDB::bind_method(D_METHOD("get_scale"),&Control::get_scale);
- ClassDB::bind_method(D_METHOD("get_custom_minimum_size"),&Control::get_custom_minimum_size);
- ClassDB::bind_method(D_METHOD("get_parent_area_size"),&Control::get_size);
- ClassDB::bind_method(D_METHOD("get_global_pos"),&Control::get_global_pos);
- ClassDB::bind_method(D_METHOD("get_rect"),&Control::get_rect);
- ClassDB::bind_method(D_METHOD("get_global_rect"),&Control::get_global_rect);
- ClassDB::bind_method(D_METHOD("set_area_as_parent_rect","margin"),&Control::set_area_as_parent_rect,DEFVAL(0));
- ClassDB::bind_method(D_METHOD("show_modal","exclusive"),&Control::show_modal,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("set_focus_mode","mode"),&Control::set_focus_mode);
- ClassDB::bind_method(D_METHOD("get_focus_mode"),&Control::get_focus_mode);
- ClassDB::bind_method(D_METHOD("has_focus"),&Control::has_focus);
- ClassDB::bind_method(D_METHOD("grab_focus"),&Control::grab_focus);
- ClassDB::bind_method(D_METHOD("release_focus"),&Control::release_focus);
- ClassDB::bind_method(D_METHOD("get_focus_owner:Control"),&Control::get_focus_owner);
-
- ClassDB::bind_method(D_METHOD("set_h_size_flags","flags"),&Control::set_h_size_flags);
- ClassDB::bind_method(D_METHOD("get_h_size_flags"),&Control::get_h_size_flags);
-
- ClassDB::bind_method(D_METHOD("set_stretch_ratio","ratio"),&Control::set_stretch_ratio);
- ClassDB::bind_method(D_METHOD("get_stretch_ratio"),&Control::get_stretch_ratio);
-
- ClassDB::bind_method(D_METHOD("set_v_size_flags","flags"),&Control::set_v_size_flags);
- ClassDB::bind_method(D_METHOD("get_v_size_flags"),&Control::get_v_size_flags);
-
- ClassDB::bind_method(D_METHOD("set_theme","theme:Theme"),&Control::set_theme);
- ClassDB::bind_method(D_METHOD("get_theme:Theme"),&Control::get_theme);
-
- ClassDB::bind_method(D_METHOD("add_icon_override","name","texture:Texture"),&Control::add_icon_override);
- ClassDB::bind_method(D_METHOD("add_shader_override","name","shader:Shader"),&Control::add_shader_override);
- ClassDB::bind_method(D_METHOD("add_style_override","name","stylebox:StyleBox"),&Control::add_style_override);
- ClassDB::bind_method(D_METHOD("add_font_override","name","font:Font"),&Control::add_font_override);
- ClassDB::bind_method(D_METHOD("add_color_override","name","color"),&Control::add_color_override);
- ClassDB::bind_method(D_METHOD("add_constant_override","name","constant"),&Control::add_constant_override);
-
- ClassDB::bind_method(D_METHOD("get_icon:Texture","name","type"),&Control::get_icon,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox","name","type"),&Control::get_stylebox,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_font:Font","name","type"),&Control::get_font,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_color","name","type"),&Control::get_color,DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_constant","name","type"),&Control::get_constant,DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("_get_rotation_deg"), &Control::_get_rotation_deg);
+ ClassDB::bind_method(D_METHOD("get_scale"), &Control::get_scale);
+ ClassDB::bind_method(D_METHOD("get_custom_minimum_size"), &Control::get_custom_minimum_size);
+ ClassDB::bind_method(D_METHOD("get_parent_area_size"), &Control::get_size);
+ ClassDB::bind_method(D_METHOD("get_global_pos"), &Control::get_global_pos);
+ ClassDB::bind_method(D_METHOD("get_rect"), &Control::get_rect);
+ ClassDB::bind_method(D_METHOD("get_global_rect"), &Control::get_global_rect);
+ ClassDB::bind_method(D_METHOD("set_area_as_parent_rect", "margin"), &Control::set_area_as_parent_rect, DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("show_modal", "exclusive"), &Control::show_modal, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("set_focus_mode", "mode"), &Control::set_focus_mode);
+ ClassDB::bind_method(D_METHOD("get_focus_mode"), &Control::get_focus_mode);
+ ClassDB::bind_method(D_METHOD("has_focus"), &Control::has_focus);
+ ClassDB::bind_method(D_METHOD("grab_focus"), &Control::grab_focus);
+ ClassDB::bind_method(D_METHOD("release_focus"), &Control::release_focus);
+ ClassDB::bind_method(D_METHOD("get_focus_owner:Control"), &Control::get_focus_owner);
+
+ ClassDB::bind_method(D_METHOD("set_h_size_flags", "flags"), &Control::set_h_size_flags);
+ ClassDB::bind_method(D_METHOD("get_h_size_flags"), &Control::get_h_size_flags);
+
+ ClassDB::bind_method(D_METHOD("set_stretch_ratio", "ratio"), &Control::set_stretch_ratio);
+ ClassDB::bind_method(D_METHOD("get_stretch_ratio"), &Control::get_stretch_ratio);
+
+ ClassDB::bind_method(D_METHOD("set_v_size_flags", "flags"), &Control::set_v_size_flags);
+ ClassDB::bind_method(D_METHOD("get_v_size_flags"), &Control::get_v_size_flags);
+
+ ClassDB::bind_method(D_METHOD("set_theme", "theme:Theme"), &Control::set_theme);
+ ClassDB::bind_method(D_METHOD("get_theme:Theme"), &Control::get_theme);
+
+ ClassDB::bind_method(D_METHOD("add_icon_override", "name", "texture:Texture"), &Control::add_icon_override);
+ ClassDB::bind_method(D_METHOD("add_shader_override", "name", "shader:Shader"), &Control::add_shader_override);
+ ClassDB::bind_method(D_METHOD("add_style_override", "name", "stylebox:StyleBox"), &Control::add_style_override);
+ ClassDB::bind_method(D_METHOD("add_font_override", "name", "font:Font"), &Control::add_font_override);
+ ClassDB::bind_method(D_METHOD("add_color_override", "name", "color"), &Control::add_color_override);
+ ClassDB::bind_method(D_METHOD("add_constant_override", "name", "constant"), &Control::add_constant_override);
+
+ ClassDB::bind_method(D_METHOD("get_icon:Texture", "name", "type"), &Control::get_icon, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox", "name", "type"), &Control::get_stylebox, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("get_font:Font", "name", "type"), &Control::get_font, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("get_color", "name", "type"), &Control::get_color, DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("get_constant", "name", "type"), &Control::get_constant, DEFVAL(""));
ClassDB::bind_method(D_METHOD("has_icon_override", "name"), &Control::has_icon_override);
ClassDB::bind_method(D_METHOD("has_stylebox_override", "name"), &Control::has_stylebox_override);
@@ -2530,183 +2384,170 @@ void Control::_bind_methods() {
ClassDB::bind_method(D_METHOD("has_color", "name", "type"), &Control::has_color, DEFVAL(""));
ClassDB::bind_method(D_METHOD("has_constant", "name", "type"), &Control::has_constant, DEFVAL(""));
- ClassDB::bind_method(D_METHOD("get_parent_control:Control"),&Control::get_parent_control);
+ ClassDB::bind_method(D_METHOD("get_parent_control:Control"), &Control::get_parent_control);
- ClassDB::bind_method(D_METHOD("set_tooltip","tooltip"),&Control::set_tooltip);
- ClassDB::bind_method(D_METHOD("get_tooltip","atpos"),&Control::get_tooltip,DEFVAL(Point2()));
- ClassDB::bind_method(D_METHOD("_get_tooltip"),&Control::_get_tooltip);
+ ClassDB::bind_method(D_METHOD("set_tooltip", "tooltip"), &Control::set_tooltip);
+ ClassDB::bind_method(D_METHOD("get_tooltip", "atpos"), &Control::get_tooltip, DEFVAL(Point2()));
+ ClassDB::bind_method(D_METHOD("_get_tooltip"), &Control::_get_tooltip);
- ClassDB::bind_method(D_METHOD("set_default_cursor_shape","shape"),&Control::set_default_cursor_shape);
- ClassDB::bind_method(D_METHOD("get_default_cursor_shape"),&Control::get_default_cursor_shape);
- ClassDB::bind_method(D_METHOD("get_cursor_shape","pos"),&Control::get_cursor_shape,DEFVAL(Point2()));
+ ClassDB::bind_method(D_METHOD("set_default_cursor_shape", "shape"), &Control::set_default_cursor_shape);
+ ClassDB::bind_method(D_METHOD("get_default_cursor_shape"), &Control::get_default_cursor_shape);
+ ClassDB::bind_method(D_METHOD("get_cursor_shape", "pos"), &Control::get_cursor_shape, DEFVAL(Point2()));
- ClassDB::bind_method(D_METHOD("set_focus_neighbour","margin","neighbour"),&Control::set_focus_neighbour);
- ClassDB::bind_method(D_METHOD("get_focus_neighbour","margin"),&Control::get_focus_neighbour);
+ ClassDB::bind_method(D_METHOD("set_focus_neighbour", "margin", "neighbour"), &Control::set_focus_neighbour);
+ ClassDB::bind_method(D_METHOD("get_focus_neighbour", "margin"), &Control::get_focus_neighbour);
- ClassDB::bind_method(D_METHOD("force_drag","data","preview"),&Control::force_drag);
+ ClassDB::bind_method(D_METHOD("force_drag", "data", "preview"), &Control::force_drag);
- ClassDB::bind_method(D_METHOD("set_mouse_filter","filter"),&Control::set_mouse_filter);
- ClassDB::bind_method(D_METHOD("get_mouse_filter"),&Control::get_mouse_filter);
+ ClassDB::bind_method(D_METHOD("set_mouse_filter", "filter"), &Control::set_mouse_filter);
+ ClassDB::bind_method(D_METHOD("get_mouse_filter"), &Control::get_mouse_filter);
- ClassDB::bind_method(D_METHOD("set_clip_contents","enable"),&Control::set_clip_contents);
- ClassDB::bind_method(D_METHOD("is_clipping_contents"),&Control::is_clipping_contents);
+ ClassDB::bind_method(D_METHOD("set_clip_contents", "enable"), &Control::set_clip_contents);
+ ClassDB::bind_method(D_METHOD("is_clipping_contents"), &Control::is_clipping_contents);
- ClassDB::bind_method(D_METHOD("grab_click_focus"),&Control::grab_click_focus);
+ ClassDB::bind_method(D_METHOD("grab_click_focus"), &Control::grab_click_focus);
- ClassDB::bind_method(D_METHOD("set_drag_forwarding","target:Control"),&Control::set_drag_forwarding);
- ClassDB::bind_method(D_METHOD("set_drag_preview","control:Control"),&Control::set_drag_preview);
+ ClassDB::bind_method(D_METHOD("set_drag_forwarding", "target:Control"), &Control::set_drag_forwarding);
+ ClassDB::bind_method(D_METHOD("set_drag_preview", "control:Control"), &Control::set_drag_preview);
- ClassDB::bind_method(D_METHOD("warp_mouse","to_pos"),&Control::warp_mouse);
+ ClassDB::bind_method(D_METHOD("warp_mouse", "to_pos"), &Control::warp_mouse);
ClassDB::bind_method(D_METHOD("minimum_size_changed"), &Control::minimum_size_changed);
ClassDB::bind_method(D_METHOD("_theme_changed"), &Control::_theme_changed);
-
-
ClassDB::bind_method(D_METHOD("_font_changed"), &Control::_font_changed);
- BIND_VMETHOD(MethodInfo("_gui_input",PropertyInfo(Variant::INPUT_EVENT,"event")));
- BIND_VMETHOD(MethodInfo(Variant::VECTOR2,"get_minimum_size"));
- BIND_VMETHOD(MethodInfo(Variant::OBJECT,"get_drag_data",PropertyInfo(Variant::VECTOR2,"pos")));
- BIND_VMETHOD(MethodInfo(Variant::BOOL,"can_drop_data",PropertyInfo(Variant::VECTOR2,"pos"),PropertyInfo(Variant::NIL,"data")));
- BIND_VMETHOD(MethodInfo("drop_data",PropertyInfo(Variant::VECTOR2,"pos"),PropertyInfo(Variant::NIL,"data")));
-
- ADD_GROUP("Anchor","anchor_");
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"anchor_left", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor","get_anchor", MARGIN_LEFT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"anchor_top", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor","get_anchor", MARGIN_TOP );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"anchor_right", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor","get_anchor", MARGIN_RIGHT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"anchor_bottom", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor","get_anchor", MARGIN_BOTTOM );
-
- ADD_GROUP("Margin","margin_");
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"margin_left", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin","get_margin",MARGIN_LEFT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"margin_top", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin","get_margin",MARGIN_TOP );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"margin_right", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin","get_margin",MARGIN_RIGHT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::INT,"margin_bottom", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin","get_margin",MARGIN_BOTTOM );
-
- ADD_GROUP("Rect","rect_");
- ADD_PROPERTYNZ( PropertyInfo(Variant::VECTOR2,"rect_pos", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_EDITOR), "set_pos","get_pos") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::VECTOR2,"rect_size", PROPERTY_HINT_NONE, "",PROPERTY_USAGE_EDITOR), "set_size","get_size") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::VECTOR2,"rect_min_size"), "set_custom_minimum_size","get_custom_minimum_size") ;
- ADD_PROPERTYNZ( PropertyInfo(Variant::REAL,"rect_rotation",PROPERTY_HINT_RANGE,"-1080,1080,0.01"), "set_rotation_deg","get_rotation_deg") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::VECTOR2,"rect_scale"), "set_scale","get_scale") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL,"rect_clip_content"), "set_clip_contents","is_clipping_contents") ;
-
-
- ADD_GROUP("Hint","hint_");
- ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"hint_tooltip", PROPERTY_HINT_MULTILINE_TEXT), "set_tooltip","_get_tooltip") ;
-
- ADD_GROUP("Focus","focus_");
- ADD_PROPERTYINZ( PropertyInfo(Variant::NODE_PATH,"focus_neighbour_left" ), "set_focus_neighbour","get_focus_neighbour",MARGIN_LEFT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::NODE_PATH,"focus_neighbour_top" ), "set_focus_neighbour","get_focus_neighbour",MARGIN_TOP );
- ADD_PROPERTYINZ( PropertyInfo(Variant::NODE_PATH,"focus_neighbour_right" ), "set_focus_neighbour","get_focus_neighbour",MARGIN_RIGHT );
- ADD_PROPERTYINZ( PropertyInfo(Variant::NODE_PATH,"focus_neighbour_bottom" ), "set_focus_neighbour","get_focus_neighbour",MARGIN_BOTTOM );
-
- ADD_GROUP("Mouse","mouse_");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"mouse_filter",PROPERTY_HINT_ENUM,"Stop,Pass,Ignore"), "set_mouse_filter","get_mouse_filter") ;
-
- ADD_GROUP("Size Flags","size_flags_");
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"size_flags_horizontal", PROPERTY_HINT_FLAGS, "Fill,Expand"), "set_h_size_flags","get_h_size_flags") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"size_flags_vertical", PROPERTY_HINT_FLAGS, "Fill,Expand"), "set_v_size_flags","get_v_size_flags") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::INT,"size_flags_stretch_ratio", PROPERTY_HINT_RANGE, "1,128,0.01"), "set_stretch_ratio","get_stretch_ratio") ;
- ADD_GROUP("Theme","");
- ADD_PROPERTYNZ( PropertyInfo(Variant::OBJECT,"theme", PROPERTY_HINT_RESOURCE_TYPE, "Theme"), "set_theme","get_theme") ;
- ADD_GROUP("","");
-
- BIND_CONSTANT( ANCHOR_BEGIN );
- BIND_CONSTANT( ANCHOR_END );
- BIND_CONSTANT( ANCHOR_CENTER );
- BIND_CONSTANT( FOCUS_NONE );
- BIND_CONSTANT( FOCUS_CLICK );
- BIND_CONSTANT( FOCUS_ALL );
-
-
- BIND_CONSTANT( NOTIFICATION_RESIZED );
- BIND_CONSTANT( NOTIFICATION_MOUSE_ENTER );
- BIND_CONSTANT( NOTIFICATION_MOUSE_EXIT );
- BIND_CONSTANT( NOTIFICATION_FOCUS_ENTER );
- BIND_CONSTANT( NOTIFICATION_FOCUS_EXIT );
- BIND_CONSTANT( NOTIFICATION_THEME_CHANGED );
- BIND_CONSTANT( NOTIFICATION_MODAL_CLOSE );
-
- BIND_CONSTANT( CURSOR_ARROW );
- BIND_CONSTANT( CURSOR_IBEAM );
- BIND_CONSTANT( CURSOR_POINTING_HAND );
- BIND_CONSTANT( CURSOR_CROSS );
- BIND_CONSTANT( CURSOR_WAIT );
- BIND_CONSTANT( CURSOR_BUSY );
- BIND_CONSTANT( CURSOR_DRAG );
- BIND_CONSTANT( CURSOR_CAN_DROP );
- BIND_CONSTANT( CURSOR_FORBIDDEN );
- BIND_CONSTANT( CURSOR_VSIZE );
- BIND_CONSTANT( CURSOR_HSIZE );
- BIND_CONSTANT( CURSOR_BDIAGSIZE );
- BIND_CONSTANT( CURSOR_FDIAGSIZE );
- BIND_CONSTANT( CURSOR_MOVE );
- BIND_CONSTANT( CURSOR_VSPLIT );
- BIND_CONSTANT( CURSOR_HSPLIT );
- BIND_CONSTANT( CURSOR_HELP );
-
- BIND_CONSTANT( SIZE_EXPAND );
- BIND_CONSTANT( SIZE_FILL );
- BIND_CONSTANT( SIZE_EXPAND_FILL );
-
- BIND_CONSTANT( MOUSE_FILTER_STOP );
- BIND_CONSTANT( MOUSE_FILTER_PASS );
- BIND_CONSTANT( MOUSE_FILTER_IGNORE );
-
- ADD_SIGNAL( MethodInfo("resized") );
- ADD_SIGNAL( MethodInfo("gui_input",PropertyInfo(Variant::INPUT_EVENT,"ev")) );
- ADD_SIGNAL( MethodInfo("mouse_entered") );
- ADD_SIGNAL( MethodInfo("mouse_exited") );
- ADD_SIGNAL( MethodInfo("focus_entered") );
- ADD_SIGNAL( MethodInfo("focus_exited") );
- ADD_SIGNAL( MethodInfo("size_flags_changed") );
- ADD_SIGNAL( MethodInfo("minimum_size_changed") );
- ADD_SIGNAL( MethodInfo("modal_closed") );
-
-
+ BIND_VMETHOD(MethodInfo("_gui_input", PropertyInfo(Variant::INPUT_EVENT, "event")));
+ BIND_VMETHOD(MethodInfo(Variant::VECTOR2, "get_minimum_size"));
+ BIND_VMETHOD(MethodInfo(Variant::OBJECT, "get_drag_data", PropertyInfo(Variant::VECTOR2, "pos")));
+ BIND_VMETHOD(MethodInfo(Variant::BOOL, "can_drop_data", PropertyInfo(Variant::VECTOR2, "pos"), PropertyInfo(Variant::NIL, "data")));
+ BIND_VMETHOD(MethodInfo("drop_data", PropertyInfo(Variant::VECTOR2, "pos"), PropertyInfo(Variant::NIL, "data")));
+
+ ADD_GROUP("Anchor", "anchor_");
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "anchor_left", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor", "get_anchor", MARGIN_LEFT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "anchor_top", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor", "get_anchor", MARGIN_TOP);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "anchor_right", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor", "get_anchor", MARGIN_RIGHT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "anchor_bottom", PROPERTY_HINT_ENUM, "Begin,End,Center"), "_set_anchor", "get_anchor", MARGIN_BOTTOM);
+
+ ADD_GROUP("Margin", "margin_");
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "margin_left", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin", "get_margin", MARGIN_LEFT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "margin_top", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin", "get_margin", MARGIN_TOP);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "margin_right", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin", "get_margin", MARGIN_RIGHT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "margin_bottom", PROPERTY_HINT_RANGE, "-4096,4096"), "set_margin", "get_margin", MARGIN_BOTTOM);
+
+ ADD_GROUP("Rect", "rect_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "rect_pos", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_pos", "get_pos");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "rect_size", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "set_size", "get_size");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::VECTOR2, "rect_min_size"), "set_custom_minimum_size", "get_custom_minimum_size");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "rect_rotation", PROPERTY_HINT_RANGE, "-1080,1080,0.01"), "set_rotation_deg", "get_rotation_deg");
+ ADD_PROPERTYNO(PropertyInfo(Variant::VECTOR2, "rect_scale"), "set_scale", "get_scale");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "rect_clip_content"), "set_clip_contents", "is_clipping_contents");
+
+ ADD_GROUP("Hint", "hint_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "hint_tooltip", PROPERTY_HINT_MULTILINE_TEXT), "set_tooltip", "_get_tooltip");
+
+ ADD_GROUP("Focus", "focus_");
+ ADD_PROPERTYINZ(PropertyInfo(Variant::NODE_PATH, "focus_neighbour_left"), "set_focus_neighbour", "get_focus_neighbour", MARGIN_LEFT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::NODE_PATH, "focus_neighbour_top"), "set_focus_neighbour", "get_focus_neighbour", MARGIN_TOP);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::NODE_PATH, "focus_neighbour_right"), "set_focus_neighbour", "get_focus_neighbour", MARGIN_RIGHT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::NODE_PATH, "focus_neighbour_bottom"), "set_focus_neighbour", "get_focus_neighbour", MARGIN_BOTTOM);
+
+ ADD_GROUP("Mouse", "mouse_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mouse_filter", PROPERTY_HINT_ENUM, "Stop,Pass,Ignore"), "set_mouse_filter", "get_mouse_filter");
+
+ ADD_GROUP("Size Flags", "size_flags_");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "size_flags_horizontal", PROPERTY_HINT_FLAGS, "Fill,Expand"), "set_h_size_flags", "get_h_size_flags");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "size_flags_vertical", PROPERTY_HINT_FLAGS, "Fill,Expand"), "set_v_size_flags", "get_v_size_flags");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "size_flags_stretch_ratio", PROPERTY_HINT_RANGE, "1,128,0.01"), "set_stretch_ratio", "get_stretch_ratio");
+ ADD_GROUP("Theme", "");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "theme", PROPERTY_HINT_RESOURCE_TYPE, "Theme"), "set_theme", "get_theme");
+ ADD_GROUP("", "");
+
+ BIND_CONSTANT(ANCHOR_BEGIN);
+ BIND_CONSTANT(ANCHOR_END);
+ BIND_CONSTANT(ANCHOR_CENTER);
+ BIND_CONSTANT(FOCUS_NONE);
+ BIND_CONSTANT(FOCUS_CLICK);
+ BIND_CONSTANT(FOCUS_ALL);
+
+ BIND_CONSTANT(NOTIFICATION_RESIZED);
+ BIND_CONSTANT(NOTIFICATION_MOUSE_ENTER);
+ BIND_CONSTANT(NOTIFICATION_MOUSE_EXIT);
+ BIND_CONSTANT(NOTIFICATION_FOCUS_ENTER);
+ BIND_CONSTANT(NOTIFICATION_FOCUS_EXIT);
+ BIND_CONSTANT(NOTIFICATION_THEME_CHANGED);
+ BIND_CONSTANT(NOTIFICATION_MODAL_CLOSE);
+
+ BIND_CONSTANT(CURSOR_ARROW);
+ BIND_CONSTANT(CURSOR_IBEAM);
+ BIND_CONSTANT(CURSOR_POINTING_HAND);
+ BIND_CONSTANT(CURSOR_CROSS);
+ BIND_CONSTANT(CURSOR_WAIT);
+ BIND_CONSTANT(CURSOR_BUSY);
+ BIND_CONSTANT(CURSOR_DRAG);
+ BIND_CONSTANT(CURSOR_CAN_DROP);
+ BIND_CONSTANT(CURSOR_FORBIDDEN);
+ BIND_CONSTANT(CURSOR_VSIZE);
+ BIND_CONSTANT(CURSOR_HSIZE);
+ BIND_CONSTANT(CURSOR_BDIAGSIZE);
+ BIND_CONSTANT(CURSOR_FDIAGSIZE);
+ BIND_CONSTANT(CURSOR_MOVE);
+ BIND_CONSTANT(CURSOR_VSPLIT);
+ BIND_CONSTANT(CURSOR_HSPLIT);
+ BIND_CONSTANT(CURSOR_HELP);
+
+ BIND_CONSTANT(SIZE_EXPAND);
+ BIND_CONSTANT(SIZE_FILL);
+ BIND_CONSTANT(SIZE_EXPAND_FILL);
+
+ BIND_CONSTANT(MOUSE_FILTER_STOP);
+ BIND_CONSTANT(MOUSE_FILTER_PASS);
+ BIND_CONSTANT(MOUSE_FILTER_IGNORE);
+
+ ADD_SIGNAL(MethodInfo("resized"));
+ ADD_SIGNAL(MethodInfo("gui_input", PropertyInfo(Variant::INPUT_EVENT, "ev")));
+ ADD_SIGNAL(MethodInfo("mouse_entered"));
+ ADD_SIGNAL(MethodInfo("mouse_exited"));
+ ADD_SIGNAL(MethodInfo("focus_entered"));
+ ADD_SIGNAL(MethodInfo("focus_exited"));
+ ADD_SIGNAL(MethodInfo("size_flags_changed"));
+ ADD_SIGNAL(MethodInfo("minimum_size_changed"));
+ ADD_SIGNAL(MethodInfo("modal_closed"));
}
Control::Control() {
- data.parent=NULL;
+ data.parent = NULL;
- data.mouse_filter=MOUSE_FILTER_STOP;
+ data.mouse_filter = MOUSE_FILTER_STOP;
- data.SI=NULL;
- data.MI=NULL;
- data.RI=NULL;
- data.modal=false;
- data.theme_owner=NULL;
- data.modal_exclusive=false;
+ data.SI = NULL;
+ data.MI = NULL;
+ data.RI = NULL;
+ data.modal = false;
+ data.theme_owner = NULL;
+ data.modal_exclusive = false;
data.default_cursor = CURSOR_ARROW;
- data.h_size_flags=SIZE_FILL;
- data.v_size_flags=SIZE_FILL;
- data.expand=1;
- data.pending_min_size_update=false;
- data.rotation=0;
- data.parent_canvas_item=NULL;
- data.scale=Vector2(1,1);
- data.drag_owner=0;
- data.modal_frame=0;
- data.block_minimum_size_adjust=false;
- data.disable_visibility_clip=false;
-
- data.clip_contents=false;
- for (int i=0;i<4;i++) {
- data.anchor[i]=ANCHOR_BEGIN;
- data.margin[i]=0;
- }
- data.focus_mode=FOCUS_NONE;
- data.modal_prev_focus_owner=0;
-
-
-
-
-
-}
-
-
-Control::~Control()
-{
+ data.h_size_flags = SIZE_FILL;
+ data.v_size_flags = SIZE_FILL;
+ data.expand = 1;
+ data.pending_min_size_update = false;
+ data.rotation = 0;
+ data.parent_canvas_item = NULL;
+ data.scale = Vector2(1, 1);
+ data.drag_owner = 0;
+ data.modal_frame = 0;
+ data.block_minimum_size_adjust = false;
+ data.disable_visibility_clip = false;
+
+ data.clip_contents = false;
+ for (int i = 0; i < 4; i++) {
+ data.anchor[i] = ANCHOR_BEGIN;
+ data.margin[i] = 0;
+ }
+ data.focus_mode = FOCUS_NONE;
+ data.modal_prev_focus_owner = 0;
+}
+
+Control::~Control() {
}
diff --git a/scene/gui/control.h b/scene/gui/control.h
index 68795b054c..a18567123b 100644
--- a/scene/gui/control.h
+++ b/scene/gui/control.h
@@ -29,13 +29,13 @@
#ifndef CONTROL_H
#define CONTROL_H
-#include "scene/main/node.h"
-#include "scene/resources/theme.h"
-#include "scene/main/timer.h"
-#include "scene/2d/canvas_item.h"
#include "math_2d.h"
#include "rid.h"
+#include "scene/2d/canvas_item.h"
#include "scene/gui/input_action.h"
+#include "scene/main/node.h"
+#include "scene/main/timer.h"
+#include "scene/resources/theme.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -46,11 +46,10 @@ class Panel;
class Control : public CanvasItem {
- GDCLASS( Control, CanvasItem );
+ GDCLASS(Control, CanvasItem);
OBJ_CATEGORY("GUI Nodes");
public:
-
enum AnchorType {
ANCHOR_BEGIN,
ANCHOR_END,
@@ -65,9 +64,9 @@ public:
enum SizeFlags {
- SIZE_FILL=1,
- SIZE_EXPAND=2,
- SIZE_EXPAND_FILL=SIZE_EXPAND|SIZE_FILL
+ SIZE_FILL = 1,
+ SIZE_EXPAND = 2,
+ SIZE_EXPAND_FILL = SIZE_EXPAND | SIZE_FILL
};
@@ -99,11 +98,10 @@ public:
};
private:
-
struct CComparator {
- bool operator()(const Control* p_a, const Control* p_b) const {
- if (p_a->get_canvas_layer()==p_b->get_canvas_layer())
+ bool operator()(const Control *p_a, const Control *p_b) const {
+ if (p_a->get_canvas_layer() == p_b->get_canvas_layer())
return p_b->is_greater_than(p_a);
else
return p_a->get_canvas_layer() < p_b->get_canvas_layer();
@@ -147,9 +145,9 @@ private:
String tooltip;
CursorShape default_cursor;
- List<Control*>::Element *MI; //modal item
- List<Control*>::Element *SI;
- List<Control*>::Element *RI;
+ List<Control *>::Element *MI; //modal item
+ List<Control *>::Element *SI;
+ List<Control *>::Element *RI;
CanvasItem *parent_canvas_item;
@@ -157,39 +155,36 @@ private:
NodePath focus_neighbour[4];
- HashMap<StringName, Ref<Texture>, StringNameHasher > icon_override;
- HashMap<StringName, Ref<Shader>, StringNameHasher > shader_override;
- HashMap<StringName, Ref<StyleBox>, StringNameHasher > style_override;
- HashMap<StringName, Ref<Font>, StringNameHasher > font_override;
- HashMap<StringName, Color, StringNameHasher > color_override;
- HashMap<StringName, int, StringNameHasher > constant_override;
- Map< Ref<Font>, int> font_refcount;
+ HashMap<StringName, Ref<Texture>, StringNameHasher> icon_override;
+ HashMap<StringName, Ref<Shader>, StringNameHasher> shader_override;
+ HashMap<StringName, Ref<StyleBox>, StringNameHasher> style_override;
+ HashMap<StringName, Ref<Font>, StringNameHasher> font_override;
+ HashMap<StringName, Color, StringNameHasher> color_override;
+ HashMap<StringName, int, StringNameHasher> constant_override;
+ Map<Ref<Font>, int> font_refcount;
} data;
// used internally
- Control* _find_control_at_pos(CanvasItem* p_node,const Point2& p_pos,const Transform2D& p_xform,Transform2D& r_inv_xform);
-
-
- void _window_find_focus_neighbour(const Vector2& p_dir, Node *p_at, const Point2* p_points ,float p_min,float &r_closest_dist,Control **r_closest);
- Control *_get_focus_neighbour(Margin p_margin,int p_count=0);
+ Control *_find_control_at_pos(CanvasItem *p_node, const Point2 &p_pos, const Transform2D &p_xform, Transform2D &r_inv_xform);
+ void _window_find_focus_neighbour(const Vector2 &p_dir, Node *p_at, const Point2 *p_points, float p_min, float &r_closest_dist, Control **r_closest);
+ Control *_get_focus_neighbour(Margin p_margin, int p_count = 0);
- void _set_anchor(Margin p_margin,AnchorType p_anchor);
+ void _set_anchor(Margin p_margin, AnchorType p_anchor);
float _get_parent_range(int p_idx) const;
float _get_range(int p_idx) const;
- float _s2a(float p_val, AnchorType p_anchor,float p_range) const;
- float _a2s(float p_val, AnchorType p_anchor,float p_range) const;
- void _propagate_theme_changed(CanvasItem *p_at, Control *p_owner, bool p_assign=true);
+ float _s2a(float p_val, AnchorType p_anchor, float p_range) const;
+ float _a2s(float p_val, AnchorType p_anchor, float p_range) const;
+ void _propagate_theme_changed(CanvasItem *p_at, Control *p_owner, bool p_assign = true);
void _theme_changed();
-
void _change_notify_margins();
void _update_minimum_size();
void _update_scroll();
- void _resize(const Size2& p_size);
+ void _resize(const Size2 &p_size);
void _size_changed();
String _get_tooltip() const;
@@ -199,70 +194,65 @@ private:
float _get_rotation_deg() const;
void _ref_font(Ref<Font> p_sc);
- void _unref_font( Ref<Font> p_sc);
+ void _unref_font(Ref<Font> p_sc);
void _font_changed();
void _update_canvas_item_transform();
-
-friend class Viewport;
+ friend class Viewport;
void _modal_stack_remove();
void _modal_set_prev_focus_owner(ObjectID p_prev);
protected:
-
virtual void add_child_notify(Node *p_child);
virtual void remove_child_notify(Node *p_child);
//virtual void _window_gui_input(InputEvent p_event);
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
void _notification(int p_notification);
-
static void _bind_methods();
//bind helpers
public:
-
enum {
-/* NOTIFICATION_DRAW=30,
+ /* NOTIFICATION_DRAW=30,
NOTIFICATION_VISIBILITY_CHANGED=38*/
- NOTIFICATION_RESIZED=40,
- NOTIFICATION_MOUSE_ENTER=41,
- NOTIFICATION_MOUSE_EXIT=42,
- NOTIFICATION_FOCUS_ENTER=43,
- NOTIFICATION_FOCUS_EXIT=44,
- NOTIFICATION_THEME_CHANGED=45,
- NOTIFICATION_MODAL_CLOSE=46,
-
+ NOTIFICATION_RESIZED = 40,
+ NOTIFICATION_MOUSE_ENTER = 41,
+ NOTIFICATION_MOUSE_EXIT = 42,
+ NOTIFICATION_FOCUS_ENTER = 43,
+ NOTIFICATION_FOCUS_EXIT = 44,
+ NOTIFICATION_THEME_CHANGED = 45,
+ NOTIFICATION_MODAL_CLOSE = 46,
};
virtual Variant edit_get_state() const;
- virtual void edit_set_state(const Variant& p_state);
- virtual void edit_set_rect(const Rect2& p_edit_rect);
+ virtual void edit_set_state(const Variant &p_state);
+ virtual void edit_set_rect(const Rect2 &p_edit_rect);
virtual Size2 edit_get_minimum_size() const;
void accept_event();
virtual Size2 get_minimum_size() const;
virtual Size2 get_combined_minimum_size() const;
- virtual bool has_point(const Point2& p_point) const;
+ virtual bool has_point(const Point2 &p_point) const;
virtual bool clips_input() const;
- virtual void set_drag_forwarding(Control* p_target);
- virtual Variant get_drag_data(const Point2& p_point);
- virtual bool can_drop_data(const Point2& p_point,const Variant& p_data) const;
- virtual void drop_data(const Point2& p_point,const Variant& p_data);
+ virtual void set_drag_forwarding(Control *p_target);
+ virtual Variant get_drag_data(const Point2 &p_point);
+ virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
+ virtual void drop_data(const Point2 &p_point, const Variant &p_data);
void set_drag_preview(Control *p_control);
- void force_drag(const Variant& p_data,Control *p_control);
+ void force_drag(const Variant &p_data, Control *p_control);
- void set_custom_minimum_size(const Size2& p_custom);
+ void set_custom_minimum_size(const Size2 &p_custom);
Size2 get_custom_minimum_size() const;
bool is_window_modal_on_top() const;
@@ -270,29 +260,25 @@ public:
Control *get_parent_control() const;
-
-
/* POSITIONING */
- void set_anchor(Margin p_margin,AnchorType p_anchor, bool p_keep_margin=false);
- void set_anchor_and_margin(Margin p_margin,AnchorType p_anchor, float p_pos);
+ void set_anchor(Margin p_margin, AnchorType p_anchor, bool p_keep_margin = false);
+ void set_anchor_and_margin(Margin p_margin, AnchorType p_anchor, float p_pos);
AnchorType get_anchor(Margin p_margin) const;
- void set_margin(Margin p_margin,float p_value);
-
- void set_begin(const Point2& p_point); // helper
- void set_end(const Point2& p_point); // helper
-
+ void set_margin(Margin p_margin, float p_value);
+ void set_begin(const Point2 &p_point); // helper
+ void set_end(const Point2 &p_point); // helper
float get_margin(Margin p_margin) const;
Point2 get_begin() const;
Point2 get_end() const;
- void set_pos(const Point2& p_point);
- void set_size(const Size2& p_size);
- void set_global_pos(const Point2& p_point);
+ void set_pos(const Point2 &p_point);
+ void set_size(const Size2 &p_size);
+ void set_global_pos(const Point2 &p_point);
Point2 get_pos() const;
Point2 get_global_pos() const;
@@ -306,15 +292,14 @@ public:
float get_rotation() const;
float get_rotation_deg() const;
- void set_scale(const Vector2& p_scale);
+ void set_scale(const Vector2 &p_scale);
Vector2 get_scale() const;
+ void set_area_as_parent_rect(int p_margin = 0);
- void set_area_as_parent_rect(int p_margin=0);
-
- void show_modal(bool p_exclusive=false);
+ void show_modal(bool p_exclusive = false);
- void set_theme(const Ref<Theme>& p_theme);
+ void set_theme(const Ref<Theme> &p_theme);
Ref<Theme> get_theme() const;
void set_h_size_flags(int p_flags);
@@ -349,44 +334,44 @@ public:
/* SKINNING */
- void add_icon_override(const StringName& p_name, const Ref<Texture>& p_icon);
- void add_shader_override(const StringName& p_name, const Ref<Shader>& p_shader);
- void add_style_override(const StringName& p_name, const Ref<StyleBox>& p_style);
- void add_font_override(const StringName& p_name, const Ref<Font>& p_font);
- void add_color_override(const StringName& p_name, const Color& p_color);
- void add_constant_override(const StringName& p_name, int p_constant);
-
- Ref<Texture> get_icon(const StringName& p_name,const StringName& p_type=StringName()) const;
- Ref<Shader> get_shader(const StringName &p_name, const StringName &p_type=StringName()) const;
- Ref<StyleBox> get_stylebox(const StringName& p_name,const StringName& p_type=StringName()) const;
- Ref<Font> get_font(const StringName& p_name,const StringName& p_type=StringName()) const;
- Color get_color(const StringName& p_name,const StringName& p_type=StringName()) const;
- int get_constant(const StringName& p_name,const StringName& p_type=StringName()) const;
-
- bool has_icon_override(const StringName& p_name) const;
- bool has_shader_override(const StringName& p_name) const;
- bool has_stylebox_override(const StringName& p_name) const;
- bool has_font_override(const StringName& p_name) const;
- bool has_color_override(const StringName& p_name) const;
- bool has_constant_override(const StringName& p_name) const;
-
- bool has_icon(const StringName& p_name,const StringName& p_type=StringName()) const;
- bool has_shader(const StringName& p_name,const StringName& p_type=StringName()) const;
- bool has_stylebox(const StringName& p_name,const StringName& p_type=StringName()) const;
- bool has_font(const StringName& p_name,const StringName& p_type=StringName()) const;
- bool has_color(const StringName& p_name,const StringName& p_type=StringName()) const;
- bool has_constant(const StringName& p_name,const StringName& p_type=StringName()) const;
+ void add_icon_override(const StringName &p_name, const Ref<Texture> &p_icon);
+ void add_shader_override(const StringName &p_name, const Ref<Shader> &p_shader);
+ void add_style_override(const StringName &p_name, const Ref<StyleBox> &p_style);
+ void add_font_override(const StringName &p_name, const Ref<Font> &p_font);
+ void add_color_override(const StringName &p_name, const Color &p_color);
+ void add_constant_override(const StringName &p_name, int p_constant);
+
+ Ref<Texture> get_icon(const StringName &p_name, const StringName &p_type = StringName()) const;
+ Ref<Shader> get_shader(const StringName &p_name, const StringName &p_type = StringName()) const;
+ Ref<StyleBox> get_stylebox(const StringName &p_name, const StringName &p_type = StringName()) const;
+ Ref<Font> get_font(const StringName &p_name, const StringName &p_type = StringName()) const;
+ Color get_color(const StringName &p_name, const StringName &p_type = StringName()) const;
+ int get_constant(const StringName &p_name, const StringName &p_type = StringName()) const;
+
+ bool has_icon_override(const StringName &p_name) const;
+ bool has_shader_override(const StringName &p_name) const;
+ bool has_stylebox_override(const StringName &p_name) const;
+ bool has_font_override(const StringName &p_name) const;
+ bool has_color_override(const StringName &p_name) const;
+ bool has_constant_override(const StringName &p_name) const;
+
+ bool has_icon(const StringName &p_name, const StringName &p_type = StringName()) const;
+ bool has_shader(const StringName &p_name, const StringName &p_type = StringName()) const;
+ bool has_stylebox(const StringName &p_name, const StringName &p_type = StringName()) const;
+ bool has_font(const StringName &p_name, const StringName &p_type = StringName()) const;
+ bool has_color(const StringName &p_name, const StringName &p_type = StringName()) const;
+ bool has_constant(const StringName &p_name, const StringName &p_type = StringName()) const;
/* TOOLTIP */
- void set_tooltip(const String& p_tooltip);
- virtual String get_tooltip(const Point2& p_pos) const;
+ void set_tooltip(const String &p_tooltip);
+ virtual String get_tooltip(const Point2 &p_pos) const;
/* CURSOR */
void set_default_cursor_shape(CursorShape p_shape);
CursorShape get_default_cursor_shape() const;
- virtual CursorShape get_cursor_shape(const Point2& p_pos=Point2i()) const;
+ virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const;
virtual Rect2 get_item_rect() const;
virtual Transform2D get_transform() const;
@@ -397,7 +382,7 @@ public:
void grab_click_focus();
- void warp_mouse(const Point2& p_to_pos);
+ void warp_mouse(const Point2 &p_to_pos);
virtual bool is_text_field() const;
@@ -412,11 +397,10 @@ public:
void set_disable_visibility_clip(bool p_ignore);
bool is_visibility_clip_disabled() const;
- virtual void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
+ virtual void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
Control();
~Control();
-
};
VARIANT_ENUM_CAST(Control::AnchorType);
diff --git a/scene/gui/dialogs.cpp b/scene/gui/dialogs.cpp
index 6d06f8c59c..d081eda86d 100644
--- a/scene/gui/dialogs.cpp
+++ b/scene/gui/dialogs.cpp
@@ -27,8 +27,8 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "dialogs.h"
-#include "print_string.h"
#include "line_edit.h"
+#include "print_string.h"
#include "translation.h"
void WindowDialog::_post_popup() {
@@ -44,7 +44,7 @@ void WindowDialog::_fix_size() {
Point2i pos = get_global_pos();
Size2i size = get_size();
Size2i viewport_size = get_viewport_rect().size;
-
+
// Windows require additional padding to keep the window chrome visible.
Ref<StyleBox> panel = get_stylebox("panel", "WindowDialog");
float top = panel->get_margin(MARGIN_TOP);
@@ -64,7 +64,7 @@ void WindowDialog::_fix_size() {
}
}
-bool WindowDialog::has_point(const Point2& p_point) const {
+bool WindowDialog::has_point(const Point2 &p_point) const {
Rect2 r(Point2(), get_size());
@@ -85,7 +85,7 @@ bool WindowDialog::has_point(const Point2& p_point) const {
return r.has_point(p_point);
}
-void WindowDialog::_gui_input(const InputEvent& p_event) {
+void WindowDialog::_gui_input(const InputEvent &p_event) {
if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == BUTTON_LEFT) {
@@ -94,7 +94,7 @@ void WindowDialog::_gui_input(const InputEvent& p_event) {
drag_type = _drag_hit_test(Point2(p_event.mouse_button.x, p_event.mouse_button.y));
if (drag_type != DRAG_NONE)
drag_offset = get_global_mouse_pos() - get_pos();
- drag_offset_far = get_pos() + get_size() - get_global_mouse_pos();
+ drag_offset_far = get_pos() + get_size() - get_global_mouse_pos();
} else if (drag_type != DRAG_NONE && !p_event.mouse_button.pressed) {
// End a dragging operation.
drag_type = DRAG_NONE;
@@ -208,13 +208,13 @@ void WindowDialog::_closed() {
hide();
}
-int WindowDialog::_drag_hit_test(const Point2& pos) const {
+int WindowDialog::_drag_hit_test(const Point2 &pos) const {
int drag_type = DRAG_NONE;
if (resizable) {
int titlebar_height = get_constant("titlebar_height", "WindowDialog");
int scaleborder_size = get_constant("scaleborder_size", "WindowDialog");
-
+
Rect2 rect = get_rect();
if (pos.y < (-titlebar_height + scaleborder_size))
@@ -233,9 +233,9 @@ int WindowDialog::_drag_hit_test(const Point2& pos) const {
return drag_type;
}
-void WindowDialog::set_title(const String& p_title) {
+void WindowDialog::set_title(const String &p_title) {
- title=XL_MESSAGE(p_title);
+ title = XL_MESSAGE(p_title);
update();
}
String WindowDialog::get_title() const {
@@ -250,36 +250,32 @@ bool WindowDialog::get_resizable() const {
return resizable;
}
-
Size2 WindowDialog::get_minimum_size() const {
- Ref<Font> font = get_font("title_font","WindowDialog");
- int msx=close_button->get_combined_minimum_size().x;
- msx+=font->get_string_size(title).x;
+ Ref<Font> font = get_font("title_font", "WindowDialog");
+ int msx = close_button->get_combined_minimum_size().x;
+ msx += font->get_string_size(title).x;
- return Size2(msx,1);
+ return Size2(msx, 1);
}
-
-
TextureButton *WindowDialog::get_close_button() {
-
return close_button;
}
void WindowDialog::_bind_methods() {
- ClassDB::bind_method( D_METHOD("_gui_input"),&WindowDialog::_gui_input);
- ClassDB::bind_method( D_METHOD("set_title","title"),&WindowDialog::set_title);
- ClassDB::bind_method( D_METHOD("get_title"),&WindowDialog::get_title);
- ClassDB::bind_method( D_METHOD("set_resizable","resizable"),&WindowDialog::set_resizable);
- ClassDB::bind_method( D_METHOD("get_resizable"), &WindowDialog::get_resizable);
- ClassDB::bind_method( D_METHOD("_closed"),&WindowDialog::_closed);
- ClassDB::bind_method( D_METHOD("get_close_button:TextureButton"),&WindowDialog::get_close_button);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &WindowDialog::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_title", "title"), &WindowDialog::set_title);
+ ClassDB::bind_method(D_METHOD("get_title"), &WindowDialog::get_title);
+ ClassDB::bind_method(D_METHOD("set_resizable", "resizable"), &WindowDialog::set_resizable);
+ ClassDB::bind_method(D_METHOD("get_resizable"), &WindowDialog::get_resizable);
+ ClassDB::bind_method(D_METHOD("_closed"), &WindowDialog::_closed);
+ ClassDB::bind_method(D_METHOD("get_close_button:TextureButton"), &WindowDialog::get_close_button);
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"window_title",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT_INTL),"set_title","get_title");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"resizable",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT_INTL),"set_resizable","get_resizable");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "window_title", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_title", "get_title");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "resizable", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_resizable", "get_resizable");
}
WindowDialog::WindowDialog() {
@@ -290,57 +286,46 @@ WindowDialog::WindowDialog() {
close_button = memnew(TextureButton);
add_child(close_button);
close_button->connect("pressed", this, "_closed");
-
}
-WindowDialog::~WindowDialog(){
-
-
+WindowDialog::~WindowDialog() {
}
-
void PopupDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
+ get_stylebox("panel", "PopupMenu")->draw(ci, Rect2(Point2(), get_size()));
}
}
PopupDialog::PopupDialog() {
-
-
}
PopupDialog::~PopupDialog() {
-
-
}
-
// AcceptDialog
-
void AcceptDialog::_post_popup() {
WindowDialog::_post_popup();
get_ok()->grab_focus();
-
}
void AcceptDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_MODAL_CLOSE) {
+ if (p_what == NOTIFICATION_MODAL_CLOSE) {
cancel_pressed();
- } else if (p_what==NOTIFICATION_RESIZED) {
+ } else if (p_what == NOTIFICATION_RESIZED) {
_update_child_rects();
}
}
-void AcceptDialog::_builtin_text_entered(const String& p_text) {
+void AcceptDialog::_builtin_text_entered(const String &p_text) {
_ok_pressed();
}
@@ -351,7 +336,6 @@ void AcceptDialog::_ok_pressed() {
hide();
ok_pressed();
emit_signal("confirmed");
-
}
void AcceptDialog::_close_pressed() {
@@ -371,7 +355,7 @@ void AcceptDialog::set_text(String p_text) {
void AcceptDialog::set_hide_on_ok(bool p_hide) {
- hide_on_ok=p_hide;
+ hide_on_ok = p_hide;
}
bool AcceptDialog::get_hide_on_ok() const {
@@ -379,91 +363,82 @@ bool AcceptDialog::get_hide_on_ok() const {
return hide_on_ok;
}
-
void AcceptDialog::register_text_enter(Node *p_line_edit) {
ERR_FAIL_NULL(p_line_edit);
- p_line_edit->connect("text_entered", this,"_builtin_text_entered");
+ p_line_edit->connect("text_entered", this, "_builtin_text_entered");
}
void AcceptDialog::_update_child_rects() {
-
- Size2 label_size=label->get_minimum_size();
+ Size2 label_size = label->get_minimum_size();
if (label->get_text().empty()) {
label_size.height = 0;
}
- int margin = get_constant("margin","Dialogs");
+ int margin = get_constant("margin", "Dialogs");
Size2 size = get_size();
Size2 hminsize = hbc->get_combined_minimum_size();
- Vector2 cpos(margin,margin+label_size.height);
- Vector2 csize(size.x-margin*2,size.y-margin*3-hminsize.y-label_size.height);
+ Vector2 cpos(margin, margin + label_size.height);
+ Vector2 csize(size.x - margin * 2, size.y - margin * 3 - hminsize.y - label_size.height);
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
- if (c==hbc || c==label || c==get_close_button() || c->is_set_as_toplevel())
+ if (c == hbc || c == label || c == get_close_button() || c->is_set_as_toplevel())
continue;
c->set_pos(cpos);
c->set_size(csize);
-
}
- cpos.y+=csize.y+margin;
- csize.y=hminsize.y;
+ cpos.y += csize.y + margin;
+ csize.y = hminsize.y;
hbc->set_pos(cpos);
hbc->set_size(csize);
-
}
Size2 AcceptDialog::get_minimum_size() const {
- int margin = get_constant("margin","Dialogs");
+ int margin = get_constant("margin", "Dialogs");
Size2 minsize = label->get_combined_minimum_size();
-
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
- if (c==hbc || c==label || c==const_cast<AcceptDialog*>(this)->get_close_button() || c->is_set_as_toplevel())
+ if (c == hbc || c == label || c == const_cast<AcceptDialog *>(this)->get_close_button() || c->is_set_as_toplevel())
continue;
Size2 cminsize = c->get_combined_minimum_size();
- minsize.x=MAX(cminsize.x,minsize.x);
- minsize.y=MAX(cminsize.y,minsize.y);
-
+ minsize.x = MAX(cminsize.x, minsize.x);
+ minsize.y = MAX(cminsize.y, minsize.y);
}
-
Size2 hminsize = hbc->get_combined_minimum_size();
- minsize.x = MAX(hminsize.x,minsize.x);
- minsize.y+=hminsize.y;
- minsize.x+=margin*2;
- minsize.y+=margin*3; //one as separation between hbc and child
+ minsize.x = MAX(hminsize.x, minsize.x);
+ minsize.y += hminsize.y;
+ minsize.x += margin * 2;
+ minsize.y += margin * 3; //one as separation between hbc and child
Size2 wmsize = WindowDialog::get_minimum_size();
- minsize.x=MAX(wmsize.x,minsize.x);
+ minsize.x = MAX(wmsize.x, minsize.x);
return minsize;
}
+void AcceptDialog::_custom_action(const String &p_action) {
-void AcceptDialog::_custom_action(const String& p_action) {
-
- emit_signal("custom_action",p_action);
+ emit_signal("custom_action", p_action);
custom_action(p_action);
}
-Button* AcceptDialog::add_button(const String& p_text,bool p_right,const String& p_action) {
-
+Button *AcceptDialog::add_button(const String &p_text, bool p_right, const String &p_action) {
- Button *button = memnew( Button );
+ Button *button = memnew(Button);
button->set_text(p_text);
if (p_right) {
hbc->add_child(button);
@@ -471,98 +446,91 @@ Button* AcceptDialog::add_button(const String& p_text,bool p_right,const String&
} else {
hbc->add_child(button);
- hbc->move_child(button,0);
+ hbc->move_child(button, 0);
hbc->add_spacer(true);
}
- if (p_action!="") {
- button->connect("pressed",this,"_custom_action",varray(p_action));
+ if (p_action != "") {
+ button->connect("pressed", this, "_custom_action", varray(p_action));
}
return button;
}
-Button* AcceptDialog::add_cancel(const String &p_cancel) {
+Button *AcceptDialog::add_cancel(const String &p_cancel) {
String c = p_cancel;
- if (p_cancel=="")
- c=RTR("Cancel");
- Button *b = swap_ok_cancel ? add_button(c,true) : add_button(c);
- b->connect("pressed",this,"_closed");
+ if (p_cancel == "")
+ c = RTR("Cancel");
+ Button *b = swap_ok_cancel ? add_button(c, true) : add_button(c);
+ b->connect("pressed", this, "_closed");
return b;
}
void AcceptDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_ok"),&AcceptDialog::_ok_pressed);
- ClassDB::bind_method(D_METHOD("get_ok"),&AcceptDialog::get_ok);
- ClassDB::bind_method(D_METHOD("get_label"),&AcceptDialog::get_label);
- ClassDB::bind_method(D_METHOD("set_hide_on_ok","enabled"),&AcceptDialog::set_hide_on_ok);
- ClassDB::bind_method(D_METHOD("get_hide_on_ok"),&AcceptDialog::get_hide_on_ok);
- ClassDB::bind_method(D_METHOD("add_button:Button","text","right","action"),&AcceptDialog::add_button,DEFVAL(false),DEFVAL(""));
- ClassDB::bind_method(D_METHOD("add_cancel:Button","name"),&AcceptDialog::add_cancel);
- ClassDB::bind_method(D_METHOD("_builtin_text_entered"),&AcceptDialog::_builtin_text_entered);
- ClassDB::bind_method(D_METHOD("register_text_enter:LineEdit","line_edit"),&AcceptDialog::register_text_enter);
- ClassDB::bind_method(D_METHOD("_custom_action"),&AcceptDialog::_custom_action);
- ClassDB::bind_method(D_METHOD("set_text","text"),&AcceptDialog::set_text);
- ClassDB::bind_method(D_METHOD("get_text"),&AcceptDialog::get_text);
+ ClassDB::bind_method(D_METHOD("_ok"), &AcceptDialog::_ok_pressed);
+ ClassDB::bind_method(D_METHOD("get_ok"), &AcceptDialog::get_ok);
+ ClassDB::bind_method(D_METHOD("get_label"), &AcceptDialog::get_label);
+ ClassDB::bind_method(D_METHOD("set_hide_on_ok", "enabled"), &AcceptDialog::set_hide_on_ok);
+ ClassDB::bind_method(D_METHOD("get_hide_on_ok"), &AcceptDialog::get_hide_on_ok);
+ ClassDB::bind_method(D_METHOD("add_button:Button", "text", "right", "action"), &AcceptDialog::add_button, DEFVAL(false), DEFVAL(""));
+ ClassDB::bind_method(D_METHOD("add_cancel:Button", "name"), &AcceptDialog::add_cancel);
+ ClassDB::bind_method(D_METHOD("_builtin_text_entered"), &AcceptDialog::_builtin_text_entered);
+ ClassDB::bind_method(D_METHOD("register_text_enter:LineEdit", "line_edit"), &AcceptDialog::register_text_enter);
+ ClassDB::bind_method(D_METHOD("_custom_action"), &AcceptDialog::_custom_action);
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &AcceptDialog::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &AcceptDialog::get_text);
- ADD_SIGNAL( MethodInfo("confirmed") );
- ADD_SIGNAL( MethodInfo("custom_action",PropertyInfo(Variant::STRING,"action")) );
-
- ADD_GROUP("Dialog","dialog");
- ADD_PROPERTYNZ( PropertyInfo(Variant::STRING,"dialog_text",PROPERTY_HINT_MULTILINE_TEXT,"",PROPERTY_USAGE_DEFAULT_INTL),"set_text","get_text");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "dialog_hide_on_ok"),"set_hide_on_ok","get_hide_on_ok") ;
+ ADD_SIGNAL(MethodInfo("confirmed"));
+ ADD_SIGNAL(MethodInfo("custom_action", PropertyInfo(Variant::STRING, "action")));
+ ADD_GROUP("Dialog", "dialog");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "dialog_text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dialog_hide_on_ok"), "set_hide_on_ok", "get_hide_on_ok");
}
-
-bool AcceptDialog::swap_ok_cancel=false;
+bool AcceptDialog::swap_ok_cancel = false;
void AcceptDialog::set_swap_ok_cancel(bool p_swap) {
- swap_ok_cancel=p_swap;
+ swap_ok_cancel = p_swap;
}
AcceptDialog::AcceptDialog() {
- int margin = get_constant("margin","Dialogs");
- int button_margin = get_constant("button_margin","Dialogs");
+ int margin = get_constant("margin", "Dialogs");
+ int button_margin = get_constant("button_margin", "Dialogs");
-
- label = memnew( Label );
- label->set_anchor(MARGIN_RIGHT,ANCHOR_END);
- label->set_anchor(MARGIN_BOTTOM,ANCHOR_END);
- label->set_begin( Point2( margin, margin) );
- label->set_end( Point2( margin, button_margin+10) );
+ label = memnew(Label);
+ label->set_anchor(MARGIN_RIGHT, ANCHOR_END);
+ label->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
+ label->set_begin(Point2(margin, margin));
+ label->set_end(Point2(margin, button_margin + 10));
//label->set_autowrap(true);
add_child(label);
- hbc = memnew( HBoxContainer );
+ hbc = memnew(HBoxContainer);
add_child(hbc);
hbc->add_spacer();
- ok = memnew( Button );
+ ok = memnew(Button);
ok->set_text(RTR("OK"));
hbc->add_child(ok);
hbc->add_spacer();
-
- ok->connect("pressed", this,"_ok");
+ ok->connect("pressed", this, "_ok");
set_as_toplevel(true);
- hide_on_ok=true;
+ hide_on_ok = true;
set_title(RTR("Alert!"));
}
-
-AcceptDialog::~AcceptDialog()
-{
+AcceptDialog::~AcceptDialog() {
}
-
void ConfirmationDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_cancel:Button"),&ConfirmationDialog::get_cancel);
+ ClassDB::bind_method(D_METHOD("get_cancel:Button"), &ConfirmationDialog::get_cancel);
}
Button *ConfirmationDialog::get_cancel() {
diff --git a/scene/gui/dialogs.h b/scene/gui/dialogs.h
index dd75b76c8e..a729a8f907 100644
--- a/scene/gui/dialogs.h
+++ b/scene/gui/dialogs.h
@@ -29,20 +29,19 @@
#ifndef DIALOGS_H
#define DIALOGS_H
-#include "scene/gui/label.h"
+#include "box_container.h"
#include "scene/gui/button.h"
-#include "scene/gui/texture_button.h"
+#include "scene/gui/label.h"
#include "scene/gui/panel.h"
#include "scene/gui/popup.h"
-#include "box_container.h"
+#include "scene/gui/texture_button.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class WindowDialog : public Popup {
- GDCLASS(WindowDialog,Popup);
+ GDCLASS(WindowDialog, Popup);
enum DRAG_TYPE {
DRAG_NONE = 0,
@@ -60,22 +59,22 @@ class WindowDialog : public Popup {
Point2 drag_offset_far;
bool resizable;
- void _gui_input(const InputEvent& p_event);
+ void _gui_input(const InputEvent &p_event);
void _closed();
- int _drag_hit_test(const Point2& pos) const;
+ int _drag_hit_test(const Point2 &pos) const;
protected:
virtual void _post_popup();
virtual void _fix_size();
- virtual void _close_pressed() {}
- virtual bool has_point(const Point2& p_point) const;
+ virtual void _close_pressed() {}
+ virtual bool has_point(const Point2 &p_point) const;
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
TextureButton *get_close_button();
- void set_title(const String& p_title);
+ void set_title(const String &p_title);
String get_title() const;
void set_resizable(bool p_resizable);
bool get_resizable() const;
@@ -84,28 +83,25 @@ public:
WindowDialog();
~WindowDialog();
-
};
class PopupDialog : public Popup {
- GDCLASS(PopupDialog,Popup);
+ GDCLASS(PopupDialog, Popup);
protected:
void _notification(int p_what);
-public:
+public:
PopupDialog();
~PopupDialog();
-
};
-
class LineEdit;
class AcceptDialog : public WindowDialog {
- GDCLASS(AcceptDialog,WindowDialog);
+ GDCLASS(AcceptDialog, WindowDialog);
HBoxContainer *hbc;
Label *label;
@@ -113,39 +109,33 @@ class AcceptDialog : public WindowDialog {
//Button *cancel; no more cancel (there is X on tht titlebar)
bool hide_on_ok;
-
- void _custom_action(const String& p_action);
+ void _custom_action(const String &p_action);
void _ok_pressed();
void _close_pressed();
- void _builtin_text_entered(const String& p_text);
+ void _builtin_text_entered(const String &p_text);
void _update_child_rects();
static bool swap_ok_cancel;
-
-
protected:
-
virtual void _post_popup();
void _notification(int p_what);
static void _bind_methods();
virtual void ok_pressed() {}
virtual void cancel_pressed() {}
- virtual void custom_action(const String&) {}
-public:
+ virtual void custom_action(const String &) {}
+public:
Size2 get_minimum_size() const;
Label *get_label() { return label; }
static void set_swap_ok_cancel(bool p_swap);
-
void register_text_enter(Node *p_line_edit);
Button *get_ok() { return ok; }
- Button* add_button(const String& p_text,bool p_right=false,const String& p_action="");
- Button* add_cancel(const String &p_cancel="");
-
+ Button *add_button(const String &p_text, bool p_right = false, const String &p_action = "");
+ Button *add_cancel(const String &p_cancel = "");
void set_hide_on_ok(bool p_hide);
bool get_hide_on_ok() const;
@@ -155,21 +145,19 @@ public:
AcceptDialog();
~AcceptDialog();
-
};
-
class ConfirmationDialog : public AcceptDialog {
- GDCLASS(ConfirmationDialog,AcceptDialog);
+ GDCLASS(ConfirmationDialog, AcceptDialog);
Button *cancel;
+
protected:
static void _bind_methods();
-public:
+public:
Button *get_cancel();
ConfirmationDialog();
-
};
#endif
diff --git a/scene/gui/file_dialog.cpp b/scene/gui/file_dialog.cpp
index 357a70a25b..d4643b399d 100644
--- a/scene/gui/file_dialog.cpp
+++ b/scene/gui/file_dialog.cpp
@@ -27,52 +27,48 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "file_dialog.h"
-#include "scene/gui/label.h"
-#include "print_string.h"
#include "os/keyboard.h"
+#include "print_string.h"
+#include "scene/gui/label.h"
+FileDialog::GetIconFunc FileDialog::get_icon_func = NULL;
+FileDialog::GetIconFunc FileDialog::get_large_icon_func = NULL;
-
-FileDialog::GetIconFunc FileDialog::get_icon_func=NULL;
-FileDialog::GetIconFunc FileDialog::get_large_icon_func=NULL;
-
-FileDialog::RegisterFunc FileDialog::register_func=NULL;
-FileDialog::RegisterFunc FileDialog::unregister_func=NULL;
-
+FileDialog::RegisterFunc FileDialog::register_func = NULL;
+FileDialog::RegisterFunc FileDialog::unregister_func = NULL;
VBoxContainer *FileDialog::get_vbox() {
return vbox;
-
}
void FileDialog::_notification(int p_what) {
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
refresh->set_icon(get_icon("reload"));
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
//RID ci = get_canvas_item();
//get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size()));
}
- if (p_what==NOTIFICATION_POPUP_HIDE) {
+ if (p_what == NOTIFICATION_POPUP_HIDE) {
set_process_unhandled_input(false);
}
}
-void FileDialog::_unhandled_input(const InputEvent& p_event) {
+void FileDialog::_unhandled_input(const InputEvent &p_event) {
- if (p_event.type==InputEvent::KEY && is_window_modal_on_top()) {
+ if (p_event.type == InputEvent::KEY && is_window_modal_on_top()) {
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
if (k.pressed) {
- bool handled=true;
+ bool handled = true;
switch (k.scancode) {
@@ -81,7 +77,7 @@ void FileDialog::_unhandled_input(const InputEvent& p_event) {
if (k.mod.command) {
set_show_hidden_files(!show_hidden_files);
} else {
- handled=false;
+ handled = false;
}
} break;
@@ -89,7 +85,7 @@ void FileDialog::_unhandled_input(const InputEvent& p_event) {
invalidate();
} break;
- default: { handled=false; }
+ default: { handled = false; }
}
if (handled)
@@ -100,15 +96,15 @@ void FileDialog::_unhandled_input(const InputEvent& p_event) {
void FileDialog::set_enable_multiple_selection(bool p_enable) {
- tree->set_select_mode(p_enable?Tree::SELECT_MULTI : Tree::SELECT_SINGLE);
+ tree->set_select_mode(p_enable ? Tree::SELECT_MULTI : Tree::SELECT_SINGLE);
};
Vector<String> FileDialog::get_selected_files() const {
Vector<String> list;
- TreeItem* item = tree->get_root();
- while ( (item = tree->get_next_selected(item)) ) {
+ TreeItem *item = tree->get_root();
+ while ((item = tree->get_next_selected(item))) {
list.push_back(dir_access->get_current_dir().plus_file(item->get_text(0)));
};
@@ -123,21 +119,20 @@ void FileDialog::update_dir() {
void FileDialog::_dir_entered(String p_dir) {
-
dir_access->change_dir(p_dir);
file->set_text("");
invalidate();
update_dir();
}
-void FileDialog::_file_entered(const String& p_file) {
+void FileDialog::_file_entered(const String &p_file) {
_action_pressed();
}
void FileDialog::_save_confirm_pressed() {
- String f=dir_access->get_current_dir().plus_file(file->get_text());
- emit_signal("file_selected",f);
+ String f = dir_access->get_current_dir().plus_file(file->get_text());
+ emit_signal("file_selected", f);
hide();
}
@@ -146,77 +141,76 @@ void FileDialog::_post_popup() {
ConfirmationDialog::_post_popup();
if (invalidated) {
update_file_list();
- invalidated=false;
+ invalidated = false;
}
- if (mode==MODE_SAVE_FILE)
+ if (mode == MODE_SAVE_FILE)
file->grab_focus();
else
tree->grab_focus();
set_process_unhandled_input(true);
-
}
void FileDialog::_action_pressed() {
- if (mode==MODE_OPEN_FILES) {
+ if (mode == MODE_OPEN_FILES) {
- TreeItem *ti=tree->get_next_selected(NULL);
- String fbase=dir_access->get_current_dir();
+ TreeItem *ti = tree->get_next_selected(NULL);
+ String fbase = dir_access->get_current_dir();
PoolVector<String> files;
- while(ti) {
+ while (ti) {
- files.push_back( fbase.plus_file(ti->get_text(0)) );
- ti=tree->get_next_selected(ti);
+ files.push_back(fbase.plus_file(ti->get_text(0)));
+ ti = tree->get_next_selected(ti);
}
if (files.size()) {
- emit_signal("files_selected",files);
+ emit_signal("files_selected", files);
hide();
}
return;
}
- String f=dir_access->get_current_dir().plus_file(file->get_text());
+ String f = dir_access->get_current_dir().plus_file(file->get_text());
- if ((mode==MODE_OPEN_ANY || mode==MODE_OPEN_FILE) && dir_access->file_exists(f)) {
- emit_signal("file_selected",f);
+ if ((mode == MODE_OPEN_ANY || mode == MODE_OPEN_FILE) && dir_access->file_exists(f)) {
+ emit_signal("file_selected", f);
hide();
- }else if (mode==MODE_OPEN_ANY || mode==MODE_OPEN_DIR) {
+ } else if (mode == MODE_OPEN_ANY || mode == MODE_OPEN_DIR) {
- String path=dir_access->get_current_dir();
+ String path = dir_access->get_current_dir();
- path=path.replace("\\","/");
+ path = path.replace("\\", "/");
- if (TreeItem* item = tree->get_selected()) {
+ if (TreeItem *item = tree->get_selected()) {
Dictionary d = item->get_metadata(0);
if (d["dir"]) {
- path=path.plus_file(d["name"]);
+ path = path.plus_file(d["name"]);
}
}
- emit_signal("dir_selected",path);
+ emit_signal("dir_selected", path);
hide();
}
- if (mode==MODE_SAVE_FILE) {
+ if (mode == MODE_SAVE_FILE) {
- bool valid=false;
+ bool valid = false;
- if (filter->get_selected()==filter->get_item_count()-1) {
- valid=true; //match none
- } else if (filters.size()>1 && filter->get_selected()==0) {
+ if (filter->get_selected() == filter->get_item_count() - 1) {
+ valid = true; //match none
+ } else if (filters.size() > 1 && filter->get_selected() == 0) {
// match all filters
- for (int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String flt=filters[i].get_slice(";",0);
- for (int j=0;j<flt.get_slice_count(",");j++) {
+ String flt = filters[i].get_slice(";", 0);
+ for (int j = 0; j < flt.get_slice_count(","); j++) {
- String str = flt.get_slice(",",j).strip_edges();
+ String str = flt.get_slice(",", j).strip_edges();
if (f.match(str)) {
- valid=true;
+ valid = true;
break;
}
}
@@ -224,48 +218,45 @@ void FileDialog::_action_pressed() {
break;
}
} else {
- int idx=filter->get_selected();
- if (filters.size()>1)
+ int idx = filter->get_selected();
+ if (filters.size() > 1)
idx--;
- if (idx>=0 && idx<filters.size()) {
+ if (idx >= 0 && idx < filters.size()) {
- String flt=filters[idx].get_slice(";",0);
- int filterSliceCount=flt.get_slice_count(",");
- for (int j=0;j<filterSliceCount;j++) {
+ String flt = filters[idx].get_slice(";", 0);
+ int filterSliceCount = flt.get_slice_count(",");
+ for (int j = 0; j < filterSliceCount; j++) {
- String str = (flt.get_slice(",",j).strip_edges());
+ String str = (flt.get_slice(",", j).strip_edges());
if (f.match(str)) {
- valid=true;
+ valid = true;
break;
}
}
- if (!valid && filterSliceCount>0) {
- String str = (flt.get_slice(",",0).strip_edges());
- f+=str.substr(1, str.length()-1);
+ if (!valid && filterSliceCount > 0) {
+ String str = (flt.get_slice(",", 0).strip_edges());
+ f += str.substr(1, str.length() - 1);
file->set_text(f.get_file());
- valid=true;
+ valid = true;
}
} else {
- valid=true;
+ valid = true;
}
}
-
if (!valid) {
- exterr->popup_centered_minsize(Size2(250,80));
+ exterr->popup_centered_minsize(Size2(250, 80));
return;
-
}
if (dir_access->file_exists(f)) {
confirm_save->set_text(RTR("File Exists, Overwrite?"));
- confirm_save->popup_centered(Size2(200,80));
+ confirm_save->popup_centered(Size2(200, 80));
} else {
-
- emit_signal("file_selected",f);
+ emit_signal("file_selected", f);
hide();
}
}
@@ -280,31 +271,29 @@ void FileDialog::_cancel_pressed() {
void FileDialog::_tree_selected() {
- TreeItem *ti=tree->get_selected();
+ TreeItem *ti = tree->get_selected();
if (!ti)
return;
- Dictionary d=ti->get_metadata(0);
+ Dictionary d = ti->get_metadata(0);
if (!d["dir"]) {
file->set_text(d["name"]);
}
-
}
void FileDialog::_tree_dc_selected() {
-
- TreeItem *ti=tree->get_selected();
+ TreeItem *ti = tree->get_selected();
if (!ti)
return;
- Dictionary d=ti->get_metadata(0);
+ Dictionary d = ti->get_metadata(0);
if (d["dir"]) {
dir_access->change_dir(d["name"]);
- if (mode==MODE_OPEN_FILE || mode==MODE_OPEN_FILES || mode==MODE_OPEN_DIR || mode==MODE_OPEN_ANY)
+ if (mode == MODE_OPEN_FILE || mode == MODE_OPEN_FILES || mode == MODE_OPEN_DIR || mode == MODE_OPEN_ANY)
file->set_text("");
call_deferred("_update_file_list");
call_deferred("_update_dir");
@@ -329,7 +318,7 @@ void FileDialog::update_file_list() {
bool show_hidden = show_hidden_files;
String item;
- while ((item=dir_access->get_next(&isdir))!="") {
+ while ((item = dir_access->get_next(&isdir)) != "") {
ishidden = dir_access->current_is_hidden();
@@ -341,7 +330,7 @@ void FileDialog::update_file_list() {
}
}
- if (dirs.find("..")==NULL) {
+ if (dirs.find("..") == NULL) {
//may happen if lacking permissions
dirs.push_back("..");
}
@@ -349,17 +338,17 @@ void FileDialog::update_file_list() {
dirs.sort_custom<NoCaseComparator>();
files.sort_custom<NoCaseComparator>();
- while(!dirs.empty()) {
- String& dir_name = dirs.front()->get();
- TreeItem *ti=tree->create_item(root);
- ti->set_text(0,dir_name+"/");
- ti->set_icon(0,folder);
+ while (!dirs.empty()) {
+ String &dir_name = dirs.front()->get();
+ TreeItem *ti = tree->create_item(root);
+ ti->set_text(0, dir_name + "/");
+ ti->set_icon(0, folder);
Dictionary d;
- d["name"]=dir_name;
- d["dir"]=true;
+ d["name"] = dir_name;
+ d["dir"] = true;
- ti->set_metadata(0,d);
+ ti->set_metadata(0, d);
dirs.pop_front();
}
@@ -368,83 +357,80 @@ void FileDialog::update_file_list() {
List<String> patterns;
// build filter
- if (filter->get_selected()==filter->get_item_count()-1) {
+ if (filter->get_selected() == filter->get_item_count() - 1) {
// match all
- } else if (filters.size()>1 && filter->get_selected()==0) {
+ } else if (filters.size() > 1 && filter->get_selected() == 0) {
// match all filters
- for (int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String f=filters[i].get_slice(";",0);
- for (int j=0;j<f.get_slice_count(",");j++) {
+ String f = filters[i].get_slice(";", 0);
+ for (int j = 0; j < f.get_slice_count(","); j++) {
- patterns.push_back(f.get_slice(",",j).strip_edges());
+ patterns.push_back(f.get_slice(",", j).strip_edges());
}
}
} else {
- int idx=filter->get_selected();
- if (filters.size()>1)
+ int idx = filter->get_selected();
+ if (filters.size() > 1)
idx--;
- if (idx>=0 && idx<filters.size()) {
+ if (idx >= 0 && idx < filters.size()) {
- String f=filters[idx].get_slice(";",0);
- for (int j=0;j<f.get_slice_count(",");j++) {
+ String f = filters[idx].get_slice(";", 0);
+ for (int j = 0; j < f.get_slice_count(","); j++) {
- patterns.push_back(f.get_slice(",",j).strip_edges());
+ patterns.push_back(f.get_slice(",", j).strip_edges());
}
}
}
-
String base_dir = dir_access->get_current_dir();
+ while (!files.empty()) {
- while(!files.empty()) {
-
- bool match=patterns.empty();
+ bool match = patterns.empty();
String match_str;
- for(List<String>::Element *E=patterns.front();E;E=E->next()) {
+ for (List<String>::Element *E = patterns.front(); E; E = E->next()) {
if (files.front()->get().matchn(E->get())) {
- match_str=E->get();
- match=true;
+ match_str = E->get();
+ match = true;
break;
}
}
if (match) {
- TreeItem *ti=tree->create_item(root);
- ti->set_text(0,files.front()->get());
+ TreeItem *ti = tree->create_item(root);
+ ti->set_text(0, files.front()->get());
if (get_icon_func) {
Ref<Texture> icon = get_icon_func(base_dir.plus_file(files.front()->get()));
- ti->set_icon(0,icon);
+ ti->set_icon(0, icon);
}
- if (mode==MODE_OPEN_DIR) {
- ti->set_custom_color(0,get_color("files_disabled"));
- ti->set_selectable(0,false);
+ if (mode == MODE_OPEN_DIR) {
+ ti->set_custom_color(0, get_color("files_disabled"));
+ ti->set_selectable(0, false);
}
Dictionary d;
- d["name"]=files.front()->get();
- d["dir"]=false;
- ti->set_metadata(0,d);
+ d["name"] = files.front()->get();
+ d["dir"] = false;
+ ti->set_metadata(0, d);
- if (file->get_text()==files.front()->get() || match_str==files.front()->get())
+ if (file->get_text() == files.front()->get() || match_str == files.front()->get())
ti->select(0);
}
files.pop_front();
}
- if (tree->get_root() && tree->get_root()->get_children() && tree->get_selected()==NULL)
+ if (tree->get_root() && tree->get_root()->get_children() && tree->get_selected() == NULL)
tree->get_root()->get_children()->select(0);
files.clear();
-
}
void FileDialog::_filter_selected(int) {
@@ -456,35 +442,34 @@ void FileDialog::update_filters() {
filter->clear();
- if (filters.size()>1) {
+ if (filters.size() > 1) {
String all_filters;
- const int max_filters=5;
+ const int max_filters = 5;
- for(int i=0;i<MIN( max_filters, filters.size()) ;i++) {
- String flt=filters[i].get_slice(";",0);
- if (i>0)
- all_filters+=",";
- all_filters+=flt;
+ for (int i = 0; i < MIN(max_filters, filters.size()); i++) {
+ String flt = filters[i].get_slice(";", 0);
+ if (i > 0)
+ all_filters += ",";
+ all_filters += flt;
}
- if (max_filters<filters.size())
- all_filters+=", ...";
+ if (max_filters < filters.size())
+ all_filters += ", ...";
- filter->add_item(RTR("All Recognized")+" ( "+all_filters+" )");
+ filter->add_item(RTR("All Recognized") + " ( " + all_filters + " )");
}
- for(int i=0;i<filters.size();i++) {
+ for (int i = 0; i < filters.size(); i++) {
- String flt=filters[i].get_slice(";",0).strip_edges();
- String desc=filters[i].get_slice(";",1).strip_edges();
+ String flt = filters[i].get_slice(";", 0).strip_edges();
+ String desc = filters[i].get_slice(";", 1).strip_edges();
if (desc.length())
- filter->add_item(String(XL_MESSAGE(desc))+" ( "+flt+" )");
+ filter->add_item(String(XL_MESSAGE(desc)) + " ( " + flt + " )");
else
- filter->add_item("( "+flt+" )");
+ filter->add_item("( " + flt + " )");
}
filter->add_item(RTR("All Files (*)"));
-
}
void FileDialog::clear_filters() {
@@ -493,21 +478,20 @@ void FileDialog::clear_filters() {
update_filters();
invalidate();
}
-void FileDialog::add_filter(const String& p_filter) {
+void FileDialog::add_filter(const String &p_filter) {
filters.push_back(p_filter);
update_filters();
invalidate();
-
}
-void FileDialog::set_filters(const Vector<String>& p_filters){
- filters=p_filters;
+void FileDialog::set_filters(const Vector<String> &p_filters) {
+ filters = p_filters;
update_filters();
invalidate();
}
-Vector<String> FileDialog::get_filters() const{
+Vector<String> FileDialog::get_filters() const {
return filters;
}
@@ -523,61 +507,76 @@ String FileDialog::get_current_path() const {
return dir->get_text().plus_file(file->get_text());
}
-void FileDialog::set_current_dir(const String& p_dir) {
+void FileDialog::set_current_dir(const String &p_dir) {
dir_access->change_dir(p_dir);
update_dir();
invalidate();
-
}
-void FileDialog::set_current_file(const String& p_file) {
+void FileDialog::set_current_file(const String &p_file) {
file->set_text(p_file);
update_dir();
invalidate();
int lp = p_file.find_last(".");
- if (lp!=-1) {
- file->select(0,lp);
+ if (lp != -1) {
+ file->select(0, lp);
file->grab_focus();
}
-
-
}
-void FileDialog::set_current_path(const String& p_path) {
+void FileDialog::set_current_path(const String &p_path) {
if (!p_path.size())
return;
- int pos=MAX( p_path.find_last("/"), p_path.find_last("\\") );
- if (pos==-1) {
+ int pos = MAX(p_path.find_last("/"), p_path.find_last("\\"));
+ if (pos == -1) {
set_current_file(p_path);
} else {
- String dir=p_path.substr(0,pos);
- String file=p_path.substr(pos+1,p_path.length());
+ String dir = p_path.substr(0, pos);
+ String file = p_path.substr(pos + 1, p_path.length());
set_current_dir(dir);
set_current_file(file);
}
}
-
void FileDialog::set_mode(Mode p_mode) {
- mode=p_mode;
- switch(mode) {
-
- case MODE_OPEN_FILE: get_ok()->set_text(RTR("Open")); set_title(RTR("Open a File")); makedir->hide(); break;
- case MODE_OPEN_FILES: get_ok()->set_text(RTR("Open")); set_title(RTR("Open File(s)")); makedir->hide(); break;
- case MODE_OPEN_DIR: get_ok()->set_text(RTR("Open")); set_title(RTR("Open a Directory")); makedir->show(); break;
- case MODE_OPEN_ANY: get_ok()->set_text(RTR("Open")); set_title(RTR("Open a File or Directory")); makedir->show(); break;
- case MODE_SAVE_FILE: get_ok()->set_text(RTR("Save")); set_title(RTR("Save a File")); makedir->show(); break;
+ mode = p_mode;
+ switch (mode) {
+
+ case MODE_OPEN_FILE:
+ get_ok()->set_text(RTR("Open"));
+ set_title(RTR("Open a File"));
+ makedir->hide();
+ break;
+ case MODE_OPEN_FILES:
+ get_ok()->set_text(RTR("Open"));
+ set_title(RTR("Open File(s)"));
+ makedir->hide();
+ break;
+ case MODE_OPEN_DIR:
+ get_ok()->set_text(RTR("Open"));
+ set_title(RTR("Open a Directory"));
+ makedir->show();
+ break;
+ case MODE_OPEN_ANY:
+ get_ok()->set_text(RTR("Open"));
+ set_title(RTR("Open a File or Directory"));
+ makedir->show();
+ break;
+ case MODE_SAVE_FILE:
+ get_ok()->set_text(RTR("Save"));
+ set_title(RTR("Save a File"));
+ makedir->show();
+ break;
}
- if (mode==MODE_OPEN_FILES) {
+ if (mode == MODE_OPEN_FILES) {
tree->set_select_mode(Tree::SELECT_MULTI);
} else {
tree->set_select_mode(Tree::SELECT_SINGLE);
-
}
}
@@ -588,11 +587,11 @@ FileDialog::Mode FileDialog::get_mode() const {
void FileDialog::set_access(Access p_access) {
- ERR_FAIL_INDEX(p_access,3);
- if (access==p_access)
+ ERR_FAIL_INDEX(p_access, 3);
+ if (access == p_access)
return;
- memdelete( dir_access );
- switch(p_access) {
+ memdelete(dir_access);
+ switch (p_access) {
case ACCESS_FILESYSTEM: {
dir_access = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
@@ -606,7 +605,7 @@ void FileDialog::set_access(Access p_access) {
dir_access = DirAccess::create(DirAccess::ACCESS_USERDATA);
} break;
}
- access=p_access;
+ access = p_access;
_update_drives();
invalidate();
update_filters();
@@ -617,38 +616,35 @@ void FileDialog::invalidate() {
if (is_visible_in_tree()) {
update_file_list();
- invalidated=false;
+ invalidated = false;
} else {
- invalidated=true;
+ invalidated = true;
}
-
}
-FileDialog::Access FileDialog::get_access() const{
+FileDialog::Access FileDialog::get_access() const {
return access;
}
void FileDialog::_make_dir_confirm() {
- Error err = dir_access->make_dir( makedirname->get_text() );
- if (err==OK) {
+ Error err = dir_access->make_dir(makedirname->get_text());
+ if (err == OK) {
dir_access->change_dir(makedirname->get_text());
invalidate();
update_filters();
update_dir();
} else {
- mkdirerr->popup_centered_minsize(Size2(250,50));
+ mkdirerr->popup_centered_minsize(Size2(250, 50));
}
makedirname->set_text(""); // reset label
}
-
void FileDialog::_make_dir() {
- makedialog->popup_centered_minsize(Size2(250,80));
+ makedialog->popup_centered_minsize(Size2(250, 80));
makedirname->grab_focus();
-
}
void FileDialog::_select_drive(int p_idx) {
@@ -658,95 +654,89 @@ void FileDialog::_select_drive(int p_idx) {
file->set_text("");
invalidate();
update_dir();
-
}
void FileDialog::_update_drives() {
-
int dc = dir_access->get_drive_count();
- if (dc==0 || access!=ACCESS_FILESYSTEM) {
+ if (dc == 0 || access != ACCESS_FILESYSTEM) {
drives->hide();
} else {
drives->clear();
drives->show();
- for(int i=0;i<dir_access->get_drive_count();i++) {
+ for (int i = 0; i < dir_access->get_drive_count(); i++) {
String d = dir_access->get_drive(i);
drives->add_item(dir_access->get_drive(i));
}
drives->select(dir_access->get_current_drive());
-
}
}
-bool FileDialog::default_show_hidden_files=false;
-
+bool FileDialog::default_show_hidden_files = false;
void FileDialog::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_unhandled_input"),&FileDialog::_unhandled_input);
-
- ClassDB::bind_method(D_METHOD("_tree_selected"),&FileDialog::_tree_selected);
- ClassDB::bind_method(D_METHOD("_tree_db_selected"),&FileDialog::_tree_dc_selected);
- ClassDB::bind_method(D_METHOD("_dir_entered"),&FileDialog::_dir_entered);
- ClassDB::bind_method(D_METHOD("_file_entered"),&FileDialog::_file_entered);
- ClassDB::bind_method(D_METHOD("_action_pressed"),&FileDialog::_action_pressed);
- ClassDB::bind_method(D_METHOD("_cancel_pressed"),&FileDialog::_cancel_pressed);
- ClassDB::bind_method(D_METHOD("_filter_selected"),&FileDialog::_filter_selected);
- ClassDB::bind_method(D_METHOD("_save_confirm_pressed"),&FileDialog::_save_confirm_pressed);
-
- ClassDB::bind_method(D_METHOD("clear_filters"),&FileDialog::clear_filters);
- ClassDB::bind_method(D_METHOD("add_filter","filter"),&FileDialog::add_filter);
- ClassDB::bind_method(D_METHOD("set_filters","filters"),&FileDialog::set_filters);
- ClassDB::bind_method(D_METHOD("get_filters"),&FileDialog::get_filters);
- ClassDB::bind_method(D_METHOD("get_current_dir"),&FileDialog::get_current_dir);
- ClassDB::bind_method(D_METHOD("get_current_file"),&FileDialog::get_current_file);
- ClassDB::bind_method(D_METHOD("get_current_path"),&FileDialog::get_current_path);
- ClassDB::bind_method(D_METHOD("set_current_dir","dir"),&FileDialog::set_current_dir);
- ClassDB::bind_method(D_METHOD("set_current_file","file"),&FileDialog::set_current_file);
- ClassDB::bind_method(D_METHOD("set_current_path","path"),&FileDialog::set_current_path);
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&FileDialog::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&FileDialog::get_mode);
- ClassDB::bind_method(D_METHOD("get_vbox:VBoxContainer"),&FileDialog::get_vbox);
- ClassDB::bind_method(D_METHOD("set_access","access"),&FileDialog::set_access);
- ClassDB::bind_method(D_METHOD("get_access"),&FileDialog::get_access);
- ClassDB::bind_method(D_METHOD("set_show_hidden_files","show"),&FileDialog::set_show_hidden_files);
- ClassDB::bind_method(D_METHOD("is_showing_hidden_files"),&FileDialog::is_showing_hidden_files);
- ClassDB::bind_method(D_METHOD("_select_drive"),&FileDialog::_select_drive);
- ClassDB::bind_method(D_METHOD("_make_dir"),&FileDialog::_make_dir);
- ClassDB::bind_method(D_METHOD("_make_dir_confirm"),&FileDialog::_make_dir_confirm);
- ClassDB::bind_method(D_METHOD("_update_file_list"),&FileDialog::update_file_list);
- ClassDB::bind_method(D_METHOD("_update_dir"),&FileDialog::update_dir);
-
- ClassDB::bind_method(D_METHOD("invalidate"),&FileDialog::invalidate);
-
- ADD_SIGNAL(MethodInfo("file_selected",PropertyInfo( Variant::STRING,"path")));
- ADD_SIGNAL(MethodInfo("files_selected",PropertyInfo( Variant::POOL_STRING_ARRAY,"paths")));
- ADD_SIGNAL(MethodInfo("dir_selected",PropertyInfo( Variant::STRING,"dir")));
-
- BIND_CONSTANT( MODE_OPEN_FILE );
- BIND_CONSTANT( MODE_OPEN_FILES );
- BIND_CONSTANT( MODE_OPEN_DIR );
- BIND_CONSTANT( MODE_OPEN_ANY );
-
- BIND_CONSTANT( MODE_SAVE_FILE );
-
- BIND_CONSTANT( ACCESS_RESOURCES );
- BIND_CONSTANT( ACCESS_USERDATA );
- BIND_CONSTANT( ACCESS_FILESYSTEM );
-
- ADD_PROPERTY( PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Open one,Open many,Open folder,Open any,Save"),"set_mode","get_mode") ;
- ADD_PROPERTY( PropertyInfo(Variant::INT, "access", PROPERTY_HINT_ENUM, "Resources,User data,File system"),"set_access","get_access") ;
- ADD_PROPERTY( PropertyInfo(Variant::POOL_STRING_ARRAY, "filters"),"set_filters","get_filters") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "show_hidden_files"),"set_show_hidden_files","is_showing_hidden_files") ;
-
+ ClassDB::bind_method(D_METHOD("_unhandled_input"), &FileDialog::_unhandled_input);
+
+ ClassDB::bind_method(D_METHOD("_tree_selected"), &FileDialog::_tree_selected);
+ ClassDB::bind_method(D_METHOD("_tree_db_selected"), &FileDialog::_tree_dc_selected);
+ ClassDB::bind_method(D_METHOD("_dir_entered"), &FileDialog::_dir_entered);
+ ClassDB::bind_method(D_METHOD("_file_entered"), &FileDialog::_file_entered);
+ ClassDB::bind_method(D_METHOD("_action_pressed"), &FileDialog::_action_pressed);
+ ClassDB::bind_method(D_METHOD("_cancel_pressed"), &FileDialog::_cancel_pressed);
+ ClassDB::bind_method(D_METHOD("_filter_selected"), &FileDialog::_filter_selected);
+ ClassDB::bind_method(D_METHOD("_save_confirm_pressed"), &FileDialog::_save_confirm_pressed);
+
+ ClassDB::bind_method(D_METHOD("clear_filters"), &FileDialog::clear_filters);
+ ClassDB::bind_method(D_METHOD("add_filter", "filter"), &FileDialog::add_filter);
+ ClassDB::bind_method(D_METHOD("set_filters", "filters"), &FileDialog::set_filters);
+ ClassDB::bind_method(D_METHOD("get_filters"), &FileDialog::get_filters);
+ ClassDB::bind_method(D_METHOD("get_current_dir"), &FileDialog::get_current_dir);
+ ClassDB::bind_method(D_METHOD("get_current_file"), &FileDialog::get_current_file);
+ ClassDB::bind_method(D_METHOD("get_current_path"), &FileDialog::get_current_path);
+ ClassDB::bind_method(D_METHOD("set_current_dir", "dir"), &FileDialog::set_current_dir);
+ ClassDB::bind_method(D_METHOD("set_current_file", "file"), &FileDialog::set_current_file);
+ ClassDB::bind_method(D_METHOD("set_current_path", "path"), &FileDialog::set_current_path);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &FileDialog::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &FileDialog::get_mode);
+ ClassDB::bind_method(D_METHOD("get_vbox:VBoxContainer"), &FileDialog::get_vbox);
+ ClassDB::bind_method(D_METHOD("set_access", "access"), &FileDialog::set_access);
+ ClassDB::bind_method(D_METHOD("get_access"), &FileDialog::get_access);
+ ClassDB::bind_method(D_METHOD("set_show_hidden_files", "show"), &FileDialog::set_show_hidden_files);
+ ClassDB::bind_method(D_METHOD("is_showing_hidden_files"), &FileDialog::is_showing_hidden_files);
+ ClassDB::bind_method(D_METHOD("_select_drive"), &FileDialog::_select_drive);
+ ClassDB::bind_method(D_METHOD("_make_dir"), &FileDialog::_make_dir);
+ ClassDB::bind_method(D_METHOD("_make_dir_confirm"), &FileDialog::_make_dir_confirm);
+ ClassDB::bind_method(D_METHOD("_update_file_list"), &FileDialog::update_file_list);
+ ClassDB::bind_method(D_METHOD("_update_dir"), &FileDialog::update_dir);
+
+ ClassDB::bind_method(D_METHOD("invalidate"), &FileDialog::invalidate);
+
+ ADD_SIGNAL(MethodInfo("file_selected", PropertyInfo(Variant::STRING, "path")));
+ ADD_SIGNAL(MethodInfo("files_selected", PropertyInfo(Variant::POOL_STRING_ARRAY, "paths")));
+ ADD_SIGNAL(MethodInfo("dir_selected", PropertyInfo(Variant::STRING, "dir")));
+
+ BIND_CONSTANT(MODE_OPEN_FILE);
+ BIND_CONSTANT(MODE_OPEN_FILES);
+ BIND_CONSTANT(MODE_OPEN_DIR);
+ BIND_CONSTANT(MODE_OPEN_ANY);
+
+ BIND_CONSTANT(MODE_SAVE_FILE);
+
+ BIND_CONSTANT(ACCESS_RESOURCES);
+ BIND_CONSTANT(ACCESS_USERDATA);
+ BIND_CONSTANT(ACCESS_FILESYSTEM);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Open one,Open many,Open folder,Open any,Save"), "set_mode", "get_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "access", PROPERTY_HINT_ENUM, "Resources,User data,File system"), "set_access", "get_access");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_STRING_ARRAY, "filters"), "set_filters", "get_filters");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_hidden_files"), "set_show_hidden_files", "is_showing_hidden_files");
}
-
void FileDialog::set_show_hidden_files(bool p_show) {
- show_hidden_files=p_show;
+ show_hidden_files = p_show;
invalidate();
}
@@ -755,109 +745,100 @@ bool FileDialog::is_showing_hidden_files() const {
}
void FileDialog::set_default_show_hidden_files(bool p_show) {
- default_show_hidden_files=p_show;
+ default_show_hidden_files = p_show;
}
FileDialog::FileDialog() {
- show_hidden_files=default_show_hidden_files;
+ show_hidden_files = default_show_hidden_files;
- VBoxContainer *vbc = memnew( VBoxContainer );
+ VBoxContainer *vbc = memnew(VBoxContainer);
add_child(vbc);
-
- mode=MODE_SAVE_FILE;
+ mode = MODE_SAVE_FILE;
set_title(RTR("Save a File"));
dir = memnew(LineEdit);
- HBoxContainer *pathhb = memnew( HBoxContainer );
+ HBoxContainer *pathhb = memnew(HBoxContainer);
pathhb->add_child(dir);
dir->set_h_size_flags(SIZE_EXPAND_FILL);
- refresh = memnew( ToolButton );
- refresh->connect("pressed",this,"_update_file_list");
+ refresh = memnew(ToolButton);
+ refresh->connect("pressed", this, "_update_file_list");
pathhb->add_child(refresh);
- drives = memnew( OptionButton );
+ drives = memnew(OptionButton);
pathhb->add_child(drives);
- drives->connect("item_selected",this,"_select_drive");
+ drives->connect("item_selected", this, "_select_drive");
- makedir = memnew( Button );
+ makedir = memnew(Button);
makedir->set_text(RTR("Create Folder"));
- makedir->connect("pressed",this,"_make_dir");
+ makedir->connect("pressed", this, "_make_dir");
pathhb->add_child(makedir);
- vbc->add_margin_child(RTR("Path:"),pathhb);
+ vbc->add_margin_child(RTR("Path:"), pathhb);
tree = memnew(Tree);
tree->set_hide_root(true);
- vbc->add_margin_child(RTR("Directories & Files:"),tree,true);
+ vbc->add_margin_child(RTR("Directories & Files:"), tree, true);
file = memnew(LineEdit);
//add_child(file);
- vbc->add_margin_child(RTR("File:"),file);
+ vbc->add_margin_child(RTR("File:"), file);
-
- filter = memnew( OptionButton );
+ filter = memnew(OptionButton);
//add_child(filter);
- vbc->add_margin_child(RTR("Filter:"),filter);
- filter->set_clip_text(true);//too many extensions overflow it
+ vbc->add_margin_child(RTR("Filter:"), filter);
+ filter->set_clip_text(true); //too many extensions overflow it
dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES);
- access=ACCESS_RESOURCES;
+ access = ACCESS_RESOURCES;
_update_drives();
-
- connect("confirmed", this,"_action_pressed");
+ connect("confirmed", this, "_action_pressed");
//cancel->connect("pressed", this,"_cancel_pressed");
- tree->connect("cell_selected", this,"_tree_selected",varray(),CONNECT_DEFERRED);
- tree->connect("item_activated", this,"_tree_db_selected",varray());
- dir->connect("text_entered", this,"_dir_entered");
- file->connect("text_entered", this,"_file_entered");
- filter->connect("item_selected", this,"_filter_selected");
-
+ tree->connect("cell_selected", this, "_tree_selected", varray(), CONNECT_DEFERRED);
+ tree->connect("item_activated", this, "_tree_db_selected", varray());
+ dir->connect("text_entered", this, "_dir_entered");
+ file->connect("text_entered", this, "_file_entered");
+ filter->connect("item_selected", this, "_filter_selected");
- confirm_save = memnew( ConfirmationDialog );
+ confirm_save = memnew(ConfirmationDialog);
confirm_save->set_as_toplevel(true);
add_child(confirm_save);
+ confirm_save->connect("confirmed", this, "_save_confirm_pressed");
- confirm_save->connect("confirmed", this,"_save_confirm_pressed");
-
- makedialog = memnew( ConfirmationDialog );
+ makedialog = memnew(ConfirmationDialog);
makedialog->set_title(RTR("Create Folder"));
- VBoxContainer *makevb= memnew( VBoxContainer );
+ VBoxContainer *makevb = memnew(VBoxContainer);
makedialog->add_child(makevb);
- makedirname = memnew( LineEdit );
- makevb->add_margin_child(RTR("Name:"),makedirname);
+ makedirname = memnew(LineEdit);
+ makevb->add_margin_child(RTR("Name:"), makedirname);
add_child(makedialog);
makedialog->register_text_enter(makedirname);
- makedialog->connect("confirmed",this,"_make_dir_confirm");
- mkdirerr = memnew( AcceptDialog );
+ makedialog->connect("confirmed", this, "_make_dir_confirm");
+ mkdirerr = memnew(AcceptDialog);
mkdirerr->set_text(RTR("Could not create folder."));
add_child(mkdirerr);
- exterr = memnew( AcceptDialog );
+ exterr = memnew(AcceptDialog);
exterr->set_text(RTR("Must use a valid extension."));
add_child(exterr);
-
//update_file_list();
update_filters();
update_dir();
set_hide_on_ok(false);
- vbox=vbc;
-
+ vbox = vbc;
- invalidated=true;
+ invalidated = true;
if (register_func)
register_func(this);
-
}
-
FileDialog::~FileDialog() {
if (unregister_func)
@@ -865,21 +846,19 @@ FileDialog::~FileDialog() {
memdelete(dir_access);
}
-
void LineEditFileChooser::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_browse"),&LineEditFileChooser::_browse);
- ClassDB::bind_method(D_METHOD("_chosen"),&LineEditFileChooser::_chosen);
- ClassDB::bind_method(D_METHOD("get_button:Button"),&LineEditFileChooser::get_button);
- ClassDB::bind_method(D_METHOD("get_line_edit:LineEdit"),&LineEditFileChooser::get_line_edit);
- ClassDB::bind_method(D_METHOD("get_file_dialog:FileDialog"),&LineEditFileChooser::get_file_dialog);
-
+ ClassDB::bind_method(D_METHOD("_browse"), &LineEditFileChooser::_browse);
+ ClassDB::bind_method(D_METHOD("_chosen"), &LineEditFileChooser::_chosen);
+ ClassDB::bind_method(D_METHOD("get_button:Button"), &LineEditFileChooser::get_button);
+ ClassDB::bind_method(D_METHOD("get_line_edit:LineEdit"), &LineEditFileChooser::get_line_edit);
+ ClassDB::bind_method(D_METHOD("get_file_dialog:FileDialog"), &LineEditFileChooser::get_file_dialog);
}
-void LineEditFileChooser::_chosen(const String& p_text){
+void LineEditFileChooser::_chosen(const String &p_text) {
line_edit->set_text(p_text);
- line_edit->emit_signal("text_entered",p_text);
+ line_edit->emit_signal("text_entered", p_text);
}
void LineEditFileChooser::_browse() {
@@ -889,18 +868,16 @@ void LineEditFileChooser::_browse() {
LineEditFileChooser::LineEditFileChooser() {
- line_edit = memnew( LineEdit );
+ line_edit = memnew(LineEdit);
add_child(line_edit);
line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
- button = memnew( Button );
+ button = memnew(Button);
button->set_text(" .. ");
add_child(button);
- button->connect("pressed",this,"_browse");
- dialog = memnew( FileDialog);
+ button->connect("pressed", this, "_browse");
+ dialog = memnew(FileDialog);
add_child(dialog);
- dialog->connect("file_selected",this,"_chosen");
- dialog->connect("dir_selected",this,"_chosen");
- dialog->connect("files_selected",this,"_chosen");
-
+ dialog->connect("file_selected", this, "_chosen");
+ dialog->connect("dir_selected", this, "_chosen");
+ dialog->connect("files_selected", this, "_chosen");
}
-
diff --git a/scene/gui/file_dialog.h b/scene/gui/file_dialog.h
index 653b38e40d..397b0feba2 100644
--- a/scene/gui/file_dialog.h
+++ b/scene/gui/file_dialog.h
@@ -29,30 +29,28 @@
#ifndef FILE_DIALOG_H
#define FILE_DIALOG_H
+#include "box_container.h"
+#include "os/dir_access.h"
+#include "scene/gui/dialogs.h"
#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
#include "scene/gui/line_edit.h"
#include "scene/gui/option_button.h"
-#include "scene/gui/dialogs.h"
#include "scene/gui/tool_button.h"
-#include "os/dir_access.h"
-#include "box_container.h"
+#include "scene/gui/tree.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class FileDialog : public ConfirmationDialog {
- GDCLASS( FileDialog, ConfirmationDialog );
+ GDCLASS(FileDialog, ConfirmationDialog);
public:
-
enum Access {
ACCESS_RESOURCES,
ACCESS_USERDATA,
ACCESS_FILESYSTEM
};
-
enum Mode {
MODE_OPEN_FILE,
MODE_OPEN_FILES,
@@ -61,8 +59,8 @@ public:
MODE_SAVE_FILE
};
- typedef Ref<Texture> (*GetIconFunc)(const String&);
- typedef void (*RegisterFunc)(FileDialog*);
+ typedef Ref<Texture> (*GetIconFunc)(const String &);
+ typedef void (*RegisterFunc)(FileDialog *);
static GetIconFunc get_icon_func;
static GetIconFunc get_large_icon_func;
@@ -70,7 +68,6 @@ public:
static RegisterFunc unregister_func;
private:
-
ConfirmationDialog *makedialog;
LineEdit *makedirname;
@@ -93,7 +90,6 @@ private:
Vector<String> filters;
-
static bool default_show_hidden_files;
bool show_hidden_files;
@@ -108,7 +104,7 @@ private:
void _select_drive(int p_idx);
void _tree_dc_selected();
void _dir_entered(String p_dir);
- void _file_entered(const String& p_file);
+ void _file_entered(const String &p_file);
void _action_pressed();
void _save_confirm_pressed();
void _cancel_pressed();
@@ -118,20 +114,18 @@ private:
void _update_drives();
- void _unhandled_input(const InputEvent& p_event);
+ void _unhandled_input(const InputEvent &p_event);
virtual void _post_popup();
protected:
-
void _notification(int p_what);
static void _bind_methods();
//bind helpers
public:
-
void clear_filters();
- void add_filter(const String& p_filter);
- void set_filters(const Vector<String>& p_filters);
+ void add_filter(const String &p_filter);
+ void set_filters(const Vector<String> &p_filters);
Vector<String> get_filters() const;
void set_enable_multiple_selection(bool p_enable);
@@ -140,9 +134,9 @@ public:
String get_current_dir() const;
String get_current_file() const;
String get_current_path() const;
- void set_current_dir(const String& p_dir);
- void set_current_file(const String& p_file);
- void set_current_path(const String& p_path);
+ void set_current_dir(const String &p_dir);
+ void set_current_file(const String &p_file);
+ void set_current_path(const String &p_path);
void set_mode(Mode p_mode);
Mode get_mode() const;
@@ -162,22 +156,22 @@ public:
FileDialog();
~FileDialog();
-
};
class LineEditFileChooser : public HBoxContainer {
- GDCLASS( LineEditFileChooser, HBoxContainer );
+ GDCLASS(LineEditFileChooser, HBoxContainer);
Button *button;
LineEdit *line_edit;
FileDialog *dialog;
- void _chosen(const String& p_text);
+ void _chosen(const String &p_text);
void _browse();
+
protected:
static void _bind_methods();
-public:
+public:
Button *get_button() { return button; }
LineEdit *get_line_edit() { return line_edit; }
FileDialog *get_file_dialog() { return dialog; }
@@ -185,7 +179,7 @@ public:
LineEditFileChooser();
};
-VARIANT_ENUM_CAST( FileDialog::Mode );
-VARIANT_ENUM_CAST( FileDialog::Access );
+VARIANT_ENUM_CAST(FileDialog::Mode);
+VARIANT_ENUM_CAST(FileDialog::Access);
#endif
diff --git a/scene/gui/graph_edit.cpp b/scene/gui/graph_edit.cpp
index a6954a2c77..6a3b5e713c 100644
--- a/scene/gui/graph_edit.cpp
+++ b/scene/gui/graph_edit.cpp
@@ -31,34 +31,30 @@
#include "os/keyboard.h"
#include "scene/gui/box_container.h"
-
#define ZOOM_SCALE 1.2
-#define MIN_ZOOM (((1/ZOOM_SCALE)/ZOOM_SCALE)/ZOOM_SCALE)
-#define MAX_ZOOM (1*ZOOM_SCALE*ZOOM_SCALE*ZOOM_SCALE)
-
+#define MIN_ZOOM (((1 / ZOOM_SCALE) / ZOOM_SCALE) / ZOOM_SCALE)
+#define MAX_ZOOM (1 * ZOOM_SCALE * ZOOM_SCALE * ZOOM_SCALE)
-bool GraphEditFilter::has_point(const Point2& p_point) const {
+bool GraphEditFilter::has_point(const Point2 &p_point) const {
return ge->_filter_input(p_point);
}
-
GraphEditFilter::GraphEditFilter(GraphEdit *p_edit) {
- ge=p_edit;
+ ge = p_edit;
}
+Error GraphEdit::connect_node(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port) {
-Error GraphEdit::connect_node(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port) {
-
- if (is_node_connected(p_from,p_from_port,p_to,p_to_port))
+ if (is_node_connected(p_from, p_from_port, p_to, p_to_port))
return OK;
Connection c;
- c.from=p_from;
- c.from_port=p_from_port;
- c.to=p_to;
- c.to_port=p_to_port;
+ c.from = p_from;
+ c.from_port = p_from_port;
+ c.to = p_to;
+ c.to_port = p_to_port;
connections.push_back(c);
top_layer->update();
update();
@@ -67,23 +63,22 @@ Error GraphEdit::connect_node(const StringName& p_from, int p_from_port,const St
return OK;
}
-bool GraphEdit::is_node_connected(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port) {
+bool GraphEdit::is_node_connected(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port) {
- for(List<Connection>::Element *E=connections.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- if (E->get().from==p_from && E->get().from_port==p_from_port && E->get().to==p_to && E->get().to_port==p_to_port)
+ if (E->get().from == p_from && E->get().from_port == p_from_port && E->get().to == p_to && E->get().to_port == p_to_port)
return true;
}
return false;
-
}
-void GraphEdit::disconnect_node(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port){
+void GraphEdit::disconnect_node(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port) {
- for(List<Connection>::Element *E=connections.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- if (E->get().from==p_from && E->get().from_port==p_from_port && E->get().to==p_to && E->get().to_port==p_to_port) {
+ if (E->get().from == p_from && E->get().from_port == p_from_port && E->get().to == p_to && E->get().to_port == p_to_port) {
connections.erase(E);
top_layer->update();
@@ -101,35 +96,34 @@ bool GraphEdit::clips_input() const {
void GraphEdit::get_connection_list(List<Connection> *r_connections) const {
- *r_connections=connections;
+ *r_connections = connections;
}
-void GraphEdit::set_scroll_ofs(const Vector2& p_ofs) {
+void GraphEdit::set_scroll_ofs(const Vector2 &p_ofs) {
- setting_scroll_ofs=true;
+ setting_scroll_ofs = true;
h_scroll->set_value(p_ofs.x);
v_scroll->set_value(p_ofs.y);
_update_scroll();
- setting_scroll_ofs=false;
+ setting_scroll_ofs = false;
}
-Vector2 GraphEdit::get_scroll_ofs() const{
+Vector2 GraphEdit::get_scroll_ofs() const {
- return Vector2(h_scroll->get_value(),v_scroll->get_value());
+ return Vector2(h_scroll->get_value(), v_scroll->get_value());
}
void GraphEdit::_scroll_moved(double) {
-
if (!awaiting_scroll_offset_update) {
call_deferred("_update_scroll_offset");
- awaiting_scroll_offset_update=true;
+ awaiting_scroll_offset_update = true;
}
top_layer->update();
update();
- if (!setting_scroll_ofs) {//in godot, signals on change value are avoided as a convention
- emit_signal("scroll_offset_changed",get_scroll_ofs());
+ if (!setting_scroll_ofs) { //in godot, signals on change value are avoided as a convention
+ emit_signal("scroll_offset_changed", get_scroll_ofs());
}
}
@@ -137,24 +131,23 @@ void GraphEdit::_update_scroll_offset() {
set_block_minimum_size_adjust(true);
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
- Point2 pos=gn->get_offset()*zoom;
- pos-=Point2(h_scroll->get_value(),v_scroll->get_value());
+ Point2 pos = gn->get_offset() * zoom;
+ pos -= Point2(h_scroll->get_value(), v_scroll->get_value());
gn->set_pos(pos);
- if (gn->get_scale()!=Vector2(zoom,zoom)) {
- gn->set_scale(Vector2(zoom,zoom));
+ if (gn->get_scale() != Vector2(zoom, zoom)) {
+ gn->set_scale(Vector2(zoom, zoom));
}
}
- connections_layer->set_pos(-Point2(h_scroll->get_value(),v_scroll->get_value()));
+ connections_layer->set_pos(-Point2(h_scroll->get_value(), v_scroll->get_value()));
set_block_minimum_size_adjust(false);
- awaiting_scroll_offset_update=false;
-
+ awaiting_scroll_offset_update = false;
}
void GraphEdit::_update_scroll() {
@@ -162,29 +155,28 @@ void GraphEdit::_update_scroll() {
if (updating)
return;
- updating=true;
+ updating = true;
set_block_minimum_size_adjust(true);
Rect2 screen;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
Rect2 r;
- r.pos=gn->get_offset()*zoom;
- r.size=gn->get_size()*zoom;
+ r.pos = gn->get_offset() * zoom;
+ r.size = gn->get_size() * zoom;
screen = screen.merge(r);
}
- screen.pos-=get_size();
- screen.size+=get_size()*2.0;
-
+ screen.pos -= get_size();
+ screen.size += get_size() * 2.0;
h_scroll->set_min(screen.pos.x);
- h_scroll->set_max(screen.pos.x+screen.size.x);
+ h_scroll->set_max(screen.pos.x + screen.size.x);
h_scroll->set_page(get_size().x);
if (h_scroll->get_max() - h_scroll->get_min() <= h_scroll->get_page())
h_scroll->hide();
@@ -192,7 +184,7 @@ void GraphEdit::_update_scroll() {
h_scroll->show();
v_scroll->set_min(screen.pos.y);
- v_scroll->set_max(screen.pos.y+screen.size.y);
+ v_scroll->set_max(screen.pos.y + screen.size.y);
v_scroll->set_page(get_size().y);
if (v_scroll->get_max() - v_scroll->get_min() <= v_scroll->get_page())
@@ -204,40 +196,37 @@ void GraphEdit::_update_scroll() {
if (!awaiting_scroll_offset_update) {
call_deferred("_update_scroll_offset");
- awaiting_scroll_offset_update=true;
+ awaiting_scroll_offset_update = true;
}
- updating=false;
+ updating = false;
}
+void GraphEdit::_graph_node_raised(Node *p_gn) {
-void GraphEdit::_graph_node_raised(Node* p_gn) {
-
- GraphNode *gn=p_gn->cast_to<GraphNode>();
+ GraphNode *gn = p_gn->cast_to<GraphNode>();
ERR_FAIL_COND(!gn);
gn->raise();
if (gn->is_comment()) {
- move_child(gn,0);
+ move_child(gn, 0);
}
- int first_not_comment=0;
- for(int i=0;i<get_child_count();i++) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ int first_not_comment = 0;
+ for (int i = 0; i < get_child_count(); i++) {
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (gn && !gn->is_comment()) {
- first_not_comment=i;
+ first_not_comment = i;
break;
}
}
- move_child(connections_layer,first_not_comment);
+ move_child(connections_layer, first_not_comment);
top_layer->raise();
- emit_signal("node_selected",p_gn);
-
+ emit_signal("node_selected", p_gn);
}
-
void GraphEdit::_graph_node_moved(Node *p_gn) {
- GraphNode *gn=p_gn->cast_to<GraphNode>();
+ GraphNode *gn = p_gn->cast_to<GraphNode>();
ERR_FAIL_COND(!gn);
top_layer->update();
update();
@@ -251,15 +240,13 @@ void GraphEdit::add_child_notify(Node *p_child) {
top_layer->call_deferred("raise"); //top layer always on top!
GraphNode *gn = p_child->cast_to<GraphNode>();
if (gn) {
- gn->set_scale(Vector2(zoom,zoom));
- gn->connect("offset_changed",this,"_graph_node_moved",varray(gn));
- gn->connect("raise_request",this,"_graph_node_raised",varray(gn));
- gn->connect("item_rect_changed",connections_layer,"update");
+ gn->set_scale(Vector2(zoom, zoom));
+ gn->connect("offset_changed", this, "_graph_node_moved", varray(gn));
+ gn->connect("raise_request", this, "_graph_node_raised", varray(gn));
+ gn->connect("item_rect_changed", connections_layer, "update");
_graph_node_moved(gn);
gn->set_mouse_filter(MOUSE_FILTER_PASS);
}
-
-
}
void GraphEdit::remove_child_notify(Node *p_child) {
@@ -269,292 +256,268 @@ void GraphEdit::remove_child_notify(Node *p_child) {
top_layer->call_deferred("raise"); //top layer always on top!
GraphNode *gn = p_child->cast_to<GraphNode>();
if (gn) {
- gn->disconnect("offset_changed",this,"_graph_node_moved");
- gn->disconnect("raise_request",this,"_graph_node_raised");
+ gn->disconnect("offset_changed", this, "_graph_node_moved");
+ gn->disconnect("raise_request", this, "_graph_node_raised");
}
}
void GraphEdit::_notification(int p_what) {
- if (p_what==NOTIFICATION_READY) {
+ if (p_what == NOTIFICATION_READY) {
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
- v_scroll->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,vmin.width);
- v_scroll->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,0);
- v_scroll->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,0);
- v_scroll->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,0);
-
- h_scroll->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,0);
- h_scroll->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,0);
- h_scroll->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,hmin.height);
- h_scroll->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,0);
+ v_scroll->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, vmin.width);
+ v_scroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ v_scroll->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
+ v_scroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
+ h_scroll->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 0);
+ h_scroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ h_scroll->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, hmin.height);
+ h_scroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
zoom_minus->set_icon(get_icon("minus"));
zoom_reset->set_icon(get_icon("reset"));
zoom_plus->set_icon(get_icon("more"));
snap_button->set_icon(get_icon("snap"));
//zoom_icon->set_texture( get_icon("Zoom", "EditorIcons"));
-
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
-
- draw_style_box( get_stylebox("bg"),Rect2(Point2(),get_size()) );
+ draw_style_box(get_stylebox("bg"), Rect2(Point2(), get_size()));
if (is_using_snap()) {
//draw grid
int snap = get_snap();
- Vector2 offset = get_scroll_ofs()/zoom;
- Size2 size = get_size()/zoom;
+ Vector2 offset = get_scroll_ofs() / zoom;
+ Size2 size = get_size() / zoom;
- Point2i from = (offset/float(snap)).floor();
- Point2i len = (size/float(snap)).floor()+Vector2(1,1);
+ Point2i from = (offset / float(snap)).floor();
+ Point2i len = (size / float(snap)).floor() + Vector2(1, 1);
Color grid_minor = get_color("grid_minor");
Color grid_major = get_color("grid_major");
- for(int i=from.x;i<from.x+len.x;i++) {
+ for (int i = from.x; i < from.x + len.x; i++) {
Color color;
- if (ABS(i)%10==0)
- color=grid_major;
+ if (ABS(i) % 10 == 0)
+ color = grid_major;
else
- color=grid_minor;
+ color = grid_minor;
- float base_ofs = i*snap*zoom - offset.x*zoom;
- draw_line(Vector2(base_ofs,0),Vector2(base_ofs,get_size().height),color);
+ float base_ofs = i * snap * zoom - offset.x * zoom;
+ draw_line(Vector2(base_ofs, 0), Vector2(base_ofs, get_size().height), color);
}
- for(int i=from.y;i<from.y+len.y;i++) {
+ for (int i = from.y; i < from.y + len.y; i++) {
Color color;
- if (ABS(i)%10==0)
- color=grid_major;
+ if (ABS(i) % 10 == 0)
+ color = grid_major;
else
- color=grid_minor;
+ color = grid_minor;
- float base_ofs = i*snap*zoom - offset.y*zoom;
- draw_line(Vector2(0,base_ofs),Vector2(get_size().width,base_ofs),color);
+ float base_ofs = i * snap * zoom - offset.y * zoom;
+ draw_line(Vector2(0, base_ofs), Vector2(get_size().width, base_ofs), color);
}
-
}
-
-
-
}
- if (p_what==NOTIFICATION_RESIZED) {
+ if (p_what == NOTIFICATION_RESIZED) {
_update_scroll();
top_layer->update();
-
}
}
-bool GraphEdit::_filter_input(const Point2& p_point) {
+bool GraphEdit::_filter_input(const Point2 &p_point) {
- Ref<Texture> port =get_icon("port","GraphNode");
+ Ref<Texture> port = get_icon("port", "GraphNode");
float grab_r_extend = 2.0;
- float grab_r=port->get_width()*0.5*grab_r_extend;
- for(int i=get_child_count()-1;i>=0;i--) {
+ float grab_r = port->get_width() * 0.5 * grab_r_extend;
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
- for(int j=0;j<gn->get_connection_output_count();j++) {
+ for (int j = 0; j < gn->get_connection_output_count(); j++) {
- Vector2 pos = gn->get_connection_output_pos(j)+gn->get_pos();
- if (pos.distance_to(p_point)<grab_r)
+ Vector2 pos = gn->get_connection_output_pos(j) + gn->get_pos();
+ if (pos.distance_to(p_point) < grab_r)
return true;
-
-
}
- for(int j=0;j<gn->get_connection_input_count();j++) {
+ for (int j = 0; j < gn->get_connection_input_count(); j++) {
- Vector2 pos = gn->get_connection_input_pos(j)+gn->get_pos();
- if (pos.distance_to(p_point)<grab_r) {
+ Vector2 pos = gn->get_connection_input_pos(j) + gn->get_pos();
+ if (pos.distance_to(p_point) < grab_r) {
return true;
}
-
-
}
-
}
return false;
}
-void GraphEdit::_top_layer_input(const InputEvent& p_ev) {
-
+void GraphEdit::_top_layer_input(const InputEvent &p_ev) {
float grab_r_extend = 2.0;
- if (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index==BUTTON_LEFT && p_ev.mouse_button.pressed) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index == BUTTON_LEFT && p_ev.mouse_button.pressed) {
- Ref<Texture> port =get_icon("port","GraphNode");
- Vector2 mpos(p_ev.mouse_button.x,p_ev.mouse_button.y);
- float grab_r=port->get_width()*0.5*grab_r_extend;
- for(int i=get_child_count()-1;i>=0;i--) {
+ Ref<Texture> port = get_icon("port", "GraphNode");
+ Vector2 mpos(p_ev.mouse_button.x, p_ev.mouse_button.y);
+ float grab_r = port->get_width() * 0.5 * grab_r_extend;
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
- for(int j=0;j<gn->get_connection_output_count();j++) {
-
- Vector2 pos = gn->get_connection_output_pos(j)+gn->get_pos();
- if (pos.distance_to(mpos)<grab_r) {
+ for (int j = 0; j < gn->get_connection_output_count(); j++) {
+ Vector2 pos = gn->get_connection_output_pos(j) + gn->get_pos();
+ if (pos.distance_to(mpos) < grab_r) {
if (valid_left_disconnect_types.has(gn->get_connection_output_type(j))) {
//check disconnect
- for (List<Connection>::Element*E=connections.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- if (E->get().from==gn->get_name() && E->get().from_port==j) {
+ if (E->get().from == gn->get_name() && E->get().from_port == j) {
- Node*to = get_node(String(E->get().to));
+ Node *to = get_node(String(E->get().to));
if (to && to->cast_to<GraphNode>()) {
- connecting_from=E->get().to;
- connecting_index=E->get().to_port;
- connecting_out=false;
- connecting_type=to->cast_to<GraphNode>()->get_connection_input_type(E->get().to_port);
- connecting_color=to->cast_to<GraphNode>()->get_connection_input_color(E->get().to_port);
- connecting_target=false;
- connecting_to=pos;
- just_disconected=true;
+ connecting_from = E->get().to;
+ connecting_index = E->get().to_port;
+ connecting_out = false;
+ connecting_type = to->cast_to<GraphNode>()->get_connection_input_type(E->get().to_port);
+ connecting_color = to->cast_to<GraphNode>()->get_connection_input_color(E->get().to_port);
+ connecting_target = false;
+ connecting_to = pos;
+ just_disconected = true;
- emit_signal("disconnection_request",E->get().from,E->get().from_port,E->get().to,E->get().to_port);
+ emit_signal("disconnection_request", E->get().from, E->get().from_port, E->get().to, E->get().to_port);
to = get_node(String(connecting_from)); //maybe it was erased
if (to && to->cast_to<GraphNode>()) {
- connecting=true;
+ connecting = true;
}
return;
}
-
}
}
}
- connecting=true;
- connecting_from=gn->get_name();
- connecting_index=j;
- connecting_out=true;
- connecting_type=gn->get_connection_output_type(j);
- connecting_color=gn->get_connection_output_color(j);
- connecting_target=false;
- connecting_to=pos;
- just_disconected=false;
+ connecting = true;
+ connecting_from = gn->get_name();
+ connecting_index = j;
+ connecting_out = true;
+ connecting_type = gn->get_connection_output_type(j);
+ connecting_color = gn->get_connection_output_color(j);
+ connecting_target = false;
+ connecting_to = pos;
+ just_disconected = false;
return;
}
-
-
}
- for(int j=0;j<gn->get_connection_input_count();j++) {
+ for (int j = 0; j < gn->get_connection_input_count(); j++) {
- Vector2 pos = gn->get_connection_input_pos(j)+gn->get_pos();
+ Vector2 pos = gn->get_connection_input_pos(j) + gn->get_pos();
- if (pos.distance_to(mpos)<grab_r) {
+ if (pos.distance_to(mpos) < grab_r) {
if (right_disconnects || valid_right_disconnect_types.has(gn->get_connection_input_type(j))) {
//check disconnect
- for (List<Connection>::Element*E=connections.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
- if (E->get().to==gn->get_name() && E->get().to_port==j) {
+ if (E->get().to == gn->get_name() && E->get().to_port == j) {
- Node*fr = get_node(String(E->get().from));
+ Node *fr = get_node(String(E->get().from));
if (fr && fr->cast_to<GraphNode>()) {
- connecting_from=E->get().from;
- connecting_index=E->get().from_port;
- connecting_out=true;
- connecting_type=fr->cast_to<GraphNode>()->get_connection_output_type(E->get().from_port);
- connecting_color=fr->cast_to<GraphNode>()->get_connection_output_color(E->get().from_port);
- connecting_target=false;
- connecting_to=pos;
- just_disconected=true;
+ connecting_from = E->get().from;
+ connecting_index = E->get().from_port;
+ connecting_out = true;
+ connecting_type = fr->cast_to<GraphNode>()->get_connection_output_type(E->get().from_port);
+ connecting_color = fr->cast_to<GraphNode>()->get_connection_output_color(E->get().from_port);
+ connecting_target = false;
+ connecting_to = pos;
+ just_disconected = true;
- emit_signal("disconnection_request",E->get().from,E->get().from_port,E->get().to,E->get().to_port);
+ emit_signal("disconnection_request", E->get().from, E->get().from_port, E->get().to, E->get().to_port);
fr = get_node(String(connecting_from)); //maybe it was erased
if (fr && fr->cast_to<GraphNode>()) {
- connecting=true;
+ connecting = true;
}
return;
}
-
}
}
}
-
- connecting=true;
- connecting_from=gn->get_name();
- connecting_index=j;
- connecting_out=false;
- connecting_type=gn->get_connection_input_type(j);
- connecting_color=gn->get_connection_input_color(j);
- connecting_target=false;
- connecting_to=pos;
- just_disconected=true;
+ connecting = true;
+ connecting_from = gn->get_name();
+ connecting_index = j;
+ connecting_out = false;
+ connecting_type = gn->get_connection_input_type(j);
+ connecting_color = gn->get_connection_input_color(j);
+ connecting_target = false;
+ connecting_to = pos;
+ just_disconected = true;
return;
}
-
-
}
}
}
- if (p_ev.type==InputEvent::MOUSE_MOTION && connecting) {
+ if (p_ev.type == InputEvent::MOUSE_MOTION && connecting) {
- connecting_to=Vector2(p_ev.mouse_motion.x,p_ev.mouse_motion.y);
- connecting_target=false;
- top_layer->update();
+ connecting_to = Vector2(p_ev.mouse_motion.x, p_ev.mouse_motion.y);
+ connecting_target = false;
+ top_layer->update();
- Ref<Texture> port =get_icon("port","GraphNode");
- Vector2 mpos(p_ev.mouse_button.x,p_ev.mouse_button.y);
- float grab_r=port->get_width()*0.5*grab_r_extend;
- for(int i=get_child_count()-1;i>=0;i--) {
+ Ref<Texture> port = get_icon("port", "GraphNode");
+ Vector2 mpos(p_ev.mouse_button.x, p_ev.mouse_button.y);
+ float grab_r = port->get_width() * 0.5 * grab_r_extend;
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
if (!connecting_out) {
- for(int j=0;j<gn->get_connection_output_count();j++) {
+ for (int j = 0; j < gn->get_connection_output_count(); j++) {
- Vector2 pos = gn->get_connection_output_pos(j)+gn->get_pos();
- int type =gn->get_connection_output_type(j);
- if ((type==connecting_type ||valid_connection_types.has(ConnType(type,connecting_type))) && pos.distance_to(mpos)<grab_r) {
+ Vector2 pos = gn->get_connection_output_pos(j) + gn->get_pos();
+ int type = gn->get_connection_output_type(j);
+ if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && pos.distance_to(mpos) < grab_r) {
- connecting_target=true;
- connecting_to=pos;
- connecting_target_to=gn->get_name();
- connecting_target_index=j;
+ connecting_target = true;
+ connecting_to = pos;
+ connecting_target_to = gn->get_name();
+ connecting_target_index = j;
return;
}
-
-
}
} else {
- for(int j=0;j<gn->get_connection_input_count();j++) {
+ for (int j = 0; j < gn->get_connection_input_count(); j++) {
- Vector2 pos = gn->get_connection_input_pos(j)+gn->get_pos();
- int type =gn->get_connection_input_type(j);
- if ((type==connecting_type ||valid_connection_types.has(ConnType(type,connecting_type))) && pos.distance_to(mpos)<grab_r) {
- connecting_target=true;
- connecting_to=pos;
- connecting_target_to=gn->get_name();
- connecting_target_index=j;
+ Vector2 pos = gn->get_connection_input_pos(j) + gn->get_pos();
+ int type = gn->get_connection_input_type(j);
+ if ((type == connecting_type || valid_connection_types.has(ConnType(type, connecting_type))) && pos.distance_to(mpos) < grab_r) {
+ connecting_target = true;
+ connecting_to = pos;
+ connecting_target_to = gn->get_name();
+ connecting_target_index = j;
return;
}
}
@@ -562,100 +525,88 @@ void GraphEdit::_top_layer_input(const InputEvent& p_ev) {
}
}
- if (p_ev.type==InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index==BUTTON_LEFT && !p_ev.mouse_button.pressed) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON && p_ev.mouse_button.button_index == BUTTON_LEFT && !p_ev.mouse_button.pressed) {
if (connecting && connecting_target) {
String from = connecting_from;
int from_slot = connecting_index;
- String to =connecting_target_to;
+ String to = connecting_target_to;
int to_slot = connecting_target_index;
if (!connecting_out) {
- SWAP(from,to);
- SWAP(from_slot,to_slot);
+ SWAP(from, to);
+ SWAP(from_slot, to_slot);
}
- emit_signal("connection_request",from,from_slot,to,to_slot);
+ emit_signal("connection_request", from, from_slot, to, to_slot);
} else if (!just_disconected) {
String from = connecting_from;
int from_slot = connecting_index;
- Vector2 ofs = Vector2(p_ev.mouse_button.x,p_ev.mouse_button.y);
- emit_signal("connection_to_empty",from,from_slot,ofs);
+ Vector2 ofs = Vector2(p_ev.mouse_button.x, p_ev.mouse_button.y);
+ emit_signal("connection_to_empty", from, from_slot, ofs);
}
- connecting=false;
+ connecting = false;
top_layer->update();
update();
connections_layer->update();
-
}
-
}
-
-template<class Vector2>
+template <class Vector2>
static _FORCE_INLINE_ Vector2 _bezier_interp(real_t t, Vector2 start, Vector2 control_1, Vector2 control_2, Vector2 end) {
- /* Formula from Wikipedia article on Bezier curves. */
+ /* 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;
-}
+ 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;
+}
-void GraphEdit::_bake_segment2d(CanvasItem* p_where,float p_begin, float p_end,const Vector2& p_a,const Vector2& p_out,const Vector2& p_b, const Vector2& p_in,int p_depth,int p_min_depth,int p_max_depth,float p_tol,const Color& p_color,const Color& p_to_color,int &lines) const {
+void GraphEdit::_bake_segment2d(CanvasItem *p_where, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_min_depth, int p_max_depth, float p_tol, const Color &p_color, const Color &p_to_color, int &lines) const {
- float mp = p_begin+(p_end-p_begin)*0.5;
- Vector2 beg = _bezier_interp(p_begin,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector2 mid = _bezier_interp(mp,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector2 end = _bezier_interp(p_end,p_a,p_a+p_out,p_b+p_in,p_b);
+ float mp = p_begin + (p_end - p_begin) * 0.5;
+ Vector2 beg = _bezier_interp(p_begin, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector2 mid = _bezier_interp(mp, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector2 end = _bezier_interp(p_end, p_a, p_a + p_out, p_b + p_in, p_b);
- Vector2 na = (mid-beg).normalized();
- Vector2 nb = (end-mid).normalized();
+ Vector2 na = (mid - beg).normalized();
+ Vector2 nb = (end - mid).normalized();
float dp = Math::rad2deg(Math::acos(na.dot(nb)));
- if (p_depth>=p_min_depth && ( dp<p_tol || p_depth>=p_max_depth)) {
-
-
+ if (p_depth >= p_min_depth && (dp < p_tol || p_depth >= p_max_depth)) {
- p_where->draw_line(beg,end,p_color.linear_interpolate(p_to_color,mp),2,true);
+ p_where->draw_line(beg, end, p_color.linear_interpolate(p_to_color, mp), 2, true);
lines++;
} else {
- _bake_segment2d(p_where,p_begin,mp,p_a,p_out,p_b,p_in,p_depth+1,p_min_depth,p_max_depth,p_tol,p_color,p_to_color,lines);
- _bake_segment2d(p_where,mp,p_end,p_a,p_out,p_b,p_in,p_depth+1,p_min_depth,p_max_depth,p_tol,p_color,p_to_color,lines);
+ _bake_segment2d(p_where, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_min_depth, p_max_depth, p_tol, p_color, p_to_color, lines);
+ _bake_segment2d(p_where, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_min_depth, p_max_depth, p_tol, p_color, p_to_color, lines);
}
}
-
-void GraphEdit::_draw_cos_line(CanvasItem* p_where,const Vector2& p_from, const Vector2& p_to,const Color& p_color,const Color& p_to_color) {
-
+void GraphEdit::_draw_cos_line(CanvasItem *p_where, const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, const Color &p_to_color) {
#if 1
//cubic bezier code
- float diff = p_to.x-p_from.x;
+ float diff = p_to.x - p_from.x;
float cp_offset;
int cp_len = get_constant("bezier_len_pos");
int cp_neg_len = get_constant("bezier_len_neg");
- if (diff>0) {
- cp_offset=MAX(cp_len,diff*0.5);
+ if (diff > 0) {
+ cp_offset = MAX(cp_len, diff * 0.5);
} else {
- cp_offset=MAX(MIN(cp_len-diff,cp_neg_len),-diff*0.5);
+ cp_offset = MAX(MIN(cp_len - diff, cp_neg_len), -diff * 0.5);
}
- Vector2 c1 = Vector2(cp_offset*zoom,0);
- Vector2 c2 = Vector2(-cp_offset*zoom,0);
-
- int lines=0;
- _bake_segment2d(p_where,0,1,p_from,c1,p_to,c2,0,3,9,8,p_color,p_to_color,lines);
+ Vector2 c1 = Vector2(cp_offset * zoom, 0);
+ Vector2 c2 = Vector2(-cp_offset * zoom, 0);
+ int lines = 0;
+ _bake_segment2d(p_where, 0, 1, p_from, c1, p_to, c2, 0, 3, 9, 8, p_color, p_to_color, lines);
#else
@@ -663,43 +614,40 @@ void GraphEdit::_draw_cos_line(CanvasItem* p_where,const Vector2& p_from, const
//old cosine code
Rect2 r;
- r.pos=p_from;
+ r.pos = p_from;
r.expand_to(p_to);
- Vector2 sign=Vector2((p_from.x < p_to.x) ? 1 : -1,(p_from.y < p_to.y) ? 1 : -1);
+ Vector2 sign = Vector2((p_from.x < p_to.x) ? 1 : -1, (p_from.y < p_to.y) ? 1 : -1);
bool flip = sign.x * sign.y < 0;
Vector2 prev;
- for(int i=0;i<=steps;i++) {
-
+ for (int i = 0; i <= steps; i++) {
- float d = i/float(steps);
- float c=-Math::cos(d*Math_PI) * 0.5+0.5;
+ float d = i / float(steps);
+ float c = -Math::cos(d * Math_PI) * 0.5 + 0.5;
if (flip)
- c=1.0-c;
- Vector2 p = r.pos+Vector2(d*r.size.width,c*r.size.height);
+ c = 1.0 - c;
+ Vector2 p = r.pos + Vector2(d * r.size.width, c * r.size.height);
- if (i>0) {
+ if (i > 0) {
- p_where->draw_line(prev,p,p_color.linear_interpolate(p_to_color,d),2);
+ p_where->draw_line(prev, p, p_color.linear_interpolate(p_to_color, d), 2);
}
- prev=p;
+ prev = p;
}
#endif
}
-
void GraphEdit::_connections_layer_draw() {
-
{
//draw connections
- List<List<Connection>::Element* > to_erase;
- for(List<Connection>::Element *E=connections.front();E;E=E->next()) {
+ List<List<Connection>::Element *> to_erase;
+ for (List<Connection>::Element *E = connections.front(); E; E = E->next()) {
NodePath fromnp(E->get().from);
- Node * from = get_node(fromnp);
+ Node *from = get_node(fromnp);
if (!from) {
to_erase.push_back(E);
continue;
@@ -713,7 +661,7 @@ void GraphEdit::_connections_layer_draw() {
}
NodePath tonp(E->get().to);
- Node * to = get_node(tonp);
+ Node *to = get_node(tonp);
if (!to) {
to_erase.push_back(E);
continue;
@@ -726,15 +674,14 @@ void GraphEdit::_connections_layer_draw() {
continue;
}
- Vector2 frompos=gfrom->get_connection_output_pos(E->get().from_port)+gfrom->get_offset()*zoom;
+ Vector2 frompos = gfrom->get_connection_output_pos(E->get().from_port) + gfrom->get_offset() * zoom;
Color color = gfrom->get_connection_output_color(E->get().from_port);
- Vector2 topos=gto->get_connection_input_pos(E->get().to_port)+gto->get_offset()*zoom;
+ Vector2 topos = gto->get_connection_input_pos(E->get().to_port) + gto->get_offset() * zoom;
Color tocolor = gto->get_connection_input_color(E->get().to_port);
- _draw_cos_line(connections_layer,frompos,topos,color,tocolor);
-
+ _draw_cos_line(connections_layer, frompos, topos, color, tocolor);
}
- while(to_erase.size()) {
+ while (to_erase.size()) {
connections.erase(to_erase.front()->get());
to_erase.pop_front();
}
@@ -753,66 +700,65 @@ void GraphEdit::_top_layer_draw() {
ERR_FAIL_COND(!from);
Vector2 pos;
if (connecting_out)
- pos=from->get_connection_output_pos(connecting_index);
+ pos = from->get_connection_output_pos(connecting_index);
else
- pos=from->get_connection_input_pos(connecting_index);
- pos+=from->get_pos();
+ pos = from->get_connection_input_pos(connecting_index);
+ pos += from->get_pos();
Vector2 topos;
- topos=connecting_to;
+ topos = connecting_to;
- Color col=connecting_color;
+ Color col = connecting_color;
if (connecting_target) {
- col.r+=0.4;
- col.g+=0.4;
- col.b+=0.4;
+ col.r += 0.4;
+ col.g += 0.4;
+ col.b += 0.4;
}
if (!connecting_out) {
- SWAP(pos,topos);
+ SWAP(pos, topos);
}
- _draw_cos_line(top_layer,pos,topos,col,col);
+ _draw_cos_line(top_layer, pos, topos, col, col);
}
-
if (box_selecting)
- top_layer->draw_rect(box_selecting_rect,Color(0.7,0.7,1.0,0.3));
+ top_layer->draw_rect(box_selecting_rect, Color(0.7, 0.7, 1.0, 0.3));
}
-void GraphEdit::set_selected(Node* p_child) {
+void GraphEdit::set_selected(Node *p_child) {
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
- gn->set_selected(gn==p_child);
+ gn->set_selected(gn == p_child);
}
}
-void GraphEdit::_gui_input(const InputEvent& p_ev) {
+void GraphEdit::_gui_input(const InputEvent &p_ev) {
- if (p_ev.type==InputEvent::MOUSE_MOTION && (p_ev.mouse_motion.button_mask&BUTTON_MASK_MIDDLE || (p_ev.mouse_motion.button_mask&BUTTON_MASK_LEFT && Input::get_singleton()->is_key_pressed(KEY_SPACE)))) {
- h_scroll->set_value( h_scroll->get_value() - p_ev.mouse_motion.relative_x );
- v_scroll->set_value( v_scroll->get_value() - p_ev.mouse_motion.relative_y );
+ if (p_ev.type == InputEvent::MOUSE_MOTION && (p_ev.mouse_motion.button_mask & BUTTON_MASK_MIDDLE || (p_ev.mouse_motion.button_mask & BUTTON_MASK_LEFT && Input::get_singleton()->is_key_pressed(KEY_SPACE)))) {
+ h_scroll->set_value(h_scroll->get_value() - p_ev.mouse_motion.relative_x);
+ v_scroll->set_value(v_scroll->get_value() - p_ev.mouse_motion.relative_y);
}
- if (p_ev.type==InputEvent::MOUSE_MOTION && dragging) {
+ if (p_ev.type == InputEvent::MOUSE_MOTION && dragging) {
- just_selected=true;
+ just_selected = true;
// TODO: Remove local mouse pos hack if/when InputEventMouseMotion is fixed to support floats
//drag_accum+=Vector2(p_ev.mouse_motion.relative_x,p_ev.mouse_motion.relative_y);
drag_accum = get_local_mouse_pos() - drag_origin;
- for(int i=get_child_count()-1;i>=0;i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ for (int i = get_child_count() - 1; i >= 0; i--) {
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (gn && gn->is_selected()) {
- Vector2 pos = (gn->get_drag_from()*zoom+drag_accum)/zoom;
+ Vector2 pos = (gn->get_drag_from() * zoom + drag_accum) / zoom;
if (is_using_snap()) {
int snap = get_snap();
- pos = pos.snapped(Vector2(snap,snap));
+ pos = pos.snapped(Vector2(snap, snap));
}
gn->set_offset(pos);
@@ -820,48 +766,47 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
}
}
- if (p_ev.type==InputEvent::MOUSE_MOTION && box_selecting) {
+ if (p_ev.type == InputEvent::MOUSE_MOTION && box_selecting) {
box_selecting_to = get_local_mouse_pos();
- box_selecting_rect = Rect2(MIN(box_selecting_from.x,box_selecting_to.x),
- MIN(box_selecting_from.y,box_selecting_to.y),
- ABS(box_selecting_from.x-box_selecting_to.x),
- ABS(box_selecting_from.y-box_selecting_to.y));
+ box_selecting_rect = Rect2(MIN(box_selecting_from.x, box_selecting_to.x),
+ MIN(box_selecting_from.y, box_selecting_to.y),
+ ABS(box_selecting_from.x - box_selecting_to.x),
+ ABS(box_selecting_from.y - box_selecting_to.y));
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
Rect2 r = gn->get_rect();
- r.size*=zoom;
+ r.size *= zoom;
bool in_box = r.intersects(box_selecting_rect);
if (in_box)
gn->set_selected(box_selection_mode_aditive);
else
- gn->set_selected(previus_selected.find(gn)!=NULL);
+ gn->set_selected(previus_selected.find(gn) != NULL);
}
top_layer->update();
}
- if (p_ev.type==InputEvent::MOUSE_BUTTON) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON) {
- const InputEventMouseButton &b=p_ev.mouse_button;
+ const InputEventMouseButton &b = p_ev.mouse_button;
- if (b.button_index==BUTTON_RIGHT && b.pressed)
- {
+ if (b.button_index == BUTTON_RIGHT && b.pressed) {
if (box_selecting) {
box_selecting = false;
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
- gn->set_selected(previus_selected.find(gn)!=NULL);
+ gn->set_selected(previus_selected.find(gn) != NULL);
}
top_layer->update();
} else {
@@ -874,27 +819,27 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
}
}
- if (b.button_index==BUTTON_LEFT && !b.pressed && dragging) {
- if (!just_selected && drag_accum==Vector2() && Input::get_singleton()->is_key_pressed(KEY_CONTROL)) {
+ if (b.button_index == BUTTON_LEFT && !b.pressed && dragging) {
+ if (!just_selected && drag_accum == Vector2() && Input::get_singleton()->is_key_pressed(KEY_CONTROL)) {
//deselect current node
- for(int i=get_child_count()-1;i>=0;i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ for (int i = get_child_count() - 1; i >= 0; i--) {
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (gn) {
Rect2 r = gn->get_rect();
- r.size*=zoom;
+ r.size *= zoom;
if (r.has_point(get_local_mouse_pos()))
gn->set_selected(false);
}
}
}
- if (drag_accum!=Vector2()) {
+ if (drag_accum != Vector2()) {
emit_signal("_begin_node_move");
- for(int i=get_child_count()-1;i>=0;i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ for (int i = get_child_count() - 1; i >= 0; i--) {
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (gn && gn->is_selected())
gn->set_drag(false);
}
@@ -909,13 +854,13 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
connections_layer->update();
}
- if (b.button_index==BUTTON_LEFT && b.pressed) {
+ if (b.button_index == BUTTON_LEFT && b.pressed) {
GraphNode *gn = NULL;
GraphNode *gn_selected = NULL;
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- gn_selected=get_child(i)->cast_to<GraphNode>();
+ gn_selected = get_child(i)->cast_to<GraphNode>();
if (gn_selected) {
@@ -923,23 +868,23 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
continue;
Rect2 r = gn_selected->get_rect();
- r.size*=zoom;
+ r.size *= zoom;
if (r.has_point(get_local_mouse_pos()))
gn = gn_selected;
- break;
+ break;
}
}
if (gn) {
- if (_filter_input(Vector2(b.x,b.y)))
+ if (_filter_input(Vector2(b.x, b.y)))
return;
dragging = true;
drag_accum = Vector2();
drag_origin = get_local_mouse_pos();
just_selected = !gn->is_selected();
- if(!gn->is_selected() && !Input::get_singleton()->is_key_pressed(KEY_CONTROL)) {
+ if (!gn->is_selected() && !Input::get_singleton()->is_key_pressed(KEY_CONTROL)) {
for (int i = 0; i < get_child_count(); i++) {
GraphNode *o_gn = get_child(i)->cast_to<GraphNode>();
if (o_gn)
@@ -957,7 +902,7 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
}
} else {
- if (_filter_input(Vector2(b.x,b.y)))
+ if (_filter_input(Vector2(b.x, b.y)))
return;
if (Input::get_singleton()->is_key_pressed(KEY_SPACE))
return;
@@ -967,9 +912,9 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
if (b.mod.control) {
box_selection_mode_aditive = true;
previus_selected.clear();
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn || !gn->is_selected())
continue;
@@ -978,9 +923,9 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
} else if (b.mod.shift) {
box_selection_mode_aditive = false;
previus_selected.clear();
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn || !gn->is_selected())
continue;
@@ -989,9 +934,9 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
} else {
box_selection_mode_aditive = true;
previus_selected.clear();
- for(int i=get_child_count()-1;i>=0;i--) {
+ for (int i = get_child_count() - 1; i >= 0; i--) {
- GraphNode *gn=get_child(i)->cast_to<GraphNode>();
+ GraphNode *gn = get_child(i)->cast_to<GraphNode>();
if (!gn)
continue;
@@ -1001,33 +946,32 @@ void GraphEdit::_gui_input(const InputEvent& p_ev) {
}
}
- if (b.button_index==BUTTON_LEFT && !b.pressed && box_selecting) {
+ if (b.button_index == BUTTON_LEFT && !b.pressed && box_selecting) {
box_selecting = false;
previus_selected.clear();
top_layer->update();
}
- if (b.button_index==BUTTON_WHEEL_UP && b.pressed) {
+ if (b.button_index == BUTTON_WHEEL_UP && b.pressed) {
//too difficult to get right
//set_zoom(zoom*ZOOM_SCALE);
}
- if (b.button_index==BUTTON_WHEEL_DOWN && b.pressed) {
+ if (b.button_index == BUTTON_WHEEL_DOWN && b.pressed) {
//too difficult to get right
//set_zoom(zoom/ZOOM_SCALE);
}
}
- if (p_ev.type==InputEvent::KEY && p_ev.key.scancode==KEY_D && p_ev.key.pressed && p_ev.key.mod.command) {
+ if (p_ev.type == InputEvent::KEY && p_ev.key.scancode == KEY_D && p_ev.key.pressed && p_ev.key.mod.command) {
emit_signal("duplicate_nodes_request");
accept_event();
}
- if (p_ev.type==InputEvent::KEY && p_ev.key.scancode==KEY_DELETE && p_ev.key.pressed) {
+ if (p_ev.type == InputEvent::KEY && p_ev.key.scancode == KEY_DELETE && p_ev.key.pressed) {
emit_signal("delete_nodes_request");
accept_event();
}
-
}
void GraphEdit::clear_connections() {
@@ -1039,14 +983,14 @@ void GraphEdit::clear_connections() {
void GraphEdit::set_zoom(float p_zoom) {
- p_zoom=CLAMP(p_zoom,MIN_ZOOM,MAX_ZOOM);
+ p_zoom = CLAMP(p_zoom, MIN_ZOOM, MAX_ZOOM);
if (zoom == p_zoom)
return;
- zoom_minus->set_disabled(zoom==MIN_ZOOM);
- zoom_plus->set_disabled(zoom==MAX_ZOOM);
+ zoom_minus->set_disabled(zoom == MIN_ZOOM);
+ zoom_plus->set_disabled(zoom == MAX_ZOOM);
- Vector2 sbofs = (Vector2( h_scroll->get_value(), v_scroll->get_value() ) + get_size()/2)/zoom;
+ Vector2 sbofs = (Vector2(h_scroll->get_value(), v_scroll->get_value()) + get_size() / 2) / zoom;
zoom = p_zoom;
top_layer->update();
@@ -1056,12 +1000,11 @@ void GraphEdit::set_zoom(float p_zoom) {
if (is_visible_in_tree()) {
- Vector2 ofs = sbofs*zoom - get_size()/2;
- h_scroll->set_value( ofs.x );
- v_scroll->set_value( ofs.y );
+ Vector2 ofs = sbofs * zoom - get_size() / 2;
+ h_scroll->set_value(ofs.x);
+ v_scroll->set_value(ofs.y);
}
-
update();
}
@@ -1071,10 +1014,10 @@ float GraphEdit::get_zoom() const {
void GraphEdit::set_right_disconnects(bool p_enable) {
- right_disconnects=p_enable;
+ right_disconnects = p_enable;
}
-bool GraphEdit::is_right_disconnects_enabled() const{
+bool GraphEdit::is_right_disconnects_enabled() const {
return right_disconnects;
}
@@ -1084,22 +1027,19 @@ void GraphEdit::add_valid_right_disconnect_type(int p_type) {
valid_right_disconnect_types.insert(p_type);
}
-void GraphEdit::remove_valid_right_disconnect_type(int p_type){
+void GraphEdit::remove_valid_right_disconnect_type(int p_type) {
valid_right_disconnect_types.erase(p_type);
-
}
-void GraphEdit::add_valid_left_disconnect_type(int p_type){
+void GraphEdit::add_valid_left_disconnect_type(int p_type) {
valid_left_disconnect_types.insert(p_type);
-
}
-void GraphEdit::remove_valid_left_disconnect_type(int p_type){
+void GraphEdit::remove_valid_left_disconnect_type(int p_type) {
valid_left_disconnect_types.erase(p_type);
-
}
Array GraphEdit::_get_connection_list() const {
@@ -1107,85 +1047,77 @@ Array GraphEdit::_get_connection_list() const {
List<Connection> conns;
get_connection_list(&conns);
Array arr;
- for(List<Connection>::Element *E=conns.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = conns.front(); E; E = E->next()) {
Dictionary d;
- d["from"]=E->get().from;
- d["from_port"]=E->get().from_port;
- d["to"]=E->get().to;
- d["to_port"]=E->get().to_port;
+ d["from"] = E->get().from;
+ d["from_port"] = E->get().from_port;
+ d["to"] = E->get().to;
+ d["to_port"] = E->get().to_port;
arr.push_back(d);
}
return arr;
}
-
-
void GraphEdit::_zoom_minus() {
-
- set_zoom(zoom/ZOOM_SCALE);
+ set_zoom(zoom / ZOOM_SCALE);
}
void GraphEdit::_zoom_reset() {
-
set_zoom(1);
}
void GraphEdit::_zoom_plus() {
- set_zoom(zoom*ZOOM_SCALE);
+ set_zoom(zoom * ZOOM_SCALE);
}
-void GraphEdit::add_valid_connection_type(int p_type,int p_with_type) {
+void GraphEdit::add_valid_connection_type(int p_type, int p_with_type) {
ConnType ct;
- ct.type_a=p_type;
- ct.type_b=p_with_type;
+ ct.type_a = p_type;
+ ct.type_b = p_with_type;
valid_connection_types.insert(ct);
}
-void GraphEdit::remove_valid_connection_type(int p_type,int p_with_type) {
+void GraphEdit::remove_valid_connection_type(int p_type, int p_with_type) {
ConnType ct;
- ct.type_a=p_type;
- ct.type_b=p_with_type;
+ ct.type_a = p_type;
+ ct.type_b = p_with_type;
valid_connection_types.erase(ct);
-
}
-bool GraphEdit::is_valid_connection_type(int p_type,int p_with_type) const {
+bool GraphEdit::is_valid_connection_type(int p_type, int p_with_type) const {
ConnType ct;
- ct.type_a=p_type;
- ct.type_b=p_with_type;
+ ct.type_a = p_type;
+ ct.type_b = p_with_type;
return valid_connection_types.has(ct);
-
}
void GraphEdit::set_use_snap(bool p_enable) {
snap_button->set_pressed(p_enable);
update();
-
}
-bool GraphEdit::is_using_snap() const{
+bool GraphEdit::is_using_snap() const {
return snap_button->is_pressed();
-
}
-int GraphEdit::get_snap() const{
+int GraphEdit::get_snap() const {
return snap_amount->get_value();
}
void GraphEdit::set_snap(int p_snap) {
- ERR_FAIL_COND(p_snap<5);
+ ERR_FAIL_COND(p_snap < 5);
snap_amount->set_value(p_snap);
update();
}
@@ -1198,78 +1130,73 @@ void GraphEdit::_snap_value_changed(double) {
update();
}
-
void GraphEdit::_bind_methods() {
- ClassDB::bind_method(D_METHOD("connect_node:Error","from","from_port","to","to_port"),&GraphEdit::connect_node);
- ClassDB::bind_method(D_METHOD("is_node_connected","from","from_port","to","to_port"),&GraphEdit::is_node_connected);
- ClassDB::bind_method(D_METHOD("disconnect_node","from","from_port","to","to_port"),&GraphEdit::disconnect_node);
- ClassDB::bind_method(D_METHOD("get_connection_list"),&GraphEdit::_get_connection_list);
- ClassDB::bind_method(D_METHOD("get_scroll_ofs"),&GraphEdit::get_scroll_ofs);
- ClassDB::bind_method(D_METHOD("set_scroll_ofs","ofs"),&GraphEdit::set_scroll_ofs);
-
- ClassDB::bind_method(D_METHOD("set_zoom","p_zoom"),&GraphEdit::set_zoom);
- ClassDB::bind_method(D_METHOD("get_zoom"),&GraphEdit::get_zoom);
+ ClassDB::bind_method(D_METHOD("connect_node:Error", "from", "from_port", "to", "to_port"), &GraphEdit::connect_node);
+ ClassDB::bind_method(D_METHOD("is_node_connected", "from", "from_port", "to", "to_port"), &GraphEdit::is_node_connected);
+ ClassDB::bind_method(D_METHOD("disconnect_node", "from", "from_port", "to", "to_port"), &GraphEdit::disconnect_node);
+ ClassDB::bind_method(D_METHOD("get_connection_list"), &GraphEdit::_get_connection_list);
+ ClassDB::bind_method(D_METHOD("get_scroll_ofs"), &GraphEdit::get_scroll_ofs);
+ ClassDB::bind_method(D_METHOD("set_scroll_ofs", "ofs"), &GraphEdit::set_scroll_ofs);
- ClassDB::bind_method(D_METHOD("set_snap","pixels"),&GraphEdit::set_snap);
- ClassDB::bind_method(D_METHOD("get_snap"),&GraphEdit::get_snap);
+ ClassDB::bind_method(D_METHOD("set_zoom", "p_zoom"), &GraphEdit::set_zoom);
+ ClassDB::bind_method(D_METHOD("get_zoom"), &GraphEdit::get_zoom);
- ClassDB::bind_method(D_METHOD("set_use_snap","enable"),&GraphEdit::set_use_snap);
- ClassDB::bind_method(D_METHOD("is_using_snap"),&GraphEdit::is_using_snap);
+ ClassDB::bind_method(D_METHOD("set_snap", "pixels"), &GraphEdit::set_snap);
+ ClassDB::bind_method(D_METHOD("get_snap"), &GraphEdit::get_snap);
- ClassDB::bind_method(D_METHOD("set_right_disconnects","enable"),&GraphEdit::set_right_disconnects);
- ClassDB::bind_method(D_METHOD("is_right_disconnects_enabled"),&GraphEdit::is_right_disconnects_enabled);
+ ClassDB::bind_method(D_METHOD("set_use_snap", "enable"), &GraphEdit::set_use_snap);
+ ClassDB::bind_method(D_METHOD("is_using_snap"), &GraphEdit::is_using_snap);
- ClassDB::bind_method(D_METHOD("_graph_node_moved"),&GraphEdit::_graph_node_moved);
- ClassDB::bind_method(D_METHOD("_graph_node_raised"),&GraphEdit::_graph_node_raised);
+ ClassDB::bind_method(D_METHOD("set_right_disconnects", "enable"), &GraphEdit::set_right_disconnects);
+ ClassDB::bind_method(D_METHOD("is_right_disconnects_enabled"), &GraphEdit::is_right_disconnects_enabled);
- ClassDB::bind_method(D_METHOD("_top_layer_input"),&GraphEdit::_top_layer_input);
- ClassDB::bind_method(D_METHOD("_top_layer_draw"),&GraphEdit::_top_layer_draw);
- ClassDB::bind_method(D_METHOD("_scroll_moved"),&GraphEdit::_scroll_moved);
- ClassDB::bind_method(D_METHOD("_zoom_minus"),&GraphEdit::_zoom_minus);
- ClassDB::bind_method(D_METHOD("_zoom_reset"),&GraphEdit::_zoom_reset);
- ClassDB::bind_method(D_METHOD("_zoom_plus"),&GraphEdit::_zoom_plus);
- ClassDB::bind_method(D_METHOD("_snap_toggled"),&GraphEdit::_snap_toggled);
- ClassDB::bind_method(D_METHOD("_snap_value_changed"),&GraphEdit::_snap_value_changed);
+ ClassDB::bind_method(D_METHOD("_graph_node_moved"), &GraphEdit::_graph_node_moved);
+ ClassDB::bind_method(D_METHOD("_graph_node_raised"), &GraphEdit::_graph_node_raised);
- ClassDB::bind_method(D_METHOD("_gui_input"),&GraphEdit::_gui_input);
- ClassDB::bind_method(D_METHOD("_update_scroll_offset"),&GraphEdit::_update_scroll_offset);
- ClassDB::bind_method(D_METHOD("_connections_layer_draw"),&GraphEdit::_connections_layer_draw);
+ ClassDB::bind_method(D_METHOD("_top_layer_input"), &GraphEdit::_top_layer_input);
+ ClassDB::bind_method(D_METHOD("_top_layer_draw"), &GraphEdit::_top_layer_draw);
+ ClassDB::bind_method(D_METHOD("_scroll_moved"), &GraphEdit::_scroll_moved);
+ ClassDB::bind_method(D_METHOD("_zoom_minus"), &GraphEdit::_zoom_minus);
+ ClassDB::bind_method(D_METHOD("_zoom_reset"), &GraphEdit::_zoom_reset);
+ ClassDB::bind_method(D_METHOD("_zoom_plus"), &GraphEdit::_zoom_plus);
+ ClassDB::bind_method(D_METHOD("_snap_toggled"), &GraphEdit::_snap_toggled);
+ ClassDB::bind_method(D_METHOD("_snap_value_changed"), &GraphEdit::_snap_value_changed);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &GraphEdit::_gui_input);
+ ClassDB::bind_method(D_METHOD("_update_scroll_offset"), &GraphEdit::_update_scroll_offset);
+ ClassDB::bind_method(D_METHOD("_connections_layer_draw"), &GraphEdit::_connections_layer_draw);
+ ClassDB::bind_method(D_METHOD("set_selected", "node"), &GraphEdit::set_selected);
- ClassDB::bind_method(D_METHOD("set_selected","node"),&GraphEdit::set_selected);
-
- ADD_SIGNAL(MethodInfo("connection_request",PropertyInfo(Variant::STRING,"from"),PropertyInfo(Variant::INT,"from_slot"),PropertyInfo(Variant::STRING,"to"),PropertyInfo(Variant::INT,"to_slot")));
- ADD_SIGNAL(MethodInfo("disconnection_request",PropertyInfo(Variant::STRING,"from"),PropertyInfo(Variant::INT,"from_slot"),PropertyInfo(Variant::STRING,"to"),PropertyInfo(Variant::INT,"to_slot")));
- ADD_SIGNAL(MethodInfo("popup_request", PropertyInfo(Variant::VECTOR2,"p_position")));
+ ADD_SIGNAL(MethodInfo("connection_request", PropertyInfo(Variant::STRING, "from"), PropertyInfo(Variant::INT, "from_slot"), PropertyInfo(Variant::STRING, "to"), PropertyInfo(Variant::INT, "to_slot")));
+ ADD_SIGNAL(MethodInfo("disconnection_request", PropertyInfo(Variant::STRING, "from"), PropertyInfo(Variant::INT, "from_slot"), PropertyInfo(Variant::STRING, "to"), PropertyInfo(Variant::INT, "to_slot")));
+ ADD_SIGNAL(MethodInfo("popup_request", PropertyInfo(Variant::VECTOR2, "p_position")));
ADD_SIGNAL(MethodInfo("duplicate_nodes_request"));
- ADD_SIGNAL(MethodInfo("node_selected",PropertyInfo(Variant::OBJECT,"node")));
- ADD_SIGNAL(MethodInfo("connection_to_empty",PropertyInfo(Variant::STRING,"from"),PropertyInfo(Variant::INT,"from_slot"),PropertyInfo(Variant::VECTOR2,"release_pos")));
+ ADD_SIGNAL(MethodInfo("node_selected", PropertyInfo(Variant::OBJECT, "node")));
+ ADD_SIGNAL(MethodInfo("connection_to_empty", PropertyInfo(Variant::STRING, "from"), PropertyInfo(Variant::INT, "from_slot"), PropertyInfo(Variant::VECTOR2, "release_pos")));
ADD_SIGNAL(MethodInfo("delete_nodes_request"));
ADD_SIGNAL(MethodInfo("_begin_node_move"));
ADD_SIGNAL(MethodInfo("_end_node_move"));
- ADD_SIGNAL(MethodInfo("scroll_offset_changed",PropertyInfo(Variant::VECTOR2,"ofs")));
+ ADD_SIGNAL(MethodInfo("scroll_offset_changed", PropertyInfo(Variant::VECTOR2, "ofs")));
}
-
-
GraphEdit::GraphEdit() {
set_focus_mode(FOCUS_ALL);
- awaiting_scroll_offset_update=false;
- top_layer=NULL;
- top_layer=memnew(GraphEditFilter(this));
+ awaiting_scroll_offset_update = false;
+ top_layer = NULL;
+ top_layer = memnew(GraphEditFilter(this));
add_child(top_layer);
top_layer->set_mouse_filter(MOUSE_FILTER_PASS);
top_layer->set_area_as_parent_rect();
- top_layer->connect("draw",this,"_top_layer_draw");
+ top_layer->connect("draw", this, "_top_layer_draw");
top_layer->set_mouse_filter(MOUSE_FILTER_PASS);
- top_layer->connect("gui_input",this,"_top_layer_input");
+ top_layer->connect("gui_input", this, "_top_layer_input");
- connections_layer = memnew( Control );
+ connections_layer = memnew(Control);
add_child(connections_layer);
- connections_layer->connect("draw",this,"_connections_layer_draw");
+ connections_layer->connect("draw", this, "_connections_layer_draw");
connections_layer->set_name("CLAYER");
connections_layer->set_disable_visibility_clip(true); // so it can draw freely and be offseted
@@ -1280,9 +1207,9 @@ GraphEdit::GraphEdit() {
v_scroll = memnew(VScrollBar);
v_scroll->set_name("_v_scroll");
top_layer->add_child(v_scroll);
- updating=false;
- connecting=false;
- right_disconnects=false;
+ updating = false;
+ connecting = false;
+ right_disconnects = false;
box_selecting = false;
dragging = false;
@@ -1294,49 +1221,46 @@ GraphEdit::GraphEdit() {
v_scroll->set_min(-10000);
v_scroll->set_max(10000);
- h_scroll->connect("value_changed", this,"_scroll_moved");
- v_scroll->connect("value_changed", this,"_scroll_moved");
+ h_scroll->connect("value_changed", this, "_scroll_moved");
+ v_scroll->connect("value_changed", this, "_scroll_moved");
zoom = 1;
- HBoxContainer *zoom_hb = memnew( HBoxContainer );
+ HBoxContainer *zoom_hb = memnew(HBoxContainer);
top_layer->add_child(zoom_hb);
- zoom_hb->set_pos(Vector2(10,10));
-
+ zoom_hb->set_pos(Vector2(10, 10));
- zoom_minus = memnew( ToolButton );
+ zoom_minus = memnew(ToolButton);
zoom_hb->add_child(zoom_minus);
- zoom_minus->connect("pressed",this,"_zoom_minus");
+ zoom_minus->connect("pressed", this, "_zoom_minus");
zoom_minus->set_focus_mode(FOCUS_NONE);
- zoom_reset = memnew( ToolButton );
+ zoom_reset = memnew(ToolButton);
zoom_hb->add_child(zoom_reset);
- zoom_reset->connect("pressed",this,"_zoom_reset");
+ zoom_reset->connect("pressed", this, "_zoom_reset");
zoom_reset->set_focus_mode(FOCUS_NONE);
- zoom_plus = memnew( ToolButton );
+ zoom_plus = memnew(ToolButton);
zoom_hb->add_child(zoom_plus);
- zoom_plus->connect("pressed",this,"_zoom_plus");
+ zoom_plus->connect("pressed", this, "_zoom_plus");
zoom_plus->set_focus_mode(FOCUS_NONE);
- snap_button = memnew( ToolButton );
+ snap_button = memnew(ToolButton);
snap_button->set_toggle_mode(true);
- snap_button->connect("pressed",this,"_snap_toggled");
+ snap_button->connect("pressed", this, "_snap_toggled");
snap_button->set_pressed(true);
snap_button->set_focus_mode(FOCUS_NONE);
zoom_hb->add_child(snap_button);
- snap_amount = memnew( SpinBox );
+ snap_amount = memnew(SpinBox);
snap_amount->set_min(5);
snap_amount->set_max(100);
snap_amount->set_step(1);
snap_amount->set_value(20);
- snap_amount->connect("value_changed",this,"_snap_value_changed");
+ snap_amount->connect("value_changed", this, "_snap_value_changed");
zoom_hb->add_child(snap_amount);
- setting_scroll_ofs=false;
- just_disconected=false;
+ setting_scroll_ofs = false;
+ just_disconected = false;
set_clip_contents(true);
-
-
}
diff --git a/scene/gui/graph_edit.h b/scene/gui/graph_edit.h
index 3e9944332f..5166f82310 100644
--- a/scene/gui/graph_edit.h
+++ b/scene/gui/graph_edit.h
@@ -32,41 +32,37 @@
#include "scene/gui/graph_node.h"
#include "scene/gui/scroll_bar.h"
#include "scene/gui/slider.h"
-#include "scene/gui/tool_button.h"
#include "scene/gui/spin_box.h"
#include "scene/gui/texture_rect.h"
+#include "scene/gui/tool_button.h"
class GraphEdit;
class GraphEditFilter : public Control {
- GDCLASS(GraphEditFilter,Control);
+ GDCLASS(GraphEditFilter, Control);
friend class GraphEdit;
GraphEdit *ge;
- virtual bool has_point(const Point2& p_point) const;
+ virtual bool has_point(const Point2 &p_point) const;
public:
-
-
GraphEditFilter(GraphEdit *p_edit);
};
class GraphEdit : public Control {
- GDCLASS(GraphEdit,Control);
-public:
+ GDCLASS(GraphEdit, Control);
+public:
struct Connection {
StringName from;
StringName to;
int from_port;
int to_port;
-
};
-private:
-
+private:
ToolButton *zoom_minus;
ToolButton *zoom_reset;
ToolButton *zoom_plus;
@@ -78,9 +74,8 @@ private:
void _zoom_reset();
void _zoom_plus();
- HScrollBar* h_scroll;
- VScrollBar* v_scroll;
-
+ HScrollBar *h_scroll;
+ VScrollBar *v_scroll;
bool connecting;
String connecting_from;
@@ -106,7 +101,7 @@ private:
Point2 box_selecting_from;
Point2 box_selecting_to;
Rect2 box_selecting_rect;
- List<GraphNode*> previus_selected;
+ List<GraphNode *> previus_selected;
bool setting_scroll_ofs;
bool right_disconnects;
@@ -114,20 +109,20 @@ private:
bool awaiting_scroll_offset_update;
List<Connection> connections;
- void _bake_segment2d(CanvasItem* p_where,float p_begin, float p_end, const Vector2& p_a, const Vector2& p_out, const Vector2& p_b, const Vector2& p_in, int p_depth, int p_min_depth, int p_max_depth, float p_tol, const Color& p_color, const Color& p_to_color, int &lines) const;
+ void _bake_segment2d(CanvasItem *p_where, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_min_depth, int p_max_depth, float p_tol, const Color &p_color, const Color &p_to_color, int &lines) const;
- void _draw_cos_line(CanvasItem* p_where,const Vector2& p_from, const Vector2& p_to, const Color& p_color, const Color &p_to_color);
+ void _draw_cos_line(CanvasItem *p_where, const Vector2 &p_from, const Vector2 &p_to, const Color &p_color, const Color &p_to_color);
- void _graph_node_raised(Node* p_gn);
+ void _graph_node_raised(Node *p_gn);
void _graph_node_moved(Node *p_gn);
void _update_scroll();
void _scroll_moved(double);
- void _gui_input(const InputEvent& p_ev);
+ void _gui_input(const InputEvent &p_ev);
Control *connections_layer;
GraphEditFilter *top_layer;
- void _top_layer_input(const InputEvent& p_ev);
+ void _top_layer_input(const InputEvent &p_ev);
void _top_layer_draw();
void _connections_layer_draw();
void _update_scroll_offset();
@@ -136,8 +131,6 @@ private:
bool lines_on_bg;
-
-
struct ConnType {
union {
@@ -148,13 +141,13 @@ private:
uint64_t key;
};
- bool operator<(const ConnType& p_type) const {
- return key<p_type.key;
+ bool operator<(const ConnType &p_type) const {
+ return key < p_type.key;
}
- ConnType(uint32_t a=0, uint32_t b=0) {
- type_a=a;
- type_b=b;
+ ConnType(uint32_t a = 0, uint32_t b = 0) {
+ type_a = a;
+ type_b = b;
}
};
@@ -163,26 +156,26 @@ private:
Set<int> valid_right_disconnect_types;
friend class GraphEditFilter;
- bool _filter_input(const Point2& p_point);
+ bool _filter_input(const Point2 &p_point);
void _snap_toggled();
void _snap_value_changed(double);
-protected:
+protected:
static void _bind_methods();
virtual void add_child_notify(Node *p_child);
virtual void remove_child_notify(Node *p_child);
void _notification(int p_what);
virtual bool clips_input() const;
-public:
- Error connect_node(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port);
- bool is_node_connected(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port);
- void disconnect_node(const StringName& p_from, int p_from_port,const StringName& p_to,int p_to_port);
+public:
+ Error connect_node(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port);
+ bool is_node_connected(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port);
+ void disconnect_node(const StringName &p_from, int p_from_port, const StringName &p_to, int p_to_port);
void clear_connections();
- void add_valid_connection_type(int p_type,int p_with_type);
- void remove_valid_connection_type(int p_type,int p_with_type);
- bool is_valid_connection_type(int p_type,int p_with_type) const;
+ void add_valid_connection_type(int p_type, int p_with_type);
+ void remove_valid_connection_type(int p_type, int p_with_type);
+ bool is_valid_connection_type(int p_type, int p_with_type) const;
void set_zoom(float p_zoom);
float get_zoom() const;
@@ -199,10 +192,10 @@ public:
void add_valid_left_disconnect_type(int p_type);
void remove_valid_left_disconnect_type(int p_type);
- void set_scroll_ofs(const Vector2& p_ofs);
+ void set_scroll_ofs(const Vector2 &p_ofs);
Vector2 get_scroll_ofs() const;
- void set_selected(Node* p_child);
+ void set_selected(Node *p_child);
void set_use_snap(bool p_enable);
bool is_using_snap() const;
@@ -210,7 +203,6 @@ public:
int get_snap() const;
void set_snap(int p_snap);
-
GraphEdit();
};
diff --git a/scene/gui/graph_node.cpp b/scene/gui/graph_node.cpp
index 58d3f42483..afbb0bbad7 100644
--- a/scene/gui/graph_node.cpp
+++ b/scene/gui/graph_node.cpp
@@ -29,170 +29,153 @@
#include "graph_node.h"
#include "method_bind_ext.inc"
-
-bool GraphNode::_set(const StringName& p_name, const Variant& p_value) {
+bool GraphNode::_set(const StringName &p_name, const Variant &p_value) {
if (!p_name.operator String().begins_with("slot/"))
return false;
- int idx=p_name.operator String().get_slice("/",1).to_int();
- String what = p_name.operator String().get_slice("/",2);
-
+ int idx = p_name.operator String().get_slice("/", 1).to_int();
+ String what = p_name.operator String().get_slice("/", 2);
Slot si;
if (slot_info.has(idx))
- si=slot_info[idx];
-
-
- if (what=="left_enabled")
- si.enable_left=p_value;
- else if (what=="left_type")
- si.type_left=p_value;
- else if (what=="left_color")
- si.color_left=p_value;
- else if (what=="right_enabled")
- si.enable_right=p_value;
- else if (what=="right_type")
- si.type_right=p_value;
- else if (what=="right_color")
- si.color_right=p_value;
+ si = slot_info[idx];
+
+ if (what == "left_enabled")
+ si.enable_left = p_value;
+ else if (what == "left_type")
+ si.type_left = p_value;
+ else if (what == "left_color")
+ si.color_left = p_value;
+ else if (what == "right_enabled")
+ si.enable_right = p_value;
+ else if (what == "right_type")
+ si.type_right = p_value;
+ else if (what == "right_color")
+ si.color_right = p_value;
else
return false;
- set_slot(idx,si.enable_left,si.type_left,si.color_left,si.enable_right,si.type_right,si.color_right);
+ set_slot(idx, si.enable_left, si.type_left, si.color_left, si.enable_right, si.type_right, si.color_right);
update();
return true;
}
-bool GraphNode::_get(const StringName& p_name,Variant &r_ret) const{
-
-
+bool GraphNode::_get(const StringName &p_name, Variant &r_ret) const {
if (!p_name.operator String().begins_with("slot/")) {
return false;
}
- int idx=p_name.operator String().get_slice("/",1).to_int();
- String what = p_name.operator String().get_slice("/",2);
-
-
+ int idx = p_name.operator String().get_slice("/", 1).to_int();
+ String what = p_name.operator String().get_slice("/", 2);
Slot si;
if (slot_info.has(idx))
- si=slot_info[idx];
-
- if (what=="left_enabled")
- r_ret=si.enable_left;
- else if (what=="left_type")
- r_ret=si.type_left;
- else if (what=="left_color")
- r_ret=si.color_left;
- else if (what=="right_enabled")
- r_ret=si.enable_right;
- else if (what=="right_type")
- r_ret=si.type_right;
- else if (what=="right_color")
- r_ret=si.color_right;
+ si = slot_info[idx];
+
+ if (what == "left_enabled")
+ r_ret = si.enable_left;
+ else if (what == "left_type")
+ r_ret = si.type_left;
+ else if (what == "left_color")
+ r_ret = si.color_left;
+ else if (what == "right_enabled")
+ r_ret = si.enable_right;
+ else if (what == "right_type")
+ r_ret = si.type_right;
+ else if (what == "right_color")
+ r_ret = si.color_right;
else
return false;
return true;
}
-void GraphNode::_get_property_list( List<PropertyInfo> *p_list) const{
+void GraphNode::_get_property_list(List<PropertyInfo> *p_list) const {
- int idx=0;
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
- if (!c || c->is_set_as_toplevel() )
+ int idx = 0;
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
+ if (!c || c->is_set_as_toplevel())
continue;
- String base="slot/"+itos(idx)+"/";
+ String base = "slot/" + itos(idx) + "/";
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"left_enabled"));
- p_list->push_back(PropertyInfo(Variant::INT,base+"left_type"));
- p_list->push_back(PropertyInfo(Variant::COLOR,base+"left_color"));
- p_list->push_back(PropertyInfo(Variant::BOOL,base+"right_enabled"));
- p_list->push_back(PropertyInfo(Variant::INT,base+"right_type"));
- p_list->push_back(PropertyInfo(Variant::COLOR,base+"right_color"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "left_enabled"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "left_type"));
+ p_list->push_back(PropertyInfo(Variant::COLOR, base + "left_color"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, base + "right_enabled"));
+ p_list->push_back(PropertyInfo(Variant::INT, base + "right_type"));
+ p_list->push_back(PropertyInfo(Variant::COLOR, base + "right_color"));
idx++;
}
}
-
void GraphNode::_resort() {
-
-
- int sep=get_constant("separation");
- Ref<StyleBox> sb=get_stylebox("frame");
- bool first=true;
+ int sep = get_constant("separation");
+ Ref<StyleBox> sb = get_stylebox("frame");
+ bool first = true;
Size2 minsize;
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
- Size2i size=c->get_combined_minimum_size();
+ Size2i size = c->get_combined_minimum_size();
- minsize.y+=size.y;
- minsize.x=MAX(minsize.x,size.x);
+ minsize.y += size.y;
+ minsize.x = MAX(minsize.x, size.x);
if (first)
- first=false;
+ first = false;
else
- minsize.y+=sep;
-
+ minsize.y += sep;
}
-
- int vofs=0;
+ int vofs = 0;
int w = get_size().x - sb->get_minimum_size().x;
-
cache_y.clear();
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
- Size2i size=c->get_combined_minimum_size();
-
- Rect2 r(sb->get_margin(MARGIN_LEFT),sb->get_margin(MARGIN_TOP)+vofs,w,size.y);
+ Size2i size = c->get_combined_minimum_size();
- fit_child_in_rect(c,r);
- cache_y.push_back(vofs+size.y*0.5);
-
- if (vofs>0)
- vofs+=sep;
- vofs+=size.y;
+ Rect2 r(sb->get_margin(MARGIN_LEFT), sb->get_margin(MARGIN_TOP) + vofs, w, size.y);
+ fit_child_in_rect(c, r);
+ cache_y.push_back(vofs + size.y * 0.5);
+ if (vofs > 0)
+ vofs += sep;
+ vofs += size.y;
}
_change_notify();
update();
- connpos_dirty=true;
-
-
+ connpos_dirty = true;
}
-bool GraphNode::has_point(const Point2& p_point) const {
+bool GraphNode::has_point(const Point2 &p_point) const {
if (comment) {
Ref<StyleBox> comment = get_stylebox("comment");
- Ref<Texture> resizer =get_icon("resizer");
+ Ref<Texture> resizer = get_icon("resizer");
- if (Rect2(get_size()-resizer->get_size(), resizer->get_size()).has_point(p_point)) {
+ if (Rect2(get_size() - resizer->get_size(), resizer->get_size()).has_point(p_point)) {
return true;
}
- if (Rect2(0,0,get_size().width,comment->get_margin(MARGIN_TOP)).has_point(p_point)) {
+ if (Rect2(0, 0, get_size().width, comment->get_margin(MARGIN_TOP)).has_point(p_point)) {
return true;
}
@@ -205,245 +188,226 @@ bool GraphNode::has_point(const Point2& p_point) const {
void GraphNode::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
Ref<StyleBox> sb;
if (comment) {
- sb = get_stylebox( selected? "commentfocus" : "comment");
+ sb = get_stylebox(selected ? "commentfocus" : "comment");
} else {
- sb = get_stylebox( selected ? "selectedframe" : "frame");
+ sb = get_stylebox(selected ? "selectedframe" : "frame");
}
//sb=sb->duplicate();
//sb->call("set_modulate",modulate);
- Ref<Texture> port =get_icon("port");
- Ref<Texture> close =get_icon("close");
- Ref<Texture> resizer =get_icon("resizer");
+ Ref<Texture> port = get_icon("port");
+ Ref<Texture> close = get_icon("close");
+ Ref<Texture> resizer = get_icon("resizer");
int close_offset = get_constant("close_offset");
Ref<Font> title_font = get_font("title_font");
int title_offset = get_constant("title_offset");
Color title_color = get_color("title_color");
- Point2i icofs = -port->get_size()*0.5;
- int edgeofs=get_constant("port_offset");
- icofs.y+=sb->get_margin(MARGIN_TOP);
-
+ Point2i icofs = -port->get_size() * 0.5;
+ int edgeofs = get_constant("port_offset");
+ icofs.y += sb->get_margin(MARGIN_TOP);
+ draw_style_box(sb, Rect2(Point2(), get_size()));
- draw_style_box(sb,Rect2(Point2(),get_size()));
-
- switch(overlay) {
+ switch (overlay) {
case OVERLAY_DISABLED: {
} break;
case OVERLAY_BREAKPOINT: {
- draw_style_box(get_stylebox("breakpoint"),Rect2(Point2(),get_size()));
+ draw_style_box(get_stylebox("breakpoint"), Rect2(Point2(), get_size()));
} break;
case OVERLAY_POSITION: {
- draw_style_box(get_stylebox("position"),Rect2(Point2(),get_size()));
+ draw_style_box(get_stylebox("position"), Rect2(Point2(), get_size()));
} break;
}
- int w = get_size().width-sb->get_minimum_size().x;
+ int w = get_size().width - sb->get_minimum_size().x;
if (show_close)
- w-=close->get_width();
+ w -= close->get_width();
- draw_string(title_font,Point2(sb->get_margin(MARGIN_LEFT),-title_font->get_height()+title_font->get_ascent()+title_offset),title,title_color,w);
+ draw_string(title_font, Point2(sb->get_margin(MARGIN_LEFT), -title_font->get_height() + title_font->get_ascent() + title_offset), title, title_color, w);
if (show_close) {
- Vector2 cpos = Point2(w+sb->get_margin(MARGIN_LEFT),-close->get_height()+close_offset);
- draw_texture(close,cpos);
- close_rect.pos=cpos;
- close_rect.size=close->get_size();
+ Vector2 cpos = Point2(w + sb->get_margin(MARGIN_LEFT), -close->get_height() + close_offset);
+ draw_texture(close, cpos);
+ close_rect.pos = cpos;
+ close_rect.size = close->get_size();
} else {
- close_rect=Rect2();
+ close_rect = Rect2();
}
- for (Map<int,Slot>::Element *E=slot_info.front();E;E=E->next()) {
+ for (Map<int, Slot>::Element *E = slot_info.front(); E; E = E->next()) {
- if (E->key() < 0 || E->key()>=cache_y.size())
+ if (E->key() < 0 || E->key() >= cache_y.size())
continue;
if (!slot_info.has(E->key()))
continue;
- const Slot &s=slot_info[E->key()];
+ const Slot &s = slot_info[E->key()];
//left
if (s.enable_left) {
Ref<Texture> p = port;
if (s.custom_slot_left.is_valid()) {
- p=s.custom_slot_left;
+ p = s.custom_slot_left;
}
- p->draw(get_canvas_item(),icofs+Point2(edgeofs,cache_y[E->key()]),s.color_left);
+ p->draw(get_canvas_item(), icofs + Point2(edgeofs, cache_y[E->key()]), s.color_left);
}
if (s.enable_right) {
Ref<Texture> p = port;
if (s.custom_slot_right.is_valid()) {
- p=s.custom_slot_right;
+ p = s.custom_slot_right;
}
- p->draw(get_canvas_item(),icofs+Point2(get_size().x-edgeofs,cache_y[E->key()]),s.color_right);
+ p->draw(get_canvas_item(), icofs + Point2(get_size().x - edgeofs, cache_y[E->key()]), s.color_right);
}
-
}
-
if (resizeable) {
- draw_texture(resizer,get_size()-resizer->get_size());
+ draw_texture(resizer, get_size() - resizer->get_size());
}
}
- if (p_what==NOTIFICATION_SORT_CHILDREN) {
+ if (p_what == NOTIFICATION_SORT_CHILDREN) {
_resort();
}
-
}
+void GraphNode::set_slot(int p_idx, bool p_enable_left, int p_type_left, const Color &p_color_left, bool p_enable_right, int p_type_right, const Color &p_color_right, const Ref<Texture> &p_custom_left, const Ref<Texture> &p_custom_right) {
-void GraphNode::set_slot(int p_idx,bool p_enable_left,int p_type_left,const Color& p_color_left, bool p_enable_right,int p_type_right,const Color& p_color_right,const Ref<Texture>& p_custom_left,const Ref<Texture>& p_custom_right) {
-
- ERR_FAIL_COND(p_idx<0);
+ ERR_FAIL_COND(p_idx < 0);
- if (!p_enable_left && p_type_left==0 && p_color_left==Color(1,1,1,1) && !p_enable_right && p_type_right==0 && p_color_right==Color(1,1,1,1)) {
+ if (!p_enable_left && p_type_left == 0 && p_color_left == Color(1, 1, 1, 1) && !p_enable_right && p_type_right == 0 && p_color_right == Color(1, 1, 1, 1)) {
slot_info.erase(p_idx);
return;
}
Slot s;
- s.enable_left=p_enable_left;
- s.type_left=p_type_left;
- s.color_left=p_color_left;
- s.enable_right=p_enable_right;
- s.type_right=p_type_right;
- s.color_right=p_color_right;
- s.custom_slot_left=p_custom_left;
- s.custom_slot_right=p_custom_right;
- slot_info[p_idx]=s;
+ s.enable_left = p_enable_left;
+ s.type_left = p_type_left;
+ s.color_left = p_color_left;
+ s.enable_right = p_enable_right;
+ s.type_right = p_type_right;
+ s.color_right = p_color_right;
+ s.custom_slot_left = p_custom_left;
+ s.custom_slot_right = p_custom_right;
+ slot_info[p_idx] = s;
update();
- connpos_dirty=true;
-
+ connpos_dirty = true;
}
-void GraphNode::clear_slot(int p_idx){
+void GraphNode::clear_slot(int p_idx) {
slot_info.erase(p_idx);
update();
- connpos_dirty=true;
-
+ connpos_dirty = true;
}
-void GraphNode::clear_all_slots(){
+void GraphNode::clear_all_slots() {
slot_info.clear();
update();
- connpos_dirty=true;
-
+ connpos_dirty = true;
}
-bool GraphNode::is_slot_enabled_left(int p_idx) const{
+bool GraphNode::is_slot_enabled_left(int p_idx) const {
if (!slot_info.has(p_idx))
return false;
return slot_info[p_idx].enable_left;
-
}
-int GraphNode::get_slot_type_left(int p_idx) const{
+int GraphNode::get_slot_type_left(int p_idx) const {
if (!slot_info.has(p_idx))
return 0;
return slot_info[p_idx].type_left;
-
}
-Color GraphNode::get_slot_color_left(int p_idx) const{
+Color GraphNode::get_slot_color_left(int p_idx) const {
if (!slot_info.has(p_idx))
- return Color(1,1,1,1);
+ return Color(1, 1, 1, 1);
return slot_info[p_idx].color_left;
-
}
-bool GraphNode::is_slot_enabled_right(int p_idx) const{
+bool GraphNode::is_slot_enabled_right(int p_idx) const {
if (!slot_info.has(p_idx))
return false;
return slot_info[p_idx].enable_right;
-
}
-
-
-int GraphNode::get_slot_type_right(int p_idx) const{
+int GraphNode::get_slot_type_right(int p_idx) const {
if (!slot_info.has(p_idx))
return 0;
return slot_info[p_idx].type_right;
-
}
-Color GraphNode::get_slot_color_right(int p_idx) const{
+Color GraphNode::get_slot_color_right(int p_idx) const {
if (!slot_info.has(p_idx))
- return Color(1,1,1,1);
+ return Color(1, 1, 1, 1);
return slot_info[p_idx].color_right;
-
}
Size2 GraphNode::get_minimum_size() const {
Ref<Font> title_font = get_font("title_font");
- int sep=get_constant("separation");
- Ref<StyleBox> sb=get_stylebox("frame");
- bool first=true;
+ int sep = get_constant("separation");
+ Ref<StyleBox> sb = get_stylebox("frame");
+ bool first = true;
Size2 minsize;
- minsize.x=title_font->get_string_size(title).x;
+ minsize.x = title_font->get_string_size(title).x;
if (show_close) {
- Ref<Texture> close =get_icon("close");
- minsize.x+=sep+close->get_width();
+ Ref<Texture> close = get_icon("close");
+ minsize.x += sep + close->get_width();
}
+ for (int i = 0; i < get_child_count(); i++) {
- for(int i=0;i<get_child_count();i++) {
-
- Control *c=get_child(i)->cast_to<Control>();
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
- Size2i size=c->get_combined_minimum_size();
+ Size2i size = c->get_combined_minimum_size();
- minsize.y+=size.y;
- minsize.x=MAX(minsize.x,size.x);
+ minsize.y += size.y;
+ minsize.x = MAX(minsize.x, size.x);
if (first)
- first=false;
+ first = false;
else
- minsize.y+=sep;
+ minsize.y += sep;
}
- return minsize+sb->get_minimum_size();
+ return minsize + sb->get_minimum_size();
}
-void GraphNode::set_title(const String& p_title) {
+void GraphNode::set_title(const String &p_title) {
- title=p_title;
+ title = p_title;
minimum_size_changed();
update();
-
}
-String GraphNode::get_title() const{
+String GraphNode::get_title() const {
return title;
}
-void GraphNode::set_offset(const Vector2& p_offset) {
+void GraphNode::set_offset(const Vector2 &p_offset) {
- offset=p_offset;
+ offset = p_offset;
emit_signal("offset_changed");
update();
}
@@ -453,103 +417,93 @@ Vector2 GraphNode::get_offset() const {
return offset;
}
-void GraphNode::set_selected(bool p_selected)
-{
+void GraphNode::set_selected(bool p_selected) {
selected = p_selected;
update();
}
-bool GraphNode::is_selected()
-{
+bool GraphNode::is_selected() {
return selected;
}
-void GraphNode::set_drag(bool p_drag)
-{
+void GraphNode::set_drag(bool p_drag) {
if (p_drag)
- drag_from=get_offset();
+ drag_from = get_offset();
else
- emit_signal("dragged",drag_from,get_offset()); //useful for undo/redo
+ emit_signal("dragged", drag_from, get_offset()); //useful for undo/redo
}
-Vector2 GraphNode::get_drag_from()
-{
+Vector2 GraphNode::get_drag_from() {
return drag_from;
}
+void GraphNode::set_show_close_button(bool p_enable) {
-void GraphNode::set_show_close_button(bool p_enable){
-
- show_close=p_enable;
+ show_close = p_enable;
update();
}
-bool GraphNode::is_close_button_visible() const{
+bool GraphNode::is_close_button_visible() const {
return show_close;
}
void GraphNode::_connpos_update() {
+ int edgeofs = get_constant("port_offset");
+ int sep = get_constant("separation");
- int edgeofs=get_constant("port_offset");
- int sep=get_constant("separation");
-
- Ref<StyleBox> sb=get_stylebox("frame");
+ Ref<StyleBox> sb = get_stylebox("frame");
conn_input_cache.clear();
conn_output_cache.clear();
- int vofs=0;
+ int vofs = 0;
- int idx=0;
+ int idx = 0;
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (c->is_set_as_toplevel())
continue;
- Size2i size=c->get_combined_minimum_size();
+ Size2i size = c->get_combined_minimum_size();
- int y = sb->get_margin(MARGIN_TOP)+vofs;
+ int y = sb->get_margin(MARGIN_TOP) + vofs;
int h = size.y;
-
if (slot_info.has(idx)) {
if (slot_info[idx].enable_left) {
ConnCache cc;
- cc.pos=Point2i(edgeofs,y+h/2);
- cc.type=slot_info[idx].type_left;
- cc.color=slot_info[idx].color_left;
+ cc.pos = Point2i(edgeofs, y + h / 2);
+ cc.type = slot_info[idx].type_left;
+ cc.color = slot_info[idx].color_left;
conn_input_cache.push_back(cc);
}
if (slot_info[idx].enable_right) {
ConnCache cc;
- cc.pos=Point2i(get_size().width-edgeofs,y+h/2);
- cc.type=slot_info[idx].type_right;
- cc.color=slot_info[idx].color_right;
+ cc.pos = Point2i(get_size().width - edgeofs, y + h / 2);
+ cc.type = slot_info[idx].type_right;
+ cc.color = slot_info[idx].color_right;
conn_output_cache.push_back(cc);
}
}
- if (vofs>0)
- vofs+=sep;
- vofs+=size.y;
+ if (vofs > 0)
+ vofs += sep;
+ vofs += size.y;
idx++;
-
}
-
- connpos_dirty=false;
+ connpos_dirty = false;
}
-int GraphNode::get_connection_input_count() {
+int GraphNode::get_connection_input_count() {
if (connpos_dirty)
_connpos_update();
return conn_input_cache.size();
-
}
int GraphNode::get_connection_output_count() {
@@ -557,16 +511,14 @@ int GraphNode::get_connection_output_count() {
_connpos_update();
return conn_output_cache.size();
-
}
-
Vector2 GraphNode::get_connection_input_pos(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_input_cache.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_idx, conn_input_cache.size(), Vector2());
Vector2 pos = conn_input_cache[p_idx].pos;
pos.x *= get_scale().x;
pos.y *= get_scale().y;
@@ -578,7 +530,7 @@ int GraphNode::get_connection_input_type(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_input_cache.size(),0);
+ ERR_FAIL_INDEX_V(p_idx, conn_input_cache.size(), 0);
return conn_input_cache[p_idx].type;
}
@@ -587,16 +539,16 @@ Color GraphNode::get_connection_input_color(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_input_cache.size(),Color());
+ ERR_FAIL_INDEX_V(p_idx, conn_input_cache.size(), Color());
return conn_input_cache[p_idx].color;
}
-Vector2 GraphNode::get_connection_output_pos(int p_idx){
+Vector2 GraphNode::get_connection_output_pos(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_output_cache.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_idx, conn_output_cache.size(), Vector2());
Vector2 pos = conn_output_cache[p_idx].pos;
pos.x *= get_scale().x;
pos.y *= get_scale().y;
@@ -608,7 +560,7 @@ int GraphNode::get_connection_output_type(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_output_cache.size(),0);
+ ERR_FAIL_INDEX_V(p_idx, conn_output_cache.size(), 0);
return conn_output_cache[p_idx].type;
}
@@ -617,35 +569,35 @@ Color GraphNode::get_connection_output_color(int p_idx) {
if (connpos_dirty)
_connpos_update();
- ERR_FAIL_INDEX_V(p_idx,conn_output_cache.size(),Color());
+ ERR_FAIL_INDEX_V(p_idx, conn_output_cache.size(), Color());
return conn_output_cache[p_idx].color;
}
-void GraphNode::_gui_input(const InputEvent& p_ev) {
+void GraphNode::_gui_input(const InputEvent &p_ev) {
- if (p_ev.type==InputEvent::MOUSE_BUTTON) {
+ if (p_ev.type == InputEvent::MOUSE_BUTTON) {
ERR_EXPLAIN("GraphNode must be the child of a GraphEdit node.");
ERR_FAIL_COND(get_parent_control() == NULL);
print_line("INPUT EVENT BUTTON");
- if(p_ev.mouse_button.pressed && p_ev.mouse_button.button_index==BUTTON_LEFT) {
+ if (p_ev.mouse_button.pressed && p_ev.mouse_button.button_index == BUTTON_LEFT) {
- Vector2 mpos = Vector2(p_ev.mouse_button.x,p_ev.mouse_button.y);
- if (close_rect.size!=Size2() && close_rect.has_point(mpos)) {
+ Vector2 mpos = Vector2(p_ev.mouse_button.x, p_ev.mouse_button.y);
+ if (close_rect.size != Size2() && close_rect.has_point(mpos)) {
emit_signal("close_request");
accept_event();
return;
}
- Ref<Texture> resizer =get_icon("resizer");
+ Ref<Texture> resizer = get_icon("resizer");
- if (resizeable && mpos.x > get_size().x-resizer->get_width() && mpos.y > get_size().y-resizer->get_height()) {
+ if (resizeable && mpos.x > get_size().x - resizer->get_width() && mpos.y > get_size().y - resizer->get_height()) {
- resizing=true;
- resizing_from=mpos;
- resizing_from_size=get_size();
+ resizing = true;
+ resizing_from = mpos;
+ resizing_from_size = get_size();
accept_event();
return;
}
@@ -653,130 +605,122 @@ void GraphNode::_gui_input(const InputEvent& p_ev) {
//send focus to parent
emit_signal("raise_request");
get_parent_control()->grab_focus();
-
}
- if(!p_ev.mouse_button.pressed && p_ev.mouse_button.button_index==BUTTON_LEFT) {
- resizing=false;
+ if (!p_ev.mouse_button.pressed && p_ev.mouse_button.button_index == BUTTON_LEFT) {
+ resizing = false;
}
-
}
-
- if (resizing && p_ev.type==InputEvent::MOUSE_MOTION) {
- Vector2 mpos = Vector2(p_ev.mouse_motion.x,p_ev.mouse_motion.y);
+ if (resizing && p_ev.type == InputEvent::MOUSE_MOTION) {
+ Vector2 mpos = Vector2(p_ev.mouse_motion.x, p_ev.mouse_motion.y);
Vector2 diff = mpos - resizing_from;
- emit_signal("resize_request",resizing_from_size+diff);
-
+ emit_signal("resize_request", resizing_from_size + diff);
}
-
-
}
void GraphNode::set_overlay(Overlay p_overlay) {
- overlay=p_overlay;
+ overlay = p_overlay;
update();
}
-GraphNode::Overlay GraphNode::get_overlay() const{
+GraphNode::Overlay GraphNode::get_overlay() const {
return overlay;
}
void GraphNode::set_comment(bool p_enable) {
- comment=p_enable;
+ comment = p_enable;
update();
}
-bool GraphNode::is_comment() const{
+bool GraphNode::is_comment() const {
return comment;
}
-
void GraphNode::set_resizeable(bool p_enable) {
- resizeable=p_enable;
+ resizeable = p_enable;
update();
}
-bool GraphNode::is_resizeable() const{
+bool GraphNode::is_resizeable() const {
return resizeable;
}
-
void GraphNode::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_title","title"),&GraphNode::set_title);
- ClassDB::bind_method(D_METHOD("get_title"),&GraphNode::get_title);
- ClassDB::bind_method(D_METHOD("_gui_input"),&GraphNode::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_title", "title"), &GraphNode::set_title);
+ ClassDB::bind_method(D_METHOD("get_title"), &GraphNode::get_title);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &GraphNode::_gui_input);
- ClassDB::bind_method(D_METHOD("set_slot","idx","enable_left","type_left","color_left","enable_right","type_right","color_right","custom_left","custom_right"),&GraphNode::set_slot,DEFVAL(Ref<Texture>()),DEFVAL(Ref<Texture>()));
- ClassDB::bind_method(D_METHOD("clear_slot","idx"),&GraphNode::clear_slot);
- ClassDB::bind_method(D_METHOD("clear_all_slots","idx"),&GraphNode::clear_all_slots);
- ClassDB::bind_method(D_METHOD("is_slot_enabled_left","idx"),&GraphNode::is_slot_enabled_left);
- ClassDB::bind_method(D_METHOD("get_slot_type_left","idx"),&GraphNode::get_slot_type_left);
- ClassDB::bind_method(D_METHOD("get_slot_color_left","idx"),&GraphNode::get_slot_color_left);
- ClassDB::bind_method(D_METHOD("is_slot_enabled_right","idx"),&GraphNode::is_slot_enabled_right);
- ClassDB::bind_method(D_METHOD("get_slot_type_right","idx"),&GraphNode::get_slot_type_right);
- ClassDB::bind_method(D_METHOD("get_slot_color_right","idx"),&GraphNode::get_slot_color_right);
+ ClassDB::bind_method(D_METHOD("set_slot", "idx", "enable_left", "type_left", "color_left", "enable_right", "type_right", "color_right", "custom_left", "custom_right"), &GraphNode::set_slot, DEFVAL(Ref<Texture>()), DEFVAL(Ref<Texture>()));
+ ClassDB::bind_method(D_METHOD("clear_slot", "idx"), &GraphNode::clear_slot);
+ ClassDB::bind_method(D_METHOD("clear_all_slots", "idx"), &GraphNode::clear_all_slots);
+ ClassDB::bind_method(D_METHOD("is_slot_enabled_left", "idx"), &GraphNode::is_slot_enabled_left);
+ ClassDB::bind_method(D_METHOD("get_slot_type_left", "idx"), &GraphNode::get_slot_type_left);
+ ClassDB::bind_method(D_METHOD("get_slot_color_left", "idx"), &GraphNode::get_slot_color_left);
+ ClassDB::bind_method(D_METHOD("is_slot_enabled_right", "idx"), &GraphNode::is_slot_enabled_right);
+ ClassDB::bind_method(D_METHOD("get_slot_type_right", "idx"), &GraphNode::get_slot_type_right);
+ ClassDB::bind_method(D_METHOD("get_slot_color_right", "idx"), &GraphNode::get_slot_color_right);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&GraphNode::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&GraphNode::get_offset);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &GraphNode::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &GraphNode::get_offset);
- ClassDB::bind_method(D_METHOD("set_comment","comment"),&GraphNode::set_comment);
- ClassDB::bind_method(D_METHOD("is_comment"),&GraphNode::is_comment);
+ ClassDB::bind_method(D_METHOD("set_comment", "comment"), &GraphNode::set_comment);
+ ClassDB::bind_method(D_METHOD("is_comment"), &GraphNode::is_comment);
- ClassDB::bind_method(D_METHOD("set_resizeable","resizeable"),&GraphNode::set_resizeable);
- ClassDB::bind_method(D_METHOD("is_resizeable"),&GraphNode::is_resizeable);
+ ClassDB::bind_method(D_METHOD("set_resizeable", "resizeable"), &GraphNode::set_resizeable);
+ ClassDB::bind_method(D_METHOD("is_resizeable"), &GraphNode::is_resizeable);
- ClassDB::bind_method(D_METHOD("set_selected","selected"),&GraphNode::set_selected);
- ClassDB::bind_method(D_METHOD("is_selected"),&GraphNode::is_selected);
+ ClassDB::bind_method(D_METHOD("set_selected", "selected"), &GraphNode::set_selected);
+ ClassDB::bind_method(D_METHOD("is_selected"), &GraphNode::is_selected);
- ClassDB::bind_method(D_METHOD("get_connection_output_count"),&GraphNode::get_connection_output_count);
- ClassDB::bind_method(D_METHOD("get_connection_input_count"),&GraphNode::get_connection_input_count);
+ ClassDB::bind_method(D_METHOD("get_connection_output_count"), &GraphNode::get_connection_output_count);
+ ClassDB::bind_method(D_METHOD("get_connection_input_count"), &GraphNode::get_connection_input_count);
- ClassDB::bind_method(D_METHOD("get_connection_output_pos","idx"),&GraphNode::get_connection_output_pos);
- ClassDB::bind_method(D_METHOD("get_connection_output_type","idx"),&GraphNode::get_connection_output_type);
- ClassDB::bind_method(D_METHOD("get_connection_output_color","idx"),&GraphNode::get_connection_output_color);
- ClassDB::bind_method(D_METHOD("get_connection_input_pos","idx"),&GraphNode::get_connection_input_pos);
- ClassDB::bind_method(D_METHOD("get_connection_input_type","idx"),&GraphNode::get_connection_input_type);
- ClassDB::bind_method(D_METHOD("get_connection_input_color","idx"),&GraphNode::get_connection_input_color);
+ ClassDB::bind_method(D_METHOD("get_connection_output_pos", "idx"), &GraphNode::get_connection_output_pos);
+ ClassDB::bind_method(D_METHOD("get_connection_output_type", "idx"), &GraphNode::get_connection_output_type);
+ ClassDB::bind_method(D_METHOD("get_connection_output_color", "idx"), &GraphNode::get_connection_output_color);
+ ClassDB::bind_method(D_METHOD("get_connection_input_pos", "idx"), &GraphNode::get_connection_input_pos);
+ ClassDB::bind_method(D_METHOD("get_connection_input_type", "idx"), &GraphNode::get_connection_input_type);
+ ClassDB::bind_method(D_METHOD("get_connection_input_color", "idx"), &GraphNode::get_connection_input_color);
- ClassDB::bind_method(D_METHOD("set_show_close_button","show"),&GraphNode::set_show_close_button);
- ClassDB::bind_method(D_METHOD("is_close_button_visible"),&GraphNode::is_close_button_visible);
+ ClassDB::bind_method(D_METHOD("set_show_close_button", "show"), &GraphNode::set_show_close_button);
+ ClassDB::bind_method(D_METHOD("is_close_button_visible"), &GraphNode::is_close_button_visible);
- ClassDB::bind_method(D_METHOD("set_overlay","overlay"),&GraphNode::set_overlay);
- ClassDB::bind_method(D_METHOD("get_overlay"),&GraphNode::get_overlay);
+ ClassDB::bind_method(D_METHOD("set_overlay", "overlay"), &GraphNode::set_overlay);
+ ClassDB::bind_method(D_METHOD("get_overlay"), &GraphNode::get_overlay);
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"title"),"set_title","get_title");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"show_close"),"set_show_close_button","is_close_button_visible");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"resizeable"),"set_resizeable","is_resizeable");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "title"), "set_title", "get_title");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_close"), "set_show_close_button", "is_close_button_visible");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "resizeable"), "set_resizeable", "is_resizeable");
ADD_SIGNAL(MethodInfo("offset_changed"));
- ADD_SIGNAL(MethodInfo("dragged",PropertyInfo(Variant::VECTOR2,"from"),PropertyInfo(Variant::VECTOR2,"to")));
+ ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::VECTOR2, "from"), PropertyInfo(Variant::VECTOR2, "to")));
ADD_SIGNAL(MethodInfo("raise_request"));
ADD_SIGNAL(MethodInfo("close_request"));
- ADD_SIGNAL(MethodInfo("resize_request",PropertyInfo(Variant::VECTOR2,"new_minsize")));
+ ADD_SIGNAL(MethodInfo("resize_request", PropertyInfo(Variant::VECTOR2, "new_minsize")));
- BIND_CONSTANT( OVERLAY_DISABLED );
- BIND_CONSTANT( OVERLAY_BREAKPOINT );
- BIND_CONSTANT( OVERLAY_POSITION );
+ BIND_CONSTANT(OVERLAY_DISABLED);
+ BIND_CONSTANT(OVERLAY_BREAKPOINT);
+ BIND_CONSTANT(OVERLAY_POSITION);
}
GraphNode::GraphNode() {
- overlay=OVERLAY_DISABLED;
- show_close=false;
- connpos_dirty=true;
+ overlay = OVERLAY_DISABLED;
+ show_close = false;
+ connpos_dirty = true;
set_mouse_filter(MOUSE_FILTER_PASS);
- comment=false;
- resizeable=false;
- resizing=false;
- selected=false;
+ comment = false;
+ resizeable = false;
+ resizing = false;
+ selected = false;
}
diff --git a/scene/gui/graph_node.h b/scene/gui/graph_node.h
index 9cb46fc49c..bab78dedb9 100644
--- a/scene/gui/graph_node.h
+++ b/scene/gui/graph_node.h
@@ -33,16 +33,16 @@
class GraphNode : public Container {
- GDCLASS(GraphNode,Container);
-public:
+ GDCLASS(GraphNode, Container);
+public:
enum Overlay {
OVERLAY_DISABLED,
OVERLAY_BREAKPOINT,
OVERLAY_POSITION
};
-private:
+private:
struct Slot {
bool enable_left;
int type_left;
@@ -53,8 +53,14 @@ private:
Ref<Texture> custom_slot_left;
Ref<Texture> custom_slot_right;
-
- Slot() { enable_left=false; type_left=0; color_left=Color(1,1,1,1); enable_right=false; type_right=0; color_right=Color(1,1,1,1); }
+ Slot() {
+ enable_left = false;
+ type_left = 0;
+ color_left = Color(1, 1, 1, 1);
+ enable_right = false;
+ type_right = 0;
+ color_right = Color(1, 1, 1, 1);
+ }
};
String title;
@@ -80,7 +86,7 @@ private:
Vector<ConnCache> conn_input_cache;
Vector<ConnCache> conn_output_cache;
- Map<int,Slot> slot_info;
+ Map<int, Slot> slot_info;
bool connpos_dirty;
@@ -92,25 +98,19 @@ private:
Overlay overlay;
- bool has_point(const Point2& p_point) const;
+ bool has_point(const Point2 &p_point) const;
protected:
-
-
- void _gui_input(const InputEvent& p_ev);
+ void _gui_input(const InputEvent &p_ev);
void _notification(int p_what);
static void _bind_methods();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
-
-
-
- void set_slot(int p_idx,bool p_enable_left,int p_type_left,const Color& p_color_left, bool p_enable_right,int p_type_right,const Color& p_color_right,const Ref<Texture>& p_custom_left=Ref<Texture>(),const Ref<Texture>& p_custom_right=Ref<Texture>());
+ void set_slot(int p_idx, bool p_enable_left, int p_type_left, const Color &p_color_left, bool p_enable_right, int p_type_right, const Color &p_color_right, const Ref<Texture> &p_custom_left = Ref<Texture>(), const Ref<Texture> &p_custom_right = Ref<Texture>());
void clear_slot(int p_idx);
void clear_all_slots();
bool is_slot_enabled_left(int p_idx) const;
@@ -120,10 +120,10 @@ public:
int get_slot_type_right(int p_idx) const;
Color get_slot_color_right(int p_idx) const;
- void set_title(const String& p_title);
+ void set_title(const String &p_title);
String get_title() const;
- void set_offset(const Vector2& p_offset);
+ void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
void set_selected(bool p_selected);
@@ -135,8 +135,8 @@ public:
void set_show_close_button(bool p_enable);
bool is_close_button_visible() const;
- int get_connection_input_count() ;
- int get_connection_output_count() ;
+ int get_connection_input_count();
+ int get_connection_output_count();
Vector2 get_connection_input_pos(int p_idx);
int get_connection_input_type(int p_idx);
Color get_connection_input_color(int p_idx);
@@ -144,7 +144,6 @@ public:
int get_connection_output_type(int p_idx);
Color get_connection_output_color(int p_idx);
-
void set_overlay(Overlay p_overlay);
Overlay get_overlay() const;
@@ -161,6 +160,6 @@ public:
GraphNode();
};
-VARIANT_ENUM_CAST( GraphNode::Overlay )
+VARIANT_ENUM_CAST(GraphNode::Overlay)
#endif // GRAPH_NODE_H
diff --git a/scene/gui/grid_container.cpp b/scene/gui/grid_container.cpp
index ee1d642110..aae11255ed 100644
--- a/scene/gui/grid_container.cpp
+++ b/scene/gui/grid_container.cpp
@@ -28,29 +28,27 @@
/*************************************************************************/
#include "grid_container.h"
-
void GridContainer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
- Map<int,int> col_minw;
- Map<int,int> row_minh;
+ Map<int, int> col_minw;
+ Map<int, int> row_minh;
Set<int> col_expanded;
Set<int> row_expanded;
- int hsep=get_constant("hseparation");
- int vsep=get_constant("vseparation");
+ int hsep = get_constant("hseparation");
+ int vsep = get_constant("vseparation");
- int idx=0;
- int max_row=0;
- int max_col=0;
+ int idx = 0;
+ int max_row = 0;
+ int max_col = 0;
Size2 size = get_size();
-
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
@@ -61,55 +59,54 @@ void GridContainer::_notification(int p_what) {
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col))
- col_minw[col] = MAX(col_minw[col],ms.width);
+ col_minw[col] = MAX(col_minw[col], ms.width);
else
- col_minw[col]=ms.width;
+ col_minw[col] = ms.width;
if (row_minh.has(row))
- row_minh[row] = MAX(row_minh[row],ms.height);
+ row_minh[row] = MAX(row_minh[row], ms.height);
else
- row_minh[row]=ms.height;
+ row_minh[row] = ms.height;
//print_line("store row "+itos(row)+" mw "+itos(ms.height));
- if (c->get_h_size_flags()&SIZE_EXPAND)
+ if (c->get_h_size_flags() & SIZE_EXPAND)
col_expanded.insert(col);
- if (c->get_v_size_flags()&SIZE_EXPAND)
+ if (c->get_v_size_flags() & SIZE_EXPAND)
row_expanded.insert(row);
- max_col=MAX(col,max_col);
- max_row=MAX(row,max_row);
+ max_col = MAX(col, max_col);
+ max_row = MAX(row, max_row);
idx++;
}
Size2 ms;
- int expand_rows=0;
- int expand_cols=0;
+ int expand_rows = 0;
+ int expand_cols = 0;
- for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) {
- ms.width+=E->get();
+ for (Map<int, int>::Element *E = col_minw.front(); E; E = E->next()) {
+ ms.width += E->get();
if (col_expanded.has(E->key()))
expand_cols++;
}
- for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) {
- ms.height+=E->get();
+ for (Map<int, int>::Element *E = row_minh.front(); E; E = E->next()) {
+ ms.height += E->get();
if (row_expanded.has(E->key()))
expand_rows++;
}
- ms.height+=vsep*max_row;
- ms.width+=hsep*max_col;
-
- int row_expand = expand_rows?(size.y-ms.y)/expand_rows:0;
- int col_expand = expand_cols?(size.x-ms.x)/expand_cols:0;
+ ms.height += vsep * max_row;
+ ms.width += hsep * max_col;
+ int row_expand = expand_rows ? (size.y - ms.y) / expand_rows : 0;
+ int col_expand = expand_cols ? (size.x - ms.x) / expand_cols : 0;
- int col_ofs=0;
- int row_ofs=0;
- idx=0;
+ int col_ofs = 0;
+ int row_ofs = 0;
+ idx = 0;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
@@ -117,78 +114,74 @@ void GridContainer::_notification(int p_what) {
int row = idx / columns;
int col = idx % columns;
- if (col==0) {
- col_ofs=0;
- if (row>0 && row_minh.has(row-1))
- row_ofs+=row_minh[row-1]+vsep+(row_expanded.has(row-1)?row_expand:0);
+ if (col == 0) {
+ col_ofs = 0;
+ if (row > 0 && row_minh.has(row - 1))
+ row_ofs += row_minh[row - 1] + vsep + (row_expanded.has(row - 1) ? row_expand : 0);
}
Size2 s;
if (col_minw.has(col))
- s.width=col_minw[col];
+ s.width = col_minw[col];
if (row_minh.has(row))
- s.height=row_minh[row];
+ s.height = row_minh[row];
if (row_expanded.has(row))
- s.height+=row_expand;
+ s.height += row_expand;
if (col_expanded.has(col))
- s.width+=col_expand;
+ s.width += col_expand;
- Point2 p(col_ofs,row_ofs);
+ Point2 p(col_ofs, row_ofs);
//print_line("col: "+itos(col)+" row: "+itos(row)+" col_ofs: "+itos(col_ofs)+" row_ofs: "+itos(row_ofs));
- fit_child_in_rect(c,Rect2(p,s));
+ fit_child_in_rect(c, Rect2(p, s));
//print_line("col: "+itos(col)+" row: "+itos(row)+" rect: "+Rect2(p,s));
if (col_minw.has(col)) {
- col_ofs+=col_minw[col]+hsep+(col_expanded.has(col)?col_expand:0);
+ col_ofs += col_minw[col] + hsep + (col_expanded.has(col) ? col_expand : 0);
}
idx++;
}
-
-
} break;
}
-
}
void GridContainer::set_columns(int p_columns) {
- ERR_FAIL_COND(p_columns<1);
- columns=p_columns;
+ ERR_FAIL_COND(p_columns < 1);
+ columns = p_columns;
queue_sort();
minimum_size_changed();
-
}
-int GridContainer::get_columns() const{
+int GridContainer::get_columns() const {
return columns;
}
-void GridContainer::_bind_methods(){
+void GridContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_columns","columns"),&GridContainer::set_columns);
- ClassDB::bind_method(D_METHOD("get_columns"),&GridContainer::get_columns);
+ ClassDB::bind_method(D_METHOD("set_columns", "columns"), &GridContainer::set_columns);
+ ClassDB::bind_method(D_METHOD("get_columns"), &GridContainer::get_columns);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"columns",PROPERTY_HINT_RANGE,"1,1024,1"),"set_columns","get_columns");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "columns", PROPERTY_HINT_RANGE, "1,1024,1"), "set_columns", "get_columns");
}
Size2 GridContainer::get_minimum_size() const {
- Map<int,int> col_minw;
- Map<int,int> row_minh;
+ Map<int, int> col_minw;
+ Map<int, int> row_minh;
- int hsep=get_constant("hseparation");
- int vsep=get_constant("vseparation");
+ int hsep = get_constant("hseparation");
+ int vsep = get_constant("vseparation");
- int idx=0;
- int max_row=0;
- int max_col=0;
+ int idx = 0;
+ int max_row = 0;
+ int max_col = 0;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
@@ -197,39 +190,37 @@ Size2 GridContainer::get_minimum_size() const {
int col = idx % columns;
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col))
- col_minw[col] = MAX(col_minw[col],ms.width);
+ col_minw[col] = MAX(col_minw[col], ms.width);
else
- col_minw[col]=ms.width;
+ col_minw[col] = ms.width;
if (row_minh.has(row))
- row_minh[row] = MAX(row_minh[row],ms.height);
+ row_minh[row] = MAX(row_minh[row], ms.height);
else
- row_minh[row]=ms.height;
- max_col=MAX(col,max_col);
- max_row=MAX(row,max_row);
+ row_minh[row] = ms.height;
+ max_col = MAX(col, max_col);
+ max_row = MAX(row, max_row);
idx++;
}
Size2 ms;
- for (Map<int,int>::Element *E=col_minw.front();E;E=E->next()) {
- ms.width+=E->get();
+ for (Map<int, int>::Element *E = col_minw.front(); E; E = E->next()) {
+ ms.width += E->get();
}
- for (Map<int,int>::Element *E=row_minh.front();E;E=E->next()) {
- ms.height+=E->get();
+ for (Map<int, int>::Element *E = row_minh.front(); E; E = E->next()) {
+ ms.height += E->get();
}
- ms.height+=vsep*max_row;
- ms.width+=hsep*max_col;
+ ms.height += vsep * max_row;
+ ms.width += hsep * max_col;
return ms;
-
}
-
GridContainer::GridContainer() {
set_mouse_filter(MOUSE_FILTER_PASS);
- columns=1;
+ columns = 1;
}
diff --git a/scene/gui/grid_container.h b/scene/gui/grid_container.h
index cc1d04cdb2..61dda4e223 100644
--- a/scene/gui/grid_container.h
+++ b/scene/gui/grid_container.h
@@ -33,15 +33,15 @@
class GridContainer : public Container {
- GDCLASS(GridContainer,Container);
+ GDCLASS(GridContainer, Container);
int columns;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_columns(int p_columns);
int get_columns() const;
virtual Size2 get_minimum_size() const;
diff --git a/scene/gui/input_action.cpp b/scene/gui/input_action.cpp
index afdffd9a53..9576bb07e4 100644
--- a/scene/gui/input_action.cpp
+++ b/scene/gui/input_action.cpp
@@ -29,42 +29,41 @@
#include "input_action.h"
#include "os/keyboard.h"
-void ShortCut::set_shortcut(const InputEvent& p_shortcut){
+void ShortCut::set_shortcut(const InputEvent &p_shortcut) {
- shortcut=p_shortcut;
+ shortcut = p_shortcut;
emit_changed();
}
-InputEvent ShortCut::get_shortcut() const{
+InputEvent ShortCut::get_shortcut() const {
return shortcut;
}
-bool ShortCut::is_shortcut(const InputEvent& p_event) const {
+bool ShortCut::is_shortcut(const InputEvent &p_event) const {
- bool same=false;
+ bool same = false;
-
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::KEY: {
- same=(shortcut.key.scancode==p_event.key.scancode && shortcut.key.mod == p_event.key.mod);
+ same = (shortcut.key.scancode == p_event.key.scancode && shortcut.key.mod == p_event.key.mod);
} break;
case InputEvent::JOYPAD_BUTTON: {
- same=(shortcut.joy_button.button_index==p_event.joy_button.button_index);
+ same = (shortcut.joy_button.button_index == p_event.joy_button.button_index);
} break;
case InputEvent::MOUSE_BUTTON: {
- same=(shortcut.mouse_button.button_index==p_event.mouse_button.button_index);
+ same = (shortcut.mouse_button.button_index == p_event.mouse_button.button_index);
} break;
case InputEvent::JOYPAD_MOTION: {
- same=(shortcut.joy_motion.axis==p_event.joy_motion.axis && (shortcut.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0));
+ same = (shortcut.joy_motion.axis == p_event.joy_motion.axis && (shortcut.joy_motion.axis_value < 0) == (p_event.joy_motion.axis_value < 0));
} break;
default: {};
@@ -75,7 +74,7 @@ bool ShortCut::is_shortcut(const InputEvent& p_event) const {
String ShortCut::get_as_text() const {
- switch(shortcut.type) {
+ switch (shortcut.type) {
case InputEvent::NONE: {
@@ -85,35 +84,35 @@ String ShortCut::get_as_text() const {
String str;
if (shortcut.key.mod.shift)
- str+=RTR("Shift+");
+ str += RTR("Shift+");
if (shortcut.key.mod.alt)
- str+=RTR("Alt+");
+ str += RTR("Alt+");
if (shortcut.key.mod.control)
- str+=RTR("Ctrl+");
+ str += RTR("Ctrl+");
if (shortcut.key.mod.meta)
- str+=RTR("Meta+");
+ str += RTR("Meta+");
- str+=keycode_get_string(shortcut.key.scancode).capitalize();
+ str += keycode_get_string(shortcut.key.scancode).capitalize();
return str;
} break;
case InputEvent::JOYPAD_BUTTON: {
- String str = RTR("Device")+" "+itos(shortcut.device)+", "+RTR("Button")+" "+itos(shortcut.joy_button.button_index);
- str+=".";
+ String str = RTR("Device") + " " + itos(shortcut.device) + ", " + RTR("Button") + " " + itos(shortcut.joy_button.button_index);
+ str += ".";
return str;
} break;
case InputEvent::MOUSE_BUTTON: {
- String str = RTR("Device")+" "+itos(shortcut.device)+", ";
+ String str = RTR("Device") + " " + itos(shortcut.device) + ", ";
switch (shortcut.mouse_button.button_index) {
- case BUTTON_LEFT: str+=RTR("Left Button."); break;
- case BUTTON_RIGHT: str+=RTR("Right Button."); break;
- case BUTTON_MIDDLE: str+=RTR("Middle Button."); break;
- case BUTTON_WHEEL_UP: str+=RTR("Wheel Up."); break;
- case BUTTON_WHEEL_DOWN: str+=RTR("Wheel Down."); break;
- default: str+=RTR("Button")+" "+itos(shortcut.mouse_button.button_index)+".";
+ case BUTTON_LEFT: str += RTR("Left Button."); break;
+ case BUTTON_RIGHT: str += RTR("Right Button."); break;
+ case BUTTON_MIDDLE: str += RTR("Middle Button."); break;
+ case BUTTON_WHEEL_UP: str += RTR("Wheel Up."); break;
+ case BUTTON_WHEEL_DOWN: str += RTR("Wheel Down."); break;
+ default: str += RTR("Button") + " " + itos(shortcut.mouse_button.button_index) + ".";
}
return str;
@@ -121,7 +120,7 @@ String ShortCut::get_as_text() const {
case InputEvent::JOYPAD_MOTION: {
int ax = shortcut.joy_motion.axis;
- String str = RTR("Device")+" "+itos(shortcut.device)+", "+RTR("Axis")+" "+itos(ax)+".";
+ String str = RTR("Device") + " " + itos(shortcut.device) + ", " + RTR("Axis") + " " + itos(ax) + ".";
return str;
} break;
@@ -132,22 +131,21 @@ String ShortCut::get_as_text() const {
bool ShortCut::is_valid() const {
- return shortcut.type!=InputEvent::NONE;
+ return shortcut.type != InputEvent::NONE;
}
void ShortCut::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shortcut","event"),&ShortCut::set_shortcut);
- ClassDB::bind_method(D_METHOD("get_shortcut"),&ShortCut::get_shortcut);
+ ClassDB::bind_method(D_METHOD("set_shortcut", "event"), &ShortCut::set_shortcut);
+ ClassDB::bind_method(D_METHOD("get_shortcut"), &ShortCut::get_shortcut);
- ClassDB::bind_method(D_METHOD("is_valid"),&ShortCut::is_valid);
+ ClassDB::bind_method(D_METHOD("is_valid"), &ShortCut::is_valid);
- ClassDB::bind_method(D_METHOD("is_shortcut","event"),&ShortCut::is_shortcut);
- ClassDB::bind_method(D_METHOD("get_as_text"),&ShortCut::get_as_text);
+ ClassDB::bind_method(D_METHOD("is_shortcut", "event"), &ShortCut::is_shortcut);
+ ClassDB::bind_method(D_METHOD("get_as_text"), &ShortCut::get_as_text);
- ADD_PROPERTY(PropertyInfo(Variant::INPUT_EVENT,"shortcut"),"set_shortcut","get_shortcut");
+ ADD_PROPERTY(PropertyInfo(Variant::INPUT_EVENT, "shortcut"), "set_shortcut", "get_shortcut");
}
-ShortCut::ShortCut(){
-
+ShortCut::ShortCut() {
}
diff --git a/scene/gui/input_action.h b/scene/gui/input_action.h
index 3cdbc755ef..a0f5cf2c11 100644
--- a/scene/gui/input_action.h
+++ b/scene/gui/input_action.h
@@ -33,17 +33,17 @@
class ShortCut : public Resource {
- GDCLASS(ShortCut,Resource);
+ GDCLASS(ShortCut, Resource);
InputEvent shortcut;
-protected:
+protected:
static void _bind_methods();
-public:
- void set_shortcut(const InputEvent& p_shortcut);
+public:
+ void set_shortcut(const InputEvent &p_shortcut);
InputEvent get_shortcut() const;
- bool is_shortcut(const InputEvent& p_Event) const;
+ bool is_shortcut(const InputEvent &p_Event) const;
bool is_valid() const;
String get_as_text() const;
diff --git a/scene/gui/item_list.cpp b/scene/gui/item_list.cpp
index 91bd16ee0b..1db748a6b1 100644
--- a/scene/gui/item_list.cpp
+++ b/scene/gui/item_list.cpp
@@ -27,264 +27,235 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "item_list.h"
-#include "os/os.h"
#include "global_config.h"
+#include "os/os.h"
-
-void ItemList::add_item(const String& p_item,const Ref<Texture>& p_texture,bool p_selectable) {
+void ItemList::add_item(const String &p_item, const Ref<Texture> &p_texture, bool p_selectable) {
Item item;
- item.icon=p_texture;
- item.icon_region=Rect2i();
- item.text=p_item;
- item.selectable=p_selectable;
- item.selected=false;
- item.disabled=false;
- item.tooltip_enabled=true;
- item.custom_bg=Color(0,0,0,0);
+ item.icon = p_texture;
+ item.icon_region = Rect2i();
+ item.text = p_item;
+ item.selectable = p_selectable;
+ item.selected = false;
+ item.disabled = false;
+ item.tooltip_enabled = true;
+ item.custom_bg = Color(0, 0, 0, 0);
items.push_back(item);
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-void ItemList::add_icon_item(const Ref<Texture>& p_item,bool p_selectable){
+void ItemList::add_icon_item(const Ref<Texture> &p_item, bool p_selectable) {
Item item;
- item.icon=p_item;
- item.icon_region=Rect2i();
+ item.icon = p_item;
+ item.icon_region = Rect2i();
//item.text=p_item;
- item.selectable=p_selectable;
- item.selected=false;
- item.disabled=false;
- item.tooltip_enabled=true;
- item.custom_bg=Color(0,0,0,0);
+ item.selectable = p_selectable;
+ item.selected = false;
+ item.disabled = false;
+ item.tooltip_enabled = true;
+ item.custom_bg = Color(0, 0, 0, 0);
items.push_back(item);
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-void ItemList::set_item_text(int p_idx,const String& p_text){
+void ItemList::set_item_text(int p_idx, const String &p_text) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].text=p_text;
+ items[p_idx].text = p_text;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-String ItemList::get_item_text(int p_idx) const{
+String ItemList::get_item_text(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), String());
return items[p_idx].text;
-
}
void ItemList::set_item_tooltip_enabled(int p_idx, const bool p_enabled) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
items[p_idx].tooltip_enabled = p_enabled;
}
bool ItemList::is_item_tooltip_enabled(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(), false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].tooltip_enabled;
}
-void ItemList::set_item_tooltip(int p_idx,const String& p_tooltip){
+void ItemList::set_item_tooltip(int p_idx, const String &p_tooltip) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].tooltip=p_tooltip;
+ items[p_idx].tooltip = p_tooltip;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-String ItemList::get_item_tooltip(int p_idx) const{
+String ItemList::get_item_tooltip(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), String());
return items[p_idx].tooltip;
-
}
-void ItemList::set_item_icon(int p_idx,const Ref<Texture>& p_icon){
+void ItemList::set_item_icon(int p_idx, const Ref<Texture> &p_icon) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].icon=p_icon;
+ items[p_idx].icon = p_icon;
update();
- shape_changed=true;
-
-
+ shape_changed = true;
}
-Ref<Texture> ItemList::get_item_icon(int p_idx) const{
+Ref<Texture> ItemList::get_item_icon(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture>());
return items[p_idx].icon;
-
}
-void ItemList::set_item_icon_region(int p_idx,const Rect2& p_region) {
+void ItemList::set_item_icon_region(int p_idx, const Rect2 &p_region) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].icon_region=p_region;
+ items[p_idx].icon_region = p_region;
update();
- shape_changed=true;
+ shape_changed = true;
}
Rect2 ItemList::get_item_icon_region(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Rect2());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Rect2());
return items[p_idx].icon_region;
}
-void ItemList::set_item_custom_bg_color(int p_idx,const Color& p_custom_bg_color) {
-
- ERR_FAIL_INDEX(p_idx,items.size());
+void ItemList::set_item_custom_bg_color(int p_idx, const Color &p_custom_bg_color) {
- items[p_idx].custom_bg=p_custom_bg_color;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].custom_bg = p_custom_bg_color;
}
Color ItemList::get_item_custom_bg_color(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Color());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Color());
return items[p_idx].custom_bg;
-
}
+void ItemList::set_item_tag_icon(int p_idx, const Ref<Texture> &p_tag_icon) {
+ ERR_FAIL_INDEX(p_idx, items.size());
-void ItemList::set_item_tag_icon(int p_idx,const Ref<Texture>& p_tag_icon){
-
- ERR_FAIL_INDEX(p_idx,items.size());
-
- items[p_idx].tag_icon=p_tag_icon;
+ items[p_idx].tag_icon = p_tag_icon;
update();
- shape_changed=true;
-
-
+ shape_changed = true;
}
-Ref<Texture> ItemList::get_item_tag_icon(int p_idx) const{
+Ref<Texture> ItemList::get_item_tag_icon(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture>());
return items[p_idx].tag_icon;
-
}
-void ItemList::set_item_selectable(int p_idx,bool p_selectable){
-
- ERR_FAIL_INDEX(p_idx,items.size());
-
- items[p_idx].selectable=p_selectable;
+void ItemList::set_item_selectable(int p_idx, bool p_selectable) {
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].selectable = p_selectable;
}
+bool ItemList::is_item_selectable(int p_idx) const {
-bool ItemList::is_item_selectable(int p_idx) const{
-
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].selectable;
}
-void ItemList::set_item_disabled(int p_idx,bool p_disabled){
+void ItemList::set_item_disabled(int p_idx, bool p_disabled) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].disabled=p_disabled;
+ items[p_idx].disabled = p_disabled;
update();
-
}
+bool ItemList::is_item_disabled(int p_idx) const {
-bool ItemList::is_item_disabled(int p_idx) const{
-
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].disabled;
}
+void ItemList::set_item_metadata(int p_idx, const Variant &p_metadata) {
-void ItemList::set_item_metadata(int p_idx,const Variant& p_metadata){
-
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].metadata=p_metadata;
+ items[p_idx].metadata = p_metadata;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-Variant ItemList::get_item_metadata(int p_idx) const{
+Variant ItemList::get_item_metadata(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Variant());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Variant());
return items[p_idx].metadata;
-
}
-void ItemList::select(int p_idx,bool p_single){
+void ItemList::select(int p_idx, bool p_single) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- if (p_single || select_mode==SELECT_SINGLE) {
+ if (p_single || select_mode == SELECT_SINGLE) {
if (!items[p_idx].selectable || items[p_idx].disabled) {
return;
}
- for(int i=0;i<items.size();i++) {
- items[i].selected=p_idx==i;
+ for (int i = 0; i < items.size(); i++) {
+ items[i].selected = p_idx == i;
}
- current=p_idx;
- ensure_selected_visible=false;
+ current = p_idx;
+ ensure_selected_visible = false;
} else {
if (items[p_idx].selectable && !items[p_idx].disabled) {
- items[p_idx].selected=true;
+ items[p_idx].selected = true;
}
}
update();
-
-
}
-void ItemList::unselect(int p_idx){
+void ItemList::unselect(int p_idx) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- if (select_mode!=SELECT_MULTI) {
- items[p_idx].selected=false;
- current=-1;
+ if (select_mode != SELECT_MULTI) {
+ items[p_idx].selected = false;
+ current = -1;
} else {
- items[p_idx].selected=false;
+ items[p_idx].selected = false;
}
update();
-
}
-bool ItemList::is_selected(int p_idx) const{
+bool ItemList::is_selected(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].selected;
-
}
void ItemList::set_current(int p_current) {
- ERR_FAIL_INDEX(p_current,items.size());
+ ERR_FAIL_INDEX(p_current, items.size());
- if (select_mode==SELECT_SINGLE)
- select(p_current,true);
+ if (select_mode == SELECT_SINGLE)
+ select(p_current, true);
else {
- current=p_current;
+ current = p_current;
update();
}
}
@@ -294,117 +265,110 @@ int ItemList::get_current() const {
return current;
}
-void ItemList::move_item(int p_item,int p_to_pos) {
+void ItemList::move_item(int p_item, int p_to_pos) {
- ERR_FAIL_INDEX(p_item,items.size());
- ERR_FAIL_INDEX(p_to_pos,items.size()+1);
+ ERR_FAIL_INDEX(p_item, items.size());
+ ERR_FAIL_INDEX(p_to_pos, items.size() + 1);
- Item it=items[p_item];
+ Item it = items[p_item];
items.remove(p_item);
- if (p_to_pos>p_item) {
+ if (p_to_pos > p_item) {
p_to_pos--;
}
- if (p_to_pos>=items.size()) {
+ if (p_to_pos >= items.size()) {
items.push_back(it);
} else {
- items.insert(p_to_pos,it);
+ items.insert(p_to_pos, it);
}
- if (current<0) {
+ if (current < 0) {
//do none
- } else if (p_item==current) {
- current=p_to_pos;
- } else if (p_to_pos>p_item && current>p_item && current<p_to_pos) {
+ } else if (p_item == current) {
+ current = p_to_pos;
+ } else if (p_to_pos > p_item && current > p_item && current < p_to_pos) {
current--;
- } else if (p_to_pos<p_item && current<p_item && current>p_to_pos) {
+ } else if (p_to_pos < p_item && current < p_item && current > p_to_pos) {
current++;
}
-
update();
}
-int ItemList::get_item_count() const{
+int ItemList::get_item_count() const {
return items.size();
}
-void ItemList::remove_item(int p_idx){
+void ItemList::remove_item(int p_idx) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
items.remove(p_idx);
update();
- shape_changed=true;
- defer_select_single=-1;
-
-
+ shape_changed = true;
+ defer_select_single = -1;
}
-void ItemList::clear(){
+void ItemList::clear() {
items.clear();
- current=-1;
- ensure_selected_visible=false;
+ current = -1;
+ ensure_selected_visible = false;
update();
- shape_changed=true;
- defer_select_single=-1;
-
+ shape_changed = true;
+ defer_select_single = -1;
}
-void ItemList::set_fixed_column_width(int p_size){
+void ItemList::set_fixed_column_width(int p_size) {
- ERR_FAIL_COND(p_size<0);
- fixed_column_width=p_size;
+ ERR_FAIL_COND(p_size < 0);
+ fixed_column_width = p_size;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-int ItemList::get_fixed_column_width() const{
+int ItemList::get_fixed_column_width() const {
return fixed_column_width;
}
-void ItemList::set_same_column_width(bool p_enable){
+void ItemList::set_same_column_width(bool p_enable) {
- same_column_width=p_enable;
+ same_column_width = p_enable;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-int ItemList::is_same_column_width() const{
+int ItemList::is_same_column_width() const {
return same_column_width;
}
-void ItemList::set_max_text_lines(int p_lines){
+void ItemList::set_max_text_lines(int p_lines) {
- ERR_FAIL_COND(p_lines<1);
- max_text_lines=p_lines;
+ ERR_FAIL_COND(p_lines < 1);
+ max_text_lines = p_lines;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-int ItemList::get_max_text_lines() const{
+int ItemList::get_max_text_lines() const {
return max_text_lines;
}
-void ItemList::set_max_columns(int p_amount){
+void ItemList::set_max_columns(int p_amount) {
- ERR_FAIL_COND(p_amount<0);
- max_columns=p_amount;
+ ERR_FAIL_COND(p_amount < 0);
+ max_columns = p_amount;
update();
}
-int ItemList::get_max_columns() const{
+int ItemList::get_max_columns() const {
return max_columns;
}
void ItemList::set_select_mode(SelectMode p_mode) {
- select_mode=p_mode;
+ select_mode = p_mode;
update();
}
@@ -413,22 +377,20 @@ ItemList::SelectMode ItemList::get_select_mode() const {
return select_mode;
}
-void ItemList::set_icon_mode(IconMode p_mode){
+void ItemList::set_icon_mode(IconMode p_mode) {
- icon_mode=p_mode;
+ icon_mode = p_mode;
update();
- shape_changed=true;
-
+ shape_changed = true;
}
-ItemList::IconMode ItemList::get_icon_mode() const{
+ItemList::IconMode ItemList::get_icon_mode() const {
return icon_mode;
}
+void ItemList::set_fixed_icon_size(const Size2 &p_size) {
-void ItemList::set_fixed_icon_size(const Size2& p_size) {
-
- fixed_icon_size=p_size;
+ fixed_icon_size = p_size;
update();
}
@@ -446,151 +408,142 @@ Size2 ItemList::Item::get_icon_size() const {
return icon_region.size;
}
-void ItemList::_gui_input(const InputEvent& p_event) {
+void ItemList::_gui_input(const InputEvent &p_event) {
- if (defer_select_single>=0 && p_event.type==InputEvent::MOUSE_MOTION) {
- defer_select_single=-1;
+ if (defer_select_single >= 0 && p_event.type == InputEvent::MOUSE_MOTION) {
+ defer_select_single = -1;
return;
}
- if (defer_select_single>=0 && p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==BUTTON_LEFT && !p_event.mouse_button.pressed) {
-
- select(defer_select_single,true);
+ if (defer_select_single >= 0 && p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == BUTTON_LEFT && !p_event.mouse_button.pressed) {
+ select(defer_select_single, true);
- emit_signal("multi_selected",defer_select_single,true);
- defer_select_single=-1;
+ emit_signal("multi_selected", defer_select_single, true);
+ defer_select_single = -1;
return;
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && (p_event.mouse_button.button_index==BUTTON_LEFT || (allow_rmb_select && p_event.mouse_button.button_index==BUTTON_RIGHT)) && p_event.mouse_button.pressed) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && (p_event.mouse_button.button_index == BUTTON_LEFT || (allow_rmb_select && p_event.mouse_button.button_index == BUTTON_RIGHT)) && p_event.mouse_button.pressed) {
const InputEventMouseButton &mb = p_event.mouse_button;
- search_string=""; //any mousepress cancels
- Vector2 pos(mb.x,mb.y);
+ search_string = ""; //any mousepress cancels
+ Vector2 pos(mb.x, mb.y);
Ref<StyleBox> bg = get_stylebox("bg");
- pos-=bg->get_offset();
- pos.y+=scroll_bar->get_value();
+ pos -= bg->get_offset();
+ pos.y += scroll_bar->get_value();
int closest = -1;
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
Rect2 rc = items[i].rect_cache;
- if (i%current_columns==current_columns-1) {
- rc.size.width=get_size().width; //not right but works
+ if (i % current_columns == current_columns - 1) {
+ rc.size.width = get_size().width; //not right but works
}
if (rc.has_point(pos)) {
- closest=i;
+ closest = i;
break;
}
}
- if (closest!=-1) {
+ if (closest != -1) {
int i = closest;
- if (select_mode==SELECT_MULTI && items[i].selected && mb.mod.command) {
+ if (select_mode == SELECT_MULTI && items[i].selected && mb.mod.command) {
unselect(i);
- emit_signal("multi_selected",i,false);
+ emit_signal("multi_selected", i, false);
- } else if (select_mode==SELECT_MULTI && mb.mod.shift && current>=0 && current<items.size() && current!=i) {
+ } else if (select_mode == SELECT_MULTI && mb.mod.shift && current >= 0 && current < items.size() && current != i) {
int from = current;
int to = i;
- if (i<current) {
- SWAP(from,to);
+ if (i < current) {
+ SWAP(from, to);
}
- for(int j=from;j<=to;j++) {
+ for (int j = from; j <= to; j++) {
bool selected = !items[j].selected;
- select(j,false);
+ select(j, false);
if (selected)
- emit_signal("multi_selected",i,true);
+ emit_signal("multi_selected", i, true);
}
- if (p_event.mouse_button.button_index==BUTTON_RIGHT) {
+ if (p_event.mouse_button.button_index == BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",i,Vector2(mb.x,mb.y));
+ emit_signal("item_rmb_selected", i, Vector2(mb.x, mb.y));
}
} else {
- if (!mb.doubleclick && !mb.mod.command && select_mode==SELECT_MULTI && items[i].selectable && !items[i].disabled && items[i].selected && p_event.mouse_button.button_index==BUTTON_LEFT) {
- defer_select_single=i;
+ if (!mb.doubleclick && !mb.mod.command && select_mode == SELECT_MULTI && items[i].selectable && !items[i].disabled && items[i].selected && p_event.mouse_button.button_index == BUTTON_LEFT) {
+ defer_select_single = i;
return;
}
- if (items[i].selected && p_event.mouse_button.button_index==BUTTON_RIGHT) {
+ if (items[i].selected && p_event.mouse_button.button_index == BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",i,Vector2(mb.x,mb.y));
+ emit_signal("item_rmb_selected", i, Vector2(mb.x, mb.y));
} else {
bool selected = !items[i].selected;
-
- select(i,select_mode==SELECT_SINGLE || !mb.mod.command);
+ select(i, select_mode == SELECT_SINGLE || !mb.mod.command);
if (selected) {
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",i);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", i);
} else
- emit_signal("multi_selected",i,true);
-
-
+ emit_signal("multi_selected", i, true);
}
- if (p_event.mouse_button.button_index==BUTTON_RIGHT) {
+ if (p_event.mouse_button.button_index == BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",i,Vector2(mb.x,mb.y));
+ emit_signal("item_rmb_selected", i, Vector2(mb.x, mb.y));
} else if (/*select_mode==SELECT_SINGLE &&*/ mb.doubleclick) {
- emit_signal("item_activated",i);
-
+ emit_signal("item_activated", i);
}
}
}
-
return;
} else {
Vector<int> sItems = get_selected_items();
- for(int i = 0; i < sItems.size(); i++) {
+ for (int i = 0; i < sItems.size(); i++) {
unselect(sItems[i]);
}
}
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==BUTTON_WHEEL_UP && p_event.mouse_button.pressed) {
-
- scroll_bar->set_value( scroll_bar->get_value()-scroll_bar->get_page()/8 );
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == BUTTON_WHEEL_UP && p_event.mouse_button.pressed) {
+ scroll_bar->set_value(scroll_bar->get_value() - scroll_bar->get_page() / 8);
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==BUTTON_WHEEL_DOWN && p_event.mouse_button.pressed) {
-
- scroll_bar->set_value( scroll_bar->get_value()+scroll_bar->get_page()/8 );
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index == BUTTON_WHEEL_DOWN && p_event.mouse_button.pressed) {
+ scroll_bar->set_value(scroll_bar->get_value() + scroll_bar->get_page() / 8);
}
- if (p_event.is_pressed() && items.size()>0) {
+ if (p_event.is_pressed() && items.size() > 0) {
if (p_event.is_action("ui_up")) {
- if (search_string!="") {
+ if (search_string != "") {
uint64_t now = OS::get_singleton()->get_ticks_msec();
- uint64_t diff = now-search_time_msec;
+ uint64_t diff = now - search_time_msec;
- if (diff<int(GlobalConfig::get_singleton()->get("gui/timers/incremental_search_max_interval_msec"))*2) {
+ if (diff < int(GlobalConfig::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
- for(int i=current-1;i>=0;i--) {
+ for (int i = current - 1; i >= 0; i--) {
if (items[i].text.begins_with(search_string)) {
set_current(i);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
-
break;
}
}
@@ -599,31 +552,31 @@ void ItemList::_gui_input(const InputEvent& p_event) {
}
}
- if (current>=current_columns) {
- set_current(current-current_columns);
+ if (current >= current_columns) {
+ set_current(current - current_columns);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
}
} else if (p_event.is_action("ui_down")) {
- if (search_string!="") {
+ if (search_string != "") {
uint64_t now = OS::get_singleton()->get_ticks_msec();
- uint64_t diff = now-search_time_msec;
+ uint64_t diff = now - search_time_msec;
- if (diff<int(GlobalConfig::get_singleton()->get("gui/timers/incremental_search_max_interval_msec"))*2) {
+ if (diff < int(GlobalConfig::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
- for(int i=current+1;i<items.size();i++) {
+ for (int i = current + 1; i < items.size(); i++) {
if (items[i].text.begins_with(search_string)) {
set_current(i);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
break;
}
@@ -633,25 +586,24 @@ void ItemList::_gui_input(const InputEvent& p_event) {
}
}
- if (current<items.size()-current_columns) {
- set_current(current+current_columns);
+ if (current < items.size() - current_columns) {
+ set_current(current + current_columns);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
-
}
} else if (p_event.is_action("ui_page_up")) {
- search_string=""; //any mousepress cancels
+ search_string = ""; //any mousepress cancels
- for(int i=4;i>0;i--) {
- if (current-current_columns*i >=0 ) {
- set_current( current- current_columns*i);
+ for (int i = 4; i > 0; i--) {
+ if (current - current_columns * i >= 0) {
+ set_current(current - current_columns * i);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
break;
@@ -659,14 +611,14 @@ void ItemList::_gui_input(const InputEvent& p_event) {
}
} else if (p_event.is_action("ui_page_down")) {
- search_string=""; //any mousepress cancels
+ search_string = ""; //any mousepress cancels
- for(int i=4;i>0;i--) {
- if (current+current_columns*i < items.size() ) {
- set_current( current+ current_columns*i);
+ for (int i = 4; i > 0; i--) {
+ if (current + current_columns * i < items.size()) {
+ set_current(current + current_columns * i);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
@@ -675,146 +627,134 @@ void ItemList::_gui_input(const InputEvent& p_event) {
}
} else if (p_event.is_action("ui_left")) {
- search_string=""; //any mousepress cancels
+ search_string = ""; //any mousepress cancels
- if (current%current_columns!=0) {
- set_current(current-1);
+ if (current % current_columns != 0) {
+ set_current(current - 1);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
-
}
} else if (p_event.is_action("ui_right")) {
- search_string=""; //any mousepress cancels
+ search_string = ""; //any mousepress cancels
- if (current%current_columns!=(current_columns-1)) {
- set_current(current+1);
+ if (current % current_columns != (current_columns - 1)) {
+ set_current(current + 1);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
accept_event();
-
}
} else if (p_event.is_action("ui_cancel")) {
- search_string="";
+ search_string = "";
} else if (p_event.is_action("ui_select")) {
-
- if (select_mode==SELECT_MULTI && current>=0 && current<items.size()) {
+ if (select_mode == SELECT_MULTI && current >= 0 && current < items.size()) {
if (items[current].selectable && !items[current].disabled && !items[current].selected) {
- select(current,false);
- emit_signal("multi_selected",current,true);
+ select(current, false);
+ emit_signal("multi_selected", current, true);
} else if (items[current].selected) {
unselect(current);
- emit_signal("multi_selected",current,false);
+ emit_signal("multi_selected", current, false);
}
}
} else if (p_event.is_action("ui_accept")) {
- search_string=""; //any mousepress cance
+ search_string = ""; //any mousepress cance
- if (current>=0 && current<items.size()) {
- emit_signal("item_activated",current);
+ if (current >= 0 && current < items.size()) {
+ emit_signal("item_activated", current);
}
- } else if (p_event.type==InputEvent::KEY) {
+ } else if (p_event.type == InputEvent::KEY) {
if (p_event.key.unicode) {
uint64_t now = OS::get_singleton()->get_ticks_msec();
- uint64_t diff = now-search_time_msec;
- uint64_t max_interval = uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec",2000));
+ uint64_t diff = now - search_time_msec;
+ uint64_t max_interval = uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000));
search_time_msec = now;
- if (diff>max_interval) {
- search_string="";
+ if (diff > max_interval) {
+ search_string = "";
}
- search_string+=String::chr(p_event.key.unicode);
- for(int i=0;i<items.size();i++) {
+ search_string += String::chr(p_event.key.unicode);
+ for (int i = 0; i < items.size(); i++) {
if (items[i].text.begins_with(search_string)) {
set_current(i);
ensure_current_is_visible();
- if (select_mode==SELECT_SINGLE) {
- emit_signal("item_selected",current);
+ if (select_mode == SELECT_SINGLE) {
+ emit_signal("item_selected", current);
}
break;
}
}
-
}
-
}
}
-
-
-
-
}
void ItemList::ensure_current_is_visible() {
- ensure_selected_visible=true;
+ ensure_selected_visible = true;
update();
}
static Rect2 _adjust_to_max_size(Size2 p_size, Size2 p_max_size) {
- Size2 size=p_max_size;
+ Size2 size = p_max_size;
int tex_width = p_size.width * size.height / p_size.height;
int tex_height = size.height;
- if (tex_width>size.width) {
- tex_width=size.width;
- tex_height=p_size.height * tex_width / p_size.width;
+ if (tex_width > size.width) {
+ tex_width = size.width;
+ tex_height = p_size.height * tex_width / p_size.width;
}
- int ofs_x=(size.width - tex_width)/2;
- int ofs_y=(size.height - tex_height)/2;
-
- return Rect2(ofs_x,ofs_y,tex_width,tex_height);
-
+ int ofs_x = (size.width - tex_width) / 2;
+ int ofs_y = (size.height - tex_height) / 2;
+ return Rect2(ofs_x, ofs_y, tex_width, tex_height);
}
void ItemList::_notification(int p_what) {
- if (p_what==NOTIFICATION_RESIZED) {
- shape_changed=true;
+ if (p_what == NOTIFICATION_RESIZED) {
+ shape_changed = true;
update();
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
Ref<StyleBox> bg = get_stylebox("bg");
int mw = scroll_bar->get_minimum_size().x;
- scroll_bar->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,mw+bg->get_margin(MARGIN_RIGHT));
- scroll_bar->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,bg->get_margin(MARGIN_RIGHT));
- scroll_bar->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,bg->get_margin(MARGIN_TOP));
- scroll_bar->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,bg->get_margin(MARGIN_BOTTOM));
-
+ scroll_bar->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, mw + bg->get_margin(MARGIN_RIGHT));
+ scroll_bar->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, bg->get_margin(MARGIN_RIGHT));
+ scroll_bar->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, bg->get_margin(MARGIN_TOP));
+ scroll_bar->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, bg->get_margin(MARGIN_BOTTOM));
Size2 size = get_size();
- float page = size.height-bg->get_minimum_size().height;
- int width = size.width-bg->get_minimum_size().width;
- if (scroll_bar->is_visible()){
- width-=mw+bg->get_margin(MARGIN_RIGHT);
+ float page = size.height - bg->get_minimum_size().height;
+ int width = size.width - bg->get_minimum_size().width;
+ if (scroll_bar->is_visible()) {
+ width -= mw + bg->get_margin(MARGIN_RIGHT);
}
scroll_bar->set_page(page);
- draw_style_box(bg,Rect2(Point2(),size));
+ draw_style_box(bg, Rect2(Point2(), size));
int hseparation = get_constant("hseparation");
int vseparation = get_constant("vseparation");
int icon_margin = get_constant("icon_margin");
int line_separation = get_constant("line_separation");
- Ref<StyleBox> sbsel = has_focus()?get_stylebox("selected_focus"):get_stylebox("selected");
- Ref<StyleBox> cursor = has_focus()?get_stylebox("cursor"):get_stylebox("cursor_unfocused");
+ Ref<StyleBox> sbsel = has_focus() ? get_stylebox("selected_focus") : get_stylebox("selected");
+ Ref<StyleBox> cursor = has_focus() ? get_stylebox("cursor") : get_stylebox("cursor_unfocused");
Ref<Font> font = get_font("font");
Color guide_color = get_color("guide_color");
@@ -830,9 +770,9 @@ void ItemList::_notification(int p_what) {
}
if (has_focus()) {
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(),true);
- draw_style_box(get_stylebox("bg_focus"),Rect2(Point2(),size));
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(),false);
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), true);
+ draw_style_box(get_stylebox("bg_focus"), Rect2(Point2(), size));
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), false);
}
if (shape_changed) {
@@ -840,114 +780,109 @@ void ItemList::_notification(int p_what) {
float max_column_width = 0;
//1- compute item minimum sizes
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
Size2 minsize;
if (items[i].icon.is_valid()) {
- if (fixed_icon_size.x>0 && fixed_icon_size.y>0) {
- minsize=fixed_icon_size* icon_scale;
+ if (fixed_icon_size.x > 0 && fixed_icon_size.y > 0) {
+ minsize = fixed_icon_size * icon_scale;
} else {
- minsize=items[i].get_icon_size() *icon_scale;
+ minsize = items[i].get_icon_size() * icon_scale;
}
- if (items[i].text!="") {
- if (icon_mode==ICON_MODE_TOP) {
- minsize.y+=icon_margin;
+ if (items[i].text != "") {
+ if (icon_mode == ICON_MODE_TOP) {
+ minsize.y += icon_margin;
} else {
- minsize.x+=icon_margin;
+ minsize.x += icon_margin;
}
}
}
- if (items[i].text!="") {
+ if (items[i].text != "") {
Size2 s = font->get_string_size(items[i].text);
//s.width=MIN(s.width,fixed_column_width);
-
-
- if (icon_mode==ICON_MODE_TOP) {
- minsize.x=MAX(minsize.x,s.width);
- if (max_text_lines>0) {
- minsize.y+=(font_height+line_separation)*max_text_lines;
+ if (icon_mode == ICON_MODE_TOP) {
+ minsize.x = MAX(minsize.x, s.width);
+ if (max_text_lines > 0) {
+ minsize.y += (font_height + line_separation) * max_text_lines;
} else {
- minsize.y+=s.height;
+ minsize.y += s.height;
}
} else {
- minsize.y=MAX(minsize.y,s.height);
- minsize.x+=s.width;
+ minsize.y = MAX(minsize.y, s.height);
+ minsize.x += s.width;
}
}
-
- if (fixed_column_width>0)
- minsize.x=fixed_column_width;
- max_column_width=MAX(max_column_width,minsize.x);
- items[i].rect_cache.size=minsize;
- items[i].min_rect_cache.size=minsize;
-
+ if (fixed_column_width > 0)
+ minsize.x = fixed_column_width;
+ max_column_width = MAX(max_column_width, minsize.x);
+ items[i].rect_cache.size = minsize;
+ items[i].min_rect_cache.size = minsize;
}
int fit_size = size.x - bg->get_minimum_size().width - mw;
//2-attempt best fit
current_columns = 0x7FFFFFFF;
- if (max_columns>0)
- current_columns=max_columns;
+ if (max_columns > 0)
+ current_columns = max_columns;
-
- while(true) {
+ while (true) {
//repeat util all fits
//print_line("try with "+itos(current_columns));
- bool all_fit=true;
+ bool all_fit = true;
Vector2 ofs;
- int col=0;
- int max_h=0;
+ int col = 0;
+ int max_h = 0;
separators.clear();
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
- if (current_columns>1 && items[i].rect_cache.size.width+ofs.x > fit_size) {
+ if (current_columns > 1 && items[i].rect_cache.size.width + ofs.x > fit_size) {
//went past
- current_columns=MAX(col,1);
- all_fit=false;
+ current_columns = MAX(col, 1);
+ all_fit = false;
break;
}
- items[i].rect_cache=items[i].min_rect_cache;
- if(same_column_width)
- items[i].rect_cache.size.x=max_column_width;
- items[i].rect_cache.pos=ofs;
- max_h=MAX(max_h,items[i].rect_cache.size.y);
- ofs.x+=items[i].rect_cache.size.x + hseparation;
+ items[i].rect_cache = items[i].min_rect_cache;
+ if (same_column_width)
+ items[i].rect_cache.size.x = max_column_width;
+ items[i].rect_cache.pos = ofs;
+ max_h = MAX(max_h, items[i].rect_cache.size.y);
+ ofs.x += items[i].rect_cache.size.x + hseparation;
//print_line("item "+itos(i)+" ofs "+rtos(items[i].rect_cache.size.x));
col++;
- if (col==current_columns) {
+ if (col == current_columns) {
- if (i<items.size()-1)
- separators.push_back(ofs.y+max_h+vseparation/2);
+ if (i < items.size() - 1)
+ separators.push_back(ofs.y + max_h + vseparation / 2);
- for(int j=i;j>=0 && col>0;j--, col--) {
+ for (int j = i; j >= 0 && col > 0; j--, col--) {
items[j].rect_cache.size.y = max_h;
}
- ofs.x=0;
- ofs.y+=max_h+vseparation;
- col=0;
- max_h=0;
+ ofs.x = 0;
+ ofs.y += max_h + vseparation;
+ col = 0;
+ max_h = 0;
}
}
- for(int j=items.size()-1;j>=0 && col>0;j--, col--) {
+ for (int j = items.size() - 1; j >= 0 && col > 0; j--, col--) {
items[j].rect_cache.size.y = max_h;
}
if (all_fit) {
- float max = MAX(page,ofs.y+max_h);
+ float max = MAX(page, ofs.y + max_h);
scroll_bar->set_max(max);
//print_line("max: "+rtos(max)+" page "+rtos(page));
- if (max<=page) {
+ if (max <= page) {
scroll_bar->set_value(0);
scroll_bar->hide();
} else {
@@ -957,12 +892,11 @@ void ItemList::_notification(int p_what) {
}
}
-
- shape_changed=false;
+ shape_changed = false;
}
//ensure_selected_visible needs to be checked before we draw the list.
- if (ensure_selected_visible && current>=0 && current <=items.size()) {
+ if (ensure_selected_visible && current >= 0 && current <= items.size()) {
Rect2 r = items[current].rect_cache;
int from = scroll_bar->get_value();
@@ -970,200 +904,188 @@ void ItemList::_notification(int p_what) {
if (r.pos.y < from) {
scroll_bar->set_value(r.pos.y);
- } else if (r.pos.y+r.size.y > to) {
- scroll_bar->set_value(r.pos.y+r.size.y - (to-from));
+ } else if (r.pos.y + r.size.y > to) {
+ scroll_bar->set_value(r.pos.y + r.size.y - (to - from));
}
-
-
}
- ensure_selected_visible=false;
+ ensure_selected_visible = false;
Vector2 base_ofs = bg->get_offset();
- base_ofs.y-=int(scroll_bar->get_value());
-
- Rect2 clip(Point2(),size-bg->get_minimum_size()+Vector2(0,scroll_bar->get_value()));
+ base_ofs.y -= int(scroll_bar->get_value());
- for(int i=0;i<items.size();i++) {
+ Rect2 clip(Point2(), size - bg->get_minimum_size() + Vector2(0, scroll_bar->get_value()));
+ for (int i = 0; i < items.size(); i++) {
Rect2 rcache = items[i].rect_cache;
if (!clip.intersects(rcache))
continue;
-
- if (current_columns==1) {
- rcache.size.width = width-rcache.pos.x;
+ if (current_columns == 1) {
+ rcache.size.width = width - rcache.pos.x;
}
- Rect2 r=rcache;
- r.pos+=base_ofs;
+ Rect2 r = rcache;
+ r.pos += base_ofs;
// Use stylebox to dimension potential bg color, even if not selected
- r.pos.x-=sbsel->get_margin(MARGIN_LEFT);
- r.size.x+=sbsel->get_margin(MARGIN_LEFT)+sbsel->get_margin(MARGIN_RIGHT);
- r.pos.y-=sbsel->get_margin(MARGIN_TOP);
- r.size.y+=sbsel->get_margin(MARGIN_TOP)+sbsel->get_margin(MARGIN_BOTTOM);
+ r.pos.x -= sbsel->get_margin(MARGIN_LEFT);
+ r.size.x += sbsel->get_margin(MARGIN_LEFT) + sbsel->get_margin(MARGIN_RIGHT);
+ r.pos.y -= sbsel->get_margin(MARGIN_TOP);
+ r.size.y += sbsel->get_margin(MARGIN_TOP) + sbsel->get_margin(MARGIN_BOTTOM);
if (items[i].selected) {
- draw_style_box(sbsel,r);
+ draw_style_box(sbsel, r);
}
- if (items[i].custom_bg.a>0.001) {
- r.pos.x+=2;
- r.size.x-=4;
- r.pos.y+=2;
- r.size.y-=4;
- draw_rect(r,items[i].custom_bg);
+ if (items[i].custom_bg.a > 0.001) {
+ r.pos.x += 2;
+ r.size.x -= 4;
+ r.pos.y += 2;
+ r.size.y -= 4;
+ draw_rect(r, items[i].custom_bg);
}
-
Vector2 text_ofs;
if (items[i].icon.is_valid()) {
Size2 icon_size;
//= _adjust_to_max_size(items[i].get_icon_size(),fixed_icon_size) * icon_scale;
- if (fixed_icon_size.x>0 && fixed_icon_size.y>0) {
- icon_size=fixed_icon_size* icon_scale;
+ if (fixed_icon_size.x > 0 && fixed_icon_size.y > 0) {
+ icon_size = fixed_icon_size * icon_scale;
} else {
- icon_size=items[i].get_icon_size() *icon_scale;
-
+ icon_size = items[i].get_icon_size() * icon_scale;
}
Vector2 icon_ofs;
Point2 pos = items[i].rect_cache.pos + icon_ofs + base_ofs;
- if (icon_mode==ICON_MODE_TOP) {
+ if (icon_mode == ICON_MODE_TOP) {
- pos.x += Math::floor((items[i].rect_cache.size.width - icon_size.width)/2);
+ pos.x += Math::floor((items[i].rect_cache.size.width - icon_size.width) / 2);
pos.y += MIN(
- Math::floor((items[i].rect_cache.size.height - icon_size.height)/2),
- items[i].rect_cache.size.height - items[i].min_rect_cache.size.height
- );
+ Math::floor((items[i].rect_cache.size.height - icon_size.height) / 2),
+ items[i].rect_cache.size.height - items[i].min_rect_cache.size.height);
text_ofs.y = icon_size.height + icon_margin;
text_ofs.y += items[i].rect_cache.size.height - items[i].min_rect_cache.size.height;
} else {
- pos.y += Math::floor((items[i].rect_cache.size.height - icon_size.height)/2);
+ pos.y += Math::floor((items[i].rect_cache.size.height - icon_size.height) / 2);
text_ofs.x = icon_size.width + icon_margin;
}
- Rect2 draw_rect=Rect2(pos,icon_size);
+ Rect2 draw_rect = Rect2(pos, icon_size);
- if (fixed_icon_size.x>0 && fixed_icon_size.y>0) {
- Rect2 adj = _adjust_to_max_size(items[i].get_icon_size() * icon_scale,icon_size);
- draw_rect.pos+=adj.pos;
- draw_rect.size=adj.size;
+ if (fixed_icon_size.x > 0 && fixed_icon_size.y > 0) {
+ Rect2 adj = _adjust_to_max_size(items[i].get_icon_size() * icon_scale, icon_size);
+ draw_rect.pos += adj.pos;
+ draw_rect.size = adj.size;
}
- Color modulate=Color(1,1,1,1);
+ Color modulate = Color(1, 1, 1, 1);
if (items[i].disabled)
- modulate.a*=0.5;
+ modulate.a *= 0.5;
if (items[i].icon_region.has_no_area())
- draw_texture_rect(items[i].icon, draw_rect,false,modulate );
+ draw_texture_rect(items[i].icon, draw_rect, false, modulate);
else
- draw_texture_rect_region(items[i].icon, draw_rect, items[i].icon_region,modulate);
-
+ draw_texture_rect_region(items[i].icon, draw_rect, items[i].icon_region, modulate);
}
if (items[i].tag_icon.is_valid()) {
- draw_texture(items[i].tag_icon,items[i].rect_cache.pos+base_ofs);
+ draw_texture(items[i].tag_icon, items[i].rect_cache.pos + base_ofs);
}
- if (items[i].text!="") {
+ if (items[i].text != "") {
- int max_len=-1;
+ int max_len = -1;
Vector2 size = font->get_string_size(items[i].text);
if (fixed_column_width)
- max_len=fixed_column_width;
- else if(same_column_width)
- max_len=items[i].rect_cache.size.x;
+ max_len = fixed_column_width;
+ else if (same_column_width)
+ max_len = items[i].rect_cache.size.x;
else
- max_len=size.x;
+ max_len = size.x;
- Color modulate=items[i].selected?font_color_selected:font_color;
+ Color modulate = items[i].selected ? font_color_selected : font_color;
if (items[i].disabled)
- modulate.a*=0.5;
+ modulate.a *= 0.5;
- if (icon_mode==ICON_MODE_TOP && max_text_lines>0) {
+ if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
int ss = items[i].text.length();
- float ofs=0;
- int line=0;
- for(int j=0;j<=ss;j++) {
-
- int cs = j<ss?font->get_char_size(items[i].text[j],items[i].text[j+1]).x:0;
- if (ofs+cs>max_len || j==ss) {
- line_limit_cache[line]=j;
- line_size_cache[line]=ofs;
+ float ofs = 0;
+ int line = 0;
+ for (int j = 0; j <= ss; j++) {
+
+ int cs = j < ss ? font->get_char_size(items[i].text[j], items[i].text[j + 1]).x : 0;
+ if (ofs + cs > max_len || j == ss) {
+ line_limit_cache[line] = j;
+ line_size_cache[line] = ofs;
line++;
- ofs=0;
- if (line>=max_text_lines)
+ ofs = 0;
+ if (line >= max_text_lines)
break;
} else {
- ofs+=cs;
+ ofs += cs;
}
-
}
- line=0;
- ofs=0;
+ line = 0;
+ ofs = 0;
- text_ofs.y+=font->get_ascent();
- text_ofs=text_ofs.floor();
- text_ofs+=base_ofs;
- text_ofs+=items[i].rect_cache.pos;
+ text_ofs.y += font->get_ascent();
+ text_ofs = text_ofs.floor();
+ text_ofs += base_ofs;
+ text_ofs += items[i].rect_cache.pos;
- for(int j=0;j<ss;j++) {
+ for (int j = 0; j < ss; j++) {
- if (j==line_limit_cache[line]) {
+ if (j == line_limit_cache[line]) {
line++;
- ofs=0;
- if (line>=max_text_lines)
+ ofs = 0;
+ if (line >= max_text_lines)
break;
}
- ofs+=font->draw_char(get_canvas_item(),text_ofs+Vector2(ofs+(max_len-line_size_cache[line])/2,line*(font_height+line_separation)).floor(),items[i].text[j],items[i].text[j+1],modulate);
+ ofs += font->draw_char(get_canvas_item(), text_ofs + Vector2(ofs + (max_len - line_size_cache[line]) / 2, line * (font_height + line_separation)).floor(), items[i].text[j], items[i].text[j + 1], modulate);
}
//special multiline mode
} else {
- if (fixed_column_width>0)
- size.x=MIN(size.x,fixed_column_width);
+ if (fixed_column_width > 0)
+ size.x = MIN(size.x, fixed_column_width);
- if (icon_mode==ICON_MODE_TOP) {
- text_ofs.x+=(items[i].rect_cache.size.width-size.x)/2;
+ if (icon_mode == ICON_MODE_TOP) {
+ text_ofs.x += (items[i].rect_cache.size.width - size.x) / 2;
} else {
- text_ofs.y+=(items[i].rect_cache.size.height-size.y)/2;
+ text_ofs.y += (items[i].rect_cache.size.height - size.y) / 2;
}
- text_ofs.y+=font->get_ascent();
- text_ofs=text_ofs.floor();
- text_ofs+=base_ofs;
- text_ofs+=items[i].rect_cache.pos;
+ text_ofs.y += font->get_ascent();
+ text_ofs = text_ofs.floor();
+ text_ofs += base_ofs;
+ text_ofs += items[i].rect_cache.pos;
- draw_string(font,text_ofs,items[i].text,modulate,max_len+1);
+ draw_string(font, text_ofs, items[i].text, modulate, max_len + 1);
}
-
-
}
- if (select_mode==SELECT_MULTI && i==current) {
-
- Rect2 r=rcache;
- r.pos+=base_ofs;
- draw_style_box(cursor,r);
+ if (select_mode == SELECT_MULTI && i == current) {
+ Rect2 r = rcache;
+ r.pos += base_ofs;
+ draw_style_box(cursor, r);
}
}
- for(int i=0;i<separators.size();i++) {
- draw_line(Vector2(bg->get_margin(MARGIN_LEFT),base_ofs.y+separators[i]),Vector2(size.width-bg->get_margin(MARGIN_LEFT),base_ofs.y+separators[i]),guide_color);
+ for (int i = 0; i < separators.size(); i++) {
+ draw_line(Vector2(bg->get_margin(MARGIN_LEFT), base_ofs.y + separators[i]), Vector2(size.width - bg->get_margin(MARGIN_LEFT), base_ofs.y + separators[i]), guide_color);
}
}
}
@@ -1172,66 +1094,64 @@ void ItemList::_scroll_changed(double) {
update();
}
-int ItemList::get_item_at_pos(const Point2& p_pos, bool p_exact) const {
+int ItemList::get_item_at_pos(const Point2 &p_pos, bool p_exact) const {
- Vector2 pos=p_pos;
+ Vector2 pos = p_pos;
Ref<StyleBox> bg = get_stylebox("bg");
- pos-=bg->get_offset();
- pos.y+=scroll_bar->get_value();
+ pos -= bg->get_offset();
+ pos.y += scroll_bar->get_value();
int closest = -1;
- int closest_dist=0x7FFFFFFF;
+ int closest_dist = 0x7FFFFFFF;
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
Rect2 rc = items[i].rect_cache;
- if (i%current_columns==current_columns-1) {
- rc.size.width=get_size().width; //not right but works
+ if (i % current_columns == current_columns - 1) {
+ rc.size.width = get_size().width; //not right but works
}
if (rc.has_point(pos)) {
- closest=i;
+ closest = i;
break;
}
float dist = rc.distance_to(pos);
- if (!p_exact && dist<closest_dist) {
- closest=i;
- closest_dist=dist;
+ if (!p_exact && dist < closest_dist) {
+ closest = i;
+ closest_dist = dist;
}
}
return closest;
}
-bool ItemList::is_pos_at_end_of_items(const Point2& p_pos) const {
+bool ItemList::is_pos_at_end_of_items(const Point2 &p_pos) const {
if (items.empty())
return true;
- Vector2 pos=p_pos;
+ Vector2 pos = p_pos;
Ref<StyleBox> bg = get_stylebox("bg");
- pos-=bg->get_offset();
- pos.y+=scroll_bar->get_value();
+ pos -= bg->get_offset();
+ pos.y += scroll_bar->get_value();
- Rect2 endrect = items[items.size()-1].rect_cache;
+ Rect2 endrect = items[items.size() - 1].rect_cache;
return (pos.y > endrect.pos.y + endrect.size.y);
-
}
-
-String ItemList::get_tooltip(const Point2& p_pos) const {
+String ItemList::get_tooltip(const Point2 &p_pos) const {
int closest = get_item_at_pos(p_pos);
- if (closest!=-1) {
+ if (closest != -1) {
if (!items[closest].tooltip_enabled) {
return "";
}
- if (items[closest].tooltip!="") {
+ if (items[closest].tooltip != "") {
return items[closest].tooltip;
}
- if (items[closest].text!="") {
+ if (items[closest].text != "") {
return items[closest].text;
}
}
@@ -1243,10 +1163,10 @@ void ItemList::sort_items_by_text() {
items.sort();
update();
- shape_changed=true;
+ shape_changed = true;
- if (select_mode==SELECT_SINGLE) {
- for(int i=0;i<items.size();i++) {
+ if (select_mode == SELECT_SINGLE) {
+ for (int i = 0; i < items.size(); i++) {
if (items[i].selected) {
select(i);
return;
@@ -1255,21 +1175,19 @@ void ItemList::sort_items_by_text() {
}
}
-int ItemList::find_metadata(const Variant& p_metadata) const {
+int ItemList::find_metadata(const Variant &p_metadata) const {
- for(int i=0;i<items.size();i++) {
- if (items[i].metadata==p_metadata) {
+ for (int i = 0; i < items.size(); i++) {
+ if (items[i].metadata == p_metadata) {
return i;
}
}
return -1;
-
}
-
void ItemList::set_allow_rmb_select(bool p_allow) {
- allow_rmb_select=p_allow;
+ allow_rmb_select = p_allow;
}
bool ItemList::get_allow_rmb_select() const {
@@ -1298,128 +1216,126 @@ Vector<int> ItemList::get_selected_items() {
return selected;
}
-void ItemList::_bind_methods(){
+void ItemList::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_item","text","icon:Texture","selectable"),&ItemList::add_item,DEFVAL(Variant()),DEFVAL(true));
- ClassDB::bind_method(D_METHOD("add_icon_item","icon:Texture","selectable"),&ItemList::add_icon_item,DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("add_item", "text", "icon:Texture", "selectable"), &ItemList::add_item, DEFVAL(Variant()), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("add_icon_item", "icon:Texture", "selectable"), &ItemList::add_icon_item, DEFVAL(true));
- ClassDB::bind_method(D_METHOD("set_item_text","idx","text"),&ItemList::set_item_text);
- ClassDB::bind_method(D_METHOD("get_item_text","idx"),&ItemList::get_item_text);
+ ClassDB::bind_method(D_METHOD("set_item_text", "idx", "text"), &ItemList::set_item_text);
+ ClassDB::bind_method(D_METHOD("get_item_text", "idx"), &ItemList::get_item_text);
- ClassDB::bind_method(D_METHOD("set_item_icon","idx","icon:Texture"),&ItemList::set_item_icon);
- ClassDB::bind_method(D_METHOD("get_item_icon:Texture","idx"),&ItemList::get_item_icon);
+ ClassDB::bind_method(D_METHOD("set_item_icon", "idx", "icon:Texture"), &ItemList::set_item_icon);
+ ClassDB::bind_method(D_METHOD("get_item_icon:Texture", "idx"), &ItemList::get_item_icon);
- ClassDB::bind_method(D_METHOD("set_item_icon_region","idx","rect"),&ItemList::set_item_icon_region);
- ClassDB::bind_method(D_METHOD("get_item_icon_region","idx"),&ItemList::get_item_icon_region);
+ ClassDB::bind_method(D_METHOD("set_item_icon_region", "idx", "rect"), &ItemList::set_item_icon_region);
+ ClassDB::bind_method(D_METHOD("get_item_icon_region", "idx"), &ItemList::get_item_icon_region);
- ClassDB::bind_method(D_METHOD("set_item_selectable","idx","selectable"),&ItemList::set_item_selectable);
- ClassDB::bind_method(D_METHOD("is_item_selectable","idx"),&ItemList::is_item_selectable);
+ ClassDB::bind_method(D_METHOD("set_item_selectable", "idx", "selectable"), &ItemList::set_item_selectable);
+ ClassDB::bind_method(D_METHOD("is_item_selectable", "idx"), &ItemList::is_item_selectable);
- ClassDB::bind_method(D_METHOD("set_item_disabled","idx","disabled"),&ItemList::set_item_disabled);
- ClassDB::bind_method(D_METHOD("is_item_disabled","idx"),&ItemList::is_item_disabled);
+ ClassDB::bind_method(D_METHOD("set_item_disabled", "idx", "disabled"), &ItemList::set_item_disabled);
+ ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &ItemList::is_item_disabled);
- ClassDB::bind_method(D_METHOD("set_item_metadata","idx","metadata"),&ItemList::set_item_metadata);
- ClassDB::bind_method(D_METHOD("get_item_metadata","idx"),&ItemList::get_item_metadata);
+ ClassDB::bind_method(D_METHOD("set_item_metadata", "idx", "metadata"), &ItemList::set_item_metadata);
+ ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &ItemList::get_item_metadata);
- ClassDB::bind_method(D_METHOD("set_item_custom_bg_color","idx","custom_bg_color"),&ItemList::set_item_custom_bg_color);
- ClassDB::bind_method(D_METHOD("get_item_custom_bg_color","idx"),&ItemList::get_item_custom_bg_color);
+ ClassDB::bind_method(D_METHOD("set_item_custom_bg_color", "idx", "custom_bg_color"), &ItemList::set_item_custom_bg_color);
+ ClassDB::bind_method(D_METHOD("get_item_custom_bg_color", "idx"), &ItemList::get_item_custom_bg_color);
- ClassDB::bind_method(D_METHOD("set_item_tooltip_enabled","idx","enable"),&ItemList::set_item_tooltip_enabled);
- ClassDB::bind_method(D_METHOD("is_item_tooltip_enabled","idx"),&ItemList::is_item_tooltip_enabled);
+ ClassDB::bind_method(D_METHOD("set_item_tooltip_enabled", "idx", "enable"), &ItemList::set_item_tooltip_enabled);
+ ClassDB::bind_method(D_METHOD("is_item_tooltip_enabled", "idx"), &ItemList::is_item_tooltip_enabled);
- ClassDB::bind_method(D_METHOD("set_item_tooltip","idx","tooltip"),&ItemList::set_item_tooltip);
- ClassDB::bind_method(D_METHOD("get_item_tooltip","idx"),&ItemList::get_item_tooltip);
+ ClassDB::bind_method(D_METHOD("set_item_tooltip", "idx", "tooltip"), &ItemList::set_item_tooltip);
+ ClassDB::bind_method(D_METHOD("get_item_tooltip", "idx"), &ItemList::get_item_tooltip);
- ClassDB::bind_method(D_METHOD("select","idx","single"),&ItemList::select,DEFVAL(true));
- ClassDB::bind_method(D_METHOD("unselect","idx"),&ItemList::unselect);
- ClassDB::bind_method(D_METHOD("is_selected","idx"),&ItemList::is_selected);
- ClassDB::bind_method(D_METHOD("get_selected_items"),&ItemList::get_selected_items);
+ ClassDB::bind_method(D_METHOD("select", "idx", "single"), &ItemList::select, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("unselect", "idx"), &ItemList::unselect);
+ ClassDB::bind_method(D_METHOD("is_selected", "idx"), &ItemList::is_selected);
+ ClassDB::bind_method(D_METHOD("get_selected_items"), &ItemList::get_selected_items);
- ClassDB::bind_method(D_METHOD("get_item_count"),&ItemList::get_item_count);
- ClassDB::bind_method(D_METHOD("remove_item","idx"),&ItemList::remove_item);
+ ClassDB::bind_method(D_METHOD("get_item_count"), &ItemList::get_item_count);
+ ClassDB::bind_method(D_METHOD("remove_item", "idx"), &ItemList::remove_item);
- ClassDB::bind_method(D_METHOD("clear"),&ItemList::clear);
- ClassDB::bind_method(D_METHOD("sort_items_by_text"),&ItemList::sort_items_by_text);
+ ClassDB::bind_method(D_METHOD("clear"), &ItemList::clear);
+ ClassDB::bind_method(D_METHOD("sort_items_by_text"), &ItemList::sort_items_by_text);
- ClassDB::bind_method(D_METHOD("set_fixed_column_width","width"),&ItemList::set_fixed_column_width);
- ClassDB::bind_method(D_METHOD("get_fixed_column_width"),&ItemList::get_fixed_column_width);
+ ClassDB::bind_method(D_METHOD("set_fixed_column_width", "width"), &ItemList::set_fixed_column_width);
+ ClassDB::bind_method(D_METHOD("get_fixed_column_width"), &ItemList::get_fixed_column_width);
- ClassDB::bind_method(D_METHOD("set_same_column_width","enable"),&ItemList::set_same_column_width);
- ClassDB::bind_method(D_METHOD("is_same_column_width"),&ItemList::is_same_column_width);
+ ClassDB::bind_method(D_METHOD("set_same_column_width", "enable"), &ItemList::set_same_column_width);
+ ClassDB::bind_method(D_METHOD("is_same_column_width"), &ItemList::is_same_column_width);
- ClassDB::bind_method(D_METHOD("set_max_text_lines","lines"),&ItemList::set_max_text_lines);
- ClassDB::bind_method(D_METHOD("get_max_text_lines"),&ItemList::get_max_text_lines);
+ ClassDB::bind_method(D_METHOD("set_max_text_lines", "lines"), &ItemList::set_max_text_lines);
+ ClassDB::bind_method(D_METHOD("get_max_text_lines"), &ItemList::get_max_text_lines);
- ClassDB::bind_method(D_METHOD("set_max_columns","amount"),&ItemList::set_max_columns);
- ClassDB::bind_method(D_METHOD("get_max_columns"),&ItemList::get_max_columns);
+ ClassDB::bind_method(D_METHOD("set_max_columns", "amount"), &ItemList::set_max_columns);
+ ClassDB::bind_method(D_METHOD("get_max_columns"), &ItemList::get_max_columns);
- ClassDB::bind_method(D_METHOD("set_select_mode","mode"),&ItemList::set_select_mode);
- ClassDB::bind_method(D_METHOD("get_select_mode"),&ItemList::get_select_mode);
+ ClassDB::bind_method(D_METHOD("set_select_mode", "mode"), &ItemList::set_select_mode);
+ ClassDB::bind_method(D_METHOD("get_select_mode"), &ItemList::get_select_mode);
- ClassDB::bind_method(D_METHOD("set_icon_mode","mode"),&ItemList::set_icon_mode);
- ClassDB::bind_method(D_METHOD("get_icon_mode"),&ItemList::get_icon_mode);
+ ClassDB::bind_method(D_METHOD("set_icon_mode", "mode"), &ItemList::set_icon_mode);
+ ClassDB::bind_method(D_METHOD("get_icon_mode"), &ItemList::get_icon_mode);
+ ClassDB::bind_method(D_METHOD("set_fixed_icon_size", "size"), &ItemList::set_fixed_icon_size);
+ ClassDB::bind_method(D_METHOD("get_fixed_icon_size"), &ItemList::get_fixed_icon_size);
- ClassDB::bind_method(D_METHOD("set_fixed_icon_size","size"),&ItemList::set_fixed_icon_size);
- ClassDB::bind_method(D_METHOD("get_fixed_icon_size"),&ItemList::get_fixed_icon_size);
+ ClassDB::bind_method(D_METHOD("set_icon_scale", "scale"), &ItemList::set_icon_scale);
+ ClassDB::bind_method(D_METHOD("get_icon_scale"), &ItemList::get_icon_scale);
- ClassDB::bind_method(D_METHOD("set_icon_scale","scale"),&ItemList::set_icon_scale);
- ClassDB::bind_method(D_METHOD("get_icon_scale"),&ItemList::get_icon_scale);
+ ClassDB::bind_method(D_METHOD("set_allow_rmb_select", "allow"), &ItemList::set_allow_rmb_select);
+ ClassDB::bind_method(D_METHOD("get_allow_rmb_select"), &ItemList::get_allow_rmb_select);
- ClassDB::bind_method(D_METHOD("set_allow_rmb_select","allow"),&ItemList::set_allow_rmb_select);
- ClassDB::bind_method(D_METHOD("get_allow_rmb_select"),&ItemList::get_allow_rmb_select);
+ ClassDB::bind_method(D_METHOD("get_item_at_pos", "pos", "exact"), &ItemList::get_item_at_pos, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_item_at_pos","pos","exact"),&ItemList::get_item_at_pos,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("ensure_current_is_visible"), &ItemList::ensure_current_is_visible);
- ClassDB::bind_method(D_METHOD("ensure_current_is_visible"),&ItemList::ensure_current_is_visible);
+ ClassDB::bind_method(D_METHOD("get_v_scroll"), &ItemList::get_v_scroll);
- ClassDB::bind_method(D_METHOD("get_v_scroll"),&ItemList::get_v_scroll);
+ ClassDB::bind_method(D_METHOD("_scroll_changed"), &ItemList::_scroll_changed);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ItemList::_gui_input);
- ClassDB::bind_method(D_METHOD("_scroll_changed"),&ItemList::_scroll_changed);
- ClassDB::bind_method(D_METHOD("_gui_input"),&ItemList::_gui_input);
+ BIND_CONSTANT(ICON_MODE_TOP);
+ BIND_CONSTANT(ICON_MODE_LEFT);
+ BIND_CONSTANT(SELECT_SINGLE);
+ BIND_CONSTANT(SELECT_MULTI);
- BIND_CONSTANT( ICON_MODE_TOP );
- BIND_CONSTANT( ICON_MODE_LEFT );
- BIND_CONSTANT( SELECT_SINGLE );
- BIND_CONSTANT( SELECT_MULTI );
+ ADD_SIGNAL(MethodInfo("item_selected", PropertyInfo(Variant::INT, "index")));
+ ADD_SIGNAL(MethodInfo("item_rmb_selected", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::VECTOR2, "atpos")));
+ ADD_SIGNAL(MethodInfo("multi_selected", PropertyInfo(Variant::INT, "index"), PropertyInfo(Variant::BOOL, "selected")));
+ ADD_SIGNAL(MethodInfo("item_activated", PropertyInfo(Variant::INT, "index")));
- ADD_SIGNAL( MethodInfo("item_selected",PropertyInfo(Variant::INT,"index")));
- ADD_SIGNAL( MethodInfo("item_rmb_selected",PropertyInfo(Variant::INT,"index"),PropertyInfo(Variant::VECTOR2,"atpos")));
- ADD_SIGNAL( MethodInfo("multi_selected",PropertyInfo(Variant::INT,"index"),PropertyInfo(Variant::BOOL,"selected")));
- ADD_SIGNAL( MethodInfo("item_activated",PropertyInfo(Variant::INT,"index")));
-
- GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec",2000);
+ GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000);
}
ItemList::ItemList() {
- current=-1;
+ current = -1;
- select_mode=SELECT_SINGLE;
- icon_mode=ICON_MODE_LEFT;
+ select_mode = SELECT_SINGLE;
+ icon_mode = ICON_MODE_LEFT;
- fixed_column_width=0;
+ fixed_column_width = 0;
same_column_width = false;
- max_text_lines=1;
- max_columns=1;
+ max_text_lines = 1;
+ max_columns = 1;
- scroll_bar = memnew( VScrollBar );
+ scroll_bar = memnew(VScrollBar);
add_child(scroll_bar);
- shape_changed=true;
- scroll_bar->connect("value_changed",this,"_scroll_changed");
+ shape_changed = true;
+ scroll_bar->connect("value_changed", this, "_scroll_changed");
set_focus_mode(FOCUS_ALL);
- current_columns=1;
- search_time_msec=0;
- ensure_selected_visible=false;
- defer_select_single=-1;
- allow_rmb_select=false;
+ current_columns = 1;
+ search_time_msec = 0;
+ ensure_selected_visible = false;
+ defer_select_single = -1;
+ allow_rmb_select = false;
icon_scale = 1.0f;
set_clip_contents(true);
}
ItemList::~ItemList() {
-
}
diff --git a/scene/gui/item_list.h b/scene/gui/item_list.h
index 35ffb1be9c..5de58cfde8 100644
--- a/scene/gui/item_list.h
+++ b/scene/gui/item_list.h
@@ -34,9 +34,9 @@
class ItemList : public Control {
- GDCLASS( ItemList, Control );
-public:
+ GDCLASS(ItemList, Control);
+public:
enum IconMode {
ICON_MODE_TOP,
ICON_MODE_LEFT
@@ -46,6 +46,7 @@ public:
SELECT_SINGLE,
SELECT_MULTI
};
+
private:
struct Item {
@@ -66,7 +67,7 @@ private:
Size2 get_icon_size() const;
- bool operator<(const Item& p_another) const { return text<p_another.text; }
+ bool operator<(const Item &p_another) const { return text < p_another.text; }
};
int current;
@@ -102,50 +103,47 @@ private:
real_t icon_scale;
void _scroll_changed(double);
- void _gui_input(const InputEvent& p_event);
-
+ void _gui_input(const InputEvent &p_event);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
-
- void add_item(const String& p_item,const Ref<Texture>& p_texture=Ref<Texture>(),bool p_selectable=true);
- void add_icon_item(const Ref<Texture>& p_item,bool p_selectable=true);
+public:
+ void add_item(const String &p_item, const Ref<Texture> &p_texture = Ref<Texture>(), bool p_selectable = true);
+ void add_icon_item(const Ref<Texture> &p_item, bool p_selectable = true);
- void set_item_text(int p_idx,const String& p_text);
+ void set_item_text(int p_idx, const String &p_text);
String get_item_text(int p_idx) const;
- void set_item_icon(int p_idx,const Ref<Texture>& p_icon);
+ void set_item_icon(int p_idx, const Ref<Texture> &p_icon);
Ref<Texture> get_item_icon(int p_idx) const;
- void set_item_icon_region(int p_idx,const Rect2& p_region);
+ void set_item_icon_region(int p_idx, const Rect2 &p_region);
Rect2 get_item_icon_region(int p_idx) const;
- void set_item_selectable(int p_idx,bool p_selectable);
+ void set_item_selectable(int p_idx, bool p_selectable);
bool is_item_selectable(int p_idx) const;
- void set_item_disabled(int p_idx,bool p_disabled);
+ void set_item_disabled(int p_idx, bool p_disabled);
bool is_item_disabled(int p_idx) const;
- void set_item_metadata(int p_idx,const Variant& p_metadata);
+ void set_item_metadata(int p_idx, const Variant &p_metadata);
Variant get_item_metadata(int p_idx) const;
- void set_item_tag_icon(int p_idx,const Ref<Texture>& p_tag_icon);
+ void set_item_tag_icon(int p_idx, const Ref<Texture> &p_tag_icon);
Ref<Texture> get_item_tag_icon(int p_idx) const;
void set_item_tooltip_enabled(int p_idx, const bool p_enabled);
bool is_item_tooltip_enabled(int p_idx) const;
- void set_item_tooltip(int p_idx,const String& p_tooltip);
+ void set_item_tooltip(int p_idx, const String &p_tooltip);
String get_item_tooltip(int p_idx) const;
- void set_item_custom_bg_color(int p_idx,const Color& p_custom_bg_color);
+ void set_item_custom_bg_color(int p_idx, const Color &p_custom_bg_color);
Color get_item_custom_bg_color(int p_idx) const;
- void select(int p_idx,bool p_single=true);
+ void select(int p_idx, bool p_single = true);
void unselect(int p_idx);
bool is_selected(int p_idx) const;
Vector<int> get_selected_items();
@@ -153,7 +151,7 @@ public:
void set_current(int p_current);
int get_current() const;
- void move_item(int p_item,int p_to_pos);
+ void move_item(int p_item, int p_to_pos);
int get_item_count() const;
void remove_item(int p_idx);
@@ -178,7 +176,7 @@ public:
void set_icon_mode(IconMode p_mode);
IconMode get_icon_mode() const;
- void set_fixed_icon_size(const Size2& p_size);
+ void set_fixed_icon_size(const Size2 &p_size);
Size2 get_fixed_icon_size() const;
void set_allow_rmb_select(bool p_allow);
@@ -187,11 +185,11 @@ public:
void ensure_current_is_visible();
void sort_items_by_text();
- int find_metadata(const Variant& p_metadata) const;
+ int find_metadata(const Variant &p_metadata) const;
- virtual String get_tooltip(const Point2& p_pos) const;
- int get_item_at_pos(const Point2& p_pos,bool p_exact=false) const;
- bool is_pos_at_end_of_items(const Point2& p_pos) const;
+ virtual String get_tooltip(const Point2 &p_pos) const;
+ int get_item_at_pos(const Point2 &p_pos, bool p_exact = false) const;
+ bool is_pos_at_end_of_items(const Point2 &p_pos) const;
void set_icon_scale(real_t p_scale);
real_t get_icon_scale() const;
@@ -205,5 +203,4 @@ public:
VARIANT_ENUM_CAST(ItemList::SelectMode);
VARIANT_ENUM_CAST(ItemList::IconMode);
-
#endif // ITEMLIST_H
diff --git a/scene/gui/label.cpp b/scene/gui/label.cpp
index 915eaa2f45..0dec69d9b3 100644
--- a/scene/gui/label.cpp
+++ b/scene/gui/label.cpp
@@ -27,29 +27,26 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "label.h"
-#include "print_string.h"
#include "global_config.h"
+#include "print_string.h"
#include "translation.h"
-
void Label::set_autowrap(bool p_autowrap) {
- autowrap=p_autowrap;
- word_cache_dirty=true;
+ autowrap = p_autowrap;
+ word_cache_dirty = true;
minimum_size_changed();
update();
-
}
bool Label::has_autowrap() const {
return autowrap;
}
-
void Label::set_uppercase(bool p_uppercase) {
- uppercase=p_uppercase;
- word_cache_dirty=true;
+ uppercase = p_uppercase;
+ word_cache_dirty = true;
minimum_size_changed();
update();
}
@@ -58,264 +55,247 @@ bool Label::is_uppercase() const {
return uppercase;
}
-
int Label::get_line_height() const {
return get_font("font")->get_height();
-
}
-
void Label::_notification(int p_what) {
- if (p_what==NOTIFICATION_TRANSLATION_CHANGED) {
+ if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
- xl_text=XL_MESSAGE(text);
+ xl_text = XL_MESSAGE(text);
minimum_size_changed();
update();
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (clip || autowrap) {
- VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(),true);
+ VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(), true);
}
if (word_cache_dirty)
regenerate_word_cache();
-
RID ci = get_canvas_item();
Size2 string_size;
- Size2 size=get_size();
+ Size2 size = get_size();
Ref<Font> font = get_font("font");
Color font_color = get_color("font_color");
Color font_color_shadow = get_color("font_color_shadow");
bool use_outline = get_constant("shadow_as_outline");
- Point2 shadow_ofs(get_constant("shadow_offset_x"),get_constant("shadow_offset_y"));
+ Point2 shadow_ofs(get_constant("shadow_offset_x"), get_constant("shadow_offset_y"));
int line_spacing = get_constant("line_spacing");
- VisualServer::get_singleton()->canvas_item_set_distance_field_mode(get_canvas_item(),font.is_valid() && font->is_distance_field_hint());
+ VisualServer::get_singleton()->canvas_item_set_distance_field_mode(get_canvas_item(), font.is_valid() && font->is_distance_field_hint());
- int font_h = font->get_height()+line_spacing;
+ int font_h = font->get_height() + line_spacing;
- int lines_visible = (size.y+line_spacing)/font_h;
+ int lines_visible = (size.y + line_spacing) / font_h;
- int space_w=font->get_char_size(' ').width;
- int chars_total=0;
+ int space_w = font->get_char_size(' ').width;
+ int chars_total = 0;
- int vbegin=0,vsep=0;
+ int vbegin = 0, vsep = 0;
if (lines_visible > line_count) {
lines_visible = line_count;
-
}
if (max_lines_visible >= 0 && lines_visible > max_lines_visible) {
lines_visible = max_lines_visible;
-
}
if (lines_visible > 0) {
- switch(valign) {
+ switch (valign) {
case VALIGN_TOP: {
//nothing
} break;
case VALIGN_CENTER: {
- vbegin=(size.y - (lines_visible * font_h - line_spacing)) / 2;
- vsep=0;
+ vbegin = (size.y - (lines_visible * font_h - line_spacing)) / 2;
+ vsep = 0;
} break;
case VALIGN_BOTTOM: {
- vbegin=size.y - (lines_visible * font_h - line_spacing);
- vsep=0;
+ vbegin = size.y - (lines_visible * font_h - line_spacing);
+ vsep = 0;
} break;
case VALIGN_FILL: {
- vbegin=0;
- if (lines_visible>1) {
- vsep=(size.y - (lines_visible * font_h - line_spacing)) / (lines_visible - 1);
+ vbegin = 0;
+ if (lines_visible > 1) {
+ vsep = (size.y - (lines_visible * font_h - line_spacing)) / (lines_visible - 1);
} else {
- vsep=0;
+ vsep = 0;
}
} break;
}
}
-
WordCache *wc = word_cache;
if (!wc)
return;
- int line=0;
- int line_to=lines_skipped + (lines_visible>0?lines_visible:1);
- while(wc) {
- /* handle lines not meant to be drawn quickly */
- if (line>=line_to)
+ int line = 0;
+ int line_to = lines_skipped + (lines_visible > 0 ? lines_visible : 1);
+ while (wc) {
+ /* handle lines not meant to be drawn quickly */
+ if (line >= line_to)
break;
- if (line<lines_skipped) {
+ if (line < lines_skipped) {
- while (wc && wc->char_pos>=0)
- wc=wc->next;
+ while (wc && wc->char_pos >= 0)
+ wc = wc->next;
if (wc)
- wc=wc->next;
+ wc = wc->next;
line++;
continue;
}
- /* handle lines normally */
+ /* handle lines normally */
- if (wc->char_pos<0) {
- //empty line
- wc=wc->next;
+ if (wc->char_pos < 0) {
+ //empty line
+ wc = wc->next;
line++;
continue;
}
- WordCache *from=wc;
- WordCache *to=wc;
+ WordCache *from = wc;
+ WordCache *to = wc;
- int taken=0;
- int spaces=0;
- while(to && to->char_pos>=0) {
+ int taken = 0;
+ int spaces = 0;
+ while (to && to->char_pos >= 0) {
- taken+=to->pixel_width;
- if (to!=from && to->space_count) {
- spaces+=to->space_count;
+ taken += to->pixel_width;
+ if (to != from && to->space_count) {
+ spaces += to->space_count;
}
- to=to->next;
+ to = to->next;
}
- bool can_fill = to && to->char_pos==WordCache::CHAR_WRAPLINE;
+ bool can_fill = to && to->char_pos == WordCache::CHAR_WRAPLINE;
- float x_ofs=0;
+ float x_ofs = 0;
switch (align) {
case ALIGN_FILL:
case ALIGN_LEFT: {
- x_ofs=0;
+ x_ofs = 0;
} break;
case ALIGN_CENTER: {
- x_ofs=int(size.width-(taken+spaces*space_w))/2;
+ x_ofs = int(size.width - (taken + spaces * space_w)) / 2;
} break;
case ALIGN_RIGHT: {
-
- x_ofs=int(size.width-(taken+spaces*space_w));
+ x_ofs = int(size.width - (taken + spaces * space_w));
} break;
- }
+ }
- int y_ofs=(line-lines_skipped)*font_h + font->get_ascent();
- y_ofs+=vbegin + line*vsep;
+ int y_ofs = (line - lines_skipped) * font_h + font->get_ascent();
+ y_ofs += vbegin + line * vsep;
- while(from!=to) {
+ while (from != to) {
- // draw a word
+ // draw a word
int pos = from->char_pos;
- if (from->char_pos<0) {
+ if (from->char_pos < 0) {
ERR_PRINT("BUG");
return;
}
if (from->space_count) {
- /* spacing */
- x_ofs+=space_w*from->space_count;
- if (can_fill && align==ALIGN_FILL && spaces) {
+ /* spacing */
+ x_ofs += space_w * from->space_count;
+ if (can_fill && align == ALIGN_FILL && spaces) {
- x_ofs+=int((size.width-(taken+space_w*spaces))/spaces);
+ x_ofs += int((size.width - (taken + space_w * spaces)) / spaces);
}
-
-
}
-
-
- if (font_color_shadow.a>0) {
+ if (font_color_shadow.a > 0) {
int chars_total_shadow = chars_total; //save chars drawn
- float x_ofs_shadow=x_ofs;
- for (int i=0;i<from->word_len;i++) {
+ float x_ofs_shadow = x_ofs;
+ for (int i = 0; i < from->word_len; i++) {
- if (visible_chars < 0 || chars_total_shadow<visible_chars) {
- CharType c = xl_text[i+pos];
- CharType n = xl_text[i+pos+1];
+ if (visible_chars < 0 || chars_total_shadow < visible_chars) {
+ CharType c = xl_text[i + pos];
+ CharType n = xl_text[i + pos + 1];
if (uppercase) {
- c=String::char_uppercase(c);
- n=String::char_uppercase(c);
+ c = String::char_uppercase(c);
+ n = String::char_uppercase(c);
}
- float move=font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+shadow_ofs, c, n,font_color_shadow );
+ float move = font->draw_char(ci, Point2(x_ofs_shadow, y_ofs) + shadow_ofs, c, n, font_color_shadow);
if (use_outline) {
- font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(-shadow_ofs.x,shadow_ofs.y), c, n,font_color_shadow );
- font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(shadow_ofs.x,-shadow_ofs.y), c, n,font_color_shadow );
- font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(-shadow_ofs.x,-shadow_ofs.y), c, n,font_color_shadow );
+ font->draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, shadow_ofs.y), c, n, font_color_shadow);
+ font->draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow);
+ font->draw_char(ci, Point2(x_ofs_shadow, y_ofs) + Vector2(-shadow_ofs.x, -shadow_ofs.y), c, n, font_color_shadow);
}
- x_ofs_shadow+=move;
+ x_ofs_shadow += move;
chars_total_shadow++;
}
}
-
-
}
- for (int i=0;i<from->word_len;i++) {
+ for (int i = 0; i < from->word_len; i++) {
- if (visible_chars < 0 || chars_total<visible_chars) {
- CharType c = xl_text[i+pos];
- CharType n = xl_text[i+pos+1];
+ if (visible_chars < 0 || chars_total < visible_chars) {
+ CharType c = xl_text[i + pos];
+ CharType n = xl_text[i + pos + 1];
if (uppercase) {
- c=String::char_uppercase(c);
- n=String::char_uppercase(c);
+ c = String::char_uppercase(c);
+ n = String::char_uppercase(c);
}
- x_ofs+=font->draw_char(ci,Point2( x_ofs, y_ofs ), c, n, font_color );
+ x_ofs += font->draw_char(ci, Point2(x_ofs, y_ofs), c, n, font_color);
chars_total++;
}
-
}
- from=from->next;
+ from = from->next;
}
- wc=to?to->next:0;
+ wc = to ? to->next : 0;
line++;
-
}
}
- if (p_what==NOTIFICATION_THEME_CHANGED) {
+ if (p_what == NOTIFICATION_THEME_CHANGED) {
- word_cache_dirty=true;
+ word_cache_dirty = true;
update();
}
- if (p_what==NOTIFICATION_RESIZED) {
+ if (p_what == NOTIFICATION_RESIZED) {
- word_cache_dirty=true;
+ word_cache_dirty = true;
}
-
}
Size2 Label::get_minimum_size() const {
if (autowrap)
- return Size2(1,1);
+ return Size2(1, 1);
else {
// don't want to mutable everything
- if(word_cache_dirty)
- const_cast<Label*>(this)->regenerate_word_cache();
+ if (word_cache_dirty)
+ const_cast<Label *>(this)->regenerate_word_cache();
- Size2 ms=minsize;
+ Size2 ms = minsize;
if (clip)
- ms.width=1;
+ ms.width = 1;
return ms;
}
}
@@ -323,33 +303,32 @@ Size2 Label::get_minimum_size() const {
int Label::get_longest_line_width() const {
Ref<Font> font = get_font("font");
- int max_line_width=0;
- int line_width=0;
+ int max_line_width = 0;
+ int line_width = 0;
- for (int i=0;i<xl_text.size();i++) {
+ for (int i = 0; i < xl_text.size(); i++) {
- CharType current=xl_text[i];
+ CharType current = xl_text[i];
if (uppercase)
- current=String::char_uppercase(current);
+ current = String::char_uppercase(current);
- if (current<32) {
+ if (current < 32) {
- if (current=='\n') {
+ if (current == '\n') {
- if (line_width>max_line_width)
- max_line_width=line_width;
- line_width=0;
+ if (line_width > max_line_width)
+ max_line_width = line_width;
+ line_width = 0;
}
} else {
- int char_width=font->get_char_size(current,xl_text[i+1]).width;
- line_width+=char_width;
+ int char_width = font->get_char_size(current, xl_text[i + 1]).width;
+ line_width += char_width;
}
-
}
- if (line_width>max_line_width)
- max_line_width=line_width;
+ if (line_width > max_line_width)
+ max_line_width = line_width;
return max_line_width;
}
@@ -359,7 +338,7 @@ int Label::get_line_count() const {
if (!is_inside_tree())
return 1;
if (word_cache_dirty)
- const_cast<Label*>(this)->regenerate_word_cache();
+ const_cast<Label *>(this)->regenerate_word_cache();
return line_count;
}
@@ -367,8 +346,8 @@ int Label::get_line_count() const {
int Label::get_visible_line_count() const {
int line_spacing = get_constant("line_spacing");
- int font_h = get_font("font")->get_height()+line_spacing;
- int lines_visible = (get_size().y+line_spacing)/font_h;
+ int font_h = get_font("font")->get_height() + line_spacing;
+ int lines_visible = (get_size().y + line_spacing) / font_h;
if (lines_visible > line_count)
lines_visible = line_count;
@@ -383,189 +362,179 @@ void Label::regenerate_word_cache() {
while (word_cache) {
- WordCache *current=word_cache;
- word_cache=current->next;
- memdelete( current );
+ WordCache *current = word_cache;
+ word_cache = current->next;
+ memdelete(current);
}
-
- int width=autowrap?get_size().width:get_longest_line_width();
+ int width = autowrap ? get_size().width : get_longest_line_width();
Ref<Font> font = get_font("font");
- int current_word_size=0;
- int word_pos=0;
- int line_width=0;
- int space_count=0;
- int space_width=font->get_char_size(' ').width;
+ int current_word_size = 0;
+ int word_pos = 0;
+ int line_width = 0;
+ int space_count = 0;
+ int space_width = font->get_char_size(' ').width;
int line_spacing = get_constant("line_spacing");
- line_count=1;
- total_char_cache=0;
+ line_count = 1;
+ total_char_cache = 0;
- WordCache *last=NULL;
+ WordCache *last = NULL;
- for (int i=0;i<xl_text.size()+1;i++) {
+ for (int i = 0; i < xl_text.size() + 1; i++) {
- CharType current=i<xl_text.length()?xl_text[i]:' '; //always a space at the end, so the algo works
+ CharType current = i < xl_text.length() ? xl_text[i] : ' '; //always a space at the end, so the algo works
if (uppercase)
- current=String::char_uppercase(current);
+ current = String::char_uppercase(current);
// ranges taken from http://www.unicodemap.org/
// if your language is not well supported, consider helping improve
// the unicode support in Godot.
- bool separatable = (current>=0x2E08 && current<=0xFAFF) || (current>=0xFE30 && current<=0xFE4F);
- //current>=33 && (current < 65||current >90) && (current<97||current>122) && (current<48||current>57);
- bool insert_newline=false;
+ bool separatable = (current >= 0x2E08 && current <= 0xFAFF) || (current >= 0xFE30 && current <= 0xFE4F);
+ //current>=33 && (current < 65||current >90) && (current<97||current>122) && (current<48||current>57);
+ bool insert_newline = false;
int char_width;
- if (current<33) {
+ if (current < 33) {
- if (current_word_size>0) {
- WordCache *wc = memnew( WordCache );
+ if (current_word_size > 0) {
+ WordCache *wc = memnew(WordCache);
if (word_cache) {
- last->next=wc;
+ last->next = wc;
} else {
- word_cache=wc;
+ word_cache = wc;
}
- last=wc;
+ last = wc;
- wc->pixel_width=current_word_size;
- wc->char_pos=word_pos;
- wc->word_len=i-word_pos;
+ wc->pixel_width = current_word_size;
+ wc->char_pos = word_pos;
+ wc->word_len = i - word_pos;
wc->space_count = space_count;
- current_word_size=0;
- space_count=0;
-
+ current_word_size = 0;
+ space_count = 0;
}
-
- if (current=='\n') {
- insert_newline=true;
+ if (current == '\n') {
+ insert_newline = true;
} else {
total_char_cache++;
}
- if (i<xl_text.length() && xl_text[i] == ' ') {
- total_char_cache--; // do not count spaces
- if (line_width > 0 || last==NULL || last->char_pos!=WordCache::CHAR_WRAPLINE) {
+ if (i < xl_text.length() && xl_text[i] == ' ') {
+ total_char_cache--; // do not count spaces
+ if (line_width > 0 || last == NULL || last->char_pos != WordCache::CHAR_WRAPLINE) {
space_count++;
- line_width+=space_width;
- }else {
- space_count=0;
+ line_width += space_width;
+ } else {
+ space_count = 0;
}
}
-
} else {
// latin characters
- if (current_word_size==0) {
- word_pos=i;
+ if (current_word_size == 0) {
+ word_pos = i;
}
- char_width=font->get_char_size(current,xl_text[i+1]).width;
- current_word_size+=char_width;
- line_width+=char_width;
+ char_width = font->get_char_size(current, xl_text[i + 1]).width;
+ current_word_size += char_width;
+ line_width += char_width;
total_char_cache++;
-
}
if ((autowrap && (line_width >= width) && ((last && last->char_pos >= 0) || separatable)) || insert_newline) {
if (separatable) {
- if (current_word_size>0) {
- WordCache *wc = memnew( WordCache );
+ if (current_word_size > 0) {
+ WordCache *wc = memnew(WordCache);
if (word_cache) {
- last->next=wc;
+ last->next = wc;
} else {
- word_cache=wc;
+ word_cache = wc;
}
- last=wc;
+ last = wc;
- wc->pixel_width=current_word_size-char_width;
- wc->char_pos=word_pos;
- wc->word_len=i-word_pos;
+ wc->pixel_width = current_word_size - char_width;
+ wc->char_pos = word_pos;
+ wc->word_len = i - word_pos;
wc->space_count = space_count;
- current_word_size=char_width;
- space_count=0;
- word_pos=i;
+ current_word_size = char_width;
+ space_count = 0;
+ word_pos = i;
}
}
- WordCache *wc = memnew( WordCache );
+ WordCache *wc = memnew(WordCache);
if (word_cache) {
- last->next=wc;
+ last->next = wc;
} else {
- word_cache=wc;
+ word_cache = wc;
}
- last=wc;
+ last = wc;
- wc->pixel_width=0;
- wc->char_pos=insert_newline?WordCache::CHAR_NEWLINE:WordCache::CHAR_WRAPLINE;
+ wc->pixel_width = 0;
+ wc->char_pos = insert_newline ? WordCache::CHAR_NEWLINE : WordCache::CHAR_WRAPLINE;
- line_width=current_word_size;
+ line_width = current_word_size;
line_count++;
- space_count=0;
-
+ space_count = 0;
}
-
}
if (!autowrap) {
- minsize.width=width;
+ minsize.width = width;
if (max_lines_visible > 0 && line_count > max_lines_visible) {
- minsize.height=(font->get_height() * max_lines_visible) + (line_spacing * (max_lines_visible - 1));
+ minsize.height = (font->get_height() * max_lines_visible) + (line_spacing * (max_lines_visible - 1));
} else {
- minsize.height=(font->get_height() * line_count)+(line_spacing * (line_count - 1));
+ minsize.height = (font->get_height() * line_count) + (line_spacing * (line_count - 1));
}
}
- word_cache_dirty=false;
-
+ word_cache_dirty = false;
}
void Label::set_align(Align p_align) {
- ERR_FAIL_INDEX(p_align,4);
- align=p_align;
+ ERR_FAIL_INDEX(p_align, 4);
+ align = p_align;
update();
}
-Label::Align Label::get_align() const{
+Label::Align Label::get_align() const {
return align;
}
void Label::set_valign(VAlign p_align) {
- ERR_FAIL_INDEX(p_align,4);
- valign=p_align;
+ ERR_FAIL_INDEX(p_align, 4);
+ valign = p_align;
update();
}
-Label::VAlign Label::get_valign() const{
+Label::VAlign Label::get_valign() const {
return valign;
}
-void Label::set_text(const String& p_string) {
-
+void Label::set_text(const String &p_string) {
- if (text==p_string)
+ if (text == p_string)
return;
- text=p_string;
- xl_text=XL_MESSAGE(p_string);
- word_cache_dirty=true;
- if (percent_visible<1)
- visible_chars=get_total_character_count()*percent_visible;
+ text = p_string;
+ xl_text = XL_MESSAGE(p_string);
+ word_cache_dirty = true;
+ if (percent_visible < 1)
+ visible_chars = get_total_character_count() * percent_visible;
update();
if (!autowrap) {
minimum_size_changed();
}
-
}
void Label::set_clip_text(bool p_clip) {
- clip=p_clip;
+ clip = p_clip;
update();
minimum_size_changed();
}
@@ -582,9 +551,9 @@ String Label::get_text() const {
void Label::set_visible_characters(int p_amount) {
- visible_chars=p_amount;
+ visible_chars = p_amount;
if (get_total_character_count() > 0) {
- percent_visible=(float)p_amount/(float)total_char_cache;
+ percent_visible = (float)p_amount / (float)total_char_cache;
}
update();
}
@@ -596,44 +565,42 @@ int Label::get_visible_characters() const {
void Label::set_percent_visible(float p_percent) {
- if (p_percent<0 || p_percent>=1) {
+ if (p_percent < 0 || p_percent >= 1) {
- visible_chars=-1;
- percent_visible=1;
+ visible_chars = -1;
+ percent_visible = 1;
} else {
- visible_chars=get_total_character_count()*p_percent;
- percent_visible=p_percent;
-
+ visible_chars = get_total_character_count() * p_percent;
+ percent_visible = p_percent;
}
update();
-
}
-float Label::get_percent_visible() const{
+float Label::get_percent_visible() const {
return percent_visible;
}
void Label::set_lines_skipped(int p_lines) {
- lines_skipped=p_lines;
+ lines_skipped = p_lines;
update();
}
-int Label::get_lines_skipped() const{
+int Label::get_lines_skipped() const {
return lines_skipped;
}
void Label::set_max_lines_visible(int p_lines) {
- max_lines_visible=p_lines;
+ max_lines_visible = p_lines;
update();
}
-int Label::get_max_lines_visible() const{
+int Label::get_max_lines_visible() const {
return max_lines_visible;
}
@@ -641,90 +608,86 @@ int Label::get_max_lines_visible() const{
int Label::get_total_character_count() const {
if (word_cache_dirty)
- const_cast<Label*>(this)->regenerate_word_cache();
+ const_cast<Label *>(this)->regenerate_word_cache();
return total_char_cache;
}
void Label::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_align","align"),&Label::set_align);
- ClassDB::bind_method(D_METHOD("get_align"),&Label::get_align);
- ClassDB::bind_method(D_METHOD("set_valign","valign"),&Label::set_valign);
- ClassDB::bind_method(D_METHOD("get_valign"),&Label::get_valign);
- ClassDB::bind_method(D_METHOD("set_text","text"),&Label::set_text);
- ClassDB::bind_method(D_METHOD("get_text"),&Label::get_text);
- ClassDB::bind_method(D_METHOD("set_autowrap","enable"),&Label::set_autowrap);
- ClassDB::bind_method(D_METHOD("has_autowrap"),&Label::has_autowrap);
- ClassDB::bind_method(D_METHOD("set_clip_text","enable"),&Label::set_clip_text);
- ClassDB::bind_method(D_METHOD("is_clipping_text"),&Label::is_clipping_text);
- ClassDB::bind_method(D_METHOD("set_uppercase","enable"),&Label::set_uppercase);
- ClassDB::bind_method(D_METHOD("is_uppercase"),&Label::is_uppercase);
- ClassDB::bind_method(D_METHOD("get_line_height"),&Label::get_line_height);
- ClassDB::bind_method(D_METHOD("get_line_count"),&Label::get_line_count);
- ClassDB::bind_method(D_METHOD("get_visible_line_count"),&Label::get_visible_line_count);
- ClassDB::bind_method(D_METHOD("get_total_character_count"),&Label::get_total_character_count);
- ClassDB::bind_method(D_METHOD("set_visible_characters","amount"),&Label::set_visible_characters);
- ClassDB::bind_method(D_METHOD("get_visible_characters"),&Label::get_visible_characters);
- ClassDB::bind_method(D_METHOD("set_percent_visible","percent_visible"),&Label::set_percent_visible);
- ClassDB::bind_method(D_METHOD("get_percent_visible"),&Label::get_percent_visible);
- ClassDB::bind_method(D_METHOD("set_lines_skipped","lines_skipped"),&Label::set_lines_skipped);
- ClassDB::bind_method(D_METHOD("get_lines_skipped"),&Label::get_lines_skipped);
- ClassDB::bind_method(D_METHOD("set_max_lines_visible","lines_visible"),&Label::set_max_lines_visible);
- ClassDB::bind_method(D_METHOD("get_max_lines_visible"),&Label::get_max_lines_visible);
-
- BIND_CONSTANT( ALIGN_LEFT );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_RIGHT );
- BIND_CONSTANT( ALIGN_FILL );
-
- BIND_CONSTANT( VALIGN_TOP );
- BIND_CONSTANT( VALIGN_CENTER );
- BIND_CONSTANT( VALIGN_BOTTOM );
- BIND_CONSTANT( VALIGN_FILL );
-
- ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "text",PROPERTY_HINT_MULTILINE_TEXT,"",PROPERTY_USAGE_DEFAULT_INTL), "set_text","get_text") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "align", PROPERTY_HINT_ENUM,"Left,Center,Right,Fill" ),"set_align","get_align") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "valign", PROPERTY_HINT_ENUM,"Top,Center,Bottom,Fill" ),"set_valign","get_valign") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "autowrap"),"set_autowrap","has_autowrap") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "clip_text"),"set_clip_text","is_clipping_text") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "uppercase"),"set_uppercase","is_uppercase") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "percent_visible", PROPERTY_HINT_RANGE,"0,1,0.001"),"set_percent_visible","get_percent_visible") ;
- ADD_PROPERTY( PropertyInfo( Variant::INT, "lines_skipped", PROPERTY_HINT_RANGE,"0,999,1"),"set_lines_skipped","get_lines_skipped") ;
- ADD_PROPERTY( PropertyInfo( Variant::INT, "max_lines_visible", PROPERTY_HINT_RANGE,"-1,999,1"),"set_max_lines_visible","get_max_lines_visible") ;
-
+ ClassDB::bind_method(D_METHOD("set_align", "align"), &Label::set_align);
+ ClassDB::bind_method(D_METHOD("get_align"), &Label::get_align);
+ ClassDB::bind_method(D_METHOD("set_valign", "valign"), &Label::set_valign);
+ ClassDB::bind_method(D_METHOD("get_valign"), &Label::get_valign);
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &Label::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &Label::get_text);
+ ClassDB::bind_method(D_METHOD("set_autowrap", "enable"), &Label::set_autowrap);
+ ClassDB::bind_method(D_METHOD("has_autowrap"), &Label::has_autowrap);
+ ClassDB::bind_method(D_METHOD("set_clip_text", "enable"), &Label::set_clip_text);
+ ClassDB::bind_method(D_METHOD("is_clipping_text"), &Label::is_clipping_text);
+ ClassDB::bind_method(D_METHOD("set_uppercase", "enable"), &Label::set_uppercase);
+ ClassDB::bind_method(D_METHOD("is_uppercase"), &Label::is_uppercase);
+ ClassDB::bind_method(D_METHOD("get_line_height"), &Label::get_line_height);
+ ClassDB::bind_method(D_METHOD("get_line_count"), &Label::get_line_count);
+ ClassDB::bind_method(D_METHOD("get_visible_line_count"), &Label::get_visible_line_count);
+ ClassDB::bind_method(D_METHOD("get_total_character_count"), &Label::get_total_character_count);
+ ClassDB::bind_method(D_METHOD("set_visible_characters", "amount"), &Label::set_visible_characters);
+ ClassDB::bind_method(D_METHOD("get_visible_characters"), &Label::get_visible_characters);
+ ClassDB::bind_method(D_METHOD("set_percent_visible", "percent_visible"), &Label::set_percent_visible);
+ ClassDB::bind_method(D_METHOD("get_percent_visible"), &Label::get_percent_visible);
+ ClassDB::bind_method(D_METHOD("set_lines_skipped", "lines_skipped"), &Label::set_lines_skipped);
+ ClassDB::bind_method(D_METHOD("get_lines_skipped"), &Label::get_lines_skipped);
+ ClassDB::bind_method(D_METHOD("set_max_lines_visible", "lines_visible"), &Label::set_max_lines_visible);
+ ClassDB::bind_method(D_METHOD("get_max_lines_visible"), &Label::get_max_lines_visible);
+
+ BIND_CONSTANT(ALIGN_LEFT);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_RIGHT);
+ BIND_CONSTANT(ALIGN_FILL);
+
+ BIND_CONSTANT(VALIGN_TOP);
+ BIND_CONSTANT(VALIGN_CENTER);
+ BIND_CONSTANT(VALIGN_BOTTOM);
+ BIND_CONSTANT(VALIGN_FILL);
+
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "valign", PROPERTY_HINT_ENUM, "Top,Center,Bottom,Fill"), "set_valign", "get_valign");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "autowrap"), "set_autowrap", "has_autowrap");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "is_clipping_text");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "uppercase"), "set_uppercase", "is_uppercase");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "percent_visible", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_percent_visible", "get_percent_visible");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "lines_skipped", PROPERTY_HINT_RANGE, "0,999,1"), "set_lines_skipped", "get_lines_skipped");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_lines_visible", PROPERTY_HINT_RANGE, "-1,999,1"), "set_max_lines_visible", "get_max_lines_visible");
}
Label::Label(const String &p_text) {
- align=ALIGN_LEFT;
- valign=VALIGN_TOP;
- xl_text="";
- word_cache=NULL;
- word_cache_dirty=true;
- autowrap=false;
- line_count=0;
+ align = ALIGN_LEFT;
+ valign = VALIGN_TOP;
+ xl_text = "";
+ word_cache = NULL;
+ word_cache_dirty = true;
+ autowrap = false;
+ line_count = 0;
set_v_size_flags(0);
- clip=false;
+ clip = false;
set_mouse_filter(MOUSE_FILTER_IGNORE);
- total_char_cache=0;
- visible_chars=-1;
- percent_visible=1;
- lines_skipped=0;
- max_lines_visible=-1;
+ total_char_cache = 0;
+ visible_chars = -1;
+ percent_visible = 1;
+ lines_skipped = 0;
+ max_lines_visible = -1;
set_text(p_text);
- uppercase=false;
+ uppercase = false;
}
-
Label::~Label() {
while (word_cache) {
- WordCache *current=word_cache;
- word_cache=current->next;
- memdelete( current );
+ WordCache *current = word_cache;
+ word_cache = current->next;
+ memdelete(current);
}
}
-
-
diff --git a/scene/gui/label.h b/scene/gui/label.h
index 80e4c970f6..769e4b2256 100644
--- a/scene/gui/label.h
+++ b/scene/gui/label.h
@@ -35,9 +35,9 @@
*/
class Label : public Control {
- GDCLASS( Label, Control );
-public:
+ GDCLASS(Label, Control);
+public:
enum Align {
ALIGN_LEFT,
@@ -70,15 +70,21 @@ private:
struct WordCache {
enum {
- CHAR_NEWLINE=-1,
- CHAR_WRAPLINE=-2
+ CHAR_NEWLINE = -1,
+ CHAR_WRAPLINE = -2
};
int char_pos; // if -1, then newline
int word_len;
int pixel_width;
int space_count;
WordCache *next;
- WordCache() { char_pos=0; word_len=0; pixel_width=0; next=0; space_count=0;}
+ WordCache() {
+ char_pos = 0;
+ word_len = 0;
+ pixel_width = 0;
+ next = 0;
+ space_count = 0;
+ }
};
bool word_cache_dirty;
@@ -91,13 +97,13 @@ private:
int visible_chars;
int lines_skipped;
int max_lines_visible;
+
protected:
void _notification(int p_what);
static void _bind_methods();
// bind helpers
public:
-
virtual Size2 get_minimum_size() const;
void set_align(Align p_align);
@@ -106,7 +112,7 @@ public:
void set_valign(VAlign p_align);
VAlign get_valign() const;
- void set_text(const String& p_string);
+ void set_text(const String &p_string);
String get_text() const;
void set_autowrap(bool p_autowrap);
@@ -135,13 +141,11 @@ public:
int get_line_count() const;
int get_visible_line_count() const;
- Label(const String& p_text=String());
+ Label(const String &p_text = String());
~Label();
-
};
-
-VARIANT_ENUM_CAST( Label::Align );
-VARIANT_ENUM_CAST( Label::VAlign );
+VARIANT_ENUM_CAST(Label::Align);
+VARIANT_ENUM_CAST(Label::VAlign);
#endif
diff --git a/scene/gui/line_edit.cpp b/scene/gui/line_edit.cpp
index 7f61cf80ec..20725194cf 100644
--- a/scene/gui/line_edit.cpp
+++ b/scene/gui/line_edit.cpp
@@ -27,10 +27,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "line_edit.h"
+#include "label.h"
#include "os/keyboard.h"
#include "os/os.h"
#include "print_string.h"
-#include "label.h"
#include "translation.h"
#ifdef TOOLS_ENABLED
#include "editor/editor_settings.h"
@@ -38,27 +38,26 @@
static bool _is_text_char(CharType c) {
- return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_';
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
void LineEdit::_gui_input(InputEvent p_event) {
-
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &b = p_event.mouse_button;
- if (b.pressed && b.button_index==BUTTON_RIGHT) {
+ if (b.pressed && b.button_index == BUTTON_RIGHT) {
menu->set_pos(get_global_transform().xform(get_local_mouse_pos()));
- menu->set_size(Vector2(1,1));
+ menu->set_size(Vector2(1, 1));
menu->popup();
grab_focus();
return;
}
- if (b.button_index!=BUTTON_LEFT)
+ if (b.button_index != BUTTON_LEFT)
break;
_reset_caret_blink_timer();
@@ -71,28 +70,28 @@ void LineEdit::_gui_input(InputEvent p_event) {
if (b.mod.shift) {
selection_fill_at_cursor();
- selection.creating=true;
+ selection.creating = true;
} else {
if (b.doubleclick) {
- selection.enabled=true;
- selection.begin=0;
- selection.end=text.length();
- selection.doubleclick=true;
+ selection.enabled = true;
+ selection.begin = 0;
+ selection.end = text.length();
+ selection.doubleclick = true;
}
- selection.drag_attempt=false;
+ selection.drag_attempt = false;
- if ((cursor_pos<selection.begin) || (cursor_pos>selection.end) || !selection.enabled) {
+ if ((cursor_pos < selection.begin) || (cursor_pos > selection.end) || !selection.enabled) {
selection_clear();
- selection.cursor_start=cursor_pos;
- selection.creating=true;
+ selection.cursor_start = cursor_pos;
+ selection.creating = true;
} else if (selection.enabled) {
- selection.drag_attempt=true;
+ selection.drag_attempt = true;
}
}
@@ -100,23 +99,23 @@ void LineEdit::_gui_input(InputEvent p_event) {
} else {
- if ( (!selection.creating) && (!selection.doubleclick)) {
+ if ((!selection.creating) && (!selection.doubleclick)) {
selection_clear();
}
- selection.creating=false;
- selection.doubleclick=false;
+ selection.creating = false;
+ selection.doubleclick = false;
if (OS::get_singleton()->has_virtual_keyboard())
- OS::get_singleton()->show_virtual_keyboard(text,get_global_rect());
+ OS::get_singleton()->show_virtual_keyboard(text, get_global_rect());
}
update();
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion& m=p_event.mouse_motion;
+ const InputEventMouseMotion &m = p_event.mouse_motion;
- if (m.button_mask&BUTTON_LEFT) {
+ if (m.button_mask & BUTTON_LEFT) {
if (selection.creating) {
set_cursor_at_pixel_pos(m.x);
@@ -127,22 +126,21 @@ void LineEdit::_gui_input(InputEvent p_event) {
} break;
case InputEvent::KEY: {
- const InputEventKey &k =p_event.key;
+ const InputEventKey &k = p_event.key;
if (!k.pressed)
return;
- unsigned int code = k.scancode;
-
+ unsigned int code = k.scancode;
if (k.mod.command) {
- bool handled=true;
+ bool handled = true;
switch (code) {
case (KEY_X): { // CUT
- if(editable) {
+ if (editable) {
cut_text();
}
@@ -156,7 +154,7 @@ void LineEdit::_gui_input(InputEvent p_event) {
case (KEY_V): { // PASTE
- if(editable) {
+ if (editable) {
paste_text();
}
@@ -165,22 +163,20 @@ void LineEdit::_gui_input(InputEvent p_event) {
case (KEY_Z): { // Simple One level undo
- if(editable) {
+ if (editable) {
undo();
-
}
-
} break;
case (KEY_U): { // Delete from start to cursor
- if(editable) {
+ if (editable) {
selection_clear();
undo_text = text;
- text = text.substr(cursor_pos,text.length()-cursor_pos);
+ text = text.substr(cursor_pos, text.length() - cursor_pos);
Ref<Font> font = get_font("font");
@@ -192,15 +188,13 @@ void LineEdit::_gui_input(InputEvent p_event) {
set_cursor_pos(0);
_text_changed();
-
}
-
} break;
case (KEY_Y): { // PASTE (Yank for unix users)
- if(editable) {
+ if (editable) {
paste_text();
}
@@ -208,11 +202,11 @@ void LineEdit::_gui_input(InputEvent p_event) {
} break;
case (KEY_K): { // Delete from cursor_pos to end
- if(editable) {
+ if (editable) {
selection_clear();
undo_text = text;
- text = text.substr(0,cursor_pos);
+ text = text.substr(0, cursor_pos);
_text_changed();
}
@@ -220,7 +214,7 @@ void LineEdit::_gui_input(InputEvent p_event) {
case (KEY_A): { //Select All
select();
} break;
- default: { handled=false;}
+ default: { handled = false; }
}
if (handled) {
@@ -232,13 +226,13 @@ void LineEdit::_gui_input(InputEvent p_event) {
_reset_caret_blink_timer();
if (!k.mod.meta) {
- bool handled=true;
+ bool handled = true;
switch (code) {
case KEY_ENTER:
case KEY_RETURN: {
- emit_signal( "text_entered",text );
+ emit_signal("text_entered", text);
if (OS::get_singleton()->has_virtual_keyboard())
OS::get_singleton()->hide_virtual_keyboard();
@@ -251,7 +245,7 @@ void LineEdit::_gui_input(InputEvent p_event) {
break;
if (selection.enabled) {
- undo_text=text;
+ undo_text = text;
selection_delete();
break;
}
@@ -260,20 +254,20 @@ void LineEdit::_gui_input(InputEvent p_event) {
if (k.mod.alt) {
#else
if (k.mod.alt) {
- handled=false;
+ handled = false;
break;
} else if (k.mod.command) {
#endif
- int cc=cursor_pos;
- bool prev_char=false;
+ int cc = cursor_pos;
+ bool prev_char = false;
- while (cc>0) {
- bool ischar=_is_text_char(text[cc-1]);
+ while (cc > 0) {
+ bool ischar = _is_text_char(text[cc - 1]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc--;
}
@@ -282,7 +276,7 @@ void LineEdit::_gui_input(InputEvent p_event) {
set_cursor_pos(cc);
} else {
- undo_text=text;
+ undo_text = text;
delete_char();
}
@@ -299,7 +293,7 @@ void LineEdit::_gui_input(InputEvent p_event) {
#ifndef APPLE_STYLE_KEYS
if (!k.mod.alt)
#endif
- shift_selection_check_pre(k.mod.shift);
+ shift_selection_check_pre(k.mod.shift);
#ifdef APPLE_STYLE_KEYS
if (k.mod.command) {
@@ -308,27 +302,27 @@ void LineEdit::_gui_input(InputEvent p_event) {
#else
if (k.mod.alt) {
- handled=false;
+ handled = false;
break;
} else if (k.mod.command) {
#endif
- bool prev_char=false;
- int cc=cursor_pos;
+ bool prev_char = false;
+ int cc = cursor_pos;
- while (cc>0) {
- bool ischar=_is_text_char(text[cc-1]);
+ while (cc > 0) {
+ bool ischar = _is_text_char(text[cc - 1]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc--;
}
set_cursor_pos(cc);
} else {
- set_cursor_pos(get_cursor_pos()-1);
+ set_cursor_pos(get_cursor_pos() - 1);
}
shift_selection_check_post(k.mod.shift);
@@ -351,27 +345,27 @@ void LineEdit::_gui_input(InputEvent p_event) {
} else if (k.mod.alt) {
#else
if (k.mod.alt) {
- handled=false;
+ handled = false;
break;
} else if (k.mod.command) {
#endif
- bool prev_char=false;
- int cc=cursor_pos;
+ bool prev_char = false;
+ int cc = cursor_pos;
- while (cc<text.length()) {
- bool ischar=_is_text_char(text[cc]);
+ while (cc < text.length()) {
+ bool ischar = _is_text_char(text[cc]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc++;
}
set_cursor_pos(cc);
} else {
- set_cursor_pos(get_cursor_pos()+1);
+ set_cursor_pos(get_cursor_pos() + 1);
}
shift_selection_check_post(k.mod.shift);
@@ -388,43 +382,43 @@ void LineEdit::_gui_input(InputEvent p_event) {
}
if (selection.enabled) {
- undo_text=text;
+ undo_text = text;
selection_delete();
break;
}
int text_len = text.length();
- if (cursor_pos==text_len)
+ if (cursor_pos == text_len)
break; // nothing to do
#ifdef APPLE_STYLE_KEYS
if (k.mod.alt) {
#else
if (k.mod.alt) {
- handled=false;
+ handled = false;
break;
} else if (k.mod.command) {
#endif
- int cc=cursor_pos;
+ int cc = cursor_pos;
- bool prev_char=false;
+ bool prev_char = false;
- while (cc<text.length()) {
+ while (cc < text.length()) {
- bool ischar=_is_text_char(text[cc]);
+ bool ischar = _is_text_char(text[cc]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc++;
}
- delete_text(cursor_pos,cc);
+ delete_text(cursor_pos, cc);
} else {
- undo_text=text;
- set_cursor_pos(cursor_pos+1);
+ undo_text = text;
+ set_cursor_pos(cursor_pos + 1);
delete_char();
}
@@ -456,21 +450,20 @@ void LineEdit::_gui_input(InputEvent p_event) {
shift_selection_check_post(k.mod.shift);
} break;
-
default: {
- handled=false;
+ handled = false;
} break;
}
if (handled) {
accept_event();
} else if (!k.mod.alt && !k.mod.command) {
- if (k.unicode>=32 && k.scancode!=KEY_DELETE) {
+ if (k.unicode >= 32 && k.scancode != KEY_DELETE) {
if (editable) {
selection_delete();
- CharType ucodestr[2]={(CharType)k.unicode,0};
+ CharType ucodestr[2] = { (CharType)k.unicode, 0 };
append_at_cursor(ucodestr);
_text_changed();
accept_event();
@@ -482,14 +475,11 @@ void LineEdit::_gui_input(InputEvent p_event) {
}
update();
-
}
-
return;
} break;
-
}
}
@@ -500,31 +490,30 @@ void LineEdit::set_align(Align p_align) {
update();
}
-LineEdit::Align LineEdit::get_align() const{
+LineEdit::Align LineEdit::get_align() const {
return align;
}
-Variant LineEdit::get_drag_data(const Point2& p_point) {
+Variant LineEdit::get_drag_data(const Point2 &p_point) {
if (selection.drag_attempt && selection.enabled) {
String t = text.substr(selection.begin, selection.end - selection.begin);
- Label *l = memnew( Label );
+ Label *l = memnew(Label);
l->set_text(t);
set_drag_preview(l);
- return t;
+ return t;
}
return Variant();
-
}
-bool LineEdit::can_drop_data(const Point2& p_point,const Variant& p_data) const{
+bool LineEdit::can_drop_data(const Point2 &p_point, const Variant &p_data) const {
- return p_data.get_type()==Variant::STRING;
+ return p_data.get_type() == Variant::STRING;
}
-void LineEdit::drop_data(const Point2& p_point,const Variant& p_data){
+void LineEdit::drop_data(const Point2 &p_point, const Variant &p_data) {
- if (p_data.get_type()==Variant::STRING) {
+ if (p_data.get_type() == Variant::STRING) {
set_cursor_at_pixel_pos(p_point.x);
int selected = selection.end - selection.begin;
@@ -537,30 +526,29 @@ void LineEdit::drop_data(const Point2& p_point,const Variant& p_data){
text.erase(selection.begin, selected);
append_at_cursor(p_data);
- selection.begin = cursor_pos-selected;
+ selection.begin = cursor_pos - selected;
selection.end = cursor_pos;
}
}
-
void LineEdit::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
#ifdef TOOLS_ENABLED
case NOTIFICATION_ENTER_TREE: {
if (get_tree()->is_editor_hint()) {
cursor_set_blink_enabled(EDITOR_DEF("text_editor/cursor/caret_blink", false));
cursor_set_blink_speed(EDITOR_DEF("text_editor/cursor/caret_blink_speed", 0.65));
- if (!EditorSettings::get_singleton()->is_connected("settings_changed",this,"_editor_settings_changed")) {
- EditorSettings::get_singleton()->connect("settings_changed",this,"_editor_settings_changed");
+ if (!EditorSettings::get_singleton()->is_connected("settings_changed", this, "_editor_settings_changed")) {
+ EditorSettings::get_singleton()->connect("settings_changed", this, "_editor_settings_changed");
}
}
} break;
#endif
case NOTIFICATION_RESIZED: {
- set_cursor_pos( get_cursor_pos() );
+ set_cursor_pos(get_cursor_pos());
} break;
case MainLoop::NOTIFICATION_WM_FOCUS_IN: {
@@ -579,100 +567,100 @@ void LineEdit::_notification(int p_what) {
draw_caret = false;
}
- int width,height;
+ int width, height;
- Size2 size=get_size();
- width=size.width;
- height=size.height;
+ Size2 size = get_size();
+ width = size.width;
+ height = size.height;
RID ci = get_canvas_item();
Ref<StyleBox> style = get_stylebox("normal");
if (!is_editable())
- style=get_stylebox("read_only");
+ style = get_stylebox("read_only");
- Ref<Font> font=get_font("font");
+ Ref<Font> font = get_font("font");
- style->draw( ci, Rect2( Point2(), size ) );
+ style->draw(ci, Rect2(Point2(), size));
if (has_focus()) {
- get_stylebox("focus")->draw( ci, Rect2( Point2(), size ) );
+ get_stylebox("focus")->draw(ci, Rect2(Point2(), size));
}
- int x_ofs=0;
+ int x_ofs = 0;
switch (align) {
case ALIGN_FILL:
case ALIGN_LEFT: {
- x_ofs=style->get_offset().x;
+ x_ofs = style->get_offset().x;
} break;
case ALIGN_CENTER: {
- x_ofs=int(size.width-(cached_width))/2;
+ x_ofs = int(size.width - (cached_width)) / 2;
} break;
case ALIGN_RIGHT: {
- x_ofs=int(size.width-style->get_offset().x-(cached_width));
+ x_ofs = int(size.width - style->get_offset().x - (cached_width));
} break;
}
- int ofs_max=width-style->get_minimum_size().width;
- int char_ofs=window_pos;
+ int ofs_max = width - style->get_minimum_size().width;
+ int char_ofs = window_pos;
- int y_area=height-style->get_minimum_size().height;
- int y_ofs=style->get_offset().y;
+ int y_area = height - style->get_minimum_size().height;
+ int y_ofs = style->get_offset().y;
- int font_ascent=font->get_ascent();
+ int font_ascent = font->get_ascent();
- Color selection_color=get_color("selection_color");
- Color font_color=get_color("font_color");
- Color font_color_selected=get_color("font_color_selected");
- Color cursor_color=get_color("cursor_color");
+ Color selection_color = get_color("selection_color");
+ Color font_color = get_color("font_color");
+ Color font_color_selected = get_color("font_color_selected");
+ Color cursor_color = get_color("cursor_color");
- const String& t = text.empty() ? placeholder : text;
+ const String &t = text.empty() ? placeholder : text;
// draw placeholder color
- if(text.empty())
+ if (text.empty())
font_color.a *= placeholder_alpha;
int caret_height = font->get_height() > y_area ? y_area : font->get_height();
- while(true) {
+ while (true) {
- //end of string, break!
- if (char_ofs>=t.length())
+ //end of string, break!
+ if (char_ofs >= t.length())
break;
- CharType cchar=pass?'*':t[char_ofs];
- CharType next=pass?'*':t[char_ofs+1];
- int char_width=font->get_char_size( cchar,next ).width;
+ CharType cchar = pass ? '*' : t[char_ofs];
+ CharType next = pass ? '*' : t[char_ofs + 1];
+ int char_width = font->get_char_size(cchar, next).width;
- // end of widget, break!
+ // end of widget, break!
if ((x_ofs + char_width) > ofs_max)
break;
-
- bool selected=selection.enabled && char_ofs>=selection.begin && char_ofs<selection.end;
+ bool selected = selection.enabled && char_ofs >= selection.begin && char_ofs < selection.end;
if (selected)
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(x_ofs, y_ofs), Size2(char_width, caret_height)), selection_color);
-
font->draw_char(ci, Point2(x_ofs, y_ofs + font_ascent), cchar, next, selected ? font_color_selected : font_color);
- if (char_ofs==cursor_pos && draw_caret) {
+ if (char_ofs == cursor_pos && draw_caret) {
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(
- Point2( x_ofs , y_ofs ), Size2( 1, caret_height ) ), cursor_color );
+ Point2(x_ofs, y_ofs), Size2(1, caret_height)),
+ cursor_color);
}
- x_ofs+=char_width;
+ x_ofs += char_width;
char_ofs++;
}
- if (char_ofs==cursor_pos && draw_caret) {//may be at the end
+ if (char_ofs == cursor_pos && draw_caret) { //may be at the end
VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(
- Point2( x_ofs , y_ofs ), Size2( 1, caret_height ) ), cursor_color );
+ Point2(x_ofs, y_ofs), Size2(1, caret_height)),
+ cursor_color);
}
} break;
case NOTIFICATION_FOCUS_ENTER: {
@@ -682,7 +670,7 @@ void LineEdit::_notification(int p_what) {
}
if (OS::get_singleton()->has_virtual_keyboard())
- OS::get_singleton()->show_virtual_keyboard(text,get_global_rect());
+ OS::get_singleton()->show_virtual_keyboard(text, get_global_rect());
} break;
case NOTIFICATION_FOCUS_EXIT: {
@@ -691,13 +679,12 @@ void LineEdit::_notification(int p_what) {
OS::get_singleton()->hide_virtual_keyboard();
} break;
-
}
}
void LineEdit::copy_text() {
- if(selection.enabled) {
+ if (selection.enabled) {
OS::get_singleton()->set_clipboard(text.substr(selection.begin, selection.end - selection.begin));
}
@@ -705,7 +692,7 @@ void LineEdit::copy_text() {
void LineEdit::cut_text() {
- if(selection.enabled) {
+ if (selection.enabled) {
undo_text = text;
OS::get_singleton()->set_clipboard(text.substr(selection.begin, selection.end - selection.begin));
selection_delete();
@@ -716,16 +703,13 @@ void LineEdit::paste_text() {
String paste_buffer = OS::get_singleton()->get_clipboard();
- if(paste_buffer != "") {
+ if (paste_buffer != "") {
- if(selection.enabled) selection_delete();
+ if (selection.enabled) selection_delete();
append_at_cursor(paste_buffer);
_text_changed();
}
-
-
-
}
void LineEdit::undo() {
@@ -736,10 +720,10 @@ void LineEdit::undo() {
Ref<Font> font = get_font("font");
cached_width = 0;
- for (int i = 0; i<text.length(); i++)
+ for (int i = 0; i < text.length(); i++)
cached_width += font->get_char_size(text[i]).width;
- if(old_cursor_pos > text.length()) {
+ if (old_cursor_pos > text.length()) {
set_cursor_pos(text.length());
} else {
set_cursor_pos(old_cursor_pos);
@@ -750,12 +734,11 @@ void LineEdit::undo() {
void LineEdit::shift_selection_check_pre(bool p_shift) {
- if (!selection.enabled && p_shift) {
- selection.cursor_start=cursor_pos;
+ if (!selection.enabled && p_shift) {
+ selection.cursor_start = cursor_pos;
}
if (!p_shift)
selection_clear();
-
}
void LineEdit::shift_selection_check_post(bool p_shift) {
@@ -781,32 +764,30 @@ void LineEdit::set_cursor_at_pixel_pos(int p_x) {
} break;
case ALIGN_CENTER: {
- pixel_ofs=int(size.width-(cached_width))/2;
+ pixel_ofs = int(size.width - (cached_width)) / 2;
} break;
case ALIGN_RIGHT: {
- pixel_ofs=int(size.width-style->get_offset().x-(cached_width));
+ pixel_ofs = int(size.width - style->get_offset().x - (cached_width));
} break;
}
-
- while (ofs<text.length()) {
+ while (ofs < text.length()) {
int char_w = 0;
if (font != NULL) {
char_w = font->get_char_size(text[ofs]).width;
}
- pixel_ofs+=char_w;
+ pixel_ofs += char_w;
if (pixel_ofs > p_x) { //found what we look for
break;
}
-
ofs++;
}
- set_cursor_pos( ofs );
+ set_cursor_pos(ofs);
/*
int new_cursor_pos=p_x;
@@ -816,7 +797,6 @@ void LineEdit::set_cursor_at_pixel_pos(int p_x) {
set_cursor_pos(window_pos+new_cursor_pos); */
}
-
bool LineEdit::cursor_get_blink_enabled() const {
return caret_blink_enabled;
}
@@ -847,7 +827,7 @@ void LineEdit::_reset_caret_blink_timer() {
draw_caret = true;
update();
}
- }
+}
void LineEdit::_toggle_draw_caret() {
draw_caret = !draw_caret;
@@ -858,18 +838,18 @@ void LineEdit::_toggle_draw_caret() {
void LineEdit::delete_char() {
- if ((text.length()<=0) || (cursor_pos==0)) return;
+ if ((text.length() <= 0) || (cursor_pos == 0)) return;
Ref<Font> font = get_font("font");
if (font != NULL) {
cached_width -= font->get_char_size(text[cursor_pos - 1]).width;
}
- text.erase( cursor_pos-1, 1 );
+ text.erase(cursor_pos - 1, 1);
- set_cursor_pos(get_cursor_pos()-1);
+ set_cursor_pos(get_cursor_pos() - 1);
- if (cursor_pos==window_pos) {
+ if (cursor_pos == window_pos) {
//set_window_pos(cursor_pos-get_window_length());
}
@@ -881,29 +861,26 @@ void LineEdit::delete_text(int p_from_column, int p_to_column) {
undo_text = text;
- if (text.size() > 0)
- {
+ if (text.size() > 0) {
Ref<Font> font = get_font("font");
if (font != NULL) {
for (int i = p_from_column; i < p_to_column; i++)
cached_width -= font->get_char_size(text[i]).width;
}
- }
- else
- {
+ } else {
cached_width = 0;
}
- text.erase(p_from_column,p_to_column-p_from_column);
- cursor_pos-=CLAMP( cursor_pos-p_from_column, 0, p_to_column-p_from_column);
+ text.erase(p_from_column, p_to_column - p_from_column);
+ cursor_pos -= CLAMP(cursor_pos - p_from_column, 0, p_to_column - p_from_column);
- if (cursor_pos>=text.length()) {
+ if (cursor_pos >= text.length()) {
- cursor_pos=text.length();
+ cursor_pos = text.length();
}
- if (window_pos>cursor_pos) {
+ if (window_pos > cursor_pos) {
- window_pos=cursor_pos;
+ window_pos = cursor_pos;
}
_text_changed();
@@ -914,8 +891,8 @@ void LineEdit::set_text(String p_text) {
clear_internal();
append_at_cursor(p_text);
update();
- cursor_pos=0;
- window_pos=0;
+ cursor_pos = 0;
+ window_pos = 0;
_text_changed();
}
@@ -941,7 +918,6 @@ String LineEdit::get_placeholder() const {
return placeholder;
}
-
void LineEdit::set_placeholder_alpha(float p_alpha) {
placeholder_alpha = p_alpha;
@@ -955,76 +931,72 @@ float LineEdit::get_placeholder_alpha() const {
void LineEdit::set_cursor_pos(int p_pos) {
- if (p_pos>(int)text.length())
- p_pos=text.length();
-
- if(p_pos<0)
- p_pos=0;
+ if (p_pos > (int)text.length())
+ p_pos = text.length();
+ if (p_pos < 0)
+ p_pos = 0;
-
- cursor_pos=p_pos;
+ cursor_pos = p_pos;
if (!is_inside_tree()) {
- window_pos=cursor_pos;
+ window_pos = cursor_pos;
return;
}
Ref<StyleBox> style = get_stylebox("normal");
- Ref<Font> font=get_font("font");
+ Ref<Font> font = get_font("font");
- if (cursor_pos<window_pos) {
+ if (cursor_pos < window_pos) {
/* Adjust window if cursor goes too much to the left */
set_window_pos(cursor_pos);
- } else if (cursor_pos>window_pos) {
+ } else if (cursor_pos > window_pos) {
/* Adjust window if cursor goes too much to the right */
- int window_width=get_size().width-style->get_minimum_size().width;
+ int window_width = get_size().width - style->get_minimum_size().width;
- if (window_width<0)
+ if (window_width < 0)
return;
- int wp=window_pos;
+ int wp = window_pos;
if (font.is_valid()) {
- int accum_width=0;
+ int accum_width = 0;
- for(int i=cursor_pos;i>=window_pos;i--) {
+ for (int i = cursor_pos; i >= window_pos; i--) {
- if (i>=text.length()) {
- accum_width=font->get_char_size(' ').width; //anything should do
+ if (i >= text.length()) {
+ accum_width = font->get_char_size(' ').width; //anything should do
} else {
- accum_width+=font->get_char_size(text[i],i+1<text.length()?text[i+1]:0).width; //anything should do
+ accum_width += font->get_char_size(text[i], i + 1 < text.length() ? text[i + 1] : 0).width; //anything should do
}
- if (accum_width>=window_width)
+ if (accum_width >= window_width)
break;
- wp=i;
+ wp = i;
}
}
- if (wp!=window_pos)
- set_window_pos( wp );
-
+ if (wp != window_pos)
+ set_window_pos(wp);
}
update();
}
-int LineEdit::get_cursor_pos() const {
+int LineEdit::get_cursor_pos() const {
return cursor_pos;
}
void LineEdit::set_window_pos(int p_pos) {
- window_pos=p_pos;
- if (window_pos<0) window_pos=0;
+ window_pos = p_pos;
+ if (window_pos < 0) window_pos = 0;
}
void LineEdit::append_at_cursor(String p_text) {
-
- if ( ( max_length <= 0 ) || (text.length()+p_text.length() <= max_length)) {
+ if ((max_length <= 0) || (text.length() + p_text.length() <= max_length)) {
undo_text = text;
@@ -1032,45 +1004,44 @@ void LineEdit::append_at_cursor(String p_text) {
if (font != NULL) {
for (int i = 0; i < p_text.length(); i++)
cached_width += font->get_char_size(p_text[i]).width;
- }
- else {
+ } else {
cached_width = 0;
}
- String pre = text.substr( 0, cursor_pos );
- String post = text.substr( cursor_pos, text.length()-cursor_pos );
- text=pre+p_text+post;
- set_cursor_pos(cursor_pos+p_text.length());
+ String pre = text.substr(0, cursor_pos);
+ String post = text.substr(cursor_pos, text.length() - cursor_pos);
+ text = pre + p_text + post;
+ set_cursor_pos(cursor_pos + p_text.length());
}
}
void LineEdit::clear_internal() {
cached_width = 0;
- cursor_pos=0;
- window_pos=0;
- undo_text="";
- text="";
+ cursor_pos = 0;
+ window_pos = 0;
+ undo_text = "";
+ text = "";
update();
}
Size2 LineEdit::get_minimum_size() const {
Ref<StyleBox> style = get_stylebox("normal");
- Ref<Font> font=get_font("font");
+ Ref<Font> font = get_font("font");
- Size2 min=style->get_minimum_size();
- min.height+=font->get_height();
+ Size2 min = style->get_minimum_size();
+ min.height += font->get_height();
//minimum size of text
int space_size = font->get_char_size(' ').x;
- int mstext = get_constant("minimum_spaces")*space_size;
+ int mstext = get_constant("minimum_spaces") * space_size;
if (expand_to_text_length) {
- mstext=MAX(mstext,font->get_string_size(text).x+space_size); //add a spce because some fonts are too exact
+ mstext = MAX(mstext, font->get_string_size(text).x + space_size); //add a spce because some fonts are too exact
}
- min.width+=mstext;
+ min.width += mstext;
return min;
}
@@ -1079,26 +1050,26 @@ Size2 LineEdit::get_minimum_size() const {
void LineEdit::selection_clear() {
- selection.begin=0;
- selection.end=0;
- selection.cursor_start=0;
- selection.enabled=false;
- selection.creating=false;
- selection.doubleclick=false;
+ selection.begin = 0;
+ selection.end = 0;
+ selection.cursor_start = 0;
+ selection.enabled = false;
+ selection.creating = false;
+ selection.doubleclick = false;
update();
}
void LineEdit::selection_delete() {
if (selection.enabled)
- delete_text(selection.begin,selection.end);
+ delete_text(selection.begin, selection.end);
selection_clear();
}
void LineEdit::set_max_length(int p_max_length) {
- ERR_FAIL_COND(p_max_length<0);
+ ERR_FAIL_COND(p_max_length < 0);
max_length = p_max_length;
set_text(text);
}
@@ -1112,16 +1083,16 @@ void LineEdit::selection_fill_at_cursor() {
int aux;
- selection.begin=cursor_pos;
- selection.end=selection.cursor_start;
+ selection.begin = cursor_pos;
+ selection.end = selection.cursor_start;
- if (selection.end<selection.begin) {
- aux=selection.end;
- selection.end=selection.begin;
- selection.begin=aux;
+ if (selection.end < selection.begin) {
+ aux = selection.end;
+ selection.end = selection.begin;
+ selection.begin = aux;
}
- selection.enabled=(selection.begin!=selection.end);
+ selection.enabled = (selection.begin != selection.end);
}
void LineEdit::select_all() {
@@ -1129,15 +1100,14 @@ void LineEdit::select_all() {
if (!text.length())
return;
- selection.begin=0;
- selection.end=text.length();
- selection.enabled=true;
+ selection.begin = 0;
+ selection.end = text.length();
+ selection.enabled = true;
update();
-
}
void LineEdit::set_editable(bool p_editable) {
- editable=p_editable;
+ editable = p_editable;
update();
}
@@ -1148,7 +1118,7 @@ bool LineEdit::is_editable() const {
void LineEdit::set_secret(bool p_secret) {
- pass=p_secret;
+ pass = p_secret;
update();
}
bool LineEdit::is_secret() const {
@@ -1158,38 +1128,38 @@ bool LineEdit::is_secret() const {
void LineEdit::select(int p_from, int p_to) {
- if (p_from==0 && p_to==0) {
+ if (p_from == 0 && p_to == 0) {
selection_clear();
return;
}
int len = text.length();
- if (p_from<0)
- p_from=0;
- if (p_from>len)
- p_from=len;
- if (p_to<0 || p_to>len)
- p_to=len;
-
- if (p_from>=p_to)
+ if (p_from < 0)
+ p_from = 0;
+ if (p_from > len)
+ p_from = len;
+ if (p_to < 0 || p_to > len)
+ p_to = len;
+
+ if (p_from >= p_to)
return;
- selection.enabled=true;
- selection.begin=p_from;
- selection.end=p_to;
- selection.creating=false;
- selection.doubleclick=false;
+ selection.enabled = true;
+ selection.begin = p_from;
+ selection.end = p_to;
+ selection.creating = false;
+ selection.doubleclick = false;
update();
}
bool LineEdit::is_text_field() const {
- return true;
+ return true;
}
void LineEdit::menu_option(int p_option) {
- switch(p_option) {
+ switch (p_option) {
case MENU_CUT: {
if (editable) {
cut_text();
@@ -1215,9 +1185,7 @@ void LineEdit::menu_option(int p_option) {
case MENU_UNDO: {
undo();
} break;
-
}
-
}
PopupMenu *LineEdit::get_menu() const {
@@ -1225,148 +1193,140 @@ PopupMenu *LineEdit::get_menu() const {
}
#ifdef TOOLS_ENABLED
- void LineEdit::_editor_settings_changed() {
- cursor_set_blink_enabled(EDITOR_DEF("text_editor/cursor/caret_blink", false));
- cursor_set_blink_speed(EDITOR_DEF("text_editor/cursor/caret_blink_speed", 0.65));
- }
+void LineEdit::_editor_settings_changed() {
+ cursor_set_blink_enabled(EDITOR_DEF("text_editor/cursor/caret_blink", false));
+ cursor_set_blink_speed(EDITOR_DEF("text_editor/cursor/caret_blink_speed", 0.65));
+}
#endif
-
void LineEdit::set_expand_to_text_length(bool p_enabled) {
expand_to_text_length = p_enabled;
minimum_size_changed();
}
-bool LineEdit::get_expand_to_text_length() const{
+bool LineEdit::get_expand_to_text_length() const {
return expand_to_text_length;
}
-
void LineEdit::_text_changed() {
if (expand_to_text_length)
minimum_size_changed();
- emit_signal("text_changed",text);
+ emit_signal("text_changed", text);
_change_notify("text");
-
}
void LineEdit::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_toggle_draw_caret"),&LineEdit::_toggle_draw_caret);
+ ClassDB::bind_method(D_METHOD("_toggle_draw_caret"), &LineEdit::_toggle_draw_caret);
#ifdef TOOLS_ENABLED
- ClassDB::bind_method("_editor_settings_changed",&LineEdit::_editor_settings_changed);
+ ClassDB::bind_method("_editor_settings_changed", &LineEdit::_editor_settings_changed);
#endif
ClassDB::bind_method(D_METHOD("set_align", "align"), &LineEdit::set_align);
ClassDB::bind_method(D_METHOD("get_align"), &LineEdit::get_align);
- ClassDB::bind_method(D_METHOD("_gui_input"),&LineEdit::_gui_input);
- ClassDB::bind_method(D_METHOD("clear"),&LineEdit::clear);
- ClassDB::bind_method(D_METHOD("select_all"),&LineEdit::select_all);
- ClassDB::bind_method(D_METHOD("set_text","text"),&LineEdit::set_text);
- ClassDB::bind_method(D_METHOD("get_text"),&LineEdit::get_text);
- ClassDB::bind_method(D_METHOD("set_placeholder","text"),&LineEdit::set_placeholder);
- ClassDB::bind_method(D_METHOD("get_placeholder"),&LineEdit::get_placeholder);
- ClassDB::bind_method(D_METHOD("set_placeholder_alpha","alpha"),&LineEdit::set_placeholder_alpha);
- ClassDB::bind_method(D_METHOD("get_placeholder_alpha"),&LineEdit::get_placeholder_alpha);
- ClassDB::bind_method(D_METHOD("set_cursor_pos","pos"),&LineEdit::set_cursor_pos);
- ClassDB::bind_method(D_METHOD("get_cursor_pos"),&LineEdit::get_cursor_pos);
- ClassDB::bind_method(D_METHOD("set_expand_to_text_length","enabled"),&LineEdit::set_expand_to_text_length);
- ClassDB::bind_method(D_METHOD("get_expand_to_text_length"),&LineEdit::get_expand_to_text_length);
- ClassDB::bind_method(D_METHOD("cursor_set_blink_enabled", "enabled"),&LineEdit::cursor_set_blink_enabled);
- ClassDB::bind_method(D_METHOD("cursor_get_blink_enabled"),&LineEdit::cursor_get_blink_enabled);
- ClassDB::bind_method(D_METHOD("cursor_set_blink_speed", "blink_speed"),&LineEdit::cursor_set_blink_speed);
- ClassDB::bind_method(D_METHOD("cursor_get_blink_speed"),&LineEdit::cursor_get_blink_speed);
- ClassDB::bind_method(D_METHOD("set_max_length","chars"),&LineEdit::set_max_length);
- ClassDB::bind_method(D_METHOD("get_max_length"),&LineEdit::get_max_length);
- ClassDB::bind_method(D_METHOD("append_at_cursor","text"),&LineEdit::append_at_cursor);
- ClassDB::bind_method(D_METHOD("set_editable","enabled"),&LineEdit::set_editable);
- ClassDB::bind_method(D_METHOD("is_editable"),&LineEdit::is_editable);
- ClassDB::bind_method(D_METHOD("set_secret","enabled"),&LineEdit::set_secret);
- ClassDB::bind_method(D_METHOD("is_secret"),&LineEdit::is_secret);
- ClassDB::bind_method(D_METHOD("select","from","to"),&LineEdit::select,DEFVAL(0),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("menu_option","option"),&LineEdit::menu_option);
- ClassDB::bind_method(D_METHOD("get_menu:PopupMenu"),&LineEdit::get_menu);
-
- ADD_SIGNAL( MethodInfo("text_changed", PropertyInfo( Variant::STRING, "text" )) );
- ADD_SIGNAL( MethodInfo("text_entered", PropertyInfo( Variant::STRING, "text" )) );
+ ClassDB::bind_method(D_METHOD("_gui_input"), &LineEdit::_gui_input);
+ ClassDB::bind_method(D_METHOD("clear"), &LineEdit::clear);
+ ClassDB::bind_method(D_METHOD("select_all"), &LineEdit::select_all);
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &LineEdit::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &LineEdit::get_text);
+ ClassDB::bind_method(D_METHOD("set_placeholder", "text"), &LineEdit::set_placeholder);
+ ClassDB::bind_method(D_METHOD("get_placeholder"), &LineEdit::get_placeholder);
+ ClassDB::bind_method(D_METHOD("set_placeholder_alpha", "alpha"), &LineEdit::set_placeholder_alpha);
+ ClassDB::bind_method(D_METHOD("get_placeholder_alpha"), &LineEdit::get_placeholder_alpha);
+ ClassDB::bind_method(D_METHOD("set_cursor_pos", "pos"), &LineEdit::set_cursor_pos);
+ ClassDB::bind_method(D_METHOD("get_cursor_pos"), &LineEdit::get_cursor_pos);
+ ClassDB::bind_method(D_METHOD("set_expand_to_text_length", "enabled"), &LineEdit::set_expand_to_text_length);
+ ClassDB::bind_method(D_METHOD("get_expand_to_text_length"), &LineEdit::get_expand_to_text_length);
+ ClassDB::bind_method(D_METHOD("cursor_set_blink_enabled", "enabled"), &LineEdit::cursor_set_blink_enabled);
+ ClassDB::bind_method(D_METHOD("cursor_get_blink_enabled"), &LineEdit::cursor_get_blink_enabled);
+ ClassDB::bind_method(D_METHOD("cursor_set_blink_speed", "blink_speed"), &LineEdit::cursor_set_blink_speed);
+ ClassDB::bind_method(D_METHOD("cursor_get_blink_speed"), &LineEdit::cursor_get_blink_speed);
+ ClassDB::bind_method(D_METHOD("set_max_length", "chars"), &LineEdit::set_max_length);
+ ClassDB::bind_method(D_METHOD("get_max_length"), &LineEdit::get_max_length);
+ ClassDB::bind_method(D_METHOD("append_at_cursor", "text"), &LineEdit::append_at_cursor);
+ ClassDB::bind_method(D_METHOD("set_editable", "enabled"), &LineEdit::set_editable);
+ ClassDB::bind_method(D_METHOD("is_editable"), &LineEdit::is_editable);
+ ClassDB::bind_method(D_METHOD("set_secret", "enabled"), &LineEdit::set_secret);
+ ClassDB::bind_method(D_METHOD("is_secret"), &LineEdit::is_secret);
+ ClassDB::bind_method(D_METHOD("select", "from", "to"), &LineEdit::select, DEFVAL(0), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("menu_option", "option"), &LineEdit::menu_option);
+ ClassDB::bind_method(D_METHOD("get_menu:PopupMenu"), &LineEdit::get_menu);
+
+ ADD_SIGNAL(MethodInfo("text_changed", PropertyInfo(Variant::STRING, "text")));
+ ADD_SIGNAL(MethodInfo("text_entered", PropertyInfo(Variant::STRING, "text")));
BIND_CONSTANT(ALIGN_LEFT);
BIND_CONSTANT(ALIGN_CENTER);
BIND_CONSTANT(ALIGN_RIGHT);
BIND_CONSTANT(ALIGN_FILL);
- BIND_CONSTANT( MENU_CUT );
- BIND_CONSTANT( MENU_COPY );
- BIND_CONSTANT( MENU_PASTE );
- BIND_CONSTANT( MENU_CLEAR );
- BIND_CONSTANT( MENU_SELECT_ALL );
- BIND_CONSTANT( MENU_UNDO );
- BIND_CONSTANT( MENU_MAX );
+ BIND_CONSTANT(MENU_CUT);
+ BIND_CONSTANT(MENU_COPY);
+ BIND_CONSTANT(MENU_PASTE);
+ BIND_CONSTANT(MENU_CLEAR);
+ BIND_CONSTANT(MENU_SELECT_ALL);
+ BIND_CONSTANT(MENU_UNDO);
+ BIND_CONSTANT(MENU_MAX);
- ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "text" ), "set_text","get_text") ;
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text"), "set_text", "get_text");
ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "max_length" ), "set_max_length","get_max_length") ;
- ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "editable" ), "set_editable","is_editable") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "secret" ), "set_secret","is_secret") ;
- ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "expand_to_len" ), "set_expand_to_text_length","get_expand_to_text_length") ;
- ADD_PROPERTY( PropertyInfo( Variant::INT,"focus_mode", PROPERTY_HINT_ENUM, "None,Click,All" ), "set_focus_mode", "get_focus_mode") ;
- ADD_GROUP("Placeholder","placeholder_");
- ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "placeholder_text" ), "set_placeholder","get_placeholder") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::REAL, "placeholder_alpha",PROPERTY_HINT_RANGE,"0,1,0.001" ), "set_placeholder_alpha","get_placeholder_alpha") ;
- ADD_GROUP("Caret","caret_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "max_length"), "set_max_length", "get_max_length");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "secret"), "set_secret", "is_secret");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "expand_to_len"), "set_expand_to_text_length", "get_expand_to_text_length");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_focus_mode", "get_focus_mode");
+ ADD_GROUP("Placeholder", "placeholder_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "placeholder_text"), "set_placeholder", "get_placeholder");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "placeholder_alpha", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_placeholder_alpha", "get_placeholder_alpha");
+ ADD_GROUP("Caret", "caret_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_blink"), "cursor_set_blink_enabled", "cursor_get_blink_enabled");
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "caret_blink_speed",PROPERTY_HINT_RANGE,"0.1,10,0.1"), "cursor_set_blink_speed","cursor_get_blink_speed") ;
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "caret_blink_speed", PROPERTY_HINT_RANGE, "0.1,10,0.1"), "cursor_set_blink_speed", "cursor_get_blink_speed");
}
LineEdit::LineEdit() {
align = ALIGN_LEFT;
cached_width = 0;
- cursor_pos=0;
- window_pos=0;
- window_has_focus=true;
+ cursor_pos = 0;
+ window_pos = 0;
+ window_has_focus = true;
max_length = 0;
- pass=false;
- placeholder_alpha=0.6;
+ pass = false;
+ placeholder_alpha = 0.6;
selection_clear();
- set_focus_mode( FOCUS_ALL );
- editable=true;
+ set_focus_mode(FOCUS_ALL);
+ editable = true;
set_default_cursor_shape(CURSOR_IBEAM);
set_mouse_filter(MOUSE_FILTER_STOP);
- draw_caret=true;
- caret_blink_enabled=false;
+ draw_caret = true;
+ caret_blink_enabled = false;
caret_blink_timer = memnew(Timer);
add_child(caret_blink_timer);
caret_blink_timer->set_wait_time(0.65);
- caret_blink_timer->connect("timeout", this,"_toggle_draw_caret");
+ caret_blink_timer->connect("timeout", this, "_toggle_draw_caret");
cursor_set_blink_enabled(false);
- menu = memnew( PopupMenu );
+ menu = memnew(PopupMenu);
add_child(menu);
- menu->add_item(TTR("Cut"),MENU_CUT,KEY_MASK_CMD|KEY_X);
- menu->add_item(TTR("Copy"),MENU_COPY,KEY_MASK_CMD|KEY_C);
- menu->add_item(TTR("Paste"),MENU_PASTE,KEY_MASK_CMD|KEY_V);
+ menu->add_item(TTR("Cut"), MENU_CUT, KEY_MASK_CMD | KEY_X);
+ menu->add_item(TTR("Copy"), MENU_COPY, KEY_MASK_CMD | KEY_C);
+ menu->add_item(TTR("Paste"), MENU_PASTE, KEY_MASK_CMD | KEY_V);
menu->add_separator();
- menu->add_item(TTR("Select All"),MENU_SELECT_ALL,KEY_MASK_CMD|KEY_A);
- menu->add_item(TTR("Clear"),MENU_CLEAR);
+ menu->add_item(TTR("Select All"), MENU_SELECT_ALL, KEY_MASK_CMD | KEY_A);
+ menu->add_item(TTR("Clear"), MENU_CLEAR);
menu->add_separator();
- menu->add_item(TTR("Undo"),MENU_UNDO,KEY_MASK_CMD|KEY_Z);
- menu->connect("id_pressed",this,"menu_option");
- expand_to_text_length=false;
-
-
+ menu->add_item(TTR("Undo"), MENU_UNDO, KEY_MASK_CMD | KEY_Z);
+ menu->connect("id_pressed", this, "menu_option");
+ expand_to_text_length = false;
}
LineEdit::~LineEdit() {
-
-
}
-
diff --git a/scene/gui/line_edit.h b/scene/gui/line_edit.h
index 64c37861d0..0746547115 100644
--- a/scene/gui/line_edit.h
+++ b/scene/gui/line_edit.h
@@ -37,7 +37,7 @@
*/
class LineEdit : public Control {
- GDCLASS( LineEdit, Control );
+ GDCLASS(LineEdit, Control);
public:
enum Align {
@@ -91,7 +91,6 @@ private:
Timer *caret_blink_timer;
-
void _text_changed();
bool expand_to_text_length;
@@ -122,16 +121,16 @@ private:
void _gui_input(InputEvent p_event);
void _notification(int p_what);
-
protected:
static void _bind_methods();
+
public:
void set_align(Align p_align);
Align get_align() const;
- virtual Variant get_drag_data(const Point2& p_point);
- virtual bool can_drop_data(const Point2& p_point,const Variant& p_data) const;
- virtual void drop_data(const Point2& p_point,const Variant& p_data);
+ virtual Variant get_drag_data(const Point2 &p_point);
+ virtual bool can_drop_data(const Point2 &p_point, const Variant &p_data) const;
+ virtual void drop_data(const Point2 &p_point, const Variant &p_data);
void menu_option(int p_option);
PopupMenu *get_menu() const;
@@ -170,7 +169,7 @@ public:
void set_secret(bool p_secret);
bool is_secret() const;
- void select(int p_from=0, int p_to=-1);
+ void select(int p_from = 0, int p_to = -1);
virtual Size2 get_minimum_size() const;
@@ -180,10 +179,8 @@ public:
virtual bool is_text_field() const;
LineEdit();
~LineEdit();
-
};
-
VARIANT_ENUM_CAST(LineEdit::Align);
#endif
diff --git a/scene/gui/link_button.cpp b/scene/gui/link_button.cpp
index 7ea88f35f3..17e549c902 100644
--- a/scene/gui/link_button.cpp
+++ b/scene/gui/link_button.cpp
@@ -28,10 +28,9 @@
/*************************************************************************/
#include "link_button.h"
+void LinkButton::set_text(const String &p_text) {
-void LinkButton::set_text(const String& p_text) {
-
- text=p_text;
+ text = p_text;
update();
minimum_size_changed();
}
@@ -42,7 +41,7 @@ String LinkButton::get_text() const {
void LinkButton::set_underline_mode(UnderlineMode p_underline_mode) {
- underline_mode=p_underline_mode;
+ underline_mode = p_underline_mode;
update();
}
@@ -51,55 +50,51 @@ LinkButton::UnderlineMode LinkButton::get_underline_mode() const {
return underline_mode;
}
-
Size2 LinkButton::get_minimum_size() const {
- return get_font("font")->get_string_size( text );
+ return get_font("font")->get_string_size(text);
}
-
-
void LinkButton::_notification(int p_what) {
- switch( p_what ) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
-
RID ci = get_canvas_item();
- Size2 size=get_size();
+ Size2 size = get_size();
Color color;
- bool do_underline=false;
+ bool do_underline = false;
//print_line(get_text()+": "+itos(is_flat())+" hover "+itos(get_draw_mode()));
- switch( get_draw_mode() ) {
+ switch (get_draw_mode()) {
case DRAW_NORMAL: {
- color=get_color("font_color");
- do_underline=underline_mode==UNDERLINE_MODE_ALWAYS;
+ color = get_color("font_color");
+ do_underline = underline_mode == UNDERLINE_MODE_ALWAYS;
} break;
case DRAW_PRESSED: {
if (has_color("font_color_pressed"))
- color=get_color("font_color_pressed");
+ color = get_color("font_color_pressed");
else
- color=get_color("font_color");
+ color = get_color("font_color");
- do_underline=underline_mode!=UNDERLINE_MODE_NEVER;
+ do_underline = underline_mode != UNDERLINE_MODE_NEVER;
} break;
case DRAW_HOVER: {
- color=get_color("font_color_hover");
- do_underline=underline_mode!=UNDERLINE_MODE_NEVER;
+ color = get_color("font_color_hover");
+ do_underline = underline_mode != UNDERLINE_MODE_NEVER;
} break;
case DRAW_DISABLED: {
- color=get_color("font_color_disabled");
- do_underline=underline_mode==UNDERLINE_MODE_ALWAYS;
+ color = get_color("font_color_disabled");
+ do_underline = underline_mode == UNDERLINE_MODE_ALWAYS;
} break;
}
@@ -107,21 +102,19 @@ void LinkButton::_notification(int p_what) {
if (has_focus()) {
Ref<StyleBox> style = get_stylebox("focus");
- style->draw(ci,Rect2(Point2(),size));
+ style->draw(ci, Rect2(Point2(), size));
}
- Ref<Font> font=get_font("font");
-
- draw_string(font,Vector2(0,font->get_ascent()),text,color);
-
+ Ref<Font> font = get_font("font");
+ draw_string(font, Vector2(0, font->get_ascent()), text, color);
if (do_underline) {
int underline_spacing = get_constant("underline_spacing");
int width = font->get_string_size(text).width;
- int y = font->get_ascent()+underline_spacing;
+ int y = font->get_ascent() + underline_spacing;
- draw_line(Vector2(0,y),Vector2(width,y),color);
+ draw_line(Vector2(0, y), Vector2(width, y), color);
}
} break;
@@ -130,24 +123,22 @@ void LinkButton::_notification(int p_what) {
void LinkButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_text","text"),&LinkButton::set_text);
- ClassDB::bind_method(D_METHOD("get_text"),&LinkButton::get_text);
-
- ClassDB::bind_method(D_METHOD("set_underline_mode","underline_mode"),&LinkButton::set_underline_mode);
- ClassDB::bind_method(D_METHOD("get_underline_mode"),&LinkButton::get_underline_mode);
-
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &LinkButton::set_text);
+ ClassDB::bind_method(D_METHOD("get_text"), &LinkButton::get_text);
- BIND_CONSTANT( UNDERLINE_MODE_ALWAYS );
- BIND_CONSTANT( UNDERLINE_MODE_ON_HOVER );
- BIND_CONSTANT( UNDERLINE_MODE_NEVER );
+ ClassDB::bind_method(D_METHOD("set_underline_mode", "underline_mode"), &LinkButton::set_underline_mode);
+ ClassDB::bind_method(D_METHOD("get_underline_mode"), &LinkButton::get_underline_mode);
- ADD_PROPERTYNZ(PropertyInfo(Variant::STRING,"text"), "set_text", "get_text");
- ADD_PROPERTYNZ(PropertyInfo(Variant::INT,"underline",PROPERTY_HINT_ENUM,"Always,On Hover,Never"), "set_underline_mode", "get_underline_mode");
+ BIND_CONSTANT(UNDERLINE_MODE_ALWAYS);
+ BIND_CONSTANT(UNDERLINE_MODE_ON_HOVER);
+ BIND_CONSTANT(UNDERLINE_MODE_NEVER);
+ ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text"), "set_text", "get_text");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "underline", PROPERTY_HINT_ENUM, "Always,On Hover,Never"), "set_underline_mode", "get_underline_mode");
}
LinkButton::LinkButton() {
- underline_mode=UNDERLINE_MODE_ALWAYS;
+ underline_mode = UNDERLINE_MODE_ALWAYS;
set_enabled_focus_mode(FOCUS_NONE);
set_default_cursor_shape(CURSOR_POINTING_HAND);
}
diff --git a/scene/gui/link_button.h b/scene/gui/link_button.h
index 42d7c05cff..97c2bfc3c8 100644
--- a/scene/gui/link_button.h
+++ b/scene/gui/link_button.h
@@ -29,33 +29,31 @@
#ifndef LINKBUTTON_H
#define LINKBUTTON_H
-
#include "scene/gui/base_button.h"
#include "scene/resources/bit_mask.h"
class LinkButton : public BaseButton {
- GDCLASS( LinkButton, BaseButton );
-public:
+ GDCLASS(LinkButton, BaseButton);
+public:
enum UnderlineMode {
UNDERLINE_MODE_ALWAYS,
UNDERLINE_MODE_ON_HOVER,
UNDERLINE_MODE_NEVER
};
+
private:
String text;
UnderlineMode underline_mode;
protected:
-
virtual Size2 get_minimum_size() const;
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_text(const String& p_text);
+ void set_text(const String &p_text);
String get_text() const;
void set_underline_mode(UnderlineMode p_underline_mode);
@@ -64,6 +62,6 @@ public:
LinkButton();
};
-VARIANT_ENUM_CAST( LinkButton::UnderlineMode );
+VARIANT_ENUM_CAST(LinkButton::UnderlineMode);
#endif // LINKBUTTON_H
diff --git a/scene/gui/margin_container.cpp b/scene/gui/margin_container.cpp
index be27c40117..b7824e9037 100644
--- a/scene/gui/margin_container.cpp
+++ b/scene/gui/margin_container.cpp
@@ -28,7 +28,6 @@
/*************************************************************************/
#include "margin_container.h"
-
Size2 MarginContainer::get_minimum_size() const {
int margin_left = get_constant("margin_left");
@@ -38,7 +37,7 @@ Size2 MarginContainer::get_minimum_size() const {
Size2 max;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -59,12 +58,11 @@ Size2 MarginContainer::get_minimum_size() const {
max.height += (margin_top + margin_bottom);
return max;
-
}
void MarginContainer::_notification(int p_what) {
- if (p_what==NOTIFICATION_SORT_CHILDREN) {
+ if (p_what == NOTIFICATION_SORT_CHILDREN) {
int margin_left = get_constant("margin_left");
int margin_top = get_constant("margin_top");
@@ -73,7 +71,7 @@ void MarginContainer::_notification(int p_what) {
Size2 s = get_size();
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -81,14 +79,12 @@ void MarginContainer::_notification(int p_what) {
if (c->is_set_as_toplevel())
continue;
- int w=s.width-margin_left-margin_right;
- int h=s.height-margin_top-margin_bottom;
- fit_child_in_rect(c,Rect2(margin_left,margin_top,w,h));
+ int w = s.width - margin_left - margin_right;
+ int h = s.height - margin_top - margin_bottom;
+ fit_child_in_rect(c, Rect2(margin_left, margin_top, w, h));
}
-
}
}
-MarginContainer::MarginContainer()
-{
+MarginContainer::MarginContainer() {
}
diff --git a/scene/gui/margin_container.h b/scene/gui/margin_container.h
index 542578dd01..9f0829a34d 100644
--- a/scene/gui/margin_container.h
+++ b/scene/gui/margin_container.h
@@ -32,12 +32,12 @@
#include "scene/gui/container.h"
class MarginContainer : public Container {
- GDCLASS(MarginContainer,Container);
+ GDCLASS(MarginContainer, Container);
protected:
void _notification(int p_what);
-public:
+public:
virtual Size2 get_minimum_size() const;
MarginContainer();
diff --git a/scene/gui/menu_button.cpp b/scene/gui/menu_button.cpp
index f15b864b95..f2e2c9b255 100644
--- a/scene/gui/menu_button.cpp
+++ b/scene/gui/menu_button.cpp
@@ -30,36 +30,32 @@
#include "os/keyboard.h"
#include "scene/main/viewport.h"
-
void MenuButton::_unhandled_key_input(InputEvent p_event) {
-
- if (p_event.is_pressed() && !p_event.is_echo() && (p_event.type==InputEvent::KEY || p_event.type==InputEvent::ACTION || p_event.type==InputEvent::JOYPAD_BUTTON)) {
+ if (p_event.is_pressed() && !p_event.is_echo() && (p_event.type == InputEvent::KEY || p_event.type == InputEvent::ACTION || p_event.type == InputEvent::JOYPAD_BUTTON)) {
if (!get_parent() || !is_visible_in_tree() || is_disabled())
return;
bool global_only = (get_viewport()->get_modal_stack_top() && !get_viewport()->get_modal_stack_top()->is_a_parent_of(this));
- if (popup->activate_item_by_event(p_event,global_only))
+ if (popup->activate_item_by_event(p_event, global_only))
accept_event();
}
}
-
void MenuButton::pressed() {
emit_signal("about_to_show");
- Size2 size=get_size();
+ Size2 size = get_size();
Point2 gp = get_global_pos();
- popup->set_global_pos( gp + Size2( 0, size.height ) );
- popup->set_size( Size2( size.width, 0) );
- popup->set_parent_rect( Rect2(Point2(gp-popup->get_global_pos()),get_size()));
+ popup->set_global_pos(gp + Size2(0, size.height));
+ popup->set_size(Size2(size.width, 0));
+ popup->set_parent_rect(Rect2(Point2(gp - popup->get_global_pos()), get_size()));
popup->popup();
popup->call_deferred("grab_click_focus");
popup->set_invalidate_click_until_motion();
-
}
void MenuButton::_gui_input(InputEvent p_event) {
@@ -91,28 +87,27 @@ Array MenuButton::_get_items() const {
return popup->get("items");
}
-void MenuButton::_set_items(const Array& p_items) {
+void MenuButton::_set_items(const Array &p_items) {
- popup->set("items",p_items);
+ popup->set("items", p_items);
}
void MenuButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_popup:PopupMenu"),&MenuButton::get_popup);
- ClassDB::bind_method(D_METHOD("_unhandled_key_input"),&MenuButton::_unhandled_key_input);
- ClassDB::bind_method(D_METHOD("_set_items"),&MenuButton::_set_items);
- ClassDB::bind_method(D_METHOD("_get_items"),&MenuButton::_get_items);
+ ClassDB::bind_method(D_METHOD("get_popup:PopupMenu"), &MenuButton::get_popup);
+ ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &MenuButton::_unhandled_key_input);
+ ClassDB::bind_method(D_METHOD("_set_items"), &MenuButton::_set_items);
+ ClassDB::bind_method(D_METHOD("_get_items"), &MenuButton::_get_items);
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"items",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_items","_get_items") ;
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_items", "_get_items");
- ADD_SIGNAL( MethodInfo("about_to_show") );
+ ADD_SIGNAL(MethodInfo("about_to_show"));
}
MenuButton::MenuButton() {
-
set_flat(true);
set_enabled_focus_mode(FOCUS_NONE);
- popup = memnew( PopupMenu );
+ popup = memnew(PopupMenu);
popup->hide();
add_child(popup);
popup->set_as_toplevel(true);
@@ -120,9 +115,5 @@ MenuButton::MenuButton() {
set_action_mode(ACTION_MODE_BUTTON_PRESS);
}
-
MenuButton::~MenuButton() {
-
}
-
-
diff --git a/scene/gui/menu_button.h b/scene/gui/menu_button.h
index 5b5573456f..4acb62cf37 100644
--- a/scene/gui/menu_button.h
+++ b/scene/gui/menu_button.h
@@ -29,14 +29,14 @@
#ifndef MENU_BUTTON_H
#define MENU_BUTTON_H
-#include "scene/gui/popup_menu.h"
#include "scene/gui/button.h"
+#include "scene/gui/popup_menu.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class MenuButton : public Button {
- GDCLASS( MenuButton, Button );
+ GDCLASS(MenuButton, Button);
bool clicked;
PopupMenu *popup;
@@ -44,15 +44,14 @@ class MenuButton : public Button {
void _unhandled_key_input(InputEvent p_event);
Array _get_items() const;
- void _set_items(const Array& p_items);
+ void _set_items(const Array &p_items);
void _gui_input(InputEvent p_event);
-protected:
-
+protected:
static void _bind_methods();
-public:
+public:
PopupMenu *get_popup();
MenuButton();
~MenuButton();
diff --git a/scene/gui/option_button.cpp b/scene/gui/option_button.cpp
index 9ead79b491..43f68d92ab 100644
--- a/scene/gui/option_button.cpp
+++ b/scene/gui/option_button.cpp
@@ -29,22 +29,19 @@
#include "option_button.h"
#include "print_string.h"
-
Size2 OptionButton::get_minimum_size() const {
-
Size2 minsize = Button::get_minimum_size();
if (has_icon("arrow"))
- minsize.width+=Control::get_icon("arrow")->get_width();
+ minsize.width += Control::get_icon("arrow")->get_width();
return minsize;
}
void OptionButton::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
@@ -53,86 +50,82 @@ void OptionButton::_notification(int p_what) {
RID ci = get_canvas_item();
Ref<Texture> arrow = Control::get_icon("arrow");
- Ref<StyleBox> normal = get_stylebox("normal" );
+ Ref<StyleBox> normal = get_stylebox("normal");
Size2 size = get_size();
- Point2 ofs( size.width - arrow->get_width() - get_constant("arrow_margin"), int(Math::abs((size.height-arrow->get_height())/2)));
- arrow->draw(ci,ofs);
+ Point2 ofs(size.width - arrow->get_width() - get_constant("arrow_margin"), int(Math::abs((size.height - arrow->get_height()) / 2)));
+ arrow->draw(ci, ofs);
} break;
}
}
-
void OptionButton::_selected(int p_which) {
int selid = -1;
- for (int i=0;i<popup->get_item_count();i++) {
+ for (int i = 0; i < popup->get_item_count(); i++) {
- bool is_clicked = popup->get_item_ID(i)==p_which;
+ bool is_clicked = popup->get_item_ID(i) == p_which;
if (is_clicked) {
- selid=i;
+ selid = i;
break;
}
}
- if (selid==-1 && p_which>=0 && p_which<popup->get_item_count()) {
- _select(p_which,true);
+ if (selid == -1 && p_which >= 0 && p_which < popup->get_item_count()) {
+ _select(p_which, true);
} else {
- ERR_FAIL_COND(selid==-1);
+ ERR_FAIL_COND(selid == -1);
- _select(selid,true);
+ _select(selid, true);
}
}
-
void OptionButton::pressed() {
- Size2 size=get_size();
- popup->set_global_pos( get_global_pos() + Size2( 0, size.height ) );
- popup->set_size( Size2( size.width, 0) );
+ Size2 size = get_size();
+ popup->set_global_pos(get_global_pos() + Size2(0, size.height));
+ popup->set_size(Size2(size.width, 0));
popup->popup();
}
-void OptionButton::add_icon_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID) {
+void OptionButton::add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID) {
- popup->add_icon_check_item( p_icon, p_label, p_ID );
- if (popup->get_item_count()==1)
+ popup->add_icon_check_item(p_icon, p_label, p_ID);
+ if (popup->get_item_count() == 1)
select(0);
}
-void OptionButton::add_item(const String& p_label,int p_ID) {
+void OptionButton::add_item(const String &p_label, int p_ID) {
- popup->add_check_item( p_label, p_ID );
- if (popup->get_item_count()==1)
+ popup->add_check_item(p_label, p_ID);
+ if (popup->get_item_count() == 1)
select(0);
}
-void OptionButton::set_item_text(int p_idx,const String& p_text) {
-
- popup->set_item_text(p_idx,p_text);
+void OptionButton::set_item_text(int p_idx, const String &p_text) {
+ popup->set_item_text(p_idx, p_text);
}
-void OptionButton::set_item_icon(int p_idx,const Ref<Texture>& p_icon) {
-
- popup->set_item_icon(p_idx,p_icon);
+void OptionButton::set_item_icon(int p_idx, const Ref<Texture> &p_icon) {
+ popup->set_item_icon(p_idx, p_icon);
}
-void OptionButton::set_item_ID(int p_idx,int p_ID) {
+void OptionButton::set_item_ID(int p_idx, int p_ID) {
- popup->set_item_ID(p_idx,p_ID);
+ popup->set_item_ID(p_idx, p_ID);
}
-void OptionButton::set_item_metadata(int p_idx,const Variant& p_metadata) {
+void OptionButton::set_item_metadata(int p_idx, const Variant &p_metadata) {
- popup->set_item_metadata(p_idx,p_metadata);
+ popup->set_item_metadata(p_idx, p_metadata);
}
-void OptionButton::set_item_disabled(int p_idx,bool p_disabled) {
+void OptionButton::set_item_disabled(int p_idx, bool p_disabled) {
- popup->set_item_disabled(p_idx,p_disabled);
+ popup->set_item_disabled(p_idx, p_disabled);
}
String OptionButton::get_item_text(int p_idx) const {
@@ -159,8 +152,7 @@ bool OptionButton::is_item_disabled(int p_idx) const {
return popup->is_item_disabled(p_idx);
}
-
-int OptionButton::get_item_count() const {
+int OptionButton::get_item_count() const {
return popup->get_item_count();
}
@@ -174,44 +166,41 @@ void OptionButton::clear() {
popup->clear();
set_text("");
- current=-1;
+ current = -1;
}
-void OptionButton::_select(int p_idx,bool p_emit) {
+void OptionButton::_select(int p_idx, bool p_emit) {
- if (p_idx<0)
+ if (p_idx < 0)
return;
- if (p_idx==current)
+ if (p_idx == current)
return;
- ERR_FAIL_INDEX( p_idx, popup->get_item_count() );
+ ERR_FAIL_INDEX(p_idx, popup->get_item_count());
- for (int i=0;i<popup->get_item_count();i++) {
+ for (int i = 0; i < popup->get_item_count(); i++) {
- popup->set_item_checked(i,i==p_idx);
+ popup->set_item_checked(i, i == p_idx);
}
-
-
- current=p_idx;
- set_text( popup->get_item_text( current ) );
- set_icon( popup->get_item_icon( current ) );
+ current = p_idx;
+ set_text(popup->get_item_text(current));
+ set_icon(popup->get_item_icon(current));
if (is_inside_tree() && p_emit)
- emit_signal("item_selected",current);
+ emit_signal("item_selected", current);
}
void OptionButton::_select_int(int p_which) {
- if (p_which<0 || p_which>=popup->get_item_count())
+ if (p_which < 0 || p_which >= popup->get_item_count())
return;
- _select(p_which,false);
-
+ _select(p_which, false);
}
void OptionButton::select(int p_idx) {
- _select(p_idx,false);
+ _select(p_idx, false);
}
int OptionButton::get_selected() const {
@@ -222,17 +211,16 @@ int OptionButton::get_selected() const {
int OptionButton::get_selected_ID() const {
int idx = get_selected();
- if (idx<0)
+ if (idx < 0)
return 0;
return get_item_ID(current);
}
Variant OptionButton::get_selected_metadata() const {
int idx = get_selected();
- if (idx<0)
+ if (idx < 0)
return Variant();
return get_item_metadata(current);
-
}
void OptionButton::remove_item(int p_idx) {
@@ -243,7 +231,7 @@ void OptionButton::remove_item(int p_idx) {
Array OptionButton::_get_items() const {
Array items;
- for(int i=0;i<get_item_count();i++) {
+ for (int i = 0; i < get_item_count(); i++) {
items.push_back(get_item_text(i));
items.push_back(get_item_icon(i));
@@ -253,90 +241,78 @@ Array OptionButton::_get_items() const {
}
return items;
-
}
-void OptionButton::_set_items(const Array& p_items){
+void OptionButton::_set_items(const Array &p_items) {
ERR_FAIL_COND(p_items.size() % 5);
clear();
- for(int i=0;i<p_items.size();i+=5) {
+ for (int i = 0; i < p_items.size(); i += 5) {
- String text=p_items[i+0];
- Ref<Texture> icon=p_items[i+1];
- bool disabled=p_items[i+2];
- int id=p_items[i+3];
- Variant meta = p_items[i+4];
+ String text = p_items[i + 0];
+ Ref<Texture> icon = p_items[i + 1];
+ bool disabled = p_items[i + 2];
+ int id = p_items[i + 3];
+ Variant meta = p_items[i + 4];
- int idx=get_item_count();
- add_item(text,id);
- set_item_icon(idx,icon);
- set_item_disabled(idx,disabled);
- set_item_metadata(idx,meta);
+ int idx = get_item_count();
+ add_item(text, id);
+ set_item_icon(idx, icon);
+ set_item_disabled(idx, disabled);
+ set_item_metadata(idx, meta);
}
-
-
}
-
void OptionButton::get_translatable_strings(List<String> *p_strings) const {
return popup->get_translatable_strings(p_strings);
}
-
void OptionButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_selected"),&OptionButton::_selected);
-
- ClassDB::bind_method(D_METHOD("add_item","label","id"),&OptionButton::add_item,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("add_icon_item","texture:Texture","label","id"),&OptionButton::add_icon_item);
- ClassDB::bind_method(D_METHOD("set_item_text","idx","text"),&OptionButton::set_item_text);
- ClassDB::bind_method(D_METHOD("set_item_icon","idx","texture:Texture"),&OptionButton::set_item_icon);
- ClassDB::bind_method(D_METHOD("set_item_disabled","idx","disabled"),&OptionButton::set_item_disabled);
- ClassDB::bind_method(D_METHOD("set_item_ID","idx","id"),&OptionButton::set_item_ID);
- ClassDB::bind_method(D_METHOD("set_item_metadata","idx","metadata"),&OptionButton::set_item_metadata);
- ClassDB::bind_method(D_METHOD("get_item_text","idx"),&OptionButton::get_item_text);
- ClassDB::bind_method(D_METHOD("get_item_icon:Texture","idx"),&OptionButton::get_item_icon);
- ClassDB::bind_method(D_METHOD("get_item_ID","idx"),&OptionButton::get_item_ID);
- ClassDB::bind_method(D_METHOD("get_item_metadata","idx"),&OptionButton::get_item_metadata);
- ClassDB::bind_method(D_METHOD("is_item_disabled","idx"),&OptionButton::is_item_disabled);
- ClassDB::bind_method(D_METHOD("get_item_count"),&OptionButton::get_item_count);
- ClassDB::bind_method(D_METHOD("add_separator"),&OptionButton::add_separator);
- ClassDB::bind_method(D_METHOD("clear"),&OptionButton::clear);
- ClassDB::bind_method(D_METHOD("select","idx"),&OptionButton::select);
- ClassDB::bind_method(D_METHOD("get_selected"),&OptionButton::get_selected);
- ClassDB::bind_method(D_METHOD("get_selected_ID"),&OptionButton::get_selected_ID);
- ClassDB::bind_method(D_METHOD("get_selected_metadata"),&OptionButton::get_selected_metadata);
- ClassDB::bind_method(D_METHOD("remove_item","idx"),&OptionButton::remove_item);
- ClassDB::bind_method(D_METHOD("_select_int"),&OptionButton::_select_int);
-
- ClassDB::bind_method(D_METHOD("_set_items"),&OptionButton::_set_items);
- ClassDB::bind_method(D_METHOD("_get_items"),&OptionButton::_get_items);
-
- ADD_PROPERTY( PropertyInfo(Variant::INT,"selected"), "_select_int","get_selected") ;
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"items",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_items","_get_items") ;
- ADD_SIGNAL( MethodInfo("item_selected", PropertyInfo( Variant::INT,"ID") ) );
+ ClassDB::bind_method(D_METHOD("_selected"), &OptionButton::_selected);
+
+ ClassDB::bind_method(D_METHOD("add_item", "label", "id"), &OptionButton::add_item, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("add_icon_item", "texture:Texture", "label", "id"), &OptionButton::add_icon_item);
+ ClassDB::bind_method(D_METHOD("set_item_text", "idx", "text"), &OptionButton::set_item_text);
+ ClassDB::bind_method(D_METHOD("set_item_icon", "idx", "texture:Texture"), &OptionButton::set_item_icon);
+ ClassDB::bind_method(D_METHOD("set_item_disabled", "idx", "disabled"), &OptionButton::set_item_disabled);
+ ClassDB::bind_method(D_METHOD("set_item_ID", "idx", "id"), &OptionButton::set_item_ID);
+ ClassDB::bind_method(D_METHOD("set_item_metadata", "idx", "metadata"), &OptionButton::set_item_metadata);
+ ClassDB::bind_method(D_METHOD("get_item_text", "idx"), &OptionButton::get_item_text);
+ ClassDB::bind_method(D_METHOD("get_item_icon:Texture", "idx"), &OptionButton::get_item_icon);
+ ClassDB::bind_method(D_METHOD("get_item_ID", "idx"), &OptionButton::get_item_ID);
+ ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &OptionButton::get_item_metadata);
+ ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &OptionButton::is_item_disabled);
+ ClassDB::bind_method(D_METHOD("get_item_count"), &OptionButton::get_item_count);
+ ClassDB::bind_method(D_METHOD("add_separator"), &OptionButton::add_separator);
+ ClassDB::bind_method(D_METHOD("clear"), &OptionButton::clear);
+ ClassDB::bind_method(D_METHOD("select", "idx"), &OptionButton::select);
+ ClassDB::bind_method(D_METHOD("get_selected"), &OptionButton::get_selected);
+ ClassDB::bind_method(D_METHOD("get_selected_ID"), &OptionButton::get_selected_ID);
+ ClassDB::bind_method(D_METHOD("get_selected_metadata"), &OptionButton::get_selected_metadata);
+ ClassDB::bind_method(D_METHOD("remove_item", "idx"), &OptionButton::remove_item);
+ ClassDB::bind_method(D_METHOD("_select_int"), &OptionButton::_select_int);
+
+ ClassDB::bind_method(D_METHOD("_set_items"), &OptionButton::_set_items);
+ ClassDB::bind_method(D_METHOD("_get_items"), &OptionButton::_get_items);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "selected"), "_select_int", "get_selected");
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_items", "_get_items");
+ ADD_SIGNAL(MethodInfo("item_selected", PropertyInfo(Variant::INT, "ID")));
}
OptionButton::OptionButton() {
-
- popup = memnew( PopupMenu );
+ popup = memnew(PopupMenu);
popup->hide();
popup->set_as_toplevel(true);
add_child(popup);
- popup->connect("id_pressed", this,"_selected");
+ popup->connect("id_pressed", this, "_selected");
- current=-1;
+ current = -1;
set_text_align(ALIGN_LEFT);
}
-
OptionButton::~OptionButton() {
-
-
-
}
-
-
diff --git a/scene/gui/option_button.h b/scene/gui/option_button.h
index 681cb5a088..55a98cb50c 100644
--- a/scene/gui/option_button.h
+++ b/scene/gui/option_button.h
@@ -36,34 +36,34 @@
*/
class OptionButton : public Button {
- GDCLASS( OptionButton, Button );
+ GDCLASS(OptionButton, Button);
PopupMenu *popup;
int current;
void _selected(int p_which);
- void _select(int p_which,bool p_emit=false);
+ void _select(int p_which, bool p_emit = false);
void _select_int(int p_which);
Array _get_items() const;
- void _set_items(const Array& p_items);
+ void _set_items(const Array &p_items);
virtual void pressed();
-protected:
+protected:
Size2 get_minimum_size() const;
void _notification(int p_what);
static void _bind_methods();
-public:
- void add_icon_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID=-1);
- void add_item(const String& p_label,int p_ID=-1);
+public:
+ void add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID = -1);
+ void add_item(const String &p_label, int p_ID = -1);
- void set_item_text(int p_idx,const String& p_text);
- void set_item_icon(int p_idx,const Ref<Texture>& p_icon);
- void set_item_ID(int p_idx,int p_ID);
- void set_item_metadata(int p_idx,const Variant& p_metadata);
- void set_item_disabled(int p_idx,bool p_disabled);
+ void set_item_text(int p_idx, const String &p_text);
+ void set_item_icon(int p_idx, const Ref<Texture> &p_icon);
+ void set_item_ID(int p_idx, int p_ID);
+ void set_item_metadata(int p_idx, const Variant &p_metadata);
+ void set_item_disabled(int p_idx, bool p_disabled);
String get_item_text(int p_idx) const;
Ref<Texture> get_item_icon(int p_idx) const;
@@ -71,7 +71,6 @@ public:
Variant get_item_metadata(int p_idx) const;
bool is_item_disabled(int p_idx) const;
-
int get_item_count() const;
void add_separator();
@@ -89,7 +88,6 @@ public:
OptionButton();
~OptionButton();
-
};
#endif
diff --git a/scene/gui/panel.cpp b/scene/gui/panel.cpp
index c4b7199c3e..536f0baf73 100644
--- a/scene/gui/panel.cpp
+++ b/scene/gui/panel.cpp
@@ -31,11 +31,11 @@
void Panel::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
Ref<StyleBox> style = get_stylebox("panel");
- style->draw( ci, Rect2( Point2(), get_size() ) );
+ style->draw(ci, Rect2(Point2(), get_size()));
}
}
@@ -44,9 +44,5 @@ Panel::Panel() {
set_mouse_filter(MOUSE_FILTER_STOP);
}
-
-Panel::~Panel()
-{
+Panel::~Panel() {
}
-
-
diff --git a/scene/gui/panel.h b/scene/gui/panel.h
index 34c73960e7..3d2c0a3e98 100644
--- a/scene/gui/panel.h
+++ b/scene/gui/panel.h
@@ -33,18 +33,16 @@
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-class Panel : public Control{
+class Panel : public Control {
- GDCLASS(Panel,Control);
-protected:
+ GDCLASS(Panel, Control);
+protected:
void _notification(int p_what);
+
public:
Panel();
~Panel();
-
};
-
-
#endif
diff --git a/scene/gui/panel_container.cpp b/scene/gui/panel_container.cpp
index 48270d12c7..9dc7a6b32e 100644
--- a/scene/gui/panel_container.cpp
+++ b/scene/gui/panel_container.cpp
@@ -28,19 +28,17 @@
/*************************************************************************/
#include "panel_container.h"
-
Size2 PanelContainer::get_minimum_size() const {
Ref<StyleBox> style;
if (has_stylebox("panel"))
- style=get_stylebox("panel");
+ style = get_stylebox("panel");
else
- style=get_stylebox("panel","PanelContainer");
-
+ style = get_stylebox("panel", "PanelContainer");
Size2 ms;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
@@ -49,53 +47,47 @@ Size2 PanelContainer::get_minimum_size() const {
continue;
Size2 minsize = c->get_combined_minimum_size();
- ms.width = MAX(ms.width , minsize.width);
- ms.height = MAX(ms.height , minsize.height);
-
-
+ ms.width = MAX(ms.width, minsize.width);
+ ms.height = MAX(ms.height, minsize.height);
}
if (style.is_valid())
- ms+=style->get_minimum_size();
+ ms += style->get_minimum_size();
return ms;
-
}
void PanelContainer::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
Ref<StyleBox> style;
if (has_stylebox("panel"))
- style=get_stylebox("panel");
+ style = get_stylebox("panel");
else
- style=get_stylebox("panel","PanelContainer");
-
- style->draw( ci, Rect2( Point2(), get_size() ) );
+ style = get_stylebox("panel", "PanelContainer");
+ style->draw(ci, Rect2(Point2(), get_size()));
}
- if (p_what==NOTIFICATION_SORT_CHILDREN) {
+ if (p_what == NOTIFICATION_SORT_CHILDREN) {
Ref<StyleBox> style;
if (has_stylebox("panel"))
- style=get_stylebox("panel");
+ style = get_stylebox("panel");
else
- style=get_stylebox("panel","PanelContainer");
+ style = get_stylebox("panel", "PanelContainer");
Size2 size = get_size();
Point2 ofs;
if (style.is_valid()) {
- size-=style->get_minimum_size();
- ofs+=style->get_offset();
+ size -= style->get_minimum_size();
+ ofs += style->get_offset();
}
-
-
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
@@ -103,12 +95,10 @@ void PanelContainer::_notification(int p_what) {
if (c->is_set_as_toplevel())
continue;
- fit_child_in_rect(c,Rect2(ofs,size));
-
+ fit_child_in_rect(c, Rect2(ofs, size));
}
}
}
-PanelContainer::PanelContainer()
-{
+PanelContainer::PanelContainer() {
}
diff --git a/scene/gui/panel_container.h b/scene/gui/panel_container.h
index 86f390fdf3..13ed1c935c 100644
--- a/scene/gui/panel_container.h
+++ b/scene/gui/panel_container.h
@@ -33,13 +33,12 @@
class PanelContainer : public Container {
- GDCLASS( PanelContainer, Container );
+ GDCLASS(PanelContainer, Container);
protected:
-
void _notification(int p_what);
-public:
+public:
virtual Size2 get_minimum_size() const;
PanelContainer();
diff --git a/scene/gui/patch_9_rect.cpp b/scene/gui/patch_9_rect.cpp
index 6fb35f72e5..d0bd45e435 100644
--- a/scene/gui/patch_9_rect.cpp
+++ b/scene/gui/patch_9_rect.cpp
@@ -32,17 +32,17 @@
void NinePatchRect::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (texture.is_null())
return;
- Size2 s=get_size();
+ Size2 s = get_size();
RID ci = get_canvas_item();
- VS::get_singleton()->canvas_item_add_nine_patch(ci,Rect2(Point2(),s),region_rect,texture->get_rid(),Vector2(margin[MARGIN_LEFT],margin[MARGIN_TOP]),Vector2(margin[MARGIN_RIGHT],margin[MARGIN_BOTTOM]),VS::NINE_PATCH_STRETCH,VS::NINE_PATCH_STRETCH,draw_center);
+ VS::get_singleton()->canvas_item_add_nine_patch(ci, Rect2(Point2(), s), region_rect, texture->get_rid(), Vector2(margin[MARGIN_LEFT], margin[MARGIN_TOP]), Vector2(margin[MARGIN_RIGHT], margin[MARGIN_BOTTOM]), VS::NINE_PATCH_STRETCH, VS::NINE_PATCH_STRETCH, draw_center);
//draw_texture_rect(texture,Rect2(Point2(),s),false,modulate);
-/*
+ /*
Vector<Point2> points;
points.resize(4);
points[0]=Point2(0,0);
@@ -63,40 +63,37 @@ void NinePatchRect::_notification(int p_what) {
Size2 NinePatchRect::get_minimum_size() const {
- return Size2(margin[MARGIN_LEFT]+margin[MARGIN_RIGHT],margin[MARGIN_TOP]+margin[MARGIN_BOTTOM]);
+ return Size2(margin[MARGIN_LEFT] + margin[MARGIN_RIGHT], margin[MARGIN_TOP] + margin[MARGIN_BOTTOM]);
}
void NinePatchRect::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("set_texture","texture"), & NinePatchRect::set_texture );
- ClassDB::bind_method(D_METHOD("get_texture"), & NinePatchRect::get_texture );
- ClassDB::bind_method(D_METHOD("set_patch_margin","margin","value"), & NinePatchRect::set_patch_margin );
- ClassDB::bind_method(D_METHOD("get_patch_margin","margin"), & NinePatchRect::get_patch_margin );
- ClassDB::bind_method(D_METHOD("set_region_rect","rect"),&NinePatchRect::set_region_rect);
- ClassDB::bind_method(D_METHOD("get_region_rect"),&NinePatchRect::get_region_rect);
- ClassDB::bind_method(D_METHOD("set_draw_center","draw_center"), & NinePatchRect::set_draw_center );
- ClassDB::bind_method(D_METHOD("get_draw_center"), & NinePatchRect::get_draw_center );
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &NinePatchRect::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &NinePatchRect::get_texture);
+ ClassDB::bind_method(D_METHOD("set_patch_margin", "margin", "value"), &NinePatchRect::set_patch_margin);
+ ClassDB::bind_method(D_METHOD("get_patch_margin", "margin"), &NinePatchRect::get_patch_margin);
+ ClassDB::bind_method(D_METHOD("set_region_rect", "rect"), &NinePatchRect::set_region_rect);
+ ClassDB::bind_method(D_METHOD("get_region_rect"), &NinePatchRect::get_region_rect);
+ ClassDB::bind_method(D_METHOD("set_draw_center", "draw_center"), &NinePatchRect::set_draw_center);
+ ClassDB::bind_method(D_METHOD("get_draw_center"), &NinePatchRect::get_draw_center);
ADD_SIGNAL(MethodInfo("texture_changed"));
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture","get_texture") ;
- ADD_PROPERTYNO( PropertyInfo( Variant::BOOL, "draw_center"), "set_draw_center","get_draw_center") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect");
-
- ADD_GROUP("Patch Margin","patch_margin_");
- ADD_PROPERTYINZ( PropertyInfo( Variant::INT, "patch_margin_left",PROPERTY_HINT_RANGE,"0,16384,1"), "set_patch_margin","get_patch_margin",MARGIN_LEFT );
- ADD_PROPERTYINZ( PropertyInfo( Variant::INT, "patch_margin_top",PROPERTY_HINT_RANGE,"0,16384,1"), "set_patch_margin","get_patch_margin",MARGIN_TOP );
- ADD_PROPERTYINZ( PropertyInfo( Variant::INT, "patch_margin_right",PROPERTY_HINT_RANGE,"0,16384,1"), "set_patch_margin","get_patch_margin",MARGIN_RIGHT );
- ADD_PROPERTYINZ( PropertyInfo( Variant::INT, "patch_margin_bottom",PROPERTY_HINT_RANGE,"0,16384,1"), "set_patch_margin","get_patch_margin",MARGIN_BOTTOM );
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "get_draw_center");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
+ ADD_GROUP("Patch Margin", "patch_margin_");
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "patch_margin_left", PROPERTY_HINT_RANGE, "0,16384,1"), "set_patch_margin", "get_patch_margin", MARGIN_LEFT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "patch_margin_top", PROPERTY_HINT_RANGE, "0,16384,1"), "set_patch_margin", "get_patch_margin", MARGIN_TOP);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "patch_margin_right", PROPERTY_HINT_RANGE, "0,16384,1"), "set_patch_margin", "get_patch_margin", MARGIN_RIGHT);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "patch_margin_bottom", PROPERTY_HINT_RANGE, "0,16384,1"), "set_patch_margin", "get_patch_margin", MARGIN_BOTTOM);
}
+void NinePatchRect::set_texture(const Ref<Texture> &p_tex) {
-void NinePatchRect::set_texture(const Ref<Texture>& p_tex) {
-
- if (texture==p_tex)
+ if (texture == p_tex)
return;
- texture=p_tex;
+ texture = p_tex;
update();
/*
if (texture.is_valid())
@@ -111,12 +108,10 @@ Ref<Texture> NinePatchRect::get_texture() const {
return texture;
}
+void NinePatchRect::set_patch_margin(Margin p_margin, int p_size) {
-
-void NinePatchRect::set_patch_margin(Margin p_margin,int p_size) {
-
- ERR_FAIL_INDEX(p_margin,4);
- margin[p_margin]=p_size;
+ ERR_FAIL_INDEX(p_margin, 4);
+ margin[p_margin] = p_size;
update();
minimum_size_changed();
switch (p_margin) {
@@ -135,18 +130,18 @@ void NinePatchRect::set_patch_margin(Margin p_margin,int p_size) {
}
}
-int NinePatchRect::get_patch_margin(Margin p_margin) const{
+int NinePatchRect::get_patch_margin(Margin p_margin) const {
- ERR_FAIL_INDEX_V(p_margin,4,0);
+ ERR_FAIL_INDEX_V(p_margin, 4, 0);
return margin[p_margin];
}
-void NinePatchRect::set_region_rect(const Rect2& p_region_rect) {
+void NinePatchRect::set_region_rect(const Rect2 &p_region_rect) {
- if (region_rect==p_region_rect)
+ if (region_rect == p_region_rect)
return;
- region_rect=p_region_rect;
+ region_rect = p_region_rect;
item_rect_changed();
_change_notify("region_rect");
@@ -159,28 +154,25 @@ Rect2 NinePatchRect::get_region_rect() const {
void NinePatchRect::set_draw_center(bool p_draw) {
- draw_center=p_draw;
+ draw_center = p_draw;
update();
}
-bool NinePatchRect::get_draw_center() const{
+bool NinePatchRect::get_draw_center() const {
return draw_center;
}
NinePatchRect::NinePatchRect() {
-
- margin[MARGIN_LEFT]=0;
- margin[MARGIN_RIGHT]=0;
- margin[MARGIN_BOTTOM]=0;
- margin[MARGIN_TOP]=0;
+ margin[MARGIN_LEFT] = 0;
+ margin[MARGIN_RIGHT] = 0;
+ margin[MARGIN_BOTTOM] = 0;
+ margin[MARGIN_TOP] = 0;
set_mouse_filter(MOUSE_FILTER_IGNORE);
- draw_center=true;
+ draw_center = true;
}
-
-NinePatchRect::~NinePatchRect()
-{
+NinePatchRect::~NinePatchRect() {
}
diff --git a/scene/gui/patch_9_rect.h b/scene/gui/patch_9_rect.h
index b87f2f64ec..09663e62f6 100644
--- a/scene/gui/patch_9_rect.h
+++ b/scene/gui/patch_9_rect.h
@@ -35,27 +35,26 @@
*/
class NinePatchRect : public Control {
- GDCLASS(NinePatchRect,Control);
+ GDCLASS(NinePatchRect, Control);
bool draw_center;
int margin[4];
Rect2 region_rect;
Ref<Texture> texture;
-protected:
+protected:
void _notification(int p_what);
virtual Size2 get_minimum_size() const;
static void _bind_methods();
public:
-
- void set_texture(const Ref<Texture>& p_tex);
+ void set_texture(const Ref<Texture> &p_tex);
Ref<Texture> get_texture() const;
- void set_patch_margin(Margin p_margin,int p_size);
+ void set_patch_margin(Margin p_margin, int p_size);
int get_patch_margin(Margin p_margin) const;
- void set_region_rect(const Rect2& p_region_rect);
+ void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
void set_draw_center(bool p_enable);
@@ -63,6 +62,5 @@ public:
NinePatchRect();
~NinePatchRect();
-
};
#endif // PATCH_9_FRAME_H
diff --git a/scene/gui/popup.cpp b/scene/gui/popup.cpp
index 1f0daa99ba..52ad37e9ab 100644
--- a/scene/gui/popup.cpp
+++ b/scene/gui/popup.cpp
@@ -29,18 +29,14 @@
#include "popup.h"
#include "os/keyboard.h"
-
-
void Popup::_gui_input(InputEvent p_event) {
-
-
}
void Popup::_notification(int p_what) {
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
if (popped_up && !is_visible_in_tree()) {
- popped_up=false;
+ popped_up = false;
notification(NOTIFICATION_POPUP_HIDE);
emit_signal("popup_hide");
}
@@ -48,20 +44,18 @@ void Popup::_notification(int p_what) {
update_configuration_warning();
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
- //small helper to make editing of these easier in editor
+ if (p_what == NOTIFICATION_ENTER_TREE) {
+//small helper to make editing of these easier in editor
#ifdef TOOLS_ENABLED
if (get_tree()->is_editor_hint() && get_tree()->get_edited_scene_root() && get_tree()->get_edited_scene_root()->is_a_parent_of(this)) {
set_as_toplevel(false);
}
#endif
}
-
}
void Popup::_fix_size() {
-
#if 0
Point2 pos = get_pos();
Size2 size = get_size();
@@ -73,34 +67,32 @@ void Popup::_fix_size() {
Point2 window_size = get_viewport_rect().size;
#endif
- if (pos.x+size.width > window_size.width)
- pos.x=window_size.width-size.width;
- if (pos.x<0)
- pos.x=0;
-
- if (pos.y+size.height > window_size.height)
- pos.y=window_size.height-size.height;
- if (pos.y<0)
- pos.y=0;
+ if (pos.x + size.width > window_size.width)
+ pos.x = window_size.width - size.width;
+ if (pos.x < 0)
+ pos.x = 0;
+
+ if (pos.y + size.height > window_size.height)
+ pos.y = window_size.height - size.height;
+ if (pos.y < 0)
+ pos.y = 0;
#if 0
if (pos!=get_pos())
set_pos(pos);
#else
- if (pos!=get_pos())
+ if (pos != get_pos())
set_global_pos(pos);
#endif
-
}
-
void Popup::set_as_minsize() {
Size2 total_minsize;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (!c->is_visible())
@@ -108,10 +100,10 @@ void Popup::set_as_minsize() {
Size2 minsize = c->get_combined_minimum_size();
- for(int j=0;j<2;j++) {
+ for (int j = 0; j < 2; j++) {
- Margin m_beg = Margin(0+j);
- Margin m_end = Margin(2+j);
+ Margin m_beg = Margin(0 + j);
+ Margin m_end = Margin(2 + j);
float margin_begin = c->get_margin(m_beg);
float margin_end = c->get_margin(m_end);
@@ -119,29 +111,25 @@ void Popup::set_as_minsize() {
AnchorType anchor_end = c->get_anchor(m_end);
if (anchor_begin == ANCHOR_BEGIN)
- minsize[j]+=margin_begin;
+ minsize[j] += margin_begin;
if (anchor_end == ANCHOR_END)
- minsize[j]+=margin_end;
-
+ minsize[j] += margin_end;
}
- total_minsize.width = MAX( total_minsize.width, minsize.width );
- total_minsize.height = MAX( total_minsize.height, minsize.height );
+ total_minsize.width = MAX(total_minsize.width, minsize.width);
+ total_minsize.height = MAX(total_minsize.height, minsize.height);
}
set_size(total_minsize);
-
}
+void Popup::popup_centered_minsize(const Size2 &p_minsize) {
-void Popup::popup_centered_minsize(const Size2& p_minsize) {
-
-
- Size2 total_minsize=p_minsize;
+ Size2 total_minsize = p_minsize;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ Control *c = get_child(i)->cast_to<Control>();
if (!c)
continue;
if (!c->is_visible())
@@ -149,10 +137,10 @@ void Popup::popup_centered_minsize(const Size2& p_minsize) {
Size2 minsize = c->get_combined_minimum_size();
- for(int j=0;j<2;j++) {
+ for (int j = 0; j < 2; j++) {
- Margin m_beg = Margin(0+j);
- Margin m_end = Margin(2+j);
+ Margin m_beg = Margin(0 + j);
+ Margin m_end = Margin(2 + j);
float margin_begin = c->get_margin(m_beg);
float margin_end = c->get_margin(m_end);
@@ -160,33 +148,30 @@ void Popup::popup_centered_minsize(const Size2& p_minsize) {
AnchorType anchor_end = c->get_anchor(m_end);
if (anchor_begin == ANCHOR_BEGIN)
- minsize[j]+=margin_begin;
+ minsize[j] += margin_begin;
if (anchor_end == ANCHOR_END)
- minsize[j]+=margin_end;
-
+ minsize[j] += margin_end;
}
- total_minsize.width = MAX( total_minsize.width, minsize.width );
- total_minsize.height = MAX( total_minsize.height, minsize.height );
+ total_minsize.width = MAX(total_minsize.width, minsize.width);
+ total_minsize.height = MAX(total_minsize.height, minsize.height);
}
-
- popup_centered( total_minsize );
- popped_up=true;
-
+ popup_centered(total_minsize);
+ popped_up = true;
}
-void Popup::popup_centered(const Size2& p_size) {
+void Popup::popup_centered(const Size2 &p_size) {
Point2 window_size = get_viewport_rect().size;
emit_signal("about_to_show");
Rect2 rect;
- rect.size = p_size==Size2()?get_size():p_size;
+ rect.size = p_size == Size2() ? get_size() : p_size;
- rect.pos = ((window_size-rect.size)/2.0).floor();
- set_pos( rect.pos );
- set_size( rect.size );
+ rect.pos = ((window_size - rect.size) / 2.0).floor();
+ set_pos(rect.pos);
+ set_size(rect.size);
show_modal(exclusive);
_fix_size();
@@ -197,21 +182,19 @@ void Popup::popup_centered(const Size2& p_size) {
_post_popup();
notification(NOTIFICATION_POST_POPUP);
- popped_up=true;
+ popped_up = true;
}
void Popup::popup_centered_ratio(float p_screen_ratio) {
-
-
emit_signal("about_to_show");
Rect2 rect;
Point2 window_size = get_viewport_rect().size;
rect.size = (window_size * p_screen_ratio).floor();
- rect.pos = ((window_size-rect.size)/2.0).floor();
- set_pos( rect.pos );
- set_size( rect.size );
+ rect.pos = ((window_size - rect.size) / 2.0).floor();
+ set_pos(rect.pos);
+ set_size(rect.size);
show_modal(exclusive);
_fix_size();
@@ -222,11 +205,10 @@ void Popup::popup_centered_ratio(float p_screen_ratio) {
_post_popup();
notification(NOTIFICATION_POST_POPUP);
- popped_up=true;
-
+ popped_up = true;
}
-void Popup::popup(const Rect2& bounds) {
+void Popup::popup(const Rect2 &bounds) {
emit_signal("about_to_show");
show_modal(exclusive);
@@ -245,43 +227,40 @@ void Popup::popup(const Rect2& bounds) {
_post_popup();
notification(NOTIFICATION_POST_POPUP);
- popped_up=true;
+ popped_up = true;
}
void Popup::set_exclusive(bool p_exclusive) {
- exclusive=p_exclusive;
+ exclusive = p_exclusive;
}
-bool Popup::is_exclusive() const {
+bool Popup::is_exclusive() const {
return exclusive;
}
-
void Popup::_bind_methods() {
- ClassDB::bind_method(D_METHOD("popup_centered","size"),&Popup::popup_centered,DEFVAL(Size2()));
- ClassDB::bind_method(D_METHOD("popup_centered_ratio","ratio"),&Popup::popup_centered_ratio,DEFVAL(0.75));
- ClassDB::bind_method(D_METHOD("popup_centered_minsize","minsize"),&Popup::popup_centered_minsize,DEFVAL(Size2()));
- ClassDB::bind_method(D_METHOD("popup","bounds"),&Popup::popup,DEFVAL(Rect2()));
- ClassDB::bind_method(D_METHOD("set_exclusive","enable"),&Popup::set_exclusive);
- ClassDB::bind_method(D_METHOD("is_exclusive"),&Popup::is_exclusive);
- ADD_SIGNAL( MethodInfo("about_to_show") );
- ADD_SIGNAL( MethodInfo("popup_hide") );
- ADD_GROUP("Popup","popup_");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "popup_exclusive"), "set_exclusive","is_exclusive") ;
+ ClassDB::bind_method(D_METHOD("popup_centered", "size"), &Popup::popup_centered, DEFVAL(Size2()));
+ ClassDB::bind_method(D_METHOD("popup_centered_ratio", "ratio"), &Popup::popup_centered_ratio, DEFVAL(0.75));
+ ClassDB::bind_method(D_METHOD("popup_centered_minsize", "minsize"), &Popup::popup_centered_minsize, DEFVAL(Size2()));
+ ClassDB::bind_method(D_METHOD("popup", "bounds"), &Popup::popup, DEFVAL(Rect2()));
+ ClassDB::bind_method(D_METHOD("set_exclusive", "enable"), &Popup::set_exclusive);
+ ClassDB::bind_method(D_METHOD("is_exclusive"), &Popup::is_exclusive);
+ ADD_SIGNAL(MethodInfo("about_to_show"));
+ ADD_SIGNAL(MethodInfo("popup_hide"));
+ ADD_GROUP("Popup", "popup_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "popup_exclusive"), "set_exclusive", "is_exclusive");
BIND_CONSTANT(NOTIFICATION_POST_POPUP);
BIND_CONSTANT(NOTIFICATION_POPUP_HIDE);
-
-
}
Popup::Popup() {
set_as_toplevel(true);
- exclusive=false;
- popped_up=false;
+ exclusive = false;
+ popped_up = false;
hide();
}
@@ -294,9 +273,7 @@ String Popup::get_configuration_warning() const {
return String();
}
-Popup::~Popup()
-{
-
+Popup::~Popup() {
}
void PopupPanel::set_child_rect(Control *p_child) {
@@ -304,21 +281,18 @@ void PopupPanel::set_child_rect(Control *p_child) {
Ref<StyleBox> p = get_stylebox("panel");
p_child->set_area_as_parent_rect();
- for(int i=0;i<4;i++) {
- p_child->set_margin(Margin(i),p->get_margin(Margin(i)));
+ for (int i = 0; i < 4; i++) {
+ p_child->set_margin(Margin(i), p->get_margin(Margin(i)));
}
}
void PopupPanel::_notification(int p_what) {
+ if (p_what == NOTIFICATION_DRAW) {
- if (p_what==NOTIFICATION_DRAW) {
-
- get_stylebox("panel")->draw(get_canvas_item(),Rect2(Point2(),get_size()));
+ get_stylebox("panel")->draw(get_canvas_item(), Rect2(Point2(), get_size()));
}
}
PopupPanel::PopupPanel() {
-
-
}
diff --git a/scene/gui/popup.h b/scene/gui/popup.h
index 4e4c8b0292..d80daaad10 100644
--- a/scene/gui/popup.h
+++ b/scene/gui/popup.h
@@ -36,56 +36,50 @@
*/
class Popup : public Control {
- GDCLASS( Popup, Control );
+ GDCLASS(Popup, Control);
bool exclusive;
bool popped_up;
protected:
-
virtual void _post_popup() {}
void _gui_input(InputEvent p_event);
void _notification(int p_what);
virtual void _fix_size();
static void _bind_methods();
-public:
+public:
enum {
- NOTIFICATION_POST_POPUP=80,
- NOTIFICATION_POPUP_HIDE=81
+ NOTIFICATION_POST_POPUP = 80,
+ NOTIFICATION_POPUP_HIDE = 81
};
void set_exclusive(bool p_exclusive);
bool is_exclusive() const;
- void popup_centered_ratio(float p_screen_ratio=0.75);
- void popup_centered(const Size2& p_size=Size2());
- void popup_centered_minsize(const Size2& p_minsize=Size2());
+ void popup_centered_ratio(float p_screen_ratio = 0.75);
+ void popup_centered(const Size2 &p_size = Size2());
+ void popup_centered_minsize(const Size2 &p_minsize = Size2());
void set_as_minsize();
- virtual void popup(const Rect2& p_bounds=Rect2());
+ virtual void popup(const Rect2 &p_bounds = Rect2());
virtual String get_configuration_warning() const;
Popup();
~Popup();
-
};
class PopupPanel : public Popup {
- GDCLASS(PopupPanel,Popup);
-
+ GDCLASS(PopupPanel, Popup);
protected:
-
void _notification(int p_what);
-public:
+public:
void set_child_rect(Control *p_child);
PopupPanel();
-
};
-
#endif
diff --git a/scene/gui/popup_menu.cpp b/scene/gui/popup_menu.cpp
index 884cf0312a..a2a670fa1f 100644
--- a/scene/gui/popup_menu.cpp
+++ b/scene/gui/popup_menu.cpp
@@ -27,14 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "popup_menu.h"
-#include "print_string.h"
+#include "os/input.h"
#include "os/keyboard.h"
+#include "print_string.h"
#include "translation.h"
-#include "os/input.h"
String PopupMenu::_get_accel_text(int p_item) const {
- ERR_FAIL_INDEX_V(p_item,items.size(),String());
+ ERR_FAIL_INDEX_V(p_item, items.size(), String());
if (items[p_item].shortcut.is_valid())
return items[p_item].shortcut->get_as_text();
@@ -61,7 +61,6 @@ String PopupMenu::_get_accel_text(int p_item) const {
*/
}
-
Size2 PopupMenu::get_minimum_size() const {
int vseparation = get_constant("vseparation");
@@ -70,123 +69,114 @@ Size2 PopupMenu::get_minimum_size() const {
Size2 minsize = get_stylebox("panel")->get_minimum_size();
Ref<Font> font = get_font("font");
- float max_w=0;
+ float max_w = 0;
int font_h = font->get_height();
int check_w = get_icon("checked")->get_width();
- int accel_max_w=0;
+ int accel_max_w = 0;
- for (int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
Size2 size;
if (!items[i].icon.is_null()) {
Size2 icon_size = items[i].icon->get_size();
- size.height = MAX( icon_size.height, font_h );
- size.width+=icon_size.width;
- size.width+=hseparation;
+ size.height = MAX(icon_size.height, font_h);
+ size.width += icon_size.width;
+ size.width += hseparation;
} else {
- size.height=font_h;
+ size.height = font_h;
}
- size.width+=items[i].h_ofs;
+ size.width += items[i].h_ofs;
if (items[i].checkable) {
- size.width+=check_w+hseparation;
+ size.width += check_w + hseparation;
}
String text = items[i].shortcut.is_valid() ? String(tr(items[i].shortcut->get_name())) : items[i].xl_text;
- size.width+=font->get_string_size(text).width;
- if (i>0)
- size.height+=vseparation;
+ size.width += font->get_string_size(text).width;
+ if (i > 0)
+ size.height += vseparation;
if (items[i].accel || (items[i].shortcut.is_valid() && items[i].shortcut->is_valid())) {
- int accel_w = hseparation*2;
- accel_w+=font->get_string_size(_get_accel_text(i)).width;
- accel_max_w = MAX( accel_w, accel_max_w );
+ int accel_w = hseparation * 2;
+ accel_w += font->get_string_size(_get_accel_text(i)).width;
+ accel_max_w = MAX(accel_w, accel_max_w);
}
-
- minsize.height+=size.height;
- max_w = MAX( max_w, size.width );
-
+ minsize.height += size.height;
+ max_w = MAX(max_w, size.width);
}
- minsize.width+=max_w+accel_max_w;
+ minsize.width += max_w + accel_max_w;
return minsize;
}
-int PopupMenu::_get_mouse_over(const Point2& p_over) const {
-
+int PopupMenu::_get_mouse_over(const Point2 &p_over) const {
- if (p_over.x<0 || p_over.x>=get_size().width)
+ if (p_over.x < 0 || p_over.x >= get_size().width)
return -1;
Ref<StyleBox> style = get_stylebox("panel");
- Point2 ofs=style->get_offset();
-
+ Point2 ofs = style->get_offset();
- if (ofs.y>p_over.y)
+ if (ofs.y > p_over.y)
return -1;
-
Ref<Font> font = get_font("font");
int vseparation = get_constant("vseparation");
//int hseparation = get_constant("hseparation");
- float font_h=font->get_height();
-
+ float font_h = font->get_height();
- for (int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
- if (i>0)
- ofs.y+=vseparation;
+ if (i > 0)
+ ofs.y += vseparation;
float h;
if (!items[i].icon.is_null()) {
Size2 icon_size = items[i].icon->get_size();
- h = MAX( icon_size.height, font_h );
+ h = MAX(icon_size.height, font_h);
} else {
- h=font_h;
+ h = font_h;
}
- ofs.y+=h;
+ ofs.y += h;
if (p_over.y < ofs.y) {
return i;
}
}
return -1;
-
}
-
void PopupMenu::_activate_submenu(int over) {
- Node* n = get_node(items[over].submenu);
- ERR_EXPLAIN("item subnode does not exist: "+items[over].submenu);
+ Node *n = get_node(items[over].submenu);
+ ERR_EXPLAIN("item subnode does not exist: " + items[over].submenu);
ERR_FAIL_COND(!n);
Popup *pm = n->cast_to<Popup>();
- ERR_EXPLAIN("item subnode is not a Popup: "+items[over].submenu);
+ ERR_EXPLAIN("item subnode is not a Popup: " + items[over].submenu);
ERR_FAIL_COND(!pm);
if (pm->is_visible_in_tree())
return; //already visible!
-
Point2 p = get_global_pos();
- Rect2 pr(p,get_size());
+ Rect2 pr(p, get_size());
Ref<StyleBox> style = get_stylebox("panel");
- Point2 pos = p+Point2(get_size().width,items[over]._ofs_cache-style->get_offset().y);
+ Point2 pos = p + Point2(get_size().width, items[over]._ofs_cache - style->get_offset().y);
Size2 size = pm->get_size();
// fix pos
- if (pos.x+size.width > get_viewport_rect().size.width)
- pos.x=p.x-size.width;
+ if (pos.x + size.width > get_viewport_rect().size.width)
+ pos.x = p.x - size.width;
pm->set_pos(pos);
pm->popup();
@@ -194,52 +184,45 @@ void PopupMenu::_activate_submenu(int over) {
PopupMenu *pum = pm->cast_to<PopupMenu>();
if (pum) {
- pr.pos-=pum->get_global_pos();
+ pr.pos -= pum->get_global_pos();
pum->clear_autohide_areas();
- pum->add_autohide_area(Rect2(pr.pos.x,pr.pos.y,pr.size.x,items[over]._ofs_cache));
- if (over<items.size()-1) {
- int from = items[over+1]._ofs_cache;
- pum->add_autohide_area(Rect2(pr.pos.x,pr.pos.y+from,pr.size.x,pr.size.y-from));
+ pum->add_autohide_area(Rect2(pr.pos.x, pr.pos.y, pr.size.x, items[over]._ofs_cache));
+ if (over < items.size() - 1) {
+ int from = items[over + 1]._ofs_cache;
+ pum->add_autohide_area(Rect2(pr.pos.x, pr.pos.y + from, pr.size.x, pr.size.y - from));
}
-
}
-
}
void PopupMenu::_submenu_timeout() {
- if (mouse_over==submenu_over) {
+ if (mouse_over == submenu_over) {
_activate_submenu(mouse_over);
- submenu_over=-1;
+ submenu_over = -1;
}
}
-
void PopupMenu::_gui_input(const InputEvent &p_event) {
- switch( p_event.type) {
+ switch (p_event.type) {
case InputEvent::KEY: {
-
if (!p_event.key.pressed)
break;
- switch(p_event.key.scancode) {
-
+ switch (p_event.key.scancode) {
case KEY_DOWN: {
+ for (int i = mouse_over + 1; i < items.size(); i++) {
- for(int i=mouse_over+1;i<items.size();i++) {
-
- if (i<0 || i>=items.size())
+ if (i < 0 || i >= items.size())
continue;
if (!items[i].separator && !items[i].disabled) {
-
- mouse_over=i;
+ mouse_over = i;
update();
break;
}
@@ -247,49 +230,38 @@ void PopupMenu::_gui_input(const InputEvent &p_event) {
} break;
case KEY_UP: {
+ for (int i = mouse_over - 1; i >= 0; i--) {
- for(int i=mouse_over-1;i>=0;i--) {
-
- if (i<0 || i>=items.size())
+ if (i < 0 || i >= items.size())
continue;
-
if (!items[i].separator && !items[i].disabled) {
-
- mouse_over=i;
- update();
- break;
+ mouse_over = i;
+ update();
+ break;
}
}
} break;
case KEY_RETURN:
case KEY_ENTER: {
- if (mouse_over>=0 && mouse_over<items.size() && !items[mouse_over].separator) {
-
+ if (mouse_over >= 0 && mouse_over < items.size() && !items[mouse_over].separator) {
activate_item(mouse_over);
-
}
} break;
}
-
-
-
-
} break;
case InputEvent::MOUSE_BUTTON: {
-
- const InputEventMouseButton &b=p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
if (b.pressed)
break;
- switch(b.button_index) {
-
+ switch (b.button_index) {
case BUTTON_WHEEL_DOWN: {
@@ -299,15 +271,15 @@ void PopupMenu::_gui_input(const InputEvent &p_event) {
Ref<Font> font = get_font("font");
Point2 pos = get_pos();
- int s = (vseparation+font->get_height())*3;
- pos.y-=s;
+ int s = (vseparation + font->get_height()) * 3;
+ pos.y -= s;
set_pos(pos);
//update hover
InputEvent ie;
- ie.type=InputEvent::MOUSE_MOTION;
- ie.mouse_motion.x=b.x;
- ie.mouse_motion.y=b.y+s;
+ ie.type = InputEvent::MOUSE_MOTION;
+ ie.mouse_motion.x = b.x;
+ ie.mouse_motion.y = b.y + s;
_gui_input(ie);
}
} break;
@@ -319,29 +291,27 @@ void PopupMenu::_gui_input(const InputEvent &p_event) {
Ref<Font> font = get_font("font");
Point2 pos = get_pos();
- int s = (vseparation+font->get_height())*3;
- pos.y+=s;
+ int s = (vseparation + font->get_height()) * 3;
+ pos.y += s;
set_pos(pos);
//update hover
InputEvent ie;
- ie.type=InputEvent::MOUSE_MOTION;
- ie.mouse_motion.x=b.x;
- ie.mouse_motion.y=b.y-s;
+ ie.type = InputEvent::MOUSE_MOTION;
+ ie.mouse_motion.x = b.x;
+ ie.mouse_motion.y = b.y - s;
_gui_input(ie);
-
-
}
} break;
case BUTTON_LEFT: {
- int over=_get_mouse_over(Point2(b.x,b.y));
+ int over = _get_mouse_over(Point2(b.x, b.y));
if (invalidated_click) {
- invalidated_click=false;
+ invalidated_click = false;
break;
}
- if (over<0) {
+ if (over < 0) {
hide();
break; //non-activable
}
@@ -349,7 +319,7 @@ void PopupMenu::_gui_input(const InputEvent &p_event) {
if (items[over].separator || items[over].disabled)
break;
- if (items[over].submenu!="") {
+ if (items[over].submenu != "") {
_activate_submenu(over);
return;
@@ -363,52 +333,48 @@ void PopupMenu::_gui_input(const InputEvent &p_event) {
} break;
case InputEvent::MOUSE_MOTION: {
-
if (invalidated_click) {
- moved+=Vector2(p_event.mouse_motion.relative_x,p_event.mouse_motion.relative_y);
- if (moved.length()>4)
- invalidated_click=false;
-
+ moved += Vector2(p_event.mouse_motion.relative_x, p_event.mouse_motion.relative_y);
+ if (moved.length() > 4)
+ invalidated_click = false;
}
- const InputEventMouseMotion &m=p_event.mouse_motion;
- for(List<Rect2>::Element *E=autohide_areas.front();E;E=E->next()) {
+ const InputEventMouseMotion &m = p_event.mouse_motion;
+ for (List<Rect2>::Element *E = autohide_areas.front(); E; E = E->next()) {
- if (!Rect2(Point2(),get_size()).has_point(Point2(m.x,m.y)) && E->get().has_point(Point2(m.x,m.y))) {
+ if (!Rect2(Point2(), get_size()).has_point(Point2(m.x, m.y)) && E->get().has_point(Point2(m.x, m.y))) {
call_deferred("hide");
return;
}
}
- int over=_get_mouse_over(Point2(m.x,m.y));
- int id = (over<0 || items[over].separator || items[over].disabled)?-1:(items[over].ID>=0?items[over].ID:over);
+ int over = _get_mouse_over(Point2(m.x, m.y));
+ int id = (over < 0 || items[over].separator || items[over].disabled) ? -1 : (items[over].ID >= 0 ? items[over].ID : over);
- if (id<0) {
- mouse_over=-1;
+ if (id < 0) {
+ mouse_over = -1;
update();
break;
}
- if (items[over].submenu!="" && submenu_over!=over) {
- submenu_over=over;
+ if (items[over].submenu != "" && submenu_over != over) {
+ submenu_over = over;
submenu_timer->start();
}
- if (over!=mouse_over) {
- mouse_over=over;
+ if (over != mouse_over) {
+ mouse_over = over;
update();
}
} break;
-
}
}
-
-bool PopupMenu::has_point(const Point2& p_point) const {
+bool PopupMenu::has_point(const Point2 &p_point) const {
if (parent_rect.has_point(p_point))
return true;
- for(const List<Rect2>::Element *E=autohide_areas.front();E;E=E->next()) {
+ for (const List<Rect2>::Element *E = autohide_areas.front(); E; E = E->next()) {
if (E->get().has_point(p_point))
return true;
@@ -419,12 +385,12 @@ bool PopupMenu::has_point(const Point2& p_point) const {
void PopupMenu::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_TRANSLATION_CHANGED: {
- for(int i=0;i<items.size();i++) {
- items[i].xl_text=XL_MESSAGE(items[i].text);
+ for (int i = 0; i < items.size(); i++) {
+ items[i].xl_text = XL_MESSAGE(items[i].text);
}
minimum_size_changed();
@@ -434,95 +400,92 @@ void PopupMenu::_notification(int p_what) {
case NOTIFICATION_DRAW: {
RID ci = get_canvas_item();
- Size2 size=get_size();
+ Size2 size = get_size();
Ref<StyleBox> style = get_stylebox("panel");
Ref<StyleBox> hover = get_stylebox("hover");
Ref<Font> font = get_font("font");
Ref<Texture> check = get_icon("checked");
Ref<Texture> uncheck = get_icon("unchecked");
- Ref<Texture> submenu= get_icon("submenu");
+ Ref<Texture> submenu = get_icon("submenu");
Ref<StyleBox> separator = get_stylebox("separator");
- style->draw( ci, Rect2( Point2(), get_size() ) );
- Point2 ofs=style->get_offset();
+ style->draw(ci, Rect2(Point2(), get_size()));
+ Point2 ofs = style->get_offset();
int vseparation = get_constant("vseparation");
int hseparation = get_constant("hseparation");
Color font_color = get_color("font_color");
Color font_color_disabled = get_color("font_color_disabled");
Color font_color_accel = get_color("font_color_accel");
Color font_color_hover = get_color("font_color_hover");
- float font_h=font->get_height();
+ float font_h = font->get_height();
- for (int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
- if (i>0)
- ofs.y+=vseparation;
- Point2 item_ofs=ofs;
+ if (i > 0)
+ ofs.y += vseparation;
+ Point2 item_ofs = ofs;
float h;
Size2 icon_size;
- item_ofs.x+=items[i].h_ofs;
+ item_ofs.x += items[i].h_ofs;
if (!items[i].icon.is_null()) {
icon_size = items[i].icon->get_size();
- h = MAX( icon_size.height, font_h );
+ h = MAX(icon_size.height, font_h);
} else {
- h=font_h;
+ h = font_h;
}
- if (i==mouse_over) {
+ if (i == mouse_over) {
- hover->draw(ci, Rect2( item_ofs+Point2(-hseparation,-vseparation), Size2( get_size().width - style->get_minimum_size().width + hseparation*2, h+vseparation*2 ) ));
+ hover->draw(ci, Rect2(item_ofs + Point2(-hseparation, -vseparation), Size2(get_size().width - style->get_minimum_size().width + hseparation * 2, h + vseparation * 2)));
}
if (items[i].separator) {
- int sep_h=separator->get_center_size().height+separator->get_minimum_size().height;
- separator->draw(ci, Rect2( item_ofs+Point2(0,Math::floor((h-sep_h)/2.0)), Size2( get_size().width - style->get_minimum_size().width , sep_h ) ));
-
+ int sep_h = separator->get_center_size().height + separator->get_minimum_size().height;
+ separator->draw(ci, Rect2(item_ofs + Point2(0, Math::floor((h - sep_h) / 2.0)), Size2(get_size().width - style->get_minimum_size().width, sep_h)));
}
if (items[i].checkable) {
if (items[i].checked)
- check->draw(ci, item_ofs+Point2(0,Math::floor((h-check->get_height())/2.0)));
+ check->draw(ci, item_ofs + Point2(0, Math::floor((h - check->get_height()) / 2.0)));
else
- uncheck->draw(ci, item_ofs+Point2(0,Math::floor((h-check->get_height())/2.0)));
+ uncheck->draw(ci, item_ofs + Point2(0, Math::floor((h - check->get_height()) / 2.0)));
- item_ofs.x+=check->get_width()+hseparation;
+ item_ofs.x += check->get_width() + hseparation;
}
if (!items[i].icon.is_null()) {
- items[i].icon->draw( ci, item_ofs+Point2(0,Math::floor((h-icon_size.height)/2.0)));
- item_ofs.x+=items[i].icon->get_width();
- item_ofs.x+=hseparation;
+ items[i].icon->draw(ci, item_ofs + Point2(0, Math::floor((h - icon_size.height) / 2.0)));
+ item_ofs.x += items[i].icon->get_width();
+ item_ofs.x += hseparation;
}
- if (items[i].submenu!="") {
- submenu->draw( ci, Point2(size.width - style->get_margin(MARGIN_RIGHT) - submenu->get_width(),item_ofs.y+Math::floor(h-submenu->get_height())/2));
+ if (items[i].submenu != "") {
+ submenu->draw(ci, Point2(size.width - style->get_margin(MARGIN_RIGHT) - submenu->get_width(), item_ofs.y + Math::floor(h - submenu->get_height()) / 2));
}
- item_ofs.y+=font->get_ascent();
+ item_ofs.y += font->get_ascent();
String text = items[i].shortcut.is_valid() ? String(tr(items[i].shortcut->get_name())) : items[i].xl_text;
if (!items[i].separator) {
- font->draw(ci,item_ofs+Point2(0,Math::floor((h-font_h)/2.0)),text,items[i].disabled?font_color_disabled:(i==mouse_over?font_color_hover:font_color));
+ font->draw(ci, item_ofs + Point2(0, Math::floor((h - font_h) / 2.0)), text, items[i].disabled ? font_color_disabled : (i == mouse_over ? font_color_hover : font_color));
}
if (items[i].accel || (items[i].shortcut.is_valid() && items[i].shortcut->is_valid())) {
//accelerator
String text = _get_accel_text(i);
- item_ofs.x=size.width-style->get_margin(MARGIN_RIGHT)-font->get_string_size(text).width;
- font->draw(ci,item_ofs+Point2(0,Math::floor((h-font_h)/2.0)),text,i==mouse_over?font_color_hover:font_color_accel);
-
+ item_ofs.x = size.width - style->get_margin(MARGIN_RIGHT) - font->get_string_size(text).width;
+ font->draw(ci, item_ofs + Point2(0, Math::floor((h - font_h) / 2.0)), text, i == mouse_over ? font_color_hover : font_color_accel);
}
- items[i]._ofs_cache=ofs.y;
-
- ofs.y+=h;
+ items[i]._ofs_cache = ofs.y;
+ ofs.y += h;
}
} break;
@@ -532,255 +495,243 @@ void PopupMenu::_notification(int p_what) {
} break;
case NOTIFICATION_MOUSE_EXIT: {
- if (mouse_over>=0) {
- mouse_over=-1;
+ if (mouse_over >= 0) {
+ mouse_over = -1;
update();
}
} break;
}
}
-
-void PopupMenu::add_icon_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID,uint32_t p_accel) {
+void PopupMenu::add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID, uint32_t p_accel) {
Item item;
- item.icon=p_icon;
- item.text=p_label;
- item.xl_text=XL_MESSAGE(p_label);
- item.accel=p_accel;
- item.ID=p_ID;
+ item.icon = p_icon;
+ item.text = p_label;
+ item.xl_text = XL_MESSAGE(p_label);
+ item.accel = p_accel;
+ item.ID = p_ID;
items.push_back(item);
update();
}
-void PopupMenu::add_item(const String& p_label,int p_ID,uint32_t p_accel) {
+void PopupMenu::add_item(const String &p_label, int p_ID, uint32_t p_accel) {
Item item;
- item.text=p_label;
- item.xl_text=XL_MESSAGE(p_label);
- item.accel=p_accel;
- item.ID=p_ID;
+ item.text = p_label;
+ item.xl_text = XL_MESSAGE(p_label);
+ item.accel = p_accel;
+ item.ID = p_ID;
items.push_back(item);
update();
}
-void PopupMenu::add_submenu_item(const String& p_label, const String& p_submenu,int p_ID){
+void PopupMenu::add_submenu_item(const String &p_label, const String &p_submenu, int p_ID) {
Item item;
- item.text=p_label;
- item.xl_text=XL_MESSAGE(p_label);
- item.ID=p_ID;
- item.submenu=p_submenu;
+ item.text = p_label;
+ item.xl_text = XL_MESSAGE(p_label);
+ item.ID = p_ID;
+ item.submenu = p_submenu;
items.push_back(item);
update();
}
-void PopupMenu::add_icon_check_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID,uint32_t p_accel) {
+void PopupMenu::add_icon_check_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID, uint32_t p_accel) {
Item item;
- item.icon=p_icon;
- item.text=p_label;
- item.xl_text=XL_MESSAGE(p_label);
- item.accel=p_accel;
- item.ID=p_ID;
- item.checkable=true;
+ item.icon = p_icon;
+ item.text = p_label;
+ item.xl_text = XL_MESSAGE(p_label);
+ item.accel = p_accel;
+ item.ID = p_ID;
+ item.checkable = true;
items.push_back(item);
update();
}
-void PopupMenu::add_check_item(const String& p_label,int p_ID,uint32_t p_accel) {
+void PopupMenu::add_check_item(const String &p_label, int p_ID, uint32_t p_accel) {
Item item;
- item.text=p_label;
- item.xl_text=XL_MESSAGE(p_label);
- item.accel=p_accel;
- item.ID=p_ID;
- item.checkable=true;
+ item.text = p_label;
+ item.xl_text = XL_MESSAGE(p_label);
+ item.accel = p_accel;
+ item.ID = p_ID;
+ item.checkable = true;
items.push_back(item);
update();
}
-
-void PopupMenu::add_icon_shortcut(const Ref<Texture>& p_icon, const Ref<ShortCut>& p_shortcut, int p_ID, bool p_global) {
+void PopupMenu::add_icon_shortcut(const Ref<Texture> &p_icon, const Ref<ShortCut> &p_shortcut, int p_ID, bool p_global) {
ERR_FAIL_COND(p_shortcut.is_null());
_ref_shortcut(p_shortcut);
Item item;
- item.ID=p_ID;
- item.icon=p_icon;
- item.shortcut=p_shortcut;
- item.shortcut_is_global=p_global;
+ item.ID = p_ID;
+ item.icon = p_icon;
+ item.shortcut = p_shortcut;
+ item.shortcut_is_global = p_global;
items.push_back(item);
update();
-
}
-void PopupMenu::add_shortcut(const Ref<ShortCut>& p_shortcut, int p_ID, bool p_global){
+void PopupMenu::add_shortcut(const Ref<ShortCut> &p_shortcut, int p_ID, bool p_global) {
ERR_FAIL_COND(p_shortcut.is_null());
_ref_shortcut(p_shortcut);
Item item;
- item.ID=p_ID;
- item.shortcut=p_shortcut;
- item.shortcut_is_global=p_global;
+ item.ID = p_ID;
+ item.shortcut = p_shortcut;
+ item.shortcut_is_global = p_global;
items.push_back(item);
update();
-
}
-void PopupMenu::add_icon_check_shortcut(const Ref<Texture>& p_icon, const Ref<ShortCut>& p_shortcut, int p_ID, bool p_global){
+void PopupMenu::add_icon_check_shortcut(const Ref<Texture> &p_icon, const Ref<ShortCut> &p_shortcut, int p_ID, bool p_global) {
ERR_FAIL_COND(p_shortcut.is_null());
_ref_shortcut(p_shortcut);
Item item;
- item.ID=p_ID;
- item.shortcut=p_shortcut;
- item.checkable=true;
- item.icon=p_icon;
- item.shortcut_is_global=p_global;
+ item.ID = p_ID;
+ item.shortcut = p_shortcut;
+ item.checkable = true;
+ item.icon = p_icon;
+ item.shortcut_is_global = p_global;
items.push_back(item);
update();
}
-void PopupMenu::add_check_shortcut(const Ref<ShortCut>& p_shortcut, int p_ID, bool p_global){
+void PopupMenu::add_check_shortcut(const Ref<ShortCut> &p_shortcut, int p_ID, bool p_global) {
ERR_FAIL_COND(p_shortcut.is_null());
_ref_shortcut(p_shortcut);
Item item;
- item.ID=p_ID;
- item.shortcut=p_shortcut;
- item.shortcut_is_global=p_global;
- item.checkable=true;
+ item.ID = p_ID;
+ item.shortcut = p_shortcut;
+ item.shortcut_is_global = p_global;
+ item.checkable = true;
items.push_back(item);
update();
}
-void PopupMenu::set_item_text(int p_idx,const String& p_text) {
+void PopupMenu::set_item_text(int p_idx, const String &p_text) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].text=p_text;
- items[p_idx].xl_text=XL_MESSAGE(p_text);
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].text = p_text;
+ items[p_idx].xl_text = XL_MESSAGE(p_text);
update();
-
}
-void PopupMenu::set_item_icon(int p_idx,const Ref<Texture>& p_icon) {
+void PopupMenu::set_item_icon(int p_idx, const Ref<Texture> &p_icon) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].icon=p_icon;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].icon = p_icon;
update();
-
}
-void PopupMenu::set_item_checked(int p_idx,bool p_checked) {
+void PopupMenu::set_item_checked(int p_idx, bool p_checked) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
- items[p_idx].checked=p_checked;
+ items[p_idx].checked = p_checked;
update();
}
-void PopupMenu::set_item_ID(int p_idx,int p_ID) {
+void PopupMenu::set_item_ID(int p_idx, int p_ID) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].ID=p_ID;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].ID = p_ID;
update();
}
-void PopupMenu::set_item_accelerator(int p_idx,uint32_t p_accel) {
+void PopupMenu::set_item_accelerator(int p_idx, uint32_t p_accel) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].accel=p_accel;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].accel = p_accel;
update();
-
}
+void PopupMenu::set_item_metadata(int p_idx, const Variant &p_meta) {
-void PopupMenu::set_item_metadata(int p_idx,const Variant& p_meta) {
-
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].metadata=p_meta;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].metadata = p_meta;
update();
}
-void PopupMenu::set_item_disabled(int p_idx,bool p_disabled) {
+void PopupMenu::set_item_disabled(int p_idx, bool p_disabled) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].disabled=p_disabled;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].disabled = p_disabled;
update();
}
-void PopupMenu::set_item_submenu(int p_idx, const String& p_submenu) {
+void PopupMenu::set_item_submenu(int p_idx, const String &p_submenu) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].submenu=p_submenu;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].submenu = p_submenu;
update();
}
void PopupMenu::toggle_item_checked(int p_idx) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
items[p_idx].checked = !items[p_idx].checked;
update();
}
String PopupMenu::get_item_text(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, items.size(), "");
return items[p_idx].text;
-
}
Ref<Texture> PopupMenu::get_item_icon(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture>());
return items[p_idx].icon;
}
-
uint32_t PopupMenu::get_item_accelerator(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),0);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), 0);
return items[p_idx].accel;
-
}
Variant PopupMenu::get_item_metadata(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Variant());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Variant());
return items[p_idx].metadata;
-
}
bool PopupMenu::is_item_disabled(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].disabled;
}
bool PopupMenu::is_item_checked(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].checked;
}
int PopupMenu::get_item_ID(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),0);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), 0);
return items[p_idx].ID;
}
int PopupMenu::get_item_index(int p_ID) const {
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
- if (items[i].ID==p_ID)
+ if (items[i].ID == p_ID)
return i;
}
@@ -789,79 +740,72 @@ int PopupMenu::get_item_index(int p_ID) const {
String PopupMenu::get_item_submenu(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, items.size(), "");
return items[p_idx].submenu;
}
String PopupMenu::get_item_tooltip(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),"");
+ ERR_FAIL_INDEX_V(p_idx, items.size(), "");
return items[p_idx].tooltip;
}
Ref<ShortCut> PopupMenu::get_item_shortcut(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),Ref<ShortCut>());
+ ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<ShortCut>());
return items[p_idx].shortcut;
}
void PopupMenu::set_item_as_separator(int p_idx, bool p_separator) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].separator=p_separator;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].separator = p_separator;
update();
-
}
bool PopupMenu::is_item_separator(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].separator;
}
-
void PopupMenu::set_item_as_checkable(int p_idx, bool p_checkable) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].checkable=p_checkable;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].checkable = p_checkable;
update();
-
}
-void PopupMenu::set_item_tooltip(int p_idx,const String& p_tooltip) {
+void PopupMenu::set_item_tooltip(int p_idx, const String &p_tooltip) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].tooltip=p_tooltip;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].tooltip = p_tooltip;
update();
}
-void PopupMenu::set_item_shortcut(int p_idx, const Ref<ShortCut>& p_shortcut, bool p_global) {
- ERR_FAIL_INDEX(p_idx,items.size());
+void PopupMenu::set_item_shortcut(int p_idx, const Ref<ShortCut> &p_shortcut, bool p_global) {
+ ERR_FAIL_INDEX(p_idx, items.size());
if (items[p_idx].shortcut.is_valid()) {
_unref_shortcut(items[p_idx].shortcut);
}
- items[p_idx].shortcut=p_shortcut;
- items[p_idx].shortcut_is_global=p_global;
-
+ items[p_idx].shortcut = p_shortcut;
+ items[p_idx].shortcut_is_global = p_global;
if (items[p_idx].shortcut.is_valid()) {
_ref_shortcut(items[p_idx].shortcut);
}
-
update();
}
void PopupMenu::set_item_h_offset(int p_idx, int p_offset) {
- ERR_FAIL_INDEX(p_idx,items.size());
- items[p_idx].h_ofs=p_offset;
+ ERR_FAIL_INDEX(p_idx, items.size());
+ items[p_idx].h_ofs = p_offset;
update();
-
}
-
bool PopupMenu::is_item_checkable(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,items.size(),false);
+ ERR_FAIL_INDEX_V(p_idx, items.size(), false);
return items[p_idx].checkable;
}
@@ -870,50 +814,48 @@ int PopupMenu::get_item_count() const {
return items.size();
}
-bool PopupMenu::activate_item_by_event(const InputEvent& p_event, bool p_for_global_only) {
+bool PopupMenu::activate_item_by_event(const InputEvent &p_event, bool p_for_global_only) {
- uint32_t code=0;
- if (p_event.type==InputEvent::KEY) {
- code=p_event.key.scancode;
- if (code==0)
- code=p_event.key.unicode;
+ uint32_t code = 0;
+ if (p_event.type == InputEvent::KEY) {
+ code = p_event.key.scancode;
+ if (code == 0)
+ code = p_event.key.unicode;
if (p_event.key.mod.control)
- code|=KEY_MASK_CTRL;
+ code |= KEY_MASK_CTRL;
if (p_event.key.mod.alt)
- code|=KEY_MASK_ALT;
+ code |= KEY_MASK_ALT;
if (p_event.key.mod.meta)
- code|=KEY_MASK_META;
+ code |= KEY_MASK_META;
if (p_event.key.mod.shift)
- code|=KEY_MASK_SHIFT;
+ code |= KEY_MASK_SHIFT;
}
-
- int il=items.size();
- for(int i=0;i<il;i++) {
+ int il = items.size();
+ for (int i = 0; i < il; i++) {
if (is_item_disabled(i))
continue;
-
if (items[i].shortcut.is_valid() && items[i].shortcut->is_shortcut(p_event) && (items[i].shortcut_is_global || !p_for_global_only)) {
activate_item(i);
return true;
}
- if (code!=0 && items[i].accel==code) {
+ if (code != 0 && items[i].accel == code) {
activate_item(i);
return true;
}
- if (items[i].submenu!="") {
- Node* n = get_node(items[i].submenu);
- if(!n)
+ if (items[i].submenu != "") {
+ Node *n = get_node(items[i].submenu);
+ if (!n)
continue;
- PopupMenu* pm = n->cast_to<PopupMenu>();
- if(!pm)
+ PopupMenu *pm = n->cast_to<PopupMenu>();
+ if (!pm)
continue;
- if(pm->activate_item_by_event(p_event,p_for_global_only)) {
+ if (pm->activate_item_by_event(p_event, p_for_global_only)) {
return true;
}
}
@@ -923,41 +865,38 @@ bool PopupMenu::activate_item_by_event(const InputEvent& p_event, bool p_for_glo
void PopupMenu::activate_item(int p_item) {
-
- ERR_FAIL_INDEX(p_item,items.size());
+ ERR_FAIL_INDEX(p_item, items.size());
ERR_FAIL_COND(items[p_item].separator);
- int id = items[p_item].ID>=0?items[p_item].ID:p_item;
- emit_signal("id_pressed",id);
- emit_signal("index_pressed",p_item);
+ int id = items[p_item].ID >= 0 ? items[p_item].ID : p_item;
+ emit_signal("id_pressed", id);
+ emit_signal("index_pressed", p_item);
//hide all parent PopupMenue's
Node *next = get_parent();
PopupMenu *pop = next->cast_to<PopupMenu>();
while (pop) {
- // We close all parents that are chained together,
+ // We close all parents that are chained together,
// with hide_on_item_selection enabled
- if(hide_on_item_selection && pop->is_hide_on_item_selection()) {
+ if (hide_on_item_selection && pop->is_hide_on_item_selection()) {
pop->hide();
next = next->get_parent();
pop = next->cast_to<PopupMenu>();
- }
- else {
- // Break out of loop when the next parent has
+ } else {
+ // Break out of loop when the next parent has
// hide_on_item_selection disabled
break;
}
}
- // Hides popup by default; unless otherwise specified
+ // Hides popup by default; unless otherwise specified
// by using set_hide_on_item_selection
if (hide_on_item_selection) {
hide();
}
-
}
void PopupMenu::remove_item(int p_idx) {
- ERR_FAIL_INDEX(p_idx,items.size());
+ ERR_FAIL_INDEX(p_idx, items.size());
if (items[p_idx].shortcut.is_valid()) {
_unref_shortcut(items[p_idx].shortcut);
@@ -970,30 +909,28 @@ void PopupMenu::remove_item(int p_idx) {
void PopupMenu::add_separator() {
Item sep;
- sep.separator=true;
- sep.ID=-1;
+ sep.separator = true;
+ sep.ID = -1;
items.push_back(sep);
update();
}
-void PopupMenu::clear() {
+void PopupMenu::clear() {
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
if (items[i].shortcut.is_valid()) {
_unref_shortcut(items[i].shortcut);
}
}
items.clear();
- mouse_over=-1;
+ mouse_over = -1;
update();
-
-
}
Array PopupMenu::_get_items() const {
Array items;
- for(int i=0;i<get_item_count();i++) {
+ for (int i = 0; i < get_item_count(); i++) {
items.push_back(get_item_text(i));
items.push_back(get_item_icon(i));
@@ -1009,68 +946,65 @@ Array PopupMenu::_get_items() const {
}
return items;
-
}
-void PopupMenu::_ref_shortcut( Ref<ShortCut> p_sc) {
+void PopupMenu::_ref_shortcut(Ref<ShortCut> p_sc) {
if (!shortcut_refcount.has(p_sc)) {
- shortcut_refcount[p_sc]=1;
- p_sc->connect("changed",this,"update");
+ shortcut_refcount[p_sc] = 1;
+ p_sc->connect("changed", this, "update");
} else {
- shortcut_refcount[p_sc]+=1;
+ shortcut_refcount[p_sc] += 1;
}
}
-void PopupMenu::_unref_shortcut(Ref<ShortCut> p_sc) {
+void PopupMenu::_unref_shortcut(Ref<ShortCut> p_sc) {
ERR_FAIL_COND(!shortcut_refcount.has(p_sc));
shortcut_refcount[p_sc]--;
- if (shortcut_refcount[p_sc]==0) {
- p_sc->disconnect("changed",this,"update");
+ if (shortcut_refcount[p_sc] == 0) {
+ p_sc->disconnect("changed", this, "update");
shortcut_refcount.erase(p_sc);
}
}
-void PopupMenu::_set_items(const Array& p_items){
+void PopupMenu::_set_items(const Array &p_items) {
ERR_FAIL_COND(p_items.size() % 10);
clear();
- for(int i=0;i<p_items.size();i+=10) {
-
- String text=p_items[i+0];
- Ref<Texture> icon=p_items[i+1];
- bool checkable=p_items[i+2];
- bool checked=p_items[i+3];
- bool disabled=p_items[i+4];
-
- int id=p_items[i+5];
- int accel=p_items[i+6];
- Variant meta=p_items[i+7];
- String subm=p_items[i+8];
- bool sep=p_items[i+9];
-
- int idx=get_item_count();
- add_item(text,id);
- set_item_icon(idx,icon);
- set_item_as_checkable(idx,checkable);
- set_item_checked(idx,checked);
- set_item_disabled(idx,disabled);
- set_item_ID(idx,id);
- set_item_metadata(idx,meta);
- set_item_as_separator(idx,sep);
- set_item_accelerator(idx,accel);
- set_item_submenu(idx,subm);
+ for (int i = 0; i < p_items.size(); i += 10) {
+
+ String text = p_items[i + 0];
+ Ref<Texture> icon = p_items[i + 1];
+ bool checkable = p_items[i + 2];
+ bool checked = p_items[i + 3];
+ bool disabled = p_items[i + 4];
+
+ int id = p_items[i + 5];
+ int accel = p_items[i + 6];
+ Variant meta = p_items[i + 7];
+ String subm = p_items[i + 8];
+ bool sep = p_items[i + 9];
+
+ int idx = get_item_count();
+ add_item(text, id);
+ set_item_icon(idx, icon);
+ set_item_as_checkable(idx, checkable);
+ set_item_checked(idx, checked);
+ set_item_disabled(idx, disabled);
+ set_item_ID(idx, id);
+ set_item_metadata(idx, meta);
+ set_item_as_separator(idx, sep);
+ set_item_accelerator(idx, accel);
+ set_item_submenu(idx, subm);
}
-
-
}
// Hide on item selection determines whether or not the popup will close after item selection
void PopupMenu::set_hide_on_item_selection(bool p_enabled) {
- hide_on_item_selection=p_enabled;
+ hide_on_item_selection = p_enabled;
}
bool PopupMenu::is_hide_on_item_selection() {
@@ -1078,128 +1012,122 @@ bool PopupMenu::is_hide_on_item_selection() {
return hide_on_item_selection;
}
-String PopupMenu::get_tooltip(const Point2& p_pos) const {
-
+String PopupMenu::get_tooltip(const Point2 &p_pos) const {
- int over=_get_mouse_over(p_pos);
- if (over<0 || over>=items.size())
+ int over = _get_mouse_over(p_pos);
+ if (over < 0 || over >= items.size())
return "";
return items[over].tooltip;
}
+void PopupMenu::set_parent_rect(const Rect2 &p_rect) {
-void PopupMenu::set_parent_rect(const Rect2& p_rect) {
-
- parent_rect=p_rect;
+ parent_rect = p_rect;
}
void PopupMenu::get_translatable_strings(List<String> *p_strings) const {
- for(int i=0;i<items.size();i++) {
+ for (int i = 0; i < items.size(); i++) {
- if (items[i].xl_text!="")
+ if (items[i].xl_text != "")
p_strings->push_back(items[i].xl_text);
}
}
-void PopupMenu::add_autohide_area(const Rect2& p_area) {
+void PopupMenu::add_autohide_area(const Rect2 &p_area) {
autohide_areas.push_back(p_area);
}
-void PopupMenu::clear_autohide_areas(){
+void PopupMenu::clear_autohide_areas() {
autohide_areas.clear();
}
void PopupMenu::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&PopupMenu::_gui_input);
- ClassDB::bind_method(D_METHOD("add_icon_item","texture","label","id","accel"),&PopupMenu::add_icon_item,DEFVAL(-1),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("add_item","label","id","accel"),&PopupMenu::add_item,DEFVAL(-1),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("add_icon_check_item","texture","label","id","accel"),&PopupMenu::add_icon_check_item,DEFVAL(-1),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("add_check_item","label","id","accel"),&PopupMenu::add_check_item,DEFVAL(-1),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("add_submenu_item","label","submenu","id"),&PopupMenu::add_submenu_item,DEFVAL(-1));
-
- ClassDB::bind_method(D_METHOD("add_icon_shortcut","texture","shortcut:ShortCut","id","global"),&PopupMenu::add_icon_shortcut,DEFVAL(-1),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("add_shortcut","shortcut:ShortCut","id","global"),&PopupMenu::add_shortcut,DEFVAL(-1),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("add_icon_check_shortcut","texture","shortcut:ShortCut","id","global"),&PopupMenu::add_icon_check_shortcut,DEFVAL(-1),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("add_check_shortcut","shortcut:ShortCut","id","global"),&PopupMenu::add_check_shortcut,DEFVAL(-1),DEFVAL(false));
-
- ClassDB::bind_method(D_METHOD("set_item_text","idx","text"),&PopupMenu::set_item_text);
- ClassDB::bind_method(D_METHOD("set_item_icon","idx","icon"),&PopupMenu::set_item_icon);
- ClassDB::bind_method(D_METHOD("set_item_checked","idx","checked"),&PopupMenu::set_item_checked);
- ClassDB::bind_method(D_METHOD("set_item_ID","idx","id"),&PopupMenu::set_item_ID);
- ClassDB::bind_method(D_METHOD("set_item_accelerator","idx","accel"),&PopupMenu::set_item_accelerator);
- ClassDB::bind_method(D_METHOD("set_item_metadata","idx","metadata"),&PopupMenu::set_item_metadata);
- ClassDB::bind_method(D_METHOD("set_item_disabled","idx","disabled"),&PopupMenu::set_item_disabled);
- ClassDB::bind_method(D_METHOD("set_item_submenu","idx","submenu"),&PopupMenu::set_item_submenu);
- ClassDB::bind_method(D_METHOD("set_item_as_separator","idx","enable"),&PopupMenu::set_item_as_separator);
- ClassDB::bind_method(D_METHOD("set_item_as_checkable","idx","enable"),&PopupMenu::set_item_as_checkable);
- ClassDB::bind_method(D_METHOD("set_item_tooltip","idx","tooltip"),&PopupMenu::set_item_tooltip);
- ClassDB::bind_method(D_METHOD("set_item_shortcut","idx","shortcut:ShortCut","global"),&PopupMenu::set_item_shortcut,DEFVAL(false));
-
- ClassDB::bind_method(D_METHOD("toggle_item_checked","idx"), &PopupMenu::toggle_item_checked);
-
- ClassDB::bind_method(D_METHOD("get_item_text","idx"),&PopupMenu::get_item_text);
- ClassDB::bind_method(D_METHOD("get_item_icon","idx"),&PopupMenu::get_item_icon);
- ClassDB::bind_method(D_METHOD("is_item_checked","idx"),&PopupMenu::is_item_checked);
- ClassDB::bind_method(D_METHOD("get_item_ID","idx"),&PopupMenu::get_item_ID);
- ClassDB::bind_method(D_METHOD("get_item_index","id"),&PopupMenu::get_item_index);
- ClassDB::bind_method(D_METHOD("get_item_accelerator","idx"),&PopupMenu::get_item_accelerator);
- ClassDB::bind_method(D_METHOD("get_item_metadata","idx"),&PopupMenu::get_item_metadata);
- ClassDB::bind_method(D_METHOD("is_item_disabled","idx"),&PopupMenu::is_item_disabled);
- ClassDB::bind_method(D_METHOD("get_item_submenu","idx"),&PopupMenu::get_item_submenu);
- ClassDB::bind_method(D_METHOD("is_item_separator","idx"),&PopupMenu::is_item_separator);
- ClassDB::bind_method(D_METHOD("is_item_checkable","idx"),&PopupMenu::is_item_checkable);
- ClassDB::bind_method(D_METHOD("get_item_tooltip","idx"),&PopupMenu::get_item_tooltip);
- ClassDB::bind_method(D_METHOD("get_item_shortcut:ShortCut","idx"),&PopupMenu::get_item_shortcut);
-
- ClassDB::bind_method(D_METHOD("get_item_count"),&PopupMenu::get_item_count);
-
- ClassDB::bind_method(D_METHOD("remove_item","idx"),&PopupMenu::remove_item);
-
- ClassDB::bind_method(D_METHOD("add_separator"),&PopupMenu::add_separator);
- ClassDB::bind_method(D_METHOD("clear"),&PopupMenu::clear);
-
- ClassDB::bind_method(D_METHOD("_set_items"),&PopupMenu::_set_items);
- ClassDB::bind_method(D_METHOD("_get_items"),&PopupMenu::_get_items);
-
- ClassDB::bind_method(D_METHOD("set_hide_on_item_selection","enable"),&PopupMenu::set_hide_on_item_selection);
- ClassDB::bind_method(D_METHOD("is_hide_on_item_selection"),&PopupMenu::is_hide_on_item_selection);
-
- ClassDB::bind_method(D_METHOD("_submenu_timeout"),&PopupMenu::_submenu_timeout);
-
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"items",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_items","_get_items") ;
- ADD_PROPERTYNO( PropertyInfo(Variant::BOOL, "hide_on_item_selection" ), "set_hide_on_item_selection", "is_hide_on_item_selection") ;
-
- ADD_SIGNAL( MethodInfo("id_pressed", PropertyInfo( Variant::INT,"ID") ) );
- ADD_SIGNAL( MethodInfo("index_pressed", PropertyInfo( Variant::INT,"index") ) );
-
+ ClassDB::bind_method(D_METHOD("_gui_input"), &PopupMenu::_gui_input);
+ ClassDB::bind_method(D_METHOD("add_icon_item", "texture", "label", "id", "accel"), &PopupMenu::add_icon_item, DEFVAL(-1), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("add_item", "label", "id", "accel"), &PopupMenu::add_item, DEFVAL(-1), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("add_icon_check_item", "texture", "label", "id", "accel"), &PopupMenu::add_icon_check_item, DEFVAL(-1), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("add_check_item", "label", "id", "accel"), &PopupMenu::add_check_item, DEFVAL(-1), DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("add_submenu_item", "label", "submenu", "id"), &PopupMenu::add_submenu_item, DEFVAL(-1));
+
+ ClassDB::bind_method(D_METHOD("add_icon_shortcut", "texture", "shortcut:ShortCut", "id", "global"), &PopupMenu::add_icon_shortcut, DEFVAL(-1), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("add_shortcut", "shortcut:ShortCut", "id", "global"), &PopupMenu::add_shortcut, DEFVAL(-1), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("add_icon_check_shortcut", "texture", "shortcut:ShortCut", "id", "global"), &PopupMenu::add_icon_check_shortcut, DEFVAL(-1), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("add_check_shortcut", "shortcut:ShortCut", "id", "global"), &PopupMenu::add_check_shortcut, DEFVAL(-1), DEFVAL(false));
+
+ ClassDB::bind_method(D_METHOD("set_item_text", "idx", "text"), &PopupMenu::set_item_text);
+ ClassDB::bind_method(D_METHOD("set_item_icon", "idx", "icon"), &PopupMenu::set_item_icon);
+ ClassDB::bind_method(D_METHOD("set_item_checked", "idx", "checked"), &PopupMenu::set_item_checked);
+ ClassDB::bind_method(D_METHOD("set_item_ID", "idx", "id"), &PopupMenu::set_item_ID);
+ ClassDB::bind_method(D_METHOD("set_item_accelerator", "idx", "accel"), &PopupMenu::set_item_accelerator);
+ ClassDB::bind_method(D_METHOD("set_item_metadata", "idx", "metadata"), &PopupMenu::set_item_metadata);
+ ClassDB::bind_method(D_METHOD("set_item_disabled", "idx", "disabled"), &PopupMenu::set_item_disabled);
+ ClassDB::bind_method(D_METHOD("set_item_submenu", "idx", "submenu"), &PopupMenu::set_item_submenu);
+ ClassDB::bind_method(D_METHOD("set_item_as_separator", "idx", "enable"), &PopupMenu::set_item_as_separator);
+ ClassDB::bind_method(D_METHOD("set_item_as_checkable", "idx", "enable"), &PopupMenu::set_item_as_checkable);
+ ClassDB::bind_method(D_METHOD("set_item_tooltip", "idx", "tooltip"), &PopupMenu::set_item_tooltip);
+ ClassDB::bind_method(D_METHOD("set_item_shortcut", "idx", "shortcut:ShortCut", "global"), &PopupMenu::set_item_shortcut, DEFVAL(false));
+
+ ClassDB::bind_method(D_METHOD("toggle_item_checked", "idx"), &PopupMenu::toggle_item_checked);
+
+ ClassDB::bind_method(D_METHOD("get_item_text", "idx"), &PopupMenu::get_item_text);
+ ClassDB::bind_method(D_METHOD("get_item_icon", "idx"), &PopupMenu::get_item_icon);
+ ClassDB::bind_method(D_METHOD("is_item_checked", "idx"), &PopupMenu::is_item_checked);
+ ClassDB::bind_method(D_METHOD("get_item_ID", "idx"), &PopupMenu::get_item_ID);
+ ClassDB::bind_method(D_METHOD("get_item_index", "id"), &PopupMenu::get_item_index);
+ ClassDB::bind_method(D_METHOD("get_item_accelerator", "idx"), &PopupMenu::get_item_accelerator);
+ ClassDB::bind_method(D_METHOD("get_item_metadata", "idx"), &PopupMenu::get_item_metadata);
+ ClassDB::bind_method(D_METHOD("is_item_disabled", "idx"), &PopupMenu::is_item_disabled);
+ ClassDB::bind_method(D_METHOD("get_item_submenu", "idx"), &PopupMenu::get_item_submenu);
+ ClassDB::bind_method(D_METHOD("is_item_separator", "idx"), &PopupMenu::is_item_separator);
+ ClassDB::bind_method(D_METHOD("is_item_checkable", "idx"), &PopupMenu::is_item_checkable);
+ ClassDB::bind_method(D_METHOD("get_item_tooltip", "idx"), &PopupMenu::get_item_tooltip);
+ ClassDB::bind_method(D_METHOD("get_item_shortcut:ShortCut", "idx"), &PopupMenu::get_item_shortcut);
+
+ ClassDB::bind_method(D_METHOD("get_item_count"), &PopupMenu::get_item_count);
+
+ ClassDB::bind_method(D_METHOD("remove_item", "idx"), &PopupMenu::remove_item);
+
+ ClassDB::bind_method(D_METHOD("add_separator"), &PopupMenu::add_separator);
+ ClassDB::bind_method(D_METHOD("clear"), &PopupMenu::clear);
+
+ ClassDB::bind_method(D_METHOD("_set_items"), &PopupMenu::_set_items);
+ ClassDB::bind_method(D_METHOD("_get_items"), &PopupMenu::_get_items);
+
+ ClassDB::bind_method(D_METHOD("set_hide_on_item_selection", "enable"), &PopupMenu::set_hide_on_item_selection);
+ ClassDB::bind_method(D_METHOD("is_hide_on_item_selection"), &PopupMenu::is_hide_on_item_selection);
+
+ ClassDB::bind_method(D_METHOD("_submenu_timeout"), &PopupMenu::_submenu_timeout);
+
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "items", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_items", "_get_items");
+ ADD_PROPERTYNO(PropertyInfo(Variant::BOOL, "hide_on_item_selection"), "set_hide_on_item_selection", "is_hide_on_item_selection");
+
+ ADD_SIGNAL(MethodInfo("id_pressed", PropertyInfo(Variant::INT, "ID")));
+ ADD_SIGNAL(MethodInfo("index_pressed", PropertyInfo(Variant::INT, "index")));
}
-
void PopupMenu::set_invalidate_click_until_motion() {
- moved=Vector2();
- invalidated_click=true;
+ moved = Vector2();
+ invalidated_click = true;
}
PopupMenu::PopupMenu() {
-
- mouse_over=-1;
+ mouse_over = -1;
set_focus_mode(FOCUS_ALL);
set_as_toplevel(true);
set_hide_on_item_selection(true);
- submenu_timer = memnew( Timer );
+ submenu_timer = memnew(Timer);
submenu_timer->set_wait_time(0.3);
submenu_timer->set_one_shot(true);
- submenu_timer->connect("timeout",this,"_submenu_timeout");
+ submenu_timer->connect("timeout", this, "_submenu_timeout");
add_child(submenu_timer);
}
-
PopupMenu::~PopupMenu() {
}
diff --git a/scene/gui/popup_menu.h b/scene/gui/popup_menu.h
index b5fca9a451..186d40f6d3 100644
--- a/scene/gui/popup_menu.h
+++ b/scene/gui/popup_menu.h
@@ -35,11 +35,9 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
class PopupMenu : public Popup {
- GDCLASS(PopupMenu, Popup );
+ GDCLASS(PopupMenu, Popup);
struct Item {
Ref<Texture> icon;
@@ -59,10 +57,18 @@ class PopupMenu : public Popup {
Ref<ShortCut> shortcut;
bool shortcut_is_global;
- Item() { checked=false; checkable=false; separator=false; accel=0; disabled=false; _ofs_cache=0; h_ofs=0; shortcut_is_global=false; }
+ Item() {
+ checked = false;
+ checkable = false;
+ separator = false;
+ accel = 0;
+ disabled = false;
+ _ofs_cache = 0;
+ h_ofs = 0;
+ shortcut_is_global = false;
+ }
};
-
Timer *submenu_timer;
List<Rect2> autohide_areas;
Vector<Item> items;
@@ -70,7 +76,7 @@ class PopupMenu : public Popup {
int submenu_over;
Rect2 parent_rect;
String _get_accel_text(int p_item) const;
- int _get_mouse_over(const Point2& p_over) const;
+ int _get_mouse_over(const Point2 &p_over) const;
virtual Size2 get_minimum_size() const;
void _gui_input(const InputEvent &p_event);
void _activate_submenu(int over);
@@ -81,44 +87,44 @@ class PopupMenu : public Popup {
Vector2 moved;
Array _get_items() const;
- void _set_items(const Array& p_items);
+ void _set_items(const Array &p_items);
- Map< Ref<ShortCut>, int> shortcut_refcount;
+ Map<Ref<ShortCut>, int> shortcut_refcount;
void _ref_shortcut(Ref<ShortCut> p_sc);
- void _unref_shortcut( Ref<ShortCut> p_sc);
-protected:
+ void _unref_shortcut(Ref<ShortCut> p_sc);
- virtual bool has_point(const Point2& p_point) const;
+protected:
+ virtual bool has_point(const Point2 &p_point) const;
-friend class MenuButton;
+ friend class MenuButton;
void _notification(int p_what);
static void _bind_methods();
-public:
- void add_icon_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID=-1,uint32_t p_accel=0);
- void add_item(const String& p_label,int p_ID=-1,uint32_t p_accel=0);
- void add_icon_check_item(const Ref<Texture>& p_icon,const String& p_label,int p_ID=-1,uint32_t p_accel=0);
- void add_check_item(const String& p_label,int p_ID=-1,uint32_t p_accel=0);
- void add_submenu_item(const String& p_label,const String& p_submenu, int p_ID=-1);
-
- void add_icon_shortcut(const Ref<Texture>& p_icon,const Ref<ShortCut>& p_shortcut,int p_ID=-1,bool p_global=false);
- void add_shortcut(const Ref<ShortCut>& p_shortcut,int p_ID=-1,bool p_global=false);
- void add_icon_check_shortcut(const Ref<Texture>& p_icon,const Ref<ShortCut>& p_shortcut,int p_ID=-1,bool p_global=false);
- void add_check_shortcut(const Ref<ShortCut>& p_shortcut,int p_ID=-1,bool p_global=false);
-
- void set_item_text(int p_idx,const String& p_text);
- void set_item_icon(int p_idx,const Ref<Texture>& p_icon);
- void set_item_checked(int p_idx,bool p_checked);
- void set_item_ID(int p_idx,int p_ID);
- void set_item_accelerator(int p_idx,uint32_t p_accel);
- void set_item_metadata(int p_idx,const Variant& p_meta);
- void set_item_disabled(int p_idx,bool p_disabled);
- void set_item_submenu(int p_idx, const String& p_submenu);
+public:
+ void add_icon_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID = -1, uint32_t p_accel = 0);
+ void add_item(const String &p_label, int p_ID = -1, uint32_t p_accel = 0);
+ void add_icon_check_item(const Ref<Texture> &p_icon, const String &p_label, int p_ID = -1, uint32_t p_accel = 0);
+ void add_check_item(const String &p_label, int p_ID = -1, uint32_t p_accel = 0);
+ void add_submenu_item(const String &p_label, const String &p_submenu, int p_ID = -1);
+
+ void add_icon_shortcut(const Ref<Texture> &p_icon, const Ref<ShortCut> &p_shortcut, int p_ID = -1, bool p_global = false);
+ void add_shortcut(const Ref<ShortCut> &p_shortcut, int p_ID = -1, bool p_global = false);
+ void add_icon_check_shortcut(const Ref<Texture> &p_icon, const Ref<ShortCut> &p_shortcut, int p_ID = -1, bool p_global = false);
+ void add_check_shortcut(const Ref<ShortCut> &p_shortcut, int p_ID = -1, bool p_global = false);
+
+ void set_item_text(int p_idx, const String &p_text);
+ void set_item_icon(int p_idx, const Ref<Texture> &p_icon);
+ void set_item_checked(int p_idx, bool p_checked);
+ void set_item_ID(int p_idx, int p_ID);
+ void set_item_accelerator(int p_idx, uint32_t p_accel);
+ void set_item_metadata(int p_idx, const Variant &p_meta);
+ void set_item_disabled(int p_idx, bool p_disabled);
+ void set_item_submenu(int p_idx, const String &p_submenu);
void set_item_as_separator(int p_idx, bool p_separator);
void set_item_as_checkable(int p_idx, bool p_checkable);
- void set_item_tooltip(int p_idx,const String& p_tooltip);
- void set_item_shortcut(int p_idx, const Ref<ShortCut>& p_shortcut,bool p_global=false);
+ void set_item_tooltip(int p_idx, const String &p_tooltip);
+ void set_item_shortcut(int p_idx, const Ref<ShortCut> &p_shortcut, bool p_global = false);
void set_item_h_offset(int p_idx, int p_offset);
void toggle_item_checked(int p_idx);
@@ -139,7 +145,7 @@ public:
int get_item_count() const;
- bool activate_item_by_event(const InputEvent& p_event,bool p_for_global_only=false);
+ bool activate_item_by_event(const InputEvent &p_event, bool p_for_global_only = false);
void activate_item(int p_item);
void remove_item(int p_idx);
@@ -148,13 +154,13 @@ public:
void clear();
- void set_parent_rect(const Rect2& p_rect);
+ void set_parent_rect(const Rect2 &p_rect);
- virtual String get_tooltip(const Point2& p_pos) const;
+ virtual String get_tooltip(const Point2 &p_pos) const;
virtual void get_translatable_strings(List<String> *p_strings) const;
- void add_autohide_area(const Rect2& p_area);
+ void add_autohide_area(const Rect2 &p_area);
void clear_autohide_areas();
void set_invalidate_click_until_motion();
@@ -163,7 +169,6 @@ public:
PopupMenu();
~PopupMenu();
-
};
#endif
diff --git a/scene/gui/progress_bar.cpp b/scene/gui/progress_bar.cpp
index 61776d3ae6..86dea6cd96 100644
--- a/scene/gui/progress_bar.cpp
+++ b/scene/gui/progress_bar.cpp
@@ -28,68 +28,64 @@
/*************************************************************************/
#include "progress_bar.h"
-
Size2 ProgressBar::get_minimum_size() const {
Ref<StyleBox> bg = get_stylebox("bg");
Ref<Font> font = get_font("font");
- Size2 ms=bg->get_minimum_size()+bg->get_center_size();
+ Size2 ms = bg->get_minimum_size() + bg->get_center_size();
if (percent_visible) {
- ms.height=MAX(ms.height,bg->get_minimum_size().height+font->get_height());
+ ms.height = MAX(ms.height, bg->get_minimum_size().height + font->get_height());
}
return ms;
}
-
void ProgressBar::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
Ref<StyleBox> bg = get_stylebox("bg");
Ref<StyleBox> fg = get_stylebox("fg");
Ref<Font> font = get_font("font");
- Color font_color=get_color("font_color");
+ Color font_color = get_color("font_color");
- draw_style_box(bg,Rect2(Point2(),get_size()));
+ draw_style_box(bg, Rect2(Point2(), get_size()));
float r = get_as_ratio();
int mp = fg->get_minimum_size().width;
- int p = r*get_size().width-mp;
- if (p>0) {
+ int p = r * get_size().width - mp;
+ if (p > 0) {
- draw_style_box(fg,Rect2(Point2(),Size2(p+fg->get_minimum_size().width,get_size().height)));
+ draw_style_box(fg, Rect2(Point2(), Size2(p + fg->get_minimum_size().width, get_size().height)));
}
if (percent_visible) {
- String txt=itos(int(get_as_ratio()*100))+"%";
- font->draw_halign(get_canvas_item(),Point2(0,font->get_ascent()+(get_size().height-font->get_height())/2),HALIGN_CENTER,get_size().width,txt,font_color);
+ String txt = itos(int(get_as_ratio() * 100)) + "%";
+ font->draw_halign(get_canvas_item(), Point2(0, font->get_ascent() + (get_size().height - font->get_height()) / 2), HALIGN_CENTER, get_size().width, txt, font_color);
}
}
}
-
void ProgressBar::set_percent_visible(bool p_visible) {
- percent_visible=p_visible;
+ percent_visible = p_visible;
update();
}
-bool ProgressBar::is_percent_visible() const{
+bool ProgressBar::is_percent_visible() const {
return percent_visible;
}
void ProgressBar::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_percent_visible","visible"),&ProgressBar::set_percent_visible);
- ClassDB::bind_method(D_METHOD("is_percent_visible"),&ProgressBar::is_percent_visible);
- ADD_GROUP("Percent","percent_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"percent_visible"),"set_percent_visible","is_percent_visible");
+ ClassDB::bind_method(D_METHOD("set_percent_visible", "visible"), &ProgressBar::set_percent_visible);
+ ClassDB::bind_method(D_METHOD("is_percent_visible"), &ProgressBar::is_percent_visible);
+ ADD_GROUP("Percent", "percent_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "percent_visible"), "set_percent_visible", "is_percent_visible");
}
ProgressBar::ProgressBar() {
set_v_size_flags(0);
- percent_visible=true;
+ percent_visible = true;
}
diff --git a/scene/gui/progress_bar.h b/scene/gui/progress_bar.h
index 01306a2ac4..b5820d1682 100644
--- a/scene/gui/progress_bar.h
+++ b/scene/gui/progress_bar.h
@@ -33,15 +33,15 @@
class ProgressBar : public Range {
- GDCLASS( ProgressBar, Range );
+ GDCLASS(ProgressBar, Range);
bool percent_visible;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_percent_visible(bool p_visible);
bool is_percent_visible() const;
diff --git a/scene/gui/range.cpp b/scene/gui/range.cpp
index f434aff08d..f15f3a6078 100644
--- a/scene/gui/range.cpp
+++ b/scene/gui/range.cpp
@@ -28,20 +28,18 @@
/*************************************************************************/
#include "range.h"
-
-
void Range::_value_changed_notify() {
_value_changed(shared->val);
- emit_signal("value_changed",shared->val);
+ emit_signal("value_changed", shared->val);
update();
_change_notify("range/value");
}
void Range::Shared::emit_value_changed() {
- for (Set<Range*>::Element *E=owners.front();E;E=E->next()) {
- Range *r=E->get();
+ for (Set<Range *>::Element *E = owners.front(); E; E = E->next()) {
+ Range *r = E->get();
if (!r->is_inside_tree())
continue;
r->_value_changed_notify();
@@ -50,65 +48,62 @@ void Range::Shared::emit_value_changed() {
void Range::_changed_notify(const char *p_what) {
- emit_signal("changed",shared->val);
+ emit_signal("changed", shared->val);
update();
_change_notify(p_what);
}
void Range::Shared::emit_changed(const char *p_what) {
- for (Set<Range*>::Element *E=owners.front();E;E=E->next()) {
- Range *r=E->get();
+ for (Set<Range *>::Element *E = owners.front(); E; E = E->next()) {
+ Range *r = E->get();
if (!r->is_inside_tree())
continue;
r->_changed_notify(p_what);
}
}
-
void Range::set_value(double p_val) {
- if(_rounded_values){
+ if (_rounded_values) {
p_val = Math::round(p_val);
}
- if (p_val>shared->max-shared->page)
- p_val=shared->max-shared->page;
+ if (p_val > shared->max - shared->page)
+ p_val = shared->max - shared->page;
- if (p_val<shared->min)
- p_val=shared->min;
+ if (p_val < shared->min)
+ p_val = shared->min;
- if (shared->val==p_val)
+ if (shared->val == p_val)
return;
- shared->val=p_val;
+ shared->val = p_val;
shared->emit_value_changed();
}
void Range::set_min(double p_min) {
- shared->min=p_min;
+ shared->min = p_min;
set_value(shared->val);
shared->emit_changed("range/min");
}
void Range::set_max(double p_max) {
- shared->max=p_max;
+ shared->max = p_max;
set_value(shared->val);
shared->emit_changed("range/max");
-
}
void Range::set_step(double p_step) {
- shared->step=p_step;
+ shared->step = p_step;
shared->emit_changed("range/step");
-
}
void Range::set_page(double p_page) {
- shared->page=p_page;
+ shared->page = p_page;
set_value(shared->val);
shared->emit_changed("range/page");
@@ -139,11 +134,11 @@ void Range::set_as_ratio(double p_value) {
double v;
- if (shared->exp_ratio && get_min()>0) {
+ if (shared->exp_ratio && get_min() > 0) {
- double exp_min = Math::log(get_min())/Math::log((double)2);
- double exp_max = Math::log(get_max())/Math::log((double)2);
- v = Math::pow(2,exp_min+(exp_max-exp_min)*p_value);
+ double exp_min = Math::log(get_min()) / Math::log((double)2);
+ double exp_max = Math::log(get_max()) / Math::log((double)2);
+ v = Math::pow(2, exp_min + (exp_max - exp_min) * p_value);
} else {
double percent = (get_max() - get_min()) * p_value;
@@ -154,15 +149,15 @@ void Range::set_as_ratio(double p_value) {
v = percent + get_min();
}
}
- set_value( v );
+ set_value(v);
}
double Range::get_as_ratio() const {
- if (shared->exp_ratio && get_min()>0) {
+ if (shared->exp_ratio && get_min() > 0) {
- double exp_min = Math::log(get_min())/Math::log((double)2);
- double exp_max = Math::log(get_max())/Math::log((double)2);
- double v = Math::log(get_value())/Math::log((double)2);
+ double exp_min = Math::log(get_min()) / Math::log((double)2);
+ double exp_max = Math::log(get_max()) / Math::log((double)2);
+ double v = Math::log(get_value()) / Math::log((double)2);
return (v - exp_min) / (exp_max - exp_min);
@@ -174,7 +169,7 @@ double Range::get_as_ratio() const {
void Range::_share(Node *p_range) {
- Range * r = p_range->cast_to<Range>();
+ Range *r = p_range->cast_to<Range>();
ERR_FAIL_COND(!r);
share(r);
}
@@ -190,69 +185,67 @@ void Range::share(Range *p_range) {
void Range::unshare() {
- Shared * nshared = memnew(Shared);
- nshared->min=shared->min;
- nshared->max=shared->max;
- nshared->val=shared->val;
- nshared->step=shared->step;
- nshared->page=shared->page;
+ Shared *nshared = memnew(Shared);
+ nshared->min = shared->min;
+ nshared->max = shared->max;
+ nshared->val = shared->val;
+ nshared->step = shared->step;
+ nshared->page = shared->page;
_unref_shared();
_ref_shared(nshared);
}
void Range::_ref_shared(Shared *p_shared) {
- if (shared && p_shared==shared)
+ if (shared && p_shared == shared)
return;
_unref_shared();
- shared=p_shared;
+ shared = p_shared;
shared->owners.insert(this);
}
-
void Range::_unref_shared() {
shared->owners.erase(this);
- if (shared->owners.size()==0) {
+ if (shared->owners.size() == 0) {
memdelete(shared);
- shared=NULL;
+ shared = NULL;
}
}
void Range::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_value"),&Range::get_value);
- ClassDB::bind_method(D_METHOD("get_min"),&Range::get_min);
- ClassDB::bind_method(D_METHOD("get_max"),&Range::get_max);
- ClassDB::bind_method(D_METHOD("get_step"),&Range::get_step);
- ClassDB::bind_method(D_METHOD("get_page"),&Range::get_page);
- ClassDB::bind_method(D_METHOD("get_as_ratio"),&Range::get_as_ratio);
- ClassDB::bind_method(D_METHOD("set_value","value"),&Range::set_value);
- ClassDB::bind_method(D_METHOD("set_min","minimum"),&Range::set_min);
- ClassDB::bind_method(D_METHOD("set_max","maximum"),&Range::set_max);
- ClassDB::bind_method(D_METHOD("set_step","step"),&Range::set_step);
- ClassDB::bind_method(D_METHOD("set_page","pagesize"),&Range::set_page);
- ClassDB::bind_method(D_METHOD("set_as_ratio","value"),&Range::set_as_ratio);
- ClassDB::bind_method(D_METHOD("set_use_rounded_values","enabled"),&Range::set_use_rounded_values);
- ClassDB::bind_method(D_METHOD("is_using_rounded_values"),&Range::is_using_rounded_values);
- ClassDB::bind_method(D_METHOD("set_exp_ratio","enabled"),&Range::set_exp_ratio);
- ClassDB::bind_method(D_METHOD("is_ratio_exp"),&Range::is_ratio_exp);
-
- ClassDB::bind_method(D_METHOD("share","with"),&Range::_share);
- ClassDB::bind_method(D_METHOD("unshare"),&Range::unshare);
-
- ADD_SIGNAL( MethodInfo("value_changed", PropertyInfo(Variant::REAL,"value")));
- ADD_SIGNAL( MethodInfo("changed"));
-
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "min_value" ), "set_min", "get_min") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "max_value" ), "set_max", "get_max") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "step" ), "set_step", "get_step") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "page" ), "set_page", "get_page") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "value" ), "set_value", "get_value") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "exp_edit" ), "set_exp_ratio", "is_ratio_exp") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "rounded" ), "set_use_rounded_values", "is_using_rounded_values") ;
-
+ ClassDB::bind_method(D_METHOD("get_value"), &Range::get_value);
+ ClassDB::bind_method(D_METHOD("get_min"), &Range::get_min);
+ ClassDB::bind_method(D_METHOD("get_max"), &Range::get_max);
+ ClassDB::bind_method(D_METHOD("get_step"), &Range::get_step);
+ ClassDB::bind_method(D_METHOD("get_page"), &Range::get_page);
+ ClassDB::bind_method(D_METHOD("get_as_ratio"), &Range::get_as_ratio);
+ ClassDB::bind_method(D_METHOD("set_value", "value"), &Range::set_value);
+ ClassDB::bind_method(D_METHOD("set_min", "minimum"), &Range::set_min);
+ ClassDB::bind_method(D_METHOD("set_max", "maximum"), &Range::set_max);
+ ClassDB::bind_method(D_METHOD("set_step", "step"), &Range::set_step);
+ ClassDB::bind_method(D_METHOD("set_page", "pagesize"), &Range::set_page);
+ ClassDB::bind_method(D_METHOD("set_as_ratio", "value"), &Range::set_as_ratio);
+ ClassDB::bind_method(D_METHOD("set_use_rounded_values", "enabled"), &Range::set_use_rounded_values);
+ ClassDB::bind_method(D_METHOD("is_using_rounded_values"), &Range::is_using_rounded_values);
+ ClassDB::bind_method(D_METHOD("set_exp_ratio", "enabled"), &Range::set_exp_ratio);
+ ClassDB::bind_method(D_METHOD("is_ratio_exp"), &Range::is_ratio_exp);
+
+ ClassDB::bind_method(D_METHOD("share", "with"), &Range::_share);
+ ClassDB::bind_method(D_METHOD("unshare"), &Range::unshare);
+
+ ADD_SIGNAL(MethodInfo("value_changed", PropertyInfo(Variant::REAL, "value")));
+ ADD_SIGNAL(MethodInfo("changed"));
+
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "min_value"), "set_min", "get_min");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "max_value"), "set_max", "get_max");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "step"), "set_step", "get_step");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "page"), "set_page", "get_page");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "value"), "set_value", "get_value");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "exp_edit"), "set_exp_ratio", "is_ratio_exp");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "rounded"), "set_use_rounded_values", "is_using_rounded_values");
}
void Range::set_use_rounded_values(bool p_enable) {
@@ -267,7 +260,7 @@ bool Range::is_using_rounded_values() const {
void Range::set_exp_ratio(bool p_enable) {
- shared->exp_ratio=p_enable;
+ shared->exp_ratio = p_enable;
}
bool Range::is_ratio_exp() const {
@@ -275,25 +268,20 @@ bool Range::is_ratio_exp() const {
return shared->exp_ratio;
}
-
-Range::Range()
-{
+Range::Range() {
shared = memnew(Shared);
- shared->min=0;
- shared->max=100;
- shared->val=
- shared->step=1;
- shared->page=0;
+ shared->min = 0;
+ shared->max = 100;
+ shared->val =
+ shared->step = 1;
+ shared->page = 0;
shared->owners.insert(this);
- shared->exp_ratio=false;
+ shared->exp_ratio = false;
_rounded_values = false;
}
-
Range::~Range() {
_unref_shared();
}
-
-
diff --git a/scene/gui/range.h b/scene/gui/range.h
index 5f274a6901..105bd08a4f 100644
--- a/scene/gui/range.h
+++ b/scene/gui/range.h
@@ -35,16 +35,15 @@
*/
class Range : public Control {
- GDCLASS( Range, Control );
-
+ GDCLASS(Range, Control);
struct Shared {
- double val,min,max;
- double step,page;
+ double val, min, max;
+ double step, page;
bool exp_ratio;
- Set<Range*> owners;
+ Set<Range *> owners;
void emit_value_changed();
- void emit_changed(const char *p_what="");
+ void emit_changed(const char *p_what = "");
};
Shared *shared;
@@ -55,17 +54,16 @@ class Range : public Control {
void _share(Node *p_range);
void _value_changed_notify();
- void _changed_notify(const char *p_what="");
+ void _changed_notify(const char *p_what = "");
protected:
-
virtual void _value_changed(double) {}
static void _bind_methods();
bool _rounded_values;
-public:
+public:
void set_value(double p_val);
void set_min(double p_min);
void set_max(double p_max);
@@ -91,7 +89,6 @@ public:
Range();
~Range();
-
};
#endif
diff --git a/scene/gui/reference_rect.cpp b/scene/gui/reference_rect.cpp
index ff4cdf04fd..cc38b896d9 100644
--- a/scene/gui/reference_rect.cpp
+++ b/scene/gui/reference_rect.cpp
@@ -30,15 +30,14 @@
void ReferenceRect::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (!is_inside_tree())
return;
if (get_tree()->is_editor_hint())
- draw_style_box(get_stylebox("border"),Rect2(Point2(),get_size())) ;
+ draw_style_box(get_stylebox("border"), Rect2(Point2(), get_size()));
}
}
-ReferenceRect::ReferenceRect()
-{
+ReferenceRect::ReferenceRect() {
}
diff --git a/scene/gui/reference_rect.h b/scene/gui/reference_rect.h
index be493f346c..b64f479829 100644
--- a/scene/gui/reference_rect.h
+++ b/scene/gui/reference_rect.h
@@ -33,11 +33,11 @@
class ReferenceRect : public Control {
- GDCLASS( ReferenceRect, Control);
+ GDCLASS(ReferenceRect, Control);
protected:
-
void _notification(int p_what);
+
public:
ReferenceRect();
};
diff --git a/scene/gui/rich_text_label.cpp b/scene/gui/rich_text_label.cpp
index 17ec71f4a4..322d9dee20 100644
--- a/scene/gui/rich_text_label.cpp
+++ b/scene/gui/rich_text_label.cpp
@@ -27,10 +27,10 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "rich_text_label.h"
-#include "scene/scene_string_names.h"
#include "os/keyboard.h"
#include "os/os.h"
-RichTextLabel::Item *RichTextLabel::_get_next_item(Item* p_item,bool p_free) {
+#include "scene/scene_string_names.h"
+RichTextLabel::Item *RichTextLabel::_get_next_item(Item *p_item, bool p_free) {
if (p_free) {
@@ -45,550 +45,511 @@ RichTextLabel::Item *RichTextLabel::_get_next_item(Item* p_item,bool p_free) {
} else {
//go up until something with a next is found
while (p_item->parent && !p_item->E->next()) {
- p_item=p_item->parent;
+ p_item = p_item->parent;
}
-
if (p_item->parent)
return p_item->E->next()->get();
else
return NULL;
-
}
} else {
- if (p_item->subitems.size() && p_item->type!=ITEM_TABLE) {
+ if (p_item->subitems.size() && p_item->type != ITEM_TABLE) {
return p_item->subitems.front()->get();
- } else if (p_item->type==ITEM_FRAME) {
+ } else if (p_item->type == ITEM_FRAME) {
return NULL;
} else if (p_item->E->next()) {
return p_item->E->next()->get();
} else {
//go up until something with a next is found
- while (p_item->type!=ITEM_FRAME && !p_item->E->next()) {
- p_item=p_item->parent;
+ while (p_item->type != ITEM_FRAME && !p_item->E->next()) {
+ p_item = p_item->parent;
}
-
- if (p_item->type!=ITEM_FRAME)
+ if (p_item->type != ITEM_FRAME)
return p_item->E->next()->get();
else
return NULL;
-
}
}
return NULL;
-
}
-
-void RichTextLabel::_process_line(ItemFrame *p_frame,const Vector2& p_ofs,int &y, int p_width, int p_line, ProcessMode p_mode,const Ref<Font> &p_base_font,const Color &p_base_color,const Point2i& p_click_pos,Item **r_click_item,int *r_click_char,bool *r_outside,int p_char_count) {
+void RichTextLabel::_process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int &y, int p_width, int p_line, ProcessMode p_mode, const Ref<Font> &p_base_font, const Color &p_base_color, const Point2i &p_click_pos, Item **r_click_item, int *r_click_char, bool *r_outside, int p_char_count) {
RID ci;
if (r_outside)
- *r_outside=false;
- if (p_mode==PROCESS_DRAW) {
- ci=get_canvas_item();
+ *r_outside = false;
+ if (p_mode == PROCESS_DRAW) {
+ ci = get_canvas_item();
if (r_click_item)
- *r_click_item=NULL;
-
+ *r_click_item = NULL;
}
Line &l = p_frame->lines[p_line];
Item *it = l.from;
+ int line_ofs = 0;
+ int margin = _find_margin(it, p_base_font);
+ Align align = _find_align(it);
+ int line = 0;
+ int spaces = 0;
- int line_ofs=0;
- int margin=_find_margin(it,p_base_font);
- Align align=_find_align(it);
- int line=0;
- int spaces=0;
+ if (p_mode != PROCESS_CACHE) {
-
- if (p_mode!=PROCESS_CACHE) {
-
- ERR_FAIL_INDEX(line,l.offset_caches.size());
+ ERR_FAIL_INDEX(line, l.offset_caches.size());
line_ofs = l.offset_caches[line];
}
- if (p_mode==PROCESS_CACHE) {
+ if (p_mode == PROCESS_CACHE) {
l.offset_caches.clear();
l.height_caches.clear();
- l.char_count=0;
- l.minimum_width=0;
+ l.char_count = 0;
+ l.minimum_width = 0;
}
- int wofs=margin;
- int spaces_size=0;
- int align_ofs=0;
-
+ int wofs = margin;
+ int spaces_size = 0;
+ int align_ofs = 0;
- if (p_mode!=PROCESS_CACHE && align!=ALIGN_FILL)
- wofs+=line_ofs;
+ if (p_mode != PROCESS_CACHE && align != ALIGN_FILL)
+ wofs += line_ofs;
- int begin=wofs;
+ int begin = wofs;
Ref<Font> cfont = _find_font(it);
if (cfont.is_null())
- cfont=p_base_font;
+ cfont = p_base_font;
//line height should be the font height for the first time, this ensures that an empty line will never have zero height and succesive newlines are displayed
- int line_height=cfont->get_height();
+ int line_height = cfont->get_height();
Variant meta;
-#define NEW_LINE \
-{\
- if (p_mode!=PROCESS_CACHE) {\
- line++;\
- if (line < l.offset_caches.size())\
- line_ofs=l.offset_caches[line];\
- wofs=margin;\
- if (align!=ALIGN_FILL)\
- wofs+=line_ofs;\
- } else {\
- int used=wofs-margin;\
- switch(align) {\
- case ALIGN_LEFT: l.offset_caches.push_back(0); break;\
- case ALIGN_CENTER: l.offset_caches.push_back(((p_width-margin)-used)/2); break;\
- case ALIGN_RIGHT: l.offset_caches.push_back(((p_width-margin)-used)); break;\
- case ALIGN_FILL: l.offset_caches.push_back((p_width-margin)-used/*+spaces_size*/); break;\
- }\
- l.height_caches.push_back(line_height);\
- l.space_caches.push_back(spaces);\
- }\
- y+=line_height+get_constant(SceneStringNames::get_singleton()->line_separation);\
- line_height=0;\
- spaces=0;\
- spaces_size=0;\
- wofs=begin;\
- align_ofs=0;\
- if (p_mode!=PROCESS_CACHE) {\
- lh=line<l.height_caches.size()?l.height_caches[line]:1;\
- }\
- if (p_mode==PROCESS_POINTER && r_click_item && p_click_pos.y>=p_ofs.y+y && p_click_pos.y<=p_ofs.y+y+lh && p_click_pos.x<p_ofs.x+wofs) {\
- if (r_outside) *r_outside=true;\
- *r_click_item=it;\
- *r_click_char=rchar;\
- return;\
- }\
-}
-
-
-#define ENSURE_WIDTH(m_width) \
- if (p_mode==PROCESS_CACHE) { \
- l.minimum_width=MAX(l.minimum_width,wofs+m_width);\
- }\
- if (wofs + m_width > p_width) {\
- if (p_mode==PROCESS_CACHE) {\
- if (spaces>0) \
- spaces-=1;\
- }\
- if (p_mode==PROCESS_POINTER && r_click_item && p_click_pos.y>=p_ofs.y+y && p_click_pos.y<=p_ofs.y+y+lh && p_click_pos.x>p_ofs.x+wofs) {\
- if (r_outside) *r_outside=true; \
- *r_click_item=it;\
- *r_click_char=rchar;\
- return;\
- }\
- NEW_LINE\
+#define NEW_LINE \
+ { \
+ if (p_mode != PROCESS_CACHE) { \
+ line++; \
+ if (line < l.offset_caches.size()) \
+ line_ofs = l.offset_caches[line]; \
+ wofs = margin; \
+ if (align != ALIGN_FILL) \
+ wofs += line_ofs; \
+ } else { \
+ int used = wofs - margin; \
+ switch (align) { \
+ case ALIGN_LEFT: l.offset_caches.push_back(0); break; \
+ case ALIGN_CENTER: l.offset_caches.push_back(((p_width - margin) - used) / 2); break; \
+ case ALIGN_RIGHT: l.offset_caches.push_back(((p_width - margin) - used)); break; \
+ case ALIGN_FILL: l.offset_caches.push_back((p_width - margin) - used /*+spaces_size*/); break; \
+ } \
+ l.height_caches.push_back(line_height); \
+ l.space_caches.push_back(spaces); \
+ } \
+ y += line_height + get_constant(SceneStringNames::get_singleton()->line_separation); \
+ line_height = 0; \
+ spaces = 0; \
+ spaces_size = 0; \
+ wofs = begin; \
+ align_ofs = 0; \
+ if (p_mode != PROCESS_CACHE) { \
+ lh = line < l.height_caches.size() ? l.height_caches[line] : 1; \
+ } \
+ if (p_mode == PROCESS_POINTER && r_click_item && p_click_pos.y >= p_ofs.y + y && p_click_pos.y <= p_ofs.y + y + lh && p_click_pos.x < p_ofs.x + wofs) { \
+ if (r_outside) *r_outside = true; \
+ *r_click_item = it; \
+ *r_click_char = rchar; \
+ return; \
+ } \
}
+#define ENSURE_WIDTH(m_width) \
+ if (p_mode == PROCESS_CACHE) { \
+ l.minimum_width = MAX(l.minimum_width, wofs + m_width); \
+ } \
+ if (wofs + m_width > p_width) { \
+ if (p_mode == PROCESS_CACHE) { \
+ if (spaces > 0) \
+ spaces -= 1; \
+ } \
+ if (p_mode == PROCESS_POINTER && r_click_item && p_click_pos.y >= p_ofs.y + y && p_click_pos.y <= p_ofs.y + y + lh && p_click_pos.x > p_ofs.x + wofs) { \
+ if (r_outside) *r_outside = true; \
+ *r_click_item = it; \
+ *r_click_char = rchar; \
+ return; \
+ } \
+ NEW_LINE \
+ }
-#define ADVANCE(m_width) \
-{\
- if (p_mode==PROCESS_POINTER && r_click_item && p_click_pos.y>=p_ofs.y+y && p_click_pos.y<=p_ofs.y+y+lh && p_click_pos.x>=p_ofs.x+wofs && p_click_pos.x<p_ofs.x+wofs+m_width) {\
- if (r_outside) *r_outside=false; \
- *r_click_item=it;\
- *r_click_char=rchar;\
- return;\
- }\
- wofs+=m_width;\
-}
+#define ADVANCE(m_width) \
+ { \
+ if (p_mode == PROCESS_POINTER && r_click_item && p_click_pos.y >= p_ofs.y + y && p_click_pos.y <= p_ofs.y + y + lh && p_click_pos.x >= p_ofs.x + wofs && p_click_pos.x < p_ofs.x + wofs + m_width) { \
+ if (r_outside) *r_outside = false; \
+ *r_click_item = it; \
+ *r_click_char = rchar; \
+ return; \
+ } \
+ wofs += m_width; \
+ }
-#define CHECK_HEIGHT( m_height ) \
-if (m_height > line_height) {\
- line_height=m_height;\
-}
+#define CHECK_HEIGHT(m_height) \
+ if (m_height > line_height) { \
+ line_height = m_height; \
+ }
Color selection_fg;
Color selection_bg;
- if (p_mode==PROCESS_DRAW) {
-
+ if (p_mode == PROCESS_DRAW) {
selection_fg = get_color("font_color_selected");
selection_bg = get_color("selection_color");
}
- int rchar=0;
- int lh=0;
+ int rchar = 0;
+ int lh = 0;
while (it) {
- switch(it->type) {
+ switch (it->type) {
case ITEM_TEXT: {
- ItemText *text = static_cast<ItemText*>(it);
+ ItemText *text = static_cast<ItemText *>(it);
- Ref<Font> font=_find_font(it);
+ Ref<Font> font = _find_font(it);
if (font.is_null())
- font=p_base_font;
+ font = p_base_font;
const CharType *c = text->text.c_str();
- const CharType *cf=c;
- int fh=font->get_height();
+ const CharType *cf = c;
+ int fh = font->get_height();
int ascent = font->get_ascent();
Color color;
- bool underline=false;
+ bool underline = false;
- if (p_mode==PROCESS_DRAW) {
- color=_find_color(text,p_base_color);
- underline=_find_underline(text);
- if (_find_meta(text,&meta)) {
+ if (p_mode == PROCESS_DRAW) {
+ color = _find_color(text, p_base_color);
+ underline = _find_underline(text);
+ if (_find_meta(text, &meta)) {
- underline=true;
+ underline = true;
}
-
- } else if (p_mode==PROCESS_CACHE) {
- l.char_count+=text->text.length();
-
+ } else if (p_mode == PROCESS_CACHE) {
+ l.char_count += text->text.length();
}
- rchar=0;
+ rchar = 0;
- while(*c) {
+ while (*c) {
- int end=0;
- int w=0;
- int fw=0;
+ int end = 0;
+ int w = 0;
+ int fw = 0;
- lh=0;
- if (p_mode!=PROCESS_CACHE) {
- lh=line<l.height_caches.size()?l.height_caches[line]:1;
+ lh = 0;
+ if (p_mode != PROCESS_CACHE) {
+ lh = line < l.height_caches.size() ? l.height_caches[line] : 1;
}
- while (c[end]!=0 && !(end && c[end-1]==' ' && c[end]!=' ')) {
+ while (c[end] != 0 && !(end && c[end - 1] == ' ' && c[end] != ' ')) {
- int cw = font->get_char_size(c[end],c[end+1]).width;
- if (c[end]=='\t') {
- cw=tab_size*font->get_char_size(' ').width;
+ int cw = font->get_char_size(c[end], c[end + 1]).width;
+ if (c[end] == '\t') {
+ cw = tab_size * font->get_char_size(' ').width;
}
- if (end>0 && w+cw+begin > p_width ) {
+ if (end > 0 && w + cw + begin > p_width) {
break; //don't allow lines longer than assigned width
}
- w+=cw;
- fw+=cw;
+ w += cw;
+ fw += cw;
end++;
}
ENSURE_WIDTH(w);
- if (end && c[end-1]==' ') {
- if (p_mode==PROCESS_CACHE) {
- spaces_size+=font->get_char_size(' ').width;
- } else if (align==ALIGN_FILL) {
- int ln = MIN(l.offset_caches.size()-1,line);
+ if (end && c[end - 1] == ' ') {
+ if (p_mode == PROCESS_CACHE) {
+ spaces_size += font->get_char_size(' ').width;
+ } else if (align == ALIGN_FILL) {
+ int ln = MIN(l.offset_caches.size() - 1, line);
if (l.space_caches[ln]) {
align_ofs = spaces * l.offset_caches[ln] / l.space_caches[ln];
}
}
spaces++;
-
}
-
{
- int ofs=0;
+ int ofs = 0;
- for(int i=0;i<end;i++) {
- int pofs=wofs+ofs;
+ for (int i = 0; i < end; i++) {
+ int pofs = wofs + ofs;
-
- if (p_mode==PROCESS_POINTER && r_click_char && p_click_pos.y>=p_ofs.y+y && p_click_pos.y<=p_ofs.y+y+lh) {
+ if (p_mode == PROCESS_POINTER && r_click_char && p_click_pos.y >= p_ofs.y + y && p_click_pos.y <= p_ofs.y + y + lh) {
//int o = (wofs+w)-p_click_pos.x;
+ int cw = font->get_char_size(c[i], c[i + 1]).x;
- int cw=font->get_char_size(c[i],c[i+1]).x;
-
- if (c[i]=='\t') {
- cw=tab_size*font->get_char_size(' ').width;
+ if (c[i] == '\t') {
+ cw = tab_size * font->get_char_size(' ').width;
}
+ if (p_click_pos.x - cw / 2 > p_ofs.x + align_ofs + pofs) {
- if (p_click_pos.x-cw/2>p_ofs.x+align_ofs+pofs) {
-
- rchar=int((&c[i])-cf);
+ rchar = int((&c[i]) - cf);
}
+ ofs += cw;
+ } else if (p_mode == PROCESS_DRAW) {
- ofs+=cw;
- } else if (p_mode==PROCESS_DRAW) {
-
- bool selected=false;
+ bool selected = false;
if (selection.active) {
- int cofs = (&c[i])-cf;
- if ((text->index > selection.from->index || (text->index == selection.from->index && cofs >=selection.from_char)) && (text->index < selection.to->index || (text->index == selection.to->index && cofs <=selection.to_char))) {
- selected=true;
+ int cofs = (&c[i]) - cf;
+ if ((text->index > selection.from->index || (text->index == selection.from->index && cofs >= selection.from_char)) && (text->index < selection.to->index || (text->index == selection.to->index && cofs <= selection.to_char))) {
+ selected = true;
}
}
- int cw=0;
+ int cw = 0;
- bool visible = visible_characters<0 || p_char_count<visible_characters;
- if (c[i]=='\t')
- visible=false;
+ bool visible = visible_characters < 0 || p_char_count < visible_characters;
+ if (c[i] == '\t')
+ visible = false;
if (selected) {
- cw = font->get_char_size(c[i],c[i+1]).x;
- draw_rect(Rect2(p_ofs.x+pofs,p_ofs.y+y,cw,lh),selection_bg);
+ cw = font->get_char_size(c[i], c[i + 1]).x;
+ draw_rect(Rect2(p_ofs.x + pofs, p_ofs.y + y, cw, lh), selection_bg);
if (visible)
- font->draw_char(ci,p_ofs+Point2(align_ofs+pofs,y+lh-(fh-ascent)),c[i],c[i+1],selection_fg);
+ font->draw_char(ci, p_ofs + Point2(align_ofs + pofs, y + lh - (fh - ascent)), c[i], c[i + 1], selection_fg);
} else {
if (visible)
- cw=font->draw_char(ci,p_ofs+Point2(align_ofs+pofs,y+lh-(fh-ascent)),c[i],c[i+1],color);
+ cw = font->draw_char(ci, p_ofs + Point2(align_ofs + pofs, y + lh - (fh - ascent)), c[i], c[i + 1], color);
}
p_char_count++;
- if (c[i]=='\t') {
- cw=tab_size*font->get_char_size(' ').width;
+ if (c[i] == '\t') {
+ cw = tab_size * font->get_char_size(' ').width;
}
-
if (underline) {
- Color uc=color;
- uc.a*=0.5;
- int uy = y+lh-fh+ascent+2;
- VS::get_singleton()->canvas_item_add_line(ci,p_ofs+Point2(align_ofs+pofs,uy),p_ofs+Point2(align_ofs+pofs+cw,uy),uc);
+ Color uc = color;
+ uc.a *= 0.5;
+ int uy = y + lh - fh + ascent + 2;
+ VS::get_singleton()->canvas_item_add_line(ci, p_ofs + Point2(align_ofs + pofs, uy), p_ofs + Point2(align_ofs + pofs + cw, uy), uc);
}
- ofs+=cw;
+ ofs += cw;
}
-
}
}
-
ADVANCE(fw);
CHECK_HEIGHT(fh); //must be done somewhere
- c=&c[end];
+ c = &c[end];
}
-
} break;
case ITEM_IMAGE: {
- lh=0;
- if (p_mode!=PROCESS_CACHE)
- lh = line<l.height_caches.size()?l.height_caches[line]:1;
+ lh = 0;
+ if (p_mode != PROCESS_CACHE)
+ lh = line < l.height_caches.size() ? l.height_caches[line] : 1;
else
- l.char_count+=1; //images count as chars too
+ l.char_count += 1; //images count as chars too
- ItemImage *img = static_cast<ItemImage*>(it);
+ ItemImage *img = static_cast<ItemImage *>(it);
- Ref<Font> font=_find_font(it);
+ Ref<Font> font = _find_font(it);
if (font.is_null())
- font=p_base_font;
+ font = p_base_font;
- if (p_mode==PROCESS_POINTER && r_click_char)
- *r_click_char=0;
+ if (p_mode == PROCESS_POINTER && r_click_char)
+ *r_click_char = 0;
- ENSURE_WIDTH( img->image->get_width() );
+ ENSURE_WIDTH(img->image->get_width());
- bool visible = visible_characters<0 || p_char_count<visible_characters;
+ bool visible = visible_characters < 0 || p_char_count < visible_characters;
- if (p_mode==PROCESS_DRAW && visible) {
- img->image->draw(ci,p_ofs+Point2(align_ofs+wofs,y+lh-font->get_descent()-img->image->get_height()));
+ if (p_mode == PROCESS_DRAW && visible) {
+ img->image->draw(ci, p_ofs + Point2(align_ofs + wofs, y + lh - font->get_descent() - img->image->get_height()));
}
p_char_count++;
- ADVANCE( img->image->get_width() );
- CHECK_HEIGHT( (img->image->get_height()+font->get_descent()) );
+ ADVANCE(img->image->get_width());
+ CHECK_HEIGHT((img->image->get_height() + font->get_descent()));
} break;
case ITEM_NEWLINE: {
-
- lh=0;
- if (p_mode!=PROCESS_CACHE)
- lh = line<l.height_caches.size()?l.height_caches[line]:1;
+ lh = 0;
+ if (p_mode != PROCESS_CACHE)
+ lh = line < l.height_caches.size() ? l.height_caches[line] : 1;
} break;
case ITEM_TABLE: {
- lh=0;
- ItemTable *table = static_cast<ItemTable*>(it);
- int hseparation=get_constant("table_hseparation");
- int vseparation=get_constant("table_vseparation");
- Color ccolor = _find_color(table,p_base_color);
- Vector2 draw_ofs = Point2(wofs,y);
+ lh = 0;
+ ItemTable *table = static_cast<ItemTable *>(it);
+ int hseparation = get_constant("table_hseparation");
+ int vseparation = get_constant("table_vseparation");
+ Color ccolor = _find_color(table, p_base_color);
+ Vector2 draw_ofs = Point2(wofs, y);
- if (p_mode==PROCESS_CACHE) {
+ if (p_mode == PROCESS_CACHE) {
- int idx=0;
+ int idx = 0;
//set minimums to zero
- for(int i=0;i<table->columns.size();i++) {
- table->columns[i].min_width=0;
- table->columns[i].width=0;
+ for (int i = 0; i < table->columns.size(); i++) {
+ table->columns[i].min_width = 0;
+ table->columns[i].width = 0;
}
//compute minimum width for each cell
- for (List<Item*>::Element *E=table->subitems.front();E;E=E->next()) {
- ERR_CONTINUE(E->get()->type!=ITEM_FRAME); //children should all be frames
- ItemFrame *frame = static_cast<ItemFrame*>(E->get());
+ for (List<Item *>::Element *E = table->subitems.front(); E; E = E->next()) {
+ ERR_CONTINUE(E->get()->type != ITEM_FRAME); //children should all be frames
+ ItemFrame *frame = static_cast<ItemFrame *>(E->get());
int column = idx % table->columns.size();
- int ly=0;
-
+ int ly = 0;
- for(int i=0;i<frame->lines.size();i++) {
+ for (int i = 0; i < frame->lines.size(); i++) {
- _process_line(frame,Point2(),ly,p_width,i,PROCESS_CACHE,cfont,Color());
- table->columns[column].min_width=MAX( table->columns[i].min_width, frame->lines[i].minimum_width );
+ _process_line(frame, Point2(), ly, p_width, i, PROCESS_CACHE, cfont, Color());
+ table->columns[column].min_width = MAX(table->columns[i].min_width, frame->lines[i].minimum_width);
}
idx++;
}
//compute available width and total radio (for expanders)
+ int total_ratio = 0;
+ int available_width = p_width - hseparation * (table->columns.size() - 1);
+ table->total_width = hseparation;
- int total_ratio=0;
- int available_width=p_width - hseparation * (table->columns.size() -1);
- table->total_width=hseparation;
-
- for(int i=0;i<table->columns.size();i++) {
- available_width-=table->columns[i].min_width;
+ for (int i = 0; i < table->columns.size(); i++) {
+ available_width -= table->columns[i].min_width;
if (table->columns[i].expand)
- total_ratio+=table->columns[i].expand_ratio;
+ total_ratio += table->columns[i].expand_ratio;
}
//assign actual widths
- for(int i=0;i<table->columns.size();i++) {
+ for (int i = 0; i < table->columns.size(); i++) {
table->columns[i].width = table->columns[i].min_width;
if (table->columns[i].expand)
- table->columns[i].width+=table->columns[i].expand_ratio*available_width/total_ratio;
- table->total_width+=table->columns[i].width+hseparation;
+ table->columns[i].width += table->columns[i].expand_ratio * available_width / total_ratio;
+ table->total_width += table->columns[i].width + hseparation;
}
//compute caches properly again with the right width
- idx=0;
- for (List<Item*>::Element *E=table->subitems.front();E;E=E->next()) {
- ERR_CONTINUE(E->get()->type!=ITEM_FRAME); //children should all be frames
- ItemFrame *frame = static_cast<ItemFrame*>(E->get());
+ idx = 0;
+ for (List<Item *>::Element *E = table->subitems.front(); E; E = E->next()) {
+ ERR_CONTINUE(E->get()->type != ITEM_FRAME); //children should all be frames
+ ItemFrame *frame = static_cast<ItemFrame *>(E->get());
int column = idx % table->columns.size();
+ for (int i = 0; i < frame->lines.size(); i++) {
- for(int i=0;i<frame->lines.size();i++) {
-
- int ly=0;
- _process_line(frame,Point2(),ly,table->columns[column].width,i,PROCESS_CACHE,cfont,Color());
- frame->lines[i].height_cache=ly; //actual height
- frame->lines[i].height_accum_cache=ly; //actual height
+ int ly = 0;
+ _process_line(frame, Point2(), ly, table->columns[column].width, i, PROCESS_CACHE, cfont, Color());
+ frame->lines[i].height_cache = ly; //actual height
+ frame->lines[i].height_accum_cache = ly; //actual height
}
idx++;
}
-
}
+ Point2 offset(align_ofs + hseparation, vseparation);
-
- Point2 offset(align_ofs+hseparation,vseparation);
-
- int row_height=0;
+ int row_height = 0;
//draw using computed caches
- int idx=0;
- for (List<Item*>::Element *E=table->subitems.front();E;E=E->next()) {
- ERR_CONTINUE(E->get()->type!=ITEM_FRAME); //children should all be frames
- ItemFrame *frame = static_cast<ItemFrame*>(E->get());
+ int idx = 0;
+ for (List<Item *>::Element *E = table->subitems.front(); E; E = E->next()) {
+ ERR_CONTINUE(E->get()->type != ITEM_FRAME); //children should all be frames
+ ItemFrame *frame = static_cast<ItemFrame *>(E->get());
int column = idx % table->columns.size();
- int ly=0;
- int yofs=0;
+ int ly = 0;
+ int yofs = 0;
+ int lines_h = frame->lines[frame->lines.size() - 1].height_accum_cache - (frame->lines[0].height_accum_cache - frame->lines[0].height_cache);
+ int lines_ofs = p_ofs.y + offset.y + draw_ofs.y;
- int lines_h = frame->lines[frame->lines.size()-1].height_accum_cache - (frame->lines[0].height_accum_cache - frame->lines[0].height_cache);
- int lines_ofs = p_ofs.y+offset.y+draw_ofs.y;
-
- bool visible = lines_ofs < get_size().height && lines_ofs+lines_h >=0;
-
- for(int i=0;i<frame->lines.size();i++) {
+ bool visible = lines_ofs < get_size().height && lines_ofs + lines_h >= 0;
+ for (int i = 0; i < frame->lines.size(); i++) {
if (visible) {
- if (p_mode==PROCESS_DRAW) {
- _process_line(frame,p_ofs+offset+draw_ofs+Vector2(0,yofs),ly,table->columns[column].width,i,PROCESS_DRAW,cfont,ccolor);
- } else if (p_mode==PROCESS_POINTER) {
- _process_line(frame,p_ofs+offset+draw_ofs+Vector2(0,yofs),ly,table->columns[column].width,i,PROCESS_POINTER,cfont,ccolor,p_click_pos,r_click_item,r_click_char,r_outside);
+ if (p_mode == PROCESS_DRAW) {
+ _process_line(frame, p_ofs + offset + draw_ofs + Vector2(0, yofs), ly, table->columns[column].width, i, PROCESS_DRAW, cfont, ccolor);
+ } else if (p_mode == PROCESS_POINTER) {
+ _process_line(frame, p_ofs + offset + draw_ofs + Vector2(0, yofs), ly, table->columns[column].width, i, PROCESS_POINTER, cfont, ccolor, p_click_pos, r_click_item, r_click_char, r_outside);
}
}
- yofs+=frame->lines[i].height_cache;
- if (p_mode==PROCESS_CACHE) {
- frame->lines[i].height_accum_cache=offset.y+draw_ofs.y+frame->lines[i].height_cache;
+ yofs += frame->lines[i].height_cache;
+ if (p_mode == PROCESS_CACHE) {
+ frame->lines[i].height_accum_cache = offset.y + draw_ofs.y + frame->lines[i].height_cache;
}
-
}
- row_height=MAX(yofs,row_height);
- offset.x+=table->columns[column].width+hseparation;
+ row_height = MAX(yofs, row_height);
+ offset.x += table->columns[column].width + hseparation;
- if (column==table->columns.size()-1) {
+ if (column == table->columns.size() - 1) {
- offset.y+=row_height+vseparation;
- offset.x=hseparation;
- row_height=0;
+ offset.y += row_height + vseparation;
+ offset.x = hseparation;
+ row_height = 0;
}
idx++;
}
int total_height = offset.y;
if (row_height) {
- total_height=row_height+vseparation;
+ total_height = row_height + vseparation;
}
-
-
- ADVANCE( table->total_width );
- CHECK_HEIGHT( total_height );
+ ADVANCE(table->total_width);
+ CHECK_HEIGHT(total_height);
} break;
default: {}
-
}
-
Item *itp = it;
it = _get_next_item(it);
- if (p_mode == PROCESS_POINTER && r_click_item && itp && !it && p_click_pos.y>p_ofs.y+y+lh) {
+ if (p_mode == PROCESS_POINTER && r_click_item && itp && !it && p_click_pos.y > p_ofs.y + y + lh) {
//at the end of all, return this
- if (r_outside) *r_outside=true;
- *r_click_item=itp;
- *r_click_char=rchar;
+ if (r_outside) *r_outside = true;
+ *r_click_item = itp;
+ *r_click_char = rchar;
return;
}
- if (it && (p_line+1 < p_frame->lines.size()) && p_frame->lines[p_line+1].from==it) {
+ if (it && (p_line + 1 < p_frame->lines.size()) && p_frame->lines[p_line + 1].from == it) {
- if (p_mode==PROCESS_POINTER && r_click_item && p_click_pos.y>=p_ofs.y+y && p_click_pos.y<=p_ofs.y+y+lh) {
+ if (p_mode == PROCESS_POINTER && r_click_item && p_click_pos.y >= p_ofs.y + y && p_click_pos.y <= p_ofs.y + y + lh) {
//went to next line, but pointer was on the previous one
- if (r_outside) *r_outside=true;
- *r_click_item=itp;
- *r_click_char=rchar;
+ if (r_outside) *r_outside = true;
+ *r_click_item = itp;
+ *r_click_char = rchar;
return;
}
@@ -602,7 +563,6 @@ if (m_height > line_height) {\
#undef ENSURE_WIDTH
#undef ADVANCE
#undef CHECK_HEIGHT
-
}
void RichTextLabel::_scroll_changed(double) {
@@ -610,44 +570,40 @@ void RichTextLabel::_scroll_changed(double) {
if (updating_scroll)
return;
- if (scroll_follow && vscroll->get_value()>=(vscroll->get_max()-vscroll->get_page()))
- scroll_following=true;
+ if (scroll_follow && vscroll->get_value() >= (vscroll->get_max() - vscroll->get_page()))
+ scroll_following = true;
else
- scroll_following=false;
+ scroll_following = false;
update();
-
}
void RichTextLabel::_update_scroll() {
- int total_height=0;
+ int total_height = 0;
if (main->lines.size())
- total_height=main->lines[main->lines.size()-1].height_accum_cache;
+ total_height = main->lines[main->lines.size() - 1].height_accum_cache;
bool exceeds = total_height > get_size().height && scroll_active;
-
- if (exceeds!=scroll_visible) {
+ if (exceeds != scroll_visible) {
if (exceeds) {
- scroll_visible=true;
- main->first_invalid_line=0;
- scroll_w=vscroll->get_combined_minimum_size().width;
+ scroll_visible = true;
+ main->first_invalid_line = 0;
+ scroll_w = vscroll->get_combined_minimum_size().width;
vscroll->show();
- vscroll->set_anchor_and_margin( MARGIN_LEFT, ANCHOR_END,scroll_w);
+ vscroll->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, scroll_w);
_validate_line_caches(main);
} else {
- scroll_visible=false;
+ scroll_visible = false;
vscroll->hide();
- scroll_w=0;
+ scroll_w = 0;
_validate_line_caches(main);
}
-
}
-
}
void RichTextLabel::_notification(int p_what) {
@@ -656,7 +612,7 @@ void RichTextLabel::_notification(int p_what) {
case NOTIFICATION_RESIZED: {
- main->first_invalid_line=0; //invalidate ALL
+ main->first_invalid_line = 0; //invalidate ALL
update();
} break;
@@ -665,7 +621,7 @@ void RichTextLabel::_notification(int p_what) {
if (bbcode != "")
set_bbcode(bbcode);
- main->first_invalid_line=0; //invalidate ALL
+ main->first_invalid_line = 0; //invalidate ALL
update();
} break;
@@ -683,14 +639,13 @@ void RichTextLabel::_notification(int p_what) {
_validate_line_caches(main);
_update_scroll();
-
- RID ci=get_canvas_item();
+ RID ci = get_canvas_item();
Size2 size = get_size();
if (has_focus()) {
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci,true);
- draw_style_box(get_stylebox("focus"),Rect2(Point2(),size));
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci,false);
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, true);
+ draw_style_box(get_stylebox("focus"), Rect2(Point2(), size));
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, false);
}
int ofs = vscroll->get_value();
@@ -699,36 +654,35 @@ void RichTextLabel::_notification(int p_what) {
int from_line = 0;
int total_chars = 0;
- while (from_line<main->lines.size()) {
+ while (from_line < main->lines.size()) {
- if (main->lines[from_line].height_accum_cache>=ofs)
+ if (main->lines[from_line].height_accum_cache >= ofs)
break;
from_line++;
- total_chars+=main->lines[from_line].char_count;
+ total_chars += main->lines[from_line].char_count;
}
- if (from_line>=main->lines.size())
+ if (from_line >= main->lines.size())
break; //nothing to draw
int y = (main->lines[from_line].height_accum_cache - main->lines[from_line].height_cache) - ofs;
- Ref<Font> base_font=get_font("normal_font");
- Color base_color=get_color("default_color");
+ Ref<Font> base_font = get_font("normal_font");
+ Color base_color = get_color("default_color");
- while (y<size.height && from_line<main->lines.size()) {
+ while (y < size.height && from_line < main->lines.size()) {
- _process_line(main,Point2(),y,size.width-scroll_w,from_line,PROCESS_DRAW,base_font,base_color,Point2i(),NULL,NULL,NULL,total_chars);
- total_chars+=main->lines[from_line].char_count;
+ _process_line(main, Point2(), y, size.width - scroll_w, from_line, PROCESS_DRAW, base_font, base_color, Point2i(), NULL, NULL, NULL, total_chars);
+ total_chars += main->lines[from_line].char_count;
from_line++;
}
}
}
}
-
-void RichTextLabel::_find_click(ItemFrame* p_frame,const Point2i& p_click,Item **r_click_item,int *r_click_char,bool *r_outside) {
+void RichTextLabel::_find_click(ItemFrame *p_frame, const Point2i &p_click, Item **r_click_item, int *r_click_char, bool *r_outside) {
if (r_click_item)
- *r_click_item=NULL;
+ *r_click_item = NULL;
Size2 size = get_size();
@@ -737,148 +691,137 @@ void RichTextLabel::_find_click(ItemFrame* p_frame,const Point2i& p_click,Item *
//todo, change to binary search
int from_line = 0;
- while (from_line<p_frame->lines.size()) {
+ while (from_line < p_frame->lines.size()) {
- if (p_frame->lines[from_line].height_accum_cache>=ofs)
+ if (p_frame->lines[from_line].height_accum_cache >= ofs)
break;
from_line++;
}
-
- if (from_line>=p_frame->lines.size())
+ if (from_line >= p_frame->lines.size())
return;
-
int y = (p_frame->lines[from_line].height_accum_cache - p_frame->lines[from_line].height_cache) - ofs;
- Ref<Font> base_font=get_font("normal_font");
- Color base_color=get_color("default_color");
-
+ Ref<Font> base_font = get_font("normal_font");
+ Color base_color = get_color("default_color");
- while (y<size.height && from_line<p_frame->lines.size()) {
+ while (y < size.height && from_line < p_frame->lines.size()) {
- _process_line(p_frame,Point2(),y,size.width-scroll_w,from_line,PROCESS_POINTER,base_font,base_color,p_click,r_click_item,r_click_char,r_outside);
+ _process_line(p_frame, Point2(), y, size.width - scroll_w, from_line, PROCESS_POINTER, base_font, base_color, p_click, r_click_item, r_click_char, r_outside);
if (r_click_item && *r_click_item)
return;
from_line++;
}
-
-
}
-
-Control::CursorShape RichTextLabel::get_cursor_shape(const Point2& p_pos) const {
+Control::CursorShape RichTextLabel::get_cursor_shape(const Point2 &p_pos) const {
if (!underline_meta || selection.click)
return CURSOR_ARROW;
- if (main->first_invalid_line<main->lines.size())
+ if (main->first_invalid_line < main->lines.size())
return CURSOR_ARROW; //invalid
- int line=0;
- Item *item=NULL;
-
- ((RichTextLabel*)(this))->_find_click(main,p_pos,&item,&line);
+ int line = 0;
+ Item *item = NULL;
+ ((RichTextLabel *)(this))->_find_click(main, p_pos, &item, &line);
- if (item && ((RichTextLabel*)(this))->_find_meta(item,NULL))
+ if (item && ((RichTextLabel *)(this))->_find_meta(item, NULL))
return CURSOR_POINTING_HAND;
return CURSOR_ARROW;
}
-
void RichTextLabel::_gui_input(InputEvent p_event) {
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- if (main->first_invalid_line<main->lines.size())
+ if (main->first_invalid_line < main->lines.size())
return;
- const InputEventMouseButton& b = p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
- if (b.button_index==BUTTON_LEFT) {
+ if (b.button_index == BUTTON_LEFT) {
if (true) {
-
if (b.pressed && !b.doubleclick) {
- int line=0;
- Item *item=NULL;
+ int line = 0;
+ Item *item = NULL;
bool outside;
- _find_click(main,Point2i(b.x,b.y),&item,&line,&outside);
+ _find_click(main, Point2i(b.x, b.y), &item, &line, &outside);
if (item) {
Variant meta;
- if (!outside && _find_meta(item,&meta)) {
+ if (!outside && _find_meta(item, &meta)) {
//meta clicked
- emit_signal("meta_clicked",meta);
+ emit_signal("meta_clicked", meta);
} else if (selection.enabled) {
- selection.click=item;
- selection.click_char=line;
-
+ selection.click = item;
+ selection.click_char = line;
}
-
}
} else if (!b.pressed) {
- selection.click=NULL;
+ selection.click = NULL;
}
}
}
- if (b.button_index==BUTTON_WHEEL_UP) {
+ if (b.button_index == BUTTON_WHEEL_UP) {
if (scroll_active)
- vscroll->set_value( vscroll->get_value()-vscroll->get_page()/8 );
+ vscroll->set_value(vscroll->get_value() - vscroll->get_page() / 8);
}
- if (b.button_index==BUTTON_WHEEL_DOWN) {
+ if (b.button_index == BUTTON_WHEEL_DOWN) {
if (scroll_active)
- vscroll->set_value( vscroll->get_value()+vscroll->get_page()/8 );
+ vscroll->set_value(vscroll->get_value() + vscroll->get_page() / 8);
}
} break;
case InputEvent::KEY: {
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
if (k.pressed && !k.mod.alt && !k.mod.shift && !k.mod.meta) {
- bool handled=true;
- switch(k.scancode) {
+ bool handled = true;
+ switch (k.scancode) {
case KEY_PAGEUP: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( vscroll->get_value() - vscroll->get_page() );
+ vscroll->set_value(vscroll->get_value() - vscroll->get_page());
} break;
case KEY_PAGEDOWN: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( vscroll->get_value() + vscroll->get_page() );
+ vscroll->set_value(vscroll->get_value() + vscroll->get_page());
} break;
case KEY_UP: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( vscroll->get_value() - get_font("normal_font")->get_height() );
+ vscroll->set_value(vscroll->get_value() - get_font("normal_font")->get_height());
} break;
case KEY_DOWN: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( vscroll->get_value() + get_font("normal_font")->get_height() );
+ vscroll->set_value(vscroll->get_value() + get_font("normal_font")->get_height());
} break;
case KEY_HOME: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( 0 );
+ vscroll->set_value(0);
} break;
case KEY_END: {
if (vscroll->is_visible_in_tree())
- vscroll->set_value( vscroll->get_max() );
+ vscroll->set_value(vscroll->get_max());
} break;
case KEY_INSERT:
case KEY_C: {
@@ -886,14 +829,13 @@ void RichTextLabel::_gui_input(InputEvent p_event) {
if (k.mod.command) {
selection_copy();
} else {
- handled=false;
+ handled = false;
}
} break;
- default: handled=false;
+ default: handled = false;
}
-
if (handled)
accept_event();
}
@@ -901,138 +843,131 @@ void RichTextLabel::_gui_input(InputEvent p_event) {
} break;
case InputEvent::MOUSE_MOTION: {
- if (main->first_invalid_line<main->lines.size())
+ if (main->first_invalid_line < main->lines.size())
return;
- const InputEventMouseMotion& m = p_event.mouse_motion;
+ const InputEventMouseMotion &m = p_event.mouse_motion;
if (selection.click) {
- int line=0;
- Item *item=NULL;
- _find_click(main,Point2i(m.x,m.y),&item,&line);
+ int line = 0;
+ Item *item = NULL;
+ _find_click(main, Point2i(m.x, m.y), &item, &line);
if (!item)
return; // do not update
+ selection.from = selection.click;
+ selection.from_char = selection.click_char;
- selection.from=selection.click;
- selection.from_char=selection.click_char;
-
- selection.to=item;
- selection.to_char=line;
+ selection.to = item;
+ selection.to_char = line;
- bool swap=false;
- if (selection.from->index > selection.to->index )
- swap=true;
+ bool swap = false;
+ if (selection.from->index > selection.to->index)
+ swap = true;
else if (selection.from->index == selection.to->index) {
if (selection.from_char > selection.to_char)
- swap=true;
+ swap = true;
else if (selection.from_char == selection.to_char) {
- selection.active=false;
+ selection.active = false;
return;
}
}
if (swap) {
- SWAP( selection.from, selection.to );
- SWAP( selection.from_char, selection.to_char );
+ SWAP(selection.from, selection.to);
+ SWAP(selection.from_char, selection.to_char);
}
- selection.active=true;
+ selection.active = true;
update();
-
}
} break;
}
-
}
Ref<Font> RichTextLabel::_find_font(Item *p_item) {
- Item *fontitem=p_item;
+ Item *fontitem = p_item;
- while(fontitem) {
+ while (fontitem) {
- if (fontitem->type==ITEM_FONT) {
+ if (fontitem->type == ITEM_FONT) {
- ItemFont *fi = static_cast<ItemFont*>(fontitem);
+ ItemFont *fi = static_cast<ItemFont *>(fontitem);
return fi->font;
}
- fontitem=fontitem->parent;
+ fontitem = fontitem->parent;
}
return Ref<Font>();
}
-int RichTextLabel::_find_margin(Item *p_item,const Ref<Font>& p_base_font) {
+int RichTextLabel::_find_margin(Item *p_item, const Ref<Font> &p_base_font) {
- Item *item=p_item;
+ Item *item = p_item;
- int margin=0;
+ int margin = 0;
- while(item) {
+ while (item) {
- if (item->type==ITEM_INDENT) {
+ if (item->type == ITEM_INDENT) {
- Ref<Font> font=_find_font(item);
+ Ref<Font> font = _find_font(item);
if (font.is_null())
- font=p_base_font;
+ font = p_base_font;
- ItemIndent *indent = static_cast<ItemIndent*>(item);
+ ItemIndent *indent = static_cast<ItemIndent *>(item);
- margin+=indent->level*tab_size*font->get_char_size(' ').width;
+ margin += indent->level * tab_size * font->get_char_size(' ').width;
- } else if (item->type==ITEM_LIST) {
+ } else if (item->type == ITEM_LIST) {
- Ref<Font> font=_find_font(item);
+ Ref<Font> font = _find_font(item);
if (font.is_null())
- font=p_base_font;
-
+ font = p_base_font;
}
- item=item->parent;
+ item = item->parent;
}
return margin;
}
-
RichTextLabel::Align RichTextLabel::_find_align(Item *p_item) {
- Item *item=p_item;
+ Item *item = p_item;
- while(item) {
+ while (item) {
- if (item->type==ITEM_ALIGN) {
+ if (item->type == ITEM_ALIGN) {
- ItemAlign *align = static_cast<ItemAlign*>(item);
+ ItemAlign *align = static_cast<ItemAlign *>(item);
return align->align;
-
}
- item=item->parent;
+ item = item->parent;
}
return default_align;
}
-Color RichTextLabel::_find_color(Item *p_item,const Color& p_default_color) {
+Color RichTextLabel::_find_color(Item *p_item, const Color &p_default_color) {
- Item *item=p_item;
+ Item *item = p_item;
- while(item) {
+ while (item) {
- if (item->type==ITEM_COLOR) {
+ if (item->type == ITEM_COLOR) {
- ItemColor *color = static_cast<ItemColor*>(item);
+ ItemColor *color = static_cast<ItemColor *>(item);
return color->color;
-
}
- item=item->parent;
+ item = item->parent;
}
return p_default_color;
@@ -1040,182 +975,165 @@ Color RichTextLabel::_find_color(Item *p_item,const Color& p_default_color) {
bool RichTextLabel::_find_underline(Item *p_item) {
- Item *item=p_item;
+ Item *item = p_item;
- while(item) {
+ while (item) {
- if (item->type==ITEM_UNDERLINE) {
+ if (item->type == ITEM_UNDERLINE) {
return true;
-
}
- item=item->parent;
+ item = item->parent;
}
return false;
}
-bool RichTextLabel::_find_meta(Item *p_item,Variant *r_meta) {
+bool RichTextLabel::_find_meta(Item *p_item, Variant *r_meta) {
- Item *item=p_item;
+ Item *item = p_item;
- while(item) {
+ while (item) {
- if (item->type==ITEM_META) {
+ if (item->type == ITEM_META) {
- ItemMeta *meta = static_cast<ItemMeta*>(item);
+ ItemMeta *meta = static_cast<ItemMeta *>(item);
if (r_meta)
- *r_meta=meta->meta;
+ *r_meta = meta->meta;
return true;
-
}
- item=item->parent;
+ item = item->parent;
}
return false;
-
}
-void RichTextLabel::_validate_line_caches(ItemFrame* p_frame) {
+void RichTextLabel::_validate_line_caches(ItemFrame *p_frame) {
- if (p_frame->first_invalid_line==p_frame->lines.size())
+ if (p_frame->first_invalid_line == p_frame->lines.size())
return;
//validate invalid lines!s
Size2 size = get_size();
- Ref<Font> base_font=get_font("normal_font");
-
- for(int i=p_frame->first_invalid_line;i<p_frame->lines.size();i++) {
-
- int y=0;
- _process_line(p_frame,Point2(),y,size.width-scroll_w,i,PROCESS_CACHE,base_font,Color());
- p_frame->lines[i].height_cache=y;
- p_frame->lines[i].height_accum_cache=y;
+ Ref<Font> base_font = get_font("normal_font");
- if (i>0)
- p_frame->lines[i].height_accum_cache+=p_frame->lines[i-1].height_accum_cache;
+ for (int i = p_frame->first_invalid_line; i < p_frame->lines.size(); i++) {
+ int y = 0;
+ _process_line(p_frame, Point2(), y, size.width - scroll_w, i, PROCESS_CACHE, base_font, Color());
+ p_frame->lines[i].height_cache = y;
+ p_frame->lines[i].height_accum_cache = y;
+ if (i > 0)
+ p_frame->lines[i].height_accum_cache += p_frame->lines[i - 1].height_accum_cache;
}
- int total_height=0;
+ int total_height = 0;
if (p_frame->lines.size())
- total_height=p_frame->lines[p_frame->lines.size()-1].height_accum_cache;
+ total_height = p_frame->lines[p_frame->lines.size() - 1].height_accum_cache;
- main->first_invalid_line=p_frame->lines.size();
+ main->first_invalid_line = p_frame->lines.size();
- updating_scroll=true;
+ updating_scroll = true;
vscroll->set_max(total_height);
vscroll->set_page(size.height);
if (scroll_follow && scroll_following)
- vscroll->set_value(total_height-size.height);
-
- updating_scroll=false;
+ vscroll->set_value(total_height - size.height);
+ updating_scroll = false;
}
+void RichTextLabel::_invalidate_current_line(ItemFrame *p_frame) {
-void RichTextLabel::_invalidate_current_line(ItemFrame* p_frame) {
-
- if (p_frame->lines.size()-1 <= p_frame->first_invalid_line) {
+ if (p_frame->lines.size() - 1 <= p_frame->first_invalid_line) {
- p_frame->first_invalid_line=p_frame->lines.size()-1;
+ p_frame->first_invalid_line = p_frame->lines.size() - 1;
update();
}
}
-void RichTextLabel::add_text(const String& p_text) {
+void RichTextLabel::add_text(const String &p_text) {
- if (current->type==ITEM_TABLE)
+ if (current->type == ITEM_TABLE)
return; //can't add anything here
- int pos=0;
+ int pos = 0;
- while (pos<p_text.length()) {
+ while (pos < p_text.length()) {
- int end=p_text.find("\n",pos);
+ int end = p_text.find("\n", pos);
String line;
- bool eol=false;
- if (end==-1) {
+ bool eol = false;
+ if (end == -1) {
- end=p_text.length();
+ end = p_text.length();
} else {
- eol=true;
+ eol = true;
}
- if (pos==0 && end==p_text.length())
- line=p_text;
+ if (pos == 0 && end == p_text.length())
+ line = p_text;
else
- line=p_text.substr(pos,end-pos);
+ line = p_text.substr(pos, end - pos);
- if (line.length()>0) {
+ if (line.length() > 0) {
- if (current->subitems.size() && current->subitems.back()->get()->type==ITEM_TEXT) {
+ if (current->subitems.size() && current->subitems.back()->get()->type == ITEM_TEXT) {
//append text condition!
- ItemText *ti = static_cast<ItemText*>(current->subitems.back()->get());
- ti->text+=line;
+ ItemText *ti = static_cast<ItemText *>(current->subitems.back()->get());
+ ti->text += line;
_invalidate_current_line(main);
} else {
//append item condition
- ItemText *item = memnew( ItemText );
- item->text=line;
- _add_item(item,false);
-
+ ItemText *item = memnew(ItemText);
+ item->text = line;
+ _add_item(item, false);
}
-
-
}
if (eol) {
- ItemNewline *item = memnew( ItemNewline );
- item->line=current_frame->lines.size();
- _add_item(item,false);
- current_frame->lines.resize(current_frame->lines.size()+1);
- if (item->type!=ITEM_NEWLINE)
- current_frame->lines[current_frame->lines.size()-1].from=item;
+ ItemNewline *item = memnew(ItemNewline);
+ item->line = current_frame->lines.size();
+ _add_item(item, false);
+ current_frame->lines.resize(current_frame->lines.size() + 1);
+ if (item->type != ITEM_NEWLINE)
+ current_frame->lines[current_frame->lines.size() - 1].from = item;
_invalidate_current_line(current_frame);
-
}
- pos=end+1;
+ pos = end + 1;
}
}
void RichTextLabel::_add_item(Item *p_item, bool p_enter, bool p_ensure_newline) {
-
-
- p_item->parent=current;
- p_item->E=current->subitems.push_back(p_item);
- p_item->index=current_idx++;
-
+ p_item->parent = current;
+ p_item->E = current->subitems.push_back(p_item);
+ p_item->index = current_idx++;
if (p_enter)
- current=p_item;
+ current = p_item;
- if (p_ensure_newline && current_frame->lines[current_frame->lines.size()-1].from) {
+ if (p_ensure_newline && current_frame->lines[current_frame->lines.size() - 1].from) {
_invalidate_current_line(current_frame);
- current_frame->lines.resize( current_frame->lines.size() +1 );
-
+ current_frame->lines.resize(current_frame->lines.size() + 1);
}
- if (current_frame->lines[current_frame->lines.size()-1].from==NULL) {
- current_frame->lines[current_frame->lines.size()-1].from=p_item;
+ if (current_frame->lines[current_frame->lines.size() - 1].from == NULL) {
+ current_frame->lines[current_frame->lines.size() - 1].from = p_item;
}
- p_item->line=current_frame->lines.size()-1;
+ p_item->line = current_frame->lines.size() - 1;
_invalidate_current_line(current_frame);
-
}
-void RichTextLabel::_remove_item(Item* p_item, const int p_line, const int p_subitem_line) {
-
+void RichTextLabel::_remove_item(Item *p_item, const int p_line, const int p_subitem_line) {
int size = p_item->subitems.size();
if (size == 0) {
@@ -1227,37 +1145,33 @@ void RichTextLabel::_remove_item(Item* p_item, const int p_line, const int p_sub
current->subitems[i]->line--;
}
}
- }
- else {
+ } else {
for (int i = 0; i < size; i++) {
_remove_item(p_item->subitems.front()->get(), p_line, p_subitem_line);
}
}
-
}
-void RichTextLabel::add_image(const Ref<Texture>& p_image) {
+void RichTextLabel::add_image(const Ref<Texture> &p_image) {
- if (current->type==ITEM_TABLE)
+ if (current->type == ITEM_TABLE)
return;
ERR_FAIL_COND(p_image.is_null());
- ItemImage *item = memnew( ItemImage );
-
- item->image=p_image;
- _add_item(item,false);
+ ItemImage *item = memnew(ItemImage);
+ item->image = p_image;
+ _add_item(item, false);
}
void RichTextLabel::add_newline() {
- if (current->type==ITEM_TABLE)
+ if (current->type == ITEM_TABLE)
return;
- ItemNewline *item = memnew( ItemNewline );
- item->line=current_frame->lines.size();
- current_frame->lines.resize(current_frame->lines.size()+1);
- _add_item(item,false);
-
+ ItemNewline *item = memnew(ItemNewline);
+ item->line = current_frame->lines.size();
+ current_frame->lines.resize(current_frame->lines.size() + 1);
+ _add_item(item, false);
}
bool RichTextLabel::remove_line(const int p_line) {
@@ -1280,155 +1194,144 @@ bool RichTextLabel::remove_line(const int p_line) {
return true;
}
-void RichTextLabel::push_font(const Ref<Font>& p_font) {
+void RichTextLabel::push_font(const Ref<Font> &p_font) {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
ERR_FAIL_COND(p_font.is_null());
- ItemFont *item = memnew( ItemFont );
-
- item->font=p_font;
- _add_item(item,true);
+ ItemFont *item = memnew(ItemFont);
+ item->font = p_font;
+ _add_item(item, true);
}
-void RichTextLabel::push_color(const Color& p_color) {
+void RichTextLabel::push_color(const Color &p_color) {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
- ItemColor *item = memnew( ItemColor );
-
- item->color=p_color;
- _add_item(item,true);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ItemColor *item = memnew(ItemColor);
+ item->color = p_color;
+ _add_item(item, true);
}
void RichTextLabel::push_underline() {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
- ItemUnderline *item = memnew( ItemUnderline );
-
- _add_item(item,true);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ItemUnderline *item = memnew(ItemUnderline);
+ _add_item(item, true);
}
void RichTextLabel::push_align(Align p_align) {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
-
- ItemAlign *item = memnew( ItemAlign );
- item->align=p_align;
- _add_item(item,true,true);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ItemAlign *item = memnew(ItemAlign);
+ item->align = p_align;
+ _add_item(item, true, true);
}
void RichTextLabel::push_indent(int p_level) {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
- ERR_FAIL_COND(p_level<0);
-
- ItemIndent *item = memnew( ItemIndent );
- item->level=p_level;
- _add_item(item,true,true);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ERR_FAIL_COND(p_level < 0);
+ ItemIndent *item = memnew(ItemIndent);
+ item->level = p_level;
+ _add_item(item, true, true);
}
void RichTextLabel::push_list(ListType p_list) {
- ERR_FAIL_COND(current->type==ITEM_TABLE);
- ERR_FAIL_INDEX(p_list,3);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ERR_FAIL_INDEX(p_list, 3);
- ItemList *item = memnew( ItemList );
-
- item->list_type=p_list;
- _add_item(item,true,true);
+ ItemList *item = memnew(ItemList);
+ item->list_type = p_list;
+ _add_item(item, true, true);
}
-void RichTextLabel::push_meta(const Variant& p_meta) {
-
- ERR_FAIL_COND(current->type==ITEM_TABLE);
- ItemMeta *item = memnew( ItemMeta );
+void RichTextLabel::push_meta(const Variant &p_meta) {
- item->meta=p_meta;
- _add_item(item,true);
+ ERR_FAIL_COND(current->type == ITEM_TABLE);
+ ItemMeta *item = memnew(ItemMeta);
+ item->meta = p_meta;
+ _add_item(item, true);
}
void RichTextLabel::push_table(int p_columns) {
- ERR_FAIL_COND( p_columns < 1);
- ItemTable *item = memnew( ItemTable );
+ ERR_FAIL_COND(p_columns < 1);
+ ItemTable *item = memnew(ItemTable);
item->columns.resize(p_columns);
- item->total_width=0;
- for(int i=0;i<item->columns.size();i++) {
- item->columns[i].expand=false;
- item->columns[i].expand_ratio=1;
+ item->total_width = 0;
+ for (int i = 0; i < item->columns.size(); i++) {
+ item->columns[i].expand = false;
+ item->columns[i].expand_ratio = 1;
}
- _add_item(item,true,true);
-
+ _add_item(item, true, true);
}
-void RichTextLabel::set_table_column_expand(int p_column,bool p_expand,int p_ratio) {
+void RichTextLabel::set_table_column_expand(int p_column, bool p_expand, int p_ratio) {
- ERR_FAIL_COND(current->type!=ITEM_TABLE);
- ItemTable *table = static_cast<ItemTable*>(current);
- ERR_FAIL_INDEX(p_column,table->columns.size());
- table->columns[p_column].expand=p_expand;
- table->columns[p_column].expand_ratio=p_ratio;
+ ERR_FAIL_COND(current->type != ITEM_TABLE);
+ ItemTable *table = static_cast<ItemTable *>(current);
+ ERR_FAIL_INDEX(p_column, table->columns.size());
+ table->columns[p_column].expand = p_expand;
+ table->columns[p_column].expand_ratio = p_ratio;
}
-void RichTextLabel::push_cell(){
+void RichTextLabel::push_cell() {
- ERR_FAIL_COND(current->type!=ITEM_TABLE);
+ ERR_FAIL_COND(current->type != ITEM_TABLE);
- ItemFrame *item = memnew( ItemFrame );
- item->parent_frame=current_frame;
- _add_item(item,true);
- current_frame=item;
- item->cell=true;
- item->parent_line=item->parent_frame->lines.size()-1;
+ ItemFrame *item = memnew(ItemFrame);
+ item->parent_frame = current_frame;
+ _add_item(item, true);
+ current_frame = item;
+ item->cell = true;
+ item->parent_line = item->parent_frame->lines.size() - 1;
item->lines.resize(1);
- item->lines[0].from=NULL;
- item->first_invalid_line=0;
-
+ item->lines[0].from = NULL;
+ item->first_invalid_line = 0;
}
int RichTextLabel::get_current_table_column() const {
- ERR_FAIL_COND_V(current->type!=ITEM_TABLE,-1);
+ ERR_FAIL_COND_V(current->type != ITEM_TABLE, -1);
- ItemTable *table = static_cast<ItemTable*>(current);
+ ItemTable *table = static_cast<ItemTable *>(current);
return table->subitems.size() % table->columns.size();
-
}
void RichTextLabel::pop() {
ERR_FAIL_COND(!current->parent);
- if (current->type==ITEM_FRAME) {
- current_frame = static_cast<ItemFrame*>(current)->parent_frame;
+ if (current->type == ITEM_FRAME) {
+ current_frame = static_cast<ItemFrame *>(current)->parent_frame;
}
- current=current->parent;
+ current = current->parent;
}
void RichTextLabel::clear() {
main->_clear_children();
- current=main;
- current_frame=main;
+ current = main;
+ current_frame = main;
main->lines.clear();
main->lines.resize(1);
- main->first_invalid_line=0;
+ main->first_invalid_line = 0;
update();
- selection.click=NULL;
- selection.active=false;
- current_idx=1;
-
+ selection.click = NULL;
+ selection.active = false;
+ current_idx = 1;
}
void RichTextLabel::set_tab_size(int p_spaces) {
- tab_size=p_spaces;
- main->first_invalid_line=0;
+ tab_size = p_spaces;
+ main->first_invalid_line = 0;
update();
}
@@ -1437,10 +1340,9 @@ int RichTextLabel::get_tab_size() const {
return tab_size;
}
-
void RichTextLabel::set_meta_underline(bool p_underline) {
- underline_meta=p_underline;
+ underline_meta = p_underline;
update();
}
@@ -1456,10 +1358,10 @@ void RichTextLabel::set_offset(int p_pixel) {
void RichTextLabel::set_scroll_active(bool p_active) {
- if (scroll_active==p_active)
+ if (scroll_active == p_active)
return;
- scroll_active=p_active;
+ scroll_active = p_active;
update();
}
@@ -1470,9 +1372,9 @@ bool RichTextLabel::is_scroll_active() const {
void RichTextLabel::set_scroll_follow(bool p_follow) {
- scroll_follow=p_follow;
- if (!vscroll->is_visible_in_tree() || vscroll->get_value()>=(vscroll->get_max()-vscroll->get_page()))
- scroll_following=true;
+ scroll_follow = p_follow;
+ if (!vscroll->is_visible_in_tree() || vscroll->get_value() >= (vscroll->get_max() - vscroll->get_page()))
+ scroll_following = true;
}
bool RichTextLabel::is_scroll_following() const {
@@ -1480,71 +1382,65 @@ bool RichTextLabel::is_scroll_following() const {
return scroll_follow;
}
-Error RichTextLabel::parse_bbcode(const String& p_bbcode) {
+Error RichTextLabel::parse_bbcode(const String &p_bbcode) {
clear();
return append_bbcode(p_bbcode);
}
-Error RichTextLabel::append_bbcode(const String& p_bbcode) {
+Error RichTextLabel::append_bbcode(const String &p_bbcode) {
int pos = 0;
List<String> tag_stack;
- Ref<Font> normal_font=get_font("normal_font");
- Ref<Font> bold_font=get_font("bold_font");
- Ref<Font> italics_font=get_font("italics_font");
- Ref<Font> bold_italics_font=get_font("bold_italics_font");
- Ref<Font> mono_font=get_font("mono_font");
+ Ref<Font> normal_font = get_font("normal_font");
+ Ref<Font> bold_font = get_font("bold_font");
+ Ref<Font> italics_font = get_font("italics_font");
+ Ref<Font> bold_italics_font = get_font("bold_italics_font");
+ Ref<Font> mono_font = get_font("mono_font");
- Color base_color=get_color("default_color");
+ Color base_color = get_color("default_color");
- int indent_level=0;
+ int indent_level = 0;
- bool in_bold=false;
- bool in_italics=false;
+ bool in_bold = false;
+ bool in_italics = false;
- while(pos < p_bbcode.length()) {
+ while (pos < p_bbcode.length()) {
+ int brk_pos = p_bbcode.find("[", pos);
- int brk_pos = p_bbcode.find("[",pos);
-
- if (brk_pos<0)
- brk_pos=p_bbcode.length();
+ if (brk_pos < 0)
+ brk_pos = p_bbcode.length();
if (brk_pos > pos) {
- add_text(p_bbcode.substr(pos,brk_pos-pos));
+ add_text(p_bbcode.substr(pos, brk_pos - pos));
}
- if (brk_pos==p_bbcode.length())
+ if (brk_pos == p_bbcode.length())
break; //nothing else o add
- int brk_end = p_bbcode.find("]",brk_pos+1);
+ int brk_end = p_bbcode.find("]", brk_pos + 1);
- if (brk_end==-1) {
+ if (brk_end == -1) {
//no close, add the rest
- add_text(p_bbcode.substr(brk_pos,p_bbcode.length()-brk_pos));
+ add_text(p_bbcode.substr(brk_pos, p_bbcode.length() - brk_pos));
break;
}
-
- String tag = p_bbcode.substr(brk_pos+1,brk_end-brk_pos-1);
-
+ String tag = p_bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
if (tag.begins_with("/") && tag_stack.size()) {
- bool tag_ok = tag_stack.size() && tag_stack.front()->get()==tag.substr(1,tag.length());
-
+ bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
-
- if (tag_stack.front()->get()=="b")
- in_bold=false;
- if (tag_stack.front()->get()=="i")
- in_italics=false;
- if (tag_stack.front()->get()=="indent")
+ if (tag_stack.front()->get() == "b")
+ in_bold = false;
+ if (tag_stack.front()->get() == "i")
+ in_italics = false;
+ if (tag_stack.front()->get() == "indent")
indent_level--;
-
if (!tag_ok) {
add_text("[");
@@ -1553,223 +1449,216 @@ Error RichTextLabel::append_bbcode(const String& p_bbcode) {
}
tag_stack.pop_front();
- pos=brk_end+1;
- if (tag!="/img")
+ pos = brk_end + 1;
+ if (tag != "/img")
pop();
- } else if (tag=="b") {
+ } else if (tag == "b") {
//use bold font
- in_bold=true;
+ in_bold = true;
if (in_italics)
push_font(bold_italics_font);
else
push_font(bold_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="i") {
+ } else if (tag == "i") {
//use italics font
- in_italics=true;
+ in_italics = true;
if (in_bold)
push_font(bold_italics_font);
else
push_font(italics_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="code") {
+ } else if (tag == "code") {
//use monospace font
push_font(mono_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("table=")) {
- int columns = tag.substr(6,tag.length()).to_int();
- if (columns<1)
- columns=1;
+ int columns = tag.substr(6, tag.length()).to_int();
+ if (columns < 1)
+ columns = 1;
//use monospace font
push_table(columns);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("table");
- } else if (tag=="cell") {
+ } else if (tag == "cell") {
push_cell();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("cell=")) {
- int ratio = tag.substr(6,tag.length()).to_int();
- if (ratio<1)
- ratio=1;
+ int ratio = tag.substr(6, tag.length()).to_int();
+ if (ratio < 1)
+ ratio = 1;
//use monospace font
- set_table_column_expand(get_current_table_column(),true,ratio);
+ set_table_column_expand(get_current_table_column(), true, ratio);
push_cell();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("cell");
- } else if (tag=="u") {
+ } else if (tag == "u") {
//use underline
push_underline();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="s") {
+ } else if (tag == "s") {
//use strikethrough (not supported underline instead)
push_underline();
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="center") {
+ } else if (tag == "center") {
//use underline
push_align(ALIGN_CENTER);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="fill") {
+ } else if (tag == "fill") {
//use underline
push_align(ALIGN_FILL);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="right") {
+ } else if (tag == "right") {
//use underline
push_align(ALIGN_RIGHT);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="ul") {
+ } else if (tag == "ul") {
//use underline
push_list(LIST_DOTS);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="ol") {
+ } else if (tag == "ol") {
//use underline
push_list(LIST_NUMBERS);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="indent") {
+ } else if (tag == "indent") {
//use underline
indent_level++;
push_indent(indent_level);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
- } else if (tag=="url") {
+ } else if (tag == "url") {
//use strikethrough (not supported underline instead)
- int end=p_bbcode.find("[",brk_end);
- if (end==-1)
- end=p_bbcode.length();
- String url = p_bbcode.substr(brk_end+1,end-brk_end-1);
+ int end = p_bbcode.find("[", brk_end);
+ if (end == -1)
+ end = p_bbcode.length();
+ String url = p_bbcode.substr(brk_end + 1, end - brk_end - 1);
push_meta(url);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("url=")) {
- String url = tag.substr(4,tag.length());
+ String url = tag.substr(4, tag.length());
push_meta(url);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("url");
- } else if (tag=="img") {
+ } else if (tag == "img") {
//use strikethrough (not supported underline instead)
- int end=p_bbcode.find("[",brk_end);
- if (end==-1)
- end=p_bbcode.length();
- String image = p_bbcode.substr(brk_end+1,end-brk_end-1);
+ int end = p_bbcode.find("[", brk_end);
+ if (end == -1)
+ end = p_bbcode.length();
+ String image = p_bbcode.substr(brk_end + 1, end - brk_end - 1);
- Ref<Texture> texture = ResourceLoader::load(image,"Texture");
+ Ref<Texture> texture = ResourceLoader::load(image, "Texture");
if (texture.is_valid())
add_image(texture);
- pos=end;
+ pos = end;
tag_stack.push_front(tag);
} else if (tag.begins_with("color=")) {
- String col = tag.substr(6,tag.length());
+ String col = tag.substr(6, tag.length());
Color color;
if (col.begins_with("#"))
- color=Color::html(col);
- else if (col=="aqua")
- color=Color::html("#00FFFF");
- else if (col=="black")
- color=Color::html("#000000");
- else if (col=="blue")
- color=Color::html("#0000FF");
- else if (col=="fuchsia")
- color=Color::html("#FF00FF");
- else if (col=="gray" || col=="grey")
- color=Color::html("#808080");
- else if (col=="green")
- color=Color::html("#008000");
- else if (col=="lime")
- color=Color::html("#00FF00");
- else if (col=="maroon")
- color=Color::html("#800000");
- else if (col=="navy")
- color=Color::html("#000080");
- else if (col=="olive")
- color=Color::html("#808000");
- else if (col=="purple")
- color=Color::html("#800080");
- else if (col=="red")
- color=Color::html("#FF0000");
- else if (col=="silver")
- color=Color::html("#C0C0C0");
- else if (col=="teal")
- color=Color::html("#008008");
- else if (col=="white")
- color=Color::html("#FFFFFF");
- else if (col=="yellow")
- color=Color::html("#FFFF00");
+ color = Color::html(col);
+ else if (col == "aqua")
+ color = Color::html("#00FFFF");
+ else if (col == "black")
+ color = Color::html("#000000");
+ else if (col == "blue")
+ color = Color::html("#0000FF");
+ else if (col == "fuchsia")
+ color = Color::html("#FF00FF");
+ else if (col == "gray" || col == "grey")
+ color = Color::html("#808080");
+ else if (col == "green")
+ color = Color::html("#008000");
+ else if (col == "lime")
+ color = Color::html("#00FF00");
+ else if (col == "maroon")
+ color = Color::html("#800000");
+ else if (col == "navy")
+ color = Color::html("#000080");
+ else if (col == "olive")
+ color = Color::html("#808000");
+ else if (col == "purple")
+ color = Color::html("#800080");
+ else if (col == "red")
+ color = Color::html("#FF0000");
+ else if (col == "silver")
+ color = Color::html("#C0C0C0");
+ else if (col == "teal")
+ color = Color::html("#008008");
+ else if (col == "white")
+ color = Color::html("#FFFFFF");
+ else if (col == "yellow")
+ color = Color::html("#FFFF00");
else
- color=base_color;
-
-
+ color = base_color;
push_color(color);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("color");
} else if (tag.begins_with("font=")) {
- String fnt = tag.substr(5,tag.length());
+ String fnt = tag.substr(5, tag.length());
-
- Ref<Font> font = ResourceLoader::load(fnt,"Font");
+ Ref<Font> font = ResourceLoader::load(fnt, "Font");
if (font.is_valid())
push_font(font);
else
push_font(normal_font);
- pos=brk_end+1;
+ pos = brk_end + 1;
tag_stack.push_front("font");
-
} else {
add_text("["); //ignore
- pos=brk_pos+1;
-
+ pos = brk_pos + 1;
}
}
return OK;
}
-
void RichTextLabel::scroll_to_line(int p_line) {
- ERR_FAIL_INDEX(p_line,main->lines.size());
+ ERR_FAIL_INDEX(p_line, main->lines.size());
_validate_line_caches(main);
- vscroll->set_value(main->lines[p_line].height_accum_cache-main->lines[p_line].height_cache);
-
+ vscroll->set_value(main->lines[p_line].height_accum_cache - main->lines[p_line].height_cache);
}
int RichTextLabel::get_line_count() const {
@@ -1779,75 +1668,72 @@ int RichTextLabel::get_line_count() const {
void RichTextLabel::set_selection_enabled(bool p_enabled) {
- selection.enabled=p_enabled;
+ selection.enabled = p_enabled;
if (!p_enabled) {
if (selection.active) {
- selection.active=false;
+ selection.active = false;
update();
}
set_focus_mode(FOCUS_NONE);
} else {
set_focus_mode(FOCUS_ALL);
}
-
}
-bool RichTextLabel::search(const String& p_string,bool p_from_selection) {
+bool RichTextLabel::search(const String &p_string, bool p_from_selection) {
- ERR_FAIL_COND_V(!selection.enabled,false);
- Item *it=main;
- int charidx=0;
+ ERR_FAIL_COND_V(!selection.enabled, false);
+ Item *it = main;
+ int charidx = 0;
if (p_from_selection && selection.active && selection.enabled) {
- it=selection.to;
- charidx=selection.to_char+1;
+ it = selection.to;
+ charidx = selection.to_char + 1;
}
- while(it) {
+ while (it) {
- if (it->type==ITEM_TEXT) {
+ if (it->type == ITEM_TEXT) {
- ItemText *t = static_cast<ItemText*>(it);
- int sp = t->text.find(p_string,charidx);
- if (sp!=-1) {
- selection.from=it;
- selection.from_char=sp;
- selection.to=it;
- selection.to_char=sp+p_string.length()-1;
- selection.active=true;
+ ItemText *t = static_cast<ItemText *>(it);
+ int sp = t->text.find(p_string, charidx);
+ if (sp != -1) {
+ selection.from = it;
+ selection.from_char = sp;
+ selection.to = it;
+ selection.to_char = sp + p_string.length() - 1;
+ selection.active = true;
update();
_validate_line_caches(main);
- int fh = _find_font(t).is_valid()?_find_font(t)->get_height():get_font("normal_font")->get_height();
+ int fh = _find_font(t).is_valid() ? _find_font(t)->get_height() : get_font("normal_font")->get_height();
- float offset =0;
+ float offset = 0;
int line = t->line;
- Item *item =t;
- while(item) {
- if (item->type==ITEM_FRAME) {
- ItemFrame *frame = static_cast<ItemFrame*>(item);
- if (line>=0 && line<frame->lines.size()) {
- offset+=frame->lines[line].height_accum_cache-frame->lines[line].height_cache;
- line=frame->line;
+ Item *item = t;
+ while (item) {
+ if (item->type == ITEM_FRAME) {
+ ItemFrame *frame = static_cast<ItemFrame *>(item);
+ if (line >= 0 && line < frame->lines.size()) {
+ offset += frame->lines[line].height_accum_cache - frame->lines[line].height_cache;
+ line = frame->line;
}
}
- item=item->parent;
+ item = item->parent;
}
- vscroll->set_value(offset-fh);
+ vscroll->set_value(offset - fh);
return true;
}
}
- it=_get_next_item(it,true);
- charidx=0;
-
+ it = _get_next_item(it, true);
+ charidx = 0;
}
return false;
-
}
void RichTextLabel::selection_copy() {
@@ -1857,37 +1743,36 @@ void RichTextLabel::selection_copy() {
String text;
- RichTextLabel::Item *item=selection.from;
+ RichTextLabel::Item *item = selection.from;
- while(item) {
+ while (item) {
- if (item->type==ITEM_TEXT) {
+ if (item->type == ITEM_TEXT) {
- String itext = static_cast<ItemText*>(item)->text;
- if (item==selection.from && item==selection.to) {
- text+=itext.substr(selection.from_char,selection.to_char-selection.from_char+1);
- } else if (item==selection.from) {
- text+=itext.substr(selection.from_char,itext.size());
- } else if (item==selection.to) {
- text+=itext.substr(0,selection.to_char+1);
+ String itext = static_cast<ItemText *>(item)->text;
+ if (item == selection.from && item == selection.to) {
+ text += itext.substr(selection.from_char, selection.to_char - selection.from_char + 1);
+ } else if (item == selection.from) {
+ text += itext.substr(selection.from_char, itext.size());
+ } else if (item == selection.to) {
+ text += itext.substr(0, selection.to_char + 1);
} else {
- text+=itext;
+ text += itext;
}
- } else if (item->type==ITEM_NEWLINE) {
- text+="\n";
+ } else if (item->type == ITEM_NEWLINE) {
+ text += "\n";
}
- if (item==selection.to)
+ if (item == selection.to)
break;
- item=_get_next_item(item,true);
+ item = _get_next_item(item, true);
}
- if (text!="") {
+ if (text != "") {
OS::get_singleton()->set_clipboard(text);
//print_line("COPY: "+text);
}
-
}
bool RichTextLabel::is_selection_enabled() const {
@@ -1895,8 +1780,8 @@ bool RichTextLabel::is_selection_enabled() const {
return selection.enabled;
}
-void RichTextLabel::set_bbcode(const String& p_bbcode) {
- bbcode=p_bbcode;
+void RichTextLabel::set_bbcode(const String &p_bbcode) {
+ bbcode = p_bbcode;
if (is_inside_tree() && use_bbcode)
parse_bbcode(p_bbcode);
else { // raw text
@@ -1911,9 +1796,9 @@ String RichTextLabel::get_bbcode() const {
}
void RichTextLabel::set_use_bbcode(bool p_enable) {
- if (use_bbcode==p_enable)
+ if (use_bbcode == p_enable)
return;
- use_bbcode=p_enable;
+ use_bbcode = p_enable;
set_bbcode(bbcode);
}
@@ -1927,109 +1812,106 @@ String RichTextLabel::get_text() {
Item *it = main;
while (it) {
if (it->type == ITEM_TEXT) {
- ItemText *t = static_cast<ItemText*>(it);
+ ItemText *t = static_cast<ItemText *>(it);
text += t->text;
} else if (it->type == ITEM_NEWLINE) {
text += "\n";
} else if (it->type == ITEM_INDENT) {
text += "\t";
}
- it=_get_next_item(it,true);
+ it = _get_next_item(it, true);
}
return text;
}
void RichTextLabel::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_gui_input"), &RichTextLabel::_gui_input);
+ ClassDB::bind_method(D_METHOD("_scroll_changed"), &RichTextLabel::_scroll_changed);
+ ClassDB::bind_method(D_METHOD("get_text"), &RichTextLabel::get_text);
+ ClassDB::bind_method(D_METHOD("add_text", "text"), &RichTextLabel::add_text);
+ ClassDB::bind_method(D_METHOD("add_image", "image:Texture"), &RichTextLabel::add_image);
+ ClassDB::bind_method(D_METHOD("newline"), &RichTextLabel::add_newline);
+ ClassDB::bind_method(D_METHOD("remove_line"), &RichTextLabel::remove_line);
+ ClassDB::bind_method(D_METHOD("push_font", "font"), &RichTextLabel::push_font);
+ ClassDB::bind_method(D_METHOD("push_color", "color"), &RichTextLabel::push_color);
+ ClassDB::bind_method(D_METHOD("push_align", "align"), &RichTextLabel::push_align);
+ ClassDB::bind_method(D_METHOD("push_indent", "level"), &RichTextLabel::push_indent);
+ ClassDB::bind_method(D_METHOD("push_list", "type"), &RichTextLabel::push_list);
+ ClassDB::bind_method(D_METHOD("push_meta", "data"), &RichTextLabel::push_meta);
+ ClassDB::bind_method(D_METHOD("push_underline"), &RichTextLabel::push_underline);
+ ClassDB::bind_method(D_METHOD("push_table", "columns"), &RichTextLabel::push_table);
+ ClassDB::bind_method(D_METHOD("set_table_column_expand", "column", "expand", "ratio"), &RichTextLabel::set_table_column_expand);
+ ClassDB::bind_method(D_METHOD("push_cell"), &RichTextLabel::push_cell);
+ ClassDB::bind_method(D_METHOD("pop"), &RichTextLabel::pop);
- ClassDB::bind_method(D_METHOD("_gui_input"),&RichTextLabel::_gui_input);
- ClassDB::bind_method(D_METHOD("_scroll_changed"),&RichTextLabel::_scroll_changed);
- ClassDB::bind_method(D_METHOD("get_text"),&RichTextLabel::get_text);
- ClassDB::bind_method(D_METHOD("add_text","text"),&RichTextLabel::add_text);
- ClassDB::bind_method(D_METHOD("add_image","image:Texture"),&RichTextLabel::add_image);
- ClassDB::bind_method(D_METHOD("newline"),&RichTextLabel::add_newline);
- ClassDB::bind_method(D_METHOD("remove_line"),&RichTextLabel::remove_line);
- ClassDB::bind_method(D_METHOD("push_font","font"),&RichTextLabel::push_font);
- ClassDB::bind_method(D_METHOD("push_color","color"),&RichTextLabel::push_color);
- ClassDB::bind_method(D_METHOD("push_align","align"),&RichTextLabel::push_align);
- ClassDB::bind_method(D_METHOD("push_indent","level"),&RichTextLabel::push_indent);
- ClassDB::bind_method(D_METHOD("push_list","type"),&RichTextLabel::push_list);
- ClassDB::bind_method(D_METHOD("push_meta","data"),&RichTextLabel::push_meta);
- ClassDB::bind_method(D_METHOD("push_underline"),&RichTextLabel::push_underline);
- ClassDB::bind_method(D_METHOD("push_table","columns"),&RichTextLabel::push_table);
- ClassDB::bind_method(D_METHOD("set_table_column_expand","column","expand","ratio"),&RichTextLabel::set_table_column_expand);
- ClassDB::bind_method(D_METHOD("push_cell"),&RichTextLabel::push_cell);
- ClassDB::bind_method(D_METHOD("pop"),&RichTextLabel::pop);
-
- ClassDB::bind_method(D_METHOD("clear"),&RichTextLabel::clear);
-
- ClassDB::bind_method(D_METHOD("set_meta_underline","enable"),&RichTextLabel::set_meta_underline);
- ClassDB::bind_method(D_METHOD("is_meta_underlined"),&RichTextLabel::is_meta_underlined);
+ ClassDB::bind_method(D_METHOD("clear"), &RichTextLabel::clear);
- ClassDB::bind_method(D_METHOD("set_scroll_active","active"),&RichTextLabel::set_scroll_active);
- ClassDB::bind_method(D_METHOD("is_scroll_active"),&RichTextLabel::is_scroll_active);
+ ClassDB::bind_method(D_METHOD("set_meta_underline", "enable"), &RichTextLabel::set_meta_underline);
+ ClassDB::bind_method(D_METHOD("is_meta_underlined"), &RichTextLabel::is_meta_underlined);
- ClassDB::bind_method(D_METHOD("set_scroll_follow","follow"),&RichTextLabel::set_scroll_follow);
- ClassDB::bind_method(D_METHOD("is_scroll_following"),&RichTextLabel::is_scroll_following);
+ ClassDB::bind_method(D_METHOD("set_scroll_active", "active"), &RichTextLabel::set_scroll_active);
+ ClassDB::bind_method(D_METHOD("is_scroll_active"), &RichTextLabel::is_scroll_active);
- ClassDB::bind_method(D_METHOD("get_v_scroll"),&RichTextLabel::get_v_scroll);
+ ClassDB::bind_method(D_METHOD("set_scroll_follow", "follow"), &RichTextLabel::set_scroll_follow);
+ ClassDB::bind_method(D_METHOD("is_scroll_following"), &RichTextLabel::is_scroll_following);
- ClassDB::bind_method(D_METHOD("scroll_to_line","line"),&RichTextLabel::scroll_to_line);
+ ClassDB::bind_method(D_METHOD("get_v_scroll"), &RichTextLabel::get_v_scroll);
- ClassDB::bind_method(D_METHOD("set_tab_size","spaces"),&RichTextLabel::set_tab_size);
- ClassDB::bind_method(D_METHOD("get_tab_size"),&RichTextLabel::get_tab_size);
+ ClassDB::bind_method(D_METHOD("scroll_to_line", "line"), &RichTextLabel::scroll_to_line);
- ClassDB::bind_method(D_METHOD("set_selection_enabled","enabled"),&RichTextLabel::set_selection_enabled);
- ClassDB::bind_method(D_METHOD("is_selection_enabled"),&RichTextLabel::is_selection_enabled);
+ ClassDB::bind_method(D_METHOD("set_tab_size", "spaces"), &RichTextLabel::set_tab_size);
+ ClassDB::bind_method(D_METHOD("get_tab_size"), &RichTextLabel::get_tab_size);
- ClassDB::bind_method(D_METHOD("parse_bbcode", "bbcode"),&RichTextLabel::parse_bbcode);
- ClassDB::bind_method(D_METHOD("append_bbcode", "bbcode"),&RichTextLabel::append_bbcode);
+ ClassDB::bind_method(D_METHOD("set_selection_enabled", "enabled"), &RichTextLabel::set_selection_enabled);
+ ClassDB::bind_method(D_METHOD("is_selection_enabled"), &RichTextLabel::is_selection_enabled);
- ClassDB::bind_method(D_METHOD("set_bbcode","text"),&RichTextLabel::set_bbcode);
- ClassDB::bind_method(D_METHOD("get_bbcode"),&RichTextLabel::get_bbcode);
+ ClassDB::bind_method(D_METHOD("parse_bbcode", "bbcode"), &RichTextLabel::parse_bbcode);
+ ClassDB::bind_method(D_METHOD("append_bbcode", "bbcode"), &RichTextLabel::append_bbcode);
- ClassDB::bind_method(D_METHOD("set_visible_characters","amount"),&RichTextLabel::set_visible_characters);
- ClassDB::bind_method(D_METHOD("get_visible_characters"),&RichTextLabel::get_visible_characters);
+ ClassDB::bind_method(D_METHOD("set_bbcode", "text"), &RichTextLabel::set_bbcode);
+ ClassDB::bind_method(D_METHOD("get_bbcode"), &RichTextLabel::get_bbcode);
- ClassDB::bind_method(D_METHOD("get_total_character_count"),&RichTextLabel::get_total_character_count);
+ ClassDB::bind_method(D_METHOD("set_visible_characters", "amount"), &RichTextLabel::set_visible_characters);
+ ClassDB::bind_method(D_METHOD("get_visible_characters"), &RichTextLabel::get_visible_characters);
- ClassDB::bind_method(D_METHOD("set_use_bbcode","enable"),&RichTextLabel::set_use_bbcode);
- ClassDB::bind_method(D_METHOD("is_using_bbcode"),&RichTextLabel::is_using_bbcode);
+ ClassDB::bind_method(D_METHOD("get_total_character_count"), &RichTextLabel::get_total_character_count);
- ADD_GROUP("BBCode","bbcode_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"bbcode_enabled"),"set_use_bbcode","is_using_bbcode");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"bbcode_text",PROPERTY_HINT_MULTILINE_TEXT),"set_bbcode","get_bbcode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"visible_characters",PROPERTY_HINT_RANGE,"-1,128000,1"),"set_visible_characters","get_visible_characters");
+ ClassDB::bind_method(D_METHOD("set_use_bbcode", "enable"), &RichTextLabel::set_use_bbcode);
+ ClassDB::bind_method(D_METHOD("is_using_bbcode"), &RichTextLabel::is_using_bbcode);
- ADD_SIGNAL( MethodInfo("meta_clicked",PropertyInfo(Variant::NIL,"meta")));
+ ADD_GROUP("BBCode", "bbcode_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bbcode_enabled"), "set_use_bbcode", "is_using_bbcode");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "bbcode_text", PROPERTY_HINT_MULTILINE_TEXT), "set_bbcode", "get_bbcode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "visible_characters", PROPERTY_HINT_RANGE, "-1,128000,1"), "set_visible_characters", "get_visible_characters");
- BIND_CONSTANT( ALIGN_LEFT );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_RIGHT );
- BIND_CONSTANT( ALIGN_FILL );
+ ADD_SIGNAL(MethodInfo("meta_clicked", PropertyInfo(Variant::NIL, "meta")));
- BIND_CONSTANT( LIST_NUMBERS );
- BIND_CONSTANT( LIST_LETTERS );
- BIND_CONSTANT( LIST_DOTS );
+ BIND_CONSTANT(ALIGN_LEFT);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_RIGHT);
+ BIND_CONSTANT(ALIGN_FILL);
- BIND_CONSTANT( ITEM_FRAME );
- BIND_CONSTANT( ITEM_TEXT );
- BIND_CONSTANT( ITEM_IMAGE );
- BIND_CONSTANT( ITEM_NEWLINE );
- BIND_CONSTANT( ITEM_FONT );
- BIND_CONSTANT( ITEM_COLOR );
- BIND_CONSTANT( ITEM_UNDERLINE );
- BIND_CONSTANT( ITEM_ALIGN );
- BIND_CONSTANT( ITEM_INDENT );
- BIND_CONSTANT( ITEM_LIST );
- BIND_CONSTANT( ITEM_META );
+ BIND_CONSTANT(LIST_NUMBERS);
+ BIND_CONSTANT(LIST_LETTERS);
+ BIND_CONSTANT(LIST_DOTS);
+ BIND_CONSTANT(ITEM_FRAME);
+ BIND_CONSTANT(ITEM_TEXT);
+ BIND_CONSTANT(ITEM_IMAGE);
+ BIND_CONSTANT(ITEM_NEWLINE);
+ BIND_CONSTANT(ITEM_FONT);
+ BIND_CONSTANT(ITEM_COLOR);
+ BIND_CONSTANT(ITEM_UNDERLINE);
+ BIND_CONSTANT(ITEM_ALIGN);
+ BIND_CONSTANT(ITEM_INDENT);
+ BIND_CONSTANT(ITEM_LIST);
+ BIND_CONSTANT(ITEM_META);
}
-
void RichTextLabel::set_visible_characters(int p_visible) {
- visible_characters=p_visible;
+ visible_characters = p_visible;
update();
}
@@ -2039,58 +1921,56 @@ int RichTextLabel::get_visible_characters() const {
}
int RichTextLabel::get_total_character_count() const {
- int tc=0;
- for(int i=0;i<current_frame->lines.size();i++)
- tc+=current_frame->lines[i].char_count;
+ int tc = 0;
+ for (int i = 0; i < current_frame->lines.size(); i++)
+ tc += current_frame->lines[i].char_count;
return tc;
}
-
RichTextLabel::RichTextLabel() {
-
- main = memnew( ItemFrame );
- main->index=0;
- current=main;
+ main = memnew(ItemFrame);
+ main->index = 0;
+ current = main;
main->lines.resize(1);
- main->lines[0].from=main;
- main->first_invalid_line=0;
- current_frame=main;
- tab_size=4;
- default_align=ALIGN_LEFT;
- underline_meta=true;
-
- scroll_visible=false;
- scroll_follow=false;
- scroll_following=false;
- updating_scroll=false;
- scroll_active=true;
- scroll_w=0;
-
- vscroll = memnew( VScrollBar );
+ main->lines[0].from = main;
+ main->first_invalid_line = 0;
+ current_frame = main;
+ tab_size = 4;
+ default_align = ALIGN_LEFT;
+ underline_meta = true;
+
+ scroll_visible = false;
+ scroll_follow = false;
+ scroll_following = false;
+ updating_scroll = false;
+ scroll_active = true;
+ scroll_w = 0;
+
+ vscroll = memnew(VScrollBar);
add_child(vscroll);
vscroll->set_drag_slave(String(".."));
vscroll->set_step(1);
- vscroll->set_anchor_and_margin( MARGIN_TOP, ANCHOR_BEGIN, 0);
- vscroll->set_anchor_and_margin( MARGIN_BOTTOM, ANCHOR_END, 0);
- vscroll->set_anchor_and_margin( MARGIN_RIGHT, ANCHOR_END, 0);
- vscroll->connect("value_changed",this,"_scroll_changed");
+ vscroll->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
+ vscroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
+ vscroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ vscroll->connect("value_changed", this, "_scroll_changed");
vscroll->set_step(1);
vscroll->hide();
- current_idx=1;
- use_bbcode=false;
+ current_idx = 1;
+ use_bbcode = false;
- selection.click=NULL;
- selection.active=false;
- selection.enabled=false;
+ selection.click = NULL;
+ selection.active = false;
+ selection.enabled = false;
- visible_characters=-1;
+ visible_characters = -1;
set_clip_contents(true);
}
RichTextLabel::~RichTextLabel() {
- memdelete( main );
+ memdelete(main);
}
diff --git a/scene/gui/rich_text_label.h b/scene/gui/rich_text_label.h
index 3bdd2cd7e3..a5f23d0ba9 100644
--- a/scene/gui/rich_text_label.h
+++ b/scene/gui/rich_text_label.h
@@ -29,14 +29,13 @@
#ifndef RICH_TEXT_LABEL_H
#define RICH_TEXT_LABEL_H
-
#include "scene/gui/scroll_bar.h"
class RichTextLabel : public Control {
- GDCLASS( RichTextLabel, Control );
-public:
+ GDCLASS(RichTextLabel, Control);
+public:
enum Align {
ALIGN_LEFT,
@@ -69,10 +68,9 @@ public:
};
protected:
-
static void _bind_methods();
-private:
+private:
struct Item;
struct Line {
@@ -86,27 +84,37 @@ private:
int char_count;
int minimum_width;
- Line() { from=NULL; char_count=0; }
+ Line() {
+ from = NULL;
+ char_count = 0;
+ }
};
-
-
struct Item {
int index;
Item *parent;
ItemType type;
- List<Item*> subitems;
- List<Item*>::Element *E;
+ List<Item *> subitems;
+ List<Item *>::Element *E;
int line;
- void _clear_children() { while (subitems.size()) { memdelete(subitems.front()->get()); subitems.pop_front(); } }
-
- Item() { parent=NULL; E=NULL; line=0;}
- virtual ~Item() { _clear_children(); }
+ void _clear_children() {
+ while (subitems.size()) {
+ memdelete(subitems.front()->get());
+ subitems.pop_front();
+ }
+ }
+
+ Item() {
+ parent = NULL;
+ E = NULL;
+ line = 0;
+ }
+ virtual ~Item() { _clear_children(); }
};
- struct ItemFrame : public Item{
+ struct ItemFrame : public Item {
int parent_line;
bool cell;
@@ -114,71 +122,74 @@ private:
int first_invalid_line;
ItemFrame *parent_frame;
- ItemFrame() { type=ITEM_FRAME; parent_frame=NULL; cell=false; parent_line=0; }
+ ItemFrame() {
+ type = ITEM_FRAME;
+ parent_frame = NULL;
+ cell = false;
+ parent_line = 0;
+ }
};
-
struct ItemText : public Item {
String text;
- ItemText() { type=ITEM_TEXT; }
+ ItemText() { type = ITEM_TEXT; }
};
struct ItemImage : public Item {
Ref<Texture> image;
- ItemImage() { type=ITEM_IMAGE; }
+ ItemImage() { type = ITEM_IMAGE; }
};
struct ItemFont : public Item {
Ref<Font> font;
- ItemFont() { type=ITEM_FONT; }
+ ItemFont() { type = ITEM_FONT; }
};
struct ItemColor : public Item {
Color color;
- ItemColor() { type=ITEM_COLOR; }
+ ItemColor() { type = ITEM_COLOR; }
};
struct ItemUnderline : public Item {
- ItemUnderline() { type=ITEM_UNDERLINE; }
+ ItemUnderline() { type = ITEM_UNDERLINE; }
};
struct ItemMeta : public Item {
Variant meta;
- ItemMeta() { type=ITEM_META; }
+ ItemMeta() { type = ITEM_META; }
};
struct ItemAlign : public Item {
Align align;
- ItemAlign() { type=ITEM_ALIGN; }
+ ItemAlign() { type = ITEM_ALIGN; }
};
struct ItemIndent : public Item {
int level;
- ItemIndent() { type=ITEM_INDENT; }
+ ItemIndent() { type = ITEM_INDENT; }
};
struct ItemList : public Item {
ListType list_type;
- ItemList() { type=ITEM_LIST; }
+ ItemList() { type = ITEM_LIST; }
};
struct ItemNewline : public Item {
- int line; // FIXME: Overriding base's line ?
- ItemNewline() { type=ITEM_NEWLINE; }
+ int line; // FIXME: Overriding base's line ?
+ ItemNewline() { type = ITEM_NEWLINE; }
};
-
- struct ItemTable : public Item{
+ struct ItemTable : public Item {
struct Column {
bool expand;
@@ -189,7 +200,7 @@ private:
Vector<Column> columns;
int total_width;
- ItemTable() { type=ITEM_TABLE; }
+ ItemTable() { type = ITEM_TABLE; }
};
ItemFrame *main;
@@ -198,7 +209,6 @@ private:
VScrollBar *vscroll;
-
bool scroll_visible;
bool scroll_follow;
bool scroll_following;
@@ -207,7 +217,6 @@ private:
bool updating_scroll;
int current_idx;
-
int tab_size;
bool underline_meta;
@@ -216,12 +225,9 @@ private:
void _invalidate_current_line(ItemFrame *p_frame);
void _validate_line_caches(ItemFrame *p_frame);
- void _add_item(Item *p_item, bool p_enter=false,bool p_ensure_newline=false);
+ void _add_item(Item *p_item, bool p_enter = false, bool p_ensure_newline = false);
void _remove_item(Item *p_item, const int p_line, const int p_subitem_line);
-
-
-
struct ProcessState {
int line_width;
@@ -250,26 +256,23 @@ private:
Selection selection;
-
int visible_characters;
-
- void _process_line(ItemFrame *p_frame,const Vector2& p_ofs,int &y, int p_width, int p_line, ProcessMode p_mode,const Ref<Font> &p_base_font,const Color &p_base_color,const Point2i& p_click_pos=Point2i(),Item **r_click_item=NULL,int *r_click_char=NULL,bool *r_outside=NULL,int p_char_count=0);
- void _find_click(ItemFrame *p_frame, const Point2i& p_click,Item **r_click_item=NULL,int *r_click_char=NULL,bool *r_outside=NULL);
-
+ void _process_line(ItemFrame *p_frame, const Vector2 &p_ofs, int &y, int p_width, int p_line, ProcessMode p_mode, const Ref<Font> &p_base_font, const Color &p_base_color, const Point2i &p_click_pos = Point2i(), Item **r_click_item = NULL, int *r_click_char = NULL, bool *r_outside = NULL, int p_char_count = 0);
+ void _find_click(ItemFrame *p_frame, const Point2i &p_click, Item **r_click_item = NULL, int *r_click_char = NULL, bool *r_outside = NULL);
Ref<Font> _find_font(Item *p_item);
- int _find_margin(Item *p_item,const Ref<Font>& p_base_font);
+ int _find_margin(Item *p_item, const Ref<Font> &p_base_font);
Align _find_align(Item *p_item);
- Color _find_color(Item *p_item,const Color& p_default_color);
+ Color _find_color(Item *p_item, const Color &p_default_color);
bool _find_underline(Item *p_item);
- bool _find_meta(Item *p_item,Variant *r_meta);
+ bool _find_meta(Item *p_item, Variant *r_meta);
void _update_scroll();
void _scroll_changed(double);
void _gui_input(InputEvent p_event);
- Item *_get_next_item(Item* p_item, bool p_free=false);
+ Item *_get_next_item(Item *p_item, bool p_free = false);
bool use_bbcode;
String bbcode;
@@ -280,21 +283,20 @@ protected:
void _notification(int p_what);
public:
-
String get_text();
- void add_text(const String& p_text);
- void add_image(const Ref<Texture>& p_image);
+ void add_text(const String &p_text);
+ void add_image(const Ref<Texture> &p_image);
void add_newline();
bool remove_line(const int p_line);
- void push_font(const Ref<Font>& p_font);
- void push_color(const Color& p_color);
+ void push_font(const Ref<Font> &p_font);
+ void push_color(const Color &p_color);
void push_underline();
void push_align(Align p_align);
void push_indent(int p_level);
void push_list(ListType p_list);
- void push_meta(const Variant& p_data);
+ void push_meta(const Variant &p_data);
void push_table(int p_columns);
- void set_table_column_expand(int p_column, bool p_expand, int p_ratio=1);
+ void set_table_column_expand(int p_column, bool p_expand, int p_ratio = 1);
int get_current_table_column() const;
void push_cell();
void pop();
@@ -315,29 +317,26 @@ public:
void set_tab_size(int p_spaces);
int get_tab_size() const;
-
-
- bool search(const String& p_string,bool p_from_selection=false);
+ bool search(const String &p_string, bool p_from_selection = false);
void scroll_to_line(int p_line);
int get_line_count() const;
VScrollBar *get_v_scroll() { return vscroll; }
- virtual CursorShape get_cursor_shape(const Point2& p_pos) const;
+ virtual CursorShape get_cursor_shape(const Point2 &p_pos) const;
void set_selection_enabled(bool p_enabled);
bool is_selection_enabled() const;
void selection_copy();
-
- Error parse_bbcode(const String& p_bbcode);
- Error append_bbcode(const String& p_bbcode);
+ Error parse_bbcode(const String &p_bbcode);
+ Error append_bbcode(const String &p_bbcode);
void set_use_bbcode(bool p_enable);
bool is_using_bbcode() const;
- void set_bbcode(const String& p_bbcode);
+ void set_bbcode(const String &p_bbcode);
String get_bbcode() const;
void set_visible_characters(int p_visible);
@@ -348,8 +347,8 @@ public:
~RichTextLabel();
};
-VARIANT_ENUM_CAST( RichTextLabel::Align );
-VARIANT_ENUM_CAST( RichTextLabel::ListType );
-VARIANT_ENUM_CAST( RichTextLabel::ItemType );
+VARIANT_ENUM_CAST(RichTextLabel::Align);
+VARIANT_ENUM_CAST(RichTextLabel::ListType);
+VARIANT_ENUM_CAST(RichTextLabel::ItemType);
#endif // RICH_TEXT_LABEL_H
diff --git a/scene/gui/scroll_bar.cpp b/scene/gui/scroll_bar.cpp
index b2ad74eaa8..37f7b46e22 100644
--- a/scene/gui/scroll_bar.cpp
+++ b/scene/gui/scroll_bar.cpp
@@ -28,166 +28,153 @@
/*************************************************************************/
#include "scroll_bar.h"
#include "os/keyboard.h"
-#include "print_string.h"
#include "os/os.h"
-bool ScrollBar::focus_by_default=false;
-
-
+#include "print_string.h"
+bool ScrollBar::focus_by_default = false;
void ScrollBar::set_can_focus_by_default(bool p_can_focus) {
- focus_by_default=p_can_focus;
+ focus_by_default = p_can_focus;
}
void ScrollBar::_gui_input(InputEvent p_event) {
-
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &b=p_event.mouse_button;
+ const InputEventMouseButton &b = p_event.mouse_button;
accept_event();
- if (b.button_index==5 && b.pressed) {
+ if (b.button_index == 5 && b.pressed) {
/*
if (orientation==VERTICAL)
set_val( get_val() + get_page() / 4.0 );
else
*/
- set_value( get_value() + get_page() / 4.0 );
+ set_value(get_value() + get_page() / 4.0);
accept_event();
-
}
- if (b.button_index==4 && b.pressed) {
+ if (b.button_index == 4 && b.pressed) {
/*
if (orientation==HORIZONTAL)
set_val( get_val() - get_page() / 4.0 );
else
*/
- set_value( get_value() - get_page() / 4.0 );
+ set_value(get_value() - get_page() / 4.0);
accept_event();
}
- if (b.button_index!=1)
+ if (b.button_index != 1)
return;
-
if (b.pressed) {
-
- double ofs = orientation==VERTICAL ? b.y : b.x ;
+ double ofs = orientation == VERTICAL ? b.y : b.x;
Ref<Texture> decr = get_icon("decrement");
Ref<Texture> incr = get_icon("increment");
- double decr_size = orientation==VERTICAL ? decr->get_height() : decr->get_width();
- double incr_size = orientation==VERTICAL ? incr->get_height() : incr->get_width();
+ double decr_size = orientation == VERTICAL ? decr->get_height() : decr->get_width();
+ double incr_size = orientation == VERTICAL ? incr->get_height() : incr->get_width();
double grabber_ofs = get_grabber_offset();
double grabber_size = get_grabber_size();
- double total = orientation==VERTICAL ? get_size().height : get_size().width;
+ double total = orientation == VERTICAL ? get_size().height : get_size().width;
- if (ofs < decr_size ) {
+ if (ofs < decr_size) {
- set_value( get_value() - (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
break;
}
- if (ofs > total-incr_size ) {
+ if (ofs > total - incr_size) {
- set_value( get_value() + (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
break;
}
- ofs-=decr_size;
+ ofs -= decr_size;
- if ( ofs < grabber_ofs ) {
+ if (ofs < grabber_ofs) {
- set_value( get_value() - get_page() );
+ set_value(get_value() - get_page());
break;
-
}
- ofs-=grabber_ofs;
+ ofs -= grabber_ofs;
- if (ofs < grabber_size ) {
+ if (ofs < grabber_size) {
- drag.active=true;
- drag.pos_at_click=grabber_ofs+ofs;
- drag.value_at_click=get_as_ratio();
+ drag.active = true;
+ drag.pos_at_click = grabber_ofs + ofs;
+ drag.value_at_click = get_as_ratio();
update();
} else {
-
- set_value( get_value() + get_page() );
+ set_value(get_value() + get_page());
}
-
} else {
- drag.active=false;
+ drag.active = false;
update();
}
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &m=p_event.mouse_motion;
+ const InputEventMouseMotion &m = p_event.mouse_motion;
accept_event();
-
if (drag.active) {
- double ofs = orientation==VERTICAL ? m.y : m.x ;
+ double ofs = orientation == VERTICAL ? m.y : m.x;
Ref<Texture> decr = get_icon("decrement");
- double decr_size = orientation==VERTICAL ? decr->get_height() : decr->get_width();
- ofs-=decr_size;
+ double decr_size = orientation == VERTICAL ? decr->get_height() : decr->get_width();
+ ofs -= decr_size;
- double diff = (ofs-drag.pos_at_click) / get_area_size();
+ double diff = (ofs - drag.pos_at_click) / get_area_size();
- set_as_ratio( drag.value_at_click + diff );
+ set_as_ratio(drag.value_at_click + diff);
} else {
-
- double ofs = orientation==VERTICAL ? m.y : m.x ;
+ double ofs = orientation == VERTICAL ? m.y : m.x;
Ref<Texture> decr = get_icon("decrement");
Ref<Texture> incr = get_icon("increment");
- double decr_size = orientation==VERTICAL ? decr->get_height() : decr->get_width();
- double incr_size = orientation==VERTICAL ? incr->get_height() : incr->get_width();
- double total = orientation==VERTICAL ? get_size().height : get_size().width;
+ double decr_size = orientation == VERTICAL ? decr->get_height() : decr->get_width();
+ double incr_size = orientation == VERTICAL ? incr->get_height() : incr->get_width();
+ double total = orientation == VERTICAL ? get_size().height : get_size().width;
HiliteStatus new_hilite;
- if (ofs < decr_size ) {
+ if (ofs < decr_size) {
- new_hilite=HILITE_DECR;
+ new_hilite = HILITE_DECR;
- } else if (ofs > total-incr_size ) {
+ } else if (ofs > total - incr_size) {
- new_hilite=HILITE_INCR;
+ new_hilite = HILITE_INCR;
} else {
- new_hilite=HILITE_RANGE;
+ new_hilite = HILITE_RANGE;
}
- if (new_hilite!=hilite) {
+ if (new_hilite != hilite) {
- hilite=new_hilite;
+ hilite = new_hilite;
update();
-
}
-
}
} break;
case InputEvent::KEY: {
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
if (!k.pressed)
return;
@@ -196,319 +183,298 @@ void ScrollBar::_gui_input(InputEvent p_event) {
case KEY_LEFT: {
- if (orientation!=HORIZONTAL)
+ if (orientation != HORIZONTAL)
return;
- set_value( get_value() - (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
} break;
case KEY_RIGHT: {
- if (orientation!=HORIZONTAL)
+ if (orientation != HORIZONTAL)
return;
- set_value( get_value() + (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
} break;
case KEY_UP: {
- if (orientation!=VERTICAL)
+ if (orientation != VERTICAL)
return;
- set_value( get_value() - (custom_step>=0?custom_step:get_step()) );
-
+ set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
} break;
case KEY_DOWN: {
- if (orientation!=VERTICAL)
+ if (orientation != VERTICAL)
return;
- set_value( get_value() + (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
} break;
case KEY_HOME: {
- set_value( get_min() );
+ set_value(get_min());
} break;
case KEY_END: {
- set_value( get_max() );
+ set_value(get_max());
} break;
-
- } break;
+ }
+ break;
}
}
}
void ScrollBar::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
- Ref<Texture> decr = hilite==HILITE_DECR ? get_icon("decrement_hilite") : get_icon("decrement");
- Ref<Texture> incr = hilite==HILITE_INCR ? get_icon("increment_hilite") : get_icon("increment");
+ Ref<Texture> decr = hilite == HILITE_DECR ? get_icon("decrement_hilite") : get_icon("decrement");
+ Ref<Texture> incr = hilite == HILITE_INCR ? get_icon("increment_hilite") : get_icon("increment");
Ref<StyleBox> bg = has_focus() ? get_stylebox("scroll_focus") : get_stylebox("scroll");
- Ref<StyleBox> grabber = (drag.active || hilite==HILITE_RANGE) ? get_stylebox("grabber_hilite") : get_stylebox("grabber");
+ Ref<StyleBox> grabber = (drag.active || hilite == HILITE_RANGE) ? get_stylebox("grabber_hilite") : get_stylebox("grabber");
Point2 ofs;
VisualServer *vs = VisualServer::get_singleton();
- vs->canvas_item_add_texture_rect( ci, Rect2( Point2(), decr->get_size()),decr->get_rid() );
+ vs->canvas_item_add_texture_rect(ci, Rect2(Point2(), decr->get_size()), decr->get_rid());
- if (orientation==HORIZONTAL)
- ofs.x+=decr->get_width();
+ if (orientation == HORIZONTAL)
+ ofs.x += decr->get_width();
else
- ofs.y+=decr->get_height();
+ ofs.y += decr->get_height();
- Size2 area=get_size();
+ Size2 area = get_size();
- if (orientation==HORIZONTAL)
- area.width-=incr->get_width()+decr->get_width();
+ if (orientation == HORIZONTAL)
+ area.width -= incr->get_width() + decr->get_width();
else
- area.height-=incr->get_height()+decr->get_height();
+ area.height -= incr->get_height() + decr->get_height();
- bg->draw(ci,Rect2(ofs,area));
+ bg->draw(ci, Rect2(ofs, area));
- if (orientation==HORIZONTAL)
- ofs.width+=area.width;
+ if (orientation == HORIZONTAL)
+ ofs.width += area.width;
else
- ofs.height+=area.height;
+ ofs.height += area.height;
- vs->canvas_item_add_texture_rect( ci, Rect2( ofs, decr->get_size()),incr->get_rid() );
+ vs->canvas_item_add_texture_rect(ci, Rect2(ofs, decr->get_size()), incr->get_rid());
Rect2 grabber_rect;
- if (orientation==HORIZONTAL) {
+ if (orientation == HORIZONTAL) {
- grabber_rect.size.width=get_grabber_size();
- grabber_rect.size.height=get_size().height;
- grabber_rect.pos.y=0;
- grabber_rect.pos.x=get_grabber_offset()+decr->get_width()+bg->get_margin( MARGIN_LEFT );
+ grabber_rect.size.width = get_grabber_size();
+ grabber_rect.size.height = get_size().height;
+ grabber_rect.pos.y = 0;
+ grabber_rect.pos.x = get_grabber_offset() + decr->get_width() + bg->get_margin(MARGIN_LEFT);
} else {
- grabber_rect.size.width=get_size().width;
- grabber_rect.size.height=get_grabber_size();
- grabber_rect.pos.y=get_grabber_offset()+decr->get_height()+bg->get_margin( MARGIN_TOP );
- grabber_rect.pos.x=0;
+ grabber_rect.size.width = get_size().width;
+ grabber_rect.size.height = get_grabber_size();
+ grabber_rect.pos.y = get_grabber_offset() + decr->get_height() + bg->get_margin(MARGIN_TOP);
+ grabber_rect.pos.x = 0;
}
- grabber->draw(ci,grabber_rect);
-
+ grabber->draw(ci, grabber_rect);
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
-
+ if (p_what == NOTIFICATION_ENTER_TREE) {
if (has_node(drag_slave_path)) {
Node *n = get_node(drag_slave_path);
- drag_slave=n->cast_to<Control>();
+ drag_slave = n->cast_to<Control>();
}
if (drag_slave) {
- drag_slave->connect("gui_input",this,"_drag_slave_input");
- drag_slave->connect("tree_exited",this,"_drag_slave_exit",varray(),CONNECT_ONESHOT);
+ drag_slave->connect("gui_input", this, "_drag_slave_input");
+ drag_slave->connect("tree_exited", this, "_drag_slave_exit", varray(), CONNECT_ONESHOT);
}
-
-
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (drag_slave) {
- drag_slave->disconnect("gui_input",this,"_drag_slave_input");
- drag_slave->disconnect("tree_exited",this,"_drag_slave_exit");
+ drag_slave->disconnect("gui_input", this, "_drag_slave_input");
+ drag_slave->disconnect("tree_exited", this, "_drag_slave_exit");
}
- drag_slave=NULL;
-
+ drag_slave = NULL;
}
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
- if (drag_slave_touching) {
+ if (drag_slave_touching) {
if (drag_slave_touching_deaccel) {
- Vector2 pos = Vector2(orientation==HORIZONTAL?get_value():0,orientation==VERTICAL?get_value():0);
- pos+=drag_slave_speed*get_fixed_process_delta_time();
+ Vector2 pos = Vector2(orientation == HORIZONTAL ? get_value() : 0, orientation == VERTICAL ? get_value() : 0);
+ pos += drag_slave_speed * get_fixed_process_delta_time();
- bool turnoff=false;
+ bool turnoff = false;
- if (orientation==HORIZONTAL) {
+ if (orientation == HORIZONTAL) {
- if (pos.x<0) {
- pos.x=0;
- turnoff=true;
+ if (pos.x < 0) {
+ pos.x = 0;
+ turnoff = true;
}
- if (pos.x > (get_max()-get_page())) {
- pos.x=get_max()-get_page();
- turnoff=true;
+ if (pos.x > (get_max() - get_page())) {
+ pos.x = get_max() - get_page();
+ turnoff = true;
}
set_value(pos.x);
- float sgn_x = drag_slave_speed.x<0? -1 : 1;
+ float sgn_x = drag_slave_speed.x < 0 ? -1 : 1;
float val_x = Math::abs(drag_slave_speed.x);
- val_x-=1000*get_fixed_process_delta_time();
+ val_x -= 1000 * get_fixed_process_delta_time();
- if (val_x<0) {
- turnoff=true;
+ if (val_x < 0) {
+ turnoff = true;
}
- drag_slave_speed.x=sgn_x*val_x;
+ drag_slave_speed.x = sgn_x * val_x;
} else {
-
- if (pos.y<0) {
- pos.y=0;
- turnoff=true;
+ if (pos.y < 0) {
+ pos.y = 0;
+ turnoff = true;
}
- if (pos.y > (get_max()-get_page())) {
- pos.y=get_max()-get_page();
- turnoff=true;
+ if (pos.y > (get_max() - get_page())) {
+ pos.y = get_max() - get_page();
+ turnoff = true;
}
set_value(pos.y);
- float sgn_y = drag_slave_speed.y<0? -1 : 1;
+ float sgn_y = drag_slave_speed.y < 0 ? -1 : 1;
float val_y = Math::abs(drag_slave_speed.y);
- val_y-=1000*get_fixed_process_delta_time();
+ val_y -= 1000 * get_fixed_process_delta_time();
- if (val_y<0) {
- turnoff=true;
+ if (val_y < 0) {
+ turnoff = true;
}
- drag_slave_speed.y=sgn_y*val_y;
+ drag_slave_speed.y = sgn_y * val_y;
}
-
if (turnoff) {
set_fixed_process(false);
- drag_slave_touching=false;
- drag_slave_touching_deaccel=false;
+ drag_slave_touching = false;
+ drag_slave_touching_deaccel = false;
}
-
} else {
-
- if (time_since_motion==0 || time_since_motion>0.1) {
+ if (time_since_motion == 0 || time_since_motion > 0.1) {
Vector2 diff = drag_slave_accum - last_drag_slave_accum;
- last_drag_slave_accum=drag_slave_accum;
- drag_slave_speed=diff/get_fixed_process_delta_time();
+ last_drag_slave_accum = drag_slave_accum;
+ drag_slave_speed = diff / get_fixed_process_delta_time();
}
- time_since_motion+=get_fixed_process_delta_time();
+ time_since_motion += get_fixed_process_delta_time();
}
}
-
-
}
- if (p_what==NOTIFICATION_MOUSE_EXIT) {
+ if (p_what == NOTIFICATION_MOUSE_EXIT) {
- hilite=HILITE_NONE;
+ hilite = HILITE_NONE;
update();
}
}
double ScrollBar::get_grabber_min_size() const {
- Ref<StyleBox> grabber=get_stylebox("grabber");
- Size2 gminsize=grabber->get_minimum_size()+grabber->get_center_size();
- return (orientation==VERTICAL)?gminsize.height:gminsize.width;
+ Ref<StyleBox> grabber = get_stylebox("grabber");
+ Size2 gminsize = grabber->get_minimum_size() + grabber->get_center_size();
+ return (orientation == VERTICAL) ? gminsize.height : gminsize.width;
}
double ScrollBar::get_grabber_size() const {
- float range = get_max()-get_min();
- if (range<=0)
+ float range = get_max() - get_min();
+ if (range <= 0)
return 0;
- float page = (get_page()>0)? get_page() : 0;
+ float page = (get_page() > 0) ? get_page() : 0;
/*
if (grabber_range < get_step())
grabber_range=get_step();
*/
- double area_size=get_area_size();
+ double area_size = get_area_size();
double grabber_size = page / range * area_size;
- return grabber_size+get_grabber_min_size();
-
+ return grabber_size + get_grabber_min_size();
}
double ScrollBar::get_area_size() const {
- if (orientation==VERTICAL) {
+ if (orientation == VERTICAL) {
- double area=get_size().height;
- area-=get_stylebox("scroll")->get_minimum_size().height;
- area-=get_icon("increment")->get_height();
- area-=get_icon("decrement")->get_height();
- area-=get_grabber_min_size();
+ double area = get_size().height;
+ area -= get_stylebox("scroll")->get_minimum_size().height;
+ area -= get_icon("increment")->get_height();
+ area -= get_icon("decrement")->get_height();
+ area -= get_grabber_min_size();
return area;
- } else if (orientation==HORIZONTAL) {
+ } else if (orientation == HORIZONTAL) {
- double area=get_size().width;
- area-=get_stylebox("scroll")->get_minimum_size().width;
- area-=get_icon("increment")->get_width();
- area-=get_icon("decrement")->get_width();
- area-=get_grabber_min_size();
+ double area = get_size().width;
+ area -= get_stylebox("scroll")->get_minimum_size().width;
+ area -= get_icon("increment")->get_width();
+ area -= get_icon("decrement")->get_width();
+ area -= get_grabber_min_size();
return area;
} else {
return 0;
}
-
}
double ScrollBar::get_area_offset() const {
- double ofs=0;
+ double ofs = 0;
- if (orientation==VERTICAL) {
-
- ofs+=get_stylebox("hscroll")->get_margin( MARGIN_TOP );
- ofs+=get_icon("decrement")->get_height();
+ if (orientation == VERTICAL) {
+ ofs += get_stylebox("hscroll")->get_margin(MARGIN_TOP);
+ ofs += get_icon("decrement")->get_height();
}
- if (orientation==HORIZONTAL) {
+ if (orientation == HORIZONTAL) {
- ofs+=get_stylebox("hscroll")->get_margin( MARGIN_LEFT );
- ofs+=get_icon("decrement")->get_width();
+ ofs += get_stylebox("hscroll")->get_margin(MARGIN_LEFT);
+ ofs += get_icon("decrement")->get_width();
}
return ofs;
}
-double ScrollBar::get_click_pos(const Point2& p_pos) const {
-
+double ScrollBar::get_click_pos(const Point2 &p_pos) const {
- float pos=(orientation==VERTICAL)?p_pos.y:p_pos.x;
- pos-=get_area_offset();
+ float pos = (orientation == VERTICAL) ? p_pos.y : p_pos.x;
+ pos -= get_area_offset();
- float area=get_area_size();
- if (area==0)
+ float area = get_area_size();
+ if (area == 0)
return 0;
else
- return pos/area;
-
+ return pos / area;
}
double ScrollBar::get_grabber_offset() const {
-
return (get_area_size()) * get_as_ratio();
-
}
-
-
Size2 ScrollBar::get_minimum_size() const {
Ref<Texture> incr = get_icon("increment");
@@ -516,31 +482,30 @@ Size2 ScrollBar::get_minimum_size() const {
Ref<StyleBox> bg = get_stylebox("scroll");
Size2 minsize;
- if (orientation==VERTICAL) {
+ if (orientation == VERTICAL) {
- minsize.width=MAX(incr->get_size().width,(bg->get_minimum_size()+bg->get_center_size()).width);
- minsize.height+=incr->get_size().height;
- minsize.height+=decr->get_size().height;
- minsize.height+=bg->get_minimum_size().height;
- minsize.height+=get_grabber_min_size();
+ minsize.width = MAX(incr->get_size().width, (bg->get_minimum_size() + bg->get_center_size()).width);
+ minsize.height += incr->get_size().height;
+ minsize.height += decr->get_size().height;
+ minsize.height += bg->get_minimum_size().height;
+ minsize.height += get_grabber_min_size();
}
- if (orientation==HORIZONTAL) {
+ if (orientation == HORIZONTAL) {
- minsize.height=MAX(incr->get_size().height,(bg->get_center_size()+bg->get_minimum_size()).height);
- minsize.width+=incr->get_size().width;
- minsize.width+=decr->get_size().width;
- minsize.width+=bg->get_minimum_size().width;
- minsize.width+=get_grabber_min_size();
+ minsize.height = MAX(incr->get_size().height, (bg->get_center_size() + bg->get_minimum_size()).height);
+ minsize.width += incr->get_size().width;
+ minsize.width += decr->get_size().width;
+ minsize.width += bg->get_minimum_size().width;
+ minsize.width += get_grabber_min_size();
}
return minsize;
-
}
void ScrollBar::set_custom_step(float p_custom_step) {
- custom_step=p_custom_step;
+ custom_step = p_custom_step;
}
float ScrollBar::get_custom_step() const {
@@ -548,53 +513,50 @@ float ScrollBar::get_custom_step() const {
return custom_step;
}
-
void ScrollBar::_drag_slave_exit() {
if (drag_slave) {
- drag_slave->disconnect("gui_input",this,"_drag_slave_input");
+ drag_slave->disconnect("gui_input", this, "_drag_slave_input");
}
- drag_slave=NULL;
+ drag_slave = NULL;
}
+void ScrollBar::_drag_slave_input(const InputEvent &p_input) {
-void ScrollBar::_drag_slave_input(const InputEvent& p_input) {
-
- switch(p_input.type) {
+ switch (p_input.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_input.mouse_button;
+ const InputEventMouseButton &mb = p_input.mouse_button;
- if (mb.button_index!=1)
+ if (mb.button_index != 1)
break;
if (mb.pressed) {
if (drag_slave_touching) {
set_fixed_process(false);
- drag_slave_touching_deaccel=false;
- drag_slave_touching=false;
- drag_slave_speed=Vector2();
- drag_slave_accum=Vector2();
- last_drag_slave_accum=Vector2();
- drag_slave_from=Vector2();
+ drag_slave_touching_deaccel = false;
+ drag_slave_touching = false;
+ drag_slave_speed = Vector2();
+ drag_slave_accum = Vector2();
+ last_drag_slave_accum = Vector2();
+ drag_slave_from = Vector2();
}
if (true) {
- drag_slave_speed=Vector2();
- drag_slave_accum=Vector2();
- last_drag_slave_accum=Vector2();
+ drag_slave_speed = Vector2();
+ drag_slave_accum = Vector2();
+ last_drag_slave_accum = Vector2();
//drag_slave_from=Vector2(h_scroll->get_val(),v_scroll->get_val());
- drag_slave_from= Vector2(orientation==HORIZONTAL?get_value():0,orientation==VERTICAL?get_value():0);
+ drag_slave_from = Vector2(orientation == HORIZONTAL ? get_value() : 0, orientation == VERTICAL ? get_value() : 0);
- drag_slave_touching=OS::get_singleton()->has_touchscreen_ui_hint();
- drag_slave_touching_deaccel=false;
- time_since_motion=0;
+ drag_slave_touching = OS::get_singleton()->has_touchscreen_ui_hint();
+ drag_slave_touching_deaccel = false;
+ time_since_motion = 0;
if (drag_slave_touching) {
set_fixed_process(true);
- time_since_motion=0;
-
+ time_since_motion = 0;
}
}
@@ -602,82 +564,79 @@ void ScrollBar::_drag_slave_input(const InputEvent& p_input) {
if (drag_slave_touching) {
- if (drag_slave_speed==Vector2()) {
- drag_slave_touching_deaccel=false;
- drag_slave_touching=false;
+ if (drag_slave_speed == Vector2()) {
+ drag_slave_touching_deaccel = false;
+ drag_slave_touching = false;
set_fixed_process(false);
} else {
- drag_slave_touching_deaccel=true;
+ drag_slave_touching_deaccel = true;
}
}
}
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_input.mouse_motion;
+ const InputEventMouseMotion &mm = p_input.mouse_motion;
- if (drag_slave_touching && ! drag_slave_touching_deaccel) {
+ if (drag_slave_touching && !drag_slave_touching_deaccel) {
- Vector2 motion = Vector2(mm.relative_x,mm.relative_y);
+ Vector2 motion = Vector2(mm.relative_x, mm.relative_y);
- drag_slave_accum-=motion;
- Vector2 diff = drag_slave_from+drag_slave_accum;
+ drag_slave_accum -= motion;
+ Vector2 diff = drag_slave_from + drag_slave_accum;
- if (orientation==HORIZONTAL)
+ if (orientation == HORIZONTAL)
set_value(diff.x);
/*
else
drag_slave_accum.x=0;
*/
- if (orientation==VERTICAL)
+ if (orientation == VERTICAL)
set_value(diff.y);
/*
else
drag_slave_accum.y=0;
*/
- time_since_motion=0;
+ time_since_motion = 0;
}
} break;
}
}
-void ScrollBar::set_drag_slave(const NodePath& p_path) {
+void ScrollBar::set_drag_slave(const NodePath &p_path) {
if (is_inside_tree()) {
if (drag_slave) {
- drag_slave->disconnect("gui_input",this,"_drag_slave_input");
- drag_slave->disconnect("tree_exited",this,"_drag_slave_exit");
+ drag_slave->disconnect("gui_input", this, "_drag_slave_input");
+ drag_slave->disconnect("tree_exited", this, "_drag_slave_exit");
}
}
- drag_slave=NULL;
- drag_slave_path=p_path;
+ drag_slave = NULL;
+ drag_slave_path = p_path;
if (is_inside_tree()) {
if (has_node(p_path)) {
Node *n = get_node(p_path);
- drag_slave=n->cast_to<Control>();
+ drag_slave = n->cast_to<Control>();
}
if (drag_slave) {
- drag_slave->connect("gui_input",this,"_drag_slave_input");
- drag_slave->connect("tree_exited",this,"_drag_slave_exit",varray(),CONNECT_ONESHOT);
+ drag_slave->connect("gui_input", this, "_drag_slave_input");
+ drag_slave->connect("tree_exited", this, "_drag_slave_exit", varray(), CONNECT_ONESHOT);
}
}
}
-NodePath ScrollBar::get_drag_slave() const{
-
+NodePath ScrollBar::get_drag_slave() const {
return drag_slave_path;
}
-
-
#if 0
void ScrollBar::mouse_button(const Point2& p_pos, int b.button_index,bool b.pressed,int p_modifier_mask) {
@@ -808,48 +767,36 @@ bool ScrollBar::key(unsigned long p_unicode, unsigned long p_scan_code,bool b.pr
return true;
}
-
-
#endif
void ScrollBar::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&ScrollBar::_gui_input);
- ClassDB::bind_method(D_METHOD("set_custom_step","step"),&ScrollBar::set_custom_step);
- ClassDB::bind_method(D_METHOD("get_custom_step"),&ScrollBar::get_custom_step);
- ClassDB::bind_method(D_METHOD("_drag_slave_input"),&ScrollBar::_drag_slave_input);
- ClassDB::bind_method(D_METHOD("_drag_slave_exit"),&ScrollBar::_drag_slave_exit);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"custom_step",PROPERTY_HINT_RANGE,"-1,4096"), "set_custom_step","get_custom_step");
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ScrollBar::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_custom_step", "step"), &ScrollBar::set_custom_step);
+ ClassDB::bind_method(D_METHOD("get_custom_step"), &ScrollBar::get_custom_step);
+ ClassDB::bind_method(D_METHOD("_drag_slave_input"), &ScrollBar::_drag_slave_input);
+ ClassDB::bind_method(D_METHOD("_drag_slave_exit"), &ScrollBar::_drag_slave_exit);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "custom_step", PROPERTY_HINT_RANGE, "-1,4096"), "set_custom_step", "get_custom_step");
}
+ScrollBar::ScrollBar(Orientation p_orientation) {
-ScrollBar::ScrollBar(Orientation p_orientation)
-{
+ orientation = p_orientation;
+ hilite = HILITE_NONE;
+ custom_step = -1;
+ drag_slave = NULL;
+ drag.active = false;
- orientation=p_orientation;
- hilite=HILITE_NONE;
- custom_step=-1;
- drag_slave=NULL;
-
- drag.active=false;
-
- drag_slave_speed=Vector2();
- drag_slave_touching=false;
- drag_slave_touching_deaccel=false;
+ drag_slave_speed = Vector2();
+ drag_slave_touching = false;
+ drag_slave_touching_deaccel = false;
if (focus_by_default)
- set_focus_mode( FOCUS_ALL );
+ set_focus_mode(FOCUS_ALL);
set_step(0);
-
}
-
-
-ScrollBar::~ScrollBar()
-{
+ScrollBar::~ScrollBar() {
}
-
-
diff --git a/scene/gui/scroll_bar.h b/scene/gui/scroll_bar.h
index be8b394957..5227fa45ac 100644
--- a/scene/gui/scroll_bar.h
+++ b/scene/gui/scroll_bar.h
@@ -31,13 +31,12 @@
#include "scene/gui/range.h"
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class ScrollBar : public Range {
- GDCLASS( ScrollBar, Range );
+ GDCLASS(ScrollBar, Range);
enum HiliteStatus {
HILITE_NONE,
@@ -61,17 +60,16 @@ class ScrollBar : public Range {
float value_at_click;
} drag;
-
double get_grabber_size() const;
double get_grabber_min_size() const;
double get_area_size() const;
double get_area_offset() const;
- double get_click_pos(const Point2& p_pos) const;
+ double get_click_pos(const Point2 &p_pos) const;
double get_grabber_offset() const;
static void set_can_focus_by_default(bool p_can_focus);
- Node* drag_slave;
+ Node *drag_slave;
NodePath drag_slave_path;
Vector2 drag_slave_speed;
@@ -85,43 +83,43 @@ class ScrollBar : public Range {
bool click_handled;
void _drag_slave_exit();
- void _drag_slave_input(const InputEvent& p_input);
+ void _drag_slave_input(const InputEvent &p_input);
void _gui_input(InputEvent p_event);
+
protected:
void _notification(int p_what);
static void _bind_methods();
public:
-
void set_custom_step(float p_custom_step);
float get_custom_step() const;
- void set_drag_slave(const NodePath& p_path);
+ void set_drag_slave(const NodePath &p_path);
NodePath get_drag_slave() const;
virtual Size2 get_minimum_size() const;
- ScrollBar(Orientation p_orientation=VERTICAL);
+ ScrollBar(Orientation p_orientation = VERTICAL);
~ScrollBar();
-
};
class HScrollBar : public ScrollBar {
- GDCLASS( HScrollBar, ScrollBar );
-public:
+ GDCLASS(HScrollBar, ScrollBar);
- HScrollBar() : ScrollBar(HORIZONTAL) { set_v_size_flags(0); }
+public:
+ HScrollBar()
+ : ScrollBar(HORIZONTAL) { set_v_size_flags(0); }
};
class VScrollBar : public ScrollBar {
- GDCLASS( VScrollBar, ScrollBar );
-public:
+ GDCLASS(VScrollBar, ScrollBar);
- VScrollBar() : ScrollBar(VERTICAL) { set_h_size_flags(0); }
+public:
+ VScrollBar()
+ : ScrollBar(VERTICAL) { set_h_size_flags(0); }
};
-
#endif
diff --git a/scene/gui/scroll_container.cpp b/scene/gui/scroll_container.cpp
index 2296c9742d..c543b783b9 100644
--- a/scene/gui/scroll_container.cpp
+++ b/scene/gui/scroll_container.cpp
@@ -35,10 +35,9 @@ bool ScrollContainer::clips_input() const {
Size2 ScrollContainer::get_minimum_size() const {
-
Size2 min_size;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -49,161 +48,150 @@ Size2 ScrollContainer::get_minimum_size() const {
continue;
Size2 minsize = c->get_combined_minimum_size();
-
if (!scroll_h) {
min_size.x = MAX(min_size.x, minsize.x);
}
if (!scroll_v) {
min_size.y = MAX(min_size.y, minsize.y);
-
}
}
if (h_scroll->is_visible_in_tree()) {
- min_size.y+=h_scroll->get_minimum_size().y;
+ min_size.y += h_scroll->get_minimum_size().y;
}
if (v_scroll->is_visible_in_tree()) {
- min_size.x+=v_scroll->get_minimum_size().x;
+ min_size.x += v_scroll->get_minimum_size().x;
}
return min_size;
};
-
void ScrollContainer::_cancel_drag() {
set_fixed_process(false);
- drag_touching_deaccel=false;
- drag_touching=false;
- drag_speed=Vector2();
- drag_accum=Vector2();
- last_drag_accum=Vector2();
- drag_from=Vector2();
+ drag_touching_deaccel = false;
+ drag_touching = false;
+ drag_speed = Vector2();
+ drag_accum = Vector2();
+ last_drag_accum = Vector2();
+ drag_from = Vector2();
}
-void ScrollContainer::_gui_input(const InputEvent& p_gui_input) {
+void ScrollContainer::_gui_input(const InputEvent &p_gui_input) {
-
- switch(p_gui_input.type) {
+ switch (p_gui_input.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_gui_input.mouse_button;
+ const InputEventMouseButton &mb = p_gui_input.mouse_button;
- if (mb.button_index==BUTTON_WHEEL_UP && mb.pressed) {
- if (h_scroll->is_visible_in_tree() && !v_scroll->is_visible_in_tree()){
+ if (mb.button_index == BUTTON_WHEEL_UP && mb.pressed) {
+ if (h_scroll->is_visible_in_tree() && !v_scroll->is_visible_in_tree()) {
// only horizontal is enabled, scroll horizontally
- h_scroll->set_value( h_scroll->get_value()-h_scroll->get_page()/8 );
+ h_scroll->set_value(h_scroll->get_value() - h_scroll->get_page() / 8);
} else if (v_scroll->is_visible_in_tree()) {
- v_scroll->set_value( v_scroll->get_value()-v_scroll->get_page()/8 );
+ v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / 8);
}
}
- if (mb.button_index==BUTTON_WHEEL_DOWN && mb.pressed) {
- if (h_scroll->is_visible_in_tree() && !v_scroll->is_visible_in_tree()){
+ if (mb.button_index == BUTTON_WHEEL_DOWN && mb.pressed) {
+ if (h_scroll->is_visible_in_tree() && !v_scroll->is_visible_in_tree()) {
// only horizontal is enabled, scroll horizontally
- h_scroll->set_value( h_scroll->get_value()+h_scroll->get_page()/8 );
+ h_scroll->set_value(h_scroll->get_value() + h_scroll->get_page() / 8);
} else if (v_scroll->is_visible_in_tree()) {
- v_scroll->set_value( v_scroll->get_value()+v_scroll->get_page()/8 );
+ v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / 8);
}
}
- if(!OS::get_singleton()->has_touchscreen_ui_hint())
+ if (!OS::get_singleton()->has_touchscreen_ui_hint())
return;
- if (mb.button_index!=BUTTON_LEFT)
+ if (mb.button_index != BUTTON_LEFT)
break;
if (mb.pressed) {
if (drag_touching) {
set_fixed_process(false);
- drag_touching_deaccel=false;
- drag_touching=false;
- drag_speed=Vector2();
- drag_accum=Vector2();
- last_drag_accum=Vector2();
- drag_from=Vector2();
+ drag_touching_deaccel = false;
+ drag_touching = false;
+ drag_speed = Vector2();
+ drag_accum = Vector2();
+ last_drag_accum = Vector2();
+ drag_from = Vector2();
}
if (true) {
- drag_speed=Vector2();
- drag_accum=Vector2();
- last_drag_accum=Vector2();
- drag_from=Vector2(h_scroll->get_value(),v_scroll->get_value());
- drag_touching=OS::get_singleton()->has_touchscreen_ui_hint();
- drag_touching_deaccel=false;
- time_since_motion=0;
+ drag_speed = Vector2();
+ drag_accum = Vector2();
+ last_drag_accum = Vector2();
+ drag_from = Vector2(h_scroll->get_value(), v_scroll->get_value());
+ drag_touching = OS::get_singleton()->has_touchscreen_ui_hint();
+ drag_touching_deaccel = false;
+ time_since_motion = 0;
if (drag_touching) {
set_fixed_process(true);
- time_since_motion=0;
-
+ time_since_motion = 0;
}
}
-
} else {
if (drag_touching) {
- if (drag_speed==Vector2()) {
- drag_touching_deaccel=false;
- drag_touching=false;
+ if (drag_speed == Vector2()) {
+ drag_touching_deaccel = false;
+ drag_touching = false;
set_fixed_process(false);
} else {
- drag_touching_deaccel=true;
+ drag_touching_deaccel = true;
}
}
}
-
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_gui_input.mouse_motion;
+ const InputEventMouseMotion &mm = p_gui_input.mouse_motion;
- if (drag_touching && ! drag_touching_deaccel) {
+ if (drag_touching && !drag_touching_deaccel) {
- Vector2 motion = Vector2(mm.relative_x,mm.relative_y);
- drag_accum-=motion;
- Vector2 diff = drag_from+drag_accum;
+ Vector2 motion = Vector2(mm.relative_x, mm.relative_y);
+ drag_accum -= motion;
+ Vector2 diff = drag_from + drag_accum;
if (scroll_h)
h_scroll->set_value(diff.x);
else
- drag_accum.x=0;
+ drag_accum.x = 0;
if (scroll_v)
v_scroll->set_value(diff.y);
else
- drag_accum.y=0;
- time_since_motion=0;
+ drag_accum.y = 0;
+ time_since_motion = 0;
}
} break;
}
-
}
-
void ScrollContainer::_update_scrollbar_pos() {
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
- v_scroll->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,vmin.width);
- v_scroll->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,0);
- v_scroll->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,0);
- v_scroll->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,0);
+ v_scroll->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_END, vmin.width);
+ v_scroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ v_scroll->set_anchor_and_margin(MARGIN_TOP, ANCHOR_BEGIN, 0);
+ v_scroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
- h_scroll->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN,0);
- h_scroll->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,0);
- h_scroll->set_anchor_and_margin(MARGIN_TOP,ANCHOR_END,hmin.height);
- h_scroll->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END,0);
+ h_scroll->set_anchor_and_margin(MARGIN_LEFT, ANCHOR_BEGIN, 0);
+ h_scroll->set_anchor_and_margin(MARGIN_RIGHT, ANCHOR_END, 0);
+ h_scroll->set_anchor_and_margin(MARGIN_TOP, ANCHOR_END, hmin.height);
+ h_scroll->set_anchor_and_margin(MARGIN_BOTTOM, ANCHOR_END, 0);
h_scroll->raise();
v_scroll->raise();
-
}
-
void ScrollContainer::_notification(int p_what) {
if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_THEME_CHANGED) {
@@ -211,18 +199,17 @@ void ScrollContainer::_notification(int p_what) {
call_deferred("_update_scrollbar_pos");
};
-
- if (p_what==NOTIFICATION_SORT_CHILDREN) {
+ if (p_what == NOTIFICATION_SORT_CHILDREN) {
child_max_size = Size2(0, 0);
Size2 size = get_size();
if (h_scroll->is_visible_in_tree())
- size.y-=h_scroll->get_minimum_size().y;
+ size.y -= h_scroll->get_minimum_size().y;
if (v_scroll->is_visible_in_tree())
- size.x-=h_scroll->get_minimum_size().x;
+ size.x -= h_scroll->get_minimum_size().x;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -235,24 +222,23 @@ void ScrollContainer::_notification(int p_what) {
child_max_size.x = MAX(child_max_size.x, minsize.x);
child_max_size.y = MAX(child_max_size.y, minsize.y);
- Rect2 r = Rect2(-scroll,minsize);
- if (!scroll_h || (!h_scroll->is_visible_in_tree() && c->get_h_size_flags()&SIZE_EXPAND)) {
- r.pos.x=0;
- if (c->get_h_size_flags()&SIZE_EXPAND)
- r.size.width=MAX(size.width,minsize.width);
+ Rect2 r = Rect2(-scroll, minsize);
+ if (!scroll_h || (!h_scroll->is_visible_in_tree() && c->get_h_size_flags() & SIZE_EXPAND)) {
+ r.pos.x = 0;
+ if (c->get_h_size_flags() & SIZE_EXPAND)
+ r.size.width = MAX(size.width, minsize.width);
else
- r.size.width=minsize.width;
+ r.size.width = minsize.width;
}
- if (!scroll_v || (!v_scroll->is_visible_in_tree() && c->get_v_size_flags()&SIZE_EXPAND)) {
- r.pos.y=0;
- r.size.height=size.height;
- if (c->get_v_size_flags()&SIZE_EXPAND)
- r.size.height=MAX(size.height,minsize.height);
+ if (!scroll_v || (!v_scroll->is_visible_in_tree() && c->get_v_size_flags() & SIZE_EXPAND)) {
+ r.pos.y = 0;
+ r.size.height = size.height;
+ if (c->get_v_size_flags() & SIZE_EXPAND)
+ r.size.height = MAX(size.height, minsize.height);
else
- r.size.height=minsize.height;
-
+ r.size.height = minsize.height;
}
- fit_child_in_rect(c,r);
+ fit_child_in_rect(c, r);
}
update();
};
@@ -260,37 +246,36 @@ void ScrollContainer::_notification(int p_what) {
if (p_what == NOTIFICATION_DRAW) {
update_scrollbars();
-
}
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
- if (drag_touching) {
+ if (drag_touching) {
if (drag_touching_deaccel) {
- Vector2 pos = Vector2(h_scroll->get_value(),v_scroll->get_value());
- pos+=drag_speed*get_fixed_process_delta_time();
+ Vector2 pos = Vector2(h_scroll->get_value(), v_scroll->get_value());
+ pos += drag_speed * get_fixed_process_delta_time();
- bool turnoff_h=false;
- bool turnoff_v=false;
+ bool turnoff_h = false;
+ bool turnoff_v = false;
- if (pos.x<0) {
- pos.x=0;
- turnoff_h=true;
+ if (pos.x < 0) {
+ pos.x = 0;
+ turnoff_h = true;
}
- if (pos.x > (h_scroll->get_max()-h_scroll->get_page())) {
- pos.x=h_scroll->get_max()-h_scroll->get_page();
- turnoff_h=true;
+ if (pos.x > (h_scroll->get_max() - h_scroll->get_page())) {
+ pos.x = h_scroll->get_max() - h_scroll->get_page();
+ turnoff_h = true;
}
- if (pos.y<0) {
- pos.y=0;
- turnoff_v=true;
+ if (pos.y < 0) {
+ pos.y = 0;
+ turnoff_v = true;
}
- if (pos.y > (v_scroll->get_max()-v_scroll->get_page())) {
- pos.y=v_scroll->get_max()-v_scroll->get_page();
- turnoff_v=true;
+ if (pos.y > (v_scroll->get_max() - v_scroll->get_page())) {
+ pos.y = v_scroll->get_max() - v_scroll->get_page();
+ turnoff_v = true;
}
if (scroll_h)
@@ -298,48 +283,43 @@ void ScrollContainer::_notification(int p_what) {
if (scroll_v)
v_scroll->set_value(pos.y);
- float sgn_x = drag_speed.x<0? -1 : 1;
+ float sgn_x = drag_speed.x < 0 ? -1 : 1;
float val_x = Math::abs(drag_speed.x);
- val_x-=1000*get_fixed_process_delta_time();
+ val_x -= 1000 * get_fixed_process_delta_time();
- if (val_x<0) {
- turnoff_h=true;
+ if (val_x < 0) {
+ turnoff_h = true;
}
-
- float sgn_y = drag_speed.y<0? -1 : 1;
+ float sgn_y = drag_speed.y < 0 ? -1 : 1;
float val_y = Math::abs(drag_speed.y);
- val_y-=1000*get_fixed_process_delta_time();
+ val_y -= 1000 * get_fixed_process_delta_time();
- if (val_y<0) {
- turnoff_v=true;
+ if (val_y < 0) {
+ turnoff_v = true;
}
-
- drag_speed=Vector2(sgn_x*val_x,sgn_y*val_y);
+ drag_speed = Vector2(sgn_x * val_x, sgn_y * val_y);
if (turnoff_h && turnoff_v) {
set_fixed_process(false);
- drag_touching=false;
- drag_touching_deaccel=false;
+ drag_touching = false;
+ drag_touching_deaccel = false;
}
-
} else {
-
- if (time_since_motion==0 || time_since_motion>0.1) {
+ if (time_since_motion == 0 || time_since_motion > 0.1) {
Vector2 diff = drag_accum - last_drag_accum;
- last_drag_accum=drag_accum;
- drag_speed=diff/get_fixed_process_delta_time();
+ last_drag_accum = drag_accum;
+ drag_speed = diff / get_fixed_process_delta_time();
}
- time_since_motion+=get_fixed_process_delta_time();
+ time_since_motion += get_fixed_process_delta_time();
}
}
}
-
};
void ScrollContainer::update_scrollbars() {
@@ -354,66 +334,62 @@ void ScrollContainer::update_scrollbars() {
if (!scroll_v || min.height <= size.height - hmin.height) {
v_scroll->hide();
- scroll.y=0;
+ scroll.y = 0;
} else {
v_scroll->show();
- scroll.y=v_scroll->get_value();
-
+ scroll.y = v_scroll->get_value();
}
v_scroll->set_max(min.height);
v_scroll->set_page(size.height - hmin.height);
-
if (!scroll_h || min.width <= size.width - vmin.width) {
h_scroll->hide();
- scroll.x=0;
+ scroll.x = 0;
} else {
h_scroll->show();
h_scroll->set_max(min.width);
h_scroll->set_page(size.width - vmin.width);
- scroll.x=h_scroll->get_value();
+ scroll.x = h_scroll->get_value();
}
}
void ScrollContainer::_scroll_moved(float) {
- scroll.x=h_scroll->get_value();
- scroll.y=v_scroll->get_value();
+ scroll.x = h_scroll->get_value();
+ scroll.y = v_scroll->get_value();
queue_sort();
update();
};
-
void ScrollContainer::set_enable_h_scroll(bool p_enable) {
- scroll_h=p_enable;
+ scroll_h = p_enable;
queue_sort();
}
-bool ScrollContainer::is_h_scroll_enabled() const{
+bool ScrollContainer::is_h_scroll_enabled() const {
return scroll_h;
}
void ScrollContainer::set_enable_v_scroll(bool p_enable) {
- scroll_v=p_enable;
+ scroll_v = p_enable;
queue_sort();
}
-bool ScrollContainer::is_v_scroll_enabled() const{
+bool ScrollContainer::is_v_scroll_enabled() const {
return scroll_v;
}
int ScrollContainer::get_v_scroll() const {
-
return v_scroll->get_value();
}
void ScrollContainer::set_v_scroll(int p_pos) {
@@ -430,14 +406,13 @@ void ScrollContainer::set_h_scroll(int p_pos) {
h_scroll->set_value(p_pos);
_cancel_drag();
-
}
String ScrollContainer::get_configuration_warning() const {
- int found=0;
+ int found = 0;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Control *c = get_child(i)->cast_to<Control>();
if (!c)
@@ -450,31 +425,29 @@ String ScrollContainer::get_configuration_warning() const {
found++;
}
- if (found!=1)
+ if (found != 1)
return TTR("ScrollContainer is intended to work with a single child control.\nUse a container as child (VBox,HBox,etc), or a Control and set the custom minimum size manually.");
else
return "";
}
-
void ScrollContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_scroll_moved"),&ScrollContainer::_scroll_moved);
- ClassDB::bind_method(D_METHOD("_gui_input"),&ScrollContainer::_gui_input);
- ClassDB::bind_method(D_METHOD("set_enable_h_scroll","enable"),&ScrollContainer::set_enable_h_scroll);
- ClassDB::bind_method(D_METHOD("is_h_scroll_enabled"),&ScrollContainer::is_h_scroll_enabled);
- ClassDB::bind_method(D_METHOD("set_enable_v_scroll","enable"),&ScrollContainer::set_enable_v_scroll);
- ClassDB::bind_method(D_METHOD("is_v_scroll_enabled"),&ScrollContainer::is_v_scroll_enabled);
- ClassDB::bind_method(D_METHOD("_update_scrollbar_pos"),&ScrollContainer::_update_scrollbar_pos);
- ClassDB::bind_method(D_METHOD("set_h_scroll","val"),&ScrollContainer::set_h_scroll);
- ClassDB::bind_method(D_METHOD("get_h_scroll"),&ScrollContainer::get_h_scroll);
- ClassDB::bind_method(D_METHOD("set_v_scroll","val"),&ScrollContainer::set_v_scroll);
- ClassDB::bind_method(D_METHOD("get_v_scroll"),&ScrollContainer::get_v_scroll);
-
- ADD_GROUP("Scroll","scroll_");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "scroll_horizontal"), "set_enable_h_scroll","is_h_scroll_enabled");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "scroll_vertical"), "set_enable_v_scroll","is_v_scroll_enabled");
-
+ ClassDB::bind_method(D_METHOD("_scroll_moved"), &ScrollContainer::_scroll_moved);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &ScrollContainer::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_enable_h_scroll", "enable"), &ScrollContainer::set_enable_h_scroll);
+ ClassDB::bind_method(D_METHOD("is_h_scroll_enabled"), &ScrollContainer::is_h_scroll_enabled);
+ ClassDB::bind_method(D_METHOD("set_enable_v_scroll", "enable"), &ScrollContainer::set_enable_v_scroll);
+ ClassDB::bind_method(D_METHOD("is_v_scroll_enabled"), &ScrollContainer::is_v_scroll_enabled);
+ ClassDB::bind_method(D_METHOD("_update_scrollbar_pos"), &ScrollContainer::_update_scrollbar_pos);
+ ClassDB::bind_method(D_METHOD("set_h_scroll", "val"), &ScrollContainer::set_h_scroll);
+ ClassDB::bind_method(D_METHOD("get_h_scroll"), &ScrollContainer::get_h_scroll);
+ ClassDB::bind_method(D_METHOD("set_v_scroll", "val"), &ScrollContainer::set_v_scroll);
+ ClassDB::bind_method(D_METHOD("get_v_scroll"), &ScrollContainer::get_v_scroll);
+
+ ADD_GROUP("Scroll", "scroll_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_horizontal"), "set_enable_h_scroll", "is_h_scroll_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "scroll_vertical"), "set_enable_v_scroll", "is_v_scroll_enabled");
};
ScrollContainer::ScrollContainer() {
@@ -487,15 +460,14 @@ ScrollContainer::ScrollContainer() {
v_scroll->set_name("_v_scroll");
add_child(v_scroll);
- h_scroll->connect("value_changed", this,"_scroll_moved");
- v_scroll->connect("value_changed", this,"_scroll_moved");
+ h_scroll->connect("value_changed", this, "_scroll_moved");
+ v_scroll->connect("value_changed", this, "_scroll_moved");
- drag_speed=Vector2();
- drag_touching=false;
- drag_touching_deaccel=false;
- scroll_h=true;
- scroll_v=true;
+ drag_speed = Vector2();
+ drag_touching = false;
+ drag_touching_deaccel = false;
+ scroll_h = true;
+ scroll_v = true;
set_clip_contents(true);
};
-
diff --git a/scene/gui/scroll_container.h b/scene/gui/scroll_container.h
index 114cd06306..07b127843a 100644
--- a/scene/gui/scroll_container.h
+++ b/scene/gui/scroll_container.h
@@ -37,8 +37,8 @@ class ScrollContainer : public Container {
GDCLASS(ScrollContainer, Container);
- HScrollBar* h_scroll;
- VScrollBar* v_scroll;
+ HScrollBar *h_scroll;
+ VScrollBar *v_scroll;
Size2 child_max_size;
Size2 scroll;
@@ -63,16 +63,15 @@ class ScrollContainer : public Container {
protected:
Size2 get_minimum_size() const;
-
- void _gui_input(const InputEvent& p_gui_input);
+ void _gui_input(const InputEvent &p_gui_input);
void _notification(int p_what);
void _scroll_moved(float);
static void _bind_methods();
void _update_scrollbar_pos();
-public:
+public:
int get_v_scroll() const;
void set_v_scroll(int p_pos);
diff --git a/scene/gui/separator.cpp b/scene/gui/separator.cpp
index 32bd2239fc..e256b8f928 100644
--- a/scene/gui/separator.cpp
+++ b/scene/gui/separator.cpp
@@ -28,54 +28,47 @@
/*************************************************************************/
#include "separator.h"
-
Size2 Separator::get_minimum_size() const {
- Size2 ms(3,3);
- ms[orientation]=get_constant("separation");
+ Size2 ms(3, 3);
+ ms[orientation] = get_constant("separation");
return ms;
-
-
}
void Separator::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
Size2i size = get_size();
Ref<StyleBox> style = get_stylebox("separator");
- Size2i ssize=style->get_minimum_size()+style->get_center_size();
+ Size2i ssize = style->get_minimum_size() + style->get_center_size();
- if (orientation==VERTICAL) {
+ if (orientation == VERTICAL) {
- style->draw(get_canvas_item(),Rect2( (size.x-ssize.x)/2,0,ssize.x,size.y ));
+ style->draw(get_canvas_item(), Rect2((size.x - ssize.x) / 2, 0, ssize.x, size.y));
} else {
- style->draw(get_canvas_item(),Rect2( 0,(size.y-ssize.y)/2,size.x,ssize.y ));
+ style->draw(get_canvas_item(), Rect2(0, (size.y - ssize.y) / 2, size.x, ssize.y));
}
} break;
}
}
-Separator::Separator()
-{
+Separator::Separator() {
}
-
-Separator::~Separator()
-{
+Separator::~Separator() {
}
HSeparator::HSeparator() {
- orientation=HORIZONTAL;
+ orientation = HORIZONTAL;
}
VSeparator::VSeparator() {
- orientation=VERTICAL;
+ orientation = VERTICAL;
}
diff --git a/scene/gui/separator.h b/scene/gui/separator.h
index 56d8a9724f..7913531748 100644
--- a/scene/gui/separator.h
+++ b/scene/gui/separator.h
@@ -36,40 +36,33 @@
#include "scene/gui/control.h"
class Separator : public Control {
- GDCLASS( Separator, Control );
-
+ GDCLASS(Separator, Control);
protected:
-
Orientation orientation;
void _notification(int p_what);
-public:
+public:
virtual Size2 get_minimum_size() const;
Separator();
~Separator();
-
};
class VSeparator : public Separator {
- GDCLASS( VSeparator, Separator );
+ GDCLASS(VSeparator, Separator);
public:
-
VSeparator();
-
};
class HSeparator : public Separator {
- GDCLASS( HSeparator, Separator );
+ GDCLASS(HSeparator, Separator);
public:
-
HSeparator();
-
};
#endif
diff --git a/scene/gui/slider.cpp b/scene/gui/slider.cpp
index a6d6864b16..365d450ed6 100644
--- a/scene/gui/slider.cpp
+++ b/scene/gui/slider.cpp
@@ -29,91 +29,88 @@
#include "slider.h"
#include "os/keyboard.h"
-
Size2 Slider::get_minimum_size() const {
Ref<StyleBox> style = get_stylebox("slider");
- Size2i ms = style->get_minimum_size()+style->get_center_size();
+ Size2i ms = style->get_minimum_size() + style->get_center_size();
return ms;
}
void Slider::_gui_input(InputEvent p_event) {
-
-
- if (p_event.type==InputEvent::MOUSE_BUTTON) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON) {
InputEventMouseButton &mb = p_event.mouse_button;
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
- if (mb.pressed) {
- Ref<Texture> grabber = get_icon(mouse_inside||has_focus()?"grabber_hilite":"grabber");
- grab.pos=orientation==VERTICAL?mb.y:mb.x;
+ if (mb.pressed) {
+ Ref<Texture> grabber = get_icon(mouse_inside || has_focus() ? "grabber_hilite" : "grabber");
+ grab.pos = orientation == VERTICAL ? mb.y : mb.x;
double grab_width = (double)grabber->get_size().width;
double grab_height = (double)grabber->get_size().height;
- double max = orientation==VERTICAL ? get_size().height - grab_height : get_size().width - grab_width;
- if (orientation==VERTICAL)
- set_as_ratio( 1 - (((double)grab.pos - (grab_height / 2.0)) / max) );
+ double max = orientation == VERTICAL ? get_size().height - grab_height : get_size().width - grab_width;
+ if (orientation == VERTICAL)
+ set_as_ratio(1 - (((double)grab.pos - (grab_height / 2.0)) / max));
else
- set_as_ratio(((double)grab.pos - (grab_width/2.0)) / max);
- grab.active=true;
- grab.uvalue=get_as_ratio();
+ set_as_ratio(((double)grab.pos - (grab_width / 2.0)) / max);
+ grab.active = true;
+ grab.uvalue = get_as_ratio();
} else {
- grab.active=false;
+ grab.active = false;
}
- } else if (mb.pressed && mb.button_index==BUTTON_WHEEL_UP) {
+ } else if (mb.pressed && mb.button_index == BUTTON_WHEEL_UP) {
- set_value( get_value() + get_step());
- } else if (mb.pressed && mb.button_index==BUTTON_WHEEL_DOWN) {
- set_value( get_value() - get_step());
+ set_value(get_value() + get_step());
+ } else if (mb.pressed && mb.button_index == BUTTON_WHEEL_DOWN) {
+ set_value(get_value() - get_step());
}
- } else if (p_event.type==InputEvent::MOUSE_MOTION) {
+ } else if (p_event.type == InputEvent::MOUSE_MOTION) {
if (grab.active) {
Size2i size = get_size();
Ref<Texture> grabber = get_icon("grabber");
- float motion = (orientation==VERTICAL?p_event.mouse_motion.y:p_event.mouse_motion.x) - grab.pos;
- if (orientation==VERTICAL)
- motion=-motion;
- float areasize = orientation==VERTICAL?size.height - grabber->get_size().height:size.width - grabber->get_size().width;
- if (areasize<=0)
+ float motion = (orientation == VERTICAL ? p_event.mouse_motion.y : p_event.mouse_motion.x) - grab.pos;
+ if (orientation == VERTICAL)
+ motion = -motion;
+ float areasize = orientation == VERTICAL ? size.height - grabber->get_size().height : size.width - grabber->get_size().width;
+ if (areasize <= 0)
return;
float umotion = motion / float(areasize);
- set_as_ratio( grab.uvalue + umotion );
+ set_as_ratio(grab.uvalue + umotion);
}
} else {
if (p_event.is_action("ui_left") && p_event.is_pressed()) {
- if (orientation!=HORIZONTAL)
+ if (orientation != HORIZONTAL)
return;
- set_value( get_value() - (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
accept_event();
} else if (p_event.is_action("ui_right") && p_event.is_pressed()) {
- if (orientation!=HORIZONTAL)
+ if (orientation != HORIZONTAL)
return;
- set_value( get_value() + (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
accept_event();
} else if (p_event.is_action("ui_up") && p_event.is_pressed()) {
- if (orientation!=VERTICAL)
+ if (orientation != VERTICAL)
return;
- set_value( get_value() + (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() + (custom_step >= 0 ? custom_step : get_step()));
accept_event();
} else if (p_event.is_action("ui_down") && p_event.is_pressed()) {
- if (orientation!=VERTICAL)
+ if (orientation != VERTICAL)
return;
- set_value( get_value() - (custom_step>=0?custom_step:get_step()) );
+ set_value(get_value() - (custom_step >= 0 ? custom_step : get_step()));
accept_event();
- } else if (p_event.type==InputEvent::KEY) {
+ } else if (p_event.type == InputEvent::KEY) {
- const InputEventKey &k=p_event.key;
+ const InputEventKey &k = p_event.key;
if (!k.pressed)
return;
@@ -122,35 +119,32 @@ void Slider::_gui_input(InputEvent p_event) {
case KEY_HOME: {
- set_value( get_min() );
+ set_value(get_min());
accept_event();
} break;
case KEY_END: {
- set_value( get_max() );
+ set_value(get_max());
accept_event();
} break;
-
- } ;
+ };
}
}
-
}
void Slider::_notification(int p_what) {
-
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_MOUSE_ENTER: {
- mouse_inside=true;
+ mouse_inside = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
- mouse_inside=false;
+ mouse_inside = false;
update();
} break;
case NOTIFICATION_DRAW: {
@@ -158,45 +152,43 @@ void Slider::_notification(int p_what) {
Size2i size = get_size();
Ref<StyleBox> style = get_stylebox("slider");
Ref<StyleBox> focus = get_stylebox("focus");
- Ref<Texture> grabber = get_icon(mouse_inside||has_focus()?"grabber_hilite":"grabber");
+ Ref<Texture> grabber = get_icon(mouse_inside || has_focus() ? "grabber_hilite" : "grabber");
Ref<Texture> tick = get_icon("tick");
- if (orientation==VERTICAL) {
+ if (orientation == VERTICAL) {
- style->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height)));
+ style->draw(ci, Rect2i(Point2i(), Size2i(style->get_minimum_size().width + style->get_center_size().width, size.height)));
/*
if (mouse_inside||has_focus())
focus->draw(ci,Rect2i(Point2i(),Size2i(style->get_minimum_size().width+style->get_center_size().width,size.height)));
*/
float areasize = size.height - grabber->get_size().height;
- if (ticks>1) {
+ if (ticks > 1) {
int tickarea = size.height - tick->get_height();
- for(int i=0;i<ticks;i++) {
- if( ! ticks_on_borders && (i == 0 || i + 1 == ticks) ) continue;
- int ofs = i*tickarea/(ticks-1);
- tick->draw(ci,Point2(0,ofs));
+ for (int i = 0; i < ticks; i++) {
+ if (!ticks_on_borders && (i == 0 || i + 1 == ticks)) continue;
+ int ofs = i * tickarea / (ticks - 1);
+ tick->draw(ci, Point2(0, ofs));
}
-
}
- grabber->draw(ci,Point2i(size.width/2-grabber->get_size().width/2,size.height - get_as_ratio()*areasize - grabber->get_size().height));
+ grabber->draw(ci, Point2i(size.width / 2 - grabber->get_size().width / 2, size.height - get_as_ratio() * areasize - grabber->get_size().height));
} else {
- style->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height)));
+ style->draw(ci, Rect2i(Point2i(), Size2i(size.width, style->get_minimum_size().height + style->get_center_size().height)));
/*
if (mouse_inside||has_focus())
focus->draw(ci,Rect2i(Point2i(),Size2i(size.width,style->get_minimum_size().height+style->get_center_size().height)));
*/
float areasize = size.width - grabber->get_size().width;
- if (ticks>1) {
+ if (ticks > 1) {
int tickarea = size.width - tick->get_width();
- for(int i=0;i<ticks;i++) {
- if( (! ticks_on_borders) && ( (i == 0) || ((i + 1) == ticks)) ) continue;
- int ofs = i*tickarea/(ticks-1);
- tick->draw(ci,Point2(ofs,0));
+ for (int i = 0; i < ticks; i++) {
+ if ((!ticks_on_borders) && ((i == 0) || ((i + 1) == ticks))) continue;
+ int ofs = i * tickarea / (ticks - 1);
+ tick->draw(ci, Point2(ofs, 0));
}
-
}
- grabber->draw(ci,Point2i(get_as_ratio()*areasize,size.height/2-grabber->get_size().height/2));
+ grabber->draw(ci, Point2i(get_as_ratio() * areasize, size.height / 2 - grabber->get_size().height / 2));
}
} break;
@@ -205,7 +197,7 @@ void Slider::_notification(int p_what) {
void Slider::set_custom_step(float p_custom_step) {
- custom_step=p_custom_step;
+ custom_step = p_custom_step;
}
float Slider::get_custom_step() const {
@@ -215,7 +207,7 @@ float Slider::get_custom_step() const {
void Slider::set_ticks(int p_count) {
- ticks=p_count;
+ ticks = p_count;
update();
}
@@ -224,35 +216,34 @@ int Slider::get_ticks() const {
return ticks;
}
-bool Slider::get_ticks_on_borders() const{
+bool Slider::get_ticks_on_borders() const {
return ticks_on_borders;
}
-void Slider::set_ticks_on_borders(bool _tob){
+void Slider::set_ticks_on_borders(bool _tob) {
ticks_on_borders = _tob;
update();
}
void Slider::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&Slider::_gui_input);
- ClassDB::bind_method(D_METHOD("set_ticks","count"),&Slider::set_ticks);
- ClassDB::bind_method(D_METHOD("get_ticks"),&Slider::get_ticks);
-
- ClassDB::bind_method(D_METHOD("get_ticks_on_borders"),&Slider::get_ticks_on_borders);
- ClassDB::bind_method(D_METHOD("set_ticks_on_borders","ticks_on_border"),&Slider::set_ticks_on_borders);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &Slider::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_ticks", "count"), &Slider::set_ticks);
+ ClassDB::bind_method(D_METHOD("get_ticks"), &Slider::get_ticks);
- ADD_PROPERTY( PropertyInfo( Variant::INT, "tick_count", PROPERTY_HINT_RANGE,"0,4096,1"), "set_ticks", "get_ticks") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "ticks_on_borders" ), "set_ticks_on_borders", "get_ticks_on_borders") ;
- ADD_PROPERTY( PropertyInfo( Variant::INT,"focus_mode", PROPERTY_HINT_ENUM, "None,Click,All" ), "set_focus_mode", "get_focus_mode") ;
+ ClassDB::bind_method(D_METHOD("get_ticks_on_borders"), &Slider::get_ticks_on_borders);
+ ClassDB::bind_method(D_METHOD("set_ticks_on_borders", "ticks_on_border"), &Slider::set_ticks_on_borders);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "tick_count", PROPERTY_HINT_RANGE, "0,4096,1"), "set_ticks", "get_ticks");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ticks_on_borders"), "set_ticks_on_borders", "get_ticks_on_borders");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "focus_mode", PROPERTY_HINT_ENUM, "None,Click,All"), "set_focus_mode", "get_focus_mode");
}
Slider::Slider(Orientation p_orientation) {
- orientation=p_orientation;
- mouse_inside=false;
- grab.active=false;
- ticks=0;
- custom_step=-1;
+ orientation = p_orientation;
+ mouse_inside = false;
+ grab.active = false;
+ ticks = 0;
+ custom_step = -1;
set_focus_mode(FOCUS_ALL);
}
diff --git a/scene/gui/slider.h b/scene/gui/slider.h
index 89eb32737b..f649a4d150 100644
--- a/scene/gui/slider.h
+++ b/scene/gui/slider.h
@@ -33,7 +33,7 @@
class Slider : public Range {
- GDCLASS( Slider, Range );
+ GDCLASS(Slider, Range);
struct Grab {
int pos;
@@ -46,16 +46,13 @@ class Slider : public Range {
Orientation orientation;
float custom_step;
-
protected:
-
void _gui_input(InputEvent p_event);
void _notification(int p_what);
static void _bind_methods();
bool ticks_on_borders;
public:
-
virtual Size2 get_minimum_size() const;
void set_custom_step(float p_custom_step);
@@ -67,25 +64,25 @@ public:
void set_ticks_on_borders(bool);
bool get_ticks_on_borders() const;
- Slider(Orientation p_orientation=VERTICAL);
+ Slider(Orientation p_orientation = VERTICAL);
};
-
-
class HSlider : public Slider {
- GDCLASS( HSlider, Slider );
-public:
+ GDCLASS(HSlider, Slider);
- HSlider() : Slider(HORIZONTAL) { set_v_size_flags(0);}
+public:
+ HSlider()
+ : Slider(HORIZONTAL) { set_v_size_flags(0); }
};
class VSlider : public Slider {
- GDCLASS( VSlider, Slider );
-public:
+ GDCLASS(VSlider, Slider);
- VSlider() : Slider(VERTICAL) { set_h_size_flags(0);}
+public:
+ VSlider()
+ : Slider(VERTICAL) { set_h_size_flags(0); }
};
#endif // SLIDER_H
diff --git a/scene/gui/spin_box.cpp b/scene/gui/spin_box.cpp
index f2c04d2f76..3f21093fb7 100644
--- a/scene/gui/spin_box.cpp
+++ b/scene/gui/spin_box.cpp
@@ -32,53 +32,47 @@
Size2 SpinBox::get_minimum_size() const {
Size2 ms = line_edit->get_combined_minimum_size();
- ms.width+=last_w;
+ ms.width += last_w;
return ms;
}
-
void SpinBox::_value_changed(double) {
- String value = String::num(get_value(),Math::step_decimals(get_step()));
- if (prefix!="")
- value=prefix+" "+value;
- if (suffix!="")
- value+=" "+suffix;
+ String value = String::num(get_value(), Math::step_decimals(get_step()));
+ if (prefix != "")
+ value = prefix + " " + value;
+ if (suffix != "")
+ value += " " + suffix;
line_edit->set_text(value);
}
-void SpinBox::_text_entered(const String& p_string) {
+void SpinBox::_text_entered(const String &p_string) {
/*
if (!p_string.is_numeric())
return;
*/
String value = p_string;
- if (prefix!="" && p_string.begins_with(prefix))
- value = p_string.substr(prefix.length(), p_string.length()-prefix.length());
- set_value( value.to_double() );
+ if (prefix != "" && p_string.begins_with(prefix))
+ value = p_string.substr(prefix.length(), p_string.length() - prefix.length());
+ set_value(value.to_double());
_value_changed(0);
}
-
LineEdit *SpinBox::get_line_edit() {
return line_edit;
}
-
-void SpinBox::_line_edit_input(const InputEvent& p_event) {
-
-
-
+void SpinBox::_line_edit_input(const InputEvent &p_event) {
}
void SpinBox::_range_click_timeout() {
if (!drag.enabled && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
- bool up = get_local_mouse_pos().y < (get_size().height/2);
- set_value( get_value() + (up?get_step():-get_step()));
+ bool up = get_local_mouse_pos().y < (get_size().height / 2);
+ set_value(get_value() + (up ? get_step() : -get_step()));
if (range_click_timer->is_one_shot()) {
range_click_timer->set_wait_time(0.075);
@@ -91,23 +85,21 @@ void SpinBox::_range_click_timeout() {
}
}
-
-void SpinBox::_gui_input(const InputEvent& p_event) {
+void SpinBox::_gui_input(const InputEvent &p_event) {
if (!is_editable()) {
return;
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed) {
- const InputEventMouseButton &mb=p_event.mouse_button;
-
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed) {
+ const InputEventMouseButton &mb = p_event.mouse_button;
- bool up = mb.y < (get_size().height/2);
+ bool up = mb.y < (get_size().height / 2);
- switch(mb.button_index) {
+ switch (mb.button_index) {
case BUTTON_LEFT: {
- set_value( get_value() + (up?get_step():-get_step()));
+ set_value(get_value() + (up ? get_step() : -get_step()));
range_click_timer->set_wait_time(0.6);
range_click_timer->set_one_shot(true);
@@ -117,70 +109,68 @@ void SpinBox::_gui_input(const InputEvent& p_event) {
} break;
case BUTTON_RIGHT: {
- set_value( (up?get_max():get_min()) );
+ set_value((up ? get_max() : get_min()));
line_edit->grab_focus();
} break;
case BUTTON_WHEEL_UP: {
if (line_edit->has_focus()) {
- set_value( get_value() + get_step() );
+ set_value(get_value() + get_step());
accept_event();
}
} break;
case BUTTON_WHEEL_DOWN: {
if (line_edit->has_focus()) {
- set_value( get_value() - get_step() );
+ set_value(get_value() - get_step());
accept_event();
}
} break;
}
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index==1) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index == 1) {
//set_default_cursor_shape(CURSOR_VSIZE);
- Vector2 cpos = Vector2(p_event.mouse_button.x,p_event.mouse_button.y);
- drag.mouse_pos=cpos;
+ Vector2 cpos = Vector2(p_event.mouse_button.x, p_event.mouse_button.y);
+ drag.mouse_pos = cpos;
}
- if (p_event.type==InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index==1) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && !p_event.mouse_button.pressed && p_event.mouse_button.button_index == 1) {
//set_default_cursor_shape(CURSOR_ARROW);
range_click_timer->stop();
if (drag.enabled) {
- drag.enabled=false;
+ drag.enabled = false;
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
warp_mouse(drag.capture_pos);
}
}
- if (p_event.type==InputEvent::MOUSE_MOTION && p_event.mouse_button.button_mask&1) {
+ if (p_event.type == InputEvent::MOUSE_MOTION && p_event.mouse_button.button_mask & 1) {
- Vector2 cpos = Vector2(p_event.mouse_motion.x,p_event.mouse_motion.y);
+ Vector2 cpos = Vector2(p_event.mouse_motion.x, p_event.mouse_motion.y);
if (drag.enabled) {
float diff_y = drag.mouse_pos.y - cpos.y;
- diff_y=Math::pow(ABS(diff_y),1.8f)*SGN(diff_y);
- diff_y*=0.1;
+ diff_y = Math::pow(ABS(diff_y), 1.8f) * SGN(diff_y);
+ diff_y *= 0.1;
- drag.mouse_pos=cpos;
- drag.base_val=CLAMP(drag.base_val + get_step() * diff_y, get_min(), get_max());
+ drag.mouse_pos = cpos;
+ drag.base_val = CLAMP(drag.base_val + get_step() * diff_y, get_min(), get_max());
- set_value( drag.base_val);
+ set_value(drag.base_val);
- } else if (drag.mouse_pos.distance_to(cpos)>2) {
+ } else if (drag.mouse_pos.distance_to(cpos) > 2) {
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
- drag.enabled=true;
- drag.base_val=get_value();
- drag.mouse_pos=cpos;
- drag.capture_pos=cpos;
-
+ drag.enabled = true;
+ drag.base_val = get_value();
+ drag.mouse_pos = cpos;
+ drag.capture_pos = cpos;
}
}
}
-
void SpinBox::_line_edit_focus_exit() {
_text_entered(line_edit->get_text());
@@ -188,54 +178,48 @@ void SpinBox::_line_edit_focus_exit() {
void SpinBox::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> updown = get_icon("updown");
int w = updown->get_width();
- if (w!=last_w) {
- line_edit->set_margin(MARGIN_RIGHT,w);
- last_w=w;
+ if (w != last_w) {
+ line_edit->set_margin(MARGIN_RIGHT, w);
+ last_w = w;
}
RID ci = get_canvas_item();
Size2i size = get_size();
- updown->draw(ci,Point2i(size.width-updown->get_width(),(size.height-updown->get_height())/2));
-
- } else if (p_what==NOTIFICATION_FOCUS_EXIT) {
+ updown->draw(ci, Point2i(size.width - updown->get_width(), (size.height - updown->get_height()) / 2));
+ } else if (p_what == NOTIFICATION_FOCUS_EXIT) {
//_value_changed(0);
- } else if (p_what==NOTIFICATION_ENTER_TREE) {
+ } else if (p_what == NOTIFICATION_ENTER_TREE) {
_value_changed(0);
}
-
}
+void SpinBox::set_suffix(const String &p_suffix) {
-void SpinBox::set_suffix(const String& p_suffix) {
-
- suffix=p_suffix;
+ suffix = p_suffix;
_value_changed(0);
-
}
-String SpinBox::get_suffix() const{
+String SpinBox::get_suffix() const {
return suffix;
}
+void SpinBox::set_prefix(const String &p_prefix) {
-void SpinBox::set_prefix(const String& p_prefix) {
-
- prefix=p_prefix;
+ prefix = p_prefix;
_value_changed(0);
-
}
-String SpinBox::get_prefix() const{
+String SpinBox::get_prefix() const {
return prefix;
}
@@ -252,41 +236,38 @@ bool SpinBox::is_editable() const {
void SpinBox::_bind_methods() {
//ClassDB::bind_method(D_METHOD("_value_changed"),&SpinBox::_value_changed);
- ClassDB::bind_method(D_METHOD("_gui_input"),&SpinBox::_gui_input);
- ClassDB::bind_method(D_METHOD("_text_entered"),&SpinBox::_text_entered);
- ClassDB::bind_method(D_METHOD("set_suffix","suffix"),&SpinBox::set_suffix);
- ClassDB::bind_method(D_METHOD("get_suffix"),&SpinBox::get_suffix);
- ClassDB::bind_method(D_METHOD("set_prefix","prefix"),&SpinBox::set_prefix);
- ClassDB::bind_method(D_METHOD("get_prefix"),&SpinBox::get_prefix);
- ClassDB::bind_method(D_METHOD("set_editable","editable"),&SpinBox::set_editable);
- ClassDB::bind_method(D_METHOD("is_editable"),&SpinBox::is_editable);
- ClassDB::bind_method(D_METHOD("_line_edit_focus_exit"),&SpinBox::_line_edit_focus_exit);
- ClassDB::bind_method(D_METHOD("get_line_edit"),&SpinBox::get_line_edit);
- ClassDB::bind_method(D_METHOD("_line_edit_input"),&SpinBox::_line_edit_input);
- ClassDB::bind_method(D_METHOD("_range_click_timeout"),&SpinBox::_range_click_timeout);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"editable"),"set_editable","is_editable");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"prefix"),"set_prefix","get_prefix");
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"suffix"),"set_suffix","get_suffix");
-
-
+ ClassDB::bind_method(D_METHOD("_gui_input"), &SpinBox::_gui_input);
+ ClassDB::bind_method(D_METHOD("_text_entered"), &SpinBox::_text_entered);
+ ClassDB::bind_method(D_METHOD("set_suffix", "suffix"), &SpinBox::set_suffix);
+ ClassDB::bind_method(D_METHOD("get_suffix"), &SpinBox::get_suffix);
+ ClassDB::bind_method(D_METHOD("set_prefix", "prefix"), &SpinBox::set_prefix);
+ ClassDB::bind_method(D_METHOD("get_prefix"), &SpinBox::get_prefix);
+ ClassDB::bind_method(D_METHOD("set_editable", "editable"), &SpinBox::set_editable);
+ ClassDB::bind_method(D_METHOD("is_editable"), &SpinBox::is_editable);
+ ClassDB::bind_method(D_METHOD("_line_edit_focus_exit"), &SpinBox::_line_edit_focus_exit);
+ ClassDB::bind_method(D_METHOD("get_line_edit"), &SpinBox::get_line_edit);
+ ClassDB::bind_method(D_METHOD("_line_edit_input"), &SpinBox::_line_edit_input);
+ ClassDB::bind_method(D_METHOD("_range_click_timeout"), &SpinBox::_range_click_timeout);
+
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "prefix"), "set_prefix", "get_prefix");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "suffix"), "set_suffix", "get_suffix");
}
SpinBox::SpinBox() {
last_w = 0;
- line_edit = memnew( LineEdit );
+ line_edit = memnew(LineEdit);
add_child(line_edit);
line_edit->set_area_as_parent_rect();
//connect("value_changed",this,"_value_changed");
- line_edit->connect("text_entered",this,"_text_entered",Vector<Variant>(),CONNECT_DEFERRED);
- line_edit->connect("focus_exited",this,"_line_edit_focus_exit",Vector<Variant>(),CONNECT_DEFERRED);
- line_edit->connect("gui_input",this,"_line_edit_input");
- drag.enabled=false;
+ line_edit->connect("text_entered", this, "_text_entered", Vector<Variant>(), CONNECT_DEFERRED);
+ line_edit->connect("focus_exited", this, "_line_edit_focus_exit", Vector<Variant>(), CONNECT_DEFERRED);
+ line_edit->connect("gui_input", this, "_line_edit_input");
+ drag.enabled = false;
- range_click_timer = memnew( Timer );
- range_click_timer->connect("timeout",this,"_range_click_timeout");
+ range_click_timer = memnew(Timer);
+ range_click_timer->connect("timeout", this, "_range_click_timeout");
add_child(range_click_timer);
}
diff --git a/scene/gui/spin_box.h b/scene/gui/spin_box.h
index 9974ec47bc..eba58402fa 100644
--- a/scene/gui/spin_box.h
+++ b/scene/gui/spin_box.h
@@ -35,7 +35,7 @@
class SpinBox : public Range {
- GDCLASS( SpinBox, Range );
+ GDCLASS(SpinBox, Range);
LineEdit *line_edit;
int last_w;
@@ -43,35 +43,31 @@ class SpinBox : public Range {
Timer *range_click_timer;
void _range_click_timeout();
- void _text_entered(const String& p_string);
+ void _text_entered(const String &p_string);
virtual void _value_changed(double);
String prefix;
String suffix;
- void _line_edit_input(const InputEvent& p_event);
-
+ void _line_edit_input(const InputEvent &p_event);
struct Drag {
float base_val;
bool enabled;
Vector2 from;
- Vector2 mouse_pos;
+ Vector2 mouse_pos;
Vector2 capture_pos;
} drag;
-
void _line_edit_focus_exit();
protected:
-
- void _gui_input(const InputEvent& p_event);
-
+ void _gui_input(const InputEvent &p_event);
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
LineEdit *get_line_edit();
virtual Size2 get_minimum_size() const;
@@ -79,10 +75,10 @@ public:
void set_editable(bool p_editable);
bool is_editable() const;
- void set_suffix(const String& p_suffix);
+ void set_suffix(const String &p_suffix);
String get_suffix() const;
- void set_prefix(const String& p_prefix);
+ void set_prefix(const String &p_prefix);
String get_prefix() const;
SpinBox();
diff --git a/scene/gui/split_container.cpp b/scene/gui/split_container.cpp
index 14ea96a4e6..5b6f17e0f7 100644
--- a/scene/gui/split_container.cpp
+++ b/scene/gui/split_container.cpp
@@ -28,10 +28,8 @@
/*************************************************************************/
#include "split_container.h"
-#include "margin_container.h"
#include "label.h"
-
-
+#include "margin_container.h"
struct _MinSizeCache {
@@ -40,235 +38,208 @@ struct _MinSizeCache {
int final_size;
};
-
Control *SplitContainer::_getch(int p_idx) const {
- int idx=0;
+ int idx = 0;
- for(int i=0;i<get_child_count();i++) {
- Control *c=get_child(i)->cast_to<Control>();
+ for (int i = 0; i < get_child_count(); i++) {
+ Control *c = get_child(i)->cast_to<Control>();
if (!c || !c->is_visible_in_tree())
continue;
if (c->is_set_as_toplevel())
continue;
- if (idx==p_idx)
+ if (idx == p_idx)
return c;
idx++;
}
return NULL;
-
}
-
void SplitContainer::_resort() {
/** First pass, determine minimum size AND amount of stretchable elements */
- int axis = vertical?1:0;
+ int axis = vertical ? 1 : 0;
- bool has_first=_getch(0);
- bool has_second=_getch(1);
+ bool has_first = _getch(0);
+ bool has_second = _getch(1);
if (!has_first && !has_second) {
return;
- } else if (! (has_first && has_second)) {
+ } else if (!(has_first && has_second)) {
if (has_first)
- fit_child_in_rect(_getch(0),Rect2(Point2(),get_size()));
+ fit_child_in_rect(_getch(0), Rect2(Point2(), get_size()));
else
- fit_child_in_rect(_getch(1),Rect2(Point2(),get_size()));
+ fit_child_in_rect(_getch(1), Rect2(Point2(), get_size()));
return;
}
+ Control *first = _getch(0);
+ Control *second = _getch(1);
-
- Control *first=_getch(0);
- Control *second=_getch(1);
-
-
- bool ratiomode=false;
- bool expand_first_mode=false;
-
-
-
+ bool ratiomode = false;
+ bool expand_first_mode = false;
if (vertical) {
- ratiomode=first->get_v_size_flags()&SIZE_EXPAND && second->get_v_size_flags()&SIZE_EXPAND;
- expand_first_mode=first->get_v_size_flags()&SIZE_EXPAND && !(second->get_v_size_flags()&SIZE_EXPAND);
+ ratiomode = first->get_v_size_flags() & SIZE_EXPAND && second->get_v_size_flags() & SIZE_EXPAND;
+ expand_first_mode = first->get_v_size_flags() & SIZE_EXPAND && !(second->get_v_size_flags() & SIZE_EXPAND);
} else {
- ratiomode=first->get_h_size_flags()&SIZE_EXPAND && second->get_h_size_flags()&SIZE_EXPAND;
- expand_first_mode=first->get_h_size_flags()&SIZE_EXPAND && !(second->get_h_size_flags()&SIZE_EXPAND);
+ ratiomode = first->get_h_size_flags() & SIZE_EXPAND && second->get_h_size_flags() & SIZE_EXPAND;
+ expand_first_mode = first->get_h_size_flags() & SIZE_EXPAND && !(second->get_h_size_flags() & SIZE_EXPAND);
}
-
- int sep=get_constant("separation");
+ int sep = get_constant("separation");
Ref<Texture> g = get_icon("grabber");
- if (dragger_visibility==DRAGGER_HIDDEN_COLLAPSED) {
- sep=0;
+ if (dragger_visibility == DRAGGER_HIDDEN_COLLAPSED) {
+ sep = 0;
} else {
- sep=MAX(sep,vertical?g->get_height():g->get_width());
+ sep = MAX(sep, vertical ? g->get_height() : g->get_width());
}
- int total = vertical?get_size().height:get_size().width;
+ int total = vertical ? get_size().height : get_size().width;
- total-=sep;
+ total -= sep;
- int minimum=0;
+ int minimum = 0;
Size2 ms_first = first->get_combined_minimum_size();
Size2 ms_second = second->get_combined_minimum_size();
if (vertical) {
- minimum=ms_first.height+ms_second.height;
+ minimum = ms_first.height + ms_second.height;
} else {
- minimum=ms_first.width+ms_second.width;
+ minimum = ms_first.width + ms_second.width;
}
- int available=total-minimum;
- if (available<0)
- available=0;
-
+ int available = total - minimum;
+ if (available < 0)
+ available = 0;
- middle_sep=0;
+ middle_sep = 0;
if (collapsed) {
-
if (ratiomode) {
- middle_sep=ms_first[axis]+available/2;
-
+ middle_sep = ms_first[axis] + available / 2;
} else if (expand_first_mode) {
- middle_sep=get_size()[axis]-ms_second[axis]-sep;
+ middle_sep = get_size()[axis] - ms_second[axis] - sep;
} else {
- middle_sep=ms_first[axis];
+ middle_sep = ms_first[axis];
}
-
} else if (ratiomode) {
- if (expand_ofs<-(available/2))
- expand_ofs=-(available/2);
- else if (expand_ofs>(available/2))
- expand_ofs=(available/2);
-
- middle_sep=ms_first[axis]+available/2+expand_ofs;
+ if (expand_ofs < -(available / 2))
+ expand_ofs = -(available / 2);
+ else if (expand_ofs > (available / 2))
+ expand_ofs = (available / 2);
+ middle_sep = ms_first[axis] + available / 2 + expand_ofs;
} else if (expand_first_mode) {
- if (expand_ofs>0)
- expand_ofs=0;
+ if (expand_ofs > 0)
+ expand_ofs = 0;
if (expand_ofs < -available)
- expand_ofs=-available;
+ expand_ofs = -available;
- middle_sep=get_size()[axis]-ms_second[axis]-sep+expand_ofs;
+ middle_sep = get_size()[axis] - ms_second[axis] - sep + expand_ofs;
} else {
- if (expand_ofs<0)
- expand_ofs=0;
+ if (expand_ofs < 0)
+ expand_ofs = 0;
if (expand_ofs > available)
- expand_ofs=available;
-
- middle_sep=ms_first[axis]+expand_ofs;
+ expand_ofs = available;
+ middle_sep = ms_first[axis] + expand_ofs;
}
-
-
if (vertical) {
- fit_child_in_rect(first,Rect2(Point2(0,0),Size2(get_size().width,middle_sep)));
- int sofs=middle_sep+sep;
- fit_child_in_rect(second,Rect2(Point2(0,sofs),Size2(get_size().width,get_size().height-sofs)));
+ fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(get_size().width, middle_sep)));
+ int sofs = middle_sep + sep;
+ fit_child_in_rect(second, Rect2(Point2(0, sofs), Size2(get_size().width, get_size().height - sofs)));
} else {
-
- fit_child_in_rect(first,Rect2(Point2(0,0),Size2(middle_sep,get_size().height)));
- int sofs=middle_sep+sep;
- fit_child_in_rect(second,Rect2(Point2(sofs,0),Size2(get_size().width-sofs,get_size().height)));
+ fit_child_in_rect(first, Rect2(Point2(0, 0), Size2(middle_sep, get_size().height)));
+ int sofs = middle_sep + sep;
+ fit_child_in_rect(second, Rect2(Point2(sofs, 0), Size2(get_size().width - sofs, get_size().height)));
}
update();
_change_notify("split/offset");
-
}
-
-
-
Size2 SplitContainer::get_minimum_size() const {
-
/* Calculate MINIMUM SIZE */
Size2i minimum;
- int sep=get_constant("separation");
+ int sep = get_constant("separation");
Ref<Texture> g = get_icon("grabber");
- sep=(dragger_visibility!=DRAGGER_HIDDEN_COLLAPSED)?MAX(sep,vertical?g->get_height():g->get_width()):0;
+ sep = (dragger_visibility != DRAGGER_HIDDEN_COLLAPSED) ? MAX(sep, vertical ? g->get_height() : g->get_width()) : 0;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
if (!_getch(i))
break;
- if (i==1) {
+ if (i == 1) {
if (vertical)
- minimum.height+=sep;
+ minimum.height += sep;
else
- minimum.width+=sep;
+ minimum.width += sep;
}
Size2 ms = _getch(i)->get_combined_minimum_size();
if (vertical) {
- minimum.height+=ms.height;
- minimum.width=MAX(minimum.width,ms.width);
+ minimum.height += ms.height;
+ minimum.width = MAX(minimum.width, ms.width);
} else {
- minimum.width+=ms.width;
- minimum.height=MAX(minimum.height,ms.height);
+ minimum.width += ms.width;
+ minimum.height = MAX(minimum.height, ms.height);
}
-
}
return minimum;
-
-
}
void SplitContainer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
_resort();
} break;
case NOTIFICATION_MOUSE_ENTER: {
- mouse_inside=true;
+ mouse_inside = true;
update();
} break;
case NOTIFICATION_MOUSE_EXIT: {
- mouse_inside=false;
+ mouse_inside = false;
update();
} break;
case NOTIFICATION_DRAW: {
@@ -278,111 +249,105 @@ void SplitContainer::_notification(int p_what) {
if (collapsed || (!mouse_inside && get_constant("autohide")))
return;
- int sep=dragger_visibility!=DRAGGER_HIDDEN_COLLAPSED?get_constant("separation"):0;
+ int sep = dragger_visibility != DRAGGER_HIDDEN_COLLAPSED ? get_constant("separation") : 0;
Ref<Texture> tex = get_icon("grabber");
- Size2 size=get_size();
+ Size2 size = get_size();
if (vertical) {
//draw_style_box( get_stylebox("bg"), Rect2(0,middle_sep,get_size().width,sep));
- if (dragger_visibility==DRAGGER_VISIBLE)
- draw_texture(tex,Point2i((size.x-tex->get_width())/2,middle_sep+(sep-tex->get_height())/2));
+ if (dragger_visibility == DRAGGER_VISIBLE)
+ draw_texture(tex, Point2i((size.x - tex->get_width()) / 2, middle_sep + (sep - tex->get_height()) / 2));
} else {
//draw_style_box( get_stylebox("bg"), Rect2(middle_sep,0,sep,get_size().height));
- if (dragger_visibility==DRAGGER_VISIBLE)
- draw_texture(tex,Point2i(middle_sep+(sep-tex->get_width())/2,(size.y-tex->get_height())/2));
-
+ if (dragger_visibility == DRAGGER_VISIBLE)
+ draw_texture(tex, Point2i(middle_sep + (sep - tex->get_width()) / 2, (size.y - tex->get_height()) / 2));
}
} break;
}
}
-void SplitContainer::_gui_input(const InputEvent& p_event) {
+void SplitContainer::_gui_input(const InputEvent &p_event) {
- if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility!=DRAGGER_VISIBLE)
+ if (collapsed || !_getch(0) || !_getch(1) || dragger_visibility != DRAGGER_VISIBLE)
return;
- if (p_event.type==InputEvent::MOUSE_BUTTON) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON) {
- const InputEventMouseButton &mb=p_event.mouse_button;
+ const InputEventMouseButton &mb = p_event.mouse_button;
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
if (mb.pressed) {
- int sep=get_constant("separation");
+ int sep = get_constant("separation");
if (vertical) {
-
- if (mb.y > middle_sep && mb.y < middle_sep+sep) {
- dragging=true;
- drag_from=mb.y;
- drag_ofs=expand_ofs;
+ if (mb.y > middle_sep && mb.y < middle_sep + sep) {
+ dragging = true;
+ drag_from = mb.y;
+ drag_ofs = expand_ofs;
}
} else {
- if (mb.x > middle_sep && mb.x < middle_sep+sep) {
- dragging=true;
- drag_from=mb.x;
- drag_ofs=expand_ofs;
+ if (mb.x > middle_sep && mb.x < middle_sep + sep) {
+ dragging = true;
+ drag_from = mb.x;
+ drag_ofs = expand_ofs;
}
}
} else {
- dragging=false;
+ dragging = false;
}
-
}
}
- if (p_event.type==InputEvent::MOUSE_MOTION) {
+ if (p_event.type == InputEvent::MOUSE_MOTION) {
- const InputEventMouseMotion &mm=p_event.mouse_motion;
+ const InputEventMouseMotion &mm = p_event.mouse_motion;
if (dragging) {
- expand_ofs=drag_ofs+((vertical?mm.y:mm.x)-drag_from);
+ expand_ofs = drag_ofs + ((vertical ? mm.y : mm.x) - drag_from);
queue_sort();
- emit_signal("dragged",get_split_offset());
+ emit_signal("dragged", get_split_offset());
}
}
-
}
-Control::CursorShape SplitContainer::get_cursor_shape(const Point2& p_pos) const {
+Control::CursorShape SplitContainer::get_cursor_shape(const Point2 &p_pos) const {
if (collapsed)
return Control::get_cursor_shape(p_pos);
if (dragging)
- return (vertical?CURSOR_VSIZE:CURSOR_HSIZE);
+ return (vertical ? CURSOR_VSIZE : CURSOR_HSIZE);
- int sep=get_constant("separation");
+ int sep = get_constant("separation");
if (vertical) {
-
- if (p_pos.y > middle_sep && p_pos.y < middle_sep+sep) {
+ if (p_pos.y > middle_sep && p_pos.y < middle_sep + sep) {
return CURSOR_VSIZE;
}
} else {
- if (p_pos.x > middle_sep && p_pos.x < middle_sep+sep) {
+ if (p_pos.x > middle_sep && p_pos.x < middle_sep + sep) {
return CURSOR_HSIZE;
}
}
return Control::get_cursor_shape(p_pos);
-
}
void SplitContainer::set_split_offset(int p_offset) {
- if (expand_ofs==p_offset)
+ if (expand_ofs == p_offset)
return;
- expand_ofs=p_offset;
+ expand_ofs = p_offset;
queue_sort();
}
@@ -393,16 +358,15 @@ int SplitContainer::get_split_offset() const {
void SplitContainer::set_collapsed(bool p_collapsed) {
- if (collapsed==p_collapsed)
+ if (collapsed == p_collapsed)
return;
- collapsed=p_collapsed;
+ collapsed = p_collapsed;
queue_sort();
-
}
void SplitContainer::set_dragger_visibility(DraggerVisibility p_visibility) {
- dragger_visibility=p_visibility;
+ dragger_visibility = p_visibility;
queue_sort();
update();
}
@@ -412,49 +376,41 @@ SplitContainer::DraggerVisibility SplitContainer::get_dragger_visibility() const
return dragger_visibility;
}
-
bool SplitContainer::is_collapsed() const {
-
return collapsed;
}
-
void SplitContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&SplitContainer::_gui_input);
- ClassDB::bind_method(D_METHOD("set_split_offset","offset"),&SplitContainer::set_split_offset);
- ClassDB::bind_method(D_METHOD("get_split_offset"),&SplitContainer::get_split_offset);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &SplitContainer::_gui_input);
+ ClassDB::bind_method(D_METHOD("set_split_offset", "offset"), &SplitContainer::set_split_offset);
+ ClassDB::bind_method(D_METHOD("get_split_offset"), &SplitContainer::get_split_offset);
- ClassDB::bind_method(D_METHOD("set_collapsed","collapsed"),&SplitContainer::set_collapsed);
- ClassDB::bind_method(D_METHOD("is_collapsed"),&SplitContainer::is_collapsed);
+ ClassDB::bind_method(D_METHOD("set_collapsed", "collapsed"), &SplitContainer::set_collapsed);
+ ClassDB::bind_method(D_METHOD("is_collapsed"), &SplitContainer::is_collapsed);
- ClassDB::bind_method(D_METHOD("set_dragger_visibility","mode"),&SplitContainer::set_dragger_visibility);
- ClassDB::bind_method(D_METHOD("get_dragger_visibility"),&SplitContainer::get_dragger_visibility);
+ ClassDB::bind_method(D_METHOD("set_dragger_visibility", "mode"), &SplitContainer::set_dragger_visibility);
+ ClassDB::bind_method(D_METHOD("get_dragger_visibility"), &SplitContainer::get_dragger_visibility);
- ADD_SIGNAL( MethodInfo("dragged",PropertyInfo(Variant::INT,"offset")));
+ ADD_SIGNAL(MethodInfo("dragged", PropertyInfo(Variant::INT, "offset")));
- ADD_PROPERTY( PropertyInfo(Variant::INT,"split_offset"),"set_split_offset","get_split_offset");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"collapsed"),"set_collapsed","is_collapsed");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"dragger_visibility",PROPERTY_HINT_ENUM,"Visible,Hidden,Hidden & Collapsed"),"set_dragger_visibility","get_dragger_visibility");
-
- BIND_CONSTANT( DRAGGER_VISIBLE );
- BIND_CONSTANT( DRAGGER_HIDDEN );
- BIND_CONSTANT( DRAGGER_HIDDEN_COLLAPSED );
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "split_offset"), "set_split_offset", "get_split_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collapsed"), "set_collapsed", "is_collapsed");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dragger_visibility", PROPERTY_HINT_ENUM, "Visible,Hidden,Hidden & Collapsed"), "set_dragger_visibility", "get_dragger_visibility");
+ BIND_CONSTANT(DRAGGER_VISIBLE);
+ BIND_CONSTANT(DRAGGER_HIDDEN);
+ BIND_CONSTANT(DRAGGER_HIDDEN_COLLAPSED);
}
SplitContainer::SplitContainer(bool p_vertical) {
-
- mouse_inside=false;
- expand_ofs=0;
- middle_sep=0;
- vertical=p_vertical;
- dragging=false;
- collapsed=false;
- dragger_visibility=DRAGGER_VISIBLE;
-
+ mouse_inside = false;
+ expand_ofs = 0;
+ middle_sep = 0;
+ vertical = p_vertical;
+ dragging = false;
+ collapsed = false;
+ dragger_visibility = DRAGGER_VISIBLE;
}
-
-
diff --git a/scene/gui/split_container.h b/scene/gui/split_container.h
index 03b6b1a167..8db6bfa658 100644
--- a/scene/gui/split_container.h
+++ b/scene/gui/split_container.h
@@ -31,16 +31,17 @@
#include "scene/gui/container.h"
-
class SplitContainer : public Container {
- GDCLASS(SplitContainer,Container);
+ GDCLASS(SplitContainer, Container);
+
public:
enum DraggerVisibility {
DRAGGER_VISIBLE,
DRAGGER_HIDDEN,
DRAGGER_HIDDEN_COLLAPSED
};
+
private:
bool vertical;
int expand_ofs;
@@ -52,20 +53,16 @@ private:
DraggerVisibility dragger_visibility;
bool mouse_inside;
-
Control *_getch(int p_idx) const;
void _resort();
-protected:
-
- void _gui_input(const InputEvent& p_event);
+protected:
+ void _gui_input(const InputEvent &p_event);
void _notification(int p_what);
static void _bind_methods();
-public:
-
-
+public:
void set_split_offset(int p_offset);
int get_split_offset() const;
@@ -75,32 +72,31 @@ public:
void set_dragger_visibility(DraggerVisibility p_visibility);
DraggerVisibility get_dragger_visibility() const;
- virtual CursorShape get_cursor_shape(const Point2& p_pos=Point2i()) const;
+ virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const;
virtual Size2 get_minimum_size() const;
- SplitContainer(bool p_vertical=false);
+ SplitContainer(bool p_vertical = false);
};
VARIANT_ENUM_CAST(SplitContainer::DraggerVisibility);
class HSplitContainer : public SplitContainer {
- GDCLASS(HSplitContainer,SplitContainer);
+ GDCLASS(HSplitContainer, SplitContainer);
public:
-
- HSplitContainer() : SplitContainer(false) {set_default_cursor_shape(CURSOR_HSPLIT);}
+ HSplitContainer()
+ : SplitContainer(false) { set_default_cursor_shape(CURSOR_HSPLIT); }
};
-
class VSplitContainer : public SplitContainer {
- GDCLASS(VSplitContainer,SplitContainer);
+ GDCLASS(VSplitContainer, SplitContainer);
public:
-
- VSplitContainer() : SplitContainer(true) {set_default_cursor_shape(CURSOR_VSPLIT);}
+ VSplitContainer()
+ : SplitContainer(true) { set_default_cursor_shape(CURSOR_VSPLIT); }
};
#endif // SPLIT_CONTAINER_H
diff --git a/scene/gui/tab_container.cpp b/scene/gui/tab_container.cpp
index fc25b68db9..89769937d4 100644
--- a/scene/gui/tab_container.cpp
+++ b/scene/gui/tab_container.cpp
@@ -30,7 +30,6 @@
#include "message_queue.h"
-
int TabContainer::_get_top_margin() const {
if (!tabs_visible)
@@ -47,7 +46,7 @@ int TabContainer::_get_top_margin() const {
Ref<Font> font = get_font("font");
int content_height = font->get_height();
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
for (int i = 0; i < tabs.size(); i++) {
Control *c = tabs[i];
@@ -63,13 +62,9 @@ int TabContainer::_get_top_margin() const {
return tab_height + content_height;
}
+void TabContainer::_gui_input(const InputEvent &p_event) {
-
-void TabContainer::_gui_input(const InputEvent& p_event) {
-
- if (p_event.type == InputEvent::MOUSE_BUTTON
- && p_event.mouse_button.pressed
- && p_event.mouse_button.button_index == BUTTON_LEFT) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON && p_event.mouse_button.pressed && p_event.mouse_button.button_index == BUTTON_LEFT) {
Point2 pos(p_event.mouse_button.x, p_event.mouse_button.y);
Size2 size = get_size();
@@ -92,7 +87,7 @@ void TabContainer::_gui_input(const InputEvent& p_event) {
return;
}
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
// Handle navigation buttons.
if (buttons_visible_cache) {
@@ -144,7 +139,7 @@ void TabContainer::_notification(int p_what) {
return;
}
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
Ref<StyleBox> tab_bg = get_stylebox("tab_bg");
Ref<StyleBox> tab_fg = get_stylebox("tab_fg");
Ref<StyleBox> tab_disabled = get_stylebox("tab_disabled");
@@ -233,9 +228,7 @@ void TabContainer::_notification(int p_what) {
// Draw the tab contents.
Control *control = tabs[i + first_tab_cache]->cast_to<Control>();
- String text = control->has_meta("_tab_name")
- ? String(XL_MESSAGE(String(control->get_meta("_tab_name"))))
- : String(control->get_name());
+ String text = control->has_meta("_tab_name") ? String(XL_MESSAGE(String(control->get_meta("_tab_name")))) : String(control->get_name());
int x_content = tab_rect.pos.x + tab_style->get_margin(MARGIN_LEFT);
int top_margin = tab_style->get_margin(MARGIN_TOP);
@@ -276,13 +269,13 @@ void TabContainer::_notification(int p_what) {
x -= increment->get_width();
increment->draw(canvas,
- Point2(x, y_center - (increment->get_height() / 2)),
- Color(1, 1, 1, last_tab_cache < tabs.size() - 1 ? 1.0 : 0.5));
+ Point2(x, y_center - (increment->get_height() / 2)),
+ Color(1, 1, 1, last_tab_cache < tabs.size() - 1 ? 1.0 : 0.5));
x -= decrement->get_width();
decrement->draw(canvas,
- Point2(x, y_center - (decrement->get_height() / 2)),
- Color(1, 1, 1, first_tab_cache > 0 ? 1.0 : 0.5));
+ Point2(x, y_center - (decrement->get_height() / 2)),
+ Color(1, 1, 1, first_tab_cache > 0 ? 1.0 : 0.5));
}
// Draw the tab area.
@@ -303,9 +296,7 @@ int TabContainer::_get_tab_width(int p_index) const {
// Get the width of the text displayed on the tab.
Ref<Font> font = get_font("font");
- String text = control->has_meta("_tab_name")
- ? String(XL_MESSAGE(String(control->get_meta("_tab_name"))))
- : String(control->get_name());
+ String text = control->has_meta("_tab_name") ? String(XL_MESSAGE(String(control->get_meta("_tab_name")))) : String(control->get_name());
int width = font->get_string_size(text).width;
// Add space for a tab icon.
@@ -333,9 +324,9 @@ int TabContainer::_get_tab_width(int p_index) const {
return width;
}
-Vector<Control*> TabContainer::_get_tabs() const {
+Vector<Control *> TabContainer::_get_tabs() const {
- Vector<Control*> controls;
+ Vector<Control *> controls;
for (int i = 0; i < get_child_count(); i++) {
Control *control = get_child(i)->cast_to<Control>();
@@ -380,7 +371,6 @@ void TabContainer::add_child_notify(Node *p_child) {
for (int i = 0; i < 4; i++)
c->set_margin(Margin(i), c->get_margin(Margin(i)) + sb->get_margin(Margin(i)));
-
update();
p_child->connect("renamed", this, "_child_renamed_callback");
if (first)
@@ -392,7 +382,6 @@ int TabContainer::get_tab_count() const {
return _get_tabs().size();
}
-
void TabContainer::set_current_tab(int p_current) {
ERR_FAIL_INDEX(p_current, get_tab_count());
@@ -401,7 +390,7 @@ void TabContainer::set_current_tab(int p_current) {
current = p_current;
Ref<StyleBox> sb = get_stylebox("panel");
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
for (int i = 0; i < tabs.size(); i++) {
Control *c = tabs[i];
@@ -413,9 +402,7 @@ void TabContainer::set_current_tab(int p_current) {
for (int i = 0; i < 4; i++)
c->set_margin(Margin(i), c->get_margin(Margin(i)) + sb->get_margin(Margin(i)));
-
- }
- else
+ } else
c->hide();
}
@@ -438,22 +425,22 @@ int TabContainer::get_current_tab() const {
}
int TabContainer::get_previous_tab() const {
-
- return previous;
+
+ return previous;
}
-Control* TabContainer::get_tab_control(int p_idx) const {
+Control *TabContainer::get_tab_control(int p_idx) const {
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
if (p_idx >= 0 && p_idx < tabs.size())
return tabs[p_idx];
else
return NULL;
}
-Control* TabContainer::get_current_tab_control() const {
+Control *TabContainer::get_current_tab_control() const {
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
if (current >= 0 && current < tabs.size())
return tabs[current];
else
@@ -499,7 +486,7 @@ void TabContainer::set_tabs_visible(bool p_visibe) {
tabs_visible = p_visibe;
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
for (int i = 0; i < tabs.size(); i++) {
Control *c = tabs[i];
@@ -507,7 +494,6 @@ void TabContainer::set_tabs_visible(bool p_visibe) {
c->set_margin(MARGIN_TOP, _get_top_margin());
else
c->set_margin(MARGIN_TOP, 0);
-
}
update();
}
@@ -515,21 +501,18 @@ void TabContainer::set_tabs_visible(bool p_visibe) {
bool TabContainer::are_tabs_visible() const {
return tabs_visible;
-
}
Control *TabContainer::_get_tab(int p_idx) const {
return get_tab_control(p_idx);
-
}
-void TabContainer::set_tab_title(int p_tab, const String& p_title) {
+void TabContainer::set_tab_title(int p_tab, const String &p_title) {
Control *child = _get_tab(p_tab);
ERR_FAIL_COND(!child);
child->set_meta("_tab_name", p_title);
-
}
String TabContainer::get_tab_title(int p_tab) const {
@@ -540,15 +523,13 @@ String TabContainer::get_tab_title(int p_tab) const {
return child->get_meta("_tab_name");
else
return child->get_name();
-
}
-void TabContainer::set_tab_icon(int p_tab, const Ref<Texture>& p_icon) {
+void TabContainer::set_tab_icon(int p_tab, const Ref<Texture> &p_icon) {
Control *child = _get_tab(p_tab);
ERR_FAIL_COND(!child);
child->set_meta("_tab_icon", p_icon);
-
}
Ref<Texture> TabContainer::get_tab_icon(int p_tab) const {
@@ -580,7 +561,7 @@ bool TabContainer::get_tab_disabled(int p_tab) const {
void TabContainer::get_translatable_strings(List<String> *p_strings) const {
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
for (int i = 0; i < tabs.size(); i++) {
Control *c = tabs[i];
@@ -599,7 +580,7 @@ Size2 TabContainer::get_minimum_size() const {
Size2 ms;
- Vector<Control*> tabs = _get_tabs();
+ Vector<Control *> tabs = _get_tabs();
for (int i = 0; i < tabs.size(); i++) {
Control *c = tabs[i];
@@ -632,7 +613,7 @@ void TabContainer::set_popup(Node *p_popup) {
update();
}
-Popup* TabContainer::get_popup() const {
+Popup *TabContainer::get_popup() const {
return popup;
}
@@ -667,7 +648,6 @@ void TabContainer::_bind_methods() {
ADD_PROPERTY(PropertyInfo(Variant::INT, "tab_align", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_tab_align", "get_tab_align");
ADD_PROPERTY(PropertyInfo(Variant::INT, "current_tab", PROPERTY_HINT_RANGE, "-1,4096,1", PROPERTY_USAGE_EDITOR), "set_current_tab", "get_current_tab");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tabs_visible"), "set_tabs_visible", "are_tabs_visible");
-
}
TabContainer::TabContainer() {
@@ -681,5 +661,4 @@ TabContainer::TabContainer() {
align = ALIGN_CENTER;
tabs_visible = true;
popup = NULL;
-
} \ No newline at end of file
diff --git a/scene/gui/tab_container.h b/scene/gui/tab_container.h
index d5a2801bbe..2594611844 100644
--- a/scene/gui/tab_container.h
+++ b/scene/gui/tab_container.h
@@ -29,22 +29,21 @@
#ifndef TAB_CONTAINER_H
#define TAB_CONTAINER_H
-
#include "scene/gui/control.h"
#include "scene/gui/popup.h"
class TabContainer : public Control {
- GDCLASS( TabContainer, Control );
-public:
+ GDCLASS(TabContainer, Control);
+public:
enum TabAlign {
ALIGN_LEFT,
ALIGN_CENTER,
ALIGN_RIGHT
};
-private:
+private:
int mouse_x_cache;
int first_tab_cache;
int tabs_ofs_cache;
@@ -58,13 +57,12 @@ private:
int _get_top_margin() const;
Popup *popup;
- Vector<Control*> _get_tabs() const;
+ Vector<Control *> _get_tabs() const;
int _get_tab_width(int p_index) const;
protected:
-
void _child_renamed_callback();
- void _gui_input(const InputEvent& p_event);
+ void _gui_input(const InputEvent &p_event);
void _notification(int p_what);
virtual void add_child_notify(Node *p_child);
virtual void remove_child_notify(Node *p_child);
@@ -72,18 +70,16 @@ protected:
static void _bind_methods();
public:
-
-
void set_tab_align(TabAlign p_align);
TabAlign get_tab_align() const;
void set_tabs_visible(bool p_visibe);
bool are_tabs_visible() const;
- void set_tab_title(int p_tab,const String& p_title);
+ void set_tab_title(int p_tab, const String &p_title);
String get_tab_title(int p_tab) const;
- void set_tab_icon(int p_tab,const Ref<Texture>& p_icon);
+ void set_tab_icon(int p_tab, const Ref<Texture> &p_icon);
Ref<Texture> get_tab_icon(int p_tab) const;
void set_tab_disabled(int p_tab, bool p_disabled);
@@ -94,21 +90,19 @@ public:
int get_current_tab() const;
int get_previous_tab() const;
- Control* get_tab_control(int p_idx) const;
- Control* get_current_tab_control() const;
+ Control *get_tab_control(int p_idx) const;
+ Control *get_current_tab_control() const;
virtual Size2 get_minimum_size() const;
virtual void get_translatable_strings(List<String> *p_strings) const;
void set_popup(Node *p_popup);
- Popup* get_popup() const;
-
+ Popup *get_popup() const;
TabContainer();
};
-
-VARIANT_ENUM_CAST( TabContainer::TabAlign );
+VARIANT_ENUM_CAST(TabContainer::TabAlign);
#endif // TAB_CONTAINER_H
diff --git a/scene/gui/tabs.cpp b/scene/gui/tabs.cpp
index 4e07a495ed..3197553876 100644
--- a/scene/gui/tabs.cpp
+++ b/scene/gui/tabs.cpp
@@ -37,152 +37,146 @@ Size2 Tabs::get_minimum_size() const {
Ref<StyleBox> tab_disabled = get_stylebox("tab_disabled");
Ref<Font> font = get_font("font");
- Size2 ms(0, MAX(MAX(tab_bg->get_minimum_size().height, tab_fg->get_minimum_size().height), tab_disabled->get_minimum_size().height)+font->get_height());
+ Size2 ms(0, MAX(MAX(tab_bg->get_minimum_size().height, tab_fg->get_minimum_size().height), tab_disabled->get_minimum_size().height) + font->get_height());
- for(int i=0;i<tabs.size();i++) {
+ for (int i = 0; i < tabs.size(); i++) {
Ref<Texture> tex = tabs[i].icon;
if (tex.is_valid()) {
ms.height = MAX(ms.height, tex->get_size().height);
- if (tabs[i].text!="")
- ms.width+=get_constant("hseparation");
+ if (tabs[i].text != "")
+ ms.width += get_constant("hseparation");
}
- ms.width+=font->get_string_size(tabs[i].text).width;
+ ms.width += font->get_string_size(tabs[i].text).width;
if (tabs[i].disabled)
ms.width += tab_disabled->get_minimum_size().width;
- else if (current==i)
- ms.width+=tab_fg->get_minimum_size().width;
+ else if (current == i)
+ ms.width += tab_fg->get_minimum_size().width;
else
- ms.width+=tab_bg->get_minimum_size().width;
+ ms.width += tab_bg->get_minimum_size().width;
if (tabs[i].right_button.is_valid()) {
- Ref<Texture> rb=tabs[i].right_button;
+ Ref<Texture> rb = tabs[i].right_button;
Size2 bms = rb->get_size();
- bms.width+=get_constant("hseparation");
- ms.width+=bms.width;
- ms.height=MAX(bms.height+tab_bg->get_minimum_size().height,ms.height);
+ bms.width += get_constant("hseparation");
+ ms.width += bms.width;
+ ms.height = MAX(bms.height + tab_bg->get_minimum_size().height, ms.height);
}
- if (cb_displaypolicy==CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy==CLOSE_BUTTON_SHOW_ACTIVE_ONLY && i==current)) {
- Ref<Texture> cb=get_icon("close");
+ if (cb_displaypolicy == CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy == CLOSE_BUTTON_SHOW_ACTIVE_ONLY && i == current)) {
+ Ref<Texture> cb = get_icon("close");
Size2 bms = cb->get_size();
- bms.width+=get_constant("hseparation");
- ms.width+=bms.width;
- ms.height=MAX(bms.height+tab_bg->get_minimum_size().height,ms.height);
+ bms.width += get_constant("hseparation");
+ ms.width += bms.width;
+ ms.height = MAX(bms.height + tab_bg->get_minimum_size().height, ms.height);
}
}
- ms.width=0; //TODO: should make this optional
+ ms.width = 0; //TODO: should make this optional
return ms;
}
+void Tabs::_gui_input(const InputEvent &p_event) {
-void Tabs::_gui_input(const InputEvent& p_event) {
+ if (p_event.type == InputEvent::MOUSE_MOTION) {
- if (p_event.type==InputEvent::MOUSE_MOTION) {
+ Point2 pos(p_event.mouse_motion.x, p_event.mouse_motion.y);
- Point2 pos( p_event.mouse_motion.x, p_event.mouse_motion.y );
-
- hilite_arrow=-1;
+ hilite_arrow = -1;
if (buttons_visible) {
Ref<Texture> incr = get_icon("increment");
Ref<Texture> decr = get_icon("decrement");
- int limit=get_size().width-incr->get_width()-decr->get_width();
+ int limit = get_size().width - incr->get_width() - decr->get_width();
- if (pos.x>limit+decr->get_width()) {
- hilite_arrow=1;
- } else if (pos.x>limit) {
- hilite_arrow=0;
+ if (pos.x > limit + decr->get_width()) {
+ hilite_arrow = 1;
+ } else if (pos.x > limit) {
+ hilite_arrow = 0;
}
}
// test hovering to display right or close button
- int hover_buttons=-1;
- hover=-1;
- for(int i=0;i<tabs.size();i++) {
+ int hover_buttons = -1;
+ hover = -1;
+ for (int i = 0; i < tabs.size(); i++) {
- if (i<offset)
+ if (i < offset)
continue;
if (tabs[i].rb_rect.has_point(pos)) {
- rb_hover=i;
- cb_hover=-1;
+ rb_hover = i;
+ cb_hover = -1;
hover_buttons = i;
break;
- }
- else if (!tabs[i].disabled && tabs[i].cb_rect.has_point(pos)) {
- cb_hover=i;
- rb_hover=-1;
+ } else if (!tabs[i].disabled && tabs[i].cb_rect.has_point(pos)) {
+ cb_hover = i;
+ rb_hover = -1;
hover_buttons = i;
break;
}
-
}
if (hover_buttons == -1) { // no hover
- rb_hover= hover_buttons;
- cb_hover= hover_buttons;
+ rb_hover = hover_buttons;
+ cb_hover = hover_buttons;
}
update();
return;
}
+ if (rb_pressing && p_event.type == InputEvent::MOUSE_BUTTON &&
+ !p_event.mouse_button.pressed &&
+ p_event.mouse_button.button_index == BUTTON_LEFT) {
- if (rb_pressing && p_event.type==InputEvent::MOUSE_BUTTON &&
- !p_event.mouse_button.pressed &&
- p_event.mouse_button.button_index==BUTTON_LEFT) {
-
- if (rb_hover!=-1) {
+ if (rb_hover != -1) {
//pressed
- emit_signal("right_button_pressed",rb_hover);
+ emit_signal("right_button_pressed", rb_hover);
}
- rb_pressing=false;
+ rb_pressing = false;
update();
}
+ if (cb_pressing && p_event.type == InputEvent::MOUSE_BUTTON &&
+ !p_event.mouse_button.pressed &&
+ p_event.mouse_button.button_index == BUTTON_LEFT) {
- if (cb_pressing && p_event.type==InputEvent::MOUSE_BUTTON &&
- !p_event.mouse_button.pressed &&
- p_event.mouse_button.button_index==BUTTON_LEFT) {
-
- if (cb_hover!=-1) {
+ if (cb_hover != -1) {
//pressed
- emit_signal("tab_close",cb_hover);
+ emit_signal("tab_close", cb_hover);
}
- cb_pressing=false;
+ cb_pressing = false;
update();
}
-
- if (p_event.type==InputEvent::MOUSE_BUTTON &&
- p_event.mouse_button.pressed &&
- p_event.mouse_button.button_index==BUTTON_LEFT) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON &&
+ p_event.mouse_button.pressed &&
+ p_event.mouse_button.button_index == BUTTON_LEFT) {
// clicks
- Point2 pos( p_event.mouse_button.x, p_event.mouse_button.y );
+ Point2 pos(p_event.mouse_button.x, p_event.mouse_button.y);
if (buttons_visible) {
Ref<Texture> incr = get_icon("increment");
Ref<Texture> decr = get_icon("decrement");
- int limit=get_size().width-incr->get_width()-decr->get_width();
+ int limit = get_size().width - incr->get_width() - decr->get_width();
- if (pos.x>limit+decr->get_width()) {
+ if (pos.x > limit + decr->get_width()) {
if (missing_right) {
offset++;
update();
}
return;
- } else if (pos.x>limit) {
- if (offset>0) {
+ } else if (pos.x > limit) {
+ if (offset > 0) {
offset--;
update();
}
@@ -190,25 +184,25 @@ void Tabs::_gui_input(const InputEvent& p_event) {
}
}
- int found=-1;
- for(int i=0;i<tabs.size();i++) {
+ int found = -1;
+ for (int i = 0; i < tabs.size(); i++) {
- if (i<offset)
+ if (i < offset)
continue;
if (tabs[i].rb_rect.has_point(pos)) {
- rb_pressing=true;
+ rb_pressing = true;
update();
return;
}
if (tabs[i].cb_rect.has_point(pos)) {
- cb_pressing=true;
+ cb_pressing = true;
update();
return;
}
- if (pos.x >=tabs[i].ofs_cache && pos.x<tabs[i].ofs_cache+tabs[i].size_cache) {
+ if (pos.x >= tabs[i].ofs_cache && pos.x < tabs[i].ofs_cache + tabs[i].size_cache) {
if (!tabs[i].disabled) {
found = i;
}
@@ -216,25 +210,22 @@ void Tabs::_gui_input(const InputEvent& p_event) {
}
}
-
- if (found!=-1) {
+ if (found != -1) {
set_current_tab(found);
- emit_signal("tab_changed",found);
+ emit_signal("tab_changed", found);
}
}
-
}
-
void Tabs::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_MOUSE_EXIT: {
- rb_hover=-1;
- cb_hover=-1;
- hover=-1;
+ rb_hover = -1;
+ cb_hover = -1;
+ hover = -1;
update();
} break;
case NOTIFICATION_RESIZED: {
@@ -252,27 +243,26 @@ void Tabs::_notification(int p_what) {
Color color_fg = get_color("font_color_fg");
Color color_bg = get_color("font_color_bg");
Color color_disabled = get_color("font_color_disabled");
- Ref<Texture> close=get_icon("close");
+ Ref<Texture> close = get_icon("close");
int h = get_size().height;
int w = 0;
int mw = 0;
- for(int i=0;i<tabs.size();i++) {
+ for (int i = 0; i < tabs.size(); i++) {
tabs[i].ofs_cache = mw;
mw += get_tab_width(i);
}
-
- if (tab_align==ALIGN_CENTER) {
- w=(get_size().width-mw)/2;
- } else if (tab_align==ALIGN_RIGHT) {
- w=get_size().width-mw;
+ if (tab_align == ALIGN_CENTER) {
+ w = (get_size().width - mw) / 2;
+ } else if (tab_align == ALIGN_RIGHT) {
+ w = get_size().width - mw;
}
- if (w<0) {
- w=0;
+ if (w < 0) {
+ w = 0;
}
Ref<Texture> incr = get_icon("increment");
@@ -280,31 +270,30 @@ void Tabs::_notification(int p_what) {
Ref<Texture> incr_hl = get_icon("increment_hilite");
Ref<Texture> decr_hl = get_icon("decrement_hilite");
- int limit=get_size().width - incr->get_size().width - decr->get_size().width;
+ int limit = get_size().width - incr->get_size().width - decr->get_size().width;
- missing_right=false;
+ missing_right = false;
- for(int i=0;i<tabs.size();i++) {
+ for (int i = 0; i < tabs.size(); i++) {
- if (i<offset)
+ if (i < offset)
continue;
- tabs[i].ofs_cache=w;
+ tabs[i].ofs_cache = w;
int lsize = get_tab_width(i);
String text = tabs[i].text;
int slen = font->get_string_size(text).width;
- if (w+lsize > limit) {
- max_drawn_tab=i-1;
- missing_right=true;
+ if (w + lsize > limit) {
+ max_drawn_tab = i - 1;
+ missing_right = true;
break;
} else {
- max_drawn_tab=i;
+ max_drawn_tab = i;
}
-
Ref<StyleBox> sb;
Color col;
@@ -312,105 +301,101 @@ void Tabs::_notification(int p_what) {
sb = tab_disabled;
col = color_disabled;
} else if (i == current) {
- sb=tab_fg;
- col=color_fg;
+ sb = tab_fg;
+ col = color_fg;
} else {
- sb=tab_bg;
- col=color_bg;
+ sb = tab_bg;
+ col = color_bg;
}
-
Rect2 sb_rect = Rect2(w, 0, lsize, h);
sb->draw(ci, sb_rect);
- w+=sb->get_margin(MARGIN_LEFT);
+ w += sb->get_margin(MARGIN_LEFT);
Size2i sb_ms = sb->get_minimum_size();
Ref<Texture> icon = tabs[i].icon;
if (icon.is_valid()) {
- icon->draw(ci, Point2i( w, sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-icon->get_height())/2 ) );
- if (text!="")
- w+=icon->get_width()+get_constant("hseparation");
-
+ icon->draw(ci, Point2i(w, sb->get_margin(MARGIN_TOP) + ((sb_rect.size.y - sb_ms.y) - icon->get_height()) / 2));
+ if (text != "")
+ w += icon->get_width() + get_constant("hseparation");
}
- font->draw(ci, Point2i( w, sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-font->get_height())/2+font->get_ascent() ), text, col );
+ font->draw(ci, Point2i(w, sb->get_margin(MARGIN_TOP) + ((sb_rect.size.y - sb_ms.y) - font->get_height()) / 2 + font->get_ascent()), text, col);
- w+=slen;
+ w += slen;
if (tabs[i].right_button.is_valid()) {
Ref<StyleBox> style = get_stylebox("button");
- Ref<Texture> rb=tabs[i].right_button;
+ Ref<Texture> rb = tabs[i].right_button;
- w+=get_constant("hseparation");
+ w += get_constant("hseparation");
Rect2 rb_rect;
- rb_rect.size=style->get_minimum_size()+rb->get_size();
- rb_rect.pos.x=w;
- rb_rect.pos.y=sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-(rb_rect.size.y))/2;
+ rb_rect.size = style->get_minimum_size() + rb->get_size();
+ rb_rect.pos.x = w;
+ rb_rect.pos.y = sb->get_margin(MARGIN_TOP) + ((sb_rect.size.y - sb_ms.y) - (rb_rect.size.y)) / 2;
- if (rb_hover==i) {
+ if (rb_hover == i) {
if (rb_pressing)
- get_stylebox("button_pressed")->draw(ci,rb_rect);
+ get_stylebox("button_pressed")->draw(ci, rb_rect);
else
- style->draw(ci,rb_rect);
+ style->draw(ci, rb_rect);
}
- rb->draw(ci,Point2i( w+style->get_margin(MARGIN_LEFT), rb_rect.pos.y+style->get_margin(MARGIN_TOP) ));
- w+=rb->get_width();
- tabs[i].rb_rect=rb_rect;
-
+ rb->draw(ci, Point2i(w + style->get_margin(MARGIN_LEFT), rb_rect.pos.y + style->get_margin(MARGIN_TOP)));
+ w += rb->get_width();
+ tabs[i].rb_rect = rb_rect;
}
- if (cb_displaypolicy==CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy==CLOSE_BUTTON_SHOW_ACTIVE_ONLY && i==current)) {
+ if (cb_displaypolicy == CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy == CLOSE_BUTTON_SHOW_ACTIVE_ONLY && i == current)) {
Ref<StyleBox> style = get_stylebox("button");
- Ref<Texture> cb=close;
+ Ref<Texture> cb = close;
- w+=get_constant("hseparation");
+ w += get_constant("hseparation");
Rect2 cb_rect;
- cb_rect.size=style->get_minimum_size()+cb->get_size();
- cb_rect.pos.x=w;
- cb_rect.pos.y=sb->get_margin(MARGIN_TOP)+((sb_rect.size.y-sb_ms.y)-(cb_rect.size.y))/2;
+ cb_rect.size = style->get_minimum_size() + cb->get_size();
+ cb_rect.pos.x = w;
+ cb_rect.pos.y = sb->get_margin(MARGIN_TOP) + ((sb_rect.size.y - sb_ms.y) - (cb_rect.size.y)) / 2;
if (!tabs[i].disabled && cb_hover == i) {
if (cb_pressing)
- get_stylebox("button_pressed")->draw(ci,cb_rect);
+ get_stylebox("button_pressed")->draw(ci, cb_rect);
else
- style->draw(ci,cb_rect);
+ style->draw(ci, cb_rect);
}
- cb->draw(ci,Point2i( w+style->get_margin(MARGIN_LEFT), cb_rect.pos.y+style->get_margin(MARGIN_TOP) ));
- w+=cb->get_width();
- tabs[i].cb_rect=cb_rect;
+ cb->draw(ci, Point2i(w + style->get_margin(MARGIN_LEFT), cb_rect.pos.y + style->get_margin(MARGIN_TOP)));
+ w += cb->get_width();
+ tabs[i].cb_rect = cb_rect;
}
- w+=sb->get_margin(MARGIN_RIGHT);
-
- tabs[i].size_cache=w-tabs[i].ofs_cache;
+ w += sb->get_margin(MARGIN_RIGHT);
+ tabs[i].size_cache = w - tabs[i].ofs_cache;
}
- if (offset>0 || missing_right) {
+ if (offset > 0 || missing_right) {
- int vofs = (get_size().height-incr->get_size().height)/2;
+ int vofs = (get_size().height - incr->get_size().height) / 2;
- if (offset>0)
- draw_texture(hilite_arrow==0 ? decr_hl : decr, Point2(limit,vofs));
+ if (offset > 0)
+ draw_texture(hilite_arrow == 0 ? decr_hl : decr, Point2(limit, vofs));
else
- draw_texture(decr,Point2(limit,vofs), Color(1,1,1,0.5));
+ draw_texture(decr, Point2(limit, vofs), Color(1, 1, 1, 0.5));
if (missing_right)
- draw_texture(hilite_arrow==1 ? incr_hl : incr, Point2(limit+decr->get_size().width,vofs));
+ draw_texture(hilite_arrow == 1 ? incr_hl : incr, Point2(limit + decr->get_size().width, vofs));
else
- draw_texture(incr,Point2(limit+decr->get_size().width,vofs), Color(1,1,1,0.5));
+ draw_texture(incr, Point2(limit + decr->get_size().width, vofs), Color(1, 1, 1, 0.5));
- buttons_visible=true;
+ buttons_visible = true;
} else {
- buttons_visible=false;
+ buttons_visible = false;
}
} break;
@@ -422,12 +407,11 @@ int Tabs::get_tab_count() const {
return tabs.size();
}
-
void Tabs::set_current_tab(int p_current) {
- ERR_FAIL_INDEX( p_current, get_tab_count() );
+ ERR_FAIL_INDEX(p_current, get_tab_count());
- current=p_current;
+ current = p_current;
_change_notify("current_tab");
update();
@@ -438,111 +422,98 @@ int Tabs::get_current_tab() const {
return current;
}
+void Tabs::set_tab_title(int p_tab, const String &p_title) {
-void Tabs::set_tab_title(int p_tab,const String& p_title) {
-
- ERR_FAIL_INDEX(p_tab,tabs.size());
- tabs[p_tab].text=p_title;
+ ERR_FAIL_INDEX(p_tab, tabs.size());
+ tabs[p_tab].text = p_title;
update();
minimum_size_changed();
-
}
-String Tabs::get_tab_title(int p_tab) const{
+String Tabs::get_tab_title(int p_tab) const {
- ERR_FAIL_INDEX_V(p_tab,tabs.size(),"");
+ ERR_FAIL_INDEX_V(p_tab, tabs.size(), "");
return tabs[p_tab].text;
-
}
+void Tabs::set_tab_icon(int p_tab, const Ref<Texture> &p_icon) {
-void Tabs::set_tab_icon(int p_tab,const Ref<Texture>& p_icon){
-
- ERR_FAIL_INDEX(p_tab,tabs.size());
- tabs[p_tab].icon=p_icon;
+ ERR_FAIL_INDEX(p_tab, tabs.size());
+ tabs[p_tab].icon = p_icon;
update();
minimum_size_changed();
-
}
-Ref<Texture> Tabs::get_tab_icon(int p_tab) const{
+Ref<Texture> Tabs::get_tab_icon(int p_tab) const {
- ERR_FAIL_INDEX_V(p_tab,tabs.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_tab, tabs.size(), Ref<Texture>());
return tabs[p_tab].icon;
-
}
-
void Tabs::set_tab_disabled(int p_tab, bool p_disabled) {
-
+
ERR_FAIL_INDEX(p_tab, tabs.size());
tabs[p_tab].disabled = p_disabled;
update();
}
bool Tabs::get_tab_disabled(int p_tab) const {
-
+
ERR_FAIL_INDEX_V(p_tab, tabs.size(), false);
return tabs[p_tab].disabled;
}
-void Tabs::set_tab_right_button(int p_tab,const Ref<Texture>& p_right_button){
+void Tabs::set_tab_right_button(int p_tab, const Ref<Texture> &p_right_button) {
- ERR_FAIL_INDEX(p_tab,tabs.size());
- tabs[p_tab].right_button=p_right_button;
+ ERR_FAIL_INDEX(p_tab, tabs.size());
+ tabs[p_tab].right_button = p_right_button;
update();
minimum_size_changed();
-
}
-Ref<Texture> Tabs::get_tab_right_button(int p_tab) const{
+Ref<Texture> Tabs::get_tab_right_button(int p_tab) const {
- ERR_FAIL_INDEX_V(p_tab,tabs.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_tab, tabs.size(), Ref<Texture>());
return tabs[p_tab].right_button;
-
}
-
-void Tabs::add_tab(const String& p_str,const Ref<Texture>& p_icon) {
+void Tabs::add_tab(const String &p_str, const Ref<Texture> &p_icon) {
Tab t;
- t.text=p_str;
- t.icon=p_icon;
+ t.text = p_str;
+ t.icon = p_icon;
t.disabled = false;
tabs.push_back(t);
update();
minimum_size_changed();
-
}
void Tabs::clear_tabs() {
tabs.clear();
- current=0;
+ current = 0;
update();
}
void Tabs::remove_tab(int p_idx) {
- ERR_FAIL_INDEX(p_idx,tabs.size());
+ ERR_FAIL_INDEX(p_idx, tabs.size());
tabs.remove(p_idx);
- if (current>=p_idx)
+ if (current >= p_idx)
current--;
update();
minimum_size_changed();
- if (current<0)
- current=0;
- if (current>=tabs.size())
- current=tabs.size()-1;
+ if (current < 0)
+ current = 0;
+ if (current >= tabs.size())
+ current = tabs.size() - 1;
_ensure_no_over_offset();
-
}
-
void Tabs::set_tab_align(TabAlign p_align) {
- tab_align=p_align;
+ tab_align = p_align;
update();
}
@@ -553,49 +524,46 @@ Tabs::TabAlign Tabs::get_tab_align() const {
int Tabs::get_tab_width(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,tabs.size(),0);
+ ERR_FAIL_INDEX_V(p_idx, tabs.size(), 0);
Ref<StyleBox> tab_bg = get_stylebox("tab_bg");
Ref<StyleBox> tab_fg = get_stylebox("tab_fg");
Ref<StyleBox> tab_disabled = get_stylebox("tab_disabled");
Ref<Font> font = get_font("font");
-
- int x=0;
+ int x = 0;
Ref<Texture> tex = tabs[p_idx].icon;
if (tex.is_valid()) {
- x+=tex->get_width();
- if (tabs[p_idx].text!="")
- x+=get_constant("hseparation");
-
+ x += tex->get_width();
+ if (tabs[p_idx].text != "")
+ x += get_constant("hseparation");
}
- x+=font->get_string_size(tabs[p_idx].text).width;
+ x += font->get_string_size(tabs[p_idx].text).width;
if (tabs[p_idx].disabled)
x += tab_disabled->get_minimum_size().width;
- else if (current==p_idx)
- x+=tab_fg->get_minimum_size().width;
+ else if (current == p_idx)
+ x += tab_fg->get_minimum_size().width;
else
- x+=tab_bg->get_minimum_size().width;
+ x += tab_bg->get_minimum_size().width;
if (tabs[p_idx].right_button.is_valid()) {
- Ref<Texture> rb=tabs[p_idx].right_button;
- x+=rb->get_width();
- x+=get_constant("hseparation");
+ Ref<Texture> rb = tabs[p_idx].right_button;
+ x += rb->get_width();
+ x += get_constant("hseparation");
}
- if (cb_displaypolicy==CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy==CLOSE_BUTTON_SHOW_ACTIVE_ONLY && p_idx==current)) {
- Ref<Texture> cb=get_icon("close");
- x+=cb->get_width();
- x+=get_constant("hseparation");
+ if (cb_displaypolicy == CLOSE_BUTTON_SHOW_ALWAYS || (cb_displaypolicy == CLOSE_BUTTON_SHOW_ACTIVE_ONLY && p_idx == current)) {
+ Ref<Texture> cb = get_icon("close");
+ x += cb->get_width();
+ x += get_constant("hseparation");
}
return x;
}
-
void Tabs::_ensure_no_over_offset() {
if (!is_inside_tree())
@@ -604,17 +572,17 @@ void Tabs::_ensure_no_over_offset() {
Ref<Texture> incr = get_icon("increment");
Ref<Texture> decr = get_icon("decrement");
- int limit=get_size().width-incr->get_width()-decr->get_width();
+ int limit = get_size().width - incr->get_width() - decr->get_width();
- while(offset>0) {
+ while (offset > 0) {
- int total_w=0;
- for(int i=0;i<tabs.size();i++) {
+ int total_w = 0;
+ for (int i = 0; i < tabs.size(); i++) {
- if (i<offset-1)
+ if (i < offset - 1)
continue;
- total_w+=get_tab_width(i);
+ total_w += get_tab_width(i);
}
if (total_w < limit) {
@@ -624,44 +592,40 @@ void Tabs::_ensure_no_over_offset() {
break;
}
}
-
}
-
void Tabs::ensure_tab_visible(int p_idx) {
if (!is_inside_tree())
return;
- ERR_FAIL_INDEX(p_idx,tabs.size());
+ ERR_FAIL_INDEX(p_idx, tabs.size());
_ensure_no_over_offset();
- if (p_idx<=offset) {
- offset=p_idx;
+ if (p_idx <= offset) {
+ offset = p_idx;
update();
return;
}
Ref<Texture> incr = get_icon("increment");
Ref<Texture> decr = get_icon("decrement");
- int limit=get_size().width-incr->get_width()-decr->get_width();
+ int limit = get_size().width - incr->get_width() - decr->get_width();
+ int x = 0;
+ for (int i = 0; i < tabs.size(); i++) {
- int x=0;
- for(int i=0;i<tabs.size();i++) {
-
- if (i<offset)
+ if (i < offset)
continue;
int sz = get_tab_width(i);
- tabs[i].x_cache=x;
- tabs[i].x_size_cache=sz;
- x+=sz;
-
+ tabs[i].x_cache = x;
+ tabs[i].x_size_cache = sz;
+ x += sz;
}
- while(offset<tabs.size() && ( (tabs[p_idx].x_cache + tabs[p_idx].x_size_cache) - tabs[offset].x_cache) > limit) {
+ while (offset < tabs.size() && ((tabs[p_idx].x_cache + tabs[p_idx].x_size_cache) - tabs[offset].x_cache) > limit) {
offset++;
}
@@ -669,57 +633,54 @@ void Tabs::ensure_tab_visible(int p_idx) {
}
void Tabs::set_tab_close_display_policy(CloseButtonDisplayPolicy p_policy) {
- cb_displaypolicy=p_policy;
+ cb_displaypolicy = p_policy;
update();
}
void Tabs::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_gui_input"),&Tabs::_gui_input);
- ClassDB::bind_method(D_METHOD("get_tab_count"),&Tabs::get_tab_count);
- ClassDB::bind_method(D_METHOD("set_current_tab","tab_idx"),&Tabs::set_current_tab);
- ClassDB::bind_method(D_METHOD("get_current_tab"),&Tabs::get_current_tab);
- ClassDB::bind_method(D_METHOD("set_tab_title","tab_idx","title"),&Tabs::set_tab_title);
- ClassDB::bind_method(D_METHOD("get_tab_title","tab_idx"),&Tabs::get_tab_title);
- ClassDB::bind_method(D_METHOD("set_tab_icon","tab_idx","icon:Texture"),&Tabs::set_tab_icon);
- ClassDB::bind_method(D_METHOD("get_tab_icon:Texture","tab_idx"),&Tabs::get_tab_icon);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &Tabs::_gui_input);
+ ClassDB::bind_method(D_METHOD("get_tab_count"), &Tabs::get_tab_count);
+ ClassDB::bind_method(D_METHOD("set_current_tab", "tab_idx"), &Tabs::set_current_tab);
+ ClassDB::bind_method(D_METHOD("get_current_tab"), &Tabs::get_current_tab);
+ ClassDB::bind_method(D_METHOD("set_tab_title", "tab_idx", "title"), &Tabs::set_tab_title);
+ ClassDB::bind_method(D_METHOD("get_tab_title", "tab_idx"), &Tabs::get_tab_title);
+ ClassDB::bind_method(D_METHOD("set_tab_icon", "tab_idx", "icon:Texture"), &Tabs::set_tab_icon);
+ ClassDB::bind_method(D_METHOD("get_tab_icon:Texture", "tab_idx"), &Tabs::get_tab_icon);
ClassDB::bind_method(D_METHOD("set_tab_disabled", "tab_idx", "disabled"), &Tabs::set_tab_disabled);
ClassDB::bind_method(D_METHOD("get_tab_disabled", "tab_idx"), &Tabs::get_tab_disabled);
- ClassDB::bind_method(D_METHOD("remove_tab","tab_idx"),&Tabs::remove_tab);
- ClassDB::bind_method(D_METHOD("add_tab","title","icon:Texture"),&Tabs::add_tab);
- ClassDB::bind_method(D_METHOD("set_tab_align","align"),&Tabs::set_tab_align);
- ClassDB::bind_method(D_METHOD("get_tab_align"),&Tabs::get_tab_align);
- ClassDB::bind_method(D_METHOD("ensure_tab_visible","idx"),&Tabs::ensure_tab_visible);
-
- ADD_SIGNAL(MethodInfo("tab_changed",PropertyInfo(Variant::INT,"tab")));
- ADD_SIGNAL(MethodInfo("right_button_pressed",PropertyInfo(Variant::INT,"tab")));
- ADD_SIGNAL(MethodInfo("tab_close",PropertyInfo(Variant::INT,"tab")));
+ ClassDB::bind_method(D_METHOD("remove_tab", "tab_idx"), &Tabs::remove_tab);
+ ClassDB::bind_method(D_METHOD("add_tab", "title", "icon:Texture"), &Tabs::add_tab);
+ ClassDB::bind_method(D_METHOD("set_tab_align", "align"), &Tabs::set_tab_align);
+ ClassDB::bind_method(D_METHOD("get_tab_align"), &Tabs::get_tab_align);
+ ClassDB::bind_method(D_METHOD("ensure_tab_visible", "idx"), &Tabs::ensure_tab_visible);
- ADD_PROPERTY( PropertyInfo(Variant::INT, "current_tab", PROPERTY_HINT_RANGE,"-1,4096,1",PROPERTY_USAGE_EDITOR), "set_current_tab", "get_current_tab") ;
+ ADD_SIGNAL(MethodInfo("tab_changed", PropertyInfo(Variant::INT, "tab")));
+ ADD_SIGNAL(MethodInfo("right_button_pressed", PropertyInfo(Variant::INT, "tab")));
+ ADD_SIGNAL(MethodInfo("tab_close", PropertyInfo(Variant::INT, "tab")));
- BIND_CONSTANT( ALIGN_LEFT );
- BIND_CONSTANT( ALIGN_CENTER );
- BIND_CONSTANT( ALIGN_RIGHT );
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "current_tab", PROPERTY_HINT_RANGE, "-1,4096,1", PROPERTY_USAGE_EDITOR), "set_current_tab", "get_current_tab");
- BIND_CONSTANT( CLOSE_BUTTON_SHOW_ACTIVE_ONLY );
- BIND_CONSTANT( CLOSE_BUTTON_SHOW_ALWAYS );
- BIND_CONSTANT( CLOSE_BUTTON_SHOW_NEVER );
+ BIND_CONSTANT(ALIGN_LEFT);
+ BIND_CONSTANT(ALIGN_CENTER);
+ BIND_CONSTANT(ALIGN_RIGHT);
+ BIND_CONSTANT(CLOSE_BUTTON_SHOW_ACTIVE_ONLY);
+ BIND_CONSTANT(CLOSE_BUTTON_SHOW_ALWAYS);
+ BIND_CONSTANT(CLOSE_BUTTON_SHOW_NEVER);
}
-
Tabs::Tabs() {
- current=0;
- tab_align=ALIGN_CENTER;
- rb_hover=-1;
- rb_pressing=false;
- hilite_arrow=-1;
+ current = 0;
+ tab_align = ALIGN_CENTER;
+ rb_hover = -1;
+ rb_pressing = false;
+ hilite_arrow = -1;
- cb_hover=-1;
- cb_pressing=false;
+ cb_hover = -1;
+ cb_pressing = false;
cb_displaypolicy = CLOSE_BUTTON_SHOW_NEVER;
- offset=0;
- max_drawn_tab=0;
-
+ offset = 0;
+ max_drawn_tab = 0;
}
diff --git a/scene/gui/tabs.h b/scene/gui/tabs.h
index 83dcce2613..39811f13c2 100644
--- a/scene/gui/tabs.h
+++ b/scene/gui/tabs.h
@@ -33,9 +33,9 @@
class Tabs : public Control {
- GDCLASS( Tabs, Control );
-public:
+ GDCLASS(Tabs, Control);
+public:
enum TabAlign {
ALIGN_LEFT,
@@ -49,9 +49,8 @@ public:
CLOSE_BUTTON_SHOW_ACTIVE_ONLY,
CLOSE_BUTTON_SHOW_ALWAYS,
};
-private:
-
+private:
struct Tab {
String text;
@@ -65,10 +64,8 @@ private:
Ref<Texture> right_button;
Rect2 rb_rect;
Rect2 cb_rect;
-
};
-
int offset;
int max_drawn_tab;
int hilite_arrow;
@@ -86,31 +83,29 @@ private:
bool cb_pressing;
CloseButtonDisplayPolicy cb_displaypolicy;
- int hover; // hovered tab
+ int hover; // hovered tab
int get_tab_width(int p_idx) const;
void _ensure_no_over_offset();
protected:
-
- void _gui_input(const InputEvent& p_event);
+ void _gui_input(const InputEvent &p_event);
void _notification(int p_what);
static void _bind_methods();
public:
+ void add_tab(const String &p_str = "", const Ref<Texture> &p_icon = Ref<Texture>());
- void add_tab(const String& p_str="",const Ref<Texture>& p_icon=Ref<Texture>());
-
- void set_tab_title(int p_tab,const String& p_title);
+ void set_tab_title(int p_tab, const String &p_title);
String get_tab_title(int p_tab) const;
- void set_tab_icon(int p_tab,const Ref<Texture>& p_icon);
+ void set_tab_icon(int p_tab, const Ref<Texture> &p_icon);
Ref<Texture> get_tab_icon(int p_tab) const;
-
+
void set_tab_disabled(int p_tab, bool p_disabled);
bool get_tab_disabled(int p_tab) const;
- void set_tab_right_button(int p_tab,const Ref<Texture>& p_right_button);
+ void set_tab_right_button(int p_tab, const Ref<Texture> &p_right_button);
Ref<Texture> get_tab_right_button(int p_tab) const;
void set_tab_align(TabAlign p_align);
diff --git a/scene/gui/text_edit.cpp b/scene/gui/text_edit.cpp
index f1b061c506..3b7ad910d6 100644
--- a/scene/gui/text_edit.cpp
+++ b/scene/gui/text_edit.cpp
@@ -28,8 +28,8 @@
/*************************************************************************/
#include "text_edit.h"
-#include "os/keyboard.h"
#include "os/input.h"
+#include "os/keyboard.h"
#include "os/os.h"
#include "global_config.h"
@@ -40,17 +40,17 @@
static bool _is_text_char(CharType c) {
- return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_';
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
static bool _is_symbol(CharType c) {
- return c!='_' && ((c>='!' && c<='/') || (c>=':' && c<='@') || (c>='[' && c<='`') || (c>='{' && c<='~') || c=='\t' || c==' ');
+ return c != '_' && ((c >= '!' && c <= '/') || (c >= ':' && c <= '@') || (c >= '[' && c <= '`') || (c >= '{' && c <= '~') || c == '\t' || c == ' ');
}
static bool _is_char(CharType c) {
- return (c>='a' && c<='z') || (c>='A' && c<='Z') || c=='_';
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static bool _is_number(CharType c) {
@@ -62,21 +62,19 @@ static bool _is_hex_symbol(CharType c) {
}
static bool _is_pair_right_symbol(CharType c) {
- return
- c == '"' ||
- c == '\'' ||
- c == ')' ||
- c == ']' ||
- c == '}';
+ return c == '"' ||
+ c == '\'' ||
+ c == ')' ||
+ c == ']' ||
+ c == '}';
}
static bool _is_pair_left_symbol(CharType c) {
- return
- c == '"' ||
- c == '\'' ||
- c == '(' ||
- c == '[' ||
- c == '{';
+ return c == '"' ||
+ c == '\'' ||
+ c == '(' ||
+ c == '[' ||
+ c == '{';
}
static bool _is_pair_symbol(CharType c) {
@@ -84,89 +82,88 @@ static bool _is_pair_symbol(CharType c) {
}
static CharType _get_right_pair_symbol(CharType c) {
- if(c == '"')
+ if (c == '"')
return '"';
- if(c == '\'')
+ if (c == '\'')
return '\'';
- if(c == '(')
+ if (c == '(')
return ')';
- if(c == '[')
+ if (c == '[')
return ']';
- if(c == '{')
+ if (c == '{')
return '}';
return 0;
}
-void TextEdit::Text::set_font(const Ref<Font>& p_font) {
+void TextEdit::Text::set_font(const Ref<Font> &p_font) {
- font=p_font;
+ font = p_font;
}
void TextEdit::Text::set_tab_size(int p_tab_size) {
- tab_size=p_tab_size;
+ tab_size = p_tab_size;
}
void TextEdit::Text::_update_line_cache(int p_line) const {
int w = 0;
- int tab_w=font->get_char_size(' ').width*tab_size;
+ int tab_w = font->get_char_size(' ').width * tab_size;
int len = text[p_line].data.length();
const CharType *str = text[p_line].data.c_str();
//update width
- for(int i=0;i<len;i++) {
- if (str[i]=='\t') {
+ for (int i = 0; i < len; i++) {
+ if (str[i] == '\t') {
- int left = w%tab_w;
- if (left==0)
- w+=tab_w;
+ int left = w % tab_w;
+ if (left == 0)
+ w += tab_w;
else
- w+=tab_w-w%tab_w; // is right...
+ w += tab_w - w % tab_w; // is right...
} else {
- w+=font->get_char_size(str[i],str[i+1]).width;
+ w += font->get_char_size(str[i], str[i + 1]).width;
}
}
-
- text[p_line].width_cache=w;
+ text[p_line].width_cache = w;
//update regions
text[p_line].region_info.clear();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
if (!_is_symbol(str[i]))
continue;
- if (str[i]=='\\') {
+ if (str[i] == '\\') {
i++; //skip quoted anything
continue;
}
- int left=len-i;
+ int left = len - i;
- for(int j=0;j<color_regions->size();j++) {
+ for (int j = 0; j < color_regions->size(); j++) {
- const ColorRegion& cr=color_regions->operator [](j);
+ const ColorRegion &cr = color_regions->operator[](j);
/* BEGIN */
- int lr=cr.begin_key.length();
- if (lr==0 || lr>left)
+ int lr = cr.begin_key.length();
+ if (lr == 0 || lr > left)
continue;
- const CharType* kc = cr.begin_key.c_str();
+ const CharType *kc = cr.begin_key.c_str();
- bool match=true;
+ bool match = true;
- for(int k=0;k<lr;k++) {
- if (kc[k]!=str[i+k]) {
- match=false;
+ for (int k = 0; k < lr; k++) {
+ if (kc[k] != str[i + k]) {
+ match = false;
break;
}
}
@@ -174,26 +171,26 @@ void TextEdit::Text::_update_line_cache(int p_line) const {
if (match) {
ColorRegionInfo cri;
- cri.end=false;
- cri.region=j;
- text[p_line].region_info[i]=cri;
- i+=lr-1;
+ cri.end = false;
+ cri.region = j;
+ text[p_line].region_info[i] = cri;
+ i += lr - 1;
break;
}
/* END */
- lr=cr.end_key.length();
- if (lr==0 || lr>left)
+ lr = cr.end_key.length();
+ if (lr == 0 || lr > left)
continue;
kc = cr.end_key.c_str();
- match=true;
+ match = true;
- for(int k=0;k<lr;k++) {
- if (kc[k]!=str[i+k]) {
- match=false;
+ for (int k = 0; k < lr; k++) {
+ if (kc[k] != str[i + k]) {
+ match = false;
break;
}
}
@@ -201,25 +198,22 @@ void TextEdit::Text::_update_line_cache(int p_line) const {
if (match) {
ColorRegionInfo cri;
- cri.end=true;
- cri.region=j;
- text[p_line].region_info[i]=cri;
- i+=lr-1;
+ cri.end = true;
+ cri.region = j;
+ text[p_line].region_info[i] = cri;
+ i += lr - 1;
break;
}
-
}
}
-
-
}
-const Map<int,TextEdit::Text::ColorRegionInfo>& TextEdit::Text::get_color_region_info(int p_line) {
+const Map<int, TextEdit::Text::ColorRegionInfo> &TextEdit::Text::get_color_region_info(int p_line) {
- Map<int,ColorRegionInfo> *cri=NULL;
- ERR_FAIL_INDEX_V(p_line,text.size(),*cri); //enjoy your crash
+ Map<int, ColorRegionInfo> *cri = NULL;
+ ERR_FAIL_INDEX_V(p_line, text.size(), *cri); //enjoy your crash
- if (text[p_line].width_cache==-1) {
+ if (text[p_line].width_cache == -1) {
_update_line_cache(p_line);
}
@@ -228,9 +222,9 @@ const Map<int,TextEdit::Text::ColorRegionInfo>& TextEdit::Text::get_color_region
int TextEdit::Text::get_line_width(int p_line) const {
- ERR_FAIL_INDEX_V(p_line,text.size(),-1);
+ ERR_FAIL_INDEX_V(p_line, text.size(), -1);
- if (text[p_line].width_cache==-1) {
+ if (text[p_line].width_cache == -1) {
_update_line_cache(p_line);
}
@@ -239,16 +233,14 @@ int TextEdit::Text::get_line_width(int p_line) const {
void TextEdit::Text::clear_caches() {
- for(int i=0;i<text.size();i++)
- text[i].width_cache=-1;
-
+ for (int i = 0; i < text.size(); i++)
+ text[i].width_cache = -1;
}
void TextEdit::Text::clear() {
-
text.clear();
- insert(0,"");
+ insert(0, "");
}
int TextEdit::Text::get_max_width() const {
@@ -256,29 +248,27 @@ int TextEdit::Text::get_max_width() const {
int max = 0;
- for(int i=0;i<text.size();i++)
- max=MAX(max,get_line_width(i));
+ for (int i = 0; i < text.size(); i++)
+ max = MAX(max, get_line_width(i));
return max;
-
}
-void TextEdit::Text::set(int p_line,const String& p_text) {
+void TextEdit::Text::set(int p_line, const String &p_text) {
- ERR_FAIL_INDEX(p_line,text.size());
+ ERR_FAIL_INDEX(p_line, text.size());
- text[p_line].width_cache=-1;
- text[p_line].data=p_text;
+ text[p_line].width_cache = -1;
+ text[p_line].data = p_text;
}
-
-void TextEdit::Text::insert(int p_at,const String& p_text) {
+void TextEdit::Text::insert(int p_at, const String &p_text) {
Line line;
- line.marked=false;
- line.breakpoint=false;
- line.width_cache=-1;
- line.data=p_text;
- text.insert(p_at,line);
+ line.marked = false;
+ line.breakpoint = false;
+ line.width_cache = -1;
+ line.data = p_text;
+ text.insert(p_at, line);
}
void TextEdit::Text::remove(int p_at) {
@@ -287,21 +277,17 @@ void TextEdit::Text::remove(int p_at) {
void TextEdit::_update_scrollbars() {
-
Size2 size = get_size();
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
+ v_scroll->set_begin(Point2(size.width - vmin.width, cache.style_normal->get_margin(MARGIN_TOP)));
+ v_scroll->set_end(Point2(size.width, size.height - cache.style_normal->get_margin(MARGIN_TOP) - cache.style_normal->get_margin(MARGIN_BOTTOM)));
+ h_scroll->set_begin(Point2(0, size.height - hmin.height));
+ h_scroll->set_end(Point2(size.width - vmin.width, size.height));
- v_scroll->set_begin( Point2(size.width - vmin.width, cache.style_normal->get_margin(MARGIN_TOP)) );
- v_scroll->set_end( Point2(size.width, size.height - cache.style_normal->get_margin(MARGIN_TOP) - cache.style_normal->get_margin(MARGIN_BOTTOM)) );
-
- h_scroll->set_begin( Point2( 0, size.height - hmin.height) );
- h_scroll->set_end( Point2(size.width-vmin.width, size.height) );
-
-
- int hscroll_rows = ((hmin.height-1)/get_row_height())+1;
+ int hscroll_rows = ((hmin.height - 1) / get_row_height()) + 1;
int visible_rows = get_visible_rows();
int total_rows = text.size();
if (scroll_past_end_of_file_enabled) {
@@ -319,28 +305,28 @@ void TextEdit::_update_scrollbars() {
total_width += cache.breakpoint_gutter_width;
}
- bool use_hscroll=true;
- bool use_vscroll=true;
+ bool use_hscroll = true;
+ bool use_vscroll = true;
if (total_rows <= visible_rows && total_width <= visible_width) {
//thanks yessopie for this clever bit of logic
- use_hscroll=false;
- use_vscroll=false;
+ use_hscroll = false;
+ use_vscroll = false;
} else {
if (total_rows > visible_rows && total_width <= visible_width - vscroll_pixels) {
//thanks yessopie for this clever bit of logic
- use_hscroll=false;
+ use_hscroll = false;
}
if (total_rows <= visible_rows - hscroll_rows && total_width > visible_width) {
//thanks yessopie for this clever bit of logic
- use_vscroll=false;
+ use_vscroll = false;
}
}
- updating_scrolls=true;
+ updating_scrolls = true;
if (use_vscroll) {
@@ -349,7 +335,7 @@ void TextEdit::_update_scrollbars() {
v_scroll->set_page(visible_rows);
v_scroll->set_value(cursor.line_ofs);
- } else {
+ } else {
cursor.line_ofs = 0;
v_scroll->hide();
}
@@ -366,24 +352,22 @@ void TextEdit::_update_scrollbars() {
h_scroll->hide();
}
-
-
- updating_scrolls=false;
+ updating_scrolls = false;
}
void TextEdit::_click_selection_held() {
- if (Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT) && selection.selecting_mode!=Selection::MODE_NONE) {
+ if (Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT) && selection.selecting_mode != Selection::MODE_NONE) {
- Point2 mp = Input::get_singleton()->get_mouse_pos()-get_global_pos();
+ Point2 mp = Input::get_singleton()->get_mouse_pos() - get_global_pos();
- int row,col;
- _get_mouse_pos(Point2i(mp.x,mp.y), row,col);
+ int row, col;
+ _get_mouse_pos(Point2i(mp.x, mp.y), row, col);
- select(selection.selecting_line,selection.selecting_column,row,col);
+ select(selection.selecting_line, selection.selecting_column, row, col);
- cursor_set_line( row );
- cursor_set_column( col );
+ cursor_set_line(row);
+ cursor_set_column(col);
update();
click_select_held->start();
@@ -394,25 +378,23 @@ void TextEdit::_click_selection_held() {
}
}
-
void TextEdit::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
_update_caches();
if (cursor_changed_dirty)
- MessageQueue::get_singleton()->push_call(this,"_cursor_changed_emit");
+ MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit");
if (text_changed_dirty)
- MessageQueue::get_singleton()->push_call(this,"_text_changed_emit");
+ MessageQueue::get_singleton()->push_call(this, "_text_changed_emit");
} break;
case NOTIFICATION_RESIZED: {
- cache.size=get_size();
+ cache.size = get_size();
adjust_viewport_to_cursor();
-
} break;
case NOTIFICATION_THEME_CHANGED: {
@@ -441,136 +423,130 @@ void TextEdit::_notification(int p_what) {
cache.breakpoint_gutter_width = 0;
}
- int line_number_char_count=0;
+ int line_number_char_count = 0;
{
- int lc=text.size()+1;
- cache.line_number_w=0;
- while(lc) {
- cache.line_number_w+=1;
- lc/=10;
+ int lc = text.size() + 1;
+ cache.line_number_w = 0;
+ while (lc) {
+ cache.line_number_w += 1;
+ lc /= 10;
};
if (line_numbers) {
- line_number_char_count=cache.line_number_w;
- cache.line_number_w=(cache.line_number_w+1)*cache.font->get_char_size('0').width;
+ line_number_char_count = cache.line_number_w;
+ cache.line_number_w = (cache.line_number_w + 1) * cache.font->get_char_size('0').width;
} else {
- cache.line_number_w=0;
+ cache.line_number_w = 0;
}
-
-
}
_update_scrollbars();
-
RID ci = get_canvas_item();
- int xmargin_beg=cache.style_normal->get_margin(MARGIN_LEFT)+cache.line_number_w+cache.breakpoint_gutter_width;
- int xmargin_end=cache.size.width-cache.style_normal->get_margin(MARGIN_RIGHT);
+ int xmargin_beg = cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width;
+ int xmargin_end = cache.size.width - cache.style_normal->get_margin(MARGIN_RIGHT);
//let's do it easy for now:
- cache.style_normal->draw(ci,Rect2(Point2(),cache.size));
+ cache.style_normal->draw(ci, Rect2(Point2(), cache.size));
if (has_focus())
- cache.style_focus->draw(ci,Rect2(Point2(),cache.size));
+ cache.style_focus->draw(ci, Rect2(Point2(), cache.size));
-
- int ascent=cache.font->get_ascent();
+ int ascent = cache.font->get_ascent();
int visible_rows = get_visible_rows();
- int tab_w = cache.font->get_char_size(' ').width*tab_size;
+ int tab_w = cache.font->get_char_size(' ').width * tab_size;
Color color = cache.font_color;
- int in_region=-1;
+ int in_region = -1;
if (syntax_coloring) {
- if (cache.background_color.a>0.01) {
+ if (cache.background_color.a > 0.01) {
- Point2i ofs = Point2i(cache.style_normal->get_offset())/2.0;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(ofs, get_size()-cache.style_normal->get_minimum_size()+ofs),cache.background_color);
+ Point2i ofs = Point2i(cache.style_normal->get_offset()) / 2.0;
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(ofs, get_size() - cache.style_normal->get_minimum_size() + ofs), cache.background_color);
}
//compute actual region to start (may be inside say, a comment).
//slow in very large documments :( but ok for source!
- for(int i=0;i<cursor.line_ofs;i++) {
+ for (int i = 0; i < cursor.line_ofs; i++) {
- const Map<int,Text::ColorRegionInfo>& cri_map=text.get_color_region_info(i);
+ const Map<int, Text::ColorRegionInfo> &cri_map = text.get_color_region_info(i);
- if (in_region>=0 && color_regions[in_region].line_only) {
- in_region=-1; //reset regions that end at end of line
+ if (in_region >= 0 && color_regions[in_region].line_only) {
+ in_region = -1; //reset regions that end at end of line
}
- for( const Map<int,Text::ColorRegionInfo>::Element* E= cri_map.front();E;E=E->next() ) {
+ for (const Map<int, Text::ColorRegionInfo>::Element *E = cri_map.front(); E; E = E->next()) {
- const Text::ColorRegionInfo &cri=E->get();
+ const Text::ColorRegionInfo &cri = E->get();
- if (in_region==-1) {
+ if (in_region == -1) {
if (!cri.end) {
- in_region=cri.region;
+ in_region = cri.region;
}
- } else if (in_region==cri.region && !color_regions[cri.region].line_only) { //ignore otherwise
+ } else if (in_region == cri.region && !color_regions[cri.region].line_only) { //ignore otherwise
if (cri.end || color_regions[cri.region].eq) {
- in_region=-1;
+ in_region = -1;
}
}
}
}
}
- int brace_open_match_line=-1;
- int brace_open_match_column=-1;
- bool brace_open_matching=false;
- bool brace_open_mismatch=false;
- int brace_close_match_line=-1;
- int brace_close_match_column=-1;
- bool brace_close_matching=false;
- bool brace_close_mismatch=false;
-
+ int brace_open_match_line = -1;
+ int brace_open_match_column = -1;
+ bool brace_open_matching = false;
+ bool brace_open_mismatch = false;
+ int brace_close_match_line = -1;
+ int brace_close_match_column = -1;
+ bool brace_close_matching = false;
+ bool brace_close_mismatch = false;
if (brace_matching_enabled) {
- if (cursor.column<text[cursor.line].length()) {
+ if (cursor.column < text[cursor.line].length()) {
//check for open
CharType c = text[cursor.line][cursor.column];
- CharType closec=0;
-
- if (c=='[') {
- closec=']';
- } else if (c=='{') {
- closec='}';
- } else if (c=='(') {
- closec=')';
+ CharType closec = 0;
+
+ if (c == '[') {
+ closec = ']';
+ } else if (c == '{') {
+ closec = '}';
+ } else if (c == '(') {
+ closec = ')';
}
- if (closec!=0) {
+ if (closec != 0) {
- int stack=1;
+ int stack = 1;
+ for (int i = cursor.line; i < text.size(); i++) {
- for(int i=cursor.line;i<text.size();i++) {
-
- int from = i==cursor.line?cursor.column+1:0;
- for(int j=from;j<text[i].length();j++) {
+ int from = i == cursor.line ? cursor.column + 1 : 0;
+ for (int j = from; j < text[i].length(); j++) {
CharType cc = text[i][j];
//ignore any brackets inside a string
- if (cc== '"' || cc == '\'') {
+ if (cc == '"' || cc == '\'') {
CharType quotation = cc;
do {
j++;
- if (!(j<text[i].length())) {
+ if (!(j < text[i].length())) {
break;
}
- cc=text[i][j];
+ cc = text[i][j];
//skip over escaped quotation marks inside strings
- if (cc=='\\') {
+ if (cc == '\\') {
bool escaped = true;
- while (j+1<text[i].length() && text[i][j+1]=='\\') {
- escaped=!escaped;
+ while (j + 1 < text[i].length() && text[i][j + 1] == '\\') {
+ escaped = !escaped;
j++;
}
if (escaped) {
@@ -578,108 +554,98 @@ void TextEdit::_notification(int p_what) {
continue;
}
}
- } while (cc!= quotation);
- } else if (cc==c)
+ } while (cc != quotation);
+ } else if (cc == c)
stack++;
- else if (cc==closec)
+ else if (cc == closec)
stack--;
- if (stack==0) {
- brace_open_match_line=i;
- brace_open_match_column=j;
- brace_open_matching=true;
+ if (stack == 0) {
+ brace_open_match_line = i;
+ brace_open_match_column = j;
+ brace_open_matching = true;
break;
}
}
- if (brace_open_match_line!=-1)
+ if (brace_open_match_line != -1)
break;
}
if (!brace_open_matching)
- brace_open_mismatch=true;
-
-
+ brace_open_mismatch = true;
}
}
- if (cursor.column>0) {
- CharType c = text[cursor.line][cursor.column-1];
- CharType closec=0;
-
-
+ if (cursor.column > 0) {
+ CharType c = text[cursor.line][cursor.column - 1];
+ CharType closec = 0;
- if (c==']') {
- closec='[';
- } else if (c=='}') {
- closec='{';
- } else if (c==')') {
- closec='(';
+ if (c == ']') {
+ closec = '[';
+ } else if (c == '}') {
+ closec = '{';
+ } else if (c == ')') {
+ closec = '(';
}
- if (closec!=0) {
+ if (closec != 0) {
- int stack=1;
+ int stack = 1;
+ for (int i = cursor.line; i >= 0; i--) {
- for(int i=cursor.line;i>=0;i--) {
-
- int from = i==cursor.line?cursor.column-2:text[i].length()-1;
- for(int j=from;j>=0;j--) {
+ int from = i == cursor.line ? cursor.column - 2 : text[i].length() - 1;
+ for (int j = from; j >= 0; j--) {
CharType cc = text[i][j];
//ignore any brackets inside a string
- if (cc== '"' || cc == '\'') {
+ if (cc == '"' || cc == '\'') {
CharType quotation = cc;
do {
j--;
- if (!(j>=0)) {
+ if (!(j >= 0)) {
break;
}
- cc=text[i][j];
+ cc = text[i][j];
//skip over escaped quotation marks inside strings
- if (cc==quotation) {
+ if (cc == quotation) {
bool escaped = false;
- while (j-1>=0 && text[i][j-1]=='\\') {
- escaped=!escaped;
+ while (j - 1 >= 0 && text[i][j - 1] == '\\') {
+ escaped = !escaped;
j--;
}
if (escaped) {
j--;
- cc='\\';
+ cc = '\\';
continue;
}
}
- } while (cc!= quotation);
- } else if (cc==c)
+ } while (cc != quotation);
+ } else if (cc == c)
stack++;
- else if (cc==closec)
+ else if (cc == closec)
stack--;
- if (stack==0) {
- brace_close_match_line=i;
- brace_close_match_column=j;
- brace_close_matching=true;
+ if (stack == 0) {
+ brace_close_match_line = i;
+ brace_close_match_column = j;
+ brace_close_matching = true;
break;
}
}
- if (brace_close_match_line!=-1)
+ if (brace_close_match_line != -1)
break;
}
if (!brace_close_matching)
- brace_close_mismatch=true;
-
-
+ brace_close_mismatch = true;
}
-
-
}
}
-
- int deregion=0; //force it to clear inrgion
+ int deregion = 0; //force it to clear inrgion
Point2 cursor_pos;
// get the highlighted words
@@ -687,22 +653,22 @@ void TextEdit::_notification(int p_what) {
String line_num_padding = line_numbers_zero_padded ? "0" : " ";
- for (int i=0;i<visible_rows;i++) {
+ for (int i = 0; i < visible_rows; i++) {
- int line=i+cursor.line_ofs;
+ int line = i + cursor.line_ofs;
- if (line<0 || line>=(int)text.size())
+ if (line < 0 || line >= (int)text.size())
continue;
- const String &str=text[line];
+ const String &str = text[line];
- int char_margin=xmargin_beg-cursor.x_ofs;
- int char_ofs=0;
- int ofs_y=i*get_row_height()+cache.line_spacing/2;
- bool prev_is_char=false;
+ int char_margin = xmargin_beg - cursor.x_ofs;
+ int char_ofs = 0;
+ int ofs_y = i * get_row_height() + cache.line_spacing / 2;
+ bool prev_is_char = false;
bool prev_is_number = false;
- bool in_keyword=false;
- bool underlined=false;
+ bool in_keyword = false;
+ bool underlined = false;
bool in_word = false;
bool in_function_name = false;
bool in_member_variable = false;
@@ -717,23 +683,22 @@ void TextEdit::_notification(int p_what) {
search_text_col = _get_column_pos_of_word(search_text, str, search_flags, 0);
if (highlighted_text.length() != 0 && highlighted_text != search_text)
- highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE|SEARCH_WHOLE_WORDS, 0);
-
- const Map<int,Text::ColorRegionInfo>& cri_map=text.get_color_region_info(line);
+ highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0);
+ const Map<int, Text::ColorRegionInfo> &cri_map = text.get_color_region_info(line);
if (text.is_marked(line)) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(xmargin_beg, ofs_y,xmargin_end-xmargin_beg,get_row_height()),cache.mark_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg, ofs_y, xmargin_end - xmargin_beg, get_row_height()), cache.mark_color);
}
if (text.is_breakpoint(line)) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(xmargin_beg, ofs_y,xmargin_end-xmargin_beg,get_row_height()),cache.breakpoint_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg, ofs_y, xmargin_end - xmargin_beg, get_row_height()), cache.breakpoint_color);
}
- if (line==cursor.line) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(0, ofs_y,xmargin_end,get_row_height()),cache.current_line_color);
+ if (line == cursor.line) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(0, ofs_y, xmargin_end, get_row_height()), cache.current_line_color);
}
// draw breakpoint marker
@@ -744,39 +709,37 @@ void TextEdit::_notification(int p_what) {
int marker_height = get_row_height() - (vertical_gap * 2);
int marker_width = cache.breakpoint_gutter_width - (horizontal_gap * 2);
// no transparency on marker
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cache.style_normal->get_margin(MARGIN_LEFT) + horizontal_gap - 2, ofs_y + vertical_gap ,marker_width, marker_height),Color(cache.breakpoint_color.r, cache.breakpoint_color.g, cache.breakpoint_color.b));
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cache.style_normal->get_margin(MARGIN_LEFT) + horizontal_gap - 2, ofs_y + vertical_gap, marker_width, marker_height), Color(cache.breakpoint_color.r, cache.breakpoint_color.g, cache.breakpoint_color.b));
}
}
-
if (cache.line_number_w) {
- String fc = String::num(line+1);
+ String fc = String::num(line + 1);
while (fc.length() < line_number_char_count) {
- fc=line_num_padding+fc;
+ fc = line_num_padding + fc;
}
- cache.font->draw(ci,Point2(cache.style_normal->get_margin(MARGIN_LEFT)+cache.breakpoint_gutter_width,ofs_y+cache.font->get_ascent()),fc,cache.line_number_color);
+ cache.font->draw(ci, Point2(cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width, ofs_y + cache.font->get_ascent()), fc, cache.line_number_color);
}
- for (int j=0;j<str.length();j++) {
+ for (int j = 0; j < str.length(); j++) {
//look for keyword
- if (deregion>0) {
+ if (deregion > 0) {
deregion--;
- if (deregion==0)
- in_region=-1;
+ if (deregion == 0)
+ in_region = -1;
}
- if (syntax_coloring && deregion==0) {
-
+ if (syntax_coloring && deregion == 0) {
color = cache.font_color; //reset
//find keyword
- bool is_char = _is_text_char(str[j]);
+ bool is_char = _is_text_char(str[j]);
bool is_symbol = _is_symbol(str[j]);
bool is_number = _is_number(str[j]);
- if (j==0 && in_region>=0 && color_regions[in_region].line_only) {
- in_region=-1; //reset regions that end at end of line
+ if (j == 0 && in_region >= 0 && color_regions[in_region].line_only) {
+ in_region = -1; //reset regions that end at end of line
}
// allow ABCDEF in hex notation
@@ -787,11 +750,11 @@ void TextEdit::_notification(int p_what) {
}
// check for dot or 'x' for hex notation in floating point number
- if ((str[j] == '.' || str[j] == 'x') && !in_word && prev_is_number && !is_number) {
+ if ((str[j] == '.' || str[j] == 'x') && !in_word && prev_is_number && !is_number) {
is_number = true;
is_symbol = false;
- if (str[j] == 'x' && str[j-1] == '0') {
+ if (str[j] == 'x' && str[j - 1] == '0') {
is_hex_notation = true;
}
}
@@ -810,49 +773,48 @@ void TextEdit::_notification(int p_what) {
if (is_symbol && cri_map.has(j)) {
+ const Text::ColorRegionInfo &cri = cri_map[j];
- const Text::ColorRegionInfo &cri=cri_map[j];
-
- if (in_region==-1) {
+ if (in_region == -1) {
if (!cri.end) {
- in_region=cri.region;
+ in_region = cri.region;
}
- } else if (in_region==cri.region && !color_regions[cri.region].line_only) { //ignore otherwise
+ } else if (in_region == cri.region && !color_regions[cri.region].line_only) { //ignore otherwise
if (cri.end || color_regions[cri.region].eq) {
- deregion=color_regions[cri.region].eq?color_regions[cri.region].begin_key.length():color_regions[cri.region].end_key.length();
+ deregion = color_regions[cri.region].eq ? color_regions[cri.region].begin_key.length() : color_regions[cri.region].end_key.length();
}
}
}
if (!is_char) {
- in_keyword=false;
- underlined=false;
+ in_keyword = false;
+ underlined = false;
}
- if (in_region==-1 && !in_keyword && is_char && !prev_is_char) {
+ if (in_region == -1 && !in_keyword && is_char && !prev_is_char) {
- int to=j;
- while(to<str.length() && _is_text_char(str[to]))
+ int to = j;
+ while (to < str.length() && _is_text_char(str[to]))
to++;
- uint32_t hash = String::hash(&str[j],to-j);
- StrRange range(&str[j],to-j);
+ uint32_t hash = String::hash(&str[j], to - j);
+ StrRange range(&str[j], to - j);
- const Color *col=keywords.custom_getptr(range,hash);
+ const Color *col = keywords.custom_getptr(range, hash);
if (col) {
- in_keyword=true;
- keyword_color=*col;
+ in_keyword = true;
+ keyword_color = *col;
}
- if (select_identifiers_enabled && hilighted_word!=String()) {
- if (hilighted_word==range) {
- underlined=true;
+ if (select_identifiers_enabled && hilighted_word != String()) {
+ if (hilighted_word == range) {
+ underlined = true;
}
}
}
@@ -860,7 +822,7 @@ void TextEdit::_notification(int p_what) {
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++;
}
@@ -876,7 +838,7 @@ void TextEdit::_notification(int p_what) {
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--;
}
@@ -890,169 +852,164 @@ void TextEdit::_notification(int p_what) {
in_member_variable = false;
}
- if (in_region>=0)
- color=color_regions[in_region].color;
+ if (in_region >= 0)
+ color = color_regions[in_region].color;
else if (in_keyword)
- color=keyword_color;
+ color = keyword_color;
else if (in_member_variable)
- color=cache.member_variable_color;
+ color = cache.member_variable_color;
else if (in_function_name)
- color=cache.function_color;
+ color = cache.function_color;
else if (is_symbol)
- color=cache.symbol_color;
+ color = cache.symbol_color;
else if (is_number)
- color=cache.number_color;
-
- prev_is_char=is_char;
- prev_is_number=is_number;
+ color = cache.number_color;
+ prev_is_char = is_char;
+ prev_is_number = is_number;
}
int char_w;
//handle tabulator
-
- if (str[j]=='\t') {
- int left = char_ofs%tab_w;
- if (left==0)
- char_w=tab_w;
+ if (str[j] == '\t') {
+ int left = char_ofs % tab_w;
+ if (left == 0)
+ char_w = tab_w;
else
- char_w=tab_w-char_ofs%tab_w; // is right...
+ char_w = tab_w - char_ofs % tab_w; // is right...
} else {
- char_w=cache.font->get_char_size(str[j],str[j+1]).width;
+ char_w = cache.font->get_char_size(str[j], str[j + 1]).width;
}
- if ( (char_ofs+char_margin)<xmargin_beg) {
- char_ofs+=char_w;
+ if ((char_ofs + char_margin) < xmargin_beg) {
+ char_ofs += char_w;
continue;
}
- if ( (char_ofs+char_margin+char_w)>=xmargin_end) {
+ if ((char_ofs + char_margin + char_w) >= xmargin_end) {
if (syntax_coloring)
continue;
else
break;
}
- bool in_search_result=false;
+ bool in_search_result = false;
if (search_text_col != -1) {
// if we are at the end check for new search result on same line
- if (j >= search_text_col+search_text.length())
+ if (j >= search_text_col + search_text.length())
search_text_col = _get_column_pos_of_word(search_text, str, search_flags, j);
- in_search_result = j >= search_text_col && j < search_text_col+search_text.length();
+ in_search_result = j >= search_text_col && j < search_text_col + search_text.length();
if (in_search_result) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y ), Size2i(char_w, get_row_height())),cache.search_result_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(char_w, get_row_height())), cache.search_result_color);
}
}
- bool in_selection = (selection.active && line>=selection.from_line && line<=selection.to_line && (line>selection.from_line || j>=selection.from_column) && (line<selection.to_line || j<selection.to_column));
+ bool in_selection = (selection.active && line >= selection.from_line && line <= selection.to_line && (line > selection.from_line || j >= selection.from_column) && (line < selection.to_line || j < selection.to_column));
if (in_selection) {
//inside selection!
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y ), Size2i(char_w,get_row_height())),cache.selection_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(char_w, get_row_height())), cache.selection_color);
}
if (in_search_result) {
- Color border_color=(line==search_result_line && j>=search_result_col && j<search_result_col+search_text.length())?cache.font_color:cache.search_result_border_color;
+ Color border_color = (line == search_result_line && j >= search_result_col && j < search_result_col + search_text.length()) ? cache.font_color : cache.search_result_border_color;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y ), Size2i(char_w,1)),border_color);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y+get_row_height()-1 ), Size2i(char_w,1)),border_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(char_w, 1)), border_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y + get_row_height() - 1), Size2i(char_w, 1)), border_color);
- if (j==search_text_col)
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y ), Size2i(1,get_row_height())),border_color);
- if (j==search_text_col+search_text.length()-1)
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin+char_w-1, ofs_y ), Size2i(1,get_row_height())),border_color);
+ if (j == search_text_col)
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(1, get_row_height())), border_color);
+ if (j == search_text_col + search_text.length() - 1)
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + char_w - 1, ofs_y), Size2i(1, get_row_height())), border_color);
}
if (highlight_all_occurrences) {
if (highlighted_text_col != -1) {
// if we are at the end check for new word on same line
- if (j > highlighted_text_col+highlighted_text.length()) {
- highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE|SEARCH_WHOLE_WORDS, j);
+ if (j > highlighted_text_col + highlighted_text.length()) {
+ highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, j);
}
- bool in_highlighted_word = (j >= highlighted_text_col && j < highlighted_text_col+highlighted_text.length());
+ bool in_highlighted_word = (j >= highlighted_text_col && j < highlighted_text_col + highlighted_text.length());
/* if this is the original highlighted text we don't want to highlight it again */
- if (cursor.line==line && (cursor.column >= highlighted_text_col && cursor.column <= highlighted_text_col+highlighted_text.length())) {
+ if (cursor.line == line && (cursor.column >= highlighted_text_col && cursor.column <= highlighted_text_col + highlighted_text.length())) {
in_highlighted_word = false;
}
if (in_highlighted_word) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2i( char_ofs+char_margin, ofs_y ), Size2i(char_w, get_row_height())),cache.word_highlighted_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(char_w, get_row_height())), cache.word_highlighted_color);
}
}
}
if (brace_matching_enabled) {
- if ( (brace_open_match_line==line && brace_open_match_column==j) ||
- (cursor.column==j && cursor.line==line && (brace_open_matching||brace_open_mismatch))) {
+ if ((brace_open_match_line == line && brace_open_match_column == j) ||
+ (cursor.column == j && cursor.line == line && (brace_open_matching || brace_open_mismatch))) {
if (brace_open_mismatch)
- color=cache.brace_mismatch_color;
- cache.font->draw_char(ci,Point2i( char_ofs+char_margin, ofs_y+ascent),'_',str[j+1],in_selection?cache.font_selected_color:color);
-
+ color = cache.brace_mismatch_color;
+ cache.font->draw_char(ci, Point2i(char_ofs + char_margin, ofs_y + ascent), '_', str[j + 1], in_selection ? cache.font_selected_color : color);
}
if (
- (brace_close_match_line==line && brace_close_match_column==j) ||
- (cursor.column==j+1 && cursor.line==line && (brace_close_matching||brace_close_mismatch))) {
-
+ (brace_close_match_line == line && brace_close_match_column == j) ||
+ (cursor.column == j + 1 && cursor.line == line && (brace_close_matching || brace_close_mismatch))) {
if (brace_close_mismatch)
- color=cache.brace_mismatch_color;
- cache.font->draw_char(ci,Point2i( char_ofs+char_margin, ofs_y+ascent),'_',str[j+1],in_selection?cache.font_selected_color:color);
-
+ color = cache.brace_mismatch_color;
+ cache.font->draw_char(ci, Point2i(char_ofs + char_margin, ofs_y + ascent), '_', str[j + 1], in_selection ? cache.font_selected_color : color);
}
}
- if (cursor.column==j && cursor.line==line) {
+ if (cursor.column == j && cursor.line == line) {
- cursor_pos = Point2i( char_ofs+char_margin, ofs_y );
+ cursor_pos = Point2i(char_ofs + char_margin, ofs_y);
if (insert_mode) {
cursor_pos.y += (get_row_height() - 3);
}
- int caret_w = (str[j]=='\t') ? cache.font->get_char_size(' ').width : char_w;
+ int caret_w = (str[j] == '\t') ? cache.font->get_char_size(' ').width : char_w;
if (draw_caret) {
if (insert_mode) {
int caret_h = (block_caret) ? 4 : 1;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor_pos, Size2i(caret_w,caret_h)),cache.caret_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, caret_h)), cache.caret_color);
} else {
caret_w = (block_caret) ? caret_w : 1;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor_pos, Size2i(caret_w,get_row_height())),cache.caret_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, get_row_height())), cache.caret_color);
}
}
}
- if (cursor.column==j && cursor.line==line && block_caret && draw_caret && !insert_mode) {
+ if (cursor.column == j && cursor.line == line && block_caret && draw_caret && !insert_mode) {
color = cache.caret_background_color;
}
- if (str[j]>=32) {
- int w = cache.font->draw_char(ci,Point2i( char_ofs+char_margin, ofs_y+ascent),str[j],str[j+1],in_selection?cache.font_selected_color:color);
+ if (str[j] >= 32) {
+ int w = cache.font->draw_char(ci, Point2i(char_ofs + char_margin, ofs_y + ascent), str[j], str[j + 1], in_selection ? cache.font_selected_color : color);
if (underlined) {
- draw_rect(Rect2( char_ofs+char_margin, ofs_y+ascent+2,w,1),in_selection?cache.font_selected_color:color);
+ draw_rect(Rect2(char_ofs + char_margin, ofs_y + ascent + 2, w, 1), in_selection ? cache.font_selected_color : color);
}
}
- else if (draw_tabs && str[j]=='\t') {
- int yofs= (get_row_height() - cache.tab_icon->get_height())/2;
- cache.tab_icon->draw(ci, Point2(char_ofs+char_margin,ofs_y+yofs),in_selection?cache.font_selected_color:color);
+ else if (draw_tabs && str[j] == '\t') {
+ int yofs = (get_row_height() - cache.tab_icon->get_height()) / 2;
+ cache.tab_icon->draw(ci, Point2(char_ofs + char_margin, ofs_y + yofs), in_selection ? cache.font_selected_color : color);
}
- char_ofs+=char_w;
+ char_ofs += char_w;
}
- if (cursor.column==str.length() && cursor.line==line && (char_ofs+char_margin)>=xmargin_beg) {
+ if (cursor.column == str.length() && cursor.line == line && (char_ofs + char_margin) >= xmargin_beg) {
- cursor_pos=Point2i( char_ofs+char_margin, ofs_y );
+ cursor_pos = Point2i(char_ofs + char_margin, ofs_y);
if (insert_mode) {
cursor_pos.y += (get_row_height() - 3);
@@ -1062,191 +1019,172 @@ void TextEdit::_notification(int p_what) {
if (insert_mode) {
int char_w = cache.font->get_char_size(' ').width;
int caret_h = (block_caret) ? 4 : 1;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor_pos, Size2i(char_w,caret_h)),cache.caret_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(char_w, caret_h)), cache.caret_color);
} else {
int char_w = cache.font->get_char_size(' ').width;
int caret_w = (block_caret) ? char_w : 1;
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor_pos, Size2i(caret_w,get_row_height())),cache.caret_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, get_row_height())), cache.caret_color);
}
}
}
}
if (line_length_guideline) {
- int x=xmargin_beg+cache.font->get_char_size('0').width*line_length_guideline_col-cursor.x_ofs;
- if (x>xmargin_beg && x<xmargin_end) {
- VisualServer::get_singleton()->canvas_item_add_line(ci,Point2(x,0),Point2(x,cache.size.height),cache.line_length_guideline_color);
+ int x = xmargin_beg + cache.font->get_char_size('0').width * line_length_guideline_col - cursor.x_ofs;
+ if (x > xmargin_beg && x < xmargin_end) {
+ VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(x, 0), Point2(x, cache.size.height), cache.line_length_guideline_color);
}
}
-
bool completion_below = false;
if (completion_active) {
// code completion box
Ref<StyleBox> csb = get_stylebox("completion");
int maxlines = get_constant("completion_lines");
- int cmax_width = get_constant("completion_max_width")*cache.font->get_char_size('x').x;
+ int cmax_width = get_constant("completion_max_width") * cache.font->get_char_size('x').x;
int scrollw = get_constant("completion_scroll_width");
Color scrollc = get_color("completion_scroll_color");
-
-
- int lines = MIN(completion_options.size(),maxlines);
- int w=0;
- int h=lines*get_row_height();
+ int lines = MIN(completion_options.size(), maxlines);
+ int w = 0;
+ int h = lines * get_row_height();
int nofs = cache.font->get_string_size(completion_base).width;
-
if (completion_options.size() < 50) {
- for(int i=0;i<completion_options.size();i++) {
- int w2=MIN(cache.font->get_string_size(completion_options[i]).x,cmax_width);
- if (w2>w)
- w=w2;
+ for (int i = 0; i < completion_options.size(); i++) {
+ int w2 = MIN(cache.font->get_string_size(completion_options[i]).x, cmax_width);
+ if (w2 > w)
+ w = w2;
}
} else {
- w=cmax_width;
+ w = cmax_width;
}
int th = h + csb->get_minimum_size().y;
- if (cursor_pos.y+get_row_height()+th > get_size().height) {
- completion_rect.pos.y=cursor_pos.y-th;
+ if (cursor_pos.y + get_row_height() + th > get_size().height) {
+ completion_rect.pos.y = cursor_pos.y - th;
} else {
- completion_rect.pos.y=cursor_pos.y+get_row_height()+csb->get_offset().y;
+ completion_rect.pos.y = cursor_pos.y + get_row_height() + csb->get_offset().y;
completion_below = true;
}
- if (cursor_pos.x-nofs+w+scrollw > get_size().width) {
- completion_rect.pos.x=get_size().width-w-scrollw;
+ if (cursor_pos.x - nofs + w + scrollw > get_size().width) {
+ completion_rect.pos.x = get_size().width - w - scrollw;
} else {
- completion_rect.pos.x=cursor_pos.x-nofs;
+ completion_rect.pos.x = cursor_pos.x - nofs;
}
- completion_rect.size.width=w+2;
- completion_rect.size.height=h;
- if (completion_options.size()<=maxlines)
- scrollw=0;
+ completion_rect.size.width = w + 2;
+ completion_rect.size.height = h;
+ if (completion_options.size() <= maxlines)
+ scrollw = 0;
- draw_style_box(csb,Rect2(completion_rect.pos-csb->get_offset(),completion_rect.size+csb->get_minimum_size()+Size2(scrollw,0)));
+ draw_style_box(csb, Rect2(completion_rect.pos - csb->get_offset(), completion_rect.size + csb->get_minimum_size() + Size2(scrollw, 0)));
- if (cache.completion_background_color.a>0.01) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(completion_rect.pos,completion_rect.size+Size2(scrollw,0)),cache.completion_background_color);
+ if (cache.completion_background_color.a > 0.01) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(completion_rect.pos, completion_rect.size + Size2(scrollw, 0)), cache.completion_background_color);
}
- int line_from = CLAMP(completion_index - lines/2, 0, completion_options.size() - lines);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(Point2(completion_rect.pos.x,completion_rect.pos.y+(completion_index-line_from)*get_row_height()),Size2(completion_rect.size.width,get_row_height())),cache.completion_selected_color);
- draw_rect(Rect2(completion_rect.pos,Size2(nofs,completion_rect.size.height)),cache.completion_existing_color);
-
-
+ int line_from = CLAMP(completion_index - lines / 2, 0, completion_options.size() - lines);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(completion_rect.pos.x, completion_rect.pos.y + (completion_index - line_from) * get_row_height()), Size2(completion_rect.size.width, get_row_height())), cache.completion_selected_color);
+ draw_rect(Rect2(completion_rect.pos, Size2(nofs, completion_rect.size.height)), cache.completion_existing_color);
-
- for(int i=0;i<lines;i++) {
+ for (int i = 0; i < lines; i++) {
int l = line_from + i;
- ERR_CONTINUE( l < 0 || l>= completion_options.size());
+ ERR_CONTINUE(l < 0 || l >= completion_options.size());
Color text_color = cache.completion_font_color;
- for(int j=0;j<color_regions.size();j++) {
+ for (int j = 0; j < color_regions.size(); j++) {
if (completion_options[l].begins_with(color_regions[j].begin_key)) {
- text_color=color_regions[j].color;
+ text_color = color_regions[j].color;
}
}
- draw_string(cache.font,Point2(completion_rect.pos.x,completion_rect.pos.y+i*get_row_height()+cache.font->get_ascent()),completion_options[l],text_color,completion_rect.size.width);
+ draw_string(cache.font, Point2(completion_rect.pos.x, completion_rect.pos.y + i * get_row_height() + cache.font->get_ascent()), completion_options[l], text_color, completion_rect.size.width);
}
if (scrollw) {
//draw a small scroll rectangle to show a position in the options
float r = maxlines / (float)completion_options.size();
float o = line_from / (float)completion_options.size();
- draw_rect(Rect2(completion_rect.pos.x+completion_rect.size.width,completion_rect.pos.y+o*completion_rect.size.y,scrollw,completion_rect.size.y*r),scrollc);
+ draw_rect(Rect2(completion_rect.pos.x + completion_rect.size.width, completion_rect.pos.y + o * completion_rect.size.y, scrollw, completion_rect.size.y * r), scrollc);
}
- completion_line_ofs=line_from;
-
+ completion_line_ofs = line_from;
}
// check to see if the hint should be drawn
bool show_hint = false;
- if (completion_hint!="") {
+ if (completion_hint != "") {
if (completion_active) {
if (completion_below && !callhint_below) {
show_hint = true;
- }
- else if (!completion_below && callhint_below) {
+ } else if (!completion_below && callhint_below) {
show_hint = true;
}
- }
- else {
+ } else {
show_hint = true;
}
}
if (show_hint) {
- Ref<StyleBox> sb = get_stylebox("panel","TooltipPanel");
+ Ref<StyleBox> sb = get_stylebox("panel", "TooltipPanel");
Ref<Font> font = cache.font;
- Color font_color = get_color("font_color","TooltipLabel");
-
+ Color font_color = get_color("font_color", "TooltipLabel");
- int max_w=0;
+ int max_w = 0;
int sc = completion_hint.get_slice_count("\n");
- int offset=0;
- int spacing=0;
- for(int i=0;i<sc;i++) {
-
- String l = completion_hint.get_slice("\n",i);
- int len = font->get_string_size(l).x;
- max_w = MAX(len,max_w);
- if (i==0) {
- offset = font->get_string_size(l.substr(0,l.find(String::chr(0xFFFF)))).x;
+ int offset = 0;
+ int spacing = 0;
+ for (int i = 0; i < sc; i++) {
+
+ String l = completion_hint.get_slice("\n", i);
+ int len = font->get_string_size(l).x;
+ max_w = MAX(len, max_w);
+ if (i == 0) {
+ offset = font->get_string_size(l.substr(0, l.find(String::chr(0xFFFF)))).x;
} else {
- spacing+=cache.line_spacing;
+ spacing += cache.line_spacing;
}
-
-
}
+ Size2 size = Size2(max_w, sc * font->get_height() + spacing);
+ Size2 minsize = size + sb->get_minimum_size();
-
- Size2 size = Size2(max_w,sc*font->get_height()+spacing);
- Size2 minsize = size+sb->get_minimum_size();
-
-
- if (completion_hint_offset==-0xFFFF) {
- completion_hint_offset=cursor_pos.x-offset;
+ if (completion_hint_offset == -0xFFFF) {
+ completion_hint_offset = cursor_pos.x - offset;
}
-
- Point2 hint_ofs = Vector2(completion_hint_offset,cursor_pos.y) + callhint_offset;
+ Point2 hint_ofs = Vector2(completion_hint_offset, cursor_pos.y) + callhint_offset;
if (callhint_below) {
hint_ofs.y += get_row_height() + sb->get_offset().y;
- }
- else {
+ } else {
hint_ofs.y -= minsize.y + sb->get_offset().y;
}
- draw_style_box(sb,Rect2(hint_ofs,minsize));
+ draw_style_box(sb, Rect2(hint_ofs, minsize));
- spacing=0;
- for(int i=0;i<sc;i++) {
- int begin=0;
- int end=0;
- String l = completion_hint.get_slice("\n",i);
+ spacing = 0;
+ for (int i = 0; i < sc; i++) {
+ int begin = 0;
+ int end = 0;
+ String l = completion_hint.get_slice("\n", i);
- if (l.find(String::chr(0xFFFF))!=-1) {
- begin = font->get_string_size(l.substr(0,l.find(String::chr(0xFFFF)))).x;
- end = font->get_string_size(l.substr(0,l.rfind(String::chr(0xFFFF)))).x;
+ if (l.find(String::chr(0xFFFF)) != -1) {
+ begin = font->get_string_size(l.substr(0, l.find(String::chr(0xFFFF)))).x;
+ end = font->get_string_size(l.substr(0, l.rfind(String::chr(0xFFFF)))).x;
}
- draw_string(font,hint_ofs+sb->get_offset()+Vector2(0,font->get_ascent()+font->get_height()*i+spacing),l.replace(String::chr(0xFFFF),""),font_color);
- if (end>0) {
- Vector2 b = hint_ofs+sb->get_offset()+Vector2(begin,font->get_height()+font->get_height()*i+spacing-1);
- draw_line(b,b+Vector2(end-begin,0),font_color);
+ draw_string(font, hint_ofs + sb->get_offset() + Vector2(0, font->get_ascent() + font->get_height() * i + spacing), l.replace(String::chr(0xFFFF), ""), font_color);
+ if (end > 0) {
+ Vector2 b = hint_ofs + sb->get_offset() + Vector2(begin, font->get_height() + font->get_height() * i + spacing - 1);
+ draw_line(b, b + Vector2(end - begin, 0), font_color);
}
- spacing+=cache.line_spacing;
+ spacing += cache.line_spacing;
}
}
-
} break;
case NOTIFICATION_FOCUS_ENTER: {
@@ -1254,7 +1192,7 @@ void TextEdit::_notification(int p_what) {
draw_caret = true;
}
if (OS::get_singleton()->has_virtual_keyboard())
- OS::get_singleton()->show_virtual_keyboard(get_text(),get_global_rect());
+ OS::get_singleton()->show_virtual_keyboard(get_text(), get_global_rect());
if (raised_from_completion) {
VisualServer::get_singleton()->canvas_item_set_z(get_canvas_item(), 1);
}
@@ -1275,27 +1213,27 @@ void TextEdit::_consume_pair_symbol(CharType ch) {
int cursor_position_to_move = cursor_get_column() + 1;
- CharType ch_single[2] = {ch, 0};
- CharType ch_single_pair[2] = {_get_right_pair_symbol(ch), 0};
- CharType ch_pair[3] = {ch, _get_right_pair_symbol(ch), 0};
+ CharType ch_single[2] = { ch, 0 };
+ CharType ch_single_pair[2] = { _get_right_pair_symbol(ch), 0 };
+ CharType ch_pair[3] = { ch, _get_right_pair_symbol(ch), 0 };
- if(is_selection_active()) {
+ if (is_selection_active()) {
- int new_column,new_line;
+ int new_column, new_line;
begin_complex_operation();
_insert_text(get_selection_from_line(), get_selection_from_column(),
- ch_single,
- &new_line, &new_column);
+ ch_single,
+ &new_line, &new_column);
int to_col_offset = 0;
- if(get_selection_from_line() == get_selection_to_line())
+ if (get_selection_from_line() == get_selection_to_line())
to_col_offset = 1;
_insert_text(get_selection_to_line(),
- get_selection_to_column() + to_col_offset,
- ch_single_pair,
- &new_line,&new_column);
+ get_selection_to_column() + to_col_offset,
+ ch_single_pair,
+ &new_line, &new_column);
end_complex_operation();
cursor_set_line(get_selection_to_line());
@@ -1306,78 +1244,71 @@ void TextEdit::_consume_pair_symbol(CharType ch) {
return;
}
- if( (ch == '\'' || ch == '"') &&
+ if ((ch == '\'' || ch == '"') &&
cursor_get_column() > 0 &&
- _is_text_char(text[cursor.line][cursor_get_column() - 1])
- ) {
+ _is_text_char(text[cursor.line][cursor_get_column() - 1])) {
insert_text_at_cursor(ch_single);
cursor_set_column(cursor_position_to_move);
return;
}
- if(cursor_get_column() < text[cursor.line].length()) {
- if(_is_text_char(text[cursor.line][cursor_get_column()])) {
+ if (cursor_get_column() < text[cursor.line].length()) {
+ if (_is_text_char(text[cursor.line][cursor_get_column()])) {
insert_text_at_cursor(ch_single);
cursor_set_column(cursor_position_to_move);
return;
}
- if( _is_pair_right_symbol(ch) &&
- text[cursor.line][cursor_get_column()] == ch
- ) {
+ if (_is_pair_right_symbol(ch) &&
+ text[cursor.line][cursor_get_column()] == ch) {
cursor_set_column(cursor_position_to_move);
return;
}
}
-
insert_text_at_cursor(ch_pair);
cursor_set_column(cursor_position_to_move);
return;
-
}
void TextEdit::_consume_backspace_for_pair_symbol(int prev_line, int prev_column) {
bool remove_right_symbol = false;
- if(cursor.column < text[cursor.line].length() && cursor.column > 0) {
+ if (cursor.column < text[cursor.line].length() && cursor.column > 0) {
CharType left_char = text[cursor.line][cursor.column - 1];
CharType right_char = text[cursor.line][cursor.column];
- if(right_char == _get_right_pair_symbol(left_char)) {
+ if (right_char == _get_right_pair_symbol(left_char)) {
remove_right_symbol = true;
}
-
}
- if(remove_right_symbol) {
- _remove_text(prev_line,prev_column,cursor.line,cursor.column + 1);
+ if (remove_right_symbol) {
+ _remove_text(prev_line, prev_column, cursor.line, cursor.column + 1);
} else {
- _remove_text(prev_line,prev_column,cursor.line,cursor.column);
+ _remove_text(prev_line, prev_column, cursor.line, cursor.column);
}
-
}
void TextEdit::backspace_at_cursor() {
if (readonly)
return;
- if (cursor.column==0 && cursor.line==0)
+ if (cursor.column == 0 && cursor.line == 0)
return;
- int prev_line = cursor.column?cursor.line:cursor.line-1;
- int prev_column = cursor.column?(cursor.column-1):(text[cursor.line-1].length());
- if(auto_brace_completion_enabled &&
+ int prev_line = cursor.column ? cursor.line : cursor.line - 1;
+ int prev_column = cursor.column ? (cursor.column - 1) : (text[cursor.line - 1].length());
+ if (auto_brace_completion_enabled &&
cursor.column > 0 &&
_is_pair_left_symbol(text[cursor.line][cursor.column - 1])) {
_consume_backspace_for_pair_symbol(prev_line, prev_column);
} else {
- _remove_text(prev_line,prev_column,cursor.line,cursor.column);
+ _remove_text(prev_line, prev_column, cursor.line, cursor.column);
}
cursor_set_line(prev_line);
cursor_set_column(prev_column);
-
}
void TextEdit::indent_selection_right() {
@@ -1441,68 +1372,67 @@ void TextEdit::indent_selection_left() {
update();
}
-void TextEdit::_get_mouse_pos(const Point2i& p_mouse, int &r_row, int &r_col) const {
+void TextEdit::_get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) const {
- float rows=p_mouse.y;
- rows-=cache.style_normal->get_margin(MARGIN_TOP);
- rows/=get_row_height();
- int row=cursor.line_ofs+rows;
+ float rows = p_mouse.y;
+ rows -= cache.style_normal->get_margin(MARGIN_TOP);
+ rows /= get_row_height();
+ int row = cursor.line_ofs + rows;
- if (row<0)
- row=0;
+ if (row < 0)
+ row = 0;
- int col=0;
+ int col = 0;
- if (row>=text.size()) {
+ if (row >= text.size()) {
- row=text.size()-1;
- col=text[row].size();
+ row = text.size() - 1;
+ col = text[row].size();
} else {
- col=p_mouse.x-(cache.style_normal->get_margin(MARGIN_LEFT)+cache.line_number_w+cache.breakpoint_gutter_width);
- col+=cursor.x_ofs;
- col=get_char_pos_for( col, get_line(row) );
+ col = p_mouse.x - (cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width);
+ col += cursor.x_ofs;
+ col = get_char_pos_for(col, get_line(row));
}
- r_row=row;
- r_col=col;
+ r_row = row;
+ r_col = col;
}
-void TextEdit::_gui_input(const InputEvent& p_gui_input) {
+void TextEdit::_gui_input(const InputEvent &p_gui_input) {
- switch(p_gui_input.type) {
+ switch (p_gui_input.type) {
case InputEvent::MOUSE_BUTTON: {
- const InputEventMouseButton &mb=p_gui_input.mouse_button;
+ const InputEventMouseButton &mb = p_gui_input.mouse_button;
- if (completion_active && completion_rect.has_point(Point2(mb.x,mb.y))) {
+ if (completion_active && completion_rect.has_point(Point2(mb.x, mb.y))) {
if (!mb.pressed)
return;
- if (mb.button_index==BUTTON_WHEEL_UP) {
- if (completion_index>0) {
+ if (mb.button_index == BUTTON_WHEEL_UP) {
+ if (completion_index > 0) {
completion_index--;
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
}
-
}
- if (mb.button_index==BUTTON_WHEEL_DOWN) {
+ if (mb.button_index == BUTTON_WHEEL_DOWN) {
- if (completion_index<completion_options.size()-1) {
+ if (completion_index < completion_options.size() - 1) {
completion_index++;
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
}
}
- if (mb.button_index==BUTTON_LEFT) {
+ if (mb.button_index == BUTTON_LEFT) {
- completion_index=CLAMP(completion_line_ofs+(mb.y-completion_rect.pos.y)/get_row_height(),0,completion_options.size()-1);
+ completion_index = CLAMP(completion_line_ofs + (mb.y - completion_rect.pos.y) / get_row_height(), 0, completion_options.size() - 1);
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
if (mb.doubleclick)
_confirm_completion();
@@ -1514,36 +1444,34 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
if (mb.pressed) {
- if (mb.button_index==BUTTON_WHEEL_UP && !mb.mod.command) {
- v_scroll->set_value( v_scroll->get_value() -3 );
+ if (mb.button_index == BUTTON_WHEEL_UP && !mb.mod.command) {
+ v_scroll->set_value(v_scroll->get_value() - 3);
}
- if (mb.button_index==BUTTON_WHEEL_DOWN && !mb.mod.command) {
- v_scroll->set_value( v_scroll->get_value() +3 );
+ if (mb.button_index == BUTTON_WHEEL_DOWN && !mb.mod.command) {
+ v_scroll->set_value(v_scroll->get_value() + 3);
}
- if (mb.button_index==BUTTON_WHEEL_LEFT) {
- h_scroll->set_value( h_scroll->get_value() -3 );
+ if (mb.button_index == BUTTON_WHEEL_LEFT) {
+ h_scroll->set_value(h_scroll->get_value() - 3);
}
- if (mb.button_index==BUTTON_WHEEL_RIGHT) {
- h_scroll->set_value( h_scroll->get_value() +3 );
+ if (mb.button_index == BUTTON_WHEEL_RIGHT) {
+ h_scroll->set_value(h_scroll->get_value() + 3);
}
- if (mb.button_index==BUTTON_LEFT) {
-
+ if (mb.button_index == BUTTON_LEFT) {
_reset_caret_blink_timer();
- int row,col;
- _get_mouse_pos(Point2i(mb.x,mb.y), row,col);
+ int row, col;
+ _get_mouse_pos(Point2i(mb.x, mb.y), row, col);
- if (mb.mod.command && hilighted_word!=String()) {
+ if (mb.mod.command && hilighted_word != String()) {
- emit_signal("symbol_lookup",hilighted_word,row,col);
+ emit_signal("symbol_lookup", hilighted_word, row, col);
return;
}
-
// toggle breakpoint on gutter click
if (draw_breakpoint_gutter) {
- int gutter=cache.style_normal->get_margin(MARGIN_LEFT);
+ int gutter = cache.style_normal->get_margin(MARGIN_LEFT);
if (mb.x > gutter && mb.x <= gutter + cache.breakpoint_gutter_width + 3) {
set_line_as_breakpoint(row, !is_line_set_as_breakpoint(row));
emit_signal("breakpoint_toggled", row);
@@ -1551,131 +1479,120 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
}
- int prev_col=cursor.column;
- int prev_line=cursor.line;
-
+ int prev_col = cursor.column;
+ int prev_line = cursor.line;
+ cursor_set_line(row);
+ cursor_set_column(col);
- cursor_set_line( row );
- cursor_set_column( col );
-
- if (mb.mod.shift && (cursor.column!=prev_col || cursor.line!=prev_line)) {
+ if (mb.mod.shift && (cursor.column != prev_col || cursor.line != prev_line)) {
if (!selection.active) {
- selection.active=true;
- selection.selecting_mode=Selection::MODE_POINTER;
- selection.from_column=prev_col;
- selection.from_line=prev_line;
- selection.to_column=cursor.column;
- selection.to_line=cursor.line;
-
- if (selection.from_line>selection.to_line || (selection.from_line==selection.to_line && selection.from_column>selection.to_column)) {
- SWAP(selection.from_column,selection.to_column);
- SWAP(selection.from_line,selection.to_line);
- selection.shiftclick_left=false;
+ selection.active = true;
+ selection.selecting_mode = Selection::MODE_POINTER;
+ selection.from_column = prev_col;
+ selection.from_line = prev_line;
+ selection.to_column = cursor.column;
+ selection.to_line = cursor.line;
+
+ if (selection.from_line > selection.to_line || (selection.from_line == selection.to_line && selection.from_column > selection.to_column)) {
+ SWAP(selection.from_column, selection.to_column);
+ SWAP(selection.from_line, selection.to_line);
+ selection.shiftclick_left = false;
} else {
- selection.shiftclick_left=true;
+ selection.shiftclick_left = true;
}
- selection.selecting_line=prev_line;
- selection.selecting_column=prev_col;
+ selection.selecting_line = prev_line;
+ selection.selecting_column = prev_col;
update();
} else {
- if (cursor.line<selection.selecting_line || (cursor.line==selection.selecting_line && cursor.column<selection.selecting_column)) {
+ if (cursor.line < selection.selecting_line || (cursor.line == selection.selecting_line && cursor.column < selection.selecting_column)) {
if (selection.shiftclick_left) {
- SWAP(selection.from_column,selection.to_column);
- SWAP(selection.from_line,selection.to_line);
+ SWAP(selection.from_column, selection.to_column);
+ SWAP(selection.from_line, selection.to_line);
selection.shiftclick_left = !selection.shiftclick_left;
}
- selection.from_column=cursor.column;
- selection.from_line=cursor.line;
+ selection.from_column = cursor.column;
+ selection.from_line = cursor.line;
- } else if (cursor.line>selection.selecting_line || (cursor.line==selection.selecting_line && cursor.column>selection.selecting_column)) {
+ } else if (cursor.line > selection.selecting_line || (cursor.line == selection.selecting_line && cursor.column > selection.selecting_column)) {
if (!selection.shiftclick_left) {
- SWAP(selection.from_column,selection.to_column);
- SWAP(selection.from_line,selection.to_line);
+ SWAP(selection.from_column, selection.to_column);
+ SWAP(selection.from_line, selection.to_line);
selection.shiftclick_left = !selection.shiftclick_left;
}
- selection.to_column=cursor.column;
- selection.to_line=cursor.line;
+ selection.to_column = cursor.column;
+ selection.to_line = cursor.line;
} else {
- selection.active=false;
+ selection.active = false;
}
update();
}
-
-
-
-
-
-
} else {
//if sel active and dblick last time < something
//else
- selection.active=false;
- selection.selecting_mode=Selection::MODE_POINTER;
- selection.selecting_line=row;
- selection.selecting_column=col;
+ selection.active = false;
+ selection.selecting_mode = Selection::MODE_POINTER;
+ selection.selecting_line = row;
+ selection.selecting_column = col;
}
-
- if (!mb.doubleclick && (OS::get_singleton()->get_ticks_msec()-last_dblclk)<600 && cursor.line==prev_line) {
+ if (!mb.doubleclick && (OS::get_singleton()->get_ticks_msec() - last_dblclk) < 600 && cursor.line == prev_line) {
//tripleclick select line
- select(cursor.line,0,cursor.line,text[cursor.line].length());
- selection.selecting_column=0;
- last_dblclk=0;
+ select(cursor.line, 0, cursor.line, text[cursor.line].length());
+ selection.selecting_column = 0;
+ last_dblclk = 0;
} else if (mb.doubleclick && text[cursor.line].length()) {
//doubleclick select world
String s = text[cursor.line];
- int beg=CLAMP(cursor.column,0,s.length());
- int end=beg;
+ int beg = CLAMP(cursor.column, 0, s.length());
+ int end = beg;
- if (s[beg]>32 || beg==s.length()) {
+ if (s[beg] > 32 || beg == s.length()) {
- bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
+ bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
- while(beg>0 && s[beg-1]>32 && (symbol==_is_symbol(s[beg-1]))) {
+ while (beg > 0 && s[beg - 1] > 32 && (symbol == _is_symbol(s[beg - 1]))) {
beg--;
}
- while(end<s.length() && s[end+1]>32 && (symbol==_is_symbol(s[end+1]))) {
+ while (end < s.length() && s[end + 1] > 32 && (symbol == _is_symbol(s[end + 1]))) {
end++;
}
- if (end<s.length())
- end+=1;
+ if (end < s.length())
+ end += 1;
- select(cursor.line,beg,cursor.line,end);
+ select(cursor.line, beg, cursor.line, end);
- selection.selecting_column=beg;
+ selection.selecting_column = beg;
}
last_dblclk = OS::get_singleton()->get_ticks_msec();
-
}
update();
}
- if (mb.button_index==BUTTON_RIGHT && context_menu_enabled) {
+ if (mb.button_index == BUTTON_RIGHT && context_menu_enabled) {
menu->set_pos(get_global_transform().xform(get_local_mouse_pos()));
- menu->set_size(Vector2(1,1));
+ menu->set_size(Vector2(1, 1));
menu->popup();
grab_focus();
-
}
} else {
- if (mb.button_index==BUTTON_LEFT)
+ if (mb.button_index == BUTTON_LEFT)
click_select_held->stop();
// notify to show soft keyboard
@@ -1685,56 +1602,53 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
} break;
case InputEvent::MOUSE_MOTION: {
- const InputEventMouseMotion &mm=p_gui_input.mouse_motion;
+ const InputEventMouseMotion &mm = p_gui_input.mouse_motion;
if (select_identifiers_enabled) {
- if (mm.mod.command && mm.button_mask==0) {
+ if (mm.mod.command && mm.button_mask == 0) {
- String new_word = get_word_at_pos(Vector2(mm.x,mm.y));
- if (new_word!=hilighted_word) {
- hilighted_word=new_word;
+ String new_word = get_word_at_pos(Vector2(mm.x, mm.y));
+ if (new_word != hilighted_word) {
+ hilighted_word = new_word;
update();
}
} else {
- if (hilighted_word!=String()) {
- hilighted_word=String();
+ if (hilighted_word != String()) {
+ hilighted_word = String();
update();
}
}
}
- if (mm.button_mask&BUTTON_MASK_LEFT && get_viewport()->gui_get_drag_data()==Variant()) { //ignore if dragging
+ if (mm.button_mask & BUTTON_MASK_LEFT && get_viewport()->gui_get_drag_data() == Variant()) { //ignore if dragging
- if (selection.selecting_mode!=Selection::MODE_NONE) {
+ if (selection.selecting_mode != Selection::MODE_NONE) {
_reset_caret_blink_timer();
- int row,col;
- _get_mouse_pos(Point2i(mm.x,mm.y), row,col);
+ int row, col;
+ _get_mouse_pos(Point2i(mm.x, mm.y), row, col);
- select(selection.selecting_line,selection.selecting_column,row,col);
+ select(selection.selecting_line, selection.selecting_column, row, col);
- cursor_set_line( row );
- cursor_set_column( col );
+ cursor_set_line(row);
+ cursor_set_column(col);
update();
click_select_held->start();
-
}
-
}
} break;
case InputEvent::KEY: {
- InputEventKey k=p_gui_input.key;
-
+ InputEventKey k = p_gui_input.key;
#ifdef OSX_ENABLED
- if (k.scancode==KEY_META) {
+ if (k.scancode == KEY_META) {
#else
- if (k.scancode==KEY_CONTROL) {
+ if (k.scancode == KEY_CONTROL) {
#endif
if (select_identifiers_enabled) {
@@ -1745,7 +1659,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
update();
} else {
- hilighted_word=String();
+ hilighted_word = String();
update();
}
}
@@ -1758,97 +1672,94 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (readonly)
break;
- bool valid=true;
+ bool valid = true;
if (k.mod.command || k.mod.meta)
- valid=false;
+ valid = false;
if (valid) {
if (!k.mod.alt) {
- if (k.scancode==KEY_UP) {
+ if (k.scancode == KEY_UP) {
- if (completion_index>0) {
+ if (completion_index > 0) {
completion_index--;
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
}
accept_event();
return;
}
+ if (k.scancode == KEY_DOWN) {
- if (k.scancode==KEY_DOWN) {
-
- if (completion_index<completion_options.size()-1) {
+ if (completion_index < completion_options.size() - 1) {
completion_index++;
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
}
accept_event();
return;
}
- if (k.scancode==KEY_PAGEUP) {
+ if (k.scancode == KEY_PAGEUP) {
- completion_index-=get_constant("completion_lines");
- if (completion_index<0)
- completion_index=0;
- completion_current=completion_options[completion_index];
+ completion_index -= get_constant("completion_lines");
+ if (completion_index < 0)
+ completion_index = 0;
+ completion_current = completion_options[completion_index];
update();
accept_event();
return;
}
+ if (k.scancode == KEY_PAGEDOWN) {
- if (k.scancode==KEY_PAGEDOWN) {
-
- completion_index+=get_constant("completion_lines");
- if (completion_index>=completion_options.size())
- completion_index=completion_options.size()-1;
- completion_current=completion_options[completion_index];
+ completion_index += get_constant("completion_lines");
+ if (completion_index >= completion_options.size())
+ completion_index = completion_options.size() - 1;
+ completion_current = completion_options[completion_index];
update();
accept_event();
return;
}
- if (k.scancode==KEY_HOME && completion_index>0) {
+ if (k.scancode == KEY_HOME && completion_index > 0) {
- completion_index=0;
- completion_current=completion_options[completion_index];
+ completion_index = 0;
+ completion_current = completion_options[completion_index];
update();
accept_event();
return;
}
- if (k.scancode==KEY_END && completion_index<completion_options.size()-1) {
+ if (k.scancode == KEY_END && completion_index < completion_options.size() - 1) {
- completion_index=completion_options.size()-1;
- completion_current=completion_options[completion_index];
+ completion_index = completion_options.size() - 1;
+ completion_current = completion_options[completion_index];
update();
accept_event();
return;
}
+ if (k.scancode == KEY_DOWN) {
- if (k.scancode==KEY_DOWN) {
-
- if (completion_index<completion_options.size()-1) {
+ if (completion_index < completion_options.size() - 1) {
completion_index++;
- completion_current=completion_options[completion_index];
+ completion_current = completion_options[completion_index];
update();
}
accept_event();
return;
}
- if (k.scancode==KEY_ENTER || k.scancode==KEY_RETURN || k.scancode==KEY_TAB) {
+ if (k.scancode == KEY_ENTER || k.scancode == KEY_RETURN || k.scancode == KEY_TAB) {
_confirm_completion();
accept_event();
return;
}
- if (k.scancode==KEY_BACKSPACE) {
+ if (k.scancode == KEY_BACKSPACE) {
_reset_caret_blink_timer();
@@ -1858,19 +1769,18 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
return;
}
-
- if (k.scancode==KEY_SHIFT) {
+ if (k.scancode == KEY_SHIFT) {
accept_event();
return;
}
}
- if (k.unicode>32) {
+ if (k.unicode > 32) {
_reset_caret_blink_timer();
- const CharType chr[2] = {(CharType)k.unicode, 0};
- if(auto_brace_completion_enabled && _is_pair_symbol(chr[0])) {
+ const CharType chr[2] = { (CharType)k.unicode, 0 };
+ if (auto_brace_completion_enabled && _is_pair_symbol(chr[0])) {
_consume_pair_symbol(chr[0]);
} else {
@@ -1898,28 +1808,26 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
_cancel_completion();
-
}
/* TEST CONTROL FIRST!! */
// some remaps for duplicate functions..
- if (k.mod.command && !k.mod.shift && !k.mod.alt && !k.mod.meta && k.scancode==KEY_INSERT) {
+ if (k.mod.command && !k.mod.shift && !k.mod.alt && !k.mod.meta && k.scancode == KEY_INSERT) {
- k.scancode=KEY_C;
+ k.scancode = KEY_C;
}
- if (!k.mod.command && k.mod.shift && !k.mod.alt && !k.mod.meta && k.scancode==KEY_INSERT) {
+ if (!k.mod.command && k.mod.shift && !k.mod.alt && !k.mod.meta && k.scancode == KEY_INSERT) {
- k.scancode=KEY_V;
- k.mod.command=true;
- k.mod.shift=false;
+ k.scancode = KEY_V;
+ k.mod.command = true;
+ k.mod.shift = false;
}
if (!k.mod.command) {
_reset_caret_blink_timer();
}
-
// save here for insert mode, just in case it is cleared in the following section
bool had_selection = selection.active;
@@ -1929,11 +1837,11 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (readonly)
break;
- bool clear=false;
- bool unselect=false;
- bool dobreak=false;
+ bool clear = false;
+ bool unselect = false;
+ bool dobreak = false;
- switch(k.scancode) {
+ switch (k.scancode) {
case KEY_TAB: {
if (k.mod.shift) {
@@ -1941,25 +1849,27 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
} else {
indent_selection_right();
}
- dobreak=true;
+ dobreak = true;
accept_event();
} break;
case KEY_X:
case KEY_C:
//special keys often used with control, wait...
- clear=(!k.mod.command || k.mod.shift || k.mod.alt );
+ clear = (!k.mod.command || k.mod.shift || k.mod.alt);
break;
case KEY_DELETE:
if (!k.mod.shift) {
accept_event();
- clear=true; dobreak=true;
+ clear = true;
+ dobreak = true;
} else if (k.mod.command || k.mod.alt) {
- dobreak=true;
+ dobreak = true;
}
break;
case KEY_BACKSPACE:
accept_event();
- clear=true; dobreak=true;
+ clear = true;
+ dobreak = true;
break;
case KEY_LEFT:
case KEY_RIGHT:
@@ -1972,19 +1882,19 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
// ignore arrows if any modifiers are held (shift = selecting, others may be used for editor hotkeys)
if (k.mod.command || k.mod.shift || k.mod.alt)
break;
- unselect=true;
+ unselect = true;
break;
default:
- if (k.unicode>=32 && !k.mod.command && !k.mod.alt && !k.mod.meta)
- clear=true;
+ if (k.unicode >= 32 && !k.mod.command && !k.mod.alt && !k.mod.meta)
+ clear = true;
if (auto_brace_completion_enabled && _is_pair_left_symbol(k.unicode))
- clear=false;
+ clear = false;
}
if (unselect) {
- selection.active=false;
- selection.selecting_mode=Selection::MODE_NONE;
+ selection.active = false;
+ selection.selecting_mode = Selection::MODE_NONE;
update();
}
if (clear) {
@@ -1992,9 +1902,9 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (!dobreak) {
begin_complex_operation();
}
- selection.active=false;
+ selection.active = false;
update();
- _remove_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
+ _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
cursor_set_line(selection.from_line);
cursor_set_column(selection.from_column);
update();
@@ -2003,9 +1913,9 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
break;
}
- selection.selecting_text=false;
+ selection.selecting_text = false;
- bool scancode_handled=true;
+ bool scancode_handled = true;
// special scancode test...
@@ -2017,20 +1927,20 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (readonly)
break;
- String ins="\n";
+ String ins = "\n";
//keep indentation
- for(int i=0;i<text[cursor.line].length();i++) {
- if (text[cursor.line][i]=='\t')
- ins+="\t";
+ for (int i = 0; i < text[cursor.line].length(); i++) {
+ if (text[cursor.line][i] == '\t')
+ ins += "\t";
else
break;
}
- if(auto_indent){
+ if (auto_indent) {
// indent once again if previous line will end with ':'
// (i.e. colon precedes current cursor position)
- if(cursor.column>0 && text[cursor.line][cursor.column-1]==':') {
- ins+="\t";
+ if (cursor.column > 0 && text[cursor.line][cursor.column - 1] == ':') {
+ ins += "\t";
}
}
@@ -2040,13 +1950,11 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (cursor.line > 0) {
cursor_set_line(cursor.line - 1);
cursor_set_column(text[cursor.line].length());
- }
- else {
+ } else {
cursor_set_column(0);
first_line = true;
}
- }
- else {
+ } else {
cursor_set_column(text[cursor.line].length());
}
}
@@ -2060,11 +1968,11 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
} break;
case KEY_ESCAPE: {
- if (completion_hint!="") {
- completion_hint="";
+ if (completion_hint != "") {
+ completion_hint = "";
update();
} else {
- scancode_handled=false;
+ scancode_handled = false;
}
} break;
case KEY_TAB: {
@@ -2075,12 +1983,11 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (selection.active) {
-
} else {
if (k.mod.shift) {
int cc = cursor.column;
- if (cc>0 && cc<=text[cursor.line].length() && text[cursor.line][cursor.column-1]=='\t') {
+ if (cc > 0 && cc <= text[cursor.line].length() && text[cursor.line][cursor.column - 1] == '\t') {
//simple unindent
backspace_at_cursor();
@@ -2100,23 +2007,23 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.alt) {
#else
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
} else if (k.mod.command) {
#endif
- int line=cursor.line;
- int column=cursor.column;
+ int line = cursor.line;
+ int column = cursor.column;
- bool prev_char=false;
- bool only_whitespace=true;
+ bool prev_char = false;
+ bool only_whitespace = true;
while (only_whitespace && line > 0) {
- while (column>0) {
- CharType c=text[line][column-1];
+ while (column > 0) {
+ CharType c = text[line][column - 1];
if (c != '\t' && c != ' ') {
- only_whitespace=false;
+ only_whitespace = false;
break;
}
@@ -2125,19 +2032,18 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (only_whitespace) {
line--;
- column=text[line].length();
+ column = text[line].length();
}
}
- while (column>0) {
- bool ischar=_is_text_char(text[line][column-1]);
+ while (column > 0) {
+ bool ischar = _is_text_char(text[line][column - 1]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
column--;
-
}
_remove_text(line, column, cursor.line, cursor.column);
@@ -2175,34 +2081,33 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
#else
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
} else if (k.mod.command) {
#endif
- bool prev_char=false;
- int cc=cursor.column;
- while (cc>0) {
+ bool prev_char = false;
+ int cc = cursor.column;
+ while (cc > 0) {
- bool ischar=_is_text_char(text[cursor.line][cc-1]);
+ bool ischar = _is_text_char(text[cursor.line][cc - 1]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc--;
-
}
cursor_set_column(cc);
- } else if (cursor.column==0) {
+ } else if (cursor.column == 0) {
- if (cursor.line>0) {
- cursor_set_line(cursor.line-1);
+ if (cursor.line > 0) {
+ cursor_set_line(cursor.line - 1);
cursor_set_column(text[cursor.line].length());
}
} else {
- cursor_set_column(cursor_get_column()-1);
+ cursor_set_column(cursor_get_column() - 1);
}
if (k.mod.shift)
@@ -2233,32 +2138,32 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
} else if (k.mod.alt) {
#else
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
} else if (k.mod.command) {
#endif
- bool prev_char=false;
- int cc=cursor.column;
- while (cc<text[cursor.line].length()) {
+ bool prev_char = false;
+ int cc = cursor.column;
+ while (cc < text[cursor.line].length()) {
- bool ischar=_is_text_char(text[cursor.line][cc]);
+ bool ischar = _is_text_char(text[cursor.line][cc]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
cc++;
}
cursor_set_column(cc);
- } else if (cursor.column==text[cursor.line].length()) {
+ } else if (cursor.column == text[cursor.line].length()) {
- if (cursor.line<text.size()-1) {
- cursor_set_line(cursor.line+1);
+ if (cursor.line < text.size() - 1) {
+ cursor_set_line(cursor.line + 1);
cursor_set_column(0);
}
} else {
- cursor_set_column(cursor_get_column()+1);
+ cursor_set_column(cursor_get_column() + 1);
}
if (k.mod.shift)
@@ -2277,7 +2182,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_pre_shift_selection();
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
#ifndef APPLE_STYLE_KEYS
@@ -2295,7 +2200,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
cursor_set_line(0);
else
#endif
- cursor_set_line(cursor_get_line()-1);
+ cursor_set_line(cursor_get_line() - 1);
if (k.mod.shift)
_post_shift_selection();
@@ -2314,7 +2219,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_pre_shift_selection();
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
#ifndef APPLE_STYLE_KEYS
@@ -2329,10 +2234,10 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
if (k.mod.command)
- cursor_set_line(text.size()-1);
+ cursor_set_line(text.size() - 1);
else
#endif
- cursor_set_line(cursor_get_line()+1);
+ cursor_set_line(cursor_get_line() + 1);
if (k.mod.shift)
_post_shift_selection();
@@ -2352,35 +2257,35 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
int curline_len = text[cursor.line].length();
- if (cursor.line==text.size()-1 && cursor.column==curline_len)
+ if (cursor.line == text.size() - 1 && cursor.column == curline_len)
break; //nothing to do
- int next_line=cursor.column<curline_len?cursor.line:cursor.line+1;
+ int next_line = cursor.column < curline_len ? cursor.line : cursor.line + 1;
int next_column;
#ifdef APPLE_STYLE_KEYS
if (k.mod.alt) {
#else
if (k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
} else if (k.mod.command) {
#endif
- int last_line=text.size()-1;
+ int last_line = text.size() - 1;
- int line=cursor.line;
- int column=cursor.column;
+ int line = cursor.line;
+ int column = cursor.column;
- bool prev_char=false;
- bool only_whitespace=true;
+ bool prev_char = false;
+ bool only_whitespace = true;
while (only_whitespace && line < last_line) {
- while (column<text[line].length()) {
- CharType c=text[line][column];
+ while (column < text[line].length()) {
+ CharType c = text[line][column];
if (c != '\t' && c != ' ') {
- only_whitespace=false;
+ only_whitespace = false;
break;
}
@@ -2389,27 +2294,27 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (only_whitespace) {
line++;
- column=0;
+ column = 0;
}
}
- while (column<text[line].length()) {
+ while (column < text[line].length()) {
- bool ischar=_is_text_char(text[line][column]);
+ bool ischar = _is_text_char(text[line][column]);
if (prev_char && !ischar)
break;
- prev_char=ischar;
+ prev_char = ischar;
column++;
}
- next_line=line;
- next_column=column;
+ next_line = line;
+ next_column = column;
} else {
- next_column=cursor.column<curline_len?(cursor.column+1):0;
+ next_column = cursor.column < curline_len ? (cursor.column + 1) : 0;
}
- _remove_text(cursor.line,cursor.column,next_line,next_column);
+ _remove_text(cursor.line, cursor.column, next_line, next_column);
update();
} break;
@@ -2423,7 +2328,6 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
#ifdef APPLE_STYLE_KEYS
case KEY_HOME: {
-
if (k.mod.shift)
_pre_shift_selection();
@@ -2431,43 +2335,41 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_post_shift_selection();
- else if(k.mod.command || k.mod.control)
+ else if (k.mod.command || k.mod.control)
deselect();
} break;
#else
case KEY_HOME: {
-
if (k.mod.shift)
_pre_shift_selection();
if (k.mod.command) {
cursor_set_line(0);
cursor_set_column(0);
- }
- else {
+ } else {
// compute whitespace symbols seq length
int current_line_whitespace_len = 0;
- while( current_line_whitespace_len < text[cursor.line].length() ) {
- CharType c = text[cursor.line][current_line_whitespace_len];
- if( c != '\t' && c != ' ' )
- break;
- current_line_whitespace_len++;
+ while (current_line_whitespace_len < text[cursor.line].length()) {
+ CharType c = text[cursor.line][current_line_whitespace_len];
+ if (c != '\t' && c != ' ')
+ break;
+ current_line_whitespace_len++;
}
- if( cursor_get_column() == current_line_whitespace_len )
- cursor_set_column(0);
+ if (cursor_get_column() == current_line_whitespace_len)
+ cursor_set_column(0);
else
- cursor_set_column(current_line_whitespace_len);
+ cursor_set_column(current_line_whitespace_len);
}
if (k.mod.shift)
_post_shift_selection();
- else if(k.mod.command || k.mod.control)
+ else if (k.mod.command || k.mod.control)
deselect();
_cancel_completion();
- completion_hint="";
+ completion_hint = "";
} break;
#endif
@@ -2484,11 +2386,11 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_pre_shift_selection();
- cursor_set_line(text.size()-1);
+ cursor_set_line(text.size() - 1);
if (k.mod.shift)
_post_shift_selection();
- else if(k.mod.command || k.mod.control)
+ else if (k.mod.command || k.mod.control)
deselect();
} break;
@@ -2499,16 +2401,16 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
_pre_shift_selection();
if (k.mod.command)
- cursor_set_line(text.size()-1);
+ cursor_set_line(text.size() - 1);
cursor_set_column(text[cursor.line].length());
if (k.mod.shift)
_post_shift_selection();
- else if(k.mod.command || k.mod.control)
+ else if (k.mod.command || k.mod.control)
deselect();
_cancel_completion();
- completion_hint="";
+ completion_hint = "";
} break;
#endif
@@ -2524,14 +2426,13 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_pre_shift_selection();
- cursor_set_line(cursor_get_line()-get_visible_rows());
+ cursor_set_line(cursor_get_line() - get_visible_rows());
if (k.mod.shift)
_post_shift_selection();
_cancel_completion();
- completion_hint="";
-
+ completion_hint = "";
} break;
case KEY_KP_3: {
@@ -2546,20 +2447,19 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (k.mod.shift)
_pre_shift_selection();
- cursor_set_line(cursor_get_line()+get_visible_rows());
+ cursor_set_line(cursor_get_line() + get_visible_rows());
if (k.mod.shift)
_post_shift_selection();
_cancel_completion();
- completion_hint="";
-
+ completion_hint = "";
} break;
case KEY_A: {
if (!k.mod.command || k.mod.shift || k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
@@ -2571,7 +2471,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
break;
}
if (!k.mod.command || k.mod.shift || k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
@@ -2581,7 +2481,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
case KEY_C: {
if (!k.mod.command || k.mod.shift || k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
@@ -2591,7 +2491,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
case KEY_Z: {
if (!k.mod.command) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
@@ -2605,7 +2505,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
break;
}
if (!k.mod.command || k.mod.shift || k.mod.alt) {
- scancode_handled=false;
+ scancode_handled = false;
break;
}
@@ -2620,31 +2520,28 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
#endif
query_code_comple();
- scancode_handled=true;
+ scancode_handled = true;
} else {
- scancode_handled=false;
+ scancode_handled = false;
}
} break;
- case KEY_U:{
+ case KEY_U: {
if (!k.mod.command || k.mod.shift) {
- scancode_handled=false;
+ scancode_handled = false;
break;
- }
- else {
+ } else {
if (selection.active) {
int ini = selection.from_line;
int end = selection.to_line;
- for (int i=ini; i<= end; i++)
- {
+ for (int i = ini; i <= end; i++) {
if (text[i][0] == '#')
- _remove_text(i,0,i,1);
+ _remove_text(i, 0, i, 1);
}
- }
- else{
+ } else {
if (text[cursor.line][0] == '#')
- _remove_text(cursor.line,0,cursor.line,1);
+ _remove_text(cursor.line, 0, cursor.line, 1);
}
update();
}
@@ -2652,9 +2549,8 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
default: {
- scancode_handled=false;
+ scancode_handled = false;
} break;
-
}
if (scancode_handled)
@@ -2674,7 +2570,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
}
*/
- if (k.scancode==KEY_INSERT) {
+ if (k.scancode == KEY_INSERT) {
set_insert_mode(!insert_mode);
accept_event();
return;
@@ -2682,7 +2578,7 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
if (!scancode_handled && !k.mod.command) { //for german kbds
- if (k.unicode>=32) {
+ if (k.unicode >= 32) {
if (readonly)
break;
@@ -2697,12 +2593,12 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
}
}
- const CharType chr[2] = {(CharType)k.unicode, 0};
+ const CharType chr[2] = { (CharType)k.unicode, 0 };
- if (completion_hint!="" && k.unicode==')') {
- completion_hint="";
+ if (completion_hint != "" && k.unicode == ')') {
+ completion_hint = "";
}
- if(auto_brace_completion_enabled && _is_pair_symbol(chr[0])) {
+ if (auto_brace_completion_enabled && _is_pair_symbol(chr[0])) {
_consume_pair_symbol(chr[0]);
} else {
_insert_text_at_cursor(chr);
@@ -2724,36 +2620,30 @@ void TextEdit::_gui_input(const InputEvent& p_gui_input) {
return;
} break;
-
}
-
}
-
void TextEdit::_pre_shift_selection() {
+ if (!selection.active || selection.selecting_mode == Selection::MODE_NONE) {
- if (!selection.active || selection.selecting_mode==Selection::MODE_NONE) {
-
- selection.selecting_line=cursor.line;
- selection.selecting_column=cursor.column;
- selection.active=true;
+ selection.selecting_line = cursor.line;
+ selection.selecting_column = cursor.column;
+ selection.active = true;
}
- selection.selecting_mode=Selection::MODE_SHIFT;
+ selection.selecting_mode = Selection::MODE_SHIFT;
}
void TextEdit::_post_shift_selection() {
+ if (selection.active && selection.selecting_mode == Selection::MODE_SHIFT) {
- if (selection.active && selection.selecting_mode==Selection::MODE_SHIFT) {
-
- select(selection.selecting_line,selection.selecting_column,cursor.line,cursor.column);
+ select(selection.selecting_line, selection.selecting_column, cursor.line, cursor.column);
update();
}
-
- selection.selecting_text=true;
+ selection.selecting_text = true;
}
void TextEdit::_scroll_lines_up() {
@@ -2788,109 +2678,106 @@ void TextEdit::_scroll_lines_down() {
/**** TEXT EDIT CORE API ****/
-void TextEdit::_base_insert_text(int p_line, int p_char,const String& p_text,int &r_end_line,int &r_end_column) {
+void TextEdit::_base_insert_text(int p_line, int p_char, const String &p_text, int &r_end_line, int &r_end_column) {
//save for undo...
- ERR_FAIL_INDEX(p_line,text.size());
- ERR_FAIL_COND(p_char<0);
+ ERR_FAIL_INDEX(p_line, text.size());
+ ERR_FAIL_COND(p_char < 0);
/* STEP 1 add spaces if the char is greater than the end of the line */
- while(p_char>text[p_line].length()) {
+ while (p_char > text[p_line].length()) {
- text.set(p_line,text[p_line]+String::chr(' '));
+ text.set(p_line, text[p_line] + String::chr(' '));
}
/* STEP 2 separate dest string in pre and post text */
- String preinsert_text = text[p_line].substr(0,p_char);
- String postinsert_text = text[p_line].substr(p_char,text[p_line].size());
+ String preinsert_text = text[p_line].substr(0, p_char);
+ String postinsert_text = text[p_line].substr(p_char, text[p_line].size());
/* STEP 3 remove \r from source text and separate in substrings */
//buh bye \r and split
- Vector<String> substrings = p_text.replace("\r","").split("\n");
+ Vector<String> substrings = p_text.replace("\r", "").split("\n");
-
- for(int i=0;i<substrings.size();i++) {
+ for (int i = 0; i < substrings.size(); i++) {
//insert the substrings
- if (i==0) {
+ if (i == 0) {
- text.set(p_line,preinsert_text+substrings[i]);
+ text.set(p_line, preinsert_text + substrings[i]);
} else {
- text.insert(p_line+i,substrings[i]);
+ text.insert(p_line + i, substrings[i]);
}
- if (i==substrings.size()-1){
+ if (i == substrings.size() - 1) {
- text.set(p_line+i,text[p_line+i]+postinsert_text);
+ text.set(p_line + i, text[p_line + i] + postinsert_text);
}
}
- r_end_line=p_line+substrings.size()-1;
- r_end_column=text[r_end_line].length()-postinsert_text.length();
+ r_end_line = p_line + substrings.size() - 1;
+ r_end_column = text[r_end_line].length() - postinsert_text.length();
if (!text_changed_dirty && !setting_text) {
if (is_inside_tree())
- MessageQueue::get_singleton()->push_call(this,"_text_changed_emit");
- text_changed_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_text_changed_emit");
+ text_changed_dirty = true;
}
-
}
-String TextEdit::_base_get_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column) const {
+String TextEdit::_base_get_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) const {
- ERR_FAIL_INDEX_V(p_from_line,text.size(),String());
- ERR_FAIL_INDEX_V(p_from_column,text[p_from_line].length()+1,String());
- ERR_FAIL_INDEX_V(p_to_line,text.size(),String());
- ERR_FAIL_INDEX_V(p_to_column,text[p_to_line].length()+1,String());
- ERR_FAIL_COND_V(p_to_line < p_from_line ,String()); // from > to
- ERR_FAIL_COND_V(p_to_line == p_from_line && p_to_column<p_from_column,String()); // from > to
+ ERR_FAIL_INDEX_V(p_from_line, text.size(), String());
+ ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, String());
+ ERR_FAIL_INDEX_V(p_to_line, text.size(), String());
+ ERR_FAIL_INDEX_V(p_to_column, text[p_to_line].length() + 1, String());
+ ERR_FAIL_COND_V(p_to_line < p_from_line, String()); // from > to
+ ERR_FAIL_COND_V(p_to_line == p_from_line && p_to_column < p_from_column, String()); // from > to
String ret;
- for(int i=p_from_line;i<=p_to_line;i++) {
+ for (int i = p_from_line; i <= p_to_line; i++) {
- int begin = (i==p_from_line)?p_from_column:0;
- int end = (i==p_to_line)?p_to_column:text[i].length();
+ int begin = (i == p_from_line) ? p_from_column : 0;
+ int end = (i == p_to_line) ? p_to_column : text[i].length();
- if (i>p_from_line)
- ret+="\n";
- ret+=text[i].substr(begin,end-begin);
+ if (i > p_from_line)
+ ret += "\n";
+ ret += text[i].substr(begin, end - begin);
}
return ret;
}
-void TextEdit::_base_remove_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column) {
-
- ERR_FAIL_INDEX(p_from_line,text.size());
- ERR_FAIL_INDEX(p_from_column,text[p_from_line].length()+1);
- ERR_FAIL_INDEX(p_to_line,text.size());
- ERR_FAIL_INDEX(p_to_column,text[p_to_line].length()+1);
- ERR_FAIL_COND(p_to_line < p_from_line ); // from > to
- ERR_FAIL_COND(p_to_line == p_from_line && p_to_column<p_from_column); // from > to
+void TextEdit::_base_remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) {
+ ERR_FAIL_INDEX(p_from_line, text.size());
+ ERR_FAIL_INDEX(p_from_column, text[p_from_line].length() + 1);
+ ERR_FAIL_INDEX(p_to_line, text.size());
+ ERR_FAIL_INDEX(p_to_column, text[p_to_line].length() + 1);
+ ERR_FAIL_COND(p_to_line < p_from_line); // from > to
+ ERR_FAIL_COND(p_to_line == p_from_line && p_to_column < p_from_column); // from > to
- String pre_text = text[p_from_line].substr(0,p_from_column);
- String post_text = text[p_to_line].substr(p_to_column,text[p_to_line].length());
+ String pre_text = text[p_from_line].substr(0, p_from_column);
+ String post_text = text[p_to_line].substr(p_to_column, text[p_to_line].length());
- for(int i=p_from_line;i<p_to_line;i++) {
+ for (int i = p_from_line; i < p_to_line; i++) {
- text.remove(p_from_line+1);
+ text.remove(p_from_line + 1);
}
- text.set(p_from_line,pre_text+post_text);
+ text.set(p_from_line, pre_text + post_text);
if (!text_changed_dirty && !setting_text) {
if (is_inside_tree())
- MessageQueue::get_singleton()->push_call(this,"_text_changed_emit");
- text_changed_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_text_changed_emit");
+ text_changed_dirty = true;
}
}
-void TextEdit::_insert_text(int p_line, int p_char,const String& p_text,int *r_end_line,int *r_end_column) {
+void TextEdit::_insert_text(int p_line, int p_char, const String &p_text, int *r_end_line, int *r_end_column) {
if (!setting_text)
idle_detect->start();
@@ -2899,53 +2786,52 @@ void TextEdit::_insert_text(int p_line, int p_char,const String& p_text,int *r_e
_clear_redo();
}
- int retline,retchar;
- _base_insert_text(p_line,p_char,p_text,retline,retchar);
+ int retline, retchar;
+ _base_insert_text(p_line, p_char, p_text, retline, retchar);
if (r_end_line)
- *r_end_line=retline;
+ *r_end_line = retline;
if (r_end_column)
- *r_end_column=retchar;
+ *r_end_column = retchar;
if (!undo_enabled)
return;
/* UNDO!! */
TextOperation op;
- op.type=TextOperation::TYPE_INSERT;
- op.from_line=p_line;
- op.from_column=p_char;
- op.to_line=retline;
- op.to_column=retchar;
- op.text=p_text;
- op.version=++version;
- op.chain_forward=false;
- op.chain_backward=false;
+ op.type = TextOperation::TYPE_INSERT;
+ op.from_line = p_line;
+ op.from_column = p_char;
+ op.to_line = retline;
+ op.to_column = retchar;
+ op.text = p_text;
+ op.version = ++version;
+ op.chain_forward = false;
+ op.chain_backward = false;
//see if it shold just be set as current op
- if (current_op.type!=op.type) {
+ if (current_op.type != op.type) {
op.prev_version = get_version();
_push_current_op();
- current_op=op;
+ current_op = op;
return; //set as current op, return
}
//see if it can be merged
- if (current_op.to_line!=p_line || current_op.to_column!=p_char) {
+ if (current_op.to_line != p_line || current_op.to_column != p_char) {
op.prev_version = get_version();
_push_current_op();
- current_op=op;
+ current_op = op;
return; //set as current op, return
}
//merge current op
- current_op.text+=p_text;
- current_op.to_column=retchar;
- current_op.to_line=retline;
- current_op.version=op.version;
-
+ current_op.text += p_text;
+ current_op.to_column = retchar;
+ current_op.to_line = retline;
+ current_op.version = op.version;
}
-void TextEdit::_remove_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column) {
+void TextEdit::_remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) {
if (!setting_text)
idle_detect->start();
@@ -2953,42 +2839,42 @@ void TextEdit::_remove_text(int p_from_line, int p_from_column,int p_to_line,int
String text;
if (undo_enabled) {
_clear_redo();
- text=_base_get_text(p_from_line,p_from_column,p_to_line,p_to_column);
+ text = _base_get_text(p_from_line, p_from_column, p_to_line, p_to_column);
}
- _base_remove_text(p_from_line,p_from_column,p_to_line,p_to_column);
+ _base_remove_text(p_from_line, p_from_column, p_to_line, p_to_column);
if (!undo_enabled)
return;
/* UNDO!! */
TextOperation op;
- op.type=TextOperation::TYPE_REMOVE;
- op.from_line=p_from_line;
- op.from_column=p_from_column;
- op.to_line=p_to_line;
- op.to_column=p_to_column;
- op.text=text;
- op.version=++version;
- op.chain_forward=false;
- op.chain_backward=false;
+ op.type = TextOperation::TYPE_REMOVE;
+ op.from_line = p_from_line;
+ op.from_column = p_from_column;
+ op.to_line = p_to_line;
+ op.to_column = p_to_column;
+ op.text = text;
+ op.version = ++version;
+ op.chain_forward = false;
+ op.chain_backward = false;
//see if it shold just be set as current op
- if (current_op.type!=op.type) {
+ if (current_op.type != op.type) {
op.prev_version = get_version();
_push_current_op();
- current_op=op;
+ current_op = op;
return; //set as current op, return
}
//see if it can be merged
- if (current_op.from_line==p_to_line && current_op.from_column==p_to_column) {
+ if (current_op.from_line == p_to_line && current_op.from_column == p_to_column) {
//basckace or similar
- current_op.text=text+current_op.text;
- current_op.from_line=p_from_line;
- current_op.from_column=p_from_column;
+ current_op.text = text + current_op.text;
+ current_op.from_line = p_from_line;
+ current_op.from_column = p_from_column;
return; //update current op
}
- if (current_op.from_line==p_from_line && current_op.from_column==p_from_column) {
+ if (current_op.from_line == p_from_line && current_op.from_column == p_from_column) {
//current_op.text=text+current_op.text;
//current_op.from_line=p_from_line;
@@ -2998,33 +2884,28 @@ void TextEdit::_remove_text(int p_from_line, int p_from_column,int p_to_line,int
op.prev_version = get_version();
_push_current_op();
- current_op=op;
-
+ current_op = op;
}
+void TextEdit::_insert_text_at_cursor(const String &p_text) {
-void TextEdit::_insert_text_at_cursor(const String& p_text) {
-
- int new_column,new_line;
- _insert_text(cursor.line,cursor.column,p_text,&new_line,&new_column);
+ int new_column, new_line;
+ _insert_text(cursor.line, cursor.column, p_text, &new_line, &new_column);
cursor_set_line(new_line);
cursor_set_column(new_column);
update();
}
-
-
-
int TextEdit::get_char_count() {
- int totalsize=0;
+ int totalsize = 0;
- for (int i=0;i<text.size();i++) {
+ for (int i = 0; i < text.size(); i++) {
- if (i>0)
+ if (i > 0)
totalsize++; // incliude \n
- totalsize+=text[i].length();
+ totalsize += text[i].length();
}
return totalsize; // omit last \n
@@ -3036,40 +2917,39 @@ Size2 TextEdit::get_minimum_size() const {
}
int TextEdit::get_visible_rows() const {
- int total=cache.size.height;
- total-=cache.style_normal->get_minimum_size().height;
- total/=get_row_height();
+ int total = cache.size.height;
+ total -= cache.style_normal->get_minimum_size().height;
+ total /= get_row_height();
return total;
}
void TextEdit::adjust_viewport_to_cursor() {
- if (cursor.line_ofs>cursor.line)
- cursor.line_ofs=cursor.line;
+ if (cursor.line_ofs > cursor.line)
+ cursor.line_ofs = cursor.line;
- int visible_width=cache.size.width-cache.style_normal->get_minimum_size().width-cache.line_number_w-cache.breakpoint_gutter_width;
+ int visible_width = cache.size.width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width;
if (v_scroll->is_visible_in_tree())
- visible_width-=v_scroll->get_combined_minimum_size().width;
- visible_width-=20; // give it a little more space
-
+ visible_width -= v_scroll->get_combined_minimum_size().width;
+ visible_width -= 20; // give it a little more space
//printf("rowofs %i, visrows %i, cursor.line %i\n",cursor.line_ofs,get_visible_rows(),cursor.line);
int visible_rows = get_visible_rows();
if (h_scroll->is_visible_in_tree())
- visible_rows-=((h_scroll->get_combined_minimum_size().height-1)/get_row_height());
+ visible_rows -= ((h_scroll->get_combined_minimum_size().height - 1) / get_row_height());
- if (cursor.line>=(cursor.line_ofs+visible_rows))
- cursor.line_ofs=cursor.line-visible_rows+1;
- if (cursor.line<cursor.line_ofs)
- cursor.line_ofs=cursor.line;
+ if (cursor.line >= (cursor.line_ofs + visible_rows))
+ cursor.line_ofs = cursor.line - visible_rows + 1;
+ if (cursor.line < cursor.line_ofs)
+ cursor.line_ofs = cursor.line;
- int cursor_x = get_column_x_offset( cursor.column, text[cursor.line] );
+ int cursor_x = get_column_x_offset(cursor.column, text[cursor.line]);
- if (cursor_x>(cursor.x_ofs+visible_width))
- cursor.x_ofs=cursor_x-visible_width+1;
+ if (cursor_x > (cursor.x_ofs + visible_width))
+ cursor.x_ofs = cursor_x - visible_width + 1;
if (cursor_x < cursor.x_ofs)
- cursor.x_ofs=cursor_x;
+ cursor.x_ofs = cursor_x;
update();
/*
@@ -3079,98 +2959,89 @@ void TextEdit::adjust_viewport_to_cursor() {
get_range()->set((int)cursor.line_ofs);
*/
-
-
}
void TextEdit::center_viewport_to_cursor() {
- if (cursor.line_ofs>cursor.line)
- cursor.line_ofs=cursor.line;
+ if (cursor.line_ofs > cursor.line)
+ cursor.line_ofs = cursor.line;
- int visible_width=cache.size.width-cache.style_normal->get_minimum_size().width-cache.line_number_w-cache.breakpoint_gutter_width;
+ int visible_width = cache.size.width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width;
if (v_scroll->is_visible_in_tree())
- visible_width-=v_scroll->get_combined_minimum_size().width;
- visible_width-=20; // give it a little more space
+ visible_width -= v_scroll->get_combined_minimum_size().width;
+ visible_width -= 20; // give it a little more space
int visible_rows = get_visible_rows();
if (h_scroll->is_visible_in_tree())
- visible_rows-=((h_scroll->get_combined_minimum_size().height-1)/get_row_height());
+ visible_rows -= ((h_scroll->get_combined_minimum_size().height - 1) / get_row_height());
- int max_ofs = text.size()-(scroll_past_end_of_file_enabled?1:visible_rows);
- cursor.line_ofs=CLAMP(cursor.line-(visible_rows/2),0,max_ofs);
+ int max_ofs = text.size() - (scroll_past_end_of_file_enabled ? 1 : visible_rows);
+ cursor.line_ofs = CLAMP(cursor.line - (visible_rows / 2), 0, max_ofs);
- int cursor_x = get_column_x_offset( cursor.column, text[cursor.line] );
+ int cursor_x = get_column_x_offset(cursor.column, text[cursor.line]);
- if (cursor_x>(cursor.x_ofs+visible_width))
- cursor.x_ofs=cursor_x-visible_width+1;
+ if (cursor_x > (cursor.x_ofs + visible_width))
+ cursor.x_ofs = cursor_x - visible_width + 1;
if (cursor_x < cursor.x_ofs)
- cursor.x_ofs=cursor_x;
+ cursor.x_ofs = cursor_x;
update();
}
void TextEdit::cursor_set_column(int p_col, bool p_adjust_viewport) {
- if (p_col<0)
- p_col=0;
+ if (p_col < 0)
+ p_col = 0;
- cursor.column=p_col;
- if (cursor.column > get_line( cursor.line ).length())
- cursor.column=get_line( cursor.line ).length();
+ cursor.column = p_col;
+ if (cursor.column > get_line(cursor.line).length())
+ cursor.column = get_line(cursor.line).length();
- cursor.last_fit_x=get_column_x_offset(cursor.column,get_line(cursor.line));
+ cursor.last_fit_x = get_column_x_offset(cursor.column, get_line(cursor.line));
if (p_adjust_viewport)
adjust_viewport_to_cursor();
if (!cursor_changed_dirty) {
if (is_inside_tree())
- MessageQueue::get_singleton()->push_call(this,"_cursor_changed_emit");
- cursor_changed_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit");
+ cursor_changed_dirty = true;
}
-
}
-
void TextEdit::cursor_set_line(int p_row, bool p_adjust_viewport) {
if (setting_row)
return;
- setting_row=true;
- if (p_row<0)
- p_row=0;
-
+ setting_row = true;
+ if (p_row < 0)
+ p_row = 0;
- if (p_row>=(int)text.size())
- p_row=(int)text.size()-1;
+ if (p_row >= (int)text.size())
+ p_row = (int)text.size() - 1;
- cursor.line=p_row;
- cursor.column=get_char_pos_for( cursor.last_fit_x, get_line( cursor.line) );
+ cursor.line = p_row;
+ cursor.column = get_char_pos_for(cursor.last_fit_x, get_line(cursor.line));
if (p_adjust_viewport)
adjust_viewport_to_cursor();
- setting_row=false;
-
+ setting_row = false;
if (!cursor_changed_dirty) {
if (is_inside_tree())
- MessageQueue::get_singleton()->push_call(this,"_cursor_changed_emit");
- cursor_changed_dirty=true;
+ MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit");
+ cursor_changed_dirty = true;
}
-
}
-
int TextEdit::cursor_get_column() const {
return cursor.column;
}
-
int TextEdit::cursor_get_line() const {
return cursor.line;
@@ -3191,7 +3062,6 @@ void TextEdit::cursor_set_blink_enabled(const bool p_enabled) {
draw_caret = true;
}
-
float TextEdit::cursor_get_blink_speed() const {
return caret_blink_timer->get_wait_time();
}
@@ -3201,7 +3071,7 @@ void TextEdit::cursor_set_blink_speed(const float p_speed) {
caret_blink_timer->set_wait_time(p_speed);
}
-void TextEdit::cursor_set_block_mode(const bool p_enable){
+void TextEdit::cursor_set_block_mode(const bool p_enable) {
block_caret = p_enable;
update();
}
@@ -3210,134 +3080,125 @@ bool TextEdit::cursor_is_block_mode() const {
return block_caret;
}
-
void TextEdit::_scroll_moved(double p_to_val) {
if (updating_scrolls)
return;
if (h_scroll->is_visible_in_tree())
- cursor.x_ofs=h_scroll->get_value();
+ cursor.x_ofs = h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- cursor.line_ofs=v_scroll->get_value();
+ cursor.line_ofs = v_scroll->get_value();
update();
}
-
-
-
-
int TextEdit::get_row_height() const {
- return cache.font->get_height()+cache.line_spacing;
+ return cache.font->get_height() + cache.line_spacing;
}
-int TextEdit::get_char_pos_for(int p_px,String p_str) const {
+int TextEdit::get_char_pos_for(int p_px, String p_str) const {
- int px=0;
- int c=0;
+ int px = 0;
+ int c = 0;
- int tab_w = cache.font->get_char_size(' ').width*tab_size;
+ int tab_w = cache.font->get_char_size(' ').width * tab_size;
- while (c<p_str.length()) {
+ while (c < p_str.length()) {
- int w=0;
+ int w = 0;
- if (p_str[c]=='\t') {
+ if (p_str[c] == '\t') {
- int left = px%tab_w;
- if (left==0)
- w=tab_w;
+ int left = px % tab_w;
+ if (left == 0)
+ w = tab_w;
else
- w=tab_w-px%tab_w; // is right...
+ w = tab_w - px % tab_w; // is right...
} else {
- w=cache.font->get_char_size(p_str[c],p_str[c+1]).width;
+ w = cache.font->get_char_size(p_str[c], p_str[c + 1]).width;
}
- if (p_px<(px+w/2))
+ if (p_px < (px + w / 2))
break;
- px+=w;
+ px += w;
c++;
}
return c;
}
-int TextEdit::get_column_x_offset(int p_char,String p_str) {
+int TextEdit::get_column_x_offset(int p_char, String p_str) {
- int px=0;
+ int px = 0;
- int tab_w = cache.font->get_char_size(' ').width*tab_size;
+ int tab_w = cache.font->get_char_size(' ').width * tab_size;
- for (int i=0;i<p_char;i++) {
+ for (int i = 0; i < p_char; i++) {
- if (i>=p_str.length())
+ if (i >= p_str.length())
break;
- if (p_str[i]=='\t') {
+ if (p_str[i] == '\t') {
- int left = px%tab_w;
- if (left==0)
- px+=tab_w;
+ int left = px % tab_w;
+ if (left == 0)
+ px += tab_w;
else
- px+=tab_w-px%tab_w; // is right...
+ px += tab_w - px % tab_w; // is right...
} else {
- px+=cache.font->get_char_size(p_str[i],p_str[i+1]).width;
+ px += cache.font->get_char_size(p_str[i], p_str[i + 1]).width;
}
}
return px;
-
}
-void TextEdit::insert_text_at_cursor(const String& p_text) {
+void TextEdit::insert_text_at_cursor(const String &p_text) {
if (selection.active) {
cursor_set_line(selection.from_line);
cursor_set_column(selection.from_column);
- _remove_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
- selection.active=false;
- selection.selecting_mode=Selection::MODE_NONE;
-
+ _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
+ selection.active = false;
+ selection.selecting_mode = Selection::MODE_NONE;
}
_insert_text_at_cursor(p_text);
update();
-
}
-Control::CursorShape TextEdit::get_cursor_shape(const Point2& p_pos) const {
- if (hilighted_word!=String())
+Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const {
+ if (hilighted_word != String())
return CURSOR_POINTING_HAND;
- int gutter=cache.style_normal->get_margin(MARGIN_LEFT)+cache.line_number_w+cache.breakpoint_gutter_width;
- if((completion_active && completion_rect.has_point(p_pos)) || p_pos.x < gutter) {
+ int gutter = cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width;
+ if ((completion_active && completion_rect.has_point(p_pos)) || p_pos.x < gutter) {
return CURSOR_ARROW;
}
return CURSOR_IBEAM;
}
+void TextEdit::set_text(String p_text) {
-void TextEdit::set_text(String p_text){
-
- setting_text=true;
+ setting_text = true;
clear();
_insert_text_at_cursor(p_text);
clear_undo_history();
- cursor.column=0;
- cursor.line=0;
- cursor.x_ofs=0;
- cursor.line_ofs=0;
- cursor.last_fit_x=0;
+ cursor.column = 0;
+ cursor.line = 0;
+ cursor.x_ofs = 0;
+ cursor.line_ofs = 0;
+ cursor.last_fit_x = 0;
cursor_set_line(0);
cursor_set_column(0);
update();
- setting_text=false;
+ setting_text = false;
_text_changed_emit();
//get_range()->set(0);
};
@@ -3345,117 +3206,102 @@ void TextEdit::set_text(String p_text){
String TextEdit::get_text() {
String longthing;
int len = text.size();
- for (int i=0;i<len;i++) {
-
+ for (int i = 0; i < len; i++) {
- longthing+=text[i];
- if (i!=len-1)
- longthing+="\n";
+ longthing += text[i];
+ if (i != len - 1)
+ longthing += "\n";
}
return longthing;
-
};
-
String TextEdit::get_text_for_lookup_completion() {
-
- int row,col;
- _get_mouse_pos(get_local_mouse_pos(), row,col);
-
+ int row, col;
+ _get_mouse_pos(get_local_mouse_pos(), row, col);
String longthing;
int len = text.size();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i==row) {
- longthing+=text[i].substr(0,col);
- longthing+=String::chr(0xFFFF); //not unicode, represents the cursor
- longthing+=text[i].substr(col,text[i].size());
+ if (i == row) {
+ longthing += text[i].substr(0, col);
+ longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ longthing += text[i].substr(col, text[i].size());
} else {
- longthing+=text[i];
+ longthing += text[i];
}
-
- if (i!=len-1)
- longthing+="\n";
+ if (i != len - 1)
+ longthing += "\n";
}
return longthing;
-
}
String TextEdit::get_text_for_completion() {
String longthing;
int len = text.size();
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i==cursor.line) {
- longthing+=text[i].substr(0,cursor.column);
- longthing+=String::chr(0xFFFF); //not unicode, represents the cursor
- longthing+=text[i].substr(cursor.column,text[i].size());
+ if (i == cursor.line) {
+ longthing += text[i].substr(0, cursor.column);
+ longthing += String::chr(0xFFFF); //not unicode, represents the cursor
+ longthing += text[i].substr(cursor.column, text[i].size());
} else {
- longthing+=text[i];
+ longthing += text[i];
}
-
- if (i!=len-1)
- longthing+="\n";
+ if (i != len - 1)
+ longthing += "\n";
}
return longthing;
-
};
-
String TextEdit::get_line(int line) const {
- if (line<0 || line>=text.size())
+ if (line < 0 || line >= text.size())
return "";
- return text[line];
-
+ return text[line];
};
void TextEdit::_clear() {
clear_undo_history();
text.clear();
- cursor.column=0;
- cursor.line=0;
- cursor.x_ofs=0;
- cursor.line_ofs=0;
- cursor.last_fit_x=0;
+ cursor.column = 0;
+ cursor.line = 0;
+ cursor.x_ofs = 0;
+ cursor.line_ofs = 0;
+ cursor.last_fit_x = 0;
}
-
-
void TextEdit::clear() {
- setting_text=true;
+ setting_text = true;
_clear();
- setting_text=false;
-
+ setting_text = false;
};
void TextEdit::set_readonly(bool p_readonly) {
-
- readonly=p_readonly;
+ readonly = p_readonly;
}
void TextEdit::set_wrap(bool p_wrap) {
- wrap=p_wrap;
+ wrap = p_wrap;
}
void TextEdit::set_max_chars(int p_max_chars) {
- max_chars=p_max_chars;
+ max_chars = p_max_chars;
}
void TextEdit::_reset_caret_blink_timer() {
@@ -3476,41 +3322,39 @@ void TextEdit::_toggle_draw_caret() {
void TextEdit::_update_caches() {
- cache.style_normal=get_stylebox("normal");
- cache.style_focus=get_stylebox("focus");
- cache.completion_background_color=get_color("completion_background_color");
- cache.completion_selected_color=get_color("completion_selected_color");
- cache.completion_existing_color=get_color("completion_existing_color");
- cache.completion_font_color=get_color("completion_font_color");
- cache.font=get_font("font");
- cache.caret_color=get_color("caret_color");
- cache.caret_background_color=get_color("caret_background_color");
- cache.line_number_color=get_color("line_number_color");
- cache.font_color=get_color("font_color");
- cache.font_selected_color=get_color("font_selected_color");
- cache.keyword_color=get_color("keyword_color");
- cache.function_color=get_color("function_color");
- cache.member_variable_color=get_color("member_variable_color");
- cache.number_color=get_color("number_color");
- cache.selection_color=get_color("selection_color");
- cache.mark_color=get_color("mark_color");
- cache.current_line_color=get_color("current_line_color");
- cache.line_length_guideline_color=get_color("line_length_guideline_color");
- cache.breakpoint_color=get_color("breakpoint_color");
- cache.brace_mismatch_color=get_color("brace_mismatch_color");
- cache.word_highlighted_color=get_color("word_highlighted_color");
- cache.search_result_color=get_color("search_result_color");
- cache.search_result_border_color=get_color("search_result_border_color");
- cache.symbol_color=get_color("symbol_color");
- cache.background_color=get_color("background_color");
- cache.line_spacing=get_constant("line_spacing");
+ cache.style_normal = get_stylebox("normal");
+ cache.style_focus = get_stylebox("focus");
+ cache.completion_background_color = get_color("completion_background_color");
+ cache.completion_selected_color = get_color("completion_selected_color");
+ cache.completion_existing_color = get_color("completion_existing_color");
+ cache.completion_font_color = get_color("completion_font_color");
+ cache.font = get_font("font");
+ cache.caret_color = get_color("caret_color");
+ cache.caret_background_color = get_color("caret_background_color");
+ cache.line_number_color = get_color("line_number_color");
+ cache.font_color = get_color("font_color");
+ cache.font_selected_color = get_color("font_selected_color");
+ cache.keyword_color = get_color("keyword_color");
+ cache.function_color = get_color("function_color");
+ cache.member_variable_color = get_color("member_variable_color");
+ cache.number_color = get_color("number_color");
+ cache.selection_color = get_color("selection_color");
+ cache.mark_color = get_color("mark_color");
+ cache.current_line_color = get_color("current_line_color");
+ cache.line_length_guideline_color = get_color("line_length_guideline_color");
+ cache.breakpoint_color = get_color("breakpoint_color");
+ cache.brace_mismatch_color = get_color("brace_mismatch_color");
+ cache.word_highlighted_color = get_color("word_highlighted_color");
+ cache.search_result_color = get_color("search_result_color");
+ cache.search_result_border_color = get_color("search_result_border_color");
+ cache.symbol_color = get_color("symbol_color");
+ cache.background_color = get_color("background_color");
+ cache.line_spacing = get_constant("line_spacing");
cache.row_height = cache.font->get_height() + cache.line_spacing;
- cache.tab_icon=get_icon("tab");
+ cache.tab_icon = get_icon("tab");
text.set_font(cache.font);
-
}
-
void TextEdit::clear_colors() {
keywords.clear();
@@ -3518,24 +3362,22 @@ void TextEdit::clear_colors() {
text.clear_caches();
}
-void TextEdit::add_keyword_color(const String& p_keyword,const Color& p_color) {
+void TextEdit::add_keyword_color(const String &p_keyword, const Color &p_color) {
- keywords[p_keyword]=p_color;
+ keywords[p_keyword] = p_color;
update();
-
}
-void TextEdit::add_color_region(const String& p_begin_key,const String& p_end_key,const Color &p_color,bool p_line_only) {
+void TextEdit::add_color_region(const String &p_begin_key, const String &p_end_key, const Color &p_color, bool p_line_only) {
- color_regions.push_back(ColorRegion(p_begin_key,p_end_key,p_color,p_line_only));
+ color_regions.push_back(ColorRegion(p_begin_key, p_end_key, p_color, p_line_only));
text.clear_caches();
update();
-
}
void TextEdit::set_syntax_coloring(bool p_enabled) {
- syntax_coloring=p_enabled;
+ syntax_coloring = p_enabled;
update();
}
@@ -3556,24 +3398,24 @@ void TextEdit::cut() {
OS::get_singleton()->set_clipboard(clipboard);
cursor_set_line(cursor.line);
cursor_set_column(0);
- _remove_text(cursor.line,0,cursor.line,text[cursor.line].length());
+ _remove_text(cursor.line, 0, cursor.line, text[cursor.line].length());
backspace_at_cursor();
update();
- cursor_set_line(cursor.line+1);
+ cursor_set_line(cursor.line + 1);
cut_copy_line = true;
} else {
- String clipboard = _base_get_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
+ String clipboard = _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
OS::get_singleton()->set_clipboard(clipboard);
cursor_set_line(selection.from_line);
cursor_set_column(selection.from_column);
- _remove_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
- selection.active=false;
- selection.selecting_mode=Selection::MODE_NONE;
+ _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
+ selection.active = false;
+ selection.selecting_mode = Selection::MODE_NONE;
update();
cut_copy_line = false;
}
@@ -3585,11 +3427,11 @@ void TextEdit::copy() {
return;
if (!selection.active) {
- String clipboard = _base_get_text(cursor.line,0,cursor.line,text[cursor.line].length());
+ String clipboard = _base_get_text(cursor.line, 0, cursor.line, text[cursor.line].length());
OS::get_singleton()->set_clipboard(clipboard);
cut_copy_line = true;
} else {
- String clipboard = _base_get_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
+ String clipboard = _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
OS::get_singleton()->set_clipboard(clipboard);
cut_copy_line = false;
}
@@ -3601,16 +3443,16 @@ void TextEdit::paste() {
if (selection.active) {
- selection.active=false;
- selection.selecting_mode=Selection::MODE_NONE;
- _remove_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
+ selection.active = false;
+ selection.selecting_mode = Selection::MODE_NONE;
+ _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
cursor_set_line(selection.from_line);
cursor_set_column(selection.from_column);
} else if (cut_copy_line) {
cursor_set_column(0);
- String ins="\n";
+ String ins = "\n";
clipboard += ins;
}
@@ -3620,74 +3462,71 @@ void TextEdit::paste() {
void TextEdit::select_all() {
- if (text.size()==1 && text[0].length()==0)
+ if (text.size() == 1 && text[0].length() == 0)
return;
- selection.active=true;
- selection.from_line=0;
- selection.from_column=0;
- selection.selecting_line=0;
- selection.selecting_column=0;
- selection.to_line=text.size()-1;
- selection.to_column=text[selection.to_line].length();
- selection.selecting_mode=Selection::MODE_SHIFT;
- selection.shiftclick_left=true;
- cursor_set_line( selection.to_line, false );
- cursor_set_column( selection.to_column, false );
+ selection.active = true;
+ selection.from_line = 0;
+ selection.from_column = 0;
+ selection.selecting_line = 0;
+ selection.selecting_column = 0;
+ selection.to_line = text.size() - 1;
+ selection.to_column = text[selection.to_line].length();
+ selection.selecting_mode = Selection::MODE_SHIFT;
+ selection.shiftclick_left = true;
+ cursor_set_line(selection.to_line, false);
+ cursor_set_column(selection.to_column, false);
update();
-
}
-
void TextEdit::deselect() {
- selection.active=false;
+ selection.active = false;
update();
}
-void TextEdit::select(int p_from_line,int p_from_column,int p_to_line,int p_to_column) {
+void TextEdit::select(int p_from_line, int p_from_column, int p_to_line, int p_to_column) {
- if (p_from_line>=text.size())
- p_from_line=text.size()-1;
- if (p_from_column>=text[p_from_line].length())
- p_from_column=text[p_from_line].length();
+ if (p_from_line >= text.size())
+ p_from_line = text.size() - 1;
+ if (p_from_column >= text[p_from_line].length())
+ p_from_column = text[p_from_line].length();
- if (p_to_line>=text.size())
- p_to_line=text.size()-1;
- if (p_to_column>=text[p_to_line].length())
- p_to_column=text[p_to_line].length();
+ if (p_to_line >= text.size())
+ p_to_line = text.size() - 1;
+ if (p_to_column >= text[p_to_line].length())
+ p_to_column = text[p_to_line].length();
- selection.from_line=p_from_line;
- selection.from_column=p_from_column;
- selection.to_line=p_to_line;
- selection.to_column=p_to_column;
+ selection.from_line = p_from_line;
+ selection.from_column = p_from_column;
+ selection.to_line = p_to_line;
+ selection.to_column = p_to_column;
- selection.active=true;
+ selection.active = true;
- if (selection.from_line==selection.to_line) {
+ if (selection.from_line == selection.to_line) {
- if (selection.from_column==selection.to_column) {
+ if (selection.from_column == selection.to_column) {
- selection.active=false;
+ selection.active = false;
- } else if (selection.from_column>selection.to_column) {
+ } else if (selection.from_column > selection.to_column) {
selection.shiftclick_left = false;
- SWAP( selection.from_column, selection.to_column );
+ SWAP(selection.from_column, selection.to_column);
} else {
selection.shiftclick_left = true;
}
- } else if (selection.from_line>selection.to_line) {
+ } else if (selection.from_line > selection.to_line) {
selection.shiftclick_left = false;
- SWAP( selection.from_line, selection.to_line );
- SWAP( selection.from_column, selection.to_column );
+ SWAP(selection.from_line, selection.to_line);
+ SWAP(selection.from_column, selection.to_column);
} else {
selection.shiftclick_left = true;
}
-
update();
}
@@ -3697,27 +3536,23 @@ bool TextEdit::is_selection_active() const {
}
int TextEdit::get_selection_from_line() const {
- ERR_FAIL_COND_V(!selection.active,-1);
+ ERR_FAIL_COND_V(!selection.active, -1);
return selection.from_line;
-
}
int TextEdit::get_selection_from_column() const {
- ERR_FAIL_COND_V(!selection.active,-1);
+ ERR_FAIL_COND_V(!selection.active, -1);
return selection.from_column;
-
}
int TextEdit::get_selection_to_line() const {
- ERR_FAIL_COND_V(!selection.active,-1);
+ ERR_FAIL_COND_V(!selection.active, -1);
return selection.to_line;
-
}
int TextEdit::get_selection_to_column() const {
- ERR_FAIL_COND_V(!selection.active,-1);
+ ERR_FAIL_COND_V(!selection.active, -1);
return selection.to_column;
-
}
String TextEdit::get_selection_text() const {
@@ -3725,30 +3560,29 @@ String TextEdit::get_selection_text() const {
if (!selection.active)
return "";
- return _base_get_text(selection.from_line,selection.from_column,selection.to_line,selection.to_column);
-
+ return _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column);
}
String TextEdit::get_word_under_cursor() const {
int prev_cc = cursor.column;
- while(prev_cc >0) {
- bool is_char = _is_text_char(text[cursor.line][prev_cc-1]);
+ while (prev_cc > 0) {
+ bool is_char = _is_text_char(text[cursor.line][prev_cc - 1]);
if (!is_char)
break;
--prev_cc;
}
int next_cc = cursor.column;
- while(next_cc<text[cursor.line].length()) {
+ while (next_cc < text[cursor.line].length()) {
bool is_char = _is_text_char(text[cursor.line][next_cc]);
- if(!is_char)
+ if (!is_char)
break;
- ++ next_cc;
+ ++next_cc;
}
if (prev_cc == cursor.column || next_cc == cursor.column)
return "";
- return text[cursor.line].substr(prev_cc, next_cc-prev_cc);
+ return text[cursor.line].substr(prev_cc, next_cc - prev_cc);
}
void TextEdit::set_search_text(const String &p_search_text) {
@@ -3783,37 +3617,37 @@ int TextEdit::_get_column_pos_of_word(const String &p_key, const String &p_searc
}
while (col == -1 && p_from_column <= p_search.length()) {
- if (p_search_flags&SEARCH_MATCH_CASE) {
- col = p_search.find(p_key,p_from_column);
+ if (p_search_flags & SEARCH_MATCH_CASE) {
+ col = p_search.find(p_key, p_from_column);
} else {
- col = p_search.findn(p_key,p_from_column);
+ col = p_search.findn(p_key, p_from_column);
}
// whole words only
- if (col != -1 && p_search_flags&SEARCH_WHOLE_WORDS) {
- p_from_column=col;
+ if (col != -1 && p_search_flags & SEARCH_WHOLE_WORDS) {
+ p_from_column = col;
- if (col > 0 && _is_text_char(p_search[col-1])) {
+ if (col > 0 && _is_text_char(p_search[col - 1])) {
col = -1;
- } else if ((col + p_key.length()) < p_search.length() && _is_text_char(p_search[col+p_key.length()])) {
+ } else if ((col + p_key.length()) < p_search.length() && _is_text_char(p_search[col + p_key.length()])) {
col = -1;
}
}
- p_from_column+=1;
+ p_from_column += 1;
}
}
return col;
}
-PoolVector<int> TextEdit::_search_bind(const String &p_key,uint32_t p_search_flags, int p_from_line,int p_from_column) const {
+PoolVector<int> TextEdit::_search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const {
- int col,line;
- if (search(p_key,p_search_flags,p_from_line,p_from_column,col,line)) {
+ int col, line;
+ if (search(p_key, p_search_flags, p_from_line, p_from_column, col, line)) {
PoolVector<int> result;
result.resize(2);
- result.set(0,line);
- result.set(1,col);
+ result.set(0, line);
+ result.set(1, col);
return result;
} else {
@@ -3822,108 +3656,104 @@ PoolVector<int> TextEdit::_search_bind(const String &p_key,uint32_t p_search_fla
}
}
-bool TextEdit::search(const String &p_key,uint32_t p_search_flags, int p_from_line, int p_from_column,int &r_line,int &r_column) const {
+bool TextEdit::search(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column, int &r_line, int &r_column) const {
- if (p_key.length()==0)
+ if (p_key.length() == 0)
return false;
- ERR_FAIL_INDEX_V(p_from_line,text.size(),false);
- ERR_FAIL_INDEX_V(p_from_column,text[p_from_line].length()+1,false);
+ ERR_FAIL_INDEX_V(p_from_line, text.size(), false);
+ ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, false);
//search through the whole documment, but start by current line
- int line=-1;
- int pos=-1;
+ int line = -1;
+ int pos = -1;
- line=p_from_line;
+ line = p_from_line;
- for(int i=0;i<text.size()+1;i++) {
+ for (int i = 0; i < text.size() + 1; i++) {
//backwards is broken...
//int idx=(p_search_flags&SEARCH_BACKWARDS)?(text.size()-i):i; //do backwards seearch
-
- if (line<0) {
- line=text.size()-1;
+ if (line < 0) {
+ line = text.size() - 1;
}
- if (line==text.size()) {
- line=0;
+ if (line == text.size()) {
+ line = 0;
}
String text_line = text[line];
- int from_column=0;
- if (line==p_from_line) {
+ int from_column = 0;
+ if (line == p_from_line) {
- if (i==text.size()) {
+ if (i == text.size()) {
//wrapped
- if (p_search_flags&SEARCH_BACKWARDS) {
- from_column=text_line.length();
+ if (p_search_flags & SEARCH_BACKWARDS) {
+ from_column = text_line.length();
} else {
- from_column=0;
+ from_column = 0;
}
} else {
- from_column=p_from_column;
+ from_column = p_from_column;
}
-
} else {
- if (p_search_flags&SEARCH_BACKWARDS)
- from_column=text_line.length()-1;
+ if (p_search_flags & SEARCH_BACKWARDS)
+ from_column = text_line.length() - 1;
else
- from_column=0;
+ from_column = 0;
}
- pos=-1;
+ pos = -1;
- int pos_from=0;
- int last_pos=-1;
- while ((last_pos=(p_search_flags&SEARCH_MATCH_CASE)?text_line.find(p_key,pos_from):text_line.findn(p_key,pos_from))!=-1) {
+ int pos_from = 0;
+ int last_pos = -1;
+ while ((last_pos = (p_search_flags & SEARCH_MATCH_CASE) ? text_line.find(p_key, pos_from) : text_line.findn(p_key, pos_from)) != -1) {
- if (p_search_flags&SEARCH_BACKWARDS) {
+ if (p_search_flags & SEARCH_BACKWARDS) {
- if (last_pos>from_column)
+ if (last_pos > from_column)
break;
- pos=last_pos;
+ pos = last_pos;
} else {
- if (last_pos>=from_column) {
- pos=last_pos;
+ if (last_pos >= from_column) {
+ pos = last_pos;
break;
}
}
- pos_from=last_pos+p_key.length();
+ pos_from = last_pos + p_key.length();
}
- if (pos!=-1 && (p_search_flags&SEARCH_WHOLE_WORDS)) {
+ if (pos != -1 && (p_search_flags & SEARCH_WHOLE_WORDS)) {
//validate for whole words
- if (pos>0 && _is_text_char(text_line[pos-1]))
- pos=-1;
- else if (_is_text_char(text_line[pos+p_key.length()]))
- pos=-1;
+ if (pos > 0 && _is_text_char(text_line[pos - 1]))
+ pos = -1;
+ else if (_is_text_char(text_line[pos + p_key.length()]))
+ pos = -1;
}
- if (pos!=-1)
+ if (pos != -1)
break;
- if (p_search_flags&SEARCH_BACKWARDS)
+ if (p_search_flags & SEARCH_BACKWARDS)
line--;
else
line++;
-
}
- if (pos==-1) {
- r_line=-1;
- r_column=-1;
+ if (pos == -1) {
+ r_line = -1;
+ r_column = -1;
return false;
}
- r_line=line;
- r_column=pos;
-
+ r_line = line;
+ r_column = pos;
return true;
}
@@ -3931,40 +3761,38 @@ bool TextEdit::search(const String &p_key,uint32_t p_search_flags, int p_from_li
void TextEdit::_cursor_changed_emit() {
emit_signal("cursor_changed");
- cursor_changed_dirty=false;
+ cursor_changed_dirty = false;
}
void TextEdit::_text_changed_emit() {
emit_signal("text_changed");
- text_changed_dirty=false;
+ text_changed_dirty = false;
}
-void TextEdit::set_line_as_marked(int p_line,bool p_marked) {
+void TextEdit::set_line_as_marked(int p_line, bool p_marked) {
- ERR_FAIL_INDEX(p_line,text.size());
- text.set_marked(p_line,p_marked);
+ ERR_FAIL_INDEX(p_line, text.size());
+ text.set_marked(p_line, p_marked);
update();
}
bool TextEdit::is_line_set_as_breakpoint(int p_line) const {
- ERR_FAIL_INDEX_V(p_line,text.size(),false);
+ ERR_FAIL_INDEX_V(p_line, text.size(), false);
return text.is_breakpoint(p_line);
-
}
-void TextEdit::set_line_as_breakpoint(int p_line,bool p_breakpoint) {
-
+void TextEdit::set_line_as_breakpoint(int p_line, bool p_breakpoint) {
- ERR_FAIL_INDEX(p_line,text.size());
- text.set_breakpoint(p_line,p_breakpoint);
+ ERR_FAIL_INDEX(p_line, text.size());
+ text.set_breakpoint(p_line, p_breakpoint);
update();
}
void TextEdit::get_breakpoints(List<int> *p_breakpoints) const {
- for(int i=0;i<text.size();i++) {
+ for (int i = 0; i < text.size(); i++) {
if (text.is_breakpoint(i))
p_breakpoints->push_back(i);
}
@@ -3975,64 +3803,62 @@ int TextEdit::get_line_count() const {
return text.size();
}
-void TextEdit::_do_text_op(const TextOperation& p_op, bool p_reverse) {
+void TextEdit::_do_text_op(const TextOperation &p_op, bool p_reverse) {
- ERR_FAIL_COND(p_op.type==TextOperation::TYPE_NONE);
+ ERR_FAIL_COND(p_op.type == TextOperation::TYPE_NONE);
- bool insert = p_op.type==TextOperation::TYPE_INSERT;
+ bool insert = p_op.type == TextOperation::TYPE_INSERT;
if (p_reverse)
- insert=!insert;
+ insert = !insert;
if (insert) {
int check_line;
int check_column;
- _base_insert_text(p_op.from_line,p_op.from_column,p_op.text,check_line,check_column);
- ERR_FAIL_COND( check_line != p_op.to_line ); // BUG
- ERR_FAIL_COND( check_column != p_op.to_column ); // BUG
+ _base_insert_text(p_op.from_line, p_op.from_column, p_op.text, check_line, check_column);
+ ERR_FAIL_COND(check_line != p_op.to_line); // BUG
+ ERR_FAIL_COND(check_column != p_op.to_column); // BUG
} else {
- _base_remove_text(p_op.from_line,p_op.from_column,p_op.to_line,p_op.to_column);
+ _base_remove_text(p_op.from_line, p_op.from_column, p_op.to_line, p_op.to_column);
}
-
}
void TextEdit::_clear_redo() {
- if (undo_stack_pos==NULL)
+ if (undo_stack_pos == NULL)
return; //nothing to clear
_push_current_op();
- while (undo_stack_pos) {
+ while (undo_stack_pos) {
List<TextOperation>::Element *elem = undo_stack_pos;
- undo_stack_pos=undo_stack_pos->next();
+ undo_stack_pos = undo_stack_pos->next();
undo_stack.erase(elem);
}
}
-
void TextEdit::undo() {
_push_current_op();
- if (undo_stack_pos==NULL) {
+ if (undo_stack_pos == NULL) {
if (!undo_stack.size())
return; //nothing to undo
- undo_stack_pos=undo_stack.back();
+ undo_stack_pos = undo_stack.back();
- } else if (undo_stack_pos==undo_stack.front())
+ } else if (undo_stack_pos == undo_stack.front())
return; // at the bottom of the undo stack
else
- undo_stack_pos=undo_stack_pos->prev();
+ undo_stack_pos = undo_stack_pos->prev();
TextOperation op = undo_stack_pos->get();
_do_text_op(op, true);
- current_op.version=op.prev_version;
- if(undo_stack_pos->get().chain_backward) {
- while(true) {
+ current_op.version = op.prev_version;
+ if (undo_stack_pos->get().chain_backward) {
+ while (true) {
ERR_BREAK(!undo_stack_pos->prev());
undo_stack_pos = undo_stack_pos->prev();
op = undo_stack_pos->get();
@@ -4059,17 +3885,17 @@ void TextEdit::redo() {
_push_current_op();
- if (undo_stack_pos==NULL)
+ if (undo_stack_pos == NULL)
return; //nothing to do.
TextOperation op = undo_stack_pos->get();
_do_text_op(op, false);
current_op.version = op.version;
- if(undo_stack_pos->get().chain_forward) {
+ if (undo_stack_pos->get().chain_forward) {
- while(true) {
+ while (true) {
ERR_BREAK(!undo_stack_pos->next());
- undo_stack_pos=undo_stack_pos->next();
+ undo_stack_pos = undo_stack_pos->next();
op = undo_stack_pos->get();
_do_text_op(op, false);
current_op.version = op.version;
@@ -4079,22 +3905,21 @@ void TextEdit::redo() {
}
cursor_set_line(undo_stack_pos->get().to_line);
cursor_set_column(undo_stack_pos->get().to_column);
- undo_stack_pos=undo_stack_pos->next();
+ undo_stack_pos = undo_stack_pos->next();
update();
}
void TextEdit::clear_undo_history() {
- saved_version=0;
- current_op.type=TextOperation::TYPE_NONE;
- undo_stack_pos=NULL;
+ saved_version = 0;
+ current_op.type = TextOperation::TYPE_NONE;
+ undo_stack_pos = NULL;
undo_stack.clear();
-
}
void TextEdit::begin_complex_operation() {
_push_current_op();
- next_operation_is_complex=true;
+ next_operation_is_complex = true;
}
void TextEdit::end_complex_operation() {
@@ -4102,29 +3927,28 @@ void TextEdit::end_complex_operation() {
_push_current_op();
ERR_FAIL_COND(undo_stack.size() == 0);
- if(undo_stack.back()->get().chain_forward) {
- undo_stack.back()->get().chain_forward=false;
+ if (undo_stack.back()->get().chain_forward) {
+ undo_stack.back()->get().chain_forward = false;
return;
}
- undo_stack.back()->get().chain_backward=true;
+ undo_stack.back()->get().chain_backward = true;
}
void TextEdit::_push_current_op() {
- if (current_op.type==TextOperation::TYPE_NONE)
+ if (current_op.type == TextOperation::TYPE_NONE)
return; // do nothing
- if(next_operation_is_complex) {
- current_op.chain_forward=true;
- next_operation_is_complex=false;
+ if (next_operation_is_complex) {
+ current_op.chain_forward = true;
+ next_operation_is_complex = false;
}
undo_stack.push_back(current_op);
- current_op.type=TextOperation::TYPE_NONE;
- current_op.text="";
- current_op.chain_forward=false;
-
+ current_op.type = TextOperation::TYPE_NONE;
+ current_op.text = "";
+ current_op.chain_forward = false;
}
void TextEdit::set_tab_size(const int p_size) {
@@ -4136,10 +3960,10 @@ void TextEdit::set_tab_size(const int p_size) {
void TextEdit::set_draw_tabs(bool p_draw) {
- draw_tabs=p_draw;
+ draw_tabs = p_draw;
}
-bool TextEdit::is_drawing_tabs() const{
+bool TextEdit::is_drawing_tabs() const {
return draw_tabs;
}
@@ -4162,7 +3986,7 @@ uint32_t TextEdit::get_saved_version() const {
}
void TextEdit::tag_saved_version() {
- saved_version=get_version();
+ saved_version = get_version();
}
int TextEdit::get_v_scroll() const {
@@ -4172,7 +3996,7 @@ int TextEdit::get_v_scroll() const {
void TextEdit::set_v_scroll(int p_scroll) {
v_scroll->set_value(p_scroll);
- cursor.line_ofs=p_scroll;
+ cursor.line_ofs = p_scroll;
}
int TextEdit::get_h_scroll() const {
@@ -4184,11 +4008,11 @@ void TextEdit::set_h_scroll(int p_scroll) {
h_scroll->set_value(p_scroll);
}
-void TextEdit::set_completion(bool p_enabled,const Vector<String>& p_prefixes) {
+void TextEdit::set_completion(bool p_enabled, const Vector<String> &p_prefixes) {
completion_prefixes.clear();
- completion_enabled=p_enabled;
- for(int i=0;i<p_prefixes.size();i++)
+ completion_enabled = p_enabled;
+ for (int i = 0; i < p_prefixes.size(); i++)
completion_prefixes.insert(p_prefixes[i]);
}
@@ -4210,12 +4034,11 @@ void TextEdit::_confirm_completion() {
_cancel_completion();
}
-
void TextEdit::_cancel_code_hint() {
VisualServer::get_singleton()->canvas_item_set_z(get_canvas_item(), 0);
raised_from_completion = false;
- completion_hint="";
+ completion_hint = "";
update();
}
@@ -4226,94 +4049,91 @@ void TextEdit::_cancel_completion() {
if (!completion_active)
return;
- completion_active=false;
+ completion_active = false;
update();
-
}
static bool _is_completable(CharType c) {
- return !_is_symbol(c) || c=='"' || c=='\'';
+ return !_is_symbol(c) || c == '"' || c == '\'';
}
-
void TextEdit::_update_completion_candidates() {
String l = text[cursor.line];
- int cofs = CLAMP(cursor.column,0,l.length());
+ int cofs = CLAMP(cursor.column, 0, l.length());
String s;
//look for keywords first
- bool inquote=false;
- int first_quote=-1;
+ bool inquote = false;
+ int first_quote = -1;
- int c=cofs-1;
- while(c>=0) {
- if (l[c]=='"' || l[c]=='\'') {
- inquote=!inquote;
- if (first_quote==-1)
- first_quote=c;
+ int c = cofs - 1;
+ while (c >= 0) {
+ if (l[c] == '"' || l[c] == '\'') {
+ inquote = !inquote;
+ if (first_quote == -1)
+ first_quote = c;
}
c--;
}
- bool pre_keyword=false;
- bool cancel=false;
+ bool pre_keyword = false;
+ bool cancel = false;
//print_line("inquote: "+itos(inquote)+"first quote "+itos(first_quote)+" cofs-1 "+itos(cofs-1));
- if (!inquote && first_quote==cofs-1) {
+ if (!inquote && first_quote == cofs - 1) {
//no completion here
//print_line("cancel!");
- cancel=true;
- } else if (inquote && first_quote!=-1) {
+ cancel = true;
+ } else if (inquote && first_quote != -1) {
- s=l.substr(first_quote,cofs-first_quote);
+ s = l.substr(first_quote, cofs - first_quote);
//print_line("s: 1"+s);
- } else if (cofs>0 && l[cofs-1]==' ') {
- int kofs=cofs-1;
+ } else if (cofs > 0 && l[cofs - 1] == ' ') {
+ int kofs = cofs - 1;
String kw;
- while (kofs>=0 && l[kofs]==' ')
+ while (kofs >= 0 && l[kofs] == ' ')
kofs--;
- while(kofs>=0 && l[kofs]>32 && _is_completable(l[kofs])) {
- kw=String::chr(l[kofs])+kw;
+ while (kofs >= 0 && l[kofs] > 32 && _is_completable(l[kofs])) {
+ kw = String::chr(l[kofs]) + kw;
kofs--;
}
- pre_keyword=keywords.has(kw);
+ pre_keyword = keywords.has(kw);
//print_line("KW "+kw+"? "+itos(pre_keyword));
} else {
-
- while(cofs>0 && l[cofs-1]>32 && _is_completable(l[cofs-1])) {
- s=String::chr(l[cofs-1])+s;
- if (l[cofs-1]=='\'' || l[cofs-1]=='"' || l[cofs-1]=='$')
+ while (cofs > 0 && l[cofs - 1] > 32 && _is_completable(l[cofs - 1])) {
+ s = String::chr(l[cofs - 1]) + s;
+ if (l[cofs - 1] == '\'' || l[cofs - 1] == '"' || l[cofs - 1] == '$')
break;
cofs--;
}
}
- if (cursor.column > 0 && l[cursor.column - 1] == '(' && !pre_keyword && !completion_strings[0].begins_with("\"")) {
+ if (cursor.column > 0 && l[cursor.column - 1] == '(' && !pre_keyword && !completion_strings[0].begins_with("\"")) {
cancel = true;
}
update();
- if (cancel || (!pre_keyword && s=="" && (cofs==0 || !completion_prefixes.has(String::chr(l[cofs-1]))))) {
+ if (cancel || (!pre_keyword && s == "" && (cofs == 0 || !completion_prefixes.has(String::chr(l[cofs - 1]))))) {
//none to complete, cancel
_cancel_completion();
return;
}
completion_options.clear();
- completion_index=0;
- completion_base=s;
+ completion_index = 0;
+ completion_base = s;
Vector<float> sim_cache;
- for(int i=0;i<completion_strings.size();i++) {
+ for (int i = 0; i < completion_strings.size(); i++) {
if (s == completion_strings[i]) {
// A perfect match, stop completion
_cancel_completion();
@@ -4321,7 +4141,7 @@ void TextEdit::_update_completion_candidates() {
}
if (s.is_subsequence_ofi(completion_strings[i])) {
- // don't remove duplicates if no input is provided
+ // don't remove duplicates if no input is provided
if (s != "" && completion_options.find(completion_strings[i]) != -1) {
continue;
}
@@ -4344,7 +4164,7 @@ void TextEdit::_update_completion_candidates() {
int pos = 0;
do {
comp_sim = sim_cache[pos++];
- } while(pos < comp_size && similarity < comp_sim);
+ } while (pos < comp_size && similarity < comp_sim);
pos = similarity > comp_sim ? pos - 1 : pos; // Pos will be off by one
completion_options.insert(pos, completion_strings[i]);
sim_cache.insert(pos, similarity);
@@ -4352,20 +4172,17 @@ void TextEdit::_update_completion_candidates() {
}
}
-
-
- if (completion_options.size()==0) {
+ if (completion_options.size() == 0) {
//no options to complete, cancel
_cancel_completion();
return;
-
}
// The top of the list is the best match
- completion_current=completion_options[0];
+ completion_current = completion_options[0];
-#if 0 // even there's only one option, user still get the chance to choose using it or not
+#if 0 // even there's only one option, user still get the chance to choose using it or not
if (completion_options.size()==1) {
//one option to complete, just complete it automagically
_confirm_completion();
@@ -4376,37 +4193,33 @@ void TextEdit::_update_completion_candidates() {
}
#endif
- completion_enabled=true;
+ completion_enabled = true;
}
-
-
void TextEdit::query_code_comple() {
String l = text[cursor.line];
- int ofs = CLAMP(cursor.column,0,l.length());
+ int ofs = CLAMP(cursor.column, 0, l.length());
- bool inquote=false;
+ bool inquote = false;
- int c=ofs-1;
- while(c>=0) {
- if (l[c]=='"' || l[c]=='\'')
- inquote=!inquote;
+ int c = ofs - 1;
+ while (c >= 0) {
+ if (l[c] == '"' || l[c] == '\'')
+ inquote = !inquote;
c--;
}
- if (ofs>0 && (inquote || _is_completable(l[ofs-1]) || completion_prefixes.has(String::chr(l[ofs-1]))))
+ if (ofs > 0 && (inquote || _is_completable(l[ofs - 1]) || completion_prefixes.has(String::chr(l[ofs - 1]))))
emit_signal("request_completion");
-
}
-
-void TextEdit::set_code_hint(const String& p_hint) {
+void TextEdit::set_code_hint(const String &p_hint) {
VisualServer::get_singleton()->canvas_item_set_z(get_canvas_item(), 1);
raised_from_completion = true;
- completion_hint=p_hint;
- completion_hint_offset=-0xFFFF;
+ completion_hint = p_hint;
+ completion_hint_offset = -0xFFFF;
update();
}
@@ -4414,119 +4227,112 @@ void TextEdit::code_complete(const Vector<String> &p_strings) {
VisualServer::get_singleton()->canvas_item_set_z(get_canvas_item(), 1);
raised_from_completion = true;
- completion_strings=p_strings;
- completion_active=true;
- completion_current="";
- completion_index=0;
+ completion_strings = p_strings;
+ completion_active = true;
+ completion_current = "";
+ completion_index = 0;
_update_completion_candidates();
//
}
+String TextEdit::get_word_at_pos(const Vector2 &p_pos) const {
-String TextEdit::get_word_at_pos(const Vector2& p_pos) const {
-
- int row,col;
+ int row, col;
_get_mouse_pos(p_pos, row, col);
String s = text[row];
- if (s.length()==0)
+ if (s.length() == 0)
return "";
- int beg=CLAMP(col,0,s.length());
- int end=beg;
+ int beg = CLAMP(col, 0, s.length());
+ int end = beg;
+ if (s[beg] > 32 || beg == s.length()) {
- if (s[beg]>32 || beg==s.length()) {
+ bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
- bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
-
- while(beg>0 && s[beg-1]>32 && (symbol==_is_symbol(s[beg-1]))) {
+ while (beg > 0 && s[beg - 1] > 32 && (symbol == _is_symbol(s[beg - 1]))) {
beg--;
}
- while(end<s.length() && s[end+1]>32 && (symbol==_is_symbol(s[end+1]))) {
+ while (end < s.length() && s[end + 1] > 32 && (symbol == _is_symbol(s[end + 1]))) {
end++;
}
- if (end<s.length())
- end+=1;
+ if (end < s.length())
+ end += 1;
- return s.substr(beg,end-beg);
+ return s.substr(beg, end - beg);
}
return String();
}
-String TextEdit::get_tooltip(const Point2& p_pos) const {
+String TextEdit::get_tooltip(const Point2 &p_pos) const {
if (!tooltip_obj)
return Control::get_tooltip(p_pos);
- int row,col;
+ int row, col;
_get_mouse_pos(p_pos, row, col);
String s = text[row];
- if (s.length()==0)
+ if (s.length() == 0)
return Control::get_tooltip(p_pos);
- int beg=CLAMP(col,0,s.length());
- int end=beg;
-
+ int beg = CLAMP(col, 0, s.length());
+ int end = beg;
- if (s[beg]>32 || beg==s.length()) {
+ if (s[beg] > 32 || beg == s.length()) {
- bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
+ bool symbol = beg < s.length() && _is_symbol(s[beg]); //not sure if right but most editors behave like this
- while(beg>0 && s[beg-1]>32 && (symbol==_is_symbol(s[beg-1]))) {
+ while (beg > 0 && s[beg - 1] > 32 && (symbol == _is_symbol(s[beg - 1]))) {
beg--;
}
- while(end<s.length() && s[end+1]>32 && (symbol==_is_symbol(s[end+1]))) {
+ while (end < s.length() && s[end + 1] > 32 && (symbol == _is_symbol(s[end + 1]))) {
end++;
}
- if (end<s.length())
- end+=1;
+ if (end < s.length())
+ end += 1;
- String tt = tooltip_obj->call(tooltip_func,s.substr(beg,end-beg),tooltip_ud);
+ String tt = tooltip_obj->call(tooltip_func, s.substr(beg, end - beg), tooltip_ud);
return tt;
-
}
return Control::get_tooltip(p_pos);
-
}
-void TextEdit::set_tooltip_request_func(Object *p_obj, const StringName& p_function,const Variant& p_udata) {
+void TextEdit::set_tooltip_request_func(Object *p_obj, const StringName &p_function, const Variant &p_udata) {
- tooltip_obj=p_obj;
- tooltip_func=p_function;
- tooltip_ud=p_udata;
+ tooltip_obj = p_obj;
+ tooltip_func = p_function;
+ tooltip_ud = p_udata;
}
-void TextEdit::set_line(int line, String new_text)
-{
+void TextEdit::set_line(int line, String new_text) {
if (line < 0 || line > text.size())
return;
_remove_text(line, 0, line, text[line].length());
_insert_text(line, 0, new_text);
- if (cursor.line==line) {
- cursor.column=MIN(cursor.column,new_text.length());
+ if (cursor.line == line) {
+ cursor.column = MIN(cursor.column, new_text.length());
}
}
-void TextEdit::insert_at(const String &p_text, int at)
-{
+void TextEdit::insert_at(const String &p_text, int at) {
cursor_set_column(0);
cursor_set_line(at);
- _insert_text(at, 0, p_text+"\n");
+ _insert_text(at, 0, p_text + "\n");
}
void TextEdit::set_show_line_numbers(bool p_show) {
- line_numbers=p_show;
+ line_numbers = p_show;
update();
}
void TextEdit::set_line_numbers_zero_padded(bool p_zero_padded) {
- line_numbers_zero_padded=p_zero_padded;
+ line_numbers_zero_padded = p_zero_padded;
update();
}
@@ -4535,12 +4341,12 @@ bool TextEdit::is_show_line_numbers_enabled() const {
}
void TextEdit::set_show_line_length_guideline(bool p_show) {
- line_length_guideline=p_show;
+ line_length_guideline = p_show;
update();
}
void TextEdit::set_line_length_guideline_column(int p_column) {
- line_length_guideline_col=p_column;
+ line_length_guideline_col = p_column;
update();
}
@@ -4564,12 +4370,12 @@ int TextEdit::get_breakpoint_gutter_width() const {
bool TextEdit::is_text_field() const {
- return true;
+ return true;
}
void TextEdit::menu_option(int p_option) {
- switch( p_option ) {
+ switch (p_option) {
case MENU_CUT: {
if (!readonly) {
cut();
@@ -4594,14 +4400,12 @@ void TextEdit::menu_option(int p_option) {
case MENU_UNDO: {
undo();
} break;
-
};
}
-
void TextEdit::set_select_identifiers_on_hover(bool p_enable) {
- select_identifiers_enabled=p_enable;
+ select_identifiers_enabled = p_enable;
}
bool TextEdit::is_selecting_identifiers_on_hover_enabled() const {
@@ -4619,65 +4423,64 @@ PopupMenu *TextEdit::get_menu() const {
void TextEdit::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("_gui_input"), &TextEdit::_gui_input);
+ ClassDB::bind_method(D_METHOD("_scroll_moved"), &TextEdit::_scroll_moved);
+ ClassDB::bind_method(D_METHOD("_cursor_changed_emit"), &TextEdit::_cursor_changed_emit);
+ ClassDB::bind_method(D_METHOD("_text_changed_emit"), &TextEdit::_text_changed_emit);
+ ClassDB::bind_method(D_METHOD("_push_current_op"), &TextEdit::_push_current_op);
+ ClassDB::bind_method(D_METHOD("_click_selection_held"), &TextEdit::_click_selection_held);
+ ClassDB::bind_method(D_METHOD("_toggle_draw_caret"), &TextEdit::_toggle_draw_caret);
- ClassDB::bind_method(D_METHOD("_gui_input"),&TextEdit::_gui_input);
- ClassDB::bind_method(D_METHOD("_scroll_moved"),&TextEdit::_scroll_moved);
- ClassDB::bind_method(D_METHOD("_cursor_changed_emit"),&TextEdit::_cursor_changed_emit);
- ClassDB::bind_method(D_METHOD("_text_changed_emit"),&TextEdit::_text_changed_emit);
- ClassDB::bind_method(D_METHOD("_push_current_op"),&TextEdit::_push_current_op);
- ClassDB::bind_method(D_METHOD("_click_selection_held"),&TextEdit::_click_selection_held);
- ClassDB::bind_method(D_METHOD("_toggle_draw_caret"),&TextEdit::_toggle_draw_caret);
-
- BIND_CONSTANT( SEARCH_MATCH_CASE );
- BIND_CONSTANT( SEARCH_WHOLE_WORDS );
- BIND_CONSTANT( SEARCH_BACKWARDS );
+ BIND_CONSTANT(SEARCH_MATCH_CASE);
+ BIND_CONSTANT(SEARCH_WHOLE_WORDS);
+ BIND_CONSTANT(SEARCH_BACKWARDS);
/*
ClassDB::bind_method(D_METHOD("delete_char"),&TextEdit::delete_char);
ClassDB::bind_method(D_METHOD("delete_line"),&TextEdit::delete_line);
*/
- ClassDB::bind_method(D_METHOD("set_text","text"),&TextEdit::set_text);
- ClassDB::bind_method(D_METHOD("insert_text_at_cursor","text"),&TextEdit::insert_text_at_cursor);
+ ClassDB::bind_method(D_METHOD("set_text", "text"), &TextEdit::set_text);
+ ClassDB::bind_method(D_METHOD("insert_text_at_cursor", "text"), &TextEdit::insert_text_at_cursor);
- ClassDB::bind_method(D_METHOD("get_line_count"),&TextEdit::get_line_count);
- ClassDB::bind_method(D_METHOD("get_text"),&TextEdit::get_text);
- ClassDB::bind_method(D_METHOD("get_line","line"),&TextEdit::get_line);
+ ClassDB::bind_method(D_METHOD("get_line_count"), &TextEdit::get_line_count);
+ ClassDB::bind_method(D_METHOD("get_text"), &TextEdit::get_text);
+ ClassDB::bind_method(D_METHOD("get_line", "line"), &TextEdit::get_line);
- ClassDB::bind_method(D_METHOD("cursor_set_column","column","adjust_viewport"),&TextEdit::cursor_set_column,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("cursor_set_line","line","adjust_viewport"),&TextEdit::cursor_set_line,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("cursor_set_column", "column", "adjust_viewport"), &TextEdit::cursor_set_column, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("cursor_set_line", "line", "adjust_viewport"), &TextEdit::cursor_set_line, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("cursor_get_column"),&TextEdit::cursor_get_column);
- ClassDB::bind_method(D_METHOD("cursor_get_line"),&TextEdit::cursor_get_line);
- ClassDB::bind_method(D_METHOD("cursor_set_blink_enabled", "enable"),&TextEdit::cursor_set_blink_enabled);
- ClassDB::bind_method(D_METHOD("cursor_get_blink_enabled"),&TextEdit::cursor_get_blink_enabled);
- ClassDB::bind_method(D_METHOD("cursor_set_blink_speed", "blink_speed"),&TextEdit::cursor_set_blink_speed);
- ClassDB::bind_method(D_METHOD("cursor_get_blink_speed"),&TextEdit::cursor_get_blink_speed);
+ ClassDB::bind_method(D_METHOD("cursor_get_column"), &TextEdit::cursor_get_column);
+ ClassDB::bind_method(D_METHOD("cursor_get_line"), &TextEdit::cursor_get_line);
+ ClassDB::bind_method(D_METHOD("cursor_set_blink_enabled", "enable"), &TextEdit::cursor_set_blink_enabled);
+ ClassDB::bind_method(D_METHOD("cursor_get_blink_enabled"), &TextEdit::cursor_get_blink_enabled);
+ ClassDB::bind_method(D_METHOD("cursor_set_blink_speed", "blink_speed"), &TextEdit::cursor_set_blink_speed);
+ ClassDB::bind_method(D_METHOD("cursor_get_blink_speed"), &TextEdit::cursor_get_blink_speed);
ClassDB::bind_method(D_METHOD("cursor_set_block_mode", "enable"), &TextEdit::cursor_set_block_mode);
ClassDB::bind_method(D_METHOD("cursor_is_block_mode"), &TextEdit::cursor_is_block_mode);
- ClassDB::bind_method(D_METHOD("set_readonly","enable"),&TextEdit::set_readonly);
- ClassDB::bind_method(D_METHOD("set_wrap","enable"),&TextEdit::set_wrap);
- ClassDB::bind_method(D_METHOD("set_max_chars","amount"),&TextEdit::set_max_chars);
-
- ClassDB::bind_method(D_METHOD("cut"),&TextEdit::cut);
- ClassDB::bind_method(D_METHOD("copy"),&TextEdit::copy);
- ClassDB::bind_method(D_METHOD("paste"),&TextEdit::paste);
- ClassDB::bind_method(D_METHOD("select_all"),&TextEdit::select_all);
- ClassDB::bind_method(D_METHOD("select","from_line","from_column","to_line","to_column"),&TextEdit::select);
-
- ClassDB::bind_method(D_METHOD("is_selection_active"),&TextEdit::is_selection_active);
- ClassDB::bind_method(D_METHOD("get_selection_from_line"),&TextEdit::get_selection_from_line);
- ClassDB::bind_method(D_METHOD("get_selection_from_column"),&TextEdit::get_selection_from_column);
- ClassDB::bind_method(D_METHOD("get_selection_to_line"),&TextEdit::get_selection_to_line);
- ClassDB::bind_method(D_METHOD("get_selection_to_column"),&TextEdit::get_selection_to_column);
- ClassDB::bind_method(D_METHOD("get_selection_text"),&TextEdit::get_selection_text);
- ClassDB::bind_method(D_METHOD("get_word_under_cursor"),&TextEdit::get_word_under_cursor);
- ClassDB::bind_method(D_METHOD("search","flags","from_line","from_column","to_line","to_column"),&TextEdit::_search_bind);
-
- ClassDB::bind_method(D_METHOD("undo"),&TextEdit::undo);
- ClassDB::bind_method(D_METHOD("redo"),&TextEdit::redo);
- ClassDB::bind_method(D_METHOD("clear_undo_history"),&TextEdit::clear_undo_history);
+ ClassDB::bind_method(D_METHOD("set_readonly", "enable"), &TextEdit::set_readonly);
+ ClassDB::bind_method(D_METHOD("set_wrap", "enable"), &TextEdit::set_wrap);
+ ClassDB::bind_method(D_METHOD("set_max_chars", "amount"), &TextEdit::set_max_chars);
+
+ ClassDB::bind_method(D_METHOD("cut"), &TextEdit::cut);
+ ClassDB::bind_method(D_METHOD("copy"), &TextEdit::copy);
+ ClassDB::bind_method(D_METHOD("paste"), &TextEdit::paste);
+ ClassDB::bind_method(D_METHOD("select_all"), &TextEdit::select_all);
+ ClassDB::bind_method(D_METHOD("select", "from_line", "from_column", "to_line", "to_column"), &TextEdit::select);
+
+ ClassDB::bind_method(D_METHOD("is_selection_active"), &TextEdit::is_selection_active);
+ ClassDB::bind_method(D_METHOD("get_selection_from_line"), &TextEdit::get_selection_from_line);
+ ClassDB::bind_method(D_METHOD("get_selection_from_column"), &TextEdit::get_selection_from_column);
+ ClassDB::bind_method(D_METHOD("get_selection_to_line"), &TextEdit::get_selection_to_line);
+ ClassDB::bind_method(D_METHOD("get_selection_to_column"), &TextEdit::get_selection_to_column);
+ ClassDB::bind_method(D_METHOD("get_selection_text"), &TextEdit::get_selection_text);
+ ClassDB::bind_method(D_METHOD("get_word_under_cursor"), &TextEdit::get_word_under_cursor);
+ ClassDB::bind_method(D_METHOD("search", "flags", "from_line", "from_column", "to_line", "to_column"), &TextEdit::_search_bind);
+
+ ClassDB::bind_method(D_METHOD("undo"), &TextEdit::undo);
+ ClassDB::bind_method(D_METHOD("redo"), &TextEdit::redo);
+ ClassDB::bind_method(D_METHOD("clear_undo_history"), &TextEdit::clear_undo_history);
ClassDB::bind_method(D_METHOD("set_show_line_numbers", "enable"), &TextEdit::set_show_line_numbers);
ClassDB::bind_method(D_METHOD("is_show_line_numbers_enabled"), &TextEdit::is_show_line_numbers_enabled);
@@ -4685,109 +4488,106 @@ void TextEdit::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_highlight_all_occurrences", "enable"), &TextEdit::set_highlight_all_occurrences);
ClassDB::bind_method(D_METHOD("is_highlight_all_occurrences_enabled"), &TextEdit::is_highlight_all_occurrences_enabled);
- ClassDB::bind_method(D_METHOD("set_syntax_coloring","enable"),&TextEdit::set_syntax_coloring);
- ClassDB::bind_method(D_METHOD("is_syntax_coloring_enabled"),&TextEdit::is_syntax_coloring_enabled);
-
+ ClassDB::bind_method(D_METHOD("set_syntax_coloring", "enable"), &TextEdit::set_syntax_coloring);
+ ClassDB::bind_method(D_METHOD("is_syntax_coloring_enabled"), &TextEdit::is_syntax_coloring_enabled);
- ClassDB::bind_method(D_METHOD("add_keyword_color","keyword","color"),&TextEdit::add_keyword_color);
- ClassDB::bind_method(D_METHOD("add_color_region","begin_key","end_key","color","line_only"),&TextEdit::add_color_region,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("clear_colors"),&TextEdit::clear_colors);
- ClassDB::bind_method(D_METHOD("menu_option"),&TextEdit::menu_option);
- ClassDB::bind_method(D_METHOD("get_menu:PopupMenu"),&TextEdit::get_menu);
+ ClassDB::bind_method(D_METHOD("add_keyword_color", "keyword", "color"), &TextEdit::add_keyword_color);
+ ClassDB::bind_method(D_METHOD("add_color_region", "begin_key", "end_key", "color", "line_only"), &TextEdit::add_color_region, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("clear_colors"), &TextEdit::clear_colors);
+ ClassDB::bind_method(D_METHOD("menu_option"), &TextEdit::menu_option);
+ ClassDB::bind_method(D_METHOD("get_menu:PopupMenu"), &TextEdit::get_menu);
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "syntax_highlighting"), "set_syntax_coloring", "is_syntax_coloring_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_line_numbers"), "set_show_line_numbers", "is_show_line_numbers_enabled");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "highlight_all_occurrences"), "set_highlight_all_occurrences", "is_highlight_all_occurrences_enabled");
-
- ADD_GROUP("Caret","caret_");
+ ADD_GROUP("Caret", "caret_");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_block_mode"), "cursor_set_block_mode", "cursor_is_block_mode");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_blink"), "cursor_set_blink_enabled", "cursor_get_blink_enabled");
- ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "caret_blink_speed",PROPERTY_HINT_RANGE,"0.1,10,0.1"), "cursor_set_blink_speed","cursor_get_blink_speed") ;
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "caret_blink_speed", PROPERTY_HINT_RANGE, "0.1,10,0.1"), "cursor_set_blink_speed", "cursor_get_blink_speed");
ADD_SIGNAL(MethodInfo("cursor_changed"));
ADD_SIGNAL(MethodInfo("text_changed"));
ADD_SIGNAL(MethodInfo("request_completion"));
- ADD_SIGNAL(MethodInfo("breakpoint_toggled", PropertyInfo( Variant::INT, "row")));
- ADD_SIGNAL(MethodInfo("symbol_lookup", PropertyInfo(Variant::STRING,"symbol"),PropertyInfo( Variant::INT, "row"),PropertyInfo( Variant::INT, "column")));
-
- BIND_CONSTANT( MENU_CUT );
- BIND_CONSTANT( MENU_COPY );
- BIND_CONSTANT( MENU_PASTE );
- BIND_CONSTANT( MENU_CLEAR );
- BIND_CONSTANT( MENU_SELECT_ALL );
- BIND_CONSTANT( MENU_UNDO );
- BIND_CONSTANT( MENU_MAX );
+ ADD_SIGNAL(MethodInfo("breakpoint_toggled", PropertyInfo(Variant::INT, "row")));
+ ADD_SIGNAL(MethodInfo("symbol_lookup", PropertyInfo(Variant::STRING, "symbol"), PropertyInfo(Variant::INT, "row"), PropertyInfo(Variant::INT, "column")));
+ BIND_CONSTANT(MENU_CUT);
+ BIND_CONSTANT(MENU_COPY);
+ BIND_CONSTANT(MENU_PASTE);
+ BIND_CONSTANT(MENU_CLEAR);
+ BIND_CONSTANT(MENU_SELECT_ALL);
+ BIND_CONSTANT(MENU_UNDO);
+ BIND_CONSTANT(MENU_MAX);
- GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec",3);
+ GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec", 3);
}
-TextEdit::TextEdit() {
+TextEdit::TextEdit() {
- readonly=false;
- setting_row=false;
- draw_tabs=false;
- draw_caret=true;
- max_chars=0;
+ readonly = false;
+ setting_row = false;
+ draw_tabs = false;
+ draw_caret = true;
+ max_chars = 0;
clear();
- wrap=false;
+ wrap = false;
set_focus_mode(FOCUS_ALL);
_update_caches();
- cache.size=Size2(1,1);
- cache.row_height=1;
- cache.line_spacing=1;
- cache.line_number_w=1;
- cache.breakpoint_gutter_width=0;
+ cache.size = Size2(1, 1);
+ cache.row_height = 1;
+ cache.line_spacing = 1;
+ cache.line_number_w = 1;
+ cache.breakpoint_gutter_width = 0;
breakpoint_gutter_width = 0;
- tab_size=4;
+ tab_size = 4;
text.set_tab_size(tab_size);
text.clear();
//text.insert(1,"Mongolia..");
//text.insert(2,"PAIS GENEROSO!!");
text.set_color_regions(&color_regions);
- h_scroll = memnew( HScrollBar );
- v_scroll = memnew( VScrollBar );
+ h_scroll = memnew(HScrollBar);
+ v_scroll = memnew(VScrollBar);
add_child(h_scroll);
add_child(v_scroll);
- updating_scrolls=false;
- selection.active=false;
+ updating_scrolls = false;
+ selection.active = false;
- h_scroll->connect("value_changed", this,"_scroll_moved");
- v_scroll->connect("value_changed", this,"_scroll_moved");
+ h_scroll->connect("value_changed", this, "_scroll_moved");
+ v_scroll->connect("value_changed", this, "_scroll_moved");
- cursor_changed_dirty=false;
- text_changed_dirty=false;
+ cursor_changed_dirty = false;
+ text_changed_dirty = false;
- selection.selecting_mode=Selection::MODE_NONE;
- selection.selecting_line=0;
- selection.selecting_column=0;
- selection.selecting_text=false;
- selection.active=false;
- syntax_coloring=false;
+ selection.selecting_mode = Selection::MODE_NONE;
+ selection.selecting_line = 0;
+ selection.selecting_column = 0;
+ selection.selecting_text = false;
+ selection.active = false;
+ syntax_coloring = false;
- block_caret=false;
- caret_blink_enabled=false;
+ block_caret = false;
+ caret_blink_enabled = false;
caret_blink_timer = memnew(Timer);
add_child(caret_blink_timer);
caret_blink_timer->set_wait_time(0.65);
- caret_blink_timer->connect("timeout", this,"_toggle_draw_caret");
+ caret_blink_timer->connect("timeout", this, "_toggle_draw_caret");
cursor_set_blink_enabled(false);
- idle_detect = memnew( Timer );
+ idle_detect = memnew(Timer);
add_child(idle_detect);
idle_detect->set_one_shot(true);
idle_detect->set_wait_time(GLOBAL_GET("gui/timers/text_edit_idle_detect_sec"));
- idle_detect->connect("timeout", this,"_push_current_op");
+ idle_detect->connect("timeout", this, "_push_current_op");
- click_select_held = memnew( Timer );
+ click_select_held = memnew(Timer);
add_child(click_select_held);
click_select_held->set_wait_time(0.05);
- click_select_held->connect("timeout", this,"_click_selection_held");
+ click_select_held->connect("timeout", this, "_click_selection_held");
#if 0
syntax_coloring=true;
@@ -4807,52 +4607,49 @@ TextEdit::TextEdit() {
#endif
- current_op.type=TextOperation::TYPE_NONE;
- undo_enabled=true;
- undo_stack_pos=NULL;
- setting_text=false;
- last_dblclk=0;
- current_op.version=0;
- version=0;
- saved_version=0;
-
- completion_enabled=false;
- completion_active=false;
- completion_line_ofs=0;
- tooltip_obj=NULL;
- line_numbers=false;
- line_numbers_zero_padded=false;
- line_length_guideline=false;
- line_length_guideline_col=80;
- draw_breakpoint_gutter=false;
- next_operation_is_complex=false;
- scroll_past_end_of_file_enabled=false;
- auto_brace_completion_enabled=false;
- brace_matching_enabled=false;
- highlight_all_occurrences=false;
- auto_indent=false;
+ current_op.type = TextOperation::TYPE_NONE;
+ undo_enabled = true;
+ undo_stack_pos = NULL;
+ setting_text = false;
+ last_dblclk = 0;
+ current_op.version = 0;
+ version = 0;
+ saved_version = 0;
+
+ completion_enabled = false;
+ completion_active = false;
+ completion_line_ofs = 0;
+ tooltip_obj = NULL;
+ line_numbers = false;
+ line_numbers_zero_padded = false;
+ line_length_guideline = false;
+ line_length_guideline_col = 80;
+ draw_breakpoint_gutter = false;
+ next_operation_is_complex = false;
+ scroll_past_end_of_file_enabled = false;
+ auto_brace_completion_enabled = false;
+ brace_matching_enabled = false;
+ highlight_all_occurrences = false;
+ auto_indent = false;
insert_mode = false;
- window_has_focus=true;
- select_identifiers_enabled=false;
+ window_has_focus = true;
+ select_identifiers_enabled = false;
raised_from_completion = false;
- context_menu_enabled=true;
- menu = memnew( PopupMenu );
+ context_menu_enabled = true;
+ menu = memnew(PopupMenu);
add_child(menu);
- menu->add_item(TTR("Cut"),MENU_CUT,KEY_MASK_CMD|KEY_X);
- menu->add_item(TTR("Copy"),MENU_COPY,KEY_MASK_CMD|KEY_C);
- menu->add_item(TTR("Paste"),MENU_PASTE,KEY_MASK_CMD|KEY_V);
+ menu->add_item(TTR("Cut"), MENU_CUT, KEY_MASK_CMD | KEY_X);
+ menu->add_item(TTR("Copy"), MENU_COPY, KEY_MASK_CMD | KEY_C);
+ menu->add_item(TTR("Paste"), MENU_PASTE, KEY_MASK_CMD | KEY_V);
menu->add_separator();
- menu->add_item(TTR("Select All"),MENU_SELECT_ALL,KEY_MASK_CMD|KEY_A);
- menu->add_item(TTR("Clear"),MENU_CLEAR);
+ menu->add_item(TTR("Select All"), MENU_SELECT_ALL, KEY_MASK_CMD | KEY_A);
+ menu->add_item(TTR("Clear"), MENU_CLEAR);
menu->add_separator();
- menu->add_item(TTR("Undo"),MENU_UNDO,KEY_MASK_CMD|KEY_Z);
- menu->connect("id_pressed",this,"menu_option");
-
-
+ menu->add_item(TTR("Undo"), MENU_UNDO, KEY_MASK_CMD | KEY_Z);
+ menu->connect("id_pressed", this, "menu_option");
}
-TextEdit::~TextEdit()
-{
+TextEdit::~TextEdit() {
}
diff --git a/scene/gui/text_edit.h b/scene/gui/text_edit.h
index 437e22ca40..e38d484b0d 100644
--- a/scene/gui/text_edit.h
+++ b/scene/gui/text_edit.h
@@ -30,19 +30,18 @@
#define TEXT_EDIT_H
#include "scene/gui/control.h"
-#include "scene/gui/scroll_bar.h"
#include "scene/gui/popup_menu.h"
+#include "scene/gui/scroll_bar.h"
#include "scene/main/timer.h"
+class TextEdit : public Control {
-class TextEdit : public Control {
-
- GDCLASS( TextEdit, Control );
+ GDCLASS(TextEdit, Control);
struct Cursor {
int last_fit_x;
- int line,column; ///< cursor
- int x_ofs,line_ofs;
+ int line, column; ///< cursor
+ int x_ofs, line_ofs;
} cursor;
struct Selection {
@@ -55,14 +54,13 @@ class TextEdit : public Control {
};
Mode selecting_mode;
- int selecting_line,selecting_column;
+ int selecting_line, selecting_column;
bool selecting_text;
-
bool active;
- int from_line,from_column;
- int to_line,to_column;
+ int from_line, from_column;
+ int to_line, to_column;
bool shiftclick_left;
@@ -113,7 +111,13 @@ class TextEdit : public Control {
String end_key;
bool line_only;
bool eq;
- ColorRegion(const String& p_begin_key="",const String& p_end_key="",const Color &p_color=Color(),bool p_line_only=false) { begin_key=p_begin_key; end_key=p_end_key; color=p_color; line_only=p_line_only || p_end_key==""; eq=begin_key==end_key; }
+ ColorRegion(const String &p_begin_key = "", const String &p_end_key = "", const Color &p_color = Color(), bool p_line_only = false) {
+ begin_key = p_begin_key;
+ end_key = p_end_key;
+ color = p_color;
+ line_only = p_line_only || p_end_key == "";
+ eq = begin_key == end_key;
+ }
};
class Text {
@@ -124,43 +128,42 @@ class TextEdit : public Control {
bool end;
};
- struct Line {
- int width_cache : 24;
- bool marked : 1;
- bool breakpoint : 1;
- Map<int,ColorRegionInfo> region_info;
- String data;
- };
+ struct Line {
+ int width_cache : 24;
+ bool marked : 1;
+ bool breakpoint : 1;
+ Map<int, ColorRegionInfo> region_info;
+ String data;
+ };
+
private:
- const Vector<ColorRegion> *color_regions;
- mutable Vector<Line> text;
- Ref<Font> font;
- int tab_size;
+ const Vector<ColorRegion> *color_regions;
+ mutable Vector<Line> text;
+ Ref<Font> font;
+ int tab_size;
- void _update_line_cache(int p_line) const;
+ void _update_line_cache(int p_line) const;
public:
-
-
void set_tab_size(int p_tab_size);
- void set_font(const Ref<Font>& p_font);
- void set_color_regions(const Vector<ColorRegion>*p_regions) { color_regions=p_regions; }
+ void set_font(const Ref<Font> &p_font);
+ void set_color_regions(const Vector<ColorRegion> *p_regions) { color_regions = p_regions; }
int get_line_width(int p_line) const;
int get_max_width() const;
- const Map<int,ColorRegionInfo>& get_color_region_info(int p_line);
- void set(int p_line,const String& p_string);
- void set_marked(int p_line,bool p_marked) { text[p_line].marked=p_marked; }
+ const Map<int, ColorRegionInfo> &get_color_region_info(int p_line);
+ void set(int p_line, const String &p_string);
+ void set_marked(int p_line, bool p_marked) { text[p_line].marked = p_marked; }
bool is_marked(int p_line) const { return text[p_line].marked; }
- void set_breakpoint(int p_line,bool p_breakpoint) { text[p_line].breakpoint=p_breakpoint; }
+ void set_breakpoint(int p_line, bool p_breakpoint) { text[p_line].breakpoint = p_breakpoint; }
bool is_breakpoint(int p_line) const { return text[p_line].breakpoint; }
- void insert(int p_at,const String& p_text);
+ void insert(int p_at, const String &p_text);
void remove(int p_at);
int size() const { return text.size(); }
void clear();
void clear_caches();
- _FORCE_INLINE_ const String& operator[](int p_line) const { return text[p_line].data; }
- Text() { tab_size=4; }
- };
+ _FORCE_INLINE_ const String &operator[](int p_line) const { return text[p_line].data; }
+ Text() { tab_size = 4; }
+ };
struct TextOperation {
@@ -171,7 +174,7 @@ class TextEdit : public Control {
};
Type type;
- int from_line,from_column;
+ int from_line, from_column;
int to_line, to_column;
String text;
uint32_t prev_version;
@@ -183,14 +186,13 @@ class TextEdit : public Control {
TextOperation current_op;
List<TextOperation> undo_stack;
- List<TextOperation>::Element *undo_stack_pos;
+ List<TextOperation>::Element *undo_stack_pos;
void _clear_redo();
- void _do_text_op(const TextOperation& p_op, bool p_reverse);
-
+ void _do_text_op(const TextOperation &p_op, bool p_reverse);
//syntax coloring
- HashMap<String,Color> keywords;
+ HashMap<String, Color> keywords;
Vector<ColorRegion> color_regions;
@@ -260,7 +262,6 @@ class TextEdit : public Control {
VScrollBar *v_scroll;
bool updating_scrolls;
-
Object *tooltip_obj;
StringName tooltip_func;
Variant tooltip_ud;
@@ -281,8 +282,8 @@ class TextEdit : public Control {
int get_char_count();
- int get_char_pos_for(int p_px,String p_pos) const;
- int get_column_x_offset(int p_column,String p_pos);
+ int get_char_pos_for(int p_px, String p_pos) const;
+ int get_column_x_offset(int p_column, String p_pos);
void adjust_viewport_to_cursor();
void _scroll_moved(double);
@@ -311,13 +312,13 @@ class TextEdit : public Control {
/* super internal api, undo/redo builds on it */
- void _base_insert_text(int p_line, int p_column,const String& p_text,int &r_end_line,int &r_end_column);
- String _base_get_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column) const;
- void _base_remove_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column);
+ void _base_insert_text(int p_line, int p_column, const String &p_text, int &r_end_line, int &r_end_column);
+ String _base_get_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) const;
+ void _base_remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column);
int _get_column_pos_of_word(const String &p_key, const String &p_search, uint32_t p_search_flags, int p_from_column);
- PoolVector<int> _search_bind(const String &p_key,uint32_t p_search_flags, int p_from_line,int p_from_column) const;
+ PoolVector<int> _search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const;
PopupMenu *menu;
@@ -328,13 +329,12 @@ class TextEdit : public Control {
void _update_completion_candidates();
protected:
+ virtual String get_tooltip(const Point2 &p_pos) const;
- virtual String get_tooltip(const Point2& p_pos) const;
-
- void _insert_text(int p_line, int p_column,const String& p_text,int *r_end_line=NULL,int *r_end_char=NULL);
- void _remove_text(int p_from_line, int p_from_column,int p_to_line,int p_to_column);
- void _insert_text_at_cursor(const String& p_text);
- void _gui_input(const InputEvent& p_input);
+ void _insert_text(int p_line, int p_column, const String &p_text, int *r_end_line = NULL, int *r_end_char = NULL);
+ void _remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column);
+ void _insert_text_at_cursor(const String &p_text);
+ void _gui_input(const InputEvent &p_input);
void _notification(int p_what);
void _consume_pair_symbol(CharType ch);
@@ -342,10 +342,7 @@ protected:
static void _bind_methods();
-
-
public:
-
enum MenuItems {
MENU_CUT,
MENU_COPY,
@@ -359,14 +356,14 @@ public:
enum SearchFlags {
- SEARCH_MATCH_CASE=1,
- SEARCH_WHOLE_WORDS=2,
- SEARCH_BACKWARDS=4
+ SEARCH_MATCH_CASE = 1,
+ SEARCH_WHOLE_WORDS = 2,
+ SEARCH_BACKWARDS = 4
};
- virtual CursorShape get_cursor_shape(const Point2& p_pos=Point2i()) const;
+ virtual CursorShape get_cursor_shape(const Point2 &p_pos = Point2i()) const;
- void _get_mouse_pos(const Point2i& p_mouse, int &r_row, int &r_col) const;
+ void _get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) const;
//void delete_char();
//void delete_line();
@@ -375,16 +372,16 @@ public:
void end_complex_operation();
void set_text(String p_text);
- void insert_text_at_cursor(const String& p_text);
- void insert_at(const String& p_text, int at);
+ void insert_text_at_cursor(const String &p_text);
+ void insert_at(const String &p_text, int at);
int get_line_count() const;
- void set_line_as_marked(int p_line,bool p_marked);
- void set_line_as_breakpoint(int p_line,bool p_breakpoint);
+ void set_line_as_marked(int p_line, bool p_marked);
+ void set_line_as_breakpoint(int p_line, bool p_breakpoint);
bool is_line_set_as_breakpoint(int p_line) const;
void get_breakpoints(List<int> *p_breakpoints) const;
String get_text();
String get_line(int line) const;
- void set_line(int line, String new_text);
+ void set_line(int line, String new_text);
void backspace_at_cursor();
void indent_selection_left();
@@ -398,7 +395,7 @@ public:
auto_brace_completion_enabled = p_enabled;
}
inline void set_brace_matching(bool p_enabled) {
- brace_matching_enabled=p_enabled;
+ brace_matching_enabled = p_enabled;
update();
}
inline void set_callhint_settings(bool below, Vector2 offset) {
@@ -409,8 +406,8 @@ public:
void center_viewport_to_cursor();
- void cursor_set_column(int p_col, bool p_adjust_viewport=true);
- void cursor_set_line(int p_row, bool p_adjust_viewport=true);
+ void cursor_set_column(int p_col, bool p_adjust_viewport = true);
+ void cursor_set_line(int p_row, bool p_adjust_viewport = true);
int cursor_get_column() const;
int cursor_get_line() const;
@@ -438,10 +435,10 @@ public:
void copy();
void paste();
void select_all();
- void select(int p_from_line,int p_from_column,int p_to_line,int p_to_column);
+ void select(int p_from_line, int p_from_column, int p_to_line, int p_to_column);
void deselect();
- void set_search_text(const String& p_search_text);
+ void set_search_text(const String &p_search_text);
void set_search_flags(uint32_t p_flags);
void set_current_search_result(int line, int col);
@@ -455,9 +452,9 @@ public:
String get_selection_text() const;
String get_word_under_cursor() const;
- String get_word_at_pos(const Vector2& p_pos) const;
+ String get_word_at_pos(const Vector2 &p_pos) const;
- bool search(const String &p_key,uint32_t p_search_flags, int p_from_line, int p_from_column,int &r_line,int &r_column) const;
+ bool search(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column, int &r_line, int &r_column) const;
void undo();
void redo();
@@ -470,8 +467,8 @@ public:
void set_insert_mode(bool p_enabled);
bool is_insert_mode() const;
- void add_keyword_color(const String& p_keyword,const Color& p_color);
- void add_color_region(const String& p_begin_key=String(),const String& p_end_key=String(),const Color &p_color=Color(),bool p_line_only=false);
+ void add_keyword_color(const String &p_keyword, const Color &p_color);
+ void add_color_region(const String &p_begin_key = String(), const String &p_end_key = String(), const Color &p_color = Color(), bool p_line_only = false);
void clear_colors();
int get_v_scroll() const;
@@ -500,11 +497,11 @@ public:
void set_breakpoint_gutter_width(int p_gutter_width);
int get_breakpoint_gutter_width() const;
- void set_tooltip_request_func(Object *p_obj, const StringName& p_function, const Variant& p_udata);
+ void set_tooltip_request_func(Object *p_obj, const StringName &p_function, const Variant &p_udata);
- void set_completion(bool p_enabled,const Vector<String>& p_prefixes);
+ void set_completion(bool p_enabled, const Vector<String> &p_prefixes);
void code_complete(const Vector<String> &p_strings);
- void set_code_hint(const String& p_hint);
+ void set_code_hint(const String &p_hint);
void query_code_comple();
void set_select_identifiers_on_hover(bool p_enable);
@@ -521,5 +518,4 @@ public:
~TextEdit();
};
-
#endif // TEXT_EDIT_H
diff --git a/scene/gui/texture_button.cpp b/scene/gui/texture_button.cpp
index 2f10de054a..54f09cbf68 100644
--- a/scene/gui/texture_button.cpp
+++ b/scene/gui/texture_button.cpp
@@ -37,27 +37,27 @@ Size2 TextureButton::get_minimum_size() const {
if (pressed.is_null()) {
if (hover.is_null())
if (click_mask.is_null())
- rscale= Size2();
+ rscale = Size2();
else
- rscale= click_mask->get_size();
+ rscale = click_mask->get_size();
else
- rscale= hover->get_size();
+ rscale = hover->get_size();
} else
- rscale=pressed->get_size();
+ rscale = pressed->get_size();
} else
- rscale= normal->get_size();
+ rscale = normal->get_size();
}
return rscale.abs();
}
-bool TextureButton::has_point(const Point2& p_point) const {
+bool TextureButton::has_point(const Point2 &p_point) const {
if (click_mask.is_valid()) {
- Point2i p =p_point;
- if (p.x<0 || p.x>=click_mask->get_size().width || p.y<0 || p.y>=click_mask->get_size().height)
+ Point2i p = p_point;
+ if (p.x < 0 || p.x >= click_mask->get_size().width || p.y < 0 || p.y >= click_mask->get_size().height)
return false;
return click_mask->get_bit(p);
@@ -68,7 +68,7 @@ bool TextureButton::has_point(const Point2& p_point) const {
void TextureButton::_notification(int p_what) {
- switch( p_what ) {
+ switch (p_what) {
case NOTIFICATION_DRAW: {
DrawMode draw_mode = get_draw_mode();
@@ -79,37 +79,37 @@ void TextureButton::_notification(int p_what) {
case DRAW_NORMAL: {
if (normal.is_valid())
- texdraw=normal;
+ texdraw = normal;
} break;
case DRAW_PRESSED: {
if (pressed.is_null()) {
if (hover.is_null()) {
if (normal.is_valid())
- texdraw=normal;
+ texdraw = normal;
} else
- texdraw=hover;
+ texdraw = hover;
} else
- texdraw=pressed;
+ texdraw = pressed;
} break;
case DRAW_HOVER: {
if (hover.is_null()) {
if (pressed.is_valid() && is_pressed())
- texdraw=pressed;
+ texdraw = pressed;
else if (normal.is_valid())
- texdraw=normal;
+ texdraw = normal;
} else
- texdraw=hover;
+ texdraw = hover;
} break;
case DRAW_DISABLED: {
if (disabled.is_null()) {
if (normal.is_valid())
- texdraw=normal;
+ texdraw = normal;
} else
- texdraw=disabled;
+ texdraw = disabled;
} break;
}
@@ -131,12 +131,12 @@ void TextureButton::_notification(int p_what) {
tile = true;
break;
case STRETCH_KEEP_CENTERED:
- ofs = (get_size() - texdraw->get_size())/2;
+ ofs = (get_size() - texdraw->get_size()) / 2;
size = texdraw->get_size();
break;
case STRETCH_KEEP_ASPECT_CENTERED:
case STRETCH_KEEP_ASPECT: {
- Size2 _size=get_size();
+ Size2 _size = get_size();
float tex_width = texdraw->get_width() * _size.height / texdraw->get_height();
float tex_height = _size.height;
@@ -145,34 +145,33 @@ void TextureButton::_notification(int p_what) {
tex_height = texdraw->get_height() * tex_width / texdraw->get_width();
}
- if (stretch_mode==STRETCH_KEEP_ASPECT_CENTERED) {
- ofs.x = (_size.width - tex_width)/2;
- ofs.y = (_size.height - tex_height)/2;
+ if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) {
+ ofs.x = (_size.width - tex_width) / 2;
+ ofs.y = (_size.height - tex_height) / 2;
}
size.width = tex_width;
size.height = tex_height;
} break;
- case STRETCH_KEEP_ASPECT_COVERED:{
+ case STRETCH_KEEP_ASPECT_COVERED: {
size = get_size();
Size2 tex_size = texdraw->get_size();
- Size2 scaleSize(size.width/tex_size.width, size.height/tex_size.height);
- float scale = scaleSize.width > scaleSize.height? scaleSize.width : scaleSize.height;
+ Size2 scaleSize(size.width / tex_size.width, size.height / tex_size.height);
+ float scale = scaleSize.width > scaleSize.height ? scaleSize.width : scaleSize.height;
Size2 scaledTexSize = tex_size * scale;
Point2 ofs = ((scaledTexSize - size) / scale).abs() / 2.0f;
- tex_regin = Rect2(ofs, size/scale);
+ tex_regin = Rect2(ofs, size / scale);
} break;
}
}
if (tile)
- draw_texture_rect(texdraw,Rect2(ofs,size),tile);
+ draw_texture_rect(texdraw, Rect2(ofs, size), tile);
else
draw_texture_rect_region(texdraw, Rect2(ofs, size), tex_regin);
}
if (has_focus() && focused.is_valid()) {
Rect2 drect(Point2(), get_size());
- draw_texture_rect(focused,drect,false);
-
+ draw_texture_rect(focused, drect, false);
};
} break;
}
@@ -180,33 +179,33 @@ void TextureButton::_notification(int p_what) {
void TextureButton::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_normal_texture","texture:Texture"),&TextureButton::set_normal_texture);
- ClassDB::bind_method(D_METHOD("set_pressed_texture","texture:Texture"),&TextureButton::set_pressed_texture);
- ClassDB::bind_method(D_METHOD("set_hover_texture","texture:Texture"),&TextureButton::set_hover_texture);
- ClassDB::bind_method(D_METHOD("set_disabled_texture","texture:Texture"),&TextureButton::set_disabled_texture);
- ClassDB::bind_method(D_METHOD("set_focused_texture","texture:Texture"),&TextureButton::set_focused_texture);
- ClassDB::bind_method(D_METHOD("set_click_mask","mask:BitMap"),&TextureButton::set_click_mask);
- ClassDB::bind_method(D_METHOD("set_expand","p_expand"),&TextureButton::set_expand);
- ClassDB::bind_method(D_METHOD("set_stretch_mode","p_mode"),&TextureButton::set_stretch_mode);
-
- ClassDB::bind_method(D_METHOD("get_normal_texture:Texture"),&TextureButton::get_normal_texture);
- ClassDB::bind_method(D_METHOD("get_pressed_texture:Texture"),&TextureButton::get_pressed_texture);
- ClassDB::bind_method(D_METHOD("get_hover_texture:Texture"),&TextureButton::get_hover_texture);
- ClassDB::bind_method(D_METHOD("get_disabled_texture:Texture"),&TextureButton::get_disabled_texture);
- ClassDB::bind_method(D_METHOD("get_focused_texture:Texture"),&TextureButton::get_focused_texture);
- ClassDB::bind_method(D_METHOD("get_click_mask:BitMap"),&TextureButton::get_click_mask);
- ClassDB::bind_method(D_METHOD("get_expand"),&TextureButton::get_expand);
- ClassDB::bind_method(D_METHOD("get_stretch_mode"),&TextureButton::get_stretch_mode);
-
- ADD_GROUP("Textures","texture_");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_normal_texture", "get_normal_texture");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_pressed",PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_pressed_texture", "get_pressed_texture");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_hover",PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_hover_texture", "get_hover_texture");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_disabled",PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_disabled_texture", "get_disabled_texture");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_focused",PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_focused_texture", "get_focused_texture");
- ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT,"texture_click_mask",PROPERTY_HINT_RESOURCE_TYPE,"BitMap"), "set_click_mask", "get_click_mask") ;
- ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL,"expand",PROPERTY_HINT_RESOURCE_TYPE,"bool"), "set_expand", "get_expand") ;
- ADD_PROPERTYNO(PropertyInfo(Variant::INT,"stretch_mode",PROPERTY_HINT_ENUM,"Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
+ ClassDB::bind_method(D_METHOD("set_normal_texture", "texture:Texture"), &TextureButton::set_normal_texture);
+ ClassDB::bind_method(D_METHOD("set_pressed_texture", "texture:Texture"), &TextureButton::set_pressed_texture);
+ ClassDB::bind_method(D_METHOD("set_hover_texture", "texture:Texture"), &TextureButton::set_hover_texture);
+ ClassDB::bind_method(D_METHOD("set_disabled_texture", "texture:Texture"), &TextureButton::set_disabled_texture);
+ ClassDB::bind_method(D_METHOD("set_focused_texture", "texture:Texture"), &TextureButton::set_focused_texture);
+ ClassDB::bind_method(D_METHOD("set_click_mask", "mask:BitMap"), &TextureButton::set_click_mask);
+ ClassDB::bind_method(D_METHOD("set_expand", "p_expand"), &TextureButton::set_expand);
+ ClassDB::bind_method(D_METHOD("set_stretch_mode", "p_mode"), &TextureButton::set_stretch_mode);
+
+ ClassDB::bind_method(D_METHOD("get_normal_texture:Texture"), &TextureButton::get_normal_texture);
+ ClassDB::bind_method(D_METHOD("get_pressed_texture:Texture"), &TextureButton::get_pressed_texture);
+ ClassDB::bind_method(D_METHOD("get_hover_texture:Texture"), &TextureButton::get_hover_texture);
+ ClassDB::bind_method(D_METHOD("get_disabled_texture:Texture"), &TextureButton::get_disabled_texture);
+ ClassDB::bind_method(D_METHOD("get_focused_texture:Texture"), &TextureButton::get_focused_texture);
+ ClassDB::bind_method(D_METHOD("get_click_mask:BitMap"), &TextureButton::get_click_mask);
+ ClassDB::bind_method(D_METHOD("get_expand"), &TextureButton::get_expand);
+ ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureButton::get_stretch_mode);
+
+ ADD_GROUP("Textures", "texture_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_normal_texture", "get_normal_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_pressed", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_pressed_texture", "get_pressed_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_hover", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_hover_texture", "get_hover_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_disabled", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_disabled_texture", "get_disabled_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_focused", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_focused_texture", "get_focused_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture_click_mask", PROPERTY_HINT_RESOURCE_TYPE, "BitMap"), "set_click_mask", "get_click_mask");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "expand", PROPERTY_HINT_RESOURCE_TYPE, "bool"), "set_expand", "get_expand");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
BIND_CONSTANT(STRETCH_SCALE);
BIND_CONSTANT(STRETCH_TILE);
@@ -215,39 +214,33 @@ void TextureButton::_bind_methods() {
BIND_CONSTANT(STRETCH_KEEP_ASPECT);
BIND_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED);
BIND_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
-
}
+void TextureButton::set_normal_texture(const Ref<Texture> &p_normal) {
-void TextureButton::set_normal_texture(const Ref<Texture>& p_normal) {
-
- normal=p_normal;
+ normal = p_normal;
update();
minimum_size_changed();
-
}
-void TextureButton::set_pressed_texture(const Ref<Texture>& p_pressed) {
+void TextureButton::set_pressed_texture(const Ref<Texture> &p_pressed) {
- pressed=p_pressed;
+ pressed = p_pressed;
update();
-
}
-void TextureButton::set_hover_texture(const Ref<Texture>& p_hover) {
+void TextureButton::set_hover_texture(const Ref<Texture> &p_hover) {
- hover=p_hover;
+ hover = p_hover;
update();
-
}
-void TextureButton::set_disabled_texture(const Ref<Texture>& p_disabled) {
+void TextureButton::set_disabled_texture(const Ref<Texture> &p_disabled) {
- disabled=p_disabled;
+ disabled = p_disabled;
update();
-
}
-void TextureButton::set_click_mask(const Ref<BitMap>& p_click_mask) {
+void TextureButton::set_click_mask(const Ref<BitMap> &p_click_mask) {
- click_mask=p_click_mask;
+ click_mask = p_click_mask;
update();
}
@@ -277,7 +270,7 @@ Ref<Texture> TextureButton::get_focused_texture() const {
return focused;
};
-void TextureButton::set_focused_texture(const Ref<Texture>& p_focused) {
+void TextureButton::set_focused_texture(const Ref<Texture> &p_focused) {
focused = p_focused;
};
diff --git a/scene/gui/texture_button.h b/scene/gui/texture_button.h
index 64103860bf..fc5079dbf9 100644
--- a/scene/gui/texture_button.h
+++ b/scene/gui/texture_button.h
@@ -33,7 +33,7 @@
#include "scene/resources/bit_mask.h"
class TextureButton : public BaseButton {
- GDCLASS( TextureButton, BaseButton );
+ GDCLASS(TextureButton, BaseButton);
public:
enum StretchMode {
@@ -57,20 +57,18 @@ private:
StretchMode stretch_mode;
protected:
-
virtual Size2 get_minimum_size() const;
- virtual bool has_point(const Point2& p_point) const;
+ virtual bool has_point(const Point2 &p_point) const;
void _notification(int p_what);
static void _bind_methods();
public:
-
- void set_normal_texture(const Ref<Texture>& p_normal);
- void set_pressed_texture(const Ref<Texture>& p_pressed);
- void set_hover_texture(const Ref<Texture>& p_hover);
- void set_disabled_texture(const Ref<Texture>& p_disabled);
- void set_focused_texture(const Ref<Texture>& p_focused);
- void set_click_mask(const Ref<BitMap>& p_image);
+ void set_normal_texture(const Ref<Texture> &p_normal);
+ void set_pressed_texture(const Ref<Texture> &p_pressed);
+ void set_hover_texture(const Ref<Texture> &p_hover);
+ void set_disabled_texture(const Ref<Texture> &p_disabled);
+ void set_focused_texture(const Ref<Texture> &p_focused);
+ void set_click_mask(const Ref<BitMap> &p_image);
Ref<Texture> get_normal_texture() const;
Ref<Texture> get_pressed_texture() const;
@@ -88,6 +86,5 @@ public:
TextureButton();
};
-
-VARIANT_ENUM_CAST( TextureButton::StretchMode );
+VARIANT_ENUM_CAST(TextureButton::StretchMode);
#endif // TEXTURE_BUTTON_H
diff --git a/scene/gui/texture_progress.cpp b/scene/gui/texture_progress.cpp
index 3897647502..914d17d2dc 100644
--- a/scene/gui/texture_progress.cpp
+++ b/scene/gui/texture_progress.cpp
@@ -28,33 +28,30 @@
/*************************************************************************/
#include "texture_progress.h"
+void TextureProgress::set_under_texture(const Ref<Texture> &p_texture) {
-void TextureProgress::set_under_texture(const Ref<Texture>& p_texture) {
-
- under=p_texture;
+ under = p_texture;
update();
minimum_size_changed();
}
-Ref<Texture> TextureProgress::get_under_texture() const{
+Ref<Texture> TextureProgress::get_under_texture() const {
return under;
-
}
-void TextureProgress::set_over_texture(const Ref<Texture>& p_texture) {
+void TextureProgress::set_over_texture(const Ref<Texture> &p_texture) {
- over=p_texture;
+ over = p_texture;
update();
if (under.is_null()) {
minimum_size_changed();
}
}
-Ref<Texture> TextureProgress::get_over_texture() const{
+Ref<Texture> TextureProgress::get_over_texture() const {
return over;
-
}
Size2 TextureProgress::get_minimum_size() const {
@@ -66,243 +63,227 @@ Size2 TextureProgress::get_minimum_size() const {
else if (progress.is_valid())
return progress->get_size();
- return Size2(1,1);
+ return Size2(1, 1);
}
-void TextureProgress::set_progress_texture(const Ref<Texture>& p_texture) {
+void TextureProgress::set_progress_texture(const Ref<Texture> &p_texture) {
- progress=p_texture;
+ progress = p_texture;
update();
minimum_size_changed();
}
-Ref<Texture> TextureProgress::get_progress_texture() const{
+Ref<Texture> TextureProgress::get_progress_texture() const {
return progress;
-
}
Point2 TextureProgress::unit_val_to_uv(float val) {
if (progress.is_null())
return Point2();
- if (val<0)
- val+=1;
- if (val>1)
- val-=1;
-
- Point2 p=get_relative_center();
-
- if (val<0.125)
- return Point2(p.x+(1-p.x)*val*8,0);
- if (val<0.25)
- return Point2(1,p.y*(val-0.125)*8);
- if (val<0.375)
- return Point2(1,p.y+(1-p.y)*(val-0.25)*8);
- if (val<0.5)
- return Point2(1-(1-p.x)*(val-0.375)*8,1);
- if (val<0.625)
- return Point2(p.x*(1-(val-0.5)*8),1);
- if (val<0.75)
- return Point2(0,1-((1-p.y)*(val-0.625)*8));
- if (val<0.875)
- return Point2(0,p.y-p.y*(val-0.75)*8);
+ if (val < 0)
+ val += 1;
+ if (val > 1)
+ val -= 1;
+
+ Point2 p = get_relative_center();
+
+ if (val < 0.125)
+ return Point2(p.x + (1 - p.x) * val * 8, 0);
+ if (val < 0.25)
+ return Point2(1, p.y * (val - 0.125) * 8);
+ if (val < 0.375)
+ return Point2(1, p.y + (1 - p.y) * (val - 0.25) * 8);
+ if (val < 0.5)
+ return Point2(1 - (1 - p.x) * (val - 0.375) * 8, 1);
+ if (val < 0.625)
+ return Point2(p.x * (1 - (val - 0.5) * 8), 1);
+ if (val < 0.75)
+ return Point2(0, 1 - ((1 - p.y) * (val - 0.625) * 8));
+ if (val < 0.875)
+ return Point2(0, p.y - p.y * (val - 0.75) * 8);
else
- return Point2(p.x*(val-0.875)*8,0);
+ return Point2(p.x * (val - 0.875) * 8, 0);
}
-Point2 TextureProgress::get_relative_center()
-{
+Point2 TextureProgress::get_relative_center() {
if (progress.is_null())
return Point2();
- Point2 p = progress->get_size()/2;
- p+=rad_center_off;
- p.x/=progress->get_width();
- p.y/=progress->get_height();
- p.x=CLAMP(p.x,0,1);
- p.y=CLAMP(p.y,0,1);
+ Point2 p = progress->get_size() / 2;
+ p += rad_center_off;
+ p.x /= progress->get_width();
+ p.y /= progress->get_height();
+ p.x = CLAMP(p.x, 0, 1);
+ p.y = CLAMP(p.y, 0, 1);
return p;
}
-void TextureProgress::_notification(int p_what){
- const float corners[12]={-0.125,-0.375,-0.625,-0.875,0.125,0.375,0.625,0.875,1.125,1.375,1.625,1.875};
- switch(p_what) {
+void TextureProgress::_notification(int p_what) {
+ const float corners[12] = { -0.125, -0.375, -0.625, -0.875, 0.125, 0.375, 0.625, 0.875, 1.125, 1.375, 1.625, 1.875 };
+ switch (p_what) {
case NOTIFICATION_DRAW: {
-
if (under.is_valid())
- draw_texture(under,Point2());
+ draw_texture(under, Point2());
if (progress.is_valid()) {
Size2 s = progress->get_size();
switch (mode) {
- case FILL_LEFT_TO_RIGHT: {
- Rect2 region=Rect2(Point2(),Size2(s.x*get_as_ratio(),s.y));
- draw_texture_rect_region(progress,region,region);
- } break;
- case FILL_RIGHT_TO_LEFT: {
- Rect2 region=Rect2(Point2(s.x-s.x*get_as_ratio(),0),Size2(s.x*get_as_ratio(),s.y));
- draw_texture_rect_region(progress,region,region);
- } break;
- case FILL_TOP_TO_BOTTOM: {
- Rect2 region=Rect2(Point2(),Size2(s.x,s.y*get_as_ratio()));
- draw_texture_rect_region(progress,region,region);
- } break;
- case FILL_BOTTOM_TO_TOP: {
- Rect2 region=Rect2(Point2(0,s.y-s.y*get_as_ratio()),Size2(s.x,s.y*get_as_ratio()));
- draw_texture_rect_region(progress,region,region);
- } break;
- case FILL_CLOCKWISE:
- case FILL_COUNTER_CLOCKWISE: {
- float val=get_as_ratio()*rad_max_degrees/360;
- if (val==1) {
- Rect2 region=Rect2(Point2(),s);
- draw_texture_rect_region(progress,region,region);
- } else if (val!=0) {
- Array pts;
- float direction=mode==FILL_CLOCKWISE?1:-1;
- float start=rad_init_angle/360;
- float end=start+direction*val;
- pts.append(start);
- pts.append(end);
- float from=MIN(start,end);
- float to=MAX(start,end);
- for (int i=0;i<12;i++)
- if (corners[i]>from&&corners[i]<to)
- pts.append(corners[i]);
- pts.sort();
- Vector<Point2> uvs;
- Vector<Point2> points;
- uvs.push_back(get_relative_center());
- points.push_back(Point2(s.x*get_relative_center().x,s.y*get_relative_center().y));
- for (int i=0;i<pts.size();i++) {
- Point2 uv=unit_val_to_uv(pts[i]);
- if (uvs.find(uv)>=0)
- continue;
- uvs.push_back(uv);
- points.push_back(Point2(uv.x*s.x,uv.y*s.y));
+ case FILL_LEFT_TO_RIGHT: {
+ Rect2 region = Rect2(Point2(), Size2(s.x * get_as_ratio(), s.y));
+ draw_texture_rect_region(progress, region, region);
+ } break;
+ case FILL_RIGHT_TO_LEFT: {
+ Rect2 region = Rect2(Point2(s.x - s.x * get_as_ratio(), 0), Size2(s.x * get_as_ratio(), s.y));
+ draw_texture_rect_region(progress, region, region);
+ } break;
+ case FILL_TOP_TO_BOTTOM: {
+ Rect2 region = Rect2(Point2(), Size2(s.x, s.y * get_as_ratio()));
+ draw_texture_rect_region(progress, region, region);
+ } break;
+ case FILL_BOTTOM_TO_TOP: {
+ Rect2 region = Rect2(Point2(0, s.y - s.y * get_as_ratio()), Size2(s.x, s.y * get_as_ratio()));
+ draw_texture_rect_region(progress, region, region);
+ } break;
+ case FILL_CLOCKWISE:
+ case FILL_COUNTER_CLOCKWISE: {
+ float val = get_as_ratio() * rad_max_degrees / 360;
+ if (val == 1) {
+ Rect2 region = Rect2(Point2(), s);
+ draw_texture_rect_region(progress, region, region);
+ } else if (val != 0) {
+ Array pts;
+ float direction = mode == FILL_CLOCKWISE ? 1 : -1;
+ float start = rad_init_angle / 360;
+ float end = start + direction * val;
+ pts.append(start);
+ pts.append(end);
+ float from = MIN(start, end);
+ float to = MAX(start, end);
+ for (int i = 0; i < 12; i++)
+ if (corners[i] > from && corners[i] < to)
+ pts.append(corners[i]);
+ pts.sort();
+ Vector<Point2> uvs;
+ Vector<Point2> points;
+ uvs.push_back(get_relative_center());
+ points.push_back(Point2(s.x * get_relative_center().x, s.y * get_relative_center().y));
+ for (int i = 0; i < pts.size(); i++) {
+ Point2 uv = unit_val_to_uv(pts[i]);
+ if (uvs.find(uv) >= 0)
+ continue;
+ uvs.push_back(uv);
+ points.push_back(Point2(uv.x * s.x, uv.y * s.y));
+ }
+ draw_polygon(points, Vector<Color>(), uvs, progress);
}
- draw_polygon(points,Vector<Color>(),uvs,progress);
- }
- if (get_tree()->is_editor_hint()) {
- Point2 p=progress->get_size();
- p.x*=get_relative_center().x;
- p.y*=get_relative_center().y;
- p=p.floor();
- draw_line(p-Point2(8,0),p+Point2(8,0),Color(0.9,0.5,0.5),2);
- draw_line(p-Point2(0,8),p+Point2(0,8),Color(0.9,0.5,0.5),2);
- }
- } break;
- default:
- draw_texture_rect_region(progress,Rect2(Point2(),Size2(s.x*get_as_ratio(),s.y)),Rect2(Point2(),Size2(s.x*get_as_ratio(),s.y)));
+ if (get_tree()->is_editor_hint()) {
+ Point2 p = progress->get_size();
+ p.x *= get_relative_center().x;
+ p.y *= get_relative_center().y;
+ p = p.floor();
+ draw_line(p - Point2(8, 0), p + Point2(8, 0), Color(0.9, 0.5, 0.5), 2);
+ draw_line(p - Point2(0, 8), p + Point2(0, 8), Color(0.9, 0.5, 0.5), 2);
+ }
+ } break;
+ default:
+ draw_texture_rect_region(progress, Rect2(Point2(), Size2(s.x * get_as_ratio(), s.y)), Rect2(Point2(), Size2(s.x * get_as_ratio(), s.y)));
}
-
-
}
if (over.is_valid())
- draw_texture(over,Point2());
+ draw_texture(over, Point2());
} break;
}
}
-void TextureProgress::set_fill_mode(int p_fill)
-{
- ERR_FAIL_INDEX(p_fill,6);
- mode=(FillMode)p_fill;
+void TextureProgress::set_fill_mode(int p_fill) {
+ ERR_FAIL_INDEX(p_fill, 6);
+ mode = (FillMode)p_fill;
update();
}
-int TextureProgress::get_fill_mode()
-{
+int TextureProgress::get_fill_mode() {
return mode;
}
-void TextureProgress::set_radial_initial_angle(float p_angle)
-{
- while(p_angle>360)
- p_angle-=360;
- while (p_angle<0)
- p_angle+=360;
- rad_init_angle=p_angle;
+void TextureProgress::set_radial_initial_angle(float p_angle) {
+ while (p_angle > 360)
+ p_angle -= 360;
+ while (p_angle < 0)
+ p_angle += 360;
+ rad_init_angle = p_angle;
update();
}
-float TextureProgress::get_radial_initial_angle()
-{
+float TextureProgress::get_radial_initial_angle() {
return rad_init_angle;
}
-void TextureProgress::set_fill_degrees(float p_angle)
-{
- rad_max_degrees=CLAMP(p_angle,0,360);
+void TextureProgress::set_fill_degrees(float p_angle) {
+ rad_max_degrees = CLAMP(p_angle, 0, 360);
update();
}
-float TextureProgress::get_fill_degrees()
-{
+float TextureProgress::get_fill_degrees() {
return rad_max_degrees;
}
-void TextureProgress::set_radial_center_offset(const Point2 &p_off)
-{
- rad_center_off=p_off;
+void TextureProgress::set_radial_center_offset(const Point2 &p_off) {
+ rad_center_off = p_off;
update();
}
-Point2 TextureProgress::get_radial_center_offset()
-{
+Point2 TextureProgress::get_radial_center_offset() {
return rad_center_off;
}
void TextureProgress::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_under_texture","tex"),&TextureProgress::set_under_texture);
- ClassDB::bind_method(D_METHOD("get_under_texture"),&TextureProgress::get_under_texture);
+ ClassDB::bind_method(D_METHOD("set_under_texture", "tex"), &TextureProgress::set_under_texture);
+ ClassDB::bind_method(D_METHOD("get_under_texture"), &TextureProgress::get_under_texture);
- ClassDB::bind_method(D_METHOD("set_progress_texture","tex"),&TextureProgress::set_progress_texture);
- ClassDB::bind_method(D_METHOD("get_progress_texture"),&TextureProgress::get_progress_texture);
+ ClassDB::bind_method(D_METHOD("set_progress_texture", "tex"), &TextureProgress::set_progress_texture);
+ ClassDB::bind_method(D_METHOD("get_progress_texture"), &TextureProgress::get_progress_texture);
- ClassDB::bind_method(D_METHOD("set_over_texture","tex"),&TextureProgress::set_over_texture);
- ClassDB::bind_method(D_METHOD("get_over_texture"),&TextureProgress::get_over_texture);
+ ClassDB::bind_method(D_METHOD("set_over_texture", "tex"), &TextureProgress::set_over_texture);
+ ClassDB::bind_method(D_METHOD("get_over_texture"), &TextureProgress::get_over_texture);
- ClassDB::bind_method(D_METHOD("set_fill_mode","mode"),&TextureProgress::set_fill_mode);
+ ClassDB::bind_method(D_METHOD("set_fill_mode", "mode"), &TextureProgress::set_fill_mode);
ClassDB::bind_method(D_METHOD("get_fill_mode"), &TextureProgress::get_fill_mode);
- ClassDB::bind_method(D_METHOD("set_radial_initial_angle","mode"),&TextureProgress::set_radial_initial_angle);
+ ClassDB::bind_method(D_METHOD("set_radial_initial_angle", "mode"), &TextureProgress::set_radial_initial_angle);
ClassDB::bind_method(D_METHOD("get_radial_initial_angle"), &TextureProgress::get_radial_initial_angle);
- ClassDB::bind_method(D_METHOD("set_radial_center_offset","mode"),&TextureProgress::set_radial_center_offset);
+ ClassDB::bind_method(D_METHOD("set_radial_center_offset", "mode"), &TextureProgress::set_radial_center_offset);
ClassDB::bind_method(D_METHOD("get_radial_center_offset"), &TextureProgress::get_radial_center_offset);
- ClassDB::bind_method(D_METHOD("set_fill_degrees","mode"),&TextureProgress::set_fill_degrees);
+ ClassDB::bind_method(D_METHOD("set_fill_degrees", "mode"), &TextureProgress::set_fill_degrees);
ClassDB::bind_method(D_METHOD("get_fill_degrees"), &TextureProgress::get_fill_degrees);
- ADD_GROUP("Textures","texture_");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture_under",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_under_texture","get_under_texture");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture_over",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_over_texture","get_over_texture");
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"texture_progress",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_progress_texture","get_progress_texture");
- ADD_PROPERTYNZ( PropertyInfo(Variant::INT,"fill_mode",PROPERTY_HINT_ENUM,"Left to Right,Right to Left,Top to Bottom,Bottom to Top,Clockwise,Counter Clockwise"),"set_fill_mode","get_fill_mode");
- ADD_GROUP("Radial Fill","radial_");
- ADD_PROPERTYNZ( PropertyInfo(Variant::REAL,"radial_initial_angle",PROPERTY_HINT_RANGE,"0.0,360.0,0.1,slider"),"set_radial_initial_angle","get_radial_initial_angle");
- ADD_PROPERTYNZ( PropertyInfo(Variant::REAL,"radial_fill_degrees",PROPERTY_HINT_RANGE,"0.0,360.0,0.1,slider"),"set_fill_degrees","get_fill_degrees");
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"radial_center_offset"),"set_radial_center_offset","get_radial_center_offset");
-
- BIND_CONSTANT( FILL_LEFT_TO_RIGHT );
- BIND_CONSTANT( FILL_RIGHT_TO_LEFT );
- BIND_CONSTANT( FILL_TOP_TO_BOTTOM );
- BIND_CONSTANT( FILL_BOTTOM_TO_TOP );
- BIND_CONSTANT( FILL_CLOCKWISE );
- BIND_CONSTANT( FILL_COUNTER_CLOCKWISE );
-
+ ADD_GROUP("Textures", "texture_");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_under", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_under_texture", "get_under_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_over", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_over_texture", "get_over_texture");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture_progress", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_progress_texture", "get_progress_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "fill_mode", PROPERTY_HINT_ENUM, "Left to Right,Right to Left,Top to Bottom,Bottom to Top,Clockwise,Counter Clockwise"), "set_fill_mode", "get_fill_mode");
+ ADD_GROUP("Radial Fill", "radial_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "radial_initial_angle", PROPERTY_HINT_RANGE, "0.0,360.0,0.1,slider"), "set_radial_initial_angle", "get_radial_initial_angle");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "radial_fill_degrees", PROPERTY_HINT_RANGE, "0.0,360.0,0.1,slider"), "set_fill_degrees", "get_fill_degrees");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "radial_center_offset"), "set_radial_center_offset", "get_radial_center_offset");
+
+ BIND_CONSTANT(FILL_LEFT_TO_RIGHT);
+ BIND_CONSTANT(FILL_RIGHT_TO_LEFT);
+ BIND_CONSTANT(FILL_TOP_TO_BOTTOM);
+ BIND_CONSTANT(FILL_BOTTOM_TO_TOP);
+ BIND_CONSTANT(FILL_CLOCKWISE);
+ BIND_CONSTANT(FILL_COUNTER_CLOCKWISE);
}
-
-TextureProgress::TextureProgress()
-{
- mode=FILL_LEFT_TO_RIGHT;
- rad_init_angle=0;
- rad_center_off=Point2();
- rad_max_degrees=360;
+TextureProgress::TextureProgress() {
+ mode = FILL_LEFT_TO_RIGHT;
+ rad_init_angle = 0;
+ rad_center_off = Point2();
+ rad_max_degrees = 360;
set_mouse_filter(MOUSE_FILTER_PASS);
}
diff --git a/scene/gui/texture_progress.h b/scene/gui/texture_progress.h
index 02794354ef..0d9b5e6b1a 100644
--- a/scene/gui/texture_progress.h
+++ b/scene/gui/texture_progress.h
@@ -33,20 +33,19 @@
class TextureProgress : public Range {
- GDCLASS( TextureProgress, Range );
+ GDCLASS(TextureProgress, Range);
Ref<Texture> under;
Ref<Texture> progress;
Ref<Texture> over;
protected:
-
static void _bind_methods();
void _notification(int p_what);
-public:
+public:
enum FillMode {
- FILL_LEFT_TO_RIGHT=0,
+ FILL_LEFT_TO_RIGHT = 0,
FILL_RIGHT_TO_LEFT,
FILL_TOP_TO_BOTTOM,
FILL_BOTTOM_TO_TOP,
@@ -66,13 +65,13 @@ public:
void set_radial_center_offset(const Point2 &p_off);
Point2 get_radial_center_offset();
- void set_under_texture(const Ref<Texture>& p_texture);
+ void set_under_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_under_texture() const;
- void set_progress_texture(const Ref<Texture>& p_texture);
+ void set_progress_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_progress_texture() const;
- void set_over_texture(const Ref<Texture>& p_texture);
+ void set_over_texture(const Ref<Texture> &p_texture);
Ref<Texture> get_over_texture() const;
Size2 get_minimum_size() const;
@@ -80,7 +79,6 @@ public:
TextureProgress();
private:
-
FillMode mode;
float rad_init_angle;
float rad_max_degrees;
diff --git a/scene/gui/texture_rect.cpp b/scene/gui/texture_rect.cpp
index f2fe3eae12..ea35ee8b52 100644
--- a/scene/gui/texture_rect.cpp
+++ b/scene/gui/texture_rect.cpp
@@ -31,65 +31,63 @@
void TextureRect::_notification(int p_what) {
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
if (texture.is_null())
return;
-
- switch(stretch_mode) {
+ switch (stretch_mode) {
case STRETCH_SCALE_ON_EXPAND: {
- Size2 s=expand?get_size():texture->get_size();
- draw_texture_rect(texture,Rect2(Point2(),s),false);
+ Size2 s = expand ? get_size() : texture->get_size();
+ draw_texture_rect(texture, Rect2(Point2(), s), false);
} break;
case STRETCH_SCALE: {
- draw_texture_rect(texture,Rect2(Point2(),get_size()),false);
+ draw_texture_rect(texture, Rect2(Point2(), get_size()), false);
} break;
case STRETCH_TILE: {
- draw_texture_rect(texture,Rect2(Point2(),get_size()),true);
+ draw_texture_rect(texture, Rect2(Point2(), get_size()), true);
} break;
case STRETCH_KEEP: {
- draw_texture_rect(texture,Rect2(Point2(),texture->get_size()),false);
+ draw_texture_rect(texture, Rect2(Point2(), texture->get_size()), false);
} break;
case STRETCH_KEEP_CENTERED: {
- Vector2 ofs = (get_size() - texture->get_size())/2;
- draw_texture_rect(texture,Rect2(ofs,texture->get_size()),false);
+ Vector2 ofs = (get_size() - texture->get_size()) / 2;
+ draw_texture_rect(texture, Rect2(ofs, texture->get_size()), false);
} break;
case STRETCH_KEEP_ASPECT_CENTERED:
case STRETCH_KEEP_ASPECT: {
- Size2 size=get_size();
- int tex_width = texture->get_width() * size.height / texture ->get_height();
+ Size2 size = get_size();
+ int tex_width = texture->get_width() * size.height / texture->get_height();
int tex_height = size.height;
- if (tex_width>size.width) {
- tex_width=size.width;
- tex_height=texture->get_height() * tex_width / texture->get_width();
+ if (tex_width > size.width) {
+ tex_width = size.width;
+ tex_height = texture->get_height() * tex_width / texture->get_width();
}
int ofs_x = 0;
int ofs_y = 0;
- if (stretch_mode==STRETCH_KEEP_ASPECT_CENTERED) {
- ofs_x+=(size.width - tex_width)/2;
- ofs_y+=(size.height - tex_height)/2;
+ if (stretch_mode == STRETCH_KEEP_ASPECT_CENTERED) {
+ ofs_x += (size.width - tex_width) / 2;
+ ofs_y += (size.height - tex_height) / 2;
}
- draw_texture_rect(texture,Rect2(ofs_x,ofs_y,tex_width,tex_height));
+ draw_texture_rect(texture, Rect2(ofs_x, ofs_y, tex_width, tex_height));
} break;
case STRETCH_KEEP_ASPECT_COVERED: {
Size2 size = get_size();
Size2 tex_size = texture->get_size();
- Size2 scaleSize(size.width/tex_size.width, size.height/tex_size.height);
- float scale = scaleSize.width > scaleSize.height? scaleSize.width : scaleSize.height;
+ Size2 scaleSize(size.width / tex_size.width, size.height / tex_size.height);
+ float scale = scaleSize.width > scaleSize.height ? scaleSize.width : scaleSize.height;
Size2 scaledTexSize = tex_size * scale;
Point2 ofs = ((scaledTexSize - size) / scale).abs() / 2.0f;
- draw_texture_rect_region(texture, Rect2(Point2(), size), Rect2(ofs, size/scale));
+ draw_texture_rect_region(texture, Rect2(Point2(), size), Rect2(ofs, size / scale));
} break;
}
-
}
}
@@ -102,32 +100,30 @@ Size2 TextureRect::get_minimum_size() const {
}
void TextureRect::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("set_texture","texture"), & TextureRect::set_texture );
- ClassDB::bind_method(D_METHOD("get_texture"), & TextureRect::get_texture );
- ClassDB::bind_method(D_METHOD("set_expand","enable"), & TextureRect::set_expand );
- ClassDB::bind_method(D_METHOD("has_expand"), & TextureRect::has_expand );
- ClassDB::bind_method(D_METHOD("set_stretch_mode","stretch_mode"), & TextureRect::set_stretch_mode );
- ClassDB::bind_method(D_METHOD("get_stretch_mode"), & TextureRect::get_stretch_mode );
-
- ADD_PROPERTYNZ( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "expand" ), "set_expand","has_expand");
- ADD_PROPERTYNO( PropertyInfo( Variant::INT, "stretch_mode",PROPERTY_HINT_ENUM,"Scale On Expand (Compat),Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
-
- BIND_CONSTANT( STRETCH_SCALE_ON_EXPAND );
- BIND_CONSTANT( STRETCH_SCALE );
- BIND_CONSTANT( STRETCH_TILE );
- BIND_CONSTANT( STRETCH_KEEP );
- BIND_CONSTANT( STRETCH_KEEP_CENTERED );
- BIND_CONSTANT( STRETCH_KEEP_ASPECT );
- BIND_CONSTANT( STRETCH_KEEP_ASPECT_CENTERED );
- BIND_CONSTANT( STRETCH_KEEP_ASPECT_COVERED );
+ ClassDB::bind_method(D_METHOD("set_texture", "texture"), &TextureRect::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture"), &TextureRect::get_texture);
+ ClassDB::bind_method(D_METHOD("set_expand", "enable"), &TextureRect::set_expand);
+ ClassDB::bind_method(D_METHOD("has_expand"), &TextureRect::has_expand);
+ ClassDB::bind_method(D_METHOD("set_stretch_mode", "stretch_mode"), &TextureRect::set_stretch_mode);
+ ClassDB::bind_method(D_METHOD("get_stretch_mode"), &TextureRect::get_stretch_mode);
+
+ ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "expand"), "set_expand", "has_expand");
+ ADD_PROPERTYNO(PropertyInfo(Variant::INT, "stretch_mode", PROPERTY_HINT_ENUM, "Scale On Expand (Compat),Scale,Tile,Keep,Keep Centered,Keep Aspect,Keep Aspect Centered,Keep Aspect Covered"), "set_stretch_mode", "get_stretch_mode");
+
+ BIND_CONSTANT(STRETCH_SCALE_ON_EXPAND);
+ BIND_CONSTANT(STRETCH_SCALE);
+ BIND_CONSTANT(STRETCH_TILE);
+ BIND_CONSTANT(STRETCH_KEEP);
+ BIND_CONSTANT(STRETCH_KEEP_CENTERED);
+ BIND_CONSTANT(STRETCH_KEEP_ASPECT);
+ BIND_CONSTANT(STRETCH_KEEP_ASPECT_CENTERED);
+ BIND_CONSTANT(STRETCH_KEEP_ASPECT_COVERED);
}
+void TextureRect::set_texture(const Ref<Texture> &p_tex) {
-void TextureRect::set_texture(const Ref<Texture>& p_tex) {
-
- texture=p_tex;
+ texture = p_tex;
update();
/*
if (texture.is_valid())
@@ -141,10 +137,9 @@ Ref<Texture> TextureRect::get_texture() const {
return texture;
}
-
void TextureRect::set_expand(bool p_expand) {
- expand=p_expand;
+ expand = p_expand;
update();
minimum_size_changed();
}
@@ -155,7 +150,7 @@ bool TextureRect::has_expand() const {
void TextureRect::set_stretch_mode(StretchMode p_mode) {
- stretch_mode=p_mode;
+ stretch_mode = p_mode;
update();
}
@@ -166,15 +161,10 @@ TextureRect::StretchMode TextureRect::get_stretch_mode() const {
TextureRect::TextureRect() {
-
- expand=false;
+ expand = false;
set_mouse_filter(MOUSE_FILTER_PASS);
- stretch_mode=STRETCH_SCALE_ON_EXPAND;
+ stretch_mode = STRETCH_SCALE_ON_EXPAND;
}
-
-TextureRect::~TextureRect()
-{
+TextureRect::~TextureRect() {
}
-
-
diff --git a/scene/gui/texture_rect.h b/scene/gui/texture_rect.h
index 0d72458909..2cc6b97b13 100644
--- a/scene/gui/texture_rect.h
+++ b/scene/gui/texture_rect.h
@@ -35,7 +35,8 @@
*/
class TextureRect : public Control {
- GDCLASS(TextureRect,Control);
+ GDCLASS(TextureRect, Control);
+
public:
enum StretchMode {
STRETCH_SCALE_ON_EXPAND, //default, for backwards compatibility
@@ -47,22 +48,21 @@ public:
STRETCH_KEEP_ASPECT_CENTERED,
STRETCH_KEEP_ASPECT_COVERED,
};
+
private:
bool expand;
Ref<Texture> texture;
StretchMode stretch_mode;
-protected:
+protected:
void _notification(int p_what);
virtual Size2 get_minimum_size() const;
static void _bind_methods();
public:
-
- void set_texture(const Ref<Texture>& p_tex);
+ void set_texture(const Ref<Texture> &p_tex);
Ref<Texture> get_texture() const;
-
void set_expand(bool p_expand);
bool has_expand() const;
@@ -71,8 +71,7 @@ public:
TextureRect();
~TextureRect();
-
};
-VARIANT_ENUM_CAST( TextureRect::StretchMode );
+VARIANT_ENUM_CAST(TextureRect::StretchMode);
#endif // TEXTURE_FRAME_H
diff --git a/scene/gui/tool_button.h b/scene/gui/tool_button.h
index ddeb34273b..02d2bfaef1 100644
--- a/scene/gui/tool_button.h
+++ b/scene/gui/tool_button.h
@@ -32,7 +32,8 @@
#include "scene/gui/button.h"
class ToolButton : public Button {
- GDCLASS(ToolButton,Button);
+ GDCLASS(ToolButton, Button);
+
public:
ToolButton();
};
diff --git a/scene/gui/tree.cpp b/scene/gui/tree.cpp
index 292efdcc01..d63ef41239 100644
--- a/scene/gui/tree.cpp
+++ b/scene/gui/tree.cpp
@@ -27,23 +27,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "tree.h"
-#include "print_string.h"
-#include "os/os.h"
-#include "os/keyboard.h"
#include "global_config.h"
#include "os/input.h"
+#include "os/keyboard.h"
+#include "os/os.h"
+#include "print_string.h"
#include "scene/main/viewport.h"
-
-
void TreeItem::move_to_top() {
- if (!parent || parent->childs==this)
+ if (!parent || parent->childs == this)
return; //already on top
TreeItem *prev = get_prev();
- prev->next=next;
- next=parent->childs;
- parent->childs=this;
+ prev->next = next;
+ next = parent->childs;
+ parent->childs = this;
}
void TreeItem::move_to_bottom() {
@@ -51,276 +49,255 @@ void TreeItem::move_to_bottom() {
if (!parent || !next)
return;
- while(next) {
+ while (next) {
- if (parent->childs==this)
- parent->childs=next;
- TreeItem *n=next;
- next=n->next;
- n->next=this;
+ if (parent->childs == this)
+ parent->childs = next;
+ TreeItem *n = next;
+ next = n->next;
+ n->next = this;
}
}
-
Size2 TreeItem::Cell::get_icon_size() const {
if (icon.is_null())
return Size2();
- if (icon_region==Rect2i())
+ if (icon_region == Rect2i())
return icon->get_size();
else
return icon_region.size;
}
-void TreeItem::Cell::draw_icon(const RID& p_where, const Point2& p_pos, const Size2& p_size) const{
+void TreeItem::Cell::draw_icon(const RID &p_where, const Point2 &p_pos, const Size2 &p_size) const {
if (icon.is_null())
return;
- Size2i dsize=(p_size==Size2()) ? icon->get_size() : p_size;
+ Size2i dsize = (p_size == Size2()) ? icon->get_size() : p_size;
- if (icon_region==Rect2i()) {
+ if (icon_region == Rect2i()) {
- icon->draw_rect_region(p_where,Rect2(p_pos,dsize),Rect2(Point2(),icon->get_size()));
+ icon->draw_rect_region(p_where, Rect2(p_pos, dsize), Rect2(Point2(), icon->get_size()));
} else {
- icon->draw_rect_region(p_where,Rect2(p_pos,dsize),icon_region);
+ icon->draw_rect_region(p_where, Rect2(p_pos, dsize), icon_region);
}
-
}
-
void TreeItem::_changed_notify(int p_cell) {
- tree->item_changed(p_cell,this);
+ tree->item_changed(p_cell, this);
}
void TreeItem::_changed_notify() {
- tree->item_changed(-1,this);
+ tree->item_changed(-1, this);
}
void TreeItem::_cell_selected(int p_cell) {
- tree->item_selected(p_cell,this);
+ tree->item_selected(p_cell, this);
}
void TreeItem::_cell_deselected(int p_cell) {
- tree->item_deselected(p_cell,this);
+ tree->item_deselected(p_cell, this);
}
/* cell mode */
-void TreeItem::set_cell_mode( int p_column, TreeCellMode p_mode ) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- Cell&c=cells[p_column];
- c.mode=p_mode;
- c.min=0;
- c.max=100;
- c.step=1;
- c.val=0;
- c.checked=false;
- c.icon=Ref<Texture>();
- c.text="";
- c.icon_max_w=0;
+void TreeItem::set_cell_mode(int p_column, TreeCellMode p_mode) {
+
+ ERR_FAIL_INDEX(p_column, cells.size());
+ Cell &c = cells[p_column];
+ c.mode = p_mode;
+ c.min = 0;
+ c.max = 100;
+ c.step = 1;
+ c.val = 0;
+ c.checked = false;
+ c.icon = Ref<Texture>();
+ c.text = "";
+ c.icon_max_w = 0;
_changed_notify(p_column);
}
-TreeItem::TreeCellMode TreeItem::get_cell_mode( int p_column ) const {
+TreeItem::TreeCellMode TreeItem::get_cell_mode(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), TreeItem::CELL_MODE_STRING );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), TreeItem::CELL_MODE_STRING);
return cells[p_column].mode;
}
-
/* check mode */
-void TreeItem::set_checked(int p_column,bool p_checked) {
+void TreeItem::set_checked(int p_column, bool p_checked) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].checked=p_checked;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].checked = p_checked;
_changed_notify(p_column);
-
}
bool TreeItem::is_checked(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
return cells[p_column].checked;
}
+void TreeItem::set_text(int p_column, String p_text) {
-void TreeItem::set_text(int p_column,String p_text) {
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].text = p_text;
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].text=p_text;
+ if (cells[p_column].mode == TreeItem::CELL_MODE_RANGE || cells[p_column].mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) {
- if (cells[p_column].mode==TreeItem::CELL_MODE_RANGE || cells[p_column].mode==TreeItem::CELL_MODE_RANGE_EXPRESSION) {
-
- cells[p_column].min=0;
- cells[p_column].max=p_text.get_slice_count(",");
- cells[p_column].step=0;
+ cells[p_column].min = 0;
+ cells[p_column].max = p_text.get_slice_count(",");
+ cells[p_column].step = 0;
}
_changed_notify(p_column);
-
}
String TreeItem::get_text(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), "" );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), "");
return cells[p_column].text;
-
}
-void TreeItem::set_suffix(int p_column,String p_suffix) {
+void TreeItem::set_suffix(int p_column, String p_suffix) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].suffix=p_suffix;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].suffix = p_suffix;
_changed_notify(p_column);
-
}
String TreeItem::get_suffix(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), "" );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), "");
return cells[p_column].suffix;
-
}
-void TreeItem::set_icon(int p_column,const Ref<Texture>& p_icon) {
+void TreeItem::set_icon(int p_column, const Ref<Texture> &p_icon) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].icon=p_icon;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].icon = p_icon;
_changed_notify(p_column);
-
}
Ref<Texture> TreeItem::get_icon(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Ref<Texture>() );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Ref<Texture>());
return cells[p_column].icon;
-
}
-void TreeItem::set_icon_region(int p_column,const Rect2& p_icon_region) {
+void TreeItem::set_icon_region(int p_column, const Rect2 &p_icon_region) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].icon_region=p_icon_region;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].icon_region = p_icon_region;
_changed_notify(p_column);
}
Rect2 TreeItem::get_icon_region(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Rect2() );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Rect2());
return cells[p_column].icon_region;
}
-void TreeItem::set_icon_max_width(int p_column,int p_max) {
+void TreeItem::set_icon_max_width(int p_column, int p_max) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].icon_max_w=p_max;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].icon_max_w = p_max;
_changed_notify(p_column);
}
int TreeItem::get_icon_max_width(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), 0);
+ ERR_FAIL_INDEX_V(p_column, cells.size(), 0);
return cells[p_column].icon_max_w;
-
}
-
/* range works for mode number or mode combo */
-void TreeItem::set_range(int p_column,double p_value) {
+void TreeItem::set_range(int p_column, double p_value) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- if (cells[p_column].step>0)
- p_value=Math::stepify( p_value, cells[p_column].step );
- if (p_value<cells[p_column].min)
- p_value=cells[p_column].min;
- if (p_value>cells[p_column].max)
- p_value=cells[p_column].max;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ if (cells[p_column].step > 0)
+ p_value = Math::stepify(p_value, cells[p_column].step);
+ if (p_value < cells[p_column].min)
+ p_value = cells[p_column].min;
+ if (p_value > cells[p_column].max)
+ p_value = cells[p_column].max;
- cells[p_column].val=p_value;
+ cells[p_column].val = p_value;
_changed_notify(p_column);
-
}
double TreeItem::get_range(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), 0 );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), 0);
return cells[p_column].val;
}
-
bool TreeItem::is_range_exponential(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false);
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
return cells[p_column].expr;
-
}
-void TreeItem::set_range_config(int p_column,double p_min,double p_max,double p_step,bool p_exp) {
+void TreeItem::set_range_config(int p_column, double p_min, double p_max, double p_step, bool p_exp) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].min=p_min;
- cells[p_column].max=p_max;
- cells[p_column].step=p_step;
- cells[p_column].expr=p_exp;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].min = p_min;
+ cells[p_column].max = p_max;
+ cells[p_column].step = p_step;
+ cells[p_column].expr = p_exp;
_changed_notify(p_column);
-
}
-void TreeItem::get_range_config(int p_column,double& r_min,double& r_max,double &r_step) const {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- r_min=cells[p_column].min;
- r_max=cells[p_column].max;
- r_step=cells[p_column].step;
+void TreeItem::get_range_config(int p_column, double &r_min, double &r_max, double &r_step) const {
+ ERR_FAIL_INDEX(p_column, cells.size());
+ r_min = cells[p_column].min;
+ r_max = cells[p_column].max;
+ r_step = cells[p_column].step;
}
-void TreeItem::set_metadata(int p_column,const Variant& p_meta) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].meta=p_meta;
+void TreeItem::set_metadata(int p_column, const Variant &p_meta) {
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].meta = p_meta;
}
Variant TreeItem::get_metadata(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Variant() );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Variant());
return cells[p_column].meta;
}
-void TreeItem::set_custom_draw(int p_column,Object *p_object,const StringName& p_callback) {
+void TreeItem::set_custom_draw(int p_column, Object *p_object, const StringName &p_callback) {
- ERR_FAIL_INDEX( p_column, cells.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_NULL(p_object);
- cells[p_column].custom_draw_obj=p_object->get_instance_ID();
- cells[p_column].custom_draw_callback=p_callback;
-
+ cells[p_column].custom_draw_obj = p_object->get_instance_ID();
+ cells[p_column].custom_draw_callback = p_callback;
}
void TreeItem::set_collapsed(bool p_collapsed) {
- if (collapsed==p_collapsed)
+ if (collapsed == p_collapsed)
return;
- collapsed=p_collapsed;
+ collapsed = p_collapsed;
TreeItem *ci = tree->selected_item;
if (ci) {
- while (ci && ci!=this) {
+ while (ci && ci != this) {
- ci=ci->parent;
+ ci = ci->parent;
}
if (ci) { // collapsing cursor/selectd, move it!
- if (tree->select_mode==Tree::SELECT_MULTI) {
+ if (tree->select_mode == Tree::SELECT_MULTI) {
- tree->selected_item=this;
+ tree->selected_item = this;
emit_signal("cell_selected");
} else {
@@ -329,13 +306,11 @@ void TreeItem::set_collapsed(bool p_collapsed) {
tree->update();
}
-
}
_changed_notify();
if (tree)
- tree->emit_signal("item_collapsed",this);
-
+ tree->emit_signal("item_collapsed", this);
}
bool TreeItem::is_collapsed() {
@@ -343,7 +318,6 @@ bool TreeItem::is_collapsed() {
return collapsed;
}
-
TreeItem *TreeItem::get_next() {
return next;
@@ -351,12 +325,12 @@ TreeItem *TreeItem::get_next() {
TreeItem *TreeItem::get_prev() {
- if (!parent || parent->childs==this)
+ if (!parent || parent->childs == this)
return NULL;
TreeItem *prev = parent->childs;
- while(prev && prev->next!=this)
- prev=prev->next;
+ while (prev && prev->next != this)
+ prev = prev->next;
return prev;
}
@@ -371,61 +345,54 @@ TreeItem *TreeItem::get_children() {
return childs;
}
-
TreeItem *TreeItem::get_prev_visible() {
- TreeItem *current=this;
+ TreeItem *current = this;
TreeItem *prev = current->get_prev();
-
if (!prev) {
- current=current->parent;
- if (!current || (current==tree->root && tree->hide_root))
+ current = current->parent;
+ if (!current || (current == tree->root && tree->hide_root))
return NULL;
} else {
-
- current=prev;
- while( !current->collapsed && current->childs ) {
+ current = prev;
+ while (!current->collapsed && current->childs) {
//go to the very end
current = current->childs;
while (current->next)
- current=current->next;
+ current = current->next;
}
-
-
}
return current;
}
-
TreeItem *TreeItem::get_next_visible() {
- TreeItem *current=this;
-
+ TreeItem *current = this;
if (!current->collapsed && current->childs) {
- current=current->childs;
+ current = current->childs;
} else if (current->next) {
- current=current->next;
+ current = current->next;
} else {
- while(current && !current->next) {
+ while (current && !current->next) {
- current=current->parent;
+ current = current->parent;
}
- if (current==NULL)
+ if (current == NULL)
return NULL;
else
- current=current->next;
+ current = current->next;
}
return current;
@@ -434,117 +401,111 @@ TreeItem *TreeItem::get_next_visible() {
void TreeItem::remove_child(TreeItem *p_item) {
ERR_FAIL_NULL(p_item);
- TreeItem **c=&childs;
+ TreeItem **c = &childs;
while (*c) {
- if ( (*c) == p_item ) {
+ if ((*c) == p_item) {
TreeItem *aux = *c;
- *c=(*c)->next;
+ *c = (*c)->next;
aux->parent = NULL;
return;
}
- c=&(*c)->next;
+ c = &(*c)->next;
}
ERR_FAIL();
}
+void TreeItem::set_selectable(int p_column, bool p_selectable) {
-void TreeItem::set_selectable(int p_column,bool p_selectable) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].selectable=p_selectable;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].selectable = p_selectable;
}
bool TreeItem::is_selectable(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
return cells[p_column].selectable;
-
}
bool TreeItem::is_selected(int p_column) {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
return cells[p_column].selectable && cells[p_column].selected;
}
void TreeItem::set_as_cursor(int p_column) {
- ERR_FAIL_INDEX( p_column, cells.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
if (!tree)
return;
- if (tree->select_mode!=Tree::SELECT_MULTI)
+ if (tree->select_mode != Tree::SELECT_MULTI)
return;
- tree->selected_item=this;
- tree->selected_col=p_column;
+ tree->selected_item = this;
+ tree->selected_col = p_column;
tree->update();
}
void TreeItem::select(int p_column) {
- ERR_FAIL_INDEX( p_column, cells.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
_cell_selected(p_column);
}
void TreeItem::deselect(int p_column) {
- ERR_FAIL_INDEX( p_column, cells.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
_cell_deselected(p_column);
}
-void TreeItem::add_button(int p_column, const Ref<Texture>& p_button, int p_id, bool p_disabled) {
+void TreeItem::add_button(int p_column, const Ref<Texture> &p_button, int p_id, bool p_disabled) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
ERR_FAIL_COND(!p_button.is_valid());
TreeItem::Cell::Button button;
- button.texture=p_button;
- if (p_id<0)
- p_id=cells[p_column].buttons.size();
- button.id=p_id;
- button.disabled=p_disabled;
+ button.texture = p_button;
+ if (p_id < 0)
+ p_id = cells[p_column].buttons.size();
+ button.id = p_id;
+ button.disabled = p_disabled;
cells[p_column].buttons.push_back(button);
_changed_notify(p_column);
}
int TreeItem::get_button_count(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), -1 );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), -1);
return cells[p_column].buttons.size();
-
}
-Ref<Texture> TreeItem::get_button(int p_column,int p_idx) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Ref<Texture>() );
- ERR_FAIL_INDEX_V( p_idx, cells[p_column].buttons.size(), Ref<Texture>() );
+Ref<Texture> TreeItem::get_button(int p_column, int p_idx) const {
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), Ref<Texture>());
return cells[p_column].buttons[p_idx].texture;
-
}
-int TreeItem::get_button_id(int p_column,int p_idx) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), -1 );
- ERR_FAIL_INDEX_V( p_idx, cells[p_column].buttons.size(), -1 );
+int TreeItem::get_button_id(int p_column, int p_idx) const {
+ ERR_FAIL_INDEX_V(p_column, cells.size(), -1);
+ ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), -1);
return cells[p_column].buttons[p_idx].id;
-
}
-void TreeItem::erase_button(int p_column,int p_idx) {
+void TreeItem::erase_button(int p_column, int p_idx) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- ERR_FAIL_INDEX( p_idx, cells[p_column].buttons.size() );
+ ERR_FAIL_INDEX(p_column, cells.size());
+ ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
cells[p_column].buttons.remove(p_idx);
_changed_notify(p_column);
}
-int TreeItem::get_button_by_id(int p_column,int p_id) const {
+int TreeItem::get_button_by_id(int p_column, int p_id) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(),-1 );
- for(int i=0;i<cells[p_column].buttons.size();i++) {
+ ERR_FAIL_INDEX_V(p_column, cells.size(), -1);
+ for (int i = 0; i < cells[p_column].buttons.size(); i++) {
- if (cells[p_column].buttons[i].id==p_id)
+ if (cells[p_column].buttons[i].id == p_id)
return i;
}
@@ -553,200 +514,190 @@ int TreeItem::get_button_by_id(int p_column,int p_id) const {
bool TreeItem::is_button_disabled(int p_column, int p_idx) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false );
- ERR_FAIL_INDEX_V( p_idx, cells[p_column].buttons.size(), false );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
+ ERR_FAIL_INDEX_V(p_idx, cells[p_column].buttons.size(), false);
return cells[p_column].buttons[p_idx].disabled;
-
}
-void TreeItem::set_button(int p_column,int p_idx,const Ref<Texture>& p_button){
+void TreeItem::set_button(int p_column, int p_idx, const Ref<Texture> &p_button) {
- ERR_FAIL_COND( p_button.is_null() );
- ERR_FAIL_INDEX( p_column, cells.size() );
- ERR_FAIL_INDEX( p_idx, cells[p_column].buttons.size() );
- cells[p_column].buttons[p_idx].texture=p_button;
+ ERR_FAIL_COND(p_button.is_null());
+ ERR_FAIL_INDEX(p_column, cells.size());
+ ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ cells[p_column].buttons[p_idx].texture = p_button;
_changed_notify(p_column);
-
}
-void TreeItem::set_button_color(int p_column,int p_idx,const Color& p_color) {
+void TreeItem::set_button_color(int p_column, int p_idx, const Color &p_color) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- ERR_FAIL_INDEX( p_idx, cells[p_column].buttons.size() );
- cells[p_column].buttons[p_idx].color=p_color;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ ERR_FAIL_INDEX(p_idx, cells[p_column].buttons.size());
+ cells[p_column].buttons[p_idx].color = p_color;
_changed_notify(p_column);
-
}
-void TreeItem::set_editable(int p_column,bool p_editable) {
+void TreeItem::set_editable(int p_column, bool p_editable) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].editable=p_editable;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].editable = p_editable;
_changed_notify(p_column);
}
bool TreeItem::is_editable(int p_column) {
- ERR_FAIL_INDEX_V( p_column, cells.size(), false );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), false);
return cells[p_column].editable;
}
+void TreeItem::set_custom_color(int p_column, const Color &p_color) {
-void TreeItem::set_custom_color(int p_column,const Color& p_color) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].custom_color=true;
- cells[p_column].color=p_color;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].custom_color = true;
+ cells[p_column].color = p_color;
_changed_notify(p_column);
}
Color TreeItem::get_custom_color(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Color() );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Color());
if (!cells[p_column].custom_color)
return Color();
return cells[p_column].color;
-
}
void TreeItem::clear_custom_color(int p_column) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].custom_color=false;
- cells[p_column].color=Color();
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].custom_color = false;
+ cells[p_column].color = Color();
_changed_notify(p_column);
}
+void TreeItem::set_tooltip(int p_column, const String &p_tooltip) {
-void TreeItem::set_tooltip(int p_column, const String& p_tooltip) {
-
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].tooltip=p_tooltip;
-
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].tooltip = p_tooltip;
}
-String TreeItem::get_tooltip(int p_column) const{
+String TreeItem::get_tooltip(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), "" );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), "");
return cells[p_column].tooltip;
}
-void TreeItem::set_custom_bg_color(int p_column,const Color& p_color,bool p_bg_outline) {
+void TreeItem::set_custom_bg_color(int p_column, const Color &p_color, bool p_bg_outline) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].custom_bg_color=true;
- cells[p_column].custom_bg_outline=p_bg_outline;
- cells[p_column].bg_color=p_color;
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].custom_bg_color = true;
+ cells[p_column].custom_bg_outline = p_bg_outline;
+ cells[p_column].bg_color = p_color;
_changed_notify(p_column);
}
void TreeItem::clear_custom_bg_color(int p_column) {
- ERR_FAIL_INDEX( p_column, cells.size() );
- cells[p_column].custom_bg_color=false;
- cells[p_column].bg_color=Color();
+ ERR_FAIL_INDEX(p_column, cells.size());
+ cells[p_column].custom_bg_color = false;
+ cells[p_column].bg_color = Color();
_changed_notify(p_column);
}
Color TreeItem::get_custom_bg_color(int p_column) const {
- ERR_FAIL_INDEX_V( p_column, cells.size(), Color() );
+ ERR_FAIL_INDEX_V(p_column, cells.size(), Color());
if (!cells[p_column].custom_bg_color)
return Color();
return cells[p_column].bg_color;
-
}
void TreeItem::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_cell_mode","column","mode"),&TreeItem::set_cell_mode);
- ClassDB::bind_method(D_METHOD("get_cell_mode","column"),&TreeItem::get_cell_mode);
-
- ClassDB::bind_method(D_METHOD("set_checked","column","checked"),&TreeItem::set_checked);
- ClassDB::bind_method(D_METHOD("is_checked","column"),&TreeItem::is_checked);
-
- ClassDB::bind_method(D_METHOD("set_text","column","text"),&TreeItem::set_text);
- ClassDB::bind_method(D_METHOD("get_text","column"),&TreeItem::get_text);
+ ClassDB::bind_method(D_METHOD("set_cell_mode", "column", "mode"), &TreeItem::set_cell_mode);
+ ClassDB::bind_method(D_METHOD("get_cell_mode", "column"), &TreeItem::get_cell_mode);
- ClassDB::bind_method(D_METHOD("set_icon","column","texture:Texture"),&TreeItem::set_icon);
- ClassDB::bind_method(D_METHOD("get_icon:Texture","column"),&TreeItem::get_icon);
+ ClassDB::bind_method(D_METHOD("set_checked", "column", "checked"), &TreeItem::set_checked);
+ ClassDB::bind_method(D_METHOD("is_checked", "column"), &TreeItem::is_checked);
- ClassDB::bind_method(D_METHOD("set_icon_region","column","region"),&TreeItem::set_icon_region);
- ClassDB::bind_method(D_METHOD("get_icon_region","column"),&TreeItem::get_icon_region);
+ ClassDB::bind_method(D_METHOD("set_text", "column", "text"), &TreeItem::set_text);
+ ClassDB::bind_method(D_METHOD("get_text", "column"), &TreeItem::get_text);
- ClassDB::bind_method(D_METHOD("set_icon_max_width","column","width"),&TreeItem::set_icon_max_width);
- ClassDB::bind_method(D_METHOD("get_icon_max_width","column"),&TreeItem::get_icon_max_width);
+ ClassDB::bind_method(D_METHOD("set_icon", "column", "texture:Texture"), &TreeItem::set_icon);
+ ClassDB::bind_method(D_METHOD("get_icon:Texture", "column"), &TreeItem::get_icon);
- ClassDB::bind_method(D_METHOD("set_range","column","value"),&TreeItem::set_range);
- ClassDB::bind_method(D_METHOD("get_range","column"),&TreeItem::get_range);
- ClassDB::bind_method(D_METHOD("set_range_config","column","min","max","step","expr"),&TreeItem::set_range_config,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_range_config","column"),&TreeItem::_get_range_config);
+ ClassDB::bind_method(D_METHOD("set_icon_region", "column", "region"), &TreeItem::set_icon_region);
+ ClassDB::bind_method(D_METHOD("get_icon_region", "column"), &TreeItem::get_icon_region);
- ClassDB::bind_method(D_METHOD("set_metadata","column","meta"),&TreeItem::set_metadata);
- ClassDB::bind_method(D_METHOD("get_metadata","column"),&TreeItem::get_metadata);
+ ClassDB::bind_method(D_METHOD("set_icon_max_width", "column", "width"), &TreeItem::set_icon_max_width);
+ ClassDB::bind_method(D_METHOD("get_icon_max_width", "column"), &TreeItem::get_icon_max_width);
- ClassDB::bind_method(D_METHOD("set_custom_draw","column","object","callback"),&TreeItem::set_custom_draw);
+ ClassDB::bind_method(D_METHOD("set_range", "column", "value"), &TreeItem::set_range);
+ ClassDB::bind_method(D_METHOD("get_range", "column"), &TreeItem::get_range);
+ ClassDB::bind_method(D_METHOD("set_range_config", "column", "min", "max", "step", "expr"), &TreeItem::set_range_config, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_range_config", "column"), &TreeItem::_get_range_config);
- ClassDB::bind_method(D_METHOD("set_collapsed","enable"),&TreeItem::set_collapsed);
- ClassDB::bind_method(D_METHOD("is_collapsed"),&TreeItem::is_collapsed);
+ ClassDB::bind_method(D_METHOD("set_metadata", "column", "meta"), &TreeItem::set_metadata);
+ ClassDB::bind_method(D_METHOD("get_metadata", "column"), &TreeItem::get_metadata);
- ClassDB::bind_method(D_METHOD("get_next:TreeItem"),&TreeItem::get_next);
- ClassDB::bind_method(D_METHOD("get_prev:TreeItem"),&TreeItem::get_prev);
- ClassDB::bind_method(D_METHOD("get_parent:TreeItem"),&TreeItem::get_parent);
- ClassDB::bind_method(D_METHOD("get_children:TreeItem"),&TreeItem::get_children);
+ ClassDB::bind_method(D_METHOD("set_custom_draw", "column", "object", "callback"), &TreeItem::set_custom_draw);
- ClassDB::bind_method(D_METHOD("get_next_visible:TreeItem"),&TreeItem::get_next_visible);
- ClassDB::bind_method(D_METHOD("get_prev_visible:TreeItem"),&TreeItem::get_prev_visible);
+ ClassDB::bind_method(D_METHOD("set_collapsed", "enable"), &TreeItem::set_collapsed);
+ ClassDB::bind_method(D_METHOD("is_collapsed"), &TreeItem::is_collapsed);
- ClassDB::bind_method(D_METHOD("remove_child:TreeItem","child"),&TreeItem::_remove_child);
+ ClassDB::bind_method(D_METHOD("get_next:TreeItem"), &TreeItem::get_next);
+ ClassDB::bind_method(D_METHOD("get_prev:TreeItem"), &TreeItem::get_prev);
+ ClassDB::bind_method(D_METHOD("get_parent:TreeItem"), &TreeItem::get_parent);
+ ClassDB::bind_method(D_METHOD("get_children:TreeItem"), &TreeItem::get_children);
- ClassDB::bind_method(D_METHOD("set_selectable","column","selectable"),&TreeItem::set_selectable);
- ClassDB::bind_method(D_METHOD("is_selectable","column"),&TreeItem::is_selectable);
+ ClassDB::bind_method(D_METHOD("get_next_visible:TreeItem"), &TreeItem::get_next_visible);
+ ClassDB::bind_method(D_METHOD("get_prev_visible:TreeItem"), &TreeItem::get_prev_visible);
- ClassDB::bind_method(D_METHOD("is_selected","column"),&TreeItem::is_selected);
- ClassDB::bind_method(D_METHOD("select","column"),&TreeItem::select);
- ClassDB::bind_method(D_METHOD("deselect","column"),&TreeItem::deselect);
+ ClassDB::bind_method(D_METHOD("remove_child:TreeItem", "child"), &TreeItem::_remove_child);
- ClassDB::bind_method(D_METHOD("set_editable","column","enabled"),&TreeItem::set_editable);
- ClassDB::bind_method(D_METHOD("is_editable","column"),&TreeItem::is_editable);
+ ClassDB::bind_method(D_METHOD("set_selectable", "column", "selectable"), &TreeItem::set_selectable);
+ ClassDB::bind_method(D_METHOD("is_selectable", "column"), &TreeItem::is_selectable);
- ClassDB::bind_method(D_METHOD("set_custom_color","column","color"),&TreeItem::set_custom_color);
- ClassDB::bind_method(D_METHOD("clear_custom_color","column"),&TreeItem::clear_custom_color);
+ ClassDB::bind_method(D_METHOD("is_selected", "column"), &TreeItem::is_selected);
+ ClassDB::bind_method(D_METHOD("select", "column"), &TreeItem::select);
+ ClassDB::bind_method(D_METHOD("deselect", "column"), &TreeItem::deselect);
- ClassDB::bind_method(D_METHOD("set_custom_bg_color","column","color","just_outline"),&TreeItem::set_custom_bg_color,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("clear_custom_bg_color","column"),&TreeItem::clear_custom_bg_color);
- ClassDB::bind_method(D_METHOD("get_custom_bg_color","column"),&TreeItem::get_custom_bg_color);
+ ClassDB::bind_method(D_METHOD("set_editable", "column", "enabled"), &TreeItem::set_editable);
+ ClassDB::bind_method(D_METHOD("is_editable", "column"), &TreeItem::is_editable);
- ClassDB::bind_method(D_METHOD("add_button","column","button:Texture","button_idx","disabled"),&TreeItem::add_button,DEFVAL(-1),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_button_count","column"),&TreeItem::get_button_count);
- ClassDB::bind_method(D_METHOD("get_button:Texture","column","button_idx"),&TreeItem::get_button);
- ClassDB::bind_method(D_METHOD("set_button","column","button_idx","button:Texture"),&TreeItem::set_button);
- ClassDB::bind_method(D_METHOD("erase_button","column","button_idx"),&TreeItem::erase_button);
- ClassDB::bind_method(D_METHOD("is_button_disabled","column","button_idx"),&TreeItem::is_button_disabled);
+ ClassDB::bind_method(D_METHOD("set_custom_color", "column", "color"), &TreeItem::set_custom_color);
+ ClassDB::bind_method(D_METHOD("clear_custom_color", "column"), &TreeItem::clear_custom_color);
- ClassDB::bind_method(D_METHOD("set_tooltip","column","tooltip"),&TreeItem::set_tooltip);
- ClassDB::bind_method(D_METHOD("get_tooltip","column"),&TreeItem::get_tooltip);
+ ClassDB::bind_method(D_METHOD("set_custom_bg_color", "column", "color", "just_outline"), &TreeItem::set_custom_bg_color, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("clear_custom_bg_color", "column"), &TreeItem::clear_custom_bg_color);
+ ClassDB::bind_method(D_METHOD("get_custom_bg_color", "column"), &TreeItem::get_custom_bg_color);
- ClassDB::bind_method(D_METHOD("move_to_top"),&TreeItem::move_to_top);
- ClassDB::bind_method(D_METHOD("move_to_bottom"),&TreeItem::move_to_bottom);
+ ClassDB::bind_method(D_METHOD("add_button", "column", "button:Texture", "button_idx", "disabled"), &TreeItem::add_button, DEFVAL(-1), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_button_count", "column"), &TreeItem::get_button_count);
+ ClassDB::bind_method(D_METHOD("get_button:Texture", "column", "button_idx"), &TreeItem::get_button);
+ ClassDB::bind_method(D_METHOD("set_button", "column", "button_idx", "button:Texture"), &TreeItem::set_button);
+ ClassDB::bind_method(D_METHOD("erase_button", "column", "button_idx"), &TreeItem::erase_button);
+ ClassDB::bind_method(D_METHOD("is_button_disabled", "column", "button_idx"), &TreeItem::is_button_disabled);
- BIND_CONSTANT( CELL_MODE_STRING );
- BIND_CONSTANT( CELL_MODE_CHECK );
- BIND_CONSTANT( CELL_MODE_RANGE );
- BIND_CONSTANT( CELL_MODE_RANGE_EXPRESSION );
- BIND_CONSTANT( CELL_MODE_ICON );
- BIND_CONSTANT( CELL_MODE_CUSTOM );
+ ClassDB::bind_method(D_METHOD("set_tooltip", "column", "tooltip"), &TreeItem::set_tooltip);
+ ClassDB::bind_method(D_METHOD("get_tooltip", "column"), &TreeItem::get_tooltip);
+ ClassDB::bind_method(D_METHOD("move_to_top"), &TreeItem::move_to_top);
+ ClassDB::bind_method(D_METHOD("move_to_bottom"), &TreeItem::move_to_bottom);
+ BIND_CONSTANT(CELL_MODE_STRING);
+ BIND_CONSTANT(CELL_MODE_CHECK);
+ BIND_CONSTANT(CELL_MODE_RANGE);
+ BIND_CONSTANT(CELL_MODE_RANGE_EXPRESSION);
+ BIND_CONSTANT(CELL_MODE_ICON);
+ BIND_CONSTANT(CELL_MODE_CUSTOM);
}
void TreeItem::clear_children() {
- TreeItem *c=childs;
+ TreeItem *c = childs;
while (c) {
- TreeItem *aux=c;
- c=c->get_next();
- aux->parent=0; // so it wont try to recursively autoremove from me in here
- memdelete( aux );
+ TreeItem *aux = c;
+ c = c->get_next();
+ aux->parent = 0; // so it wont try to recursively autoremove from me in here
+ memdelete(aux);
}
childs = 0;
@@ -754,13 +705,12 @@ void TreeItem::clear_children() {
TreeItem::TreeItem(Tree *p_tree) {
- tree=p_tree;
- collapsed=false;
-
- parent=0; // parent item
- next=0; // next in list
- childs=0; //child items
+ tree = p_tree;
+ collapsed = false;
+ parent = 0; // parent item
+ next = 0; // next in list
+ childs = 0; //child items
}
TreeItem::~TreeItem() {
@@ -770,33 +720,29 @@ TreeItem::~TreeItem() {
if (parent)
parent->remove_child(this);
- if (tree && tree->root==this) {
+ if (tree && tree->root == this) {
- tree->root=0;
+ tree->root = 0;
}
- if (tree && tree->popup_edited_item==this) {
- tree->popup_edited_item=NULL;
- tree->pressing_for_editor=false;
-
+ if (tree && tree->popup_edited_item == this) {
+ tree->popup_edited_item = NULL;
+ tree->pressing_for_editor = false;
}
- if (tree && tree->selected_item==this)
- tree->selected_item=NULL;
+ if (tree && tree->selected_item == this)
+ tree->selected_item = NULL;
+ if (tree && tree->drop_mode_over == this)
+ tree->drop_mode_over = NULL;
- if (tree && tree->drop_mode_over==this)
- tree->drop_mode_over=NULL;
+ if (tree && tree->single_select_defer == this)
+ tree->single_select_defer = NULL;
- if (tree && tree->single_select_defer==this)
- tree->single_select_defer=NULL;
-
- if (tree && tree->edited_item==this) {
- tree->edited_item=NULL;
- tree->pressing_for_editor=false;
+ if (tree && tree->edited_item == this) {
+ tree->edited_item = NULL;
+ tree->pressing_for_editor = false;
}
-
-
}
/**********************************************/
@@ -806,41 +752,37 @@ TreeItem::~TreeItem() {
/**********************************************/
/**********************************************/
-
-
-
-
void Tree::update_cache() {
cache.font = get_font("font");
cache.tb_font = get_font("title_button_font");
cache.bg = get_stylebox("bg");
- cache.selected= get_stylebox("selected");
- cache.selected_focus= get_stylebox("selected_focus");
+ cache.selected = get_stylebox("selected");
+ cache.selected_focus = get_stylebox("selected_focus");
cache.cursor = get_stylebox("cursor");
cache.cursor_unfocus = get_stylebox("cursor_unfocused");
- cache.button_pressed= get_stylebox("button_pressed");
-
- cache.checked=get_icon("checked");
- cache.unchecked=get_icon("unchecked");
- cache.arrow_collapsed=get_icon("arrow_collapsed");
- cache.arrow =get_icon("arrow");
- cache.select_arrow =get_icon("select_arrow");
- cache.updown=get_icon("updown");
-
- cache.font_color=get_color("font_color");
- cache.font_color_selected=get_color("font_color_selected");
- cache.guide_color=get_color("guide_color");
- cache.drop_position_color=get_color("drop_position_color");
- cache.hseparation=get_constant("hseparation");
- cache.vseparation=get_constant("vseparation");
- cache.item_margin=get_constant("item_margin");
- cache.button_margin=get_constant("button_margin");
- cache.guide_width=get_constant("guide_width");
- cache.draw_relationship_lines=get_constant("draw_relationship_lines");
- cache.relationship_line_color=get_color("relationship_line_color");
- cache.scroll_border=get_constant("scroll_border");
- cache.scroll_speed=get_constant("scroll_speed");
+ cache.button_pressed = get_stylebox("button_pressed");
+
+ cache.checked = get_icon("checked");
+ cache.unchecked = get_icon("unchecked");
+ cache.arrow_collapsed = get_icon("arrow_collapsed");
+ cache.arrow = get_icon("arrow");
+ cache.select_arrow = get_icon("select_arrow");
+ cache.updown = get_icon("updown");
+
+ cache.font_color = get_color("font_color");
+ cache.font_color_selected = get_color("font_color_selected");
+ cache.guide_color = get_color("guide_color");
+ cache.drop_position_color = get_color("drop_position_color");
+ cache.hseparation = get_constant("hseparation");
+ cache.vseparation = get_constant("vseparation");
+ cache.item_margin = get_constant("item_margin");
+ cache.button_margin = get_constant("button_margin");
+ cache.guide_width = get_constant("guide_width");
+ cache.draw_relationship_lines = get_constant("draw_relationship_lines");
+ cache.relationship_line_color = get_color("relationship_line_color");
+ cache.scroll_border = get_constant("scroll_border");
+ cache.scroll_speed = get_constant("scroll_speed");
cache.title_button = get_stylebox("title_button_normal");
cache.title_button_pressed = get_stylebox("title_button_pressed");
@@ -848,39 +790,32 @@ void Tree::update_cache() {
cache.title_button_color = get_color("title_button_color");
v_scroll->set_custom_step(cache.font->get_height());
-
}
int Tree::compute_item_height(TreeItem *p_item) const {
- if (p_item==root && hide_root)
+ if (p_item == root && hide_root)
return 0;
- int height=cache.font->get_height();
-
-
- for (int i=0;i<columns.size();i++) {
+ int height = cache.font->get_height();
+ for (int i = 0; i < columns.size(); i++) {
- for(int j=0;j<p_item->cells[i].buttons.size();j++) {
+ for (int j = 0; j < p_item->cells[i].buttons.size(); j++) {
-
- Size2i s;// = cache.button_pressed->get_minimum_size();
- s+= p_item->cells[i].buttons[j].texture->get_size();
- if (s.height>height)
- height=s.height;
+ Size2i s; // = cache.button_pressed->get_minimum_size();
+ s += p_item->cells[i].buttons[j].texture->get_size();
+ if (s.height > height)
+ height = s.height;
}
- switch(p_item->cells[i].mode) {
+ switch (p_item->cells[i].mode) {
case TreeItem::CELL_MODE_CHECK: {
int check_icon_h = cache.checked->get_height();
- if (height<check_icon_h)
- height=check_icon_h;
-
-
-
+ if (height < check_icon_h)
+ height = check_icon_h;
}
case TreeItem::CELL_MODE_STRING:
case TreeItem::CELL_MODE_CUSTOM:
@@ -890,11 +825,11 @@ int Tree::compute_item_height(TreeItem *p_item) const {
if (!icon.is_null()) {
Size2i s = p_item->cells[i].get_icon_size();
- if (p_item->cells[i].icon_max_w>0 && s.width > p_item->cells[i].icon_max_w ) {
- s.height=s.height * p_item->cells[i].icon_max_w / s.width;
+ if (p_item->cells[i].icon_max_w > 0 && s.width > p_item->cells[i].icon_max_w) {
+ s.height = s.height * p_item->cells[i].icon_max_w / s.width;
}
- if (s.height > height )
- height=s.height;
+ if (s.height > height)
+ height = s.height;
}
} break;
@@ -902,51 +837,47 @@ int Tree::compute_item_height(TreeItem *p_item) const {
}
}
-
height += cache.vseparation;
return height;
-
}
int Tree::get_item_height(TreeItem *p_item) const {
- int height=compute_item_height(p_item);
- height+=cache.vseparation;
+ int height = compute_item_height(p_item);
+ height += cache.vseparation;
if (!p_item->collapsed) { /* if not collapsed, check the childs */
- TreeItem *c=p_item->childs;
+ TreeItem *c = p_item->childs;
while (c) {
- height += get_item_height( c );
+ height += get_item_height(c);
- c=c->next;
+ c = c->next;
}
}
return height;
}
+void Tree::draw_item_rect(const TreeItem::Cell &p_cell, const Rect2i &p_rect, const Color &p_color) {
-void Tree::draw_item_rect(const TreeItem::Cell& p_cell,const Rect2i& p_rect,const Color& p_color) {
-
- Rect2i rect=p_rect;
+ Rect2i rect = p_rect;
RID ci = get_canvas_item();
if (!p_cell.icon.is_null()) {
Size2i bmsize = p_cell.get_icon_size();
- if (p_cell.icon_max_w>0 && bmsize.width > p_cell.icon_max_w) {
+ if (p_cell.icon_max_w > 0 && bmsize.width > p_cell.icon_max_w) {
bmsize.height = bmsize.height * p_cell.icon_max_w / bmsize.width;
- bmsize.width=p_cell.icon_max_w;
+ bmsize.width = p_cell.icon_max_w;
}
- p_cell.draw_icon(ci,rect.pos + Size2i(0,Math::floor((real_t)(rect.size.y-bmsize.y)/2)),bmsize);
- rect.pos.x+=bmsize.x+cache.hseparation;
- rect.size.x-=bmsize.x+cache.hseparation;
-
+ p_cell.draw_icon(ci, rect.pos + Size2i(0, Math::floor((real_t)(rect.size.y - bmsize.y) / 2)), bmsize);
+ rect.pos.x += bmsize.x + cache.hseparation;
+ rect.size.x -= bmsize.x + cache.hseparation;
}
/*
@@ -957,12 +888,11 @@ void Tree::draw_item_rect(const TreeItem::Cell& p_cell,const Rect2i& p_rect,cons
Ref<Font> font = cache.font;
String text = p_cell.text;
- if (p_cell.suffix!=String())
- text+=" "+p_cell.suffix;
-
- rect.pos.y+=Math::floor((rect.size.y-font->get_height())/2.0) +font->get_ascent();
- font->draw(ci,rect.pos,text,p_color,rect.size.x);
+ if (p_cell.suffix != String())
+ text += " " + p_cell.suffix;
+ rect.pos.y += Math::floor((rect.size.y - font->get_height()) / 2.0) + font->get_ascent();
+ font->draw(ci, rect.pos, text, p_color, rect.size.x);
}
#if 0
@@ -991,27 +921,25 @@ void Tree::draw_item_text(String p_text,const Ref<Texture>& p_icon,int p_icon_ma
font->draw(ci,p_rect.pos,p_text,p_color,p_rect.size.x);
}
#endif
-int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2& p_draw_size,TreeItem *p_item) {
+int Tree::draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 &p_draw_size, TreeItem *p_item) {
- if (p_pos.y-cache.offset.y > (p_draw_size.height))
+ if (p_pos.y - cache.offset.y > (p_draw_size.height))
return -1; //draw no more!
RID ci = get_canvas_item();
- int htotal=0;
+ int htotal = 0;
- int label_h=compute_item_height( p_item );
+ int label_h = compute_item_height(p_item);
/* Calculate height of the label part */
- label_h+=cache.vseparation;
+ label_h += cache.vseparation;
/* Draw label, if height fits */
+ bool skip = (p_item == root && hide_root);
- bool skip=(p_item==root && hide_root);
-
-
- if (!skip && (p_pos.y+label_h-cache.offset.y)>0) {
+ if (!skip && (p_pos.y + label_h - cache.offset.y) > 0) {
if (!hide_folding && p_item->childs) { //has childs, draw the guide box
@@ -1019,15 +947,12 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
if (p_item->collapsed) {
- arrow=cache.arrow_collapsed;
+ arrow = cache.arrow_collapsed;
} else {
- arrow=cache.arrow;
-
+ arrow = cache.arrow;
}
- arrow->draw( ci , p_pos+p_draw_ofs+Point2i(0,(label_h-arrow->get_height())/2)-cache.offset);
-
-
+ arrow->draw(ci, p_pos + p_draw_ofs + Point2i(0, (label_h - arrow->get_height()) / 2) - cache.offset);
}
//draw separation.
@@ -1035,162 +960,156 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
Ref<Font> font = cache.font;
- int font_ascent=font->get_ascent();
+ int font_ascent = font->get_ascent();
- int ofs = p_pos.x + (hide_folding?cache.hseparation:cache.item_margin);
- for (int i=0;i<columns.size();i++) {
+ int ofs = p_pos.x + (hide_folding ? cache.hseparation : cache.item_margin);
+ for (int i = 0; i < columns.size(); i++) {
int w = get_column_width(i);
- if (i==0) {
+ if (i == 0) {
- w-=ofs;
+ w -= ofs;
- if (w<=0) {
+ if (w <= 0) {
- ofs=get_column_width(0);
+ ofs = get_column_width(0);
continue;
}
} else {
- ofs+=cache.hseparation;
- w-=cache.hseparation;
+ ofs += cache.hseparation;
+ w -= cache.hseparation;
}
- int bw=0;
- for(int j=p_item->cells[i].buttons.size()-1;j>=0;j--) {
- Ref<Texture> b=p_item->cells[i].buttons[j].texture;
+ int bw = 0;
+ for (int j = p_item->cells[i].buttons.size() - 1; j >= 0; j--) {
+ Ref<Texture> b = p_item->cells[i].buttons[j].texture;
Size2 s = b->get_size() + cache.button_pressed->get_minimum_size();
- Point2i o = Point2i( ofs+w-s.width, p_pos.y )-cache.offset+p_draw_ofs;
+ Point2i o = Point2i(ofs + w - s.width, p_pos.y) - cache.offset + p_draw_ofs;
- if (cache.click_type==Cache::CLICK_BUTTON && cache.click_item==p_item && cache.click_column==i && cache.click_index==j && !p_item->cells[i].buttons[j].disabled) {
+ if (cache.click_type == Cache::CLICK_BUTTON && cache.click_item == p_item && cache.click_column == i && cache.click_index == j && !p_item->cells[i].buttons[j].disabled) {
//being pressed
- cache.button_pressed->draw(get_canvas_item(),Rect2(o,s));
+ cache.button_pressed->draw(get_canvas_item(), Rect2(o, s));
}
- o.y+=(label_h-s.height)/2;
- o+=cache.button_pressed->get_offset();
+ o.y += (label_h - s.height) / 2;
+ o += cache.button_pressed->get_offset();
- b->draw(ci,o,p_item->cells[i].buttons[j].disabled?Color(1,1,1,0.5):p_item->cells[i].buttons[j].color);
- w-=s.width+cache.button_margin;
- bw+=s.width+cache.button_margin;
+ b->draw(ci, o, p_item->cells[i].buttons[j].disabled ? Color(1, 1, 1, 0.5) : p_item->cells[i].buttons[j].color);
+ w -= s.width + cache.button_margin;
+ bw += s.width + cache.button_margin;
}
- Rect2i item_rect = Rect2i( Point2i( ofs, p_pos.y )-cache.offset+p_draw_ofs, Size2i( w, label_h ));
- Rect2i cell_rect=item_rect;
- if (i!=0) {
- cell_rect.pos.x-=cache.hseparation;
- cell_rect.size.x+=cache.hseparation;
+ Rect2i item_rect = Rect2i(Point2i(ofs, p_pos.y) - cache.offset + p_draw_ofs, Size2i(w, label_h));
+ Rect2i cell_rect = item_rect;
+ if (i != 0) {
+ cell_rect.pos.x -= cache.hseparation;
+ cell_rect.size.x += cache.hseparation;
}
+ VisualServer::get_singleton()->canvas_item_add_line(ci, Point2i(cell_rect.pos.x, cell_rect.pos.y + cell_rect.size.height), cell_rect.pos + cell_rect.size, cache.guide_color, 1);
+ if (i == 0) {
- VisualServer::get_singleton()->canvas_item_add_line(ci,Point2i(cell_rect.pos.x,cell_rect.pos.y+cell_rect.size.height),cell_rect.pos+cell_rect.size,cache.guide_color,1);
-
- if (i==0) {
-
- if (p_item->cells[0].selected && select_mode==SELECT_ROW) {
- Rect2i row_rect = Rect2i( Point2i( cache.bg->get_margin(MARGIN_LEFT), item_rect.pos.y), Size2i( get_size().width-cache.bg->get_minimum_size().width, item_rect.size.y ));
+ if (p_item->cells[0].selected && select_mode == SELECT_ROW) {
+ Rect2i row_rect = Rect2i(Point2i(cache.bg->get_margin(MARGIN_LEFT), item_rect.pos.y), Size2i(get_size().width - cache.bg->get_minimum_size().width, item_rect.size.y));
//Rect2 r = Rect2i(row_rect.pos,row_rect.size);
//r.grow(cache.selected->get_margin(MARGIN_LEFT));
if (has_focus())
- cache.selected_focus->draw(ci,row_rect );
+ cache.selected_focus->draw(ci, row_rect);
else
- cache.selected->draw(ci,row_rect );
+ cache.selected->draw(ci, row_rect);
}
-
}
- if (p_item->cells[i].selected && select_mode!=SELECT_ROW) {
+ if (p_item->cells[i].selected && select_mode != SELECT_ROW) {
- Rect2i r(item_rect.pos,item_rect.size);
- if (p_item->cells[i].text.size() > 0){
+ Rect2i r(item_rect.pos, item_rect.size);
+ if (p_item->cells[i].text.size() > 0) {
float icon_width = p_item->cells[i].get_icon_size().width;
r.pos.x += icon_width;
r.size.x -= icon_width;
}
//r.grow(cache.selected->get_margin(MARGIN_LEFT));
- if (has_focus()){
- cache.selected_focus->draw(ci,r );
- p_item->set_meta("__focus_rect", Rect2(r.pos,r.size));
+ if (has_focus()) {
+ cache.selected_focus->draw(ci, r);
+ p_item->set_meta("__focus_rect", Rect2(r.pos, r.size));
} else {
- cache.selected->draw(ci,r );
+ cache.selected->draw(ci, r);
}
- if (text_editor->is_visible_in_tree()){
+ if (text_editor->is_visible_in_tree()) {
text_editor->set_pos(get_global_pos() + r.pos);
}
}
if (p_item->cells[i].custom_bg_color) {
- Rect2 r=cell_rect;
- r.pos.x-=cache.hseparation;
- r.size.x+=cache.hseparation;
+ Rect2 r = cell_rect;
+ r.pos.x -= cache.hseparation;
+ r.size.x += cache.hseparation;
if (p_item->cells[i].custom_bg_outline) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y,r.size.x,1),p_item->cells[i].bg_color);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y+r.size.y-1,r.size.x,1),p_item->cells[i].bg_color);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y,1,r.size.y),p_item->cells[i].bg_color);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x+r.size.x-1,r.pos.y,1,r.size.y),p_item->cells[i].bg_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, r.size.x, 1), p_item->cells[i].bg_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y + r.size.y - 1, r.size.x, 1), p_item->cells[i].bg_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, 1, r.size.y), p_item->cells[i].bg_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x + r.size.x - 1, r.pos.y, 1, r.size.y), p_item->cells[i].bg_color);
} else {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,r,p_item->cells[i].bg_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, r, p_item->cells[i].bg_color);
}
}
- if (drop_mode_flags && drop_mode_over==p_item) {
-
- Rect2 r=cell_rect;
+ if (drop_mode_flags && drop_mode_over == p_item) {
- if (drop_mode_section==-1 || drop_mode_section==0) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y,r.size.x,1),cache.drop_position_color);
+ Rect2 r = cell_rect;
+ if (drop_mode_section == -1 || drop_mode_section == 0) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, r.size.x, 1), cache.drop_position_color);
}
- if (drop_mode_section==0) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y,1,r.size.y),cache.drop_position_color);
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x+r.size.x-1,r.pos.y,1,r.size.y),cache.drop_position_color);
-
+ if (drop_mode_section == 0) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y, 1, r.size.y), cache.drop_position_color);
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x + r.size.x - 1, r.pos.y, 1, r.size.y), cache.drop_position_color);
}
- if (drop_mode_section==1 || drop_mode_section==0) {
- VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(r.pos.x,r.pos.y+r.size.y,r.size.x,1),cache.drop_position_color);
+ if (drop_mode_section == 1 || drop_mode_section == 0) {
+ VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(r.pos.x, r.pos.y + r.size.y, r.size.x, 1), cache.drop_position_color);
}
}
- Color col=p_item->cells[i].custom_color?p_item->cells[i].color:get_color( p_item->cells[i].selected?"font_color_selected":"font_color");
+ Color col = p_item->cells[i].custom_color ? p_item->cells[i].color : get_color(p_item->cells[i].selected ? "font_color_selected" : "font_color");
- Point2i text_pos=item_rect.pos;
- text_pos.y+=Math::floor((item_rect.size.y-font->get_height())/2) + font_ascent;
+ Point2i text_pos = item_rect.pos;
+ text_pos.y += Math::floor((item_rect.size.y - font->get_height()) / 2) + font_ascent;
switch (p_item->cells[i].mode) {
case TreeItem::CELL_MODE_STRING: {
- draw_item_rect(p_item->cells[i],item_rect,col);
+ draw_item_rect(p_item->cells[i], item_rect, col);
} break;
case TreeItem::CELL_MODE_CHECK: {
Ref<Texture> checked = cache.checked;
Ref<Texture> unchecked = cache.unchecked;
- Point2i check_ofs=item_rect.pos;
- check_ofs.y+=Math::floor((real_t)(item_rect.size.y-checked->get_height())/2);
+ Point2i check_ofs = item_rect.pos;
+ check_ofs.y += Math::floor((real_t)(item_rect.size.y - checked->get_height()) / 2);
if (p_item->cells[i].checked) {
- checked->draw( ci, check_ofs );
+ checked->draw(ci, check_ofs);
} else {
- unchecked->draw( ci, check_ofs );
-
+ unchecked->draw(ci, check_ofs);
}
- int check_w = checked->get_width()+cache.hseparation;
+ int check_w = checked->get_width() + cache.hseparation;
- text_pos.x+=check_w;
+ text_pos.x += check_w;
- item_rect.size.x-=check_w;
- item_rect.pos.x+=check_w;
+ item_rect.size.x -= check_w;
+ item_rect.pos.x += check_w;
- draw_item_rect(p_item->cells[i],item_rect,col);
+ draw_item_rect(p_item->cells[i], item_rect, col);
//font->draw( ci, text_pos, p_item->cells[i].text, col,item_rect.size.x-check_w );
@@ -1198,7 +1117,7 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
case TreeItem::CELL_MODE_RANGE:
case TreeItem::CELL_MODE_RANGE_EXPRESSION: {
- if (p_item->cells[i].text!="") {
+ if (p_item->cells[i].text != "") {
if (!p_item->cells[i].editable)
break;
@@ -1206,41 +1125,41 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
int option = (int)p_item->cells[i].val;
String s = p_item->cells[i].text;
- s=s.get_slicec(',',option);
+ s = s.get_slicec(',', option);
- if (p_item->cells[i].suffix!=String())
- s+=" "+p_item->cells[i].suffix;
+ if (p_item->cells[i].suffix != String())
+ s += " " + p_item->cells[i].suffix;
Ref<Texture> downarrow = cache.select_arrow;
- font->draw(ci, text_pos, s, col,item_rect.size.x-downarrow->get_width() );
+ font->draw(ci, text_pos, s, col, item_rect.size.x - downarrow->get_width());
//?
- Point2i arrow_pos=item_rect.pos;
- arrow_pos.x+=item_rect.size.x-downarrow->get_width();
- arrow_pos.y+=Math::floor(((item_rect.size.y-downarrow->get_height()))/2.0);
+ Point2i arrow_pos = item_rect.pos;
+ arrow_pos.x += item_rect.size.x - downarrow->get_width();
+ arrow_pos.y += Math::floor(((item_rect.size.y - downarrow->get_height())) / 2.0);
- downarrow->draw( ci, arrow_pos );
+ downarrow->draw(ci, arrow_pos);
} else {
Ref<Texture> updown = cache.updown;
- String valtext = String::num( p_item->cells[i].val, Math::step_decimals( p_item->cells[i].step ) );
+ String valtext = String::num(p_item->cells[i].val, Math::step_decimals(p_item->cells[i].step));
//String valtext = rtos( p_item->cells[i].val );
- if (p_item->cells[i].suffix!=String())
- valtext+=" "+p_item->cells[i].suffix;
+ if (p_item->cells[i].suffix != String())
+ valtext += " " + p_item->cells[i].suffix;
- font->draw( ci, text_pos, valtext, col, item_rect.size.x-updown->get_width());
+ font->draw(ci, text_pos, valtext, col, item_rect.size.x - updown->get_width());
if (!p_item->cells[i].editable)
break;
- Point2i updown_pos=item_rect.pos;
- updown_pos.x+=item_rect.size.x-updown->get_width();
- updown_pos.y+=Math::floor(((item_rect.size.y-updown->get_height()))/2.0);
+ Point2i updown_pos = item_rect.pos;
+ updown_pos.x += item_rect.size.x - updown->get_width();
+ updown_pos.y += Math::floor(((item_rect.size.y - updown->get_height())) / 2.0);
- updown->draw( ci, updown_pos );
+ updown->draw(ci, updown_pos);
}
} break;
@@ -1249,16 +1168,15 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
if (p_item->cells[i].icon.is_null())
break;
Size2i icon_size = p_item->cells[i].get_icon_size();
- if (p_item->cells[i].icon_max_w>0 && icon_size.width >p_item->cells[i].icon_max_w) {
+ if (p_item->cells[i].icon_max_w > 0 && icon_size.width > p_item->cells[i].icon_max_w) {
icon_size.height = icon_size.height * p_item->cells[i].icon_max_w / icon_size.width;
- icon_size.width=p_item->cells[i].icon_max_w;
+ icon_size.width = p_item->cells[i].icon_max_w;
}
- Point2i icon_ofs = (item_rect.size-icon_size)/2;
- icon_ofs+=item_rect.pos;
+ Point2i icon_ofs = (item_rect.size - icon_size) / 2;
+ icon_ofs += item_rect.pos;
-
- draw_texture_rect(p_item->cells[i].icon,Rect2(icon_ofs,icon_size));
+ draw_texture_rect(p_item->cells[i].icon, Rect2(icon_ofs, icon_size));
//p_item->cells[i].icon->draw(ci, icon_ofs);
} break;
@@ -1266,253 +1184,234 @@ int Tree::draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2&
//int option = (int)p_item->cells[i].val;
-
-
if (p_item->cells[i].custom_draw_obj) {
- Object* cdo = ObjectDB::get_instance(p_item->cells[i].custom_draw_obj);
+ Object *cdo = ObjectDB::get_instance(p_item->cells[i].custom_draw_obj);
if (cdo)
- cdo->call(p_item->cells[i].custom_draw_callback,p_item,Rect2(item_rect));
+ cdo->call(p_item->cells[i].custom_draw_callback, p_item, Rect2(item_rect));
}
if (!p_item->cells[i].editable) {
- draw_item_rect(p_item->cells[i],item_rect,col);
+ draw_item_rect(p_item->cells[i], item_rect, col);
break;
}
Ref<Texture> downarrow = cache.select_arrow;
- Rect2i ir=item_rect;
- ir.size.width-=downarrow->get_width();
- draw_item_rect(p_item->cells[i],ir,col);
+ Rect2i ir = item_rect;
+ ir.size.width -= downarrow->get_width();
+ draw_item_rect(p_item->cells[i], ir, col);
- Point2i arrow_pos=item_rect.pos;
- arrow_pos.x+=item_rect.size.x-downarrow->get_width();
- arrow_pos.y+=Math::floor(((item_rect.size.y-downarrow->get_height()))/2.0);
+ Point2i arrow_pos = item_rect.pos;
+ arrow_pos.x += item_rect.size.x - downarrow->get_width();
+ arrow_pos.y += Math::floor(((item_rect.size.y - downarrow->get_height())) / 2.0);
- downarrow->draw( ci, arrow_pos );
+ downarrow->draw(ci, arrow_pos);
} break;
}
- if (i==0) {
+ if (i == 0) {
- ofs=get_column_width(0);
+ ofs = get_column_width(0);
} else {
- ofs+=w+bw;
+ ofs += w + bw;
}
- if (select_mode==SELECT_MULTI && selected_item==p_item && selected_col==i) {
+ if (select_mode == SELECT_MULTI && selected_item == p_item && selected_col == i) {
if (has_focus())
- cache.cursor->draw(ci,cell_rect);
+ cache.cursor->draw(ci, cell_rect);
else
- cache.cursor_unfocus->draw(ci,cell_rect);
+ cache.cursor_unfocus->draw(ci, cell_rect);
}
-
}
//separator
//get_painter()->draw_fill_rect( Point2i(0,pos.y),Size2i(get_size().width,1),color( COLOR_TREE_GRID) );
//pos=p_pos; //reset pos
-
}
-
- Point2 children_pos=p_pos;
+ Point2 children_pos = p_pos;
if (!skip) {
- children_pos.x+=cache.item_margin;
- htotal+=label_h;
- children_pos.y+=htotal;
-
+ children_pos.x += cache.item_margin;
+ htotal += label_h;
+ children_pos.y += htotal;
}
-
if (!p_item->collapsed) { /* if not collapsed, check the childs */
- TreeItem *c=p_item->childs;
+ TreeItem *c = p_item->childs;
while (c) {
- if (cache.draw_relationship_lines == 1){
- int root_ofs = children_pos.x + (hide_folding?cache.hseparation:cache.item_margin);
- int parent_ofs = p_pos.x + (hide_folding?cache.hseparation:cache.item_margin);
- Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h/2)-cache.offset+p_draw_ofs;
+ if (cache.draw_relationship_lines == 1) {
+ int root_ofs = children_pos.x + (hide_folding ? cache.hseparation : cache.item_margin);
+ int parent_ofs = p_pos.x + (hide_folding ? cache.hseparation : cache.item_margin);
+ Point2i root_pos = Point2i(root_ofs, children_pos.y + label_h / 2) - cache.offset + p_draw_ofs;
if (c->get_children() != NULL)
- root_pos -= Point2i(cache.arrow->get_width(),0);
+ root_pos -= Point2i(cache.arrow->get_width(), 0);
- Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width()/2, p_pos.y + label_h/2 + cache.arrow->get_height()/2)-cache.offset+p_draw_ofs;
+ Point2i parent_pos = Point2i(parent_ofs - cache.arrow->get_width() / 2, p_pos.y + label_h / 2 + cache.arrow->get_height() / 2) - cache.offset + p_draw_ofs;
VisualServer::get_singleton()->canvas_item_add_line(ci, root_pos, Point2i(parent_pos.x, root_pos.y), cache.relationship_line_color);
VisualServer::get_singleton()->canvas_item_add_line(ci, Point2i(parent_pos.x, root_pos.y), parent_pos, cache.relationship_line_color);
}
- int child_h=draw_item(children_pos, p_draw_ofs, p_draw_size, c );
+ int child_h = draw_item(children_pos, p_draw_ofs, p_draw_size, c);
- if (child_h<0 && cache.draw_relationship_lines == 0)
+ if (child_h < 0 && cache.draw_relationship_lines == 0)
return -1; // break, stop drawing, no need to anymore
- htotal+=child_h;
- children_pos.y+=child_h;
- c=c->next;
+ htotal += child_h;
+ children_pos.y += child_h;
+ c = c->next;
}
}
-
return htotal;
-
-
}
-int Tree::_count_selected_items(TreeItem* p_from) const {
+int Tree::_count_selected_items(TreeItem *p_from) const {
- int count=0;
- for(int i=0;i<columns.size();i++) {
+ int count = 0;
+ for (int i = 0; i < columns.size(); i++) {
if (p_from->is_selected(i))
count++;
}
if (p_from->get_children()) {
- count+=_count_selected_items(p_from->get_children());
+ count += _count_selected_items(p_from->get_children());
}
if (p_from->get_next()) {
- count+=_count_selected_items(p_from->get_next());
+ count += _count_selected_items(p_from->get_next());
}
return count;
-
}
void Tree::select_single_item(TreeItem *p_selected, TreeItem *p_current, int p_col, TreeItem *p_prev, bool *r_in_range, bool p_force_deselect) {
- TreeItem::Cell &selected_cell=p_selected->cells[p_col];
+ TreeItem::Cell &selected_cell = p_selected->cells[p_col];
- bool switched=false;
- if (r_in_range && !*r_in_range && (p_current==p_selected || p_current==p_prev)) {
- *r_in_range=true;
- switched=true;
+ bool switched = false;
+ if (r_in_range && !*r_in_range && (p_current == p_selected || p_current == p_prev)) {
+ *r_in_range = true;
+ switched = true;
}
- bool emitted_row=false;
+ bool emitted_row = false;
- for (int i=0;i<columns.size();i++) {
+ for (int i = 0; i < columns.size(); i++) {
- TreeItem::Cell &c=p_current->cells[i];
+ TreeItem::Cell &c = p_current->cells[i];
if (!c.selectable)
continue;
- if (select_mode==SELECT_ROW) {
+ if (select_mode == SELECT_ROW) {
- if (p_selected==p_current && !c.selected) {
- c.selected=true;
- selected_item=p_selected;
- selected_col=0;
- selected_item=p_selected;
- if (!emitted_row) {
- emit_signal("item_selected");
- emitted_row=true;
- }
- /*
+ if (p_selected == p_current && !c.selected) {
+ c.selected = true;
+ selected_item = p_selected;
+ selected_col = 0;
+ selected_item = p_selected;
+ if (!emitted_row) {
+ emit_signal("item_selected");
+ emitted_row = true;
+ }
+ /*
if (p_col==i)
p_current->selected_signal.call(p_col);
*/
} else if (c.selected) {
- c.selected=false;
- //p_current->deselected_signal.call(p_col);
+ c.selected = false;
+ //p_current->deselected_signal.call(p_col);
}
- } else if (select_mode==SELECT_SINGLE || select_mode==SELECT_MULTI) {
+ } else if (select_mode == SELECT_SINGLE || select_mode == SELECT_MULTI) {
- if (!r_in_range && &selected_cell==&c) {
+ if (!r_in_range && &selected_cell == &c) {
if (!selected_cell.selected) {
- selected_cell.selected=true;
+ selected_cell.selected = true;
- selected_item=p_selected;
- selected_col=i;
+ selected_item = p_selected;
+ selected_col = i;
emit_signal("cell_selected");
- if (select_mode==SELECT_MULTI)
- emit_signal("multi_selected",p_current,i,true);
- else if(select_mode == SELECT_SINGLE)
+ if (select_mode == SELECT_MULTI)
+ emit_signal("multi_selected", p_current, i, true);
+ else if (select_mode == SELECT_SINGLE)
emit_signal("item_selected");
- } else if (select_mode==SELECT_MULTI && (selected_item!=p_selected || selected_col!=i)) {
+ } else if (select_mode == SELECT_MULTI && (selected_item != p_selected || selected_col != i)) {
- selected_item=p_selected;
- selected_col=i;
+ selected_item = p_selected;
+ selected_col = i;
emit_signal("cell_selected");
-
}
} else {
-
if (r_in_range && *r_in_range && !p_force_deselect) {
-
if (!c.selected && c.selectable) {
- c.selected=true;
- emit_signal("multi_selected",p_current,i,true);
+ c.selected = true;
+ emit_signal("multi_selected", p_current, i, true);
}
- } else if (!r_in_range || p_force_deselect){
- if (select_mode==SELECT_MULTI && c.selected)
- emit_signal("multi_selected",p_current,i,false);
- c.selected=false;
+ } else if (!r_in_range || p_force_deselect) {
+ if (select_mode == SELECT_MULTI && c.selected)
+ emit_signal("multi_selected", p_current, i, false);
+ c.selected = false;
}
//p_current->deselected_signal.call(p_col);
}
}
-
}
- if (!switched && r_in_range && *r_in_range && (p_current==p_selected || p_current==p_prev)) {
- *r_in_range=false;
+ if (!switched && r_in_range && *r_in_range && (p_current == p_selected || p_current == p_prev)) {
+ *r_in_range = false;
}
- TreeItem *c=p_current->childs;
+ TreeItem *c = p_current->childs;
while (c) {
- select_single_item(p_selected,c,p_col,p_prev,r_in_range,p_current->is_collapsed() || p_force_deselect);
- c=c->next;
+ select_single_item(p_selected, c, p_col, p_prev, r_in_range, p_current->is_collapsed() || p_force_deselect);
+ c = c->next;
}
-
}
-
Rect2 Tree::search_item_rect(TreeItem *p_from, TreeItem *p_item) {
-
return Rect2();
}
-
void Tree::_range_click_timeout() {
if (range_item_last && !range_drag_enabled && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) {
- Point2 pos = get_local_mouse_pos()-cache.bg->get_offset();
+ Point2 pos = get_local_mouse_pos() - cache.bg->get_offset();
if (show_column_titles) {
- pos.y-=_get_title_button_height();
+ pos.y -= _get_title_button_height();
- if (pos.y<0) {
+ if (pos.y < 0) {
range_click_timer->stop();
return;
}
}
- click_handled=false;
+ click_handled = false;
InputModifierState mod = InputModifierState(); // should be irrelevant..
blocked++;
- propagate_mouse_event(pos+cache.offset, 0, 0, false, root, BUTTON_LEFT, mod);
+ propagate_mouse_event(pos + cache.offset, 0, 0, false, root, BUTTON_LEFT, mod);
blocked--;
if (range_click_timer->is_one_shot()) {
@@ -1529,120 +1428,112 @@ void Tree::_range_click_timeout() {
}
}
+int Tree::propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, bool p_doubleclick, TreeItem *p_item, int p_button, const InputModifierState &p_mod) {
-int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_doubleclick,TreeItem *p_item,int p_button,const InputModifierState& p_mod) {
+ int item_h = compute_item_height(p_item) + cache.vseparation;
- int item_h=compute_item_height( p_item )+cache.vseparation;
+ bool skip = (p_item == root && hide_root);
- bool skip=(p_item==root && hide_root);
-
- if (!skip && p_pos.y<item_h) {
+ if (!skip && p_pos.y < item_h) {
// check event!
if (range_click_timer->get_time_left() > 0 && p_item != range_item_last) {
return -1;
}
- if (!hide_folding && (p_pos.x >=x_ofs && p_pos.x < (x_ofs+cache.item_margin) )) {
-
+ if (!hide_folding && (p_pos.x >= x_ofs && p_pos.x < (x_ofs + cache.item_margin))) {
if (p_item->childs)
- p_item->set_collapsed( ! p_item->is_collapsed() );
+ p_item->set_collapsed(!p_item->is_collapsed());
return -1; //handled!
}
- int x=p_pos.x;
+ int x = p_pos.x;
/* find clicked column */
- int col=-1;
- int col_ofs=0;
- int col_width=0;
- for (int i=0;i<columns.size();i++) {
-
- col_width=get_column_width(i);
- if (x>col_width) {
- col_ofs+=col_width;
- x-=col_width;
+ int col = -1;
+ int col_ofs = 0;
+ int col_width = 0;
+ for (int i = 0; i < columns.size(); i++) {
+
+ col_width = get_column_width(i);
+ if (x > col_width) {
+ col_ofs += col_width;
+ x -= col_width;
continue;
}
- col=i;
+ col = i;
break;
}
-
-
- if (col==-1)
+ if (col == -1)
return -1;
- else if (col==0) {
- int margin=x_ofs+cache.item_margin;//-cache.hseparation;
+ else if (col == 0) {
+ int margin = x_ofs + cache.item_margin; //-cache.hseparation;
//int lm = cache.bg->get_margin(MARGIN_LEFT);
- col_width-=margin;
- col_ofs+=margin;
- x-=margin;
+ col_width -= margin;
+ col_ofs += margin;
+ x -= margin;
} else {
- col_width-=cache.hseparation;
- x-=cache.hseparation;
-
+ col_width -= cache.hseparation;
+ x -= cache.hseparation;
}
TreeItem::Cell &c = p_item->cells[col];
+ bool already_selected = c.selected;
+ bool already_cursor = (p_item == selected_item) && col == selected_col;
- bool already_selected=c.selected;
- bool already_cursor=(p_item==selected_item) && col == selected_col;
-
-
- for(int j=c.buttons.size()-1;j>=0;j--) {
- Ref<Texture> b=c.buttons[j].texture;
+ for (int j = c.buttons.size() - 1; j >= 0; j--) {
+ Ref<Texture> b = c.buttons[j].texture;
int w = b->get_size().width + cache.button_pressed->get_minimum_size().width;
- if (x>col_width-w) {
+ if (x > col_width - w) {
if (c.buttons[j].disabled) {
- pressed_button=-1;
- cache.click_type=Cache::CLICK_NONE;
+ pressed_button = -1;
+ cache.click_type = Cache::CLICK_NONE;
return -1;
}
- pressed_button=j;
- cache.click_type=Cache::CLICK_BUTTON;
- cache.click_index=j;
- cache.click_id=c.buttons[j].id;
- cache.click_item=p_item;
- cache.click_column=col;
- cache.click_pos=get_global_mouse_pos()-get_global_pos();
+ pressed_button = j;
+ cache.click_type = Cache::CLICK_BUTTON;
+ cache.click_index = j;
+ cache.click_id = c.buttons[j].id;
+ cache.click_item = p_item;
+ cache.click_column = col;
+ cache.click_pos = get_global_mouse_pos() - get_global_pos();
update();
//emit_signal("button_pressed");
return -1;
}
- col_width-=w+cache.button_margin;
+ col_width -= w + cache.button_margin;
}
- if (p_button==BUTTON_LEFT || (p_button==BUTTON_RIGHT && allow_rmb_select)) {
+ if (p_button == BUTTON_LEFT || (p_button == BUTTON_RIGHT && allow_rmb_select)) {
/* process selection */
- if (p_doubleclick && (!c.editable || c.mode==TreeItem::CELL_MODE_CUSTOM || c.mode==TreeItem::CELL_MODE_ICON /*|| c.mode==TreeItem::CELL_MODE_CHECK*/)) { //it' s confusing for check
+ if (p_doubleclick && (!c.editable || c.mode == TreeItem::CELL_MODE_CUSTOM || c.mode == TreeItem::CELL_MODE_ICON /*|| c.mode==TreeItem::CELL_MODE_CHECK*/)) { //it' s confusing for check
emit_signal("item_activated");
return -1;
}
- if (select_mode==SELECT_MULTI && p_mod.command && c.selectable) {
+ if (select_mode == SELECT_MULTI && p_mod.command && c.selectable) {
- if (!c.selected || p_button==BUTTON_RIGHT) {
+ if (!c.selected || p_button == BUTTON_RIGHT) {
p_item->select(col);
- emit_signal("multi_selected",p_item,col,true);
- if (p_button==BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",get_local_mouse_pos());
+ emit_signal("multi_selected", p_item, col, true);
+ if (p_button == BUTTON_RIGHT) {
+ emit_signal("item_rmb_selected", get_local_mouse_pos());
}
-
//p_item->selected_signal.call(col);
} else {
p_item->deselect(col);
- emit_signal("multi_selected",p_item,col,false);
+ emit_signal("multi_selected", p_item, col, false);
//p_item->deselected_signal.call(col);
}
@@ -1650,29 +1541,29 @@ int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_
if (c.selectable) {
- if (select_mode==SELECT_MULTI && p_mod.shift && selected_item && selected_item!=p_item) {
+ if (select_mode == SELECT_MULTI && p_mod.shift && selected_item && selected_item != p_item) {
- bool inrange=false;
+ bool inrange = false;
- select_single_item( p_item, root, col,selected_item,&inrange );
- if (p_button==BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",get_local_mouse_pos());
+ select_single_item(p_item, root, col, selected_item, &inrange);
+ if (p_button == BUTTON_RIGHT) {
+ emit_signal("item_rmb_selected", get_local_mouse_pos());
}
} else {
int icount = _count_selected_items(root);
- if (select_mode==SELECT_MULTI && icount>1 && p_button!=BUTTON_RIGHT) {
- single_select_defer=p_item;
- single_select_defer_column=col;
+ if (select_mode == SELECT_MULTI && icount > 1 && p_button != BUTTON_RIGHT) {
+ single_select_defer = p_item;
+ single_select_defer_column = col;
} else {
- if (p_button!=BUTTON_RIGHT || !c.selected) {
- select_single_item( p_item, root, col );
+ if (p_button != BUTTON_RIGHT || !c.selected) {
+ select_single_item(p_item, root, col);
}
- if (p_button==BUTTON_RIGHT) {
- emit_signal("item_rmb_selected",get_local_mouse_pos());
+ if (p_button == BUTTON_RIGHT) {
+ emit_signal("item_rmb_selected", get_local_mouse_pos());
}
}
}
@@ -1684,34 +1575,30 @@ int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_
*/
update();
}
-
-
}
}
-
-
if (!c.editable)
return -1; // if cell is not editable, don't bother
/* editing */
- bool bring_up_editor=force_select_on_already_selected ? (c.selected && already_selected) : c.selected;
- String editor_text=c.text;
+ bool bring_up_editor = force_select_on_already_selected ? (c.selected && already_selected) : c.selected;
+ String editor_text = c.text;
switch (c.mode) {
case TreeItem::CELL_MODE_STRING: {
//nothing in particular
- if (select_mode==SELECT_MULTI && (get_tree()->get_last_event_id() == focus_in_id || !already_cursor)) {
- bring_up_editor=false;
+ if (select_mode == SELECT_MULTI && (get_tree()->get_last_event_id() == focus_in_id || !already_cursor)) {
+ bring_up_editor = false;
}
} break;
case TreeItem::CELL_MODE_CHECK: {
- bring_up_editor=false; //checkboxes are not edited with editor
+ bring_up_editor = false; //checkboxes are not edited with editor
if (force_edit_checkbox_only_on_checkbox) {
if (x < cache.checked->get_width()) {
p_item->set_checked(col, !c.checked);
@@ -1728,38 +1615,36 @@ int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_
case TreeItem::CELL_MODE_RANGE:
case TreeItem::CELL_MODE_RANGE_EXPRESSION: {
-
- if (c.text!="") {
+ if (c.text != "") {
//if (x >= (get_column_width(col)-item_h/2)) {
popup_menu->clear();
- for (int i=0;i<c.text.get_slice_count(",");i++) {
-
- String s = c.text.get_slicec(',',i);
- popup_menu->add_item(s,i);
+ for (int i = 0; i < c.text.get_slice_count(","); i++) {
+ String s = c.text.get_slicec(',', i);
+ popup_menu->add_item(s, i);
}
- popup_menu->set_size(Size2(col_width,0));
- popup_menu->set_pos( get_global_pos() + Point2i(col_ofs,_get_title_button_height()+y_ofs+item_h)-cache.offset );
+ popup_menu->set_size(Size2(col_width, 0));
+ popup_menu->set_pos(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs + item_h) - cache.offset);
popup_menu->popup();
- popup_edited_item=p_item;
- popup_edited_item_col=col;
+ popup_edited_item = p_item;
+ popup_edited_item_col = col;
//}
- bring_up_editor=false;
+ bring_up_editor = false;
} else {
- if (x >= (col_width-item_h/2)) {
+ if (x >= (col_width - item_h / 2)) {
/* touching the combo */
- bool up=p_pos.y < (item_h /2);
+ bool up = p_pos.y < (item_h / 2);
- if (p_button==BUTTON_LEFT) {
+ if (p_button == BUTTON_LEFT) {
if (range_click_timer->get_time_left() == 0) {
- range_item_last=p_item;
- range_up_last=up;
+ range_item_last = p_item;
+ range_up_last = up;
range_click_timer->set_wait_time(0.6);
range_click_timer->set_one_shot(true);
@@ -1770,115 +1655,103 @@ int Tree::propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_
return -1; // break. avoid changing direction on mouse held
}
- p_item->set_range( col, c.val + (up?1.0:-1.0) * c.step );
+ p_item->set_range(col, c.val + (up ? 1.0 : -1.0) * c.step);
- item_edited(col,p_item);
+ item_edited(col, p_item);
- } else if (p_button==BUTTON_RIGHT) {
+ } else if (p_button == BUTTON_RIGHT) {
- p_item->set_range( col, (up?c.max:c.min) );
- item_edited(col,p_item);
- } else if (p_button==BUTTON_WHEEL_UP) {
+ p_item->set_range(col, (up ? c.max : c.min));
+ item_edited(col, p_item);
+ } else if (p_button == BUTTON_WHEEL_UP) {
- p_item->set_range( col, c.val + c.step );
- item_edited(col,p_item);
- } else if (p_button==BUTTON_WHEEL_DOWN) {
+ p_item->set_range(col, c.val + c.step);
+ item_edited(col, p_item);
+ } else if (p_button == BUTTON_WHEEL_DOWN) {
- p_item->set_range( col, c.val - c.step );
- item_edited(col,p_item);
+ p_item->set_range(col, c.val - c.step);
+ item_edited(col, p_item);
}
//p_item->edited_signal.call(col);
- bring_up_editor=false;
-
-
- } else {
+ bring_up_editor = false;
- editor_text=String::num( p_item->cells[col].val, Math::step_decimals( p_item->cells[col].step ) );
- if (select_mode==SELECT_MULTI && get_tree()->get_last_event_id() == focus_in_id)
- bring_up_editor=false;
+ } else {
+ editor_text = String::num(p_item->cells[col].val, Math::step_decimals(p_item->cells[col].step));
+ if (select_mode == SELECT_MULTI && get_tree()->get_last_event_id() == focus_in_id)
+ bring_up_editor = false;
}
-
}
- click_handled=true;
+ click_handled = true;
} break;
case TreeItem::CELL_MODE_ICON: {
- bring_up_editor=false;
+ bring_up_editor = false;
} break;
case TreeItem::CELL_MODE_CUSTOM: {
- edited_item=p_item;
- edited_col=col;
- custom_popup_rect=Rect2i(get_global_pos() + Point2i(col_ofs,_get_title_button_height()+y_ofs+item_h-cache.offset.y), Size2(get_column_width(col),item_h));
- emit_signal("custom_popup_edited",((bool)(x >= (col_width-item_h/2))));
-
- bring_up_editor=false;
- item_edited(col,p_item);
- click_handled=true;
+ edited_item = p_item;
+ edited_col = col;
+ custom_popup_rect = Rect2i(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs + item_h - cache.offset.y), Size2(get_column_width(col), item_h));
+ emit_signal("custom_popup_edited", ((bool)(x >= (col_width - item_h / 2))));
+
+ bring_up_editor = false;
+ item_edited(col, p_item);
+ click_handled = true;
return -1;
} break;
-
};
- if (!bring_up_editor || p_button!=BUTTON_LEFT)
+ if (!bring_up_editor || p_button != BUTTON_LEFT)
return -1;
+ click_handled = true;
+ popup_edited_item = p_item;
+ popup_edited_item_col = col;
-
- click_handled=true;
- popup_edited_item=p_item;
- popup_edited_item_col=col;
-
- pressing_item_rect=Rect2(get_global_pos() + Point2i(col_ofs,_get_title_button_height()+y_ofs)-cache.offset,Size2(col_width,item_h));
- pressing_for_editor_text=editor_text;
- pressing_for_editor=true;
+ pressing_item_rect = Rect2(get_global_pos() + Point2i(col_ofs, _get_title_button_height() + y_ofs) - cache.offset, Size2(col_width, item_h));
+ pressing_for_editor_text = editor_text;
+ pressing_for_editor = true;
return -1; //select
} else {
- Point2i new_pos=p_pos;
+ Point2i new_pos = p_pos;
if (!skip) {
- x_ofs+=cache.item_margin;
+ x_ofs += cache.item_margin;
//new_pos.x-=cache.item_margin;
- y_ofs+=item_h;
- new_pos.y-=item_h;
+ y_ofs += item_h;
+ new_pos.y -= item_h;
}
-
if (!p_item->collapsed) { /* if not collapsed, check the childs */
- TreeItem *c=p_item->childs;
+ TreeItem *c = p_item->childs;
while (c) {
- int child_h=propagate_mouse_event( new_pos,x_ofs,y_ofs,p_doubleclick,c,p_button,p_mod);
+ int child_h = propagate_mouse_event(new_pos, x_ofs, y_ofs, p_doubleclick, c, p_button, p_mod);
- if (child_h<0)
+ if (child_h < 0)
return -1; // break, stop propagating, no need to anymore
- new_pos.y-=child_h;
- y_ofs+=child_h;
- c=c->next;
- item_h+=child_h;
+ new_pos.y -= child_h;
+ y_ofs += child_h;
+ c = c->next;
+ item_h += child_h;
}
}
-
-
-
}
return item_h; // nothing found
-
}
-
void Tree::_text_editor_modal_close() {
- if ( Input::get_singleton()->is_key_pressed(KEY_ESCAPE) ||
- Input::get_singleton()->is_key_pressed(KEY_ENTER) ||
- Input::get_singleton()->is_key_pressed(KEY_RETURN) ) {
+ if (Input::get_singleton()->is_key_pressed(KEY_ESCAPE) ||
+ Input::get_singleton()->is_key_pressed(KEY_ENTER) ||
+ Input::get_singleton()->is_key_pressed(KEY_RETURN)) {
return;
}
@@ -1889,52 +1762,49 @@ void Tree::_text_editor_modal_close() {
text_editor_enter(text_editor->get_text());
}
-
void Tree::text_editor_enter(String p_text) {
-
text_editor->hide();
value_editor->hide();
if (!popup_edited_item)
return;
- if (popup_edited_item_col<0 || popup_edited_item_col>columns.size())
+ if (popup_edited_item_col < 0 || popup_edited_item_col > columns.size())
return;
- TreeItem::Cell &c=popup_edited_item->cells[popup_edited_item_col];
- switch( c.mode ) {
+ TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col];
+ switch (c.mode) {
case TreeItem::CELL_MODE_STRING: {
- c.text=p_text;
+ c.text = p_text;
//popup_edited_item->edited_signal.call( popup_edited_item_col );
} break;
case TreeItem::CELL_MODE_RANGE: {
- c.val=p_text.to_double();
- if (c.step>0)
- c.val=Math::stepify(c.val,c.step);
- if (c.val<c.min)
- c.val=c.min;
- else if (c.val>c.max)
- c.val=c.max;
+ c.val = p_text.to_double();
+ if (c.step > 0)
+ c.val = Math::stepify(c.val, c.step);
+ if (c.val < c.min)
+ c.val = c.min;
+ else if (c.val > c.max)
+ c.val = c.max;
//popup_edited_item->edited_signal.call( popup_edited_item_col );
} break;
case TreeItem::CELL_MODE_RANGE_EXPRESSION: {
- if(evaluator)
- c.val=evaluator->eval(p_text);
+ if (evaluator)
+ c.val = evaluator->eval(p_text);
else
- c.val=p_text.to_double();
+ c.val = p_text.to_double();
} break;
- default: { ERR_FAIL(); }
+ default: { ERR_FAIL(); }
}
- item_edited(popup_edited_item_col,popup_edited_item);
+ item_edited(popup_edited_item_col, popup_edited_item);
update();
-
}
void Tree::value_editor_changed(double p_value) {
@@ -1946,9 +1816,9 @@ void Tree::value_editor_changed(double p_value) {
return;
}
- TreeItem::Cell &c=popup_edited_item->cells[popup_edited_item_col];
- c.val=p_value;
- item_edited(popup_edited_item_col,popup_edited_item);
+ TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col];
+ c.val = p_value;
+ item_edited(popup_edited_item_col, popup_edited_item);
update();
}
@@ -1957,18 +1827,15 @@ void Tree::popup_select(int p_option) {
if (!popup_edited_item)
return;
- if (popup_edited_item_col<0 || popup_edited_item_col>columns.size())
+ if (popup_edited_item_col < 0 || popup_edited_item_col > columns.size())
return;
-
- popup_edited_item->cells[popup_edited_item_col].val=p_option;
+ popup_edited_item->cells[popup_edited_item_col].val = p_option;
//popup_edited_item->edited_signal.call( popup_edited_item_col );
update();
- item_edited(popup_edited_item_col,popup_edited_item);
+ item_edited(popup_edited_item_col, popup_edited_item);
}
-
-
void Tree::_gui_input(InputEvent p_event) {
switch (p_event.type) {
@@ -1977,7 +1844,7 @@ void Tree::_gui_input(InputEvent p_event) {
if (!p_event.key.pressed)
break;
- if (p_event.key.mod.alt || p_event.key.mod.command || (p_event.key.mod.shift && p_event.key.unicode==0) || p_event.key.mod.meta)
+ if (p_event.key.mod.alt || p_event.key.mod.command || (p_event.key.mod.shift && p_event.key.unicode == 0) || p_event.key.mod.meta)
break;
if (!root)
return;
@@ -1985,23 +1852,27 @@ void Tree::_gui_input(InputEvent p_event) {
if (hide_root && !root->get_next_visible())
return;
- switch(p_event.key.scancode) {
-#define EXIT_BREAK { if (!cursor_can_exit_tree) accept_event(); break; }
+ switch (p_event.key.scancode) {
+#define EXIT_BREAK \
+ { \
+ if (!cursor_can_exit_tree) accept_event(); \
+ break; \
+ }
case KEY_RIGHT: {
//TreeItem *next = NULL;
if (!selected_item)
break;
- if (select_mode==SELECT_ROW)
+ if (select_mode == SELECT_ROW)
EXIT_BREAK;
- if (selected_col>=(columns.size()-1))
+ if (selected_col >= (columns.size() - 1))
EXIT_BREAK;
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
selected_col++;
emit_signal("cell_selected");
} else {
- selected_item->select(selected_col+1);
+ selected_item->select(selected_col + 1);
}
update();
@@ -2014,16 +1885,16 @@ void Tree::_gui_input(InputEvent p_event) {
//TreeItem *next = NULL;
if (!selected_item)
break;
- if (select_mode==SELECT_ROW)
+ if (select_mode == SELECT_ROW)
EXIT_BREAK;
- if (selected_col<=0)
+ if (selected_col <= 0)
EXIT_BREAK;
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
selected_col--;
emit_signal("cell_selected");
} else {
- selected_item->select(selected_col-1);
+ selected_item->select(selected_col - 1);
}
update();
@@ -2035,43 +1906,41 @@ void Tree::_gui_input(InputEvent p_event) {
TreeItem *next = NULL;
if (!selected_item) {
- next=hide_root?root->get_next_visible():root;
- selected_item=0;
+ next = hide_root ? root->get_next_visible() : root;
+ selected_item = 0;
} else {
- next=selected_item->get_next_visible();
+ next = selected_item->get_next_visible();
//if (diff < uint64_t(GLOBAL_DEF("gui/incr_search_max_interval_msec",2000))) {
- if (last_keypress!=0) {
+ if (last_keypress != 0) {
//incr search next
int col;
- next=_search_item_text(next,incr_search,&col,true);
+ next = _search_item_text(next, incr_search, &col, true);
if (!next) {
accept_event();
return;
}
-
}
}
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
if (!next)
EXIT_BREAK;
- selected_item=next;
+ selected_item = next;
emit_signal("cell_selected");
update();
} else {
- int col=selected_col<0?0:selected_col;
+ int col = selected_col < 0 ? 0 : selected_col;
while (next && !next->cells[col].selectable)
- next=next->get_next_visible();
+ next = next->get_next_visible();
if (!next)
EXIT_BREAK; // do nothing..
next->select(col);
-
}
ensure_cursor_is_visible();
@@ -2080,47 +1949,43 @@ void Tree::_gui_input(InputEvent p_event) {
} break;
case KEY_UP: {
- TreeItem *prev = NULL;
- if (!selected_item) {
- prev = get_last_item();
- selected_col=0;
- } else {
-
- prev=selected_item->get_prev_visible();
- if (last_keypress!=0) {
- //incr search next
- int col;
- prev=_search_item_text(prev,incr_search,&col,true,true);
- if (!prev) {
- accept_event();
- return;
- }
+ TreeItem *prev = NULL;
+ if (!selected_item) {
+ prev = get_last_item();
+ selected_col = 0;
+ } else {
+ prev = selected_item->get_prev_visible();
+ if (last_keypress != 0) {
+ //incr search next
+ int col;
+ prev = _search_item_text(prev, incr_search, &col, true, true);
+ if (!prev) {
+ accept_event();
+ return;
}
-
}
+ }
- if (select_mode==SELECT_MULTI) {
-
+ if (select_mode == SELECT_MULTI) {
- if (!prev)
- break;
- selected_item=prev;
- emit_signal("cell_selected");
- update();
- } else {
-
- int col=selected_col<0?0:selected_col;
- while (prev && !prev->cells[col].selectable)
- prev=prev->get_prev_visible();
- if (!prev)
- break; // do nothing..
- prev->select(col);
+ if (!prev)
+ break;
+ selected_item = prev;
+ emit_signal("cell_selected");
+ update();
+ } else {
- }
+ int col = selected_col < 0 ? 0 : selected_col;
+ while (prev && !prev->cells[col].selectable)
+ prev = prev->get_prev_visible();
+ if (!prev)
+ break; // do nothing..
+ prev->select(col);
+ }
- ensure_cursor_is_visible();
- accept_event();
+ ensure_cursor_is_visible();
+ accept_event();
} break;
case KEY_PAGEDOWN: {
@@ -2128,73 +1993,69 @@ void Tree::_gui_input(InputEvent p_event) {
TreeItem *next = NULL;
if (!selected_item)
break;
- next=selected_item;
+ next = selected_item;
- for(int i=0;i<10;i++) {
+ for (int i = 0; i < 10; i++) {
TreeItem *_n = next->get_next_visible();
if (_n) {
- next=_n;
+ next = _n;
} else {
break;
}
}
- if (next==selected_item)
+ if (next == selected_item)
break;
- if (select_mode==SELECT_MULTI) {
-
+ if (select_mode == SELECT_MULTI) {
- selected_item=next;
+ selected_item = next;
emit_signal("cell_selected");
update();
} else {
while (next && !next->cells[selected_col].selectable)
- next=next->get_next_visible();
+ next = next->get_next_visible();
if (!next)
EXIT_BREAK; // do nothing..
next->select(selected_col);
-
}
ensure_cursor_is_visible();
- } break;
+ } break;
case KEY_PAGEUP: {
TreeItem *prev = NULL;
if (!selected_item)
break;
- prev=selected_item;
+ prev = selected_item;
- for(int i=0;i<10;i++) {
+ for (int i = 0; i < 10; i++) {
TreeItem *_n = prev->get_prev_visible();
if (_n) {
- prev=_n;
+ prev = _n;
} else {
break;
}
}
- if (prev==selected_item)
+ if (prev == selected_item)
break;
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
-
- selected_item=prev;
+ selected_item = prev;
emit_signal("cell_selected");
update();
} else {
while (prev && !prev->cells[selected_col].selectable)
- prev=prev->get_prev_visible();
+ prev = prev->get_prev_visible();
if (!prev)
EXIT_BREAK; // do nothing..
prev->select(selected_col);
-
}
ensure_cursor_is_visible();
@@ -2209,21 +2070,20 @@ void Tree::_gui_input(InputEvent p_event) {
if (!edit_selected()) {
emit_signal("item_activated");
}
-
}
accept_event();
} break;
case KEY_SPACE: {
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
if (!selected_item)
break;
if (selected_item->is_selected(selected_col)) {
selected_item->deselect(selected_col);
- emit_signal("multi_selected",selected_item,selected_col,false);
+ emit_signal("multi_selected", selected_item, selected_col, false);
} else if (selected_item->is_selectable(selected_col)) {
selected_item->select(selected_col);
- emit_signal("multi_selected",selected_item,selected_col,true);
+ emit_signal("multi_selected", selected_item, selected_col, true);
}
}
accept_event();
@@ -2231,19 +2091,19 @@ void Tree::_gui_input(InputEvent p_event) {
} break;
default: {
- if (p_event.key.unicode>0) {
+ if (p_event.key.unicode > 0) {
_do_incr_search(String::chr(p_event.key.unicode));
accept_event();
return;
} else {
- if (p_event.key.scancode!=KEY_SHIFT)
- last_keypress=0;
+ if (p_event.key.scancode != KEY_SHIFT)
+ last_keypress = 0;
}
} break;
- last_keypress=0;
+ last_keypress = 0;
}
} break;
@@ -2252,119 +2112,107 @@ void Tree::_gui_input(InputEvent p_event) {
if (cache.font.is_null()) // avoid a strange case that may fuckup stuff
update_cache();
- const InputEventMouseMotion& b=p_event.mouse_motion;
+ const InputEventMouseMotion &b = p_event.mouse_motion;
Ref<StyleBox> bg = cache.bg;
- Point2 pos = Point2(b.x,b.y) - bg->get_offset();
+ Point2 pos = Point2(b.x, b.y) - bg->get_offset();
Cache::ClickType old_hover = cache.hover_type;
int old_index = cache.hover_index;
- cache.hover_type=Cache::CLICK_NONE;
- cache.hover_index=0;
+ cache.hover_type = Cache::CLICK_NONE;
+ cache.hover_index = 0;
if (show_column_titles) {
- pos.y-=_get_title_button_height();
- if (pos.y<0) {
- pos.x+=cache.offset.x;
- int len=0;
- for(int i=0;i<columns.size();i++) {
+ pos.y -= _get_title_button_height();
+ if (pos.y < 0) {
+ pos.x += cache.offset.x;
+ int len = 0;
+ for (int i = 0; i < columns.size(); i++) {
- len+=get_column_width(i);
- if (pos.x<len) {
+ len += get_column_width(i);
+ if (pos.x < len) {
- cache.hover_type=Cache::CLICK_TITLE;
- cache.hover_index=i;
+ cache.hover_type = Cache::CLICK_TITLE;
+ cache.hover_index = i;
update();
break;
}
}
-
}
-
}
if (drop_mode_flags && root) {
- Point2 mpos=Point2(b.x,b.y);
+ Point2 mpos = Point2(b.x, b.y);
mpos -= cache.bg->get_offset();
- mpos.y-=_get_title_button_height();
- if (mpos.y>=0) {
+ mpos.y -= _get_title_button_height();
+ if (mpos.y >= 0) {
if (h_scroll->is_visible_in_tree())
- mpos.x+=h_scroll->get_value();
+ mpos.x += h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- mpos.y+=v_scroll->get_value();
+ mpos.y += v_scroll->get_value();
- int col,h,section;
- TreeItem *it = _find_item_at_pos(root,mpos,col,h,section);
+ int col, h, section;
+ TreeItem *it = _find_item_at_pos(root, mpos, col, h, section);
- if (it!=drop_mode_over || section!=drop_mode_section) {
- drop_mode_over=it;
- drop_mode_section=section;
+ if (it != drop_mode_over || section != drop_mode_section) {
+ drop_mode_over = it;
+ drop_mode_section = section;
update();
}
}
}
-
-
- if (cache.hover_type!=old_hover || cache.hover_index!=old_index) {
+ if (cache.hover_type != old_hover || cache.hover_index != old_index) {
update();
}
- if (pressing_for_editor && popup_edited_item && (popup_edited_item->get_cell_mode(popup_edited_item_col)==TreeItem::CELL_MODE_RANGE || popup_edited_item->get_cell_mode(popup_edited_item_col)==TreeItem::CELL_MODE_RANGE_EXPRESSION)) {
+ if (pressing_for_editor && popup_edited_item && (popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE || popup_edited_item->get_cell_mode(popup_edited_item_col) == TreeItem::CELL_MODE_RANGE_EXPRESSION)) {
//range drag
if (!range_drag_enabled) {
- Vector2 cpos = Vector2(b.x,b.y);
- if (cpos.distance_to(pressing_pos)>2) {
- range_drag_enabled=true;
- range_drag_capture_pos=cpos;
- range_drag_base=popup_edited_item->get_range(popup_edited_item_col);
+ Vector2 cpos = Vector2(b.x, b.y);
+ if (cpos.distance_to(pressing_pos) > 2) {
+ range_drag_enabled = true;
+ range_drag_capture_pos = cpos;
+ range_drag_base = popup_edited_item->get_range(popup_edited_item_col);
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
}
} else {
- TreeItem::Cell &c=popup_edited_item->cells[popup_edited_item_col];
+ TreeItem::Cell &c = popup_edited_item->cells[popup_edited_item_col];
float diff_y = -b.relative_y;
- diff_y=Math::pow(ABS(diff_y),1.8f)*SGN(diff_y);
- diff_y*=0.1;
- range_drag_base=CLAMP(range_drag_base + c.step * diff_y, c.min, c.max);
- popup_edited_item->set_range(popup_edited_item_col,range_drag_base);
- item_edited(popup_edited_item_col,popup_edited_item);
-
+ diff_y = Math::pow(ABS(diff_y), 1.8f) * SGN(diff_y);
+ diff_y *= 0.1;
+ range_drag_base = CLAMP(range_drag_base + c.step * diff_y, c.min, c.max);
+ popup_edited_item->set_range(popup_edited_item_col, range_drag_base);
+ item_edited(popup_edited_item_col, popup_edited_item);
}
-
}
- if (drag_touching && ! drag_touching_deaccel) {
-
-
- drag_accum-=b.relative_y;
- v_scroll->set_value(drag_from+drag_accum);
- drag_speed=-b.speed_y;
+ if (drag_touching && !drag_touching_deaccel) {
+ drag_accum -= b.relative_y;
+ v_scroll->set_value(drag_from + drag_accum);
+ drag_speed = -b.speed_y;
}
} break;
case InputEvent::MOUSE_BUTTON: {
-
-
if (cache.font.is_null()) // avoid a strange case that may fuckup stuff
update_cache();
- const InputEventMouseButton& b=p_event.mouse_button;
-
+ const InputEventMouseButton &b = p_event.mouse_button;
if (!b.pressed) {
- if (b.button_index==BUTTON_LEFT) {
-
+ if (b.button_index == BUTTON_LEFT) {
if (single_select_defer) {
- select_single_item( single_select_defer, root, single_select_defer_column );
- single_select_defer=NULL;
+ select_single_item(single_select_defer, root, single_select_defer_column);
+ single_select_defer = NULL;
}
range_click_timer->stop();
@@ -2373,77 +2221,70 @@ void Tree::_gui_input(InputEvent p_event) {
if (range_drag_enabled) {
- range_drag_enabled=false;
+ range_drag_enabled = false;
Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
warp_mouse(range_drag_capture_pos);
} else {
Rect2 rect = get_selected()->get_meta("__focus_rect");
- if (rect.has_point(Point2(p_event.mouse_button.x,p_event.mouse_button.y))) {
+ if (rect.has_point(Point2(p_event.mouse_button.x, p_event.mouse_button.y))) {
edit_selected();
} else {
emit_signal("item_double_clicked");
}
}
- pressing_for_editor=false;
-
+ pressing_for_editor = false;
}
-
-
- if (cache.click_type==Cache::CLICK_BUTTON) {
+ if (cache.click_type == Cache::CLICK_BUTTON) {
// make sure in case of wrong reference after reconstructing whole TreeItems
- cache.click_item=get_item_at_pos(cache.click_pos);
- emit_signal("button_pressed",cache.click_item,cache.click_column,cache.click_id);
-
+ cache.click_item = get_item_at_pos(cache.click_pos);
+ emit_signal("button_pressed", cache.click_item, cache.click_column, cache.click_id);
}
- cache.click_type=Cache::CLICK_NONE;
- cache.click_index=-1;
- cache.click_id=-1;
- cache.click_item=NULL;
- cache.click_column=0;
+ cache.click_type = Cache::CLICK_NONE;
+ cache.click_index = -1;
+ cache.click_id = -1;
+ cache.click_item = NULL;
+ cache.click_column = 0;
if (drag_touching) {
-
- if (drag_speed==0) {
- drag_touching_deaccel=false;
- drag_touching=false;
+ if (drag_speed == 0) {
+ drag_touching_deaccel = false;
+ drag_touching = false;
set_fixed_process(false);
} else {
- drag_touching_deaccel=true;
+ drag_touching_deaccel = true;
}
-
}
update();
}
break;
-
}
if (range_drag_enabled)
break;
- switch(b.button_index) {
+ switch (b.button_index) {
case BUTTON_RIGHT:
case BUTTON_LEFT: {
Ref<StyleBox> bg = cache.bg;
- Point2 pos = Point2(b.x,b.y) - bg->get_offset();
- cache.click_type=Cache::CLICK_NONE;
- if (show_column_titles && b.button_index==BUTTON_LEFT) {
- pos.y-=_get_title_button_height();
+ Point2 pos = Point2(b.x, b.y) - bg->get_offset();
+ cache.click_type = Cache::CLICK_NONE;
+ if (show_column_titles && b.button_index == BUTTON_LEFT) {
+ pos.y -= _get_title_button_height();
- if (pos.y<0) {
- pos.x+=cache.offset.x;
- int len=0;
- for(int i=0;i<columns.size();i++) {
+ if (pos.y < 0) {
+ pos.x += cache.offset.x;
+ int len = 0;
+ for (int i = 0; i < columns.size(); i++) {
- len+=get_column_width(i);
- if (pos.x<len) {
+ len += get_column_width(i);
+ if (pos.x < len) {
- cache.click_type=Cache::CLICK_TITLE;
- cache.click_index=i;
+ cache.click_type = Cache::CLICK_TITLE;
+ cache.click_index = i;
//cache.click_id=;
update();
break;
@@ -2451,140 +2292,134 @@ void Tree::_gui_input(InputEvent p_event) {
}
break;
}
-
}
if (!root || (!root->get_children() && hide_root)) {
- if (b.button_index==BUTTON_RIGHT && allow_rmb_select) {
- emit_signal("empty_tree_rmb_selected",get_local_mouse_pos());
+ if (b.button_index == BUTTON_RIGHT && allow_rmb_select) {
+ emit_signal("empty_tree_rmb_selected", get_local_mouse_pos());
}
break;
}
- click_handled=false;
- pressing_for_editor=false;
+ click_handled = false;
+ pressing_for_editor = false;
blocked++;
- bool handled = propagate_mouse_event(pos+cache.offset,0,0,b.doubleclick,root,b.button_index,b.mod);
+ bool handled = propagate_mouse_event(pos + cache.offset, 0, 0, b.doubleclick, root, b.button_index, b.mod);
blocked--;
if (pressing_for_editor) {
- pressing_pos=Point2(b.x,b.y);
+ pressing_pos = Point2(b.x, b.y);
}
-
- if (b.button_index==BUTTON_RIGHT)
+ if (b.button_index == BUTTON_RIGHT)
break;
if (drag_touching) {
set_fixed_process(false);
- drag_touching_deaccel=false;
- drag_touching=false;
- drag_speed=0;
- drag_from=0;
+ drag_touching_deaccel = false;
+ drag_touching = false;
+ drag_speed = 0;
+ drag_from = 0;
}
if (!click_handled) {
- drag_speed=0;
- drag_accum=0;
+ drag_speed = 0;
+ drag_accum = 0;
//last_drag_accum=0;
- drag_from=v_scroll->get_value();
- drag_touching=OS::get_singleton()->has_touchscreen_ui_hint();
- drag_touching_deaccel=false;
+ drag_from = v_scroll->get_value();
+ drag_touching = OS::get_singleton()->has_touchscreen_ui_hint();
+ drag_touching_deaccel = false;
if (drag_touching) {
set_fixed_process(true);
}
}
-
} break;
case BUTTON_WHEEL_UP: {
- v_scroll->set_value( v_scroll->get_value()-v_scroll->get_page()/8 );
+ v_scroll->set_value(v_scroll->get_value() - v_scroll->get_page() / 8);
} break;
case BUTTON_WHEEL_DOWN: {
- v_scroll->set_value( v_scroll->get_value()+v_scroll->get_page()/8 );
+ v_scroll->set_value(v_scroll->get_value() + v_scroll->get_page() / 8);
} break;
}
} break;
}
-
}
-
bool Tree::edit_selected() {
TreeItem *s = get_selected();
ERR_EXPLAIN("No item selected!");
- ERR_FAIL_COND_V(!s,false);
+ ERR_FAIL_COND_V(!s, false);
ensure_cursor_is_visible();
int col = get_selected_column();
ERR_EXPLAIN("No item column selected!");
- ERR_FAIL_INDEX_V(col,columns.size(),false);
+ ERR_FAIL_INDEX_V(col, columns.size(), false);
if (!s->cells[col].editable)
return false;
Rect2 rect = s->get_meta("__focus_rect");
- popup_edited_item=s;
- popup_edited_item_col=col;
+ popup_edited_item = s;
+ popup_edited_item_col = col;
TreeItem::Cell &c = s->cells[col];
- if (c.mode==TreeItem::CELL_MODE_CHECK) {
+ if (c.mode == TreeItem::CELL_MODE_CHECK) {
s->set_checked(col, !c.checked);
- item_edited(col,s);
+ item_edited(col, s);
return true;
- } else if (c.mode==TreeItem::CELL_MODE_CUSTOM) {
+ } else if (c.mode == TreeItem::CELL_MODE_CUSTOM) {
- edited_item=s;
- edited_col=col;
- custom_popup_rect=Rect2i( get_global_pos() + rect.pos, rect.size );
- emit_signal("custom_popup_edited",false);
- item_edited(col,s);
+ edited_item = s;
+ edited_col = col;
+ custom_popup_rect = Rect2i(get_global_pos() + rect.pos, rect.size);
+ emit_signal("custom_popup_edited", false);
+ item_edited(col, s);
return true;
- } else if ((c.mode==TreeItem::CELL_MODE_RANGE||c.mode==TreeItem::CELL_MODE_RANGE_EXPRESSION) && c.text!="") {
+ } else if ((c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) && c.text != "") {
popup_menu->clear();
- for (int i=0;i<c.text.get_slice_count(",");i++) {
-
- String s = c.text.get_slicec(',',i);
- popup_menu->add_item(s,i);
+ for (int i = 0; i < c.text.get_slice_count(","); i++) {
+ String s = c.text.get_slicec(',', i);
+ popup_menu->add_item(s, i);
}
- popup_menu->set_size(Size2(rect.size.width,0));
- popup_menu->set_pos( get_global_pos() + rect.pos + Point2i(0,rect.size.height) );
+ popup_menu->set_size(Size2(rect.size.width, 0));
+ popup_menu->set_pos(get_global_pos() + rect.pos + Point2i(0, rect.size.height));
popup_menu->popup();
- popup_edited_item=s;
- popup_edited_item_col=col;
+ popup_edited_item = s;
+ popup_edited_item_col = col;
return true;
- } else if (c.mode==TreeItem::CELL_MODE_STRING || c.mode==TreeItem::CELL_MODE_RANGE || c.mode==TreeItem::CELL_MODE_RANGE_EXPRESSION ) {
+ } else if (c.mode == TreeItem::CELL_MODE_STRING || c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) {
- Point2i textedpos=get_global_pos() + rect.pos;
- text_editor->set_pos( textedpos );
- text_editor->set_size( rect.size);
+ Point2i textedpos = get_global_pos() + rect.pos;
+ text_editor->set_pos(textedpos);
+ text_editor->set_size(rect.size);
text_editor->clear();
- text_editor->set_text( c.mode==TreeItem::CELL_MODE_STRING?c.text:String::num( c.val, Math::step_decimals( c.step ) ) );
+ text_editor->set_text(c.mode == TreeItem::CELL_MODE_STRING ? c.text : String::num(c.val, Math::step_decimals(c.step)));
text_editor->select_all();
- if (c.mode==TreeItem::CELL_MODE_RANGE || c.mode==TreeItem::CELL_MODE_RANGE_EXPRESSION ) {
+ if (c.mode == TreeItem::CELL_MODE_RANGE || c.mode == TreeItem::CELL_MODE_RANGE_EXPRESSION) {
- value_editor->set_pos(textedpos + Point2i(0,text_editor->get_size().height) );
- value_editor->set_size( Size2(rect.size.width,1));
+ value_editor->set_pos(textedpos + Point2i(0, text_editor->get_size().height));
+ value_editor->set_size(Size2(rect.size.width, 1));
value_editor->show_modal();
- updating_value_editor=true;
- value_editor->set_min( c.min );
- value_editor->set_max( c.max );
- value_editor->set_step( c.step );
- value_editor->set_value( c.val );
- value_editor->set_exp_ratio( c.expr );
- updating_value_editor=false;
+ updating_value_editor = true;
+ value_editor->set_min(c.min);
+ value_editor->set_max(c.max);
+ value_editor->set_step(c.step);
+ value_editor->set_value(c.val);
+ value_editor->set_exp_ratio(c.expr);
+ updating_value_editor = false;
}
text_editor->show_modal();
@@ -2597,12 +2432,12 @@ bool Tree::edit_selected() {
Size2 Tree::get_internal_min_size() const {
- Size2i size=cache.bg->get_offset();
+ Size2i size = cache.bg->get_offset();
if (root)
- size.height+=get_item_height(root);
- for (int i=0;i<columns.size();i++) {
+ size.height += get_item_height(root);
+ for (int i = 0; i < columns.size(); i++) {
- size.width+=columns[i].min_width;
+ size.width += columns[i].min_width;
}
return size;
@@ -2613,140 +2448,133 @@ void Tree::update_scrollbars() {
Size2 size = get_size();
int tbh;
if (show_column_titles) {
- tbh=_get_title_button_height();
+ tbh = _get_title_button_height();
} else {
- tbh=0;
+ tbh = 0;
}
Size2 hmin = h_scroll->get_combined_minimum_size();
Size2 vmin = v_scroll->get_combined_minimum_size();
+ v_scroll->set_begin(Point2(size.width - vmin.width, cache.bg->get_margin(MARGIN_TOP)));
+ v_scroll->set_end(Point2(size.width, size.height - cache.bg->get_margin(MARGIN_TOP) - cache.bg->get_margin(MARGIN_BOTTOM)));
-
- v_scroll->set_begin( Point2(size.width - vmin.width , cache.bg->get_margin(MARGIN_TOP)) );
- v_scroll->set_end( Point2(size.width, size.height-cache.bg->get_margin(MARGIN_TOP)-cache.bg->get_margin(MARGIN_BOTTOM)) );
-
- h_scroll->set_begin( Point2( 0, size.height - hmin.height) );
- h_scroll->set_end( Point2(size.width-vmin.width, size.height) );
-
+ h_scroll->set_begin(Point2(0, size.height - hmin.height));
+ h_scroll->set_end(Point2(size.width - vmin.width, size.height));
Size2 min = get_internal_min_size();
if (min.height < size.height - hmin.height) {
v_scroll->hide();
- cache.offset.y=0;
+ cache.offset.y = 0;
} else {
v_scroll->show();
v_scroll->set_max(min.height);
v_scroll->set_page(size.height - hmin.height - tbh);
- cache.offset.y=v_scroll->get_value();
+ cache.offset.y = v_scroll->get_value();
}
if (min.width < size.width - vmin.width) {
h_scroll->hide();
- cache.offset.x=0;
+ cache.offset.x = 0;
} else {
h_scroll->show();
h_scroll->set_max(min.width);
h_scroll->set_page(size.width - vmin.width);
- cache.offset.x=h_scroll->get_value();
+ cache.offset.x = h_scroll->get_value();
}
}
-
int Tree::_get_title_button_height() const {
- return show_column_titles?cache.font->get_height() + cache.title_button->get_minimum_size().height:0;
+ return show_column_titles ? cache.font->get_height() + cache.title_button->get_minimum_size().height : 0;
}
void Tree::_notification(int p_what) {
- if (p_what==NOTIFICATION_FOCUS_ENTER) {
+ if (p_what == NOTIFICATION_FOCUS_ENTER) {
- focus_in_id=get_tree()->get_last_event_id();
+ focus_in_id = get_tree()->get_last_event_id();
}
- if (p_what==NOTIFICATION_MOUSE_EXIT) {
+ if (p_what == NOTIFICATION_MOUSE_EXIT) {
- if (cache.hover_type!=Cache::CLICK_NONE) {
- cache.hover_type=Cache::CLICK_NONE;
+ if (cache.hover_type != Cache::CLICK_NONE) {
+ cache.hover_type = Cache::CLICK_NONE;
update();
}
}
- if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- drag_touching=false;
+ drag_touching = false;
}
- if (p_what==NOTIFICATION_ENTER_TREE) {
+ if (p_what == NOTIFICATION_ENTER_TREE) {
update_cache();
}
- if (p_what==NOTIFICATION_DRAG_END) {
+ if (p_what == NOTIFICATION_DRAG_END) {
- drop_mode_flags=0;
+ drop_mode_flags = 0;
scrolling = false;
set_fixed_process(false);
update();
}
- if (p_what==NOTIFICATION_DRAG_BEGIN) {
+ if (p_what == NOTIFICATION_DRAG_BEGIN) {
- single_select_defer=NULL;
+ single_select_defer = NULL;
if (cache.scroll_speed > 0 && get_rect().has_point(get_viewport()->get_mouse_pos() - get_global_pos())) {
scrolling = true;
set_fixed_process(true);
}
}
- if (p_what==NOTIFICATION_FIXED_PROCESS) {
+ if (p_what == NOTIFICATION_FIXED_PROCESS) {
- if (drag_touching) {
+ if (drag_touching) {
if (drag_touching_deaccel) {
float pos = v_scroll->get_value();
- pos+=drag_speed*get_fixed_process_delta_time();
+ pos += drag_speed * get_fixed_process_delta_time();
- bool turnoff=false;
- if (pos<0) {
- pos=0;
- turnoff=true;
+ bool turnoff = false;
+ if (pos < 0) {
+ pos = 0;
+ turnoff = true;
set_fixed_process(false);
- drag_touching=false;
- drag_touching_deaccel=false;
+ drag_touching = false;
+ drag_touching_deaccel = false;
}
- if (pos > (v_scroll->get_max()-v_scroll->get_page())) {
- pos=v_scroll->get_max()-v_scroll->get_page();
- turnoff=true;
-
+ if (pos > (v_scroll->get_max() - v_scroll->get_page())) {
+ pos = v_scroll->get_max() - v_scroll->get_page();
+ turnoff = true;
}
v_scroll->set_value(pos);
- float sgn = drag_speed<0? -1 : 1;
+ float sgn = drag_speed < 0 ? -1 : 1;
float val = Math::abs(drag_speed);
- val-=1000*get_fixed_process_delta_time();
+ val -= 1000 * get_fixed_process_delta_time();
- if (val<0) {
- turnoff=true;
+ if (val < 0) {
+ turnoff = true;
}
- drag_speed=sgn*val;
+ drag_speed = sgn * val;
if (turnoff) {
set_fixed_process(false);
- drag_touching=false;
- drag_touching_deaccel=false;
+ drag_touching = false;
+ drag_touching_deaccel = false;
}
-
} else {
-
}
}
-
+
if (scrolling) {
Point2 point = get_viewport()->get_mouse_pos() - get_global_pos();
if (point.x < cache.scroll_border) {
@@ -2770,7 +2598,7 @@ void Tree::_notification(int p_what) {
}
}
- if (p_what==NOTIFICATION_DRAW) {
+ if (p_what == NOTIFICATION_DRAW) {
update_cache();
update_scrollbars();
@@ -2780,125 +2608,117 @@ void Tree::_notification(int p_what) {
Ref<StyleBox> bg_focus = get_stylebox("bg_focus");
Point2 draw_ofs;
- draw_ofs+=bg->get_offset();
- Size2 draw_size=get_size()-bg->get_minimum_size();
+ draw_ofs += bg->get_offset();
+ Size2 draw_size = get_size() - bg->get_minimum_size();
- bg->draw( ci, Rect2( Point2(), get_size()) );
+ bg->draw(ci, Rect2(Point2(), get_size()));
if (has_focus()) {
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci,true);
- bg_focus->draw( ci, Rect2( Point2(), get_size()) );
- VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci,false);
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, true);
+ bg_focus->draw(ci, Rect2(Point2(), get_size()));
+ VisualServer::get_singleton()->canvas_item_add_clip_ignore(ci, false);
}
int tbh = _get_title_button_height();
- draw_ofs.y+=tbh;
- draw_size.y-=tbh;
+ draw_ofs.y += tbh;
+ draw_size.y -= tbh;
if (root) {
-
- draw_item( Point2(),draw_ofs,draw_size,root);
-
+ draw_item(Point2(), draw_ofs, draw_size, root);
}
- int ofs=0;
+ int ofs = 0;
- for (int i=0;i<(columns.size()-1-1);i++) {
+ for (int i = 0; i < (columns.size() - 1 - 1); i++) {
- ofs+=get_column_width(i);
+ ofs += get_column_width(i);
}
if (show_column_titles) {
//title butons
- int ofs=cache.bg->get_margin(MARGIN_LEFT);
- for(int i=0;i<columns.size();i++) {
+ int ofs = cache.bg->get_margin(MARGIN_LEFT);
+ for (int i = 0; i < columns.size(); i++) {
- Ref<StyleBox> sb = (cache.click_type==Cache::CLICK_TITLE && cache.click_index==i)?cache.title_button_pressed:((cache.hover_type==Cache::CLICK_TITLE && cache.hover_index==i)?cache.title_button_hover:cache.title_button);
+ Ref<StyleBox> sb = (cache.click_type == Cache::CLICK_TITLE && cache.click_index == i) ? cache.title_button_pressed : ((cache.hover_type == Cache::CLICK_TITLE && cache.hover_index == i) ? cache.title_button_hover : cache.title_button);
Ref<Font> f = cache.tb_font;
- Rect2 tbrect = Rect2(ofs - cache.offset.x,bg->get_margin(MARGIN_TOP),get_column_width(i),tbh);
- sb->draw(ci,tbrect);
- ofs+=tbrect.size.width;
+ Rect2 tbrect = Rect2(ofs - cache.offset.x, bg->get_margin(MARGIN_TOP), get_column_width(i), tbh);
+ sb->draw(ci, tbrect);
+ ofs += tbrect.size.width;
//text
int clip_w = tbrect.size.width - sb->get_minimum_size().width;
- f->draw_halign(ci,tbrect.pos+Point2i(sb->get_offset().x,(tbrect.size.height-f->get_height())/2+f->get_ascent()),HALIGN_CENTER,clip_w,columns[i].title,cache.title_button_color);
+ f->draw_halign(ci, tbrect.pos + Point2i(sb->get_offset().x, (tbrect.size.height - f->get_height()) / 2 + f->get_ascent()), HALIGN_CENTER, clip_w, columns[i].title, cache.title_button_color);
}
}
}
- if (p_what==NOTIFICATION_THEME_CHANGED) {
+ if (p_what == NOTIFICATION_THEME_CHANGED) {
update_cache();
}
-
}
-
-
-
Size2 Tree::get_minimum_size() const {
- return Size2(1,1);
+ return Size2(1, 1);
}
TreeItem *Tree::create_item(TreeItem *p_parent) {
- ERR_FAIL_COND_V(blocked>0,NULL);
+ ERR_FAIL_COND_V(blocked > 0, NULL);
- TreeItem *ti = memnew( TreeItem(this) );
+ TreeItem *ti = memnew(TreeItem(this));
- ti->cells.resize( columns.size() );
- ERR_FAIL_COND_V(!ti,NULL);
+ ti->cells.resize(columns.size());
+ ERR_FAIL_COND_V(!ti, NULL);
if (p_parent) {
/* Always append at the end */
- TreeItem *last=0;
- TreeItem *c=p_parent->childs;
+ TreeItem *last = 0;
+ TreeItem *c = p_parent->childs;
- while(c) {
+ while (c) {
- last=c;
- c=c->next;
+ last = c;
+ c = c->next;
}
if (last) {
- last->next=ti;
+ last->next = ti;
} else {
- p_parent->childs=ti;
+ p_parent->childs = ti;
}
- ti->parent=p_parent;
+ ti->parent = p_parent;
} else {
if (root)
- ti->childs=root;
-
- root=ti;
+ ti->childs = root;
+ root = ti;
}
-
return ti;
}
-TreeItem* Tree::get_root() {
+TreeItem *Tree::get_root() {
return root;
}
-TreeItem* Tree::get_last_item() {
+TreeItem *Tree::get_last_item() {
- TreeItem *last=root;
+ TreeItem *last = root;
- while(last) {
+ while (last) {
if (last->next)
- last=last->next;
+ last = last->next;
else if (last->childs)
- last=last->childs;
+ last = last->childs;
else
break;
}
@@ -2906,54 +2726,53 @@ TreeItem* Tree::get_last_item() {
return last;
}
-void Tree::item_edited(int p_column,TreeItem *p_item) {
+void Tree::item_edited(int p_column, TreeItem *p_item) {
- edited_item=p_item;
- edited_col=p_column;
+ edited_item = p_item;
+ edited_col = p_column;
emit_signal("item_edited");
}
-void Tree::item_changed(int p_column,TreeItem *p_item) {
+void Tree::item_changed(int p_column, TreeItem *p_item) {
update();
}
-void Tree::item_selected(int p_column,TreeItem *p_item) {
+void Tree::item_selected(int p_column, TreeItem *p_item) {
- if (select_mode==SELECT_MULTI) {
+ if (select_mode == SELECT_MULTI) {
if (!p_item->cells[p_column].selectable)
return;
- p_item->cells[p_column].selected=true;
+ p_item->cells[p_column].selected = true;
//emit_signal("multi_selected",p_item,p_column,true); - NO this is for TreeItem::select
} else {
- select_single_item(p_item,root,p_column);
+ select_single_item(p_item, root, p_column);
}
update();
}
-void Tree::item_deselected(int p_column,TreeItem *p_item) {
+void Tree::item_deselected(int p_column, TreeItem *p_item) {
- if (select_mode==SELECT_MULTI || select_mode == SELECT_SINGLE) {
- p_item->cells[p_column].selected=false;
+ if (select_mode == SELECT_MULTI || select_mode == SELECT_SINGLE) {
+ p_item->cells[p_column].selected = false;
}
update();
}
-
void Tree::set_select_mode(SelectMode p_mode) {
- select_mode=p_mode;
+ select_mode = p_mode;
}
void Tree::clear() {
- if (blocked>0) {
+ if (blocked > 0) {
- ERR_FAIL_COND(blocked>0);
+ ERR_FAIL_COND(blocked > 0);
}
if (pressing_for_editor) {
@@ -2966,43 +2785,37 @@ void Tree::clear() {
}
if (root) {
- memdelete( root );
+ memdelete(root);
root = NULL;
};
- selected_item=NULL;
- edited_item=NULL;
- popup_edited_item=NULL;
+ selected_item = NULL;
+ edited_item = NULL;
+ popup_edited_item = NULL;
update();
};
-
-
void Tree::set_hide_root(bool p_enabled) {
-
-
- hide_root=p_enabled;
+ hide_root = p_enabled;
update();
}
-void Tree::set_column_min_width(int p_column,int p_min_width) {
+void Tree::set_column_min_width(int p_column, int p_min_width) {
+ ERR_FAIL_INDEX(p_column, columns.size());
- ERR_FAIL_INDEX(p_column,columns.size());
-
- if (p_min_width<1)
+ if (p_min_width < 1)
return;
- columns[p_column].min_width=p_min_width;
+ columns[p_column].min_width = p_min_width;
update();
-
}
-void Tree::set_column_expand(int p_column,bool p_expand) {
+void Tree::set_column_expand(int p_column, bool p_expand) {
- ERR_FAIL_INDEX(p_column,columns.size());
+ ERR_FAIL_INDEX(p_column, columns.size());
- columns[p_column].expand=p_expand;
+ columns[p_column].expand = p_expand;
update();
}
@@ -3026,7 +2839,7 @@ int Tree::get_edited_column() const {
return edited_col;
}
-TreeItem* Tree::get_next_selected( TreeItem* p_item) {
+TreeItem *Tree::get_next_selected(TreeItem *p_item) {
/*
if (!p_item)
@@ -3035,35 +2848,33 @@ TreeItem* Tree::get_next_selected( TreeItem* p_item) {
if (!root)
return NULL;
- while(true) {
-
+ while (true) {
if (!p_item) {
- p_item=root;
+ p_item = root;
} else {
if (p_item->childs) {
- p_item=p_item->childs;
+ p_item = p_item->childs;
} else if (p_item->next) {
- p_item=p_item->next;
+ p_item = p_item->next;
} else {
- while(!p_item->next) {
+ while (!p_item->next) {
- p_item=p_item->parent;
- if (p_item==NULL)
+ p_item = p_item->parent;
+ if (p_item == NULL)
return NULL;
}
- p_item=p_item->next;
+ p_item = p_item->next;
}
-
}
- for (int i=0;i<columns.size();i++)
+ for (int i = 0; i < columns.size(); i++)
if (p_item->cells[i].selected)
return p_item;
}
@@ -3073,64 +2884,62 @@ TreeItem* Tree::get_next_selected( TreeItem* p_item) {
int Tree::get_column_width(int p_column) const {
- ERR_FAIL_INDEX_V(p_column,columns.size(),-1);
-
+ ERR_FAIL_INDEX_V(p_column, columns.size(), -1);
if (!columns[p_column].expand)
return columns[p_column].min_width;
Ref<StyleBox> bg = cache.bg;
- int expand_area=get_size().width-(bg->get_margin(MARGIN_LEFT)+bg->get_margin(MARGIN_RIGHT));
+ int expand_area = get_size().width - (bg->get_margin(MARGIN_LEFT) + bg->get_margin(MARGIN_RIGHT));
if (v_scroll->is_visible_in_tree())
- expand_area-=v_scroll->get_combined_minimum_size().width;
+ expand_area -= v_scroll->get_combined_minimum_size().width;
- int expanding_columns=0;
- int expanding_total=0;
+ int expanding_columns = 0;
+ int expanding_total = 0;
- for (int i=0;i<columns.size();i++) {
+ for (int i = 0; i < columns.size(); i++) {
if (!columns[i].expand) {
- expand_area-=columns[i].min_width;
+ expand_area -= columns[i].min_width;
} else {
- expanding_total+=columns[i].min_width;
+ expanding_total += columns[i].min_width;
expanding_columns++;
}
}
- if (expand_area<expanding_total)
+ if (expand_area < expanding_total)
return columns[p_column].min_width;
- ERR_FAIL_COND_V(expanding_columns==0,-1); // shouldnt happen
+ ERR_FAIL_COND_V(expanding_columns == 0, -1); // shouldnt happen
return expand_area * columns[p_column].min_width / expanding_total;
}
void Tree::propagate_set_columns(TreeItem *p_item) {
- p_item->cells.resize( columns.size() );
+ p_item->cells.resize(columns.size());
TreeItem *c = p_item->get_children();
- while(c) {
+ while (c) {
propagate_set_columns(c);
- c=c->get_next();
+ c = c->get_next();
}
}
void Tree::set_columns(int p_columns) {
- ERR_FAIL_COND(p_columns<1);
- ERR_FAIL_COND(blocked>0);
+ ERR_FAIL_COND(p_columns < 1);
+ ERR_FAIL_COND(blocked > 0);
columns.resize(p_columns);
if (root)
propagate_set_columns(root);
- if (selected_col>=p_columns)
- selected_col=p_columns-1;
+ if (selected_col >= p_columns)
+ selected_col = p_columns - 1;
update();
-
}
int Tree::get_columns() const {
@@ -3150,35 +2959,35 @@ Rect2 Tree::get_custom_popup_rect() const {
int Tree::get_item_offset(TreeItem *p_item) const {
- TreeItem *it=root;
- int ofs=_get_title_button_height();
+ TreeItem *it = root;
+ int ofs = _get_title_button_height();
if (!it)
return 0;
- while(true) {
+ while (true) {
- if (it==p_item)
+ if (it == p_item)
return ofs;
- ofs+=compute_item_height(it)+cache.vseparation;
+ ofs += compute_item_height(it) + cache.vseparation;
if (it->childs && !it->collapsed) {
- it=it->childs;
+ it = it->childs;
} else if (it->next) {
- it=it->next;
+ it = it->next;
} else {
- while(!it->next) {
+ while (!it->next) {
- it=it->parent;
- if (it==NULL)
+ it = it->parent;
+ if (it == NULL)
return 0;
}
- it=it->next;
+ it = it->next;
}
}
@@ -3194,13 +3003,13 @@ void Tree::ensure_cursor_is_visible() {
if (!selected)
return;
int ofs = get_item_offset(selected);
- if (ofs==-1)
+ if (ofs == -1)
return;
- int h = compute_item_height(selected)+cache.vseparation;
- int screenh=get_size().height-h_scroll->get_combined_minimum_size().height;
+ int h = compute_item_height(selected) + cache.vseparation;
+ int screenh = get_size().height - h_scroll->get_combined_minimum_size().height;
- if (ofs+h>v_scroll->get_value()+screenh)
- v_scroll->call_deferred("set_val", ofs-screenh+h);
+ if (ofs + h > v_scroll->get_value() + screenh)
+ v_scroll->call_deferred("set_val", ofs - screenh + h);
else if (ofs < v_scroll->get_value())
v_scroll->set_value(ofs);
}
@@ -3210,32 +3019,31 @@ int Tree::get_pressed_button() const {
return pressed_button;
}
+Rect2 Tree::get_item_rect(TreeItem *p_item, int p_column) const {
-Rect2 Tree::get_item_rect(TreeItem *p_item,int p_column) const {
-
- ERR_FAIL_NULL_V(p_item,Rect2());
- ERR_FAIL_COND_V(p_item->tree!=this,Rect2());
- if (p_column!=-1) {
- ERR_FAIL_INDEX_V(p_column,columns.size(),Rect2());
+ ERR_FAIL_NULL_V(p_item, Rect2());
+ ERR_FAIL_COND_V(p_item->tree != this, Rect2());
+ if (p_column != -1) {
+ ERR_FAIL_INDEX_V(p_column, columns.size(), Rect2());
}
int ofs = get_item_offset(p_item);
int height = compute_item_height(p_item);
Rect2 r;
- r.pos.y=ofs;
- r.size.height=height;
+ r.pos.y = ofs;
+ r.size.height = height;
- if (p_column==-1) {
- r.pos.x=0;
- r.size.x=get_size().width;
+ if (p_column == -1) {
+ r.pos.x = 0;
+ r.size.x = get_size().width;
} else {
- int accum=0;
- for(int i=0;i<p_column;i++) {
- accum+=get_column_width(i);
+ int accum = 0;
+ for (int i = 0; i < p_column; i++) {
+ accum += get_column_width(i);
}
- r.pos.x=accum;
- r.size.x=get_column_width(p_column);
+ r.pos.x = accum;
+ r.size.x = get_column_width(p_column);
}
return r;
@@ -3243,7 +3051,7 @@ Rect2 Tree::get_item_rect(TreeItem *p_item,int p_column) const {
void Tree::set_column_titles_visible(bool p_show) {
- show_column_titles=p_show;
+ show_column_titles = p_show;
update();
}
@@ -3252,16 +3060,16 @@ bool Tree::are_column_titles_visible() const {
return show_column_titles;
}
-void Tree::set_column_title(int p_column,const String& p_title) {
+void Tree::set_column_title(int p_column, const String &p_title) {
- ERR_FAIL_INDEX(p_column,columns.size());
- columns[p_column].title=p_title;
+ ERR_FAIL_INDEX(p_column, columns.size());
+ columns[p_column].title = p_title;
update();
}
String Tree::get_column_title(int p_column) const {
- ERR_FAIL_INDEX_V(p_column,columns.size(),"");
+ ERR_FAIL_INDEX_V(p_column, columns.size(), "");
return columns[p_column].title;
}
@@ -3269,153 +3077,137 @@ Point2 Tree::get_scroll() const {
Point2 ofs;
if (h_scroll->is_visible_in_tree())
- ofs.x=h_scroll->get_value();
+ ofs.x = h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- ofs.y=v_scroll->get_value();
+ ofs.y = v_scroll->get_value();
return ofs;
-
}
-TreeItem* Tree::_search_item_text(TreeItem *p_at, const String& p_find,int *r_col,bool p_selectable,bool p_backwards) {
-
-
+TreeItem *Tree::_search_item_text(TreeItem *p_at, const String &p_find, int *r_col, bool p_selectable, bool p_backwards) {
- while(p_at) {
+ while (p_at) {
- for(int i=0;i<columns.size();i++) {
- if (p_at->get_text(i).findn(p_find)==0 && (!p_selectable || p_at->is_selectable(i))) {
+ for (int i = 0; i < columns.size(); i++) {
+ if (p_at->get_text(i).findn(p_find) == 0 && (!p_selectable || p_at->is_selectable(i))) {
if (r_col)
- *r_col=i;
+ *r_col = i;
return p_at;
}
}
if (p_backwards)
- p_at=p_at->get_prev_visible();
+ p_at = p_at->get_prev_visible();
else
- p_at=p_at->get_next_visible();
+ p_at = p_at->get_next_visible();
}
return NULL;
-
}
-
-TreeItem* Tree::search_item_text(const String& p_find,int *r_col,bool p_selectable) {
+TreeItem *Tree::search_item_text(const String &p_find, int *r_col, bool p_selectable) {
if (!root)
return NULL;
- return _search_item_text(root,p_find,r_col,p_selectable);
-
+ return _search_item_text(root, p_find, r_col, p_selectable);
}
-void Tree::_do_incr_search(const String& p_add) {
+void Tree::_do_incr_search(const String &p_add) {
uint64_t time = OS::get_singleton()->get_ticks_usec() / 1000; // convert to msec
uint64_t diff = time - last_keypress;
- if (diff > uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec",2000)))
- incr_search=p_add;
+ if (diff > uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000)))
+ incr_search = p_add;
else
- incr_search+=p_add;
-
+ incr_search += p_add;
- last_keypress=time;
+ last_keypress = time;
int col;
- TreeItem *item = search_item_text(incr_search,&col,true);
+ TreeItem *item = search_item_text(incr_search, &col, true);
if (!item)
return;
item->select(col);
ensure_cursor_is_visible();
-
-
}
-TreeItem* Tree::_find_item_at_pos(TreeItem*p_item, const Point2& p_pos,int& r_column,int &h,int &section) const {
+TreeItem *Tree::_find_item_at_pos(TreeItem *p_item, const Point2 &p_pos, int &r_column, int &h, int &section) const {
Point2 pos = p_pos;
+ if (root != p_item || !hide_root) {
- if (root!=p_item || ! hide_root) {
+ h = compute_item_height(p_item) + cache.vseparation;
+ if (pos.y < h) {
- h = compute_item_height(p_item)+cache.vseparation;
- if (pos.y<h) {
-
- if (drop_mode_flags==DROP_MODE_ON_ITEM) {
- section=0;
- } else if (drop_mode_flags==DROP_MODE_INBETWEEN) {
- section=pos.y<h/2?-1:1;
- } else if (pos.y<h/4) {
- section=-1;
- } else if (pos.y>=(h*3/4)) {
- section=1;
+ if (drop_mode_flags == DROP_MODE_ON_ITEM) {
+ section = 0;
+ } else if (drop_mode_flags == DROP_MODE_INBETWEEN) {
+ section = pos.y < h / 2 ? -1 : 1;
+ } else if (pos.y < h / 4) {
+ section = -1;
+ } else if (pos.y >= (h * 3 / 4)) {
+ section = 1;
} else {
- section=0;
+ section = 0;
}
- for(int i=0;i<columns.size();i++) {
+ for (int i = 0; i < columns.size(); i++) {
int w = get_column_width(i);
if (pos.x < w) {
- r_column=i;
-
+ r_column = i;
return p_item;
}
- pos.x-=w;
+ pos.x -= w;
}
-
-
-
return NULL;
} else {
- pos.y-=h;
+ pos.y -= h;
}
} else {
- h=0;
+ h = 0;
}
if (p_item->is_collapsed())
return NULL; // do not try childs, it's collapsed
TreeItem *n = p_item->get_children();
- while(n) {
-
+ while (n) {
int ch;
- TreeItem *r = _find_item_at_pos(n,pos,r_column,ch,section);
- pos.y-=ch;
- h+=ch;
+ TreeItem *r = _find_item_at_pos(n, pos, r_column, ch, section);
+ pos.y -= ch;
+ h += ch;
if (r)
return r;
- n=n->get_next();
+ n = n->get_next();
}
return NULL;
-
}
-int Tree::get_column_at_pos(const Point2& p_pos) const {
+int Tree::get_column_at_pos(const Point2 &p_pos) const {
if (root) {
- Point2 pos=p_pos;
+ Point2 pos = p_pos;
pos -= cache.bg->get_offset();
- pos.y-=_get_title_button_height();
- if (pos.y<0)
+ pos.y -= _get_title_button_height();
+ if (pos.y < 0)
return -1;
if (h_scroll->is_visible_in_tree())
- pos.x+=h_scroll->get_value();
+ pos.x += h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- pos.y+=v_scroll->get_value();
+ pos.y += v_scroll->get_value();
- int col,h,section;
- TreeItem *it = _find_item_at_pos(root,pos,col,h,section);
+ int col, h, section;
+ TreeItem *it = _find_item_at_pos(root, pos, col, h, section);
if (it) {
return col;
@@ -3423,26 +3215,25 @@ int Tree::get_column_at_pos(const Point2& p_pos) const {
}
return -1;
-
}
-int Tree::get_drop_section_at_pos(const Point2& p_pos) const {
+int Tree::get_drop_section_at_pos(const Point2 &p_pos) const {
if (root) {
- Point2 pos=p_pos;
+ Point2 pos = p_pos;
pos -= cache.bg->get_offset();
- pos.y-=_get_title_button_height();
- if (pos.y<0)
+ pos.y -= _get_title_button_height();
+ if (pos.y < 0)
return -100;
if (h_scroll->is_visible_in_tree())
- pos.x+=h_scroll->get_value();
+ pos.x += h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- pos.y+=v_scroll->get_value();
+ pos.y += v_scroll->get_value();
- int col,h,section;
- TreeItem *it = _find_item_at_pos(root,pos,col,h,section);
+ int col, h, section;
+ TreeItem *it = _find_item_at_pos(root, pos, col, h, section);
if (it) {
return section;
@@ -3450,26 +3241,24 @@ int Tree::get_drop_section_at_pos(const Point2& p_pos) const {
}
return -100;
-
}
-TreeItem* Tree::get_item_at_pos(const Point2& p_pos) const {
-
+TreeItem *Tree::get_item_at_pos(const Point2 &p_pos) const {
if (root) {
- Point2 pos=p_pos;
+ Point2 pos = p_pos;
pos -= cache.bg->get_offset();
- pos.y-=_get_title_button_height();
- if (pos.y<0)
+ pos.y -= _get_title_button_height();
+ if (pos.y < 0)
return NULL;
if (h_scroll->is_visible_in_tree())
- pos.x+=h_scroll->get_value();
+ pos.x += h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- pos.y+=v_scroll->get_value();
+ pos.y += v_scroll->get_value();
- int col,h,section;
- TreeItem *it = _find_item_at_pos(root,pos,col,h,section);
+ int col, h, section;
+ TreeItem *it = _find_item_at_pos(root, pos, col, h, section);
if (it) {
@@ -3478,35 +3267,33 @@ TreeItem* Tree::get_item_at_pos(const Point2& p_pos) const {
}
return NULL;
-
}
-String Tree::get_tooltip(const Point2& p_pos) const {
+String Tree::get_tooltip(const Point2 &p_pos) const {
if (root) {
- Point2 pos=p_pos;
+ Point2 pos = p_pos;
pos -= cache.bg->get_offset();
- pos.y-=_get_title_button_height();
- if (pos.y<0)
+ pos.y -= _get_title_button_height();
+ if (pos.y < 0)
return Control::get_tooltip(p_pos);
if (h_scroll->is_visible_in_tree())
- pos.x+=h_scroll->get_value();
+ pos.x += h_scroll->get_value();
if (v_scroll->is_visible_in_tree())
- pos.y+=v_scroll->get_value();
-
- int col,h,section;
- TreeItem *it = _find_item_at_pos(root,pos,col,h,section);
+ pos.y += v_scroll->get_value();
+ int col, h, section;
+ TreeItem *it = _find_item_at_pos(root, pos, col, h, section);
if (it) {
String ret;
- if (it->get_tooltip(col)=="")
- ret=it->get_text(col);
+ if (it->get_tooltip(col) == "")
+ ret = it->get_text(col);
else
- ret=it->get_tooltip(col);
+ ret = it->get_tooltip(col);
return ret;
}
}
@@ -3516,7 +3303,7 @@ String Tree::get_tooltip(const Point2& p_pos) const {
void Tree::set_cursor_can_exit_tree(bool p_enable) {
- cursor_can_exit_tree=p_enable;
+ cursor_can_exit_tree = p_enable;
}
bool Tree::can_cursor_exit_tree() const {
@@ -3525,7 +3312,7 @@ bool Tree::can_cursor_exit_tree() const {
}
void Tree::set_hide_folding(bool p_hide) {
- hide_folding=p_hide;
+ hide_folding = p_hide;
update();
}
@@ -3539,11 +3326,11 @@ void Tree::set_value_evaluator(ValueEvaluator *p_evaluator) {
}
void Tree::set_drop_mode_flags(int p_flags) {
- if (drop_mode_flags==p_flags)
+ if (drop_mode_flags == p_flags)
return;
- drop_mode_flags=p_flags;
- if (drop_mode_flags==0) {
- drop_mode_over=NULL;
+ drop_mode_flags = p_flags;
+ if (drop_mode_flags == 0) {
+ drop_mode_over = NULL;
}
update();
@@ -3556,7 +3343,7 @@ int Tree::get_drop_mode_flags() const {
void Tree::set_single_select_cell_editing_only_when_already_selected(bool p_enable) {
- force_select_on_already_selected=p_enable;
+ force_select_on_already_selected = p_enable;
}
bool Tree::get_single_select_cell_editing_only_when_already_selected() const {
@@ -3566,7 +3353,7 @@ bool Tree::get_single_select_cell_editing_only_when_already_selected() const {
void Tree::set_edit_checkbox_cell_only_when_checkbox_is_pressed(bool p_enable) {
- force_edit_checkbox_only_on_checkbox=p_enable;
+ force_edit_checkbox_only_on_checkbox = p_enable;
}
bool Tree::get_edit_checkbox_cell_only_when_checkbox_is_pressed() const {
@@ -3574,194 +3361,188 @@ bool Tree::get_edit_checkbox_cell_only_when_checkbox_is_pressed() const {
return force_edit_checkbox_only_on_checkbox;
}
-
void Tree::set_allow_rmb_select(bool p_allow) {
- allow_rmb_select=p_allow;
+ allow_rmb_select = p_allow;
}
-bool Tree::get_allow_rmb_select() const{
+bool Tree::get_allow_rmb_select() const {
return allow_rmb_select;
}
-
void Tree::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_range_click_timeout"),&Tree::_range_click_timeout);
- ClassDB::bind_method(D_METHOD("_gui_input"),&Tree::_gui_input);
- ClassDB::bind_method(D_METHOD("_popup_select"),&Tree::popup_select);
- ClassDB::bind_method(D_METHOD("_text_editor_enter"),&Tree::text_editor_enter);
- ClassDB::bind_method(D_METHOD("_text_editor_modal_close"),&Tree::_text_editor_modal_close);
- ClassDB::bind_method(D_METHOD("_value_editor_changed"),&Tree::value_editor_changed);
- ClassDB::bind_method(D_METHOD("_scroll_moved"),&Tree::_scroll_moved);
-
- ClassDB::bind_method(D_METHOD("clear"),&Tree::clear);
- ClassDB::bind_method(D_METHOD("create_item:TreeItem","parent:TreeItem"),&Tree::_create_item,DEFVAL(Variant()));
-
- ClassDB::bind_method(D_METHOD("get_root:TreeItem"),&Tree::get_root);
- ClassDB::bind_method(D_METHOD("set_column_min_width","column","min_width"),&Tree::set_column_min_width);
- ClassDB::bind_method(D_METHOD("set_column_expand","column","expand"),&Tree::set_column_expand);
- ClassDB::bind_method(D_METHOD("get_column_width","column"),&Tree::get_column_width);
-
- ClassDB::bind_method(D_METHOD("set_hide_root","enable"),&Tree::set_hide_root);
- ClassDB::bind_method(D_METHOD("get_next_selected:TreeItem","from:TreeItem"),&Tree::_get_next_selected);
- ClassDB::bind_method(D_METHOD("get_selected:TreeItem"),&Tree::get_selected);
- ClassDB::bind_method(D_METHOD("get_selected_column"),&Tree::get_selected_column);
- ClassDB::bind_method(D_METHOD("get_pressed_button"),&Tree::get_pressed_button);
- ClassDB::bind_method(D_METHOD("set_select_mode","mode"),&Tree::set_select_mode);
-
- ClassDB::bind_method(D_METHOD("set_columns","amount"),&Tree::set_columns);
- ClassDB::bind_method(D_METHOD("get_columns"),&Tree::get_columns);
-
- ClassDB::bind_method(D_METHOD("get_edited:TreeItem"),&Tree::get_edited);
- ClassDB::bind_method(D_METHOD("get_edited_column"),&Tree::get_edited_column);
- ClassDB::bind_method(D_METHOD("get_custom_popup_rect"),&Tree::get_custom_popup_rect);
- ClassDB::bind_method(D_METHOD("get_item_area_rect","item:TreeItem","column"),&Tree::_get_item_rect,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("get_item_at_pos:TreeItem","pos"),&Tree::get_item_at_pos);
- ClassDB::bind_method(D_METHOD("get_column_at_pos","pos"),&Tree::get_column_at_pos);
-
- ClassDB::bind_method(D_METHOD("ensure_cursor_is_visible"),&Tree::ensure_cursor_is_visible);
-
- ClassDB::bind_method(D_METHOD("set_column_titles_visible","visible"),&Tree::set_column_titles_visible);
- ClassDB::bind_method(D_METHOD("are_column_titles_visible"),&Tree::are_column_titles_visible);
-
- ClassDB::bind_method(D_METHOD("set_column_title","column","title"),&Tree::set_column_title);
- ClassDB::bind_method(D_METHOD("get_column_title","column"),&Tree::get_column_title);
- ClassDB::bind_method(D_METHOD("get_scroll"),&Tree::get_scroll);
-
- ClassDB::bind_method(D_METHOD("set_hide_folding","hide"),&Tree::set_hide_folding);
- ClassDB::bind_method(D_METHOD("is_folding_hidden"),&Tree::is_folding_hidden);
-
- ClassDB::bind_method(D_METHOD("set_drop_mode_flags","flags"),&Tree::set_drop_mode_flags);
- ClassDB::bind_method(D_METHOD("get_drop_mode_flags"),&Tree::get_drop_mode_flags);
-
- ClassDB::bind_method(D_METHOD("set_allow_rmb_select","allow"),&Tree::set_allow_rmb_select);
- ClassDB::bind_method(D_METHOD("get_allow_rmb_select"),&Tree::get_allow_rmb_select);
-
- ClassDB::bind_method(D_METHOD("set_single_select_cell_editing_only_when_already_selected","enable"),&Tree::set_single_select_cell_editing_only_when_already_selected);
- ClassDB::bind_method(D_METHOD("get_single_select_cell_editing_only_when_already_selected"),&Tree::get_single_select_cell_editing_only_when_already_selected);
-
- ADD_SIGNAL( MethodInfo("item_selected"));
- ADD_SIGNAL( MethodInfo("cell_selected"));
- ADD_SIGNAL( MethodInfo("multi_selected",PropertyInfo(Variant::OBJECT,"item"),PropertyInfo(Variant::INT,"column"),PropertyInfo(Variant::BOOL,"selected")) );
- ADD_SIGNAL( MethodInfo("item_rmb_selected",PropertyInfo(Variant::VECTOR2,"pos")));
- ADD_SIGNAL( MethodInfo("empty_tree_rmb_selected",PropertyInfo(Variant::VECTOR2,"pos")));
- ADD_SIGNAL( MethodInfo("item_edited"));
- ADD_SIGNAL( MethodInfo("item_double_clicked"));
- ADD_SIGNAL( MethodInfo("item_collapsed",PropertyInfo(Variant::OBJECT,"item")));
+ ClassDB::bind_method(D_METHOD("_range_click_timeout"), &Tree::_range_click_timeout);
+ ClassDB::bind_method(D_METHOD("_gui_input"), &Tree::_gui_input);
+ ClassDB::bind_method(D_METHOD("_popup_select"), &Tree::popup_select);
+ ClassDB::bind_method(D_METHOD("_text_editor_enter"), &Tree::text_editor_enter);
+ ClassDB::bind_method(D_METHOD("_text_editor_modal_close"), &Tree::_text_editor_modal_close);
+ ClassDB::bind_method(D_METHOD("_value_editor_changed"), &Tree::value_editor_changed);
+ ClassDB::bind_method(D_METHOD("_scroll_moved"), &Tree::_scroll_moved);
+
+ ClassDB::bind_method(D_METHOD("clear"), &Tree::clear);
+ ClassDB::bind_method(D_METHOD("create_item:TreeItem", "parent:TreeItem"), &Tree::_create_item, DEFVAL(Variant()));
+
+ ClassDB::bind_method(D_METHOD("get_root:TreeItem"), &Tree::get_root);
+ ClassDB::bind_method(D_METHOD("set_column_min_width", "column", "min_width"), &Tree::set_column_min_width);
+ ClassDB::bind_method(D_METHOD("set_column_expand", "column", "expand"), &Tree::set_column_expand);
+ ClassDB::bind_method(D_METHOD("get_column_width", "column"), &Tree::get_column_width);
+
+ ClassDB::bind_method(D_METHOD("set_hide_root", "enable"), &Tree::set_hide_root);
+ ClassDB::bind_method(D_METHOD("get_next_selected:TreeItem", "from:TreeItem"), &Tree::_get_next_selected);
+ ClassDB::bind_method(D_METHOD("get_selected:TreeItem"), &Tree::get_selected);
+ ClassDB::bind_method(D_METHOD("get_selected_column"), &Tree::get_selected_column);
+ ClassDB::bind_method(D_METHOD("get_pressed_button"), &Tree::get_pressed_button);
+ ClassDB::bind_method(D_METHOD("set_select_mode", "mode"), &Tree::set_select_mode);
+
+ ClassDB::bind_method(D_METHOD("set_columns", "amount"), &Tree::set_columns);
+ ClassDB::bind_method(D_METHOD("get_columns"), &Tree::get_columns);
+
+ ClassDB::bind_method(D_METHOD("get_edited:TreeItem"), &Tree::get_edited);
+ ClassDB::bind_method(D_METHOD("get_edited_column"), &Tree::get_edited_column);
+ ClassDB::bind_method(D_METHOD("get_custom_popup_rect"), &Tree::get_custom_popup_rect);
+ ClassDB::bind_method(D_METHOD("get_item_area_rect", "item:TreeItem", "column"), &Tree::_get_item_rect, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("get_item_at_pos:TreeItem", "pos"), &Tree::get_item_at_pos);
+ ClassDB::bind_method(D_METHOD("get_column_at_pos", "pos"), &Tree::get_column_at_pos);
+
+ ClassDB::bind_method(D_METHOD("ensure_cursor_is_visible"), &Tree::ensure_cursor_is_visible);
+
+ ClassDB::bind_method(D_METHOD("set_column_titles_visible", "visible"), &Tree::set_column_titles_visible);
+ ClassDB::bind_method(D_METHOD("are_column_titles_visible"), &Tree::are_column_titles_visible);
+
+ ClassDB::bind_method(D_METHOD("set_column_title", "column", "title"), &Tree::set_column_title);
+ ClassDB::bind_method(D_METHOD("get_column_title", "column"), &Tree::get_column_title);
+ ClassDB::bind_method(D_METHOD("get_scroll"), &Tree::get_scroll);
+
+ ClassDB::bind_method(D_METHOD("set_hide_folding", "hide"), &Tree::set_hide_folding);
+ ClassDB::bind_method(D_METHOD("is_folding_hidden"), &Tree::is_folding_hidden);
+
+ ClassDB::bind_method(D_METHOD("set_drop_mode_flags", "flags"), &Tree::set_drop_mode_flags);
+ ClassDB::bind_method(D_METHOD("get_drop_mode_flags"), &Tree::get_drop_mode_flags);
+
+ ClassDB::bind_method(D_METHOD("set_allow_rmb_select", "allow"), &Tree::set_allow_rmb_select);
+ ClassDB::bind_method(D_METHOD("get_allow_rmb_select"), &Tree::get_allow_rmb_select);
+
+ ClassDB::bind_method(D_METHOD("set_single_select_cell_editing_only_when_already_selected", "enable"), &Tree::set_single_select_cell_editing_only_when_already_selected);
+ ClassDB::bind_method(D_METHOD("get_single_select_cell_editing_only_when_already_selected"), &Tree::get_single_select_cell_editing_only_when_already_selected);
+
+ ADD_SIGNAL(MethodInfo("item_selected"));
+ ADD_SIGNAL(MethodInfo("cell_selected"));
+ ADD_SIGNAL(MethodInfo("multi_selected", PropertyInfo(Variant::OBJECT, "item"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::BOOL, "selected")));
+ ADD_SIGNAL(MethodInfo("item_rmb_selected", PropertyInfo(Variant::VECTOR2, "pos")));
+ ADD_SIGNAL(MethodInfo("empty_tree_rmb_selected", PropertyInfo(Variant::VECTOR2, "pos")));
+ ADD_SIGNAL(MethodInfo("item_edited"));
+ ADD_SIGNAL(MethodInfo("item_double_clicked"));
+ ADD_SIGNAL(MethodInfo("item_collapsed", PropertyInfo(Variant::OBJECT, "item")));
//ADD_SIGNAL( MethodInfo("item_doubleclicked" ) );
- ADD_SIGNAL( MethodInfo("button_pressed",PropertyInfo(Variant::OBJECT,"item"),PropertyInfo(Variant::INT,"column"),PropertyInfo(Variant::INT,"id")));
- ADD_SIGNAL( MethodInfo("custom_popup_edited",PropertyInfo(Variant::BOOL,"arrow_clicked") ) );
- ADD_SIGNAL( MethodInfo("item_activated"));
+ ADD_SIGNAL(MethodInfo("button_pressed", PropertyInfo(Variant::OBJECT, "item"), PropertyInfo(Variant::INT, "column"), PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("custom_popup_edited", PropertyInfo(Variant::BOOL, "arrow_clicked")));
+ ADD_SIGNAL(MethodInfo("item_activated"));
- BIND_CONSTANT( SELECT_SINGLE );
- BIND_CONSTANT( SELECT_ROW );
- BIND_CONSTANT( SELECT_MULTI );
-
- BIND_CONSTANT( DROP_MODE_DISABLED );
- BIND_CONSTANT( DROP_MODE_ON_ITEM );
- BIND_CONSTANT( DROP_MODE_INBETWEEN );
+ BIND_CONSTANT(SELECT_SINGLE);
+ BIND_CONSTANT(SELECT_ROW);
+ BIND_CONSTANT(SELECT_MULTI);
+ BIND_CONSTANT(DROP_MODE_DISABLED);
+ BIND_CONSTANT(DROP_MODE_ON_ITEM);
+ BIND_CONSTANT(DROP_MODE_INBETWEEN);
}
Tree::Tree() {
- selected_col=0;
+ selected_col = 0;
columns.resize(1);
- selected_item=NULL;
- edited_item=NULL;
- selected_col=-1;
- edited_col=-1;
-
- hide_root=false;
- select_mode=SELECT_SINGLE;
- root=0;
- popup_menu=NULL;
- popup_edited_item=NULL;
- text_editor=NULL;
+ selected_item = NULL;
+ edited_item = NULL;
+ selected_col = -1;
+ edited_col = -1;
+
+ hide_root = false;
+ select_mode = SELECT_SINGLE;
+ root = 0;
+ popup_menu = NULL;
+ popup_edited_item = NULL;
+ text_editor = NULL;
set_focus_mode(FOCUS_ALL);
-
- popup_menu = memnew( PopupMenu );
+ popup_menu = memnew(PopupMenu);
popup_menu->hide();
add_child(popup_menu);
popup_menu->set_as_toplevel(true);
- text_editor = memnew( LineEdit );
+ text_editor = memnew(LineEdit);
add_child(text_editor);
text_editor->set_as_toplevel(true);
text_editor->hide();
- value_editor = memnew( HSlider );
+ value_editor = memnew(HSlider);
add_child(value_editor);
value_editor->set_as_toplevel(true);
value_editor->hide();
- h_scroll = memnew( HScrollBar );
- v_scroll = memnew( VScrollBar );
+ h_scroll = memnew(HScrollBar);
+ v_scroll = memnew(VScrollBar);
add_child(h_scroll);
add_child(v_scroll);
- range_click_timer = memnew( Timer );
- range_click_timer->connect("timeout",this,"_range_click_timeout");
+ range_click_timer = memnew(Timer);
+ range_click_timer->connect("timeout", this, "_range_click_timeout");
add_child(range_click_timer);
- h_scroll->connect("value_changed", this,"_scroll_moved");
- v_scroll->connect("value_changed", this,"_scroll_moved");
- text_editor->connect("text_entered", this,"_text_editor_enter");
- text_editor->connect("modal_closed", this,"_text_editor_modal_close");
- popup_menu->connect("id_pressed", this,"_popup_select");
- value_editor->connect("value_changed", this,"_value_editor_changed");
+ h_scroll->connect("value_changed", this, "_scroll_moved");
+ v_scroll->connect("value_changed", this, "_scroll_moved");
+ text_editor->connect("text_entered", this, "_text_editor_enter");
+ text_editor->connect("modal_closed", this, "_text_editor_modal_close");
+ popup_menu->connect("id_pressed", this, "_popup_select");
+ value_editor->connect("value_changed", this, "_value_editor_changed");
value_editor->set_as_toplevel(true);
text_editor->set_as_toplevel(true);
- updating_value_editor=false;
- pressed_button=-1;
- show_column_titles=false;
+ updating_value_editor = false;
+ pressed_button = -1;
+ show_column_titles = false;
cache.click_type = Cache::CLICK_NONE;
cache.hover_type = Cache::CLICK_NONE;
cache.hover_index = -1;
- cache.click_index=-1;
- cache.click_id=-1;
- cache.click_item=NULL;
- cache.click_column=0;
- last_keypress=0;
- focus_in_id=0;
+ cache.click_index = -1;
+ cache.click_id = -1;
+ cache.click_item = NULL;
+ cache.click_column = 0;
+ last_keypress = 0;
+ focus_in_id = 0;
- blocked=0;
+ blocked = 0;
- cursor_can_exit_tree=true;
+ cursor_can_exit_tree = true;
set_mouse_filter(MOUSE_FILTER_STOP);
- drag_speed=0;
- drag_touching=false;
- drag_touching_deaccel=false;
- pressing_for_editor=false;
- range_drag_enabled=false;
+ drag_speed = 0;
+ drag_touching = false;
+ drag_touching_deaccel = false;
+ pressing_for_editor = false;
+ range_drag_enabled = false;
- hide_folding=false;
+ hide_folding = false;
- evaluator=NULL;
+ evaluator = NULL;
- drop_mode_flags=0;
- drop_mode_over=NULL;
- drop_mode_section=0;
- single_select_defer=NULL;
- force_select_on_already_selected=false;
+ drop_mode_flags = 0;
+ drop_mode_over = NULL;
+ drop_mode_section = 0;
+ single_select_defer = NULL;
+ force_select_on_already_selected = false;
- allow_rmb_select=false;
- force_edit_checkbox_only_on_checkbox=false;
+ allow_rmb_select = false;
+ force_edit_checkbox_only_on_checkbox = false;
set_clip_contents(true);
}
-
Tree::~Tree() {
if (root) {
- memdelete( root );
+ memdelete(root);
}
-
}
diff --git a/scene/gui/tree.h b/scene/gui/tree.h
index 14bd2efbaa..68d4453156 100644
--- a/scene/gui/tree.h
+++ b/scene/gui/tree.h
@@ -29,25 +29,24 @@
#ifndef TREE_H
#define TREE_H
+#include "core/helper/value_evaluator.h"
#include "scene/gui/control.h"
-#include "scene/gui/popup_menu.h"
#include "scene/gui/line_edit.h"
+#include "scene/gui/popup_menu.h"
#include "scene/gui/scroll_bar.h"
#include "scene/gui/slider.h"
-#include "core/helper/value_evaluator.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class Tree;
class TreeItem : public Object {
- GDCLASS(TreeItem,Object);
-public:
+ GDCLASS(TreeItem, Object);
+public:
enum TreeCellMode {
CELL_MODE_STRING, ///< just a string
@@ -59,8 +58,7 @@ public:
};
private:
-friend class Tree;
-
+ friend class Tree;
struct Cell {
@@ -70,7 +68,7 @@ friend class Tree;
Rect2i icon_region;
String text;
String suffix;
- double min,max,step,val;
+ double min, max, step, val;
int icon_max_w;
bool expr;
bool checked;
@@ -94,33 +92,35 @@ friend class Tree;
bool disabled;
Ref<Texture> texture;
Color color;
- Button() { id=0; disabled=false; color=Color(1,1,1,1); }
+ Button() {
+ id = 0;
+ disabled = false;
+ color = Color(1, 1, 1, 1);
+ }
};
- Vector< Button > buttons;
+ Vector<Button> buttons;
Cell() {
- custom_draw_obj=0;
- mode=TreeItem::CELL_MODE_STRING;
- min=0;
- max=100;
- step=1;
- val=0;
- checked=false;
- editable=false;
- selected=false;
- selectable=true;
- custom_color=false;
- custom_bg_color=false;
- expr=false;
- icon_max_w=0;
+ custom_draw_obj = 0;
+ mode = TreeItem::CELL_MODE_STRING;
+ min = 0;
+ max = 100;
+ step = 1;
+ val = 0;
+ checked = false;
+ editable = false;
+ selected = false;
+ selectable = true;
+ custom_color = false;
+ custom_bg_color = false;
+ expr = false;
+ icon_max_w = 0;
}
-
Size2 get_icon_size() const;
- void draw_icon(const RID& p_where, const Point2& p_pos, const Size2& p_size=Size2()) const;
-
+ void draw_icon(const RID &p_where, const Point2 &p_pos, const Size2 &p_size = Size2()) const;
};
Vector<Cell> cells;
@@ -132,79 +132,76 @@ friend class Tree;
TreeItem *childs; //child items
Tree *tree; //tree (for reference)
-
-
TreeItem(Tree *p_tree);
-
void _changed_notify(int p_cell);
void _changed_notify();
void _cell_selected(int p_cell);
void _cell_deselected(int p_cell);
-protected:
+protected:
static void _bind_methods();
//bind helpers
- Dictionary _get_range_config( int p_column ) {
+ Dictionary _get_range_config(int p_column) {
Dictionary d;
- double min,max,step;
- get_range_config(p_column,min,max,step);
- d["min"]=min;
- d["max"]=max;
- d["step"]=step;
- d["expr"]=false;
+ double min, max, step;
+ get_range_config(p_column, min, max, step);
+ d["min"] = min;
+ d["max"] = max;
+ d["step"] = step;
+ d["expr"] = false;
return d;
}
- void _remove_child(Object *p_child) { remove_child( p_child->cast_to<TreeItem>() ); }
-public:
+ void _remove_child(Object *p_child) { remove_child(p_child->cast_to<TreeItem>()); }
+public:
/* cell mode */
- void set_cell_mode( int p_column, TreeCellMode p_mode );
- TreeCellMode get_cell_mode( int p_column ) const;
+ void set_cell_mode(int p_column, TreeCellMode p_mode);
+ TreeCellMode get_cell_mode(int p_column) const;
/* check mode */
- void set_checked(int p_column,bool p_checked);
+ void set_checked(int p_column, bool p_checked);
bool is_checked(int p_column) const;
- void set_text(int p_column,String p_text);
+ void set_text(int p_column, String p_text);
String get_text(int p_column) const;
- void set_suffix(int p_column,String p_suffix);
+ void set_suffix(int p_column, String p_suffix);
String get_suffix(int p_column) const;
- void set_icon(int p_column,const Ref<Texture>& p_icon);
+ void set_icon(int p_column, const Ref<Texture> &p_icon);
Ref<Texture> get_icon(int p_column) const;
- void set_icon_region(int p_column,const Rect2& p_icon_region);
+ void set_icon_region(int p_column, const Rect2 &p_icon_region);
Rect2 get_icon_region(int p_column) const;
- void set_icon_max_width(int p_column,int p_max);
+ void set_icon_max_width(int p_column, int p_max);
int get_icon_max_width(int p_column) const;
- void add_button(int p_column,const Ref<Texture>& p_button,int p_id=-1,bool p_disabled=false);
+ void add_button(int p_column, const Ref<Texture> &p_button, int p_id = -1, bool p_disabled = false);
int get_button_count(int p_column) const;
- Ref<Texture> get_button(int p_column,int p_idx) const;
- int get_button_id(int p_column,int p_idx) const;
- void erase_button(int p_column,int p_idx);
- int get_button_by_id(int p_column,int p_id) const;
- bool is_button_disabled(int p_column,int p_idx) const;
- void set_button(int p_column,int p_idx,const Ref<Texture>& p_button);
- void set_button_color(int p_column,int p_idx,const Color& p_color);
+ Ref<Texture> get_button(int p_column, int p_idx) const;
+ int get_button_id(int p_column, int p_idx) const;
+ void erase_button(int p_column, int p_idx);
+ int get_button_by_id(int p_column, int p_id) const;
+ bool is_button_disabled(int p_column, int p_idx) const;
+ void set_button(int p_column, int p_idx, const Ref<Texture> &p_button);
+ void set_button_color(int p_column, int p_idx, const Color &p_color);
/* range works for mode number or mode combo */
- void set_range(int p_column,double p_value);
+ void set_range(int p_column, double p_value);
double get_range(int p_column) const;
- void set_range_config(int p_column,double p_min,double p_max,double p_step,bool p_exp=false);
- void get_range_config(int p_column,double& r_min,double& r_max,double &r_step) const;
+ void set_range_config(int p_column, double p_min, double p_max, double p_step, bool p_exp = false);
+ void get_range_config(int p_column, double &r_min, double &r_max, double &r_step) const;
bool is_range_exponential(int p_column) const;
- void set_metadata(int p_column,const Variant& p_meta);
+ void set_metadata(int p_column, const Variant &p_meta);
Variant get_metadata(int p_column) const;
- void set_custom_draw(int p_column,Object *p_object,const StringName& p_callback);
+ void set_custom_draw(int p_column, Object *p_object, const StringName &p_callback);
void set_collapsed(bool p_collapsed);
bool is_collapsed();
@@ -219,7 +216,7 @@ public:
void remove_child(TreeItem *p_item);
- void set_selectable(int p_column,bool p_selectable);
+ void set_selectable(int p_column, bool p_selectable);
bool is_selectable(int p_column) const;
bool is_selected(int p_column);
@@ -227,52 +224,49 @@ public:
void deselect(int p_column);
void set_as_cursor(int p_column);
- void set_editable(int p_column,bool p_editable);
+ void set_editable(int p_column, bool p_editable);
bool is_editable(int p_column);
- void set_custom_color(int p_column,const Color& p_color);
+ void set_custom_color(int p_column, const Color &p_color);
Color get_custom_color(int p_column) const;
void clear_custom_color(int p_column);
- void set_custom_bg_color(int p_column, const Color& p_color, bool p_bg_outline=false);
+ void set_custom_bg_color(int p_column, const Color &p_color, bool p_bg_outline = false);
void clear_custom_bg_color(int p_column);
Color get_custom_bg_color(int p_column) const;
- void set_tooltip(int p_column, const String& p_tooltip);
+ void set_tooltip(int p_column, const String &p_tooltip);
String get_tooltip(int p_column) const;
-
void clear_children();
void move_to_top();
void move_to_bottom();
~TreeItem();
-
};
-
-VARIANT_ENUM_CAST( TreeItem::TreeCellMode );
-
+VARIANT_ENUM_CAST(TreeItem::TreeCellMode);
class Tree : public Control {
- GDCLASS( Tree, Control );
+ GDCLASS(Tree, Control);
+
public:
enum SelectMode {
- SELECT_SINGLE,
- SELECT_ROW,
- SELECT_MULTI
+ SELECT_SINGLE,
+ SELECT_ROW,
+ SELECT_MULTI
};
enum DropModeFlags {
- DROP_MODE_DISABLED=0,
- DROP_MODE_ON_ITEM=1,
- DROP_MODE_INBETWEEN=2
+ DROP_MODE_DISABLED = 0,
+ DROP_MODE_ON_ITEM = 1,
+ DROP_MODE_INBETWEEN = 2
};
private:
-friend class TreeItem;
+ friend class TreeItem;
TreeItem *root;
TreeItem *popup_edited_item;
@@ -295,7 +289,6 @@ friend class TreeItem;
bool range_drag_enabled;
Vector2 range_drag_capture_pos;
-
//TreeItem *cursor_item;
//int cursor_column;
@@ -315,7 +308,10 @@ friend class TreeItem;
int min_width;
bool expand;
String title;
- ColumnInfo() { min_width=1; expand=true; }
+ ColumnInfo() {
+ min_width = 1;
+ expand = true;
+ }
};
bool show_column_titles;
@@ -335,10 +331,10 @@ friend class TreeItem;
int compute_item_height(TreeItem *p_item) const;
int get_item_height(TreeItem *p_item) const;
//void draw_item_text(String p_text,const Ref<Texture>& p_icon,int p_icon_max_w,bool p_tool,Rect2i p_rect,const Color& p_color);
- void draw_item_rect(const TreeItem::Cell& p_cell,const Rect2i& p_rect,const Color& p_color);
- int draw_item(const Point2i& p_pos,const Point2& p_draw_ofs, const Size2& p_draw_size,TreeItem *p_item);
- void select_single_item(TreeItem *p_selected,TreeItem *p_current,int p_col,TreeItem *p_prev=NULL,bool *r_in_range=NULL,bool p_force_deselect=false);
- int propagate_mouse_event(const Point2i &p_pos,int x_ofs,int y_ofs,bool p_doubleclick,TreeItem *p_item,int p_button,const InputModifierState& p_mod);
+ void draw_item_rect(const TreeItem::Cell &p_cell, const Rect2i &p_rect, const Color &p_color);
+ int draw_item(const Point2i &p_pos, const Point2 &p_draw_ofs, const Size2 &p_draw_size, TreeItem *p_item);
+ void select_single_item(TreeItem *p_selected, TreeItem *p_current, int p_col, TreeItem *p_prev = NULL, bool *r_in_range = NULL, bool p_force_deselect = false);
+ int propagate_mouse_event(const Point2i &p_pos, int x_ofs, int y_ofs, bool p_doubleclick, TreeItem *p_item, int p_button, const InputModifierState &p_mod);
void text_editor_enter(String p_text);
void _text_editor_modal_close();
void value_editor_changed(double p_value);
@@ -350,10 +346,10 @@ friend class TreeItem;
Size2 get_minimum_size() const;
- void item_edited(int p_column,TreeItem *p_item);
- void item_changed(int p_column,TreeItem *p_item);
- void item_selected(int p_column,TreeItem *p_item);
- void item_deselected(int p_column,TreeItem *p_item);
+ void item_edited(int p_column, TreeItem *p_item);
+ void item_changed(int p_column, TreeItem *p_item);
+ void item_selected(int p_column, TreeItem *p_item);
+ void item_deselected(int p_column, TreeItem *p_item);
void propagate_set_columns(TreeItem *p_item);
@@ -413,7 +409,6 @@ friend class TreeItem;
} cache;
-
int _get_title_button_height() const;
void _scroll_moved(float p_value);
@@ -429,13 +424,13 @@ friend class TreeItem;
uint64_t last_keypress;
String incr_search;
bool cursor_can_exit_tree;
- void _do_incr_search(const String& p_add);
+ void _do_incr_search(const String &p_add);
- TreeItem* _search_item_text(TreeItem *p_at, const String& p_find,int *r_col,bool p_selectable,bool p_backwards=false);
+ TreeItem *_search_item_text(TreeItem *p_at, const String &p_find, int *r_col, bool p_selectable, bool p_backwards = false);
- TreeItem* _find_item_at_pos(TreeItem *p_current, const Point2& p_pos, int& r_column, int &h, int &section) const;
+ TreeItem *_find_item_at_pos(TreeItem *p_current, const Point2 &p_pos, int &r_column, int &h, int &section) const;
-/* float drag_speed;
+ /* float drag_speed;
float drag_accum;
float last_drag_accum;
@@ -459,37 +454,35 @@ friend class TreeItem;
ValueEvaluator *evaluator;
- int _count_selected_items(TreeItem* p_from) const;
+ int _count_selected_items(TreeItem *p_from) const;
protected:
static void _bind_methods();
//bind helpers
- Object* _create_item(Object *p_parent) { return create_item(p_parent->cast_to<TreeItem>() ); }
- TreeItem *_get_next_selected(Object *p_item) { return get_next_selected(p_item->cast_to<TreeItem>() ); }
- Rect2 _get_item_rect(Object *p_item,int p_column) const { return get_item_rect(p_item->cast_to<TreeItem>(),p_column ); }
-
+ Object *_create_item(Object *p_parent) { return create_item(p_parent->cast_to<TreeItem>()); }
+ TreeItem *_get_next_selected(Object *p_item) { return get_next_selected(p_item->cast_to<TreeItem>()); }
+ Rect2 _get_item_rect(Object *p_item, int p_column) const { return get_item_rect(p_item->cast_to<TreeItem>(), p_column); }
public:
+ virtual String get_tooltip(const Point2 &p_pos) const;
- virtual String get_tooltip(const Point2& p_pos) const;
-
- TreeItem* get_item_at_pos(const Point2& p_pos) const;
- int get_column_at_pos(const Point2& p_pos) const;
- int get_drop_section_at_pos(const Point2& p_pos) const;
+ TreeItem *get_item_at_pos(const Point2 &p_pos) const;
+ int get_column_at_pos(const Point2 &p_pos) const;
+ int get_drop_section_at_pos(const Point2 &p_pos) const;
void clear();
- TreeItem* create_item(TreeItem *p_parent=0);
- TreeItem* get_root();
- TreeItem* get_last_item();
+ TreeItem *create_item(TreeItem *p_parent = 0);
+ TreeItem *get_root();
+ TreeItem *get_last_item();
- void set_column_min_width(int p_column,int p_min_width);
- void set_column_expand(int p_column,bool p_expand);
+ void set_column_min_width(int p_column, int p_min_width);
+ void set_column_expand(int p_column, bool p_expand);
int get_column_width(int p_column) const;
void set_hide_root(bool p_eanbled);
- TreeItem *get_next_selected( TreeItem* p_item);
+ TreeItem *get_next_selected(TreeItem *p_item);
TreeItem *get_selected() const;
int get_selected_column() const;
int get_pressed_button() const;
@@ -498,7 +491,7 @@ public:
void set_columns(int p_columns);
int get_columns() const;
- void set_column_title(int p_column,const String& p_title);
+ void set_column_title(int p_column, const String &p_title);
String get_column_title(int p_column) const;
void set_column_titles_visible(bool p_show);
@@ -512,10 +505,10 @@ public:
Rect2 get_custom_popup_rect() const;
int get_item_offset(TreeItem *p_item) const;
- Rect2 get_item_rect(TreeItem *p_item,int p_column=-1) const;
+ Rect2 get_item_rect(TreeItem *p_item, int p_column = -1) const;
bool edit_selected();
- TreeItem* search_item_text(const String& p_find,int *r_col=NULL,bool p_selectable=false);
+ TreeItem *search_item_text(const String &p_find, int *r_col = NULL, bool p_selectable = false);
Point2 get_scroll() const;
@@ -536,7 +529,6 @@ public:
void set_edit_checkbox_cell_only_when_checkbox_is_pressed(bool p_enable);
bool get_edit_checkbox_cell_only_when_checkbox_is_pressed() const;
-
void set_allow_rmb_select(bool p_allow);
bool get_allow_rmb_select() const;
@@ -544,8 +536,7 @@ public:
Tree();
~Tree();
-
};
-VARIANT_ENUM_CAST( Tree::SelectMode );
+VARIANT_ENUM_CAST(Tree::SelectMode);
#endif
diff --git a/scene/gui/video_player.cpp b/scene/gui/video_player.cpp
index 063ad8c44a..433cc546a6 100644
--- a/scene/gui/video_player.cpp
+++ b/scene/gui/video_player.cpp
@@ -54,15 +54,15 @@ int VideoPlayer::sp_get_channel_count() const {
return playback->get_channels();
}
-void VideoPlayer::sp_set_mix_rate(int p_rate){
+void VideoPlayer::sp_set_mix_rate(int p_rate) {
- server_mix_rate=p_rate;
+ server_mix_rate = p_rate;
}
-bool VideoPlayer::sp_mix(int32_t *p_buffer,int p_frames) {
+bool VideoPlayer::sp_mix(int32_t *p_buffer, int p_frames) {
if (resampler.is_ready()) {
- return resampler.mix(p_buffer,p_frames);
+ return resampler.mix(p_buffer, p_frames);
}
return false;
@@ -93,24 +93,22 @@ void VideoPlayer::sp_update() {
#endif
}
-int VideoPlayer::_audio_mix_callback(void* p_udata,const int16_t *p_data,int p_frames) {
+int VideoPlayer::_audio_mix_callback(void *p_udata, const int16_t *p_data, int p_frames) {
- VideoPlayer *vp=(VideoPlayer*)p_udata;
+ VideoPlayer *vp = (VideoPlayer *)p_udata;
- int todo=MIN(vp->resampler.get_todo(),p_frames);
+ int todo = MIN(vp->resampler.get_todo(), p_frames);
int16_t *wb = vp->resampler.get_write_buffer();
int c = vp->resampler.get_channel_count();
- for(int i=0;i<todo*c;i++) {
- wb[i]=p_data[i];
+ for (int i = 0; i < todo * c; i++) {
+ wb[i] = p_data[i];
}
vp->resampler.write(todo);
return todo;
}
-
-
void VideoPlayer::_notification(int p_notification) {
switch (p_notification) {
@@ -133,12 +131,11 @@ void VideoPlayer::_notification(int p_notification) {
double audio_time = USEC_TO_SEC(OS::get_singleton()->get_ticks_usec()); //AudioServer::get_singleton()->get_mix_time();
- double delta = last_audio_time==0?0:audio_time-last_audio_time;
- last_audio_time=audio_time;
- if (delta==0)
+ double delta = last_audio_time == 0 ? 0 : audio_time - last_audio_time;
+ last_audio_time = audio_time;
+ if (delta == 0)
return;
-
playback->update(delta);
} break;
@@ -150,17 +147,13 @@ void VideoPlayer::_notification(int p_notification) {
if (texture->get_width() == 0)
return;
- Size2 s=expand?get_size():texture->get_size();
- draw_texture_rect(texture,Rect2(Point2(),s),false);
+ Size2 s = expand ? get_size() : texture->get_size();
+ draw_texture_rect(texture, Rect2(Point2(), s), false);
} break;
};
-
};
-
-
-
Size2 VideoPlayer::get_minimum_size() const {
if (!expand && !texture.is_null())
@@ -171,7 +164,7 @@ Size2 VideoPlayer::get_minimum_size() const {
void VideoPlayer::set_expand(bool p_expand) {
- expand=p_expand;
+ expand = p_expand;
update();
minimum_size_changed();
}
@@ -181,35 +174,34 @@ bool VideoPlayer::has_expand() const {
return expand;
}
-
void VideoPlayer::set_stream(const Ref<VideoStream> &p_stream) {
stop();
- stream=p_stream;
- if (stream.is_valid()) {
- stream->set_audio_track(audio_track);
- playback=stream->instance_playback();
- } else {
- playback=Ref<VideoStreamPlayback>();
- }
+ stream = p_stream;
+ if (stream.is_valid()) {
+ stream->set_audio_track(audio_track);
+ playback = stream->instance_playback();
+ } else {
+ playback = Ref<VideoStreamPlayback>();
+ }
if (!playback.is_null()) {
playback->set_loop(loops);
playback->set_paused(paused);
- texture=playback->get_texture();
+ texture = playback->get_texture();
const int channels = playback->get_channels();
AudioServer::get_singleton()->lock();
if (channels > 0)
- resampler.setup(channels,playback->get_mix_rate(),server_mix_rate,buffering_ms,0);
+ resampler.setup(channels, playback->get_mix_rate(), server_mix_rate, buffering_ms, 0);
else
resampler.clear();
AudioServer::get_singleton()->unlock();
if (channels > 0)
- playback->set_mix_callback(_audio_mix_callback,this);
+ playback->set_mix_callback(_audio_mix_callback, this);
} else {
texture.unref();
@@ -219,7 +211,6 @@ void VideoPlayer::set_stream(const Ref<VideoStream> &p_stream) {
}
update();
-
};
Ref<VideoStream> VideoPlayer::get_stream() const {
@@ -235,9 +226,9 @@ void VideoPlayer::play() {
playback->stop();
playback->play();
set_process_internal(true);
-// AudioServer::get_singleton()->stream_set_active(stream_rid,true);
-// AudioServer::get_singleton()->stream_set_volume_scale(stream_rid,volume);
- last_audio_time=0;
+ // AudioServer::get_singleton()->stream_set_active(stream_rid,true);
+ // AudioServer::get_singleton()->stream_set_volume_scale(stream_rid,volume);
+ last_audio_time = 0;
};
void VideoPlayer::stop() {
@@ -248,10 +239,10 @@ void VideoPlayer::stop() {
return;
playback->stop();
-// AudioServer::get_singleton()->stream_set_active(stream_rid,false);
+ // AudioServer::get_singleton()->stream_set_active(stream_rid,false);
resampler.flush();
set_process_internal(false);
- last_audio_time=0;
+ last_audio_time = 0;
};
bool VideoPlayer::is_playing() const {
@@ -264,7 +255,7 @@ bool VideoPlayer::is_playing() const {
void VideoPlayer::set_paused(bool p_paused) {
- paused=p_paused;
+ paused = p_paused;
if (playback.is_valid()) {
playback->set_paused(p_paused);
set_process_internal(!p_paused);
@@ -279,27 +270,26 @@ bool VideoPlayer::is_paused() const {
void VideoPlayer::set_buffering_msec(int p_msec) {
- buffering_ms=p_msec;
+ buffering_ms = p_msec;
}
-int VideoPlayer::get_buffering_msec() const{
+int VideoPlayer::get_buffering_msec() const {
return buffering_ms;
}
void VideoPlayer::set_audio_track(int p_track) {
- audio_track=p_track;
+ audio_track = p_track;
}
int VideoPlayer::get_audio_track() const {
- return audio_track;
+ return audio_track;
}
-
void VideoPlayer::set_volume(float p_vol) {
- volume=p_vol;
+ volume = p_vol;
};
float VideoPlayer::get_volume() const {
@@ -309,7 +299,7 @@ float VideoPlayer::get_volume() const {
void VideoPlayer::set_volume_db(float p_db) {
- if (p_db<-79)
+ if (p_db < -79)
set_volume(0);
else
set_volume(Math::db2linear(p_db));
@@ -317,13 +307,12 @@ void VideoPlayer::set_volume_db(float p_db) {
float VideoPlayer::get_volume_db() const {
- if (volume==0)
+ if (volume == 0)
return -80;
else
return Math::linear2db(volume);
};
-
String VideoPlayer::get_stream_name() const {
if (stream.is_null())
@@ -343,12 +332,12 @@ Ref<Texture> VideoPlayer::get_video_texture() {
if (playback.is_valid())
return playback->get_texture();
- return Ref<Texture> ();
+ return Ref<Texture>();
}
void VideoPlayer::set_autoplay(bool p_enable) {
- autoplay=p_enable;
+ autoplay = p_enable;
};
bool VideoPlayer::has_autoplay() const {
@@ -358,75 +347,72 @@ bool VideoPlayer::has_autoplay() const {
void VideoPlayer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_stream","stream:VideoStream"),&VideoPlayer::set_stream);
- ClassDB::bind_method(D_METHOD("get_stream:VideoStream"),&VideoPlayer::get_stream);
+ ClassDB::bind_method(D_METHOD("set_stream", "stream:VideoStream"), &VideoPlayer::set_stream);
+ ClassDB::bind_method(D_METHOD("get_stream:VideoStream"), &VideoPlayer::get_stream);
- ClassDB::bind_method(D_METHOD("play"),&VideoPlayer::play);
- ClassDB::bind_method(D_METHOD("stop"),&VideoPlayer::stop);
+ ClassDB::bind_method(D_METHOD("play"), &VideoPlayer::play);
+ ClassDB::bind_method(D_METHOD("stop"), &VideoPlayer::stop);
- ClassDB::bind_method(D_METHOD("is_playing"),&VideoPlayer::is_playing);
+ ClassDB::bind_method(D_METHOD("is_playing"), &VideoPlayer::is_playing);
- ClassDB::bind_method(D_METHOD("set_paused","paused"),&VideoPlayer::set_paused);
- ClassDB::bind_method(D_METHOD("is_paused"),&VideoPlayer::is_paused);
+ ClassDB::bind_method(D_METHOD("set_paused", "paused"), &VideoPlayer::set_paused);
+ ClassDB::bind_method(D_METHOD("is_paused"), &VideoPlayer::is_paused);
- ClassDB::bind_method(D_METHOD("set_volume","volume"),&VideoPlayer::set_volume);
- ClassDB::bind_method(D_METHOD("get_volume"),&VideoPlayer::get_volume);
+ ClassDB::bind_method(D_METHOD("set_volume", "volume"), &VideoPlayer::set_volume);
+ ClassDB::bind_method(D_METHOD("get_volume"), &VideoPlayer::get_volume);
- ClassDB::bind_method(D_METHOD("set_volume_db","db"),&VideoPlayer::set_volume_db);
- ClassDB::bind_method(D_METHOD("get_volume_db"),&VideoPlayer::get_volume_db);
+ ClassDB::bind_method(D_METHOD("set_volume_db", "db"), &VideoPlayer::set_volume_db);
+ ClassDB::bind_method(D_METHOD("get_volume_db"), &VideoPlayer::get_volume_db);
- ClassDB::bind_method(D_METHOD("set_audio_track","track"),&VideoPlayer::set_audio_track);
- ClassDB::bind_method(D_METHOD("get_audio_track"),&VideoPlayer::get_audio_track);
+ ClassDB::bind_method(D_METHOD("set_audio_track", "track"), &VideoPlayer::set_audio_track);
+ ClassDB::bind_method(D_METHOD("get_audio_track"), &VideoPlayer::get_audio_track);
- ClassDB::bind_method(D_METHOD("get_stream_name"),&VideoPlayer::get_stream_name);
+ ClassDB::bind_method(D_METHOD("get_stream_name"), &VideoPlayer::get_stream_name);
- ClassDB::bind_method(D_METHOD("get_stream_pos"),&VideoPlayer::get_stream_pos);
+ ClassDB::bind_method(D_METHOD("get_stream_pos"), &VideoPlayer::get_stream_pos);
- ClassDB::bind_method(D_METHOD("set_autoplay","enabled"),&VideoPlayer::set_autoplay);
- ClassDB::bind_method(D_METHOD("has_autoplay"),&VideoPlayer::has_autoplay);
+ ClassDB::bind_method(D_METHOD("set_autoplay", "enabled"), &VideoPlayer::set_autoplay);
+ ClassDB::bind_method(D_METHOD("has_autoplay"), &VideoPlayer::has_autoplay);
- ClassDB::bind_method(D_METHOD("set_expand","enable"), &VideoPlayer::set_expand );
- ClassDB::bind_method(D_METHOD("has_expand"), &VideoPlayer::has_expand );
+ ClassDB::bind_method(D_METHOD("set_expand", "enable"), &VideoPlayer::set_expand);
+ ClassDB::bind_method(D_METHOD("has_expand"), &VideoPlayer::has_expand);
- ClassDB::bind_method(D_METHOD("set_buffering_msec","msec"),&VideoPlayer::set_buffering_msec);
- ClassDB::bind_method(D_METHOD("get_buffering_msec"),&VideoPlayer::get_buffering_msec);
+ ClassDB::bind_method(D_METHOD("set_buffering_msec", "msec"), &VideoPlayer::set_buffering_msec);
+ ClassDB::bind_method(D_METHOD("get_buffering_msec"), &VideoPlayer::get_buffering_msec);
- ClassDB::bind_method(D_METHOD("get_video_texture:Texture"), &VideoPlayer::get_video_texture );
+ ClassDB::bind_method(D_METHOD("get_video_texture:Texture"), &VideoPlayer::get_video_texture);
- ADD_PROPERTY( PropertyInfo(Variant::INT, "audio_track",PROPERTY_HINT_RANGE,"0,128,1"), "set_audio_track", "get_audio_track") ;
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE,"VideoStream"), "set_stream", "get_stream") ;
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "audio_track", PROPERTY_HINT_RANGE, "0,128,1"), "set_audio_track", "get_audio_track");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "VideoStream"), "set_stream", "get_stream");
//ADD_PROPERTY( PropertyInfo(Variant::BOOL, "stream/loop"), "set_loop", "has_loop") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE,"-80,24,0.01"), "set_volume_db", "get_volume_db") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "has_autoplay") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "paused"), "set_paused", "is_paused") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "expand" ), "set_expand","has_expand") ;
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24,0.01"), "set_volume_db", "get_volume_db");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "has_autoplay");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "paused"), "set_paused", "is_paused");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "expand"), "set_expand", "has_expand");
}
-
VideoPlayer::VideoPlayer() {
- volume=1;
+ volume = 1;
loops = false;
paused = false;
autoplay = false;
expand = true;
loops = false;
- audio_track=0;
-
- buffering_ms=500;
- server_mix_rate=44100;
+ audio_track = 0;
-// internal_stream.player=this;
-// stream_rid=AudioServer::get_singleton()->audio_stream_create(&internal_stream);
- last_audio_time=0;
+ buffering_ms = 500;
+ server_mix_rate = 44100;
+ // internal_stream.player=this;
+ // stream_rid=AudioServer::get_singleton()->audio_stream_create(&internal_stream);
+ last_audio_time = 0;
};
VideoPlayer::~VideoPlayer() {
-// if (stream_rid.is_valid())
-// AudioServer::get_singleton()->free(stream_rid);
+ // if (stream_rid.is_valid())
+ // AudioServer::get_singleton()->free(stream_rid);
resampler.clear(); //Not necessary here, but make in consistent with other "stream_player" classes
};
-
diff --git a/scene/gui/video_player.h b/scene/gui/video_player.h
index 168ea805b1..4f2894cdc2 100644
--- a/scene/gui/video_player.h
+++ b/scene/gui/video_player.h
@@ -29,15 +29,15 @@
#ifndef VIDEO_PLAYER_H
#define VIDEO_PLAYER_H
-#include "scene/resources/video_stream.h"
#include "scene/gui/control.h"
+#include "scene/resources/video_stream.h"
#include "servers/audio/audio_rb_resampler.h"
class VideoPlayer : public Control {
- GDCLASS(VideoPlayer,Control);
+ GDCLASS(VideoPlayer, Control);
-/* struct InternalStream : public AudioServer::AudioStream {
+ /* struct InternalStream : public AudioServer::AudioStream {
VideoPlayer *player;
virtual int get_channel_count() const;
virtual void set_mix_rate(int p_rate); //notify the stream of the mix rate
@@ -46,16 +46,15 @@ class VideoPlayer : public Control {
};
*/
-// InternalStream internal_stream;
+ // InternalStream internal_stream;
Ref<VideoStreamPlayback> playback;
Ref<VideoStream> stream;
int sp_get_channel_count() const;
void sp_set_mix_rate(int p_rate); //notify the stream of the mix rate
- bool sp_mix(int32_t *p_buffer,int p_frames);
+ bool sp_mix(int32_t *p_buffer, int p_frames);
void sp_update();
-
RID stream_rid;
Ref<ImageTexture> texture;
@@ -70,24 +69,20 @@ class VideoPlayer : public Control {
bool expand;
bool loops;
int buffering_ms;
- int server_mix_rate;
- int audio_track;
-
- static int _audio_mix_callback(void* p_udata,const int16_t *p_data,int p_frames);
+ int server_mix_rate;
+ int audio_track;
+ static int _audio_mix_callback(void *p_udata, const int16_t *p_data, int p_frames);
protected:
-
static void _bind_methods();
void _notification(int p_notification);
public:
-
Size2 get_minimum_size() const;
void set_expand(bool p_expand);
bool has_expand() const;
-
Ref<Texture> get_video_texture();
void set_stream(const Ref<VideoStream> &p_stream);
diff --git a/scene/gui/viewport_container.cpp b/scene/gui/viewport_container.cpp
index adc4a14a60..93789d945d 100644
--- a/scene/gui/viewport_container.cpp
+++ b/scene/gui/viewport_container.cpp
@@ -35,28 +35,25 @@ Size2 ViewportContainer::get_minimum_size() const {
if (stretch)
return Size2();
Size2 ms;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Viewport *c = get_child(i)->cast_to<Viewport>();
if (!c)
continue;
Size2 minsize = c->get_size();
- ms.width = MAX(ms.width , minsize.width);
- ms.height = MAX(ms.height , minsize.height);
+ ms.width = MAX(ms.width, minsize.width);
+ ms.height = MAX(ms.height, minsize.height);
}
return ms;
-
}
-
void ViewportContainer::set_stretch(bool p_enable) {
- stretch=p_enable;
+ stretch = p_enable;
queue_sort();
update();
-
}
bool ViewportContainer::is_stretch_enabled() const {
@@ -64,16 +61,14 @@ bool ViewportContainer::is_stretch_enabled() const {
return stretch;
}
-
void ViewportContainer::_notification(int p_what) {
-
- if (p_what==NOTIFICATION_RESIZED) {
+ if (p_what == NOTIFICATION_RESIZED) {
if (!stretch)
return;
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Viewport *c = get_child(i)->cast_to<Viewport>();
if (!c)
@@ -83,50 +78,46 @@ void ViewportContainer::_notification(int p_what) {
}
}
- if (p_what==NOTIFICATION_ENTER_TREE || p_what==NOTIFICATION_VISIBILITY_CHANGED) {
+ if (p_what == NOTIFICATION_ENTER_TREE || p_what == NOTIFICATION_VISIBILITY_CHANGED) {
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
Viewport *c = get_child(i)->cast_to<Viewport>();
if (!c)
continue;
-
if (is_visible_in_tree())
c->set_update_mode(Viewport::UPDATE_ALWAYS);
else
c->set_update_mode(Viewport::UPDATE_DISABLED);
}
-
}
- if (p_what==NOTIFICATION_DRAW) {
-
- for(int i=0;i<get_child_count();i++) {
+ if (p_what == NOTIFICATION_DRAW) {
+ for (int i = 0; i < get_child_count(); i++) {
Viewport *c = get_child(i)->cast_to<Viewport>();
if (!c)
continue;
if (stretch)
- draw_texture_rect(c->get_texture(),Rect2(Vector2(),get_size()*Size2(1,-1)));
+ draw_texture_rect(c->get_texture(), Rect2(Vector2(), get_size() * Size2(1, -1)));
else
- draw_texture_rect(c->get_texture(),Rect2(Vector2(),c->get_size()*Size2(1,-1)));
+ draw_texture_rect(c->get_texture(), Rect2(Vector2(), c->get_size() * Size2(1, -1)));
}
}
-
}
void ViewportContainer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_stretch","enable"),&ViewportContainer::set_stretch);
- ClassDB::bind_method(D_METHOD("is_stretch_enabled"),&ViewportContainer::is_stretch_enabled);
+ ClassDB::bind_method(D_METHOD("set_stretch", "enable"), &ViewportContainer::set_stretch);
+ ClassDB::bind_method(D_METHOD("is_stretch_enabled"), &ViewportContainer::is_stretch_enabled);
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"stretch"),"set_stretch","is_stretch_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stretch"), "set_stretch", "is_stretch_enabled");
}
ViewportContainer::ViewportContainer() {
- stretch=false;
+ stretch = false;
}
diff --git a/scene/gui/viewport_container.h b/scene/gui/viewport_container.h
index bcd41fa4a8..96b352b1cc 100644
--- a/scene/gui/viewport_container.h
+++ b/scene/gui/viewport_container.h
@@ -33,15 +33,15 @@
class ViewportContainer : public Container {
- GDCLASS( ViewportContainer, Container );
+ GDCLASS(ViewportContainer, Container);
bool stretch;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_stretch(bool p_enable);
bool is_stretch_enabled() const;
diff --git a/scene/io/resource_format_image.cpp b/scene/io/resource_format_image.cpp
index 8bb07adb5f..6a550a847d 100644
--- a/scene/io/resource_format_image.cpp
+++ b/scene/io/resource_format_image.cpp
@@ -29,10 +29,10 @@
#include "resource_format_image.h"
#if 0
-#include "scene/resources/texture.h"
-#include "io/image_loader.h"
#include "global_config.h"
+#include "io/image_loader.h"
#include "os/os.h"
+#include "scene/resources/texture.h"
RES ResourceFormatLoaderImage::load(const String &p_path, const String& p_original_path, Error *r_error) {
if (r_error)
diff --git a/scene/main/canvas_layer.cpp b/scene/main/canvas_layer.cpp
index 04d72b5a3d..1fecb6fd9a 100644
--- a/scene/main/canvas_layer.cpp
+++ b/scene/main/canvas_layer.cpp
@@ -29,27 +29,24 @@
#include "canvas_layer.h"
#include "viewport.h"
-
void CanvasLayer::set_layer(int p_xform) {
- layer=p_xform;
+ layer = p_xform;
if (viewport.is_valid())
- VisualServer::get_singleton()->viewport_set_canvas_layer(viewport,canvas->get_canvas(),layer);
-
+ VisualServer::get_singleton()->viewport_set_canvas_layer(viewport, canvas->get_canvas(), layer);
}
-int CanvasLayer::get_layer() const{
+int CanvasLayer::get_layer() const {
return layer;
}
-void CanvasLayer::set_transform(const Transform2D& p_xform) {
+void CanvasLayer::set_transform(const Transform2D &p_xform) {
- transform=p_xform;
- locrotscale_dirty=true;
+ transform = p_xform;
+ locrotscale_dirty = true;
if (viewport.is_valid())
- VisualServer::get_singleton()->viewport_set_canvas_transform(viewport,canvas->get_canvas(),transform);
-
+ VisualServer::get_singleton()->viewport_set_canvas_transform(viewport, canvas->get_canvas(), transform);
}
Transform2D CanvasLayer::get_transform() const {
@@ -59,56 +56,50 @@ Transform2D CanvasLayer::get_transform() const {
void CanvasLayer::_update_xform() {
- transform.set_rotation_and_scale(rot,scale);
+ transform.set_rotation_and_scale(rot, scale);
transform.set_origin(ofs);
if (viewport.is_valid())
- VisualServer::get_singleton()->viewport_set_canvas_transform(viewport,canvas->get_canvas(),transform);
-
+ VisualServer::get_singleton()->viewport_set_canvas_transform(viewport, canvas->get_canvas(), transform);
}
void CanvasLayer::_update_locrotscale() {
- ofs=transform.elements[2];
- rot=transform.get_rotation();
- scale=transform.get_scale();
- locrotscale_dirty=false;
+ ofs = transform.elements[2];
+ rot = transform.get_rotation();
+ scale = transform.get_scale();
+ locrotscale_dirty = false;
}
-
-void CanvasLayer::set_offset(const Vector2& p_offset) {
+void CanvasLayer::set_offset(const Vector2 &p_offset) {
if (locrotscale_dirty)
_update_locrotscale();
- ofs=p_offset;
+ ofs = p_offset;
_update_xform();
-
}
Vector2 CanvasLayer::get_offset() const {
if (locrotscale_dirty)
- const_cast<CanvasLayer*>(this)->_update_locrotscale();
+ const_cast<CanvasLayer *>(this)->_update_locrotscale();
return ofs;
}
-
void CanvasLayer::set_rotation(real_t p_radians) {
if (locrotscale_dirty)
_update_locrotscale();
-
- rot=p_radians;
+ rot = p_radians;
_update_xform();
-
}
real_t CanvasLayer::get_rotation() const {
if (locrotscale_dirty)
- const_cast<CanvasLayer*>(this)->_update_locrotscale();
+ const_cast<CanvasLayer *>(this)->_update_locrotscale();
return rot;
}
@@ -137,26 +128,23 @@ real_t CanvasLayer::_get_rotationd() const {
return get_rotationd();
}
-void CanvasLayer::set_scale(const Vector2& p_scale) {
+void CanvasLayer::set_scale(const Vector2 &p_scale) {
if (locrotscale_dirty)
_update_locrotscale();
- scale=p_scale;
+ scale = p_scale;
_update_xform();
-
}
Vector2 CanvasLayer::get_scale() const {
if (locrotscale_dirty)
- const_cast<CanvasLayer*>(this)->_update_locrotscale();
+ const_cast<CanvasLayer *>(this)->_update_locrotscale();
return scale;
}
-
-
Ref<World2D> CanvasLayer::get_world_2d() const {
return canvas;
@@ -164,30 +152,28 @@ Ref<World2D> CanvasLayer::get_world_2d() const {
void CanvasLayer::_notification(int p_what) {
- switch(p_what) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (custom_viewport && ObjectDB::get_instance(custom_viewport_id)) {
- vp=custom_viewport;
+ vp = custom_viewport;
} else {
- vp=Node::get_viewport();
-
+ vp = Node::get_viewport();
}
ERR_FAIL_COND(!vp);
- viewport=vp->get_viewport_rid();
-
- VisualServer::get_singleton()->viewport_attach_canvas(viewport,canvas->get_canvas());
- VisualServer::get_singleton()->viewport_set_canvas_layer(viewport,canvas->get_canvas(),layer);
- VisualServer::get_singleton()->viewport_set_canvas_transform(viewport,canvas->get_canvas(),transform);
+ viewport = vp->get_viewport_rid();
+ VisualServer::get_singleton()->viewport_attach_canvas(viewport, canvas->get_canvas());
+ VisualServer::get_singleton()->viewport_set_canvas_layer(viewport, canvas->get_canvas(), layer);
+ VisualServer::get_singleton()->viewport_set_canvas_transform(viewport, canvas->get_canvas(), transform);
} break;
case NOTIFICATION_EXIT_TREE: {
- VisualServer::get_singleton()->viewport_remove_canvas(viewport,canvas->get_canvas());
- viewport=RID();
+ VisualServer::get_singleton()->viewport_remove_canvas(viewport, canvas->get_canvas());
+ viewport = RID();
} break;
}
@@ -196,14 +182,12 @@ void CanvasLayer::_notification(int p_what) {
Size2 CanvasLayer::get_viewport_size() const {
if (!is_inside_tree())
- return Size2(1,1);
-
+ return Size2(1, 1);
Rect2 r = vp->get_visible_rect();
return r.size;
}
-
RID CanvasLayer::get_viewport() const {
return viewport;
@@ -212,42 +196,40 @@ RID CanvasLayer::get_viewport() const {
void CanvasLayer::set_custom_viewport(Node *p_viewport) {
ERR_FAIL_NULL(p_viewport);
if (is_inside_tree()) {
- VisualServer::get_singleton()->viewport_remove_canvas(viewport,canvas->get_canvas());
- viewport=RID();
+ VisualServer::get_singleton()->viewport_remove_canvas(viewport, canvas->get_canvas());
+ viewport = RID();
}
- custom_viewport=p_viewport->cast_to<Viewport>();
+ custom_viewport = p_viewport->cast_to<Viewport>();
if (custom_viewport) {
- custom_viewport_id=custom_viewport->get_instance_ID();
+ custom_viewport_id = custom_viewport->get_instance_ID();
} else {
- custom_viewport_id=0;
+ custom_viewport_id = 0;
}
if (is_inside_tree()) {
-
if (custom_viewport)
- vp=custom_viewport;
+ vp = custom_viewport;
else
- vp=Node::get_viewport();
+ vp = Node::get_viewport();
viewport = vp->get_viewport_rid();
- VisualServer::get_singleton()->viewport_attach_canvas(viewport,canvas->get_canvas());
- VisualServer::get_singleton()->viewport_set_canvas_layer(viewport,canvas->get_canvas(),layer);
- VisualServer::get_singleton()->viewport_set_canvas_transform(viewport,canvas->get_canvas(),transform);
+ VisualServer::get_singleton()->viewport_attach_canvas(viewport, canvas->get_canvas());
+ VisualServer::get_singleton()->viewport_set_canvas_layer(viewport, canvas->get_canvas(), layer);
+ VisualServer::get_singleton()->viewport_set_canvas_transform(viewport, canvas->get_canvas(), transform);
}
-
}
-Node* CanvasLayer::get_custom_viewport() const {
+Node *CanvasLayer::get_custom_viewport() const {
return custom_viewport;
}
void CanvasLayer::reset_sort_index() {
- sort_index=0;
+ sort_index = 0;
}
int CanvasLayer::get_sort_index() {
@@ -255,55 +237,52 @@ int CanvasLayer::get_sort_index() {
return sort_index++;
}
-
void CanvasLayer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_layer", "layer"), &CanvasLayer::set_layer);
+ ClassDB::bind_method(D_METHOD("get_layer"), &CanvasLayer::get_layer);
- ClassDB::bind_method(D_METHOD("set_layer","layer"),&CanvasLayer::set_layer);
- ClassDB::bind_method(D_METHOD("get_layer"),&CanvasLayer::get_layer);
+ ClassDB::bind_method(D_METHOD("set_transform", "transform"), &CanvasLayer::set_transform);
+ ClassDB::bind_method(D_METHOD("get_transform"), &CanvasLayer::get_transform);
- ClassDB::bind_method(D_METHOD("set_transform","transform"),&CanvasLayer::set_transform);
- ClassDB::bind_method(D_METHOD("get_transform"),&CanvasLayer::get_transform);
+ ClassDB::bind_method(D_METHOD("set_offset", "offset"), &CanvasLayer::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset"), &CanvasLayer::get_offset);
- ClassDB::bind_method(D_METHOD("set_offset","offset"),&CanvasLayer::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset"),&CanvasLayer::get_offset);
+ ClassDB::bind_method(D_METHOD("set_rotation", "radians"), &CanvasLayer::set_rotation);
+ ClassDB::bind_method(D_METHOD("get_rotation"), &CanvasLayer::get_rotation);
- ClassDB::bind_method(D_METHOD("set_rotation","radians"),&CanvasLayer::set_rotation);
- ClassDB::bind_method(D_METHOD("get_rotation"),&CanvasLayer::get_rotation);
-
- ClassDB::bind_method(D_METHOD("set_rotationd","degrees"),&CanvasLayer::set_rotationd);
- ClassDB::bind_method(D_METHOD("get_rotationd"),&CanvasLayer::get_rotationd);
+ ClassDB::bind_method(D_METHOD("set_rotationd", "degrees"), &CanvasLayer::set_rotationd);
+ ClassDB::bind_method(D_METHOD("get_rotationd"), &CanvasLayer::get_rotationd);
// TODO: Obsolete those two methods (old name) properly (GH-4397)
- ClassDB::bind_method(D_METHOD("_set_rotationd","degrees"),&CanvasLayer::_set_rotationd);
- ClassDB::bind_method(D_METHOD("_get_rotationd"),&CanvasLayer::_get_rotationd);
+ ClassDB::bind_method(D_METHOD("_set_rotationd", "degrees"), &CanvasLayer::_set_rotationd);
+ ClassDB::bind_method(D_METHOD("_get_rotationd"), &CanvasLayer::_get_rotationd);
- ClassDB::bind_method(D_METHOD("set_scale","scale"),&CanvasLayer::set_scale);
- ClassDB::bind_method(D_METHOD("get_scale"),&CanvasLayer::get_scale);
+ ClassDB::bind_method(D_METHOD("set_scale", "scale"), &CanvasLayer::set_scale);
+ ClassDB::bind_method(D_METHOD("get_scale"), &CanvasLayer::get_scale);
- ClassDB::bind_method(D_METHOD("set_custom_viewport","viewport:Viewport"),&CanvasLayer::set_custom_viewport);
- ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"),&CanvasLayer::get_custom_viewport);
+ ClassDB::bind_method(D_METHOD("set_custom_viewport", "viewport:Viewport"), &CanvasLayer::set_custom_viewport);
+ ClassDB::bind_method(D_METHOD("get_custom_viewport:Viewport"), &CanvasLayer::get_custom_viewport);
- ClassDB::bind_method(D_METHOD("get_world_2d:World2D"),&CanvasLayer::get_world_2d);
+ ClassDB::bind_method(D_METHOD("get_world_2d:World2D"), &CanvasLayer::get_world_2d);
//ClassDB::bind_method(D_METHOD("get_viewport"),&CanvasLayer::get_viewport);
- ADD_PROPERTY( PropertyInfo(Variant::INT,"layer",PROPERTY_HINT_RANGE,"-128,128,1"),"set_layer","get_layer") ;
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "layer", PROPERTY_HINT_RANGE, "-128,128,1"), "set_layer", "get_layer");
//ADD_PROPERTY( PropertyInfo(Variant::MATRIX32,"transform",PROPERTY_HINT_RANGE),"set_transform","get_transform") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"offset"),"set_offset","get_offset") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"rotation"),"set_rotationd","get_rotationd") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"scale"),"set_scale","get_scale") ;
-
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "offset"), "set_offset", "get_offset");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "rotation"), "set_rotationd", "get_rotationd");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "scale"), "set_scale", "get_scale");
}
CanvasLayer::CanvasLayer() {
- vp=NULL;
- scale=Vector2(1,1);
- rot=0;
- locrotscale_dirty=false;
- layer=1;
- canvas = Ref<World2D>( memnew(World2D) );
- custom_viewport=NULL;
- custom_viewport_id=0;
- sort_index=0;
+ vp = NULL;
+ scale = Vector2(1, 1);
+ rot = 0;
+ locrotscale_dirty = false;
+ layer = 1;
+ canvas = Ref<World2D>(memnew(World2D));
+ custom_viewport = NULL;
+ custom_viewport_id = 0;
+ sort_index = 0;
}
diff --git a/scene/main/canvas_layer.h b/scene/main/canvas_layer.h
index 8efbbd5a05..26d21e3a0f 100644
--- a/scene/main/canvas_layer.h
+++ b/scene/main/canvas_layer.h
@@ -32,11 +32,10 @@
#include "scene/main/node.h"
#include "scene/resources/world_2d.h"
-
class Viewport;
class CanvasLayer : public Node {
- GDCLASS( CanvasLayer, Node );
+ GDCLASS(CanvasLayer, Node);
bool locrotscale_dirty;
Vector2 ofs;
@@ -61,20 +60,18 @@ class CanvasLayer : public Node {
void _update_xform();
void _update_locrotscale();
-
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
void set_layer(int p_xform);
int get_layer() const;
- void set_transform(const Transform2D& p_xform);
+ void set_transform(const Transform2D &p_xform);
Transform2D get_transform() const;
- void set_offset(const Vector2& p_offset);
+ void set_offset(const Vector2 &p_offset);
Vector2 get_offset() const;
void set_rotation(real_t p_radians);
@@ -83,7 +80,7 @@ public:
void set_rotationd(real_t p_degrees);
real_t get_rotationd() const;
- void set_scale(const Size2& p_scale);
+ void set_scale(const Size2 &p_scale);
Size2 get_scale() const;
Ref<World2D> get_world_2d() const;
@@ -93,7 +90,7 @@ public:
RID get_viewport() const;
void set_custom_viewport(Node *p_viewport);
- Node* get_custom_viewport() const;
+ Node *get_custom_viewport() const;
void reset_sort_index();
int get_sort_index();
diff --git a/scene/main/http_request.cpp b/scene/main/http_request.cpp
index 77b08fd58b..38ee03ab47 100644
--- a/scene/main/http_request.cpp
+++ b/scene/main/http_request.cpp
@@ -28,41 +28,39 @@
/*************************************************************************/
#include "http_request.h"
-void HTTPRequest::_redirect_request(const String& p_new_url) {
-
-
+void HTTPRequest::_redirect_request(const String &p_new_url) {
}
Error HTTPRequest::_request() {
//print_line("Requesting:\n\tURL: "+url+"\n\tString: "+request_string+"\n\tPort: "+itos(port)+"\n\tSSL: "+itos(use_ssl)+"\n\tValidate SSL: "+itos(validate_ssl));
- return client->connect_to_host(url,port,use_ssl,validate_ssl);
+ return client->connect_to_host(url, port, use_ssl, validate_ssl);
}
-Error HTTPRequest::_parse_url(const String& p_url) {
+Error HTTPRequest::_parse_url(const String &p_url) {
- url=p_url;
- use_ssl=false;
+ url = p_url;
+ use_ssl = false;
- request_string="";
- port=80;
- request_sent=false;
- got_response=false;
- body_len=-1;
+ request_string = "";
+ port = 80;
+ request_sent = false;
+ got_response = false;
+ body_len = -1;
body.resize(0);
- downloaded=0;
- redirections=0;
+ downloaded = 0;
+ redirections = 0;
//print_line("1 url: "+url);
if (url.begins_with("http://")) {
- url=url.substr(7,url.length()-7);
+ url = url.substr(7, url.length() - 7);
//print_line("no SSL");
} else if (url.begins_with("https://")) {
- url=url.substr(8,url.length()-8);
- use_ssl=true;
- port=443;
+ url = url.substr(8, url.length() - 8);
+ use_ssl = true;
+ port = 443;
//print_line("yes SSL");
} else {
ERR_EXPLAIN("Malformed URL");
@@ -73,22 +71,22 @@ Error HTTPRequest::_parse_url(const String& p_url) {
int slash_pos = url.find("/");
- if (slash_pos!=-1) {
- request_string=url.substr(slash_pos,url.length());
- url=url.substr(0,slash_pos);
+ if (slash_pos != -1) {
+ request_string = url.substr(slash_pos, url.length());
+ url = url.substr(0, slash_pos);
//print_line("request string: "+request_string);
} else {
- request_string="/";
+ request_string = "/";
//print_line("no request");
}
//print_line("3 url: "+url);
int colon_pos = url.find(":");
- if (colon_pos!=-1) {
- port=url.substr(colon_pos+1,url.length()).to_int();
- url=url.substr(0,colon_pos);
- ERR_FAIL_COND_V(port<1 || port > 65535,ERR_INVALID_PARAMETER);
+ if (colon_pos != -1) {
+ port = url.substr(colon_pos + 1, url.length()).to_int();
+ url = url.substr(0, colon_pos);
+ ERR_FAIL_COND_V(port < 1 || port > 65535, ERR_INVALID_PARAMETER);
}
//print_line("4 url: "+url);
@@ -96,79 +94,76 @@ Error HTTPRequest::_parse_url(const String& p_url) {
return OK;
}
-Error HTTPRequest::request(const String& p_url, const Vector<String>& p_custom_headers, bool p_ssl_validate_domain, HTTPClient::Method p_method, const String& p_request_data) {
+Error HTTPRequest::request(const String &p_url, const Vector<String> &p_custom_headers, bool p_ssl_validate_domain, HTTPClient::Method p_method, const String &p_request_data) {
- ERR_FAIL_COND_V(!is_inside_tree(),ERR_UNCONFIGURED);
- if ( requesting ) {
+ ERR_FAIL_COND_V(!is_inside_tree(), ERR_UNCONFIGURED);
+ if (requesting) {
ERR_EXPLAIN("HTTPRequest is processing a request. Wait for completion or cancel it before attempting a new one.");
ERR_FAIL_V(ERR_BUSY);
}
- method=p_method;
+ method = p_method;
Error err = _parse_url(p_url);
if (err)
return err;
- validate_ssl=p_ssl_validate_domain;
+ validate_ssl = p_ssl_validate_domain;
- bool has_user_agent=false;
- bool has_accept=false;
- headers=p_custom_headers;
+ bool has_user_agent = false;
+ bool has_accept = false;
+ headers = p_custom_headers;
request_data = p_request_data;
- for(int i=0;i<headers.size();i++) {
+ for (int i = 0; i < headers.size(); i++) {
- if (headers[i].findn("user-agent:")==0)
- has_user_agent=true;
- if (headers[i].findn("Accept:")==0)
- has_accept=true;
+ if (headers[i].findn("user-agent:") == 0)
+ has_user_agent = true;
+ if (headers[i].findn("Accept:") == 0)
+ has_accept = true;
}
if (!has_user_agent) {
- headers.push_back("User-Agent: GodotEngine/"+String(VERSION_MKSTRING)+" ("+OS::get_singleton()->get_name()+")");
+ headers.push_back("User-Agent: GodotEngine/" + String(VERSION_MKSTRING) + " (" + OS::get_singleton()->get_name() + ")");
}
if (!has_accept) {
headers.push_back("Accept: */*");
}
- requesting=true;
+ requesting = true;
if (use_threads) {
- thread_done=false;
- thread_request_quit=false;
+ thread_done = false;
+ thread_request_quit = false;
client->set_blocking_mode(true);
- thread=Thread::create(_thread_func,this);
+ thread = Thread::create(_thread_func, this);
} else {
client->set_blocking_mode(false);
err = _request();
- if (err!=OK) {
- call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
+ if (err != OK) {
+ call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
return ERR_CANT_CONNECT;
}
set_process_internal(true);
-
}
-
return OK;
}
-
void HTTPRequest::_thread_func(void *p_userdata) {
- HTTPRequest *hr = (HTTPRequest*)p_userdata;
+ HTTPRequest *hr = (HTTPRequest *)p_userdata;
Error err = hr->_request();
- if (err!=OK) {
- hr->call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
+ if (err != OK) {
+ hr->call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
} else {
- while(!hr->thread_request_quit) {
+ while (!hr->thread_request_quit) {
bool exit = hr->_update_connection();
if (exit)
@@ -177,7 +172,7 @@ void HTTPRequest::_thread_func(void *p_userdata) {
}
}
- hr->thread_done=true;
+ hr->thread_done = true;
}
void HTTPRequest::cancel_request() {
@@ -188,90 +183,88 @@ void HTTPRequest::cancel_request() {
if (!use_threads) {
set_process_internal(false);
} else {
- thread_request_quit=true;
+ thread_request_quit = true;
Thread::wait_to_finish(thread);
memdelete(thread);
- thread=NULL;
+ thread = NULL;
}
if (file) {
memdelete(file);
- file=NULL;
+ file = NULL;
}
client->close();
body.resize(0);
//downloaded=0;
- got_response=false;
- response_code=-1;
+ got_response = false;
+ response_code = -1;
//body_len=-1;
- request_sent=false;
- requesting=false;
+ request_sent = false;
+ requesting = false;
}
-
bool HTTPRequest::_handle_response(bool *ret_value) {
if (!client->has_response()) {
- call_deferred("_request_done",RESULT_NO_RESPONSE,0,PoolStringArray(),PoolByteArray());
- *ret_value=true;
+ call_deferred("_request_done", RESULT_NO_RESPONSE, 0, PoolStringArray(), PoolByteArray());
+ *ret_value = true;
return true;
}
- got_response=true;
- response_code=client->get_response_code();
+ got_response = true;
+ response_code = client->get_response_code();
List<String> rheaders;
client->get_response_headers(&rheaders);
response_headers.resize(0);
- downloaded=0;
- for (List<String>::Element *E=rheaders.front();E;E=E->next()) {
+ downloaded = 0;
+ for (List<String>::Element *E = rheaders.front(); E; E = E->next()) {
//print_line("HEADER: "+E->get());
response_headers.push_back(E->get());
}
- if (response_code==301 || response_code==302) {
+ if (response_code == 301 || response_code == 302) {
//redirect
- if (max_redirects>=0 && redirections>=max_redirects) {
+ if (max_redirects >= 0 && redirections >= max_redirects) {
- call_deferred("_request_done",RESULT_REDIRECT_LIMIT_REACHED,response_code,response_headers,PoolByteArray());
- *ret_value=true;
+ call_deferred("_request_done", RESULT_REDIRECT_LIMIT_REACHED, response_code, response_headers, PoolByteArray());
+ *ret_value = true;
return true;
}
String new_request;
- for (List<String>::Element *E=rheaders.front();E;E=E->next()) {
- if (E->get().findn("Location: ")!=-1) {
- new_request=E->get().substr(9,E->get().length()).strip_edges();
+ for (List<String>::Element *E = rheaders.front(); E; E = E->next()) {
+ if (E->get().findn("Location: ") != -1) {
+ new_request = E->get().substr(9, E->get().length()).strip_edges();
}
}
//print_line("NEW LOCATION: "+new_request);
- if (new_request!="") {
+ if (new_request != "") {
//process redirect
client->close();
- int new_redirs=redirections+1; //because _request() will clear it
+ int new_redirs = redirections + 1; //because _request() will clear it
Error err;
if (new_request.begins_with("http")) {
//new url, request all again
- err=_parse_url(new_request);
+ err = _parse_url(new_request);
} else {
- request_string=new_request;
+ request_string = new_request;
}
err = _request();
//print_line("new connection: "+itos(err));
- if (err==OK) {
- request_sent=false;
- got_response=false;
- body_len=-1;
+ if (err == OK) {
+ request_sent = false;
+ got_response = false;
+ body_len = -1;
body.resize(0);
- downloaded=0;
- redirections=new_redirs;
- *ret_value=false;
+ downloaded = 0;
+ redirections = new_redirs;
+ *ret_value = false;
return true;
-
}
}
}
@@ -279,12 +272,11 @@ bool HTTPRequest::_handle_response(bool *ret_value) {
return false;
}
-
bool HTTPRequest::_update_connection() {
- switch( client->get_status() ) {
+ switch (client->get_status()) {
case HTTPClient::STATUS_DISCONNECTED: {
- call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
+ call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
return true; //end it, since it's doing something
} break;
case HTTPClient::STATUS_RESOLVING: {
@@ -293,7 +285,7 @@ bool HTTPRequest::_update_connection() {
return false;
} break;
case HTTPClient::STATUS_CANT_RESOLVE: {
- call_deferred("_request_done",RESULT_CANT_RESOLVE,0,PoolStringArray(),PoolByteArray());
+ call_deferred("_request_done", RESULT_CANT_RESOLVE, 0, PoolStringArray(), PoolByteArray());
return true;
} break;
@@ -304,7 +296,7 @@ bool HTTPRequest::_update_connection() {
} break; //connecting to ip
case HTTPClient::STATUS_CANT_CONNECT: {
- call_deferred("_request_done",RESULT_CANT_CONNECT,0,PoolStringArray(),PoolByteArray());
+ call_deferred("_request_done", RESULT_CANT_CONNECT, 0, PoolStringArray(), PoolByteArray());
return true;
} break;
@@ -321,30 +313,28 @@ bool HTTPRequest::_update_connection() {
if (_handle_response(&ret_value))
return ret_value;
-
- call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,PoolByteArray());
+ call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
return true;
}
- if (got_response && body_len<0) {
+ if (got_response && body_len < 0) {
//chunked transfer is done
- call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,body);
+ call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
return true;
-
}
- call_deferred("_request_done",RESULT_CHUNKED_BODY_SIZE_MISMATCH,response_code,response_headers,PoolByteArray());
+ call_deferred("_request_done", RESULT_CHUNKED_BODY_SIZE_MISMATCH, response_code, response_headers, PoolByteArray());
return true;
//request migh have been done
} else {
//did not request yet, do request
- Error err = client->request(method,request_string,headers,request_data);
- if (err!=OK) {
- call_deferred("_request_done",RESULT_CONNECTION_ERROR,0,PoolStringArray(),PoolByteArray());
+ Error err = client->request(method, request_string, headers, request_data);
+ if (err != OK) {
+ call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
return true;
}
- request_sent=true;
+ request_sent = true;
return false;
}
} break; //connected: { } break requests only accepted here
@@ -358,67 +348,64 @@ bool HTTPRequest::_update_connection() {
if (!got_response) {
-
bool ret_value;
if (_handle_response(&ret_value))
return ret_value;
- if (!client->is_response_chunked() && client->get_response_body_length()==0) {
+ if (!client->is_response_chunked() && client->get_response_body_length() == 0) {
- call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,PoolByteArray());
+ call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, PoolByteArray());
return true;
}
-
if (client->is_response_chunked()) {
- body_len=-1; //no body len because chunked, change your webserver configuration if you want body len
+ body_len = -1; //no body len because chunked, change your webserver configuration if you want body len
} else {
- body_len=client->get_response_body_length();
+ body_len = client->get_response_body_length();
- if (body_size_limit>=0 && body_len>body_size_limit) {
- call_deferred("_request_done",RESULT_BODY_SIZE_LIMIT_EXCEEDED,response_code,response_headers,PoolByteArray());
+ if (body_size_limit >= 0 && body_len > body_size_limit) {
+ call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
return true;
}
}
- if (download_to_file!=String()) {
- file=FileAccess::open(download_to_file,FileAccess::WRITE);
+ if (download_to_file != String()) {
+ file = FileAccess::open(download_to_file, FileAccess::WRITE);
if (!file) {
- call_deferred("_request_done",RESULT_DOWNLOAD_FILE_CANT_OPEN,response_code,response_headers,PoolByteArray());
+ call_deferred("_request_done", RESULT_DOWNLOAD_FILE_CANT_OPEN, response_code, response_headers, PoolByteArray());
return true;
}
}
}
-
//print_line("BODY: "+itos(body.size()));
client->poll();
PoolByteArray chunk = client->read_response_body_chunk();
- downloaded+=chunk.size();
+ downloaded += chunk.size();
if (file) {
- PoolByteArray::Read r=chunk.read();
- file->store_buffer(r.ptr(),chunk.size());
- if (file->get_error()!=OK) {
- call_deferred("_request_done",RESULT_DOWNLOAD_FILE_WRITE_ERROR,response_code,response_headers,PoolByteArray());
+ PoolByteArray::Read r = chunk.read();
+ file->store_buffer(r.ptr(), chunk.size());
+ if (file->get_error() != OK) {
+ call_deferred("_request_done", RESULT_DOWNLOAD_FILE_WRITE_ERROR, response_code, response_headers, PoolByteArray());
return true;
}
} else {
body.append_array(chunk);
}
- if (body_size_limit>=0 && downloaded>body_size_limit) {
- call_deferred("_request_done",RESULT_BODY_SIZE_LIMIT_EXCEEDED,response_code,response_headers,PoolByteArray());
+ if (body_size_limit >= 0 && downloaded > body_size_limit) {
+ call_deferred("_request_done", RESULT_BODY_SIZE_LIMIT_EXCEEDED, response_code, response_headers, PoolByteArray());
return true;
}
- if (body_len>=0) {
+ if (body_len >= 0) {
- if (downloaded==body_len) {
- call_deferred("_request_done",RESULT_SUCCESS,response_code,response_headers,body);
+ if (downloaded == body_len) {
+ call_deferred("_request_done", RESULT_SUCCESS, response_code, response_headers, body);
return true;
}
/*if (body.size()>=body_len) {
@@ -431,31 +418,27 @@ bool HTTPRequest::_update_connection() {
} break; // request resulted in body: { } break which must be read
case HTTPClient::STATUS_CONNECTION_ERROR: {
- call_deferred("_request_done",RESULT_CONNECTION_ERROR,0,PoolStringArray(),PoolByteArray());
+ call_deferred("_request_done", RESULT_CONNECTION_ERROR, 0, PoolStringArray(), PoolByteArray());
return true;
} break;
case HTTPClient::STATUS_SSL_HANDSHAKE_ERROR: {
- call_deferred("_request_done",RESULT_SSL_HANDSHAKE_ERROR,0,PoolStringArray(),PoolByteArray());
+ call_deferred("_request_done", RESULT_SSL_HANDSHAKE_ERROR, 0, PoolStringArray(), PoolByteArray());
return true;
} break;
-
}
ERR_FAIL_V(false);
}
-
-void HTTPRequest::_request_done(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data) {
-
+void HTTPRequest::_request_done(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data) {
cancel_request();
- emit_signal("request_completed",p_status,p_code,headers,p_data);
+ emit_signal("request_completed", p_status, p_code, headers, p_data);
}
-
void HTTPRequest::_notification(int p_what) {
- if (p_what==NOTIFICATION_INTERNAL_PROCESS) {
+ if (p_what == NOTIFICATION_INTERNAL_PROCESS) {
if (use_threads)
return;
@@ -467,18 +450,17 @@ void HTTPRequest::_notification(int p_what) {
}
}
- if (p_what==NOTIFICATION_EXIT_TREE) {
+ if (p_what == NOTIFICATION_EXIT_TREE) {
if (requesting) {
cancel_request();
}
}
-
}
void HTTPRequest::set_use_threads(bool p_use) {
- ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
- use_threads=p_use;
+ ERR_FAIL_COND(status != HTTPClient::STATUS_DISCONNECTED);
+ use_threads = p_use;
}
bool HTTPRequest::is_using_threads() const {
@@ -488,9 +470,9 @@ bool HTTPRequest::is_using_threads() const {
void HTTPRequest::set_body_size_limit(int p_bytes) {
- ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
+ ERR_FAIL_COND(status != HTTPClient::STATUS_DISCONNECTED);
- body_size_limit=p_bytes;
+ body_size_limit = p_bytes;
}
int HTTPRequest::get_body_size_limit() const {
@@ -498,12 +480,11 @@ int HTTPRequest::get_body_size_limit() const {
return body_size_limit;
}
+void HTTPRequest::set_download_file(const String &p_file) {
-void HTTPRequest::set_download_file(const String& p_file) {
+ ERR_FAIL_COND(status != HTTPClient::STATUS_DISCONNECTED);
- ERR_FAIL_COND( status!=HTTPClient::STATUS_DISCONNECTED );
-
- download_to_file=p_file;
+ download_to_file = p_file;
}
String HTTPRequest::get_download_file() const {
@@ -516,10 +497,10 @@ HTTPClient::Status HTTPRequest::get_http_client_status() const {
void HTTPRequest::set_max_redirects(int p_max) {
- max_redirects=p_max;
+ max_redirects = p_max;
}
-int HTTPRequest::get_max_redirects() const{
+int HTTPRequest::get_max_redirects() const {
return max_redirects;
}
@@ -528,80 +509,76 @@ int HTTPRequest::get_downloaded_bytes() const {
return downloaded;
}
-int HTTPRequest::get_body_size() const{
+int HTTPRequest::get_body_size() const {
return body_len;
}
-
void HTTPRequest::_bind_methods() {
- ClassDB::bind_method(D_METHOD("request","url","custom_headers","ssl_validate_domain","method","request_data"),&HTTPRequest::request,DEFVAL(PoolStringArray()),DEFVAL(true),DEFVAL(HTTPClient::METHOD_GET),DEFVAL(String()));
- ClassDB::bind_method(D_METHOD("cancel_request"),&HTTPRequest::cancel_request);
+ ClassDB::bind_method(D_METHOD("request", "url", "custom_headers", "ssl_validate_domain", "method", "request_data"), &HTTPRequest::request, DEFVAL(PoolStringArray()), DEFVAL(true), DEFVAL(HTTPClient::METHOD_GET), DEFVAL(String()));
+ ClassDB::bind_method(D_METHOD("cancel_request"), &HTTPRequest::cancel_request);
- ClassDB::bind_method(D_METHOD("get_http_client_status"),&HTTPRequest::get_http_client_status);
+ ClassDB::bind_method(D_METHOD("get_http_client_status"), &HTTPRequest::get_http_client_status);
- ClassDB::bind_method(D_METHOD("set_use_threads","enable"),&HTTPRequest::set_use_threads);
- ClassDB::bind_method(D_METHOD("is_using_threads"),&HTTPRequest::is_using_threads);
+ ClassDB::bind_method(D_METHOD("set_use_threads", "enable"), &HTTPRequest::set_use_threads);
+ ClassDB::bind_method(D_METHOD("is_using_threads"), &HTTPRequest::is_using_threads);
- ClassDB::bind_method(D_METHOD("set_body_size_limit","bytes"),&HTTPRequest::set_body_size_limit);
- ClassDB::bind_method(D_METHOD("get_body_size_limit"),&HTTPRequest::get_body_size_limit);
+ ClassDB::bind_method(D_METHOD("set_body_size_limit", "bytes"), &HTTPRequest::set_body_size_limit);
+ ClassDB::bind_method(D_METHOD("get_body_size_limit"), &HTTPRequest::get_body_size_limit);
- ClassDB::bind_method(D_METHOD("set_max_redirects","amount"),&HTTPRequest::set_max_redirects);
- ClassDB::bind_method(D_METHOD("get_max_redirects"),&HTTPRequest::get_max_redirects);
+ ClassDB::bind_method(D_METHOD("set_max_redirects", "amount"), &HTTPRequest::set_max_redirects);
+ ClassDB::bind_method(D_METHOD("get_max_redirects"), &HTTPRequest::get_max_redirects);
- ClassDB::bind_method(D_METHOD("set_download_file","path"),&HTTPRequest::set_download_file);
- ClassDB::bind_method(D_METHOD("get_download_file"),&HTTPRequest::get_download_file);
+ ClassDB::bind_method(D_METHOD("set_download_file", "path"), &HTTPRequest::set_download_file);
+ ClassDB::bind_method(D_METHOD("get_download_file"), &HTTPRequest::get_download_file);
- ClassDB::bind_method(D_METHOD("get_downloaded_bytes"),&HTTPRequest::get_downloaded_bytes);
- ClassDB::bind_method(D_METHOD("get_body_size"),&HTTPRequest::get_body_size);
+ ClassDB::bind_method(D_METHOD("get_downloaded_bytes"), &HTTPRequest::get_downloaded_bytes);
+ ClassDB::bind_method(D_METHOD("get_body_size"), &HTTPRequest::get_body_size);
- ClassDB::bind_method(D_METHOD("_redirect_request"),&HTTPRequest::_redirect_request);
- ClassDB::bind_method(D_METHOD("_request_done"),&HTTPRequest::_request_done);
+ ClassDB::bind_method(D_METHOD("_redirect_request"), &HTTPRequest::_redirect_request);
+ ClassDB::bind_method(D_METHOD("_request_done"), &HTTPRequest::_request_done);
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_threads"),"set_use_threads","is_using_threads");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"body_size_limit",PROPERTY_HINT_RANGE,"-1,2000000000"),"set_body_size_limit","get_body_size_limit");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"max_redirects",PROPERTY_HINT_RANGE,"-1,1024"),"set_max_redirects","get_max_redirects");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_threads"), "set_use_threads", "is_using_threads");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "body_size_limit", PROPERTY_HINT_RANGE, "-1,2000000000"), "set_body_size_limit", "get_body_size_limit");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "max_redirects", PROPERTY_HINT_RANGE, "-1,1024"), "set_max_redirects", "get_max_redirects");
- ADD_SIGNAL(MethodInfo("request_completed",PropertyInfo(Variant::INT,"result"),PropertyInfo(Variant::INT,"response_code"),PropertyInfo(Variant::POOL_STRING_ARRAY,"headers"),PropertyInfo(Variant::POOL_BYTE_ARRAY,"body")));
+ ADD_SIGNAL(MethodInfo("request_completed", PropertyInfo(Variant::INT, "result"), PropertyInfo(Variant::INT, "response_code"), PropertyInfo(Variant::POOL_STRING_ARRAY, "headers"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "body")));
- BIND_CONSTANT( RESULT_SUCCESS );
+ BIND_CONSTANT(RESULT_SUCCESS);
//BIND_CONSTANT( RESULT_NO_BODY );
- BIND_CONSTANT( RESULT_CHUNKED_BODY_SIZE_MISMATCH );
- BIND_CONSTANT( RESULT_CANT_CONNECT );
- BIND_CONSTANT( RESULT_CANT_RESOLVE );
- BIND_CONSTANT( RESULT_CONNECTION_ERROR );
- BIND_CONSTANT( RESULT_SSL_HANDSHAKE_ERROR );
- BIND_CONSTANT( RESULT_NO_RESPONSE );
- BIND_CONSTANT( RESULT_BODY_SIZE_LIMIT_EXCEEDED );
- BIND_CONSTANT( RESULT_REQUEST_FAILED );
- BIND_CONSTANT( RESULT_DOWNLOAD_FILE_CANT_OPEN );
- BIND_CONSTANT( RESULT_DOWNLOAD_FILE_WRITE_ERROR );
- BIND_CONSTANT( RESULT_REDIRECT_LIMIT_REACHED );
-
+ BIND_CONSTANT(RESULT_CHUNKED_BODY_SIZE_MISMATCH);
+ BIND_CONSTANT(RESULT_CANT_CONNECT);
+ BIND_CONSTANT(RESULT_CANT_RESOLVE);
+ BIND_CONSTANT(RESULT_CONNECTION_ERROR);
+ BIND_CONSTANT(RESULT_SSL_HANDSHAKE_ERROR);
+ BIND_CONSTANT(RESULT_NO_RESPONSE);
+ BIND_CONSTANT(RESULT_BODY_SIZE_LIMIT_EXCEEDED);
+ BIND_CONSTANT(RESULT_REQUEST_FAILED);
+ BIND_CONSTANT(RESULT_DOWNLOAD_FILE_CANT_OPEN);
+ BIND_CONSTANT(RESULT_DOWNLOAD_FILE_WRITE_ERROR);
+ BIND_CONSTANT(RESULT_REDIRECT_LIMIT_REACHED);
}
-HTTPRequest::HTTPRequest()
-{
-
- thread=NULL;
-
- port=80;
- redirections=0;
- max_redirects=8;
- body_len=-1;
- got_response=false;
- validate_ssl=false;
- use_ssl=false;
- response_code=0;
- request_sent=false;
- requesting=false;
- client.instance();
- use_threads=false;
- thread_done=false;
- body_size_limit=-1;
- file=NULL;
- status=HTTPClient::STATUS_DISCONNECTED;
+HTTPRequest::HTTPRequest() {
+
+ thread = NULL;
+ port = 80;
+ redirections = 0;
+ max_redirects = 8;
+ body_len = -1;
+ got_response = false;
+ validate_ssl = false;
+ use_ssl = false;
+ response_code = 0;
+ request_sent = false;
+ requesting = false;
+ client.instance();
+ use_threads = false;
+ thread_done = false;
+ body_size_limit = -1;
+ file = NULL;
+ status = HTTPClient::STATUS_DISCONNECTED;
}
HTTPRequest::~HTTPRequest() {
diff --git a/scene/main/http_request.h b/scene/main/http_request.h
index a9c495fd81..2b2d7f9a38 100644
--- a/scene/main/http_request.h
+++ b/scene/main/http_request.h
@@ -29,16 +29,16 @@
#ifndef HTTPREQUEST_H
#define HTTPREQUEST_H
-#include "node.h"
#include "io/http_client.h"
+#include "node.h"
#include "os/file_access.h"
#include "os/thread.h"
class HTTPRequest : public Node {
- GDCLASS(HTTPRequest,Node);
-public:
+ GDCLASS(HTTPRequest, Node);
+public:
enum Result {
RESULT_SUCCESS,
//RESULT_NO_BODY,
@@ -57,7 +57,6 @@ public:
};
private:
-
bool requesting;
String request_string;
@@ -94,12 +93,11 @@ private:
int max_redirects;
- void _redirect_request(const String& p_new_url);
-
+ void _redirect_request(const String &p_new_url);
bool _handle_response(bool *ret_value);
- Error _parse_url(const String& p_url);
+ Error _parse_url(const String &p_url);
Error _request();
volatile bool thread_done;
@@ -107,23 +105,22 @@ private:
Thread *thread;
- void _request_done(int p_status, int p_code, const PoolStringArray& headers, const PoolByteArray& p_data);
+ void _request_done(int p_status, int p_code, const PoolStringArray &headers, const PoolByteArray &p_data);
static void _thread_func(void *p_userdata);
protected:
-
void _notification(int p_what);
static void _bind_methods();
-public:
- Error request(const String& p_url, const Vector<String>& p_custom_headers=Vector<String>(), bool p_ssl_validate_domain=true, HTTPClient::Method p_method=HTTPClient::METHOD_GET, const String& p_request_data=""); //connects to a full url and perform request
+public:
+ Error request(const String &p_url, const Vector<String> &p_custom_headers = Vector<String>(), bool p_ssl_validate_domain = true, HTTPClient::Method p_method = HTTPClient::METHOD_GET, const String &p_request_data = ""); //connects to a full url and perform request
void cancel_request();
HTTPClient::Status get_http_client_status() const;
void set_use_threads(bool p_use);
bool is_using_threads() const;
- void set_download_file(const String& p_file);
+ void set_download_file(const String &p_file);
String get_download_file() const;
void set_body_size_limit(int p_bytes);
diff --git a/scene/main/instance_placeholder.cpp b/scene/main/instance_placeholder.cpp
index 935811009b..469a5e9441 100644
--- a/scene/main/instance_placeholder.cpp
+++ b/scene/main/instance_placeholder.cpp
@@ -28,51 +28,50 @@
/*************************************************************************/
#include "instance_placeholder.h"
-#include "scene/resources/packed_scene.h"
#include "io/resource_loader.h"
+#include "scene/resources/packed_scene.h"
-bool InstancePlaceholder::_set(const StringName& p_name, const Variant& p_value) {
+bool InstancePlaceholder::_set(const StringName &p_name, const Variant &p_value) {
PropSet ps;
- ps.name=p_name;
- ps.value=p_value;
+ ps.name = p_name;
+ ps.value = p_value;
stored_values.push_back(ps);
return true;
}
-bool InstancePlaceholder::_get(const StringName& p_name,Variant &r_ret) const{
+bool InstancePlaceholder::_get(const StringName &p_name, Variant &r_ret) const {
- for (const List<PropSet>::Element *E=stored_values.front();E;E=E->next()) {
- if (E->get().name==p_name) {
- r_ret=E->get().value;
+ for (const List<PropSet>::Element *E = stored_values.front(); E; E = E->next()) {
+ if (E->get().name == p_name) {
+ r_ret = E->get().value;
return true;
}
}
return false;
}
-void InstancePlaceholder::_get_property_list( List<PropertyInfo> *p_list) const{
+void InstancePlaceholder::_get_property_list(List<PropertyInfo> *p_list) const {
- for (const List<PropSet>::Element *E=stored_values.front();E;E=E->next()) {
+ for (const List<PropSet>::Element *E = stored_values.front(); E; E = E->next()) {
PropertyInfo pi;
- pi.name=E->get().name;
- pi.type=E->get().value.get_type();
- pi.usage=PROPERTY_USAGE_STORAGE;
+ pi.name = E->get().name;
+ pi.type = E->get().value.get_type();
+ pi.usage = PROPERTY_USAGE_STORAGE;
p_list->push_back(pi);
}
}
+void InstancePlaceholder::set_instance_path(const String &p_name) {
-void InstancePlaceholder::set_instance_path(const String& p_name) {
-
- path=p_name;
+ path = p_name;
}
String InstancePlaceholder::get_instance_path() const {
return path;
}
-void InstancePlaceholder::replace_by_instance(const Ref<PackedScene> &p_custom_scene){
+void InstancePlaceholder::replace_by_instance(const Ref<PackedScene> &p_custom_scene) {
ERR_FAIL_COND(!is_inside_tree());
@@ -84,7 +83,7 @@ void InstancePlaceholder::replace_by_instance(const Ref<PackedScene> &p_custom_s
if (p_custom_scene.is_valid())
ps = p_custom_scene;
else
- ps = ResourceLoader::load(path,"PackedScene");
+ ps = ResourceLoader::load(path, "PackedScene");
if (!ps.is_valid())
return;
@@ -92,15 +91,15 @@ void InstancePlaceholder::replace_by_instance(const Ref<PackedScene> &p_custom_s
scene->set_name(get_name());
int pos = get_position_in_parent();
- for(List<PropSet>::Element *E=stored_values.front();E;E=E->next()) {
- scene->set(E->get().name,E->get().value);
+ for (List<PropSet>::Element *E = stored_values.front(); E; E = E->next()) {
+ scene->set(E->get().name, E->get().value);
}
queue_delete();
base->remove_child(this);
base->add_child(scene);
- base->move_child(scene,pos);
+ base->move_child(scene, pos);
}
Dictionary InstancePlaceholder::get_stored_values(bool p_with_order) {
@@ -108,7 +107,7 @@ Dictionary InstancePlaceholder::get_stored_values(bool p_with_order) {
Dictionary ret;
PoolStringArray order;
- for(List<PropSet>::Element *E=stored_values.front();E;E=E->next()) {
+ for (List<PropSet>::Element *E = stored_values.front(); E; E = E->next()) {
ret[E->get().name] = E->get().value;
if (p_with_order)
order.push_back(E->get().name);
@@ -122,12 +121,10 @@ Dictionary InstancePlaceholder::get_stored_values(bool p_with_order) {
void InstancePlaceholder::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_stored_values","with_order"),&InstancePlaceholder::get_stored_values,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("replace_by_instance","custom_scene:PackedScene"),&InstancePlaceholder::replace_by_instance,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("get_instance_path"),&InstancePlaceholder::get_instance_path);
+ ClassDB::bind_method(D_METHOD("get_stored_values", "with_order"), &InstancePlaceholder::get_stored_values, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("replace_by_instance", "custom_scene:PackedScene"), &InstancePlaceholder::replace_by_instance, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("get_instance_path"), &InstancePlaceholder::get_instance_path);
}
InstancePlaceholder::InstancePlaceholder() {
-
-
}
diff --git a/scene/main/instance_placeholder.h b/scene/main/instance_placeholder.h
index 069b1c9756..7900e35b00 100644
--- a/scene/main/instance_placeholder.h
+++ b/scene/main/instance_placeholder.h
@@ -35,7 +35,7 @@ class PackedScene;
class InstancePlaceholder : public Node {
- GDCLASS(InstancePlaceholder,Node);
+ GDCLASS(InstancePlaceholder, Node);
String path;
struct PropSet {
@@ -46,20 +46,19 @@ class InstancePlaceholder : public Node {
List<PropSet> stored_values;
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
- void set_instance_path(const String& p_name);
+ void set_instance_path(const String &p_name);
String get_instance_path() const;
Dictionary get_stored_values(bool p_with_order = false);
- void replace_by_instance(const Ref<PackedScene>& p_custom_scene=Ref<PackedScene>());
+ void replace_by_instance(const Ref<PackedScene> &p_custom_scene = Ref<PackedScene>());
InstancePlaceholder();
};
diff --git a/scene/main/node.cpp b/scene/main/node.cpp
index a189702894..864e26a651 100644
--- a/scene/main/node.cpp
+++ b/scene/main/node.cpp
@@ -27,75 +27,71 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "node.h"
-#include "print_string.h"
+#include "instance_placeholder.h"
+#include "io/resource_loader.h"
#include "message_queue.h"
-#include "scene/scene_string_names.h"
+#include "print_string.h"
#include "scene/resources/packed_scene.h"
-#include "io/resource_loader.h"
+#include "scene/scene_string_names.h"
#include "viewport.h"
-#include "instance_placeholder.h"
VARIANT_ENUM_CAST(Node::PauseMode);
VARIANT_ENUM_CAST(Node::NetworkMode);
VARIANT_ENUM_CAST(Node::RPCMode);
-
-
-
void Node::_notification(int p_notification) {
- switch(p_notification) {
+ switch (p_notification) {
case NOTIFICATION_PROCESS: {
if (get_script_instance()) {
- Variant time=get_process_delta_time();
- const Variant*ptr[1]={&time};
+ Variant time = get_process_delta_time();
+ const Variant *ptr[1] = { &time };
Variant::CallError err;
- get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_process,ptr,1);
+ get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_process, ptr, 1);
}
} break;
case NOTIFICATION_FIXED_PROCESS: {
if (get_script_instance()) {
- Variant time=get_fixed_process_delta_time();
- const Variant*ptr[1]={&time};
+ Variant time = get_fixed_process_delta_time();
+ const Variant *ptr[1] = { &time };
Variant::CallError err;
- get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_fixed_process,ptr,1);
+ get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_fixed_process, ptr, 1);
}
} break;
case NOTIFICATION_ENTER_TREE: {
- if (data.pause_mode==PAUSE_MODE_INHERIT) {
+ if (data.pause_mode == PAUSE_MODE_INHERIT) {
if (data.parent)
- data.pause_owner=data.parent->data.pause_owner;
+ data.pause_owner = data.parent->data.pause_owner;
else
- data.pause_owner=NULL;
+ data.pause_owner = NULL;
} else {
- data.pause_owner=this;
+ data.pause_owner = this;
}
- if (data.network_mode==NETWORK_MODE_INHERIT) {
+ if (data.network_mode == NETWORK_MODE_INHERIT) {
if (data.parent)
- data.network_owner=data.parent->data.network_owner;
+ data.network_owner = data.parent->data.network_owner;
else
- data.network_owner=NULL;
+ data.network_owner = NULL;
} else {
- data.network_owner=this;
+ data.network_owner = this;
}
-
if (data.input)
- add_to_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_input" + itos(get_viewport()->get_instance_ID()));
if (data.unhandled_input)
- add_to_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_ID()));
if (data.unhandled_key_input)
- add_to_group("_vp_unhandled_key_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_ID()));
get_tree()->node_count++;
@@ -104,25 +100,24 @@ void Node::_notification(int p_notification) {
get_tree()->node_count--;
if (data.input)
- remove_from_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
+ remove_from_group("_vp_input" + itos(get_viewport()->get_instance_ID()));
if (data.unhandled_input)
- remove_from_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
+ remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_ID()));
if (data.unhandled_key_input)
- remove_from_group("_vp_unhandled_key_input"+itos(get_viewport()->get_instance_ID()));
-
+ remove_from_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_ID()));
- data.pause_owner=NULL;
- data.network_owner=NULL;
+ data.pause_owner = NULL;
+ data.network_owner = NULL;
if (data.path_cache) {
memdelete(data.path_cache);
- data.path_cache=NULL;
+ data.path_cache = NULL;
}
} break;
case NOTIFICATION_PATH_CHANGED: {
if (data.path_cache) {
memdelete(data.path_cache);
- data.path_cache=NULL;
+ data.path_cache = NULL;
}
} break;
case NOTIFICATION_READY: {
@@ -150,19 +145,19 @@ void Node::_notification(int p_notification) {
}
Variant::CallError err;
- get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_ready,NULL,0);
+ get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_ready, NULL, 0);
}
//emit_signal(SceneStringNames::get_singleton()->enter_tree);
} break;
case NOTIFICATION_POSTINITIALIZE: {
- data.in_constructor=false;
+ data.in_constructor = false;
} break;
case NOTIFICATION_PREDELETE: {
set_owner(NULL);
- while ( data.owned.size() ) {
+ while (data.owned.size()) {
data.owned.front()->get()->set_owner(NULL);
}
@@ -173,72 +168,67 @@ void Node::_notification(int p_notification) {
}
// kill children as cleanly as possible
- while( data.children.size() ) {
+ while (data.children.size()) {
Node *child = data.children[0];
remove_child(child);
- memdelete( child );
+ memdelete(child);
}
} break;
}
}
-
void Node::_propagate_ready() {
- data.ready_notified=true;
+ data.ready_notified = true;
data.blocked++;
- for (int i=0;i<data.children.size();i++) {
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->_propagate_ready();
}
data.blocked--;
if (data.ready_first) {
notification(NOTIFICATION_READY);
- data.ready_first=false;
+ data.ready_first = false;
}
-
}
-
void Node::_propagate_enter_tree() {
// this needs to happen to all childs before any enter_tree
if (data.parent) {
- data.tree=data.parent->data.tree;
- data.depth=data.parent->data.depth+1;
+ data.tree = data.parent->data.tree;
+ data.depth = data.parent->data.depth + 1;
} else {
- data.depth=1;
+ data.depth = 1;
}
data.viewport = cast_to<Viewport>();
if (!data.viewport)
data.viewport = data.parent->data.viewport;
- data.inside_tree=true;
+ data.inside_tree = true;
- for (Map< StringName, GroupData>::Element *E=data.grouped.front();E;E=E->next()) {
- E->get().group=data.tree->add_to_group(E->key(),this);
+ for (Map<StringName, GroupData>::Element *E = data.grouped.front(); E; E = E->next()) {
+ E->get().group = data.tree->add_to_group(E->key(), this);
}
-
notification(NOTIFICATION_ENTER_TREE);
if (get_script_instance()) {
Variant::CallError err;
- get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_enter_tree,NULL,0);
+ get_script_instance()->call_multilevel_reversed(SceneStringNames::get_singleton()->_enter_tree, NULL, 0);
}
emit_signal(SceneStringNames::get_singleton()->tree_entered);
-
data.blocked++;
//block while adding children
- for (int i=0;i<data.children.size();i++) {
+ for (int i = 0; i < data.children.size(); i++) {
if (!data.children[i]->is_inside_tree()) // could have been added in enter_tree
data.children[i]->_propagate_enter_tree();
@@ -248,7 +238,7 @@ void Node::_propagate_enter_tree() {
#ifdef DEBUG_ENABLED
- if (ScriptDebugger::get_singleton() && data.filename!=String()) {
+ if (ScriptDebugger::get_singleton() && data.filename != String()) {
//used for live edit
data.tree->live_scene_edit_cache[data.filename].insert(this);
}
@@ -256,27 +246,25 @@ void Node::_propagate_enter_tree() {
// enter groups
}
-
-
void Node::_propagate_exit_tree() {
- //block while removing children
+//block while removing children
#ifdef DEBUG_ENABLED
- if (ScriptDebugger::get_singleton() && data.filename!=String()) {
+ if (ScriptDebugger::get_singleton() && data.filename != String()) {
//used for live edit
- Map<String,Set<Node*> >::Element *E=data.tree->live_scene_edit_cache.find(data.filename);
+ Map<String, Set<Node *> >::Element *E = data.tree->live_scene_edit_cache.find(data.filename);
if (E) {
E->get().erase(this);
- if (E->get().size()==0) {
+ if (E->get().size() == 0) {
data.tree->live_scene_edit_cache.erase(E);
}
}
- Map<Node*,Map<ObjectID,Node*> >::Element *F=data.tree->live_edit_remove_list.find(this);
+ Map<Node *, Map<ObjectID, Node *> >::Element *F = data.tree->live_edit_remove_list.find(this);
if (F) {
- for (Map<ObjectID,Node*>::Element*G=F->get().front();G;G=G->next()) {
+ for (Map<ObjectID, Node *>::Element *G = F->get().front(); G; G = G->next()) {
memdelete(G->get());
}
@@ -286,7 +274,7 @@ void Node::_propagate_exit_tree() {
#endif
data.blocked++;
- for (int i=data.children.size()-1;i>=0;i--) {
+ for (int i = data.children.size() - 1; i >= 0; i--) {
data.children[i]->_propagate_exit_tree();
}
@@ -296,59 +284,52 @@ void Node::_propagate_exit_tree() {
if (get_script_instance()) {
Variant::CallError err;
- get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_tree,NULL,0);
+ get_script_instance()->call_multilevel(SceneStringNames::get_singleton()->_exit_tree, NULL, 0);
}
emit_signal(SceneStringNames::get_singleton()->tree_exited);
- notification(NOTIFICATION_EXIT_TREE,true);
+ notification(NOTIFICATION_EXIT_TREE, true);
if (data.tree)
data.tree->node_removed(this);
// exit groups
- for (Map< StringName, GroupData>::Element *E=data.grouped.front();E;E=E->next()) {
- data.tree->remove_from_group(E->key(),this);
- E->get().group=NULL;
+ for (Map<StringName, GroupData>::Element *E = data.grouped.front(); E; E = E->next()) {
+ data.tree->remove_from_group(E->key(), this);
+ E->get().group = NULL;
}
-
data.viewport = NULL;
if (data.tree)
data.tree->tree_changed();
- data.inside_tree=false;
- data.ready_notified=false;
- data.tree=NULL;
- data.depth=-1;
-
+ data.inside_tree = false;
+ data.ready_notified = false;
+ data.tree = NULL;
+ data.depth = -1;
}
-
-
-
-
-void Node::move_child(Node *p_child,int p_pos) {
+void Node::move_child(Node *p_child, int p_pos) {
ERR_FAIL_NULL(p_child);
- ERR_EXPLAIN("Invalid new child position: "+itos(p_pos));
- ERR_FAIL_INDEX( p_pos, data.children.size()+1 );
+ ERR_EXPLAIN("Invalid new child position: " + itos(p_pos));
+ ERR_FAIL_INDEX(p_pos, data.children.size() + 1);
ERR_EXPLAIN("child is not a child of this node.");
- ERR_FAIL_COND(p_child->data.parent!=this);
- if (data.blocked>0) {
+ ERR_FAIL_COND(p_child->data.parent != this);
+ if (data.blocked > 0) {
ERR_EXPLAIN("Parent node is busy setting up children, move_child() failed. Consider using call_deferred(\"move_child\") instead (or \"popup\" if this is from a popup).");
- ERR_FAIL_COND(data.blocked>0);
+ ERR_FAIL_COND(data.blocked > 0);
}
-
- if (p_child->data.pos==p_pos)
+ if (p_child->data.pos == p_pos)
return; //do nothing
- int motion_from = MIN(p_pos,p_child->data.pos);
- int motion_to = MAX(p_pos,p_child->data.pos);
+ int motion_from = MIN(p_pos, p_child->data.pos);
+ int motion_to = MAX(p_pos, p_child->data.pos);
- data.children.remove( p_child->data.pos );
- data.children.insert( p_pos, p_child );
+ data.children.remove(p_child->data.pos);
+ data.children.insert(p_pos, p_child);
if (data.tree) {
data.tree->tree_changed();
@@ -356,22 +337,20 @@ void Node::move_child(Node *p_child,int p_pos) {
data.blocked++;
//new pos first
- for (int i=motion_from;i<=motion_to;i++) {
+ for (int i = motion_from; i <= motion_to; i++) {
- data.children[i]->data.pos=i;
+ data.children[i]->data.pos = i;
}
// notification second
move_child_notify(p_child);
- for (int i=motion_from;i<=motion_to;i++) {
- data.children[i]->notification( NOTIFICATION_MOVED_IN_PARENT );
-
+ for (int i = motion_from; i <= motion_to; i++) {
+ data.children[i]->notification(NOTIFICATION_MOVED_IN_PARENT);
}
- for (const Map< StringName, GroupData>::Element *E=p_child->data.grouped.front();E;E=E->next()) {
- E->get().group->changed=true;
+ for (const Map<StringName, GroupData>::Element *E = p_child->data.grouped.front(); E; E = E->next()) {
+ E->get().group->changed = true;
}
data.blocked--;
-
}
void Node::raise() {
@@ -379,8 +358,7 @@ void Node::raise() {
if (!data.parent)
return;
- data.parent->move_child(this,data.parent->data.children.size()-1);
-
+ data.parent->move_child(this, data.parent->data.children.size() - 1);
}
void Node::add_child_notify(Node *p_child) {
@@ -412,17 +390,17 @@ void Node::move_child_notify(Node *p_child) {
void Node::set_fixed_process(bool p_process) {
- if (data.fixed_process==p_process)
+ if (data.fixed_process == p_process)
return;
- data.fixed_process=p_process;
+ data.fixed_process = p_process;
if (data.fixed_process)
- add_to_group("fixed_process",false);
+ add_to_group("fixed_process", false);
else
remove_from_group("fixed_process");
- data.fixed_process=p_process;
+ data.fixed_process = p_process;
_change_notify("fixed_process");
}
@@ -433,17 +411,17 @@ bool Node::is_fixed_processing() const {
void Node::set_fixed_process_internal(bool p_process_internal) {
- if (data.fixed_process_internal==p_process_internal)
+ if (data.fixed_process_internal == p_process_internal)
return;
- data.fixed_process_internal=p_process_internal;
+ data.fixed_process_internal = p_process_internal;
if (data.fixed_process_internal)
- add_to_group("fixed_process_internal",false);
+ add_to_group("fixed_process_internal", false);
else
remove_from_group("fixed_process_internal");
- data.fixed_process_internal=p_process_internal;
+ data.fixed_process_internal = p_process_internal;
_change_notify("fixed_process_internal");
}
@@ -452,33 +430,29 @@ bool Node::is_fixed_processing_internal() const {
return data.fixed_process_internal;
}
-
void Node::set_pause_mode(PauseMode p_mode) {
- if (data.pause_mode==p_mode)
+ if (data.pause_mode == p_mode)
return;
- bool prev_inherits=data.pause_mode==PAUSE_MODE_INHERIT;
- data.pause_mode=p_mode;
+ bool prev_inherits = data.pause_mode == PAUSE_MODE_INHERIT;
+ data.pause_mode = p_mode;
if (!is_inside_tree())
return; //pointless
- if ((data.pause_mode==PAUSE_MODE_INHERIT) == prev_inherits)
+ if ((data.pause_mode == PAUSE_MODE_INHERIT) == prev_inherits)
return; ///nothing changed
- Node *owner=NULL;
+ Node *owner = NULL;
- if (data.pause_mode==PAUSE_MODE_INHERIT) {
+ if (data.pause_mode == PAUSE_MODE_INHERIT) {
if (data.parent)
- owner=data.parent->data.pause_owner;
+ owner = data.parent->data.pause_owner;
} else {
- owner=this;
+ owner = this;
}
_propagate_pause_owner(owner);
-
-
-
}
Node::PauseMode Node::get_pause_mode() const {
@@ -486,12 +460,12 @@ Node::PauseMode Node::get_pause_mode() const {
return data.pause_mode;
}
-void Node::_propagate_pause_owner(Node*p_owner) {
+void Node::_propagate_pause_owner(Node *p_owner) {
- if (data.pause_mode!=PAUSE_MODE_INHERIT)
+ if (data.pause_mode != PAUSE_MODE_INHERIT)
return;
- data.pause_owner=p_owner;
- for(int i=0;i<data.children.size();i++) {
+ data.pause_owner = p_owner;
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->_propagate_pause_owner(p_owner);
}
@@ -499,30 +473,27 @@ void Node::_propagate_pause_owner(Node*p_owner) {
void Node::set_network_mode(NetworkMode p_mode) {
- if (data.network_mode==p_mode)
+ if (data.network_mode == p_mode)
return;
- bool prev_inherits=data.network_mode==NETWORK_MODE_INHERIT;
- data.network_mode=p_mode;
+ bool prev_inherits = data.network_mode == NETWORK_MODE_INHERIT;
+ data.network_mode = p_mode;
if (!is_inside_tree())
return; //pointless
- if ((data.network_mode==NETWORK_MODE_INHERIT) == prev_inherits)
+ if ((data.network_mode == NETWORK_MODE_INHERIT) == prev_inherits)
return; ///nothing changed
- Node *owner=NULL;
+ Node *owner = NULL;
- if (data.network_mode==NETWORK_MODE_INHERIT) {
+ if (data.network_mode == NETWORK_MODE_INHERIT) {
if (data.parent)
- owner=data.parent->data.network_owner;
+ owner = data.parent->data.network_owner;
} else {
- owner=this;
+ owner = this;
}
_propagate_network_owner(owner);
-
-
-
}
Node::NetworkMode Node::get_network_mode() const {
@@ -532,9 +503,9 @@ Node::NetworkMode Node::get_network_mode() const {
bool Node::is_network_master() const {
- ERR_FAIL_COND_V(!is_inside_tree(),false);
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
- switch(data.network_mode) {
+ switch (data.network_mode) {
case NETWORK_MODE_INHERIT: {
if (data.network_owner)
@@ -554,14 +525,12 @@ bool Node::is_network_master() const {
return false;
}
+void Node::_propagate_network_owner(Node *p_owner) {
-
-void Node::_propagate_network_owner(Node*p_owner) {
-
- if (data.network_mode!=NETWORK_MODE_INHERIT)
+ if (data.network_mode != NETWORK_MODE_INHERIT)
return;
- data.network_owner=p_owner;
- for(int i=0;i<data.children.size();i++) {
+ data.network_owner = p_owner;
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->_propagate_network_owner(p_owner);
}
@@ -569,194 +538,187 @@ void Node::_propagate_network_owner(Node*p_owner) {
/***** RPC CONFIG ********/
-void Node::rpc_config(const StringName& p_method,RPCMode p_mode) {
+void Node::rpc_config(const StringName &p_method, RPCMode p_mode) {
- if (p_mode==RPC_MODE_DISABLED) {
+ if (p_mode == RPC_MODE_DISABLED) {
data.rpc_methods.erase(p_method);
} else {
- data.rpc_methods[p_method]=p_mode;
+ data.rpc_methods[p_method] = p_mode;
};
}
-void Node::rset_config(const StringName& p_property,RPCMode p_mode) {
+void Node::rset_config(const StringName &p_property, RPCMode p_mode) {
- if (p_mode==RPC_MODE_DISABLED) {
+ if (p_mode == RPC_MODE_DISABLED) {
data.rpc_properties.erase(p_property);
} else {
- data.rpc_properties[p_property]=p_mode;
+ data.rpc_properties[p_property] = p_mode;
};
}
/***** RPC FUNCTIONS ********/
-void Node::rpc(const StringName& p_method,VARIANT_ARG_DECLARE) {
+void Node::rpc(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
- rpcp(0,false,p_method,argptr,argc);
+ rpcp(0, false, p_method, argptr, argc);
}
-
-void Node::rpc_id(int p_peer_id,const StringName& p_method,VARIANT_ARG_DECLARE) {
+void Node::rpc_id(int p_peer_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
- rpcp(p_peer_id,false,p_method,argptr,argc);
+ rpcp(p_peer_id, false, p_method, argptr, argc);
}
-
-void Node::rpc_unreliable(const StringName& p_method,VARIANT_ARG_DECLARE) {
+void Node::rpc_unreliable(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
- rpcp(0,true,p_method,argptr,argc);
+ rpcp(0, true, p_method, argptr, argc);
}
-
-void Node::rpc_unreliable_id(int p_peer_id,const StringName& p_method,VARIANT_ARG_DECLARE) {
+void Node::rpc_unreliable_id(int p_peer_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
- int argc=0;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ int argc = 0;
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
- rpcp(p_peer_id,true,p_method,argptr,argc);
+ rpcp(p_peer_id, true, p_method, argptr, argc);
}
+Variant Node::_rpc_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant Node::_rpc_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- if (p_argcount<1) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
+ if (p_argcount < 1) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
return Variant();
}
StringName method = *p_args[0];
- rpcp(0,false,method,&p_args[1],p_argcount-1);
+ rpcp(0, false, method, &p_args[1], p_argcount - 1);
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
return Variant();
}
+Variant Node::_rpc_id_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant Node::_rpc_id_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- if (p_argcount<2) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=2;
+ if (p_argcount < 2) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 2;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::INT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::INT;
+ if (p_args[0]->get_type() != Variant::INT) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::INT;
return Variant();
}
- if (p_args[1]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
+ if (p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
return Variant();
}
int peer_id = *p_args[0];
StringName method = *p_args[1];
- rpcp(peer_id,false,method,&p_args[2],p_argcount-2);
+ rpcp(peer_id, false, method, &p_args[2], p_argcount - 2);
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
return Variant();
}
+Variant Node::_rpc_unreliable_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant Node::_rpc_unreliable_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- if (p_argcount<1) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=1;
+ if (p_argcount < 1) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 1;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::STRING;
+ if (p_args[0]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::STRING;
return Variant();
}
StringName method = *p_args[0];
- rpcp(0,true,method,&p_args[1],p_argcount-1);
+ rpcp(0, true, method, &p_args[1], p_argcount - 1);
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
return Variant();
}
+Variant Node::_rpc_unreliable_id_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant Node::_rpc_unreliable_id_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
- if (p_argcount<2) {
- r_error.error=Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
- r_error.argument=2;
+ if (p_argcount < 2) {
+ r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+ r_error.argument = 2;
return Variant();
}
- if (p_args[0]->get_type()!=Variant::INT) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=0;
- r_error.expected=Variant::INT;
+ if (p_args[0]->get_type() != Variant::INT) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 0;
+ r_error.expected = Variant::INT;
return Variant();
}
- if (p_args[1]->get_type()!=Variant::STRING) {
- r_error.error=Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
- r_error.argument=1;
- r_error.expected=Variant::STRING;
+ if (p_args[1]->get_type() != Variant::STRING) {
+ r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+ r_error.argument = 1;
+ r_error.expected = Variant::STRING;
return Variant();
}
int peer_id = *p_args[0];
StringName method = *p_args[1];
- rpcp(peer_id,true,method,&p_args[2],p_argcount-2);
+ rpcp(peer_id, true, method, &p_args[2], p_argcount - 2);
- r_error.error=Variant::CallError::CALL_OK;
+ r_error.error = Variant::CallError::CALL_OK;
return Variant();
}
@@ -785,24 +747,21 @@ Variant Node::_rpc_bind(const Variant** p_args, int p_argcount, Variant::CallErr
}
#endif
-void Node::rpcp(int p_peer_id,bool p_unreliable,const StringName& p_method,const Variant** p_arg,int p_argcount) {
+void Node::rpcp(int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
ERR_FAIL_COND(!is_inside_tree());
- bool skip_rpc=false;
+ bool skip_rpc = false;
- if (p_peer_id==0 || p_peer_id==get_tree()->get_network_unique_id() || (p_peer_id<0 && p_peer_id!=-get_tree()->get_network_unique_id())) {
+ if (p_peer_id == 0 || p_peer_id == get_tree()->get_network_unique_id() || (p_peer_id < 0 && p_peer_id != -get_tree()->get_network_unique_id())) {
//check that send mode can use local call
+ bool call_local = false;
- bool call_local=false;
-
-
-
- Map<StringName,RPCMode>::Element *E = data.rpc_methods.find(p_method);
+ Map<StringName, RPCMode>::Element *E = data.rpc_methods.find(p_method);
if (E) {
- switch(E->get()) {
+ switch (E->get()) {
case RPC_MODE_DISABLED: {
//do nothing
@@ -812,36 +771,34 @@ void Node::rpcp(int p_peer_id,bool p_unreliable,const StringName& p_method,const
} break;
case RPC_MODE_SYNC: {
//call it, sync always results in call
- call_local=true;
+ call_local = true;
} break;
case RPC_MODE_MASTER: {
- call_local=is_network_master();
+ call_local = is_network_master();
if (call_local) {
- skip_rpc=true; //no other master so..
+ skip_rpc = true; //no other master so..
}
} break;
case RPC_MODE_SLAVE: {
- call_local=!is_network_master();
+ call_local = !is_network_master();
} break;
-
}
}
-
if (call_local) {
Variant::CallError ce;
- call(p_method,p_arg,p_argcount,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
- String error = Variant::get_call_error_text(this,p_method,p_arg,p_argcount,ce);
- error="rpc() aborted in local call: - "+error;
+ call(p_method, p_arg, p_argcount, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
+ String error = Variant::get_call_error_text(this, p_method, p_arg, p_argcount, ce);
+ error = "rpc() aborted in local call: - " + error;
ERR_PRINTS(error);
return;
}
- } else if (get_script_instance()){
+ } else if (get_script_instance()) {
//attempt with script
ScriptInstance::RPCMode rpc_mode = get_script_instance()->get_rpc_mode(p_method);
- switch(rpc_mode) {
+ switch (rpc_mode) {
case ScriptInstance::RPC_MODE_DISABLED: {
//do nothing
@@ -851,26 +808,26 @@ void Node::rpcp(int p_peer_id,bool p_unreliable,const StringName& p_method,const
} break;
case ScriptInstance::RPC_MODE_SYNC: {
//call it, sync always results in call
- call_local=true;
+ call_local = true;
} break;
case ScriptInstance::RPC_MODE_MASTER: {
- call_local=is_network_master();
+ call_local = is_network_master();
if (call_local) {
- skip_rpc=true; //no other master so..
+ skip_rpc = true; //no other master so..
}
} break;
case ScriptInstance::RPC_MODE_SLAVE: {
- call_local=!is_network_master();
+ call_local = !is_network_master();
} break;
}
if (call_local) {
Variant::CallError ce;
- ce.error=Variant::CallError::CALL_OK;
- get_script_instance()->call(p_method,p_arg,p_argcount,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
- String error = Variant::get_call_error_text(this,p_method,p_arg,p_argcount,ce);
- error="rpc() aborted in script local call: - "+error;
+ ce.error = Variant::CallError::CALL_OK;
+ get_script_instance()->call(p_method, p_arg, p_argcount, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
+ String error = Variant::get_call_error_text(this, p_method, p_arg, p_argcount, ce);
+ error = "rpc() aborted in script local call: - " + error;
ERR_PRINTS(error);
return;
}
@@ -881,31 +838,26 @@ void Node::rpcp(int p_peer_id,bool p_unreliable,const StringName& p_method,const
if (skip_rpc)
return;
-
- get_tree()->_rpc(this,p_peer_id,p_unreliable,false,p_method,p_arg,p_argcount);
-
+ get_tree()->_rpc(this, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
}
-
/******** RSET *********/
-
-void Node::rsetp(int p_peer_id,bool p_unreliable,const StringName& p_property,const Variant& p_value) {
+void Node::rsetp(int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
ERR_FAIL_COND(!is_inside_tree());
- bool skip_rset=false;
+ bool skip_rset = false;
- if (p_peer_id==0 || p_peer_id==get_tree()->get_network_unique_id() || (p_peer_id<0 && p_peer_id!=-get_tree()->get_network_unique_id())) {
+ if (p_peer_id == 0 || p_peer_id == get_tree()->get_network_unique_id() || (p_peer_id < 0 && p_peer_id != -get_tree()->get_network_unique_id())) {
//check that send mode can use local call
+ bool set_local = false;
- bool set_local=false;
-
- Map<StringName,RPCMode>::Element *E = data.rpc_properties.find(p_property);
+ Map<StringName, RPCMode>::Element *E = data.rpc_properties.find(p_property);
if (E) {
- switch(E->get()) {
+ switch (E->get()) {
case RPC_MODE_DISABLED: {
//do nothing
@@ -915,37 +867,35 @@ void Node::rsetp(int p_peer_id,bool p_unreliable,const StringName& p_property,co
} break;
case RPC_MODE_SYNC: {
//call it, sync always results in call
- set_local=true;
+ set_local = true;
} break;
case RPC_MODE_MASTER: {
- set_local=is_network_master();
+ set_local = is_network_master();
if (set_local) {
- skip_rset=true;
+ skip_rset = true;
}
} break;
case RPC_MODE_SLAVE: {
- set_local=!is_network_master();
+ set_local = !is_network_master();
} break;
-
}
}
-
if (set_local) {
bool valid;
- set(p_property,p_value,&valid);
+ set(p_property, p_value, &valid);
if (!valid) {
- String error="rset() aborted in local set, property not found: - "+String(p_property);
+ String error = "rset() aborted in local set, property not found: - " + String(p_property);
ERR_PRINTS(error);
return;
}
- } else if (get_script_instance()){
+ } else if (get_script_instance()) {
//attempt with script
ScriptInstance::RPCMode rpc_mode = get_script_instance()->get_rset_mode(p_property);
- switch(rpc_mode) {
+ switch (rpc_mode) {
case ScriptInstance::RPC_MODE_DISABLED: {
//do nothing
@@ -955,76 +905,68 @@ void Node::rsetp(int p_peer_id,bool p_unreliable,const StringName& p_property,co
} break;
case ScriptInstance::RPC_MODE_SYNC: {
//call it, sync always results in call
- set_local=true;
+ set_local = true;
} break;
case ScriptInstance::RPC_MODE_MASTER: {
- set_local=is_network_master();
+ set_local = is_network_master();
if (set_local) {
- skip_rset=true;
+ skip_rset = true;
}
} break;
case ScriptInstance::RPC_MODE_SLAVE: {
- set_local=!is_network_master();
+ set_local = !is_network_master();
} break;
}
if (set_local) {
- bool valid = get_script_instance()->set(p_property,p_value);
+ bool valid = get_script_instance()->set(p_property, p_value);
if (!valid) {
- String error="rset() aborted in local script set, property not found: - "+String(p_property);
+ String error = "rset() aborted in local script set, property not found: - " + String(p_property);
ERR_PRINTS(error);
return;
}
}
-
}
}
if (skip_rset)
return;
- const Variant*vptr = &p_value;
-
- get_tree()->_rpc(this,p_peer_id,p_unreliable,true,p_property,&vptr,1);
+ const Variant *vptr = &p_value;
+ get_tree()->_rpc(this, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
}
+void Node::rset(const StringName &p_property, const Variant &p_value) {
-
-void Node::rset(const StringName& p_property,const Variant& p_value) {
-
- rsetp(0,false,p_property,p_value);
-
+ rsetp(0, false, p_property, p_value);
}
-void Node::rset_id(int p_peer_id,const StringName& p_property,const Variant& p_value) {
-
- rsetp(p_peer_id,false,p_property,p_value);
+void Node::rset_id(int p_peer_id, const StringName &p_property, const Variant &p_value) {
+ rsetp(p_peer_id, false, p_property, p_value);
}
-void Node::rset_unreliable(const StringName& p_property,const Variant& p_value) {
-
- rsetp(0,true,p_property,p_value);
+void Node::rset_unreliable(const StringName &p_property, const Variant &p_value) {
+ rsetp(0, true, p_property, p_value);
}
-void Node::rset_unreliable_id(int p_peer_id,const StringName& p_property,const Variant& p_value) {
-
- rsetp(p_peer_id,true,p_property,p_value);
+void Node::rset_unreliable_id(int p_peer_id, const StringName &p_property, const Variant &p_value) {
+ rsetp(p_peer_id, true, p_property, p_value);
}
//////////// end of rpc
-bool Node::can_call_rpc(const StringName& p_method) const {
+bool Node::can_call_rpc(const StringName &p_method) const {
- const Map<StringName,RPCMode>::Element *E = data.rpc_methods.find(p_method);
+ const Map<StringName, RPCMode>::Element *E = data.rpc_methods.find(p_method);
if (E) {
- switch(E->get()) {
+ switch (E->get()) {
case RPC_MODE_DISABLED: {
return false;
@@ -1044,12 +986,11 @@ bool Node::can_call_rpc(const StringName& p_method) const {
}
}
-
- if (get_script_instance()){
+ if (get_script_instance()) {
//attempt with script
ScriptInstance::RPCMode rpc_mode = get_script_instance()->get_rpc_mode(p_method);
- switch(rpc_mode) {
+ switch (rpc_mode) {
case ScriptInstance::RPC_MODE_DISABLED: {
return false;
@@ -1067,19 +1008,18 @@ bool Node::can_call_rpc(const StringName& p_method) const {
return !is_network_master();
} break;
}
-
}
- ERR_PRINTS("RPC on unauthorized method attempted: "+String(p_method)+" on base: "+String(Variant(this)));
+ ERR_PRINTS("RPC on unauthorized method attempted: " + String(p_method) + " on base: " + String(Variant(this)));
return false;
}
-bool Node::can_call_rset(const StringName& p_property) const {
+bool Node::can_call_rset(const StringName &p_property) const {
- const Map<StringName,RPCMode>::Element *E = data.rpc_properties.find(p_property);
+ const Map<StringName, RPCMode>::Element *E = data.rpc_properties.find(p_property);
if (E) {
- switch(E->get()) {
+ switch (E->get()) {
case RPC_MODE_DISABLED: {
return false;
@@ -1099,12 +1039,11 @@ bool Node::can_call_rset(const StringName& p_property) const {
}
}
-
- if (get_script_instance()){
+ if (get_script_instance()) {
//attempt with script
ScriptInstance::RPCMode rpc_mode = get_script_instance()->get_rset_mode(p_property);
- switch(rpc_mode) {
+ switch (rpc_mode) {
case ScriptInstance::RPC_MODE_DISABLED: {
return false;
@@ -1122,43 +1061,39 @@ bool Node::can_call_rset(const StringName& p_property) const {
return !is_network_master();
} break;
}
-
}
- ERR_PRINTS("RSET on unauthorized property attempted: "+String(p_property)+" on base: "+String(Variant(this)));
+ ERR_PRINTS("RSET on unauthorized property attempted: " + String(p_property) + " on base: " + String(Variant(this)));
return false;
}
-
bool Node::can_process() const {
- ERR_FAIL_COND_V( !is_inside_tree(), false );
+ ERR_FAIL_COND_V(!is_inside_tree(), false);
if (get_tree()->is_paused()) {
- if (data.pause_mode==PAUSE_MODE_STOP)
+ if (data.pause_mode == PAUSE_MODE_STOP)
return false;
- if (data.pause_mode==PAUSE_MODE_PROCESS)
+ if (data.pause_mode == PAUSE_MODE_PROCESS)
return true;
- if (data.pause_mode==PAUSE_MODE_INHERIT) {
+ if (data.pause_mode == PAUSE_MODE_INHERIT) {
if (!data.pause_owner)
return false; //clearly no pause owner by default
- if (data.pause_owner->data.pause_mode==PAUSE_MODE_PROCESS)
+ if (data.pause_owner->data.pause_mode == PAUSE_MODE_PROCESS)
return true;
- if (data.pause_owner->data.pause_mode==PAUSE_MODE_STOP)
+ if (data.pause_owner->data.pause_mode == PAUSE_MODE_STOP)
return false;
}
-
}
return true;
}
-
float Node::get_fixed_process_delta_time() const {
if (data.tree)
@@ -1177,21 +1112,20 @@ float Node::get_process_delta_time() const {
void Node::set_process(bool p_idle_process) {
- if (data.idle_process==p_idle_process)
+ if (data.idle_process == p_idle_process)
return;
- data.idle_process=p_idle_process;
+ data.idle_process = p_idle_process;
if (data.idle_process)
- add_to_group("idle_process",false);
+ add_to_group("idle_process", false);
else
remove_from_group("idle_process");
- data.idle_process=p_idle_process;
+ data.idle_process = p_idle_process;
_change_notify("idle_process");
}
-
bool Node::is_processing() const {
return data.idle_process;
@@ -1199,17 +1133,17 @@ bool Node::is_processing() const {
void Node::set_process_internal(bool p_idle_process_internal) {
- if (data.idle_process_internal==p_idle_process_internal)
+ if (data.idle_process_internal == p_idle_process_internal)
return;
- data.idle_process_internal=p_idle_process_internal;
+ data.idle_process_internal = p_idle_process_internal;
if (data.idle_process_internal)
- add_to_group("idle_process_internal",false);
+ add_to_group("idle_process_internal", false);
else
remove_from_group("idle_process_internal");
- data.idle_process_internal=p_idle_process_internal;
+ data.idle_process_internal = p_idle_process_internal;
_change_notify("idle_process_internal");
}
@@ -1218,22 +1152,19 @@ bool Node::is_processing_internal() const {
return data.idle_process_internal;
}
-
void Node::set_process_input(bool p_enable) {
- if (p_enable==data.input)
+ if (p_enable == data.input)
return;
- data.input=p_enable;
+ data.input = p_enable;
if (!is_inside_tree())
return;
if (p_enable)
- add_to_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_input" + itos(get_viewport()->get_instance_ID()));
else
- remove_from_group("_vp_input"+itos(get_viewport()->get_instance_ID()));
-
-
+ remove_from_group("_vp_input" + itos(get_viewport()->get_instance_ID()));
}
bool Node::is_processing_input() const {
@@ -1242,61 +1173,56 @@ bool Node::is_processing_input() const {
void Node::set_process_unhandled_input(bool p_enable) {
- if (p_enable==data.unhandled_input)
+ if (p_enable == data.unhandled_input)
return;
- data.unhandled_input=p_enable;
+ data.unhandled_input = p_enable;
if (!is_inside_tree())
return;
if (p_enable)
- add_to_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_ID()));
else
- remove_from_group("_vp_unhandled_input"+itos(get_viewport()->get_instance_ID()));
+ remove_from_group("_vp_unhandled_input" + itos(get_viewport()->get_instance_ID()));
}
-
bool Node::is_processing_unhandled_input() const {
return data.unhandled_input;
}
-
void Node::set_process_unhandled_key_input(bool p_enable) {
- if (p_enable==data.unhandled_key_input)
+ if (p_enable == data.unhandled_key_input)
return;
- data.unhandled_key_input=p_enable;
+ data.unhandled_key_input = p_enable;
if (!is_inside_tree())
return;
if (p_enable)
- add_to_group("_vp_unhandled_key_input"+itos(get_viewport()->get_instance_ID()));
+ add_to_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_ID()));
else
- remove_from_group("_vp_unhandled_key_input"+itos(get_viewport()->get_instance_ID()));
+ remove_from_group("_vp_unhandled_key_input" + itos(get_viewport()->get_instance_ID()));
}
-
bool Node::is_processing_unhandled_key_input() const {
return data.unhandled_key_input;
}
-
StringName Node::get_name() const {
return data.name;
}
-void Node::_set_name_nocheck(const StringName& p_name) {
-
- data.name=p_name;
+void Node::_set_name_nocheck(const StringName &p_name) {
+ data.name = p_name;
}
-void Node::set_name(const String& p_name) {
+void Node::set_name(const String &p_name) {
- String name=p_name.replace(":","").replace("/","").replace("@","");
+ String name = p_name.replace(":", "").replace("/", "").replace("@", "");
- ERR_FAIL_COND(name=="");
- data.name=name;
+ ERR_FAIL_COND(name == "");
+ data.name = name;
if (data.parent) {
@@ -1312,7 +1238,7 @@ void Node::set_name(const String& p_name) {
}
}
-static bool node_hrcr=false;
+static bool node_hrcr = false;
static SafeRefCount node_hrcr_count;
void Node::init_node_hrcr() {
@@ -1321,12 +1247,11 @@ void Node::init_node_hrcr() {
void Node::set_human_readable_collision_renaming(bool p_enabled) {
- node_hrcr=p_enabled;
+ node_hrcr = p_enabled;
}
-
#ifdef TOOLS_ENABLED
-String Node::validate_child_name(Node* p_child) {
+String Node::validate_child_name(Node *p_child) {
return _generate_serial_child_name(p_child);
}
@@ -1341,28 +1266,28 @@ void Node::_validate_child_name(Node *p_child, bool p_force_human_readable) {
//this approach to autoset node names is human readable but very slow
//it's turned on while running in the editor
- p_child->data.name=_generate_serial_child_name(p_child);
+ p_child->data.name = _generate_serial_child_name(p_child);
} else {
//this approach to autoset node names is fast but not as readable
//it's the default and reserves the '@' character for unique names.
- bool unique=true;
+ bool unique = true;
- if (p_child->data.name==StringName() || p_child->data.name.operator String()[0]=='@') {
+ if (p_child->data.name == StringName() || p_child->data.name.operator String()[0] == '@') {
//new unique name must be assigned
- unique=false;
+ unique = false;
} else {
//check if exists
- Node **childs=data.children.ptr();
+ Node **childs = data.children.ptr();
int cc = data.children.size();
- for(int i=0;i<cc;i++) {
- if (childs[i]==p_child)
+ for (int i = 0; i < cc; i++) {
+ if (childs[i] == p_child)
continue;
- if (childs[i]->data.name==p_child->data.name) {
- unique=false;
+ if (childs[i]->data.name == p_child->data.name) {
+ unique = false;
break;
}
}
@@ -1371,8 +1296,8 @@ void Node::_validate_child_name(Node *p_child, bool p_force_human_readable) {
if (!unique) {
node_hrcr_count.ref();
- String name = "@"+String(p_child->get_name())+"@"+itos(node_hrcr_count.get());
- p_child->data.name=name;
+ String name = "@" + String(p_child->get_name()) + "@" + itos(node_hrcr_count.get());
+ p_child->data.name = name;
}
}
}
@@ -1381,7 +1306,7 @@ String Node::_generate_serial_child_name(Node *p_child) {
String name = p_child->data.name;
- if (name=="") {
+ if (name == "") {
name = p_child->get_class();
// Adjust casing according to project setting. The current type name is expected to be in PascalCase.
@@ -1399,48 +1324,48 @@ String Node::_generate_serial_child_name(Node *p_child) {
// Extract trailing number
String nums;
- for(int i=name.length()-1;i>=0;i--) {
- CharType n=name[i];
- if (n>='0' && n<='9') {
- nums=String::chr(name[i])+nums;
+ for (int i = name.length() - 1; i >= 0; i--) {
+ CharType n = name[i];
+ if (n >= '0' && n <= '9') {
+ nums = String::chr(name[i]) + nums;
} else {
break;
}
}
- String nnsep=_get_name_num_separator();
- int num=0;
- bool explicit_zero=false;
- if (nums.length()>0 && name.substr(name.length()-nnsep.length()-nums.length(),nnsep.length()) == nnsep) {
+ String nnsep = _get_name_num_separator();
+ int num = 0;
+ bool explicit_zero = false;
+ if (nums.length() > 0 && name.substr(name.length() - nnsep.length() - nums.length(), nnsep.length()) == nnsep) {
// Base name + Separator + Number
- num=nums.to_int();
- name=name.substr(0,name.length()-nnsep.length()-nums.length()); // Keep base name
- if (num==0) {
- explicit_zero=true;
+ num = nums.to_int();
+ name = name.substr(0, name.length() - nnsep.length() - nums.length()); // Keep base name
+ if (num == 0) {
+ explicit_zero = true;
}
}
- for(;;) {
+ for (;;) {
String attempt = (name + (num > 0 || explicit_zero ? nnsep + itos(num) : "")).strip_edges();
- bool found=false;
- for(int i=0;i<data.children.size();i++) {
- if (data.children[i]==p_child)
+ bool found = false;
+ for (int i = 0; i < data.children.size(); i++) {
+ if (data.children[i] == p_child)
continue;
- if (data.children[i]->data.name==attempt) {
- found=true;
+ if (data.children[i]->data.name == attempt) {
+ found = true;
break;
}
}
if (!found) {
return attempt;
} else {
- if (num==0) {
+ if (num == 0) {
if (explicit_zero) {
// Name ended in separator + 0; user expects to get to separator + 1
- num=1;
+ num = 1;
} else {
// Name was undecorated so skip to 2 for a more natural result
- num=2;
+ num = 2;
}
} else {
num++;
@@ -1449,13 +1374,13 @@ String Node::_generate_serial_child_name(Node *p_child) {
}
}
-void Node::_add_child_nocheck(Node* p_child,const StringName& p_name) {
+void Node::_add_child_nocheck(Node *p_child, const StringName &p_name) {
//add a child node quickly, without name validation
- p_child->data.name=p_name;
- p_child->data.pos=data.children.size();
- data.children.push_back( p_child );
- p_child->data.parent=this;
+ p_child->data.name = p_name;
+ p_child->data.pos = data.children.size();
+ data.children.push_back(p_child);
+ p_child->data.parent = this;
p_child->notification(NOTIFICATION_PARENTED);
if (data.tree) {
@@ -1464,37 +1389,33 @@ void Node::_add_child_nocheck(Node* p_child,const StringName& p_name) {
/* Notify */
//recognize childs created in this node constructor
- p_child->data.parent_owned=data.in_constructor;
+ p_child->data.parent_owned = data.in_constructor;
add_child_notify(p_child);
-
-
}
-
void Node::add_child(Node *p_child, bool p_legible_unique_name) {
ERR_FAIL_NULL(p_child);
/* Fail if node has a parent */
- if (p_child==this) {
- ERR_EXPLAIN("Can't add child "+p_child->get_name()+" to itself.")
- ERR_FAIL_COND( p_child==this ); // adding to itself!
+ if (p_child == this) {
+ ERR_EXPLAIN("Can't add child " + p_child->get_name() + " to itself.")
+ ERR_FAIL_COND(p_child == this); // adding to itself!
}
ERR_EXPLAIN("Can't add child, already has a parent");
- ERR_FAIL_COND( p_child->data.parent );
+ ERR_FAIL_COND(p_child->data.parent);
- if (data.blocked>0) {
+ if (data.blocked > 0) {
ERR_EXPLAIN("Parent node is busy setting up children, add_node() failed. Consider using call_deferred(\"add_child\",child) instead.");
- ERR_FAIL_COND(data.blocked>0);
+ ERR_FAIL_COND(data.blocked > 0);
}
ERR_EXPLAIN("Can't add child while a notification is happening");
- ERR_FAIL_COND( data.blocked > 0 );
+ ERR_FAIL_COND(data.blocked > 0);
/* Validate name */
- _validate_child_name(p_child,p_legible_unique_name);
-
- _add_child_nocheck(p_child,p_child->data.name);
+ _validate_child_name(p_child, p_legible_unique_name);
+ _add_child_nocheck(p_child, p_child->data.name);
}
void Node::add_child_below_node(Node *p_node, Node *p_child, bool p_legible_unique_name) {
@@ -1507,39 +1428,32 @@ void Node::add_child_below_node(Node *p_node, Node *p_child, bool p_legible_uniq
}
}
-
void Node::_propagate_validate_owner() {
if (data.owner) {
- bool found=false;
+ bool found = false;
Node *parent = data.parent;
- while(parent) {
+ while (parent) {
+ if (parent == data.owner) {
- if (parent==data.owner) {
-
- found=true;
+ found = true;
break;
}
- parent=parent->data.parent;
+ parent = parent->data.parent;
}
-
if (!found) {
-
data.owner->data.owned.erase(data.OW);
- data.owner=NULL;
+ data.owner = NULL;
}
-
}
-
- for(int i=0;i<data.children.size();i++) {
-
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->_propagate_validate_owner();
}
@@ -1548,28 +1462,27 @@ void Node::_propagate_validate_owner() {
void Node::remove_child(Node *p_child) {
ERR_FAIL_NULL(p_child);
- if (data.blocked>0) {
+ if (data.blocked > 0) {
ERR_EXPLAIN("Parent node is busy setting up children, remove_node() failed. Consider using call_deferred(\"remove_child\",child) instead.");
- ERR_FAIL_COND(data.blocked>0);
+ ERR_FAIL_COND(data.blocked > 0);
}
- int idx=-1;
- for (int i=0;i<data.children.size();i++) {
+ int idx = -1;
+ for (int i = 0; i < data.children.size(); i++) {
- if (data.children[i]==p_child) {
+ if (data.children[i] == p_child) {
- idx=i;
+ idx = i;
break;
}
}
- ERR_FAIL_COND( idx==-1 );
+ ERR_FAIL_COND(idx == -1);
//ERR_FAIL_COND( p_child->data.blocked > 0 );
-
//if (data.scene) { does not matter
- p_child->_set_tree(NULL);
+ p_child->_set_tree(NULL);
//}
remove_child_notify(p_child);
@@ -1577,19 +1490,16 @@ void Node::remove_child(Node *p_child) {
data.children.remove(idx);
- for (int i=idx;i<data.children.size();i++) {
+ for (int i = idx; i < data.children.size(); i++) {
- data.children[i]->data.pos=i;
+ data.children[i]->data.pos = i;
}
- p_child->data.parent=NULL;
- p_child->data.pos=-1;
-
-
+ p_child->data.parent = NULL;
+ p_child->data.pos = -1;
// validate owner
p_child->_propagate_validate_owner();
-
}
int Node::get_child_count() const {
@@ -1598,75 +1508,72 @@ int Node::get_child_count() const {
}
Node *Node::get_child(int p_index) const {
- ERR_FAIL_INDEX_V( p_index, data.children.size(), NULL );
+ ERR_FAIL_INDEX_V(p_index, data.children.size(), NULL);
return data.children[p_index];
}
+Node *Node::_get_child_by_name(const StringName &p_name) const {
-Node *Node::_get_child_by_name(const StringName& p_name) const {
+ int cc = data.children.size();
+ Node *const *cd = data.children.ptr();
- int cc=data.children.size();
- Node* const* cd=data.children.ptr();
-
- for(int i=0;i<cc;i++){
- if (cd[i]->data.name==p_name)
+ for (int i = 0; i < cc; i++) {
+ if (cd[i]->data.name == p_name)
return cd[i];
}
return NULL;
}
-Node *Node::_get_node(const NodePath& p_path) const {
+Node *Node::_get_node(const NodePath &p_path) const {
if (!data.inside_tree && p_path.is_absolute()) {
ERR_EXPLAIN("Can't use get_node() with absolute paths from outside the active scene tree.");
ERR_FAIL_V(NULL);
}
- Node *current=NULL;
- Node *root=NULL;
+ Node *current = NULL;
+ Node *root = NULL;
if (!p_path.is_absolute()) {
- current=const_cast<Node*>(this); //start from this
+ current = const_cast<Node *>(this); //start from this
} else {
- root=const_cast<Node*>(this);
+ root = const_cast<Node *>(this);
while (root->data.parent)
- root=root->data.parent; //start from root
+ root = root->data.parent; //start from root
}
-
- for(int i=0;i<p_path.get_name_count();i++) {
-
+ for (int i = 0; i < p_path.get_name_count(); i++) {
StringName name = p_path.get_name(i);
Node *next = NULL;
- if (name==SceneStringNames::get_singleton()->dot) { // .
+ if (name == SceneStringNames::get_singleton()->dot) { // .
- next=current;
+ next = current;
- } else if (name==SceneStringNames::get_singleton()->doubledot) { // ..
+ } else if (name == SceneStringNames::get_singleton()->doubledot) { // ..
- if (current==NULL || !current->data.parent)
+ if (current == NULL || !current->data.parent)
return NULL;
- next=current->data.parent;
- } else if (current==NULL) {
+ next = current->data.parent;
+ } else if (current == NULL) {
- if (name==root->get_name())
- next=root;
+ if (name == root->get_name())
+ next = root;
} else {
- next=NULL;
+ next = NULL;
- for(int j=0;j<current->data.children.size();j++) {
+ for (int j = 0; j < current->data.children.size(); j++) {
Node *child = current->data.children[j];
- if ( child->data.name == name ) {
+ if (child->data.name == name) {
next = child;
break;
@@ -1676,33 +1583,32 @@ Node *Node::_get_node(const NodePath& p_path) const {
return NULL;
};
}
- current=next;
+ current = next;
}
return current;
}
-Node *Node::get_node(const NodePath& p_path) const {
+Node *Node::get_node(const NodePath &p_path) const {
Node *node = _get_node(p_path);
if (!node) {
- ERR_EXPLAIN("Node not found: "+p_path);
- ERR_FAIL_COND_V(!node,NULL);
+ ERR_EXPLAIN("Node not found: " + p_path);
+ ERR_FAIL_COND_V(!node, NULL);
}
return node;
}
-bool Node::has_node(const NodePath& p_path) const {
+bool Node::has_node(const NodePath &p_path) const {
- return _get_node(p_path)!=NULL;
+ return _get_node(p_path) != NULL;
}
+Node *Node::find_node(const String &p_mask, bool p_recursive, bool p_owned) const {
-Node* Node::find_node(const String& p_mask,bool p_recursive,bool p_owned) const {
-
- Node * const*cptr = data.children.ptr();
+ Node *const *cptr = data.children.ptr();
int ccount = data.children.size();
- for(int i=0;i<ccount;i++) {
+ for (int i = 0; i < ccount; i++) {
if (p_owned && !cptr[i]->data.owner)
continue;
if (cptr[i]->data.name.operator String().match(p_mask))
@@ -1711,12 +1617,11 @@ Node* Node::find_node(const String& p_mask,bool p_recursive,bool p_owned) const
if (!p_recursive)
continue;
- Node* ret = cptr[i]->find_node(p_mask,true,p_owned);
+ Node *ret = cptr[i]->find_node(p_mask, true, p_owned);
if (ret)
return ret;
}
return NULL;
-
}
Node *Node::get_parent() const {
@@ -1724,16 +1629,15 @@ Node *Node::get_parent() const {
return data.parent;
}
-
bool Node::is_a_parent_of(const Node *p_node) const {
- ERR_FAIL_NULL_V(p_node,false);
- Node *p=p_node->data.parent;
- while(p) {
+ ERR_FAIL_NULL_V(p_node, false);
+ Node *p = p_node->data.parent;
+ while (p) {
- if (p==this)
+ if (p == this)
return true;
- p=p->data.parent;
+ p = p->data.parent;
}
return false;
@@ -1741,12 +1645,12 @@ bool Node::is_a_parent_of(const Node *p_node) const {
bool Node::is_greater_than(const Node *p_node) const {
- ERR_FAIL_NULL_V(p_node,false);
- ERR_FAIL_COND_V( !data.inside_tree, false );
- ERR_FAIL_COND_V( !p_node->data.inside_tree, false );
+ ERR_FAIL_NULL_V(p_node, false);
+ ERR_FAIL_COND_V(!data.inside_tree, false);
+ ERR_FAIL_COND_V(!p_node->data.inside_tree, false);
- ERR_FAIL_COND_V( data.depth<0, false);
- ERR_FAIL_COND_V( p_node->data.depth<0, false);
+ ERR_FAIL_COND_V(data.depth < 0, false);
+ ERR_FAIL_COND_V(p_node->data.depth < 0, false);
#ifdef NO_ALLOCA
Vector<int> this_stack;
@@ -1756,46 +1660,46 @@ bool Node::is_greater_than(const Node *p_node) const {
#else
- int *this_stack=(int*)alloca(sizeof(int)*data.depth);
- int *that_stack=(int*)alloca(sizeof(int)*p_node->data.depth);
+ int *this_stack = (int *)alloca(sizeof(int) * data.depth);
+ int *that_stack = (int *)alloca(sizeof(int) * p_node->data.depth);
#endif
const Node *n = this;
- int idx=data.depth-1;
- while(n) {
- ERR_FAIL_INDEX_V(idx, data.depth,false);
- this_stack[idx--]=n->data.pos;
- n=n->data.parent;
+ int idx = data.depth - 1;
+ while (n) {
+ ERR_FAIL_INDEX_V(idx, data.depth, false);
+ this_stack[idx--] = n->data.pos;
+ n = n->data.parent;
}
- ERR_FAIL_COND_V(idx!=-1,false);
+ ERR_FAIL_COND_V(idx != -1, false);
n = p_node;
- idx=p_node->data.depth-1;
- while(n) {
- ERR_FAIL_INDEX_V(idx, p_node->data.depth,false);
- that_stack[idx--]=n->data.pos;
+ idx = p_node->data.depth - 1;
+ while (n) {
+ ERR_FAIL_INDEX_V(idx, p_node->data.depth, false);
+ that_stack[idx--] = n->data.pos;
- n=n->data.parent;
+ n = n->data.parent;
}
- ERR_FAIL_COND_V(idx!=-1,false);
- idx=0;
+ ERR_FAIL_COND_V(idx != -1, false);
+ idx = 0;
bool res;
- while(true) {
+ while (true) {
// using -2 since out-of-tree or nonroot nodes have -1
- int this_idx = (idx >= data.depth)? -2 : this_stack[idx];
- int that_idx = (idx >= p_node->data.depth)? -2 : that_stack[idx];
+ int this_idx = (idx >= data.depth) ? -2 : this_stack[idx];
+ int that_idx = (idx >= p_node->data.depth) ? -2 : that_stack[idx];
if (this_idx > that_idx) {
- res=true;
+ res = true;
break;
} else if (this_idx < that_idx) {
- res=false;
+ res = false;
break;
- } else if (this_idx == -2 ) {
- res=false; // equal
+ } else if (this_idx == -2) {
+ res = false; // equal
break;
}
idx++;
@@ -1804,22 +1708,20 @@ bool Node::is_greater_than(const Node *p_node) const {
return res;
}
-void Node::get_owned_by(Node *p_by,List<Node*> *p_owned) {
+void Node::get_owned_by(Node *p_by, List<Node *> *p_owned) {
- if (data.owner==p_by)
+ if (data.owner == p_by)
p_owned->push_back(this);
- for (int i=0;i<get_child_count();i++)
- get_child(i)->get_owned_by(p_by,p_owned);
-
+ for (int i = 0; i < get_child_count(); i++)
+ get_child(i)->get_owned_by(p_by, p_owned);
}
-
-void Node::_set_owner_nocheck(Node* p_owner) {
+void Node::_set_owner_nocheck(Node *p_owner) {
ERR_FAIL_COND(data.owner);
- data.owner=p_owner;
- data.owner->data.owned.push_back( this );
+ data.owner = p_owner;
+ data.owner->data.owned.push_back(this);
data.OW = data.owner->data.owned.back();
}
@@ -1827,27 +1729,27 @@ void Node::set_owner(Node *p_owner) {
if (data.owner) {
- data.owner->data.owned.erase( data.OW );
- data.OW=NULL;
- data.owner=NULL;
+ data.owner->data.owned.erase(data.OW);
+ data.OW = NULL;
+ data.owner = NULL;
}
- ERR_FAIL_COND(p_owner==this);
+ ERR_FAIL_COND(p_owner == this);
if (!p_owner)
return;
- Node *check=this->get_parent();
- bool owner_valid=false;
+ Node *check = this->get_parent();
+ bool owner_valid = false;
- while(check) {
+ while (check) {
- if (check==p_owner) {
- owner_valid=true;
+ if (check == p_owner) {
+ owner_valid = true;
break;
}
- check=check->data.parent;
+ check = check->data.parent;
}
ERR_FAIL_COND(!owner_valid);
@@ -1859,95 +1761,93 @@ Node *Node::get_owner() const {
return data.owner;
}
+Node *Node::find_common_parent_with(const Node *p_node) const {
-Node* Node::find_common_parent_with(const Node *p_node) const {
-
- if (this==p_node)
- return const_cast<Node*>(p_node);
+ if (this == p_node)
+ return const_cast<Node *>(p_node);
- Set<const Node*> visited;
+ Set<const Node *> visited;
- const Node *n=this;
+ const Node *n = this;
- while(n) {
+ while (n) {
visited.insert(n);
- n=n->data.parent;
+ n = n->data.parent;
}
- const Node *common_parent=p_node;
+ const Node *common_parent = p_node;
- while(common_parent) {
+ while (common_parent) {
if (visited.has(common_parent))
break;
- common_parent=common_parent->data.parent;
+ common_parent = common_parent->data.parent;
}
if (!common_parent)
return NULL;
- return const_cast<Node*>(common_parent);
-
+ return const_cast<Node *>(common_parent);
}
NodePath Node::get_path_to(const Node *p_node) const {
- ERR_FAIL_NULL_V(p_node,NodePath());
+ ERR_FAIL_NULL_V(p_node, NodePath());
- if (this==p_node)
+ if (this == p_node)
return NodePath(".");
- Set<const Node*> visited;
+ Set<const Node *> visited;
- const Node *n=this;
+ const Node *n = this;
- while(n) {
+ while (n) {
visited.insert(n);
- n=n->data.parent;
+ n = n->data.parent;
}
- const Node *common_parent=p_node;
+ const Node *common_parent = p_node;
- while(common_parent) {
+ while (common_parent) {
if (visited.has(common_parent))
break;
- common_parent=common_parent->data.parent;
+ common_parent = common_parent->data.parent;
}
- ERR_FAIL_COND_V(!common_parent,NodePath()); //nodes not in the same tree
+ ERR_FAIL_COND_V(!common_parent, NodePath()); //nodes not in the same tree
visited.clear();
Vector<StringName> path;
- n=p_node;
+ n = p_node;
- while(n!=common_parent) {
+ while (n != common_parent) {
- path.push_back( n->get_name() );
- n=n->data.parent;
+ path.push_back(n->get_name());
+ n = n->data.parent;
}
- n=this;
- StringName up=String("..");
+ n = this;
+ StringName up = String("..");
- while(n!=common_parent) {
+ while (n != common_parent) {
- path.push_back( up );
- n=n->data.parent;
+ path.push_back(up);
+ n = n->data.parent;
}
path.invert();
- return NodePath(path,false);
+ return NodePath(path, false);
}
NodePath Node::get_path() const {
- ERR_FAIL_COND_V(!is_inside_tree(),NodePath());
+ ERR_FAIL_COND_V(!is_inside_tree(), NodePath());
if (data.path_cache)
return *data.path_cache;
@@ -1956,24 +1856,24 @@ NodePath Node::get_path() const {
Vector<StringName> path;
- while(n) {
+ while (n) {
path.push_back(n->get_name());
- n=n->data.parent;
+ n = n->data.parent;
}
path.invert();
- data.path_cache = memnew( NodePath( path, true ) );
+ data.path_cache = memnew(NodePath(path, true));
return *data.path_cache;
}
-bool Node::is_in_group(const StringName& p_identifier) const {
+bool Node::is_in_group(const StringName &p_identifier) const {
return data.grouped.has(p_identifier);
}
-void Node::add_to_group(const StringName& p_identifier,bool p_persistent) {
+void Node::add_to_group(const StringName &p_identifier, bool p_persistent) {
ERR_FAIL_COND(!p_identifier.operator String().length());
@@ -1983,32 +1883,28 @@ void Node::add_to_group(const StringName& p_identifier,bool p_persistent) {
GroupData gd;
if (data.tree) {
- gd.group=data.tree->add_to_group(p_identifier,this);
+ gd.group = data.tree->add_to_group(p_identifier, this);
} else {
- gd.group=NULL;
+ gd.group = NULL;
}
- gd.persistent=p_persistent;
-
- data.grouped[p_identifier]=gd;
+ gd.persistent = p_persistent;
+ data.grouped[p_identifier] = gd;
}
-void Node::remove_from_group(const StringName& p_identifier) {
-
+void Node::remove_from_group(const StringName &p_identifier) {
- ERR_FAIL_COND(!data.grouped.has(p_identifier) );
+ ERR_FAIL_COND(!data.grouped.has(p_identifier));
-
- Map< StringName, GroupData>::Element *E=data.grouped.find(p_identifier);
+ Map<StringName, GroupData>::Element *E = data.grouped.find(p_identifier);
ERR_FAIL_COND(!E);
if (data.tree)
- data.tree->remove_from_group(E->key(),this);
+ data.tree->remove_from_group(E->key(), this);
data.grouped.erase(E);
-
}
Array Node::_get_groups() const {
@@ -2016,7 +1912,7 @@ Array Node::_get_groups() const {
Array groups;
List<GroupInfo> gi;
get_groups(&gi);
- for (List<GroupInfo>::Element *E=gi.front();E;E=E->next()) {
+ for (List<GroupInfo>::Element *E = gi.front(); E; E = E->next()) {
groups.push_back(E->get().name);
}
@@ -2025,33 +1921,27 @@ Array Node::_get_groups() const {
void Node::get_groups(List<GroupInfo> *p_groups) const {
-
- for (const Map< StringName, GroupData>::Element *E=data.grouped.front();E;E=E->next()) {
+ for (const Map<StringName, GroupData>::Element *E = data.grouped.front(); E; E = E->next()) {
GroupInfo gi;
- gi.name=E->key();
- gi.persistent=E->get().persistent;
+ gi.name = E->key();
+ gi.persistent = E->get().persistent;
p_groups->push_back(gi);
}
-
}
bool Node::has_persistent_groups() const {
-
- for (const Map< StringName, GroupData>::Element *E=data.grouped.front();E;E=E->next()) {
+ for (const Map<StringName, GroupData>::Element *E = data.grouped.front(); E; E = E->next()) {
if (E->get().persistent)
return true;
}
-
return false;
-
-
}
void Node::_print_tree(const Node *p_node) {
print_line(String(p_node->get_path_to(this)));
- for (int i=0;i<data.children.size();i++)
+ for (int i = 0; i < data.children.size(); i++)
data.children[i]->_print_tree(p_node);
}
@@ -2060,16 +1950,15 @@ void Node::print_tree() {
_print_tree(this);
}
-
void Node::_propagate_reverse_notification(int p_notification) {
data.blocked++;
- for (int i=data.children.size()-1;i>=0;i--) {
+ for (int i = data.children.size() - 1; i >= 0; i--) {
data.children[i]->_propagate_reverse_notification(p_notification);
}
- notification(p_notification,true);
+ notification(p_notification, true);
data.blocked--;
}
@@ -2080,15 +1969,15 @@ void Node::_propagate_deferred_notification(int p_notification, bool p_reverse)
data.blocked++;
if (!p_reverse)
- MessageQueue::get_singleton()->push_notification(this,p_notification);
+ MessageQueue::get_singleton()->push_notification(this, p_notification);
- for (int i=0;i<data.children.size();i++) {
+ for (int i = 0; i < data.children.size(); i++) {
- data.children[i]->_propagate_deferred_notification(p_notification,p_reverse);
+ data.children[i]->_propagate_deferred_notification(p_notification, p_reverse);
}
if (p_reverse)
- MessageQueue::get_singleton()->push_notification(this,p_notification);
+ MessageQueue::get_singleton()->push_notification(this, p_notification);
data.blocked--;
}
@@ -2098,21 +1987,20 @@ void Node::propagate_notification(int p_notification) {
data.blocked++;
notification(p_notification);
- for (int i=0;i<data.children.size();i++) {
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->propagate_notification(p_notification);
}
data.blocked--;
}
-
-void Node::_propagate_replace_owner(Node *p_owner,Node* p_by_owner) {
- if (get_owner()==p_owner)
+void Node::_propagate_replace_owner(Node *p_owner, Node *p_by_owner) {
+ if (get_owner() == p_owner)
set_owner(p_by_owner);
data.blocked++;
- for (int i=0;i<data.children.size();i++)
- data.children[i]->_propagate_replace_owner(p_owner,p_by_owner);
+ for (int i = 0; i < data.children.size(); i++)
+ data.children[i]->_propagate_replace_owner(p_owner, p_by_owner);
data.blocked--;
}
@@ -2124,21 +2012,21 @@ void Node::remove_and_skip() {
ERR_FAIL_COND(!data.parent);
- Node *new_owner=get_owner();
+ Node *new_owner = get_owner();
- List<Node*> children;
+ List<Node *> children;
- while(true) {
+ while (true) {
- bool clear=true;
- for (int i=0;i<data.children.size();i++) {
+ bool clear = true;
+ for (int i = 0; i < data.children.size(); i++) {
if (!data.children[i]->get_owner())
continue;
remove_child(data.children[i]);
- data.children[i]->_propagate_replace_owner(this,NULL);
+ data.children[i]->_propagate_replace_owner(this, NULL);
children.push_back(data.children[i]);
- clear=false;
+ clear = false;
break;
}
@@ -2146,27 +2034,27 @@ void Node::remove_and_skip() {
break;
}
- while(!children.empty()) {
+ while (!children.empty()) {
- Node *c=children.front()->get();
+ Node *c = children.front()->get();
data.parent->add_child(c);
- c->_propagate_replace_owner(NULL,new_owner);
+ c->_propagate_replace_owner(NULL, new_owner);
children.pop_front();
}
data.parent->remove_child(this);
}
-void Node::set_filename(const String& p_filename) {
+void Node::set_filename(const String &p_filename) {
- data.filename=p_filename;
+ data.filename = p_filename;
}
String Node::get_filename() const {
return data.filename;
}
-void Node::set_editable_instance(Node* p_node,bool p_editable) {
+void Node::set_editable_instance(Node *p_node, bool p_editable) {
ERR_FAIL_NULL(p_node);
ERR_FAIL_COND(!is_a_parent_of(p_node));
@@ -2174,30 +2062,28 @@ void Node::set_editable_instance(Node* p_node,bool p_editable) {
if (!p_editable)
data.editable_instances.erase(p);
else
- data.editable_instances[p]=true;
-
+ data.editable_instances[p] = true;
}
bool Node::is_editable_instance(Node *p_node) const {
if (!p_node)
return false; //easier, null is never editable :)
- ERR_FAIL_COND_V(!is_a_parent_of(p_node),false);
+ ERR_FAIL_COND_V(!is_a_parent_of(p_node), false);
NodePath p = get_path_to(p_node);
return data.editable_instances.has(p);
}
-void Node::set_editable_instances(const HashMap<NodePath,int>& p_editable_instances) {
+void Node::set_editable_instances(const HashMap<NodePath, int> &p_editable_instances) {
- data.editable_instances=p_editable_instances;
+ data.editable_instances = p_editable_instances;
}
-HashMap<NodePath,int> Node::get_editable_instances() const {
+HashMap<NodePath, int> Node::get_editable_instances() const {
return data.editable_instances;
}
-
#if 0
void Node::generate_instance_state() {
@@ -2251,32 +2137,32 @@ Dictionary Node::get_instance_state() const {
#endif
-void Node::set_scene_instance_state(const Ref<SceneState>& p_state) {
+void Node::set_scene_instance_state(const Ref<SceneState> &p_state) {
- data.instance_state=p_state;
+ data.instance_state = p_state;
}
-Ref<SceneState> Node::get_scene_instance_state() const{
+Ref<SceneState> Node::get_scene_instance_state() const {
return data.instance_state;
}
-void Node::set_scene_inherited_state(const Ref<SceneState>& p_state) {
+void Node::set_scene_inherited_state(const Ref<SceneState> &p_state) {
- data.inherited_state=p_state;
+ data.inherited_state = p_state;
}
-Ref<SceneState> Node::get_scene_inherited_state() const{
+Ref<SceneState> Node::get_scene_inherited_state() const {
return data.inherited_state;
}
void Node::set_scene_instance_load_placeholder(bool p_enable) {
- data.use_placeholder=p_enable;
+ data.use_placeholder = p_enable;
}
-bool Node::get_scene_instance_load_placeholder() const{
+bool Node::get_scene_instance_load_placeholder() const {
return data.use_placeholder;
}
@@ -2286,43 +2172,39 @@ int Node::get_position_in_parent() const {
return data.pos;
}
-
-
Node *Node::_duplicate(int p_flags) const {
+ Node *node = NULL;
- Node *node=NULL;
-
- bool instanced=false;
+ bool instanced = false;
if (cast_to<InstancePlaceholder>()) {
const InstancePlaceholder *ip = cast_to<const InstancePlaceholder>();
- InstancePlaceholder *nip = memnew( InstancePlaceholder );
- nip->set_instance_path( ip->get_instance_path() );
- node=nip;
+ InstancePlaceholder *nip = memnew(InstancePlaceholder);
+ nip->set_instance_path(ip->get_instance_path());
+ node = nip;
- } else if ((p_flags&DUPLICATE_USE_INSTANCING) && get_filename()!=String()) {
+ } else if ((p_flags & DUPLICATE_USE_INSTANCING) && get_filename() != String()) {
Ref<PackedScene> res = ResourceLoader::load(get_filename());
- ERR_FAIL_COND_V(res.is_null(),NULL);
- node=res->instance();
- ERR_FAIL_COND_V(!node,NULL);
+ ERR_FAIL_COND_V(res.is_null(), NULL);
+ node = res->instance();
+ ERR_FAIL_COND_V(!node, NULL);
- instanced=true;
+ instanced = true;
} else {
Object *obj = ClassDB::instance(get_class());
- ERR_FAIL_COND_V(!obj,NULL);
+ ERR_FAIL_COND_V(!obj, NULL);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
- ERR_FAIL_COND_V(!node,NULL);
+ ERR_FAIL_COND_V(!node, NULL);
}
-
- if (get_filename()!="") { //an instance
+ if (get_filename() != "") { //an instance
node->set_filename(get_filename());
}
@@ -2330,16 +2212,15 @@ Node *Node::_duplicate(int p_flags) const {
get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
String name = E->get().name;
- if (!(p_flags&DUPLICATE_SCRIPTS) && name=="script/script")
+ if (!(p_flags & DUPLICATE_SCRIPTS) && name == "script/script")
continue;
- node->set( name, get(name) );
-
+ node->set(name, get(name));
}
node->set_name(get_name());
@@ -2347,7 +2228,7 @@ Node *Node::_duplicate(int p_flags) const {
if (p_flags & DUPLICATE_GROUPS) {
List<GroupInfo> gi;
get_groups(&gi);
- for (List<GroupInfo>::Element *E=gi.front();E;E=E->next()) {
+ for (List<GroupInfo>::Element *E = gi.front(); E; E = E->next()) {
node->add_to_group(E->get().name, E->get().persistent);
}
@@ -2356,11 +2237,11 @@ Node *Node::_duplicate(int p_flags) const {
if (p_flags & DUPLICATE_SIGNALS)
_duplicate_signals(this, node);
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
if (get_child(i)->data.parent_owned)
continue;
- if (instanced && get_child(i)->data.owner==this)
+ if (instanced && get_child(i)->data.owner == this)
continue; //part of instance
Node *dup = get_child(i)->duplicate(p_flags);
@@ -2373,40 +2254,38 @@ Node *Node::_duplicate(int p_flags) const {
node->add_child(dup);
}
-
return node;
}
Node *Node::duplicate(int p_flags) const {
- Node* dupe = _duplicate(p_flags);
+ Node *dupe = _duplicate(p_flags);
- if (dupe && (p_flags&DUPLICATE_SIGNALS)) {
- _duplicate_signals(this,dupe);
+ if (dupe && (p_flags & DUPLICATE_SIGNALS)) {
+ _duplicate_signals(this, dupe);
}
return dupe;
}
+void Node::_duplicate_and_reown(Node *p_new_parent, const Map<Node *, Node *> &p_reown_map) const {
-void Node::_duplicate_and_reown(Node* p_new_parent, const Map<Node*,Node*>& p_reown_map) const {
-
- if (get_owner()!=get_parent()->get_owner())
+ if (get_owner() != get_parent()->get_owner())
return;
- Node *node=NULL;
+ Node *node = NULL;
- if (get_filename()!="") {
+ if (get_filename() != "") {
Ref<PackedScene> res = ResourceLoader::load(get_filename());
ERR_FAIL_COND(res.is_null());
- node=res->instance();
+ node = res->instance();
ERR_FAIL_COND(!node);
} else {
Object *obj = ClassDB::instance(get_class());
if (!obj) {
- print_line("could not duplicate: "+String(get_class()));
+ print_line("could not duplicate: " + String(get_class()));
}
ERR_FAIL_COND(!obj);
node = obj->cast_to<Node>();
@@ -2414,32 +2293,29 @@ void Node::_duplicate_and_reown(Node* p_new_parent, const Map<Node*,Node*>& p_re
memdelete(obj);
}
-
List<PropertyInfo> plist;
get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
String name = E->get().name;
- node->set( name, get(name) );
-
+ node->set(name, get(name));
}
node->set_name(get_name());
p_new_parent->add_child(node);
- Node *owner=get_owner();
+ Node *owner = get_owner();
if (p_reown_map.has(owner))
- owner=p_reown_map[owner];
-
+ owner = p_reown_map[owner];
if (owner) {
NodePath p = get_path_to(owner);
- if (owner!=this) {
+ if (owner != this) {
Node *new_owner = node->get_node(p);
if (new_owner) {
node->set_owner(new_owner);
@@ -2447,26 +2323,23 @@ void Node::_duplicate_and_reown(Node* p_new_parent, const Map<Node*,Node*>& p_re
}
}
- for(int i=0;i<get_child_count();i++) {
+ for (int i = 0; i < get_child_count(); i++) {
- get_child(i)->_duplicate_and_reown(node,p_reown_map);
+ get_child(i)->_duplicate_and_reown(node, p_reown_map);
}
-
}
+void Node::_duplicate_signals(const Node *p_original, Node *p_copy) const {
-void Node::_duplicate_signals(const Node* p_original,Node* p_copy) const {
-
- if (this!=p_original && (get_owner()!=p_original && get_owner()!=p_original->get_owner()))
+ if (this != p_original && (get_owner() != p_original && get_owner() != p_original->get_owner()))
return;
List<Connection> conns;
get_all_signal_connections(&conns);
+ for (List<Connection>::Element *E = conns.front(); E; E = E->next()) {
- for (List<Connection>::Element *E=conns.front();E;E=E->next()) {
-
- if (E->get().flags&CONNECT_PERSIST) {
+ if (E->get().flags & CONNECT_PERSIST) {
//user connected
NodePath p = p_original->get_path_to(this);
Node *copy = p_copy->get_node(p);
@@ -2478,37 +2351,32 @@ void Node::_duplicate_signals(const Node* p_original,Node* p_copy) const {
NodePath ptarget = p_original->get_path_to(target);
Node *copytarget = p_copy->get_node(ptarget);
-
if (copy && copytarget) {
- copy->connect(E->get().signal,copytarget,E->get().method,E->get().binds,CONNECT_PERSIST);
+ copy->connect(E->get().signal, copytarget, E->get().method, E->get().binds, CONNECT_PERSIST);
}
-
}
}
- for(int i=0;i<get_child_count();i++) {
- get_child(i)->_duplicate_signals(p_original,p_copy);
+ for (int i = 0; i < get_child_count(); i++) {
+ get_child(i)->_duplicate_signals(p_original, p_copy);
}
-
}
+Node *Node::duplicate_and_reown(const Map<Node *, Node *> &p_reown_map) const {
-Node *Node::duplicate_and_reown(const Map<Node*,Node*>& p_reown_map) const {
-
+ ERR_FAIL_COND_V(get_filename() != "", NULL);
- ERR_FAIL_COND_V(get_filename()!="",NULL);
-
- Node *node=NULL;
+ Node *node = NULL;
Object *obj = ClassDB::instance(get_class());
if (!obj) {
- print_line("could not duplicate: "+String(get_class()));
+ print_line("could not duplicate: " + String(get_class()));
}
- ERR_FAIL_COND_V(!obj,NULL);
+ ERR_FAIL_COND_V(!obj, NULL);
node = obj->cast_to<Node>();
if (!node)
memdelete(obj);
- ERR_FAIL_COND_V(!node,NULL);
+ ERR_FAIL_COND_V(!node, NULL);
node->set_name(get_name());
@@ -2516,35 +2384,31 @@ Node *Node::duplicate_and_reown(const Map<Node*,Node*>& p_reown_map) const {
get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
String name = E->get().name;
- node->set( name, get(name) );
-
+ node->set(name, get(name));
}
+ for (int i = 0; i < get_child_count(); i++) {
- for(int i=0;i<get_child_count();i++) {
-
- get_child(i)->_duplicate_and_reown(node,p_reown_map);
+ get_child(i)->_duplicate_and_reown(node, p_reown_map);
}
- _duplicate_signals(this,node);
+ _duplicate_signals(this, node);
return node;
-
}
-static void find_owned_by(Node* p_by, Node* p_node, List<Node*> *p_owned) {
-
+static void find_owned_by(Node *p_by, Node *p_node, List<Node *> *p_owned) {
- if (p_node->get_owner()==p_by)
+ if (p_node->get_owner() == p_by)
p_owned->push_back(p_node);
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- find_owned_by(p_by,p_node->get_child(i),p_owned);
+ find_owned_by(p_by, p_node->get_child(i), p_owned);
}
}
@@ -2554,14 +2418,14 @@ struct _NodeReplaceByPair {
Variant value;
};
-void Node::replace_by(Node* p_node,bool p_keep_data) {
+void Node::replace_by(Node *p_node, bool p_keep_data) {
ERR_FAIL_NULL(p_node);
ERR_FAIL_COND(p_node->data.parent);
- List<Node*> owned = data.owned;
- List<Node*> owned_by_owner;
- Node *owner = (data.owner==this)?p_node:data.owner;
+ List<Node *> owned = data.owned;
+ List<Node *> owned_by_owner;
+ Node *owner = (data.owner == this) ? p_node : data.owner;
List<_NodeReplaceByPair> replace_data;
@@ -2570,27 +2434,27 @@ void Node::replace_by(Node* p_node,bool p_keep_data) {
List<PropertyInfo> plist;
get_property_list(&plist);
- for(List<PropertyInfo>::Element *E=plist.front();E;E=E->next() ) {
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
_NodeReplaceByPair rd;
- if (!(E->get().usage&PROPERTY_USAGE_STORAGE))
+ if (!(E->get().usage & PROPERTY_USAGE_STORAGE))
continue;
- rd.name=E->get().name;
- rd.value=get(rd.name);
+ rd.name = E->get().name;
+ rd.value = get(rd.name);
}
List<GroupInfo> groups;
get_groups(&groups);
- for(List<GroupInfo>::Element *E=groups.front();E;E=E->next())
+ for (List<GroupInfo>::Element *E = groups.front(); E; E = E->next())
p_node->add_to_group(E->get().name, E->get().persistent);
}
_replace_connections_target(p_node);
if (data.owner) {
- for(int i=0;i<get_child_count();i++)
- find_owned_by(data.owner,get_child(i),&owned_by_owner);
+ for (int i = 0; i < get_child_count(); i++)
+ find_owned_by(data.owner, get_child(i), &owned_by_owner);
}
Node *parent = data.parent;
@@ -2600,73 +2464,70 @@ void Node::replace_by(Node* p_node,bool p_keep_data) {
parent->remove_child(this);
parent->add_child(p_node);
- parent->move_child(p_node,pos_in_parent);
+ parent->move_child(p_node, pos_in_parent);
}
- while(get_child_count()) {
+ while (get_child_count()) {
- Node * child = get_child(0);
+ Node *child = get_child(0);
remove_child(child);
p_node->add_child(child);
}
p_node->set_owner(owner);
- for(int i=0;i<owned.size();i++)
+ for (int i = 0; i < owned.size(); i++)
owned[i]->set_owner(p_node);
- for(int i=0;i<owned_by_owner.size();i++)
+ for (int i = 0; i < owned_by_owner.size(); i++)
owned_by_owner[i]->set_owner(owner);
p_node->set_filename(get_filename());
- for (List<_NodeReplaceByPair>::Element *E=replace_data.front();E;E=E->next()) {
+ for (List<_NodeReplaceByPair>::Element *E = replace_data.front(); E; E = E->next()) {
- p_node->set(E->get().name,E->get().value);
+ p_node->set(E->get().name, E->get().value);
}
-
}
-void Node::_replace_connections_target(Node* p_new_target) {
+void Node::_replace_connections_target(Node *p_new_target) {
List<Connection> cl;
get_signals_connected_to_this(&cl);
- for(List<Connection>::Element *E=cl.front();E;E=E->next()) {
+ for (List<Connection>::Element *E = cl.front(); E; E = E->next()) {
- Connection &c=E->get();
+ Connection &c = E->get();
- c.source->disconnect(c.signal,this,c.method);
- c.source->connect(c.signal,p_new_target,c.method,c.binds,c.flags);
+ c.source->disconnect(c.signal, this, c.method);
+ c.source->connect(c.signal, p_new_target, c.method, c.binds, c.flags);
}
}
Vector<Variant> Node::make_binds(VARIANT_ARG_DECLARE) {
-
Vector<Variant> ret;
- if (p_arg1.get_type()==Variant::NIL)
+ if (p_arg1.get_type() == Variant::NIL)
return ret;
else
ret.push_back(p_arg1);
- if (p_arg2.get_type()==Variant::NIL)
+ if (p_arg2.get_type() == Variant::NIL)
return ret;
else
ret.push_back(p_arg2);
-
- if (p_arg3.get_type()==Variant::NIL)
+ if (p_arg3.get_type() == Variant::NIL)
return ret;
else
ret.push_back(p_arg3);
- if (p_arg4.get_type()==Variant::NIL)
+ if (p_arg4.get_type() == Variant::NIL)
return ret;
else
ret.push_back(p_arg4);
- if (p_arg5.get_type()==Variant::NIL)
+ if (p_arg5.get_type() == Variant::NIL)
return ret;
else
ret.push_back(p_arg5);
@@ -2674,9 +2535,7 @@ Vector<Variant> Node::make_binds(VARIANT_ARG_DECLARE) {
return ret;
}
-
-
-bool Node::has_node_and_resource(const NodePath& p_path) const {
+bool Node::has_node_and_resource(const NodePath &p_path) const {
if (!has_node(p_path))
return false;
@@ -2685,23 +2544,21 @@ bool Node::has_node_and_resource(const NodePath& p_path) const {
if (p_path.get_subname_count()) {
RES r;
- for(int j=0;j<p_path.get_subname_count();j++) {
- r = j==0 ? node->get(p_path.get_subname(j)) : r->get(p_path.get_subname(j));
+ for (int j = 0; j < p_path.get_subname_count(); j++) {
+ r = j == 0 ? node->get(p_path.get_subname(j)) : r->get(p_path.get_subname(j));
if (r.is_null())
return false;
}
}
-
return true;
}
-
-Array Node::_get_node_and_resource(const NodePath& p_path) {
+Array Node::_get_node_and_resource(const NodePath &p_path) {
Node *node;
RES res;
- node = get_node_and_resource(p_path,res);
+ node = get_node_and_resource(p_path, res);
Array result;
if (node)
@@ -2717,7 +2574,7 @@ Array Node::_get_node_and_resource(const NodePath& p_path) {
return result;
}
-Node *Node::get_node_and_resource(const NodePath& p_path,RES& r_res) const {
+Node *Node::get_node_and_resource(const NodePath &p_path, RES &r_res) const {
Node *node = get_node(p_path);
r_res = RES();
@@ -2726,9 +2583,9 @@ Node *Node::get_node_and_resource(const NodePath& p_path,RES& r_res) const {
if (p_path.get_subname_count()) {
- for(int j=0;j<p_path.get_subname_count();j++) {
- r_res = j==0 ? node->get(p_path.get_subname(j)) : r_res->get(p_path.get_subname(j));
- ERR_FAIL_COND_V( r_res.is_null(), node );
+ for (int j = 0; j < p_path.get_subname_count(); j++) {
+ r_res = j == 0 ? node->get(p_path.get_subname(j)) : r_res->get(p_path.get_subname(j));
+ ERR_FAIL_COND_V(r_res.is_null(), node);
}
}
@@ -2737,40 +2594,35 @@ Node *Node::get_node_and_resource(const NodePath& p_path,RES& r_res) const {
void Node::_set_tree(SceneTree *p_tree) {
- SceneTree *tree_changed_a=NULL;
- SceneTree *tree_changed_b=NULL;
+ SceneTree *tree_changed_a = NULL;
+ SceneTree *tree_changed_b = NULL;
//ERR_FAIL_COND(p_scene && data.parent && !data.parent->data.scene); //nobug if both are null
if (data.tree) {
_propagate_exit_tree();
- tree_changed_a=data.tree;
+ tree_changed_a = data.tree;
}
-
- data.tree=p_tree;
+ data.tree = p_tree;
if (data.tree) {
-
_propagate_enter_tree();
if (!data.parent || data.parent->data.ready_notified) { // No parent (root) or parent ready
_propagate_ready(); //reverse_notification(NOTIFICATION_READY);
}
- tree_changed_b=data.tree;
-
+ tree_changed_b = data.tree;
}
if (tree_changed_a)
tree_changed_a->tree_changed();
if (tree_changed_b)
tree_changed_b->tree_changed();
-
}
-
static void _Node_debug_sn(Object *p_obj) {
Node *n = p_obj->cast_to<Node>();
@@ -2780,18 +2632,17 @@ static void _Node_debug_sn(Object *p_obj) {
if (n->is_inside_tree())
return;
- Node *p=n;
- while(p->get_parent()) {
- p=p->get_parent();
+ Node *p = n;
+ while (p->get_parent()) {
+ p = p->get_parent();
}
String path;
- if (p==n)
- path=n->get_name();
+ if (p == n)
+ path = n->get_name();
else
- path=String(p->get_name())+"/"+p->get_path_to(n);
- print_line(itos(p_obj->get_instance_ID())+"- Stray Node: "+path+" (Type: "+n->get_class()+")");
-
+ path = String(p->get_name()) + "/" + p->get_path_to(n);
+ print_line(itos(p_obj->get_instance_ID()) + "- Stray Node: " + path + " (Type: " + n->get_class() + ")");
}
void Node::_print_stray_nodes() {
@@ -2809,7 +2660,7 @@ void Node::print_stray_nodes() {
void Node::queue_delete() {
- ERR_FAIL_COND( !is_inside_tree() );
+ ERR_FAIL_COND(!is_inside_tree());
get_tree()->queue_delete(this);
}
@@ -2818,17 +2669,16 @@ Array Node::_get_children() const {
Array arr;
int cc = get_child_count();
arr.resize(cc);
- for(int i=0;i<cc;i++)
- arr[i]=get_child(i);
+ for (int i = 0; i < cc; i++)
+ arr[i] = get_child(i);
return arr;
}
#ifdef TOOLS_ENABLED
-void Node::set_import_path(const NodePath& p_import_path) {
-
+void Node::set_import_path(const NodePath &p_import_path) {
- data.import_path=p_import_path;
+ data.import_path = p_import_path;
}
NodePath Node::get_import_path() const {
@@ -2838,35 +2688,33 @@ NodePath Node::get_import_path() const {
#endif
-static void _add_nodes_to_options(const Node *p_base,const Node *p_node,List<String>*r_options) {
+static void _add_nodes_to_options(const Node *p_base, const Node *p_node, List<String> *r_options) {
- if (p_node!=p_base && !p_node->get_owner())
+ if (p_node != p_base && !p_node->get_owner())
return;
String n = p_base->get_path_to(p_node);
- r_options->push_back("\""+n+"\"");
- for(int i=0;i<p_node->get_child_count();i++) {
- _add_nodes_to_options(p_base,p_node->get_child(i),r_options);
+ r_options->push_back("\"" + n + "\"");
+ for (int i = 0; i < p_node->get_child_count(); i++) {
+ _add_nodes_to_options(p_base, p_node->get_child(i), r_options);
}
}
-void Node::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {
+void Node::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
- String pf=p_function;
- if ((pf=="has_node" || pf=="get_node") && p_idx==0) {
+ String pf = p_function;
+ if ((pf == "has_node" || pf == "get_node") && p_idx == 0) {
- _add_nodes_to_options(this,this,r_options);
+ _add_nodes_to_options(this, this, r_options);
}
- Object::get_argument_options(p_function,p_idx,r_options);
+ Object::get_argument_options(p_function, p_idx, r_options);
}
-
void Node::clear_internal_tree_resource_paths() {
clear_internal_resource_paths();
- for(int i=0;i<data.children.size();i++) {
+ for (int i = 0; i < data.children.size(); i++) {
data.children[i]->clear_internal_tree_resource_paths();
}
-
}
String Node::get_configuration_warning() const {
@@ -2879,11 +2727,10 @@ void Node::update_configuration_warning() {
#ifdef TOOLS_ENABLED
if (!is_inside_tree())
return;
- if (get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()==this || get_tree()->get_edited_scene_root()->is_a_parent_of(this))) {
- get_tree()->emit_signal(SceneStringNames::get_singleton()->node_configuration_warning_changed,this);
+ if (get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root() == this || get_tree()->get_edited_scene_root()->is_a_parent_of(this))) {
+ get_tree()->emit_signal(SceneStringNames::get_singleton()->node_configuration_warning_changed, this);
}
#endif
-
}
bool Node::is_owned_by_parent() const {
@@ -2891,7 +2738,7 @@ bool Node::is_owned_by_parent() const {
}
void Node::set_display_folded(bool p_folded) {
- data.display_folded=p_folded;
+ data.display_folded = p_folded;
}
bool Node::is_displayed_folded() const {
@@ -2900,202 +2747,194 @@ bool Node::is_displayed_folded() const {
}
void Node::request_ready() {
- data.ready_first=true;
+ data.ready_first = true;
}
void Node::_bind_methods() {
- GLOBAL_DEF("node/name_num_separator",0);
- GlobalConfig::get_singleton()->set_custom_property_info("node/name_num_separator",PropertyInfo(Variant::INT,"node/name_num_separator",PROPERTY_HINT_ENUM, "None,Space,Underscore,Dash"));
- GLOBAL_DEF("node/name_casing",NAME_CASING_PASCAL_CASE);
- GlobalConfig::get_singleton()->set_custom_property_info("node/name_casing",PropertyInfo(Variant::INT,"node/name_casing",PROPERTY_HINT_ENUM,"PascalCase,camelCase,snake_case"));
+ GLOBAL_DEF("node/name_num_separator", 0);
+ GlobalConfig::get_singleton()->set_custom_property_info("node/name_num_separator", PropertyInfo(Variant::INT, "node/name_num_separator", PROPERTY_HINT_ENUM, "None,Space,Underscore,Dash"));
+ GLOBAL_DEF("node/name_casing", NAME_CASING_PASCAL_CASE);
+ GlobalConfig::get_singleton()->set_custom_property_info("node/name_casing", PropertyInfo(Variant::INT, "node/name_casing", PROPERTY_HINT_ENUM, "PascalCase,camelCase,snake_case"));
- ClassDB::bind_method(D_METHOD("_add_child_below_node","node:Node","child_node:Node","legible_unique_name"),&Node::add_child_below_node,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("_add_child_below_node", "node:Node", "child_node:Node", "legible_unique_name"), &Node::add_child_below_node, DEFVAL(false));
- ClassDB::bind_method(D_METHOD("set_name","name"),&Node::set_name);
- ClassDB::bind_method(D_METHOD("get_name"),&Node::get_name);
- ClassDB::bind_method(D_METHOD("add_child","node:Node","legible_unique_name"),&Node::add_child,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("remove_child","node:Node"),&Node::remove_child);
+ ClassDB::bind_method(D_METHOD("set_name", "name"), &Node::set_name);
+ ClassDB::bind_method(D_METHOD("get_name"), &Node::get_name);
+ ClassDB::bind_method(D_METHOD("add_child", "node:Node", "legible_unique_name"), &Node::add_child, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("remove_child", "node:Node"), &Node::remove_child);
//ClassDB::bind_method(D_METHOD("remove_and_delete_child","node:Node"),&Node::remove_and_delete_child);
- ClassDB::bind_method(D_METHOD("get_child_count"),&Node::get_child_count);
- ClassDB::bind_method(D_METHOD("get_children"),&Node::_get_children);
- ClassDB::bind_method(D_METHOD("get_child:Node","idx"),&Node::get_child);
- ClassDB::bind_method(D_METHOD("has_node","path"),&Node::has_node);
- ClassDB::bind_method(D_METHOD("get_node:Node","path"),&Node::get_node);
- ClassDB::bind_method(D_METHOD("get_parent:Node"),&Node::get_parent);
- ClassDB::bind_method(D_METHOD("find_node:Node","mask","recursive","owned"),&Node::find_node,DEFVAL(true),DEFVAL(true));
- ClassDB::bind_method(D_METHOD("has_node_and_resource","path"),&Node::has_node_and_resource);
- ClassDB::bind_method(D_METHOD("get_node_and_resource","path"),&Node::_get_node_and_resource);
-
- ClassDB::bind_method(D_METHOD("is_inside_tree"),&Node::is_inside_tree);
- ClassDB::bind_method(D_METHOD("is_a_parent_of","node:Node"),&Node::is_a_parent_of);
- ClassDB::bind_method(D_METHOD("is_greater_than","node:Node"),&Node::is_greater_than);
- ClassDB::bind_method(D_METHOD("get_path"),&Node::get_path);
- ClassDB::bind_method(D_METHOD("get_path_to","node:Node"),&Node::get_path_to);
- ClassDB::bind_method(D_METHOD("add_to_group","group","persistent"),&Node::add_to_group,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("remove_from_group","group"),&Node::remove_from_group);
- ClassDB::bind_method(D_METHOD("is_in_group","group"),&Node::is_in_group);
- ClassDB::bind_method(D_METHOD("move_child","child_node:Node","to_pos"),&Node::move_child);
- ClassDB::bind_method(D_METHOD("get_groups"),&Node::_get_groups);
- ClassDB::bind_method(D_METHOD("raise"),&Node::raise);
- ClassDB::bind_method(D_METHOD("set_owner","owner:Node"),&Node::set_owner);
- ClassDB::bind_method(D_METHOD("get_owner:Node"),&Node::get_owner);
- ClassDB::bind_method(D_METHOD("remove_and_skip"),&Node::remove_and_skip);
- ClassDB::bind_method(D_METHOD("get_index"),&Node::get_index);
- ClassDB::bind_method(D_METHOD("print_tree"),&Node::print_tree);
- ClassDB::bind_method(D_METHOD("set_filename","filename"),&Node::set_filename);
- ClassDB::bind_method(D_METHOD("get_filename"),&Node::get_filename);
- ClassDB::bind_method(D_METHOD("propagate_notification","what"),&Node::propagate_notification);
- ClassDB::bind_method(D_METHOD("set_fixed_process","enable"),&Node::set_fixed_process);
- ClassDB::bind_method(D_METHOD("get_fixed_process_delta_time"),&Node::get_fixed_process_delta_time);
- ClassDB::bind_method(D_METHOD("is_fixed_processing"),&Node::is_fixed_processing);
- ClassDB::bind_method(D_METHOD("get_process_delta_time"),&Node::get_process_delta_time);
- ClassDB::bind_method(D_METHOD("set_process","enable"),&Node::set_process);
- ClassDB::bind_method(D_METHOD("is_processing"),&Node::is_processing);
- ClassDB::bind_method(D_METHOD("set_process_input","enable"),&Node::set_process_input);
- ClassDB::bind_method(D_METHOD("is_processing_input"),&Node::is_processing_input);
- ClassDB::bind_method(D_METHOD("set_process_unhandled_input","enable"),&Node::set_process_unhandled_input);
- ClassDB::bind_method(D_METHOD("is_processing_unhandled_input"),&Node::is_processing_unhandled_input);
- ClassDB::bind_method(D_METHOD("set_process_unhandled_key_input","enable"),&Node::set_process_unhandled_key_input);
- ClassDB::bind_method(D_METHOD("is_processing_unhandled_key_input"),&Node::is_processing_unhandled_key_input);
- ClassDB::bind_method(D_METHOD("set_pause_mode","mode"),&Node::set_pause_mode);
- ClassDB::bind_method(D_METHOD("get_pause_mode"),&Node::get_pause_mode);
- ClassDB::bind_method(D_METHOD("can_process"),&Node::can_process);
- ClassDB::bind_method(D_METHOD("print_stray_nodes"),&Node::_print_stray_nodes);
- ClassDB::bind_method(D_METHOD("get_position_in_parent"),&Node::get_position_in_parent);
- ClassDB::bind_method(D_METHOD("set_display_folded","fold"),&Node::set_display_folded);
- ClassDB::bind_method(D_METHOD("is_displayed_folded"),&Node::is_displayed_folded);
-
- ClassDB::bind_method(D_METHOD("set_process_internal","enable"),&Node::set_process_internal);
- ClassDB::bind_method(D_METHOD("is_processing_internal"),&Node::is_processing_internal);
-
- ClassDB::bind_method(D_METHOD("set_fixed_process_internal","enable"),&Node::set_fixed_process_internal);
- ClassDB::bind_method(D_METHOD("is_fixed_processing_internal"),&Node::is_fixed_processing_internal);
-
- ClassDB::bind_method(D_METHOD("get_tree:SceneTree"),&Node::get_tree);
-
- ClassDB::bind_method(D_METHOD("duplicate:Node","flags"),&Node::duplicate,DEFVAL(DUPLICATE_USE_INSTANCING|DUPLICATE_SIGNALS|DUPLICATE_GROUPS|DUPLICATE_SCRIPTS));
- ClassDB::bind_method(D_METHOD("replace_by","node:Node","keep_data"),&Node::replace_by,DEFVAL(false));
-
- ClassDB::bind_method(D_METHOD("set_scene_instance_load_placeholder","load_placeholder"),&Node::set_scene_instance_load_placeholder);
- ClassDB::bind_method(D_METHOD("get_scene_instance_load_placeholder"),&Node::get_scene_instance_load_placeholder);
-
-
- ClassDB::bind_method(D_METHOD("get_viewport"),&Node::get_viewport);
-
- ClassDB::bind_method(D_METHOD("queue_free"),&Node::queue_delete);
-
- ClassDB::bind_method(D_METHOD("request_ready"),&Node::request_ready);
-
- ClassDB::bind_method(D_METHOD("set_network_mode","mode"),&Node::set_network_mode);
- ClassDB::bind_method(D_METHOD("get_network_mode"),&Node::get_network_mode);
-
- ClassDB::bind_method(D_METHOD("is_network_master"),&Node::is_network_master);
-
- ClassDB::bind_method(D_METHOD("rpc_config","method","mode"),&Node::rpc_config);
- ClassDB::bind_method(D_METHOD("rset_config","property","mode"),&Node::rset_config);
-
+ ClassDB::bind_method(D_METHOD("get_child_count"), &Node::get_child_count);
+ ClassDB::bind_method(D_METHOD("get_children"), &Node::_get_children);
+ ClassDB::bind_method(D_METHOD("get_child:Node", "idx"), &Node::get_child);
+ ClassDB::bind_method(D_METHOD("has_node", "path"), &Node::has_node);
+ ClassDB::bind_method(D_METHOD("get_node:Node", "path"), &Node::get_node);
+ ClassDB::bind_method(D_METHOD("get_parent:Node"), &Node::get_parent);
+ ClassDB::bind_method(D_METHOD("find_node:Node", "mask", "recursive", "owned"), &Node::find_node, DEFVAL(true), DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("has_node_and_resource", "path"), &Node::has_node_and_resource);
+ ClassDB::bind_method(D_METHOD("get_node_and_resource", "path"), &Node::_get_node_and_resource);
+
+ ClassDB::bind_method(D_METHOD("is_inside_tree"), &Node::is_inside_tree);
+ ClassDB::bind_method(D_METHOD("is_a_parent_of", "node:Node"), &Node::is_a_parent_of);
+ ClassDB::bind_method(D_METHOD("is_greater_than", "node:Node"), &Node::is_greater_than);
+ ClassDB::bind_method(D_METHOD("get_path"), &Node::get_path);
+ ClassDB::bind_method(D_METHOD("get_path_to", "node:Node"), &Node::get_path_to);
+ ClassDB::bind_method(D_METHOD("add_to_group", "group", "persistent"), &Node::add_to_group, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("remove_from_group", "group"), &Node::remove_from_group);
+ ClassDB::bind_method(D_METHOD("is_in_group", "group"), &Node::is_in_group);
+ ClassDB::bind_method(D_METHOD("move_child", "child_node:Node", "to_pos"), &Node::move_child);
+ ClassDB::bind_method(D_METHOD("get_groups"), &Node::_get_groups);
+ ClassDB::bind_method(D_METHOD("raise"), &Node::raise);
+ ClassDB::bind_method(D_METHOD("set_owner", "owner:Node"), &Node::set_owner);
+ ClassDB::bind_method(D_METHOD("get_owner:Node"), &Node::get_owner);
+ ClassDB::bind_method(D_METHOD("remove_and_skip"), &Node::remove_and_skip);
+ ClassDB::bind_method(D_METHOD("get_index"), &Node::get_index);
+ ClassDB::bind_method(D_METHOD("print_tree"), &Node::print_tree);
+ ClassDB::bind_method(D_METHOD("set_filename", "filename"), &Node::set_filename);
+ ClassDB::bind_method(D_METHOD("get_filename"), &Node::get_filename);
+ ClassDB::bind_method(D_METHOD("propagate_notification", "what"), &Node::propagate_notification);
+ ClassDB::bind_method(D_METHOD("set_fixed_process", "enable"), &Node::set_fixed_process);
+ ClassDB::bind_method(D_METHOD("get_fixed_process_delta_time"), &Node::get_fixed_process_delta_time);
+ ClassDB::bind_method(D_METHOD("is_fixed_processing"), &Node::is_fixed_processing);
+ ClassDB::bind_method(D_METHOD("get_process_delta_time"), &Node::get_process_delta_time);
+ ClassDB::bind_method(D_METHOD("set_process", "enable"), &Node::set_process);
+ ClassDB::bind_method(D_METHOD("is_processing"), &Node::is_processing);
+ ClassDB::bind_method(D_METHOD("set_process_input", "enable"), &Node::set_process_input);
+ ClassDB::bind_method(D_METHOD("is_processing_input"), &Node::is_processing_input);
+ ClassDB::bind_method(D_METHOD("set_process_unhandled_input", "enable"), &Node::set_process_unhandled_input);
+ ClassDB::bind_method(D_METHOD("is_processing_unhandled_input"), &Node::is_processing_unhandled_input);
+ ClassDB::bind_method(D_METHOD("set_process_unhandled_key_input", "enable"), &Node::set_process_unhandled_key_input);
+ ClassDB::bind_method(D_METHOD("is_processing_unhandled_key_input"), &Node::is_processing_unhandled_key_input);
+ ClassDB::bind_method(D_METHOD("set_pause_mode", "mode"), &Node::set_pause_mode);
+ ClassDB::bind_method(D_METHOD("get_pause_mode"), &Node::get_pause_mode);
+ ClassDB::bind_method(D_METHOD("can_process"), &Node::can_process);
+ ClassDB::bind_method(D_METHOD("print_stray_nodes"), &Node::_print_stray_nodes);
+ ClassDB::bind_method(D_METHOD("get_position_in_parent"), &Node::get_position_in_parent);
+ ClassDB::bind_method(D_METHOD("set_display_folded", "fold"), &Node::set_display_folded);
+ ClassDB::bind_method(D_METHOD("is_displayed_folded"), &Node::is_displayed_folded);
+
+ ClassDB::bind_method(D_METHOD("set_process_internal", "enable"), &Node::set_process_internal);
+ ClassDB::bind_method(D_METHOD("is_processing_internal"), &Node::is_processing_internal);
+
+ ClassDB::bind_method(D_METHOD("set_fixed_process_internal", "enable"), &Node::set_fixed_process_internal);
+ ClassDB::bind_method(D_METHOD("is_fixed_processing_internal"), &Node::is_fixed_processing_internal);
+
+ ClassDB::bind_method(D_METHOD("get_tree:SceneTree"), &Node::get_tree);
+
+ ClassDB::bind_method(D_METHOD("duplicate:Node", "flags"), &Node::duplicate, DEFVAL(DUPLICATE_USE_INSTANCING | DUPLICATE_SIGNALS | DUPLICATE_GROUPS | DUPLICATE_SCRIPTS));
+ ClassDB::bind_method(D_METHOD("replace_by", "node:Node", "keep_data"), &Node::replace_by, DEFVAL(false));
+
+ ClassDB::bind_method(D_METHOD("set_scene_instance_load_placeholder", "load_placeholder"), &Node::set_scene_instance_load_placeholder);
+ ClassDB::bind_method(D_METHOD("get_scene_instance_load_placeholder"), &Node::get_scene_instance_load_placeholder);
+
+ ClassDB::bind_method(D_METHOD("get_viewport"), &Node::get_viewport);
+
+ ClassDB::bind_method(D_METHOD("queue_free"), &Node::queue_delete);
+
+ ClassDB::bind_method(D_METHOD("request_ready"), &Node::request_ready);
+
+ ClassDB::bind_method(D_METHOD("set_network_mode", "mode"), &Node::set_network_mode);
+ ClassDB::bind_method(D_METHOD("get_network_mode"), &Node::get_network_mode);
+
+ ClassDB::bind_method(D_METHOD("is_network_master"), &Node::is_network_master);
+
+ ClassDB::bind_method(D_METHOD("rpc_config", "method", "mode"), &Node::rpc_config);
+ ClassDB::bind_method(D_METHOD("rset_config", "property", "mode"), &Node::rset_config);
#ifdef TOOLS_ENABLED
- ClassDB::bind_method(D_METHOD("_set_import_path","import_path"),&Node::set_import_path);
- ClassDB::bind_method(D_METHOD("_get_import_path"),&Node::get_import_path);
- ADD_PROPERTYNZ( PropertyInfo(Variant::NODE_PATH,"_import_path",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_import_path","_get_import_path");
+ ClassDB::bind_method(D_METHOD("_set_import_path", "import_path"), &Node::set_import_path);
+ ClassDB::bind_method(D_METHOD("_get_import_path"), &Node::get_import_path);
+ ADD_PROPERTYNZ(PropertyInfo(Variant::NODE_PATH, "_import_path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_import_path", "_get_import_path");
#endif
{
MethodInfo mi;
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
+ mi.name = "rpc";
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "rpc", &Node::_rpc_bind, mi);
+ mi.name = "rpc_unreliable";
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "rpc_unreliable", &Node::_rpc_unreliable_bind, mi);
- mi.name="rpc";
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"rpc",&Node::_rpc_bind,mi);
- mi.name="rpc_unreliable";
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"rpc_unreliable",&Node::_rpc_unreliable_bind,mi);
-
- mi.arguments.push_front( PropertyInfo( Variant::INT, "peer_id") );
-
- mi.name="rpc_id";
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"rpc_id",&Node::_rpc_id_bind,mi);
- mi.name="rpc_unreliable_id";
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"rpc_unreliable_id",&Node::_rpc_unreliable_id_bind,mi);
-
+ mi.arguments.push_front(PropertyInfo(Variant::INT, "peer_id"));
+ mi.name = "rpc_id";
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "rpc_id", &Node::_rpc_id_bind, mi);
+ mi.name = "rpc_unreliable_id";
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "rpc_unreliable_id", &Node::_rpc_unreliable_id_bind, mi);
}
- ClassDB::bind_method(D_METHOD("rset","property","value:Variant"),&Node::rset);
- ClassDB::bind_method(D_METHOD("rset_id","peer_id","property","value:Variant"),&Node::rset_id);
- ClassDB::bind_method(D_METHOD("rset_unreliable","property","value:Variant"),&Node::rset_unreliable);
- ClassDB::bind_method(D_METHOD("rset_unreliable_id","peer_id","property","value:Variant"),&Node::rset_unreliable_id);
-
+ ClassDB::bind_method(D_METHOD("rset", "property", "value:Variant"), &Node::rset);
+ ClassDB::bind_method(D_METHOD("rset_id", "peer_id", "property", "value:Variant"), &Node::rset_id);
+ ClassDB::bind_method(D_METHOD("rset_unreliable", "property", "value:Variant"), &Node::rset_unreliable);
+ ClassDB::bind_method(D_METHOD("rset_unreliable_id", "peer_id", "property", "value:Variant"), &Node::rset_unreliable_id);
- BIND_CONSTANT( NOTIFICATION_ENTER_TREE );
- BIND_CONSTANT( NOTIFICATION_EXIT_TREE );
- BIND_CONSTANT( NOTIFICATION_MOVED_IN_PARENT );
+ BIND_CONSTANT(NOTIFICATION_ENTER_TREE);
+ BIND_CONSTANT(NOTIFICATION_EXIT_TREE);
+ BIND_CONSTANT(NOTIFICATION_MOVED_IN_PARENT);
//BIND_CONSTANT( NOTIFICATION_PARENT_DECONFIGURED );
- BIND_CONSTANT( NOTIFICATION_READY );
- BIND_CONSTANT( NOTIFICATION_FIXED_PROCESS );
- BIND_CONSTANT( NOTIFICATION_PROCESS );
- BIND_CONSTANT( NOTIFICATION_PARENTED );
- BIND_CONSTANT( NOTIFICATION_UNPARENTED );
- BIND_CONSTANT( NOTIFICATION_PAUSED );
- BIND_CONSTANT( NOTIFICATION_UNPAUSED );
- BIND_CONSTANT( NOTIFICATION_INSTANCED );
- BIND_CONSTANT( NOTIFICATION_DRAG_BEGIN );
- BIND_CONSTANT( NOTIFICATION_DRAG_END );
- BIND_CONSTANT( NOTIFICATION_PATH_CHANGED);
- BIND_CONSTANT( NOTIFICATION_TRANSLATION_CHANGED );
- BIND_CONSTANT( NOTIFICATION_INTERNAL_PROCESS );
- BIND_CONSTANT( NOTIFICATION_INTERNAL_FIXED_PROCESS );
-
-
- BIND_CONSTANT( NETWORK_MODE_INHERIT );
- BIND_CONSTANT( NETWORK_MODE_MASTER );
- BIND_CONSTANT( NETWORK_MODE_SLAVE );
-
- BIND_CONSTANT( RPC_MODE_DISABLED );
- BIND_CONSTANT( RPC_MODE_REMOTE );
- BIND_CONSTANT( RPC_MODE_SYNC );
- BIND_CONSTANT( RPC_MODE_MASTER );
- BIND_CONSTANT( RPC_MODE_SLAVE );
-
- BIND_CONSTANT( PAUSE_MODE_INHERIT );
- BIND_CONSTANT( PAUSE_MODE_STOP );
- BIND_CONSTANT( PAUSE_MODE_PROCESS );
-
- BIND_CONSTANT( DUPLICATE_SIGNALS );
- BIND_CONSTANT( DUPLICATE_GROUPS );
- BIND_CONSTANT( DUPLICATE_SCRIPTS );
-
- ADD_SIGNAL( MethodInfo("renamed") );
- ADD_SIGNAL( MethodInfo("tree_entered") );
- ADD_SIGNAL( MethodInfo("tree_exited") );
+ BIND_CONSTANT(NOTIFICATION_READY);
+ BIND_CONSTANT(NOTIFICATION_FIXED_PROCESS);
+ BIND_CONSTANT(NOTIFICATION_PROCESS);
+ BIND_CONSTANT(NOTIFICATION_PARENTED);
+ BIND_CONSTANT(NOTIFICATION_UNPARENTED);
+ BIND_CONSTANT(NOTIFICATION_PAUSED);
+ BIND_CONSTANT(NOTIFICATION_UNPAUSED);
+ BIND_CONSTANT(NOTIFICATION_INSTANCED);
+ BIND_CONSTANT(NOTIFICATION_DRAG_BEGIN);
+ BIND_CONSTANT(NOTIFICATION_DRAG_END);
+ BIND_CONSTANT(NOTIFICATION_PATH_CHANGED);
+ BIND_CONSTANT(NOTIFICATION_TRANSLATION_CHANGED);
+ BIND_CONSTANT(NOTIFICATION_INTERNAL_PROCESS);
+ BIND_CONSTANT(NOTIFICATION_INTERNAL_FIXED_PROCESS);
+
+ BIND_CONSTANT(NETWORK_MODE_INHERIT);
+ BIND_CONSTANT(NETWORK_MODE_MASTER);
+ BIND_CONSTANT(NETWORK_MODE_SLAVE);
+
+ BIND_CONSTANT(RPC_MODE_DISABLED);
+ BIND_CONSTANT(RPC_MODE_REMOTE);
+ BIND_CONSTANT(RPC_MODE_SYNC);
+ BIND_CONSTANT(RPC_MODE_MASTER);
+ BIND_CONSTANT(RPC_MODE_SLAVE);
+
+ BIND_CONSTANT(PAUSE_MODE_INHERIT);
+ BIND_CONSTANT(PAUSE_MODE_STOP);
+ BIND_CONSTANT(PAUSE_MODE_PROCESS);
+
+ BIND_CONSTANT(DUPLICATE_SIGNALS);
+ BIND_CONSTANT(DUPLICATE_GROUPS);
+ BIND_CONSTANT(DUPLICATE_SCRIPTS);
+
+ ADD_SIGNAL(MethodInfo("renamed"));
+ ADD_SIGNAL(MethodInfo("tree_entered"));
+ ADD_SIGNAL(MethodInfo("tree_exited"));
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/process" ),"set_process","is_processing") ;
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/fixed_process" ), "set_fixed_process","is_fixed_processing") ;
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/input" ), "set_process_input","is_processing_input" ) ;
//ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "process/unhandled_input" ), "set_process_unhandled_input","is_processing_unhandled_input" ) ;
- ADD_GROUP("Pause","pause_");
- ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "pause_mode",PROPERTY_HINT_ENUM,"Inherit,Stop,Process" ), "set_pause_mode", "get_pause_mode" );
- ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "editor/display_folded",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR ), "set_display_folded", "is_displayed_folded");
-
- BIND_VMETHOD( MethodInfo("_process",PropertyInfo(Variant::REAL,"delta")) );
- BIND_VMETHOD( MethodInfo("_fixed_process",PropertyInfo(Variant::REAL,"delta")) );
- BIND_VMETHOD( MethodInfo("_enter_tree") );
- BIND_VMETHOD( MethodInfo("_exit_tree") );
- BIND_VMETHOD( MethodInfo("_ready") );
- BIND_VMETHOD( MethodInfo("_input",PropertyInfo(Variant::INPUT_EVENT,"event")) );
- BIND_VMETHOD( MethodInfo("_unhandled_input",PropertyInfo(Variant::INPUT_EVENT,"event")) );
- BIND_VMETHOD( MethodInfo("_unhandled_key_input",PropertyInfo(Variant::INPUT_EVENT,"key_event")) );
+ ADD_GROUP("Pause", "pause_");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::INT, "pause_mode", PROPERTY_HINT_ENUM, "Inherit,Stop,Process"), "set_pause_mode", "get_pause_mode");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "editor/display_folded", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_display_folded", "is_displayed_folded");
+
+ BIND_VMETHOD(MethodInfo("_process", PropertyInfo(Variant::REAL, "delta")));
+ BIND_VMETHOD(MethodInfo("_fixed_process", PropertyInfo(Variant::REAL, "delta")));
+ BIND_VMETHOD(MethodInfo("_enter_tree"));
+ BIND_VMETHOD(MethodInfo("_exit_tree"));
+ BIND_VMETHOD(MethodInfo("_ready"));
+ BIND_VMETHOD(MethodInfo("_input", PropertyInfo(Variant::INPUT_EVENT, "event")));
+ BIND_VMETHOD(MethodInfo("_unhandled_input", PropertyInfo(Variant::INPUT_EVENT, "event")));
+ BIND_VMETHOD(MethodInfo("_unhandled_key_input", PropertyInfo(Variant::INPUT_EVENT, "key_event")));
//ClassDB::bind_method(D_METHOD("get_child",&Node::get_child,PH("index")));
//ClassDB::bind_method(D_METHOD("get_node",&Node::get_node,PH("path")));
}
-
String Node::_get_name_num_separator() {
- switch(GlobalConfig::get_singleton()->get("node/name_num_separator").operator int()) {
+ switch (GlobalConfig::get_singleton()->get("node/name_num_separator").operator int()) {
case 0: return "";
case 1: return " ";
case 2: return "_";
@@ -3104,53 +2943,46 @@ String Node::_get_name_num_separator() {
return " ";
}
-
Node::Node() {
- data.pos=-1;
- data.depth=-1;
- data.blocked=0;
- data.parent=NULL;
- data.tree=NULL;
- data.fixed_process=false;
- data.idle_process=false;
- data.fixed_process_internal=false;
- data.idle_process_internal=false;
- data.inside_tree=false;
- data.ready_notified=false;
-
- data.owner=NULL;
- data.OW=NULL;
- data.input=false;
- data.unhandled_input=false;
- data.unhandled_key_input=false;
- data.pause_mode=PAUSE_MODE_INHERIT;
- data.pause_owner=NULL;
- data.network_mode=NETWORK_MODE_INHERIT;
- data.network_owner=NULL;
- data.path_cache=NULL;
- data.parent_owned=false;
- data.in_constructor=true;
- data.viewport=NULL;
- data.use_placeholder=false;
- data.display_folded=false;
- data.ready_first=true;
-
+ data.pos = -1;
+ data.depth = -1;
+ data.blocked = 0;
+ data.parent = NULL;
+ data.tree = NULL;
+ data.fixed_process = false;
+ data.idle_process = false;
+ data.fixed_process_internal = false;
+ data.idle_process_internal = false;
+ data.inside_tree = false;
+ data.ready_notified = false;
+
+ data.owner = NULL;
+ data.OW = NULL;
+ data.input = false;
+ data.unhandled_input = false;
+ data.unhandled_key_input = false;
+ data.pause_mode = PAUSE_MODE_INHERIT;
+ data.pause_owner = NULL;
+ data.network_mode = NETWORK_MODE_INHERIT;
+ data.network_owner = NULL;
+ data.path_cache = NULL;
+ data.parent_owned = false;
+ data.in_constructor = true;
+ data.viewport = NULL;
+ data.use_placeholder = false;
+ data.display_folded = false;
+ data.ready_first = true;
}
Node::~Node() {
-
data.grouped.clear();
data.owned.clear();
data.children.clear();
-
ERR_FAIL_COND(data.parent);
ERR_FAIL_COND(data.children.size());
-
-
}
-
////////////////////////////////
diff --git a/scene/main/node.h b/scene/main/node.h
index b042cabb6f..714a58bd82 100644
--- a/scene/main/node.h
+++ b/scene/main/node.h
@@ -29,24 +29,22 @@
#ifndef NODE_H
#define NODE_H
+#include "class_db.h"
#include "global_config.h"
+#include "map.h"
#include "object.h"
#include "path_db.h"
-#include "map.h"
-#include "class_db.h"
-#include "script_language.h"
#include "scene/main/scene_main_loop.h"
-
+#include "script_language.h"
class Viewport;
class SceneState;
class Node : public Object {
- GDCLASS( Node, Object );
+ GDCLASS(Node, Object);
OBJ_CATEGORY("Nodes");
public:
-
enum PauseMode {
PAUSE_MODE_INHERIT,
@@ -56,10 +54,10 @@ public:
enum DuplicateFlags {
- DUPLICATE_SIGNALS=1,
- DUPLICATE_GROUPS=2,
- DUPLICATE_SCRIPTS=4,
- DUPLICATE_USE_INSTANCING=8
+ DUPLICATE_SIGNALS = 1,
+ DUPLICATE_GROUPS = 2,
+ DUPLICATE_SCRIPTS = 4,
+ DUPLICATE_USE_INSTANCING = 8
};
enum NetworkMode {
@@ -80,31 +78,28 @@ public:
struct Comparator {
- bool operator()(const Node* p_a, const Node* p_b) const { return p_b->is_greater_than(p_a); }
+ bool operator()(const Node *p_a, const Node *p_b) const { return p_b->is_greater_than(p_a); }
};
private:
-
struct GroupData {
bool persistent;
SceneTree::Group *group;
- GroupData() { persistent=false; }
+ GroupData() { persistent = false; }
};
-
-
struct Data {
String filename;
Ref<SceneState> instance_state;
Ref<SceneState> inherited_state;
- HashMap<NodePath,int> editable_instances;
+ HashMap<NodePath, int> editable_instances;
Node *parent;
Node *owner;
- Vector<Node*> children; // list of children
+ Vector<Node *> children; // list of children
int pos;
int depth;
int blocked; // safeguard that throws an error when attempting to modify the tree in a harmful way while being traversed.
@@ -119,19 +114,17 @@ private:
Viewport *viewport;
-
- Map< StringName, GroupData> grouped;
- List<Node*>::Element *OW; // owned element
- List<Node*> owned;
+ Map<StringName, GroupData> grouped;
+ List<Node *>::Element *OW; // owned element
+ List<Node *> owned;
PauseMode pause_mode;
Node *pause_owner;
NetworkMode network_mode;
Node *network_owner;
- Map<StringName,RPCMode> rpc_methods;
- Map<StringName,RPCMode> rpc_properties;
-
+ Map<StringName, RPCMode> rpc_methods;
+ Map<StringName, RPCMode> rpc_properties;
// variables used to properly sort the node when processing, ignored otherwise
//should move all the stuff below to bits
@@ -161,15 +154,14 @@ private:
NAME_CASING_SNAKE_CASE
};
-
void _print_tree(const Node *p_node);
- Node *_get_node(const NodePath& p_path) const;
- Node *_get_child_by_name(const StringName& p_name) const;
+ Node *_get_node(const NodePath &p_path) const;
+ Node *_get_child_by_name(const StringName &p_name) const;
- void _replace_connections_target(Node* p_new_target);
+ void _replace_connections_target(Node *p_new_target);
- void _validate_child_name(Node *p_child, bool p_force_human_readable=false);
+ void _validate_child_name(Node *p_child, bool p_force_human_readable = false);
String _generate_serial_child_name(Node *p_child);
void _propagate_reverse_notification(int p_notification);
@@ -179,29 +171,29 @@ private:
void _propagate_exit_tree();
void _propagate_validate_owner();
void _print_stray_nodes();
- void _propagate_pause_owner(Node*p_owner);
- void _propagate_network_owner(Node*p_owner);
- Array _get_node_and_resource(const NodePath& p_path);
+ void _propagate_pause_owner(Node *p_owner);
+ void _propagate_network_owner(Node *p_owner);
+ Array _get_node_and_resource(const NodePath &p_path);
- void _duplicate_signals(const Node* p_original,Node* p_copy) const;
- void _duplicate_and_reown(Node* p_new_parent, const Map<Node*,Node*>& p_reown_map) const;
+ void _duplicate_signals(const Node *p_original, Node *p_copy) const;
+ void _duplicate_and_reown(Node *p_new_parent, const Map<Node *, Node *> &p_reown_map) const;
Node *_duplicate(int p_flags) const;
Array _get_children() const;
Array _get_groups() const;
- Variant _rpc_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _rpc_unreliable_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _rpc_id_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _rpc_unreliable_id_bind(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
+ Variant _rpc_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _rpc_unreliable_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _rpc_id_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _rpc_unreliable_id_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
-friend class SceneTree;
+ friend class SceneTree;
void _set_tree(SceneTree *p_tree);
-protected:
+protected:
void _block() { data.blocked++; }
- void _unblock() { data.blocked--; }
+ void _unblock() { data.blocked--; }
void _notification(int p_notification);
@@ -210,37 +202,36 @@ protected:
virtual void move_child_notify(Node *p_child);
//void remove_and_delete_child(Node *p_child);
- void _propagate_replace_owner(Node *p_owner,Node* p_by_owner);
+ void _propagate_replace_owner(Node *p_owner, Node *p_by_owner);
static void _bind_methods();
static String _get_name_num_separator();
-friend class SceneState;
+ friend class SceneState;
- void _add_child_nocheck(Node* p_child,const StringName& p_name);
- void _set_owner_nocheck(Node* p_owner);
- void _set_name_nocheck(const StringName& p_name);
+ void _add_child_nocheck(Node *p_child, const StringName &p_name);
+ void _set_owner_nocheck(Node *p_owner);
+ void _set_name_nocheck(const StringName &p_name);
public:
-
enum {
// you can make your own, but don't use the same numbers as other notifications in other nodes
- NOTIFICATION_ENTER_TREE=10,
- NOTIFICATION_EXIT_TREE =11,
- NOTIFICATION_MOVED_IN_PARENT =12,
- NOTIFICATION_READY=13,
+ NOTIFICATION_ENTER_TREE = 10,
+ NOTIFICATION_EXIT_TREE = 11,
+ NOTIFICATION_MOVED_IN_PARENT = 12,
+ NOTIFICATION_READY = 13,
//NOTIFICATION_PARENT_DECONFIGURED =15, - it's confusing, it's going away
- NOTIFICATION_PAUSED=14,
- NOTIFICATION_UNPAUSED=15,
+ NOTIFICATION_PAUSED = 14,
+ NOTIFICATION_UNPAUSED = 15,
NOTIFICATION_FIXED_PROCESS = 16,
NOTIFICATION_PROCESS = 17,
- NOTIFICATION_PARENTED=18,
- NOTIFICATION_UNPARENTED=19,
- NOTIFICATION_INSTANCED=20,
- NOTIFICATION_DRAG_BEGIN=21,
- NOTIFICATION_DRAG_END=22,
- NOTIFICATION_PATH_CHANGED=23,
- NOTIFICATION_TRANSLATION_CHANGED=24,
+ NOTIFICATION_PARENTED = 18,
+ NOTIFICATION_UNPARENTED = 19,
+ NOTIFICATION_INSTANCED = 20,
+ NOTIFICATION_DRAG_BEGIN = 21,
+ NOTIFICATION_DRAG_END = 22,
+ NOTIFICATION_PATH_CHANGED = 23,
+ NOTIFICATION_TRANSLATION_CHANGED = 24,
NOTIFICATION_INTERNAL_PROCESS = 25,
NOTIFICATION_INTERNAL_FIXED_PROCESS = 26,
@@ -249,22 +240,25 @@ public:
/* NODE/TREE */
StringName get_name() const;
- void set_name(const String& p_name);
+ void set_name(const String &p_name);
- void add_child(Node *p_child,bool p_legible_unique_name=false);
- void add_child_below_node(Node *p_node, Node *p_child, bool p_legible_unique_name=false);
+ void add_child(Node *p_child, bool p_legible_unique_name = false);
+ void add_child_below_node(Node *p_node, Node *p_child, bool p_legible_unique_name = false);
void remove_child(Node *p_child);
int get_child_count() const;
Node *get_child(int p_index) const;
- bool has_node(const NodePath& p_path) const;
- Node *get_node(const NodePath& p_path) const;
- Node* find_node(const String& p_mask,bool p_recursive=true,bool p_owned=true) const;
- bool has_node_and_resource(const NodePath& p_path) const;
- Node *get_node_and_resource(const NodePath& p_path,RES& r_res) const;
+ bool has_node(const NodePath &p_path) const;
+ Node *get_node(const NodePath &p_path) const;
+ Node *find_node(const String &p_mask, bool p_recursive = true, bool p_owned = true) const;
+ bool has_node_and_resource(const NodePath &p_path) const;
+ Node *get_node_and_resource(const NodePath &p_path, RES &r_res) const;
Node *get_parent() const;
- _FORCE_INLINE_ SceneTree *get_tree() const { ERR_FAIL_COND_V( !data.tree, NULL ); return data.tree; }
+ _FORCE_INLINE_ SceneTree *get_tree() const {
+ ERR_FAIL_COND_V(!data.tree, NULL);
+ return data.tree;
+ }
_FORCE_INLINE_ bool is_inside_tree() const { return data.inside_tree; }
@@ -273,11 +267,11 @@ public:
NodePath get_path() const;
NodePath get_path_to(const Node *p_node) const;
- Node* find_common_parent_with(const Node *p_node) const;
+ Node *find_common_parent_with(const Node *p_node) const;
- void add_to_group(const StringName& p_identifier,bool p_persistent=false);
- void remove_from_group(const StringName& p_identifier);
- bool is_in_group(const StringName& p_identifier) const;
+ void add_to_group(const StringName &p_identifier, bool p_persistent = false);
+ void remove_from_group(const StringName &p_identifier);
+ bool is_in_group(const StringName &p_identifier) const;
struct GroupInfo {
@@ -288,27 +282,25 @@ public:
void get_groups(List<GroupInfo> *p_groups) const;
bool has_persistent_groups() const;
- void move_child(Node *p_child,int p_pos);
+ void move_child(Node *p_child, int p_pos);
void raise();
void set_owner(Node *p_owner);
Node *get_owner() const;
- void get_owned_by(Node *p_by,List<Node*> *p_owned);
-
+ void get_owned_by(Node *p_by, List<Node *> *p_owned);
void remove_and_skip();
int get_index() const;
void print_tree();
- void set_filename(const String& p_filename);
+ void set_filename(const String &p_filename);
String get_filename() const;
- void set_editable_instance(Node* p_node,bool p_editable);
- bool is_editable_instance(Node* p_node) const;
- void set_editable_instances(const HashMap<NodePath,int>& p_editable_instances);
- HashMap<NodePath,int> get_editable_instances() const;
-
+ void set_editable_instance(Node *p_node, bool p_editable);
+ bool is_editable_instance(Node *p_node) const;
+ void set_editable_instances(const HashMap<NodePath, int> &p_editable_instances);
+ HashMap<NodePath, int> get_editable_instances() const;
/* NOTIFICATIONS */
@@ -340,16 +332,16 @@ public:
int get_position_in_parent() const;
- Node *duplicate(int p_flags=DUPLICATE_GROUPS|DUPLICATE_SIGNALS|DUPLICATE_SCRIPTS) const;
- Node *duplicate_and_reown(const Map<Node*,Node*>& p_reown_map) const;
+ Node *duplicate(int p_flags = DUPLICATE_GROUPS | DUPLICATE_SIGNALS | DUPLICATE_SCRIPTS) const;
+ Node *duplicate_and_reown(const Map<Node *, Node *> &p_reown_map) const;
//Node *clone_tree() const;
// used by editors, to save what has changed only
- void set_scene_instance_state(const Ref<SceneState>& p_state);
+ void set_scene_instance_state(const Ref<SceneState> &p_state);
Ref<SceneState> get_scene_instance_state() const;
- void set_scene_inherited_state(const Ref<SceneState>& p_state);
+ void set_scene_inherited_state(const Ref<SceneState> &p_state);
Ref<SceneState> get_scene_inherited_state() const;
void set_scene_instance_load_placeholder(bool p_enable);
@@ -357,7 +349,7 @@ public:
static Vector<Variant> make_binds(VARIANT_ARG_LIST);
- void replace_by(Node* p_node,bool p_keep_data=false);
+ void replace_by(Node *p_node, bool p_keep_data = false);
void set_pause_mode(PauseMode p_mode);
PauseMode get_pause_mode() const;
@@ -368,25 +360,25 @@ public:
static void print_stray_nodes();
#ifdef TOOLS_ENABLED
- String validate_child_name(Node* p_child);
+ String validate_child_name(Node *p_child);
#endif
void queue_delete();
-//shitty hacks for speed
+ //shitty hacks for speed
static void set_human_readable_collision_renaming(bool p_enabled);
static void init_node_hrcr();
- void force_parent_owned() { data.parent_owned=true; } //hack to avoid duplicate nodes
+ void force_parent_owned() { data.parent_owned = true; } //hack to avoid duplicate nodes
#ifdef TOOLS_ENABLED
- void set_import_path(const NodePath& p_import_path); //path used when imported, used by scene editors to keep tracking
+ void set_import_path(const NodePath &p_import_path); //path used when imported, used by scene editors to keep tracking
NodePath get_import_path() const;
#endif
bool is_owned_by_parent() const;
- void get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const;
+ void get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const;
void clear_internal_tree_resource_paths();
@@ -404,33 +396,30 @@ public:
NetworkMode get_network_mode() const;
bool is_network_master() const;
- void rpc_config(const StringName& p_method,RPCMode p_mode); // config a local method for RPC
- void rset_config(const StringName& p_property,RPCMode p_mode); // config a local property for RPC
-
- void rpc(const StringName& p_method,VARIANT_ARG_LIST); //rpc call, honors RPCMode
- void rpc_unreliable(const StringName& p_method,VARIANT_ARG_LIST); //rpc call, honors RPCMode
- void rpc_id(int p_peer_id,const StringName& p_method,VARIANT_ARG_LIST); //rpc call, honors RPCMode
- void rpc_unreliable_id(int p_peer_id,const StringName& p_method,VARIANT_ARG_LIST); //rpc call, honors RPCMode
+ void rpc_config(const StringName &p_method, RPCMode p_mode); // config a local method for RPC
+ void rset_config(const StringName &p_property, RPCMode p_mode); // config a local property for RPC
- void rpcp(int p_peer_id,bool p_unreliable,const StringName& p_method,const Variant** p_arg,int p_argcount);
+ void rpc(const StringName &p_method, VARIANT_ARG_LIST); //rpc call, honors RPCMode
+ void rpc_unreliable(const StringName &p_method, VARIANT_ARG_LIST); //rpc call, honors RPCMode
+ void rpc_id(int p_peer_id, const StringName &p_method, VARIANT_ARG_LIST); //rpc call, honors RPCMode
+ void rpc_unreliable_id(int p_peer_id, const StringName &p_method, VARIANT_ARG_LIST); //rpc call, honors RPCMode
- void rset(const StringName& p_property, const Variant& p_value); //remote set call, honors RPCMode
- void rset_unreliable(const StringName& p_property,const Variant& p_value); //remote set call, honors RPCMode
- void rset_id(int p_peer_id,const StringName& p_property,const Variant& p_value); //remote set call, honors RPCMode
- void rset_unreliable_id(int p_peer_id,const StringName& p_property,const Variant& p_value); //remote set call, honors RPCMode
+ void rpcp(int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount);
- void rsetp(int p_peer_id,bool p_unreliable,const StringName& p_property,const Variant& p_value);
+ void rset(const StringName &p_property, const Variant &p_value); //remote set call, honors RPCMode
+ void rset_unreliable(const StringName &p_property, const Variant &p_value); //remote set call, honors RPCMode
+ void rset_id(int p_peer_id, const StringName &p_property, const Variant &p_value); //remote set call, honors RPCMode
+ void rset_unreliable_id(int p_peer_id, const StringName &p_property, const Variant &p_value); //remote set call, honors RPCMode
- bool can_call_rpc(const StringName& p_method) const;
- bool can_call_rset(const StringName& p_property) const;
+ void rsetp(int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value);
+ bool can_call_rpc(const StringName &p_method) const;
+ bool can_call_rset(const StringName &p_property) const;
Node();
~Node();
};
-
-typedef Set<Node*,Node::Comparator> NodeSet;
-
+typedef Set<Node *, Node::Comparator> NodeSet;
#endif
diff --git a/scene/main/resource_preloader.cpp b/scene/main/resource_preloader.cpp
index 29333ff4bc..c08a6bcd5b 100644
--- a/scene/main/resource_preloader.cpp
+++ b/scene/main/resource_preloader.cpp
@@ -28,26 +28,25 @@
/*************************************************************************/
#include "resource_preloader.h"
-void ResourcePreloader::_set_resources(const Array& p_data) {
+void ResourcePreloader::_set_resources(const Array &p_data) {
resources.clear();
- ERR_FAIL_COND(p_data.size()!=2);
- PoolVector<String> names=p_data[0];
- Array resdata=p_data[1];
+ ERR_FAIL_COND(p_data.size() != 2);
+ PoolVector<String> names = p_data[0];
+ Array resdata = p_data[1];
- ERR_FAIL_COND(names.size()!=resdata.size());
+ ERR_FAIL_COND(names.size() != resdata.size());
- for(int i=0;i<resdata.size();i++) {
+ for (int i = 0; i < resdata.size(); i++) {
- String name=names[i];
+ String name = names[i];
RES resource = resdata[i];
- ERR_CONTINUE( !resource.is_valid() );
- resources[name]=resource;
+ ERR_CONTINUE(!resource.is_valid());
+ resources[name] = resource;
//add_resource(name,resource);
}
-
}
Array ResourcePreloader::_get_resources() const {
@@ -59,15 +58,15 @@ Array ResourcePreloader::_get_resources() const {
Set<String> sorted_names;
- for(Map<StringName,RES >::Element *E=resources.front();E;E=E->next()) {
+ for (Map<StringName, RES>::Element *E = resources.front(); E; E = E->next()) {
sorted_names.insert(E->key());
}
- int i=0;
- for(Set<String>::Element *E=sorted_names.front();E;E=E->next()) {
+ int i = 0;
+ for (Set<String>::Element *E = sorted_names.front(); E; E = E->next()) {
- names.set(i,E->get());
- arr[i]=resources[E->get()];
+ names.set(i, E->get());
+ arr[i] = resources[E->get()];
i++;
}
@@ -77,65 +76,54 @@ Array ResourcePreloader::_get_resources() const {
return res;
}
-
-void ResourcePreloader::add_resource(const StringName& p_name,const RES& p_resource) {
-
+void ResourcePreloader::add_resource(const StringName &p_name, const RES &p_resource) {
ERR_FAIL_COND(p_resource.is_null());
if (resources.has(p_name)) {
-
StringName new_name;
- int idx=2;
+ int idx = 2;
- while(true) {
+ while (true) {
- new_name=p_name.operator String()+" "+itos(idx);
+ new_name = p_name.operator String() + " " + itos(idx);
if (resources.has(new_name)) {
idx++;
continue;
}
break;
-
}
- add_resource(new_name,p_resource);
+ add_resource(new_name, p_resource);
} else {
- resources[p_name]=p_resource;
+ resources[p_name] = p_resource;
}
-
-
-
}
-void ResourcePreloader::remove_resource(const StringName& p_name) {
+void ResourcePreloader::remove_resource(const StringName &p_name) {
- ERR_FAIL_COND( !resources.has(p_name) );
+ ERR_FAIL_COND(!resources.has(p_name));
resources.erase(p_name);
-
}
-void ResourcePreloader::rename_resource(const StringName& p_from_name,const StringName& p_to_name) {
+void ResourcePreloader::rename_resource(const StringName &p_from_name, const StringName &p_to_name) {
- ERR_FAIL_COND( !resources.has(p_from_name) );
+ ERR_FAIL_COND(!resources.has(p_from_name));
RES res = resources[p_from_name];
resources.erase(p_from_name);
- add_resource(p_to_name,res);
-
-
-
+ add_resource(p_to_name, res);
}
-bool ResourcePreloader::has_resource(const StringName& p_name) const {
+bool ResourcePreloader::has_resource(const StringName &p_name) const {
return resources.has(p_name);
}
-RES ResourcePreloader::get_resource(const StringName& p_name) const {
+RES ResourcePreloader::get_resource(const StringName &p_name) const {
- ERR_FAIL_COND_V(!resources.has(p_name),RES());
+ ERR_FAIL_COND_V(!resources.has(p_name), RES());
return resources[p_name];
}
@@ -143,9 +131,9 @@ PoolVector<String> ResourcePreloader::_get_resource_list() const {
PoolVector<String> res;
res.resize(resources.size());
- int i=0;
- for(Map<StringName,RES >::Element *E=resources.front();E;E=E->next(),i++) {
- res.set(i,E->key());
+ int i = 0;
+ for (Map<StringName, RES>::Element *E = resources.front(); E; E = E->next(), i++) {
+ res.set(i, E->key());
}
return res;
@@ -153,31 +141,26 @@ PoolVector<String> ResourcePreloader::_get_resource_list() const {
void ResourcePreloader::get_resource_list(List<StringName> *p_list) {
- for(Map<StringName,RES >::Element *E=resources.front();E;E=E->next()) {
+ for (Map<StringName, RES>::Element *E = resources.front(); E; E = E->next()) {
p_list->push_back(E->key());
}
-
}
-
void ResourcePreloader::_bind_methods() {
- ClassDB::bind_method(D_METHOD("_set_resources"),&ResourcePreloader::_set_resources);
- ClassDB::bind_method(D_METHOD("_get_resources"),&ResourcePreloader::_get_resources);
-
- ClassDB::bind_method(D_METHOD("add_resource","name","resource"),&ResourcePreloader::add_resource);
- ClassDB::bind_method(D_METHOD("remove_resource","name"),&ResourcePreloader::remove_resource);
- ClassDB::bind_method(D_METHOD("rename_resource","name","newname"),&ResourcePreloader::rename_resource);
- ClassDB::bind_method(D_METHOD("has_resource","name"),&ResourcePreloader::has_resource);
- ClassDB::bind_method(D_METHOD("get_resource","name"),&ResourcePreloader::get_resource);
- ClassDB::bind_method(D_METHOD("get_resource_list"),&ResourcePreloader::_get_resource_list);
-
+ ClassDB::bind_method(D_METHOD("_set_resources"), &ResourcePreloader::_set_resources);
+ ClassDB::bind_method(D_METHOD("_get_resources"), &ResourcePreloader::_get_resources);
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"resources",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_resources", "_get_resources");
+ ClassDB::bind_method(D_METHOD("add_resource", "name", "resource"), &ResourcePreloader::add_resource);
+ ClassDB::bind_method(D_METHOD("remove_resource", "name"), &ResourcePreloader::remove_resource);
+ ClassDB::bind_method(D_METHOD("rename_resource", "name", "newname"), &ResourcePreloader::rename_resource);
+ ClassDB::bind_method(D_METHOD("has_resource", "name"), &ResourcePreloader::has_resource);
+ ClassDB::bind_method(D_METHOD("get_resource", "name"), &ResourcePreloader::get_resource);
+ ClassDB::bind_method(D_METHOD("get_resource_list"), &ResourcePreloader::_get_resource_list);
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "resources", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_resources", "_get_resources");
}
-ResourcePreloader::ResourcePreloader()
-{
+ResourcePreloader::ResourcePreloader() {
}
diff --git a/scene/main/resource_preloader.h b/scene/main/resource_preloader.h
index 4e585d1751..5fba70c1c0 100644
--- a/scene/main/resource_preloader.h
+++ b/scene/main/resource_preloader.h
@@ -29,35 +29,30 @@
#ifndef RESOURCE_PRELOADER_H
#define RESOURCE_PRELOADER_H
-
#include "scene/main/node.h"
class ResourcePreloader : public Node {
- GDCLASS(ResourcePreloader,Node);
-
- Map<StringName,RES > resources;
+ GDCLASS(ResourcePreloader, Node);
+ Map<StringName, RES> resources;
- void _set_resources(const Array& p_data);
+ void _set_resources(const Array &p_data);
Array _get_resources() const;
PoolVector<String> _get_resource_list() const;
protected:
-
static void _bind_methods();
public:
-
- void add_resource(const StringName& p_name,const RES& p_resource);
- void remove_resource(const StringName& p_name);
- void rename_resource(const StringName& p_from_name,const StringName& p_to_name);
- bool has_resource(const StringName& p_name) const;
- RES get_resource(const StringName& p_name) const;
+ void add_resource(const StringName &p_name, const RES &p_resource);
+ void remove_resource(const StringName &p_name);
+ void rename_resource(const StringName &p_from_name, const StringName &p_to_name);
+ bool has_resource(const StringName &p_name) const;
+ RES get_resource(const StringName &p_name) const;
void get_resource_list(List<StringName> *p_list);
-
ResourcePreloader();
};
diff --git a/scene/main/scene_main_loop.cpp b/scene/main/scene_main_loop.cpp
index 093359ab16..e766d1c149 100644
--- a/scene/main/scene_main_loop.cpp
+++ b/scene/main/scene_main_loop.cpp
@@ -28,35 +28,34 @@
/*************************************************************************/
#include "scene_main_loop.h"
-#include "print_string.h"
-#include "os/os.h"
+#include "global_config.h"
#include "message_queue.h"
#include "node.h"
-#include "global_config.h"
-#include <stdio.h>
#include "os/keyboard.h"
+#include "os/os.h"
+#include "print_string.h"
+#include <stdio.h>
//#include "servers/spatial_sound_2d_server.h"
-#include "servers/physics_2d_server.h"
-#include "servers/physics_server.h"
-#include "scene/scene_string_names.h"
+#include "io/marshalls.h"
#include "io/resource_loader.h"
-#include "viewport.h"
-#include "scene/resources/packed_scene.h"
#include "scene/resources/material.h"
#include "scene/resources/mesh.h"
-#include "io/marshalls.h"
+#include "scene/resources/packed_scene.h"
+#include "scene/scene_string_names.h"
+#include "servers/physics_2d_server.h"
+#include "servers/physics_server.h"
+#include "viewport.h"
void SceneTreeTimer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_time_left","time"),&SceneTreeTimer::set_time_left);
- ClassDB::bind_method(D_METHOD("get_time_left"),&SceneTreeTimer::get_time_left);
+ ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left);
+ ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left);
ADD_SIGNAL(MethodInfo("timeout"));
}
-
void SceneTreeTimer::set_time_left(float p_time) {
- time_left=p_time;
+ time_left = p_time;
}
float SceneTreeTimer::get_time_left() const {
@@ -74,11 +73,10 @@ bool SceneTreeTimer::is_pause_mode_process() {
}
SceneTreeTimer::SceneTreeTimer() {
- time_left=0;
+ time_left = 0;
process_pause = true;
}
-
void SceneTree::tree_changed() {
tree_version++;
@@ -87,40 +85,36 @@ void SceneTree::tree_changed() {
void SceneTree::node_removed(Node *p_node) {
- if (current_scene==p_node) {
- current_scene=NULL;
+ if (current_scene == p_node) {
+ current_scene = NULL;
}
- emit_signal(node_removed_name,p_node);
- if (call_lock>0)
+ emit_signal(node_removed_name, p_node);
+ if (call_lock > 0)
call_skip.insert(p_node);
-
-
}
+SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) {
-SceneTree::Group *SceneTree::add_to_group(const StringName& p_group, Node *p_node) {
-
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E) {
- E=group_map.insert(p_group,Group());
+ E = group_map.insert(p_group, Group());
}
- if (E->get().nodes.find(p_node)!=-1) {
- ERR_EXPLAIN("Already in group: "+p_group);
+ if (E->get().nodes.find(p_node) != -1) {
+ ERR_EXPLAIN("Already in group: " + p_group);
ERR_FAIL_V(&E->get());
}
E->get().nodes.push_back(p_node);
//E->get().last_tree_version=0;
- E->get().changed=true;
+ E->get().changed = true;
return &E->get();
}
-void SceneTree::remove_from_group(const StringName& p_group, Node *p_node) {
+void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) {
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
ERR_FAIL_COND(!E);
-
E->get().nodes.erase(p_node);
if (E->get().nodes.empty())
group_map.erase(E);
@@ -128,38 +122,38 @@ void SceneTree::remove_from_group(const StringName& p_group, Node *p_node) {
void SceneTree::_flush_transform_notifications() {
- SelfList<Node>* n = xform_change_list.first();
- while(n) {
+ SelfList<Node> *n = xform_change_list.first();
+ while (n) {
- Node *node=n->self();
- SelfList<Node>* nx = n->next();
+ Node *node = n->self();
+ SelfList<Node> *nx = n->next();
xform_change_list.remove(n);
- n=nx;
+ n = nx;
node->notification(NOTIFICATION_TRANSFORM_CHANGED);
}
}
void SceneTree::_flush_ugc() {
- ugc_locked=true;
+ ugc_locked = true;
while (unique_group_calls.size()) {
- Map<UGCall,Vector<Variant> >::Element *E=unique_group_calls.front();
+ Map<UGCall, Vector<Variant> >::Element *E = unique_group_calls.front();
Variant v[VARIANT_ARG_MAX];
- for(int i=0;i<E->get().size();i++)
- v[i]=E->get()[i];
+ for (int i = 0; i < E->get().size(); i++)
+ v[i] = E->get()[i];
- call_group_flags(GROUP_CALL_REALTIME,E->key().group,E->key().call,v[0],v[1],v[2],v[3],v[4]);
+ call_group_flags(GROUP_CALL_REALTIME, E->key().group, E->key().call, v[0], v[1], v[2], v[3], v[4]);
unique_group_calls.erase(E);
}
- ugc_locked=false;
+ ugc_locked = false;
}
-void SceneTree::_update_group_order(Group& g) {
+void SceneTree::_update_group_order(Group &g) {
if (!g.changed)
return;
@@ -167,32 +161,29 @@ void SceneTree::_update_group_order(Group& g) {
return;
Node **nodes = &g.nodes[0];
- int node_count=g.nodes.size();
-
- SortArray<Node*,Node::Comparator> node_sort;
- node_sort.sort(nodes,node_count);
- g.changed=false;
+ int node_count = g.nodes.size();
+ SortArray<Node *, Node::Comparator> node_sort;
+ node_sort.sort(nodes, node_count);
+ g.changed = false;
}
+void SceneTree::call_group_flags(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
-void SceneTree::call_group_flags(uint32_t p_call_flags,const StringName& p_group,const StringName& p_function,VARIANT_ARG_DECLARE) {
-
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
- Group &g=E->get();
+ Group &g = E->get();
if (g.nodes.empty())
return;
-
- if (p_call_flags&GROUP_CALL_UNIQUE && !(p_call_flags&GROUP_CALL_REALTIME)) {
+ if (p_call_flags & GROUP_CALL_UNIQUE && !(p_call_flags & GROUP_CALL_REALTIME)) {
ERR_FAIL_COND(ugc_locked);
UGCall ug;
- ug.call=p_function;
- ug.group=p_group;
+ ug.call = p_function;
+ ug.group = p_group;
if (unique_group_calls.has(ug))
return;
@@ -200,210 +191,201 @@ void SceneTree::call_group_flags(uint32_t p_call_flags,const StringName& p_group
VARIANT_ARGPTRS;
Vector<Variant> args;
- for(int i=0;i<VARIANT_ARG_MAX;i++) {
- if (argptr[i]->get_type()==Variant::NIL)
+ for (int i = 0; i < VARIANT_ARG_MAX; i++) {
+ if (argptr[i]->get_type() == Variant::NIL)
break;
args.push_back(*argptr[i]);
}
- unique_group_calls[ug]=args;
+ unique_group_calls[ug] = args;
return;
}
_update_group_order(g);
- Vector<Node*> nodes_copy = g.nodes;
+ Vector<Node *> nodes_copy = g.nodes;
Node **nodes = &nodes_copy[0];
- int node_count=nodes_copy.size();
+ int node_count = nodes_copy.size();
call_lock++;
- if (p_call_flags&GROUP_CALL_REVERSE) {
+ if (p_call_flags & GROUP_CALL_REVERSE) {
- for(int i=node_count-1;i>=0;i--) {
+ for (int i = node_count - 1; i >= 0; i--) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME) {
- if (p_call_flags&GROUP_CALL_MULTILEVEL)
- nodes[i]->call_multilevel(p_function,VARIANT_ARG_PASS);
+ if (p_call_flags & GROUP_CALL_REALTIME) {
+ if (p_call_flags & GROUP_CALL_MULTILEVEL)
+ nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS);
else
- nodes[i]->call(p_function,VARIANT_ARG_PASS);
+ nodes[i]->call(p_function, VARIANT_ARG_PASS);
} else
- MessageQueue::get_singleton()->push_call(nodes[i],p_function,VARIANT_ARG_PASS);
-
+ MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
}
} else {
- for(int i=0;i<node_count;i++) {
+ for (int i = 0; i < node_count; i++) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME) {
- if (p_call_flags&GROUP_CALL_MULTILEVEL)
- nodes[i]->call_multilevel(p_function,VARIANT_ARG_PASS);
+ if (p_call_flags & GROUP_CALL_REALTIME) {
+ if (p_call_flags & GROUP_CALL_MULTILEVEL)
+ nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS);
else
- nodes[i]->call(p_function,VARIANT_ARG_PASS);
+ nodes[i]->call(p_function, VARIANT_ARG_PASS);
} else
- MessageQueue::get_singleton()->push_call(nodes[i],p_function,VARIANT_ARG_PASS);
+ MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
}
-
}
call_lock--;
- if (call_lock==0)
+ if (call_lock == 0)
call_skip.clear();
}
-void SceneTree::notify_group_flags(uint32_t p_call_flags,const StringName& p_group,int p_notification) {
+void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) {
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
- Group &g=E->get();
+ Group &g = E->get();
if (g.nodes.empty())
return;
_update_group_order(g);
- Vector<Node*> nodes_copy = g.nodes;
+ Vector<Node *> nodes_copy = g.nodes;
Node **nodes = &nodes_copy[0];
- int node_count=nodes_copy.size();
+ int node_count = nodes_copy.size();
call_lock++;
- if (p_call_flags&GROUP_CALL_REVERSE) {
+ if (p_call_flags & GROUP_CALL_REVERSE) {
- for(int i=node_count-1;i>=0;i--) {
+ for (int i = node_count - 1; i >= 0; i--) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME)
+ if (p_call_flags & GROUP_CALL_REALTIME)
nodes[i]->notification(p_notification);
else
- MessageQueue::get_singleton()->push_notification(nodes[i],p_notification);
+ MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
}
} else {
- for(int i=0;i<node_count;i++) {
+ for (int i = 0; i < node_count; i++) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME)
+ if (p_call_flags & GROUP_CALL_REALTIME)
nodes[i]->notification(p_notification);
else
- MessageQueue::get_singleton()->push_notification(nodes[i],p_notification);
+ MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
}
-
}
call_lock--;
- if (call_lock==0)
+ if (call_lock == 0)
call_skip.clear();
}
-void SceneTree::set_group_flags(uint32_t p_call_flags,const StringName& p_group,const String& p_name,const Variant& p_value) {
+void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) {
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
- Group &g=E->get();
+ Group &g = E->get();
if (g.nodes.empty())
return;
_update_group_order(g);
- Vector<Node*> nodes_copy = g.nodes;
+ Vector<Node *> nodes_copy = g.nodes;
Node **nodes = &nodes_copy[0];
- int node_count=nodes_copy.size();
+ int node_count = nodes_copy.size();
call_lock++;
- if (p_call_flags&GROUP_CALL_REVERSE) {
+ if (p_call_flags & GROUP_CALL_REVERSE) {
- for(int i=node_count-1;i>=0;i--) {
+ for (int i = node_count - 1; i >= 0; i--) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME)
- nodes[i]->set(p_name,p_value);
+ if (p_call_flags & GROUP_CALL_REALTIME)
+ nodes[i]->set(p_name, p_value);
else
- MessageQueue::get_singleton()->push_set(nodes[i],p_name,p_value);
+ MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
}
} else {
- for(int i=0;i<node_count;i++) {
+ for (int i = 0; i < node_count; i++) {
if (call_lock && call_skip.has(nodes[i]))
continue;
- if (p_call_flags&GROUP_CALL_REALTIME)
- nodes[i]->set(p_name,p_value);
+ if (p_call_flags & GROUP_CALL_REALTIME)
+ nodes[i]->set(p_name, p_value);
else
- MessageQueue::get_singleton()->push_set(nodes[i],p_name,p_value);
+ MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
}
-
}
call_lock--;
- if (call_lock==0)
+ if (call_lock == 0)
call_skip.clear();
}
+void SceneTree::call_group(const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
-void SceneTree::call_group(const StringName& p_group,const StringName& p_function,VARIANT_ARG_DECLARE) {
-
- call_group_flags(0,p_group,VARIANT_ARG_PASS);
+ call_group_flags(0, p_group, VARIANT_ARG_PASS);
}
-void SceneTree::notify_group(const StringName& p_group,int p_notification) {
+void SceneTree::notify_group(const StringName &p_group, int p_notification) {
- notify_group_flags(0,p_group,p_notification);
+ notify_group_flags(0, p_group, p_notification);
}
-void SceneTree::set_group(const StringName& p_group,const String& p_name,const Variant& p_value) {
+void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) {
- set_group_flags(0,p_group,p_name,p_value);
+ set_group_flags(0, p_group, p_name, p_value);
}
-
void SceneTree::set_input_as_handled() {
- input_handled=true;
+ input_handled = true;
}
-void SceneTree::input_text( const String& p_text ) {
+void SceneTree::input_text(const String &p_text) {
root_lock++;
- call_group_flags(GROUP_CALL_REALTIME,"_viewports","_vp_input_text",p_text); //special one for GUI, as controls use their own process check
+ call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input_text", p_text); //special one for GUI, as controls use their own process check
root_lock--;
-
}
-void SceneTree::input_event( const InputEvent& p_event ) {
-
+void SceneTree::input_event(const InputEvent &p_event) {
- if (is_editor_hint() && (p_event.type==InputEvent::JOYPAD_MOTION || p_event.type==InputEvent::JOYPAD_BUTTON))
+ if (is_editor_hint() && (p_event.type == InputEvent::JOYPAD_MOTION || p_event.type == InputEvent::JOYPAD_BUTTON))
return; //avoid joy input on editor
root_lock++;
//last_id=p_event.ID;
- input_handled=false;
-
+ input_handled = false;
InputEvent ev = p_event;
- ev.ID=++last_id; //this should work better
+ ev.ID = ++last_id; //this should work better
#if 0
switch(ev.type) {
@@ -480,10 +462,10 @@ void SceneTree::input_event( const InputEvent& p_event ) {
//transform for the rest
#else
- call_group_flags(GROUP_CALL_REALTIME,"_viewports","_vp_input",ev); //special one for GUI, as controls use their own process check
+ call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input", ev); //special one for GUI, as controls use their own process check
#endif
- if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_remote() && ev.type==InputEvent::KEY && ev.key.pressed && !ev.key.echo && ev.key.scancode==KEY_F8) {
+ if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_remote() && ev.type == InputEvent::KEY && ev.key.pressed && !ev.key.echo && ev.key.scancode == KEY_F8) {
ScriptDebugger::get_singleton()->request_quit();
}
@@ -505,42 +487,37 @@ void SceneTree::input_event( const InputEvent& p_event ) {
}
#else
- call_group_flags(GROUP_CALL_REALTIME,"_viewports","_vp_unhandled_input",ev); //special one for GUI, as controls use their own process check
+ call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_unhandled_input", ev); //special one for GUI, as controls use their own process check
#endif
- input_handled=true;
+ input_handled = true;
_flush_ugc();
root_lock--;
MessageQueue::get_singleton()->flush(); //small little hack
} else {
- input_handled=true;
+ input_handled = true;
root_lock--;
-
}
_call_idle_callbacks();
-
}
void SceneTree::init() {
//_quit=false;
- accept_quit=true;
- quit_on_go_back=true;
- initialized=true;
- input_handled=false;
+ accept_quit = true;
+ quit_on_go_back = true;
+ initialized = true;
+ input_handled = false;
-
- pause=false;
+ pause = false;
root->_set_tree(this);
MainLoop::init();
-
}
bool SceneTree::iteration(float p_time) {
-
root_lock++;
current_frame++;
@@ -548,15 +525,15 @@ bool SceneTree::iteration(float p_time) {
_flush_transform_notifications();
MainLoop::iteration(p_time);
- fixed_process_time=p_time;
+ fixed_process_time = p_time;
emit_signal("fixed_frame");
- _notify_group_pause("fixed_process_internal",Node::NOTIFICATION_INTERNAL_FIXED_PROCESS);
- _notify_group_pause("fixed_process",Node::NOTIFICATION_FIXED_PROCESS);
+ _notify_group_pause("fixed_process_internal", Node::NOTIFICATION_INTERNAL_FIXED_PROCESS);
+ _notify_group_pause("fixed_process", Node::NOTIFICATION_FIXED_PROCESS);
_flush_ugc();
_flush_transform_notifications();
- call_group_flags(GROUP_CALL_REALTIME,"_viewports","update_worlds");
+ call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");
root_lock--;
_flush_delete_queue();
@@ -565,8 +542,7 @@ bool SceneTree::iteration(float p_time) {
return _quit;
}
-bool SceneTree::idle(float p_time){
-
+bool SceneTree::idle(float p_time) {
//print_line("ram: "+itos(OS::get_singleton()->get_static_memory_usage())+" sram: "+itos(OS::get_singleton()->get_dynamic_memory_usage()));
//print_line("node count: "+itos(get_node_count()));
@@ -576,7 +552,7 @@ bool SceneTree::idle(float p_time){
MainLoop::idle(p_time);
- idle_process_time=p_time;
+ idle_process_time = p_time;
_network_poll();
@@ -584,24 +560,21 @@ bool SceneTree::idle(float p_time){
_flush_transform_notifications();
- _notify_group_pause("idle_process_internal",Node::NOTIFICATION_INTERNAL_PROCESS);
- _notify_group_pause("idle_process",Node::NOTIFICATION_PROCESS);
+ _notify_group_pause("idle_process_internal", Node::NOTIFICATION_INTERNAL_PROCESS);
+ _notify_group_pause("idle_process", Node::NOTIFICATION_PROCESS);
- Size2 win_size=Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height );
- if(win_size!=last_screen_size) {
+ Size2 win_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
+ if (win_size != last_screen_size) {
-
- last_screen_size=win_size;
+ last_screen_size = win_size;
_update_root_rect();
-
emit_signal("screen_resized");
-
}
_flush_ugc();
_flush_transform_notifications(); //transforms after world update, to avoid unnecesary enter/exit notifications
- call_group_flags(GROUP_CALL_REALTIME,"_viewports","update_worlds");
+ call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");
root_lock--;
@@ -609,22 +582,22 @@ bool SceneTree::idle(float p_time){
//go through timers
- for (List<Ref<SceneTreeTimer> >::Element *E=timers.front();E;) {
+ for (List<Ref<SceneTreeTimer> >::Element *E = timers.front(); E;) {
List<Ref<SceneTreeTimer> >::Element *N = E->next();
if (pause && !E->get()->is_pause_mode_process()) {
- E=N;
+ E = N;
continue;
}
float time_left = E->get()->get_time_left();
- time_left-=p_time;
+ time_left -= p_time;
E->get()->set_time_left(time_left);
- if (time_left<0) {
+ if (time_left < 0) {
E->get()->emit_signal("timeout");
timers.erase(E);
}
- E=N;
+ E = N;
}
_call_idle_callbacks();
@@ -638,7 +611,7 @@ void SceneTree::finish() {
_flush_ugc();
- initialized=false;
+ initialized = false;
MainLoop::finish();
@@ -646,27 +619,15 @@ void SceneTree::finish() {
root->_set_tree(NULL);
memdelete(root); //delete root
}
-
-
-
-
-
-
-
-
-
}
-
void SceneTree::quit() {
- _quit=true;
+ _quit = true;
}
void SceneTree::_notification(int p_notification) {
-
-
switch (p_notification) {
case NOTIFICATION_WM_QUIT_REQUEST: {
@@ -674,7 +635,7 @@ void SceneTree::_notification(int p_notification) {
get_root()->propagate_notification(p_notification);
if (accept_quit) {
- _quit=true;
+ _quit = true;
break;
}
} break;
@@ -683,7 +644,7 @@ void SceneTree::_notification(int p_notification) {
get_root()->propagate_notification(p_notification);
if (quit_on_go_back) {
- _quit=true;
+ _quit = true;
break;
}
} break;
@@ -698,7 +659,7 @@ void SceneTree::_notification(int p_notification) {
} break;
case NOTIFICATION_WM_UNFOCUS_REQUEST: {
- notify_group_flags(GROUP_CALL_REALTIME|GROUP_CALL_MULTILEVEL,"input",NOTIFICATION_WM_UNFOCUS_REQUEST);
+ notify_group_flags(GROUP_CALL_REALTIME | GROUP_CALL_MULTILEVEL, "input", NOTIFICATION_WM_UNFOCUS_REQUEST);
} break;
@@ -707,23 +668,22 @@ void SceneTree::_notification(int p_notification) {
};
};
-
void SceneTree::set_auto_accept_quit(bool p_enable) {
- accept_quit=p_enable;
+ accept_quit = p_enable;
}
void SceneTree::set_quit_on_go_back(bool p_enable) {
- quit_on_go_back=p_enable;
+ quit_on_go_back = p_enable;
}
void SceneTree::set_editor_hint(bool p_enabled) {
- editor_hint=p_enabled;
+ editor_hint = p_enabled;
}
-bool SceneTree::is_node_being_edited(const Node* p_node) const {
+bool SceneTree::is_node_being_edited(const Node *p_node) const {
#ifdef TOOLS_ENABLED
return editor_hint && edited_scene_root && edited_scene_root->is_a_parent_of(p_node);
#else
@@ -738,7 +698,7 @@ bool SceneTree::is_editor_hint() const {
void SceneTree::set_debug_collisions_hint(bool p_enabled) {
- debug_collisions_hint=p_enabled;
+ debug_collisions_hint = p_enabled;
}
bool SceneTree::is_debugging_collisions_hint() const {
@@ -748,7 +708,7 @@ bool SceneTree::is_debugging_collisions_hint() const {
void SceneTree::set_debug_navigation_hint(bool p_enabled) {
- debug_navigation_hint=p_enabled;
+ debug_navigation_hint = p_enabled;
}
bool SceneTree::is_debugging_navigation_hint() const {
@@ -756,9 +716,9 @@ bool SceneTree::is_debugging_navigation_hint() const {
return debug_navigation_hint;
}
-void SceneTree::set_debug_collisions_color(const Color& p_color) {
+void SceneTree::set_debug_collisions_color(const Color &p_color) {
- debug_collisions_color=p_color;
+ debug_collisions_color = p_color;
}
Color SceneTree::get_debug_collisions_color() const {
@@ -766,9 +726,9 @@ Color SceneTree::get_debug_collisions_color() const {
return debug_collisions_color;
}
-void SceneTree::set_debug_collision_contact_color(const Color& p_color) {
+void SceneTree::set_debug_collision_contact_color(const Color &p_color) {
- debug_collision_contact_color=p_color;
+ debug_collision_contact_color = p_color;
}
Color SceneTree::get_debug_collision_contact_color() const {
@@ -776,9 +736,9 @@ Color SceneTree::get_debug_collision_contact_color() const {
return debug_collision_contact_color;
}
-void SceneTree::set_debug_navigation_color(const Color& p_color) {
+void SceneTree::set_debug_navigation_color(const Color &p_color) {
- debug_navigation_color=p_color;
+ debug_navigation_color = p_color;
}
Color SceneTree::get_debug_navigation_color() const {
@@ -786,9 +746,9 @@ Color SceneTree::get_debug_navigation_color() const {
return debug_navigation_color;
}
-void SceneTree::set_debug_navigation_disabled_color(const Color& p_color) {
+void SceneTree::set_debug_navigation_disabled_color(const Color &p_color) {
- debug_navigation_disabled_color=p_color;
+ debug_navigation_disabled_color = p_color;
}
Color SceneTree::get_debug_navigation_disabled_color() const {
@@ -801,50 +761,47 @@ Ref<Material> SceneTree::get_debug_navigation_material() {
if (navigation_material.is_valid())
return navigation_material;
- Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
-/* line_material->set_flag(Material::FLAG_UNSHADED, true);
+ Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
+ /* line_material->set_flag(Material::FLAG_UNSHADED, true);
line_material->set_line_width(3.0);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_ALPHA, true);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_COLOR_ARRAY, true);
line_material->set_parameter(FixedSpatialMaterial::PARAM_DIFFUSE,get_debug_navigation_color());*/
- navigation_material=line_material;
+ navigation_material = line_material;
return navigation_material;
-
}
-Ref<Material> SceneTree::get_debug_navigation_disabled_material(){
+Ref<Material> SceneTree::get_debug_navigation_disabled_material() {
if (navigation_disabled_material.is_valid())
return navigation_disabled_material;
- Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
-/* line_material->set_flag(Material::FLAG_UNSHADED, true);
+ Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
+ /* line_material->set_flag(Material::FLAG_UNSHADED, true);
line_material->set_line_width(3.0);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_ALPHA, true);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_COLOR_ARRAY, true);
line_material->set_parameter(FixedSpatialMaterial::PARAM_DIFFUSE,get_debug_navigation_disabled_color());*/
- navigation_disabled_material=line_material;
+ navigation_disabled_material = line_material;
return navigation_disabled_material;
-
}
Ref<Material> SceneTree::get_debug_collision_material() {
if (collision_material.is_valid())
return collision_material;
-
- Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>( memnew( FixedSpatialMaterial ));
+ Ref<FixedSpatialMaterial> line_material = Ref<FixedSpatialMaterial>(memnew(FixedSpatialMaterial));
/*line_material->set_flag(Material::FLAG_UNSHADED, true);
line_material->set_line_width(3.0);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_ALPHA, true);
line_material->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_COLOR_ARRAY, true);
line_material->set_parameter(FixedSpatialMaterial::PARAM_DIFFUSE,get_debug_collisions_color());*/
- collision_material=line_material;
+ collision_material = line_material;
return collision_material;
}
@@ -854,62 +811,58 @@ Ref<Mesh> SceneTree::get_debug_contact_mesh() {
if (debug_contact_mesh.is_valid())
return debug_contact_mesh;
- debug_contact_mesh = Ref<Mesh>( memnew( Mesh ) );
+ debug_contact_mesh = Ref<Mesh>(memnew(Mesh));
- Ref<FixedSpatialMaterial> mat = memnew( FixedSpatialMaterial );
+ Ref<FixedSpatialMaterial> mat = memnew(FixedSpatialMaterial);
/*mat->set_flag(Material::FLAG_UNSHADED,true);
mat->set_flag(Material::FLAG_DOUBLE_SIDED,true);
mat->set_fixed_flag(FixedSpatialMaterial::FLAG_USE_ALPHA,true);
mat->set_parameter(FixedSpatialMaterial::PARAM_DIFFUSE,get_debug_collision_contact_color());*/
- Vector3 diamond[6]={
+ Vector3 diamond[6] = {
Vector3(-1, 0, 0),
- Vector3( 1, 0, 0),
- Vector3( 0, -1, 0),
- Vector3( 0, 1, 0),
- Vector3( 0, 0, -1),
- Vector3( 0, 0, 1)
+ Vector3(1, 0, 0),
+ Vector3(0, -1, 0),
+ Vector3(0, 1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, 1)
};
- int diamond_faces[8*3]={
- 0,2,4,
- 0,3,4,
- 1,2,4,
- 1,3,4,
- 0,2,5,
- 0,3,5,
- 1,2,5,
- 1,3,5,
+ int diamond_faces[8 * 3] = {
+ 0, 2, 4,
+ 0, 3, 4,
+ 1, 2, 4,
+ 1, 3, 4,
+ 0, 2, 5,
+ 0, 3, 5,
+ 1, 2, 5,
+ 1, 3, 5,
};
PoolVector<int> indices;
- for(int i=0;i<8*3;i++)
+ for (int i = 0; i < 8 * 3; i++)
indices.push_back(diamond_faces[i]);
PoolVector<Vector3> vertices;
- for(int i=0;i<6;i++)
- vertices.push_back(diamond[i]*0.1);
+ for (int i = 0; i < 6; i++)
+ vertices.push_back(diamond[i] * 0.1);
Array arr;
arr.resize(Mesh::ARRAY_MAX);
- arr[Mesh::ARRAY_VERTEX]=vertices;
- arr[Mesh::ARRAY_INDEX]=indices;
-
+ arr[Mesh::ARRAY_VERTEX] = vertices;
+ arr[Mesh::ARRAY_INDEX] = indices;
- debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr);
- debug_contact_mesh->surface_set_material(0,mat);
+ debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
+ debug_contact_mesh->surface_set_material(0, mat);
return debug_contact_mesh;
-
}
-
-
void SceneTree::set_pause(bool p_enabled) {
- if (p_enabled==pause)
+ if (p_enabled == pause)
return;
- pause=p_enabled;
+ pause = p_enabled;
PhysicsServer::get_singleton()->set_active(!p_enabled);
Physics2DServer::get_singleton()->set_active(!p_enabled);
if (get_root())
@@ -921,12 +874,12 @@ bool SceneTree::is_paused() const {
return pause;
}
-void SceneTree::_call_input_pause(const StringName& p_group,const StringName& p_method,const InputEvent& p_input) {
+void SceneTree::_call_input_pause(const StringName &p_group, const StringName &p_method, const InputEvent &p_input) {
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
- Group &g=E->get();
+ Group &g = E->get();
if (g.nodes.empty())
return;
@@ -934,17 +887,17 @@ void SceneTree::_call_input_pause(const StringName& p_group,const StringName& p_
//copy, so copy on write happens in case something is removed from process while being called
//performance is not lost because only if something is added/removed the vector is copied.
- Vector<Node*> nodes_copy = g.nodes;
+ Vector<Node *> nodes_copy = g.nodes;
- int node_count=nodes_copy.size();
+ int node_count = nodes_copy.size();
Node **nodes = &nodes_copy[0];
- Variant arg=p_input;
- const Variant *v[1]={&arg};
+ Variant arg = p_input;
+ const Variant *v[1] = { &arg };
call_lock++;
- for(int i=node_count-1;i>=0;i--) {
+ for (int i = node_count - 1; i >= 0; i--) {
if (input_handled)
break;
@@ -957,37 +910,36 @@ void SceneTree::_call_input_pause(const StringName& p_group,const StringName& p_
continue;
Variant::CallError ce;
- n->call_multilevel(p_method,(const Variant**)v,1);
+ n->call_multilevel(p_method, (const Variant **)v, 1);
//ERR_FAIL_COND(node_count != g.nodes.size());
}
call_lock--;
- if (call_lock==0)
+ if (call_lock == 0)
call_skip.clear();
}
-void SceneTree::_notify_group_pause(const StringName& p_group,int p_notification) {
+void SceneTree::_notify_group_pause(const StringName &p_group, int p_notification) {
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
- Group &g=E->get();
+ Group &g = E->get();
if (g.nodes.empty())
return;
-
_update_group_order(g);
//copy, so copy on write happens in case something is removed from process while being called
//performance is not lost because only if something is added/removed the vector is copied.
- Vector<Node*> nodes_copy = g.nodes;
+ Vector<Node *> nodes_copy = g.nodes;
- int node_count=nodes_copy.size();
+ int node_count = nodes_copy.size();
Node **nodes = &nodes_copy[0];
call_lock++;
- for(int i=0;i<node_count;i++) {
+ for (int i = 0; i < node_count; i++) {
Node *n = nodes[i];
if (call_lock && call_skip.has(n))
@@ -1001,7 +953,7 @@ void SceneTree::_notify_group_pause(const StringName& p_group,int p_notification
}
call_lock--;
- if (call_lock==0)
+ if (call_lock == 0)
call_skip.clear();
}
@@ -1021,51 +973,47 @@ uint32_t SceneTree::get_last_event_id() const {
return last_id;
}
+Variant SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant SceneTree::_call_group_flags(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
+ r_error.error = Variant::CallError::CALL_OK;
- r_error.error=Variant::CallError::CALL_OK;
-
- ERR_FAIL_COND_V(p_argcount<3,Variant());
- ERR_FAIL_COND_V(!p_args[0]->is_num(),Variant());
- ERR_FAIL_COND_V(p_args[1]->get_type()!=Variant::STRING,Variant());
- ERR_FAIL_COND_V(p_args[2]->get_type()!=Variant::STRING,Variant());
+ ERR_FAIL_COND_V(p_argcount < 3, Variant());
+ ERR_FAIL_COND_V(!p_args[0]->is_num(), Variant());
+ ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant());
+ ERR_FAIL_COND_V(p_args[2]->get_type() != Variant::STRING, Variant());
int flags = *p_args[0];
StringName group = *p_args[1];
StringName method = *p_args[2];
Variant v[VARIANT_ARG_MAX];
- for(int i=0;i<MIN(p_argcount-3,5);i++) {
+ for (int i = 0; i < MIN(p_argcount - 3, 5); i++) {
- v[i]=*p_args[i+3];
+ v[i] = *p_args[i + 3];
}
- call_group_flags(flags,group,method,v[0],v[1],v[2],v[3],v[4]);
+ call_group_flags(flags, group, method, v[0], v[1], v[2], v[3], v[4]);
return Variant();
}
+Variant SceneTree::_call_group(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
-Variant SceneTree::_call_group(const Variant** p_args, int p_argcount, Variant::CallError& r_error) {
-
+ r_error.error = Variant::CallError::CALL_OK;
- r_error.error=Variant::CallError::CALL_OK;
-
- ERR_FAIL_COND_V(p_argcount<2,Variant());
- ERR_FAIL_COND_V(p_args[0]->get_type()!=Variant::STRING,Variant());
- ERR_FAIL_COND_V(p_args[1]->get_type()!=Variant::STRING,Variant());
+ ERR_FAIL_COND_V(p_argcount < 2, Variant());
+ ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING, Variant());
+ ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant());
StringName group = *p_args[0];
StringName method = *p_args[1];
Variant v[VARIANT_ARG_MAX];
- for(int i=0;i<MIN(p_argcount-2,5);i++) {
+ for (int i = 0; i < MIN(p_argcount - 2, 5); i++) {
- v[i]=*p_args[i+2];
+ v[i] = *p_args[i + 2];
}
- call_group_flags(0,group,method,v[0],v[1],v[2],v[3],v[4]);
+ call_group_flags(0, group, method, v[0], v[1], v[2], v[3], v[4]);
return Variant();
}
@@ -1074,62 +1022,59 @@ int64_t SceneTree::get_frame() const {
return current_frame;
}
-
-Array SceneTree::_get_nodes_in_group(const StringName& p_group) {
+Array SceneTree::_get_nodes_in_group(const StringName &p_group) {
Array ret;
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return ret;
_update_group_order(E->get()); //update order just in case
int nc = E->get().nodes.size();
- if (nc==0)
+ if (nc == 0)
return ret;
ret.resize(nc);
Node **ptr = E->get().nodes.ptr();
- for(int i=0;i<nc;i++) {
+ for (int i = 0; i < nc; i++) {
- ret[i]=ptr[i];
+ ret[i] = ptr[i];
}
return ret;
}
-bool SceneTree::has_group(const StringName& p_identifier) const {
+bool SceneTree::has_group(const StringName &p_identifier) const {
return group_map.has(p_identifier);
}
-void SceneTree::get_nodes_in_group(const StringName& p_group,List<Node*> *p_list) {
+void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) {
-
- Map<StringName,Group>::Element *E=group_map.find(p_group);
+ Map<StringName, Group>::Element *E = group_map.find(p_group);
if (!E)
return;
_update_group_order(E->get()); //update order just in case
int nc = E->get().nodes.size();
- if (nc==0)
+ if (nc == 0)
return;
Node **ptr = E->get().nodes.ptr();
- for(int i=0;i<nc;i++) {
+ for (int i = 0; i < nc; i++) {
p_list->push_back(ptr[i]);
}
}
-
-static void _fill_array(Node *p_node, Array& array, int p_level) {
+static void _fill_array(Node *p_node, Array &array, int p_level) {
array.push_back(p_level);
array.push_back(p_node->get_name());
array.push_back(p_node->get_class());
array.push_back(p_node->get_instance_ID());
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- _fill_array(p_node->get_child(i),array,p_level+1);
+ _fill_array(p_node->get_child(i), array, p_level + 1);
}
}
@@ -1138,20 +1083,19 @@ void SceneTree::_debugger_request_tree(void *self) {
SceneTree *sml = (SceneTree *)self;
Array arr;
- _fill_array(sml->root,arr,0);
- ScriptDebugger::get_singleton()->send_message("scene_tree",arr);
+ _fill_array(sml->root, arr, 0);
+ ScriptDebugger::get_singleton()->send_message("scene_tree", arr);
}
-
void SceneTree::_flush_delete_queue() {
_THREAD_SAFE_METHOD_
- while( delete_queue.size() ) {
+ while (delete_queue.size()) {
- Object *obj = ObjectDB::get_instance( delete_queue.front()->get() );
+ Object *obj = ObjectDB::get_instance(delete_queue.front()->get());
if (obj) {
- memdelete( obj );
+ memdelete(obj);
}
delete_queue.pop_front();
}
@@ -1165,27 +1109,24 @@ void SceneTree::queue_delete(Object *p_object) {
delete_queue.push_back(p_object->get_instance_ID());
}
-
int SceneTree::get_node_count() const {
return node_count;
}
-
void SceneTree::_update_root_rect() {
+ if (stretch_mode == STRETCH_MODE_DISABLED) {
- if (stretch_mode==STRETCH_MODE_DISABLED) {
-
- root->set_size(last_screen_size);
- root->set_attach_to_screen_rect(Rect2(Point2(),last_screen_size));
+ root->set_size(last_screen_size);
+ root->set_attach_to_screen_rect(Rect2(Point2(), last_screen_size));
root->set_size_override_stretch(false);
- root->set_size_override(false,Size2());
+ root->set_size_override(false, Size2());
return; //user will take care
}
//actual screen video mode
- Size2 video_mode = Size2(OS::get_singleton()->get_video_mode().width,OS::get_singleton()->get_video_mode().height);
+ Size2 video_mode = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
Size2 desired_res = stretch_min;
Size2 viewport_size;
@@ -1194,42 +1135,41 @@ void SceneTree::_update_root_rect() {
float viewport_aspect = desired_res.aspect();
float video_mode_aspect = video_mode.aspect();
- if (stretch_aspect==STRETCH_ASPECT_IGNORE || ABS(viewport_aspect - video_mode_aspect)<CMP_EPSILON) {
+ if (stretch_aspect == STRETCH_ASPECT_IGNORE || ABS(viewport_aspect - video_mode_aspect) < CMP_EPSILON) {
//same aspect or ignore aspect
- viewport_size=desired_res;
- screen_size=video_mode;
+ viewport_size = desired_res;
+ screen_size = video_mode;
} else if (viewport_aspect < video_mode_aspect) {
// screen ratio is smaller vertically
- if (stretch_aspect==STRETCH_ASPECT_KEEP_HEIGHT) {
+ if (stretch_aspect == STRETCH_ASPECT_KEEP_HEIGHT) {
//will stretch horizontally
- viewport_size.x=desired_res.y*video_mode_aspect;
- viewport_size.y=desired_res.y;
- screen_size=video_mode;
+ viewport_size.x = desired_res.y * video_mode_aspect;
+ viewport_size.y = desired_res.y;
+ screen_size = video_mode;
} else {
//will need black bars
- viewport_size=desired_res;
+ viewport_size = desired_res;
screen_size.x = video_mode.y * viewport_aspect;
- screen_size.y=video_mode.y;
+ screen_size.y = video_mode.y;
}
} else {
//screen ratio is smaller horizontally
- if (stretch_aspect==STRETCH_ASPECT_KEEP_WIDTH) {
+ if (stretch_aspect == STRETCH_ASPECT_KEEP_WIDTH) {
//will stretch horizontally
- viewport_size.x=desired_res.x;
- viewport_size.y=desired_res.x / video_mode_aspect;
- screen_size=video_mode;
+ viewport_size.x = desired_res.x;
+ viewport_size.y = desired_res.x / video_mode_aspect;
+ screen_size = video_mode;
} else {
//will need black bars
- viewport_size=desired_res;
- screen_size.x=video_mode.x;
+ viewport_size = desired_res;
+ screen_size.x = video_mode.x;
screen_size.y = video_mode.x / viewport_aspect;
}
-
}
screen_size = screen_size.floor();
@@ -1239,16 +1179,16 @@ void SceneTree::_update_root_rect() {
Size2 offset;
//black bars and margin
if (screen_size.x < video_mode.x) {
- margin.x = Math::round((video_mode.x - screen_size.x)/2.0);
- VisualServer::get_singleton()->black_bars_set_margins(margin.x,0,margin.x,0);
+ margin.x = Math::round((video_mode.x - screen_size.x) / 2.0);
+ VisualServer::get_singleton()->black_bars_set_margins(margin.x, 0, margin.x, 0);
offset.x = Math::round(margin.x * viewport_size.y / screen_size.y);
} else if (screen_size.y < video_mode.y) {
- margin.y = Math::round((video_mode.y - screen_size.y)/2.0);
- VisualServer::get_singleton()->black_bars_set_margins(0,margin.y,0,margin.y);
+ margin.y = Math::round((video_mode.y - screen_size.y) / 2.0);
+ VisualServer::get_singleton()->black_bars_set_margins(0, margin.y, 0, margin.y);
offset.y = Math::round(margin.y * viewport_size.x / screen_size.x);
} else {
- VisualServer::get_singleton()->black_bars_set_margins(0,0,0,0);
+ VisualServer::get_singleton()->black_bars_set_margins(0, 0, 0, 0);
}
//print_line("VP SIZE: "+viewport_size+" OFFSET: "+offset+" = "+(offset*2+viewport_size));
@@ -1257,37 +1197,33 @@ void SceneTree::_update_root_rect() {
case STRETCH_MODE_2D: {
root->set_size(screen_size);
- root->set_attach_to_screen_rect(Rect2(margin,screen_size));
+ root->set_attach_to_screen_rect(Rect2(margin, screen_size));
root->set_size_override_stretch(true);
- root->set_size_override(true,viewport_size);
+ root->set_size_override(true, viewport_size);
} break;
case STRETCH_MODE_VIEWPORT: {
root->set_size(viewport_size);
- root->set_attach_to_screen_rect(Rect2(margin,screen_size));
+ root->set_attach_to_screen_rect(Rect2(margin, screen_size));
root->set_size_override_stretch(false);
- root->set_size_override(false,Size2());
+ root->set_size_override(false, Size2());
} break;
-
-
}
-
}
-void SceneTree::set_screen_stretch(StretchMode p_mode,StretchAspect p_aspect,const Size2 p_minsize) {
+void SceneTree::set_screen_stretch(StretchMode p_mode, StretchAspect p_aspect, const Size2 p_minsize) {
- stretch_mode=p_mode;
- stretch_aspect=p_aspect;
- stretch_min=p_minsize;
+ stretch_mode = p_mode;
+ stretch_aspect = p_aspect;
+ stretch_min = p_minsize;
_update_root_rect();
}
-
#ifdef TOOLS_ENABLED
void SceneTree::set_edited_scene_root(Node *p_node) {
- edited_scene_root=p_node;
+ edited_scene_root = p_node;
}
Node *SceneTree::get_edited_scene_root() const {
@@ -1296,76 +1232,74 @@ Node *SceneTree::get_edited_scene_root() const {
}
#endif
-void SceneTree::set_current_scene(Node* p_scene) {
+void SceneTree::set_current_scene(Node *p_scene) {
- ERR_FAIL_COND(p_scene && p_scene->get_parent()!=root);
- current_scene=p_scene;
+ ERR_FAIL_COND(p_scene && p_scene->get_parent() != root);
+ current_scene = p_scene;
}
-Node* SceneTree::get_current_scene() const{
+Node *SceneTree::get_current_scene() const {
return current_scene;
}
-void SceneTree::_change_scene(Node* p_to) {
+void SceneTree::_change_scene(Node *p_to) {
if (current_scene) {
- memdelete( current_scene );
- current_scene=NULL;
+ memdelete(current_scene);
+ current_scene = NULL;
}
if (p_to) {
- current_scene=p_to;
+ current_scene = p_to;
root->add_child(p_to);
}
}
-Error SceneTree::change_scene(const String& p_path){
+Error SceneTree::change_scene(const String &p_path) {
Ref<PackedScene> new_scene = ResourceLoader::load(p_path);
if (new_scene.is_null())
return ERR_CANT_OPEN;
return change_scene_to(new_scene);
-
}
-Error SceneTree::change_scene_to(const Ref<PackedScene>& p_scene){
+Error SceneTree::change_scene_to(const Ref<PackedScene> &p_scene) {
- Node *new_scene=NULL;
+ Node *new_scene = NULL;
if (p_scene.is_valid()) {
new_scene = p_scene->instance();
- ERR_FAIL_COND_V(!new_scene,ERR_CANT_CREATE);
+ ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE);
}
- call_deferred("_change_scene",new_scene);
+ call_deferred("_change_scene", new_scene);
return OK;
-
}
Error SceneTree::reload_current_scene() {
- ERR_FAIL_COND_V(!current_scene,ERR_UNCONFIGURED);
+ ERR_FAIL_COND_V(!current_scene, ERR_UNCONFIGURED);
String fname = current_scene->get_filename();
return change_scene(fname);
}
-void SceneTree::add_current_scene(Node * p_current) {
+void SceneTree::add_current_scene(Node *p_current) {
- current_scene=p_current;
+ current_scene = p_current;
root->add_child(p_current);
}
#ifdef DEBUG_ENABLED
-void SceneTree::_live_edit_node_path_func(const NodePath &p_path,int p_id) {
+void SceneTree::_live_edit_node_path_func(const NodePath &p_path, int p_id) {
- live_edit_node_path_cache[p_id]=p_path;
+ live_edit_node_path_cache[p_id] = p_path;
}
-void SceneTree::_live_edit_res_path_func(const String &p_path,int p_id) {
+void SceneTree::_live_edit_res_path_func(const String &p_path, int p_id) {
- live_edit_resource_cache[p_id]=p_path;
+ live_edit_resource_cache[p_id] = p_path;
}
-void SceneTree::_live_edit_node_set_func(int p_id,const StringName& p_prop,const Variant& p_value) {
+void SceneTree::_live_edit_node_set_func(int p_id, const StringName &p_prop, const Variant &p_value) {
if (!live_edit_node_path_cache.has(p_id))
return;
@@ -1375,13 +1309,13 @@ void SceneTree::_live_edit_node_set_func(int p_id,const StringName& p_prop,const
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1390,20 +1324,18 @@ void SceneTree::_live_edit_node_set_func(int p_id,const StringName& p_prop,const
continue;
Node *n2 = n->get_node(np);
- n2->set(p_prop,p_value);
+ n2->set(p_prop, p_value);
}
-
}
-void SceneTree::_live_edit_node_set_res_func(int p_id,const StringName& p_prop,const String& p_value) {
+void SceneTree::_live_edit_node_set_res_func(int p_id, const StringName &p_prop, const String &p_value) {
RES r = ResourceLoader::load(p_value);
if (!r.is_valid())
return;
- _live_edit_node_set_func(p_id,p_prop,r);
-
+ _live_edit_node_set_func(p_id, p_prop, r);
}
-void SceneTree::_live_edit_node_call_func(int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) {
+void SceneTree::_live_edit_node_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
if (!live_edit_node_path_cache.has(p_id))
return;
@@ -1413,13 +1345,13 @@ void SceneTree::_live_edit_node_call_func(int p_id,const StringName& p_method,VA
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1428,10 +1360,10 @@ void SceneTree::_live_edit_node_call_func(int p_id,const StringName& p_method,VA
continue;
Node *n2 = n->get_node(np);
- n2->call(p_method,VARIANT_ARG_PASS);
+ n2->call(p_method, VARIANT_ARG_PASS);
}
}
-void SceneTree::_live_edit_res_set_func(int p_id,const StringName& p_prop,const Variant& p_value) {
+void SceneTree::_live_edit_res_set_func(int p_id, const StringName &p_prop, const Variant &p_value) {
if (!live_edit_resource_cache.has(p_id))
return;
@@ -1445,17 +1377,16 @@ void SceneTree::_live_edit_res_set_func(int p_id,const StringName& p_prop,const
if (!r.is_valid())
return;
- r->set(p_prop,p_value);
+ r->set(p_prop, p_value);
}
-void SceneTree::_live_edit_res_set_res_func(int p_id,const StringName& p_prop,const String& p_value) {
+void SceneTree::_live_edit_res_set_res_func(int p_id, const StringName &p_prop, const String &p_value) {
RES r = ResourceLoader::load(p_value);
if (!r.is_valid())
return;
- _live_edit_res_set_func(p_id,p_prop,r);
-
+ _live_edit_res_set_func(p_id, p_prop, r);
}
-void SceneTree::_live_edit_res_call_func(int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) {
+void SceneTree::_live_edit_res_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
if (!live_edit_resource_cache.has(p_id))
return;
@@ -1469,29 +1400,28 @@ void SceneTree::_live_edit_res_call_func(int p_id,const StringName& p_method,VAR
if (!r.is_valid())
return;
- r->call(p_method,VARIANT_ARG_PASS);
+ r->call(p_method, VARIANT_ARG_PASS);
}
-void SceneTree::_live_edit_root_func(const NodePath& p_scene_path,const String& p_scene_from) {
+void SceneTree::_live_edit_root_func(const NodePath &p_scene_path, const String &p_scene_from) {
- live_edit_root=p_scene_path;
- live_edit_scene=p_scene_from;
+ live_edit_root = p_scene_path;
+ live_edit_scene = p_scene_from;
}
-void SceneTree::_live_edit_create_node_func(const NodePath& p_parent,const String& p_type,const String& p_name) {
-
+void SceneTree::_live_edit_create_node_func(const NodePath &p_parent, const String &p_type, const String &p_name) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1503,13 +1433,13 @@ void SceneTree::_live_edit_create_node_func(const NodePath& p_parent,const Strin
Object *o = ClassDB::instance(p_type);
if (!o)
continue;
- Node *no=o->cast_to<Node>();
+ Node *no = o->cast_to<Node>();
no->set_name(p_name);
n2->add_child(no);
}
}
-void SceneTree::_live_edit_instance_node_func(const NodePath& p_parent,const String& p_path,const String& p_name){
+void SceneTree::_live_edit_instance_node_func(const NodePath &p_parent, const String &p_path, const String &p_name) {
Ref<PackedScene> ps = ResourceLoader::load(p_path);
@@ -1520,13 +1450,13 @@ void SceneTree::_live_edit_instance_node_func(const NodePath& p_parent,const Str
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1535,29 +1465,27 @@ void SceneTree::_live_edit_instance_node_func(const NodePath& p_parent,const Str
continue;
Node *n2 = n->get_node(p_parent);
-
-
- Node *no=ps->instance();
+ Node *no = ps->instance();
no->set_name(p_name);
n2->add_child(no);
}
}
-void SceneTree::_live_edit_remove_node_func(const NodePath& p_at){
+void SceneTree::_live_edit_remove_node_func(const NodePath &p_at) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;) {
+ for (Set<Node *>::Element *F = E->get().front(); F;) {
- Set<Node*>::Element *N=F->next();
+ Set<Node *>::Element *N = F->next();
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1568,26 +1496,24 @@ void SceneTree::_live_edit_remove_node_func(const NodePath& p_at){
memdelete(n2);
- F=N;
-
+ F = N;
}
}
-void SceneTree::_live_edit_remove_and_keep_node_func(const NodePath& p_at,ObjectID p_keep_id){
+void SceneTree::_live_edit_remove_and_keep_node_func(const NodePath &p_at, ObjectID p_keep_id) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
+ for (Set<Node *>::Element *F = E->get().front(); F;) {
- for(Set<Node*>::Element *F=E->get().front();F;) {
-
- Set<Node*>::Element *N=F->next();
+ Set<Node *>::Element *N = F->next();
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1599,28 +1525,26 @@ void SceneTree::_live_edit_remove_and_keep_node_func(const NodePath& p_at,Object
n2->get_parent()->remove_child(n2);
- live_edit_remove_list[n][p_keep_id]=n2;
-
- F=N;
+ live_edit_remove_list[n][p_keep_id] = n2;
+ F = N;
}
}
-void SceneTree::_live_edit_restore_node_func(ObjectID p_id,const NodePath& p_at,int p_at_pos){
-
+void SceneTree::_live_edit_restore_node_func(ObjectID p_id, const NodePath &p_at, int p_at_pos) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;) {
+ for (Set<Node *>::Element *F = E->get().front(); F;) {
- Set<Node*>::Element *N=F->next();
+ Set<Node *>::Element *N = F->next();
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1629,12 +1553,12 @@ void SceneTree::_live_edit_restore_node_func(ObjectID p_id,const NodePath& p_at,
continue;
Node *n2 = n->get_node(p_at);
- Map<Node*,Map<ObjectID,Node*> >::Element *EN=live_edit_remove_list.find(n);
+ Map<Node *, Map<ObjectID, Node *> >::Element *EN = live_edit_remove_list.find(n);
if (!EN)
continue;
- Map<ObjectID,Node*>::Element *FN=EN->get().find(p_id);
+ Map<ObjectID, Node *>::Element *FN = EN->get().find(p_id);
if (!FN)
continue;
@@ -1642,27 +1566,26 @@ void SceneTree::_live_edit_restore_node_func(ObjectID p_id,const NodePath& p_at,
EN->get().erase(FN);
- if (EN->get().size()==0) {
+ if (EN->get().size() == 0) {
live_edit_remove_list.erase(EN);
}
- F=N;
-
+ F = N;
}
}
-void SceneTree::_live_edit_duplicate_node_func(const NodePath& p_at,const String& p_new_name){
+void SceneTree::_live_edit_duplicate_node_func(const NodePath &p_at, const String &p_new_name) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1678,22 +1601,21 @@ void SceneTree::_live_edit_duplicate_node_func(const NodePath& p_at,const String
dup->set_name(p_new_name);
n2->get_parent()->add_child(dup);
-
}
}
-void SceneTree::_live_edit_reparent_node_func(const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos){
+void SceneTree::_live_edit_reparent_node_func(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) {
Node *base = NULL;
if (root->has_node(live_edit_root))
base = root->get_node(live_edit_root);
- Map<String,Set<Node*> >::Element *E=live_scene_edit_cache.find(live_edit_scene);
+ Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
if (!E)
return; //scene not editable
- for(Set<Node*>::Element *F=E->get().front();F;F=F->next()) {
+ for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
- Node *n=F->get();
+ Node *n = F->get();
if (base && !base->is_a_parent_of(n))
continue;
@@ -1710,23 +1632,19 @@ void SceneTree::_live_edit_reparent_node_func(const NodePath& p_at,const NodePat
nfrom->set_name(p_new_name);
nto->add_child(nfrom);
- if (p_at_pos>=0)
- nto->move_child(nfrom,p_at_pos);
-
+ if (p_at_pos >= 0)
+ nto->move_child(nfrom, p_at_pos);
}
}
-
#endif
+void SceneTree::drop_files(const Vector<String> &p_files, int p_from_screen) {
-void SceneTree::drop_files(const Vector<String>& p_files,int p_from_screen) {
-
- emit_signal("files_dropped",p_files,p_from_screen);
- MainLoop::drop_files(p_files,p_from_screen);
+ emit_signal("files_dropped", p_files, p_from_screen);
+ MainLoop::drop_files(p_files, p_from_screen);
}
-
Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pause) {
Ref<SceneTreeTimer> stt;
@@ -1739,19 +1657,17 @@ Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pa
void SceneTree::_network_peer_connected(int p_id) {
-
connected_peers.insert(p_id);
- path_get_cache.insert(p_id,PathGetCache());
-
+ path_get_cache.insert(p_id, PathGetCache());
- emit_signal("network_peer_connected",p_id);
+ emit_signal("network_peer_connected", p_id);
}
void SceneTree::_network_peer_disconnected(int p_id) {
connected_peers.erase(p_id);
path_get_cache.erase(p_id); //I no longer need your cache, sorry
- emit_signal("network_peer_disconnected",p_id);
+ emit_signal("network_peer_disconnected", p_id);
}
void SceneTree::_connected_to_server() {
@@ -1769,38 +1685,37 @@ void SceneTree::_server_disconnected() {
emit_signal("server_disconnected");
}
-void SceneTree::set_network_peer(const Ref<NetworkedMultiplayerPeer>& p_network_peer) {
+void SceneTree::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_network_peer) {
if (network_peer.is_valid()) {
- network_peer->disconnect("peer_connected",this,"_network_peer_connected");
- network_peer->disconnect("peer_disconnected",this,"_network_peer_disconnected");
- network_peer->disconnect("connection_succeeded",this,"_connected_to_server");
- network_peer->disconnect("connection_failed",this,"_connection_failed");
- network_peer->disconnect("server_disconnected",this,"_server_disconnected");
+ network_peer->disconnect("peer_connected", this, "_network_peer_connected");
+ network_peer->disconnect("peer_disconnected", this, "_network_peer_disconnected");
+ network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
+ network_peer->disconnect("connection_failed", this, "_connection_failed");
+ network_peer->disconnect("server_disconnected", this, "_server_disconnected");
connected_peers.clear();
path_get_cache.clear();
path_send_cache.clear();
- last_send_cache_id=1;
+ last_send_cache_id = 1;
}
ERR_EXPLAIN("Supplied NetworkedNetworkPeer must be connecting or connected.");
- ERR_FAIL_COND(p_network_peer.is_valid() && p_network_peer->get_connection_status()==NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED);
+ ERR_FAIL_COND(p_network_peer.is_valid() && p_network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED);
- network_peer=p_network_peer;
+ network_peer = p_network_peer;
if (network_peer.is_valid()) {
- network_peer->connect("peer_connected",this,"_network_peer_connected");
- network_peer->connect("peer_disconnected",this,"_network_peer_disconnected");
- network_peer->connect("connection_succeeded",this,"_connected_to_server");
- network_peer->connect("connection_failed",this,"_connection_failed");
- network_peer->connect("server_disconnected",this,"_server_disconnected");
+ network_peer->connect("peer_connected", this, "_network_peer_connected");
+ network_peer->connect("peer_disconnected", this, "_network_peer_disconnected");
+ network_peer->connect("connection_succeeded", this, "_connected_to_server");
+ network_peer->connect("connection_failed", this, "_connection_failed");
+ network_peer->connect("server_disconnected", this, "_server_disconnected");
}
}
bool SceneTree::is_network_server() const {
- ERR_FAIL_COND_V(!network_peer.is_valid(),false);
+ ERR_FAIL_COND_V(!network_peer.is_valid(), false);
return network_peer->is_server();
-
}
bool SceneTree::has_network_peer() const {
@@ -1809,7 +1724,7 @@ bool SceneTree::has_network_peer() const {
int SceneTree::get_network_unique_id() const {
- ERR_FAIL_COND_V(!network_peer.is_valid(),0);
+ ERR_FAIL_COND_V(!network_peer.is_valid(), 0);
return network_peer->get_unique_id();
}
@@ -1820,41 +1735,38 @@ void SceneTree::set_refuse_new_network_connections(bool p_refuse) {
bool SceneTree::is_refusing_new_network_connections() const {
- ERR_FAIL_COND_V(!network_peer.is_valid(),false);
+ ERR_FAIL_COND_V(!network_peer.is_valid(), false);
return network_peer->is_refusing_new_connections();
-
}
-
-void SceneTree::_rpc(Node* p_from,int p_to,bool p_unreliable,bool p_set,const StringName& p_name,const Variant** p_arg,int p_argcount) {
+void SceneTree::_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
if (network_peer.is_null()) {
ERR_EXPLAIN("Attempt to remote call/set when networking is not active in SceneTree.");
ERR_FAIL();
}
- if (network_peer->get_connection_status()==NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
+ if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
ERR_EXPLAIN("Attempt to remote call/set when networking is not connected yet in SceneTree.");
ERR_FAIL();
}
- if (network_peer->get_connection_status()==NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
+ if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
ERR_EXPLAIN("Attempt to remote call/set when networking is disconnected.");
ERR_FAIL();
}
- if (p_argcount>255) {
+ if (p_argcount > 255) {
ERR_EXPLAIN("Too many arguments >255.");
ERR_FAIL();
}
- if (p_to!=0 && !connected_peers.has(ABS(p_to))) {
- if (p_to==get_network_unique_id()) {
- ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: "+itos(get_network_unique_id()));
+ if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
+ if (p_to == get_network_unique_id()) {
+ ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: " + itos(get_network_unique_id()));
} else {
- ERR_EXPLAIN("Attempt to remote call unexisting ID: "+itos(p_to));
-
+ ERR_EXPLAIN("Attempt to remote call unexisting ID: " + itos(p_to));
}
ERR_FAIL();
@@ -1863,111 +1775,107 @@ void SceneTree::_rpc(Node* p_from,int p_to,bool p_unreliable,bool p_set,const St
NodePath from_path = p_from->get_path();
ERR_FAIL_COND(from_path.is_empty());
-
-
//see if the path is cached
PathSentCache *psc = path_send_cache.getptr(from_path);
if (!psc) {
//path is not cached, create
- path_send_cache[from_path]=PathSentCache();
+ path_send_cache[from_path] = PathSentCache();
psc = path_send_cache.getptr(from_path);
- psc->id=last_send_cache_id++;
-
+ psc->id = last_send_cache_id++;
}
-
//create base packet, lots of harcode because it must be tight
- int ofs=0;
+ int ofs = 0;
-#define MAKE_ROOM(m_amount) if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
+#define MAKE_ROOM(m_amount) \
+ if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
//encode type
MAKE_ROOM(1);
- packet_cache[0]=p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
- ofs+=1;
+ packet_cache[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
+ ofs += 1;
//encode ID
- MAKE_ROOM(ofs+4);
- encode_uint32(psc->id,&packet_cache[ofs]);
- ofs+=4;
+ MAKE_ROOM(ofs + 4);
+ encode_uint32(psc->id, &packet_cache[ofs]);
+ ofs += 4;
//encode function name
CharString name = String(p_name).utf8();
- int len = encode_cstring(name.get_data(),NULL);
- MAKE_ROOM(ofs+len);
- encode_cstring(name.get_data(),&packet_cache[ofs]);
- ofs+=len;
+ int len = encode_cstring(name.get_data(), NULL);
+ MAKE_ROOM(ofs + len);
+ encode_cstring(name.get_data(), &packet_cache[ofs]);
+ ofs += len;
if (p_set) {
//set argument
- Error err = encode_variant(*p_arg[0],NULL,len);
- ERR_FAIL_COND(err!=OK);
- MAKE_ROOM(ofs+len);
- encode_variant(*p_arg[0],&packet_cache[ofs],len);
- ofs+=len;
+ Error err = encode_variant(*p_arg[0], NULL, len);
+ ERR_FAIL_COND(err != OK);
+ MAKE_ROOM(ofs + len);
+ encode_variant(*p_arg[0], &packet_cache[ofs], len);
+ ofs += len;
} else {
//call arguments
- MAKE_ROOM(ofs+1);
- packet_cache[ofs]=p_argcount;
- ofs+=1;
- for(int i=0;i<p_argcount;i++) {
- Error err = encode_variant(*p_arg[i],NULL,len);
- ERR_FAIL_COND(err!=OK);
- MAKE_ROOM(ofs+len);
- encode_variant(*p_arg[i],&packet_cache[ofs],len);
- ofs+=len;
+ MAKE_ROOM(ofs + 1);
+ packet_cache[ofs] = p_argcount;
+ ofs += 1;
+ for (int i = 0; i < p_argcount; i++) {
+ Error err = encode_variant(*p_arg[i], NULL, len);
+ ERR_FAIL_COND(err != OK);
+ MAKE_ROOM(ofs + len);
+ encode_variant(*p_arg[i], &packet_cache[ofs], len);
+ ofs += len;
}
-
}
//see if all peers have cached path (is so, call can be fast)
- bool has_all_peers=true;
+ bool has_all_peers = true;
List<int> peers_to_add; //if one is missing, take note to add it
- for (Set<int>::Element *E=connected_peers.front();E;E=E->next()) {
+ for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
- if (p_to<0 && E->get()==-p_to)
+ if (p_to < 0 && E->get() == -p_to)
continue; //continue, excluded
- if (p_to>0 && E->get()!=p_to)
+ if (p_to > 0 && E->get() != p_to)
continue; //continue, not for this peer
- Map<int,bool>::Element *F = psc->confirmed_peers.find(E->get());
+ Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
- if (!F || F->get()==false) {
+ if (!F || F->get() == false) {
//path was not cached, or was cached but is unconfirmed
if (!F) {
//not cached at all, take note
peers_to_add.push_back(E->get());
}
- has_all_peers=false;
+ has_all_peers = false;
}
}
//those that need to be added, send a message for this
- for (List<int>::Element *E=peers_to_add.front();E;E=E->next()) {
+ for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
//encode function name
CharString pname = String(from_path).utf8();
- int len = encode_cstring(pname.get_data(),NULL);
+ int len = encode_cstring(pname.get_data(), NULL);
Vector<uint8_t> packet;
- packet.resize(1+4+len);
- packet[0]=NETWORK_COMMAND_SIMPLIFY_PATH;
- encode_uint32(psc->id,&packet[1]);
- encode_cstring(pname.get_data(),&packet[5]);
+ packet.resize(1 + 4 + len);
+ packet[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
+ encode_uint32(psc->id, &packet[1]);
+ encode_cstring(pname.get_data(), &packet[5]);
network_peer->set_target_peer(E->get()); //to all of you
network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
- network_peer->put_packet(packet.ptr(),packet.size());
+ network_peer->put_packet(packet.ptr(), packet.size());
- psc->confirmed_peers.insert(E->get(),false); //insert into confirmed, but as false since it was not confirmed
+ psc->confirmed_peers.insert(E->get(), false); //insert into confirmed, but as false since it was not confirmed
}
//take chance and set transfer mode, since all send methods will use it
@@ -1977,150 +1885,141 @@ void SceneTree::_rpc(Node* p_from,int p_to,bool p_unreliable,bool p_set,const St
//they all have verified paths, so send fast
network_peer->set_target_peer(p_to); //to all of you
- network_peer->put_packet(packet_cache.ptr(),ofs); //a message with love
+ network_peer->put_packet(packet_cache.ptr(), ofs); //a message with love
} else {
//not all verified path, so send one by one
//apend path at the end, since we will need it for some packets
CharString pname = String(from_path).utf8();
- int path_len = encode_cstring(pname.get_data(),NULL);
- MAKE_ROOM(ofs+path_len);
- encode_cstring(pname.get_data(),&packet_cache[ofs]);
+ int path_len = encode_cstring(pname.get_data(), NULL);
+ MAKE_ROOM(ofs + path_len);
+ encode_cstring(pname.get_data(), &packet_cache[ofs]);
+ for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
- for (Set<int>::Element *E=connected_peers.front();E;E=E->next()) {
-
- if (p_to<0 && E->get()==-p_to)
+ if (p_to < 0 && E->get() == -p_to)
continue; //continue, excluded
- if (p_to>0 && E->get()!=p_to)
+ if (p_to > 0 && E->get() != p_to)
continue; //continue, not for this peer
- Map<int,bool>::Element *F = psc->confirmed_peers.find(E->get());
- ERR_CONTINUE(!F);//should never happen
+ Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
+ ERR_CONTINUE(!F); //should never happen
network_peer->set_target_peer(E->get()); //to this one specifically
- if (F->get()==true) {
+ if (F->get() == true) {
//this one confirmed path, so use id
- encode_uint32(psc->id,&packet_cache[1]);
- network_peer->put_packet(packet_cache.ptr(),ofs);
+ encode_uint32(psc->id, &packet_cache[1]);
+ network_peer->put_packet(packet_cache.ptr(), ofs);
} else {
//this one did not confirm path yet, so use entire path (sorry!)
- encode_uint32(0x80000000|ofs,&packet_cache[1]); //offset to path and flag
- network_peer->put_packet(packet_cache.ptr(),ofs+path_len);
+ encode_uint32(0x80000000 | ofs, &packet_cache[1]); //offset to path and flag
+ network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
}
-
}
}
}
+void SceneTree::_network_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
-void SceneTree::_network_process_packet(int p_from, const uint8_t* p_packet, int p_packet_len) {
-
- ERR_FAIL_COND(p_packet_len<5);
+ ERR_FAIL_COND(p_packet_len < 5);
uint8_t packet_type = p_packet[0];
- switch(packet_type) {
+ switch (packet_type) {
case NETWORK_COMMAND_REMOTE_CALL:
case NETWORK_COMMAND_REMOTE_SET: {
- ERR_FAIL_COND(p_packet_len<5);
+ ERR_FAIL_COND(p_packet_len < 5);
uint32_t target = decode_uint32(&p_packet[1]);
+ Node *node = NULL;
- Node *node=NULL;
-
- if (target&0x80000000) {
+ if (target & 0x80000000) {
- int ofs = target&0x7FFFFFFF;
- ERR_FAIL_COND(ofs>=p_packet_len);
+ int ofs = target & 0x7FFFFFFF;
+ ERR_FAIL_COND(ofs >= p_packet_len);
String paths;
- paths.parse_utf8((const char*)&p_packet[ofs],p_packet_len-ofs);
+ paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
NodePath np = paths;
node = get_root()->get_node(np);
- if (node==NULL) {
- ERR_EXPLAIN("Failed to get path from RPC: "+String(np));
- ERR_FAIL_COND(node==NULL);
+ if (node == NULL) {
+ ERR_EXPLAIN("Failed to get path from RPC: " + String(np));
+ ERR_FAIL_COND(node == NULL);
}
} else {
int id = target;
- Map<int,PathGetCache>::Element *E=path_get_cache.find(p_from);
+ Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
ERR_FAIL_COND(!E);
- Map<int,PathGetCache::NodeInfo>::Element *F=E->get().nodes.find(id);
+ Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
ERR_FAIL_COND(!F);
PathGetCache::NodeInfo *ni = &F->get();
//do proper caching later
node = get_root()->get_node(ni->path);
- if (node==NULL) {
- ERR_EXPLAIN("Failed to get cached path from RPC: "+String(ni->path));
- ERR_FAIL_COND(node==NULL);
+ if (node == NULL) {
+ ERR_EXPLAIN("Failed to get cached path from RPC: " + String(ni->path));
+ ERR_FAIL_COND(node == NULL);
}
-
-
}
- ERR_FAIL_COND(p_packet_len<6);
+ ERR_FAIL_COND(p_packet_len < 6);
//detect cstring end
- int len_end=5;
- for(;len_end<p_packet_len;len_end++) {
- if (p_packet[len_end]==0) {
+ int len_end = 5;
+ for (; len_end < p_packet_len; len_end++) {
+ if (p_packet[len_end] == 0) {
break;
}
}
- ERR_FAIL_COND(len_end>=p_packet_len);
+ ERR_FAIL_COND(len_end >= p_packet_len);
- StringName name = String::utf8((const char*)&p_packet[5]);
+ StringName name = String::utf8((const char *)&p_packet[5]);
-
-
-
- if (packet_type==NETWORK_COMMAND_REMOTE_CALL) {
+ if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
if (!node->can_call_rpc(name))
return;
- int ofs = len_end+1;
+ int ofs = len_end + 1;
- ERR_FAIL_COND(ofs>=p_packet_len);
+ ERR_FAIL_COND(ofs >= p_packet_len);
int argc = p_packet[ofs];
Vector<Variant> args;
- Vector<const Variant*> argp;
+ Vector<const Variant *> argp;
args.resize(argc);
argp.resize(argc);
ofs++;
- for(int i=0;i<argc;i++) {
+ for (int i = 0; i < argc; i++) {
- ERR_FAIL_COND(ofs>=p_packet_len);
+ ERR_FAIL_COND(ofs >= p_packet_len);
int vlen;
- Error err = decode_variant(args[i],&p_packet[ofs],p_packet_len-ofs,&vlen);
- ERR_FAIL_COND(err!=OK);
+ Error err = decode_variant(args[i], &p_packet[ofs], p_packet_len - ofs, &vlen);
+ ERR_FAIL_COND(err != OK);
//args[i]=p_packet[3+i];
- argp[i]=&args[i];
- ofs+=vlen;
+ argp[i] = &args[i];
+ ofs += vlen;
}
Variant::CallError ce;
- node->call(name,argp.ptr(),argc,ce);
- if (ce.error!=Variant::CallError::CALL_OK) {
- String error = Variant::get_call_error_text(node,name,argp.ptr(),argc,ce);
- error="RPC - "+error;
+ node->call(name, argp.ptr(), argc, ce);
+ if (ce.error != Variant::CallError::CALL_OK) {
+ String error = Variant::get_call_error_text(node, name, argp.ptr(), argc, ce);
+ error = "RPC - " + error;
ERR_PRINTS(error);
}
@@ -2129,18 +2028,18 @@ void SceneTree::_network_process_packet(int p_from, const uint8_t* p_packet, int
if (!node->can_call_rset(name))
return;
- int ofs = len_end+1;
+ int ofs = len_end + 1;
- ERR_FAIL_COND(ofs>=p_packet_len);
+ ERR_FAIL_COND(ofs >= p_packet_len);
Variant value;
- decode_variant(value,&p_packet[ofs],p_packet_len-ofs);
+ decode_variant(value, &p_packet[ofs], p_packet_len - ofs);
bool valid;
- node->set(name,value,&valid);
+ node->set(name, value, &valid);
if (!valid) {
- String error = "Error setting remote property '"+String(name)+"', not found in object of type "+node->get_class();
+ String error = "Error setting remote property '" + String(name) + "', not found in object of type " + node->get_class();
ERR_PRINTS(error);
}
}
@@ -2148,64 +2047,62 @@ void SceneTree::_network_process_packet(int p_from, const uint8_t* p_packet, int
} break;
case NETWORK_COMMAND_SIMPLIFY_PATH: {
- ERR_FAIL_COND(p_packet_len<5);
+ ERR_FAIL_COND(p_packet_len < 5);
int id = decode_uint32(&p_packet[1]);
String paths;
- paths.parse_utf8((const char*)&p_packet[5],p_packet_len-5);
+ paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
NodePath path = paths;
if (!path_get_cache.has(p_from)) {
- path_get_cache[p_from]=PathGetCache();
+ path_get_cache[p_from] = PathGetCache();
}
PathGetCache::NodeInfo ni;
- ni.path=path;
- ni.instance=0;
-
- path_get_cache[p_from].nodes[id]=ni;
+ ni.path = path;
+ ni.instance = 0;
+ path_get_cache[p_from].nodes[id] = ni;
{
//send ack
//encode path
CharString pname = String(path).utf8();
- int len = encode_cstring(pname.get_data(),NULL);
+ int len = encode_cstring(pname.get_data(), NULL);
Vector<uint8_t> packet;
- packet.resize(1+len);
- packet[0]=NETWORK_COMMAND_CONFIRM_PATH;
- encode_cstring(pname.get_data(),&packet[1]);
+ packet.resize(1 + len);
+ packet[0] = NETWORK_COMMAND_CONFIRM_PATH;
+ encode_cstring(pname.get_data(), &packet[1]);
network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
network_peer->set_target_peer(p_from);
- network_peer->put_packet(packet.ptr(),packet.size());
+ network_peer->put_packet(packet.ptr(), packet.size());
}
} break;
case NETWORK_COMMAND_CONFIRM_PATH: {
String paths;
- paths.parse_utf8((const char*)&p_packet[1],p_packet_len-1);
+ paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
NodePath path = paths;
PathSentCache *psc = path_send_cache.getptr(path);
ERR_FAIL_COND(!psc);
- Map<int,bool>::Element *E=psc->confirmed_peers.find(p_from);
+ Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
ERR_FAIL_COND(!E);
- E->get()=true;
+ E->get() = true;
} break;
}
-
}
void SceneTree::_network_poll() {
- if (!network_peer.is_valid() || network_peer->get_connection_status()==NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
+ if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
return;
network_peer->poll();
@@ -2213,269 +2110,245 @@ void SceneTree::_network_poll() {
if (!network_peer.is_valid()) //it's possible that polling might have resulted in a disconnection, so check here
return;
- while(network_peer->get_available_packet_count()) {
+ while (network_peer->get_available_packet_count()) {
int sender = network_peer->get_packet_peer();
const uint8_t *packet;
int len;
- Error err = network_peer->get_packet(&packet,len);
- if (err!=OK) {
+ Error err = network_peer->get_packet(&packet, len);
+ if (err != OK) {
ERR_PRINT("Error getting packet!");
}
- _network_process_packet(sender,packet,len);
+ _network_process_packet(sender, packet, len);
if (!network_peer.is_valid()) {
break; //it's also possible that a packet or RPC caused a disconnection, so also check here
}
}
-
-
}
-
void SceneTree::_bind_methods() {
-
//ClassDB::bind_method(D_METHOD("call_group","call_flags","group","method","arg1","arg2"),&SceneMainLoop::_call_group,DEFVAL(Variant()),DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("get_root:Viewport"),&SceneTree::get_root);
- ClassDB::bind_method(D_METHOD("has_group","name"),&SceneTree::has_group);
+ ClassDB::bind_method(D_METHOD("get_root:Viewport"), &SceneTree::get_root);
+ ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);
- ClassDB::bind_method(D_METHOD("set_auto_accept_quit","enabled"),&SceneTree::set_auto_accept_quit);
+ ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit);
- ClassDB::bind_method(D_METHOD("set_editor_hint","enable"),&SceneTree::set_editor_hint);
- ClassDB::bind_method(D_METHOD("is_editor_hint"),&SceneTree::is_editor_hint);
- ClassDB::bind_method(D_METHOD("set_debug_collisions_hint","enable"),&SceneTree::set_debug_collisions_hint);
- ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"),&SceneTree::is_debugging_collisions_hint);
- ClassDB::bind_method(D_METHOD("set_debug_navigation_hint","enable"),&SceneTree::set_debug_navigation_hint);
- ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"),&SceneTree::is_debugging_navigation_hint);
+ ClassDB::bind_method(D_METHOD("set_editor_hint", "enable"), &SceneTree::set_editor_hint);
+ ClassDB::bind_method(D_METHOD("is_editor_hint"), &SceneTree::is_editor_hint);
+ ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint);
+ ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint);
+ ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint);
+ ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint);
#ifdef TOOLS_ENABLED
- ClassDB::bind_method(D_METHOD("set_edited_scene_root","scene"),&SceneTree::set_edited_scene_root);
- ClassDB::bind_method(D_METHOD("get_edited_scene_root"),&SceneTree::get_edited_scene_root);
+ ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root);
+ ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root);
#endif
- ClassDB::bind_method(D_METHOD("set_pause","enable"),&SceneTree::set_pause);
- ClassDB::bind_method(D_METHOD("is_paused"),&SceneTree::is_paused);
- ClassDB::bind_method(D_METHOD("set_input_as_handled"),&SceneTree::set_input_as_handled);
+ ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause);
+ ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused);
+ ClassDB::bind_method(D_METHOD("set_input_as_handled"), &SceneTree::set_input_as_handled);
- ClassDB::bind_method(D_METHOD("create_timer:SceneTreeTimer","time_sec", "pause_mode_process"),&SceneTree::create_timer, DEFVAL(true));
-
-
- ClassDB::bind_method(D_METHOD("get_node_count"),&SceneTree::get_node_count);
- ClassDB::bind_method(D_METHOD("get_frame"),&SceneTree::get_frame);
- ClassDB::bind_method(D_METHOD("quit"),&SceneTree::quit);
-
- ClassDB::bind_method(D_METHOD("set_screen_stretch","mode","aspect","minsize"),&SceneTree::set_screen_stretch);
-
- ClassDB::bind_method(D_METHOD("queue_delete","obj"),&SceneTree::queue_delete);
+ ClassDB::bind_method(D_METHOD("create_timer:SceneTreeTimer", "time_sec", "pause_mode_process"), &SceneTree::create_timer, DEFVAL(true));
+ ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count);
+ ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame);
+ ClassDB::bind_method(D_METHOD("quit"), &SceneTree::quit);
+ ClassDB::bind_method(D_METHOD("set_screen_stretch", "mode", "aspect", "minsize"), &SceneTree::set_screen_stretch);
+ ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete);
MethodInfo mi;
- mi.name="call_group_flags";
- mi.arguments.push_back( PropertyInfo( Variant::INT, "flags"));
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "group"));
- mi.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
-
+ mi.name = "call_group_flags";
+ mi.arguments.push_back(PropertyInfo(Variant::INT, "flags"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "group"));
+ mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_group_flags",&SceneTree::_call_group_flags,mi);
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi);
- ClassDB::bind_method(D_METHOD("notify_group_flags","call_flags","group","notification"),&SceneTree::notify_group_flags);
- ClassDB::bind_method(D_METHOD("set_group_flags","call_flags","group","property","value"),&SceneTree::set_group_flags);
+ ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags);
+ ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags);
MethodInfo mi2;
- mi2.name="call_group";
- mi2.arguments.push_back( PropertyInfo( Variant::STRING, "group"));
- mi2.arguments.push_back( PropertyInfo( Variant::STRING, "method"));
-
-
- ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT,"call_group",&SceneTree::_call_group,mi2);
-
- ClassDB::bind_method(D_METHOD("notify_group","call_flags","group","notification"),&SceneTree::notify_group);
- ClassDB::bind_method(D_METHOD("set_group","call_flags","group","property","value"),&SceneTree::set_group);
-
- ClassDB::bind_method(D_METHOD("get_nodes_in_group","group"),&SceneTree::_get_nodes_in_group);
+ mi2.name = "call_group";
+ mi2.arguments.push_back(PropertyInfo(Variant::STRING, "group"));
+ mi2.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
+ ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2);
- ClassDB::bind_method(D_METHOD("set_current_scene","child_node:Node"),&SceneTree::set_current_scene);
- ClassDB::bind_method(D_METHOD("get_current_scene:Node"),&SceneTree::get_current_scene);
+ ClassDB::bind_method(D_METHOD("notify_group", "call_flags", "group", "notification"), &SceneTree::notify_group);
+ ClassDB::bind_method(D_METHOD("set_group", "call_flags", "group", "property", "value"), &SceneTree::set_group);
- ClassDB::bind_method(D_METHOD("change_scene","path"),&SceneTree::change_scene);
- ClassDB::bind_method(D_METHOD("change_scene_to","packed_scene:PackedScene"),&SceneTree::change_scene_to);
+ ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group);
- ClassDB::bind_method(D_METHOD("reload_current_scene"),&SceneTree::reload_current_scene);
+ ClassDB::bind_method(D_METHOD("set_current_scene", "child_node:Node"), &SceneTree::set_current_scene);
+ ClassDB::bind_method(D_METHOD("get_current_scene:Node"), &SceneTree::get_current_scene);
- ClassDB::bind_method(D_METHOD("_change_scene"),&SceneTree::_change_scene);
+ ClassDB::bind_method(D_METHOD("change_scene", "path"), &SceneTree::change_scene);
+ ClassDB::bind_method(D_METHOD("change_scene_to", "packed_scene:PackedScene"), &SceneTree::change_scene_to);
+ ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);
- ClassDB::bind_method(D_METHOD("set_network_peer","peer:NetworkedMultiplayerPeer"),&SceneTree::set_network_peer);
- ClassDB::bind_method(D_METHOD("is_network_server"),&SceneTree::is_network_server);
- ClassDB::bind_method(D_METHOD("has_network_peer"),&SceneTree::has_network_peer);
- ClassDB::bind_method(D_METHOD("get_network_unique_id"),&SceneTree::get_network_unique_id);
- ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections","refuse"),&SceneTree::set_refuse_new_network_connections);
- ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"),&SceneTree::is_refusing_new_network_connections);
- ClassDB::bind_method(D_METHOD("_network_peer_connected"),&SceneTree::_network_peer_connected);
- ClassDB::bind_method(D_METHOD("_network_peer_disconnected"),&SceneTree::_network_peer_disconnected);
- ClassDB::bind_method(D_METHOD("_connected_to_server"),&SceneTree::_connected_to_server);
- ClassDB::bind_method(D_METHOD("_connection_failed"),&SceneTree::_connection_failed);
- ClassDB::bind_method(D_METHOD("_server_disconnected"),&SceneTree::_server_disconnected);
+ ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene);
- ADD_SIGNAL( MethodInfo("tree_changed") );
- ADD_SIGNAL( MethodInfo("node_removed",PropertyInfo( Variant::OBJECT, "node") ) );
- ADD_SIGNAL( MethodInfo("screen_resized") );
- ADD_SIGNAL( MethodInfo("node_configuration_warning_changed",PropertyInfo( Variant::OBJECT, "node")) );
+ ClassDB::bind_method(D_METHOD("set_network_peer", "peer:NetworkedMultiplayerPeer"), &SceneTree::set_network_peer);
+ ClassDB::bind_method(D_METHOD("is_network_server"), &SceneTree::is_network_server);
+ ClassDB::bind_method(D_METHOD("has_network_peer"), &SceneTree::has_network_peer);
+ ClassDB::bind_method(D_METHOD("get_network_unique_id"), &SceneTree::get_network_unique_id);
+ ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &SceneTree::set_refuse_new_network_connections);
+ ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &SceneTree::is_refusing_new_network_connections);
+ ClassDB::bind_method(D_METHOD("_network_peer_connected"), &SceneTree::_network_peer_connected);
+ ClassDB::bind_method(D_METHOD("_network_peer_disconnected"), &SceneTree::_network_peer_disconnected);
+ ClassDB::bind_method(D_METHOD("_connected_to_server"), &SceneTree::_connected_to_server);
+ ClassDB::bind_method(D_METHOD("_connection_failed"), &SceneTree::_connection_failed);
+ ClassDB::bind_method(D_METHOD("_server_disconnected"), &SceneTree::_server_disconnected);
- ADD_SIGNAL( MethodInfo("idle_frame"));
- ADD_SIGNAL( MethodInfo("fixed_frame"));
+ ADD_SIGNAL(MethodInfo("tree_changed"));
+ ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node")));
+ ADD_SIGNAL(MethodInfo("screen_resized"));
+ ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node")));
- ADD_SIGNAL( MethodInfo("files_dropped",PropertyInfo(Variant::POOL_STRING_ARRAY,"files"),PropertyInfo(Variant::INT,"screen")) );
- ADD_SIGNAL( MethodInfo("network_peer_connected",PropertyInfo(Variant::INT,"id")));
- ADD_SIGNAL( MethodInfo("network_peer_disconnected",PropertyInfo(Variant::INT,"id")));
- ADD_SIGNAL( MethodInfo("connected_to_server"));
- ADD_SIGNAL( MethodInfo("connection_failed"));
- ADD_SIGNAL( MethodInfo("server_disconnected"));
+ ADD_SIGNAL(MethodInfo("idle_frame"));
+ ADD_SIGNAL(MethodInfo("fixed_frame"));
- BIND_CONSTANT( GROUP_CALL_DEFAULT );
- BIND_CONSTANT( GROUP_CALL_REVERSE );
- BIND_CONSTANT( GROUP_CALL_REALTIME );
- BIND_CONSTANT( GROUP_CALL_UNIQUE );
+ ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen")));
+ ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
+ ADD_SIGNAL(MethodInfo("connected_to_server"));
+ ADD_SIGNAL(MethodInfo("connection_failed"));
+ ADD_SIGNAL(MethodInfo("server_disconnected"));
- BIND_CONSTANT( STRETCH_MODE_DISABLED );
- BIND_CONSTANT( STRETCH_MODE_2D );
- BIND_CONSTANT( STRETCH_MODE_VIEWPORT );
- BIND_CONSTANT( STRETCH_ASPECT_IGNORE );
- BIND_CONSTANT( STRETCH_ASPECT_KEEP );
- BIND_CONSTANT( STRETCH_ASPECT_KEEP_WIDTH );
- BIND_CONSTANT( STRETCH_ASPECT_KEEP_HEIGHT );
+ BIND_CONSTANT(GROUP_CALL_DEFAULT);
+ BIND_CONSTANT(GROUP_CALL_REVERSE);
+ BIND_CONSTANT(GROUP_CALL_REALTIME);
+ BIND_CONSTANT(GROUP_CALL_UNIQUE);
+ BIND_CONSTANT(STRETCH_MODE_DISABLED);
+ BIND_CONSTANT(STRETCH_MODE_2D);
+ BIND_CONSTANT(STRETCH_MODE_VIEWPORT);
+ BIND_CONSTANT(STRETCH_ASPECT_IGNORE);
+ BIND_CONSTANT(STRETCH_ASPECT_KEEP);
+ BIND_CONSTANT(STRETCH_ASPECT_KEEP_WIDTH);
+ BIND_CONSTANT(STRETCH_ASPECT_KEEP_HEIGHT);
}
-SceneTree *SceneTree::singleton=NULL;
-
+SceneTree *SceneTree::singleton = NULL;
SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS];
-int SceneTree::idle_callback_count=0;
+int SceneTree::idle_callback_count = 0;
void SceneTree::_call_idle_callbacks() {
- for(int i=0;i<idle_callback_count;i++) {
+ for (int i = 0; i < idle_callback_count; i++) {
idle_callbacks[i]();
}
}
void SceneTree::add_idle_callback(IdleCallback p_callback) {
- ERR_FAIL_COND(idle_callback_count>=MAX_IDLE_CALLBACKS);
- idle_callbacks[idle_callback_count++]=p_callback;
+ ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS);
+ idle_callbacks[idle_callback_count++] = p_callback;
}
-
SceneTree::SceneTree() {
- singleton=this;
- _quit=false;
- initialized=false;
- editor_hint=false;
- debug_collisions_hint=false;
- debug_navigation_hint=false;
- debug_collisions_color=GLOBAL_DEF("debug/collision/shape_color",Color(0.0,0.6,0.7,0.5));
- debug_collision_contact_color=GLOBAL_DEF("debug/collision/contact_color",Color(1.0,0.2,0.1,0.8));
- debug_navigation_color=GLOBAL_DEF("debug/navigation/geometry_color",Color(0.1,1.0,0.7,0.4));
- debug_navigation_disabled_color=GLOBAL_DEF("debug/navigation/disabled_geometry_color",Color(1.0,0.7,0.1,0.4));
- collision_debug_contacts=GLOBAL_DEF("debug/collision/max_contacts_displayed",10000);
-
-
-
- tree_version=1;
- fixed_process_time=1;
- idle_process_time=1;
- last_id=1;
- root=NULL;
- current_frame=0;
- tree_changed_name="tree_changed";
- node_removed_name="node_removed";
- ugc_locked=false;
- call_lock=0;
- root_lock=0;
- node_count=0;
+ singleton = this;
+ _quit = false;
+ initialized = false;
+ editor_hint = false;
+ debug_collisions_hint = false;
+ debug_navigation_hint = false;
+ debug_collisions_color = GLOBAL_DEF("debug/collision/shape_color", Color(0.0, 0.6, 0.7, 0.5));
+ debug_collision_contact_color = GLOBAL_DEF("debug/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
+ debug_navigation_color = GLOBAL_DEF("debug/navigation/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
+ debug_navigation_disabled_color = GLOBAL_DEF("debug/navigation/disabled_geometry_color", Color(1.0, 0.7, 0.1, 0.4));
+ collision_debug_contacts = GLOBAL_DEF("debug/collision/max_contacts_displayed", 10000);
+
+ tree_version = 1;
+ fixed_process_time = 1;
+ idle_process_time = 1;
+ last_id = 1;
+ root = NULL;
+ current_frame = 0;
+ tree_changed_name = "tree_changed";
+ node_removed_name = "node_removed";
+ ugc_locked = false;
+ call_lock = 0;
+ root_lock = 0;
+ node_count = 0;
//create with mainloop
- root = memnew( Viewport );
+ root = memnew(Viewport);
root->set_name("root");
- root->set_world( Ref<World>( memnew( World )));
+ root->set_world(Ref<World>(memnew(World)));
//root->set_world_2d( Ref<World2D>( memnew( World2D )));
root->set_as_audio_listener(true);
root->set_as_audio_listener_2d(true);
- current_scene=NULL;
+ current_scene = NULL;
- int ref_atlas_size = GLOBAL_DEF("rendering/reflections/atlas_size",2048);
- int ref_atlas_subdiv = GLOBAL_DEF("rendering/reflections/atlas_subdiv",8);
- int msaa_mode = GLOBAL_DEF("rendering/quality/msaa",0);
- GlobalConfig::get_singleton()->set_custom_property_info("rendering/quality/msaa",PropertyInfo(Variant::INT,"rendering/quality/msaa",PROPERTY_HINT_ENUM,"Disabled,2x,4x,8x,16x"));
+ int ref_atlas_size = GLOBAL_DEF("rendering/reflections/atlas_size", 2048);
+ int ref_atlas_subdiv = GLOBAL_DEF("rendering/reflections/atlas_subdiv", 8);
+ int msaa_mode = GLOBAL_DEF("rendering/quality/msaa", 0);
+ GlobalConfig::get_singleton()->set_custom_property_info("rendering/quality/msaa", PropertyInfo(Variant::INT, "rendering/quality/msaa", PROPERTY_HINT_ENUM, "Disabled,2x,4x,8x,16x"));
root->set_msaa(Viewport::MSAA(msaa_mode));
- bool hdr = GLOBAL_DEF("rendering/quality/hdr",true);
+ bool hdr = GLOBAL_DEF("rendering/quality/hdr", true);
root->set_hdr(hdr);
- VS::get_singleton()->scenario_set_reflection_atlas_size(root->get_world()->get_scenario(),ref_atlas_size,ref_atlas_subdiv);
-
+ VS::get_singleton()->scenario_set_reflection_atlas_size(root->get_world()->get_scenario(), ref_atlas_size, ref_atlas_subdiv);
- stretch_mode=STRETCH_MODE_DISABLED;
- stretch_aspect=STRETCH_ASPECT_IGNORE;
+ stretch_mode = STRETCH_MODE_DISABLED;
+ stretch_aspect = STRETCH_ASPECT_IGNORE;
- last_screen_size=Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height );
+ last_screen_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
root->set_size(last_screen_size);
if (ScriptDebugger::get_singleton()) {
- ScriptDebugger::get_singleton()->set_request_scene_tree_message_func(_debugger_request_tree,this);
+ ScriptDebugger::get_singleton()->set_request_scene_tree_message_func(_debugger_request_tree, this);
}
- root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking",true));
+ root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true));
#ifdef TOOLS_ENABLED
- edited_scene_root=NULL;
+ edited_scene_root = NULL;
#endif
#ifdef DEBUG_ENABLED
-
- live_edit_funcs.udata=this;
- live_edit_funcs.node_path_func=_live_edit_node_path_funcs;
- live_edit_funcs.res_path_func=_live_edit_res_path_funcs;
- live_edit_funcs.node_set_func=_live_edit_node_set_funcs;
- live_edit_funcs.node_set_res_func=_live_edit_node_set_res_funcs;
- live_edit_funcs.node_call_func=_live_edit_node_call_funcs;
- live_edit_funcs.res_set_func=_live_edit_res_set_funcs;
- live_edit_funcs.res_set_res_func=_live_edit_res_set_res_funcs;
- live_edit_funcs.res_call_func=_live_edit_res_call_funcs;
- live_edit_funcs.root_func=_live_edit_root_funcs;
-
- live_edit_funcs.tree_create_node_func=_live_edit_create_node_funcs;
- live_edit_funcs.tree_instance_node_func=_live_edit_instance_node_funcs;
- live_edit_funcs.tree_remove_node_func=_live_edit_remove_node_funcs;
- live_edit_funcs.tree_remove_and_keep_node_func=_live_edit_remove_and_keep_node_funcs;
- live_edit_funcs.tree_restore_node_func=_live_edit_restore_node_funcs;
- live_edit_funcs.tree_duplicate_node_func=_live_edit_duplicate_node_funcs;
- live_edit_funcs.tree_reparent_node_func=_live_edit_reparent_node_funcs;
+ live_edit_funcs.udata = this;
+ live_edit_funcs.node_path_func = _live_edit_node_path_funcs;
+ live_edit_funcs.res_path_func = _live_edit_res_path_funcs;
+ live_edit_funcs.node_set_func = _live_edit_node_set_funcs;
+ live_edit_funcs.node_set_res_func = _live_edit_node_set_res_funcs;
+ live_edit_funcs.node_call_func = _live_edit_node_call_funcs;
+ live_edit_funcs.res_set_func = _live_edit_res_set_funcs;
+ live_edit_funcs.res_set_res_func = _live_edit_res_set_res_funcs;
+ live_edit_funcs.res_call_func = _live_edit_res_call_funcs;
+ live_edit_funcs.root_func = _live_edit_root_funcs;
+
+ live_edit_funcs.tree_create_node_func = _live_edit_create_node_funcs;
+ live_edit_funcs.tree_instance_node_func = _live_edit_instance_node_funcs;
+ live_edit_funcs.tree_remove_node_func = _live_edit_remove_node_funcs;
+ live_edit_funcs.tree_remove_and_keep_node_func = _live_edit_remove_and_keep_node_funcs;
+ live_edit_funcs.tree_restore_node_func = _live_edit_restore_node_funcs;
+ live_edit_funcs.tree_duplicate_node_func = _live_edit_duplicate_node_funcs;
+ live_edit_funcs.tree_reparent_node_func = _live_edit_reparent_node_funcs;
if (ScriptDebugger::get_singleton()) {
ScriptDebugger::get_singleton()->set_live_edit_funcs(&live_edit_funcs);
}
- live_edit_root=NodePath("/root");
+ live_edit_root = NodePath("/root");
- last_send_cache_id=1;
+ last_send_cache_id = 1;
#endif
-
-
}
-
SceneTree::~SceneTree() {
-
-
}
diff --git a/scene/main/scene_main_loop.h b/scene/main/scene_main_loop.h
index 7f69f5eef7..fadf77e30f 100644
--- a/scene/main/scene_main_loop.h
+++ b/scene/main/scene_main_loop.h
@@ -29,20 +29,17 @@
#ifndef SCENE_MAIN_LOOP_H
#define SCENE_MAIN_LOOP_H
-
+#include "io/networked_multiplayer_peer.h"
#include "os/main_loop.h"
+#include "os/thread_safe.h"
#include "scene/resources/world.h"
#include "scene/resources/world_2d.h"
-#include "os/thread_safe.h"
#include "self_list.h"
-#include "io/networked_multiplayer_peer.h"
-
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class SceneTree;
class PackedScene;
class Node;
@@ -50,17 +47,16 @@ class Viewport;
class Material;
class Mesh;
-
-
class SceneTreeTimer : public Reference {
- GDCLASS(SceneTreeTimer,Reference);
+ GDCLASS(SceneTreeTimer, Reference);
float time_left;
bool process_pause;
+
protected:
static void _bind_methods();
-public:
+public:
void set_time_left(float p_time);
float get_time_left() const;
@@ -74,10 +70,9 @@ class SceneTree : public MainLoop {
_THREAD_SAFE_CLASS_
- GDCLASS( SceneTree, MainLoop );
-public:
-
+ GDCLASS(SceneTree, MainLoop);
+public:
typedef void (*IdleCallback)();
enum StretchMode {
@@ -94,15 +89,14 @@ public:
STRETCH_ASPECT_KEEP_WIDTH,
STRETCH_ASPECT_KEEP_HEIGHT,
};
-private:
-
+private:
struct Group {
- Vector<Node*> nodes;
+ Vector<Node *> nodes;
//uint64_t last_tree_version;
bool changed;
- Group() { changed=false; };
+ Group() { changed = false; };
};
Viewport *root;
@@ -120,7 +114,7 @@ private:
bool pause;
int root_lock;
- Map<StringName,Group> group_map;
+ Map<StringName, Group> group_map;
bool _quit;
bool initialized;
bool input_handled;
@@ -128,7 +122,6 @@ private:
StringName tree_changed_name;
StringName node_removed_name;
-
int64_t current_frame;
int node_count;
@@ -140,13 +133,12 @@ private:
StringName group;
StringName call;
- bool operator<(const UGCall& p_with) const { return group==p_with.group?call<p_with.call:group<p_with.group; }
+ bool operator<(const UGCall &p_with) const { return group == p_with.group ? call < p_with.call : group < p_with.group; }
};
//safety for when a node is deleted while a group is being called
int call_lock;
- Set<Node*> call_skip; //skip erased nodes
-
+ Set<Node *> call_skip; //skip erased nodes
StretchMode stretch_mode;
StretchAspect stretch_aspect;
@@ -156,15 +148,15 @@ private:
List<ObjectID> delete_queue;
- Map<UGCall,Vector<Variant> > unique_group_calls;
+ Map<UGCall, Vector<Variant> > unique_group_calls;
bool ugc_locked;
void _flush_ugc();
void _flush_transform_notifications();
- _FORCE_INLINE_ void _update_group_order(Group& g);
+ _FORCE_INLINE_ void _update_group_order(Group &g);
void _update_listener();
- Array _get_nodes_in_group(const StringName& p_group);
+ Array _get_nodes_in_group(const StringName &p_group);
Node *current_scene;
@@ -178,12 +170,11 @@ private:
Ref<Material> collision_material;
int collision_debug_contacts;
- void _change_scene(Node* p_to);
+ void _change_scene(Node *p_to);
//void _call_group(uint32_t p_call_flags,const StringName& p_group,const StringName& p_function,const Variant& p_arg1,const Variant& p_arg2);
List<Ref<SceneTreeTimer> > timers;
-
///network///
enum NetworkCommands {
@@ -205,11 +196,11 @@ private:
//path sent caches
struct PathSentCache {
- Map<int,bool> confirmed_peers;
+ Map<int, bool> confirmed_peers;
int id;
};
- HashMap<NodePath,PathSentCache> path_send_cache;
+ HashMap<NodePath, PathSentCache> path_send_cache;
int last_send_cache_id;
//path get caches
@@ -219,10 +210,10 @@ private:
ObjectID instance;
};
- Map<int,NodeInfo> nodes;
+ Map<int, NodeInfo> nodes;
};
- Map<int,PathGetCache> path_get_cache;
+ Map<int, PathGetCache> path_get_cache;
Vector<uint8_t> packet_cache;
@@ -230,91 +221,85 @@ private:
void _network_poll();
static SceneTree *singleton;
-friend class Node;
-
-
+ friend class Node;
-
- void _rpc(Node* p_from,int p_to,bool p_unreliable,bool p_set,const StringName& p_name,const Variant** p_arg,int p_argcount);
+ void _rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount);
void tree_changed();
void node_removed(Node *p_node);
+ Group *add_to_group(const StringName &p_group, Node *p_node);
+ void remove_from_group(const StringName &p_group, Node *p_node);
- Group* add_to_group(const StringName& p_group, Node *p_node);
- void remove_from_group(const StringName& p_group, Node *p_node);
-
- void _notify_group_pause(const StringName& p_group,int p_notification);
- void _call_input_pause(const StringName& p_group,const StringName& p_method,const InputEvent& p_input);
- Variant _call_group_flags(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
- Variant _call_group(const Variant** p_args, int p_argcount, Variant::CallError& r_error);
-
-
+ void _notify_group_pause(const StringName &p_group, int p_notification);
+ void _call_input_pause(const StringName &p_group, const StringName &p_method, const InputEvent &p_input);
+ Variant _call_group_flags(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
+ Variant _call_group(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
static void _debugger_request_tree(void *self);
void _flush_delete_queue();
-//optimization
-friend class CanvasItem;
-friend class Spatial;
-friend class Viewport;
+ //optimization
+ friend class CanvasItem;
+ friend class Spatial;
+ friend class Viewport;
SelfList<Node>::List xform_change_list;
#ifdef DEBUG_ENABLED
- Map<int,NodePath> live_edit_node_path_cache;
- Map<int,String> live_edit_resource_cache;
+ Map<int, NodePath> live_edit_node_path_cache;
+ Map<int, String> live_edit_resource_cache;
NodePath live_edit_root;
String live_edit_scene;
- Map<String,Set<Node*> > live_scene_edit_cache;
- Map<Node*,Map<ObjectID,Node*> > live_edit_remove_list;
+ Map<String, Set<Node *> > live_scene_edit_cache;
+ Map<Node *, Map<ObjectID, Node *> > live_edit_remove_list;
ScriptDebugger::LiveEditFuncs live_edit_funcs;
- void _live_edit_node_path_func(const NodePath &p_path,int p_id) ;
- void _live_edit_res_path_func(const String &p_path,int p_id) ;
-
- void _live_edit_node_set_func(int p_id,const StringName& p_prop,const Variant& p_value) ;
- void _live_edit_node_set_res_func(int p_id,const StringName& p_prop,const String& p_value) ;
- void _live_edit_node_call_func(int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) ;
- void _live_edit_res_set_func(int p_id,const StringName& p_prop,const Variant& p_value) ;
- void _live_edit_res_set_res_func(int p_id,const StringName& p_prop,const String& p_value) ;
- void _live_edit_res_call_func(int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) ;
- void _live_edit_root_func(const NodePath& p_scene_path,const String& p_scene_from) ;
-
- void _live_edit_create_node_func(const NodePath& p_parent,const String& p_type,const String& p_name);
- void _live_edit_instance_node_func(const NodePath& p_parent,const String& p_path,const String& p_name);
- void _live_edit_remove_node_func(const NodePath& p_at);
- void _live_edit_remove_and_keep_node_func(const NodePath& p_at,ObjectID p_keep_id);
- void _live_edit_restore_node_func(ObjectID p_id,const NodePath& p_at,int p_at_pos);
- void _live_edit_duplicate_node_func(const NodePath& p_at,const String& p_new_name);
- void _live_edit_reparent_node_func(const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos);
-
- static void _live_edit_node_path_funcs(void *self,const NodePath &p_path,int p_id) { reinterpret_cast<SceneTree*>(self)->_live_edit_node_path_func(p_path,p_id); }
- static void _live_edit_res_path_funcs(void *self,const String &p_path,int p_id) { reinterpret_cast<SceneTree*>(self)->_live_edit_res_path_func(p_path,p_id); }
-
- static void _live_edit_node_set_funcs(void *self,int p_id,const StringName& p_prop,const Variant& p_value) { reinterpret_cast<SceneTree*>(self)->_live_edit_node_set_func(p_id,p_prop,p_value); }
- static void _live_edit_node_set_res_funcs(void *self,int p_id,const StringName& p_prop,const String& p_value) { reinterpret_cast<SceneTree*>(self)->_live_edit_node_set_res_func(p_id,p_prop,p_value); }
- static void _live_edit_node_call_funcs(void *self,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) { reinterpret_cast<SceneTree*>(self)->_live_edit_node_call_func(p_id,p_method,VARIANT_ARG_PASS); }
- static void _live_edit_res_set_funcs(void *self,int p_id,const StringName& p_prop,const Variant& p_value) { reinterpret_cast<SceneTree*>(self)->_live_edit_res_set_func(p_id,p_prop,p_value); }
- static void _live_edit_res_set_res_funcs(void *self,int p_id,const StringName& p_prop,const String& p_value) { reinterpret_cast<SceneTree*>(self)->_live_edit_res_set_res_func(p_id,p_prop,p_value); }
- static void _live_edit_res_call_funcs(void *self,int p_id,const StringName& p_method,VARIANT_ARG_DECLARE) { reinterpret_cast<SceneTree*>(self)->_live_edit_res_call_func(p_id,p_method,VARIANT_ARG_PASS); }
- static void _live_edit_root_funcs(void *self, const NodePath& p_scene_path,const String& p_scene_from) { reinterpret_cast<SceneTree*>(self)->_live_edit_root_func(p_scene_path,p_scene_from); }
-
- static void _live_edit_create_node_funcs(void* self,const NodePath& p_parent,const String& p_type,const String& p_name) { reinterpret_cast<SceneTree*>(self)->_live_edit_create_node_func(p_parent,p_type,p_name); }
- static void _live_edit_instance_node_funcs(void* self,const NodePath& p_parent,const String& p_path,const String& p_name) { reinterpret_cast<SceneTree*>(self)->_live_edit_instance_node_func(p_parent,p_path,p_name); }
- static void _live_edit_remove_node_funcs(void* self,const NodePath& p_at) { reinterpret_cast<SceneTree*>(self)->_live_edit_remove_node_func(p_at); }
- static void _live_edit_remove_and_keep_node_funcs(void* self,const NodePath& p_at,ObjectID p_keep_id) { reinterpret_cast<SceneTree*>(self)->_live_edit_remove_and_keep_node_func(p_at,p_keep_id); }
- static void _live_edit_restore_node_funcs(void* self,ObjectID p_id,const NodePath& p_at,int p_at_pos) { reinterpret_cast<SceneTree*>(self)->_live_edit_restore_node_func(p_id,p_at,p_at_pos); }
- static void _live_edit_duplicate_node_funcs(void* self,const NodePath& p_at,const String& p_new_name) { reinterpret_cast<SceneTree*>(self)->_live_edit_duplicate_node_func(p_at,p_new_name); }
- static void _live_edit_reparent_node_funcs(void* self,const NodePath& p_at,const NodePath& p_new_place,const String& p_new_name,int p_at_pos) { reinterpret_cast<SceneTree*>(self)->_live_edit_reparent_node_func(p_at,p_new_place,p_new_name,p_at_pos); }
+ void _live_edit_node_path_func(const NodePath &p_path, int p_id);
+ void _live_edit_res_path_func(const String &p_path, int p_id);
+
+ void _live_edit_node_set_func(int p_id, const StringName &p_prop, const Variant &p_value);
+ void _live_edit_node_set_res_func(int p_id, const StringName &p_prop, const String &p_value);
+ void _live_edit_node_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE);
+ void _live_edit_res_set_func(int p_id, const StringName &p_prop, const Variant &p_value);
+ void _live_edit_res_set_res_func(int p_id, const StringName &p_prop, const String &p_value);
+ void _live_edit_res_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE);
+ void _live_edit_root_func(const NodePath &p_scene_path, const String &p_scene_from);
+
+ void _live_edit_create_node_func(const NodePath &p_parent, const String &p_type, const String &p_name);
+ void _live_edit_instance_node_func(const NodePath &p_parent, const String &p_path, const String &p_name);
+ void _live_edit_remove_node_func(const NodePath &p_at);
+ void _live_edit_remove_and_keep_node_func(const NodePath &p_at, ObjectID p_keep_id);
+ void _live_edit_restore_node_func(ObjectID p_id, const NodePath &p_at, int p_at_pos);
+ void _live_edit_duplicate_node_func(const NodePath &p_at, const String &p_new_name);
+ void _live_edit_reparent_node_func(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos);
+
+ static void _live_edit_node_path_funcs(void *self, const NodePath &p_path, int p_id) { reinterpret_cast<SceneTree *>(self)->_live_edit_node_path_func(p_path, p_id); }
+ static void _live_edit_res_path_funcs(void *self, const String &p_path, int p_id) { reinterpret_cast<SceneTree *>(self)->_live_edit_res_path_func(p_path, p_id); }
+
+ static void _live_edit_node_set_funcs(void *self, int p_id, const StringName &p_prop, const Variant &p_value) { reinterpret_cast<SceneTree *>(self)->_live_edit_node_set_func(p_id, p_prop, p_value); }
+ static void _live_edit_node_set_res_funcs(void *self, int p_id, const StringName &p_prop, const String &p_value) { reinterpret_cast<SceneTree *>(self)->_live_edit_node_set_res_func(p_id, p_prop, p_value); }
+ static void _live_edit_node_call_funcs(void *self, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { reinterpret_cast<SceneTree *>(self)->_live_edit_node_call_func(p_id, p_method, VARIANT_ARG_PASS); }
+ static void _live_edit_res_set_funcs(void *self, int p_id, const StringName &p_prop, const Variant &p_value) { reinterpret_cast<SceneTree *>(self)->_live_edit_res_set_func(p_id, p_prop, p_value); }
+ static void _live_edit_res_set_res_funcs(void *self, int p_id, const StringName &p_prop, const String &p_value) { reinterpret_cast<SceneTree *>(self)->_live_edit_res_set_res_func(p_id, p_prop, p_value); }
+ static void _live_edit_res_call_funcs(void *self, int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { reinterpret_cast<SceneTree *>(self)->_live_edit_res_call_func(p_id, p_method, VARIANT_ARG_PASS); }
+ static void _live_edit_root_funcs(void *self, const NodePath &p_scene_path, const String &p_scene_from) { reinterpret_cast<SceneTree *>(self)->_live_edit_root_func(p_scene_path, p_scene_from); }
+
+ static void _live_edit_create_node_funcs(void *self, const NodePath &p_parent, const String &p_type, const String &p_name) { reinterpret_cast<SceneTree *>(self)->_live_edit_create_node_func(p_parent, p_type, p_name); }
+ static void _live_edit_instance_node_funcs(void *self, const NodePath &p_parent, const String &p_path, const String &p_name) { reinterpret_cast<SceneTree *>(self)->_live_edit_instance_node_func(p_parent, p_path, p_name); }
+ static void _live_edit_remove_node_funcs(void *self, const NodePath &p_at) { reinterpret_cast<SceneTree *>(self)->_live_edit_remove_node_func(p_at); }
+ static void _live_edit_remove_and_keep_node_funcs(void *self, const NodePath &p_at, ObjectID p_keep_id) { reinterpret_cast<SceneTree *>(self)->_live_edit_remove_and_keep_node_func(p_at, p_keep_id); }
+ static void _live_edit_restore_node_funcs(void *self, ObjectID p_id, const NodePath &p_at, int p_at_pos) { reinterpret_cast<SceneTree *>(self)->_live_edit_restore_node_func(p_id, p_at, p_at_pos); }
+ static void _live_edit_duplicate_node_funcs(void *self, const NodePath &p_at, const String &p_new_name) { reinterpret_cast<SceneTree *>(self)->_live_edit_duplicate_node_func(p_at, p_new_name); }
+ static void _live_edit_reparent_node_funcs(void *self, const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) { reinterpret_cast<SceneTree *>(self)->_live_edit_reparent_node_func(p_at, p_new_place, p_new_name, p_at_pos); }
#endif
enum {
- MAX_IDLE_CALLBACKS=256
+ MAX_IDLE_CALLBACKS = 256
};
static IdleCallback idle_callbacks[MAX_IDLE_CALLBACKS];
@@ -322,39 +307,36 @@ friend class Viewport;
void _call_idle_callbacks();
protected:
-
-
void _notification(int p_notification);
static void _bind_methods();
public:
-
enum {
- NOTIFICATION_TRANSFORM_CHANGED=29
+ NOTIFICATION_TRANSFORM_CHANGED = 29
};
enum CallGroupFlags {
- GROUP_CALL_DEFAULT=0,
- GROUP_CALL_REVERSE=1,
- GROUP_CALL_REALTIME=2,
- GROUP_CALL_UNIQUE=4,
- GROUP_CALL_MULTILEVEL=8,
+ GROUP_CALL_DEFAULT = 0,
+ GROUP_CALL_REVERSE = 1,
+ GROUP_CALL_REALTIME = 2,
+ GROUP_CALL_UNIQUE = 4,
+ GROUP_CALL_MULTILEVEL = 8,
};
_FORCE_INLINE_ Viewport *get_root() const { return root; }
uint32_t get_last_event_id() const;
- void call_group_flags(uint32_t p_call_flags,const StringName& p_group,const StringName& p_function,VARIANT_ARG_LIST);
- void notify_group_flags(uint32_t p_call_flags,const StringName& p_group,int p_notification);
- void set_group_flags(uint32_t p_call_flags,const StringName& p_group,const String& p_name,const Variant& p_value);
+ void call_group_flags(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, VARIANT_ARG_LIST);
+ void notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification);
+ void set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value);
- void call_group(const StringName& p_group,const StringName& p_function,VARIANT_ARG_LIST);
- void notify_group(const StringName& p_group,int p_notification);
- void set_group(const StringName& p_group,const String& p_name,const Variant& p_value);
+ void call_group(const StringName &p_group, const StringName &p_function, VARIANT_ARG_LIST);
+ void notify_group(const StringName &p_group, int p_notification);
+ void set_group(const StringName &p_group, const String &p_name, const Variant &p_value);
- virtual void input_text( const String& p_text );
- virtual void input_event( const InputEvent& p_event );
+ virtual void input_text(const String &p_text);
+ virtual void input_event(const InputEvent &p_event);
virtual void init();
virtual bool iteration(float p_time);
@@ -374,12 +356,12 @@ public:
void set_editor_hint(bool p_enabled);
bool is_editor_hint() const;
- bool is_node_being_edited(const Node* p_node) const;
+ bool is_node_being_edited(const Node *p_node) const;
void set_pause(bool p_enabled);
bool is_paused() const;
- void set_camera(const RID& p_camera);
+ void set_camera(const RID &p_camera);
RID get_camera() const;
void set_debug_collisions_hint(bool p_enabled);
@@ -388,19 +370,18 @@ public:
void set_debug_navigation_hint(bool p_enabled);
bool is_debugging_navigation_hint() const;
- void set_debug_collisions_color(const Color& p_color);
+ void set_debug_collisions_color(const Color &p_color);
Color get_debug_collisions_color() const;
- void set_debug_collision_contact_color(const Color& p_color);
+ void set_debug_collision_contact_color(const Color &p_color);
Color get_debug_collision_contact_color() const;
- void set_debug_navigation_color(const Color& p_color);
+ void set_debug_navigation_color(const Color &p_color);
Color get_debug_navigation_color() const;
- void set_debug_navigation_disabled_color(const Color& p_color);
+ void set_debug_navigation_disabled_color(const Color &p_color);
Color get_debug_navigation_disabled_color() const;
-
Ref<Material> get_debug_navigation_material();
Ref<Material> get_debug_navigation_disabled_material();
Ref<Material> get_debug_collision_material();
@@ -414,38 +395,37 @@ public:
void queue_delete(Object *p_object);
- void get_nodes_in_group(const StringName& p_group,List<Node*> *p_list);
- bool has_group(const StringName& p_identifier) const;
-
+ void get_nodes_in_group(const StringName &p_group, List<Node *> *p_list);
+ bool has_group(const StringName &p_identifier) const;
- void set_screen_stretch(StretchMode p_mode,StretchAspect p_aspect,const Size2 p_minsize);
+ void set_screen_stretch(StretchMode p_mode, StretchAspect p_aspect, const Size2 p_minsize);
- //void change_scene(const String& p_path);
- //Node *get_loaded_scene();
+//void change_scene(const String& p_path);
+//Node *get_loaded_scene();
#ifdef TOOLS_ENABLED
void set_edited_scene_root(Node *p_node);
Node *get_edited_scene_root() const;
#endif
- void set_current_scene(Node* p_scene);
- Node* get_current_scene() const;
- Error change_scene(const String& p_path);
- Error change_scene_to(const Ref<PackedScene>& p_scene);
+ void set_current_scene(Node *p_scene);
+ Node *get_current_scene() const;
+ Error change_scene(const String &p_path);
+ Error change_scene_to(const Ref<PackedScene> &p_scene);
Error reload_current_scene();
- Ref<SceneTreeTimer> create_timer(float p_delay_sec, bool p_process_pause=true);
+ Ref<SceneTreeTimer> create_timer(float p_delay_sec, bool p_process_pause = true);
//used by Main::start, don't use otherwise
- void add_current_scene(Node * p_current);
+ void add_current_scene(Node *p_current);
- static SceneTree* get_singleton() { return singleton; }
+ static SceneTree *get_singleton() { return singleton; }
- void drop_files(const Vector<String>& p_files,int p_from_screen=0);
+ void drop_files(const Vector<String> &p_files, int p_from_screen = 0);
//network API
- void set_network_peer(const Ref<NetworkedMultiplayerPeer>& p_network_peer);
+ void set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_network_peer);
bool is_network_server() const;
bool has_network_peer() const;
int get_network_unique_id() const;
@@ -456,13 +436,9 @@ public:
static void add_idle_callback(IdleCallback p_callback);
SceneTree();
~SceneTree();
-
};
-
-VARIANT_ENUM_CAST( SceneTree::StretchMode );
-VARIANT_ENUM_CAST( SceneTree::StretchAspect );
-
-
+VARIANT_ENUM_CAST(SceneTree::StretchMode);
+VARIANT_ENUM_CAST(SceneTree::StretchAspect);
#endif
diff --git a/scene/main/timer.cpp b/scene/main/timer.cpp
index d27b53d48b..5df30e5080 100644
--- a/scene/main/timer.cpp
+++ b/scene/main/timer.cpp
@@ -28,21 +28,19 @@
/*************************************************************************/
#include "timer.h"
-
void Timer::_notification(int p_what) {
- switch(p_what) {
-
+ switch (p_what) {
case NOTIFICATION_READY: {
if (autostart) {
#ifdef TOOLS_ENABLED
- if (get_tree()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root()==this || get_tree()->get_edited_scene_root()->is_a_parent_of(this)))
+ if (get_tree()->is_editor_hint() && get_tree()->get_edited_scene_root() && (get_tree()->get_edited_scene_root() == this || get_tree()->get_edited_scene_root()->is_a_parent_of(this)))
break;
#endif
start();
- autostart=false;
+ autostart = false;
}
} break;
case NOTIFICATION_INTERNAL_PROCESS: {
@@ -50,7 +48,7 @@ void Timer::_notification(int p_what) {
return;
time_left -= get_process_delta_time();
- if (time_left<0) {
+ if (time_left < 0) {
if (!one_shot)
//time_left=wait_time+time_left;
time_left = wait_time;
@@ -66,7 +64,7 @@ void Timer::_notification(int p_what) {
return;
time_left -= get_fixed_process_delta_time();
- if (time_left<0) {
+ if (time_left < 0) {
if (!one_shot)
//time_left = wait_time + time_left;
time_left = wait_time;
@@ -79,13 +77,10 @@ void Timer::_notification(int p_what) {
}
}
-
-
void Timer::set_wait_time(float p_time) {
ERR_EXPLAIN("time should be greater than zero.");
- ERR_FAIL_COND(p_time<=0);
- wait_time=p_time;
-
+ ERR_FAIL_COND(p_time <= 0);
+ wait_time = p_time;
}
float Timer::get_wait_time() const {
@@ -94,7 +89,7 @@ float Timer::get_wait_time() const {
void Timer::set_one_shot(bool p_one_shot) {
- one_shot=p_one_shot;
+ one_shot = p_one_shot;
}
bool Timer::is_one_shot() const {
@@ -103,7 +98,7 @@ bool Timer::is_one_shot() const {
void Timer::set_autostart(bool p_start) {
- autostart=p_start;
+ autostart = p_start;
}
bool Timer::has_autostart() const {
@@ -111,24 +106,22 @@ bool Timer::has_autostart() const {
}
void Timer::start() {
- time_left=wait_time;
+ time_left = wait_time;
_set_process(true);
}
void Timer::stop() {
- time_left=-1;
+ time_left = -1;
_set_process(false);
- autostart=false;
+ autostart = false;
}
-
void Timer::set_active(bool p_active) {
if (active == p_active)
return;
active = p_active;
_set_process(processing);
-
}
bool Timer::is_active() const {
@@ -137,7 +130,7 @@ bool Timer::is_active() const {
float Timer::get_time_left() const {
- return time_left >0 ? time_left : 0;
+ return time_left > 0 ? time_left : 0;
}
void Timer::set_timer_process_mode(TimerProcessMode p_mode) {
@@ -151,25 +144,23 @@ void Timer::set_timer_process_mode(TimerProcessMode p_mode) {
set_fixed_process_internal(false);
set_process_internal(true);
}
- break;
+ break;
case TIMER_PROCESS_IDLE:
if (is_processing_internal()) {
set_process_internal(false);
set_fixed_process_internal(true);
}
- break;
+ break;
}
timer_process_mode = p_mode;
}
-Timer::TimerProcessMode Timer::get_timer_process_mode() const{
+Timer::TimerProcessMode Timer::get_timer_process_mode() const {
return timer_process_mode;
}
-
-void Timer::_set_process(bool p_process, bool p_force)
-{
+void Timer::_set_process(bool p_process, bool p_force) {
switch (timer_process_mode) {
case TIMER_PROCESS_FIXED: set_fixed_process_internal(p_process && active); break;
case TIMER_PROCESS_IDLE: set_process_internal(p_process && active); break;
@@ -179,43 +170,42 @@ void Timer::_set_process(bool p_process, bool p_force)
void Timer::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_wait_time","time_sec"),&Timer::set_wait_time);
- ClassDB::bind_method(D_METHOD("get_wait_time"),&Timer::get_wait_time);
+ ClassDB::bind_method(D_METHOD("set_wait_time", "time_sec"), &Timer::set_wait_time);
+ ClassDB::bind_method(D_METHOD("get_wait_time"), &Timer::get_wait_time);
- ClassDB::bind_method(D_METHOD("set_one_shot","enable"),&Timer::set_one_shot);
- ClassDB::bind_method(D_METHOD("is_one_shot"),&Timer::is_one_shot);
+ ClassDB::bind_method(D_METHOD("set_one_shot", "enable"), &Timer::set_one_shot);
+ ClassDB::bind_method(D_METHOD("is_one_shot"), &Timer::is_one_shot);
- ClassDB::bind_method(D_METHOD("set_autostart","enable"),&Timer::set_autostart);
- ClassDB::bind_method(D_METHOD("has_autostart"),&Timer::has_autostart);
+ ClassDB::bind_method(D_METHOD("set_autostart", "enable"), &Timer::set_autostart);
+ ClassDB::bind_method(D_METHOD("has_autostart"), &Timer::has_autostart);
- ClassDB::bind_method(D_METHOD("start"),&Timer::start);
- ClassDB::bind_method(D_METHOD("stop"),&Timer::stop);
+ ClassDB::bind_method(D_METHOD("start"), &Timer::start);
+ ClassDB::bind_method(D_METHOD("stop"), &Timer::stop);
ClassDB::bind_method(D_METHOD("set_active", "active"), &Timer::set_active);
ClassDB::bind_method(D_METHOD("is_active"), &Timer::is_active);
- ClassDB::bind_method(D_METHOD("get_time_left"),&Timer::get_time_left);
+ ClassDB::bind_method(D_METHOD("get_time_left"), &Timer::get_time_left);
ClassDB::bind_method(D_METHOD("set_timer_process_mode", "mode"), &Timer::set_timer_process_mode);
ClassDB::bind_method(D_METHOD("get_timer_process_mode"), &Timer::get_timer_process_mode);
- ADD_SIGNAL( MethodInfo("timeout") );
-
- ADD_PROPERTY( PropertyInfo(Variant::INT, "process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_timer_process_mode", "get_timer_process_mode") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL, "wait_time", PROPERTY_HINT_EXP_RANGE, "0.01,4096,0.01" ), "set_wait_time", "get_wait_time") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "one_shot" ), "set_one_shot", "is_one_shot") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL, "autostart" ), "set_autostart", "has_autostart") ;
+ ADD_SIGNAL(MethodInfo("timeout"));
- BIND_CONSTANT( TIMER_PROCESS_FIXED );
- BIND_CONSTANT( TIMER_PROCESS_IDLE );
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "process_mode", PROPERTY_HINT_ENUM, "Fixed,Idle"), "set_timer_process_mode", "get_timer_process_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wait_time", PROPERTY_HINT_EXP_RANGE, "0.01,4096,0.01"), "set_wait_time", "get_wait_time");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "one_shot"), "set_one_shot", "is_one_shot");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autostart"), "set_autostart", "has_autostart");
+ BIND_CONSTANT(TIMER_PROCESS_FIXED);
+ BIND_CONSTANT(TIMER_PROCESS_IDLE);
}
Timer::Timer() {
timer_process_mode = TIMER_PROCESS_IDLE;
- autostart=false;
- wait_time=1;
- one_shot=false;
+ autostart = false;
+ wait_time = 1;
+ one_shot = false;
time_left = -1;
processing = false;
active = true;
diff --git a/scene/main/timer.h b/scene/main/timer.h
index 6b69f3f409..756b779717 100644
--- a/scene/main/timer.h
+++ b/scene/main/timer.h
@@ -33,7 +33,7 @@
class Timer : public Node {
- GDCLASS( Timer, Node );
+ GDCLASS(Timer, Node);
float wait_time;
bool one_shot;
@@ -42,12 +42,12 @@ class Timer : public Node {
bool active;
double time_left;
-protected:
+protected:
void _notification(int p_what);
static void _bind_methods();
-public:
+public:
enum TimerProcessMode {
TIMER_PROCESS_FIXED,
TIMER_PROCESS_IDLE,
@@ -76,7 +76,6 @@ public:
private:
TimerProcessMode timer_process_mode;
void _set_process(bool p_process, bool p_force = false);
-
};
VARIANT_ENUM_CAST(Timer::TimerProcessMode);
diff --git a/scene/main/viewport.cpp b/scene/main/viewport.cpp
index ef39dcde4b..23f8189167 100644
--- a/scene/main/viewport.cpp
+++ b/scene/main/viewport.cpp
@@ -27,24 +27,23 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "viewport.h"
+#include "os/input.h"
#include "os/os.h"
#include "scene/3d/spatial.h"
-#include "os/input.h"
#include "servers/physics_2d_server.h"
//#include "scene/3d/camera.h"
-
-#include "scene/gui/control.h"
#include "scene/3d/camera.h"
+#include "scene/3d/collision_object.h"
#include "scene/3d/listener.h"
-#include "scene/resources/mesh.h"
#include "scene/3d/spatial_indexer.h"
-#include "scene/3d/collision_object.h"
+#include "scene/gui/control.h"
+#include "scene/resources/mesh.h"
#include "scene/2d/collision_object_2d.h"
-#include "scene/gui/panel.h"
#include "scene/gui/label.h"
+#include "scene/gui/panel.h"
#include "scene/main/timer.h"
#include "scene/scene_string_names.h"
@@ -56,7 +55,7 @@ void ViewportTexture::setup_local_to_scene() {
vp->viewport_textures.erase(this);
}
- vp=NULL;
+ vp = NULL;
Node *local_scene = get_local_scene();
if (!local_scene) {
@@ -75,17 +74,16 @@ void ViewportTexture::setup_local_to_scene() {
vp->viewport_textures.insert(this);
}
-void ViewportTexture::set_viewport_path_in_scene(const NodePath& p_path) {
+void ViewportTexture::set_viewport_path_in_scene(const NodePath &p_path) {
- if (path==p_path)
+ if (path == p_path)
return;
- path=p_path;
+ path = p_path;
if (get_local_scene()) {
setup_local_to_scene();
}
-
}
NodePath ViewportTexture::get_viewport_path_in_scene() const {
@@ -95,41 +93,40 @@ NodePath ViewportTexture::get_viewport_path_in_scene() const {
int ViewportTexture::get_width() const {
- ERR_FAIL_COND_V(!vp,0);
+ ERR_FAIL_COND_V(!vp, 0);
return vp->size.width;
}
-int ViewportTexture::get_height() const{
+int ViewportTexture::get_height() const {
- ERR_FAIL_COND_V(!vp,0);
+ ERR_FAIL_COND_V(!vp, 0);
return vp->size.height;
}
-Size2 ViewportTexture::get_size() const{
+Size2 ViewportTexture::get_size() const {
- ERR_FAIL_COND_V(!vp,Size2());
+ ERR_FAIL_COND_V(!vp, Size2());
return vp->size;
}
-RID ViewportTexture::get_rid() const{
+RID ViewportTexture::get_rid() const {
- ERR_FAIL_COND_V(!vp,RID());
+ ERR_FAIL_COND_V(!vp, RID());
return vp->texture_rid;
}
-bool ViewportTexture::has_alpha() const{
+bool ViewportTexture::has_alpha() const {
return false;
}
-void ViewportTexture::set_flags(uint32_t p_flags){
+void ViewportTexture::set_flags(uint32_t p_flags) {
if (!vp)
return;
- vp->texture_flags=p_flags;
- VS::get_singleton()->texture_set_flags(vp->texture_rid,p_flags);
-
+ vp->texture_flags = p_flags;
+ VS::get_singleton()->texture_set_flags(vp->texture_rid, p_flags);
}
-uint32_t ViewportTexture::get_flags() const{
+uint32_t ViewportTexture::get_flags() const {
if (!vp)
return 0;
@@ -139,21 +136,19 @@ uint32_t ViewportTexture::get_flags() const{
void ViewportTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_viewport_path_in_scene","path"),&ViewportTexture::set_viewport_path_in_scene);
- ClassDB::bind_method(D_METHOD("get_viewport_path_in_scene"),&ViewportTexture::get_viewport_path_in_scene);
-
- ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH,"viewport_path"),"set_viewport_path_in_scene","get_viewport_path_in_scene");
+ ClassDB::bind_method(D_METHOD("set_viewport_path_in_scene", "path"), &ViewportTexture::set_viewport_path_in_scene);
+ ClassDB::bind_method(D_METHOD("get_viewport_path_in_scene"), &ViewportTexture::get_viewport_path_in_scene);
+ ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "viewport_path"), "set_viewport_path_in_scene", "get_viewport_path_in_scene");
}
-ViewportTexture::ViewportTexture(){
+ViewportTexture::ViewportTexture() {
- vp=NULL;
+ vp = NULL;
set_local_to_scene(true);
-
}
-ViewportTexture::~ViewportTexture(){
+ViewportTexture::~ViewportTexture() {
if (vp) {
vp->viewport_textures.erase(this);
@@ -164,37 +159,32 @@ ViewportTexture::~ViewportTexture(){
class TooltipPanel : public Panel {
- GDCLASS(TooltipPanel,Panel)
+ GDCLASS(TooltipPanel, Panel)
public:
- TooltipPanel() {};
-
+ TooltipPanel(){};
};
class TooltipLabel : public Label {
- GDCLASS(TooltipLabel,Label)
+ GDCLASS(TooltipLabel, Label)
public:
- TooltipLabel() {};
-
+ TooltipLabel(){};
};
-
Viewport::GUI::GUI() {
+ mouse_focus = NULL;
+ mouse_focus_button = -1;
+ key_focus = NULL;
+ mouse_over = NULL;
- mouse_focus=NULL;
- mouse_focus_button=-1;
- key_focus=NULL;
- mouse_over=NULL;
-
- cancelled_input_ID=0;
- tooltip=NULL;
- tooltip_popup=NULL;
- tooltip_label=NULL;
- subwindow_order_dirty=false;
+ cancelled_input_ID = 0;
+ tooltip = NULL;
+ tooltip_popup = NULL;
+ tooltip_label = NULL;
+ subwindow_order_dirty = false;
}
-
/////////////////////////////////////
void Viewport::_update_stretch_transform() {
@@ -202,20 +192,17 @@ void Viewport::_update_stretch_transform() {
//print_line("sive override size "+size_override_size);
//print_line("rect size "+size);
- stretch_transform=Transform2D();
- Size2 scale = size/(size_override_size+size_override_margin*2);
+ stretch_transform = Transform2D();
+ Size2 scale = size / (size_override_size + size_override_margin * 2);
stretch_transform.scale(scale);
- stretch_transform.elements[2]=size_override_margin*scale;
-
+ stretch_transform.elements[2] = size_override_margin * scale;
} else {
-
- stretch_transform=Transform2D();
+ stretch_transform = Transform2D();
}
_update_global_transform();
-
}
void Viewport::_update_rect() {
@@ -223,7 +210,6 @@ void Viewport::_update_rect() {
if (!is_inside_tree())
return;
-
/*if (!render_target && parent_control) {
Control *c = parent_control;
@@ -231,7 +217,7 @@ void Viewport::_update_rect() {
rect.pos=Point2();
rect.size=c->get_size();
}*/
-/*
+ /*
VisualServer::ViewportRect vr;
vr.x=rect.pos.x;
vr.y=rect.pos.y;
@@ -253,7 +239,6 @@ void Viewport::_update_rect() {
emit_signal("size_changed");
texture->emit_changed();
*/
-
}
void Viewport::_parent_resized() {
@@ -262,12 +247,11 @@ void Viewport::_parent_resized() {
}
void Viewport::_parent_draw() {
-
}
void Viewport::_parent_visibility_changed() {
-/*
+ /*
if (parent_control) {
Control *c = parent_control;
@@ -277,13 +261,11 @@ void Viewport::_parent_visibility_changed() {
_update_listener_2d();
}
*/
-
}
-
void Viewport::_vp_enter_tree() {
-/* if (parent_control) {
+ /* if (parent_control) {
Control *cparent=parent_control;
RID parent_ci = cparent->get_canvas_item();
@@ -301,7 +283,6 @@ void Viewport::_vp_enter_tree() {
}
*/
-
}
void Viewport::_vp_exit_tree() {
@@ -332,23 +313,21 @@ void Viewport::_vp_exit_tree() {
*/
}
-
void Viewport::update_worlds() {
if (!is_inside_tree())
return;
Rect2 xformed_rect = (global_canvas_transform * canvas_transform).affine_inverse().xform(get_visible_rect());
- find_world_2d()->_update_viewport(this,xformed_rect);
+ find_world_2d()->_update_viewport(this, xformed_rect);
find_world_2d()->_update();
find_world()->_update(get_tree()->get_frame());
}
-
void Viewport::_test_new_mouseover(ObjectID new_collider) {
#ifndef _3D_DISABLED
- if (new_collider!=physics_object_over) {
+ if (new_collider != physics_object_over) {
if (physics_object_over) {
Object *obj = ObjectDB::get_instance(physics_object_over);
@@ -366,72 +345,66 @@ void Viewport::_test_new_mouseover(ObjectID new_collider) {
CollisionObject *co = obj->cast_to<CollisionObject>();
if (co) {
co->_mouse_enter();
-
}
}
-
}
- physics_object_over=new_collider;
-
+ physics_object_over = new_collider;
}
#endif
-
}
void Viewport::_notification(int p_what) {
-
- switch( p_what ) {
+ switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
if (get_parent()) {
parent = get_parent()->get_viewport();
- VisualServer::get_singleton()->viewport_set_parent_viewport(viewport,parent->get_viewport_rid());
+ VisualServer::get_singleton()->viewport_set_parent_viewport(viewport, parent->get_viewport_rid());
} else {
- parent=NULL;
+ parent = NULL;
}
- current_canvas=find_world_2d()->get_canvas();
- VisualServer::get_singleton()->viewport_set_scenario(viewport,find_world()->get_scenario());
- VisualServer::get_singleton()->viewport_attach_canvas(viewport,current_canvas);
+ current_canvas = find_world_2d()->get_canvas();
+ VisualServer::get_singleton()->viewport_set_scenario(viewport, find_world()->get_scenario());
+ VisualServer::get_singleton()->viewport_attach_canvas(viewport, current_canvas);
_update_listener();
_update_listener_2d();
_update_rect();
- find_world_2d()->_register_viewport(this,Rect2());
+ find_world_2d()->_register_viewport(this, Rect2());
add_to_group("_viewports");
if (get_tree()->is_debugging_collisions_hint()) {
//2D
- Physics2DServer::get_singleton()->space_set_debug_contacts(find_world_2d()->get_space(),get_tree()->get_collision_debug_contact_count());
- contact_2d_debug=VisualServer::get_singleton()->canvas_item_create();
- VisualServer::get_singleton()->canvas_item_set_parent(contact_2d_debug,find_world_2d()->get_canvas());
+ Physics2DServer::get_singleton()->space_set_debug_contacts(find_world_2d()->get_space(), get_tree()->get_collision_debug_contact_count());
+ contact_2d_debug = VisualServer::get_singleton()->canvas_item_create();
+ VisualServer::get_singleton()->canvas_item_set_parent(contact_2d_debug, find_world_2d()->get_canvas());
//3D
- PhysicsServer::get_singleton()->space_set_debug_contacts(find_world()->get_space(),get_tree()->get_collision_debug_contact_count());
- contact_3d_debug_multimesh=VisualServer::get_singleton()->multimesh_create();
- VisualServer::get_singleton()->multimesh_allocate(contact_3d_debug_multimesh,get_tree()->get_collision_debug_contact_count(),VS::MULTIMESH_TRANSFORM_3D,VS::MULTIMESH_COLOR_8BIT);
- VisualServer::get_singleton()->multimesh_set_visible_instances(contact_3d_debug_multimesh,0);
- VisualServer::get_singleton()->multimesh_set_mesh(contact_3d_debug_multimesh,get_tree()->get_debug_contact_mesh()->get_rid());
- contact_3d_debug_instance=VisualServer::get_singleton()->instance_create();
- VisualServer::get_singleton()->instance_set_base(contact_3d_debug_instance,contact_3d_debug_multimesh);
- VisualServer::get_singleton()->instance_set_scenario(contact_3d_debug_instance,find_world()->get_scenario());
- VisualServer::get_singleton()->instance_geometry_set_flag(contact_3d_debug_instance,VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS,true);
-
+ PhysicsServer::get_singleton()->space_set_debug_contacts(find_world()->get_space(), get_tree()->get_collision_debug_contact_count());
+ contact_3d_debug_multimesh = VisualServer::get_singleton()->multimesh_create();
+ VisualServer::get_singleton()->multimesh_allocate(contact_3d_debug_multimesh, get_tree()->get_collision_debug_contact_count(), VS::MULTIMESH_TRANSFORM_3D, VS::MULTIMESH_COLOR_8BIT);
+ VisualServer::get_singleton()->multimesh_set_visible_instances(contact_3d_debug_multimesh, 0);
+ VisualServer::get_singleton()->multimesh_set_mesh(contact_3d_debug_multimesh, get_tree()->get_debug_contact_mesh()->get_rid());
+ contact_3d_debug_instance = VisualServer::get_singleton()->instance_create();
+ VisualServer::get_singleton()->instance_set_base(contact_3d_debug_instance, contact_3d_debug_multimesh);
+ VisualServer::get_singleton()->instance_set_scenario(contact_3d_debug_instance, find_world()->get_scenario());
+ VisualServer::get_singleton()->instance_geometry_set_flag(contact_3d_debug_instance, VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS, true);
}
- VS::get_singleton()->viewport_set_active(viewport,true);
+ VS::get_singleton()->viewport_set_active(viewport, true);
} break;
case NOTIFICATION_READY: {
#ifndef _3D_DISABLED
if (listeners.size() && !listener) {
- Listener *first=NULL;
- for(Set<Listener*>::Element *E=listeners.front();E;E=E->next()) {
+ Listener *first = NULL;
+ for (Set<Listener *>::Element *E = listeners.front(); E; E = E->next()) {
- if (first==NULL || first->is_greater_than(E->get())) {
- first=E->get();
+ if (first == NULL || first->is_greater_than(E->get())) {
+ first = E->get();
}
}
@@ -441,11 +414,11 @@ void Viewport::_notification(int p_what) {
if (cameras.size() && !camera) {
//there are cameras but no current camera, pick first in tree and make it current
- Camera *first=NULL;
- for(Set<Camera*>::Element *E=cameras.front();E;E=E->next()) {
+ Camera *first = NULL;
+ for (Set<Camera *>::Element *E = cameras.front(); E; E = E->next()) {
- if (first==NULL || first->is_greater_than(E->get())) {
- first=E->get();
+ if (first == NULL || first->is_greater_than(E->get())) {
+ first = E->get();
}
}
@@ -456,7 +429,6 @@ void Viewport::_notification(int p_what) {
} break;
case NOTIFICATION_EXIT_TREE: {
-
_gui_cancel_tooltip();
if (world_2d.is_valid())
world_2d->_remove_viewport(this);
@@ -466,33 +438,31 @@ void Viewport::_notification(int p_what) {
_vp_exit_tree();
*/
- VisualServer::get_singleton()->viewport_set_scenario(viewport,RID());
-// SpatialSoundServer::get_singleton()->listener_set_space(internal_listener, RID());
- VisualServer::get_singleton()->viewport_remove_canvas(viewport,current_canvas);
+ VisualServer::get_singleton()->viewport_set_scenario(viewport, RID());
+ // SpatialSoundServer::get_singleton()->listener_set_space(internal_listener, RID());
+ VisualServer::get_singleton()->viewport_remove_canvas(viewport, current_canvas);
if (contact_2d_debug.is_valid()) {
VisualServer::get_singleton()->free(contact_2d_debug);
- contact_2d_debug=RID();
+ contact_2d_debug = RID();
}
if (contact_3d_debug_multimesh.is_valid()) {
VisualServer::get_singleton()->free(contact_3d_debug_multimesh);
VisualServer::get_singleton()->free(contact_3d_debug_instance);
- contact_3d_debug_instance=RID();
- contact_3d_debug_multimesh=RID();
+ contact_3d_debug_instance = RID();
+ contact_3d_debug_multimesh = RID();
}
remove_from_group("_viewports");
-
- VS::get_singleton()->viewport_set_active(viewport,false);
-
+ VS::get_singleton()->viewport_set_active(viewport, false);
} break;
case NOTIFICATION_FIXED_PROCESS: {
- if (gui.tooltip_timer>=0) {
- gui.tooltip_timer-=get_fixed_process_delta_time();
- if (gui.tooltip_timer<0) {
+ if (gui.tooltip_timer >= 0) {
+ gui.tooltip_timer -= get_fixed_process_delta_time();
+ if (gui.tooltip_timer < 0) {
_gui_show_tooltip();
}
}
@@ -500,107 +470,99 @@ void Viewport::_notification(int p_what) {
if (get_tree()->is_debugging_collisions_hint() && contact_2d_debug.is_valid()) {
VisualServer::get_singleton()->canvas_item_clear(contact_2d_debug);
- VisualServer::get_singleton()->canvas_item_set_draw_index(contact_2d_debug,0xFFFFF); //very high index
+ VisualServer::get_singleton()->canvas_item_set_draw_index(contact_2d_debug, 0xFFFFF); //very high index
Vector<Vector2> points = Physics2DServer::get_singleton()->space_get_contacts(find_world_2d()->get_space());
int point_count = Physics2DServer::get_singleton()->space_get_contact_count(find_world_2d()->get_space());
Color ccol = get_tree()->get_debug_collision_contact_color();
+ for (int i = 0; i < point_count; i++) {
- for(int i=0;i<point_count;i++) {
-
- VisualServer::get_singleton()->canvas_item_add_rect(contact_2d_debug,Rect2(points[i]-Vector2(2,2),Vector2(5,5)),ccol);
+ VisualServer::get_singleton()->canvas_item_add_rect(contact_2d_debug, Rect2(points[i] - Vector2(2, 2), Vector2(5, 5)), ccol);
}
}
if (get_tree()->is_debugging_collisions_hint() && contact_3d_debug_multimesh.is_valid()) {
-
Vector<Vector3> points = PhysicsServer::get_singleton()->space_get_contacts(find_world()->get_space());
int point_count = PhysicsServer::get_singleton()->space_get_contact_count(find_world()->get_space());
-
- VS::get_singleton()->multimesh_set_visible_instances(contact_3d_debug_multimesh,point_count);
-
+ VS::get_singleton()->multimesh_set_visible_instances(contact_3d_debug_multimesh, point_count);
}
+ if (physics_object_picking && (to_screen_rect == Rect2() || Input::get_singleton()->get_mouse_mode() != Input::MOUSE_MODE_CAPTURED)) {
-
- if (physics_object_picking && (to_screen_rect==Rect2() || Input::get_singleton()->get_mouse_mode()!=Input::MOUSE_MODE_CAPTURED)) {
-
- Vector2 last_pos(1e20,1e20);
+ Vector2 last_pos(1e20, 1e20);
CollisionObject *last_object;
- ObjectID last_id=0;
+ ObjectID last_id = 0;
PhysicsDirectSpaceState::RayResult result;
- Physics2DDirectSpaceState *ss2d=Physics2DServer::get_singleton()->space_get_direct_state(find_world_2d()->get_space());
+ Physics2DDirectSpaceState *ss2d = Physics2DServer::get_singleton()->space_get_direct_state(find_world_2d()->get_space());
- bool motion_tested=false;
+ bool motion_tested = false;
- while(physics_picking_events.size()) {
+ while (physics_picking_events.size()) {
InputEvent ev = physics_picking_events.front()->get();
physics_picking_events.pop_front();
Vector2 pos;
- switch(ev.type) {
+ switch (ev.type) {
case InputEvent::MOUSE_MOTION: {
- pos.x=ev.mouse_motion.x;
- pos.y=ev.mouse_motion.y;
- motion_tested=true;
- physics_last_mousepos=pos;
+ pos.x = ev.mouse_motion.x;
+ pos.y = ev.mouse_motion.y;
+ motion_tested = true;
+ physics_last_mousepos = pos;
} break;
case InputEvent::MOUSE_BUTTON: {
- pos.x=ev.mouse_button.x;
- pos.y=ev.mouse_button.y;
+ pos.x = ev.mouse_button.x;
+ pos.y = ev.mouse_button.y;
} break;
case InputEvent::SCREEN_DRAG: {
- pos.x=ev.screen_drag.x;
- pos.y=ev.screen_drag.y;
+ pos.x = ev.screen_drag.x;
+ pos.y = ev.screen_drag.y;
} break;
case InputEvent::SCREEN_TOUCH: {
- pos.x=ev.screen_touch.x;
- pos.y=ev.screen_touch.y;
+ pos.x = ev.screen_touch.x;
+ pos.y = ev.screen_touch.y;
} break;
-
}
if (ss2d) {
//send to 2D
-
uint64_t frame = get_tree()->get_frame();
Vector2 point = get_canvas_transform().affine_inverse().xform(pos);
Physics2DDirectSpaceState::ShapeResult res[64];
- int rc = ss2d->intersect_point(point,res,64,Set<RID>(),0xFFFFFFFF,0xFFFFFFFF,true);
- for(int i=0;i<rc;i++) {
+ int rc = ss2d->intersect_point(point, res, 64, Set<RID>(), 0xFFFFFFFF, 0xFFFFFFFF, true);
+ for (int i = 0; i < rc; i++) {
if (res[i].collider_id && res[i].collider) {
- CollisionObject2D *co=res[i].collider->cast_to<CollisionObject2D>();
+ CollisionObject2D *co = res[i].collider->cast_to<CollisionObject2D>();
if (co) {
- Map<ObjectID,uint64_t>::Element *E=physics_2d_mouseover.find(res[i].collider_id);
+ Map<ObjectID, uint64_t>::Element *E = physics_2d_mouseover.find(res[i].collider_id);
if (!E) {
- E=physics_2d_mouseover.insert(res[i].collider_id,frame);
+ E = physics_2d_mouseover.insert(res[i].collider_id, frame);
co->_mouse_enter();
} else {
- E->get()=frame;
+ E->get() = frame;
}
- co->_input_event(this,ev,res[i].shape);
+ co->_input_event(this, ev, res[i].shape);
}
}
}
- List<Map<ObjectID,uint64_t>::Element*> to_erase;
+ List<Map<ObjectID, uint64_t>::Element *> to_erase;
- for (Map<ObjectID,uint64_t>::Element*E=physics_2d_mouseover.front();E;E=E->next()) {
- if (E->get()!=frame) {
- Object *o=ObjectDB::get_instance(E->key());
+ for (Map<ObjectID, uint64_t>::Element *E = physics_2d_mouseover.front(); E; E = E->next()) {
+ if (E->get() != frame) {
+ Object *o = ObjectDB::get_instance(E->key());
if (o) {
- CollisionObject2D *co=o->cast_to<CollisionObject2D>();
+ CollisionObject2D *co = o->cast_to<CollisionObject2D>();
if (co) {
co->_mouse_exit();
}
@@ -609,60 +571,50 @@ void Viewport::_notification(int p_what) {
}
}
- while(to_erase.size()) {
+ while (to_erase.size()) {
physics_2d_mouseover.erase(to_erase.front()->get());
to_erase.pop_front();
}
-
}
-
-
#ifndef _3D_DISABLED
- bool captured=false;
-
- if (physics_object_capture!=0) {
+ bool captured = false;
+ if (physics_object_capture != 0) {
Object *obj = ObjectDB::get_instance(physics_object_capture);
if (obj) {
CollisionObject *co = obj->cast_to<CollisionObject>();
if (co) {
- co->_input_event(camera,ev,Vector3(),Vector3(),0);
- captured=true;
- if (ev.type==InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index==1 && !ev.mouse_button.pressed) {
- physics_object_capture=0;
+ co->_input_event(camera, ev, Vector3(), Vector3(), 0);
+ captured = true;
+ if (ev.type == InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index == 1 && !ev.mouse_button.pressed) {
+ physics_object_capture = 0;
}
} else {
- physics_object_capture=0;
+ physics_object_capture = 0;
}
} else {
- physics_object_capture=0;
+ physics_object_capture = 0;
}
}
-
if (captured) {
//none
- } else if (pos==last_pos) {
+ } else if (pos == last_pos) {
if (last_id) {
if (ObjectDB::get_instance(last_id)) {
//good, exists
- last_object->_input_event(camera,ev,result.position,result.normal,result.shape);
- if (last_object->get_capture_input_on_drag() && ev.type==InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index==1 && ev.mouse_button.pressed) {
- physics_object_capture=last_id;
+ last_object->_input_event(camera, ev, result.position, result.normal, result.shape);
+ if (last_object->get_capture_input_on_drag() && ev.type == InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index == 1 && ev.mouse_button.pressed) {
+ physics_object_capture = last_id;
}
-
-
}
}
} else {
-
-
-
if (camera) {
Vector3 from = camera->project_ray_origin(pos);
@@ -671,8 +623,8 @@ void Viewport::_notification(int p_what) {
PhysicsDirectSpaceState *space = PhysicsServer::get_singleton()->space_get_direct_state(find_world()->get_space());
if (space) {
- bool col = space->intersect_ray(from,from+dir*10000,result,Set<RID>(),0xFFFFFFFF,0xFFFFFFFF,true);
- ObjectID new_collider=0;
+ bool col = space->intersect_ray(from, from + dir * 10000, result, Set<RID>(), 0xFFFFFFFF, 0xFFFFFFFF, true);
+ ObjectID new_collider = 0;
if (col) {
if (result.collider) {
@@ -680,29 +632,28 @@ void Viewport::_notification(int p_what) {
CollisionObject *co = result.collider->cast_to<CollisionObject>();
if (co) {
- co->_input_event(camera,ev,result.position,result.normal,result.shape);
- last_object=co;
- last_id=result.collider_id;
- new_collider=last_id;
- if (co->get_capture_input_on_drag() && ev.type==InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index==1 && ev.mouse_button.pressed) {
- physics_object_capture=last_id;
+ co->_input_event(camera, ev, result.position, result.normal, result.shape);
+ last_object = co;
+ last_id = result.collider_id;
+ new_collider = last_id;
+ if (co->get_capture_input_on_drag() && ev.type == InputEvent::MOUSE_BUTTON && ev.mouse_button.button_index == 1 && ev.mouse_button.pressed) {
+ physics_object_capture = last_id;
}
-
}
}
}
- if (ev.type==InputEvent::MOUSE_MOTION) {
+ if (ev.type == InputEvent::MOUSE_MOTION) {
_test_new_mouseover(new_collider);
}
}
- last_pos=pos;
+ last_pos = pos;
}
}
}
- if (!motion_tested && camera && physics_last_mousepos!=Vector2(1e20,1e20)) {
+ if (!motion_tested && camera && physics_last_mousepos != Vector2(1e20, 1e20)) {
//test anyway for mouseenter/exit because objects might move
Vector3 from = camera->project_ray_origin(physics_last_mousepos);
@@ -711,24 +662,21 @@ void Viewport::_notification(int p_what) {
PhysicsDirectSpaceState *space = PhysicsServer::get_singleton()->space_get_direct_state(find_world()->get_space());
if (space) {
- bool col = space->intersect_ray(from,from+dir*10000,result,Set<RID>(),0xFFFFFFFF,0xFFFFFFFF,true);
- ObjectID new_collider=0;
+ bool col = space->intersect_ray(from, from + dir * 10000, result, Set<RID>(), 0xFFFFFFFF, 0xFFFFFFFF, true);
+ ObjectID new_collider = 0;
if (col) {
if (result.collider) {
CollisionObject *co = result.collider->cast_to<CollisionObject>();
if (co) {
- new_collider=result.collider_id;
-
+ new_collider = result.collider_id;
}
}
}
_test_new_mouseover(new_collider);
-
}
#endif
}
-
}
} break;
@@ -742,36 +690,33 @@ RID Viewport::get_viewport_rid() const {
void Viewport::set_size(const Size2 &p_size) {
- if (size==p_size.floor())
+ if (size == p_size.floor())
return;
- size=p_size.floor();
- VS::get_singleton()->viewport_set_size(viewport,size.width,size.height);
+ size = p_size.floor();
+ VS::get_singleton()->viewport_set_size(viewport, size.width, size.height);
_update_rect();
_update_stretch_transform();
emit_signal("size_changed");
-
}
Rect2 Viewport::get_visible_rect() const {
-
Rect2 r;
- if (size==Size2()) {
+ if (size == Size2()) {
- r=Rect2( Point2(), Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height ) );
+ r = Rect2(Point2(), Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height));
} else {
- r=Rect2( Point2() , size );
+ r = Rect2(Point2(), size);
}
if (size_override) {
- r.size=size_override_size;
+ r.size = size_override_size;
}
-
return r;
}
@@ -780,16 +725,14 @@ Size2 Viewport::get_size() const {
return size;
}
-
void Viewport::_update_listener() {
-/*
+ /*
if (is_inside_tree() && audio_listener && (camera || listener) && (!get_parent() || (get_parent()->cast_to<Control>() && get_parent()->cast_to<Control>()->is_visible_in_tree()))) {
SpatialSoundServer::get_singleton()->listener_set_space(internal_listener, find_world()->get_sound_space());
} else {
SpatialSoundServer::get_singleton()->listener_set_space(internal_listener, RID());
}
*/
-
}
void Viewport::_update_listener_2d() {
@@ -802,43 +745,39 @@ void Viewport::_update_listener_2d() {
*/
}
-
void Viewport::set_as_audio_listener(bool p_enable) {
- if (p_enable==audio_listener)
+ if (p_enable == audio_listener)
return;
- audio_listener=p_enable;
+ audio_listener = p_enable;
_update_listener();
-
}
bool Viewport::is_audio_listener() const {
- return audio_listener;
+ return audio_listener;
}
void Viewport::set_as_audio_listener_2d(bool p_enable) {
- if (p_enable==audio_listener_2d)
+ if (p_enable == audio_listener_2d)
return;
- audio_listener_2d=p_enable;
+ audio_listener_2d = p_enable;
_update_listener_2d();
-
-
}
bool Viewport::is_audio_listener_2d() const {
- return audio_listener_2d;
+ return audio_listener_2d;
}
-void Viewport::set_canvas_transform(const Transform2D& p_transform) {
+void Viewport::set_canvas_transform(const Transform2D &p_transform) {
- canvas_transform=p_transform;
- VisualServer::get_singleton()->viewport_set_canvas_transform(viewport,find_world_2d()->get_canvas(),canvas_transform);
+ canvas_transform = p_transform;
+ VisualServer::get_singleton()->viewport_set_canvas_transform(viewport, find_world_2d()->get_canvas(), canvas_transform);
Transform2D xform = (global_canvas_transform * canvas_transform).affine_inverse();
Size2 ss = get_visible_rect().size;
@@ -848,22 +787,18 @@ void Viewport::set_canvas_transform(const Transform2D& p_transform) {
SpatialSound2DServer::get_singleton()->listener_set_param(internal_listener_2d, SpatialSound2DServer::LISTENER_PARAM_PAN_RANGE, panrange);
*/
-
}
-Transform2D Viewport::get_canvas_transform() const{
+Transform2D Viewport::get_canvas_transform() const {
return canvas_transform;
}
-
-
void Viewport::_update_global_transform() {
-
Transform2D sxform = stretch_transform * global_canvas_transform;
- VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport,sxform);
+ VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport, sxform);
Transform2D xform = (sxform * canvas_transform).affine_inverse();
Size2 ss = get_visible_rect().size;
@@ -875,17 +810,14 @@ void Viewport::_update_global_transform() {
*/
}
+void Viewport::set_global_canvas_transform(const Transform2D &p_transform) {
-void Viewport::set_global_canvas_transform(const Transform2D& p_transform) {
-
- global_canvas_transform=p_transform;
+ global_canvas_transform = p_transform;
_update_global_transform();
-
-
}
-Transform2D Viewport::get_global_canvas_transform() const{
+Transform2D Viewport::get_global_canvas_transform() const {
return global_canvas_transform;
}
@@ -893,12 +825,12 @@ Transform2D Viewport::get_global_canvas_transform() const{
void Viewport::_listener_transform_changed_notify() {
#ifndef _3D_DISABLED
- //if (listener)
+//if (listener)
// SpatialSoundServer::get_singleton()->listener_set_transform(internal_listener, listener->get_listener_transform());
#endif
}
-void Viewport::_listener_set(Listener* p_listener) {
+void Viewport::_listener_set(Listener *p_listener) {
#ifndef _3D_DISABLED
@@ -912,13 +844,13 @@ void Viewport::_listener_set(Listener* p_listener) {
#endif
}
-bool Viewport::_listener_add(Listener* p_listener) {
+bool Viewport::_listener_add(Listener *p_listener) {
listeners.insert(p_listener);
return listeners.size() == 1;
}
-void Viewport::_listener_remove(Listener* p_listener) {
+void Viewport::_listener_remove(Listener *p_listener) {
listeners.erase(p_listener);
if (listener == p_listener) {
@@ -927,10 +859,10 @@ void Viewport::_listener_remove(Listener* p_listener) {
}
#ifndef _3D_DISABLED
-void Viewport::_listener_make_next_current(Listener* p_exclude) {
+void Viewport::_listener_make_next_current(Listener *p_exclude) {
if (listeners.size() > 0) {
- for (Set<Listener*>::Element *E = listeners.front(); E; E = E->next()) {
+ for (Set<Listener *>::Element *E = listeners.front(); E; E = E->next()) {
if (p_exclude == E->get())
continue;
@@ -940,10 +872,8 @@ void Viewport::_listener_make_next_current(Listener* p_exclude) {
return;
E->get()->make_current();
-
}
- }
- else {
+ } else {
// Attempt to reset listener to the camera position
if (camera != NULL) {
_update_listener();
@@ -956,27 +886,27 @@ void Viewport::_listener_make_next_current(Listener* p_exclude) {
void Viewport::_camera_transform_changed_notify() {
#ifndef _3D_DISABLED
- // If there is an active listener in the scene, it takes priority over the camera
+// If there is an active listener in the scene, it takes priority over the camera
// if (camera && !listener)
// SpatialSoundServer::get_singleton()->listener_set_transform(internal_listener, camera->get_camera_transform());
#endif
}
-void Viewport::_camera_set(Camera* p_camera) {
+void Viewport::_camera_set(Camera *p_camera) {
#ifndef _3D_DISABLED
- if (camera==p_camera)
+ if (camera == p_camera)
return;
if (camera && find_world().is_valid()) {
camera->notification(Camera::NOTIFICATION_LOST_CURRENT);
}
- camera=p_camera;
+ camera = p_camera;
if (camera)
- VisualServer::get_singleton()->viewport_attach_camera(viewport,camera->get_camera());
+ VisualServer::get_singleton()->viewport_attach_camera(viewport, camera->get_camera());
else
- VisualServer::get_singleton()->viewport_attach_camera(viewport,RID());
+ VisualServer::get_singleton()->viewport_attach_camera(viewport, RID());
if (camera && find_world().is_valid()) {
camera->notification(Camera::NOTIFICATION_BECAME_CURRENT);
@@ -987,43 +917,41 @@ void Viewport::_camera_set(Camera* p_camera) {
#endif
}
-bool Viewport::_camera_add(Camera* p_camera) {
+bool Viewport::_camera_add(Camera *p_camera) {
cameras.insert(p_camera);
- return cameras.size()==1;
+ return cameras.size() == 1;
}
-void Viewport::_camera_remove(Camera* p_camera) {
+void Viewport::_camera_remove(Camera *p_camera) {
cameras.erase(p_camera);
- if (camera==p_camera) {
- camera=NULL;
+ if (camera == p_camera) {
+ camera = NULL;
}
}
#ifndef _3D_DISABLED
-void Viewport::_camera_make_next_current(Camera* p_exclude) {
+void Viewport::_camera_make_next_current(Camera *p_exclude) {
- for(Set<Camera*>::Element *E=cameras.front();E;E=E->next()) {
+ for (Set<Camera *>::Element *E = cameras.front(); E; E = E->next()) {
- if (p_exclude==E->get())
+ if (p_exclude == E->get())
continue;
if (!E->get()->is_inside_tree())
continue;
- if (camera!=NULL)
+ if (camera != NULL)
return;
E->get()->make_current();
-
}
}
#endif
void Viewport::set_transparent_background(bool p_enable) {
- transparent_bg=p_enable;
- VS::get_singleton()->viewport_set_transparent_background(viewport,p_enable);
-
+ transparent_bg = p_enable;
+ VS::get_singleton()->viewport_set_transparent_background(viewport, p_enable);
}
bool Viewport::has_transparent_background() const {
@@ -1031,37 +959,37 @@ bool Viewport::has_transparent_background() const {
return transparent_bg;
}
-void Viewport::set_world_2d(const Ref<World2D>& p_world_2d) {
- if (world_2d==p_world_2d)
+void Viewport::set_world_2d(const Ref<World2D> &p_world_2d) {
+ if (world_2d == p_world_2d)
return;
- if (parent && parent->find_world_2d()==p_world_2d) {
+ if (parent && parent->find_world_2d() == p_world_2d) {
WARN_PRINT("Unable to use parent world as world_2d");
return;
}
if (is_inside_tree()) {
find_world_2d()->_remove_viewport(this);
- VisualServer::get_singleton()->viewport_remove_canvas(viewport,current_canvas);
+ VisualServer::get_singleton()->viewport_remove_canvas(viewport, current_canvas);
}
if (p_world_2d.is_valid())
- world_2d=p_world_2d;
+ world_2d = p_world_2d;
else {
WARN_PRINT("Invalid world");
- world_2d=Ref<World2D>( memnew( World2D ));
+ world_2d = Ref<World2D>(memnew(World2D));
}
_update_listener_2d();
if (is_inside_tree()) {
- current_canvas=find_world_2d()->get_canvas();
- VisualServer::get_singleton()->viewport_attach_canvas(viewport,current_canvas);
- find_world_2d()->_register_viewport(this,Rect2());
+ current_canvas = find_world_2d()->get_canvas();
+ VisualServer::get_singleton()->viewport_attach_canvas(viewport, current_canvas);
+ find_world_2d()->_register_viewport(this, Rect2());
}
}
-Ref<World2D> Viewport::find_world_2d() const{
+Ref<World2D> Viewport::find_world_2d() const {
if (world_2d.is_valid())
return world_2d;
@@ -1073,8 +1001,7 @@ Ref<World2D> Viewport::find_world_2d() const{
void Viewport::_propagate_enter_world(Node *p_node) {
-
- if (p_node!=this) {
+ if (p_node != this) {
if (!p_node->is_inside_tree()) //may not have entered scene yet
return;
@@ -1093,27 +1020,26 @@ void Viewport::_propagate_enter_world(Node *p_node) {
}
}
-
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
_propagate_enter_world(p_node->get_child(i));
}
}
-void Viewport::_propagate_viewport_notification(Node* p_node,int p_what) {
+void Viewport::_propagate_viewport_notification(Node *p_node, int p_what) {
p_node->notification(p_what);
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
Node *c = p_node->get_child(i);
if (c->cast_to<Viewport>())
continue;
- _propagate_viewport_notification(c,p_what);
+ _propagate_viewport_notification(c, p_what);
}
}
void Viewport::_propagate_exit_world(Node *p_node) {
- if (p_node!=this) {
+ if (p_node != this) {
if (!p_node->is_inside_tree()) //may have exited scene already
return;
@@ -1132,18 +1058,15 @@ void Viewport::_propagate_exit_world(Node *p_node) {
}
}
-
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
_propagate_exit_world(p_node->get_child(i));
}
-
}
+void Viewport::set_world(const Ref<World> &p_world) {
-void Viewport::set_world(const Ref<World>& p_world) {
-
- if (world==p_world)
+ if (world == p_world)
return;
if (is_inside_tree())
@@ -1154,7 +1077,7 @@ void Viewport::set_world(const Ref<World>& p_world) {
camera->notification(Camera::NOTIFICATION_LOST_CURRENT);
#endif
- world=p_world;
+ world = p_world;
if (is_inside_tree())
_propagate_enter_world(this);
@@ -1167,24 +1090,23 @@ void Viewport::set_world(const Ref<World>& p_world) {
//propagate exit
if (is_inside_tree()) {
- VisualServer::get_singleton()->viewport_set_scenario(viewport,find_world()->get_scenario());
+ VisualServer::get_singleton()->viewport_set_scenario(viewport, find_world()->get_scenario());
}
_update_listener();
-
}
-Ref<World> Viewport::get_world() const{
+Ref<World> Viewport::get_world() const {
return world;
}
-Ref<World2D> Viewport::get_world_2d() const{
+Ref<World2D> Viewport::get_world_2d() const {
return world_2d;
}
-Ref<World> Viewport::find_world() const{
+Ref<World> Viewport::find_world() const {
if (own_world.is_valid())
return own_world;
@@ -1196,36 +1118,33 @@ Ref<World> Viewport::find_world() const{
return Ref<World>();
}
-Listener* Viewport::get_listener() const {
+Listener *Viewport::get_listener() const {
return listener;
}
-Camera* Viewport::get_camera() const {
+Camera *Viewport::get_camera() const {
return camera;
}
-
Transform2D Viewport::get_final_transform() const {
return stretch_transform * global_canvas_transform;
}
-void Viewport::set_size_override(bool p_enable, const Size2& p_size, const Vector2 &p_margin) {
+void Viewport::set_size_override(bool p_enable, const Size2 &p_size, const Vector2 &p_margin) {
- if (size_override==p_enable && p_size==size_override_size)
+ if (size_override == p_enable && p_size == size_override_size)
return;
- size_override=p_enable;
- if (p_size.x>=0 || p_size.y>=0) {
- size_override_size=p_size;
+ size_override = p_enable;
+ if (p_size.x >= 0 || p_size.y >= 0) {
+ size_override_size = p_size;
}
- size_override_margin=p_margin;
+ size_override_margin = p_margin;
_update_rect();
_update_stretch_transform();
-
-
}
Size2 Viewport::get_size_override() const {
@@ -1238,19 +1157,17 @@ bool Viewport::is_size_override_enabled() const {
}
void Viewport::set_size_override_stretch(bool p_enable) {
- if (p_enable==size_override_stretch)
+ if (p_enable == size_override_stretch)
return;
- size_override_stretch=p_enable;
+ size_override_stretch = p_enable;
if (size_override) {
_update_rect();
}
-
_update_stretch_transform();
}
-
bool Viewport::is_size_override_stretch_enabled() const {
return size_override_stretch;
@@ -1293,19 +1210,18 @@ bool Viewport::is_set_as_render_target() const{
}
#endif
-void Viewport::set_update_mode(UpdateMode p_mode){
-
- update_mode=p_mode;
- VS::get_singleton()->viewport_set_update_mode(viewport,VS::ViewportUpdateMode(p_mode));
+void Viewport::set_update_mode(UpdateMode p_mode) {
+ update_mode = p_mode;
+ VS::get_singleton()->viewport_set_update_mode(viewport, VS::ViewportUpdateMode(p_mode));
}
-Viewport::UpdateMode Viewport::get_update_mode() const{
+Viewport::UpdateMode Viewport::get_update_mode() const {
return update_mode;
}
//RID get_texture() const;
-void Viewport::queue_screen_capture(){
+void Viewport::queue_screen_capture() {
//VS::get_singleton()->viewport_queue_screen_capture(viewport);
}
@@ -1322,78 +1238,73 @@ Ref<ViewportTexture> Viewport::get_texture() const {
void Viewport::set_vflip(bool p_enable) {
- vflip=p_enable;
- VisualServer::get_singleton()->viewport_set_vflip(viewport,p_enable);
+ vflip = p_enable;
+ VisualServer::get_singleton()->viewport_set_vflip(viewport, p_enable);
}
-bool Viewport::get_vflip() const{
+bool Viewport::get_vflip() const {
return vflip;
}
void Viewport::set_clear_on_new_frame(bool p_enable) {
- clear_on_new_frame=p_enable;
+ clear_on_new_frame = p_enable;
//VisualServer::get_singleton()->viewport_set_clear_on_new_frame(viewport,p_enable);
}
-bool Viewport::get_clear_on_new_frame() const{
+bool Viewport::get_clear_on_new_frame() const {
return clear_on_new_frame;
}
void Viewport::set_shadow_atlas_size(int p_size) {
- if (shadow_atlas_size==p_size)
+ if (shadow_atlas_size == p_size)
return;
- shadow_atlas_size=p_size;
- VS::get_singleton()->viewport_set_shadow_atlas_size(viewport,p_size);
+ shadow_atlas_size = p_size;
+ VS::get_singleton()->viewport_set_shadow_atlas_size(viewport, p_size);
}
-int Viewport::get_shadow_atlas_size() const{
+int Viewport::get_shadow_atlas_size() const {
return shadow_atlas_size;
}
-void Viewport::set_shadow_atlas_quadrant_subdiv(int p_quadrant,ShadowAtlasQuadrantSubdiv p_subdiv){
+void Viewport::set_shadow_atlas_quadrant_subdiv(int p_quadrant, ShadowAtlasQuadrantSubdiv p_subdiv) {
+ ERR_FAIL_INDEX(p_quadrant, 4);
+ ERR_FAIL_INDEX(p_subdiv, SHADOW_ATLAS_QUADRANT_SUBDIV_MAX);
- ERR_FAIL_INDEX(p_quadrant,4);
- ERR_FAIL_INDEX(p_subdiv,SHADOW_ATLAS_QUADRANT_SUBDIV_MAX);
-
- if (shadow_atlas_quadrant_subdiv[p_quadrant]==p_subdiv)
+ if (shadow_atlas_quadrant_subdiv[p_quadrant] == p_subdiv)
return;
- shadow_atlas_quadrant_subdiv[p_quadrant]=p_subdiv;
- static const int subdiv[SHADOW_ATLAS_QUADRANT_SUBDIV_MAX]={0,1,4,16,64,256,1024};
-
- VS::get_singleton()->viewport_set_shadow_atlas_quadrant_subdivision(viewport,p_quadrant,subdiv[p_subdiv]);
+ shadow_atlas_quadrant_subdiv[p_quadrant] = p_subdiv;
+ static const int subdiv[SHADOW_ATLAS_QUADRANT_SUBDIV_MAX] = { 0, 1, 4, 16, 64, 256, 1024 };
+ VS::get_singleton()->viewport_set_shadow_atlas_quadrant_subdivision(viewport, p_quadrant, subdiv[p_subdiv]);
}
-Viewport::ShadowAtlasQuadrantSubdiv Viewport::get_shadow_atlas_quadrant_subdiv(int p_quadrant) const{
+Viewport::ShadowAtlasQuadrantSubdiv Viewport::get_shadow_atlas_quadrant_subdiv(int p_quadrant) const {
- ERR_FAIL_INDEX_V(p_quadrant,4,SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
+ ERR_FAIL_INDEX_V(p_quadrant, 4, SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
return shadow_atlas_quadrant_subdiv[p_quadrant];
}
-
void Viewport::clear() {
//clear=true;
//VisualServer::get_singleton()->viewport_clear(viewport);
}
-
Transform2D Viewport::_get_input_pre_xform() const {
Transform2D pre_xf;
+ if (to_screen_rect != Rect2()) {
- if (to_screen_rect!=Rect2()) {
-
- pre_xf.elements[2]=-to_screen_rect.pos;
- pre_xf.scale(size/to_screen_rect.size);
+ pre_xf.elements[2] = -to_screen_rect.pos;
+ pre_xf.scale(size / to_screen_rect.size);
}
return pre_xf;
@@ -1410,24 +1321,22 @@ Vector2 Viewport::_get_window_offset() const {
return Vector2();
}
-void Viewport::_make_input_local(InputEvent& ev) {
+void Viewport::_make_input_local(InputEvent &ev) {
-
- switch(ev.type) {
+ switch (ev.type) {
case InputEvent::MOUSE_BUTTON: {
Vector2 vp_ofs = _get_window_offset();
Transform2D ai = get_final_transform().affine_inverse() * _get_input_pre_xform();
- Vector2 g = ai.xform(Vector2(ev.mouse_button.global_x,ev.mouse_button.global_y));
- Vector2 l = ai.xform(Vector2(ev.mouse_button.x,ev.mouse_button.y)-vp_ofs);
-
+ Vector2 g = ai.xform(Vector2(ev.mouse_button.global_x, ev.mouse_button.global_y));
+ Vector2 l = ai.xform(Vector2(ev.mouse_button.x, ev.mouse_button.y) - vp_ofs);
- ev.mouse_button.x=l.x;
- ev.mouse_button.y=l.y;
- ev.mouse_button.global_x=g.x;
- ev.mouse_button.global_y=g.y;
+ ev.mouse_button.x = l.x;
+ ev.mouse_button.y = l.y;
+ ev.mouse_button.global_x = g.x;
+ ev.mouse_button.global_y = g.y;
} break;
case InputEvent::MOUSE_MOTION: {
@@ -1435,20 +1344,19 @@ void Viewport::_make_input_local(InputEvent& ev) {
Vector2 vp_ofs = _get_window_offset();
Transform2D ai = get_final_transform().affine_inverse() * _get_input_pre_xform();
- Vector2 g = ai.xform(Vector2(ev.mouse_motion.global_x,ev.mouse_motion.global_y));
- Vector2 l = ai.xform(Vector2(ev.mouse_motion.x,ev.mouse_motion.y)-vp_ofs);
- Vector2 r = ai.basis_xform(Vector2(ev.mouse_motion.relative_x,ev.mouse_motion.relative_y));
- Vector2 s = ai.basis_xform(Vector2(ev.mouse_motion.speed_x,ev.mouse_motion.speed_y));
-
-
- ev.mouse_motion.x=l.x;
- ev.mouse_motion.y=l.y;
- ev.mouse_motion.global_x=g.x;
- ev.mouse_motion.global_y=g.y;
- ev.mouse_motion.relative_x=r.x;
- ev.mouse_motion.relative_y=r.y;
- ev.mouse_motion.speed_x=s.x;
- ev.mouse_motion.speed_y=s.y;
+ Vector2 g = ai.xform(Vector2(ev.mouse_motion.global_x, ev.mouse_motion.global_y));
+ Vector2 l = ai.xform(Vector2(ev.mouse_motion.x, ev.mouse_motion.y) - vp_ofs);
+ Vector2 r = ai.basis_xform(Vector2(ev.mouse_motion.relative_x, ev.mouse_motion.relative_y));
+ Vector2 s = ai.basis_xform(Vector2(ev.mouse_motion.speed_x, ev.mouse_motion.speed_y));
+
+ ev.mouse_motion.x = l.x;
+ ev.mouse_motion.y = l.y;
+ ev.mouse_motion.global_x = g.x;
+ ev.mouse_motion.global_y = g.y;
+ ev.mouse_motion.relative_x = r.x;
+ ev.mouse_motion.relative_y = r.y;
+ ev.mouse_motion.speed_x = s.x;
+ ev.mouse_motion.speed_y = s.y;
} break;
case InputEvent::SCREEN_TOUCH: {
@@ -1456,11 +1364,10 @@ void Viewport::_make_input_local(InputEvent& ev) {
Vector2 vp_ofs = _get_window_offset();
Transform2D ai = get_final_transform().affine_inverse() * _get_input_pre_xform();
- Vector2 t = ai.xform(Vector2(ev.screen_touch.x,ev.screen_touch.y)-vp_ofs);
+ Vector2 t = ai.xform(Vector2(ev.screen_touch.x, ev.screen_touch.y) - vp_ofs);
-
- ev.screen_touch.x=t.x;
- ev.screen_touch.y=t.y;
+ ev.screen_touch.x = t.x;
+ ev.screen_touch.y = t.y;
} break;
case InputEvent::SCREEN_DRAG: {
@@ -1468,29 +1375,27 @@ void Viewport::_make_input_local(InputEvent& ev) {
Vector2 vp_ofs = _get_window_offset();
Transform2D ai = get_final_transform().affine_inverse() * _get_input_pre_xform();
- Vector2 t = ai.xform(Vector2(ev.screen_drag.x,ev.screen_drag.y)-vp_ofs);
- Vector2 r = ai.basis_xform(Vector2(ev.screen_drag.relative_x,ev.screen_drag.relative_y));
- Vector2 s = ai.basis_xform(Vector2(ev.screen_drag.speed_x,ev.screen_drag.speed_y));
- ev.screen_drag.x=t.x;
- ev.screen_drag.y=t.y;
- ev.screen_drag.relative_x=r.x;
- ev.screen_drag.relative_y=r.y;
- ev.screen_drag.speed_x=s.x;
- ev.screen_drag.speed_y=s.y;
+ Vector2 t = ai.xform(Vector2(ev.screen_drag.x, ev.screen_drag.y) - vp_ofs);
+ Vector2 r = ai.basis_xform(Vector2(ev.screen_drag.relative_x, ev.screen_drag.relative_y));
+ Vector2 s = ai.basis_xform(Vector2(ev.screen_drag.speed_x, ev.screen_drag.speed_y));
+ ev.screen_drag.x = t.x;
+ ev.screen_drag.y = t.y;
+ ev.screen_drag.relative_x = r.x;
+ ev.screen_drag.relative_y = r.y;
+ ev.screen_drag.speed_x = s.x;
+ ev.screen_drag.speed_y = s.y;
} break;
}
-
-
}
-void Viewport::_vp_input_text(const String& p_text) {
+void Viewport::_vp_input_text(const String &p_text) {
if (gui.key_focus) {
- gui.key_focus->call("set_text",p_text);
+ gui.key_focus->call("set_text", p_text);
}
}
-void Viewport::_vp_input(const InputEvent& p_ev) {
+void Viewport::_vp_input(const InputEvent &p_ev) {
if (disable_input)
return;
@@ -1501,21 +1406,18 @@ void Viewport::_vp_input(const InputEvent& p_ev) {
}
#endif
-
- if (to_screen_rect==Rect2())
+ if (to_screen_rect == Rect2())
return; //if render target, can't get input events
//this one handles system input, p_ev are in system coordinates
//they are converted to viewport coordinates
-
InputEvent ev = p_ev;
_make_input_local(ev);
input(ev);
-
}
-void Viewport::_vp_unhandled_input(const InputEvent& p_ev) {
+void Viewport::_vp_unhandled_input(const InputEvent &p_ev) {
if (disable_input)
return;
@@ -1530,7 +1432,7 @@ void Viewport::_vp_unhandled_input(const InputEvent& p_ev) {
return;
*/
- if (to_screen_rect==Rect2())
+ if (to_screen_rect == Rect2())
return; //if render target, can't get input events
//this one handles system input, p_ev are in system coordinates
@@ -1539,7 +1441,6 @@ void Viewport::_vp_unhandled_input(const InputEvent& p_ev) {
InputEvent ev = p_ev;
_make_input_local(ev);
unhandled_input(ev);
-
}
Vector2 Viewport::get_mouse_pos() const {
@@ -1547,24 +1448,21 @@ Vector2 Viewport::get_mouse_pos() const {
return (get_final_transform().affine_inverse() * _get_input_pre_xform()).xform(Input::get_singleton()->get_mouse_pos() - _get_window_offset());
}
-void Viewport::warp_mouse(const Vector2& p_pos) {
+void Viewport::warp_mouse(const Vector2 &p_pos) {
Vector2 gpos = (get_final_transform().affine_inverse() * _get_input_pre_xform()).affine_inverse().xform(p_pos);
Input::get_singleton()->warp_mouse_pos(gpos);
}
-
-
void Viewport::_gui_sort_subwindows() {
if (!gui.subwindow_order_dirty)
return;
-
gui.modal_stack.sort_custom<Control::CComparator>();
gui.subwindows.sort_custom<Control::CComparator>();
- gui.subwindow_order_dirty=false;
+ gui.subwindow_order_dirty = false;
}
void Viewport::_gui_sort_modal_stack() {
@@ -1572,7 +1470,6 @@ void Viewport::_gui_sort_modal_stack() {
gui.modal_stack.sort_custom<Control::CComparator>();
}
-
void Viewport::_gui_sort_roots() {
if (!gui.roots_order_dirty)
@@ -1580,19 +1477,17 @@ void Viewport::_gui_sort_roots() {
gui.roots.sort_custom<Control::CComparator>();
- gui.roots_order_dirty=false;
+ gui.roots_order_dirty = false;
}
-
void Viewport::_gui_cancel_tooltip() {
- gui.tooltip=NULL;
- gui.tooltip_timer=-1;
+ gui.tooltip = NULL;
+ gui.tooltip_timer = -1;
if (gui.tooltip_popup) {
gui.tooltip_popup->queue_delete();
- gui.tooltip_popup=NULL;
+ gui.tooltip_popup = NULL;
}
-
}
void Viewport::_gui_show_tooltip() {
@@ -1601,47 +1496,46 @@ void Viewport::_gui_show_tooltip() {
return;
}
- String tooltip = gui.tooltip->get_tooltip( gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos) );
- if (tooltip.length()==0)
+ String tooltip = gui.tooltip->get_tooltip(gui.tooltip->get_global_transform().xform_inv(gui.tooltip_pos));
+ if (tooltip.length() == 0)
return; // bye
if (gui.tooltip_popup) {
memdelete(gui.tooltip_popup);
- gui.tooltip_popup=NULL;
+ gui.tooltip_popup = NULL;
}
Control *rp = gui.tooltip->get_root_parent_control();
if (!rp)
return;
-
- gui.tooltip_popup = memnew( TooltipPanel );
+ gui.tooltip_popup = memnew(TooltipPanel);
rp->add_child(gui.tooltip_popup);
gui.tooltip_popup->force_parent_owned();
- gui.tooltip_label = memnew( TooltipLabel );
+ gui.tooltip_label = memnew(TooltipLabel);
gui.tooltip_popup->add_child(gui.tooltip_label);
gui.tooltip_popup->set_as_toplevel(true);
gui.tooltip_popup->hide();
- Ref<StyleBox> ttp = gui.tooltip_label->get_stylebox("panel","TooltipPanel");
+ Ref<StyleBox> ttp = gui.tooltip_label->get_stylebox("panel", "TooltipPanel");
- gui.tooltip_label->set_anchor_and_margin(MARGIN_LEFT,Control::ANCHOR_BEGIN,ttp->get_margin(MARGIN_LEFT));
- gui.tooltip_label->set_anchor_and_margin(MARGIN_TOP,Control::ANCHOR_BEGIN,ttp->get_margin(MARGIN_TOP));
- gui.tooltip_label->set_anchor_and_margin(MARGIN_RIGHT,Control::ANCHOR_END,ttp->get_margin(MARGIN_RIGHT));
- gui.tooltip_label->set_anchor_and_margin(MARGIN_BOTTOM,Control::ANCHOR_END,ttp->get_margin(MARGIN_BOTTOM));
+ gui.tooltip_label->set_anchor_and_margin(MARGIN_LEFT, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_LEFT));
+ gui.tooltip_label->set_anchor_and_margin(MARGIN_TOP, Control::ANCHOR_BEGIN, ttp->get_margin(MARGIN_TOP));
+ gui.tooltip_label->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, ttp->get_margin(MARGIN_RIGHT));
+ gui.tooltip_label->set_anchor_and_margin(MARGIN_BOTTOM, Control::ANCHOR_END, ttp->get_margin(MARGIN_BOTTOM));
gui.tooltip_label->set_text(tooltip);
- Rect2 r(gui.tooltip_pos+Point2(10,10),gui.tooltip_label->get_combined_minimum_size()+ttp->get_minimum_size());
+ Rect2 r(gui.tooltip_pos + Point2(10, 10), gui.tooltip_label->get_combined_minimum_size() + ttp->get_minimum_size());
Rect2 vr = gui.tooltip_label->get_viewport_rect();
- if (r.size.x+r.pos.x>vr.size.x)
- r.pos.x=vr.size.x-r.size.x;
- else if (r.pos.x<0)
- r.pos.x=0;
+ if (r.size.x + r.pos.x > vr.size.x)
+ r.pos.x = vr.size.x - r.size.x;
+ else if (r.pos.x < 0)
+ r.pos.x = 0;
- if (r.size.y+r.pos.y>vr.size.y)
- r.pos.y=vr.size.y-r.size.y;
- else if (r.pos.y<0)
- r.pos.y=0;
+ if (r.size.y + r.pos.y > vr.size.y)
+ r.pos.y = vr.size.y - r.size.y;
+ else if (r.pos.y < 0)
+ r.pos.y = 0;
gui.tooltip_popup->set_global_pos(r.pos);
gui.tooltip_popup->set_size(r.size);
@@ -1650,56 +1544,53 @@ void Viewport::_gui_show_tooltip() {
gui.tooltip_popup->show();
}
-
-void Viewport::_gui_call_input(Control *p_control,const InputEvent& p_input) {
+void Viewport::_gui_call_input(Control *p_control, const InputEvent &p_input) {
//_block();
-
InputEvent ev = p_input;
//mouse wheel events can't be stopped
- bool cant_stop_me_now = (ev.type==InputEvent::MOUSE_BUTTON &&
- (ev.mouse_button.button_index==BUTTON_WHEEL_DOWN ||
- ev.mouse_button.button_index==BUTTON_WHEEL_UP ||
- ev.mouse_button.button_index==BUTTON_WHEEL_LEFT ||
- ev.mouse_button.button_index==BUTTON_WHEEL_RIGHT ) );
+ bool cant_stop_me_now = (ev.type == InputEvent::MOUSE_BUTTON &&
+ (ev.mouse_button.button_index == BUTTON_WHEEL_DOWN ||
+ ev.mouse_button.button_index == BUTTON_WHEEL_UP ||
+ ev.mouse_button.button_index == BUTTON_WHEEL_LEFT ||
+ ev.mouse_button.button_index == BUTTON_WHEEL_RIGHT));
- CanvasItem *ci=p_control;
- while(ci) {
+ CanvasItem *ci = p_control;
+ while (ci) {
Control *control = ci->cast_to<Control>();
if (control) {
- control->call_multilevel(SceneStringNames::get_singleton()->_gui_input,ev);
+ control->call_multilevel(SceneStringNames::get_singleton()->_gui_input, ev);
if (gui.key_event_accepted)
break;
if (!control->is_inside_tree())
break;
- control->emit_signal(SceneStringNames::get_singleton()->gui_input,ev);
+ control->emit_signal(SceneStringNames::get_singleton()->gui_input, ev);
if (!control->is_inside_tree() || control->is_set_as_toplevel())
break;
if (gui.key_event_accepted)
break;
- if (!cant_stop_me_now && control->data.mouse_filter==Control::MOUSE_FILTER_STOP && (ev.type==InputEvent::MOUSE_BUTTON || ev.type==InputEvent::MOUSE_MOTION))
+ if (!cant_stop_me_now && control->data.mouse_filter == Control::MOUSE_FILTER_STOP && (ev.type == InputEvent::MOUSE_BUTTON || ev.type == InputEvent::MOUSE_MOTION))
break;
}
if (ci->is_set_as_toplevel())
break;
- ev=ev.xform_by(ci->get_transform()); //transform event upwards
- ci=ci->get_parent_item();
+ ev = ev.xform_by(ci->get_transform()); //transform event upwards
+ ci = ci->get_parent_item();
}
//_unblock();
-
}
-Control* Viewport::_gui_find_control(const Point2& p_global) {
+Control *Viewport::_gui_find_control(const Point2 &p_global) {
_gui_sort_subwindows();
- for (List<Control*>::Element *E=gui.subwindows.back();E;E=E->prev()) {
+ for (List<Control *>::Element *E = gui.subwindows.back(); E; E = E->prev()) {
Control *sw = E->get();
if (!sw->is_visible_in_tree())
@@ -1708,18 +1599,18 @@ Control* Viewport::_gui_find_control(const Point2& p_global) {
Transform2D xform;
CanvasItem *pci = sw->get_parent_item();
if (pci)
- xform=pci->get_global_transform_with_canvas();
+ xform = pci->get_global_transform_with_canvas();
else
- xform=sw->get_canvas_transform();
+ xform = sw->get_canvas_transform();
- Control *ret = _gui_find_control_at_pos(sw,p_global,xform,gui.focus_inv_xform);
+ Control *ret = _gui_find_control_at_pos(sw, p_global, xform, gui.focus_inv_xform);
if (ret)
return ret;
}
_gui_sort_roots();
- for (List<Control*>::Element *E=gui.roots.back();E;E=E->prev()) {
+ for (List<Control *>::Element *E = gui.roots.back(); E; E = E->prev()) {
Control *sw = E->get();
if (!sw->is_visible_in_tree())
@@ -1728,27 +1619,24 @@ Control* Viewport::_gui_find_control(const Point2& p_global) {
Transform2D xform;
CanvasItem *pci = sw->get_parent_item();
if (pci)
- xform=pci->get_global_transform_with_canvas();
+ xform = pci->get_global_transform_with_canvas();
else
- xform=sw->get_canvas_transform();
+ xform = sw->get_canvas_transform();
-
- Control *ret = _gui_find_control_at_pos(sw,p_global,xform,gui.focus_inv_xform);
+ Control *ret = _gui_find_control_at_pos(sw, p_global, xform, gui.focus_inv_xform);
if (ret)
return ret;
}
return NULL;
-
}
-
-Control* Viewport::_gui_find_control_at_pos(CanvasItem* p_node,const Point2& p_global,const Transform2D& p_xform,Transform2D& r_inv_xform) {
+Control *Viewport::_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform) {
if (p_node->cast_to<Viewport>())
return NULL;
- Control *c=p_node->cast_to<Control>();
+ Control *c = p_node->cast_to<Control>();
if (c) {
//print_line("at "+String(c->get_path())+" POS "+c->get_pos()+" bt "+p_xform);
@@ -1763,21 +1651,21 @@ Control* Viewport::_gui_find_control_at_pos(CanvasItem* p_node,const Point2& p_g
Transform2D matrix = p_xform * p_node->get_transform();
// matrix.basis_determinant() == 0.0f implies that node does not exist on scene
- if(matrix.basis_determinant() == 0.0f)
+ if (matrix.basis_determinant() == 0.0f)
return NULL;
if (!c || !c->clips_input() || c->has_point(matrix.affine_inverse().xform(p_global))) {
- for(int i=p_node->get_child_count()-1;i>=0;i--) {
+ for (int i = p_node->get_child_count() - 1; i >= 0; i--) {
- if (p_node==gui.tooltip_popup)
+ if (p_node == gui.tooltip_popup)
continue;
CanvasItem *ci = p_node->get_child(i)->cast_to<CanvasItem>();
if (!ci || ci->is_set_as_toplevel())
continue;
- Control *ret=_gui_find_control_at_pos(ci,p_global,matrix,r_inv_xform);
+ Control *ret = _gui_find_control_at_pos(ci, p_global, matrix, r_inv_xform);
if (ret)
return ret;
}
@@ -1789,33 +1677,31 @@ Control* Viewport::_gui_find_control_at_pos(CanvasItem* p_node,const Point2& p_g
matrix.affine_invert();
//conditions for considering this as a valid control for return
- if (c->data.mouse_filter!=Control::MOUSE_FILTER_IGNORE && c->has_point(matrix.xform(p_global)) && (!gui.drag_preview || (c!=gui.drag_preview && !gui.drag_preview->is_a_parent_of(c)))) {
- r_inv_xform=matrix;
+ if (c->data.mouse_filter != Control::MOUSE_FILTER_IGNORE && c->has_point(matrix.xform(p_global)) && (!gui.drag_preview || (c != gui.drag_preview && !gui.drag_preview->is_a_parent_of(c)))) {
+ r_inv_xform = matrix;
return c;
} else
return NULL;
}
-bool Viewport::_gui_drop(Control *p_at_control,Point2 p_at_pos,bool p_just_check) {
-
+bool Viewport::_gui_drop(Control *p_at_control, Point2 p_at_pos, bool p_just_check) {
{ //attempt grab, try parent controls too
- CanvasItem *ci=p_at_control;
- while(ci) {
+ CanvasItem *ci = p_at_control;
+ while (ci) {
Control *control = ci->cast_to<Control>();
if (control) {
-
- if (control->can_drop_data(p_at_pos,gui.drag_data)) {
+ if (control->can_drop_data(p_at_pos, gui.drag_data)) {
if (!p_just_check) {
- control->drop_data(p_at_pos,gui.drag_data);
+ control->drop_data(p_at_pos, gui.drag_data);
}
return true;
}
- if (control->data.mouse_filter==Control::MOUSE_FILTER_STOP)
+ if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP)
break;
}
@@ -1824,19 +1710,16 @@ bool Viewport::_gui_drop(Control *p_at_control,Point2 p_at_pos,bool p_just_check
if (ci->is_set_as_toplevel())
break;
- ci=ci->get_parent_item();
+ ci = ci->get_parent_item();
}
}
return false;
}
-
void Viewport::_gui_input_event(InputEvent p_event) {
-
-
- if (p_event.ID==gui.cancelled_input_ID) {
+ if (p_event.ID == gui.cancelled_input_ID) {
return;
}
//?
@@ -1846,27 +1729,22 @@ void Viewport::_gui_input_event(InputEvent p_event) {
}
*/
-
- switch(p_event.type) {
+ switch (p_event.type) {
case InputEvent::MOUSE_BUTTON: {
+ gui.key_event_accepted = false;
- gui.key_event_accepted=false;
-
- Point2 mpos=Point2(p_event.mouse_button.x,p_event.mouse_button.y);
+ Point2 mpos = Point2(p_event.mouse_button.x, p_event.mouse_button.y);
if (p_event.mouse_button.pressed) {
-
-
Size2 pos = mpos;
- if (gui.mouse_focus && p_event.mouse_button.button_index!=gui.mouse_focus_button) {
+ if (gui.mouse_focus && p_event.mouse_button.button_index != gui.mouse_focus_button) {
//do not steal mouse focus and stuff
} else {
-
_gui_sort_modal_stack();
while (!gui.modal_stack.empty()) {
@@ -1874,7 +1752,7 @@ void Viewport::_gui_input_event(InputEvent p_event) {
Vector2 pos = top->get_global_transform_with_canvas().affine_inverse().xform(mpos);
if (!top->has_point(pos)) {
- if (top->data.modal_exclusive || top->data.modal_frame==Engine::get_singleton()->get_frames_drawn()) {
+ if (top->data.modal_exclusive || top->data.modal_frame == Engine::get_singleton()->get_frames_drawn()) {
//cancel event, sorry, modal exclusive EATS UP ALL
//alternative, you can't pop out a window the same frame it was made modal (fixes many issues)
get_tree()->set_input_as_handled();
@@ -1889,8 +1767,6 @@ void Viewport::_gui_input_event(InputEvent p_event) {
}
}
-
-
//Matrix32 parent_xform;
/*
@@ -1900,21 +1776,18 @@ void Viewport::_gui_input_event(InputEvent p_event) {
gui.mouse_focus = _gui_find_control(pos);
//print_line("has mf "+itos(gui.mouse_focus!=NULL));
- gui.mouse_focus_button=p_event.mouse_button.button_index;
+ gui.mouse_focus_button = p_event.mouse_button.button_index;
if (!gui.mouse_focus) {
break;
}
- if (p_event.mouse_button.button_index==BUTTON_LEFT) {
- gui.drag_accum=Vector2();
- gui.drag_attempted=false;
+ if (p_event.mouse_button.button_index == BUTTON_LEFT) {
+ gui.drag_accum = Vector2();
+ gui.drag_attempted = false;
}
-
-
}
-
p_event.mouse_button.global_x = pos.x;
p_event.mouse_button.global_y = pos.y;
@@ -1928,91 +1801,84 @@ void Viewport::_gui_input_event(InputEvent p_event) {
Array arr;
arr.push_back(gui.mouse_focus->get_path());
arr.push_back(gui.mouse_focus->get_class());
- ScriptDebugger::get_singleton()->send_message("click_ctrl",arr);
+ ScriptDebugger::get_singleton()->send_message("click_ctrl", arr);
}
- /*if (bool(GLOBAL_DEF("debug/print_clicked_control",false))) {
+/*if (bool(GLOBAL_DEF("debug/print_clicked_control",false))) {
print_line(String(gui.mouse_focus->get_path())+" - "+pos);
}*/
#endif
- if (p_event.mouse_button.button_index==BUTTON_LEFT) { //assign focus
- CanvasItem *ci=gui.mouse_focus;
- while(ci) {
+ if (p_event.mouse_button.button_index == BUTTON_LEFT) { //assign focus
+ CanvasItem *ci = gui.mouse_focus;
+ while (ci) {
Control *control = ci->cast_to<Control>();
if (control) {
- if (control->get_focus_mode()!=Control::FOCUS_NONE) {
- if (control!=gui.key_focus) {
+ if (control->get_focus_mode() != Control::FOCUS_NONE) {
+ if (control != gui.key_focus) {
control->grab_focus();
}
break;
}
- if (control->data.mouse_filter==Control::MOUSE_FILTER_STOP)
+ if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP)
break;
}
if (ci->is_set_as_toplevel())
break;
- ci=ci->get_parent_item();
+ ci = ci->get_parent_item();
}
}
-
if (gui.mouse_focus->can_process()) {
- _gui_call_input(gui.mouse_focus,p_event);
+ _gui_call_input(gui.mouse_focus, p_event);
}
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,"windows","_cancel_input_ID",p_event.ID);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, "windows", "_cancel_input_ID", p_event.ID);
get_tree()->set_input_as_handled();
-
- if (gui.drag_data.get_type()!=Variant::NIL && p_event.mouse_button.button_index==BUTTON_LEFT) {
+ if (gui.drag_data.get_type() != Variant::NIL && p_event.mouse_button.button_index == BUTTON_LEFT) {
//alternate drop use (when using force_drag(), as proposed by #5342
if (gui.mouse_focus) {
- _gui_drop(gui.mouse_focus,pos,false);
+ _gui_drop(gui.mouse_focus, pos, false);
}
- gui.drag_data=Variant();
+ gui.drag_data = Variant();
if (gui.drag_preview) {
- memdelete( gui.drag_preview );
- gui.drag_preview=NULL;
+ memdelete(gui.drag_preview);
+ gui.drag_preview = NULL;
}
- _propagate_viewport_notification(this,NOTIFICATION_DRAG_END);
+ _propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
//change mouse accordingly
}
-
-
_gui_cancel_tooltip();
//gui.tooltip_popup->hide();
} else {
-
-
- if (gui.drag_data.get_type()!=Variant::NIL && p_event.mouse_button.button_index==BUTTON_LEFT) {
+ if (gui.drag_data.get_type() != Variant::NIL && p_event.mouse_button.button_index == BUTTON_LEFT) {
if (gui.mouse_over) {
Size2 pos = mpos;
pos = gui.focus_inv_xform.xform(pos);
- _gui_drop(gui.mouse_over,pos,false);
-
+ _gui_drop(gui.mouse_over, pos, false);
}
- if (gui.drag_preview && p_event.mouse_button.button_index==BUTTON_LEFT) {
- memdelete( gui.drag_preview );
- gui.drag_preview=NULL;
+ if (gui.drag_preview && p_event.mouse_button.button_index == BUTTON_LEFT) {
+ memdelete(gui.drag_preview);
+ gui.drag_preview = NULL;
}
- gui.drag_data=Variant();
- _propagate_viewport_notification(this,NOTIFICATION_DRAG_END);
+ gui.drag_data = Variant();
+ _propagate_viewport_notification(this, NOTIFICATION_DRAG_END);
//change mouse accordingly
}
@@ -2029,12 +1895,12 @@ void Viewport::_gui_input_event(InputEvent p_event) {
p_event.mouse_button.y = pos.y;
if (gui.mouse_focus->can_process()) {
- _gui_call_input(gui.mouse_focus,p_event);
+ _gui_call_input(gui.mouse_focus, p_event);
}
- if (p_event.mouse_button.button_index==gui.mouse_focus_button) {
- gui.mouse_focus=NULL;
- gui.mouse_focus_button=-1;
+ if (p_event.mouse_button.button_index == gui.mouse_focus_button) {
+ gui.mouse_focus = NULL;
+ gui.mouse_focus_button = -1;
}
/*if (gui.drag_data.get_type()!=Variant::NIL && p_event.mouse_button.button_index==BUTTON_LEFT) {
@@ -2042,66 +1908,60 @@ void Viewport::_gui_input_event(InputEvent p_event) {
gui.drag_data=Variant(); //always clear
}*/
-
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,"windows","_cancel_input_ID",p_event.ID);
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, "windows", "_cancel_input_ID", p_event.ID);
get_tree()->set_input_as_handled();
-
}
} break;
case InputEvent::MOUSE_MOTION: {
- gui.key_event_accepted=false;
- Point2 mpos=Point2(p_event.mouse_motion.x,p_event.mouse_motion.y);
+ gui.key_event_accepted = false;
+ Point2 mpos = Point2(p_event.mouse_motion.x, p_event.mouse_motion.y);
- gui.last_mouse_pos=mpos;
+ gui.last_mouse_pos = mpos;
Control *over = NULL;
-
// D&D
- if (!gui.drag_attempted && gui.mouse_focus && p_event.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
+ if (!gui.drag_attempted && gui.mouse_focus && p_event.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
- gui.drag_accum+=Point2(p_event.mouse_motion.relative_x,p_event.mouse_motion.relative_y);
+ gui.drag_accum += Point2(p_event.mouse_motion.relative_x, p_event.mouse_motion.relative_y);
float len = gui.drag_accum.length();
- if (len>10) {
+ if (len > 10) {
{ //attempt grab, try parent controls too
- CanvasItem *ci=gui.mouse_focus;
- while(ci) {
+ CanvasItem *ci = gui.mouse_focus;
+ while (ci) {
Control *control = ci->cast_to<Control>();
if (control) {
- gui.drag_data=control->get_drag_data(control->get_global_transform_with_canvas().affine_inverse().xform(mpos)-gui.drag_accum);
- if (gui.drag_data.get_type()!=Variant::NIL) {
+ gui.drag_data = control->get_drag_data(control->get_global_transform_with_canvas().affine_inverse().xform(mpos) - gui.drag_accum);
+ if (gui.drag_data.get_type() != Variant::NIL) {
- gui.mouse_focus=NULL;
+ gui.mouse_focus = NULL;
}
- if (control->data.mouse_filter==Control::MOUSE_FILTER_STOP)
+ if (control->data.mouse_filter == Control::MOUSE_FILTER_STOP)
break;
}
if (ci->is_set_as_toplevel())
break;
- ci=ci->get_parent_item();
+ ci = ci->get_parent_item();
}
}
+ gui.drag_attempted = true;
+ if (gui.drag_data.get_type() != Variant::NIL) {
-
- gui.drag_attempted=true;
- if (gui.drag_data.get_type()!=Variant::NIL) {
-
- _propagate_viewport_notification(this,NOTIFICATION_DRAG_BEGIN);
+ _propagate_viewport_notification(this, NOTIFICATION_DRAG_BEGIN);
}
}
}
-
if (gui.mouse_focus) {
- over=gui.mouse_focus;
+ over = gui.mouse_focus;
//recompute focus_inv_xform again here
} else {
@@ -2109,19 +1969,16 @@ void Viewport::_gui_input_event(InputEvent p_event) {
over = _gui_find_control(mpos);
}
-
-
- if (gui.drag_data.get_type()==Variant::NIL && over && !gui.modal_stack.empty()) {
+ if (gui.drag_data.get_type() == Variant::NIL && over && !gui.modal_stack.empty()) {
Control *top = gui.modal_stack.back()->get();
- if (over!=top && !top->is_a_parent_of(over)) {
+ if (over != top && !top->is_a_parent_of(over)) {
break; // don't send motion event to anything below modal stack top
}
}
-
- if (over!=gui.mouse_over) {
+ if (over != gui.mouse_over) {
if (gui.mouse_over)
gui.mouse_over->notification(Control::NOTIFICATION_MOUSE_EXIT);
@@ -2130,10 +1987,9 @@ void Viewport::_gui_input_event(InputEvent p_event) {
if (over)
over->notification(Control::NOTIFICATION_MOUSE_ENTER);
-
}
- gui.mouse_over=over;
+ gui.mouse_over = over;
if (gui.drag_preview) {
gui.drag_preview->set_pos(mpos);
@@ -2144,29 +2000,26 @@ void Viewport::_gui_input_event(InputEvent p_event) {
break;
}
-
Transform2D localizer = over->get_global_transform_with_canvas().affine_inverse();
Size2 pos = localizer.xform(mpos);
- Vector2 speed = localizer.basis_xform(Point2(p_event.mouse_motion.speed_x,p_event.mouse_motion.speed_y));
- Vector2 rel = localizer.basis_xform(Point2(p_event.mouse_motion.relative_x,p_event.mouse_motion.relative_y));
-
+ Vector2 speed = localizer.basis_xform(Point2(p_event.mouse_motion.speed_x, p_event.mouse_motion.speed_y));
+ Vector2 rel = localizer.basis_xform(Point2(p_event.mouse_motion.relative_x, p_event.mouse_motion.relative_y));
p_event.mouse_motion.global_x = mpos.x;
p_event.mouse_motion.global_y = mpos.y;
- p_event.mouse_motion.speed_x=speed.x;
- p_event.mouse_motion.speed_y=speed.y;
- p_event.mouse_motion.relative_x=rel.x;
- p_event.mouse_motion.relative_y=rel.y;
+ p_event.mouse_motion.speed_x = speed.x;
+ p_event.mouse_motion.speed_y = speed.y;
+ p_event.mouse_motion.relative_x = rel.x;
+ p_event.mouse_motion.relative_y = rel.y;
- if (p_event.mouse_motion.button_mask==0) {
+ if (p_event.mouse_motion.button_mask == 0) {
//nothing pressed
- bool can_tooltip=true;
+ bool can_tooltip = true;
if (!gui.modal_stack.empty()) {
- if (gui.modal_stack.back()->get()!=over && !gui.modal_stack.back()->get()->is_a_parent_of(over))
- can_tooltip=false;
-
+ if (gui.modal_stack.back()->get() != over && !gui.modal_stack.back()->get()->is_a_parent_of(over))
+ can_tooltip = false;
}
bool is_tooltip_shown = false;
@@ -2179,51 +2032,40 @@ void Viewport::_gui_input_event(InputEvent p_event) {
_gui_cancel_tooltip();
else if (tooltip == gui.tooltip_label->get_text())
is_tooltip_shown = true;
- }
- else
+ } else
_gui_cancel_tooltip();
}
if (can_tooltip && !is_tooltip_shown) {
- gui.tooltip=over;
- gui.tooltip_pos=mpos;//(parent_xform * get_transform()).affine_inverse().xform(pos);
- gui.tooltip_timer=gui.tooltip_delay;
-
+ gui.tooltip = over;
+ gui.tooltip_pos = mpos; //(parent_xform * get_transform()).affine_inverse().xform(pos);
+ gui.tooltip_timer = gui.tooltip_delay;
}
}
-
//pos = gui.focus_inv_xform.xform(pos);
-
p_event.mouse_motion.x = pos.x;
p_event.mouse_motion.y = pos.y;
-
Control::CursorShape cursor_shape = over->get_cursor_shape(pos);
- OS::get_singleton()->set_cursor_shape( (OS::CursorShape)cursor_shape );
-
+ OS::get_singleton()->set_cursor_shape((OS::CursorShape)cursor_shape);
if (over->can_process()) {
- _gui_call_input(over,p_event);
+ _gui_call_input(over, p_event);
}
-
-
get_tree()->set_input_as_handled();
+ if (gui.drag_data.get_type() != Variant::NIL && p_event.mouse_motion.button_mask & BUTTON_MASK_LEFT) {
- if (gui.drag_data.get_type()!=Variant::NIL && p_event.mouse_motion.button_mask&BUTTON_MASK_LEFT) {
-
-
- bool can_drop = _gui_drop(over,pos,true);
+ bool can_drop = _gui_drop(over, pos, true);
if (!can_drop) {
- OS::get_singleton()->set_cursor_shape( OS::CURSOR_FORBIDDEN );
+ OS::get_singleton()->set_cursor_shape(OS::CURSOR_FORBIDDEN);
} else {
- OS::get_singleton()->set_cursor_shape( OS::CURSOR_CAN_DROP );
-
+ OS::get_singleton()->set_cursor_shape(OS::CURSOR_CAN_DROP);
}
//change mouse accordingly i guess
}
@@ -2234,21 +2076,19 @@ void Viewport::_gui_input_event(InputEvent p_event) {
case InputEvent::JOYPAD_MOTION:
case InputEvent::KEY: {
-
if (gui.key_focus && !gui.key_focus->is_visible_in_tree()) {
gui.key_focus->release_focus();
}
- if (gui.key_focus) {
+ if (gui.key_focus) {
- gui.key_event_accepted=false;
+ gui.key_event_accepted = false;
if (gui.key_focus->can_process()) {
- gui.key_focus->call_multilevel(SceneStringNames::get_singleton()->_gui_input,p_event);
+ gui.key_focus->call_multilevel(SceneStringNames::get_singleton()->_gui_input, p_event);
if (gui.key_focus) //maybe lost it
- gui.key_focus->emit_signal(SceneStringNames::get_singleton()->gui_input,p_event);
+ gui.key_focus->emit_signal(SceneStringNames::get_singleton()->gui_input, p_event);
}
-
if (gui.key_event_accepted) {
get_tree()->set_input_as_handled();
@@ -2256,7 +2096,6 @@ void Viewport::_gui_input_event(InputEvent p_event) {
}
}
-
if (p_event.is_pressed() && p_event.is_action("ui_cancel") && !gui.modal_stack.empty()) {
_gui_sort_modal_stack();
@@ -2269,14 +2108,13 @@ void Viewport::_gui_input_event(InputEvent p_event) {
}
}
-
- Control * from = gui.key_focus ? gui.key_focus : NULL; //hmm
+ Control *from = gui.key_focus ? gui.key_focus : NULL; //hmm
//keyboard focus
//if (from && p_event.key.pressed && !p_event.key.mod.alt && !p_event.key.mod.meta && !p_event.key.mod.command) {
if (from && p_event.is_pressed()) {
- Control * next=NULL;
+ Control *next = NULL;
if (p_event.is_action("ui_focus_next")) {
@@ -2308,7 +2146,6 @@ void Viewport::_gui_input_event(InputEvent p_event) {
next = from->_get_focus_neighbour(MARGIN_BOTTOM);
}
-
if (next) {
next->grab_focus();
get_tree()->set_input_as_handled();
@@ -2319,41 +2156,39 @@ void Viewport::_gui_input_event(InputEvent p_event) {
}
}
+List<Control *>::Element *Viewport::_gui_add_root_control(Control *p_control) {
-List<Control*>::Element* Viewport::_gui_add_root_control(Control* p_control) {
-
- gui.roots_order_dirty=true;
+ gui.roots_order_dirty = true;
return gui.roots.push_back(p_control);
}
-List<Control*>::Element* Viewport::_gui_add_subwindow_control(Control* p_control) {
+List<Control *>::Element *Viewport::_gui_add_subwindow_control(Control *p_control) {
- gui.subwindow_order_dirty=true;
+ gui.subwindow_order_dirty = true;
return gui.subwindows.push_back(p_control);
-
}
void Viewport::_gui_set_subwindow_order_dirty() {
- gui.subwindow_order_dirty=true;
+ gui.subwindow_order_dirty = true;
}
void Viewport::_gui_set_root_order_dirty() {
- gui.roots_order_dirty=true;
+ gui.roots_order_dirty = true;
}
-void Viewport::_gui_remove_modal_control(List<Control*>::Element *MI) {
+void Viewport::_gui_remove_modal_control(List<Control *>::Element *MI) {
gui.modal_stack.erase(MI);
}
-void Viewport::_gui_remove_from_modal_stack(List<Control*>::Element *MI,ObjectID p_prev_focus_owner) {
+void Viewport::_gui_remove_from_modal_stack(List<Control *>::Element *MI, ObjectID p_prev_focus_owner) {
//transfer the focus stack to the next
- List<Control*>::Element *next = MI->next();
+ List<Control *>::Element *next = MI->next();
gui.modal_stack.erase(MI);
- MI=NULL;
+ MI = NULL;
if (p_prev_focus_owner) {
@@ -2377,25 +2212,25 @@ void Viewport::_gui_remove_from_modal_stack(List<Control*>::Element *MI,ObjectID
}
}
-void Viewport::_gui_force_drag(Control *p_base, const Variant& p_data, Control *p_control) {
+void Viewport::_gui_force_drag(Control *p_base, const Variant &p_data, Control *p_control) {
ERR_EXPLAIN("Drag data must be a value");
- ERR_FAIL_COND(p_data.get_type()==Variant::NIL);
+ ERR_FAIL_COND(p_data.get_type() == Variant::NIL);
- gui.drag_data=p_data;
- gui.mouse_focus=NULL;
+ gui.drag_data = p_data;
+ gui.mouse_focus = NULL;
if (p_control) {
- _gui_set_drag_preview(p_base,p_control);
+ _gui_set_drag_preview(p_base, p_control);
}
}
void Viewport::_gui_set_drag_preview(Control *p_base, Control *p_control) {
ERR_FAIL_NULL(p_control);
- ERR_FAIL_COND( !((Object*)p_control)->cast_to<Control>());
+ ERR_FAIL_COND(!((Object *)p_control)->cast_to<Control>());
ERR_FAIL_COND(p_control->is_inside_tree());
- ERR_FAIL_COND(p_control->get_parent()!=NULL);
+ ERR_FAIL_COND(p_control->get_parent() != NULL);
if (gui.drag_preview) {
memdelete(gui.drag_preview);
@@ -2405,25 +2240,24 @@ void Viewport::_gui_set_drag_preview(Control *p_base, Control *p_control) {
p_base->get_root_parent_control()->add_child(p_control); //add as child of viewport
p_control->raise();
if (gui.drag_preview) {
- memdelete( gui.drag_preview );
+ memdelete(gui.drag_preview);
}
- gui.drag_preview=p_control;
+ gui.drag_preview = p_control;
}
-
-void Viewport::_gui_remove_root_control(List<Control*>::Element *RI) {
+void Viewport::_gui_remove_root_control(List<Control *>::Element *RI) {
gui.roots.erase(RI);
}
-void Viewport::_gui_remove_subwindow_control(List<Control*>::Element* SI){
+void Viewport::_gui_remove_subwindow_control(List<Control *>::Element *SI) {
gui.subwindows.erase(SI);
}
void Viewport::_gui_unfocus_control(Control *p_control) {
- if (gui.key_focus==p_control) {
+ if (gui.key_focus == p_control) {
gui.key_focus->release_focus();
}
}
@@ -2431,7 +2265,7 @@ void Viewport::_gui_unfocus_control(Control *p_control) {
void Viewport::_gui_hid_control(Control *p_control) {
if (gui.mouse_focus == p_control) {
- gui.mouse_focus=NULL;
+ gui.mouse_focus = NULL;
}
/* ???
@@ -2445,81 +2279,71 @@ void Viewport::_gui_hid_control(Control *p_control) {
*/
if (gui.key_focus == p_control)
- gui.key_focus=NULL;
+ gui.key_focus = NULL;
if (gui.mouse_over == p_control)
- gui.mouse_over=NULL;
+ gui.mouse_over = NULL;
if (gui.tooltip == p_control)
- gui.tooltip=NULL;
+ gui.tooltip = NULL;
if (gui.tooltip == p_control) {
- gui.tooltip=NULL;
+ gui.tooltip = NULL;
_gui_cancel_tooltip();
}
-
}
void Viewport::_gui_remove_control(Control *p_control) {
-
if (gui.mouse_focus == p_control)
- gui.mouse_focus=NULL;
+ gui.mouse_focus = NULL;
if (gui.key_focus == p_control)
- gui.key_focus=NULL;
+ gui.key_focus = NULL;
if (gui.mouse_over == p_control)
- gui.mouse_over=NULL;
+ gui.mouse_over = NULL;
if (gui.tooltip == p_control)
- gui.tooltip=NULL;
+ gui.tooltip = NULL;
if (gui.tooltip_popup == p_control) {
_gui_cancel_tooltip();
}
-
-
}
void Viewport::_gui_remove_focus() {
if (gui.key_focus) {
- Node *f=gui.key_focus;
- gui.key_focus=NULL;
- f->notification( Control::NOTIFICATION_FOCUS_EXIT,true );
-
-
+ Node *f = gui.key_focus;
+ gui.key_focus = NULL;
+ f->notification(Control::NOTIFICATION_FOCUS_EXIT, true);
}
}
-bool Viewport::_gui_is_modal_on_top(const Control* p_control) {
-
- return (gui.modal_stack.size() && gui.modal_stack.back()->get()==p_control);
+bool Viewport::_gui_is_modal_on_top(const Control *p_control) {
+ return (gui.modal_stack.size() && gui.modal_stack.back()->get() == p_control);
}
-bool Viewport::_gui_control_has_focus(const Control* p_control) {
+bool Viewport::_gui_control_has_focus(const Control *p_control) {
- return gui.key_focus==p_control;
+ return gui.key_focus == p_control;
}
-void Viewport::_gui_control_grab_focus(Control* p_control) {
-
+void Viewport::_gui_control_grab_focus(Control *p_control) {
//no need for change
- if (gui.key_focus && gui.key_focus==p_control)
+ if (gui.key_focus && gui.key_focus == p_control)
return;
- get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME,"_viewports","_gui_remove_focus");
- gui.key_focus=p_control;
+ get_tree()->call_group_flags(SceneTree::GROUP_CALL_REALTIME, "_viewports", "_gui_remove_focus");
+ gui.key_focus = p_control;
p_control->notification(Control::NOTIFICATION_FOCUS_ENTER);
p_control->update();
-
}
void Viewport::_gui_accept_event() {
- gui.key_event_accepted=true;
+ gui.key_event_accepted = true;
if (is_inside_tree())
get_tree()->set_input_as_handled();
}
-
-List<Control*>::Element* Viewport::_gui_show_modal(Control* p_control) {
+List<Control *>::Element *Viewport::_gui_show_modal(Control *p_control) {
gui.modal_stack.push_back(p_control);
if (gui.key_focus)
@@ -2539,77 +2363,67 @@ void Viewport::_gui_grab_click_focus(Control *p_control) {
if (gui.mouse_focus) {
-
- if (gui.mouse_focus==p_control)
+ if (gui.mouse_focus == p_control)
return;
InputEvent ie;
- ie.type=InputEvent::MOUSE_BUTTON;
- InputEventMouseButton &mb=ie.mouse_button;
+ ie.type = InputEvent::MOUSE_BUTTON;
+ InputEventMouseButton &mb = ie.mouse_button;
//send unclic
- Point2 click =gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
- mb.x=click.x;
- mb.y=click.y;
- mb.button_index=gui.mouse_focus_button;
- mb.pressed=false;
- gui.mouse_focus->call_deferred(SceneStringNames::get_singleton()->_gui_input,ie);
-
-
- gui.mouse_focus=p_control;
- gui.focus_inv_xform=gui.mouse_focus->get_global_transform_with_canvas().affine_inverse();
- click =gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
- mb.x=click.x;
- mb.y=click.y;
- mb.button_index=gui.mouse_focus_button;
- mb.pressed=true;
- gui.mouse_focus->call_deferred(SceneStringNames::get_singleton()->_gui_input,ie);
+ Point2 click = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
+ mb.x = click.x;
+ mb.y = click.y;
+ mb.button_index = gui.mouse_focus_button;
+ mb.pressed = false;
+ gui.mouse_focus->call_deferred(SceneStringNames::get_singleton()->_gui_input, ie);
+ gui.mouse_focus = p_control;
+ gui.focus_inv_xform = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse();
+ click = gui.mouse_focus->get_global_transform_with_canvas().affine_inverse().xform(gui.last_mouse_pos);
+ mb.x = click.x;
+ mb.y = click.y;
+ mb.button_index = gui.mouse_focus_button;
+ mb.pressed = true;
+ gui.mouse_focus->call_deferred(SceneStringNames::get_singleton()->_gui_input, ie);
}
}
-
///////////////////////////////
-
-void Viewport::input(const InputEvent& p_event) {
+void Viewport::input(const InputEvent &p_event) {
ERR_FAIL_COND(!is_inside_tree());
-
- get_tree()->_call_input_pause(input_group,"_input",p_event); //not a bug, must happen before GUI, order is _input -> gui input -> _unhandled input
+ get_tree()->_call_input_pause(input_group, "_input", p_event); //not a bug, must happen before GUI, order is _input -> gui input -> _unhandled input
_gui_input_event(p_event);
//get_tree()->call_group(SceneTree::GROUP_CALL_REVERSE|SceneTree::GROUP_CALL_REALTIME|SceneTree::GROUP_CALL_MULIILEVEL,gui_input_group,"_gui_input",p_event); //special one for GUI, as controls use their own process check
}
-void Viewport::unhandled_input(const InputEvent& p_event) {
+void Viewport::unhandled_input(const InputEvent &p_event) {
ERR_FAIL_COND(!is_inside_tree());
-
- get_tree()->_call_input_pause(unhandled_input_group,"_unhandled_input",p_event);
+ get_tree()->_call_input_pause(unhandled_input_group, "_unhandled_input", p_event);
//call_group(GROUP_CALL_REVERSE|GROUP_CALL_REALTIME|GROUP_CALL_MULIILEVEL,"unhandled_input","_unhandled_input",ev);
- if (!get_tree()->input_handled && p_event.type==InputEvent::KEY) {
- get_tree()->_call_input_pause(unhandled_key_input_group,"_unhandled_key_input",p_event);
+ if (!get_tree()->input_handled && p_event.type == InputEvent::KEY) {
+ get_tree()->_call_input_pause(unhandled_key_input_group, "_unhandled_key_input", p_event);
//call_group(GROUP_CALL_REVERSE|GROUP_CALL_REALTIME|GROUP_CALL_MULIILEVEL,"unhandled_key_input","_unhandled_key_input",ev);
}
-
if (physics_object_picking && !get_tree()->input_handled) {
- if (p_event.type==InputEvent::MOUSE_BUTTON || p_event.type==InputEvent::MOUSE_MOTION || p_event.type==InputEvent::SCREEN_DRAG || p_event.type==InputEvent::SCREEN_TOUCH) {
+ if (p_event.type == InputEvent::MOUSE_BUTTON || p_event.type == InputEvent::MOUSE_MOTION || p_event.type == InputEvent::SCREEN_DRAG || p_event.type == InputEvent::SCREEN_TOUCH) {
physics_picking_events.push_back(p_event);
}
}
-
}
void Viewport::set_use_own_world(bool p_world) {
- if (p_world==own_world.is_valid())
+ if (p_world == own_world.is_valid())
return;
-
if (is_inside_tree())
_propagate_exit_world(this);
@@ -2619,9 +2433,9 @@ void Viewport::set_use_own_world(bool p_world) {
#endif
if (!p_world)
- own_world=Ref<World>();
+ own_world = Ref<World>();
else
- own_world=Ref<World>( memnew( World ));
+ own_world = Ref<World>(memnew(World));
if (is_inside_tree())
_propagate_enter_world(this);
@@ -2634,12 +2448,10 @@ void Viewport::set_use_own_world(bool p_world) {
//propagate exit
if (is_inside_tree()) {
- VisualServer::get_singleton()->viewport_set_scenario(viewport,find_world()->get_scenario());
+ VisualServer::get_singleton()->viewport_set_scenario(viewport, find_world()->get_scenario());
}
_update_listener();
-
-
}
bool Viewport::is_using_own_world() const {
@@ -2647,35 +2459,29 @@ bool Viewport::is_using_own_world() const {
return own_world.is_valid();
}
-void Viewport::set_attach_to_screen_rect(const Rect2& p_rect) {
+void Viewport::set_attach_to_screen_rect(const Rect2 &p_rect) {
- VS::get_singleton()->viewport_attach_to_screen(viewport,p_rect);
- to_screen_rect=p_rect;
+ VS::get_singleton()->viewport_attach_to_screen(viewport, p_rect);
+ to_screen_rect = p_rect;
}
-Rect2 Viewport::get_attach_to_screen_rect() const{
+Rect2 Viewport::get_attach_to_screen_rect() const {
return to_screen_rect;
}
-
void Viewport::set_physics_object_picking(bool p_enable) {
- physics_object_picking=p_enable;
+ physics_object_picking = p_enable;
set_fixed_process(physics_object_picking);
if (!physics_object_picking)
physics_picking_events.clear();
-
-
}
-
Vector2 Viewport::get_camera_coords(const Vector2 &p_viewport_coords) const {
Transform2D xf = get_final_transform();
return xf.xform(p_viewport_coords);
-
-
}
Vector2 Viewport::get_camera_rect_size() const {
@@ -2683,10 +2489,8 @@ Vector2 Viewport::get_camera_rect_size() const {
return size;
}
-
bool Viewport::get_physics_object_picking() {
-
return physics_object_picking;
}
@@ -2696,7 +2500,7 @@ bool Viewport::gui_has_modal_stack() const {
}
void Viewport::set_disable_input(bool p_disable) {
- disable_input=p_disable;
+ disable_input = p_disable;
}
bool Viewport::is_input_disabled() const {
@@ -2705,8 +2509,8 @@ bool Viewport::is_input_disabled() const {
}
void Viewport::set_disable_3d(bool p_disable) {
- disable_3d=p_disable;
- VS::get_singleton()->viewport_set_disable_3d(viewport,p_disable);
+ disable_3d = p_disable;
+ VS::get_singleton()->viewport_set_disable_3d(viewport, p_disable);
}
bool Viewport::is_3d_disabled() const {
@@ -2719,7 +2523,7 @@ Variant Viewport::gui_get_drag_data() const {
}
Control *Viewport::get_modal_stack_top() const {
- return gui.modal_stack.size()?gui.modal_stack.back()->get():NULL;
+ return gui.modal_stack.size() ? gui.modal_stack.back()->get() : NULL;
}
String Viewport::get_configuration_warning() const {
@@ -2732,8 +2536,8 @@ String Viewport::get_configuration_warning() const {
return String();
}
-void Viewport::gui_reset_canvas_sort_index() {
- gui.canvas_sort_index=0;
+void Viewport::gui_reset_canvas_sort_index() {
+ gui.canvas_sort_index = 0;
}
int Viewport::gui_get_canvas_sort_index() {
@@ -2742,11 +2546,11 @@ int Viewport::gui_get_canvas_sort_index() {
void Viewport::set_msaa(MSAA p_msaa) {
- ERR_FAIL_INDEX(p_msaa,5);
- if (msaa==p_msaa)
+ ERR_FAIL_INDEX(p_msaa, 5);
+ if (msaa == p_msaa)
return;
- msaa=p_msaa;
- VS::get_singleton()->viewport_set_msaa(viewport,VS::ViewportMSAA(p_msaa));
+ msaa = p_msaa;
+ VS::get_singleton()->viewport_set_msaa(viewport, VS::ViewportMSAA(p_msaa));
}
Viewport::MSAA Viewport::get_msaa() const {
@@ -2756,260 +2560,241 @@ Viewport::MSAA Viewport::get_msaa() const {
void Viewport::set_hdr(bool p_hdr) {
- if (hdr==p_hdr)
+ if (hdr == p_hdr)
return;
- hdr=p_hdr;
- VS::get_singleton()->viewport_set_hdr(viewport,p_hdr);
-
+ hdr = p_hdr;
+ VS::get_singleton()->viewport_set_hdr(viewport, p_hdr);
}
-bool Viewport::get_hdr() const{
+bool Viewport::get_hdr() const {
return hdr;
}
-
-
void Viewport::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("set_size","size"), &Viewport::set_size);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &Viewport::set_size);
ClassDB::bind_method(D_METHOD("get_size"), &Viewport::get_size);
- ClassDB::bind_method(D_METHOD("set_world_2d","world_2d:World2D"), &Viewport::set_world_2d);
+ ClassDB::bind_method(D_METHOD("set_world_2d", "world_2d:World2D"), &Viewport::set_world_2d);
ClassDB::bind_method(D_METHOD("get_world_2d:World2D"), &Viewport::get_world_2d);
ClassDB::bind_method(D_METHOD("find_world_2d:World2D"), &Viewport::find_world_2d);
- ClassDB::bind_method(D_METHOD("set_world","world:World"), &Viewport::set_world);
+ ClassDB::bind_method(D_METHOD("set_world", "world:World"), &Viewport::set_world);
ClassDB::bind_method(D_METHOD("get_world:World"), &Viewport::get_world);
ClassDB::bind_method(D_METHOD("find_world:World"), &Viewport::find_world);
- ClassDB::bind_method(D_METHOD("set_canvas_transform","xform"), &Viewport::set_canvas_transform);
+ ClassDB::bind_method(D_METHOD("set_canvas_transform", "xform"), &Viewport::set_canvas_transform);
ClassDB::bind_method(D_METHOD("get_canvas_transform"), &Viewport::get_canvas_transform);
- ClassDB::bind_method(D_METHOD("set_global_canvas_transform","xform"), &Viewport::set_global_canvas_transform);
+ ClassDB::bind_method(D_METHOD("set_global_canvas_transform", "xform"), &Viewport::set_global_canvas_transform);
ClassDB::bind_method(D_METHOD("get_global_canvas_transform"), &Viewport::get_global_canvas_transform);
ClassDB::bind_method(D_METHOD("get_final_transform"), &Viewport::get_final_transform);
ClassDB::bind_method(D_METHOD("get_visible_rect"), &Viewport::get_visible_rect);
- ClassDB::bind_method(D_METHOD("set_transparent_background","enable"), &Viewport::set_transparent_background);
+ ClassDB::bind_method(D_METHOD("set_transparent_background", "enable"), &Viewport::set_transparent_background);
ClassDB::bind_method(D_METHOD("has_transparent_background"), &Viewport::has_transparent_background);
ClassDB::bind_method(D_METHOD("_parent_visibility_changed"), &Viewport::_parent_visibility_changed);
ClassDB::bind_method(D_METHOD("_parent_resized"), &Viewport::_parent_resized);
ClassDB::bind_method(D_METHOD("_vp_input"), &Viewport::_vp_input);
- ClassDB::bind_method(D_METHOD("_vp_input_text","text"), &Viewport::_vp_input_text);
+ ClassDB::bind_method(D_METHOD("_vp_input_text", "text"), &Viewport::_vp_input_text);
ClassDB::bind_method(D_METHOD("_vp_unhandled_input"), &Viewport::_vp_unhandled_input);
- ClassDB::bind_method(D_METHOD("set_size_override","enable","size","margin"), &Viewport::set_size_override,DEFVAL(Size2(-1,-1)),DEFVAL(Size2(0,0)));
+ ClassDB::bind_method(D_METHOD("set_size_override", "enable", "size", "margin"), &Viewport::set_size_override, DEFVAL(Size2(-1, -1)), DEFVAL(Size2(0, 0)));
ClassDB::bind_method(D_METHOD("get_size_override"), &Viewport::get_size_override);
ClassDB::bind_method(D_METHOD("is_size_override_enabled"), &Viewport::is_size_override_enabled);
- ClassDB::bind_method(D_METHOD("set_size_override_stretch","enabled"), &Viewport::set_size_override_stretch);
+ ClassDB::bind_method(D_METHOD("set_size_override_stretch", "enabled"), &Viewport::set_size_override_stretch);
ClassDB::bind_method(D_METHOD("is_size_override_stretch_enabled"), &Viewport::is_size_override_stretch_enabled);
ClassDB::bind_method(D_METHOD("queue_screen_capture"), &Viewport::queue_screen_capture);
ClassDB::bind_method(D_METHOD("get_screen_capture"), &Viewport::get_screen_capture);
-
- ClassDB::bind_method(D_METHOD("set_vflip","enable"), &Viewport::set_vflip);
+ ClassDB::bind_method(D_METHOD("set_vflip", "enable"), &Viewport::set_vflip);
ClassDB::bind_method(D_METHOD("get_vflip"), &Viewport::get_vflip);
- ClassDB::bind_method(D_METHOD("set_clear_on_new_frame","enable"), &Viewport::set_clear_on_new_frame);
+ ClassDB::bind_method(D_METHOD("set_clear_on_new_frame", "enable"), &Viewport::set_clear_on_new_frame);
ClassDB::bind_method(D_METHOD("get_clear_on_new_frame"), &Viewport::get_clear_on_new_frame);
ClassDB::bind_method(D_METHOD("clear"), &Viewport::clear);
- ClassDB::bind_method(D_METHOD("set_update_mode","mode"), &Viewport::set_update_mode);
+ ClassDB::bind_method(D_METHOD("set_update_mode", "mode"), &Viewport::set_update_mode);
ClassDB::bind_method(D_METHOD("get_update_mode"), &Viewport::get_update_mode);
- ClassDB::bind_method(D_METHOD("set_msaa","msaa"), &Viewport::set_msaa);
+ ClassDB::bind_method(D_METHOD("set_msaa", "msaa"), &Viewport::set_msaa);
ClassDB::bind_method(D_METHOD("get_msaa"), &Viewport::get_msaa);
- ClassDB::bind_method(D_METHOD("set_hdr","enable"), &Viewport::set_hdr);
+ ClassDB::bind_method(D_METHOD("set_hdr", "enable"), &Viewport::set_hdr);
ClassDB::bind_method(D_METHOD("get_hdr"), &Viewport::get_hdr);
ClassDB::bind_method(D_METHOD("get_texture:ViewportTexture"), &Viewport::get_texture);
- ClassDB::bind_method(D_METHOD("set_physics_object_picking","enable"), &Viewport::set_physics_object_picking);
+ ClassDB::bind_method(D_METHOD("set_physics_object_picking", "enable"), &Viewport::set_physics_object_picking);
ClassDB::bind_method(D_METHOD("get_physics_object_picking"), &Viewport::get_physics_object_picking);
ClassDB::bind_method(D_METHOD("get_viewport_rid"), &Viewport::get_viewport_rid);
- ClassDB::bind_method(D_METHOD("input","local_event"), &Viewport::input);
- ClassDB::bind_method(D_METHOD("unhandled_input","local_event"), &Viewport::unhandled_input);
+ ClassDB::bind_method(D_METHOD("input", "local_event"), &Viewport::input);
+ ClassDB::bind_method(D_METHOD("unhandled_input", "local_event"), &Viewport::unhandled_input);
ClassDB::bind_method(D_METHOD("update_worlds"), &Viewport::update_worlds);
- ClassDB::bind_method(D_METHOD("set_use_own_world","enable"), &Viewport::set_use_own_world);
+ ClassDB::bind_method(D_METHOD("set_use_own_world", "enable"), &Viewport::set_use_own_world);
ClassDB::bind_method(D_METHOD("is_using_own_world"), &Viewport::is_using_own_world);
ClassDB::bind_method(D_METHOD("get_camera:Camera"), &Viewport::get_camera);
- ClassDB::bind_method(D_METHOD("set_as_audio_listener","enable"), &Viewport::set_as_audio_listener);
- ClassDB::bind_method(D_METHOD("is_audio_listener","enable"), &Viewport::is_audio_listener);
+ ClassDB::bind_method(D_METHOD("set_as_audio_listener", "enable"), &Viewport::set_as_audio_listener);
+ ClassDB::bind_method(D_METHOD("is_audio_listener", "enable"), &Viewport::is_audio_listener);
- ClassDB::bind_method(D_METHOD("set_as_audio_listener_2d","enable"), &Viewport::set_as_audio_listener_2d);
- ClassDB::bind_method(D_METHOD("is_audio_listener_2d","enable"), &Viewport::is_audio_listener_2d);
- ClassDB::bind_method(D_METHOD("set_attach_to_screen_rect","rect"), &Viewport::set_attach_to_screen_rect);
+ ClassDB::bind_method(D_METHOD("set_as_audio_listener_2d", "enable"), &Viewport::set_as_audio_listener_2d);
+ ClassDB::bind_method(D_METHOD("is_audio_listener_2d", "enable"), &Viewport::is_audio_listener_2d);
+ ClassDB::bind_method(D_METHOD("set_attach_to_screen_rect", "rect"), &Viewport::set_attach_to_screen_rect);
ClassDB::bind_method(D_METHOD("get_mouse_pos"), &Viewport::get_mouse_pos);
- ClassDB::bind_method(D_METHOD("warp_mouse","to_pos"), &Viewport::warp_mouse);
+ ClassDB::bind_method(D_METHOD("warp_mouse", "to_pos"), &Viewport::warp_mouse);
ClassDB::bind_method(D_METHOD("gui_has_modal_stack"), &Viewport::gui_has_modal_stack);
ClassDB::bind_method(D_METHOD("gui_get_drag_data:Variant"), &Viewport::gui_get_drag_data);
- ClassDB::bind_method(D_METHOD("set_disable_input","disable"), &Viewport::set_disable_input);
+ ClassDB::bind_method(D_METHOD("set_disable_input", "disable"), &Viewport::set_disable_input);
ClassDB::bind_method(D_METHOD("is_input_disabled"), &Viewport::is_input_disabled);
- ClassDB::bind_method(D_METHOD("set_disable_3d","disable"), &Viewport::set_disable_3d);
+ ClassDB::bind_method(D_METHOD("set_disable_3d", "disable"), &Viewport::set_disable_3d);
ClassDB::bind_method(D_METHOD("is_3d_disabled"), &Viewport::is_3d_disabled);
ClassDB::bind_method(D_METHOD("_gui_show_tooltip"), &Viewport::_gui_show_tooltip);
ClassDB::bind_method(D_METHOD("_gui_remove_focus"), &Viewport::_gui_remove_focus);
- ClassDB::bind_method(D_METHOD("set_shadow_atlas_size","size"), &Viewport::set_shadow_atlas_size);
+ ClassDB::bind_method(D_METHOD("set_shadow_atlas_size", "size"), &Viewport::set_shadow_atlas_size);
ClassDB::bind_method(D_METHOD("get_shadow_atlas_size"), &Viewport::get_shadow_atlas_size);
- ClassDB::bind_method(D_METHOD("set_shadow_atlas_quadrant_subdiv","quadrant","subdiv"), &Viewport::set_shadow_atlas_quadrant_subdiv);
- ClassDB::bind_method(D_METHOD("get_shadow_atlas_quadrant_subdiv","quadrant"), &Viewport::get_shadow_atlas_quadrant_subdiv);
+ ClassDB::bind_method(D_METHOD("set_shadow_atlas_quadrant_subdiv", "quadrant", "subdiv"), &Viewport::set_shadow_atlas_quadrant_subdiv);
+ ClassDB::bind_method(D_METHOD("get_shadow_atlas_quadrant_subdiv", "quadrant"), &Viewport::get_shadow_atlas_quadrant_subdiv);
- ADD_PROPERTY( PropertyInfo(Variant::RECT2,"size"), "set_size", "get_size") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"own_world"), "set_use_own_world", "is_using_own_world") ;
- ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"world",PROPERTY_HINT_RESOURCE_TYPE,"World"), "set_world", "get_world") ;
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "size"), "set_size", "get_size");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "own_world"), "set_use_own_world", "is_using_own_world");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "world", PROPERTY_HINT_RESOURCE_TYPE, "World"), "set_world", "get_world");
//ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"world_2d",PROPERTY_HINT_RESOURCE_TYPE,"World2D"), "set_world_2d", "get_world_2d") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"transparent_bg"), "set_transparent_background", "has_transparent_background") ;
- ADD_GROUP("Rendering","");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"msaa",PROPERTY_HINT_ENUM,"Disabled,2x,4x,8x,16x"), "set_msaa", "get_msaa") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"hdr"), "set_hdr", "get_hdr") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"disable_3d"), "set_disable_3d", "is_3d_disabled") ;
- ADD_GROUP("Render Target","render_target_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"render_target_v_flip"), "set_vflip", "get_vflip") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"render_target_clear_on_new_frame"), "set_clear_on_new_frame", "get_clear_on_new_frame") ;
- ADD_PROPERTY( PropertyInfo(Variant::INT,"render_target_update_mode",PROPERTY_HINT_ENUM,"Disabled,Once,When Visible,Always"), "set_update_mode", "get_update_mode") ;
- ADD_GROUP("Audio Listener","audio_listener_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"audio_listener_enable_2d"), "set_as_audio_listener_2d", "is_audio_listener_2d") ;
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"audio_listener_enable_3d"), "set_as_audio_listener", "is_audio_listener") ;
- ADD_GROUP("Physics","physics_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"physics_object_picking"), "set_physics_object_picking", "get_physics_object_picking") ;
- ADD_GROUP("GUI","gui_");
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"gui_disable_input"), "set_disable_input", "is_input_disabled") ;
- ADD_GROUP("Shadow Atlas","shadow_atlas_");
- ADD_PROPERTY( PropertyInfo(Variant::INT,"shadow_atlas_size"), "set_shadow_atlas_size", "get_shadow_atlas_size") ;
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"shadow_atlas_quad_0",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv",0 );
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"shadow_atlas_quad_1",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv",1 );
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"shadow_atlas_quad_2",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv",2 );
- ADD_PROPERTYI( PropertyInfo(Variant::INT,"shadow_atlas_quad_3",PROPERTY_HINT_ENUM,"Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv",3 );
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "transparent_bg"), "set_transparent_background", "has_transparent_background");
+ ADD_GROUP("Rendering", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "msaa", PROPERTY_HINT_ENUM, "Disabled,2x,4x,8x,16x"), "set_msaa", "get_msaa");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "hdr"), "set_hdr", "get_hdr");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "disable_3d"), "set_disable_3d", "is_3d_disabled");
+ ADD_GROUP("Render Target", "render_target_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "render_target_v_flip"), "set_vflip", "get_vflip");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "render_target_clear_on_new_frame"), "set_clear_on_new_frame", "get_clear_on_new_frame");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "render_target_update_mode", PROPERTY_HINT_ENUM, "Disabled,Once,When Visible,Always"), "set_update_mode", "get_update_mode");
+ ADD_GROUP("Audio Listener", "audio_listener_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "audio_listener_enable_2d"), "set_as_audio_listener_2d", "is_audio_listener_2d");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "audio_listener_enable_3d"), "set_as_audio_listener", "is_audio_listener");
+ ADD_GROUP("Physics", "physics_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "physics_object_picking"), "set_physics_object_picking", "get_physics_object_picking");
+ ADD_GROUP("GUI", "gui_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "gui_disable_input"), "set_disable_input", "is_input_disabled");
+ ADD_GROUP("Shadow Atlas", "shadow_atlas_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "shadow_atlas_size"), "set_shadow_atlas_size", "get_shadow_atlas_size");
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "shadow_atlas_quad_0", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "shadow_atlas_quad_1", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "shadow_atlas_quad_2", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::INT, "shadow_atlas_quad_3", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), "set_shadow_atlas_quadrant_subdiv", "get_shadow_atlas_quadrant_subdiv", 3);
ADD_SIGNAL(MethodInfo("size_changed"));
- BIND_CONSTANT( UPDATE_DISABLED );
- BIND_CONSTANT( UPDATE_ONCE );
- BIND_CONSTANT( UPDATE_WHEN_VISIBLE );
- BIND_CONSTANT( UPDATE_ALWAYS );
+ BIND_CONSTANT(UPDATE_DISABLED);
+ BIND_CONSTANT(UPDATE_ONCE);
+ BIND_CONSTANT(UPDATE_WHEN_VISIBLE);
+ BIND_CONSTANT(UPDATE_ALWAYS);
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_1 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_4 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_16 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_64 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_256 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_1024 );
- BIND_CONSTANT( SHADOW_ATLAS_QUADRANT_SUBDIV_MAX );
-
- BIND_CONSTANT( MSAA_DISABLED );
- BIND_CONSTANT( MSAA_2X );
- BIND_CONSTANT( MSAA_4X );
- BIND_CONSTANT( MSAA_8X );
- BIND_CONSTANT( MSAA_16X );
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_DISABLED);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_1);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_4);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_16);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_64);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_256);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_1024);
+ BIND_CONSTANT(SHADOW_ATLAS_QUADRANT_SUBDIV_MAX);
+ BIND_CONSTANT(MSAA_DISABLED);
+ BIND_CONSTANT(MSAA_2X);
+ BIND_CONSTANT(MSAA_4X);
+ BIND_CONSTANT(MSAA_8X);
+ BIND_CONSTANT(MSAA_16X);
}
-
-
-
-
Viewport::Viewport() {
-
- world_2d = Ref<World2D>( memnew( World2D ));
+ world_2d = Ref<World2D>(memnew(World2D));
viewport = VisualServer::get_singleton()->viewport_create();
- texture_rid=VisualServer::get_singleton()->viewport_get_texture(viewport);
- texture_flags=0;
+ texture_rid = VisualServer::get_singleton()->viewport_get_texture(viewport);
+ texture_flags = 0;
default_texture.instance();
- default_texture->vp=const_cast<Viewport*>(this);
+ default_texture->vp = const_cast<Viewport *>(this);
viewport_textures.insert(default_texture.ptr());
//internal_listener = SpatialSoundServer::get_singleton()->listener_create();
- audio_listener=false;
+ audio_listener = false;
//internal_listener_2d = SpatialSound2DServer::get_singleton()->listener_create();
- audio_listener_2d=false;
- transparent_bg=false;
- parent=NULL;
- listener=NULL;
- camera=NULL;
- size_override=false;
- size_override_stretch=false;
- size_override_size=Size2(1,1);
- gen_mipmaps=false;
-
- vflip=false;
- clear_on_new_frame=true;
+ audio_listener_2d = false;
+ transparent_bg = false;
+ parent = NULL;
+ listener = NULL;
+ camera = NULL;
+ size_override = false;
+ size_override_stretch = false;
+ size_override_size = Size2(1, 1);
+ gen_mipmaps = false;
+
+ vflip = false;
+ clear_on_new_frame = true;
//clear=true;
- update_mode=UPDATE_WHEN_VISIBLE;
+ update_mode = UPDATE_WHEN_VISIBLE;
- physics_object_picking=false;
- physics_object_capture=0;
- physics_object_over=0;
- physics_last_mousepos=Vector2(1e20,1e20);
+ physics_object_picking = false;
+ physics_object_capture = 0;
+ physics_object_over = 0;
+ physics_last_mousepos = Vector2(1e20, 1e20);
- shadow_atlas_size=0;
- for(int i=0;i<4;i++) {
- shadow_atlas_quadrant_subdiv[i]=SHADOW_ATLAS_QUADRANT_SUBDIV_MAX;
+ shadow_atlas_size = 0;
+ for (int i = 0; i < 4; i++) {
+ shadow_atlas_quadrant_subdiv[i] = SHADOW_ATLAS_QUADRANT_SUBDIV_MAX;
}
- set_shadow_atlas_quadrant_subdiv(0,SHADOW_ATLAS_QUADRANT_SUBDIV_4);
- set_shadow_atlas_quadrant_subdiv(1,SHADOW_ATLAS_QUADRANT_SUBDIV_4);
- set_shadow_atlas_quadrant_subdiv(2,SHADOW_ATLAS_QUADRANT_SUBDIV_16);
- set_shadow_atlas_quadrant_subdiv(3,SHADOW_ATLAS_QUADRANT_SUBDIV_64);
-
+ set_shadow_atlas_quadrant_subdiv(0, SHADOW_ATLAS_QUADRANT_SUBDIV_4);
+ set_shadow_atlas_quadrant_subdiv(1, SHADOW_ATLAS_QUADRANT_SUBDIV_4);
+ set_shadow_atlas_quadrant_subdiv(2, SHADOW_ATLAS_QUADRANT_SUBDIV_16);
+ set_shadow_atlas_quadrant_subdiv(3, SHADOW_ATLAS_QUADRANT_SUBDIV_64);
- String id=itos(get_instance_ID());
- input_group = "_vp_input"+id;
- gui_input_group = "_vp_gui_input"+id;
- unhandled_input_group = "_vp_unhandled_input"+id;
- unhandled_key_input_group = "_vp_unhandled_key_input"+id;
+ String id = itos(get_instance_ID());
+ input_group = "_vp_input" + id;
+ gui_input_group = "_vp_gui_input" + id;
+ unhandled_input_group = "_vp_unhandled_input" + id;
+ unhandled_key_input_group = "_vp_unhandled_key_input" + id;
- disable_input=false;
- disable_3d=false;
+ disable_input = false;
+ disable_3d = false;
//window tooltip
gui.tooltip_timer = -1;
//gui.tooltip_timer->force_parent_owned();
- gui.tooltip_delay=GLOBAL_DEF("gui/timers/tooltip_delay_sec",0.7);
-
- gui.tooltip=NULL;
- gui.tooltip_label=NULL;
- gui.drag_preview=NULL;
- gui.drag_attempted=false;
- gui.canvas_sort_index=0;
-
-
- msaa=MSAA_DISABLED;
- hdr=false;
+ gui.tooltip_delay = GLOBAL_DEF("gui/timers/tooltip_delay_sec", 0.7);
+ gui.tooltip = NULL;
+ gui.tooltip_label = NULL;
+ gui.drag_preview = NULL;
+ gui.drag_attempted = false;
+ gui.canvas_sort_index = 0;
+ msaa = MSAA_DISABLED;
+ hdr = false;
}
-
Viewport::~Viewport() {
//erase itself from viewport textures
- for(Set<ViewportTexture*>::Element *E=viewport_textures.front();E;E=E->next()) {
- E->get()->vp=NULL;
+ for (Set<ViewportTexture *>::Element *E = viewport_textures.front(); E; E = E->next()) {
+ E->get()->vp = NULL;
}
- VisualServer::get_singleton()->free( viewport );
+ VisualServer::get_singleton()->free(viewport);
//SpatialSoundServer::get_singleton()->free(internal_listener);
//SpatialSound2DServer::get_singleton()->free(internal_listener_2d);
-
}
-
-
diff --git a/scene/main/viewport.h b/scene/main/viewport.h
index 59e34d5c62..3fc781c62c 100644
--- a/scene/main/viewport.h
+++ b/scene/main/viewport.h
@@ -29,11 +29,11 @@
#ifndef VIEWPORT_H
#define VIEWPORT_H
-#include "scene/main/node.h"
-#include "servers/visual_server.h"
-#include "scene/resources/world_2d.h"
#include "math_2d.h"
+#include "scene/main/node.h"
#include "scene/resources/texture.h"
+#include "scene/resources/world_2d.h"
+#include "servers/visual_server.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
@@ -50,23 +50,22 @@ class Viewport;
class ViewportTexture : public Texture {
- GDCLASS( ViewportTexture, Texture );
+ GDCLASS(ViewportTexture, Texture);
NodePath path;
-friend class Viewport;
- Viewport* vp;
-protected:
+ friend class Viewport;
+ Viewport *vp;
+protected:
static void _bind_methods();
-public:
- void set_viewport_path_in_scene(const NodePath& p_path);
+public:
+ void set_viewport_path_in_scene(const NodePath &p_path);
NodePath get_viewport_path_in_scene() const;
virtual void setup_local_to_scene();
-
virtual int get_width() const;
virtual int get_height() const;
virtual Size2 get_size() const;
@@ -79,14 +78,13 @@ public:
ViewportTexture();
~ViewportTexture();
-
};
class Viewport : public Node {
- GDCLASS( Viewport, Node );
-public:
+ GDCLASS(Viewport, Node);
+public:
enum UpdateMode {
UPDATE_DISABLED,
UPDATE_ONCE, //then goes to disabled
@@ -115,18 +113,15 @@ public:
};
private:
-
-friend class ViewportTexture;
-
-
+ friend class ViewportTexture;
Viewport *parent;
Listener *listener;
- Set<Listener*> listeners;
+ Set<Listener *> listeners;
Camera *camera;
- Set<Camera*> cameras;
+ Set<Camera *> cameras;
RID viewport;
RID current_canvas;
@@ -167,7 +162,7 @@ friend class ViewportTexture;
ObjectID physics_object_over;
Vector2 physics_last_mousepos;
void _test_new_mouseover(ObjectID new_collider);
- Map<ObjectID,uint64_t> physics_2d_mouseover;
+ Map<ObjectID, uint64_t> physics_2d_mouseover;
void _update_rect();
@@ -191,11 +186,9 @@ friend class ViewportTexture;
void _propagate_exit_world(Node *p_node);
void _propagate_viewport_notification(Node *p_node, int p_what);
-
void _update_stretch_transform();
void _update_global_transform();
-
bool disable_3d;
UpdateMode update_mode;
RID texture_rid;
@@ -208,8 +201,7 @@ friend class ViewportTexture;
bool hdr;
Ref<ViewportTexture> default_texture;
- Set<ViewportTexture*> viewport_textures;
-
+ Set<ViewportTexture *> viewport_textures;
struct GUI {
// info used when this is a window
@@ -230,31 +222,29 @@ friend class ViewportTexture;
Control *drag_preview;
float tooltip_timer;
float tooltip_delay;
- List<Control*> modal_stack;
+ List<Control *> modal_stack;
unsigned int cancelled_input_ID;
Transform2D focus_inv_xform;
bool subwindow_order_dirty;
- List<Control*> subwindows;
+ List<Control *> subwindows;
bool roots_order_dirty;
- List<Control*> roots;
+ List<Control *> roots;
int canvas_sort_index; //for sorting items with canvas as root
-
GUI();
} gui;
bool disable_input;
- void _gui_call_input(Control *p_control,const InputEvent& p_input);
+ void _gui_call_input(Control *p_control, const InputEvent &p_input);
void _gui_sort_subwindows();
void _gui_sort_roots();
void _gui_sort_modal_stack();
- Control* _gui_find_control(const Point2& p_global);
- Control* _gui_find_control_at_pos(CanvasItem* p_node,const Point2& p_global,const Transform2D& p_xform,Transform2D& r_inv_xform);
+ Control *_gui_find_control(const Point2 &p_global);
+ Control *_gui_find_control_at_pos(CanvasItem *p_node, const Point2 &p_global, const Transform2D &p_xform, Transform2D &r_inv_xform);
void _gui_input_event(InputEvent p_event);
-
void update_worlds();
_FORCE_INLINE_ Transform2D _get_input_pre_xform() const;
@@ -262,43 +252,40 @@ friend class ViewportTexture;
void _vp_enter_tree();
void _vp_exit_tree();
- void _vp_input(const InputEvent& p_ev);
- void _vp_input_text(const String& p_text);
- void _vp_unhandled_input(const InputEvent& p_ev);
- void _make_input_local(InputEvent& ev);
-
+ void _vp_input(const InputEvent &p_ev);
+ void _vp_input_text(const String &p_text);
+ void _vp_unhandled_input(const InputEvent &p_ev);
+ void _make_input_local(InputEvent &ev);
-friend class Control;
+ friend class Control;
- List<Control*>::Element* _gui_add_root_control(Control* p_control);
- List<Control*>::Element* _gui_add_subwindow_control(Control* p_control);
+ List<Control *>::Element *_gui_add_root_control(Control *p_control);
+ List<Control *>::Element *_gui_add_subwindow_control(Control *p_control);
void _gui_set_subwindow_order_dirty();
void _gui_set_root_order_dirty();
-
- void _gui_remove_modal_control(List<Control*>::Element *MI);
- void _gui_remove_from_modal_stack(List<Control*>::Element *MI,ObjectID p_prev_focus_owner);
- void _gui_remove_root_control(List<Control*>::Element *RI);
- void _gui_remove_subwindow_control(List<Control*>::Element* SI);
+ void _gui_remove_modal_control(List<Control *>::Element *MI);
+ void _gui_remove_from_modal_stack(List<Control *>::Element *MI, ObjectID p_prev_focus_owner);
+ void _gui_remove_root_control(List<Control *>::Element *RI);
+ void _gui_remove_subwindow_control(List<Control *>::Element *SI);
void _gui_cancel_tooltip();
void _gui_show_tooltip();
-
void _gui_remove_control(Control *p_control);
void _gui_hid_control(Control *p_control);
- void _gui_force_drag(Control *p_base,const Variant& p_data,Control *p_control);
- void _gui_set_drag_preview(Control *p_base,Control *p_control);
+ void _gui_force_drag(Control *p_base, const Variant &p_data, Control *p_control);
+ void _gui_set_drag_preview(Control *p_base, Control *p_control);
- bool _gui_is_modal_on_top(const Control* p_control);
- List<Control*>::Element* _gui_show_modal(Control* p_control);
+ bool _gui_is_modal_on_top(const Control *p_control);
+ List<Control *>::Element *_gui_show_modal(Control *p_control);
void _gui_remove_focus();
void _gui_unfocus_control(Control *p_control);
- bool _gui_control_has_focus(const Control* p_control);
- void _gui_control_grab_focus(Control* p_control);
+ bool _gui_control_has_focus(const Control *p_control);
+ void _gui_control_grab_focus(Control *p_control);
void _gui_grab_click_focus(Control *p_control);
void _gui_accept_event();
@@ -306,30 +293,29 @@ friend class Control;
Vector2 _get_window_offset() const;
- bool _gui_drop(Control *p_at_control,Point2 p_at_pos,bool p_just_check);
+ bool _gui_drop(Control *p_at_control, Point2 p_at_pos, bool p_just_check);
-friend class Listener;
+ friend class Listener;
void _listener_transform_changed_notify();
- void _listener_set(Listener* p_listener);
- bool _listener_add(Listener* p_listener); //true if first
- void _listener_remove(Listener* p_listener);
- void _listener_make_next_current(Listener* p_exclude);
+ void _listener_set(Listener *p_listener);
+ bool _listener_add(Listener *p_listener); //true if first
+ void _listener_remove(Listener *p_listener);
+ void _listener_make_next_current(Listener *p_exclude);
-friend class Camera;
+ friend class Camera;
void _camera_transform_changed_notify();
- void _camera_set(Camera* p_camera);
- bool _camera_add(Camera* p_camera); //true if first
- void _camera_remove(Camera* p_camera);
- void _camera_make_next_current(Camera* p_exclude);
-
+ void _camera_set(Camera *p_camera);
+ bool _camera_add(Camera *p_camera); //true if first
+ void _camera_remove(Camera *p_camera);
+ void _camera_make_next_current(Camera *p_exclude);
protected:
void _notification(int p_what);
static void _bind_methods();
-public:
- Listener* get_listener() const;
- Camera* get_camera() const;
+public:
+ Listener *get_listener() const;
+ Camera *get_camera() const;
void set_as_audio_listener(bool p_enable);
bool is_audio_listener() const;
@@ -337,26 +323,24 @@ public:
void set_as_audio_listener_2d(bool p_enable);
bool is_audio_listener_2d() const;
- void set_size(const Size2& p_size);
-
+ void set_size(const Size2 &p_size);
Size2 get_size() const;
Rect2 get_visible_rect() const;
RID get_viewport_rid() const;
- void set_world(const Ref<World>& p_world);
- void set_world_2d(const Ref<World2D>& p_world_2d);
+ void set_world(const Ref<World> &p_world);
+ void set_world_2d(const Ref<World2D> &p_world_2d);
Ref<World> get_world() const;
Ref<World> find_world() const;
Ref<World2D> get_world_2d() const;
Ref<World2D> find_world_2d() const;
-
- void set_canvas_transform(const Transform2D& p_transform);
+ void set_canvas_transform(const Transform2D &p_transform);
Transform2D get_canvas_transform() const;
- void set_global_canvas_transform(const Transform2D& p_transform);
+ void set_global_canvas_transform(const Transform2D &p_transform);
Transform2D get_global_canvas_transform() const;
Transform2D get_final_transform() const;
@@ -364,8 +348,7 @@ public:
void set_transparent_background(bool p_enable);
bool has_transparent_background() const;
-
- void set_size_override(bool p_enable,const Size2& p_size=Size2(-1,-1),const Vector2& p_margin=Vector2());
+ void set_size_override(bool p_enable, const Size2 &p_size = Size2(-1, -1), const Vector2 &p_margin = Vector2());
Size2 get_size_override() const;
bool is_size_override_enabled() const;
@@ -379,7 +362,6 @@ public:
bool get_clear_on_new_frame() const;
void clear();
-
void set_update_mode(UpdateMode p_mode);
UpdateMode get_update_mode() const;
Ref<ViewportTexture> get_texture() const;
@@ -387,7 +369,7 @@ public:
void set_shadow_atlas_size(int p_size);
int get_shadow_atlas_size() const;
- void set_shadow_atlas_quadrant_subdiv(int p_quadrant,ShadowAtlasQuadrantSubdiv p_subdiv);
+ void set_shadow_atlas_quadrant_subdiv(int p_quadrant, ShadowAtlasQuadrantSubdiv p_subdiv);
ShadowAtlasQuadrantSubdiv get_shadow_atlas_quadrant_subdiv(int p_quadrant) const;
void set_msaa(MSAA p_msaa);
@@ -396,7 +378,7 @@ public:
void set_hdr(bool p_hdr);
bool get_hdr() const;
- Vector2 get_camera_coords(const Vector2& p_viewport_coords) const;
+ Vector2 get_camera_coords(const Vector2 &p_viewport_coords) const;
Vector2 get_camera_rect_size() const;
void queue_screen_capture();
@@ -405,8 +387,8 @@ public:
void set_use_own_world(bool p_world);
bool is_using_own_world() const;
- void input(const InputEvent& p_event);
- void unhandled_input(const InputEvent& p_event);
+ void input(const InputEvent &p_event);
+ void unhandled_input(const InputEvent &p_event);
void set_disable_input(bool p_disable);
bool is_input_disabled() const;
@@ -414,11 +396,11 @@ public:
void set_disable_3d(bool p_disable);
bool is_3d_disabled() const;
- void set_attach_to_screen_rect(const Rect2& p_rect);
+ void set_attach_to_screen_rect(const Rect2 &p_rect);
Rect2 get_attach_to_screen_rect() const;
Vector2 get_mouse_pos() const;
- void warp_mouse(const Vector2& p_pos);
+ void warp_mouse(const Vector2 &p_pos);
void set_physics_object_picking(bool p_enable);
bool get_physics_object_picking();
@@ -433,15 +415,12 @@ public:
virtual String get_configuration_warning() const;
-
-
Viewport();
~Viewport();
-
};
-VARIANT_ENUM_CAST( Viewport::UpdateMode );
-VARIANT_ENUM_CAST( Viewport::ShadowAtlasQuadrantSubdiv );
-VARIANT_ENUM_CAST( Viewport::MSAA );
+VARIANT_ENUM_CAST(Viewport::UpdateMode);
+VARIANT_ENUM_CAST(Viewport::ShadowAtlasQuadrantSubdiv);
+VARIANT_ENUM_CAST(Viewport::MSAA);
#endif
diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp
index ffdc85301a..06dae328f4 100644
--- a/scene/register_scene_types.cpp
+++ b/scene/register_scene_types.cpp
@@ -27,96 +27,95 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "register_scene_types.h"
-#include "os/os.h"
#include "global_config.h"
+#include "os/os.h"
#include "scene/io/resource_format_image.h"
#include "scene/io/resource_format_wav.h"
//#include "scene/io/scene_format_script.h"
-#include "resources/default_theme/default_theme.h"
#include "class_db.h"
-#include "scene/main/canvas_layer.h"
-#include "scene/main/instance_placeholder.h"
-#include "scene/main/viewport.h"
-#include "scene/main/http_request.h"
-#include "scene/gui/control.h"
-#include "scene/gui/texture_progress.h"
+#include "resources/default_theme/default_theme.h"
+#include "scene/2d/light_2d.h"
+#include "scene/2d/light_occluder_2d.h"
+#include "scene/2d/particles_2d.h"
+#include "scene/2d/path_2d.h"
+#include "scene/gui/box_container.h"
#include "scene/gui/button.h"
-#include "scene/gui/link_button.h"
#include "scene/gui/button_array.h"
#include "scene/gui/button_group.h"
+#include "scene/gui/center_container.h"
+#include "scene/gui/check_box.h"
+#include "scene/gui/check_button.h"
+#include "scene/gui/color_picker.h"
+#include "scene/gui/color_rect.h"
+#include "scene/gui/control.h"
+#include "scene/gui/dialogs.h"
+#include "scene/gui/file_dialog.h"
+#include "scene/gui/graph_edit.h"
+#include "scene/gui/graph_node.h"
+#include "scene/gui/grid_container.h"
+#include "scene/gui/item_list.h"
#include "scene/gui/label.h"
#include "scene/gui/line_edit.h"
-#include "scene/gui/scroll_bar.h"
+#include "scene/gui/link_button.h"
+#include "scene/gui/margin_container.h"
+#include "scene/gui/menu_button.h"
+#include "scene/gui/option_button.h"
+#include "scene/gui/panel.h"
+#include "scene/gui/panel_container.h"
+#include "scene/gui/patch_9_rect.h"
+#include "scene/gui/popup_menu.h"
#include "scene/gui/progress_bar.h"
+#include "scene/gui/reference_rect.h"
+#include "scene/gui/rich_text_label.h"
+#include "scene/gui/scroll_bar.h"
+#include "scene/gui/scroll_container.h"
+#include "scene/gui/separator.h"
#include "scene/gui/slider.h"
-#include "scene/gui/popup_menu.h"
#include "scene/gui/spin_box.h"
-#include "scene/gui/option_button.h"
-#include "scene/gui/color_picker.h"
-#include "scene/gui/texture_rect.h"
-#include "scene/gui/color_rect.h"
-#include "scene/gui/patch_9_rect.h"
-#include "scene/gui/menu_button.h"
-#include "scene/gui/check_box.h"
-#include "scene/gui/check_button.h"
+#include "scene/gui/spin_box.h"
+#include "scene/gui/split_container.h"
#include "scene/gui/tab_container.h"
-#include "scene/gui/panel_container.h"
#include "scene/gui/tabs.h"
-#include "scene/gui/center_container.h"
-#include "scene/gui/scroll_container.h"
-#include "scene/gui/margin_container.h"
-#include "scene/gui/viewport_container.h"
-#include "scene/gui/panel.h"
-#include "scene/gui/spin_box.h"
-#include "scene/gui/file_dialog.h"
-#include "scene/gui/dialogs.h"
-#include "scene/gui/tree.h"
-#include "scene/gui/item_list.h"
#include "scene/gui/text_edit.h"
#include "scene/gui/texture_button.h"
-#include "scene/gui/separator.h"
-#include "scene/gui/rich_text_label.h"
-#include "scene/gui/box_container.h"
-#include "scene/gui/grid_container.h"
-#include "scene/gui/split_container.h"
-#include "scene/gui/video_player.h"
-#include "scene/gui/reference_rect.h"
-#include "scene/gui/graph_node.h"
-#include "scene/gui/graph_edit.h"
+#include "scene/gui/texture_progress.h"
+#include "scene/gui/texture_rect.h"
#include "scene/gui/tool_button.h"
+#include "scene/gui/tree.h"
+#include "scene/gui/video_player.h"
+#include "scene/gui/viewport_container.h"
+#include "scene/main/canvas_layer.h"
+#include "scene/main/http_request.h"
+#include "scene/main/instance_placeholder.h"
+#include "scene/main/viewport.h"
#include "scene/resources/audio_stream_sample.h"
#include "scene/resources/video_stream.h"
-#include "scene/2d/particles_2d.h"
-#include "scene/2d/path_2d.h"
-#include "scene/2d/light_2d.h"
-#include "scene/2d/light_occluder_2d.h"
-#include "scene/2d/canvas_item.h"
-#include "scene/2d/sprite.h"
#include "scene/2d/animated_sprite.h"
-#include "scene/2d/polygon_2d.h"
#include "scene/2d/back_buffer_copy.h"
-
+#include "scene/2d/canvas_item.h"
+#include "scene/2d/polygon_2d.h"
+#include "scene/2d/sprite.h"
#include "scene/2d/visibility_notifier_2d.h"
-#include "scene/2d/physics_body_2d.h"
-#include "scene/2d/ray_cast_2d.h"
-#include "scene/2d/joints_2d.h"
#include "scene/2d/area_2d.h"
#include "scene/2d/camera_2d.h"
-#include "scene/2d/collision_shape_2d.h"
#include "scene/2d/collision_polygon_2d.h"
+#include "scene/2d/collision_shape_2d.h"
+#include "scene/2d/joints_2d.h"
#include "scene/2d/parallax_background.h"
#include "scene/2d/parallax_layer.h"
+#include "scene/2d/physics_body_2d.h"
+#include "scene/2d/ray_cast_2d.h"
//#include "scene/2d/sound_player_2d.h"
//#include "scene/2d/sample_player_2d.h"
-#include "scene/2d/screen_button.h"
+#include "scene/2d/canvas_modulate.h"
+#include "scene/2d/navigation2d.h"
#include "scene/2d/remote_transform_2d.h"
+#include "scene/2d/screen_button.h"
#include "scene/2d/y_sort.h"
-#include "scene/2d/navigation2d.h"
-#include "scene/2d/canvas_modulate.h"
#include "scene/2d/position_2d.h"
#include "scene/2d/tile_map.h"
@@ -128,14 +127,13 @@
#include "scene/animation/animation_player.h"
#include "scene/animation/animation_tree_player.h"
#include "scene/animation/tween.h"
-#include "scene/main/scene_main_loop.h"
#include "scene/main/resource_preloader.h"
-#include "scene/resources/packed_scene.h"
#include "scene/main/scene_main_loop.h"
+#include "scene/main/scene_main_loop.h"
+#include "scene/resources/packed_scene.h"
-
-#include "scene/resources/surface_tool.h"
#include "scene/resources/mesh_data_tool.h"
+#include "scene/resources/surface_tool.h"
#include "scene/resources/dynamic_font.h"
#include "scene/resources/dynamic_font_stb.h"
@@ -145,34 +143,33 @@
#include "scene/audio/audio_player.h"
//#include "scene/audio/event_player.h"
//#include "scene/audio/sound_room_params.h"
-#include "scene/resources/sphere_shape.h"
-#include "scene/resources/ray_shape.h"
#include "scene/resources/box_shape.h"
#include "scene/resources/capsule_shape.h"
-#include "scene/resources/plane_shape.h"
-#include "scene/resources/convex_polygon_shape.h"
#include "scene/resources/concave_polygon_shape.h"
+#include "scene/resources/convex_polygon_shape.h"
+#include "scene/resources/plane_shape.h"
+#include "scene/resources/ray_shape.h"
+#include "scene/resources/sphere_shape.h"
-#include "scene/resources/shape_line_2d.h"
-#include "scene/resources/circle_shape_2d.h"
-#include "scene/resources/segment_shape_2d.h"
-#include "scene/resources/rectangle_shape_2d.h"
#include "scene/resources/capsule_shape_2d.h"
-#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/circle_shape_2d.h"
#include "scene/resources/concave_polygon_shape_2d.h"
+#include "scene/resources/convex_polygon_shape_2d.h"
+#include "scene/resources/rectangle_shape_2d.h"
+#include "scene/resources/segment_shape_2d.h"
+#include "scene/resources/shape_line_2d.h"
#include "scene/resources/mesh_library.h"
-
#include "scene/resources/polygon_path_finder.h"
//#include "scene/resources/sample.h"
//#include "scene/audio/sample_player.h"
-#include "scene/resources/texture.h"
-#include "scene/resources/sky_box.h"
#include "scene/resources/material.h"
#include "scene/resources/mesh.h"
#include "scene/resources/room.h"
+#include "scene/resources/sky_box.h"
+#include "scene/resources/texture.h"
#include "scene/resources/shader_graph.h"
@@ -181,19 +178,18 @@
//#include "scene/resources/sample_library.h"
//#include "scene/resources/audio_stream.h"
-#include "scene/resources/gibberish_stream.h"
#include "scene/resources/bit_mask.h"
#include "scene/resources/color_ramp.h"
+#include "scene/resources/gibberish_stream.h"
#include "scene/scene_string_names.h"
-
-#include "scene/3d/spatial.h"
-#include "scene/3d/remote_transform.h"
-#include "scene/3d/skeleton.h"
#include "scene/3d/bone_attachment.h"
-#include "scene/3d/room_instance.h"
#include "scene/3d/path.h"
+#include "scene/3d/remote_transform.h"
+#include "scene/3d/room_instance.h"
#include "scene/3d/scenario_fx.h"
+#include "scene/3d/skeleton.h"
+#include "scene/3d/spatial.h"
#include "scene/3d/visibility_notifier.h"
@@ -201,53 +197,51 @@
#include "scene/3d/camera.h"
#include "scene/3d/listener.h"
+#include "scene/3d/gi_probe.h"
#include "scene/3d/interpolated_camera.h"
-#include "scene/3d/position_3d.h"
-#include "scene/3d/test_cube.h"
-#include "scene/3d/mesh_instance.h"
-#include "scene/3d/quad.h"
#include "scene/3d/light.h"
-#include "scene/3d/reflection_probe.h"
-#include "scene/3d/gi_probe.h"
+#include "scene/3d/mesh_instance.h"
#include "scene/3d/particles.h"
+#include "scene/3d/physics_body.h"
#include "scene/3d/portal.h"
+#include "scene/3d/position_3d.h"
+#include "scene/3d/quad.h"
+#include "scene/3d/reflection_probe.h"
+#include "scene/3d/test_cube.h"
#include "scene/resources/environment.h"
-#include "scene/3d/physics_body.h"
-#include "scene/3d/vehicle_body.h"
-#include "scene/3d/body_shape.h"
#include "scene/3d/area.h"
-#include "scene/3d/physics_joint.h"
-#include "scene/3d/multimesh_instance.h"
#include "scene/3d/baked_light_instance.h"
-#include "scene/3d/ray_cast.h"
+#include "scene/3d/body_shape.h"
#include "scene/3d/immediate_geometry.h"
+#include "scene/3d/multimesh_instance.h"
+#include "scene/3d/physics_joint.h"
+#include "scene/3d/ray_cast.h"
#include "scene/3d/sprite_3d.h"
+#include "scene/3d/vehicle_body.h"
//#include "scene/3d/spatial_sample_player.h"
//#include "scene/3d/spatial_stream_player.h"
-#include "scene/3d/proximity_group.h"
-#include "scene/3d/navigation_mesh.h"
-#include "scene/3d/navigation.h"
#include "scene/3d/collision_polygon.h"
+#include "scene/3d/navigation.h"
+#include "scene/3d/navigation_mesh.h"
+#include "scene/3d/proximity_group.h"
#endif
#include "scene/resources/scene_format_text.h"
//static ResourceFormatLoaderWAV *resource_loader_wav=NULL;
-
#ifdef TOOLS_ENABLED
-
#endif
-static ResourceFormatLoaderTheme *resource_loader_theme=NULL;
+static ResourceFormatLoaderTheme *resource_loader_theme = NULL;
-static ResourceFormatSaverText *resource_saver_text=NULL;
-static ResourceFormatLoaderText *resource_loader_text=NULL;
+static ResourceFormatSaverText *resource_saver_text = NULL;
+static ResourceFormatLoaderText *resource_loader_text = NULL;
-static ResourceFormatLoaderDynamicFont *resource_loader_dynamic_font=NULL;
+static ResourceFormatLoaderDynamicFont *resource_loader_dynamic_font = NULL;
-static ResourceFormatLoaderStreamTexture *resource_loader_stream_texture=NULL;
+static ResourceFormatLoaderStreamTexture *resource_loader_stream_texture = NULL;
//static SceneStringNames *string_names;
@@ -261,31 +255,29 @@ void register_scene_types() {
//resource_loader_wav = memnew( ResourceFormatLoaderWAV );
//ResourceLoader::add_resource_format_loader( resource_loader_wav );
- resource_loader_dynamic_font = memnew( ResourceFormatLoaderDynamicFont );
- ResourceLoader::add_resource_format_loader( resource_loader_dynamic_font );
+ resource_loader_dynamic_font = memnew(ResourceFormatLoaderDynamicFont);
+ ResourceLoader::add_resource_format_loader(resource_loader_dynamic_font);
- resource_loader_stream_texture = memnew( ResourceFormatLoaderStreamTexture);
- ResourceLoader::add_resource_format_loader( resource_loader_stream_texture );
+ resource_loader_stream_texture = memnew(ResourceFormatLoaderStreamTexture);
+ ResourceLoader::add_resource_format_loader(resource_loader_stream_texture);
#ifdef TOOLS_ENABLED
- //scene first!
+//scene first!
#endif
- resource_loader_theme = memnew( ResourceFormatLoaderTheme );
- ResourceLoader::add_resource_format_loader( resource_loader_theme );
-
+ resource_loader_theme = memnew(ResourceFormatLoaderTheme);
+ ResourceLoader::add_resource_format_loader(resource_loader_theme);
- bool default_theme_hidpi=GLOBAL_DEF("gui/theme/use_hidpi",false);
- GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/use_hidpi",PropertyInfo(Variant::BOOL,"gui/theme/use_hidpi",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED));
- String theme_path = GLOBAL_DEF("gui/theme/custom","");
- GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/custom",PropertyInfo(Variant::STRING,"gui/theme/custom",PROPERTY_HINT_FILE,"*.tres,*.res",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED));
- String font_path = GLOBAL_DEF("gui/theme/custom_font","");
- GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/custom_font",PropertyInfo(Variant::STRING,"gui/theme/custom_font",PROPERTY_HINT_FILE,"*.tres,*.res,*.fnt",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_RESTART_IF_CHANGED));
+ bool default_theme_hidpi = GLOBAL_DEF("gui/theme/use_hidpi", false);
+ GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/use_hidpi", PropertyInfo(Variant::BOOL, "gui/theme/use_hidpi", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ String theme_path = GLOBAL_DEF("gui/theme/custom", "");
+ GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/custom", PropertyInfo(Variant::STRING, "gui/theme/custom", PROPERTY_HINT_FILE, "*.tres,*.res", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
+ String font_path = GLOBAL_DEF("gui/theme/custom_font", "");
+ GlobalConfig::get_singleton()->set_custom_property_info("gui/theme/custom_font", PropertyInfo(Variant::STRING, "gui/theme/custom_font", PROPERTY_HINT_FILE, "*.tres,*.res,*.fnt", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_RESTART_IF_CHANGED));
-
- if (theme_path!=String()) {
+ if (theme_path != String()) {
Ref<Theme> theme = ResourceLoader::load(theme_path);
if (theme.is_valid()) {
Theme::set_default(theme);
@@ -293,13 +285,12 @@ void register_scene_types() {
} else {
Ref<Font> font;
- if (font_path!=String()) {
- font=ResourceLoader::load(font_path);
+ if (font_path != String()) {
+ font = ResourceLoader::load(font_path);
}
- make_default_theme(default_theme_hidpi,font);
+ make_default_theme(default_theme_hidpi, font);
}
-
OS::get_singleton()->yield(); //may take time to init
ClassDB::register_class<Object>();
@@ -368,14 +359,13 @@ void register_scene_types() {
OS::get_singleton()->yield(); //may take time to init
-
ClassDB::register_virtual_class<ButtonArray>();
ClassDB::register_class<HButtonArray>();
ClassDB::register_class<VButtonArray>();
ClassDB::register_class<TextureProgress>();
ClassDB::register_class<ItemList>();
-#ifndef ADVANCED_GUI_DISABLED
+#ifndef ADVANCED_GUI_DISABLED
ClassDB::register_class<FileDialog>();
ClassDB::register_class<LineEdit>();
@@ -447,7 +437,6 @@ void register_scene_types() {
ClassDB::register_class<RigidBody>();
ClassDB::register_class<KinematicBody>();
-
ClassDB::register_class<VehicleBody>();
ClassDB::register_class<VehicleWheel>();
ClassDB::register_class<Area>();
@@ -478,13 +467,9 @@ void register_scene_types() {
OS::get_singleton()->yield(); //may take time to init
-
-
#endif
ClassDB::register_class<MeshLibrary>();
- AcceptDialog::set_swap_ok_cancel( GLOBAL_DEF("gui/common/swap_ok_cancel",bool(OS::get_singleton()->get_swap_ok_cancel())) );
-
-
+ AcceptDialog::set_swap_ok_cancel(GLOBAL_DEF("gui/common/swap_ok_cancel", bool(OS::get_singleton()->get_swap_ok_cancel())));
ClassDB::register_class<CanvasItemMaterial>();
ClassDB::register_virtual_class<CanvasItem>();
@@ -536,7 +521,7 @@ void register_scene_types() {
ClassDB::register_virtual_class<Shader>();
//ClassDB::register_virtual_type<ShaderGraph>();
ClassDB::register_class<CanvasItemShader>();
- //ClassDB::register_type<CanvasItemShaderGraph>();
+//ClassDB::register_type<CanvasItemShaderGraph>();
#ifndef _3D_DISABLED
ClassDB::register_class<Mesh>();
@@ -589,7 +574,7 @@ void register_scene_types() {
ClassDB::register_class<StyleBoxEmpty>();
ClassDB::register_class<StyleBoxTexture>();
- ClassDB::register_class<StyleBoxFlat>();
+ ClassDB::register_class<StyleBoxFlat>();
ClassDB::register_class<Theme>();
ClassDB::register_class<PolygonPathFinder>();
@@ -631,18 +616,17 @@ void register_scene_types() {
OS::get_singleton()->yield(); //may take time to init
+ resource_saver_text = memnew(ResourceFormatSaverText);
+ ResourceSaver::add_resource_format_saver(resource_saver_text, true);
- resource_saver_text = memnew( ResourceFormatSaverText );
- ResourceSaver::add_resource_format_saver(resource_saver_text,true);
-
- resource_loader_text = memnew( ResourceFormatLoaderText );
- ResourceLoader::add_resource_format_loader(resource_loader_text,true);
+ resource_loader_text = memnew(ResourceFormatLoaderText);
+ ResourceLoader::add_resource_format_loader(resource_loader_text, true);
- for(int i=0;i<20;i++) {
- GLOBAL_DEF("layer_names/2d_render/layer_"+itos(i+1),"");
- GLOBAL_DEF("layer_names/2d_physics/layer_"+itos(i+1),"");
- GLOBAL_DEF("layer_names/3d_render/layer_"+itos(i+1),"");
- GLOBAL_DEF("layer_names/3d_physics/layer_"+itos(i+1),"");
+ for (int i = 0; i < 20; i++) {
+ GLOBAL_DEF("layer_names/2d_render/layer_" + itos(i + 1), "");
+ GLOBAL_DEF("layer_names/2d_physics/layer_" + itos(i + 1), "");
+ GLOBAL_DEF("layer_names/3d_render/layer_" + itos(i + 1), "");
+ GLOBAL_DEF("layer_names/3d_physics/layer_" + itos(i + 1), "");
}
}
@@ -650,18 +634,15 @@ void unregister_scene_types() {
clear_default_theme();
-// memdelete( resource_loader_wav );
- memdelete( resource_loader_dynamic_font );
- memdelete( resource_loader_stream_texture );
-
+ // memdelete( resource_loader_wav );
+ memdelete(resource_loader_dynamic_font);
+ memdelete(resource_loader_stream_texture);
#ifdef TOOLS_ENABLED
-
#endif
-
- memdelete( resource_loader_theme );
+ memdelete(resource_loader_theme);
if (resource_saver_text) {
memdelete(resource_saver_text);
diff --git a/scene/resources/animation.cpp b/scene/resources/animation.cpp
index b743834e63..4fddd55e20 100644
--- a/scene/resources/animation.cpp
+++ b/scene/resources/animation.cpp
@@ -29,33 +29,32 @@
#include "animation.h"
#include "geometry.h"
+bool Animation::_set(const StringName &p_name, const Variant &p_value) {
-bool Animation::_set(const StringName& p_name, const Variant& p_value) {
+ String name = p_name;
- String name=p_name;
-
- if (name=="length")
+ if (name == "length")
set_length(p_value);
- else if (name=="loop")
+ else if (name == "loop")
set_loop(p_value);
- else if (name=="step")
+ else if (name == "step")
set_step(p_value);
else if (name.begins_with("tracks/")) {
- int track=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
+ int track = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
- if (tracks.size()==track && what=="type") {
+ if (tracks.size() == track && what == "type") {
- String type=p_value;
+ String type = p_value;
- if (type=="transform") {
+ if (type == "transform") {
add_track(TYPE_TRANSFORM);
- } else if (type=="value") {
+ } else if (type == "value") {
add_track(TYPE_VALUE);
- } else if (type=="method") {
+ } else if (type == "method") {
add_track(TYPE_METHOD);
} else {
@@ -66,23 +65,23 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) {
return true;
}
- ERR_FAIL_INDEX_V( track, tracks.size(),false );
+ ERR_FAIL_INDEX_V(track, tracks.size(), false);
- if (what=="path")
- track_set_path(track,p_value);
- else if (what=="interp")
- track_set_interpolation_type(track,InterpolationType(p_value.operator int()));
- else if (what=="loop_wrap")
- track_set_interpolation_loop_wrap(track,p_value);
- else if (what=="imported")
- track_set_imported(track,p_value);
- else if (what == "keys" || what=="key_values") {
+ if (what == "path")
+ track_set_path(track, p_value);
+ else if (what == "interp")
+ track_set_interpolation_type(track, InterpolationType(p_value.operator int()));
+ else if (what == "loop_wrap")
+ track_set_interpolation_loop_wrap(track, p_value);
+ else if (what == "imported")
+ track_set_imported(track, p_value);
+ else if (what == "keys" || what == "key_values") {
- if (track_get_type(track)==TYPE_TRANSFORM) {
+ if (track_get_type(track) == TYPE_TRANSFORM) {
- TransformTrack *tt = static_cast<TransformTrack*>(tracks[track]);
- PoolVector<float> values=p_value;
- int vcount=values.size();
+ TransformTrack *tt = static_cast<TransformTrack *>(tracks[track]);
+ PoolVector<float> values = p_value;
+ int vcount = values.size();
#if 0 // old compatibility hack
if ((vcount%11) == 0) {
@@ -121,137 +120,126 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) {
}
#endif
- ERR_FAIL_COND_V(vcount%12,false); // shuld be multiple of 11
+ ERR_FAIL_COND_V(vcount % 12, false); // shuld be multiple of 11
PoolVector<float>::Read r = values.read();
- tt->transforms.resize(vcount/12);
-
-
- for(int i=0;i<(vcount/12);i++) {
-
+ tt->transforms.resize(vcount / 12);
- TKey<TransformKey> &tk=tt->transforms[i];
- const float *ofs=&r[i*12];
- tk.time=ofs[0];
- tk.transition=ofs[1];
+ for (int i = 0; i < (vcount / 12); i++) {
- tk.value.loc.x=ofs[2];
- tk.value.loc.y=ofs[3];
- tk.value.loc.z=ofs[4];
+ TKey<TransformKey> &tk = tt->transforms[i];
+ const float *ofs = &r[i * 12];
+ tk.time = ofs[0];
+ tk.transition = ofs[1];
- tk.value.rot.x=ofs[5];
- tk.value.rot.y=ofs[6];
- tk.value.rot.z=ofs[7];
- tk.value.rot.w=ofs[8];
-
- tk.value.scale.x=ofs[9];
- tk.value.scale.y=ofs[10];
- tk.value.scale.z=ofs[11];
+ tk.value.loc.x = ofs[2];
+ tk.value.loc.y = ofs[3];
+ tk.value.loc.z = ofs[4];
+ tk.value.rot.x = ofs[5];
+ tk.value.rot.y = ofs[6];
+ tk.value.rot.z = ofs[7];
+ tk.value.rot.w = ofs[8];
+ tk.value.scale.x = ofs[9];
+ tk.value.scale.y = ofs[10];
+ tk.value.scale.z = ofs[11];
}
- } else if (track_get_type(track)==TYPE_VALUE) {
+ } else if (track_get_type(track) == TYPE_VALUE) {
- ValueTrack *vt = static_cast<ValueTrack*>(tracks[track]);
+ ValueTrack *vt = static_cast<ValueTrack *>(tracks[track]);
Dictionary d = p_value;
- ERR_FAIL_COND_V(!d.has("times"),false);
- ERR_FAIL_COND_V(!d.has("values"),false);
+ ERR_FAIL_COND_V(!d.has("times"), false);
+ ERR_FAIL_COND_V(!d.has("values"), false);
if (d.has("cont")) {
bool v = d["cont"];
- vt->update_mode=v?UPDATE_CONTINUOUS:UPDATE_DISCRETE;
+ vt->update_mode = v ? UPDATE_CONTINUOUS : UPDATE_DISCRETE;
}
if (d.has("update")) {
- int um =d["update"];
- if (um<0)
- um=0;
- else if (um>2)
- um=2;
- vt->update_mode=UpdateMode(um);
+ int um = d["update"];
+ if (um < 0)
+ um = 0;
+ else if (um > 2)
+ um = 2;
+ vt->update_mode = UpdateMode(um);
}
+ PoolVector<float> times = d["times"];
+ Array values = d["values"];
-
- PoolVector<float> times=d["times"];
- Array values=d["values"];
-
- ERR_FAIL_COND_V(times.size()!=values.size(),false);
+ ERR_FAIL_COND_V(times.size() != values.size(), false);
if (times.size()) {
- int valcount=times.size();
+ int valcount = times.size();
PoolVector<float>::Read rt = times.read();
vt->values.resize(valcount);
- for(int i=0;i<valcount;i++) {
+ for (int i = 0; i < valcount; i++) {
- vt->values[i].time=rt[i];
- vt->values[i].value=values[i];
+ vt->values[i].time = rt[i];
+ vt->values[i].value = values[i];
}
if (d.has("transitions")) {
PoolVector<float> transitions = d["transitions"];
- ERR_FAIL_COND_V(transitions.size()!=valcount,false);
+ ERR_FAIL_COND_V(transitions.size() != valcount, false);
PoolVector<float>::Read rtr = transitions.read();
+ for (int i = 0; i < valcount; i++) {
- for(int i=0;i<valcount;i++) {
-
- vt->values[i].transition=rtr[i];
+ vt->values[i].transition = rtr[i];
}
}
-
}
return true;
} else {
- while(track_get_key_count(track))
- track_remove_key(track,0); //well shouldn't be set anyway
+ while (track_get_key_count(track))
+ track_remove_key(track, 0); //well shouldn't be set anyway
Dictionary d = p_value;
- ERR_FAIL_COND_V(!d.has("times"),false);
- ERR_FAIL_COND_V(!d.has("values"),false);
+ ERR_FAIL_COND_V(!d.has("times"), false);
+ ERR_FAIL_COND_V(!d.has("values"), false);
- PoolVector<float> times=d["times"];
- Array values=d["values"];
+ PoolVector<float> times = d["times"];
+ Array values = d["values"];
- ERR_FAIL_COND_V(times.size()!=values.size(),false);
+ ERR_FAIL_COND_V(times.size() != values.size(), false);
if (times.size()) {
- int valcount=times.size();
+ int valcount = times.size();
PoolVector<float>::Read rt = times.read();
- for(int i=0;i<valcount;i++) {
+ for (int i = 0; i < valcount; i++) {
- track_insert_key(track,rt[i],values[i]);
+ track_insert_key(track, rt[i], values[i]);
}
if (d.has("transitions")) {
PoolVector<float> transitions = d["transitions"];
- ERR_FAIL_COND_V(transitions.size()!=valcount,false);
+ ERR_FAIL_COND_V(transitions.size() != valcount, false);
PoolVector<float>::Read rtr = transitions.read();
- for(int i=0;i<valcount;i++) {
+ for (int i = 0; i < valcount; i++) {
- track_set_key_transition(track,i,rtr[i]);
+ track_set_key_transition(track, i, rtr[i]);
}
}
-
}
-
-
}
} else
return false;
@@ -261,84 +249,81 @@ bool Animation::_set(const StringName& p_name, const Variant& p_value) {
return true;
}
+bool Animation::_get(const StringName &p_name, Variant &r_ret) const {
-bool Animation::_get(const StringName& p_name,Variant &r_ret) const {
+ String name = p_name;
- String name=p_name;
-
- if (name=="length")
- r_ret= length;
- else if (name=="loop")
- r_ret= loop;
- else if (name=="step")
- r_ret= step;
+ if (name == "length")
+ r_ret = length;
+ else if (name == "loop")
+ r_ret = loop;
+ else if (name == "step")
+ r_ret = step;
else if (name.begins_with("tracks/")) {
- int track=name.get_slicec('/',1).to_int();
- String what=name.get_slicec('/',2);
- ERR_FAIL_INDEX_V( track, tracks.size(), false );
- if (what=="type") {
-
+ int track = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
+ ERR_FAIL_INDEX_V(track, tracks.size(), false);
+ if (what == "type") {
switch (track_get_type(track)) {
- case TYPE_TRANSFORM: r_ret= "transform"; break;
- case TYPE_VALUE: r_ret= "value";break;
- case TYPE_METHOD: r_ret= "method";break;
+ case TYPE_TRANSFORM: r_ret = "transform"; break;
+ case TYPE_VALUE: r_ret = "value"; break;
+ case TYPE_METHOD: r_ret = "method"; break;
}
return true;
- } else if (what=="path")
- r_ret=track_get_path(track);
- else if (what=="interp")
+ } else if (what == "path")
+ r_ret = track_get_path(track);
+ else if (what == "interp")
r_ret = track_get_interpolation_type(track);
- else if (what=="loop_wrap")
+ else if (what == "loop_wrap")
r_ret = track_get_interpolation_loop_wrap(track);
- else if (what=="imported")
+ else if (what == "imported")
r_ret = track_is_imported(track);
- else if (what=="keys") {
+ else if (what == "keys") {
- if (track_get_type(track)==TYPE_TRANSFORM) {
+ if (track_get_type(track) == TYPE_TRANSFORM) {
PoolVector<real_t> keys;
- int kk=track_get_key_count(track);
- keys.resize(kk*12);
+ int kk = track_get_key_count(track);
+ keys.resize(kk * 12);
PoolVector<real_t>::Write w = keys.write();
- int idx=0;
- for(int i=0;i<track_get_key_count(track);i++) {
+ int idx = 0;
+ for (int i = 0; i < track_get_key_count(track); i++) {
Vector3 loc;
Quat rot;
Vector3 scale;
- transform_track_get_key(track,i,&loc,&rot,&scale);
-
- w[idx++]=track_get_key_time(track,i);
- w[idx++]=track_get_key_transition(track,i);
- w[idx++]=loc.x;
- w[idx++]=loc.y;
- w[idx++]=loc.z;
-
- w[idx++]=rot.x;
- w[idx++]=rot.y;
- w[idx++]=rot.z;
- w[idx++]=rot.w;
-
- w[idx++]=scale.x;
- w[idx++]=scale.y;
- w[idx++]=scale.z;
+ transform_track_get_key(track, i, &loc, &rot, &scale);
+
+ w[idx++] = track_get_key_time(track, i);
+ w[idx++] = track_get_key_transition(track, i);
+ w[idx++] = loc.x;
+ w[idx++] = loc.y;
+ w[idx++] = loc.z;
+
+ w[idx++] = rot.x;
+ w[idx++] = rot.y;
+ w[idx++] = rot.z;
+ w[idx++] = rot.w;
+
+ w[idx++] = scale.x;
+ w[idx++] = scale.y;
+ w[idx++] = scale.z;
}
w = PoolVector<real_t>::Write();
- r_ret=keys;
+ r_ret = keys;
return true;
- } else if (track_get_type(track)==TYPE_VALUE) {
-
+ } else if (track_get_type(track) == TYPE_VALUE) {
- const ValueTrack *vt = static_cast<const ValueTrack*>(tracks[track]);
+ const ValueTrack *vt = static_cast<const ValueTrack *>(tracks[track]);
Dictionary d;
@@ -346,82 +331,80 @@ bool Animation::_get(const StringName& p_name,Variant &r_ret) const {
PoolVector<float> key_transitions;
Array key_values;
- int kk=vt->values.size();
+ int kk = vt->values.size();
key_times.resize(kk);
key_transitions.resize(kk);
key_values.resize(kk);
- PoolVector<float>::Write wti=key_times.write();
- PoolVector<float>::Write wtr=key_transitions.write();
+ PoolVector<float>::Write wti = key_times.write();
+ PoolVector<float>::Write wtr = key_transitions.write();
- int idx=0;
+ int idx = 0;
const TKey<Variant> *vls = vt->values.ptr();
- for(int i=0;i<kk;i++) {
+ for (int i = 0; i < kk; i++) {
- wti[idx]=vls[i].time;
- wtr[idx]=vls[i].transition;
- key_values[idx]=vls[i].value;
+ wti[idx] = vls[i].time;
+ wtr[idx] = vls[i].transition;
+ key_values[idx] = vls[i].value;
idx++;
}
- wti=PoolVector<float>::Write();
- wtr=PoolVector<float>::Write();
+ wti = PoolVector<float>::Write();
+ wtr = PoolVector<float>::Write();
- d["times"]=key_times;
- d["transitions"]=key_transitions;
- d["values"]=key_values;
- if (track_get_type(track)==TYPE_VALUE) {
- d["update"]=value_track_get_update_mode(track);
+ d["times"] = key_times;
+ d["transitions"] = key_transitions;
+ d["values"] = key_values;
+ if (track_get_type(track) == TYPE_VALUE) {
+ d["update"] = value_track_get_update_mode(track);
}
- r_ret=d;
+ r_ret = d;
return true;
} else {
-
Dictionary d;
PoolVector<float> key_times;
PoolVector<float> key_transitions;
Array key_values;
- int kk=track_get_key_count(track);
+ int kk = track_get_key_count(track);
key_times.resize(kk);
key_transitions.resize(kk);
key_values.resize(kk);
- PoolVector<float>::Write wti=key_times.write();
- PoolVector<float>::Write wtr=key_transitions.write();
+ PoolVector<float>::Write wti = key_times.write();
+ PoolVector<float>::Write wtr = key_transitions.write();
- int idx=0;
- for(int i=0;i<track_get_key_count(track);i++) {
+ int idx = 0;
+ for (int i = 0; i < track_get_key_count(track); i++) {
- wti[idx]=track_get_key_time(track,i);
- wtr[idx]=track_get_key_transition(track,i);
- key_values[idx]=track_get_key_value(track,i);
+ wti[idx] = track_get_key_time(track, i);
+ wtr[idx] = track_get_key_transition(track, i);
+ key_values[idx] = track_get_key_value(track, i);
idx++;
}
- wti=PoolVector<float>::Write();
- wtr=PoolVector<float>::Write();
+ wti = PoolVector<float>::Write();
+ wtr = PoolVector<float>::Write();
- d["times"]=key_times;
- d["transitions"]=key_transitions;
- d["values"]=key_values;
- if (track_get_type(track)==TYPE_VALUE) {
- d["update"]=value_track_get_update_mode(track);
+ d["times"] = key_times;
+ d["transitions"] = key_transitions;
+ d["values"] = key_values;
+ if (track_get_type(track) == TYPE_VALUE) {
+ d["update"] = value_track_get_update_mode(track);
}
- r_ret=d;
+ r_ret = d;
return true;
-
}
} else
return false;
@@ -429,47 +412,45 @@ bool Animation::_get(const StringName& p_name,Variant &r_ret) const {
return false;
return true;
-
}
+void Animation::_get_property_list(List<PropertyInfo> *p_list) const {
-void Animation::_get_property_list( List<PropertyInfo> *p_list) const {
-
- p_list->push_back( PropertyInfo( Variant::REAL, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001"));
- p_list->push_back( PropertyInfo( Variant::BOOL, "loop" ));
- p_list->push_back( PropertyInfo( Variant::REAL, "step", PROPERTY_HINT_RANGE, "0,4096,0.001" ));
+ p_list->push_back(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001"));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "loop"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "step", PROPERTY_HINT_RANGE, "0,4096,0.001"));
- for (int i=0;i<tracks.size();i++) {
+ for (int i = 0; i < tracks.size(); i++) {
- p_list->push_back( PropertyInfo( Variant::STRING, "tracks/"+itos(i)+"/type", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::NODE_PATH, "tracks/"+itos(i)+"/path", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::INT, "tracks/"+itos(i)+"/interp", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::BOOL, "tracks/"+itos(i)+"/loop_wrap", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::BOOL, "tracks/"+itos(i)+"/imported", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
- p_list->push_back( PropertyInfo( Variant::ARRAY, "tracks/"+itos(i)+"/keys", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR) );
+ p_list->push_back(PropertyInfo(Variant::STRING, "tracks/" + itos(i) + "/type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tracks/" + itos(i) + "/path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::INT, "tracks/" + itos(i) + "/interp", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/loop_wrap", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/imported", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::ARRAY, "tracks/" + itos(i) + "/keys", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
}
}
-int Animation::add_track(TrackType p_type,int p_at_pos) {
+int Animation::add_track(TrackType p_type, int p_at_pos) {
- if (p_at_pos<0 || p_at_pos>=tracks.size())
- p_at_pos=tracks.size();
+ if (p_at_pos < 0 || p_at_pos >= tracks.size())
+ p_at_pos = tracks.size();
- switch( p_type ) {
+ switch (p_type) {
case TYPE_TRANSFORM: {
- TransformTrack *tt = memnew( TransformTrack );
- tracks.insert( p_at_pos,tt );
+ TransformTrack *tt = memnew(TransformTrack);
+ tracks.insert(p_at_pos, tt);
} break;
case TYPE_VALUE: {
- tracks.insert( p_at_pos,memnew( ValueTrack ) );
+ tracks.insert(p_at_pos, memnew(ValueTrack));
} break;
case TYPE_METHOD: {
- tracks.insert( p_at_pos,memnew( MethodTrack ) );
+ tracks.insert(p_at_pos, memnew(MethodTrack));
} break;
default: {
@@ -484,31 +465,31 @@ int Animation::add_track(TrackType p_type,int p_at_pos) {
void Animation::remove_track(int p_track) {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
_clear(tt->transforms);
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
_clear(vt->values);
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
_clear(mt->methods);
} break;
}
- memdelete( t );
+ memdelete(t);
tracks.remove(p_track);
emit_changed();
}
@@ -520,27 +501,26 @@ int Animation::get_track_count() const {
Animation::TrackType Animation::track_get_type(int p_track) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(), TYPE_TRANSFORM );
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), TYPE_TRANSFORM);
return tracks[p_track]->type;
}
-void Animation::track_set_path(int p_track,const NodePath& p_path) {
+void Animation::track_set_path(int p_track, const NodePath &p_path) {
ERR_FAIL_INDEX(p_track, tracks.size());
- tracks[p_track]->path=p_path;
+ tracks[p_track]->path = p_path;
emit_changed();
-
}
NodePath Animation::track_get_path(int p_track) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),NodePath());
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), NodePath());
return tracks[p_track]->path;
}
-int Animation::find_track(const NodePath& p_path) const {
+int Animation::find_track(const NodePath &p_path) const {
- for (int i=0; i<tracks.size(); i++) {
+ for (int i = 0; i < tracks.size(); i++) {
if (tracks[i]->path == p_path)
return i;
@@ -548,34 +528,30 @@ int Animation::find_track(const NodePath& p_path) const {
return -1;
};
-
-void Animation::track_set_interpolation_type(int p_track,InterpolationType p_interp) {
+void Animation::track_set_interpolation_type(int p_track, InterpolationType p_interp) {
ERR_FAIL_INDEX(p_track, tracks.size());
- ERR_FAIL_INDEX(p_interp,3);
- tracks[p_track]->interpolation=p_interp;
+ ERR_FAIL_INDEX(p_interp, 3);
+ tracks[p_track]->interpolation = p_interp;
emit_changed();
-
}
Animation::InterpolationType Animation::track_get_interpolation_type(int p_track) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),INTERPOLATION_NEAREST);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST);
return tracks[p_track]->interpolation;
}
-void Animation::track_set_interpolation_loop_wrap(int p_track,bool p_enable) {
+void Animation::track_set_interpolation_loop_wrap(int p_track, bool p_enable) {
ERR_FAIL_INDEX(p_track, tracks.size());
- tracks[p_track]->loop_wrap=p_enable;
+ tracks[p_track]->loop_wrap = p_enable;
emit_changed();
-
}
-bool Animation::track_get_interpolation_loop_wrap(int p_track) const{
+bool Animation::track_get_interpolation_loop_wrap(int p_track) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),INTERPOLATION_NEAREST);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST);
return tracks[p_track]->loop_wrap;
-
}
// transform
@@ -605,23 +581,22 @@ int Animation::_insert_pos(float p_time, T& p_keys) {
}
*/
-template<class T, class V>
-int Animation::_insert(float p_time, T& p_keys, const V& p_value) {
+template <class T, class V>
+int Animation::_insert(float p_time, T &p_keys, const V &p_value) {
- int idx=p_keys.size();
+ int idx = p_keys.size();
- while(true) {
+ while (true) {
-
- if (idx==0 || p_keys[idx-1].time < p_time) {
+ if (idx == 0 || p_keys[idx - 1].time < p_time) {
//condition for insertion.
- p_keys.insert(idx,p_value);
+ p_keys.insert(idx, p_value);
return idx;
- } else if (p_keys[idx-1].time == p_time) {
+ } else if (p_keys[idx - 1].time == p_time) {
// condition for replacing.
- p_keys[idx-1]=p_value;
- return idx-1;
+ p_keys[idx - 1] = p_value;
+ return idx - 1;
}
idx--;
@@ -630,82 +605,81 @@ int Animation::_insert(float p_time, T& p_keys, const V& p_value) {
return -1;
}
-template<class T>
-void Animation::_clear(T& p_keys) {
-
+template <class T>
+void Animation::_clear(T &p_keys) {
p_keys.clear();
}
-Error Animation::transform_track_get_key(int p_track, int p_key, Vector3* r_loc, Quat* r_rot, Vector3* r_scale) const {
+Error Animation::transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),ERR_INVALID_PARAMETER);
- Track *t=tracks[p_track];
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER);
+ Track *t = tracks[p_track];
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,ERR_INVALID_PARAMETER);
- ERR_FAIL_INDEX_V(p_key,tt->transforms.size(),ERR_INVALID_PARAMETER);
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_key, tt->transforms.size(), ERR_INVALID_PARAMETER);
if (r_loc)
- *r_loc=tt->transforms[p_key].value.loc;
+ *r_loc = tt->transforms[p_key].value.loc;
if (r_rot)
- *r_rot=tt->transforms[p_key].value.rot;
+ *r_rot = tt->transforms[p_key].value.rot;
if (r_scale)
- *r_scale=tt->transforms[p_key].value.scale;
+ *r_scale = tt->transforms[p_key].value.scale;
return OK;
}
-int Animation::transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat& p_rot, const Vector3& p_scale) {
+int Animation::transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot, const Vector3 &p_scale) {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),-1);
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,-1);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, -1);
- TransformTrack * tt = static_cast<TransformTrack*>(t);
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
TKey<TransformKey> tkey;
- tkey.time=p_time;
- tkey.value.loc=p_loc;
- tkey.value.rot=p_rot;
- tkey.value.scale=p_scale;
+ tkey.time = p_time;
+ tkey.value.loc = p_loc;
+ tkey.value.rot = p_rot;
+ tkey.value.scale = p_scale;
- int ret = _insert( p_time, tt->transforms, tkey );
+ int ret = _insert(p_time, tt->transforms, tkey);
emit_changed();
return ret;
}
void Animation::track_remove_key_at_pos(int p_track, float p_pos) {
- int idx = track_find_key(p_track,p_pos,true);
+ int idx = track_find_key(p_track, p_pos, true);
ERR_FAIL_COND(idx < 0);
- track_remove_key(p_track,idx);
+ track_remove_key(p_track, idx);
}
void Animation::track_remove_key(int p_track, int p_idx) {
- ERR_FAIL_INDEX(p_track,tracks.size());
- Track *t=tracks[p_track];
+ ERR_FAIL_INDEX(p_track, tracks.size());
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX(p_idx,tt->transforms.size());
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX(p_idx, tt->transforms.size());
tt->transforms.remove(p_idx);
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX(p_idx,vt->values.size());
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX(p_idx, vt->values.size());
vt->values.remove(p_idx);
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX(p_idx,mt->methods.size());
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX(p_idx, mt->methods.size());
mt->methods.remove(p_idx);
} break;
@@ -716,39 +690,39 @@ void Animation::track_remove_key(int p_track, int p_idx) {
int Animation::track_find_key(int p_track, float p_time, bool p_exact) const {
- ERR_FAIL_INDEX_V(p_track,tracks.size(),-1);
- Track *t=tracks[p_track];
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- int k = _find(tt->transforms,p_time);
- if (k<0 || k>=tt->transforms.size())
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ int k = _find(tt->transforms, p_time);
+ if (k < 0 || k >= tt->transforms.size())
return -1;
- if (tt->transforms[k].time!=p_time && p_exact)
+ if (tt->transforms[k].time != p_time && p_exact)
return -1;
return k;
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- int k = _find(vt->values,p_time);
- if (k<0 || k>=vt->values.size())
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ int k = _find(vt->values, p_time);
+ if (k < 0 || k >= vt->values.size())
return -1;
- if (vt->values[k].time!=p_time && p_exact)
+ if (vt->values[k].time != p_time && p_exact)
return -1;
return k;
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- int k = _find(mt->methods,p_time);
- if (k<0 || k>=mt->methods.size())
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ int k = _find(mt->methods, p_time);
+ if (k < 0 || k >= mt->methods.size())
return -1;
- if (mt->methods[k].time!=p_time && p_exact)
+ if (mt->methods[k].time != p_time && p_exact)
return -1;
return k;
@@ -758,65 +732,63 @@ int Animation::track_find_key(int p_track, float p_time, bool p_exact) const {
return -1;
}
-
-void Animation::track_insert_key(int p_track, float p_time, const Variant& p_value,float p_transition) {
+void Animation::track_insert_key(int p_track, float p_time, const Variant &p_value, float p_transition) {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
Dictionary d = p_value;
Vector3 loc;
if (d.has("loc"))
- loc=d["loc"];
+ loc = d["loc"];
Quat rot;
if (d.has("rot"))
- rot=d["rot"];
+ rot = d["rot"];
Vector3 scale;
if (d.has("scale"))
- scale=d["scale"];
+ scale = d["scale"];
- int idx = transform_track_insert_key(p_track,p_time,loc,rot,scale);
- track_set_key_transition(p_track,idx,p_transition);
+ int idx = transform_track_insert_key(p_track, p_time, loc, rot, scale);
+ track_set_key_transition(p_track, idx, p_transition);
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
- TKey<Variant> k;
- k.time=p_time;
- k.transition=p_transition;
- k.value=p_value;
- _insert( p_time, vt->values, k );
+ TKey<Variant> k;
+ k.time = p_time;
+ k.transition = p_transition;
+ k.value = p_value;
+ _insert(p_time, vt->values, k);
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
- ERR_FAIL_COND( p_value.get_type() != Variant::DICTIONARY );
+ ERR_FAIL_COND(p_value.get_type() != Variant::DICTIONARY);
- Dictionary d=p_value;
- ERR_FAIL_COND(!d.has("method") || d["method"].get_type()!=Variant::STRING);
+ Dictionary d = p_value;
+ ERR_FAIL_COND(!d.has("method") || d["method"].get_type() != Variant::STRING);
ERR_FAIL_COND(!d.has("args") || !d["args"].is_array());
MethodKey k;
- k.time=p_time;
- k.transition=p_transition;
- k.method=d["method"];
- k.params=d["args"];
+ k.time = p_time;
+ k.transition = p_transition;
+ k.method = d["method"];
+ k.params = d["args"];
- _insert( p_time, mt->methods, k );
+ _insert(p_time, mt->methods, k);
} break;
-
}
emit_changed();
@@ -824,25 +796,25 @@ void Animation::track_insert_key(int p_track, float p_time, const Variant& p_val
int Animation::track_get_key_count(int p_track) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),-1);
- Track *t=tracks[p_track];
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
return tt->transforms.size();
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
return vt->values.size();
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
return mt->methods.size();
} break;
}
@@ -853,40 +825,39 @@ int Animation::track_get_key_count(int p_track) const {
Variant Animation::track_get_key_value(int p_track, int p_key_idx) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), Variant());
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), Variant() );
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), Variant());
Dictionary d;
- d["loc"]=tt->transforms[p_key_idx].value.loc;
- d["rot"]=tt->transforms[p_key_idx].value.rot;
- d["scale"]=tt->transforms[p_key_idx].value.scale;
+ d["loc"] = tt->transforms[p_key_idx].value.loc;
+ d["rot"] = tt->transforms[p_key_idx].value.rot;
+ d["scale"] = tt->transforms[p_key_idx].value.scale;
return d;
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), Variant() );
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), Variant());
return vt->values[p_key_idx].value;
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), Variant() );
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), Variant());
Dictionary d;
- d["method"]=mt->methods[p_key_idx].method;
- d["args"]=mt->methods[p_key_idx].params;
+ d["method"] = mt->methods[p_key_idx].method;
+ d["args"] = mt->methods[p_key_idx].params;
return d;
} break;
-
}
ERR_FAIL_V(Variant());
@@ -895,452 +866,431 @@ Variant Animation::track_get_key_value(int p_track, int p_key_idx) const {
float Animation::track_get_key_time(int p_track, int p_key_idx) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), -1 );
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1);
return tt->transforms[p_key_idx].time;
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), -1 );
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1);
return vt->values[p_key_idx].time;
-
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), -1 );
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1);
return mt->methods[p_key_idx].time;
-
} break;
}
ERR_FAIL_V(-1);
-
}
float Animation::track_get_key_transition(int p_track, int p_key_idx) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), -1);
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, tt->transforms.size(), -1 );
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1);
return tt->transforms[p_key_idx].transition;
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, vt->values.size(), -1 );
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1);
return vt->values[p_key_idx].transition;
-
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX_V( p_key_idx, mt->methods.size(), -1 );
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1);
return mt->methods[p_key_idx].transition;
-
} break;
}
ERR_FAIL_V(0);
-
}
-void Animation::track_set_key_value(int p_track, int p_key_idx,const Variant& p_value) {
+void Animation::track_set_key_value(int p_track, int p_key_idx, const Variant &p_value) {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, tt->transforms.size());
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, tt->transforms.size());
Dictionary d = p_value;
if (d.has("loc"))
- tt->transforms[p_key_idx].value.loc=d["loc"];
+ tt->transforms[p_key_idx].value.loc = d["loc"];
if (d.has("rot"))
- tt->transforms[p_key_idx].value.rot=d["rot"];
+ tt->transforms[p_key_idx].value.rot = d["rot"];
if (d.has("scale"))
- tt->transforms[p_key_idx].value.scale=d["scale"];
+ tt->transforms[p_key_idx].value.scale = d["scale"];
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, vt->values.size());
- vt->values[p_key_idx].value=p_value;
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, vt->values.size());
+ vt->values[p_key_idx].value = p_value;
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, mt->methods.size());
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, mt->methods.size());
Dictionary d = p_value;
if (d.has("method"))
- mt->methods[p_key_idx].method=d["method"];
+ mt->methods[p_key_idx].method = d["method"];
if (d.has("args"))
- mt->methods[p_key_idx].params=d["args"];
+ mt->methods[p_key_idx].params = d["args"];
} break;
}
-
}
-void Animation::track_set_key_transition(int p_track, int p_key_idx,float p_transition) {
+void Animation::track_set_key_transition(int p_track, int p_key_idx, float p_transition) {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
+ Track *t = tracks[p_track];
- switch(t->type) {
+ switch (t->type) {
case TYPE_TRANSFORM: {
- TransformTrack * tt = static_cast<TransformTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, tt->transforms.size());
- tt->transforms[p_key_idx].transition=p_transition;
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, tt->transforms.size());
+ tt->transforms[p_key_idx].transition = p_transition;
} break;
case TYPE_VALUE: {
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, vt->values.size());
- vt->values[p_key_idx].transition=p_transition;
-
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, vt->values.size());
+ vt->values[p_key_idx].transition = p_transition;
} break;
case TYPE_METHOD: {
- MethodTrack * mt = static_cast<MethodTrack*>(t);
- ERR_FAIL_INDEX( p_key_idx, mt->methods.size());
- mt->methods[p_key_idx].transition=p_transition;
-
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
+ ERR_FAIL_INDEX(p_key_idx, mt->methods.size());
+ mt->methods[p_key_idx].transition = p_transition;
} break;
}
-
}
+template <class K>
+int Animation::_find(const Vector<K> &p_keys, float p_time) const {
-
-template<class K>
-int Animation::_find( const Vector<K>& p_keys, float p_time) const {
-
- int len=p_keys.size();
- if (len==0)
+ int len = p_keys.size();
+ if (len == 0)
return -2;
int low = 0;
- int high = len -1;
+ int high = len - 1;
int middle;
- const K* keys =&p_keys[0];
+ const K *keys = &p_keys[0];
- while( low <= high ) {
+ while (low <= high) {
- middle = ( low + high ) / 2;
+ middle = (low + high) / 2;
- if( p_time == keys[ middle ].time ) { //match
+ if (p_time == keys[middle].time) { //match
return middle;
- } else if( p_time < keys[middle].time )
+ } else if (p_time < keys[middle].time)
high = middle - 1; //search low end of array
else
low = middle + 1; //search high end of array
}
- if (keys[middle].time>p_time)
+ if (keys[middle].time > p_time)
middle--;
return middle;
}
-Animation::TransformKey Animation::_interpolate( const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, float p_c) const {
+Animation::TransformKey Animation::_interpolate(const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, float p_c) const {
TransformKey ret;
- ret.loc=_interpolate(p_a.loc,p_b.loc,p_c);
- ret.rot=_interpolate(p_a.rot,p_b.rot,p_c);
- ret.scale=_interpolate(p_a.scale,p_b.scale,p_c);
+ ret.loc = _interpolate(p_a.loc, p_b.loc, p_c);
+ ret.rot = _interpolate(p_a.rot, p_b.rot, p_c);
+ ret.scale = _interpolate(p_a.scale, p_b.scale, p_c);
return ret;
}
-Vector3 Animation::_interpolate( const Vector3& p_a, const Vector3& p_b, float p_c) const {
+Vector3 Animation::_interpolate(const Vector3 &p_a, const Vector3 &p_b, float p_c) const {
- return p_a.linear_interpolate(p_b,p_c);
+ return p_a.linear_interpolate(p_b, p_c);
}
-Quat Animation::_interpolate( const Quat& p_a, const Quat& p_b, float p_c) const {
+Quat Animation::_interpolate(const Quat &p_a, const Quat &p_b, float p_c) const {
- return p_a.slerp(p_b,p_c);
+ return p_a.slerp(p_b, p_c);
}
-Variant Animation::_interpolate( const Variant& p_a, const Variant& p_b, float p_c) const {
+Variant Animation::_interpolate(const Variant &p_a, const Variant &p_b, float p_c) const {
Variant dst;
- Variant::interpolate(p_a,p_b,p_c,dst);
+ Variant::interpolate(p_a, p_b, p_c, dst);
return dst;
}
+float Animation::_interpolate(const float &p_a, const float &p_b, float p_c) const {
-float Animation::_interpolate( const float& p_a, const float& p_b, float p_c) const {
-
- return p_a*(1.0-p_c) + p_b*p_c;
+ return p_a * (1.0 - p_c) + p_b * p_c;
}
-Animation::TransformKey Animation::_cubic_interpolate( const Animation::TransformKey& p_pre_a, const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, const Animation::TransformKey& p_post_b,float p_c) const {
-
+Animation::TransformKey Animation::_cubic_interpolate(const Animation::TransformKey &p_pre_a, const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, const Animation::TransformKey &p_post_b, float p_c) const {
Animation::TransformKey tk;
- tk.loc = p_a.loc.cubic_interpolate(p_b.loc,p_pre_a.loc,p_post_b.loc,p_c);
- tk.scale = p_a.scale.cubic_interpolate(p_b.scale,p_pre_a.scale,p_post_b.scale,p_c);
- tk.rot = p_a.rot.cubic_slerp(p_b.rot,p_pre_a.rot,p_post_b.rot,p_c);
+ tk.loc = p_a.loc.cubic_interpolate(p_b.loc, p_pre_a.loc, p_post_b.loc, p_c);
+ tk.scale = p_a.scale.cubic_interpolate(p_b.scale, p_pre_a.scale, p_post_b.scale, p_c);
+ tk.rot = p_a.rot.cubic_slerp(p_b.rot, p_pre_a.rot, p_post_b.rot, p_c);
return tk;
-
}
-Vector3 Animation::_cubic_interpolate( const Vector3& p_pre_a,const Vector3& p_a, const Vector3& p_b,const Vector3& p_post_b, float p_c) const {
+Vector3 Animation::_cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, float p_c) const {
- return p_a.cubic_interpolate(p_b,p_pre_a,p_post_b,p_c);
+ return p_a.cubic_interpolate(p_b, p_pre_a, p_post_b, p_c);
}
-Quat Animation::_cubic_interpolate( const Quat& p_pre_a,const Quat& p_a, const Quat& p_b,const Quat& p_post_b, float p_c) const {
+Quat Animation::_cubic_interpolate(const Quat &p_pre_a, const Quat &p_a, const Quat &p_b, const Quat &p_post_b, float p_c) const {
- return p_a.cubic_slerp(p_b,p_pre_a,p_post_b,p_c);
+ return p_a.cubic_slerp(p_b, p_pre_a, p_post_b, p_c);
}
-Variant Animation::_cubic_interpolate( const Variant& p_pre_a,const Variant& p_a, const Variant& p_b, const Variant& p_post_b,float p_c) const {
+Variant Animation::_cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, float p_c) const {
- Variant::Type type_a=p_a.get_type();
- Variant::Type type_b=p_b.get_type();
- Variant::Type type_pa=p_pre_a.get_type();
- Variant::Type type_pb=p_post_b.get_type();
+ Variant::Type type_a = p_a.get_type();
+ Variant::Type type_b = p_b.get_type();
+ Variant::Type type_pa = p_pre_a.get_type();
+ Variant::Type type_pb = p_post_b.get_type();
//make int and real play along
- uint32_t vformat=1<<type_a;
- vformat|=1<<type_b;
- vformat|=1<<type_pa;
- vformat|=1<<type_pb;
+ uint32_t vformat = 1 << type_a;
+ vformat |= 1 << type_b;
+ vformat |= 1 << type_pa;
+ vformat |= 1 << type_pb;
- if (vformat==((1<<Variant::INT)|(1<<Variant::REAL)) || vformat==(1<<Variant::REAL)) {
+ if (vformat == ((1 << Variant::INT) | (1 << Variant::REAL)) || vformat == (1 << Variant::REAL)) {
//mix of real and int
- real_t p0=p_pre_a;
- real_t p1=p_a;
- real_t p2=p_b;
- real_t p3=p_post_b;
+ real_t p0 = p_pre_a;
+ real_t p1 = p_a;
+ real_t p2 = p_b;
+ real_t p3 = p_post_b;
float t = p_c;
float t2 = t * t;
float t3 = t2 * t;
- return
- 0.5f * ( ( p1 * 2.0f) +
- ( -p0 + p2 ) * t +
- ( 2.0f * p0 - 5.0f * p1 + 4 * p2 - p3 ) * t2 +
- ( -p0 + 3.0f * p1 - 3.0f * p2 + p3 ) * t3 );
-
+ return 0.5f * ((p1 * 2.0f) +
+ (-p0 + p2) * t +
+ (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 +
+ (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
} else if ((vformat & (vformat - 1))) {
return p_a; //can't interpolate, mix of types
}
- switch(type_a) {
+ switch (type_a) {
case Variant::VECTOR2: {
- Vector2 a=p_a;
- Vector2 b=p_b;
- Vector2 pa=p_pre_a;
- Vector2 pb=p_post_b;
+ Vector2 a = p_a;
+ Vector2 b = p_b;
+ Vector2 pa = p_pre_a;
+ Vector2 pb = p_post_b;
- return a.cubic_interpolate(b,pa,pb,p_c);
+ return a.cubic_interpolate(b, pa, pb, p_c);
} break;
case Variant::RECT2: {
- Rect2 a=p_a;
- Rect2 b=p_b;
- Rect2 pa=p_pre_a;
- Rect2 pb=p_post_b;
+ Rect2 a = p_a;
+ Rect2 b = p_b;
+ Rect2 pa = p_pre_a;
+ Rect2 pb = p_post_b;
return Rect2(
- a.pos.cubic_interpolate(b.pos,pa.pos,pb.pos,p_c),
- a.size.cubic_interpolate(b.size,pa.size,pb.size,p_c)
- );
+ a.pos.cubic_interpolate(b.pos, pa.pos, pb.pos, p_c),
+ a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c));
} break;
case Variant::VECTOR3: {
- Vector3 a=p_a;
- Vector3 b=p_b;
- Vector3 pa=p_pre_a;
- Vector3 pb=p_post_b;
+ Vector3 a = p_a;
+ Vector3 b = p_b;
+ Vector3 pa = p_pre_a;
+ Vector3 pb = p_post_b;
- return a.cubic_interpolate(b,pa,pb,p_c);
+ return a.cubic_interpolate(b, pa, pb, p_c);
} break;
case Variant::QUAT: {
- Quat a=p_a;
- Quat b=p_b;
- Quat pa=p_pre_a;
- Quat pb=p_post_b;
+ Quat a = p_a;
+ Quat b = p_b;
+ Quat pa = p_pre_a;
+ Quat pb = p_post_b;
- return a.cubic_slerp(b,pa,pb,p_c);
+ return a.cubic_slerp(b, pa, pb, p_c);
} break;
case Variant::RECT3: {
- Rect3 a=p_a;
- Rect3 b=p_b;
- Rect3 pa=p_pre_a;
- Rect3 pb=p_post_b;
+ Rect3 a = p_a;
+ Rect3 b = p_b;
+ Rect3 pa = p_pre_a;
+ Rect3 pb = p_post_b;
return Rect3(
- a.pos.cubic_interpolate(b.pos,pa.pos,pb.pos,p_c),
- a.size.cubic_interpolate(b.size,pa.size,pb.size,p_c)
- );
+ a.pos.cubic_interpolate(b.pos, pa.pos, pb.pos, p_c),
+ a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c));
} break;
default: {
- return _interpolate(p_a,p_b,p_c);
+ return _interpolate(p_a, p_b, p_c);
}
}
return Variant();
}
-float Animation::_cubic_interpolate( const float& p_pre_a,const float& p_a, const float& p_b, const float& p_post_b, float p_c) const {
+float Animation::_cubic_interpolate(const float &p_pre_a, const float &p_a, const float &p_b, const float &p_post_b, float p_c) const {
- return _interpolate(p_a,p_b,p_c);
+ return _interpolate(p_a, p_b, p_c);
}
-template<class T>
-T Animation::_interpolate( const Vector< TKey<T> >& p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap,bool *p_ok) const {
+template <class T>
+T Animation::_interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const {
- int len=_find( p_keys, length )+1; // try to find last key (there may be more past the end)
+ int len = _find(p_keys, length) + 1; // try to find last key (there may be more past the end)
- if (len<=0) {
+ if (len <= 0) {
// (-1 or -2 returned originally) (plus one above)
// meaning no keys, or only key time is larger than length
if (p_ok)
- *p_ok=false;
+ *p_ok = false;
return T();
- } else if (len==1) { // one key found (0+1), return it
+ } else if (len == 1) { // one key found (0+1), return it
if (p_ok)
- *p_ok=true;
+ *p_ok = true;
return p_keys[0].value;
}
- int idx=_find(p_keys, p_time);
+ int idx = _find(p_keys, p_time);
- ERR_FAIL_COND_V( idx==-2, T());
+ ERR_FAIL_COND_V(idx == -2, T());
if (p_ok)
- *p_ok=true;
+ *p_ok = true;
- int next=0;
- float c=0;
+ int next = 0;
+ float c = 0;
// prepare for all cases of interpolation
if (loop && p_loop_wrap) {
- // loop
- if (idx>=0) {
+ // loop
+ if (idx >= 0) {
- if ((idx+1) < len) {
+ if ((idx + 1) < len) {
- next=idx+1;
- float delta=p_keys[next].time - p_keys[idx].time;
- float from=p_time-p_keys[idx].time;
+ next = idx + 1;
+ float delta = p_keys[next].time - p_keys[idx].time;
+ float from = p_time - p_keys[idx].time;
- if (Math::absf(delta)>CMP_EPSILON)
- c=from/delta;
+ if (Math::absf(delta) > CMP_EPSILON)
+ c = from / delta;
else
- c=0;
+ c = 0;
} else {
- next=0;
- float delta=(length - p_keys[idx].time) + p_keys[next].time;
- float from=p_time-p_keys[idx].time;
+ next = 0;
+ float delta = (length - p_keys[idx].time) + p_keys[next].time;
+ float from = p_time - p_keys[idx].time;
- if (Math::absf(delta)>CMP_EPSILON)
- c=from/delta;
+ if (Math::absf(delta) > CMP_EPSILON)
+ c = from / delta;
else
- c=0;
-
+ c = 0;
}
} else {
// on loop, behind first key
- idx=len-1;
- next=0;
- float endtime=(length - p_keys[idx].time);
- if (endtime<0) // may be keys past the end
- endtime=0;
- float delta=endtime + p_keys[next].time;
- float from=endtime+p_time;
-
- if (Math::absf(delta)>CMP_EPSILON)
- c=from/delta;
+ idx = len - 1;
+ next = 0;
+ float endtime = (length - p_keys[idx].time);
+ if (endtime < 0) // may be keys past the end
+ endtime = 0;
+ float delta = endtime + p_keys[next].time;
+ float from = endtime + p_time;
+
+ if (Math::absf(delta) > CMP_EPSILON)
+ c = from / delta;
else
- c=0;
+ c = 0;
}
} else { // no loop
- if (idx>=0) {
+ if (idx >= 0) {
- if ((idx+1) < len) {
+ if ((idx + 1) < len) {
- next=idx+1;
- float delta=p_keys[next].time - p_keys[idx].time;
- float from=p_time - p_keys[idx].time;
+ next = idx + 1;
+ float delta = p_keys[next].time - p_keys[idx].time;
+ float from = p_time - p_keys[idx].time;
- if (Math::absf(delta)>CMP_EPSILON)
- c=from/delta;
+ if (Math::absf(delta) > CMP_EPSILON)
+ c = from / delta;
else
- c=0;
+ c = 0;
} else {
- next=idx;
+ next = idx;
}
- } else if (idx<0) {
+ } else if (idx < 0) {
- idx=next=0;
+ idx = next = 0;
}
-
}
float tr = p_keys[idx].transition;
- if (tr==0 || idx==next) {
+ if (tr == 0 || idx == next) {
// don't interpolate if not needed
return p_keys[idx].value;
}
- if (tr!=1.0) {
+ if (tr != 1.0) {
- c = Math::ease(c,tr);
+ c = Math::ease(c, tr);
}
- switch(p_interp) {
+ switch (p_interp) {
case INTERPOLATION_NEAREST: {
@@ -1351,66 +1301,59 @@ T Animation::_interpolate( const Vector< TKey<T> >& p_keys, float p_time, Inter
return _interpolate(p_keys[idx].value, p_keys[next].value, c);
} break;
case INTERPOLATION_CUBIC: {
- int pre = idx-1;
- if (pre<0)
- pre=0;
- int post = next+1;
- if (post>=len)
- post=next;
+ int pre = idx - 1;
+ if (pre < 0)
+ pre = 0;
+ int post = next + 1;
+ if (post >= len)
+ post = next;
-
- return _cubic_interpolate(p_keys[pre].value,p_keys[idx].value, p_keys[next].value,p_keys[post].value, c);
+ return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c);
} break;
default: return p_keys[idx].value;
}
// do a barrel roll
-
-
}
+Error Animation::transform_track_interpolate(int p_track, float p_time, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const {
-Error Animation::transform_track_interpolate(int p_track, float p_time, Vector3 * r_loc, Quat *r_rot, Vector3 *r_scale) const {
-
- ERR_FAIL_INDEX_V(p_track, tracks.size(),ERR_INVALID_PARAMETER);
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V(t->type!=TYPE_TRANSFORM,ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER);
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER);
- TransformTrack * tt = static_cast<TransformTrack*>(t);
+ TransformTrack *tt = static_cast<TransformTrack *>(t);
bool ok;
- TransformKey tk = _interpolate( tt->transforms, p_time, tt->interpolation, tt->loop_wrap, &ok );
+ TransformKey tk = _interpolate(tt->transforms, p_time, tt->interpolation, tt->loop_wrap, &ok);
if (!ok) // ??
return ERR_UNAVAILABLE;
if (r_loc)
- *r_loc=tk.loc;
+ *r_loc = tk.loc;
if (r_rot)
- *r_rot=tk.rot;
+ *r_rot = tk.rot;
if (r_scale)
- *r_scale=tk.scale;
+ *r_scale = tk.scale;
return OK;
-
}
Variant Animation::value_track_interpolate(int p_track, float p_time) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),0);
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V(t->type!=TYPE_VALUE, Variant());
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), 0);
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_VALUE, Variant());
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
bool ok;
-
- Variant res = _interpolate( vt->values, p_time, vt->update_mode==UPDATE_CONTINUOUS?vt->interpolation:INTERPOLATION_NEAREST,vt->loop_wrap, &ok );
-
+ Variant res = _interpolate(vt->values, p_time, vt->update_mode == UPDATE_CONTINUOUS ? vt->interpolation : INTERPOLATION_NEAREST, vt->loop_wrap, &ok);
if (ok) {
@@ -1420,219 +1363,203 @@ Variant Animation::value_track_interpolate(int p_track, float p_time) const {
return Variant();
}
-void Animation::_value_track_get_key_indices_in_range(const ValueTrack * vt, float from_time, float to_time,List<int> *p_indices) const {
+void Animation::_value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const {
- if (from_time!=length && to_time==length)
- to_time=length*1.01; //include a little more if at the end
- int to=_find( vt->values, to_time);
+ if (from_time != length && to_time == length)
+ to_time = length * 1.01; //include a little more if at the end
+ int to = _find(vt->values, to_time);
// can't really send the events == time, will be sent in the next frame.
// if event>=len then it will probably never be requested by the anim player.
- if (to>=0 && vt->values[to].time>=to_time)
+ if (to >= 0 && vt->values[to].time >= to_time)
to--;
- if (to<0)
+ if (to < 0)
return; // not bother
- int from=_find( vt->values, from_time);
+ int from = _find(vt->values, from_time);
// position in the right first event.+
- if (from<0 || vt->values[from].time<from_time)
+ if (from < 0 || vt->values[from].time < from_time)
from++;
- int max=vt->values.size();
+ int max = vt->values.size();
- for (int i=from;i<=to;i++) {
+ for (int i = from; i <= to; i++) {
- ERR_CONTINUE( i<0 || i>=max); // shouldn't happen
+ ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen
p_indices->push_back(i);
}
-
-
}
-void Animation::value_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const {
+void Animation::value_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
- ERR_FAIL_COND( t->type != TYPE_VALUE );
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND(t->type != TYPE_VALUE);
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
- float from_time=p_time-p_delta;
- float to_time=p_time;
+ float from_time = p_time - p_delta;
+ float to_time = p_time;
- if (from_time>to_time)
- SWAP(from_time,to_time);
+ if (from_time > to_time)
+ SWAP(from_time, to_time);
if (loop) {
- from_time=Math::fposmod(from_time,length);
- to_time=Math::fposmod(to_time,length);
+ from_time = Math::fposmod(from_time, length);
+ to_time = Math::fposmod(to_time, length);
- if (from_time>to_time) {
+ if (from_time > to_time) {
// handle loop by splitting
- _value_track_get_key_indices_in_range(vt,length-from_time,length,p_indices);
- _value_track_get_key_indices_in_range(vt,0,to_time,p_indices);
+ _value_track_get_key_indices_in_range(vt, length - from_time, length, p_indices);
+ _value_track_get_key_indices_in_range(vt, 0, to_time, p_indices);
return;
}
} else {
- if (from_time<0)
- from_time=0;
- if (from_time>length)
- from_time=length;
-
- if (to_time<0)
- to_time=0;
- if (to_time>length)
- to_time=length;
-
+ if (from_time < 0)
+ from_time = 0;
+ if (from_time > length)
+ from_time = length;
+ if (to_time < 0)
+ to_time = 0;
+ if (to_time > length)
+ to_time = length;
}
- _value_track_get_key_indices_in_range(vt,from_time,to_time,p_indices);
-
-
+ _value_track_get_key_indices_in_range(vt, from_time, to_time, p_indices);
}
void Animation::value_track_set_update_mode(int p_track, UpdateMode p_mode) {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
- ERR_FAIL_COND( t->type != TYPE_VALUE );
- ERR_FAIL_INDEX(p_mode,3);
-
- ValueTrack * vt = static_cast<ValueTrack*>(t);
- vt->update_mode=p_mode;
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND(t->type != TYPE_VALUE);
+ ERR_FAIL_INDEX(p_mode, 3);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
+ vt->update_mode = p_mode;
}
Animation::UpdateMode Animation::value_track_get_update_mode(int p_track) const {
ERR_FAIL_INDEX_V(p_track, tracks.size(), UPDATE_CONTINUOUS);
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V( t->type != TYPE_VALUE, UPDATE_CONTINUOUS );
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_VALUE, UPDATE_CONTINUOUS);
- ValueTrack * vt = static_cast<ValueTrack*>(t);
+ ValueTrack *vt = static_cast<ValueTrack *>(t);
return vt->update_mode;
-
}
+void Animation::_method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const {
-void Animation::_method_track_get_key_indices_in_range(const MethodTrack * mt, float from_time, float to_time,List<int> *p_indices) const {
-
- if (from_time!=length && to_time==length)
- to_time=length*1.01; //include a little more if at the end
-
+ if (from_time != length && to_time == length)
+ to_time = length * 1.01; //include a little more if at the end
- int to=_find( mt->methods, to_time);
+ int to = _find(mt->methods, to_time);
// can't really send the events == time, will be sent in the next frame.
// if event>=len then it will probably never be requested by the anim player.
- if (to>=0 && mt->methods[to].time>=to_time)
+ if (to >= 0 && mt->methods[to].time >= to_time)
to--;
- if (to<0)
+ if (to < 0)
return; // not bother
- int from=_find( mt->methods, from_time);
+ int from = _find(mt->methods, from_time);
// position in the right first event.+
- if (from<0 || mt->methods[from].time<from_time)
+ if (from < 0 || mt->methods[from].time < from_time)
from++;
- int max=mt->methods.size();
+ int max = mt->methods.size();
- for (int i=from;i<=to;i++) {
+ for (int i = from; i <= to; i++) {
- ERR_CONTINUE( i<0 || i>=max); // shouldn't happen
+ ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen
p_indices->push_back(i);
}
-
}
-void Animation::method_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const {
+void Animation::method_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const {
ERR_FAIL_INDEX(p_track, tracks.size());
- Track *t=tracks[p_track];
- ERR_FAIL_COND( t->type != TYPE_METHOD );
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND(t->type != TYPE_METHOD);
- MethodTrack * mt = static_cast<MethodTrack*>(t);
+ MethodTrack *mt = static_cast<MethodTrack *>(t);
- float from_time=p_time-p_delta;
- float to_time=p_time;
+ float from_time = p_time - p_delta;
+ float to_time = p_time;
- if (from_time>to_time)
- SWAP(from_time,to_time);
+ if (from_time > to_time)
+ SWAP(from_time, to_time);
if (loop) {
if (from_time > length || from_time < 0)
- from_time=Math::fposmod(from_time,length);
+ from_time = Math::fposmod(from_time, length);
if (to_time > length || to_time < 0)
- to_time=Math::fposmod(to_time,length);
+ to_time = Math::fposmod(to_time, length);
- if (from_time>to_time) {
+ if (from_time > to_time) {
// handle loop by splitting
- _method_track_get_key_indices_in_range(mt,from_time,length,p_indices);
- _method_track_get_key_indices_in_range(mt,0,to_time,p_indices);
+ _method_track_get_key_indices_in_range(mt, from_time, length, p_indices);
+ _method_track_get_key_indices_in_range(mt, 0, to_time, p_indices);
return;
}
} else {
- if (from_time<0)
- from_time=0;
- if (from_time>length)
- from_time=length;
-
- if (to_time<0)
- to_time=0;
- if (to_time>length)
- to_time=length;
+ if (from_time < 0)
+ from_time = 0;
+ if (from_time > length)
+ from_time = length;
+ if (to_time < 0)
+ to_time = 0;
+ if (to_time > length)
+ to_time = length;
}
- _method_track_get_key_indices_in_range(mt,from_time,to_time,p_indices);
-
-
+ _method_track_get_key_indices_in_range(mt, from_time, to_time, p_indices);
}
-Vector<Variant> Animation::method_track_get_params(int p_track,int p_key_idx) const {
+Vector<Variant> Animation::method_track_get_params(int p_track, int p_key_idx) const {
- ERR_FAIL_INDEX_V(p_track, tracks.size(),Vector<Variant>());
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V( t->type != TYPE_METHOD, Vector<Variant>() );
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector<Variant>());
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_METHOD, Vector<Variant>());
- MethodTrack * pm = static_cast<MethodTrack*>(t);
+ MethodTrack *pm = static_cast<MethodTrack *>(t);
- ERR_FAIL_INDEX_V( p_key_idx, pm->methods.size(), Vector<Variant>() );
+ ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), Vector<Variant>());
- const MethodKey& mk=pm->methods[p_key_idx];
+ const MethodKey &mk = pm->methods[p_key_idx];
return mk.params;
}
-StringName Animation::method_track_get_name(int p_track,int p_key_idx) const {
-
- ERR_FAIL_INDEX_V(p_track, tracks.size(),StringName());
- Track *t=tracks[p_track];
- ERR_FAIL_COND_V( t->type != TYPE_METHOD, StringName() );
+StringName Animation::method_track_get_name(int p_track, int p_key_idx) const {
- MethodTrack * pm = static_cast<MethodTrack*>(t);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), StringName());
+ Track *t = tracks[p_track];
+ ERR_FAIL_COND_V(t->type != TYPE_METHOD, StringName());
- ERR_FAIL_INDEX_V( p_key_idx, pm->methods.size(), StringName() );
+ MethodTrack *pm = static_cast<MethodTrack *>(t);
- return pm->methods[ p_key_idx ].method;
+ ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), StringName());
+ return pm->methods[p_key_idx].method;
}
-
void Animation::set_length(float p_length) {
- ERR_FAIL_COND( length<0 );
- length=p_length;
+ ERR_FAIL_COND(length < 0);
+ length = p_length;
emit_changed();
}
float Animation::get_length() const {
@@ -1642,7 +1569,7 @@ float Animation::get_length() const {
void Animation::set_loop(bool p_enabled) {
- loop=p_enabled;
+ loop = p_enabled;
emit_changed();
}
bool Animation::has_loop() const {
@@ -1652,286 +1579,271 @@ bool Animation::has_loop() const {
void Animation::track_move_up(int p_track) {
+ if (p_track >= 0 && p_track < (tracks.size() - 1)) {
- if (p_track>=0 && p_track<(tracks.size()-1)) {
-
- SWAP( tracks[p_track], tracks[p_track+1] );
+ SWAP(tracks[p_track], tracks[p_track + 1]);
}
emit_changed();
}
-void Animation::track_set_imported(int p_track,bool p_imported) {
+void Animation::track_set_imported(int p_track, bool p_imported) {
- ERR_FAIL_INDEX(p_track,tracks.size());
- tracks[p_track]->imported=p_imported;
+ ERR_FAIL_INDEX(p_track, tracks.size());
+ tracks[p_track]->imported = p_imported;
}
-bool Animation::track_is_imported(int p_track) const{
+bool Animation::track_is_imported(int p_track) const {
- ERR_FAIL_INDEX_V(p_track,tracks.size(),false);
+ ERR_FAIL_INDEX_V(p_track, tracks.size(), false);
return tracks[p_track]->imported;
-
}
-
void Animation::track_move_down(int p_track) {
- if (p_track>0 && p_track<tracks.size()) {
+ if (p_track > 0 && p_track < tracks.size()) {
- SWAP( tracks[p_track], tracks[p_track-1] );
+ SWAP(tracks[p_track], tracks[p_track - 1]);
}
emit_changed();
}
void Animation::set_step(float p_step) {
- step=p_step;
+ step = p_step;
emit_changed();
}
-float Animation::get_step() const{
+float Animation::get_step() const {
return step;
}
-
void Animation::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_track","type","at_pos"),&Animation::add_track,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("remove_track","idx"),&Animation::remove_track);
- ClassDB::bind_method(D_METHOD("get_track_count"),&Animation::get_track_count);
- ClassDB::bind_method(D_METHOD("track_get_type","idx"),&Animation::track_get_type);
- ClassDB::bind_method(D_METHOD("track_get_path","idx"),&Animation::track_get_path);
- ClassDB::bind_method(D_METHOD("track_set_path","idx","path"),&Animation::track_set_path);
- ClassDB::bind_method(D_METHOD("find_track","path"),&Animation::find_track);
-
- ClassDB::bind_method(D_METHOD("track_move_up","idx"),&Animation::track_move_up);
- ClassDB::bind_method(D_METHOD("track_move_down","idx"),&Animation::track_move_down);
-
- ClassDB::bind_method(D_METHOD("track_set_imported","idx","imported"),&Animation::track_set_imported);
- ClassDB::bind_method(D_METHOD("track_is_imported","idx"),&Animation::track_is_imported);
-
+ ClassDB::bind_method(D_METHOD("add_track", "type", "at_pos"), &Animation::add_track, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("remove_track", "idx"), &Animation::remove_track);
+ ClassDB::bind_method(D_METHOD("get_track_count"), &Animation::get_track_count);
+ ClassDB::bind_method(D_METHOD("track_get_type", "idx"), &Animation::track_get_type);
+ ClassDB::bind_method(D_METHOD("track_get_path", "idx"), &Animation::track_get_path);
+ ClassDB::bind_method(D_METHOD("track_set_path", "idx", "path"), &Animation::track_set_path);
+ ClassDB::bind_method(D_METHOD("find_track", "path"), &Animation::find_track);
- ClassDB::bind_method(D_METHOD("transform_track_insert_key","idx","time","loc","rot","scale"),&Animation::transform_track_insert_key);
- ClassDB::bind_method(D_METHOD("track_insert_key","idx","time","key","transition"),&Animation::track_insert_key,DEFVAL(1));
- ClassDB::bind_method(D_METHOD("track_remove_key","idx","key_idx"),&Animation::track_remove_key);
- ClassDB::bind_method(D_METHOD("track_remove_key_at_pos","idx","pos"),&Animation::track_remove_key_at_pos);
- ClassDB::bind_method(D_METHOD("track_set_key_value","idx","key","value"),&Animation::track_set_key_value);
- ClassDB::bind_method(D_METHOD("track_set_key_transition","idx","key_idx","transition"),&Animation::track_set_key_transition);
- ClassDB::bind_method(D_METHOD("track_get_key_transition","idx","key_idx"),&Animation::track_get_key_transition);
+ ClassDB::bind_method(D_METHOD("track_move_up", "idx"), &Animation::track_move_up);
+ ClassDB::bind_method(D_METHOD("track_move_down", "idx"), &Animation::track_move_down);
- ClassDB::bind_method(D_METHOD("track_get_key_count","idx"),&Animation::track_get_key_count);
- ClassDB::bind_method(D_METHOD("track_get_key_value","idx","key_idx"),&Animation::track_get_key_value);
- ClassDB::bind_method(D_METHOD("track_get_key_time","idx","key_idx"),&Animation::track_get_key_time);
- ClassDB::bind_method(D_METHOD("track_find_key","idx","time","exact"),&Animation::track_find_key,DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("track_set_imported", "idx", "imported"), &Animation::track_set_imported);
+ ClassDB::bind_method(D_METHOD("track_is_imported", "idx"), &Animation::track_is_imported);
- ClassDB::bind_method(D_METHOD("track_set_interpolation_type","idx","interpolation"),&Animation::track_set_interpolation_type);
- ClassDB::bind_method(D_METHOD("track_get_interpolation_type","idx"),&Animation::track_get_interpolation_type);
+ ClassDB::bind_method(D_METHOD("transform_track_insert_key", "idx", "time", "loc", "rot", "scale"), &Animation::transform_track_insert_key);
+ ClassDB::bind_method(D_METHOD("track_insert_key", "idx", "time", "key", "transition"), &Animation::track_insert_key, DEFVAL(1));
+ ClassDB::bind_method(D_METHOD("track_remove_key", "idx", "key_idx"), &Animation::track_remove_key);
+ ClassDB::bind_method(D_METHOD("track_remove_key_at_pos", "idx", "pos"), &Animation::track_remove_key_at_pos);
+ ClassDB::bind_method(D_METHOD("track_set_key_value", "idx", "key", "value"), &Animation::track_set_key_value);
+ ClassDB::bind_method(D_METHOD("track_set_key_transition", "idx", "key_idx", "transition"), &Animation::track_set_key_transition);
+ ClassDB::bind_method(D_METHOD("track_get_key_transition", "idx", "key_idx"), &Animation::track_get_key_transition);
- ClassDB::bind_method(D_METHOD("track_set_interpolation_loop_wrap","idx","interpolation"),&Animation::track_set_interpolation_loop_wrap);
- ClassDB::bind_method(D_METHOD("track_get_interpolation_loop_wrap","idx"),&Animation::track_get_interpolation_loop_wrap);
+ ClassDB::bind_method(D_METHOD("track_get_key_count", "idx"), &Animation::track_get_key_count);
+ ClassDB::bind_method(D_METHOD("track_get_key_value", "idx", "key_idx"), &Animation::track_get_key_value);
+ ClassDB::bind_method(D_METHOD("track_get_key_time", "idx", "key_idx"), &Animation::track_get_key_time);
+ ClassDB::bind_method(D_METHOD("track_find_key", "idx", "time", "exact"), &Animation::track_find_key, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("track_set_interpolation_type", "idx", "interpolation"), &Animation::track_set_interpolation_type);
+ ClassDB::bind_method(D_METHOD("track_get_interpolation_type", "idx"), &Animation::track_get_interpolation_type);
- ClassDB::bind_method(D_METHOD("transform_track_interpolate","idx","time_sec"),&Animation::_transform_track_interpolate);
- ClassDB::bind_method(D_METHOD("value_track_set_update_mode","idx","mode"),&Animation::value_track_set_update_mode);
- ClassDB::bind_method(D_METHOD("value_track_get_update_mode","idx"),&Animation::value_track_get_update_mode);
+ ClassDB::bind_method(D_METHOD("track_set_interpolation_loop_wrap", "idx", "interpolation"), &Animation::track_set_interpolation_loop_wrap);
+ ClassDB::bind_method(D_METHOD("track_get_interpolation_loop_wrap", "idx"), &Animation::track_get_interpolation_loop_wrap);
- ClassDB::bind_method(D_METHOD("value_track_get_key_indices","idx","time_sec","delta"),&Animation::_value_track_get_key_indices);
+ ClassDB::bind_method(D_METHOD("transform_track_interpolate", "idx", "time_sec"), &Animation::_transform_track_interpolate);
+ ClassDB::bind_method(D_METHOD("value_track_set_update_mode", "idx", "mode"), &Animation::value_track_set_update_mode);
+ ClassDB::bind_method(D_METHOD("value_track_get_update_mode", "idx"), &Animation::value_track_get_update_mode);
- ClassDB::bind_method(D_METHOD("method_track_get_key_indices","idx","time_sec","delta"),&Animation::_method_track_get_key_indices);
- ClassDB::bind_method(D_METHOD("method_track_get_name","idx","key_idx"),&Animation::method_track_get_name);
- ClassDB::bind_method(D_METHOD("method_track_get_params","idx","key_idx"),&Animation::method_track_get_params);
+ ClassDB::bind_method(D_METHOD("value_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_value_track_get_key_indices);
- ClassDB::bind_method(D_METHOD("set_length","time_sec"),&Animation::set_length);
- ClassDB::bind_method(D_METHOD("get_length"),&Animation::get_length);
+ ClassDB::bind_method(D_METHOD("method_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_method_track_get_key_indices);
+ ClassDB::bind_method(D_METHOD("method_track_get_name", "idx", "key_idx"), &Animation::method_track_get_name);
+ ClassDB::bind_method(D_METHOD("method_track_get_params", "idx", "key_idx"), &Animation::method_track_get_params);
- ClassDB::bind_method(D_METHOD("set_loop","enabled"),&Animation::set_loop);
- ClassDB::bind_method(D_METHOD("has_loop"),&Animation::has_loop);
+ ClassDB::bind_method(D_METHOD("set_length", "time_sec"), &Animation::set_length);
+ ClassDB::bind_method(D_METHOD("get_length"), &Animation::get_length);
- ClassDB::bind_method(D_METHOD("set_step","size_sec"),&Animation::set_step);
- ClassDB::bind_method(D_METHOD("get_step"),&Animation::get_step);
+ ClassDB::bind_method(D_METHOD("set_loop", "enabled"), &Animation::set_loop);
+ ClassDB::bind_method(D_METHOD("has_loop"), &Animation::has_loop);
- ClassDB::bind_method(D_METHOD("clear"),&Animation::clear);
+ ClassDB::bind_method(D_METHOD("set_step", "size_sec"), &Animation::set_step);
+ ClassDB::bind_method(D_METHOD("get_step"), &Animation::get_step);
- BIND_CONSTANT( TYPE_VALUE );
- BIND_CONSTANT( TYPE_TRANSFORM );
- BIND_CONSTANT( TYPE_METHOD );
+ ClassDB::bind_method(D_METHOD("clear"), &Animation::clear);
- BIND_CONSTANT( INTERPOLATION_NEAREST );
- BIND_CONSTANT( INTERPOLATION_LINEAR );
- BIND_CONSTANT( INTERPOLATION_CUBIC );
-
- BIND_CONSTANT( UPDATE_CONTINUOUS );
- BIND_CONSTANT( UPDATE_DISCRETE );
- BIND_CONSTANT( UPDATE_TRIGGER );
+ BIND_CONSTANT(TYPE_VALUE);
+ BIND_CONSTANT(TYPE_TRANSFORM);
+ BIND_CONSTANT(TYPE_METHOD);
+ BIND_CONSTANT(INTERPOLATION_NEAREST);
+ BIND_CONSTANT(INTERPOLATION_LINEAR);
+ BIND_CONSTANT(INTERPOLATION_CUBIC);
+ BIND_CONSTANT(UPDATE_CONTINUOUS);
+ BIND_CONSTANT(UPDATE_DISCRETE);
+ BIND_CONSTANT(UPDATE_TRIGGER);
}
void Animation::clear() {
- for(int i=0;i<tracks.size();i++)
- memdelete( tracks[i] );
+ for (int i = 0; i < tracks.size(); i++)
+ memdelete(tracks[i]);
tracks.clear();
- loop=false;
- length=1;
-
+ loop = false;
+ length = 1;
}
+bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0, const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle, const Vector3 &p_norm) {
-
-bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0,const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle,const Vector3& p_norm) {
-
-
- real_t c = (t1.time-t0.time)/(t2.time-t0.time);
- real_t t[3]={-1,-1,-1};
+ real_t c = (t1.time - t0.time) / (t2.time - t0.time);
+ real_t t[3] = { -1, -1, -1 };
{ //translation
- const Vector3 &v0=t0.value.loc;
- const Vector3 &v1=t1.value.loc;
- const Vector3 &v2=t2.value.loc;
+ const Vector3 &v0 = t0.value.loc;
+ const Vector3 &v1 = t1.value.loc;
+ const Vector3 &v2 = t2.value.loc;
- if (v0.distance_to(v2)<CMP_EPSILON) {
+ if (v0.distance_to(v2) < CMP_EPSILON) {
//0 and 2 are close, let's see if 1 is close
- if (v0.distance_to(v1)>CMP_EPSILON) {
+ if (v0.distance_to(v1) > CMP_EPSILON) {
//not close, not optimizable
return false;
}
} else {
- Vector3 pd = (v2-v0);
+ Vector3 pd = (v2 - v0);
float d0 = pd.dot(v0);
float d1 = pd.dot(v1);
float d2 = pd.dot(v2);
- if (d1<d0 || d1>d2) {
+ if (d1 < d0 || d1 > d2) {
return false;
}
- Vector3 s[2]={ v0, v2 };
- real_t d =Geometry::get_closest_point_to_segment(v1,s).distance_to(v1);
+ Vector3 s[2] = { v0, v2 };
+ real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1);
- if (d>pd.length()*p_alowed_linear_err) {
+ if (d > pd.length() * p_alowed_linear_err) {
return false; //beyond allowed error for colinearity
}
- if (p_norm!=Vector3() && Math::acos(pd.normalized().dot(p_norm))>p_alowed_angular_err)
+ if (p_norm != Vector3() && Math::acos(pd.normalized().dot(p_norm)) > p_alowed_angular_err)
return false;
- t[0] = (d1-d0)/(d2-d0);
+ t[0] = (d1 - d0) / (d2 - d0);
}
}
{ //rotation
- const Quat &q0=t0.value.rot;
- const Quat &q1=t1.value.rot;
- const Quat &q2=t2.value.rot;
+ const Quat &q0 = t0.value.rot;
+ const Quat &q1 = t1.value.rot;
+ const Quat &q2 = t2.value.rot;
//localize both to rotation from q0
- if ((q0-q2).length() < CMP_EPSILON) {
+ if ((q0 - q2).length() < CMP_EPSILON) {
- if ((q0-q1).length() > CMP_EPSILON)
+ if ((q0 - q1).length() > CMP_EPSILON)
return false;
} else {
-
Quat r02 = (q0.inverse() * q2).normalized();
Quat r01 = (q0.inverse() * q1).normalized();
- Vector3 v02,v01;
- real_t a02,a01;
+ Vector3 v02, v01;
+ real_t a02, a01;
- r02.get_axis_and_angle(v02,a02);
- r01.get_axis_and_angle(v01,a01);
+ r02.get_axis_and_angle(v02, a02);
+ r01.get_axis_and_angle(v01, a01);
- if (Math::abs(a02)>p_max_optimizable_angle)
+ if (Math::abs(a02) > p_max_optimizable_angle)
return false;
- if (v01.dot(v02)<0) {
+ if (v01.dot(v02) < 0) {
//make sure both rotations go the same way to compare
- v02=-v02;
- a02=-a02;
+ v02 = -v02;
+ a02 = -a02;
}
- real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized()))/Math_PI;
- if (err_01>p_alowed_angular_err) {
+ real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized())) / Math_PI;
+ if (err_01 > p_alowed_angular_err) {
//not rotating in the same axis
return false;
}
- if (a01*a02 < 0 ) {
+ if (a01 * a02 < 0) {
//not rotating in the same direction
return false;
}
- real_t tr = a01/a02;
- if (tr<0 || tr>1)
+ real_t tr = a01 / a02;
+ if (tr < 0 || tr > 1)
return false; //rotating too much or too less
- t[1]=tr;
-
+ t[1] = tr;
}
-
}
{ //scale
- const Vector3 &v0=t0.value.scale;
- const Vector3 &v1=t1.value.scale;
- const Vector3 &v2=t2.value.scale;
+ const Vector3 &v0 = t0.value.scale;
+ const Vector3 &v1 = t1.value.scale;
+ const Vector3 &v2 = t2.value.scale;
- if (v0.distance_to(v2)<CMP_EPSILON) {
+ if (v0.distance_to(v2) < CMP_EPSILON) {
//0 and 2 are close, let's see if 1 is close
- if (v0.distance_to(v1)>CMP_EPSILON) {
+ if (v0.distance_to(v1) > CMP_EPSILON) {
//not close, not optimizable
return false;
}
} else {
- Vector3 pd = (v2-v0);
+ Vector3 pd = (v2 - v0);
float d0 = pd.dot(v0);
float d1 = pd.dot(v1);
float d2 = pd.dot(v2);
- if (d1<d0 || d1>d2) {
+ if (d1 < d0 || d1 > d2) {
return false; //beyond segment range
}
- Vector3 s[2]={ v0, v2 };
- real_t d =Geometry::get_closest_point_to_segment(v1,s).distance_to(v1);
+ Vector3 s[2] = { v0, v2 };
+ real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1);
- if (d>pd.length()*p_alowed_linear_err) {
+ if (d > pd.length() * p_alowed_linear_err) {
return false; //beyond allowed error for colinearity
}
- t[2] = (d1-d0)/(d2-d0);
+ t[2] = (d1 - d0) / (d2 - d0);
}
}
- bool erase=false;
- if (t[0]==-1 && t[1]==-1 && t[2]==-1) {
+ bool erase = false;
+ if (t[0] == -1 && t[1] == -1 && t[2] == -1) {
- erase=true;
+ erase = true;
} else {
- erase=true;
- real_t lt=-1;
- for(int j=0;j<3;j++) {
+ erase = true;
+ real_t lt = -1;
+ for (int j = 0; j < 3; j++) {
//search for t on first, one must be it
- if (t[j]!=-1) {
- lt=t[j]; //official t
+ if (t[j] != -1) {
+ lt = t[j]; //official t
//validate rest
- for(int k=j+1;k<3;k++) {
- if (t[k]==-1)
+ for (int k = j + 1; k < 3; k++) {
+ if (t[k] == -1)
continue;
- if (Math::abs(lt-t[k])>p_alowed_linear_err) {
- erase=false;
+ if (Math::abs(lt - t[k]) > p_alowed_linear_err) {
+ erase = false;
break;
}
}
@@ -1939,102 +1851,86 @@ bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0,const
}
}
- ERR_FAIL_COND_V( lt==-1,false );
+ ERR_FAIL_COND_V(lt == -1, false);
if (erase) {
- if (Math::abs(lt-c)>p_alowed_linear_err) {
+ if (Math::abs(lt - c) > p_alowed_linear_err) {
//todo, evaluate changing the transition if this fails?
//this could be done as a second pass and would be
//able to optimize more
- erase=false;
+ erase = false;
} else {
//print_line(itos(i)+"because of interp");
}
}
-
}
-
return erase;
-
-
}
+void Animation::_transform_track_optimize(int p_idx, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle) {
-void Animation::_transform_track_optimize(int p_idx,float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle) {
-
- ERR_FAIL_INDEX(p_idx,tracks.size());
- ERR_FAIL_COND(tracks[p_idx]->type!=TYPE_TRANSFORM);
- TransformTrack *tt= static_cast<TransformTrack*>(tracks[p_idx]);
- bool prev_erased=false;
+ ERR_FAIL_INDEX(p_idx, tracks.size());
+ ERR_FAIL_COND(tracks[p_idx]->type != TYPE_TRANSFORM);
+ TransformTrack *tt = static_cast<TransformTrack *>(tracks[p_idx]);
+ bool prev_erased = false;
TKey<TransformKey> first_erased;
Vector3 norm;
- for(int i=1;i<tt->transforms.size()-1;i++) {
+ for (int i = 1; i < tt->transforms.size() - 1; i++) {
- TKey<TransformKey> &t0 = tt->transforms[i-1];
+ TKey<TransformKey> &t0 = tt->transforms[i - 1];
TKey<TransformKey> &t1 = tt->transforms[i];
- TKey<TransformKey> &t2 = tt->transforms[i+1];
+ TKey<TransformKey> &t2 = tt->transforms[i + 1];
- bool erase = _transform_track_optimize_key(t0,t1,t2,p_alowed_linear_err,p_alowed_angular_err,p_max_optimizable_angle,norm);
+ bool erase = _transform_track_optimize_key(t0, t1, t2, p_alowed_linear_err, p_alowed_angular_err, p_max_optimizable_angle, norm);
if (erase && !prev_erased) {
- norm=(t2.value.loc-t1.value.loc).normalized();
+ norm = (t2.value.loc - t1.value.loc).normalized();
}
-
- if (prev_erased && !_transform_track_optimize_key(t0,first_erased,t2,p_alowed_linear_err,p_alowed_angular_err,p_max_optimizable_angle,norm)) {
- //avoid error to go beyond first erased key
- erase=false;
+ if (prev_erased && !_transform_track_optimize_key(t0, first_erased, t2, p_alowed_linear_err, p_alowed_angular_err, p_max_optimizable_angle, norm)) {
+ //avoid error to go beyond first erased key
+ erase = false;
}
-
if (erase) {
if (!prev_erased) {
- first_erased=t1;
- prev_erased=true;
+ first_erased = t1;
+ prev_erased = true;
}
tt->transforms.remove(i);
i--;
} else {
- prev_erased=false;
- norm=Vector3();
+ prev_erased = false;
+ norm = Vector3();
}
}
-
-
}
-void Animation::optimize(float p_allowed_linear_err,float p_allowed_angular_err,float p_angle_max) {
+void Animation::optimize(float p_allowed_linear_err, float p_allowed_angular_err, float p_angle_max) {
- for(int i=0;i<tracks.size();i++) {
-
- if (tracks[i]->type==TYPE_TRANSFORM)
- _transform_track_optimize(i,p_allowed_linear_err,p_allowed_angular_err,p_angle_max);
+ for (int i = 0; i < tracks.size(); i++) {
+ if (tracks[i]->type == TYPE_TRANSFORM)
+ _transform_track_optimize(i, p_allowed_linear_err, p_allowed_angular_err, p_angle_max);
}
-
}
-
Animation::Animation() {
- step=0.1;
- loop=false;
- length=1;
+ step = 0.1;
+ loop = false;
+ length = 1;
}
-
Animation::~Animation() {
- for(int i=0;i<tracks.size();i++)
- memdelete( tracks[i] );
-
+ for (int i = 0; i < tracks.size(); i++)
+ memdelete(tracks[i]);
}
-
-
diff --git a/scene/resources/animation.h b/scene/resources/animation.h
index b81ac4f1bf..57ab8b282f 100644
--- a/scene/resources/animation.h
+++ b/scene/resources/animation.h
@@ -35,12 +35,10 @@
*/
class Animation : public Resource {
- GDCLASS( Animation, Resource );
+ GDCLASS(Animation, Resource);
RES_BASE_EXTENSION("anm");
-public:
-
-
+public:
enum TrackType {
TYPE_VALUE, ///< Set a value in a property, can be interpolated.
TYPE_TRANSFORM, ///< Transform a node or a bone.
@@ -61,7 +59,6 @@ public:
};
private:
-
struct Track {
TrackType type;
@@ -69,7 +66,11 @@ private:
bool loop_wrap;
NodePath path; // path to something
bool imported;
- Track() { interpolation=INTERPOLATION_LINEAR; imported=false; loop_wrap=true;}
+ Track() {
+ interpolation = INTERPOLATION_LINEAR;
+ imported = false;
+ loop_wrap = true;
+ }
virtual ~Track() {}
};
@@ -77,18 +78,17 @@ private:
float transition;
float time; // time in secs
- Key() { transition=1; }
+ Key() { transition = 1; }
};
// transform key holds either Vector3 or Quaternion
- template<class T>
+ template <class T>
struct TKey : public Key {
float time;
T value;
};
-
struct TransformKey {
Vector3 loc;
@@ -100,9 +100,9 @@ private:
struct TransformTrack : public Track {
- Vector< TKey<TransformKey> > transforms;
+ Vector<TKey<TransformKey> > transforms;
- TransformTrack() { type=TYPE_TRANSFORM; }
+ TransformTrack() { type = TYPE_TRANSFORM; }
};
/* PROPERTY VALUE TRACK */
@@ -111,12 +111,14 @@ private:
UpdateMode update_mode;
bool update_on_seek;
- Vector< TKey<Variant> > values;
+ Vector<TKey<Variant> > values;
- ValueTrack() { type=TYPE_VALUE; update_mode=UPDATE_CONTINUOUS; }
+ ValueTrack() {
+ type = TYPE_VALUE;
+ update_mode = UPDATE_CONTINUOUS;
+ }
};
-
/* METHOD TRACK */
struct MethodKey : public Key {
@@ -127,56 +129,55 @@ private:
struct MethodTrack : public Track {
- Vector< MethodKey > methods;
- MethodTrack() { type=TYPE_METHOD; }
+ Vector<MethodKey> methods;
+ MethodTrack() { type = TYPE_METHOD; }
};
- Vector<Track*> tracks;
+ Vector<Track *> tracks;
/*
template<class T>
int _insert_pos(float p_time, T& p_keys);*/
- template<class T>
- void _clear(T& p_keys);
+ template <class T>
+ void _clear(T &p_keys);
- template<class T, class V>
- int _insert(float p_time, T& p_keys, const V& p_value);
+ template <class T, class V>
+ int _insert(float p_time, T &p_keys, const V &p_value);
- template<class K>
- inline int _find( const Vector<K>& p_keys, float p_time) const;
+ template <class K>
+ inline int _find(const Vector<K> &p_keys, float p_time) const;
- _FORCE_INLINE_ Animation::TransformKey _interpolate( const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, float p_c) const;
+ _FORCE_INLINE_ Animation::TransformKey _interpolate(const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, float p_c) const;
- _FORCE_INLINE_ Vector3 _interpolate( const Vector3& p_a, const Vector3& p_b, float p_c) const;
- _FORCE_INLINE_ Quat _interpolate( const Quat& p_a, const Quat& p_b, float p_c) const;
- _FORCE_INLINE_ Variant _interpolate( const Variant& p_a, const Variant& p_b, float p_c) const;
- _FORCE_INLINE_ float _interpolate( const float& p_a, const float& p_b, float p_c) const;
+ _FORCE_INLINE_ Vector3 _interpolate(const Vector3 &p_a, const Vector3 &p_b, float p_c) const;
+ _FORCE_INLINE_ Quat _interpolate(const Quat &p_a, const Quat &p_b, float p_c) const;
+ _FORCE_INLINE_ Variant _interpolate(const Variant &p_a, const Variant &p_b, float p_c) const;
+ _FORCE_INLINE_ float _interpolate(const float &p_a, const float &p_b, float p_c) const;
- _FORCE_INLINE_ Animation::TransformKey _cubic_interpolate( const Animation::TransformKey& p_pre_a, const Animation::TransformKey& p_a, const Animation::TransformKey& p_b, const Animation::TransformKey& p_post_b,float p_c) const;
- _FORCE_INLINE_ Vector3 _cubic_interpolate( const Vector3& p_pre_a,const Vector3& p_a, const Vector3& p_b,const Vector3& p_post_b, float p_c) const;
- _FORCE_INLINE_ Quat _cubic_interpolate( const Quat& p_pre_a,const Quat& p_a, const Quat& p_b,const Quat& p_post_b, float p_c) const;
- _FORCE_INLINE_ Variant _cubic_interpolate( const Variant& p_pre_a,const Variant& p_a, const Variant& p_b, const Variant& p_post_b,float p_c) const;
- _FORCE_INLINE_ float _cubic_interpolate( const float& p_pre_a,const float& p_a, const float& p_b, const float& p_post_b, float p_c) const;
+ _FORCE_INLINE_ Animation::TransformKey _cubic_interpolate(const Animation::TransformKey &p_pre_a, const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, const Animation::TransformKey &p_post_b, float p_c) const;
+ _FORCE_INLINE_ Vector3 _cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, float p_c) const;
+ _FORCE_INLINE_ Quat _cubic_interpolate(const Quat &p_pre_a, const Quat &p_a, const Quat &p_b, const Quat &p_post_b, float p_c) const;
+ _FORCE_INLINE_ Variant _cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, float p_c) const;
+ _FORCE_INLINE_ float _cubic_interpolate(const float &p_pre_a, const float &p_a, const float &p_b, const float &p_post_b, float p_c) const;
- template<class T>
- _FORCE_INLINE_ T _interpolate( const Vector< TKey<T> >& p_keys, float p_time, InterpolationType p_interp,bool p_loop_wrap,bool *p_ok) const;
+ template <class T>
+ _FORCE_INLINE_ T _interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const;
- _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack * vt, float from_time, float to_time,List<int> *p_indices) const;
- _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack * mt, float from_time, float to_time,List<int> *p_indices) const;
+ _FORCE_INLINE_ void _value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const;
+ _FORCE_INLINE_ void _method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const;
float length;
float step;
bool loop;
-// bind helpers
+ // bind helpers
private:
-
Array _transform_track_interpolate(int p_track, float p_time) const {
Vector3 loc;
Quat rot;
Vector3 scale;
- transform_track_interpolate(p_track,p_time,&loc,&rot,&scale);
+ transform_track_interpolate(p_track, p_time, &loc, &rot, &scale);
Array ret;
ret.push_back(loc);
ret.push_back(rot);
@@ -187,10 +188,10 @@ private:
PoolVector<int> _value_track_get_key_indices(int p_track, float p_time, float p_delta) const {
List<int> idxs;
- value_track_get_key_indices(p_track,p_time,p_delta,&idxs);
+ value_track_get_key_indices(p_track, p_time, p_delta, &idxs);
PoolVector<int> idxr;
- for (List<int>::Element *E=idxs.front();E;E=E->next()) {
+ for (List<int>::Element *E = idxs.front(); E; E = E->next()) {
idxr.push_back(E->get());
}
@@ -199,52 +200,49 @@ private:
PoolVector<int> _method_track_get_key_indices(int p_track, float p_time, float p_delta) const {
List<int> idxs;
- method_track_get_key_indices(p_track,p_time,p_delta,&idxs);
+ method_track_get_key_indices(p_track, p_time, p_delta, &idxs);
PoolVector<int> idxr;
- for (List<int>::Element *E=idxs.front();E;E=E->next()) {
+ for (List<int>::Element *E = idxs.front(); E; E = E->next()) {
idxr.push_back(E->get());
}
return idxr;
}
- bool _transform_track_optimize_key(const TKey<TransformKey> &t0,const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err,float p_alowed_angular_err,float p_max_optimizable_angle,const Vector3& p_norm);
- void _transform_track_optimize(int p_idx, float p_allowed_err=0.05, float p_alowed_angular_err=0.01,float p_max_optimizable_angle=Math_PI*0.125);
+ bool _transform_track_optimize_key(const TKey<TransformKey> &t0, const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle, const Vector3 &p_norm);
+ void _transform_track_optimize(int p_idx, float p_allowed_err = 0.05, float p_alowed_angular_err = 0.01, float p_max_optimizable_angle = Math_PI * 0.125);
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
- int add_track(TrackType p_type,int p_at_pos=-1);
+ int add_track(TrackType p_type, int p_at_pos = -1);
void remove_track(int p_track);
int get_track_count() const;
TrackType track_get_type(int p_track) const;
- void track_set_path(int p_track,const NodePath& p_path);
+ void track_set_path(int p_track, const NodePath &p_path);
NodePath track_get_path(int p_track) const;
- int find_track(const NodePath& p_path) const;
+ int find_track(const NodePath &p_path) const;
// transform
-
void track_move_up(int p_track);
void track_move_down(int p_track);
- void track_set_imported(int p_track,bool p_imported);
+ void track_set_imported(int p_track, bool p_imported);
bool track_is_imported(int p_track) const;
- int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat& p_rot=Quat(), const Vector3& p_scale=Vector3());
- void track_insert_key(int p_track, float p_time, const Variant& p_key, float p_transition=1);
- void track_set_key_transition(int p_track, int p_key_idx,float p_transition);
- void track_set_key_value(int p_track, int p_key_idx,const Variant& p_value);
- int track_find_key(int p_track, float p_time, bool p_exact=false) const;
+ int transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot = Quat(), const Vector3 &p_scale = Vector3());
+ void track_insert_key(int p_track, float p_time, const Variant &p_key, float p_transition = 1);
+ void track_set_key_transition(int p_track, int p_key_idx, float p_transition);
+ void track_set_key_value(int p_track, int p_key_idx, const Variant &p_value);
+ int track_find_key(int p_track, float p_time, bool p_exact = false) const;
void track_remove_key(int p_track, int p_idx);
void track_remove_key_at_pos(int p_track, float p_pos);
int track_get_key_count(int p_track) const;
@@ -252,25 +250,23 @@ public:
float track_get_key_time(int p_track, int p_key_idx) const;
float track_get_key_transition(int p_track, int p_key_idx) const;
- Error transform_track_get_key(int p_track, int p_key, Vector3* r_loc, Quat* r_rot, Vector3* r_scale) const;
- void track_set_interpolation_type(int p_track,InterpolationType p_interp);
+ Error transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const;
+ void track_set_interpolation_type(int p_track, InterpolationType p_interp);
InterpolationType track_get_interpolation_type(int p_track) const;
- void track_set_interpolation_loop_wrap(int p_track,bool p_enable);
+ void track_set_interpolation_loop_wrap(int p_track, bool p_enable);
bool track_get_interpolation_loop_wrap(int p_track) const;
- Error transform_track_interpolate(int p_track, float p_time, Vector3 * r_loc, Quat *r_rot, Vector3 *r_scale) const;
+ Error transform_track_interpolate(int p_track, float p_time, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const;
Variant value_track_interpolate(int p_track, float p_time) const;
- void value_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const;
+ void value_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const;
void value_track_set_update_mode(int p_track, UpdateMode p_mode);
UpdateMode value_track_get_update_mode(int p_track) const;
-
- void method_track_get_key_indices(int p_track, float p_time, float p_delta,List<int> *p_indices) const;
- Vector<Variant> method_track_get_params(int p_track,int p_key_idx) const;
- StringName method_track_get_name(int p_track,int p_key_idx) const;
-
+ void method_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const;
+ Vector<Variant> method_track_get_params(int p_track, int p_key_idx) const;
+ StringName method_track_get_name(int p_track, int p_key_idx) const;
void set_length(float p_length);
float get_length() const;
@@ -283,17 +279,14 @@ public:
void clear();
- void optimize(float p_allowed_linear_err=0.05,float p_allowed_angular_err=0.01,float p_max_optimizable_angle=Math_PI*0.125);
+ void optimize(float p_allowed_linear_err = 0.05, float p_allowed_angular_err = 0.01, float p_max_optimizable_angle = Math_PI * 0.125);
Animation();
~Animation();
-
};
-VARIANT_ENUM_CAST( Animation::TrackType );
-VARIANT_ENUM_CAST( Animation::InterpolationType );
-VARIANT_ENUM_CAST( Animation::UpdateMode );
-
-
+VARIANT_ENUM_CAST(Animation::TrackType);
+VARIANT_ENUM_CAST(Animation::InterpolationType);
+VARIANT_ENUM_CAST(Animation::UpdateMode);
#endif
diff --git a/scene/resources/audio_stream_resampled.cpp b/scene/resources/audio_stream_resampled.cpp
index b2f314a55e..1c0c725ef9 100644
--- a/scene/resources/audio_stream_resampled.cpp
+++ b/scene/resources/audio_stream_resampled.cpp
@@ -29,7 +29,6 @@
#include "audio_stream_resampled.h"
#include "global_config.h"
-
#if 0
int AudioStreamResampled::get_channel_count() const {
diff --git a/scene/resources/audio_stream_sample.cpp b/scene/resources/audio_stream_sample.cpp
index 4aee119b0e..b419f4b6be 100644
--- a/scene/resources/audio_stream_sample.cpp
+++ b/scene/resources/audio_stream_sample.cpp
@@ -30,26 +30,26 @@
void AudioStreamPlaybackSample::start(float p_from_pos) {
- for(int i=0;i<2;i++) {
- ima_adpcm[i].step_index=0;
- ima_adpcm[i].predictor=0;
- ima_adpcm[i].loop_step_index=0;
- ima_adpcm[i].loop_predictor=0;
- ima_adpcm[i].last_nibble=-1;
- ima_adpcm[i].loop_pos=0x7FFFFFFF;
- ima_adpcm[i].window_ofs=0;
- ima_adpcm[i].ptr=(const uint8_t*)base->data;
- ima_adpcm[i].ptr+=AudioStreamSample::DATA_PAD;
+ for (int i = 0; i < 2; i++) {
+ ima_adpcm[i].step_index = 0;
+ ima_adpcm[i].predictor = 0;
+ ima_adpcm[i].loop_step_index = 0;
+ ima_adpcm[i].loop_predictor = 0;
+ ima_adpcm[i].last_nibble = -1;
+ ima_adpcm[i].loop_pos = 0x7FFFFFFF;
+ ima_adpcm[i].window_ofs = 0;
+ ima_adpcm[i].ptr = (const uint8_t *)base->data;
+ ima_adpcm[i].ptr += AudioStreamSample::DATA_PAD;
}
seek_pos(p_from_pos);
- sign=1;
- active=true;
+ sign = 1;
+ active = true;
}
void AudioStreamPlaybackSample::stop() {
- active=false;
+ active = false;
}
bool AudioStreamPlaybackSample::is_playing() const {
@@ -64,42 +64,40 @@ int AudioStreamPlaybackSample::get_loop_count() const {
float AudioStreamPlaybackSample::get_pos() const {
- return float(offset>>MIX_FRAC_BITS)/base->mix_rate;
+ return float(offset >> MIX_FRAC_BITS) / base->mix_rate;
}
void AudioStreamPlaybackSample::seek_pos(float p_time) {
- if (base->format==AudioStreamSample::FORMAT_IMA_ADPCM)
+ if (base->format == AudioStreamSample::FORMAT_IMA_ADPCM)
return; //no seeking in ima-adpcm
- float max=get_length();
- if (p_time<0) {
- p_time=0;
- } else if (p_time>=max) {
- p_time=max-0.001;
+ float max = get_length();
+ if (p_time < 0) {
+ p_time = 0;
+ } else if (p_time >= max) {
+ p_time = max - 0.001;
}
- offset = uint64_t(p_time * base->mix_rate)<<MIX_FRAC_BITS;
+ offset = uint64_t(p_time * base->mix_rate) << MIX_FRAC_BITS;
}
-
-template<class Depth,bool is_stereo,bool is_ima_adpcm>
-void AudioStreamPlaybackSample::do_resample(const Depth* p_src, AudioFrame *p_dst,int64_t &offset,int32_t &increment,uint32_t amount,IMA_ADPCM_State *ima_adpcm) {
+template <class Depth, bool is_stereo, bool is_ima_adpcm>
+void AudioStreamPlaybackSample::do_resample(const Depth *p_src, AudioFrame *p_dst, int64_t &offset, int32_t &increment, uint32_t amount, IMA_ADPCM_State *ima_adpcm) {
// this function will be compiled branchless by any decent compiler
- int32_t final,final_r,next,next_r;
+ int32_t final, final_r, next, next_r;
while (amount--) {
- int64_t pos=offset >> MIX_FRAC_BITS;
+ int64_t pos = offset >> MIX_FRAC_BITS;
if (is_stereo && !is_ima_adpcm)
- pos<<=1;
+ pos <<= 1;
if (is_ima_adpcm) {
int64_t sample_pos = pos + ima_adpcm[0].window_ofs;
- while(sample_pos>ima_adpcm[0].last_nibble) {
-
+ while (sample_pos > ima_adpcm[0].last_nibble) {
static const int16_t _ima_adpcm_step_table[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
@@ -118,227 +116,215 @@ void AudioStreamPlaybackSample::do_resample(const Depth* p_src, AudioFrame *p_ds
-1, -1, -1, -1, 2, 4, 6, 8
};
- for(int i=0;i<(is_stereo?2:1);i++) {
+ for (int i = 0; i < (is_stereo ? 2 : 1); i++) {
-
- int16_t nibble,diff,step;
+ int16_t nibble, diff, step;
ima_adpcm[i].last_nibble++;
- const uint8_t *src_ptr=ima_adpcm[i].ptr;
-
-
- uint8_t nbb = src_ptr[ (ima_adpcm[i].last_nibble>>1) * (is_stereo?2:1) + i ];
- nibble = (ima_adpcm[i].last_nibble&1)?(nbb>>4):(nbb&0xF);
- step=_ima_adpcm_step_table[ima_adpcm[i].step_index];
+ const uint8_t *src_ptr = ima_adpcm[i].ptr;
+ uint8_t nbb = src_ptr[(ima_adpcm[i].last_nibble >> 1) * (is_stereo ? 2 : 1) + i];
+ nibble = (ima_adpcm[i].last_nibble & 1) ? (nbb >> 4) : (nbb & 0xF);
+ step = _ima_adpcm_step_table[ima_adpcm[i].step_index];
ima_adpcm[i].step_index += _ima_adpcm_index_table[nibble];
- if (ima_adpcm[i].step_index<0)
- ima_adpcm[i].step_index=0;
- if (ima_adpcm[i].step_index>88)
- ima_adpcm[i].step_index=88;
+ if (ima_adpcm[i].step_index < 0)
+ ima_adpcm[i].step_index = 0;
+ if (ima_adpcm[i].step_index > 88)
+ ima_adpcm[i].step_index = 88;
- diff = step >> 3 ;
+ diff = step >> 3;
if (nibble & 1)
- diff += step >> 2 ;
+ diff += step >> 2;
if (nibble & 2)
- diff += step >> 1 ;
+ diff += step >> 1;
if (nibble & 4)
- diff += step ;
+ diff += step;
if (nibble & 8)
- diff = -diff ;
-
- ima_adpcm[i].predictor+=diff;
- if (ima_adpcm[i].predictor<-0x8000)
- ima_adpcm[i].predictor=-0x8000;
- else if (ima_adpcm[i].predictor>0x7FFF)
- ima_adpcm[i].predictor=0x7FFF;
+ diff = -diff;
+ ima_adpcm[i].predictor += diff;
+ if (ima_adpcm[i].predictor < -0x8000)
+ ima_adpcm[i].predictor = -0x8000;
+ else if (ima_adpcm[i].predictor > 0x7FFF)
+ ima_adpcm[i].predictor = 0x7FFF;
/* store loop if there */
- if (ima_adpcm[i].last_nibble==ima_adpcm[i].loop_pos) {
+ if (ima_adpcm[i].last_nibble == ima_adpcm[i].loop_pos) {
ima_adpcm[i].loop_step_index = ima_adpcm[i].step_index;
ima_adpcm[i].loop_predictor = ima_adpcm[i].predictor;
}
//printf("%i - %i - pred %i\n",int(ima_adpcm[i].last_nibble),int(nibble),int(ima_adpcm[i].predictor));
-
}
-
}
- final=ima_adpcm[0].predictor;
+ final = ima_adpcm[0].predictor;
if (is_stereo) {
- final_r=ima_adpcm[1].predictor;
+ final_r = ima_adpcm[1].predictor;
}
} else {
- final=p_src[pos];
+ final = p_src[pos];
if (is_stereo)
- final_r=p_src[pos+1];
+ final_r = p_src[pos + 1];
- if (sizeof(Depth)==1) { /* conditions will not exist anymore when compiled! */
- final<<=8;
+ if (sizeof(Depth) == 1) { /* conditions will not exist anymore when compiled! */
+ final <<= 8;
if (is_stereo)
- final_r<<=8;
+ final_r <<= 8;
}
if (is_stereo) {
- next=p_src[pos+2];
- next_r=p_src[pos+3];
+ next = p_src[pos + 2];
+ next_r = p_src[pos + 3];
} else {
- next=p_src[pos+1];
+ next = p_src[pos + 1];
}
- if (sizeof(Depth)==1) {
- next<<=8;
+ if (sizeof(Depth) == 1) {
+ next <<= 8;
if (is_stereo)
- next_r<<=8;
+ next_r <<= 8;
}
- int32_t frac=int64_t(offset&MIX_FRAC_MASK);
+ int32_t frac = int64_t(offset & MIX_FRAC_MASK);
- final=final+((next-final)*frac >> MIX_FRAC_BITS);
+ final = final + ((next - final) * frac >> MIX_FRAC_BITS);
if (is_stereo)
- final_r=final_r+((next_r-final_r)*frac >> MIX_FRAC_BITS);
-
+ final_r = final_r + ((next_r - final_r) * frac >> MIX_FRAC_BITS);
}
-
if (!is_stereo) {
- final_r=final; //copy to right channel if stereo
+ final_r = final; //copy to right channel if stereo
}
- p_dst->l=final/32767.0;
- p_dst->r=final_r/32767.0;
+ p_dst->l = final / 32767.0;
+ p_dst->r = final_r / 32767.0;
p_dst++;
- offset+=increment;
+ offset += increment;
}
}
-void AudioStreamPlaybackSample::mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames) {
+void AudioStreamPlaybackSample::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
if (!base->data || !active) {
- for(int i=0;i<p_frames;i++) {
- p_buffer[i]=AudioFrame(0,0);
+ for (int i = 0; i < p_frames; i++) {
+ p_buffer[i] = AudioFrame(0, 0);
}
return;
}
int len = base->data_bytes;
- switch(base->format) {
- case AudioStreamSample::FORMAT_8_BITS: len/=1; break;
- case AudioStreamSample::FORMAT_16_BITS: len/=2; break;
- case AudioStreamSample::FORMAT_IMA_ADPCM: len*=2; break;
+ switch (base->format) {
+ case AudioStreamSample::FORMAT_8_BITS: len /= 1; break;
+ case AudioStreamSample::FORMAT_16_BITS: len /= 2; break;
+ case AudioStreamSample::FORMAT_IMA_ADPCM: len *= 2; break;
}
if (base->stereo) {
- len/=2;
+ len /= 2;
}
/* some 64-bit fixed point precaches */
- int64_t loop_begin_fp=((int64_t)len<< MIX_FRAC_BITS);
- int64_t loop_end_fp=((int64_t)base->loop_end << MIX_FRAC_BITS);
- int64_t length_fp=((int64_t)len << MIX_FRAC_BITS);
- int64_t begin_limit=(base->loop_mode!=AudioStreamSample::LOOP_DISABLED)?loop_begin_fp:0;
- int64_t end_limit=(base->loop_mode!=AudioStreamSample::LOOP_DISABLED)?loop_end_fp:length_fp;
- bool is_stereo=base->stereo;
+ int64_t loop_begin_fp = ((int64_t)len << MIX_FRAC_BITS);
+ int64_t loop_end_fp = ((int64_t)base->loop_end << MIX_FRAC_BITS);
+ int64_t length_fp = ((int64_t)len << MIX_FRAC_BITS);
+ int64_t begin_limit = (base->loop_mode != AudioStreamSample::LOOP_DISABLED) ? loop_begin_fp : 0;
+ int64_t end_limit = (base->loop_mode != AudioStreamSample::LOOP_DISABLED) ? loop_end_fp : length_fp;
+ bool is_stereo = base->stereo;
- int32_t todo=p_frames;
+ int32_t todo = p_frames;
float base_rate = AudioServer::get_singleton()->get_mix_rate();
float srate = base->mix_rate;
- srate*=p_rate_scale;
+ srate *= p_rate_scale;
float fincrement = srate / base_rate;
int32_t increment = int32_t(fincrement * MIX_FRAC_LEN);
- increment*=sign;
-
+ increment *= sign;
//looping
- AudioStreamSample::LoopMode loop_format=base->loop_mode;
+ AudioStreamSample::LoopMode loop_format = base->loop_mode;
AudioStreamSample::Format format = base->format;
-
/* audio data */
- uint8_t *dataptr=(uint8_t*)base->data;
- const void *data=dataptr+AudioStreamSample::DATA_PAD;
- AudioFrame *dst_buff=p_buffer;
-
+ uint8_t *dataptr = (uint8_t *)base->data;
+ const void *data = dataptr + AudioStreamSample::DATA_PAD;
+ AudioFrame *dst_buff = p_buffer;
- if (format==AudioStreamSample::FORMAT_IMA_ADPCM) {
+ if (format == AudioStreamSample::FORMAT_IMA_ADPCM) {
- if (loop_format!=AudioStreamSample::LOOP_DISABLED) {
- ima_adpcm[0].loop_pos=loop_begin_fp>>MIX_FRAC_BITS;
- ima_adpcm[1].loop_pos=loop_begin_fp>>MIX_FRAC_BITS;
- loop_format=AudioStreamSample::LOOP_FORWARD;
+ if (loop_format != AudioStreamSample::LOOP_DISABLED) {
+ ima_adpcm[0].loop_pos = loop_begin_fp >> MIX_FRAC_BITS;
+ ima_adpcm[1].loop_pos = loop_begin_fp >> MIX_FRAC_BITS;
+ loop_format = AudioStreamSample::LOOP_FORWARD;
}
}
- while (todo>0) {
+ while (todo > 0) {
- int64_t limit=0;
- int32_t target=0,aux=0;
+ int64_t limit = 0;
+ int32_t target = 0, aux = 0;
/** LOOP CHECKING **/
- if ( increment < 0 ) {
+ if (increment < 0) {
/* going backwards */
- if ( loop_format!=AudioStreamSample::LOOP_DISABLED && offset < loop_begin_fp ) {
+ if (loop_format != AudioStreamSample::LOOP_DISABLED && offset < loop_begin_fp) {
/* loopstart reached */
- if ( loop_format==AudioStreamSample::LOOP_PING_PONG ) {
+ if (loop_format == AudioStreamSample::LOOP_PING_PONG) {
/* bounce ping pong */
- offset= loop_begin_fp + ( loop_begin_fp-offset );
- increment=-increment;
- sign*=-1;
+ offset = loop_begin_fp + (loop_begin_fp - offset);
+ increment = -increment;
+ sign *= -1;
} else {
/* go to loop-end */
- offset=loop_end_fp-(loop_begin_fp-offset);
+ offset = loop_end_fp - (loop_begin_fp - offset);
}
} else {
/* check for sample not reaching begining */
- if(offset < 0) {
+ if (offset < 0) {
- active=false;
+ active = false;
break;
}
}
} else {
/* going forward */
- if( loop_format!=AudioStreamSample::LOOP_DISABLED && offset >= loop_end_fp ) {
+ if (loop_format != AudioStreamSample::LOOP_DISABLED && offset >= loop_end_fp) {
/* loopend reached */
- if ( loop_format==AudioStreamSample::LOOP_PING_PONG ) {
+ if (loop_format == AudioStreamSample::LOOP_PING_PONG) {
/* bounce ping pong */
- offset=loop_end_fp-(offset-loop_end_fp);
- increment=-increment;
- sign*=-1;
+ offset = loop_end_fp - (offset - loop_end_fp);
+ increment = -increment;
+ sign *= -1;
} else {
/* go to loop-begin */
- if (format==AudioStreamSample::FORMAT_IMA_ADPCM) {
- for(int i=0;i<2;i++) {
- ima_adpcm[i].step_index=ima_adpcm[i].loop_step_index;
- ima_adpcm[i].predictor=ima_adpcm[i].loop_predictor;
- ima_adpcm[i].last_nibble=loop_begin_fp>>MIX_FRAC_BITS;
+ if (format == AudioStreamSample::FORMAT_IMA_ADPCM) {
+ for (int i = 0; i < 2; i++) {
+ ima_adpcm[i].step_index = ima_adpcm[i].loop_step_index;
+ ima_adpcm[i].predictor = ima_adpcm[i].loop_predictor;
+ ima_adpcm[i].last_nibble = loop_begin_fp >> MIX_FRAC_BITS;
}
- offset=loop_begin_fp;
+ offset = loop_begin_fp;
} else {
- offset=loop_begin_fp+(offset-loop_end_fp);
+ offset = loop_begin_fp + (offset - loop_end_fp);
}
-
}
} else {
/* no loop, check for end of sample */
- if(offset >= length_fp) {
+ if (offset >= length_fp) {
- active=false;
+ active = false;
break;
}
}
@@ -347,160 +333,151 @@ void AudioStreamPlaybackSample::mix(AudioFrame* p_buffer,float p_rate_scale,int
/** MIXCOUNT COMPUTING **/
/* next possible limit (looppoints or sample begin/end */
- limit=(increment < 0) ?begin_limit:end_limit;
+ limit = (increment < 0) ? begin_limit : end_limit;
/* compute what is shorter, the todo or the limit? */
- aux=(limit-offset)/increment+1;
- target=(aux<todo)?aux:todo; /* mix target is the shorter buffer */
+ aux = (limit - offset) / increment + 1;
+ target = (aux < todo) ? aux : todo; /* mix target is the shorter buffer */
/* check just in case */
- if ( target<=0 ) {
- active=false;
+ if (target <= 0) {
+ active = false;
break;
}
- todo-=target;
+ todo -= target;
- switch(base->format) {
+ switch (base->format) {
case AudioStreamSample::FORMAT_8_BITS: {
if (is_stereo)
- do_resample<int8_t,true,false>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int8_t, true, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm);
else
- do_resample<int8_t,false,false>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int8_t, false, false>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm);
} break;
case AudioStreamSample::FORMAT_16_BITS: {
if (is_stereo)
- do_resample<int16_t,true,false>((int16_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int16_t, true, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm);
else
- do_resample<int16_t,false,false>((int16_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int16_t, false, false>((int16_t *)data, dst_buff, offset, increment, target, ima_adpcm);
} break;
case AudioStreamSample::FORMAT_IMA_ADPCM: {
if (is_stereo)
- do_resample<int8_t,true,true>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int8_t, true, true>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm);
else
- do_resample<int8_t,false,true>((int8_t*)data,dst_buff,offset,increment,target,ima_adpcm);
+ do_resample<int8_t, false, true>((int8_t *)data, dst_buff, offset, increment, target, ima_adpcm);
} break;
}
- dst_buff+=target;
-
+ dst_buff += target;
}
-
-
}
float AudioStreamPlaybackSample::get_length() const {
int len = base->data_bytes;
- switch(base->format) {
- case AudioStreamSample::FORMAT_8_BITS: len/=1; break;
- case AudioStreamSample::FORMAT_16_BITS: len/=2; break;
- case AudioStreamSample::FORMAT_IMA_ADPCM: len*=2; break;
+ switch (base->format) {
+ case AudioStreamSample::FORMAT_8_BITS: len /= 1; break;
+ case AudioStreamSample::FORMAT_16_BITS: len /= 2; break;
+ case AudioStreamSample::FORMAT_IMA_ADPCM: len *= 2; break;
}
if (base->stereo) {
- len/=2;
+ len /= 2;
}
-
- return float(len)/base->mix_rate;
+ return float(len) / base->mix_rate;
}
-
AudioStreamPlaybackSample::AudioStreamPlaybackSample() {
- active=false;
- offset=0;
- sign=1;
+ active = false;
+ offset = 0;
+ sign = 1;
}
-
/////////////////////
-
void AudioStreamSample::set_format(Format p_format) {
- format=p_format;
+ format = p_format;
}
-AudioStreamSample::Format AudioStreamSample::get_format() const{
+AudioStreamSample::Format AudioStreamSample::get_format() const {
return format;
}
-void AudioStreamSample::set_loop_mode(LoopMode p_loop_mode){
+void AudioStreamSample::set_loop_mode(LoopMode p_loop_mode) {
- loop_mode=p_loop_mode;
+ loop_mode = p_loop_mode;
}
-AudioStreamSample::LoopMode AudioStreamSample::get_loop_mode() const{
+AudioStreamSample::LoopMode AudioStreamSample::get_loop_mode() const {
return loop_mode;
}
-void AudioStreamSample::set_loop_begin(int p_frame){
+void AudioStreamSample::set_loop_begin(int p_frame) {
- loop_begin=p_frame;
+ loop_begin = p_frame;
}
-int AudioStreamSample::get_loop_begin() const{
+int AudioStreamSample::get_loop_begin() const {
return loop_begin;
}
-void AudioStreamSample::set_loop_end(int p_frame){
+void AudioStreamSample::set_loop_end(int p_frame) {
- loop_end=p_frame;
+ loop_end = p_frame;
}
-int AudioStreamSample::get_loop_end() const{
+int AudioStreamSample::get_loop_end() const {
return loop_end;
}
+void AudioStreamSample::set_mix_rate(int p_hz) {
-void AudioStreamSample::set_mix_rate(int p_hz){
-
- mix_rate=p_hz;
+ mix_rate = p_hz;
}
-int AudioStreamSample::get_mix_rate() const{
+int AudioStreamSample::get_mix_rate() const {
return mix_rate;
}
-void AudioStreamSample::set_stereo(bool p_enable){
+void AudioStreamSample::set_stereo(bool p_enable) {
- stereo=p_enable;
+ stereo = p_enable;
}
-bool AudioStreamSample::is_stereo() const{
+bool AudioStreamSample::is_stereo() const {
return stereo;
}
-void AudioStreamSample::set_data(const PoolVector<uint8_t>& p_data) {
+void AudioStreamSample::set_data(const PoolVector<uint8_t> &p_data) {
AudioServer::get_singleton()->lock();
if (data) {
AudioServer::get_singleton()->audio_data_free(data);
- data=NULL;
- data_bytes=0;
+ data = NULL;
+ data_bytes = 0;
}
int datalen = p_data.size();
if (datalen) {
PoolVector<uint8_t>::Read r = p_data.read();
- int alloc_len = datalen+DATA_PAD*2;
+ int alloc_len = datalen + DATA_PAD * 2;
data = AudioServer::get_singleton()->audio_data_alloc(alloc_len); //alloc with some padding for interpolation
- zeromem(data,alloc_len);
- uint8_t *dataptr=(uint8_t*)data;
- copymem(dataptr+DATA_PAD,r.ptr(),datalen);
- data_bytes=datalen;
+ zeromem(data, alloc_len);
+ uint8_t *dataptr = (uint8_t *)data;
+ copymem(dataptr + DATA_PAD, r.ptr(), datalen);
+ data_bytes = datalen;
}
AudioServer::get_singleton()->unlock();
-
}
-PoolVector<uint8_t> AudioStreamSample::get_data() const{
+PoolVector<uint8_t> AudioStreamSample::get_data() const {
PoolVector<uint8_t> pv;
@@ -508,20 +485,19 @@ PoolVector<uint8_t> AudioStreamSample::get_data() const{
pv.resize(data_bytes);
{
- PoolVector<uint8_t>::Write w =pv.write();
- copymem(w.ptr(),data,data_bytes);
+ PoolVector<uint8_t>::Write w = pv.write();
+ copymem(w.ptr(), data, data_bytes);
}
}
return pv;
}
-
Ref<AudioStreamPlayback> AudioStreamSample::instance_playback() {
Ref<AudioStreamPlaybackSample> sample;
sample.instance();
- sample->base=Ref<AudioStreamSample>(this);
+ sample->base = Ref<AudioStreamSample>(this);
return sample;
}
@@ -532,54 +508,51 @@ String AudioStreamSample::get_stream_name() const {
void AudioStreamSample::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_format","format"),&AudioStreamSample::set_format);
- ClassDB::bind_method(D_METHOD("get_format"),&AudioStreamSample::get_format);
-
- ClassDB::bind_method(D_METHOD("set_loop_mode","loop_mode"),&AudioStreamSample::set_loop_mode);
- ClassDB::bind_method(D_METHOD("get_loop_mode"),&AudioStreamSample::get_loop_mode);
+ ClassDB::bind_method(D_METHOD("set_format", "format"), &AudioStreamSample::set_format);
+ ClassDB::bind_method(D_METHOD("get_format"), &AudioStreamSample::get_format);
- ClassDB::bind_method(D_METHOD("set_loop_begin","loop_begin"),&AudioStreamSample::set_loop_begin);
- ClassDB::bind_method(D_METHOD("get_loop_begin"),&AudioStreamSample::get_loop_begin);
+ ClassDB::bind_method(D_METHOD("set_loop_mode", "loop_mode"), &AudioStreamSample::set_loop_mode);
+ ClassDB::bind_method(D_METHOD("get_loop_mode"), &AudioStreamSample::get_loop_mode);
- ClassDB::bind_method(D_METHOD("set_loop_end","loop_end"),&AudioStreamSample::set_loop_end);
- ClassDB::bind_method(D_METHOD("get_loop_end"),&AudioStreamSample::get_loop_end);
+ ClassDB::bind_method(D_METHOD("set_loop_begin", "loop_begin"), &AudioStreamSample::set_loop_begin);
+ ClassDB::bind_method(D_METHOD("get_loop_begin"), &AudioStreamSample::get_loop_begin);
- ClassDB::bind_method(D_METHOD("set_mix_rate","mix_rate"),&AudioStreamSample::set_mix_rate);
- ClassDB::bind_method(D_METHOD("get_mix_rate"),&AudioStreamSample::get_mix_rate);
+ ClassDB::bind_method(D_METHOD("set_loop_end", "loop_end"), &AudioStreamSample::set_loop_end);
+ ClassDB::bind_method(D_METHOD("get_loop_end"), &AudioStreamSample::get_loop_end);
- ClassDB::bind_method(D_METHOD("set_stereo","stereo"),&AudioStreamSample::set_stereo);
- ClassDB::bind_method(D_METHOD("is_stereo"),&AudioStreamSample::is_stereo);
+ ClassDB::bind_method(D_METHOD("set_mix_rate", "mix_rate"), &AudioStreamSample::set_mix_rate);
+ ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioStreamSample::get_mix_rate);
- ClassDB::bind_method(D_METHOD("set_data","data"),&AudioStreamSample::set_data);
- ClassDB::bind_method(D_METHOD("get_data"),&AudioStreamSample::get_data);
+ ClassDB::bind_method(D_METHOD("set_stereo", "stereo"), &AudioStreamSample::set_stereo);
+ ClassDB::bind_method(D_METHOD("is_stereo"), &AudioStreamSample::is_stereo);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"format",PROPERTY_HINT_ENUM,"8-Bit,16-Bit,IMA-ADPCM"),"set_format","get_format");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_mode",PROPERTY_HINT_ENUM,"Disabled,Forward,Ping-Pong"),"set_loop_mode","get_loop_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_begin"),"set_loop_begin","get_loop_begin");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"loop_end"),"set_loop_end","get_loop_end");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"mix_rate"),"set_mix_rate","get_mix_rate");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"stereo"),"set_stereo","is_stereo");
- ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"set_data","get_data");
+ ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamSample::set_data);
+ ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamSample::get_data);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "format", PROPERTY_HINT_ENUM, "8-Bit,16-Bit,IMA-ADPCM"), "set_format", "get_format");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_mode", PROPERTY_HINT_ENUM, "Disabled,Forward,Ping-Pong"), "set_loop_mode", "get_loop_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_begin"), "set_loop_begin", "get_loop_begin");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "loop_end"), "set_loop_end", "get_loop_end");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mix_rate"), "set_mix_rate", "get_mix_rate");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stereo"), "set_stereo", "is_stereo");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data");
}
-AudioStreamSample::AudioStreamSample()
-{
- format=FORMAT_8_BITS;
- loop_mode=LOOP_DISABLED;
- stereo=false;
- loop_begin=0;
- loop_end=0;
- mix_rate=44100;
- data=NULL;
- data_bytes=0;
+AudioStreamSample::AudioStreamSample() {
+ format = FORMAT_8_BITS;
+ loop_mode = LOOP_DISABLED;
+ stereo = false;
+ loop_begin = 0;
+ loop_end = 0;
+ mix_rate = 44100;
+ data = NULL;
+ data_bytes = 0;
}
AudioStreamSample::~AudioStreamSample() {
-
if (data) {
AudioServer::get_singleton()->audio_data_free(data);
- data=NULL;
- data_bytes=0;
+ data = NULL;
+ data_bytes = 0;
}
}
diff --git a/scene/resources/audio_stream_sample.h b/scene/resources/audio_stream_sample.h
index 53e628c0e4..d5d1ae79c0 100644
--- a/scene/resources/audio_stream_sample.h
+++ b/scene/resources/audio_stream_sample.h
@@ -31,16 +31,15 @@
#include "servers/audio/audio_stream.h"
-
class AudioStreamSample;
class AudioStreamPlaybackSample : public AudioStreamPlayback {
- GDCLASS( AudioStreamPlaybackSample, AudioStreamPlayback )
+ GDCLASS(AudioStreamPlaybackSample, AudioStreamPlayback)
enum {
- MIX_FRAC_BITS=13,
- MIX_FRAC_LEN=(1<<MIX_FRAC_BITS),
- MIX_FRAC_MASK=MIX_FRAC_LEN-1,
+ MIX_FRAC_BITS = 13,
+ MIX_FRAC_LEN = (1 << MIX_FRAC_BITS),
+ MIX_FRAC_MASK = MIX_FRAC_LEN - 1,
};
struct IMA_ADPCM_State {
@@ -59,14 +58,14 @@ class AudioStreamPlaybackSample : public AudioStreamPlayback {
int64_t offset;
int sign;
bool active;
-friend class AudioStreamSample;
+ friend class AudioStreamSample;
Ref<AudioStreamSample> base;
- template<class Depth,bool is_stereo,bool is_ima_adpcm>
- void do_resample(const Depth* p_src, AudioFrame *p_dst,int64_t &offset,int32_t &increment,uint32_t amount,IMA_ADPCM_State *ima_adpcm);
-public:
+ template <class Depth, bool is_stereo, bool is_ima_adpcm>
+ void do_resample(const Depth *p_src, AudioFrame *p_dst, int64_t &offset, int32_t &increment, uint32_t amount, IMA_ADPCM_State *ima_adpcm);
- virtual void start(float p_from_pos=0.0);
+public:
+ virtual void start(float p_from_pos = 0.0);
virtual void stop();
virtual bool is_playing() const;
@@ -75,20 +74,18 @@ public:
virtual float get_pos() const;
virtual void seek_pos(float p_time);
- virtual void mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames);
+ virtual void mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames);
virtual float get_length() const; //if supported, otherwise return 0
-
AudioStreamPlaybackSample();
};
class AudioStreamSample : public AudioStream {
- GDCLASS(AudioStreamSample,AudioStream)
+ GDCLASS(AudioStreamSample, AudioStream)
RES_BASE_EXTENSION("smp")
public:
-
enum Format {
FORMAT_8_BITS,
FORMAT_16_BITS,
@@ -101,12 +98,11 @@ public:
LOOP_PING_PONG
};
-
private:
-friend class AudioStreamPlaybackSample;
+ friend class AudioStreamPlaybackSample;
enum {
- DATA_PAD=16 //padding for interpolation
+ DATA_PAD = 16 //padding for interpolation
};
Format format;
@@ -117,9 +113,10 @@ friend class AudioStreamPlaybackSample;
int mix_rate;
void *data;
uint32_t data_bytes;
-protected:
+protected:
static void _bind_methods();
+
public:
void set_format(Format p_format);
Format get_format() const;
@@ -139,10 +136,9 @@ public:
void set_stereo(bool p_enable);
bool is_stereo() const;
- void set_data(const PoolVector<uint8_t>& p_data);
+ void set_data(const PoolVector<uint8_t> &p_data);
PoolVector<uint8_t> get_data() const;
-
virtual Ref<AudioStreamPlayback> instance_playback();
virtual String get_stream_name() const;
diff --git a/scene/resources/baked_light.cpp b/scene/resources/baked_light.cpp
index 616c12e8d7..7fa930fd58 100644
--- a/scene/resources/baked_light.cpp
+++ b/scene/resources/baked_light.cpp
@@ -28,4 +28,3 @@
/*************************************************************************/
#include "baked_light.h"
#include "servers/visual_server.h"
-
diff --git a/scene/resources/baked_light.h b/scene/resources/baked_light.h
index 0c69ce429e..7dee40b34e 100644
--- a/scene/resources/baked_light.h
+++ b/scene/resources/baked_light.h
@@ -32,6 +32,4 @@
#include "resource.h"
#include "scene/resources/texture.h"
-
-
#endif // BAKED_LIGHT_H
diff --git a/scene/resources/bit_mask.cpp b/scene/resources/bit_mask.cpp
index 4ceac5af0c..277acad905 100644
--- a/scene/resources/bit_mask.cpp
+++ b/scene/resources/bit_mask.cpp
@@ -29,177 +29,166 @@
#include "bit_mask.h"
#include "io/image_loader.h"
-void BitMap::create(const Size2& p_size) {
+void BitMap::create(const Size2 &p_size) {
- ERR_FAIL_COND(p_size.width<1);
- ERR_FAIL_COND(p_size.height<1);
-
- width=p_size.width;
- height=p_size.height;
- bitmask.resize(((width*height)/8)+1);
- zeromem(bitmask.ptr(),bitmask.size());
+ ERR_FAIL_COND(p_size.width < 1);
+ ERR_FAIL_COND(p_size.height < 1);
+ width = p_size.width;
+ height = p_size.height;
+ bitmask.resize(((width * height) / 8) + 1);
+ zeromem(bitmask.ptr(), bitmask.size());
}
-void BitMap::create_from_image_alpha(const Image& p_image){
+void BitMap::create_from_image_alpha(const Image &p_image) {
ERR_FAIL_COND(p_image.empty());
- Image img=p_image;
+ Image img = p_image;
img.convert(Image::FORMAT_LA8);
- ERR_FAIL_COND(img.get_format()!=Image::FORMAT_LA8);
-
- create(Size2(img.get_width(),img.get_height()));
+ ERR_FAIL_COND(img.get_format() != Image::FORMAT_LA8);
+ create(Size2(img.get_width(), img.get_height()));
PoolVector<uint8_t>::Read r = img.get_data().read();
uint8_t *w = bitmask.ptr();
- for(int i=0;i<width*height;i++) {
+ for (int i = 0; i < width * height; i++) {
- int bbyte = i/8;
+ int bbyte = i / 8;
int bbit = i % 8;
- if (r[i*2])
- w[bbyte]|=(1<<bbit);
+ if (r[i * 2])
+ w[bbyte] |= (1 << bbit);
}
-
}
+void BitMap::set_bit_rect(const Rect2 &p_rect, bool p_value) {
-void BitMap::set_bit_rect(const Rect2& p_rect,bool p_value) {
-
- Rect2i current = Rect2i(0,0,width,height).clip(p_rect);
+ Rect2i current = Rect2i(0, 0, width, height).clip(p_rect);
uint8_t *data = bitmask.ptr();
- for(int i=current.pos.x;i<current.pos.x+current.size.x;i++) {
-
- for(int j=current.pos.y;j<current.pos.y+current.size.y;j++) {
+ for (int i = current.pos.x; i < current.pos.x + current.size.x; i++) {
+ for (int j = current.pos.y; j < current.pos.y + current.size.y; j++) {
int ofs = width * j + i;
- int bbyte = ofs/8;
+ int bbyte = ofs / 8;
int bbit = ofs % 8;
uint8_t b = data[bbyte];
if (p_value)
- b|=(1<<bbit);
+ b |= (1 << bbit);
else
- b&=!(1<<bbit);
-
- data[bbyte]=b;
+ b &= !(1 << bbit);
+ data[bbyte] = b;
}
}
-
}
int BitMap::get_true_bit_count() const {
int ds = bitmask.size();
const uint8_t *d = bitmask.ptr();
- int c=0;
+ int c = 0;
-//fast, almot branchless version
+ //fast, almot branchless version
- for(int i=0;i<ds;i++) {
+ for (int i = 0; i < ds; i++) {
- c+=(d[i]&(1<<7))>>7;
- c+=(d[i]&(1<<6))>>6;
- c+=(d[i]&(1<<5))>>5;
- c+=(d[i]&(1<<4))>>4;
- c+=(d[i]&(1<<3))>>3;
- c+=(d[i]&(1<<2))>>2;
- c+=d[i]&1;
+ c += (d[i] & (1 << 7)) >> 7;
+ c += (d[i] & (1 << 6)) >> 6;
+ c += (d[i] & (1 << 5)) >> 5;
+ c += (d[i] & (1 << 4)) >> 4;
+ c += (d[i] & (1 << 3)) >> 3;
+ c += (d[i] & (1 << 2)) >> 2;
+ c += d[i] & 1;
}
return c;
}
+void BitMap::set_bit(const Point2 &p_pos, bool p_value) {
-void BitMap::set_bit(const Point2& p_pos,bool p_value){
-
- int x=Math::fast_ftoi(p_pos.x);
- int y=Math::fast_ftoi(p_pos.y);
+ int x = Math::fast_ftoi(p_pos.x);
+ int y = Math::fast_ftoi(p_pos.y);
- ERR_FAIL_INDEX(x,width);
- ERR_FAIL_INDEX(y,height);
+ ERR_FAIL_INDEX(x, width);
+ ERR_FAIL_INDEX(y, height);
int ofs = width * y + x;
- int bbyte = ofs/8;
+ int bbyte = ofs / 8;
int bbit = ofs % 8;
uint8_t b = bitmask[bbyte];
if (p_value)
- b|=(1<<bbit);
+ b |= (1 << bbit);
else
- b&=!(1<<bbit);
+ b &= !(1 << bbit);
- bitmask[bbyte]=b;
+ bitmask[bbyte] = b;
}
-bool BitMap::get_bit(const Point2& p_pos) const{
+bool BitMap::get_bit(const Point2 &p_pos) const {
- int x=Math::fast_ftoi(p_pos.x);
- int y=Math::fast_ftoi(p_pos.y);
- ERR_FAIL_INDEX_V(x,width,false);
- ERR_FAIL_INDEX_V(y,height,false);
+ int x = Math::fast_ftoi(p_pos.x);
+ int y = Math::fast_ftoi(p_pos.y);
+ ERR_FAIL_INDEX_V(x, width, false);
+ ERR_FAIL_INDEX_V(y, height, false);
int ofs = width * y + x;
- int bbyte = ofs/8;
+ int bbyte = ofs / 8;
int bbit = ofs % 8;
- return (bitmask[bbyte]&(1<<bbit))!=0;
-
+ return (bitmask[bbyte] & (1 << bbit)) != 0;
}
Size2 BitMap::get_size() const {
- return Size2(width,height);
+ return Size2(width, height);
}
-void BitMap::_set_data(const Dictionary& p_d) {
+void BitMap::_set_data(const Dictionary &p_d) {
ERR_FAIL_COND(!p_d.has("size"));
ERR_FAIL_COND(!p_d.has("data"));
create(p_d["size"]);
- bitmask=p_d["data"];
+ bitmask = p_d["data"];
}
-Dictionary BitMap::_get_data() const{
+Dictionary BitMap::_get_data() const {
Dictionary d;
- d["size"]=get_size();
- d["data"]=bitmask;
+ d["size"] = get_size();
+ d["data"] = bitmask;
return d;
}
void BitMap::_bind_methods() {
- ClassDB::bind_method(D_METHOD("create","size"),&BitMap::create);
- ClassDB::bind_method(D_METHOD("create_from_image_alpha","image"),&BitMap::create_from_image_alpha);
+ ClassDB::bind_method(D_METHOD("create", "size"), &BitMap::create);
+ ClassDB::bind_method(D_METHOD("create_from_image_alpha", "image"), &BitMap::create_from_image_alpha);
- ClassDB::bind_method(D_METHOD("set_bit","pos","bit"),&BitMap::set_bit);
- ClassDB::bind_method(D_METHOD("get_bit","pos"),&BitMap::get_bit);
+ ClassDB::bind_method(D_METHOD("set_bit", "pos", "bit"), &BitMap::set_bit);
+ ClassDB::bind_method(D_METHOD("get_bit", "pos"), &BitMap::get_bit);
- ClassDB::bind_method(D_METHOD("set_bit_rect","p_rect","bit"),&BitMap::set_bit_rect);
- ClassDB::bind_method(D_METHOD("get_true_bit_count"),&BitMap::get_true_bit_count);
+ ClassDB::bind_method(D_METHOD("set_bit_rect", "p_rect", "bit"), &BitMap::set_bit_rect);
+ ClassDB::bind_method(D_METHOD("get_true_bit_count"), &BitMap::get_true_bit_count);
- ClassDB::bind_method(D_METHOD("get_size"),&BitMap::get_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &BitMap::get_size);
- ClassDB::bind_method(D_METHOD("_set_data"),&BitMap::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"),&BitMap::_get_data);
-
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_data","_get_data");
+ ClassDB::bind_method(D_METHOD("_set_data"), &BitMap::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &BitMap::_get_data);
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
}
BitMap::BitMap() {
- width=0;
- height=0;
+ width = 0;
+ height = 0;
}
//////////////////////////////////////
-
diff --git a/scene/resources/bit_mask.h b/scene/resources/bit_mask.h
index f749a53e34..3cee2279b8 100644
--- a/scene/resources/bit_mask.h
+++ b/scene/resources/bit_mask.h
@@ -29,13 +29,12 @@
#ifndef BIT_MASK_H
#define BIT_MASK_H
-#include "resource.h"
#include "io/resource_loader.h"
-
+#include "resource.h"
class BitMap : public Resource {
- GDCLASS(BitMap,Resource);
+ GDCLASS(BitMap, Resource);
OBJ_SAVE_TYPE(BitMap);
RES_BASE_EXTENSION("pbm");
@@ -44,19 +43,18 @@ class BitMap : public Resource {
int height;
protected:
- void _set_data(const Dictionary& p_d);
+ void _set_data(const Dictionary &p_d);
Dictionary _get_data() const;
static void _bind_methods();
-public:
+public:
+ void create(const Size2 &p_size);
+ void create_from_image_alpha(const Image &p_image);
- void create(const Size2& p_size);
- void create_from_image_alpha(const Image& p_image);
-
- void set_bit(const Point2& p_pos,bool p_value);
- bool get_bit(const Point2& p_pos) const;
- void set_bit_rect(const Rect2& p_rect,bool p_value);
+ void set_bit(const Point2 &p_pos, bool p_value);
+ bool get_bit(const Point2 &p_pos) const;
+ void set_bit_rect(const Rect2 &p_rect, bool p_value);
int get_true_bit_count() const;
Size2 get_size() const;
@@ -64,5 +62,4 @@ public:
BitMap();
};
-
#endif // BIT_MASK_H
diff --git a/scene/resources/bounds.cpp b/scene/resources/bounds.cpp
index 26bf6270e9..974ff76cd0 100644
--- a/scene/resources/bounds.cpp
+++ b/scene/resources/bounds.cpp
@@ -28,19 +28,17 @@
/*************************************************************************/
#include "bounds.h"
-
void Bounds::_bind_methods() {
- ClassDB::bind_method( D_METHOD("set_bsp_tree","bsp_tree"),&Bounds::set_bsp_tree);
- ClassDB::bind_method( D_METHOD("get_bsp_tree"),&Bounds::get_bsp_tree );
-
- ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "bsp_tree" ), "set_bsp_tree", "get_bsp_tree");
+ ClassDB::bind_method(D_METHOD("set_bsp_tree", "bsp_tree"), &Bounds::set_bsp_tree);
+ ClassDB::bind_method(D_METHOD("get_bsp_tree"), &Bounds::get_bsp_tree);
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "bsp_tree"), "set_bsp_tree", "get_bsp_tree");
}
-void Bounds::set_bsp_tree(const BSP_Tree& p_bsp_tree) {
+void Bounds::set_bsp_tree(const BSP_Tree &p_bsp_tree) {
- bsp_tree=p_bsp_tree;
+ bsp_tree = p_bsp_tree;
}
BSP_Tree Bounds::get_bsp_tree() const {
@@ -48,7 +46,5 @@ BSP_Tree Bounds::get_bsp_tree() const {
return bsp_tree;
}
-
-Bounds::Bounds()
-{
+Bounds::Bounds() {
}
diff --git a/scene/resources/bounds.h b/scene/resources/bounds.h
index bd5d996a36..62e1b8e0ef 100644
--- a/scene/resources/bounds.h
+++ b/scene/resources/bounds.h
@@ -29,21 +29,19 @@
#ifndef BOUNDS_H
#define BOUNDS_H
-#include "resource.h"
#include "bsp_tree.h"
+#include "resource.h"
class Bounds : public Resource {
- GDCLASS(Bounds,Resource);
+ GDCLASS(Bounds, Resource);
BSP_Tree bsp_tree;
protected:
-
static void _bind_methods();
public:
-
- void set_bsp_tree(const BSP_Tree& p_bsp_tree);
+ void set_bsp_tree(const BSP_Tree &p_bsp_tree);
BSP_Tree get_bsp_tree() const;
Bounds();
diff --git a/scene/resources/box_shape.cpp b/scene/resources/box_shape.cpp
index e8eccaceae..1e9991d7dc 100644
--- a/scene/resources/box_shape.cpp
+++ b/scene/resources/box_shape.cpp
@@ -29,34 +29,31 @@
#include "box_shape.h"
#include "servers/physics_server.h"
-
Vector<Vector3> BoxShape::_gen_debug_mesh_lines() {
-
Vector<Vector3> lines;
Rect3 aabb;
- aabb.pos=-get_extents();
- aabb.size=aabb.pos*-2;
+ aabb.pos = -get_extents();
+ aabb.size = aabb.pos * -2;
- for(int i=0;i<12;i++) {
- Vector3 a,b;
- aabb.get_edge(i,a,b);
+ for (int i = 0; i < 12; i++) {
+ Vector3 a, b;
+ aabb.get_edge(i, a, b);
lines.push_back(a);
lines.push_back(b);
}
-
return lines;
}
void BoxShape::_update_shape() {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),extents);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), extents);
}
-void BoxShape::set_extents(const Vector3& p_extents) {
+void BoxShape::set_extents(const Vector3 &p_extents) {
- extents=p_extents;
+ extents = p_extents;
_update_shape();
notify_change_to_owners();
_change_notify("extents");
@@ -67,17 +64,16 @@ Vector3 BoxShape::get_extents() const {
return extents;
}
-
void BoxShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents","extents"),&BoxShape::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"),&BoxShape::get_extents);
-
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"extents"), "set_extents", "get_extents") ;
+ ClassDB::bind_method(D_METHOD("set_extents", "extents"), &BoxShape::set_extents);
+ ClassDB::bind_method(D_METHOD("get_extents"), &BoxShape::get_extents);
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, "extents"), "set_extents", "get_extents");
}
-BoxShape::BoxShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_BOX)) {
+BoxShape::BoxShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_BOX)) {
- set_extents(Vector3(1,1,1));
+ set_extents(Vector3(1, 1, 1));
}
diff --git a/scene/resources/box_shape.h b/scene/resources/box_shape.h
index c17dd22015..2bab6d9b8a 100644
--- a/scene/resources/box_shape.h
+++ b/scene/resources/box_shape.h
@@ -33,19 +33,17 @@
class BoxShape : public Shape {
- GDCLASS(BoxShape,Shape);
+ GDCLASS(BoxShape, Shape);
Vector3 extents;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
public:
-
- void set_extents(const Vector3& p_extents);
+ void set_extents(const Vector3 &p_extents);
Vector3 get_extents() const;
BoxShape();
diff --git a/scene/resources/canvas.cpp b/scene/resources/canvas.cpp
index bda97141cc..dd0375b765 100644
--- a/scene/resources/canvas.cpp
+++ b/scene/resources/canvas.cpp
@@ -36,11 +36,9 @@ RID Canvas::get_rid() const {
Canvas::Canvas() {
- canvas=VisualServer::get_singleton()->canvas_create();
+ canvas = VisualServer::get_singleton()->canvas_create();
}
-
Canvas::~Canvas() {
VisualServer::get_singleton()->free(canvas);
}
-
diff --git a/scene/resources/canvas.h b/scene/resources/canvas.h
index 960136ac14..1d3775c30c 100644
--- a/scene/resources/canvas.h
+++ b/scene/resources/canvas.h
@@ -29,17 +29,15 @@
#ifndef CANVAS_H
#define CANVAS_H
-
#include "resource.h"
class Canvas : public Resource {
- GDCLASS(Canvas,Resource);
+ GDCLASS(Canvas, Resource);
RID canvas;
public:
-
virtual RID get_rid() const;
Canvas();
~Canvas();
diff --git a/scene/resources/capsule_shape.cpp b/scene/resources/capsule_shape.cpp
index bd30f009c4..1aa3fee0ca 100644
--- a/scene/resources/capsule_shape.cpp
+++ b/scene/resources/capsule_shape.cpp
@@ -29,43 +29,39 @@
#include "capsule_shape.h"
#include "servers/physics_server.h"
-
Vector<Vector3> CapsuleShape::_gen_debug_mesh_lines() {
-
float radius = get_radius();
float height = get_height();
-
Vector<Vector3> points;
- Vector3 d(0,0,height*0.5);
- for(int i=0;i<360;i++) {
+ Vector3 d(0, 0, height * 0.5);
+ for (int i = 0; i < 360; i++) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*radius;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*radius;
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * radius;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * radius;
- points.push_back(Vector3(a.x,a.y,0)+d);
- points.push_back(Vector3(b.x,b.y,0)+d);
+ points.push_back(Vector3(a.x, a.y, 0) + d);
+ points.push_back(Vector3(b.x, b.y, 0) + d);
- points.push_back(Vector3(a.x,a.y,0)-d);
- points.push_back(Vector3(b.x,b.y,0)-d);
+ points.push_back(Vector3(a.x, a.y, 0) - d);
+ points.push_back(Vector3(b.x, b.y, 0) - d);
- if (i%90==0) {
+ if (i % 90 == 0) {
- points.push_back(Vector3(a.x,a.y,0)+d);
- points.push_back(Vector3(a.x,a.y,0)-d);
+ points.push_back(Vector3(a.x, a.y, 0) + d);
+ points.push_back(Vector3(a.x, a.y, 0) - d);
}
- Vector3 dud = i<180?d:-d;
-
- points.push_back(Vector3(0,a.y,a.x)+dud);
- points.push_back(Vector3(0,b.y,b.x)+dud);
- points.push_back(Vector3(a.y,0,a.x)+dud);
- points.push_back(Vector3(b.y,0,b.x)+dud);
+ Vector3 dud = i < 180 ? d : -d;
+ points.push_back(Vector3(0, a.y, a.x) + dud);
+ points.push_back(Vector3(0, b.y, b.x) + dud);
+ points.push_back(Vector3(a.y, 0, a.x) + dud);
+ points.push_back(Vector3(b.y, 0, b.x) + dud);
}
return points;
@@ -74,14 +70,14 @@ Vector<Vector3> CapsuleShape::_gen_debug_mesh_lines() {
void CapsuleShape::_update_shape() {
Dictionary d;
- d["radius"]=radius;
- d["height"]=height;
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),d);
+ d["radius"] = radius;
+ d["height"] = height;
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), d);
}
void CapsuleShape::set_radius(float p_radius) {
- radius=p_radius;
+ radius = p_radius;
_update_shape();
notify_change_to_owners();
_change_notify("radius");
@@ -94,7 +90,7 @@ float CapsuleShape::get_radius() const {
void CapsuleShape::set_height(float p_height) {
- height=p_height;
+ height = p_height;
_update_shape();
notify_change_to_owners();
_change_notify("height");
@@ -107,19 +103,19 @@ float CapsuleShape::get_height() const {
void CapsuleShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius","radius"),&CapsuleShape::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&CapsuleShape::get_radius);
- ClassDB::bind_method(D_METHOD("set_height","height"),&CapsuleShape::set_height);
- ClassDB::bind_method(D_METHOD("get_height"),&CapsuleShape::get_height);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.01,4096,0.01"), "set_radius","get_radius") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"height",PROPERTY_HINT_RANGE,"0.01,4096,0.01"), "set_height","get_height") ;
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CapsuleShape::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &CapsuleShape::get_radius);
+ ClassDB::bind_method(D_METHOD("set_height", "height"), &CapsuleShape::set_height);
+ ClassDB::bind_method(D_METHOD("get_height"), &CapsuleShape::get_height);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_radius", "get_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "0.01,4096,0.01"), "set_height", "get_height");
}
-CapsuleShape::CapsuleShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CAPSULE)) {
+CapsuleShape::CapsuleShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CAPSULE)) {
- radius=1.0;
- height=1.0;
+ radius = 1.0;
+ height = 1.0;
_update_shape();
}
diff --git a/scene/resources/capsule_shape.h b/scene/resources/capsule_shape.h
index e788d9cfc5..ecffdd8ce7 100644
--- a/scene/resources/capsule_shape.h
+++ b/scene/resources/capsule_shape.h
@@ -33,25 +33,23 @@
class CapsuleShape : public Shape {
- GDCLASS(CapsuleShape,Shape);
+ GDCLASS(CapsuleShape, Shape);
float radius;
float height;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
+public:
void set_radius(float p_radius);
float get_radius() const;
void set_height(float p_height);
float get_height() const;
-
CapsuleShape();
};
diff --git a/scene/resources/capsule_shape_2d.cpp b/scene/resources/capsule_shape_2d.cpp
index 523d6d7455..d24640e43d 100644
--- a/scene/resources/capsule_shape_2d.cpp
+++ b/scene/resources/capsule_shape_2d.cpp
@@ -33,14 +33,13 @@
void CapsuleShape2D::_update_shape() {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),Vector2(radius,height));
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), Vector2(radius, height));
emit_changed();
}
-
void CapsuleShape2D::set_radius(real_t p_radius) {
- radius=p_radius;
+ radius = p_radius;
_update_shape();
}
@@ -51,7 +50,7 @@ real_t CapsuleShape2D::get_radius() const {
void CapsuleShape2D::set_height(real_t p_height) {
- height=p_height;
+ height = p_height;
_update_shape();
}
@@ -60,50 +59,47 @@ real_t CapsuleShape2D::get_height() const {
return height;
}
-
-void CapsuleShape2D::draw(const RID& p_to_rid,const Color& p_color) {
+void CapsuleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector<Vector2> points;
- for(int i=0;i<24;i++) {
- Vector2 ofs = Vector2(0,(i>6 && i<=18) ? -get_height()*0.5 : get_height()*0.5);
+ for (int i = 0; i < 24; i++) {
+ Vector2 ofs = Vector2(0, (i > 6 && i <= 18) ? -get_height() * 0.5 : get_height() * 0.5);
- points.push_back(Vector2(Math::sin(i*Math_PI*2/24.0),Math::cos(i*Math_PI*2/24.0))*get_radius() + ofs);
- if (i==6 || i==18)
- points.push_back(Vector2(Math::sin(i*Math_PI*2/24.0),Math::cos(i*Math_PI*2/24.0))*get_radius() - ofs);
+ points.push_back(Vector2(Math::sin(i * Math_PI * 2 / 24.0), Math::cos(i * Math_PI * 2 / 24.0)) * get_radius() + ofs);
+ if (i == 6 || i == 18)
+ points.push_back(Vector2(Math::sin(i * Math_PI * 2 / 24.0), Math::cos(i * Math_PI * 2 / 24.0)) * get_radius() - ofs);
}
Vector<Color> col;
col.push_back(p_color);
- VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col);
-
+ VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col);
}
Rect2 CapsuleShape2D::get_rect() const {
- Vector2 he=Point2(get_radius(),get_radius()+get_height()*0.5);
+ Vector2 he = Point2(get_radius(), get_radius() + get_height() * 0.5);
Rect2 rect;
- rect.pos=-he;
- rect.size=he*2.0;
+ rect.pos = -he;
+ rect.size = he * 2.0;
return rect;
}
void CapsuleShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius","radius"),&CapsuleShape2D::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&CapsuleShape2D::get_radius);
-
- ClassDB::bind_method(D_METHOD("set_height","height"),&CapsuleShape2D::set_height);
- ClassDB::bind_method(D_METHOD("get_height"),&CapsuleShape2D::get_height);
-
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CapsuleShape2D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &CapsuleShape2D::get_radius);
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius"),"set_radius","get_radius") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"height"),"set_height","get_height") ;
+ ClassDB::bind_method(D_METHOD("set_height", "height"), &CapsuleShape2D::set_height);
+ ClassDB::bind_method(D_METHOD("get_height"), &CapsuleShape2D::get_height);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius"), "set_radius", "get_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "height"), "set_height", "get_height");
}
-CapsuleShape2D::CapsuleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CAPSULE)) {
+CapsuleShape2D::CapsuleShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CAPSULE)) {
- radius=10;
- height=20;
+ radius = 10;
+ height = 20;
_update_shape();
}
diff --git a/scene/resources/capsule_shape_2d.h b/scene/resources/capsule_shape_2d.h
index ef06072e14..05d819c1d5 100644
--- a/scene/resources/capsule_shape_2d.h
+++ b/scene/resources/capsule_shape_2d.h
@@ -32,25 +32,25 @@
#include "scene/resources/shape_2d.h"
class CapsuleShape2D : public Shape2D {
- GDCLASS( CapsuleShape2D, Shape2D );
+ GDCLASS(CapsuleShape2D, Shape2D);
real_t height;
real_t radius;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void set_height(real_t p_height);
real_t get_height() const;
void set_radius(real_t p_radius);
real_t get_radius() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
- virtual Rect2 get_rect() const ;
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
+ virtual Rect2 get_rect() const;
CapsuleShape2D();
};
diff --git a/scene/resources/circle_shape_2d.cpp b/scene/resources/circle_shape_2d.cpp
index cd707b1032..2271a3ad93 100644
--- a/scene/resources/circle_shape_2d.cpp
+++ b/scene/resources/circle_shape_2d.cpp
@@ -32,14 +32,13 @@
#include "servers/visual_server.h"
void CircleShape2D::_update_shape() {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),radius);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), radius);
emit_changed();
}
-
void CircleShape2D::set_radius(real_t p_radius) {
- radius=p_radius;
+ radius = p_radius;
_update_shape();
}
@@ -48,39 +47,37 @@ real_t CircleShape2D::get_radius() const {
return radius;
}
-
void CircleShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius","radius"),&CircleShape2D::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&CircleShape2D::get_radius);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0.01,16384,0.5"),"set_radius","get_radius") ;
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &CircleShape2D::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &CircleShape2D::get_radius);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0.01,16384,0.5"), "set_radius", "get_radius");
}
Rect2 CircleShape2D::get_rect() const {
Rect2 rect;
- rect.pos=-Point2(get_radius(),get_radius());
- rect.size=Point2(get_radius(),get_radius())*2.0;
+ rect.pos = -Point2(get_radius(), get_radius());
+ rect.size = Point2(get_radius(), get_radius()) * 2.0;
return rect;
}
-void CircleShape2D::draw(const RID& p_to_rid,const Color& p_color) {
+void CircleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector<Vector2> points;
- for(int i=0;i<24;i++) {
+ for (int i = 0; i < 24; i++) {
- points.push_back(Vector2(Math::cos(i*Math_PI*2/24.0),Math::sin(i*Math_PI*2/24.0))*get_radius());
+ points.push_back(Vector2(Math::cos(i * Math_PI * 2 / 24.0), Math::sin(i * Math_PI * 2 / 24.0)) * get_radius());
}
Vector<Color> col;
col.push_back(p_color);
- VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col);
-
+ VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col);
}
-CircleShape2D::CircleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CIRCLE)) {
+CircleShape2D::CircleShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CIRCLE)) {
- radius=10;
+ radius = 10;
_update_shape();
}
diff --git a/scene/resources/circle_shape_2d.h b/scene/resources/circle_shape_2d.h
index ec11b55169..11fdc51f09 100644
--- a/scene/resources/circle_shape_2d.h
+++ b/scene/resources/circle_shape_2d.h
@@ -32,22 +32,21 @@
#include "scene/resources/shape_2d.h"
class CircleShape2D : public Shape2D {
- GDCLASS( CircleShape2D, Shape2D );
+ GDCLASS(CircleShape2D, Shape2D);
real_t radius;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void set_radius(real_t p_radius);
real_t get_radius() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
virtual Rect2 get_rect() const;
-
CircleShape2D();
};
diff --git a/scene/resources/color_ramp.cpp b/scene/resources/color_ramp.cpp
index b14ba4c8ed..2c20ad527b 100644
--- a/scene/resources/color_ramp.cpp
+++ b/scene/resources/color_ramp.cpp
@@ -38,51 +38,45 @@
ColorRamp::ColorRamp() {
//Set initial color ramp transition from black to white
points.resize(2);
- points[0].color = Color(0,0,0,1);
+ points[0].color = Color(0, 0, 0, 1);
points[0].offset = 0;
- points[1].color = Color(1,1,1,1);
+ points[1].color = Color(1, 1, 1, 1);
points[1].offset = 1;
is_sorted = true;
}
ColorRamp::~ColorRamp() {
-
}
void ColorRamp::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("add_point", "offset", "color"), &ColorRamp::add_point);
+ ClassDB::bind_method(D_METHOD("remove_point", "offset", "color"), &ColorRamp::remove_point);
+ ClassDB::bind_method(D_METHOD("set_offset", "point", "offset"), &ColorRamp::set_offset);
+ ClassDB::bind_method(D_METHOD("get_offset", "point"), &ColorRamp::get_offset);
+ ClassDB::bind_method(D_METHOD("set_color", "point", "color"), &ColorRamp::set_color);
+ ClassDB::bind_method(D_METHOD("get_color", "point"), &ColorRamp::get_color);
+ ClassDB::bind_method(D_METHOD("interpolate", "offset"), &ColorRamp::get_color_at_offset);
- ClassDB::bind_method(D_METHOD("add_point","offset","color"),&ColorRamp::add_point);
- ClassDB::bind_method(D_METHOD("remove_point","offset","color"),&ColorRamp::remove_point);
-
- ClassDB::bind_method(D_METHOD("set_offset","point","offset"),&ColorRamp::set_offset);
- ClassDB::bind_method(D_METHOD("get_offset","point"),&ColorRamp::get_offset);
-
- ClassDB::bind_method(D_METHOD("set_color","point","color"),&ColorRamp::set_color);
- ClassDB::bind_method(D_METHOD("get_color","point"),&ColorRamp::get_color);
+ ClassDB::bind_method(D_METHOD("get_point_count"), &ColorRamp::get_points_count);
- ClassDB::bind_method(D_METHOD("interpolate","offset"),&ColorRamp::get_color_at_offset);
+ ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_OFFSETS, "offsets"), &ColorRamp::set_offsets);
+ ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_OFFSETS), &ColorRamp::get_offsets);
- ClassDB::bind_method(D_METHOD("get_point_count"),&ColorRamp::get_points_count);
+ ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_COLORS, "colors"), &ColorRamp::set_colors);
+ ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_COLORS), &ColorRamp::get_colors);
- ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_OFFSETS,"offsets"),&ColorRamp::set_offsets);
- ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_OFFSETS),&ColorRamp::get_offsets);
-
- ClassDB::bind_method(D_METHOD(COLOR_RAMP_SET_COLORS,"colors"),&ColorRamp::set_colors);
- ClassDB::bind_method(D_METHOD(COLOR_RAMP_GET_COLORS),&ColorRamp::get_colors);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"offsets"),COLOR_RAMP_SET_OFFSETS,COLOR_RAMP_GET_OFFSETS) ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"colors"),COLOR_RAMP_SET_COLORS,COLOR_RAMP_GET_COLORS) ;
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "offsets"), COLOR_RAMP_SET_OFFSETS, COLOR_RAMP_GET_OFFSETS);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "colors"), COLOR_RAMP_SET_COLORS, COLOR_RAMP_GET_COLORS);
}
Vector<float> ColorRamp::get_offsets() const {
Vector<float> offsets;
offsets.resize(points.size());
- for(int i = 0; i < points.size(); i++)
- {
+ for (int i = 0; i < points.size(); i++) {
offsets[i] = points[i].offset;
}
return offsets;
@@ -91,44 +85,41 @@ Vector<float> ColorRamp::get_offsets() const {
Vector<Color> ColorRamp::get_colors() const {
Vector<Color> colors;
colors.resize(points.size());
- for(int i = 0; i < points.size(); i++)
- {
+ for (int i = 0; i < points.size(); i++) {
colors[i] = points[i].color;
}
return colors;
}
-void ColorRamp::set_offsets(const Vector<float>& p_offsets) {
+void ColorRamp::set_offsets(const Vector<float> &p_offsets) {
points.resize(p_offsets.size());
- for(int i = 0; i < points.size(); i++)
- {
+ for (int i = 0; i < points.size(); i++) {
points[i].offset = p_offsets[i];
}
is_sorted = false;
emit_signal(CoreStringNames::get_singleton()->changed);
}
-void ColorRamp::set_colors(const Vector<Color>& p_colors) {
- if(points.size()<p_colors.size())
+void ColorRamp::set_colors(const Vector<Color> &p_colors) {
+ if (points.size() < p_colors.size())
is_sorted = false;
points.resize(p_colors.size());
- for(int i = 0; i < points.size(); i++)
- {
+ for (int i = 0; i < points.size(); i++) {
points[i].color = p_colors[i];
}
emit_signal(CoreStringNames::get_singleton()->changed);
}
-Vector<ColorRamp::Point>& ColorRamp::get_points() {
+Vector<ColorRamp::Point> &ColorRamp::get_points() {
return points;
}
-void ColorRamp::add_point(float p_offset, const Color& p_color) {
+void ColorRamp::add_point(float p_offset, const Color &p_color) {
Point p;
- p.offset=p_offset;
- p.color=p_color;
- is_sorted=false;
+ p.offset = p_offset;
+ p.color = p_color;
+ is_sorted = false;
points.push_back(p);
emit_signal(CoreStringNames::get_singleton()->changed);
@@ -136,20 +127,20 @@ void ColorRamp::add_point(float p_offset, const Color& p_color) {
void ColorRamp::remove_point(int p_index) {
- ERR_FAIL_INDEX(p_index,points.size());
- ERR_FAIL_COND(points.size()<=2);
+ ERR_FAIL_INDEX(p_index, points.size());
+ ERR_FAIL_COND(points.size() <= 2);
points.remove(p_index);
emit_signal(CoreStringNames::get_singleton()->changed);
}
-void ColorRamp::set_points(Vector<ColorRamp::Point>& p_points) {
+void ColorRamp::set_points(Vector<ColorRamp::Point> &p_points) {
points = p_points;
is_sorted = false;
emit_signal(CoreStringNames::get_singleton()->changed);
}
void ColorRamp::set_offset(int pos, const float offset) {
- if(points.size() <= pos)
+ if (points.size() <= pos)
points.resize(pos + 1);
points[pos].offset = offset;
is_sorted = false;
@@ -157,14 +148,13 @@ void ColorRamp::set_offset(int pos, const float offset) {
}
float ColorRamp::get_offset(int pos) const {
- if(points.size() > pos)
+ if (points.size() > pos)
return points[pos].offset;
- return 0; //TODO: Maybe throw some error instead?
+ return 0; //TODO: Maybe throw some error instead?
}
-void ColorRamp::set_color(int pos, const Color& color) {
- if(points.size() <= pos)
- {
+void ColorRamp::set_color(int pos, const Color &color) {
+ if (points.size() <= pos) {
points.resize(pos + 1);
is_sorted = false;
}
@@ -173,9 +163,9 @@ void ColorRamp::set_color(int pos, const Color& color) {
}
Color ColorRamp::get_color(int pos) const {
- if(points.size() > pos)
+ if (points.size() > pos)
return points[pos].color;
- return Color(0,0,0,1); //TODO: Maybe throw some error instead?
+ return Color(0, 0, 0, 1); //TODO: Maybe throw some error instead?
}
int ColorRamp::get_points_count() const {
diff --git a/scene/resources/color_ramp.h b/scene/resources/color_ramp.h
index b6ca56dbf5..78c88c3270 100644
--- a/scene/resources/color_ramp.h
+++ b/scene/resources/color_ramp.h
@@ -31,17 +31,17 @@
#include "resource.h"
-class ColorRamp: public Resource {
- GDCLASS( ColorRamp, Resource );
- OBJ_SAVE_TYPE( ColorRamp );
+class ColorRamp : public Resource {
+ GDCLASS(ColorRamp, Resource);
+ OBJ_SAVE_TYPE(ColorRamp);
public:
struct Point {
float offset;
Color color;
- bool operator<(const Point& p_ponit) const {
- return offset<p_ponit.offset;
+ bool operator<(const Point &p_ponit) const {
+ return offset < p_ponit.offset;
}
};
@@ -56,47 +56,45 @@ public:
ColorRamp();
virtual ~ColorRamp();
- void add_point(float p_offset, const Color& p_color);
+ void add_point(float p_offset, const Color &p_color);
void remove_point(int p_index);
- void set_points(Vector<Point>& points);
- Vector<Point>& get_points();
+ void set_points(Vector<Point> &points);
+ Vector<Point> &get_points();
void set_offset(int pos, const float offset);
float get_offset(int pos) const;
- void set_color(int pos, const Color& color);
+ void set_color(int pos, const Color &color);
Color get_color(int pos) const;
- void set_offsets(const Vector<float>& offsets);
+ void set_offsets(const Vector<float> &offsets);
Vector<float> get_offsets() const;
- void set_colors(const Vector<Color>& colors);
+ void set_colors(const Vector<Color> &colors);
Vector<Color> get_colors() const;
_FORCE_INLINE_ Color get_color_at_offset(float p_offset) {
if (points.empty())
- return Color(0,0,0,1);
+ return Color(0, 0, 0, 1);
- if(!is_sorted)
- {
+ if (!is_sorted) {
points.sort();
is_sorted = true;
}
//binary search
int low = 0;
- int high = points.size() -1;
+ int high = points.size() - 1;
int middle;
- while( low <= high )
- {
- middle = ( low + high ) / 2;
- Point& point = points[middle];
- if( point.offset > p_offset ) {
+ while (low <= high) {
+ middle = (low + high) / 2;
+ Point &point = points[middle];
+ if (point.offset > p_offset) {
high = middle - 1; //search low end of array
- } else if ( point.offset < p_offset) {
+ } else if (point.offset < p_offset) {
low = middle + 1; //search high end of array
} else {
return point.color;
@@ -104,19 +102,18 @@ public:
}
//return interpolated value
- if (points[middle].offset>p_offset)
- {
+ if (points[middle].offset > p_offset) {
middle--;
}
- int first=middle;
- int second=middle+1;
- if(second>=points.size())
- return points[points.size()-1].color;
- if(first<0)
+ int first = middle;
+ int second = middle + 1;
+ if (second >= points.size())
+ return points[points.size() - 1].color;
+ if (first < 0)
return points[0].color;
- Point& pointFirst = points[first];
- Point& pointSecond = points[second];
- return pointFirst.color.linear_interpolate(pointSecond.color, (p_offset-pointFirst.offset)/(pointSecond.offset - pointFirst.offset));
+ Point &pointFirst = points[first];
+ Point &pointSecond = points[second];
+ return pointFirst.color.linear_interpolate(pointSecond.color, (p_offset - pointFirst.offset) / (pointSecond.offset - pointFirst.offset));
}
int get_points_count() const;
diff --git a/scene/resources/concave_polygon_shape.cpp b/scene/resources/concave_polygon_shape.cpp
index 3945ade215..0031580153 100644
--- a/scene/resources/concave_polygon_shape.cpp
+++ b/scene/resources/concave_polygon_shape.cpp
@@ -34,87 +34,79 @@ Vector<Vector3> ConcavePolygonShape::_gen_debug_mesh_lines() {
Set<DrawEdge> edges;
- PoolVector<Vector3> data=get_faces();
- int datalen=data.size();
- ERR_FAIL_COND_V( (datalen%3)!=0,Vector<Vector3>() );
+ PoolVector<Vector3> data = get_faces();
+ int datalen = data.size();
+ ERR_FAIL_COND_V((datalen % 3) != 0, Vector<Vector3>());
- PoolVector<Vector3>::Read r=data.read();
+ PoolVector<Vector3>::Read r = data.read();
- for(int i=0;i<datalen;i+=3) {
+ for (int i = 0; i < datalen; i += 3) {
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- DrawEdge de(r[i+j],r[i+((j+1)%3)]);
+ DrawEdge de(r[i + j], r[i + ((j + 1) % 3)]);
edges.insert(de);
}
-
}
Vector<Vector3> points;
- points.resize(edges.size()*2);
- int idx=0;
- for (Set<DrawEdge>::Element*E=edges.front();E;E=E->next()) {
+ points.resize(edges.size() * 2);
+ int idx = 0;
+ for (Set<DrawEdge>::Element *E = edges.front(); E; E = E->next()) {
- points[idx+0]=E->get().a;
- points[idx+1]=E->get().b;
- idx+=2;
+ points[idx + 0] = E->get().a;
+ points[idx + 1] = E->get().b;
+ idx += 2;
}
return points;
-
}
-bool ConcavePolygonShape::_set(const StringName& p_name, const Variant& p_value) {
+bool ConcavePolygonShape::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name=="data")
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),p_value);
+ if (p_name == "data")
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), p_value);
else
return false;
return true;
-
}
-bool ConcavePolygonShape::_get(const StringName& p_name,Variant &r_ret) const {
+bool ConcavePolygonShape::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name=="data")
- r_ret=PhysicsServer::get_singleton()->shape_get_data(get_shape());
+ if (p_name == "data")
+ r_ret = PhysicsServer::get_singleton()->shape_get_data(get_shape());
else
return false;
return true;
-
}
-void ConcavePolygonShape::_get_property_list( List<PropertyInfo> *p_list) const {
+void ConcavePolygonShape::_get_property_list(List<PropertyInfo> *p_list) const {
- p_list->push_back( PropertyInfo(Variant::ARRAY,"data") );
+ p_list->push_back(PropertyInfo(Variant::ARRAY, "data"));
}
-
void ConcavePolygonShape::_update_shape() {
-
}
-void ConcavePolygonShape::set_faces(const PoolVector<Vector3>& p_faces) {
+void ConcavePolygonShape::set_faces(const PoolVector<Vector3> &p_faces) {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),p_faces);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), p_faces);
notify_change_to_owners();
}
PoolVector<Vector3> ConcavePolygonShape::get_faces() const {
return PhysicsServer::get_singleton()->shape_get_data(get_shape());
-
}
-
-
void ConcavePolygonShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_faces","faces"),&ConcavePolygonShape::set_faces);
- ClassDB::bind_method(D_METHOD("get_faces"),&ConcavePolygonShape::get_faces);
+ ClassDB::bind_method(D_METHOD("set_faces", "faces"), &ConcavePolygonShape::set_faces);
+ ClassDB::bind_method(D_METHOD("get_faces"), &ConcavePolygonShape::get_faces);
}
-ConcavePolygonShape::ConcavePolygonShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONCAVE_POLYGON)) {
+ConcavePolygonShape::ConcavePolygonShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONCAVE_POLYGON)) {
//set_planes(Vector3(1,1,1));
}
diff --git a/scene/resources/concave_polygon_shape.h b/scene/resources/concave_polygon_shape.h
index 36e806d37a..f048a4d151 100644
--- a/scene/resources/concave_polygon_shape.h
+++ b/scene/resources/concave_polygon_shape.h
@@ -33,44 +33,41 @@
class ConcavePolygonShape : public Shape {
- GDCLASS(ConcavePolygonShape,Shape);
+ GDCLASS(ConcavePolygonShape, Shape);
struct DrawEdge {
Vector3 a;
Vector3 b;
- bool operator<(const DrawEdge& p_edge) const {
- if (a==p_edge.a)
- return b<p_edge.b;
+ bool operator<(const DrawEdge &p_edge) const {
+ if (a == p_edge.a)
+ return b < p_edge.b;
else
- return a<p_edge.a;
+ return a < p_edge.a;
}
- DrawEdge(const Vector3& p_a=Vector3(),const Vector3& p_b=Vector3()) {
- a=p_a;
- b=p_b;
- if (a<b) {
- SWAP(a,b);
+ DrawEdge(const Vector3 &p_a = Vector3(), const Vector3 &p_b = Vector3()) {
+ a = p_a;
+ b = p_b;
+ if (a < b) {
+ SWAP(a, b);
}
}
};
protected:
-
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
- void set_faces(const PoolVector<Vector3>& p_faces);
+public:
+ void set_faces(const PoolVector<Vector3> &p_faces);
PoolVector<Vector3> get_faces() const;
-
ConcavePolygonShape();
};
diff --git a/scene/resources/concave_polygon_shape_2d.cpp b/scene/resources/concave_polygon_shape_2d.cpp
index f3dfa8a2b3..04a69d9c8e 100644
--- a/scene/resources/concave_polygon_shape_2d.cpp
+++ b/scene/resources/concave_polygon_shape_2d.cpp
@@ -31,9 +31,9 @@
#include "servers/physics_2d_server.h"
#include "servers/visual_server.h"
-void ConcavePolygonShape2D::set_segments(const PoolVector<Vector2>& p_segments) {
+void ConcavePolygonShape2D::set_segments(const PoolVector<Vector2> &p_segments) {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),p_segments);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), p_segments);
emit_changed();
}
@@ -42,55 +42,47 @@ PoolVector<Vector2> ConcavePolygonShape2D::get_segments() const {
return Physics2DServer::get_singleton()->shape_get_data(get_rid());
}
-void ConcavePolygonShape2D::draw(const RID& p_to_rid,const Color& p_color) {
-
+void ConcavePolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) {
PoolVector<Vector2> s = get_segments();
- int len=s.size();
- if (len==0 || (len%2)==1)
+ int len = s.size();
+ if (len == 0 || (len % 2) == 1)
return;
PoolVector<Vector2>::Read r = s.read();
- for(int i=0;i<len;i+=2) {
- VisualServer::get_singleton()->canvas_item_add_line(p_to_rid,r[i],r[i+1],p_color,2);
+ for (int i = 0; i < len; i += 2) {
+ VisualServer::get_singleton()->canvas_item_add_line(p_to_rid, r[i], r[i + 1], p_color, 2);
}
-
}
Rect2 ConcavePolygonShape2D::get_rect() const {
-
PoolVector<Vector2> s = get_segments();
- int len=s.size();
- if (len==0)
+ int len = s.size();
+ if (len == 0)
return Rect2();
Rect2 rect;
PoolVector<Vector2>::Read r = s.read();
- for(int i=0;i<len;i++) {
- if (i==0)
- rect.pos=r[i];
+ for (int i = 0; i < len; i++) {
+ if (i == 0)
+ rect.pos = r[i];
else
rect.expand_to(r[i]);
}
return rect;
-
}
-
void ConcavePolygonShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_segments","segments"),&ConcavePolygonShape2D::set_segments);
- ClassDB::bind_method(D_METHOD("get_segments"),&ConcavePolygonShape2D::get_segments);
-
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"segments"),"set_segments","get_segments") ;
+ ClassDB::bind_method(D_METHOD("set_segments", "segments"), &ConcavePolygonShape2D::set_segments);
+ ClassDB::bind_method(D_METHOD("get_segments"), &ConcavePolygonShape2D::get_segments);
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "segments"), "set_segments", "get_segments");
}
-ConcavePolygonShape2D::ConcavePolygonShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONCAVE_POLYGON)) {
-
+ConcavePolygonShape2D::ConcavePolygonShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONCAVE_POLYGON)) {
}
-
-
diff --git a/scene/resources/concave_polygon_shape_2d.h b/scene/resources/concave_polygon_shape_2d.h
index 309fb4a7b3..23c602980c 100644
--- a/scene/resources/concave_polygon_shape_2d.h
+++ b/scene/resources/concave_polygon_shape_2d.h
@@ -32,17 +32,17 @@
#include "scene/resources/shape_2d.h"
class ConcavePolygonShape2D : public Shape2D {
- GDCLASS( ConcavePolygonShape2D, Shape2D );
-protected:
+ GDCLASS(ConcavePolygonShape2D, Shape2D);
+protected:
static void _bind_methods();
-public:
- void set_segments(const PoolVector<Vector2>& p_segments);
+public:
+ void set_segments(const PoolVector<Vector2> &p_segments);
PoolVector<Vector2> get_segments() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
- virtual Rect2 get_rect() const ;
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
+ virtual Rect2 get_rect() const;
ConcavePolygonShape2D();
};
diff --git a/scene/resources/convex_polygon_shape.cpp b/scene/resources/convex_polygon_shape.cpp
index 207419f8cd..350c4c2d86 100644
--- a/scene/resources/convex_polygon_shape.cpp
+++ b/scene/resources/convex_polygon_shape.cpp
@@ -27,46 +27,42 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "convex_polygon_shape.h"
-#include "servers/physics_server.h"
#include "quick_hull.h"
+#include "servers/physics_server.h"
Vector<Vector3> ConvexPolygonShape::_gen_debug_mesh_lines() {
PoolVector<Vector3> points = get_points();
- if (points.size()>3) {
+ if (points.size() > 3) {
QuickHull qh;
Vector<Vector3> varr = Variant(points);
Geometry::MeshData md;
- Error err = qh.build(varr,md);
- if (err==OK) {
+ Error err = qh.build(varr, md);
+ if (err == OK) {
Vector<Vector3> lines;
- lines.resize(md.edges.size()*2);
- for(int i=0;i<md.edges.size();i++) {
- lines[i*2+0]=md.vertices[md.edges[i].a];
- lines[i*2+1]=md.vertices[md.edges[i].b];
+ lines.resize(md.edges.size() * 2);
+ for (int i = 0; i < md.edges.size(); i++) {
+ lines[i * 2 + 0] = md.vertices[md.edges[i].a];
+ lines[i * 2 + 1] = md.vertices[md.edges[i].b];
}
return lines;
-
-
}
-
}
return Vector<Vector3>();
}
-
void ConvexPolygonShape::_update_shape() {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),points);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), points);
emit_changed();
}
-void ConvexPolygonShape::set_points(const PoolVector<Vector3>& p_points) {
+void ConvexPolygonShape::set_points(const PoolVector<Vector3> &p_points) {
- points=p_points;
+ points = p_points;
_update_shape();
notify_change_to_owners();
}
@@ -76,17 +72,16 @@ PoolVector<Vector3> ConvexPolygonShape::get_points() const {
return points;
}
-
void ConvexPolygonShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_points","points"),&ConvexPolygonShape::set_points);
- ClassDB::bind_method(D_METHOD("get_points"),&ConvexPolygonShape::get_points);
-
- ADD_PROPERTY( PropertyInfo(Variant::ARRAY,"points"), "set_points", "get_points") ;
+ ClassDB::bind_method(D_METHOD("set_points", "points"), &ConvexPolygonShape::set_points);
+ ClassDB::bind_method(D_METHOD("get_points"), &ConvexPolygonShape::get_points);
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "points"), "set_points", "get_points");
}
-ConvexPolygonShape::ConvexPolygonShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON)) {
+ConvexPolygonShape::ConvexPolygonShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_CONVEX_POLYGON)) {
//set_points(Vector3(1,1,1));
}
diff --git a/scene/resources/convex_polygon_shape.h b/scene/resources/convex_polygon_shape.h
index 215de941c6..6701c41f0f 100644
--- a/scene/resources/convex_polygon_shape.h
+++ b/scene/resources/convex_polygon_shape.h
@@ -33,19 +33,18 @@
class ConvexPolygonShape : public Shape {
- GDCLASS(ConvexPolygonShape,Shape);
+ GDCLASS(ConvexPolygonShape, Shape);
PoolVector<Vector3> points;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
- void set_points(const PoolVector<Vector3>& p_points);
+public:
+ void set_points(const PoolVector<Vector3> &p_points);
PoolVector<Vector3> get_points() const;
ConvexPolygonShape();
diff --git a/scene/resources/convex_polygon_shape_2d.cpp b/scene/resources/convex_polygon_shape_2d.cpp
index 2a4b181611..311614b7c1 100644
--- a/scene/resources/convex_polygon_shape_2d.cpp
+++ b/scene/resources/convex_polygon_shape_2d.cpp
@@ -28,28 +28,26 @@
/*************************************************************************/
#include "convex_polygon_shape_2d.h"
+#include "geometry.h"
#include "servers/physics_2d_server.h"
#include "servers/visual_server.h"
-#include "geometry.h"
void ConvexPolygonShape2D::_update_shape() {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),points);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), points);
emit_changed();
-
}
-void ConvexPolygonShape2D::set_point_cloud(const Vector<Vector2>& p_points) {
+void ConvexPolygonShape2D::set_point_cloud(const Vector<Vector2> &p_points) {
-
- Vector<Point2> hull=Geometry::convex_hull_2d(p_points);
- ERR_FAIL_COND(hull.size()<3);
+ Vector<Point2> hull = Geometry::convex_hull_2d(p_points);
+ ERR_FAIL_COND(hull.size() < 3);
set_points(hull);
}
-void ConvexPolygonShape2D::set_points(const Vector<Vector2>& p_points) {
+void ConvexPolygonShape2D::set_points(const Vector<Vector2> &p_points) {
- points=p_points;
+ points = p_points;
_update_shape();
}
@@ -58,48 +56,41 @@ Vector<Vector2> ConvexPolygonShape2D::get_points() const {
return points;
}
-
void ConvexPolygonShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_point_cloud","point_cloud"),&ConvexPolygonShape2D::set_point_cloud);
- ClassDB::bind_method(D_METHOD("set_points","points"),&ConvexPolygonShape2D::set_points);
- ClassDB::bind_method(D_METHOD("get_points"),&ConvexPolygonShape2D::get_points);
-
-
-
- ADD_PROPERTY( PropertyInfo(Variant::POOL_VECTOR2_ARRAY,"points"),"set_points","get_points") ;
+ ClassDB::bind_method(D_METHOD("set_point_cloud", "point_cloud"), &ConvexPolygonShape2D::set_point_cloud);
+ ClassDB::bind_method(D_METHOD("set_points", "points"), &ConvexPolygonShape2D::set_points);
+ ClassDB::bind_method(D_METHOD("get_points"), &ConvexPolygonShape2D::get_points);
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR2_ARRAY, "points"), "set_points", "get_points");
}
-void ConvexPolygonShape2D::draw(const RID& p_to_rid,const Color& p_color) {
-
+void ConvexPolygonShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector<Color> col;
col.push_back(p_color);
- VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid,points,col);
+ VisualServer::get_singleton()->canvas_item_add_polygon(p_to_rid, points, col);
}
-Rect2 ConvexPolygonShape2D::get_rect() const {
-
+Rect2 ConvexPolygonShape2D::get_rect() const {
Rect2 rect;
- for(int i=0;i<points.size();i++) {
- if (i==0)
- rect.pos=points[i];
+ for (int i = 0; i < points.size(); i++) {
+ if (i == 0)
+ rect.pos = points[i];
else
rect.expand_to(points[i]);
}
return rect;
-
}
-ConvexPolygonShape2D::ConvexPolygonShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON)) {
-
+ConvexPolygonShape2D::ConvexPolygonShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_CONVEX_POLYGON)) {
- int pcount =3;
- for(int i=0;i<pcount;i++)
- points.push_back(Vector2(Math::sin(i*Math_PI*2/pcount),-Math::cos(i*Math_PI*2/pcount))*10);
+ int pcount = 3;
+ for (int i = 0; i < pcount; i++)
+ points.push_back(Vector2(Math::sin(i * Math_PI * 2 / pcount), -Math::cos(i * Math_PI * 2 / pcount)) * 10);
_update_shape();
}
diff --git a/scene/resources/convex_polygon_shape_2d.h b/scene/resources/convex_polygon_shape_2d.h
index 8a4ad0e6d8..edb302ba5e 100644
--- a/scene/resources/convex_polygon_shape_2d.h
+++ b/scene/resources/convex_polygon_shape_2d.h
@@ -32,21 +32,21 @@
#include "scene/resources/shape_2d.h"
class ConvexPolygonShape2D : public Shape2D {
- GDCLASS( ConvexPolygonShape2D, Shape2D );
+ GDCLASS(ConvexPolygonShape2D, Shape2D);
Vector<Vector2> points;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
- void set_point_cloud(const Vector<Vector2>& p_points);
- void set_points(const Vector<Vector2>& p_points);
+public:
+ void set_point_cloud(const Vector<Vector2> &p_points);
+ void set_points(const Vector<Vector2> &p_points);
Vector<Vector2> get_points() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
- virtual Rect2 get_rect() const ;
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
+ virtual Rect2 get_rect() const;
ConvexPolygonShape2D();
};
diff --git a/scene/resources/curve.cpp b/scene/resources/curve.cpp
index 9311ab4dd7..f85220ac23 100644
--- a/scene/resources/curve.cpp
+++ b/scene/resources/curve.cpp
@@ -29,19 +29,16 @@
#include "curve.h"
#include "core_string_names.h"
-template<class T>
+template <class T>
static _FORCE_INLINE_ T _bezier_interp(real_t t, T start, T control_1, T control_2, T end) {
- /* Formula from Wikipedia article on Bezier curves. */
+ /* 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;
+ 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;
+ return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
}
#if 0
@@ -382,92 +379,80 @@ Curve2D::Curve2D()
#endif
-
-
-
int Curve2D::get_point_count() const {
return points.size();
}
-void Curve2D::add_point(const Vector2& p_pos, const Vector2& p_in, const Vector2& p_out,int p_atpos) {
+void Curve2D::add_point(const Vector2 &p_pos, const Vector2 &p_in, const Vector2 &p_out, int p_atpos) {
Point n;
- n.pos=p_pos;
- n.in=p_in;
- n.out=p_out;
- if (p_atpos>=0 && p_atpos<points.size())
- points.insert(p_atpos,n);
+ n.pos = p_pos;
+ n.in = p_in;
+ n.out = p_out;
+ if (p_atpos >= 0 && p_atpos < points.size())
+ points.insert(p_atpos, n);
else
points.push_back(n);
-
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
-void Curve2D::set_point_pos(int p_index, const Vector2& p_pos) {
+void Curve2D::set_point_pos(int p_index, const Vector2 &p_pos) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].pos=p_pos;
- baked_cache_dirty=true;
+ points[p_index].pos = p_pos;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector2 Curve2D::get_point_pos(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector2());
return points[p_index].pos;
-
}
+void Curve2D::set_point_in(int p_index, const Vector2 &p_in) {
-void Curve2D::set_point_in(int p_index, const Vector2& p_in) {
-
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].in=p_in;
- baked_cache_dirty=true;
+ points[p_index].in = p_in;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector2 Curve2D::get_point_in(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector2());
return points[p_index].in;
-
}
-void Curve2D::set_point_out(int p_index, const Vector2& p_out) {
+void Curve2D::set_point_out(int p_index, const Vector2 &p_out) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].out=p_out;
- baked_cache_dirty=true;
+ points[p_index].out = p_out;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector2 Curve2D::get_point_out(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector2());
return points[p_index].out;
-
}
-
void Curve2D::remove_point(int p_index) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
points.remove(p_index);
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
void Curve2D::clear_points() {
if (!points.empty()) {
points.clear();
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
}
@@ -475,151 +460,138 @@ void Curve2D::clear_points() {
Vector2 Curve2D::interpolate(int p_index, float p_offset) const {
int pc = points.size();
- ERR_FAIL_COND_V(pc==0,Vector2());
+ ERR_FAIL_COND_V(pc == 0, Vector2());
- if (p_index >= pc-1)
- return points[pc-1].pos;
- else if (p_index<0)
+ if (p_index >= pc - 1)
+ return points[pc - 1].pos;
+ else if (p_index < 0)
return points[0].pos;
Vector2 p0 = points[p_index].pos;
- Vector2 p1 = p0+points[p_index].out;
- Vector2 p3 = points[p_index+1].pos;
- Vector2 p2 = p3+points[p_index+1].in;
+ Vector2 p1 = p0 + points[p_index].out;
+ Vector2 p3 = points[p_index + 1].pos;
+ Vector2 p2 = p3 + points[p_index + 1].in;
- return _bezier_interp(p_offset,p0,p1,p2,p3);
+ return _bezier_interp(p_offset, p0, p1, p2, p3);
}
Vector2 Curve2D::interpolatef(real_t p_findex) const {
+ if (p_findex < 0)
+ p_findex = 0;
+ else if (p_findex >= points.size())
+ p_findex = points.size();
- if (p_findex<0)
- p_findex=0;
- else if (p_findex>=points.size())
- p_findex=points.size();
-
- return interpolate((int)p_findex,Math::fmod(p_findex,(real_t)1.0));
-
+ return interpolate((int)p_findex, Math::fmod(p_findex, (real_t)1.0));
}
+void Curve2D::_bake_segment2d(Map<float, Vector2> &r_bake, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, float p_tol) const {
-void Curve2D::_bake_segment2d(Map<float,Vector2>& r_bake, float p_begin, float p_end,const Vector2& p_a,const Vector2& p_out,const Vector2& p_b, const Vector2& p_in,int p_depth,int p_max_depth,float p_tol) const {
-
- float mp = p_begin+(p_end-p_begin)*0.5;
- Vector2 beg = _bezier_interp(p_begin,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector2 mid = _bezier_interp(mp,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector2 end = _bezier_interp(p_end,p_a,p_a+p_out,p_b+p_in,p_b);
+ float mp = p_begin + (p_end - p_begin) * 0.5;
+ Vector2 beg = _bezier_interp(p_begin, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector2 mid = _bezier_interp(mp, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector2 end = _bezier_interp(p_end, p_a, p_a + p_out, p_b + p_in, p_b);
- Vector2 na = (mid-beg).normalized();
- Vector2 nb = (end-mid).normalized();
+ Vector2 na = (mid - beg).normalized();
+ Vector2 nb = (end - mid).normalized();
float dp = na.dot(nb);
- if (dp<Math::cos(Math::deg2rad(p_tol))) {
+ if (dp < Math::cos(Math::deg2rad(p_tol))) {
- r_bake[mp]=mid;
+ r_bake[mp] = mid;
}
- if (p_depth<p_max_depth) {
- _bake_segment2d(r_bake,p_begin,mp,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol);
- _bake_segment2d(r_bake,mp,p_end,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol);
+ if (p_depth < p_max_depth) {
+ _bake_segment2d(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol);
+ _bake_segment2d(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol);
}
}
-
-
void Curve2D::_bake() const {
if (!baked_cache_dirty)
return;
- baked_max_ofs=0;
- baked_cache_dirty=false;
+ baked_max_ofs = 0;
+ baked_cache_dirty = false;
- if (points.size()==0) {
+ if (points.size() == 0) {
baked_point_cache.resize(0);
return;
}
- if (points.size()==1) {
+ if (points.size() == 1) {
baked_point_cache.resize(1);
- baked_point_cache.set(0,points[0].pos);
+ baked_point_cache.set(0, points[0].pos);
return;
}
-
- Vector2 pos=points[0].pos;
+ Vector2 pos = points[0].pos;
List<Vector2> pointlist;
pointlist.push_back(pos); //start always from origin
- for(int i=0;i<points.size()-1;i++) {
+ for (int i = 0; i < points.size() - 1; i++) {
float step = 0.1; // at least 10 substeps ought to be enough?
float p = 0;
- while(p<1.0) {
-
- float np=p+step;
- if (np>1.0)
- np=1.0;
+ while (p < 1.0) {
+ float np = p + step;
+ if (np > 1.0)
+ np = 1.0;
- Vector2 npp = _bezier_interp(np, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos);
+ Vector2 npp = _bezier_interp(np, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos);
float d = pos.distance_to(npp);
- if (d>bake_interval) {
+ if (d > bake_interval) {
// OK! between P and NP there _has_ to be Something, let's go searching!
int iterations = 10; //lots of detail!
float low = p;
float hi = np;
- float mid = low+(hi-low)*0.5;
+ float mid = low + (hi - low) * 0.5;
- for(int j=0;j<iterations;j++) {
+ for (int j = 0; j < iterations; j++) {
-
- npp = _bezier_interp(mid, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos);
+ npp = _bezier_interp(mid, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos);
d = pos.distance_to(npp);
if (bake_interval < d)
- hi=mid;
+ hi = mid;
else
- low=mid;
- mid = low+(hi-low)*0.5;
-
+ low = mid;
+ mid = low + (hi - low) * 0.5;
}
- pos=npp;
- p=mid;
+ pos = npp;
+ p = mid;
pointlist.push_back(pos);
} else {
- p=np;
+ p = np;
}
-
}
}
- Vector2 lastpos = points[points.size()-1].pos;
-
+ Vector2 lastpos = points[points.size() - 1].pos;
float rem = pos.distance_to(lastpos);
- baked_max_ofs=(pointlist.size()-1)*bake_interval+rem;
+ baked_max_ofs = (pointlist.size() - 1) * bake_interval + rem;
pointlist.push_back(lastpos);
baked_point_cache.resize(pointlist.size());
PoolVector2Array::Write w = baked_point_cache.write();
- int idx=0;
-
+ int idx = 0;
- for(List<Vector2>::Element *E=pointlist.front();E;E=E->next()) {
+ for (List<Vector2>::Element *E = pointlist.front(); E; E = E->next()) {
- w[idx]=E->get();
+ w[idx] = E->get();
idx++;
}
-
}
float Curve2D::get_baked_length() const {
@@ -629,51 +601,50 @@ float Curve2D::get_baked_length() const {
return baked_max_ofs;
}
-Vector2 Curve2D::interpolate_baked(float p_offset,bool p_cubic) const{
+Vector2 Curve2D::interpolate_baked(float p_offset, bool p_cubic) const {
if (baked_cache_dirty)
_bake();
//validate//
int pc = baked_point_cache.size();
- if (pc==0) {
+ if (pc == 0) {
ERR_EXPLAIN("No points in Curve2D");
- ERR_FAIL_COND_V(pc==0,Vector2());
+ ERR_FAIL_COND_V(pc == 0, Vector2());
}
- if (pc==1)
+ if (pc == 1)
return baked_point_cache.get(0);
- int bpc=baked_point_cache.size();
+ int bpc = baked_point_cache.size();
PoolVector2Array::Read r = baked_point_cache.read();
- if (p_offset<0)
+ if (p_offset < 0)
return r[0];
- if (p_offset>=baked_max_ofs)
- return r[bpc-1];
+ if (p_offset >= baked_max_ofs)
+ return r[bpc - 1];
- int idx = Math::floor((double)p_offset/(double)bake_interval);
- float frac = Math::fmod(p_offset,(float)bake_interval);
+ int idx = Math::floor((double)p_offset / (double)bake_interval);
+ float frac = Math::fmod(p_offset, (float)bake_interval);
- if (idx>=bpc-1) {
- return r[bpc-1];
- } else if (idx==bpc-2) {
- frac/=Math::fmod(baked_max_ofs,bake_interval);
+ if (idx >= bpc - 1) {
+ return r[bpc - 1];
+ } else if (idx == bpc - 2) {
+ frac /= Math::fmod(baked_max_ofs, bake_interval);
} else {
- frac/=bake_interval;
+ frac /= bake_interval;
}
if (p_cubic) {
- Vector2 pre = idx>0? r[idx-1] : r[idx];
- Vector2 post = (idx<(bpc-2))? r[idx+2] : r[idx+1];
- return r[idx].cubic_interpolate(r[idx+1],pre,post,frac);
+ Vector2 pre = idx > 0 ? r[idx - 1] : r[idx];
+ Vector2 post = (idx < (bpc - 2)) ? r[idx + 2] : r[idx + 1];
+ return r[idx].cubic_interpolate(r[idx + 1], pre, post, frac);
} else {
- return r[idx].linear_interpolate(r[idx+1],frac);
+ return r[idx].linear_interpolate(r[idx + 1], frac);
}
}
-
PoolVector2Array Curve2D::get_baked_points() const {
if (baked_cache_dirty)
@@ -682,16 +653,14 @@ PoolVector2Array Curve2D::get_baked_points() const {
return baked_point_cache;
}
+void Curve2D::set_bake_interval(float p_tolerance) {
-void Curve2D::set_bake_interval(float p_tolerance){
-
- bake_interval=p_tolerance;
- baked_cache_dirty=true;
+ bake_interval = p_tolerance;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
-float Curve2D::get_bake_interval() const{
+float Curve2D::get_bake_interval() const {
return bake_interval;
}
@@ -701,143 +670,125 @@ Dictionary Curve2D::_get_data() const {
Dictionary dc;
PoolVector2Array d;
- d.resize(points.size()*3);
+ d.resize(points.size() * 3);
PoolVector2Array::Write w = d.write();
+ for (int i = 0; i < points.size(); i++) {
- for(int i=0;i<points.size();i++) {
-
- w[i*3+0]=points[i].in;
- w[i*3+1]=points[i].out;
- w[i*3+2]=points[i].pos;
-
+ w[i * 3 + 0] = points[i].in;
+ w[i * 3 + 1] = points[i].out;
+ w[i * 3 + 2] = points[i].pos;
}
- w=PoolVector2Array::Write();
+ w = PoolVector2Array::Write();
- dc["points"]=d;
+ dc["points"] = d;
return dc;
}
-void Curve2D::_set_data(const Dictionary& p_data){
-
+void Curve2D::_set_data(const Dictionary &p_data) {
ERR_FAIL_COND(!p_data.has("points"));
- PoolVector2Array rp=p_data["points"];
+ PoolVector2Array rp = p_data["points"];
int pc = rp.size();
- ERR_FAIL_COND(pc%3!=0);
- points.resize(pc/3);
+ ERR_FAIL_COND(pc % 3 != 0);
+ points.resize(pc / 3);
PoolVector2Array::Read r = rp.read();
- for(int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
- points[i].in=r[i*3+0];
- points[i].out=r[i*3+1];
- points[i].pos=r[i*3+2];
+ points[i].in = r[i * 3 + 0];
+ points[i].out = r[i * 3 + 1];
+ points[i].pos = r[i * 3 + 2];
}
- baked_cache_dirty=true;
-
+ baked_cache_dirty = true;
}
-
-PoolVector2Array Curve2D::tesselate(int p_max_stages,float p_tolerance) const {
+PoolVector2Array Curve2D::tesselate(int p_max_stages, float p_tolerance) const {
PoolVector2Array tess;
-
- if (points.size()==0) {
+ if (points.size() == 0) {
return tess;
}
- Vector< Map<float,Vector2> > midpoints;
+ Vector<Map<float, Vector2> > midpoints;
- midpoints.resize(points.size()-1);
+ midpoints.resize(points.size() - 1);
- int pc=1;
- for(int i=0;i<points.size()-1;i++) {
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
- _bake_segment2d(midpoints[i],0,1,points[i].pos,points[i].out,points[i+1].pos,points[i+1].in,0,p_max_stages,p_tolerance);
+ _bake_segment2d(midpoints[i], 0, 1, points[i].pos, points[i].out, points[i + 1].pos, points[i + 1].in, 0, p_max_stages, p_tolerance);
pc++;
- pc+=midpoints[i].size();
-
+ pc += midpoints[i].size();
}
tess.resize(pc);
- PoolVector2Array::Write bpw=tess.write();
- bpw[0]=points[0].pos;
- int pidx=0;
+ PoolVector2Array::Write bpw = tess.write();
+ bpw[0] = points[0].pos;
+ int pidx = 0;
- for(int i=0;i<points.size()-1;i++) {
+ for (int i = 0; i < points.size() - 1; i++) {
- for(Map<float,Vector2>::Element *E=midpoints[i].front();E;E=E->next()) {
+ for (Map<float, Vector2>::Element *E = midpoints[i].front(); E; E = E->next()) {
pidx++;
bpw[pidx] = E->get();
}
pidx++;
- bpw[pidx] = points[i+1].pos;
-
+ bpw[pidx] = points[i + 1].pos;
}
- bpw=PoolVector2Array::Write ();
+ bpw = PoolVector2Array::Write();
return tess;
-
}
void Curve2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_point_count"),&Curve2D::get_point_count);
- ClassDB::bind_method(D_METHOD("add_point","pos","in","out","atpos"),&Curve2D::add_point,DEFVAL(Vector2()),DEFVAL(Vector2()),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("set_point_pos","idx","pos"),&Curve2D::set_point_pos);
- ClassDB::bind_method(D_METHOD("get_point_pos","idx"),&Curve2D::get_point_pos);
- ClassDB::bind_method(D_METHOD("set_point_in","idx","pos"),&Curve2D::set_point_in);
- ClassDB::bind_method(D_METHOD("get_point_in","idx"),&Curve2D::get_point_in);
- ClassDB::bind_method(D_METHOD("set_point_out","idx","pos"),&Curve2D::set_point_out);
- ClassDB::bind_method(D_METHOD("get_point_out","idx"),&Curve2D::get_point_out);
- ClassDB::bind_method(D_METHOD("remove_point","idx"),&Curve2D::remove_point);
- ClassDB::bind_method(D_METHOD("clear_points"),&Curve2D::clear_points);
- ClassDB::bind_method(D_METHOD("interpolate","idx","t"),&Curve2D::interpolate);
- ClassDB::bind_method(D_METHOD("interpolatef","fofs"),&Curve2D::interpolatef);
+ ClassDB::bind_method(D_METHOD("get_point_count"), &Curve2D::get_point_count);
+ ClassDB::bind_method(D_METHOD("add_point", "pos", "in", "out", "atpos"), &Curve2D::add_point, DEFVAL(Vector2()), DEFVAL(Vector2()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("set_point_pos", "idx", "pos"), &Curve2D::set_point_pos);
+ ClassDB::bind_method(D_METHOD("get_point_pos", "idx"), &Curve2D::get_point_pos);
+ ClassDB::bind_method(D_METHOD("set_point_in", "idx", "pos"), &Curve2D::set_point_in);
+ ClassDB::bind_method(D_METHOD("get_point_in", "idx"), &Curve2D::get_point_in);
+ ClassDB::bind_method(D_METHOD("set_point_out", "idx", "pos"), &Curve2D::set_point_out);
+ ClassDB::bind_method(D_METHOD("get_point_out", "idx"), &Curve2D::get_point_out);
+ ClassDB::bind_method(D_METHOD("remove_point", "idx"), &Curve2D::remove_point);
+ ClassDB::bind_method(D_METHOD("clear_points"), &Curve2D::clear_points);
+ ClassDB::bind_method(D_METHOD("interpolate", "idx", "t"), &Curve2D::interpolate);
+ ClassDB::bind_method(D_METHOD("interpolatef", "fofs"), &Curve2D::interpolatef);
//ClassDB::bind_method(D_METHOD("bake","subdivs"),&Curve2D::bake,DEFVAL(10));
- ClassDB::bind_method(D_METHOD("set_bake_interval","distance"),&Curve2D::set_bake_interval);
- ClassDB::bind_method(D_METHOD("get_bake_interval"),&Curve2D::get_bake_interval);
-
- ClassDB::bind_method(D_METHOD("get_baked_length"),&Curve2D::get_baked_length);
- ClassDB::bind_method(D_METHOD("interpolate_baked","offset","cubic"),&Curve2D::interpolate_baked,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_baked_points"),&Curve2D::get_baked_points);
- ClassDB::bind_method(D_METHOD("tesselate","max_stages","tolerance_degrees"),&Curve2D::tesselate,DEFVAL(5),DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("set_bake_interval", "distance"), &Curve2D::set_bake_interval);
+ ClassDB::bind_method(D_METHOD("get_bake_interval"), &Curve2D::get_bake_interval);
- ClassDB::bind_method(D_METHOD("_get_data"),&Curve2D::_get_data);
- ClassDB::bind_method(D_METHOD("_set_data"),&Curve2D::_set_data);
+ ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve2D::get_baked_length);
+ ClassDB::bind_method(D_METHOD("interpolate_baked", "offset", "cubic"), &Curve2D::interpolate_baked, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve2D::get_baked_points);
+ ClassDB::bind_method(D_METHOD("tesselate", "max_stages", "tolerance_degrees"), &Curve2D::tesselate, DEFVAL(5), DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("_get_data"), &Curve2D::_get_data);
+ ClassDB::bind_method(D_METHOD("_set_data"), &Curve2D::_set_data);
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "bake_interval",PROPERTY_HINT_RANGE,"0.01,512,0.01"), "set_bake_interval","get_bake_interval");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bake_interval", PROPERTY_HINT_RANGE, "0.01,512,0.01"), "set_bake_interval", "get_bake_interval");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
/*ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_out"), "set_points_out","get_points_out");
ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_pos"), "set_points_pos","get_points_pos");
*/
}
-
-
-
-Curve2D::Curve2D()
-{
- baked_cache_dirty=false;
- baked_max_ofs=0;
-/* add_point(Vector2(-1,0,0));
+Curve2D::Curve2D() {
+ baked_cache_dirty = false;
+ baked_max_ofs = 0;
+ /* add_point(Vector2(-1,0,0));
add_point(Vector2(0,2,0));
add_point(Vector2(0,3,5));*/
- bake_interval=5;
-
+ bake_interval = 5;
}
-
-
-
/***********************************************************************************/
/***********************************************************************************/
/***********************************************************************************/
@@ -849,93 +800,82 @@ int Curve3D::get_point_count() const {
return points.size();
}
-void Curve3D::add_point(const Vector3& p_pos, const Vector3& p_in, const Vector3& p_out,int p_atpos) {
+void Curve3D::add_point(const Vector3 &p_pos, const Vector3 &p_in, const Vector3 &p_out, int p_atpos) {
Point n;
- n.pos=p_pos;
- n.in=p_in;
- n.out=p_out;
- if (p_atpos>=0 && p_atpos<points.size())
- points.insert(p_atpos,n);
+ n.pos = p_pos;
+ n.in = p_in;
+ n.out = p_out;
+ if (p_atpos >= 0 && p_atpos < points.size())
+ points.insert(p_atpos, n);
else
points.push_back(n);
-
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
-void Curve3D::set_point_pos(int p_index, const Vector3& p_pos) {
+void Curve3D::set_point_pos(int p_index, const Vector3 &p_pos) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].pos=p_pos;
- baked_cache_dirty=true;
+ points[p_index].pos = p_pos;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector3 Curve3D::get_point_pos(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector3());
return points[p_index].pos;
-
}
void Curve3D::set_point_tilt(int p_index, float p_tilt) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].tilt=p_tilt;
- baked_cache_dirty=true;
+ points[p_index].tilt = p_tilt;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
float Curve3D::get_point_tilt(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),0);
+ ERR_FAIL_INDEX_V(p_index, points.size(), 0);
return points[p_index].tilt;
-
}
+void Curve3D::set_point_in(int p_index, const Vector3 &p_in) {
-void Curve3D::set_point_in(int p_index, const Vector3& p_in) {
-
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].in=p_in;
- baked_cache_dirty=true;
+ points[p_index].in = p_in;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector3 Curve3D::get_point_in(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector3());
return points[p_index].in;
-
}
-void Curve3D::set_point_out(int p_index, const Vector3& p_out) {
+void Curve3D::set_point_out(int p_index, const Vector3 &p_out) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
- points[p_index].out=p_out;
- baked_cache_dirty=true;
+ points[p_index].out = p_out;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
Vector3 Curve3D::get_point_out(int p_index) const {
- ERR_FAIL_INDEX_V(p_index,points.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_index, points.size(), Vector3());
return points[p_index].out;
-
}
-
void Curve3D::remove_point(int p_index) {
- ERR_FAIL_INDEX(p_index,points.size());
+ ERR_FAIL_INDEX(p_index, points.size());
points.remove(p_index);
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
@@ -943,7 +883,7 @@ void Curve3D::clear_points() {
if (!points.empty()) {
points.clear();
- baked_cache_dirty=true;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
}
}
@@ -951,158 +891,147 @@ void Curve3D::clear_points() {
Vector3 Curve3D::interpolate(int p_index, float p_offset) const {
int pc = points.size();
- ERR_FAIL_COND_V(pc==0,Vector3());
+ ERR_FAIL_COND_V(pc == 0, Vector3());
- if (p_index >= pc-1)
- return points[pc-1].pos;
- else if (p_index<0)
+ if (p_index >= pc - 1)
+ return points[pc - 1].pos;
+ else if (p_index < 0)
return points[0].pos;
Vector3 p0 = points[p_index].pos;
- Vector3 p1 = p0+points[p_index].out;
- Vector3 p3 = points[p_index+1].pos;
- Vector3 p2 = p3+points[p_index+1].in;
+ Vector3 p1 = p0 + points[p_index].out;
+ Vector3 p3 = points[p_index + 1].pos;
+ Vector3 p2 = p3 + points[p_index + 1].in;
- return _bezier_interp(p_offset,p0,p1,p2,p3);
+ return _bezier_interp(p_offset, p0, p1, p2, p3);
}
Vector3 Curve3D::interpolatef(real_t p_findex) const {
+ if (p_findex < 0)
+ p_findex = 0;
+ else if (p_findex >= points.size())
+ p_findex = points.size();
- if (p_findex<0)
- p_findex=0;
- else if (p_findex>=points.size())
- p_findex=points.size();
-
- return interpolate((int)p_findex,Math::fmod(p_findex,(real_t)1.0));
-
+ return interpolate((int)p_findex, Math::fmod(p_findex, (real_t)1.0));
}
+void Curve3D::_bake_segment3d(Map<float, Vector3> &r_bake, float p_begin, float p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, float p_tol) const {
-void Curve3D::_bake_segment3d(Map<float,Vector3>& r_bake, float p_begin, float p_end,const Vector3& p_a,const Vector3& p_out,const Vector3& p_b, const Vector3& p_in,int p_depth,int p_max_depth,float p_tol) const {
+ float mp = p_begin + (p_end - p_begin) * 0.5;
+ Vector3 beg = _bezier_interp(p_begin, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector3 mid = _bezier_interp(mp, p_a, p_a + p_out, p_b + p_in, p_b);
+ Vector3 end = _bezier_interp(p_end, p_a, p_a + p_out, p_b + p_in, p_b);
- float mp = p_begin+(p_end-p_begin)*0.5;
- Vector3 beg = _bezier_interp(p_begin,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector3 mid = _bezier_interp(mp,p_a,p_a+p_out,p_b+p_in,p_b);
- Vector3 end = _bezier_interp(p_end,p_a,p_a+p_out,p_b+p_in,p_b);
-
- Vector3 na = (mid-beg).normalized();
- Vector3 nb = (end-mid).normalized();
+ Vector3 na = (mid - beg).normalized();
+ Vector3 nb = (end - mid).normalized();
float dp = na.dot(nb);
- if (dp<Math::cos(Math::deg2rad(p_tol))) {
+ if (dp < Math::cos(Math::deg2rad(p_tol))) {
- r_bake[mp]=mid;
+ r_bake[mp] = mid;
}
- if (p_depth<p_max_depth) {
- _bake_segment3d(r_bake,p_begin,mp,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol);
- _bake_segment3d(r_bake,mp,p_end,p_a,p_out,p_b,p_in,p_depth+1,p_max_depth,p_tol);
+ if (p_depth < p_max_depth) {
+ _bake_segment3d(r_bake, p_begin, mp, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol);
+ _bake_segment3d(r_bake, mp, p_end, p_a, p_out, p_b, p_in, p_depth + 1, p_max_depth, p_tol);
}
}
-
-
void Curve3D::_bake() const {
if (!baked_cache_dirty)
return;
- baked_max_ofs=0;
- baked_cache_dirty=false;
+ baked_max_ofs = 0;
+ baked_cache_dirty = false;
- if (points.size()==0) {
+ if (points.size() == 0) {
baked_point_cache.resize(0);
baked_tilt_cache.resize(0);
return;
}
- if (points.size()==1) {
+ if (points.size() == 1) {
baked_point_cache.resize(1);
- baked_point_cache.set(0,points[0].pos);
+ baked_point_cache.set(0, points[0].pos);
baked_tilt_cache.resize(1);
- baked_tilt_cache.set(0,points[0].tilt);
+ baked_tilt_cache.set(0, points[0].tilt);
return;
}
-
- Vector3 pos=points[0].pos;
+ Vector3 pos = points[0].pos;
List<Plane> pointlist;
- pointlist.push_back(Plane(pos,points[0].tilt));
+ pointlist.push_back(Plane(pos, points[0].tilt));
- for(int i=0;i<points.size()-1;i++) {
+ for (int i = 0; i < points.size() - 1; i++) {
float step = 0.1; // at least 10 substeps ought to be enough?
float p = 0;
- while(p<1.0) {
-
- float np=p+step;
- if (np>1.0)
- np=1.0;
+ while (p < 1.0) {
+ float np = p + step;
+ if (np > 1.0)
+ np = 1.0;
- Vector3 npp = _bezier_interp(np, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos);
+ Vector3 npp = _bezier_interp(np, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos);
float d = pos.distance_to(npp);
- if (d>bake_interval) {
+ if (d > bake_interval) {
// OK! between P and NP there _has_ to be Something, let's go searching!
int iterations = 10; //lots of detail!
float low = p;
float hi = np;
- float mid = low+(hi-low)*0.5;
+ float mid = low + (hi - low) * 0.5;
- for(int j=0;j<iterations;j++) {
+ for (int j = 0; j < iterations; j++) {
-
- npp = _bezier_interp(mid, points[i].pos,points[i].pos+points[i].out,points[i+1].pos+points[i+1].in,points[i+1].pos);
+ npp = _bezier_interp(mid, points[i].pos, points[i].pos + points[i].out, points[i + 1].pos + points[i + 1].in, points[i + 1].pos);
d = pos.distance_to(npp);
if (bake_interval < d)
- hi=mid;
+ hi = mid;
else
- low=mid;
- mid = low+(hi-low)*0.5;
-
+ low = mid;
+ mid = low + (hi - low) * 0.5;
}
- pos=npp;
- p=mid;
+ pos = npp;
+ p = mid;
Plane post;
- post.normal=pos;
- post.d=Math::lerp(points[i].tilt,points[i+1].tilt,mid);
+ post.normal = pos;
+ post.d = Math::lerp(points[i].tilt, points[i + 1].tilt, mid);
pointlist.push_back(post);
} else {
- p=np;
+ p = np;
}
-
}
}
- Vector3 lastpos = points[points.size()-1].pos;
- float lastilt = points[points.size()-1].tilt;
+ Vector3 lastpos = points[points.size() - 1].pos;
+ float lastilt = points[points.size() - 1].tilt;
float rem = pos.distance_to(lastpos);
- baked_max_ofs=(pointlist.size()-1)*bake_interval+rem;
- pointlist.push_back(Plane(lastpos,lastilt));
+ baked_max_ofs = (pointlist.size() - 1) * bake_interval + rem;
+ pointlist.push_back(Plane(lastpos, lastilt));
baked_point_cache.resize(pointlist.size());
PoolVector3Array::Write w = baked_point_cache.write();
- int idx=0;
+ int idx = 0;
baked_tilt_cache.resize(pointlist.size());
PoolRealArray::Write wt = baked_tilt_cache.write();
- for(List<Plane>::Element *E=pointlist.front();E;E=E->next()) {
+ for (List<Plane>::Element *E = pointlist.front(); E; E = E->next()) {
- w[idx]=E->get().normal;
- wt[idx]=E->get().d;
+ w[idx] = E->get().normal;
+ wt[idx] = E->get().d;
idx++;
}
-
}
float Curve3D::get_baked_length() const {
@@ -1112,90 +1041,87 @@ float Curve3D::get_baked_length() const {
return baked_max_ofs;
}
-Vector3 Curve3D::interpolate_baked(float p_offset,bool p_cubic) const{
+Vector3 Curve3D::interpolate_baked(float p_offset, bool p_cubic) const {
if (baked_cache_dirty)
_bake();
//validate//
int pc = baked_point_cache.size();
- if (pc==0) {
+ if (pc == 0) {
ERR_EXPLAIN("No points in Curve3D");
- ERR_FAIL_COND_V(pc==0,Vector3());
+ ERR_FAIL_COND_V(pc == 0, Vector3());
}
- if (pc==1)
+ if (pc == 1)
return baked_point_cache.get(0);
- int bpc=baked_point_cache.size();
+ int bpc = baked_point_cache.size();
PoolVector3Array::Read r = baked_point_cache.read();
- if (p_offset<0)
+ if (p_offset < 0)
return r[0];
- if (p_offset>=baked_max_ofs)
- return r[bpc-1];
+ if (p_offset >= baked_max_ofs)
+ return r[bpc - 1];
- int idx = Math::floor((double)p_offset/(double)bake_interval);
- float frac = Math::fmod(p_offset,bake_interval);
+ int idx = Math::floor((double)p_offset / (double)bake_interval);
+ float frac = Math::fmod(p_offset, bake_interval);
- if (idx>=bpc-1) {
- return r[bpc-1];
- } else if (idx==bpc-2) {
- frac/=Math::fmod(baked_max_ofs,bake_interval);
+ if (idx >= bpc - 1) {
+ return r[bpc - 1];
+ } else if (idx == bpc - 2) {
+ frac /= Math::fmod(baked_max_ofs, bake_interval);
} else {
- frac/=bake_interval;
+ frac /= bake_interval;
}
if (p_cubic) {
- Vector3 pre = idx>0? r[idx-1] : r[idx];
- Vector3 post = (idx<(bpc-2))? r[idx+2] : r[idx+1];
- return r[idx].cubic_interpolate(r[idx+1],pre,post,frac);
+ Vector3 pre = idx > 0 ? r[idx - 1] : r[idx];
+ Vector3 post = (idx < (bpc - 2)) ? r[idx + 2] : r[idx + 1];
+ return r[idx].cubic_interpolate(r[idx + 1], pre, post, frac);
} else {
- return r[idx].linear_interpolate(r[idx+1],frac);
+ return r[idx].linear_interpolate(r[idx + 1], frac);
}
}
-float Curve3D::interpolate_baked_tilt(float p_offset) const{
+float Curve3D::interpolate_baked_tilt(float p_offset) const {
if (baked_cache_dirty)
_bake();
//validate//
int pc = baked_tilt_cache.size();
- if (pc==0) {
+ if (pc == 0) {
ERR_EXPLAIN("No tilts in Curve3D");
- ERR_FAIL_COND_V(pc==0,0);
+ ERR_FAIL_COND_V(pc == 0, 0);
}
- if (pc==1)
+ if (pc == 1)
return baked_tilt_cache.get(0);
- int bpc=baked_tilt_cache.size();
+ int bpc = baked_tilt_cache.size();
PoolRealArray::Read r = baked_tilt_cache.read();
- if (p_offset<0)
+ if (p_offset < 0)
return r[0];
- if (p_offset>=baked_max_ofs)
- return r[bpc-1];
+ if (p_offset >= baked_max_ofs)
+ return r[bpc - 1];
- int idx = Math::floor((double)p_offset/(double)bake_interval);
- float frac = Math::fmod(p_offset,bake_interval);
+ int idx = Math::floor((double)p_offset / (double)bake_interval);
+ float frac = Math::fmod(p_offset, bake_interval);
- if (idx>=bpc-1) {
- return r[bpc-1];
- } else if (idx==bpc-2) {
- frac/=Math::fmod(baked_max_ofs,bake_interval);
+ if (idx >= bpc - 1) {
+ return r[bpc - 1];
+ } else if (idx == bpc - 2) {
+ frac /= Math::fmod(baked_max_ofs, bake_interval);
} else {
- frac/=bake_interval;
+ frac /= bake_interval;
}
- return Math::lerp(r[idx],r[idx+1],frac);
-
-
+ return Math::lerp(r[idx], r[idx + 1], frac);
}
-
PoolVector3Array Curve3D::get_baked_points() const {
if (baked_cache_dirty)
@@ -1204,7 +1130,6 @@ PoolVector3Array Curve3D::get_baked_points() const {
return baked_point_cache;
}
-
PoolRealArray Curve3D::get_baked_tilts() const {
if (baked_cache_dirty)
@@ -1213,16 +1138,14 @@ PoolRealArray Curve3D::get_baked_tilts() const {
return baked_tilt_cache;
}
+void Curve3D::set_bake_interval(float p_tolerance) {
-void Curve3D::set_bake_interval(float p_tolerance){
-
- bake_interval=p_tolerance;
- baked_cache_dirty=true;
+ bake_interval = p_tolerance;
+ baked_cache_dirty = true;
emit_signal(CoreStringNames::get_singleton()->changed);
-
}
-float Curve3D::get_bake_interval() const{
+float Curve3D::get_bake_interval() const {
return bake_interval;
}
@@ -1232,163 +1155,134 @@ Dictionary Curve3D::_get_data() const {
Dictionary dc;
PoolVector3Array d;
- d.resize(points.size()*3);
+ d.resize(points.size() * 3);
PoolVector3Array::Write w = d.write();
PoolRealArray t;
t.resize(points.size());
PoolRealArray::Write wt = t.write();
+ for (int i = 0; i < points.size(); i++) {
- for(int i=0;i<points.size();i++) {
-
- w[i*3+0]=points[i].in;
- w[i*3+1]=points[i].out;
- w[i*3+2]=points[i].pos;
- wt[i]=points[i].tilt;
+ w[i * 3 + 0] = points[i].in;
+ w[i * 3 + 1] = points[i].out;
+ w[i * 3 + 2] = points[i].pos;
+ wt[i] = points[i].tilt;
}
- w=PoolVector3Array::Write();
- wt=PoolRealArray::Write();
+ w = PoolVector3Array::Write();
+ wt = PoolRealArray::Write();
- dc["points"]=d;
- dc["tilts"]=t;
+ dc["points"] = d;
+ dc["tilts"] = t;
return dc;
}
-void Curve3D::_set_data(const Dictionary& p_data){
-
+void Curve3D::_set_data(const Dictionary &p_data) {
ERR_FAIL_COND(!p_data.has("points"));
ERR_FAIL_COND(!p_data.has("tilts"));
- PoolVector3Array rp=p_data["points"];
+ PoolVector3Array rp = p_data["points"];
int pc = rp.size();
- ERR_FAIL_COND(pc%3!=0);
- points.resize(pc/3);
+ ERR_FAIL_COND(pc % 3 != 0);
+ points.resize(pc / 3);
PoolVector3Array::Read r = rp.read();
- PoolRealArray rtl=p_data["tilts"];
- PoolRealArray::Read rt=rtl.read();
+ PoolRealArray rtl = p_data["tilts"];
+ PoolRealArray::Read rt = rtl.read();
- for(int i=0;i<points.size();i++) {
+ for (int i = 0; i < points.size(); i++) {
- points[i].in=r[i*3+0];
- points[i].out=r[i*3+1];
- points[i].pos=r[i*3+2];
- points[i].tilt=rt[i];
+ points[i].in = r[i * 3 + 0];
+ points[i].out = r[i * 3 + 1];
+ points[i].pos = r[i * 3 + 2];
+ points[i].tilt = rt[i];
}
- baked_cache_dirty=true;
-
+ baked_cache_dirty = true;
}
-
-PoolVector3Array Curve3D::tesselate(int p_max_stages,float p_tolerance) const {
+PoolVector3Array Curve3D::tesselate(int p_max_stages, float p_tolerance) const {
PoolVector3Array tess;
-
- if (points.size()==0) {
+ if (points.size() == 0) {
return tess;
}
- Vector< Map<float,Vector3> > midpoints;
+ Vector<Map<float, Vector3> > midpoints;
- midpoints.resize(points.size()-1);
+ midpoints.resize(points.size() - 1);
- int pc=1;
- for(int i=0;i<points.size()-1;i++) {
+ int pc = 1;
+ for (int i = 0; i < points.size() - 1; i++) {
- _bake_segment3d(midpoints[i],0,1,points[i].pos,points[i].out,points[i+1].pos,points[i+1].in,0,p_max_stages,p_tolerance);
+ _bake_segment3d(midpoints[i], 0, 1, points[i].pos, points[i].out, points[i + 1].pos, points[i + 1].in, 0, p_max_stages, p_tolerance);
pc++;
- pc+=midpoints[i].size();
-
+ pc += midpoints[i].size();
}
tess.resize(pc);
- PoolVector3Array::Write bpw=tess.write();
- bpw[0]=points[0].pos;
- int pidx=0;
+ PoolVector3Array::Write bpw = tess.write();
+ bpw[0] = points[0].pos;
+ int pidx = 0;
- for(int i=0;i<points.size()-1;i++) {
+ for (int i = 0; i < points.size() - 1; i++) {
- for(Map<float,Vector3>::Element *E=midpoints[i].front();E;E=E->next()) {
+ for (Map<float, Vector3>::Element *E = midpoints[i].front(); E; E = E->next()) {
pidx++;
bpw[pidx] = E->get();
}
pidx++;
- bpw[pidx] = points[i+1].pos;
-
+ bpw[pidx] = points[i + 1].pos;
}
- bpw=PoolVector3Array::Write ();
+ bpw = PoolVector3Array::Write();
return tess;
-
}
void Curve3D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_point_count"),&Curve3D::get_point_count);
- ClassDB::bind_method(D_METHOD("add_point","pos","in","out","atpos"),&Curve3D::add_point,DEFVAL(Vector3()),DEFVAL(Vector3()),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("set_point_pos","idx","pos"),&Curve3D::set_point_pos);
- ClassDB::bind_method(D_METHOD("get_point_pos","idx"),&Curve3D::get_point_pos);
- ClassDB::bind_method(D_METHOD("set_point_tilt","idx","tilt"),&Curve3D::set_point_tilt);
- ClassDB::bind_method(D_METHOD("get_point_tilt","idx"),&Curve3D::get_point_tilt);
- ClassDB::bind_method(D_METHOD("set_point_in","idx","pos"),&Curve3D::set_point_in);
- ClassDB::bind_method(D_METHOD("get_point_in","idx"),&Curve3D::get_point_in);
- ClassDB::bind_method(D_METHOD("set_point_out","idx","pos"),&Curve3D::set_point_out);
- ClassDB::bind_method(D_METHOD("get_point_out","idx"),&Curve3D::get_point_out);
- ClassDB::bind_method(D_METHOD("remove_point","idx"),&Curve3D::remove_point);
- ClassDB::bind_method(D_METHOD("clear_points"),&Curve3D::clear_points);
- ClassDB::bind_method(D_METHOD("interpolate","idx","t"),&Curve3D::interpolate);
- ClassDB::bind_method(D_METHOD("interpolatef","fofs"),&Curve3D::interpolatef);
+ ClassDB::bind_method(D_METHOD("get_point_count"), &Curve3D::get_point_count);
+ ClassDB::bind_method(D_METHOD("add_point", "pos", "in", "out", "atpos"), &Curve3D::add_point, DEFVAL(Vector3()), DEFVAL(Vector3()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("set_point_pos", "idx", "pos"), &Curve3D::set_point_pos);
+ ClassDB::bind_method(D_METHOD("get_point_pos", "idx"), &Curve3D::get_point_pos);
+ ClassDB::bind_method(D_METHOD("set_point_tilt", "idx", "tilt"), &Curve3D::set_point_tilt);
+ ClassDB::bind_method(D_METHOD("get_point_tilt", "idx"), &Curve3D::get_point_tilt);
+ ClassDB::bind_method(D_METHOD("set_point_in", "idx", "pos"), &Curve3D::set_point_in);
+ ClassDB::bind_method(D_METHOD("get_point_in", "idx"), &Curve3D::get_point_in);
+ ClassDB::bind_method(D_METHOD("set_point_out", "idx", "pos"), &Curve3D::set_point_out);
+ ClassDB::bind_method(D_METHOD("get_point_out", "idx"), &Curve3D::get_point_out);
+ ClassDB::bind_method(D_METHOD("remove_point", "idx"), &Curve3D::remove_point);
+ ClassDB::bind_method(D_METHOD("clear_points"), &Curve3D::clear_points);
+ ClassDB::bind_method(D_METHOD("interpolate", "idx", "t"), &Curve3D::interpolate);
+ ClassDB::bind_method(D_METHOD("interpolatef", "fofs"), &Curve3D::interpolatef);
//ClassDB::bind_method(D_METHOD("bake","subdivs"),&Curve3D::bake,DEFVAL(10));
- ClassDB::bind_method(D_METHOD("set_bake_interval","distance"),&Curve3D::set_bake_interval);
- ClassDB::bind_method(D_METHOD("get_bake_interval"),&Curve3D::get_bake_interval);
-
- ClassDB::bind_method(D_METHOD("get_baked_length"),&Curve3D::get_baked_length);
- ClassDB::bind_method(D_METHOD("interpolate_baked","offset","cubic"),&Curve3D::interpolate_baked,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_baked_points"),&Curve3D::get_baked_points);
- ClassDB::bind_method(D_METHOD("get_baked_tilts"),&Curve3D::get_baked_tilts);
- ClassDB::bind_method(D_METHOD("tesselate","max_stages","tolerance_degrees"),&Curve3D::tesselate,DEFVAL(5),DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("set_bake_interval", "distance"), &Curve3D::set_bake_interval);
+ ClassDB::bind_method(D_METHOD("get_bake_interval"), &Curve3D::get_bake_interval);
- ClassDB::bind_method(D_METHOD("_get_data"),&Curve3D::_get_data);
- ClassDB::bind_method(D_METHOD("_set_data"),&Curve3D::_set_data);
+ ClassDB::bind_method(D_METHOD("get_baked_length"), &Curve3D::get_baked_length);
+ ClassDB::bind_method(D_METHOD("interpolate_baked", "offset", "cubic"), &Curve3D::interpolate_baked, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_baked_points"), &Curve3D::get_baked_points);
+ ClassDB::bind_method(D_METHOD("get_baked_tilts"), &Curve3D::get_baked_tilts);
+ ClassDB::bind_method(D_METHOD("tesselate", "max_stages", "tolerance_degrees"), &Curve3D::tesselate, DEFVAL(5), DEFVAL(4));
+ ClassDB::bind_method(D_METHOD("_get_data"), &Curve3D::_get_data);
+ ClassDB::bind_method(D_METHOD("_set_data"), &Curve3D::_set_data);
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "bake_interval",PROPERTY_HINT_RANGE,"0.01,512,0.01"), "set_bake_interval","get_bake_interval");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "bake_interval", PROPERTY_HINT_RANGE, "0.01,512,0.01"), "set_bake_interval", "get_bake_interval");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
/*ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_out"), "set_points_out","get_points_out");
ADD_PROPERTY( PropertyInfo( Variant::VECTOR3_ARRAY, "points_pos"), "set_points_pos","get_points_pos");
*/
}
-
-
-
-Curve3D::Curve3D()
-{
- baked_cache_dirty=false;
- baked_max_ofs=0;
-/* add_point(Vector3(-1,0,0));
+Curve3D::Curve3D() {
+ baked_cache_dirty = false;
+ baked_max_ofs = 0;
+ /* add_point(Vector3(-1,0,0));
add_point(Vector3(0,2,0));
add_point(Vector3(0,3,5));*/
- bake_interval=0.2;
-
+ bake_interval = 0.2;
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/scene/resources/curve.h b/scene/resources/curve.h
index 3362109354..2a8fab7f4c 100644
--- a/scene/resources/curve.h
+++ b/scene/resources/curve.h
@@ -81,10 +81,9 @@ public:
#endif
-
class Curve2D : public Resource {
- GDCLASS(Curve2D,Resource);
+ GDCLASS(Curve2D, Resource);
struct Point {
@@ -93,7 +92,6 @@ class Curve2D : public Resource {
Vector2 pos;
};
-
Vector<Point> points;
struct BakedPoint {
@@ -106,31 +104,25 @@ class Curve2D : public Resource {
mutable PoolVector2Array baked_point_cache;
mutable float baked_max_ofs;
-
void _bake() const;
float bake_interval;
- void _bake_segment2d(Map<float,Vector2>& r_bake, float p_begin, float p_end,const Vector2& p_a,const Vector2& p_out,const Vector2& p_b, const Vector2& p_in,int p_depth,int p_max_depth,float p_tol) const;
+ void _bake_segment2d(Map<float, Vector2> &r_bake, float p_begin, float p_end, const Vector2 &p_a, const Vector2 &p_out, const Vector2 &p_b, const Vector2 &p_in, int p_depth, int p_max_depth, float p_tol) const;
Dictionary _get_data() const;
void _set_data(const Dictionary &p_data);
protected:
-
static void _bind_methods();
-
-
public:
-
-
int get_point_count() const;
- void add_point(const Vector2& p_pos, const Vector2& p_in=Vector2(), const Vector2& p_out=Vector2(),int p_atpos=-1);
- void set_point_pos(int p_index, const Vector2& p_pos);
+ void add_point(const Vector2 &p_pos, const Vector2 &p_in = Vector2(), const Vector2 &p_out = Vector2(), int p_atpos = -1);
+ void set_point_pos(int p_index, const Vector2 &p_pos);
Vector2 get_point_pos(int p_index) const;
- void set_point_in(int p_index, const Vector2& p_in);
+ void set_point_in(int p_index, const Vector2 &p_in);
Vector2 get_point_in(int p_index) const;
- void set_point_out(int p_index, const Vector2& p_out);
+ void set_point_out(int p_index, const Vector2 &p_out);
Vector2 get_point_out(int p_index) const;
void remove_point(int p_index);
void clear_points();
@@ -138,26 +130,21 @@ public:
Vector2 interpolate(int p_index, float p_offset) const;
Vector2 interpolatef(real_t p_findex) const;
-
void set_bake_interval(float p_distance);
float get_bake_interval() const;
-
float get_baked_length() const;
- Vector2 interpolate_baked(float p_offset,bool p_cubic=false) const;
+ Vector2 interpolate_baked(float p_offset, bool p_cubic = false) const;
PoolVector2Array get_baked_points() const; //useful for going thru
- PoolVector2Array tesselate(int p_max_stages=5,float p_tolerance=4) const; //useful for display
-
+ PoolVector2Array tesselate(int p_max_stages = 5, float p_tolerance = 4) const; //useful for display
Curve2D();
};
-
-
class Curve3D : public Resource {
- GDCLASS(Curve3D,Resource);
+ GDCLASS(Curve3D, Resource);
struct Point {
@@ -166,10 +153,9 @@ class Curve3D : public Resource {
Vector3 pos;
float tilt;
- Point() { tilt=0; }
+ Point() { tilt = 0; }
};
-
Vector<Point> points;
struct BakedPoint {
@@ -183,33 +169,27 @@ class Curve3D : public Resource {
mutable PoolRealArray baked_tilt_cache;
mutable float baked_max_ofs;
-
void _bake() const;
float bake_interval;
- void _bake_segment3d(Map<float,Vector3>& r_bake, float p_begin, float p_end,const Vector3& p_a,const Vector3& p_out,const Vector3& p_b, const Vector3& p_in,int p_depth,int p_max_depth,float p_tol) const;
+ void _bake_segment3d(Map<float, Vector3> &r_bake, float p_begin, float p_end, const Vector3 &p_a, const Vector3 &p_out, const Vector3 &p_b, const Vector3 &p_in, int p_depth, int p_max_depth, float p_tol) const;
Dictionary _get_data() const;
void _set_data(const Dictionary &p_data);
protected:
-
static void _bind_methods();
-
-
public:
-
-
int get_point_count() const;
- void add_point(const Vector3& p_pos, const Vector3& p_in=Vector3(), const Vector3& p_out=Vector3(),int p_atpos=-1);
- void set_point_pos(int p_index, const Vector3& p_pos);
+ void add_point(const Vector3 &p_pos, const Vector3 &p_in = Vector3(), const Vector3 &p_out = Vector3(), int p_atpos = -1);
+ void set_point_pos(int p_index, const Vector3 &p_pos);
Vector3 get_point_pos(int p_index) const;
void set_point_tilt(int p_index, float p_tilt);
float get_point_tilt(int p_index) const;
- void set_point_in(int p_index, const Vector3& p_in);
+ void set_point_in(int p_index, const Vector3 &p_in);
Vector3 get_point_in(int p_index) const;
- void set_point_out(int p_index, const Vector3& p_out);
+ void set_point_out(int p_index, const Vector3 &p_out);
Vector3 get_point_out(int p_index) const;
void remove_point(int p_index);
void clear_points();
@@ -217,19 +197,16 @@ public:
Vector3 interpolate(int p_index, float p_offset) const;
Vector3 interpolatef(real_t p_findex) const;
-
void set_bake_interval(float p_distance);
float get_bake_interval() const;
-
float get_baked_length() const;
- Vector3 interpolate_baked(float p_offset,bool p_cubic=false) const;
+ Vector3 interpolate_baked(float p_offset, bool p_cubic = false) const;
float interpolate_baked_tilt(float p_offset) const;
PoolVector3Array get_baked_points() const; //useful for going thru
PoolRealArray get_baked_tilts() const; //useful for going thru
- PoolVector3Array tesselate(int p_max_stages=5,float p_tolerance=4) const; //useful for display
-
+ PoolVector3Array tesselate(int p_max_stages = 5, float p_tolerance = 4) const; //useful for display
Curve3D();
};
diff --git a/scene/resources/default_theme/default_theme.cpp b/scene/resources/default_theme/default_theme.cpp
index dbe0f3e33e..60490d70ca 100644
--- a/scene/resources/default_theme/default_theme.cpp
+++ b/scene/resources/default_theme/default_theme.cpp
@@ -31,196 +31,182 @@
#include "scene/resources/theme.h"
-#include "theme_data.h"
#include "os/os.h"
+#include "theme_data.h"
-#include "font_lodpi.inc"
#include "font_hidpi.inc"
+#include "font_lodpi.inc"
-typedef Map<const void*,Ref<ImageTexture> > TexCacheMap;
+typedef Map<const void *, Ref<ImageTexture> > TexCacheMap;
-static TexCacheMap *tex_cache;
-static float scale=1;
+static TexCacheMap *tex_cache;
+static float scale = 1;
-template<class T>
-static Ref<StyleBoxTexture> make_stylebox(T p_src,float p_left, float p_top, float p_right, float p_botton,float p_margin_left=-1, float p_margin_top=-1, float p_margin_right=-1, float p_margin_botton=-1, bool p_draw_center=true) {
+template <class T>
+static Ref<StyleBoxTexture> make_stylebox(T p_src, float p_left, float p_top, float p_right, float p_botton, float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_botton = -1, bool p_draw_center = true) {
Ref<ImageTexture> texture;
-
if (tex_cache->has(p_src)) {
- texture=(*tex_cache)[p_src];
+ texture = (*tex_cache)[p_src];
} else {
- texture = Ref<ImageTexture>( memnew( ImageTexture ) );
+ texture = Ref<ImageTexture>(memnew(ImageTexture));
Image img(p_src);
- if (scale>1) {
- Size2 orig_size = Size2(img.get_width(),img.get_height());
+ if (scale > 1) {
+ Size2 orig_size = Size2(img.get_width(), img.get_height());
img.convert(Image::FORMAT_RGBA8);
img.expand_x2_hq2x();
- if (scale!=2.0) {
- img.resize(orig_size.x*scale,orig_size.y*scale);
+ if (scale != 2.0) {
+ img.resize(orig_size.x * scale, orig_size.y * scale);
}
- } else if (scale<1) {
- Size2 orig_size = Size2(img.get_width(),img.get_height());
+ } else if (scale < 1) {
+ Size2 orig_size = Size2(img.get_width(), img.get_height());
img.convert(Image::FORMAT_RGBA8);
- img.resize(orig_size.x*scale,orig_size.y*scale);
+ img.resize(orig_size.x * scale, orig_size.y * scale);
}
- texture->create_from_image( img,ImageTexture::FLAG_FILTER );
- (*tex_cache)[p_src]=texture;
+ texture->create_from_image(img, ImageTexture::FLAG_FILTER);
+ (*tex_cache)[p_src] = texture;
}
-
- Ref<StyleBoxTexture> style( memnew( StyleBoxTexture ) );
+ Ref<StyleBoxTexture> style(memnew(StyleBoxTexture));
style->set_texture(texture);
- style->set_margin_size( MARGIN_LEFT, p_left * scale);
- style->set_margin_size( MARGIN_RIGHT, p_right * scale);
- style->set_margin_size( MARGIN_BOTTOM, p_botton * scale);
- style->set_margin_size( MARGIN_TOP, p_top * scale);
- style->set_default_margin( MARGIN_LEFT, p_margin_left * scale);
- style->set_default_margin( MARGIN_RIGHT, p_margin_right * scale);
- style->set_default_margin( MARGIN_BOTTOM, p_margin_botton * scale);
- style->set_default_margin( MARGIN_TOP, p_margin_top * scale);
+ style->set_margin_size(MARGIN_LEFT, p_left * scale);
+ style->set_margin_size(MARGIN_RIGHT, p_right * scale);
+ style->set_margin_size(MARGIN_BOTTOM, p_botton * scale);
+ style->set_margin_size(MARGIN_TOP, p_top * scale);
+ style->set_default_margin(MARGIN_LEFT, p_margin_left * scale);
+ style->set_default_margin(MARGIN_RIGHT, p_margin_right * scale);
+ style->set_default_margin(MARGIN_BOTTOM, p_margin_botton * scale);
+ style->set_default_margin(MARGIN_TOP, p_margin_top * scale);
style->set_draw_center(p_draw_center);
return style;
}
+static Ref<StyleBoxTexture> sb_expand(Ref<StyleBoxTexture> p_sbox, float p_left, float p_top, float p_right, float p_botton) {
-static Ref<StyleBoxTexture> sb_expand(Ref<StyleBoxTexture> p_sbox,float p_left, float p_top, float p_right, float p_botton) {
-
- p_sbox->set_expand_margin_size(MARGIN_LEFT,p_left * scale);
- p_sbox->set_expand_margin_size(MARGIN_TOP,p_top * scale);
- p_sbox->set_expand_margin_size(MARGIN_RIGHT,p_right * scale);
- p_sbox->set_expand_margin_size(MARGIN_BOTTOM,p_botton * scale);
+ p_sbox->set_expand_margin_size(MARGIN_LEFT, p_left * scale);
+ p_sbox->set_expand_margin_size(MARGIN_TOP, p_top * scale);
+ p_sbox->set_expand_margin_size(MARGIN_RIGHT, p_right * scale);
+ p_sbox->set_expand_margin_size(MARGIN_BOTTOM, p_botton * scale);
return p_sbox;
}
-template<class T>
+template <class T>
static Ref<Texture> make_icon(T p_src) {
-
- Ref<ImageTexture> texture( memnew( ImageTexture ) );
+ Ref<ImageTexture> texture(memnew(ImageTexture));
Image img = Image(p_src);
- if (scale>1) {
- Size2 orig_size = Size2(img.get_width(),img.get_height());
+ if (scale > 1) {
+ Size2 orig_size = Size2(img.get_width(), img.get_height());
img.convert(Image::FORMAT_RGBA8);
img.expand_x2_hq2x();
- if (scale!=2.0) {
- img.resize(orig_size.x*scale,orig_size.y*scale);
+ if (scale != 2.0) {
+ img.resize(orig_size.x * scale, orig_size.y * scale);
}
- } else if (scale<1) {
- Size2 orig_size = Size2(img.get_width(),img.get_height());
+ } else if (scale < 1) {
+ Size2 orig_size = Size2(img.get_width(), img.get_height());
img.convert(Image::FORMAT_RGBA8);
- img.resize(orig_size.x*scale,orig_size.y*scale);
+ img.resize(orig_size.x * scale, orig_size.y * scale);
}
- texture->create_from_image( img,ImageTexture::FLAG_FILTER );
+ texture->create_from_image(img, ImageTexture::FLAG_FILTER);
return texture;
}
-static Ref<Shader> make_shader(const char*vertex_code,const char*fragment_code,const char*lighting_code) {
- Ref<Shader> shader = (memnew( Shader(Shader::MODE_CANVAS_ITEM) ));
+static Ref<Shader> make_shader(const char *vertex_code, const char *fragment_code, const char *lighting_code) {
+ Ref<Shader> shader = (memnew(Shader(Shader::MODE_CANVAS_ITEM)));
//shader->set_code(vertex_code, fragment_code, lighting_code);
return shader;
}
-static Ref<BitmapFont> make_font(int p_height,int p_ascent, int p_valign, int p_charcount, const int *p_chars,const Ref<Texture> &p_texture) {
-
+static Ref<BitmapFont> make_font(int p_height, int p_ascent, int p_valign, int p_charcount, const int *p_chars, const Ref<Texture> &p_texture) {
- Ref<BitmapFont> font( memnew( BitmapFont ) );
- font->add_texture( p_texture );
+ Ref<BitmapFont> font(memnew(BitmapFont));
+ font->add_texture(p_texture);
- for (int i=0;i<p_charcount;i++) {
+ for (int i = 0; i < p_charcount; i++) {
- const int *c = &p_chars[i*8];
+ const int *c = &p_chars[i * 8];
- int chr=c[0];
+ int chr = c[0];
Rect2 frect;
- frect.pos.x=c[1];
- frect.pos.y=c[2];
- frect.size.x=c[3];
- frect.size.y=c[4];
- Point2 align( c[5], c[6]+p_valign);
- int advance=c[7];
-
-
- font->add_char( chr, 0, frect, align,advance );
-
+ frect.pos.x = c[1];
+ frect.pos.y = c[2];
+ frect.size.x = c[3];
+ frect.size.y = c[4];
+ Point2 align(c[5], c[6] + p_valign);
+ int advance = c[7];
+
+ font->add_char(chr, 0, frect, align, advance);
}
- font->set_height( p_height );
- font->set_ascent( p_ascent );
+ font->set_height(p_height);
+ font->set_ascent(p_ascent);
return font;
}
+static Ref<BitmapFont> make_font2(int p_height, int p_ascent, int p_charcount, const int *p_char_rects, int p_kerning_count, const int *p_kernings, int p_w, int p_h, const unsigned char *p_img) {
-
-static Ref<BitmapFont> make_font2(int p_height,int p_ascent, int p_charcount, const int *p_char_rects,int p_kerning_count,const int *p_kernings,int p_w, int p_h, const unsigned char *p_img) {
-
-
- Ref<BitmapFont> font( memnew( BitmapFont ) );
+ Ref<BitmapFont> font(memnew(BitmapFont));
Image image(p_img);
- Ref<ImageTexture> tex = memnew( ImageTexture );
+ Ref<ImageTexture> tex = memnew(ImageTexture);
tex->create_from_image(image);
- font->add_texture( tex );
+ font->add_texture(tex);
- for (int i=0;i<p_charcount;i++) {
+ for (int i = 0; i < p_charcount; i++) {
- const int *c = &p_char_rects[i*8];
+ const int *c = &p_char_rects[i * 8];
- int chr=c[0];
+ int chr = c[0];
Rect2 frect;
- frect.pos.x=c[1];
- frect.pos.y=c[2];
- frect.size.x=c[3];
- frect.size.y=c[4];
- Point2 align( c[6], c[5]);
- int advance=c[7];
-
- font->add_char( chr, 0, frect, align,advance );
-
+ frect.pos.x = c[1];
+ frect.pos.y = c[2];
+ frect.size.x = c[3];
+ frect.size.y = c[4];
+ Point2 align(c[6], c[5]);
+ int advance = c[7];
+
+ font->add_char(chr, 0, frect, align, advance);
}
- for(int i=0;i<p_kerning_count;i++) {
+ for (int i = 0; i < p_kerning_count; i++) {
- font->add_kerning_pair(p_kernings[i*3+0],p_kernings[i*3+1],p_kernings[i*3+2]);
+ font->add_kerning_pair(p_kernings[i * 3 + 0], p_kernings[i * 3 + 1], p_kernings[i * 3 + 2]);
}
- font->set_height( p_height );
- font->set_ascent( p_ascent );
+ font->set_height(p_height);
+ font->set_ascent(p_ascent);
return font;
}
+static Ref<StyleBox> make_empty_stylebox(float p_margin_left = -1, float p_margin_top = -1, float p_margin_right = -1, float p_margin_botton = -1) {
-static Ref<StyleBox> make_empty_stylebox(float p_margin_left=-1, float p_margin_top=-1, float p_margin_right=-1, float p_margin_botton=-1) {
+ Ref<StyleBox> style(memnew(StyleBoxEmpty));
- Ref<StyleBox> style( memnew( StyleBoxEmpty) );
-
- style->set_default_margin( MARGIN_LEFT, p_margin_left * scale);
- style->set_default_margin( MARGIN_RIGHT, p_margin_right * scale);
- style->set_default_margin( MARGIN_BOTTOM, p_margin_botton * scale);
- style->set_default_margin( MARGIN_TOP, p_margin_top * scale);
+ style->set_default_margin(MARGIN_LEFT, p_margin_left * scale);
+ style->set_default_margin(MARGIN_RIGHT, p_margin_right * scale);
+ style->set_default_margin(MARGIN_BOTTOM, p_margin_botton * scale);
+ style->set_default_margin(MARGIN_TOP, p_margin_top * scale);
return style;
}
+void fill_default_theme(Ref<Theme> &t, const Ref<Font> &default_font, const Ref<Font> &large_font, Ref<Texture> &default_icon, Ref<StyleBox> &default_style, float p_scale) {
+ scale = p_scale;
-void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref<Font> & large_font, Ref<Texture>& default_icon, Ref<StyleBox>& default_style, float p_scale) {
-
- scale=p_scale;
-
- tex_cache = memnew( TexCacheMap );
+ tex_cache = memnew(TexCacheMap);
//Ref<BitmapFont> default_font = make_font(_bi_font_normal_height,_bi_font_normal_ascent,_bi_font_normal_valign,_bi_font_normal_charcount,_bi_font_normal_characters,make_icon(font_normal_png));
@@ -230,356 +216,324 @@ void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref
Color control_font_color_lower = Color::html("a0a0a0");
Color control_font_color_low = Color::html("b0b0b0");
Color control_font_color_hover = Color::html("f0f0f0");
- Color control_font_color_disabled = Color(0.9,0.9,0.9,0.2);
+ Color control_font_color_disabled = Color(0.9, 0.9, 0.9, 0.2);
Color control_font_color_pressed = Color::html("ffffff");
Color font_color_selection = Color::html("7d7d7d");
-
// Panel
- t->set_stylebox("panel","Panel", make_stylebox( panel_bg_png,0,0,0,0) );
-
-
+ t->set_stylebox("panel", "Panel", make_stylebox(panel_bg_png, 0, 0, 0, 0));
// Focus
- Ref<StyleBoxTexture> focus = make_stylebox( focus_png,5,5,5,5);
- for(int i=0;i<4;i++) {
- focus->set_expand_margin_size(Margin(i),1 *scale);
+ Ref<StyleBoxTexture> focus = make_stylebox(focus_png, 5, 5, 5, 5);
+ for (int i = 0; i < 4; i++) {
+ focus->set_expand_margin_size(Margin(i), 1 * scale);
}
-
-
// Button
- Ref<StyleBox> sb_button_normal = sb_expand( make_stylebox( button_normal_png,4,4,4,4,6,3,6,3),2,2,2,2);
- Ref<StyleBox> sb_button_pressed = sb_expand( make_stylebox( button_pressed_png,4,4,4,4,6,3,6,3),2,2,2,2);
- Ref<StyleBox> sb_button_hover = sb_expand( make_stylebox( button_hover_png,4,4,4,4,6,2,6,2),2,2,2,2);
- Ref<StyleBox> sb_button_disabled = sb_expand( make_stylebox( button_disabled_png,4,4,4,4,6,2,6,2),2,2,2,2);
- Ref<StyleBox> sb_button_focus = sb_expand( make_stylebox( button_focus_png,4,4,4,4,6,2,6,2),2,2,2,2);
+ Ref<StyleBox> sb_button_normal = sb_expand(make_stylebox(button_normal_png, 4, 4, 4, 4, 6, 3, 6, 3), 2, 2, 2, 2);
+ Ref<StyleBox> sb_button_pressed = sb_expand(make_stylebox(button_pressed_png, 4, 4, 4, 4, 6, 3, 6, 3), 2, 2, 2, 2);
+ Ref<StyleBox> sb_button_hover = sb_expand(make_stylebox(button_hover_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2);
+ Ref<StyleBox> sb_button_disabled = sb_expand(make_stylebox(button_disabled_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2);
+ Ref<StyleBox> sb_button_focus = sb_expand(make_stylebox(button_focus_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2);
- t->set_stylebox("normal","Button", sb_button_normal);
- t->set_stylebox("pressed","Button", sb_button_pressed);
- t->set_stylebox("hover","Button", sb_button_hover);
- t->set_stylebox("disabled","Button", sb_button_disabled);
- t->set_stylebox("focus","Button", sb_button_focus);
+ t->set_stylebox("normal", "Button", sb_button_normal);
+ t->set_stylebox("pressed", "Button", sb_button_pressed);
+ t->set_stylebox("hover", "Button", sb_button_hover);
+ t->set_stylebox("disabled", "Button", sb_button_disabled);
+ t->set_stylebox("focus", "Button", sb_button_focus);
- t->set_font("font","Button", default_font );
+ t->set_font("font", "Button", default_font);
- t->set_color("font_color","Button", control_font_color );
- t->set_color("font_color_pressed","Button", control_font_color_pressed );
- t->set_color("font_color_hover","Button", control_font_color_hover );
- t->set_color("font_color_disabled","Button", control_font_color_disabled );
+ t->set_color("font_color", "Button", control_font_color);
+ t->set_color("font_color_pressed", "Button", control_font_color_pressed);
+ t->set_color("font_color_hover", "Button", control_font_color_hover);
+ t->set_color("font_color_disabled", "Button", control_font_color_disabled);
- t->set_constant("hseparation","Button", 2 *scale);
+ t->set_constant("hseparation", "Button", 2 * scale);
// LinkButton
- t->set_font("font","LinkButton", default_font );
+ t->set_font("font", "LinkButton", default_font);
- t->set_color("font_color","LinkButton", control_font_color );
- t->set_color("font_color_pressed","LinkButton", control_font_color_pressed );
- t->set_color("font_color_hover","LinkButton", control_font_color_hover );
+ t->set_color("font_color", "LinkButton", control_font_color);
+ t->set_color("font_color_pressed", "LinkButton", control_font_color_pressed);
+ t->set_color("font_color_hover", "LinkButton", control_font_color_hover);
- t->set_constant("underline_spacing","LinkButton", 2 *scale);
+ t->set_constant("underline_spacing", "LinkButton", 2 * scale);
// ColorPickerButton
- t->set_stylebox("normal","ColorPickerButton", sb_button_normal);
- t->set_stylebox("pressed","ColorPickerButton", sb_button_pressed);
- t->set_stylebox("hover","ColorPickerButton", sb_button_hover);
- t->set_stylebox("disabled","ColorPickerButton", sb_button_disabled);
- t->set_stylebox("focus","ColorPickerButton", sb_button_focus);
+ t->set_stylebox("normal", "ColorPickerButton", sb_button_normal);
+ t->set_stylebox("pressed", "ColorPickerButton", sb_button_pressed);
+ t->set_stylebox("hover", "ColorPickerButton", sb_button_hover);
+ t->set_stylebox("disabled", "ColorPickerButton", sb_button_disabled);
+ t->set_stylebox("focus", "ColorPickerButton", sb_button_focus);
- t->set_font("font","ColorPickerButton", default_font );
+ t->set_font("font", "ColorPickerButton", default_font);
- t->set_color("font_color","ColorPickerButton", Color(1,1,1,1) );
- t->set_color("font_color_pressed","ColorPickerButton", Color(0.8,0.8,0.8,1) );
- t->set_color("font_color_hover","ColorPickerButton", Color(1,1,1,1) );
- t->set_color("font_color_disabled","ColorPickerButton", Color(0.9,0.9,0.9,0.3) );
-
- t->set_constant("hseparation","ColorPickerButton", 2 *scale);
+ t->set_color("font_color", "ColorPickerButton", Color(1, 1, 1, 1));
+ t->set_color("font_color_pressed", "ColorPickerButton", Color(0.8, 0.8, 0.8, 1));
+ t->set_color("font_color_hover", "ColorPickerButton", Color(1, 1, 1, 1));
+ t->set_color("font_color_disabled", "ColorPickerButton", Color(0.9, 0.9, 0.9, 0.3));
+ t->set_constant("hseparation", "ColorPickerButton", 2 * scale);
// ToolButton
- Ref<StyleBox> tb_empty = memnew( StyleBoxEmpty );
- tb_empty->set_default_margin(MARGIN_LEFT,6 *scale);
- tb_empty->set_default_margin(MARGIN_RIGHT,6 *scale);
- tb_empty->set_default_margin(MARGIN_TOP,4 *scale);
- tb_empty->set_default_margin(MARGIN_BOTTOM,4 *scale);
-
- t->set_stylebox("normal","ToolButton", tb_empty);
- t->set_stylebox("pressed","ToolButton", make_stylebox( button_pressed_png,4,4,4,4) );
- t->set_stylebox("hover","ToolButton", make_stylebox( button_normal_png,4,4,4,4) );
- t->set_stylebox("disabled","ToolButton", make_empty_stylebox(4,4,4,4) );
- t->set_stylebox("focus","ToolButton", focus );
- t->set_font("font","ToolButton", default_font );
-
- t->set_color("font_color","ToolButton", control_font_color );
- t->set_color("font_color_pressed","ToolButton", control_font_color_pressed );
- t->set_color("font_color_hover","ToolButton", control_font_color_hover );
- t->set_color("font_color_disabled","ToolButton", Color(0.9,0.95,1,0.3) );
+ Ref<StyleBox> tb_empty = memnew(StyleBoxEmpty);
+ tb_empty->set_default_margin(MARGIN_LEFT, 6 * scale);
+ tb_empty->set_default_margin(MARGIN_RIGHT, 6 * scale);
+ tb_empty->set_default_margin(MARGIN_TOP, 4 * scale);
+ tb_empty->set_default_margin(MARGIN_BOTTOM, 4 * scale);
- t->set_constant("hseparation","ToolButton", 3 );
+ t->set_stylebox("normal", "ToolButton", tb_empty);
+ t->set_stylebox("pressed", "ToolButton", make_stylebox(button_pressed_png, 4, 4, 4, 4));
+ t->set_stylebox("hover", "ToolButton", make_stylebox(button_normal_png, 4, 4, 4, 4));
+ t->set_stylebox("disabled", "ToolButton", make_empty_stylebox(4, 4, 4, 4));
+ t->set_stylebox("focus", "ToolButton", focus);
+ t->set_font("font", "ToolButton", default_font);
+ t->set_color("font_color", "ToolButton", control_font_color);
+ t->set_color("font_color_pressed", "ToolButton", control_font_color_pressed);
+ t->set_color("font_color_hover", "ToolButton", control_font_color_hover);
+ t->set_color("font_color_disabled", "ToolButton", Color(0.9, 0.95, 1, 0.3));
+ t->set_constant("hseparation", "ToolButton", 3);
// OptionButton
- Ref<StyleBox> sb_optbutton_normal = sb_expand( make_stylebox( option_button_normal_png,4,4,21,4,6,3,21,3),2,2,2,2);
- Ref<StyleBox> sb_optbutton_pressed = sb_expand( make_stylebox( option_button_pressed_png,4,4,21,4,6,3,21,3),2,2,2,2);
- Ref<StyleBox> sb_optbutton_hover = sb_expand( make_stylebox( option_button_hover_png,4,4,21,4,6,2,21,2),2,2,2,2);
- Ref<StyleBox> sb_optbutton_disabled = sb_expand( make_stylebox( option_button_disabled_png,4,4,21,4,6,2,21,2),2,2,2,2);
- Ref<StyleBox> sb_optbutton_focus = sb_expand( make_stylebox( button_focus_png,4,4,4,4,6,2,6,2),2,2,2,2);
+ Ref<StyleBox> sb_optbutton_normal = sb_expand(make_stylebox(option_button_normal_png, 4, 4, 21, 4, 6, 3, 21, 3), 2, 2, 2, 2);
+ Ref<StyleBox> sb_optbutton_pressed = sb_expand(make_stylebox(option_button_pressed_png, 4, 4, 21, 4, 6, 3, 21, 3), 2, 2, 2, 2);
+ Ref<StyleBox> sb_optbutton_hover = sb_expand(make_stylebox(option_button_hover_png, 4, 4, 21, 4, 6, 2, 21, 2), 2, 2, 2, 2);
+ Ref<StyleBox> sb_optbutton_disabled = sb_expand(make_stylebox(option_button_disabled_png, 4, 4, 21, 4, 6, 2, 21, 2), 2, 2, 2, 2);
+ Ref<StyleBox> sb_optbutton_focus = sb_expand(make_stylebox(button_focus_png, 4, 4, 4, 4, 6, 2, 6, 2), 2, 2, 2, 2);
- t->set_stylebox("normal","OptionButton", sb_optbutton_normal );
- t->set_stylebox("pressed","OptionButton", sb_optbutton_pressed );
- t->set_stylebox("hover","OptionButton", sb_optbutton_hover );
- t->set_stylebox("disabled","OptionButton", sb_optbutton_disabled );
- t->set_stylebox("focus","OptionButton", sb_button_focus );
+ t->set_stylebox("normal", "OptionButton", sb_optbutton_normal);
+ t->set_stylebox("pressed", "OptionButton", sb_optbutton_pressed);
+ t->set_stylebox("hover", "OptionButton", sb_optbutton_hover);
+ t->set_stylebox("disabled", "OptionButton", sb_optbutton_disabled);
+ t->set_stylebox("focus", "OptionButton", sb_button_focus);
- t->set_icon("arrow","OptionButton", make_icon( option_arrow_png ) );
+ t->set_icon("arrow", "OptionButton", make_icon(option_arrow_png));
- t->set_font("font","OptionButton", default_font );
-
- t->set_color("font_color","OptionButton", control_font_color );
- t->set_color("font_color_pressed","OptionButton", control_font_color_pressed );
- t->set_color("font_color_hover","OptionButton", control_font_color_hover );
- t->set_color("font_color_disabled","OptionButton", control_font_color_disabled );
-
- t->set_constant("hseparation","OptionButton", 2 *scale);
- t->set_constant("arrow_margin","OptionButton", 2 *scale);
+ t->set_font("font", "OptionButton", default_font);
+ t->set_color("font_color", "OptionButton", control_font_color);
+ t->set_color("font_color_pressed", "OptionButton", control_font_color_pressed);
+ t->set_color("font_color_hover", "OptionButton", control_font_color_hover);
+ t->set_color("font_color_disabled", "OptionButton", control_font_color_disabled);
+ t->set_constant("hseparation", "OptionButton", 2 * scale);
+ t->set_constant("arrow_margin", "OptionButton", 2 * scale);
// MenuButton
- t->set_stylebox("normal","MenuButton", sb_button_normal );
- t->set_stylebox("pressed","MenuButton", sb_button_pressed );
- t->set_stylebox("hover","MenuButton", sb_button_pressed );
- t->set_stylebox("disabled","MenuButton", make_empty_stylebox(0,0,0,0) );
- t->set_stylebox("focus","MenuButton", sb_button_focus );
+ t->set_stylebox("normal", "MenuButton", sb_button_normal);
+ t->set_stylebox("pressed", "MenuButton", sb_button_pressed);
+ t->set_stylebox("hover", "MenuButton", sb_button_pressed);
+ t->set_stylebox("disabled", "MenuButton", make_empty_stylebox(0, 0, 0, 0));
+ t->set_stylebox("focus", "MenuButton", sb_button_focus);
- t->set_font("font","MenuButton", default_font );
+ t->set_font("font", "MenuButton", default_font);
- t->set_color("font_color","MenuButton", control_font_color );
- t->set_color("font_color_pressed","MenuButton", control_font_color_pressed );
- t->set_color("font_color_hover","MenuButton", control_font_color_hover );
- t->set_color("font_color_disabled","MenuButton", Color(1,1,1,0.3) );
+ t->set_color("font_color", "MenuButton", control_font_color);
+ t->set_color("font_color_pressed", "MenuButton", control_font_color_pressed);
+ t->set_color("font_color_hover", "MenuButton", control_font_color_hover);
+ t->set_color("font_color_disabled", "MenuButton", Color(1, 1, 1, 0.3));
- t->set_constant("hseparation","MenuButton", 3 *scale);
+ t->set_constant("hseparation", "MenuButton", 3 * scale);
// ButtonGroup
- t->set_stylebox("panel","ButtonGroup", memnew( StyleBoxEmpty ));
+ t->set_stylebox("panel", "ButtonGroup", memnew(StyleBoxEmpty));
// CheckBox
- Ref<StyleBox> cbx_empty = memnew( StyleBoxEmpty );
- cbx_empty->set_default_margin(MARGIN_LEFT,22 *scale);
- cbx_empty->set_default_margin(MARGIN_RIGHT,4 *scale);
- cbx_empty->set_default_margin(MARGIN_TOP,4 *scale);
- cbx_empty->set_default_margin(MARGIN_BOTTOM,5 *scale);
+ Ref<StyleBox> cbx_empty = memnew(StyleBoxEmpty);
+ cbx_empty->set_default_margin(MARGIN_LEFT, 22 * scale);
+ cbx_empty->set_default_margin(MARGIN_RIGHT, 4 * scale);
+ cbx_empty->set_default_margin(MARGIN_TOP, 4 * scale);
+ cbx_empty->set_default_margin(MARGIN_BOTTOM, 5 * scale);
Ref<StyleBox> cbx_focus = focus;
- cbx_focus->set_default_margin(MARGIN_LEFT,4 *scale);
- cbx_focus->set_default_margin(MARGIN_RIGHT,22 *scale);
- cbx_focus->set_default_margin(MARGIN_TOP,4 *scale);
- cbx_focus->set_default_margin(MARGIN_BOTTOM,5 *scale);
+ cbx_focus->set_default_margin(MARGIN_LEFT, 4 * scale);
+ cbx_focus->set_default_margin(MARGIN_RIGHT, 22 * scale);
+ cbx_focus->set_default_margin(MARGIN_TOP, 4 * scale);
+ cbx_focus->set_default_margin(MARGIN_BOTTOM, 5 * scale);
- t->set_stylebox("normal","CheckBox", cbx_empty );
- t->set_stylebox("pressed","CheckBox", cbx_empty );
- t->set_stylebox("disabled","CheckBox", cbx_empty );
- t->set_stylebox("hover","CheckBox", cbx_empty );
- t->set_stylebox("focus","CheckBox", cbx_focus );
+ t->set_stylebox("normal", "CheckBox", cbx_empty);
+ t->set_stylebox("pressed", "CheckBox", cbx_empty);
+ t->set_stylebox("disabled", "CheckBox", cbx_empty);
+ t->set_stylebox("hover", "CheckBox", cbx_empty);
+ t->set_stylebox("focus", "CheckBox", cbx_focus);
t->set_icon("checked", "CheckBox", make_icon(checked_png));
t->set_icon("unchecked", "CheckBox", make_icon(unchecked_png));
t->set_icon("radio_checked", "CheckBox", make_icon(radio_checked_png));
t->set_icon("radio_unchecked", "CheckBox", make_icon(radio_unchecked_png));
- t->set_font("font","CheckBox", default_font );
-
- t->set_color("font_color","CheckBox", control_font_color );
- t->set_color("font_color_pressed","CheckBox", control_font_color_pressed );
- t->set_color("font_color_hover","CheckBox", control_font_color_hover );
- t->set_color("font_color_disabled","CheckBox", control_font_color_disabled );
-
- t->set_constant("hseparation","CheckBox",4 *scale);
- t->set_constant("check_vadjust","CheckBox",0 *scale);
+ t->set_font("font", "CheckBox", default_font);
+ t->set_color("font_color", "CheckBox", control_font_color);
+ t->set_color("font_color_pressed", "CheckBox", control_font_color_pressed);
+ t->set_color("font_color_hover", "CheckBox", control_font_color_hover);
+ t->set_color("font_color_disabled", "CheckBox", control_font_color_disabled);
+ t->set_constant("hseparation", "CheckBox", 4 * scale);
+ t->set_constant("check_vadjust", "CheckBox", 0 * scale);
// CheckButton
- Ref<StyleBox> cb_empty = memnew( StyleBoxEmpty );
- cb_empty->set_default_margin(MARGIN_LEFT,6 *scale);
- cb_empty->set_default_margin(MARGIN_RIGHT,70 *scale);
- cb_empty->set_default_margin(MARGIN_TOP,4 *scale);
- cb_empty->set_default_margin(MARGIN_BOTTOM,4 *scale);
-
- t->set_stylebox("normal","CheckButton", cb_empty );
- t->set_stylebox("pressed","CheckButton", cb_empty );
- t->set_stylebox("disabled","CheckButton", cb_empty );
- t->set_stylebox("hover","CheckButton", cb_empty );
- t->set_stylebox("focus","CheckButton", focus );
+ Ref<StyleBox> cb_empty = memnew(StyleBoxEmpty);
+ cb_empty->set_default_margin(MARGIN_LEFT, 6 * scale);
+ cb_empty->set_default_margin(MARGIN_RIGHT, 70 * scale);
+ cb_empty->set_default_margin(MARGIN_TOP, 4 * scale);
+ cb_empty->set_default_margin(MARGIN_BOTTOM, 4 * scale);
- t->set_icon("on","CheckButton", make_icon(toggle_on_png) );
- t->set_icon("off","CheckButton", make_icon(toggle_off_png));
+ t->set_stylebox("normal", "CheckButton", cb_empty);
+ t->set_stylebox("pressed", "CheckButton", cb_empty);
+ t->set_stylebox("disabled", "CheckButton", cb_empty);
+ t->set_stylebox("hover", "CheckButton", cb_empty);
+ t->set_stylebox("focus", "CheckButton", focus);
- t->set_font("font","CheckButton", default_font );
+ t->set_icon("on", "CheckButton", make_icon(toggle_on_png));
+ t->set_icon("off", "CheckButton", make_icon(toggle_off_png));
- t->set_color("font_color","CheckButton", control_font_color );
- t->set_color("font_color_pressed","CheckButton", control_font_color_pressed );
- t->set_color("font_color_hover","CheckButton", control_font_color_hover );
- t->set_color("font_color_disabled","CheckButton", control_font_color_disabled );
-
- t->set_constant("hseparation","CheckButton",4 *scale);
- t->set_constant("check_vadjust","CheckButton",0 *scale);
+ t->set_font("font", "CheckButton", default_font);
+ t->set_color("font_color", "CheckButton", control_font_color);
+ t->set_color("font_color_pressed", "CheckButton", control_font_color_pressed);
+ t->set_color("font_color_hover", "CheckButton", control_font_color_hover);
+ t->set_color("font_color_disabled", "CheckButton", control_font_color_disabled);
+ t->set_constant("hseparation", "CheckButton", 4 * scale);
+ t->set_constant("check_vadjust", "CheckButton", 0 * scale);
// Label
- t->set_font("font","Label", default_font );
-
- t->set_color("font_color","Label", Color(1,1,1) );
- t->set_color("font_color_shadow","Label", Color(0,0,0,0) );
-
- t->set_constant("shadow_offset_x","Label", 1 *scale);
- t->set_constant("shadow_offset_y","Label", 1 *scale);
- t->set_constant("shadow_as_outline","Label", 0 *scale);
- t->set_constant("line_spacing","Label", 3 *scale);
+ t->set_font("font", "Label", default_font);
+ t->set_color("font_color", "Label", Color(1, 1, 1));
+ t->set_color("font_color_shadow", "Label", Color(0, 0, 0, 0));
+ t->set_constant("shadow_offset_x", "Label", 1 * scale);
+ t->set_constant("shadow_offset_y", "Label", 1 * scale);
+ t->set_constant("shadow_as_outline", "Label", 0 * scale);
+ t->set_constant("line_spacing", "Label", 3 * scale);
// LineEdit
- t->set_stylebox("normal","LineEdit", make_stylebox( line_edit_png,5,5,5,5) );
- t->set_stylebox("focus","LineEdit", focus );
- t->set_stylebox("read_only","LineEdit", make_stylebox( line_edit_disabled_png,6,6,6,6) );
+ t->set_stylebox("normal", "LineEdit", make_stylebox(line_edit_png, 5, 5, 5, 5));
+ t->set_stylebox("focus", "LineEdit", focus);
+ t->set_stylebox("read_only", "LineEdit", make_stylebox(line_edit_disabled_png, 6, 6, 6, 6));
- t->set_font("font","LineEdit", default_font );
-
- t->set_color("font_color","LineEdit", control_font_color );
- t->set_color("font_color_selected","LineEdit", Color(0,0,0) );
- t->set_color("cursor_color","LineEdit", control_font_color_hover );
- t->set_color("selection_color","LineEdit", font_color_selection );
-
- t->set_constant("minimum_spaces","LineEdit", 12 *scale);
+ t->set_font("font", "LineEdit", default_font);
+ t->set_color("font_color", "LineEdit", control_font_color);
+ t->set_color("font_color_selected", "LineEdit", Color(0, 0, 0));
+ t->set_color("cursor_color", "LineEdit", control_font_color_hover);
+ t->set_color("selection_color", "LineEdit", font_color_selection);
+ t->set_constant("minimum_spaces", "LineEdit", 12 * scale);
// ProgressBar
- t->set_stylebox("bg","ProgressBar", make_stylebox( progress_bar_png,4,4,4,4,0,0,0,0) );
- t->set_stylebox("fg","ProgressBar", make_stylebox( progress_fill_png,6,6,6,6,2,1,2,1) );
-
- t->set_font("font","ProgressBar", default_font );
-
- t->set_color("font_color","ProgressBar", control_font_color_hover );
- t->set_color("font_color_shadow","ProgressBar", Color(0,0,0) );
+ t->set_stylebox("bg", "ProgressBar", make_stylebox(progress_bar_png, 4, 4, 4, 4, 0, 0, 0, 0));
+ t->set_stylebox("fg", "ProgressBar", make_stylebox(progress_fill_png, 6, 6, 6, 6, 2, 1, 2, 1));
+ t->set_font("font", "ProgressBar", default_font);
+ t->set_color("font_color", "ProgressBar", control_font_color_hover);
+ t->set_color("font_color_shadow", "ProgressBar", Color(0, 0, 0));
// TextEdit
- t->set_stylebox("normal","TextEdit", make_stylebox( tree_bg_png,3,3,3,3) );
- t->set_stylebox("focus","TextEdit", focus );
- t->set_stylebox("completion","TextEdit", make_stylebox( tree_bg_png,3,3,3,3) );
-
- t->set_icon("tab","TextEdit", make_icon( tab_png) );
-
- t->set_font("font","TextEdit", default_font );
-
- t->set_color("background_color", "TextEdit", Color(0,0,0,0));
- t->set_color("completion_background_color", "TextEdit",Color::html("2C2A32"));
- t->set_color("completion_selected_color", "TextEdit",Color::html("434244"));
- t->set_color("completion_existing_color", "TextEdit",Color::html("21dfdfdf"));
- t->set_color("completion_scroll_color","TextEdit", control_font_color_pressed );
- t->set_color("completion_font_color","TextEdit", Color::html("aaaaaa"));
- t->set_color("font_color","TextEdit", control_font_color );
- t->set_color("font_color_selected","TextEdit", Color(0,0,0) );
- t->set_color("selection_color","TextEdit", font_color_selection );
- t->set_color("mark_color","TextEdit", Color(1.0,0.4,0.4,0.4) );
- t->set_color("breakpoint_color","TextEdit", Color(0.8,0.8,0.4,0.2) );
- t->set_color("current_line_color","TextEdit", Color(0.25,0.25,0.26,0.8) );
- t->set_color("caret_color","TextEdit", control_font_color );
+ t->set_stylebox("normal", "TextEdit", make_stylebox(tree_bg_png, 3, 3, 3, 3));
+ t->set_stylebox("focus", "TextEdit", focus);
+ t->set_stylebox("completion", "TextEdit", make_stylebox(tree_bg_png, 3, 3, 3, 3));
+
+ t->set_icon("tab", "TextEdit", make_icon(tab_png));
+
+ t->set_font("font", "TextEdit", default_font);
+
+ t->set_color("background_color", "TextEdit", Color(0, 0, 0, 0));
+ t->set_color("completion_background_color", "TextEdit", Color::html("2C2A32"));
+ t->set_color("completion_selected_color", "TextEdit", Color::html("434244"));
+ t->set_color("completion_existing_color", "TextEdit", Color::html("21dfdfdf"));
+ t->set_color("completion_scroll_color", "TextEdit", control_font_color_pressed);
+ t->set_color("completion_font_color", "TextEdit", Color::html("aaaaaa"));
+ t->set_color("font_color", "TextEdit", control_font_color);
+ t->set_color("font_color_selected", "TextEdit", Color(0, 0, 0));
+ t->set_color("selection_color", "TextEdit", font_color_selection);
+ t->set_color("mark_color", "TextEdit", Color(1.0, 0.4, 0.4, 0.4));
+ t->set_color("breakpoint_color", "TextEdit", Color(0.8, 0.8, 0.4, 0.2));
+ t->set_color("current_line_color", "TextEdit", Color(0.25, 0.25, 0.26, 0.8));
+ t->set_color("caret_color", "TextEdit", control_font_color);
t->set_color("caret_background_color", "TextEdit", Color::html("000000"));
- t->set_color("symbol_color","TextEdit", control_font_color_hover );
- t->set_color("brace_mismatch_color","TextEdit", Color(1,0.2,0.2) );
- t->set_color("line_number_color","TextEdit",Color::html("66aaaaaa"));
- t->set_color("function_color","TextEdit",Color::html("66a2ce"));
- t->set_color("member_variable_color","TextEdit",Color::html("e64e59"));
- t->set_color("number_color","TextEdit",Color::html("EB9532"));
- t->set_color("word_highlighted_color","TextEdit",Color(0.8,0.9,0.9,0.15));
-
- t->set_constant("completion_lines","TextEdit", 7 );
- t->set_constant("completion_max_width","TextEdit", 50 );
- t->set_constant("completion_scroll_width","TextEdit", 3 );
- t->set_constant("line_spacing","TextEdit",4 *scale);
+ t->set_color("symbol_color", "TextEdit", control_font_color_hover);
+ t->set_color("brace_mismatch_color", "TextEdit", Color(1, 0.2, 0.2));
+ t->set_color("line_number_color", "TextEdit", Color::html("66aaaaaa"));
+ t->set_color("function_color", "TextEdit", Color::html("66a2ce"));
+ t->set_color("member_variable_color", "TextEdit", Color::html("e64e59"));
+ t->set_color("number_color", "TextEdit", Color::html("EB9532"));
+ t->set_color("word_highlighted_color", "TextEdit", Color(0.8, 0.9, 0.9, 0.15));
+ t->set_constant("completion_lines", "TextEdit", 7);
+ t->set_constant("completion_max_width", "TextEdit", 50);
+ t->set_constant("completion_scroll_width", "TextEdit", 3);
+ t->set_constant("line_spacing", "TextEdit", 4 * scale);
- Ref<Texture> empty_icon = memnew( ImageTexture );
+ Ref<Texture> empty_icon = memnew(ImageTexture);
// HScrollBar
- t->set_stylebox("scroll","HScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) );
- t->set_stylebox("scroll_focus","HScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) );
- t->set_stylebox("grabber","HScrollBar", make_stylebox( scroll_grabber_png,5,5,5,5,2,2,2,2) );
- t->set_stylebox("grabber_hilite","HScrollBar", make_stylebox( scroll_grabber_hl_png,5,5,5,5,2,2,2,2) );
-
- t->set_icon("increment","HScrollBar",empty_icon);
- t->set_icon("increment_hilite","HScrollBar",empty_icon);
- t->set_icon("decrement","HScrollBar",empty_icon);
- t->set_icon("decrement_hilite","HScrollBar",empty_icon);
-
+ t->set_stylebox("scroll", "HScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0));
+ t->set_stylebox("scroll_focus", "HScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0));
+ t->set_stylebox("grabber", "HScrollBar", make_stylebox(scroll_grabber_png, 5, 5, 5, 5, 2, 2, 2, 2));
+ t->set_stylebox("grabber_hilite", "HScrollBar", make_stylebox(scroll_grabber_hl_png, 5, 5, 5, 5, 2, 2, 2, 2));
+ t->set_icon("increment", "HScrollBar", empty_icon);
+ t->set_icon("increment_hilite", "HScrollBar", empty_icon);
+ t->set_icon("decrement", "HScrollBar", empty_icon);
+ t->set_icon("decrement_hilite", "HScrollBar", empty_icon);
// VScrollBar
- t->set_stylebox("scroll","VScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) );
- t->set_stylebox("scroll_focus","VScrollBar", make_stylebox( scroll_bg_png,5,5,5,5,0,0,0,0) );
- t->set_stylebox("grabber","VScrollBar", make_stylebox( scroll_grabber_png,5,5,5,5,2,2,2,2) );
- t->set_stylebox("grabber_hilite","VScrollBar", make_stylebox( scroll_grabber_hl_png,5,5,5,5,2,2,2,2) );
-
- t->set_icon("increment","VScrollBar",empty_icon);
- t->set_icon("increment_hilite","VScrollBar",empty_icon);
- t->set_icon("decrement","VScrollBar",empty_icon);
- t->set_icon("decrement_hilite","VScrollBar",empty_icon);
-
+ t->set_stylebox("scroll", "VScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0));
+ t->set_stylebox("scroll_focus", "VScrollBar", make_stylebox(scroll_bg_png, 5, 5, 5, 5, 0, 0, 0, 0));
+ t->set_stylebox("grabber", "VScrollBar", make_stylebox(scroll_grabber_png, 5, 5, 5, 5, 2, 2, 2, 2));
+ t->set_stylebox("grabber_hilite", "VScrollBar", make_stylebox(scroll_grabber_hl_png, 5, 5, 5, 5, 2, 2, 2, 2));
+ t->set_icon("increment", "VScrollBar", empty_icon);
+ t->set_icon("increment_hilite", "VScrollBar", empty_icon);
+ t->set_icon("decrement", "VScrollBar", empty_icon);
+ t->set_icon("decrement_hilite", "VScrollBar", empty_icon);
// HSlider
- t->set_stylebox("slider","HSlider", make_stylebox( hslider_bg_png,4,4,4,4) );
- t->set_stylebox("grabber_hilite","HSlider", make_stylebox( hslider_grabber_hl_png,6,6,6,6) );
- t->set_stylebox("focus","HSlider", focus );
-
- t->set_icon("grabber","HSlider", make_icon( hslider_grabber_png ) );
- t->set_icon("grabber_hilite","HSlider", make_icon( hslider_grabber_hl_png ) );
- t->set_icon("tick","HSlider", make_icon( hslider_tick_png ) );
-
-
+ t->set_stylebox("slider", "HSlider", make_stylebox(hslider_bg_png, 4, 4, 4, 4));
+ t->set_stylebox("grabber_hilite", "HSlider", make_stylebox(hslider_grabber_hl_png, 6, 6, 6, 6));
+ t->set_stylebox("focus", "HSlider", focus);
+ t->set_icon("grabber", "HSlider", make_icon(hslider_grabber_png));
+ t->set_icon("grabber_hilite", "HSlider", make_icon(hslider_grabber_hl_png));
+ t->set_icon("tick", "HSlider", make_icon(hslider_tick_png));
// VSlider
- t->set_stylebox("slider","VSlider", make_stylebox( vslider_bg_png,4,4,4,4) );
- t->set_stylebox("grabber_hilite","VSlider", make_stylebox( vslider_grabber_hl_png,6,6,6,6) );
- t->set_stylebox("focus","HSlider", focus );
-
- t->set_icon("grabber","VSlider", make_icon( vslider_grabber_png) );
- t->set_icon("grabber_hilite","VSlider", make_icon( vslider_grabber_hl_png ) );
- t->set_icon("tick","VSlider", make_icon( vslider_tick_png ) );
-
+ t->set_stylebox("slider", "VSlider", make_stylebox(vslider_bg_png, 4, 4, 4, 4));
+ t->set_stylebox("grabber_hilite", "VSlider", make_stylebox(vslider_grabber_hl_png, 6, 6, 6, 6));
+ t->set_stylebox("focus", "HSlider", focus);
+ t->set_icon("grabber", "VSlider", make_icon(vslider_grabber_png));
+ t->set_icon("grabber_hilite", "VSlider", make_icon(vslider_grabber_hl_png));
+ t->set_icon("tick", "VSlider", make_icon(vslider_tick_png));
// SpinBox
- t->set_icon("updown","SpinBox",make_icon(spinbox_updown_png));
-
-
+ t->set_icon("updown", "SpinBox", make_icon(spinbox_updown_png));
// WindowDialog
@@ -597,381 +551,349 @@ void fill_default_theme(Ref<Theme>& t, const Ref<Font> & default_font, const Ref
t->set_constant("close_h_ofs", "WindowDialog", 18 * scale);
t->set_constant("close_v_ofs", "WindowDialog", 18 * scale);
-
// File Dialog
- t->set_icon("reload","FileDialog",make_icon( icon_reload_png ));
-
+ t->set_icon("reload", "FileDialog", make_icon(icon_reload_png));
// Popup
- Ref<StyleBoxTexture> style_pp = sb_expand( make_stylebox( popup_bg_png,5,5,5,5,4,4,4,4),2,2,2,2);
+ Ref<StyleBoxTexture> style_pp = sb_expand(make_stylebox(popup_bg_png, 5, 5, 5, 5, 4, 4, 4, 4), 2, 2, 2, 2);
- Ref<StyleBoxTexture> selected = make_stylebox( selection_png,6,6,6,6);
- for(int i=0;i<4;i++) {
- selected->set_expand_margin_size(Margin(i),2 *scale);
+ Ref<StyleBoxTexture> selected = make_stylebox(selection_png, 6, 6, 6, 6);
+ for (int i = 0; i < 4; i++) {
+ selected->set_expand_margin_size(Margin(i), 2 * scale);
}
- t->set_stylebox("panel","PopupPanel", style_pp );
-
-
-
+ t->set_stylebox("panel", "PopupPanel", style_pp);
// PopupMenu
- t->set_stylebox("panel","PopupMenu", make_stylebox( popup_bg_png,4,4,4,4,10,10,10,10) );
- t->set_stylebox("panel_disabled","PopupMenu", make_stylebox( popup_bg_disabled_png,4,4,4,4) );
- t->set_stylebox("hover","PopupMenu", selected );
- t->set_stylebox("separator","PopupMenu", make_stylebox( vseparator_png,3,3,3,3) );
-
- t->set_icon("checked","PopupMenu", make_icon(checked_png) );
- t->set_icon("unchecked","PopupMenu", make_icon(unchecked_png) );
- t->set_icon("submenu","PopupMenu", make_icon(submenu_png) );
+ t->set_stylebox("panel", "PopupMenu", make_stylebox(popup_bg_png, 4, 4, 4, 4, 10, 10, 10, 10));
+ t->set_stylebox("panel_disabled", "PopupMenu", make_stylebox(popup_bg_disabled_png, 4, 4, 4, 4));
+ t->set_stylebox("hover", "PopupMenu", selected);
+ t->set_stylebox("separator", "PopupMenu", make_stylebox(vseparator_png, 3, 3, 3, 3));
- t->set_font("font","PopupMenu", default_font );
+ t->set_icon("checked", "PopupMenu", make_icon(checked_png));
+ t->set_icon("unchecked", "PopupMenu", make_icon(unchecked_png));
+ t->set_icon("submenu", "PopupMenu", make_icon(submenu_png));
- t->set_color("font_color","PopupMenu", control_font_color );
- t->set_color("font_color_accel","PopupMenu", Color(0.7,0.7,0.7,0.8) );
- t->set_color("font_color_disabled","PopupMenu", Color(0.4,0.4,0.4,0.8) );
- t->set_color("font_color_hover","PopupMenu", control_font_color );
+ t->set_font("font", "PopupMenu", default_font);
- t->set_constant("hseparation","PopupMenu",4 *scale);
- t->set_constant("vseparation","PopupMenu",4 *scale);
+ t->set_color("font_color", "PopupMenu", control_font_color);
+ t->set_color("font_color_accel", "PopupMenu", Color(0.7, 0.7, 0.7, 0.8));
+ t->set_color("font_color_disabled", "PopupMenu", Color(0.4, 0.4, 0.4, 0.8));
+ t->set_color("font_color_hover", "PopupMenu", control_font_color);
+ t->set_constant("hseparation", "PopupMenu", 4 * scale);
+ t->set_constant("vseparation", "PopupMenu", 4 * scale);
// GraphNode
- Ref<StyleBoxTexture> graphsb = make_stylebox(graph_node_png,6,24,6,5,16,24,16,5);
- Ref<StyleBoxTexture> graphsbcomment = make_stylebox(graph_node_comment_png,6,24,6,5,16,24,16,5);
- Ref<StyleBoxTexture> graphsbcommentselected = make_stylebox(graph_node_comment_focus_png,6,24,6,5,16,24,16,5);
- Ref<StyleBoxTexture> graphsbselected = make_stylebox(graph_node_selected_png,6,24,6,5,16,24,16,5);
- Ref<StyleBoxTexture> graphsbdefault = make_stylebox(graph_node_default_png,4,4,4,4,6,4,4,4);
- Ref<StyleBoxTexture> graphsbdeffocus = make_stylebox(graph_node_default_focus_png,4,4,4,4,6,4,4,4);
- Ref<StyleBoxTexture> graph_bpoint = make_stylebox(graph_node_breakpoint_png,6,24,6,5,16,24,16,5);
- Ref<StyleBoxTexture> graph_position = make_stylebox(graph_node_position_png,6,24,6,5,16,24,16,5);
+ Ref<StyleBoxTexture> graphsb = make_stylebox(graph_node_png, 6, 24, 6, 5, 16, 24, 16, 5);
+ Ref<StyleBoxTexture> graphsbcomment = make_stylebox(graph_node_comment_png, 6, 24, 6, 5, 16, 24, 16, 5);
+ Ref<StyleBoxTexture> graphsbcommentselected = make_stylebox(graph_node_comment_focus_png, 6, 24, 6, 5, 16, 24, 16, 5);
+ Ref<StyleBoxTexture> graphsbselected = make_stylebox(graph_node_selected_png, 6, 24, 6, 5, 16, 24, 16, 5);
+ Ref<StyleBoxTexture> graphsbdefault = make_stylebox(graph_node_default_png, 4, 4, 4, 4, 6, 4, 4, 4);
+ Ref<StyleBoxTexture> graphsbdeffocus = make_stylebox(graph_node_default_focus_png, 4, 4, 4, 4, 6, 4, 4, 4);
+ Ref<StyleBoxTexture> graph_bpoint = make_stylebox(graph_node_breakpoint_png, 6, 24, 6, 5, 16, 24, 16, 5);
+ Ref<StyleBoxTexture> graph_position = make_stylebox(graph_node_position_png, 6, 24, 6, 5, 16, 24, 16, 5);
//graphsb->set_expand_margin_size(MARGIN_LEFT,10);
//graphsb->set_expand_margin_size(MARGIN_RIGHT,10);
- t->set_stylebox("frame","GraphNode", graphsb );
- t->set_stylebox("selectedframe","GraphNode", graphsbselected );
- t->set_stylebox("defaultframe", "GraphNode", graphsbdefault );
- t->set_stylebox("defaultfocus", "GraphNode", graphsbdeffocus );
- t->set_stylebox("comment", "GraphNode", graphsbcomment );
- t->set_stylebox("commentfocus", "GraphNode", graphsbcommentselected );
- t->set_stylebox("breakpoint", "GraphNode", graph_bpoint );
- t->set_stylebox("position", "GraphNode", graph_position );
- t->set_constant("separation","GraphNode", 1 *scale);
- t->set_icon("port","GraphNode", make_icon( graph_port_png ) );
- t->set_icon("close","GraphNode", make_icon( graph_node_close_png ) );
- t->set_icon("resizer","GraphNode", make_icon( window_resizer_png ) );
- t->set_font("title_font","GraphNode", default_font );
- t->set_color("title_color","GraphNode", Color(0,0,0,1));
- t->set_constant("title_offset","GraphNode", 20 *scale);
- t->set_constant("close_offset","GraphNode", 18 *scale);
- t->set_constant("port_offset","GraphNode", 3 *scale);
-
+ t->set_stylebox("frame", "GraphNode", graphsb);
+ t->set_stylebox("selectedframe", "GraphNode", graphsbselected);
+ t->set_stylebox("defaultframe", "GraphNode", graphsbdefault);
+ t->set_stylebox("defaultfocus", "GraphNode", graphsbdeffocus);
+ t->set_stylebox("comment", "GraphNode", graphsbcomment);
+ t->set_stylebox("commentfocus", "GraphNode", graphsbcommentselected);
+ t->set_stylebox("breakpoint", "GraphNode", graph_bpoint);
+ t->set_stylebox("position", "GraphNode", graph_position);
+ t->set_constant("separation", "GraphNode", 1 * scale);
+ t->set_icon("port", "GraphNode", make_icon(graph_port_png));
+ t->set_icon("close", "GraphNode", make_icon(graph_node_close_png));
+ t->set_icon("resizer", "GraphNode", make_icon(window_resizer_png));
+ t->set_font("title_font", "GraphNode", default_font);
+ t->set_color("title_color", "GraphNode", Color(0, 0, 0, 1));
+ t->set_constant("title_offset", "GraphNode", 20 * scale);
+ t->set_constant("close_offset", "GraphNode", 18 * scale);
+ t->set_constant("port_offset", "GraphNode", 3 * scale);
// Tree
- Ref<StyleBoxTexture> tree_selected = make_stylebox( selection_png,4,4,4,4,8,0,8,0);
- Ref<StyleBoxTexture> tree_selected_oof = make_stylebox( selection_oof_png,4,4,4,4,8,0,8,0);
-
- t->set_stylebox("bg","Tree", make_stylebox( tree_bg_png,4,4,4,5) );
- t->set_stylebox("bg_focus","Tree", focus );
- t->set_stylebox("selected","Tree", tree_selected_oof );
- t->set_stylebox("selected_focus","Tree", tree_selected );
- t->set_stylebox("cursor","Tree", focus );
- t->set_stylebox("cursor_unfocused","Tree", focus );
- t->set_stylebox("button_pressed","Tree",make_stylebox( button_pressed_png,4,4,4,4));
- t->set_stylebox("title_button_normal","Tree", make_stylebox( tree_title_png,4,4,4,4) );
- t->set_stylebox("title_button_pressed","Tree", make_stylebox( tree_title_pressed_png,4,4,4,4) );
- t->set_stylebox("title_button_hover","Tree", make_stylebox( tree_title_png,4,4,4,4) );
-
- t->set_icon("checked","Tree",make_icon(checked_png));
- t->set_icon("unchecked","Tree",make_icon(unchecked_png));
- t->set_icon("updown","Tree",make_icon(updown_png));
- t->set_icon("select_arrow","Tree",make_icon(dropdown_png));
- t->set_icon("arrow","Tree",make_icon(arrow_down_png));
- t->set_icon("arrow_collapsed","Tree",make_icon(arrow_right_png));
-
- t->set_font("title_button_font","Tree", default_font );
- t->set_font("font","Tree", default_font );
-
- t->set_color("title_button_color","Tree", control_font_color );
- t->set_color("font_color","Tree", control_font_color_low );
- t->set_color("font_color_selected","Tree", control_font_color_pressed );
- t->set_color("selection_color","Tree", Color(0.1,0.1,1,0.8) );
- t->set_color("cursor_color","Tree", Color(0,0,0) );
- t->set_color("guide_color","Tree", Color(0,0,0,0.1) );
- t->set_color("drop_position_color","Tree", Color(1,0.3,0.2) );
- t->set_color("relationship_line_color", "Tree", Color::html("464646") );
-
- t->set_constant("hseparation","Tree",4 *scale);
- t->set_constant("vseparation","Tree",4 *scale);
- t->set_constant("guide_width","Tree",2 *scale);
- t->set_constant("item_margin","Tree",12 *scale);
- t->set_constant("button_margin","Tree",4 *scale);
+ Ref<StyleBoxTexture> tree_selected = make_stylebox(selection_png, 4, 4, 4, 4, 8, 0, 8, 0);
+ Ref<StyleBoxTexture> tree_selected_oof = make_stylebox(selection_oof_png, 4, 4, 4, 4, 8, 0, 8, 0);
+
+ t->set_stylebox("bg", "Tree", make_stylebox(tree_bg_png, 4, 4, 4, 5));
+ t->set_stylebox("bg_focus", "Tree", focus);
+ t->set_stylebox("selected", "Tree", tree_selected_oof);
+ t->set_stylebox("selected_focus", "Tree", tree_selected);
+ t->set_stylebox("cursor", "Tree", focus);
+ t->set_stylebox("cursor_unfocused", "Tree", focus);
+ t->set_stylebox("button_pressed", "Tree", make_stylebox(button_pressed_png, 4, 4, 4, 4));
+ t->set_stylebox("title_button_normal", "Tree", make_stylebox(tree_title_png, 4, 4, 4, 4));
+ t->set_stylebox("title_button_pressed", "Tree", make_stylebox(tree_title_pressed_png, 4, 4, 4, 4));
+ t->set_stylebox("title_button_hover", "Tree", make_stylebox(tree_title_png, 4, 4, 4, 4));
+
+ t->set_icon("checked", "Tree", make_icon(checked_png));
+ t->set_icon("unchecked", "Tree", make_icon(unchecked_png));
+ t->set_icon("updown", "Tree", make_icon(updown_png));
+ t->set_icon("select_arrow", "Tree", make_icon(dropdown_png));
+ t->set_icon("arrow", "Tree", make_icon(arrow_down_png));
+ t->set_icon("arrow_collapsed", "Tree", make_icon(arrow_right_png));
+
+ t->set_font("title_button_font", "Tree", default_font);
+ t->set_font("font", "Tree", default_font);
+
+ t->set_color("title_button_color", "Tree", control_font_color);
+ t->set_color("font_color", "Tree", control_font_color_low);
+ t->set_color("font_color_selected", "Tree", control_font_color_pressed);
+ t->set_color("selection_color", "Tree", Color(0.1, 0.1, 1, 0.8));
+ t->set_color("cursor_color", "Tree", Color(0, 0, 0));
+ t->set_color("guide_color", "Tree", Color(0, 0, 0, 0.1));
+ t->set_color("drop_position_color", "Tree", Color(1, 0.3, 0.2));
+ t->set_color("relationship_line_color", "Tree", Color::html("464646"));
+
+ t->set_constant("hseparation", "Tree", 4 * scale);
+ t->set_constant("vseparation", "Tree", 4 * scale);
+ t->set_constant("guide_width", "Tree", 2 * scale);
+ t->set_constant("item_margin", "Tree", 12 * scale);
+ t->set_constant("button_margin", "Tree", 4 * scale);
t->set_constant("draw_relationship_lines", "Tree", 0);
t->set_constant("scroll_border", "Tree", 4);
t->set_constant("scroll_speed", "Tree", 12);
-
// ItemList
- Ref<StyleBoxTexture> item_selected = make_stylebox( selection_png,4,4,4,4,8,2,8,2);
- Ref<StyleBoxTexture> item_selected_oof = make_stylebox( selection_oof_png,4,4,4,4,8,2,8,2);
-
- t->set_stylebox("bg","ItemList", make_stylebox( tree_bg_png,4,4,4,5) );
- t->set_stylebox("bg_focus","ItemList", focus );
- t->set_constant("hseparation","ItemList",4);
- t->set_constant("vseparation","ItemList",2);
- t->set_constant("icon_margin","ItemList",4);
- t->set_constant("line_separation","ItemList",2 *scale);
- t->set_font("font","ItemList", default_font );
- t->set_color("font_color","ItemList", control_font_color_lower );
- t->set_color("font_color_selected","ItemList", control_font_color_pressed );
- t->set_color("guide_color","ItemList", Color(0,0,0,0.1) );
- t->set_stylebox("selected","ItemList", item_selected_oof );
- t->set_stylebox("selected_focus","ItemList", item_selected );
- t->set_stylebox("cursor","ItemList", focus );
- t->set_stylebox("cursor_unfocused","ItemList", focus );
-
+ Ref<StyleBoxTexture> item_selected = make_stylebox(selection_png, 4, 4, 4, 4, 8, 2, 8, 2);
+ Ref<StyleBoxTexture> item_selected_oof = make_stylebox(selection_oof_png, 4, 4, 4, 4, 8, 2, 8, 2);
+
+ t->set_stylebox("bg", "ItemList", make_stylebox(tree_bg_png, 4, 4, 4, 5));
+ t->set_stylebox("bg_focus", "ItemList", focus);
+ t->set_constant("hseparation", "ItemList", 4);
+ t->set_constant("vseparation", "ItemList", 2);
+ t->set_constant("icon_margin", "ItemList", 4);
+ t->set_constant("line_separation", "ItemList", 2 * scale);
+ t->set_font("font", "ItemList", default_font);
+ t->set_color("font_color", "ItemList", control_font_color_lower);
+ t->set_color("font_color_selected", "ItemList", control_font_color_pressed);
+ t->set_color("guide_color", "ItemList", Color(0, 0, 0, 0.1));
+ t->set_stylebox("selected", "ItemList", item_selected_oof);
+ t->set_stylebox("selected_focus", "ItemList", item_selected);
+ t->set_stylebox("cursor", "ItemList", focus);
+ t->set_stylebox("cursor_unfocused", "ItemList", focus);
// TabContainer
- Ref<StyleBoxTexture> tc_sb = sb_expand( make_stylebox( tab_container_bg_png,4,4,4,4,4,4,4,4),3,3,3,3);
+ Ref<StyleBoxTexture> tc_sb = sb_expand(make_stylebox(tab_container_bg_png, 4, 4, 4, 4, 4, 4, 4, 4), 3, 3, 3, 3);
- tc_sb->set_expand_margin_size(MARGIN_TOP,2 *scale);
- tc_sb->set_default_margin(MARGIN_TOP,8 *scale);
+ tc_sb->set_expand_margin_size(MARGIN_TOP, 2 * scale);
+ tc_sb->set_default_margin(MARGIN_TOP, 8 * scale);
- t->set_stylebox("tab_fg","TabContainer", sb_expand( make_stylebox( tab_current_png,4,4,4,1,16,4,16,4),2,2,2,2) );
- t->set_stylebox("tab_bg","TabContainer", sb_expand( make_stylebox( tab_behind_png,5,5,5,1,16,6,16,4),3,0,3,3) );
+ t->set_stylebox("tab_fg", "TabContainer", sb_expand(make_stylebox(tab_current_png, 4, 4, 4, 1, 16, 4, 16, 4), 2, 2, 2, 2));
+ t->set_stylebox("tab_bg", "TabContainer", sb_expand(make_stylebox(tab_behind_png, 5, 5, 5, 1, 16, 6, 16, 4), 3, 0, 3, 3));
t->set_stylebox("tab_disabled", "TabContainer", sb_expand(make_stylebox(tab_disabled_png, 5, 5, 5, 1, 16, 6, 16, 4), 3, 0, 3, 3));
- t->set_stylebox("panel","TabContainer", tc_sb );
+ t->set_stylebox("panel", "TabContainer", tc_sb);
- t->set_icon("increment","TabContainer",make_icon( scroll_button_right_png));
- t->set_icon("increment_hilite","TabContainer",make_icon( scroll_button_right_hl_png));
- t->set_icon("decrement","TabContainer",make_icon( scroll_button_left_png));
- t->set_icon("decrement_hilite","TabContainer",make_icon( scroll_button_left_hl_png));
- t->set_icon("menu","TabContainer",make_icon( tab_menu_png));
- t->set_icon("menu_hilite","TabContainer",make_icon( tab_menu_hl_png));
+ t->set_icon("increment", "TabContainer", make_icon(scroll_button_right_png));
+ t->set_icon("increment_hilite", "TabContainer", make_icon(scroll_button_right_hl_png));
+ t->set_icon("decrement", "TabContainer", make_icon(scroll_button_left_png));
+ t->set_icon("decrement_hilite", "TabContainer", make_icon(scroll_button_left_hl_png));
+ t->set_icon("menu", "TabContainer", make_icon(tab_menu_png));
+ t->set_icon("menu_hilite", "TabContainer", make_icon(tab_menu_hl_png));
- t->set_font("font","TabContainer", default_font );
+ t->set_font("font", "TabContainer", default_font);
- t->set_color("font_color_fg","TabContainer", control_font_color_hover );
- t->set_color("font_color_bg","TabContainer", control_font_color_low );
+ t->set_color("font_color_fg", "TabContainer", control_font_color_hover);
+ t->set_color("font_color_bg", "TabContainer", control_font_color_low);
t->set_color("font_color_disabled", "TabContainer", control_font_color_disabled);
- t->set_constant("side_margin","TabContainer", 8 *scale);
- t->set_constant("top_margin","TabContainer", 24 *scale);
- t->set_constant("label_valign_fg","TabContainer", 0 *scale);
- t->set_constant("label_valign_bg","TabContainer", 2 *scale);
- t->set_constant("hseparation","TabContainer", 4 *scale);
-
-
+ t->set_constant("side_margin", "TabContainer", 8 * scale);
+ t->set_constant("top_margin", "TabContainer", 24 * scale);
+ t->set_constant("label_valign_fg", "TabContainer", 0 * scale);
+ t->set_constant("label_valign_bg", "TabContainer", 2 * scale);
+ t->set_constant("hseparation", "TabContainer", 4 * scale);
// Tabs
- t->set_stylebox("tab_fg","Tabs", sb_expand( make_stylebox( tab_current_png,4,3,4,1,16,3,16,2),2,2,2,2) );
- t->set_stylebox("tab_bg","Tabs", sb_expand( make_stylebox( tab_behind_png,5,4,5,1,16,5,16,2),3,3,3,3) );
+ t->set_stylebox("tab_fg", "Tabs", sb_expand(make_stylebox(tab_current_png, 4, 3, 4, 1, 16, 3, 16, 2), 2, 2, 2, 2));
+ t->set_stylebox("tab_bg", "Tabs", sb_expand(make_stylebox(tab_behind_png, 5, 4, 5, 1, 16, 5, 16, 2), 3, 3, 3, 3));
t->set_stylebox("tab_disabled", "Tabs", sb_expand(make_stylebox(tab_disabled_png, 5, 4, 5, 1, 16, 5, 16, 2), 3, 3, 3, 3));
- t->set_stylebox("panel","Tabs",tc_sb );
- t->set_stylebox("button_pressed","Tabs", make_stylebox( button_pressed_png,4,4,4,4) );
- t->set_stylebox("button","Tabs", make_stylebox( button_normal_png,4,4,4,4) );
+ t->set_stylebox("panel", "Tabs", tc_sb);
+ t->set_stylebox("button_pressed", "Tabs", make_stylebox(button_pressed_png, 4, 4, 4, 4));
+ t->set_stylebox("button", "Tabs", make_stylebox(button_normal_png, 4, 4, 4, 4));
- t->set_icon("increment","Tabs",make_icon( scroll_button_right_png));
- t->set_icon("increment_hilite","Tabs",make_icon( scroll_button_right_hl_png));
- t->set_icon("decrement","Tabs",make_icon( scroll_button_left_png));
- t->set_icon("decrement_hilite","Tabs",make_icon( scroll_button_left_hl_png));
- t->set_icon("close","Tabs",make_icon( tab_close_png));
+ t->set_icon("increment", "Tabs", make_icon(scroll_button_right_png));
+ t->set_icon("increment_hilite", "Tabs", make_icon(scroll_button_right_hl_png));
+ t->set_icon("decrement", "Tabs", make_icon(scroll_button_left_png));
+ t->set_icon("decrement_hilite", "Tabs", make_icon(scroll_button_left_hl_png));
+ t->set_icon("close", "Tabs", make_icon(tab_close_png));
- t->set_font("font","Tabs", default_font );
+ t->set_font("font", "Tabs", default_font);
- t->set_color("font_color_fg","Tabs", control_font_color_hover );
- t->set_color("font_color_bg","Tabs", control_font_color_low );
+ t->set_color("font_color_fg", "Tabs", control_font_color_hover);
+ t->set_color("font_color_bg", "Tabs", control_font_color_low);
t->set_color("font_color_disabled", "Tabs", control_font_color_disabled);
- t->set_constant("top_margin","Tabs", 24 *scale);
- t->set_constant("label_valign_fg","Tabs", 0 *scale);
- t->set_constant("label_valign_bg","Tabs", 2 *scale);
- t->set_constant("hseparation","Tabs", 4 *scale);
-
-
+ t->set_constant("top_margin", "Tabs", 24 * scale);
+ t->set_constant("label_valign_fg", "Tabs", 0 * scale);
+ t->set_constant("label_valign_bg", "Tabs", 2 * scale);
+ t->set_constant("hseparation", "Tabs", 4 * scale);
// Separators
- t->set_stylebox("separator","HSeparator", make_stylebox( vseparator_png,3,3,3,3) );
- t->set_stylebox("separator","VSeparator", make_stylebox( hseparator_png,3,3,3,3) );
-
- t->set_icon("close","Icons", make_icon(icon_close_png));
- t->set_font("normal","Fonts", default_font );
- t->set_font("large","Fonts", large_font );
+ t->set_stylebox("separator", "HSeparator", make_stylebox(vseparator_png, 3, 3, 3, 3));
+ t->set_stylebox("separator", "VSeparator", make_stylebox(hseparator_png, 3, 3, 3, 3));
- t->set_constant("separation","HSeparator", 4 *scale);
- t->set_constant("separation","VSeparator", 4 *scale);
+ t->set_icon("close", "Icons", make_icon(icon_close_png));
+ t->set_font("normal", "Fonts", default_font);
+ t->set_font("large", "Fonts", large_font);
+ t->set_constant("separation", "HSeparator", 4 * scale);
+ t->set_constant("separation", "VSeparator", 4 * scale);
// Dialogs
- t->set_constant("margin","Dialogs",8 *scale);
- t->set_constant("button_margin","Dialogs",32 *scale);
-
-
+ t->set_constant("margin", "Dialogs", 8 * scale);
+ t->set_constant("button_margin", "Dialogs", 32 * scale);
// FileDialog
- t->set_icon("folder","FileDialog",make_icon(icon_folder_png));
- t->set_color("files_disabled","FileDialog",Color(0,0,0,0.7));
-
-
+ t->set_icon("folder", "FileDialog", make_icon(icon_folder_png));
+ t->set_color("files_disabled", "FileDialog", Color(0, 0, 0, 0.7));
// colorPicker
- t->set_constant("value_height","ColorPicker", 23 *scale);
- t->set_constant("value_width","ColorPicker", 50 *scale);
- t->set_constant("color_width","ColorPicker", 100 *scale);
- t->set_constant("label_width","ColorPicker", 20 *scale);
- t->set_constant("hseparator","ColorPicker", 4 *scale);
+ t->set_constant("value_height", "ColorPicker", 23 * scale);
+ t->set_constant("value_width", "ColorPicker", 50 * scale);
+ t->set_constant("color_width", "ColorPicker", 100 * scale);
+ t->set_constant("label_width", "ColorPicker", 20 * scale);
+ t->set_constant("hseparator", "ColorPicker", 4 * scale);
- t->set_icon("screen_picker","ColorPicker", make_icon( icon_color_pick_png ) );
- t->set_icon("add_preset","ColorPicker", make_icon( icon_add_png ) );
- t->set_icon("color_hue", "ColorPicker", make_icon( color_picker_hue_png));
- t->set_icon("color_sample", "ColorPicker", make_icon( color_picker_sample_png));
+ t->set_icon("screen_picker", "ColorPicker", make_icon(icon_color_pick_png));
+ t->set_icon("add_preset", "ColorPicker", make_icon(icon_add_png));
+ t->set_icon("color_hue", "ColorPicker", make_icon(color_picker_hue_png));
+ t->set_icon("color_sample", "ColorPicker", make_icon(color_picker_sample_png));
// TooltipPanel
- Ref<StyleBoxTexture> style_tt = make_stylebox( tooltip_bg_png,4,4,4,4);
- for(int i=0;i<4;i++)
- style_tt->set_expand_margin_size((Margin)i,4 *scale);
-
- t->set_stylebox("panel","TooltipPanel", style_tt );
-
- t->set_font("font","TooltipLabel", default_font );
+ Ref<StyleBoxTexture> style_tt = make_stylebox(tooltip_bg_png, 4, 4, 4, 4);
+ for (int i = 0; i < 4; i++)
+ style_tt->set_expand_margin_size((Margin)i, 4 * scale);
- t->set_color("font_color","TooltipLabel", Color(0,0,0) );
- t->set_color("font_color_shadow","TooltipLabel", Color(0,0,0,0.1) );
+ t->set_stylebox("panel", "TooltipPanel", style_tt);
- t->set_constant("shadow_offset_x","TooltipLabel", 1 );
- t->set_constant("shadow_offset_y","TooltipLabel", 1 );
+ t->set_font("font", "TooltipLabel", default_font);
+ t->set_color("font_color", "TooltipLabel", Color(0, 0, 0));
+ t->set_color("font_color_shadow", "TooltipLabel", Color(0, 0, 0, 0.1));
+ t->set_constant("shadow_offset_x", "TooltipLabel", 1);
+ t->set_constant("shadow_offset_y", "TooltipLabel", 1);
// RichTextLabel
- t->set_stylebox("focus","RichTextLabel", focus );
+ t->set_stylebox("focus", "RichTextLabel", focus);
- t->set_font("normal_font","RichTextLabel", default_font );
- t->set_font("bold_font","RichTextLabel", default_font );
- t->set_font("italics_font","RichTextLabel", default_font );
- t->set_font("bold_italics_font","RichTextLabel", default_font );
- t->set_font("mono_font","RichTextLabel", default_font );
-
- t->set_color("default_color","RichTextLabel", control_font_color );
- t->set_color("font_color_selected","RichTextLabel", font_color_selection );
- t->set_color("selection_color","RichTextLabel", Color(0.1,0.1,1,0.8) );
-
- t->set_constant("line_separation","RichTextLabel", 1 *scale);
- t->set_constant("table_hseparation","RichTextLabel", 3 *scale);
- t->set_constant("table_vseparation","RichTextLabel", 3 *scale);
+ t->set_font("normal_font", "RichTextLabel", default_font);
+ t->set_font("bold_font", "RichTextLabel", default_font);
+ t->set_font("italics_font", "RichTextLabel", default_font);
+ t->set_font("bold_italics_font", "RichTextLabel", default_font);
+ t->set_font("mono_font", "RichTextLabel", default_font);
+ t->set_color("default_color", "RichTextLabel", control_font_color);
+ t->set_color("font_color_selected", "RichTextLabel", font_color_selection);
+ t->set_color("selection_color", "RichTextLabel", Color(0.1, 0.1, 1, 0.8));
+ t->set_constant("line_separation", "RichTextLabel", 1 * scale);
+ t->set_constant("table_hseparation", "RichTextLabel", 3 * scale);
+ t->set_constant("table_vseparation", "RichTextLabel", 3 * scale);
// Containers
- t->set_stylebox("bg","VSplitContainer", make_stylebox( vsplit_bg_png,1,1,1,1) );
- t->set_stylebox("bg","HSplitContainer", make_stylebox( hsplit_bg_png,1,1,1,1) );
-
- t->set_icon("grabber","VSplitContainer",make_icon(vsplitter_png));
- t->set_icon("grabber","HSplitContainer",make_icon(hsplitter_png));
-
- t->set_constant("separation","HBoxContainer",4 *scale);
- t->set_constant("separation","VBoxContainer",4 *scale);
- t->set_constant("margin_left","MarginContainer",8 *scale);
- t->set_constant("margin_top","MarginContainer",0 *scale);
- t->set_constant("margin_right","MarginContainer",0 *scale);
- t->set_constant("margin_bottom","MarginContainer",0 *scale);
- t->set_constant("hseparation","GridContainer",4 *scale);
- t->set_constant("vseparation","GridContainer",4 *scale);
- t->set_constant("separation","HSplitContainer",12 *scale);
- t->set_constant("separation","VSplitContainer",12 *scale);
- t->set_constant("autohide","HSplitContainer",1 *scale);
- t->set_constant("autohide","VSplitContainer",1 *scale);
-
-
+ t->set_stylebox("bg", "VSplitContainer", make_stylebox(vsplit_bg_png, 1, 1, 1, 1));
+ t->set_stylebox("bg", "HSplitContainer", make_stylebox(hsplit_bg_png, 1, 1, 1, 1));
+
+ t->set_icon("grabber", "VSplitContainer", make_icon(vsplitter_png));
+ t->set_icon("grabber", "HSplitContainer", make_icon(hsplitter_png));
+
+ t->set_constant("separation", "HBoxContainer", 4 * scale);
+ t->set_constant("separation", "VBoxContainer", 4 * scale);
+ t->set_constant("margin_left", "MarginContainer", 8 * scale);
+ t->set_constant("margin_top", "MarginContainer", 0 * scale);
+ t->set_constant("margin_right", "MarginContainer", 0 * scale);
+ t->set_constant("margin_bottom", "MarginContainer", 0 * scale);
+ t->set_constant("hseparation", "GridContainer", 4 * scale);
+ t->set_constant("vseparation", "GridContainer", 4 * scale);
+ t->set_constant("separation", "HSplitContainer", 12 * scale);
+ t->set_constant("separation", "VSplitContainer", 12 * scale);
+ t->set_constant("autohide", "HSplitContainer", 1 * scale);
+ t->set_constant("autohide", "VSplitContainer", 1 * scale);
// HButtonArray
- t->set_stylebox("normal","HButtonArray", sb_button_normal);
- t->set_stylebox("selected","HButtonArray", sb_button_pressed);
- t->set_stylebox("hover","HButtonArray", sb_button_hover);
-
- t->set_font("font","HButtonArray", default_font);
- t->set_font("font_selected","HButtonArray", default_font);
+ t->set_stylebox("normal", "HButtonArray", sb_button_normal);
+ t->set_stylebox("selected", "HButtonArray", sb_button_pressed);
+ t->set_stylebox("hover", "HButtonArray", sb_button_hover);
- t->set_color("font_color","HButtonArray", control_font_color_low );
- t->set_color("font_color_selected","HButtonArray", control_font_color_hover );
+ t->set_font("font", "HButtonArray", default_font);
+ t->set_font("font_selected", "HButtonArray", default_font);
- t->set_constant("icon_separator","HButtonArray", 2 *scale );
- t->set_constant("button_separator","HButtonArray", 4 *scale );
+ t->set_color("font_color", "HButtonArray", control_font_color_low);
+ t->set_color("font_color_selected", "HButtonArray", control_font_color_hover);
- t->set_stylebox("focus","HButtonArray", focus );
+ t->set_constant("icon_separator", "HButtonArray", 2 * scale);
+ t->set_constant("button_separator", "HButtonArray", 4 * scale);
+ t->set_stylebox("focus", "HButtonArray", focus);
// VButtonArray
- t->set_stylebox("normal","VButtonArray", sb_button_normal);
- t->set_stylebox("selected","VButtonArray", sb_button_pressed);
- t->set_stylebox("hover","VButtonArray", sb_button_hover);
-
- t->set_font("font","VButtonArray", default_font);
- t->set_font("font_selected","VButtonArray", default_font);
+ t->set_stylebox("normal", "VButtonArray", sb_button_normal);
+ t->set_stylebox("selected", "VButtonArray", sb_button_pressed);
+ t->set_stylebox("hover", "VButtonArray", sb_button_hover);
- t->set_color("font_color","VButtonArray", control_font_color_low );
- t->set_color("font_color_selected","VButtonArray", control_font_color_hover );
+ t->set_font("font", "VButtonArray", default_font);
+ t->set_font("font_selected", "VButtonArray", default_font);
- t->set_constant("icon_separator","VButtonArray", 2 *scale);
- t->set_constant("button_separator","VButtonArray", 4 *scale);
+ t->set_color("font_color", "VButtonArray", control_font_color_low);
+ t->set_color("font_color_selected", "VButtonArray", control_font_color_hover);
- t->set_stylebox("focus","VButtonArray", focus );
+ t->set_constant("icon_separator", "VButtonArray", 2 * scale);
+ t->set_constant("button_separator", "VButtonArray", 4 * scale);
+ t->set_stylebox("focus", "VButtonArray", focus);
// ReferenceRect
- Ref<StyleBoxTexture> ttnc = make_stylebox( full_panel_bg_png,8,8,8,8);
+ Ref<StyleBoxTexture> ttnc = make_stylebox(full_panel_bg_png, 8, 8, 8, 8);
ttnc->set_draw_center(false);
- t->set_stylebox("border","ReferenceRect", make_stylebox( reference_border_png,4,4,4,4) );
- t->set_stylebox("panelnc","Panel", ttnc );
- t->set_stylebox("panelf","Panel", tc_sb );
-
- Ref<StyleBoxTexture> sb_pc = make_stylebox( tab_container_bg_png,4,4,4,4,7,7,7,7);
- t->set_stylebox("panel","PanelContainer", sb_pc );
-
-
+ t->set_stylebox("border", "ReferenceRect", make_stylebox(reference_border_png, 4, 4, 4, 4));
+ t->set_stylebox("panelnc", "Panel", ttnc);
+ t->set_stylebox("panelf", "Panel", tc_sb);
- t->set_icon("minus","GraphEdit", make_icon(icon_zoom_less_png) );
- t->set_icon("reset","GraphEdit", make_icon(icon_zoom_reset_png) );
- t->set_icon("more","GraphEdit", make_icon(icon_zoom_more_png) );
- t->set_icon("snap","GraphEdit", make_icon(icon_snap_png) );
- t->set_stylebox("bg","GraphEdit", make_stylebox( tree_bg_png,4,4,4,5) );
- t->set_color("grid_minor","GraphEdit", Color(1,1,1,0.05) );
- t->set_color("grid_major","GraphEdit", Color(1,1,1,0.2) );
- t->set_constant("bezier_len_pos","GraphEdit", 80*scale );
- t->set_constant("bezier_len_neg","GraphEdit", 160*scale );
+ Ref<StyleBoxTexture> sb_pc = make_stylebox(tab_container_bg_png, 4, 4, 4, 4, 7, 7, 7, 7);
+ t->set_stylebox("panel", "PanelContainer", sb_pc);
+ t->set_icon("minus", "GraphEdit", make_icon(icon_zoom_less_png));
+ t->set_icon("reset", "GraphEdit", make_icon(icon_zoom_reset_png));
+ t->set_icon("more", "GraphEdit", make_icon(icon_zoom_more_png));
+ t->set_icon("snap", "GraphEdit", make_icon(icon_snap_png));
+ t->set_stylebox("bg", "GraphEdit", make_stylebox(tree_bg_png, 4, 4, 4, 5));
+ t->set_color("grid_minor", "GraphEdit", Color(1, 1, 1, 0.05));
+ t->set_color("grid_major", "GraphEdit", Color(1, 1, 1, 0.2));
+ t->set_constant("bezier_len_pos", "GraphEdit", 80 * scale);
+ t->set_constant("bezier_len_neg", "GraphEdit", 160 * scale);
-
- t->set_icon( "logo","Icons", make_icon(logo_png) );
-
+ t->set_icon("logo", "Icons", make_icon(logo_png));
// Theme
- default_icon= make_icon(error_icon_png) ;
- default_style = make_stylebox( error_icon_png,2,2,2,2) ;
-
- memdelete( tex_cache );
+ default_icon = make_icon(error_icon_png);
+ default_style = make_stylebox(error_icon_png, 2, 2, 2, 2);
+ memdelete(tex_cache);
}
-void make_default_theme(bool p_hidpi,Ref<Font> p_font) {
+void make_default_theme(bool p_hidpi, Ref<Font> p_font) {
Ref<Theme> t;
t.instance();
@@ -980,27 +902,25 @@ void make_default_theme(bool p_hidpi,Ref<Font> p_font) {
Ref<Texture> default_icon;
Ref<BitmapFont> default_font;
if (p_font.is_valid()) {
- default_font=p_font;
+ default_font = p_font;
} else if (p_hidpi) {
- default_font=make_font2(_hidpi_font_height,_hidpi_font_ascent,_hidpi_font_charcount,&_hidpi_font_charrects[0][0],_hidpi_font_kerning_pair_count,&_hidpi_font_kerning_pairs[0][0],_hidpi_font_img_width,_hidpi_font_img_height,_hidpi_font_img_data);
+ default_font = make_font2(_hidpi_font_height, _hidpi_font_ascent, _hidpi_font_charcount, &_hidpi_font_charrects[0][0], _hidpi_font_kerning_pair_count, &_hidpi_font_kerning_pairs[0][0], _hidpi_font_img_width, _hidpi_font_img_height, _hidpi_font_img_data);
} else {
- default_font=make_font2(_lodpi_font_height,_lodpi_font_ascent,_lodpi_font_charcount,&_lodpi_font_charrects[0][0],_lodpi_font_kerning_pair_count,&_lodpi_font_kerning_pairs[0][0],_lodpi_font_img_width,_lodpi_font_img_height,_lodpi_font_img_data);
+ default_font = make_font2(_lodpi_font_height, _lodpi_font_ascent, _lodpi_font_charcount, &_lodpi_font_charrects[0][0], _lodpi_font_kerning_pair_count, &_lodpi_font_kerning_pairs[0][0], _lodpi_font_img_width, _lodpi_font_img_height, _lodpi_font_img_data);
}
- Ref<BitmapFont> large_font=default_font;
- fill_default_theme(t,default_font,large_font,default_icon,default_style,p_hidpi?2.0:1.0);
-
- Theme::set_default( t );
- Theme::set_default_icon( default_icon );
- Theme::set_default_style( default_style );
- Theme::set_default_font( default_font );
+ Ref<BitmapFont> large_font = default_font;
+ fill_default_theme(t, default_font, large_font, default_icon, default_style, p_hidpi ? 2.0 : 1.0);
+ Theme::set_default(t);
+ Theme::set_default_icon(default_icon);
+ Theme::set_default_style(default_style);
+ Theme::set_default_font(default_font);
}
void clear_default_theme() {
- Theme::set_default( Ref<Theme>() );
- Theme::set_default_icon( Ref< Texture >() );
- Theme::set_default_style( Ref< StyleBox >() );
- Theme::set_default_font( Ref< Font >() );
-
+ Theme::set_default(Ref<Theme>());
+ Theme::set_default_icon(Ref<Texture>());
+ Theme::set_default_style(Ref<StyleBox>());
+ Theme::set_default_font(Ref<Font>());
}
diff --git a/scene/resources/default_theme/default_theme.h b/scene/resources/default_theme/default_theme.h
index 01141ed0a0..fc557e4270 100644
--- a/scene/resources/default_theme/default_theme.h
+++ b/scene/resources/default_theme/default_theme.h
@@ -35,7 +35,7 @@
@author Juan Linietsky <reduzio@gmail.com>
*/
-void fill_default_theme(Ref<Theme>& theme,const Ref<Font> & default_font,const Ref<Font> & large_font,Ref<Texture>& default_icon, Ref<StyleBox>& default_style,float p_scale);
+void fill_default_theme(Ref<Theme> &theme, const Ref<Font> &default_font, const Ref<Font> &large_font, Ref<Texture> &default_icon, Ref<StyleBox> &default_style, float p_scale);
void make_default_theme(bool p_hidpi, Ref<Font> p_font);
void clear_default_theme();
diff --git a/scene/resources/dynamic_font.cpp b/scene/resources/dynamic_font.cpp
index 02149f5748..08ebb954b2 100644
--- a/scene/resources/dynamic_font.cpp
+++ b/scene/resources/dynamic_font.cpp
@@ -30,9 +30,9 @@
#include "dynamic_font.h"
#include "os/file_access.h"
-bool DynamicFontData::CacheID::operator< (CacheID right) const{
+bool DynamicFontData::CacheID::operator<(CacheID right) const {
- if (size<right.size)
+ if (size < right.size)
return true;
if (mipmaps != right.mipmaps)
return right.mipmaps;
@@ -41,37 +41,34 @@ bool DynamicFontData::CacheID::operator< (CacheID right) const{
return false;
}
-Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_id){
-
+Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(CacheID p_id) {
if (size_cache.has(p_id)) {
- return Ref<DynamicFontAtSize>( size_cache[p_id] );
+ return Ref<DynamicFontAtSize>(size_cache[p_id]);
}
-
Ref<DynamicFontAtSize> dfas;
dfas.instance();
- dfas->font=Ref<DynamicFontData>( this );
+ dfas->font = Ref<DynamicFontData>(this);
- size_cache[p_id]=dfas.ptr();
- dfas->id=p_id;
+ size_cache[p_id] = dfas.ptr();
+ dfas->id = p_id;
dfas->_load();
return dfas;
-
}
-void DynamicFontData::set_font_ptr(const uint8_t* p_font_mem,int p_font_mem_size) {
+void DynamicFontData::set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size) {
- font_mem=p_font_mem;
- font_mem_size=p_font_mem_size;
+ font_mem = p_font_mem;
+ font_mem_size = p_font_mem_size;
}
-void DynamicFontData::set_font_path(const String& p_path) {
+void DynamicFontData::set_font_path(const String &p_path) {
- font_path=p_path;
+ font_path = p_path;
}
String DynamicFontData::get_font_path() const {
@@ -80,73 +77,67 @@ String DynamicFontData::get_font_path() const {
void DynamicFontData::set_force_autohinter(bool p_force) {
- force_autohinter=p_force;
+ force_autohinter = p_force;
}
void DynamicFontData::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_font_path","path"),&DynamicFontData::set_font_path);
- ClassDB::bind_method(D_METHOD("get_font_path"),&DynamicFontData::get_font_path);
+ ClassDB::bind_method(D_METHOD("set_font_path", "path"), &DynamicFontData::set_font_path);
+ ClassDB::bind_method(D_METHOD("get_font_path"), &DynamicFontData::get_font_path);
- ADD_PROPERTY(PropertyInfo(Variant::STRING,"font_path",PROPERTY_HINT_FILE,"*.ttf,*.otf"),"set_font_path","get_font_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "font_path", PROPERTY_HINT_FILE, "*.ttf,*.otf"), "set_font_path", "get_font_path");
}
-DynamicFontData::DynamicFontData()
-{
+DynamicFontData::DynamicFontData() {
- force_autohinter=false;
- font_mem=NULL;
- font_mem_size=0;
+ force_autohinter = false;
+ font_mem = NULL;
+ font_mem_size = 0;
}
-DynamicFontData::~DynamicFontData()
-{
-
+DynamicFontData::~DynamicFontData() {
}
-
-
////////////////////
Error DynamicFontAtSize::_load() {
-
- int error = FT_Init_FreeType( &library );
+ int error = FT_Init_FreeType(&library);
ERR_EXPLAIN(TTR("Error initializing FreeType."));
- ERR_FAIL_COND_V( error !=0, ERR_CANT_CREATE );
+ ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE);
- if (font->font_path!=String()) {
+ if (font->font_path != String()) {
- FileAccess *f=FileAccess::open(font->font_path,FileAccess::READ);
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
+ FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
- memset(&stream,0,sizeof(FT_StreamRec));
- stream.base=NULL;
- stream.size=f->get_len();
- stream.pos=0;
- stream.descriptor.pointer=f;
- stream.read=_ft_stream_io;
- stream.close=_ft_stream_close;
+ memset(&stream, 0, sizeof(FT_StreamRec));
+ stream.base = NULL;
+ stream.size = f->get_len();
+ stream.pos = 0;
+ stream.descriptor.pointer = f;
+ stream.read = _ft_stream_io;
+ stream.close = _ft_stream_close;
FT_Open_Args fargs;
- memset(&fargs,0,sizeof(FT_Open_Args));
- fargs.flags=FT_OPEN_STREAM;
- fargs.stream=&stream;
- error = FT_Open_Face( library,&fargs,0,&face);
+ memset(&fargs, 0, sizeof(FT_Open_Args));
+ fargs.flags = FT_OPEN_STREAM;
+ fargs.stream = &stream;
+ error = FT_Open_Face(library, &fargs, 0, &face);
} else if (font->font_mem) {
- memset(&stream,0,sizeof(FT_StreamRec));
- stream.base=(unsigned char*)font->font_mem;
- stream.size=font->font_mem_size;
- stream.pos=0;
+ memset(&stream, 0, sizeof(FT_StreamRec));
+ stream.base = (unsigned char *)font->font_mem;
+ stream.size = font->font_mem_size;
+ stream.pos = 0;
FT_Open_Args fargs;
- memset(&fargs,0,sizeof(FT_Open_Args));
- fargs.memory_base=(unsigned char*)font->font_mem;
- fargs.memory_size=font->font_mem_size;
- fargs.flags= FT_OPEN_MEMORY;
- fargs.stream=&stream;
- error = FT_Open_Face( library,&fargs,0,&face);
+ memset(&fargs, 0, sizeof(FT_Open_Args));
+ fargs.memory_base = (unsigned char *)font->font_mem;
+ fargs.memory_size = font->font_mem_size;
+ fargs.flags = FT_OPEN_MEMORY;
+ fargs.stream = &stream;
+ error = FT_Open_Face(library, &fargs, 0, &face);
} else {
ERR_EXPLAIN("DynamicFont uninitialized");
@@ -155,19 +146,17 @@ Error DynamicFontAtSize::_load() {
//error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );
- if ( error == FT_Err_Unknown_File_Format ) {
+ if (error == FT_Err_Unknown_File_Format) {
ERR_EXPLAIN(TTR("Unknown font format."));
- FT_Done_FreeType( library );
+ FT_Done_FreeType(library);
- } else if ( error ) {
+ } else if (error) {
ERR_EXPLAIN(TTR("Error loading font."));
- FT_Done_FreeType( library );
-
+ FT_Done_FreeType(library);
}
- ERR_FAIL_COND_V(error,ERR_FILE_CANT_OPEN);
-
+ ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);
/*error = FT_Set_Char_Size(face,0,64*size,512,512);
@@ -177,26 +166,26 @@ Error DynamicFontAtSize::_load() {
ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
}*/
- error = FT_Set_Pixel_Sizes(face,0,id.size);
+ error = FT_Set_Pixel_Sizes(face, 0, id.size);
- ascent=face->size->metrics.ascender>>6;
- descent=-face->size->metrics.descender>>6;
- linegap=0;
- texture_flags=0;
+ ascent = face->size->metrics.ascender >> 6;
+ descent = -face->size->metrics.descender >> 6;
+ linegap = 0;
+ texture_flags = 0;
if (id.mipmaps)
- texture_flags|=Texture::FLAG_MIPMAPS;
+ texture_flags |= Texture::FLAG_MIPMAPS;
if (id.filter)
- texture_flags|=Texture::FLAG_FILTER;
+ texture_flags |= Texture::FLAG_FILTER;
//print_line("ASCENT: "+itos(ascent)+" descent "+itos(descent)+" hinted: "+itos(face->face_flags&FT_FACE_FLAG_HINTER));
- valid=true;
+ valid = true;
return OK;
}
float DynamicFontAtSize::get_height() const {
- return ascent+descent;
+ return ascent + descent;
}
float DynamicFontAtSize::get_ascent() const {
@@ -208,23 +197,23 @@ float DynamicFontAtSize::get_descent() const {
return descent;
}
-Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const {
+Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
if (!valid)
- return Size2(1,1);
- const_cast<DynamicFontAtSize*>(this)->_update_char(p_char);
+ return Size2(1, 1);
+ const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
const Character *c = char_map.getptr(p_char);
- ERR_FAIL_COND_V(!c,Size2());
+ ERR_FAIL_COND_V(!c, Size2());
- Size2 ret(0,get_height());
+ Size2 ret(0, get_height());
if (!c->found) {
//not found, try in fallbacks
- for(int i=0;i<p_fallbacks.size();i++) {
+ for (int i = 0; i < p_fallbacks.size(); i++) {
- DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr());
+ DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
if (!fb->valid)
continue;
@@ -235,83 +224,79 @@ Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next,const Vec
if (!ch->found)
continue;
- c=ch;
+ c = ch;
break;
}
//not found, try 0xFFFD to display 'not found'.
if (!c->found) {
- const_cast<DynamicFontAtSize*>(this)->_update_char(0xFFFD);
+ const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
c = char_map.getptr(0xFFFD);
- ERR_FAIL_COND_V(!c,Size2());
-
+ ERR_FAIL_COND_V(!c, Size2());
}
}
if (c->found) {
- ret.x=c->advance;
+ ret.x = c->advance;
}
-
if (p_next) {
- FT_Vector delta;
- FT_Get_Kerning( face, p_char,p_next, FT_KERNING_DEFAULT, &delta );
+ FT_Vector delta;
+ FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
- if (delta.x==0) {
- for(int i=0;i<p_fallbacks.size();i++) {
+ if (delta.x == 0) {
+ for (int i = 0; i < p_fallbacks.size(); i++) {
- DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr());
+ DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
if (!fb->valid)
continue;
- FT_Get_Kerning( fb->face, p_char,p_next, FT_KERNING_DEFAULT, &delta );
+ FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
- if (delta.x==0)
+ if (delta.x == 0)
continue;
- ret.x+=delta.x>>6;
+ ret.x += delta.x >> 6;
break;
}
} else {
- ret.x+=delta.x>>6;
+ ret.x += delta.x >> 6;
}
-
-
}
return ret;
}
-void DynamicFontAtSize::set_texture_flags(uint32_t p_flags){
-
- texture_flags=p_flags;
- for(int i=0;i<textures.size();i++) {
+void DynamicFontAtSize::set_texture_flags(uint32_t p_flags) {
+
+ texture_flags = p_flags;
+ for (int i = 0; i < textures.size(); i++) {
Ref<ImageTexture> &tex = textures[i].texture;
if (!tex.is_null())
tex->set_flags(p_flags);
}
}
-float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const {
+float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const {
if (!valid)
return 0;
- const_cast<DynamicFontAtSize*>(this)->_update_char(p_char);
+ const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
- const Character * c = char_map.getptr(p_char);
+ const Character *c = char_map.getptr(p_char);
- float advance=0;
+ float advance = 0;
if (!c->found) {
//not found, try in fallbacks
- bool used_fallback=false;
+ bool used_fallback = false;
- for(int i=0;i<p_fallbacks.size();i++) {
+ for (int i = 0; i < p_fallbacks.size(); i++) {
- DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr());
+ DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
if (!fb->valid)
continue;
@@ -322,93 +307,87 @@ float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharT
if (!ch->found)
continue;
- Point2 cpos=p_pos;
- cpos.x+=ch->h_align;
- cpos.y-=get_ascent();
- cpos.y+=ch->v_align;
- ERR_FAIL_COND_V( ch->texture_idx<-1 || ch->texture_idx>=fb->textures.size(),0);
- if (ch->texture_idx!=-1)
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, ch->rect.size ), fb->textures[ch->texture_idx].texture->get_rid(),ch->rect, p_modulate );
- advance=ch->advance;
- used_fallback=true;
+ Point2 cpos = p_pos;
+ cpos.x += ch->h_align;
+ cpos.y -= get_ascent();
+ cpos.y += ch->v_align;
+ ERR_FAIL_COND_V(ch->texture_idx < -1 || ch->texture_idx >= fb->textures.size(), 0);
+ if (ch->texture_idx != -1)
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, ch->rect.size), fb->textures[ch->texture_idx].texture->get_rid(), ch->rect, p_modulate);
+ advance = ch->advance;
+ used_fallback = true;
break;
}
//not found, try 0xFFFD to display 'not found'.
if (!used_fallback) {
- const_cast<DynamicFontAtSize*>(this)->_update_char(0xFFFD);
+ const_cast<DynamicFontAtSize *>(this)->_update_char(0xFFFD);
c = char_map.getptr(0xFFFD);
-
}
}
if (c->found) {
-
- Point2 cpos=p_pos;
- cpos.x+=c->h_align;
- cpos.y-=get_ascent();
- cpos.y+=c->v_align;
- ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0);
- if (c->texture_idx!=-1)
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx].texture->get_rid(),c->rect, p_modulate );
- advance=c->advance;
+ Point2 cpos = p_pos;
+ cpos.x += c->h_align;
+ cpos.y -= get_ascent();
+ cpos.y += c->v_align;
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
+ if (c->texture_idx != -1)
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate);
+ advance = c->advance;
//textures[c->texture_idx].texture->draw(p_canvas_item,Vector2());
}
-
if (p_next) {
- FT_Vector delta;
- FT_Get_Kerning( face, p_char,p_next, FT_KERNING_DEFAULT, &delta );
+ FT_Vector delta;
+ FT_Get_Kerning(face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
- if (delta.x==0) {
- for(int i=0;i<p_fallbacks.size();i++) {
+ if (delta.x == 0) {
+ for (int i = 0; i < p_fallbacks.size(); i++) {
- DynamicFontAtSize *fb = const_cast<DynamicFontAtSize*>(p_fallbacks[i].ptr());
+ DynamicFontAtSize *fb = const_cast<DynamicFontAtSize *>(p_fallbacks[i].ptr());
if (!fb->valid)
continue;
- FT_Get_Kerning( fb->face, p_char,p_next, FT_KERNING_DEFAULT, &delta );
+ FT_Get_Kerning(fb->face, p_char, p_next, FT_KERNING_DEFAULT, &delta);
- if (delta.x==0)
+ if (delta.x == 0)
continue;
- advance+=delta.x>>6;
+ advance += delta.x >> 6;
break;
}
} else {
- advance+=delta.x>>6;
+ advance += delta.x >> 6;
}
}
return advance;
}
-unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) {
-
+unsigned long DynamicFontAtSize::_ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count) {
- FileAccess *f=(FileAccess*)stream->descriptor.pointer;
+ FileAccess *f = (FileAccess *)stream->descriptor.pointer;
- if (f->get_pos()!=offset) {
+ if (f->get_pos() != offset) {
f->seek(offset);
-
}
- if (count==0)
+ if (count == 0)
return 0;
- return f->get_buffer(buffer,count);
+ return f->get_buffer(buffer, count);
}
void DynamicFontAtSize::_ft_stream_close(FT_Stream stream) {
- FileAccess *f=(FileAccess*)stream->descriptor.pointer;
+ FileAccess *f = (FileAccess *)stream->descriptor.pointer;
f->close();
memdelete(f);
}
-
void DynamicFontAtSize::_update_char(CharType p_char) {
if (char_map.has(p_char))
@@ -418,154 +397,146 @@ void DynamicFontAtSize::_update_char(CharType p_char) {
FT_GlyphSlot slot = face->glyph;
- if (FT_Get_Char_Index( face, p_char)==0) {
+ if (FT_Get_Char_Index(face, p_char) == 0) {
//not found
Character ch;
- ch.texture_idx=-1;
- ch.advance=0;
- ch.h_align=0;
- ch.v_align=0;
- ch.found=false;
+ ch.texture_idx = -1;
+ ch.advance = 0;
+ ch.h_align = 0;
+ ch.v_align = 0;
+ ch.found = false;
- char_map[p_char]=ch;
+ char_map[p_char] = ch;
return;
}
- int error = FT_Load_Char( face, p_char, FT_LOAD_RENDER|(font->force_autohinter?FT_LOAD_FORCE_AUTOHINT:0) );
+ int error = FT_Load_Char(face, p_char, FT_LOAD_RENDER | (font->force_autohinter ? FT_LOAD_FORCE_AUTOHINT : 0));
if (!error) {
- error = FT_Render_Glyph( face->glyph, ft_render_mode_normal );
+ error = FT_Render_Glyph(face->glyph, ft_render_mode_normal);
}
if (error) {
- int advance=0;
+ int advance = 0;
//stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
//print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale));
Character ch;
- ch.texture_idx=-1;
- ch.advance=advance;
- ch.h_align=0;
- ch.v_align=0;
- ch.found=false;
-
- char_map[p_char]=ch;
+ ch.texture_idx = -1;
+ ch.advance = advance;
+ ch.h_align = 0;
+ ch.v_align = 0;
+ ch.found = false;
+ char_map[p_char] = ch;
return;
}
-
-
int w = slot->bitmap.width;
int h = slot->bitmap.rows;
//int p = slot->bitmap.pitch;
- int yofs=slot->bitmap_top;
- int xofs=slot->bitmap_left;
- int advance=slot->advance.x>>6;
+ int yofs = slot->bitmap_top;
+ int xofs = slot->bitmap_left;
+ int advance = slot->advance.x >> 6;
+ int mw = w + rect_margin * 2;
+ int mh = h + rect_margin * 2;
- int mw=w+rect_margin*2;
- int mh=h+rect_margin*2;
+ if (mw > 4096 || mh > 4096) {
- if (mw>4096 || mh>4096) {
-
- ERR_FAIL_COND(mw>4096);
- ERR_FAIL_COND(mh>4096);
+ ERR_FAIL_COND(mw > 4096);
+ ERR_FAIL_COND(mh > 4096);
}
//find a texture to fit this...
- int tex_index=-1;
- int tex_x=0;
- int tex_y=0;
+ int tex_index = -1;
+ int tex_x = 0;
+ int tex_y = 0;
- for(int i=0;i<textures.size();i++) {
+ for (int i = 0; i < textures.size(); i++) {
- CharTexture &ct=textures[i];
+ CharTexture &ct = textures[i];
if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
continue;
- tex_y=0x7FFFFFFF;
- tex_x=0;
+ tex_y = 0x7FFFFFFF;
+ tex_x = 0;
- for(int j=0;j<ct.texture_size-mw;j++) {
+ for (int j = 0; j < ct.texture_size - mw; j++) {
- int max_y=0;
+ int max_y = 0;
- for(int k=j;k<j+mw;k++) {
+ for (int k = j; k < j + mw; k++) {
int y = ct.offsets[k];
- if (y>max_y)
- max_y=y;
+ if (y > max_y)
+ max_y = y;
}
- if (max_y<tex_y) {
- tex_y=max_y;
- tex_x=j;
+ if (max_y < tex_y) {
+ tex_y = max_y;
+ tex_x = j;
}
}
- if (tex_y==0x7FFFFFFF || tex_y+mh > ct.texture_size)
+ if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size)
continue; //fail, could not fit it here
- tex_index=i;
+ tex_index = i;
break;
}
//print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y));
- if (tex_index==-1) {
+ if (tex_index == -1) {
//could not find texture to fit, create one
tex_x = 0;
tex_y = 0;
- int texsize = MAX(id.size*8,256);
- if (mw>texsize)
- texsize=mw; //special case, adapt to it?
- if (mh>texsize)
- texsize=mh; //special case, adapt to it?
-
- texsize=nearest_power_of_2(texsize);
+ int texsize = MAX(id.size * 8, 256);
+ if (mw > texsize)
+ texsize = mw; //special case, adapt to it?
+ if (mh > texsize)
+ texsize = mh; //special case, adapt to it?
- texsize=MIN(texsize,4096);
+ texsize = nearest_power_of_2(texsize);
+ texsize = MIN(texsize, 4096);
CharTexture tex;
- tex.texture_size=texsize;
- tex.imgdata.resize(texsize*texsize*2); //grayscale alpha
+ tex.texture_size = texsize;
+ tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha
{
//zero texture
PoolVector<uint8_t>::Write w = tex.imgdata.write();
- ERR_FAIL_COND(texsize*texsize*2 > tex.imgdata.size());
- for(int i=0;i<texsize*texsize*2;i++) {
- w[i]=0;
+ ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size());
+ for (int i = 0; i < texsize * texsize * 2; i++) {
+ w[i] = 0;
}
}
tex.offsets.resize(texsize);
- for(int i=0;i<texsize;i++) //zero offsets
- tex.offsets[i]=0;
+ for (int i = 0; i < texsize; i++) //zero offsets
+ tex.offsets[i] = 0;
textures.push_back(tex);
- tex_index=textures.size()-1;
-
+ tex_index = textures.size() - 1;
}
-
//fit character in char texture
- CharTexture &tex=textures[tex_index];
+ CharTexture &tex = textures[tex_index];
{
PoolVector<uint8_t>::Write wr = tex.imgdata.write();
+ for (int i = 0; i < h; i++) {
+ for (int j = 0; j < w; j++) {
- for(int i=0;i<h;i++) {
- for(int j=0;j<w;j++) {
-
- int ofs = ( (i+tex_y+rect_margin)*tex.texture_size+j+tex_x+rect_margin)*2;
+ int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2;
ERR_FAIL_COND(ofs >= tex.imgdata.size());
- wr[ofs+0]=255; //grayscale as 1
- wr[ofs+1]=slot->bitmap.buffer[i*slot->bitmap.width+j];
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = slot->bitmap.buffer[i * slot->bitmap.width + j];
}
}
}
@@ -573,237 +544,224 @@ void DynamicFontAtSize::_update_char(CharType p_char) {
//blit to image and texture
{
- Image img(tex.texture_size,tex.texture_size,0,Image::FORMAT_LA8,tex.imgdata);
+ Image img(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata);
if (tex.texture.is_null()) {
tex.texture.instance();
- tex.texture->create_from_image(img,Texture::FLAG_VIDEO_SURFACE|texture_flags);
+ tex.texture->create_from_image(img, Texture::FLAG_VIDEO_SURFACE | texture_flags);
} else {
tex.texture->set_data(img); //update
}
-
}
-
// update height array
- for(int k=tex_x;k<tex_x+mw;k++) {
+ for (int k = tex_x; k < tex_x + mw; k++) {
- tex.offsets[k]=tex_y+mh;
+ tex.offsets[k] = tex_y + mh;
}
-
Character chr;
- chr.h_align=xofs;
- chr.v_align=ascent-yofs;// + ascent - descent;
- chr.advance=advance;
- chr.texture_idx=tex_index;
- chr.found=true;
-
+ chr.h_align = xofs;
+ chr.v_align = ascent - yofs; // + ascent - descent;
+ chr.advance = advance;
+ chr.texture_idx = tex_index;
+ chr.found = true;
- chr.rect=Rect2(tex_x+rect_margin,tex_y+rect_margin,w,h);
+ chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h);
//print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs));
- char_map[p_char]=chr;
-
-
+ char_map[p_char] = chr;
}
DynamicFontAtSize::DynamicFontAtSize() {
- valid=false;
- rect_margin=1;
- ascent=1;
- descent=1;
- linegap=1;
- texture_flags=0;
+ valid = false;
+ rect_margin = 1;
+ ascent = 1;
+ descent = 1;
+ linegap = 1;
+ texture_flags = 0;
}
-DynamicFontAtSize::~DynamicFontAtSize(){
+DynamicFontAtSize::~DynamicFontAtSize() {
if (valid) {
- FT_Done_FreeType( library );
+ FT_Done_FreeType(library);
font->size_cache.erase(id);
}
}
/////////////////////////
+void DynamicFont::_reload_cache() {
-void DynamicFont::_reload_cache(){
-
- ERR_FAIL_COND(cache_id.size<1);
+ ERR_FAIL_COND(cache_id.size < 1);
if (!data.is_valid())
return;
- data_at_size=data->_get_dynamic_font_at_size(cache_id);
- for (int i=0;i<fallbacks.size();i++){
- fallback_data_at_size[i]=fallbacks[i]->_get_dynamic_font_at_size(cache_id);
+ data_at_size = data->_get_dynamic_font_at_size(cache_id);
+ for (int i = 0; i < fallbacks.size(); i++) {
+ fallback_data_at_size[i] = fallbacks[i]->_get_dynamic_font_at_size(cache_id);
}
emit_changed();
_change_notify();
}
-void DynamicFont::set_font_data(const Ref<DynamicFontData>& p_data) {
+void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
- data=p_data;
+ data = p_data;
if (data.is_valid())
- data_at_size=data->_get_dynamic_font_at_size(cache_id);
+ data_at_size = data->_get_dynamic_font_at_size(cache_id);
else
- data_at_size=Ref<DynamicFontAtSize>();
+ data_at_size = Ref<DynamicFontAtSize>();
emit_changed();
}
-
-Ref<DynamicFontData> DynamicFont::get_font_data() const{
+Ref<DynamicFontData> DynamicFont::get_font_data() const {
return data;
}
-void DynamicFont::set_size(int p_size){
+void DynamicFont::set_size(int p_size) {
- if (cache_id.size==p_size)
+ if (cache_id.size == p_size)
return;
- cache_id.size=p_size;
+ cache_id.size = p_size;
_reload_cache();
}
-int DynamicFont::get_size() const{
+int DynamicFont::get_size() const {
return cache_id.size;
}
-bool DynamicFont::get_use_mipmaps() const{
+bool DynamicFont::get_use_mipmaps() const {
return cache_id.mipmaps;
}
-void DynamicFont::set_use_mipmaps(bool p_enable){
+void DynamicFont::set_use_mipmaps(bool p_enable) {
- if (cache_id.mipmaps==p_enable)
+ if (cache_id.mipmaps == p_enable)
return;
- cache_id.mipmaps=p_enable;
+ cache_id.mipmaps = p_enable;
_reload_cache();
}
-bool DynamicFont::get_use_filter() const{
+bool DynamicFont::get_use_filter() const {
return cache_id.filter;
}
-void DynamicFont::set_use_filter(bool p_enable){
+void DynamicFont::set_use_filter(bool p_enable) {
- if (cache_id.filter==p_enable)
+ if (cache_id.filter == p_enable)
return;
- cache_id.filter=p_enable;
+ cache_id.filter = p_enable;
_reload_cache();
}
-int DynamicFont::get_spacing(int p_type) const{
+int DynamicFont::get_spacing(int p_type) const {
- if (p_type == SPACING_TOP){
+ if (p_type == SPACING_TOP) {
return spacing_top;
- }else if (p_type == SPACING_BOTTOM){
+ } else if (p_type == SPACING_BOTTOM) {
return spacing_bottom;
- }else if (p_type == SPACING_CHAR){
+ } else if (p_type == SPACING_CHAR) {
return spacing_char;
- }else if (p_type == SPACING_SPACE){
+ } else if (p_type == SPACING_SPACE) {
return spacing_space;
}
return 0;
}
-void DynamicFont::set_spacing(int p_type, int p_value){
+void DynamicFont::set_spacing(int p_type, int p_value) {
- if (p_type == SPACING_TOP){
- spacing_top=p_value;
- }else if (p_type == SPACING_BOTTOM){
- spacing_bottom=p_value;
- }else if (p_type == SPACING_CHAR){
- spacing_char=p_value;
- }else if (p_type == SPACING_SPACE){
- spacing_space=p_value;
+ if (p_type == SPACING_TOP) {
+ spacing_top = p_value;
+ } else if (p_type == SPACING_BOTTOM) {
+ spacing_bottom = p_value;
+ } else if (p_type == SPACING_CHAR) {
+ spacing_char = p_value;
+ } else if (p_type == SPACING_SPACE) {
+ spacing_space = p_value;
}
emit_changed();
_change_notify();
}
-float DynamicFont::get_height() const{
+float DynamicFont::get_height() const {
if (!data_at_size.is_valid())
return 1;
- return data_at_size->get_height()+spacing_top+spacing_bottom;
+ return data_at_size->get_height() + spacing_top + spacing_bottom;
}
-float DynamicFont::get_ascent() const{
+float DynamicFont::get_ascent() const {
if (!data_at_size.is_valid())
return 1;
- return data_at_size->get_ascent()+spacing_top;
+ return data_at_size->get_ascent() + spacing_top;
}
-float DynamicFont::get_descent() const{
+float DynamicFont::get_descent() const {
if (!data_at_size.is_valid())
return 1;
- return data_at_size->get_descent()+spacing_bottom;
-
+ return data_at_size->get_descent() + spacing_bottom;
}
-Size2 DynamicFont::get_char_size(CharType p_char,CharType p_next) const{
+Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
if (!data_at_size.is_valid())
- return Size2(1,1);
+ return Size2(1, 1);
- Size2 ret=data_at_size->get_char_size(p_char,p_next,fallback_data_at_size);
- if (p_char==' ')
- ret.width+=spacing_space+spacing_char;
+ Size2 ret = data_at_size->get_char_size(p_char, p_next, fallback_data_at_size);
+ if (p_char == ' ')
+ ret.width += spacing_space + spacing_char;
else if (p_next)
- ret.width+=spacing_char;
+ ret.width += spacing_char;
return ret;
-
}
-bool DynamicFont::is_distance_field_hint() const{
+bool DynamicFont::is_distance_field_hint() const {
return false;
}
-float DynamicFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const {
+float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
if (!data_at_size.is_valid())
return 0;
- return data_at_size->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate,fallback_data_at_size)+spacing_char;
-
+ return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate, fallback_data_at_size) + spacing_char;
}
-void DynamicFont::set_fallback(int p_idx,const Ref<DynamicFontData>& p_data) {
+void DynamicFont::set_fallback(int p_idx, const Ref<DynamicFontData> &p_data) {
ERR_FAIL_COND(p_data.is_null());
- ERR_FAIL_INDEX(p_idx,fallbacks.size());
- fallbacks[p_idx]=p_data;
- fallback_data_at_size[p_idx]=fallbacks[p_idx]->_get_dynamic_font_at_size(cache_id);
-
+ ERR_FAIL_INDEX(p_idx, fallbacks.size());
+ fallbacks[p_idx] = p_data;
+ fallback_data_at_size[p_idx] = fallbacks[p_idx]->_get_dynamic_font_at_size(cache_id);
}
-void DynamicFont::add_fallback(const Ref<DynamicFontData>& p_data) {
+void DynamicFont::add_fallback(const Ref<DynamicFontData> &p_data) {
ERR_FAIL_COND(p_data.is_null());
fallbacks.push_back(p_data);
- fallback_data_at_size.push_back(fallbacks[fallbacks.size()-1]->_get_dynamic_font_at_size(cache_id)); //const..
+ fallback_data_at_size.push_back(fallbacks[fallbacks.size() - 1]->_get_dynamic_font_at_size(cache_id)); //const..
_change_notify();
emit_changed();
_change_notify();
-
}
int DynamicFont::get_fallback_count() const {
@@ -811,37 +769,37 @@ int DynamicFont::get_fallback_count() const {
}
Ref<DynamicFontData> DynamicFont::get_fallback(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,fallbacks.size(),Ref<DynamicFontData>());
+ ERR_FAIL_INDEX_V(p_idx, fallbacks.size(), Ref<DynamicFontData>());
return fallbacks[p_idx];
}
void DynamicFont::remove_fallback(int p_idx) {
- ERR_FAIL_INDEX(p_idx,fallbacks.size());
+ ERR_FAIL_INDEX(p_idx, fallbacks.size());
fallbacks.remove(p_idx);
fallback_data_at_size.remove(p_idx);
emit_changed();
_change_notify();
}
-bool DynamicFont::_set(const StringName& p_name, const Variant& p_value) {
+bool DynamicFont::_set(const StringName &p_name, const Variant &p_value) {
String str = p_name;
if (str.begins_with("fallback/")) {
- int idx = str.get_slicec('/',1).to_int();
+ int idx = str.get_slicec('/', 1).to_int();
Ref<DynamicFontData> fd = p_value;
if (fd.is_valid()) {
- if (idx==fallbacks.size()) {
+ if (idx == fallbacks.size()) {
add_fallback(fd);
return true;
- } else if (idx>=0 && idx<fallbacks.size()) {
- set_fallback(idx,fd);
+ } else if (idx >= 0 && idx < fallbacks.size()) {
+ set_fallback(idx, fd);
return true;
} else {
return false;
}
- } else if (idx>=0 && idx<fallbacks.size()) {
+ } else if (idx >= 0 && idx < fallbacks.size()) {
remove_fallback(idx);
return true;
}
@@ -850,100 +808,95 @@ bool DynamicFont::_set(const StringName& p_name, const Variant& p_value) {
return false;
}
-bool DynamicFont::_get(const StringName& p_name,Variant &r_ret) const{
+bool DynamicFont::_get(const StringName &p_name, Variant &r_ret) const {
String str = p_name;
if (str.begins_with("fallback/")) {
- int idx = str.get_slicec('/',1).to_int();
+ int idx = str.get_slicec('/', 1).to_int();
- if (idx==fallbacks.size()) {
- r_ret=Ref<DynamicFontData>();
+ if (idx == fallbacks.size()) {
+ r_ret = Ref<DynamicFontData>();
return true;
- } else if (idx>=0 && idx<fallbacks.size()) {
- r_ret=get_fallback(idx);
+ } else if (idx >= 0 && idx < fallbacks.size()) {
+ r_ret = get_fallback(idx);
return true;
}
}
return false;
}
-void DynamicFont::_get_property_list( List<PropertyInfo> *p_list) const{
+void DynamicFont::_get_property_list(List<PropertyInfo> *p_list) const {
- for(int i=0;i<fallbacks.size();i++) {
- p_list->push_back(PropertyInfo(Variant::OBJECT,"fallback/"+itos(i),PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"));
+ for (int i = 0; i < fallbacks.size(); i++) {
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(i), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
}
- p_list->push_back(PropertyInfo(Variant::OBJECT,"fallback/"+itos(fallbacks.size()),PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "fallback/" + itos(fallbacks.size()), PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"));
}
-
void DynamicFont::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_font_data","data:DynamicFontData"),&DynamicFont::set_font_data);
- ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"),&DynamicFont::get_font_data);
-
- ClassDB::bind_method(D_METHOD("set_size","data"),&DynamicFont::set_size);
- ClassDB::bind_method(D_METHOD("get_size"),&DynamicFont::get_size);
-
- ClassDB::bind_method(D_METHOD("set_use_mipmaps","enable"),&DynamicFont::set_use_mipmaps);
- ClassDB::bind_method(D_METHOD("get_use_mipmaps"),&DynamicFont::get_use_mipmaps);
- ClassDB::bind_method(D_METHOD("set_use_filter","enable"),&DynamicFont::set_use_filter);
- ClassDB::bind_method(D_METHOD("get_use_filter"),&DynamicFont::get_use_filter);
- ClassDB::bind_method(D_METHOD("set_spacing","type","value"),&DynamicFont::set_spacing);
- ClassDB::bind_method(D_METHOD("get_spacing","type"),&DynamicFont::get_spacing);
-
- ClassDB::bind_method(D_METHOD("add_fallback","data:DynamicFontData"),&DynamicFont::add_fallback);
- ClassDB::bind_method(D_METHOD("set_fallback","idx","data:DynamicFontData"),&DynamicFont::set_fallback);
- ClassDB::bind_method(D_METHOD("get_fallback:DynamicFontData","idx"),&DynamicFont::get_fallback);
- ClassDB::bind_method(D_METHOD("remove_fallback","idx"),&DynamicFont::remove_fallback);
- ClassDB::bind_method(D_METHOD("get_fallback_count"),&DynamicFont::get_fallback_count);
-
-
- ADD_GROUP("Settings","");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"size"),"set_size","get_size");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_mipmaps"),"set_use_mipmaps","get_use_mipmaps");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"use_filter"),"set_use_filter","get_use_filter");
- ADD_GROUP("Extra Spacing","extra_spacing");
- ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_top"),"set_spacing","get_spacing",SPACING_TOP);
- ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_bottom"),"set_spacing","get_spacing",SPACING_BOTTOM);
- ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_char"),"set_spacing","get_spacing",SPACING_CHAR);
- ADD_PROPERTYINZ(PropertyInfo(Variant::INT,"extra_spacing_space"),"set_spacing","get_spacing",SPACING_SPACE);
- ADD_GROUP("Font","");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"font_data",PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"),"set_font_data","get_font_data");
-
- BIND_CONSTANT( SPACING_TOP );
- BIND_CONSTANT( SPACING_BOTTOM );
- BIND_CONSTANT( SPACING_CHAR );
- BIND_CONSTANT( SPACING_SPACE );
+ ClassDB::bind_method(D_METHOD("set_font_data", "data:DynamicFontData"), &DynamicFont::set_font_data);
+ ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"), &DynamicFont::get_font_data);
+
+ ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
+
+ ClassDB::bind_method(D_METHOD("set_use_mipmaps", "enable"), &DynamicFont::set_use_mipmaps);
+ ClassDB::bind_method(D_METHOD("get_use_mipmaps"), &DynamicFont::get_use_mipmaps);
+ ClassDB::bind_method(D_METHOD("set_use_filter", "enable"), &DynamicFont::set_use_filter);
+ ClassDB::bind_method(D_METHOD("get_use_filter"), &DynamicFont::get_use_filter);
+ ClassDB::bind_method(D_METHOD("set_spacing", "type", "value"), &DynamicFont::set_spacing);
+ ClassDB::bind_method(D_METHOD("get_spacing", "type"), &DynamicFont::get_spacing);
+
+ ClassDB::bind_method(D_METHOD("add_fallback", "data:DynamicFontData"), &DynamicFont::add_fallback);
+ ClassDB::bind_method(D_METHOD("set_fallback", "idx", "data:DynamicFontData"), &DynamicFont::set_fallback);
+ ClassDB::bind_method(D_METHOD("get_fallback:DynamicFontData", "idx"), &DynamicFont::get_fallback);
+ ClassDB::bind_method(D_METHOD("remove_fallback", "idx"), &DynamicFont::remove_fallback);
+ ClassDB::bind_method(D_METHOD("get_fallback_count"), &DynamicFont::get_fallback_count);
+
+ ADD_GROUP("Settings", "");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "size"), "set_size", "get_size");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_mipmaps"), "set_use_mipmaps", "get_use_mipmaps");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_filter"), "set_use_filter", "get_use_filter");
+ ADD_GROUP("Extra Spacing", "extra_spacing");
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_top"), "set_spacing", "get_spacing", SPACING_TOP);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_bottom"), "set_spacing", "get_spacing", SPACING_BOTTOM);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_char"), "set_spacing", "get_spacing", SPACING_CHAR);
+ ADD_PROPERTYINZ(PropertyInfo(Variant::INT, "extra_spacing_space"), "set_spacing", "get_spacing", SPACING_SPACE);
+ ADD_GROUP("Font", "");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font_data", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
+
+ BIND_CONSTANT(SPACING_TOP);
+ BIND_CONSTANT(SPACING_BOTTOM);
+ BIND_CONSTANT(SPACING_CHAR);
+ BIND_CONSTANT(SPACING_SPACE);
}
DynamicFont::DynamicFont() {
- spacing_top=0;
- spacing_bottom=0;
- spacing_char=0;
- spacing_space=0;
+ spacing_top = 0;
+ spacing_bottom = 0;
+ spacing_char = 0;
+ spacing_space = 0;
}
DynamicFont::~DynamicFont() {
-
}
/////////////////////////
-
-RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_FILE_CANT_OPEN;
+ *r_error = ERR_FILE_CANT_OPEN;
Ref<DynamicFontData> dfont;
dfont.instance();
dfont->set_font_path(p_path);
-
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return dfont;
}
@@ -954,18 +907,17 @@ void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_
p_extensions->push_back("otf");
}
-bool ResourceFormatLoaderDynamicFont::handles_type(const String& p_type) const {
+bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
- return (p_type=="DynamicFontData");
+ return (p_type == "DynamicFontData");
}
String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
String el = p_path.get_extension().to_lower();
- if (el=="ttf" || el=="otf")
+ if (el == "ttf" || el == "otf")
return "DynamicFontData";
return "";
}
-
#endif
diff --git a/scene/resources/dynamic_font.h b/scene/resources/dynamic_font.h
index 321ec7e332..9502943909 100644
--- a/scene/resources/dynamic_font.h
+++ b/scene/resources/dynamic_font.h
@@ -30,54 +30,55 @@
#define DYNAMIC_FONT_H
#ifdef FREETYPE_ENABLED
-#include "scene/resources/font.h"
-#include "os/thread_safe.h"
#include "io/resource_loader.h"
+#include "os/thread_safe.h"
+#include "scene/resources/font.h"
#include <ft2build.h>
#include FT_FREETYPE_H
-
class DynamicFontAtSize;
class DynamicFont;
class DynamicFontData : public Resource {
- GDCLASS(DynamicFontData,Resource);
+ GDCLASS(DynamicFontData, Resource);
public:
-
- struct CacheID{
+ struct CacheID {
int size;
bool mipmaps;
bool filter;
- bool operator< (CacheID right) const;
- CacheID() { size=16; mipmaps=false; filter=false; }
+ bool operator<(CacheID right) const;
+ CacheID() {
+ size = 16;
+ mipmaps = false;
+ filter = false;
+ }
};
private:
-
const uint8_t *font_mem;
int font_mem_size;
bool force_autohinter;
String font_path;
- Map<CacheID,DynamicFontAtSize*> size_cache;
+ Map<CacheID, DynamicFontAtSize *> size_cache;
friend class DynamicFontAtSize;
-friend class DynamicFont;
+ friend class DynamicFont;
Ref<DynamicFontAtSize> _get_dynamic_font_at_size(CacheID p_cache);
-protected:
+protected:
static void _bind_methods();
-public:
- void set_font_ptr(const uint8_t* p_font_mem,int p_font_mem_size);
- void set_font_path(const String& p_path);
+public:
+ void set_font_ptr(const uint8_t *p_font_mem, int p_font_mem_size);
+ void set_font_path(const String &p_path);
String get_font_path() const;
void set_force_autohinter(bool p_force);
@@ -85,15 +86,14 @@ public:
~DynamicFontData();
};
-
class DynamicFontAtSize : public Reference {
- GDCLASS(DynamicFontAtSize,Reference)
+ GDCLASS(DynamicFontAtSize, Reference)
_THREAD_SAFE_CLASS_
- FT_Library library; /* handle to library */
- FT_Face face; /* handle to face object */
+ FT_Library library; /* handle to library */
+ FT_Face face; /* handle to face object */
FT_StreamRec stream;
int ascent;
@@ -124,39 +124,35 @@ class DynamicFontAtSize : public Reference {
float h_align;
float advance;
- Character() { texture_idx=0; v_align=0; }
+ Character() {
+ texture_idx = 0;
+ v_align = 0;
+ }
};
+ static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char *buffer, unsigned long count);
+ static void _ft_stream_close(FT_Stream stream);
- static unsigned long _ft_stream_io(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count );
- static void _ft_stream_close(FT_Stream stream);
-
- HashMap< CharType, Character > char_map;
+ HashMap<CharType, Character> char_map;
_FORCE_INLINE_ void _update_char(CharType p_char);
-friend class DynamicFontData;
+ friend class DynamicFontData;
Ref<DynamicFontData> font;
DynamicFontData::CacheID id;
-
-
Error _load();
-protected:
-
-
+protected:
public:
-
-
float get_height() const;
float get_ascent() const;
float get_descent() const;
- Size2 get_char_size(CharType p_char,CharType p_next,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const;
+ Size2 get_char_size(CharType p_char, CharType p_next, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const;
- float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate,const Vector<Ref<DynamicFontAtSize> >& p_fallbacks) const;
+ float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate, const Vector<Ref<DynamicFontAtSize> > &p_fallbacks) const;
void set_texture_flags(uint32_t p_flags);
@@ -168,11 +164,10 @@ public:
class DynamicFont : public Font {
- GDCLASS( DynamicFont, Font );
+ GDCLASS(DynamicFont, Font);
public:
-
- enum SpacingType{
+ enum SpacingType {
SPACING_TOP,
SPACING_BOTTOM,
SPACING_CHAR,
@@ -180,13 +175,11 @@ public:
};
private:
-
Ref<DynamicFontData> data;
Ref<DynamicFontAtSize> data_at_size;
- Vector< Ref<DynamicFontData> > fallbacks;
- Vector< Ref<DynamicFontAtSize> > fallback_data_at_size;
-
+ Vector<Ref<DynamicFontData> > fallbacks;
+ Vector<Ref<DynamicFontAtSize> > fallback_data_at_size;
DynamicFontData::CacheID cache_id;
bool valid;
@@ -196,18 +189,16 @@ private:
int spacing_space;
protected:
-
void _reload_cache();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
- void set_font_data(const Ref<DynamicFontData>& p_data);
+ void set_font_data(const Ref<DynamicFontData> &p_data);
Ref<DynamicFontData> get_font_data() const;
void set_size(int p_size);
@@ -222,8 +213,8 @@ public:
int get_spacing(int p_type) const;
void set_spacing(int p_type, int p_value);
- void add_fallback(const Ref<DynamicFontData>& p_data);
- void set_fallback(int p_idx,const Ref<DynamicFontData>& p_data);
+ void add_fallback(const Ref<DynamicFontData> &p_data);
+ void set_fallback(int p_idx, const Ref<DynamicFontData> &p_data);
int get_fallback_count() const;
Ref<DynamicFontData> get_fallback(int p_idx) const;
void remove_fallback(int p_idx);
@@ -233,32 +224,26 @@ public:
virtual float get_ascent() const;
virtual float get_descent() const;
- virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const;
+ virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const;
virtual bool is_distance_field_hint() const;
- virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const;
+ virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const;
DynamicFont();
~DynamicFont();
-
};
-
-
/////////////
class ResourceFormatLoaderDynamicFont : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
-
#endif
#endif
diff --git a/scene/resources/dynamic_font_stb.cpp b/scene/resources/dynamic_font_stb.cpp
index 2d659a7e97..7b62ccc369 100644
--- a/scene/resources/dynamic_font_stb.cpp
+++ b/scene/resources/dynamic_font_stb.cpp
@@ -31,24 +31,24 @@
#ifndef FREETYPE_ENABLED
#define STB_TRUETYPE_IMPLEMENTATION
-#include "stb_truetype.h"
#include "os/file_access.h"
+#include "stb_truetype.h"
void DynamicFontData::lock() {
- fr=font_data.read();
+ fr = font_data.read();
- if (fr.ptr()!=last_data_ptr) {
+ if (fr.ptr() != last_data_ptr) {
- last_data_ptr=fr.ptr();
+ last_data_ptr = fr.ptr();
if (!stbtt_InitFont(&info, last_data_ptr, 0)) {
- valid=false;
+ valid = false;
} else {
- valid=true;
+ valid = true;
}
- last_data_ptr=fr.ptr();
+ last_data_ptr = fr.ptr();
}
}
@@ -57,26 +57,26 @@ void DynamicFontData::unlock() {
fr = PoolVector<uint8_t>::Read();
}
-void DynamicFontData::set_font_data(const PoolVector<uint8_t>& p_font) {
+void DynamicFontData::set_font_data(const PoolVector<uint8_t> &p_font) {
//clear caches and stuff
- ERR_FAIL_COND(font_data.size()) ;
- font_data=p_font;
+ ERR_FAIL_COND(font_data.size());
+ font_data = p_font;
lock();
if (valid) {
stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap);
- descent=-descent + linegap;
+ descent = -descent + linegap;
- for(int i=32;i<1024;i++) {
- for(int j=32;j<1024;j++) {
+ for (int i = 32; i < 1024; i++) {
+ for (int j = 32; j < 1024; j++) {
- int kern = stbtt_GetCodepointKernAdvance(&info, i,j);
- if (kern!=0) {
+ int kern = stbtt_GetCodepointKernAdvance(&info, i, j);
+ if (kern != 0) {
KerningPairKey kpk;
- kpk.A=i;
- kpk.B=j;
- kerning_map[kpk]=kern;
+ kpk.A = i;
+ kpk.B = j;
+ kerning_map[kpk] = kern;
}
}
}
@@ -90,21 +90,20 @@ void DynamicFontData::set_font_data(const PoolVector<uint8_t>& p_font) {
Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) {
- ERR_FAIL_COND_V(!valid,Ref<DynamicFontAtSize>());
+ ERR_FAIL_COND_V(!valid, Ref<DynamicFontAtSize>());
if (size_cache.has(p_size)) {
- return Ref<DynamicFontAtSize>( size_cache[p_size] );
+ return Ref<DynamicFontAtSize>(size_cache[p_size]);
}
-
Ref<DynamicFontAtSize> dfas;
dfas.instance();
- dfas->font=Ref<DynamicFontData>( this );
+ dfas->font = Ref<DynamicFontData>(this);
- size_cache[p_size]=dfas.ptr();
+ size_cache[p_size] = dfas.ptr();
- dfas->size=p_size;
+ dfas->size = p_size;
lock();
@@ -113,100 +112,90 @@ Ref<DynamicFontAtSize> DynamicFontData::_get_dynamic_font_at_size(int p_size) {
unlock();
return dfas;
-
}
-DynamicFontData::DynamicFontData()
-{
- last_data_ptr=NULL;
- valid=false;
+DynamicFontData::DynamicFontData() {
+ last_data_ptr = NULL;
+ valid = false;
}
-DynamicFontData::~DynamicFontData()
-{
-
+DynamicFontData::~DynamicFontData() {
}
-
-
////////////////////
float DynamicFontAtSize::get_height() const {
- return (font->ascent+font->descent)*scale;
+ return (font->ascent + font->descent) * scale;
}
float DynamicFontAtSize::get_ascent() const {
- return font->ascent*scale;
+ return font->ascent * scale;
}
float DynamicFontAtSize::get_descent() const {
- return font->descent*scale;
+ return font->descent * scale;
}
-Size2 DynamicFontAtSize::get_char_size(CharType p_char,CharType p_next) const {
+Size2 DynamicFontAtSize::get_char_size(CharType p_char, CharType p_next) const {
- const_cast<DynamicFontAtSize*>(this)->_update_char(p_char);
+ const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
const Character *c = char_map.getptr(p_char);
- ERR_FAIL_COND_V(!c,Size2());
+ ERR_FAIL_COND_V(!c, Size2());
- Size2 ret( c->advance, get_height());
+ Size2 ret(c->advance, get_height());
if (p_next) {
DynamicFontData::KerningPairKey kpk;
- kpk.A=p_char;
- kpk.B=p_next;
+ kpk.A = p_char;
+ kpk.B = p_next;
- const Map<DynamicFontData::KerningPairKey,int>::Element *K=font->kerning_map.find(kpk);
+ const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
if (K) {
- ret.x+=K->get()*scale;
+ ret.x += K->get() * scale;
}
-
}
return ret;
}
+float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
-float DynamicFontAtSize::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const {
+ const_cast<DynamicFontAtSize *>(this)->_update_char(p_char);
- const_cast<DynamicFontAtSize*>(this)->_update_char(p_char);
-
- const Character * c = char_map.getptr(p_char);
+ const Character *c = char_map.getptr(p_char);
if (!c) {
return 0;
}
- Point2 cpos=p_pos;
- cpos.x+=c->h_align;
- cpos.y-=get_ascent();
- cpos.y+=c->v_align;
- ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0);
- if (c->texture_idx!=-1)
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx].texture->get_rid(),c->rect, p_modulate );
+ Point2 cpos = p_pos;
+ cpos.x += c->h_align;
+ cpos.y -= get_ascent();
+ cpos.y += c->v_align;
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
+ if (c->texture_idx != -1)
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx].texture->get_rid(), c->rect, p_modulate);
//textures[c->texture_idx].texture->draw(p_canvas_item,Vector2());
float ret = c->advance;
if (p_next) {
DynamicFontData::KerningPairKey kpk;
- kpk.A=p_char;
- kpk.B=p_next;
+ kpk.A = p_char;
+ kpk.B = p_next;
- const Map<DynamicFontData::KerningPairKey,int>::Element *K=font->kerning_map.find(kpk);
+ const Map<DynamicFontData::KerningPairKey, int>::Element *K = font->kerning_map.find(kpk);
if (K) {
- ret+=K->get()*scale;
+ ret += K->get() * scale;
}
-
}
return ret;
}
-
void DynamicFontAtSize::_update_char(CharType p_char) {
if (char_map.has(p_char))
@@ -214,9 +203,8 @@ void DynamicFontAtSize::_update_char(CharType p_char) {
font->lock();
-
- int w,h,xofs,yofs;
- unsigned char * cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs );
+ int w, h, xofs, yofs;
+ unsigned char *cpbitmap = stbtt_GetCodepointBitmap(&font->info, scale, scale, p_char, &w, &h, &xofs, &yofs);
if (!cpbitmap) {
//no glyph
@@ -225,123 +213,120 @@ void DynamicFontAtSize::_update_char(CharType p_char) {
stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
//print_line("char has no bitmap: "+itos(p_char)+" but advance is "+itos(advance*scale));
Character ch;
- ch.texture_idx=-1;
- ch.advance=advance*scale;
- ch.h_align=0;
- ch.v_align=0;
+ ch.texture_idx = -1;
+ ch.advance = advance * scale;
+ ch.h_align = 0;
+ ch.v_align = 0;
- char_map[p_char]=ch;
+ char_map[p_char] = ch;
font->unlock();
return;
}
- int mw=w+rect_margin*2;
- int mh=h+rect_margin*2;
+ int mw = w + rect_margin * 2;
+ int mh = h + rect_margin * 2;
- if (mw>4096 || mh>4096) {
+ if (mw > 4096 || mh > 4096) {
- stbtt_FreeBitmap(cpbitmap,NULL);
+ stbtt_FreeBitmap(cpbitmap, NULL);
font->unlock();
- ERR_FAIL_COND(mw>4096);
- ERR_FAIL_COND(mh>4096);
+ ERR_FAIL_COND(mw > 4096);
+ ERR_FAIL_COND(mh > 4096);
}
//find a texture to fit this...
- int tex_index=-1;
- int tex_x=0;
- int tex_y=0;
+ int tex_index = -1;
+ int tex_x = 0;
+ int tex_y = 0;
- for(int i=0;i<textures.size();i++) {
+ for (int i = 0; i < textures.size(); i++) {
- CharTexture &ct=textures[i];
+ CharTexture &ct = textures[i];
if (mw > ct.texture_size || mh > ct.texture_size) //too big for this texture
continue;
- tex_y=0x7FFFFFFF;
- tex_x=0;
+ tex_y = 0x7FFFFFFF;
+ tex_x = 0;
- for(int j=0;j<ct.texture_size-mw;j++) {
+ for (int j = 0; j < ct.texture_size - mw; j++) {
- int max_y=0;
+ int max_y = 0;
- for(int k=j;k<j+mw;k++) {
+ for (int k = j; k < j + mw; k++) {
int y = ct.offsets[k];
- if (y>max_y)
- max_y=y;
+ if (y > max_y)
+ max_y = y;
}
- if (max_y<tex_y) {
- tex_y=max_y;
- tex_x=j;
+ if (max_y < tex_y) {
+ tex_y = max_y;
+ tex_x = j;
}
}
- if (tex_y==0x7FFFFFFF || tex_y+mh > ct.texture_size)
+ if (tex_y == 0x7FFFFFFF || tex_y + mh > ct.texture_size)
continue; //fail, could not fit it here
- tex_index=i;
+ tex_index = i;
break;
}
//print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" X: "+itos(tex_x)+" Y: "+itos(tex_y));
- if (tex_index==-1) {
+ if (tex_index == -1) {
//could not find texture to fit, create one
tex_x = 0;
tex_y = 0;
- int texsize = MAX(size*8,256);
- if (mw>texsize)
- texsize=mw; //special case, adapt to it?
- if (mh>texsize)
- texsize=mh; //special case, adapt to it?
-
- texsize=nearest_power_of_2(texsize);
+ int texsize = MAX(size * 8, 256);
+ if (mw > texsize)
+ texsize = mw; //special case, adapt to it?
+ if (mh > texsize)
+ texsize = mh; //special case, adapt to it?
- texsize=MIN(texsize,4096);
+ texsize = nearest_power_of_2(texsize);
+ texsize = MIN(texsize, 4096);
CharTexture tex;
- tex.texture_size=texsize;
- tex.imgdata.resize(texsize*texsize*2); //grayscale alpha
+ tex.texture_size = texsize;
+ tex.imgdata.resize(texsize * texsize * 2); //grayscale alpha
{
//zero texture
PoolVector<uint8_t>::Write w = tex.imgdata.write();
- ERR_FAIL_COND(texsize*texsize*2 > tex.imgdata.size());
- for(int i=0;i<texsize*texsize*2;i++) {
- w[i]=0;
+ ERR_FAIL_COND(texsize * texsize * 2 > tex.imgdata.size());
+ for (int i = 0; i < texsize * texsize * 2; i++) {
+ w[i] = 0;
}
}
tex.offsets.resize(texsize);
- for(int i=0;i<texsize;i++) //zero offsets
- tex.offsets[i]=0;
+ for (int i = 0; i < texsize; i++) //zero offsets
+ tex.offsets[i] = 0;
textures.push_back(tex);
- tex_index=textures.size()-1;
-
+ tex_index = textures.size() - 1;
}
-
//fit character in char texture
- CharTexture &tex=textures[tex_index];
+ CharTexture &tex = textures[tex_index];
{
PoolVector<uint8_t>::Write wr = tex.imgdata.write();
- for(int i=0;i<h;i++) {
- for(int j=0;j<w;j++) {
+ for (int i = 0; i < h; i++) {
+ for (int j = 0; j < w; j++) {
- int ofs = ( (i+tex_y+rect_margin)*tex.texture_size+j+tex_x+rect_margin)*2;
+ int ofs = ((i + tex_y + rect_margin) * tex.texture_size + j + tex_x + rect_margin) * 2;
ERR_FAIL_COND(ofs >= tex.imgdata.size());
- wr[ofs+0]=255; //grayscale as 1
- wr[ofs+1]=cpbitmap[i*w+j]; //alpha as 0
+ wr[ofs + 0] = 255; //grayscale as 1
+ wr[ofs + 1] = cpbitmap[i * w + j]; //alpha as 0
}
}
}
@@ -349,53 +334,49 @@ void DynamicFontAtSize::_update_char(CharType p_char) {
//blit to image and texture
{
- Image img(tex.texture_size,tex.texture_size,0,Image::FORMAT_LA8,tex.imgdata);
+ Image img(tex.texture_size, tex.texture_size, 0, Image::FORMAT_LA8, tex.imgdata);
if (tex.texture.is_null()) {
tex.texture.instance();
- tex.texture->create_from_image(img,Texture::FLAG_FILTER);
+ tex.texture->create_from_image(img, Texture::FLAG_FILTER);
} else {
tex.texture->set_data(img); //update
}
-
}
-
// update height array
- for(int k=tex_x;k<tex_x+mw;k++) {
+ for (int k = tex_x; k < tex_x + mw; k++) {
- tex.offsets[k]=tex_y+mh;
+ tex.offsets[k] = tex_y + mh;
}
int advance;
stbtt_GetCodepointHMetrics(&font->info, p_char, &advance, 0);
Character chr;
- chr.h_align=xofs;
- chr.v_align=yofs + get_ascent();
- chr.advance=advance*scale;
- chr.texture_idx=tex_index;
+ chr.h_align = xofs;
+ chr.v_align = yofs + get_ascent();
+ chr.advance = advance * scale;
+ chr.texture_idx = tex_index;
-
- chr.rect=Rect2(tex_x+rect_margin,tex_y+rect_margin,w,h);
+ chr.rect = Rect2(tex_x + rect_margin, tex_y + rect_margin, w, h);
//print_line("CHAR: "+String::chr(p_char)+" TEX INDEX: "+itos(tex_index)+" RECT: "+chr.rect+" X OFS: "+itos(xofs)+" Y OFS: "+itos(yofs));
- char_map[p_char]=chr;
+ char_map[p_char] = chr;
- stbtt_FreeBitmap(cpbitmap,NULL);
+ stbtt_FreeBitmap(cpbitmap, NULL);
font->unlock();
-
}
DynamicFontAtSize::DynamicFontAtSize() {
- rect_margin=1;
+ rect_margin = 1;
}
-DynamicFontAtSize::~DynamicFontAtSize(){
+DynamicFontAtSize::~DynamicFontAtSize() {
ERR_FAIL_COND(!font.ptr());
font->size_cache.erase(size);
@@ -403,48 +384,45 @@ DynamicFontAtSize::~DynamicFontAtSize(){
/////////////////////////
-
void DynamicFont::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_font_data","data:DynamicFontData"),&DynamicFont::set_font_data);
- ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"),&DynamicFont::get_font_data);
+ ClassDB::bind_method(D_METHOD("set_font_data", "data:DynamicFontData"), &DynamicFont::set_font_data);
+ ClassDB::bind_method(D_METHOD("get_font_data:DynamicFontData"), &DynamicFont::get_font_data);
- ClassDB::bind_method(D_METHOD("set_size","data"),&DynamicFont::set_size);
- ClassDB::bind_method(D_METHOD("get_size"),&DynamicFont::get_size);
+ ClassDB::bind_method(D_METHOD("set_size", "data"), &DynamicFont::set_size);
+ ClassDB::bind_method(D_METHOD("get_size"), &DynamicFont::get_size);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"font/size"),"set_size","get_size");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"font/font",PROPERTY_HINT_RESOURCE_TYPE,"DynamicFontData"),"set_font_data","get_font_data");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "font/size"), "set_size", "get_size");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "font/font", PROPERTY_HINT_RESOURCE_TYPE, "DynamicFontData"), "set_font_data", "get_font_data");
}
+void DynamicFont::set_font_data(const Ref<DynamicFontData> &p_data) {
-void DynamicFont::set_font_data(const Ref<DynamicFontData>& p_data) {
-
- data=p_data;
- data_at_size=data->_get_dynamic_font_at_size(size);
+ data = p_data;
+ data_at_size = data->_get_dynamic_font_at_size(size);
}
-Ref<DynamicFontData> DynamicFont::get_font_data() const{
+Ref<DynamicFontData> DynamicFont::get_font_data() const {
return data;
}
-void DynamicFont::set_size(int p_size){
+void DynamicFont::set_size(int p_size) {
- if (size==p_size)
+ if (size == p_size)
return;
- size=p_size;
- ERR_FAIL_COND(p_size<1);
+ size = p_size;
+ ERR_FAIL_COND(p_size < 1);
if (!data.is_valid())
return;
- data_at_size=data->_get_dynamic_font_at_size(size);
-
+ data_at_size = data->_get_dynamic_font_at_size(size);
}
-int DynamicFont::get_size() const{
+int DynamicFont::get_size() const {
return size;
}
-float DynamicFont::get_height() const{
+float DynamicFont::get_height() const {
if (!data_at_size.is_valid())
return 1;
@@ -452,7 +430,7 @@ float DynamicFont::get_height() const{
return data_at_size->get_height();
}
-float DynamicFont::get_ascent() const{
+float DynamicFont::get_ascent() const {
if (!data_at_size.is_valid())
return 1;
@@ -460,68 +438,62 @@ float DynamicFont::get_ascent() const{
return data_at_size->get_ascent();
}
-float DynamicFont::get_descent() const{
+float DynamicFont::get_descent() const {
if (!data_at_size.is_valid())
return 1;
return data_at_size->get_descent();
-
}
-Size2 DynamicFont::get_char_size(CharType p_char,CharType p_next) const{
+Size2 DynamicFont::get_char_size(CharType p_char, CharType p_next) const {
if (!data_at_size.is_valid())
- return Size2(1,1);
-
- return data_at_size->get_char_size(p_char,p_next);
+ return Size2(1, 1);
+ return data_at_size->get_char_size(p_char, p_next);
}
-bool DynamicFont::is_distance_field_hint() const{
+bool DynamicFont::is_distance_field_hint() const {
return false;
}
-float DynamicFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next,const Color& p_modulate) const {
+float DynamicFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
if (!data_at_size.is_valid())
return 0;
- return data_at_size->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate);
-
+ return data_at_size->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate);
}
DynamicFont::DynamicFont() {
- size=16;
+ size = 16;
}
DynamicFont::~DynamicFont() {
-
}
/////////////////////////
-
-RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_FILE_CANT_OPEN;
-
+ *r_error = ERR_FILE_CANT_OPEN;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
- ERR_FAIL_COND_V(!f,RES());
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, RES());
PoolVector<uint8_t> data;
data.resize(f->get_len());
- ERR_FAIL_COND_V(data.size()==0,RES());
+ ERR_FAIL_COND_V(data.size() == 0, RES());
{
PoolVector<uint8_t>::Write w = data.write();
- f->get_buffer(w.ptr(),data.size());
+ f->get_buffer(w.ptr(), data.size());
}
Ref<DynamicFontData> dfd;
@@ -529,7 +501,7 @@ RES ResourceFormatLoaderDynamicFont::load(const String &p_path, const String& p_
dfd->set_font_data(data);
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return dfd;
}
@@ -539,15 +511,15 @@ void ResourceFormatLoaderDynamicFont::get_recognized_extensions(List<String> *p_
p_extensions->push_back("ttf");
}
-bool ResourceFormatLoaderDynamicFont::handles_type(const String& p_type) const {
+bool ResourceFormatLoaderDynamicFont::handles_type(const String &p_type) const {
- return (p_type=="DynamicFontData");
+ return (p_type == "DynamicFontData");
}
String ResourceFormatLoaderDynamicFont::get_resource_type(const String &p_path) const {
String el = p_path.extension().to_lower();
- if (el=="ttf")
+ if (el == "ttf")
return "DynamicFontData";
return "";
}
diff --git a/scene/resources/dynamic_font_stb.h b/scene/resources/dynamic_font_stb.h
index 4eb0575d8e..0c17e3a8b3 100644
--- a/scene/resources/dynamic_font_stb.h
+++ b/scene/resources/dynamic_font_stb.h
@@ -32,43 +32,40 @@
#ifndef FREETYPE_ENABLED
#include "font.h"
-#include "stb_truetype.h"
#include "io/resource_loader.h"
-
-
+#include "stb_truetype.h"
class DynamicFontAtSize;
class DynamicFont;
class DynamicFontData : public Resource {
- GDCLASS(DynamicFontData,Resource);
+ GDCLASS(DynamicFontData, Resource);
bool valid;
PoolVector<uint8_t> font_data;
PoolVector<uint8_t>::Read fr;
- const uint8_t* last_data_ptr;
+ const uint8_t *last_data_ptr;
struct KerningPairKey {
union {
struct {
- uint32_t A,B;
+ uint32_t A, B;
};
uint64_t pair;
};
- _FORCE_INLINE_ bool operator<(const KerningPairKey& p_r) const { return pair<p_r.pair; }
+ _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; }
};
- Map<KerningPairKey,int> kerning_map;
+ Map<KerningPairKey, int> kerning_map;
+ Map<int, DynamicFontAtSize *> size_cache;
- Map<int,DynamicFontAtSize*> size_cache;
-
-friend class DynamicFontAtSize;
+ friend class DynamicFontAtSize;
stbtt_fontinfo info;
int ascent;
@@ -78,22 +75,19 @@ friend class DynamicFontAtSize;
void lock();
void unlock();
-friend class DynamicFont;
-
+ friend class DynamicFont;
Ref<DynamicFontAtSize> _get_dynamic_font_at_size(int p_size);
-public:
- void set_font_data(const PoolVector<uint8_t>& p_font);
+public:
+ void set_font_data(const PoolVector<uint8_t> &p_font);
DynamicFontData();
~DynamicFontData();
};
-
class DynamicFontAtSize : public Reference {
- GDCLASS(DynamicFontAtSize,Reference);
-
+ GDCLASS(DynamicFontAtSize, Reference);
int rect_margin;
@@ -115,34 +109,31 @@ class DynamicFontAtSize : public Reference {
float h_align;
float advance;
- Character() { texture_idx=0; v_align=0; }
+ Character() {
+ texture_idx = 0;
+ v_align = 0;
+ }
};
-
-
- HashMap< CharType, Character > char_map;
+ HashMap<CharType, Character> char_map;
_FORCE_INLINE_ void _update_char(CharType p_char);
-friend class DynamicFontData;
+ friend class DynamicFontData;
Ref<DynamicFontData> font;
float scale;
int size;
protected:
-
public:
-
float get_height() const;
float get_ascent() const;
float get_descent() const;
- Size2 get_char_size(CharType p_char,CharType p_next=0) const;
-
- float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const;
-
+ Size2 get_char_size(CharType p_char, CharType p_next = 0) const;
+ float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const;
DynamicFontAtSize();
~DynamicFontAtSize();
@@ -152,20 +143,17 @@ public:
class DynamicFont : public Font {
- GDCLASS( DynamicFont, Font );
+ GDCLASS(DynamicFont, Font);
Ref<DynamicFontData> data;
Ref<DynamicFontAtSize> data_at_size;
int size;
-
protected:
-
static void _bind_methods();
public:
-
- void set_font_data(const Ref<DynamicFontData>& p_data);
+ void set_font_data(const Ref<DynamicFontData> &p_data);
Ref<DynamicFontData> get_font_data() const;
void set_size(int p_size);
@@ -176,31 +164,25 @@ public:
virtual float get_ascent() const;
virtual float get_descent() const;
- virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const;
+ virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const;
virtual bool is_distance_field_hint() const;
- virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const;
+ virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const;
DynamicFont();
~DynamicFont();
-
};
-
-
/////////////
class ResourceFormatLoaderDynamicFont : public ResourceFormatLoader {
public:
-
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
-
#endif
#endif // DYNAMICFONT_H
diff --git a/scene/resources/environment.cpp b/scene/resources/environment.cpp
index f44b37f6f5..b134d8052b 100644
--- a/scene/resources/environment.cpp
+++ b/scene/resources/environment.cpp
@@ -27,76 +27,75 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "environment.h"
-#include "texture.h"
#include "global_config.h"
#include "servers/visual_server.h"
+#include "texture.h"
RID Environment::get_rid() const {
return environment;
}
-
void Environment::set_background(BGMode p_bg) {
- bg_mode=p_bg;
- VS::get_singleton()->environment_set_background(environment,VS::EnvironmentBG(p_bg));
+ bg_mode = p_bg;
+ VS::get_singleton()->environment_set_background(environment, VS::EnvironmentBG(p_bg));
_change_notify();
}
-void Environment::set_skybox(const Ref<SkyBox> &p_skybox){
+void Environment::set_skybox(const Ref<SkyBox> &p_skybox) {
- bg_skybox=p_skybox;
+ bg_skybox = p_skybox;
RID sb_rid;
if (bg_skybox.is_valid())
- sb_rid=bg_skybox->get_rid();
+ sb_rid = bg_skybox->get_rid();
- VS::get_singleton()->environment_set_skybox(environment,sb_rid);
+ VS::get_singleton()->environment_set_skybox(environment, sb_rid);
}
void Environment::set_skybox_scale(float p_scale) {
- bg_skybox_scale=p_scale;
- VS::get_singleton()->environment_set_skybox_scale(environment,p_scale);
+ bg_skybox_scale = p_scale;
+ VS::get_singleton()->environment_set_skybox_scale(environment, p_scale);
}
-void Environment::set_bg_color(const Color& p_color){
+void Environment::set_bg_color(const Color &p_color) {
- bg_color=p_color;
- VS::get_singleton()->environment_set_bg_color(environment,p_color);
+ bg_color = p_color;
+ VS::get_singleton()->environment_set_bg_color(environment, p_color);
}
-void Environment::set_bg_energy(float p_energy){
+void Environment::set_bg_energy(float p_energy) {
- bg_energy=p_energy;
- VS::get_singleton()->environment_set_bg_energy(environment,p_energy);
+ bg_energy = p_energy;
+ VS::get_singleton()->environment_set_bg_energy(environment, p_energy);
}
-void Environment::set_canvas_max_layer(int p_max_layer){
+void Environment::set_canvas_max_layer(int p_max_layer) {
- bg_canvas_max_layer=p_max_layer;
- VS::get_singleton()->environment_set_canvas_max_layer(environment,p_max_layer);
+ bg_canvas_max_layer = p_max_layer;
+ VS::get_singleton()->environment_set_canvas_max_layer(environment, p_max_layer);
}
-void Environment::set_ambient_light_color(const Color& p_color){
+void Environment::set_ambient_light_color(const Color &p_color) {
- ambient_color=p_color;
- VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution);
+ ambient_color = p_color;
+ VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution);
}
-void Environment::set_ambient_light_energy(float p_energy){
+void Environment::set_ambient_light_energy(float p_energy) {
- ambient_energy=p_energy;
- VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution);
+ ambient_energy = p_energy;
+ VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution);
}
-void Environment::set_ambient_light_skybox_contribution(float p_energy){
+void Environment::set_ambient_light_skybox_contribution(float p_energy) {
- ambient_skybox_contribution=p_energy;
- VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution);
+ ambient_skybox_contribution = p_energy;
+ VS::get_singleton()->environment_set_ambient_light(environment, ambient_color, ambient_energy, ambient_skybox_contribution);
}
-Environment::BGMode Environment::get_background() const{
+Environment::BGMode Environment::get_background() const {
return bg_mode;
}
-Ref<SkyBox> Environment::get_skybox() const{
+Ref<SkyBox> Environment::get_skybox() const {
return bg_skybox;
}
@@ -106,60 +105,57 @@ float Environment::get_skybox_scale() const {
return bg_skybox_scale;
}
-Color Environment::get_bg_color() const{
+Color Environment::get_bg_color() const {
return bg_color;
}
-float Environment::get_bg_energy() const{
+float Environment::get_bg_energy() const {
return bg_energy;
}
-int Environment::get_canvas_max_layer() const{
+int Environment::get_canvas_max_layer() const {
return bg_canvas_max_layer;
}
-Color Environment::get_ambient_light_color() const{
+Color Environment::get_ambient_light_color() const {
return ambient_color;
}
-float Environment::get_ambient_light_energy() const{
+float Environment::get_ambient_light_energy() const {
return ambient_energy;
}
-float Environment::get_ambient_light_skybox_contribution() const{
+float Environment::get_ambient_light_skybox_contribution() const {
return ambient_skybox_contribution;
}
-
-
void Environment::set_tonemapper(ToneMapper p_tone_mapper) {
- tone_mapper=p_tone_mapper;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
+ tone_mapper = p_tone_mapper;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
-Environment::ToneMapper Environment::get_tonemapper() const{
+Environment::ToneMapper Environment::get_tonemapper() const {
return tone_mapper;
}
-void Environment::set_tonemap_exposure(float p_exposure){
+void Environment::set_tonemap_exposure(float p_exposure) {
- tonemap_exposure=p_exposure;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
+ tonemap_exposure = p_exposure;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
-float Environment::get_tonemap_exposure() const{
+float Environment::get_tonemap_exposure() const {
return tonemap_exposure;
}
-void Environment::set_tonemap_white(float p_white){
-
- tonemap_white=p_white;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
+void Environment::set_tonemap_white(float p_white) {
+ tonemap_white = p_white;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
float Environment::get_tonemap_white() const {
@@ -168,9 +164,8 @@ float Environment::get_tonemap_white() const {
void Environment::set_tonemap_auto_exposure(bool p_enabled) {
- tonemap_auto_exposure=p_enabled;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
-
+ tonemap_auto_exposure = p_enabled;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
bool Environment::get_tonemap_auto_exposure() const {
@@ -179,9 +174,8 @@ bool Environment::get_tonemap_auto_exposure() const {
void Environment::set_tonemap_auto_exposure_max(float p_auto_exposure_max) {
- tonemap_auto_exposure_max=p_auto_exposure_max;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
-
+ tonemap_auto_exposure_max = p_auto_exposure_max;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
float Environment::get_tonemap_auto_exposure_max() const {
@@ -190,9 +184,8 @@ float Environment::get_tonemap_auto_exposure_max() const {
void Environment::set_tonemap_auto_exposure_min(float p_auto_exposure_min) {
- tonemap_auto_exposure_min=p_auto_exposure_min;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
-
+ tonemap_auto_exposure_min = p_auto_exposure_min;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
float Environment::get_tonemap_auto_exposure_min() const {
@@ -201,9 +194,8 @@ float Environment::get_tonemap_auto_exposure_min() const {
void Environment::set_tonemap_auto_exposure_speed(float p_auto_exposure_speed) {
- tonemap_auto_exposure_speed=p_auto_exposure_speed;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
-
+ tonemap_auto_exposure_speed = p_auto_exposure_speed;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
float Environment::get_tonemap_auto_exposure_speed() const {
@@ -212,9 +204,8 @@ float Environment::get_tonemap_auto_exposure_speed() const {
void Environment::set_tonemap_auto_exposure_grey(float p_auto_exposure_grey) {
- tonemap_auto_exposure_grey=p_auto_exposure_grey;
- VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey);
-
+ tonemap_auto_exposure_grey = p_auto_exposure_grey;
+ VS::get_singleton()->environment_set_tonemap(environment, VS::EnvironmentToneMapper(tone_mapper), tonemap_exposure, tonemap_white, tonemap_auto_exposure, tonemap_auto_exposure_min, tonemap_auto_exposure_max, tonemap_auto_exposure_speed, tonemap_auto_exposure_grey);
}
float Environment::get_tonemap_auto_exposure_grey() const {
@@ -223,8 +214,8 @@ float Environment::get_tonemap_auto_exposure_grey() const {
void Environment::set_adjustment_enable(bool p_enable) {
- adjustment_enabled=p_enable;
- VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID());
+ adjustment_enabled = p_enable;
+ VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID());
}
bool Environment::is_adjustment_enabled() const {
@@ -232,12 +223,10 @@ bool Environment::is_adjustment_enabled() const {
return adjustment_enabled;
}
-
void Environment::set_adjustment_brightness(float p_brightness) {
- adjustment_brightness=p_brightness;
- VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID());
-
+ adjustment_brightness = p_brightness;
+ VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID());
}
float Environment::get_adjustment_brightness() const {
@@ -246,9 +235,8 @@ float Environment::get_adjustment_brightness() const {
void Environment::set_adjustment_contrast(float p_contrast) {
- adjustment_contrast=p_contrast;
- VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID());
-
+ adjustment_contrast = p_contrast;
+ VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID());
}
float Environment::get_adjustment_contrast() const {
@@ -257,65 +245,60 @@ float Environment::get_adjustment_contrast() const {
void Environment::set_adjustment_saturation(float p_saturation) {
- adjustment_saturation=p_saturation;
- VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID());
-
+ adjustment_saturation = p_saturation;
+ VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID());
}
float Environment::get_adjustment_saturation() const {
return adjustment_saturation;
}
-void Environment::set_adjustment_color_correction(const Ref<Texture>& p_ramp) {
-
- adjustment_color_correction=p_ramp;
- VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID());
+void Environment::set_adjustment_color_correction(const Ref<Texture> &p_ramp) {
+ adjustment_color_correction = p_ramp;
+ VS::get_singleton()->environment_set_adjustment(environment, adjustment_enabled, adjustment_brightness, adjustment_contrast, adjustment_saturation, adjustment_color_correction.is_valid() ? adjustment_color_correction->get_rid() : RID());
}
Ref<Texture> Environment::get_adjustment_color_correction() const {
return adjustment_color_correction;
}
+void Environment::_validate_property(PropertyInfo &property) const {
-void Environment::_validate_property(PropertyInfo& property) const {
-
- if (property.name=="background/skybox" || property.name=="background/skybox_scale" || property.name=="ambient_light/skybox_contribution") {
- if (bg_mode!=BG_SKYBOX) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "background/skybox" || property.name == "background/skybox_scale" || property.name == "ambient_light/skybox_contribution") {
+ if (bg_mode != BG_SKYBOX) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
- if (property.name=="background/color") {
- if (bg_mode!=BG_COLOR) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "background/color") {
+ if (bg_mode != BG_COLOR) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
- if (property.name=="background/canvas_max_layer") {
- if (bg_mode!=BG_CANVAS) {
- property.usage=PROPERTY_USAGE_NOEDITOR;
+ if (property.name == "background/canvas_max_layer") {
+ if (bg_mode != BG_CANVAS) {
+ property.usage = PROPERTY_USAGE_NOEDITOR;
}
}
-
}
void Environment::set_ssr_enabled(bool p_enable) {
- ssr_enabled=p_enable;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
+ ssr_enabled = p_enable;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
-bool Environment::is_ssr_enabled() const{
+bool Environment::is_ssr_enabled() const {
return ssr_enabled;
}
-void Environment::set_ssr_max_steps(int p_steps){
-
- ssr_max_steps=p_steps;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
+void Environment::set_ssr_max_steps(int p_steps) {
+ ssr_max_steps = p_steps;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
int Environment::get_ssr_max_steps() const {
@@ -324,9 +307,8 @@ int Environment::get_ssr_max_steps() const {
void Environment::set_ssr_accel(float p_accel) {
- ssr_accel=p_accel;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
-
+ ssr_accel = p_accel;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
float Environment::get_ssr_accel() const {
@@ -335,9 +317,8 @@ float Environment::get_ssr_accel() const {
void Environment::set_ssr_fade(float p_fade) {
- ssr_fade=p_fade;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
-
+ ssr_fade = p_fade;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
float Environment::get_ssr_fade() const {
@@ -346,9 +327,8 @@ float Environment::get_ssr_fade() const {
void Environment::set_ssr_depth_tolerance(float p_depth_tolerance) {
- ssr_depth_tolerance=p_depth_tolerance;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
-
+ ssr_depth_tolerance = p_depth_tolerance;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
float Environment::get_ssr_depth_tolerance() const {
@@ -357,9 +337,8 @@ float Environment::get_ssr_depth_tolerance() const {
void Environment::set_ssr_smooth(bool p_enable) {
- ssr_smooth=p_enable;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
-
+ ssr_smooth = p_enable;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
bool Environment::is_ssr_smooth() const {
@@ -368,9 +347,8 @@ bool Environment::is_ssr_smooth() const {
void Environment::set_ssr_rough(bool p_enable) {
- ssr_roughness=p_enable;
- VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness);
-
+ ssr_roughness = p_enable;
+ VS::get_singleton()->environment_set_ssr(environment, ssr_enabled, ssr_max_steps, ssr_accel, ssr_fade, ssr_depth_tolerance, ssr_smooth, ssr_roughness);
}
bool Environment::is_ssr_rough() const {
@@ -379,84 +357,80 @@ bool Environment::is_ssr_rough() const {
void Environment::set_ssao_enabled(bool p_enable) {
- ssao_enabled=p_enable;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
-
+ ssao_enabled = p_enable;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-bool Environment::is_ssao_enabled() const{
+bool Environment::is_ssao_enabled() const {
return ssao_enabled;
}
-void Environment::set_ssao_radius(float p_radius){
+void Environment::set_ssao_radius(float p_radius) {
- ssao_radius=p_radius;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_radius = p_radius;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_radius() const{
+float Environment::get_ssao_radius() const {
return ssao_radius;
}
+void Environment::set_ssao_intensity(float p_intensity) {
-void Environment::set_ssao_intensity(float p_intensity){
-
- ssao_intensity=p_intensity;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_intensity = p_intensity;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_intensity() const{
+float Environment::get_ssao_intensity() const {
return ssao_intensity;
}
-void Environment::set_ssao_radius2(float p_radius){
+void Environment::set_ssao_radius2(float p_radius) {
- ssao_radius2=p_radius;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_radius2 = p_radius;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_radius2() const{
+float Environment::get_ssao_radius2() const {
return ssao_radius2;
}
+void Environment::set_ssao_intensity2(float p_intensity) {
-void Environment::set_ssao_intensity2(float p_intensity){
-
- ssao_intensity2=p_intensity;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_intensity2 = p_intensity;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_intensity2() const{
+float Environment::get_ssao_intensity2() const {
return ssao_intensity2;
}
-void Environment::set_ssao_bias(float p_bias){
+void Environment::set_ssao_bias(float p_bias) {
- ssao_bias=p_bias;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_bias = p_bias;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_bias() const{
+float Environment::get_ssao_bias() const {
return ssao_bias;
}
-void Environment::set_ssao_direct_light_affect(float p_direct_light_affect){
+void Environment::set_ssao_direct_light_affect(float p_direct_light_affect) {
- ssao_direct_light_affect=p_direct_light_affect;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_direct_light_affect = p_direct_light_affect;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
-float Environment::get_ssao_direct_light_affect() const{
+float Environment::get_ssao_direct_light_affect() const {
return ssao_direct_light_affect;
}
+void Environment::set_ssao_color(const Color &p_color) {
-void Environment::set_ssao_color(const Color& p_color) {
-
- ssao_color=p_color;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_color = p_color;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
Color Environment::get_ssao_color() const {
@@ -466,8 +440,8 @@ Color Environment::get_ssao_color() const {
void Environment::set_ssao_blur(bool p_enable) {
- ssao_blur=p_enable;
- VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur);
+ ssao_blur = p_enable;
+ VS::get_singleton()->environment_set_ssao(environment, ssao_enabled, ssao_radius, ssao_intensity, ssao_radius2, ssao_intensity2, ssao_bias, ssao_direct_light_affect, ssao_color, ssao_blur);
}
bool Environment::is_ssao_blur_enabled() const {
@@ -476,110 +450,102 @@ bool Environment::is_ssao_blur_enabled() const {
void Environment::set_glow_enabled(bool p_enabled) {
- glow_enabled=p_enabled;
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_enabled = p_enabled;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-bool Environment::is_glow_enabled() const{
+bool Environment::is_glow_enabled() const {
return glow_enabled;
}
-void Environment::set_glow_level(int p_level,bool p_enabled){
+void Environment::set_glow_level(int p_level, bool p_enabled) {
- ERR_FAIL_INDEX(p_level,VS::MAX_GLOW_LEVELS);
+ ERR_FAIL_INDEX(p_level, VS::MAX_GLOW_LEVELS);
if (p_enabled)
- glow_levels|=(1<<p_level);
+ glow_levels |= (1 << p_level);
else
- glow_levels&=~(1<<p_level);
-
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_levels &= ~(1 << p_level);
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-bool Environment::is_glow_level_enabled(int p_level) const{
+bool Environment::is_glow_level_enabled(int p_level) const {
- ERR_FAIL_INDEX_V(p_level,VS::MAX_GLOW_LEVELS,false);
+ ERR_FAIL_INDEX_V(p_level, VS::MAX_GLOW_LEVELS, false);
- return glow_levels&(1<<p_level);
+ return glow_levels & (1 << p_level);
}
-void Environment::set_glow_intensity(float p_intensity){
+void Environment::set_glow_intensity(float p_intensity) {
- glow_intensity=p_intensity;
-
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_intensity = p_intensity;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-float Environment::get_glow_intensity() const{
+float Environment::get_glow_intensity() const {
return glow_intensity;
}
-void Environment::set_glow_strength(float p_strength){
-
- glow_strength=p_strength;
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+void Environment::set_glow_strength(float p_strength) {
+ glow_strength = p_strength;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-float Environment::get_glow_strength() const{
+float Environment::get_glow_strength() const {
return glow_strength;
}
-void Environment::set_glow_bloom(float p_treshold){
+void Environment::set_glow_bloom(float p_treshold) {
- glow_bloom=p_treshold;
-
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_bloom = p_treshold;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-float Environment::get_glow_bloom() const{
+float Environment::get_glow_bloom() const {
return glow_bloom;
}
-void Environment::set_glow_blend_mode(GlowBlendMode p_mode){
-
- glow_blend_mode=p_mode;
+void Environment::set_glow_blend_mode(GlowBlendMode p_mode) {
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_blend_mode = p_mode;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-Environment::GlowBlendMode Environment::get_glow_blend_mode() const{
+Environment::GlowBlendMode Environment::get_glow_blend_mode() const {
return glow_blend_mode;
}
-void Environment::set_glow_hdr_bleed_treshold(float p_treshold){
+void Environment::set_glow_hdr_bleed_treshold(float p_treshold) {
- glow_hdr_bleed_treshold=p_treshold;
-
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_hdr_bleed_treshold = p_treshold;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-float Environment::get_glow_hdr_bleed_treshold() const{
+float Environment::get_glow_hdr_bleed_treshold() const {
return glow_hdr_bleed_treshold;
}
-void Environment::set_glow_hdr_bleed_scale(float p_scale){
-
- glow_hdr_bleed_scale=p_scale;
+void Environment::set_glow_hdr_bleed_scale(float p_scale) {
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
+ glow_hdr_bleed_scale = p_scale;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
-float Environment::get_glow_hdr_bleed_scale() const{
+float Environment::get_glow_hdr_bleed_scale() const {
return glow_hdr_bleed_scale;
}
void Environment::set_glow_bicubic_upscale(bool p_enable) {
- glow_bicubic_upscale=p_enable;
- VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale);
-
+ glow_bicubic_upscale = p_enable;
+ VS::get_singleton()->environment_set_glow(environment, glow_enabled, glow_levels, glow_intensity, glow_strength, glow_bloom, VS::EnvironmentGlowBlendMode(glow_blend_mode), glow_hdr_bleed_treshold, glow_hdr_bleed_treshold, glow_bicubic_upscale);
}
bool Environment::is_glow_bicubic_upscale_enabled() const {
@@ -587,54 +553,51 @@ bool Environment::is_glow_bicubic_upscale_enabled() const {
return glow_bicubic_upscale;
}
-
void Environment::set_dof_blur_far_enabled(bool p_enable) {
- dof_blur_far_enabled=p_enable;
- VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
+ dof_blur_far_enabled = p_enable;
+ VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
}
-bool Environment::is_dof_blur_far_enabled() const{
+bool Environment::is_dof_blur_far_enabled() const {
return dof_blur_far_enabled;
}
-void Environment::set_dof_blur_far_distance(float p_distance){
-
- dof_blur_far_distance=p_distance;
- VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
+void Environment::set_dof_blur_far_distance(float p_distance) {
+ dof_blur_far_distance = p_distance;
+ VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
}
-float Environment::get_dof_blur_far_distance() const{
+float Environment::get_dof_blur_far_distance() const {
return dof_blur_far_distance;
}
-void Environment::set_dof_blur_far_transition(float p_distance){
+void Environment::set_dof_blur_far_transition(float p_distance) {
- dof_blur_far_transition=p_distance;
- VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
+ dof_blur_far_transition = p_distance;
+ VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
}
-float Environment::get_dof_blur_far_transition() const{
+float Environment::get_dof_blur_far_transition() const {
return dof_blur_far_transition;
}
-void Environment::set_dof_blur_far_amount(float p_amount){
-
- dof_blur_far_amount=p_amount;
- VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
+void Environment::set_dof_blur_far_amount(float p_amount) {
+ dof_blur_far_amount = p_amount;
+ VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
}
-float Environment::get_dof_blur_far_amount() const{
+float Environment::get_dof_blur_far_amount() const {
return dof_blur_far_amount;
}
void Environment::set_dof_blur_far_quality(DOFBlurQuality p_quality) {
- dof_blur_far_quality=p_quality;
- VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
+ dof_blur_far_quality = p_quality;
+ VS::get_singleton()->environment_set_dof_blur_far(environment, dof_blur_far_enabled, dof_blur_far_distance, dof_blur_far_transition, dof_blur_far_amount, VS::EnvironmentDOFBlurQuality(dof_blur_far_quality));
}
Environment::DOFBlurQuality Environment::get_dof_blur_far_quality() const {
@@ -642,55 +605,54 @@ Environment::DOFBlurQuality Environment::get_dof_blur_far_quality() const {
return dof_blur_far_quality;
}
-
void Environment::set_dof_blur_near_enabled(bool p_enable) {
- dof_blur_near_enabled=p_enable;
- VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
+ dof_blur_near_enabled = p_enable;
+ VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
}
-bool Environment::is_dof_blur_near_enabled() const{
+bool Environment::is_dof_blur_near_enabled() const {
return dof_blur_near_enabled;
}
-void Environment::set_dof_blur_near_distance(float p_distance){
+void Environment::set_dof_blur_near_distance(float p_distance) {
- dof_blur_near_distance=p_distance;
- VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
+ dof_blur_near_distance = p_distance;
+ VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
}
-float Environment::get_dof_blur_near_distance() const{
+float Environment::get_dof_blur_near_distance() const {
return dof_blur_near_distance;
}
-void Environment::set_dof_blur_near_transition(float p_distance){
+void Environment::set_dof_blur_near_transition(float p_distance) {
- dof_blur_near_transition=p_distance;
- VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
+ dof_blur_near_transition = p_distance;
+ VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
}
-float Environment::get_dof_blur_near_transition() const{
+float Environment::get_dof_blur_near_transition() const {
return dof_blur_near_transition;
}
-void Environment::set_dof_blur_near_amount(float p_amount){
+void Environment::set_dof_blur_near_amount(float p_amount) {
- dof_blur_near_amount=p_amount;
- VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
+ dof_blur_near_amount = p_amount;
+ VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
}
-float Environment::get_dof_blur_near_amount() const{
+float Environment::get_dof_blur_near_amount() const {
return dof_blur_near_amount;
}
void Environment::set_dof_blur_near_quality(DOFBlurQuality p_quality) {
- dof_blur_near_quality=p_quality;
- VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
+ dof_blur_near_quality = p_quality;
+ VS::get_singleton()->environment_set_dof_blur_near(environment, dof_blur_near_enabled, dof_blur_near_distance, dof_blur_near_transition, dof_blur_near_amount, VS::EnvironmentDOFBlurQuality(dof_blur_near_quality));
}
Environment::DOFBlurQuality Environment::get_dof_blur_near_quality() const {
@@ -698,263 +660,255 @@ Environment::DOFBlurQuality Environment::get_dof_blur_near_quality() const {
return dof_blur_near_quality;
}
-
void Environment::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_background","mode"),&Environment::set_background);
- ClassDB::bind_method(D_METHOD("set_skybox","skybox:CubeMap"),&Environment::set_skybox);
- ClassDB::bind_method(D_METHOD("set_skybox_scale","scale"),&Environment::set_skybox_scale);
- ClassDB::bind_method(D_METHOD("set_bg_color","color"),&Environment::set_bg_color);
- ClassDB::bind_method(D_METHOD("set_bg_energy","energy"),&Environment::set_bg_energy);
- ClassDB::bind_method(D_METHOD("set_canvas_max_layer","layer"),&Environment::set_canvas_max_layer);
- ClassDB::bind_method(D_METHOD("set_ambient_light_color","color"),&Environment::set_ambient_light_color);
- ClassDB::bind_method(D_METHOD("set_ambient_light_energy","energy"),&Environment::set_ambient_light_energy);
- ClassDB::bind_method(D_METHOD("set_ambient_light_skybox_contribution","energy"),&Environment::set_ambient_light_skybox_contribution);
-
-
- ClassDB::bind_method(D_METHOD("get_background"),&Environment::get_background);
- ClassDB::bind_method(D_METHOD("get_skybox:CubeMap"),&Environment::get_skybox);
- ClassDB::bind_method(D_METHOD("get_skybox_scale"),&Environment::get_skybox_scale);
- ClassDB::bind_method(D_METHOD("get_bg_color"),&Environment::get_bg_color);
- ClassDB::bind_method(D_METHOD("get_bg_energy"),&Environment::get_bg_energy);
- ClassDB::bind_method(D_METHOD("get_canvas_max_layer"),&Environment::get_canvas_max_layer);
- ClassDB::bind_method(D_METHOD("get_ambient_light_color"),&Environment::get_ambient_light_color);
- ClassDB::bind_method(D_METHOD("get_ambient_light_energy"),&Environment::get_ambient_light_energy);
- ClassDB::bind_method(D_METHOD("get_ambient_light_skybox_contribution"),&Environment::get_ambient_light_skybox_contribution);
-
-
- ADD_GROUP("Background","background_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"background_mode",PROPERTY_HINT_ENUM,"Clear Color,Custom Color,Skybox,Canvas,Keep"),"set_background","get_background") ;
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"background_skybox",PROPERTY_HINT_RESOURCE_TYPE,"SkyBox"),"set_skybox","get_skybox") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_skybox_scale",PROPERTY_HINT_RANGE,"0,32,0.01"),"set_skybox_scale","get_skybox_scale") ;
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"background_color"),"set_bg_color","get_bg_color") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_bg_energy","get_bg_energy") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"background_canvas_max_layer",PROPERTY_HINT_RANGE,"-1000,1000,1"),"set_canvas_max_layer","get_canvas_max_layer") ;
- ADD_GROUP("Ambient Light","ambient_light_");
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ambient_light_color"),"set_ambient_light_color","get_ambient_light_color") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_ambient_light_energy","get_ambient_light_energy") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_skybox_contribution",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_ambient_light_skybox_contribution","get_ambient_light_skybox_contribution") ;
-
-
- ClassDB::bind_method(D_METHOD("set_ssr_enabled","enabled"),&Environment::set_ssr_enabled);
- ClassDB::bind_method(D_METHOD("is_ssr_enabled"),&Environment::is_ssr_enabled);
-
- ClassDB::bind_method(D_METHOD("set_ssr_max_steps","max_steps"),&Environment::set_ssr_max_steps);
- ClassDB::bind_method(D_METHOD("get_ssr_max_steps"),&Environment::get_ssr_max_steps);
-
- ClassDB::bind_method(D_METHOD("set_ssr_accel","accel"),&Environment::set_ssr_accel);
- ClassDB::bind_method(D_METHOD("get_ssr_accel"),&Environment::get_ssr_accel);
-
- ClassDB::bind_method(D_METHOD("set_ssr_fade","fade"),&Environment::set_ssr_fade);
- ClassDB::bind_method(D_METHOD("get_ssr_fade"),&Environment::get_ssr_fade);
-
- ClassDB::bind_method(D_METHOD("set_ssr_depth_tolerance","depth_tolerance"),&Environment::set_ssr_depth_tolerance);
- ClassDB::bind_method(D_METHOD("get_ssr_depth_tolerance"),&Environment::get_ssr_depth_tolerance);
-
- ClassDB::bind_method(D_METHOD("set_ssr_smooth","smooth"),&Environment::set_ssr_smooth);
- ClassDB::bind_method(D_METHOD("is_ssr_smooth"),&Environment::is_ssr_smooth);
-
- ClassDB::bind_method(D_METHOD("set_ssr_rough","rough"),&Environment::set_ssr_rough);
- ClassDB::bind_method(D_METHOD("is_ssr_rough"),&Environment::is_ssr_rough);
-
- ADD_GROUP("SS Reflections","ss_reflections_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_enabled"),"set_ssr_enabled","is_ssr_enabled") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"ss_reflections_max_steps",PROPERTY_HINT_RANGE,"1,512,1"),"set_ssr_max_steps","get_ssr_max_steps") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_accel",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_ssr_accel","get_ssr_accel") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_fade",PROPERTY_HINT_EXP_EASING),"set_ssr_fade","get_ssr_fade") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_depth_tolerance",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_ssr_depth_tolerance","get_ssr_depth_tolerance") ;
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_accel_smooth"),"set_ssr_smooth","is_ssr_smooth") ;
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_roughness"),"set_ssr_rough","is_ssr_rough") ;
+ ClassDB::bind_method(D_METHOD("set_background", "mode"), &Environment::set_background);
+ ClassDB::bind_method(D_METHOD("set_skybox", "skybox:CubeMap"), &Environment::set_skybox);
+ ClassDB::bind_method(D_METHOD("set_skybox_scale", "scale"), &Environment::set_skybox_scale);
+ ClassDB::bind_method(D_METHOD("set_bg_color", "color"), &Environment::set_bg_color);
+ ClassDB::bind_method(D_METHOD("set_bg_energy", "energy"), &Environment::set_bg_energy);
+ ClassDB::bind_method(D_METHOD("set_canvas_max_layer", "layer"), &Environment::set_canvas_max_layer);
+ ClassDB::bind_method(D_METHOD("set_ambient_light_color", "color"), &Environment::set_ambient_light_color);
+ ClassDB::bind_method(D_METHOD("set_ambient_light_energy", "energy"), &Environment::set_ambient_light_energy);
+ ClassDB::bind_method(D_METHOD("set_ambient_light_skybox_contribution", "energy"), &Environment::set_ambient_light_skybox_contribution);
+
+ ClassDB::bind_method(D_METHOD("get_background"), &Environment::get_background);
+ ClassDB::bind_method(D_METHOD("get_skybox:CubeMap"), &Environment::get_skybox);
+ ClassDB::bind_method(D_METHOD("get_skybox_scale"), &Environment::get_skybox_scale);
+ ClassDB::bind_method(D_METHOD("get_bg_color"), &Environment::get_bg_color);
+ ClassDB::bind_method(D_METHOD("get_bg_energy"), &Environment::get_bg_energy);
+ ClassDB::bind_method(D_METHOD("get_canvas_max_layer"), &Environment::get_canvas_max_layer);
+ ClassDB::bind_method(D_METHOD("get_ambient_light_color"), &Environment::get_ambient_light_color);
+ ClassDB::bind_method(D_METHOD("get_ambient_light_energy"), &Environment::get_ambient_light_energy);
+ ClassDB::bind_method(D_METHOD("get_ambient_light_skybox_contribution"), &Environment::get_ambient_light_skybox_contribution);
+
+ ADD_GROUP("Background", "background_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "background_mode", PROPERTY_HINT_ENUM, "Clear Color,Custom Color,Skybox,Canvas,Keep"), "set_background", "get_background");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "background_skybox", PROPERTY_HINT_RESOURCE_TYPE, "SkyBox"), "set_skybox", "get_skybox");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "background_skybox_scale", PROPERTY_HINT_RANGE, "0,32,0.01"), "set_skybox_scale", "get_skybox_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "background_color"), "set_bg_color", "get_bg_color");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "background_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_bg_energy", "get_bg_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "background_canvas_max_layer", PROPERTY_HINT_RANGE, "-1000,1000,1"), "set_canvas_max_layer", "get_canvas_max_layer");
+ ADD_GROUP("Ambient Light", "ambient_light_");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "ambient_light_color"), "set_ambient_light_color", "get_ambient_light_color");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ambient_light_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_ambient_light_energy", "get_ambient_light_energy");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ambient_light_skybox_contribution", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_ambient_light_skybox_contribution", "get_ambient_light_skybox_contribution");
+
+ ClassDB::bind_method(D_METHOD("set_ssr_enabled", "enabled"), &Environment::set_ssr_enabled);
+ ClassDB::bind_method(D_METHOD("is_ssr_enabled"), &Environment::is_ssr_enabled);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_max_steps", "max_steps"), &Environment::set_ssr_max_steps);
+ ClassDB::bind_method(D_METHOD("get_ssr_max_steps"), &Environment::get_ssr_max_steps);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_accel", "accel"), &Environment::set_ssr_accel);
+ ClassDB::bind_method(D_METHOD("get_ssr_accel"), &Environment::get_ssr_accel);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_fade", "fade"), &Environment::set_ssr_fade);
+ ClassDB::bind_method(D_METHOD("get_ssr_fade"), &Environment::get_ssr_fade);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_depth_tolerance", "depth_tolerance"), &Environment::set_ssr_depth_tolerance);
+ ClassDB::bind_method(D_METHOD("get_ssr_depth_tolerance"), &Environment::get_ssr_depth_tolerance);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_smooth", "smooth"), &Environment::set_ssr_smooth);
+ ClassDB::bind_method(D_METHOD("is_ssr_smooth"), &Environment::is_ssr_smooth);
+
+ ClassDB::bind_method(D_METHOD("set_ssr_rough", "rough"), &Environment::set_ssr_rough);
+ ClassDB::bind_method(D_METHOD("is_ssr_rough"), &Environment::is_ssr_rough);
+
+ ADD_GROUP("SS Reflections", "ss_reflections_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_enabled"), "set_ssr_enabled", "is_ssr_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "ss_reflections_max_steps", PROPERTY_HINT_RANGE, "1,512,1"), "set_ssr_max_steps", "get_ssr_max_steps");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_accel", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_ssr_accel", "get_ssr_accel");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_fade", PROPERTY_HINT_EXP_EASING), "set_ssr_fade", "get_ssr_fade");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ss_reflections_depth_tolerance", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_ssr_depth_tolerance", "get_ssr_depth_tolerance");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_accel_smooth"), "set_ssr_smooth", "is_ssr_smooth");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ss_reflections_roughness"), "set_ssr_rough", "is_ssr_rough");
- ClassDB::bind_method(D_METHOD("set_ssao_enabled","enabled"),&Environment::set_ssao_enabled);
- ClassDB::bind_method(D_METHOD("is_ssao_enabled"),&Environment::is_ssao_enabled);
+ ClassDB::bind_method(D_METHOD("set_ssao_enabled", "enabled"), &Environment::set_ssao_enabled);
+ ClassDB::bind_method(D_METHOD("is_ssao_enabled"), &Environment::is_ssao_enabled);
- ClassDB::bind_method(D_METHOD("set_ssao_radius","radius"),&Environment::set_ssao_radius);
- ClassDB::bind_method(D_METHOD("get_ssao_radius"),&Environment::get_ssao_radius);
+ ClassDB::bind_method(D_METHOD("set_ssao_radius", "radius"), &Environment::set_ssao_radius);
+ ClassDB::bind_method(D_METHOD("get_ssao_radius"), &Environment::get_ssao_radius);
- ClassDB::bind_method(D_METHOD("set_ssao_intensity","intensity"),&Environment::set_ssao_intensity);
- ClassDB::bind_method(D_METHOD("get_ssao_intensity"),&Environment::get_ssao_intensity);
+ ClassDB::bind_method(D_METHOD("set_ssao_intensity", "intensity"), &Environment::set_ssao_intensity);
+ ClassDB::bind_method(D_METHOD("get_ssao_intensity"), &Environment::get_ssao_intensity);
- ClassDB::bind_method(D_METHOD("set_ssao_radius2","radius"),&Environment::set_ssao_radius2);
- ClassDB::bind_method(D_METHOD("get_ssao_radius2"),&Environment::get_ssao_radius2);
+ ClassDB::bind_method(D_METHOD("set_ssao_radius2", "radius"), &Environment::set_ssao_radius2);
+ ClassDB::bind_method(D_METHOD("get_ssao_radius2"), &Environment::get_ssao_radius2);
- ClassDB::bind_method(D_METHOD("set_ssao_intensity2","intensity"),&Environment::set_ssao_intensity2);
- ClassDB::bind_method(D_METHOD("get_ssao_intensity2"),&Environment::get_ssao_intensity2);
+ ClassDB::bind_method(D_METHOD("set_ssao_intensity2", "intensity"), &Environment::set_ssao_intensity2);
+ ClassDB::bind_method(D_METHOD("get_ssao_intensity2"), &Environment::get_ssao_intensity2);
+
+ ClassDB::bind_method(D_METHOD("set_ssao_bias", "bias"), &Environment::set_ssao_bias);
+ ClassDB::bind_method(D_METHOD("get_ssao_bias"), &Environment::get_ssao_bias);
+
+ ClassDB::bind_method(D_METHOD("set_ssao_direct_light_affect", "amount"), &Environment::set_ssao_direct_light_affect);
+ ClassDB::bind_method(D_METHOD("get_ssao_direct_light_affect"), &Environment::get_ssao_direct_light_affect);
+
+ ClassDB::bind_method(D_METHOD("set_ssao_color", "color"), &Environment::set_ssao_color);
+ ClassDB::bind_method(D_METHOD("get_ssao_color"), &Environment::get_ssao_color);
+
+ ClassDB::bind_method(D_METHOD("set_ssao_blur", "enabled"), &Environment::set_ssao_blur);
+ ClassDB::bind_method(D_METHOD("is_ssao_blur_enabled"), &Environment::is_ssao_blur_enabled);
+
+ ADD_GROUP("SSAO", "ssao_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ssao_enabled"), "set_ssao_enabled", "is_ssao_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_radius", PROPERTY_HINT_RANGE, "0.1,16,0.1"), "set_ssao_radius", "get_ssao_radius");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_intensity", PROPERTY_HINT_RANGE, "0.0,9,0.1"), "set_ssao_intensity", "get_ssao_intensity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_radius2", PROPERTY_HINT_RANGE, "0.0,16,0.1"), "set_ssao_radius2", "get_ssao_radius2");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_intensity2", PROPERTY_HINT_RANGE, "0.0,9,0.1"), "set_ssao_intensity2", "get_ssao_intensity2");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_bias", PROPERTY_HINT_RANGE, "0.001,8,0.001"), "set_ssao_bias", "get_ssao_bias");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ssao_light_affect", PROPERTY_HINT_RANGE, "0.00,1,0.01"), "set_ssao_direct_light_affect", "get_ssao_direct_light_affect");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "ssao_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_ssao_color", "get_ssao_color");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "ssao_blur"), "set_ssao_blur", "is_ssao_blur_enabled");
+
+ ClassDB::bind_method(D_METHOD("set_dof_blur_far_enabled", "enabled"), &Environment::set_dof_blur_far_enabled);
+ ClassDB::bind_method(D_METHOD("is_dof_blur_far_enabled"), &Environment::is_dof_blur_far_enabled);
+
+ ClassDB::bind_method(D_METHOD("set_dof_blur_far_distance", "intensity"), &Environment::set_dof_blur_far_distance);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_far_distance"), &Environment::get_dof_blur_far_distance);
+
+ ClassDB::bind_method(D_METHOD("set_dof_blur_far_transition", "intensity"), &Environment::set_dof_blur_far_transition);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_far_transition"), &Environment::get_dof_blur_far_transition);
- ClassDB::bind_method(D_METHOD("set_ssao_bias","bias"),&Environment::set_ssao_bias);
- ClassDB::bind_method(D_METHOD("get_ssao_bias"),&Environment::get_ssao_bias);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_far_amount", "intensity"), &Environment::set_dof_blur_far_amount);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_far_amount"), &Environment::get_dof_blur_far_amount);
- ClassDB::bind_method(D_METHOD("set_ssao_direct_light_affect","amount"),&Environment::set_ssao_direct_light_affect);
- ClassDB::bind_method(D_METHOD("get_ssao_direct_light_affect"),&Environment::get_ssao_direct_light_affect);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_far_quality", "intensity"), &Environment::set_dof_blur_far_quality);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_far_quality"), &Environment::get_dof_blur_far_quality);
- ClassDB::bind_method(D_METHOD("set_ssao_color","color"),&Environment::set_ssao_color);
- ClassDB::bind_method(D_METHOD("get_ssao_color"),&Environment::get_ssao_color);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_near_enabled", "enabled"), &Environment::set_dof_blur_near_enabled);
+ ClassDB::bind_method(D_METHOD("is_dof_blur_near_enabled"), &Environment::is_dof_blur_near_enabled);
- ClassDB::bind_method(D_METHOD("set_ssao_blur","enabled"),&Environment::set_ssao_blur);
- ClassDB::bind_method(D_METHOD("is_ssao_blur_enabled"),&Environment::is_ssao_blur_enabled);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_near_distance", "intensity"), &Environment::set_dof_blur_near_distance);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_near_distance"), &Environment::get_dof_blur_near_distance);
- ADD_GROUP("SSAO","ssao_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_enabled"),"set_ssao_enabled","is_ssao_enabled") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius",PROPERTY_HINT_RANGE,"0.1,16,0.1"),"set_ssao_radius","get_ssao_radius") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity",PROPERTY_HINT_RANGE,"0.0,9,0.1"),"set_ssao_intensity","get_ssao_intensity") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius2",PROPERTY_HINT_RANGE,"0.0,16,0.1"),"set_ssao_radius2","get_ssao_radius2") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity2",PROPERTY_HINT_RANGE,"0.0,9,0.1"),"set_ssao_intensity2","get_ssao_intensity2") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_bias",PROPERTY_HINT_RANGE,"0.001,8,0.001"),"set_ssao_bias","get_ssao_bias") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_light_affect",PROPERTY_HINT_RANGE,"0.00,1,0.01"),"set_ssao_direct_light_affect","get_ssao_direct_light_affect") ;
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ssao_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_ssao_color","get_ssao_color") ;
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_blur"),"set_ssao_blur","is_ssao_blur_enabled") ;
+ ClassDB::bind_method(D_METHOD("set_dof_blur_near_transition", "intensity"), &Environment::set_dof_blur_near_transition);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_near_transition"), &Environment::get_dof_blur_near_transition);
- ClassDB::bind_method(D_METHOD("set_dof_blur_far_enabled","enabled"),&Environment::set_dof_blur_far_enabled);
- ClassDB::bind_method(D_METHOD("is_dof_blur_far_enabled"),&Environment::is_dof_blur_far_enabled);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_near_amount", "intensity"), &Environment::set_dof_blur_near_amount);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_near_amount"), &Environment::get_dof_blur_near_amount);
- ClassDB::bind_method(D_METHOD("set_dof_blur_far_distance","intensity"),&Environment::set_dof_blur_far_distance);
- ClassDB::bind_method(D_METHOD("get_dof_blur_far_distance"),&Environment::get_dof_blur_far_distance);
+ ClassDB::bind_method(D_METHOD("set_dof_blur_near_quality", "level"), &Environment::set_dof_blur_near_quality);
+ ClassDB::bind_method(D_METHOD("get_dof_blur_near_quality"), &Environment::get_dof_blur_near_quality);
- ClassDB::bind_method(D_METHOD("set_dof_blur_far_transition","intensity"),&Environment::set_dof_blur_far_transition);
- ClassDB::bind_method(D_METHOD("get_dof_blur_far_transition"),&Environment::get_dof_blur_far_transition);
+ ADD_GROUP("DOF Far Blur", "dof_blur_far_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_far_enabled"), "set_dof_blur_far_enabled", "is_dof_blur_far_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_distance", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_far_distance", "get_dof_blur_far_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_transition", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_far_transition", "get_dof_blur_far_transition");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_far_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_far_amount", "get_dof_blur_far_amount");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dof_blur_far_quality", PROPERTY_HINT_ENUM, "Low,Medium,High"), "set_dof_blur_far_quality", "get_dof_blur_far_quality");
- ClassDB::bind_method(D_METHOD("set_dof_blur_far_amount","intensity"),&Environment::set_dof_blur_far_amount);
- ClassDB::bind_method(D_METHOD("get_dof_blur_far_amount"),&Environment::get_dof_blur_far_amount);
+ ADD_GROUP("DOF Far Near", "dof_blur_near_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "dof_blur_near_enabled"), "set_dof_blur_near_enabled", "is_dof_blur_near_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_distance", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_near_distance", "get_dof_blur_near_distance");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_transition", PROPERTY_HINT_EXP_RANGE, "0.01,8192,0.01"), "set_dof_blur_near_transition", "get_dof_blur_near_transition");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dof_blur_near_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dof_blur_near_amount", "get_dof_blur_near_amount");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dof_blur_near_quality", PROPERTY_HINT_ENUM, "Low,Medium,High"), "set_dof_blur_near_quality", "get_dof_blur_near_quality");
- ClassDB::bind_method(D_METHOD("set_dof_blur_far_quality","intensity"),&Environment::set_dof_blur_far_quality);
- ClassDB::bind_method(D_METHOD("get_dof_blur_far_quality"),&Environment::get_dof_blur_far_quality);
+ ClassDB::bind_method(D_METHOD("set_glow_enabled", "enabled"), &Environment::set_glow_enabled);
+ ClassDB::bind_method(D_METHOD("is_glow_enabled"), &Environment::is_glow_enabled);
- ClassDB::bind_method(D_METHOD("set_dof_blur_near_enabled","enabled"),&Environment::set_dof_blur_near_enabled);
- ClassDB::bind_method(D_METHOD("is_dof_blur_near_enabled"),&Environment::is_dof_blur_near_enabled);
+ ClassDB::bind_method(D_METHOD("set_glow_level", "idx", "enabled"), &Environment::set_glow_level);
+ ClassDB::bind_method(D_METHOD("is_glow_level_enabled", "idx"), &Environment::is_glow_level_enabled);
- ClassDB::bind_method(D_METHOD("set_dof_blur_near_distance","intensity"),&Environment::set_dof_blur_near_distance);
- ClassDB::bind_method(D_METHOD("get_dof_blur_near_distance"),&Environment::get_dof_blur_near_distance);
+ ClassDB::bind_method(D_METHOD("set_glow_intensity", "intensity"), &Environment::set_glow_intensity);
+ ClassDB::bind_method(D_METHOD("get_glow_intensity"), &Environment::get_glow_intensity);
- ClassDB::bind_method(D_METHOD("set_dof_blur_near_transition","intensity"),&Environment::set_dof_blur_near_transition);
- ClassDB::bind_method(D_METHOD("get_dof_blur_near_transition"),&Environment::get_dof_blur_near_transition);
+ ClassDB::bind_method(D_METHOD("set_glow_strength", "strength"), &Environment::set_glow_strength);
+ ClassDB::bind_method(D_METHOD("get_glow_strength"), &Environment::get_glow_strength);
- ClassDB::bind_method(D_METHOD("set_dof_blur_near_amount","intensity"),&Environment::set_dof_blur_near_amount);
- ClassDB::bind_method(D_METHOD("get_dof_blur_near_amount"),&Environment::get_dof_blur_near_amount);
+ ClassDB::bind_method(D_METHOD("set_glow_bloom", "amount"), &Environment::set_glow_bloom);
+ ClassDB::bind_method(D_METHOD("get_glow_bloom"), &Environment::get_glow_bloom);
- ClassDB::bind_method(D_METHOD("set_dof_blur_near_quality","level"),&Environment::set_dof_blur_near_quality);
- ClassDB::bind_method(D_METHOD("get_dof_blur_near_quality"),&Environment::get_dof_blur_near_quality);
+ ClassDB::bind_method(D_METHOD("set_glow_blend_mode", "mode"), &Environment::set_glow_blend_mode);
+ ClassDB::bind_method(D_METHOD("get_glow_blend_mode"), &Environment::get_glow_blend_mode);
- ADD_GROUP("DOF Far Blur","dof_blur_far_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_far_enabled"),"set_dof_blur_far_enabled","is_dof_blur_far_enabled") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_far_distance","get_dof_blur_far_distance") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_far_transition","get_dof_blur_far_transition") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dof_blur_far_amount","get_dof_blur_far_amount") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_far_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),"set_dof_blur_far_quality","get_dof_blur_far_quality") ;
+ ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_treshold", "treshold"), &Environment::set_glow_hdr_bleed_treshold);
+ ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_treshold"), &Environment::get_glow_hdr_bleed_treshold);
- ADD_GROUP("DOF Far Near","dof_blur_near_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_near_enabled"),"set_dof_blur_near_enabled","is_dof_blur_near_enabled") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_near_distance","get_dof_blur_near_distance") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),"set_dof_blur_near_transition","get_dof_blur_near_transition") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dof_blur_near_amount","get_dof_blur_near_amount") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_near_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),"set_dof_blur_near_quality","get_dof_blur_near_quality") ;
+ ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_scale", "scale"), &Environment::set_glow_hdr_bleed_scale);
+ ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_scale"), &Environment::get_glow_hdr_bleed_scale);
+ ClassDB::bind_method(D_METHOD("set_glow_bicubic_upscale", "enabled"), &Environment::set_glow_bicubic_upscale);
+ ClassDB::bind_method(D_METHOD("is_glow_bicubic_upscale_enabled"), &Environment::is_glow_bicubic_upscale_enabled);
- ClassDB::bind_method(D_METHOD("set_glow_enabled","enabled"),&Environment::set_glow_enabled);
- ClassDB::bind_method(D_METHOD("is_glow_enabled"),&Environment::is_glow_enabled);
+ ADD_GROUP("Glow", "glow_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "glow_enabled"), "set_glow_enabled", "is_glow_enabled");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/1"), "set_glow_level", "is_glow_level_enabled", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/2"), "set_glow_level", "is_glow_level_enabled", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/3"), "set_glow_level", "is_glow_level_enabled", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/4"), "set_glow_level", "is_glow_level_enabled", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/5"), "set_glow_level", "is_glow_level_enabled", 4);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/6"), "set_glow_level", "is_glow_level_enabled", 5);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "glow_levels/7"), "set_glow_level", "is_glow_level_enabled", 6);
- ClassDB::bind_method(D_METHOD("set_glow_level","idx","enabled"),&Environment::set_glow_level);
- ClassDB::bind_method(D_METHOD("is_glow_level_enabled","idx"),&Environment::is_glow_level_enabled);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_intensity", PROPERTY_HINT_RANGE, "0.0,8.0,0.01"), "set_glow_intensity", "get_glow_intensity");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_strength", PROPERTY_HINT_RANGE, "0.0,2.0,0.01"), "set_glow_strength", "get_glow_strength");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_bloom", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_glow_bloom", "get_glow_bloom");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "glow_blend_mode", PROPERTY_HINT_ENUM, "Additive,Screen,Softlight,Replace"), "set_glow_blend_mode", "get_glow_blend_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_hdr_treshold", PROPERTY_HINT_RANGE, "0.0,4.0,0.01"), "set_glow_hdr_bleed_treshold", "get_glow_hdr_bleed_treshold");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "glow_hdr_scale", PROPERTY_HINT_RANGE, "0.0,4.0,0.01"), "set_glow_hdr_bleed_scale", "get_glow_hdr_bleed_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "glow_bicubic_upscale"), "set_glow_bicubic_upscale", "is_glow_bicubic_upscale_enabled");
- ClassDB::bind_method(D_METHOD("set_glow_intensity","intensity"),&Environment::set_glow_intensity);
- ClassDB::bind_method(D_METHOD("get_glow_intensity"),&Environment::get_glow_intensity);
+ ClassDB::bind_method(D_METHOD("set_tonemapper", "mode"), &Environment::set_tonemapper);
+ ClassDB::bind_method(D_METHOD("get_tonemapper"), &Environment::get_tonemapper);
- ClassDB::bind_method(D_METHOD("set_glow_strength","strength"),&Environment::set_glow_strength);
- ClassDB::bind_method(D_METHOD("get_glow_strength"),&Environment::get_glow_strength);
+ ClassDB::bind_method(D_METHOD("set_tonemap_exposure", "exposure"), &Environment::set_tonemap_exposure);
+ ClassDB::bind_method(D_METHOD("get_tonemap_exposure"), &Environment::get_tonemap_exposure);
- ClassDB::bind_method(D_METHOD("set_glow_bloom","amount"),&Environment::set_glow_bloom);
- ClassDB::bind_method(D_METHOD("get_glow_bloom"),&Environment::get_glow_bloom);
+ ClassDB::bind_method(D_METHOD("set_tonemap_white", "white"), &Environment::set_tonemap_white);
+ ClassDB::bind_method(D_METHOD("get_tonemap_white"), &Environment::get_tonemap_white);
- ClassDB::bind_method(D_METHOD("set_glow_blend_mode","mode"),&Environment::set_glow_blend_mode);
- ClassDB::bind_method(D_METHOD("get_glow_blend_mode"),&Environment::get_glow_blend_mode);
+ ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure", "auto_exposure"), &Environment::set_tonemap_auto_exposure);
+ ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure"), &Environment::get_tonemap_auto_exposure);
- ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_treshold","treshold"),&Environment::set_glow_hdr_bleed_treshold);
- ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_treshold"),&Environment::get_glow_hdr_bleed_treshold);
+ ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_max", "exposure_max"), &Environment::set_tonemap_auto_exposure_max);
+ ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_max"), &Environment::get_tonemap_auto_exposure_max);
- ClassDB::bind_method(D_METHOD("set_glow_hdr_bleed_scale","scale"),&Environment::set_glow_hdr_bleed_scale);
- ClassDB::bind_method(D_METHOD("get_glow_hdr_bleed_scale"),&Environment::get_glow_hdr_bleed_scale);
+ ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_min", "exposure_min"), &Environment::set_tonemap_auto_exposure_min);
+ ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_min"), &Environment::get_tonemap_auto_exposure_min);
- ClassDB::bind_method(D_METHOD("set_glow_bicubic_upscale","enabled"),&Environment::set_glow_bicubic_upscale);
- ClassDB::bind_method(D_METHOD("is_glow_bicubic_upscale_enabled"),&Environment::is_glow_bicubic_upscale_enabled);
+ ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_speed", "exposure_speed"), &Environment::set_tonemap_auto_exposure_speed);
+ ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_speed"), &Environment::get_tonemap_auto_exposure_speed);
- ADD_GROUP("Glow","glow_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_enabled"),"set_glow_enabled","is_glow_enabled") ;
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/1"),"set_glow_level","is_glow_level_enabled",0 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/2"),"set_glow_level","is_glow_level_enabled",1 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/3"),"set_glow_level","is_glow_level_enabled",2 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/4"),"set_glow_level","is_glow_level_enabled",3 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/5"),"set_glow_level","is_glow_level_enabled",4 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/6"),"set_glow_level","is_glow_level_enabled",5 );
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/7"),"set_glow_level","is_glow_level_enabled",6 );
+ ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_grey", "exposure_grey"), &Environment::set_tonemap_auto_exposure_grey);
+ ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_grey"), &Environment::get_tonemap_auto_exposure_grey);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_intensity",PROPERTY_HINT_RANGE,"0.0,8.0,0.01"),"set_glow_intensity","get_glow_intensity") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_strength",PROPERTY_HINT_RANGE,"0.0,2.0,0.01"),"set_glow_strength","get_glow_strength") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_bloom",PROPERTY_HINT_RANGE,"0.0,1.0,0.01"),"set_glow_bloom","get_glow_bloom") ;
- ADD_PROPERTY(PropertyInfo(Variant::INT,"glow_blend_mode",PROPERTY_HINT_ENUM,"Additive,Screen,Softlight,Replace"),"set_glow_blend_mode","get_glow_blend_mode") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_treshold",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),"set_glow_hdr_bleed_treshold","get_glow_hdr_bleed_treshold") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_scale",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),"set_glow_hdr_bleed_scale","get_glow_hdr_bleed_scale") ;
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_bicubic_upscale"),"set_glow_bicubic_upscale","is_glow_bicubic_upscale_enabled") ;
+ ADD_GROUP("Tonemap", "tonemap_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "tonemap_mode", PROPERTY_HINT_ENUM, "Linear,Reindhart,Filmic,Aces"), "set_tonemapper", "get_tonemapper");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tonemap_exposure", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_exposure", "get_tonemap_exposure");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tonemap_white", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_white", "get_tonemap_white");
+ ADD_GROUP("Auto Exposure", "auto_exposure_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_expoure_enabled"), "set_tonemap_auto_exposure", "get_tonemap_auto_exposure");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_scale", PROPERTY_HINT_RANGE, "0.01,64,0.01"), "set_tonemap_auto_exposure_grey", "get_tonemap_auto_exposure_grey");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_min_luma", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_auto_exposure_min", "get_tonemap_auto_exposure_min");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_max_luma", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_tonemap_auto_exposure_max", "get_tonemap_auto_exposure_max");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "auto_expoure_speed", PROPERTY_HINT_RANGE, "0.01,64,0.01"), "set_tonemap_auto_exposure_speed", "get_tonemap_auto_exposure_speed");
+ ClassDB::bind_method(D_METHOD("set_adjustment_enable", "enabled"), &Environment::set_adjustment_enable);
+ ClassDB::bind_method(D_METHOD("is_adjustment_enabled"), &Environment::is_adjustment_enabled);
- ClassDB::bind_method(D_METHOD("set_tonemapper","mode"),&Environment::set_tonemapper);
- ClassDB::bind_method(D_METHOD("get_tonemapper"),&Environment::get_tonemapper);
+ ClassDB::bind_method(D_METHOD("set_adjustment_brightness", "brightness"), &Environment::set_adjustment_brightness);
+ ClassDB::bind_method(D_METHOD("get_adjustment_brightness"), &Environment::get_adjustment_brightness);
- ClassDB::bind_method(D_METHOD("set_tonemap_exposure","exposure"),&Environment::set_tonemap_exposure);
- ClassDB::bind_method(D_METHOD("get_tonemap_exposure"),&Environment::get_tonemap_exposure);
+ ClassDB::bind_method(D_METHOD("set_adjustment_contrast", "contrast"), &Environment::set_adjustment_contrast);
+ ClassDB::bind_method(D_METHOD("get_adjustment_contrast"), &Environment::get_adjustment_contrast);
- ClassDB::bind_method(D_METHOD("set_tonemap_white","white"),&Environment::set_tonemap_white);
- ClassDB::bind_method(D_METHOD("get_tonemap_white"),&Environment::get_tonemap_white);
+ ClassDB::bind_method(D_METHOD("set_adjustment_saturation", "saturation"), &Environment::set_adjustment_saturation);
+ ClassDB::bind_method(D_METHOD("get_adjustment_saturation"), &Environment::get_adjustment_saturation);
- ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure","auto_exposure"),&Environment::set_tonemap_auto_exposure);
- ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure"),&Environment::get_tonemap_auto_exposure);
+ ClassDB::bind_method(D_METHOD("set_adjustment_color_correction", "color_correction"), &Environment::set_adjustment_color_correction);
+ ClassDB::bind_method(D_METHOD("get_adjustment_color_correction"), &Environment::get_adjustment_color_correction);
- ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_max","exposure_max"),&Environment::set_tonemap_auto_exposure_max);
- ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_max"),&Environment::get_tonemap_auto_exposure_max);
+ ADD_GROUP("Adjustments", "adjustment_");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "adjustment_enabled"), "set_adjustment_enable", "is_adjustment_enabled");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_brightness", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_brightness", "get_adjustment_brightness");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_contrast", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_contrast", "get_adjustment_contrast");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "adjustment_saturation", PROPERTY_HINT_RANGE, "0.01,8,0.01"), "set_adjustment_saturation", "get_adjustment_saturation");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "adjustment_color_correction", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_adjustment_color_correction", "get_adjustment_color_correction");
- ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_min","exposure_min"),&Environment::set_tonemap_auto_exposure_min);
- ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_min"),&Environment::get_tonemap_auto_exposure_min);
-
- ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_speed","exposure_speed"),&Environment::set_tonemap_auto_exposure_speed);
- ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_speed"),&Environment::get_tonemap_auto_exposure_speed);
-
- ClassDB::bind_method(D_METHOD("set_tonemap_auto_exposure_grey","exposure_grey"),&Environment::set_tonemap_auto_exposure_grey);
- ClassDB::bind_method(D_METHOD("get_tonemap_auto_exposure_grey"),&Environment::get_tonemap_auto_exposure_grey);
-
-
- ADD_GROUP("Tonemap","tonemap_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"tonemap_mode",PROPERTY_HINT_ENUM,"Linear,Reindhart,Filmic,Aces"),"set_tonemapper","get_tonemapper") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_exposure",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_exposure","get_tonemap_exposure") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_white",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_white","get_tonemap_white") ;
- ADD_GROUP("Auto Exposure","auto_exposure_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"auto_expoure_enabled"),"set_tonemap_auto_exposure","get_tonemap_auto_exposure") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_scale",PROPERTY_HINT_RANGE,"0.01,64,0.01"),"set_tonemap_auto_exposure_grey","get_tonemap_auto_exposure_grey") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_min_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_auto_exposure_min","get_tonemap_auto_exposure_min") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_max_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_tonemap_auto_exposure_max","get_tonemap_auto_exposure_max") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_speed",PROPERTY_HINT_RANGE,"0.01,64,0.01"),"set_tonemap_auto_exposure_speed","get_tonemap_auto_exposure_speed") ;
-
- ClassDB::bind_method(D_METHOD("set_adjustment_enable","enabled"),&Environment::set_adjustment_enable);
- ClassDB::bind_method(D_METHOD("is_adjustment_enabled"),&Environment::is_adjustment_enabled);
-
- ClassDB::bind_method(D_METHOD("set_adjustment_brightness","brightness"),&Environment::set_adjustment_brightness);
- ClassDB::bind_method(D_METHOD("get_adjustment_brightness"),&Environment::get_adjustment_brightness);
-
- ClassDB::bind_method(D_METHOD("set_adjustment_contrast","contrast"),&Environment::set_adjustment_contrast);
- ClassDB::bind_method(D_METHOD("get_adjustment_contrast"),&Environment::get_adjustment_contrast);
-
- ClassDB::bind_method(D_METHOD("set_adjustment_saturation","saturation"),&Environment::set_adjustment_saturation);
- ClassDB::bind_method(D_METHOD("get_adjustment_saturation"),&Environment::get_adjustment_saturation);
-
- ClassDB::bind_method(D_METHOD("set_adjustment_color_correction","color_correction"),&Environment::set_adjustment_color_correction);
- ClassDB::bind_method(D_METHOD("get_adjustment_color_correction"),&Environment::get_adjustment_color_correction);
-
- ADD_GROUP("Adjustments","adjustment_");
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"adjustment_enabled"),"set_adjustment_enable","is_adjustment_enabled") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_brightness",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_brightness","get_adjustment_brightness") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_contrast",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_contrast","get_adjustment_contrast") ;
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_saturation",PROPERTY_HINT_RANGE,"0.01,8,0.01"),"set_adjustment_saturation","get_adjustment_saturation") ;
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"adjustment_color_correction",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_adjustment_color_correction","get_adjustment_color_correction") ;
-
-
- GLOBAL_DEF("rendering/skybox/irradiance_cube_resolution",256);
+ GLOBAL_DEF("rendering/skybox/irradiance_cube_resolution", 256);
BIND_CONSTANT(BG_KEEP);
BIND_CONSTANT(BG_CLEAR_COLOR);
@@ -973,79 +927,75 @@ void Environment::_bind_methods() {
BIND_CONSTANT(DOF_BLUR_QUALITY_LOW);
BIND_CONSTANT(DOF_BLUR_QUALITY_MEDIUM);
BIND_CONSTANT(DOF_BLUR_QUALITY_HIGH);
-
-
}
Environment::Environment() {
- bg_mode=BG_CLEAR_COLOR;
- bg_skybox_scale=1.0;
- bg_energy=1.0;
- bg_canvas_max_layer=0;
- ambient_energy=1.0;
- ambient_skybox_contribution=0;
-
-
- tone_mapper=TONE_MAPPER_LINEAR;
- tonemap_exposure=1.0;
- tonemap_white=1.0;
- tonemap_auto_exposure=false;
- tonemap_auto_exposure_max=8;
- tonemap_auto_exposure_min=0.05;
- tonemap_auto_exposure_speed=0.5;
- tonemap_auto_exposure_grey=0.4;
+ bg_mode = BG_CLEAR_COLOR;
+ bg_skybox_scale = 1.0;
+ bg_energy = 1.0;
+ bg_canvas_max_layer = 0;
+ ambient_energy = 1.0;
+ ambient_skybox_contribution = 0;
+
+ tone_mapper = TONE_MAPPER_LINEAR;
+ tonemap_exposure = 1.0;
+ tonemap_white = 1.0;
+ tonemap_auto_exposure = false;
+ tonemap_auto_exposure_max = 8;
+ tonemap_auto_exposure_min = 0.05;
+ tonemap_auto_exposure_speed = 0.5;
+ tonemap_auto_exposure_grey = 0.4;
set_tonemapper(tone_mapper); //update
- adjustment_enabled=false;
- adjustment_contrast=1.0;
- adjustment_saturation=1.0;
- adjustment_brightness=1.0;
+ adjustment_enabled = false;
+ adjustment_contrast = 1.0;
+ adjustment_saturation = 1.0;
+ adjustment_brightness = 1.0;
set_adjustment_enable(adjustment_enabled); //update
environment = VS::get_singleton()->environment_create();
- ssr_enabled=false;
- ssr_max_steps=64;
- ssr_accel=0.04;
- ssr_fade=2.0;
- ssr_depth_tolerance=0.2;
- ssr_smooth=true;
- ssr_roughness=true;
-
- ssao_enabled=false;
- ssao_radius=1;
- ssao_intensity=1;
- ssao_radius2=0;
- ssao_intensity2=1;
- ssao_bias=0.01;
- ssao_direct_light_affect=false;
- ssao_blur=true;
-
- glow_enabled=false;
- glow_levels=(1<<2)|(1<<4);
- glow_intensity=0.8;
- glow_strength=1.0;
- glow_bloom=0.0;
- glow_blend_mode=GLOW_BLEND_MODE_SOFTLIGHT;
- glow_hdr_bleed_treshold=1.0;
- glow_hdr_bleed_scale=2.0;
- glow_bicubic_upscale=false;
-
- dof_blur_far_enabled=false;
- dof_blur_far_distance=10;
- dof_blur_far_transition=5;
- dof_blur_far_amount=0.1;
- dof_blur_far_quality=DOF_BLUR_QUALITY_MEDIUM;
-
- dof_blur_near_enabled=false;
- dof_blur_near_distance=2;
- dof_blur_near_transition=1;
- dof_blur_near_amount=0.1;
- dof_blur_near_quality=DOF_BLUR_QUALITY_MEDIUM;
-
+ ssr_enabled = false;
+ ssr_max_steps = 64;
+ ssr_accel = 0.04;
+ ssr_fade = 2.0;
+ ssr_depth_tolerance = 0.2;
+ ssr_smooth = true;
+ ssr_roughness = true;
+
+ ssao_enabled = false;
+ ssao_radius = 1;
+ ssao_intensity = 1;
+ ssao_radius2 = 0;
+ ssao_intensity2 = 1;
+ ssao_bias = 0.01;
+ ssao_direct_light_affect = false;
+ ssao_blur = true;
+
+ glow_enabled = false;
+ glow_levels = (1 << 2) | (1 << 4);
+ glow_intensity = 0.8;
+ glow_strength = 1.0;
+ glow_bloom = 0.0;
+ glow_blend_mode = GLOW_BLEND_MODE_SOFTLIGHT;
+ glow_hdr_bleed_treshold = 1.0;
+ glow_hdr_bleed_scale = 2.0;
+ glow_bicubic_upscale = false;
+
+ dof_blur_far_enabled = false;
+ dof_blur_far_distance = 10;
+ dof_blur_far_transition = 5;
+ dof_blur_far_amount = 0.1;
+ dof_blur_far_quality = DOF_BLUR_QUALITY_MEDIUM;
+
+ dof_blur_near_enabled = false;
+ dof_blur_near_distance = 2;
+ dof_blur_near_transition = 1;
+ dof_blur_near_amount = 0.1;
+ dof_blur_near_quality = DOF_BLUR_QUALITY_MEDIUM;
}
Environment::~Environment() {
diff --git a/scene/resources/environment.h b/scene/resources/environment.h
index b8c243b588..3ac311f4a3 100644
--- a/scene/resources/environment.h
+++ b/scene/resources/environment.h
@@ -30,15 +30,15 @@
#define ENVIRONMENT_H
#include "resource.h"
-#include "servers/visual_server.h"
-#include "scene/resources/texture.h"
#include "scene/resources/sky_box.h"
+#include "scene/resources/texture.h"
+#include "servers/visual_server.h"
class Environment : public Resource {
- GDCLASS(Environment,Resource);
-public:
+ GDCLASS(Environment, Resource);
+public:
enum BGMode {
BG_CLEAR_COLOR,
@@ -49,8 +49,6 @@ public:
BG_MAX
};
-
-
enum ToneMapper {
TONE_MAPPER_LINEAR,
TONE_MAPPER_REINHARDT,
@@ -140,20 +138,17 @@ private:
DOFBlurQuality dof_blur_near_quality;
protected:
-
static void _bind_methods();
- virtual void _validate_property(PropertyInfo& property) const;
+ virtual void _validate_property(PropertyInfo &property) const;
public:
-
-
void set_background(BGMode p_bg);
- void set_skybox(const Ref<SkyBox>& p_skybox);
+ void set_skybox(const Ref<SkyBox> &p_skybox);
void set_skybox_scale(float p_scale);
- void set_bg_color(const Color& p_color);
+ void set_bg_color(const Color &p_color);
void set_bg_energy(float p_energy);
void set_canvas_max_layer(int p_max_layer);
- void set_ambient_light_color(const Color& p_color);
+ void set_ambient_light_color(const Color &p_color);
void set_ambient_light_energy(float p_energy);
void set_ambient_light_skybox_contribution(float p_energy);
@@ -167,7 +162,6 @@ public:
float get_ambient_light_energy() const;
float get_ambient_light_skybox_contribution() const;
-
void set_tonemapper(ToneMapper p_tone_mapper);
ToneMapper get_tonemapper() const;
@@ -204,7 +198,7 @@ public:
void set_adjustment_saturation(float p_saturation);
float get_adjustment_saturation() const;
- void set_adjustment_color_correction(const Ref<Texture>& p_ramp);
+ void set_adjustment_color_correction(const Ref<Texture> &p_ramp);
Ref<Texture> get_adjustment_color_correction() const;
void set_ssr_enabled(bool p_enable);
@@ -249,17 +243,16 @@ public:
void set_ssao_direct_light_affect(float p_direct_light_affect);
float get_ssao_direct_light_affect() const;
- void set_ssao_color(const Color& p_color);
+ void set_ssao_color(const Color &p_color);
Color get_ssao_color() const;
void set_ssao_blur(bool p_enable);
bool is_ssao_blur_enabled() const;
-
void set_glow_enabled(bool p_enabled);
bool is_glow_enabled() const;
- void set_glow_level(int p_level,bool p_enabled);
+ void set_glow_level(int p_level, bool p_enabled);
bool is_glow_level_enabled(int p_level) const;
void set_glow_intensity(float p_intensity);
@@ -313,16 +306,12 @@ public:
void set_dof_blur_near_quality(DOFBlurQuality p_quality);
DOFBlurQuality get_dof_blur_near_quality() const;
-
virtual RID get_rid() const;
Environment();
~Environment();
};
-
-
-
VARIANT_ENUM_CAST(Environment::BGMode)
VARIANT_ENUM_CAST(Environment::ToneMapper)
VARIANT_ENUM_CAST(Environment::GlowBlendMode)
diff --git a/scene/resources/font.cpp b/scene/resources/font.cpp
index d94e046b98..9f30474a26 100644
--- a/scene/resources/font.cpp
+++ b/scene/resources/font.cpp
@@ -28,46 +28,44 @@
/*************************************************************************/
#include "font.h"
-#include "core/os/file_access.h"
#include "core/io/resource_loader.h"
+#include "core/os/file_access.h"
+void Font::draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate) const {
-
-void Font::draw_halign(RID p_canvas_item, const Point2& p_pos, HAlign p_align,float p_width,const String& p_text,const Color& p_modulate) const {
-
- float length=get_string_size(p_text).width;
- if (length>=p_width) {
- draw(p_canvas_item,p_pos,p_text,p_modulate,p_width);
+ float length = get_string_size(p_text).width;
+ if (length >= p_width) {
+ draw(p_canvas_item, p_pos, p_text, p_modulate, p_width);
return;
}
float ofs;
- switch(p_align) {
+ switch (p_align) {
case HALIGN_LEFT: {
- ofs=0;
+ ofs = 0;
} break;
case HALIGN_CENTER: {
- ofs = Math::floor( (p_width-length) / 2.0 );
+ ofs = Math::floor((p_width - length) / 2.0);
} break;
case HALIGN_RIGHT: {
- ofs=p_width-length;
+ ofs = p_width - length;
} break;
}
- draw(p_canvas_item,p_pos+Point2(ofs,0),p_text,p_modulate,p_width);
+ draw(p_canvas_item, p_pos + Point2(ofs, 0), p_text, p_modulate, p_width);
}
-void Font::draw(RID p_canvas_item, const Point2& p_pos, const String& p_text, const Color& p_modulate,int p_clip_w) const {
+void Font::draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) const {
Vector2 ofs;
- for (int i=0;i<p_text.length();i++) {
+ for (int i = 0; i < p_text.length(); i++) {
int width = get_char_size(p_text[i]).width;
- if (p_clip_w>=0 && (ofs.x+width)>p_clip_w)
+ if (p_clip_w >= 0 && (ofs.x + width) > p_clip_w)
break; //clip
- ofs.x+=draw_char(p_canvas_item,p_pos+ofs,p_text[i],p_text[i+1],p_modulate);
+ ofs.x += draw_char(p_canvas_item, p_pos + ofs, p_text[i], p_text[i + 1], p_modulate);
}
}
@@ -78,53 +76,47 @@ void Font::update_changes() {
void Font::_bind_methods() {
- ClassDB::bind_method(D_METHOD("draw","canvas_item","pos","string","modulate","clip_w"),&Font::draw,DEFVAL(Color(1,1,1)),DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("get_ascent"),&Font::get_ascent);
- ClassDB::bind_method(D_METHOD("get_descent"),&Font::get_descent);
- ClassDB::bind_method(D_METHOD("get_height"),&Font::get_height);
- ClassDB::bind_method(D_METHOD("is_distance_field_hint"),&Font::is_distance_field_hint);
- ClassDB::bind_method(D_METHOD("get_string_size","string"),&Font::get_string_size);
- ClassDB::bind_method(D_METHOD("draw_char","canvas_item","pos","char","next","modulate"),&Font::draw_char,DEFVAL(-1),DEFVAL(Color(1,1,1)));
- ClassDB::bind_method(D_METHOD("update_changes"),&Font::update_changes);
-
+ ClassDB::bind_method(D_METHOD("draw", "canvas_item", "pos", "string", "modulate", "clip_w"), &Font::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("get_ascent"), &Font::get_ascent);
+ ClassDB::bind_method(D_METHOD("get_descent"), &Font::get_descent);
+ ClassDB::bind_method(D_METHOD("get_height"), &Font::get_height);
+ ClassDB::bind_method(D_METHOD("is_distance_field_hint"), &Font::is_distance_field_hint);
+ ClassDB::bind_method(D_METHOD("get_string_size", "string"), &Font::get_string_size);
+ ClassDB::bind_method(D_METHOD("draw_char", "canvas_item", "pos", "char", "next", "modulate"), &Font::draw_char, DEFVAL(-1), DEFVAL(Color(1, 1, 1)));
+ ClassDB::bind_method(D_METHOD("update_changes"), &Font::update_changes);
}
-
Font::Font() {
-
-
}
/////////////////////////////////////////////////////////////////
-void BitmapFont::_set_chars(const PoolVector<int>& p_chars) {
+void BitmapFont::_set_chars(const PoolVector<int> &p_chars) {
int len = p_chars.size();
//char 1 charsize 1 texture, 4 rect, 2 align, advance 1
- ERR_FAIL_COND(len%9);
+ ERR_FAIL_COND(len % 9);
if (!len)
return; //none to do
- int chars = len/9;
+ int chars = len / 9;
+ PoolVector<int>::Read r = p_chars.read();
+ for (int i = 0; i < chars; i++) {
- PoolVector<int>::Read r=p_chars.read();
- for(int i=0;i<chars;i++) {
-
- const int* data = &r[i*9];
- add_char(data[0],data[1],Rect2(data[2],data[3],data[4],data[5]), Size2(data[6],data[7]),data[8]);
+ const int *data = &r[i * 9];
+ add_char(data[0], data[1], Rect2(data[2], data[3], data[4], data[5]), Size2(data[6], data[7]), data[8]);
}
-
}
PoolVector<int> BitmapFont::_get_chars() const {
PoolVector<int> chars;
- const CharType* key=NULL;
+ const CharType *key = NULL;
- while((key=char_map.next(key))) {
+ while ((key = char_map.next(key))) {
- const Character *c=char_map.getptr(*key);
+ const Character *c = char_map.getptr(*key);
chars.push_back(*key);
chars.push_back(c->texture_idx);
chars.push_back(c->rect.pos.x);
@@ -140,18 +132,18 @@ PoolVector<int> BitmapFont::_get_chars() const {
return chars;
}
-void BitmapFont::_set_kernings(const PoolVector<int>& p_kernings) {
+void BitmapFont::_set_kernings(const PoolVector<int> &p_kernings) {
- int len=p_kernings.size();
- ERR_FAIL_COND(len%3);
+ int len = p_kernings.size();
+ ERR_FAIL_COND(len % 3);
if (!len)
return;
- PoolVector<int>::Read r=p_kernings.read();
+ PoolVector<int>::Read r = p_kernings.read();
- for(int i=0;i<len/3;i++) {
+ for (int i = 0; i < len / 3; i++) {
- const int* data = &r[i*3];
- add_kerning_pair(data[0],data[1],data[2]);
+ const int *data = &r[i * 3];
+ add_kerning_pair(data[0], data[1], data[2]);
}
}
@@ -159,7 +151,7 @@ PoolVector<int> BitmapFont::_get_kernings() const {
PoolVector<int> kernings;
- for(Map<KerningPairKey,int>::Element *E=kerning_map.front();E;E=E->next()) {
+ for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
kernings.push_back(E->key().A);
kernings.push_back(E->key().B);
@@ -169,86 +161,79 @@ PoolVector<int> BitmapFont::_get_kernings() const {
return kernings;
}
+void BitmapFont::_set_textures(const Vector<Variant> &p_textures) {
-void BitmapFont::_set_textures(const Vector<Variant> & p_textures) {
-
- for(int i=0;i<p_textures.size();i++) {
+ for (int i = 0; i < p_textures.size(); i++) {
Ref<Texture> tex = p_textures[i];
ERR_CONTINUE(!tex.is_valid());
add_texture(tex);
}
-
}
Vector<Variant> BitmapFont::_get_textures() const {
Vector<Variant> rtextures;
- for(int i=0;i<textures.size();i++)
+ for (int i = 0; i < textures.size(); i++)
rtextures.push_back(textures[i].get_ref_ptr());
return rtextures;
}
-Error BitmapFont::create_from_fnt(const String& p_string) {
+Error BitmapFont::create_from_fnt(const String &p_string) {
//fnt format used by angelcode bmfont
//http://www.angelcode.com/products/bmfont/
- FileAccess *f = FileAccess::open(p_string,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_string, FileAccess::READ);
if (!f) {
- ERR_EXPLAIN("Can't open font: "+p_string);
+ ERR_EXPLAIN("Can't open font: " + p_string);
ERR_FAIL_V(ERR_FILE_NOT_FOUND);
}
clear();
- while(true) {
+ while (true) {
- String line=f->get_line();
+ String line = f->get_line();
- int delimiter=line.find(" ");
- String type=line.substr(0,delimiter);
- int pos = delimiter+1;
- Map<String,String> keys;
+ int delimiter = line.find(" ");
+ String type = line.substr(0, delimiter);
+ int pos = delimiter + 1;
+ Map<String, String> keys;
- while (pos < line.size() && line[pos]==' ')
+ while (pos < line.size() && line[pos] == ' ')
pos++;
+ while (pos < line.size()) {
- while(pos<line.size()) {
-
- int eq = line.find("=",pos);
- if (eq==-1)
+ int eq = line.find("=", pos);
+ if (eq == -1)
break;
- String key=line.substr(pos,eq-pos);
- int end=-1;
+ String key = line.substr(pos, eq - pos);
+ int end = -1;
String value;
- if (line[eq+1]=='"') {
- end=line.find("\"",eq+2);
- if (end==-1)
+ 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;
+ value = line.substr(eq + 2, end - 1 - eq - 1);
+ pos = end + 1;
} else {
- end=line.find(" ",eq+1);
- if (end==-1)
- end=line.size();
+ end = line.find(" ", eq + 1);
+ if (end == -1)
+ end = line.size();
- value=line.substr(eq+1,end-eq);
-
- pos=end;
+ value = line.substr(eq + 1, end - eq);
+ pos = end;
}
- while (pos<line.size() && line[pos]==' ')
+ while (pos < line.size() && line[pos] == ' ')
pos++;
-
- keys[key]=value;
-
+ keys[key] = value;
}
-
- if (type=="info") {
+ if (type == "info") {
if (keys.has("face"))
set_name(keys["face"]);
@@ -257,19 +242,19 @@ Error BitmapFont::create_from_fnt(const String& p_string) {
font->set_height(keys["size"].to_int());
*/
- } else if (type=="common") {
+ } else if (type == "common") {
if (keys.has("lineHeight"))
set_height(keys["lineHeight"].to_int());
if (keys.has("base"))
set_ascent(keys["base"].to_int());
- } else if (type=="page") {
+ } else if (type == "page") {
if (keys.has("file")) {
String file = keys["file"];
- file=p_string.get_base_dir()+"/"+file;
+ file = p_string.get_base_dir() + "/" + file;
Ref<Texture> tex = ResourceLoader::load(file);
if (tex.is_null()) {
ERR_PRINT("Can't load font texture!");
@@ -277,80 +262,75 @@ Error BitmapFont::create_from_fnt(const String& p_string) {
add_texture(tex);
}
}
- } else if (type=="char") {
+ } else if (type == "char") {
- CharType idx=0;
+ CharType idx = 0;
if (keys.has("id"))
- idx=keys["id"].to_int();
+ idx = keys["id"].to_int();
Rect2 rect;
if (keys.has("x"))
- rect.pos.x=keys["x"].to_int();
+ rect.pos.x = keys["x"].to_int();
if (keys.has("y"))
- rect.pos.y=keys["y"].to_int();
+ rect.pos.y = keys["y"].to_int();
if (keys.has("width"))
- rect.size.width=keys["width"].to_int();
+ rect.size.width = keys["width"].to_int();
if (keys.has("height"))
- rect.size.height=keys["height"].to_int();
+ rect.size.height = keys["height"].to_int();
Point2 ofs;
if (keys.has("xoffset"))
- ofs.x=keys["xoffset"].to_int();
+ ofs.x = keys["xoffset"].to_int();
if (keys.has("yoffset"))
- ofs.y=keys["yoffset"].to_int();
+ ofs.y = keys["yoffset"].to_int();
- int texture=0;
+ int texture = 0;
if (keys.has("page"))
- texture=keys["page"].to_int();
- int advance=-1;
+ texture = keys["page"].to_int();
+ int advance = -1;
if (keys.has("xadvance"))
- advance=keys["xadvance"].to_int();
+ advance = keys["xadvance"].to_int();
- add_char(idx,texture,rect,ofs,advance);
+ add_char(idx, texture, rect, ofs, advance);
- } else if (type=="kerning") {
+ } else if (type == "kerning") {
- CharType first=0,second=0;
- int k=0;
+ CharType first = 0, second = 0;
+ int k = 0;
if (keys.has("first"))
- first=keys["first"].to_int();
+ first = keys["first"].to_int();
if (keys.has("second"))
- second=keys["second"].to_int();
+ second = keys["second"].to_int();
if (keys.has("amount"))
- k=keys["amount"].to_int();
-
- add_kerning_pair(first,second,-k);
+ k = keys["amount"].to_int();
+ add_kerning_pair(first, second, -k);
}
if (f->eof_reached())
break;
}
-
-
memdelete(f);
return OK;
}
-
-
void BitmapFont::set_height(float p_height) {
- height=p_height;
+ height = p_height;
}
-float BitmapFont::get_height() const{
+float BitmapFont::get_height() const {
return height;
}
-void BitmapFont::set_ascent(float p_ascent){
+void BitmapFont::set_ascent(float p_ascent) {
- ascent=p_ascent;
+ ascent = p_ascent;
}
float BitmapFont::get_ascent() const {
@@ -358,13 +338,13 @@ float BitmapFont::get_ascent() const {
}
float BitmapFont::get_descent() const {
- return height-ascent;
+ return height - ascent;
}
-void BitmapFont::add_texture(const Ref<Texture>& p_texture) {
+void BitmapFont::add_texture(const Ref<Texture> &p_texture) {
- ERR_FAIL_COND( p_texture.is_null());
- textures.push_back( p_texture );
+ ERR_FAIL_COND(p_texture.is_null());
+ textures.push_back(p_texture);
}
int BitmapFont::get_texture_count() const {
@@ -387,9 +367,9 @@ Vector<CharType> BitmapFont::get_char_keys() const {
Vector<CharType> chars;
chars.resize(char_map.size());
- const CharType* ct = NULL;
+ const CharType *ct = NULL;
int count = 0;
- while ( (ct = char_map.next(ct)) ) {
+ while ((ct = char_map.next(ct))) {
chars[count++] = *ct;
};
@@ -406,60 +386,56 @@ BitmapFont::Character BitmapFont::get_character(CharType p_char) const {
return char_map[p_char];
};
-void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2& p_rect, const Size2& p_align, float p_advance) {
+void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance) {
- if (p_advance<0)
- p_advance=p_rect.size.width;
+ if (p_advance < 0)
+ p_advance = p_rect.size.width;
Character c;
- c.rect=p_rect;
- c.texture_idx=p_texture_idx;
- c.v_align=p_align.y;
- c.advance=p_advance;
- c.h_align=p_align.x;
+ c.rect = p_rect;
+ c.texture_idx = p_texture_idx;
+ c.v_align = p_align.y;
+ c.advance = p_advance;
+ c.h_align = p_align.x;
- char_map[p_char]=c;
+ char_map[p_char] = c;
}
-void BitmapFont::add_kerning_pair(CharType p_A,CharType p_B,int p_kerning) {
-
+void BitmapFont::add_kerning_pair(CharType p_A, CharType p_B, int p_kerning) {
KerningPairKey kpk;
- kpk.A=p_A;
- kpk.B=p_B;
+ kpk.A = p_A;
+ kpk.B = p_B;
- if (p_kerning==0 && kerning_map.has(kpk)) {
+ if (p_kerning == 0 && kerning_map.has(kpk)) {
kerning_map.erase(kpk);
} else {
- kerning_map[kpk]=p_kerning;
+ kerning_map[kpk] = p_kerning;
}
}
Vector<BitmapFont::KerningPairKey> BitmapFont::get_kerning_pair_keys() const {
-
Vector<BitmapFont::KerningPairKey> ret;
ret.resize(kerning_map.size());
- int i=0;
-
- for (Map<KerningPairKey,int>::Element *E=kerning_map.front();E;E=E->next()) {
- ret[i++]=E->key();
+ int i = 0;
+ for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
+ ret[i++] = E->key();
}
return ret;
-
}
-int BitmapFont::get_kerning_pair(CharType p_A,CharType p_B) const {
+int BitmapFont::get_kerning_pair(CharType p_A, CharType p_B) const {
KerningPairKey kpk;
- kpk.A=p_A;
- kpk.B=p_B;
+ kpk.A = p_A;
+ kpk.B = p_B;
- const Map<KerningPairKey,int>::Element *E=kerning_map.find(kpk);
+ const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
if (E)
return E->get();
@@ -468,96 +444,94 @@ int BitmapFont::get_kerning_pair(CharType p_A,CharType p_B) const {
void BitmapFont::set_distance_field_hint(bool p_distance_field) {
- distance_field_hint=p_distance_field;
+ distance_field_hint = p_distance_field;
emit_changed();
}
-bool BitmapFont::is_distance_field_hint() const{
+bool BitmapFont::is_distance_field_hint() const {
return distance_field_hint;
}
-
void BitmapFont::clear() {
- height=1;
- ascent=0;
+ height = 1;
+ ascent = 0;
char_map.clear();
textures.clear();
kerning_map.clear();
- distance_field_hint=false;
+ distance_field_hint = false;
}
-Size2 Font::get_string_size(const String& p_string) const {
+Size2 Font::get_string_size(const String &p_string) const {
- float w=0;
+ float w = 0;
int l = p_string.length();
- if (l==0)
- return Size2(0,get_height());
+ if (l == 0)
+ return Size2(0, get_height());
const CharType *sptr = &p_string[0];
- for (int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- w+=get_char_size(sptr[i],sptr[i+1]).width;
+ w += get_char_size(sptr[i], sptr[i + 1]).width;
}
- return Size2(w,get_height());
+ return Size2(w, get_height());
}
void BitmapFont::set_fallback(const Ref<BitmapFont> &p_fallback) {
- fallback=p_fallback;
+ fallback = p_fallback;
}
-Ref<BitmapFont> BitmapFont::get_fallback() const{
+Ref<BitmapFont> BitmapFont::get_fallback() const {
return fallback;
}
-float BitmapFont::draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char, CharType p_next, const Color& p_modulate) const {
+float BitmapFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
- const Character * c = char_map.getptr(p_char);
+ const Character *c = char_map.getptr(p_char);
if (!c) {
if (fallback.is_valid())
- return fallback->draw_char(p_canvas_item,p_pos,p_char,p_next,p_modulate);
+ return fallback->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate);
return 0;
}
- Point2 cpos=p_pos;
- cpos.x+=c->h_align;
- cpos.y-=ascent;
- cpos.y+=c->v_align;
- ERR_FAIL_COND_V( c->texture_idx<-1 || c->texture_idx>=textures.size(),0);
- if (c->texture_idx!=-1)
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region( p_canvas_item, Rect2( cpos, c->rect.size ), textures[c->texture_idx]->get_rid(),c->rect, p_modulate );
+ Point2 cpos = p_pos;
+ cpos.x += c->h_align;
+ cpos.y -= ascent;
+ cpos.y += c->v_align;
+ ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
+ if (c->texture_idx != -1)
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx]->get_rid(), c->rect, p_modulate);
- return get_char_size(p_char,p_next).width;
+ return get_char_size(p_char, p_next).width;
}
+Size2 BitmapFont::get_char_size(CharType p_char, CharType p_next) const {
-Size2 BitmapFont::get_char_size(CharType p_char,CharType p_next) const {
-
- const Character * c = char_map.getptr(p_char);
+ const Character *c = char_map.getptr(p_char);
if (!c) {
if (fallback.is_valid())
- return fallback->get_char_size(p_char,p_next);
+ return fallback->get_char_size(p_char, p_next);
return Size2();
}
- Size2 ret(c->advance,c->rect.size.y);
+ Size2 ret(c->advance, c->rect.size.y);
if (p_next) {
KerningPairKey kpk;
- kpk.A=p_char;
- kpk.B=p_next;
+ kpk.A = p_char;
+ kpk.B = p_next;
- const Map<KerningPairKey,int>::Element *E=kerning_map.find(kpk);
+ const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
if (E) {
- ret.width-=E->get();
+ ret.width -= E->get();
}
}
@@ -566,63 +540,54 @@ Size2 BitmapFont::get_char_size(CharType p_char,CharType p_next) const {
void BitmapFont::_bind_methods() {
- ClassDB::bind_method(D_METHOD("create_from_fnt","path"),&BitmapFont::create_from_fnt);
- ClassDB::bind_method(D_METHOD("set_height","px"),&BitmapFont::set_height);
+ ClassDB::bind_method(D_METHOD("create_from_fnt", "path"), &BitmapFont::create_from_fnt);
+ ClassDB::bind_method(D_METHOD("set_height", "px"), &BitmapFont::set_height);
- ClassDB::bind_method(D_METHOD("set_ascent","px"),&BitmapFont::set_ascent);
+ ClassDB::bind_method(D_METHOD("set_ascent", "px"), &BitmapFont::set_ascent);
- ClassDB::bind_method(D_METHOD("add_kerning_pair","char_a","char_b","kerning"),&BitmapFont::add_kerning_pair);
- ClassDB::bind_method(D_METHOD("get_kerning_pair","char_a","char_b"),&BitmapFont::get_kerning_pair);
+ ClassDB::bind_method(D_METHOD("add_kerning_pair", "char_a", "char_b", "kerning"), &BitmapFont::add_kerning_pair);
+ ClassDB::bind_method(D_METHOD("get_kerning_pair", "char_a", "char_b"), &BitmapFont::get_kerning_pair);
- ClassDB::bind_method(D_METHOD("add_texture","texture:Texture"),&BitmapFont::add_texture);
- ClassDB::bind_method(D_METHOD("add_char","character","texture","rect","align","advance"),&BitmapFont::add_char,DEFVAL(Point2()),DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("add_texture", "texture:Texture"), &BitmapFont::add_texture);
+ ClassDB::bind_method(D_METHOD("add_char", "character", "texture", "rect", "align", "advance"), &BitmapFont::add_char, DEFVAL(Point2()), DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("get_texture_count"), &BitmapFont::get_texture_count);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture", "idx"), &BitmapFont::get_texture);
- ClassDB::bind_method(D_METHOD("get_texture_count"),&BitmapFont::get_texture_count);
- ClassDB::bind_method(D_METHOD("get_texture:Texture","idx"),&BitmapFont::get_texture);
+ ClassDB::bind_method(D_METHOD("get_char_size", "char", "next"), &BitmapFont::get_char_size, DEFVAL(0));
- ClassDB::bind_method(D_METHOD("get_char_size","char","next"),&BitmapFont::get_char_size,DEFVAL(0));
+ ClassDB::bind_method(D_METHOD("set_distance_field_hint", "enable"), &BitmapFont::set_distance_field_hint);
- ClassDB::bind_method(D_METHOD("set_distance_field_hint","enable"),&BitmapFont::set_distance_field_hint);
+ ClassDB::bind_method(D_METHOD("clear"), &BitmapFont::clear);
- ClassDB::bind_method(D_METHOD("clear"),&BitmapFont::clear);
+ ClassDB::bind_method(D_METHOD("_set_chars"), &BitmapFont::_set_chars);
+ ClassDB::bind_method(D_METHOD("_get_chars"), &BitmapFont::_get_chars);
+ ClassDB::bind_method(D_METHOD("_set_kernings"), &BitmapFont::_set_kernings);
+ ClassDB::bind_method(D_METHOD("_get_kernings"), &BitmapFont::_get_kernings);
- ClassDB::bind_method(D_METHOD("_set_chars"),&BitmapFont::_set_chars);
- ClassDB::bind_method(D_METHOD("_get_chars"),&BitmapFont::_get_chars);
+ ClassDB::bind_method(D_METHOD("_set_textures"), &BitmapFont::_set_textures);
+ ClassDB::bind_method(D_METHOD("_get_textures"), &BitmapFont::_get_textures);
- ClassDB::bind_method(D_METHOD("_set_kernings"),&BitmapFont::_set_kernings);
- ClassDB::bind_method(D_METHOD("_get_kernings"),&BitmapFont::_get_kernings);
+ ClassDB::bind_method(D_METHOD("set_fallback", "fallback"), &BitmapFont::set_fallback);
+ ClassDB::bind_method(D_METHOD("get_fallback"), &BitmapFont::get_fallback);
- ClassDB::bind_method(D_METHOD("_set_textures"),&BitmapFont::_set_textures);
- ClassDB::bind_method(D_METHOD("_get_textures"),&BitmapFont::_get_textures);
-
- ClassDB::bind_method(D_METHOD("set_fallback","fallback"),&BitmapFont::set_fallback);
- ClassDB::bind_method(D_METHOD("get_fallback"),&BitmapFont::get_fallback);
-
- ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "textures", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_textures", "_get_textures") ;
- ADD_PROPERTY( PropertyInfo( Variant::POOL_INT_ARRAY, "chars", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_chars", "_get_chars") ;
- ADD_PROPERTY( PropertyInfo( Variant::POOL_INT_ARRAY, "kernings", PROPERTY_HINT_NONE,"", PROPERTY_USAGE_NOEDITOR ), "_set_kernings", "_get_kernings") ;
-
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "height", PROPERTY_HINT_RANGE,"-1024,1024,1" ), "set_height", "get_height") ;
- ADD_PROPERTY( PropertyInfo( Variant::REAL, "ascent", PROPERTY_HINT_RANGE,"-1024,1024,1" ), "set_ascent", "get_ascent") ;
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "distance_field" ), "set_distance_field_hint", "is_distance_field_hint") ;
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE,"BitmapFont" ), "set_fallback", "get_fallback") ;
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_textures", "_get_textures");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "chars", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_chars", "_get_chars");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY, "kernings", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_kernings", "_get_kernings");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_height", "get_height");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ascent", PROPERTY_HINT_RANGE, "-1024,1024,1"), "set_ascent", "get_ascent");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "distance_field"), "set_distance_field_hint", "is_distance_field_hint");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE, "BitmapFont"), "set_fallback", "get_fallback");
}
BitmapFont::BitmapFont() {
clear();
-
-
-
}
-
BitmapFont::~BitmapFont() {
clear();
}
-
-
diff --git a/scene/resources/font.h b/scene/resources/font.h
index ad0f0176db..332017684d 100644
--- a/scene/resources/font.h
+++ b/scene/resources/font.h
@@ -29,50 +29,45 @@
#ifndef FONT_H
#define FONT_H
+#include "map.h"
#include "resource.h"
#include "scene/resources/texture.h"
-#include "map.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
class Font : public Resource {
- GDCLASS( Font, Resource );
+ GDCLASS(Font, Resource);
protected:
-
static void _bind_methods();
public:
+ virtual float get_height() const = 0;
- virtual float get_height() const=0;
+ virtual float get_ascent() const = 0;
+ virtual float get_descent() const = 0;
- virtual float get_ascent() const=0;
- virtual float get_descent() const=0;
+ virtual Size2 get_char_size(CharType p_char, CharType p_next = 0) const = 0;
+ Size2 get_string_size(const String &p_string) const;
- virtual Size2 get_char_size(CharType p_char,CharType p_next=0) const=0;
- Size2 get_string_size(const String& p_string) const;
+ virtual bool is_distance_field_hint() const = 0;
- virtual bool is_distance_field_hint() const=0;
-
- void draw(RID p_canvas_item, const Point2& p_pos, const String& p_text,const Color& p_modulate=Color(1,1,1),int p_clip_w=-1) const;
- void draw_halign(RID p_canvas_item, const Point2& p_pos, HAlign p_align,float p_width,const String& p_text,const Color& p_modulate=Color(1,1,1)) const;
- virtual float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char, CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const=0;
+ void draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate = Color(1, 1, 1), int p_clip_w = -1) const;
+ void draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate = Color(1, 1, 1)) const;
+ virtual float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const = 0;
void update_changes();
Font();
-
};
-
class BitmapFont : public Font {
- GDCLASS( BitmapFont, Font );
+ GDCLASS(BitmapFont, Font);
RES_BASE_EXTENSION("fnt");
- Vector< Ref<Texture> > textures;
+ Vector<Ref<Texture> > textures;
public:
struct Character {
@@ -83,47 +78,47 @@ public:
float h_align;
float advance;
- Character() { texture_idx=0; v_align=0; }
+ Character() {
+ texture_idx = 0;
+ v_align = 0;
+ }
};
struct KerningPairKey {
union {
struct {
- uint32_t A,B;
+ uint32_t A, B;
};
uint64_t pair;
};
- _FORCE_INLINE_ bool operator<(const KerningPairKey& p_r) const { return pair<p_r.pair; }
+ _FORCE_INLINE_ bool operator<(const KerningPairKey &p_r) const { return pair < p_r.pair; }
};
private:
-
-
- HashMap< CharType, Character > char_map;
- Map<KerningPairKey,int> kerning_map;
+ HashMap<CharType, Character> char_map;
+ Map<KerningPairKey, int> kerning_map;
float height;
float ascent;
bool distance_field_hint;
- void _set_chars(const PoolVector<int>& p_chars);
+ void _set_chars(const PoolVector<int> &p_chars);
PoolVector<int> _get_chars() const;
- void _set_kernings(const PoolVector<int>& p_kernings);
+ void _set_kernings(const PoolVector<int> &p_kernings);
PoolVector<int> _get_kernings() const;
- void _set_textures(const Vector<Variant> & p_textures);
+ void _set_textures(const Vector<Variant> &p_textures);
Vector<Variant> _get_textures() const;
Ref<BitmapFont> fallback;
-protected:
+protected:
static void _bind_methods();
public:
-
- Error create_from_fnt(const String& p_file);
+ Error create_from_fnt(const String &p_file);
void set_height(float p_height);
float get_height() const;
@@ -132,8 +127,8 @@ public:
float get_ascent() const;
float get_descent() const;
- void add_texture(const Ref<Texture>& p_texture);
- void add_char(CharType p_char, int p_texture_idx, const Rect2& p_rect, const Size2& p_align, float p_advance=-1);
+ void add_texture(const Ref<Texture> &p_texture);
+ void add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance = -1);
int get_character_count() const;
Vector<CharType> get_char_keys() const;
@@ -142,11 +137,11 @@ public:
int get_texture_count() const;
Ref<Texture> get_texture(int p_idx) const;
- void add_kerning_pair(CharType p_A,CharType p_B,int p_kerning);
- int get_kerning_pair(CharType p_A,CharType p_B) const;
+ void add_kerning_pair(CharType p_A, CharType p_B, int p_kerning);
+ int get_kerning_pair(CharType p_A, CharType p_B) const;
Vector<KerningPairKey> get_kerning_pair_keys() const;
- Size2 get_char_size(CharType p_char,CharType p_next=0) const;
+ Size2 get_char_size(CharType p_char, CharType p_next = 0) const;
void set_fallback(const Ref<BitmapFont> &p_fallback);
Ref<BitmapFont> get_fallback() const;
@@ -156,14 +151,10 @@ public:
void set_distance_field_hint(bool p_distance_field);
bool is_distance_field_hint() const;
- float draw_char(RID p_canvas_item, const Point2& p_pos, CharType p_char,CharType p_next=0,const Color& p_modulate=Color(1,1,1)) const;
+ float draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next = 0, const Color &p_modulate = Color(1, 1, 1)) const;
BitmapFont();
~BitmapFont();
};
-
-
-
-
#endif
diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp
index 3780c466a5..410f4962fa 100644
--- a/scene/resources/material.cpp
+++ b/scene/resources/material.cpp
@@ -36,7 +36,7 @@ RID Material::get_rid() const {
Material::Material() {
- material=VisualServer::get_singleton()->material_create();
+ material = VisualServer::get_singleton()->material_create();
}
Material::~Material() {
@@ -44,13 +44,12 @@ Material::~Material() {
VisualServer::get_singleton()->free(material);
}
-
/////////////////////////////////
-Mutex *FixedSpatialMaterial::material_mutex=NULL;
+Mutex *FixedSpatialMaterial::material_mutex = NULL;
SelfList<FixedSpatialMaterial>::List FixedSpatialMaterial::dirty_materials;
-Map<FixedSpatialMaterial::MaterialKey,FixedSpatialMaterial::ShaderData> FixedSpatialMaterial::shader_map;
-FixedSpatialMaterial::ShaderNames* FixedSpatialMaterial::shader_names=NULL;
+Map<FixedSpatialMaterial::MaterialKey, FixedSpatialMaterial::ShaderData> FixedSpatialMaterial::shader_map;
+FixedSpatialMaterial::ShaderNames *FixedSpatialMaterial::shader_names = NULL;
void FixedSpatialMaterial::init_shaders() {
@@ -58,303 +57,293 @@ void FixedSpatialMaterial::init_shaders() {
material_mutex = Mutex::create();
#endif
- shader_names = memnew( ShaderNames );
-
- shader_names->albedo="albedo";
- shader_names->specular="specular";
- shader_names->roughness="roughness";
- shader_names->metalness="metalness";
- shader_names->emission="emission";
- shader_names->emission_energy="emission_energy";
- shader_names->normal_scale="normal_scale";
- shader_names->rim="rim";
- shader_names->rim_tint="rim_tint";
- shader_names->clearcoat="clearcoat";
- shader_names->clearcoat_gloss="clearcoat_gloss";
- shader_names->anisotropy="anisotropy_ratio";
- shader_names->height_scale="height_scale";
- shader_names->subsurface_scattering_strength="subsurface_scattering_strength";
- shader_names->refraction="refraction";
- shader_names->refraction_roughness="refraction_roughness";
- shader_names->point_size="point_size";
- shader_names->uv1_scale="uv1_scale";
- shader_names->uv1_offset="uv1_offset";
- shader_names->uv2_scale="uv2_scale";
- shader_names->uv2_offset="uv2_offset";
-
- shader_names->texture_names[TEXTURE_ALBEDO]="texture_albedo";
- shader_names->texture_names[TEXTURE_SPECULAR]="texture_specular";
- shader_names->texture_names[TEXTURE_EMISSION]="texture_emission";
- shader_names->texture_names[TEXTURE_NORMAL]="texture_normal";
- shader_names->texture_names[TEXTURE_RIM]="texture_rim";
- shader_names->texture_names[TEXTURE_CLEARCOAT]="texture_clearcoat";
- shader_names->texture_names[TEXTURE_FLOWMAP]="texture_flowmap";
- shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION]="texture_ambient_occlusion";
- shader_names->texture_names[TEXTURE_HEIGHT]="texture_height";
- shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING]="texture_subsurface_scattering";
- shader_names->texture_names[TEXTURE_REFRACTION]="texture_refraction";
- shader_names->texture_names[TEXTURE_REFRACTION_ROUGHNESS]="texture_refraction_roughness";
- shader_names->texture_names[TEXTURE_DETAIL_MASK]="texture_detail_mask";
- shader_names->texture_names[TEXTURE_DETAIL_ALBEDO]="texture_detail_albedo";
- shader_names->texture_names[TEXTURE_DETAIL_NORMAL]="texture_detail_normal";
-
-}
-
-void FixedSpatialMaterial::finish_shaders(){
+ shader_names = memnew(ShaderNames);
+
+ shader_names->albedo = "albedo";
+ shader_names->specular = "specular";
+ shader_names->roughness = "roughness";
+ shader_names->metalness = "metalness";
+ shader_names->emission = "emission";
+ shader_names->emission_energy = "emission_energy";
+ shader_names->normal_scale = "normal_scale";
+ shader_names->rim = "rim";
+ shader_names->rim_tint = "rim_tint";
+ shader_names->clearcoat = "clearcoat";
+ shader_names->clearcoat_gloss = "clearcoat_gloss";
+ shader_names->anisotropy = "anisotropy_ratio";
+ shader_names->height_scale = "height_scale";
+ shader_names->subsurface_scattering_strength = "subsurface_scattering_strength";
+ shader_names->refraction = "refraction";
+ shader_names->refraction_roughness = "refraction_roughness";
+ shader_names->point_size = "point_size";
+ shader_names->uv1_scale = "uv1_scale";
+ shader_names->uv1_offset = "uv1_offset";
+ shader_names->uv2_scale = "uv2_scale";
+ shader_names->uv2_offset = "uv2_offset";
+
+ shader_names->texture_names[TEXTURE_ALBEDO] = "texture_albedo";
+ shader_names->texture_names[TEXTURE_SPECULAR] = "texture_specular";
+ shader_names->texture_names[TEXTURE_EMISSION] = "texture_emission";
+ shader_names->texture_names[TEXTURE_NORMAL] = "texture_normal";
+ shader_names->texture_names[TEXTURE_RIM] = "texture_rim";
+ shader_names->texture_names[TEXTURE_CLEARCOAT] = "texture_clearcoat";
+ shader_names->texture_names[TEXTURE_FLOWMAP] = "texture_flowmap";
+ shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION] = "texture_ambient_occlusion";
+ shader_names->texture_names[TEXTURE_HEIGHT] = "texture_height";
+ shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING] = "texture_subsurface_scattering";
+ shader_names->texture_names[TEXTURE_REFRACTION] = "texture_refraction";
+ shader_names->texture_names[TEXTURE_REFRACTION_ROUGHNESS] = "texture_refraction_roughness";
+ shader_names->texture_names[TEXTURE_DETAIL_MASK] = "texture_detail_mask";
+ shader_names->texture_names[TEXTURE_DETAIL_ALBEDO] = "texture_detail_albedo";
+ shader_names->texture_names[TEXTURE_DETAIL_NORMAL] = "texture_detail_normal";
+}
+
+void FixedSpatialMaterial::finish_shaders() {
#ifndef NO_THREADS
- memdelete( material_mutex );
+ memdelete(material_mutex);
#endif
- memdelete( shader_names );
-
+ memdelete(shader_names);
}
-
-
void FixedSpatialMaterial::_update_shader() {
- dirty_materials.remove( &element );
+ dirty_materials.remove(&element);
MaterialKey mk = _compute_key();
- if (mk.key==current_key.key)
+ if (mk.key == current_key.key)
return; //no update required in the end
if (shader_map.has(current_key)) {
shader_map[current_key].users--;
- if (shader_map[current_key].users==0) {
+ if (shader_map[current_key].users == 0) {
//deallocate shader, as it's no longer in use
VS::get_singleton()->free(shader_map[current_key].shader);
shader_map.erase(current_key);
}
}
- current_key=mk;
+ current_key = mk;
if (shader_map.has(mk)) {
- VS::get_singleton()->material_set_shader(_get_material(),shader_map[mk].shader);
+ VS::get_singleton()->material_set_shader(_get_material(), shader_map[mk].shader);
shader_map[mk].users++;
return;
}
//must create a shader!
- String code="render_mode ";
- switch(blend_mode) {
- case BLEND_MODE_MIX: code+="blend_mix"; break;
- case BLEND_MODE_ADD: code+="blend_add"; break;
- case BLEND_MODE_SUB: code+="blend_sub"; break;
- case BLEND_MODE_MUL: code+="blend_mul"; break;
+ String code = "render_mode ";
+ switch (blend_mode) {
+ case BLEND_MODE_MIX: code += "blend_mix"; break;
+ case BLEND_MODE_ADD: code += "blend_add"; break;
+ case BLEND_MODE_SUB: code += "blend_sub"; break;
+ case BLEND_MODE_MUL: code += "blend_mul"; break;
}
- switch(depth_draw_mode) {
- case DEPTH_DRAW_OPAQUE_ONLY: code+=",depth_draw_opaque"; break;
- case DEPTH_DRAW_ALWAYS: code+=",depth_draw_always"; break;
- case DEPTH_DRAW_DISABLED: code+=",depth_draw_never"; break;
- case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code+=",depth_draw_alpha_prepass"; break;
+ switch (depth_draw_mode) {
+ case DEPTH_DRAW_OPAQUE_ONLY: code += ",depth_draw_opaque"; break;
+ case DEPTH_DRAW_ALWAYS: code += ",depth_draw_always"; break;
+ case DEPTH_DRAW_DISABLED: code += ",depth_draw_never"; break;
+ case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code += ",depth_draw_alpha_prepass"; break;
}
- switch(cull_mode) {
- case CULL_BACK: code+=",cull_back"; break;
- case CULL_FRONT: code+=",cull_front"; break;
- case CULL_DISABLED: code+=",cull_disabled"; break;
-
+ switch (cull_mode) {
+ case CULL_BACK: code += ",cull_back"; break;
+ case CULL_FRONT: code += ",cull_front"; break;
+ case CULL_DISABLED: code += ",cull_disabled"; break;
}
if (flags[FLAG_UNSHADED]) {
- code+=",unshaded";
+ code += ",unshaded";
}
if (flags[FLAG_ONTOP]) {
- code+=",ontop";
+ code += ",ontop";
}
- code+=";\n";
-
+ code += ";\n";
- code+="uniform vec4 albedo : hint_color;\n";
- code+="uniform sampler2D texture_albedo : hint_albedo;\n";
- if (specular_mode==SPECULAR_MODE_SPECULAR) {
- code+="uniform vec4 specular : hint_color;\n";
+ code += "uniform vec4 albedo : hint_color;\n";
+ code += "uniform sampler2D texture_albedo : hint_albedo;\n";
+ if (specular_mode == SPECULAR_MODE_SPECULAR) {
+ code += "uniform vec4 specular : hint_color;\n";
} else {
- code+="uniform float metalness;\n";
+ code += "uniform float metalness;\n";
}
- code+="uniform float roughness : hint_range(0,1);\n";
- code+="uniform float point_size : hint_range(0,128);\n";
- code+="uniform sampler2D texture_specular : hint_white;\n";
- code+="uniform vec2 uv1_scale;\n";
- code+="uniform vec2 uv1_offset;\n";
- code+="uniform vec2 uv2_scale;\n";
- code+="uniform vec2 uv2_offset;\n";
+ code += "uniform float roughness : hint_range(0,1);\n";
+ code += "uniform float point_size : hint_range(0,128);\n";
+ code += "uniform sampler2D texture_specular : hint_white;\n";
+ code += "uniform vec2 uv1_scale;\n";
+ code += "uniform vec2 uv1_offset;\n";
+ code += "uniform vec2 uv2_scale;\n";
+ code += "uniform vec2 uv2_offset;\n";
if (features[FEATURE_EMISSION]) {
- code+="uniform sampler2D texture_emission : hint_black_albedo;\n";
- code+="uniform vec4 emission : hint_color;\n";
- code+="uniform float emission_energy;\n";
+ code += "uniform sampler2D texture_emission : hint_black_albedo;\n";
+ code += "uniform vec4 emission : hint_color;\n";
+ code += "uniform float emission_energy;\n";
}
if (features[FEATURE_NORMAL_MAPPING]) {
- code+="uniform sampler2D texture_normal : hint_normal;\n";
- code+="uniform float normal_scale : hint_range(-16,16);\n";
+ code += "uniform sampler2D texture_normal : hint_normal;\n";
+ code += "uniform float normal_scale : hint_range(-16,16);\n";
}
if (features[FEATURE_RIM]) {
- code+="uniform float rim : hint_range(0,1);\n";
- code+="uniform float rim_tint : hint_range(0,1);\n";
- code+="uniform sampler2D texture_rim : hint_white;\n";
+ code += "uniform float rim : hint_range(0,1);\n";
+ code += "uniform float rim_tint : hint_range(0,1);\n";
+ code += "uniform sampler2D texture_rim : hint_white;\n";
}
if (features[FEATURE_CLEARCOAT]) {
- code+="uniform float clearcoat : hint_range(0,1);\n";
- code+="uniform float clearcoat_gloss : hint_range(0,1);\n";
- code+="uniform sampler2D texture_clearcoat : hint_white;\n";
+ code += "uniform float clearcoat : hint_range(0,1);\n";
+ code += "uniform float clearcoat_gloss : hint_range(0,1);\n";
+ code += "uniform sampler2D texture_clearcoat : hint_white;\n";
}
if (features[FEATURE_ANISOTROPY]) {
- code+="uniform float anisotropy_ratio : hint_range(0,256);\n";
- code+="uniform sampler2D texture_flowmap : hint_aniso;\n";
+ code += "uniform float anisotropy_ratio : hint_range(0,256);\n";
+ code += "uniform sampler2D texture_flowmap : hint_aniso;\n";
}
if (features[FEATURE_AMBIENT_OCCLUSION]) {
- code+="uniform sampler2D texture_ambient_occlusion : hint_white;\n";
+ code += "uniform sampler2D texture_ambient_occlusion : hint_white;\n";
}
if (features[FEATURE_DETAIL]) {
- code+="uniform sampler2D texture_detail_albedo : hint_albedo;\n";
- code+="uniform sampler2D texture_detail_normal : hint_normal;\n";
- code+="uniform sampler2D texture_detail_mask : hint_white;\n";
+ code += "uniform sampler2D texture_detail_albedo : hint_albedo;\n";
+ code += "uniform sampler2D texture_detail_normal : hint_normal;\n";
+ code += "uniform sampler2D texture_detail_mask : hint_white;\n";
}
if (features[FEATURE_SUBSURACE_SCATTERING]) {
- code+="uniform float subsurface_scattering_strength : hint_range(0,1);\n";
- code+="uniform sampler2D texture_subsurface_scattering : hint_white;\n";
-
+ code += "uniform float subsurface_scattering_strength : hint_range(0,1);\n";
+ code += "uniform sampler2D texture_subsurface_scattering : hint_white;\n";
}
+ code += "\n\n";
- code+="\n\n";
-
- code+="void vertex() {\n";
+ code += "void vertex() {\n";
if (flags[FLAG_SRGB_VERTEX_COLOR]) {
- code+="\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n";
+ code += "\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n";
}
if (flags[FLAG_USE_POINT_SIZE]) {
- code+="\tPOINT_SIZE=point_size;\n";
+ code += "\tPOINT_SIZE=point_size;\n";
}
- code+="\tUV=UV*uv1_scale+uv1_offset;\n";
- if (detail_uv==DETAIL_UV_2) {
- code+="\tUV2=UV2*uv2_scale+uv2_offset;\n";
+ code += "\tUV=UV*uv1_scale+uv1_offset;\n";
+ if (detail_uv == DETAIL_UV_2) {
+ code += "\tUV2=UV2*uv2_scale+uv2_offset;\n";
}
- code+="}\n";
- code+="\n\n";
- code+="void fragment() {\n";
+ code += "}\n";
+ code += "\n\n";
+ code += "void fragment() {\n";
if (flags[FLAG_USE_POINT_SIZE]) {
- code+="\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n";
+ code += "\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n";
} else {
- code+="\tvec4 albedo_tex = texture(texture_albedo,UV);\n";
+ code += "\tvec4 albedo_tex = texture(texture_albedo,UV);\n";
}
if (flags[FLAG_ALBEDO_FROM_VERTEX_COLOR]) {
- code+="\talbedo_tex *= COLOR;\n";
+ code += "\talbedo_tex *= COLOR;\n";
}
- code+="\tALBEDO = albedo.rgb * albedo_tex.rgb;\n";
+ code += "\tALBEDO = albedo.rgb * albedo_tex.rgb;\n";
if (features[FEATURE_TRANSPARENT]) {
- code+="\tALPHA = albedo.a * albedo_tex.a;\n";
+ code += "\tALPHA = albedo.a * albedo_tex.a;\n";
}
if (features[FEATURE_EMISSION]) {
- code+="\tEMISSION = (emission.rgb+texture(texture_emission,UV).rgb)*emission_energy;\n";
+ code += "\tEMISSION = (emission.rgb+texture(texture_emission,UV).rgb)*emission_energy;\n";
}
if (features[FEATURE_NORMAL_MAPPING]) {
- code+="\tNORMALMAP = texture(texture_normal,UV).rgb;\n";
- code+="\tNORMALMAP_DEPTH = normal_scale;\n";
+ code += "\tNORMALMAP = texture(texture_normal,UV).rgb;\n";
+ code += "\tNORMALMAP_DEPTH = normal_scale;\n";
}
if (features[FEATURE_RIM]) {
- code+="\tvec2 rim_tex = texture(texture_rim,UV).xw;\n";
- code+="\tRIM = rim*rim_tex.x;";
- code+="\tRIM_TINT = rim_tint*rim_tex.y;\n";
+ code += "\tvec2 rim_tex = texture(texture_rim,UV).xw;\n";
+ code += "\tRIM = rim*rim_tex.x;";
+ code += "\tRIM_TINT = rim_tint*rim_tex.y;\n";
}
if (features[FEATURE_CLEARCOAT]) {
- code+="\tvec2 clearcoat_tex = texture(texture_clearcoat,UV).xw;\n";
- code+="\tCLEARCOAT = clearcoat*clearcoat_tex.x;";
- code+="\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n";
+ code += "\tvec2 clearcoat_tex = texture(texture_clearcoat,UV).xw;\n";
+ code += "\tCLEARCOAT = clearcoat*clearcoat_tex.x;";
+ code += "\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n";
}
if (features[FEATURE_ANISOTROPY]) {
- code+="\tvec4 anisotropy_tex = texture(texture_flowmap,UV);\n";
- code+="\tANISOTROPY = anisotropy_ratio*anisotropy_tex.a;\n";
- code+="\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n";
+ code += "\tvec4 anisotropy_tex = texture(texture_flowmap,UV);\n";
+ code += "\tANISOTROPY = anisotropy_ratio*anisotropy_tex.a;\n";
+ code += "\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n";
}
if (features[FEATURE_AMBIENT_OCCLUSION]) {
- code+="\tAO = texture(texture_ambient_occlusion,UV).r;\n";
+ code += "\tAO = texture(texture_ambient_occlusion,UV).r;\n";
}
if (features[FEATURE_SUBSURACE_SCATTERING]) {
- code+="\tfloat sss_tex = texture(texture_subsurface_scattering,UV).r;\n";
- code+="\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n";
+ code += "\tfloat sss_tex = texture(texture_subsurface_scattering,UV).r;\n";
+ code += "\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n";
}
if (features[FEATURE_DETAIL]) {
- String det_uv=detail_uv==DETAIL_UV_1?"UV":"UV2";
- code+="\tvec4 detail_tex = texture(texture_detail_albedo,"+det_uv+");\n";
- code+="\tvec4 detail_norm_tex = texture(texture_detail_normal,"+det_uv+");\n";
- code+="\tvec4 detail_mask_tex = texture(texture_detail_mask,UV);\n";
+ String det_uv = detail_uv == DETAIL_UV_1 ? "UV" : "UV2";
+ code += "\tvec4 detail_tex = texture(texture_detail_albedo," + det_uv + ");\n";
+ code += "\tvec4 detail_norm_tex = texture(texture_detail_normal," + det_uv + ");\n";
+ code += "\tvec4 detail_mask_tex = texture(texture_detail_mask,UV);\n";
- switch(detail_blend_mode) {
+ switch (detail_blend_mode) {
case BLEND_MODE_MIX: {
- code+="\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n";
+ code += "\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n";
} break;
case BLEND_MODE_ADD: {
- code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n";
+ code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n";
} break;
case BLEND_MODE_SUB: {
- code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n";
+ code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n";
} break;
case BLEND_MODE_MUL: {
- code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n";
+ code += "\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n";
} break;
-
}
- code+="\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n";
+ code += "\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n";
- code+="\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n";
- code+="\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n";
+ code += "\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n";
+ code += "\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n";
}
- if (specular_mode==SPECULAR_MODE_SPECULAR) {
+ if (specular_mode == SPECULAR_MODE_SPECULAR) {
- code+="\tvec4 specular_tex = texture(texture_specular,UV);\n";
- code+="\tSPECULAR = specular.rgb * specular_tex.rgb;\n";
- code+="\tROUGHNESS = specular_tex.a * roughness;\n";
+ code += "\tvec4 specular_tex = texture(texture_specular,UV);\n";
+ code += "\tSPECULAR = specular.rgb * specular_tex.rgb;\n";
+ code += "\tROUGHNESS = specular_tex.a * roughness;\n";
} else {
- code+="\tvec4 specular_tex = texture(texture_specular,UV);\n";
- code+="\tSPECULAR = vec3(ALBEDO.rgb * metalness * specular_tex.r);\n";
- code+="\tROUGHNESS = specular_tex.a * roughness;\n";
+ code += "\tvec4 specular_tex = texture(texture_specular,UV);\n";
+ code += "\tSPECULAR = vec3(ALBEDO.rgb * metalness * specular_tex.r);\n";
+ code += "\tROUGHNESS = specular_tex.a * roughness;\n";
}
- code+="}\n";
+ code += "}\n";
ShaderData shader_data;
shader_data.shader = VS::get_singleton()->shader_create(VS::SHADER_SPATIAL);
- shader_data.users=1;
-
- VS::get_singleton()->shader_set_code( shader_data.shader, code );
+ shader_data.users = 1;
- shader_map[mk]=shader_data;
+ VS::get_singleton()->shader_set_code(shader_data.shader, code);
- VS::get_singleton()->material_set_shader(_get_material(),shader_data.shader);
+ shader_map[mk] = shader_data;
+ VS::get_singleton()->material_set_shader(_get_material(), shader_data.shader);
}
void FixedSpatialMaterial::flush_changes() {
@@ -382,38 +371,36 @@ void FixedSpatialMaterial::_queue_shader_change() {
if (material_mutex)
material_mutex->unlock();
-
-
}
bool FixedSpatialMaterial::_is_shader_dirty() const {
- bool dirty=false;
+ bool dirty = false;
if (material_mutex)
material_mutex->lock();
- dirty=element.in_list();
+ dirty = element.in_list();
if (material_mutex)
material_mutex->unlock();
return dirty;
}
-void FixedSpatialMaterial::set_albedo(const Color& p_albedo) {
+void FixedSpatialMaterial::set_albedo(const Color &p_albedo) {
- albedo=p_albedo;
+ albedo = p_albedo;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->albedo,p_albedo);
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->albedo, p_albedo);
}
-Color FixedSpatialMaterial::get_albedo() const{
+Color FixedSpatialMaterial::get_albedo() const {
return albedo;
}
void FixedSpatialMaterial::set_specular_mode(SpecularMode p_mode) {
- specular_mode=p_mode;
+ specular_mode = p_mode;
_change_notify();
_queue_shader_change();
}
@@ -423,167 +410,146 @@ FixedSpatialMaterial::SpecularMode FixedSpatialMaterial::get_specular_mode() con
return specular_mode;
}
-void FixedSpatialMaterial::set_specular(const Color& p_specular){
-
- specular=p_specular;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->specular,p_specular);
+void FixedSpatialMaterial::set_specular(const Color &p_specular) {
+ specular = p_specular;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->specular, p_specular);
}
-Color FixedSpatialMaterial::get_specular() const{
+Color FixedSpatialMaterial::get_specular() const {
return specular;
}
-void FixedSpatialMaterial::set_roughness(float p_roughness){
-
- roughness=p_roughness;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->roughness,p_roughness);
+void FixedSpatialMaterial::set_roughness(float p_roughness) {
+ roughness = p_roughness;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->roughness, p_roughness);
}
-
-float FixedSpatialMaterial::get_roughness() const{
+float FixedSpatialMaterial::get_roughness() const {
return roughness;
}
-void FixedSpatialMaterial::set_metalness(float p_metalness){
+void FixedSpatialMaterial::set_metalness(float p_metalness) {
- metalness=p_metalness;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->metalness,p_metalness);
+ metalness = p_metalness;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->metalness, p_metalness);
}
-
-float FixedSpatialMaterial::get_metalness() const{
+float FixedSpatialMaterial::get_metalness() const {
return metalness;
}
-void FixedSpatialMaterial::set_emission(const Color& p_emission){
-
- emission=p_emission;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->emission,p_emission);
+void FixedSpatialMaterial::set_emission(const Color &p_emission) {
+ emission = p_emission;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->emission, p_emission);
}
-Color FixedSpatialMaterial::get_emission() const{
+Color FixedSpatialMaterial::get_emission() const {
return emission;
}
+void FixedSpatialMaterial::set_emission_energy(float p_emission_energy) {
-void FixedSpatialMaterial::set_emission_energy(float p_emission_energy){
-
- emission_energy=p_emission_energy;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->emission_energy,p_emission_energy);
-
+ emission_energy = p_emission_energy;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->emission_energy, p_emission_energy);
}
-float FixedSpatialMaterial::get_emission_energy() const{
+float FixedSpatialMaterial::get_emission_energy() const {
return emission_energy;
}
-void FixedSpatialMaterial::set_normal_scale(float p_normal_scale){
-
- normal_scale=p_normal_scale;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->normal_scale,p_normal_scale);
+void FixedSpatialMaterial::set_normal_scale(float p_normal_scale) {
+ normal_scale = p_normal_scale;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->normal_scale, p_normal_scale);
}
-float FixedSpatialMaterial::get_normal_scale() const{
+float FixedSpatialMaterial::get_normal_scale() const {
return normal_scale;
}
-void FixedSpatialMaterial::set_rim(float p_rim){
-
- rim=p_rim;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->rim,p_rim);
-
+void FixedSpatialMaterial::set_rim(float p_rim) {
+ rim = p_rim;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->rim, p_rim);
}
-float FixedSpatialMaterial::get_rim() const{
+float FixedSpatialMaterial::get_rim() const {
return rim;
}
-void FixedSpatialMaterial::set_rim_tint(float p_rim_tint){
-
- rim_tint=p_rim_tint;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->rim_tint,p_rim_tint);
+void FixedSpatialMaterial::set_rim_tint(float p_rim_tint) {
+ rim_tint = p_rim_tint;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->rim_tint, p_rim_tint);
}
-float FixedSpatialMaterial::get_rim_tint() const{
+float FixedSpatialMaterial::get_rim_tint() const {
return rim_tint;
}
-void FixedSpatialMaterial::set_clearcoat(float p_clearcoat){
-
- clearcoat=p_clearcoat;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat,p_clearcoat);
+void FixedSpatialMaterial::set_clearcoat(float p_clearcoat) {
+ clearcoat = p_clearcoat;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat, p_clearcoat);
}
-float FixedSpatialMaterial::get_clearcoat() const{
+float FixedSpatialMaterial::get_clearcoat() const {
return clearcoat;
}
-void FixedSpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss){
-
- clearcoat_gloss=p_clearcoat_gloss;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat_gloss,p_clearcoat_gloss);
-
+void FixedSpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss) {
+ clearcoat_gloss = p_clearcoat_gloss;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->clearcoat_gloss, p_clearcoat_gloss);
}
-float FixedSpatialMaterial::get_clearcoat_gloss() const{
+float FixedSpatialMaterial::get_clearcoat_gloss() const {
return clearcoat_gloss;
}
-void FixedSpatialMaterial::set_anisotropy(float p_anisotropy){
-
- anisotropy=p_anisotropy;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->anisotropy,p_anisotropy);
+void FixedSpatialMaterial::set_anisotropy(float p_anisotropy) {
+ anisotropy = p_anisotropy;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->anisotropy, p_anisotropy);
}
-float FixedSpatialMaterial::get_anisotropy() const{
+float FixedSpatialMaterial::get_anisotropy() const {
return anisotropy;
}
-void FixedSpatialMaterial::set_height_scale(float p_height_scale){
-
- height_scale=p_height_scale;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->height_scale,p_height_scale);
-
+void FixedSpatialMaterial::set_height_scale(float p_height_scale) {
+ height_scale = p_height_scale;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->height_scale, p_height_scale);
}
-float FixedSpatialMaterial::get_height_scale() const{
+float FixedSpatialMaterial::get_height_scale() const {
return height_scale;
}
+void FixedSpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength) {
-void FixedSpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength){
-
- subsurface_scattering_strength=p_subsurface_scattering_strength;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->subsurface_scattering_strength,subsurface_scattering_strength);
-
-
+ subsurface_scattering_strength = p_subsurface_scattering_strength;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->subsurface_scattering_strength, subsurface_scattering_strength);
}
-float FixedSpatialMaterial::get_subsurface_scattering_strength() const{
+float FixedSpatialMaterial::get_subsurface_scattering_strength() const {
return subsurface_scattering_strength;
}
-void FixedSpatialMaterial::set_refraction(float p_refraction){
-
- refraction=p_refraction;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction,refraction);
+void FixedSpatialMaterial::set_refraction(float p_refraction) {
+ refraction = p_refraction;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction, refraction);
}
float FixedSpatialMaterial::get_refraction() const {
@@ -593,10 +559,8 @@ float FixedSpatialMaterial::get_refraction() const {
void FixedSpatialMaterial::set_refraction_roughness(float p_refraction_roughness) {
- refraction_roughness=p_refraction_roughness;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction_roughness,refraction_roughness);
-
-
+ refraction_roughness = p_refraction_roughness;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->refraction_roughness, refraction_roughness);
}
float FixedSpatialMaterial::get_refraction_roughness() const {
@@ -605,10 +569,10 @@ float FixedSpatialMaterial::get_refraction_roughness() const {
void FixedSpatialMaterial::set_detail_uv(DetailUV p_detail_uv) {
- if (detail_uv==p_detail_uv)
+ if (detail_uv == p_detail_uv)
return;
- detail_uv=p_detail_uv;
+ detail_uv = p_detail_uv;
_queue_shader_change();
}
FixedSpatialMaterial::DetailUV FixedSpatialMaterial::get_detail_uv() const {
@@ -618,10 +582,10 @@ FixedSpatialMaterial::DetailUV FixedSpatialMaterial::get_detail_uv() const {
void FixedSpatialMaterial::set_blend_mode(BlendMode p_mode) {
- if (blend_mode==p_mode)
+ if (blend_mode == p_mode)
return;
- blend_mode=p_mode;
+ blend_mode = p_mode;
_queue_shader_change();
}
FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_blend_mode() const {
@@ -631,7 +595,7 @@ FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_blend_mode() const {
void FixedSpatialMaterial::set_detail_blend_mode(BlendMode p_mode) {
- detail_blend_mode=p_mode;
+ detail_blend_mode = p_mode;
_queue_shader_change();
}
FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_detail_blend_mode() const {
@@ -641,10 +605,10 @@ FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_detail_blend_mode() co
void FixedSpatialMaterial::set_depth_draw_mode(DepthDrawMode p_mode) {
- if (depth_draw_mode==p_mode)
+ if (depth_draw_mode == p_mode)
return;
- depth_draw_mode=p_mode;
+ depth_draw_mode = p_mode;
_queue_shader_change();
}
FixedSpatialMaterial::DepthDrawMode FixedSpatialMaterial::get_depth_draw_mode() const {
@@ -654,10 +618,10 @@ FixedSpatialMaterial::DepthDrawMode FixedSpatialMaterial::get_depth_draw_mode()
void FixedSpatialMaterial::set_cull_mode(CullMode p_mode) {
- if (cull_mode==p_mode)
+ if (cull_mode == p_mode)
return;
- cull_mode=p_mode;
+ cull_mode = p_mode;
_queue_shader_change();
}
FixedSpatialMaterial::CullMode FixedSpatialMaterial::get_cull_mode() const {
@@ -667,10 +631,10 @@ FixedSpatialMaterial::CullMode FixedSpatialMaterial::get_cull_mode() const {
void FixedSpatialMaterial::set_diffuse_mode(DiffuseMode p_mode) {
- if (diffuse_mode==p_mode)
+ if (diffuse_mode == p_mode)
return;
- diffuse_mode=p_mode;
+ diffuse_mode = p_mode;
_queue_shader_change();
}
FixedSpatialMaterial::DiffuseMode FixedSpatialMaterial::get_diffuse_mode() const {
@@ -678,91 +642,84 @@ FixedSpatialMaterial::DiffuseMode FixedSpatialMaterial::get_diffuse_mode() const
return diffuse_mode;
}
-void FixedSpatialMaterial::set_flag(Flags p_flag,bool p_enabled) {
+void FixedSpatialMaterial::set_flag(Flags p_flag, bool p_enabled) {
- ERR_FAIL_INDEX(p_flag,FLAG_MAX);
+ ERR_FAIL_INDEX(p_flag, FLAG_MAX);
- if (flags[p_flag]==p_enabled)
+ if (flags[p_flag] == p_enabled)
return;
- flags[p_flag]=p_enabled;
+ flags[p_flag] = p_enabled;
_queue_shader_change();
}
bool FixedSpatialMaterial::get_flag(Flags p_flag) const {
- ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false);
+ ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false);
return flags[p_flag];
}
-void FixedSpatialMaterial::set_feature(Feature p_feature,bool p_enabled) {
+void FixedSpatialMaterial::set_feature(Feature p_feature, bool p_enabled) {
- ERR_FAIL_INDEX(p_feature,FEATURE_MAX);
- if (features[p_feature]==p_enabled)
+ ERR_FAIL_INDEX(p_feature, FEATURE_MAX);
+ if (features[p_feature] == p_enabled)
return;
- features[p_feature]=p_enabled;
+ features[p_feature] = p_enabled;
_change_notify();
_queue_shader_change();
-
-
}
bool FixedSpatialMaterial::get_feature(Feature p_feature) const {
- ERR_FAIL_INDEX_V(p_feature,FEATURE_MAX,false);
+ ERR_FAIL_INDEX_V(p_feature, FEATURE_MAX, false);
return features[p_feature];
}
-
-
void FixedSpatialMaterial::set_texture(TextureParam p_param, const Ref<Texture> &p_texture) {
- ERR_FAIL_INDEX(p_param,TEXTURE_MAX);
- textures[p_param]=p_texture;
+ ERR_FAIL_INDEX(p_param, TEXTURE_MAX);
+ textures[p_param] = p_texture;
RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID();
- VS::get_singleton()->material_set_param(_get_material(),shader_names->texture_names[p_param],rid);
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->texture_names[p_param], rid);
}
Ref<Texture> FixedSpatialMaterial::get_texture(TextureParam p_param) const {
- ERR_FAIL_INDEX_V(p_param,TEXTURE_MAX,Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_param, TEXTURE_MAX, Ref<Texture>());
return textures[p_param];
}
-
-void FixedSpatialMaterial::_validate_feature(const String& text, Feature feature,PropertyInfo& property) const {
- if (property.name.begins_with(text) && property.name!=text+"_enabled" && !features[feature]) {
- property.usage=0;
+void FixedSpatialMaterial::_validate_feature(const String &text, Feature feature, PropertyInfo &property) const {
+ if (property.name.begins_with(text) && property.name != text + "_enabled" && !features[feature]) {
+ property.usage = 0;
}
-
}
-void FixedSpatialMaterial::_validate_property(PropertyInfo& property) const {
- _validate_feature("normal",FEATURE_NORMAL_MAPPING,property);
- _validate_feature("emission",FEATURE_EMISSION,property);
- _validate_feature("rim",FEATURE_RIM,property);
- _validate_feature("clearcoat",FEATURE_CLEARCOAT,property);
- _validate_feature("anisotropy",FEATURE_ANISOTROPY,property);
- _validate_feature("ao",FEATURE_AMBIENT_OCCLUSION,property);
- _validate_feature("height",FEATURE_HEIGHT_MAPPING,property);
- _validate_feature("subsurf_scatter",FEATURE_SUBSURACE_SCATTERING,property);
- _validate_feature("refraction",FEATURE_REFRACTION,property);
- _validate_feature("detail",FEATURE_DETAIL,property);
-
- if (property.name=="specular/color" && specular_mode==SPECULAR_MODE_METALLIC) {
- property.usage=0;
+void FixedSpatialMaterial::_validate_property(PropertyInfo &property) const {
+ _validate_feature("normal", FEATURE_NORMAL_MAPPING, property);
+ _validate_feature("emission", FEATURE_EMISSION, property);
+ _validate_feature("rim", FEATURE_RIM, property);
+ _validate_feature("clearcoat", FEATURE_CLEARCOAT, property);
+ _validate_feature("anisotropy", FEATURE_ANISOTROPY, property);
+ _validate_feature("ao", FEATURE_AMBIENT_OCCLUSION, property);
+ _validate_feature("height", FEATURE_HEIGHT_MAPPING, property);
+ _validate_feature("subsurf_scatter", FEATURE_SUBSURACE_SCATTERING, property);
+ _validate_feature("refraction", FEATURE_REFRACTION, property);
+ _validate_feature("detail", FEATURE_DETAIL, property);
+
+ if (property.name == "specular/color" && specular_mode == SPECULAR_MODE_METALLIC) {
+ property.usage = 0;
}
- if (property.name=="specular/metalness" && specular_mode==SPECULAR_MODE_SPECULAR) {
- property.usage=0;
+ if (property.name == "specular/metalness" && specular_mode == SPECULAR_MODE_SPECULAR) {
+ property.usage = 0;
}
-
}
void FixedSpatialMaterial::set_line_width(float p_line_width) {
- line_width=p_line_width;
- VS::get_singleton()->material_set_line_width(_get_material(),line_width);
+ line_width = p_line_width;
+ VS::get_singleton()->material_set_line_width(_get_material(), line_width);
}
float FixedSpatialMaterial::get_line_width() const {
@@ -772,8 +729,8 @@ float FixedSpatialMaterial::get_line_width() const {
void FixedSpatialMaterial::set_point_size(float p_point_size) {
- point_size=p_point_size;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->point_size,p_point_size);
+ point_size = p_point_size;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->point_size, p_point_size);
}
float FixedSpatialMaterial::get_point_size() const {
@@ -781,321 +738,312 @@ float FixedSpatialMaterial::get_point_size() const {
return point_size;
}
+void FixedSpatialMaterial::set_uv1_scale(const Vector2 &p_scale) {
-void FixedSpatialMaterial::set_uv1_scale(const Vector2& p_scale) {
-
- uv1_scale=p_scale;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_scale,p_scale);
+ uv1_scale = p_scale;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_scale, p_scale);
}
-Vector2 FixedSpatialMaterial::get_uv1_scale() const{
+Vector2 FixedSpatialMaterial::get_uv1_scale() const {
return uv1_scale;
}
-void FixedSpatialMaterial::set_uv1_offset(const Vector2& p_offset){
-
- uv1_offset=p_offset;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_offset,p_offset);
+void FixedSpatialMaterial::set_uv1_offset(const Vector2 &p_offset) {
+ uv1_offset = p_offset;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->uv1_offset, p_offset);
}
-Vector2 FixedSpatialMaterial::get_uv1_offset() const{
+Vector2 FixedSpatialMaterial::get_uv1_offset() const {
return uv1_offset;
}
+void FixedSpatialMaterial::set_uv2_scale(const Vector2 &p_scale) {
-void FixedSpatialMaterial::set_uv2_scale(const Vector2& p_scale) {
-
- uv2_scale=p_scale;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_scale,p_scale);
+ uv2_scale = p_scale;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_scale, p_scale);
}
-Vector2 FixedSpatialMaterial::get_uv2_scale() const{
+Vector2 FixedSpatialMaterial::get_uv2_scale() const {
return uv2_scale;
}
-void FixedSpatialMaterial::set_uv2_offset(const Vector2& p_offset){
-
- uv2_offset=p_offset;
- VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_offset,p_offset);
+void FixedSpatialMaterial::set_uv2_offset(const Vector2 &p_offset) {
+ uv2_offset = p_offset;
+ VS::get_singleton()->material_set_param(_get_material(), shader_names->uv2_offset, p_offset);
}
-Vector2 FixedSpatialMaterial::get_uv2_offset() const{
+Vector2 FixedSpatialMaterial::get_uv2_offset() const {
return uv2_offset;
}
void FixedSpatialMaterial::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_albedo", "albedo"), &FixedSpatialMaterial::set_albedo);
+ ClassDB::bind_method(D_METHOD("get_albedo"), &FixedSpatialMaterial::get_albedo);
- ClassDB::bind_method(D_METHOD("set_albedo","albedo"),&FixedSpatialMaterial::set_albedo);
- ClassDB::bind_method(D_METHOD("get_albedo"),&FixedSpatialMaterial::get_albedo);
+ ClassDB::bind_method(D_METHOD("set_specular_mode", "specular_mode"), &FixedSpatialMaterial::set_specular_mode);
+ ClassDB::bind_method(D_METHOD("get_specular_mode"), &FixedSpatialMaterial::get_specular_mode);
- ClassDB::bind_method(D_METHOD("set_specular_mode","specular_mode"),&FixedSpatialMaterial::set_specular_mode);
- ClassDB::bind_method(D_METHOD("get_specular_mode"),&FixedSpatialMaterial::get_specular_mode);
+ ClassDB::bind_method(D_METHOD("set_specular", "specular"), &FixedSpatialMaterial::set_specular);
+ ClassDB::bind_method(D_METHOD("get_specular"), &FixedSpatialMaterial::get_specular);
- ClassDB::bind_method(D_METHOD("set_specular","specular"),&FixedSpatialMaterial::set_specular);
- ClassDB::bind_method(D_METHOD("get_specular"),&FixedSpatialMaterial::get_specular);
+ ClassDB::bind_method(D_METHOD("set_metalness", "metalness"), &FixedSpatialMaterial::set_metalness);
+ ClassDB::bind_method(D_METHOD("get_metalness"), &FixedSpatialMaterial::get_metalness);
- ClassDB::bind_method(D_METHOD("set_metalness","metalness"),&FixedSpatialMaterial::set_metalness);
- ClassDB::bind_method(D_METHOD("get_metalness"),&FixedSpatialMaterial::get_metalness);
+ ClassDB::bind_method(D_METHOD("set_roughness", "roughness"), &FixedSpatialMaterial::set_roughness);
+ ClassDB::bind_method(D_METHOD("get_roughness"), &FixedSpatialMaterial::get_roughness);
- ClassDB::bind_method(D_METHOD("set_roughness","roughness"),&FixedSpatialMaterial::set_roughness);
- ClassDB::bind_method(D_METHOD("get_roughness"),&FixedSpatialMaterial::get_roughness);
+ ClassDB::bind_method(D_METHOD("set_emission", "emission"), &FixedSpatialMaterial::set_emission);
+ ClassDB::bind_method(D_METHOD("get_emission"), &FixedSpatialMaterial::get_emission);
- ClassDB::bind_method(D_METHOD("set_emission","emission"),&FixedSpatialMaterial::set_emission);
- ClassDB::bind_method(D_METHOD("get_emission"),&FixedSpatialMaterial::get_emission);
+ ClassDB::bind_method(D_METHOD("set_emission_energy", "emission_energy"), &FixedSpatialMaterial::set_emission_energy);
+ ClassDB::bind_method(D_METHOD("get_emission_energy"), &FixedSpatialMaterial::get_emission_energy);
- ClassDB::bind_method(D_METHOD("set_emission_energy","emission_energy"),&FixedSpatialMaterial::set_emission_energy);
- ClassDB::bind_method(D_METHOD("get_emission_energy"),&FixedSpatialMaterial::get_emission_energy);
+ ClassDB::bind_method(D_METHOD("set_normal_scale", "normal_scale"), &FixedSpatialMaterial::set_normal_scale);
+ ClassDB::bind_method(D_METHOD("get_normal_scale"), &FixedSpatialMaterial::get_normal_scale);
- ClassDB::bind_method(D_METHOD("set_normal_scale","normal_scale"),&FixedSpatialMaterial::set_normal_scale);
- ClassDB::bind_method(D_METHOD("get_normal_scale"),&FixedSpatialMaterial::get_normal_scale);
+ ClassDB::bind_method(D_METHOD("set_rim", "rim"), &FixedSpatialMaterial::set_rim);
+ ClassDB::bind_method(D_METHOD("get_rim"), &FixedSpatialMaterial::get_rim);
- ClassDB::bind_method(D_METHOD("set_rim","rim"),&FixedSpatialMaterial::set_rim);
- ClassDB::bind_method(D_METHOD("get_rim"),&FixedSpatialMaterial::get_rim);
+ ClassDB::bind_method(D_METHOD("set_rim_tint", "rim_tint"), &FixedSpatialMaterial::set_rim_tint);
+ ClassDB::bind_method(D_METHOD("get_rim_tint"), &FixedSpatialMaterial::get_rim_tint);
- ClassDB::bind_method(D_METHOD("set_rim_tint","rim_tint"),&FixedSpatialMaterial::set_rim_tint);
- ClassDB::bind_method(D_METHOD("get_rim_tint"),&FixedSpatialMaterial::get_rim_tint);
+ ClassDB::bind_method(D_METHOD("set_clearcoat", "clearcoat"), &FixedSpatialMaterial::set_clearcoat);
+ ClassDB::bind_method(D_METHOD("get_clearcoat"), &FixedSpatialMaterial::get_clearcoat);
- ClassDB::bind_method(D_METHOD("set_clearcoat","clearcoat"),&FixedSpatialMaterial::set_clearcoat);
- ClassDB::bind_method(D_METHOD("get_clearcoat"),&FixedSpatialMaterial::get_clearcoat);
+ ClassDB::bind_method(D_METHOD("set_clearcoat_gloss", "clearcoat_gloss"), &FixedSpatialMaterial::set_clearcoat_gloss);
+ ClassDB::bind_method(D_METHOD("get_clearcoat_gloss"), &FixedSpatialMaterial::get_clearcoat_gloss);
- ClassDB::bind_method(D_METHOD("set_clearcoat_gloss","clearcoat_gloss"),&FixedSpatialMaterial::set_clearcoat_gloss);
- ClassDB::bind_method(D_METHOD("get_clearcoat_gloss"),&FixedSpatialMaterial::get_clearcoat_gloss);
+ ClassDB::bind_method(D_METHOD("set_anisotropy", "anisotropy"), &FixedSpatialMaterial::set_anisotropy);
+ ClassDB::bind_method(D_METHOD("get_anisotropy"), &FixedSpatialMaterial::get_anisotropy);
- ClassDB::bind_method(D_METHOD("set_anisotropy","anisotropy"),&FixedSpatialMaterial::set_anisotropy);
- ClassDB::bind_method(D_METHOD("get_anisotropy"),&FixedSpatialMaterial::get_anisotropy);
+ ClassDB::bind_method(D_METHOD("set_height_scale", "height_scale"), &FixedSpatialMaterial::set_height_scale);
+ ClassDB::bind_method(D_METHOD("get_height_scale"), &FixedSpatialMaterial::get_height_scale);
- ClassDB::bind_method(D_METHOD("set_height_scale","height_scale"),&FixedSpatialMaterial::set_height_scale);
- ClassDB::bind_method(D_METHOD("get_height_scale"),&FixedSpatialMaterial::get_height_scale);
+ ClassDB::bind_method(D_METHOD("set_subsurface_scattering_strength", "strength"), &FixedSpatialMaterial::set_subsurface_scattering_strength);
+ ClassDB::bind_method(D_METHOD("get_subsurface_scattering_strength"), &FixedSpatialMaterial::get_subsurface_scattering_strength);
- ClassDB::bind_method(D_METHOD("set_subsurface_scattering_strength","strength"),&FixedSpatialMaterial::set_subsurface_scattering_strength);
- ClassDB::bind_method(D_METHOD("get_subsurface_scattering_strength"),&FixedSpatialMaterial::get_subsurface_scattering_strength);
+ ClassDB::bind_method(D_METHOD("set_refraction", "refraction"), &FixedSpatialMaterial::set_refraction);
+ ClassDB::bind_method(D_METHOD("get_refraction"), &FixedSpatialMaterial::get_refraction);
- ClassDB::bind_method(D_METHOD("set_refraction","refraction"),&FixedSpatialMaterial::set_refraction);
- ClassDB::bind_method(D_METHOD("get_refraction"),&FixedSpatialMaterial::get_refraction);
+ ClassDB::bind_method(D_METHOD("set_refraction_roughness", "refraction_roughness"), &FixedSpatialMaterial::set_refraction_roughness);
+ ClassDB::bind_method(D_METHOD("get_refraction_roughness"), &FixedSpatialMaterial::get_refraction_roughness);
- ClassDB::bind_method(D_METHOD("set_refraction_roughness","refraction_roughness"),&FixedSpatialMaterial::set_refraction_roughness);
- ClassDB::bind_method(D_METHOD("get_refraction_roughness"),&FixedSpatialMaterial::get_refraction_roughness);
+ ClassDB::bind_method(D_METHOD("set_line_width", "line_width"), &FixedSpatialMaterial::set_line_width);
+ ClassDB::bind_method(D_METHOD("get_line_width"), &FixedSpatialMaterial::get_line_width);
- ClassDB::bind_method(D_METHOD("set_line_width","line_width"),&FixedSpatialMaterial::set_line_width);
- ClassDB::bind_method(D_METHOD("get_line_width"),&FixedSpatialMaterial::get_line_width);
+ ClassDB::bind_method(D_METHOD("set_point_size", "point_size"), &FixedSpatialMaterial::set_point_size);
+ ClassDB::bind_method(D_METHOD("get_point_size"), &FixedSpatialMaterial::get_point_size);
- ClassDB::bind_method(D_METHOD("set_point_size","point_size"),&FixedSpatialMaterial::set_point_size);
- ClassDB::bind_method(D_METHOD("get_point_size"),&FixedSpatialMaterial::get_point_size);
+ ClassDB::bind_method(D_METHOD("set_detail_uv", "detail_uv"), &FixedSpatialMaterial::set_detail_uv);
+ ClassDB::bind_method(D_METHOD("get_detail_uv"), &FixedSpatialMaterial::get_detail_uv);
- ClassDB::bind_method(D_METHOD("set_detail_uv","detail_uv"),&FixedSpatialMaterial::set_detail_uv);
- ClassDB::bind_method(D_METHOD("get_detail_uv"),&FixedSpatialMaterial::get_detail_uv);
+ ClassDB::bind_method(D_METHOD("set_blend_mode", "blend_mode"), &FixedSpatialMaterial::set_blend_mode);
+ ClassDB::bind_method(D_METHOD("get_blend_mode"), &FixedSpatialMaterial::get_blend_mode);
- ClassDB::bind_method(D_METHOD("set_blend_mode","blend_mode"),&FixedSpatialMaterial::set_blend_mode);
- ClassDB::bind_method(D_METHOD("get_blend_mode"),&FixedSpatialMaterial::get_blend_mode);
+ ClassDB::bind_method(D_METHOD("set_depth_draw_mode", "depth_draw_mode"), &FixedSpatialMaterial::set_depth_draw_mode);
+ ClassDB::bind_method(D_METHOD("get_depth_draw_mode"), &FixedSpatialMaterial::get_depth_draw_mode);
- ClassDB::bind_method(D_METHOD("set_depth_draw_mode","depth_draw_mode"),&FixedSpatialMaterial::set_depth_draw_mode);
- ClassDB::bind_method(D_METHOD("get_depth_draw_mode"),&FixedSpatialMaterial::get_depth_draw_mode);
+ ClassDB::bind_method(D_METHOD("set_cull_mode", "cull_mode"), &FixedSpatialMaterial::set_cull_mode);
+ ClassDB::bind_method(D_METHOD("get_cull_mode"), &FixedSpatialMaterial::get_cull_mode);
- ClassDB::bind_method(D_METHOD("set_cull_mode","cull_mode"),&FixedSpatialMaterial::set_cull_mode);
- ClassDB::bind_method(D_METHOD("get_cull_mode"),&FixedSpatialMaterial::get_cull_mode);
+ ClassDB::bind_method(D_METHOD("set_diffuse_mode", "diffuse_mode"), &FixedSpatialMaterial::set_diffuse_mode);
+ ClassDB::bind_method(D_METHOD("get_diffuse_mode"), &FixedSpatialMaterial::get_diffuse_mode);
- ClassDB::bind_method(D_METHOD("set_diffuse_mode","diffuse_mode"),&FixedSpatialMaterial::set_diffuse_mode);
- ClassDB::bind_method(D_METHOD("get_diffuse_mode"),&FixedSpatialMaterial::get_diffuse_mode);
+ ClassDB::bind_method(D_METHOD("set_flag", "flag", "enable"), &FixedSpatialMaterial::set_flag);
+ ClassDB::bind_method(D_METHOD("get_flag"), &FixedSpatialMaterial::get_flag);
- ClassDB::bind_method(D_METHOD("set_flag","flag","enable"),&FixedSpatialMaterial::set_flag);
- ClassDB::bind_method(D_METHOD("get_flag"),&FixedSpatialMaterial::get_flag);
+ ClassDB::bind_method(D_METHOD("set_feature", "feature", "enable"), &FixedSpatialMaterial::set_feature);
+ ClassDB::bind_method(D_METHOD("get_feature", "feature"), &FixedSpatialMaterial::get_feature);
- ClassDB::bind_method(D_METHOD("set_feature","feature","enable"),&FixedSpatialMaterial::set_feature);
- ClassDB::bind_method(D_METHOD("get_feature","feature"),&FixedSpatialMaterial::get_feature);
+ ClassDB::bind_method(D_METHOD("set_texture", "param:Texture", "texture"), &FixedSpatialMaterial::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture", "param:Texture"), &FixedSpatialMaterial::get_texture);
- ClassDB::bind_method(D_METHOD("set_texture","param:Texture","texture"),&FixedSpatialMaterial::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture:Texture","param:Texture"),&FixedSpatialMaterial::get_texture);
+ ClassDB::bind_method(D_METHOD("set_detail_blend_mode", "detail_blend_mode"), &FixedSpatialMaterial::set_detail_blend_mode);
+ ClassDB::bind_method(D_METHOD("get_detail_blend_mode"), &FixedSpatialMaterial::get_detail_blend_mode);
- ClassDB::bind_method(D_METHOD("set_detail_blend_mode","detail_blend_mode"),&FixedSpatialMaterial::set_detail_blend_mode);
- ClassDB::bind_method(D_METHOD("get_detail_blend_mode"),&FixedSpatialMaterial::get_detail_blend_mode);
+ ClassDB::bind_method(D_METHOD("set_uv1_scale", "scale"), &FixedSpatialMaterial::set_uv1_scale);
+ ClassDB::bind_method(D_METHOD("get_uv1_scale"), &FixedSpatialMaterial::get_uv1_scale);
- ClassDB::bind_method(D_METHOD("set_uv1_scale","scale"),&FixedSpatialMaterial::set_uv1_scale);
- ClassDB::bind_method(D_METHOD("get_uv1_scale"),&FixedSpatialMaterial::get_uv1_scale);
+ ClassDB::bind_method(D_METHOD("set_uv1_offset", "offset"), &FixedSpatialMaterial::set_uv1_offset);
+ ClassDB::bind_method(D_METHOD("get_uv1_offset"), &FixedSpatialMaterial::get_uv1_offset);
- ClassDB::bind_method(D_METHOD("set_uv1_offset","offset"),&FixedSpatialMaterial::set_uv1_offset);
- ClassDB::bind_method(D_METHOD("get_uv1_offset"),&FixedSpatialMaterial::get_uv1_offset);
+ ClassDB::bind_method(D_METHOD("set_uv2_scale", "scale"), &FixedSpatialMaterial::set_uv2_scale);
+ ClassDB::bind_method(D_METHOD("get_uv2_scale"), &FixedSpatialMaterial::get_uv2_scale);
- ClassDB::bind_method(D_METHOD("set_uv2_scale","scale"),&FixedSpatialMaterial::set_uv2_scale);
- ClassDB::bind_method(D_METHOD("get_uv2_scale"),&FixedSpatialMaterial::get_uv2_scale);
+ ClassDB::bind_method(D_METHOD("set_uv2_offset", "offset"), &FixedSpatialMaterial::set_uv2_offset);
+ ClassDB::bind_method(D_METHOD("get_uv2_offset"), &FixedSpatialMaterial::get_uv2_offset);
- ClassDB::bind_method(D_METHOD("set_uv2_offset","offset"),&FixedSpatialMaterial::set_uv2_offset);
- ClassDB::bind_method(D_METHOD("get_uv2_offset"),&FixedSpatialMaterial::get_uv2_offset);
-
- ADD_GROUP("Flags","flags_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_transparent"),"set_feature","get_feature",FEATURE_TRANSPARENT);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_unshaded"),"set_flag","get_flag",FLAG_UNSHADED);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_on_top"),"set_flag","get_flag",FLAG_ONTOP);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_use_point_size"),"set_flag","get_flag",FLAG_USE_POINT_SIZE);
- ADD_GROUP("Vertex Color","vertex_color");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_use_as_albedo"),"set_flag","get_flag",FLAG_ALBEDO_FROM_VERTEX_COLOR);
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_is_srgb"),"set_flag","get_flag",FLAG_SRGB_VERTEX_COLOR);
-
- ADD_GROUP("Parameters","params_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"params_diffuse_mode",PROPERTY_HINT_ENUM,"Labert,Lambert Wrap,Oren Nayar,Burley"),"set_diffuse_mode","get_diffuse_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"params_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),"set_blend_mode","get_blend_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"params_cull_mode",PROPERTY_HINT_ENUM,"Back,Front,Disabled"),"set_cull_mode","get_cull_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"params_depth_draw_mode",PROPERTY_HINT_ENUM,"Opaque Only,Always,Never,Opaque Pre-Pass"),"set_depth_draw_mode","get_depth_draw_mode");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_line_width",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_line_width","get_line_width");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_point_size",PROPERTY_HINT_RANGE,"0.1,128,0.1"),"set_point_size","get_point_size");
-
- ADD_GROUP("Albedo","albedo_");
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"albedo_color"),"set_albedo","get_albedo");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"albedo_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_ALBEDO);
-
- ADD_GROUP("Specular","specular_");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"specular_mode",PROPERTY_HINT_ENUM,"Metallic,Specular"),"set_specular_mode","get_specular_mode");
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"specular_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_specular","get_specular");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_metalness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_metalness","get_metalness");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_roughness","get_roughness");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"specular_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_SPECULAR);
-
- ADD_GROUP("Emission","emission_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"emission_enabled"),"set_feature","get_feature",FEATURE_EMISSION);
- ADD_PROPERTY(PropertyInfo(Variant::COLOR,"emission_color",PROPERTY_HINT_COLOR_NO_ALPHA),"set_emission","get_emission");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"emission_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),"set_emission_energy","get_emission_energy");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"emission_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_EMISSION);
-
- ADD_GROUP("NormapMap","normal_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"normal_enabled"),"set_feature","get_feature",FEATURE_NORMAL_MAPPING);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"normal_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),"set_normal_scale","get_normal_scale");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"normal_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_NORMAL);
-
- ADD_GROUP("Rim","rim_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"rim_enabled"),"set_feature","get_feature",FEATURE_RIM);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_rim","get_rim");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_tint",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_rim_tint","get_rim_tint");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"rim_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_RIM);
-
- ADD_GROUP("Clearcoat","clearcoat_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"clearcoat_enabled"),"set_feature","get_feature",FEATURE_CLEARCOAT);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_clearcoat","get_clearcoat");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_gloss",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_clearcoat_gloss","get_clearcoat_gloss");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"clearcoat_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_CLEARCOAT);
-
- ADD_GROUP("Anisotropy","anisotropy_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"anisotropy_enabled"),"set_feature","get_feature",FEATURE_ANISOTROPY);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"anisotropy_anisotropy",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_anisotropy","get_anisotropy");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"anisotropy_flowmap",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_FLOWMAP);
-
- ADD_GROUP("Ambient Occlusion","ao_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"ao_enabled"),"set_feature","get_feature",FEATURE_AMBIENT_OCCLUSION);
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"ao_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_AMBIENT_OCCLUSION);
-
- ADD_GROUP("Height","height_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"height_enabled"),"set_feature","get_feature",FEATURE_HEIGHT_MAPPING);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"height_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),"set_height_scale","get_height_scale");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"height_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_HEIGHT);
-
- ADD_GROUP("Subsurf Scatter","subsurf_scatter_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"subsurf_scatter_enabled"),"set_feature","get_feature",FEATURE_SUBSURACE_SCATTERING);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"subsurf_scatter_strength",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_subsurface_scattering_strength","get_subsurface_scattering_strength");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"subsurf_scatter_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_SUBSURFACE_SCATTERING);
-
- ADD_GROUP("Refraction","refraction_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"refraction_enabled"),"set_feature","get_feature",FEATURE_REFRACTION);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_displacement",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_refraction","get_refraction");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_refraction_roughness","get_refraction_roughness");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"refraction_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_REFRACTION);
-
- ADD_GROUP("Detail","detail_");
- ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"detail_enabled"),"set_feature","get_feature",FEATURE_DETAIL);
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_mask",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_MASK);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),"set_detail_blend_mode","get_detail_blend_mode");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_uv_layer",PROPERTY_HINT_ENUM,"UV1,UV2"),"set_detail_uv","get_detail_uv");
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_albedo",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_ALBEDO);
- ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),"set_texture","get_texture",TEXTURE_DETAIL_NORMAL);
-
- ADD_GROUP("UV1","uv1_");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_scale"),"set_uv1_scale","get_uv1_scale");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_offset"),"set_uv1_offset","get_uv1_offset");
-
- ADD_GROUP("UV2","uv2_");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_scale"),"set_uv2_scale","get_uv2_scale");
- ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_offset"),"set_uv2_offset","get_uv2_offset");
-
-
- BIND_CONSTANT( TEXTURE_ALBEDO );
- BIND_CONSTANT( TEXTURE_SPECULAR );
- BIND_CONSTANT( TEXTURE_EMISSION );
- BIND_CONSTANT( TEXTURE_NORMAL );
- BIND_CONSTANT( TEXTURE_RIM );
- BIND_CONSTANT( TEXTURE_CLEARCOAT );
- BIND_CONSTANT( TEXTURE_FLOWMAP );
- BIND_CONSTANT( TEXTURE_AMBIENT_OCCLUSION );
- BIND_CONSTANT( TEXTURE_HEIGHT );
- BIND_CONSTANT( TEXTURE_SUBSURFACE_SCATTERING );
- BIND_CONSTANT( TEXTURE_REFRACTION );
- BIND_CONSTANT( TEXTURE_REFRACTION_ROUGHNESS );
- BIND_CONSTANT( TEXTURE_DETAIL_MASK );
- BIND_CONSTANT( TEXTURE_DETAIL_ALBEDO );
- BIND_CONSTANT( TEXTURE_DETAIL_NORMAL );
- BIND_CONSTANT( TEXTURE_MAX );
-
-
- BIND_CONSTANT( DETAIL_UV_1 );
- BIND_CONSTANT( DETAIL_UV_2 );
-
- BIND_CONSTANT( FEATURE_TRANSPARENT );
- BIND_CONSTANT( FEATURE_EMISSION );
- BIND_CONSTANT( FEATURE_NORMAL_MAPPING );
- BIND_CONSTANT( FEATURE_RIM );
- BIND_CONSTANT( FEATURE_CLEARCOAT );
- BIND_CONSTANT( FEATURE_ANISOTROPY );
- BIND_CONSTANT( FEATURE_AMBIENT_OCCLUSION );
- BIND_CONSTANT( FEATURE_HEIGHT_MAPPING );
- BIND_CONSTANT( FEATURE_SUBSURACE_SCATTERING );
- BIND_CONSTANT( FEATURE_REFRACTION );
- BIND_CONSTANT( FEATURE_DETAIL );
- BIND_CONSTANT( FEATURE_MAX );
-
- BIND_CONSTANT( BLEND_MODE_MIX );
- BIND_CONSTANT( BLEND_MODE_ADD );
- BIND_CONSTANT( BLEND_MODE_SUB );
- BIND_CONSTANT( BLEND_MODE_MUL );
-
- BIND_CONSTANT( DEPTH_DRAW_OPAQUE_ONLY );
- BIND_CONSTANT( DEPTH_DRAW_ALWAYS );
- BIND_CONSTANT( DEPTH_DRAW_DISABLED );
- BIND_CONSTANT( DEPTH_DRAW_ALPHA_OPAQUE_PREPASS );
-
-
- BIND_CONSTANT( CULL_BACK );
- BIND_CONSTANT( CULL_FRONT );
- BIND_CONSTANT( CULL_DISABLED );
-
- BIND_CONSTANT( FLAG_UNSHADED );
- BIND_CONSTANT( FLAG_ONTOP );
- BIND_CONSTANT( FLAG_ALBEDO_FROM_VERTEX_COLOR );
- BIND_CONSTANT( FLAG_SRGB_VERTEX_COLOR )
- BIND_CONSTANT( FLAG_USE_POINT_SIZE )
- BIND_CONSTANT( FLAG_MAX );
-
- BIND_CONSTANT( DIFFUSE_LAMBERT );
- BIND_CONSTANT( DIFFUSE_LAMBERT_WRAP );
- BIND_CONSTANT( DIFFUSE_OREN_NAYAR );
- BIND_CONSTANT( DIFFUSE_BURLEY );
-
- BIND_CONSTANT( SPECULAR_MODE_METALLIC );
- BIND_CONSTANT( SPECULAR_MODE_SPECULAR );
-
-}
-
-
-FixedSpatialMaterial::FixedSpatialMaterial() : element(this) {
+ ADD_GROUP("Flags", "flags_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_transparent"), "set_feature", "get_feature", FEATURE_TRANSPARENT);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_unshaded"), "set_flag", "get_flag", FLAG_UNSHADED);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_on_top"), "set_flag", "get_flag", FLAG_ONTOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "flags_use_point_size"), "set_flag", "get_flag", FLAG_USE_POINT_SIZE);
+ ADD_GROUP("Vertex Color", "vertex_color");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_use_as_albedo"), "set_flag", "get_flag", FLAG_ALBEDO_FROM_VERTEX_COLOR);
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "vertex_color_is_srgb"), "set_flag", "get_flag", FLAG_SRGB_VERTEX_COLOR);
+
+ ADD_GROUP("Parameters", "params_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "params_diffuse_mode", PROPERTY_HINT_ENUM, "Labert,Lambert Wrap,Oren Nayar,Burley"), "set_diffuse_mode", "get_diffuse_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "params_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_blend_mode", "get_blend_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "params_cull_mode", PROPERTY_HINT_ENUM, "Back,Front,Disabled"), "set_cull_mode", "get_cull_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "params_depth_draw_mode", PROPERTY_HINT_ENUM, "Opaque Only,Always,Never,Opaque Pre-Pass"), "set_depth_draw_mode", "get_depth_draw_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_line_width", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_line_width", "get_line_width");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "params_point_size", PROPERTY_HINT_RANGE, "0.1,128,0.1"), "set_point_size", "get_point_size");
+
+ ADD_GROUP("Albedo", "albedo_");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "albedo_color"), "set_albedo", "get_albedo");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "albedo_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_ALBEDO);
+
+ ADD_GROUP("Specular", "specular_");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "specular_mode", PROPERTY_HINT_ENUM, "Metallic,Specular"), "set_specular_mode", "get_specular_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "specular_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_specular", "get_specular");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "specular_metalness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_metalness", "get_metalness");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "specular_roughness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_roughness", "get_roughness");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "specular_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_SPECULAR);
+
+ ADD_GROUP("Emission", "emission_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "emission_enabled"), "set_feature", "get_feature", FEATURE_EMISSION);
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "emission_color", PROPERTY_HINT_COLOR_NO_ALPHA), "set_emission", "get_emission");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "emission_energy", PROPERTY_HINT_RANGE, "0,16,0.01"), "set_emission_energy", "get_emission_energy");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "emission_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_EMISSION);
+
+ ADD_GROUP("NormapMap", "normal_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "normal_enabled"), "set_feature", "get_feature", FEATURE_NORMAL_MAPPING);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "normal_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_normal_scale", "get_normal_scale");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "normal_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_NORMAL);
+
+ ADD_GROUP("Rim", "rim_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "rim_enabled"), "set_feature", "get_feature", FEATURE_RIM);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim", "get_rim");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "rim_tint", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_rim_tint", "get_rim_tint");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "rim_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_RIM);
+
+ ADD_GROUP("Clearcoat", "clearcoat_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "clearcoat_enabled"), "set_feature", "get_feature", FEATURE_CLEARCOAT);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat_amount", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat", "get_clearcoat");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "clearcoat_gloss", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_clearcoat_gloss", "get_clearcoat_gloss");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "clearcoat_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_CLEARCOAT);
+
+ ADD_GROUP("Anisotropy", "anisotropy_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "anisotropy_enabled"), "set_feature", "get_feature", FEATURE_ANISOTROPY);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "anisotropy_anisotropy", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_anisotropy", "get_anisotropy");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "anisotropy_flowmap", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_FLOWMAP);
+
+ ADD_GROUP("Ambient Occlusion", "ao_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "ao_enabled"), "set_feature", "get_feature", FEATURE_AMBIENT_OCCLUSION);
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "ao_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_AMBIENT_OCCLUSION);
+
+ ADD_GROUP("Height", "height_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "height_enabled"), "set_feature", "get_feature", FEATURE_HEIGHT_MAPPING);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "height_scale", PROPERTY_HINT_RANGE, "-16,16,0.01"), "set_height_scale", "get_height_scale");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "height_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_HEIGHT);
+
+ ADD_GROUP("Subsurf Scatter", "subsurf_scatter_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "subsurf_scatter_enabled"), "set_feature", "get_feature", FEATURE_SUBSURACE_SCATTERING);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "subsurf_scatter_strength", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_subsurface_scattering_strength", "get_subsurface_scattering_strength");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "subsurf_scatter_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_SUBSURFACE_SCATTERING);
+
+ ADD_GROUP("Refraction", "refraction_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "refraction_enabled"), "set_feature", "get_feature", FEATURE_REFRACTION);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "refraction_displacement", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_refraction", "get_refraction");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "refraction_roughness", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_refraction_roughness", "get_refraction_roughness");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "refraction_texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_REFRACTION);
+
+ ADD_GROUP("Detail", "detail_");
+ ADD_PROPERTYI(PropertyInfo(Variant::BOOL, "detail_enabled"), "set_feature", "get_feature", FEATURE_DETAIL);
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_mask", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_MASK);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_blend_mode", PROPERTY_HINT_ENUM, "Mix,Add,Sub,Mul"), "set_detail_blend_mode", "get_detail_blend_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "detail_uv_layer", PROPERTY_HINT_ENUM, "UV1,UV2"), "set_detail_uv", "get_detail_uv");
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_albedo", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_ALBEDO);
+ ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "detail_normal", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture", TEXTURE_DETAIL_NORMAL);
+
+ ADD_GROUP("UV1", "uv1_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv1_scale"), "set_uv1_scale", "get_uv1_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv1_offset"), "set_uv1_offset", "get_uv1_offset");
+
+ ADD_GROUP("UV2", "uv2_");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv2_scale"), "set_uv2_scale", "get_uv2_scale");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "uv2_offset"), "set_uv2_offset", "get_uv2_offset");
+
+ BIND_CONSTANT(TEXTURE_ALBEDO);
+ BIND_CONSTANT(TEXTURE_SPECULAR);
+ BIND_CONSTANT(TEXTURE_EMISSION);
+ BIND_CONSTANT(TEXTURE_NORMAL);
+ BIND_CONSTANT(TEXTURE_RIM);
+ BIND_CONSTANT(TEXTURE_CLEARCOAT);
+ BIND_CONSTANT(TEXTURE_FLOWMAP);
+ BIND_CONSTANT(TEXTURE_AMBIENT_OCCLUSION);
+ BIND_CONSTANT(TEXTURE_HEIGHT);
+ BIND_CONSTANT(TEXTURE_SUBSURFACE_SCATTERING);
+ BIND_CONSTANT(TEXTURE_REFRACTION);
+ BIND_CONSTANT(TEXTURE_REFRACTION_ROUGHNESS);
+ BIND_CONSTANT(TEXTURE_DETAIL_MASK);
+ BIND_CONSTANT(TEXTURE_DETAIL_ALBEDO);
+ BIND_CONSTANT(TEXTURE_DETAIL_NORMAL);
+ BIND_CONSTANT(TEXTURE_MAX);
+
+ BIND_CONSTANT(DETAIL_UV_1);
+ BIND_CONSTANT(DETAIL_UV_2);
+
+ BIND_CONSTANT(FEATURE_TRANSPARENT);
+ BIND_CONSTANT(FEATURE_EMISSION);
+ BIND_CONSTANT(FEATURE_NORMAL_MAPPING);
+ BIND_CONSTANT(FEATURE_RIM);
+ BIND_CONSTANT(FEATURE_CLEARCOAT);
+ BIND_CONSTANT(FEATURE_ANISOTROPY);
+ BIND_CONSTANT(FEATURE_AMBIENT_OCCLUSION);
+ BIND_CONSTANT(FEATURE_HEIGHT_MAPPING);
+ BIND_CONSTANT(FEATURE_SUBSURACE_SCATTERING);
+ BIND_CONSTANT(FEATURE_REFRACTION);
+ BIND_CONSTANT(FEATURE_DETAIL);
+ BIND_CONSTANT(FEATURE_MAX);
+
+ BIND_CONSTANT(BLEND_MODE_MIX);
+ BIND_CONSTANT(BLEND_MODE_ADD);
+ BIND_CONSTANT(BLEND_MODE_SUB);
+ BIND_CONSTANT(BLEND_MODE_MUL);
+
+ BIND_CONSTANT(DEPTH_DRAW_OPAQUE_ONLY);
+ BIND_CONSTANT(DEPTH_DRAW_ALWAYS);
+ BIND_CONSTANT(DEPTH_DRAW_DISABLED);
+ BIND_CONSTANT(DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
+
+ BIND_CONSTANT(CULL_BACK);
+ BIND_CONSTANT(CULL_FRONT);
+ BIND_CONSTANT(CULL_DISABLED);
+
+ BIND_CONSTANT(FLAG_UNSHADED);
+ BIND_CONSTANT(FLAG_ONTOP);
+ BIND_CONSTANT(FLAG_ALBEDO_FROM_VERTEX_COLOR);
+ BIND_CONSTANT(FLAG_SRGB_VERTEX_COLOR)
+ BIND_CONSTANT(FLAG_USE_POINT_SIZE)
+ BIND_CONSTANT(FLAG_MAX);
+
+ BIND_CONSTANT(DIFFUSE_LAMBERT);
+ BIND_CONSTANT(DIFFUSE_LAMBERT_WRAP);
+ BIND_CONSTANT(DIFFUSE_OREN_NAYAR);
+ BIND_CONSTANT(DIFFUSE_BURLEY);
+
+ BIND_CONSTANT(SPECULAR_MODE_METALLIC);
+ BIND_CONSTANT(SPECULAR_MODE_SPECULAR);
+}
+
+FixedSpatialMaterial::FixedSpatialMaterial()
+ : element(this) {
//initialize to right values
- specular_mode=SPECULAR_MODE_METALLIC;
- set_albedo(Color(0.7,0.7,0.7,1.0));
- set_specular(Color(0.1,0.1,0.1));
+ specular_mode = SPECULAR_MODE_METALLIC;
+ set_albedo(Color(0.7, 0.7, 0.7, 1.0));
+ set_specular(Color(0.1, 0.1, 0.1));
set_roughness(0.0);
set_metalness(0.1);
- set_emission(Color(0,0,0));
+ set_emission(Color(0, 0, 0));
set_emission_energy(1.0);
set_normal_scale(1);
set_rim(1.0);
@@ -1109,27 +1057,27 @@ FixedSpatialMaterial::FixedSpatialMaterial() : element(this) {
set_refraction_roughness(0);
set_line_width(1);
set_point_size(1);
- set_uv1_offset(Vector2(0,0));
- set_uv1_scale(Vector2(1,1));
- set_uv2_offset(Vector2(0,0));
- set_uv2_scale(Vector2(1,1));
-
- detail_uv=DETAIL_UV_1;
- blend_mode=BLEND_MODE_MIX;
- detail_blend_mode=BLEND_MODE_MIX;
- depth_draw_mode=DEPTH_DRAW_OPAQUE_ONLY;
- cull_mode=CULL_BACK;
- for(int i=0;i<FLAG_MAX;i++) {
- flags[i]=0;
+ set_uv1_offset(Vector2(0, 0));
+ set_uv1_scale(Vector2(1, 1));
+ set_uv2_offset(Vector2(0, 0));
+ set_uv2_scale(Vector2(1, 1));
+
+ detail_uv = DETAIL_UV_1;
+ blend_mode = BLEND_MODE_MIX;
+ detail_blend_mode = BLEND_MODE_MIX;
+ depth_draw_mode = DEPTH_DRAW_OPAQUE_ONLY;
+ cull_mode = CULL_BACK;
+ for (int i = 0; i < FLAG_MAX; i++) {
+ flags[i] = 0;
}
- diffuse_mode=DIFFUSE_LAMBERT;
+ diffuse_mode = DIFFUSE_LAMBERT;
- for(int i=0;i<FEATURE_MAX;i++) {
- features[i]=false;
+ for (int i = 0; i < FEATURE_MAX; i++) {
+ features[i] = false;
}
- current_key.key=0;
- current_key.invalid_key=1;
+ current_key.key = 0;
+ current_key.invalid_key = 1;
_queue_shader_change();
}
@@ -1140,17 +1088,15 @@ FixedSpatialMaterial::~FixedSpatialMaterial() {
if (shader_map.has(current_key)) {
shader_map[current_key].users--;
- if (shader_map[current_key].users==0) {
+ if (shader_map[current_key].users == 0) {
//deallocate shader, as it's no longer in use
VS::get_singleton()->free(shader_map[current_key].shader);
shader_map.erase(current_key);
}
- VS::get_singleton()->material_set_shader(_get_material(),RID());
+ VS::get_singleton()->material_set_shader(_get_material(), RID());
}
-
if (material_mutex)
material_mutex->unlock();
-
}
diff --git a/scene/resources/material.h b/scene/resources/material.h
index 6b957d0203..a8288153c3 100644
--- a/scene/resources/material.h
+++ b/scene/resources/material.h
@@ -29,41 +29,38 @@
#ifndef MATERIAL_H
#define MATERIAL_H
-#include "servers/visual_server.h"
-#include "scene/resources/texture.h"
-#include "scene/resources/shader.h"
#include "resource.h"
-#include "servers/visual/shader_language.h"
+#include "scene/resources/shader.h"
+#include "scene/resources/texture.h"
#include "self_list.h"
+#include "servers/visual/shader_language.h"
+#include "servers/visual_server.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class Material : public Resource {
- GDCLASS(Material,Resource);
+ GDCLASS(Material, Resource);
RES_BASE_EXTENSION("mtl");
- OBJ_SAVE_TYPE( Material );
+ OBJ_SAVE_TYPE(Material);
RID material;
+
protected:
+ _FORCE_INLINE_ RID _get_material() const { return material; }
- _FORCE_INLINE_ RID _get_material() const { return material; }
public:
-
virtual RID get_rid() const;
Material();
virtual ~Material();
};
-
class FixedSpatialMaterial : public Material {
- GDCLASS(FixedSpatialMaterial,Material)
-
+ GDCLASS(FixedSpatialMaterial, Material)
public:
-
enum TextureParam {
TEXTURE_ALBEDO,
TEXTURE_SPECULAR,
@@ -82,10 +79,8 @@ public:
TEXTURE_DETAIL_NORMAL,
TEXTURE_MAX
-
};
-
enum DetailUV {
DETAIL_UV_1,
DETAIL_UV_2
@@ -106,7 +101,6 @@ public:
FEATURE_MAX
};
-
enum BlendMode {
BLEND_MODE_MIX,
BLEND_MODE_ADD,
@@ -167,10 +161,9 @@ private:
uint32_t key;
- bool operator<(const MaterialKey& p_key) const {
+ bool operator<(const MaterialKey &p_key) const {
return key < p_key.key;
}
-
};
struct ShaderData {
@@ -178,31 +171,31 @@ private:
int users;
};
- static Map<MaterialKey,ShaderData> shader_map;
+ static Map<MaterialKey, ShaderData> shader_map;
MaterialKey current_key;
_FORCE_INLINE_ MaterialKey _compute_key() const {
MaterialKey mk;
- mk.key=0;
- for(int i=0;i<FEATURE_MAX;i++) {
+ mk.key = 0;
+ for (int i = 0; i < FEATURE_MAX; i++) {
if (features[i]) {
- mk.feature_mask|=(1<<i);
+ mk.feature_mask |= (1 << i);
}
}
- mk.detail_uv=detail_uv;
- mk.blend_mode=blend_mode;
- mk.depth_draw_mode=depth_draw_mode;
- mk.cull_mode=cull_mode;
- for(int i=0;i<FLAG_MAX;i++) {
+ mk.detail_uv = detail_uv;
+ mk.blend_mode = blend_mode;
+ mk.depth_draw_mode = depth_draw_mode;
+ mk.cull_mode = cull_mode;
+ for (int i = 0; i < FLAG_MAX; i++) {
if (flags[i]) {
- mk.flags|=(1<<i);
+ mk.flags |= (1 << i);
}
}
- mk.detail_blend_mode=detail_blend_mode;
- mk.diffuse_mode=diffuse_mode;
- mk.specular_mode=specular_mode;
+ mk.detail_blend_mode = detail_blend_mode;
+ mk.diffuse_mode = diffuse_mode;
+ mk.specular_mode = specular_mode;
return mk;
}
@@ -230,12 +223,11 @@ private:
StringName uv2_scale;
StringName uv2_offset;
StringName texture_names[TEXTURE_MAX];
-
};
static Mutex *material_mutex;
static SelfList<FixedSpatialMaterial>::List dirty_materials;
- static ShaderNames* shader_names;
+ static ShaderNames *shader_names;
SelfList<FixedSpatialMaterial> element;
@@ -282,23 +274,20 @@ private:
Ref<Texture> textures[TEXTURE_MAX];
- _FORCE_INLINE_ void _validate_feature(const String& text, Feature feature,PropertyInfo& property) const;
+ _FORCE_INLINE_ void _validate_feature(const String &text, Feature feature, PropertyInfo &property) const;
protected:
-
static void _bind_methods();
- void _validate_property(PropertyInfo& property) const;
+ void _validate_property(PropertyInfo &property) const;
public:
-
-
- void set_albedo(const Color& p_albedo);
+ void set_albedo(const Color &p_albedo);
Color get_albedo() const;
void set_specular_mode(SpecularMode p_mode);
SpecularMode get_specular_mode() const;
- void set_specular(const Color& p_specular);
+ void set_specular(const Color &p_specular);
Color get_specular() const;
void set_metalness(float p_metalness);
@@ -307,7 +296,7 @@ public:
void set_roughness(float p_roughness);
float get_roughness() const;
- void set_emission(const Color& p_emission);
+ void set_emission(const Color &p_emission);
Color get_emission() const;
void set_emission_energy(float p_emission_energy);
@@ -367,25 +356,25 @@ public:
void set_diffuse_mode(DiffuseMode p_mode);
DiffuseMode get_diffuse_mode() const;
- void set_flag(Flags p_flag,bool p_enabled);
+ void set_flag(Flags p_flag, bool p_enabled);
bool get_flag(Flags p_flag) const;
- void set_texture(TextureParam p_param,const Ref<Texture>& p_texture);
+ void set_texture(TextureParam p_param, const Ref<Texture> &p_texture);
Ref<Texture> get_texture(TextureParam p_param) const;
- void set_feature(Feature p_feature,bool p_enabled);
+ void set_feature(Feature p_feature, bool p_enabled);
bool get_feature(Feature p_feature) const;
- void set_uv1_scale(const Vector2& p_scale);
+ void set_uv1_scale(const Vector2 &p_scale);
Vector2 get_uv1_scale() const;
- void set_uv1_offset(const Vector2& p_offset);
+ void set_uv1_offset(const Vector2 &p_offset);
Vector2 get_uv1_offset() const;
- void set_uv2_scale(const Vector2& p_scale);
+ void set_uv2_scale(const Vector2 &p_scale);
Vector2 get_uv2_scale() const;
- void set_uv2_offset(const Vector2& p_offset);
+ void set_uv2_offset(const Vector2 &p_offset);
Vector2 get_uv2_offset() const;
static void init_shaders();
@@ -396,21 +385,16 @@ public:
virtual ~FixedSpatialMaterial();
};
-VARIANT_ENUM_CAST( FixedSpatialMaterial::TextureParam )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::DetailUV )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::Feature )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::BlendMode )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::DepthDrawMode )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::CullMode )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::Flags )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::DiffuseMode )
-VARIANT_ENUM_CAST( FixedSpatialMaterial::SpecularMode )
+VARIANT_ENUM_CAST(FixedSpatialMaterial::TextureParam)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::DetailUV)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::Feature)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::BlendMode)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::DepthDrawMode)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::CullMode)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::Flags)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::DiffuseMode)
+VARIANT_ENUM_CAST(FixedSpatialMaterial::SpecularMode)
//////////////////////
-
-
-
-
-
#endif
diff --git a/scene/resources/mesh.cpp b/scene/resources/mesh.cpp
index 9990a6e796..f951cf1620 100644
--- a/scene/resources/mesh.cpp
+++ b/scene/resources/mesh.cpp
@@ -31,7 +31,7 @@
#include "scene/resources/convex_polygon_shape.h"
#include "surface_tool.h"
-static const char* _array_name[]={
+static const char *_array_name[] = {
"vertex_array",
"normal_array",
"tangent_array",
@@ -44,7 +44,7 @@ static const char* _array_name[]={
NULL
};
-static const Mesh::ArrayType _array_types[]={
+static const Mesh::ArrayType _array_types[] = {
Mesh::ARRAY_VERTEX,
Mesh::ARRAY_NORMAL,
@@ -57,9 +57,8 @@ static const Mesh::ArrayType _array_types[]={
Mesh::ARRAY_INDEX
};
-
/* compatibility */
-static const int _format_translate[]={
+static const int _format_translate[] = {
Mesh::ARRAY_FORMAT_VERTEX,
Mesh::ARRAY_FORMAT_NORMAL,
@@ -72,22 +71,21 @@ static const int _format_translate[]={
Mesh::ARRAY_FORMAT_INDEX,
};
+bool Mesh::_set(const StringName &p_name, const Variant &p_value) {
-bool Mesh::_set(const StringName& p_name, const Variant& p_value) {
-
- String sname=p_name;
+ String sname = p_name;
- if (p_name=="blend_shape/names") {
+ if (p_name == "blend_shape/names") {
- PoolVector<String> sk=p_value;
+ PoolVector<String> sk = p_value;
int sz = sk.size();
PoolVector<String>::Read r = sk.read();
- for(int i=0;i<sz;i++)
+ for (int i = 0; i < sz; i++)
add_blend_shape(r[i]);
return true;
}
- if (p_name=="blend_shape/mode") {
+ if (p_name == "blend_shape/mode") {
set_blend_shape_mode(BlendShapeMode(int(p_value)));
return true;
@@ -95,19 +93,19 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) {
if (sname.begins_with("surface_")) {
- int sl=sname.find("/");
- if (sl==-1)
+ int sl = sname.find("/");
+ if (sl == -1)
return false;
- int idx=sname.substr(8,sl-8).to_int()-1;
- String what = sname.get_slicec('/',1);
- if (what=="material")
- surface_set_material(idx,p_value);
- else if (what=="name")
- surface_set_name(idx,p_value);
+ int idx = sname.substr(8, sl - 8).to_int() - 1;
+ String what = sname.get_slicec('/', 1);
+ if (what == "material")
+ surface_set_material(idx, p_value);
+ else if (what == "name")
+ surface_set_name(idx, p_value);
return true;
}
- if (sname=="custom_aabb/custom_aabb") {
+ if (sname == "custom_aabb/custom_aabb") {
set_custom_aabb(p_value);
return true;
@@ -116,52 +114,51 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) {
if (!sname.begins_with("surfaces"))
return false;
+ int idx = sname.get_slicec('/', 1).to_int();
+ String what = sname.get_slicec('/', 2);
- int idx=sname.get_slicec('/',1).to_int();
- String what=sname.get_slicec('/',2);
-
- if (idx==surfaces.size()) {
+ if (idx == surfaces.size()) {
//create
- Dictionary d=p_value;
- ERR_FAIL_COND_V(!d.has("primitive"),false);
+ Dictionary d = p_value;
+ ERR_FAIL_COND_V(!d.has("primitive"), false);
if (d.has("arrays")) {
//old format
- ERR_FAIL_COND_V(!d.has("morph_arrays"),false);
- add_surface_from_arrays(PrimitiveType(int(d["primitive"])),d["arrays"],d["morph_arrays"]);
+ ERR_FAIL_COND_V(!d.has("morph_arrays"), false);
+ add_surface_from_arrays(PrimitiveType(int(d["primitive"])), d["arrays"], d["morph_arrays"]);
} else if (d.has("array_data")) {
PoolVector<uint8_t> array_data = d["array_data"];
PoolVector<uint8_t> array_index_data;
if (d.has("array_index_data"))
- array_index_data=d["array_index_data"];
+ array_index_data = d["array_index_data"];
- ERR_FAIL_COND_V(!d.has("format"),false);
+ ERR_FAIL_COND_V(!d.has("format"), false);
uint32_t format = d["format"];
- ERR_FAIL_COND_V(!d.has("primitive"),false);
+ ERR_FAIL_COND_V(!d.has("primitive"), false);
uint32_t primitive = d["primitive"];
- ERR_FAIL_COND_V(!d.has("vertex_count"),false);
+ ERR_FAIL_COND_V(!d.has("vertex_count"), false);
int vertex_count = d["vertex_count"];
- int index_count=0;
+ int index_count = 0;
if (d.has("index_count"))
- index_count=d["index_count"];
+ index_count = d["index_count"];
- Vector< PoolVector<uint8_t> > blend_shapes;
+ Vector<PoolVector<uint8_t> > blend_shapes;
if (d.has("blend_shape_data")) {
- Array blend_shape_data=d["blend_shape_data"];
- for(int i=0;i<blend_shape_data.size();i++) {
+ Array blend_shape_data = d["blend_shape_data"];
+ for (int i = 0; i < blend_shape_data.size(); i++) {
PoolVector<uint8_t> shape = blend_shape_data[i];
blend_shapes.push_back(shape);
}
}
- ERR_FAIL_COND_V(!d.has("aabb"),false);
+ ERR_FAIL_COND_V(!d.has("aabb"), false);
Rect3 aabb = d["aabb"];
Vector<Rect3> bone_aabb;
@@ -169,247 +166,228 @@ bool Mesh::_set(const StringName& p_name, const Variant& p_value) {
Array baabb = d["bone_aabb"];
bone_aabb.resize(baabb.size());
- for(int i=0;i<baabb.size();i++) {
- bone_aabb[i]=baabb[i];
+ for (int i = 0; i < baabb.size(); i++) {
+ bone_aabb[i] = baabb[i];
}
}
- add_surface(format,PrimitiveType(primitive),array_data,vertex_count,array_index_data,index_count,aabb,blend_shapes,bone_aabb);
+ add_surface(format, PrimitiveType(primitive), array_data, vertex_count, array_index_data, index_count, aabb, blend_shapes, bone_aabb);
} else {
ERR_FAIL_V(false);
}
-
if (d.has("material")) {
- surface_set_material(idx,d["material"]);
+ surface_set_material(idx, d["material"]);
}
if (d.has("name")) {
- surface_set_name(idx,d["name"]);
+ surface_set_name(idx, d["name"]);
}
-
return true;
}
return false;
}
-bool Mesh::_get(const StringName& p_name,Variant &r_ret) const {
+bool Mesh::_get(const StringName &p_name, Variant &r_ret) const {
- String sname=p_name;
+ String sname = p_name;
- if (p_name=="blend_shape/names") {
+ if (p_name == "blend_shape/names") {
PoolVector<String> sk;
- for(int i=0;i<blend_shapes.size();i++)
+ for (int i = 0; i < blend_shapes.size(); i++)
sk.push_back(blend_shapes[i]);
- r_ret=sk;
+ r_ret = sk;
return true;
- } else if (p_name=="blend_shape/mode") {
+ } else if (p_name == "blend_shape/mode") {
r_ret = get_blend_shape_mode();
return true;
} else if (sname.begins_with("surface_")) {
- int sl=sname.find("/");
- if (sl==-1)
+ int sl = sname.find("/");
+ if (sl == -1)
return false;
- int idx=sname.substr(8,sl-8).to_int()-1;
- String what = sname.get_slicec('/',1);
- if (what=="material")
- r_ret=surface_get_material(idx);
- else if (what=="name")
- r_ret=surface_get_name(idx);
+ int idx = sname.substr(8, sl - 8).to_int() - 1;
+ String what = sname.get_slicec('/', 1);
+ if (what == "material")
+ r_ret = surface_get_material(idx);
+ else if (what == "name")
+ r_ret = surface_get_name(idx);
return true;
- } else if (sname=="custom_aabb/custom_aabb") {
+ } else if (sname == "custom_aabb/custom_aabb") {
- r_ret=custom_aabb;
+ r_ret = custom_aabb;
return true;
} else if (!sname.begins_with("surfaces"))
return false;
-
- int idx=sname.get_slicec('/',1).to_int();
- ERR_FAIL_INDEX_V(idx,surfaces.size(),false);
+ int idx = sname.get_slicec('/', 1).to_int();
+ ERR_FAIL_INDEX_V(idx, surfaces.size(), false);
Dictionary d;
- d["array_data"]=VS::get_singleton()->mesh_surface_get_array(mesh,idx);
- d["vertex_count"]=VS::get_singleton()->mesh_surface_get_array_len(mesh,idx);
- d["array_index_data"]=VS::get_singleton()->mesh_surface_get_index_array(mesh,idx);
- d["index_count"]=VS::get_singleton()->mesh_surface_get_array_index_len(mesh,idx);
- d["primitive"]=VS::get_singleton()->mesh_surface_get_primitive_type(mesh,idx);
- d["format"]=VS::get_singleton()->mesh_surface_get_format(mesh,idx);
- d["aabb"]=VS::get_singleton()->mesh_surface_get_aabb(mesh,idx);
+ d["array_data"] = VS::get_singleton()->mesh_surface_get_array(mesh, idx);
+ d["vertex_count"] = VS::get_singleton()->mesh_surface_get_array_len(mesh, idx);
+ d["array_index_data"] = VS::get_singleton()->mesh_surface_get_index_array(mesh, idx);
+ d["index_count"] = VS::get_singleton()->mesh_surface_get_array_index_len(mesh, idx);
+ d["primitive"] = VS::get_singleton()->mesh_surface_get_primitive_type(mesh, idx);
+ d["format"] = VS::get_singleton()->mesh_surface_get_format(mesh, idx);
+ d["aabb"] = VS::get_singleton()->mesh_surface_get_aabb(mesh, idx);
- Vector<Rect3> skel_aabb = VS::get_singleton()->mesh_surface_get_skeleton_aabb(mesh,idx);
+ Vector<Rect3> skel_aabb = VS::get_singleton()->mesh_surface_get_skeleton_aabb(mesh, idx);
Array arr;
- for(int i=0;i<skel_aabb.size();i++) {
- arr[i]=skel_aabb[i];
+ for (int i = 0; i < skel_aabb.size(); i++) {
+ arr[i] = skel_aabb[i];
}
- d["skeleton_aabb"]=arr;
+ d["skeleton_aabb"] = arr;
- Vector< PoolVector<uint8_t> > blend_shape_data = VS::get_singleton()->mesh_surface_get_blend_shapes(mesh,idx);
+ Vector<PoolVector<uint8_t> > blend_shape_data = VS::get_singleton()->mesh_surface_get_blend_shapes(mesh, idx);
Array md;
- for(int i=0;i<blend_shape_data.size();i++) {
+ for (int i = 0; i < blend_shape_data.size(); i++) {
md.push_back(blend_shape_data[i]);
}
- d["blend_shape_data"]=md;
+ d["blend_shape_data"] = md;
Ref<Material> m = surface_get_material(idx);
if (m.is_valid())
- d["material"]=m;
+ d["material"] = m;
String n = surface_get_name(idx);
- if (n!="")
- d["name"]=n;
+ if (n != "")
+ d["name"] = n;
- r_ret=d;
+ r_ret = d;
return true;
}
-void Mesh::_get_property_list( List<PropertyInfo> *p_list) const {
+void Mesh::_get_property_list(List<PropertyInfo> *p_list) const {
if (blend_shapes.size()) {
- p_list->push_back(PropertyInfo(Variant::POOL_STRING_ARRAY,"blend_shape/names",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::INT,"blend_shape/mode",PROPERTY_HINT_ENUM,"Normalized,Relative"));
+ p_list->push_back(PropertyInfo(Variant::POOL_STRING_ARRAY, "blend_shape/names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::INT, "blend_shape/mode", PROPERTY_HINT_ENUM, "Normalized,Relative"));
}
- for (int i=0;i<surfaces.size();i++) {
+ for (int i = 0; i < surfaces.size(); i++) {
- p_list->push_back( PropertyInfo( Variant::DICTIONARY,"surfaces/"+itos(i), PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR ) );
- p_list->push_back( PropertyInfo( Variant::STRING,"surface_"+itos(i+1)+"/name", PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR ) );
- p_list->push_back( PropertyInfo( Variant::OBJECT,"surface_"+itos(i+1)+"/material", PROPERTY_HINT_RESOURCE_TYPE,"Material",PROPERTY_USAGE_EDITOR ) );
+ p_list->push_back(PropertyInfo(Variant::DICTIONARY, "surfaces/" + itos(i), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i + 1) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "Material", PROPERTY_USAGE_EDITOR));
}
- p_list->push_back( PropertyInfo( Variant::RECT3,"custom_aabb/custom_aabb" ) );
-
+ p_list->push_back(PropertyInfo(Variant::RECT3, "custom_aabb/custom_aabb"));
}
-
void Mesh::_recompute_aabb() {
// regenerate AABB
- aabb=Rect3();
+ aabb = Rect3();
- for (int i=0;i<surfaces.size();i++) {
+ for (int i = 0; i < surfaces.size(); i++) {
- if (i==0)
- aabb=surfaces[i].aabb;
+ if (i == 0)
+ aabb = surfaces[i].aabb;
else
aabb.merge_with(surfaces[i].aabb);
}
-
}
-void Mesh::add_surface(uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes,const Vector<Rect3>& p_bone_aabbs) {
+void Mesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes, const Vector<Rect3> &p_bone_aabbs) {
Surface s;
- s.aabb=p_aabb;
+ s.aabb = p_aabb;
surfaces.push_back(s);
- VisualServer::get_singleton()->mesh_add_surface(mesh,p_format,(VS::PrimitiveType)p_primitive,p_array,p_vertex_count,p_index_array,p_index_count,p_aabb,p_blend_shapes,p_bone_aabbs);
-
+ VisualServer::get_singleton()->mesh_add_surface(mesh, p_format, (VS::PrimitiveType)p_primitive, p_array, p_vertex_count, p_index_array, p_index_count, p_aabb, p_blend_shapes, p_bone_aabbs);
}
-void Mesh::add_surface_from_arrays(PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,uint32_t p_flags) {
-
+void Mesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_flags) {
- ERR_FAIL_COND(p_arrays.size()!=ARRAY_MAX);
+ ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX);
Surface s;
- VisualServer::get_singleton()->mesh_add_surface_from_arrays(mesh,(VisualServer::PrimitiveType)p_primitive, p_arrays,p_blend_shapes,p_flags);
+ VisualServer::get_singleton()->mesh_add_surface_from_arrays(mesh, (VisualServer::PrimitiveType)p_primitive, p_arrays, p_blend_shapes, p_flags);
surfaces.push_back(s);
-
-
/* make aABB? */ {
- PoolVector<Vector3> vertices=p_arrays[ARRAY_VERTEX];
- int len=vertices.size();
- ERR_FAIL_COND(len==0);
- PoolVector<Vector3>::Read r=vertices.read();
- const Vector3 *vtx=r.ptr();
+ PoolVector<Vector3> vertices = p_arrays[ARRAY_VERTEX];
+ int len = vertices.size();
+ ERR_FAIL_COND(len == 0);
+ PoolVector<Vector3>::Read r = vertices.read();
+ const Vector3 *vtx = r.ptr();
// check AABB
Rect3 aabb;
- for (int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- if (i==0)
- aabb.pos=vtx[i];
+ if (i == 0)
+ aabb.pos = vtx[i];
else
aabb.expand_to(vtx[i]);
}
- surfaces[surfaces.size()-1].aabb=aabb;
+ surfaces[surfaces.size() - 1].aabb = aabb;
_recompute_aabb();
-
}
- triangle_mesh=Ref<TriangleMesh>();
+ triangle_mesh = Ref<TriangleMesh>();
_change_notify();
emit_changed();
-
}
Array Mesh::surface_get_arrays(int p_surface) const {
- ERR_FAIL_INDEX_V(p_surface,surfaces.size(),Array());
- return VisualServer::get_singleton()->mesh_surface_get_arrays(mesh,p_surface);
-
+ ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
+ return VisualServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
}
Array Mesh::surface_get_blend_shape_arrays(int p_surface) const {
- ERR_FAIL_INDEX_V(p_surface,surfaces.size(),Array());
+ ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
return Array();
-
}
-
-
-
int Mesh::get_surface_count() const {
return surfaces.size();
}
-void Mesh::add_blend_shape(const StringName& p_name) {
+void Mesh::add_blend_shape(const StringName &p_name) {
if (surfaces.size()) {
ERR_EXPLAIN("Can't add a shape key count if surfaces are already created.");
ERR_FAIL_COND(surfaces.size());
}
- StringName name=p_name;
+ StringName name = p_name;
- if (blend_shapes.find(name)!=-1 ) {
+ if (blend_shapes.find(name) != -1) {
- int count=2;
+ int count = 2;
do {
name = String(p_name) + " " + itos(count);
count++;
- } while(blend_shapes.find(name)!=-1);
+ } while (blend_shapes.find(name) != -1);
}
blend_shapes.push_back(name);
- VS::get_singleton()->mesh_set_blend_shape_count(mesh,blend_shapes.size());
-
+ VS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
}
-
int Mesh::get_blend_shape_count() const {
return blend_shapes.size();
}
StringName Mesh::get_blend_shape_name(int p_index) const {
- ERR_FAIL_INDEX_V( p_index, blend_shapes.size(),StringName() );
+ ERR_FAIL_INDEX_V(p_index, blend_shapes.size(), StringName());
return blend_shapes[p_index];
}
void Mesh::clear_blend_shapes() {
@@ -424,8 +402,8 @@ void Mesh::clear_blend_shapes() {
void Mesh::set_blend_shape_mode(BlendShapeMode p_mode) {
- blend_shape_mode=p_mode;
- VS::get_singleton()->mesh_set_blend_shape_mode(mesh,(VS::BlendShapeMode)p_mode);
+ blend_shape_mode = p_mode;
+ VS::get_singleton()->mesh_set_blend_shape_mode(mesh, (VS::BlendShapeMode)p_mode);
}
Mesh::BlendShapeMode Mesh::get_blend_shape_mode() const {
@@ -433,113 +411,99 @@ Mesh::BlendShapeMode Mesh::get_blend_shape_mode() const {
return blend_shape_mode;
}
-
void Mesh::surface_remove(int p_idx) {
- ERR_FAIL_INDEX(p_idx, surfaces.size() );
- VisualServer::get_singleton()->mesh_remove_surface(mesh,p_idx);
+ ERR_FAIL_INDEX(p_idx, surfaces.size());
+ VisualServer::get_singleton()->mesh_remove_surface(mesh, p_idx);
surfaces.remove(p_idx);
- triangle_mesh=Ref<TriangleMesh>();
+ triangle_mesh = Ref<TriangleMesh>();
_recompute_aabb();
_change_notify();
emit_changed();
}
-
-
-
-
int Mesh::surface_get_array_len(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(), -1 );
- return VisualServer::get_singleton()->mesh_surface_get_array_len( mesh, p_idx );
-
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
+ return VisualServer::get_singleton()->mesh_surface_get_array_len(mesh, p_idx);
}
int Mesh::surface_get_array_index_len(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(), -1 );
- return VisualServer::get_singleton()->mesh_surface_get_array_index_len( mesh, p_idx );
-
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
+ return VisualServer::get_singleton()->mesh_surface_get_array_index_len(mesh, p_idx);
}
uint32_t Mesh::surface_get_format(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(), 0 );
- return VisualServer::get_singleton()->mesh_surface_get_format( mesh, p_idx );
-
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0);
+ return VisualServer::get_singleton()->mesh_surface_get_format(mesh, p_idx);
}
-
-
Mesh::PrimitiveType Mesh::surface_get_primitive_type(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(), PRIMITIVE_LINES );
- return (PrimitiveType)VisualServer::get_singleton()->mesh_surface_get_primitive_type( mesh, p_idx );
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), PRIMITIVE_LINES);
+ return (PrimitiveType)VisualServer::get_singleton()->mesh_surface_get_primitive_type(mesh, p_idx);
}
+void Mesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
-void Mesh::surface_set_material(int p_idx, const Ref<Material>& p_material) {
-
- ERR_FAIL_INDEX( p_idx, surfaces.size() );
- if (surfaces[p_idx].material==p_material)
+ ERR_FAIL_INDEX(p_idx, surfaces.size());
+ if (surfaces[p_idx].material == p_material)
return;
- surfaces[p_idx].material=p_material;
- VisualServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null()?RID():p_material->get_rid());
+ surfaces[p_idx].material = p_material;
+ VisualServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null() ? RID() : p_material->get_rid());
_change_notify("material");
}
-void Mesh::surface_set_name(int p_idx, const String& p_name) {
+void Mesh::surface_set_name(int p_idx, const String &p_name) {
- ERR_FAIL_INDEX( p_idx, surfaces.size() );
+ ERR_FAIL_INDEX(p_idx, surfaces.size());
- surfaces[p_idx].name=p_name;
+ surfaces[p_idx].name = p_name;
}
-String Mesh::surface_get_name(int p_idx) const{
+String Mesh::surface_get_name(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(),String() );
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), String());
return surfaces[p_idx].name;
-
}
-void Mesh::surface_set_custom_aabb(int p_idx,const Rect3& p_aabb) {
+void Mesh::surface_set_custom_aabb(int p_idx, const Rect3 &p_aabb) {
- ERR_FAIL_INDEX( p_idx, surfaces.size() );
- surfaces[p_idx].aabb=p_aabb;
-// set custom aabb too?
+ ERR_FAIL_INDEX(p_idx, surfaces.size());
+ surfaces[p_idx].aabb = p_aabb;
+ // set custom aabb too?
}
-Ref<Material> Mesh::surface_get_material(int p_idx) const {
+Ref<Material> Mesh::surface_get_material(int p_idx) const {
- ERR_FAIL_INDEX_V( p_idx, surfaces.size(), Ref<Material>() );
+ ERR_FAIL_INDEX_V(p_idx, surfaces.size(), Ref<Material>());
return surfaces[p_idx].material;
-
}
-void Mesh::add_surface_from_mesh_data(const Geometry::MeshData& p_mesh_data) {
+void Mesh::add_surface_from_mesh_data(const Geometry::MeshData &p_mesh_data) {
- VisualServer::get_singleton()->mesh_add_surface_from_mesh_data( mesh, p_mesh_data );
+ VisualServer::get_singleton()->mesh_add_surface_from_mesh_data(mesh, p_mesh_data);
Rect3 aabb;
- for (int i=0;i<p_mesh_data.vertices.size();i++) {
+ for (int i = 0; i < p_mesh_data.vertices.size(); i++) {
- if (i==0)
- aabb.pos=p_mesh_data.vertices[i];
+ if (i == 0)
+ aabb.pos = p_mesh_data.vertices[i];
else
aabb.expand_to(p_mesh_data.vertices[i]);
}
-
Surface s;
- s.aabb=aabb;
- if (surfaces.size()==0)
- aabb=s.aabb;
+ s.aabb = aabb;
+ if (surfaces.size() == 0)
+ aabb = s.aabb;
else
aabb.merge_with(s.aabb);
- triangle_mesh=Ref<TriangleMesh>();
+ triangle_mesh = Ref<TriangleMesh>();
surfaces.push_back(s);
_change_notify();
@@ -556,11 +520,10 @@ Rect3 Mesh::get_aabb() const {
return aabb;
}
+void Mesh::set_custom_aabb(const Rect3 &p_custom) {
-void Mesh::set_custom_aabb(const Rect3& p_custom) {
-
- custom_aabb=p_custom;
- VS::get_singleton()->mesh_set_custom_aabb(mesh,custom_aabb);
+ custom_aabb = p_custom;
+ VS::get_singleton()->mesh_set_custom_aabb(mesh, custom_aabb);
}
Rect3 Mesh::get_custom_aabb() const {
@@ -568,15 +531,13 @@ Rect3 Mesh::get_custom_aabb() const {
return custom_aabb;
}
-
PoolVector<Face3> Mesh::get_faces() const {
-
Ref<TriangleMesh> tm = generate_triangle_mesh();
if (tm.is_valid())
return tm->get_faces();
return PoolVector<Face3>();
-/*
+ /*
for (int i=0;i<surfaces.size();i++) {
if (VisualServer::get_singleton()->mesh_surface_get_primitive_type( mesh, i ) != VisualServer::PRIMITIVE_TRIANGLES )
@@ -634,22 +595,20 @@ PoolVector<Face3> Mesh::get_faces() const {
}
*/
-
}
Ref<Shape> Mesh::create_convex_shape() const {
PoolVector<Vector3> vertices;
- for(int i=0;i<get_surface_count();i++) {
+ for (int i = 0; i < get_surface_count(); i++) {
Array a = surface_get_arrays(i);
- PoolVector<Vector3> v=a[ARRAY_VERTEX];
+ PoolVector<Vector3> v = a[ARRAY_VERTEX];
vertices.append_array(v);
-
}
- Ref<ConvexPolygonShape> shape = memnew( ConvexPolygonShape );
+ Ref<ConvexPolygonShape> shape = memnew(ConvexPolygonShape);
shape->set_points(vertices);
return shape;
}
@@ -657,26 +616,26 @@ Ref<Shape> Mesh::create_convex_shape() const {
Ref<Shape> Mesh::create_trimesh_shape() const {
PoolVector<Face3> faces = get_faces();
- if (faces.size()==0)
+ if (faces.size() == 0)
return Ref<Shape>();
PoolVector<Vector3> face_points;
- face_points.resize( faces.size()*3 );
+ face_points.resize(faces.size() * 3);
- for (int i=0;i<face_points.size();i++) {
+ for (int i = 0; i < face_points.size(); i++) {
- Face3 f = faces.get( i/3 );
- face_points.set(i, f.vertex[i%3] );
+ Face3 f = faces.get(i / 3);
+ face_points.set(i, f.vertex[i % 3]);
}
- Ref<ConcavePolygonShape> shape = memnew( ConcavePolygonShape );
+ Ref<ConcavePolygonShape> shape = memnew(ConcavePolygonShape);
shape->set_faces(face_points);
return shape;
}
void Mesh::center_geometry() {
-/*
+ /*
Vector3 ofs = aabb.pos+aabb.size*0.5;
for(int i=0;i<get_surface_count();i++) {
@@ -700,17 +659,15 @@ void Mesh::center_geometry() {
aabb.pos-=ofs;
*/
-
}
void Mesh::regen_normalmaps() {
+ Vector<Ref<SurfaceTool> > surfs;
+ for (int i = 0; i < get_surface_count(); i++) {
- Vector< Ref<SurfaceTool> > surfs;
- for(int i=0;i<get_surface_count();i++) {
-
- Ref<SurfaceTool> st = memnew( SurfaceTool );
- st->create_from(Ref<Mesh>(this),i);
+ Ref<SurfaceTool> st = memnew(SurfaceTool);
+ st->create_from(Ref<Mesh>(this), i);
surfs.push_back(st);
}
@@ -718,129 +675,121 @@ void Mesh::regen_normalmaps() {
surface_remove(0);
}
- for(int i=0;i<surfs.size();i++) {
+ for (int i = 0; i < surfs.size(); i++) {
surfs[i]->generate_tangents();
surfs[i]->commit(Ref<Mesh>(this));
}
}
-
-
Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
if (triangle_mesh.is_valid())
return triangle_mesh;
- int facecount=0;
+ int facecount = 0;
- for(int i=0;i<get_surface_count();i++) {
+ for (int i = 0; i < get_surface_count(); i++) {
- if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES)
+ if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
continue;
- if (surface_get_format(i)&ARRAY_FORMAT_INDEX) {
+ if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
- facecount+=surface_get_array_index_len(i);
+ facecount += surface_get_array_index_len(i);
} else {
- facecount+=surface_get_array_len(i);
+ facecount += surface_get_array_len(i);
}
-
}
- if (facecount==0 || (facecount%3)!=0)
+ if (facecount == 0 || (facecount % 3) != 0)
return triangle_mesh;
PoolVector<Vector3> faces;
faces.resize(facecount);
- PoolVector<Vector3>::Write facesw=faces.write();
+ PoolVector<Vector3>::Write facesw = faces.write();
- int widx=0;
+ int widx = 0;
- for(int i=0;i<get_surface_count();i++) {
+ for (int i = 0; i < get_surface_count(); i++) {
- if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES)
+ if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
continue;
Array a = surface_get_arrays(i);
int vc = surface_get_array_len(i);
PoolVector<Vector3> vertices = a[ARRAY_VERTEX];
- PoolVector<Vector3>::Read vr=vertices.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
- if (surface_get_format(i)&ARRAY_FORMAT_INDEX) {
+ if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
- int ic=surface_get_array_index_len(i);
+ int ic = surface_get_array_index_len(i);
PoolVector<int> indices = a[ARRAY_INDEX];
PoolVector<int>::Read ir = indices.read();
- for(int i=0;i<ic;i++) {
+ for (int i = 0; i < ic; i++) {
int index = ir[i];
- facesw[widx++]=vr[ index ];
+ facesw[widx++] = vr[index];
}
} else {
- for(int i=0;i<vc;i++)
- facesw[widx++]=vr[ i ];
+ for (int i = 0; i < vc; i++)
+ facesw[widx++] = vr[i];
}
-
}
- facesw=PoolVector<Vector3>::Write();
-
+ facesw = PoolVector<Vector3>::Write();
- triangle_mesh = Ref<TriangleMesh>( memnew( TriangleMesh ));
+ triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
triangle_mesh->create(faces);
return triangle_mesh;
-
-
}
Ref<Mesh> Mesh::create_outline(float p_margin) const {
-
Array arrays;
- int index_accum=0;
- for(int i=0;i<get_surface_count();i++) {
+ int index_accum = 0;
+ for (int i = 0; i < get_surface_count(); i++) {
- if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES)
+ if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
continue;
Array a = surface_get_arrays(i);
- int vcount=0;
+ int vcount = 0;
- if (i==0) {
- arrays=a;
- PoolVector<Vector3> v=a[ARRAY_VERTEX];
- index_accum+=v.size();
+ if (i == 0) {
+ arrays = a;
+ PoolVector<Vector3> v = a[ARRAY_VERTEX];
+ index_accum += v.size();
} else {
- for(int j=0;j<arrays.size();j++) {
+ for (int j = 0; j < arrays.size(); j++) {
- if (arrays[j].get_type()==Variant::NIL || a[j].get_type()==Variant::NIL) {
+ if (arrays[j].get_type() == Variant::NIL || a[j].get_type() == Variant::NIL) {
//mismatch, do not use
- arrays[j]=Variant();
+ arrays[j] = Variant();
continue;
}
- switch(j) {
+ switch (j) {
case ARRAY_VERTEX:
- case ARRAY_NORMAL: {
+ case ARRAY_NORMAL: {
PoolVector<Vector3> dst = arrays[j];
PoolVector<Vector3> src = a[j];
- if (j==ARRAY_VERTEX)
- vcount=src.size();
- if (dst.size()==0 || src.size()==0) {
- arrays[j]=Variant();
+ if (j == ARRAY_VERTEX)
+ vcount = src.size();
+ if (dst.size() == 0 || src.size() == 0) {
+ arrays[j] = Variant();
continue;
}
dst.append_array(src);
- arrays[j]=dst;
+ arrays[j] = dst;
} break;
case ARRAY_TANGENT:
case ARRAY_BONES:
@@ -848,58 +797,56 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const {
PoolVector<real_t> dst = arrays[j];
PoolVector<real_t> src = a[j];
- if (dst.size()==0 || src.size()==0) {
- arrays[j]=Variant();
+ if (dst.size() == 0 || src.size() == 0) {
+ arrays[j] = Variant();
continue;
}
dst.append_array(src);
- arrays[j]=dst;
+ arrays[j] = dst;
} break;
case ARRAY_COLOR: {
PoolVector<Color> dst = arrays[j];
PoolVector<Color> src = a[j];
- if (dst.size()==0 || src.size()==0) {
- arrays[j]=Variant();
+ if (dst.size() == 0 || src.size() == 0) {
+ arrays[j] = Variant();
continue;
}
dst.append_array(src);
- arrays[j]=dst;
+ arrays[j] = dst;
} break;
case ARRAY_TEX_UV:
case ARRAY_TEX_UV2: {
PoolVector<Vector2> dst = arrays[j];
PoolVector<Vector2> src = a[j];
- if (dst.size()==0 || src.size()==0) {
- arrays[j]=Variant();
+ if (dst.size() == 0 || src.size() == 0) {
+ arrays[j] = Variant();
continue;
}
dst.append_array(src);
- arrays[j]=dst;
+ arrays[j] = dst;
} break;
case ARRAY_INDEX: {
PoolVector<int> dst = arrays[j];
PoolVector<int> src = a[j];
- if (dst.size()==0 || src.size()==0) {
- arrays[j]=Variant();
+ if (dst.size() == 0 || src.size() == 0) {
+ arrays[j] = Variant();
continue;
}
{
int ss = src.size();
PoolVector<int>::Write w = src.write();
- for(int k=0;k<ss;k++) {
- w[k]+=index_accum;
+ for (int k = 0; k < ss; k++) {
+ w[k] += index_accum;
}
-
}
dst.append_array(src);
- arrays[j]=dst;
- index_accum+=vcount;
+ arrays[j] = dst;
+ index_accum += vcount;
} break;
-
}
}
}
@@ -907,49 +854,47 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const {
{
PoolVector<int>::Write ir;
- PoolVector<int> indices =arrays[ARRAY_INDEX];
- bool has_indices=false;
- PoolVector<Vector3> vertices =arrays[ARRAY_VERTEX];
+ PoolVector<int> indices = arrays[ARRAY_INDEX];
+ bool has_indices = false;
+ PoolVector<Vector3> vertices = arrays[ARRAY_VERTEX];
int vc = vertices.size();
- ERR_FAIL_COND_V(!vc,Ref<Mesh>());
- PoolVector<Vector3>::Write r=vertices.write();
-
+ ERR_FAIL_COND_V(!vc, Ref<Mesh>());
+ PoolVector<Vector3>::Write r = vertices.write();
if (indices.size()) {
- vc=indices.size();
- ir=indices.write();
- has_indices=true;
+ vc = indices.size();
+ ir = indices.write();
+ has_indices = true;
}
- Map<Vector3,Vector3> normal_accum;
+ Map<Vector3, Vector3> normal_accum;
//fill normals with triangle normals
- for(int i=0;i<vc;i+=3) {
-
+ for (int i = 0; i < vc; i += 3) {
Vector3 t[3];
if (has_indices) {
- t[0]=r[ir[i+0]];
- t[1]=r[ir[i+1]];
- t[2]=r[ir[i+2]];
+ t[0] = r[ir[i + 0]];
+ t[1] = r[ir[i + 1]];
+ t[2] = r[ir[i + 2]];
} else {
- t[0]=r[i+0];
- t[1]=r[i+1];
- t[2]=r[i+2];
+ t[0] = r[i + 0];
+ t[1] = r[i + 1];
+ t[2] = r[i + 2];
}
- Vector3 n = Plane(t[0],t[1],t[2]).normal;
+ Vector3 n = Plane(t[0], t[1], t[2]).normal;
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- Map<Vector3,Vector3>::Element *E=normal_accum.find(t[j]);
+ Map<Vector3, Vector3>::Element *E = normal_accum.find(t[j]);
if (!E) {
- normal_accum[t[j]]=n;
+ normal_accum[t[j]] = n;
} else {
float d = n.dot(E->get());
- if (d<1.0)
- E->get()+=n*(1.0-d);
+ if (d < 1.0)
+ E->get() += n * (1.0 - d);
//E->get()+=n;
}
}
@@ -957,28 +902,26 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const {
//normalize
- for (Map<Vector3,Vector3>::Element *E=normal_accum.front();E;E=E->next()) {
+ for (Map<Vector3, Vector3>::Element *E = normal_accum.front(); E; E = E->next()) {
E->get().normalize();
}
-
//displace normals
int vc2 = vertices.size();
- for(int i=0;i<vc2;i++) {
-
+ for (int i = 0; i < vc2; i++) {
- Vector3 t=r[i];
+ Vector3 t = r[i];
- Map<Vector3,Vector3>::Element *E=normal_accum.find(t);
+ Map<Vector3, Vector3>::Element *E = normal_accum.find(t);
ERR_CONTINUE(!E);
- t+=E->get()*p_margin;
- r[i]=t;
+ t += E->get() * p_margin;
+ r[i] = t;
}
r = PoolVector<Vector3>::Write();
- arrays[ARRAY_VERTEX]=vertices;
+ arrays[ARRAY_VERTEX] = vertices;
if (!has_indices) {
@@ -986,112 +929,99 @@ Ref<Mesh> Mesh::create_outline(float p_margin) const {
new_indices.resize(vertices.size());
PoolVector<int>::Write iw = new_indices.write();
- for(int j=0;j<vc2;j+=3) {
+ for (int j = 0; j < vc2; j += 3) {
- iw[j]=j;
- iw[j+1]=j+2;
- iw[j+2]=j+1;
+ iw[j] = j;
+ iw[j + 1] = j + 2;
+ iw[j + 2] = j + 1;
}
- iw=PoolVector<int>::Write();
- arrays[ARRAY_INDEX]=new_indices;
+ iw = PoolVector<int>::Write();
+ arrays[ARRAY_INDEX] = new_indices;
} else {
- for(int j=0;j<vc;j+=3) {
+ for (int j = 0; j < vc; j += 3) {
- SWAP(ir[j+1],ir[j+2]);
+ SWAP(ir[j + 1], ir[j + 2]);
}
- ir=PoolVector<int>::Write();
- arrays[ARRAY_INDEX]=indices;
-
+ ir = PoolVector<int>::Write();
+ arrays[ARRAY_INDEX] = indices;
}
}
-
-
-
- Ref<Mesh> newmesh = memnew( Mesh );
- newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES,arrays);
+ Ref<Mesh> newmesh = memnew(Mesh);
+ newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES, arrays);
return newmesh;
}
-
void Mesh::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_blend_shape","name"),&Mesh::add_blend_shape);
- ClassDB::bind_method(D_METHOD("get_blend_shape_count"),&Mesh::get_blend_shape_count);
- ClassDB::bind_method(D_METHOD("get_blend_shape_name","index"),&Mesh::get_blend_shape_name);
- ClassDB::bind_method(D_METHOD("clear_blend_shapes"),&Mesh::clear_blend_shapes);
- ClassDB::bind_method(D_METHOD("set_blend_shape_mode","mode"),&Mesh::set_blend_shape_mode);
- ClassDB::bind_method(D_METHOD("get_blend_shape_mode"),&Mesh::get_blend_shape_mode);
-
- ClassDB::bind_method(D_METHOD("add_surface_from_arrays","primitive","arrays","blend_shapes","compress_flags"),&Mesh::add_surface_from_arrays,DEFVAL(Array()),DEFVAL(ARRAY_COMPRESS_DEFAULT));
- ClassDB::bind_method(D_METHOD("get_surface_count"),&Mesh::get_surface_count);
- ClassDB::bind_method(D_METHOD("surface_remove","surf_idx"),&Mesh::surface_remove);
- ClassDB::bind_method(D_METHOD("surface_get_array_len","surf_idx"),&Mesh::surface_get_array_len);
- ClassDB::bind_method(D_METHOD("surface_get_array_index_len","surf_idx"),&Mesh::surface_get_array_index_len);
- ClassDB::bind_method(D_METHOD("surface_get_format","surf_idx"),&Mesh::surface_get_format);
- ClassDB::bind_method(D_METHOD("surface_get_primitive_type","surf_idx"),&Mesh::surface_get_primitive_type);
- ClassDB::bind_method(D_METHOD("surface_set_material","surf_idx","material:Material"),&Mesh::surface_set_material);
- ClassDB::bind_method(D_METHOD("surface_get_material:Material","surf_idx"),&Mesh::surface_get_material);
- ClassDB::bind_method(D_METHOD("surface_set_name","surf_idx","name"),&Mesh::surface_set_name);
- ClassDB::bind_method(D_METHOD("surface_get_name","surf_idx"),&Mesh::surface_get_name);
- ClassDB::bind_method(D_METHOD("center_geometry"),&Mesh::center_geometry);
- ClassDB::set_method_flags(get_class_static(),_scs_create("center_geometry"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("regen_normalmaps"),&Mesh::regen_normalmaps);
- ClassDB::set_method_flags(get_class_static(),_scs_create("regen_normalmaps"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
-
- ClassDB::bind_method(D_METHOD("set_custom_aabb","aabb"),&Mesh::set_custom_aabb);
- ClassDB::bind_method(D_METHOD("get_custom_aabb"),&Mesh::get_custom_aabb);
-
-
- BIND_CONSTANT( NO_INDEX_ARRAY );
- BIND_CONSTANT( ARRAY_WEIGHTS_SIZE );
-
- BIND_CONSTANT( ARRAY_VERTEX );
- BIND_CONSTANT( ARRAY_NORMAL );
- BIND_CONSTANT( ARRAY_TANGENT );
- BIND_CONSTANT( ARRAY_COLOR );
- BIND_CONSTANT( ARRAY_TEX_UV );
- BIND_CONSTANT( ARRAY_TEX_UV2 );
- BIND_CONSTANT( ARRAY_BONES );
- BIND_CONSTANT( ARRAY_WEIGHTS );
- BIND_CONSTANT( ARRAY_INDEX );
-
- BIND_CONSTANT( ARRAY_FORMAT_VERTEX );
- BIND_CONSTANT( ARRAY_FORMAT_NORMAL );
- BIND_CONSTANT( ARRAY_FORMAT_TANGENT );
- BIND_CONSTANT( ARRAY_FORMAT_COLOR );
- BIND_CONSTANT( ARRAY_FORMAT_TEX_UV );
- BIND_CONSTANT( ARRAY_FORMAT_TEX_UV2 );
- BIND_CONSTANT( ARRAY_FORMAT_BONES );
- BIND_CONSTANT( ARRAY_FORMAT_WEIGHTS );
- BIND_CONSTANT( ARRAY_FORMAT_INDEX );
-
- BIND_CONSTANT( PRIMITIVE_POINTS );
- BIND_CONSTANT( PRIMITIVE_LINES );
- BIND_CONSTANT( PRIMITIVE_LINE_STRIP );
- BIND_CONSTANT( PRIMITIVE_LINE_LOOP );
- BIND_CONSTANT( PRIMITIVE_TRIANGLES );
- BIND_CONSTANT( PRIMITIVE_TRIANGLE_STRIP );
- BIND_CONSTANT( PRIMITIVE_TRIANGLE_FAN );
-
+ ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &Mesh::add_blend_shape);
+ ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &Mesh::get_blend_shape_count);
+ ClassDB::bind_method(D_METHOD("get_blend_shape_name", "index"), &Mesh::get_blend_shape_name);
+ ClassDB::bind_method(D_METHOD("clear_blend_shapes"), &Mesh::clear_blend_shapes);
+ ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &Mesh::set_blend_shape_mode);
+ ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &Mesh::get_blend_shape_mode);
+
+ ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "compress_flags"), &Mesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(ARRAY_COMPRESS_DEFAULT));
+ ClassDB::bind_method(D_METHOD("get_surface_count"), &Mesh::get_surface_count);
+ ClassDB::bind_method(D_METHOD("surface_remove", "surf_idx"), &Mesh::surface_remove);
+ ClassDB::bind_method(D_METHOD("surface_get_array_len", "surf_idx"), &Mesh::surface_get_array_len);
+ ClassDB::bind_method(D_METHOD("surface_get_array_index_len", "surf_idx"), &Mesh::surface_get_array_index_len);
+ ClassDB::bind_method(D_METHOD("surface_get_format", "surf_idx"), &Mesh::surface_get_format);
+ ClassDB::bind_method(D_METHOD("surface_get_primitive_type", "surf_idx"), &Mesh::surface_get_primitive_type);
+ ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material:Material"), &Mesh::surface_set_material);
+ ClassDB::bind_method(D_METHOD("surface_get_material:Material", "surf_idx"), &Mesh::surface_get_material);
+ ClassDB::bind_method(D_METHOD("surface_set_name", "surf_idx", "name"), &Mesh::surface_set_name);
+ ClassDB::bind_method(D_METHOD("surface_get_name", "surf_idx"), &Mesh::surface_get_name);
+ ClassDB::bind_method(D_METHOD("center_geometry"), &Mesh::center_geometry);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("center_geometry"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("regen_normalmaps"), &Mesh::regen_normalmaps);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("regen_normalmaps"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+
+ ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &Mesh::set_custom_aabb);
+ ClassDB::bind_method(D_METHOD("get_custom_aabb"), &Mesh::get_custom_aabb);
+
+ BIND_CONSTANT(NO_INDEX_ARRAY);
+ BIND_CONSTANT(ARRAY_WEIGHTS_SIZE);
+
+ BIND_CONSTANT(ARRAY_VERTEX);
+ BIND_CONSTANT(ARRAY_NORMAL);
+ BIND_CONSTANT(ARRAY_TANGENT);
+ BIND_CONSTANT(ARRAY_COLOR);
+ BIND_CONSTANT(ARRAY_TEX_UV);
+ BIND_CONSTANT(ARRAY_TEX_UV2);
+ BIND_CONSTANT(ARRAY_BONES);
+ BIND_CONSTANT(ARRAY_WEIGHTS);
+ BIND_CONSTANT(ARRAY_INDEX);
+
+ BIND_CONSTANT(ARRAY_FORMAT_VERTEX);
+ BIND_CONSTANT(ARRAY_FORMAT_NORMAL);
+ BIND_CONSTANT(ARRAY_FORMAT_TANGENT);
+ BIND_CONSTANT(ARRAY_FORMAT_COLOR);
+ BIND_CONSTANT(ARRAY_FORMAT_TEX_UV);
+ BIND_CONSTANT(ARRAY_FORMAT_TEX_UV2);
+ BIND_CONSTANT(ARRAY_FORMAT_BONES);
+ BIND_CONSTANT(ARRAY_FORMAT_WEIGHTS);
+ BIND_CONSTANT(ARRAY_FORMAT_INDEX);
+
+ BIND_CONSTANT(PRIMITIVE_POINTS);
+ BIND_CONSTANT(PRIMITIVE_LINES);
+ BIND_CONSTANT(PRIMITIVE_LINE_STRIP);
+ BIND_CONSTANT(PRIMITIVE_LINE_LOOP);
+ BIND_CONSTANT(PRIMITIVE_TRIANGLES);
+ BIND_CONSTANT(PRIMITIVE_TRIANGLE_STRIP);
+ BIND_CONSTANT(PRIMITIVE_TRIANGLE_FAN);
}
-
-
Mesh::Mesh() {
- mesh=VisualServer::get_singleton()->mesh_create();
- blend_shape_mode=BLEND_SHAPE_MODE_RELATIVE;
-
+ mesh = VisualServer::get_singleton()->mesh_create();
+ blend_shape_mode = BLEND_SHAPE_MODE_RELATIVE;
}
-
Mesh::~Mesh() {
VisualServer::get_singleton()->free(mesh);
}
-
-
diff --git a/scene/resources/mesh.h b/scene/resources/mesh.h
index 1af33ad836..8b1936ed06 100644
--- a/scene/resources/mesh.h
+++ b/scene/resources/mesh.h
@@ -29,86 +29,85 @@
#ifndef MESH_H
#define MESH_H
-#include "servers/visual_server.h"
+#include "resource.h"
#include "scene/resources/material.h"
#include "scene/resources/shape.h"
-#include "resource.h"
+#include "servers/visual_server.h"
#include "triangle_mesh.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class Mesh : public Resource {
- GDCLASS( Mesh, Resource );
+ GDCLASS(Mesh, Resource);
RES_BASE_EXTENSION("msh");
public:
-
enum {
- NO_INDEX_ARRAY=VisualServer::NO_INDEX_ARRAY,
- ARRAY_WEIGHTS_SIZE=VisualServer::ARRAY_WEIGHTS_SIZE
+ NO_INDEX_ARRAY = VisualServer::NO_INDEX_ARRAY,
+ ARRAY_WEIGHTS_SIZE = VisualServer::ARRAY_WEIGHTS_SIZE
};
enum ArrayType {
- ARRAY_VERTEX=VisualServer::ARRAY_VERTEX,
- ARRAY_NORMAL=VisualServer::ARRAY_NORMAL,
- ARRAY_TANGENT=VisualServer::ARRAY_TANGENT,
- ARRAY_COLOR=VisualServer::ARRAY_COLOR,
- ARRAY_TEX_UV=VisualServer::ARRAY_TEX_UV,
- ARRAY_TEX_UV2=VisualServer::ARRAY_TEX_UV2,
- ARRAY_BONES=VisualServer::ARRAY_BONES,
- ARRAY_WEIGHTS=VisualServer::ARRAY_WEIGHTS,
- ARRAY_INDEX=VisualServer::ARRAY_INDEX,
- ARRAY_MAX=VisualServer::ARRAY_MAX
+ ARRAY_VERTEX = VisualServer::ARRAY_VERTEX,
+ ARRAY_NORMAL = VisualServer::ARRAY_NORMAL,
+ ARRAY_TANGENT = VisualServer::ARRAY_TANGENT,
+ ARRAY_COLOR = VisualServer::ARRAY_COLOR,
+ ARRAY_TEX_UV = VisualServer::ARRAY_TEX_UV,
+ ARRAY_TEX_UV2 = VisualServer::ARRAY_TEX_UV2,
+ ARRAY_BONES = VisualServer::ARRAY_BONES,
+ ARRAY_WEIGHTS = VisualServer::ARRAY_WEIGHTS,
+ ARRAY_INDEX = VisualServer::ARRAY_INDEX,
+ ARRAY_MAX = VisualServer::ARRAY_MAX
};
enum ArrayFormat {
/* ARRAY FORMAT FLAGS */
- ARRAY_FORMAT_VERTEX=1<<ARRAY_VERTEX, // mandatory
- ARRAY_FORMAT_NORMAL=1<<ARRAY_NORMAL,
- ARRAY_FORMAT_TANGENT=1<<ARRAY_TANGENT,
- ARRAY_FORMAT_COLOR=1<<ARRAY_COLOR,
- ARRAY_FORMAT_TEX_UV=1<<ARRAY_TEX_UV,
- ARRAY_FORMAT_TEX_UV2=1<<ARRAY_TEX_UV2,
- ARRAY_FORMAT_BONES=1<<ARRAY_BONES,
- ARRAY_FORMAT_WEIGHTS=1<<ARRAY_WEIGHTS,
- ARRAY_FORMAT_INDEX=1<<ARRAY_INDEX,
-
- ARRAY_COMPRESS_BASE=(ARRAY_INDEX+1),
- ARRAY_COMPRESS_VERTEX=1<<(ARRAY_VERTEX+ARRAY_COMPRESS_BASE), // mandatory
- ARRAY_COMPRESS_NORMAL=1<<(ARRAY_NORMAL+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TANGENT=1<<(ARRAY_TANGENT+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_COLOR=1<<(ARRAY_COLOR+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TEX_UV=1<<(ARRAY_TEX_UV+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TEX_UV2=1<<(ARRAY_TEX_UV2+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_BONES=1<<(ARRAY_BONES+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_WEIGHTS=1<<(ARRAY_WEIGHTS+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_INDEX=1<<(ARRAY_INDEX+ARRAY_COMPRESS_BASE),
-
- ARRAY_FLAG_USE_2D_VERTICES=ARRAY_COMPRESS_INDEX<<1,
- ARRAY_FLAG_USE_16_BIT_BONES=ARRAY_COMPRESS_INDEX<<2,
-
- ARRAY_COMPRESS_DEFAULT=ARRAY_COMPRESS_VERTEX|ARRAY_COMPRESS_NORMAL|ARRAY_COMPRESS_TANGENT|ARRAY_COMPRESS_COLOR|ARRAY_COMPRESS_TEX_UV|ARRAY_COMPRESS_TEX_UV2|ARRAY_COMPRESS_WEIGHTS
+ ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX, // mandatory
+ ARRAY_FORMAT_NORMAL = 1 << ARRAY_NORMAL,
+ ARRAY_FORMAT_TANGENT = 1 << ARRAY_TANGENT,
+ ARRAY_FORMAT_COLOR = 1 << ARRAY_COLOR,
+ ARRAY_FORMAT_TEX_UV = 1 << ARRAY_TEX_UV,
+ ARRAY_FORMAT_TEX_UV2 = 1 << ARRAY_TEX_UV2,
+ ARRAY_FORMAT_BONES = 1 << ARRAY_BONES,
+ ARRAY_FORMAT_WEIGHTS = 1 << ARRAY_WEIGHTS,
+ ARRAY_FORMAT_INDEX = 1 << ARRAY_INDEX,
+
+ ARRAY_COMPRESS_BASE = (ARRAY_INDEX + 1),
+ ARRAY_COMPRESS_VERTEX = 1 << (ARRAY_VERTEX + ARRAY_COMPRESS_BASE), // mandatory
+ ARRAY_COMPRESS_NORMAL = 1 << (ARRAY_NORMAL + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TANGENT = 1 << (ARRAY_TANGENT + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_COLOR = 1 << (ARRAY_COLOR + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TEX_UV = 1 << (ARRAY_TEX_UV + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TEX_UV2 = 1 << (ARRAY_TEX_UV2 + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_BONES = 1 << (ARRAY_BONES + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_WEIGHTS = 1 << (ARRAY_WEIGHTS + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_INDEX = 1 << (ARRAY_INDEX + ARRAY_COMPRESS_BASE),
+
+ ARRAY_FLAG_USE_2D_VERTICES = ARRAY_COMPRESS_INDEX << 1,
+ ARRAY_FLAG_USE_16_BIT_BONES = ARRAY_COMPRESS_INDEX << 2,
+
+ ARRAY_COMPRESS_DEFAULT = ARRAY_COMPRESS_VERTEX | ARRAY_COMPRESS_NORMAL | ARRAY_COMPRESS_TANGENT | ARRAY_COMPRESS_COLOR | ARRAY_COMPRESS_TEX_UV | ARRAY_COMPRESS_TEX_UV2 | ARRAY_COMPRESS_WEIGHTS
};
enum PrimitiveType {
- PRIMITIVE_POINTS=VisualServer::PRIMITIVE_POINTS,
- PRIMITIVE_LINES=VisualServer::PRIMITIVE_LINES,
- PRIMITIVE_LINE_STRIP=VisualServer::PRIMITIVE_LINE_STRIP,
- PRIMITIVE_LINE_LOOP=VisualServer::PRIMITIVE_LINE_LOOP,
- PRIMITIVE_TRIANGLES=VisualServer::PRIMITIVE_TRIANGLES,
- PRIMITIVE_TRIANGLE_STRIP=VisualServer::PRIMITIVE_TRIANGLE_STRIP,
- PRIMITIVE_TRIANGLE_FAN=VisualServer::PRIMITIVE_TRIANGLE_FAN,
+ PRIMITIVE_POINTS = VisualServer::PRIMITIVE_POINTS,
+ PRIMITIVE_LINES = VisualServer::PRIMITIVE_LINES,
+ PRIMITIVE_LINE_STRIP = VisualServer::PRIMITIVE_LINE_STRIP,
+ PRIMITIVE_LINE_LOOP = VisualServer::PRIMITIVE_LINE_LOOP,
+ PRIMITIVE_TRIANGLES = VisualServer::PRIMITIVE_TRIANGLES,
+ PRIMITIVE_TRIANGLE_STRIP = VisualServer::PRIMITIVE_TRIANGLE_STRIP,
+ PRIMITIVE_TRIANGLE_FAN = VisualServer::PRIMITIVE_TRIANGLE_FAN,
};
enum BlendShapeMode {
- BLEND_SHAPE_MODE_NORMALIZED=VS::BLEND_SHAPE_MODE_NORMALIZED,
- BLEND_SHAPE_MODE_RELATIVE=VS::BLEND_SHAPE_MODE_RELATIVE,
+ BLEND_SHAPE_MODE_NORMALIZED = VS::BLEND_SHAPE_MODE_NORMALIZED,
+ BLEND_SHAPE_MODE_RELATIVE = VS::BLEND_SHAPE_MODE_RELATIVE,
};
private:
@@ -126,25 +125,23 @@ private:
mutable Ref<TriangleMesh> triangle_mesh;
-
void _recompute_aabb();
-protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+protected:
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
-
- void add_surface_from_arrays(PrimitiveType p_primitive, const Array& p_arrays, const Array& p_blend_shapes=Array(), uint32_t p_flags=ARRAY_COMPRESS_DEFAULT);
- void add_surface(uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>());
+ void add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), uint32_t p_flags = ARRAY_COMPRESS_DEFAULT);
+ void add_surface(uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>());
Array surface_get_arrays(int p_surface) const;
virtual Array surface_get_blend_shape_arrays(int p_surface) const;
- void add_blend_shape(const StringName& p_name);
+ void add_blend_shape(const StringName &p_name);
int get_blend_shape_count() const;
StringName get_blend_shape_name(int p_index) const;
void clear_blend_shapes();
@@ -155,8 +152,7 @@ public:
int get_surface_count() const;
void surface_remove(int p_idx);
- void surface_set_custom_aabb(int p_surface,const Rect3& p_aabb); //only recognized by driver
-
+ void surface_set_custom_aabb(int p_surface, const Rect3 &p_aabb); //only recognized by driver
int surface_get_array_len(int p_idx) const;
int surface_get_array_index_len(int p_idx) const;
@@ -164,15 +160,15 @@ public:
PrimitiveType surface_get_primitive_type(int p_idx) const;
bool surface_is_alpha_sorting_enabled(int p_idx) const;
- void surface_set_material(int p_idx, const Ref<Material>& p_material);
+ void surface_set_material(int p_idx, const Ref<Material> &p_material);
Ref<Material> surface_get_material(int p_idx) const;
- void surface_set_name(int p_idx, const String& p_name);
+ void surface_set_name(int p_idx, const String &p_name);
String surface_get_name(int p_idx) const;
- void add_surface_from_mesh_data(const Geometry::MeshData& p_mesh_data);
+ void add_surface_from_mesh_data(const Geometry::MeshData &p_mesh_data);
- void set_custom_aabb(const Rect3& p_custom);
+ void set_custom_aabb(const Rect3 &p_custom);
Rect3 get_custom_aabb() const;
Rect3 get_aabb() const;
@@ -191,11 +187,10 @@ public:
Mesh();
~Mesh();
-
};
-VARIANT_ENUM_CAST( Mesh::ArrayType );
-VARIANT_ENUM_CAST( Mesh::PrimitiveType );
-VARIANT_ENUM_CAST( Mesh::BlendShapeMode );
+VARIANT_ENUM_CAST(Mesh::ArrayType);
+VARIANT_ENUM_CAST(Mesh::PrimitiveType);
+VARIANT_ENUM_CAST(Mesh::BlendShapeMode);
#endif
diff --git a/scene/resources/mesh_data_tool.cpp b/scene/resources/mesh_data_tool.cpp
index abe335aa5b..fcc1f80d25 100644
--- a/scene/resources/mesh_data_tool.cpp
+++ b/scene/resources/mesh_data_tool.cpp
@@ -28,152 +28,142 @@
/*************************************************************************/
#include "mesh_data_tool.h"
-
void MeshDataTool::clear() {
vertices.clear();
edges.clear();
faces.clear();
material = Ref<Material>();
- format=0;
+ format = 0;
}
+Error MeshDataTool::create_from_surface(const Ref<Mesh> &p_mesh, int p_surface) {
-Error MeshDataTool::create_from_surface(const Ref<Mesh>& p_mesh,int p_surface) {
-
- ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER);
-
- ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER);
- ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface)!=Mesh::PRIMITIVE_TRIANGLES,ERR_INVALID_PARAMETER);
-
+ ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface) != Mesh::PRIMITIVE_TRIANGLES, ERR_INVALID_PARAMETER);
Array arrays = p_mesh->surface_get_arrays(p_surface);
- ERR_FAIL_COND_V( arrays.empty(), ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(arrays.empty(), ERR_INVALID_PARAMETER);
PoolVector<Vector3> varray = arrays[Mesh::ARRAY_VERTEX];
int vcount = varray.size();
- ERR_FAIL_COND_V( vcount == 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(vcount == 0, ERR_INVALID_PARAMETER);
clear();
format = p_mesh->surface_get_format(p_surface);
- material=p_mesh->surface_get_material(p_surface);
+ material = p_mesh->surface_get_material(p_surface);
PoolVector<Vector3>::Read vr = varray.read();
PoolVector<Vector3>::Read nr;
- if (arrays[Mesh::ARRAY_NORMAL].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_NORMAL].get_type() != Variant::NIL)
nr = arrays[Mesh::ARRAY_NORMAL].operator PoolVector<Vector3>().read();
PoolVector<real_t>::Read ta;
- if (arrays[Mesh::ARRAY_TANGENT].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_TANGENT].get_type() != Variant::NIL)
ta = arrays[Mesh::ARRAY_TANGENT].operator PoolVector<real_t>().read();
PoolVector<Vector2>::Read uv;
- if (arrays[Mesh::ARRAY_TEX_UV].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_TEX_UV].get_type() != Variant::NIL)
uv = arrays[Mesh::ARRAY_TEX_UV].operator PoolVector<Vector2>().read();
PoolVector<Vector2>::Read uv2;
- if (arrays[Mesh::ARRAY_TEX_UV2].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_TEX_UV2].get_type() != Variant::NIL)
uv2 = arrays[Mesh::ARRAY_TEX_UV2].operator PoolVector<Vector2>().read();
PoolVector<Color>::Read col;
- if (arrays[Mesh::ARRAY_COLOR].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_COLOR].get_type() != Variant::NIL)
col = arrays[Mesh::ARRAY_COLOR].operator PoolVector<Color>().read();
PoolVector<real_t>::Read bo;
- if (arrays[Mesh::ARRAY_BONES].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_BONES].get_type() != Variant::NIL)
bo = arrays[Mesh::ARRAY_BONES].operator PoolVector<real_t>().read();
PoolVector<real_t>::Read we;
- if (arrays[Mesh::ARRAY_WEIGHTS].get_type()!=Variant::NIL)
+ if (arrays[Mesh::ARRAY_WEIGHTS].get_type() != Variant::NIL)
we = arrays[Mesh::ARRAY_WEIGHTS].operator PoolVector<real_t>().read();
-
vertices.resize(vcount);
- for(int i=0;i<vcount;i++) {
+ for (int i = 0; i < vcount; i++) {
Vertex v;
- v.vertex=vr[i];
+ v.vertex = vr[i];
if (nr.ptr())
- v.normal=nr[i];
+ v.normal = nr[i];
if (ta.ptr())
- v.tangent=Plane(ta[i*4+0],ta[i*4+1],ta[i*4+2],ta[i*4+3]);
+ v.tangent = Plane(ta[i * 4 + 0], ta[i * 4 + 1], ta[i * 4 + 2], ta[i * 4 + 3]);
if (uv.ptr())
- v.uv=uv[i];
+ v.uv = uv[i];
if (uv2.ptr())
- v.uv2=uv2[i];
+ v.uv2 = uv2[i];
if (col.ptr())
- v.color=col[i];
+ v.color = col[i];
if (we.ptr()) {
- v.weights.push_back(we[i*4+0]);
- v.weights.push_back(we[i*4+1]);
- v.weights.push_back(we[i*4+2]);
- v.weights.push_back(we[i*4+3]);
+ v.weights.push_back(we[i * 4 + 0]);
+ v.weights.push_back(we[i * 4 + 1]);
+ v.weights.push_back(we[i * 4 + 2]);
+ v.weights.push_back(we[i * 4 + 3]);
}
if (bo.ptr()) {
- v.bones.push_back(bo[i*4+0]);
- v.bones.push_back(bo[i*4+1]);
- v.bones.push_back(bo[i*4+2]);
- v.bones.push_back(bo[i*4+3]);
+ v.bones.push_back(bo[i * 4 + 0]);
+ v.bones.push_back(bo[i * 4 + 1]);
+ v.bones.push_back(bo[i * 4 + 2]);
+ v.bones.push_back(bo[i * 4 + 3]);
}
- vertices[i]=v;
-
-
+ vertices[i] = v;
}
-
PoolVector<int> indices;
- if (arrays[Mesh::ARRAY_INDEX].get_type()!=Variant::NIL) {
+ if (arrays[Mesh::ARRAY_INDEX].get_type() != Variant::NIL) {
indices = arrays[Mesh::ARRAY_INDEX];
} else {
//make code simpler
indices.resize(vcount);
- PoolVector<int>::Write iw=indices.write();
- for(int i=0;i<vcount;i++)
- iw[i]=i;
+ PoolVector<int>::Write iw = indices.write();
+ for (int i = 0; i < vcount; i++)
+ iw[i] = i;
}
-
- int icount=indices.size();
+ int icount = indices.size();
PoolVector<int>::Read r = indices.read();
+ Map<Point2i, int> edge_indices;
- Map<Point2i,int> edge_indices;
+ for (int i = 0; i < icount; i += 3) {
- for(int i=0;i<icount;i+=3) {
+ Vertex *v[3] = { &vertices[r[i + 0]], &vertices[r[i + 1]], &vertices[r[i + 2]] };
- Vertex*v[3]={ &vertices[r[i+0]], &vertices[r[i+1]], &vertices[r[i+2]] };
-
- int fidx=faces.size();
+ int fidx = faces.size();
Face face;
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- face.v[j]=r[i+j];
+ face.v[j] = r[i + j];
- Point2i edge(r[i+j],r[i+(j+1)%3]);
+ Point2i edge(r[i + j], r[i + (j + 1) % 3]);
if (edge.x > edge.y) {
- SWAP(edge.x,edge.y);
+ SWAP(edge.x, edge.y);
}
if (edge_indices.has(edge)) {
- face.edges[j]=edge_indices[edge];
+ face.edges[j] = edge_indices[edge];
} else {
- face.edges[j]=edge_indices.size();
- edge_indices[edge]=face.edges[j];
+ face.edges[j] = edge_indices.size();
+ edge_indices[edge] = face.edges[j];
Edge e;
- e.vertex[0]=edge.x;
- e.vertex[1]=edge.y;
+ e.vertex[0] = edge.x;
+ e.vertex[1] = edge.y;
edges.push_back(e);
}
@@ -182,22 +172,19 @@ Error MeshDataTool::create_from_surface(const Ref<Mesh>& p_mesh,int p_surface) {
v[j]->edges.push_back(face.edges[j]);
}
-
faces.push_back(face);
}
-
return OK;
}
-Error MeshDataTool::commit_to_surface(const Ref<Mesh>& p_mesh) {
+Error MeshDataTool::commit_to_surface(const Ref<Mesh> &p_mesh) {
- ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(p_mesh.is_null(), ERR_INVALID_PARAMETER);
Array arr;
arr.resize(Mesh::ARRAY_MAX);
-
- int vcount=vertices.size();
+ int vcount = vertices.size();
PoolVector<Vector3> v;
PoolVector<Vector3> n;
@@ -212,124 +199,119 @@ Error MeshDataTool::commit_to_surface(const Ref<Mesh>& p_mesh) {
{
v.resize(vcount);
- PoolVector<Vector3>::Write vr=v.write();
+ PoolVector<Vector3>::Write vr = v.write();
PoolVector<Vector3>::Write nr;
- if (format&Mesh::ARRAY_FORMAT_NORMAL) {
+ if (format & Mesh::ARRAY_FORMAT_NORMAL) {
n.resize(vcount);
nr = n.write();
}
PoolVector<real_t>::Write ta;
- if (format&Mesh::ARRAY_FORMAT_TANGENT) {
- t.resize(vcount*4);
+ if (format & Mesh::ARRAY_FORMAT_TANGENT) {
+ t.resize(vcount * 4);
ta = t.write();
}
-
PoolVector<Vector2>::Write uv;
- if (format&Mesh::ARRAY_FORMAT_TEX_UV) {
+ if (format & Mesh::ARRAY_FORMAT_TEX_UV) {
u.resize(vcount);
uv = u.write();
}
PoolVector<Vector2>::Write uv2;
- if (format&Mesh::ARRAY_FORMAT_TEX_UV2) {
+ if (format & Mesh::ARRAY_FORMAT_TEX_UV2) {
u2.resize(vcount);
uv2 = u2.write();
}
PoolVector<Color>::Write col;
- if (format&Mesh::ARRAY_FORMAT_COLOR) {
+ if (format & Mesh::ARRAY_FORMAT_COLOR) {
c.resize(vcount);
col = c.write();
}
PoolVector<real_t>::Write bo;
- if (format&Mesh::ARRAY_FORMAT_BONES) {
- b.resize(vcount*4);
+ if (format & Mesh::ARRAY_FORMAT_BONES) {
+ b.resize(vcount * 4);
bo = b.write();
}
PoolVector<real_t>::Write we;
- if (format&Mesh::ARRAY_FORMAT_WEIGHTS) {
- w.resize(vcount*4);
+ if (format & Mesh::ARRAY_FORMAT_WEIGHTS) {
+ w.resize(vcount * 4);
we = w.write();
}
+ for (int i = 0; i < vcount; i++) {
- for(int i=0;i<vcount;i++) {
-
- Vertex &vtx=vertices[i];
+ Vertex &vtx = vertices[i];
- vr[i]=vtx.vertex;
+ vr[i] = vtx.vertex;
if (nr.ptr())
- nr[i]=vtx.normal;
+ nr[i] = vtx.normal;
if (ta.ptr()) {
- ta[i*4+0]=vtx.tangent.normal.x;
- ta[i*4+1]=vtx.tangent.normal.y;
- ta[i*4+2]=vtx.tangent.normal.z;
- ta[i*4+3]=vtx.tangent.d;
+ ta[i * 4 + 0] = vtx.tangent.normal.x;
+ ta[i * 4 + 1] = vtx.tangent.normal.y;
+ ta[i * 4 + 2] = vtx.tangent.normal.z;
+ ta[i * 4 + 3] = vtx.tangent.d;
}
if (uv.ptr())
- uv[i]=vtx.uv;
+ uv[i] = vtx.uv;
if (uv2.ptr())
- uv2[i]=vtx.uv2;
+ uv2[i] = vtx.uv2;
if (col.ptr())
- col[i]=vtx.color;
+ col[i] = vtx.color;
if (we.ptr()) {
- we[i*4+0]=vtx.weights[0];
- we[i*4+1]=vtx.weights[1];
- we[i*4+2]=vtx.weights[2];
- we[i*4+3]=vtx.weights[3];
-
+ we[i * 4 + 0] = vtx.weights[0];
+ we[i * 4 + 1] = vtx.weights[1];
+ we[i * 4 + 2] = vtx.weights[2];
+ we[i * 4 + 3] = vtx.weights[3];
}
if (bo.ptr()) {
- bo[i*4+0]=vtx.bones[0];
- bo[i*4+1]=vtx.bones[1];
- bo[i*4+2]=vtx.bones[2];
- bo[i*4+3]=vtx.bones[3];
+ bo[i * 4 + 0] = vtx.bones[0];
+ bo[i * 4 + 1] = vtx.bones[1];
+ bo[i * 4 + 2] = vtx.bones[2];
+ bo[i * 4 + 3] = vtx.bones[3];
}
-
}
int fc = faces.size();
- in.resize(fc*3);
- PoolVector<int>::Write iw=in.write();
- for(int i=0;i<fc;i++) {
+ in.resize(fc * 3);
+ PoolVector<int>::Write iw = in.write();
+ for (int i = 0; i < fc; i++) {
- iw[i*3+0]=faces[i].v[0];
- iw[i*3+1]=faces[i].v[1];
- iw[i*3+2]=faces[i].v[2];
+ iw[i * 3 + 0] = faces[i].v[0];
+ iw[i * 3 + 1] = faces[i].v[1];
+ iw[i * 3 + 2] = faces[i].v[2];
}
-
}
- arr[Mesh::ARRAY_VERTEX]=v;
- arr[Mesh::ARRAY_INDEX]=in;
+ arr[Mesh::ARRAY_VERTEX] = v;
+ arr[Mesh::ARRAY_INDEX] = in;
if (n.size())
- arr[Mesh::ARRAY_NORMAL]=n;
+ arr[Mesh::ARRAY_NORMAL] = n;
if (c.size())
- arr[Mesh::ARRAY_COLOR]=c;
+ arr[Mesh::ARRAY_COLOR] = c;
if (u.size())
- arr[Mesh::ARRAY_TEX_UV]=u;
+ arr[Mesh::ARRAY_TEX_UV] = u;
if (u2.size())
- arr[Mesh::ARRAY_TEX_UV2]=u2;
+ arr[Mesh::ARRAY_TEX_UV2] = u2;
if (t.size())
- arr[Mesh::ARRAY_TANGENT]=t;
+ arr[Mesh::ARRAY_TANGENT] = t;
if (b.size())
- arr[Mesh::ARRAY_BONES]=b;
+ arr[Mesh::ARRAY_BONES] = b;
if (w.size())
- arr[Mesh::ARRAY_WEIGHTS]=w;
+ arr[Mesh::ARRAY_WEIGHTS] = w;
- Ref<Mesh> ncmesh=p_mesh;
+ Ref<Mesh> ncmesh = p_mesh;
int sc = ncmesh->get_surface_count();
- ncmesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr);
- ncmesh->surface_set_material(sc,material);
+ ncmesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
+ ncmesh->surface_set_material(sc, material);
return OK;
}
@@ -343,213 +325,185 @@ int MeshDataTool::get_vertex_count() const {
return vertices.size();
}
-int MeshDataTool::get_edge_count() const{
+int MeshDataTool::get_edge_count() const {
return edges.size();
}
-int MeshDataTool::get_face_count() const{
+int MeshDataTool::get_face_count() const {
return faces.size();
}
Vector3 MeshDataTool::get_vertex(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector3());
return vertices[p_idx].vertex;
}
-void MeshDataTool::set_vertex(int p_idx,const Vector3& p_vertex){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].vertex=p_vertex;
+void MeshDataTool::set_vertex(int p_idx, const Vector3 &p_vertex) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].vertex = p_vertex;
}
-Vector3 MeshDataTool::get_vertex_normal(int p_idx) const{
+Vector3 MeshDataTool::get_vertex_normal(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector3());
return vertices[p_idx].normal;
-
}
-void MeshDataTool::set_vertex_normal(int p_idx,const Vector3& p_normal){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].normal=p_normal;
- format|=Mesh::ARRAY_FORMAT_NORMAL;
+void MeshDataTool::set_vertex_normal(int p_idx, const Vector3 &p_normal) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].normal = p_normal;
+ format |= Mesh::ARRAY_FORMAT_NORMAL;
}
-Plane MeshDataTool::get_vertex_tangent(int p_idx) const{
+Plane MeshDataTool::get_vertex_tangent(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Plane());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Plane());
return vertices[p_idx].tangent;
-
}
-void MeshDataTool::set_vertex_tangent(int p_idx,const Plane& p_tangent){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].tangent=p_tangent;
- format|=Mesh::ARRAY_FORMAT_TANGENT;
+void MeshDataTool::set_vertex_tangent(int p_idx, const Plane &p_tangent) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].tangent = p_tangent;
+ format |= Mesh::ARRAY_FORMAT_TANGENT;
}
-Vector2 MeshDataTool::get_vertex_uv(int p_idx) const{
+Vector2 MeshDataTool::get_vertex_uv(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector2());
return vertices[p_idx].uv;
-
}
-void MeshDataTool::set_vertex_uv(int p_idx,const Vector2& p_uv){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].uv=p_uv;
- format|=Mesh::ARRAY_FORMAT_TEX_UV;
+void MeshDataTool::set_vertex_uv(int p_idx, const Vector2 &p_uv) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].uv = p_uv;
+ format |= Mesh::ARRAY_FORMAT_TEX_UV;
}
-Vector2 MeshDataTool::get_vertex_uv2(int p_idx) const{
+Vector2 MeshDataTool::get_vertex_uv2(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector2());
return vertices[p_idx].uv2;
-
}
-void MeshDataTool::set_vertex_uv2(int p_idx,const Vector2& p_uv2){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].uv2=p_uv2;
- format|=Mesh::ARRAY_FORMAT_TEX_UV2;
+void MeshDataTool::set_vertex_uv2(int p_idx, const Vector2 &p_uv2) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].uv2 = p_uv2;
+ format |= Mesh::ARRAY_FORMAT_TEX_UV2;
}
-Color MeshDataTool::get_vertex_color(int p_idx) const{
+Color MeshDataTool::get_vertex_color(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Color());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Color());
return vertices[p_idx].color;
-
-
}
-void MeshDataTool::set_vertex_color(int p_idx,const Color& p_color){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].color=p_color;
- format|=Mesh::ARRAY_FORMAT_COLOR;
+void MeshDataTool::set_vertex_color(int p_idx, const Color &p_color) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].color = p_color;
+ format |= Mesh::ARRAY_FORMAT_COLOR;
}
-Vector<int> MeshDataTool::get_vertex_bones(int p_idx) const{
+Vector<int> MeshDataTool::get_vertex_bones(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>());
return vertices[p_idx].bones;
-
}
-void MeshDataTool::set_vertex_bones(int p_idx,const Vector<int>& p_bones){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].bones=p_bones;
- format|=Mesh::ARRAY_FORMAT_BONES;
+void MeshDataTool::set_vertex_bones(int p_idx, const Vector<int> &p_bones) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].bones = p_bones;
+ format |= Mesh::ARRAY_FORMAT_BONES;
}
-Vector<float> MeshDataTool::get_vertex_weights(int p_idx) const{
+Vector<float> MeshDataTool::get_vertex_weights(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<float>());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<float>());
return vertices[p_idx].weights;
-
}
-void MeshDataTool::set_vertex_weights(int p_idx,const Vector<float>& p_weights){
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].weights=p_weights;
- format|=Mesh::ARRAY_FORMAT_WEIGHTS;
-
-
+void MeshDataTool::set_vertex_weights(int p_idx, const Vector<float> &p_weights) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].weights = p_weights;
+ format |= Mesh::ARRAY_FORMAT_WEIGHTS;
}
-Variant MeshDataTool::get_vertex_meta(int p_idx) const{
+Variant MeshDataTool::get_vertex_meta(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Variant());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Variant());
return vertices[p_idx].meta;
-
}
-void MeshDataTool::set_vertex_meta(int p_idx,const Variant& p_meta){
-
- ERR_FAIL_INDEX(p_idx,vertices.size());
- vertices[p_idx].meta=p_meta;
+void MeshDataTool::set_vertex_meta(int p_idx, const Variant &p_meta) {
+ ERR_FAIL_INDEX(p_idx, vertices.size());
+ vertices[p_idx].meta = p_meta;
}
Vector<int> MeshDataTool::get_vertex_edges(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>());
return vertices[p_idx].edges;
-
}
-Vector<int> MeshDataTool::get_vertex_faces(int p_idx) const{
+Vector<int> MeshDataTool::get_vertex_faces(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,vertices.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_idx, vertices.size(), Vector<int>());
return vertices[p_idx].faces;
-
}
-int MeshDataTool::get_edge_vertex(int p_edge,int p_vertex) const {
+int MeshDataTool::get_edge_vertex(int p_edge, int p_vertex) const {
- ERR_FAIL_INDEX_V(p_edge,edges.size(),-1);
- ERR_FAIL_INDEX_V(p_vertex,2,-1);
+ ERR_FAIL_INDEX_V(p_edge, edges.size(), -1);
+ ERR_FAIL_INDEX_V(p_vertex, 2, -1);
return edges[p_edge].vertex[p_vertex];
-
}
-Vector<int> MeshDataTool::get_edge_faces(int p_edge) const{
+Vector<int> MeshDataTool::get_edge_faces(int p_edge) const {
- ERR_FAIL_INDEX_V(p_edge,edges.size(),Vector<int>());
+ ERR_FAIL_INDEX_V(p_edge, edges.size(), Vector<int>());
return edges[p_edge].faces;
-
}
-Variant MeshDataTool::get_edge_meta(int p_idx) const{
+Variant MeshDataTool::get_edge_meta(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,edges.size(),Variant());
+ ERR_FAIL_INDEX_V(p_idx, edges.size(), Variant());
return edges[p_idx].meta;
-
}
-void MeshDataTool::set_edge_meta(int p_idx,const Variant& p_meta){
+void MeshDataTool::set_edge_meta(int p_idx, const Variant &p_meta) {
- ERR_FAIL_INDEX(p_idx,edges.size());
- edges[p_idx].meta=p_meta;
+ ERR_FAIL_INDEX(p_idx, edges.size());
+ edges[p_idx].meta = p_meta;
}
-int MeshDataTool::get_face_vertex(int p_face,int p_vertex) const {
+int MeshDataTool::get_face_vertex(int p_face, int p_vertex) const {
- ERR_FAIL_INDEX_V(p_face,faces.size(),-1);
- ERR_FAIL_INDEX_V(p_vertex,3,-1);
+ ERR_FAIL_INDEX_V(p_face, faces.size(), -1);
+ ERR_FAIL_INDEX_V(p_vertex, 3, -1);
return faces[p_face].v[p_vertex];
-
}
-int MeshDataTool::get_face_edge(int p_face,int p_vertex) const{
+int MeshDataTool::get_face_edge(int p_face, int p_vertex) const {
- ERR_FAIL_INDEX_V(p_face,faces.size(),-1);
- ERR_FAIL_INDEX_V(p_vertex,3,-1);
+ ERR_FAIL_INDEX_V(p_face, faces.size(), -1);
+ ERR_FAIL_INDEX_V(p_vertex, 3, -1);
return faces[p_face].edges[p_vertex];
-
}
-Variant MeshDataTool::get_face_meta(int p_face) const{
+Variant MeshDataTool::get_face_meta(int p_face) const {
- ERR_FAIL_INDEX_V(p_face,faces.size(),Variant());
+ ERR_FAIL_INDEX_V(p_face, faces.size(), Variant());
return faces[p_face].meta;
-
}
-void MeshDataTool::set_face_meta(int p_face,const Variant& p_meta){
+void MeshDataTool::set_face_meta(int p_face, const Variant &p_meta) {
- ERR_FAIL_INDEX(p_face,faces.size());
- faces[p_face].meta=p_meta;
+ ERR_FAIL_INDEX(p_face, faces.size());
+ faces[p_face].meta = p_meta;
}
Vector3 MeshDataTool::get_face_normal(int p_face) const {
- ERR_FAIL_INDEX_V(p_face,faces.size(),Vector3());
+ ERR_FAIL_INDEX_V(p_face, faces.size(), Vector3());
Vector3 v0 = vertices[faces[p_face].v[0]].vertex;
Vector3 v1 = vertices[faces[p_face].v[1]].vertex;
Vector3 v2 = vertices[faces[p_face].v[2]].vertex;
- return Plane(v0,v1,v2).normal;
-
+ return Plane(v0, v1, v2).normal;
}
Ref<Material> MeshDataTool::get_material() const {
@@ -559,71 +513,70 @@ Ref<Material> MeshDataTool::get_material() const {
void MeshDataTool::set_material(const Ref<Material> &p_material) {
- material=p_material;
+ material = p_material;
}
-
void MeshDataTool::_bind_methods() {
- ClassDB::bind_method(D_METHOD("clear"),&MeshDataTool::clear);
- ClassDB::bind_method(D_METHOD("create_from_surface","mesh","surface"),&MeshDataTool::create_from_surface);
- ClassDB::bind_method(D_METHOD("commit_to_surface","mesh"),&MeshDataTool::commit_to_surface);
+ ClassDB::bind_method(D_METHOD("clear"), &MeshDataTool::clear);
+ ClassDB::bind_method(D_METHOD("create_from_surface", "mesh", "surface"), &MeshDataTool::create_from_surface);
+ ClassDB::bind_method(D_METHOD("commit_to_surface", "mesh"), &MeshDataTool::commit_to_surface);
- ClassDB::bind_method(D_METHOD("get_format"),&MeshDataTool::get_format);
+ ClassDB::bind_method(D_METHOD("get_format"), &MeshDataTool::get_format);
- ClassDB::bind_method(D_METHOD("get_vertex_count"),&MeshDataTool::get_vertex_count);
- ClassDB::bind_method(D_METHOD("get_edge_count"),&MeshDataTool::get_edge_count);
- ClassDB::bind_method(D_METHOD("get_face_count"),&MeshDataTool::get_face_count);
+ ClassDB::bind_method(D_METHOD("get_vertex_count"), &MeshDataTool::get_vertex_count);
+ ClassDB::bind_method(D_METHOD("get_edge_count"), &MeshDataTool::get_edge_count);
+ ClassDB::bind_method(D_METHOD("get_face_count"), &MeshDataTool::get_face_count);
- ClassDB::bind_method(D_METHOD("set_vertex","idx","vertex"),&MeshDataTool::set_vertex);
- ClassDB::bind_method(D_METHOD("get_vertex","idx"),&MeshDataTool::get_vertex);
+ ClassDB::bind_method(D_METHOD("set_vertex", "idx", "vertex"), &MeshDataTool::set_vertex);
+ ClassDB::bind_method(D_METHOD("get_vertex", "idx"), &MeshDataTool::get_vertex);
- ClassDB::bind_method(D_METHOD("set_vertex_normal","idx","normal"),&MeshDataTool::set_vertex_normal);
- ClassDB::bind_method(D_METHOD("get_vertex_normal","idx"),&MeshDataTool::get_vertex_normal);
+ ClassDB::bind_method(D_METHOD("set_vertex_normal", "idx", "normal"), &MeshDataTool::set_vertex_normal);
+ ClassDB::bind_method(D_METHOD("get_vertex_normal", "idx"), &MeshDataTool::get_vertex_normal);
- ClassDB::bind_method(D_METHOD("set_vertex_tangent","idx","tangent"),&MeshDataTool::set_vertex_tangent);
- ClassDB::bind_method(D_METHOD("get_vertex_tangent","idx"),&MeshDataTool::get_vertex_tangent);
+ ClassDB::bind_method(D_METHOD("set_vertex_tangent", "idx", "tangent"), &MeshDataTool::set_vertex_tangent);
+ ClassDB::bind_method(D_METHOD("get_vertex_tangent", "idx"), &MeshDataTool::get_vertex_tangent);
- ClassDB::bind_method(D_METHOD("set_vertex_uv","idx","uv"),&MeshDataTool::set_vertex_uv);
- ClassDB::bind_method(D_METHOD("get_vertex_uv","idx"),&MeshDataTool::get_vertex_uv);
+ ClassDB::bind_method(D_METHOD("set_vertex_uv", "idx", "uv"), &MeshDataTool::set_vertex_uv);
+ ClassDB::bind_method(D_METHOD("get_vertex_uv", "idx"), &MeshDataTool::get_vertex_uv);
- ClassDB::bind_method(D_METHOD("set_vertex_uv2","idx","uv2"),&MeshDataTool::set_vertex_uv2);
- ClassDB::bind_method(D_METHOD("get_vertex_uv2","idx"),&MeshDataTool::get_vertex_uv2);
+ ClassDB::bind_method(D_METHOD("set_vertex_uv2", "idx", "uv2"), &MeshDataTool::set_vertex_uv2);
+ ClassDB::bind_method(D_METHOD("get_vertex_uv2", "idx"), &MeshDataTool::get_vertex_uv2);
- ClassDB::bind_method(D_METHOD("set_vertex_color","idx","color"),&MeshDataTool::set_vertex_color);
- ClassDB::bind_method(D_METHOD("get_vertex_color","idx"),&MeshDataTool::get_vertex_color);
+ ClassDB::bind_method(D_METHOD("set_vertex_color", "idx", "color"), &MeshDataTool::set_vertex_color);
+ ClassDB::bind_method(D_METHOD("get_vertex_color", "idx"), &MeshDataTool::get_vertex_color);
- ClassDB::bind_method(D_METHOD("set_vertex_bones","idx","bones"),&MeshDataTool::set_vertex_bones);
- ClassDB::bind_method(D_METHOD("get_vertex_bones","idx"),&MeshDataTool::get_vertex_bones);
+ ClassDB::bind_method(D_METHOD("set_vertex_bones", "idx", "bones"), &MeshDataTool::set_vertex_bones);
+ ClassDB::bind_method(D_METHOD("get_vertex_bones", "idx"), &MeshDataTool::get_vertex_bones);
- ClassDB::bind_method(D_METHOD("set_vertex_weights","idx","weights"),&MeshDataTool::set_vertex_weights);
- ClassDB::bind_method(D_METHOD("get_vertex_weights","idx"),&MeshDataTool::get_vertex_weights);
+ ClassDB::bind_method(D_METHOD("set_vertex_weights", "idx", "weights"), &MeshDataTool::set_vertex_weights);
+ ClassDB::bind_method(D_METHOD("get_vertex_weights", "idx"), &MeshDataTool::get_vertex_weights);
- ClassDB::bind_method(D_METHOD("set_vertex_meta","idx","meta"),&MeshDataTool::set_vertex_meta);
- ClassDB::bind_method(D_METHOD("get_vertex_meta","idx"),&MeshDataTool::get_vertex_meta);
+ ClassDB::bind_method(D_METHOD("set_vertex_meta", "idx", "meta"), &MeshDataTool::set_vertex_meta);
+ ClassDB::bind_method(D_METHOD("get_vertex_meta", "idx"), &MeshDataTool::get_vertex_meta);
- ClassDB::bind_method(D_METHOD("get_vertex_edges","idx"),&MeshDataTool::get_vertex_edges);
- ClassDB::bind_method(D_METHOD("get_vertex_faces","idx"),&MeshDataTool::get_vertex_faces);
+ ClassDB::bind_method(D_METHOD("get_vertex_edges", "idx"), &MeshDataTool::get_vertex_edges);
+ ClassDB::bind_method(D_METHOD("get_vertex_faces", "idx"), &MeshDataTool::get_vertex_faces);
- ClassDB::bind_method(D_METHOD("get_edge_vertex","idx","vertex"),&MeshDataTool::get_edge_vertex);
- ClassDB::bind_method(D_METHOD("get_edge_faces","idx","faces"),&MeshDataTool::get_edge_faces);
+ ClassDB::bind_method(D_METHOD("get_edge_vertex", "idx", "vertex"), &MeshDataTool::get_edge_vertex);
+ ClassDB::bind_method(D_METHOD("get_edge_faces", "idx", "faces"), &MeshDataTool::get_edge_faces);
- ClassDB::bind_method(D_METHOD("set_edge_meta","idx","meta"),&MeshDataTool::set_edge_meta);
- ClassDB::bind_method(D_METHOD("get_edge_meta","idx"),&MeshDataTool::get_edge_meta);
+ ClassDB::bind_method(D_METHOD("set_edge_meta", "idx", "meta"), &MeshDataTool::set_edge_meta);
+ ClassDB::bind_method(D_METHOD("get_edge_meta", "idx"), &MeshDataTool::get_edge_meta);
- ClassDB::bind_method(D_METHOD("get_face_vertex","idx","vertex"),&MeshDataTool::get_face_vertex);
- ClassDB::bind_method(D_METHOD("get_face_edge","idx","edge"),&MeshDataTool::get_face_edge);
+ ClassDB::bind_method(D_METHOD("get_face_vertex", "idx", "vertex"), &MeshDataTool::get_face_vertex);
+ ClassDB::bind_method(D_METHOD("get_face_edge", "idx", "edge"), &MeshDataTool::get_face_edge);
- ClassDB::bind_method(D_METHOD("set_face_meta","idx","meta"),&MeshDataTool::set_face_meta);
- ClassDB::bind_method(D_METHOD("get_face_meta","idx"),&MeshDataTool::get_face_meta);
+ ClassDB::bind_method(D_METHOD("set_face_meta", "idx", "meta"), &MeshDataTool::set_face_meta);
+ ClassDB::bind_method(D_METHOD("get_face_meta", "idx"), &MeshDataTool::get_face_meta);
- ClassDB::bind_method(D_METHOD("get_face_normal","idx"),&MeshDataTool::get_face_normal);
+ ClassDB::bind_method(D_METHOD("get_face_normal", "idx"), &MeshDataTool::get_face_normal);
- ClassDB::bind_method(D_METHOD("set_material","material:Material"),&MeshDataTool::set_material);
- ClassDB::bind_method(D_METHOD("get_material","material"),&MeshDataTool::get_material);
+ ClassDB::bind_method(D_METHOD("set_material", "material:Material"), &MeshDataTool::set_material);
+ ClassDB::bind_method(D_METHOD("get_material", "material"), &MeshDataTool::get_material);
}
-MeshDataTool::MeshDataTool(){
+MeshDataTool::MeshDataTool() {
clear();
}
diff --git a/scene/resources/mesh_data_tool.h b/scene/resources/mesh_data_tool.h
index fa9c50d2ec..14318a9f82 100644
--- a/scene/resources/mesh_data_tool.h
+++ b/scene/resources/mesh_data_tool.h
@@ -31,10 +31,9 @@
#include "scene/resources/mesh.h"
-class MeshDataTool : public Reference {
-
- GDCLASS(MeshDataTool,Reference);
+class MeshDataTool : public Reference {
+ GDCLASS(MeshDataTool, Reference);
int format;
struct Vertex {
@@ -69,18 +68,17 @@ class MeshDataTool : public Reference {
Variant meta;
};
-
Vector<Face> faces;
Ref<Material> material;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void clear();
- Error create_from_surface(const Ref<Mesh>& p_mesh,int p_surface);
- Error commit_to_surface(const Ref<Mesh>& p_mesh);
+ Error create_from_surface(const Ref<Mesh> &p_mesh, int p_surface);
+ Error commit_to_surface(const Ref<Mesh> &p_mesh);
int get_format() const;
@@ -89,44 +87,44 @@ public:
int get_face_count() const;
Vector3 get_vertex(int p_idx) const;
- void set_vertex(int p_idx,const Vector3& p_vertex);
+ void set_vertex(int p_idx, const Vector3 &p_vertex);
Vector3 get_vertex_normal(int p_idx) const;
- void set_vertex_normal(int p_idx,const Vector3& p_normal);
+ void set_vertex_normal(int p_idx, const Vector3 &p_normal);
Plane get_vertex_tangent(int p_idx) const;
- void set_vertex_tangent(int p_idx,const Plane& p_tangent);
+ void set_vertex_tangent(int p_idx, const Plane &p_tangent);
Vector2 get_vertex_uv(int p_idx) const;
- void set_vertex_uv(int p_idx,const Vector2& p_uv);
+ void set_vertex_uv(int p_idx, const Vector2 &p_uv);
Vector2 get_vertex_uv2(int p_idx) const;
- void set_vertex_uv2(int p_idx,const Vector2& p_uv2);
+ void set_vertex_uv2(int p_idx, const Vector2 &p_uv2);
Color get_vertex_color(int p_idx) const;
- void set_vertex_color(int p_idx,const Color& p_color);
+ void set_vertex_color(int p_idx, const Color &p_color);
Vector<int> get_vertex_bones(int p_idx) const;
- void set_vertex_bones(int p_idx,const Vector<int>& p_bones);
+ void set_vertex_bones(int p_idx, const Vector<int> &p_bones);
Vector<float> get_vertex_weights(int p_idx) const;
- void set_vertex_weights(int p_idx,const Vector<float>& p_weights);
+ void set_vertex_weights(int p_idx, const Vector<float> &p_weights);
Variant get_vertex_meta(int p_idx) const;
- void set_vertex_meta(int p_idx,const Variant& p_meta);
+ void set_vertex_meta(int p_idx, const Variant &p_meta);
Vector<int> get_vertex_edges(int p_idx) const;
Vector<int> get_vertex_faces(int p_idx) const;
- int get_edge_vertex(int p_edge,int p_vertex) const;
+ int get_edge_vertex(int p_edge, int p_vertex) const;
Vector<int> get_edge_faces(int p_edge) const;
Variant get_edge_meta(int p_idx) const;
- void set_edge_meta(int p_idx,const Variant& p_meta);
+ void set_edge_meta(int p_idx, const Variant &p_meta);
- int get_face_vertex(int p_face,int p_vertex) const;
- int get_face_edge(int p_face,int p_vertex) const;
+ int get_face_vertex(int p_face, int p_vertex) const;
+ int get_face_edge(int p_face, int p_vertex) const;
Variant get_face_meta(int p_face) const;
- void set_face_meta(int p_face,const Variant& p_meta);
+ void set_face_meta(int p_face, const Variant &p_meta);
Vector3 get_face_normal(int p_face) const;
Ref<Material> get_material() const;
diff --git a/scene/resources/mesh_library.cpp b/scene/resources/mesh_library.cpp
index becbf39dad..92ca921f25 100644
--- a/scene/resources/mesh_library.cpp
+++ b/scene/resources/mesh_library.cpp
@@ -28,28 +28,26 @@
/*************************************************************************/
#include "mesh_library.h"
+bool MeshLibrary::_set(const StringName &p_name, const Variant &p_value) {
-
-bool MeshLibrary::_set(const StringName& p_name, const Variant& p_value) {
-
- String name=p_name;
+ String name = p_name;
if (name.begins_with("item/")) {
- int idx = name.get_slicec('/',1).to_int();
- String what = name.get_slicec('/',2);
+ int idx = name.get_slicec('/', 1).to_int();
+ String what = name.get_slicec('/', 2);
if (!item_map.has(idx))
create_item(idx);
- if(what=="name")
- set_item_name(idx,p_value);
- else if(what=="mesh")
- set_item_mesh(idx,p_value);
- else if(what=="shape")
- set_item_shape(idx,p_value);
- else if(what=="preview")
- set_item_preview(idx,p_value);
- else if(what=="navmesh")
- set_item_navmesh(idx,p_value);
+ if (what == "name")
+ set_item_name(idx, p_value);
+ else if (what == "mesh")
+ set_item_mesh(idx, p_value);
+ else if (what == "shape")
+ set_item_shape(idx, p_value);
+ else if (what == "preview")
+ set_item_preview(idx, p_value);
+ else if (what == "navmesh")
+ set_item_navmesh(idx, p_value);
else
return false;
@@ -59,137 +57,125 @@ bool MeshLibrary::_set(const StringName& p_name, const Variant& p_value) {
return false;
}
-bool MeshLibrary::_get(const StringName& p_name,Variant &r_ret) const {
-
- String name=p_name;
- int idx = name.get_slicec('/',1).to_int();
- ERR_FAIL_COND_V(!item_map.has(idx),false);
- String what = name.get_slicec('/',2);
-
- if(what=="name")
- r_ret= get_item_name(idx);
- else if(what=="mesh")
- r_ret= get_item_mesh(idx);
- else if(what=="shape")
- r_ret= get_item_shape(idx);
- else if(what=="navmesh")
- r_ret= get_item_navmesh(idx);
- else if(what=="preview")
- r_ret= get_item_preview(idx);
+bool MeshLibrary::_get(const StringName &p_name, Variant &r_ret) const {
+
+ String name = p_name;
+ int idx = name.get_slicec('/', 1).to_int();
+ ERR_FAIL_COND_V(!item_map.has(idx), false);
+ String what = name.get_slicec('/', 2);
+
+ if (what == "name")
+ r_ret = get_item_name(idx);
+ else if (what == "mesh")
+ r_ret = get_item_mesh(idx);
+ else if (what == "shape")
+ r_ret = get_item_shape(idx);
+ else if (what == "navmesh")
+ r_ret = get_item_navmesh(idx);
+ else if (what == "preview")
+ r_ret = get_item_preview(idx);
else
return false;
return true;
}
-void MeshLibrary::_get_property_list( List<PropertyInfo> *p_list) const {
+void MeshLibrary::_get_property_list(List<PropertyInfo> *p_list) const {
- for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) {
+ for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) {
- String name="item/"+itos(E->key())+"/";
- p_list->push_back( PropertyInfo(Variant::STRING,name+"name"));
- p_list->push_back( PropertyInfo(Variant::OBJECT,name+"mesh",PROPERTY_HINT_RESOURCE_TYPE,"Mesh"));
- p_list->push_back( PropertyInfo(Variant::OBJECT,name+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape"));
- p_list->push_back( PropertyInfo(Variant::OBJECT,name+"navmesh",PROPERTY_HINT_RESOURCE_TYPE,"NavigationMesh"));
- p_list->push_back( PropertyInfo(Variant::OBJECT,name+"preview",PROPERTY_HINT_RESOURCE_TYPE,"Texture",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_EDITOR_HELPER));
+ String name = "item/" + itos(E->key()) + "/";
+ p_list->push_back(PropertyInfo(Variant::STRING, name + "name"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, name + "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, name + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, name + "navmesh", PROPERTY_HINT_RESOURCE_TYPE, "NavigationMesh"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, name + "preview", PROPERTY_HINT_RESOURCE_TYPE, "Texture", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_EDITOR_HELPER));
}
}
-
-
void MeshLibrary::create_item(int p_item) {
- ERR_FAIL_COND(p_item<0);
+ ERR_FAIL_COND(p_item < 0);
ERR_FAIL_COND(item_map.has(p_item));
- item_map[p_item]=Item();
+ item_map[p_item] = Item();
_change_notify();
}
-void MeshLibrary::set_item_name(int p_item,const String& p_name) {
+void MeshLibrary::set_item_name(int p_item, const String &p_name) {
ERR_FAIL_COND(!item_map.has(p_item));
- item_map[p_item].name=p_name;
+ item_map[p_item].name = p_name;
emit_changed();
_change_notify();
-
}
-void MeshLibrary::set_item_mesh(int p_item,const Ref<Mesh>& p_mesh) {
+void MeshLibrary::set_item_mesh(int p_item, const Ref<Mesh> &p_mesh) {
ERR_FAIL_COND(!item_map.has(p_item));
- item_map[p_item].mesh=p_mesh;
+ item_map[p_item].mesh = p_mesh;
notify_change_to_owners();
emit_changed();
_change_notify();
-
-
}
-void MeshLibrary::set_item_shape(int p_item,const Ref<Shape>& p_shape) {
+void MeshLibrary::set_item_shape(int p_item, const Ref<Shape> &p_shape) {
ERR_FAIL_COND(!item_map.has(p_item));
- item_map[p_item].shape=p_shape;
+ item_map[p_item].shape = p_shape;
_change_notify();
notify_change_to_owners();
emit_changed();
_change_notify();
-
}
-
-void MeshLibrary::set_item_navmesh(int p_item,const Ref<NavigationMesh>& p_navmesh) {
+void MeshLibrary::set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh) {
ERR_FAIL_COND(!item_map.has(p_item));
- item_map[p_item].navmesh=p_navmesh;
+ item_map[p_item].navmesh = p_navmesh;
_change_notify();
notify_change_to_owners();
emit_changed();
_change_notify();
-
}
-void MeshLibrary::set_item_preview(int p_item,const Ref<Texture>& p_preview) {
+void MeshLibrary::set_item_preview(int p_item, const Ref<Texture> &p_preview) {
ERR_FAIL_COND(!item_map.has(p_item));
- item_map[p_item].preview=p_preview;
+ item_map[p_item].preview = p_preview;
emit_changed();
_change_notify();
-
}
String MeshLibrary::get_item_name(int p_item) const {
- ERR_FAIL_COND_V(!item_map.has(p_item),"");
+ ERR_FAIL_COND_V(!item_map.has(p_item), "");
return item_map[p_item].name;
-
}
Ref<Mesh> MeshLibrary::get_item_mesh(int p_item) const {
- ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Mesh>());
+ ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Mesh>());
return item_map[p_item].mesh;
-
}
Ref<Shape> MeshLibrary::get_item_shape(int p_item) const {
- ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Shape>());
+ ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Shape>());
return item_map[p_item].shape;
}
Ref<NavigationMesh> MeshLibrary::get_item_navmesh(int p_item) const {
- ERR_FAIL_COND_V(!item_map.has(p_item),Ref<NavigationMesh>());
+ ERR_FAIL_COND_V(!item_map.has(p_item), Ref<NavigationMesh>());
return item_map[p_item].navmesh;
}
-
Ref<Texture> MeshLibrary::get_item_preview(int p_item) const {
- ERR_FAIL_COND_V(!item_map.has(p_item),Ref<Texture>());
+ ERR_FAIL_COND_V(!item_map.has(p_item), Ref<Texture>());
return item_map[p_item].preview;
}
bool MeshLibrary::has_item(int p_item) const {
- return item_map.has(p_item) ;
+ return item_map.has(p_item);
}
void MeshLibrary::remove_item(int p_item) {
@@ -198,7 +184,6 @@ void MeshLibrary::remove_item(int p_item) {
notify_change_to_owners();
_change_notify();
emit_changed();
-
}
void MeshLibrary::clear() {
@@ -213,20 +198,20 @@ Vector<int> MeshLibrary::get_item_list() const {
Vector<int> ret;
ret.resize(item_map.size());
- int idx=0;
- for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) {
+ int idx = 0;
+ for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) {
- ret[idx++]=E->key();
+ ret[idx++] = E->key();
}
return ret;
}
-int MeshLibrary::find_item_name(const String& p_name) const {
+int MeshLibrary::find_item_name(const String &p_name) const {
- for(Map<int,Item>::Element *E=item_map.front();E;E=E->next()) {
+ for (Map<int, Item>::Element *E = item_map.front(); E; E = E->next()) {
- if (E->get().name==p_name)
+ if (E->get().name == p_name)
return E->key();
}
return -1;
@@ -237,33 +222,27 @@ int MeshLibrary::get_last_unused_item_id() const {
if (!item_map.size())
return 0;
else
- return item_map.back()->key()+1;
+ return item_map.back()->key() + 1;
}
-
-
void MeshLibrary::_bind_methods() {
- ClassDB::bind_method(D_METHOD("create_item","id"),&MeshLibrary::create_item);
- ClassDB::bind_method(D_METHOD("set_item_name","id","name"),&MeshLibrary::set_item_name);
- ClassDB::bind_method(D_METHOD("set_item_mesh","id","mesh:Mesh"),&MeshLibrary::set_item_mesh);
- ClassDB::bind_method(D_METHOD("set_item_navmesh","id","navmesh:NavigationMesh"),&MeshLibrary::set_item_navmesh);
- ClassDB::bind_method(D_METHOD("set_item_shape","id","shape:Shape"),&MeshLibrary::set_item_shape);
- ClassDB::bind_method(D_METHOD("get_item_name","id"),&MeshLibrary::get_item_name);
- ClassDB::bind_method(D_METHOD("get_item_mesh:Mesh","id"),&MeshLibrary::get_item_mesh);
- ClassDB::bind_method(D_METHOD("get_item_navmesh:NavigationMesh","id"),&MeshLibrary::get_item_navmesh);
- ClassDB::bind_method(D_METHOD("get_item_shape:Shape","id"),&MeshLibrary::get_item_shape);
- ClassDB::bind_method(D_METHOD("remove_item","id"),&MeshLibrary::remove_item);
- ClassDB::bind_method(D_METHOD("clear"),&MeshLibrary::clear);
- ClassDB::bind_method(D_METHOD("get_item_list"),&MeshLibrary::get_item_list);
- ClassDB::bind_method(D_METHOD("get_last_unused_item_id"),&MeshLibrary::get_last_unused_item_id);
+ ClassDB::bind_method(D_METHOD("create_item", "id"), &MeshLibrary::create_item);
+ ClassDB::bind_method(D_METHOD("set_item_name", "id", "name"), &MeshLibrary::set_item_name);
+ ClassDB::bind_method(D_METHOD("set_item_mesh", "id", "mesh:Mesh"), &MeshLibrary::set_item_mesh);
+ ClassDB::bind_method(D_METHOD("set_item_navmesh", "id", "navmesh:NavigationMesh"), &MeshLibrary::set_item_navmesh);
+ ClassDB::bind_method(D_METHOD("set_item_shape", "id", "shape:Shape"), &MeshLibrary::set_item_shape);
+ ClassDB::bind_method(D_METHOD("get_item_name", "id"), &MeshLibrary::get_item_name);
+ ClassDB::bind_method(D_METHOD("get_item_mesh:Mesh", "id"), &MeshLibrary::get_item_mesh);
+ ClassDB::bind_method(D_METHOD("get_item_navmesh:NavigationMesh", "id"), &MeshLibrary::get_item_navmesh);
+ ClassDB::bind_method(D_METHOD("get_item_shape:Shape", "id"), &MeshLibrary::get_item_shape);
+ ClassDB::bind_method(D_METHOD("remove_item", "id"), &MeshLibrary::remove_item);
+ ClassDB::bind_method(D_METHOD("clear"), &MeshLibrary::clear);
+ ClassDB::bind_method(D_METHOD("get_item_list"), &MeshLibrary::get_item_list);
+ ClassDB::bind_method(D_METHOD("get_last_unused_item_id"), &MeshLibrary::get_last_unused_item_id);
}
MeshLibrary::MeshLibrary() {
-
-
}
MeshLibrary::~MeshLibrary() {
-
-
}
diff --git a/scene/resources/mesh_library.h b/scene/resources/mesh_library.h
index bb8012d3ff..5f4a695c56 100644
--- a/scene/resources/mesh_library.h
+++ b/scene/resources/mesh_library.h
@@ -29,15 +29,15 @@
#ifndef GRID_THEME_H
#define GRID_THEME_H
-#include "resource.h"
-#include "mesh.h"
-#include "shape.h"
#include "map.h"
+#include "mesh.h"
+#include "resource.h"
#include "scene/3d/navigation_mesh.h"
+#include "shape.h"
class MeshLibrary : public Resource {
- GDCLASS(MeshLibrary,Resource);
+ GDCLASS(MeshLibrary, Resource);
RES_BASE_EXTENSION("gt");
struct Item {
@@ -48,24 +48,22 @@ class MeshLibrary : public Resource {
Ref<NavigationMesh> navmesh;
};
- Map<int,Item> item_map;
+ Map<int, Item> item_map;
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
-public:
-
+public:
void create_item(int p_item);
- void set_item_name(int p_item,const String& p_name);
- void set_item_mesh(int p_item,const Ref<Mesh>& p_mesh);
- void set_item_navmesh(int p_item, const Ref<NavigationMesh>& p_navmesh);
- void set_item_shape(int p_item,const Ref<Shape>& p_shape);
- void set_item_preview(int p_item,const Ref<Texture>& p_preview);
+ void set_item_name(int p_item, const String &p_name);
+ void set_item_mesh(int p_item, const Ref<Mesh> &p_mesh);
+ void set_item_navmesh(int p_item, const Ref<NavigationMesh> &p_navmesh);
+ void set_item_shape(int p_item, const Ref<Shape> &p_shape);
+ void set_item_preview(int p_item, const Ref<Texture> &p_preview);
String get_item_name(int p_item) const;
Ref<Mesh> get_item_mesh(int p_item) const;
Ref<NavigationMesh> get_item_navmesh(int p_item) const;
@@ -77,7 +75,7 @@ public:
void clear();
- int find_item_name(const String& p_name) const;
+ int find_item_name(const String &p_name) const;
Vector<int> get_item_list() const;
int get_last_unused_item_id() const;
diff --git a/scene/resources/multimesh.cpp b/scene/resources/multimesh.cpp
index 69ef3f18a6..6202109cd1 100644
--- a/scene/resources/multimesh.cpp
+++ b/scene/resources/multimesh.cpp
@@ -29,232 +29,201 @@
#include "multimesh.h"
#include "servers/visual_server.h"
-
-
-void MultiMesh::_set_transform_array(const PoolVector<Vector3>& p_array) {
+void MultiMesh::_set_transform_array(const PoolVector<Vector3> &p_array) {
int instance_count = get_instance_count();
PoolVector<Vector3> xforms = p_array;
- int len=xforms.size();
- ERR_FAIL_COND((len/4) != instance_count);
- if (len==0)
+ int len = xforms.size();
+ ERR_FAIL_COND((len / 4) != instance_count);
+ if (len == 0)
return;
PoolVector<Vector3>::Read r = xforms.read();
- for(int i=0;i<len/4;i++) {
+ for (int i = 0; i < len / 4; i++) {
Transform t;
- t.basis[0]=r[i*4+0];
- t.basis[1]=r[i*4+1];
- t.basis[2]=r[i*4+2];
- t.origin=r[i*4+3];
+ t.basis[0] = r[i * 4 + 0];
+ t.basis[1] = r[i * 4 + 1];
+ t.basis[2] = r[i * 4 + 2];
+ t.origin = r[i * 4 + 3];
- set_instance_transform(i,t);
+ set_instance_transform(i, t);
}
-
}
PoolVector<Vector3> MultiMesh::_get_transform_array() const {
int instance_count = get_instance_count();
- if (instance_count==0)
+ if (instance_count == 0)
return PoolVector<Vector3>();
PoolVector<Vector3> xforms;
- xforms.resize(instance_count*4);
+ xforms.resize(instance_count * 4);
PoolVector<Vector3>::Write w = xforms.write();
- for(int i=0;i<instance_count;i++) {
+ for (int i = 0; i < instance_count; i++) {
- Transform t=get_instance_transform(i);
- w[i*4+0]=t.basis[0];
- w[i*4+1]=t.basis[1];
- w[i*4+2]=t.basis[2];
- w[i*4+3]=t.origin;
+ Transform t = get_instance_transform(i);
+ w[i * 4 + 0] = t.basis[0];
+ w[i * 4 + 1] = t.basis[1];
+ w[i * 4 + 2] = t.basis[2];
+ w[i * 4 + 3] = t.origin;
}
return xforms;
-
}
-
-void MultiMesh::_set_color_array(const PoolVector<Color>& p_array) {
+void MultiMesh::_set_color_array(const PoolVector<Color> &p_array) {
int instance_count = get_instance_count();
PoolVector<Color> colors = p_array;
- int len=colors.size();
+ int len = colors.size();
ERR_FAIL_COND(len != instance_count);
- if (len==0)
+ if (len == 0)
return;
PoolVector<Color>::Read r = colors.read();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- set_instance_color(i,r[i]);
+ set_instance_color(i, r[i]);
}
-
}
PoolVector<Color> MultiMesh::_get_color_array() const {
int instance_count = get_instance_count();
- if (instance_count==0)
+ if (instance_count == 0)
return PoolVector<Color>();
PoolVector<Color> colors;
colors.resize(instance_count);
- for(int i=0;i<instance_count;i++) {
+ for (int i = 0; i < instance_count; i++) {
- colors.set(i,get_instance_color(i));
+ colors.set(i, get_instance_color(i));
}
return colors;
-
}
+void MultiMesh::set_mesh(const Ref<Mesh> &p_mesh) {
-
-
-void MultiMesh::set_mesh(const Ref<Mesh>& p_mesh) {
-
- mesh=p_mesh;
+ mesh = p_mesh;
if (!mesh.is_null())
- VisualServer::get_singleton()->multimesh_set_mesh(multimesh,mesh->get_rid());
+ VisualServer::get_singleton()->multimesh_set_mesh(multimesh, mesh->get_rid());
else
- VisualServer::get_singleton()->multimesh_set_mesh(multimesh,RID());
-
+ VisualServer::get_singleton()->multimesh_set_mesh(multimesh, RID());
}
Ref<Mesh> MultiMesh::get_mesh() const {
return mesh;
-
}
void MultiMesh::set_instance_count(int p_count) {
- VisualServer::get_singleton()->multimesh_allocate(multimesh,p_count,VS::MultimeshTransformFormat(transform_format),VS::MultimeshColorFormat(color_format));
-
+ VisualServer::get_singleton()->multimesh_allocate(multimesh, p_count, VS::MultimeshTransformFormat(transform_format), VS::MultimeshColorFormat(color_format));
}
int MultiMesh::get_instance_count() const {
return VisualServer::get_singleton()->multimesh_get_instance_count(multimesh);
-
}
-void MultiMesh::set_instance_transform(int p_instance, const Transform& p_transform) {
-
- VisualServer::get_singleton()->multimesh_instance_set_transform(multimesh,p_instance,p_transform);
-
+void MultiMesh::set_instance_transform(int p_instance, const Transform &p_transform) {
+ VisualServer::get_singleton()->multimesh_instance_set_transform(multimesh, p_instance, p_transform);
}
Transform MultiMesh::get_instance_transform(int p_instance) const {
- return VisualServer::get_singleton()->multimesh_instance_get_transform(multimesh,p_instance);
-
+ return VisualServer::get_singleton()->multimesh_instance_get_transform(multimesh, p_instance);
}
-void MultiMesh::set_instance_color(int p_instance, const Color& p_color) {
-
-
- VisualServer::get_singleton()->multimesh_instance_set_color(multimesh,p_instance,p_color);
+void MultiMesh::set_instance_color(int p_instance, const Color &p_color) {
+ VisualServer::get_singleton()->multimesh_instance_set_color(multimesh, p_instance, p_color);
}
Color MultiMesh::get_instance_color(int p_instance) const {
- return VisualServer::get_singleton()->multimesh_instance_get_color(multimesh,p_instance);
-
+ return VisualServer::get_singleton()->multimesh_instance_get_color(multimesh, p_instance);
}
-
Rect3 MultiMesh::get_aabb() const {
return VisualServer::get_singleton()->multimesh_get_aabb(multimesh);
-
}
-
RID MultiMesh::get_rid() const {
return multimesh;
-
}
-
void MultiMesh::set_color_format(ColorFormat p_color_format) {
- color_format=p_color_format;
+ color_format = p_color_format;
}
-MultiMesh::ColorFormat MultiMesh::get_color_format() const{
+MultiMesh::ColorFormat MultiMesh::get_color_format() const {
return color_format;
}
-void MultiMesh::set_transform_format(TransformFormat p_transform_format){
+void MultiMesh::set_transform_format(TransformFormat p_transform_format) {
- transform_format=p_transform_format;
+ transform_format = p_transform_format;
}
-MultiMesh::TransformFormat MultiMesh::get_transform_format() const{
+MultiMesh::TransformFormat MultiMesh::get_transform_format() const {
return transform_format;
}
-
void MultiMesh::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mesh","mesh:Mesh"),&MultiMesh::set_mesh);
- ClassDB::bind_method(D_METHOD("get_mesh:Mesh"),&MultiMesh::get_mesh);
- ClassDB::bind_method(D_METHOD("set_color_format","format"),&MultiMesh::set_color_format);
- ClassDB::bind_method(D_METHOD("get_color_format"),&MultiMesh::get_color_format);
- ClassDB::bind_method(D_METHOD("set_transform_format","format"),&MultiMesh::set_transform_format);
- ClassDB::bind_method(D_METHOD("get_transform_format"),&MultiMesh::get_transform_format);
-
- ClassDB::bind_method(D_METHOD("set_instance_count","count"),&MultiMesh::set_instance_count);
- ClassDB::bind_method(D_METHOD("get_instance_count"),&MultiMesh::get_instance_count);
- ClassDB::bind_method(D_METHOD("set_instance_transform","instance","transform"),&MultiMesh::set_instance_transform);
- ClassDB::bind_method(D_METHOD("get_instance_transform","instance"),&MultiMesh::get_instance_transform);
- ClassDB::bind_method(D_METHOD("set_instance_color","instance","color"),&MultiMesh::set_instance_color);
- ClassDB::bind_method(D_METHOD("get_instance_color","instance"),&MultiMesh::get_instance_color);
- ClassDB::bind_method(D_METHOD("get_aabb"),&MultiMesh::get_aabb);
-
-
- ClassDB::bind_method(D_METHOD("_set_transform_array"),&MultiMesh::_set_transform_array);
- ClassDB::bind_method(D_METHOD("_get_transform_array"),&MultiMesh::_get_transform_array);
- ClassDB::bind_method(D_METHOD("_set_color_array"),&MultiMesh::_set_color_array);
- ClassDB::bind_method(D_METHOD("_get_color_array"),&MultiMesh::_get_color_array);
-
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"color_format",PROPERTY_HINT_ENUM,"None,Byte,Float"), "set_color_format", "get_color_format");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"transform_format",PROPERTY_HINT_ENUM,"2D,3D"), "set_transform_format", "get_transform_format");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"instance_count",PROPERTY_HINT_RANGE,"0,16384,1"), "set_instance_count", "get_instance_count");
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"mesh",PROPERTY_HINT_RESOURCE_TYPE,"Mesh"), "set_mesh", "get_mesh");
- ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY,"transform_array",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_transform_array", "_get_transform_array");
- ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY,"color_array",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_color_array", "_get_color_array");
-
-
-
- BIND_CONSTANT( TRANSFORM_2D );
- BIND_CONSTANT( TRANSFORM_3D );
- BIND_CONSTANT( COLOR_NONE );
- BIND_CONSTANT( COLOR_8BIT );
- BIND_CONSTANT( COLOR_FLOAT );
-
+ ClassDB::bind_method(D_METHOD("set_mesh", "mesh:Mesh"), &MultiMesh::set_mesh);
+ ClassDB::bind_method(D_METHOD("get_mesh:Mesh"), &MultiMesh::get_mesh);
+ ClassDB::bind_method(D_METHOD("set_color_format", "format"), &MultiMesh::set_color_format);
+ ClassDB::bind_method(D_METHOD("get_color_format"), &MultiMesh::get_color_format);
+ ClassDB::bind_method(D_METHOD("set_transform_format", "format"), &MultiMesh::set_transform_format);
+ ClassDB::bind_method(D_METHOD("get_transform_format"), &MultiMesh::get_transform_format);
+
+ ClassDB::bind_method(D_METHOD("set_instance_count", "count"), &MultiMesh::set_instance_count);
+ ClassDB::bind_method(D_METHOD("get_instance_count"), &MultiMesh::get_instance_count);
+ ClassDB::bind_method(D_METHOD("set_instance_transform", "instance", "transform"), &MultiMesh::set_instance_transform);
+ ClassDB::bind_method(D_METHOD("get_instance_transform", "instance"), &MultiMesh::get_instance_transform);
+ ClassDB::bind_method(D_METHOD("set_instance_color", "instance", "color"), &MultiMesh::set_instance_color);
+ ClassDB::bind_method(D_METHOD("get_instance_color", "instance"), &MultiMesh::get_instance_color);
+ ClassDB::bind_method(D_METHOD("get_aabb"), &MultiMesh::get_aabb);
+
+ ClassDB::bind_method(D_METHOD("_set_transform_array"), &MultiMesh::_set_transform_array);
+ ClassDB::bind_method(D_METHOD("_get_transform_array"), &MultiMesh::_get_transform_array);
+ ClassDB::bind_method(D_METHOD("_set_color_array"), &MultiMesh::_set_color_array);
+ ClassDB::bind_method(D_METHOD("_get_color_array"), &MultiMesh::_get_color_array);
+
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "color_format", PROPERTY_HINT_ENUM, "None,Byte,Float"), "set_color_format", "get_color_format");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "transform_format", PROPERTY_HINT_ENUM, "2D,3D"), "set_transform_format", "get_transform_format");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "instance_count", PROPERTY_HINT_RANGE, "0,16384,1"), "set_instance_count", "get_instance_count");
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "mesh", PROPERTY_HINT_RESOURCE_TYPE, "Mesh"), "set_mesh", "get_mesh");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "transform_array", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_transform_array", "_get_transform_array");
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_COLOR_ARRAY, "color_array", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_color_array", "_get_color_array");
+
+ BIND_CONSTANT(TRANSFORM_2D);
+ BIND_CONSTANT(TRANSFORM_3D);
+ BIND_CONSTANT(COLOR_NONE);
+ BIND_CONSTANT(COLOR_8BIT);
+ BIND_CONSTANT(COLOR_FLOAT);
}
MultiMesh::MultiMesh() {
multimesh = VisualServer::get_singleton()->multimesh_create();
- color_format=COLOR_NONE;
- transform_format=TRANSFORM_2D;
+ color_format = COLOR_NONE;
+ transform_format = TRANSFORM_2D;
}
MultiMesh::~MultiMesh() {
diff --git a/scene/resources/multimesh.h b/scene/resources/multimesh.h
index c86b33adcf..1ecf76142a 100644
--- a/scene/resources/multimesh.h
+++ b/scene/resources/multimesh.h
@@ -34,10 +34,10 @@
class MultiMesh : public Resource {
- GDCLASS( MultiMesh, Resource );
+ GDCLASS(MultiMesh, Resource);
RES_BASE_EXTENSION("mmsh");
-public:
+public:
enum TransformFormat {
TRANSFORM_2D = VS::MULTIMESH_TRANSFORM_2D,
TRANSFORM_3D = VS::MULTIMESH_TRANSFORM_3D
@@ -48,26 +48,24 @@ public:
COLOR_8BIT = VS::MULTIMESH_COLOR_8BIT,
COLOR_FLOAT = VS::MULTIMESH_COLOR_FLOAT,
};
+
private:
Ref<Mesh> mesh;
RID multimesh;
TransformFormat transform_format;
ColorFormat color_format;
-
protected:
-
static void _bind_methods();
- void _set_transform_array(const PoolVector<Vector3>& p_array);
+ void _set_transform_array(const PoolVector<Vector3> &p_array);
PoolVector<Vector3> _get_transform_array() const;
- void _set_color_array(const PoolVector<Color>& p_array);
+ void _set_color_array(const PoolVector<Color> &p_array);
PoolVector<Color> _get_color_array() const;
public:
-
- void set_mesh(const Ref<Mesh>& p_mesh);
+ void set_mesh(const Ref<Mesh> &p_mesh);
Ref<Mesh> get_mesh() const;
void set_color_format(ColorFormat p_color_format);
@@ -79,10 +77,10 @@ public:
void set_instance_count(int p_count);
int get_instance_count() const;
- void set_instance_transform(int p_instance, const Transform& p_transform);
+ void set_instance_transform(int p_instance, const Transform &p_transform);
Transform get_instance_transform(int p_instance) const;
- void set_instance_color(int p_instance, const Color& p_color);
+ void set_instance_color(int p_instance, const Color &p_color);
Color get_instance_color(int p_instance) const;
virtual Rect3 get_aabb() const;
@@ -91,11 +89,9 @@ public:
MultiMesh();
~MultiMesh();
-
};
-
-VARIANT_ENUM_CAST( MultiMesh::TransformFormat );
-VARIANT_ENUM_CAST( MultiMesh::ColorFormat);
+VARIANT_ENUM_CAST(MultiMesh::TransformFormat);
+VARIANT_ENUM_CAST(MultiMesh::ColorFormat);
#endif // MULTI_MESH_H
diff --git a/scene/resources/packed_scene.cpp b/scene/resources/packed_scene.cpp
index 5e3347687a..0c2f07aa4a 100644
--- a/scene/resources/packed_scene.cpp
+++ b/scene/resources/packed_scene.cpp
@@ -27,234 +27,227 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "packed_scene.h"
+#include "core/core_string_names.h"
#include "global_config.h"
#include "io/resource_loader.h"
+#include "scene/2d/node_2d.h"
#include "scene/3d/spatial.h"
#include "scene/gui/control.h"
-#include "scene/2d/node_2d.h"
#include "scene/main/instance_placeholder.h"
-#include "core/core_string_names.h"
#define PACK_VERSION 2
bool SceneState::can_instance() const {
- return nodes.size()>0;
+ return nodes.size() > 0;
}
-
Node *SceneState::instance(GenEditState p_edit_state) const {
// nodes where instancing failed (because something is missing)
- List<Node*> stray_instances;
+ List<Node *> stray_instances;
-#define NODE_FROM_ID(p_name,p_id)\
- Node *p_name;\
- if (p_id&FLAG_ID_IS_PATH) {\
- NodePath np=node_paths[p_id&FLAG_MASK];\
- p_name=ret_nodes[0]->_get_node(np);\
- } else {\
- ERR_FAIL_INDEX_V(p_id&FLAG_MASK,nc,NULL);\
- p_name=ret_nodes[p_id&FLAG_MASK];\
+#define NODE_FROM_ID(p_name, p_id) \
+ Node *p_name; \
+ if (p_id & FLAG_ID_IS_PATH) { \
+ NodePath np = node_paths[p_id & FLAG_MASK]; \
+ p_name = ret_nodes[0]->_get_node(np); \
+ } else { \
+ ERR_FAIL_INDEX_V(p_id &FLAG_MASK, nc, NULL); \
+ p_name = ret_nodes[p_id & FLAG_MASK]; \
}
int nc = nodes.size();
- ERR_FAIL_COND_V(nc==0,NULL);
+ ERR_FAIL_COND_V(nc == 0, NULL);
- const StringName*snames=NULL;
- int sname_count=names.size();
+ const StringName *snames = NULL;
+ int sname_count = names.size();
if (sname_count)
- snames=&names[0];
+ snames = &names[0];
- const Variant*props=NULL;
- int prop_count=variants.size();
+ const Variant *props = NULL;
+ int prop_count = variants.size();
if (prop_count)
- props=&variants[0];
+ props = &variants[0];
//Vector<Variant> properties;
const NodeData *nd = &nodes[0];
- Node **ret_nodes=(Node**)alloca( sizeof(Node*)*nc );
+ Node **ret_nodes = (Node **)alloca(sizeof(Node *) * nc);
- bool gen_node_path_cache=p_edit_state!=GEN_EDIT_STATE_DISABLED && node_path_cache.empty();
+ bool gen_node_path_cache = p_edit_state != GEN_EDIT_STATE_DISABLED && node_path_cache.empty();
- Map<Ref<Resource>,Ref<Resource> > resources_local_to_scene;
+ Map<Ref<Resource>, Ref<Resource> > resources_local_to_scene;
- for(int i=0;i<nc;i++) {
+ for (int i = 0; i < nc; i++) {
- const NodeData &n=nd[i];
+ const NodeData &n = nd[i];
- Node *parent=NULL;
+ Node *parent = NULL;
- if (i>0) {
+ if (i > 0) {
- NODE_FROM_ID(nparent,n.parent);
+ NODE_FROM_ID(nparent, n.parent);
#ifdef DEBUG_ENABLED
- if (!nparent && n.parent&FLAG_ID_IS_PATH) {
-
- WARN_PRINT(String("Parent path '"+String(node_paths[n.parent&FLAG_MASK])+"' for node '"+String(snames[n.name])+"' has vanished when instancing: '"+get_path()+"'.").ascii().get_data());
+ if (!nparent && n.parent & FLAG_ID_IS_PATH) {
+ WARN_PRINT(String("Parent path '" + String(node_paths[n.parent & FLAG_MASK]) + "' for node '" + String(snames[n.name]) + "' has vanished when instancing: '" + get_path() + "'.").ascii().get_data());
}
#endif
- parent=nparent;
+ parent = nparent;
}
- Node *node=NULL;
-
+ Node *node = NULL;
- if (i==0 && base_scene_idx>=0) {
+ if (i == 0 && base_scene_idx >= 0) {
//scene inheritance on root node
- //print_line("scene inherit");
- Ref<PackedScene> sdata = props[ base_scene_idx ];
- ERR_FAIL_COND_V( !sdata.is_valid(), NULL);
- node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state
- ERR_FAIL_COND_V(!node,NULL);
- if (p_edit_state!=GEN_EDIT_STATE_DISABLED) {
+ //print_line("scene inherit");
+ Ref<PackedScene> sdata = props[base_scene_idx];
+ ERR_FAIL_COND_V(!sdata.is_valid(), NULL);
+ node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE); //only main gets main edit state
+ ERR_FAIL_COND_V(!node, NULL);
+ if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
node->set_scene_inherited_state(sdata->get_state());
}
- } else if (n.instance>=0) {
+ } else if (n.instance >= 0) {
//instance a scene into this node
- //print_line("instance");
- if (n.instance&FLAG_INSTANCE_IS_PLACEHOLDER) {
+ //print_line("instance");
+ if (n.instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
- String path = props[n.instance&FLAG_MASK];
+ String path = props[n.instance & FLAG_MASK];
if (disable_placeholders) {
- Ref<PackedScene> sdata = ResourceLoader::load(path,"PackedScene");
- ERR_FAIL_COND_V( !sdata.is_valid(), NULL);
- node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
- ERR_FAIL_COND_V(!node,NULL);
+ Ref<PackedScene> sdata = ResourceLoader::load(path, "PackedScene");
+ ERR_FAIL_COND_V(!sdata.is_valid(), NULL);
+ node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
+ ERR_FAIL_COND_V(!node, NULL);
} else {
- InstancePlaceholder *ip = memnew( InstancePlaceholder );
+ InstancePlaceholder *ip = memnew(InstancePlaceholder);
ip->set_instance_path(path);
- node=ip;
+ node = ip;
}
node->set_scene_instance_load_placeholder(true);
} else {
- Ref<PackedScene> sdata = props[ n.instance&FLAG_MASK ];
- ERR_FAIL_COND_V( !sdata.is_valid(), NULL);
- node = sdata->instance(p_edit_state==GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
- ERR_FAIL_COND_V(!node,NULL);
-
+ Ref<PackedScene> sdata = props[n.instance & FLAG_MASK];
+ ERR_FAIL_COND_V(!sdata.is_valid(), NULL);
+ node = sdata->instance(p_edit_state == GEN_EDIT_STATE_DISABLED ? PackedScene::GEN_EDIT_STATE_DISABLED : PackedScene::GEN_EDIT_STATE_INSTANCE);
+ ERR_FAIL_COND_V(!node, NULL);
}
- } else if (n.type==TYPE_INSTANCED) {
+ } else if (n.type == TYPE_INSTANCED) {
//print_line("instanced");
//get the node from somewhere, it likely already exists from another instance
if (parent) {
- node=parent->_get_child_by_name(snames[n.name]);
+ node = parent->_get_child_by_name(snames[n.name]);
#ifdef DEBUG_ENABLED
if (!node) {
- WARN_PRINT(String("Node '"+String(ret_nodes[0]->get_path_to(parent))+"/"+String(snames[n.name])+"' was modified from inside a instance, but it has vanished.").ascii().get_data());
+ WARN_PRINT(String("Node '" + String(ret_nodes[0]->get_path_to(parent)) + "/" + String(snames[n.name]) + "' was modified from inside a instance, but it has vanished.").ascii().get_data());
}
#endif
}
} else if (ClassDB::is_class_enabled(snames[n.type])) {
- //print_line("created");
+ //print_line("created");
//node belongs to this scene and must be created
- Object * obj = ClassDB::instance(snames[ n.type ]);
+ Object *obj = ClassDB::instance(snames[n.type]);
if (!obj || !obj->cast_to<Node>()) {
if (obj) {
memdelete(obj);
- obj=NULL;
+ obj = NULL;
}
- WARN_PRINT(String("Warning node of type "+snames[n.type].operator String()+" does not exist.").ascii().get_data());
- if (n.parent>=0 && n.parent<nc && ret_nodes[n.parent]) {
+ WARN_PRINT(String("Warning node of type " + snames[n.type].operator String() + " does not exist.").ascii().get_data());
+ if (n.parent >= 0 && n.parent < nc && ret_nodes[n.parent]) {
if (ret_nodes[n.parent]->cast_to<Spatial>()) {
- obj = memnew( Spatial );
+ obj = memnew(Spatial);
} else if (ret_nodes[n.parent]->cast_to<Control>()) {
- obj = memnew( Control );
+ obj = memnew(Control);
} else if (ret_nodes[n.parent]->cast_to<Node2D>()) {
- obj = memnew( Node2D );
+ obj = memnew(Node2D);
}
}
if (!obj) {
- obj = memnew( Node );
+ obj = memnew(Node);
}
}
node = obj->cast_to<Node>();
} else {
- print_line("wtf class is disabled for: "+itos(n.type));
- print_line("name: "+String(snames[n.type]));
+ print_line("wtf class is disabled for: " + itos(n.type));
+ print_line("name: " + String(snames[n.type]));
}
-
if (node) {
// may not have found the node (part of instanced scene and removed)
// if found all is good, otherwise ignore
//properties
- int nprop_count=n.properties.size();
+ int nprop_count = n.properties.size();
if (nprop_count) {
- const NodeData::Property* nprops=&n.properties[0];
+ const NodeData::Property *nprops = &n.properties[0];
- for(int j=0;j<nprop_count;j++) {
+ for (int j = 0; j < nprop_count; j++) {
bool valid;
- ERR_FAIL_INDEX_V( nprops[j].name, sname_count, NULL );
- ERR_FAIL_INDEX_V( nprops[j].value, prop_count, NULL );
-
+ ERR_FAIL_INDEX_V(nprops[j].name, sname_count, NULL);
+ ERR_FAIL_INDEX_V(nprops[j].value, prop_count, NULL);
- if (snames[ nprops[j].name ]==CoreStringNames::get_singleton()->_script) {
+ if (snames[nprops[j].name] == CoreStringNames::get_singleton()->_script) {
//work around to avoid old script variables from disappearing, should be the proper fix to:
//https://github.com/godotengine/godot/issues/2958
//store old state
- List<Pair<StringName,Variant> > old_state;
+ List<Pair<StringName, Variant> > old_state;
if (node->get_script_instance()) {
node->get_script_instance()->get_property_state(old_state);
}
- node->set(snames[ nprops[j].name ],props[ nprops[j].value ],&valid);
+ node->set(snames[nprops[j].name], props[nprops[j].value], &valid);
//restore old state for new script, if exists
- for (List<Pair<StringName,Variant> >::Element *E=old_state.front();E;E=E->next()) {
- node->set(E->get().first,E->get().second);
+ for (List<Pair<StringName, Variant> >::Element *E = old_state.front(); E; E = E->next()) {
+ node->set(E->get().first, E->get().second);
}
} else {
- Variant value = props[ nprops[j].value ];
+ Variant value = props[nprops[j].value];
- if (value.get_type()==Variant::OBJECT) {
+ if (value.get_type() == Variant::OBJECT) {
//handle resources that are local to scene by duplicating them if needed
Ref<Resource> res = value;
if (res.is_valid()) {
if (res->is_local_to_scene()) {
- Map<Ref<Resource>,Ref<Resource> >::Element *E=resources_local_to_scene.find(res);
+ Map<Ref<Resource>, Ref<Resource> >::Element *E = resources_local_to_scene.find(res);
if (E) {
- value=E->get();
+ value = E->get();
} else {
- Node *base = i==0?node:ret_nodes[0];
+ Node *base = i == 0 ? node : ret_nodes[0];
- if (p_edit_state==GEN_EDIT_STATE_MAIN) {
+ if (p_edit_state == GEN_EDIT_STATE_MAIN) {
- res->local_scene=base;
- resources_local_to_scene[res]=res;
+ res->local_scene = base;
+ resources_local_to_scene[res] = res;
} else {
- Node *base = i==0?node:ret_nodes[0];
- Ref<Resource> local_dupe = res->duplicate_for_local_scene(base,resources_local_to_scene);
- resources_local_to_scene[res]=local_dupe;
- res=local_dupe;
- value=local_dupe;
+ Node *base = i == 0 ? node : ret_nodes[0];
+ Ref<Resource> local_dupe = res->duplicate_for_local_scene(base, resources_local_to_scene);
+ resources_local_to_scene[res] = local_dupe;
+ res = local_dupe;
+ value = local_dupe;
}
res->setup_local_to_scene();
-
}
//must make a copy, because this res is local to scene
}
}
}
- node->set(snames[ nprops[j].name ],value,&valid);
+ node->set(snames[nprops[j].name], value, &valid);
}
}
}
@@ -262,60 +255,56 @@ Node *SceneState::instance(GenEditState p_edit_state) const {
//name
//groups
- for(int j=0;j<n.groups.size();j++) {
+ for (int j = 0; j < n.groups.size(); j++) {
- ERR_FAIL_INDEX_V( n.groups[j], sname_count, NULL );
- node->add_to_group( snames[ n.groups[j] ], true );
+ ERR_FAIL_INDEX_V(n.groups[j], sname_count, NULL);
+ node->add_to_group(snames[n.groups[j]], true);
}
- if (n.instance>=0 || n.type!=TYPE_INSTANCED || i==0) {
+ if (n.instance >= 0 || n.type != TYPE_INSTANCED || i == 0) {
//if node was not part of instance, must set it's name, parenthood and ownership
- if (i>0) {
+ if (i > 0) {
if (parent) {
- parent->_add_child_nocheck(node,snames[n.name]);
+ parent->_add_child_nocheck(node, snames[n.name]);
} else {
//it may be possible that an instanced scene has changed
//and the node has nowhere to go anymore
stray_instances.push_back(node); //can't be added, go to stray list
}
} else {
- node->_set_name_nocheck( snames[ n.name ] );
+ node->_set_name_nocheck(snames[n.name]);
}
}
- if (n.owner>=0) {
+ if (n.owner >= 0) {
- NODE_FROM_ID(owner,n.owner);
+ NODE_FROM_ID(owner, n.owner);
if (owner)
node->_set_owner_nocheck(owner);
}
-
-
}
-
- ret_nodes[i]=node;
+ ret_nodes[i] = node;
if (node && gen_node_path_cache && ret_nodes[0]) {
NodePath n = ret_nodes[0]->get_path_to(node);
- node_path_cache[n]=i;
+ node_path_cache[n] = i;
}
}
-
//do connections
int cc = connections.size();
const ConnectionData *cdata = connections.ptr();
- for(int i=0;i<cc;i++) {
+ for (int i = 0; i < cc; i++) {
- const ConnectionData &c=cdata[i];
+ const ConnectionData &c = cdata[i];
//ERR_FAIL_INDEX_V( c.from, nc, NULL );
//ERR_FAIL_INDEX_V( c.to, nc, NULL );
- NODE_FROM_ID(cfrom,c.from);
- NODE_FROM_ID(cto,c.to);
+ NODE_FROM_ID(cfrom, c.from);
+ NODE_FROM_ID(cto, c.to);
if (!cfrom || !cto)
continue;
@@ -323,56 +312,52 @@ Node *SceneState::instance(GenEditState p_edit_state) const {
Vector<Variant> binds;
if (c.binds.size()) {
binds.resize(c.binds.size());
- for(int j=0;j<c.binds.size();j++)
- binds[j]=props[ c.binds[j] ];
+ for (int j = 0; j < c.binds.size(); j++)
+ binds[j] = props[c.binds[j]];
}
-
- cfrom->connect( snames[ c.signal], cto, snames[ c.method], binds,CONNECT_PERSIST|c.flags );
+ cfrom->connect(snames[c.signal], cto, snames[c.method], binds, CONNECT_PERSIST | c.flags);
}
//Node *s = ret_nodes[0];
//remove nodes that could not be added, likely as a result that
- while(stray_instances.size()) {
+ while (stray_instances.size()) {
memdelete(stray_instances.front()->get());
stray_instances.pop_front();
}
- for(int i=0;i<editable_instances.size();i++) {
+ for (int i = 0; i < editable_instances.size(); i++) {
Node *ei = ret_nodes[0]->_get_node(editable_instances[i]);
if (ei) {
- ret_nodes[0]->set_editable_instance(ei,true);
+ ret_nodes[0]->set_editable_instance(ei, true);
}
}
return ret_nodes[0];
-
}
-
-static int _nm_get_string(const String& p_string, Map<StringName,int> &name_map) {
+static int _nm_get_string(const String &p_string, Map<StringName, int> &name_map) {
if (name_map.has(p_string))
return name_map[p_string];
int idx = name_map.size();
- name_map[p_string]=idx;
+ name_map[p_string] = idx;
return idx;
}
-static int _vm_get_variant(const Variant& p_variant, HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map) {
+static int _vm_get_variant(const Variant &p_variant, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map) {
if (variant_map.has(p_variant))
return variant_map[p_variant];
int idx = variant_map.size();
- variant_map[p_variant]=idx;
+ variant_map[p_variant] = idx;
return idx;
}
-Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map) {
-
+Error SceneState::_parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map) {
// this function handles all the work related to properly packing scenes, be it
// instanced or inherited.
@@ -380,18 +365,18 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
// document it. if you fail to understand something, please ask!
//discard nodes that do not belong to be processed
- if (p_node!=p_owner && p_node->get_owner()!=p_owner && !p_owner->is_editable_instance(p_node->get_owner()))
+ if (p_node != p_owner && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner()))
return OK;
// save the child instanced scenes that are chosen as editable, so they can be restored
// upon load back
- if (p_node!=p_owner && p_node->get_filename()!=String() && p_owner->is_editable_instance(p_node))
+ if (p_node != p_owner && p_node->get_filename() != String() && p_owner->is_editable_instance(p_node))
editable_instances.push_back(p_owner->get_path_to(p_node));
NodeData nd;
- nd.name=_nm_get_string(p_node->get_name(),name_map);
- nd.instance=-1; //not instanced by default
+ nd.name = _nm_get_string(p_node->get_name(), name_map);
+ nd.instance = -1; //not instanced by default
// if this node is part of an instanced scene or sub-instanced scene
// we need to get the corresponding instance states.
@@ -400,34 +385,34 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
List<PackState> pack_state_stack;
- bool instanced_by_owner=true;
+ bool instanced_by_owner = true;
{
- Node *n=p_node;
+ Node *n = p_node;
- while(n) {
+ while (n) {
- if (n==p_owner) {
+ if (n == p_owner) {
Ref<SceneState> state = n->get_scene_inherited_state();
if (state.is_valid()) {
int node = state->find_node_by_path(n->get_path_to(p_node));
- if (node>=0) {
+ if (node >= 0) {
//this one has state for this node, save
PackState ps;
- ps.node=node;
- ps.state=state;
+ ps.node = node;
+ ps.state = state;
pack_state_stack.push_back(ps);
- instanced_by_owner=false;
+ instanced_by_owner = false;
}
}
- if (p_node->get_filename()!=String() && p_node->get_owner()==p_owner && instanced_by_owner) {
+ if (p_node->get_filename() != String() && p_node->get_owner() == p_owner && instanced_by_owner) {
if (p_node->get_scene_instance_load_placeholder()) {
//it's a placeholder, use the placeholder path
- nd.instance=_vm_get_variant(p_node->get_filename(),variant_map);
- nd.instance|=FLAG_INSTANCE_IS_PLACEHOLDER;
+ nd.instance = _vm_get_variant(p_node->get_filename(), variant_map);
+ nd.instance |= FLAG_INSTANCE_IS_PLACEHOLDER;
} else {
//must instance ourselves
Ref<PackedScene> instance = ResourceLoader::load(p_node->get_filename());
@@ -435,27 +420,26 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
return ERR_CANT_OPEN;
}
- nd.instance=_vm_get_variant(instance,variant_map);
+ nd.instance = _vm_get_variant(instance, variant_map);
}
}
- n=NULL;
+ n = NULL;
} else {
- if (n->get_filename()!=String()) {
+ if (n->get_filename() != String()) {
//is an instance
Ref<SceneState> state = n->get_scene_instance_state();
if (state.is_valid()) {
int node = state->find_node_by_path(n->get_path_to(p_node));
- if (node>=0) {
+ if (node >= 0) {
//this one has state for this node, save
PackState ps;
- ps.node=node;
- ps.state=state;
+ ps.node = node;
+ ps.state = state;
pack_state_stack.push_back(ps);
}
}
-
}
- n=n->get_owner();
+ n = n->get_owner();
}
}
}
@@ -520,16 +504,14 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
List<PropertyInfo> plist;
p_node->get_property_list(&plist);
- for (List<PropertyInfo>::Element *E=plist.front();E;E=E->next()) {
-
+ for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) {
if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) {
continue;
}
String name = E->get().name;
- Variant value = p_node->get( E->get().name );
-
+ Variant value = p_node->get(E->get().name);
bool isdefault = ((E->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO) && value.is_zero()) || ((E->get().usage & PROPERTY_USAGE_STORE_IF_NONONE) && value.is_one());
@@ -539,8 +521,6 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
}
*/
-
-
//print_line("PASSED!");
//print_line("at: "+String(p_node->get_name())+"::"+name+": - nz: "+itos(E->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO)+" no: "+itos(E->get().usage&PROPERTY_USAGE_STORE_IF_NONONE));
//print_line("value: "+String(value)+" is zero: "+itos(value.is_zero())+" is one" +itos(value.is_one()));
@@ -551,37 +531,36 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
// only save what has been changed
// only save changed properties in instance
- if (E->get().usage & PROPERTY_USAGE_NO_INSTANCE_STATE || E->get().name=="__meta__") {
+ if (E->get().usage & PROPERTY_USAGE_NO_INSTANCE_STATE || E->get().name == "__meta__") {
//property has requested that no instance state is saved, sorry
//also, meta won't be overriden or saved
continue;
}
- bool exists=false;
+ bool exists = false;
Variant original;
- for (List<PackState>::Element *F=pack_state_stack.back();F;F=F->prev()) {
+ for (List<PackState>::Element *F = pack_state_stack.back(); F; F = F->prev()) {
//check all levels of pack to see if the property exists somewhere
- const PackState &ps=F->get();
+ const PackState &ps = F->get();
- original = ps.state->get_property_value(ps.node,E->get().name,exists);
+ original = ps.state->get_property_value(ps.node, E->get().name, exists);
if (exists) {
break;
}
}
-
if (exists) {
//check if already exists and did not change
- if (value.get_type()==Variant::REAL && original.get_type()==Variant::REAL) {
+ if (value.get_type() == Variant::REAL && original.get_type() == Variant::REAL) {
//this must be done because, as some scenes save as text, there might be a tiny difference in floats due to numerical error
float a = value;
float b = original;
- if (Math::abs(a-b)<CMP_EPSILON)
+ if (Math::abs(a - b) < CMP_EPSILON)
continue;
- } else if (bool(Variant::evaluate(Variant::OP_EQUAL,value,original))) {
+ } else if (bool(Variant::evaluate(Variant::OP_EQUAL, value, original))) {
continue;
}
@@ -593,8 +572,7 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
continue;
}
-
- } else {
+ } else {
if (isdefault) {
//it's the default value, no point in saving it
@@ -603,20 +581,18 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
}
NodeData::Property prop;
- prop.name=_nm_get_string( name,name_map);
- prop.value=_vm_get_variant( value, variant_map);
+ prop.name = _nm_get_string(name, name_map);
+ prop.value = _vm_get_variant(value, variant_map);
nd.properties.push_back(prop);
-
}
-
// save the groups this node is into
// discard groups that come from the original scene
List<Node::GroupInfo> groups;
p_node->get_groups(&groups);
- for(List<Node::GroupInfo>::Element *E=groups.front();E;E=E->next()) {
- Node::GroupInfo &gi=E->get();
+ for (List<Node::GroupInfo>::Element *E = groups.front(); E; E = E->next()) {
+ Node::GroupInfo &gi = E->get();
if (!gi.persistent)
continue;
@@ -625,12 +601,12 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
continue; //group was instanced, don't add here
*/
- bool skip=false;
- for (List<PackState>::Element *F=pack_state_stack.front();F;F=F->next()) {
+ bool skip = false;
+ for (List<PackState>::Element *F = pack_state_stack.front(); F; F = F->next()) {
//check all levels of pack to see if the group was added somewhere
- const PackState &ps=F->get();
- if (ps.state->is_node_in_group(ps.node,gi.name)) {
- skip=true;
+ const PackState &ps = F->get();
+ if (ps.state->is_node_in_group(ps.node, gi.name)) {
+ skip = true;
break;
}
}
@@ -638,24 +614,23 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
if (skip)
continue;
- nd.groups.push_back(_nm_get_string(gi.name,name_map));
+ nd.groups.push_back(_nm_get_string(gi.name, name_map));
}
-
// save the right owner
// for the saved scene root this is -1
// for nodes of the saved scene this is 0
// for nodes of instanced scenes this is >0
- if (p_node==p_owner) {
+ if (p_node == p_owner) {
//saved scene root
- nd.owner=-1;
- } else if (p_node->get_owner()==p_owner) {
+ nd.owner = -1;
+ } else if (p_node->get_owner() == p_owner) {
//part of saved scene
- nd.owner=0;
+ nd.owner = 0;
} else {
- nd.owner=-1;
+ nd.owner = -1;
#if 0
// this is pointless, if this was instanced by something else,
// the owner will already be set.
@@ -677,22 +652,19 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
}
#endif
-
-
}
// Save the right type. If this node was created by an instance
// then flag that the node should not be created but reused
if (pack_state_stack.empty()) {
//this node is not part of an instancing process, so save the type
- nd.type=_nm_get_string(p_node->get_class(),name_map);
+ nd.type = _nm_get_string(p_node->get_class(), name_map);
} else {
// this node is part of an instanced process, so do not save the type.
// instead, save that it was instanced
- nd.type=TYPE_INSTANCED;
+ nd.type = TYPE_INSTANCED;
}
-
// determine whether to save this node or not
// if this node is part of an instanced sub-scene, we can skip storing it if basically
// no properties changed and no groups were added to it.
@@ -700,59 +672,54 @@ Error SceneState::_parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<S
// that hold changes
bool save_node = nd.properties.size() || nd.groups.size(); // some local properties or groups exist
- save_node = save_node || p_node==p_owner; // owner is always saved
- save_node = save_node || (p_node->get_owner()==p_owner && instanced_by_owner); //part of scene and not instanced
-
+ save_node = save_node || p_node == p_owner; // owner is always saved
+ save_node = save_node || (p_node->get_owner() == p_owner && instanced_by_owner); //part of scene and not instanced
int idx = nodes.size();
- int parent_node=NO_PARENT_SAVED;
+ int parent_node = NO_PARENT_SAVED;
if (save_node) {
//don't save the node if nothing and subscene
- node_map[p_node]=idx;
+ node_map[p_node] = idx;
//ok validate parent node
- if (p_parent_idx==NO_PARENT_SAVED) {
+ if (p_parent_idx == NO_PARENT_SAVED) {
int sidx;
if (nodepath_map.has(p_node->get_parent())) {
- sidx=nodepath_map[p_node->get_parent()];
+ sidx = nodepath_map[p_node->get_parent()];
} else {
- sidx=nodepath_map.size();
- nodepath_map[p_node->get_parent()]=sidx;
+ sidx = nodepath_map.size();
+ nodepath_map[p_node->get_parent()] = sidx;
}
- nd.parent=FLAG_ID_IS_PATH|sidx;
+ nd.parent = FLAG_ID_IS_PATH | sidx;
} else {
- nd.parent=p_parent_idx;
+ nd.parent = p_parent_idx;
}
- parent_node=idx;
+ parent_node = idx;
nodes.push_back(nd);
-
}
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- for(int i=0;i<p_node->get_child_count();i++) {
-
- Node *c=p_node->get_child(i);
- Error err = _parse_node(p_owner,c,parent_node,name_map,variant_map,node_map,nodepath_map);
+ Node *c = p_node->get_child(i);
+ Error err = _parse_node(p_owner, c, parent_node, name_map, variant_map, node_map, nodepath_map);
if (err)
return err;
}
return OK;
-
}
-Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map) {
+Error SceneState::_parse_connections(Node *p_owner, Node *p_node, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map) {
- if (p_node!=p_owner && p_node->get_owner() && p_node->get_owner()!=p_owner && !p_owner->is_editable_instance(p_node->get_owner()))
+ if (p_node != p_owner && p_node->get_owner() && p_node->get_owner() != p_owner && !p_owner->is_editable_instance(p_node->get_owner()))
return OK;
-
List<MethodInfo> _signals;
p_node->get_signal_list(&_signals);
_signals.sort();
@@ -760,27 +727,24 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName,
//ERR_FAIL_COND_V( !node_map.has(p_node), ERR_BUG);
//NodeData &nd = nodes[node_map[p_node]];
-
- for(List<MethodInfo>::Element *E=_signals.front();E;E=E->next()) {
+ for (List<MethodInfo>::Element *E = _signals.front(); E; E = E->next()) {
List<Node::Connection> conns;
- p_node->get_signal_connection_list(E->get().name,&conns);
+ p_node->get_signal_connection_list(E->get().name, &conns);
conns.sort();
- for(List<Node::Connection>::Element *F=conns.front();F;F=F->next()) {
+ for (List<Node::Connection>::Element *F = conns.front(); F; F = F->next()) {
const Node::Connection &c = F->get();
- if (!(c.flags&CONNECT_PERSIST)) //only persistent connections get saved
+ if (!(c.flags & CONNECT_PERSIST)) //only persistent connections get saved
continue;
// only connections that originate or end into main saved scene are saved
// everything else is discarded
-
- Node *target=c.target->cast_to<Node>();
-
+ Node *target = c.target->cast_to<Node>();
if (!target) {
continue;
@@ -791,150 +755,139 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName,
ERR_CONTINUE(!common_parent);
- if (common_parent!=p_owner && common_parent->get_filename()==String()) {
- common_parent=common_parent->get_owner();
+ if (common_parent != p_owner && common_parent->get_filename() == String()) {
+ common_parent = common_parent->get_owner();
}
- bool exists=false;
+ bool exists = false;
//go through ownership chain to see if this exists
- while(common_parent) {
-
-
+ while (common_parent) {
Ref<SceneState> ps;
- if (common_parent==p_owner)
- ps=common_parent->get_scene_inherited_state();
+ if (common_parent == p_owner)
+ ps = common_parent->get_scene_inherited_state();
else
- ps=common_parent->get_scene_instance_state();
-
+ ps = common_parent->get_scene_instance_state();
if (ps.is_valid()) {
NodePath signal_from = common_parent->get_path_to(p_node);
NodePath signal_to = common_parent->get_path_to(target);
- if (ps->has_connection(signal_from,c.signal,signal_to,c.method)) {
- exists=true;
+ if (ps->has_connection(signal_from, c.signal, signal_to, c.method)) {
+ exists = true;
break;
}
-
}
- if (common_parent==p_owner)
+ if (common_parent == p_owner)
break;
else
- common_parent=common_parent->get_owner();
+ common_parent = common_parent->get_owner();
}
if (exists) { //already exists (comes from instance or inheritance), so don't save
continue;
}
-
-
{
- Node *nl=p_node;
+ Node *nl = p_node;
- bool exists=false;
+ bool exists = false;
- while(nl) {
+ while (nl) {
- if (nl==p_owner) {
+ if (nl == p_owner) {
Ref<SceneState> state = nl->get_scene_inherited_state();
if (state.is_valid()) {
int from_node = state->find_node_by_path(nl->get_path_to(p_node));
int to_node = state->find_node_by_path(nl->get_path_to(target));
- if (from_node>=0 && to_node>=0) {
+ if (from_node >= 0 && to_node >= 0) {
//this one has state for this node, save
- if (state->is_connection(from_node,c.signal,to_node,c.method)) {
- exists=true;
+ if (state->is_connection(from_node, c.signal, to_node, c.method)) {
+ exists = true;
break;
}
}
}
- nl=NULL;
+ nl = NULL;
} else {
- if (nl->get_filename()!=String()) {
+ if (nl->get_filename() != String()) {
//is an instance
Ref<SceneState> state = nl->get_scene_instance_state();
if (state.is_valid()) {
int from_node = state->find_node_by_path(nl->get_path_to(p_node));
int to_node = state->find_node_by_path(nl->get_path_to(target));
- if (from_node>=0 && to_node>=0) {
+ if (from_node >= 0 && to_node >= 0) {
//this one has state for this node, save
- if (state->is_connection(from_node,c.signal,to_node,c.method)) {
- exists=true;
+ if (state->is_connection(from_node, c.signal, to_node, c.method)) {
+ exists = true;
break;
}
}
}
-
}
- nl=nl->get_owner();
+ nl = nl->get_owner();
}
}
if (exists) {
continue;
}
-
}
-
int src_id;
if (node_map.has(p_node)) {
- src_id=node_map[p_node];
+ src_id = node_map[p_node];
} else {
if (nodepath_map.has(p_node)) {
- src_id=FLAG_ID_IS_PATH|nodepath_map[p_node];
+ src_id = FLAG_ID_IS_PATH | nodepath_map[p_node];
} else {
- int sidx=nodepath_map.size();
- nodepath_map[p_node]=sidx;
- src_id=FLAG_ID_IS_PATH|sidx;
+ int sidx = nodepath_map.size();
+ nodepath_map[p_node] = sidx;
+ src_id = FLAG_ID_IS_PATH | sidx;
}
}
-
-
int target_id;
if (node_map.has(target)) {
- target_id=node_map[target];
+ target_id = node_map[target];
} else {
if (nodepath_map.has(target)) {
- target_id=FLAG_ID_IS_PATH|nodepath_map[target];
+ target_id = FLAG_ID_IS_PATH | nodepath_map[target];
} else {
- int sidx=nodepath_map.size();
- nodepath_map[target]=sidx;
- target_id=FLAG_ID_IS_PATH|sidx;
+ int sidx = nodepath_map.size();
+ nodepath_map[target] = sidx;
+ target_id = FLAG_ID_IS_PATH | sidx;
}
}
ConnectionData cd;
- cd.from=src_id;
- cd.to=target_id;
- cd.method=_nm_get_string(c.method,name_map);
- cd.signal=_nm_get_string(c.signal,name_map);
- cd.flags=c.flags;
- for(int i=0;i<c.binds.size();i++) {
-
- cd.binds.push_back( _vm_get_variant(c.binds[i],variant_map));
+ cd.from = src_id;
+ cd.to = target_id;
+ cd.method = _nm_get_string(c.method, name_map);
+ cd.signal = _nm_get_string(c.signal, name_map);
+ cd.flags = c.flags;
+ for (int i = 0; i < c.binds.size(); i++) {
+
+ cd.binds.push_back(_vm_get_variant(c.binds[i], variant_map));
}
connections.push_back(cd);
}
}
- for(int i=0;i<p_node->get_child_count();i++) {
+ for (int i = 0; i < p_node->get_child_count(); i++) {
- Node *c=p_node->get_child(i);
- Error err = _parse_connections(p_owner,c,name_map,variant_map,node_map,nodepath_map);
+ Node *c = p_node->get_child(i);
+ Error err = _parse_connections(p_owner, c, name_map, variant_map, node_map, nodepath_map);
if (err)
return err;
}
@@ -942,19 +895,17 @@ Error SceneState::_parse_connections(Node *p_owner,Node *p_node, Map<StringName,
return OK;
}
-
Error SceneState::pack(Node *p_scene) {
- ERR_FAIL_NULL_V( p_scene, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_NULL_V(p_scene, ERR_INVALID_PARAMETER);
clear();
Node *scene = p_scene;
- Map<StringName,int> name_map;
- HashMap<Variant,int,VariantHasher,VariantComparator> variant_map;
- Map<Node*,int> node_map;
- Map<Node*,int> nodepath_map;
+ Map<StringName, int> name_map;
+ HashMap<Variant, int, VariantHasher, VariantComparator> variant_map;
+ Map<Node *, int> node_map;
+ Map<Node *, int> nodepath_map;
//if using scene inheritance, pack the scene it inherits from
if (scene->get_scene_inherited_state().is_valid()) {
@@ -962,19 +913,18 @@ Error SceneState::pack(Node *p_scene) {
Ref<PackedScene> instance = ResourceLoader::load(path);
if (instance.is_valid()) {
- base_scene_idx=_vm_get_variant(instance,variant_map);
+ base_scene_idx = _vm_get_variant(instance, variant_map);
}
}
//instanced, only direct sub-scnes are supported of course
-
- Error err = _parse_node(scene,scene,-1,name_map,variant_map,node_map,nodepath_map);
+ Error err = _parse_node(scene, scene, -1, name_map, variant_map, node_map, nodepath_map);
if (err) {
clear();
ERR_FAIL_V(err);
}
- err = _parse_connections(scene,scene,name_map,variant_map,node_map,nodepath_map);
+ err = _parse_connections(scene, scene, name_map, variant_map, node_map, nodepath_map);
if (err) {
clear();
ERR_FAIL_V(err);
@@ -982,35 +932,34 @@ Error SceneState::pack(Node *p_scene) {
names.resize(name_map.size());
- for(Map<StringName,int>::Element *E=name_map.front();E;E=E->next()) {
+ for (Map<StringName, int>::Element *E = name_map.front(); E; E = E->next()) {
- names[E->get()]=E->key();
+ names[E->get()] = E->key();
}
variants.resize(variant_map.size());
- const Variant *K=NULL;
- while((K=variant_map.next(K))) {
+ const Variant *K = NULL;
+ while ((K = variant_map.next(K))) {
int idx = variant_map[*K];
- variants[idx]=*K;
+ variants[idx] = *K;
}
node_paths.resize(nodepath_map.size());
- for(Map<Node*,int>::Element *E=nodepath_map.front();E;E=E->next()) {
+ for (Map<Node *, int>::Element *E = nodepath_map.front(); E; E = E->next()) {
- node_paths[E->get()]=scene->get_path_to(E->key());
+ node_paths[E->get()] = scene->get_path_to(E->key());
}
-
return OK;
}
void SceneState::set_path(const String &p_path) {
- path=p_path;
+ path = p_path;
}
-String SceneState::get_path() const{
+String SceneState::get_path() const {
return path;
}
@@ -1024,13 +973,12 @@ void SceneState::clear() {
node_path_cache.clear();
node_paths.clear();
editable_instances.clear();
- base_scene_idx=-1;
-
+ base_scene_idx = -1;
}
Ref<SceneState> SceneState::_get_base_scene_state() const {
- if (base_scene_idx>=0) {
+ if (base_scene_idx >= 0) {
Ref<PackedScene> ps = variants[base_scene_idx];
if (ps.is_valid()) {
@@ -1041,15 +989,15 @@ Ref<SceneState> SceneState::_get_base_scene_state() const {
return Ref<SceneState>();
}
-int SceneState::find_node_by_path(const NodePath& p_node) const {
+int SceneState::find_node_by_path(const NodePath &p_node) const {
if (!node_path_cache.has(p_node)) {
if (_get_base_scene_state().is_valid()) {
int idx = _get_base_scene_state()->find_node_by_path(p_node);
- if (idx>=0) {
+ if (idx >= 0) {
if (!base_scene_node_remap.has(idx)) {
int ridx = nodes.size() + base_scene_node_remap.size();
- base_scene_node_remap[ridx]=idx;
+ base_scene_node_remap[ridx] = idx;
}
return base_scene_node_remap[idx];
@@ -1065,27 +1013,26 @@ int SceneState::find_node_by_path(const NodePath& p_node) const {
//the node in the instanced scene, as a property may be missing
//from the local one
int idx = _get_base_scene_state()->find_node_by_path(p_node);
- base_scene_node_remap[nid]=idx;
-
+ base_scene_node_remap[nid] = idx;
}
return nid;
}
-Variant SceneState::get_property_value(int p_node, const StringName& p_property, bool &found) const {
+Variant SceneState::get_property_value(int p_node, const StringName &p_property, bool &found) const {
- found=false;
+ found = false;
- ERR_FAIL_COND_V(p_node<0,Variant());
+ ERR_FAIL_COND_V(p_node < 0, Variant());
- if (p_node<nodes.size()) {
+ if (p_node < nodes.size()) {
//find in built-in nodes
int pc = nodes[p_node].properties.size();
- const StringName* namep = names.ptr();
+ const StringName *namep = names.ptr();
- const NodeData::Property *p=nodes[p_node].properties.ptr();
- for(int i=0;i<pc;i++) {
- if (p_property==namep[p[i].name]) {
- found=true;
+ const NodeData::Property *p = nodes[p_node].properties.ptr();
+ for (int i = 0; i < pc; i++) {
+ if (p_property == namep[p[i].name]) {
+ found = true;
return variants[p[i].value];
}
}
@@ -1094,61 +1041,61 @@ Variant SceneState::get_property_value(int p_node, const StringName& p_property,
//property not found, try on instance
if (base_scene_node_remap.has(p_node)) {
- return _get_base_scene_state()->get_property_value(base_scene_node_remap[p_node],p_property,found);
+ return _get_base_scene_state()->get_property_value(base_scene_node_remap[p_node], p_property, found);
}
return Variant();
}
-bool SceneState::is_node_in_group(int p_node,const StringName& p_group) const {
+bool SceneState::is_node_in_group(int p_node, const StringName &p_group) const {
- ERR_FAIL_COND_V(p_node<0,false);
+ ERR_FAIL_COND_V(p_node < 0, false);
- if (p_node<nodes.size()) {
- const StringName* namep = names.ptr();
- for(int i=0;i<nodes[p_node].groups.size();i++) {
- if (namep[nodes[p_node].groups[i]]==p_group)
+ if (p_node < nodes.size()) {
+ const StringName *namep = names.ptr();
+ for (int i = 0; i < nodes[p_node].groups.size(); i++) {
+ if (namep[nodes[p_node].groups[i]] == p_group)
return true;
}
}
if (base_scene_node_remap.has(p_node)) {
- return _get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node],p_group);
+ return _get_base_scene_state()->is_node_in_group(base_scene_node_remap[p_node], p_group);
}
return false;
}
-bool SceneState::disable_placeholders=false;
+bool SceneState::disable_placeholders = false;
void SceneState::set_disable_placeholders(bool p_disable) {
- disable_placeholders=p_disable;
+ disable_placeholders = p_disable;
}
-bool SceneState::is_connection(int p_node,const StringName& p_signal,int p_to_node,const StringName& p_to_method) const {
+bool SceneState::is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const {
- ERR_FAIL_COND_V(p_node<0,false);
- ERR_FAIL_COND_V(p_to_node<0,false);
+ ERR_FAIL_COND_V(p_node < 0, false);
+ ERR_FAIL_COND_V(p_to_node < 0, false);
- if (p_node<nodes.size() && p_to_node<nodes.size()) {
+ if (p_node < nodes.size() && p_to_node < nodes.size()) {
- int signal_idx=-1;
- int method_idx=-1;
- for(int i=0;i<names.size();i++) {
- if (names[i]==p_signal) {
- signal_idx=i;
- } else if (names[i]==p_to_method) {
- method_idx=i;
+ int signal_idx = -1;
+ int method_idx = -1;
+ for (int i = 0; i < names.size(); i++) {
+ if (names[i] == p_signal) {
+ signal_idx = i;
+ } else if (names[i] == p_to_method) {
+ method_idx = i;
}
}
- if (signal_idx>=0 && method_idx>=0) {
+ if (signal_idx >= 0 && method_idx >= 0) {
//signal and method strings are stored..
- for(int i=0;i<connections.size();i++) {
+ for (int i = 0; i < connections.size(); i++) {
- if (connections[i].from==p_node && connections[i].to==p_to_node && connections[i].signal==signal_idx && connections[i].method==method_idx) {
+ if (connections[i].from == p_node && connections[i].to == p_to_node && connections[i].signal == signal_idx && connections[i].method == method_idx) {
return true;
}
@@ -1157,30 +1104,27 @@ bool SceneState::is_connection(int p_node,const StringName& p_signal,int p_to_no
}
if (base_scene_node_remap.has(p_node) && base_scene_node_remap.has(p_to_node)) {
- return _get_base_scene_state()->is_connection(base_scene_node_remap[p_node],p_signal,base_scene_node_remap[p_to_node],p_to_method);
+ return _get_base_scene_state()->is_connection(base_scene_node_remap[p_node], p_signal, base_scene_node_remap[p_to_node], p_to_method);
}
return false;
-
}
+void SceneState::set_bundled_scene(const Dictionary &d) {
-void SceneState::set_bundled_scene(const Dictionary& d) {
-
-
- ERR_FAIL_COND( !d.has("names"));
- ERR_FAIL_COND( !d.has("variants"));
- ERR_FAIL_COND( !d.has("node_count"));
- ERR_FAIL_COND( !d.has("nodes"));
- ERR_FAIL_COND( !d.has("conn_count"));
- ERR_FAIL_COND( !d.has("conns"));
+ ERR_FAIL_COND(!d.has("names"));
+ ERR_FAIL_COND(!d.has("variants"));
+ ERR_FAIL_COND(!d.has("node_count"));
+ ERR_FAIL_COND(!d.has("nodes"));
+ ERR_FAIL_COND(!d.has("conn_count"));
+ ERR_FAIL_COND(!d.has("conns"));
//ERR_FAIL_COND( !d.has("path"));
- int version=1;
+ int version = 1;
if (d.has("version"))
- version=d["version"];
+ version = d["version"];
- if (version>PACK_VERSION) {
+ if (version > PACK_VERSION) {
ERR_EXPLAIN("Save format version too new!");
ERR_FAIL();
}
@@ -1190,19 +1134,19 @@ void SceneState::set_bundled_scene(const Dictionary& d) {
int namecount = snames.size();
names.resize(namecount);
- PoolVector<String>::Read r =snames.read();
- for(int i=0;i<names.size();i++)
- names[i]=r[i];
+ PoolVector<String>::Read r = snames.read();
+ for (int i = 0; i < names.size(); i++)
+ names[i] = r[i];
}
Array svariants = d["variants"];
if (svariants.size()) {
- int varcount=svariants.size();
+ int varcount = svariants.size();
variants.resize(varcount);
- for(int i=0;i<varcount;i++) {
+ for (int i = 0; i < varcount; i++) {
- variants[i]=svariants[i];
+ variants[i] = svariants[i];
}
} else {
@@ -1210,83 +1154,80 @@ void SceneState::set_bundled_scene(const Dictionary& d) {
}
nodes.resize(d["node_count"]);
- int nc=nodes.size();
+ int nc = nodes.size();
if (nc) {
PoolVector<int> snodes = d["nodes"];
PoolVector<int>::Read r = snodes.read();
- int idx=0;
- for(int i=0;i<nc;i++) {
+ int idx = 0;
+ for (int i = 0; i < nc; i++) {
NodeData &nd = nodes[i];
- nd.parent=r[idx++];
- nd.owner=r[idx++];
- nd.type=r[idx++];
- nd.name=r[idx++];
- nd.instance=r[idx++];
+ nd.parent = r[idx++];
+ nd.owner = r[idx++];
+ nd.type = r[idx++];
+ nd.name = r[idx++];
+ nd.instance = r[idx++];
nd.properties.resize(r[idx++]);
- for(int j=0;j<nd.properties.size();j++) {
+ for (int j = 0; j < nd.properties.size(); j++) {
- nd.properties[j].name=r[idx++];
- nd.properties[j].value=r[idx++];
+ nd.properties[j].name = r[idx++];
+ nd.properties[j].value = r[idx++];
}
nd.groups.resize(r[idx++]);
- for(int j=0;j<nd.groups.size();j++) {
+ for (int j = 0; j < nd.groups.size(); j++) {
- nd.groups[j]=r[idx++];
+ nd.groups[j] = r[idx++];
}
}
-
}
connections.resize(d["conn_count"]);
- int cc=connections.size();
+ int cc = connections.size();
if (cc) {
PoolVector<int> sconns = d["conns"];
PoolVector<int>::Read r = sconns.read();
- int idx=0;
- for(int i=0;i<cc;i++) {
+ int idx = 0;
+ for (int i = 0; i < cc; i++) {
ConnectionData &cd = connections[i];
- cd.from=r[idx++];
- cd.to=r[idx++];
- cd.signal=r[idx++];
- cd.method=r[idx++];
- cd.flags=r[idx++];
+ cd.from = r[idx++];
+ cd.to = r[idx++];
+ cd.signal = r[idx++];
+ cd.method = r[idx++];
+ cd.flags = r[idx++];
cd.binds.resize(r[idx++]);
- for(int j=0;j<cd.binds.size();j++) {
+ for (int j = 0; j < cd.binds.size(); j++) {
- cd.binds[j]=r[idx++];
+ cd.binds[j] = r[idx++];
}
}
-
}
Array np;
if (d.has("node_paths")) {
- np=d["node_paths"];
+ np = d["node_paths"];
}
node_paths.resize(np.size());
- for(int i=0;i<np.size();i++) {
- node_paths[i]=np[i];
+ for (int i = 0; i < np.size(); i++) {
+ node_paths[i] = np[i];
}
Array ei;
if (d.has("editable_instances")) {
- ei=d["editable_instances"];
+ ei = d["editable_instances"];
}
if (d.has("base_scene")) {
- base_scene_idx=d["base_scene"];
+ base_scene_idx = d["base_scene"];
}
editable_instances.resize(ei.size());
- for(int i=0;i<editable_instances.size();i++) {
- editable_instances[i]=ei[i];
+ for (int i = 0; i < editable_instances.size(); i++) {
+ editable_instances[i] = ei[i];
}
//path=d["path"];
-
}
Dictionary SceneState::get_bundled_scene() const {
@@ -1296,85 +1237,82 @@ Dictionary SceneState::get_bundled_scene() const {
if (names.size()) {
- PoolVector<String>::Write r=rnames.write();
+ PoolVector<String>::Write r = rnames.write();
- for(int i=0;i<names.size();i++)
- r[i]=names[i];
+ for (int i = 0; i < names.size(); i++)
+ r[i] = names[i];
}
Dictionary d;
- d["names"]=rnames;
- d["variants"]=variants;
+ d["names"] = rnames;
+ d["variants"] = variants;
Vector<int> rnodes;
- d["node_count"]=nodes.size();
+ d["node_count"] = nodes.size();
- for(int i=0;i<nodes.size();i++) {
+ for (int i = 0; i < nodes.size(); i++) {
- const NodeData &nd=nodes[i];
+ const NodeData &nd = nodes[i];
rnodes.push_back(nd.parent);
rnodes.push_back(nd.owner);
rnodes.push_back(nd.type);
rnodes.push_back(nd.name);
rnodes.push_back(nd.instance);
rnodes.push_back(nd.properties.size());
- for(int j=0;j<nd.properties.size();j++) {
+ for (int j = 0; j < nd.properties.size(); j++) {
rnodes.push_back(nd.properties[j].name);
rnodes.push_back(nd.properties[j].value);
}
rnodes.push_back(nd.groups.size());
- for(int j=0;j<nd.groups.size();j++) {
+ for (int j = 0; j < nd.groups.size(); j++) {
rnodes.push_back(nd.groups[j]);
}
}
- d["nodes"]=rnodes;
+ d["nodes"] = rnodes;
Vector<int> rconns;
- d["conn_count"]=connections.size();
+ d["conn_count"] = connections.size();
- for(int i=0;i<connections.size();i++) {
+ for (int i = 0; i < connections.size(); i++) {
- const ConnectionData &cd=connections[i];
+ const ConnectionData &cd = connections[i];
rconns.push_back(cd.from);
rconns.push_back(cd.to);
rconns.push_back(cd.signal);
rconns.push_back(cd.method);
rconns.push_back(cd.flags);
rconns.push_back(cd.binds.size());
- for(int j=0;j<cd.binds.size();j++)
+ for (int j = 0; j < cd.binds.size(); j++)
rconns.push_back(cd.binds[j]);
-
}
- d["conns"]=rconns;
+ d["conns"] = rconns;
Array rnode_paths;
rnode_paths.resize(node_paths.size());
- for(int i=0;i<node_paths.size();i++) {
- rnode_paths[i]=node_paths[i];
+ for (int i = 0; i < node_paths.size(); i++) {
+ rnode_paths[i] = node_paths[i];
}
- d["node_paths"]=rnode_paths;
+ d["node_paths"] = rnode_paths;
Array reditable_instances;
reditable_instances.resize(editable_instances.size());
- for(int i=0;i<editable_instances.size();i++) {
- reditable_instances[i]=editable_instances[i];
+ for (int i = 0; i < editable_instances.size(); i++) {
+ reditable_instances[i] = editable_instances[i];
}
- d["editable_instances"]=reditable_instances;
- if (base_scene_idx>=0) {
- d["base_scene"]=base_scene_idx;
+ d["editable_instances"] = reditable_instances;
+ if (base_scene_idx >= 0) {
+ d["base_scene"] = base_scene_idx;
}
- d["version"]=PACK_VERSION;
+ d["version"] = PACK_VERSION;
//d["path"]=path;
return d;
-
-
}
int SceneState::get_node_count() const {
@@ -1384,76 +1322,68 @@ int SceneState::get_node_count() const {
StringName SceneState::get_node_type(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName());
- if (nodes[p_idx].type==TYPE_INSTANCED)
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
+ if (nodes[p_idx].type == TYPE_INSTANCED)
return StringName();
return names[nodes[p_idx].type];
}
StringName SceneState::get_node_name(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName());
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
return names[nodes[p_idx].name];
}
-
bool SceneState::is_node_instance_placeholder(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),false);
-
- return nodes[p_idx].instance>=0 && nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER;
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), false);
+ return nodes[p_idx].instance >= 0 && nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER;
}
Ref<PackedScene> SceneState::get_node_instance(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),Ref<PackedScene>());
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), Ref<PackedScene>());
- if (nodes[p_idx].instance>=0) {
- if (nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER)
+ if (nodes[p_idx].instance >= 0) {
+ if (nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER)
return Ref<PackedScene>();
else
- return variants[nodes[p_idx].instance&FLAG_MASK];
- } else if (nodes[p_idx].parent<0 || nodes[p_idx].parent==NO_PARENT_SAVED) {
+ return variants[nodes[p_idx].instance & FLAG_MASK];
+ } else if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
- if (base_scene_idx>=0) {
+ if (base_scene_idx >= 0) {
return variants[base_scene_idx];
}
}
-
-
return Ref<PackedScene>();
-
-
}
String SceneState::get_node_instance_placeholder(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),String());
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), String());
- if (nodes[p_idx].instance>=0 && nodes[p_idx].instance&FLAG_INSTANCE_IS_PLACEHOLDER) {
- return variants[nodes[p_idx].instance&FLAG_MASK];
+ if (nodes[p_idx].instance >= 0 && nodes[p_idx].instance & FLAG_INSTANCE_IS_PLACEHOLDER) {
+ return variants[nodes[p_idx].instance & FLAG_MASK];
}
return String();
-
}
-Vector<StringName> SceneState::get_node_groups(int p_idx) const{
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),Vector<StringName>());
+Vector<StringName> SceneState::get_node_groups(int p_idx) const {
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), Vector<StringName>());
Vector<StringName> groups;
- for(int i=0;i<nodes[p_idx].groups.size();i++) {
+ for (int i = 0; i < nodes[p_idx].groups.size(); i++) {
groups.push_back(names[nodes[p_idx].groups[i]]);
}
return groups;
}
+NodePath SceneState::get_node_path(int p_idx, bool p_for_parent) const {
-NodePath SceneState::get_node_path(int p_idx,bool p_for_parent) const {
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),NodePath());
-
- if (nodes[p_idx].parent<0 || nodes[p_idx].parent==NO_PARENT_SAVED) {
+ if (nodes[p_idx].parent < 0 || nodes[p_idx].parent == NO_PARENT_SAVED) {
if (p_for_parent) {
return NodePath();
} else {
@@ -1463,67 +1393,63 @@ NodePath SceneState::get_node_path(int p_idx,bool p_for_parent) const {
Vector<StringName> sub_path;
NodePath base_path;
- int nidx=p_idx;
- while(true) {
- if (nodes[nidx].parent==NO_PARENT_SAVED || nodes[nidx].parent<0) {
+ int nidx = p_idx;
+ while (true) {
+ if (nodes[nidx].parent == NO_PARENT_SAVED || nodes[nidx].parent < 0) {
- sub_path.insert(0,".");
+ sub_path.insert(0, ".");
break;
}
- if (!p_for_parent || p_idx!=nidx) {
- sub_path.insert(0,names[nodes[nidx].name]);
+ if (!p_for_parent || p_idx != nidx) {
+ sub_path.insert(0, names[nodes[nidx].name]);
}
- if (nodes[nidx].parent&FLAG_ID_IS_PATH) {
- base_path=node_paths[nodes[nidx].parent&FLAG_MASK];
+ if (nodes[nidx].parent & FLAG_ID_IS_PATH) {
+ base_path = node_paths[nodes[nidx].parent & FLAG_MASK];
break;
} else {
- nidx=nodes[nidx].parent&FLAG_MASK;
+ nidx = nodes[nidx].parent & FLAG_MASK;
}
}
- for(int i=base_path.get_name_count()-1;i>=0;i--) {
- sub_path.insert(0,base_path.get_name(i));
+ for (int i = base_path.get_name_count() - 1; i >= 0; i--) {
+ sub_path.insert(0, base_path.get_name(i));
}
if (sub_path.empty()) {
return NodePath(".");
}
- return NodePath(sub_path,false);
-
+ return NodePath(sub_path, false);
}
int SceneState::get_node_property_count(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),-1);
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), -1);
return nodes[p_idx].properties.size();
-
}
-StringName SceneState::get_node_property_name(int p_idx,int p_prop) const{
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),StringName());
- ERR_FAIL_INDEX_V(p_prop,nodes[p_idx].properties.size(),StringName());
+StringName SceneState::get_node_property_name(int p_idx, int p_prop) const {
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), StringName());
+ ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), StringName());
return names[nodes[p_idx].properties[p_prop].name];
-
}
-Variant SceneState::get_node_property_value(int p_idx,int p_prop) const{
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),Variant());
- ERR_FAIL_INDEX_V(p_prop,nodes[p_idx].properties.size(),Variant());
+Variant SceneState::get_node_property_value(int p_idx, int p_prop) const {
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), Variant());
+ ERR_FAIL_INDEX_V(p_prop, nodes[p_idx].properties.size(), Variant());
return variants[nodes[p_idx].properties[p_prop].value];
}
-
NodePath SceneState::get_node_owner_path(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,nodes.size(),NodePath());
- if (nodes[p_idx].owner<0 || nodes[p_idx].owner==NO_PARENT_SAVED)
+ ERR_FAIL_INDEX_V(p_idx, nodes.size(), NodePath());
+ if (nodes[p_idx].owner < 0 || nodes[p_idx].owner == NO_PARENT_SAVED)
return NodePath(); //root likely
- if (nodes[p_idx].owner&FLAG_ID_IS_PATH) {
- return node_paths[nodes[p_idx].owner&FLAG_MASK];
+ if (nodes[p_idx].owner & FLAG_ID_IS_PATH) {
+ return node_paths[nodes[p_idx].owner & FLAG_MASK];
} else {
- return get_node_path(nodes[p_idx].owner&FLAG_MASK);
+ return get_node_path(nodes[p_idx].owner & FLAG_MASK);
}
}
@@ -1531,82 +1457,77 @@ int SceneState::get_connection_count() const {
return connections.size();
}
-NodePath SceneState::get_connection_source(int p_idx) const{
+NodePath SceneState::get_connection_source(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,connections.size(),NodePath());
- if (connections[p_idx].from&FLAG_ID_IS_PATH) {
- return node_paths[connections[p_idx].from&FLAG_MASK];
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
+ if (connections[p_idx].from & FLAG_ID_IS_PATH) {
+ return node_paths[connections[p_idx].from & FLAG_MASK];
} else {
- return get_node_path(connections[p_idx].from&FLAG_MASK);
+ return get_node_path(connections[p_idx].from & FLAG_MASK);
}
-
}
-StringName SceneState::get_connection_signal(int p_idx) const{
+StringName SceneState::get_connection_signal(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,connections.size(),StringName());
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
return names[connections[p_idx].signal];
-
}
-NodePath SceneState::get_connection_target(int p_idx) const{
+NodePath SceneState::get_connection_target(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,connections.size(),NodePath());
- if (connections[p_idx].to&FLAG_ID_IS_PATH) {
- return node_paths[connections[p_idx].to&FLAG_MASK];
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), NodePath());
+ if (connections[p_idx].to & FLAG_ID_IS_PATH) {
+ return node_paths[connections[p_idx].to & FLAG_MASK];
} else {
- return get_node_path(connections[p_idx].to&FLAG_MASK);
+ return get_node_path(connections[p_idx].to & FLAG_MASK);
}
-
}
-StringName SceneState::get_connection_method(int p_idx) const{
+StringName SceneState::get_connection_method(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,connections.size(),StringName());
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), StringName());
return names[connections[p_idx].method];
-
}
+int SceneState::get_connection_flags(int p_idx) const {
-int SceneState::get_connection_flags(int p_idx) const{
-
- ERR_FAIL_INDEX_V(p_idx,connections.size(),-1);
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), -1);
return connections[p_idx].flags;
}
Array SceneState::get_connection_binds(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,connections.size(),Array());
+ ERR_FAIL_INDEX_V(p_idx, connections.size(), Array());
Array binds;
- for(int i=0;i<connections[p_idx].binds.size();i++) {
+ for (int i = 0; i < connections[p_idx].binds.size(); i++) {
binds.push_back(variants[connections[p_idx].binds[i]]);
}
return binds;
}
-bool SceneState::has_connection(const NodePath& p_node_from, const StringName& p_signal, const NodePath& p_node_to, const StringName& p_method) const {
+bool SceneState::has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method) const {
- for(int i=0;i<connections.size();i++) {
+ for (int i = 0; i < connections.size(); i++) {
const ConnectionData &c = connections[i];
NodePath np_from;
- if (c.from&FLAG_ID_IS_PATH) {
- np_from=node_paths[c.from&FLAG_MASK];
+ if (c.from & FLAG_ID_IS_PATH) {
+ np_from = node_paths[c.from & FLAG_MASK];
} else {
- np_from=get_node_path(c.from);
+ np_from = get_node_path(c.from);
}
NodePath np_to;
- if (c.to&FLAG_ID_IS_PATH) {
- np_to=node_paths[c.to&FLAG_MASK];
+ if (c.to & FLAG_ID_IS_PATH) {
+ np_to = node_paths[c.to & FLAG_MASK];
} else {
- np_to=get_node_path(c.to);
+ np_to = get_node_path(c.to);
}
- StringName sn_signal=names[c.signal];
- StringName sn_method=names[c.method];
+ StringName sn_signal = names[c.signal];
+ StringName sn_method = names[c.method];
- if (np_from==p_node_from && sn_signal==p_signal && np_to==p_node_to && sn_method==p_method) {
+ if (np_from == p_node_from && sn_signal == p_signal && np_to == p_node_to && sn_method == p_method) {
return true;
}
}
@@ -1619,88 +1540,86 @@ Vector<NodePath> SceneState::get_editable_instances() const {
}
//add
-int SceneState::add_name(const StringName& p_name) {
+int SceneState::add_name(const StringName &p_name) {
names.push_back(p_name);
- return names.size()-1;
+ return names.size() - 1;
}
-int SceneState::find_name(const StringName& p_name) const {
+int SceneState::find_name(const StringName &p_name) const {
- for(int i=0;i<names.size();i++) {
- if (names[i]==p_name)
+ for (int i = 0; i < names.size(); i++) {
+ if (names[i] == p_name)
return i;
}
return -1;
}
-int SceneState::add_value(const Variant& p_value) {
+int SceneState::add_value(const Variant &p_value) {
variants.push_back(p_value);
- return variants.size()-1;
+ return variants.size() - 1;
}
-int SceneState::add_node_path(const NodePath& p_path){
+int SceneState::add_node_path(const NodePath &p_path) {
node_paths.push_back(p_path);
- return (node_paths.size()-1)|FLAG_ID_IS_PATH;
+ return (node_paths.size() - 1) | FLAG_ID_IS_PATH;
}
-int SceneState::add_node(int p_parent,int p_owner,int p_type,int p_name, int p_instance){
+int SceneState::add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance) {
NodeData nd;
- nd.parent=p_parent;
- nd.owner=p_owner;
- nd.type=p_type;
- nd.name=p_name;
- nd.instance=p_instance;
+ nd.parent = p_parent;
+ nd.owner = p_owner;
+ nd.type = p_type;
+ nd.name = p_name;
+ nd.instance = p_instance;
nodes.push_back(nd);
- return nodes.size()-1;
+ return nodes.size() - 1;
}
-void SceneState::add_node_property(int p_node,int p_name,int p_value){
+void SceneState::add_node_property(int p_node, int p_name, int p_value) {
- ERR_FAIL_INDEX(p_node,nodes.size());
- ERR_FAIL_INDEX(p_name,names.size());
- ERR_FAIL_INDEX(p_value,variants.size());
+ ERR_FAIL_INDEX(p_node, nodes.size());
+ ERR_FAIL_INDEX(p_name, names.size());
+ ERR_FAIL_INDEX(p_value, variants.size());
NodeData::Property prop;
- prop.name=p_name;
- prop.value=p_value;
+ prop.name = p_name;
+ prop.value = p_value;
nodes[p_node].properties.push_back(prop);
}
-void SceneState::add_node_group(int p_node,int p_group){
+void SceneState::add_node_group(int p_node, int p_group) {
- ERR_FAIL_INDEX(p_node,nodes.size());
- ERR_FAIL_INDEX(p_group,names.size());
+ ERR_FAIL_INDEX(p_node, nodes.size());
+ ERR_FAIL_INDEX(p_group, names.size());
nodes[p_node].groups.push_back(p_group);
-
}
-void SceneState::set_base_scene(int p_idx){
+void SceneState::set_base_scene(int p_idx) {
- ERR_FAIL_INDEX(p_idx,variants.size());
- base_scene_idx=p_idx;
+ ERR_FAIL_INDEX(p_idx, variants.size());
+ base_scene_idx = p_idx;
}
-void SceneState::add_connection(int p_from,int p_to, int p_signal, int p_method, int p_flags,const Vector<int>& p_binds){
+void SceneState::add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, const Vector<int> &p_binds) {
- ERR_FAIL_INDEX(p_signal,names.size());
- ERR_FAIL_INDEX(p_method,names.size());
+ ERR_FAIL_INDEX(p_signal, names.size());
+ ERR_FAIL_INDEX(p_method, names.size());
- for(int i=0;i<p_binds.size();i++) {
- ERR_FAIL_INDEX(p_binds[i],variants.size());
+ for (int i = 0; i < p_binds.size(); i++) {
+ ERR_FAIL_INDEX(p_binds[i], variants.size());
}
ConnectionData c;
- c.from=p_from;
- c.to=p_to;
- c.signal=p_signal;
- c.method=p_method;
- c.flags=p_flags;
- c.binds=p_binds;
+ c.from = p_from;
+ c.to = p_to;
+ c.signal = p_signal;
+ c.method = p_method;
+ c.flags = p_flags;
+ c.binds = p_binds;
connections.push_back(c);
-
}
-void SceneState::add_editable_instance(const NodePath& p_path){
+void SceneState::add_editable_instance(const NodePath &p_path) {
editable_instances.push_back(p_path);
}
@@ -1710,7 +1629,7 @@ PoolVector<String> SceneState::_get_node_groups(int p_idx) const {
Vector<StringName> groups = get_node_groups(p_idx);
PoolVector<String> ret;
- for(int i=0;i<groups.size();i++)
+ for (int i = 0; i < groups.size(); i++)
ret.push_back(groups[i]);
return ret;
@@ -1720,43 +1639,40 @@ void SceneState::_bind_methods() {
//unbuild API
- ClassDB::bind_method(D_METHOD("get_node_count"),&SceneState::get_node_count);
- ClassDB::bind_method(D_METHOD("get_node_type","idx"),&SceneState::get_node_type);
- ClassDB::bind_method(D_METHOD("get_node_name","idx"),&SceneState::get_node_name);
- ClassDB::bind_method(D_METHOD("get_node_path","idx","for_parent"),&SceneState::get_node_path,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("get_node_owner_path","idx"),&SceneState::get_node_owner_path);
- ClassDB::bind_method(D_METHOD("is_node_instance_placeholder","idx"),&SceneState::is_node_instance_placeholder);
- ClassDB::bind_method(D_METHOD("get_node_instance_placeholder","idx"),&SceneState::get_node_instance_placeholder);
- ClassDB::bind_method(D_METHOD("get_node_instance:PackedScene","idx"),&SceneState::get_node_instance);
- ClassDB::bind_method(D_METHOD("get_node_groups","idx"),&SceneState::_get_node_groups);
- ClassDB::bind_method(D_METHOD("get_node_property_count","idx"),&SceneState::get_node_property_count);
- ClassDB::bind_method(D_METHOD("get_node_property_name","idx","prop_idx"),&SceneState::get_node_property_name);
- ClassDB::bind_method(D_METHOD("get_node_property_value","idx","prop_idx"),&SceneState::get_node_property_value);
- ClassDB::bind_method(D_METHOD("get_connection_count"),&SceneState::get_connection_count);
- ClassDB::bind_method(D_METHOD("get_connection_source","idx"),&SceneState::get_connection_source);
- ClassDB::bind_method(D_METHOD("get_connection_signal","idx"),&SceneState::get_connection_signal);
- ClassDB::bind_method(D_METHOD("get_connection_target","idx"),&SceneState::get_connection_target);
- ClassDB::bind_method(D_METHOD("get_connection_method","idx"),&SceneState::get_connection_method);
- ClassDB::bind_method(D_METHOD("get_connection_flags","idx"),&SceneState::get_connection_flags);
- ClassDB::bind_method(D_METHOD("get_connection_binds","idx"),&SceneState::get_connection_binds);
-
- BIND_CONSTANT( GEN_EDIT_STATE_DISABLED );
- BIND_CONSTANT( GEN_EDIT_STATE_INSTANCE );
- BIND_CONSTANT( GEN_EDIT_STATE_MAIN );
+ ClassDB::bind_method(D_METHOD("get_node_count"), &SceneState::get_node_count);
+ ClassDB::bind_method(D_METHOD("get_node_type", "idx"), &SceneState::get_node_type);
+ ClassDB::bind_method(D_METHOD("get_node_name", "idx"), &SceneState::get_node_name);
+ ClassDB::bind_method(D_METHOD("get_node_path", "idx", "for_parent"), &SceneState::get_node_path, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("get_node_owner_path", "idx"), &SceneState::get_node_owner_path);
+ ClassDB::bind_method(D_METHOD("is_node_instance_placeholder", "idx"), &SceneState::is_node_instance_placeholder);
+ ClassDB::bind_method(D_METHOD("get_node_instance_placeholder", "idx"), &SceneState::get_node_instance_placeholder);
+ ClassDB::bind_method(D_METHOD("get_node_instance:PackedScene", "idx"), &SceneState::get_node_instance);
+ ClassDB::bind_method(D_METHOD("get_node_groups", "idx"), &SceneState::_get_node_groups);
+ ClassDB::bind_method(D_METHOD("get_node_property_count", "idx"), &SceneState::get_node_property_count);
+ ClassDB::bind_method(D_METHOD("get_node_property_name", "idx", "prop_idx"), &SceneState::get_node_property_name);
+ ClassDB::bind_method(D_METHOD("get_node_property_value", "idx", "prop_idx"), &SceneState::get_node_property_value);
+ ClassDB::bind_method(D_METHOD("get_connection_count"), &SceneState::get_connection_count);
+ ClassDB::bind_method(D_METHOD("get_connection_source", "idx"), &SceneState::get_connection_source);
+ ClassDB::bind_method(D_METHOD("get_connection_signal", "idx"), &SceneState::get_connection_signal);
+ ClassDB::bind_method(D_METHOD("get_connection_target", "idx"), &SceneState::get_connection_target);
+ ClassDB::bind_method(D_METHOD("get_connection_method", "idx"), &SceneState::get_connection_method);
+ ClassDB::bind_method(D_METHOD("get_connection_flags", "idx"), &SceneState::get_connection_flags);
+ ClassDB::bind_method(D_METHOD("get_connection_binds", "idx"), &SceneState::get_connection_binds);
+
+ BIND_CONSTANT(GEN_EDIT_STATE_DISABLED);
+ BIND_CONSTANT(GEN_EDIT_STATE_INSTANCE);
+ BIND_CONSTANT(GEN_EDIT_STATE_MAIN);
}
SceneState::SceneState() {
- base_scene_idx=-1;
- last_modified_time=0;
+ base_scene_idx = -1;
+ last_modified_time = 0;
}
-
////////////////
-
-
-void PackedScene::_set_bundled_scene(const Dictionary& d) {
+void PackedScene::_set_bundled_scene(const Dictionary &d) {
state->set_bundled_scene(d);
}
@@ -1766,7 +1682,6 @@ Dictionary PackedScene::_get_bundled_scene() const {
return state->get_bundled_scene();
}
-
Error PackedScene::pack(Node *p_scene) {
return state->pack(p_scene);
@@ -1785,9 +1700,9 @@ bool PackedScene::can_instance() const {
Node *PackedScene::instance(GenEditState p_edit_state) const {
#ifndef TOOLS_ENABLED
- if (p_edit_state!=GEN_EDIT_STATE_DISABLED) {
+ if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
ERR_EXPLAIN("Edit state is only for editors, does not work without tools compiled");
- ERR_FAIL_COND_V(p_edit_state!=GEN_EDIT_STATE_DISABLED,NULL);
+ ERR_FAIL_COND_V(p_edit_state != GEN_EDIT_STATE_DISABLED, NULL);
}
#endif
@@ -1795,14 +1710,13 @@ Node *PackedScene::instance(GenEditState p_edit_state) const {
if (!s)
return NULL;
- if (p_edit_state!=GEN_EDIT_STATE_DISABLED) {
+ if (p_edit_state != GEN_EDIT_STATE_DISABLED) {
s->set_scene_instance_state(state);
}
- if (get_path()!="" && get_path().find("::")==-1)
+ if (get_path() != "" && get_path().find("::") == -1)
s->set_filename(get_path());
-
s->notification(Node::NOTIFICATION_INSTANCED);
return s;
@@ -1810,17 +1724,16 @@ Node *PackedScene::instance(GenEditState p_edit_state) const {
void PackedScene::replace_state(Ref<SceneState> p_by) {
- state=p_by;
+ state = p_by;
state->set_path(get_path());
#ifdef TOOLS_ENABLED
state->set_last_modified_time(get_last_modified_time());
#endif
-
}
void PackedScene::recreate_state() {
- state = Ref<SceneState>( memnew( SceneState ));
+ state = Ref<SceneState>(memnew(SceneState));
state->set_path(get_path());
#ifdef TOOLS_ENABLED
state->set_last_modified_time(get_last_modified_time());
@@ -1832,32 +1745,29 @@ Ref<SceneState> PackedScene::get_state() {
return state;
}
-void PackedScene::set_path(const String& p_path,bool p_take_over) {
+void PackedScene::set_path(const String &p_path, bool p_take_over) {
state->set_path(p_path);
- Resource::set_path(p_path,p_take_over);
+ Resource::set_path(p_path, p_take_over);
}
-
void PackedScene::_bind_methods() {
- ClassDB::bind_method(D_METHOD("pack","path:Node"),&PackedScene::pack);
- ClassDB::bind_method(D_METHOD("instance:Node","edit_state"),&PackedScene::instance,DEFVAL(false));
- ClassDB::bind_method(D_METHOD("can_instance"),&PackedScene::can_instance);
- ClassDB::bind_method(D_METHOD("_set_bundled_scene"),&PackedScene::_set_bundled_scene);
- ClassDB::bind_method(D_METHOD("_get_bundled_scene"),&PackedScene::_get_bundled_scene);
- ClassDB::bind_method(D_METHOD("get_state:SceneState"),&PackedScene::get_state);
-
- ADD_PROPERTY( PropertyInfo(Variant::DICTIONARY,"_bundled"),"_set_bundled_scene","_get_bundled_scene");
+ ClassDB::bind_method(D_METHOD("pack", "path:Node"), &PackedScene::pack);
+ ClassDB::bind_method(D_METHOD("instance:Node", "edit_state"), &PackedScene::instance, DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("can_instance"), &PackedScene::can_instance);
+ ClassDB::bind_method(D_METHOD("_set_bundled_scene"), &PackedScene::_set_bundled_scene);
+ ClassDB::bind_method(D_METHOD("_get_bundled_scene"), &PackedScene::_get_bundled_scene);
+ ClassDB::bind_method(D_METHOD("get_state:SceneState"), &PackedScene::get_state);
- BIND_CONSTANT( GEN_EDIT_STATE_DISABLED );
- BIND_CONSTANT( GEN_EDIT_STATE_INSTANCE );
- BIND_CONSTANT( GEN_EDIT_STATE_MAIN );
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_bundled"), "_set_bundled_scene", "_get_bundled_scene");
+ BIND_CONSTANT(GEN_EDIT_STATE_DISABLED);
+ BIND_CONSTANT(GEN_EDIT_STATE_INSTANCE);
+ BIND_CONSTANT(GEN_EDIT_STATE_MAIN);
}
PackedScene::PackedScene() {
- state = Ref<SceneState>( memnew( SceneState ));
-
+ state = Ref<SceneState>(memnew(SceneState));
}
diff --git a/scene/resources/packed_scene.h b/scene/resources/packed_scene.h
index 4a3841abe9..5fa54413a8 100644
--- a/scene/resources/packed_scene.h
+++ b/scene/resources/packed_scene.h
@@ -32,23 +32,21 @@
#include "resource.h"
#include "scene/main/node.h"
-
class SceneState : public Reference {
- GDCLASS( SceneState, Reference );
-
+ GDCLASS(SceneState, Reference);
Vector<StringName> names;
Vector<Variant> variants;
Vector<NodePath> node_paths;
Vector<NodePath> editable_instances;
- mutable HashMap<NodePath,int> node_path_cache;
- mutable Map<int,int> base_scene_node_remap;
+ mutable HashMap<NodePath, int> node_path_cache;
+ mutable Map<int, int> base_scene_node_remap;
int base_scene_idx;
enum {
- NO_PARENT_SAVED=0x7FFFFFFF,
+ NO_PARENT_SAVED = 0x7FFFFFFF,
};
struct NodeData {
@@ -67,13 +65,12 @@ class SceneState : public Reference {
Vector<Property> properties;
Vector<int> groups;
-
};
struct PackState {
Ref<SceneState> state;
int node;
- PackState() { node=-1; }
+ PackState() { node = -1; }
};
Vector<NodeData> nodes;
@@ -90,9 +87,8 @@ class SceneState : public Reference {
Vector<ConnectionData> connections;
-
- Error _parse_node(Node *p_owner,Node *p_node,int p_parent_idx, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map);
- Error _parse_connections(Node *p_owner,Node *p_node, Map<StringName,int> &name_map,HashMap<Variant,int,VariantHasher,VariantComparator> &variant_map,Map<Node*,int> &node_map,Map<Node*,int> &nodepath_map);
+ Error _parse_node(Node *p_owner, Node *p_node, int p_parent_idx, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map);
+ Error _parse_connections(Node *p_owner, Node *p_node, Map<StringName, int> &name_map, HashMap<Variant, int, VariantHasher, VariantComparator> &variant_map, Map<Node *, int> &node_map, Map<Node *, int> &nodepath_map);
String path;
@@ -105,16 +101,14 @@ class SceneState : public Reference {
PoolVector<String> _get_node_groups(int p_idx) const;
protected:
-
static void _bind_methods();
public:
-
enum {
- FLAG_ID_IS_PATH=(1<<30),
- TYPE_INSTANCED=0x7FFFFFFF,
- FLAG_INSTANCE_IS_PLACEHOLDER=(1<<30),
- FLAG_MASK=(1<<24)-1,
+ FLAG_ID_IS_PATH = (1 << 30),
+ TYPE_INSTANCED = 0x7FFFFFFF,
+ FLAG_INSTANCE_IS_PLACEHOLDER = (1 << 30),
+ FLAG_MASK = (1 << 24) - 1,
};
enum GenEditState {
@@ -125,13 +119,12 @@ public:
static void set_disable_placeholders(bool p_disable);
- int find_node_by_path(const NodePath& p_node) const;
- Variant get_property_value(int p_node,const StringName& p_property,bool &found) const;
- bool is_node_in_group(int p_node,const StringName& p_group) const;
- bool is_connection(int p_node,const StringName& p_signal,int p_to_node,const StringName& p_to_method) const;
-
+ int find_node_by_path(const NodePath &p_node) const;
+ Variant get_property_value(int p_node, const StringName &p_property, bool &found) const;
+ bool is_node_in_group(int p_node, const StringName &p_group) const;
+ bool is_connection(int p_node, const StringName &p_signal, int p_to_node, const StringName &p_to_method) const;
- void set_bundled_scene(const Dictionary& p_dictionary);
+ void set_bundled_scene(const Dictionary &p_dictionary);
Dictionary get_bundled_scene() const;
Error pack(Node *p_scene);
@@ -144,13 +137,12 @@ public:
bool can_instance() const;
Node *instance(GenEditState p_edit_state) const;
-
//unbuild API
int get_node_count() const;
StringName get_node_type(int p_idx) const;
StringName get_node_name(int p_idx) const;
- NodePath get_node_path(int p_idx,bool p_for_parent=false) const;
+ NodePath get_node_path(int p_idx, bool p_for_parent = false) const;
NodePath get_node_owner_path(int p_idx) const;
Ref<PackedScene> get_node_instance(int p_idx) const;
String get_node_instance_placeholder(int p_idx) const;
@@ -158,8 +150,8 @@ public:
Vector<StringName> get_node_groups(int p_idx) const;
int get_node_property_count(int p_idx) const;
- StringName get_node_property_name(int p_idx,int p_prop) const;
- Variant get_node_property_value(int p_idx,int p_prop) const;
+ StringName get_node_property_name(int p_idx, int p_prop) const;
+ Variant get_node_property_value(int p_idx, int p_prop) const;
int get_connection_count() const;
NodePath get_connection_source(int p_idx) const;
@@ -169,27 +161,26 @@ public:
int get_connection_flags(int p_idx) const;
Array get_connection_binds(int p_idx) const;
- bool has_connection(const NodePath &p_node_from, const StringName& p_signal, const NodePath &p_node_to, const StringName& p_method) const;
+ bool has_connection(const NodePath &p_node_from, const StringName &p_signal, const NodePath &p_node_to, const StringName &p_method) const;
Vector<NodePath> get_editable_instances() const;
//build API
- int add_name(const StringName& p_name);
- int find_name(const StringName& p_name) const;
- int add_value(const Variant& p_value);
- int add_node_path(const NodePath& p_path);
- int add_node(int p_parent,int p_owner,int p_type,int p_name, int p_instance);
- void add_node_property(int p_node,int p_name,int p_value);
- void add_node_group(int p_node,int p_group);
+ int add_name(const StringName &p_name);
+ int find_name(const StringName &p_name) const;
+ int add_value(const Variant &p_value);
+ int add_node_path(const NodePath &p_path);
+ int add_node(int p_parent, int p_owner, int p_type, int p_name, int p_instance);
+ void add_node_property(int p_node, int p_name, int p_value);
+ void add_node_group(int p_node, int p_group);
void set_base_scene(int p_idx);
- void add_connection(int p_from,int p_to, int p_signal, int p_method, int p_flags,const Vector<int>& p_binds);
- void add_editable_instance(const NodePath& p_path);
+ void add_connection(int p_from, int p_to, int p_signal, int p_method, int p_flags, const Vector<int> &p_binds);
+ void add_editable_instance(const NodePath &p_path);
- virtual void set_last_modified_time(uint64_t p_time) { last_modified_time=p_time; }
+ virtual void set_last_modified_time(uint64_t p_time) { last_modified_time = p_time; }
uint64_t get_last_modified_time() const { return last_modified_time; }
-
SceneState();
};
@@ -197,20 +188,19 @@ VARIANT_ENUM_CAST(SceneState::GenEditState)
class PackedScene : public Resource {
- GDCLASS(PackedScene, Resource );
+ GDCLASS(PackedScene, Resource);
RES_BASE_EXTENSION("scn");
Ref<SceneState> state;
- void _set_bundled_scene(const Dictionary& p_scene);
+ void _set_bundled_scene(const Dictionary &p_scene);
Dictionary _get_bundled_scene() const;
protected:
-
virtual bool editor_can_reload_from_file() { return false; } // this is handled by editor better
static void _bind_methods();
-public:
+public:
enum GenEditState {
GEN_EDIT_STATE_DISABLED,
GEN_EDIT_STATE_INSTANCE,
@@ -222,12 +212,12 @@ public:
void clear();
bool can_instance() const;
- Node *instance(GenEditState p_edit_state=GEN_EDIT_STATE_DISABLED) const;
+ Node *instance(GenEditState p_edit_state = GEN_EDIT_STATE_DISABLED) const;
void recreate_state();
void replace_state(Ref<SceneState> p_by);
- virtual void set_path(const String& p_path,bool p_take_over=false);
+ virtual void set_path(const String &p_path, bool p_take_over = false);
#ifdef TOOLS_ENABLED
virtual void set_last_modified_time(uint64_t p_time) { state->set_last_modified_time(p_time); }
@@ -235,7 +225,6 @@ public:
Ref<SceneState> get_state();
PackedScene();
-
};
VARIANT_ENUM_CAST(PackedScene::GenEditState)
diff --git a/scene/resources/plane_shape.cpp b/scene/resources/plane_shape.cpp
index f1bb6d60c0..e3535b1a63 100644
--- a/scene/resources/plane_shape.cpp
+++ b/scene/resources/plane_shape.cpp
@@ -38,11 +38,11 @@ Vector<Vector3> PlaneShape::_gen_debug_mesh_lines() {
Vector3 n1 = p.get_any_perpendicular_normal();
Vector3 n2 = p.normal.cross(n1).normalized();
- Vector3 pface[4]={
- p.normal*p.d+n1*10.0+n2*10.0,
- p.normal*p.d+n1*10.0+n2*-10.0,
- p.normal*p.d+n1*-10.0+n2*-10.0,
- p.normal*p.d+n1*-10.0+n2*10.0,
+ Vector3 pface[4] = {
+ p.normal * p.d + n1 * 10.0 + n2 * 10.0,
+ p.normal * p.d + n1 * 10.0 + n2 * -10.0,
+ p.normal * p.d + n1 * -10.0 + n2 * -10.0,
+ p.normal * p.d + n1 * -10.0 + n2 * 10.0,
};
points.push_back(pface[0]);
@@ -53,20 +53,20 @@ Vector<Vector3> PlaneShape::_gen_debug_mesh_lines() {
points.push_back(pface[3]);
points.push_back(pface[3]);
points.push_back(pface[0]);
- points.push_back(p.normal*p.d);
- points.push_back(p.normal*p.d+p.normal*3);
+ points.push_back(p.normal * p.d);
+ points.push_back(p.normal * p.d + p.normal * 3);
return points;
}
void PlaneShape::_update_shape() {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),plane);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), plane);
}
void PlaneShape::set_plane(Plane p_plane) {
- plane=p_plane;
+ plane = p_plane;
_update_shape();
notify_change_to_owners();
_change_notify("plane");
@@ -77,17 +77,16 @@ Plane PlaneShape::get_plane() const {
return plane;
}
-
void PlaneShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_plane","plane"),&PlaneShape::set_plane);
- ClassDB::bind_method(D_METHOD("get_plane"),&PlaneShape::get_plane);
-
- ADD_PROPERTY( PropertyInfo(Variant::PLANE,"plane"), "set_plane", "get_plane") ;
+ ClassDB::bind_method(D_METHOD("set_plane", "plane"), &PlaneShape::set_plane);
+ ClassDB::bind_method(D_METHOD("get_plane"), &PlaneShape::get_plane);
+ ADD_PROPERTY(PropertyInfo(Variant::PLANE, "plane"), "set_plane", "get_plane");
}
-PlaneShape::PlaneShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_PLANE)) {
+PlaneShape::PlaneShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_PLANE)) {
- set_plane(Plane(0,1,0,0));
+ set_plane(Plane(0, 1, 0, 0));
}
diff --git a/scene/resources/plane_shape.h b/scene/resources/plane_shape.h
index 88f3a04f05..899aad7e01 100644
--- a/scene/resources/plane_shape.h
+++ b/scene/resources/plane_shape.h
@@ -33,17 +33,16 @@
class PlaneShape : public Shape {
- GDCLASS(PlaneShape,Shape);
+ GDCLASS(PlaneShape, Shape);
Plane plane;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
+public:
void set_plane(Plane p_plane);
Plane get_plane() const;
diff --git a/scene/resources/polygon_path_finder.cpp b/scene/resources/polygon_path_finder.cpp
index 6dac8a9779..44ef828d02 100644
--- a/scene/resources/polygon_path_finder.cpp
+++ b/scene/resources/polygon_path_finder.cpp
@@ -29,107 +29,98 @@
#include "polygon_path_finder.h"
#include "geometry.h"
+bool PolygonPathFinder::_is_point_inside(const Vector2 &p_point) const {
-bool PolygonPathFinder::_is_point_inside(const Vector2& p_point) const {
+ int crosses = 0;
- int crosses=0;
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
-
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
-
-
- const Edge& e=E->get();
+ const Edge &e = E->get();
Vector2 a = points[e.points[0]].pos;
Vector2 b = points[e.points[1]].pos;
-
- if (Geometry::segment_intersects_segment_2d(a,b,p_point,outside_point,NULL)) {
+ if (Geometry::segment_intersects_segment_2d(a, b, p_point, outside_point, NULL)) {
crosses++;
}
}
- return crosses&1;
+ return crosses & 1;
}
-void PolygonPathFinder::setup(const Vector<Vector2>& p_points, const Vector<int>& p_connections) {
+void PolygonPathFinder::setup(const Vector<Vector2> &p_points, const Vector<int> &p_connections) {
-
- ERR_FAIL_COND(p_connections.size()&1);
+ ERR_FAIL_COND(p_connections.size() & 1);
points.clear();
edges.clear();
//insert points
- int point_count=p_points.size();
- points.resize(point_count+2);
- bounds=Rect2();
+ int point_count = p_points.size();
+ points.resize(point_count + 2);
+ bounds = Rect2();
- for(int i=0;i<p_points.size();i++) {
+ for (int i = 0; i < p_points.size(); i++) {
- points[i].pos=p_points[i];
- points[i].penalty=0;
+ points[i].pos = p_points[i];
+ points[i].penalty = 0;
- outside_point.x = i==0?p_points[0].x:(MAX( p_points[i].x, outside_point.x ));
- outside_point.y = i==0?p_points[0].y:(MAX( p_points[i].y, outside_point.y ));
+ outside_point.x = i == 0 ? p_points[0].x : (MAX(p_points[i].x, outside_point.x));
+ outside_point.y = i == 0 ? p_points[0].y : (MAX(p_points[i].y, outside_point.y));
- if (i==0) {
- bounds.pos=points[i].pos;
+ if (i == 0) {
+ bounds.pos = points[i].pos;
} else {
bounds.expand_to(points[i].pos);
}
}
- outside_point.x+=20.451+Math::randf()*10.2039;
- outside_point.y+=21.193+Math::randf()*12.5412;
+ outside_point.x += 20.451 + Math::randf() * 10.2039;
+ outside_point.y += 21.193 + Math::randf() * 12.5412;
//insert edges (which are also connetions)
- for(int i=0;i<p_connections.size();i+=2) {
+ for (int i = 0; i < p_connections.size(); i += 2) {
- Edge e(p_connections[i],p_connections[i+1]);
- ERR_FAIL_INDEX(e.points[0],point_count);
- ERR_FAIL_INDEX(e.points[1],point_count);
- points[p_connections[i]].connections.insert(p_connections[i+1]);
- points[p_connections[i+1]].connections.insert(p_connections[i]);
+ Edge e(p_connections[i], p_connections[i + 1]);
+ ERR_FAIL_INDEX(e.points[0], point_count);
+ ERR_FAIL_INDEX(e.points[1], point_count);
+ points[p_connections[i]].connections.insert(p_connections[i + 1]);
+ points[p_connections[i + 1]].connections.insert(p_connections[i]);
edges.insert(e);
}
-
//fill the remaining connections based on visibility
- for(int i=0;i<point_count;i++) {
+ for (int i = 0; i < point_count; i++) {
- for(int j=i+1;j<point_count;j++) {
+ for (int j = i + 1; j < point_count; j++) {
- if (edges.has(Edge(i,j)))
+ if (edges.has(Edge(i, j)))
continue; //if in edge ignore
- Vector2 from=points[i].pos;
- Vector2 to=points[j].pos;
+ Vector2 from = points[i].pos;
+ Vector2 to = points[j].pos;
- if (!_is_point_inside(from*0.5+to*0.5)) //connection between points in inside space
+ if (!_is_point_inside(from * 0.5 + to * 0.5)) //connection between points in inside space
continue;
- bool valid=true;
+ bool valid = true;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- const Edge& e=E->get();
- if (e.points[0]==i || e.points[1]==i || e.points[0]==j || e.points[1]==j )
+ const Edge &e = E->get();
+ if (e.points[0] == i || e.points[1] == i || e.points[0] == j || e.points[1] == j)
continue;
-
Vector2 a = points[e.points[0]].pos;
Vector2 b = points[e.points[1]].pos;
-
- if (Geometry::segment_intersects_segment_2d(a,b,from,to,NULL)) {
- valid=false;
+ if (Geometry::segment_intersects_segment_2d(a, b, from, to, NULL)) {
+ valid = false;
break;
}
-
}
if (valid) {
@@ -140,92 +131,86 @@ void PolygonPathFinder::setup(const Vector<Vector2>& p_points, const Vector<int>
}
}
-
-Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector2& p_to) {
+Vector<Vector2> PolygonPathFinder::find_path(const Vector2 &p_from, const Vector2 &p_to) {
Vector<Vector2> path;
- Vector2 from=p_from;
- Vector2 to=p_to;
- Edge ignore_from_edge(-1,-1);
- Edge ignore_to_edge(-1,-1);
+ Vector2 from = p_from;
+ Vector2 to = p_to;
+ Edge ignore_from_edge(-1, -1);
+ Edge ignore_to_edge(-1, -1);
if (!_is_point_inside(from)) {
- float closest_dist=1e20;
+ float closest_dist = 1e20;
Vector2 closest_point;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- const Edge& e=E->get();
- Vector2 seg[2]={
+ const Edge &e = E->get();
+ Vector2 seg[2] = {
points[e.points[0]].pos,
points[e.points[1]].pos
};
-
- Vector2 closest = Geometry::get_closest_point_to_segment_2d(from,seg);
+ Vector2 closest = Geometry::get_closest_point_to_segment_2d(from, seg);
float d = from.distance_squared_to(closest);
- if (d<closest_dist) {
- ignore_from_edge=E->get();
- closest_dist=d;
- closest_point=closest;
+ if (d < closest_dist) {
+ ignore_from_edge = E->get();
+ closest_dist = d;
+ closest_point = closest;
}
}
- from=closest_point;
+ from = closest_point;
};
-
if (!_is_point_inside(to)) {
- float closest_dist=1e20;
+ float closest_dist = 1e20;
Vector2 closest_point;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- const Edge& e=E->get();
- Vector2 seg[2]={
+ const Edge &e = E->get();
+ Vector2 seg[2] = {
points[e.points[0]].pos,
points[e.points[1]].pos
};
-
- Vector2 closest = Geometry::get_closest_point_to_segment_2d(to,seg);
+ Vector2 closest = Geometry::get_closest_point_to_segment_2d(to, seg);
float d = to.distance_squared_to(closest);
- if (d<closest_dist) {
- ignore_to_edge=E->get();
- closest_dist=d;
- closest_point=closest;
+ if (d < closest_dist) {
+ ignore_to_edge = E->get();
+ closest_dist = d;
+ closest_point = closest;
}
}
- to=closest_point;
+ to = closest_point;
};
//test direct connection
{
- bool can_see_eachother=true;
+ bool can_see_eachother = true;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- const Edge& e=E->get();
- if (e.points[0]==ignore_from_edge.points[0] && e.points[1]==ignore_from_edge.points[1])
+ const Edge &e = E->get();
+ if (e.points[0] == ignore_from_edge.points[0] && e.points[1] == ignore_from_edge.points[1])
continue;
- if (e.points[0]==ignore_to_edge.points[0] && e.points[1]==ignore_to_edge.points[1])
+ if (e.points[0] == ignore_to_edge.points[0] && e.points[1] == ignore_to_edge.points[1])
continue;
Vector2 a = points[e.points[0]].pos;
Vector2 b = points[e.points[1]].pos;
-
- if (Geometry::segment_intersects_segment_2d(a,b,from,to,NULL)) {
- can_see_eachother=false;
+ if (Geometry::segment_intersects_segment_2d(a, b, from, to, NULL)) {
+ can_see_eachother = false;
break;
}
-
}
if (can_see_eachother) {
@@ -238,85 +223,72 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector
//add to graph
- int aidx = points.size()-2;
- int bidx = points.size()-1;
- points[aidx].pos=from;
- points[bidx].pos=to;
- points[aidx].distance=0;
- points[bidx].distance=0;
- points[aidx].prev=-1;
- points[bidx].prev=-1;
- points[aidx].penalty=0;
- points[bidx].penalty=0;
-
-
-
- for(int i=0;i<points.size()-2;i++) {
-
-
- bool valid_a=true;
- bool valid_b=true;
- points[i].prev=-1;
- points[i].distance=0;
-
- if (!_is_point_inside(from*0.5+points[i].pos*0.5)) {
- valid_a=false;
-
+ int aidx = points.size() - 2;
+ int bidx = points.size() - 1;
+ points[aidx].pos = from;
+ points[bidx].pos = to;
+ points[aidx].distance = 0;
+ points[bidx].distance = 0;
+ points[aidx].prev = -1;
+ points[bidx].prev = -1;
+ points[aidx].penalty = 0;
+ points[bidx].penalty = 0;
+
+ for (int i = 0; i < points.size() - 2; i++) {
+
+ bool valid_a = true;
+ bool valid_b = true;
+ points[i].prev = -1;
+ points[i].distance = 0;
+
+ if (!_is_point_inside(from * 0.5 + points[i].pos * 0.5)) {
+ valid_a = false;
}
-
- if (!_is_point_inside(to*0.5+points[i].pos*0.5)) {
- valid_b=false;
-
+ if (!_is_point_inside(to * 0.5 + points[i].pos * 0.5)) {
+ valid_b = false;
}
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
-
- const Edge& e=E->get();
+ const Edge &e = E->get();
- if (e.points[0]==i || e.points[1]==i)
+ if (e.points[0] == i || e.points[1] == i)
continue;
-
Vector2 a = points[e.points[0]].pos;
Vector2 b = points[e.points[1]].pos;
if (valid_a) {
- if (e.points[0]!=ignore_from_edge.points[1] &&
- e.points[1]!=ignore_from_edge.points[1] &&
- e.points[0]!=ignore_from_edge.points[0] &&
- e.points[1]!=ignore_from_edge.points[0]) {
-
+ if (e.points[0] != ignore_from_edge.points[1] &&
+ e.points[1] != ignore_from_edge.points[1] &&
+ e.points[0] != ignore_from_edge.points[0] &&
+ e.points[1] != ignore_from_edge.points[0]) {
- if (Geometry::segment_intersects_segment_2d(a,b,from,points[i].pos,NULL)) {
- valid_a=false;
+ if (Geometry::segment_intersects_segment_2d(a, b, from, points[i].pos, NULL)) {
+ valid_a = false;
}
}
}
if (valid_b) {
- if (e.points[0]!=ignore_to_edge.points[1] &&
- e.points[1]!=ignore_to_edge.points[1] &&
- e.points[0]!=ignore_to_edge.points[0] &&
- e.points[1]!=ignore_to_edge.points[0]) {
-
+ if (e.points[0] != ignore_to_edge.points[1] &&
+ e.points[1] != ignore_to_edge.points[1] &&
+ e.points[0] != ignore_to_edge.points[0] &&
+ e.points[1] != ignore_to_edge.points[0]) {
- if (Geometry::segment_intersects_segment_2d(a,b,to,points[i].pos,NULL)) {
- valid_b=false;
+ if (Geometry::segment_intersects_segment_2d(a, b, to, points[i].pos, NULL)) {
+ valid_b = false;
}
}
}
if (!valid_a && !valid_b)
break;
-
-
}
-
if (valid_a) {
points[i].connections.insert(aidx);
points[aidx].connections.insert(i);
@@ -326,82 +298,76 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector
points[i].connections.insert(bidx);
points[bidx].connections.insert(i);
}
-
}
//solve graph
Set<int> open_list;
- points[aidx].distance=0;
- points[aidx].prev=aidx;
- for(Set<int>::Element *E=points[aidx].connections.front();E;E=E->next()) {
+ points[aidx].distance = 0;
+ points[aidx].prev = aidx;
+ for (Set<int>::Element *E = points[aidx].connections.front(); E; E = E->next()) {
open_list.insert(E->get());
- points[E->get()].distance=from.distance_to(points[E->get()].pos);
- points[E->get()].prev=aidx;
-
+ points[E->get()].distance = from.distance_to(points[E->get()].pos);
+ points[E->get()].prev = aidx;
}
+ bool found_route = false;
- bool found_route=false;
-
- while(true) {
+ while (true) {
- if (open_list.size()==0) {
+ if (open_list.size() == 0) {
printf("open list empty\n");
break;
}
//check open list
- int least_cost_point=-1;
- float least_cost=1e30;
+ int least_cost_point = -1;
+ float least_cost = 1e30;
//this could be faster (cache previous results)
- for (Set<int>::Element *E=open_list.front();E;E=E->next()) {
+ for (Set<int>::Element *E = open_list.front(); E; E = E->next()) {
- const Point& p =points[E->get()];
+ const Point &p = points[E->get()];
float cost = p.distance;
- cost+=p.pos.distance_to(to);
- cost+=p.penalty;
+ cost += p.pos.distance_to(to);
+ cost += p.penalty;
- if (cost<least_cost) {
+ if (cost < least_cost) {
- least_cost_point=E->get();
- least_cost=cost;
+ least_cost_point = E->get();
+ least_cost = cost;
}
}
-
Point &np = points[least_cost_point];
//open the neighbours for search
- for(Set<int>::Element *E=np.connections.front();E;E=E->next()) {
+ for (Set<int>::Element *E = np.connections.front(); E; E = E->next()) {
- Point& p =points[E->get()];
+ Point &p = points[E->get()];
float distance = np.pos.distance_to(p.pos) + np.distance;
- if (p.prev!=-1) {
+ if (p.prev != -1) {
//oh this was visited already, can we win the cost?
- if (p.distance>distance) {
+ if (p.distance > distance) {
- p.prev=least_cost_point; //reasign previous
- p.distance=distance;
+ p.prev = least_cost_point; //reasign previous
+ p.distance = distance;
}
} else {
//add to open neighbours
- p.prev=least_cost_point;
- p.distance=distance;
+ p.prev = least_cost_point;
+ p.distance = distance;
open_list.insert(E->get());
- if (E->get()==bidx) {
+ if (E->get() == bidx) {
//oh my reached end! stop algorithm
- found_route=true;
+ found_route = true;
break;
-
}
-
}
}
@@ -415,186 +381,179 @@ Vector<Vector2> PolygonPathFinder::find_path(const Vector2& p_from, const Vector
int at = bidx;
path.push_back(points[at].pos);
do {
- at=points[at].prev;
+ at = points[at].prev;
path.push_back(points[at].pos);
- } while (at!=aidx);
+ } while (at != aidx);
path.invert();
}
- for(int i=0;i<points.size()-2;i++) {
+ for (int i = 0; i < points.size() - 2; i++) {
points[i].connections.erase(aidx);
points[i].connections.erase(bidx);
- points[i].prev=-1;
- points[i].distance=0;
+ points[i].prev = -1;
+ points[i].distance = 0;
}
points[aidx].connections.clear();
- points[aidx].prev=-1;
- points[aidx].distance=0;
+ points[aidx].prev = -1;
+ points[aidx].distance = 0;
points[bidx].connections.clear();
- points[bidx].prev=-1;
- points[bidx].distance=0;
+ points[bidx].prev = -1;
+ points[bidx].distance = 0;
return path;
}
-void PolygonPathFinder::_set_data(const Dictionary& p_data) {
-
+void PolygonPathFinder::_set_data(const Dictionary &p_data) {
ERR_FAIL_COND(!p_data.has("points"));
ERR_FAIL_COND(!p_data.has("connections"));
ERR_FAIL_COND(!p_data.has("segments"));
ERR_FAIL_COND(!p_data.has("bounds"));
- PoolVector<Vector2> p=p_data["points"];
- Array c=p_data["connections"];
+ PoolVector<Vector2> p = p_data["points"];
+ Array c = p_data["connections"];
- ERR_FAIL_COND(c.size()!=p.size());
+ ERR_FAIL_COND(c.size() != p.size());
if (c.size())
return;
int pc = p.size();
- points.resize(pc+2);
+ points.resize(pc + 2);
- PoolVector<Vector2>::Read pr=p.read();
- for(int i=0;i<pc;i++) {
- points[i].pos=pr[i];
- PoolVector<int> con=c[i];
- PoolVector<int>::Read cr=con.read();
- int cc=con.size();
- for(int j=0;j<cc;j++) {
+ PoolVector<Vector2>::Read pr = p.read();
+ for (int i = 0; i < pc; i++) {
+ points[i].pos = pr[i];
+ PoolVector<int> con = c[i];
+ PoolVector<int>::Read cr = con.read();
+ int cc = con.size();
+ for (int j = 0; j < cc; j++) {
points[i].connections.insert(cr[j]);
}
-
}
if (p_data.has("penalties")) {
- PoolVector<float> penalties=p_data["penalties"];
- if (penalties.size()==pc) {
+ PoolVector<float> penalties = p_data["penalties"];
+ if (penalties.size() == pc) {
PoolVector<float>::Read pr = penalties.read();
- for(int i=0;i<pc;i++) {
- points[i].penalty=pr[i];
+ for (int i = 0; i < pc; i++) {
+ points[i].penalty = pr[i];
}
}
}
- PoolVector<int> segs=p_data["segments"];
- int sc=segs.size();
- ERR_FAIL_COND(sc&1);
+ PoolVector<int> segs = p_data["segments"];
+ int sc = segs.size();
+ ERR_FAIL_COND(sc & 1);
PoolVector<int>::Read sr = segs.read();
- for(int i=0;i<sc;i+=2) {
+ for (int i = 0; i < sc; i += 2) {
- Edge e(sr[i],sr[i+1]);
+ Edge e(sr[i], sr[i + 1]);
edges.insert(e);
}
- bounds=p_data["bounds"];
-
+ bounds = p_data["bounds"];
}
-Dictionary PolygonPathFinder::_get_data() const{
+Dictionary PolygonPathFinder::_get_data() const {
Dictionary d;
PoolVector<Vector2> p;
PoolVector<int> ind;
Array connections;
- p.resize(points.size()-2);
- connections.resize(points.size()-2);
- ind.resize(edges.size()*2);
+ p.resize(points.size() - 2);
+ connections.resize(points.size() - 2);
+ ind.resize(edges.size() * 2);
PoolVector<float> penalties;
- penalties.resize(points.size()-2);
+ penalties.resize(points.size() - 2);
{
- PoolVector<Vector2>::Write wp=p.write();
- PoolVector<float>::Write pw=penalties.write();
+ PoolVector<Vector2>::Write wp = p.write();
+ PoolVector<float>::Write pw = penalties.write();
- for(int i=0;i<points.size()-2;i++) {
- wp[i]=points[i].pos;
- pw[i]=points[i].penalty;
+ for (int i = 0; i < points.size() - 2; i++) {
+ wp[i] = points[i].pos;
+ pw[i] = points[i].penalty;
PoolVector<int> c;
c.resize(points[i].connections.size());
{
- PoolVector<int>::Write cw=c.write();
- int idx=0;
- for (Set<int>::Element *E=points[i].connections.front();E;E=E->next()) {
- cw[idx++]=E->get();
+ PoolVector<int>::Write cw = c.write();
+ int idx = 0;
+ for (Set<int>::Element *E = points[i].connections.front(); E; E = E->next()) {
+ cw[idx++] = E->get();
}
}
- connections[i]=c;
+ connections[i] = c;
}
}
{
- PoolVector<int>::Write iw=ind.write();
- int idx=0;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
- iw[idx++]=E->get().points[0];
- iw[idx++]=E->get().points[1];
+ PoolVector<int>::Write iw = ind.write();
+ int idx = 0;
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
+ iw[idx++] = E->get().points[0];
+ iw[idx++] = E->get().points[1];
}
-
}
- d["bounds"]=bounds;
- d["points"]=p;
- d["penalties"]=penalties;
- d["connections"]=connections;
- d["segments"]=ind;
+ d["bounds"] = bounds;
+ d["points"] = p;
+ d["penalties"] = penalties;
+ d["connections"] = connections;
+ d["segments"] = ind;
return d;
-
}
-bool PolygonPathFinder::is_point_inside(const Vector2& p_point) const {
+bool PolygonPathFinder::is_point_inside(const Vector2 &p_point) const {
return _is_point_inside(p_point);
}
-Vector2 PolygonPathFinder::get_closest_point(const Vector2& p_point) const {
+Vector2 PolygonPathFinder::get_closest_point(const Vector2 &p_point) const {
- float closest_dist=1e20;
+ float closest_dist = 1e20;
Vector2 closest_point;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
- const Edge& e=E->get();
- Vector2 seg[2]={
+ const Edge &e = E->get();
+ Vector2 seg[2] = {
points[e.points[0]].pos,
points[e.points[1]].pos
};
-
- Vector2 closest = Geometry::get_closest_point_to_segment_2d(p_point,seg);
+ Vector2 closest = Geometry::get_closest_point_to_segment_2d(p_point, seg);
float d = p_point.distance_squared_to(closest);
- if (d<closest_dist) {
- closest_dist=d;
- closest_point=closest;
+ if (d < closest_dist) {
+ closest_dist = d;
+ closest_point = closest;
}
}
- ERR_FAIL_COND_V(closest_dist==1e20,Vector2());
+ ERR_FAIL_COND_V(closest_dist == 1e20, Vector2());
return closest_point;
}
-Vector<Vector2> PolygonPathFinder::get_intersections(const Vector2& p_from, const Vector2& p_to) const {
+Vector<Vector2> PolygonPathFinder::get_intersections(const Vector2 &p_from, const Vector2 &p_to) const {
Vector<Vector2> inters;
- for (Set<Edge>::Element *E=edges.front();E;E=E->next()) {
+ for (Set<Edge>::Element *E = edges.front(); E; E = E->next()) {
Vector2 a = points[E->get().points[0]].pos;
Vector2 b = points[E->get().points[1]].pos;
Vector2 res;
- if (Geometry::segment_intersects_segment_2d(a,b,p_from,p_to,&res)) {
+ if (Geometry::segment_intersects_segment_2d(a, b, p_from, p_to, &res)) {
inters.push_back(res);
}
}
return inters;
-
}
Rect2 PolygonPathFinder::get_bounds() const {
@@ -602,40 +561,34 @@ Rect2 PolygonPathFinder::get_bounds() const {
return bounds;
}
-void PolygonPathFinder::set_point_penalty(int p_point,float p_penalty) {
+void PolygonPathFinder::set_point_penalty(int p_point, float p_penalty) {
- ERR_FAIL_INDEX(p_point,points.size()-2);
- points[p_point].penalty=p_penalty;
+ ERR_FAIL_INDEX(p_point, points.size() - 2);
+ points[p_point].penalty = p_penalty;
}
float PolygonPathFinder::get_point_penalty(int p_point) const {
- ERR_FAIL_INDEX_V(p_point,points.size()-2,0);
+ ERR_FAIL_INDEX_V(p_point, points.size() - 2, 0);
return points[p_point].penalty;
-
}
-
void PolygonPathFinder::_bind_methods() {
- ClassDB::bind_method(D_METHOD("setup","points","connections"),&PolygonPathFinder::setup);
- ClassDB::bind_method(D_METHOD("find_path","from","to"),&PolygonPathFinder::find_path);
- ClassDB::bind_method(D_METHOD("get_intersections","from","to"),&PolygonPathFinder::get_intersections);
- ClassDB::bind_method(D_METHOD("get_closest_point","point"),&PolygonPathFinder::get_closest_point);
- ClassDB::bind_method(D_METHOD("is_point_inside","point"),&PolygonPathFinder::is_point_inside);
- ClassDB::bind_method(D_METHOD("set_point_penalty","idx","penalty"),&PolygonPathFinder::set_point_penalty);
- ClassDB::bind_method(D_METHOD("get_point_penalty","idx"),&PolygonPathFinder::get_point_penalty);
+ ClassDB::bind_method(D_METHOD("setup", "points", "connections"), &PolygonPathFinder::setup);
+ ClassDB::bind_method(D_METHOD("find_path", "from", "to"), &PolygonPathFinder::find_path);
+ ClassDB::bind_method(D_METHOD("get_intersections", "from", "to"), &PolygonPathFinder::get_intersections);
+ ClassDB::bind_method(D_METHOD("get_closest_point", "point"), &PolygonPathFinder::get_closest_point);
+ ClassDB::bind_method(D_METHOD("is_point_inside", "point"), &PolygonPathFinder::is_point_inside);
+ ClassDB::bind_method(D_METHOD("set_point_penalty", "idx", "penalty"), &PolygonPathFinder::set_point_penalty);
+ ClassDB::bind_method(D_METHOD("get_point_penalty", "idx"), &PolygonPathFinder::get_point_penalty);
- ClassDB::bind_method(D_METHOD("get_bounds"),&PolygonPathFinder::get_bounds);
- ClassDB::bind_method(D_METHOD("_set_data"),&PolygonPathFinder::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"),&PolygonPathFinder::_get_data);
-
- ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY,"data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),"_set_data","_get_data");
+ ClassDB::bind_method(D_METHOD("get_bounds"), &PolygonPathFinder::get_bounds);
+ ClassDB::bind_method(D_METHOD("_set_data"), &PolygonPathFinder::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &PolygonPathFinder::_get_data);
+ ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
}
-PolygonPathFinder::PolygonPathFinder()
-{
+PolygonPathFinder::PolygonPathFinder() {
}
-
-
diff --git a/scene/resources/polygon_path_finder.h b/scene/resources/polygon_path_finder.h
index 58b8023843..cd2fea87d4 100644
--- a/scene/resources/polygon_path_finder.h
+++ b/scene/resources/polygon_path_finder.h
@@ -33,7 +33,7 @@
class PolygonPathFinder : public Resource {
- GDCLASS(PolygonPathFinder,Resource);
+ GDCLASS(PolygonPathFinder, Resource);
struct Point {
Vector2 pos;
@@ -47,18 +47,18 @@ class PolygonPathFinder : public Resource {
int points[2];
- _FORCE_INLINE_ bool operator<(const Edge& p_edge) const {
+ _FORCE_INLINE_ bool operator<(const Edge &p_edge) const {
- if (points[0]==p_edge.points[0])
- return points[1]<p_edge.points[1];
+ if (points[0] == p_edge.points[0])
+ return points[1] < p_edge.points[1];
else
- return points[0]<p_edge.points[0];
+ return points[0] < p_edge.points[0];
}
- Edge(int a=0, int b=0) {
+ Edge(int a = 0, int b = 0) {
- if (a>b) {
- SWAP(a,b);
+ if (a > b) {
+ SWAP(a, b);
}
points[0] = a;
points[1] = b;
@@ -71,28 +71,26 @@ class PolygonPathFinder : public Resource {
Vector<Point> points;
Set<Edge> edges;
- bool _is_point_inside(const Vector2& p_point) const;
+ bool _is_point_inside(const Vector2 &p_point) const;
- void _set_data(const Dictionary& p_data);
+ void _set_data(const Dictionary &p_data);
Dictionary _get_data() const;
-protected:
+protected:
static void _bind_methods();
-public:
+public:
+ void setup(const Vector<Vector2> &p_points, const Vector<int> &p_connections);
+ Vector<Vector2> find_path(const Vector2 &p_from, const Vector2 &p_to);
- void setup(const Vector<Vector2>& p_points, const Vector<int>& p_connections);
- Vector<Vector2> find_path(const Vector2& p_from, const Vector2& p_to);
-
- void set_point_penalty(int p_point,float p_penalty);
+ void set_point_penalty(int p_point, float p_penalty);
float get_point_penalty(int p_point) const;
- bool is_point_inside(const Vector2& p_point) const;
- Vector2 get_closest_point(const Vector2& p_point) const;
- Vector<Vector2> get_intersections(const Vector2& p_from, const Vector2& p_to) const;
+ bool is_point_inside(const Vector2 &p_point) const;
+ Vector2 get_closest_point(const Vector2 &p_point) const;
+ Vector<Vector2> get_intersections(const Vector2 &p_from, const Vector2 &p_to) const;
Rect2 get_bounds() const;
-
PolygonPathFinder();
};
diff --git a/scene/resources/ray_shape.cpp b/scene/resources/ray_shape.cpp
index 52ce736925..8187b8b3f1 100644
--- a/scene/resources/ray_shape.cpp
+++ b/scene/resources/ray_shape.cpp
@@ -34,20 +34,20 @@ Vector<Vector3> RayShape::_gen_debug_mesh_lines() {
Vector<Vector3> points;
points.push_back(Vector3());
- points.push_back(Vector3(0,0,get_length()));
+ points.push_back(Vector3(0, 0, get_length()));
return points;
}
void RayShape::_update_shape() {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),length);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), length);
emit_changed();
}
void RayShape::set_length(float p_length) {
- length=p_length;
+ length = p_length;
_update_shape();
notify_change_to_owners();
}
@@ -57,17 +57,16 @@ float RayShape::get_length() const {
return length;
}
-
void RayShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_length","length"),&RayShape::set_length);
- ClassDB::bind_method(D_METHOD("get_length"),&RayShape::get_length);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"length",PROPERTY_HINT_RANGE,"0,4096,0.01"), "set_length", "get_length") ;
+ ClassDB::bind_method(D_METHOD("set_length", "length"), &RayShape::set_length);
+ ClassDB::bind_method(D_METHOD("get_length"), &RayShape::get_length);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_length", "get_length");
}
-RayShape::RayShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_RAY)) {
+RayShape::RayShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_RAY)) {
set_length(1.0);
}
diff --git a/scene/resources/ray_shape.h b/scene/resources/ray_shape.h
index 9ee59d5f91..f8dbf89e04 100644
--- a/scene/resources/ray_shape.h
+++ b/scene/resources/ray_shape.h
@@ -32,16 +32,15 @@
class RayShape : public Shape {
- GDCLASS(RayShape,Shape);
+ GDCLASS(RayShape, Shape);
float length;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
+public:
void set_length(float p_length);
float get_length() const;
diff --git a/scene/resources/rectangle_shape_2d.cpp b/scene/resources/rectangle_shape_2d.cpp
index 1161843a2b..06b5ac0316 100644
--- a/scene/resources/rectangle_shape_2d.cpp
+++ b/scene/resources/rectangle_shape_2d.cpp
@@ -32,14 +32,13 @@
#include "servers/visual_server.h"
void RectangleShape2D::_update_shape() {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),extents);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), extents);
emit_changed();
}
+void RectangleShape2D::set_extents(const Vector2 &p_extents) {
-void RectangleShape2D::set_extents(const Vector2& p_extents) {
-
- extents=p_extents;
+ extents = p_extents;
_update_shape();
}
@@ -48,33 +47,27 @@ Vector2 RectangleShape2D::get_extents() const {
return extents;
}
-void RectangleShape2D::draw(const RID& p_to_rid,const Color& p_color) {
-
-
- VisualServer::get_singleton()->canvas_item_add_rect(p_to_rid,Rect2(-extents,extents*2.0),p_color);
+void RectangleShape2D::draw(const RID &p_to_rid, const Color &p_color) {
+ VisualServer::get_singleton()->canvas_item_add_rect(p_to_rid, Rect2(-extents, extents * 2.0), p_color);
}
Rect2 RectangleShape2D::get_rect() const {
- return Rect2(-extents,extents*2.0);
-
+ return Rect2(-extents, extents * 2.0);
}
-
void RectangleShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_extents","extents"),&RectangleShape2D::set_extents);
- ClassDB::bind_method(D_METHOD("get_extents"),&RectangleShape2D::get_extents);
-
-
-
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"extents"),"set_extents","get_extents") ;
+ ClassDB::bind_method(D_METHOD("set_extents", "extents"), &RectangleShape2D::set_extents);
+ ClassDB::bind_method(D_METHOD("get_extents"), &RectangleShape2D::get_extents);
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "extents"), "set_extents", "get_extents");
}
-RectangleShape2D::RectangleShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RECTANGLE)) {
+RectangleShape2D::RectangleShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RECTANGLE)) {
- extents=Vector2(10,10);
+ extents = Vector2(10, 10);
_update_shape();
}
diff --git a/scene/resources/rectangle_shape_2d.h b/scene/resources/rectangle_shape_2d.h
index 6682b67de0..8de2f7580e 100644
--- a/scene/resources/rectangle_shape_2d.h
+++ b/scene/resources/rectangle_shape_2d.h
@@ -32,20 +32,20 @@
#include "scene/resources/shape_2d.h"
class RectangleShape2D : public Shape2D {
- GDCLASS( RectangleShape2D, Shape2D );
+ GDCLASS(RectangleShape2D, Shape2D);
Vector2 extents;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
- void set_extents(const Vector2& p_extents);
+public:
+ void set_extents(const Vector2 &p_extents);
Vector2 get_extents() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
- virtual Rect2 get_rect() const ;
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
+ virtual Rect2 get_rect() const;
RectangleShape2D();
};
diff --git a/scene/resources/room.cpp b/scene/resources/room.cpp
index e677f92c31..9ec8914e2f 100644
--- a/scene/resources/room.cpp
+++ b/scene/resources/room.cpp
@@ -30,16 +30,14 @@
#include "servers/visual_server.h"
-
RID RoomBounds::get_rid() const {
return area;
}
+void RoomBounds::set_geometry_hint(const PoolVector<Face3> &p_geometry_hint) {
-void RoomBounds::set_geometry_hint(const PoolVector<Face3>& p_geometry_hint) {
-
- geometry_hint=p_geometry_hint;
+ geometry_hint = p_geometry_hint;
}
PoolVector<Face3> RoomBounds::get_geometry_hint() const {
@@ -47,29 +45,21 @@ PoolVector<Face3> RoomBounds::get_geometry_hint() const {
return geometry_hint;
}
-
-
void RoomBounds::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("set_geometry_hint","triangles"),&RoomBounds::set_geometry_hint);
- ClassDB::bind_method(D_METHOD("get_geometry_hint"),&RoomBounds::get_geometry_hint);
+ ClassDB::bind_method(D_METHOD("set_geometry_hint", "triangles"), &RoomBounds::set_geometry_hint);
+ ClassDB::bind_method(D_METHOD("get_geometry_hint"), &RoomBounds::get_geometry_hint);
//ADD_PROPERTY( PropertyInfo( Variant::DICTIONARY, "bounds"), "set_bounds","get_bounds") ;
- ADD_PROPERTY( PropertyInfo( Variant::POOL_VECTOR3_ARRAY, "geometry_hint"),"set_geometry_hint","get_geometry_hint") ;
-
+ ADD_PROPERTY(PropertyInfo(Variant::POOL_VECTOR3_ARRAY, "geometry_hint"), "set_geometry_hint", "get_geometry_hint");
}
RoomBounds::RoomBounds() {
- area=VisualServer::get_singleton()->room_create();
+ area = VisualServer::get_singleton()->room_create();
}
-
RoomBounds::~RoomBounds() {
VisualServer::get_singleton()->free(area);
-
}
-
-
diff --git a/scene/resources/room.h b/scene/resources/room.h
index 84d68e5718..c7db4b13d9 100644
--- a/scene/resources/room.h
+++ b/scene/resources/room.h
@@ -29,38 +29,31 @@
#ifndef ROOM_BOUNDS_H
#define ROOM_BOUNDS_H
-#include "resource.h"
#include "bsp_tree.h"
+#include "resource.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class RoomBounds : public Resource {
- GDCLASS( RoomBounds, Resource );
+ GDCLASS(RoomBounds, Resource);
RES_BASE_EXTENSION("room");
RID area;
PoolVector<Face3> geometry_hint;
-
protected:
-
static void _bind_methods();
public:
-
virtual RID get_rid() const;
-
- void set_geometry_hint(const PoolVector<Face3>& geometry_hint);
+ void set_geometry_hint(const PoolVector<Face3> &geometry_hint);
PoolVector<Face3> get_geometry_hint() const;
RoomBounds();
~RoomBounds();
-
};
-
-
#endif // ROOM_H
diff --git a/scene/resources/scene_format_text.cpp b/scene/resources/scene_format_text.cpp
index 3a254836a2..7162c9fc18 100644
--- a/scene/resources/scene_format_text.cpp
+++ b/scene/resources/scene_format_text.cpp
@@ -29,25 +29,22 @@
#include "scene_format_text.h"
#include "global_config.h"
-#include "version.h"
#include "os/dir_access.h"
+#include "version.h"
//version 2: changed names for basis, rect3, poolvectors, etc.
#define FORMAT_VERSION 2
-#include "version.h"
#include "os/dir_access.h"
+#include "version.h"
-#define _printerr() ERR_PRINT(String(res_path+":"+itos(lines)+" - Parse Error: "+error_text).utf8().get_data());
-
-
-
+#define _printerr() ERR_PRINT(String(res_path + ":" + itos(lines) + " - Parse Error: " + error_text).utf8().get_data());
///
-void ResourceInteractiveLoaderText::set_local_path(const String& p_local_path) {
+void ResourceInteractiveLoaderText::set_local_path(const String &p_local_path) {
- res_path=p_local_path;
+ res_path = p_local_path;
}
Ref<Resource> ResourceInteractiveLoaderText::get_resource() {
@@ -55,47 +52,46 @@ Ref<Resource> ResourceInteractiveLoaderText::get_resource() {
return resource;
}
-Error ResourceInteractiveLoaderText::_parse_sub_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) {
+Error ResourceInteractiveLoaderText::_parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
VariantParser::Token token;
- VariantParser::get_token(p_stream,token,line,r_err_str);
- if (token.type!=VariantParser::TK_NUMBER) {
- r_err_str="Expected number (sub-resource index)";
+ VariantParser::get_token(p_stream, token, line, r_err_str);
+ if (token.type != VariantParser::TK_NUMBER) {
+ r_err_str = "Expected number (sub-resource index)";
return ERR_PARSE_ERROR;
}
int index = token.value;
- String path = local_path+"::"+itos(index);
+ String path = local_path + "::" + itos(index);
if (!ignore_resource_parsing) {
if (!ResourceCache::has(path)) {
- r_err_str="Can't load cached sub-resource: "+path;
+ r_err_str = "Can't load cached sub-resource: " + path;
return ERR_PARSE_ERROR;
}
- r_res=RES(ResourceCache::get(path));
+ r_res = RES(ResourceCache::get(path));
} else {
- r_res=RES();
+ r_res = RES();
}
- VariantParser::get_token(p_stream,token,line,r_err_str);
- if (token.type!=VariantParser::TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ VariantParser::get_token(p_stream, token, line, r_err_str);
+ if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
-
return OK;
}
-Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str){
+Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) {
VariantParser::Token token;
- VariantParser::get_token(p_stream,token,line,r_err_str);
- if (token.type!=VariantParser::TK_NUMBER) {
- r_err_str="Expected number (sub-resource index)";
+ VariantParser::get_token(p_stream, token, line, r_err_str);
+ if (token.type != VariantParser::TK_NUMBER) {
+ r_err_str = "Expected number (sub-resource index)";
return ERR_PARSE_ERROR;
}
@@ -104,93 +100,88 @@ Error ResourceInteractiveLoaderText::_parse_ext_resource(VariantParser::Stream*
if (!ignore_resource_parsing) {
if (!ext_resources.has(id)) {
- r_err_str="Can't load cached ext-resource #"+itos(id);
+ r_err_str = "Can't load cached ext-resource #" + itos(id);
return ERR_PARSE_ERROR;
}
String path = ext_resources[id].path;
String type = ext_resources[id].type;
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
-
+ path = GlobalConfig::get_singleton()->localize_path(res_path.get_base_dir().plus_file(path));
}
- r_res=ResourceLoader::load(path,type);
+ r_res = ResourceLoader::load(path, type);
if (r_res.is_null()) {
- WARN_PRINT(String("Couldn't load external resource: "+path).utf8().get_data());
+ WARN_PRINT(String("Couldn't load external resource: " + path).utf8().get_data());
}
} else {
- r_res=RES();
+ r_res = RES();
}
- VariantParser::get_token(p_stream,token,line,r_err_str);
- if (token.type!=VariantParser::TK_PARENTHESIS_CLOSE) {
- r_err_str="Expected ')'";
+ VariantParser::get_token(p_stream, token, line, r_err_str);
+ if (token.type != VariantParser::TK_PARENTHESIS_CLOSE) {
+ r_err_str = "Expected ')'";
return ERR_PARSE_ERROR;
}
-
return OK;
}
-
Error ResourceInteractiveLoaderText::poll() {
- if (error!=OK)
+ if (error != OK)
return error;
- if (next_tag.name=="ext_resource") {
-
+ if (next_tag.name == "ext_resource") {
if (!next_tag.fields.has("path")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'path' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'path' in external resource tag";
_printerr();
return error;
}
if (!next_tag.fields.has("type")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'type' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'type' in external resource tag";
_printerr();
return error;
}
if (!next_tag.fields.has("id")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'id' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'id' in external resource tag";
_printerr();
return error;
}
- String path=next_tag.fields["path"];
- String type=next_tag.fields["type"];
- int index=next_tag.fields["id"];
+ String path = next_tag.fields["path"];
+ String type = next_tag.fields["type"];
+ int index = next_tag.fields["id"];
-
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
+ path = GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
}
if (remaps.has(path)) {
- path=remaps[path];
+ path = remaps[path];
}
- RES res = ResourceLoader::load(path,type);
+ RES res = ResourceLoader::load(path, type);
if (res.is_null()) {
if (ResourceLoader::get_abort_on_missing_resources()) {
- error=ERR_FILE_CORRUPT;
- error_text="[ext_resource] referenced nonexistent resource at: "+path;
+ error = ERR_FILE_CORRUPT;
+ error_text = "[ext_resource] referenced nonexistent resource at: " + path;
_printerr();
return error;
} else {
- ResourceLoader::notify_dependency_error(local_path,path,type);
+ ResourceLoader::notify_dependency_error(local_path, path, type);
}
} else {
@@ -198,11 +189,11 @@ Error ResourceInteractiveLoaderText::poll() {
}
ExtResource er;
- er.path=path;
- er.type=type;
- ext_resources[index]=er;
+ er.path = path;
+ er.type = type;
+ ext_resources[index] = er;
- error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
+ error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
if (error) {
_printerr();
@@ -211,138 +202,130 @@ Error ResourceInteractiveLoaderText::poll() {
resource_current++;
return error;
-
- } else if (next_tag.name=="sub_resource") {
-
+ } else if (next_tag.name == "sub_resource") {
if (!next_tag.fields.has("type")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'type' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'type' in external resource tag";
_printerr();
return error;
}
if (!next_tag.fields.has("id")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'index' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'index' in external resource tag";
_printerr();
return error;
}
- String type=next_tag.fields["type"];
- int id=next_tag.fields["id"];
-
- String path = local_path+"::"+itos(id);
+ String type = next_tag.fields["type"];
+ int id = next_tag.fields["id"];
+ String path = local_path + "::" + itos(id);
//bool exists=ResourceCache::has(path);
Ref<Resource> res;
- if ( !ResourceCache::has(path)) { //only if it doesn't exist
+ if (!ResourceCache::has(path)) { //only if it doesn't exist
Object *obj = ClassDB::instance(type);
if (!obj) {
- error_text+="Can't create sub resource of type: "+type;
+ error_text += "Can't create sub resource of type: " + type;
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
-
Resource *r = obj->cast_to<Resource>();
if (!r) {
- error_text+="Can't create sub resource of type, because not a resource: "+type;
+ error_text += "Can't create sub resource of type, because not a resource: " + type;
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
- res=Ref<Resource>(r);
+ res = Ref<Resource>(r);
resource_cache.push_back(res);
res->set_path(path);
-
}
resource_current++;
- while(true) {
+ while (true) {
String assign;
Variant value;
- error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp);
+ error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
if (error) {
_printerr();
return error;
}
- if (assign!=String()) {
+ if (assign != String()) {
if (res.is_valid()) {
- res->set(assign,value);
+ res->set(assign, value);
}
//it's assignment
- } else if (next_tag.name!=String()) {
+ } else if (next_tag.name != String()) {
- error=OK;
+ error = OK;
break;
} else {
- error=ERR_FILE_CORRUPT;
- error_text="Premature end of file while parsing [sub_resource]";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Premature end of file while parsing [sub_resource]";
_printerr();
return error;
}
-
-
}
return OK;
- } else if (next_tag.name=="resource") {
+ } else if (next_tag.name == "resource") {
if (is_scene) {
- error_text+="found the 'resource' tag on a scene file!";
+ error_text += "found the 'resource' tag on a scene file!";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
Object *obj = ClassDB::instance(res_type);
if (!obj) {
- error_text+="Can't create sub resource of type: "+res_type;
+ error_text += "Can't create sub resource of type: " + res_type;
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
-
Resource *r = obj->cast_to<Resource>();
if (!r) {
- error_text+="Can't create sub resource of type, because not a resource: "+res_type;
+ error_text += "Can't create sub resource of type, because not a resource: " + res_type;
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
- resource=Ref<Resource>(r);
+ resource = Ref<Resource>(r);
resource_current++;
- while(true) {
+ while (true) {
String assign;
Variant value;
- error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp);
+ error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
if (error) {
- if (error!=ERR_FILE_EOF) {
+ if (error != ERR_FILE_EOF) {
_printerr();
} else {
if (!ResourceCache::has(res_path)) {
@@ -352,31 +335,30 @@ Error ResourceInteractiveLoaderText::poll() {
return error;
}
- if (assign!=String()) {
- resource->set(assign,value);
+ if (assign != String()) {
+ resource->set(assign, value);
//it's assignment
- } else if (next_tag.name!=String()) {
+ } else if (next_tag.name != String()) {
- error=ERR_FILE_CORRUPT;
- error_text="Extra tag found when parsing main resource file";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Extra tag found when parsing main resource file";
_printerr();
return error;
} else {
- error=ERR_FILE_EOF;
+ error = ERR_FILE_EOF;
return error;
}
-
}
return OK;
- } else if (next_tag.name=="node") {
+ } else if (next_tag.name == "node") {
if (!is_scene) {
- error_text+="found the 'node' tag on a resource file!";
+ error_text += "found the 'node' tag on a resource file!";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
@@ -393,87 +375,84 @@ Error ResourceInteractiveLoaderText::poll() {
*/
- int parent=-1;
- int owner=-1;
- int type=-1;
- int name=-1;
- int instance=-1;
+ int parent = -1;
+ int owner = -1;
+ int type = -1;
+ int name = -1;
+ int instance = -1;
//int base_scene=-1;
if (next_tag.fields.has("name")) {
- name=packed_scene->get_state()->add_name(next_tag.fields["name"]);
+ name = packed_scene->get_state()->add_name(next_tag.fields["name"]);
}
if (next_tag.fields.has("parent")) {
NodePath np = next_tag.fields["parent"];
np.prepend_period(); //compatible to how it manages paths internally
- parent=packed_scene->get_state()->add_node_path(np);
+ parent = packed_scene->get_state()->add_node_path(np);
}
-
-
if (next_tag.fields.has("type")) {
- type=packed_scene->get_state()->add_name(next_tag.fields["type"]);
+ type = packed_scene->get_state()->add_name(next_tag.fields["type"]);
} else {
- type=SceneState::TYPE_INSTANCED; //no type? assume this was instanced
+ type = SceneState::TYPE_INSTANCED; //no type? assume this was instanced
}
-
if (next_tag.fields.has("instance")) {
- instance=packed_scene->get_state()->add_value(next_tag.fields["instance"]);
+ instance = packed_scene->get_state()->add_value(next_tag.fields["instance"]);
- if (packed_scene->get_state()->get_node_count()==0 && parent==-1) {
+ if (packed_scene->get_state()->get_node_count() == 0 && parent == -1) {
packed_scene->get_state()->set_base_scene(instance);
- instance=-1;
+ instance = -1;
}
}
if (next_tag.fields.has("instance_placeholder")) {
- String path=next_tag.fields["instance_placeholder"];
+ String path = next_tag.fields["instance_placeholder"];
int path_v = packed_scene->get_state()->add_value(path);
- if (packed_scene->get_state()->get_node_count()==0) {
- error=ERR_FILE_CORRUPT;
- error_text="Instance Placeholder can't be used for inheritance.";
+ if (packed_scene->get_state()->get_node_count() == 0) {
+ error = ERR_FILE_CORRUPT;
+ error_text = "Instance Placeholder can't be used for inheritance.";
_printerr();
return error;
}
- instance=path_v|SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
+ instance = path_v | SceneState::FLAG_INSTANCE_IS_PLACEHOLDER;
}
if (next_tag.fields.has("owner")) {
- owner=packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
+ owner = packed_scene->get_state()->add_node_path(next_tag.fields["owner"]);
} else {
- if (parent!=-1 && !(type==SceneState::TYPE_INSTANCED && instance==-1))
- owner=0; //if no owner, owner is root
+ if (parent != -1 && !(type == SceneState::TYPE_INSTANCED && instance == -1))
+ owner = 0; //if no owner, owner is root
}
- int node_id = packed_scene->get_state()->add_node(parent,owner,type,name,instance);
+ int node_id = packed_scene->get_state()->add_node(parent, owner, type, name, instance);
if (next_tag.fields.has("groups")) {
Array groups = next_tag.fields["groups"];
- for (int i=0;i<groups.size();i++) {
- packed_scene->get_state()->add_node_group(node_id,packed_scene->get_state()->add_name(groups[i]));
+ for (int i = 0; i < groups.size(); i++) {
+ packed_scene->get_state()->add_node_group(node_id, packed_scene->get_state()->add_name(groups[i]));
}
}
- while(true) {
+ while (true) {
String assign;
Variant value;
- error = VariantParser::parse_tag_assign_eof(&stream,lines,error_text,next_tag,assign,value,&rp);
+ error = VariantParser::parse_tag_assign_eof(&stream, lines, error_text, next_tag, assign, value, &rp);
if (error) {
- if (error!=ERR_FILE_EOF) {
+ if (error != ERR_FILE_EOF) {
_printerr();
} else {
- resource=packed_scene;
+ resource = packed_scene;
if (!ResourceCache::has(res_path)) {
packed_scene->set_path(res_path);
}
@@ -481,57 +460,56 @@ Error ResourceInteractiveLoaderText::poll() {
return error;
}
- if (assign!=String()) {
+ if (assign != String()) {
int nameidx = packed_scene->get_state()->add_name(assign);
int valueidx = packed_scene->get_state()->add_value(value);
- packed_scene->get_state()->add_node_property(node_id,nameidx,valueidx);
+ packed_scene->get_state()->add_node_property(node_id, nameidx, valueidx);
//it's assignment
- } else if (next_tag.name!=String()) {
+ } else if (next_tag.name != String()) {
- error=OK;
+ error = OK;
return error;
} else {
- resource=packed_scene;
- error=ERR_FILE_EOF;
+ resource = packed_scene;
+ error = ERR_FILE_EOF;
return error;
}
-
}
return OK;
- } else if (next_tag.name=="connection") {
+ } else if (next_tag.name == "connection") {
if (!is_scene) {
- error_text+="found the 'connection' tag on a resource file!";
+ error_text += "found the 'connection' tag on a resource file!";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
if (!next_tag.fields.has("from")) {
- error=ERR_FILE_CORRUPT;
- error_text="missing 'from' field fron connection tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "missing 'from' field fron connection tag";
return error;
}
if (!next_tag.fields.has("to")) {
- error=ERR_FILE_CORRUPT;
- error_text="missing 'to' field fron connection tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "missing 'to' field fron connection tag";
return error;
}
if (!next_tag.fields.has("signal")) {
- error=ERR_FILE_CORRUPT;
- error_text="missing 'signal' field fron connection tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "missing 'signal' field fron connection tag";
return error;
}
if (!next_tag.fields.has("method")) {
- error=ERR_FILE_CORRUPT;
- error_text="missing 'method' field fron connection tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "missing 'method' field fron connection tag";
return error;
}
@@ -539,55 +517,54 @@ Error ResourceInteractiveLoaderText::poll() {
NodePath to = next_tag.fields["to"];
StringName method = next_tag.fields["method"];
StringName signal = next_tag.fields["signal"];
- int flags=CONNECT_PERSIST;
+ int flags = CONNECT_PERSIST;
Array binds;
if (next_tag.fields.has("flags")) {
- flags=next_tag.fields["flags"];
+ flags = next_tag.fields["flags"];
}
if (next_tag.fields.has("binds")) {
- binds=next_tag.fields["binds"];
+ binds = next_tag.fields["binds"];
}
Vector<int> bind_ints;
- for(int i=0;i<binds.size();i++) {
- bind_ints.push_back( packed_scene->get_state()->add_value( binds[i] ) );
+ for (int i = 0; i < binds.size(); i++) {
+ bind_ints.push_back(packed_scene->get_state()->add_value(binds[i]));
}
packed_scene->get_state()->add_connection(
- packed_scene->get_state()->add_node_path(from.simplified()),
- packed_scene->get_state()->add_node_path(to.simplified()),
- packed_scene->get_state()->add_name(signal),
- packed_scene->get_state()->add_name(method),
- flags,
- bind_ints
- );
+ packed_scene->get_state()->add_node_path(from.simplified()),
+ packed_scene->get_state()->add_node_path(to.simplified()),
+ packed_scene->get_state()->add_name(signal),
+ packed_scene->get_state()->add_name(method),
+ flags,
+ bind_ints);
- error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
+ error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
if (error) {
- if (error!=ERR_FILE_EOF) {
+ if (error != ERR_FILE_EOF) {
_printerr();
} else {
- resource=packed_scene;
+ resource = packed_scene;
}
}
return error;
- } else if (next_tag.name=="editable") {
+ } else if (next_tag.name == "editable") {
if (!is_scene) {
- error_text+="found the 'editable' tag on a resource file!";
+ error_text += "found the 'editable' tag on a resource file!";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
if (!next_tag.fields.has("path")) {
- error=ERR_FILE_CORRUPT;
- error_text="missing 'path' field fron connection tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "missing 'path' field fron connection tag";
_printerr();
return error;
}
@@ -596,13 +573,13 @@ Error ResourceInteractiveLoaderText::poll() {
packed_scene->get_state()->add_editable_instance(path.simplified());
- error = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
+ error = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
if (error) {
- if (error!=ERR_FILE_EOF) {
+ if (error != ERR_FILE_EOF) {
_printerr();
} else {
- resource=packed_scene;
+ resource = packed_scene;
}
}
@@ -610,9 +587,9 @@ Error ResourceInteractiveLoaderText::poll() {
} else {
- error_text+="Unknown tag in file: "+next_tag.name;
+ error_text += "Unknown tag in file: " + next_tag.name;
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
return error;
}
@@ -625,7 +602,7 @@ int ResourceInteractiveLoaderText::get_stage() const {
}
int ResourceInteractiveLoaderText::get_stage_count() const {
- return resources_total;//+ext_resources;
+ return resources_total; //+ext_resources;
}
ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() {
@@ -633,89 +610,79 @@ ResourceInteractiveLoaderText::~ResourceInteractiveLoaderText() {
memdelete(f);
}
-void ResourceInteractiveLoaderText::get_dependencies(FileAccess *f,List<String> *p_dependencies,bool p_add_types) {
-
+void ResourceInteractiveLoaderText::get_dependencies(FileAccess *f, List<String> *p_dependencies, bool p_add_types) {
open(f);
- ignore_resource_parsing=true;
- ERR_FAIL_COND(error!=OK);
+ ignore_resource_parsing = true;
+ ERR_FAIL_COND(error != OK);
- while(next_tag.name=="ext_resource") {
+ while (next_tag.name == "ext_resource") {
if (!next_tag.fields.has("type")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'type' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'type' in external resource tag";
_printerr();
return;
}
if (!next_tag.fields.has("id")) {
- error=ERR_FILE_CORRUPT;
- error_text="Missing 'index' in external resource tag";
+ error = ERR_FILE_CORRUPT;
+ error_text = "Missing 'index' in external resource tag";
_printerr();
return;
}
- String path=next_tag.fields["path"];
- String type=next_tag.fields["type"];
-
+ String path = next_tag.fields["path"];
+ String type = next_tag.fields["type"];
- if (path.find("://")==-1 && path.is_rel_path()) {
+ if (path.find("://") == -1 && path.is_rel_path()) {
// path is relative to file being loaded, so convert to a resource path
- path=GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
+ path = GlobalConfig::get_singleton()->localize_path(local_path.get_base_dir().plus_file(path));
}
-
if (p_add_types) {
- path+="::"+type;
+ path += "::" + type;
}
p_dependencies->push_back(path);
- Error err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
+ Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
if (err) {
- print_line(error_text+" - "+itos(lines));
- error_text="Unexpected end of file";
+ print_line(error_text + " - " + itos(lines));
+ error_text = "Unexpected end of file";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
}
-
-
}
}
-Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path,const Map<String,String>& p_map) {
-
+Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map) {
- open(p_f,true);
- ERR_FAIL_COND_V(error!=OK,error);
- ignore_resource_parsing=true;
+ open(p_f, true);
+ ERR_FAIL_COND_V(error != OK, error);
+ ignore_resource_parsing = true;
//FileAccess
FileAccess *fw = NULL;
- String base_path=local_path.get_base_dir();
-
+ String base_path = local_path.get_base_dir();
uint64_t tag_end = f->get_pos();
+ while (true) {
- while(true) {
-
+ Error err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
-
- Error err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
-
- if (err!=OK) {
+ if (err != OK) {
if (fw) {
memdelete(fw);
}
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
ERR_FAIL_V(error);
}
- if (next_tag.name!="ext_resource") {
+ if (next_tag.name != "ext_resource") {
//nothing was done
if (!fw)
@@ -723,22 +690,21 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const
break;
-
} else {
if (!fw) {
- fw=FileAccess::open(p_path+".depren",FileAccess::WRITE);
+ fw = FileAccess::open(p_path + ".depren", FileAccess::WRITE);
if (is_scene) {
- fw->store_line("[gd_scene load_steps="+itos(resources_total)+" format="+itos(FORMAT_VERSION)+"]\n");
+ fw->store_line("[gd_scene load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
} else {
- fw->store_line("[gd_resource type=\""+res_type+"\" load_steps="+itos(resources_total)+" format="+itos(FORMAT_VERSION)+"]\n");
+ fw->store_line("[gd_resource type=\"" + res_type + "\" load_steps=" + itos(resources_total) + " format=" + itos(FORMAT_VERSION) + "]\n");
}
}
if (!next_tag.fields.has("path") || !next_tag.fields.has("id") || !next_tag.fields.has("type")) {
memdelete(fw);
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
ERR_FAIL_V(error);
}
@@ -746,41 +712,38 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const
int index = next_tag.fields["id"];
String type = next_tag.fields["type"];
-
- bool relative=false;
+ bool relative = false;
if (!path.begins_with("res://")) {
- path=base_path.plus_file(path).simplify_path();
- relative=true;
+ path = base_path.plus_file(path).simplify_path();
+ relative = true;
}
if (p_map.has(path)) {
- String np=p_map[path];
- path=np;
+ String np = p_map[path];
+ path = np;
}
if (relative) {
//restore relative
- path=base_path.path_to_file(path);
+ path = base_path.path_to_file(path);
}
- fw->store_line("[ext_resource path=\""+path+"\" type=\""+type+"\" id="+itos(index)+"]");
+ fw->store_line("[ext_resource path=\"" + path + "\" type=\"" + type + "\" id=" + itos(index) + "]");
tag_end = f->get_pos();
-
}
-
}
f->seek(tag_end);
- uint8_t c=f->get_8();
- while(!f->eof_reached()) {
+ uint8_t c = f->get_8();
+ while (!f->eof_reached()) {
fw->store_8(c);
- c=f->get_8();
+ c = f->get_8();
}
f->close();
- bool all_ok = fw->get_error()==OK;
+ bool all_ok = fw->get_error() == OK;
memdelete(fw);
@@ -790,114 +753,101 @@ Error ResourceInteractiveLoaderText::rename_dependencies(FileAccess *p_f, const
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
da->remove(p_path);
- da->rename(p_path+".depren",p_path);
+ da->rename(p_path + ".depren", p_path);
memdelete(da);
return OK;
-
}
+void ResourceInteractiveLoaderText::open(FileAccess *p_f, bool p_skip_first_tag) {
-void ResourceInteractiveLoaderText::open(FileAccess *p_f,bool p_skip_first_tag) {
-
- error=OK;
-
- lines=1;
- f=p_f;
+ error = OK;
+ lines = 1;
+ f = p_f;
- stream.f=f;
- is_scene=false;
- ignore_resource_parsing=false;
- resource_current=0;
-
+ stream.f = f;
+ is_scene = false;
+ ignore_resource_parsing = false;
+ resource_current = 0;
VariantParser::Tag tag;
- Error err = VariantParser::parse_tag(&stream,lines,error_text,tag);
+ Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
if (err) {
- error=err;
+ error = err;
_printerr();
return;
}
if (tag.fields.has("format")) {
int fmt = tag.fields["format"];
- if (fmt>FORMAT_VERSION) {
- error_text="Saved with newer format version";
+ if (fmt > FORMAT_VERSION) {
+ error_text = "Saved with newer format version";
_printerr();
- error=ERR_PARSE_ERROR;
+ error = ERR_PARSE_ERROR;
return;
}
}
-
- if (tag.name=="gd_scene") {
- is_scene=true;
+ if (tag.name == "gd_scene") {
+ is_scene = true;
packed_scene.instance();
- } else if (tag.name=="gd_resource") {
+ } else if (tag.name == "gd_resource") {
if (!tag.fields.has("type")) {
- error_text="Missing 'type' field in 'gd_resource' tag";
+ error_text = "Missing 'type' field in 'gd_resource' tag";
_printerr();
- error=ERR_PARSE_ERROR;
+ error = ERR_PARSE_ERROR;
return;
}
- res_type=tag.fields["type"];
+ res_type = tag.fields["type"];
} else {
- error_text="Unrecognized file type: "+tag.name;
+ error_text = "Unrecognized file type: " + tag.name;
_printerr();
- error=ERR_PARSE_ERROR;
+ error = ERR_PARSE_ERROR;
return;
-
}
-
-
if (tag.fields.has("load_steps")) {
- resources_total=tag.fields["load_steps"];
+ resources_total = tag.fields["load_steps"];
} else {
- resources_total=0;
+ resources_total = 0;
}
if (!p_skip_first_tag) {
- err = VariantParser::parse_tag(&stream,lines,error_text,next_tag,&rp);
+ err = VariantParser::parse_tag(&stream, lines, error_text, next_tag, &rp);
if (err) {
- error_text="Unexpected end of file";
+ error_text = "Unexpected end of file";
_printerr();
- error=ERR_FILE_CORRUPT;
+ error = ERR_FILE_CORRUPT;
}
}
- rp.ext_func=_parse_ext_resources;
- rp.sub_func=_parse_sub_resources;
- rp.func=NULL;
- rp.userdata=this;
-
+ rp.ext_func = _parse_ext_resources;
+ rp.sub_func = _parse_sub_resources;
+ rp.func = NULL;
+ rp.userdata = this;
}
-
-
-
String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) {
- error=OK;
-
- lines=1;
- f=p_f;
+ error = OK;
- stream.f=f;
+ lines = 1;
+ f = p_f;
- ignore_resource_parsing=true;
+ stream.f = f;
+ ignore_resource_parsing = true;
VariantParser::Tag tag;
- Error err = VariantParser::parse_tag(&stream,lines,error_text,tag);
+ Error err = VariantParser::parse_tag(&stream, lines, error_text, tag);
if (err) {
_printerr();
@@ -906,30 +856,26 @@ String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) {
if (tag.fields.has("format")) {
int fmt = tag.fields["format"];
- if (fmt>FORMAT_VERSION) {
- error_text="Saved with newer format version";
+ if (fmt > FORMAT_VERSION) {
+ error_text = "Saved with newer format version";
_printerr();
return "";
}
}
- if (tag.name=="gd_scene")
+ if (tag.name == "gd_scene")
return "PackedScene";
- if (tag.name!="gd_resource")
+ if (tag.name != "gd_resource")
return "";
-
-
if (!tag.fields.has("type")) {
- error_text="Missing 'type' field in 'gd_resource' tag";
+ error_text = "Missing 'type' field in 'gd_resource' tag";
_printerr();
return "";
}
return tag.fields["type"];
-
-
}
/////////////////////
@@ -937,110 +883,102 @@ String ResourceInteractiveLoaderText::recognize(FileAccess *p_f) {
Ref<ResourceInteractiveLoader> ResourceFormatLoaderText::load_interactive(const String &p_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
+ if (err != OK) {
- if (err!=OK) {
-
- ERR_FAIL_COND_V(err!=OK,Ref<ResourceInteractiveLoader>());
+ ERR_FAIL_COND_V(err != OK, Ref<ResourceInteractiveLoader>());
}
- Ref<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) );
ria->open(f);
return ria;
}
-void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const {
+void ResourceFormatLoaderText::get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const {
- if (p_type=="") {
+ if (p_type == "") {
get_recognized_extensions(p_extensions);
return;
}
- if (p_type=="PackedScene")
+ if (p_type == "PackedScene")
p_extensions->push_back("tscn");
else
p_extensions->push_back("tres");
-
}
-void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceFormatLoaderText::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("tscn");
p_extensions->push_back("tres");
}
-bool ResourceFormatLoaderText::handles_type(const String& p_type) const{
+bool ResourceFormatLoaderText::handles_type(const String &p_type) const {
return true;
}
-String ResourceFormatLoaderText::get_resource_type(const String &p_path) const{
-
+String ResourceFormatLoaderText::get_resource_type(const String &p_path) const {
-
- String ext=p_path.get_extension().to_lower();
- if (ext=="tscn")
+ String ext = p_path.get_extension().to_lower();
+ if (ext == "tscn")
return "PackedScene";
- else if (ext!="tres")
+ else if (ext != "tres")
return String();
//for anyhting else must test..
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
return ""; //could not rwead
}
- Ref<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) );
String r = ria->recognize(f);
return r;
}
+void ResourceFormatLoaderText::get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types) {
-void ResourceFormatLoaderText::get_dependencies(const String& p_path,List<String> *p_dependencies,bool p_add_types) {
-
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
ERR_FAIL();
}
- Ref<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) );
- ria->get_dependencies(f,p_dependencies,p_add_types);
-
-
+ ria->get_dependencies(f, p_dependencies, p_add_types);
}
-Error ResourceFormatLoaderText::rename_dependencies(const String &p_path,const Map<String,String>& p_map) {
+Error ResourceFormatLoaderText::rename_dependencies(const String &p_path, const Map<String, String> &p_map) {
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
if (!f) {
ERR_FAIL_V(ERR_CANT_OPEN);
}
- Ref<ResourceInteractiveLoaderText> ria = memnew( ResourceInteractiveLoaderText );
- ria->local_path=GlobalConfig::get_singleton()->localize_path(p_path);
- ria->res_path=ria->local_path;
+ Ref<ResourceInteractiveLoaderText> ria = memnew(ResourceInteractiveLoaderText);
+ ria->local_path = GlobalConfig::get_singleton()->localize_path(p_path);
+ ria->res_path = ria->local_path;
//ria->set_local_path( GlobalConfig::get_singleton()->localize_path(p_path) );
- return ria->rename_dependencies(f,p_path,p_map);
+ return ria->rename_dependencies(f, p_path, p_map);
}
-
/*****************************************************************************************************/
/*****************************************************************************************************/
/*****************************************************************************************************/
@@ -1052,28 +990,26 @@ Error ResourceFormatLoaderText::rename_dependencies(const String &p_path,const M
/*****************************************************************************************************/
/*****************************************************************************************************/
+String ResourceFormatSaverTextInstance::_write_resources(void *ud, const RES &p_resource) {
-String ResourceFormatSaverTextInstance::_write_resources(void *ud,const RES& p_resource) {
-
- ResourceFormatSaverTextInstance *rsi=(ResourceFormatSaverTextInstance*)ud;
+ ResourceFormatSaverTextInstance *rsi = (ResourceFormatSaverTextInstance *)ud;
return rsi->_write_resource(p_resource);
-
}
-String ResourceFormatSaverTextInstance::_write_resource(const RES& res) {
+String ResourceFormatSaverTextInstance::_write_resource(const RES &res) {
if (external_resources.has(res)) {
- return "ExtResource( "+itos(external_resources[res]+1)+" )";
+ return "ExtResource( " + itos(external_resources[res] + 1) + " )";
} else {
if (internal_resources.has(res)) {
- return "SubResource( "+itos(internal_resources[res])+" )";
- } else if (res->get_path().length() && res->get_path().find("::")==-1) {
+ return "SubResource( " + itos(internal_resources[res]) + " )";
+ } else if (res->get_path().length() && res->get_path().find("::") == -1) {
//external resource
- String path=relative_paths?local_path.path_to_file(res->get_path()):res->get_path();
- return "Resource( \""+path+"\" )";
+ String path = relative_paths ? local_path.path_to_file(res->get_path()) : res->get_path();
+ return "Resource( \"" + path + "\" )";
} else {
ERR_EXPLAIN("Resource was not pre cached for the resource section, bug?");
ERR_FAIL_V("null");
@@ -1084,21 +1020,19 @@ String ResourceFormatSaverTextInstance::_write_resource(const RES& res) {
return "null";
}
-void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,bool p_main) {
-
+void ResourceFormatSaverTextInstance::_find_resources(const Variant &p_variant, bool p_main) {
- switch(p_variant.get_type()) {
+ switch (p_variant.get_type()) {
case Variant::OBJECT: {
-
RES res = p_variant.operator RefPtr();
if (res.is_null() || external_resources.has(res))
return;
- if (!p_main && (!bundle_resources ) && res->get_path().length() && res->get_path().find("::") == -1 ) {
+ if (!p_main && (!bundle_resources) && res->get_path().length() && res->get_path().find("::") == -1) {
int index = external_resources.size();
- external_resources[res]=index;
+ external_resources[res] = index;
return;
}
@@ -1107,45 +1041,45 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,b
List<PropertyInfo> property_list;
- res->get_property_list( &property_list );
+ res->get_property_list(&property_list);
property_list.sort();
- List<PropertyInfo>::Element *I=property_list.front();
+ List<PropertyInfo>::Element *I = property_list.front();
- while(I) {
+ while (I) {
- PropertyInfo pi=I->get();
+ PropertyInfo pi = I->get();
- if (pi.usage&PROPERTY_USAGE_STORAGE) {
+ if (pi.usage & PROPERTY_USAGE_STORAGE) {
- Variant v=res->get(I->get().name);
+ Variant v = res->get(I->get().name);
_find_resources(v);
}
- I=I->next();
+ I = I->next();
}
- resource_set.insert( res ); //saved after, so the childs it needs are available when loaded
+ resource_set.insert(res); //saved after, so the childs it needs are available when loaded
saved_resources.push_back(res);
} break;
case Variant::ARRAY: {
- Array varray=p_variant;
- int len=varray.size();
- for(int i=0;i<len;i++) {
+ Array varray = p_variant;
+ int len = varray.size();
+ for (int i = 0; i < len; i++) {
- Variant v=varray.get(i);
+ Variant v = varray.get(i);
_find_resources(v);
}
} break;
case Variant::DICTIONARY: {
- Dictionary d=p_variant;
+ Dictionary d = p_variant;
List<Variant> keys;
d.get_key_list(&keys);
- for(List<Variant>::Element *E=keys.front();E;E=E->next()) {
+ for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
Variant v = d[E->get()];
_find_resources(v);
@@ -1153,62 +1087,60 @@ void ResourceFormatSaverTextInstance::_find_resources(const Variant& p_variant,b
} break;
default: {}
}
-
}
-static String _valprop(const String& p_name) {
+static String _valprop(const String &p_name) {
- if (p_name.find("\"")!=-1 || p_name.find("=")!=-1 || p_name.find(" ")!=-1)
- return "\""+p_name.c_escape_multiline()+"\"";
+ if (p_name.find("\"") != -1 || p_name.find("=") != -1 || p_name.find(" ") != -1)
+ return "\"" + p_name.c_escape_multiline() + "\"";
return p_name;
}
-Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
+Error ResourceFormatSaverTextInstance::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
if (p_path.ends_with(".tscn")) {
- packed_scene=p_resource;
+ packed_scene = p_resource;
}
Error err;
- f = FileAccess::open(p_path, FileAccess::WRITE,&err);
- ERR_FAIL_COND_V( err, ERR_CANT_OPEN );
+ f = FileAccess::open(p_path, FileAccess::WRITE, &err);
+ ERR_FAIL_COND_V(err, ERR_CANT_OPEN);
FileAccessRef _fref(f);
local_path = GlobalConfig::get_singleton()->localize_path(p_path);
- relative_paths=p_flags&ResourceSaver::FLAG_RELATIVE_PATHS;
- skip_editor=p_flags&ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
- bundle_resources=p_flags&ResourceSaver::FLAG_BUNDLE_RESOURCES;
- takeover_paths=p_flags&ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
+ relative_paths = p_flags & ResourceSaver::FLAG_RELATIVE_PATHS;
+ skip_editor = p_flags & ResourceSaver::FLAG_OMIT_EDITOR_PROPERTIES;
+ bundle_resources = p_flags & ResourceSaver::FLAG_BUNDLE_RESOURCES;
+ takeover_paths = p_flags & ResourceSaver::FLAG_REPLACE_SUBRESOURCE_PATHS;
if (!p_path.begins_with("res://")) {
- takeover_paths=false;
+ takeover_paths = false;
}
// save resources
- _find_resources(p_resource,true);
+ _find_resources(p_resource, true);
if (packed_scene.is_valid()) {
//add instances to external resources if saving a packed scene
- for(int i=0;i<packed_scene->get_state()->get_node_count();i++) {
+ for (int i = 0; i < packed_scene->get_state()->get_node_count(); i++) {
if (packed_scene->get_state()->is_node_instance_placeholder(i))
continue;
- Ref<PackedScene> instance=packed_scene->get_state()->get_node_instance(i);
+ Ref<PackedScene> instance = packed_scene->get_state()->get_node_instance(i);
if (instance.is_valid() && !external_resources.has(instance)) {
int index = external_resources.size();
- external_resources[instance]=index;
+ external_resources[instance] = index;
}
}
}
-
- ERR_FAIL_COND_V(err!=OK,err);
+ ERR_FAIL_COND_V(err != OK, err);
{
- String title=packed_scene.is_valid()?"[gd_scene ":"[gd_resource ";
+ String title = packed_scene.is_valid() ? "[gd_scene " : "[gd_resource ";
if (packed_scene.is_null())
- title+="type=\""+p_resource->get_class()+"\" ";
- int load_steps=saved_resources.size()+external_resources.size();
+ title += "type=\"" + p_resource->get_class() + "\" ";
+ int load_steps = saved_resources.size() + external_resources.size();
/*
if (packed_scene.is_valid()) {
load_steps+=packed_scene->get_node_count();
@@ -1216,29 +1148,28 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
//no, better to not use load steps from nodes, no point to that
*/
- if (load_steps>1) {
- title+="load_steps="+itos(load_steps)+" ";
+ if (load_steps > 1) {
+ title += "load_steps=" + itos(load_steps) + " ";
}
- title+="format="+itos(FORMAT_VERSION)+"";
+ title += "format=" + itos(FORMAT_VERSION) + "";
//title+="engine_version=\""+itos(VERSION_MAJOR)+"."+itos(VERSION_MINOR)+"\"";
f->store_string(title);
f->store_line("]\n"); //one empty line
}
-
Vector<RES> sorted_er;
sorted_er.resize(external_resources.size());
- for(Map<RES,int>::Element *E=external_resources.front();E;E=E->next()) {
+ for (Map<RES, int>::Element *E = external_resources.front(); E; E = E->next()) {
- sorted_er[E->get()]=E->key();
+ sorted_er[E->get()] = E->key();
}
- for(int i=0;i<sorted_er.size();i++) {
+ for (int i = 0; i < sorted_er.size(); i++) {
String p = sorted_er[i]->get_path();
- f->store_string("[ext_resource path=\""+p+"\" type=\""+sorted_er[i]->get_save_class()+"\" id="+itos(i+1)+"]\n"); //bundled
+ f->store_string("[ext_resource path=\"" + p + "\" type=\"" + sorted_er[i]->get_save_class() + "\" id=" + itos(i + 1) + "]\n"); //bundled
}
if (external_resources.size())
@@ -1246,12 +1177,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
Set<int> used_indices;
- for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {
+ for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
RES res = E->get();
- if (E->next() && (res->get_path()=="" || res->get_path().find("::") != -1 )) {
+ if (E->next() && (res->get_path() == "" || res->get_path().find("::") != -1)) {
- if (res->get_subindex()!=0) {
+ if (res->get_subindex() != 0) {
if (used_indices.has(res->get_subindex())) {
res->set_subindex(0); //repeated
} else {
@@ -1261,11 +1192,11 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
}
}
- for(List<RES>::Element *E=saved_resources.front();E;E=E->next()) {
+ for (List<RES>::Element *E = saved_resources.front(); E; E = E->next()) {
RES res = E->get();
ERR_CONTINUE(!resource_set.has(res));
- bool main = (E->next()==NULL);
+ bool main = (E->next() == NULL);
if (main && packed_scene.is_valid())
break; //save as a scene
@@ -1273,11 +1204,11 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
if (main) {
f->store_line("[resource]\n");
} else {
- String line="[sub_resource ";
- if (res->get_subindex()==0) {
- int new_subindex=1;
+ String line = "[sub_resource ";
+ if (res->get_subindex() == 0) {
+ int new_subindex = 1;
if (used_indices.size()) {
- new_subindex=used_indices.back()->get()+1;
+ new_subindex = used_indices.back()->get() + 1;
}
res->set_subindex(new_subindex);
@@ -1285,97 +1216,87 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
}
int idx = res->get_subindex();
- line+="type=\""+res->get_class()+"\" id="+itos(idx);
- f->store_line(line+"]\n");
+ line += "type=\"" + res->get_class() + "\" id=" + itos(idx);
+ f->store_line(line + "]\n");
if (takeover_paths) {
- res->set_path(p_path+"::"+itos(idx),true);
+ res->set_path(p_path + "::" + itos(idx), true);
}
- internal_resources[res]=idx;
+ internal_resources[res] = idx;
#ifdef TOOLS_ENABLED
res->set_edited(false);
#endif
-
-
}
-
List<PropertyInfo> property_list;
res->get_property_list(&property_list);
//property_list.sort();
- for(List<PropertyInfo>::Element *PE = property_list.front();PE;PE=PE->next()) {
-
+ for (List<PropertyInfo>::Element *PE = property_list.front(); PE; PE = PE->next()) {
if (skip_editor && PE->get().name.begins_with("__editor"))
continue;
- if (PE->get().usage&PROPERTY_USAGE_STORAGE) {
+ if (PE->get().usage & PROPERTY_USAGE_STORAGE) {
String name = PE->get().name;
Variant value = res->get(name);
-
- if ((PE->get().usage&PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero())||(PE->get().usage&PROPERTY_USAGE_STORE_IF_NONONE && value.is_one()) )
+ if ((PE->get().usage & PROPERTY_USAGE_STORE_IF_NONZERO && value.is_zero()) || (PE->get().usage & PROPERTY_USAGE_STORE_IF_NONONE && value.is_one()))
continue;
- if (PE->get().type==Variant::OBJECT && value.is_zero() && !(PE->get().usage&PROPERTY_USAGE_STORE_IF_NULL))
+ if (PE->get().type == Variant::OBJECT && value.is_zero() && !(PE->get().usage & PROPERTY_USAGE_STORE_IF_NULL))
continue;
String vars;
- VariantWriter::write_to_string(value,vars,_write_resources,this);
- f->store_string(_valprop(name)+" = "+vars+"\n");
+ VariantWriter::write_to_string(value, vars, _write_resources, this);
+ f->store_string(_valprop(name) + " = " + vars + "\n");
}
-
-
}
f->store_string("\n");
-
}
if (packed_scene.is_valid()) {
//if this is a scene, save nodes and connections!
Ref<SceneState> state = packed_scene->get_state();
- for(int i=0;i<state->get_node_count();i++) {
+ for (int i = 0; i < state->get_node_count(); i++) {
StringName type = state->get_node_type(i);
StringName name = state->get_node_name(i);
- NodePath path = state->get_node_path(i,true);
+ NodePath path = state->get_node_path(i, true);
NodePath owner = state->get_node_owner_path(i);
Ref<PackedScene> instance = state->get_node_instance(i);
String instance_placeholder = state->get_node_instance_placeholder(i);
Vector<StringName> groups = state->get_node_groups(i);
-
-
- String header="[node";
- header+=" name=\""+String(name)+"\"";
- if (type!=StringName()) {
- header+=" type=\""+String(type)+"\"";
+ String header = "[node";
+ header += " name=\"" + String(name) + "\"";
+ if (type != StringName()) {
+ header += " type=\"" + String(type) + "\"";
}
- if (path!=NodePath()) {
- header+=" parent=\""+String(path.simplified())+"\"";
+ if (path != NodePath()) {
+ header += " parent=\"" + String(path.simplified()) + "\"";
}
- if (owner!=NodePath() && owner!=NodePath(".")) {
- header+=" owner=\""+String(owner.simplified())+"\"";
+ if (owner != NodePath() && owner != NodePath(".")) {
+ header += " owner=\"" + String(owner.simplified()) + "\"";
}
if (groups.size()) {
- String sgroups=" groups=[\n";
- for(int j=0;j<groups.size();j++) {
- sgroups+="\""+String(groups[j]).c_escape()+"\",\n";
+ String sgroups = " groups=[\n";
+ for (int j = 0; j < groups.size(); j++) {
+ sgroups += "\"" + String(groups[j]).c_escape() + "\",\n";
}
- sgroups+="]";
- header+=sgroups;
+ sgroups += "]";
+ header += sgroups;
}
f->store_string(header);
- if (instance_placeholder!=String()) {
+ if (instance_placeholder != String()) {
String vars;
f->store_string(" instance_placeholder=");
- VariantWriter::write_to_string(instance_placeholder,vars,_write_resources,this);
+ VariantWriter::write_to_string(instance_placeholder, vars, _write_resources, this);
f->store_string(vars);
}
@@ -1383,47 +1304,44 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
String vars;
f->store_string(" instance=");
- VariantWriter::write_to_string(instance,vars,_write_resources,this);
+ VariantWriter::write_to_string(instance, vars, _write_resources, this);
f->store_string(vars);
-
}
f->store_line("]\n");
- for(int j=0;j<state->get_node_property_count(i);j++) {
+ for (int j = 0; j < state->get_node_property_count(i); j++) {
String vars;
- VariantWriter::write_to_string(state->get_node_property_value(i,j),vars,_write_resources,this);
+ VariantWriter::write_to_string(state->get_node_property_value(i, j), vars, _write_resources, this);
- f->store_string(_valprop(String(state->get_node_property_name(i,j)))+" = "+vars+"\n");
+ f->store_string(_valprop(String(state->get_node_property_name(i, j))) + " = " + vars + "\n");
}
if (state->get_node_property_count(i)) {
//add space
f->store_line(String());
}
-
}
- for(int i=0;i<state->get_connection_count();i++) {
+ for (int i = 0; i < state->get_connection_count(); i++) {
- String connstr="[connection";
- connstr+=" signal=\""+String(state->get_connection_signal(i))+"\"";
- connstr+=" from=\""+String(state->get_connection_source(i).simplified())+"\"";
- connstr+=" to=\""+String(state->get_connection_target(i).simplified())+"\"";
- connstr+=" method=\""+String(state->get_connection_method(i))+"\"";
+ String connstr = "[connection";
+ connstr += " signal=\"" + String(state->get_connection_signal(i)) + "\"";
+ connstr += " from=\"" + String(state->get_connection_source(i).simplified()) + "\"";
+ connstr += " to=\"" + String(state->get_connection_target(i).simplified()) + "\"";
+ connstr += " method=\"" + String(state->get_connection_method(i)) + "\"";
int flags = state->get_connection_flags(i);
- if (flags!=Object::CONNECT_PERSIST) {
- connstr+=" flags="+itos(flags);
+ if (flags != Object::CONNECT_PERSIST) {
+ connstr += " flags=" + itos(flags);
}
- Array binds=state->get_connection_binds(i);
+ Array binds = state->get_connection_binds(i);
f->store_string(connstr);
if (binds.size()) {
String vars;
- VariantWriter::write_to_string(binds,vars,_write_resources,this);
- f->store_string(" binds= "+vars);
-
+ VariantWriter::write_to_string(binds, vars, _write_resources, this);
+ f->store_string(" binds= " + vars);
}
f->store_line("]\n");
@@ -1432,12 +1350,12 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
f->store_line(String());
Vector<NodePath> editable_instances = state->get_editable_instances();
- for(int i=0;i<editable_instances.size();i++) {
- f->store_line("[editable path=\""+editable_instances[i].operator String()+"\"]");
+ for (int i = 0; i < editable_instances.size(); i++) {
+ f->store_line("[editable path=\"" + editable_instances[i].operator String() + "\"]");
}
}
- if (f->get_error()!=OK && f->get_error()!=ERR_FILE_EOF) {
+ if (f->get_error() != OK && f->get_error() != ERR_FILE_EOF) {
f->close();
return ERR_CANT_CREATE;
}
@@ -1448,34 +1366,29 @@ Error ResourceFormatSaverTextInstance::save(const String &p_path,const RES& p_re
return OK;
}
+Error ResourceFormatSaverText::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
-
-Error ResourceFormatSaverText::save(const String &p_path,const RES& p_resource,uint32_t p_flags) {
-
- if (p_path.ends_with(".sct") && p_resource->get_class()!="PackedScene") {
+ if (p_path.ends_with(".sct") && p_resource->get_class() != "PackedScene") {
return ERR_FILE_UNRECOGNIZED;
}
ResourceFormatSaverTextInstance saver;
- return saver.save(p_path,p_resource,p_flags);
-
+ return saver.save(p_path, p_resource, p_flags);
}
-bool ResourceFormatSaverText::recognize(const RES& p_resource) const {
-
+bool ResourceFormatSaverText::recognize(const RES &p_resource) const {
return true; // all recognized!
}
-void ResourceFormatSaverText::get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const {
+void ResourceFormatSaverText::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
- if (p_resource->get_class()=="PackedScene")
+ if (p_resource->get_class() == "PackedScene")
p_extensions->push_back("tscn"); //text scene
else
p_extensions->push_back("tres"); //text resource
-
}
-ResourceFormatSaverText* ResourceFormatSaverText::singleton=NULL;
+ResourceFormatSaverText *ResourceFormatSaverText::singleton = NULL;
ResourceFormatSaverText::ResourceFormatSaverText() {
- singleton=this;
+ singleton = this;
}
diff --git a/scene/resources/scene_format_text.h b/scene/resources/scene_format_text.h
index ce18f6a702..99e7de6232 100644
--- a/scene/resources/scene_format_text.h
+++ b/scene/resources/scene_format_text.h
@@ -35,8 +35,6 @@
#include "scene/resources/packed_scene.h"
#include "variant_parser.h"
-
-
class ResourceInteractiveLoaderText : public ResourceInteractiveLoader {
String local_path;
@@ -52,7 +50,6 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader {
String type;
};
-
bool is_scene;
String res_type;
@@ -60,7 +57,7 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader {
//Map<String,String> remaps;
- Map<int,ExtResource> ext_resources;
+ Map<int, ExtResource> ext_resources;
int resources_total;
int resource_current;
@@ -70,22 +67,20 @@ class ResourceInteractiveLoaderText : public ResourceInteractiveLoader {
mutable int lines;
- Map<String,String> remaps;
+ Map<String, String> remaps;
//void _printerr();
- static Error _parse_sub_resources(void* p_self, VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText*>(p_self)->_parse_sub_resource(p_stream,r_res,line,r_err_str); }
- static Error _parse_ext_resources(void* p_self, VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText*>(p_self)->_parse_ext_resource(p_stream,r_res,line,r_err_str); }
+ static Error _parse_sub_resources(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText *>(p_self)->_parse_sub_resource(p_stream, r_res, line, r_err_str); }
+ static Error _parse_ext_resources(void *p_self, VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str) { return reinterpret_cast<ResourceInteractiveLoaderText *>(p_self)->_parse_ext_resource(p_stream, r_res, line, r_err_str); }
- Error _parse_sub_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str);
- Error _parse_ext_resource(VariantParser::Stream* p_stream,Ref<Resource>& r_res,int &line,String &r_err_str);
+ Error _parse_sub_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str);
+ Error _parse_ext_resource(VariantParser::Stream *p_stream, Ref<Resource> &r_res, int &line, String &r_err_str);
VariantParser::ResourceParser rp;
-
Ref<PackedScene> packed_scene;
-
-friend class ResourceFormatLoaderText;
+ friend class ResourceFormatLoaderText;
List<RES> resource_cache;
Error error;
@@ -93,41 +88,32 @@ friend class ResourceFormatLoaderText;
RES resource;
public:
-
- virtual void set_local_path(const String& p_local_path);
+ virtual void set_local_path(const String &p_local_path);
virtual Ref<Resource> get_resource();
virtual Error poll();
virtual int get_stage() const;
virtual int get_stage_count() const;
- void open(FileAccess *p_f, bool p_skip_first_tag=false);
+ void open(FileAccess *p_f, bool p_skip_first_tag = false);
String recognize(FileAccess *p_f);
void get_dependencies(FileAccess *p_f, List<String> *p_dependencies, bool p_add_types);
- Error rename_dependencies(FileAccess *p_f, const String &p_path,const Map<String,String>& p_map);
-
+ Error rename_dependencies(FileAccess *p_f, const String &p_path, const Map<String, String> &p_map);
~ResourceInteractiveLoaderText();
-
};
-
-
class ResourceFormatLoaderText : public ResourceFormatLoader {
public:
-
- virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path,Error *r_error=NULL);
- virtual void get_recognized_extensions_for_type(const String& p_type,List<String> *p_extensions) const;
+ virtual Ref<ResourceInteractiveLoader> load_interactive(const String &p_path, Error *r_error = NULL);
+ virtual void get_recognized_extensions_for_type(const String &p_type, List<String> *p_extensions) const;
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
- virtual void get_dependencies(const String& p_path, List<String> *p_dependencies, bool p_add_types=false);
- virtual Error rename_dependencies(const String &p_path,const Map<String,String>& p_map);
-
-
+ virtual void get_dependencies(const String &p_path, List<String> *p_dependencies, bool p_add_types = false);
+ virtual Error rename_dependencies(const String &p_path, const Map<String, String> &p_map);
};
-
-class ResourceFormatSaverTextInstance {
+class ResourceFormatSaverTextInstance {
String local_path;
@@ -140,31 +126,26 @@ class ResourceFormatSaverTextInstance {
FileAccess *f;
Set<RES> resource_set;
List<RES> saved_resources;
- Map<RES,int> external_resources;
- Map<RES,int> internal_resources;
-
- void _find_resources(const Variant& p_variant,bool p_main=false);
+ Map<RES, int> external_resources;
+ Map<RES, int> internal_resources;
- static String _write_resources(void *ud,const RES& p_resource);
- String _write_resource(const RES& res);
+ void _find_resources(const Variant &p_variant, bool p_main = false);
+ static String _write_resources(void *ud, const RES &p_resource);
+ String _write_resource(const RES &res);
public:
-
- Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
-
-
+ Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
};
class ResourceFormatSaverText : public ResourceFormatSaver {
public:
- static ResourceFormatSaverText* singleton;
- virtual Error save(const String &p_path,const RES& p_resource,uint32_t p_flags=0);
- virtual bool recognize(const RES& p_resource) const;
- virtual void get_recognized_extensions(const RES& p_resource,List<String> *p_extensions) const;
+ static ResourceFormatSaverText *singleton;
+ virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0);
+ virtual bool recognize(const RES &p_resource) const;
+ virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const;
ResourceFormatSaverText();
};
-
#endif // SCENE_FORMAT_TEXT_H
diff --git a/scene/resources/segment_shape_2d.cpp b/scene/resources/segment_shape_2d.cpp
index fbe1efe5d1..7a1114f895 100644
--- a/scene/resources/segment_shape_2d.cpp
+++ b/scene/resources/segment_shape_2d.cpp
@@ -34,138 +34,119 @@
void SegmentShape2D::_update_shape() {
Rect2 r;
- r.pos=a;
- r.size=b;
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),r);
+ r.pos = a;
+ r.size = b;
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), r);
emit_changed();
-
}
-void SegmentShape2D::set_a(const Vector2& p_a) {
+void SegmentShape2D::set_a(const Vector2 &p_a) {
- a=p_a;
+ a = p_a;
_update_shape();
-
}
Vector2 SegmentShape2D::get_a() const {
return a;
}
-void SegmentShape2D::set_b(const Vector2& p_b) {
+void SegmentShape2D::set_b(const Vector2 &p_b) {
- b=p_b;
+ b = p_b;
_update_shape();
-
}
Vector2 SegmentShape2D::get_b() const {
return b;
}
-void SegmentShape2D::draw(const RID& p_to_rid,const Color& p_color) {
+void SegmentShape2D::draw(const RID &p_to_rid, const Color &p_color) {
- VisualServer::get_singleton()->canvas_item_add_line(p_to_rid,a,b,p_color,3);
+ VisualServer::get_singleton()->canvas_item_add_line(p_to_rid, a, b, p_color, 3);
}
-Rect2 SegmentShape2D::get_rect() const{
+Rect2 SegmentShape2D::get_rect() const {
Rect2 rect;
- rect.pos=a;
+ rect.pos = a;
rect.expand_to(b);
return rect;
-
}
-
-
-
void SegmentShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_a","a"),&SegmentShape2D::set_a);
- ClassDB::bind_method(D_METHOD("get_a"),&SegmentShape2D::get_a);
-
- ClassDB::bind_method(D_METHOD("set_b","b"),&SegmentShape2D::set_b);
- ClassDB::bind_method(D_METHOD("get_b"),&SegmentShape2D::get_b);
-
+ ClassDB::bind_method(D_METHOD("set_a", "a"), &SegmentShape2D::set_a);
+ ClassDB::bind_method(D_METHOD("get_a"), &SegmentShape2D::get_a);
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"a"),"set_a","get_a") ;
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"b"),"set_b","get_b") ;
+ ClassDB::bind_method(D_METHOD("set_b", "b"), &SegmentShape2D::set_b);
+ ClassDB::bind_method(D_METHOD("get_b"), &SegmentShape2D::get_b);
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "a"), "set_a", "get_a");
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "b"), "set_b", "get_b");
}
-SegmentShape2D::SegmentShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_SEGMENT)) {
+SegmentShape2D::SegmentShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_SEGMENT)) {
- a=Vector2();
- b=Vector2(0,10);
+ a = Vector2();
+ b = Vector2(0, 10);
_update_shape();
}
-
////////////////////////////////////////////////////////////
-
void RayShape2D::_update_shape() {
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),length);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), length);
emit_changed();
-
}
+void RayShape2D::draw(const RID &p_to_rid, const Color &p_color) {
-void RayShape2D::draw(const RID& p_to_rid,const Color& p_color) {
-
-
- Vector2 tip = Vector2(0,get_length());
- VS::get_singleton()->canvas_item_add_line(p_to_rid,Vector2(),tip,p_color,3);
+ Vector2 tip = Vector2(0, get_length());
+ VS::get_singleton()->canvas_item_add_line(p_to_rid, Vector2(), tip, p_color, 3);
Vector<Vector2> pts;
- float tsize=4;
- pts.push_back(tip+Vector2(0,tsize));
- pts.push_back(tip+Vector2(0.707*tsize,0));
- pts.push_back(tip+Vector2(-0.707*tsize,0));
+ float tsize = 4;
+ pts.push_back(tip + Vector2(0, tsize));
+ pts.push_back(tip + Vector2(0.707 * tsize, 0));
+ pts.push_back(tip + Vector2(-0.707 * tsize, 0));
Vector<Color> cols;
- for(int i=0;i<3;i++)
+ for (int i = 0; i < 3; i++)
cols.push_back(p_color);
- VS::get_singleton()->canvas_item_add_primitive(p_to_rid,pts,cols,Vector<Point2>(),RID());
-
-
-
+ VS::get_singleton()->canvas_item_add_primitive(p_to_rid, pts, cols, Vector<Point2>(), RID());
}
Rect2 RayShape2D::get_rect() const {
Rect2 rect;
- rect.pos=Vector2();
- rect.expand_to(Vector2(0,length));
- rect=rect.grow(0.707*4);
+ rect.pos = Vector2();
+ rect.expand_to(Vector2(0, length));
+ rect = rect.grow(0.707 * 4);
return rect;
}
-
void RayShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_length","length"),&RayShape2D::set_length);
- ClassDB::bind_method(D_METHOD("get_length"),&RayShape2D::get_length);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"length"),"set_length","get_length") ;
+ ClassDB::bind_method(D_METHOD("set_length", "length"), &RayShape2D::set_length);
+ ClassDB::bind_method(D_METHOD("get_length"), &RayShape2D::get_length);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "length"), "set_length", "get_length");
}
void RayShape2D::set_length(real_t p_length) {
- length=p_length;
+ length = p_length;
_update_shape();
}
real_t RayShape2D::get_length() const {
return length;
-
-
}
-RayShape2D::RayShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RAY)) {
+RayShape2D::RayShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_RAY)) {
- length=20;
+ length = 20;
_update_shape();
}
diff --git a/scene/resources/segment_shape_2d.h b/scene/resources/segment_shape_2d.h
index 775bdabe9d..e58ce6be60 100644
--- a/scene/resources/segment_shape_2d.h
+++ b/scene/resources/segment_shape_2d.h
@@ -32,49 +32,46 @@
#include "scene/resources/shape_2d.h"
class SegmentShape2D : public Shape2D {
- GDCLASS( SegmentShape2D, Shape2D );
+ GDCLASS(SegmentShape2D, Shape2D);
Vector2 a;
Vector2 b;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
- void set_a(const Vector2& p_a);
- void set_b(const Vector2& p_b);
+public:
+ void set_a(const Vector2 &p_a);
+ void set_b(const Vector2 &p_b);
Vector2 get_a() const;
Vector2 get_b() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
virtual Rect2 get_rect() const;
SegmentShape2D();
};
-
class RayShape2D : public Shape2D {
- GDCLASS( RayShape2D, Shape2D );
-
+ GDCLASS(RayShape2D, Shape2D);
real_t length;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
+public:
void set_length(real_t p_length);
real_t get_length() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
virtual Rect2 get_rect() const;
RayShape2D();
};
-
#endif // SEGMENT_SHAPE_2D_H
diff --git a/scene/resources/shader.cpp b/scene/resources/shader.cpp
index 375a9a1cb0..fd058a4a6f 100644
--- a/scene/resources/shader.cpp
+++ b/scene/resources/shader.cpp
@@ -27,50 +27,45 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "shader.h"
-#include "servers/visual_server.h"
-#include "texture.h"
#include "os/file_access.h"
#include "scene/scene_string_names.h"
-
-
+#include "servers/visual_server.h"
+#include "texture.h"
Shader::Mode Shader::get_mode() const {
return mode;
}
-void Shader::set_code(const String& p_code) {
+void Shader::set_code(const String &p_code) {
- VisualServer::get_singleton()->shader_set_code(shader,p_code);
- params_cache_dirty=true;
+ VisualServer::get_singleton()->shader_set_code(shader, p_code);
+ params_cache_dirty = true;
emit_signal(SceneStringNames::get_singleton()->changed);
}
-
String Shader::get_code() const {
return VisualServer::get_singleton()->shader_get_code(shader);
}
-
void Shader::get_param_list(List<PropertyInfo> *p_params) const {
-
List<PropertyInfo> local;
- VisualServer::get_singleton()->shader_get_param_list(shader,&local);
+ VisualServer::get_singleton()->shader_get_param_list(shader, &local);
params_cache.clear();
- params_cache_dirty=false;
+ params_cache_dirty = false;
- for(List<PropertyInfo>::Element *E=local.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = local.front(); E; E = E->next()) {
- PropertyInfo pi=E->get();
- pi.name="shader_param/"+pi.name;
- params_cache[pi.name]=E->get().name;
+ PropertyInfo pi = E->get();
+ pi.name = "shader_param/" + pi.name;
+ params_cache[pi.name] = E->get().name;
if (p_params) {
//small little hack
- if (pi.type==Variant::_RID)
- pi.type=Variant::OBJECT;
+ if (pi.type == Variant::_RID)
+ pi.type = Variant::OBJECT;
p_params->push_back(pi);
}
}
@@ -81,19 +76,18 @@ RID Shader::get_rid() const {
return shader;
}
-
-void Shader::set_default_texture_param(const StringName& p_param,const Ref<Texture>& p_texture) {
+void Shader::set_default_texture_param(const StringName &p_param, const Ref<Texture> &p_texture) {
if (p_texture.is_valid()) {
- default_textures[p_param]=p_texture;
- VS::get_singleton()->shader_set_default_texture_param(shader,p_param,p_texture->get_rid());
+ default_textures[p_param] = p_texture;
+ VS::get_singleton()->shader_set_default_texture_param(shader, p_param, p_texture->get_rid());
} else {
default_textures.erase(p_param);
- VS::get_singleton()->shader_set_default_texture_param(shader,p_param,RID());
+ VS::get_singleton()->shader_set_default_texture_param(shader, p_param, RID());
}
}
-Ref<Texture> Shader::get_default_texture_param(const StringName& p_param) const{
+Ref<Texture> Shader::get_default_texture_param(const StringName &p_param) const {
if (default_textures.has(p_param))
return default_textures[p_param];
@@ -101,52 +95,47 @@ Ref<Texture> Shader::get_default_texture_param(const StringName& p_param) const{
return Ref<Texture>();
}
-void Shader::get_default_texture_param_list(List<StringName>* r_textures) const{
+void Shader::get_default_texture_param_list(List<StringName> *r_textures) const {
- for(const Map<StringName,Ref<Texture> >::Element *E=default_textures.front();E;E=E->next()) {
+ for (const Map<StringName, Ref<Texture> >::Element *E = default_textures.front(); E; E = E->next()) {
r_textures->push_back(E->key());
}
-
}
-bool Shader::has_param(const StringName& p_param) const {
+bool Shader::has_param(const StringName &p_param) const {
return params_cache.has(p_param);
}
void Shader::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_mode"),&Shader::get_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &Shader::get_mode);
- ClassDB::bind_method(D_METHOD("set_code","code"),&Shader::set_code);
- ClassDB::bind_method(D_METHOD("get_code"),&Shader::get_code);
+ ClassDB::bind_method(D_METHOD("set_code", "code"), &Shader::set_code);
+ ClassDB::bind_method(D_METHOD("get_code"), &Shader::get_code);
- ClassDB::bind_method(D_METHOD("set_default_texture_param","param","texture:Texture"),&Shader::set_default_texture_param);
- ClassDB::bind_method(D_METHOD("get_default_texture_param:Texture","param"),&Shader::get_default_texture_param);
+ ClassDB::bind_method(D_METHOD("set_default_texture_param", "param", "texture:Texture"), &Shader::set_default_texture_param);
+ ClassDB::bind_method(D_METHOD("get_default_texture_param:Texture", "param"), &Shader::get_default_texture_param);
- ClassDB::bind_method(D_METHOD("has_param","name"),&Shader::has_param);
+ ClassDB::bind_method(D_METHOD("has_param", "name"), &Shader::has_param);
//ClassDB::bind_method(D_METHOD("get_param_list"),&Shader::get_fragment_code);
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "code", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_code", "get_code");
- ADD_PROPERTY( PropertyInfo(Variant::STRING, "code",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "set_code", "get_code") ;
-
- BIND_CONSTANT( MODE_SPATIAL);
- BIND_CONSTANT( MODE_CANVAS_ITEM );
- BIND_CONSTANT( MODE_PARTICLES );
-
+ BIND_CONSTANT(MODE_SPATIAL);
+ BIND_CONSTANT(MODE_CANVAS_ITEM);
+ BIND_CONSTANT(MODE_PARTICLES);
}
Shader::Shader(Mode p_mode) {
- mode=p_mode;
+ mode = p_mode;
shader = VisualServer::get_singleton()->shader_create(VS::ShaderMode(p_mode));
- params_cache_dirty=true;
+ params_cache_dirty = true;
}
Shader::~Shader() {
VisualServer::get_singleton()->free(shader);
}
-
-
diff --git a/scene/resources/shader.h b/scene/resources/shader.h
index 59d7601d98..b7fa349dfe 100644
--- a/scene/resources/shader.h
+++ b/scene/resources/shader.h
@@ -29,14 +29,14 @@
#ifndef SHADER_H
#define SHADER_H
-#include "resource.h"
#include "io/resource_loader.h"
+#include "resource.h"
#include "scene/resources/texture.h"
class Shader : public Resource {
- GDCLASS(Shader,Resource);
- OBJ_SAVE_TYPE( Shader );
+ GDCLASS(Shader, Resource);
+ OBJ_SAVE_TYPE(Shader);
RES_BASE_EXTENSION("shd");
public:
@@ -47,6 +47,7 @@ public:
MODE_PARTICLES,
MODE_MAX
};
+
private:
RID shader;
Mode mode;
@@ -55,37 +56,31 @@ private:
// shaders keep a list of ShaderMaterial -> VisualServer name translations, to make
// convertion fast and save memory.
mutable bool params_cache_dirty;
- mutable Map<StringName,StringName> params_cache; //map a shader param to a material param..
- Map<StringName,Ref<Texture> > default_textures;
-
-
+ mutable Map<StringName, StringName> params_cache; //map a shader param to a material param..
+ Map<StringName, Ref<Texture> > default_textures;
protected:
-
-
-
static void _bind_methods();
-public:
-
+public:
//void set_mode(Mode p_mode);
Mode get_mode() const;
- void set_code( const String& p_code);
+ void set_code(const String &p_code);
String get_code() const;
void get_param_list(List<PropertyInfo> *p_params) const;
- bool has_param(const StringName& p_param) const;
+ bool has_param(const StringName &p_param) const;
- void set_default_texture_param(const StringName& p_param, const Ref<Texture> &p_texture);
- Ref<Texture> get_default_texture_param(const StringName& p_param) const;
- void get_default_texture_param_list(List<StringName>* r_textures) const;
+ void set_default_texture_param(const StringName &p_param, const Ref<Texture> &p_texture);
+ Ref<Texture> get_default_texture_param(const StringName &p_param) const;
+ void get_default_texture_param_list(List<StringName> *r_textures) const;
- _FORCE_INLINE_ StringName remap_param(const StringName& p_param) const {
+ _FORCE_INLINE_ StringName remap_param(const StringName &p_param) const {
if (params_cache_dirty)
get_param_list(NULL);
- const Map<StringName,StringName>::Element *E=params_cache.find(p_param);
+ const Map<StringName, StringName>::Element *E = params_cache.find(p_param);
if (E)
return E->get();
return StringName();
@@ -95,38 +90,35 @@ public:
Shader(Mode p_mode);
~Shader();
-
};
-VARIANT_ENUM_CAST( Shader::Mode );
+VARIANT_ENUM_CAST(Shader::Mode);
class SpatialShader : public Shader {
- GDCLASS(SpatialShader,Shader);
+ GDCLASS(SpatialShader, Shader);
public:
-
- SpatialShader() : Shader(MODE_SPATIAL) {};
+ SpatialShader()
+ : Shader(MODE_SPATIAL){};
};
class CanvasItemShader : public Shader {
- GDCLASS(CanvasItemShader,Shader);
+ GDCLASS(CanvasItemShader, Shader);
public:
-
- CanvasItemShader() : Shader(MODE_CANVAS_ITEM) {};
+ CanvasItemShader()
+ : Shader(MODE_CANVAS_ITEM){};
};
-
class ParticlesShader : public Shader {
- GDCLASS(ParticlesShader,Shader);
+ GDCLASS(ParticlesShader, Shader);
public:
-
- ParticlesShader() : Shader(MODE_PARTICLES) {};
+ ParticlesShader()
+ : Shader(MODE_PARTICLES){};
};
-
#endif // SHADER_H
diff --git a/scene/resources/shader_graph.cpp b/scene/resources/shader_graph.cpp
index c21feb0bf5..49e987727d 100644
--- a/scene/resources/shader_graph.cpp
+++ b/scene/resources/shader_graph.cpp
@@ -397,7 +397,6 @@ void ShaderGraph::_bind_methods() {
ADD_SIGNAL(MethodInfo("updated"));
-
#if 0
ClassDB::bind_method(D_METHOD("node_add"),&ShaderGraph::node_add );
ClassDB::bind_method(D_METHOD("node_remove"),&ShaderGraph::node_remove );
@@ -2076,32 +2075,32 @@ void ShaderGraph::_add_node_code(ShaderType p_type,Node *p_node,const Vector<Str
const char *typestr[4]={"float","vec3","mat4","texture"};
-#define OUTNAME(id,slot) (String(typestr[get_node_output_slot_type(get_mode(),p_type,p_node->type,slot)])+" "+("nd"+itos(id)+"sl"+itos(slot)))
-#define OUTVAR(id,slot) ("nd"+itos(id)+"sl"+itos(slot))
-#define DEF_VEC(slot)\
- if (p_inputs[slot].ends_with("def")){\
- Vector3 v = p_node->defaults[slot];\
- code+=String(typestr[1])+" "+p_inputs[slot]+"=vec3("+v+");\n";\
+#define OUTNAME(id, slot) (String(typestr[get_node_output_slot_type(get_mode(), p_type, p_node->type, slot)]) + " " + ("nd" + itos(id) + "sl" + itos(slot)))
+#define OUTVAR(id, slot) ("nd" + itos(id) + "sl" + itos(slot))
+#define DEF_VEC(slot) \
+ if (p_inputs[slot].ends_with("def")) { \
+ Vector3 v = p_node->defaults[slot]; \
+ code += String(typestr[1]) + " " + p_inputs[slot] + "=vec3(" + v + ");\n"; \
}
-#define DEF_SCALAR(slot)\
- if (p_inputs[slot].ends_with("def")){\
- double v = p_node->defaults[slot];\
- code+=String(typestr[0])+" "+p_inputs[slot]+"="+rtos(v)+";\n";\
+#define DEF_SCALAR(slot) \
+ if (p_inputs[slot].ends_with("def")) { \
+ double v = p_node->defaults[slot]; \
+ code += String(typestr[0]) + " " + p_inputs[slot] + "=" + rtos(v) + ";\n"; \
}
-#define DEF_COLOR(slot)\
- if (p_inputs[slot].ends_with("def")){\
- Color col = p_node->defaults[slot];\
- code+=String(typestr[1])+" "+p_inputs[slot]+"=vec3("+rtos(col.r)+","+rtos(col.g)+","+rtos(col.b)+");\n";\
+#define DEF_COLOR(slot) \
+ if (p_inputs[slot].ends_with("def")) { \
+ Color col = p_node->defaults[slot]; \
+ code += String(typestr[1]) + " " + p_inputs[slot] + "=vec3(" + rtos(col.r) + "," + rtos(col.g) + "," + rtos(col.b) + ");\n"; \
}
-#define DEF_MATRIX(slot) \
- if (p_inputs[slot].ends_with("def")){\
- Transform xf = p_node->defaults[slot]; \
- code+=String(typestr[2])+" "+p_inputs[slot]+"=mat4(\n";\
- code+="\tvec4(vec3("+rtos(xf.basis.get_axis(0).x)+","+rtos(xf.basis.get_axis(0).y)+","+rtos(xf.basis.get_axis(0).z)+"),0),\n";\
- code+="\tvec4(vec3("+rtos(xf.basis.get_axis(1).x)+","+rtos(xf.basis.get_axis(1).y)+","+rtos(xf.basis.get_axis(1).z)+"),0),\n";\
- code+="\tvec4(vec3("+rtos(xf.basis.get_axis(2).x)+","+rtos(xf.basis.get_axis(2).y)+","+rtos(xf.basis.get_axis(2).z)+"),0),\n";\
- code+="\tvec4(vec3("+rtos(xf.origin.x)+","+rtos(xf.origin.y)+","+rtos(xf.origin.z)+"),1)\n";\
- code+=");\n";\
+#define DEF_MATRIX(slot) \
+ if (p_inputs[slot].ends_with("def")) { \
+ Transform xf = p_node->defaults[slot]; \
+ code += String(typestr[2]) + " " + p_inputs[slot] + "=mat4(\n"; \
+ code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(0).x) + "," + rtos(xf.basis.get_axis(0).y) + "," + rtos(xf.basis.get_axis(0).z) + "),0),\n"; \
+ code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(1).x) + "," + rtos(xf.basis.get_axis(1).y) + "," + rtos(xf.basis.get_axis(1).z) + "),0),\n"; \
+ code += "\tvec4(vec3(" + rtos(xf.basis.get_axis(2).x) + "," + rtos(xf.basis.get_axis(2).y) + "," + rtos(xf.basis.get_axis(2).z) + "),0),\n"; \
+ code += "\tvec4(vec3(" + rtos(xf.origin.x) + "," + rtos(xf.origin.y) + "," + rtos(xf.origin.z) + "),1)\n"; \
+ code += ");\n"; \
}
switch(p_node->type) {
diff --git a/scene/resources/shader_graph.h b/scene/resources/shader_graph.h
index f4e24dbe78..190d76fce6 100644
--- a/scene/resources/shader_graph.h
+++ b/scene/resources/shader_graph.h
@@ -29,7 +29,6 @@
#ifndef SHADER_GRAPH_H
#define SHADER_GRAPH_H
-
#if 0
#include "map.h"
#include "scene/resources/shader.h"
diff --git a/scene/resources/shape.cpp b/scene/resources/shape.cpp
index a90c3b47a9..c666ff0cd3 100644
--- a/scene/resources/shape.cpp
+++ b/scene/resources/shape.cpp
@@ -28,25 +28,23 @@
/*************************************************************************/
#include "shape.h"
-#include "servers/physics_server.h"
-#include "scene/resources/mesh.h"
#include "os/os.h"
#include "scene/main/scene_main_loop.h"
+#include "scene/resources/mesh.h"
+#include "servers/physics_server.h"
-
-void Shape::add_vertices_to_array(PoolVector<Vector3> &array, const Transform& p_xform) {
+void Shape::add_vertices_to_array(PoolVector<Vector3> &array, const Transform &p_xform) {
Vector<Vector3> toadd = _gen_debug_mesh_lines();
if (toadd.size()) {
- int base=array.size();
- array.resize(base+toadd.size());
+ int base = array.size();
+ array.resize(base + toadd.size());
PoolVector<Vector3>::Write w = array.write();
- for(int i=0;i<toadd.size();i++) {
- w[i+base]=p_xform.xform(toadd[i]);
+ for (int i = 0; i < toadd.size(); i++) {
+ w[i + base] = p_xform.xform(toadd[i]);
}
-
}
}
@@ -65,46 +63,39 @@ Ref<Mesh> Shape::get_debug_mesh() {
array.resize(lines.size());
{
- PoolVector<Vector3>::Write w=array.write();
- for(int i=0;i<lines.size();i++) {
- w[i]=lines[i];
+ PoolVector<Vector3>::Write w = array.write();
+ for (int i = 0; i < lines.size(); i++) {
+ w[i] = lines[i];
}
}
Array arr;
arr.resize(Mesh::ARRAY_MAX);
- arr[Mesh::ARRAY_VERTEX]=array;
+ arr[Mesh::ARRAY_VERTEX] = array;
- SceneTree *st=OS::get_singleton()->get_main_loop()->cast_to<SceneTree>();
+ SceneTree *st = OS::get_singleton()->get_main_loop()->cast_to<SceneTree>();
- debug_mesh_cache->add_surface_from_arrays(Mesh::PRIMITIVE_LINES,arr);
+ debug_mesh_cache->add_surface_from_arrays(Mesh::PRIMITIVE_LINES, arr);
if (st) {
- debug_mesh_cache->surface_set_material(0,st->get_debug_collision_material());
+ debug_mesh_cache->surface_set_material(0, st->get_debug_collision_material());
}
-
}
-
-
return debug_mesh_cache;
-
}
Shape::Shape() {
ERR_PRINT("Constructor must not be called!");
-
}
-
Shape::Shape(RID p_shape) {
- shape=p_shape;
+ shape = p_shape;
}
Shape::~Shape() {
PhysicsServer::get_singleton()->free(shape);
}
-
diff --git a/scene/resources/shape.h b/scene/resources/shape.h
index 29a93b642c..8a8ecf1228 100644
--- a/scene/resources/shape.h
+++ b/scene/resources/shape.h
@@ -34,26 +34,24 @@ class Mesh;
class Shape : public Resource {
- GDCLASS( Shape, Resource );
- OBJ_SAVE_TYPE( Shape );
+ GDCLASS(Shape, Resource);
+ OBJ_SAVE_TYPE(Shape);
RES_BASE_EXTENSION("shp");
RID shape;
Ref<Mesh> debug_mesh_cache;
protected:
-
_FORCE_INLINE_ RID get_shape() const { return shape; }
Shape(RID p_shape);
- virtual Vector<Vector3> _gen_debug_mesh_lines()=0;// { return Vector<Vector3>(); }
+ virtual Vector<Vector3> _gen_debug_mesh_lines() = 0; // { return Vector<Vector3>(); }
public:
-
virtual RID get_rid() const { return shape; }
Ref<Mesh> get_debug_mesh();
- void add_vertices_to_array(PoolVector<Vector3> &array, const Transform& p_xform);
+ void add_vertices_to_array(PoolVector<Vector3> &array, const Transform &p_xform);
Shape();
~Shape();
diff --git a/scene/resources/shape_2d.cpp b/scene/resources/shape_2d.cpp
index ec1568e218..497110c6f9 100644
--- a/scene/resources/shape_2d.cpp
+++ b/scene/resources/shape_2d.cpp
@@ -33,96 +33,84 @@ RID Shape2D::get_rid() const {
return shape;
}
-
void Shape2D::set_custom_solver_bias(real_t p_bias) {
- custom_bias=p_bias;
- Physics2DServer::get_singleton()->shape_set_custom_solver_bias(shape,custom_bias);
+ custom_bias = p_bias;
+ Physics2DServer::get_singleton()->shape_set_custom_solver_bias(shape, custom_bias);
}
-real_t Shape2D::get_custom_solver_bias() const{
+real_t Shape2D::get_custom_solver_bias() const {
return custom_bias;
-
}
+bool Shape2D::collide_with_motion(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) {
-bool Shape2D::collide_with_motion(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_shape_motion) {
-
- ERR_FAIL_COND_V(p_shape.is_null(),false);
+ ERR_FAIL_COND_V(p_shape.is_null(), false);
int r;
- return Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,p_local_motion,p_shape->get_rid(),p_shape_xform,p_shape_motion,NULL,0,r);
+ return Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, p_local_motion, p_shape->get_rid(), p_shape_xform, p_shape_motion, NULL, 0, r);
}
-bool Shape2D::collide(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform){
- ERR_FAIL_COND_V(p_shape.is_null(),false);
+bool Shape2D::collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) {
+ ERR_FAIL_COND_V(p_shape.is_null(), false);
int r;
- return Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,Vector2(),p_shape->get_rid(),p_shape_xform,Vector2(),NULL,0,r);
-
-
+ return Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), NULL, 0, r);
}
-Variant Shape2D::collide_with_motion_and_get_contacts(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_shape_motion){
+Variant Shape2D::collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_shape_motion) {
- ERR_FAIL_COND_V(p_shape.is_null(),Variant());
+ ERR_FAIL_COND_V(p_shape.is_null(), Variant());
const int max_contacts = 16;
- Vector2 result[max_contacts*2];
- int contacts=0;
+ Vector2 result[max_contacts * 2];
+ int contacts = 0;
- if (!Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,p_local_motion,p_shape->get_rid(),p_shape_xform,p_shape_motion,result,max_contacts,contacts))
+ if (!Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, p_local_motion, p_shape->get_rid(), p_shape_xform, p_shape_motion, result, max_contacts, contacts))
return Variant();
Array results;
- results.resize(contacts*2);
- for(int i=0;i<contacts;i++) {
- results[i]=result[i];
+ results.resize(contacts * 2);
+ for (int i = 0; i < contacts; i++) {
+ results[i] = result[i];
}
return results;
-
}
-Variant Shape2D::collide_and_get_contacts(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform){
+Variant Shape2D::collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform) {
- ERR_FAIL_COND_V(p_shape.is_null(),Variant());
+ ERR_FAIL_COND_V(p_shape.is_null(), Variant());
const int max_contacts = 16;
- Vector2 result[max_contacts*2];
- int contacts=0;
+ Vector2 result[max_contacts * 2];
+ int contacts = 0;
- if (!Physics2DServer::get_singleton()->shape_collide(get_rid(),p_local_xform,Vector2(),p_shape->get_rid(),p_shape_xform,Vector2(),result,max_contacts,contacts))
+ if (!Physics2DServer::get_singleton()->shape_collide(get_rid(), p_local_xform, Vector2(), p_shape->get_rid(), p_shape_xform, Vector2(), result, max_contacts, contacts))
return Variant();
Array results;
- results.resize(contacts*2);
- for(int i=0;i<contacts;i++) {
- results[i]=result[i];
+ results.resize(contacts * 2);
+ for (int i = 0; i < contacts; i++) {
+ results[i] = result[i];
}
return results;
-
-
}
void Shape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_custom_solver_bias","bias"),&Shape2D::set_custom_solver_bias);
- ClassDB::bind_method(D_METHOD("get_custom_solver_bias"),&Shape2D::get_custom_solver_bias);
- ClassDB::bind_method(D_METHOD("collide","local_xform","with_shape:Shape2D","shape_xform"),&Shape2D::collide);
- ClassDB::bind_method(D_METHOD("collide_with_motion","local_xform","local_motion","with_shape:Shape2D","shape_xform","shape_motion"),&Shape2D::collide_with_motion);
- ClassDB::bind_method(D_METHOD("collide_and_get_contacts:Variant","local_xform","with_shape:Shape2D","shape_xform"),&Shape2D::collide_and_get_contacts);
- ClassDB::bind_method(D_METHOD("collide_with_motion_and_get_contacts:Variant","local_xform","local_motion","with_shape:Shape2D","shape_xform","shape_motion"),&Shape2D::collide_with_motion_and_get_contacts);
+ ClassDB::bind_method(D_METHOD("set_custom_solver_bias", "bias"), &Shape2D::set_custom_solver_bias);
+ ClassDB::bind_method(D_METHOD("get_custom_solver_bias"), &Shape2D::get_custom_solver_bias);
+ ClassDB::bind_method(D_METHOD("collide", "local_xform", "with_shape:Shape2D", "shape_xform"), &Shape2D::collide);
+ ClassDB::bind_method(D_METHOD("collide_with_motion", "local_xform", "local_motion", "with_shape:Shape2D", "shape_xform", "shape_motion"), &Shape2D::collide_with_motion);
+ ClassDB::bind_method(D_METHOD("collide_and_get_contacts:Variant", "local_xform", "with_shape:Shape2D", "shape_xform"), &Shape2D::collide_and_get_contacts);
+ ClassDB::bind_method(D_METHOD("collide_with_motion_and_get_contacts:Variant", "local_xform", "local_motion", "with_shape:Shape2D", "shape_xform", "shape_motion"), &Shape2D::collide_with_motion_and_get_contacts);
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"custom_solver_bias",PROPERTY_HINT_RANGE,"0,1,0.001"),"set_custom_solver_bias","get_custom_solver_bias");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "custom_solver_bias", PROPERTY_HINT_RANGE, "0,1,0.001"), "set_custom_solver_bias", "get_custom_solver_bias");
}
-
-
-Shape2D::Shape2D(const RID& p_rid) {
- shape=p_rid;
- custom_bias=0;
+Shape2D::Shape2D(const RID &p_rid) {
+ shape = p_rid;
+ custom_bias = 0;
}
-
-
Shape2D::~Shape2D() {
Physics2DServer::get_singleton()->free(shape);
diff --git a/scene/resources/shape_2d.h b/scene/resources/shape_2d.h
index 6a7ec03a9a..afae74c385 100644
--- a/scene/resources/shape_2d.h
+++ b/scene/resources/shape_2d.h
@@ -32,28 +32,27 @@
#include "resource.h"
class Shape2D : public Resource {
- GDCLASS( Shape2D, Resource );
- OBJ_SAVE_TYPE( Shape2D );
+ GDCLASS(Shape2D, Resource);
+ OBJ_SAVE_TYPE(Shape2D);
RID shape;
real_t custom_bias;
-protected:
-
+protected:
static void _bind_methods();
- Shape2D(const RID& p_rid);
-public:
+ Shape2D(const RID &p_rid);
+public:
void set_custom_solver_bias(real_t p_bias);
real_t get_custom_solver_bias() const;
- bool collide_with_motion(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_p_shape_motion);
- bool collide(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform);
+ bool collide_with_motion(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_p_shape_motion);
+ bool collide(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform);
- Variant collide_with_motion_and_get_contacts(const Transform2D& p_local_xform, const Vector2& p_local_motion, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform, const Vector2 &p_p_shape_motion);
- Variant collide_and_get_contacts(const Transform2D& p_local_xform, const Ref<Shape2D>& p_shape, const Transform2D& p_shape_xform);
+ Variant collide_with_motion_and_get_contacts(const Transform2D &p_local_xform, const Vector2 &p_local_motion, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform, const Vector2 &p_p_shape_motion);
+ Variant collide_and_get_contacts(const Transform2D &p_local_xform, const Ref<Shape2D> &p_shape, const Transform2D &p_shape_xform);
- virtual void draw(const RID& p_to_rid,const Color& p_color) {}
+ virtual void draw(const RID &p_to_rid, const Color &p_color) {}
virtual Rect2 get_rect() const { return Rect2(); }
virtual RID get_rid() const;
Shape2D();
diff --git a/scene/resources/shape_line_2d.cpp b/scene/resources/shape_line_2d.cpp
index 64e50e62c8..777dbead52 100644
--- a/scene/resources/shape_line_2d.cpp
+++ b/scene/resources/shape_line_2d.cpp
@@ -34,23 +34,20 @@ void LineShape2D::_update_shape() {
Array arr;
arr.push_back(normal);
arr.push_back(d);
- Physics2DServer::get_singleton()->shape_set_data(get_rid(),arr);
+ Physics2DServer::get_singleton()->shape_set_data(get_rid(), arr);
emit_changed();
-
}
-void LineShape2D::set_normal(const Vector2& p_normal) {
+void LineShape2D::set_normal(const Vector2 &p_normal) {
- normal=p_normal;
+ normal = p_normal;
_update_shape();
-
}
void LineShape2D::set_d(real_t p_d) {
- d=p_d;
+ d = p_d;
_update_shape();
-
}
Vector2 LineShape2D::get_normal() const {
@@ -62,48 +59,45 @@ real_t LineShape2D::get_d() const {
return d;
}
-
-void LineShape2D::draw(const RID& p_to_rid,const Color& p_color) {
+void LineShape2D::draw(const RID &p_to_rid, const Color &p_color) {
Vector2 point = get_d() * get_normal();
- Vector2 l1[2]={point-get_normal().tangent()*100,point+get_normal().tangent()*100};
- VS::get_singleton()->canvas_item_add_line(p_to_rid,l1[0],l1[1],p_color,3);
- Vector2 l2[2]={point,point+get_normal()*30};
- VS::get_singleton()->canvas_item_add_line(p_to_rid,l2[0],l2[1],p_color,3);
-
+ Vector2 l1[2] = { point - get_normal().tangent() * 100, point + get_normal().tangent() * 100 };
+ VS::get_singleton()->canvas_item_add_line(p_to_rid, l1[0], l1[1], p_color, 3);
+ Vector2 l2[2] = { point, point + get_normal() * 30 };
+ VS::get_singleton()->canvas_item_add_line(p_to_rid, l2[0], l2[1], p_color, 3);
}
-Rect2 LineShape2D::get_rect() const{
+Rect2 LineShape2D::get_rect() const {
Vector2 point = get_d() * get_normal();
- Vector2 l1[2]={point-get_normal().tangent()*100,point+get_normal().tangent()*100};
- Vector2 l2[2]={point,point+get_normal()*30};
+ Vector2 l1[2] = { point - get_normal().tangent() * 100, point + get_normal().tangent() * 100 };
+ Vector2 l2[2] = { point, point + get_normal() * 30 };
Rect2 rect;
- rect.pos=l1[0];
+ rect.pos = l1[0];
rect.expand_to(l1[1]);
rect.expand_to(l2[0]);
rect.expand_to(l2[1]);
return rect;
-
}
void LineShape2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_normal","normal"),&LineShape2D::set_normal);
- ClassDB::bind_method(D_METHOD("get_normal"),&LineShape2D::get_normal);
-
- ClassDB::bind_method(D_METHOD("set_d","d"),&LineShape2D::set_d);
- ClassDB::bind_method(D_METHOD("get_d"),&LineShape2D::get_d);
+ ClassDB::bind_method(D_METHOD("set_normal", "normal"), &LineShape2D::set_normal);
+ ClassDB::bind_method(D_METHOD("get_normal"), &LineShape2D::get_normal);
- ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"normal"),"set_normal","get_normal") ;
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"d"),"set_d","get_d") ;
+ ClassDB::bind_method(D_METHOD("set_d", "d"), &LineShape2D::set_d);
+ ClassDB::bind_method(D_METHOD("get_d"), &LineShape2D::get_d);
+ ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "normal"), "set_normal", "get_normal");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "d"), "set_d", "get_d");
}
-LineShape2D::LineShape2D() : Shape2D( Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_LINE)) {
+LineShape2D::LineShape2D()
+ : Shape2D(Physics2DServer::get_singleton()->shape_create(Physics2DServer::SHAPE_LINE)) {
- normal=Vector2(0,-1);
- d=0;
+ normal = Vector2(0, -1);
+ d = 0;
_update_shape();
}
diff --git a/scene/resources/shape_line_2d.h b/scene/resources/shape_line_2d.h
index abad5f6a24..cd62504d81 100644
--- a/scene/resources/shape_line_2d.h
+++ b/scene/resources/shape_line_2d.h
@@ -32,24 +32,24 @@
#include "scene/resources/shape_2d.h"
class LineShape2D : public Shape2D {
- GDCLASS( LineShape2D, Shape2D );
+ GDCLASS(LineShape2D, Shape2D);
Vector2 normal;
real_t d;
void _update_shape();
-protected:
+protected:
static void _bind_methods();
-public:
- void set_normal(const Vector2& p_normal);
+public:
+ void set_normal(const Vector2 &p_normal);
void set_d(real_t p_d);
Vector2 get_normal() const;
real_t get_d() const;
- virtual void draw(const RID& p_to_rid,const Color& p_color);
+ virtual void draw(const RID &p_to_rid, const Color &p_color);
virtual Rect2 get_rect() const;
LineShape2D();
diff --git a/scene/resources/sky_box.cpp b/scene/resources/sky_box.cpp
index 0f8a1e5339..cb3b1cf60d 100644
--- a/scene/resources/sky_box.cpp
+++ b/scene/resources/sky_box.cpp
@@ -29,11 +29,10 @@
#include "sky_box.h"
#include "io/image_loader.h"
-
void SkyBox::set_radiance_size(RadianceSize p_size) {
- ERR_FAIL_INDEX(p_size,RADIANCE_SIZE_MAX);
+ ERR_FAIL_INDEX(p_size, RADIANCE_SIZE_MAX);
- radiance_size=p_size;
+ radiance_size = p_size;
_radiance_changed();
}
@@ -44,94 +43,87 @@ SkyBox::RadianceSize SkyBox::get_radiance_size() const {
void SkyBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radiance_size","size"),&SkyBox::set_radiance_size);
- ClassDB::bind_method(D_METHOD("get_radiance_size"),&SkyBox::get_radiance_size);
-
- ADD_PROPERTY(PropertyInfo(Variant::INT,"radiance_size",PROPERTY_HINT_ENUM,"256,512,1024,2048"),"set_radiance_size","get_radiance_size");
+ ClassDB::bind_method(D_METHOD("set_radiance_size", "size"), &SkyBox::set_radiance_size);
+ ClassDB::bind_method(D_METHOD("get_radiance_size"), &SkyBox::get_radiance_size);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "radiance_size", PROPERTY_HINT_ENUM, "256,512,1024,2048"), "set_radiance_size", "get_radiance_size");
- BIND_CONSTANT( RADIANCE_SIZE_256 );
- BIND_CONSTANT( RADIANCE_SIZE_512 );
- BIND_CONSTANT( RADIANCE_SIZE_1024 );
- BIND_CONSTANT( RADIANCE_SIZE_2048 );
- BIND_CONSTANT( RADIANCE_SIZE_MAX );
+ BIND_CONSTANT(RADIANCE_SIZE_256);
+ BIND_CONSTANT(RADIANCE_SIZE_512);
+ BIND_CONSTANT(RADIANCE_SIZE_1024);
+ BIND_CONSTANT(RADIANCE_SIZE_2048);
+ BIND_CONSTANT(RADIANCE_SIZE_MAX);
}
-SkyBox::SkyBox()
-{
- radiance_size=RADIANCE_SIZE_512;
+SkyBox::SkyBox() {
+ radiance_size = RADIANCE_SIZE_512;
}
/////////////////////////////////////////
-
-
void ImageSkyBox::_radiance_changed() {
if (cube_map_valid) {
- static const int size[RADIANCE_SIZE_MAX]={
- 256,512,1024,2048
+ static const int size[RADIANCE_SIZE_MAX] = {
+ 256, 512, 1024, 2048
};
- VS::get_singleton()->skybox_set_texture(sky_box,cube_map,size[get_radiance_size()]);
+ VS::get_singleton()->skybox_set_texture(sky_box, cube_map, size[get_radiance_size()]);
}
}
-void ImageSkyBox::set_image_path(ImagePath p_image,const String &p_path) {
+void ImageSkyBox::set_image_path(ImagePath p_image, const String &p_path) {
- ERR_FAIL_INDEX(p_image,IMAGE_PATH_MAX);
- image_path[p_image]=p_path;
+ ERR_FAIL_INDEX(p_image, IMAGE_PATH_MAX);
+ image_path[p_image] = p_path;
- bool all_ok=true;
- for(int i=0;i<IMAGE_PATH_MAX;i++) {
- if (image_path[i]==String()) {
- all_ok=false;
+ bool all_ok = true;
+ for (int i = 0; i < IMAGE_PATH_MAX; i++) {
+ if (image_path[i] == String()) {
+ all_ok = false;
}
}
- cube_map_valid=false;
+ cube_map_valid = false;
if (all_ok) {
Image images[IMAGE_PATH_MAX];
- int w=0,h=0;
+ int w = 0, h = 0;
Image::Format format;
- for(int i=0;i<IMAGE_PATH_MAX;i++) {
- Error err = ImageLoader::load_image(image_path[i],&images[i]);
+ for (int i = 0; i < IMAGE_PATH_MAX; i++) {
+ Error err = ImageLoader::load_image(image_path[i], &images[i]);
if (err) {
- ERR_PRINTS("Error loading image for skybox: "+image_path[i]);
+ ERR_PRINTS("Error loading image for skybox: " + image_path[i]);
return;
}
- if (i==0) {
- w=images[0].get_width();
- h=images[0].get_height();
- format=images[0].get_format();
+ if (i == 0) {
+ w = images[0].get_width();
+ h = images[0].get_height();
+ format = images[0].get_format();
} else {
- if (images[i].get_width()!=w || images[i].get_height()!=h || images[i].get_format()!=format) {
- ERR_PRINTS("Image size mismatch ("+itos(images[i].get_width())+","+itos(images[i].get_height())+":"+Image::get_format_name(images[i].get_format())+" when it should be "+itos(w)+","+itos(h)+":"+Image::get_format_name(format)+"): "+image_path[i]);
+ if (images[i].get_width() != w || images[i].get_height() != h || images[i].get_format() != format) {
+ ERR_PRINTS("Image size mismatch (" + itos(images[i].get_width()) + "," + itos(images[i].get_height()) + ":" + Image::get_format_name(images[i].get_format()) + " when it should be " + itos(w) + "," + itos(h) + ":" + Image::get_format_name(format) + "): " + image_path[i]);
return;
}
}
}
- VS::get_singleton()->texture_allocate(cube_map,w,h,format,VS::TEXTURE_FLAG_FILTER|VS::TEXTURE_FLAG_CUBEMAP|VS::TEXTURE_FLAG_MIPMAPS);
- for(int i=0;i<IMAGE_PATH_MAX;i++) {
- VS::get_singleton()->texture_set_data(cube_map,images[i],VS::CubeMapSide(i));
+ VS::get_singleton()->texture_allocate(cube_map, w, h, format, VS::TEXTURE_FLAG_FILTER | VS::TEXTURE_FLAG_CUBEMAP | VS::TEXTURE_FLAG_MIPMAPS);
+ for (int i = 0; i < IMAGE_PATH_MAX; i++) {
+ VS::get_singleton()->texture_set_data(cube_map, images[i], VS::CubeMapSide(i));
}
- cube_map_valid=true;
+ cube_map_valid = true;
_radiance_changed();
}
-
-
}
String ImageSkyBox::get_image_path(ImagePath p_image) const {
- ERR_FAIL_INDEX_V(p_image,IMAGE_PATH_MAX,String());
+ ERR_FAIL_INDEX_V(p_image, IMAGE_PATH_MAX, String());
return image_path[p_image];
-
}
RID ImageSkyBox::get_rid() const {
@@ -141,42 +133,41 @@ RID ImageSkyBox::get_rid() const {
void ImageSkyBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_image_path","image","path"),&ImageSkyBox::set_image_path);
- ClassDB::bind_method(D_METHOD("get_image_path","image"),&ImageSkyBox::get_image_path);
+ ClassDB::bind_method(D_METHOD("set_image_path", "image", "path"), &ImageSkyBox::set_image_path);
+ ClassDB::bind_method(D_METHOD("get_image_path", "image"), &ImageSkyBox::get_image_path);
List<String> extensions;
ImageLoader::get_recognized_extensions(&extensions);
String hints;
- for(List<String>::Element *E=extensions.front();E;E=E->next()) {
- if (hints!=String()) {
- hints+=",";
+ for (List<String>::Element *E = extensions.front(); E; E = E->next()) {
+ if (hints != String()) {
+ hints += ",";
}
- hints+="*."+E->get();
+ hints += "*." + E->get();
}
- ADD_GROUP("Image Path","image_path_");
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_x",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_X);
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_x",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_X);
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_y",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_y",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_Y);
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_z",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_NEGATIVE_Z);
- ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_z",PROPERTY_HINT_FILE,hints),"set_image_path","get_image_path",IMAGE_PATH_POSITIVE_Z);
-
- BIND_CONSTANT( IMAGE_PATH_NEGATIVE_X );
- BIND_CONSTANT( IMAGE_PATH_POSITIVE_X );
- BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Y );
- BIND_CONSTANT( IMAGE_PATH_POSITIVE_Y );
- BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Z );
- BIND_CONSTANT( IMAGE_PATH_POSITIVE_Z );
- BIND_CONSTANT( IMAGE_PATH_MAX );
-
+ ADD_GROUP("Image Path", "image_path_");
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_x", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_X);
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_x", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_X);
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_y", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_Y);
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_y", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_Y);
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_negative_z", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_NEGATIVE_Z);
+ ADD_PROPERTYI(PropertyInfo(Variant::STRING, "image_path_positive_z", PROPERTY_HINT_FILE, hints), "set_image_path", "get_image_path", IMAGE_PATH_POSITIVE_Z);
+
+ BIND_CONSTANT(IMAGE_PATH_NEGATIVE_X);
+ BIND_CONSTANT(IMAGE_PATH_POSITIVE_X);
+ BIND_CONSTANT(IMAGE_PATH_NEGATIVE_Y);
+ BIND_CONSTANT(IMAGE_PATH_POSITIVE_Y);
+ BIND_CONSTANT(IMAGE_PATH_NEGATIVE_Z);
+ BIND_CONSTANT(IMAGE_PATH_POSITIVE_Z);
+ BIND_CONSTANT(IMAGE_PATH_MAX);
}
ImageSkyBox::ImageSkyBox() {
- cube_map=VS::get_singleton()->texture_create();
- sky_box=VS::get_singleton()->skybox_create();
- cube_map_valid=false;
+ cube_map = VS::get_singleton()->texture_create();
+ sky_box = VS::get_singleton()->skybox_create();
+ cube_map_valid = false;
}
ImageSkyBox::~ImageSkyBox() {
@@ -184,4 +175,3 @@ ImageSkyBox::~ImageSkyBox() {
VS::get_singleton()->free(cube_map);
VS::get_singleton()->free(sky_box);
}
-
diff --git a/scene/resources/sky_box.h b/scene/resources/sky_box.h
index 171782d132..23ba077df3 100644
--- a/scene/resources/sky_box.h
+++ b/scene/resources/sky_box.h
@@ -32,10 +32,9 @@
#include "scene/resources/texture.h"
class SkyBox : public Resource {
- GDCLASS(SkyBox,Resource);
+ GDCLASS(SkyBox, Resource);
public:
-
enum RadianceSize {
RADIANCE_SIZE_256,
RADIANCE_SIZE_512,
@@ -43,14 +42,15 @@ public:
RADIANCE_SIZE_2048,
RADIANCE_SIZE_MAX
};
-private:
+private:
RadianceSize radiance_size;
+
protected:
static void _bind_methods();
- virtual void _radiance_changed()=0;
-public:
+ virtual void _radiance_changed() = 0;
+public:
void set_radiance_size(RadianceSize p_size);
RadianceSize get_radiance_size() const;
SkyBox();
@@ -58,12 +58,10 @@ public:
VARIANT_ENUM_CAST(SkyBox::RadianceSize)
-
class ImageSkyBox : public SkyBox {
- GDCLASS(ImageSkyBox,SkyBox);
+ GDCLASS(ImageSkyBox, SkyBox);
public:
-
enum ImagePath {
IMAGE_PATH_NEGATIVE_X,
IMAGE_PATH_POSITIVE_X,
@@ -73,17 +71,19 @@ public:
IMAGE_PATH_POSITIVE_Z,
IMAGE_PATH_MAX
};
+
private:
RID cube_map;
RID sky_box;
bool cube_map_valid;
String image_path[IMAGE_PATH_MAX];
+
protected:
static void _bind_methods();
virtual void _radiance_changed();
-public:
+public:
void set_image_path(ImagePath p_image, const String &p_path);
String get_image_path(ImagePath p_image) const;
@@ -95,5 +95,4 @@ public:
VARIANT_ENUM_CAST(ImageSkyBox::ImagePath)
-
#endif // SKYBOX_H
diff --git a/scene/resources/space_2d.cpp b/scene/resources/space_2d.cpp
index f1fe9629dd..d0a18b98bd 100644
--- a/scene/resources/space_2d.cpp
+++ b/scene/resources/space_2d.cpp
@@ -33,11 +33,10 @@ RID Space2D::get_rid() const {
return space;
}
-
void Space2D::set_active(bool p_active) {
- active=p_active;
- Physics2DServer::get_singleton()->space_set_active(space,active);
+ active = p_active;
+ Physics2DServer::get_singleton()->space_set_active(space, active);
}
bool Space2D::is_active() const {
@@ -45,24 +44,21 @@ bool Space2D::is_active() const {
return active;
}
-
void Space2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_active","active"),&Space2D::set_active);
- ClassDB::bind_method(D_METHOD("is_active"),&Space2D::is_active);
-
- ADD_PROPERTY( PropertyInfo(Variant::BOOL,"active"),"set_active","is_active") ;
+ ClassDB::bind_method(D_METHOD("set_active", "active"), &Space2D::set_active);
+ ClassDB::bind_method(D_METHOD("is_active"), &Space2D::is_active);
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active");
}
Space2D::Space2D() {
- active=false;
- space=Physics2DServer::get_singleton()->space_create();
+ active = false;
+ space = Physics2DServer::get_singleton()->space_create();
}
Space2D::~Space2D() {
Physics2DServer::get_singleton()->free(space);
}
-
diff --git a/scene/resources/space_2d.h b/scene/resources/space_2d.h
index 82aef89c07..b6c2607b13 100644
--- a/scene/resources/space_2d.h
+++ b/scene/resources/space_2d.h
@@ -29,21 +29,19 @@
#ifndef SPACE_2D_H
#define SPACE_2D_H
-#include "servers/physics_2d_server.h"
#include "resource.h"
-
+#include "servers/physics_2d_server.h"
class Space2D : public Resource {
- GDCLASS(Space2D,Resource);
+ GDCLASS(Space2D, Resource);
bool active;
RID space;
-protected:
+protected:
static void _bind_methods();
-public:
-
+public:
void set_active(bool p_active);
bool is_active() const;
diff --git a/scene/resources/sphere_shape.cpp b/scene/resources/sphere_shape.cpp
index 3029625928..c242e748a4 100644
--- a/scene/resources/sphere_shape.cpp
+++ b/scene/resources/sphere_shape.cpp
@@ -31,24 +31,23 @@
Vector<Vector3> SphereShape::_gen_debug_mesh_lines() {
- float r=get_radius();
+ float r = get_radius();
Vector<Vector3> points;
- for(int i=0;i<=360;i++) {
+ for (int i = 0; i <= 360; i++) {
- float ra=Math::deg2rad((float)i);
- float rb=Math::deg2rad((float)i+1);
- Point2 a = Vector2(Math::sin(ra),Math::cos(ra))*r;
- Point2 b = Vector2(Math::sin(rb),Math::cos(rb))*r;
-
- points.push_back(Vector3(a.x,0,a.y));
- points.push_back(Vector3(b.x,0,b.y));
- points.push_back(Vector3(0,a.x,a.y));
- points.push_back(Vector3(0,b.x,b.y));
- points.push_back(Vector3(a.x,a.y,0));
- points.push_back(Vector3(b.x,b.y,0));
+ float ra = Math::deg2rad((float)i);
+ float rb = Math::deg2rad((float)i + 1);
+ Point2 a = Vector2(Math::sin(ra), Math::cos(ra)) * r;
+ Point2 b = Vector2(Math::sin(rb), Math::cos(rb)) * r;
+ points.push_back(Vector3(a.x, 0, a.y));
+ points.push_back(Vector3(b.x, 0, b.y));
+ points.push_back(Vector3(0, a.x, a.y));
+ points.push_back(Vector3(0, b.x, b.y));
+ points.push_back(Vector3(a.x, a.y, 0));
+ points.push_back(Vector3(b.x, b.y, 0));
}
return points;
@@ -56,12 +55,12 @@ Vector<Vector3> SphereShape::_gen_debug_mesh_lines() {
void SphereShape::_update_shape() {
- PhysicsServer::get_singleton()->shape_set_data(get_shape(),radius);
+ PhysicsServer::get_singleton()->shape_set_data(get_shape(), radius);
}
void SphereShape::set_radius(float p_radius) {
- radius=p_radius;
+ radius = p_radius;
_update_shape();
notify_change_to_owners();
_change_notify("radius");
@@ -72,17 +71,16 @@ float SphereShape::get_radius() const {
return radius;
}
-
void SphereShape::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_radius","radius"),&SphereShape::set_radius);
- ClassDB::bind_method(D_METHOD("get_radius"),&SphereShape::get_radius);
-
- ADD_PROPERTY( PropertyInfo(Variant::REAL,"radius",PROPERTY_HINT_RANGE,"0,4096,0.01"), "set_radius", "get_radius");
+ ClassDB::bind_method(D_METHOD("set_radius", "radius"), &SphereShape::set_radius);
+ ClassDB::bind_method(D_METHOD("get_radius"), &SphereShape::get_radius);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "radius", PROPERTY_HINT_RANGE, "0,4096,0.01"), "set_radius", "get_radius");
}
-SphereShape::SphereShape() : Shape( PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_SPHERE)) {
+SphereShape::SphereShape()
+ : Shape(PhysicsServer::get_singleton()->shape_create(PhysicsServer::SHAPE_SPHERE)) {
set_radius(1.0);
}
diff --git a/scene/resources/sphere_shape.h b/scene/resources/sphere_shape.h
index 990564be80..576c59ee7d 100644
--- a/scene/resources/sphere_shape.h
+++ b/scene/resources/sphere_shape.h
@@ -29,22 +29,20 @@
#ifndef SPHERE_SHAPE_H
#define SPHERE_SHAPE_H
-
#include "scene/resources/shape.h"
class SphereShape : public Shape {
- GDCLASS(SphereShape,Shape);
+ GDCLASS(SphereShape, Shape);
float radius;
protected:
-
static void _bind_methods();
virtual void _update_shape();
virtual Vector<Vector3> _gen_debug_mesh_lines();
-public:
+public:
void set_radius(float p_radius);
float get_radius() const;
diff --git a/scene/resources/style_box.cpp b/scene/resources/style_box.cpp
index 34a4202942..7a503207bc 100644
--- a/scene/resources/style_box.cpp
+++ b/scene/resources/style_box.cpp
@@ -28,25 +28,24 @@
/*************************************************************************/
#include "style_box.h"
-bool StyleBox::test_mask(const Point2& p_point, const Rect2& p_rect) const {
+bool StyleBox::test_mask(const Point2 &p_point, const Rect2 &p_rect) const {
return true;
}
void StyleBox::set_default_margin(Margin p_margin, float p_value) {
- margin[p_margin]=p_value;
+ margin[p_margin] = p_value;
emit_changed();
-
}
-float StyleBox::get_default_margin(Margin p_margin) const{
+float StyleBox::get_default_margin(Margin p_margin) const {
return margin[p_margin];
}
float StyleBox::get_margin(Margin p_margin) const {
- if (margin[p_margin]<0)
+ if (margin[p_margin] < 0)
return get_style_margin(p_margin);
else
return margin[p_margin];
@@ -54,13 +53,12 @@ float StyleBox::get_margin(Margin p_margin) const {
Size2 StyleBox::get_minimum_size() const {
- return Size2( get_margin( MARGIN_LEFT) + get_margin( MARGIN_RIGHT ) , get_margin( MARGIN_TOP) + get_margin( MARGIN_BOTTOM ) );
+ return Size2(get_margin(MARGIN_LEFT) + get_margin(MARGIN_RIGHT), get_margin(MARGIN_TOP) + get_margin(MARGIN_BOTTOM));
}
-
Point2 StyleBox::get_offset() const {
- return Point2( get_margin( MARGIN_LEFT), get_margin( MARGIN_TOP) );
+ return Point2(get_margin(MARGIN_LEFT), get_margin(MARGIN_TOP));
}
Size2 StyleBox::get_center_size() const {
@@ -70,58 +68,53 @@ Size2 StyleBox::get_center_size() const {
void StyleBox::_bind_methods() {
- ClassDB::bind_method(D_METHOD("test_mask","point","rect"),&StyleBox::test_mask);
+ ClassDB::bind_method(D_METHOD("test_mask", "point", "rect"), &StyleBox::test_mask);
- ClassDB::bind_method(D_METHOD("set_default_margin","margin","offset"),&StyleBox::set_default_margin);
- ClassDB::bind_method(D_METHOD("get_default_margin","margin"),&StyleBox::get_default_margin);
+ ClassDB::bind_method(D_METHOD("set_default_margin", "margin", "offset"), &StyleBox::set_default_margin);
+ ClassDB::bind_method(D_METHOD("get_default_margin", "margin"), &StyleBox::get_default_margin);
//ClassDB::bind_method(D_METHOD("set_default_margin"),&StyleBox::set_default_margin);
//ClassDB::bind_method(D_METHOD("get_default_margin"),&StyleBox::get_default_margin);
- ClassDB::bind_method(D_METHOD("get_margin","margin"),&StyleBox::get_margin);
- ClassDB::bind_method(D_METHOD("get_minimum_size"),&StyleBox::get_minimum_size);
- ClassDB::bind_method(D_METHOD("get_center_size"),&StyleBox::get_center_size);
- ClassDB::bind_method(D_METHOD("get_offset"),&StyleBox::get_offset);
-
- ClassDB::bind_method(D_METHOD("draw","canvas_item","rect"),&StyleBox::draw);
-
- ADD_GROUP("Content Margin","content_margin_");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_left", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_LEFT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_right", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_RIGHT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_top", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_TOP);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "content_margin_bottom", PROPERTY_HINT_RANGE,"-1,2048,1" ), "set_default_margin","get_default_margin", MARGIN_BOTTOM );
+ ClassDB::bind_method(D_METHOD("get_margin", "margin"), &StyleBox::get_margin);
+ ClassDB::bind_method(D_METHOD("get_minimum_size"), &StyleBox::get_minimum_size);
+ ClassDB::bind_method(D_METHOD("get_center_size"), &StyleBox::get_center_size);
+ ClassDB::bind_method(D_METHOD("get_offset"), &StyleBox::get_offset);
+ ClassDB::bind_method(D_METHOD("draw", "canvas_item", "rect"), &StyleBox::draw);
+ ADD_GROUP("Content Margin", "content_margin_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_left", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_right", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_top", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "content_margin_bottom", PROPERTY_HINT_RANGE, "-1,2048,1"), "set_default_margin", "get_default_margin", MARGIN_BOTTOM);
}
StyleBox::StyleBox() {
- for (int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- margin[i]=-1;
+ margin[i] = -1;
}
}
-
void StyleBoxTexture::set_texture(RES p_texture) {
- if (texture==p_texture)
+ if (texture == p_texture)
return;
- texture=p_texture;
+ texture = p_texture;
emit_signal("texture_changed");
emit_changed();
-
}
RES StyleBoxTexture::get_texture() const {
return texture;
}
-void StyleBoxTexture::set_margin_size(Margin p_margin,float p_size) {
+void StyleBoxTexture::set_margin_size(Margin p_margin, float p_size) {
- margin[p_margin]=p_size;
+ margin[p_margin] = p_size;
emit_changed();
-
}
float StyleBoxTexture::get_margin_size(Margin p_margin) const {
@@ -133,23 +126,22 @@ float StyleBoxTexture::get_style_margin(Margin p_margin) const {
return margin[p_margin];
}
-void StyleBoxTexture::draw(RID p_canvas_item,const Rect2& p_rect) const {
+void StyleBoxTexture::draw(RID p_canvas_item, const Rect2 &p_rect) const {
if (texture.is_null())
return;
- Rect2 r=p_rect;
- r.pos.x-=expand_margin[MARGIN_LEFT];
- r.pos.y-=expand_margin[MARGIN_TOP];
- r.size.x+=expand_margin[MARGIN_LEFT]+expand_margin[MARGIN_RIGHT];
- r.size.y+=expand_margin[MARGIN_TOP]+expand_margin[MARGIN_BOTTOM];
- VisualServer::get_singleton()->canvas_item_add_nine_patch( p_canvas_item,r,region_rect,texture->get_rid(),Vector2(margin[MARGIN_LEFT],margin[MARGIN_TOP]),Vector2(margin[MARGIN_RIGHT],margin[MARGIN_BOTTOM]),VS::NINE_PATCH_STRETCH,VS::NINE_PATCH_STRETCH,draw_center,modulate);
+ Rect2 r = p_rect;
+ r.pos.x -= expand_margin[MARGIN_LEFT];
+ r.pos.y -= expand_margin[MARGIN_TOP];
+ r.size.x += expand_margin[MARGIN_LEFT] + expand_margin[MARGIN_RIGHT];
+ r.size.y += expand_margin[MARGIN_TOP] + expand_margin[MARGIN_BOTTOM];
+ VisualServer::get_singleton()->canvas_item_add_nine_patch(p_canvas_item, r, region_rect, texture->get_rid(), Vector2(margin[MARGIN_LEFT], margin[MARGIN_TOP]), Vector2(margin[MARGIN_RIGHT], margin[MARGIN_BOTTOM]), VS::NINE_PATCH_STRETCH, VS::NINE_PATCH_STRETCH, draw_center, modulate);
}
void StyleBoxTexture::set_draw_center(bool p_draw) {
- draw_center=p_draw;
+ draw_center = p_draw;
emit_changed();
-
}
bool StyleBoxTexture::get_draw_center() const {
@@ -165,26 +157,25 @@ Size2 StyleBoxTexture::get_center_size() const {
return texture->get_size() - get_minimum_size();
}
-void StyleBoxTexture::set_expand_margin_size(Margin p_expand_margin,float p_size) {
+void StyleBoxTexture::set_expand_margin_size(Margin p_expand_margin, float p_size) {
- ERR_FAIL_INDEX(p_expand_margin,4);
- expand_margin[p_expand_margin]=p_size;
+ ERR_FAIL_INDEX(p_expand_margin, 4);
+ expand_margin[p_expand_margin] = p_size;
emit_changed();
-
}
float StyleBoxTexture::get_expand_margin_size(Margin p_expand_margin) const {
- ERR_FAIL_INDEX_V(p_expand_margin,4,0);
+ ERR_FAIL_INDEX_V(p_expand_margin, 4, 0);
return expand_margin[p_expand_margin];
}
-void StyleBoxTexture::set_region_rect(const Rect2& p_region_rect) {
+void StyleBoxTexture::set_region_rect(const Rect2 &p_region_rect) {
- if (region_rect==p_region_rect)
+ if (region_rect == p_region_rect)
return;
- region_rect=p_region_rect;
+ region_rect = p_region_rect;
emit_changed();
}
@@ -193,11 +184,10 @@ Rect2 StyleBoxTexture::get_region_rect() const {
return region_rect;
}
-
-void StyleBoxTexture::set_modulate(const Color& p_modulate) {
- if (modulate==p_modulate)
+void StyleBoxTexture::set_modulate(const Color &p_modulate) {
+ if (modulate == p_modulate)
return;
- modulate=p_modulate;
+ modulate = p_modulate;
emit_changed();
}
@@ -206,84 +196,74 @@ Color StyleBoxTexture::get_modulate() const {
return modulate;
}
-
void StyleBoxTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_texture","texture:Texture"),&StyleBoxTexture::set_texture);
- ClassDB::bind_method(D_METHOD("get_texture:Texture"),&StyleBoxTexture::get_texture);
-
- ClassDB::bind_method(D_METHOD("set_margin_size","margin","size"),&StyleBoxTexture::set_margin_size);
- ClassDB::bind_method(D_METHOD("get_margin_size","margin"),&StyleBoxTexture::get_margin_size);
+ ClassDB::bind_method(D_METHOD("set_texture", "texture:Texture"), &StyleBoxTexture::set_texture);
+ ClassDB::bind_method(D_METHOD("get_texture:Texture"), &StyleBoxTexture::get_texture);
- ClassDB::bind_method(D_METHOD("set_expand_margin_size","margin","size"),&StyleBoxTexture::set_expand_margin_size);
- ClassDB::bind_method(D_METHOD("get_expand_margin_size","margin"),&StyleBoxTexture::get_expand_margin_size);
+ ClassDB::bind_method(D_METHOD("set_margin_size", "margin", "size"), &StyleBoxTexture::set_margin_size);
+ ClassDB::bind_method(D_METHOD("get_margin_size", "margin"), &StyleBoxTexture::get_margin_size);
- ClassDB::bind_method(D_METHOD("set_region_rect","region"),&StyleBoxTexture::set_region_rect);
- ClassDB::bind_method(D_METHOD("get_region_rect"),&StyleBoxTexture::get_region_rect);
+ ClassDB::bind_method(D_METHOD("set_expand_margin_size", "margin", "size"), &StyleBoxTexture::set_expand_margin_size);
+ ClassDB::bind_method(D_METHOD("get_expand_margin_size", "margin"), &StyleBoxTexture::get_expand_margin_size);
- ClassDB::bind_method(D_METHOD("set_draw_center","enable"),&StyleBoxTexture::set_draw_center);
- ClassDB::bind_method(D_METHOD("get_draw_center"),&StyleBoxTexture::get_draw_center);
+ ClassDB::bind_method(D_METHOD("set_region_rect", "region"), &StyleBoxTexture::set_region_rect);
+ ClassDB::bind_method(D_METHOD("get_region_rect"), &StyleBoxTexture::get_region_rect);
- ClassDB::bind_method(D_METHOD("set_modulate","color"),&StyleBoxTexture::set_modulate);
- ClassDB::bind_method(D_METHOD("get_modulate"),&StyleBoxTexture::get_modulate);
+ ClassDB::bind_method(D_METHOD("set_draw_center", "enable"), &StyleBoxTexture::set_draw_center);
+ ClassDB::bind_method(D_METHOD("get_draw_center"), &StyleBoxTexture::get_draw_center);
+ ClassDB::bind_method(D_METHOD("set_modulate", "color"), &StyleBoxTexture::set_modulate);
+ ClassDB::bind_method(D_METHOD("get_modulate"), &StyleBoxTexture::get_modulate);
ADD_SIGNAL(MethodInfo("texture_changed"));
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture" ), "set_texture","get_texture") ;
- ADD_PROPERTYNZ( PropertyInfo( Variant::RECT2, "region_rect"), "set_region_rect","get_region_rect");
- ADD_GROUP("Margin","margin_");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_left", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_LEFT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_right", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_RIGHT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_top", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_TOP);
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "margin_bottom", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_margin_size","get_margin_size", MARGIN_BOTTOM );
- ADD_GROUP("Expand Margin","expand_margin_");
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_LEFT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_RIGHT );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_TOP );
- ADD_PROPERTYI( PropertyInfo( Variant::REAL, "expand_margin_bottom", PROPERTY_HINT_RANGE,"0,2048,1" ), "set_expand_margin_size","get_expand_margin_size", MARGIN_BOTTOM );
- ADD_GROUP("Modulate","modulate_");
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "modulate_color" ), "set_modulate","get_modulate");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "draw_center" ) , "set_draw_center","get_draw_center");
-
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_texture", "get_texture");
+ ADD_PROPERTYNZ(PropertyInfo(Variant::RECT2, "region_rect"), "set_region_rect", "get_region_rect");
+ ADD_GROUP("Margin", "margin_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_margin_size", "get_margin_size", MARGIN_BOTTOM);
+ ADD_GROUP("Expand Margin", "expand_margin_");
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_left", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_LEFT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_right", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_RIGHT);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_top", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_TOP);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "expand_margin_bottom", PROPERTY_HINT_RANGE, "0,2048,1"), "set_expand_margin_size", "get_expand_margin_size", MARGIN_BOTTOM);
+ ADD_GROUP("Modulate", "modulate_");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "modulate_color"), "set_modulate", "get_modulate");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_center"), "set_draw_center", "get_draw_center");
}
StyleBoxTexture::StyleBoxTexture() {
-
- for (int i=0;i<4;i++) {
- margin[i]=0;
- expand_margin[i]=0;
+ for (int i = 0; i < 4; i++) {
+ margin[i] = 0;
+ expand_margin[i] = 0;
}
- draw_center=true;
- modulate=Color(1,1,1,1);
-
+ draw_center = true;
+ modulate = Color(1, 1, 1, 1);
}
StyleBoxTexture::~StyleBoxTexture() {
-
-
}
////////////////
-void StyleBoxFlat::set_bg_color(const Color& p_color) {
+void StyleBoxFlat::set_bg_color(const Color &p_color) {
- bg_color=p_color;
+ bg_color = p_color;
emit_changed();
-
}
-void StyleBoxFlat::set_light_color(const Color& p_color) {
+void StyleBoxFlat::set_light_color(const Color &p_color) {
- light_color=p_color;
+ light_color = p_color;
emit_changed();
-
}
-void StyleBoxFlat::set_dark_color(const Color& p_color) {
+void StyleBoxFlat::set_dark_color(const Color &p_color) {
- dark_color=p_color;
+ dark_color = p_color;
emit_changed();
-
}
Color StyleBoxFlat::get_bg_color() const {
@@ -299,37 +279,31 @@ Color StyleBoxFlat::get_dark_color() const {
return dark_color;
}
-
void StyleBoxFlat::set_border_size(int p_size) {
- border_size=p_size;
+ border_size = p_size;
emit_changed();
-
}
int StyleBoxFlat::get_border_size() const {
return border_size;
-
}
void StyleBoxFlat::set_border_blend(bool p_blend) {
- blend=p_blend;
+ blend = p_blend;
emit_changed();
-
}
bool StyleBoxFlat::get_border_blend() const {
return blend;
-
}
void StyleBoxFlat::set_draw_center(bool p_draw) {
- draw_center=p_draw;
+ draw_center = p_draw;
emit_changed();
-
}
bool StyleBoxFlat::get_draw_center() const {
@@ -340,48 +314,41 @@ Size2 StyleBoxFlat::get_center_size() const {
return Size2();
}
-
-void StyleBoxFlat::draw(RID p_canvas_item,const Rect2& p_rect) const {
+void StyleBoxFlat::draw(RID p_canvas_item, const Rect2 &p_rect) const {
VisualServer *vs = VisualServer::get_singleton();
Rect2i r = p_rect;
- for (int i=0;i<border_size;i++) {
-
+ for (int i = 0; i < border_size; i++) {
-
- Color color_upleft=light_color;
- Color color_downright=dark_color;
+ Color color_upleft = light_color;
+ Color color_downright = dark_color;
if (blend) {
- color_upleft.r=(border_size-i)*color_upleft.r/border_size + i*bg_color.r/border_size;
- color_upleft.g=(border_size-i)*color_upleft.g/border_size + i*bg_color.g/border_size;
- color_upleft.b=(border_size-i)*color_upleft.b/border_size + i*bg_color.b/border_size;
-
- color_downright.r=(border_size-i)*color_downright.r/border_size + i*bg_color.r/border_size;
- color_downright.g=(border_size-i)*color_downright.g/border_size + i*bg_color.g/border_size;
- color_downright.b=(border_size-i)*color_downright.b/border_size + i*bg_color.b/border_size;
+ color_upleft.r = (border_size - i) * color_upleft.r / border_size + i * bg_color.r / border_size;
+ color_upleft.g = (border_size - i) * color_upleft.g / border_size + i * bg_color.g / border_size;
+ color_upleft.b = (border_size - i) * color_upleft.b / border_size + i * bg_color.b / border_size;
+ color_downright.r = (border_size - i) * color_downright.r / border_size + i * bg_color.r / border_size;
+ color_downright.g = (border_size - i) * color_downright.g / border_size + i * bg_color.g / border_size;
+ color_downright.b = (border_size - i) * color_downright.b / border_size + i * bg_color.b / border_size;
}
- vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i( r.pos.x,r.pos.y+r.size.y-1), Size2(r.size.x ,1 )),color_downright);
- vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i( r.pos.x+r.size.x-1,r.pos.y ), Size2( 1 ,r.size.y )), color_downright);
-
- vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, Size2(r.size.x ,1 )), color_upleft);
- vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, Size2( 1 ,r.size.y )), color_upleft);
+ vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i(r.pos.x, r.pos.y + r.size.y - 1), Size2(r.size.x, 1)), color_downright);
+ vs->canvas_item_add_rect(p_canvas_item, Rect2(Point2i(r.pos.x + r.size.x - 1, r.pos.y), Size2(1, r.size.y)), color_downright);
+ vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, Size2(r.size.x, 1)), color_upleft);
+ vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, Size2(1, r.size.y)), color_upleft);
r.pos.x++;
r.pos.y++;
- r.size.x-=2;
- r.size.y-=2;
+ r.size.x -= 2;
+ r.size.y -= 2;
}
if (draw_center)
- vs->canvas_item_add_rect(p_canvas_item, Rect2( r.pos, r.size) , bg_color );
-
-
+ vs->canvas_item_add_rect(p_canvas_item, Rect2(r.pos, r.size), bg_color);
}
float StyleBoxFlat::get_style_margin(Margin p_margin) const {
@@ -390,40 +357,35 @@ float StyleBoxFlat::get_style_margin(Margin p_margin) const {
}
void StyleBoxFlat::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_bg_color","color"),&StyleBoxFlat::set_bg_color);
- ClassDB::bind_method(D_METHOD("get_bg_color"),&StyleBoxFlat::get_bg_color);
- ClassDB::bind_method(D_METHOD("set_light_color","color"),&StyleBoxFlat::set_light_color);
- ClassDB::bind_method(D_METHOD("get_light_color"),&StyleBoxFlat::get_light_color);
- ClassDB::bind_method(D_METHOD("set_dark_color","color"),&StyleBoxFlat::set_dark_color);
- ClassDB::bind_method(D_METHOD("get_dark_color"),&StyleBoxFlat::get_dark_color);
- ClassDB::bind_method(D_METHOD("set_border_size","size"),&StyleBoxFlat::set_border_size);
- ClassDB::bind_method(D_METHOD("get_border_size"),&StyleBoxFlat::get_border_size);
- ClassDB::bind_method(D_METHOD("set_border_blend","blend"),&StyleBoxFlat::set_border_blend);
- ClassDB::bind_method(D_METHOD("get_border_blend"),&StyleBoxFlat::get_border_blend);
- ClassDB::bind_method(D_METHOD("set_draw_center","size"),&StyleBoxFlat::set_draw_center);
- ClassDB::bind_method(D_METHOD("get_draw_center"),&StyleBoxFlat::get_draw_center);
-
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "bg_color"), "set_bg_color","get_bg_color") ;
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "light_color"),"set_light_color","get_light_color");
- ADD_PROPERTY( PropertyInfo( Variant::COLOR, "dark_color"),"set_dark_color","get_dark_color");
- ADD_PROPERTY( PropertyInfo( Variant::INT, "border_size",PROPERTY_HINT_RANGE,"0,4096"),"set_border_size","get_border_size");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "border_blend"),"set_border_blend","get_border_blend");
- ADD_PROPERTY( PropertyInfo( Variant::BOOL, "draw_bg"),"set_draw_center","get_draw_center");
-
+ ClassDB::bind_method(D_METHOD("set_bg_color", "color"), &StyleBoxFlat::set_bg_color);
+ ClassDB::bind_method(D_METHOD("get_bg_color"), &StyleBoxFlat::get_bg_color);
+ ClassDB::bind_method(D_METHOD("set_light_color", "color"), &StyleBoxFlat::set_light_color);
+ ClassDB::bind_method(D_METHOD("get_light_color"), &StyleBoxFlat::get_light_color);
+ ClassDB::bind_method(D_METHOD("set_dark_color", "color"), &StyleBoxFlat::set_dark_color);
+ ClassDB::bind_method(D_METHOD("get_dark_color"), &StyleBoxFlat::get_dark_color);
+ ClassDB::bind_method(D_METHOD("set_border_size", "size"), &StyleBoxFlat::set_border_size);
+ ClassDB::bind_method(D_METHOD("get_border_size"), &StyleBoxFlat::get_border_size);
+ ClassDB::bind_method(D_METHOD("set_border_blend", "blend"), &StyleBoxFlat::set_border_blend);
+ ClassDB::bind_method(D_METHOD("get_border_blend"), &StyleBoxFlat::get_border_blend);
+ ClassDB::bind_method(D_METHOD("set_draw_center", "size"), &StyleBoxFlat::set_draw_center);
+ ClassDB::bind_method(D_METHOD("get_draw_center"), &StyleBoxFlat::get_draw_center);
+
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "bg_color"), "set_bg_color", "get_bg_color");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "light_color"), "set_light_color", "get_light_color");
+ ADD_PROPERTY(PropertyInfo(Variant::COLOR, "dark_color"), "set_dark_color", "get_dark_color");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "border_size", PROPERTY_HINT_RANGE, "0,4096"), "set_border_size", "get_border_size");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "border_blend"), "set_border_blend", "get_border_blend");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "draw_bg"), "set_draw_center", "get_draw_center");
}
StyleBoxFlat::StyleBoxFlat() {
- bg_color=Color(0.6,0.6,0.6);
- light_color=Color(0.8,0.8,0.8);
- dark_color=Color(0.8,0.8,0.8);
- draw_center=true;
- blend=true;
- border_size=0;
-
+ bg_color = Color(0.6, 0.6, 0.6);
+ light_color = Color(0.8, 0.8, 0.8);
+ dark_color = Color(0.8, 0.8, 0.8);
+ draw_center = true;
+ blend = true;
+ border_size = 0;
}
StyleBoxFlat::~StyleBoxFlat() {
-
-
}
-
diff --git a/scene/resources/style_box.h b/scene/resources/style_box.h
index f8b02724ee..f0107ed71f 100644
--- a/scene/resources/style_box.h
+++ b/scene/resources/style_box.h
@@ -30,32 +30,31 @@
#define STYLE_BOX_H
#include "resource.h"
-#include "servers/visual_server.h"
#include "scene/resources/texture.h"
+#include "servers/visual_server.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class StyleBox : public Resource {
- GDCLASS( StyleBox, Resource );
+ GDCLASS(StyleBox, Resource);
RES_BASE_EXTENSION("sbx");
- OBJ_SAVE_TYPE( StyleBox );
+ OBJ_SAVE_TYPE(StyleBox);
float margin[4];
protected:
-
- virtual float get_style_margin(Margin p_margin) const=0;
+ virtual float get_style_margin(Margin p_margin) const = 0;
static void _bind_methods();
-public:
- virtual bool test_mask(const Point2& p_point, const Rect2& p_rect) const;
+public:
+ virtual bool test_mask(const Point2 &p_point, const Rect2 &p_rect) const;
void set_default_margin(Margin p_margin, float p_value);
float get_default_margin(Margin p_margin) const;
float get_margin(Margin p_margin) const;
virtual Size2 get_center_size() const;
- virtual void draw(RID p_canvas_item,const Rect2& p_rect) const=0;
+ virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const = 0;
Size2 get_minimum_size() const;
Point2 get_offset() const;
@@ -65,19 +64,17 @@ public:
class StyleBoxEmpty : public StyleBox {
- GDCLASS( StyleBoxEmpty, StyleBox );
+ GDCLASS(StyleBoxEmpty, StyleBox);
virtual float get_style_margin(Margin p_margin) const { return 0; }
-public:
- virtual void draw(RID p_canvas_item,const Rect2& p_rect) const {}
+public:
+ virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const {}
StyleBoxEmpty() {}
-
};
class StyleBoxTexture : public StyleBox {
- GDCLASS( StyleBoxTexture, StyleBox );
-
+ GDCLASS(StyleBoxTexture, StyleBox);
float expand_margin[4];
float margin[4];
@@ -86,21 +83,18 @@ class StyleBoxTexture : public StyleBox {
bool draw_center;
Color modulate;
-
protected:
-
virtual float get_style_margin(Margin p_margin) const;
static void _bind_methods();
public:
-
- void set_expand_margin_size(Margin p_expand_margin,float p_size);
+ void set_expand_margin_size(Margin p_expand_margin, float p_size);
float get_expand_margin_size(Margin p_expand_margin) const;
- void set_margin_size(Margin p_margin,float p_size);
+ void set_margin_size(Margin p_margin, float p_size);
float get_margin_size(Margin p_margin) const;
- void set_region_rect(const Rect2& p_region_rect);
+ void set_region_rect(const Rect2 &p_region_rect);
Rect2 get_region_rect() const;
void set_texture(RES p_texture);
@@ -110,20 +104,18 @@ public:
bool get_draw_center() const;
virtual Size2 get_center_size() const;
- void set_modulate(const Color& p_modulate);
+ void set_modulate(const Color &p_modulate);
Color get_modulate() const;
-
- virtual void draw(RID p_canvas_item,const Rect2& p_rect) const;
+ virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const;
StyleBoxTexture();
~StyleBoxTexture();
-
};
class StyleBoxFlat : public StyleBox {
- GDCLASS( StyleBoxFlat, StyleBox );
+ GDCLASS(StyleBoxFlat, StyleBox);
Color bg_color;
Color light_color;
@@ -135,15 +127,13 @@ class StyleBoxFlat : public StyleBox {
bool blend;
protected:
-
virtual float get_style_margin(Margin p_margin) const;
static void _bind_methods();
public:
-
- void set_bg_color(const Color& p_color);
- void set_light_color(const Color& p_color);
- void set_dark_color(const Color& p_color);
+ void set_bg_color(const Color &p_color);
+ void set_light_color(const Color &p_color);
+ void set_dark_color(const Color &p_color);
Color get_bg_color() const;
Color get_light_color() const;
@@ -159,13 +149,10 @@ public:
bool get_draw_center() const;
virtual Size2 get_center_size() const;
- virtual void draw(RID p_canvas_item,const Rect2& p_rect) const;
+ virtual void draw(RID p_canvas_item, const Rect2 &p_rect) const;
StyleBoxFlat();
~StyleBoxFlat();
-
};
-
-
#endif
diff --git a/scene/resources/surface_tool.cpp b/scene/resources/surface_tool.cpp
index cf07f1658b..7564735cf2 100644
--- a/scene/resources/surface_tool.cpp
+++ b/scene/resources/surface_tool.cpp
@@ -32,56 +32,53 @@
#define _VERTEX_SNAP 0.0001
#define EQ_VERTEX_DIST 0.00001
+bool SurfaceTool::Vertex::operator==(const Vertex &p_b) const {
-bool SurfaceTool::Vertex::operator==(const Vertex& p_b) const {
-
-
- if (vertex!=p_b.vertex)
+ if (vertex != p_b.vertex)
return false;
- if (uv!=p_b.uv)
+ if (uv != p_b.uv)
return false;
- if (uv2!=p_b.uv2)
+ if (uv2 != p_b.uv2)
return false;
- if (normal!=p_b.normal)
+ if (normal != p_b.normal)
return false;
- if (binormal!=p_b.binormal)
+ if (binormal != p_b.binormal)
return false;
- if (color!=p_b.color)
+ if (color != p_b.color)
return false;
- if (bones.size()!=p_b.bones.size())
+ if (bones.size() != p_b.bones.size())
return false;
- for(int i=0;i<bones.size();i++) {
- if (bones[i]!=p_b.bones[i])
+ for (int i = 0; i < bones.size(); i++) {
+ if (bones[i] != p_b.bones[i])
return false;
}
- for(int i=0;i<weights.size();i++) {
- if (weights[i]!=p_b.weights[i])
+ for (int i = 0; i < weights.size(); i++) {
+ if (weights[i] != p_b.weights[i])
return false;
}
return true;
}
-
uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) {
- uint32_t h = hash_djb2_buffer((const uint8_t*)&p_vtx.vertex,sizeof(real_t)*3);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.normal,sizeof(real_t)*3,h);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.binormal,sizeof(real_t)*3,h);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.tangent,sizeof(real_t)*3,h);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.uv,sizeof(real_t)*2,h);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.uv2,sizeof(real_t)*2,h);
- h = hash_djb2_buffer((const uint8_t*)&p_vtx.color,sizeof(real_t)*4,h);
- h = hash_djb2_buffer((const uint8_t*)p_vtx.bones.ptr(),p_vtx.bones.size()*sizeof(int),h);
- h = hash_djb2_buffer((const uint8_t*)p_vtx.weights.ptr(),p_vtx.weights.size()*sizeof(float),h);
+ uint32_t h = hash_djb2_buffer((const uint8_t *)&p_vtx.vertex, sizeof(real_t) * 3);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.normal, sizeof(real_t) * 3, h);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.binormal, sizeof(real_t) * 3, h);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.tangent, sizeof(real_t) * 3, h);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv, sizeof(real_t) * 2, h);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.uv2, sizeof(real_t) * 2, h);
+ h = hash_djb2_buffer((const uint8_t *)&p_vtx.color, sizeof(real_t) * 4, h);
+ h = hash_djb2_buffer((const uint8_t *)p_vtx.bones.ptr(), p_vtx.bones.size() * sizeof(int), h);
+ h = hash_djb2_buffer((const uint8_t *)p_vtx.weights.ptr(), p_vtx.weights.size() * sizeof(float), h);
return h;
}
@@ -89,165 +86,154 @@ void SurfaceTool::begin(Mesh::PrimitiveType p_primitive) {
clear();
- primitive=p_primitive;
- begun=true;
- first=true;
+ primitive = p_primitive;
+ begun = true;
+ first = true;
}
-void SurfaceTool::add_vertex( const Vector3& p_vertex) {
+void SurfaceTool::add_vertex(const Vector3 &p_vertex) {
ERR_FAIL_COND(!begun);
Vertex vtx;
- vtx.vertex=p_vertex;
- vtx.color=last_color;
- vtx.normal=last_normal;
- vtx.uv=last_uv;
- vtx.weights=last_weights;
- vtx.bones=last_bones;
- vtx.tangent=last_tangent.normal;
- vtx.binormal=last_normal.cross(last_tangent.normal).normalized() * last_tangent.d;
+ vtx.vertex = p_vertex;
+ vtx.color = last_color;
+ vtx.normal = last_normal;
+ vtx.uv = last_uv;
+ vtx.weights = last_weights;
+ vtx.bones = last_bones;
+ vtx.tangent = last_tangent.normal;
+ vtx.binormal = last_normal.cross(last_tangent.normal).normalized() * last_tangent.d;
vertex_array.push_back(vtx);
- first=false;
- format|=Mesh::ARRAY_FORMAT_VERTEX;
-
+ first = false;
+ format |= Mesh::ARRAY_FORMAT_VERTEX;
}
-void SurfaceTool::add_color( Color p_color ) {
+void SurfaceTool::add_color(Color p_color) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_COLOR));
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_COLOR));
- format|=Mesh::ARRAY_FORMAT_COLOR;
- last_color=p_color;
+ format |= Mesh::ARRAY_FORMAT_COLOR;
+ last_color = p_color;
}
-void SurfaceTool::add_normal( const Vector3& p_normal) {
+void SurfaceTool::add_normal(const Vector3 &p_normal) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_NORMAL));
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_NORMAL));
- format|=Mesh::ARRAY_FORMAT_NORMAL;
- last_normal=p_normal;
+ format |= Mesh::ARRAY_FORMAT_NORMAL;
+ last_normal = p_normal;
}
-
-void SurfaceTool::add_tangent( const Plane& p_tangent ) {
+void SurfaceTool::add_tangent(const Plane &p_tangent) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TANGENT));
-
- format|=Mesh::ARRAY_FORMAT_TANGENT;
- last_tangent=p_tangent;
-
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TANGENT));
+ format |= Mesh::ARRAY_FORMAT_TANGENT;
+ last_tangent = p_tangent;
}
-
-void SurfaceTool::add_uv( const Vector2& p_uv) {
+void SurfaceTool::add_uv(const Vector2 &p_uv) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TEX_UV));
-
- format|=Mesh::ARRAY_FORMAT_TEX_UV;
- last_uv=p_uv;
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV));
+ format |= Mesh::ARRAY_FORMAT_TEX_UV;
+ last_uv = p_uv;
}
-void SurfaceTool::add_uv2( const Vector2& p_uv2) {
+void SurfaceTool::add_uv2(const Vector2 &p_uv2) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_TEX_UV2));
-
- format|=Mesh::ARRAY_FORMAT_TEX_UV2;
- last_uv2=p_uv2;
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV2));
+ format |= Mesh::ARRAY_FORMAT_TEX_UV2;
+ last_uv2 = p_uv2;
}
-void SurfaceTool::add_bones( const Vector<int>& p_bones) {
+void SurfaceTool::add_bones(const Vector<int> &p_bones) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND(p_bones.size()!=4);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_BONES));
+ ERR_FAIL_COND(p_bones.size() != 4);
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_BONES));
- format|=Mesh::ARRAY_FORMAT_BONES;
- last_bones=p_bones;
+ format |= Mesh::ARRAY_FORMAT_BONES;
+ last_bones = p_bones;
}
-void SurfaceTool::add_weights( const Vector<float>& p_weights) {
+void SurfaceTool::add_weights(const Vector<float> &p_weights) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND(p_weights.size()!=4);
- ERR_FAIL_COND( !first && !(format&Mesh::ARRAY_FORMAT_WEIGHTS));
-
- format|=Mesh::ARRAY_FORMAT_WEIGHTS;
- last_weights=p_weights;
+ ERR_FAIL_COND(p_weights.size() != 4);
+ ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_WEIGHTS));
+ format |= Mesh::ARRAY_FORMAT_WEIGHTS;
+ last_weights = p_weights;
}
void SurfaceTool::add_smooth_group(bool p_smooth) {
ERR_FAIL_COND(!begun);
if (index_array.size()) {
- smooth_groups[index_array.size()]=p_smooth;
+ smooth_groups[index_array.size()] = p_smooth;
} else {
- smooth_groups[vertex_array.size()]=p_smooth;
+ smooth_groups[vertex_array.size()] = p_smooth;
}
}
-void SurfaceTool::add_triangle_fan(const Vector<Vector3>& p_vertexes, const Vector<Vector2>& p_uvs, const Vector<Color>& p_colors,const Vector<Vector2>& p_uv2s, const Vector<Vector3>& p_normals, const Vector<Plane>& p_tangents) {
+void SurfaceTool::add_triangle_fan(const Vector<Vector3> &p_vertexes, const Vector<Vector2> &p_uvs, const Vector<Color> &p_colors, const Vector<Vector2> &p_uv2s, const Vector<Vector3> &p_normals, const Vector<Plane> &p_tangents) {
ERR_FAIL_COND(!begun);
- ERR_FAIL_COND(primitive!=Mesh::PRIMITIVE_TRIANGLES);
- ERR_FAIL_COND(p_vertexes.size()<3);
-
-#define ADD_POINT(n)\
- {\
- if(p_colors.size() > n)\
- add_color(p_colors[n]);\
- if(p_uvs.size() > n)\
- add_uv(p_uvs[n]);\
- if(p_uv2s.size() > n)\
- add_uv2(p_uv2s[n]);\
- if(p_normals.size() > n)\
- add_normal(p_normals[n]);\
- if(p_tangents.size() > n)\
- add_tangent(p_tangents[n]);\
- add_vertex(p_vertexes[n]);\
+ ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
+ ERR_FAIL_COND(p_vertexes.size() < 3);
+
+#define ADD_POINT(n) \
+ { \
+ if (p_colors.size() > n) \
+ add_color(p_colors[n]); \
+ if (p_uvs.size() > n) \
+ add_uv(p_uvs[n]); \
+ if (p_uv2s.size() > n) \
+ add_uv2(p_uv2s[n]); \
+ if (p_normals.size() > n) \
+ add_normal(p_normals[n]); \
+ if (p_tangents.size() > n) \
+ add_tangent(p_tangents[n]); \
+ add_vertex(p_vertexes[n]); \
}
- for(int i=0;i<p_vertexes.size() - 2;i++) {
+ for (int i = 0; i < p_vertexes.size() - 2; i++) {
ADD_POINT(0);
- ADD_POINT(i+1);
- ADD_POINT(i+2);
+ ADD_POINT(i + 1);
+ ADD_POINT(i + 2);
}
#undef ADD_POINT
-
}
-void SurfaceTool::add_index( int p_index) {
+void SurfaceTool::add_index(int p_index) {
ERR_FAIL_COND(!begun);
- format|=Mesh::ARRAY_FORMAT_INDEX;
+ format |= Mesh::ARRAY_FORMAT_INDEX;
index_array.push_back(p_index);
}
-Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) {
-
+Ref<Mesh> SurfaceTool::commit(const Ref<Mesh> &p_existing) {
Ref<Mesh> mesh;
if (p_existing.is_valid())
- mesh=p_existing;
+ mesh = p_existing;
else
- mesh= Ref<Mesh>( memnew( Mesh ) );
+ mesh = Ref<Mesh>(memnew(Mesh));
- int varr_len=vertex_array.size();
+ int varr_len = vertex_array.size();
-
- if (varr_len==0)
+ if (varr_len == 0)
return mesh;
int surface = mesh->get_surface_count();
@@ -255,9 +241,9 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) {
Array a;
a.resize(Mesh::ARRAY_MAX);
- for (int i=0;i<Mesh::ARRAY_MAX;i++) {
+ for (int i = 0; i < Mesh::ARRAY_MAX; i++) {
- switch(format&(1<<i)) {
+ switch (format & (1 << i)) {
case Mesh::ARRAY_FORMAT_VERTEX:
case Mesh::ARRAY_FORMAT_NORMAL: {
@@ -266,24 +252,23 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) {
array.resize(varr_len);
PoolVector<Vector3>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) {
- const Vertex &v=E->get();
+ const Vertex &v = E->get();
- switch(i) {
+ switch (i) {
case Mesh::ARRAY_VERTEX: {
- w[idx]=v.vertex;
+ w[idx] = v.vertex;
} break;
case Mesh::ARRAY_NORMAL: {
- w[idx]=v.normal;
+ w[idx] = v.normal;
} break;
}
-
}
- w=PoolVector<Vector3>::Write();
- a[i]=array;
+ w = PoolVector<Vector3>::Write();
+ a[i] = array;
} break;
@@ -294,141 +279,134 @@ Ref<Mesh> SurfaceTool::commit(const Ref<Mesh>& p_existing) {
array.resize(varr_len);
PoolVector<Vector2>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) {
- const Vertex &v=E->get();
+ const Vertex &v = E->get();
- switch(i) {
+ switch (i) {
case Mesh::ARRAY_TEX_UV: {
- w[idx]=v.uv;
+ w[idx] = v.uv;
} break;
case Mesh::ARRAY_TEX_UV2: {
- w[idx]=v.uv2;
+ w[idx] = v.uv2;
} break;
}
-
}
- w=PoolVector<Vector2>::Write();
- a[i]=array;
+ w = PoolVector<Vector2>::Write();
+ a[i] = array;
} break;
case Mesh::ARRAY_FORMAT_TANGENT: {
-
PoolVector<float> array;
- array.resize(varr_len*4);
+ array.resize(varr_len * 4);
PoolVector<float>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) {
- const Vertex &v=E->get();
+ const Vertex &v = E->get();
- w[idx+0]=v.tangent.x;
- w[idx+1]=v.tangent.y;
- w[idx+2]=v.tangent.z;
+ w[idx + 0] = v.tangent.x;
+ w[idx + 1] = v.tangent.y;
+ w[idx + 2] = v.tangent.z;
//float d = v.tangent.dot(v.binormal,v.normal);
- float d = v.binormal.dot( v.normal.cross(v.tangent));
- w[idx+3]=d<0 ? -1 : 1;
+ float d = v.binormal.dot(v.normal.cross(v.tangent));
+ w[idx + 3] = d < 0 ? -1 : 1;
}
- w=PoolVector<float>::Write();
- a[i]=array;
+ w = PoolVector<float>::Write();
+ a[i] = array;
} break;
- case Mesh::ARRAY_FORMAT_COLOR: {
+ case Mesh::ARRAY_FORMAT_COLOR: {
PoolVector<Color> array;
array.resize(varr_len);
PoolVector<Color>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx++) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx++) {
- const Vertex &v=E->get();
- w[idx]=v.color;
+ const Vertex &v = E->get();
+ w[idx] = v.color;
}
- w=PoolVector<Color>::Write();
- a[i]=array;
+ w = PoolVector<Color>::Write();
+ a[i] = array;
} break;
case Mesh::ARRAY_FORMAT_BONES: {
-
PoolVector<int> array;
- array.resize(varr_len*4);
+ array.resize(varr_len * 4);
PoolVector<int>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) {
- const Vertex &v=E->get();
+ const Vertex &v = E->get();
- ERR_CONTINUE( v.bones.size()!=4 );
+ ERR_CONTINUE(v.bones.size() != 4);
- for(int j=0;j<4;j++) {
- w[idx+j]=v.bones[j];
+ for (int j = 0; j < 4; j++) {
+ w[idx + j] = v.bones[j];
}
-
}
- w=PoolVector<int>::Write();
- a[i]=array;
+ w = PoolVector<int>::Write();
+ a[i] = array;
} break;
case Mesh::ARRAY_FORMAT_WEIGHTS: {
-
PoolVector<float> array;
- array.resize(varr_len*4);
+ array.resize(varr_len * 4);
PoolVector<float>::Write w = array.write();
- int idx=0;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next(),idx+=4) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next(), idx += 4) {
- const Vertex &v=E->get();
- ERR_CONTINUE( v.weights.size()!=4 );
+ const Vertex &v = E->get();
+ ERR_CONTINUE(v.weights.size() != 4);
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- w[idx+j]=v.weights[j];
+ w[idx + j] = v.weights[j];
}
-
}
- w=PoolVector<float>::Write();
- a[i]=array;
+ w = PoolVector<float>::Write();
+ a[i] = array;
} break;
case Mesh::ARRAY_FORMAT_INDEX: {
- ERR_CONTINUE( index_array.size() ==0 );
+ ERR_CONTINUE(index_array.size() == 0);
PoolVector<int> array;
array.resize(index_array.size());
PoolVector<int>::Write w = array.write();
- int idx=0;
- for(List< int>::Element *E=index_array.front();E;E=E->next(),idx++) {
+ int idx = 0;
+ for (List<int>::Element *E = index_array.front(); E; E = E->next(), idx++) {
- w[idx]=E->get();
+ w[idx] = E->get();
}
- w=PoolVector<int>::Write();
- a[i]=array;
+ w = PoolVector<int>::Write();
+ a[i] = array;
} break;
default: {}
}
-
}
- mesh->add_surface_from_arrays(primitive,a);
+ mesh->add_surface_from_arrays(primitive, a);
if (material.is_valid())
- mesh->surface_set_material(surface,material);
+ mesh->surface_set_material(surface, material);
return mesh;
}
@@ -438,57 +416,54 @@ void SurfaceTool::index() {
if (index_array.size())
return; //already indexed
-
- HashMap<Vertex,int,VertexHasher> indices;
+ HashMap<Vertex, int, VertexHasher> indices;
List<Vertex> new_vertices;
- for(List< Vertex >::Element *E=vertex_array.front();E;E=E->next()) {
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) {
- int *idxptr=indices.getptr(E->get());
+ int *idxptr = indices.getptr(E->get());
int idx;
if (!idxptr) {
- idx=indices.size();
+ idx = indices.size();
new_vertices.push_back(E->get());
- indices[E->get()]=idx;
+ indices[E->get()] = idx;
} else {
- idx=*idxptr;
+ idx = *idxptr;
}
index_array.push_back(idx);
-
}
vertex_array.clear();
- vertex_array=new_vertices;
+ vertex_array = new_vertices;
- format|=Mesh::ARRAY_FORMAT_INDEX;
+ format |= Mesh::ARRAY_FORMAT_INDEX;
}
void SurfaceTool::deindex() {
- if (index_array.size()==0)
+ if (index_array.size() == 0)
return; //nothing to deindex
- Vector< Vertex > varr;
+ Vector<Vertex> varr;
varr.resize(vertex_array.size());
- int idx=0;
- for (List< Vertex >::Element *E=vertex_array.front();E;E=E->next()) {
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) {
- varr[idx++]=E->get();
+ varr[idx++] = E->get();
}
vertex_array.clear();
- for (List<int>::Element *E=index_array.front();E;E=E->next()) {
+ for (List<int>::Element *E = index_array.front(); E; E = E->next()) {
- ERR_FAIL_INDEX(E->get(),varr.size());
+ ERR_FAIL_INDEX(E->get(), varr.size());
vertex_array.push_back(varr[E->get()]);
}
- format&=~Mesh::ARRAY_FORMAT_INDEX;
+ format &= ~Mesh::ARRAY_FORMAT_INDEX;
}
-
-void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int& lformat) {
+void SurfaceTool::_create_list(const Ref<Mesh> &p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int &lformat) {
Array arr = p_existing->surface_get_arrays(p_surface);
- ERR_FAIL_COND( arr.size() !=VS::ARRAY_MAX );
+ ERR_FAIL_COND(arr.size() != VS::ARRAY_MAX);
PoolVector<Vector3> varr = arr[VS::ARRAY_VERTEX];
PoolVector<Vector3> narr = arr[VS::ARRAY_NORMAL];
@@ -501,90 +476,90 @@ void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List<
int vc = varr.size();
- if (vc==0)
+ if (vc == 0)
return;
- lformat=0;
+ lformat = 0;
PoolVector<Vector3>::Read rv;
if (varr.size()) {
- lformat|=VS::ARRAY_FORMAT_VERTEX;
- rv=varr.read();
+ lformat |= VS::ARRAY_FORMAT_VERTEX;
+ rv = varr.read();
}
PoolVector<Vector3>::Read rn;
if (narr.size()) {
- lformat|=VS::ARRAY_FORMAT_NORMAL;
- rn=narr.read();
+ lformat |= VS::ARRAY_FORMAT_NORMAL;
+ rn = narr.read();
}
PoolVector<float>::Read rt;
if (tarr.size()) {
- lformat|=VS::ARRAY_FORMAT_TANGENT;
- rt=tarr.read();
+ lformat |= VS::ARRAY_FORMAT_TANGENT;
+ rt = tarr.read();
}
PoolVector<Color>::Read rc;
if (carr.size()) {
- lformat|=VS::ARRAY_FORMAT_COLOR;
- rc=carr.read();
+ lformat |= VS::ARRAY_FORMAT_COLOR;
+ rc = carr.read();
}
PoolVector<Vector2>::Read ruv;
if (uvarr.size()) {
- lformat|=VS::ARRAY_FORMAT_TEX_UV;
- ruv=uvarr.read();
+ lformat |= VS::ARRAY_FORMAT_TEX_UV;
+ ruv = uvarr.read();
}
PoolVector<Vector2>::Read ruv2;
if (uv2arr.size()) {
- lformat|=VS::ARRAY_FORMAT_TEX_UV2;
- ruv2=uv2arr.read();
+ lformat |= VS::ARRAY_FORMAT_TEX_UV2;
+ ruv2 = uv2arr.read();
}
PoolVector<int>::Read rb;
if (barr.size()) {
- lformat|=VS::ARRAY_FORMAT_BONES;
- rb=barr.read();
+ lformat |= VS::ARRAY_FORMAT_BONES;
+ rb = barr.read();
}
PoolVector<float>::Read rw;
if (warr.size()) {
- lformat|=VS::ARRAY_FORMAT_WEIGHTS;
- rw=warr.read();
+ lformat |= VS::ARRAY_FORMAT_WEIGHTS;
+ rw = warr.read();
}
- for(int i=0;i<vc;i++) {
+ for (int i = 0; i < vc; i++) {
Vertex v;
- if (lformat&VS::ARRAY_FORMAT_VERTEX)
- v.vertex=varr[i];
- if (lformat&VS::ARRAY_FORMAT_NORMAL)
- v.normal=narr[i];
- if (lformat&VS::ARRAY_FORMAT_TANGENT) {
- Plane p( tarr[i*4+0], tarr[i*4+1], tarr[i*4+2], tarr[i*4+3] );
- v.tangent=p.normal;
- v.binormal=p.normal.cross(last_normal).normalized() * p.d;
+ if (lformat & VS::ARRAY_FORMAT_VERTEX)
+ v.vertex = varr[i];
+ if (lformat & VS::ARRAY_FORMAT_NORMAL)
+ v.normal = narr[i];
+ if (lformat & VS::ARRAY_FORMAT_TANGENT) {
+ Plane p(tarr[i * 4 + 0], tarr[i * 4 + 1], tarr[i * 4 + 2], tarr[i * 4 + 3]);
+ v.tangent = p.normal;
+ v.binormal = p.normal.cross(last_normal).normalized() * p.d;
}
- if (lformat&VS::ARRAY_FORMAT_COLOR)
- v.color=carr[i];
- if (lformat&VS::ARRAY_FORMAT_TEX_UV)
- v.uv=uvarr[i];
- if (lformat&VS::ARRAY_FORMAT_TEX_UV2)
- v.uv2=uv2arr[i];
- if (lformat&VS::ARRAY_FORMAT_BONES) {
+ if (lformat & VS::ARRAY_FORMAT_COLOR)
+ v.color = carr[i];
+ if (lformat & VS::ARRAY_FORMAT_TEX_UV)
+ v.uv = uvarr[i];
+ if (lformat & VS::ARRAY_FORMAT_TEX_UV2)
+ v.uv2 = uv2arr[i];
+ if (lformat & VS::ARRAY_FORMAT_BONES) {
Vector<int> b;
b.resize(4);
- b[0]=barr[i*4+0];
- b[1]=barr[i*4+1];
- b[2]=barr[i*4+2];
- b[3]=barr[i*4+3];
- v.bones=b;
+ b[0] = barr[i * 4 + 0];
+ b[1] = barr[i * 4 + 1];
+ b[2] = barr[i * 4 + 2];
+ b[3] = barr[i * 4 + 3];
+ v.bones = b;
}
- if (lformat&VS::ARRAY_FORMAT_WEIGHTS) {
+ if (lformat & VS::ARRAY_FORMAT_WEIGHTS) {
Vector<float> w;
w.resize(4);
- w[0]=warr[i*4+0];
- w[1]=warr[i*4+1];
- w[2]=warr[i*4+2];
- w[3]=warr[i*4+3];
- v.weights=w;
+ w[0] = warr[i * 4 + 0];
+ w[1] = warr[i * 4 + 1];
+ w[2] = warr[i * 4 + 2];
+ w[3] = warr[i * 4 + 3];
+ v.weights = w;
}
r_vertex->push_back(v);
@@ -592,64 +567,58 @@ void SurfaceTool::_create_list(const Ref<Mesh>& p_existing, int p_surface, List<
//indices
- PoolVector<int> idx= arr[VS::ARRAY_INDEX];
+ PoolVector<int> idx = arr[VS::ARRAY_INDEX];
int is = idx.size();
if (is) {
- lformat|=VS::ARRAY_FORMAT_INDEX;
- PoolVector<int>::Read iarr=idx.read();
- for(int i=0;i<is;i++) {
+ lformat |= VS::ARRAY_FORMAT_INDEX;
+ PoolVector<int>::Read iarr = idx.read();
+ for (int i = 0; i < is; i++) {
r_index->push_back(iarr[i]);
}
-
}
-
-
}
-
-void SurfaceTool::create_from(const Ref<Mesh>& p_existing, int p_surface) {
+void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) {
clear();
- primitive=p_existing->surface_get_primitive_type(p_surface);
- _create_list(p_existing,p_surface,&vertex_array,&index_array,format);
- material=p_existing->surface_get_material(p_surface);
-
+ primitive = p_existing->surface_get_primitive_type(p_surface);
+ _create_list(p_existing, p_surface, &vertex_array, &index_array, format);
+ material = p_existing->surface_get_material(p_surface);
}
-void SurfaceTool::append_from(const Ref<Mesh>& p_existing, int p_surface,const Transform& p_xform) {
+void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform &p_xform) {
- if (vertex_array.size()==0) {
- primitive=p_existing->surface_get_primitive_type(p_surface);
- format=0;
+ if (vertex_array.size() == 0) {
+ primitive = p_existing->surface_get_primitive_type(p_surface);
+ format = 0;
}
int nformat;
List<Vertex> nvertices;
List<int> nindices;
- _create_list(p_existing,p_surface,&nvertices,&nindices,nformat);
- format|=nformat;
+ _create_list(p_existing, p_surface, &nvertices, &nindices, nformat);
+ format |= nformat;
int vfrom = vertex_array.size();
+ for (List<Vertex>::Element *E = nvertices.front(); E; E = E->next()) {
- for(List<Vertex>::Element *E=nvertices.front();E;E=E->next()) {
-
- Vertex v=E->get();
- v.vertex=p_xform.xform(v.vertex);
- if (nformat&VS::ARRAY_FORMAT_NORMAL) {
- v.normal=p_xform.basis.xform(v.normal);
+ Vertex v = E->get();
+ v.vertex = p_xform.xform(v.vertex);
+ if (nformat & VS::ARRAY_FORMAT_NORMAL) {
+ v.normal = p_xform.basis.xform(v.normal);
}
- if (nformat&VS::ARRAY_FORMAT_TANGENT) {
- v.tangent=p_xform.basis.xform(v.tangent);
- v.binormal=p_xform.basis.xform(v.binormal);
+ if (nformat & VS::ARRAY_FORMAT_TANGENT) {
+ v.tangent = p_xform.basis.xform(v.tangent);
+ v.binormal = p_xform.basis.xform(v.binormal);
}
vertex_array.push_back(v);
}
- for(List<int>::Element *E=nindices.front();E;E=E->next()) {
+ for (List<int>::Element *E = nindices.front(); E; E = E->next()) {
- int dst_index = E->get()+vfrom;
+ int dst_index = E->get() + vfrom;
/*
if (dst_index <0 || dst_index>=vertex_array.size()) {
print_line("invalid index!");
@@ -657,240 +626,220 @@ void SurfaceTool::append_from(const Ref<Mesh>& p_existing, int p_surface,const T
*/
index_array.push_back(dst_index);
}
- if (index_array.size()%3)
+ if (index_array.size() % 3)
print_line("IA not div of 3?");
-
}
//mikktspace callbacks
-int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext * pContext) {
+int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext *pContext) {
- Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData);
- return varr.size()/3;
+ Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData);
+ return varr.size() / 3;
}
-int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext * pContext, const int iFace){
+int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace) {
return 3; //always 3
}
-void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert){
-
- Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData);
- Vector3 v = varr[iFace*3+iVert]->get().vertex;
- fvPosOut[0]=v.x;
- fvPosOut[1]=v.y;
- fvPosOut[2]=v.z;
-
+void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert) {
+ Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData);
+ Vector3 v = varr[iFace * 3 + iVert]->get().vertex;
+ fvPosOut[0] = v.x;
+ fvPosOut[1] = v.y;
+ fvPosOut[2] = v.z;
}
-void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert){
-
-
- Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData);
- Vector3 v = varr[iFace*3+iVert]->get().normal;
- fvNormOut[0]=v.x;
- fvNormOut[1]=v.y;
- fvNormOut[2]=v.z;
+void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert) {
+ Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData);
+ Vector3 v = varr[iFace * 3 + iVert]->get().normal;
+ fvNormOut[0] = v.x;
+ fvNormOut[1] = v.y;
+ fvNormOut[2] = v.z;
}
-void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert){
+void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert) {
- Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData);
- Vector2 v = varr[iFace*3+iVert]->get().uv;
- fvTexcOut[0]=v.x;
- fvTexcOut[1]=v.y;
+ Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData);
+ Vector2 v = varr[iFace * 3 + iVert]->get().uv;
+ fvTexcOut[0] = v.x;
+ fvTexcOut[1] = v.y;
//fvTexcOut[1]=1.0-v.y;
-
}
-void SurfaceTool::mikktSetTSpaceBasic(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert){
+void SurfaceTool::mikktSetTSpaceBasic(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert) {
- Vector<List<Vertex>::Element*> &varr = *((Vector<List<Vertex>::Element*>*)pContext->m_pUserData);
- Vertex &vtx = varr[iFace*3+iVert]->get();
+ Vector<List<Vertex>::Element *> &varr = *((Vector<List<Vertex>::Element *> *)pContext->m_pUserData);
+ Vertex &vtx = varr[iFace * 3 + iVert]->get();
- vtx.tangent = Vector3(fvTangent[0],fvTangent[1],fvTangent[2]);
+ vtx.tangent = Vector3(fvTangent[0], fvTangent[1], fvTangent[2]);
vtx.binormal = vtx.normal.cross(vtx.tangent) * fSign;
}
-
void SurfaceTool::generate_tangents() {
- ERR_FAIL_COND(!(format&Mesh::ARRAY_FORMAT_TEX_UV));
- ERR_FAIL_COND(!(format&Mesh::ARRAY_FORMAT_NORMAL));
+ ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_TEX_UV));
+ ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_NORMAL));
- bool indexed = index_array.size()>0;
+ bool indexed = index_array.size() > 0;
if (indexed)
deindex();
-
SMikkTSpaceInterface mkif;
- mkif.m_getNormal=mikktGetNormal;
- mkif.m_getNumFaces=mikktGetNumFaces;
- mkif.m_getNumVerticesOfFace=mikktGetNumVerticesOfFace;
- mkif.m_getPosition=mikktGetPosition;
- mkif.m_getTexCoord=mikktGetTexCoord;
- mkif.m_setTSpaceBasic=mikktSetTSpaceBasic;
- mkif.m_setTSpace=NULL;
+ mkif.m_getNormal = mikktGetNormal;
+ mkif.m_getNumFaces = mikktGetNumFaces;
+ mkif.m_getNumVerticesOfFace = mikktGetNumVerticesOfFace;
+ mkif.m_getPosition = mikktGetPosition;
+ mkif.m_getTexCoord = mikktGetTexCoord;
+ mkif.m_setTSpaceBasic = mikktSetTSpaceBasic;
+ mkif.m_setTSpace = NULL;
SMikkTSpaceContext msc;
- msc.m_pInterface=&mkif;
+ msc.m_pInterface = &mkif;
- Vector<List<Vertex>::Element*> vtx;
+ Vector<List<Vertex>::Element *> vtx;
vtx.resize(vertex_array.size());
- int idx=0;
- for (List<Vertex>::Element *E=vertex_array.front();E;E=E->next()) {
- vtx[idx++]=E;
- E->get().binormal=Vector3();
- E->get().tangent=Vector3();
+ int idx = 0;
+ for (List<Vertex>::Element *E = vertex_array.front(); E; E = E->next()) {
+ vtx[idx++] = E;
+ E->get().binormal = Vector3();
+ E->get().tangent = Vector3();
}
- msc.m_pUserData=&vtx;
+ msc.m_pUserData = &vtx;
bool res = genTangSpaceDefault(&msc);
ERR_FAIL_COND(!res);
- format|=Mesh::ARRAY_FORMAT_TANGENT;
+ format |= Mesh::ARRAY_FORMAT_TANGENT;
if (indexed)
index();
-
-
}
void SurfaceTool::generate_normals() {
- ERR_FAIL_COND(primitive!=Mesh::PRIMITIVE_TRIANGLES);
+ ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
- bool was_indexed=index_array.size();
+ bool was_indexed = index_array.size();
deindex();
- HashMap<Vertex,Vector3,VertexHasher> vertex_hash;
+ HashMap<Vertex, Vector3, VertexHasher> vertex_hash;
- int count=0;
- bool smooth=false;
+ int count = 0;
+ bool smooth = false;
if (smooth_groups.has(0))
- smooth=smooth_groups[0];
+ smooth = smooth_groups[0];
- List< Vertex >::Element *B=vertex_array.front();
- for(List< Vertex >::Element *E=B;E;) {
+ List<Vertex>::Element *B = vertex_array.front();
+ for (List<Vertex>::Element *E = B; E;) {
- List< Vertex >::Element *v[3];
- v[0]=E;
- v[1]=v[0]->next();
+ List<Vertex>::Element *v[3];
+ v[0] = E;
+ v[1] = v[0]->next();
ERR_FAIL_COND(!v[1]);
- v[2]=v[1]->next();
+ v[2] = v[1]->next();
ERR_FAIL_COND(!v[2]);
- E=v[2]->next();
+ E = v[2]->next();
- Vector3 normal = Plane(v[0]->get().vertex,v[1]->get().vertex,v[2]->get().vertex).normal;
+ Vector3 normal = Plane(v[0]->get().vertex, v[1]->get().vertex, v[2]->get().vertex).normal;
if (smooth) {
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 *lv=vertex_hash.getptr(v[i]->get());
+ Vector3 *lv = vertex_hash.getptr(v[i]->get());
if (!lv) {
- vertex_hash.set(v[i]->get(),normal);
+ vertex_hash.set(v[i]->get(), normal);
} else {
- (*lv)+=normal;
+ (*lv) += normal;
}
}
} else {
- for(int i=0;i<3;i++) {
-
- v[i]->get().normal=normal;
+ for (int i = 0; i < 3; i++) {
+ v[i]->get().normal = normal;
}
}
- count+=3;
+ count += 3;
if (smooth_groups.has(count) || !E) {
if (vertex_hash.size()) {
- while (B!=E) {
+ while (B != E) {
-
- Vector3* lv=vertex_hash.getptr(B->get());
+ Vector3 *lv = vertex_hash.getptr(B->get());
if (lv) {
- B->get().normal=lv->normalized();
+ B->get().normal = lv->normalized();
}
- B=B->next();
+ B = B->next();
}
} else {
- B=E;
+ B = E;
}
vertex_hash.clear();
if (E) {
- smooth=smooth_groups[count];
- print_line("SMOOTH AT "+itos(count)+": "+itos(smooth));
-
+ smooth = smooth_groups[count];
+ print_line("SMOOTH AT " + itos(count) + ": " + itos(smooth));
}
}
-
}
- format|=Mesh::ARRAY_FORMAT_NORMAL;
+ format |= Mesh::ARRAY_FORMAT_NORMAL;
if (was_indexed) {
index();
smooth_groups.clear();
}
-
}
-void SurfaceTool::set_material(const Ref<Material>& p_material) {
+void SurfaceTool::set_material(const Ref<Material> &p_material) {
- material=p_material;
+ material = p_material;
}
void SurfaceTool::clear() {
- begun=false;
- primitive=Mesh::PRIMITIVE_LINES;
- format=0;
+ begun = false;
+ primitive = Mesh::PRIMITIVE_LINES;
+ format = 0;
last_bones.clear();
last_weights.clear();
index_array.clear();
vertex_array.clear();
smooth_groups.clear();
-
}
void SurfaceTool::_bind_methods() {
- ClassDB::bind_method(D_METHOD("begin","primitive"),&SurfaceTool::begin);
- ClassDB::bind_method(D_METHOD("add_vertex","vertex"),&SurfaceTool::add_vertex);
- ClassDB::bind_method(D_METHOD("add_color","color"),&SurfaceTool::add_color);
- ClassDB::bind_method(D_METHOD("add_normal","normal"),&SurfaceTool::add_normal);
- ClassDB::bind_method(D_METHOD("add_tangent","tangent"),&SurfaceTool::add_tangent);
- ClassDB::bind_method(D_METHOD("add_uv","uv"),&SurfaceTool::add_uv);
- ClassDB::bind_method(D_METHOD("add_uv2","uv2"),&SurfaceTool::add_uv2);
- ClassDB::bind_method(D_METHOD("add_bones","bones"),&SurfaceTool::add_bones);
- ClassDB::bind_method(D_METHOD("add_weights","weights"),&SurfaceTool::add_weights);
- ClassDB::bind_method(D_METHOD("add_smooth_group","smooth"),&SurfaceTool::add_smooth_group);
- ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertexes", "uvs", "colors", "uv2s", "normals", "tangents"),&SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()),DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>()));
- ClassDB::bind_method(D_METHOD("set_material","material:Material"),&SurfaceTool::set_material);
- ClassDB::bind_method(D_METHOD("index"),&SurfaceTool::index);
- ClassDB::bind_method(D_METHOD("deindex"),&SurfaceTool::deindex);
+ ClassDB::bind_method(D_METHOD("begin", "primitive"), &SurfaceTool::begin);
+ ClassDB::bind_method(D_METHOD("add_vertex", "vertex"), &SurfaceTool::add_vertex);
+ ClassDB::bind_method(D_METHOD("add_color", "color"), &SurfaceTool::add_color);
+ ClassDB::bind_method(D_METHOD("add_normal", "normal"), &SurfaceTool::add_normal);
+ ClassDB::bind_method(D_METHOD("add_tangent", "tangent"), &SurfaceTool::add_tangent);
+ ClassDB::bind_method(D_METHOD("add_uv", "uv"), &SurfaceTool::add_uv);
+ ClassDB::bind_method(D_METHOD("add_uv2", "uv2"), &SurfaceTool::add_uv2);
+ ClassDB::bind_method(D_METHOD("add_bones", "bones"), &SurfaceTool::add_bones);
+ ClassDB::bind_method(D_METHOD("add_weights", "weights"), &SurfaceTool::add_weights);
+ ClassDB::bind_method(D_METHOD("add_smooth_group", "smooth"), &SurfaceTool::add_smooth_group);
+ ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertexes", "uvs", "colors", "uv2s", "normals", "tangents"), &SurfaceTool::add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Vector3>()), DEFVAL(Vector<Plane>()));
+ ClassDB::bind_method(D_METHOD("set_material", "material:Material"), &SurfaceTool::set_material);
+ ClassDB::bind_method(D_METHOD("index"), &SurfaceTool::index);
+ ClassDB::bind_method(D_METHOD("deindex"), &SurfaceTool::deindex);
///ClassDB::bind_method(D_METHOD("generate_flat_normals"),&SurfaceTool::generate_flat_normals);
- ClassDB::bind_method(D_METHOD("generate_normals"),&SurfaceTool::generate_normals);
+ ClassDB::bind_method(D_METHOD("generate_normals"), &SurfaceTool::generate_normals);
ClassDB::bind_method(D_METHOD("add_index", "index"), &SurfaceTool::add_index);
- ClassDB::bind_method(D_METHOD("commit:Mesh","existing:Mesh"),&SurfaceTool::commit,DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("clear"),&SurfaceTool::clear);
-
+ ClassDB::bind_method(D_METHOD("commit:Mesh", "existing:Mesh"), &SurfaceTool::commit, DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("clear"), &SurfaceTool::clear);
}
-
SurfaceTool::SurfaceTool() {
- first=false;
- begun=false;
- primitive=Mesh::PRIMITIVE_LINES;
- format=0;
-
+ first = false;
+ begun = false;
+ primitive = Mesh::PRIMITIVE_LINES;
+ format = 0;
}
-
diff --git a/scene/resources/surface_tool.h b/scene/resources/surface_tool.h
index f859efbfe5..542c21e7b8 100644
--- a/scene/resources/surface_tool.h
+++ b/scene/resources/surface_tool.h
@@ -29,34 +29,32 @@
#ifndef SURFACE_TOOL_H
#define SURFACE_TOOL_H
-#include "scene/resources/mesh.h"
#include "mikktspace.h"
-
+#include "scene/resources/mesh.h"
class SurfaceTool : public Reference {
- GDCLASS(SurfaceTool, Reference );
+ GDCLASS(SurfaceTool, Reference);
+
public:
struct Vertex {
- Vector3 vertex;
- Color color;
- Vector3 normal; // normal, binormal, tangent
- Vector3 binormal;
- Vector3 tangent;
- Vector2 uv;
- Vector2 uv2;
- Vector<int> bones;
- Vector<float> weights;
+ Vector3 vertex;
+ Color color;
+ Vector3 normal; // normal, binormal, tangent
+ Vector3 binormal;
+ Vector3 tangent;
+ Vector2 uv;
+ Vector2 uv2;
+ Vector<int> bones;
+ Vector<float> weights;
- bool operator==(const Vertex& p_vertex) const;
+ bool operator==(const Vertex &p_vertex) const;
- Vertex() { }
+ Vertex() {}
};
-
private:
-
struct VertexHasher {
static _FORCE_INLINE_ uint32_t hash(const Vertex &p_vtx);
};
@@ -67,9 +65,9 @@ private:
int format;
Ref<Material> material;
//arrays
- List< Vertex > vertex_array;
- List< int > index_array;
- Map<int,bool> smooth_groups;
+ List<Vertex> vertex_array;
+ List<int> index_array;
+ Map<int, bool> smooth_groups;
//memory
Color last_color;
@@ -80,57 +78,54 @@ private:
Vector<float> last_weights;
Plane last_tangent;
- void _create_list(const Ref<Mesh>& p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index,int &lformat);
-
+ void _create_list(const Ref<Mesh> &p_existing, int p_surface, List<Vertex> *r_vertex, List<int> *r_index, int &lformat);
//mikktspace callbacks
- static int mikktGetNumFaces(const SMikkTSpaceContext * pContext);
- static int mikktGetNumVerticesOfFace(const SMikkTSpaceContext * pContext, const int iFace);
- static void mikktGetPosition(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert);
- static void mikktGetNormal(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert);
- static void mikktGetTexCoord(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert);
- static void mikktSetTSpaceBasic(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert);
-protected:
+ static int mikktGetNumFaces(const SMikkTSpaceContext *pContext);
+ static int mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace);
+ static void mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert);
+ static void mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert);
+ static void mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert);
+ static void mikktSetTSpaceBasic(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert);
+protected:
static void _bind_methods();
public:
-
void begin(Mesh::PrimitiveType p_primitive);
- void add_vertex( const Vector3& p_vertex);
- void add_color( Color p_color );
- void add_normal( const Vector3& p_normal);
- void add_tangent( const Plane& p_tangent );
- void add_uv( const Vector2& p_uv);
- void add_uv2( const Vector2& p_uv);
- void add_bones( const Vector<int>& p_indices);
- void add_weights( const Vector<float>& p_weights);
+ void add_vertex(const Vector3 &p_vertex);
+ void add_color(Color p_color);
+ void add_normal(const Vector3 &p_normal);
+ void add_tangent(const Plane &p_tangent);
+ void add_uv(const Vector2 &p_uv);
+ void add_uv2(const Vector2 &p_uv);
+ void add_bones(const Vector<int> &p_indices);
+ void add_weights(const Vector<float> &p_weights);
void add_smooth_group(bool p_smooth);
- void add_triangle_fan( const Vector<Vector3>& p_vertexes, const Vector<Vector2>& p_uvs=Vector<Vector2>(), const Vector<Color>& p_colors=Vector<Color>(), const Vector<Vector2>& p_uv2s=Vector<Vector2>(), const Vector<Vector3>& p_normals=Vector<Vector3>(), const Vector<Plane>& p_tangents=Vector<Plane>() );
+ void add_triangle_fan(const Vector<Vector3> &p_vertexes, const Vector<Vector2> &p_uvs = Vector<Vector2>(), const Vector<Color> &p_colors = Vector<Color>(), const Vector<Vector2> &p_uv2s = Vector<Vector2>(), const Vector<Vector3> &p_normals = Vector<Vector3>(), const Vector<Plane> &p_tangents = Vector<Plane>());
- void add_index( int p_index);
+ void add_index(int p_index);
void index();
void deindex();
void generate_normals();
void generate_tangents();
- void add_to_format(int p_flags) { format|=p_flags; }
+ void add_to_format(int p_flags) { format |= p_flags; }
- void set_material(const Ref<Material>& p_material);
+ void set_material(const Ref<Material> &p_material);
void clear();
- List< Vertex > &get_vertex_array() { return vertex_array; }
+ List<Vertex> &get_vertex_array() { return vertex_array; }
- void create_from(const Ref<Mesh>& p_existing, int p_surface);
- void append_from(const Ref<Mesh>& p_existing, int p_surface,const Transform& p_xform);
- Ref<Mesh> commit(const Ref<Mesh>& p_existing=Ref<Mesh>());
+ void create_from(const Ref<Mesh> &p_existing, int p_surface);
+ void append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform &p_xform);
+ Ref<Mesh> commit(const Ref<Mesh> &p_existing = Ref<Mesh>());
SurfaceTool();
};
-
#endif
diff --git a/scene/resources/texture.cpp b/scene/resources/texture.cpp
index 62feb7b37c..f979c5c758 100644
--- a/scene/resources/texture.cpp
+++ b/scene/resources/texture.cpp
@@ -27,213 +27,184 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "texture.h"
-#include "io/image_loader.h"
#include "core/os/os.h"
-
-
+#include "io/image_loader.h"
Size2 Texture::get_size() const {
- return Size2(get_width(),get_height());
+ return Size2(get_width(), get_height());
}
+void Texture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const {
-void Texture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const {
-
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, get_size()),get_rid(),false,p_modulate,p_transpose);
-
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, get_size()), get_rid(), false, p_modulate, p_transpose);
}
-void Texture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const {
-
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,get_rid(),p_tile,p_modulate,p_transpose);
+void Texture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const {
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, get_rid(), p_tile, p_modulate, p_transpose);
}
-void Texture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{
+void Texture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const {
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,get_rid(),p_src_rect,p_modulate,p_transpose);
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, get_rid(), p_src_rect, p_modulate, p_transpose);
}
-bool Texture::get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const {
+bool Texture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const {
- r_rect=p_rect;
- r_src_rect=p_src_rect;
+ r_rect = p_rect;
+ r_src_rect = p_src_rect;
return true;
}
void Texture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_width"),&Texture::get_width);
- ClassDB::bind_method(D_METHOD("get_height"),&Texture::get_height);
- ClassDB::bind_method(D_METHOD("get_size"),&Texture::get_size);
- ClassDB::bind_method(D_METHOD("has_alpha"),&Texture::has_alpha);
- ClassDB::bind_method(D_METHOD("set_flags","flags"),&Texture::set_flags);
- ClassDB::bind_method(D_METHOD("get_flags"),&Texture::get_flags);
- ClassDB::bind_method(D_METHOD("draw","canvas_item","pos","modulate","transpose"),&Texture::draw,DEFVAL(Color(1,1,1)),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_rect","canvas_item","rect","tile","modulate","transpose"),&Texture::draw_rect,DEFVAL(Color(1,1,1)),DEFVAL(false));
- ClassDB::bind_method(D_METHOD("draw_rect_region","canvas_item","rect","src_rect","modulate","transpose"),&Texture::draw_rect_region,DEFVAL(Color(1,1,1)),DEFVAL(false));
-
- BIND_CONSTANT( FLAG_MIPMAPS );
- BIND_CONSTANT( FLAG_REPEAT );
- BIND_CONSTANT( FLAG_FILTER );
- BIND_CONSTANT( FLAG_VIDEO_SURFACE );
- BIND_CONSTANT( FLAGS_DEFAULT );
- BIND_CONSTANT( FLAG_ANISOTROPIC_FILTER );
- BIND_CONSTANT( FLAG_CONVERT_TO_LINEAR );
- BIND_CONSTANT( FLAG_MIRRORED_REPEAT );
-
+ ClassDB::bind_method(D_METHOD("get_width"), &Texture::get_width);
+ ClassDB::bind_method(D_METHOD("get_height"), &Texture::get_height);
+ ClassDB::bind_method(D_METHOD("get_size"), &Texture::get_size);
+ ClassDB::bind_method(D_METHOD("has_alpha"), &Texture::has_alpha);
+ ClassDB::bind_method(D_METHOD("set_flags", "flags"), &Texture::set_flags);
+ ClassDB::bind_method(D_METHOD("get_flags"), &Texture::get_flags);
+ ClassDB::bind_method(D_METHOD("draw", "canvas_item", "pos", "modulate", "transpose"), &Texture::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_rect", "canvas_item", "rect", "tile", "modulate", "transpose"), &Texture::draw_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("draw_rect_region", "canvas_item", "rect", "src_rect", "modulate", "transpose"), &Texture::draw_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false));
+
+ BIND_CONSTANT(FLAG_MIPMAPS);
+ BIND_CONSTANT(FLAG_REPEAT);
+ BIND_CONSTANT(FLAG_FILTER);
+ BIND_CONSTANT(FLAG_VIDEO_SURFACE);
+ BIND_CONSTANT(FLAGS_DEFAULT);
+ BIND_CONSTANT(FLAG_ANISOTROPIC_FILTER);
+ BIND_CONSTANT(FLAG_CONVERT_TO_LINEAR);
+ BIND_CONSTANT(FLAG_MIRRORED_REPEAT);
}
Texture::Texture() {
-
-
-
}
-
-
/////////////////////
-
-
-
-
void ImageTexture::reload_from_file() {
- String path=get_path();
+ String path = get_path();
if (!path.is_resource_file())
return;
uint32_t flags = get_flags();
Image img;
- Error err = ImageLoader::load_image(path,&img);
- ERR_FAIL_COND(err!=OK);
-
- create_from_image(img,flags);
+ Error err = ImageLoader::load_image(path, &img);
+ ERR_FAIL_COND(err != OK);
+ create_from_image(img, flags);
}
-bool ImageTexture::_set(const StringName& p_name, const Variant& p_value) {
+bool ImageTexture::_set(const StringName &p_name, const Variant &p_value) {
- if (p_name=="image" && p_value.get_type()==Variant::IMAGE)
- create_from_image( p_value,flags );
- else if (p_name=="flags")
- if (w*h==0)
- flags=p_value;
+ if (p_name == "image" && p_value.get_type() == Variant::IMAGE)
+ create_from_image(p_value, flags);
+ else if (p_name == "flags")
+ if (w * h == 0)
+ flags = p_value;
else
set_flags(p_value);
- else if (p_name=="size") {
+ else if (p_name == "size") {
Size2 s = p_value;
- w=s.width;
- h=s.height;
- VisualServer::get_singleton()->texture_set_size_override(texture,w,h);
- } else if (p_name=="storage") {
- storage=Storage(p_value.operator int());
- } else if (p_name=="lossy_quality") {
- lossy_storage_quality=p_value;
- } else if (p_name=="_data") {
+ w = s.width;
+ h = s.height;
+ VisualServer::get_singleton()->texture_set_size_override(texture, w, h);
+ } else if (p_name == "storage") {
+ storage = Storage(p_value.operator int());
+ } else if (p_name == "lossy_quality") {
+ lossy_storage_quality = p_value;
+ } else if (p_name == "_data") {
_set_data(p_value);
} else
return false;
return true;
-
}
-bool ImageTexture::_get(const StringName& p_name,Variant &r_ret) const {
-
+bool ImageTexture::_get(const StringName &p_name, Variant &r_ret) const {
- if (p_name=="image_data") {
+ if (p_name == "image_data") {
- } else if (p_name=="image")
- r_ret= get_data();
- else if (p_name=="flags")
- r_ret= flags;
- else if (p_name=="size")
- r_ret=Size2(w,h);
- else if (p_name=="storage")
- r_ret= storage;
- else if (p_name=="lossy_quality")
- r_ret= lossy_storage_quality;
+ } else if (p_name == "image")
+ r_ret = get_data();
+ else if (p_name == "flags")
+ r_ret = flags;
+ else if (p_name == "size")
+ r_ret = Size2(w, h);
+ else if (p_name == "storage")
+ r_ret = storage;
+ else if (p_name == "lossy_quality")
+ r_ret = lossy_storage_quality;
else
return false;
return true;
}
+void ImageTexture::_get_property_list(List<PropertyInfo> *p_list) const {
-
-
-void ImageTexture::_get_property_list( List<PropertyInfo> *p_list) const {
-
-
- PropertyHint img_hint=PROPERTY_HINT_NONE;
- if (storage==STORAGE_COMPRESS_LOSSY) {
- img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSY;
- } else if (storage==STORAGE_COMPRESS_LOSSLESS) {
- img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS;
+ PropertyHint img_hint = PROPERTY_HINT_NONE;
+ if (storage == STORAGE_COMPRESS_LOSSY) {
+ img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSY;
+ } else if (storage == STORAGE_COMPRESS_LOSSLESS) {
+ img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS;
}
-
-
- p_list->push_back( PropertyInfo( Variant::INT, "flags", PROPERTY_HINT_FLAGS,"Mipmaps,Repeat,Filter,Anisotropic,sRGB,Mirrored Repeat") );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "image", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::VECTOR2, "size",PROPERTY_HINT_NONE, ""));
- p_list->push_back( PropertyInfo( Variant::INT, "storage", PROPERTY_HINT_ENUM,"Uncompressed,Compress Lossy,Compress Lossless"));
- p_list->push_back( PropertyInfo( Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE,"0.0,1.0,0.01" ));
+ p_list->push_back(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter,Anisotropic,sRGB,Mirrored Repeat"));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "image", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, ""));
+ p_list->push_back(PropertyInfo(Variant::INT, "storage", PROPERTY_HINT_ENUM, "Uncompressed,Compress Lossy,Compress Lossless"));
+ p_list->push_back(PropertyInfo(Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"));
}
-void ImageTexture::_reload_hook(const RID& p_hook) {
+void ImageTexture::_reload_hook(const RID &p_hook) {
- String path=get_path();
+ String path = get_path();
if (!path.is_resource_file())
return;
Image img;
- Error err = ImageLoader::load_image(path,&img);
+ Error err = ImageLoader::load_image(path, &img);
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
-
- VisualServer::get_singleton()->texture_set_data(texture,img);
+ VisualServer::get_singleton()->texture_set_data(texture, img);
_change_notify();
}
-void ImageTexture::create(int p_width, int p_height,Image::Format p_format,uint32_t p_flags) {
-
- flags=p_flags;
- VisualServer::get_singleton()->texture_allocate(texture,p_width, p_height, p_format, p_flags);
- format=p_format;
- w=p_width;
- h=p_height;
+void ImageTexture::create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags) {
+ flags = p_flags;
+ VisualServer::get_singleton()->texture_allocate(texture, p_width, p_height, p_format, p_flags);
+ format = p_format;
+ w = p_width;
+ h = p_height;
}
-void ImageTexture::create_from_image(const Image& p_image, uint32_t p_flags) {
+void ImageTexture::create_from_image(const Image &p_image, uint32_t p_flags) {
- flags=p_flags;
- w=p_image.get_width();
- h=p_image.get_height();
- format=p_image.get_format();
+ flags = p_flags;
+ w = p_image.get_width();
+ h = p_image.get_height();
+ format = p_image.get_format();
- VisualServer::get_singleton()->texture_allocate(texture,p_image.get_width(),p_image.get_height(), p_image.get_format(), p_flags);
- VisualServer::get_singleton()->texture_set_data(texture,p_image);
+ VisualServer::get_singleton()->texture_allocate(texture, p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags);
+ VisualServer::get_singleton()->texture_set_data(texture, p_image);
_change_notify();
}
void ImageTexture::set_flags(uint32_t p_flags) {
-
-
-/* uint32_t cube = flags & FLAG_CUBEMAP;
+ /* uint32_t cube = flags & FLAG_CUBEMAP;
if (flags == p_flags&cube)
return;
flags=p_flags|cube; */
- flags=p_flags;
- VisualServer::get_singleton()->texture_set_flags(texture,p_flags);
-
+ flags = p_flags;
+ VisualServer::get_singleton()->texture_set_flags(texture, p_flags);
}
uint32_t ImageTexture::get_flags() const {
@@ -246,24 +217,23 @@ Image::Format ImageTexture::get_format() const {
return format;
}
-void ImageTexture::load(const String& p_path) {
-
- Image img;
- img.load(p_path);
- create_from_image(img);
+void ImageTexture::load(const String &p_path) {
+ Image img;
+ img.load(p_path);
+ create_from_image(img);
}
-void ImageTexture::set_data(const Image& p_image) {
+void ImageTexture::set_data(const Image &p_image) {
- VisualServer::get_singleton()->texture_set_data(texture,p_image);
+ VisualServer::get_singleton()->texture_set_data(texture, p_image);
_change_notify();
}
void ImageTexture::_resource_path_changed() {
- String path=get_path();
+ String path = get_path();
}
Image ImageTexture::get_data() const {
@@ -281,7 +251,6 @@ int ImageTexture::get_height() const {
return h;
}
-
RID ImageTexture::get_rid() const {
return texture;
@@ -289,7 +258,7 @@ RID ImageTexture::get_rid() const {
void ImageTexture::fix_alpha_edges() {
- if (format==Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) {
+ if (format == Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) {
Image img = get_data();
img.fix_alpha_edges();
@@ -299,7 +268,7 @@ void ImageTexture::fix_alpha_edges() {
void ImageTexture::premultiply_alpha() {
- if (format==Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) {
+ if (format == Image::FORMAT_RGBA8 /*&& !(flags&FLAG_CUBEMAP)*/) {
Image img = get_data();
img.premultiply_alpha();
@@ -311,69 +280,64 @@ void ImageTexture::normal_to_xy() {
Image img = get_data();
img.normalmap_to_xy();
- create_from_image(img,flags);
+ create_from_image(img, flags);
}
void ImageTexture::shrink_x2_and_keep_size() {
- Size2 sizeov=get_size();
+ Size2 sizeov = get_size();
Image img = get_data();
- img.resize(img.get_width()/2,img.get_height()/2,Image::INTERPOLATE_BILINEAR);
- create_from_image(img,flags);
+ img.resize(img.get_width() / 2, img.get_height() / 2, Image::INTERPOLATE_BILINEAR);
+ create_from_image(img, flags);
set_size_override(sizeov);
-
}
bool ImageTexture::has_alpha() const {
- return ( format==Image::FORMAT_LA8 || format==Image::FORMAT_RGBA8 );
+ return (format == Image::FORMAT_LA8 || format == Image::FORMAT_RGBA8);
}
+void ImageTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const {
-void ImageTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const {
-
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, Size2(w,h)),texture,false,p_modulate,p_transpose);
-
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose);
}
-void ImageTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const {
+void ImageTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const {
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,texture,p_tile,p_modulate,p_transpose);
-
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose);
}
-void ImageTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{
+void ImageTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const {
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,texture,p_src_rect,p_modulate,p_transpose);
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose);
}
-void ImageTexture::set_size_override(const Size2& p_size) {
+void ImageTexture::set_size_override(const Size2 &p_size) {
- Size2 s=p_size;
- if (s.x!=0)
- w=s.x;
- if (s.y!=0)
- h=s.y;
- VisualServer::get_singleton()->texture_set_size_override(texture,w,h);
+ Size2 s = p_size;
+ if (s.x != 0)
+ w = s.x;
+ if (s.y != 0)
+ h = s.y;
+ VisualServer::get_singleton()->texture_set_size_override(texture, w, h);
}
-void ImageTexture::set_path(const String& p_path,bool p_take_over) {
+void ImageTexture::set_path(const String &p_path, bool p_take_over) {
if (texture.is_valid()) {
- VisualServer::get_singleton()->texture_set_path(texture,p_path);
+ VisualServer::get_singleton()->texture_set_path(texture, p_path);
}
- Resource::set_path(p_path,p_take_over);
+ Resource::set_path(p_path, p_take_over);
}
-
void ImageTexture::set_storage(Storage p_storage) {
- storage=p_storage;
+ storage = p_storage;
}
ImageTexture::Storage ImageTexture::get_storage() const {
@@ -383,7 +347,7 @@ ImageTexture::Storage ImageTexture::get_storage() const {
void ImageTexture::set_lossy_storage_quality(float p_lossy_storage_quality) {
- lossy_storage_quality=p_lossy_storage_quality;
+ lossy_storage_quality = p_lossy_storage_quality;
}
float ImageTexture::get_lossy_storage_quality() const {
@@ -406,57 +370,50 @@ void ImageTexture::_set_data(Dictionary p_data) {
void ImageTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("create","width","height","format","flags"),&ImageTexture::create,DEFVAL(FLAGS_DEFAULT));
- ClassDB::bind_method(D_METHOD("create_from_image","image","flags"),&ImageTexture::create_from_image,DEFVAL(FLAGS_DEFAULT));
- ClassDB::bind_method(D_METHOD("get_format"),&ImageTexture::get_format);
- ClassDB::bind_method(D_METHOD("load","path"),&ImageTexture::load);
- ClassDB::bind_method(D_METHOD("set_data","image"),&ImageTexture::set_data);
- ClassDB::bind_method(D_METHOD("get_data","cube_side"),&ImageTexture::get_data);
- ClassDB::bind_method(D_METHOD("set_storage","mode"),&ImageTexture::set_storage);
- ClassDB::bind_method(D_METHOD("get_storage"),&ImageTexture::get_storage);
- ClassDB::bind_method(D_METHOD("set_lossy_storage_quality","quality"),&ImageTexture::set_lossy_storage_quality);
- ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"),&ImageTexture::get_lossy_storage_quality);
- ClassDB::bind_method(D_METHOD("fix_alpha_edges"),&ImageTexture::fix_alpha_edges);
- ClassDB::bind_method(D_METHOD("premultiply_alpha"),&ImageTexture::premultiply_alpha);
- ClassDB::bind_method(D_METHOD("normal_to_xy"),&ImageTexture::normal_to_xy);
- ClassDB::bind_method(D_METHOD("shrink_x2_and_keep_size"),&ImageTexture::shrink_x2_and_keep_size);
-
- ClassDB::bind_method(D_METHOD("set_size_override","size"),&ImageTexture::set_size_override);
- ClassDB::set_method_flags(get_class_static(),_scs_create("fix_alpha_edges"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::set_method_flags(get_class_static(),_scs_create("premultiply_alpha"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::set_method_flags(get_class_static(),_scs_create("normal_to_xy"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::set_method_flags(get_class_static(),_scs_create("shrink_x2_and_keep_size"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR);
- ClassDB::bind_method(D_METHOD("_reload_hook","rid"),&ImageTexture::_reload_hook);
-
-
- BIND_CONSTANT( STORAGE_RAW );
- BIND_CONSTANT( STORAGE_COMPRESS_LOSSY );
- BIND_CONSTANT( STORAGE_COMPRESS_LOSSLESS );
-
-
+ ClassDB::bind_method(D_METHOD("create", "width", "height", "format", "flags"), &ImageTexture::create, DEFVAL(FLAGS_DEFAULT));
+ ClassDB::bind_method(D_METHOD("create_from_image", "image", "flags"), &ImageTexture::create_from_image, DEFVAL(FLAGS_DEFAULT));
+ ClassDB::bind_method(D_METHOD("get_format"), &ImageTexture::get_format);
+ ClassDB::bind_method(D_METHOD("load", "path"), &ImageTexture::load);
+ ClassDB::bind_method(D_METHOD("set_data", "image"), &ImageTexture::set_data);
+ ClassDB::bind_method(D_METHOD("get_data", "cube_side"), &ImageTexture::get_data);
+ ClassDB::bind_method(D_METHOD("set_storage", "mode"), &ImageTexture::set_storage);
+ ClassDB::bind_method(D_METHOD("get_storage"), &ImageTexture::get_storage);
+ ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &ImageTexture::set_lossy_storage_quality);
+ ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &ImageTexture::get_lossy_storage_quality);
+ ClassDB::bind_method(D_METHOD("fix_alpha_edges"), &ImageTexture::fix_alpha_edges);
+ ClassDB::bind_method(D_METHOD("premultiply_alpha"), &ImageTexture::premultiply_alpha);
+ ClassDB::bind_method(D_METHOD("normal_to_xy"), &ImageTexture::normal_to_xy);
+ ClassDB::bind_method(D_METHOD("shrink_x2_and_keep_size"), &ImageTexture::shrink_x2_and_keep_size);
+
+ ClassDB::bind_method(D_METHOD("set_size_override", "size"), &ImageTexture::set_size_override);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("fix_alpha_edges"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("premultiply_alpha"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("normal_to_xy"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::set_method_flags(get_class_static(), _scs_create("shrink_x2_and_keep_size"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
+ ClassDB::bind_method(D_METHOD("_reload_hook", "rid"), &ImageTexture::_reload_hook);
+
+ BIND_CONSTANT(STORAGE_RAW);
+ BIND_CONSTANT(STORAGE_COMPRESS_LOSSY);
+ BIND_CONSTANT(STORAGE_COMPRESS_LOSSLESS);
}
ImageTexture::ImageTexture() {
- w=h=0;
- flags=FLAGS_DEFAULT;
+ w = h = 0;
+ flags = FLAGS_DEFAULT;
texture = VisualServer::get_singleton()->texture_create();
storage = STORAGE_RAW;
- lossy_storage_quality=0.7;
-
-
+ lossy_storage_quality = 0.7;
}
-
ImageTexture::~ImageTexture() {
- VisualServer::get_singleton()->free( texture );
+ VisualServer::get_singleton()->free(texture);
}
//////////////////////////////////////////
-
-void StreamTexture::_requested_3d(void* p_ud) {
+void StreamTexture::_requested_3d(void *p_ud) {
StreamTexture *st = (StreamTexture *)p_ud;
Ref<StreamTexture> stex(st);
@@ -464,18 +421,16 @@ void StreamTexture::_requested_3d(void* p_ud) {
request_3d_callback(stex);
}
-void StreamTexture::_requested_srgb(void* p_ud) {
+void StreamTexture::_requested_srgb(void *p_ud) {
StreamTexture *st = (StreamTexture *)p_ud;
Ref<StreamTexture> stex(st);
ERR_FAIL_COND(!request_srgb_callback);
request_srgb_callback(stex);
-
}
-StreamTexture::TextureFormatRequestCallback StreamTexture::request_3d_callback=NULL;
-StreamTexture::TextureFormatRequestCallback StreamTexture::request_srgb_callback=NULL;
-
+StreamTexture::TextureFormatRequestCallback StreamTexture::request_3d_callback = NULL;
+StreamTexture::TextureFormatRequestCallback StreamTexture::request_srgb_callback = NULL;
uint32_t StreamTexture::get_flags() const {
@@ -486,81 +441,77 @@ Image::Format StreamTexture::get_format() const {
return format;
}
+Error StreamTexture::_load_data(const String &p_path, int &tw, int &th, int &flags, Image &image, int p_size_limit) {
-Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,Image& image,int p_size_limit) {
-
-
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
- ERR_FAIL_COND_V(!f,ERR_CANT_OPEN);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ);
+ ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
uint8_t header[4];
- f->get_buffer(header,4);
- if (header[0]!='G' || header[1]!='D' || header[2]!='S' || header[3]!='T') {
+ f->get_buffer(header, 4);
+ if (header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T') {
memdelete(f);
- ERR_FAIL_COND_V(header[0]!='G' || header[1]!='D' || header[2]!='S' || header[3]!='T',ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T', ERR_FILE_CORRUPT);
}
tw = f->get_32();
th = f->get_32();
- flags= f->get_32(); //texture flags!
+ flags = f->get_32(); //texture flags!
uint32_t df = f->get_32(); //data format
- print_line("width: "+itos(tw));
- print_line("height: "+itos(th));
- print_line("flags: "+itos(flags));
- print_line("df: "+itos(df));
+ print_line("width: " + itos(tw));
+ print_line("height: " + itos(th));
+ print_line("flags: " + itos(flags));
+ print_line("df: " + itos(df));
-
- if (request_3d_callback && df&FORMAT_BIT_DETECT_3D) {
- print_line("request detect 3D at "+p_path);
- VS::get_singleton()->texture_set_detect_3d_callback(texture,_requested_3d,this);
+ if (request_3d_callback && df & FORMAT_BIT_DETECT_3D) {
+ print_line("request detect 3D at " + p_path);
+ VS::get_singleton()->texture_set_detect_3d_callback(texture, _requested_3d, this);
} else {
- print_line("not requesting detect 3D at "+p_path);
- VS::get_singleton()->texture_set_detect_3d_callback(texture,NULL,NULL);
+ print_line("not requesting detect 3D at " + p_path);
+ VS::get_singleton()->texture_set_detect_3d_callback(texture, NULL, NULL);
}
- if (request_srgb_callback && df&FORMAT_BIT_DETECT_SRGB) {
- print_line("request detect srgb at "+p_path);
- VS::get_singleton()->texture_set_detect_srgb_callback(texture,_requested_srgb,this);
+ if (request_srgb_callback && df & FORMAT_BIT_DETECT_SRGB) {
+ print_line("request detect srgb at " + p_path);
+ VS::get_singleton()->texture_set_detect_srgb_callback(texture, _requested_srgb, this);
} else {
- VS::get_singleton()->texture_set_detect_srgb_callback(texture,NULL,NULL);
- print_line("not requesting detect srgb at "+p_path);
+ VS::get_singleton()->texture_set_detect_srgb_callback(texture, NULL, NULL);
+ print_line("not requesting detect srgb at " + p_path);
}
- if (!(df&FORMAT_BIT_STREAM)) {
- p_size_limit=0;
+ if (!(df & FORMAT_BIT_STREAM)) {
+ p_size_limit = 0;
}
-
- if (df&FORMAT_BIT_LOSSLESS || df&FORMAT_BIT_LOSSY) {
+ if (df & FORMAT_BIT_LOSSLESS || df & FORMAT_BIT_LOSSY) {
//look for a PNG or WEBP file inside
- int sw=tw;
- int sh=th;
+ int sw = tw;
+ int sh = th;
uint32_t mipmaps = f->get_32();
uint32_t size = f->get_32();
- print_line("mipmaps: "+itos(mipmaps));
+ print_line("mipmaps: " + itos(mipmaps));
- while(mipmaps>1 && p_size_limit>0 && (sw>p_size_limit || sh>p_size_limit)) {
+ while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) {
- f->seek(f->get_pos()+size);
+ f->seek(f->get_pos() + size);
mipmaps = f->get_32();
size = f->get_32();
- sw=MAX(sw>>1,1);
- sh=MAX(sh>>1,1);
+ sw = MAX(sw >> 1, 1);
+ sh = MAX(sh >> 1, 1);
mipmaps--;
}
//mipmaps need to be read independently, they will be later combined
Vector<Image> mipmap_images;
- int total_size=0;
+ int total_size = 0;
- for(int i=0;i<mipmaps;i++) {
+ for (int i = 0; i < mipmaps; i++) {
- if (i>0) {
+ if (i > 0) {
size = f->get_32();
}
@@ -568,11 +519,11 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,
pv.resize(size);
{
PoolVector<uint8_t>::Write w = pv.write();
- f->get_buffer(w.ptr(),size);
+ f->get_buffer(w.ptr(), size);
}
Image img;
- if (df&FORMAT_BIT_LOSSLESS) {
+ if (df & FORMAT_BIT_LOSSLESS) {
img = Image::lossless_unpacker(pv);
} else {
img = Image::lossy_unpacker(pv);
@@ -580,21 +531,20 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,
if (img.empty()) {
memdelete(f);
- ERR_FAIL_COND_V(img.empty(),ERR_FILE_CORRUPT);
+ ERR_FAIL_COND_V(img.empty(), ERR_FILE_CORRUPT);
}
- total_size+=img.get_data().size();
+ total_size += img.get_data().size();
mipmap_images.push_back(img);
}
- print_line("mipmap read total: "+itos(mipmap_images.size()));
-
+ print_line("mipmap read total: " + itos(mipmap_images.size()));
memdelete(f); //no longer needed
- if (mipmap_images.size()==1) {
+ if (mipmap_images.size() == 1) {
- image=mipmap_images[0];
+ image = mipmap_images[0];
return OK;
} else {
@@ -602,82 +552,80 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,
img_data.resize(total_size);
{
- PoolVector<uint8_t>::Write w=img_data.write();
+ PoolVector<uint8_t>::Write w = img_data.write();
- int ofs=0;
- for(int i=0;i<mipmap_images.size();i++) {
+ int ofs = 0;
+ for (int i = 0; i < mipmap_images.size(); i++) {
PoolVector<uint8_t> id = mipmap_images[i].get_data();
int len = id.size();
PoolVector<uint8_t>::Read r = id.read();
- copymem(&w[ofs],r.ptr(),len);
- ofs+=len;
+ copymem(&w[ofs], r.ptr(), len);
+ ofs += len;
}
}
- image = Image(sw,sh,true,mipmap_images[0].get_format(),img_data);
+ image = Image(sw, sh, true, mipmap_images[0].get_format(), img_data);
return OK;
}
} else {
//look for regular format
- Image::Format format = (Image::Format)(df&FORMAT_MASK_IMAGE_FORMAT);
- bool mipmaps = df&FORMAT_BIT_HAS_MIPMAPS;
+ Image::Format format = (Image::Format)(df & FORMAT_MASK_IMAGE_FORMAT);
+ bool mipmaps = df & FORMAT_BIT_HAS_MIPMAPS;
if (!mipmaps) {
- int size = Image::get_image_data_size(tw,th,format,0);
+ int size = Image::get_image_data_size(tw, th, format, 0);
PoolVector<uint8_t> img_data;
img_data.resize(size);
{
- PoolVector<uint8_t>::Write w=img_data.write();
- f->get_buffer(w.ptr(),size);
+ PoolVector<uint8_t>::Write w = img_data.write();
+ f->get_buffer(w.ptr(), size);
}
memdelete(f);
- image = Image(tw,th,false,format,img_data);
+ image = Image(tw, th, false, format, img_data);
return OK;
} else {
- int sw=tw;
- int sh=th;
-
- int mipmaps = Image::get_image_required_mipmaps(tw,th,format);
- int total_size = Image::get_image_data_size(tw,th,format,mipmaps);
- int idx=0;
- int ofs=0;
+ int sw = tw;
+ int sh = th;
+ int mipmaps = Image::get_image_required_mipmaps(tw, th, format);
+ int total_size = Image::get_image_data_size(tw, th, format, mipmaps);
+ int idx = 0;
+ int ofs = 0;
- while(mipmaps>1 && p_size_limit>0 && (sw>p_size_limit || sh>p_size_limit)) {
+ while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) {
- sw=MAX(sw>>1,1);
- sh=MAX(sh>>1,1);
+ sw = MAX(sw >> 1, 1);
+ sh = MAX(sh >> 1, 1);
mipmaps--;
idx++;
}
- if (idx>0) {
- ofs=Image::get_image_data_size(tw,th,format,idx-1);
+ if (idx > 0) {
+ ofs = Image::get_image_data_size(tw, th, format, idx - 1);
}
- if (total_size - ofs <=0) {
+ if (total_size - ofs <= 0) {
memdelete(f);
ERR_FAIL_V(ERR_FILE_CORRUPT);
}
- f->seek(f->get_pos()+ofs);
-
+ f->seek(f->get_pos() + ofs);
PoolVector<uint8_t> img_data;
img_data.resize(total_size - ofs);
{
- PoolVector<uint8_t>::Write w=img_data.write();
- int bytes = f->get_buffer(w.ptr(),total_size - ofs);
- print_line("requested read: "+itos(total_size - ofs)+" but got: "+itos(bytes));
+ PoolVector<uint8_t>::Write w = img_data.write();
+ int bytes = f->get_buffer(w.ptr(), total_size - ofs);
+ print_line("requested read: " + itos(total_size - ofs) + " but got: " + itos(bytes));
memdelete(f);
@@ -686,7 +634,7 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,
}
}
- image = Image(sw,sh,true,format,img_data);
+ image = Image(sw, sh, true, format, img_data);
return OK;
}
@@ -695,23 +643,22 @@ Error StreamTexture::_load_data(const String& p_path,int &tw,int &th,int& flags,
return ERR_BUG; //unreachable
}
-Error StreamTexture::load(const String& p_path) {
-
+Error StreamTexture::load(const String &p_path) {
- int lw,lh,lflags;
+ int lw, lh, lflags;
Image image;
- Error err = _load_data(p_path,lw,lh,lflags,image);
+ Error err = _load_data(p_path, lw, lh, lflags, image);
if (err)
return err;
- VS::get_singleton()->texture_allocate(texture,image.get_width(),image.get_height(),image.get_format(),lflags);
- VS::get_singleton()->texture_set_data(texture,image);
+ VS::get_singleton()->texture_allocate(texture, image.get_width(), image.get_height(), image.get_format(), lflags);
+ VS::get_singleton()->texture_set_data(texture, image);
- w=lw;
- h=lh;
- flags=lflags;
- path_to_file=p_path;
- format=image.get_format();
+ w = lw;
+ h = lh;
+ flags = lflags;
+ path_to_file = p_path;
+ format = image.get_format();
return OK;
}
@@ -733,26 +680,23 @@ RID StreamTexture::get_rid() const {
return texture;
}
+void StreamTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const {
-void StreamTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const {
-
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,Rect2( p_pos, Size2(w,h)),texture,false,p_modulate,p_transpose);
-
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose);
}
-void StreamTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const {
+void StreamTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const {
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item,p_rect,texture,p_tile,p_modulate,p_transpose);
-
+ VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose);
}
-void StreamTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const{
+void StreamTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const {
- if ((w|h)==0)
+ if ((w | h) == 0)
return;
- VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,p_rect,texture,p_src_rect,p_modulate,p_transpose);
+ VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose);
}
bool StreamTexture::has_alpha() const {
@@ -765,16 +709,15 @@ Image StreamTexture::get_data() const {
return VS::get_singleton()->texture_get_data(texture);
}
-void StreamTexture::set_flags(uint32_t p_flags){
-
+void StreamTexture::set_flags(uint32_t p_flags) {
}
void StreamTexture::reload_from_file() {
#ifdef TOOLS_ENABLED
String ipath = get_import_path();
- if (ipath.is_resource_file() && ipath!=path_to_file) {
- path_to_file=ipath;
+ if (ipath.is_resource_file() && ipath != path_to_file) {
+ path_to_file = ipath;
}
#endif
load(path_to_file);
@@ -782,19 +725,18 @@ void StreamTexture::reload_from_file() {
void StreamTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("load","path"),&StreamTexture::load);
- ClassDB::bind_method(D_METHOD("get_load_path"),&StreamTexture::get_load_path);
+ ClassDB::bind_method(D_METHOD("load", "path"), &StreamTexture::load);
+ ClassDB::bind_method(D_METHOD("get_load_path"), &StreamTexture::get_load_path);
- ADD_PROPERTY( PropertyInfo(Variant::STRING,"load_path",PROPERTY_HINT_FILE,"*.stex"),"load","get_load_path");
+ ADD_PROPERTY(PropertyInfo(Variant::STRING, "load_path", PROPERTY_HINT_FILE, "*.stex"), "load", "get_load_path");
}
-
StreamTexture::StreamTexture() {
- format=Image::FORMAT_MAX;
- flags=0;
- w=0;
- h=0;
+ format = Image::FORMAT_MAX;
+ flags = 0;
+ w = 0;
+ h = 0;
texture = VS::get_singleton()->texture_create();
}
@@ -804,61 +746,53 @@ StreamTexture::~StreamTexture() {
VS::get_singleton()->free(texture);
}
-
-
-RES ResourceFormatLoaderStreamTexture::load(const String &p_path,const String& p_original_path,Error *r_error) {
+RES ResourceFormatLoaderStreamTexture::load(const String &p_path, const String &p_original_path, Error *r_error) {
Ref<StreamTexture> st;
st.instance();
Error err = st->load(p_path);
if (r_error)
- *r_error=err;
- if (err!=OK)
+ *r_error = err;
+ if (err != OK)
return RES();
return st;
}
-void ResourceFormatLoaderStreamTexture::get_recognized_extensions(List<String> *p_extensions) const{
+void ResourceFormatLoaderStreamTexture::get_recognized_extensions(List<String> *p_extensions) const {
p_extensions->push_back("stex");
}
-bool ResourceFormatLoaderStreamTexture::handles_type(const String& p_type) const{
- return p_type=="StreamTexture";
-
+bool ResourceFormatLoaderStreamTexture::handles_type(const String &p_type) const {
+ return p_type == "StreamTexture";
}
-String ResourceFormatLoaderStreamTexture::get_resource_type(const String &p_path) const{
+String ResourceFormatLoaderStreamTexture::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="stex")
+ if (p_path.get_extension().to_lower() == "stex")
return "StreamTexture";
return "";
}
-
-
-
-
//////////////////////////////////////////
-
int AtlasTexture::get_width() const {
- if (region.size.width==0) {
+ if (region.size.width == 0) {
if (atlas.is_valid())
return atlas->get_width();
return 1;
} else {
- return region.size.width+margin.size.width;
+ return region.size.width + margin.size.width;
}
}
int AtlasTexture::get_height() const {
- if (region.size.height==0) {
+ if (region.size.height == 0) {
if (atlas.is_valid())
return atlas->get_height();
return 1;
} else {
- return region.size.height+margin.size.height;
+ return region.size.height + margin.size.height;
}
}
RID AtlasTexture::get_rid() const {
@@ -881,11 +815,9 @@ void AtlasTexture::set_flags(uint32_t p_flags) {
if (atlas.is_valid())
atlas->set_flags(p_flags);
-
}
-
-uint32_t AtlasTexture::get_flags() const{
+uint32_t AtlasTexture::get_flags() const {
if (atlas.is_valid())
return atlas->get_flags();
@@ -893,24 +825,23 @@ uint32_t AtlasTexture::get_flags() const{
return 0;
}
-void AtlasTexture::set_atlas(const Ref<Texture>& p_atlas){
+void AtlasTexture::set_atlas(const Ref<Texture> &p_atlas) {
- if (atlas==p_atlas)
+ if (atlas == p_atlas)
return;
- atlas=p_atlas;
+ atlas = p_atlas;
emit_changed();
emit_signal("atlas_changed");
}
-Ref<Texture> AtlasTexture::get_atlas() const{
+Ref<Texture> AtlasTexture::get_atlas() const {
return atlas;
}
-void AtlasTexture::set_region(const Rect2& p_region) {
+void AtlasTexture::set_region(const Rect2 &p_region) {
- region=p_region;
+ region = p_region;
emit_changed();
-
}
Rect2 AtlasTexture::get_region() const {
@@ -918,11 +849,10 @@ Rect2 AtlasTexture::get_region() const {
return region;
}
-void AtlasTexture::set_margin(const Rect2& p_margin) {
+void AtlasTexture::set_margin(const Rect2 &p_margin) {
- margin=p_margin;
+ margin = p_margin;
emit_changed();
-
}
Rect2 AtlasTexture::get_margin() const {
@@ -932,144 +862,128 @@ Rect2 AtlasTexture::get_margin() const {
void AtlasTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_atlas","atlas:Texture"),&AtlasTexture::set_atlas);
- ClassDB::bind_method(D_METHOD("get_atlas:Texture"),&AtlasTexture::get_atlas);
+ ClassDB::bind_method(D_METHOD("set_atlas", "atlas:Texture"), &AtlasTexture::set_atlas);
+ ClassDB::bind_method(D_METHOD("get_atlas:Texture"), &AtlasTexture::get_atlas);
- ClassDB::bind_method(D_METHOD("set_region","region"),&AtlasTexture::set_region);
- ClassDB::bind_method(D_METHOD("get_region"),&AtlasTexture::get_region);
+ ClassDB::bind_method(D_METHOD("set_region", "region"), &AtlasTexture::set_region);
+ ClassDB::bind_method(D_METHOD("get_region"), &AtlasTexture::get_region);
- ClassDB::bind_method(D_METHOD("set_margin","margin"),&AtlasTexture::set_margin);
- ClassDB::bind_method(D_METHOD("get_margin"),&AtlasTexture::get_margin);
+ ClassDB::bind_method(D_METHOD("set_margin", "margin"), &AtlasTexture::set_margin);
+ ClassDB::bind_method(D_METHOD("get_margin"), &AtlasTexture::get_margin);
ADD_SIGNAL(MethodInfo("atlas_changed"));
- ADD_PROPERTY( PropertyInfo( Variant::OBJECT, "atlas", PROPERTY_HINT_RESOURCE_TYPE,"Texture"), "set_atlas","get_atlas") ;
- ADD_PROPERTY( PropertyInfo( Variant::RECT2, "region"), "set_region","get_region") ;
- ADD_PROPERTY( PropertyInfo( Variant::RECT2, "margin"), "set_margin","get_margin") ;
-
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "atlas", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_atlas", "get_atlas");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region"), "set_region", "get_region");
+ ADD_PROPERTY(PropertyInfo(Variant::RECT2, "margin"), "set_margin", "get_margin");
}
+void AtlasTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const {
-
-
-void AtlasTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const {
-
- Rect2 rc=region;
+ Rect2 rc = region;
if (!atlas.is_valid())
return;
- if (rc.size.width==0) {
- rc.size.width=atlas->get_width();
+ if (rc.size.width == 0) {
+ rc.size.width = atlas->get_width();
}
- if (rc.size.height==0) {
- rc.size.height=atlas->get_height();
+ if (rc.size.height == 0) {
+ rc.size.height = atlas->get_height();
}
- VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,Rect2(p_pos+margin.pos,rc.size),atlas->get_rid(),rc,p_modulate,p_transpose);
+ VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(p_pos + margin.pos, rc.size), atlas->get_rid(), rc, p_modulate, p_transpose);
}
-void AtlasTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const {
+void AtlasTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const {
- Rect2 rc=region;
+ Rect2 rc = region;
if (!atlas.is_valid())
return;
- if (rc.size.width==0) {
- rc.size.width=atlas->get_width();
+ if (rc.size.width == 0) {
+ rc.size.width = atlas->get_width();
}
- if (rc.size.height==0) {
- rc.size.height=atlas->get_height();
+ if (rc.size.height == 0) {
+ rc.size.height = atlas->get_height();
}
- Vector2 scale = p_rect.size / (region.size+margin.size);
- Rect2 dr( p_rect.pos+margin.pos*scale,rc.size*scale );
-
- VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,dr,atlas->get_rid(),rc,p_modulate,p_transpose);
+ Vector2 scale = p_rect.size / (region.size + margin.size);
+ Rect2 dr(p_rect.pos + margin.pos * scale, rc.size * scale);
+ VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), rc, p_modulate, p_transpose);
}
-void AtlasTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const {
+void AtlasTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const {
//this might not necesarily work well if using a rect, needs to be fixed properly
- Rect2 rc=region;
+ Rect2 rc = region;
if (!atlas.is_valid())
return;
- Rect2 src=p_src_rect;
- src.pos+=(rc.pos-margin.pos);
+ Rect2 src = p_src_rect;
+ src.pos += (rc.pos - margin.pos);
Rect2 src_c = rc.clip(src);
- if (src_c.size==Size2())
+ if (src_c.size == Size2())
return;
- Vector2 ofs = (src_c.pos-src.pos);
+ Vector2 ofs = (src_c.pos - src.pos);
Vector2 scale = p_rect.size / p_src_rect.size;
- if(scale.x < 0)
- {
- float mx = (margin.size.width - margin.pos.x);
- mx -= margin.pos.x;
- ofs.x = -(ofs.x + mx);
- }
- if(scale.y < 0)
- {
- float my = margin.size.height - margin.pos.y;
- my -= margin.pos.y;
- ofs.y = -(ofs.y + my);
- }
- Rect2 dr( p_rect.pos+ofs*scale,src_c.size*scale );
+ if (scale.x < 0) {
+ float mx = (margin.size.width - margin.pos.x);
+ mx -= margin.pos.x;
+ ofs.x = -(ofs.x + mx);
+ }
+ if (scale.y < 0) {
+ float my = margin.size.height - margin.pos.y;
+ my -= margin.pos.y;
+ ofs.y = -(ofs.y + my);
+ }
+ Rect2 dr(p_rect.pos + ofs * scale, src_c.size * scale);
- VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item,dr,atlas->get_rid(),src_c,p_modulate,p_transpose);
+ VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), src_c, p_modulate, p_transpose);
}
-bool AtlasTexture::get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const {
+bool AtlasTexture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const {
- Rect2 rc=region;
+ Rect2 rc = region;
if (!atlas.is_valid())
return false;
- Rect2 src=p_src_rect;
- src.pos+=(rc.pos-margin.pos);
+ Rect2 src = p_src_rect;
+ src.pos += (rc.pos - margin.pos);
Rect2 src_c = rc.clip(src);
- if (src_c.size==Size2())
+ if (src_c.size == Size2())
return false;
- Vector2 ofs = (src_c.pos-src.pos);
+ Vector2 ofs = (src_c.pos - src.pos);
Vector2 scale = p_rect.size / p_src_rect.size;
- if(scale.x < 0)
- {
- float mx = (margin.size.width - margin.pos.x);
- mx -= margin.pos.x;
- ofs.x = -(ofs.x + mx);
- }
- if(scale.y < 0)
- {
- float my = margin.size.height - margin.pos.y;
- my -= margin.pos.y;
- ofs.y = -(ofs.y + my);
- }
- Rect2 dr( p_rect.pos+ofs*scale,src_c.size*scale );
-
-
-
- r_rect=dr;
- r_src_rect=src_c;
+ if (scale.x < 0) {
+ float mx = (margin.size.width - margin.pos.x);
+ mx -= margin.pos.x;
+ ofs.x = -(ofs.x + mx);
+ }
+ if (scale.y < 0) {
+ float my = margin.size.height - margin.pos.y;
+ my -= margin.pos.y;
+ ofs.y = -(ofs.y + my);
+ }
+ Rect2 dr(p_rect.pos + ofs * scale, src_c.size * scale);
+
+ r_rect = dr;
+ r_src_rect = src_c;
return true;
}
-
AtlasTexture::AtlasTexture() {
-
-
}
-
//////////////////////////////////////////
-
int LargeTexture::get_width() const {
return size.width;
@@ -1085,7 +999,7 @@ RID LargeTexture::get_rid() const {
bool LargeTexture::has_alpha() const {
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
if (pieces[i].texture->has_alpha())
return true;
}
@@ -1095,14 +1009,12 @@ bool LargeTexture::has_alpha() const {
void LargeTexture::set_flags(uint32_t p_flags) {
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
pieces[i].texture->set_flags(p_flags);
}
-
}
-
-uint32_t LargeTexture::get_flags() const{
+uint32_t LargeTexture::get_flags() const {
if (pieces.size())
return pieces[0].texture->get_flags();
@@ -1110,168 +1022,149 @@ uint32_t LargeTexture::get_flags() const{
return 0;
}
-
-int LargeTexture::add_piece(const Point2& p_offset,const Ref<Texture>& p_texture) {
+int LargeTexture::add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture) {
ERR_FAIL_COND_V(p_texture.is_null(), -1);
Piece p;
- p.offset=p_offset;
- p.texture=p_texture;
+ p.offset = p_offset;
+ p.texture = p_texture;
pieces.push_back(p);
return pieces.size() - 1;
}
-void LargeTexture::set_piece_offset(int p_idx, const Point2& p_offset) {
+void LargeTexture::set_piece_offset(int p_idx, const Point2 &p_offset) {
ERR_FAIL_INDEX(p_idx, pieces.size());
pieces[p_idx].offset = p_offset;
};
-void LargeTexture::set_piece_texture(int p_idx, const Ref<Texture>& p_texture) {
+void LargeTexture::set_piece_texture(int p_idx, const Ref<Texture> &p_texture) {
ERR_FAIL_INDEX(p_idx, pieces.size());
pieces[p_idx].texture = p_texture;
};
+void LargeTexture::set_size(const Size2 &p_size) {
-
-void LargeTexture::set_size(const Size2& p_size){
-
- size=p_size;
+ size = p_size;
}
-void LargeTexture::clear(){
+void LargeTexture::clear() {
pieces.clear();
- size=Size2i();
+ size = Size2i();
}
Array LargeTexture::_get_data() const {
Array arr;
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
arr.push_back(pieces[i].offset);
arr.push_back(pieces[i].texture);
}
arr.push_back(Size2(size));
return arr;
-
}
-void LargeTexture::_set_data(const Array& p_array) {
+void LargeTexture::_set_data(const Array &p_array) {
- ERR_FAIL_COND(p_array.size()<1);
- ERR_FAIL_COND(!(p_array.size()&1));
+ ERR_FAIL_COND(p_array.size() < 1);
+ ERR_FAIL_COND(!(p_array.size() & 1));
clear();
- for(int i=0;i<p_array.size()-1;i+=2) {
- add_piece(p_array[i],p_array[i+1]);
+ for (int i = 0; i < p_array.size() - 1; i += 2) {
+ add_piece(p_array[i], p_array[i + 1]);
}
- size=Size2(p_array[p_array.size()-1]);
+ size = Size2(p_array[p_array.size() - 1]);
}
int LargeTexture::get_piece_count() const {
return pieces.size();
}
-Vector2 LargeTexture::get_piece_offset(int p_idx) const{
+Vector2 LargeTexture::get_piece_offset(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,pieces.size(),Vector2());
+ ERR_FAIL_INDEX_V(p_idx, pieces.size(), Vector2());
return pieces[p_idx].offset;
}
-Ref<Texture> LargeTexture::get_piece_texture(int p_idx) const{
+Ref<Texture> LargeTexture::get_piece_texture(int p_idx) const {
- ERR_FAIL_INDEX_V(p_idx,pieces.size(),Ref<Texture>());
+ ERR_FAIL_INDEX_V(p_idx, pieces.size(), Ref<Texture>());
return pieces[p_idx].texture;
-
}
-
void LargeTexture::_bind_methods() {
- ClassDB::bind_method(D_METHOD("add_piece","ofs","texture:Texture"),&LargeTexture::add_piece);
- ClassDB::bind_method(D_METHOD("set_piece_offset", "idx", "ofs"),&LargeTexture::set_piece_offset);
- ClassDB::bind_method(D_METHOD("set_piece_texture","idx", "texture:Texture"),&LargeTexture::set_piece_texture);
- ClassDB::bind_method(D_METHOD("set_size","size"),&LargeTexture::set_size);
- ClassDB::bind_method(D_METHOD("clear"),&LargeTexture::clear);
+ ClassDB::bind_method(D_METHOD("add_piece", "ofs", "texture:Texture"), &LargeTexture::add_piece);
+ ClassDB::bind_method(D_METHOD("set_piece_offset", "idx", "ofs"), &LargeTexture::set_piece_offset);
+ ClassDB::bind_method(D_METHOD("set_piece_texture", "idx", "texture:Texture"), &LargeTexture::set_piece_texture);
+ ClassDB::bind_method(D_METHOD("set_size", "size"), &LargeTexture::set_size);
+ ClassDB::bind_method(D_METHOD("clear"), &LargeTexture::clear);
- ClassDB::bind_method(D_METHOD("get_piece_count"),&LargeTexture::get_piece_count);
- ClassDB::bind_method(D_METHOD("get_piece_offset","idx"),&LargeTexture::get_piece_offset);
- ClassDB::bind_method(D_METHOD("get_piece_texture:Texture","idx"),&LargeTexture::get_piece_texture);
+ ClassDB::bind_method(D_METHOD("get_piece_count"), &LargeTexture::get_piece_count);
+ ClassDB::bind_method(D_METHOD("get_piece_offset", "idx"), &LargeTexture::get_piece_offset);
+ ClassDB::bind_method(D_METHOD("get_piece_texture:Texture", "idx"), &LargeTexture::get_piece_texture);
- ClassDB::bind_method(D_METHOD("_set_data","data"),&LargeTexture::_set_data);
- ClassDB::bind_method(D_METHOD("_get_data"),&LargeTexture::_get_data);
-
- ADD_PROPERTY( PropertyInfo( Variant::ARRAY, "_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR), "_set_data","_get_data") ;
+ ClassDB::bind_method(D_METHOD("_set_data", "data"), &LargeTexture::_set_data);
+ ClassDB::bind_method(D_METHOD("_get_data"), &LargeTexture::_get_data);
+ ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data");
}
+void LargeTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose) const {
-
-
-void LargeTexture::draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate, bool p_transpose) const {
-
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
// TODO
- pieces[i].texture->draw(p_canvas_item,pieces[i].offset+p_pos,p_modulate,p_transpose);
+ pieces[i].texture->draw(p_canvas_item, pieces[i].offset + p_pos, p_modulate, p_transpose);
}
}
-void LargeTexture::draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile,const Color& p_modulate, bool p_transpose) const {
+void LargeTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose) const {
//tiling not supported for this
- if (size.x==0 || size.y==0)
+ if (size.x == 0 || size.y == 0)
return;
- Size2 scale = p_rect.size/size;
+ Size2 scale = p_rect.size / size;
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
// TODO
- pieces[i].texture->draw_rect(p_canvas_item,Rect2(pieces[i].offset*scale+p_rect.pos,pieces[i].texture->get_size()*scale),false,p_modulate,p_transpose);
+ pieces[i].texture->draw_rect(p_canvas_item, Rect2(pieces[i].offset * scale + p_rect.pos, pieces[i].texture->get_size() * scale), false, p_modulate, p_transpose);
}
}
-void LargeTexture::draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate, bool p_transpose) const {
-
+void LargeTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) const {
//tiling not supported for this
- if (p_src_rect.size.x==0 || p_src_rect.size.y==0)
+ if (p_src_rect.size.x == 0 || p_src_rect.size.y == 0)
return;
- Size2 scale = p_rect.size/p_src_rect.size;
+ Size2 scale = p_rect.size / p_src_rect.size;
- for(int i=0;i<pieces.size();i++) {
+ for (int i = 0; i < pieces.size(); i++) {
// TODO
- Rect2 rect( pieces[i].offset, pieces[i].texture->get_size());
+ Rect2 rect(pieces[i].offset, pieces[i].texture->get_size());
if (!p_src_rect.intersects(rect))
continue;
Rect2 local = p_src_rect.clip(rect);
Rect2 target = local;
- target.size*=scale;
- target.pos=p_rect.pos+(p_src_rect.pos+rect.pos)*scale;
- local.pos-=rect.pos;
- pieces[i].texture->draw_rect_region(p_canvas_item,target,local,p_modulate,p_transpose);
+ target.size *= scale;
+ target.pos = p_rect.pos + (p_src_rect.pos + rect.pos) * scale;
+ local.pos -= rect.pos;
+ pieces[i].texture->draw_rect_region(p_canvas_item, target, local, p_modulate, p_transpose);
}
-
}
-
LargeTexture::LargeTexture() {
-
-
}
-
///////////////////////////////////////////////
-
-
-
void CubeMap::set_flags(uint32_t p_flags) {
- flags=p_flags;
+ flags = p_flags;
if (_is_valid())
- VS::get_singleton()->texture_set_flags(cubemap,flags|VS::TEXTURE_FLAG_CUBEMAP);
+ VS::get_singleton()->texture_set_flags(cubemap, flags | VS::TEXTURE_FLAG_CUBEMAP);
}
uint32_t CubeMap::get_flags() const {
@@ -1279,27 +1172,26 @@ uint32_t CubeMap::get_flags() const {
return flags;
}
-void CubeMap::set_side(Side p_side,const Image& p_image) {
+void CubeMap::set_side(Side p_side, const Image &p_image) {
ERR_FAIL_COND(p_image.empty());
- ERR_FAIL_INDEX(p_side,6);
+ ERR_FAIL_INDEX(p_side, 6);
if (!_is_valid()) {
format = p_image.get_format();
- w=p_image.get_width();
- h=p_image.get_height();
- VS::get_singleton()->texture_allocate(cubemap,w,h,p_image.get_format(),flags|VS::TEXTURE_FLAG_CUBEMAP);
+ w = p_image.get_width();
+ h = p_image.get_height();
+ VS::get_singleton()->texture_allocate(cubemap, w, h, p_image.get_format(), flags | VS::TEXTURE_FLAG_CUBEMAP);
}
- VS::get_singleton()->texture_set_data(cubemap,p_image,VS::CubeMapSide(p_side));
- valid[p_side]=true;
+ VS::get_singleton()->texture_set_data(cubemap, p_image, VS::CubeMapSide(p_side));
+ valid[p_side] = true;
}
Image CubeMap::get_side(Side p_side) const {
if (!valid[p_side])
return Image();
- return VS::get_singleton()->texture_get_data(cubemap,VS::CubeMapSide(p_side));
-
+ return VS::get_singleton()->texture_get_data(cubemap, VS::CubeMapSide(p_side));
}
Image::Format CubeMap::get_format() const {
@@ -1320,10 +1212,9 @@ RID CubeMap::get_rid() const {
return cubemap;
}
-
void CubeMap::set_storage(Storage p_storage) {
- storage=p_storage;
+ storage = p_storage;
}
CubeMap::Storage CubeMap::get_storage() const {
@@ -1333,7 +1224,7 @@ CubeMap::Storage CubeMap::get_storage() const {
void CubeMap::set_lossy_storage_quality(float p_lossy_storage_quality) {
- lossy_storage_quality=p_lossy_storage_quality;
+ lossy_storage_quality = p_lossy_storage_quality;
}
float CubeMap::get_lossy_storage_quality() const {
@@ -1341,149 +1232,133 @@ float CubeMap::get_lossy_storage_quality() const {
return lossy_storage_quality;
}
-void CubeMap::set_path(const String& p_path,bool p_take_over) {
+void CubeMap::set_path(const String &p_path, bool p_take_over) {
if (cubemap.is_valid()) {
- VisualServer::get_singleton()->texture_set_path(cubemap,p_path);
+ VisualServer::get_singleton()->texture_set_path(cubemap, p_path);
}
- Resource::set_path(p_path,p_take_over);
+ Resource::set_path(p_path, p_take_over);
}
+bool CubeMap::_set(const StringName &p_name, const Variant &p_value) {
-bool CubeMap::_set(const StringName& p_name, const Variant& p_value) {
-
- if (p_name=="side/left") {
- set_side(SIDE_LEFT,p_value);
- } else if (p_name=="side/right") {
- set_side(SIDE_RIGHT,p_value);
- } else if (p_name=="side/bottom") {
- set_side(SIDE_BOTTOM,p_value);
- } else if (p_name=="side/top") {
- set_side(SIDE_TOP,p_value);
- } else if (p_name=="side/front") {
- set_side(SIDE_FRONT,p_value);
- } else if (p_name=="side/back") {
- set_side(SIDE_BACK,p_value);
- } else if (p_name=="flags") {
+ if (p_name == "side/left") {
+ set_side(SIDE_LEFT, p_value);
+ } else if (p_name == "side/right") {
+ set_side(SIDE_RIGHT, p_value);
+ } else if (p_name == "side/bottom") {
+ set_side(SIDE_BOTTOM, p_value);
+ } else if (p_name == "side/top") {
+ set_side(SIDE_TOP, p_value);
+ } else if (p_name == "side/front") {
+ set_side(SIDE_FRONT, p_value);
+ } else if (p_name == "side/back") {
+ set_side(SIDE_BACK, p_value);
+ } else if (p_name == "flags") {
set_flags(p_value);
- } else if (p_name=="storage") {
- storage=Storage(p_value.operator int());
- } else if (p_name=="lossy_quality") {
- lossy_storage_quality=p_value;
+ } else if (p_name == "storage") {
+ storage = Storage(p_value.operator int());
+ } else if (p_name == "lossy_quality") {
+ lossy_storage_quality = p_value;
} else
return false;
return true;
-
}
-bool CubeMap::_get(const StringName& p_name,Variant &r_ret) const {
-
- if (p_name=="side/left") {
- r_ret=get_side(SIDE_LEFT);
- } else if (p_name=="side/right") {
- r_ret=get_side(SIDE_RIGHT);
- } else if (p_name=="side/bottom") {
- r_ret=get_side(SIDE_BOTTOM);
- } else if (p_name=="side/top") {
- r_ret=get_side(SIDE_TOP);
- } else if (p_name=="side/front") {
- r_ret=get_side(SIDE_FRONT);
- } else if (p_name=="side/back") {
- r_ret=get_side(SIDE_BACK);
- } else if (p_name=="flags") {
- r_ret= flags;
- } else if (p_name=="storage") {
- r_ret= storage;
- } else if (p_name=="lossy_quality") {
- r_ret= lossy_storage_quality;
+bool CubeMap::_get(const StringName &p_name, Variant &r_ret) const {
+
+ if (p_name == "side/left") {
+ r_ret = get_side(SIDE_LEFT);
+ } else if (p_name == "side/right") {
+ r_ret = get_side(SIDE_RIGHT);
+ } else if (p_name == "side/bottom") {
+ r_ret = get_side(SIDE_BOTTOM);
+ } else if (p_name == "side/top") {
+ r_ret = get_side(SIDE_TOP);
+ } else if (p_name == "side/front") {
+ r_ret = get_side(SIDE_FRONT);
+ } else if (p_name == "side/back") {
+ r_ret = get_side(SIDE_BACK);
+ } else if (p_name == "flags") {
+ r_ret = flags;
+ } else if (p_name == "storage") {
+ r_ret = storage;
+ } else if (p_name == "lossy_quality") {
+ r_ret = lossy_storage_quality;
} else
return false;
return true;
}
+void CubeMap::_get_property_list(List<PropertyInfo> *p_list) const {
-
-
-void CubeMap::_get_property_list( List<PropertyInfo> *p_list) const {
-
-
- PropertyHint img_hint=PROPERTY_HINT_NONE;
- if (storage==STORAGE_COMPRESS_LOSSY) {
- img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSY;
- } else if (storage==STORAGE_COMPRESS_LOSSLESS) {
- img_hint=PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS;
+ PropertyHint img_hint = PROPERTY_HINT_NONE;
+ if (storage == STORAGE_COMPRESS_LOSSY) {
+ img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSY;
+ } else if (storage == STORAGE_COMPRESS_LOSSLESS) {
+ img_hint = PROPERTY_HINT_IMAGE_COMPRESS_LOSSLESS;
}
-
- p_list->push_back( PropertyInfo( Variant::INT, "flags", PROPERTY_HINT_FLAGS,"Mipmaps,Repeat,Filter" ) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/left", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/right", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/bottom", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/top", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/front", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::IMAGE, "side/back", img_hint,String::num(lossy_storage_quality)) );
- p_list->push_back( PropertyInfo( Variant::INT, "storage", PROPERTY_HINT_ENUM,"Uncompressed,Compress Lossy,Compress Lossless",PROPERTY_USAGE_EDITOR));
- p_list->push_back( PropertyInfo( Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE,"0.0,1.0,0.01" ) );
+ p_list->push_back(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter"));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/left", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/right", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/bottom", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/top", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/front", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::IMAGE, "side/back", img_hint, String::num(lossy_storage_quality)));
+ p_list->push_back(PropertyInfo(Variant::INT, "storage", PROPERTY_HINT_ENUM, "Uncompressed,Compress Lossy,Compress Lossless", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"));
}
void CubeMap::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_width"),&CubeMap::get_width);
- ClassDB::bind_method(D_METHOD("get_height"),&CubeMap::get_height);
+ ClassDB::bind_method(D_METHOD("get_width"), &CubeMap::get_width);
+ ClassDB::bind_method(D_METHOD("get_height"), &CubeMap::get_height);
//ClassDB::bind_method(D_METHOD("get_rid"),&CubeMap::get_rid);
- ClassDB::bind_method(D_METHOD("set_flags","flags"),&CubeMap::set_flags);
- ClassDB::bind_method(D_METHOD("get_flags"),&CubeMap::get_flags);
-
- ClassDB::bind_method(D_METHOD("set_side","side","image"),&CubeMap::set_side);
- ClassDB::bind_method(D_METHOD("get_side","side"),&CubeMap::get_side);
- ClassDB::bind_method(D_METHOD("set_storage","mode"),&CubeMap::set_storage);
- ClassDB::bind_method(D_METHOD("get_storage"),&CubeMap::get_storage);
- ClassDB::bind_method(D_METHOD("set_lossy_storage_quality","quality"),&CubeMap::set_lossy_storage_quality);
- ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"),&CubeMap::get_lossy_storage_quality);
-
-
- BIND_CONSTANT( STORAGE_RAW );
- BIND_CONSTANT( STORAGE_COMPRESS_LOSSY );
- BIND_CONSTANT( STORAGE_COMPRESS_LOSSLESS );
- BIND_CONSTANT( SIDE_LEFT );
- BIND_CONSTANT( SIDE_RIGHT );
- BIND_CONSTANT( SIDE_BOTTOM );
- BIND_CONSTANT( SIDE_TOP );
- BIND_CONSTANT( SIDE_FRONT );
- BIND_CONSTANT( SIDE_BACK );
- BIND_CONSTANT( FLAG_MIPMAPS );
- BIND_CONSTANT( FLAG_REPEAT );
- BIND_CONSTANT( FLAG_FILTER );
- BIND_CONSTANT( FLAGS_DEFAULT );
-
-
+ ClassDB::bind_method(D_METHOD("set_flags", "flags"), &CubeMap::set_flags);
+ ClassDB::bind_method(D_METHOD("get_flags"), &CubeMap::get_flags);
+
+ ClassDB::bind_method(D_METHOD("set_side", "side", "image"), &CubeMap::set_side);
+ ClassDB::bind_method(D_METHOD("get_side", "side"), &CubeMap::get_side);
+ ClassDB::bind_method(D_METHOD("set_storage", "mode"), &CubeMap::set_storage);
+ ClassDB::bind_method(D_METHOD("get_storage"), &CubeMap::get_storage);
+ ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &CubeMap::set_lossy_storage_quality);
+ ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &CubeMap::get_lossy_storage_quality);
+
+ BIND_CONSTANT(STORAGE_RAW);
+ BIND_CONSTANT(STORAGE_COMPRESS_LOSSY);
+ BIND_CONSTANT(STORAGE_COMPRESS_LOSSLESS);
+ BIND_CONSTANT(SIDE_LEFT);
+ BIND_CONSTANT(SIDE_RIGHT);
+ BIND_CONSTANT(SIDE_BOTTOM);
+ BIND_CONSTANT(SIDE_TOP);
+ BIND_CONSTANT(SIDE_FRONT);
+ BIND_CONSTANT(SIDE_BACK);
+ BIND_CONSTANT(FLAG_MIPMAPS);
+ BIND_CONSTANT(FLAG_REPEAT);
+ BIND_CONSTANT(FLAG_FILTER);
+ BIND_CONSTANT(FLAGS_DEFAULT);
}
CubeMap::CubeMap() {
- w=h=0;
- flags=FLAGS_DEFAULT;
- for(int i=0;i<6;i++)
- valid[i]=false;
+ w = h = 0;
+ flags = FLAGS_DEFAULT;
+ for (int i = 0; i < 6; i++)
+ valid[i] = false;
cubemap = VisualServer::get_singleton()->texture_create();
storage = STORAGE_RAW;
- lossy_storage_quality=0.7;
-
-
+ lossy_storage_quality = 0.7;
}
-
CubeMap::~CubeMap() {
- VisualServer::get_singleton()->free( cubemap );
+ VisualServer::get_singleton()->free(cubemap);
}
-
-
-
/* BIND_CONSTANT( FLAG_CUBEMAP );
BIND_CONSTANT( CUBEMAP_LEFT );
BIND_CONSTANT( CUBEMAP_RIGHT );
diff --git a/scene/resources/texture.h b/scene/resources/texture.h
index cae77ad5cf..0092fee836 100644
--- a/scene/resources/texture.h
+++ b/scene/resources/texture.h
@@ -29,76 +29,73 @@
#ifndef TEXTURE_H
#define TEXTURE_H
-#include "resource.h"
-#include "servers/visual_server.h"
#include "io/resource_loader.h"
#include "math_2d.h"
+#include "resource.h"
+#include "servers/visual_server.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
class Texture : public Resource {
- GDCLASS( Texture, Resource );
- OBJ_SAVE_TYPE( Texture ); //children are all saved as Texture, so they can be exchanged
+ GDCLASS(Texture, Resource);
+ OBJ_SAVE_TYPE(Texture); //children are all saved as Texture, so they can be exchanged
protected:
-
static void _bind_methods();
-public:
+public:
enum Flags {
- FLAG_MIPMAPS=VisualServer::TEXTURE_FLAG_MIPMAPS,
- FLAG_REPEAT=VisualServer::TEXTURE_FLAG_REPEAT,
- FLAG_FILTER=VisualServer::TEXTURE_FLAG_FILTER,
- FLAG_ANISOTROPIC_FILTER=VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER,
- FLAG_CONVERT_TO_LINEAR=VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR,
- FLAG_VIDEO_SURFACE=VisualServer::TEXTURE_FLAG_USED_FOR_STREAMING,
- FLAGS_DEFAULT=FLAG_MIPMAPS|FLAG_REPEAT|FLAG_FILTER,
- FLAG_MIRRORED_REPEAT=VisualServer::TEXTURE_FLAG_MIRRORED_REPEAT
+ FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS,
+ FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT,
+ FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER,
+ FLAG_ANISOTROPIC_FILTER = VisualServer::TEXTURE_FLAG_ANISOTROPIC_FILTER,
+ FLAG_CONVERT_TO_LINEAR = VisualServer::TEXTURE_FLAG_CONVERT_TO_LINEAR,
+ FLAG_VIDEO_SURFACE = VisualServer::TEXTURE_FLAG_USED_FOR_STREAMING,
+ FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER,
+ FLAG_MIRRORED_REPEAT = VisualServer::TEXTURE_FLAG_MIRRORED_REPEAT
};
-
- virtual int get_width() const=0;
- virtual int get_height() const=0;
+ virtual int get_width() const = 0;
+ virtual int get_height() const = 0;
virtual Size2 get_size() const;
- virtual RID get_rid() const=0;
+ virtual RID get_rid() const = 0;
- virtual bool has_alpha() const=0;
+ virtual bool has_alpha() const = 0;
- virtual void set_flags(uint32_t p_flags)=0;
- virtual uint32_t get_flags() const=0;
+ virtual void set_flags(uint32_t p_flags) = 0;
+ virtual uint32_t get_flags() const = 0;
- virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual bool get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const;
+ virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const;
virtual Image get_data() const { return Image(); }
Texture();
};
-VARIANT_ENUM_CAST( Texture::Flags );
-
+VARIANT_ENUM_CAST(Texture::Flags);
class ImageTexture : public Texture {
- GDCLASS( ImageTexture, Texture );
+ GDCLASS(ImageTexture, Texture);
RES_BASE_EXTENSION("tex");
+
public:
enum Storage {
STORAGE_RAW,
STORAGE_COMPRESS_LOSSY,
STORAGE_COMPRESS_LOSSLESS
};
+
private:
RID texture;
Image::Format format;
uint32_t flags;
- int w,h;
+ int w, h;
Storage storage;
Size2 size_override;
float lossy_storage_quality;
@@ -106,28 +103,25 @@ private:
protected:
virtual void reload_from_file();
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
- void _reload_hook(const RID& p_hook);
+ void _reload_hook(const RID &p_hook);
virtual void _resource_path_changed();
static void _bind_methods();
void _set_data(Dictionary p_data);
public:
-
-
- void create(int p_width, int p_height,Image::Format p_format,uint32_t p_flags=FLAGS_DEFAULT);
- void create_from_image(const Image& p_image, uint32_t p_flags=FLAGS_DEFAULT);
-
+ void create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags = FLAGS_DEFAULT);
+ void create_from_image(const Image &p_image, uint32_t p_flags = FLAGS_DEFAULT);
void set_flags(uint32_t p_flags);
uint32_t get_flags() const;
Image::Format get_format() const;
- void load(const String& p_path);
- void set_data(const Image& p_image);
+ void load(const String &p_path);
+ void set_data(const Image &p_image);
Image get_data() const;
int get_width() const;
@@ -136,9 +130,9 @@ public:
virtual RID get_rid() const;
bool has_alpha() const;
- virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
+ virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
void set_storage(Storage p_storage);
Storage get_storage() const;
@@ -150,21 +144,18 @@ public:
void normal_to_xy();
void shrink_x2_and_keep_size();
+ void set_size_override(const Size2 &p_size);
- void set_size_override(const Size2& p_size);
-
- virtual void set_path(const String& p_path,bool p_take_over=false);
+ virtual void set_path(const String &p_path, bool p_take_over = false);
ImageTexture();
~ImageTexture();
-
};
-
-
class StreamTexture : public Texture {
- GDCLASS( StreamTexture, Texture );
+ GDCLASS(StreamTexture, Texture);
+
public:
enum DataFormat {
DATA_FORMAT_IMAGE,
@@ -173,53 +164,49 @@ public:
};
enum FormatBits {
- FORMAT_MASK_IMAGE_FORMAT=(1<<20)-1,
- FORMAT_BIT_LOSSLESS=1<<20,
- FORMAT_BIT_LOSSY=1<<21,
- FORMAT_BIT_STREAM=1<<22,
- FORMAT_BIT_HAS_MIPMAPS=1<<23,
- FORMAT_BIT_DETECT_3D=1<<24,
- FORMAT_BIT_DETECT_SRGB=1<<25,
+ FORMAT_MASK_IMAGE_FORMAT = (1 << 20) - 1,
+ FORMAT_BIT_LOSSLESS = 1 << 20,
+ FORMAT_BIT_LOSSY = 1 << 21,
+ FORMAT_BIT_STREAM = 1 << 22,
+ FORMAT_BIT_HAS_MIPMAPS = 1 << 23,
+ FORMAT_BIT_DETECT_3D = 1 << 24,
+ FORMAT_BIT_DETECT_SRGB = 1 << 25,
};
private:
-
- Error _load_data(const String &p_path, int &tw, int &th, int& flags, Image& image, int p_size_limit=0);
+ Error _load_data(const String &p_path, int &tw, int &th, int &flags, Image &image, int p_size_limit = 0);
String path_to_file;
RID texture;
Image::Format format;
uint32_t flags;
- int w,h;
+ int w, h;
virtual void reload_from_file();
- static void _requested_3d(void* p_ud);
- static void _requested_srgb(void* p_ud);
+ static void _requested_3d(void *p_ud);
+ static void _requested_srgb(void *p_ud);
protected:
-
static void _bind_methods();
public:
-
-
- typedef void (*TextureFormatRequestCallback)(const Ref<StreamTexture>&);
+ typedef void (*TextureFormatRequestCallback)(const Ref<StreamTexture> &);
static TextureFormatRequestCallback request_3d_callback;
static TextureFormatRequestCallback request_srgb_callback;
uint32_t get_flags() const;
Image::Format get_format() const;
- Error load(const String& p_path);
+ Error load(const String &p_path);
String get_load_path() const;
int get_width() const;
int get_height() const;
virtual RID get_rid() const;
- virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
+ virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
virtual bool has_alpha() const;
virtual void set_flags(uint32_t p_flags);
@@ -228,37 +215,31 @@ public:
StreamTexture();
~StreamTexture();
-
};
-
class ResourceFormatLoaderStreamTexture : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
-
-
-VARIANT_ENUM_CAST( ImageTexture::Storage );
+VARIANT_ENUM_CAST(ImageTexture::Storage);
class AtlasTexture : public Texture {
- GDCLASS( AtlasTexture, Texture );
+ GDCLASS(AtlasTexture, Texture);
RES_BASE_EXTENSION("atex");
-protected:
-
+protected:
Ref<Texture> atlas;
Rect2 region;
Rect2 margin;
static void _bind_methods();
-public:
+public:
virtual int get_width() const;
virtual int get_height() const;
virtual RID get_rid() const;
@@ -268,30 +249,29 @@ public:
virtual void set_flags(uint32_t p_flags);
virtual uint32_t get_flags() const;
- void set_atlas(const Ref<Texture>& p_atlas);
+ void set_atlas(const Ref<Texture> &p_atlas);
Ref<Texture> get_atlas() const;
- void set_region(const Rect2& p_region);
- Rect2 get_region() const ;
-
- void set_margin(const Rect2& p_margin);
- Rect2 get_margin() const ;
+ void set_region(const Rect2 &p_region);
+ Rect2 get_region() const;
- virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual bool get_rect_region(const Rect2& p_rect, const Rect2& p_src_rect,Rect2& r_rect,Rect2& r_src_rect) const;
+ void set_margin(const Rect2 &p_margin);
+ Rect2 get_margin() const;
+ virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual bool get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const;
AtlasTexture();
};
class LargeTexture : public Texture {
- GDCLASS( LargeTexture, Texture );
+ GDCLASS(LargeTexture, Texture);
RES_BASE_EXTENSION("ltex");
-protected:
+protected:
struct Piece {
Point2 offset;
@@ -301,12 +281,11 @@ protected:
Vector<Piece> pieces;
Size2i size;
-
Array _get_data() const;
- void _set_data(const Array& p_array);
+ void _set_data(const Array &p_array);
static void _bind_methods();
-public:
+public:
virtual int get_width() const;
virtual int get_height() const;
virtual RID get_rid() const;
@@ -316,31 +295,29 @@ public:
virtual void set_flags(uint32_t p_flags);
virtual uint32_t get_flags() const;
- int add_piece(const Point2& p_offset,const Ref<Texture>& p_texture);
- void set_piece_offset(int p_idx, const Point2& p_offset);
- void set_piece_texture(int p_idx, const Ref<Texture>& p_texture);
+ int add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture);
+ void set_piece_offset(int p_idx, const Point2 &p_offset);
+ void set_piece_texture(int p_idx, const Ref<Texture> &p_texture);
- void set_size(const Size2& p_size);
+ void set_size(const Size2 &p_size);
void clear();
int get_piece_count() const;
Vector2 get_piece_offset(int p_idx) const;
Ref<Texture> get_piece_texture(int p_idx) const;
- virtual void draw(RID p_canvas_item, const Point2& p_pos, const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect(RID p_canvas_item,const Rect2& p_rect, bool p_tile=false,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
- virtual void draw_rect_region(RID p_canvas_item,const Rect2& p_rect, const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1), bool p_transpose=false) const;
-
+ virtual void draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
+ virtual void draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) const;
LargeTexture();
};
-
-
class CubeMap : public Resource {
- GDCLASS( CubeMap, Resource );
+ GDCLASS(CubeMap, Resource);
RES_BASE_EXTENSION("cbm");
+
public:
enum Storage {
STORAGE_RAW,
@@ -359,37 +336,40 @@ public:
};
enum Flags {
- FLAG_MIPMAPS=VisualServer::TEXTURE_FLAG_MIPMAPS,
- FLAG_REPEAT=VisualServer::TEXTURE_FLAG_REPEAT,
- FLAG_FILTER=VisualServer::TEXTURE_FLAG_FILTER,
- FLAGS_DEFAULT=FLAG_MIPMAPS|FLAG_REPEAT|FLAG_FILTER,
+ FLAG_MIPMAPS = VisualServer::TEXTURE_FLAG_MIPMAPS,
+ FLAG_REPEAT = VisualServer::TEXTURE_FLAG_REPEAT,
+ FLAG_FILTER = VisualServer::TEXTURE_FLAG_FILTER,
+ FLAGS_DEFAULT = FLAG_MIPMAPS | FLAG_REPEAT | FLAG_FILTER,
};
private:
-
bool valid[6];
RID cubemap;
Image::Format format;
uint32_t flags;
- int w,h;
+ int w, h;
Storage storage;
Size2 size_override;
float lossy_storage_quality;
- _FORCE_INLINE_ bool _is_valid() const { for(int i=0;i<6;i++) { if (valid[i]) return true; } return false; }
+ _FORCE_INLINE_ bool _is_valid() const {
+ for (int i = 0; i < 6; i++) {
+ if (valid[i]) return true;
+ }
+ return false;
+ }
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
-public:
+public:
void set_flags(uint32_t p_flags);
uint32_t get_flags() const;
- void set_side(Side p_side,const Image& p_image);
+ void set_side(Side p_side, const Image &p_image);
Image get_side(Side p_side) const;
Image::Format get_format() const;
@@ -404,17 +384,15 @@ public:
void set_lossy_storage_quality(float p_lossy_storage_quality);
float get_lossy_storage_quality() const;
- virtual void set_path(const String& p_path,bool p_take_over=false);
+ virtual void set_path(const String &p_path, bool p_take_over = false);
CubeMap();
~CubeMap();
-
};
-VARIANT_ENUM_CAST( CubeMap::Flags );
-VARIANT_ENUM_CAST( CubeMap::Side );
-VARIANT_ENUM_CAST( CubeMap::Storage );
-
+VARIANT_ENUM_CAST(CubeMap::Flags);
+VARIANT_ENUM_CAST(CubeMap::Side);
+VARIANT_ENUM_CAST(CubeMap::Storage);
/*
enum CubeMapSide {
@@ -430,5 +408,4 @@ VARIANT_ENUM_CAST( CubeMap::Storage );
*/
//VARIANT_ENUM_CAST( Texture::CubeMapSide );
-
#endif
diff --git a/scene/resources/theme.cpp b/scene/resources/theme.cpp
index 10ad38d498..c1ef3e8c1f 100644
--- a/scene/resources/theme.cpp
+++ b/scene/resources/theme.cpp
@@ -27,64 +27,61 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "theme.h"
-#include "print_string.h"
#include "os/file_access.h"
-
+#include "print_string.h"
Ref<Theme> Theme::default_theme;
-
void Theme::_emit_theme_changed() {
emit_changed();
}
-void Theme::_ref_font( Ref<Font> p_sc) {
+void Theme::_ref_font(Ref<Font> p_sc) {
if (!font_refcount.has(p_sc)) {
- font_refcount[p_sc]=1;
- p_sc->connect("changed",this,"_emit_theme_changed");
+ font_refcount[p_sc] = 1;
+ p_sc->connect("changed", this, "_emit_theme_changed");
} else {
- font_refcount[p_sc]+=1;
+ font_refcount[p_sc] += 1;
}
}
-void Theme::_unref_font(Ref<Font> p_sc) {
+void Theme::_unref_font(Ref<Font> p_sc) {
ERR_FAIL_COND(!font_refcount.has(p_sc));
font_refcount[p_sc]--;
- if (font_refcount[p_sc]==0) {
- p_sc->disconnect("changed",this,"_emit_theme_changed");
+ if (font_refcount[p_sc] == 0) {
+ p_sc->disconnect("changed", this, "_emit_theme_changed");
font_refcount.erase(p_sc);
}
}
+bool Theme::_set(const StringName &p_name, const Variant &p_value) {
-bool Theme::_set(const StringName& p_name, const Variant& p_value) {
-
- String sname=p_name;
+ String sname = p_name;
- if (sname.find("/")!=-1) {
+ if (sname.find("/") != -1) {
- String type=sname.get_slicec('/',1);
- String node_type=sname.get_slicec('/',0);
- String name=sname.get_slicec('/',2);
+ String type = sname.get_slicec('/', 1);
+ String node_type = sname.get_slicec('/', 0);
+ String name = sname.get_slicec('/', 2);
- if (type=="icons") {
+ if (type == "icons") {
- set_icon(name,node_type,p_value);
- } else if (type=="styles") {
+ set_icon(name, node_type, p_value);
+ } else if (type == "styles") {
- set_stylebox(name,node_type,p_value);
- } else if (type=="fonts") {
+ set_stylebox(name, node_type, p_value);
+ } else if (type == "fonts") {
- set_font(name,node_type,p_value);
- } else if (type=="colors") {
+ set_font(name, node_type, p_value);
+ } else if (type == "colors") {
- set_color(name,node_type,p_value);
- } else if (type=="constants") {
+ set_color(name, node_type, p_value);
+ } else if (type == "constants") {
- set_constant(name,node_type,p_value);
+ set_constant(name, node_type, p_value);
} else
return false;
@@ -92,43 +89,42 @@ bool Theme::_set(const StringName& p_name, const Variant& p_value) {
}
return false;
-
}
-bool Theme::_get(const StringName& p_name,Variant &r_ret) const {
+bool Theme::_get(const StringName &p_name, Variant &r_ret) const {
- String sname=p_name;
+ String sname = p_name;
- if (sname.find("/")!=-1) {
+ if (sname.find("/") != -1) {
- String type=sname.get_slicec('/',1);
- String node_type=sname.get_slicec('/',0);
- String name=sname.get_slicec('/',2);
+ String type = sname.get_slicec('/', 1);
+ String node_type = sname.get_slicec('/', 0);
+ String name = sname.get_slicec('/', 2);
- if (type=="icons") {
+ if (type == "icons") {
- if (!has_icon(name,node_type))
- r_ret=Ref<Texture>();
+ if (!has_icon(name, node_type))
+ r_ret = Ref<Texture>();
else
- r_ret= get_icon(name,node_type);
- } else if (type=="styles") {
+ r_ret = get_icon(name, node_type);
+ } else if (type == "styles") {
- if (!has_stylebox(name,node_type))
- r_ret=Ref<StyleBox>();
+ if (!has_stylebox(name, node_type))
+ r_ret = Ref<StyleBox>();
else
- r_ret= get_stylebox(name,node_type);
- } else if (type=="fonts") {
+ r_ret = get_stylebox(name, node_type);
+ } else if (type == "fonts") {
- if (!has_font(name,node_type))
- r_ret=Ref<Font>();
+ if (!has_font(name, node_type))
+ r_ret = Ref<Font>();
else
- r_ret= get_font(name,node_type);
- } else if (type=="colors") {
+ r_ret = get_font(name, node_type);
+ } else if (type == "colors") {
- r_ret= get_color(name,node_type);
- } else if (type=="constants") {
+ r_ret = get_color(name, node_type);
+ } else if (type == "constants") {
- r_ret= get_constant(name,node_type);
+ r_ret = get_constant(name, node_type);
} else
return false;
@@ -138,77 +134,74 @@ bool Theme::_get(const StringName& p_name,Variant &r_ret) const {
return false;
}
-void Theme::_get_property_list( List<PropertyInfo> *p_list) const {
-
+void Theme::_get_property_list(List<PropertyInfo> *p_list) const {
List<PropertyInfo> list;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=icon_map.next(key))) {
+ while ((key = icon_map.next(key))) {
- const StringName *key2=NULL;
+ const StringName *key2 = NULL;
- while((key2=icon_map[*key].next(key2))) {
+ while ((key2 = icon_map[*key].next(key2))) {
- list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/icons/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "Texture",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) );
+ list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/icons/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "Texture", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL));
}
}
- key=NULL;
+ key = NULL;
- while((key=style_map.next(key))) {
+ while ((key = style_map.next(key))) {
- const StringName *key2=NULL;
+ const StringName *key2 = NULL;
- while((key2=style_map[*key].next(key2))) {
+ while ((key2 = style_map[*key].next(key2))) {
- list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/styles/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) );
+ list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/styles/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "StyleBox", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL));
}
}
- key=NULL;
+ key = NULL;
+ while ((key = font_map.next(key))) {
- while((key=font_map.next(key))) {
+ const StringName *key2 = NULL;
- const StringName *key2=NULL;
+ while ((key2 = font_map[*key].next(key2))) {
- while((key2=font_map[*key].next(key2))) {
-
- list.push_back( PropertyInfo( Variant::OBJECT, String()+*key+"/fonts/"+*key2, PROPERTY_HINT_RESOURCE_TYPE, "Font",PROPERTY_USAGE_DEFAULT|PROPERTY_USAGE_STORE_IF_NULL ) );
+ list.push_back(PropertyInfo(Variant::OBJECT, String() + *key + "/fonts/" + *key2, PROPERTY_HINT_RESOURCE_TYPE, "Font", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_STORE_IF_NULL));
}
}
- key=NULL;
+ key = NULL;
- while((key=color_map.next(key))) {
+ while ((key = color_map.next(key))) {
- const StringName *key2=NULL;
+ const StringName *key2 = NULL;
- while((key2=color_map[*key].next(key2))) {
+ while ((key2 = color_map[*key].next(key2))) {
- list.push_back( PropertyInfo( Variant::COLOR, String()+*key+"/colors/"+*key2 ) );
+ list.push_back(PropertyInfo(Variant::COLOR, String() + *key + "/colors/" + *key2));
}
}
- key=NULL;
+ key = NULL;
- while((key=constant_map.next(key))) {
+ while ((key = constant_map.next(key))) {
- const StringName *key2=NULL;
+ const StringName *key2 = NULL;
- while((key2=constant_map[*key].next(key2))) {
+ while ((key2 = constant_map[*key].next(key2))) {
- list.push_back( PropertyInfo( Variant::INT, String()+*key+"/constants/"+*key2 ) );
+ list.push_back(PropertyInfo(Variant::INT, String() + *key + "/constants/" + *key2));
}
}
list.sort();
- for(List<PropertyInfo>::Element *E=list.front();E;E=E->next()) {
+ for (List<PropertyInfo>::Element *E = list.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
-
}
Ref<Theme> Theme::get_default() {
@@ -216,17 +209,16 @@ Ref<Theme> Theme::get_default() {
return default_theme;
}
+void Theme::set_default_theme_font(const Ref<Font> &p_default_font) {
-void Theme::set_default_theme_font( const Ref<Font>& p_default_font ) {
-
- if (default_theme_font==p_default_font)
+ if (default_theme_font == p_default_font)
return;
if (default_theme_font.is_valid()) {
_unref_font(default_theme_font);
}
- default_theme_font=p_default_font;
+ default_theme_font = p_default_font;
if (default_theme_font.is_valid()) {
_ref_font(default_theme_font);
@@ -234,7 +226,6 @@ void Theme::set_default_theme_font( const Ref<Font>& p_default_font ) {
_change_notify();
emit_changed();
-
}
Ref<Font> Theme::get_default_theme_font() const {
@@ -242,43 +233,42 @@ Ref<Font> Theme::get_default_theme_font() const {
return default_theme_font;
}
-void Theme::set_default(const Ref<Theme>& p_default) {
+void Theme::set_default(const Ref<Theme> &p_default) {
- default_theme=p_default;
+ default_theme = p_default;
}
Ref<Texture> Theme::default_icon;
Ref<StyleBox> Theme::default_style;
Ref<Font> Theme::default_font;
+void Theme::set_default_icon(const Ref<Texture> &p_icon) {
-void Theme::set_default_icon( const Ref<Texture>& p_icon ) {
-
- default_icon=p_icon;
+ default_icon = p_icon;
}
-void Theme::set_default_style( const Ref<StyleBox>& p_style) {
+void Theme::set_default_style(const Ref<StyleBox> &p_style) {
- default_style=p_style;
+ default_style = p_style;
}
-void Theme::set_default_font( const Ref<Font>& p_font ) {
+void Theme::set_default_font(const Ref<Font> &p_font) {
- default_font=p_font;
+ default_font = p_font;
}
-void Theme::set_icon(const StringName& p_name,const StringName& p_type,const Ref<Texture>& p_icon) {
+void Theme::set_icon(const StringName &p_name, const StringName &p_type, const Ref<Texture> &p_icon) {
//ERR_FAIL_COND(p_icon.is_null());
- bool new_value=!icon_map.has(p_type) || !icon_map[p_type].has(p_name);
+ bool new_value = !icon_map.has(p_type) || !icon_map[p_type].has(p_name);
- icon_map[p_type][p_name]=p_icon;
+ icon_map[p_type][p_name] = p_icon;
if (new_value) {
_change_notify();
emit_changed();
}
}
-Ref<Texture> Theme::get_icon(const StringName& p_name,const StringName& p_type) const {
+Ref<Texture> Theme::get_icon(const StringName &p_name, const StringName &p_type) const {
if (icon_map.has(p_type) && icon_map[p_type].has(p_name) && icon_map[p_type][p_name].is_valid()) {
@@ -288,13 +278,12 @@ Ref<Texture> Theme::get_icon(const StringName& p_name,const StringName& p_type)
}
}
-bool Theme::has_icon(const StringName& p_name,const StringName& p_type) const {
+bool Theme::has_icon(const StringName &p_name, const StringName &p_type) const {
return (icon_map.has(p_type) && icon_map[p_type].has(p_name) && icon_map[p_type][p_name].is_valid());
}
-
-void Theme::clear_icon(const StringName& p_name,const StringName& p_type) {
+void Theme::clear_icon(const StringName &p_name, const StringName &p_type) {
ERR_FAIL_COND(!icon_map.has(p_type));
ERR_FAIL_COND(!icon_map[p_type].has(p_name));
@@ -302,7 +291,6 @@ void Theme::clear_icon(const StringName& p_name,const StringName& p_type) {
icon_map[p_type].erase(p_name);
_change_notify();
emit_changed();
-
}
void Theme::get_icon_list(StringName p_type, List<StringName> *p_list) const {
@@ -310,19 +298,18 @@ void Theme::get_icon_list(StringName p_type, List<StringName> *p_list) const {
if (!icon_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=icon_map[p_type].next(key))) {
+ while ((key = icon_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
-void Theme::set_shader(const StringName &p_name,const StringName &p_type,const Ref<Shader>& p_shader) {
- bool new_value=!shader_map.has(p_type) || !shader_map[p_type].has(p_name);
+void Theme::set_shader(const StringName &p_name, const StringName &p_type, const Ref<Shader> &p_shader) {
+ bool new_value = !shader_map.has(p_type) || !shader_map[p_type].has(p_name);
- shader_map[p_type][p_name]=p_shader;
+ shader_map[p_type][p_name] = p_shader;
if (new_value) {
_change_notify();
@@ -355,48 +342,43 @@ void Theme::get_shader_list(const StringName &p_type, List<StringName> *p_list)
if (!shader_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=shader_map[p_type].next(key))) {
+ while ((key = shader_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
-
-void Theme::set_stylebox(const StringName& p_name,const StringName& p_type,const Ref<StyleBox>& p_style) {
+void Theme::set_stylebox(const StringName &p_name, const StringName &p_type, const Ref<StyleBox> &p_style) {
//ERR_FAIL_COND(p_style.is_null());
- bool new_value=!style_map.has(p_type) || !style_map[p_type].has(p_name);
+ bool new_value = !style_map.has(p_type) || !style_map[p_type].has(p_name);
- style_map[p_type][p_name]=p_style;
+ style_map[p_type][p_name] = p_style;
if (new_value)
_change_notify();
emit_changed();
-
}
-
-Ref<StyleBox> Theme::get_stylebox(const StringName& p_name,const StringName& p_type) const {
+Ref<StyleBox> Theme::get_stylebox(const StringName &p_name, const StringName &p_type) const {
if (style_map.has(p_type) && style_map[p_type].has(p_name) && style_map[p_type][p_name].is_valid()) {
return style_map[p_type][p_name];
} else {
return default_style;
-
}
}
-bool Theme::has_stylebox(const StringName& p_name,const StringName& p_type) const {
+bool Theme::has_stylebox(const StringName &p_name, const StringName &p_type) const {
return (style_map.has(p_type) && style_map[p_type].has(p_name) && style_map[p_type][p_name].is_valid());
}
-void Theme::clear_stylebox(const StringName& p_name,const StringName& p_type) {
+void Theme::clear_stylebox(const StringName &p_name, const StringName &p_type) {
ERR_FAIL_COND(!style_map.has(p_type));
ERR_FAIL_COND(!style_map[p_type].has(p_name));
@@ -404,7 +386,6 @@ void Theme::clear_stylebox(const StringName& p_name,const StringName& p_type) {
style_map[p_type].erase(p_name);
_change_notify();
emit_changed();
-
}
void Theme::get_stylebox_list(StringName p_type, List<StringName> *p_list) const {
@@ -412,34 +393,33 @@ void Theme::get_stylebox_list(StringName p_type, List<StringName> *p_list) const
if (!style_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=style_map[p_type].next(key))) {
+ while ((key = style_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
void Theme::get_stylebox_types(List<StringName> *p_list) const {
- const StringName *key=NULL;
- while((key=style_map.next(key))) {
+ const StringName *key = NULL;
+ while ((key = style_map.next(key))) {
p_list->push_back(*key);
}
}
-void Theme::set_font(const StringName& p_name,const StringName& p_type,const Ref<Font>& p_font) {
+void Theme::set_font(const StringName &p_name, const StringName &p_type, const Ref<Font> &p_font) {
//ERR_FAIL_COND(p_font.is_null());
- bool new_value=!font_map.has(p_type) || !font_map[p_type].has(p_name);
+ bool new_value = !font_map.has(p_type) || !font_map[p_type].has(p_name);
if (!new_value) {
if (font_map[p_type][p_name].is_valid()) {
_unref_font(font_map[p_type][p_name]);
}
}
- font_map[p_type][p_name]=p_font;
+ font_map[p_type][p_name] = p_font;
if (p_font.is_valid()) {
_ref_font(p_font);
@@ -450,7 +430,7 @@ void Theme::set_font(const StringName& p_name,const StringName& p_type,const Ref
emit_changed();
}
}
-Ref<Font> Theme::get_font(const StringName& p_name,const StringName& p_type) const {
+Ref<Font> Theme::get_font(const StringName &p_name, const StringName &p_type) const {
if (font_map.has(p_type) && font_map[p_type].has(p_name) && font_map[p_type][p_name].is_valid())
return font_map[p_type][p_name];
@@ -458,15 +438,14 @@ Ref<Font> Theme::get_font(const StringName& p_name,const StringName& p_type) con
return default_theme_font;
else
return default_font;
-
}
-bool Theme::has_font(const StringName& p_name,const StringName& p_type) const {
+bool Theme::has_font(const StringName &p_name, const StringName &p_type) const {
return (font_map.has(p_type) && font_map[p_type].has(p_name) && font_map[p_type][p_name].is_valid());
}
-void Theme::clear_font(const StringName& p_name,const StringName& p_type) {
+void Theme::clear_font(const StringName &p_name, const StringName &p_type) {
ERR_FAIL_COND(!font_map.has(p_type));
ERR_FAIL_COND(!font_map[p_type].has(p_name));
@@ -478,7 +457,6 @@ void Theme::clear_font(const StringName& p_name,const StringName& p_type) {
font_map[p_type].erase(p_name);
_change_notify();
emit_changed();
-
}
void Theme::get_font_list(StringName p_type, List<StringName> *p_list) const {
@@ -486,45 +464,40 @@ void Theme::get_font_list(StringName p_type, List<StringName> *p_list) const {
if (!font_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=font_map[p_type].next(key))) {
+ while ((key = font_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
-void Theme::set_color(const StringName& p_name,const StringName& p_type,const Color& p_color) {
+void Theme::set_color(const StringName &p_name, const StringName &p_type, const Color &p_color) {
- bool new_value=!color_map.has(p_type) || !color_map[p_type].has(p_name);
+ bool new_value = !color_map.has(p_type) || !color_map[p_type].has(p_name);
- color_map[p_type][p_name]=p_color;
+ color_map[p_type][p_name] = p_color;
if (new_value) {
_change_notify();
emit_changed();
-
}
}
-
-
-Color Theme::get_color(const StringName& p_name,const StringName& p_type) const {
+Color Theme::get_color(const StringName &p_name, const StringName &p_type) const {
if (color_map.has(p_type) && color_map[p_type].has(p_name))
return color_map[p_type][p_name];
else
return Color();
-
}
-bool Theme::has_color(const StringName& p_name,const StringName& p_type) const {
+bool Theme::has_color(const StringName &p_name, const StringName &p_type) const {
return (color_map.has(p_type) && color_map[p_type].has(p_name));
}
-void Theme::clear_color(const StringName& p_name,const StringName& p_type) {
+void Theme::clear_color(const StringName &p_name, const StringName &p_type) {
ERR_FAIL_COND(!color_map.has(p_type));
ERR_FAIL_COND(!color_map[p_type].has(p_name));
@@ -532,7 +505,6 @@ void Theme::clear_color(const StringName& p_name,const StringName& p_type) {
color_map[p_type].erase(p_name);
_change_notify();
emit_changed();
-
}
void Theme::get_color_list(StringName p_type, List<StringName> *p_list) const {
@@ -540,19 +512,18 @@ void Theme::get_color_list(StringName p_type, List<StringName> *p_list) const {
if (!color_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=color_map[p_type].next(key))) {
+ while ((key = color_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
-void Theme::set_constant(const StringName& p_name,const StringName& p_type,int p_constant) {
+void Theme::set_constant(const StringName &p_name, const StringName &p_type, int p_constant) {
- bool new_value=!constant_map.has(p_type) || !constant_map[p_type].has(p_name);
- constant_map[p_type][p_name]=p_constant;
+ bool new_value = !constant_map.has(p_type) || !constant_map[p_type].has(p_name);
+ constant_map[p_type][p_name] = p_constant;
if (new_value) {
_change_notify();
@@ -560,22 +531,21 @@ void Theme::set_constant(const StringName& p_name,const StringName& p_type,int p
}
}
-int Theme::get_constant(const StringName& p_name,const StringName& p_type) const {
+int Theme::get_constant(const StringName &p_name, const StringName &p_type) const {
if (constant_map.has(p_type) && constant_map[p_type].has(p_name))
return constant_map[p_type][p_name];
else {
return 0;
}
-
}
-bool Theme::has_constant(const StringName& p_name,const StringName& p_type) const {
+bool Theme::has_constant(const StringName &p_name, const StringName &p_type) const {
return (constant_map.has(p_type) && constant_map[p_type].has(p_name));
}
-void Theme::clear_constant(const StringName& p_name,const StringName& p_type) {
+void Theme::clear_constant(const StringName &p_name, const StringName &p_type) {
ERR_FAIL_COND(!constant_map.has(p_type));
ERR_FAIL_COND(!constant_map[p_type].has(p_name));
@@ -583,7 +553,6 @@ void Theme::clear_constant(const StringName& p_name,const StringName& p_type) {
constant_map[p_type].erase(p_name);
_change_notify();
emit_changed();
-
}
void Theme::get_constant_list(StringName p_type, List<StringName> *p_list) const {
@@ -591,192 +560,176 @@ void Theme::get_constant_list(StringName p_type, List<StringName> *p_list) const
if (!constant_map.has(p_type))
return;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=constant_map[p_type].next(key))) {
+ while ((key = constant_map[p_type].next(key))) {
p_list->push_back(*key);
}
-
}
-
void Theme::copy_default_theme() {
- Ref<Theme> default_theme=get_default();
+ Ref<Theme> default_theme = get_default();
- icon_map=default_theme->icon_map;
- style_map=default_theme->style_map;
- font_map=default_theme->font_map;
- color_map=default_theme->color_map;
- constant_map=default_theme->constant_map;
+ icon_map = default_theme->icon_map;
+ style_map = default_theme->style_map;
+ font_map = default_theme->font_map;
+ color_map = default_theme->color_map;
+ constant_map = default_theme->constant_map;
_change_notify();
emit_changed();
-
}
void Theme::get_type_list(List<StringName> *p_list) const {
Set<StringName> types;
- const StringName *key=NULL;
+ const StringName *key = NULL;
- while((key=icon_map.next(key))) {
+ while ((key = icon_map.next(key))) {
types.insert(*key);
}
- key=NULL;
+ key = NULL;
- while((key=style_map.next(key))) {
+ while ((key = style_map.next(key))) {
types.insert(*key);
}
- key=NULL;
+ key = NULL;
- while((key=font_map.next(key))) {
+ while ((key = font_map.next(key))) {
types.insert(*key);
}
- key=NULL;
+ key = NULL;
- while((key=color_map.next(key))) {
+ while ((key = color_map.next(key))) {
types.insert(*key);
}
- key=NULL;
+ key = NULL;
- while((key=constant_map.next(key))) {
+ while ((key = constant_map.next(key))) {
types.insert(*key);
}
-
- for(Set<StringName>::Element *E=types.front();E;E=E->next()) {
+ for (Set<StringName>::Element *E = types.front(); E; E = E->next()) {
p_list->push_back(E->get());
}
}
-
void Theme::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_icon","name","type","texture:Texture"),&Theme::set_icon);
- ClassDB::bind_method(D_METHOD("get_icon:Texture","name","type"),&Theme::get_icon);
- ClassDB::bind_method(D_METHOD("has_icon","name","type"),&Theme::has_icon);
- ClassDB::bind_method(D_METHOD("clear_icon","name","type"),&Theme::clear_icon);
- ClassDB::bind_method(D_METHOD("get_icon_list","type"),&Theme::_get_icon_list);
-
- ClassDB::bind_method(D_METHOD("set_stylebox","name","type","texture:StyleBox"),&Theme::set_stylebox);
- ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox","name","type"),&Theme::get_stylebox);
- ClassDB::bind_method(D_METHOD("has_stylebox","name","type"),&Theme::has_stylebox);
- ClassDB::bind_method(D_METHOD("clear_stylebox","name","type"),&Theme::clear_stylebox);
- ClassDB::bind_method(D_METHOD("get_stylebox_list","type"),&Theme::_get_stylebox_list);
- ClassDB::bind_method(D_METHOD("get_stylebox_types"),&Theme::_get_stylebox_types);
+ ClassDB::bind_method(D_METHOD("set_icon", "name", "type", "texture:Texture"), &Theme::set_icon);
+ ClassDB::bind_method(D_METHOD("get_icon:Texture", "name", "type"), &Theme::get_icon);
+ ClassDB::bind_method(D_METHOD("has_icon", "name", "type"), &Theme::has_icon);
+ ClassDB::bind_method(D_METHOD("clear_icon", "name", "type"), &Theme::clear_icon);
+ ClassDB::bind_method(D_METHOD("get_icon_list", "type"), &Theme::_get_icon_list);
- ClassDB::bind_method(D_METHOD("set_font","name","type","font:Font"),&Theme::set_font);
- ClassDB::bind_method(D_METHOD("get_font:Font","name","type"),&Theme::get_font);
- ClassDB::bind_method(D_METHOD("has_font","name","type"),&Theme::has_font);
- ClassDB::bind_method(D_METHOD("clear_font","name","type"),&Theme::clear_font);
- ClassDB::bind_method(D_METHOD("get_font_list","type"),&Theme::_get_font_list);
+ ClassDB::bind_method(D_METHOD("set_stylebox", "name", "type", "texture:StyleBox"), &Theme::set_stylebox);
+ ClassDB::bind_method(D_METHOD("get_stylebox:StyleBox", "name", "type"), &Theme::get_stylebox);
+ ClassDB::bind_method(D_METHOD("has_stylebox", "name", "type"), &Theme::has_stylebox);
+ ClassDB::bind_method(D_METHOD("clear_stylebox", "name", "type"), &Theme::clear_stylebox);
+ ClassDB::bind_method(D_METHOD("get_stylebox_list", "type"), &Theme::_get_stylebox_list);
+ ClassDB::bind_method(D_METHOD("get_stylebox_types"), &Theme::_get_stylebox_types);
- ClassDB::bind_method(D_METHOD("set_color","name","type","color"),&Theme::set_color);
- ClassDB::bind_method(D_METHOD("get_color","name","type"),&Theme::get_color);
- ClassDB::bind_method(D_METHOD("has_color","name","type"),&Theme::has_color);
- ClassDB::bind_method(D_METHOD("clear_color","name","type"),&Theme::clear_color);
- ClassDB::bind_method(D_METHOD("get_color_list","type"),&Theme::_get_color_list);
+ ClassDB::bind_method(D_METHOD("set_font", "name", "type", "font:Font"), &Theme::set_font);
+ ClassDB::bind_method(D_METHOD("get_font:Font", "name", "type"), &Theme::get_font);
+ ClassDB::bind_method(D_METHOD("has_font", "name", "type"), &Theme::has_font);
+ ClassDB::bind_method(D_METHOD("clear_font", "name", "type"), &Theme::clear_font);
+ ClassDB::bind_method(D_METHOD("get_font_list", "type"), &Theme::_get_font_list);
- ClassDB::bind_method(D_METHOD("set_constant","name","type","constant"),&Theme::set_constant);
- ClassDB::bind_method(D_METHOD("get_constant","name","type"),&Theme::get_constant);
- ClassDB::bind_method(D_METHOD("has_constant","name","type"),&Theme::has_constant);
- ClassDB::bind_method(D_METHOD("clear_constant","name","type"),&Theme::clear_constant);
- ClassDB::bind_method(D_METHOD("get_constant_list","type"),&Theme::_get_constant_list);
+ ClassDB::bind_method(D_METHOD("set_color", "name", "type", "color"), &Theme::set_color);
+ ClassDB::bind_method(D_METHOD("get_color", "name", "type"), &Theme::get_color);
+ ClassDB::bind_method(D_METHOD("has_color", "name", "type"), &Theme::has_color);
+ ClassDB::bind_method(D_METHOD("clear_color", "name", "type"), &Theme::clear_color);
+ ClassDB::bind_method(D_METHOD("get_color_list", "type"), &Theme::_get_color_list);
- ClassDB::bind_method(D_METHOD("set_default_font","font"),&Theme::set_default_theme_font);
- ClassDB::bind_method(D_METHOD("get_default_font"),&Theme::get_default_theme_font);
+ ClassDB::bind_method(D_METHOD("set_constant", "name", "type", "constant"), &Theme::set_constant);
+ ClassDB::bind_method(D_METHOD("get_constant", "name", "type"), &Theme::get_constant);
+ ClassDB::bind_method(D_METHOD("has_constant", "name", "type"), &Theme::has_constant);
+ ClassDB::bind_method(D_METHOD("clear_constant", "name", "type"), &Theme::clear_constant);
+ ClassDB::bind_method(D_METHOD("get_constant_list", "type"), &Theme::_get_constant_list);
- ClassDB::bind_method(D_METHOD("get_type_list","type"),&Theme::_get_type_list);
+ ClassDB::bind_method(D_METHOD("set_default_font", "font"), &Theme::set_default_theme_font);
+ ClassDB::bind_method(D_METHOD("get_default_font"), &Theme::get_default_theme_font);
- ClassDB::bind_method(D_METHOD("_emit_theme_changed"),&Theme::_emit_theme_changed);
+ ClassDB::bind_method(D_METHOD("get_type_list", "type"), &Theme::_get_type_list);
+ ClassDB::bind_method(D_METHOD("_emit_theme_changed"), &Theme::_emit_theme_changed);
+ ClassDB::bind_method("copy_default_theme", &Theme::copy_default_theme);
-
- ClassDB::bind_method("copy_default_theme",&Theme::copy_default_theme);
-
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"default_font",PROPERTY_HINT_RESOURCE_TYPE,"Font"),"set_default_font","get_default_font");
-
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "default_font", PROPERTY_HINT_RESOURCE_TYPE, "Font"), "set_default_font", "get_default_font");
}
Theme::Theme() {
-
-
}
-
-Theme::~Theme()
-{
+Theme::~Theme() {
}
-
-
-RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_original_path, Error *r_error) {
+RES ResourceFormatLoaderTheme::load(const String &p_path, const String &p_original_path, Error *r_error) {
if (r_error)
- *r_error=ERR_CANT_OPEN;
+ *r_error = ERR_CANT_OPEN;
Error err;
- FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);
+ FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
- ERR_EXPLAIN("Unable to open theme file: "+p_path);
- ERR_FAIL_COND_V(err,RES());
+ ERR_EXPLAIN("Unable to open theme file: " + p_path);
+ ERR_FAIL_COND_V(err, RES());
String base_path = p_path.get_base_dir();
- Ref<Theme> theme( memnew( Theme ) );
- Map<StringName,Variant> library;
+ Ref<Theme> theme(memnew(Theme));
+ Map<StringName, Variant> library;
if (r_error)
- *r_error=ERR_FILE_CORRUPT;
+ *r_error = ERR_FILE_CORRUPT;
- bool reading_library=false;
- int line=0;
+ bool reading_library = false;
+ int line = 0;
- while(!f->eof_reached()) {
+ while (!f->eof_reached()) {
String l = f->get_line().strip_edges();
line++;
int comment = l.find(";");
- if (comment!=-1)
- l=l.substr(0,comment);
- if (l=="")
+ if (comment != -1)
+ l = l.substr(0, comment);
+ if (l == "")
continue;
if (l.begins_with("[")) {
- if (l=="[library]") {
- reading_library=true;
- } else if (l=="[theme]") {
- reading_library=false;
+ if (l == "[library]") {
+ reading_library = true;
+ } else if (l == "[theme]") {
+ reading_library = false;
} else {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Unknown section type: '" + l + "'.");
ERR_FAIL_V(RES());
}
continue;
}
int eqpos = l.find("=");
- if (eqpos==-1) {
+ if (eqpos == -1) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected '='.");
ERR_FAIL_V(RES());
}
-
- String right=l.substr(eqpos+1,l.length()).strip_edges();
- if (right=="") {
+ String right = l.substr(eqpos + 1, l.length()).strip_edges();
+ if (right == "") {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected value after '='.");
ERR_FAIL_V(RES());
}
@@ -790,15 +743,14 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin
value = Color::html(right);
} else if (right.begins_with("@")) { //reference
- String reference = right.substr(1,right.length());
+ String reference = right.substr(1, right.length());
if (!library.has(reference)) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid reference to '" + reference + "'.");
ERR_FAIL_V(RES());
-
}
- value=library[reference];
+ value = library[reference];
} else if (right.begins_with("default")) { //use default
//do none
@@ -806,135 +758,128 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin
//attempt to parse a constructor
int popenpos = right.find("(");
- if (popenpos==-1) {
+ if (popenpos == -1) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor syntax: " + right);
ERR_FAIL_V(RES());
}
int pclosepos = right.find_last(")");
- if (pclosepos==-1) {
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
+ if (pclosepos == -1) {
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor parameter syntax: " + right);
ERR_FAIL_V(RES());
-
}
- String type = right.substr(0,popenpos);
- String param = right.substr(popenpos+1,pclosepos-popenpos-1);
-
+ String type = right.substr(0, popenpos);
+ String param = right.substr(popenpos + 1, pclosepos - popenpos - 1);
-
- if (type=="icon") {
+ if (type == "icon") {
String path;
if (param.is_abs_path())
- path=param;
+ path = param;
else
- path=base_path+"/"+param;
+ path = base_path + "/" + param;
Ref<Texture> texture = ResourceLoader::load(path);
if (!texture.is_valid()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't find icon at path: " + path);
ERR_FAIL_V(RES());
}
- value=texture;
+ value = texture;
- } else if (type=="sbox") {
+ } else if (type == "sbox") {
String path;
if (param.is_abs_path())
- path=param;
+ path = param;
else
- path=base_path+"/"+param;
+ path = base_path + "/" + param;
Ref<StyleBox> stylebox = ResourceLoader::load(path);
if (!stylebox.is_valid()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path);
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't find stylebox at path: " + path);
ERR_FAIL_V(RES());
}
- value=stylebox;
+ value = stylebox;
- } else if (type=="sboxt") {
+ } else if (type == "sboxt") {
Vector<String> params = param.split(",");
- if (params.size()!=5 && params.size()!=9) {
+ if (params.size() != 5 && params.size() != 9) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid param count for sboxt(): '" + right + "'.");
ERR_FAIL_V(RES());
-
}
- String path=params[0];
+ String path = params[0];
if (!param.is_abs_path())
- path=base_path+"/"+path;
+ path = base_path + "/" + path;
Ref<Texture> tex = ResourceLoader::load(path);
if (tex.is_null()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Could not open texture for sboxt at path: '" + params[0] + "'.");
ERR_FAIL_V(RES());
-
}
- Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) );
+ Ref<StyleBoxTexture> sbtex(memnew(StyleBoxTexture));
sbtex->set_texture(tex);
- for(int i=0;i<4;i++) {
- if (!params[i+1].is_valid_integer()) {
+ for (int i = 0; i < 4; i++) {
+ if (!params[i + 1].is_valid_integer()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxt #" + itos(i + 1) + ", expected integer constant, got: '" + params[i + 1] + "'.");
ERR_FAIL_V(RES());
}
- int margin = params[i+1].to_int();
- sbtex->set_expand_margin_size(Margin(i),margin);
+ int margin = params[i + 1].to_int();
+ sbtex->set_expand_margin_size(Margin(i), margin);
}
- if (params.size()==9) {
+ if (params.size() == 9) {
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- if (!params[i+5].is_valid_integer()) {
+ if (!params[i + 5].is_valid_integer()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxt #" + itos(i + 5) + ", expected integer constant, got: '" + params[i + 5] + "'.");
ERR_FAIL_V(RES());
}
- int margin = params[i+5].to_int();
- sbtex->set_margin_size(Margin(i),margin);
+ int margin = params[i + 5].to_int();
+ sbtex->set_margin_size(Margin(i), margin);
}
}
value = sbtex;
- } else if (type=="sboxf") {
+ } else if (type == "sboxf") {
Vector<String> params = param.split(",");
- if (params.size()<2) {
+ if (params.size() < 2) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid param count for sboxf(): '" + right + "'.");
ERR_FAIL_V(RES());
-
}
- Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) );
+ Ref<StyleBoxFlat> sbflat(memnew(StyleBoxFlat));
if (!params[0].is_valid_integer()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected integer numeric constant for parameter 0 (border size).");
ERR_FAIL_V(RES());
-
}
sbflat->set_border_size(params[0].to_int());
@@ -942,19 +887,17 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin
if (!params[0].is_valid_integer()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected integer numeric constant for parameter 0 (border size).");
ERR_FAIL_V(RES());
-
}
+ int left = MIN(params.size() - 1, 3);
- int left = MIN( params.size()-1, 3 );
+ int ccodes = 0;
- int ccodes=0;
+ for (int i = 0; i < left; i++) {
- for(int i=0;i<left;i++) {
-
- if (params[i+1].is_valid_html_color())
+ if (params[i + 1].is_valid_html_color())
ccodes++;
else
break;
@@ -964,173 +907,164 @@ RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_origin
Color bright;
Color dark;
- if (ccodes<1) {
+ if (ccodes < 1) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected at least 1, 2 or 3 html color codes.");
ERR_FAIL_V(RES());
- } else if (ccodes==1) {
+ } else if (ccodes == 1) {
- normal=Color::html(params[1]);
- bright=Color::html(params[1]);
- dark=Color::html(params[1]);
- } else if (ccodes==2) {
+ normal = Color::html(params[1]);
+ bright = Color::html(params[1]);
+ dark = Color::html(params[1]);
+ } else if (ccodes == 2) {
- normal=Color::html(params[1]);
- bright=Color::html(params[2]);
- dark=Color::html(params[2]);
+ normal = Color::html(params[1]);
+ bright = Color::html(params[2]);
+ dark = Color::html(params[2]);
} else {
- normal=Color::html(params[1]);
- bright=Color::html(params[2]);
- dark=Color::html(params[3]);
+ normal = Color::html(params[1]);
+ bright = Color::html(params[2]);
+ dark = Color::html(params[3]);
}
sbflat->set_dark_color(dark);
sbflat->set_light_color(bright);
sbflat->set_bg_color(normal);
- if (params.size()==ccodes+5) {
+ if (params.size() == ccodes + 5) {
//margins
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
- if (!params[i+ccodes+1].is_valid_integer()) {
+ if (!params[i + ccodes + 1].is_valid_integer()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid expand margin parameter for sboxf #" + itos(i + ccodes + 1) + ", expected integer constant, got: '" + params[i + ccodes + 1] + "'.");
ERR_FAIL_V(RES());
}
//int margin = params[i+ccodes+1].to_int();
//sbflat->set_margin_size(Margin(i),margin);
}
- } else if (params.size()!=ccodes+1) {
+ } else if (params.size() != ccodes + 1) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid amount of margin parameters for sboxt.");
ERR_FAIL_V(RES());
-
}
-
- value=sbflat;
+ value = sbflat;
} else {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid constructor type: '" + type + "'.");
ERR_FAIL_V(RES());
-
}
-
}
-
//parse left and do something with it
- String left= l.substr(0,eqpos);
+ String left = l.substr(0, eqpos);
if (reading_library) {
- left=left.strip_edges();
+ left = left.strip_edges();
if (!left.is_valid_identifier()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": <LibraryItem> is not a valid identifier.");
ERR_FAIL_V(RES());
}
if (library.has(left)) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Already in library: '" + left + "'.");
ERR_FAIL_V(RES());
}
- library[left]=value;
+ library[left] = value;
} else {
int pointpos = left.find(".");
- if (pointpos==-1) {
+ if (pointpos == -1) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Expected 'control.item=..' assign syntax.");
ERR_FAIL_V(RES());
}
- String control=left.substr(0,pointpos).strip_edges();
+ String control = left.substr(0, pointpos).strip_edges();
if (!control.is_valid_identifier()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": <Control> is not a valid identifier.");
ERR_FAIL_V(RES());
}
- String item=left.substr(pointpos+1,left.size()).strip_edges();
+ String item = left.substr(pointpos + 1, left.size()).strip_edges();
if (!item.is_valid_identifier()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": <Item> is not a valid identifier.");
ERR_FAIL_V(RES());
}
- if (value.get_type()==Variant::NIL) {
+ if (value.get_type() == Variant::NIL) {
//try to use exiting
- if (Theme::get_default()->has_stylebox(item,control))
- value=Theme::get_default()->get_stylebox(item,control);
- else if (Theme::get_default()->has_font(item,control))
- value=Theme::get_default()->get_font(item,control);
- else if (Theme::get_default()->has_icon(item,control))
- value=Theme::get_default()->get_icon(item,control);
- else if (Theme::get_default()->has_color(item,control))
- value=Theme::get_default()->get_color(item,control);
- else if (Theme::get_default()->has_constant(item,control))
- value=Theme::get_default()->get_constant(item,control);
+ if (Theme::get_default()->has_stylebox(item, control))
+ value = Theme::get_default()->get_stylebox(item, control);
+ else if (Theme::get_default()->has_font(item, control))
+ value = Theme::get_default()->get_font(item, control);
+ else if (Theme::get_default()->has_icon(item, control))
+ value = Theme::get_default()->get_icon(item, control);
+ else if (Theme::get_default()->has_color(item, control))
+ value = Theme::get_default()->get_color(item, control);
+ else if (Theme::get_default()->has_constant(item, control))
+ value = Theme::get_default()->get_constant(item, control);
else {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Default not present for: '" + control + "." + item + "'.");
ERR_FAIL_V(RES());
}
-
}
- if (value.get_type()==Variant::OBJECT) {
+ if (value.get_type() == Variant::OBJECT) {
Ref<Resource> res = value;
if (!res.is_valid()) {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL).");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid resource (NULL).");
ERR_FAIL_V(RES());
}
if (res->cast_to<StyleBox>()) {
- theme->set_stylebox(item,control,res);
+ theme->set_stylebox(item, control, res);
} else if (res->cast_to<Font>()) {
- theme->set_font(item,control,res);
+ theme->set_font(item, control, res);
} else if (res->cast_to<Font>()) {
- theme->set_font(item,control,res);
+ theme->set_font(item, control, res);
} else if (res->cast_to<Texture>()) {
- theme->set_icon(item,control,res);
+ theme->set_icon(item, control, res);
} else {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type.");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Invalid resource type.");
ERR_FAIL_V(RES());
}
- } else if (value.get_type()==Variant::COLOR) {
+ } else if (value.get_type() == Variant::COLOR) {
- theme->set_color(item,control,value);
+ theme->set_color(item, control, value);
- } else if (value.get_type()==Variant::INT) {
+ } else if (value.get_type() == Variant::INT) {
- theme->set_constant(item,control,value);
+ theme->set_constant(item, control, value);
} else {
memdelete(f);
- ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?");
+ ERR_EXPLAIN(p_path + ":" + itos(line) + ": Couldn't even determine what this setting is! what did you do!?");
ERR_FAIL_V(RES());
}
-
}
-
-
}
f->close();
memdelete(f);
if (r_error)
- *r_error=OK;
+ *r_error = OK;
return theme;
}
@@ -1140,14 +1074,14 @@ void ResourceFormatLoaderTheme::get_recognized_extensions(List<String> *p_extens
p_extensions->push_back("theme");
}
-bool ResourceFormatLoaderTheme::handles_type(const String& p_type) const {
+bool ResourceFormatLoaderTheme::handles_type(const String &p_type) const {
- return p_type=="Theme";
+ return p_type == "Theme";
}
String ResourceFormatLoaderTheme::get_resource_type(const String &p_path) const {
- if (p_path.get_extension().to_lower()=="theme")
+ if (p_path.get_extension().to_lower() == "theme")
return "Theme";
return "";
}
diff --git a/scene/resources/theme.h b/scene/resources/theme.h
index e9d890cf97..4de6fd78ca 100644
--- a/scene/resources/theme.h
+++ b/scene/resources/theme.h
@@ -29,42 +29,41 @@
#ifndef THEME_H
#define THEME_H
+#include "io/resource_loader.h"
#include "resource.h"
#include "scene/resources/font.h"
+#include "scene/resources/shader.h"
#include "scene/resources/style_box.h"
#include "scene/resources/texture.h"
-#include "scene/resources/shader.h"
-#include "io/resource_loader.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class Theme : public Resource {
- GDCLASS( Theme, Resource );
+ GDCLASS(Theme, Resource);
RES_BASE_EXTENSION("thm");
static Ref<Theme> default_theme;
-
//keep a reference count to font, so each time the font changes, we emit theme changed too
- Map< Ref<Font>, int> font_refcount;
+ Map<Ref<Font>, int> font_refcount;
void _ref_font(Ref<Font> p_sc);
- void _unref_font( Ref<Font> p_sc);
+ void _unref_font(Ref<Font> p_sc);
void _emit_theme_changed();
+ HashMap<StringName, HashMap<StringName, Ref<Texture>, StringNameHasher>, StringNameHasher> icon_map;
+ HashMap<StringName, HashMap<StringName, Ref<StyleBox>, StringNameHasher>, StringNameHasher> style_map;
+ HashMap<StringName, HashMap<StringName, Ref<Font>, StringNameHasher>, StringNameHasher> font_map;
+ HashMap<StringName, HashMap<StringName, Ref<Shader>, StringNameHasher>, StringNameHasher> shader_map;
+ HashMap<StringName, HashMap<StringName, Color, StringNameHasher>, StringNameHasher> color_map;
+ HashMap<StringName, HashMap<StringName, int, StringNameHasher>, StringNameHasher> constant_map;
- HashMap<StringName,HashMap<StringName,Ref<Texture>,StringNameHasher >, StringNameHasher > icon_map;
- HashMap<StringName,HashMap<StringName,Ref<StyleBox>,StringNameHasher >,StringNameHasher > style_map;
- HashMap<StringName,HashMap<StringName,Ref<Font>,StringNameHasher >,StringNameHasher > font_map;
- HashMap<StringName,HashMap<StringName,Ref<Shader>,StringNameHasher >, StringNameHasher > shader_map;
- HashMap<StringName,HashMap<StringName,Color,StringNameHasher >,StringNameHasher > color_map;
- HashMap<StringName,HashMap<StringName,int,StringNameHasher>,StringNameHasher > constant_map;
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static Ref<Texture> default_icon;
static Ref<StyleBox> default_style;
@@ -72,84 +71,134 @@ protected:
Ref<Font> default_theme_font;
- PoolVector<String> _get_icon_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_icon_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_stylebox_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_stylebox_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_stylebox_types(void) const { PoolVector<String> ilret; List<StringName> il; get_stylebox_types(&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_font_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_font_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_color_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_color_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_constant_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_constant_list(p_type,&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
- PoolVector<String> _get_type_list(const String& p_type) const { PoolVector<String> ilret; List<StringName> il; get_type_list(&il); for(List<StringName>::Element *E=il.front();E;E=E->next()) { ilret.push_back(E->get()); } return ilret; }
+ PoolVector<String> _get_icon_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_icon_list(p_type, &il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_stylebox_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_stylebox_list(p_type, &il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_stylebox_types(void) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_stylebox_types(&il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_font_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_font_list(p_type, &il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_color_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_color_list(p_type, &il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_constant_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_constant_list(p_type, &il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
+ PoolVector<String> _get_type_list(const String &p_type) const {
+ PoolVector<String> ilret;
+ List<StringName> il;
+ get_type_list(&il);
+ for (List<StringName>::Element *E = il.front(); E; E = E->next()) {
+ ilret.push_back(E->get());
+ }
+ return ilret;
+ }
static void _bind_methods();
-public:
+public:
static Ref<Theme> get_default();
- static void set_default(const Ref<Theme>& p_default);
+ static void set_default(const Ref<Theme> &p_default);
- static void set_default_icon( const Ref<Texture>& p_icon );
- static void set_default_style( const Ref<StyleBox>& p_default_style);
- static void set_default_font( const Ref<Font>& p_default_font );
+ static void set_default_icon(const Ref<Texture> &p_icon);
+ static void set_default_style(const Ref<StyleBox> &p_default_style);
+ static void set_default_font(const Ref<Font> &p_default_font);
- void set_default_theme_font( const Ref<Font>& p_default_font );
+ void set_default_theme_font(const Ref<Font> &p_default_font);
Ref<Font> get_default_theme_font() const;
- void set_icon(const StringName& p_name,const StringName& p_type,const Ref<Texture>& p_icon);
- Ref<Texture> get_icon(const StringName& p_name,const StringName& p_type) const;
- bool has_icon(const StringName& p_name,const StringName& p_type) const;
- void clear_icon(const StringName& p_name,const StringName& p_type);
+ void set_icon(const StringName &p_name, const StringName &p_type, const Ref<Texture> &p_icon);
+ Ref<Texture> get_icon(const StringName &p_name, const StringName &p_type) const;
+ bool has_icon(const StringName &p_name, const StringName &p_type) const;
+ void clear_icon(const StringName &p_name, const StringName &p_type);
void get_icon_list(StringName p_type, List<StringName> *p_list) const;
- void set_shader(const StringName& p_name,const StringName& p_type,const Ref<Shader>& p_shader);
- Ref<Shader> get_shader(const StringName& p_name,const StringName& p_type) const;
- bool has_shader(const StringName& p_name,const StringName& p_type) const;
- void clear_shader(const StringName& p_name,const StringName& p_type);
- void get_shader_list(const StringName& p_name, List<StringName> *p_list) const;
+ void set_shader(const StringName &p_name, const StringName &p_type, const Ref<Shader> &p_shader);
+ Ref<Shader> get_shader(const StringName &p_name, const StringName &p_type) const;
+ bool has_shader(const StringName &p_name, const StringName &p_type) const;
+ void clear_shader(const StringName &p_name, const StringName &p_type);
+ void get_shader_list(const StringName &p_name, List<StringName> *p_list) const;
- void set_stylebox(const StringName& p_name,const StringName& p_type,const Ref<StyleBox>& p_style);
- Ref<StyleBox> get_stylebox(const StringName& p_name,const StringName& p_type) const;
- bool has_stylebox(const StringName& p_name,const StringName& p_type) const;
- void clear_stylebox(const StringName& p_name,const StringName& p_type);
+ void set_stylebox(const StringName &p_name, const StringName &p_type, const Ref<StyleBox> &p_style);
+ Ref<StyleBox> get_stylebox(const StringName &p_name, const StringName &p_type) const;
+ bool has_stylebox(const StringName &p_name, const StringName &p_type) const;
+ void clear_stylebox(const StringName &p_name, const StringName &p_type);
void get_stylebox_list(StringName p_type, List<StringName> *p_list) const;
void get_stylebox_types(List<StringName> *p_list) const;
- void set_font(const StringName& p_name,const StringName& p_type,const Ref<Font>& p_font);
- Ref<Font> get_font(const StringName& p_name,const StringName& p_type) const;
- bool has_font(const StringName& p_name,const StringName& p_type) const;
- void clear_font(const StringName& p_name,const StringName& p_type);
+ void set_font(const StringName &p_name, const StringName &p_type, const Ref<Font> &p_font);
+ Ref<Font> get_font(const StringName &p_name, const StringName &p_type) const;
+ bool has_font(const StringName &p_name, const StringName &p_type) const;
+ void clear_font(const StringName &p_name, const StringName &p_type);
void get_font_list(StringName p_type, List<StringName> *p_list) const;
- void set_color(const StringName& p_name,const StringName& p_type,const Color& p_color);
- Color get_color(const StringName& p_name,const StringName& p_type) const;
- bool has_color(const StringName& p_name,const StringName& p_type) const;
- void clear_color(const StringName& p_name,const StringName& p_type);
+ void set_color(const StringName &p_name, const StringName &p_type, const Color &p_color);
+ Color get_color(const StringName &p_name, const StringName &p_type) const;
+ bool has_color(const StringName &p_name, const StringName &p_type) const;
+ void clear_color(const StringName &p_name, const StringName &p_type);
void get_color_list(StringName p_type, List<StringName> *p_list) const;
- void set_constant(const StringName& p_name,const StringName& p_type,int p_constant);
- int get_constant(const StringName& p_name,const StringName& p_type) const;
- bool has_constant(const StringName& p_name,const StringName& p_type) const;
- void clear_constant(const StringName& p_name,const StringName& p_type);
+ void set_constant(const StringName &p_name, const StringName &p_type, int p_constant);
+ int get_constant(const StringName &p_name, const StringName &p_type) const;
+ bool has_constant(const StringName &p_name, const StringName &p_type) const;
+ void clear_constant(const StringName &p_name, const StringName &p_type);
void get_constant_list(StringName p_type, List<StringName> *p_list) const;
void get_type_list(List<StringName> *p_list) const;
-
void copy_default_theme();
Theme();
~Theme();
-
};
-
class ResourceFormatLoaderTheme : public ResourceFormatLoader {
public:
- virtual RES load(const String &p_path,const String& p_original_path="",Error *r_error=NULL);
+ virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL);
virtual void get_recognized_extensions(List<String> *p_extensions) const;
- virtual bool handles_type(const String& p_type) const;
+ virtual bool handles_type(const String &p_type) const;
virtual String get_resource_type(const String &p_path) const;
-
};
-
-
#endif
diff --git a/scene/resources/tile_set.cpp b/scene/resources/tile_set.cpp
index e12d8057d8..3e128379ae 100644
--- a/scene/resources/tile_set.cpp
+++ b/scene/resources/tile_set.cpp
@@ -28,341 +28,318 @@
/*************************************************************************/
#include "tile_set.h"
-bool TileSet::_set(const StringName& p_name, const Variant& p_value) {
+bool TileSet::_set(const StringName &p_name, const Variant &p_value) {
String n = p_name;
int slash = n.find("/");
- if (slash==-1)
+ if (slash == -1)
return false;
- int id = String::to_int(n.c_str(),slash);
+ int id = String::to_int(n.c_str(), slash);
if (!tile_map.has(id))
create_tile(id);
- String what = n.substr(slash+1,n.length());
-
- if (what=="name")
- tile_set_name(id,p_value);
- else if (what=="texture")
- tile_set_texture(id,p_value);
- else if (what=="tex_offset")
- tile_set_texture_offset(id,p_value);
- else if (what=="material")
- tile_set_material(id,p_value);
- else if (what=="modulate")
- tile_set_modulate(id,p_value);
- else if (what=="shape_offset")
- tile_set_shape_offset(id,p_value);
- else if (what=="region")
- tile_set_region(id,p_value);
- else if (what=="shape")
- tile_set_shape(id,p_value);
- else if (what=="shapes")
- _tile_set_shapes(id,p_value);
- else if (what=="occluder")
- tile_set_light_occluder(id,p_value);
- else if (what=="occluder_offset")
- tile_set_occluder_offset(id,p_value);
- else if (what=="navigation")
- tile_set_navigation_polygon(id,p_value);
- else if (what=="navigation_offset")
- tile_set_navigation_polygon_offset(id,p_value);
+ String what = n.substr(slash + 1, n.length());
+
+ if (what == "name")
+ tile_set_name(id, p_value);
+ else if (what == "texture")
+ tile_set_texture(id, p_value);
+ else if (what == "tex_offset")
+ tile_set_texture_offset(id, p_value);
+ else if (what == "material")
+ tile_set_material(id, p_value);
+ else if (what == "modulate")
+ tile_set_modulate(id, p_value);
+ else if (what == "shape_offset")
+ tile_set_shape_offset(id, p_value);
+ else if (what == "region")
+ tile_set_region(id, p_value);
+ else if (what == "shape")
+ tile_set_shape(id, p_value);
+ else if (what == "shapes")
+ _tile_set_shapes(id, p_value);
+ else if (what == "occluder")
+ tile_set_light_occluder(id, p_value);
+ else if (what == "occluder_offset")
+ tile_set_occluder_offset(id, p_value);
+ else if (what == "navigation")
+ tile_set_navigation_polygon(id, p_value);
+ else if (what == "navigation_offset")
+ tile_set_navigation_polygon_offset(id, p_value);
else
return false;
return true;
-
}
-bool TileSet::_get(const StringName& p_name,Variant &r_ret) const{
+bool TileSet::_get(const StringName &p_name, Variant &r_ret) const {
String n = p_name;
int slash = n.find("/");
- if (slash==-1)
+ if (slash == -1)
return false;
- int id = String::to_int(n.c_str(),slash);
-
- ERR_FAIL_COND_V(!tile_map.has(id),false);
-
- String what = n.substr(slash+1,n.length());
-
- if (what=="name")
- r_ret=tile_get_name(id);
- else if (what=="texture")
- r_ret=tile_get_texture(id);
- else if (what=="tex_offset")
- r_ret=tile_get_texture_offset(id);
- else if (what=="material")
- r_ret=tile_get_material(id);
- else if (what=="modulate")
- r_ret=tile_get_modulate(id);
- else if (what=="shape_offset")
- r_ret=tile_get_shape_offset(id);
- else if (what=="region")
- r_ret=tile_get_region(id);
- else if (what=="shape")
- r_ret=tile_get_shape(id);
- else if (what=="shapes")
- r_ret=_tile_get_shapes(id);
- else if (what=="occluder")
- r_ret=tile_get_light_occluder(id);
- else if (what=="occluder_offset")
- r_ret=tile_get_occluder_offset(id);
- else if (what=="navigation")
- r_ret=tile_get_navigation_polygon(id);
- else if (what=="navigation_offset")
- r_ret=tile_get_navigation_polygon_offset(id);
+ int id = String::to_int(n.c_str(), slash);
+
+ ERR_FAIL_COND_V(!tile_map.has(id), false);
+
+ String what = n.substr(slash + 1, n.length());
+
+ if (what == "name")
+ r_ret = tile_get_name(id);
+ else if (what == "texture")
+ r_ret = tile_get_texture(id);
+ else if (what == "tex_offset")
+ r_ret = tile_get_texture_offset(id);
+ else if (what == "material")
+ r_ret = tile_get_material(id);
+ else if (what == "modulate")
+ r_ret = tile_get_modulate(id);
+ else if (what == "shape_offset")
+ r_ret = tile_get_shape_offset(id);
+ else if (what == "region")
+ r_ret = tile_get_region(id);
+ else if (what == "shape")
+ r_ret = tile_get_shape(id);
+ else if (what == "shapes")
+ r_ret = _tile_get_shapes(id);
+ else if (what == "occluder")
+ r_ret = tile_get_light_occluder(id);
+ else if (what == "occluder_offset")
+ r_ret = tile_get_occluder_offset(id);
+ else if (what == "navigation")
+ r_ret = tile_get_navigation_polygon(id);
+ else if (what == "navigation_offset")
+ r_ret = tile_get_navigation_polygon_offset(id);
else
return false;
return true;
-
}
-void TileSet::_get_property_list( List<PropertyInfo> *p_list) const{
+void TileSet::_get_property_list(List<PropertyInfo> *p_list) const {
- for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) {
+ for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) {
int id = E->key();
- String pre = itos(id)+"/";
- p_list->push_back(PropertyInfo(Variant::STRING,pre+"name"));
- p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"));
- p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"tex_offset"));
- p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"material",PROPERTY_HINT_RESOURCE_TYPE,"CanvasItemMaterial"));
- p_list->push_back(PropertyInfo(Variant::COLOR,pre+"modulate"));
- p_list->push_back(PropertyInfo(Variant::RECT2,pre+"region"));
- p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"occluder_offset"));
- p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"occluder",PROPERTY_HINT_RESOURCE_TYPE,"OccluderPolygon2D"));
- p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"navigation_offset"));
- p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"navigation",PROPERTY_HINT_RESOURCE_TYPE,"NavigationPolygon"));
- p_list->push_back(PropertyInfo(Variant::VECTOR2,pre+"shape_offset"));
- p_list->push_back(PropertyInfo(Variant::OBJECT,pre+"shape",PROPERTY_HINT_RESOURCE_TYPE,"Shape2D",PROPERTY_USAGE_EDITOR));
- p_list->push_back(PropertyInfo(Variant::ARRAY,pre+"shapes",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
+ String pre = itos(id) + "/";
+ p_list->push_back(PropertyInfo(Variant::STRING, pre + "name"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "tex_offset"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial"));
+ p_list->push_back(PropertyInfo(Variant::COLOR, pre + "modulate"));
+ p_list->push_back(PropertyInfo(Variant::RECT2, pre + "region"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "occluder_offset"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "occluder", PROPERTY_HINT_RESOURCE_TYPE, "OccluderPolygon2D"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "navigation_offset"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "navigation", PROPERTY_HINT_RESOURCE_TYPE, "NavigationPolygon"));
+ p_list->push_back(PropertyInfo(Variant::VECTOR2, pre + "shape_offset"));
+ p_list->push_back(PropertyInfo(Variant::OBJECT, pre + "shape", PROPERTY_HINT_RESOURCE_TYPE, "Shape2D", PROPERTY_USAGE_EDITOR));
+ p_list->push_back(PropertyInfo(Variant::ARRAY, pre + "shapes", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
}
}
void TileSet::create_tile(int p_id) {
- ERR_FAIL_COND( tile_map.has(p_id) );
- tile_map[p_id]=Data();
+ ERR_FAIL_COND(tile_map.has(p_id));
+ tile_map[p_id] = Data();
_change_notify("");
emit_changed();
-
}
-void TileSet::tile_set_texture(int p_id,const Ref<Texture> &p_texture) {
+void TileSet::tile_set_texture(int p_id, const Ref<Texture> &p_texture) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].texture=p_texture;
+ tile_map[p_id].texture = p_texture;
emit_changed();
-
}
Ref<Texture> TileSet::tile_get_texture(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<Texture>());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<Texture>());
return tile_map[p_id].texture;
-
}
-
-void TileSet::tile_set_material(int p_id,const Ref<CanvasItemMaterial> &p_material) {
+void TileSet::tile_set_material(int p_id, const Ref<CanvasItemMaterial> &p_material) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].material=p_material;
+ tile_map[p_id].material = p_material;
emit_changed();
-
}
-Ref<CanvasItemMaterial> TileSet::tile_get_material(int p_id) const{
+Ref<CanvasItemMaterial> TileSet::tile_get_material(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<CanvasItemMaterial>());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<CanvasItemMaterial>());
return tile_map[p_id].material;
}
-
-void TileSet::tile_set_modulate(int p_id,const Color &p_modulate) {
+void TileSet::tile_set_modulate(int p_id, const Color &p_modulate) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].modulate=p_modulate;
+ tile_map[p_id].modulate = p_modulate;
emit_changed();
-
}
-Color TileSet::tile_get_modulate(int p_id) const{
+Color TileSet::tile_get_modulate(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Color(1,1,1));
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Color(1, 1, 1));
return tile_map[p_id].modulate;
}
-void TileSet::tile_set_texture_offset(int p_id,const Vector2 &p_offset) {
+void TileSet::tile_set_texture_offset(int p_id, const Vector2 &p_offset) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].offset=p_offset;
+ tile_map[p_id].offset = p_offset;
emit_changed();
}
Vector2 TileSet::tile_get_texture_offset(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2());
return tile_map[p_id].offset;
-
}
-void TileSet::tile_set_shape_offset(int p_id,const Vector2 &p_offset) {
+void TileSet::tile_set_shape_offset(int p_id, const Vector2 &p_offset) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].shape_offset=p_offset;
+ tile_map[p_id].shape_offset = p_offset;
emit_changed();
}
Vector2 TileSet::tile_get_shape_offset(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2());
return tile_map[p_id].shape_offset;
-
}
-void TileSet::tile_set_region(int p_id,const Rect2 &p_region) {
+void TileSet::tile_set_region(int p_id, const Rect2 &p_region) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].region=p_region;
+ tile_map[p_id].region = p_region;
emit_changed();
}
Rect2 TileSet::tile_get_region(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Rect2());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Rect2());
return tile_map[p_id].region;
-
}
-
-void TileSet::tile_set_name(int p_id,const String &p_name) {
+void TileSet::tile_set_name(int p_id, const String &p_name) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].name=p_name;
+ tile_map[p_id].name = p_name;
emit_changed();
}
String TileSet::tile_get_name(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),String());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), String());
return tile_map[p_id].name;
-
}
-void TileSet::tile_set_shape(int p_id,const Ref<Shape2D> &p_shape) {
+void TileSet::tile_set_shape(int p_id, const Ref<Shape2D> &p_shape) {
ERR_FAIL_COND(!tile_map.has(p_id));
tile_map[p_id].shapes.resize(1);
- tile_map[p_id].shapes[0]=p_shape;
+ tile_map[p_id].shapes[0] = p_shape;
emit_changed();
-
}
Ref<Shape2D> TileSet::tile_get_shape(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<Shape2D>());
- if (tile_map[p_id].shapes.size()>0)
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<Shape2D>());
+ if (tile_map[p_id].shapes.size() > 0)
return tile_map[p_id].shapes[0];
return Ref<Shape2D>();
-
}
-void TileSet::tile_set_light_occluder(int p_id,const Ref<OccluderPolygon2D> &p_light_occluder) {
+void TileSet::tile_set_light_occluder(int p_id, const Ref<OccluderPolygon2D> &p_light_occluder) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].occluder=p_light_occluder;
-
+ tile_map[p_id].occluder = p_light_occluder;
}
-Ref<OccluderPolygon2D> TileSet::tile_get_light_occluder(int p_id) const{
+Ref<OccluderPolygon2D> TileSet::tile_get_light_occluder(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<OccluderPolygon2D>());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<OccluderPolygon2D>());
return tile_map[p_id].occluder;
-
}
-void TileSet::tile_set_navigation_polygon_offset(int p_id,const Vector2& p_offset) {
+void TileSet::tile_set_navigation_polygon_offset(int p_id, const Vector2 &p_offset) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].navigation_polygon_offset=p_offset;
-
+ tile_map[p_id].navigation_polygon_offset = p_offset;
}
-Vector2 TileSet::tile_get_navigation_polygon_offset(int p_id) const{
- ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2());
+Vector2 TileSet::tile_get_navigation_polygon_offset(int p_id) const {
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2());
return tile_map[p_id].navigation_polygon_offset;
}
-void TileSet::tile_set_navigation_polygon(int p_id,const Ref<NavigationPolygon> &p_navigation_polygon) {
+void TileSet::tile_set_navigation_polygon(int p_id, const Ref<NavigationPolygon> &p_navigation_polygon) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].navigation_polygon=p_navigation_polygon;
-
+ tile_map[p_id].navigation_polygon = p_navigation_polygon;
}
Ref<NavigationPolygon> TileSet::tile_get_navigation_polygon(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Ref<NavigationPolygon>());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Ref<NavigationPolygon>());
return tile_map[p_id].navigation_polygon;
-
}
-void TileSet::tile_set_occluder_offset(int p_id,const Vector2& p_offset) {
+void TileSet::tile_set_occluder_offset(int p_id, const Vector2 &p_offset) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].occluder_offset=p_offset;
-
+ tile_map[p_id].occluder_offset = p_offset;
}
-Vector2 TileSet::tile_get_occluder_offset(int p_id) const{
- ERR_FAIL_COND_V(!tile_map.has(p_id),Vector2());
+Vector2 TileSet::tile_get_occluder_offset(int p_id) const {
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Vector2());
return tile_map[p_id].occluder_offset;
}
-void TileSet::tile_set_shapes(int p_id,const Vector<Ref<Shape2D> > &p_shapes) {
+void TileSet::tile_set_shapes(int p_id, const Vector<Ref<Shape2D> > &p_shapes) {
ERR_FAIL_COND(!tile_map.has(p_id));
- tile_map[p_id].shapes=p_shapes;
+ tile_map[p_id].shapes = p_shapes;
emit_changed();
-
}
Vector<Ref<Shape2D> > TileSet::tile_get_shapes(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Vector<Ref<Shape2D> >());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Vector<Ref<Shape2D> >());
return tile_map[p_id].shapes;
}
-void TileSet::_tile_set_shapes(int p_id,const Array& p_shapes) {
+void TileSet::_tile_set_shapes(int p_id, const Array &p_shapes) {
ERR_FAIL_COND(!tile_map.has(p_id));
Vector<Ref<Shape2D> > shapes;
- for(int i=0;i<p_shapes.size();i++) {
+ for (int i = 0; i < p_shapes.size(); i++) {
Ref<Shape2D> s = p_shapes[i];
if (s.is_valid())
shapes.push_back(s);
}
- tile_set_shapes(p_id,shapes);
+ tile_set_shapes(p_id, shapes);
}
-Array TileSet::_tile_get_shapes(int p_id) const{
+Array TileSet::_tile_get_shapes(int p_id) const {
- ERR_FAIL_COND_V(!tile_map.has(p_id),Array());
+ ERR_FAIL_COND_V(!tile_map.has(p_id), Array());
Array arr;
- Vector<Ref<Shape2D> >shp = tile_map[p_id].shapes;
- for(int i=0;i<shp.size();i++)
+ Vector<Ref<Shape2D> > shp = tile_map[p_id].shapes;
+ for (int i = 0; i < shp.size(); i++)
arr.push_back(shp[i]);
return arr;
}
-Array TileSet::_get_tiles_ids() const{
+Array TileSet::_get_tiles_ids() const {
Array arr;
@@ -375,11 +352,10 @@ Array TileSet::_get_tiles_ids() const{
void TileSet::get_tile_list(List<int> *p_tiles) const {
- for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) {
+ for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) {
p_tiles->push_back(E->key());
}
-
}
bool TileSet::has_tile(int p_id) const {
@@ -397,20 +373,17 @@ void TileSet::remove_tile(int p_id) {
int TileSet::get_last_unused_tile_id() const {
-
if (tile_map.size())
- return tile_map.back()->key()+1;
+ return tile_map.back()->key() + 1;
else
return 0;
-
}
-int TileSet::find_tile_by_name(const String& p_name) const {
+int TileSet::find_tile_by_name(const String &p_name) const {
+ for (Map<int, Data>::Element *E = tile_map.front(); E; E = E->next()) {
- for(Map<int,Data>::Element *E=tile_map.front();E;E=E->next()) {
-
- if (p_name==E->get().name)
+ if (p_name == E->get().name)
return E->key();
}
return -1;
@@ -425,42 +398,38 @@ void TileSet::clear() {
void TileSet::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("create_tile","id"),&TileSet::create_tile);
- ClassDB::bind_method(D_METHOD("tile_set_name","id","name"),&TileSet::tile_set_name);
- ClassDB::bind_method(D_METHOD("tile_get_name","id"),&TileSet::tile_get_name);
- ClassDB::bind_method(D_METHOD("tile_set_texture","id","texture:Texture"),&TileSet::tile_set_texture);
- ClassDB::bind_method(D_METHOD("tile_get_texture:Texture","id"),&TileSet::tile_get_texture);
- ClassDB::bind_method(D_METHOD("tile_set_material","id","material:CanvasItemMaterial"),&TileSet::tile_set_material);
- ClassDB::bind_method(D_METHOD("tile_get_material:CanvasItemMaterial","id"),&TileSet::tile_get_material);
- ClassDB::bind_method(D_METHOD("tile_set_texture_offset","id","texture_offset"),&TileSet::tile_set_texture_offset);
- ClassDB::bind_method(D_METHOD("tile_get_texture_offset","id"),&TileSet::tile_get_texture_offset);
- ClassDB::bind_method(D_METHOD("tile_set_shape_offset","id","shape_offset"),&TileSet::tile_set_shape_offset);
- ClassDB::bind_method(D_METHOD("tile_get_shape_offset","id"),&TileSet::tile_get_shape_offset);
- ClassDB::bind_method(D_METHOD("tile_set_region","id","region"),&TileSet::tile_set_region);
- ClassDB::bind_method(D_METHOD("tile_get_region","id"),&TileSet::tile_get_region);
- ClassDB::bind_method(D_METHOD("tile_set_shape","id","shape:Shape2D"),&TileSet::tile_set_shape);
- ClassDB::bind_method(D_METHOD("tile_get_shape:Shape2D","id"),&TileSet::tile_get_shape);
- ClassDB::bind_method(D_METHOD("tile_set_shapes","id","shapes"),&TileSet::_tile_set_shapes);
- ClassDB::bind_method(D_METHOD("tile_get_shapes","id"),&TileSet::_tile_get_shapes);
- ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon","id","navigation_polygon:NavigationPolygon"),&TileSet::tile_set_navigation_polygon);
- ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon:NavigationPolygon","id"),&TileSet::tile_get_navigation_polygon);
- ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon_offset","id","navigation_polygon_offset"),&TileSet::tile_set_navigation_polygon_offset);
- ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon_offset","id"),&TileSet::tile_get_navigation_polygon_offset);
- ClassDB::bind_method(D_METHOD("tile_set_light_occluder","id","light_occluder:OccluderPolygon2D"),&TileSet::tile_set_light_occluder);
- ClassDB::bind_method(D_METHOD("tile_get_light_occluder:OccluderPolygon2D","id"),&TileSet::tile_get_light_occluder);
- ClassDB::bind_method(D_METHOD("tile_set_occluder_offset","id","occluder_offset"),&TileSet::tile_set_occluder_offset);
- ClassDB::bind_method(D_METHOD("tile_get_occluder_offset","id"),&TileSet::tile_get_occluder_offset);
-
- ClassDB::bind_method(D_METHOD("remove_tile","id"),&TileSet::remove_tile);
- ClassDB::bind_method(D_METHOD("clear"),&TileSet::clear);
- ClassDB::bind_method(D_METHOD("get_last_unused_tile_id"),&TileSet::get_last_unused_tile_id);
- ClassDB::bind_method(D_METHOD("find_tile_by_name","name"),&TileSet::find_tile_by_name);
+ ClassDB::bind_method(D_METHOD("create_tile", "id"), &TileSet::create_tile);
+ ClassDB::bind_method(D_METHOD("tile_set_name", "id", "name"), &TileSet::tile_set_name);
+ ClassDB::bind_method(D_METHOD("tile_get_name", "id"), &TileSet::tile_get_name);
+ ClassDB::bind_method(D_METHOD("tile_set_texture", "id", "texture:Texture"), &TileSet::tile_set_texture);
+ ClassDB::bind_method(D_METHOD("tile_get_texture:Texture", "id"), &TileSet::tile_get_texture);
+ ClassDB::bind_method(D_METHOD("tile_set_material", "id", "material:CanvasItemMaterial"), &TileSet::tile_set_material);
+ ClassDB::bind_method(D_METHOD("tile_get_material:CanvasItemMaterial", "id"), &TileSet::tile_get_material);
+ ClassDB::bind_method(D_METHOD("tile_set_texture_offset", "id", "texture_offset"), &TileSet::tile_set_texture_offset);
+ ClassDB::bind_method(D_METHOD("tile_get_texture_offset", "id"), &TileSet::tile_get_texture_offset);
+ ClassDB::bind_method(D_METHOD("tile_set_shape_offset", "id", "shape_offset"), &TileSet::tile_set_shape_offset);
+ ClassDB::bind_method(D_METHOD("tile_get_shape_offset", "id"), &TileSet::tile_get_shape_offset);
+ ClassDB::bind_method(D_METHOD("tile_set_region", "id", "region"), &TileSet::tile_set_region);
+ ClassDB::bind_method(D_METHOD("tile_get_region", "id"), &TileSet::tile_get_region);
+ ClassDB::bind_method(D_METHOD("tile_set_shape", "id", "shape:Shape2D"), &TileSet::tile_set_shape);
+ ClassDB::bind_method(D_METHOD("tile_get_shape:Shape2D", "id"), &TileSet::tile_get_shape);
+ ClassDB::bind_method(D_METHOD("tile_set_shapes", "id", "shapes"), &TileSet::_tile_set_shapes);
+ ClassDB::bind_method(D_METHOD("tile_get_shapes", "id"), &TileSet::_tile_get_shapes);
+ ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon", "id", "navigation_polygon:NavigationPolygon"), &TileSet::tile_set_navigation_polygon);
+ ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon:NavigationPolygon", "id"), &TileSet::tile_get_navigation_polygon);
+ ClassDB::bind_method(D_METHOD("tile_set_navigation_polygon_offset", "id", "navigation_polygon_offset"), &TileSet::tile_set_navigation_polygon_offset);
+ ClassDB::bind_method(D_METHOD("tile_get_navigation_polygon_offset", "id"), &TileSet::tile_get_navigation_polygon_offset);
+ ClassDB::bind_method(D_METHOD("tile_set_light_occluder", "id", "light_occluder:OccluderPolygon2D"), &TileSet::tile_set_light_occluder);
+ ClassDB::bind_method(D_METHOD("tile_get_light_occluder:OccluderPolygon2D", "id"), &TileSet::tile_get_light_occluder);
+ ClassDB::bind_method(D_METHOD("tile_set_occluder_offset", "id", "occluder_offset"), &TileSet::tile_set_occluder_offset);
+ ClassDB::bind_method(D_METHOD("tile_get_occluder_offset", "id"), &TileSet::tile_get_occluder_offset);
+
+ ClassDB::bind_method(D_METHOD("remove_tile", "id"), &TileSet::remove_tile);
+ ClassDB::bind_method(D_METHOD("clear"), &TileSet::clear);
+ ClassDB::bind_method(D_METHOD("get_last_unused_tile_id"), &TileSet::get_last_unused_tile_id);
+ ClassDB::bind_method(D_METHOD("find_tile_by_name", "name"), &TileSet::find_tile_by_name);
ClassDB::bind_method(D_METHOD("get_tiles_ids", "name"), &TileSet::_get_tiles_ids);
-
}
-
TileSet::TileSet() {
-
}
diff --git a/scene/resources/tile_set.h b/scene/resources/tile_set.h
index b80889fc6f..53f68d00a5 100644
--- a/scene/resources/tile_set.h
+++ b/scene/resources/tile_set.h
@@ -30,14 +30,14 @@
#define TILE_SET_H
#include "resource.h"
-#include "scene/resources/shape_2d.h"
-#include "scene/resources/texture.h"
#include "scene/2d/light_occluder_2d.h"
#include "scene/2d/navigation_polygon.h"
+#include "scene/resources/shape_2d.h"
+#include "scene/resources/texture.h"
class TileSet : public Resource {
- GDCLASS( TileSet, Resource );
+ GDCLASS(TileSet, Resource);
struct Data {
@@ -55,72 +55,69 @@ class TileSet : public Resource {
Color modulate;
// Default modulate for back-compat
- explicit Data() : modulate(1,1,1) {}
+ explicit Data()
+ : modulate(1, 1, 1) {}
};
- Map<int,Data> tile_map;
-
+ Map<int, Data> tile_map;
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
- void _tile_set_shapes(int p_id,const Array& p_shapes);
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
+ void _tile_set_shapes(int p_id, const Array &p_shapes);
Array _tile_get_shapes(int p_id) const;
Array _get_tiles_ids() const;
static void _bind_methods();
-public:
-
-
+public:
void create_tile(int p_id);
- void tile_set_name(int p_id,const String &p_name);
+ void tile_set_name(int p_id, const String &p_name);
String tile_get_name(int p_id) const;
void tile_set_texture(int p_id, const Ref<Texture> &p_texture);
Ref<Texture> tile_get_texture(int p_id) const;
- void tile_set_texture_offset(int p_id,const Vector2 &p_offset);
+ void tile_set_texture_offset(int p_id, const Vector2 &p_offset);
Vector2 tile_get_texture_offset(int p_id) const;
- void tile_set_shape_offset(int p_id,const Vector2 &p_offset);
+ void tile_set_shape_offset(int p_id, const Vector2 &p_offset);
Vector2 tile_get_shape_offset(int p_id) const;
- void tile_set_region(int p_id,const Rect2 &p_region);
+ void tile_set_region(int p_id, const Rect2 &p_region);
Rect2 tile_get_region(int p_id) const;
- void tile_set_shape(int p_id,const Ref<Shape2D> &p_shape);
+ void tile_set_shape(int p_id, const Ref<Shape2D> &p_shape);
Ref<Shape2D> tile_get_shape(int p_id) const;
- void tile_set_material(int p_id,const Ref<CanvasItemMaterial> &p_material);
+ void tile_set_material(int p_id, const Ref<CanvasItemMaterial> &p_material);
Ref<CanvasItemMaterial> tile_get_material(int p_id) const;
- void tile_set_modulate(int p_id,const Color &p_color);
+ void tile_set_modulate(int p_id, const Color &p_color);
Color tile_get_modulate(int p_id) const;
- void tile_set_occluder_offset(int p_id,const Vector2& p_offset);
+ void tile_set_occluder_offset(int p_id, const Vector2 &p_offset);
Vector2 tile_get_occluder_offset(int p_id) const;
- void tile_set_light_occluder(int p_id,const Ref<OccluderPolygon2D> &p_light_occluder);
+ void tile_set_light_occluder(int p_id, const Ref<OccluderPolygon2D> &p_light_occluder);
Ref<OccluderPolygon2D> tile_get_light_occluder(int p_id) const;
- void tile_set_navigation_polygon_offset(int p_id,const Vector2& p_offset);
+ void tile_set_navigation_polygon_offset(int p_id, const Vector2 &p_offset);
Vector2 tile_get_navigation_polygon_offset(int p_id) const;
- void tile_set_navigation_polygon(int p_id,const Ref<NavigationPolygon> &p_navigation_polygon);
+ void tile_set_navigation_polygon(int p_id, const Ref<NavigationPolygon> &p_navigation_polygon);
Ref<NavigationPolygon> tile_get_navigation_polygon(int p_id) const;
- void tile_set_shapes(int p_id,const Vector<Ref<Shape2D> > &p_shapes);
+ void tile_set_shapes(int p_id, const Vector<Ref<Shape2D> > &p_shapes);
Vector<Ref<Shape2D> > tile_get_shapes(int p_id) const;
void remove_tile(int p_id);
bool has_tile(int p_id) const;
- int find_tile_by_name(const String& p_name) const;
+ int find_tile_by_name(const String &p_name) const;
void get_tile_list(List<int> *p_tiles) const;
void clear();
diff --git a/scene/resources/video_stream.cpp b/scene/resources/video_stream.cpp
index 84186616d7..47c40e4e6b 100644
--- a/scene/resources/video_stream.cpp
+++ b/scene/resources/video_stream.cpp
@@ -28,12 +28,10 @@
/*************************************************************************/
#include "video_stream.h"
-void VideoStreamPlayback::_bind_methods() {
+void VideoStreamPlayback::_bind_methods(){
};
-
-VideoStreamPlayback::VideoStreamPlayback() {
+VideoStreamPlayback::VideoStreamPlayback(){
};
-
diff --git a/scene/resources/video_stream.h b/scene/resources/video_stream.h
index bcd25c0336..7c1bd94c8b 100644
--- a/scene/resources/video_stream.h
+++ b/scene/resources/video_stream.h
@@ -32,62 +32,56 @@
#include "audio_stream_resampled.h"
#include "scene/resources/texture.h"
-
class VideoStreamPlayback : public Resource {
- GDCLASS(VideoStreamPlayback,Resource);
+ GDCLASS(VideoStreamPlayback, Resource);
protected:
static void _bind_methods();
public:
+ typedef int (*AudioMixCallback)(void *p_udata, const int16_t *p_data, int p_frames);
- typedef int (*AudioMixCallback)(void* p_udata,const int16_t *p_data,int p_frames);
-
- virtual void stop()=0;
- virtual void play()=0;
+ virtual void stop() = 0;
+ virtual void play() = 0;
- virtual bool is_playing() const=0;
+ virtual bool is_playing() const = 0;
- virtual void set_paused(bool p_paused)=0;
- virtual bool is_paused(bool p_paused) const=0;
+ virtual void set_paused(bool p_paused) = 0;
+ virtual bool is_paused(bool p_paused) const = 0;
- virtual void set_loop(bool p_enable)=0;
- virtual bool has_loop() const=0;
+ virtual void set_loop(bool p_enable) = 0;
+ virtual bool has_loop() const = 0;
- virtual float get_length() const=0;
+ virtual float get_length() const = 0;
- virtual float get_pos() const=0;
- virtual void seek_pos(float p_time)=0;
+ virtual float get_pos() const = 0;
+ virtual void seek_pos(float p_time) = 0;
- virtual void set_audio_track(int p_idx) =0;
+ virtual void set_audio_track(int p_idx) = 0;
//virtual int mix(int16_t* p_bufer,int p_frames)=0;
- virtual Ref<Texture> get_texture()=0;
- virtual void update(float p_delta)=0;
+ virtual Ref<Texture> get_texture() = 0;
+ virtual void update(float p_delta) = 0;
- virtual void set_mix_callback(AudioMixCallback p_callback,void *p_userdata)=0;
- virtual int get_channels() const=0;
- virtual int get_mix_rate() const=0;
+ virtual void set_mix_callback(AudioMixCallback p_callback, void *p_userdata) = 0;
+ virtual int get_channels() const = 0;
+ virtual int get_mix_rate() const = 0;
VideoStreamPlayback();
};
-
class VideoStream : public Resource {
- GDCLASS( VideoStream, Resource );
- OBJ_SAVE_TYPE( VideoStream ); //children are all saved as AudioStream, so they can be exchanged
+ GDCLASS(VideoStream, Resource);
+ OBJ_SAVE_TYPE(VideoStream); //children are all saved as AudioStream, so they can be exchanged
public:
-
- virtual void set_audio_track(int p_track)=0;
- virtual Ref<VideoStreamPlayback> instance_playback()=0;
+ virtual void set_audio_track(int p_track) = 0;
+ virtual Ref<VideoStreamPlayback> instance_playback() = 0;
VideoStream() {}
};
-
#endif
-
diff --git a/scene/resources/world.cpp b/scene/resources/world.cpp
index f9233d950c..dc62c2ab3e 100644
--- a/scene/resources/world.cpp
+++ b/scene/resources/world.cpp
@@ -27,76 +27,73 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "world.h"
+#include "camera_matrix.h"
+#include "octree.h"
#include "scene/3d/camera.h"
-#include "scene/3d/visibility_notifier.h"
#include "scene/3d/spatial_indexer.h"
+#include "scene/3d/visibility_notifier.h"
#include "scene/scene_string_names.h"
-#include "octree.h"
-#include "camera_matrix.h"
struct SpatialIndexer {
-
Octree<VisibilityNotifier> octree;
struct NotifierData {
Rect3 aabb;
OctreeElementID id;
-
};
- Map<VisibilityNotifier*,NotifierData> notifiers;
+ Map<VisibilityNotifier *, NotifierData> notifiers;
struct CameraData {
- Map<VisibilityNotifier*,uint64_t> notifiers;
+ Map<VisibilityNotifier *, uint64_t> notifiers;
};
- Map<Camera*,CameraData> cameras;
+ Map<Camera *, CameraData> cameras;
enum {
- VISIBILITY_CULL_MAX=32768
+ VISIBILITY_CULL_MAX = 32768
};
- Vector<VisibilityNotifier*> cull;
+ Vector<VisibilityNotifier *> cull;
bool changed;
uint64_t pass;
uint64_t last_frame;
- void _notifier_add(VisibilityNotifier* p_notifier,const Rect3& p_rect) {
+ void _notifier_add(VisibilityNotifier *p_notifier, const Rect3 &p_rect) {
ERR_FAIL_COND(notifiers.has(p_notifier));
- notifiers[p_notifier].aabb=p_rect;
- notifiers[p_notifier].id = octree.create(p_notifier,p_rect);
- changed=true;
-
+ notifiers[p_notifier].aabb = p_rect;
+ notifiers[p_notifier].id = octree.create(p_notifier, p_rect);
+ changed = true;
}
- void _notifier_update(VisibilityNotifier* p_notifier,const Rect3& p_rect) {
+ void _notifier_update(VisibilityNotifier *p_notifier, const Rect3 &p_rect) {
- Map<VisibilityNotifier*,NotifierData>::Element *E=notifiers.find(p_notifier);
+ Map<VisibilityNotifier *, NotifierData>::Element *E = notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
- if (E->get().aabb==p_rect)
+ if (E->get().aabb == p_rect)
return;
- E->get().aabb=p_rect;
- octree.move(E->get().id,E->get().aabb);
- changed=true;
+ E->get().aabb = p_rect;
+ octree.move(E->get().id, E->get().aabb);
+ changed = true;
}
- void _notifier_remove(VisibilityNotifier* p_notifier) {
+ void _notifier_remove(VisibilityNotifier *p_notifier) {
- Map<VisibilityNotifier*,NotifierData>::Element *E=notifiers.find(p_notifier);
+ Map<VisibilityNotifier *, NotifierData>::Element *E = notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
octree.erase(E->get().id);
notifiers.erase(p_notifier);
- List<Camera*> removed;
- for (Map<Camera*,CameraData>::Element*F=cameras.front();F;F=F->next()) {
+ List<Camera *> removed;
+ for (Map<Camera *, CameraData>::Element *F = cameras.front(); F; F = F->next()) {
- Map<VisibilityNotifier*,uint64_t>::Element*G=F->get().notifiers.find(p_notifier);
+ Map<VisibilityNotifier *, uint64_t>::Element *G = F->get().notifiers.find(p_notifier);
if (G) {
F->get().notifiers.erase(G);
@@ -104,170 +101,154 @@ struct SpatialIndexer {
}
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
p_notifier->_exit_camera(removed.front()->get());
removed.pop_front();
}
-
- changed=true;
+ changed = true;
}
- void _add_camera(Camera* p_camera) {
+ void _add_camera(Camera *p_camera) {
ERR_FAIL_COND(cameras.has(p_camera));
CameraData vd;
- cameras[p_camera]=vd;
- changed=true;
-
+ cameras[p_camera] = vd;
+ changed = true;
}
- void _update_camera(Camera* p_camera) {
+ void _update_camera(Camera *p_camera) {
- Map<Camera*,CameraData>::Element *E= cameras.find(p_camera);
+ Map<Camera *, CameraData>::Element *E = cameras.find(p_camera);
ERR_FAIL_COND(!E);
- changed=true;
+ changed = true;
}
- void _remove_camera(Camera* p_camera) {
+ void _remove_camera(Camera *p_camera) {
ERR_FAIL_COND(!cameras.has(p_camera));
- List<VisibilityNotifier*> removed;
- for(Map<VisibilityNotifier*,uint64_t>::Element *E=cameras[p_camera].notifiers.front();E;E=E->next()) {
+ List<VisibilityNotifier *> removed;
+ for (Map<VisibilityNotifier *, uint64_t>::Element *E = cameras[p_camera].notifiers.front(); E; E = E->next()) {
removed.push_back(E->key());
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
removed.front()->get()->_exit_camera(p_camera);
removed.pop_front();
}
cameras.erase(p_camera);
-
}
void _update(uint64_t p_frame) {
- if (p_frame==last_frame)
+ if (p_frame == last_frame)
return;
- last_frame=p_frame;
+ last_frame = p_frame;
if (!changed)
return;
-
-
- for (Map<Camera*,CameraData>::Element *E=cameras.front();E;E=E->next()) {
+ for (Map<Camera *, CameraData>::Element *E = cameras.front(); E; E = E->next()) {
pass++;
- Camera *c=E->key();
+ Camera *c = E->key();
Vector<Plane> planes = c->get_frustum();
- int culled = octree.cull_convex(planes,cull.ptr(),cull.size());
-
+ int culled = octree.cull_convex(planes, cull.ptr(), cull.size());
- VisibilityNotifier**ptr=cull.ptr();
+ VisibilityNotifier **ptr = cull.ptr();
- List<VisibilityNotifier*> added;
- List<VisibilityNotifier*> removed;
+ List<VisibilityNotifier *> added;
+ List<VisibilityNotifier *> removed;
- for(int i=0;i<culled;i++) {
+ for (int i = 0; i < culled; i++) {
//notifiers in frustum
- Map<VisibilityNotifier*,uint64_t>::Element *H=E->get().notifiers.find(ptr[i]);
+ Map<VisibilityNotifier *, uint64_t>::Element *H = E->get().notifiers.find(ptr[i]);
if (!H) {
- E->get().notifiers.insert(ptr[i],pass);
+ E->get().notifiers.insert(ptr[i], pass);
added.push_back(ptr[i]);
} else {
- H->get()=pass;
+ H->get() = pass;
}
-
-
}
- for (Map<VisibilityNotifier*,uint64_t>::Element *F=E->get().notifiers.front();F;F=F->next()) {
+ for (Map<VisibilityNotifier *, uint64_t>::Element *F = E->get().notifiers.front(); F; F = F->next()) {
- if (F->get()!=pass)
+ if (F->get() != pass)
removed.push_back(F->key());
}
- while(!added.empty()) {
+ while (!added.empty()) {
added.front()->get()->_enter_camera(E->key());
added.pop_front();
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
E->get().notifiers.erase(removed.front()->get());
removed.front()->get()->_exit_camera(E->key());
removed.pop_front();
}
}
- changed=false;
+ changed = false;
}
-
SpatialIndexer() {
- pass=0;
- last_frame=0;
- changed=false;
+ pass = 0;
+ last_frame = 0;
+ changed = false;
cull.resize(VISIBILITY_CULL_MAX);
}
-
};
-
-
-void World::_register_camera(Camera* p_camera) {
+void World::_register_camera(Camera *p_camera) {
#ifndef _3D_DISABLED
indexer->_add_camera(p_camera);
#endif
}
-void World::_update_camera(Camera* p_camera){
+void World::_update_camera(Camera *p_camera) {
#ifndef _3D_DISABLED
indexer->_update_camera(p_camera);
#endif
}
-void World::_remove_camera(Camera* p_camera){
+void World::_remove_camera(Camera *p_camera) {
#ifndef _3D_DISABLED
indexer->_remove_camera(p_camera);
#endif
}
-
-
-
-void World::_register_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect){
+void World::_register_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect) {
#ifndef _3D_DISABLED
- indexer->_notifier_add(p_notifier,p_rect);
+ indexer->_notifier_add(p_notifier, p_rect);
#endif
}
-void World::_update_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect){
+void World::_update_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect) {
#ifndef _3D_DISABLED
- indexer->_notifier_update(p_notifier,p_rect);
+ indexer->_notifier_update(p_notifier, p_rect);
#endif
}
-void World::_remove_notifier(VisibilityNotifier* p_notifier){
+void World::_remove_notifier(VisibilityNotifier *p_notifier) {
#ifndef _3D_DISABLED
indexer->_notifier_remove(p_notifier);
#endif
}
-
void World::_update(uint64_t p_frame) {
#ifndef _3D_DISABLED
@@ -275,26 +256,22 @@ void World::_update(uint64_t p_frame) {
#endif
}
-
-
-
-
RID World::get_space() const {
return space;
}
-RID World::get_scenario() const{
+RID World::get_scenario() const {
return scenario;
}
-void World::set_environment(const Ref<Environment>& p_environment) {
+void World::set_environment(const Ref<Environment> &p_environment) {
- environment=p_environment;
+ environment = p_environment;
if (environment.is_valid())
- VS::get_singleton()->scenario_set_environment(scenario,environment->get_rid());
+ VS::get_singleton()->scenario_set_environment(scenario, environment->get_rid());
else
- VS::get_singleton()->scenario_set_environment(scenario,RID());
+ VS::get_singleton()->scenario_set_environment(scenario, RID());
}
Ref<Environment> World::get_environment() const {
@@ -302,7 +279,6 @@ Ref<Environment> World::get_environment() const {
return environment;
}
-
PhysicsDirectSpaceState *World::get_direct_space_state() {
return PhysicsServer::get_singleton()->space_get_direct_state(space);
@@ -310,31 +286,29 @@ PhysicsDirectSpaceState *World::get_direct_space_state() {
void World::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_space"),&World::get_space);
- ClassDB::bind_method(D_METHOD("get_scenario"),&World::get_scenario);
- ClassDB::bind_method(D_METHOD("set_environment","env:Environment"),&World::set_environment);
- ClassDB::bind_method(D_METHOD("get_environment:Environment"),&World::get_environment);
- ClassDB::bind_method(D_METHOD("get_direct_space_state:PhysicsDirectSpaceState"),&World::get_direct_space_state);
- ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"environment",PROPERTY_HINT_RESOURCE_TYPE,"Environment"),"set_environment","get_environment");
-
+ ClassDB::bind_method(D_METHOD("get_space"), &World::get_space);
+ ClassDB::bind_method(D_METHOD("get_scenario"), &World::get_scenario);
+ ClassDB::bind_method(D_METHOD("set_environment", "env:Environment"), &World::set_environment);
+ ClassDB::bind_method(D_METHOD("get_environment:Environment"), &World::get_environment);
+ ClassDB::bind_method(D_METHOD("get_direct_space_state:PhysicsDirectSpaceState"), &World::get_direct_space_state);
+ ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "environment", PROPERTY_HINT_RESOURCE_TYPE, "Environment"), "set_environment", "get_environment");
}
-
World::World() {
space = PhysicsServer::get_singleton()->space_create();
scenario = VisualServer::get_singleton()->scenario_create();
- PhysicsServer::get_singleton()->space_set_active(space,true);
- PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_GRAVITY,GLOBAL_DEF("physics/3d/default_gravity",9.8));
- PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_GRAVITY_VECTOR,GLOBAL_DEF("physics/3d/default_gravity_vector",Vector3(0,-1,0)));
- PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_LINEAR_DAMP,GLOBAL_DEF("physics/3d/default_linear_damp",0.1));
- PhysicsServer::get_singleton()->area_set_param(space,PhysicsServer::AREA_PARAM_ANGULAR_DAMP,GLOBAL_DEF("physics/3d/default_angular_damp",0.1));
+ PhysicsServer::get_singleton()->space_set_active(space, true);
+ PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_GRAVITY, GLOBAL_DEF("physics/3d/default_gravity", 9.8));
+ PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF("physics/3d/default_gravity_vector", Vector3(0, -1, 0)));
+ PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/3d/default_linear_damp", 0.1));
+ PhysicsServer::get_singleton()->area_set_param(space, PhysicsServer::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/3d/default_angular_damp", 0.1));
#ifdef _3D_DISABLED
indexer = NULL;
#else
- indexer = memnew( SpatialIndexer );
+ indexer = memnew(SpatialIndexer);
#endif
}
@@ -344,8 +318,6 @@ World::~World() {
VisualServer::get_singleton()->free(scenario);
#ifndef _3D_DISABLED
- memdelete( indexer );
+ memdelete(indexer);
#endif
-
-
}
diff --git a/scene/resources/world.h b/scene/resources/world.h
index 1ad60f3405..a597633ca1 100644
--- a/scene/resources/world.h
+++ b/scene/resources/world.h
@@ -30,9 +30,9 @@
#define WORLD_H
#include "resource.h"
+#include "scene/resources/environment.h"
#include "servers/physics_server.h"
#include "servers/visual_server.h"
-#include "scene/resources/environment.h"
class SpatialIndexer;
class Camera;
@@ -41,42 +41,39 @@ class VisibilityNotifier;
class World : public Resource {
GDCLASS(World, Resource);
RES_BASE_EXTENSION("wrd");
+
private:
RID space;
RID scenario;
- SpatialIndexer* indexer;
+ SpatialIndexer *indexer;
Ref<Environment> environment;
protected:
-
static void _bind_methods();
-friend class Camera;
-friend class VisibilityNotifier;
+ friend class Camera;
+ friend class VisibilityNotifier;
- void _register_camera(Camera* p_camera);
- void _update_camera(Camera* p_camera);
- void _remove_camera(Camera* p_camera);
+ void _register_camera(Camera *p_camera);
+ void _update_camera(Camera *p_camera);
+ void _remove_camera(Camera *p_camera);
- void _register_notifier(VisibilityNotifier* p_notifier,const Rect3& p_rect);
- void _update_notifier(VisibilityNotifier *p_notifier,const Rect3& p_rect);
- void _remove_notifier(VisibilityNotifier* p_notifier);
-friend class Viewport;
+ void _register_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect);
+ void _update_notifier(VisibilityNotifier *p_notifier, const Rect3 &p_rect);
+ void _remove_notifier(VisibilityNotifier *p_notifier);
+ friend class Viewport;
void _update(uint64_t p_frame);
-
public:
-
RID get_space() const;
RID get_scenario() const;
- void set_environment(const Ref<Environment>& p_environment);
+ void set_environment(const Ref<Environment> &p_environment);
Ref<Environment> get_environment() const;
PhysicsDirectSpaceState *get_direct_space_state();
World();
~World();
-
};
#endif // WORLD_H
diff --git a/scene/resources/world_2d.cpp b/scene/resources/world_2d.cpp
index 6b745d5d35..cb346199c9 100644
--- a/scene/resources/world_2d.cpp
+++ b/scene/resources/world_2d.cpp
@@ -27,18 +27,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "world_2d.h"
-#include "servers/visual_server.h"
#include "servers/physics_2d_server.h"
+#include "servers/visual_server.h"
//#include "servers/spatial_sound_2d_server.h"
#include "global_config.h"
+#include "global_config.h"
+#include "scene/2d/camera_2d.h"
#include "scene/2d/visibility_notifier_2d.h"
#include "scene/main/viewport.h"
-#include "scene/2d/camera_2d.h"
-#include "global_config.h"
struct SpatialIndexer2D {
-
struct CellRef {
int ref;
@@ -53,12 +52,10 @@ struct SpatialIndexer2D {
}
_FORCE_INLINE_ CellRef() {
- ref=0;
+ ref = 0;
}
};
-
-
struct CellKey {
union {
@@ -69,61 +66,58 @@ struct SpatialIndexer2D {
uint64_t key;
};
- bool operator==(const CellKey& p_key) const { return key==p_key.key; }
- _FORCE_INLINE_ bool operator<(const CellKey& p_key) const {
+ bool operator==(const CellKey &p_key) const { return key == p_key.key; }
+ _FORCE_INLINE_ bool operator<(const CellKey &p_key) const {
return key < p_key.key;
}
-
};
struct CellData {
- Map<VisibilityNotifier2D*,CellRef> notifiers;
+ Map<VisibilityNotifier2D *, CellRef> notifiers;
};
-
- Map<CellKey,CellData> cells;
+ Map<CellKey, CellData> cells;
int cell_size;
- Map<VisibilityNotifier2D*,Rect2> notifiers;
+ Map<VisibilityNotifier2D *, Rect2> notifiers;
struct ViewportData {
- Map<VisibilityNotifier2D*,uint64_t> notifiers;
+ Map<VisibilityNotifier2D *, uint64_t> notifiers;
Rect2 rect;
};
- Map<Viewport*,ViewportData> viewports;
+ Map<Viewport *, ViewportData> viewports;
bool changed;
uint64_t pass;
-
- void _notifier_update_cells(VisibilityNotifier2D *p_notifier,const Rect2& p_rect,bool p_add) {
+ void _notifier_update_cells(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect, bool p_add) {
Point2i begin = p_rect.pos;
- begin/=cell_size;
- Point2i end = p_rect.pos+p_rect.size;
- end/=cell_size;
- for(int i=begin.x;i<=end.x;i++) {
+ begin /= cell_size;
+ Point2i end = p_rect.pos + p_rect.size;
+ end /= cell_size;
+ for (int i = begin.x; i <= end.x; i++) {
- for(int j=begin.y;j<=end.y;j++) {
+ for (int j = begin.y; j <= end.y; j++) {
CellKey ck;
- ck.x=i;
- ck.y=j;
- Map<CellKey,CellData>::Element *E=cells.find(ck);
+ ck.x = i;
+ ck.y = j;
+ Map<CellKey, CellData>::Element *E = cells.find(ck);
if (p_add) {
if (!E)
- E=cells.insert(ck,CellData());
+ E = cells.insert(ck, CellData());
E->get().notifiers[p_notifier].inc();
} else {
ERR_CONTINUE(!E);
- if (E->get().notifiers[p_notifier].dec()==0) {
+ if (E->get().notifiers[p_notifier].dec() == 0) {
E->get().notifiers.erase(p_notifier);
if (E->get().notifiers.empty()) {
@@ -135,38 +129,38 @@ struct SpatialIndexer2D {
}
}
- void _notifier_add(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) {
+ void _notifier_add(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) {
ERR_FAIL_COND(notifiers.has(p_notifier));
- notifiers[p_notifier]=p_rect;
- _notifier_update_cells(p_notifier,p_rect,true);
- changed=true;
+ notifiers[p_notifier] = p_rect;
+ _notifier_update_cells(p_notifier, p_rect, true);
+ changed = true;
}
- void _notifier_update(VisibilityNotifier2D* p_notifier,const Rect2& p_rect) {
+ void _notifier_update(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) {
- Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier);
+ Map<VisibilityNotifier2D *, Rect2>::Element *E = notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
- if (E->get()==p_rect)
+ if (E->get() == p_rect)
return;
- _notifier_update_cells(p_notifier,p_rect,true);
- _notifier_update_cells(p_notifier,E->get(),false);
- E->get()=p_rect;
- changed=true;
+ _notifier_update_cells(p_notifier, p_rect, true);
+ _notifier_update_cells(p_notifier, E->get(), false);
+ E->get() = p_rect;
+ changed = true;
}
- void _notifier_remove(VisibilityNotifier2D* p_notifier) {
+ void _notifier_remove(VisibilityNotifier2D *p_notifier) {
- Map<VisibilityNotifier2D*,Rect2>::Element *E=notifiers.find(p_notifier);
+ Map<VisibilityNotifier2D *, Rect2>::Element *E = notifiers.find(p_notifier);
ERR_FAIL_COND(!E);
- _notifier_update_cells(p_notifier,E->get(),false);
+ _notifier_update_cells(p_notifier, E->get(), false);
notifiers.erase(p_notifier);
- List<Viewport*> removed;
- for (Map<Viewport*,ViewportData>::Element*F=viewports.front();F;F=F->next()) {
+ List<Viewport *> removed;
+ for (Map<Viewport *, ViewportData>::Element *F = viewports.front(); F; F = F->next()) {
- Map<VisibilityNotifier2D*,uint64_t>::Element*G=F->get().notifiers.find(p_notifier);
+ Map<VisibilityNotifier2D *, uint64_t>::Element *G = F->get().notifiers.find(p_notifier);
if (G) {
F->get().notifiers.erase(G);
@@ -174,44 +168,43 @@ struct SpatialIndexer2D {
}
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
p_notifier->_exit_viewport(removed.front()->get());
removed.pop_front();
}
- changed=true;
+ changed = true;
}
- void _add_viewport(Viewport* p_viewport,const Rect2& p_rect) {
+ void _add_viewport(Viewport *p_viewport, const Rect2 &p_rect) {
ERR_FAIL_COND(viewports.has(p_viewport));
ViewportData vd;
- vd.rect=p_rect;
- viewports[p_viewport]=vd;
- changed=true;
-
+ vd.rect = p_rect;
+ viewports[p_viewport] = vd;
+ changed = true;
}
- void _update_viewport(Viewport* p_viewport, const Rect2& p_rect) {
+ void _update_viewport(Viewport *p_viewport, const Rect2 &p_rect) {
- Map<Viewport*,ViewportData>::Element *E= viewports.find(p_viewport);
+ Map<Viewport *, ViewportData>::Element *E = viewports.find(p_viewport);
ERR_FAIL_COND(!E);
- if (E->get().rect==p_rect)
+ if (E->get().rect == p_rect)
return;
- E->get().rect=p_rect;
- changed=true;
+ E->get().rect = p_rect;
+ changed = true;
}
- void _remove_viewport(Viewport* p_viewport) {
+ void _remove_viewport(Viewport *p_viewport) {
ERR_FAIL_COND(!viewports.has(p_viewport));
- List<VisibilityNotifier2D*> removed;
- for(Map<VisibilityNotifier2D*,uint64_t>::Element *E=viewports[p_viewport].notifiers.front();E;E=E->next()) {
+ List<VisibilityNotifier2D *> removed;
+ for (Map<VisibilityNotifier2D *, uint64_t>::Element *E = viewports[p_viewport].notifiers.front(); E; E = E->next()) {
removed.push_back(E->key());
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
removed.front()->get()->_exit_viewport(p_viewport);
removed.pop_front();
}
@@ -221,45 +214,44 @@ struct SpatialIndexer2D {
void _update() {
-
if (!changed)
return;
- for (Map<Viewport*,ViewportData>::Element *E=viewports.front();E;E=E->next()) {
+ for (Map<Viewport *, ViewportData>::Element *E = viewports.front(); E; E = E->next()) {
Point2i begin = E->get().rect.pos;
- begin/=cell_size;
- Point2i end = E->get().rect.pos+E->get().rect.size;
- end/=cell_size;
+ begin /= cell_size;
+ Point2i end = E->get().rect.pos + E->get().rect.size;
+ end /= cell_size;
pass++;
- List<VisibilityNotifier2D*> added;
- List<VisibilityNotifier2D*> removed;
+ List<VisibilityNotifier2D *> added;
+ List<VisibilityNotifier2D *> removed;
- int visible_cells=(end.x-begin.x)*(end.y-begin.y);
+ int visible_cells = (end.x - begin.x) * (end.y - begin.y);
- if (visible_cells>10000) {
+ if (visible_cells > 10000) {
//well you zoomed out a lot, it's your problem. To avoid freezing in the for loops below, we'll manually check cell by cell
- for (Map<CellKey,CellData>::Element *F=cells.front();F;F=F->next()) {
+ for (Map<CellKey, CellData>::Element *F = cells.front(); F; F = F->next()) {
- const CellKey &ck=F->key();
+ const CellKey &ck = F->key();
- if (ck.x<begin.x || ck.x>end.x)
+ if (ck.x < begin.x || ck.x > end.x)
continue;
- if (ck.y<begin.y || ck.y>end.y)
+ if (ck.y < begin.y || ck.y > end.y)
continue;
//notifiers in cell
- for (Map<VisibilityNotifier2D*,CellRef>::Element *G=F->get().notifiers.front();G;G=G->next()) {
+ for (Map<VisibilityNotifier2D *, CellRef>::Element *G = F->get().notifiers.front(); G; G = G->next()) {
- Map<VisibilityNotifier2D*,uint64_t>::Element *H=E->get().notifiers.find(G->key());
+ Map<VisibilityNotifier2D *, uint64_t>::Element *H = E->get().notifiers.find(G->key());
if (!H) {
- H=E->get().notifiers.insert(G->key(),pass);
+ H = E->get().notifiers.insert(G->key(), pass);
added.push_back(G->key());
} else {
- H->get()=pass;
+ H->get() = pass;
}
}
}
@@ -267,94 +259,87 @@ struct SpatialIndexer2D {
} else {
//check cells in grid fashion
- for(int i=begin.x;i<=end.x;i++) {
+ for (int i = begin.x; i <= end.x; i++) {
- for(int j=begin.y;j<=end.y;j++) {
+ for (int j = begin.y; j <= end.y; j++) {
CellKey ck;
- ck.x=i;
- ck.y=j;
+ ck.x = i;
+ ck.y = j;
- Map<CellKey,CellData>::Element *F=cells.find(ck);
+ Map<CellKey, CellData>::Element *F = cells.find(ck);
if (!F) {
continue;
}
-
//notifiers in cell
- for (Map<VisibilityNotifier2D*,CellRef>::Element *G=F->get().notifiers.front();G;G=G->next()) {
+ for (Map<VisibilityNotifier2D *, CellRef>::Element *G = F->get().notifiers.front(); G; G = G->next()) {
- Map<VisibilityNotifier2D*,uint64_t>::Element *H=E->get().notifiers.find(G->key());
+ Map<VisibilityNotifier2D *, uint64_t>::Element *H = E->get().notifiers.find(G->key());
if (!H) {
- H=E->get().notifiers.insert(G->key(),pass);
+ H = E->get().notifiers.insert(G->key(), pass);
added.push_back(G->key());
} else {
- H->get()=pass;
+ H->get() = pass;
}
}
}
}
}
- for (Map<VisibilityNotifier2D*,uint64_t>::Element *F=E->get().notifiers.front();F;F=F->next()) {
+ for (Map<VisibilityNotifier2D *, uint64_t>::Element *F = E->get().notifiers.front(); F; F = F->next()) {
- if (F->get()!=pass)
+ if (F->get() != pass)
removed.push_back(F->key());
}
- while(!added.empty()) {
+ while (!added.empty()) {
added.front()->get()->_enter_viewport(E->key());
added.pop_front();
}
- while(!removed.empty()) {
+ while (!removed.empty()) {
E->get().notifiers.erase(removed.front()->get());
removed.front()->get()->_exit_viewport(E->key());
removed.pop_front();
}
}
- changed=false;
+ changed = false;
}
-
SpatialIndexer2D() {
- pass=0;
- changed=false;
- cell_size=100; //should be configurable with GLOBAL_DEF("") i guess
+ pass = 0;
+ changed = false;
+ cell_size = 100; //should be configurable with GLOBAL_DEF("") i guess
}
-
};
+void World2D::_register_viewport(Viewport *p_viewport, const Rect2 &p_rect) {
-
-void World2D::_register_viewport(Viewport* p_viewport,const Rect2& p_rect) {
-
- indexer->_add_viewport(p_viewport,p_rect);
+ indexer->_add_viewport(p_viewport, p_rect);
}
-void World2D::_update_viewport(Viewport* p_viewport,const Rect2& p_rect){
-
- indexer->_update_viewport(p_viewport,p_rect);
+void World2D::_update_viewport(Viewport *p_viewport, const Rect2 &p_rect) {
+ indexer->_update_viewport(p_viewport, p_rect);
}
-void World2D::_remove_viewport(Viewport* p_viewport){
+void World2D::_remove_viewport(Viewport *p_viewport) {
indexer->_remove_viewport(p_viewport);
}
-void World2D::_register_notifier(VisibilityNotifier2D* p_notifier, const Rect2 &p_rect){
-
- indexer->_notifier_add(p_notifier,p_rect);
+void World2D::_register_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) {
+ indexer->_notifier_add(p_notifier, p_rect);
}
-void World2D::_update_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect){
+void World2D::_update_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect) {
- indexer->_notifier_update(p_notifier,p_rect);
+ indexer->_notifier_update(p_notifier, p_rect);
}
-void World2D::_remove_notifier(VisibilityNotifier2D* p_notifier){
+void World2D::_remove_notifier(VisibilityNotifier2D *p_notifier) {
indexer->_notifier_remove(p_notifier);
}
@@ -364,7 +349,6 @@ void World2D::_update() {
indexer->_update();
}
-
RID World2D::get_canvas() {
return canvas;
@@ -382,12 +366,11 @@ RID World2D::get_sound_space() {
void World2D::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_canvas"),&World2D::get_canvas);
- ClassDB::bind_method(D_METHOD("get_space"),&World2D::get_space);
- ClassDB::bind_method(D_METHOD("get_sound_space"),&World2D::get_sound_space);
-
- ClassDB::bind_method(D_METHOD("get_direct_space_state:Physics2DDirectSpaceState"),&World2D::get_direct_space_state);
+ ClassDB::bind_method(D_METHOD("get_canvas"), &World2D::get_canvas);
+ ClassDB::bind_method(D_METHOD("get_space"), &World2D::get_space);
+ ClassDB::bind_method(D_METHOD("get_sound_space"), &World2D::get_sound_space);
+ ClassDB::bind_method(D_METHOD("get_direct_space_state:Physics2DDirectSpaceState"), &World2D::get_direct_space_state);
}
Physics2DDirectSpaceState *World2D::get_direct_space_state() {
@@ -395,23 +378,20 @@ Physics2DDirectSpaceState *World2D::get_direct_space_state() {
return Physics2DServer::get_singleton()->space_get_direct_state(space);
}
-
World2D::World2D() {
canvas = VisualServer::get_singleton()->canvas_create();
space = Physics2DServer::get_singleton()->space_create();
//set space2D to be more friendly with pixels than meters, by adjusting some constants
- Physics2DServer::get_singleton()->space_set_active(space,true);
- Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY,GLOBAL_DEF("physics/2d/default_gravity",98));
- Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_GRAVITY_VECTOR,GLOBAL_DEF("physics/2d/default_gravity_vector",Vector2(0,1)));
- Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_LINEAR_DAMP,GLOBAL_DEF("physics/2d/default_linear_damp",0.1));
- Physics2DServer::get_singleton()->area_set_param(space,Physics2DServer::AREA_PARAM_ANGULAR_DAMP,GLOBAL_DEF("physics/2d/default_angular_damp",1));
- indexer = memnew( SpatialIndexer2D );
-
+ Physics2DServer::get_singleton()->space_set_active(space, true);
+ Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY, GLOBAL_DEF("physics/2d/default_gravity", 98));
+ Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_GRAVITY_VECTOR, GLOBAL_DEF("physics/2d/default_gravity_vector", Vector2(0, 1)));
+ Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_LINEAR_DAMP, GLOBAL_DEF("physics/2d/default_linear_damp", 0.1));
+ Physics2DServer::get_singleton()->area_set_param(space, Physics2DServer::AREA_PARAM_ANGULAR_DAMP, GLOBAL_DEF("physics/2d/default_angular_damp", 1));
+ indexer = memnew(SpatialIndexer2D);
}
-
World2D::~World2D() {
VisualServer::get_singleton()->free(canvas);
diff --git a/scene/resources/world_2d.h b/scene/resources/world_2d.h
index c02880e9ed..2bb5eb1526 100644
--- a/scene/resources/world_2d.h
+++ b/scene/resources/world_2d.h
@@ -29,9 +29,9 @@
#ifndef WORLD_2D_H
#define WORLD_2D_H
+#include "global_config.h"
#include "resource.h"
#include "servers/physics_2d_server.h"
-#include "global_config.h"
class SpatialIndexer2D;
class VisibilityNotifier2D;
@@ -39,32 +39,30 @@ class Viewport;
class World2D : public Resource {
- GDCLASS( World2D, Resource );
+ GDCLASS(World2D, Resource);
RID canvas;
RID space;
RID sound_space;
- SpatialIndexer2D* indexer;
-protected:
+ SpatialIndexer2D *indexer;
+protected:
static void _bind_methods();
-friend class Viewport;
-friend class VisibilityNotifier2D;
+ friend class Viewport;
+ friend class VisibilityNotifier2D;
- void _register_viewport(Viewport* p_viewport,const Rect2& p_rect);
- void _update_viewport(Viewport* p_viewport,const Rect2& p_rect);
- void _remove_viewport(Viewport* p_viewport);
+ void _register_viewport(Viewport *p_viewport, const Rect2 &p_rect);
+ void _update_viewport(Viewport *p_viewport, const Rect2 &p_rect);
+ void _remove_viewport(Viewport *p_viewport);
- void _register_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect);
- void _update_notifier(VisibilityNotifier2D* p_notifier,const Rect2& p_rect);
- void _remove_notifier(VisibilityNotifier2D* p_notifier);
+ void _register_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect);
+ void _update_notifier(VisibilityNotifier2D *p_notifier, const Rect2 &p_rect);
+ void _remove_notifier(VisibilityNotifier2D *p_notifier);
void _update();
-public:
-
-
+public:
RID get_canvas();
RID get_space();
RID get_sound_space();
diff --git a/scene/scene_string_names.cpp b/scene/scene_string_names.cpp
index d3a913680b..ae939ead5f 100644
--- a/scene/scene_string_names.cpp
+++ b/scene/scene_string_names.cpp
@@ -28,39 +28,39 @@
/*************************************************************************/
#include "scene_string_names.h"
-SceneStringNames* SceneStringNames::singleton=NULL;
+SceneStringNames *SceneStringNames::singleton = NULL;
SceneStringNames::SceneStringNames() {
- resized=StaticCString::create("resized");
- dot=StaticCString::create(".");
- doubledot=StaticCString::create("..");
- draw=StaticCString::create("draw");
- _draw=StaticCString::create("_draw");
- hide=StaticCString::create("hide");
- visibility_changed=StaticCString::create("visibility_changed");
- input_event=StaticCString::create("input_event");
- shader_shader=StaticCString::create("shader/shader");
- shader_unshaded=StaticCString::create("shader/unshaded");
- shading_mode=StaticCString::create("shader/shading_mode");
- tree_entered=StaticCString::create("tree_entered");
- tree_exited=StaticCString::create("tree_exited");
- item_rect_changed=StaticCString::create("item_rect_changed");
- size_flags_changed=StaticCString::create("size_flags_changed");
- minimum_size_changed=StaticCString::create("minimum_size_changed");
- sleeping_state_changed=StaticCString::create("sleeping_state_changed");
-
- finished=StaticCString::create("finished");
- emission_finished=StaticCString::create("emission_finished");
- animation_finished=StaticCString::create("animation_finished");
- animation_changed=StaticCString::create("animation_changed");
- animation_started=StaticCString::create("animation_started");
-
- mouse_entered=StaticCString::create("mouse_entered");
- mouse_exited=StaticCString::create("mouse_exited");
-
- focus_entered=StaticCString::create("focus_entered");
- focus_exited=StaticCString::create("focus_exited");
+ resized = StaticCString::create("resized");
+ dot = StaticCString::create(".");
+ doubledot = StaticCString::create("..");
+ draw = StaticCString::create("draw");
+ _draw = StaticCString::create("_draw");
+ hide = StaticCString::create("hide");
+ visibility_changed = StaticCString::create("visibility_changed");
+ input_event = StaticCString::create("input_event");
+ shader_shader = StaticCString::create("shader/shader");
+ shader_unshaded = StaticCString::create("shader/unshaded");
+ shading_mode = StaticCString::create("shader/shading_mode");
+ tree_entered = StaticCString::create("tree_entered");
+ tree_exited = StaticCString::create("tree_exited");
+ item_rect_changed = StaticCString::create("item_rect_changed");
+ size_flags_changed = StaticCString::create("size_flags_changed");
+ minimum_size_changed = StaticCString::create("minimum_size_changed");
+ sleeping_state_changed = StaticCString::create("sleeping_state_changed");
+
+ finished = StaticCString::create("finished");
+ emission_finished = StaticCString::create("emission_finished");
+ animation_finished = StaticCString::create("animation_finished");
+ animation_changed = StaticCString::create("animation_changed");
+ animation_started = StaticCString::create("animation_started");
+
+ mouse_entered = StaticCString::create("mouse_entered");
+ mouse_exited = StaticCString::create("mouse_exited");
+
+ focus_entered = StaticCString::create("focus_entered");
+ focus_exited = StaticCString::create("focus_exited");
sort_children = StaticCString::create("sort_children");
@@ -75,40 +75,40 @@ SceneStringNames::SceneStringNames() {
_body_inout = StaticCString::create("_body_inout");
_area_inout = StaticCString::create("_area_inout");
- idle=StaticCString::create("idle");
- iteration=StaticCString::create("iteration");
- update=StaticCString::create("update");
- updated=StaticCString::create("updated");
+ idle = StaticCString::create("idle");
+ iteration = StaticCString::create("iteration");
+ update = StaticCString::create("update");
+ updated = StaticCString::create("updated");
- _get_gizmo_geometry=StaticCString::create("_get_gizmo_geometry");
- _can_gizmo_scale=StaticCString::create("_can_gizmo_scale");
+ _get_gizmo_geometry = StaticCString::create("_get_gizmo_geometry");
+ _can_gizmo_scale = StaticCString::create("_can_gizmo_scale");
- _fixed_process=StaticCString::create("_fixed_process");
- _process=StaticCString::create("_process");
+ _fixed_process = StaticCString::create("_fixed_process");
+ _process = StaticCString::create("_process");
- _enter_tree=StaticCString::create("_enter_tree");
- _exit_tree=StaticCString::create("_exit_tree");
- _enter_world=StaticCString::create("_enter_world");
- _exit_world=StaticCString::create("_exit_world");
- _ready=StaticCString::create("_ready");
+ _enter_tree = StaticCString::create("_enter_tree");
+ _exit_tree = StaticCString::create("_exit_tree");
+ _enter_world = StaticCString::create("_enter_world");
+ _exit_world = StaticCString::create("_exit_world");
+ _ready = StaticCString::create("_ready");
- _update_scroll=StaticCString::create("_update_scroll");
- _update_xform=StaticCString::create("_update_xform");
+ _update_scroll = StaticCString::create("_update_scroll");
+ _update_xform = StaticCString::create("_update_xform");
- _proxgroup_add=StaticCString::create("_proxgroup_add");
- _proxgroup_remove=StaticCString::create("_proxgroup_remove");
+ _proxgroup_add = StaticCString::create("_proxgroup_add");
+ _proxgroup_remove = StaticCString::create("_proxgroup_remove");
- grouped=StaticCString::create("grouped");
- ungrouped=StaticCString::create("ungrouped");
+ grouped = StaticCString::create("grouped");
+ ungrouped = StaticCString::create("ungrouped");
- screen_entered=StaticCString::create("screen_entered");
- screen_exited=StaticCString::create("screen_exited");
+ screen_entered = StaticCString::create("screen_entered");
+ screen_exited = StaticCString::create("screen_exited");
- viewport_entered=StaticCString::create("viewport_entered");
- viewport_exited=StaticCString::create("viewport_exited");
+ viewport_entered = StaticCString::create("viewport_entered");
+ viewport_exited = StaticCString::create("viewport_exited");
- camera_entered=StaticCString::create("camera_entered");
- camera_exited=StaticCString::create("camera_exited");
+ camera_entered = StaticCString::create("camera_entered");
+ camera_exited = StaticCString::create("camera_exited");
_body_enter_tree = StaticCString::create("_body_enter_tree");
_body_exit_tree = StaticCString::create("_body_exit_tree");
@@ -117,38 +117,38 @@ SceneStringNames::SceneStringNames() {
_area_exit_tree = StaticCString::create("_area_exit_tree");
_input = StaticCString::create("_input");
- _input_event=StaticCString::create("_input_event");
+ _input_event = StaticCString::create("_input_event");
- gui_input=StaticCString::create("gui_input");
- _gui_input=StaticCString::create("_gui_input");
+ gui_input = StaticCString::create("gui_input");
+ _gui_input = StaticCString::create("_gui_input");
- _unhandled_input=StaticCString::create("_unhandled_input");
- _unhandled_key_input=StaticCString::create("_unhandled_key_input");
+ _unhandled_input = StaticCString::create("_unhandled_input");
+ _unhandled_key_input = StaticCString::create("_unhandled_key_input");
- changed=StaticCString::create("changed");
- _shader_changed=StaticCString::create("_shader_changed");
+ changed = StaticCString::create("changed");
+ _shader_changed = StaticCString::create("_shader_changed");
- _spatial_editor_group=StaticCString::create("_spatial_editor_group");
- _request_gizmo=StaticCString::create("_request_gizmo");
+ _spatial_editor_group = StaticCString::create("_spatial_editor_group");
+ _request_gizmo = StaticCString::create("_request_gizmo");
- offset=StaticCString::create("offset");
- unit_offset=StaticCString::create("unit_offset");
- rotation_mode=StaticCString::create("rotation_mode");
- rotate=StaticCString::create("rotate");
- h_offset=StaticCString::create("h_offset");
- v_offset=StaticCString::create("v_offset");
+ offset = StaticCString::create("offset");
+ unit_offset = StaticCString::create("unit_offset");
+ rotation_mode = StaticCString::create("rotation_mode");
+ rotate = StaticCString::create("rotate");
+ h_offset = StaticCString::create("h_offset");
+ v_offset = StaticCString::create("v_offset");
- transform_pos=StaticCString::create("transform/pos");
- transform_rot=StaticCString::create("transform/rot");
- transform_scale=StaticCString::create("transform/scale");
+ transform_pos = StaticCString::create("transform/pos");
+ transform_rot = StaticCString::create("transform/rot");
+ transform_scale = StaticCString::create("transform/scale");
- _update_remote=StaticCString::create("_update_remote");
- _update_pairs=StaticCString::create("_update_pairs");
+ _update_remote = StaticCString::create("_update_remote");
+ _update_pairs = StaticCString::create("_update_pairs");
- get_minimum_size=StaticCString::create("get_minimum_size");
+ get_minimum_size = StaticCString::create("get_minimum_size");
- area_entered=StaticCString::create("area_entered");
- area_exited=StaticCString::create("area_exited");
+ area_entered = StaticCString::create("area_entered");
+ area_exited = StaticCString::create("area_exited");
has_point = StaticCString::create("has_point");
@@ -166,30 +166,30 @@ SceneStringNames::SceneStringNames() {
baked_light_changed = StaticCString::create("baked_light_changed");
_baked_light_changed = StaticCString::create("_baked_light_changed");
- _mouse_enter=StaticCString::create("_mouse_enter");
- _mouse_exit=StaticCString::create("_mouse_exit");
+ _mouse_enter = StaticCString::create("_mouse_enter");
+ _mouse_exit = StaticCString::create("_mouse_exit");
- _pressed=StaticCString::create("_pressed");
- _toggled=StaticCString::create("_toggled");
+ _pressed = StaticCString::create("_pressed");
+ _toggled = StaticCString::create("_toggled");
- frame_changed=StaticCString::create("frame_changed");
+ frame_changed = StaticCString::create("frame_changed");
- playback_speed=StaticCString::create("playback/speed");
- playback_active=StaticCString::create("playback/active");
- autoplay=StaticCString::create("autoplay");
- blend_times=StaticCString::create("blend_times");
- speed=StaticCString::create("speed");
+ playback_speed = StaticCString::create("playback/speed");
+ playback_active = StaticCString::create("playback/active");
+ autoplay = StaticCString::create("autoplay");
+ blend_times = StaticCString::create("blend_times");
+ speed = StaticCString::create("speed");
node_configuration_warning_changed = StaticCString::create("node_configuration_warning_changed");
- path_pp=NodePath("..");
+ path_pp = NodePath("..");
- _default=StaticCString::create("default");
+ _default = StaticCString::create("default");
- for(int i=0;i<MAX_MATERIALS;i++) {
+ for (int i = 0; i < MAX_MATERIALS; i++) {
- mesh_materials[i]="material/"+itos(i);
+ mesh_materials[i] = "material/" + itos(i);
}
- _mesh_changed=StaticCString::create("_mesh_changed");
+ _mesh_changed = StaticCString::create("_mesh_changed");
}
diff --git a/scene/scene_string_names.h b/scene/scene_string_names.h
index 624a9147d5..e16e1e04e6 100644
--- a/scene/scene_string_names.h
+++ b/scene/scene_string_names.h
@@ -29,22 +29,25 @@
#ifndef SCENE_STRING_NAMES_H
#define SCENE_STRING_NAMES_H
-#include "string_db.h"
#include "path_db.h"
+#include "string_db.h"
class SceneStringNames {
-friend void register_scene_types();
-friend void unregister_scene_types();
+ friend void register_scene_types();
+ friend void unregister_scene_types();
- static SceneStringNames* singleton;
+ static SceneStringNames *singleton;
static void create() { singleton = memnew(SceneStringNames); }
- static void free() { memdelete( singleton); singleton=NULL; }
+ static void free() {
+ memdelete(singleton);
+ singleton = NULL;
+ }
SceneStringNames();
-public:
- _FORCE_INLINE_ static SceneStringNames* get_singleton() { return singleton; }
+public:
+ _FORCE_INLINE_ static SceneStringNames *get_singleton() { return singleton; }
StringName resized;
StringName dot;
@@ -96,7 +99,6 @@ public:
StringName _body_inout;
StringName _area_inout;
-
StringName _get_gizmo_geometry;
StringName _can_gizmo_scale;
@@ -193,12 +195,10 @@ public:
StringName node_configuration_warning_changed;
enum {
- MAX_MATERIALS=32
+ MAX_MATERIALS = 32
};
StringName mesh_materials[MAX_MATERIALS];
StringName _mesh_changed;
-
};
-
#endif // SCENE_STRING_NAMES_H
diff --git a/servers/audio/audio_driver_dummy.cpp b/servers/audio/audio_driver_dummy.cpp
index 6c12957851..e3022225a3 100644
--- a/servers/audio/audio_driver_dummy.cpp
+++ b/servers/audio/audio_driver_dummy.cpp
@@ -31,42 +31,37 @@
#include "global_config.h"
#include "os/os.h"
-
-
Error AudioDriverDummy::init() {
- active=false;
- thread_exited=false;
- exit_thread=false;
+ active = false;
+ thread_exited = false;
+ exit_thread = false;
pcm_open = false;
samples_in = NULL;
-
mix_rate = 44100;
speaker_mode = SPEAKER_MODE_STEREO;
channels = 2;
- int latency = GLOBAL_DEF("audio/output_latency",25);
- buffer_size = nearest_power_of_2( latency * mix_rate / 1000 );
+ int latency = GLOBAL_DEF("audio/output_latency", 25);
+ buffer_size = nearest_power_of_2(latency * mix_rate / 1000);
- samples_in = memnew_arr(int32_t, buffer_size*channels);
+ samples_in = memnew_arr(int32_t, buffer_size * channels);
- mutex=Mutex::create();
+ mutex = Mutex::create();
thread = Thread::create(AudioDriverDummy::thread_func, this);
return OK;
};
-void AudioDriverDummy::thread_func(void* p_udata) {
+void AudioDriverDummy::thread_func(void *p_udata) {
- AudioDriverDummy* ad = (AudioDriverDummy*)p_udata;
-
- uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate))*1000000;
+ AudioDriverDummy *ad = (AudioDriverDummy *)p_udata;
+ uint64_t usdelay = (ad->buffer_size / float(ad->mix_rate)) * 1000000;
while (!ad->exit_thread) {
-
if (!ad->active) {
} else {
@@ -76,15 +71,12 @@ void AudioDriverDummy::thread_func(void* p_udata) {
ad->audio_server_process(ad->buffer_size, ad->samples_in);
ad->unlock();
-
};
OS::get_singleton()->delay_usec(usdelay);
-
};
- ad->thread_exited=true;
-
+ ad->thread_exited = true;
};
void AudioDriverDummy::start() {
@@ -137,12 +129,9 @@ void AudioDriverDummy::finish() {
AudioDriverDummy::AudioDriverDummy() {
mutex = NULL;
- thread=NULL;
-
+ thread = NULL;
};
-AudioDriverDummy::~AudioDriverDummy() {
+AudioDriverDummy::~AudioDriverDummy(){
};
-
-
diff --git a/servers/audio/audio_driver_dummy.h b/servers/audio/audio_driver_dummy.h
index 78ec41ea09..02f6a5407c 100644
--- a/servers/audio/audio_driver_dummy.h
+++ b/servers/audio/audio_driver_dummy.h
@@ -31,18 +31,17 @@
#include "servers/audio_server.h"
-#include "core/os/thread.h"
#include "core/os/mutex.h"
-
+#include "core/os/thread.h"
class AudioDriverDummy : public AudioDriver {
- Thread* thread;
- Mutex* mutex;
+ Thread *thread;
+ Mutex *mutex;
- int32_t* samples_in;
+ int32_t *samples_in;
- static void thread_func(void* p_udata);
+ static void thread_func(void *p_udata);
int buffer_size;
unsigned int mix_rate;
@@ -56,8 +55,7 @@ class AudioDriverDummy : public AudioDriver {
bool pcm_open;
public:
-
- const char* get_name() const {
+ const char *get_name() const {
return "Dummy";
};
diff --git a/servers/audio/audio_effect.cpp b/servers/audio/audio_effect.cpp
index b0844ff924..bb1179134c 100644
--- a/servers/audio/audio_effect.cpp
+++ b/servers/audio/audio_effect.cpp
@@ -28,7 +28,5 @@
/*************************************************************************/
#include "audio_effect.h"
-AudioEffect::AudioEffect()
-{
-
+AudioEffect::AudioEffect() {
}
diff --git a/servers/audio/audio_effect.h b/servers/audio/audio_effect.h
index db3ec91195..6981cf0db7 100644
--- a/servers/audio/audio_effect.h
+++ b/servers/audio/audio_effect.h
@@ -32,22 +32,17 @@
#include "audio_frame.h"
#include "resource.h"
-
class AudioEffectInstance : public Reference {
- GDCLASS(AudioEffectInstance,Reference)
+ GDCLASS(AudioEffectInstance, Reference)
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count)=0;
-
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) = 0;
};
-
class AudioEffect : public Resource {
- GDCLASS(AudioEffect,Resource)
+ GDCLASS(AudioEffect, Resource)
public:
-
- virtual Ref<AudioEffectInstance> instance()=0;
+ virtual Ref<AudioEffectInstance> instance() = 0;
AudioEffect();
};
diff --git a/servers/audio/audio_filter_sw.cpp b/servers/audio/audio_filter_sw.cpp
index e97eb75d04..b3ed76f22c 100644
--- a/servers/audio/audio_filter_sw.cpp
+++ b/servers/audio/audio_filter_sw.cpp
@@ -34,62 +34,57 @@ void AudioFilterSW::set_mode(Mode p_mode) {
}
void AudioFilterSW::set_cutoff(float p_cutoff) {
- cutoff=p_cutoff;
+ cutoff = p_cutoff;
}
void AudioFilterSW::set_resonance(float p_resonance) {
- resonance=p_resonance;
+ resonance = p_resonance;
}
void AudioFilterSW::set_gain(float p_gain) {
- gain=p_gain;
+ gain = p_gain;
}
void AudioFilterSW::set_sampling_rate(float p_srate) {
- sampling_rate=p_srate;
+ sampling_rate = p_srate;
}
-
void AudioFilterSW::prepare_coefficients(Coeffs *p_coeffs) {
- int sr_limit = (sampling_rate/2)+512;
-
-
- double final_cutoff=(cutoff>sr_limit)?sr_limit:cutoff;
- if (final_cutoff<1) //avoid crapness
- final_cutoff=1; //dont allow less than this
+ int sr_limit = (sampling_rate / 2) + 512;
+ double final_cutoff = (cutoff > sr_limit) ? sr_limit : cutoff;
+ if (final_cutoff < 1) //avoid crapness
+ final_cutoff = 1; //dont allow less than this
+ double omega = 2.0 * Math_PI * final_cutoff / sampling_rate;
- double omega=2.0*Math_PI*final_cutoff/sampling_rate;
+ double sin_v = Math::sin(omega);
+ double cos_v = Math::cos(omega);
- double sin_v=Math::sin(omega);
- double cos_v=Math::cos(omega);
-
- double Q=resonance;
- if (Q<=0.0) {
- Q=0.0001;
+ double Q = resonance;
+ if (Q <= 0.0) {
+ Q = 0.0001;
}
+ if (mode == BANDPASS)
+ Q *= 2.0;
+ else if (mode == PEAK)
+ Q *= 3.0;
- if (mode==BANDPASS)
- Q*=2.0;
- else if (mode==PEAK)
- Q*=3.0;
-
- double tmpgain=gain;
+ double tmpgain = gain;
- if (tmpgain<0.001)
- tmpgain=0.001;
+ if (tmpgain < 0.001)
+ tmpgain = 0.001;
- if (stages>1) {
+ if (stages > 1) {
- Q=(Q>1.0 ? Math::pow(Q,1.0/stages) : Q);
- tmpgain = Math::pow(tmpgain,1.0/(stages+1));
+ Q = (Q > 1.0 ? Math::pow(Q, 1.0 / stages) : Q);
+ tmpgain = Math::pow(tmpgain, 1.0 / (stages + 1));
}
- double alpha = sin_v/(2*Q);
+ double alpha = sin_v / (2 * Q);
double a0 = 1.0 + alpha;
@@ -97,169 +92,159 @@ void AudioFilterSW::prepare_coefficients(Coeffs *p_coeffs) {
case LOWPASS: {
- p_coeffs->b0= (1.0 - cos_v)/2.0 ;
- p_coeffs->b1= 1.0 - cos_v ;
- p_coeffs->b2= (1.0 - cos_v)/2.0 ;
- p_coeffs->a1= -2.0*cos_v;
- p_coeffs->a2= 1.0 - alpha ;
+ p_coeffs->b0 = (1.0 - cos_v) / 2.0;
+ p_coeffs->b1 = 1.0 - cos_v;
+ p_coeffs->b2 = (1.0 - cos_v) / 2.0;
+ p_coeffs->a1 = -2.0 * cos_v;
+ p_coeffs->a2 = 1.0 - alpha;
} break;
-
case HIGHPASS: {
- p_coeffs->b0 = (1.0 + cos_v)/2.0;
+ p_coeffs->b0 = (1.0 + cos_v) / 2.0;
p_coeffs->b1 = -(1.0 + cos_v);
- p_coeffs->b2 = (1.0 + cos_v)/2.0;
- p_coeffs->a1 = -2.0*cos_v;
- p_coeffs->a2 = 1.0 - alpha;
+ p_coeffs->b2 = (1.0 + cos_v) / 2.0;
+ p_coeffs->a1 = -2.0 * cos_v;
+ p_coeffs->a2 = 1.0 - alpha;
} break;
case BANDPASS: {
- p_coeffs->b0 = alpha*sqrt(Q+1);
- p_coeffs->b1 = 0.0 ;
- p_coeffs->b2 = -alpha*sqrt(Q+1);
- p_coeffs->a1 = -2.0*cos_v;
- p_coeffs->a2 = 1.0 - alpha;
+ p_coeffs->b0 = alpha * sqrt(Q + 1);
+ p_coeffs->b1 = 0.0;
+ p_coeffs->b2 = -alpha * sqrt(Q + 1);
+ p_coeffs->a1 = -2.0 * cos_v;
+ p_coeffs->a2 = 1.0 - alpha;
} break;
case NOTCH: {
- p_coeffs->b0 = 1.0;
- p_coeffs->b1 = -2.0*cos_v;
- p_coeffs->b2 = 1.0;
- p_coeffs->a1 = -2.0*cos_v;
- p_coeffs->a2 = 1.0 - alpha;
+ p_coeffs->b0 = 1.0;
+ p_coeffs->b1 = -2.0 * cos_v;
+ p_coeffs->b2 = 1.0;
+ p_coeffs->a1 = -2.0 * cos_v;
+ p_coeffs->a2 = 1.0 - alpha;
} break;
case PEAK: {
- p_coeffs->b0 = (1.0+alpha*tmpgain);
- p_coeffs->b1 = (-2.0*cos_v);
- p_coeffs->b2 = (1.0-alpha*tmpgain);
- p_coeffs->a1 = -2*cos_v;
- p_coeffs->a2 = (1-alpha/tmpgain);
+ p_coeffs->b0 = (1.0 + alpha * tmpgain);
+ p_coeffs->b1 = (-2.0 * cos_v);
+ p_coeffs->b2 = (1.0 - alpha * tmpgain);
+ p_coeffs->a1 = -2 * cos_v;
+ p_coeffs->a2 = (1 - alpha / tmpgain);
} break;
case BANDLIMIT: {
//this one is extra tricky
- double hicutoff=resonance;
- double centercutoff = (cutoff+resonance)/2.0;
- double bandwidth=(Math::log(centercutoff)-Math::log(hicutoff))/Math::log((double)2);
- omega=2.0*Math_PI*centercutoff/sampling_rate;
- alpha = Math::sin(omega)*Math::sinh( Math::log((double)2)/2 * bandwidth * omega/Math::sin(omega) );
- a0=1+alpha;
-
- p_coeffs->b0 = alpha;
- p_coeffs->b1 = 0;
- p_coeffs->b2 = -alpha;
- p_coeffs->a1 = -2*Math::cos(omega);
- p_coeffs->a2 = 1-alpha;
+ double hicutoff = resonance;
+ double centercutoff = (cutoff + resonance) / 2.0;
+ double bandwidth = (Math::log(centercutoff) - Math::log(hicutoff)) / Math::log((double)2);
+ omega = 2.0 * Math_PI * centercutoff / sampling_rate;
+ alpha = Math::sin(omega) * Math::sinh(Math::log((double)2) / 2 * bandwidth * omega / Math::sin(omega));
+ a0 = 1 + alpha;
+
+ p_coeffs->b0 = alpha;
+ p_coeffs->b1 = 0;
+ p_coeffs->b2 = -alpha;
+ p_coeffs->a1 = -2 * Math::cos(omega);
+ p_coeffs->a2 = 1 - alpha;
} break;
case LOWSHELF: {
- double tmpq = Math::sqrt(Q);
- if (tmpq<=0)
- tmpq=0.001;
+ double tmpq = Math::sqrt(Q);
+ if (tmpq <= 0)
+ tmpq = 0.001;
alpha = sin_v / (2 * tmpq);
- double beta = Math::sqrt(tmpgain) / tmpq;
+ double beta = Math::sqrt(tmpgain) / tmpq;
- a0=(tmpgain+1.0)+(tmpgain-1.0)*cos_v+beta*sin_v;
- p_coeffs->b0=tmpgain*((tmpgain+1.0)-(tmpgain-1.0)*cos_v+beta*sin_v);
- p_coeffs->b1=2.0*tmpgain*((tmpgain-1.0)-(tmpgain+1.0)*cos_v);
- p_coeffs->b2=tmpgain*((tmpgain+1.0)-(tmpgain-1.0)*cos_v-beta*sin_v);
- p_coeffs->a1=-2.0*((tmpgain-1.0)+(tmpgain+1.0)*cos_v);
- p_coeffs->a2=((tmpgain+1.0)+(tmpgain-1.0)*cos_v-beta*sin_v);
+ a0 = (tmpgain + 1.0) + (tmpgain - 1.0) * cos_v + beta * sin_v;
+ p_coeffs->b0 = tmpgain * ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v + beta * sin_v);
+ p_coeffs->b1 = 2.0 * tmpgain * ((tmpgain - 1.0) - (tmpgain + 1.0) * cos_v);
+ p_coeffs->b2 = tmpgain * ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v - beta * sin_v);
+ p_coeffs->a1 = -2.0 * ((tmpgain - 1.0) + (tmpgain + 1.0) * cos_v);
+ p_coeffs->a2 = ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v - beta * sin_v);
} break;
case HIGHSHELF: {
- double tmpq= Math::sqrt(Q);
- if (tmpq<=0)
- tmpq=0.001;
+ double tmpq = Math::sqrt(Q);
+ if (tmpq <= 0)
+ tmpq = 0.001;
alpha = sin_v / (2 * tmpq);
- double beta = Math::sqrt(tmpgain) / tmpq;
-
- a0=(tmpgain+1.0)-(tmpgain-1.0)*cos_v+beta*sin_v;
- p_coeffs->b0=tmpgain*((tmpgain+1.0)+(tmpgain-1.0)*cos_v+beta*sin_v);
- p_coeffs->b1=-2.0*tmpgain*((tmpgain-1.0)+(tmpgain+1.0)*cos_v);
- p_coeffs->b2=tmpgain*((tmpgain+1.0)+(tmpgain-1.0)*cos_v-beta*sin_v);
- p_coeffs->a1=2.0*((tmpgain-1.0)-(tmpgain+1.0)*cos_v);
- p_coeffs->a2=((tmpgain+1.0)-(tmpgain-1.0)*cos_v-beta*sin_v);
+ double beta = Math::sqrt(tmpgain) / tmpq;
+ a0 = (tmpgain + 1.0) - (tmpgain - 1.0) * cos_v + beta * sin_v;
+ p_coeffs->b0 = tmpgain * ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v + beta * sin_v);
+ p_coeffs->b1 = -2.0 * tmpgain * ((tmpgain - 1.0) + (tmpgain + 1.0) * cos_v);
+ p_coeffs->b2 = tmpgain * ((tmpgain + 1.0) + (tmpgain - 1.0) * cos_v - beta * sin_v);
+ p_coeffs->a1 = 2.0 * ((tmpgain - 1.0) - (tmpgain + 1.0) * cos_v);
+ p_coeffs->a2 = ((tmpgain + 1.0) - (tmpgain - 1.0) * cos_v - beta * sin_v);
} break;
+ };
- };
+ p_coeffs->b0 /= a0;
+ p_coeffs->b1 /= a0;
+ p_coeffs->b2 /= a0;
+ p_coeffs->a1 /= 0.0 - a0;
+ p_coeffs->a2 /= 0.0 - a0;
- p_coeffs->b0/=a0;
- p_coeffs->b1/=a0;
- p_coeffs->b2/=a0;
- p_coeffs->a1/=0.0-a0;
- p_coeffs->a2/=0.0-a0;
-
- //undenormalise
-/* p_coeffs->b0=undenormalise(p_coeffs->b0);
+ //undenormalise
+ /* p_coeffs->b0=undenormalise(p_coeffs->b0);
p_coeffs->b1=undenormalise(p_coeffs->b1);
p_coeffs->b2=undenormalise(p_coeffs->b2);
p_coeffs->a1=undenormalise(p_coeffs->a1);
p_coeffs->a2=undenormalise(p_coeffs->a2);*/
-
}
void AudioFilterSW::set_stages(int p_stages) { //adjust for multiple stages
- stages=p_stages;
+ stages = p_stages;
}
/* Fouriertransform kernel to obtain response */
-float AudioFilterSW::get_response(float p_freq,Coeffs *p_coeffs) {
+float AudioFilterSW::get_response(float p_freq, Coeffs *p_coeffs) {
- float freq=p_freq / sampling_rate * Math_PI * 2.0f;
+ float freq = p_freq / sampling_rate * Math_PI * 2.0f;
- float cx=p_coeffs->b0,cy=0.0;
+ float cx = p_coeffs->b0, cy = 0.0;
cx += cos(freq) * p_coeffs->b1;
cy -= sin(freq) * p_coeffs->b1;
- cx += cos(2*freq) * p_coeffs->b2;
- cy -= sin(2*freq) * p_coeffs->b2;
-
-
- float H=cx*cx+cy*cy;
- cx=1.0;
- cy=0.0;
+ cx += cos(2 * freq) * p_coeffs->b2;
+ cy -= sin(2 * freq) * p_coeffs->b2;
+ float H = cx * cx + cy * cy;
+ cx = 1.0;
+ cy = 0.0;
cx -= cos(freq) * p_coeffs->a1;
cy += sin(freq) * p_coeffs->a1;
- cx -= cos(2*freq) * p_coeffs->a2;
- cy += sin(2*freq) * p_coeffs->a2;
-
+ cx -= cos(2 * freq) * p_coeffs->a2;
+ cy += sin(2 * freq) * p_coeffs->a2;
- H=H/(cx*cx+cy*cy);
+ H = H / (cx * cx + cy * cy);
return H;
}
-
AudioFilterSW::AudioFilterSW() {
-
- sampling_rate=44100;
- resonance=0.5;
- cutoff=5000;
- gain=1.0;
- mode=LOWPASS;
- stages=1;
+ sampling_rate = 44100;
+ resonance = 0.5;
+ cutoff = 5000;
+ gain = 1.0;
+ mode = LOWPASS;
+ stages = 1;
}
AudioFilterSW::Processor::Processor() {
set_filter(NULL);
-
}
-void AudioFilterSW::Processor::set_filter(AudioFilterSW * p_filter) {
+void AudioFilterSW::Processor::set_filter(AudioFilterSW *p_filter) {
- ha1=ha2=hb1=hb2=0;
- filter=p_filter;
+ ha1 = ha2 = hb1 = hb2 = 0;
+ filter = p_filter;
}
void AudioFilterSW::Processor::update_coeffs() {
@@ -268,19 +253,16 @@ void AudioFilterSW::Processor::update_coeffs() {
return;
filter->prepare_coefficients(&coeffs);
-
}
-void AudioFilterSW::Processor::process(float *p_samples,int p_amount, int p_stride) {
+void AudioFilterSW::Processor::process(float *p_samples, int p_amount, int p_stride) {
if (!filter)
return;
- for (int i=0;i<p_amount;i++) {
+ for (int i = 0; i < p_amount; i++) {
process_one(*p_samples);
- p_samples+=p_stride;
+ p_samples += p_stride;
}
-
-
}
diff --git a/servers/audio/audio_filter_sw.h b/servers/audio/audio_filter_sw.h
index b711944ca8..bbd006e525 100644
--- a/servers/audio/audio_filter_sw.h
+++ b/servers/audio/audio_filter_sw.h
@@ -29,19 +29,17 @@
#ifndef AUDIO_FILTER_SW_H
#define AUDIO_FILTER_SW_H
-
#include "math_funcs.h"
class AudioFilterSW {
public:
-
struct Coeffs {
- float a1,a2;
- float b0,b1,b2;
+ float a1, a2;
+ float b0, b1, b2;
//bool operator==(const Coeffs &p_rv) { return (FLOATS_EQ(a1,p_rv.a1) && FLOATS_EQ(a2,p_rv.a2) && FLOATS_EQ(b1,p_rv.b1) && FLOATS_EQ(b2,p_rv.b2) && FLOATS_EQ(b0,p_rv.b0) ); }
- Coeffs() { a1=a2=b0=b1=b2=0.0; }
+ Coeffs() { a1 = a2 = b0 = b1 = b2 = 0.0; }
};
enum Mode {
@@ -58,21 +56,19 @@ public:
class Processor { // simple filter processor
- AudioFilterSW * filter;
+ AudioFilterSW *filter;
Coeffs coeffs;
- float ha1,ha2,hb1,hb2; //history
+ float ha1, ha2, hb1, hb2; //history
public:
- void set_filter(AudioFilterSW * p_filter);
- void process(float *p_samples,int p_amount, int p_stride=1);
+ void set_filter(AudioFilterSW *p_filter);
+ void process(float *p_samples, int p_amount, int p_stride = 1);
void update_coeffs();
- _ALWAYS_INLINE_ void process_one(float& p_sample);
+ _ALWAYS_INLINE_ void process_one(float &p_sample);
Processor();
};
private:
-
-
float cutoff;
float resonance;
float gain;
@@ -80,11 +76,8 @@ private:
int stages;
Mode mode;
-
-
public:
-
- float get_response(float p_freq,Coeffs *p_coeffs);
+ float get_response(float p_freq, Coeffs *p_coeffs);
void set_mode(Mode p_mode);
void set_cutoff(float p_cutoff);
@@ -96,24 +89,18 @@ public:
void prepare_coefficients(Coeffs *p_coeffs);
AudioFilterSW();
-
};
-
-
-
/* inline methods */
-
void AudioFilterSW::Processor::process_one(float &p_val) {
- float pre=p_val;
- p_val = (p_val * coeffs.b0 + hb1 * coeffs.b1 + hb2 * coeffs.b2 + ha1 * coeffs.a1 + ha2 * coeffs.a2);
- ha2=ha1;
- hb2=hb1;
- hb1=pre;
- ha1=p_val;
+ float pre = p_val;
+ p_val = (p_val * coeffs.b0 + hb1 * coeffs.b1 + hb2 * coeffs.b2 + ha1 * coeffs.a1 + ha2 * coeffs.a2);
+ ha2 = ha1;
+ hb2 = hb1;
+ hb1 = pre;
+ ha1 = p_val;
}
-
#endif // AUDIO_FILTER_SW_H
diff --git a/servers/audio/audio_rb_resampler.cpp b/servers/audio/audio_rb_resampler.cpp
index 28f0007b5b..bf10f813a2 100644
--- a/servers/audio/audio_rb_resampler.cpp
+++ b/servers/audio/audio_rb_resampler.cpp
@@ -28,7 +28,6 @@
/*************************************************************************/
#include "audio_rb_resampler.h"
-
int AudioRBResampler::get_channel_count() const {
if (!rb)
@@ -37,153 +36,142 @@ int AudioRBResampler::get_channel_count() const {
return channels;
}
+template <int C>
+uint32_t AudioRBResampler::_resample(int32_t *p_dest, int p_todo, int32_t p_increment) {
-template<int C>
-uint32_t AudioRBResampler::_resample(int32_t *p_dest,int p_todo,int32_t p_increment) {
-
- uint32_t read=offset&MIX_FRAC_MASK;
+ uint32_t read = offset & MIX_FRAC_MASK;
- for (int i=0;i<p_todo;i++) {
+ for (int i = 0; i < p_todo; i++) {
- offset = (offset + p_increment)&(((1<<(rb_bits+MIX_FRAC_BITS))-1));
- read+=p_increment;
+ offset = (offset + p_increment) & (((1 << (rb_bits + MIX_FRAC_BITS)) - 1));
+ read += p_increment;
uint32_t pos = offset >> MIX_FRAC_BITS;
uint32_t frac = offset & MIX_FRAC_MASK;
#ifndef FAST_AUDIO
- ERR_FAIL_COND_V(pos>=rb_len,0);
+ ERR_FAIL_COND_V(pos >= rb_len, 0);
#endif
- uint32_t pos_next = (pos+1)&rb_mask;
+ uint32_t pos_next = (pos + 1) & rb_mask;
//printf("rb pos %i\n",pos);
// since this is a template with a known compile time value (C), conditionals go away when compiling.
- if (C==1) {
+ if (C == 1) {
int32_t v0 = rb[pos];
- int32_t v0n=rb[pos_next];
+ int32_t v0n = rb[pos_next];
#ifndef FAST_AUDIO
- v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS;
+ v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS;
#endif
- v0<<=16;
- p_dest[i]=v0;
-
+ v0 <<= 16;
+ p_dest[i] = v0;
}
- if (C==2) {
+ if (C == 2) {
- int32_t v0 = rb[(pos<<1)+0];
- int32_t v1 = rb[(pos<<1)+1];
- int32_t v0n=rb[(pos_next<<1)+0];
- int32_t v1n=rb[(pos_next<<1)+1];
+ int32_t v0 = rb[(pos << 1) + 0];
+ int32_t v1 = rb[(pos << 1) + 1];
+ int32_t v0n = rb[(pos_next << 1) + 0];
+ int32_t v1n = rb[(pos_next << 1) + 1];
#ifndef FAST_AUDIO
- v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS;
- v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS;
+ v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS;
+ v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS;
#endif
- v0<<=16;
- v1<<=16;
- p_dest[(i<<1)+0]=v0;
- p_dest[(i<<1)+1]=v1;
-
+ v0 <<= 16;
+ v1 <<= 16;
+ p_dest[(i << 1) + 0] = v0;
+ p_dest[(i << 1) + 1] = v1;
}
- if (C==4) {
+ if (C == 4) {
- int32_t v0 = rb[(pos<<2)+0];
- int32_t v1 = rb[(pos<<2)+1];
- int32_t v2 = rb[(pos<<2)+2];
- int32_t v3 = rb[(pos<<2)+3];
- int32_t v0n = rb[(pos_next<<2)+0];
- int32_t v1n=rb[(pos_next<<2)+1];
- int32_t v2n=rb[(pos_next<<2)+2];
- int32_t v3n=rb[(pos_next<<2)+3];
+ int32_t v0 = rb[(pos << 2) + 0];
+ int32_t v1 = rb[(pos << 2) + 1];
+ int32_t v2 = rb[(pos << 2) + 2];
+ int32_t v3 = rb[(pos << 2) + 3];
+ int32_t v0n = rb[(pos_next << 2) + 0];
+ int32_t v1n = rb[(pos_next << 2) + 1];
+ int32_t v2n = rb[(pos_next << 2) + 2];
+ int32_t v3n = rb[(pos_next << 2) + 3];
#ifndef FAST_AUDIO
- v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS;
- v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS;
- v2+=(v2n-v2)*(int32_t)frac >> MIX_FRAC_BITS;
- v3+=(v3n-v3)*(int32_t)frac >> MIX_FRAC_BITS;
+ v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS;
+ v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS;
+ v2 += (v2n - v2) * (int32_t)frac >> MIX_FRAC_BITS;
+ v3 += (v3n - v3) * (int32_t)frac >> MIX_FRAC_BITS;
#endif
- v0<<=16;
- v1<<=16;
- v2<<=16;
- v3<<=16;
- p_dest[(i<<2)+0]=v0;
- p_dest[(i<<2)+1]=v1;
- p_dest[(i<<2)+2]=v2;
- p_dest[(i<<2)+3]=v3;
-
+ v0 <<= 16;
+ v1 <<= 16;
+ v2 <<= 16;
+ v3 <<= 16;
+ p_dest[(i << 2) + 0] = v0;
+ p_dest[(i << 2) + 1] = v1;
+ p_dest[(i << 2) + 2] = v2;
+ p_dest[(i << 2) + 3] = v3;
}
- if (C==6) {
-
- int32_t v0 = rb[(pos*6)+0];
- int32_t v1 = rb[(pos*6)+1];
- int32_t v2 = rb[(pos*6)+2];
- int32_t v3 = rb[(pos*6)+3];
- int32_t v4 = rb[(pos*6)+4];
- int32_t v5 = rb[(pos*6)+5];
- int32_t v0n = rb[(pos_next*6)+0];
- int32_t v1n=rb[(pos_next*6)+1];
- int32_t v2n=rb[(pos_next*6)+2];
- int32_t v3n=rb[(pos_next*6)+3];
- int32_t v4n=rb[(pos_next*6)+4];
- int32_t v5n=rb[(pos_next*6)+5];
+ if (C == 6) {
+
+ int32_t v0 = rb[(pos * 6) + 0];
+ int32_t v1 = rb[(pos * 6) + 1];
+ int32_t v2 = rb[(pos * 6) + 2];
+ int32_t v3 = rb[(pos * 6) + 3];
+ int32_t v4 = rb[(pos * 6) + 4];
+ int32_t v5 = rb[(pos * 6) + 5];
+ int32_t v0n = rb[(pos_next * 6) + 0];
+ int32_t v1n = rb[(pos_next * 6) + 1];
+ int32_t v2n = rb[(pos_next * 6) + 2];
+ int32_t v3n = rb[(pos_next * 6) + 3];
+ int32_t v4n = rb[(pos_next * 6) + 4];
+ int32_t v5n = rb[(pos_next * 6) + 5];
#ifndef FAST_AUDIO
- v0+=(v0n-v0)*(int32_t)frac >> MIX_FRAC_BITS;
- v1+=(v1n-v1)*(int32_t)frac >> MIX_FRAC_BITS;
- v2+=(v2n-v2)*(int32_t)frac >> MIX_FRAC_BITS;
- v3+=(v3n-v3)*(int32_t)frac >> MIX_FRAC_BITS;
- v4+=(v4n-v4)*(int32_t)frac >> MIX_FRAC_BITS;
- v5+=(v5n-v5)*(int32_t)frac >> MIX_FRAC_BITS;
+ v0 += (v0n - v0) * (int32_t)frac >> MIX_FRAC_BITS;
+ v1 += (v1n - v1) * (int32_t)frac >> MIX_FRAC_BITS;
+ v2 += (v2n - v2) * (int32_t)frac >> MIX_FRAC_BITS;
+ v3 += (v3n - v3) * (int32_t)frac >> MIX_FRAC_BITS;
+ v4 += (v4n - v4) * (int32_t)frac >> MIX_FRAC_BITS;
+ v5 += (v5n - v5) * (int32_t)frac >> MIX_FRAC_BITS;
#endif
- v0<<=16;
- v1<<=16;
- v2<<=16;
- v3<<=16;
- v4<<=16;
- v5<<=16;
- p_dest[(i*6)+0]=v0;
- p_dest[(i*6)+1]=v1;
- p_dest[(i*6)+2]=v2;
- p_dest[(i*6)+3]=v3;
- p_dest[(i*6)+4]=v4;
- p_dest[(i*6)+5]=v5;
-
+ v0 <<= 16;
+ v1 <<= 16;
+ v2 <<= 16;
+ v3 <<= 16;
+ v4 <<= 16;
+ v5 <<= 16;
+ p_dest[(i * 6) + 0] = v0;
+ p_dest[(i * 6) + 1] = v1;
+ p_dest[(i * 6) + 2] = v2;
+ p_dest[(i * 6) + 3] = v3;
+ p_dest[(i * 6) + 4] = v4;
+ p_dest[(i * 6) + 5] = v5;
}
-
-
}
-
- return read>>MIX_FRAC_BITS;//rb_read_pos=offset>>MIX_FRAC_BITS;
-
+ return read >> MIX_FRAC_BITS; //rb_read_pos=offset>>MIX_FRAC_BITS;
}
-
bool AudioRBResampler::mix(int32_t *p_dest, int p_frames) {
-
if (!rb)
return false;
- int write_pos_cache=rb_write_pos;
+ int write_pos_cache = rb_write_pos;
- int32_t increment=(src_mix_rate*MIX_FRAC_LEN)/target_mix_rate;
+ int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate;
int rb_todo;
- if (write_pos_cache==rb_read_pos) {
+ if (write_pos_cache == rb_read_pos) {
return false; //out of buffer
- } else if (rb_read_pos<write_pos_cache) {
+ } else if (rb_read_pos < write_pos_cache) {
- rb_todo=write_pos_cache-rb_read_pos; //-1?
+ rb_todo = write_pos_cache - rb_read_pos; //-1?
} else {
- rb_todo=(rb_len-rb_read_pos)+write_pos_cache; //-1?
+ rb_todo = (rb_len - rb_read_pos) + write_pos_cache; //-1?
}
- int todo = MIN( ((int64_t(rb_todo)<<MIX_FRAC_BITS)/increment)+1, p_frames );
+ int todo = MIN(((int64_t(rb_todo) << MIX_FRAC_BITS) / increment) + 1, p_frames);
#if 0
if (int(src_mix_rate)==target_mix_rate) {
@@ -224,118 +212,104 @@ bool AudioRBResampler::mix(int32_t *p_dest, int p_frames) {
#endif
{
- uint32_t read=0;
- switch(channels) {
- case 1: read=_resample<1>(p_dest,todo,increment); break;
- case 2: read=_resample<2>(p_dest,todo,increment); break;
- case 4: read=_resample<4>(p_dest,todo,increment); break;
- case 6: read=_resample<6>(p_dest,todo,increment); break;
+ uint32_t read = 0;
+ switch (channels) {
+ case 1: read = _resample<1>(p_dest, todo, increment); break;
+ case 2: read = _resample<2>(p_dest, todo, increment); break;
+ case 4: read = _resample<4>(p_dest, todo, increment); break;
+ case 6: read = _resample<6>(p_dest, todo, increment); break;
}
#if 1
//end of stream, fadeout
- int remaining = p_frames-todo;
- if (remaining && todo>0) {
+ int remaining = p_frames - todo;
+ if (remaining && todo > 0) {
//print_line("fadeout");
- for(int c=0;c<channels;c++) {
+ for (int c = 0; c < channels; c++) {
- for(int i=0;i<todo;i++) {
+ for (int i = 0; i < todo; i++) {
- int32_t samp = p_dest[i*channels+c]>>8;
- uint32_t mul = (todo-i) * 256 /todo;
+ int32_t samp = p_dest[i * channels + c] >> 8;
+ uint32_t mul = (todo - i) * 256 / todo;
//print_line("mul: "+itos(i)+" "+itos(mul));
- p_dest[i*channels+c]=samp*mul;
+ p_dest[i * channels + c] = samp * mul;
}
-
}
-
}
#else
- int remaining = p_frames-todo;
- if (remaining && todo>0) {
-
+ int remaining = p_frames - todo;
+ if (remaining && todo > 0) {
- for(int c=0;c<channels;c++) {
+ for (int c = 0; c < channels; c++) {
- int32_t from = p_dest[(todo-1)*channels+c]>>8;
+ int32_t from = p_dest[(todo - 1) * channels + c] >> 8;
- for(int i=0;i<remaining;i++) {
+ for (int i = 0; i < remaining; i++) {
- uint32_t mul = (remaining-i) * 256 /remaining;
- p_dest[(todo+i)*channels+c]=from*mul;
+ uint32_t mul = (remaining - i) * 256 / remaining;
+ p_dest[(todo + i) * channels + c] = from * mul;
}
-
}
-
}
#endif
//zero out what remains there to avoid glitches
- for(int i=todo*channels;i<int(p_frames)*channels;i++) {
+ for (int i = todo * channels; i < int(p_frames) * channels; i++) {
- p_dest[i]=0;
+ p_dest[i] = 0;
}
- if (read>rb_todo)
- read=rb_todo;
-
- rb_read_pos = (rb_read_pos+read)&rb_mask;
-
-
-
+ if (read > rb_todo)
+ read = rb_todo;
+ rb_read_pos = (rb_read_pos + read) & rb_mask;
}
return true;
}
+Error AudioRBResampler::setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed) {
-Error AudioRBResampler::setup(int p_channels,int p_src_mix_rate,int p_target_mix_rate,int p_buffer_msec,int p_minbuff_needed) {
-
- ERR_FAIL_COND_V(p_channels!=1 && p_channels!=2 && p_channels!=4 && p_channels!=6,ERR_INVALID_PARAMETER);
-
+ ERR_FAIL_COND_V(p_channels != 1 && p_channels != 2 && p_channels != 4 && p_channels != 6, ERR_INVALID_PARAMETER);
//float buffering_sec = int(GLOBAL_DEF("audio/stream_buffering_ms",500))/1000.0;
- int desired_rb_bits =nearest_shift(MAX((p_buffer_msec/1000.0)*p_src_mix_rate,p_minbuff_needed));
+ int desired_rb_bits = nearest_shift(MAX((p_buffer_msec / 1000.0) * p_src_mix_rate, p_minbuff_needed));
- bool recreate=!rb;
+ bool recreate = !rb;
- if (rb && (uint32_t(desired_rb_bits)!=rb_bits || channels!=uint32_t(p_channels))) {
+ if (rb && (uint32_t(desired_rb_bits) != rb_bits || channels != uint32_t(p_channels))) {
//recreate
memdelete_arr(rb);
memdelete_arr(read_buf);
- recreate=true;
-
+ recreate = true;
}
if (recreate) {
- channels=p_channels;
- rb_bits=desired_rb_bits;
- rb_len=(1<<rb_bits);
- rb_mask=rb_len-1;
- rb = memnew_arr( int16_t, rb_len * p_channels );
- read_buf = memnew_arr( int16_t, rb_len * p_channels );
-
+ channels = p_channels;
+ rb_bits = desired_rb_bits;
+ rb_len = (1 << rb_bits);
+ rb_mask = rb_len - 1;
+ rb = memnew_arr(int16_t, rb_len * p_channels);
+ read_buf = memnew_arr(int16_t, rb_len * p_channels);
}
- src_mix_rate=p_src_mix_rate;
- target_mix_rate=p_target_mix_rate;
- offset=0;
- rb_read_pos=0;
- rb_write_pos=0;
+ src_mix_rate = p_src_mix_rate;
+ target_mix_rate = p_target_mix_rate;
+ offset = 0;
+ rb_read_pos = 0;
+ rb_write_pos = 0;
//avoid maybe strange noises upon load
- for (int i=0;i<(rb_len*channels);i++) {
+ for (int i = 0; i < (rb_len * channels); i++) {
- rb[i]=0;
- read_buf[i]=0;
+ rb[i] = 0;
+ read_buf[i] = 0;
}
return OK;
-
}
void AudioRBResampler::clear() {
@@ -348,29 +322,28 @@ void AudioRBResampler::clear() {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
- rb=NULL;
- offset=0;
- rb_read_pos=0;
- rb_write_pos=0;
- read_buf=NULL;
+ rb = NULL;
+ offset = 0;
+ rb_read_pos = 0;
+ rb_write_pos = 0;
+ read_buf = NULL;
}
AudioRBResampler::AudioRBResampler() {
- rb=NULL;
- offset=0;
- read_buf=NULL;
- rb_read_pos=0;
- rb_write_pos=0;
-
- rb_bits=0;
- rb_len=0;
- rb_mask=0;
- read_buff_len=0;
- channels=0;
- src_mix_rate=0;
- target_mix_rate=0;
-
+ rb = NULL;
+ offset = 0;
+ read_buf = NULL;
+ rb_read_pos = 0;
+ rb_write_pos = 0;
+
+ rb_bits = 0;
+ rb_len = 0;
+ rb_mask = 0;
+ read_buff_len = 0;
+ channels = 0;
+ src_mix_rate = 0;
+ target_mix_rate = 0;
}
AudioRBResampler::~AudioRBResampler() {
@@ -379,6 +352,4 @@ AudioRBResampler::~AudioRBResampler() {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
-
}
-
diff --git a/servers/audio/audio_rb_resampler.h b/servers/audio/audio_rb_resampler.h
index e97e275b68..d775aed0d9 100644
--- a/servers/audio/audio_rb_resampler.h
+++ b/servers/audio/audio_rb_resampler.h
@@ -29,8 +29,8 @@
#ifndef AUDIO_RB_RESAMPLER_H
#define AUDIO_RB_RESAMPLER_H
-#include "typedefs.h"
#include "os/memory.h"
+#include "typedefs.h"
struct AudioRBResampler {
@@ -47,58 +47,53 @@ struct AudioRBResampler {
int32_t offset; //contains the fractional remainder of the resampler
enum {
- MIX_FRAC_BITS=13,
- MIX_FRAC_LEN=(1<<MIX_FRAC_BITS),
- MIX_FRAC_MASK=MIX_FRAC_LEN-1,
+ MIX_FRAC_BITS = 13,
+ MIX_FRAC_LEN = (1 << MIX_FRAC_BITS),
+ MIX_FRAC_MASK = MIX_FRAC_LEN - 1,
};
int16_t *read_buf;
int16_t *rb;
-
- template<int C>
- uint32_t _resample(int32_t *p_dest,int p_todo,int32_t p_increment);
-
+ template <int C>
+ uint32_t _resample(int32_t *p_dest, int p_todo, int32_t p_increment);
public:
-
_FORCE_INLINE_ void flush() {
- rb_read_pos=0;
- rb_write_pos=0;
- offset=0;
+ rb_read_pos = 0;
+ rb_write_pos = 0;
+ offset = 0;
}
- _FORCE_INLINE_ bool is_ready() const{
- return rb!=NULL;
+ _FORCE_INLINE_ bool is_ready() const {
+ return rb != NULL;
}
-
_FORCE_INLINE_ int get_total() const {
- return rb_len-1;
+ return rb_len - 1;
}
_FORCE_INLINE_ int get_todo() const { //return amount of frames to mix
int todo;
- int read_pos_cache=rb_read_pos;
+ int read_pos_cache = rb_read_pos;
- if (read_pos_cache==rb_write_pos) {
- todo=rb_len-1;
- } else if (read_pos_cache>rb_write_pos) {
+ if (read_pos_cache == rb_write_pos) {
+ todo = rb_len - 1;
+ } else if (read_pos_cache > rb_write_pos) {
- todo=read_pos_cache-rb_write_pos-1;
+ todo = read_pos_cache - rb_write_pos - 1;
} else {
- todo=(rb_len-rb_write_pos)+read_pos_cache-1;
+ todo = (rb_len - rb_write_pos) + read_pos_cache - 1;
}
return todo;
}
-
_FORCE_INLINE_ bool has_data() const {
- return rb && rb_read_pos!=rb_write_pos;
+ return rb && rb_read_pos != rb_write_pos;
}
_FORCE_INLINE_ int16_t *get_write_buffer() { return read_buf; }
@@ -106,57 +101,54 @@ public:
ERR_FAIL_COND(p_frames >= rb_len);
- switch(channels) {
+ switch (channels) {
case 1: {
- for(uint32_t i=0;i<p_frames;i++) {
+ for (uint32_t i = 0; i < p_frames; i++) {
- rb[ rb_write_pos ] = read_buf[i];
- rb_write_pos=(rb_write_pos+1)&rb_mask;
+ rb[rb_write_pos] = read_buf[i];
+ rb_write_pos = (rb_write_pos + 1) & rb_mask;
}
} break;
case 2: {
- for(uint32_t i=0;i<p_frames;i++) {
+ for (uint32_t i = 0; i < p_frames; i++) {
- rb[ (rb_write_pos<<1)+0 ] = read_buf[(i<<1)+0];
- rb[ (rb_write_pos<<1)+1 ] = read_buf[(i<<1)+1];
- rb_write_pos=(rb_write_pos+1)&rb_mask;
+ rb[(rb_write_pos << 1) + 0] = read_buf[(i << 1) + 0];
+ rb[(rb_write_pos << 1) + 1] = read_buf[(i << 1) + 1];
+ rb_write_pos = (rb_write_pos + 1) & rb_mask;
}
} break;
case 4: {
- for(uint32_t i=0;i<p_frames;i++) {
+ for (uint32_t i = 0; i < p_frames; i++) {
- rb[ (rb_write_pos<<2)+0 ] = read_buf[(i<<2)+0];
- rb[ (rb_write_pos<<2)+1 ] = read_buf[(i<<2)+1];
- rb[ (rb_write_pos<<2)+2 ] = read_buf[(i<<2)+2];
- rb[ (rb_write_pos<<2)+3 ] = read_buf[(i<<2)+3];
- rb_write_pos=(rb_write_pos+1)&rb_mask;
+ rb[(rb_write_pos << 2) + 0] = read_buf[(i << 2) + 0];
+ rb[(rb_write_pos << 2) + 1] = read_buf[(i << 2) + 1];
+ rb[(rb_write_pos << 2) + 2] = read_buf[(i << 2) + 2];
+ rb[(rb_write_pos << 2) + 3] = read_buf[(i << 2) + 3];
+ rb_write_pos = (rb_write_pos + 1) & rb_mask;
}
} break;
case 6: {
- for(uint32_t i=0;i<p_frames;i++) {
+ for (uint32_t i = 0; i < p_frames; i++) {
- rb[ (rb_write_pos*6)+0 ] = read_buf[(i*6)+0];
- rb[ (rb_write_pos*6)+1 ] = read_buf[(i*6)+1];
- rb[ (rb_write_pos*6)+2 ] = read_buf[(i*6)+2];
- rb[ (rb_write_pos*6)+3 ] = read_buf[(i*6)+3];
- rb[ (rb_write_pos*6)+4 ] = read_buf[(i*6)+4];
- rb[ (rb_write_pos*6)+5 ] = read_buf[(i*6)+5];
- rb_write_pos=(rb_write_pos+1)&rb_mask;
+ rb[(rb_write_pos * 6) + 0] = read_buf[(i * 6) + 0];
+ rb[(rb_write_pos * 6) + 1] = read_buf[(i * 6) + 1];
+ rb[(rb_write_pos * 6) + 2] = read_buf[(i * 6) + 2];
+ rb[(rb_write_pos * 6) + 3] = read_buf[(i * 6) + 3];
+ rb[(rb_write_pos * 6) + 4] = read_buf[(i * 6) + 4];
+ rb[(rb_write_pos * 6) + 5] = read_buf[(i * 6) + 5];
+ rb_write_pos = (rb_write_pos + 1) & rb_mask;
}
} break;
-
-
}
-
}
int get_channel_count() const;
- Error setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed=-1);
+ Error setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed = -1);
void clear();
bool mix(int32_t *p_dest, int p_frames);
diff --git a/servers/audio/audio_stream.cpp b/servers/audio/audio_stream.cpp
index f4214838a1..5f77eb54f6 100644
--- a/servers/audio/audio_stream.cpp
+++ b/servers/audio/audio_stream.cpp
@@ -30,57 +30,53 @@
//////////////////////////////
-
-
void AudioStreamPlaybackResampled::_begin_resample() {
//clear cubic interpolation history
- internal_buffer[0]=AudioFrame(0.0,0.0);
- internal_buffer[1]=AudioFrame(0.0,0.0);
- internal_buffer[2]=AudioFrame(0.0,0.0);
- internal_buffer[3]=AudioFrame(0.0,0.0);
+ internal_buffer[0] = AudioFrame(0.0, 0.0);
+ internal_buffer[1] = AudioFrame(0.0, 0.0);
+ internal_buffer[2] = AudioFrame(0.0, 0.0);
+ internal_buffer[3] = AudioFrame(0.0, 0.0);
//mix buffer
- _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN);
- mix_offset=0;
+ _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
+ mix_offset = 0;
}
-void AudioStreamPlaybackResampled::mix(AudioFrame* p_buffer,float p_rate_scale,int p_frames) {
+void AudioStreamPlaybackResampled::mix(AudioFrame *p_buffer, float p_rate_scale, int p_frames) {
float target_rate = AudioServer::get_singleton()->get_mix_rate() * p_rate_scale;
- uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double( FP_LEN ));
-
- for(int i=0;i<p_frames;i++) {
-
+ uint64_t mix_increment = uint64_t((get_stream_sampling_rate() / double(target_rate)) * double(FP_LEN));
+ for (int i = 0; i < p_frames; i++) {
uint32_t idx = CUBIC_INTERP_HISTORY + uint32_t(mix_offset >> FP_BITS);
//standard cubic interpolation (great quality/performance ratio)
//this used to be moved to a LUT for greater performance, but nowadays CPU speed is generally faster than memory.
- float mu = (mix_offset&FP_MASK)/float(FP_LEN);
- AudioFrame y0 = internal_buffer[idx-3];
- AudioFrame y1 = internal_buffer[idx-2];
- AudioFrame y2 = internal_buffer[idx-1];
- AudioFrame y3 = internal_buffer[idx-0];
+ float mu = (mix_offset & FP_MASK) / float(FP_LEN);
+ AudioFrame y0 = internal_buffer[idx - 3];
+ AudioFrame y1 = internal_buffer[idx - 2];
+ AudioFrame y2 = internal_buffer[idx - 1];
+ AudioFrame y3 = internal_buffer[idx - 0];
- float mu2 = mu*mu;
+ float mu2 = mu * mu;
AudioFrame a0 = y3 - y2 - y0 + y1;
AudioFrame a1 = y0 - y1 - a0;
AudioFrame a2 = y2 - y0;
AudioFrame a3 = y1;
- p_buffer[i] = (a0*mu*mu2 + a1*mu2 + a2*mu + a3);
+ p_buffer[i] = (a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3);
- mix_offset+=mix_increment;
+ mix_offset += mix_increment;
- while ( (mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN ) {
+ while ((mix_offset >> FP_BITS) >= INTERNAL_BUFFER_LEN) {
- internal_buffer[0]=internal_buffer[INTERNAL_BUFFER_LEN+0];
- internal_buffer[1]=internal_buffer[INTERNAL_BUFFER_LEN+1];
- internal_buffer[2]=internal_buffer[INTERNAL_BUFFER_LEN+2];
- internal_buffer[3]=internal_buffer[INTERNAL_BUFFER_LEN+3];
- _mix_internal(internal_buffer+4,INTERNAL_BUFFER_LEN);
- mix_offset-=(INTERNAL_BUFFER_LEN<<FP_BITS);
+ internal_buffer[0] = internal_buffer[INTERNAL_BUFFER_LEN + 0];
+ internal_buffer[1] = internal_buffer[INTERNAL_BUFFER_LEN + 1];
+ internal_buffer[2] = internal_buffer[INTERNAL_BUFFER_LEN + 2];
+ internal_buffer[3] = internal_buffer[INTERNAL_BUFFER_LEN + 3];
+ _mix_internal(internal_buffer + 4, INTERNAL_BUFFER_LEN);
+ mix_offset -= (INTERNAL_BUFFER_LEN << FP_BITS);
}
}
}
diff --git a/servers/audio/audio_stream.h b/servers/audio/audio_stream.h
index d08fedb084..0d7b4adbfe 100644
--- a/servers/audio/audio_stream.h
+++ b/servers/audio/audio_stream.h
@@ -34,68 +34,57 @@
class AudioStreamPlayback : public Reference {
- GDCLASS( AudioStreamPlayback, Reference )
+ GDCLASS(AudioStreamPlayback, Reference)
public:
+ virtual void start(float p_from_pos = 0.0) = 0;
+ virtual void stop() = 0;
+ virtual bool is_playing() const = 0;
- virtual void start(float p_from_pos=0.0)=0;
- virtual void stop()=0;
- virtual bool is_playing() const=0;
+ virtual int get_loop_count() const = 0; //times it looped
- virtual int get_loop_count() const=0; //times it looped
-
- virtual float get_pos() const=0;
- virtual void seek_pos(float p_time)=0;
-
- virtual void mix(AudioFrame* p_bufer,float p_rate_scale,int p_frames)=0;
-
- virtual float get_length() const=0; //if supported, otherwise return 0
+ virtual float get_pos() const = 0;
+ virtual void seek_pos(float p_time) = 0;
+ virtual void mix(AudioFrame *p_bufer, float p_rate_scale, int p_frames) = 0;
+ virtual float get_length() const = 0; //if supported, otherwise return 0
};
class AudioStreamPlaybackResampled : public AudioStreamPlayback {
- GDCLASS( AudioStreamPlaybackResampled, AudioStreamPlayback )
-
-
+ GDCLASS(AudioStreamPlaybackResampled, AudioStreamPlayback)
enum {
- FP_BITS=16, //fixed point used for resampling
- FP_LEN=(1<<FP_BITS),
- FP_MASK=FP_LEN-1,
- INTERNAL_BUFFER_LEN=256,
- CUBIC_INTERP_HISTORY=4
+ FP_BITS = 16, //fixed point used for resampling
+ FP_LEN = (1 << FP_BITS),
+ FP_MASK = FP_LEN - 1,
+ INTERNAL_BUFFER_LEN = 256,
+ CUBIC_INTERP_HISTORY = 4
};
- AudioFrame internal_buffer[INTERNAL_BUFFER_LEN+CUBIC_INTERP_HISTORY];
+ AudioFrame internal_buffer[INTERNAL_BUFFER_LEN + CUBIC_INTERP_HISTORY];
uint64_t mix_offset;
protected:
void _begin_resample();
- virtual void _mix_internal(AudioFrame* p_bufer,int p_frames)=0;
- virtual float get_stream_sampling_rate()=0;
+ virtual void _mix_internal(AudioFrame *p_bufer, int p_frames) = 0;
+ virtual float get_stream_sampling_rate() = 0;
public:
+ virtual void mix(AudioFrame *p_bufer, float p_rate_scale, int p_frames);
- virtual void mix(AudioFrame* p_bufer,float p_rate_scale,int p_frames);
-
- AudioStreamPlaybackResampled() { mix_offset=0; }
+ AudioStreamPlaybackResampled() { mix_offset = 0; }
};
class AudioStream : public Resource {
- GDCLASS( AudioStream, Resource )
- OBJ_SAVE_TYPE( AudioStream ) //children are all saved as AudioStream, so they can be exchanged
-
+ GDCLASS(AudioStream, Resource)
+ OBJ_SAVE_TYPE(AudioStream) //children are all saved as AudioStream, so they can be exchanged
public:
-
- virtual Ref<AudioStreamPlayback> instance_playback()=0;
- virtual String get_stream_name() const=0;
-
-
+ virtual Ref<AudioStreamPlayback> instance_playback() = 0;
+ virtual String get_stream_name() const = 0;
};
-
#endif // AUDIO_STREAM_H
diff --git a/servers/audio/effects/audio_effect_amplify.cpp b/servers/audio/effects/audio_effect_amplify.cpp
index a0796f5224..6a4d03e517 100644
--- a/servers/audio/effects/audio_effect_amplify.cpp
+++ b/servers/audio/effects/audio_effect_amplify.cpp
@@ -28,35 +28,31 @@
/*************************************************************************/
#include "audio_effect_amplify.h"
-
-void AudioEffectAmplifyInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
+void AudioEffectAmplifyInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
//multiply volume interpolating to avoid clicks if this changes
float volume_db = base->volume_db;
float vol = Math::db2linear(mix_volume_db);
- float vol_inc = (Math::db2linear(volume_db) - vol)/float(p_frame_count);
+ float vol_inc = (Math::db2linear(volume_db) - vol) / float(p_frame_count);
- for(int i=0;i<p_frame_count;i++) {
- p_dst_frames[i]=p_src_frames[i]*vol;
- vol+=vol_inc;
+ for (int i = 0; i < p_frame_count; i++) {
+ p_dst_frames[i] = p_src_frames[i] * vol;
+ vol += vol_inc;
}
//set volume for next mix
mix_volume_db = volume_db;
-
}
-
Ref<AudioEffectInstance> AudioEffectAmplify::instance() {
Ref<AudioEffectAmplifyInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectAmplify>(this);
- ins->mix_volume_db=volume_db;
+ ins->base = Ref<AudioEffectAmplify>(this);
+ ins->mix_volume_db = volume_db;
return ins;
}
void AudioEffectAmplify::set_volume_db(float p_volume) {
- volume_db=p_volume;
+ volume_db = p_volume;
}
float AudioEffectAmplify::get_volume_db() const {
@@ -66,13 +62,12 @@ float AudioEffectAmplify::get_volume_db() const {
void AudioEffectAmplify::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_volume_db","volume"),&AudioEffectAmplify::set_volume_db);
- ClassDB::bind_method(D_METHOD("get_volume_db"),&AudioEffectAmplify::get_volume_db);
+ ClassDB::bind_method(D_METHOD("set_volume_db", "volume"), &AudioEffectAmplify::set_volume_db);
+ ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioEffectAmplify::get_volume_db);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24,0.01"),"set_volume_db","get_volume_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "volume_db", PROPERTY_HINT_RANGE, "-80,24,0.01"), "set_volume_db", "get_volume_db");
}
-AudioEffectAmplify::AudioEffectAmplify()
-{
- volume_db=0;
+AudioEffectAmplify::AudioEffectAmplify() {
+ volume_db = 0;
}
diff --git a/servers/audio/effects/audio_effect_amplify.h b/servers/audio/effects/audio_effect_amplify.h
index 03f558e52e..0c75b43691 100644
--- a/servers/audio/effects/audio_effect_amplify.h
+++ b/servers/audio/effects/audio_effect_amplify.h
@@ -34,30 +34,26 @@
class AudioEffectAmplify;
class AudioEffectAmplifyInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectAmplifyInstance,AudioEffectInstance)
-friend class AudioEffectAmplify;
+ GDCLASS(AudioEffectAmplifyInstance, AudioEffectInstance)
+ friend class AudioEffectAmplify;
Ref<AudioEffectAmplify> base;
float mix_volume_db;
-public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectAmplify : public AudioEffect {
- GDCLASS(AudioEffectAmplify,AudioEffect)
+ GDCLASS(AudioEffectAmplify, AudioEffect)
-friend class AudioEffectAmplifyInstance;
+ friend class AudioEffectAmplifyInstance;
float volume_db;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
void set_volume_db(float p_volume);
float get_volume_db() const;
diff --git a/servers/audio/effects/audio_effect_chorus.cpp b/servers/audio/effects/audio_effect_chorus.cpp
index 20b45b5725..fa3a571c6e 100644
--- a/servers/audio/effects/audio_effect_chorus.cpp
+++ b/servers/audio/effects/audio_effect_chorus.cpp
@@ -27,161 +27,153 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "audio_effect_chorus.h"
-#include "servers/audio_server.h"
#include "math_funcs.h"
+#include "servers/audio_server.h"
-void AudioEffectChorusInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectChorusInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
int todo = p_frame_count;
- while(todo) {
+ while (todo) {
- int to_mix = MIN(todo,256); //can't mix too much
+ int to_mix = MIN(todo, 256); //can't mix too much
- _process_chunk(p_src_frames,p_dst_frames,to_mix);
+ _process_chunk(p_src_frames, p_dst_frames, to_mix);
- p_src_frames+=to_mix;
- p_dst_frames+=to_mix;
+ p_src_frames += to_mix;
+ p_dst_frames += to_mix;
- todo-=to_mix;
+ todo -= to_mix;
}
}
-void AudioEffectChorusInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
+void AudioEffectChorusInstance::_process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
//fill ringbuffer
- for(int i=0;i<p_frame_count;i++) {
- audio_buffer[(buffer_pos+i)&buffer_mask]=p_src_frames[i];
- p_dst_frames[i]=p_src_frames[i]*base->dry;
+ for (int i = 0; i < p_frame_count; i++) {
+ audio_buffer[(buffer_pos + i) & buffer_mask] = p_src_frames[i];
+ p_dst_frames[i] = p_src_frames[i] * base->dry;
}
float mix_rate = AudioServer::get_singleton()->get_mix_rate();
/* process voices */
- for (int vc=0;vc<base->voice_count;vc++) {
+ for (int vc = 0; vc < base->voice_count; vc++) {
- AudioEffectChorus::Voice &v=base->voice[vc];
+ AudioEffectChorus::Voice &v = base->voice[vc];
+ double time_to_mix = (float)p_frame_count / mix_rate;
+ double cycles_to_mix = time_to_mix * v.rate;
- double time_to_mix=(float)p_frame_count/mix_rate;
- double cycles_to_mix=time_to_mix*v.rate;
+ unsigned int local_rb_pos = buffer_pos;
+ AudioFrame *dst_buff = p_dst_frames;
+ AudioFrame *rb_buff = audio_buffer.ptr();
- unsigned int local_rb_pos=buffer_pos;
- AudioFrame *dst_buff=p_dst_frames;
- AudioFrame *rb_buff=audio_buffer.ptr();
+ double delay_msec = v.delay;
+ unsigned int delay_frames = Math::fast_ftoi((delay_msec / 1000.0) * mix_rate);
+ float max_depth_frames = (v.depth / 1000.0) * mix_rate;
- double delay_msec=v.delay;
- unsigned int delay_frames=Math::fast_ftoi((delay_msec/1000.0)*mix_rate);
- float max_depth_frames=(v.depth/1000.0)*mix_rate;
-
- uint64_t local_cycles=cycles[vc];
- uint64_t increment=llrint(cycles_to_mix/(double)p_frame_count*(double)(1<<AudioEffectChorus::CYCLES_FRAC));
+ uint64_t local_cycles = cycles[vc];
+ uint64_t increment = llrint(cycles_to_mix / (double)p_frame_count * (double)(1 << AudioEffectChorus::CYCLES_FRAC));
//check the LFO doesnt read ahead of the write pos
- if ((((int)max_depth_frames)+10)>delay_frames) { //10 as some threshold to avoid precision stuff
- delay_frames+=(int)max_depth_frames-delay_frames;
- delay_frames+=10; //threshold to avoid precision stuff
-
+ if ((((int)max_depth_frames) + 10) > delay_frames) { //10 as some threshold to avoid precision stuff
+ delay_frames += (int)max_depth_frames - delay_frames;
+ delay_frames += 10; //threshold to avoid precision stuff
}
-
-
//low pass filter
- if (v.cutoff==0)
+ if (v.cutoff == 0)
continue;
- float auxlp=expf(-2.0*Math_PI*v.cutoff/mix_rate);
- float c1=1.0-auxlp;
- float c2=auxlp;
- AudioFrame h=filter_h[vc];
- if (v.cutoff>=AudioEffectChorus::MS_CUTOFF_MAX) {
- c1=1.0; c2=0.0;
+ float auxlp = expf(-2.0 * Math_PI * v.cutoff / mix_rate);
+ float c1 = 1.0 - auxlp;
+ float c2 = auxlp;
+ AudioFrame h = filter_h[vc];
+ if (v.cutoff >= AudioEffectChorus::MS_CUTOFF_MAX) {
+ c1 = 1.0;
+ c2 = 0.0;
}
//vol modifier
- AudioFrame vol_modifier=AudioFrame(base->wet,base->wet) * Math::db2linear(v.level);
- vol_modifier.l*=CLAMP( 1.0 - v.pan, 0, 1);
- vol_modifier.r*=CLAMP( 1.0 + v.pan, 0, 1);
-
+ AudioFrame vol_modifier = AudioFrame(base->wet, base->wet) * Math::db2linear(v.level);
+ vol_modifier.l *= CLAMP(1.0 - v.pan, 0, 1);
+ vol_modifier.r *= CLAMP(1.0 + v.pan, 0, 1);
-
- for (int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
/** COMPUTE WAVEFORM **/
- float phase=(float)(local_cycles&AudioEffectChorus::CYCLES_MASK)/(float)(1<<AudioEffectChorus::CYCLES_FRAC);
+ float phase = (float)(local_cycles & AudioEffectChorus::CYCLES_MASK) / (float)(1 << AudioEffectChorus::CYCLES_FRAC);
- float wave_delay=sinf(phase*2.0*Math_PI)*max_depth_frames;
+ float wave_delay = sinf(phase * 2.0 * Math_PI) * max_depth_frames;
- int wave_delay_frames=lrint(floor(wave_delay));
- float wave_delay_frac=wave_delay-(float)wave_delay_frames;
+ int wave_delay_frames = lrint(floor(wave_delay));
+ float wave_delay_frac = wave_delay - (float)wave_delay_frames;
/** COMPUTE RINGBUFFER POS**/
- unsigned int rb_source=local_rb_pos;
- rb_source-=delay_frames;
+ unsigned int rb_source = local_rb_pos;
+ rb_source -= delay_frames;
- rb_source-=wave_delay_frames;
+ rb_source -= wave_delay_frames;
/** READ FROM RINGBUFFER, LINEARLY INTERPOLATE */
- AudioFrame val=rb_buff[rb_source&buffer_mask];
- AudioFrame val_next=rb_buff[(rb_source-1)&buffer_mask];
+ AudioFrame val = rb_buff[rb_source & buffer_mask];
+ AudioFrame val_next = rb_buff[(rb_source - 1) & buffer_mask];
- val+=(val_next-val)*wave_delay_frac;
+ val += (val_next - val) * wave_delay_frac;
- val=val*c1+h*c2;
- h=val;
+ val = val * c1 + h * c2;
+ h = val;
/** MIX VALUE TO OUTPUT **/
- dst_buff[i]+=val*vol_modifier;
+ dst_buff[i] += val * vol_modifier;
- local_cycles+=increment;
+ local_cycles += increment;
local_rb_pos++;
-
}
- filter_h[vc]=h;
- cycles[vc]+=Math::fast_ftoi(cycles_to_mix*(double)(1<<AudioEffectChorus::CYCLES_FRAC));
+ filter_h[vc] = h;
+ cycles[vc] += Math::fast_ftoi(cycles_to_mix * (double)(1 << AudioEffectChorus::CYCLES_FRAC));
}
- buffer_pos+=p_frame_count;
+ buffer_pos += p_frame_count;
}
-
Ref<AudioEffectInstance> AudioEffectChorus::instance() {
Ref<AudioEffectChorusInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectChorus>(this);
- for(int i=0;i<4;i++) {
- ins->filter_h[i]=AudioFrame(0,0);
- ins->cycles[i]=0;
+ ins->base = Ref<AudioEffectChorus>(this);
+ for (int i = 0; i < 4; i++) {
+ ins->filter_h[i] = AudioFrame(0, 0);
+ ins->cycles[i] = 0;
}
- float ring_buffer_max_size=AudioEffectChorus::MAX_DELAY_MS+AudioEffectChorus::MAX_DEPTH_MS+AudioEffectChorus::MAX_WIDTH_MS;
+ float ring_buffer_max_size = AudioEffectChorus::MAX_DELAY_MS + AudioEffectChorus::MAX_DEPTH_MS + AudioEffectChorus::MAX_WIDTH_MS;
- ring_buffer_max_size*=2; //just to avoid complications
- ring_buffer_max_size/=1000.0;//convert to seconds
- ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate();
+ ring_buffer_max_size *= 2; //just to avoid complications
+ ring_buffer_max_size /= 1000.0; //convert to seconds
+ ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate();
- int ringbuff_size=ring_buffer_max_size;
+ int ringbuff_size = ring_buffer_max_size;
- int bits=0;
+ int bits = 0;
- while(ringbuff_size>0) {
+ while (ringbuff_size > 0) {
bits++;
- ringbuff_size/=2;
+ ringbuff_size /= 2;
}
- ringbuff_size=1<<bits;
- ins->buffer_mask=ringbuff_size-1;
- ins->buffer_pos=0;
+ ringbuff_size = 1 << bits;
+ ins->buffer_mask = ringbuff_size - 1;
+ ins->buffer_pos = 0;
ins->audio_buffer.resize(ringbuff_size);
- for(int i=0;i<ringbuff_size;i++) {
- ins->audio_buffer[i]=AudioFrame(0,0);
+ for (int i = 0; i < ringbuff_size; i++) {
+ ins->audio_buffer[i] = AudioFrame(0, 0);
}
return ins;
@@ -189,205 +181,195 @@ Ref<AudioEffectInstance> AudioEffectChorus::instance() {
void AudioEffectChorus::set_voice_count(int p_voices) {
- ERR_FAIL_COND(p_voices<1 || p_voices>=MAX_VOICES);
- voice_count=p_voices;
+ ERR_FAIL_COND(p_voices < 1 || p_voices >= MAX_VOICES);
+ voice_count = p_voices;
_change_notify();
}
-
-int AudioEffectChorus::get_voice_count() const{
+int AudioEffectChorus::get_voice_count() const {
return voice_count;
}
-void AudioEffectChorus::set_voice_delay_ms(int p_voice,float p_delay_ms){
-
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
+void AudioEffectChorus::set_voice_delay_ms(int p_voice, float p_delay_ms) {
- voice[p_voice].delay=p_delay_ms;
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
+ voice[p_voice].delay = p_delay_ms;
}
-float AudioEffectChorus::get_voice_delay_ms(int p_voice) const{
+float AudioEffectChorus::get_voice_delay_ms(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].delay;
}
-void AudioEffectChorus::set_voice_rate_hz(int p_voice,float p_rate_hz){
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
+void AudioEffectChorus::set_voice_rate_hz(int p_voice, float p_rate_hz) {
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
- voice[p_voice].rate=p_rate_hz;
+ voice[p_voice].rate = p_rate_hz;
}
-float AudioEffectChorus::get_voice_rate_hz(int p_voice) const{
+float AudioEffectChorus::get_voice_rate_hz(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].rate;
}
-void AudioEffectChorus::set_voice_depth_ms(int p_voice,float p_depth_ms){
+void AudioEffectChorus::set_voice_depth_ms(int p_voice, float p_depth_ms) {
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
- voice[p_voice].depth=p_depth_ms;
+ voice[p_voice].depth = p_depth_ms;
}
-float AudioEffectChorus::get_voice_depth_ms(int p_voice) const{
+float AudioEffectChorus::get_voice_depth_ms(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].depth;
}
-void AudioEffectChorus::set_voice_level_db(int p_voice,float p_level_db){
+void AudioEffectChorus::set_voice_level_db(int p_voice, float p_level_db) {
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
- voice[p_voice].level=p_level_db;
+ voice[p_voice].level = p_level_db;
}
-float AudioEffectChorus::get_voice_level_db(int p_voice) const{
+float AudioEffectChorus::get_voice_level_db(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].level;
}
+void AudioEffectChorus::set_voice_cutoff_hz(int p_voice, float p_cutoff_hz) {
-void AudioEffectChorus::set_voice_cutoff_hz(int p_voice,float p_cutoff_hz){
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
-
- voice[p_voice].cutoff=p_cutoff_hz;
+ voice[p_voice].cutoff = p_cutoff_hz;
}
-float AudioEffectChorus::get_voice_cutoff_hz(int p_voice) const{
+float AudioEffectChorus::get_voice_cutoff_hz(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].cutoff;
}
-void AudioEffectChorus::set_voice_pan(int p_voice,float p_pan){
+void AudioEffectChorus::set_voice_pan(int p_voice, float p_pan) {
- ERR_FAIL_INDEX(p_voice,MAX_VOICES);
+ ERR_FAIL_INDEX(p_voice, MAX_VOICES);
- voice[p_voice].pan=p_pan;
+ voice[p_voice].pan = p_pan;
}
-float AudioEffectChorus::get_voice_pan(int p_voice) const{
+float AudioEffectChorus::get_voice_pan(int p_voice) const {
- ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0);
+ ERR_FAIL_INDEX_V(p_voice, MAX_VOICES, 0);
return voice[p_voice].pan;
}
+void AudioEffectChorus::set_wet(float amount) {
-void AudioEffectChorus::set_wet(float amount){
-
-
- wet=amount;
+ wet = amount;
}
-float AudioEffectChorus::get_wet() const{
+float AudioEffectChorus::get_wet() const {
return wet;
}
-void AudioEffectChorus::set_dry(float amount){
-
- dry=amount;
+void AudioEffectChorus::set_dry(float amount) {
+ dry = amount;
}
-float AudioEffectChorus::get_dry() const{
+float AudioEffectChorus::get_dry() const {
return dry;
}
-void AudioEffectChorus::_validate_property(PropertyInfo& property) const {
+void AudioEffectChorus::_validate_property(PropertyInfo &property) const {
if (property.name.begins_with("voice/")) {
- int voice_idx = property.name.get_slice("/",1).to_int();
- if (voice_idx>voice_count) {
- property.usage=0;
+ int voice_idx = property.name.get_slice("/", 1).to_int();
+ if (voice_idx > voice_count) {
+ property.usage = 0;
}
}
}
-
void AudioEffectChorus::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_voice_count","voices"),&AudioEffectChorus::set_voice_count);
- ClassDB::bind_method(D_METHOD("get_voice_count"),&AudioEffectChorus::get_voice_count);
-
-
- ClassDB::bind_method(D_METHOD("set_voice_delay_ms","voice_idx","delay_ms"),&AudioEffectChorus::set_voice_delay_ms);
- ClassDB::bind_method(D_METHOD("get_voice_delay_ms","voice_idx"),&AudioEffectChorus::get_voice_delay_ms);
+ ClassDB::bind_method(D_METHOD("set_voice_count", "voices"), &AudioEffectChorus::set_voice_count);
+ ClassDB::bind_method(D_METHOD("get_voice_count"), &AudioEffectChorus::get_voice_count);
- ClassDB::bind_method(D_METHOD("set_voice_rate_hz","voice_idx","rate_hz"),&AudioEffectChorus::set_voice_rate_hz);
- ClassDB::bind_method(D_METHOD("get_voice_rate_hz","voice_idx"),&AudioEffectChorus::get_voice_rate_hz);
+ ClassDB::bind_method(D_METHOD("set_voice_delay_ms", "voice_idx", "delay_ms"), &AudioEffectChorus::set_voice_delay_ms);
+ ClassDB::bind_method(D_METHOD("get_voice_delay_ms", "voice_idx"), &AudioEffectChorus::get_voice_delay_ms);
- ClassDB::bind_method(D_METHOD("set_voice_depth_ms","voice_idx","depth_ms"),&AudioEffectChorus::set_voice_depth_ms);
- ClassDB::bind_method(D_METHOD("get_voice_depth_ms","voice_idx"),&AudioEffectChorus::get_voice_depth_ms);
+ ClassDB::bind_method(D_METHOD("set_voice_rate_hz", "voice_idx", "rate_hz"), &AudioEffectChorus::set_voice_rate_hz);
+ ClassDB::bind_method(D_METHOD("get_voice_rate_hz", "voice_idx"), &AudioEffectChorus::get_voice_rate_hz);
- ClassDB::bind_method(D_METHOD("set_voice_level_db","voice_idx","level_db"),&AudioEffectChorus::set_voice_level_db);
- ClassDB::bind_method(D_METHOD("get_voice_level_db","voice_idx"),&AudioEffectChorus::get_voice_level_db);
+ ClassDB::bind_method(D_METHOD("set_voice_depth_ms", "voice_idx", "depth_ms"), &AudioEffectChorus::set_voice_depth_ms);
+ ClassDB::bind_method(D_METHOD("get_voice_depth_ms", "voice_idx"), &AudioEffectChorus::get_voice_depth_ms);
- ClassDB::bind_method(D_METHOD("set_voice_cutoff_hz","voice_idx","cutoff_hz"),&AudioEffectChorus::set_voice_cutoff_hz);
- ClassDB::bind_method(D_METHOD("get_voice_cutoff_hz","voice_idx"),&AudioEffectChorus::get_voice_cutoff_hz);
+ ClassDB::bind_method(D_METHOD("set_voice_level_db", "voice_idx", "level_db"), &AudioEffectChorus::set_voice_level_db);
+ ClassDB::bind_method(D_METHOD("get_voice_level_db", "voice_idx"), &AudioEffectChorus::get_voice_level_db);
- ClassDB::bind_method(D_METHOD("set_voice_pan","voice_idx","pan"),&AudioEffectChorus::set_voice_pan);
- ClassDB::bind_method(D_METHOD("get_voice_pan","voice_idx"),&AudioEffectChorus::get_voice_pan);
+ ClassDB::bind_method(D_METHOD("set_voice_cutoff_hz", "voice_idx", "cutoff_hz"), &AudioEffectChorus::set_voice_cutoff_hz);
+ ClassDB::bind_method(D_METHOD("get_voice_cutoff_hz", "voice_idx"), &AudioEffectChorus::get_voice_cutoff_hz);
- ClassDB::bind_method(D_METHOD("set_wet","amount"),&AudioEffectChorus::set_wet);
- ClassDB::bind_method(D_METHOD("get_wet"),&AudioEffectChorus::get_wet);
+ ClassDB::bind_method(D_METHOD("set_voice_pan", "voice_idx", "pan"), &AudioEffectChorus::set_voice_pan);
+ ClassDB::bind_method(D_METHOD("get_voice_pan", "voice_idx"), &AudioEffectChorus::get_voice_pan);
- ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectChorus::set_dry);
- ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectChorus::get_dry);
+ ClassDB::bind_method(D_METHOD("set_wet", "amount"), &AudioEffectChorus::set_wet);
+ ClassDB::bind_method(D_METHOD("get_wet"), &AudioEffectChorus::get_wet);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"voice_count",PROPERTY_HINT_RANGE,"1,4,1"),"set_voice_count","get_voice_count");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_wet","get_wet");
+ ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectChorus::set_dry);
+ ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectChorus::get_dry);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",0);
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "voice_count", PROPERTY_HINT_RANGE, "1,4,1"), "set_voice_count", "get_voice_count");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wet", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_wet", "get_wet");
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 0);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/1/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 0);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",2);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",2);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",2);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",2);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",2);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 1);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/2/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 1);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_voice_delay_ms","get_voice_delay_ms",3);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),"set_voice_rate_hz","get_voice_rate_hz",3);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),"set_voice_depth_ms","get_voice_depth_ms",3);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),"set_voice_level_db","get_voice_level_db",3);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),"set_voice_cutoff_hz","get_voice_cutoff_hz",3);
- ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_voice_pan","get_voice_pan",3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/3/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 2);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/delay_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_voice_delay_ms", "get_voice_delay_ms", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/rate_hz", PROPERTY_HINT_RANGE, "0.1,20,0.1"), "set_voice_rate_hz", "get_voice_rate_hz", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/depth_ms", PROPERTY_HINT_RANGE, "0,20,0.01"), "set_voice_depth_ms", "get_voice_depth_ms", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/level_db", PROPERTY_HINT_RANGE, "-60,24,0.1"), "set_voice_level_db", "get_voice_level_db", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/cutoff_hz", PROPERTY_HINT_RANGE, "1,16000,1"), "set_voice_cutoff_hz", "get_voice_cutoff_hz", 3);
+ ADD_PROPERTYI(PropertyInfo(Variant::REAL, "voice/4/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_voice_pan", "get_voice_pan", 3);
}
-AudioEffectChorus::AudioEffectChorus()
-{
- voice_count=2;
- voice[0].delay=15;
- voice[1].delay=20;
- voice[0].rate=0.8;
- voice[1].rate=1.2;
- voice[0].depth=2;
- voice[1].depth=3;
- voice[0].cutoff=8000;
- voice[1].cutoff=8000;
- voice[0].pan=-0.5;
- voice[1].pan=0.5;
-
- wet=0.5;
- dry=1.0;
+AudioEffectChorus::AudioEffectChorus() {
+ voice_count = 2;
+ voice[0].delay = 15;
+ voice[1].delay = 20;
+ voice[0].rate = 0.8;
+ voice[1].rate = 1.2;
+ voice[0].depth = 2;
+ voice[1].depth = 3;
+ voice[0].cutoff = 8000;
+ voice[1].cutoff = 8000;
+ voice[0].pan = -0.5;
+ voice[1].pan = 0.5;
+
+ wet = 0.5;
+ dry = 1.0;
}
diff --git a/servers/audio/effects/audio_effect_chorus.h b/servers/audio/effects/audio_effect_chorus.h
index ae0964bd53..9af9ab1b9a 100644
--- a/servers/audio/effects/audio_effect_chorus.h
+++ b/servers/audio/effects/audio_effect_chorus.h
@@ -29,14 +29,13 @@
#ifndef AUDIOEFFECTCHORUS_H
#define AUDIOEFFECTCHORUS_H
-
#include "servers/audio/audio_effect.h"
class AudioEffectChorus;
class AudioEffectChorusInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectChorusInstance,AudioEffectInstance)
-friend class AudioEffectChorus;
+ GDCLASS(AudioEffectChorusInstance, AudioEffectInstance)
+ friend class AudioEffectChorus;
Ref<AudioEffectChorus> base;
Vector<AudioFrame> audio_buffer;
@@ -46,34 +45,31 @@ friend class AudioEffectChorus;
AudioFrame filter_h[4];
uint64_t cycles[4];
- void _process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+ void _process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
-
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectChorus : public AudioEffect {
- GDCLASS(AudioEffectChorus,AudioEffect)
+ GDCLASS(AudioEffectChorus, AudioEffect)
+
+ friend class AudioEffectChorusInstance;
-friend class AudioEffectChorusInstance;
public:
enum {
- MAX_DELAY_MS=50,
- MAX_DEPTH_MS=20,
- MAX_WIDTH_MS=50,
- MAX_VOICES=4,
- CYCLES_FRAC=16,
- CYCLES_MASK=(1<<CYCLES_FRAC)-1,
- MAX_CHANNELS=4,
- MS_CUTOFF_MAX=16000
+ MAX_DELAY_MS = 50,
+ MAX_DEPTH_MS = 20,
+ MAX_WIDTH_MS = 50,
+ MAX_VOICES = 4,
+ CYCLES_FRAC = 16,
+ CYCLES_MASK = (1 << CYCLES_FRAC) - 1,
+ MAX_CHANNELS = 4,
+ MS_CUTOFF_MAX = 16000
};
private:
-
struct Voice {
float delay;
@@ -85,13 +81,12 @@ private:
Voice() {
- delay=12.0;
- rate=1;
- depth=0;
- level=0;
- cutoff=MS_CUTOFF_MAX;
- pan=0;
-
+ delay = 12.0;
+ rate = 1;
+ depth = 0;
+ level = 0;
+ cutoff = MS_CUTOFF_MAX;
+ pan = 0;
}
} voice[MAX_VOICES];
@@ -101,32 +96,31 @@ private:
float wet;
float dry;
-
protected:
- void _validate_property(PropertyInfo& property) const;
+ void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
+public:
void set_voice_count(int p_voices);
int get_voice_count() const;
- void set_voice_delay_ms(int p_voice,float p_delay_ms);
+ void set_voice_delay_ms(int p_voice, float p_delay_ms);
float get_voice_delay_ms(int p_voice) const;
- void set_voice_rate_hz(int p_voice,float p_rate_hz);
+ void set_voice_rate_hz(int p_voice, float p_rate_hz);
float get_voice_rate_hz(int p_voice) const;
- void set_voice_depth_ms(int p_voice,float p_depth_ms);
+ void set_voice_depth_ms(int p_voice, float p_depth_ms);
float get_voice_depth_ms(int p_voice) const;
- void set_voice_level_db(int p_voice,float p_level_db);
+ void set_voice_level_db(int p_voice, float p_level_db);
float get_voice_level_db(int p_voice) const;
- void set_voice_cutoff_hz(int p_voice,float p_cutoff_hz);
+ void set_voice_cutoff_hz(int p_voice, float p_cutoff_hz);
float get_voice_cutoff_hz(int p_voice) const;
- void set_voice_pan(int p_voice,float p_pan);
+ void set_voice_pan(int p_voice, float p_pan);
float get_voice_pan(int p_voice) const;
void set_wet(float amount);
diff --git a/servers/audio/effects/audio_effect_compressor.cpp b/servers/audio/effects/audio_effect_compressor.cpp
index c08302c58e..8b67353229 100644
--- a/servers/audio/effects/audio_effect_compressor.cpp
+++ b/servers/audio/effects/audio_effect_compressor.cpp
@@ -29,11 +29,10 @@
#include "audio_effect_compressor.h"
#include "servers/audio_server.h"
-void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
+void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
float treshold = Math::db2linear(base->treshold);
- float sample_rate=AudioServer::get_singleton()->get_mix_rate();
+ float sample_rate = AudioServer::get_singleton()->get_mix_rate();
float ratatcoef = exp(-1 / (0.00001f * sample_rate));
float ratrelcoef = exp(-1 / (0.5f * sample_rate));
@@ -49,35 +48,35 @@ void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,Audio
const AudioFrame *src = p_src_frames;
- if (base->sidechain!=StringName() && current_channel!=-1) {
+ if (base->sidechain != StringName() && current_channel != -1) {
int bus = AudioServer::get_singleton()->thread_find_bus_index(base->sidechain);
- if (bus>=0) {
- src = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus,current_channel);
+ if (bus >= 0) {
+ src = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus, current_channel);
}
}
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
AudioFrame s = src[i];
//convert to positive
s.l = Math::abs(s.l);
s.r = Math::abs(s.r);
- float peak = MAX(s.l,s.r);
+ float peak = MAX(s.l, s.r);
- float overdb = 2.08136898f * Math::linear2db(peak/treshold);
+ float overdb = 2.08136898f * Math::linear2db(peak / treshold);
- if (overdb<0.0) //we only care about what goes over to compress
- overdb=0.0;
+ if (overdb < 0.0) //we only care about what goes over to compress
+ overdb = 0.0;
- if(overdb-rundb>5) // diffeence is too large
+ if (overdb - rundb > 5) // diffeence is too large
averatio = 4;
- if(overdb > rundb) {
+ if (overdb > rundb) {
rundb = overdb + atcoef * (rundb - overdb);
runratio = averatio + ratatcoef * (runratio - averatio);
- } else {
+ } else {
rundb = overdb + relcoef * (rundb - overdb);
runratio = averatio + ratrelcoef * (runratio - averatio);
}
@@ -87,52 +86,47 @@ void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,Audio
float cratio;
- if(false) { //rato all-in
+ if (false) { //rato all-in
cratio = 12 + averatio;
} else {
cratio = base->ratio;
}
- float gr = -overdb * (cratio-1)/cratio;
+ float gr = -overdb * (cratio - 1) / cratio;
float grv = Math::db2linear(gr);
- runmax = maxover + relcoef * (runmax - maxover); // highest peak for setting att/rel decays in reltime
+ runmax = maxover + relcoef * (runmax - maxover); // highest peak for setting att/rel decays in reltime
maxover = runmax;
if (grv < gr_meter) {
- gr_meter=grv;
+ gr_meter = grv;
} else {
- gr_meter*=gr_meter_decay;
- if(gr_meter>1)
- gr_meter=1;
+ gr_meter *= gr_meter_decay;
+ if (gr_meter > 1)
+ gr_meter = 1;
}
-
- p_dst_frames[i] = p_src_frames[i] * grv * makeup * mix + p_src_frames[i] * (1.0-mix);
-
+ p_dst_frames[i] = p_src_frames[i] * grv * makeup * mix + p_src_frames[i] * (1.0 - mix);
}
-
}
-
Ref<AudioEffectInstance> AudioEffectCompressor::instance() {
Ref<AudioEffectCompressorInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectCompressor>(this);
- ins->rundb=0;
- ins->runratio=0;
- ins->averatio=0;
- ins->runmax=0;
- ins->maxover=0;
- ins->gr_meter=1.0;
- ins->current_channel=-1;
+ ins->base = Ref<AudioEffectCompressor>(this);
+ ins->rundb = 0;
+ ins->runratio = 0;
+ ins->averatio = 0;
+ ins->runmax = 0;
+ ins->maxover = 0;
+ ins->gr_meter = 1.0;
+ ins->current_channel = -1;
return ins;
}
-
void AudioEffectCompressor::set_treshold(float p_treshold) {
- treshold=p_treshold;
+ treshold = p_treshold;
}
float AudioEffectCompressor::get_treshold() const {
@@ -142,7 +136,7 @@ float AudioEffectCompressor::get_treshold() const {
void AudioEffectCompressor::set_ratio(float p_ratio) {
- ratio=p_ratio;
+ ratio = p_ratio;
}
float AudioEffectCompressor::get_ratio() const {
@@ -151,7 +145,7 @@ float AudioEffectCompressor::get_ratio() const {
void AudioEffectCompressor::set_gain(float p_gain) {
- gain=p_gain;
+ gain = p_gain;
}
float AudioEffectCompressor::get_gain() const {
@@ -160,7 +154,7 @@ float AudioEffectCompressor::get_gain() const {
void AudioEffectCompressor::set_attack_us(float p_attack_us) {
- attack_us=p_attack_us;
+ attack_us = p_attack_us;
}
float AudioEffectCompressor::get_attack_us() const {
@@ -169,7 +163,7 @@ float AudioEffectCompressor::get_attack_us() const {
void AudioEffectCompressor::set_release_ms(float p_release_ms) {
- release_ms=p_release_ms;
+ release_ms = p_release_ms;
}
float AudioEffectCompressor::get_release_ms() const {
@@ -178,17 +172,17 @@ float AudioEffectCompressor::get_release_ms() const {
void AudioEffectCompressor::set_mix(float p_mix) {
- mix=p_mix;
+ mix = p_mix;
}
float AudioEffectCompressor::get_mix() const {
return mix;
}
-void AudioEffectCompressor::set_sidechain(const StringName& p_sidechain) {
+void AudioEffectCompressor::set_sidechain(const StringName &p_sidechain) {
AudioServer::get_singleton()->lock();
- sidechain=p_sidechain;
+ sidechain = p_sidechain;
AudioServer::get_singleton()->unlock();
}
@@ -197,59 +191,57 @@ StringName AudioEffectCompressor::get_sidechain() const {
return sidechain;
}
-void AudioEffectCompressor::_validate_property(PropertyInfo& property) const {
+void AudioEffectCompressor::_validate_property(PropertyInfo &property) const {
- if (property.name=="sidechain") {
+ if (property.name == "sidechain") {
- String buses="";
- for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) {
- buses+=",";
- buses+=AudioServer::get_singleton()->get_bus_name(i);
+ String buses = "";
+ for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
+ buses += ",";
+ buses += AudioServer::get_singleton()->get_bus_name(i);
}
- property.hint_string=buses;
+ property.hint_string = buses;
}
}
void AudioEffectCompressor::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_treshold","treshold"),&AudioEffectCompressor::set_treshold);
- ClassDB::bind_method(D_METHOD("get_treshold"),&AudioEffectCompressor::get_treshold);
-
- ClassDB::bind_method(D_METHOD("set_ratio","ratio"),&AudioEffectCompressor::set_ratio);
- ClassDB::bind_method(D_METHOD("get_ratio"),&AudioEffectCompressor::get_ratio);
+ ClassDB::bind_method(D_METHOD("set_treshold", "treshold"), &AudioEffectCompressor::set_treshold);
+ ClassDB::bind_method(D_METHOD("get_treshold"), &AudioEffectCompressor::get_treshold);
- ClassDB::bind_method(D_METHOD("set_gain","gain"),&AudioEffectCompressor::set_gain);
- ClassDB::bind_method(D_METHOD("get_gain"),&AudioEffectCompressor::get_gain);
+ ClassDB::bind_method(D_METHOD("set_ratio", "ratio"), &AudioEffectCompressor::set_ratio);
+ ClassDB::bind_method(D_METHOD("get_ratio"), &AudioEffectCompressor::get_ratio);
- ClassDB::bind_method(D_METHOD("set_attack_us","attack_us"),&AudioEffectCompressor::set_attack_us);
- ClassDB::bind_method(D_METHOD("get_attack_us"),&AudioEffectCompressor::get_attack_us);
+ ClassDB::bind_method(D_METHOD("set_gain", "gain"), &AudioEffectCompressor::set_gain);
+ ClassDB::bind_method(D_METHOD("get_gain"), &AudioEffectCompressor::get_gain);
- ClassDB::bind_method(D_METHOD("set_release_ms","release_ms"),&AudioEffectCompressor::set_release_ms);
- ClassDB::bind_method(D_METHOD("get_release_ms"),&AudioEffectCompressor::get_release_ms);
+ ClassDB::bind_method(D_METHOD("set_attack_us", "attack_us"), &AudioEffectCompressor::set_attack_us);
+ ClassDB::bind_method(D_METHOD("get_attack_us"), &AudioEffectCompressor::get_attack_us);
- ClassDB::bind_method(D_METHOD("set_mix","mix"),&AudioEffectCompressor::set_mix);
- ClassDB::bind_method(D_METHOD("get_mix"),&AudioEffectCompressor::get_mix);
+ ClassDB::bind_method(D_METHOD("set_release_ms", "release_ms"), &AudioEffectCompressor::set_release_ms);
+ ClassDB::bind_method(D_METHOD("get_release_ms"), &AudioEffectCompressor::get_release_ms);
- ClassDB::bind_method(D_METHOD("set_sidechain","sidechain"),&AudioEffectCompressor::set_sidechain);
- ClassDB::bind_method(D_METHOD("get_sidechain"),&AudioEffectCompressor::get_sidechain);
+ ClassDB::bind_method(D_METHOD("set_mix", "mix"), &AudioEffectCompressor::set_mix);
+ ClassDB::bind_method(D_METHOD("get_mix"), &AudioEffectCompressor::get_mix);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold",PROPERTY_HINT_RANGE,"-60,0,0.1"),"set_treshold","get_treshold");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ratio",PROPERTY_HINT_RANGE,"1,48,0.1"),"set_ratio","get_ratio");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"-20,20,0.1"),"set_gain","get_gain");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"attack_us",PROPERTY_HINT_RANGE,"20,2000,1"),"set_attack_us","get_attack_us");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"release_ms",PROPERTY_HINT_RANGE,"20,2000,1"),"set_release_ms","get_release_ms");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"mix",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_mix","get_mix");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"sidechain",PROPERTY_HINT_ENUM),"set_sidechain","get_sidechain");
+ ClassDB::bind_method(D_METHOD("set_sidechain", "sidechain"), &AudioEffectCompressor::set_sidechain);
+ ClassDB::bind_method(D_METHOD("get_sidechain"), &AudioEffectCompressor::get_sidechain);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "treshold", PROPERTY_HINT_RANGE, "-60,0,0.1"), "set_treshold", "get_treshold");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ratio", PROPERTY_HINT_RANGE, "1,48,0.1"), "set_ratio", "get_ratio");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gain", PROPERTY_HINT_RANGE, "-20,20,0.1"), "set_gain", "get_gain");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "attack_us", PROPERTY_HINT_RANGE, "20,2000,1"), "set_attack_us", "get_attack_us");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "release_ms", PROPERTY_HINT_RANGE, "20,2000,1"), "set_release_ms", "get_release_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "mix", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_mix", "get_mix");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "sidechain", PROPERTY_HINT_ENUM), "set_sidechain", "get_sidechain");
}
-AudioEffectCompressor::AudioEffectCompressor()
-{
- treshold=0;
- ratio=4;
- gain=0;
- attack_us=20;
- release_ms=250;
- mix=1;
+AudioEffectCompressor::AudioEffectCompressor() {
+ treshold = 0;
+ ratio = 4;
+ gain = 0;
+ attack_us = 20;
+ release_ms = 250;
+ mix = 1;
}
diff --git a/servers/audio/effects/audio_effect_compressor.h b/servers/audio/effects/audio_effect_compressor.h
index 3988ad1526..34f80348db 100644
--- a/servers/audio/effects/audio_effect_compressor.h
+++ b/servers/audio/effects/audio_effect_compressor.h
@@ -29,30 +29,27 @@
#ifndef AUDIOEFFECTCOMPRESSOR_H
#define AUDIOEFFECTCOMPRESSOR_H
-
#include "servers/audio/audio_effect.h"
class AudioEffectCompressor;
class AudioEffectCompressorInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectCompressorInstance,AudioEffectInstance)
-friend class AudioEffectCompressor;
+ GDCLASS(AudioEffectCompressorInstance, AudioEffectInstance)
+ friend class AudioEffectCompressor;
Ref<AudioEffectCompressor> base;
- float rundb,averatio,runratio,runmax,maxover,gr_meter;
+ float rundb, averatio, runratio, runmax, maxover, gr_meter;
int current_channel;
-public:
-
- void set_current_channel(int p_channel) { current_channel=p_channel; }
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ void set_current_channel(int p_channel) { current_channel = p_channel; }
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectCompressor : public AudioEffect {
- GDCLASS(AudioEffectCompressor,AudioEffect)
+ GDCLASS(AudioEffectCompressor, AudioEffect)
-friend class AudioEffectCompressorInstance;
+ friend class AudioEffectCompressorInstance;
float treshold;
float ratio;
float gain;
@@ -61,16 +58,13 @@ friend class AudioEffectCompressorInstance;
float mix;
StringName sidechain;
-
protected:
- void _validate_property(PropertyInfo& property) const;
+ void _validate_property(PropertyInfo &property) const;
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
-
void set_treshold(float p_treshold);
float get_treshold() const;
@@ -89,7 +83,7 @@ public:
void set_mix(float p_mix);
float get_mix() const;
- void set_sidechain(const StringName& p_sidechain);
+ void set_sidechain(const StringName &p_sidechain);
StringName get_sidechain() const;
AudioEffectCompressor();
diff --git a/servers/audio/effects/audio_effect_delay.cpp b/servers/audio/effects/audio_effect_delay.cpp
index a6d2048896..b643f801a7 100644
--- a/servers/audio/effects/audio_effect_delay.cpp
+++ b/servers/audio/effects/audio_effect_delay.cpp
@@ -27,328 +27,315 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "audio_effect_delay.h"
-#include "servers/audio_server.h"
#include "math_funcs.h"
+#include "servers/audio_server.h"
-void AudioEffectDelayInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectDelayInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
int todo = p_frame_count;
- while(todo) {
+ while (todo) {
- int to_mix = MIN(todo,256); //can't mix too much
+ int to_mix = MIN(todo, 256); //can't mix too much
- _process_chunk(p_src_frames,p_dst_frames,to_mix);
+ _process_chunk(p_src_frames, p_dst_frames, to_mix);
- p_src_frames+=to_mix;
- p_dst_frames+=to_mix;
+ p_src_frames += to_mix;
+ p_dst_frames += to_mix;
- todo-=to_mix;
+ todo -= to_mix;
}
}
-void AudioEffectDelayInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
-
-
- float main_level_f=base->dry;
+void AudioEffectDelayInstance::_process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
+ float main_level_f = base->dry;
float mix_rate = AudioServer::get_singleton()->get_mix_rate();
- float tap_1_level_f=base->tap_1_active?Math::db2linear(base->tap_1_level):0.0;
- int tap_1_delay_frames=int((base->tap_1_delay_ms/1000.0)*mix_rate);;
+ float tap_1_level_f = base->tap_1_active ? Math::db2linear(base->tap_1_level) : 0.0;
+ int tap_1_delay_frames = int((base->tap_1_delay_ms / 1000.0) * mix_rate);
+ ;
- float tap_2_level_f=base->tap_2_active?Math::db2linear(base->tap_2_level):0.0;
- int tap_2_delay_frames=int((base->tap_2_delay_ms/1000.0)*mix_rate);;
+ float tap_2_level_f = base->tap_2_active ? Math::db2linear(base->tap_2_level) : 0.0;
+ int tap_2_delay_frames = int((base->tap_2_delay_ms / 1000.0) * mix_rate);
+ ;
- float feedback_level_f=base->feedback_active?Math::db2linear(base->feedback_level):0.0;
- unsigned int feedback_delay_frames=int((base->feedback_delay_ms/1000.0)*mix_rate);;
+ float feedback_level_f = base->feedback_active ? Math::db2linear(base->feedback_level) : 0.0;
+ unsigned int feedback_delay_frames = int((base->feedback_delay_ms / 1000.0) * mix_rate);
+ ;
+ AudioFrame tap1_vol = AudioFrame(tap_1_level_f, tap_1_level_f);
- AudioFrame tap1_vol=AudioFrame(tap_1_level_f,tap_1_level_f);
+ tap1_vol.l *= CLAMP(1.0 - base->tap_1_pan, 0, 1);
+ tap1_vol.r *= CLAMP(1.0 + base->tap_1_pan, 0, 1);
- tap1_vol.l*=CLAMP( 1.0 - base->tap_1_pan, 0, 1);
- tap1_vol.r*=CLAMP( 1.0 + base->tap_1_pan, 0, 1);
+ AudioFrame tap2_vol = AudioFrame(tap_2_level_f, tap_2_level_f);
- AudioFrame tap2_vol=AudioFrame(tap_2_level_f,tap_2_level_f);
-
- tap2_vol.l*=CLAMP( 1.0 - base->tap_2_pan, 0, 1);
- tap2_vol.r*=CLAMP( 1.0 + base->tap_2_pan, 0, 1);
+ tap2_vol.l *= CLAMP(1.0 - base->tap_2_pan, 0, 1);
+ tap2_vol.r *= CLAMP(1.0 + base->tap_2_pan, 0, 1);
// feedback lowpass here
- float lpf_c=expf(-2.0*Math_PI*base->feedback_lowpass/mix_rate); // 0 .. 10khz
- float lpf_ic=1.0-lpf_c;
-
- const AudioFrame *src=p_src_frames;
- AudioFrame *dst=p_dst_frames;
- AudioFrame *rb_buf=ring_buffer.ptr();
- AudioFrame *fb_buf=feedback_buffer.ptr();
+ float lpf_c = expf(-2.0 * Math_PI * base->feedback_lowpass / mix_rate); // 0 .. 10khz
+ float lpf_ic = 1.0 - lpf_c;
+ const AudioFrame *src = p_src_frames;
+ AudioFrame *dst = p_dst_frames;
+ AudioFrame *rb_buf = ring_buffer.ptr();
+ AudioFrame *fb_buf = feedback_buffer.ptr();
- for (int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
+ rb_buf[ring_buffer_pos & ring_buffer_mask] = src[i];
- rb_buf[ring_buffer_pos&ring_buffer_mask]=src[i];
+ AudioFrame main_val = src[i] * main_level_f;
+ AudioFrame tap_1_val = rb_buf[(ring_buffer_pos - tap_1_delay_frames) & ring_buffer_mask] * tap1_vol;
+ AudioFrame tap_2_val = rb_buf[(ring_buffer_pos - tap_2_delay_frames) & ring_buffer_mask] * tap2_vol;
- AudioFrame main_val=src[i]*main_level_f;
- AudioFrame tap_1_val=rb_buf[(ring_buffer_pos-tap_1_delay_frames)&ring_buffer_mask]*tap1_vol;
- AudioFrame tap_2_val=rb_buf[(ring_buffer_pos-tap_2_delay_frames)&ring_buffer_mask]*tap2_vol;
+ AudioFrame out = main_val + tap_1_val + tap_2_val;
- AudioFrame out=main_val+tap_1_val+tap_2_val;
-
- out+=fb_buf[ feedback_buffer_pos ];
+ out += fb_buf[feedback_buffer_pos];
//apply lowpass and feedback gain
- AudioFrame fb_in=out*feedback_level_f*lpf_ic+h*lpf_c;
+ AudioFrame fb_in = out * feedback_level_f * lpf_ic + h * lpf_c;
fb_in.undenormalise(); //avoid denormals
- h=fb_in;
- fb_buf[ feedback_buffer_pos ]=fb_in;
+ h = fb_in;
+ fb_buf[feedback_buffer_pos] = fb_in;
- dst[i]=out;
+ dst[i] = out;
ring_buffer_pos++;
- if ( (++feedback_buffer_pos) >= feedback_delay_frames )
- feedback_buffer_pos=0;
+ if ((++feedback_buffer_pos) >= feedback_delay_frames)
+ feedback_buffer_pos = 0;
}
}
-
-
Ref<AudioEffectInstance> AudioEffectDelay::instance() {
Ref<AudioEffectDelayInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectDelay>(this);
+ ins->base = Ref<AudioEffectDelay>(this);
- float ring_buffer_max_size=MAX_DELAY_MS+100; //add 100ms of extra room, just in case
- ring_buffer_max_size/=1000.0;//convert to seconds
- ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate();
+ float ring_buffer_max_size = MAX_DELAY_MS + 100; //add 100ms of extra room, just in case
+ ring_buffer_max_size /= 1000.0; //convert to seconds
+ ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate();
- int ringbuff_size=ring_buffer_max_size;
+ int ringbuff_size = ring_buffer_max_size;
- int bits=0;
+ int bits = 0;
- while(ringbuff_size>0) {
+ while (ringbuff_size > 0) {
bits++;
- ringbuff_size/=2;
+ ringbuff_size /= 2;
}
- ringbuff_size=1<<bits;
- ins->ring_buffer_mask=ringbuff_size-1;
- ins->ring_buffer_pos=0;
+ ringbuff_size = 1 << bits;
+ ins->ring_buffer_mask = ringbuff_size - 1;
+ ins->ring_buffer_pos = 0;
- ins->ring_buffer.resize( ringbuff_size );
- ins->feedback_buffer.resize( ringbuff_size );
+ ins->ring_buffer.resize(ringbuff_size);
+ ins->feedback_buffer.resize(ringbuff_size);
- ins->feedback_buffer_pos=0;
+ ins->feedback_buffer_pos = 0;
- ins->h=AudioFrame(0,0);
+ ins->h = AudioFrame(0, 0);
return ins;
}
-
void AudioEffectDelay::set_dry(float p_dry) {
- dry=p_dry;
+ dry = p_dry;
}
-float AudioEffectDelay::get_dry(){
+float AudioEffectDelay::get_dry() {
return dry;
}
-void AudioEffectDelay::set_tap1_active(bool p_active){
+void AudioEffectDelay::set_tap1_active(bool p_active) {
- tap_1_active=p_active;
+ tap_1_active = p_active;
}
-bool AudioEffectDelay::is_tap1_active() const{
+bool AudioEffectDelay::is_tap1_active() const {
return tap_1_active;
}
-void AudioEffectDelay::set_tap1_delay_ms(float p_delay_ms){
+void AudioEffectDelay::set_tap1_delay_ms(float p_delay_ms) {
- tap_1_delay_ms=p_delay_ms;
+ tap_1_delay_ms = p_delay_ms;
}
-float AudioEffectDelay::get_tap1_delay_ms() const{
+float AudioEffectDelay::get_tap1_delay_ms() const {
return tap_1_delay_ms;
}
-void AudioEffectDelay::set_tap1_level_db(float p_level_db){
+void AudioEffectDelay::set_tap1_level_db(float p_level_db) {
- tap_1_level=p_level_db;
+ tap_1_level = p_level_db;
}
-float AudioEffectDelay::get_tap1_level_db() const{
+float AudioEffectDelay::get_tap1_level_db() const {
return tap_1_level;
}
-void AudioEffectDelay::set_tap1_pan(float p_pan){
+void AudioEffectDelay::set_tap1_pan(float p_pan) {
- tap_1_pan=p_pan;
+ tap_1_pan = p_pan;
}
-float AudioEffectDelay::get_tap1_pan() const{
+float AudioEffectDelay::get_tap1_pan() const {
return tap_1_pan;
}
+void AudioEffectDelay::set_tap2_active(bool p_active) {
-void AudioEffectDelay::set_tap2_active(bool p_active){
-
- tap_2_active=p_active;
+ tap_2_active = p_active;
}
-bool AudioEffectDelay::is_tap2_active() const{
+bool AudioEffectDelay::is_tap2_active() const {
return tap_2_active;
}
-void AudioEffectDelay::set_tap2_delay_ms(float p_delay_ms){
+void AudioEffectDelay::set_tap2_delay_ms(float p_delay_ms) {
- tap_2_delay_ms=p_delay_ms;
+ tap_2_delay_ms = p_delay_ms;
}
-float AudioEffectDelay::get_tap2_delay_ms() const{
+float AudioEffectDelay::get_tap2_delay_ms() const {
return tap_2_delay_ms;
}
-void AudioEffectDelay::set_tap2_level_db(float p_level_db){
+void AudioEffectDelay::set_tap2_level_db(float p_level_db) {
- tap_2_level=p_level_db;
+ tap_2_level = p_level_db;
}
-float AudioEffectDelay::get_tap2_level_db() const{
+float AudioEffectDelay::get_tap2_level_db() const {
return tap_2_level;
}
-void AudioEffectDelay::set_tap2_pan(float p_pan){
+void AudioEffectDelay::set_tap2_pan(float p_pan) {
- tap_2_pan=p_pan;
+ tap_2_pan = p_pan;
}
-float AudioEffectDelay::get_tap2_pan() const{
+float AudioEffectDelay::get_tap2_pan() const {
return tap_2_pan;
}
-void AudioEffectDelay::set_feedback_active(bool p_active){
+void AudioEffectDelay::set_feedback_active(bool p_active) {
- feedback_active=p_active;
+ feedback_active = p_active;
}
-bool AudioEffectDelay::is_feedback_active() const{
+bool AudioEffectDelay::is_feedback_active() const {
return feedback_active;
}
-void AudioEffectDelay::set_feedback_delay_ms(float p_delay_ms){
+void AudioEffectDelay::set_feedback_delay_ms(float p_delay_ms) {
- feedback_delay_ms=p_delay_ms;
+ feedback_delay_ms = p_delay_ms;
}
-float AudioEffectDelay::get_feedback_delay_ms() const{
+float AudioEffectDelay::get_feedback_delay_ms() const {
return feedback_delay_ms;
}
-void AudioEffectDelay::set_feedback_level_db(float p_level_db){
+void AudioEffectDelay::set_feedback_level_db(float p_level_db) {
- feedback_level=p_level_db;
+ feedback_level = p_level_db;
}
-float AudioEffectDelay::get_feedback_level_db() const{
+float AudioEffectDelay::get_feedback_level_db() const {
return feedback_level;
}
-void AudioEffectDelay::set_feedback_lowpass(float p_lowpass){
+void AudioEffectDelay::set_feedback_lowpass(float p_lowpass) {
- feedback_lowpass=p_lowpass;
+ feedback_lowpass = p_lowpass;
}
-float AudioEffectDelay::get_feedback_lowpass() const{
+float AudioEffectDelay::get_feedback_lowpass() const {
return feedback_lowpass;
}
-
void AudioEffectDelay::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectDelay::set_dry);
- ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectDelay::get_dry);
+ ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectDelay::set_dry);
+ ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectDelay::get_dry);
- ClassDB::bind_method(D_METHOD("set_tap1_active","amount"),&AudioEffectDelay::set_tap1_active);
- ClassDB::bind_method(D_METHOD("is_tap1_active"),&AudioEffectDelay::is_tap1_active);
+ ClassDB::bind_method(D_METHOD("set_tap1_active", "amount"), &AudioEffectDelay::set_tap1_active);
+ ClassDB::bind_method(D_METHOD("is_tap1_active"), &AudioEffectDelay::is_tap1_active);
- ClassDB::bind_method(D_METHOD("set_tap1_delay_ms","amount"),&AudioEffectDelay::set_tap1_delay_ms);
- ClassDB::bind_method(D_METHOD("get_tap1_delay_ms"),&AudioEffectDelay::get_tap1_delay_ms);
+ ClassDB::bind_method(D_METHOD("set_tap1_delay_ms", "amount"), &AudioEffectDelay::set_tap1_delay_ms);
+ ClassDB::bind_method(D_METHOD("get_tap1_delay_ms"), &AudioEffectDelay::get_tap1_delay_ms);
- ClassDB::bind_method(D_METHOD("set_tap1_level_db","amount"),&AudioEffectDelay::set_tap1_level_db);
- ClassDB::bind_method(D_METHOD("get_tap1_level_db"),&AudioEffectDelay::get_tap1_level_db);
+ ClassDB::bind_method(D_METHOD("set_tap1_level_db", "amount"), &AudioEffectDelay::set_tap1_level_db);
+ ClassDB::bind_method(D_METHOD("get_tap1_level_db"), &AudioEffectDelay::get_tap1_level_db);
- ClassDB::bind_method(D_METHOD("set_tap1_pan","amount"),&AudioEffectDelay::set_tap1_pan);
- ClassDB::bind_method(D_METHOD("get_tap1_pan"),&AudioEffectDelay::get_tap1_pan);
+ ClassDB::bind_method(D_METHOD("set_tap1_pan", "amount"), &AudioEffectDelay::set_tap1_pan);
+ ClassDB::bind_method(D_METHOD("get_tap1_pan"), &AudioEffectDelay::get_tap1_pan);
- ClassDB::bind_method(D_METHOD("set_tap2_active","amount"),&AudioEffectDelay::set_tap2_active);
- ClassDB::bind_method(D_METHOD("is_tap2_active"),&AudioEffectDelay::is_tap2_active);
+ ClassDB::bind_method(D_METHOD("set_tap2_active", "amount"), &AudioEffectDelay::set_tap2_active);
+ ClassDB::bind_method(D_METHOD("is_tap2_active"), &AudioEffectDelay::is_tap2_active);
- ClassDB::bind_method(D_METHOD("set_tap2_delay_ms","amount"),&AudioEffectDelay::set_tap2_delay_ms);
- ClassDB::bind_method(D_METHOD("get_tap2_delay_ms"),&AudioEffectDelay::get_tap2_delay_ms);
+ ClassDB::bind_method(D_METHOD("set_tap2_delay_ms", "amount"), &AudioEffectDelay::set_tap2_delay_ms);
+ ClassDB::bind_method(D_METHOD("get_tap2_delay_ms"), &AudioEffectDelay::get_tap2_delay_ms);
- ClassDB::bind_method(D_METHOD("set_tap2_level_db","amount"),&AudioEffectDelay::set_tap2_level_db);
- ClassDB::bind_method(D_METHOD("get_tap2_level_db"),&AudioEffectDelay::get_tap2_level_db);
+ ClassDB::bind_method(D_METHOD("set_tap2_level_db", "amount"), &AudioEffectDelay::set_tap2_level_db);
+ ClassDB::bind_method(D_METHOD("get_tap2_level_db"), &AudioEffectDelay::get_tap2_level_db);
- ClassDB::bind_method(D_METHOD("set_tap2_pan","amount"),&AudioEffectDelay::set_tap2_pan);
- ClassDB::bind_method(D_METHOD("get_tap2_pan"),&AudioEffectDelay::get_tap2_pan);
+ ClassDB::bind_method(D_METHOD("set_tap2_pan", "amount"), &AudioEffectDelay::set_tap2_pan);
+ ClassDB::bind_method(D_METHOD("get_tap2_pan"), &AudioEffectDelay::get_tap2_pan);
+ ClassDB::bind_method(D_METHOD("set_feedback_active", "amount"), &AudioEffectDelay::set_feedback_active);
+ ClassDB::bind_method(D_METHOD("is_feedback_active"), &AudioEffectDelay::is_feedback_active);
- ClassDB::bind_method(D_METHOD("set_feedback_active","amount"),&AudioEffectDelay::set_feedback_active);
- ClassDB::bind_method(D_METHOD("is_feedback_active"),&AudioEffectDelay::is_feedback_active);
+ ClassDB::bind_method(D_METHOD("set_feedback_delay_ms", "amount"), &AudioEffectDelay::set_feedback_delay_ms);
+ ClassDB::bind_method(D_METHOD("get_feedback_delay_ms"), &AudioEffectDelay::get_feedback_delay_ms);
- ClassDB::bind_method(D_METHOD("set_feedback_delay_ms","amount"),&AudioEffectDelay::set_feedback_delay_ms);
- ClassDB::bind_method(D_METHOD("get_feedback_delay_ms"),&AudioEffectDelay::get_feedback_delay_ms);
+ ClassDB::bind_method(D_METHOD("set_feedback_level_db", "amount"), &AudioEffectDelay::set_feedback_level_db);
+ ClassDB::bind_method(D_METHOD("get_feedback_level_db"), &AudioEffectDelay::get_feedback_level_db);
- ClassDB::bind_method(D_METHOD("set_feedback_level_db","amount"),&AudioEffectDelay::set_feedback_level_db);
- ClassDB::bind_method(D_METHOD("get_feedback_level_db"),&AudioEffectDelay::get_feedback_level_db);
+ ClassDB::bind_method(D_METHOD("set_feedback_lowpass", "amount"), &AudioEffectDelay::set_feedback_lowpass);
+ ClassDB::bind_method(D_METHOD("get_feedback_lowpass"), &AudioEffectDelay::get_feedback_lowpass);
- ClassDB::bind_method(D_METHOD("set_feedback_lowpass","amount"),&AudioEffectDelay::set_feedback_lowpass);
- ClassDB::bind_method(D_METHOD("get_feedback_lowpass"),&AudioEffectDelay::get_feedback_lowpass);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry");
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap1/active"),"set_tap1_active","is_tap1_active");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_tap1_delay_ms","get_tap1_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_tap1_level_db","get_tap1_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_tap1_pan","get_tap1_pan");
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap2/active"),"set_tap2_active","is_tap2_active");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_tap2_delay_ms","get_tap2_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_tap2_level_db","get_tap2_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_tap2_pan","get_tap2_pan");
-
- ADD_PROPERTY(PropertyInfo(Variant::BOOL,"feedback/active"),"set_feedback_active","is_feedback_active");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),"set_feedback_delay_ms","get_feedback_delay_ms");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),"set_feedback_level_db","get_feedback_level_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/lowpass",PROPERTY_HINT_RANGE,"1,16000,1"),"set_feedback_lowpass","get_feedback_lowpass");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap1/active"), "set_tap1_active", "is_tap1_active");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_tap1_delay_ms", "get_tap1_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_tap1_level_db", "get_tap1_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap1/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap1_pan", "get_tap1_pan");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "tap2/active"), "set_tap2_active", "is_tap2_active");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_tap2_delay_ms", "get_tap2_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_tap2_level_db", "get_tap2_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "tap2/pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_tap2_pan", "get_tap2_pan");
+ ADD_PROPERTY(PropertyInfo(Variant::BOOL, "feedback/active"), "set_feedback_active", "is_feedback_active");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/delay_ms", PROPERTY_HINT_RANGE, "0,1500,1"), "set_feedback_delay_ms", "get_feedback_delay_ms");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/level_db", PROPERTY_HINT_RANGE, "-60,0,0.01"), "set_feedback_level_db", "get_feedback_level_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback/lowpass", PROPERTY_HINT_RANGE, "1,16000,1"), "set_feedback_lowpass", "get_feedback_lowpass");
}
-AudioEffectDelay::AudioEffectDelay()
-{
- tap_1_active=true;
- tap_1_delay_ms=250;
- tap_1_level=-6;
- tap_1_pan=0.2;
-
- tap_2_active=true;
- tap_2_delay_ms=500;
- tap_2_level=-12;
- tap_2_pan=-0.4;
+AudioEffectDelay::AudioEffectDelay() {
+ tap_1_active = true;
+ tap_1_delay_ms = 250;
+ tap_1_level = -6;
+ tap_1_pan = 0.2;
- feedback_active=false;
- feedback_delay_ms=340;
- feedback_level=-6;
- feedback_lowpass=16000;
+ tap_2_active = true;
+ tap_2_delay_ms = 500;
+ tap_2_level = -12;
+ tap_2_pan = -0.4;
- dry=1.0;
+ feedback_active = false;
+ feedback_delay_ms = 340;
+ feedback_level = -6;
+ feedback_lowpass = 16000;
+ dry = 1.0;
}
diff --git a/servers/audio/effects/audio_effect_delay.h b/servers/audio/effects/audio_effect_delay.h
index 3e9f7f0584..247fddac00 100644
--- a/servers/audio/effects/audio_effect_delay.h
+++ b/servers/audio/effects/audio_effect_delay.h
@@ -34,8 +34,8 @@
class AudioEffectDelay;
class AudioEffectDelayInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectDelayInstance,AudioEffectInstance)
-friend class AudioEffectDelay;
+ GDCLASS(AudioEffectDelayInstance, AudioEffectInstance)
+ friend class AudioEffectDelay;
Ref<AudioEffectDelay> base;
Vector<AudioFrame> ring_buffer;
@@ -49,23 +49,20 @@ friend class AudioEffectDelay;
unsigned int feedback_buffer_pos;
AudioFrame h;
- void _process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+ void _process_chunk(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
-
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectDelay : public AudioEffect {
- GDCLASS(AudioEffectDelay,AudioEffect)
+ GDCLASS(AudioEffectDelay, AudioEffect)
-friend class AudioEffectDelayInstance;
+ friend class AudioEffectDelayInstance;
enum {
- MAX_DELAY_MS=3000,
- MAX_TAPS=2
+ MAX_DELAY_MS = 3000,
+ MAX_TAPS = 2
};
float dry;
@@ -85,13 +82,10 @@ friend class AudioEffectDelayInstance;
float feedback_level;
float feedback_lowpass;
-
-
protected:
-
static void _bind_methods();
-public:
+public:
void set_dry(float p_dry);
float get_dry();
@@ -136,5 +130,4 @@ public:
AudioEffectDelay();
};
-
#endif // AUDIOEFFECTDELAY_H
diff --git a/servers/audio/effects/audio_effect_distortion.cpp b/servers/audio/effects/audio_effect_distortion.cpp
index b72cd8e0a6..e5430fcd21 100644
--- a/servers/audio/effects/audio_effect_distortion.cpp
+++ b/servers/audio/effects/audio_effect_distortion.cpp
@@ -27,173 +27,159 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "audio_effect_distortion.h"
-#include "servers/audio_server.h"
#include "math_funcs.h"
+#include "servers/audio_server.h"
+void AudioEffectDistortionInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
-
-void AudioEffectDistortionInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
- const float *src = (const float*)p_src_frames;
- float *dst = (float*)p_dst_frames;
+ const float *src = (const float *)p_src_frames;
+ float *dst = (float *)p_dst_frames;
//float lpf_c=expf(-2.0*Math_PI*keep_hf_hz.get()/(mix_rate*(float)OVERSAMPLE));
- float lpf_c=expf(-2.0*Math_PI*base->keep_hf_hz/(AudioServer::get_singleton()->get_mix_rate()));
- float lpf_ic=1.0-lpf_c;
+ float lpf_c = expf(-2.0 * Math_PI * base->keep_hf_hz / (AudioServer::get_singleton()->get_mix_rate()));
+ float lpf_ic = 1.0 - lpf_c;
- float drive_f=base->drive;
- float pregain_f=Math::db2linear(base->pre_gain);
- float postgain_f=Math::db2linear(base->post_gain);
+ float drive_f = base->drive;
+ float pregain_f = Math::db2linear(base->pre_gain);
+ float postgain_f = Math::db2linear(base->post_gain);
- float atan_mult=pow(10,drive_f*drive_f*3.0)-1.0+0.001;
- float atan_div=1.0/(atanf(atan_mult)*(1.0+drive_f*8));
+ float atan_mult = pow(10, drive_f * drive_f * 3.0) - 1.0 + 0.001;
+ float atan_div = 1.0 / (atanf(atan_mult) * (1.0 + drive_f * 8));
- float lofi_mult=powf(2.0,2.0+(1.0-drive_f)*14); //goes from 16 to 2 bits
+ float lofi_mult = powf(2.0, 2.0 + (1.0 - drive_f) * 14); //goes from 16 to 2 bits
- for (int i=0;i<p_frame_count*2;i++) {
+ for (int i = 0; i < p_frame_count * 2; i++) {
- float out=undenormalise(src[i]*lpf_ic+lpf_c*h[i&1]);
- h[i&1]=out;
- float a=out;
- float ha=src[i]-out; //high freqs
- a*=pregain_f;
+ float out = undenormalise(src[i] * lpf_ic + lpf_c * h[i & 1]);
+ h[i & 1] = out;
+ float a = out;
+ float ha = src[i] - out; //high freqs
+ a *= pregain_f;
switch (base->mode) {
case AudioEffectDistortion::MODE_CLIP: {
- a=powf(a,1.0001-drive_f);
- if (a>1.0)
- a=1.0;
- else if (a<(-1.0))
- a=-1.0;
+ a = powf(a, 1.0001 - drive_f);
+ if (a > 1.0)
+ a = 1.0;
+ else if (a < (-1.0))
+ a = -1.0;
} break;
case AudioEffectDistortion::MODE_ATAN: {
-
- a=atanf(a*atan_mult)*atan_div;
+ a = atanf(a * atan_mult) * atan_div;
} break;
case AudioEffectDistortion::MODE_LOFI: {
- a = floorf(a*lofi_mult+0.5)/lofi_mult;
+ a = floorf(a * lofi_mult + 0.5) / lofi_mult;
} break;
case AudioEffectDistortion::MODE_OVERDRIVE: {
-
const double x = a * 0.686306;
- const double z = 1 + exp (sqrt (fabs (x)) * -0.75);
+ const double z = 1 + exp(sqrt(fabs(x)) * -0.75);
a = (expf(x) - expf(-x * z)) / (expf(x) + expf(-x));
} break;
case AudioEffectDistortion::MODE_WAVESHAPE: {
float x = a;
- float k= 2*drive_f/(1.00001-drive_f);
-
- a = (1.0+k)*x/(1.0+k*fabsf(x));
+ float k = 2 * drive_f / (1.00001 - drive_f);
+ a = (1.0 + k) * x / (1.0 + k * fabsf(x));
} break;
}
- dst[i]=a*postgain_f+ha;
-
+ dst[i] = a * postgain_f + ha;
}
-
-
}
-
Ref<AudioEffectInstance> AudioEffectDistortion::instance() {
Ref<AudioEffectDistortionInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectDistortion>(this);
- ins->h[0]=0;
- ins->h[1]=0;
+ ins->base = Ref<AudioEffectDistortion>(this);
+ ins->h[0] = 0;
+ ins->h[1] = 0;
return ins;
}
-
void AudioEffectDistortion::set_mode(Mode p_mode) {
- mode=p_mode;
+ mode = p_mode;
}
-AudioEffectDistortion::Mode AudioEffectDistortion::get_mode() const{
+AudioEffectDistortion::Mode AudioEffectDistortion::get_mode() const {
return mode;
}
-void AudioEffectDistortion::set_pre_gain(float p_pre_gain){
+void AudioEffectDistortion::set_pre_gain(float p_pre_gain) {
- pre_gain=p_pre_gain;
+ pre_gain = p_pre_gain;
}
-float AudioEffectDistortion::get_pre_gain() const{
+float AudioEffectDistortion::get_pre_gain() const {
return pre_gain;
}
-void AudioEffectDistortion::set_keep_hf_hz(float p_keep_hf_hz){
+void AudioEffectDistortion::set_keep_hf_hz(float p_keep_hf_hz) {
- keep_hf_hz=p_keep_hf_hz;
+ keep_hf_hz = p_keep_hf_hz;
}
-float AudioEffectDistortion::get_keep_hf_hz() const{
+float AudioEffectDistortion::get_keep_hf_hz() const {
return keep_hf_hz;
}
-void AudioEffectDistortion::set_drive(float p_drive){
+void AudioEffectDistortion::set_drive(float p_drive) {
- drive=p_drive;
+ drive = p_drive;
}
-float AudioEffectDistortion::get_drive() const{
+float AudioEffectDistortion::get_drive() const {
return drive;
}
-void AudioEffectDistortion::set_post_gain(float p_post_gain){
+void AudioEffectDistortion::set_post_gain(float p_post_gain) {
- post_gain=p_post_gain;
+ post_gain = p_post_gain;
}
-float AudioEffectDistortion::get_post_gain() const{
+float AudioEffectDistortion::get_post_gain() const {
return post_gain;
}
-
void AudioEffectDistortion::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_mode","mode"),&AudioEffectDistortion::set_mode);
- ClassDB::bind_method(D_METHOD("get_mode"),&AudioEffectDistortion::get_mode);
-
- ClassDB::bind_method(D_METHOD("set_pre_gain","pre_gain"),&AudioEffectDistortion::set_pre_gain);
- ClassDB::bind_method(D_METHOD("get_pre_gain"),&AudioEffectDistortion::get_pre_gain);
+ ClassDB::bind_method(D_METHOD("set_mode", "mode"), &AudioEffectDistortion::set_mode);
+ ClassDB::bind_method(D_METHOD("get_mode"), &AudioEffectDistortion::get_mode);
- ClassDB::bind_method(D_METHOD("set_keep_hf_hz","keep_hf_hz"),&AudioEffectDistortion::set_keep_hf_hz);
- ClassDB::bind_method(D_METHOD("get_keep_hf_hz"),&AudioEffectDistortion::get_keep_hf_hz);
+ ClassDB::bind_method(D_METHOD("set_pre_gain", "pre_gain"), &AudioEffectDistortion::set_pre_gain);
+ ClassDB::bind_method(D_METHOD("get_pre_gain"), &AudioEffectDistortion::get_pre_gain);
- ClassDB::bind_method(D_METHOD("set_drive","drive"),&AudioEffectDistortion::set_drive);
- ClassDB::bind_method(D_METHOD("get_drive"),&AudioEffectDistortion::get_drive);
+ ClassDB::bind_method(D_METHOD("set_keep_hf_hz", "keep_hf_hz"), &AudioEffectDistortion::set_keep_hf_hz);
+ ClassDB::bind_method(D_METHOD("get_keep_hf_hz"), &AudioEffectDistortion::get_keep_hf_hz);
+ ClassDB::bind_method(D_METHOD("set_drive", "drive"), &AudioEffectDistortion::set_drive);
+ ClassDB::bind_method(D_METHOD("get_drive"), &AudioEffectDistortion::get_drive);
- ClassDB::bind_method(D_METHOD("set_post_gain","post_gain"),&AudioEffectDistortion::set_post_gain);
- ClassDB::bind_method(D_METHOD("get_post_gain"),&AudioEffectDistortion::get_post_gain);
+ ClassDB::bind_method(D_METHOD("set_post_gain", "post_gain"), &AudioEffectDistortion::set_post_gain);
+ ClassDB::bind_method(D_METHOD("get_post_gain"), &AudioEffectDistortion::get_post_gain);
- ADD_PROPERTY(PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Clip,ATan,LoFi,Overdrive,WaveShape"),"set_mode","get_mode");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"pre_gain",PROPERTY_HINT_RANGE,"-60,60,0.01"),"set_pre_gain","get_pre_gain");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"keep_hf_hz",PROPERTY_HINT_RANGE,"1,20000,1"),"set_keep_hf_hz","get_keep_hf_hz");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"drive",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_drive","get_drive");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"post_gain",PROPERTY_HINT_RANGE,"-80,24,0.01"),"set_post_gain","get_post_gain");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Clip,ATan,LoFi,Overdrive,WaveShape"), "set_mode", "get_mode");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "pre_gain", PROPERTY_HINT_RANGE, "-60,60,0.01"), "set_pre_gain", "get_pre_gain");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "keep_hf_hz", PROPERTY_HINT_RANGE, "1,20000,1"), "set_keep_hf_hz", "get_keep_hf_hz");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "drive", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_drive", "get_drive");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "post_gain", PROPERTY_HINT_RANGE, "-80,24,0.01"), "set_post_gain", "get_post_gain");
}
-AudioEffectDistortion::AudioEffectDistortion()
-{
- mode=MODE_CLIP;
- pre_gain=0;
- post_gain=0;
- keep_hf_hz=16000;
- drive=0;
+AudioEffectDistortion::AudioEffectDistortion() {
+ mode = MODE_CLIP;
+ pre_gain = 0;
+ post_gain = 0;
+ keep_hf_hz = 16000;
+ drive = 0;
}
-
diff --git a/servers/audio/effects/audio_effect_distortion.h b/servers/audio/effects/audio_effect_distortion.h
index c4388f0256..6cd92dea18 100644
--- a/servers/audio/effects/audio_effect_distortion.h
+++ b/servers/audio/effects/audio_effect_distortion.h
@@ -34,19 +34,17 @@
class AudioEffectDistortion;
class AudioEffectDistortionInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectDistortionInstance,AudioEffectInstance)
-friend class AudioEffectDistortion;
+ GDCLASS(AudioEffectDistortionInstance, AudioEffectInstance)
+ friend class AudioEffectDistortion;
Ref<AudioEffectDistortion> base;
float h[2];
-public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectDistortion : public AudioEffect {
- GDCLASS(AudioEffectDistortion,AudioEffect)
+ GDCLASS(AudioEffectDistortion, AudioEffect)
public:
enum Mode {
MODE_CLIP,
@@ -56,7 +54,7 @@ public:
MODE_WAVESHAPE,
};
-friend class AudioEffectDistortionInstance;
+ friend class AudioEffectDistortionInstance;
Mode mode;
float pre_gain;
float post_gain;
@@ -64,14 +62,11 @@ friend class AudioEffectDistortionInstance;
float drive;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
-
void set_mode(Mode p_mode);
Mode get_mode() const;
@@ -87,11 +82,9 @@ public:
void set_post_gain(float post_gain);
float get_post_gain() const;
-
-
AudioEffectDistortion();
};
-VARIANT_ENUM_CAST( AudioEffectDistortion::Mode )
+VARIANT_ENUM_CAST(AudioEffectDistortion::Mode)
#endif // AUDIOEFFECTDISTORTION_H
diff --git a/servers/audio/effects/audio_effect_eq.cpp b/servers/audio/effects/audio_effect_eq.cpp
index 2caec9e49e..a103d34d0f 100644
--- a/servers/audio/effects/audio_effect_eq.cpp
+++ b/servers/audio/effects/audio_effect_eq.cpp
@@ -29,24 +29,22 @@
#include "audio_effect_eq.h"
#include "servers/audio_server.h"
-
-void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectEQInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
int band_count = bands[0].size();
EQ::BandProcess *proc_l = bands[0].ptr();
EQ::BandProcess *proc_r = bands[1].ptr();
float *bgain = gains.ptr();
- for(int i=0;i<band_count;i++) {
- bgain[i]=Math::db2linear(base->gain[i]);
+ for (int i = 0; i < band_count; i++) {
+ bgain[i] = Math::db2linear(base->gain[i]);
}
-
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
AudioFrame src = p_src_frames[i];
- AudioFrame dst = AudioFrame(0,0);
+ AudioFrame dst = AudioFrame(0, 0);
- for(int j=0;j<band_count;j++) {
+ for (int j = 0; j < band_count; j++) {
float l = src.l;
float r = src.r;
@@ -54,38 +52,36 @@ void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p
proc_l[j].process_one(l);
proc_r[j].process_one(r);
- dst.l+=l * bgain[j];
- dst.r+=r * bgain[j];
+ dst.l += l * bgain[j];
+ dst.r += r * bgain[j];
}
- p_dst_frames[i]=dst;
+ p_dst_frames[i] = dst;
}
-
}
-
Ref<AudioEffectInstance> AudioEffectEQ::instance() {
Ref<AudioEffectEQInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectEQ>(this);
+ ins->base = Ref<AudioEffectEQ>(this);
ins->gains.resize(eq.get_band_count());
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
ins->bands[i].resize(eq.get_band_count());
- for(int j=0;j<ins->bands[i].size();j++) {
- ins->bands[i][j]=eq.get_band_processor(j);
+ for (int j = 0; j < ins->bands[i].size(); j++) {
+ ins->bands[i][j] = eq.get_band_processor(j);
}
}
return ins;
}
-void AudioEffectEQ::set_band_gain_db(int p_band,float p_volume) {
- ERR_FAIL_INDEX(p_band,gain.size());
- gain[p_band]=p_volume;
+void AudioEffectEQ::set_band_gain_db(int p_band, float p_volume) {
+ ERR_FAIL_INDEX(p_band, gain.size());
+ gain[p_band] = p_volume;
}
float AudioEffectEQ::get_band_gain_db(int p_band) const {
- ERR_FAIL_INDEX_V(p_band,gain.size(),0);
+ ERR_FAIL_INDEX_V(p_band, gain.size(), 0);
return gain[p_band];
}
@@ -93,58 +89,52 @@ int AudioEffectEQ::get_band_count() const {
return gain.size();
}
-bool AudioEffectEQ::_set(const StringName& p_name, const Variant& p_value) {
+bool AudioEffectEQ::_set(const StringName &p_name, const Variant &p_value) {
- const Map<StringName,int>::Element *E=prop_band_map.find(p_name);
+ const Map<StringName, int>::Element *E = prop_band_map.find(p_name);
if (E) {
- set_band_gain_db(E->get(),p_value);
+ set_band_gain_db(E->get(), p_value);
return true;
}
return false;
}
-bool AudioEffectEQ::_get(const StringName& p_name,Variant &r_ret) const{
+bool AudioEffectEQ::_get(const StringName &p_name, Variant &r_ret) const {
- const Map<StringName,int>::Element *E=prop_band_map.find(p_name);
+ const Map<StringName, int>::Element *E = prop_band_map.find(p_name);
if (E) {
- r_ret=get_band_gain_db(E->get());
+ r_ret = get_band_gain_db(E->get());
return true;
}
return false;
-
}
-void AudioEffectEQ::_get_property_list( List<PropertyInfo> *p_list) const{
+void AudioEffectEQ::_get_property_list(List<PropertyInfo> *p_list) const {
- for(int i=0;i<band_names.size();i++) {
+ for (int i = 0; i < band_names.size(); i++) {
- p_list->push_back(PropertyInfo(Variant::REAL,band_names[i],PROPERTY_HINT_RANGE,"-60,24,0.1"));
+ p_list->push_back(PropertyInfo(Variant::REAL, band_names[i], PROPERTY_HINT_RANGE, "-60,24,0.1"));
}
}
-
-
void AudioEffectEQ::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_band_gain_db","band_idx","volume_db"),&AudioEffectEQ::set_band_gain_db);
- ClassDB::bind_method(D_METHOD("get_band_gain_db","band_idx"),&AudioEffectEQ::get_band_gain_db);
- ClassDB::bind_method(D_METHOD("get_band_count"),&AudioEffectEQ::get_band_count);
-
+ ClassDB::bind_method(D_METHOD("set_band_gain_db", "band_idx", "volume_db"), &AudioEffectEQ::set_band_gain_db);
+ ClassDB::bind_method(D_METHOD("get_band_gain_db", "band_idx"), &AudioEffectEQ::get_band_gain_db);
+ ClassDB::bind_method(D_METHOD("get_band_count"), &AudioEffectEQ::get_band_count);
}
-AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset)
-{
-
+AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset) {
eq.set_mix_rate(AudioServer::get_singleton()->get_mix_rate());
eq.set_preset_band_mode(p_preset);
gain.resize(eq.get_band_count());
- for(int i=0;i<gain.size();i++) {
- gain[i]=0.0;
- String name = "band_db/"+itos(eq.get_band_frequency(i))+"_hz";
- prop_band_map[name]=i;
+ for (int i = 0; i < gain.size(); i++) {
+ gain[i] = 0.0;
+ String name = "band_db/" + itos(eq.get_band_frequency(i)) + "_hz";
+ prop_band_map[name] = i;
band_names.push_back(name);
}
}
diff --git a/servers/audio/effects/audio_effect_eq.h b/servers/audio/effects/audio_effect_eq.h
index 2f577ffd20..917bf584c7 100644
--- a/servers/audio/effects/audio_effect_eq.h
+++ b/servers/audio/effects/audio_effect_eq.h
@@ -29,72 +29,68 @@
#ifndef AUDIOEFFECTEQ_H
#define AUDIOEFFECTEQ_H
-
#include "servers/audio/audio_effect.h"
#include "servers/audio/effects/eq.h"
class AudioEffectEQ;
class AudioEffectEQInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectEQInstance,AudioEffectInstance)
-friend class AudioEffectEQ;
+ GDCLASS(AudioEffectEQInstance, AudioEffectInstance)
+ friend class AudioEffectEQ;
Ref<AudioEffectEQ> base;
Vector<EQ::BandProcess> bands[2];
Vector<float> gains;
-public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectEQ : public AudioEffect {
- GDCLASS(AudioEffectEQ,AudioEffect)
+ GDCLASS(AudioEffectEQ, AudioEffect)
-friend class AudioEffectEQInstance;
+ friend class AudioEffectEQInstance;
EQ eq;
Vector<float> gain;
- Map<StringName,int> prop_band_map;
+ Map<StringName, int> prop_band_map;
Vector<String> band_names;
protected:
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
-
-
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
- void set_band_gain_db(int p_band,float p_volume);
+ void set_band_gain_db(int p_band, float p_volume);
float get_band_gain_db(int p_band) const;
int get_band_count() const;
- AudioEffectEQ(EQ::Preset p_preset=EQ::PRESET_6_BANDS);
+ AudioEffectEQ(EQ::Preset p_preset = EQ::PRESET_6_BANDS);
};
-
class AudioEffectEQ6 : public AudioEffectEQ {
- GDCLASS(AudioEffectEQ6,AudioEffectEQ)
+ GDCLASS(AudioEffectEQ6, AudioEffectEQ)
public:
- AudioEffectEQ6() : AudioEffectEQ(EQ::PRESET_6_BANDS) {}
+ AudioEffectEQ6()
+ : AudioEffectEQ(EQ::PRESET_6_BANDS) {}
};
class AudioEffectEQ10 : public AudioEffectEQ {
- GDCLASS(AudioEffectEQ10,AudioEffectEQ)
+ GDCLASS(AudioEffectEQ10, AudioEffectEQ)
public:
- AudioEffectEQ10() : AudioEffectEQ(EQ::PRESET_10_BANDS) {}
+ AudioEffectEQ10()
+ : AudioEffectEQ(EQ::PRESET_10_BANDS) {}
};
class AudioEffectEQ21 : public AudioEffectEQ {
- GDCLASS(AudioEffectEQ21,AudioEffectEQ)
+ GDCLASS(AudioEffectEQ21, AudioEffectEQ)
public:
- AudioEffectEQ21() : AudioEffectEQ(EQ::PRESET_21_BANDS) {}
+ AudioEffectEQ21()
+ : AudioEffectEQ(EQ::PRESET_21_BANDS) {}
};
#endif // AUDIOEFFECTEQ_H
diff --git a/servers/audio/effects/audio_effect_filter.cpp b/servers/audio/effects/audio_effect_filter.cpp
index c854842943..4c158ce44e 100644
--- a/servers/audio/effects/audio_effect_filter.cpp
+++ b/servers/audio/effects/audio_effect_filter.cpp
@@ -29,118 +29,110 @@
#include "audio_effect_filter.h"
#include "servers/audio_server.h"
-template<int S>
-void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+template <int S>
+void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
float f = p_src_frames[i].l;
filter_process[0][0].process_one(f);
- if (S>1)
+ if (S > 1)
filter_process[0][1].process_one(f);
- if (S>2)
+ if (S > 2)
filter_process[0][2].process_one(f);
- if (S>3)
+ if (S > 3)
filter_process[0][3].process_one(f);
- p_dst_frames[i].l=f;
+ p_dst_frames[i].l = f;
}
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
float f = p_src_frames[i].r;
filter_process[1][0].process_one(f);
- if (S>1)
+ if (S > 1)
filter_process[1][1].process_one(f);
- if (S>2)
+ if (S > 2)
filter_process[1][2].process_one(f);
- if (S>3)
+ if (S > 3)
filter_process[1][3].process_one(f);
- p_dst_frames[i].r=f;
+ p_dst_frames[i].r = f;
}
-
}
-void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
filter.set_cutoff(base->cutoff);
filter.set_gain(base->gain);
filter.set_resonance(base->resonance);
filter.set_mode(base->mode);
- int stages = int(base->db)+1;
+ int stages = int(base->db) + 1;
filter.set_stages(stages);
filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate());
- for(int i=0;i<2;i++) {
- for(int j=0;j<4;j++) {
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < 4; j++) {
filter_process[i][j].update_coeffs();
}
}
-
- if (stages==1) {
- _process_filter<1>(p_src_frames,p_dst_frames,p_frame_count);
- } else if (stages==2) {
- _process_filter<2>(p_src_frames,p_dst_frames,p_frame_count);
- } else if (stages==3) {
- _process_filter<3>(p_src_frames,p_dst_frames,p_frame_count);
- } else if (stages==4) {
- _process_filter<4>(p_src_frames,p_dst_frames,p_frame_count);
+ if (stages == 1) {
+ _process_filter<1>(p_src_frames, p_dst_frames, p_frame_count);
+ } else if (stages == 2) {
+ _process_filter<2>(p_src_frames, p_dst_frames, p_frame_count);
+ } else if (stages == 3) {
+ _process_filter<3>(p_src_frames, p_dst_frames, p_frame_count);
+ } else if (stages == 4) {
+ _process_filter<4>(p_src_frames, p_dst_frames, p_frame_count);
}
-
}
-
AudioEffectFilterInstance::AudioEffectFilterInstance() {
- for(int i=0;i<2;i++) {
- for(int j=0;j<4;j++) {
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < 4; j++) {
filter_process[i][j].set_filter(&filter);
}
}
-
}
-
Ref<AudioEffectInstance> AudioEffectFilter::instance() {
Ref<AudioEffectFilterInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectFilter>(this);
+ ins->base = Ref<AudioEffectFilter>(this);
return ins;
}
void AudioEffectFilter::set_cutoff(float p_freq) {
- cutoff=p_freq;
+ cutoff = p_freq;
}
-float AudioEffectFilter::get_cutoff() const{
+float AudioEffectFilter::get_cutoff() const {
return cutoff;
}
-void AudioEffectFilter::set_resonance(float p_amount){
+void AudioEffectFilter::set_resonance(float p_amount) {
- resonance=p_amount;
+ resonance = p_amount;
}
-float AudioEffectFilter::get_resonance() const{
+float AudioEffectFilter::get_resonance() const {
return resonance;
}
-void AudioEffectFilter::set_gain(float p_amount){
+void AudioEffectFilter::set_gain(float p_amount) {
- gain=p_amount;
+ gain = p_amount;
}
float AudioEffectFilter::get_gain() const {
return gain;
}
-
-
void AudioEffectFilter::set_db(FilterDB p_db) {
- db=p_db;
+ db = p_db;
}
AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const {
@@ -150,30 +142,29 @@ AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const {
void AudioEffectFilter::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_cutoff","freq"),&AudioEffectFilter::set_cutoff);
- ClassDB::bind_method(D_METHOD("get_cutoff"),&AudioEffectFilter::get_cutoff);
+ ClassDB::bind_method(D_METHOD("set_cutoff", "freq"), &AudioEffectFilter::set_cutoff);
+ ClassDB::bind_method(D_METHOD("get_cutoff"), &AudioEffectFilter::get_cutoff);
- ClassDB::bind_method(D_METHOD("set_resonance","amount"),&AudioEffectFilter::set_resonance);
- ClassDB::bind_method(D_METHOD("get_resonance"),&AudioEffectFilter::get_resonance);
+ ClassDB::bind_method(D_METHOD("set_resonance", "amount"), &AudioEffectFilter::set_resonance);
+ ClassDB::bind_method(D_METHOD("get_resonance"), &AudioEffectFilter::get_resonance);
- ClassDB::bind_method(D_METHOD("set_gain","amount"),&AudioEffectFilter::set_gain);
- ClassDB::bind_method(D_METHOD("get_gain"),&AudioEffectFilter::get_gain);
+ ClassDB::bind_method(D_METHOD("set_gain", "amount"), &AudioEffectFilter::set_gain);
+ ClassDB::bind_method(D_METHOD("get_gain"), &AudioEffectFilter::get_gain);
- ClassDB::bind_method(D_METHOD("set_db","amount"),&AudioEffectFilter::set_db);
- ClassDB::bind_method(D_METHOD("get_db"),&AudioEffectFilter::get_db);
+ ClassDB::bind_method(D_METHOD("set_db", "amount"), &AudioEffectFilter::set_db);
+ ClassDB::bind_method(D_METHOD("get_db"), &AudioEffectFilter::get_db);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"cutoff_hz",PROPERTY_HINT_RANGE,"1,40000,0.1"),"set_cutoff","get_cutoff");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"resonance",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_resonance","get_resonance");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_gain","get_gain");
- ADD_PROPERTY(PropertyInfo(Variant::INT,"dB",PROPERTY_HINT_ENUM,"6db,12db,18db,24db"),"set_db","get_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "cutoff_hz", PROPERTY_HINT_RANGE, "1,40000,0.1"), "set_cutoff", "get_cutoff");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "resonance", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_resonance", "get_resonance");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "gain", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_gain", "get_gain");
+ ADD_PROPERTY(PropertyInfo(Variant::INT, "dB", PROPERTY_HINT_ENUM, "6db,12db,18db,24db"), "set_db", "get_db");
}
-AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode)
-{
+AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode) {
- mode=p_mode;
- cutoff=2000;
- resonance=0.5;
- gain=1.0;
- db=FILTER_6DB;
+ mode = p_mode;
+ cutoff = 2000;
+ resonance = 0.5;
+ gain = 1.0;
+ db = FILTER_6DB;
}
diff --git a/servers/audio/effects/audio_effect_filter.h b/servers/audio/effects/audio_effect_filter.h
index 0215f5a141..4973630198 100644
--- a/servers/audio/effects/audio_effect_filter.h
+++ b/servers/audio/effects/audio_effect_filter.h
@@ -35,33 +35,31 @@
class AudioEffectFilter;
class AudioEffectFilterInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectFilterInstance,AudioEffectInstance)
-friend class AudioEffectFilter;
+ GDCLASS(AudioEffectFilterInstance, AudioEffectInstance)
+ friend class AudioEffectFilter;
Ref<AudioEffectFilter> base;
AudioFilterSW filter;
AudioFilterSW::Processor filter_process[2][4];
- template<int S>
- void _process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
-public:
+ template <int S>
+ void _process_filter(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
AudioEffectFilterInstance();
};
-
class AudioEffectFilter : public AudioEffect {
- GDCLASS(AudioEffectFilter,AudioEffect)
+ GDCLASS(AudioEffectFilter, AudioEffect)
public:
-
enum FilterDB {
- FILTER_6DB,
- FILTER_12DB,
- FILTER_18DB,
- FILTER_24DB,
+ FILTER_6DB,
+ FILTER_12DB,
+ FILTER_18DB,
+ FILTER_24DB,
};
friend class AudioEffectFilterInstance;
@@ -71,13 +69,10 @@ public:
float gain;
FilterDB db;
-
protected:
-
-
static void _bind_methods();
-public:
+public:
void set_cutoff(float p_freq);
float get_cutoff() const;
@@ -92,62 +87,58 @@ public:
Ref<AudioEffectInstance> instance();
- AudioEffectFilter(AudioFilterSW::Mode p_mode=AudioFilterSW::LOWPASS);
+ AudioEffectFilter(AudioFilterSW::Mode p_mode = AudioFilterSW::LOWPASS);
};
VARIANT_ENUM_CAST(AudioEffectFilter::FilterDB)
class AudioEffectLowPassFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectLowPassFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectLowPassFilter, AudioEffectFilter)
public:
-
- AudioEffectLowPassFilter() : AudioEffectFilter(AudioFilterSW::LOWPASS) {}
+ AudioEffectLowPassFilter()
+ : AudioEffectFilter(AudioFilterSW::LOWPASS) {}
};
class AudioEffectHighPassFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectHighPassFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectHighPassFilter, AudioEffectFilter)
public:
-
- AudioEffectHighPassFilter() : AudioEffectFilter(AudioFilterSW::HIGHPASS) {}
+ AudioEffectHighPassFilter()
+ : AudioEffectFilter(AudioFilterSW::HIGHPASS) {}
};
class AudioEffectBandPassFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectBandPassFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectBandPassFilter, AudioEffectFilter)
public:
-
- AudioEffectBandPassFilter() : AudioEffectFilter(AudioFilterSW::BANDPASS) {}
+ AudioEffectBandPassFilter()
+ : AudioEffectFilter(AudioFilterSW::BANDPASS) {}
};
class AudioEffectNotchFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectNotchFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectNotchFilter, AudioEffectFilter)
public:
-
- AudioEffectNotchFilter() : AudioEffectFilter(AudioFilterSW::NOTCH) {}
+ AudioEffectNotchFilter()
+ : AudioEffectFilter(AudioFilterSW::NOTCH) {}
};
class AudioEffectBandLimitFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectBandLimitFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectBandLimitFilter, AudioEffectFilter)
public:
-
- AudioEffectBandLimitFilter() : AudioEffectFilter(AudioFilterSW::BANDLIMIT) {}
+ AudioEffectBandLimitFilter()
+ : AudioEffectFilter(AudioFilterSW::BANDLIMIT) {}
};
-
class AudioEffectLowShelfFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectLowShelfFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectLowShelfFilter, AudioEffectFilter)
public:
-
- AudioEffectLowShelfFilter() : AudioEffectFilter(AudioFilterSW::LOWSHELF) {}
+ AudioEffectLowShelfFilter()
+ : AudioEffectFilter(AudioFilterSW::LOWSHELF) {}
};
-
class AudioEffectHighShelfFilter : public AudioEffectFilter {
- GDCLASS(AudioEffectHighShelfFilter,AudioEffectFilter)
+ GDCLASS(AudioEffectHighShelfFilter, AudioEffectFilter)
public:
-
- AudioEffectHighShelfFilter() : AudioEffectFilter(AudioFilterSW::HIGHSHELF) {}
+ AudioEffectHighShelfFilter()
+ : AudioEffectFilter(AudioFilterSW::HIGHSHELF) {}
};
-
-
#endif // AUDIOEFFECTFILTER_H
diff --git a/servers/audio/effects/audio_effect_limiter.cpp b/servers/audio/effects/audio_effect_limiter.cpp
index a44bb51762..022d2d9aa4 100644
--- a/servers/audio/effects/audio_effect_limiter.cpp
+++ b/servers/audio/effects/audio_effect_limiter.cpp
@@ -28,7 +28,7 @@
/*************************************************************************/
#include "audio_effect_limiter.h"
-void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
float thresh = Math::db2linear(base->treshold);
float threshdb = base->treshold;
@@ -44,25 +44,23 @@ void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFra
float scratio = base->soft_clip_ratio;
float scmult = Math::abs((ceildb - sc) / (peakdb - sc));
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
float spl0 = p_src_frames[i].l;
float spl1 = p_src_frames[i].r;
spl0 = spl0 * makeup;
spl1 = spl1 * makeup;
- float sign0 = (spl0 < 0.0 ? -1.0 : 1.0 );
- float sign1 = (spl1 < 0.0 ? -1.0 : 1.0 );
+ float sign0 = (spl0 < 0.0 ? -1.0 : 1.0);
+ float sign1 = (spl1 < 0.0 ? -1.0 : 1.0);
float abs0 = Math::abs(spl0);
float abs1 = Math::abs(spl1);
float overdb0 = Math::linear2db(abs0) - ceildb;
float overdb1 = Math::linear2db(abs1) - ceildb;
- if (abs0 > scv)
- {
+ if (abs0 > scv) {
spl0 = sign0 * (scv + Math::db2linear(overdb0 * scmult));
}
- if (abs1 > scv)
- {
+ if (abs1 > scv) {
spl1 = sign1 * (scv + Math::db2linear(overdb1 * scmult));
}
@@ -72,81 +70,76 @@ void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFra
p_dst_frames[i].l = spl0;
p_dst_frames[i].r = spl1;
}
-
}
-
Ref<AudioEffectInstance> AudioEffectLimiter::instance() {
Ref<AudioEffectLimiterInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectLimiter>(this);
+ ins->base = Ref<AudioEffectLimiter>(this);
return ins;
}
-
void AudioEffectLimiter::set_treshold_db(float p_treshold) {
- treshold=p_treshold;
+ treshold = p_treshold;
}
-float AudioEffectLimiter::get_treshold_db() const{
+float AudioEffectLimiter::get_treshold_db() const {
return treshold;
}
-void AudioEffectLimiter::set_ceiling_db(float p_ceiling){
+void AudioEffectLimiter::set_ceiling_db(float p_ceiling) {
- ceiling=p_ceiling;
+ ceiling = p_ceiling;
}
-float AudioEffectLimiter::get_ceiling_db() const{
+float AudioEffectLimiter::get_ceiling_db() const {
return ceiling;
}
-void AudioEffectLimiter::set_soft_clip_db(float p_soft_clip){
+void AudioEffectLimiter::set_soft_clip_db(float p_soft_clip) {
- soft_clip=p_soft_clip;
+ soft_clip = p_soft_clip;
}
-float AudioEffectLimiter::get_soft_clip_db() const{
+float AudioEffectLimiter::get_soft_clip_db() const {
return soft_clip;
}
-void AudioEffectLimiter::set_soft_clip_ratio(float p_soft_clip){
+void AudioEffectLimiter::set_soft_clip_ratio(float p_soft_clip) {
- soft_clip_ratio=p_soft_clip;
+ soft_clip_ratio = p_soft_clip;
}
-float AudioEffectLimiter::get_soft_clip_ratio() const{
+float AudioEffectLimiter::get_soft_clip_ratio() const {
return soft_clip;
}
-
void AudioEffectLimiter::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_ceiling_db","ceiling"),&AudioEffectLimiter::set_ceiling_db);
- ClassDB::bind_method(D_METHOD("get_ceiling_db"),&AudioEffectLimiter::get_ceiling_db);
+ ClassDB::bind_method(D_METHOD("set_ceiling_db", "ceiling"), &AudioEffectLimiter::set_ceiling_db);
+ ClassDB::bind_method(D_METHOD("get_ceiling_db"), &AudioEffectLimiter::get_ceiling_db);
- ClassDB::bind_method(D_METHOD("set_treshold_db","treshold"),&AudioEffectLimiter::set_treshold_db);
- ClassDB::bind_method(D_METHOD("get_treshold_db"),&AudioEffectLimiter::get_treshold_db);
+ ClassDB::bind_method(D_METHOD("set_treshold_db", "treshold"), &AudioEffectLimiter::set_treshold_db);
+ ClassDB::bind_method(D_METHOD("get_treshold_db"), &AudioEffectLimiter::get_treshold_db);
- ClassDB::bind_method(D_METHOD("set_soft_clip_db","soft_clip"),&AudioEffectLimiter::set_soft_clip_db);
- ClassDB::bind_method(D_METHOD("get_soft_clip_db"),&AudioEffectLimiter::get_soft_clip_db);
+ ClassDB::bind_method(D_METHOD("set_soft_clip_db", "soft_clip"), &AudioEffectLimiter::set_soft_clip_db);
+ ClassDB::bind_method(D_METHOD("get_soft_clip_db"), &AudioEffectLimiter::get_soft_clip_db);
- ClassDB::bind_method(D_METHOD("set_soft_clip_ratio","soft_clip"),&AudioEffectLimiter::set_soft_clip_ratio);
- ClassDB::bind_method(D_METHOD("get_soft_clip_ratio"),&AudioEffectLimiter::get_soft_clip_ratio);
+ ClassDB::bind_method(D_METHOD("set_soft_clip_ratio", "soft_clip"), &AudioEffectLimiter::set_soft_clip_ratio);
+ ClassDB::bind_method(D_METHOD("get_soft_clip_ratio"), &AudioEffectLimiter::get_soft_clip_ratio);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"ceiling_db",PROPERTY_HINT_RANGE,"-20,-0.1,0.1"),"set_ceiling_db","get_ceiling_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold_db",PROPERTY_HINT_RANGE,"-30,0,0.1"),"set_treshold_db","get_treshold_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_db",PROPERTY_HINT_RANGE,"0,6,0.1"),"set_soft_clip_db","get_soft_clip_db");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_ratio",PROPERTY_HINT_RANGE,"3,20,0.1"),"set_soft_clip_ratio","get_soft_clip_ratio");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "ceiling_db", PROPERTY_HINT_RANGE, "-20,-0.1,0.1"), "set_ceiling_db", "get_ceiling_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "treshold_db", PROPERTY_HINT_RANGE, "-30,0,0.1"), "set_treshold_db", "get_treshold_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "soft_clip_db", PROPERTY_HINT_RANGE, "0,6,0.1"), "set_soft_clip_db", "get_soft_clip_db");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "soft_clip_ratio", PROPERTY_HINT_RANGE, "3,20,0.1"), "set_soft_clip_ratio", "get_soft_clip_ratio");
}
-AudioEffectLimiter::AudioEffectLimiter()
-{
- treshold=0;
- ceiling=-0.1;
- soft_clip=2;
- soft_clip_ratio=10;
+AudioEffectLimiter::AudioEffectLimiter() {
+ treshold = 0;
+ ceiling = -0.1;
+ soft_clip = 2;
+ soft_clip_ratio = 10;
}
diff --git a/servers/audio/effects/audio_effect_limiter.h b/servers/audio/effects/audio_effect_limiter.h
index 12639498d9..9863a788f5 100644
--- a/servers/audio/effects/audio_effect_limiter.h
+++ b/servers/audio/effects/audio_effect_limiter.h
@@ -29,39 +29,34 @@
#ifndef AUDIO_EFFECT_LIMITER_H
#define AUDIO_EFFECT_LIMITER_H
-
#include "servers/audio/audio_effect.h"
class AudioEffectLimiter;
class AudioEffectLimiterInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectLimiterInstance,AudioEffectInstance)
-friend class AudioEffectLimiter;
+ GDCLASS(AudioEffectLimiterInstance, AudioEffectInstance)
+ friend class AudioEffectLimiter;
Ref<AudioEffectLimiter> base;
float mix_volume_db;
-public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectLimiter : public AudioEffect {
- GDCLASS(AudioEffectLimiter,AudioEffect)
+ GDCLASS(AudioEffectLimiter, AudioEffect)
-friend class AudioEffectLimiterInstance;
+ friend class AudioEffectLimiterInstance;
float treshold;
float ceiling;
float soft_clip;
float soft_clip_ratio;
protected:
-
static void _bind_methods();
-public:
-
+public:
void set_treshold_db(float p_treshold);
float get_treshold_db() const;
@@ -74,7 +69,6 @@ public:
void set_soft_clip_ratio(float p_soft_clip);
float get_soft_clip_ratio() const;
-
Ref<AudioEffectInstance> instance();
void set_volume_db(float p_volume);
float get_volume_db() const;
@@ -82,5 +76,4 @@ public:
AudioEffectLimiter();
};
-
#endif // AUDIO_EFFECT_LIMITER_H
diff --git a/servers/audio/effects/audio_effect_panner.cpp b/servers/audio/effects/audio_effect_panner.cpp
index 937575a5b5..ec0ccab453 100644
--- a/servers/audio/effects/audio_effect_panner.cpp
+++ b/servers/audio/effects/audio_effect_panner.cpp
@@ -28,32 +28,27 @@
/*************************************************************************/
#include "audio_effect_panner.h"
+void AudioEffectPannerInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
-void AudioEffectPannerInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+ float lvol = CLAMP(1.0 - base->pan, 0, 1);
+ float rvol = CLAMP(1.0 + base->pan, 0, 1);
-
- float lvol = CLAMP( 1.0 - base->pan, 0, 1);
- float rvol = CLAMP( 1.0 + base->pan, 0, 1);
-
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
p_dst_frames[i].l = p_src_frames[i].l * lvol + p_src_frames[i].r * (1.0 - rvol);
p_dst_frames[i].r = p_src_frames[i].r * rvol + p_src_frames[i].l * (1.0 - lvol);
-
}
-
}
-
Ref<AudioEffectInstance> AudioEffectPanner::instance() {
Ref<AudioEffectPannerInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectPanner>(this);
+ ins->base = Ref<AudioEffectPanner>(this);
return ins;
}
void AudioEffectPanner::set_pan(float p_cpanume) {
- pan=p_cpanume;
+ pan = p_cpanume;
}
float AudioEffectPanner::get_pan() const {
@@ -63,13 +58,12 @@ float AudioEffectPanner::get_pan() const {
void AudioEffectPanner::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_pan","cpanume"),&AudioEffectPanner::set_pan);
- ClassDB::bind_method(D_METHOD("get_pan"),&AudioEffectPanner::get_pan);
+ ClassDB::bind_method(D_METHOD("set_pan", "cpanume"), &AudioEffectPanner::set_pan);
+ ClassDB::bind_method(D_METHOD("get_pan"), &AudioEffectPanner::get_pan);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),"set_pan","get_pan");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "pan", PROPERTY_HINT_RANGE, "-1,1,0.01"), "set_pan", "get_pan");
}
-AudioEffectPanner::AudioEffectPanner()
-{
- pan=0;
+AudioEffectPanner::AudioEffectPanner() {
+ pan = 0;
}
diff --git a/servers/audio/effects/audio_effect_panner.h b/servers/audio/effects/audio_effect_panner.h
index 999b5f5649..19bef45f1e 100644
--- a/servers/audio/effects/audio_effect_panner.h
+++ b/servers/audio/effects/audio_effect_panner.h
@@ -34,29 +34,24 @@
class AudioEffectPanner;
class AudioEffectPannerInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectPannerInstance,AudioEffectInstance)
-friend class AudioEffectPanner;
+ GDCLASS(AudioEffectPannerInstance, AudioEffectInstance)
+ friend class AudioEffectPanner;
Ref<AudioEffectPanner> base;
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
-
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectPanner : public AudioEffect {
- GDCLASS(AudioEffectPanner,AudioEffect)
+ GDCLASS(AudioEffectPanner, AudioEffect)
-friend class AudioEffectPannerInstance;
+ friend class AudioEffectPannerInstance;
float pan;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
void set_pan(float p_volume);
float get_pan() const;
@@ -64,5 +59,4 @@ public:
AudioEffectPanner();
};
-
#endif // AUDIOEFFECTPANNER_H
diff --git a/servers/audio/effects/audio_effect_phaser.cpp b/servers/audio/effects/audio_effect_phaser.cpp
index c9576404f1..72549009c8 100644
--- a/servers/audio/effects/audio_effect_phaser.cpp
+++ b/servers/audio/effects/audio_effect_phaser.cpp
@@ -27,113 +27,107 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "audio_effect_phaser.h"
-#include "servers/audio_server.h"
#include "math_funcs.h"
+#include "servers/audio_server.h"
-void AudioEffectPhaserInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectPhaserInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
float sampling_rate = AudioServer::get_singleton()->get_mix_rate();
- float dmin = base->range_min / (sampling_rate/2.0);
- float dmax = base->range_max / (sampling_rate/2.0);
+ float dmin = base->range_min / (sampling_rate / 2.0);
+ float dmax = base->range_max / (sampling_rate / 2.0);
float increment = 2.f * Math_PI * (base->rate / sampling_rate);
- for(int i=0;i<p_frame_count;i++) {
+ for (int i = 0; i < p_frame_count; i++) {
phase += increment;
- while ( phase >= Math_PI * 2.f ) {
+ while (phase >= Math_PI * 2.f) {
phase -= Math_PI * 2.f;
}
- float d = dmin + (dmax-dmin) * ((sin( phase ) + 1.f)/2.f);
-
+ float d = dmin + (dmax - dmin) * ((sin(phase) + 1.f) / 2.f);
//update filter coeffs
- for( int j=0; j<6; j++ ) {
- allpass[0][j].delay( d );
- allpass[1][j].delay( d );
+ for (int j = 0; j < 6; j++) {
+ allpass[0][j].delay(d);
+ allpass[1][j].delay(d);
}
//calculate output
- float y = allpass[0][0].update(
- allpass[0][1].update(
- allpass[0][2].update(
- allpass[0][3].update(
- allpass[0][4].update(
- allpass[0][5].update( p_src_frames[i].l + h.l * base->feedback ))))));
- h.l=y;
+ float y = allpass[0][0].update(
+ allpass[0][1].update(
+ allpass[0][2].update(
+ allpass[0][3].update(
+ allpass[0][4].update(
+ allpass[0][5].update(p_src_frames[i].l + h.l * base->feedback))))));
+ h.l = y;
p_dst_frames[i].l = p_src_frames[i].l + y * base->depth;
- y = allpass[1][0].update(
- allpass[1][1].update(
- allpass[1][2].update(
- allpass[1][3].update(
- allpass[1][4].update(
- allpass[1][5].update( p_src_frames[i].r + h.r * base->feedback ))))));
- h.r=y;
+ y = allpass[1][0].update(
+ allpass[1][1].update(
+ allpass[1][2].update(
+ allpass[1][3].update(
+ allpass[1][4].update(
+ allpass[1][5].update(p_src_frames[i].r + h.r * base->feedback))))));
+ h.r = y;
p_dst_frames[i].r = p_src_frames[i].r + y * base->depth;
-
-
}
-
}
-
Ref<AudioEffectInstance> AudioEffectPhaser::instance() {
Ref<AudioEffectPhaserInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectPhaser>(this);
- ins->phase=0;
- ins->h=AudioFrame(0,0);
+ ins->base = Ref<AudioEffectPhaser>(this);
+ ins->phase = 0;
+ ins->h = AudioFrame(0, 0);
return ins;
}
-
void AudioEffectPhaser::set_range_min_hz(float p_hz) {
- range_min=p_hz;
+ range_min = p_hz;
}
-float AudioEffectPhaser::get_range_min_hz() const{
+float AudioEffectPhaser::get_range_min_hz() const {
return range_min;
}
-void AudioEffectPhaser::set_range_max_hz(float p_hz){
+void AudioEffectPhaser::set_range_max_hz(float p_hz) {
- range_max=p_hz;
+ range_max = p_hz;
}
-float AudioEffectPhaser::get_range_max_hz() const{
+float AudioEffectPhaser::get_range_max_hz() const {
return range_max;
}
-void AudioEffectPhaser::set_rate_hz(float p_hz){
+void AudioEffectPhaser::set_rate_hz(float p_hz) {
- rate=p_hz;
+ rate = p_hz;
}
-float AudioEffectPhaser::get_rate_hz() const{
+float AudioEffectPhaser::get_rate_hz() const {
return rate;
}
-void AudioEffectPhaser::set_feedback(float p_fbk){
+void AudioEffectPhaser::set_feedback(float p_fbk) {
- feedback=p_fbk;
+ feedback = p_fbk;
}
-float AudioEffectPhaser::get_feedback() const{
+float AudioEffectPhaser::get_feedback() const {
return feedback;
}
void AudioEffectPhaser::set_depth(float p_depth) {
- depth=p_depth;
+ depth = p_depth;
}
float AudioEffectPhaser::get_depth() const {
@@ -143,34 +137,32 @@ float AudioEffectPhaser::get_depth() const {
void AudioEffectPhaser::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_range_min_hz","hz"),&AudioEffectPhaser::set_range_min_hz);
- ClassDB::bind_method(D_METHOD("get_range_min_hz"),&AudioEffectPhaser::get_range_min_hz);
-
- ClassDB::bind_method(D_METHOD("set_range_max_hz","hz"),&AudioEffectPhaser::set_range_max_hz);
- ClassDB::bind_method(D_METHOD("get_range_max_hz"),&AudioEffectPhaser::get_range_max_hz);
+ ClassDB::bind_method(D_METHOD("set_range_min_hz", "hz"), &AudioEffectPhaser::set_range_min_hz);
+ ClassDB::bind_method(D_METHOD("get_range_min_hz"), &AudioEffectPhaser::get_range_min_hz);
- ClassDB::bind_method(D_METHOD("set_rate_hz","hz"),&AudioEffectPhaser::set_rate_hz);
- ClassDB::bind_method(D_METHOD("get_rate_hz"),&AudioEffectPhaser::get_rate_hz);
+ ClassDB::bind_method(D_METHOD("set_range_max_hz", "hz"), &AudioEffectPhaser::set_range_max_hz);
+ ClassDB::bind_method(D_METHOD("get_range_max_hz"), &AudioEffectPhaser::get_range_max_hz);
- ClassDB::bind_method(D_METHOD("set_feedback","fbk"),&AudioEffectPhaser::set_feedback);
- ClassDB::bind_method(D_METHOD("get_feedback"),&AudioEffectPhaser::get_feedback);
+ ClassDB::bind_method(D_METHOD("set_rate_hz", "hz"), &AudioEffectPhaser::set_rate_hz);
+ ClassDB::bind_method(D_METHOD("get_rate_hz"), &AudioEffectPhaser::get_rate_hz);
- ClassDB::bind_method(D_METHOD("set_depth","depth"),&AudioEffectPhaser::set_depth);
- ClassDB::bind_method(D_METHOD("get_depth"),&AudioEffectPhaser::get_depth);
+ ClassDB::bind_method(D_METHOD("set_feedback", "fbk"), &AudioEffectPhaser::set_feedback);
+ ClassDB::bind_method(D_METHOD("get_feedback"), &AudioEffectPhaser::get_feedback);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_min_hz",PROPERTY_HINT_RANGE,"10,10000"),"set_range_min_hz","get_range_min_hz");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_max_hz",PROPERTY_HINT_RANGE,"10,10000"),"set_range_max_hz","get_range_max_hz");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"rate_hz",PROPERTY_HINT_RANGE,"0.01,20"),"set_rate_hz","get_rate_hz");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback",PROPERTY_HINT_RANGE,"0.1,0.9,0.1"),"set_feedback","get_feedback");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"depth",PROPERTY_HINT_RANGE,"0.1,4,0.1"),"set_depth","get_depth");
+ ClassDB::bind_method(D_METHOD("set_depth", "depth"), &AudioEffectPhaser::set_depth);
+ ClassDB::bind_method(D_METHOD("get_depth"), &AudioEffectPhaser::get_depth);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_min_hz", PROPERTY_HINT_RANGE, "10,10000"), "set_range_min_hz", "get_range_min_hz");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "range_max_hz", PROPERTY_HINT_RANGE, "10,10000"), "set_range_max_hz", "get_range_max_hz");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "rate_hz", PROPERTY_HINT_RANGE, "0.01,20"), "set_rate_hz", "get_rate_hz");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "feedback", PROPERTY_HINT_RANGE, "0.1,0.9,0.1"), "set_feedback", "get_feedback");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "depth", PROPERTY_HINT_RANGE, "0.1,4,0.1"), "set_depth", "get_depth");
}
-AudioEffectPhaser::AudioEffectPhaser()
-{
- range_min=440;
- range_max=1600;
- rate=0.5;
- feedback=0.7;
- depth=1;
+AudioEffectPhaser::AudioEffectPhaser() {
+ range_min = 440;
+ range_max = 1600;
+ rate = 0.5;
+ feedback = 0.7;
+ depth = 1;
}
diff --git a/servers/audio/effects/audio_effect_phaser.h b/servers/audio/effects/audio_effect_phaser.h
index a7294183f6..70b3a3a4c4 100644
--- a/servers/audio/effects/audio_effect_phaser.h
+++ b/servers/audio/effects/audio_effect_phaser.h
@@ -29,50 +29,48 @@
#ifndef AUDIO_EFFECT_PHASER_H
#define AUDIO_EFFECT_PHASER_H
-
-
#include "servers/audio/audio_effect.h"
class AudioEffectPhaser;
class AudioEffectPhaserInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectPhaserInstance,AudioEffectInstance)
-friend class AudioEffectPhaser;
+ GDCLASS(AudioEffectPhaserInstance, AudioEffectInstance)
+ friend class AudioEffectPhaser;
Ref<AudioEffectPhaser> base;
float phase;
AudioFrame h;
- class AllpassDelay{
+ class AllpassDelay {
float a, h;
- public:
- _ALWAYS_INLINE_ void delay( float d ) {
+ public:
+ _ALWAYS_INLINE_ void delay(float d) {
a = (1.f - d) / (1.f + d);
}
- _ALWAYS_INLINE_ float update( float s ){
+ _ALWAYS_INLINE_ float update(float s) {
float y = s * -a + h;
h = y * a + s;
return y;
}
- AllpassDelay() { a =0; h = 0;}
-
+ AllpassDelay() {
+ a = 0;
+ h = 0;
+ }
};
AllpassDelay allpass[2][6];
-public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+public:
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectPhaser : public AudioEffect {
- GDCLASS(AudioEffectPhaser,AudioEffect)
+ GDCLASS(AudioEffectPhaser, AudioEffect)
-friend class AudioEffectPhaserInstance;
+ friend class AudioEffectPhaserInstance;
float range_min;
float range_max;
float rate;
@@ -80,11 +78,9 @@ friend class AudioEffectPhaserInstance;
float depth;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
void set_range_min_hz(float p_hz);
@@ -105,5 +101,4 @@ public:
AudioEffectPhaser();
};
-
#endif // AUDIO_EFFECT_PHASER_H
diff --git a/servers/audio/effects/audio_effect_pitch_shift.cpp b/servers/audio/effects/audio_effect_pitch_shift.cpp
index e00755e1a0..6a14ba7155 100644
--- a/servers/audio/effects/audio_effect_pitch_shift.cpp
+++ b/servers/audio/effects/audio_effect_pitch_shift.cpp
@@ -28,8 +28,8 @@
/*************************************************************************/
#include "audio_effect_pitch_shift.h"
-#include "servers/audio_server.h"
#include "math_funcs.h"
+#include "servers/audio_server.h"
/* Thirdparty code, so disable clang-format with Godot style */
/* clang-format off */
@@ -281,34 +281,31 @@ void SMBPitchShift::smbFft(float *fftBuffer, long fftFrameSize, long sign)
/* Godot code again */
/* clang-format on */
-void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
float sample_rate = AudioServer::get_singleton()->get_mix_rate();
- float *in_l = (float*)p_src_frames;
+ float *in_l = (float *)p_src_frames;
float *in_r = in_l + 1;
- float *out_l = (float*)p_dst_frames;
+ float *out_l = (float *)p_dst_frames;
float *out_r = out_l + 1;
- shift_l.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_l,out_l,2);
- shift_r.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_r,out_r,2);
-
+ shift_l.PitchShift(base->pitch_scale, p_frame_count, 2048, 4, sample_rate, in_l, out_l, 2);
+ shift_r.PitchShift(base->pitch_scale, p_frame_count, 2048, 4, sample_rate, in_r, out_r, 2);
}
-
Ref<AudioEffectInstance> AudioEffectPitchShift::instance() {
Ref<AudioEffectPitchShiftInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectPitchShift>(this);
-
+ ins->base = Ref<AudioEffectPitchShift>(this);
return ins;
}
void AudioEffectPitchShift::set_pitch_scale(float p_adjust) {
- pitch_scale=p_adjust;
+ pitch_scale = p_adjust;
}
float AudioEffectPitchShift::get_pitch_scale() const {
@@ -316,17 +313,14 @@ float AudioEffectPitchShift::get_pitch_scale() const {
return pitch_scale;
}
-
void AudioEffectPitchShift::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_pitch_scale","rate"),&AudioEffectPitchShift::set_pitch_scale);
- ClassDB::bind_method(D_METHOD("get_pitch_scale"),&AudioEffectPitchShift::get_pitch_scale);
-
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"pitch_scale",PROPERTY_HINT_RANGE,"0.01,16,0.01"),"set_pitch_scale","get_pitch_scale");
+ ClassDB::bind_method(D_METHOD("set_pitch_scale", "rate"), &AudioEffectPitchShift::set_pitch_scale);
+ ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioEffectPitchShift::get_pitch_scale);
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,16,0.01"), "set_pitch_scale", "get_pitch_scale");
}
AudioEffectPitchShift::AudioEffectPitchShift() {
- pitch_scale=1.0;
-
+ pitch_scale = 1.0;
}
diff --git a/servers/audio/effects/audio_effect_pitch_shift.h b/servers/audio/effects/audio_effect_pitch_shift.h
index 1320976f5f..610efdc0e1 100644
--- a/servers/audio/effects/audio_effect_pitch_shift.h
+++ b/servers/audio/effects/audio_effect_pitch_shift.h
@@ -29,21 +29,20 @@
#ifndef AUDIO_EFFECT_PITCH_SHIFT_H
#define AUDIO_EFFECT_PITCH_SHIFT_H
-
#include "servers/audio/audio_effect.h"
class SMBPitchShift {
enum {
- MAX_FRAME_LENGTH=8192
+ MAX_FRAME_LENGTH = 8192
};
float gInFIFO[MAX_FRAME_LENGTH];
float gOutFIFO[MAX_FRAME_LENGTH];
- float gFFTworksp[2*MAX_FRAME_LENGTH];
- float gLastPhase[MAX_FRAME_LENGTH/2+1];
- float gSumPhase[MAX_FRAME_LENGTH/2+1];
- float gOutputAccum[2*MAX_FRAME_LENGTH];
+ float gFFTworksp[2 * MAX_FRAME_LENGTH];
+ float gLastPhase[MAX_FRAME_LENGTH / 2 + 1];
+ float gSumPhase[MAX_FRAME_LENGTH / 2 + 1];
+ float gOutputAccum[2 * MAX_FRAME_LENGTH];
float gAnaFreq[MAX_FRAME_LENGTH];
float gAnaMagn[MAX_FRAME_LENGTH];
float gSynFreq[MAX_FRAME_LENGTH];
@@ -51,47 +50,41 @@ class SMBPitchShift {
long gRover;
void smbFft(float *fftBuffer, long fftFrameSize, long sign);
+
public:
void PitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize, long osamp, float sampleRate, float *indata, float *outdata, int stride);
SMBPitchShift() {
- gRover=0;
- memset(gInFIFO, 0, MAX_FRAME_LENGTH*sizeof(float));
- memset(gOutFIFO, 0, MAX_FRAME_LENGTH*sizeof(float));
- memset(gFFTworksp, 0, 2*MAX_FRAME_LENGTH*sizeof(float));
- memset(gLastPhase, 0, (MAX_FRAME_LENGTH/2+1)*sizeof(float));
- memset(gSumPhase, 0, (MAX_FRAME_LENGTH/2+1)*sizeof(float));
- memset(gOutputAccum, 0, 2*MAX_FRAME_LENGTH*sizeof(float));
- memset(gAnaFreq, 0, MAX_FRAME_LENGTH*sizeof(float));
- memset(gAnaMagn, 0, MAX_FRAME_LENGTH*sizeof(float));
+ gRover = 0;
+ memset(gInFIFO, 0, MAX_FRAME_LENGTH * sizeof(float));
+ memset(gOutFIFO, 0, MAX_FRAME_LENGTH * sizeof(float));
+ memset(gFFTworksp, 0, 2 * MAX_FRAME_LENGTH * sizeof(float));
+ memset(gLastPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float));
+ memset(gSumPhase, 0, (MAX_FRAME_LENGTH / 2 + 1) * sizeof(float));
+ memset(gOutputAccum, 0, 2 * MAX_FRAME_LENGTH * sizeof(float));
+ memset(gAnaFreq, 0, MAX_FRAME_LENGTH * sizeof(float));
+ memset(gAnaMagn, 0, MAX_FRAME_LENGTH * sizeof(float));
}
-
-
};
-
class AudioEffectPitchShift;
class AudioEffectPitchShiftInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectPitchShiftInstance,AudioEffectInstance)
-friend class AudioEffectPitchShift;
+ GDCLASS(AudioEffectPitchShiftInstance, AudioEffectInstance)
+ friend class AudioEffectPitchShift;
Ref<AudioEffectPitchShift> base;
SMBPitchShift shift_l;
SMBPitchShift shift_r;
-
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
-
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
};
-
class AudioEffectPitchShift : public AudioEffect {
- GDCLASS(AudioEffectPitchShift,AudioEffect)
+ GDCLASS(AudioEffectPitchShift, AudioEffect)
-friend class AudioEffectPitchShiftInstance;
+ friend class AudioEffectPitchShiftInstance;
float pitch_scale;
int window_size;
@@ -100,11 +93,9 @@ friend class AudioEffectPitchShiftInstance;
bool filter;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
void set_pitch_scale(float p_adjust);
@@ -113,5 +104,4 @@ public:
AudioEffectPitchShift();
};
-
#endif // AUDIO_EFFECT_PITCH_SHIFT_H
diff --git a/servers/audio/effects/audio_effect_reverb.cpp b/servers/audio/effects/audio_effect_reverb.cpp
index d668c63e8e..f01bd266b8 100644
--- a/servers/audio/effects/audio_effect_reverb.cpp
+++ b/servers/audio/effects/audio_effect_reverb.cpp
@@ -28,99 +28,98 @@
/*************************************************************************/
#include "audio_effect_reverb.h"
#include "servers/audio_server.h"
-void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
-
- for(int i=0;i<2;i++) {
- Reverb &r=reverb[i];
-
- r.set_predelay( base->predelay);
- r.set_predelay_feedback( base->predelay_fb );
- r.set_highpass( base->hpf );
- r.set_room_size( base->room_size );
- r.set_damp( base->damping );
- r.set_extra_spread( base->spread );
- r.set_wet( base->wet );
- r.set_dry( base->dry );
+void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
+
+ for (int i = 0; i < 2; i++) {
+ Reverb &r = reverb[i];
+
+ r.set_predelay(base->predelay);
+ r.set_predelay_feedback(base->predelay_fb);
+ r.set_highpass(base->hpf);
+ r.set_room_size(base->room_size);
+ r.set_damp(base->damping);
+ r.set_extra_spread(base->spread);
+ r.set_wet(base->wet);
+ r.set_dry(base->dry);
}
int todo = p_frame_count;
- int offset=0;
+ int offset = 0;
- while(todo) {
+ while (todo) {
- int to_mix = MIN(todo,Reverb::INPUT_BUFFER_MAX_SIZE);
+ int to_mix = MIN(todo, Reverb::INPUT_BUFFER_MAX_SIZE);
- for(int j=0;j<to_mix;j++) {
- tmp_src[j]=p_src_frames[offset+j].l;
+ for (int j = 0; j < to_mix; j++) {
+ tmp_src[j] = p_src_frames[offset + j].l;
}
- reverb[0].process(tmp_src,tmp_dst,to_mix);
+ reverb[0].process(tmp_src, tmp_dst, to_mix);
- for(int j=0;j<to_mix;j++) {
- p_dst_frames[offset+j].l=tmp_dst[j];
- tmp_src[j]=p_src_frames[offset+j].r;
+ for (int j = 0; j < to_mix; j++) {
+ p_dst_frames[offset + j].l = tmp_dst[j];
+ tmp_src[j] = p_src_frames[offset + j].r;
}
- reverb[1].process(tmp_src,tmp_dst,to_mix);
+ reverb[1].process(tmp_src, tmp_dst, to_mix);
- for(int j=0;j<to_mix;j++) {
- p_dst_frames[offset+j].r=tmp_dst[j];
+ for (int j = 0; j < to_mix; j++) {
+ p_dst_frames[offset + j].r = tmp_dst[j];
}
- offset+=to_mix;
- todo-=to_mix;
+ offset += to_mix;
+ todo -= to_mix;
}
}
AudioEffectReverbInstance::AudioEffectReverbInstance() {
- reverb[0].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() );
+ reverb[0].set_mix_rate(AudioServer::get_singleton()->get_mix_rate());
reverb[0].set_extra_spread_base(0);
- reverb[1].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() );
+ reverb[1].set_mix_rate(AudioServer::get_singleton()->get_mix_rate());
reverb[1].set_extra_spread_base(0.000521); //for stereo effect
-
}
Ref<AudioEffectInstance> AudioEffectReverb::instance() {
Ref<AudioEffectReverbInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectReverb>(this);
+ ins->base = Ref<AudioEffectReverb>(this);
return ins;
}
void AudioEffectReverb::set_predelay_msec(float p_msec) {
- predelay=p_msec;
+ predelay = p_msec;
}
-void AudioEffectReverb::set_predelay_feedback(float p_feedback){
+void AudioEffectReverb::set_predelay_feedback(float p_feedback) {
- predelay_fb=p_feedback;
+ predelay_fb = p_feedback;
}
-void AudioEffectReverb::set_room_size(float p_size){
+void AudioEffectReverb::set_room_size(float p_size) {
- room_size=p_size;
+ room_size = p_size;
}
-void AudioEffectReverb::set_damping(float p_damping){
+void AudioEffectReverb::set_damping(float p_damping) {
- damping=p_damping;
+ damping = p_damping;
}
-void AudioEffectReverb::set_spread(float p_spread){
+void AudioEffectReverb::set_spread(float p_spread) {
- spread=p_spread;
+ spread = p_spread;
}
-void AudioEffectReverb::set_dry(float p_dry){
+void AudioEffectReverb::set_dry(float p_dry) {
- dry=p_dry;
+ dry = p_dry;
}
-void AudioEffectReverb::set_wet(float p_wet){
+void AudioEffectReverb::set_wet(float p_wet) {
- wet=p_wet;
+ wet = p_wet;
}
void AudioEffectReverb::set_hpf(float p_hpf) {
- hpf=p_hpf;
+ hpf = p_hpf;
}
float AudioEffectReverb::get_predelay_msec() const {
@@ -156,55 +155,51 @@ float AudioEffectReverb::get_hpf() const {
return hpf;
}
-
void AudioEffectReverb::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_predelay_msec", "msec"), &AudioEffectReverb::set_predelay_msec);
+ ClassDB::bind_method(D_METHOD("get_predelay_msec"), &AudioEffectReverb::get_predelay_msec);
- ClassDB::bind_method(D_METHOD("set_predelay_msec","msec"),&AudioEffectReverb::set_predelay_msec);
- ClassDB::bind_method(D_METHOD("get_predelay_msec"),&AudioEffectReverb::get_predelay_msec);
-
- ClassDB::bind_method(D_METHOD("set_predelay_feedback","feedback"),&AudioEffectReverb::set_predelay_feedback);
- ClassDB::bind_method(D_METHOD("get_predelay_feedback"),&AudioEffectReverb::get_predelay_feedback);
+ ClassDB::bind_method(D_METHOD("set_predelay_feedback", "feedback"), &AudioEffectReverb::set_predelay_feedback);
+ ClassDB::bind_method(D_METHOD("get_predelay_feedback"), &AudioEffectReverb::get_predelay_feedback);
- ClassDB::bind_method(D_METHOD("set_room_size","size"),&AudioEffectReverb::set_room_size);
- ClassDB::bind_method(D_METHOD("get_room_size"),&AudioEffectReverb::get_room_size);
+ ClassDB::bind_method(D_METHOD("set_room_size", "size"), &AudioEffectReverb::set_room_size);
+ ClassDB::bind_method(D_METHOD("get_room_size"), &AudioEffectReverb::get_room_size);
- ClassDB::bind_method(D_METHOD("set_damping","amount"),&AudioEffectReverb::set_damping);
- ClassDB::bind_method(D_METHOD("get_damping"),&AudioEffectReverb::get_damping);
+ ClassDB::bind_method(D_METHOD("set_damping", "amount"), &AudioEffectReverb::set_damping);
+ ClassDB::bind_method(D_METHOD("get_damping"), &AudioEffectReverb::get_damping);
- ClassDB::bind_method(D_METHOD("set_spread","amount"),&AudioEffectReverb::set_spread);
- ClassDB::bind_method(D_METHOD("get_spread"),&AudioEffectReverb::get_spread);
+ ClassDB::bind_method(D_METHOD("set_spread", "amount"), &AudioEffectReverb::set_spread);
+ ClassDB::bind_method(D_METHOD("get_spread"), &AudioEffectReverb::get_spread);
- ClassDB::bind_method(D_METHOD("set_dry","amount"),&AudioEffectReverb::set_dry);
- ClassDB::bind_method(D_METHOD("get_dry"),&AudioEffectReverb::get_dry);
+ ClassDB::bind_method(D_METHOD("set_dry", "amount"), &AudioEffectReverb::set_dry);
+ ClassDB::bind_method(D_METHOD("get_dry"), &AudioEffectReverb::get_dry);
- ClassDB::bind_method(D_METHOD("set_wet","amount"),&AudioEffectReverb::set_wet);
- ClassDB::bind_method(D_METHOD("get_wet"),&AudioEffectReverb::get_wet);
+ ClassDB::bind_method(D_METHOD("set_wet", "amount"), &AudioEffectReverb::set_wet);
+ ClassDB::bind_method(D_METHOD("get_wet"), &AudioEffectReverb::get_wet);
- ClassDB::bind_method(D_METHOD("set_hpf","amount"),&AudioEffectReverb::set_hpf);
- ClassDB::bind_method(D_METHOD("get_hpf"),&AudioEffectReverb::get_hpf);
+ ClassDB::bind_method(D_METHOD("set_hpf", "amount"), &AudioEffectReverb::set_hpf);
+ ClassDB::bind_method(D_METHOD("get_hpf"), &AudioEffectReverb::get_hpf);
-
- ADD_GROUP("Predelay","predelay_");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_msec",PROPERTY_HINT_RANGE,"20,500,1"),"set_predelay_msec","get_predelay_msec");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_feedback",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_predelay_msec","get_predelay_msec");
- ADD_GROUP("","");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"room_size",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_room_size","get_room_size");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_damping","get_damping");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"spread",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_spread","get_spread");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"hipass",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_hpf","get_hpf");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_dry","get_dry");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_wet","get_wet");
+ ADD_GROUP("Predelay", "predelay_");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "predelay_msec", PROPERTY_HINT_RANGE, "20,500,1"), "set_predelay_msec", "get_predelay_msec");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "predelay_feedback", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_predelay_msec", "get_predelay_msec");
+ ADD_GROUP("", "");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "room_size", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_room_size", "get_room_size");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "damping", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_damping", "get_damping");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "spread", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_spread", "get_spread");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "hipass", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_hpf", "get_hpf");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "dry", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_dry", "get_dry");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "wet", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_wet", "get_wet");
}
AudioEffectReverb::AudioEffectReverb() {
- predelay=150;
- predelay_fb=0.4;
- hpf=0;
- room_size=0.8;
- damping=0.5;
- spread=1.0;
- dry=1.0;
- wet=0.5;
-
+ predelay = 150;
+ predelay_fb = 0.4;
+ hpf = 0;
+ room_size = 0.8;
+ damping = 0.5;
+ spread = 1.0;
+ dry = 1.0;
+ wet = 0.5;
}
diff --git a/servers/audio/effects/audio_effect_reverb.h b/servers/audio/effects/audio_effect_reverb.h
index 41b4f15cf0..2c665ca916 100644
--- a/servers/audio/effects/audio_effect_reverb.h
+++ b/servers/audio/effects/audio_effect_reverb.h
@@ -29,36 +29,32 @@
#ifndef AUDIOEFFECTREVERB_H
#define AUDIOEFFECTREVERB_H
-
#include "servers/audio/audio_effect.h"
#include "servers/audio/effects/reverb.h"
class AudioEffectReverb;
class AudioEffectReverbInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectReverbInstance,AudioEffectInstance)
+ GDCLASS(AudioEffectReverbInstance, AudioEffectInstance)
Ref<AudioEffectReverb> base;
float tmp_src[Reverb::INPUT_BUFFER_MAX_SIZE];
float tmp_dst[Reverb::INPUT_BUFFER_MAX_SIZE];
-friend class AudioEffectReverb;
+ friend class AudioEffectReverb;
Reverb reverb[2];
-
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
AudioEffectReverbInstance();
};
-
class AudioEffectReverb : public AudioEffect {
- GDCLASS(AudioEffectReverb,AudioEffect)
+ GDCLASS(AudioEffectReverb, AudioEffect)
-friend class AudioEffectReverbInstance;
+ friend class AudioEffectReverbInstance;
float predelay;
float predelay_fb;
@@ -70,11 +66,9 @@ friend class AudioEffectReverbInstance;
float wet;
protected:
-
static void _bind_methods();
-public:
-
+public:
void set_predelay_msec(float p_msec);
void set_predelay_feedback(float p_feedback);
void set_room_size(float p_size);
@@ -100,5 +94,4 @@ public:
AudioEffectReverb();
};
-
#endif // AUDIOEFFECTREVERB_H
diff --git a/servers/audio/effects/audio_effect_stereo_enhance.cpp b/servers/audio/effects/audio_effect_stereo_enhance.cpp
index 388c38ed17..9aed528bd3 100644
--- a/servers/audio/effects/audio_effect_stereo_enhance.cpp
+++ b/servers/audio/effects/audio_effect_stereo_enhance.cpp
@@ -28,55 +28,50 @@
/*************************************************************************/
#include "audio_effect_stereo_enhance.h"
#include "servers/audio_server.h"
-void AudioEffectStereoEnhanceInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) {
+void AudioEffectStereoEnhanceInstance::process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count) {
+ float intensity = base->pan_pullout;
+ bool surround_mode = base->surround > 0;
+ float surround_amount = base->surround;
+ unsigned int delay_frames = (base->time_pullout / 1000.0) * AudioServer::get_singleton()->get_mix_rate();
- float intensity=base->pan_pullout;
- bool surround_mode=base->surround>0;
- float surround_amount=base->surround;
- unsigned int delay_frames=(base->time_pullout/1000.0)*AudioServer::get_singleton()->get_mix_rate();
+ for (int i = 0; i < p_frame_count; i++) {
- for (int i=0;i<p_frame_count;i++) {
+ float l = p_src_frames[i].l;
+ float r = p_src_frames[i].r;
- float l=p_src_frames[i].l;
- float r=p_src_frames[i].r;
+ float center = (l + r) / 2.0f;
- float center=(l+r)/2.0f;
-
- l=( center+(l-center)*intensity );
- r=( center+(r-center)*intensity );
+ l = (center + (l - center) * intensity);
+ r = (center + (r - center) * intensity);
if (surround_mode) {
- float val=(l+r)/2.0;
+ float val = (l + r) / 2.0;
- delay_ringbuff[ringbuff_pos&ringbuff_mask]=val;
+ delay_ringbuff[ringbuff_pos & ringbuff_mask] = val;
- float out=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask]*surround_amount;
+ float out = delay_ringbuff[(ringbuff_pos - delay_frames) & ringbuff_mask] * surround_amount;
- l+=out;
- r+=-out;
+ l += out;
+ r += -out;
} else {
- float val=r;
+ float val = r;
- delay_ringbuff[ringbuff_pos&ringbuff_mask]=val;
+ delay_ringbuff[ringbuff_pos & ringbuff_mask] = val;
//r is delayed
- r=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask];;
-
-
+ r = delay_ringbuff[(ringbuff_pos - delay_frames) & ringbuff_mask];
+ ;
}
- p_dst_frames[i].l=l;
- p_dst_frames[i].r=r;
+ p_dst_frames[i].l = l;
+ p_dst_frames[i].r = r;
ringbuff_pos++;
-
}
-
}
-
AudioEffectStereoEnhanceInstance::~AudioEffectStereoEnhanceInstance() {
memdelete_arr(delay_ringbuff);
@@ -86,78 +81,76 @@ Ref<AudioEffectInstance> AudioEffectStereoEnhance::instance() {
Ref<AudioEffectStereoEnhanceInstance> ins;
ins.instance();
- ins->base=Ref<AudioEffectStereoEnhance>(this);
-
+ ins->base = Ref<AudioEffectStereoEnhance>(this);
- float ring_buffer_max_size=AudioEffectStereoEnhanceInstance::MAX_DELAY_MS+2;
- ring_buffer_max_size/=1000.0;//convert to seconds
- ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate();
+ float ring_buffer_max_size = AudioEffectStereoEnhanceInstance::MAX_DELAY_MS + 2;
+ ring_buffer_max_size /= 1000.0; //convert to seconds
+ ring_buffer_max_size *= AudioServer::get_singleton()->get_mix_rate();
- int ringbuff_size=(int)ring_buffer_max_size;
+ int ringbuff_size = (int)ring_buffer_max_size;
- int bits=0;
+ int bits = 0;
- while(ringbuff_size>0) {
+ while (ringbuff_size > 0) {
bits++;
- ringbuff_size/=2;
+ ringbuff_size /= 2;
}
- ringbuff_size=1<<bits;
- ins->ringbuff_mask=ringbuff_size-1;
- ins->ringbuff_pos=0;
+ ringbuff_size = 1 << bits;
+ ins->ringbuff_mask = ringbuff_size - 1;
+ ins->ringbuff_pos = 0;
- ins->delay_ringbuff = memnew_arr(float,ringbuff_size );
+ ins->delay_ringbuff = memnew_arr(float, ringbuff_size);
return ins;
}
-void AudioEffectStereoEnhance::set_pan_pullout(float p_amount) {
+void AudioEffectStereoEnhance::set_pan_pullout(float p_amount) {
- pan_pullout=p_amount;
+ pan_pullout = p_amount;
}
-float AudioEffectStereoEnhance::get_pan_pullout() const {
+float AudioEffectStereoEnhance::get_pan_pullout() const {
return pan_pullout;
}
-void AudioEffectStereoEnhance::set_time_pullout(float p_amount) {
+void AudioEffectStereoEnhance::set_time_pullout(float p_amount) {
- time_pullout=p_amount;
+ time_pullout = p_amount;
}
-float AudioEffectStereoEnhance::get_time_pullout() const {
+float AudioEffectStereoEnhance::get_time_pullout() const {
return time_pullout;
}
-void AudioEffectStereoEnhance::set_surround(float p_amount) {
+void AudioEffectStereoEnhance::set_surround(float p_amount) {
- surround=p_amount;
+ surround = p_amount;
}
-float AudioEffectStereoEnhance::get_surround() const {
+float AudioEffectStereoEnhance::get_surround() const {
return surround;
}
void AudioEffectStereoEnhance::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_pan_pullout","amount"),&AudioEffectStereoEnhance::set_pan_pullout);
- ClassDB::bind_method(D_METHOD("get_pan_pullout"),&AudioEffectStereoEnhance::get_pan_pullout);
+ ClassDB::bind_method(D_METHOD("set_pan_pullout", "amount"), &AudioEffectStereoEnhance::set_pan_pullout);
+ ClassDB::bind_method(D_METHOD("get_pan_pullout"), &AudioEffectStereoEnhance::get_pan_pullout);
- ClassDB::bind_method(D_METHOD("set_time_pullout","amount"),&AudioEffectStereoEnhance::set_time_pullout);
- ClassDB::bind_method(D_METHOD("get_time_pullout"),&AudioEffectStereoEnhance::get_time_pullout);
+ ClassDB::bind_method(D_METHOD("set_time_pullout", "amount"), &AudioEffectStereoEnhance::set_time_pullout);
+ ClassDB::bind_method(D_METHOD("get_time_pullout"), &AudioEffectStereoEnhance::get_time_pullout);
- ClassDB::bind_method(D_METHOD("set_surround","amount"),&AudioEffectStereoEnhance::set_surround);
- ClassDB::bind_method(D_METHOD("get_surround"),&AudioEffectStereoEnhance::get_surround);
+ ClassDB::bind_method(D_METHOD("set_surround", "amount"), &AudioEffectStereoEnhance::set_surround);
+ ClassDB::bind_method(D_METHOD("get_surround"), &AudioEffectStereoEnhance::get_surround);
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"pan_pullout",PROPERTY_HINT_RANGE,"0,4,0.01"),"set_pan_pullout","get_pan_pullout");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"time_pullout_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),"set_time_pullout","get_time_pullout");
- ADD_PROPERTY(PropertyInfo(Variant::REAL,"surround",PROPERTY_HINT_RANGE,"0,1,0.01"),"set_surround","get_surround");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "pan_pullout", PROPERTY_HINT_RANGE, "0,4,0.01"), "set_pan_pullout", "get_pan_pullout");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "time_pullout_ms", PROPERTY_HINT_RANGE, "0,50,0.01"), "set_time_pullout", "get_time_pullout");
+ ADD_PROPERTY(PropertyInfo(Variant::REAL, "surround", PROPERTY_HINT_RANGE, "0,1,0.01"), "set_surround", "get_surround");
}
-AudioEffectStereoEnhance::AudioEffectStereoEnhance()
-{
- pan_pullout=1;
- time_pullout=0;
- surround=0;
+AudioEffectStereoEnhance::AudioEffectStereoEnhance() {
+ pan_pullout = 1;
+ time_pullout = 0;
+ surround = 0;
}
diff --git a/servers/audio/effects/audio_effect_stereo_enhance.h b/servers/audio/effects/audio_effect_stereo_enhance.h
index 5eef8a33b2..21331692e9 100644
--- a/servers/audio/effects/audio_effect_stereo_enhance.h
+++ b/servers/audio/effects/audio_effect_stereo_enhance.h
@@ -29,38 +29,34 @@
#ifndef AUDIOEFFECTSTEREOENHANCE_H
#define AUDIOEFFECTSTEREOENHANCE_H
-
#include "servers/audio/audio_effect.h"
class AudioEffectStereoEnhance;
class AudioEffectStereoEnhanceInstance : public AudioEffectInstance {
- GDCLASS(AudioEffectStereoEnhanceInstance,AudioEffectInstance)
-friend class AudioEffectStereoEnhance;
+ GDCLASS(AudioEffectStereoEnhanceInstance, AudioEffectInstance)
+ friend class AudioEffectStereoEnhance;
Ref<AudioEffectStereoEnhance> base;
enum {
- MAX_DELAY_MS=50
+ MAX_DELAY_MS = 50
};
float *delay_ringbuff;
unsigned int ringbuff_pos;
unsigned int ringbuff_mask;
-
public:
-
- virtual void process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count);
+ virtual void process(const AudioFrame *p_src_frames, AudioFrame *p_dst_frames, int p_frame_count);
~AudioEffectStereoEnhanceInstance();
};
-
class AudioEffectStereoEnhance : public AudioEffect {
- GDCLASS(AudioEffectStereoEnhance,AudioEffect)
+ GDCLASS(AudioEffectStereoEnhance, AudioEffect)
-friend class AudioEffectStereoEnhanceInstance;
+ friend class AudioEffectStereoEnhanceInstance;
float volume_db;
float pan_pullout;
@@ -68,11 +64,9 @@ friend class AudioEffectStereoEnhanceInstance;
float surround;
protected:
-
static void _bind_methods();
-public:
-
+public:
Ref<AudioEffectInstance> instance();
void set_pan_pullout(float p_amount);
diff --git a/servers/audio/effects/eq.cpp b/servers/audio/effects/eq.cpp
index 4b461e97bb..857f81e856 100644
--- a/servers/audio/effects/eq.cpp
+++ b/servers/audio/effects/eq.cpp
@@ -30,135 +30,119 @@
// Author: reduzio@gmail.com (C) 2006
#include "eq.h"
-#include <math.h>
#include "error_macros.h"
#include "math_funcs.h"
+#include <math.h>
-#define POW2(v) ((v)*(v))
+#define POW2(v) ((v) * (v))
/* Helper */
- static int solve_quadratic(double a,double b,double c,double *r1, double *r2) {
-//solves quadractic and returns number of roots
+static int solve_quadratic(double a, double b, double c, double *r1, double *r2) {
+ //solves quadractic and returns number of roots
- double base=2*a;
+ double base = 2 * a;
if (base == 0.0f)
return 0;
- double squared=b*b-4*a*c;
- if (squared<0.0)
+ double squared = b * b - 4 * a * c;
+ if (squared < 0.0)
return 0;
- squared=sqrt(squared);
+ squared = sqrt(squared);
- *r1=(-b+squared)/base;
- *r2=(-b-squared)/base;
+ *r1 = (-b + squared) / base;
+ *r2 = (-b - squared) / base;
- if (*r1==*r2)
+ if (*r1 == *r2)
return 1;
else
return 2;
- }
+}
EQ::BandProcess::BandProcess() {
- c1=c2=c3=history.a1=history.a2=history.a3=0;
- history.b1=history.b2=history.b3=0;
+ c1 = c2 = c3 = history.a1 = history.a2 = history.a3 = 0;
+ history.b1 = history.b2 = history.b3 = 0;
}
void EQ::recalculate_band_coefficients() {
-#define BAND_LOG( m_f ) ( log((m_f)) / log(2.) )
+#define BAND_LOG(m_f) (log((m_f)) / log(2.))
- for (int i=0;i<band.size();i++) {
+ for (int i = 0; i < band.size(); i++) {
double octave_size;
- double frq=band[i].freq;
+ double frq = band[i].freq;
- if (i==0) {
+ if (i == 0) {
- octave_size=BAND_LOG(band[1].freq)-BAND_LOG(frq);
- } else if (i==(band.size()-1)) {
+ octave_size = BAND_LOG(band[1].freq) - BAND_LOG(frq);
+ } else if (i == (band.size() - 1)) {
- octave_size=BAND_LOG(frq)-BAND_LOG(band[i-1].freq);
+ octave_size = BAND_LOG(frq) - BAND_LOG(band[i - 1].freq);
} else {
- double next=BAND_LOG(band[i+1].freq)-BAND_LOG(frq);
- double prev=BAND_LOG(frq)-BAND_LOG(band[i-1].freq);
- octave_size=(next+prev)/2.0;
+ double next = BAND_LOG(band[i + 1].freq) - BAND_LOG(frq);
+ double prev = BAND_LOG(frq) - BAND_LOG(band[i - 1].freq);
+ octave_size = (next + prev) / 2.0;
}
+ double frq_l = round(frq / pow(2.0, octave_size / 2.0));
+ double side_gain2 = POW2(Math_SQRT12);
+ double th = 2.0 * Math_PI * frq / mix_rate;
+ double th_l = 2.0 * Math_PI * frq_l / mix_rate;
- double frq_l=round(frq/pow(2.0,octave_size/2.0));
-
-
+ double c2a = side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) + side_gain2 - POW2(sin(th_l));
- double side_gain2=POW2(Math_SQRT12);
- double th=2.0*Math_PI*frq/mix_rate;
- double th_l=2.0*Math_PI*frq_l/mix_rate;
+ double c2b = 2.0 * side_gain2 * POW2(cos(th_l)) + side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) - side_gain2 + POW2(sin(th_l));
- double c2a=side_gain2 * POW2(cos(th))
- - 2.0 * side_gain2 * cos(th_l) * cos(th)
- + side_gain2
- - POW2(sin(th_l));
-
- double c2b=2.0 * side_gain2 * POW2(cos(th_l))
- + side_gain2 * POW2(cos(th))
- - 2.0 * side_gain2 * cos(th_l) * cos(th)
- - side_gain2
- + POW2(sin(th_l));
-
- double c2c=0.25 * side_gain2 * POW2(cos(th))
- - 0.5 * side_gain2 * cos(th_l) * cos(th)
- + 0.25 * side_gain2
- - 0.25 * POW2(sin(th_l));
+ double c2c = 0.25 * side_gain2 * POW2(cos(th)) - 0.5 * side_gain2 * cos(th_l) * cos(th) + 0.25 * side_gain2 - 0.25 * POW2(sin(th_l));
//printf("band %i, precoefs = %f,%f,%f\n",i,c2a,c2b,c2c);
- double r1,r2; //roots
- int roots=solve_quadratic(c2a,c2b,c2c,&r1,&r2);
+ double r1, r2; //roots
+ int roots = solve_quadratic(c2a, c2b, c2c, &r1, &r2);
- ERR_CONTINUE( roots==0 );
+ ERR_CONTINUE(roots == 0);
- band[i].c1=2.0 * ((0.5-r1)/2.0);
- band[i].c2=2.0 * r1;
- band[i].c3=2.0 * (0.5+r1) * cos(th);
+ band[i].c1 = 2.0 * ((0.5 - r1) / 2.0);
+ band[i].c2 = 2.0 * r1;
+ band[i].c3 = 2.0 * (0.5 + r1) * cos(th);
//printf("band %i, coefs = %f,%f,%f\n",i,(float)bands[i].c1,(float)bands[i].c2,(float)bands[i].c3);
-
}
}
void EQ::set_preset_band_mode(Preset p_preset) {
-
band.clear();
-#define PUSH_BANDS(m_bands) \
- for (int i=0;i<m_bands;i++) { \
- Band b; \
- b.freq=bands[i];\
- band.push_back(b);\
+#define PUSH_BANDS(m_bands) \
+ for (int i = 0; i < m_bands; i++) { \
+ Band b; \
+ b.freq = bands[i]; \
+ band.push_back(b); \
}
switch (p_preset) {
case PRESET_6_BANDS: {
- static const double bands[] = { 32 , 100 , 320 , 1e3, 3200, 10e3 };
+ static const double bands[] = { 32, 100, 320, 1e3, 3200, 10e3 };
PUSH_BANDS(6);
} break;
case PRESET_8_BANDS: {
- static const double bands[] = { 32,72,192,512,1200,3000,7500,16e3 };
+ static const double bands[] = { 32, 72, 192, 512, 1200, 3000, 7500, 16e3 };
PUSH_BANDS(8);
} break;
case PRESET_10_BANDS: {
- static const double bands[] = { 31.25, 62.5, 125 , 250 , 500 , 1e3, 2e3, 4e3, 8e3, 16e3 };
+ static const double bands[] = { 31.25, 62.5, 125, 250, 500, 1e3, 2e3, 4e3, 8e3, 16e3 };
PUSH_BANDS(10);
@@ -166,17 +150,16 @@ void EQ::set_preset_band_mode(Preset p_preset) {
case PRESET_21_BANDS: {
- static const double bands[] = { 22 , 32 , 44 , 63 , 90 , 125 , 175 , 250 , 350 , 500 , 700 , 1e3, 1400 , 2e3, 2800 , 4e3, 5600 , 8e3, 11e3, 16e3, 22e3 };
+ static const double bands[] = { 22, 32, 44, 63, 90, 125, 175, 250, 350, 500, 700, 1e3, 1400, 2e3, 2800, 4e3, 5600, 8e3, 11e3, 16e3, 22e3 };
PUSH_BANDS(21);
} break;
case PRESET_31_BANDS: {
- static const double bands[] = { 20, 25, 31.5, 40 , 50 , 63 , 80 , 100 , 125 , 160 , 200 , 250 , 315 , 400 , 500 , 630 , 800 , 1e3 , 1250 , 1600 , 2e3, 2500 , 3150 , 4e3, 5e3, 6300 , 8e3, 10e3, 12500 , 16e3, 20e3 };
+ static const double bands[] = { 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1e3, 1250, 1600, 2e3, 2500, 3150, 4e3, 5e3, 6300, 8e3, 10e3, 12500, 16e3, 20e3 };
PUSH_BANDS(31);
} break;
-
};
recalculate_band_coefficients();
@@ -188,52 +171,42 @@ int EQ::get_band_count() const {
}
float EQ::get_band_frequency(int p_band) {
- ERR_FAIL_INDEX_V(p_band,band.size(),0);
+ ERR_FAIL_INDEX_V(p_band, band.size(), 0);
return band[p_band].freq;
}
-void EQ::set_bands(const Vector<float>& p_bands) {
+void EQ::set_bands(const Vector<float> &p_bands) {
band.resize(p_bands.size());
- for (int i=0;i<p_bands.size();i++) {
+ for (int i = 0; i < p_bands.size(); i++) {
- band[i].freq=p_bands[i];
+ band[i].freq = p_bands[i];
}
recalculate_band_coefficients();
-
}
void EQ::set_mix_rate(float p_mix_rate) {
- mix_rate=p_mix_rate;
+ mix_rate = p_mix_rate;
recalculate_band_coefficients();
}
EQ::BandProcess EQ::get_band_processor(int p_band) const {
-
EQ::BandProcess band_proc;
- ERR_FAIL_INDEX_V(p_band,band.size(),band_proc);
+ ERR_FAIL_INDEX_V(p_band, band.size(), band_proc);
- band_proc.c1=band[p_band].c1;
- band_proc.c2=band[p_band].c2;
- band_proc.c3=band[p_band].c3;
+ band_proc.c1 = band[p_band].c1;
+ band_proc.c2 = band[p_band].c2;
+ band_proc.c3 = band[p_band].c3;
return band_proc;
-
-
}
-
-EQ::EQ()
-{
- mix_rate=44100;
+EQ::EQ() {
+ mix_rate = 44100;
}
-
-EQ::~EQ()
-{
+EQ::~EQ() {
}
-
-
diff --git a/servers/audio/effects/eq.h b/servers/audio/effects/eq.h
index 1a568ee213..a6d471cc4a 100644
--- a/servers/audio/effects/eq.h
+++ b/servers/audio/effects/eq.h
@@ -32,18 +32,15 @@
#ifndef EQ_FILTER_H
#define EQ_FILTER_H
-
#include "typedefs.h"
#include "vector.h"
-
/**
@author Juan Linietsky
*/
class EQ {
public:
-
enum Preset {
PRESET_6_BANDS,
@@ -53,21 +50,18 @@ public:
PRESET_31_BANDS
};
-
-
class BandProcess {
- friend class EQ;
- float c1,c2,c3;
+ friend class EQ;
+ float c1, c2, c3;
struct History {
- float a1,a2,a3;
- float b1,b2,b3;
+ float a1, a2, a3;
+ float b1, b2, b3;
} history;
public:
-
- inline void process_one(float & p_data);
+ inline void process_one(float &p_data);
BandProcess();
};
@@ -76,7 +70,7 @@ private:
struct Band {
float freq;
- float c1,c2,c3;
+ float c1, c2, c3;
};
Vector<Band> band;
@@ -86,41 +80,32 @@ private:
void recalculate_band_coefficients();
public:
-
-
void set_mix_rate(float p_mix_rate);
int get_band_count() const;
void set_preset_band_mode(Preset p_preset);
- void set_bands(const Vector<float>& p_bands);
+ void set_bands(const Vector<float> &p_bands);
BandProcess get_band_processor(int p_band) const;
float get_band_frequency(int p_band);
EQ();
~EQ();
-
};
-
/* Inline Function */
-inline void EQ::BandProcess::process_one(float & p_data) {
+inline void EQ::BandProcess::process_one(float &p_data) {
+ history.a1 = p_data;
- history.a1=p_data;
-
- history.b1= c1 * ( history.a1 - history.a3 )
- + c3 * history.b2
- - c2 * history.b3;
+ history.b1 = c1 * (history.a1 - history.a3) + c3 * history.b2 - c2 * history.b3;
p_data = history.b1;
- history.a3=history.a2;
- history.a2=history.a1;
- history.b3=history.b2;
- history.b2=history.b1;
-
+ history.a3 = history.a2;
+ history.a2 = history.a1;
+ history.b3 = history.b2;
+ history.b2 = history.b1;
}
-
#endif
diff --git a/servers/audio/effects/reverb.cpp b/servers/audio/effects/reverb.cpp
index bc3212201f..6462977d7c 100644
--- a/servers/audio/effects/reverb.cpp
+++ b/servers/audio/effects/reverb.cpp
@@ -30,11 +30,10 @@
// Author: Juan Linietsky <reduzio@gmail.com>, (C) 2006
#include "reverb.h"
-#include <math.h>
#include "math_funcs.h"
+#include <math.h>
-
-const float Reverb::comb_tunings[MAX_COMBS]={
+const float Reverb::comb_tunings[MAX_COMBS] = {
//freeverb comb tunings
0.025306122448979593,
0.026938775510204082,
@@ -46,7 +45,7 @@ const float Reverb::comb_tunings[MAX_COMBS]={
0.036666666666666667
};
-const float Reverb::allpass_tunings[MAX_ALLPASS]={
+const float Reverb::allpass_tunings[MAX_ALLPASS] = {
//freeverb allpass tunings
0.0051020408163265302,
0.007732426303854875,
@@ -54,76 +53,72 @@ const float Reverb::allpass_tunings[MAX_ALLPASS]={
0.012607709750566893
};
+void Reverb::process(float *p_src, float *p_dst, int p_frames) {
+ if (p_frames > INPUT_BUFFER_MAX_SIZE)
+ p_frames = INPUT_BUFFER_MAX_SIZE;
-void Reverb::process(float *p_src,float *p_dst,int p_frames) {
-
- if (p_frames>INPUT_BUFFER_MAX_SIZE)
- p_frames=INPUT_BUFFER_MAX_SIZE;
-
- int predelay_frames=lrint((params.predelay/1000.0)*params.mix_rate);
- if (predelay_frames<10)
- predelay_frames=10;
- if (predelay_frames>=echo_buffer_size)
- predelay_frames=echo_buffer_size-1;
+ int predelay_frames = lrint((params.predelay / 1000.0) * params.mix_rate);
+ if (predelay_frames < 10)
+ predelay_frames = 10;
+ if (predelay_frames >= echo_buffer_size)
+ predelay_frames = echo_buffer_size - 1;
- for (int i=0;i<p_frames;i++) {
+ for (int i = 0; i < p_frames; i++) {
- if (echo_buffer_pos>=echo_buffer_size)
- echo_buffer_pos=0;
+ if (echo_buffer_pos >= echo_buffer_size)
+ echo_buffer_pos = 0;
- int read_pos=echo_buffer_pos-predelay_frames;
- while (read_pos<0)
- read_pos+=echo_buffer_size;
+ int read_pos = echo_buffer_pos - predelay_frames;
+ while (read_pos < 0)
+ read_pos += echo_buffer_size;
- float in=undenormalise(echo_buffer[read_pos]*params.predelay_fb+p_src[i]);
+ float in = undenormalise(echo_buffer[read_pos] * params.predelay_fb + p_src[i]);
- echo_buffer[echo_buffer_pos]=in;
+ echo_buffer[echo_buffer_pos] = in;
- input_buffer[i]=in;
+ input_buffer[i] = in;
- p_dst[i]=0; //take the chance and clear this
+ p_dst[i] = 0; //take the chance and clear this
echo_buffer_pos++;
}
- if (params.hpf>0) {
- float hpaux=expf(-2.0*Math_PI*params.hpf*6000/params.mix_rate);
- float hp_a1=(1.0+hpaux)/2.0;
- float hp_a2=-(1.0+hpaux)/2.0;
- float hp_b1=hpaux;
+ if (params.hpf > 0) {
+ float hpaux = expf(-2.0 * Math_PI * params.hpf * 6000 / params.mix_rate);
+ float hp_a1 = (1.0 + hpaux) / 2.0;
+ float hp_a2 = -(1.0 + hpaux) / 2.0;
+ float hp_b1 = hpaux;
- for (int i=0;i<p_frames;i++) {
+ for (int i = 0; i < p_frames; i++) {
- float in=input_buffer[i];
- input_buffer[i]=in*hp_a1+hpf_h1*hp_a2+hpf_h2*hp_b1;
- hpf_h2=input_buffer[i];
- hpf_h1=in;
+ float in = input_buffer[i];
+ input_buffer[i] = in * hp_a1 + hpf_h1 * hp_a2 + hpf_h2 * hp_b1;
+ hpf_h2 = input_buffer[i];
+ hpf_h1 = in;
}
}
- for (int i=0;i<MAX_COMBS;i++) {
+ for (int i = 0; i < MAX_COMBS; i++) {
- Comb &c=comb[i];
+ Comb &c = comb[i];
- int size_limit=c.size-lrintf((float)c.extra_spread_frames*(1.0-params.extra_spread));
- for (int j=0;j<p_frames;j++) {
+ int size_limit = c.size - lrintf((float)c.extra_spread_frames * (1.0 - params.extra_spread));
+ for (int j = 0; j < p_frames; j++) {
- if (c.pos>=size_limit) //reset this now just in case
- c.pos=0;
+ if (c.pos >= size_limit) //reset this now just in case
+ c.pos = 0;
- float out=undenormalise(c.buffer[c.pos]*c.feedback);
- out=out*(1.0-c.damp)+c.damp_h*c.damp; //lowpass
- c.damp_h=out;
- c.buffer[c.pos]=input_buffer[j]+out;
- p_dst[j]+=out;
+ float out = undenormalise(c.buffer[c.pos] * c.feedback);
+ out = out * (1.0 - c.damp) + c.damp_h * c.damp; //lowpass
+ c.damp_h = out;
+ c.buffer[c.pos] = input_buffer[j] + out;
+ p_dst[j] += out;
c.pos++;
}
-
}
-
- static const float allpass_feedback=0.7;
+ static const float allpass_feedback = 0.7;
/* this one works, but the other version is just nicer....
int ap_size_limit[MAX_ALLPASS];
@@ -158,170 +153,154 @@ void Reverb::process(float *p_src,float *p_dst,int p_frames) {
}
*/
- for (int i=0;i<MAX_ALLPASS;i++) {
+ for (int i = 0; i < MAX_ALLPASS; i++) {
- AllPass &a=allpass[i];
- int size_limit=a.size-lrintf((float)a.extra_spread_frames*(1.0-params.extra_spread));
+ AllPass &a = allpass[i];
+ int size_limit = a.size - lrintf((float)a.extra_spread_frames * (1.0 - params.extra_spread));
- for (int j=0;j<p_frames;j++) {
+ for (int j = 0; j < p_frames; j++) {
- if (a.pos>=size_limit)
- a.pos=0;
+ if (a.pos >= size_limit)
+ a.pos = 0;
- float aux=a.buffer[a.pos];
- a.buffer[a.pos]=undenormalise(allpass_feedback*aux+p_dst[j]);
- p_dst[j]=aux-allpass_feedback*a.buffer[a.pos];
+ float aux = a.buffer[a.pos];
+ a.buffer[a.pos] = undenormalise(allpass_feedback * aux + p_dst[j]);
+ p_dst[j] = aux - allpass_feedback * a.buffer[a.pos];
a.pos++;
-
}
}
- static const float wet_scale=0.6;
-
- for (int i=0;i<p_frames;i++) {
+ static const float wet_scale = 0.6;
+ for (int i = 0; i < p_frames; i++) {
- p_dst[i]=p_dst[i]*params.wet*wet_scale+p_src[i]*params.dry;
+ p_dst[i] = p_dst[i] * params.wet * wet_scale + p_src[i] * params.dry;
}
-
}
-
void Reverb::set_room_size(float p_size) {
- params.room_size=p_size;
+ params.room_size = p_size;
update_parameters();
-
}
void Reverb::set_damp(float p_damp) {
- params.damp=p_damp;
+ params.damp = p_damp;
update_parameters();
-
}
void Reverb::set_wet(float p_wet) {
- params.wet=p_wet;
-
+ params.wet = p_wet;
}
void Reverb::set_dry(float p_dry) {
- params.dry=p_dry;
-
+ params.dry = p_dry;
}
void Reverb::set_predelay(float p_predelay) {
- params.predelay=p_predelay;
+ params.predelay = p_predelay;
}
void Reverb::set_predelay_feedback(float p_predelay_fb) {
- params.predelay_fb=p_predelay_fb;
-
+ params.predelay_fb = p_predelay_fb;
}
void Reverb::set_highpass(float p_frq) {
- if (p_frq>1)
- p_frq=1;
- if (p_frq<0)
- p_frq=0;
- params.hpf=p_frq;
+ if (p_frq > 1)
+ p_frq = 1;
+ if (p_frq < 0)
+ p_frq = 0;
+ params.hpf = p_frq;
}
void Reverb::set_extra_spread(float p_spread) {
- params.extra_spread=p_spread;
-
+ params.extra_spread = p_spread;
}
-
void Reverb::set_mix_rate(float p_mix_rate) {
- params.mix_rate=p_mix_rate;
+ params.mix_rate = p_mix_rate;
configure_buffers();
}
void Reverb::set_extra_spread_base(float p_sec) {
- params.extra_spread_base=p_sec;
+ params.extra_spread_base = p_sec;
configure_buffers();
}
-
void Reverb::configure_buffers() {
clear_buffers(); //clear if necesary
- for (int i=0;i<MAX_COMBS;i++) {
-
- Comb &c=comb[i];
-
+ for (int i = 0; i < MAX_COMBS; i++) {
- c.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate);
+ Comb &c = comb[i];
- int len=lrint(comb_tunings[i]*params.mix_rate)+c.extra_spread_frames;
- if (len<5)
- len=5; //may this happen?
+ c.extra_spread_frames = lrint(params.extra_spread_base * params.mix_rate);
- c.buffer = memnew_arr(float,len);
- c.pos=0;
- for (int j=0;j<len;j++)
- c.buffer[j]=0;
- c.size=len;
+ int len = lrint(comb_tunings[i] * params.mix_rate) + c.extra_spread_frames;
+ if (len < 5)
+ len = 5; //may this happen?
+ c.buffer = memnew_arr(float, len);
+ c.pos = 0;
+ for (int j = 0; j < len; j++)
+ c.buffer[j] = 0;
+ c.size = len;
}
- for (int i=0;i<MAX_ALLPASS;i++) {
+ for (int i = 0; i < MAX_ALLPASS; i++) {
- AllPass &a=allpass[i];
+ AllPass &a = allpass[i];
- a.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate);
+ a.extra_spread_frames = lrint(params.extra_spread_base * params.mix_rate);
- int len=lrint(allpass_tunings[i]*params.mix_rate)+a.extra_spread_frames;
- if (len<5)
- len=5; //may this happen?
+ int len = lrint(allpass_tunings[i] * params.mix_rate) + a.extra_spread_frames;
+ if (len < 5)
+ len = 5; //may this happen?
- a.buffer = memnew_arr(float,len);
- a.pos=0;
- for (int j=0;j<len;j++)
- a.buffer[j]=0;
- a.size=len;
+ a.buffer = memnew_arr(float, len);
+ a.pos = 0;
+ for (int j = 0; j < len; j++)
+ a.buffer[j] = 0;
+ a.size = len;
}
- echo_buffer_size=(int)(((float)MAX_ECHO_MS/1000.0)*params.mix_rate+1.0);
- echo_buffer = memnew_arr(float,echo_buffer_size);
- for (int i=0;i<echo_buffer_size;i++) {
+ echo_buffer_size = (int)(((float)MAX_ECHO_MS / 1000.0) * params.mix_rate + 1.0);
+ echo_buffer = memnew_arr(float, echo_buffer_size);
+ for (int i = 0; i < echo_buffer_size; i++) {
- echo_buffer[i]=0;
+ echo_buffer[i] = 0;
}
- echo_buffer_pos=0;
+ echo_buffer_pos = 0;
}
-
void Reverb::update_parameters() {
//more freeverb derived constants
static const float room_scale = 0.28f;
static const float room_offset = 0.7f;
- for (int i=0;i<MAX_COMBS;i++) {
+ for (int i = 0; i < MAX_COMBS; i++) {
- Comb &c=comb[i];
- c.feedback=room_offset+params.room_size*room_scale;
- if (c.feedback<room_offset)
- c.feedback=room_offset;
- else if (c.feedback>(room_offset+room_scale))
- c.feedback=(room_offset+room_scale);
+ Comb &c = comb[i];
+ c.feedback = room_offset + params.room_size * room_scale;
+ if (c.feedback < room_offset)
+ c.feedback = room_offset;
+ else if (c.feedback > (room_offset + room_scale))
+ c.feedback = (room_offset + room_scale);
- float auxdmp=params.damp/2.0+0.5; //only half the range (0.5 .. 1.0 is enough)
- auxdmp*=auxdmp;
+ float auxdmp = params.damp / 2.0 + 0.5; //only half the range (0.5 .. 1.0 is enough)
+ auxdmp *= auxdmp;
- c.damp=expf(-2.0*Math_PI*auxdmp*10000/params.mix_rate); // 0 .. 10khz
+ c.damp = expf(-2.0 * Math_PI * auxdmp * 10000 / params.mix_rate); // 0 .. 10khz
}
-
}
void Reverb::clear_buffers() {
@@ -329,55 +308,47 @@ void Reverb::clear_buffers() {
if (echo_buffer)
memdelete_arr(echo_buffer);
- for (int i=0;i<MAX_COMBS;i++) {
+ for (int i = 0; i < MAX_COMBS; i++) {
if (comb[i].buffer)
memdelete_arr(comb[i].buffer);
- comb[i].buffer=0;
-
+ comb[i].buffer = 0;
}
- for (int i=0;i<MAX_ALLPASS;i++) {
+ for (int i = 0; i < MAX_ALLPASS; i++) {
if (allpass[i].buffer)
memdelete_arr(allpass[i].buffer);
- allpass[i].buffer=0;
+ allpass[i].buffer = 0;
}
-
}
Reverb::Reverb() {
- params.room_size=0.8;
- params.damp=0.5;
- params.dry=1.0;
- params.wet=0.0;
- params.mix_rate=44100;
- params.extra_spread_base=0;
- params.extra_spread=1.0;
- params.predelay=150;
- params.predelay_fb=0.4;
- params.hpf=0;
- hpf_h1=0;
- hpf_h2=0;
-
-
- input_buffer=memnew_arr(float,INPUT_BUFFER_MAX_SIZE);
- echo_buffer=0;
+ params.room_size = 0.8;
+ params.damp = 0.5;
+ params.dry = 1.0;
+ params.wet = 0.0;
+ params.mix_rate = 44100;
+ params.extra_spread_base = 0;
+ params.extra_spread = 1.0;
+ params.predelay = 150;
+ params.predelay_fb = 0.4;
+ params.hpf = 0;
+ hpf_h1 = 0;
+ hpf_h2 = 0;
+
+ input_buffer = memnew_arr(float, INPUT_BUFFER_MAX_SIZE);
+ echo_buffer = 0;
configure_buffers();
update_parameters();
-
-
}
-
Reverb::~Reverb() {
memdelete_arr(input_buffer);
clear_buffers();
}
-
-
diff --git a/servers/audio/effects/reverb.h b/servers/audio/effects/reverb.h
index f0a0466f8a..33f11e59fe 100644
--- a/servers/audio/effects/reverb.h
+++ b/servers/audio/effects/reverb.h
@@ -32,27 +32,26 @@
#ifndef REVERB_H
#define REVERB_H
-#include "typedefs.h"
-#include "os/memory.h"
#include "audio_frame.h"
+#include "os/memory.h"
+#include "typedefs.h"
class Reverb {
public:
enum {
- INPUT_BUFFER_MAX_SIZE=1024,
+ INPUT_BUFFER_MAX_SIZE = 1024,
};
+
private:
enum {
- MAX_COMBS=8,
- MAX_ALLPASS=4,
- MAX_ECHO_MS=500
+ MAX_COMBS = 8,
+ MAX_ALLPASS = 4,
+ MAX_ECHO_MS = 500
};
-
-
static const float comb_tunings[MAX_COMBS];
static const float allpass_tunings[MAX_ALLPASS];
@@ -66,7 +65,13 @@ private:
int pos;
int extra_spread_frames;
- Comb() { size=0; buffer=0; feedback=0; damp_h=0; pos=0; }
+ Comb() {
+ size = 0;
+ buffer = 0;
+ feedback = 0;
+ damp_h = 0;
+ pos = 0;
+ }
};
struct AllPass {
@@ -75,7 +80,11 @@ private:
float *buffer;
int pos;
int extra_spread_frames;
- AllPass() { size=0; buffer=0; pos=0; }
+ AllPass() {
+ size = 0;
+ buffer = 0;
+ pos = 0;
+ }
};
Comb comb[MAX_COMBS];
@@ -85,8 +94,7 @@ private:
int echo_buffer_size;
int echo_buffer_pos;
- float hpf_h1,hpf_h2;
-
+ float hpf_h1, hpf_h2;
struct Parameters {
@@ -105,8 +113,8 @@ private:
void configure_buffers();
void update_parameters();
void clear_buffers();
-public:
+public:
void set_room_size(float p_size);
void set_damp(float p_damp);
void set_wet(float p_wet);
@@ -118,14 +126,11 @@ public:
void set_extra_spread(float p_spread);
void set_extra_spread_base(float p_sec);
- void process(float *p_src,float *p_dst,int p_frames);
+ void process(float *p_src, float *p_dst, int p_frames);
Reverb();
~Reverb();
-
};
-
-
#endif
diff --git a/servers/audio/reverb_sw.cpp b/servers/audio/reverb_sw.cpp
index 5e02f37679..ea89f7e198 100644
--- a/servers/audio/reverb_sw.cpp
+++ b/servers/audio/reverb_sw.cpp
@@ -27,223 +27,217 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "reverb_sw.h"
-#include "stdlib.h"
#include "print_string.h"
-#define SETMIN( x, y ) (x) = MIN ( (x), (y) )
-#define rangeloop( c, min, max ) \
- for ( (c) = (min) ; (c) < (max) ; (c)++ )
-
-#define ABSDIFF(x, y)\
- ( ((x) < (y)) ? ((y) - (x)) : ((x) - (y)) )
+#include "stdlib.h"
+#define SETMIN(x, y) (x) = MIN((x), (y))
+#define rangeloop(c, min, max) \
+ for ((c) = (min); (c) < (max); (c)++)
+#define ABSDIFF(x, y) \
+ (((x) < (y)) ? ((y) - (x)) : ((x) - (y)))
#ifdef bleh_MSC_VER
#if _MSC_VER >= 1400
- _FORCE_INLINE_ int32_tMULSHIFT_S32 (
+_FORCE_INLINE_ int32_tMULSHIFT_S32(
int32_t Factor1,
int32_t Factor2,
- uint8_t Bits
- ) {
-
- return __ll_rshift (
- __emul ( Factor1, Factor2 ),
- Bits
- );
- }
+ uint8_t Bits) {
+
+ return __ll_rshift(
+ __emul(Factor1, Factor2),
+ Bits);
+}
#endif
#else
-#define MULSHIFT_S32( Factor1, Factor2, Bits )\
- ( (int) (( (int64_t)(Factor1) * (Factor2) ) >> (Bits)) )
+#define MULSHIFT_S32(Factor1, Factor2, Bits) \
+ ((int)(((int64_t)(Factor1) * (Factor2)) >> (Bits)))
#endif
-
-
struct ReverbParamsSW {
- unsigned int BufferSize; // Required buffer size
- int gLPF; // Coefficient
- int gEcho0; // Coefficient
- int gEcho1; // Coefficient
- int gEcho2; // Coefficient
- int gEcho3; // Coefficient
- int gWall; // Coefficient
- int gReva; // Coefficient
- int gRevb; // Coefficient
- int gInputL; // Coefficient
- int gInputR; // Coefficient
- unsigned int nRevaOldL; // Offset
- unsigned int nRevaOldR; // Offset
- unsigned int nRevbOldL; // Offset
- unsigned int nRevbOldR; // Offset
- unsigned int nLwlNew; // Offset
- unsigned int nRwrNew; // Offset
- unsigned int nEcho0L; // Offset
- unsigned int nEcho0R; // Offset
- unsigned int nEcho1L; // Offset
- unsigned int nEcho1R; // Offset
- unsigned int nLwlOld; // Offset
- unsigned int nRwrOld; // Offset
- unsigned int nLwrNew; // Offset
- unsigned int nRwlNew; // Offset
- unsigned int nEcho2L; // Offset
- unsigned int nEcho2R; // Offset
- unsigned int nEcho3L; // Offset
- unsigned int nEcho3R; // Offset
- unsigned int nLwrOld; // Offset
- unsigned int nRwlOld; // Offset
- unsigned int nRevaNewL; // Offset
- unsigned int nRevaNewR; // Offset
- unsigned int nRevbNewL; // Offset
- unsigned int nRevbNewR; // Offset
+ unsigned int BufferSize; // Required buffer size
+ int gLPF; // Coefficient
+ int gEcho0; // Coefficient
+ int gEcho1; // Coefficient
+ int gEcho2; // Coefficient
+ int gEcho3; // Coefficient
+ int gWall; // Coefficient
+ int gReva; // Coefficient
+ int gRevb; // Coefficient
+ int gInputL; // Coefficient
+ int gInputR; // Coefficient
+ unsigned int nRevaOldL; // Offset
+ unsigned int nRevaOldR; // Offset
+ unsigned int nRevbOldL; // Offset
+ unsigned int nRevbOldR; // Offset
+ unsigned int nLwlNew; // Offset
+ unsigned int nRwrNew; // Offset
+ unsigned int nEcho0L; // Offset
+ unsigned int nEcho0R; // Offset
+ unsigned int nEcho1L; // Offset
+ unsigned int nEcho1R; // Offset
+ unsigned int nLwlOld; // Offset
+ unsigned int nRwrOld; // Offset
+ unsigned int nLwrNew; // Offset
+ unsigned int nRwlNew; // Offset
+ unsigned int nEcho2L; // Offset
+ unsigned int nEcho2R; // Offset
+ unsigned int nEcho3L; // Offset
+ unsigned int nEcho3R; // Offset
+ unsigned int nLwrOld; // Offset
+ unsigned int nRwlOld; // Offset
+ unsigned int nRevaNewL; // Offset
+ unsigned int nRevaNewR; // Offset
+ unsigned int nRevbNewL; // Offset
+ unsigned int nRevbNewR; // Offset
};
static ReverbParamsSW reverb_params_Room = {
- 0x26C0/2,
+ 0x26C0 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x6D80, 0x54B8, -0x4130, 0x0000, 0x0000, -0x4580,
+ 0x6D80, 0x54B8, -0x4130, 0x0000, 0x0000, -0x4580,
//gReva gRevb gInputL gInputR
- 0x5800, 0x5300, -0x8000, -0x8000,
+ 0x5800, 0x5300, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x01B4 - 0x007D, 0x0136 - 0x007D, 0x00B8 - 0x005B, 0x005C - 0x005B,
+ 0x01B4 - 0x007D, 0x0136 - 0x007D, 0x00B8 - 0x005B, 0x005C - 0x005B,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x04D6, 0x0333, 0x03F0, 0x0227, 0x0374, 0x01EF,
+ 0x04D6, 0x0333, 0x03F0, 0x0227, 0x0374, 0x01EF,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x0334, 0x01B5, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0334, 0x01B5, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x0000, 0x0000, 0x01B4, 0x0136, 0x00B8, 0x005C
+ 0x0000, 0x0000, 0x01B4, 0x0136, 0x00B8, 0x005C
};
static ReverbParamsSW reverb_params_StudioSmall = {
- 0x1F40/2,
+ 0x1F40 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x70F0, 0x4FA8, -0x4320, 0x4410, -0x3F10, -0x6400,
+ 0x70F0, 0x4FA8, -0x4320, 0x4410, -0x3F10, -0x6400,
//gReva gRevb gInputL gInputR
- 0x5280, 0x4EC0, -0x8000, -0x8000,
+ 0x5280, 0x4EC0, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x00B4 - 0x0033, 0x0080 - 0x0033, 0x004C - 0x0025, 0x0026 - 0x0025,
+ 0x00B4 - 0x0033, 0x0080 - 0x0033, 0x004C - 0x0025, 0x0026 - 0x0025,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x03E4, 0x031B, 0x03A4, 0x02AF, 0x0372, 0x0266,
+ 0x03E4, 0x031B, 0x03A4, 0x02AF, 0x0372, 0x0266,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x031C, 0x025D, 0x025C, 0x018E, 0x022F, 0x0135, 0x01D2, 0x00B7,
+ 0x031C, 0x025D, 0x025C, 0x018E, 0x022F, 0x0135, 0x01D2, 0x00B7,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x018F, 0x00B5, 0x00B4, 0x0080, 0x004C, 0x0026
+ 0x018F, 0x00B5, 0x00B4, 0x0080, 0x004C, 0x0026
};
static ReverbParamsSW reverb_params_StudioMedium = {
- 0x4840/2,
+ 0x4840 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x4B40,
+ 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x4B40,
//gReva gRevb gInputL gInputR
- 0x5280, 0x4EC0, -0x8000, -0x8000,
+ 0x5280, 0x4EC0, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x0264 - 0x00B1, 0x01B2 - 0x00B1, 0x0100 - 0x007F, 0x0080 - 0x007F,
+ 0x0264 - 0x00B1, 0x01B2 - 0x00B1, 0x0100 - 0x007F, 0x0080 - 0x007F,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x0904, 0x076B, 0x0824, 0x065F, 0x07A2, 0x0616,
+ 0x0904, 0x076B, 0x0824, 0x065F, 0x07A2, 0x0616,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x076C, 0x05ED, 0x05EC, 0x042E, 0x050F, 0x0305, 0x0462, 0x02B7,
+ 0x076C, 0x05ED, 0x05EC, 0x042E, 0x050F, 0x0305, 0x0462, 0x02B7,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x042F, 0x0265, 0x0264, 0x01B2, 0x0100, 0x0080
+ 0x042F, 0x0265, 0x0264, 0x01B2, 0x0100, 0x0080
};
static ReverbParamsSW reverb_params_StudioLarge = {
- 0x6FE0/2,
+ 0x6FE0 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x6F60, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x5980,
+ 0x6F60, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x5980,
//gReva gRevb gInputL gInputR
- 0x5680, 0x52C0, -0x8000, -0x8000,
+ 0x5680, 0x52C0, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x031C - 0x00E3, 0x0238 - 0x00E3, 0x0154 - 0x00A9, 0x00AA - 0x00A9,
+ 0x031C - 0x00E3, 0x0238 - 0x00E3, 0x0154 - 0x00A9, 0x00AA - 0x00A9,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x0DFB, 0x0B58, 0x0D09, 0x0A3C, 0x0BD9, 0x0973,
+ 0x0DFB, 0x0B58, 0x0D09, 0x0A3C, 0x0BD9, 0x0973,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x0B59, 0x08DA, 0x08D9, 0x05E9, 0x07EC, 0x04B0, 0x06EF, 0x03D2,
+ 0x0B59, 0x08DA, 0x08D9, 0x05E9, 0x07EC, 0x04B0, 0x06EF, 0x03D2,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x05EA, 0x031D, 0x031C, 0x0238, 0x0154, 0x00AA
+ 0x05EA, 0x031D, 0x031C, 0x0238, 0x0154, 0x00AA
};
static ReverbParamsSW reverb_params_Hall = {
- 0xADE0/2,
+ 0xADE0 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x6000, 0x5000, 0x4C00, -0x4800, -0x4400, -0x4000,
+ 0x6000, 0x5000, 0x4C00, -0x4800, -0x4400, -0x4000,
//gReva gRevb gInputL gInputR
- 0x6000, 0x5C00, -0x8000, -0x8000,
+ 0x6000, 0x5C00, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x05C0 - 0x01A5, 0x041A - 0x01A5, 0x0274 - 0x0139, 0x013A - 0x0139,
+ 0x05C0 - 0x01A5, 0x041A - 0x01A5, 0x0274 - 0x0139, 0x013A - 0x0139,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x15BA, 0x11BB, 0x14C2, 0x10BD, 0x11BC, 0x0DC1,
+ 0x15BA, 0x11BB, 0x14C2, 0x10BD, 0x11BC, 0x0DC1,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x11C0, 0x0DC3, 0x0DC0, 0x09C1, 0x0BC4, 0x07C1, 0x0A00, 0x06CD,
+ 0x11C0, 0x0DC3, 0x0DC0, 0x09C1, 0x0BC4, 0x07C1, 0x0A00, 0x06CD,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x09C2, 0x05C1, 0x05C0, 0x041A, 0x0274, 0x013A
+ 0x09C2, 0x05C1, 0x05C0, 0x041A, 0x0274, 0x013A
};
static ReverbParamsSW reverb_params_SpaceEcho = {
- 0xF6C0/2,
+ 0xF6C0 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x7E00, 0x5000, -0x4C00, -0x5000, 0x4C00, -0x5000,
+ 0x7E00, 0x5000, -0x4C00, -0x5000, 0x4C00, -0x5000,
//gReva gRevb gInputL gInputR
- 0x6000, 0x5400, -0x8000, -0x8000,
+ 0x6000, 0x5400, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x0AE0 - 0x033D, 0x07A2 - 0x033D, 0x0464 - 0x0231, 0x0232 - 0x0231,
+ 0x0AE0 - 0x033D, 0x07A2 - 0x033D, 0x0464 - 0x0231, 0x0232 - 0x0231,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x1ED6, 0x1A31, 0x1D14, 0x183B, 0x1BC2, 0x16B2,
+ 0x1ED6, 0x1A31, 0x1D14, 0x183B, 0x1BC2, 0x16B2,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x1A32, 0x15EF, 0x15EE, 0x1055, 0x1334, 0x0F2D, 0x11F6, 0x0C5D,
+ 0x1A32, 0x15EF, 0x15EE, 0x1055, 0x1334, 0x0F2D, 0x11F6, 0x0C5D,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x1056, 0x0AE1, 0x0AE0, 0x07A2, 0x0464, 0x0232
+ 0x1056, 0x0AE1, 0x0AE0, 0x07A2, 0x0464, 0x0232
};
static ReverbParamsSW reverb_params_Echo = {
- 0x18040/2,
+ 0x18040 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, -0x7F00,
+ 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, -0x7F00,
//gReva gRevb gInputL gInputR
- 0x0000, 0x0000, -0x8000, -0x8000,
+ 0x0000, 0x0000, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001,
+ 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000,
+ 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002
+ 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002
};
static ReverbParamsSW reverb_params_Delay = {
- 0x18040/2,
+ 0x18040 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x7FFF, 0x7FFF, 0x0000, 0x0000, 0x0000, 0x0000,
//gReva gRevb gInputL gInputR
- 0x0000, 0x0000, -0x8000, -0x8000,
+ 0x0000, 0x0000, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001,
+ 0x1004 - 0x0001, 0x1002 - 0x0001, 0x0004 - 0x0001, 0x0002 - 0x0001,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000,
+ 0x1FFF, 0x0FFF, 0x1005, 0x0005, 0x0000, 0x0000,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1005, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002
+ 0x0000, 0x0000, 0x1004, 0x1002, 0x0004, 0x0002
};
static ReverbParamsSW reverb_params_HalfEcho = {
- 0x3C00/2,
+ 0x3C00 / 2,
//gLPF gEcho0 gEcho1 gEcho2 gEcho3 gWall
- 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x7B00,
+ 0x70F0, 0x4FA8, -0x4320, 0x4510, -0x4110, -0x7B00,
//gReva gRevb gInputL gInputR
- 0x5F80, 0x54C0, -0x8000, -0x8000,
+ 0x5F80, 0x54C0, -0x8000, -0x8000,
//nRevaOldL nRevaOldR nRevbOldL nRevbOldR
- 0x0058 - 0x0017, 0x0040 - 0x0017, 0x0028 - 0x0013, 0x0014 - 0x0013,
+ 0x0058 - 0x0017, 0x0040 - 0x0017, 0x0028 - 0x0013, 0x0014 - 0x0013,
//nLwlNew nRwrNew nEcho0L nEcho0R nEcho1L nEcho1R
- 0x0371, 0x02AF, 0x02E5, 0x01DF, 0x02B0, 0x01D7,
+ 0x0371, 0x02AF, 0x02E5, 0x01DF, 0x02B0, 0x01D7,
//nLwlOld nRwrOld nLwrNew nRwlNew nEcho2L nEcho2R nEcho3L nEcho3R
- 0x0358, 0x026A, 0x01D6, 0x011E, 0x012D, 0x00B1, 0x011F, 0x0059,
+ 0x0358, 0x026A, 0x01D6, 0x011E, 0x012D, 0x00B1, 0x011F, 0x0059,
//nLwrOld nRwlOld nRevaNewL nRevaNewR nRevbNewL nRevbNewR
- 0x01A0, 0x00E3, 0x0058, 0x0040, 0x0028, 0x0014
+ 0x01A0, 0x00E3, 0x0058, 0x0040, 0x0028, 0x0014
};
-
-static ReverbParamsSW * reverb_param_modes[] = {
+static ReverbParamsSW *reverb_param_modes[] = {
&reverb_params_Room,
&reverb_params_StudioSmall,
&reverb_params_StudioMedium,
@@ -255,25 +249,24 @@ static ReverbParamsSW * reverb_param_modes[] = {
&reverb_params_HalfEcho,
};
-bool ReverbSW::process(int *p_input,int *p_output,int p_frames,int p_stereo_stride) {
+bool ReverbSW::process(int *p_input, int *p_output, int p_frames, int p_stereo_stride) {
if (!reverb_buffer)
return false;
+//
+// p_input must point to a non-looping buffer.
+// BOTH p_input and p_output must be touched (use ClearModuleBuffer).
- //
- // p_input must point to a non-looping buffer.
- // BOTH p_input and p_output must be touched (use ClearModuleBuffer).
-
- // LOCAL MACROS
+// LOCAL MACROS
#undef LM_SETSRCOFFSET
-#define LM_SETSRCOFFSET(x) \
- (x) = current_params->x + Offset; \
- if ( (x) >= reverb_buffer_size ) { \
- (x) -= reverb_buffer_size; \
- } \
- SETMIN ( aSample, reverb_buffer_size - (x) );
+#define LM_SETSRCOFFSET(x) \
+ (x) = current_params->x + Offset; \
+ if ((x) >= reverb_buffer_size) { \
+ (x) -= reverb_buffer_size; \
+ } \
+ SETMIN(aSample, reverb_buffer_size - (x));
/*
#undef LM_SETSRCOFFSET2
@@ -286,15 +279,15 @@ bool ReverbSW::process(int *p_input,int *p_output,int p_frames,int p_stereo_stri
SETMIN ( aSample, reverb_buffer_size - (x) );
*/
#undef LM_SRCADVANCE
-#define LM_SRCADVANCE(x) \
- (x) += aSample;
+#define LM_SRCADVANCE(x) \
+ (x) += aSample;
#undef LM_MUL
-#define LM_MUL(x,y) \
-MULSHIFT_S32 ( x, current_params->y, 15 )
+#define LM_MUL(x, y) \
+ MULSHIFT_S32(x, current_params->y, 15)
#undef LM_REVERB
-#define LM_REVERB(x) reverb_buffer[ (x) + cSample ]
+#define LM_REVERB(x) reverb_buffer[(x) + cSample]
// LOCAL VARIABLES
@@ -305,16 +298,15 @@ MULSHIFT_S32 ( x, current_params->y, 15 )
// CODE
-
lwl = state.lwl;
lwr = state.lwr;
rwl = state.rwl;
rwr = state.rwr;
Offset = state.Offset;
- int max=0;
+ int max = 0;
- while ( p_frames ) {
+ while (p_frames) {
// Offsets
@@ -354,109 +346,110 @@ MULSHIFT_S32 ( x, current_params->y, 15 )
// Set initial offsets
- LM_SETSRCOFFSET ( nLwlOld );
- LM_SETSRCOFFSET ( nRwrOld );
- LM_SETSRCOFFSET ( nLwlNew );
- LM_SETSRCOFFSET ( nRwrNew );
- LM_SETSRCOFFSET ( nLwrOld );
- LM_SETSRCOFFSET ( nRwlOld );
- LM_SETSRCOFFSET ( nLwrNew );
- LM_SETSRCOFFSET ( nRwlNew );
- LM_SETSRCOFFSET ( nEcho0L );
- LM_SETSRCOFFSET ( nEcho1L );
- LM_SETSRCOFFSET ( nEcho2L );
- LM_SETSRCOFFSET ( nEcho3L );
- LM_SETSRCOFFSET ( nEcho0R );
- LM_SETSRCOFFSET ( nEcho1R );
- LM_SETSRCOFFSET ( nEcho2R );
- LM_SETSRCOFFSET ( nEcho3R );
- LM_SETSRCOFFSET ( nRevaOldL );
- LM_SETSRCOFFSET ( nRevaOldR );
- LM_SETSRCOFFSET ( nRevbOldL );
- LM_SETSRCOFFSET ( nRevbOldR );
- LM_SETSRCOFFSET ( nRevaNewL );
- LM_SETSRCOFFSET ( nRevaNewR );
- LM_SETSRCOFFSET ( nRevbNewL );
- LM_SETSRCOFFSET ( nRevbNewR );
+ LM_SETSRCOFFSET(nLwlOld);
+ LM_SETSRCOFFSET(nRwrOld);
+ LM_SETSRCOFFSET(nLwlNew);
+ LM_SETSRCOFFSET(nRwrNew);
+ LM_SETSRCOFFSET(nLwrOld);
+ LM_SETSRCOFFSET(nRwlOld);
+ LM_SETSRCOFFSET(nLwrNew);
+ LM_SETSRCOFFSET(nRwlNew);
+ LM_SETSRCOFFSET(nEcho0L);
+ LM_SETSRCOFFSET(nEcho1L);
+ LM_SETSRCOFFSET(nEcho2L);
+ LM_SETSRCOFFSET(nEcho3L);
+ LM_SETSRCOFFSET(nEcho0R);
+ LM_SETSRCOFFSET(nEcho1R);
+ LM_SETSRCOFFSET(nEcho2R);
+ LM_SETSRCOFFSET(nEcho3R);
+ LM_SETSRCOFFSET(nRevaOldL);
+ LM_SETSRCOFFSET(nRevaOldR);
+ LM_SETSRCOFFSET(nRevbOldL);
+ LM_SETSRCOFFSET(nRevbOldR);
+ LM_SETSRCOFFSET(nRevaNewL);
+ LM_SETSRCOFFSET(nRevaNewR);
+ LM_SETSRCOFFSET(nRevbNewL);
+ LM_SETSRCOFFSET(nRevbNewR);
//SETMIN ( aSample, p_output.Size - p_output.Offset );
- for (unsigned int cSample=0;cSample<aSample;cSample++) {
+ for (unsigned int cSample = 0; cSample < aSample; cSample++) {
int tempL0, tempL1, tempR0, tempR1;
- tempL1 = p_input[(cSample<<p_stereo_stride)]>>8;
- tempR1 = p_input[(cSample<<p_stereo_stride) + 1]>>8;
+ tempL1 = p_input[(cSample << p_stereo_stride)] >> 8;
+ tempR1 = p_input[(cSample << p_stereo_stride) + 1] >> 8;
- tempL0 = LM_MUL ( tempL1, gInputL );
- tempR0 = LM_MUL ( tempR1, gInputR );
+ tempL0 = LM_MUL(tempL1, gInputL);
+ tempR0 = LM_MUL(tempR1, gInputR);
/*
Left -> Wall -> Left Reflection
*/
- tempL1 = tempL0 + LM_MUL ( LM_REVERB( nLwlOld ), gWall );
- tempR1 = tempR0 + LM_MUL ( LM_REVERB( nRwrOld ), gWall );
- lwl += LM_MUL ( tempL1 - lwl, gLPF );
- rwr += LM_MUL ( tempR1 - rwr, gLPF );
- LM_REVERB( nLwlNew ) = lwl;
- LM_REVERB( nRwrNew ) = rwr;
+ tempL1 = tempL0 + LM_MUL(LM_REVERB(nLwlOld), gWall);
+ tempR1 = tempR0 + LM_MUL(LM_REVERB(nRwrOld), gWall);
+ lwl += LM_MUL(tempL1 - lwl, gLPF);
+ rwr += LM_MUL(tempR1 - rwr, gLPF);
+ LM_REVERB(nLwlNew) = lwl;
+ LM_REVERB(nRwrNew) = rwr;
/*
Left -> Wall -> Right Reflection
*/
- tempL1 = tempL0 + LM_MUL ( LM_REVERB( nRwlOld ), gWall );
- tempR1 = tempR0 + LM_MUL ( LM_REVERB( nLwrOld ), gWall );
- lwr += LM_MUL ( tempL1 - lwr, gLPF );
- rwl += LM_MUL ( tempR1 - rwl, gLPF );
- LM_REVERB( nLwrNew ) = lwr;
- LM_REVERB( nRwlNew ) = rwl;
+ tempL1 = tempL0 + LM_MUL(LM_REVERB(nRwlOld), gWall);
+ tempR1 = tempR0 + LM_MUL(LM_REVERB(nLwrOld), gWall);
+ lwr += LM_MUL(tempL1 - lwr, gLPF);
+ rwl += LM_MUL(tempR1 - rwl, gLPF);
+ LM_REVERB(nLwrNew) = lwr;
+ LM_REVERB(nRwlNew) = rwl;
/*
Early Echo(Early Reflection)
*/
tempL0 =
- LM_MUL ( LM_REVERB( nEcho0L ), gEcho0 ) +
- LM_MUL ( LM_REVERB( nEcho1L ), gEcho1 ) +
- LM_MUL ( LM_REVERB( nEcho2L ), gEcho2 ) +
- LM_MUL ( LM_REVERB( nEcho3L ), gEcho3 );
+ LM_MUL(LM_REVERB(nEcho0L), gEcho0) +
+ LM_MUL(LM_REVERB(nEcho1L), gEcho1) +
+ LM_MUL(LM_REVERB(nEcho2L), gEcho2) +
+ LM_MUL(LM_REVERB(nEcho3L), gEcho3);
tempR0 =
- LM_MUL ( LM_REVERB( nEcho0R ), gEcho0 ) +
- LM_MUL ( LM_REVERB( nEcho1R ), gEcho1 ) +
- LM_MUL ( LM_REVERB( nEcho2R ), gEcho2 ) +
- LM_MUL ( LM_REVERB( nEcho3R ), gEcho3 );
+ LM_MUL(LM_REVERB(nEcho0R), gEcho0) +
+ LM_MUL(LM_REVERB(nEcho1R), gEcho1) +
+ LM_MUL(LM_REVERB(nEcho2R), gEcho2) +
+ LM_MUL(LM_REVERB(nEcho3R), gEcho3);
/*
Late Reverb
*/
- tempL1 = LM_REVERB( nRevaOldL );
- tempR1 = LM_REVERB( nRevaOldR );
- tempL0 -= LM_MUL ( tempL1, gReva );
- tempR0 -= LM_MUL ( tempR1, gReva );
- LM_REVERB( nRevaNewL ) = tempL0;
- LM_REVERB( nRevaNewR ) = tempR0;
- tempL0 = LM_MUL ( tempL0, gReva ) + tempL1;
- tempR0 = LM_MUL ( tempR0, gReva ) + tempR1;
- tempL1 = LM_REVERB( nRevbOldL );
- tempR1 = LM_REVERB( nRevbOldR );
- tempL0 -= LM_MUL ( tempL1, gRevb );
- tempR0 -= LM_MUL ( tempR1, gRevb );
- LM_REVERB( nRevbNewL ) = tempL0;
- LM_REVERB( nRevbNewR ) = tempR0;
- tempL0 = LM_MUL ( tempL0, gRevb ) + tempL1;
- tempR0 = LM_MUL ( tempR0, gRevb ) + tempR1;
+ tempL1 = LM_REVERB(nRevaOldL);
+ tempR1 = LM_REVERB(nRevaOldR);
+ tempL0 -= LM_MUL(tempL1, gReva);
+ tempR0 -= LM_MUL(tempR1, gReva);
+ LM_REVERB(nRevaNewL) = tempL0;
+ LM_REVERB(nRevaNewR) = tempR0;
+ tempL0 = LM_MUL(tempL0, gReva) + tempL1;
+ tempR0 = LM_MUL(tempR0, gReva) + tempR1;
+ tempL1 = LM_REVERB(nRevbOldL);
+ tempR1 = LM_REVERB(nRevbOldR);
+ tempL0 -= LM_MUL(tempL1, gRevb);
+ tempR0 -= LM_MUL(tempR1, gRevb);
+ LM_REVERB(nRevbNewL) = tempL0;
+ LM_REVERB(nRevbNewR) = tempR0;
+ tempL0 = LM_MUL(tempL0, gRevb) + tempL1;
+ tempR0 = LM_MUL(tempR0, gRevb) + tempR1;
/*
Output
*/
- max|=abs(tempL0);
- max|=abs(tempR0);
-
- p_output[(cSample<<p_stereo_stride)] += tempL0<<8;
- p_output[(cSample<<p_stereo_stride) + 1] += tempR0<<8;
+ max |= abs(tempL0);
+ max |= abs(tempR0);
+ p_output[(cSample << p_stereo_stride)] += tempL0 << 8;
+ p_output[(cSample << p_stereo_stride) + 1] += tempR0 << 8;
}
// Advance offsets
Offset += aSample;
- if ( Offset >= reverb_buffer_size ) { Offset -= reverb_buffer_size; }
+ if (Offset >= reverb_buffer_size) {
+ Offset -= reverb_buffer_size;
+ }
p_input += aSample << p_stereo_stride;
p_output += aSample << p_stereo_stride;
@@ -470,100 +463,91 @@ MULSHIFT_S32 ( x, current_params->y, 15 )
state.rwr = rwr;
state.Offset = Offset;
- return (max&0x7FFFFF00)!=0; // audio was mixed?
+ return (max & 0x7FFFFF00) != 0; // audio was mixed?
}
void ReverbSW::adjust_current_params() {
- *current_params=*reverb_param_modes[mode];
-
- uint32_t maxofs=0;
-
-#define LM_CONFIG_PARAM( x )\
- current_params->x=(int)( ( (int64_t)current_params->x*(int64_t)mix_rate*8L)/(int64_t)44100);\
- if (current_params->x>maxofs)\
- maxofs=current_params->x;
-
-
- LM_CONFIG_PARAM ( nLwlOld );
- LM_CONFIG_PARAM ( nRwrOld );
- LM_CONFIG_PARAM ( nLwlNew );
- LM_CONFIG_PARAM ( nRwrNew );
- LM_CONFIG_PARAM ( nLwrOld );
- LM_CONFIG_PARAM ( nRwlOld );
- LM_CONFIG_PARAM ( nLwrNew );
- LM_CONFIG_PARAM ( nRwlNew );
- LM_CONFIG_PARAM ( nEcho0L );
- LM_CONFIG_PARAM ( nEcho1L );
- LM_CONFIG_PARAM ( nEcho2L );
- LM_CONFIG_PARAM ( nEcho3L );
- LM_CONFIG_PARAM ( nEcho0R );
- LM_CONFIG_PARAM ( nEcho1R );
- LM_CONFIG_PARAM ( nEcho2R );
- LM_CONFIG_PARAM ( nEcho3R );
- LM_CONFIG_PARAM ( nRevaOldL );
- LM_CONFIG_PARAM ( nRevaOldR );
- LM_CONFIG_PARAM ( nRevbOldL );
- LM_CONFIG_PARAM ( nRevbOldR );
- LM_CONFIG_PARAM ( nRevaNewL );
- LM_CONFIG_PARAM ( nRevaNewR );
- LM_CONFIG_PARAM ( nRevbNewL );
- LM_CONFIG_PARAM ( nRevbNewR );
-
- int needed_buffer_size=maxofs+1;
+ *current_params = *reverb_param_modes[mode];
+
+ uint32_t maxofs = 0;
+
+#define LM_CONFIG_PARAM(x) \
+ current_params->x = (int)(((int64_t)current_params->x * (int64_t)mix_rate * 8L) / (int64_t)44100); \
+ if (current_params->x > maxofs) \
+ maxofs = current_params->x;
+
+ LM_CONFIG_PARAM(nLwlOld);
+ LM_CONFIG_PARAM(nRwrOld);
+ LM_CONFIG_PARAM(nLwlNew);
+ LM_CONFIG_PARAM(nRwrNew);
+ LM_CONFIG_PARAM(nLwrOld);
+ LM_CONFIG_PARAM(nRwlOld);
+ LM_CONFIG_PARAM(nLwrNew);
+ LM_CONFIG_PARAM(nRwlNew);
+ LM_CONFIG_PARAM(nEcho0L);
+ LM_CONFIG_PARAM(nEcho1L);
+ LM_CONFIG_PARAM(nEcho2L);
+ LM_CONFIG_PARAM(nEcho3L);
+ LM_CONFIG_PARAM(nEcho0R);
+ LM_CONFIG_PARAM(nEcho1R);
+ LM_CONFIG_PARAM(nEcho2R);
+ LM_CONFIG_PARAM(nEcho3R);
+ LM_CONFIG_PARAM(nRevaOldL);
+ LM_CONFIG_PARAM(nRevaOldR);
+ LM_CONFIG_PARAM(nRevbOldL);
+ LM_CONFIG_PARAM(nRevbOldR);
+ LM_CONFIG_PARAM(nRevaNewL);
+ LM_CONFIG_PARAM(nRevaNewR);
+ LM_CONFIG_PARAM(nRevbNewL);
+ LM_CONFIG_PARAM(nRevbNewR);
+
+ int needed_buffer_size = maxofs + 1;
if (reverb_buffer)
memdelete_arr(reverb_buffer);
- reverb_buffer = memnew_arr(int,needed_buffer_size);
- reverb_buffer_size=needed_buffer_size;
+ reverb_buffer = memnew_arr(int, needed_buffer_size);
+ reverb_buffer_size = needed_buffer_size;
- for (uint32_t i=0;i<reverb_buffer_size;i++)
- reverb_buffer[i]=0;
+ for (uint32_t i = 0; i < reverb_buffer_size; i++)
+ reverb_buffer[i] = 0;
state.reset();
-
-
}
void ReverbSW::set_mode(ReverbMode p_mode) {
- if (mode==p_mode)
+ if (mode == p_mode)
return;
- mode=p_mode;
+ mode = p_mode;
adjust_current_params();
}
void ReverbSW::set_mix_rate(int p_mix_rate) {
- if (p_mix_rate==mix_rate)
+ if (p_mix_rate == mix_rate)
return;
- mix_rate=p_mix_rate;
+ mix_rate = p_mix_rate;
adjust_current_params();
-
}
-
ReverbSW::ReverbSW() {
- reverb_buffer=0;
- reverb_buffer_size=0;
- mode=REVERB_MODE_ROOM;
- mix_rate=1;
+ reverb_buffer = 0;
+ reverb_buffer_size = 0;
+ mode = REVERB_MODE_ROOM;
+ mix_rate = 1;
current_params = memnew(ReverbParamsSW);
}
-
ReverbSW::~ReverbSW() {
-
if (reverb_buffer)
memdelete_arr(reverb_buffer);
memdelete(current_params);
-
}
-
diff --git a/servers/audio/reverb_sw.h b/servers/audio/reverb_sw.h
index d9f16a5fbb..06a14322a6 100644
--- a/servers/audio/reverb_sw.h
+++ b/servers/audio/reverb_sw.h
@@ -29,8 +29,8 @@
#ifndef REVERB_SW_H
#define REVERB_SW_H
-#include "typedefs.h"
#include "os/memory.h"
+#include "typedefs.h"
class ReverbParamsSW;
@@ -55,13 +55,18 @@ private:
int rwl;
int rwr;
unsigned int Offset;
- void reset() { lwl=0; lwr=0; rwl=0; rwr=0; Offset=0; }
+ void reset() {
+ lwl = 0;
+ lwr = 0;
+ rwl = 0;
+ rwr = 0;
+ Offset = 0;
+ }
State() { reset(); }
} state;
ReverbParamsSW *current_params;
-
int *reverb_buffer;
unsigned int reverb_buffer_size;
ReverbMode mode;
@@ -70,15 +75,12 @@ private:
void adjust_current_params();
public:
-
-
void set_mode(ReverbMode p_mode);
- bool process(int *p_input,int *p_output,int p_frames,int p_stereo_stride=1); // return tru if audio was created
+ bool process(int *p_input, int *p_output, int p_frames, int p_stereo_stride = 1); // return tru if audio was created
void set_mix_rate(int p_mix_rate);
ReverbSW();
~ReverbSW();
-
};
#endif
diff --git a/servers/audio/voice_rb_sw.h b/servers/audio/voice_rb_sw.h
index cbf1392482..117a62a436 100644
--- a/servers/audio/voice_rb_sw.h
+++ b/servers/audio/voice_rb_sw.h
@@ -29,13 +29,12 @@
#ifndef VOICE_RB_SW_H
#define VOICE_RB_SW_H
-#include "servers/audio_server.h"
#include "os/os.h"
+#include "servers/audio_server.h"
class VoiceRBSW {
public:
-
enum {
- VOICE_RB_SIZE=1024
+ VOICE_RB_SIZE = 1024
};
struct Command {
@@ -72,7 +71,7 @@ public:
struct {
- float pan,depth,height;
+ float pan, depth, height;
} pan;
struct {
@@ -100,47 +99,42 @@ public:
bool positional;
} positional;
-
};
- Command() { type=CMD_NONE; }
-
+ Command() { type = CMD_NONE; }
};
-private:
+private:
Command voice_cmd_rb[VOICE_RB_SIZE];
volatile int read_pos;
volatile int write_pos;
public:
-
- _FORCE_INLINE_ bool commands_left() const { return read_pos!=write_pos; }
+ _FORCE_INLINE_ bool commands_left() const { return read_pos != write_pos; }
_FORCE_INLINE_ Command pop_command() {
- ERR_FAIL_COND_V( read_pos==write_pos, Command() );
- Command cmd=voice_cmd_rb[read_pos];
- read_pos=(read_pos+1)%VOICE_RB_SIZE;
+ ERR_FAIL_COND_V(read_pos == write_pos, Command());
+ Command cmd = voice_cmd_rb[read_pos];
+ read_pos = (read_pos + 1) % VOICE_RB_SIZE;
return cmd;
}
- _FORCE_INLINE_ void push_command(const Command& p_command) {
+ _FORCE_INLINE_ void push_command(const Command &p_command) {
- bool full = ((write_pos+1)%VOICE_RB_SIZE)==read_pos;
+ bool full = ((write_pos + 1) % VOICE_RB_SIZE) == read_pos;
if (full) {
#ifdef DEBUG_ENABLED
if (OS::get_singleton()->is_stdout_verbose()) {
ERR_EXPLAIN("Audio Ring Buffer Full (too many commands");
- ERR_FAIL_COND( ((write_pos+1)%VOICE_RB_SIZE)==read_pos);
+ ERR_FAIL_COND(((write_pos + 1) % VOICE_RB_SIZE) == read_pos);
}
#endif
return;
}
- voice_cmd_rb[write_pos]=p_command;
- write_pos=(write_pos+1)%VOICE_RB_SIZE;
-
+ voice_cmd_rb[write_pos] = p_command;
+ write_pos = (write_pos + 1) % VOICE_RB_SIZE;
}
- VoiceRBSW() { read_pos=write_pos=0; }
-
+ VoiceRBSW() { read_pos = write_pos = 0; }
};
#endif // VOICE_RB_SW_H
diff --git a/servers/audio_server.cpp b/servers/audio_server.cpp
index 192d958a64..5419c5cfe7 100644
--- a/servers/audio_server.cpp
+++ b/servers/audio_server.cpp
@@ -28,10 +28,10 @@
/*************************************************************************/
#include "audio_server.h"
#include "global_config.h"
-#include "os/os.h"
-#include "servers/audio/effects/audio_effect_compressor.h"
#include "io/resource_loader.h"
#include "os/file_access.h"
+#include "os/os.h"
+#include "servers/audio/effects/audio_effect_compressor.h"
#ifdef TOOLS_ENABLED
#define MARK_EDITED set_edited(true);
@@ -42,7 +42,7 @@
#endif
-AudioDriver *AudioDriver::singleton=NULL;
+AudioDriver *AudioDriver::singleton = NULL;
AudioDriver *AudioDriver::get_singleton() {
return singleton;
@@ -50,51 +50,44 @@ AudioDriver *AudioDriver::get_singleton() {
void AudioDriver::set_singleton() {
- singleton=this;
+ singleton = this;
}
-void AudioDriver::audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time) {
-
+void AudioDriver::audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time) {
if (p_update_mix_time)
update_mix_time(p_frames);
if (AudioServer::get_singleton())
- AudioServer::get_singleton()->_driver_process(p_frames,p_buffer);
+ AudioServer::get_singleton()->_driver_process(p_frames, p_buffer);
}
-
-
void AudioDriver::update_mix_time(int p_frames) {
- _mix_amount+=p_frames;
- _last_mix_time=OS::get_singleton()->get_ticks_usec();
+ _mix_amount += p_frames;
+ _last_mix_time = OS::get_singleton()->get_ticks_usec();
}
double AudioDriver::get_mix_time() const {
double total = (OS::get_singleton()->get_ticks_usec() - _last_mix_time) / 1000000.0;
- total+=_mix_amount/(double)get_mix_rate();
+ total += _mix_amount / (double)get_mix_rate();
return total;
-
}
-
AudioDriver::AudioDriver() {
- _last_mix_time=0;
- _mix_amount=0;
+ _last_mix_time = 0;
+ _mix_amount = 0;
}
-
AudioDriver *AudioDriverManager::drivers[MAX_DRIVERS];
-int AudioDriverManager::driver_count=0;
-
+int AudioDriverManager::driver_count = 0;
void AudioDriverManager::add_driver(AudioDriver *p_driver) {
- ERR_FAIL_COND(driver_count>=MAX_DRIVERS);
- drivers[driver_count++]=p_driver;
+ ERR_FAIL_COND(driver_count >= MAX_DRIVERS);
+ drivers[driver_count++] = p_driver;
}
int AudioDriverManager::get_driver_count() {
@@ -103,213 +96,197 @@ int AudioDriverManager::get_driver_count() {
}
AudioDriver *AudioDriverManager::get_driver(int p_driver) {
- ERR_FAIL_INDEX_V(p_driver,driver_count,NULL);
+ ERR_FAIL_INDEX_V(p_driver, driver_count, NULL);
return drivers[p_driver];
}
-
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
-void AudioServer::_driver_process(int p_frames,int32_t* p_buffer) {
+void AudioServer::_driver_process(int p_frames, int32_t *p_buffer) {
- int todo=p_frames;
+ int todo = p_frames;
- while(todo) {
+ while (todo) {
- if (to_mix==0) {
+ if (to_mix == 0) {
_mix_step();
}
- int to_copy = MIN(to_mix,todo);
+ int to_copy = MIN(to_mix, todo);
Bus *master = buses[0];
- int from = buffer_size-to_mix;
- int from_buf=p_frames-todo;
+ int from = buffer_size - to_mix;
+ int from_buf = p_frames - todo;
//master master, send to output
int cs = master->channels.size();
- for(int k=0;k<cs;k++) {
+ for (int k = 0; k < cs; k++) {
if (master->channels[k].active) {
AudioFrame *buf = master->channels[k].buffer.ptr();
- for(int j=0;j<to_copy;j++) {
+ for (int j = 0; j < to_copy; j++) {
- float l = CLAMP(buf[from+j].l,-1.0,1.0);
- int32_t vl = l*((1<<20)-1);
- p_buffer[(from_buf+j)*(cs*2)+k*2+0]=vl<<11;
+ float l = CLAMP(buf[from + j].l, -1.0, 1.0);
+ int32_t vl = l * ((1 << 20) - 1);
+ p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 0] = vl << 11;
- float r = CLAMP(buf[from+j].r,-1.0,1.0);
- int32_t vr = r*((1<<20)-1);
- p_buffer[(from_buf+j)*(cs*2)+k*2+1]=vr<<11;
+ float r = CLAMP(buf[from + j].r, -1.0, 1.0);
+ int32_t vr = r * ((1 << 20) - 1);
+ p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 1] = vr << 11;
}
} else {
- for(int j=0;j<to_copy;j++) {
+ for (int j = 0; j < to_copy; j++) {
- p_buffer[(from_buf+j)*(cs*2)+k*2+0]=0;
- p_buffer[(from_buf+j)*(cs*2)+k*2+1]=0;
+ p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 0] = 0;
+ p_buffer[(from_buf + j) * (cs * 2) + k * 2 + 1] = 0;
}
}
-
}
- todo-=to_copy;
- to_mix-=to_copy;
-
+ todo -= to_copy;
+ to_mix -= to_copy;
}
-
}
void AudioServer::_mix_step() {
- for(int i=0;i<buses.size();i++) {
+ for (int i = 0; i < buses.size(); i++) {
Bus *bus = buses[i];
- bus->index_cache=i; //might be moved around by editor, so..
- for(int k=0;k<bus->channels.size();k++) {
+ bus->index_cache = i; //might be moved around by editor, so..
+ for (int k = 0; k < bus->channels.size(); k++) {
- bus->channels[k].used=false;
+ bus->channels[k].used = false;
}
}
//make callbacks for mixing the audio
- for (Set<CallbackItem>::Element *E=callbacks.front();E;E=E->next()) {
+ for (Set<CallbackItem>::Element *E = callbacks.front(); E; E = E->next()) {
E->get().callback(E->get().userdata);
}
- for(int i=buses.size()-1;i>=0;i--) {
+ for (int i = buses.size() - 1; i >= 0; i--) {
//go bus by bus
Bus *bus = buses[i];
-
- for(int k=0;k<bus->channels.size();k++) {
+ for (int k = 0; k < bus->channels.size(); k++) {
if (bus->channels[k].active && !bus->channels[k].used) {
//buffer was not used, but it's still active, so it must be cleaned
AudioFrame *buf = bus->channels[k].buffer.ptr();
- for(uint32_t j=0;j<buffer_size;j++) {
+ for (uint32_t j = 0; j < buffer_size; j++) {
- buf[j]=AudioFrame(0,0);
+ buf[j] = AudioFrame(0, 0);
}
}
-
}
-
//process effects
- for(int j=0;j<bus->effects.size();j++) {
+ for (int j = 0; j < bus->effects.size(); j++) {
if (!bus->effects[j].enabled)
continue;
- for(int k=0;k<bus->channels.size();k++) {
+ for (int k = 0; k < bus->channels.size(); k++) {
if (!bus->channels[k].active)
continue;
- bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(),temp_buffer[k].ptr(),buffer_size);
+ bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(), temp_buffer[k].ptr(), buffer_size);
}
//swap buffers, so internal buffer always has the right data
- for(int k=0;k<bus->channels.size();k++) {
+ for (int k = 0; k < bus->channels.size(); k++) {
if (!buses[i]->channels[k].active)
continue;
- SWAP(bus->channels[k].buffer,temp_buffer[k]);
+ SWAP(bus->channels[k].buffer, temp_buffer[k]);
}
}
//process send
- Bus *send=NULL;
+ Bus *send = NULL;
- if (i>0) {
+ if (i > 0) {
//everything has a send save for master bus
if (!bus_map.has(bus->send)) {
- send=buses[0];
+ send = buses[0];
} else {
- send=bus_map[bus->send];
- if (send->index_cache>=bus->index_cache) { //invalid, send to master
- send=buses[0];
+ send = bus_map[bus->send];
+ if (send->index_cache >= bus->index_cache) { //invalid, send to master
+ send = buses[0];
}
}
}
-
- for(int k=0;k<bus->channels.size();k++) {
+ for (int k = 0; k < bus->channels.size(); k++) {
if (!bus->channels[k].active)
continue;
AudioFrame *buf = bus->channels[k].buffer.ptr();
-
- AudioFrame peak = AudioFrame(0,0);
- for(uint32_t j=0;j<buffer_size;j++) {
+ AudioFrame peak = AudioFrame(0, 0);
+ for (uint32_t j = 0; j < buffer_size; j++) {
float l = ABS(buf[j].l);
- if (l>peak.l) {
- peak.l=l;
+ if (l > peak.l) {
+ peak.l = l;
}
float r = ABS(buf[j].r);
- if (r>peak.r) {
- peak.r=r;
+ if (r > peak.r) {
+ peak.r = r;
}
}
- bus->channels[k].peak_volume=AudioFrame(Math::linear2db(peak.l+0.0000000001),Math::linear2db(peak.r+0.0000000001));
-
+ bus->channels[k].peak_volume = AudioFrame(Math::linear2db(peak.l + 0.0000000001), Math::linear2db(peak.r + 0.0000000001));
if (!bus->channels[k].used) {
//see if any audio is contained, because channel was not used
-
- if (MAX(peak.r,peak.l) > Math::db2linear(channel_disable_treshold_db)) {
- bus->channels[k].last_mix_with_audio=mix_frames;
- } else if (mix_frames-bus->channels[k].last_mix_with_audio > channel_disable_frames ) {
- bus->channels[k].active=false;
+ if (MAX(peak.r, peak.l) > Math::db2linear(channel_disable_treshold_db)) {
+ bus->channels[k].last_mix_with_audio = mix_frames;
+ } else if (mix_frames - bus->channels[k].last_mix_with_audio > channel_disable_frames) {
+ bus->channels[k].active = false;
continue; //went inactive, dont mix.
}
}
if (send) {
//if not master bus, send
- AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache,k);
+ AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache, k);
- for(uint32_t j=0;j<buffer_size;j++) {
- target_buf[j]+=buf[j];
+ for (uint32_t j = 0; j < buffer_size; j++) {
+ target_buf[j] += buf[j];
}
}
-
}
-
}
-
- mix_frames+=buffer_size;
- to_mix=buffer_size;
-
+ mix_frames += buffer_size;
+ to_mix = buffer_size;
}
-AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus,int p_buffer) {
+AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus, int p_buffer) {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),NULL);
- ERR_FAIL_INDEX_V(p_buffer,buses[p_bus]->channels.size(),NULL);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), NULL);
+ ERR_FAIL_INDEX_V(p_buffer, buses[p_bus]->channels.size(), NULL);
AudioFrame *data = buses[p_bus]->channels[p_buffer].buffer.ptr();
-
if (!buses[p_bus]->channels[p_buffer].used) {
- buses[p_bus]->channels[p_buffer].used=true;
- buses[p_bus]->channels[p_buffer].active=true;
- buses[p_bus]->channels[p_buffer].last_mix_with_audio=mix_frames;
- for(uint32_t i=0;i<buffer_size;i++) {
- data[i]=AudioFrame(0,0);
+ buses[p_bus]->channels[p_buffer].used = true;
+ buses[p_bus]->channels[p_buffer].active = true;
+ buses[p_bus]->channels[p_buffer].last_mix_with_audio = mix_frames;
+ for (uint32_t i = 0; i < buffer_size; i++) {
+ data[i] = AudioFrame(0, 0);
}
}
@@ -321,28 +298,27 @@ int AudioServer::thread_get_mix_buffer_size() const {
return buffer_size;
}
-int AudioServer::thread_find_bus_index(const StringName& p_name) {
+int AudioServer::thread_find_bus_index(const StringName &p_name) {
if (bus_map.has(p_name)) {
return bus_map[p_name]->index_cache;
} else {
return 0;
}
-
}
void AudioServer::set_bus_count(int p_count) {
- ERR_FAIL_COND(p_count<1);
- ERR_FAIL_INDEX(p_count,256);
+ ERR_FAIL_COND(p_count < 1);
+ ERR_FAIL_INDEX(p_count, 256);
MARK_EDITED
lock();
int cb = buses.size();
- if (p_count<buses.size()) {
- for(int i=p_count;i<buses.size();i++) {
+ if (p_count < buses.size()) {
+ for (int i = p_count; i < buses.size(); i++) {
bus_map.erase(buses[i]->name);
memdelete(buses[i]);
}
@@ -350,47 +326,44 @@ void AudioServer::set_bus_count(int p_count) {
buses.resize(p_count);
- for(int i=cb;i<buses.size();i++) {
+ for (int i = cb; i < buses.size(); i++) {
- String attempt="New Bus";
- int attempts=1;
- while(true) {
+ String attempt = "New Bus";
+ int attempts = 1;
+ while (true) {
- bool name_free=true;
- for(int j=0;j<i;j++) {
+ bool name_free = true;
+ for (int j = 0; j < i; j++) {
- if (buses[j]->name==attempt) {
- name_free=false;
+ if (buses[j]->name == attempt) {
+ name_free = false;
break;
}
}
if (!name_free) {
attempts++;
- attempt="New Bus " +itos(attempts);
+ attempt = "New Bus " + itos(attempts);
} else {
break;
}
-
}
-
- buses[i]=memnew(Bus);
+ buses[i] = memnew(Bus);
buses[i]->channels.resize(_get_channel_count());
- for(int j=0;j<_get_channel_count();j++) {
+ for (int j = 0; j < _get_channel_count(); j++) {
buses[i]->channels[j].buffer.resize(buffer_size);
}
- buses[i]->name=attempt;
- buses[i]->solo=false;
- buses[i]->mute=false;
- buses[i]->bypass=false;
- buses[i]->volume_db=0;
- if (i>0) {
- buses[i]->send="Master";
+ buses[i]->name = attempt;
+ buses[i]->solo = false;
+ buses[i]->mute = false;
+ buses[i]->bypass = false;
+ buses[i]->volume_db = 0;
+ if (i > 0) {
+ buses[i]->send = "Master";
}
- bus_map[attempt]=buses[i];
-
+ bus_map[attempt] = buses[i];
}
unlock();
@@ -398,11 +371,10 @@ void AudioServer::set_bus_count(int p_count) {
emit_signal("bus_layout_changed");
}
-
void AudioServer::remove_bus(int p_index) {
- ERR_FAIL_INDEX(p_index,buses.size());
- ERR_FAIL_COND(p_index==0);
+ ERR_FAIL_INDEX(p_index, buses.size());
+ ERR_FAIL_COND(p_index == 0);
MARK_EDITED
@@ -417,76 +389,74 @@ void AudioServer::add_bus(int p_at_pos) {
MARK_EDITED
- if (p_at_pos>=buses.size()) {
- p_at_pos=-1;
- } else if (p_at_pos==0) {
- if (buses.size()>1)
- p_at_pos=1;
+ if (p_at_pos >= buses.size()) {
+ p_at_pos = -1;
+ } else if (p_at_pos == 0) {
+ if (buses.size() > 1)
+ p_at_pos = 1;
else
- p_at_pos=-1;
+ p_at_pos = -1;
}
- String attempt="New Bus";
- int attempts=1;
- while(true) {
+ String attempt = "New Bus";
+ int attempts = 1;
+ while (true) {
- bool name_free=true;
- for(int j=0;j<buses.size();j++) {
+ bool name_free = true;
+ for (int j = 0; j < buses.size(); j++) {
- if (buses[j]->name==attempt) {
- name_free=false;
+ if (buses[j]->name == attempt) {
+ name_free = false;
break;
}
}
if (!name_free) {
attempts++;
- attempt="New Bus " +itos(attempts);
+ attempt = "New Bus " + itos(attempts);
} else {
break;
}
-
}
- Bus* bus =memnew(Bus);
+ Bus *bus = memnew(Bus);
bus->channels.resize(_get_channel_count());
- for(int j=0;j<_get_channel_count();j++) {
+ for (int j = 0; j < _get_channel_count(); j++) {
bus->channels[j].buffer.resize(buffer_size);
}
- bus->name=attempt;
- bus->solo=false;
- bus->mute=false;
- bus->bypass=false;
- bus->volume_db=0;
+ bus->name = attempt;
+ bus->solo = false;
+ bus->mute = false;
+ bus->bypass = false;
+ bus->volume_db = 0;
- bus_map[attempt]=bus;
+ bus_map[attempt] = bus;
- if (p_at_pos==-1)
+ if (p_at_pos == -1)
buses.push_back(bus);
else
- buses.insert(p_at_pos,bus);
-
+ buses.insert(p_at_pos, bus);
}
-void AudioServer::move_bus(int p_bus,int p_to_pos) {
+void AudioServer::move_bus(int p_bus, int p_to_pos) {
- ERR_FAIL_COND(p_bus<1 || p_bus>=buses.size());
- ERR_FAIL_COND(p_to_pos!=-1 && (p_to_pos<1 || p_to_pos>buses.size()));
+ ERR_FAIL_COND(p_bus < 1 || p_bus >= buses.size());
+ ERR_FAIL_COND(p_to_pos != -1 && (p_to_pos < 1 || p_to_pos > buses.size()));
MARK_EDITED
- if (p_bus==p_to_pos)
+ if (p_bus == p_to_pos)
return;
Bus *bus = buses[p_bus];
buses.remove(p_bus);
- if (p_to_pos==-1) {
+ if (p_to_pos == -1) {
buses.push_back(bus);
- } else if (p_to_pos<p_bus) {
- buses.insert(p_to_pos,bus);
+ } else if (p_to_pos < p_bus) {
+ buses.insert(p_to_pos, bus);
} else {
- buses.insert(p_to_pos-1,bus);
+ buses.insert(p_to_pos - 1, bus);
}
}
@@ -495,32 +465,31 @@ int AudioServer::get_bus_count() const {
return buses.size();
}
+void AudioServer::set_bus_name(int p_bus, const String &p_name) {
-void AudioServer::set_bus_name(int p_bus,const String& p_name) {
-
- ERR_FAIL_INDEX(p_bus,buses.size());
- if (p_bus==0 && p_name!="Master")
+ ERR_FAIL_INDEX(p_bus, buses.size());
+ if (p_bus == 0 && p_name != "Master")
return; //bus 0 is always master
MARK_EDITED
lock();
- if (buses[p_bus]->name==p_name) {
+ if (buses[p_bus]->name == p_name) {
unlock();
return;
}
- String attempt=p_name;
- int attempts=1;
+ String attempt = p_name;
+ int attempts = 1;
- while(true) {
+ while (true) {
- bool name_free=true;
- for(int i=0;i<buses.size();i++) {
+ bool name_free = true;
+ for (int i = 0; i < buses.size(); i++) {
- if (buses[i]->name==attempt) {
- name_free=false;
+ if (buses[i]->name == attempt) {
+ name_free = false;
break;
}
}
@@ -530,142 +499,128 @@ void AudioServer::set_bus_name(int p_bus,const String& p_name) {
}
attempts++;
- attempt=p_name+" "+itos(attempts);
+ attempt = p_name + " " + itos(attempts);
}
bus_map.erase(buses[p_bus]->name);
- buses[p_bus]->name=attempt;
- bus_map[attempt]=buses[p_bus];
+ buses[p_bus]->name = attempt;
+ bus_map[attempt] = buses[p_bus];
unlock();
emit_signal("bus_layout_changed");
-
}
String AudioServer::get_bus_name(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),String());
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), String());
return buses[p_bus]->name;
}
-void AudioServer::set_bus_volume_db(int p_bus,float p_volume_db) {
+void AudioServer::set_bus_volume_db(int p_bus, float p_volume_db) {
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
- buses[p_bus]->volume_db=p_volume_db;
-
+ buses[p_bus]->volume_db = p_volume_db;
}
float AudioServer::get_bus_volume_db(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),0);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
return buses[p_bus]->volume_db;
-
}
-void AudioServer::set_bus_send(int p_bus,const StringName& p_send) {
+void AudioServer::set_bus_send(int p_bus, const StringName &p_send) {
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
- buses[p_bus]->send=p_send;
-
+ buses[p_bus]->send = p_send;
}
StringName AudioServer::get_bus_send(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),StringName());
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), StringName());
return buses[p_bus]->send;
-
}
+void AudioServer::set_bus_solo(int p_bus, bool p_enable) {
-void AudioServer::set_bus_solo(int p_bus,bool p_enable) {
-
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
- buses[p_bus]->solo=p_enable;
-
+ buses[p_bus]->solo = p_enable;
}
-bool AudioServer::is_bus_solo(int p_bus) const{
+bool AudioServer::is_bus_solo(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),false);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
return buses[p_bus]->solo;
-
}
-void AudioServer::set_bus_mute(int p_bus,bool p_enable){
+void AudioServer::set_bus_mute(int p_bus, bool p_enable) {
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
- buses[p_bus]->mute=p_enable;
+ buses[p_bus]->mute = p_enable;
}
-bool AudioServer::is_bus_mute(int p_bus) const{
+bool AudioServer::is_bus_mute(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),false);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
return buses[p_bus]->mute;
-
}
-void AudioServer::set_bus_bypass_effects(int p_bus,bool p_enable){
+void AudioServer::set_bus_bypass_effects(int p_bus, bool p_enable) {
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
- buses[p_bus]->bypass=p_enable;
+ buses[p_bus]->bypass = p_enable;
}
-bool AudioServer::is_bus_bypassing_effects(int p_bus) const{
+bool AudioServer::is_bus_bypassing_effects(int p_bus) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),false);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
return buses[p_bus]->bypass;
-
}
-
void AudioServer::_update_bus_effects(int p_bus) {
- for(int i=0;i<buses[p_bus]->channels.size();i++) {
+ for (int i = 0; i < buses[p_bus]->channels.size(); i++) {
buses[p_bus]->channels[i].effect_instances.resize(buses[p_bus]->effects.size());
- for(int j=0;j<buses[p_bus]->effects.size();j++) {
+ for (int j = 0; j < buses[p_bus]->effects.size(); j++) {
Ref<AudioEffectInstance> fx = buses[p_bus]->effects[j].effect->instance();
if (fx->cast_to<AudioEffectCompressorInstance>()) {
fx->cast_to<AudioEffectCompressorInstance>()->set_current_channel(i);
}
- buses[p_bus]->channels[i].effect_instances[j]=fx;
-
+ buses[p_bus]->channels[i].effect_instances[j] = fx;
}
}
}
-
-void AudioServer::add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int p_at_pos) {
+void AudioServer::add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos) {
ERR_FAIL_COND(p_effect.is_null());
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
-
lock();
Bus::Effect fx;
- fx.effect=p_effect;
+ fx.effect = p_effect;
//fx.instance=p_effect->instance();
- fx.enabled=true;
+ fx.enabled = true;
- if (p_at_pos>=buses[p_bus]->effects.size() || p_at_pos<0) {
+ if (p_at_pos >= buses[p_bus]->effects.size() || p_at_pos < 0) {
buses[p_bus]->effects.push_back(fx);
} else {
- buses[p_bus]->effects.insert(p_at_pos,fx);
+ buses[p_bus]->effects.insert(p_at_pos, fx);
}
_update_bus_effects(p_bus);
@@ -673,14 +628,12 @@ void AudioServer::add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int
unlock();
}
+void AudioServer::remove_bus_effect(int p_bus, int p_effect) {
-void AudioServer::remove_bus_effect(int p_bus,int p_effect) {
-
- ERR_FAIL_INDEX(p_bus,buses.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
MARK_EDITED
-
lock();
buses[p_bus]->effects.remove(p_effect);
@@ -691,88 +644,78 @@ void AudioServer::remove_bus_effect(int p_bus,int p_effect) {
int AudioServer::get_bus_effect_count(int p_bus) {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),0);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
return buses[p_bus]->effects.size();
-
}
-Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus,int p_effect) {
+Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus, int p_effect) {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),Ref<AudioEffect>());
- ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),Ref<AudioEffect>());
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), Ref<AudioEffect>());
+ ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), Ref<AudioEffect>());
return buses[p_bus]->effects[p_effect].effect;
-
}
-void AudioServer::swap_bus_effects(int p_bus,int p_effect,int p_by_effect) {
+void AudioServer::swap_bus_effects(int p_bus, int p_effect, int p_by_effect) {
- ERR_FAIL_INDEX(p_bus,buses.size());
- ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size());
- ERR_FAIL_INDEX(p_by_effect,buses[p_bus]->effects.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
+ ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size());
+ ERR_FAIL_INDEX(p_by_effect, buses[p_bus]->effects.size());
MARK_EDITED
-
lock();
- SWAP( buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect] );
+ SWAP(buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect]);
_update_bus_effects(p_bus);
unlock();
}
-void AudioServer::set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled) {
+void AudioServer::set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled) {
- ERR_FAIL_INDEX(p_bus,buses.size());
- ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size());
+ ERR_FAIL_INDEX(p_bus, buses.size());
+ ERR_FAIL_INDEX(p_effect, buses[p_bus]->effects.size());
MARK_EDITED
-
- buses[p_bus]->effects[p_effect].enabled=p_enabled;
-
+ buses[p_bus]->effects[p_effect].enabled = p_enabled;
}
-bool AudioServer::is_bus_effect_enabled(int p_bus,int p_effect) const {
+bool AudioServer::is_bus_effect_enabled(int p_bus, int p_effect) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),false);
- ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),false);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
+ ERR_FAIL_INDEX_V(p_effect, buses[p_bus]->effects.size(), false);
return buses[p_bus]->effects[p_effect].enabled;
-
}
+float AudioServer::get_bus_peak_volume_left_db(int p_bus, int p_channel) const {
-float AudioServer::get_bus_peak_volume_left_db(int p_bus,int p_channel) const {
-
- ERR_FAIL_INDEX_V(p_bus,buses.size(),0);
- ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
+ ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0);
return buses[p_bus]->channels[p_channel].peak_volume.l;
-
}
-float AudioServer::get_bus_peak_volume_right_db(int p_bus,int p_channel) const {
+float AudioServer::get_bus_peak_volume_right_db(int p_bus, int p_channel) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),0);
- ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), 0);
+ ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), 0);
return buses[p_bus]->channels[p_channel].peak_volume.r;
-
}
-bool AudioServer::is_bus_channel_active(int p_bus,int p_channel) const {
+bool AudioServer::is_bus_channel_active(int p_bus, int p_channel) const {
- ERR_FAIL_INDEX_V(p_bus,buses.size(),false);
- ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),false);
+ ERR_FAIL_INDEX_V(p_bus, buses.size(), false);
+ ERR_FAIL_INDEX_V(p_channel, buses[p_bus]->channels.size(), false);
return buses[p_bus]->channels[p_channel].active;
-
}
void AudioServer::init() {
- channel_disable_treshold_db=GLOBAL_DEF("audio/channel_disable_treshold_db",-60.0);
- channel_disable_frames=float(GLOBAL_DEF("audio/channel_disable_time",2.0))*get_mix_rate();
- buffer_size=1024; //harcoded for now
- switch( get_speaker_mode() ) {
+ channel_disable_treshold_db = GLOBAL_DEF("audio/channel_disable_treshold_db", -60.0);
+ channel_disable_frames = float(GLOBAL_DEF("audio/channel_disable_time", 2.0)) * get_mix_rate();
+ buffer_size = 1024; //harcoded for now
+ switch (get_speaker_mode()) {
case SPEAKER_MODE_STEREO: {
temp_buffer.resize(1);
} break;
@@ -784,21 +727,20 @@ void AudioServer::init() {
} break;
}
- for(int i=0;i<temp_buffer.size();i++) {
+ for (int i = 0; i < temp_buffer.size(); i++) {
temp_buffer[i].resize(buffer_size);
}
- mix_count=0;
- set_bus_count(1);;
- set_bus_name(0,"Master");
-
+ mix_count = 0;
+ set_bus_count(1);
+ ;
+ set_bus_name(0, "Master");
if (AudioDriver::get_singleton())
AudioDriver::get_singleton()->start();
#ifdef TOOLS_ENABLED
set_edited(false); //avoid editors from thinking this was edited
#endif
-
}
void AudioServer::load_default_bus_layout() {
@@ -809,20 +751,17 @@ void AudioServer::load_default_bus_layout() {
set_bus_layout(default_layout);
}
}
-
}
void AudioServer::finish() {
- for(int i=0;i<buses.size();i++) {
+ for (int i = 0; i < buses.size(); i++) {
memdelete(buses[i]);
}
buses.clear();
}
void AudioServer::update() {
-
-
}
/* MISC config */
@@ -834,11 +773,9 @@ void AudioServer::lock() {
void AudioServer::unlock() {
AudioDriver::get_singleton()->unlock();
-
}
-
-AudioServer::SpeakerMode AudioServer::get_speaker_mode() const {
+AudioServer::SpeakerMode AudioServer::get_speaker_mode() const {
return (AudioServer::SpeakerMode)AudioDriver::get_singleton()->get_speaker_mode();
}
@@ -866,29 +803,26 @@ double AudioServer::get_output_delay() const {
return 0;
}
-AudioServer* AudioServer::singleton=NULL;
-
-
-
+AudioServer *AudioServer::singleton = NULL;
-void* AudioServer::audio_data_alloc(uint32_t p_data_len,const uint8_t *p_from_data) {
+void *AudioServer::audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data) {
- void * ad = memalloc( p_data_len );
- ERR_FAIL_COND_V(!ad,NULL);
+ void *ad = memalloc(p_data_len);
+ ERR_FAIL_COND_V(!ad, NULL);
if (p_from_data) {
- copymem(ad,p_from_data,p_data_len);
+ copymem(ad, p_from_data, p_data_len);
}
audio_data_lock->lock();
- audio_data[ad]=p_data_len;
- audio_data_total_mem+=p_data_len;
- audio_data_max_mem=MAX(audio_data_total_mem,audio_data_max_mem);
+ audio_data[ad] = p_data_len;
+ audio_data_total_mem += p_data_len;
+ audio_data_max_mem = MAX(audio_data_total_mem, audio_data_max_mem);
audio_data_lock->unlock();
return ad;
}
-void AudioServer::audio_data_free(void* p_data) {
+void AudioServer::audio_data_free(void *p_data) {
audio_data_lock->lock();
if (!audio_data.has(p_data)) {
@@ -896,86 +830,82 @@ void AudioServer::audio_data_free(void* p_data) {
ERR_FAIL();
}
- audio_data_total_mem-=audio_data[p_data];
+ audio_data_total_mem -= audio_data[p_data];
audio_data.erase(p_data);
memfree(p_data);
audio_data_lock->unlock();
-
-
}
-size_t AudioServer::audio_data_get_total_memory_usage() const{
+size_t AudioServer::audio_data_get_total_memory_usage() const {
return audio_data_total_mem;
}
-size_t AudioServer::audio_data_get_max_memory_usage() const{
+size_t AudioServer::audio_data_get_max_memory_usage() const {
return audio_data_max_mem;
-
}
-void AudioServer::add_callback(AudioCallback p_callback,void *p_userdata) {
+void AudioServer::add_callback(AudioCallback p_callback, void *p_userdata) {
lock();
CallbackItem ci;
- ci.callback=p_callback;
- ci.userdata=p_userdata;
+ ci.callback = p_callback;
+ ci.userdata = p_userdata;
callbacks.insert(ci);
unlock();
}
-void AudioServer::remove_callback(AudioCallback p_callback,void *p_userdata) {
+void AudioServer::remove_callback(AudioCallback p_callback, void *p_userdata) {
lock();
CallbackItem ci;
- ci.callback=p_callback;
- ci.userdata=p_userdata;
+ ci.callback = p_callback;
+ ci.userdata = p_userdata;
callbacks.erase(ci);
unlock();
-
}
void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_state) {
- ERR_FAIL_COND(p_state.is_null() || p_state->buses.size()==0);
+ ERR_FAIL_COND(p_state.is_null() || p_state->buses.size() == 0);
lock();
- for(int i=0;i<buses.size();i++) {
+ for (int i = 0; i < buses.size(); i++) {
memdelete(buses[i]);
}
buses.resize(p_state->buses.size());
bus_map.clear();
- for(int i=0;i<p_state->buses.size();i++) {
- Bus * bus = memnew(Bus);
- if (i==0) {
- bus->name="Master";
+ for (int i = 0; i < p_state->buses.size(); i++) {
+ Bus *bus = memnew(Bus);
+ if (i == 0) {
+ bus->name = "Master";
} else {
- bus->name=p_state->buses[i].name;
- bus->send=p_state->buses[i].send;
+ bus->name = p_state->buses[i].name;
+ bus->send = p_state->buses[i].send;
}
- bus->solo=p_state->buses[i].solo;
- bus->mute=p_state->buses[i].mute;
- bus->bypass=p_state->buses[i].bypass;
- bus->volume_db=p_state->buses[i].volume_db;
+ bus->solo = p_state->buses[i].solo;
+ bus->mute = p_state->buses[i].mute;
+ bus->bypass = p_state->buses[i].bypass;
+ bus->volume_db = p_state->buses[i].volume_db;
- for(int j=0;j<p_state->buses[i].effects.size();j++) {
+ for (int j = 0; j < p_state->buses[i].effects.size(); j++) {
Ref<AudioEffect> fx = p_state->buses[i].effects[j].effect;
if (fx.is_valid()) {
Bus::Effect bfx;
- bfx.effect=fx;
- bfx.enabled=p_state->buses[i].effects[j].enabled;
+ bfx.effect = fx;
+ bfx.enabled = p_state->buses[i].effects[j].enabled;
bus->effects.push_back(bfx);
}
}
- bus_map[bus->name]=bus;
- buses[i]=bus;
+ bus_map[bus->name] = bus;
+ buses[i] = bus;
buses[i]->channels.resize(_get_channel_count());
- for(int j=0;j<_get_channel_count();j++) {
+ for (int j = 0; j < _get_channel_count(); j++) {
buses[i]->channels[j].buffer.resize(buffer_size);
}
_update_bus_effects(i);
@@ -984,100 +914,94 @@ void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_state) {
set_edited(false);
#endif
unlock();
-
}
-
Ref<AudioBusLayout> AudioServer::generate_bus_layout() const {
Ref<AudioBusLayout> state;
state.instance();
- state->buses.resize( buses.size() );
+ state->buses.resize(buses.size());
- for(int i=0;i<buses.size();i++) {
+ for (int i = 0; i < buses.size(); i++) {
- state->buses[i].name=buses[i]->name;
- state->buses[i].send=buses[i]->send;
- state->buses[i].mute=buses[i]->mute;
- state->buses[i].solo=buses[i]->solo;
- state->buses[i].bypass=buses[i]->bypass;
- state->buses[i].volume_db=buses[i]->volume_db;
- for(int j=0;j<buses[i]->effects.size();j++) {
+ state->buses[i].name = buses[i]->name;
+ state->buses[i].send = buses[i]->send;
+ state->buses[i].mute = buses[i]->mute;
+ state->buses[i].solo = buses[i]->solo;
+ state->buses[i].bypass = buses[i]->bypass;
+ state->buses[i].volume_db = buses[i]->volume_db;
+ for (int j = 0; j < buses[i]->effects.size(); j++) {
AudioBusLayout::Bus::Effect fx;
- fx.effect=buses[i]->effects[j].effect;
- fx.enabled=buses[i]->effects[j].enabled;
+ fx.effect = buses[i]->effects[j].effect;
+ fx.enabled = buses[i]->effects[j].enabled;
state->buses[i].effects.push_back(fx);
-
}
}
return state;
}
-
void AudioServer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("set_bus_count", "amount"), &AudioServer::set_bus_count);
+ ClassDB::bind_method(D_METHOD("get_bus_count"), &AudioServer::get_bus_count);
- ClassDB::bind_method(D_METHOD("set_bus_count","amount"),&AudioServer::set_bus_count);
- ClassDB::bind_method(D_METHOD("get_bus_count"),&AudioServer::get_bus_count);
+ ClassDB::bind_method(D_METHOD("remove_bus", "index"), &AudioServer::remove_bus);
+ ClassDB::bind_method(D_METHOD("add_bus", "at_pos"), &AudioServer::add_bus, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("move_bus", "index", "to_index"), &AudioServer::move_bus);
- ClassDB::bind_method(D_METHOD("remove_bus","index"),&AudioServer::remove_bus);
- ClassDB::bind_method(D_METHOD("add_bus","at_pos"),&AudioServer::add_bus,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("move_bus","index","to_index"),&AudioServer::move_bus);
+ ClassDB::bind_method(D_METHOD("set_bus_name", "bus_idx", "name"), &AudioServer::set_bus_name);
+ ClassDB::bind_method(D_METHOD("get_bus_name", "bus_idx"), &AudioServer::get_bus_name);
- ClassDB::bind_method(D_METHOD("set_bus_name","bus_idx","name"),&AudioServer::set_bus_name);
- ClassDB::bind_method(D_METHOD("get_bus_name","bus_idx"),&AudioServer::get_bus_name);
+ ClassDB::bind_method(D_METHOD("set_bus_volume_db", "bus_idx", "volume_db"), &AudioServer::set_bus_volume_db);
+ ClassDB::bind_method(D_METHOD("get_bus_volume_db", "bus_idx"), &AudioServer::get_bus_volume_db);
- ClassDB::bind_method(D_METHOD("set_bus_volume_db","bus_idx","volume_db"),&AudioServer::set_bus_volume_db);
- ClassDB::bind_method(D_METHOD("get_bus_volume_db","bus_idx"),&AudioServer::get_bus_volume_db);
+ ClassDB::bind_method(D_METHOD("set_bus_send", "bus_idx", "send"), &AudioServer::set_bus_send);
+ ClassDB::bind_method(D_METHOD("get_bus_send", "bus_idx"), &AudioServer::get_bus_send);
- ClassDB::bind_method(D_METHOD("set_bus_send","bus_idx","send"),&AudioServer::set_bus_send);
- ClassDB::bind_method(D_METHOD("get_bus_send","bus_idx"),&AudioServer::get_bus_send);
+ ClassDB::bind_method(D_METHOD("set_bus_solo", "bus_idx", "enable"), &AudioServer::set_bus_solo);
+ ClassDB::bind_method(D_METHOD("is_bus_solo", "bus_idx"), &AudioServer::is_bus_solo);
- ClassDB::bind_method(D_METHOD("set_bus_solo","bus_idx","enable"),&AudioServer::set_bus_solo);
- ClassDB::bind_method(D_METHOD("is_bus_solo","bus_idx"),&AudioServer::is_bus_solo);
+ ClassDB::bind_method(D_METHOD("set_bus_mute", "bus_idx", "enable"), &AudioServer::set_bus_mute);
+ ClassDB::bind_method(D_METHOD("is_bus_mute", "bus_idx"), &AudioServer::is_bus_mute);
- ClassDB::bind_method(D_METHOD("set_bus_mute","bus_idx","enable"),&AudioServer::set_bus_mute);
- ClassDB::bind_method(D_METHOD("is_bus_mute","bus_idx"),&AudioServer::is_bus_mute);
+ ClassDB::bind_method(D_METHOD("set_bus_bypass_effects", "bus_idx", "enable"), &AudioServer::set_bus_bypass_effects);
+ ClassDB::bind_method(D_METHOD("is_bus_bypassing_effects", "bus_idx"), &AudioServer::is_bus_bypassing_effects);
- ClassDB::bind_method(D_METHOD("set_bus_bypass_effects","bus_idx","enable"),&AudioServer::set_bus_bypass_effects);
- ClassDB::bind_method(D_METHOD("is_bus_bypassing_effects","bus_idx"),&AudioServer::is_bus_bypassing_effects);
+ ClassDB::bind_method(D_METHOD("add_bus_effect", "bus_idx", "effect:AudioEffect"), &AudioServer::add_bus_effect, DEFVAL(-1));
+ ClassDB::bind_method(D_METHOD("remove_bus_effect", "bus_idx", "effect_idx"), &AudioServer::remove_bus_effect);
- ClassDB::bind_method(D_METHOD("add_bus_effect","bus_idx","effect:AudioEffect"),&AudioServer::add_bus_effect,DEFVAL(-1));
- ClassDB::bind_method(D_METHOD("remove_bus_effect","bus_idx","effect_idx"),&AudioServer::remove_bus_effect);
+ ClassDB::bind_method(D_METHOD("get_bus_effect_count", "bus_idx"), &AudioServer::add_bus_effect);
+ ClassDB::bind_method(D_METHOD("get_bus_effect:AudioEffect", "bus_idx", "effect_idx"), &AudioServer::get_bus_effect);
+ ClassDB::bind_method(D_METHOD("swap_bus_effects", "bus_idx", "effect_idx", "by_effect_idx"), &AudioServer::swap_bus_effects);
- ClassDB::bind_method(D_METHOD("get_bus_effect_count","bus_idx"),&AudioServer::add_bus_effect);
- ClassDB::bind_method(D_METHOD("get_bus_effect:AudioEffect","bus_idx","effect_idx"),&AudioServer::get_bus_effect);
- ClassDB::bind_method(D_METHOD("swap_bus_effects","bus_idx","effect_idx","by_effect_idx"),&AudioServer::swap_bus_effects);
+ ClassDB::bind_method(D_METHOD("set_bus_effect_enabled", "bus_idx", "effect_idx", "enabled"), &AudioServer::set_bus_effect_enabled);
+ ClassDB::bind_method(D_METHOD("is_bus_effect_enabled", "bus_idx", "effect_idx"), &AudioServer::is_bus_effect_enabled);
- ClassDB::bind_method(D_METHOD("set_bus_effect_enabled","bus_idx","effect_idx","enabled"),&AudioServer::set_bus_effect_enabled);
- ClassDB::bind_method(D_METHOD("is_bus_effect_enabled","bus_idx","effect_idx"),&AudioServer::is_bus_effect_enabled);
+ ClassDB::bind_method(D_METHOD("get_bus_peak_volume_left_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_left_db);
+ ClassDB::bind_method(D_METHOD("get_bus_peak_volume_right_db", "bus_idx", "channel"), &AudioServer::get_bus_peak_volume_right_db);
- ClassDB::bind_method(D_METHOD("get_bus_peak_volume_left_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_left_db);
- ClassDB::bind_method(D_METHOD("get_bus_peak_volume_right_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_right_db);
+ ClassDB::bind_method(D_METHOD("lock"), &AudioServer::lock);
+ ClassDB::bind_method(D_METHOD("unlock"), &AudioServer::unlock);
- ClassDB::bind_method(D_METHOD("lock"),&AudioServer::lock);
- ClassDB::bind_method(D_METHOD("unlock"),&AudioServer::unlock);
+ ClassDB::bind_method(D_METHOD("get_speaker_mode"), &AudioServer::get_speaker_mode);
+ ClassDB::bind_method(D_METHOD("get_mix_rate"), &AudioServer::get_mix_rate);
- ClassDB::bind_method(D_METHOD("get_speaker_mode"),&AudioServer::get_speaker_mode);
- ClassDB::bind_method(D_METHOD("get_mix_rate"),&AudioServer::get_mix_rate);
+ ClassDB::bind_method(D_METHOD("set_state", "state:AudioServerState"), &AudioServer::set_bus_layout);
+ ClassDB::bind_method(D_METHOD("generate_state:AudioServerState"), &AudioServer::generate_bus_layout);
- ClassDB::bind_method(D_METHOD("set_state","state:AudioServerState"),&AudioServer::set_bus_layout);
- ClassDB::bind_method(D_METHOD("generate_state:AudioServerState"),&AudioServer::generate_bus_layout);
-
- ADD_SIGNAL(MethodInfo("bus_layout_changed") );
+ ADD_SIGNAL(MethodInfo("bus_layout_changed"));
}
AudioServer::AudioServer() {
- singleton=this;
- audio_data_total_mem=0;
- audio_data_max_mem=0;
- audio_data_lock=Mutex::create();
- mix_frames=0;
- to_mix=0;
-
+ singleton = this;
+ audio_data_total_mem = 0;
+ audio_data_max_mem = 0;
+ audio_data_lock = Mutex::create();
+ mix_frames = 0;
+ to_mix = 0;
}
AudioServer::~AudioServer() {
@@ -1087,46 +1011,44 @@ AudioServer::~AudioServer() {
/////////////////////////////////
-
-
-bool AudioBusLayout::_set(const StringName& p_name, const Variant& p_value) {
+bool AudioBusLayout::_set(const StringName &p_name, const Variant &p_value) {
String s = p_name;
if (s.begins_with("bus/")) {
- int index = s.get_slice("/",1).to_int();
- if (buses.size()<=index) {
- buses.resize(index+1);
+ int index = s.get_slice("/", 1).to_int();
+ if (buses.size() <= index) {
+ buses.resize(index + 1);
}
Bus &bus = buses[index];
- String what = s.get_slice("/",2);
-
- if (what=="name") {
- bus.name=p_value;
- } else if (what=="solo") {
- bus.solo=p_value;
- } else if (what=="mute") {
- bus.mute=p_value;
- } else if (what=="bypass_fx") {
- bus.bypass=p_value;
- } else if (what=="volume_db") {
- bus.volume_db=p_value;
- } else if (what=="send") {
- bus.send=p_value;
- } else if (what=="effect") {
- int which = s.get_slice("/",3).to_int();
- if (bus.effects.size()<=which) {
- bus.effects.resize(which+1);
+ String what = s.get_slice("/", 2);
+
+ if (what == "name") {
+ bus.name = p_value;
+ } else if (what == "solo") {
+ bus.solo = p_value;
+ } else if (what == "mute") {
+ bus.mute = p_value;
+ } else if (what == "bypass_fx") {
+ bus.bypass = p_value;
+ } else if (what == "volume_db") {
+ bus.volume_db = p_value;
+ } else if (what == "send") {
+ bus.send = p_value;
+ } else if (what == "effect") {
+ int which = s.get_slice("/", 3).to_int();
+ if (bus.effects.size() <= which) {
+ bus.effects.resize(which + 1);
}
Bus::Effect &fx = bus.effects[which];
- String fxwhat = s.get_slice("/",4);
- if (fxwhat=="effect") {
- fx.effect=p_value;
- } else if (fxwhat=="enabled") {
- fx.enabled=p_value;
+ String fxwhat = s.get_slice("/", 4);
+ if (fxwhat == "effect") {
+ fx.effect = p_value;
+ } else if (fxwhat == "enabled") {
+ fx.enabled = p_value;
} else {
return false;
}
@@ -1140,47 +1062,46 @@ bool AudioBusLayout::_set(const StringName& p_name, const Variant& p_value) {
}
return false;
-
}
-bool AudioBusLayout::_get(const StringName& p_name,Variant &r_ret) const{
+bool AudioBusLayout::_get(const StringName &p_name, Variant &r_ret) const {
String s = p_name;
if (s.begins_with("bus/")) {
- int index = s.get_slice("/",1).to_int();
- if (index<0 || index>=buses.size())
+ int index = s.get_slice("/", 1).to_int();
+ if (index < 0 || index >= buses.size())
return false;
const Bus &bus = buses[index];
- String what = s.get_slice("/",2);
-
- if (what=="name") {
- r_ret=bus.name;
- } else if (what=="solo") {
- r_ret=bus.solo;
- } else if (what=="mute") {
- r_ret=bus.mute;
- } else if (what=="bypass_fx") {
- r_ret=bus.bypass;
- } else if (what=="volume_db") {
- r_ret=bus.volume_db;
- } else if (what=="send") {
- r_ret=bus.send;
- } else if (what=="effect") {
- int which = s.get_slice("/",3).to_int();
- if (which<0 || which>=bus.effects.size()) {
+ String what = s.get_slice("/", 2);
+
+ if (what == "name") {
+ r_ret = bus.name;
+ } else if (what == "solo") {
+ r_ret = bus.solo;
+ } else if (what == "mute") {
+ r_ret = bus.mute;
+ } else if (what == "bypass_fx") {
+ r_ret = bus.bypass;
+ } else if (what == "volume_db") {
+ r_ret = bus.volume_db;
+ } else if (what == "send") {
+ r_ret = bus.send;
+ } else if (what == "effect") {
+ int which = s.get_slice("/", 3).to_int();
+ if (which < 0 || which >= bus.effects.size()) {
return false;
}
const Bus::Effect &fx = bus.effects[which];
- String fxwhat = s.get_slice("/",4);
- if (fxwhat=="effect") {
- r_ret=fx.effect;
- } else if (fxwhat=="enabled") {
- r_ret=fx.enabled;
+ String fxwhat = s.get_slice("/", 4);
+ if (fxwhat == "effect") {
+ r_ret = fx.effect;
+ } else if (fxwhat == "enabled") {
+ r_ret = fx.enabled;
} else {
return false;
}
@@ -1194,28 +1115,26 @@ bool AudioBusLayout::_get(const StringName& p_name,Variant &r_ret) const{
}
return false;
-
}
-void AudioBusLayout::_get_property_list( List<PropertyInfo> *p_list) const{
+void AudioBusLayout::_get_property_list(List<PropertyInfo> *p_list) const {
- for(int i=0;i<buses.size();i++) {
- p_list->push_back(PropertyInfo(Variant::STRING,"bus/"+itos(i)+"/name",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/solo",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/mute",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/bypass_fx",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/volume_db",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/send",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
+ for (int i = 0; i < buses.size(); i++) {
+ p_list->push_back(PropertyInfo(Variant::STRING, "bus/" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/solo", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/mute", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/bypass_fx", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::REAL, "bus/" + itos(i) + "/volume_db", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::REAL, "bus/" + itos(i) + "/send", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
- for(int j=0;j<buses[i].effects.size();j++) {
- p_list->push_back(PropertyInfo(Variant::OBJECT,"bus/"+itos(i)+"/effect/"+itos(j)+"/effect",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
- p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/effect/"+itos(j)+"/enabled",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR));
+ for (int j = 0; j < buses[i].effects.size(); j++) {
+ p_list->push_back(PropertyInfo(Variant::OBJECT, "bus/" + itos(i) + "/effect/" + itos(j) + "/effect", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
+ p_list->push_back(PropertyInfo(Variant::BOOL, "bus/" + itos(i) + "/effect/" + itos(j) + "/enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR));
}
}
}
-
AudioBusLayout::AudioBusLayout() {
buses.resize(1);
- buses[0].name="Master";
+ buses[0].name = "Master";
}
diff --git a/servers/audio_server.h b/servers/audio_server.h
index 88849bb591..46f845f2d4 100644
--- a/servers/audio_server.h
+++ b/servers/audio_server.h
@@ -29,28 +29,22 @@
#ifndef AUDIO_SERVER_H
#define AUDIO_SERVER_H
-#include "variant.h"
-#include "object.h"
#include "audio_frame.h"
+#include "object.h"
#include "servers/audio/audio_effect.h"
-
+#include "variant.h"
class AudioDriver {
-
static AudioDriver *singleton;
uint64_t _last_mix_time;
uint64_t _mix_amount;
-
protected:
-
- void audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time=true);
+ void audio_server_process(int p_frames, int32_t *p_buffer, bool p_update_mix_time = true);
void update_mix_time(int p_frames);
public:
-
-
double get_mix_time() const; //useful for video -> audio sync
enum SpeakerMode {
@@ -62,49 +56,43 @@ public:
static AudioDriver *get_singleton();
void set_singleton();
- virtual const char* get_name() const=0;
+ virtual const char *get_name() const = 0;
- virtual Error init()=0;
- virtual void start()=0;
- virtual int get_mix_rate() const =0;
- virtual SpeakerMode get_speaker_mode() const=0;
- virtual void lock()=0;
- virtual void unlock()=0;
- virtual void finish()=0;
+ virtual Error init() = 0;
+ virtual void start() = 0;
+ virtual int get_mix_rate() const = 0;
+ virtual SpeakerMode get_speaker_mode() const = 0;
+ virtual void lock() = 0;
+ virtual void unlock() = 0;
+ virtual void finish() = 0;
virtual float get_latency() { return 0; }
-
-
-
AudioDriver();
virtual ~AudioDriver() {}
};
-
-
class AudioDriverManager {
enum {
- MAX_DRIVERS=10
+ MAX_DRIVERS = 10
};
static AudioDriver *drivers[MAX_DRIVERS];
static int driver_count;
-public:
+public:
static void add_driver(AudioDriver *p_driver);
static int get_driver_count();
static AudioDriver *get_driver(int p_driver);
};
-
class AudioBusLayout;
class AudioServer : public Object {
- GDCLASS( AudioServer, Object )
+ GDCLASS(AudioServer, Object)
public:
//re-expose this her, as AudioDriver is not exposed to script
enum SpeakerMode {
@@ -114,10 +102,10 @@ public:
};
enum {
- AUDIO_DATA_INVALID_ID=-1
+ AUDIO_DATA_INVALID_ID = -1
};
- typedef void (*AudioCallback)(void* p_userdata);
+ typedef void (*AudioCallback)(void *p_userdata);
private:
uint32_t buffer_size;
@@ -144,12 +132,16 @@ private:
Vector<AudioFrame> buffer;
Vector<Ref<AudioEffectInstance> > effect_instances;
uint64_t last_mix_with_audio;
- Channel() { last_mix_with_audio=0; used=false; active=false; peak_volume=AudioFrame(0,0); }
+ Channel() {
+ last_mix_with_audio = 0;
+ used = false;
+ active = false;
+ peak_volume = AudioFrame(0, 0);
+ }
};
Vector<Channel> channels;
-
struct Effect {
Ref<AudioEffect> effect;
bool enabled;
@@ -161,31 +153,26 @@ private:
int index_cache;
};
-
- Vector< Vector<AudioFrame> >temp_buffer; //temp_buffer for each level
- Vector<Bus*> buses;
- Map<StringName,Bus*> bus_map;
+ Vector<Vector<AudioFrame> > temp_buffer; //temp_buffer for each level
+ Vector<Bus *> buses;
+ Map<StringName, Bus *> bus_map;
_FORCE_INLINE_ int _get_channel_count() const {
switch (AudioDriver::get_singleton()->get_speaker_mode()) {
case AudioDriver::SPEAKER_MODE_STEREO: return 1;
case AudioDriver::SPEAKER_SURROUND_51: return 3;
case AudioDriver::SPEAKER_SURROUND_71: return 4;
-
}
ERR_FAIL_V(1);
}
-
void _update_bus_effects(int p_bus);
-
- static AudioServer* singleton;
+ static AudioServer *singleton;
// TODO create an audiodata pool to optimize memory
-
- Map<void*,uint32_t> audio_data;
+ Map<void *, uint32_t> audio_data;
size_t audio_data_total_mem;
size_t audio_data_max_mem;
@@ -198,68 +185,66 @@ private:
AudioCallback callback;
void *userdata;
- bool operator<(const CallbackItem& p_item) const {
- return (callback==p_item.callback ? userdata < p_item.userdata : callback < p_item.callback);
+ bool operator<(const CallbackItem &p_item) const {
+ return (callback == p_item.callback ? userdata < p_item.userdata : callback < p_item.callback);
}
};
Set<CallbackItem> callbacks;
-friend class AudioDriver;
+ friend class AudioDriver;
void _driver_process(int p_frames, int32_t *p_buffer);
-protected:
+protected:
static void _bind_methods();
-public:
+public:
//do not use from outside audio thread
- AudioFrame *thread_get_channel_mix_buffer(int p_bus,int p_buffer);
+ AudioFrame *thread_get_channel_mix_buffer(int p_bus, int p_buffer);
int thread_get_mix_buffer_size() const;
- int thread_find_bus_index(const StringName& p_name);
-
+ int thread_find_bus_index(const StringName &p_name);
void set_bus_count(int p_count);
int get_bus_count() const;
void remove_bus(int p_index);
- void add_bus(int p_at_pos=-1);
+ void add_bus(int p_at_pos = -1);
- void move_bus(int p_bus,int p_to_pos);
+ void move_bus(int p_bus, int p_to_pos);
- void set_bus_name(int p_bus,const String& p_name);
+ void set_bus_name(int p_bus, const String &p_name);
String get_bus_name(int p_bus) const;
- void set_bus_volume_db(int p_bus,float p_volume_db);
+ void set_bus_volume_db(int p_bus, float p_volume_db);
float get_bus_volume_db(int p_bus) const;
-
- void set_bus_send(int p_bus,const StringName& p_send);
+ void set_bus_send(int p_bus, const StringName &p_send);
StringName get_bus_send(int p_bus) const;
- void set_bus_solo(int p_bus,bool p_enable);
+ void set_bus_solo(int p_bus, bool p_enable);
bool is_bus_solo(int p_bus) const;
- void set_bus_mute(int p_bus,bool p_enable);
+ void set_bus_mute(int p_bus, bool p_enable);
bool is_bus_mute(int p_bus) const;
- void set_bus_bypass_effects(int p_bus,bool p_enable);
+ void set_bus_bypass_effects(int p_bus, bool p_enable);
bool is_bus_bypassing_effects(int p_bus) const;
- void add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int p_at_pos=-1);
- void remove_bus_effect(int p_bus,int p_effect);
+ void add_bus_effect(int p_bus, const Ref<AudioEffect> &p_effect, int p_at_pos = -1);
+ void remove_bus_effect(int p_bus, int p_effect);
int get_bus_effect_count(int p_bus);
- Ref<AudioEffect> get_bus_effect(int p_bus,int p_effect);
+ Ref<AudioEffect> get_bus_effect(int p_bus, int p_effect);
- void swap_bus_effects(int p_bus,int p_effect,int p_by_effect);
+ void swap_bus_effects(int p_bus, int p_effect, int p_by_effect);
- void set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled);
- bool is_bus_effect_enabled(int p_bus,int p_effect) const;
+ void set_bus_effect_enabled(int p_bus, int p_effect, bool p_enabled);
+ bool is_bus_effect_enabled(int p_bus, int p_effect) const;
- float get_bus_peak_volume_left_db(int p_bus,int p_channel) const;
- float get_bus_peak_volume_right_db(int p_bus,int p_channel) const;
+ float get_bus_peak_volume_left_db(int p_bus, int p_channel) const;
+ float get_bus_peak_volume_right_db(int p_bus, int p_channel) const;
- bool is_bus_channel_active(int p_bus,int p_channel) const;
+ bool is_bus_channel_active(int p_bus, int p_channel) const;
virtual void init();
virtual void finish();
@@ -271,7 +256,6 @@ public:
virtual void lock();
virtual void unlock();
-
virtual SpeakerMode get_speaker_mode() const;
virtual float get_mix_rate() const;
@@ -282,30 +266,29 @@ public:
virtual double get_mix_time() const; //useful for video -> audio sync
virtual double get_output_delay() const;
- void* audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data=NULL);
- void audio_data_free(void* p_data);
+ void *audio_data_alloc(uint32_t p_data_len, const uint8_t *p_from_data = NULL);
+ void audio_data_free(void *p_data);
size_t audio_data_get_total_memory_usage() const;
size_t audio_data_get_max_memory_usage() const;
+ void add_callback(AudioCallback p_callback, void *p_userdata);
+ void remove_callback(AudioCallback p_callback, void *p_userdata);
- void add_callback(AudioCallback p_callback,void *p_userdata);
- void remove_callback(AudioCallback p_callback,void *p_userdata);
-
- void set_bus_layout(const Ref<AudioBusLayout>& p_state);
+ void set_bus_layout(const Ref<AudioBusLayout> &p_state);
Ref<AudioBusLayout> generate_bus_layout() const;
AudioServer();
virtual ~AudioServer();
};
-VARIANT_ENUM_CAST( AudioServer::SpeakerMode )
+VARIANT_ENUM_CAST(AudioServer::SpeakerMode)
class AudioBusLayout : public Resource {
- GDCLASS(AudioBusLayout,Resource)
+ GDCLASS(AudioBusLayout, Resource)
-friend class AudioServer;
+ friend class AudioServer;
struct Bus {
@@ -325,32 +308,24 @@ friend class AudioServer;
StringName send;
Bus() {
- solo=false;
- mute=false;
- bypass=false;
- volume_db=0;
+ solo = false;
+ mute = false;
+ bypass = false;
+ volume_db = 0;
}
};
Vector<Bus> buses;
protected:
-
- bool _set(const StringName& p_name, const Variant& p_value);
- bool _get(const StringName& p_name,Variant &r_ret) const;
- void _get_property_list( List<PropertyInfo> *p_list) const;
+ bool _set(const StringName &p_name, const Variant &p_value);
+ bool _get(const StringName &p_name, Variant &r_ret) const;
+ void _get_property_list(List<PropertyInfo> *p_list) const;
public:
-
AudioBusLayout();
};
-
-
-
-
-
typedef AudioServer AS;
-
#endif // AUDIO_SERVER_H
diff --git a/servers/physics/area_pair_sw.cpp b/servers/physics/area_pair_sw.cpp
index 3aa0816b06..d1040baa65 100644
--- a/servers/physics/area_pair_sw.cpp
+++ b/servers/physics/area_pair_sw.cpp
@@ -29,7 +29,6 @@
#include "area_pair_sw.h"
#include "collision_solver_sw.h"
-
bool AreaPairSW::setup(real_t p_step) {
if (!area->test_collision_mask(body)) {
@@ -37,63 +36,55 @@ bool AreaPairSW::setup(real_t p_step) {
return false;
}
- bool result = CollisionSolverSW::solve_static(body->get_shape(body_shape),body->get_transform() * body->get_shape_transform(body_shape),area->get_shape(area_shape),area->get_transform() * area->get_shape_transform(area_shape),NULL,this);
+ bool result = CollisionSolverSW::solve_static(body->get_shape(body_shape), body->get_transform() * body->get_shape_transform(body_shape), area->get_shape(area_shape), area->get_transform() * area->get_shape_transform(area_shape), NULL, this);
- if (result!=colliding) {
+ if (result != colliding) {
if (result) {
- if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
body->add_area(area);
if (area->has_monitor_callback())
- area->add_body_to_query(body,body_shape,area_shape);
+ area->add_body_to_query(body, body_shape, area_shape);
} else {
- if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
body->remove_area(area);
if (area->has_monitor_callback())
- area->remove_body_from_query(body,body_shape,area_shape);
-
+ area->remove_body_from_query(body, body_shape, area_shape);
}
- colliding=result;
-
+ colliding = result;
}
return false; //never do any post solving
}
void AreaPairSW::solve(real_t p_step) {
-
-
}
+AreaPairSW::AreaPairSW(BodySW *p_body, int p_body_shape, AreaSW *p_area, int p_area_shape) {
-AreaPairSW::AreaPairSW(BodySW *p_body,int p_body_shape, AreaSW *p_area,int p_area_shape) {
-
- body=p_body;
- area=p_area;
- body_shape=p_body_shape;
- area_shape=p_area_shape;
- colliding=false;
- body->add_constraint(this,0);
+ body = p_body;
+ area = p_area;
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+ colliding = false;
+ body->add_constraint(this, 0);
area->add_constraint(this);
- if (p_body->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC)
+ if (p_body->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC)
p_body->set_active(true);
-
}
AreaPairSW::~AreaPairSW() {
if (colliding) {
- if (area->get_space_override_mode()!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED)
body->remove_area(area);
if (area->has_monitor_callback())
- area->remove_body_from_query(body,body_shape,area_shape);
-
-
+ area->remove_body_from_query(body, body_shape, area_shape);
}
body->remove_constraint(this);
area->remove_constraint(this);
@@ -101,8 +92,6 @@ AreaPairSW::~AreaPairSW() {
////////////////////////////////////////////////////
-
-
bool Area2PairSW::setup(real_t p_step) {
if (!area_a->test_collision_mask(area_b)) {
@@ -111,51 +100,45 @@ bool Area2PairSW::setup(real_t p_step) {
}
//bool result = area_a->test_collision_mask(area_b) && CollisionSolverSW::solve(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),Vector2(),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),Vector2(),NULL,this);
- bool result = CollisionSolverSW::solve_static(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),NULL,this);
+ bool result = CollisionSolverSW::solve_static(area_a->get_shape(shape_a), area_a->get_transform() * area_a->get_shape_transform(shape_a), area_b->get_shape(shape_b), area_b->get_transform() * area_b->get_shape_transform(shape_b), NULL, this);
- if (result!=colliding) {
+ if (result != colliding) {
if (result) {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->add_area_to_query(area_a,shape_a,shape_b);
+ area_b->add_area_to_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->add_area_to_query(area_b,shape_b,shape_a);
+ area_a->add_area_to_query(area_b, shape_b, shape_a);
} else {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->remove_area_from_query(area_a,shape_a,shape_b);
+ area_b->remove_area_from_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->remove_area_from_query(area_b,shape_b,shape_a);
+ area_a->remove_area_from_query(area_b, shape_b, shape_a);
}
- colliding=result;
-
+ colliding = result;
}
return false; //never do any post solving
}
void Area2PairSW::solve(real_t p_step) {
-
-
}
+Area2PairSW::Area2PairSW(AreaSW *p_area_a, int p_shape_a, AreaSW *p_area_b, int p_shape_b) {
-Area2PairSW::Area2PairSW(AreaSW *p_area_a,int p_shape_a, AreaSW *p_area_b,int p_shape_b) {
-
-
- area_a=p_area_a;
- area_b=p_area_b;
- shape_a=p_shape_a;
- shape_b=p_shape_b;
- colliding=false;
+ area_a = p_area_a;
+ area_b = p_area_b;
+ shape_a = p_shape_a;
+ shape_b = p_shape_b;
+ colliding = false;
area_a->add_constraint(this);
area_b->add_constraint(this);
-
}
Area2PairSW::~Area2PairSW() {
@@ -163,10 +146,10 @@ Area2PairSW::~Area2PairSW() {
if (colliding) {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->remove_area_from_query(area_a,shape_a,shape_b);
+ area_b->remove_area_from_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->remove_area_from_query(area_b,shape_b,shape_a);
+ area_a->remove_area_from_query(area_b, shape_b, shape_a);
}
area_a->remove_constraint(this);
diff --git a/servers/physics/area_pair_sw.h b/servers/physics/area_pair_sw.h
index 637976a095..8fc7e7efaa 100644
--- a/servers/physics/area_pair_sw.h
+++ b/servers/physics/area_pair_sw.h
@@ -29,9 +29,9 @@
#ifndef AREA_PAIR_SW_H
#define AREA_PAIR_SW_H
-#include "constraint_sw.h"
-#include "body_sw.h"
#include "area_sw.h"
+#include "body_sw.h"
+#include "constraint_sw.h"
class AreaPairSW : public ConstraintSW {
@@ -40,16 +40,15 @@ class AreaPairSW : public ConstraintSW {
int body_shape;
int area_shape;
bool colliding;
-public:
+public:
bool setup(real_t p_step);
void solve(real_t p_step);
- AreaPairSW(BodySW *p_body,int p_body_shape, AreaSW *p_area,int p_area_shape);
+ AreaPairSW(BodySW *p_body, int p_body_shape, AreaSW *p_area, int p_area_shape);
~AreaPairSW();
};
-
class Area2PairSW : public ConstraintSW {
AreaSW *area_a;
@@ -57,15 +56,13 @@ class Area2PairSW : public ConstraintSW {
int shape_a;
int shape_b;
bool colliding;
-public:
+public:
bool setup(real_t p_step);
void solve(real_t p_step);
- Area2PairSW(AreaSW *p_area_a,int p_shape_a, AreaSW *p_area_b,int p_shape_b);
+ Area2PairSW(AreaSW *p_area_a, int p_shape_a, AreaSW *p_area_b, int p_shape_b);
~Area2PairSW();
};
-
#endif // AREA_PAIR__SW_H
-
diff --git a/servers/physics/area_sw.cpp b/servers/physics/area_sw.cpp
index 8aed07d5e5..dfb5d191bc 100644
--- a/servers/physics/area_sw.cpp
+++ b/servers/physics/area_sw.cpp
@@ -27,18 +27,26 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "area_sw.h"
-#include "space_sw.h"
#include "body_sw.h"
+#include "space_sw.h"
-AreaSW::BodyKey::BodyKey(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; }
-AreaSW::BodyKey::BodyKey(AreaSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; }
+AreaSW::BodyKey::BodyKey(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
+ rid = p_body->get_self();
+ instance_id = p_body->get_instance_id();
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+}
+AreaSW::BodyKey::BodyKey(AreaSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
+ rid = p_body->get_self();
+ instance_id = p_body->get_instance_id();
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+}
void AreaSW::_shapes_changed() {
-
-
}
-void AreaSW::set_transform(const Transform& p_transform) {
+void AreaSW::set_transform(const Transform &p_transform) {
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
@@ -54,7 +62,6 @@ void AreaSW::set_space(SpaceSW *p_space) {
get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
if (moved_list.in_list())
get_space()->area_remove_from_moved_list(&moved_list);
-
}
monitored_bodies.clear();
@@ -63,44 +70,38 @@ void AreaSW::set_space(SpaceSW *p_space) {
_set_space(p_space);
}
+void AreaSW::set_monitor_callback(ObjectID p_id, const StringName &p_method) {
-void AreaSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) {
-
-
- if (p_id==monitor_callback_id) {
- monitor_callback_method=p_method;
+ if (p_id == monitor_callback_id) {
+ monitor_callback_method = p_method;
return;
}
_unregister_shapes();
- monitor_callback_id=p_id;
- monitor_callback_method=p_method;
+ monitor_callback_id = p_id;
+ monitor_callback_method = p_method;
monitored_bodies.clear();
monitored_areas.clear();
-
_shape_changed();
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
-
-
}
-void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method) {
+void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName &p_method) {
-
- if (p_id==area_monitor_callback_id) {
- area_monitor_callback_method=p_method;
+ if (p_id == area_monitor_callback_id) {
+ area_monitor_callback_method = p_method;
return;
}
_unregister_shapes();
- area_monitor_callback_id=p_id;
- area_monitor_callback_method=p_method;
+ area_monitor_callback_id = p_id;
+ area_monitor_callback_method = p_method;
monitored_bodies.clear();
monitored_areas.clear();
@@ -109,45 +110,39 @@ void AreaSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
-
-
}
-
void AreaSW::set_space_override_mode(PhysicsServer::AreaSpaceOverrideMode p_mode) {
- bool do_override=p_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
- if (do_override==(space_override_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED))
+ bool do_override = p_mode != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
+ if (do_override == (space_override_mode != PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED))
return;
_unregister_shapes();
- space_override_mode=p_mode;
+ space_override_mode = p_mode;
_shape_changed();
}
-void AreaSW::set_param(PhysicsServer::AreaParameter p_param, const Variant& p_value) {
-
- switch(p_param) {
- case PhysicsServer::AREA_PARAM_GRAVITY: gravity=p_value; break;
- case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector=p_value; break;
- case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point=p_value; break;
- case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale=p_value; break;
- case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation=p_value; break;
- case PhysicsServer::AREA_PARAM_LINEAR_DAMP: linear_damp=p_value; break;
- case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: angular_damp=p_value; break;
- case PhysicsServer::AREA_PARAM_PRIORITY: priority=p_value; break;
+void AreaSW::set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value) {
+
+ switch (p_param) {
+ case PhysicsServer::AREA_PARAM_GRAVITY: gravity = p_value; break;
+ case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector = p_value; break;
+ case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point = p_value; break;
+ case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale = p_value; break;
+ case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation = p_value; break;
+ case PhysicsServer::AREA_PARAM_LINEAR_DAMP: linear_damp = p_value; break;
+ case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: angular_damp = p_value; break;
+ case PhysicsServer::AREA_PARAM_PRIORITY: priority = p_value; break;
}
-
-
}
Variant AreaSW::get_param(PhysicsServer::AreaParameter p_param) const {
-
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::AREA_PARAM_GRAVITY: return gravity;
case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: return gravity_vector;
case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: return gravity_is_point;
case PhysicsServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return gravity_distance_scale;
- case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation;
+ case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation;
case PhysicsServer::AREA_PARAM_LINEAR_DAMP: return linear_damp;
case PhysicsServer::AREA_PARAM_ANGULAR_DAMP: return angular_damp;
case PhysicsServer::AREA_PARAM_PRIORITY: return priority;
@@ -156,23 +151,20 @@ Variant AreaSW::get_param(PhysicsServer::AreaParameter p_param) const {
return Variant();
}
-
void AreaSW::_queue_monitor_update() {
ERR_FAIL_COND(!get_space());
if (!monitor_query_list.in_list())
get_space()->area_add_to_monitor_query_list(&monitor_query_list);
-
-
}
void AreaSW::set_monitorable(bool p_monitorable) {
- if (monitorable==p_monitorable)
+ if (monitorable == p_monitorable)
return;
- monitorable=p_monitorable;
+ monitorable = p_monitorable;
_set_static(!monitorable);
}
@@ -182,29 +174,29 @@ void AreaSW::call_queries() {
Variant res[5];
Variant *resptr[5];
- for(int i=0;i<5;i++)
- resptr[i]=&res[i];
+ for (int i = 0; i < 5; i++)
+ resptr[i] = &res[i];
Object *obj = ObjectDB::get_instance(monitor_callback_id);
if (!obj) {
monitored_bodies.clear();
- monitor_callback_id=0;
+ monitor_callback_id = 0;
return;
}
- for (Map<BodyKey,BodyState>::Element *E=monitored_bodies.front();E;E=E->next()) {
+ for (Map<BodyKey, BodyState>::Element *E = monitored_bodies.front(); E; E = E->next()) {
- if (E->get().state==0)
+ if (E->get().state == 0)
continue; //nothing happened
- res[0]=E->get().state>0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED;
- res[1]=E->key().rid;
- res[2]=E->key().instance_id;
- res[3]=E->key().body_shape;
- res[4]=E->key().area_shape;
+ res[0] = E->get().state > 0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED;
+ res[1] = E->key().rid;
+ res[2] = E->key().instance_id;
+ res[3] = E->key().body_shape;
+ res[4] = E->key().area_shape;
Variant::CallError ce;
- obj->call(monitor_callback_method,(const Variant**)resptr,5,ce);
+ obj->call(monitor_callback_method, (const Variant **)resptr, 5, ce);
}
}
@@ -212,64 +204,56 @@ void AreaSW::call_queries() {
if (area_monitor_callback_id && !monitored_areas.empty()) {
-
Variant res[5];
Variant *resptr[5];
- for(int i=0;i<5;i++)
- resptr[i]=&res[i];
+ for (int i = 0; i < 5; i++)
+ resptr[i] = &res[i];
Object *obj = ObjectDB::get_instance(area_monitor_callback_id);
if (!obj) {
monitored_areas.clear();
- area_monitor_callback_id=0;
+ area_monitor_callback_id = 0;
return;
}
+ for (Map<BodyKey, BodyState>::Element *E = monitored_areas.front(); E; E = E->next()) {
-
- for (Map<BodyKey,BodyState>::Element *E=monitored_areas.front();E;E=E->next()) {
-
- if (E->get().state==0)
+ if (E->get().state == 0)
continue; //nothing happened
- res[0]=E->get().state>0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED;
- res[1]=E->key().rid;
- res[2]=E->key().instance_id;
- res[3]=E->key().body_shape;
- res[4]=E->key().area_shape;
-
+ res[0] = E->get().state > 0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED;
+ res[1] = E->key().rid;
+ res[2] = E->key().instance_id;
+ res[3] = E->key().body_shape;
+ res[4] = E->key().area_shape;
Variant::CallError ce;
- obj->call(area_monitor_callback_method,(const Variant**)resptr,5,ce);
+ obj->call(area_monitor_callback_method, (const Variant **)resptr, 5, ce);
}
}
monitored_areas.clear();
//get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
-
}
-AreaSW::AreaSW() : CollisionObjectSW(TYPE_AREA), monitor_query_list(this), moved_list(this) {
+AreaSW::AreaSW()
+ : CollisionObjectSW(TYPE_AREA), monitor_query_list(this), moved_list(this) {
_set_static(true); //areas are never active
- space_override_mode=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
- gravity=9.80665;
- gravity_vector=Vector3(0,-1,0);
- gravity_is_point=false;
- gravity_distance_scale=0;
- point_attenuation=1;
- angular_damp=1.0;
- linear_damp=0.1;
- priority=0;
+ space_override_mode = PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
+ gravity = 9.80665;
+ gravity_vector = Vector3(0, -1, 0);
+ gravity_is_point = false;
+ gravity_distance_scale = 0;
+ point_attenuation = 1;
+ angular_damp = 1.0;
+ linear_damp = 0.1;
+ priority = 0;
set_ray_pickable(false);
- monitor_callback_id=0;
- area_monitor_callback_id=0;
- monitorable=false;
-
+ monitor_callback_id = 0;
+ area_monitor_callback_id = 0;
+ monitorable = false;
}
AreaSW::~AreaSW() {
-
-
}
-
diff --git a/servers/physics/area_sw.h b/servers/physics/area_sw.h
index 4e6f1c5a51..2c0cd8dbcd 100644
--- a/servers/physics/area_sw.h
+++ b/servers/physics/area_sw.h
@@ -29,17 +29,16 @@
#ifndef AREA_SW_H
#define AREA_SW_H
-#include "servers/physics_server.h"
#include "collision_object_sw.h"
#include "self_list.h"
+#include "servers/physics_server.h"
//#include "servers/physics/query_sw.h"
class SpaceSW;
class BodySW;
class ConstraintSW;
-class AreaSW : public CollisionObjectSW{
-
+class AreaSW : public CollisionObjectSW {
PhysicsServer::AreaSpaceOverrideMode space_override_mode;
real_t gravity;
@@ -68,24 +67,22 @@ class AreaSW : public CollisionObjectSW{
uint32_t body_shape;
uint32_t area_shape;
- _FORCE_INLINE_ bool operator<( const BodyKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const BodyKey &p_key) const {
- if (rid==p_key.rid) {
+ if (rid == p_key.rid) {
- if (body_shape==p_key.body_shape) {
+ if (body_shape == p_key.body_shape) {
return area_shape < p_key.area_shape;
} else
return body_shape < p_key.body_shape;
} else
return rid < p_key.rid;
-
}
_FORCE_INLINE_ BodyKey() {}
- BodyKey(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
- BodyKey(AreaSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
-
+ BodyKey(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
+ BodyKey(AreaSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
};
struct BodyState {
@@ -93,125 +90,111 @@ class AreaSW : public CollisionObjectSW{
int state;
_FORCE_INLINE_ void inc() { state++; }
_FORCE_INLINE_ void dec() { state--; }
- _FORCE_INLINE_ BodyState() { state=0; }
+ _FORCE_INLINE_ BodyState() { state = 0; }
};
- Map<BodyKey,BodyState> monitored_bodies;
- Map<BodyKey,BodyState> monitored_areas;
+ Map<BodyKey, BodyState> monitored_bodies;
+ Map<BodyKey, BodyState> monitored_areas;
//virtual void shape_changed_notify(ShapeSW *p_shape);
//virtual void shape_deleted_notify(ShapeSW *p_shape);
- Set<ConstraintSW*> constraints;
-
+ Set<ConstraintSW *> constraints;
virtual void _shapes_changed();
void _queue_monitor_update();
public:
-
//_FORCE_INLINE_ const Transform& get_inverse_transform() const { return inverse_transform; }
//_FORCE_INLINE_ SpaceSW* get_owner() { return owner; }
- void set_monitor_callback(ObjectID p_id, const StringName& p_method);
+ void set_monitor_callback(ObjectID p_id, const StringName &p_method);
_FORCE_INLINE_ bool has_monitor_callback() const { return monitor_callback_id; }
- void set_area_monitor_callback(ObjectID p_id, const StringName& p_method);
+ void set_area_monitor_callback(ObjectID p_id, const StringName &p_method);
_FORCE_INLINE_ bool has_area_monitor_callback() const { return area_monitor_callback_id; }
- _FORCE_INLINE_ void add_body_to_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
- _FORCE_INLINE_ void remove_body_from_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
+ _FORCE_INLINE_ void add_body_to_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
+ _FORCE_INLINE_ void remove_body_from_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
- _FORCE_INLINE_ void add_area_to_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape);
- _FORCE_INLINE_ void remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape);
+ _FORCE_INLINE_ void add_area_to_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape);
+ _FORCE_INLINE_ void remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape);
- void set_param(PhysicsServer::AreaParameter p_param, const Variant& p_value);
+ void set_param(PhysicsServer::AreaParameter p_param, const Variant &p_value);
Variant get_param(PhysicsServer::AreaParameter p_param) const;
void set_space_override_mode(PhysicsServer::AreaSpaceOverrideMode p_mode);
PhysicsServer::AreaSpaceOverrideMode get_space_override_mode() const { return space_override_mode; }
- _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity=p_gravity; }
+ _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity = p_gravity; }
_FORCE_INLINE_ real_t get_gravity() const { return gravity; }
- _FORCE_INLINE_ void set_gravity_vector(const Vector3& p_gravity) { gravity_vector=p_gravity; }
+ _FORCE_INLINE_ void set_gravity_vector(const Vector3 &p_gravity) { gravity_vector = p_gravity; }
_FORCE_INLINE_ Vector3 get_gravity_vector() const { return gravity_vector; }
- _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point=p_enable; }
+ _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point = p_enable; }
_FORCE_INLINE_ bool is_gravity_point() const { return gravity_is_point; }
- _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale=scale; }
+ _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale = scale; }
_FORCE_INLINE_ real_t get_gravity_distance_scale() const { return gravity_distance_scale; }
- _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation=p_point_attenuation; }
+ _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation = p_point_attenuation; }
_FORCE_INLINE_ real_t get_point_attenuation() const { return point_attenuation; }
- _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp=p_linear_damp; }
+ _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp = p_linear_damp; }
_FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; }
- _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp=p_angular_damp; }
+ _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp = p_angular_damp; }
_FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; }
- _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; }
+ _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; }
_FORCE_INLINE_ int get_priority() const { return priority; }
- _FORCE_INLINE_ void add_constraint( ConstraintSW* p_constraint) { constraints.insert(p_constraint); }
- _FORCE_INLINE_ void remove_constraint( ConstraintSW* p_constraint) { constraints.erase(p_constraint); }
- _FORCE_INLINE_ const Set<ConstraintSW*>& get_constraints() const { return constraints; }
+ _FORCE_INLINE_ void add_constraint(ConstraintSW *p_constraint) { constraints.insert(p_constraint); }
+ _FORCE_INLINE_ void remove_constraint(ConstraintSW *p_constraint) { constraints.erase(p_constraint); }
+ _FORCE_INLINE_ const Set<ConstraintSW *> &get_constraints() const { return constraints; }
void set_monitorable(bool p_monitorable);
_FORCE_INLINE_ bool is_monitorable() const { return monitorable; }
- void set_transform(const Transform& p_transform);
+ void set_transform(const Transform &p_transform);
void set_space(SpaceSW *p_space);
-
void call_queries();
AreaSW();
~AreaSW();
};
-void AreaSW::add_body_to_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) {
+void AreaSW::add_body_to_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
- BodyKey bk(p_body,p_body_shape,p_area_shape);
+ BodyKey bk(p_body, p_body_shape, p_area_shape);
monitored_bodies[bk].inc();
if (!monitor_query_list.in_list())
_queue_monitor_update();
}
-void AreaSW::remove_body_from_query(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) {
+void AreaSW::remove_body_from_query(BodySW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
- BodyKey bk(p_body,p_body_shape,p_area_shape);
+ BodyKey bk(p_body, p_body_shape, p_area_shape);
monitored_bodies[bk].dec();
if (!monitor_query_list.in_list())
_queue_monitor_update();
}
+void AreaSW::add_area_to_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) {
-void AreaSW::add_area_to_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) {
-
-
- BodyKey bk(p_area,p_area_shape,p_self_shape);
+ BodyKey bk(p_area, p_area_shape, p_self_shape);
monitored_areas[bk].inc();
if (!monitor_query_list.in_list())
_queue_monitor_update();
-
-
}
-void AreaSW::remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) {
-
+void AreaSW::remove_area_from_query(AreaSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) {
- BodyKey bk(p_area,p_area_shape,p_self_shape);
+ BodyKey bk(p_area, p_area_shape, p_self_shape);
monitored_areas[bk].dec();
if (!monitor_query_list.in_list())
_queue_monitor_update();
-
}
-
-
-
-
-
#endif // AREA__SW_H
diff --git a/servers/physics/body_pair_sw.cpp b/servers/physics/body_pair_sw.cpp
index 7fb3def387..555d5f15c5 100644
--- a/servers/physics/body_pair_sw.cpp
+++ b/servers/physics/body_pair_sw.cpp
@@ -28,8 +28,8 @@
/*************************************************************************/
#include "body_pair_sw.h"
#include "collision_solver_sw.h"
-#include "space_sw.h"
#include "os/os.h"
+#include "space_sw.h"
/*
#define NO_ACCUMULATE_IMPULSES
@@ -41,19 +41,17 @@
#define NO_TANGENTIALS
/* BODY PAIR */
-
//#define ALLOWED_PENETRATION 0.01
#define RELAXATION_TIMESTEPS 3
#define MIN_VELOCITY 0.0001
-void BodyPairSW::_contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) {
-
- BodyPairSW* pair = (BodyPairSW*)p_userdata;
- pair->contact_added_callback(p_point_A,p_point_B);
+void BodyPairSW::_contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
+ BodyPairSW *pair = (BodyPairSW *)p_userdata;
+ pair->contact_added_callback(p_point_A, p_point_B);
}
-void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B) {
+void BodyPairSW::contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B) {
// check if we already have the contact
@@ -61,40 +59,36 @@ void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3&
//Vector3 local_B = B->get_inv_transform().xform(p_point_B);
Vector3 local_A = A->get_inv_transform().basis.xform(p_point_A);
- Vector3 local_B = B->get_inv_transform().basis.xform(p_point_B-offset_B);
-
-
+ Vector3 local_B = B->get_inv_transform().basis.xform(p_point_B - offset_B);
int new_index = contact_count;
- ERR_FAIL_COND( new_index >= (MAX_CONTACTS+1) );
+ ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1));
Contact contact;
- contact.acc_normal_impulse=0;
- contact.acc_bias_impulse=0;
- contact.acc_tangent_impulse=Vector3();
- contact.local_A=local_A;
- contact.local_B=local_B;
- contact.normal=(p_point_A-p_point_B).normalized();
-
-
+ contact.acc_normal_impulse = 0;
+ contact.acc_bias_impulse = 0;
+ contact.acc_tangent_impulse = Vector3();
+ contact.local_A = local_A;
+ contact.local_B = local_B;
+ contact.normal = (p_point_A - p_point_B).normalized();
// attempt to determine if the contact will be reused
- real_t contact_recycle_radius=space->get_contact_recycle_radius();
+ real_t contact_recycle_radius = space->get_contact_recycle_radius();
- for (int i=0;i<contact_count;i++) {
+ for (int i = 0; i < contact_count; i++) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
if (
- c.local_A.distance_squared_to( local_A ) < (contact_recycle_radius*contact_recycle_radius) &&
- c.local_B.distance_squared_to( local_B ) < (contact_recycle_radius*contact_recycle_radius) ) {
-
- contact.acc_normal_impulse=c.acc_normal_impulse;
- contact.acc_bias_impulse=c.acc_bias_impulse;
- contact.acc_tangent_impulse=c.acc_tangent_impulse;
- new_index=i;
- break;
+ c.local_A.distance_squared_to(local_A) < (contact_recycle_radius * contact_recycle_radius) &&
+ c.local_B.distance_squared_to(local_B) < (contact_recycle_radius * contact_recycle_radius)) {
+
+ contact.acc_normal_impulse = c.acc_normal_impulse;
+ contact.acc_bias_impulse = c.acc_bias_impulse;
+ contact.acc_tangent_impulse = c.acc_tangent_impulse;
+ new_index = i;
+ break;
}
}
@@ -104,66 +98,63 @@ void BodyPairSW::contact_added_callback(const Vector3& p_point_A,const Vector3&
// remove the contact with the minimum depth
- int least_deep=-1;
- real_t min_depth=1e10;
+ int least_deep = -1;
+ real_t min_depth = 1e10;
- for (int i=0;i<=contact_count;i++) {
+ for (int i = 0; i <= contact_count; i++) {
- Contact& c = (i==contact_count)?contact:contacts[i];
+ Contact &c = (i == contact_count) ? contact : contacts[i];
Vector3 global_A = A->get_transform().basis.xform(c.local_A);
- Vector3 global_B = B->get_transform().basis.xform(c.local_B)+offset_B;
+ Vector3 global_B = B->get_transform().basis.xform(c.local_B) + offset_B;
Vector3 axis = global_A - global_B;
- real_t depth = axis.dot( c.normal );
+ real_t depth = axis.dot(c.normal);
- if (depth<min_depth) {
+ if (depth < min_depth) {
- min_depth=depth;
- least_deep=i;
+ min_depth = depth;
+ least_deep = i;
}
}
- ERR_FAIL_COND(least_deep==-1);
+ ERR_FAIL_COND(least_deep == -1);
if (least_deep < contact_count) { //replace the last deep contact by the new one
- contacts[least_deep]=contact;
+ contacts[least_deep] = contact;
}
return;
}
- contacts[new_index]=contact;
+ contacts[new_index] = contact;
- if (new_index==contact_count) {
+ if (new_index == contact_count) {
contact_count++;
}
-
}
void BodyPairSW::validate_contacts() {
//make sure to erase contacts that are no longer valid
- real_t contact_max_separation=space->get_contact_max_separation();
- for (int i=0;i<contact_count;i++) {
+ real_t contact_max_separation = space->get_contact_max_separation();
+ for (int i = 0; i < contact_count; i++) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
Vector3 global_A = A->get_transform().basis.xform(c.local_A);
- Vector3 global_B = B->get_transform().basis.xform(c.local_B)+offset_B;
+ Vector3 global_B = B->get_transform().basis.xform(c.local_B) + offset_B;
Vector3 axis = global_A - global_B;
- real_t depth = axis.dot( c.normal );
+ real_t depth = axis.dot(c.normal);
if (depth < -contact_max_separation || (global_B + c.normal * depth - global_A).length() > contact_max_separation) {
// contact no longer needed, remove
-
- if ((i+1) < contact_count) {
+ if ((i + 1) < contact_count) {
// swap with the last one
- SWAP( contacts[i], contacts[ contact_count-1 ] );
-
+ SWAP(contacts[i], contacts[contact_count - 1]);
}
i--;
@@ -172,21 +163,18 @@ void BodyPairSW::validate_contacts() {
}
}
+bool BodyPairSW::_test_ccd(real_t p_step, BodySW *p_A, int p_shape_A, const Transform &p_xform_A, BodySW *p_B, int p_shape_B, const Transform &p_xform_B) {
-bool BodyPairSW::_test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transform& p_xform_A,BodySW *p_B, int p_shape_B,const Transform& p_xform_B) {
-
-
-
- Vector3 motion = p_A->get_linear_velocity()*p_step;
+ Vector3 motion = p_A->get_linear_velocity() * p_step;
real_t mlen = motion.length();
- if (mlen<CMP_EPSILON)
+ if (mlen < CMP_EPSILON)
return false;
Vector3 mnormal = motion / mlen;
- real_t min,max;
- p_A->get_shape(p_shape_A)->project_range(mnormal,p_xform_A,min,max);
- bool fast_object = mlen > (max-min)*0.3; //going too fast in that direction
+ real_t min, max;
+ p_A->get_shape(p_shape_A)->project_range(mnormal, p_xform_A, min, max);
+ bool fast_object = mlen > (max - min) * 0.3; //going too fast in that direction
if (!fast_object) { //did it move enough in this direction to even attempt raycast? let's say it should move more than 1/3 the size of the object in that axis
return false;
@@ -194,35 +182,34 @@ bool BodyPairSW::_test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transf
//cast a segment from support in motion normal, in the same direction of motion by motion length
//support is the worst case collision point, so real collision happened before
- Vector3 s=p_A->get_shape(p_shape_A)->get_support(p_xform_A.basis.xform(mnormal).normalized());
+ Vector3 s = p_A->get_shape(p_shape_A)->get_support(p_xform_A.basis.xform(mnormal).normalized());
Vector3 from = p_xform_A.xform(s);
Vector3 to = from + motion;
Transform from_inv = p_xform_B.affine_inverse();
- Vector3 local_from = from_inv.xform(from-mnormal*mlen*0.1); //start from a little inside the bounding box
+ Vector3 local_from = from_inv.xform(from - mnormal * mlen * 0.1); //start from a little inside the bounding box
Vector3 local_to = from_inv.xform(to);
- Vector3 rpos,rnorm;
- if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from,local_to,rpos,rnorm)) {
+ Vector3 rpos, rnorm;
+ if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm)) {
return false;
}
//shorten the linear velocity so it does not hit, but gets close enough, next frame will hit softly or soft enough
Vector3 hitpos = p_xform_B.xform(rpos);
- real_t newlen = hitpos.distance_to(from)-(max-min)*0.01;
- p_A->set_linear_velocity((mnormal*newlen)/p_step);
+ real_t newlen = hitpos.distance_to(from) - (max - min) * 0.01;
+ p_A->set_linear_velocity((mnormal * newlen) / p_step);
return true;
}
-
bool BodyPairSW::setup(real_t p_step) {
//cannot collide
- if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported()==0 && B->get_max_contacts_reported()==0)) {
- collided=false;
+ if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported() == 0 && B->get_max_contacts_reported() == 0)) {
+ collided = false;
return false;
}
@@ -231,86 +218,79 @@ bool BodyPairSW::setup(real_t p_step) {
validate_contacts();
Vector3 offset_A = A->get_transform().get_origin();
- Transform xform_Au = Transform(A->get_transform().basis,Vector3());
+ Transform xform_Au = Transform(A->get_transform().basis, Vector3());
Transform xform_A = xform_Au * A->get_shape_transform(shape_A);
Transform xform_Bu = B->get_transform();
- xform_Bu.origin-=offset_A;
+ xform_Bu.origin -= offset_A;
Transform xform_B = xform_Bu * B->get_shape_transform(shape_B);
- ShapeSW *shape_A_ptr=A->get_shape(shape_A);
- ShapeSW *shape_B_ptr=B->get_shape(shape_B);
-
- bool collided = CollisionSolverSW::solve_static(shape_A_ptr,xform_A,shape_B_ptr,xform_B,_contact_added_callback,this,&sep_axis);
- this->collided=collided;
+ ShapeSW *shape_A_ptr = A->get_shape(shape_A);
+ ShapeSW *shape_B_ptr = B->get_shape(shape_B);
+ bool collided = CollisionSolverSW::solve_static(shape_A_ptr, xform_A, shape_B_ptr, xform_B, _contact_added_callback, this, &sep_axis);
+ this->collided = collided;
if (!collided) {
//test ccd (currently just a raycast)
- if (A->is_continuous_collision_detection_enabled() && A->get_mode()>PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC) {
- _test_ccd(p_step,A,shape_A,xform_A,B,shape_B,xform_B);
+ if (A->is_continuous_collision_detection_enabled() && A->get_mode() > PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC) {
+ _test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B);
}
- if (B->is_continuous_collision_detection_enabled() && B->get_mode()>PhysicsServer::BODY_MODE_KINEMATIC && A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC) {
- _test_ccd(p_step,B,shape_B,xform_B,A,shape_A,xform_A);
+ if (B->is_continuous_collision_detection_enabled() && B->get_mode() > PhysicsServer::BODY_MODE_KINEMATIC && A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC) {
+ _test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A);
}
return false;
}
-
-
real_t max_penetration = space->get_contact_max_allowed_penetration();
real_t bias = (real_t)0.3;
if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) {
- if (shape_A_ptr->get_custom_bias()==0)
- bias=shape_B_ptr->get_custom_bias();
- else if (shape_B_ptr->get_custom_bias()==0)
- bias=shape_A_ptr->get_custom_bias();
+ if (shape_A_ptr->get_custom_bias() == 0)
+ bias = shape_B_ptr->get_custom_bias();
+ else if (shape_B_ptr->get_custom_bias() == 0)
+ bias = shape_A_ptr->get_custom_bias();
else
- bias=(shape_B_ptr->get_custom_bias()+shape_A_ptr->get_custom_bias())*0.5;
+ bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5;
}
+ real_t inv_dt = 1.0 / p_step;
-
- real_t inv_dt = 1.0/p_step;
-
- for(int i=0;i<contact_count;i++) {
+ for (int i = 0; i < contact_count; i++) {
Contact &c = contacts[i];
- c.active=false;
+ c.active = false;
Vector3 global_A = xform_Au.xform(c.local_A);
Vector3 global_B = xform_Bu.xform(c.local_B);
-
real_t depth = c.normal.dot(global_A - global_B);
- if (depth<=0) {
- c.active=false;
+ if (depth <= 0) {
+ c.active = false;
continue;
}
- c.active=true;
+ c.active = true;
#ifdef DEBUG_ENABLED
-
if (space->is_debugging_contacts()) {
- space->add_debug_contact(global_A+offset_A);
- space->add_debug_contact(global_B+offset_A);
+ space->add_debug_contact(global_A + offset_A);
+ space->add_debug_contact(global_B + offset_A);
}
#endif
- c.rA = global_A-A->get_center_of_mass();
- c.rB = global_B-B->get_center_of_mass()-offset_B;
+ c.rA = global_A - A->get_center_of_mass();
+ c.rB = global_B - B->get_center_of_mass() - offset_B;
- // contact query reporting...
+// contact query reporting...
#if 0
if (A->get_body_type() == PhysicsServer::BODY_CHARACTER)
static_cast<CharacterBodySW*>(A)->report_character_contact( global_A, global_B, B );
@@ -323,30 +303,28 @@ bool BodyPairSW::setup(real_t p_step) {
#endif
if (A->can_report_contacts()) {
- Vector3 crA = A->get_angular_velocity().cross( c.rA ) + A->get_linear_velocity();
- A->add_contact(global_A,-c.normal,depth,shape_A,global_B,shape_B,B->get_instance_id(),B->get_self(),crA);
+ Vector3 crA = A->get_angular_velocity().cross(c.rA) + A->get_linear_velocity();
+ A->add_contact(global_A, -c.normal, depth, shape_A, global_B, shape_B, B->get_instance_id(), B->get_self(), crA);
}
if (B->can_report_contacts()) {
- Vector3 crB = B->get_angular_velocity().cross( c.rB ) + B->get_linear_velocity();
- B->add_contact(global_B,c.normal,depth,shape_B,global_A,shape_A,A->get_instance_id(),A->get_self(),crB);
+ Vector3 crB = B->get_angular_velocity().cross(c.rB) + B->get_linear_velocity();
+ B->add_contact(global_B, c.normal, depth, shape_B, global_A, shape_A, A->get_instance_id(), A->get_self(), crB);
}
- if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode()<=PhysicsServer::BODY_MODE_KINEMATIC)) {
- c.active=false;
- collided=false;
+ if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC && B->get_mode() <= PhysicsServer::BODY_MODE_KINEMATIC)) {
+ c.active = false;
+ collided = false;
continue;
-
}
-
- c.active=true;
+ c.active = true;
// Precompute normal mass, tangent mass, and bias.
- Vector3 inertia_A = A->get_inv_inertia_tensor().xform( c.rA.cross( c.normal ) );
- Vector3 inertia_B = B->get_inv_inertia_tensor().xform( c.rB.cross( c.normal ) );
+ Vector3 inertia_A = A->get_inv_inertia_tensor().xform(c.rA.cross(c.normal));
+ Vector3 inertia_B = B->get_inv_inertia_tensor().xform(c.rB.cross(c.normal));
real_t kNormal = A->get_inv_mass() + B->get_inv_mass();
- kNormal += c.normal.dot( inertia_A.cross(c.rA ) ) + c.normal.dot( inertia_B.cross( c.rB ));
+ kNormal += c.normal.dot(inertia_A.cross(c.rA)) + c.normal.dot(inertia_B.cross(c.rB));
c.mass_normal = 1.0f / kNormal;
#if 1
@@ -354,34 +332,32 @@ bool BodyPairSW::setup(real_t p_step) {
#else
if (depth > max_penetration) {
- c.bias = (depth - max_penetration) * (1.0/(p_step*(1.0/RELAXATION_TIMESTEPS)));
+ c.bias = (depth - max_penetration) * (1.0 / (p_step * (1.0 / RELAXATION_TIMESTEPS)));
} else {
real_t approach = -0.1 * (depth - max_penetration) / (CMP_EPSILON + max_penetration);
- approach = CLAMP( approach, CMP_EPSILON, 1.0 );
- c.bias = approach * (depth - max_penetration) * (1.0/p_step);
+ approach = CLAMP(approach, CMP_EPSILON, 1.0);
+ c.bias = approach * (depth - max_penetration) * (1.0 / p_step);
}
#endif
- c.depth=depth;
+ c.depth = depth;
Vector3 j_vec = c.normal * c.acc_normal_impulse + c.acc_tangent_impulse;
- A->apply_impulse( c.rA+A->get_center_of_mass(), -j_vec );
- B->apply_impulse( c.rB+B->get_center_of_mass(), j_vec );
- c.acc_bias_impulse=0;
+ A->apply_impulse(c.rA + A->get_center_of_mass(), -j_vec);
+ B->apply_impulse(c.rB + B->get_center_of_mass(), j_vec);
+ c.acc_bias_impulse = 0;
Vector3 jb_vec = c.normal * c.acc_bias_impulse;
- A->apply_bias_impulse( c.rA+A->get_center_of_mass(), -jb_vec );
- B->apply_bias_impulse( c.rB+B->get_center_of_mass(), jb_vec );
+ A->apply_bias_impulse(c.rA + A->get_center_of_mass(), -jb_vec);
+ B->apply_bias_impulse(c.rB + B->get_center_of_mass(), jb_vec);
- c.bounce = MAX(A->get_bounce(),B->get_bounce());
+ c.bounce = MAX(A->get_bounce(), B->get_bounce());
if (c.bounce) {
- Vector3 crA = A->get_angular_velocity().cross( c.rA );
- Vector3 crB = B->get_angular_velocity().cross( c.rB );
+ Vector3 crA = A->get_angular_velocity().cross(c.rA);
+ Vector3 crB = B->get_angular_velocity().cross(c.rB);
Vector3 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
//normal impule
c.bounce = c.bounce * dv.dot(c.normal);
}
-
-
}
return true;
@@ -392,68 +368,63 @@ void BodyPairSW::solve(real_t p_step) {
if (!collided)
return;
-
- for(int i=0;i<contact_count;i++) {
+ for (int i = 0; i < contact_count; i++) {
Contact &c = contacts[i];
if (!c.active)
continue;
- c.active=false; //try to deactivate, will activate itself if still needed
+ c.active = false; //try to deactivate, will activate itself if still needed
//bias impule
- Vector3 crbA = A->get_biased_angular_velocity().cross( c.rA );
- Vector3 crbB = B->get_biased_angular_velocity().cross( c.rB );
+ Vector3 crbA = A->get_biased_angular_velocity().cross(c.rA);
+ Vector3 crbB = B->get_biased_angular_velocity().cross(c.rB);
Vector3 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;
real_t vbn = dbv.dot(c.normal);
- if (Math::abs(-vbn+c.bias)>MIN_VELOCITY) {
+ if (Math::abs(-vbn + c.bias) > MIN_VELOCITY) {
- real_t jbn = (-vbn + c.bias)*c.mass_normal;
+ real_t jbn = (-vbn + c.bias) * c.mass_normal;
real_t jbnOld = c.acc_bias_impulse;
c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f);
Vector3 jb = c.normal * (c.acc_bias_impulse - jbnOld);
+ A->apply_bias_impulse(c.rA + A->get_center_of_mass(), -jb);
+ B->apply_bias_impulse(c.rB + B->get_center_of_mass(), jb);
- A->apply_bias_impulse(c.rA+A->get_center_of_mass(),-jb);
- B->apply_bias_impulse(c.rB+B->get_center_of_mass(), jb);
-
- c.active=true;
+ c.active = true;
}
-
- Vector3 crA = A->get_angular_velocity().cross( c.rA );
- Vector3 crB = B->get_angular_velocity().cross( c.rB );
+ Vector3 crA = A->get_angular_velocity().cross(c.rA);
+ Vector3 crB = B->get_angular_velocity().cross(c.rB);
Vector3 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
//normal impule
real_t vn = dv.dot(c.normal);
- if (Math::abs(vn)>MIN_VELOCITY) {
+ if (Math::abs(vn) > MIN_VELOCITY) {
- real_t jn = -(c.bounce + vn)*c.mass_normal;
+ real_t jn = -(c.bounce + vn) * c.mass_normal;
real_t jnOld = c.acc_normal_impulse;
c.acc_normal_impulse = MAX(jnOld + jn, 0.0f);
+ Vector3 j = c.normal * (c.acc_normal_impulse - jnOld);
- Vector3 j =c.normal * (c.acc_normal_impulse - jnOld);
-
-
- A->apply_impulse(c.rA+A->get_center_of_mass(),-j);
- B->apply_impulse(c.rB+B->get_center_of_mass(), j);
+ A->apply_impulse(c.rA + A->get_center_of_mass(), -j);
+ B->apply_impulse(c.rB + B->get_center_of_mass(), j);
- c.active=true;
+ c.active = true;
}
//friction impule
real_t friction = A->get_friction() * B->get_friction();
- Vector3 lvA = A->get_linear_velocity() + A->get_angular_velocity().cross( c.rA );
- Vector3 lvB = B->get_linear_velocity() + B->get_angular_velocity().cross( c.rB );
+ Vector3 lvA = A->get_linear_velocity() + A->get_angular_velocity().cross(c.rA);
+ Vector3 lvB = B->get_linear_velocity() + B->get_angular_velocity().cross(c.rB);
Vector3 dtv = lvB - lvA;
real_t tn = c.normal.dot(dtv);
@@ -466,15 +437,14 @@ void BodyPairSW::solve(real_t p_step) {
tv /= tvl;
- Vector3 temp1 = A->get_inv_inertia_tensor().xform( c.rA.cross( tv ) );
- Vector3 temp2 = B->get_inv_inertia_tensor().xform( c.rB.cross( tv ) );
+ Vector3 temp1 = A->get_inv_inertia_tensor().xform(c.rA.cross(tv));
+ Vector3 temp2 = B->get_inv_inertia_tensor().xform(c.rB.cross(tv));
real_t t = -tvl /
- (A->get_inv_mass() + B->get_inv_mass() + tv.dot(temp1.cross(c.rA) + temp2.cross(c.rB)));
+ (A->get_inv_mass() + B->get_inv_mass() + tv.dot(temp1.cross(c.rA) + temp2.cross(c.rB)));
Vector3 jt = t * tv;
-
Vector3 jtOld = c.acc_tangent_impulse;
c.acc_tangent_impulse += jt;
@@ -483,46 +453,35 @@ void BodyPairSW::solve(real_t p_step) {
if (fi_len > CMP_EPSILON && fi_len > jtMax) {
- c.acc_tangent_impulse*=jtMax / fi_len;
+ c.acc_tangent_impulse *= jtMax / fi_len;
}
jt = c.acc_tangent_impulse - jtOld;
+ A->apply_impulse(c.rA + A->get_center_of_mass(), -jt);
+ B->apply_impulse(c.rB + B->get_center_of_mass(), jt);
- A->apply_impulse( c.rA+A->get_center_of_mass(), -jt );
- B->apply_impulse( c.rB+B->get_center_of_mass(), jt );
-
- c.active=true;
-
+ c.active = true;
}
-
-
}
-
}
-
-
-
-
-BodyPairSW::BodyPairSW(BodySW *p_A, int p_shape_A,BodySW *p_B, int p_shape_B) : ConstraintSW(_arr,2) {
-
- A=p_A;
- B=p_B;
- shape_A=p_shape_A;
- shape_B=p_shape_B;
- space=A->get_space();
- A->add_constraint(this,0);
- B->add_constraint(this,1);
- contact_count=0;
- collided=false;
-
+BodyPairSW::BodyPairSW(BodySW *p_A, int p_shape_A, BodySW *p_B, int p_shape_B)
+ : ConstraintSW(_arr, 2) {
+
+ A = p_A;
+ B = p_B;
+ shape_A = p_shape_A;
+ shape_B = p_shape_B;
+ space = A->get_space();
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
+ contact_count = 0;
+ collided = false;
}
-
BodyPairSW::~BodyPairSW() {
A->remove_constraint(this);
B->remove_constraint(this);
-
}
diff --git a/servers/physics/body_pair_sw.h b/servers/physics/body_pair_sw.h
index f282a56b9e..fa426adafd 100644
--- a/servers/physics/body_pair_sw.h
+++ b/servers/physics/body_pair_sw.h
@@ -35,7 +35,7 @@
class BodyPairSW : public ConstraintSW {
enum {
- MAX_CONTACTS=4
+ MAX_CONTACTS = 4
};
union {
@@ -50,22 +50,21 @@ class BodyPairSW : public ConstraintSW {
int shape_A;
int shape_B;
-
struct Contact {
Vector3 position;
Vector3 normal;
Vector3 local_A, local_B;
- real_t acc_normal_impulse; // accumulated normal impulse (Pn)
- Vector3 acc_tangent_impulse; // accumulated tangent impulse (Pt)
- real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb)
+ real_t acc_normal_impulse; // accumulated normal impulse (Pn)
+ Vector3 acc_tangent_impulse; // accumulated tangent impulse (Pt)
+ real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb)
real_t mass_normal;
real_t bias;
real_t bounce;
real_t depth;
bool active;
- Vector3 rA,rB; // Offset in world orientation with respect to center of mass
+ Vector3 rA, rB; // Offset in world orientation with respect to center of mass
};
Vector3 offset_B; //use local A coordinates to avoid numerical issues on collision detection
@@ -76,24 +75,21 @@ class BodyPairSW : public ConstraintSW {
bool collided;
int cc;
+ static void _contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata);
- static void _contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata);
-
- void contact_added_callback(const Vector3& p_point_A,const Vector3& p_point_B);
+ void contact_added_callback(const Vector3 &p_point_A, const Vector3 &p_point_B);
void validate_contacts();
- bool _test_ccd(real_t p_step,BodySW *p_A, int p_shape_A,const Transform& p_xform_A,BodySW *p_B, int p_shape_B,const Transform& p_xform_B);
+ bool _test_ccd(real_t p_step, BodySW *p_A, int p_shape_A, const Transform &p_xform_A, BodySW *p_B, int p_shape_B, const Transform &p_xform_B);
SpaceSW *space;
public:
-
bool setup(real_t p_step);
void solve(real_t p_step);
- BodyPairSW(BodySW *p_A, int p_shape_A,BodySW *p_B, int p_shape_B);
+ BodyPairSW(BodySW *p_A, int p_shape_A, BodySW *p_B, int p_shape_B);
~BodyPairSW();
-
};
#endif // BODY_PAIR__SW_H
diff --git a/servers/physics/body_sw.cpp b/servers/physics/body_sw.cpp
index 7fcd767268..a4fc694f67 100644
--- a/servers/physics/body_sw.cpp
+++ b/servers/physics/body_sw.cpp
@@ -27,18 +27,17 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "body_sw.h"
-#include "space_sw.h"
#include "area_sw.h"
+#include "space_sw.h"
void BodySW::_update_inertia() {
if (get_space() && !inertia_update_list.in_list())
get_space()->body_add_to_inertia_update_list(&inertia_update_list);
-
}
void BodySW::_update_transform_dependant() {
-
+
center_of_mass = get_transform().basis.xform(center_of_mass_local);
principal_inertia_axes = get_transform().basis * principal_inertia_axes_local;
@@ -47,30 +46,29 @@ void BodySW::_update_transform_dependant() {
Basis tbt = tb.transposed();
tb.scale(_inv_inertia);
_inv_inertia_tensor = tb * tbt;
-
}
void BodySW::update_inertias() {
//update shapes and motions
- switch(mode) {
+ switch (mode) {
case PhysicsServer::BODY_MODE_RIGID: {
//update tensor for all shapes, not the best way but should be somehow OK. (inspired from bullet)
- real_t total_area=0;
+ real_t total_area = 0;
- for (int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
- total_area+=get_shape_area(i);
+ total_area += get_shape_area(i);
}
// We have to recompute the center of mass
center_of_mass_local.zero();
- for (int i=0; i<get_shape_count(); i++) {
- real_t area=get_shape_area(i);
+ for (int i = 0; i < get_shape_count(); i++) {
+ real_t area = get_shape_area(i);
real_t mass = area * this->mass / total_area;
@@ -84,25 +82,23 @@ void BodySW::update_inertias() {
Basis inertia_tensor;
inertia_tensor.set_zero();
- for (int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
- const ShapeSW* shape=get_shape(i);
+ const ShapeSW *shape = get_shape(i);
- real_t area=get_shape_area(i);
+ real_t area = get_shape_area(i);
real_t mass = area * this->mass / total_area;
- Basis shape_inertia_tensor=shape->get_moment_of_inertia(mass).to_diagonal_matrix();
- Transform shape_transform=get_shape_transform(i);
+ Basis shape_inertia_tensor = shape->get_moment_of_inertia(mass).to_diagonal_matrix();
+ Transform shape_transform = get_shape_transform(i);
Basis shape_basis = shape_transform.basis.orthonormalized();
// NOTE: we don't take the scale of collision shapes into account when computing the inertia tensor!
shape_inertia_tensor = shape_basis * shape_inertia_tensor * shape_basis.transposed();
Vector3 shape_origin = shape_transform.origin - center_of_mass_local;
- inertia_tensor += shape_inertia_tensor + (Basis()*shape_origin.dot(shape_origin)-shape_origin.outer(shape_origin))*mass;
-
-
+ inertia_tensor += shape_inertia_tensor + (Basis() * shape_origin.dot(shape_origin) - shape_origin.outer(shape_origin)) * mass;
}
// Compute the principal axes of inertia
@@ -110,9 +106,9 @@ void BodySW::update_inertias() {
_inv_inertia = inertia_tensor.get_main_diagonal().inverse();
if (mass)
- _inv_mass=1.0/mass;
+ _inv_mass = 1.0 / mass;
else
- _inv_mass=0;
+ _inv_mass = 0;
} break;
@@ -120,42 +116,39 @@ void BodySW::update_inertias() {
case PhysicsServer::BODY_MODE_STATIC: {
_inv_inertia_tensor.set_zero();
- _inv_mass=0;
+ _inv_mass = 0;
} break;
case PhysicsServer::BODY_MODE_CHARACTER: {
_inv_inertia_tensor.set_zero();
- _inv_mass=1.0/mass;
+ _inv_mass = 1.0 / mass;
} break;
}
-
//_update_shapes();
_update_transform_dependant();
}
-
-
void BodySW::set_active(bool p_active) {
- if (active==p_active)
+ if (active == p_active)
return;
- active=p_active;
+ active = p_active;
if (!p_active) {
if (get_space())
get_space()->body_remove_from_active_list(&active_list);
} else {
- if (mode==PhysicsServer::BODY_MODE_STATIC)
+ if (mode == PhysicsServer::BODY_MODE_STATIC)
return; //static bodies can't become active
if (get_space())
get_space()->body_add_to_active_list(&active_list);
//still_time=0;
}
-/*
+ /*
if (!space)
return;
@@ -168,43 +161,41 @@ void BodySW::set_active(bool p_active) {
*/
}
-
-
void BodySW::set_param(PhysicsServer::BodyParameter p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::BODY_PARAM_BOUNCE: {
- bounce=p_value;
+ bounce = p_value;
} break;
case PhysicsServer::BODY_PARAM_FRICTION: {
- friction=p_value;
+ friction = p_value;
} break;
case PhysicsServer::BODY_PARAM_MASS: {
- ERR_FAIL_COND(p_value<=0);
- mass=p_value;
+ ERR_FAIL_COND(p_value <= 0);
+ mass = p_value;
_update_inertia();
} break;
case PhysicsServer::BODY_PARAM_GRAVITY_SCALE: {
- gravity_scale=p_value;
+ gravity_scale = p_value;
} break;
case PhysicsServer::BODY_PARAM_LINEAR_DAMP: {
- linear_damp=p_value;
+ linear_damp = p_value;
} break;
case PhysicsServer::BODY_PARAM_ANGULAR_DAMP: {
- angular_damp=p_value;
+ angular_damp = p_value;
} break;
- default:{}
+ default: {}
}
}
real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::BODY_PARAM_BOUNCE: {
return bounce;
@@ -228,7 +219,7 @@ real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const {
return angular_damp;
} break;
- default:{}
+ default: {}
}
return 0;
@@ -236,35 +227,35 @@ real_t BodySW::get_param(PhysicsServer::BodyParameter p_param) const {
void BodySW::set_mode(PhysicsServer::BodyMode p_mode) {
- PhysicsServer::BodyMode prev=mode;
- mode=p_mode;
+ PhysicsServer::BodyMode prev = mode;
+ mode = p_mode;
- switch(p_mode) {
+ switch (p_mode) {
//CLEAR UP EVERYTHING IN CASE IT NOT WORKS!
case PhysicsServer::BODY_MODE_STATIC:
case PhysicsServer::BODY_MODE_KINEMATIC: {
_set_inv_transform(get_transform().affine_inverse());
- _inv_mass=0;
- _set_static(p_mode==PhysicsServer::BODY_MODE_STATIC);
+ _inv_mass = 0;
+ _set_static(p_mode == PhysicsServer::BODY_MODE_STATIC);
//set_active(p_mode==PhysicsServer::BODY_MODE_KINEMATIC);
- set_active(p_mode==PhysicsServer::BODY_MODE_KINEMATIC && contacts.size());
- linear_velocity=Vector3();
- angular_velocity=Vector3();
- if (mode==PhysicsServer::BODY_MODE_KINEMATIC && prev!=mode) {
- first_time_kinematic=true;
+ set_active(p_mode == PhysicsServer::BODY_MODE_KINEMATIC && contacts.size());
+ linear_velocity = Vector3();
+ angular_velocity = Vector3();
+ if (mode == PhysicsServer::BODY_MODE_KINEMATIC && prev != mode) {
+ first_time_kinematic = true;
}
} break;
case PhysicsServer::BODY_MODE_RIGID: {
- _inv_mass=mass>0?(1.0/mass):0;
+ _inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
case PhysicsServer::BODY_MODE_CHARACTER: {
- _inv_mass=mass>0?(1.0/mass):0;
+ _inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
}
@@ -274,7 +265,6 @@ void BodySW::set_mode(PhysicsServer::BodyMode p_mode) {
if (get_space())
_update_queries();
*/
-
}
PhysicsServer::BodyMode BodySW::get_mode() const {
@@ -286,35 +276,33 @@ void BodySW::_shapes_changed() {
_update_inertia();
}
-void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_variant) {
+void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant &p_variant) {
- switch(p_state) {
+ switch (p_state) {
case PhysicsServer::BODY_STATE_TRANSFORM: {
-
- if (mode==PhysicsServer::BODY_MODE_KINEMATIC) {
- new_transform=p_variant;
+ if (mode == PhysicsServer::BODY_MODE_KINEMATIC) {
+ new_transform = p_variant;
//wakeup_neighbours();
set_active(true);
if (first_time_kinematic) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
- first_time_kinematic=false;
+ first_time_kinematic = false;
}
- } else if (mode==PhysicsServer::BODY_MODE_STATIC) {
+ } else if (mode == PhysicsServer::BODY_MODE_STATIC) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
wakeup_neighbours();
} else {
Transform t = p_variant;
t.orthonormalize();
- new_transform=get_transform(); //used as old to compute motion
- if (new_transform==t)
+ new_transform = get_transform(); //used as old to compute motion
+ if (new_transform == t)
break;
_set_transform(t);
_set_inv_transform(get_transform().inverse());
-
}
wakeup();
@@ -325,7 +313,7 @@ void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_varian
if (mode==PhysicsServer::BODY_MODE_STATIC)
break;
*/
- linear_velocity=p_variant;
+ linear_velocity = p_variant;
wakeup();
} break;
case PhysicsServer::BODY_STATE_ANGULAR_VELOCITY: {
@@ -333,38 +321,37 @@ void BodySW::set_state(PhysicsServer::BodyState p_state, const Variant& p_varian
if (mode!=PhysicsServer::BODY_MODE_RIGID)
break;
*/
- angular_velocity=p_variant;
+ angular_velocity = p_variant;
wakeup();
} break;
case PhysicsServer::BODY_STATE_SLEEPING: {
//?
- if (mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC)
+ if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC)
break;
- bool do_sleep=p_variant;
+ bool do_sleep = p_variant;
if (do_sleep) {
- linear_velocity=Vector3();
+ linear_velocity = Vector3();
//biased_linear_velocity=Vector3();
- angular_velocity=Vector3();
+ angular_velocity = Vector3();
//biased_angular_velocity=Vector3();
set_active(false);
} else {
- if (mode!=PhysicsServer::BODY_MODE_STATIC)
+ if (mode != PhysicsServer::BODY_MODE_STATIC)
set_active(true);
}
} break;
case PhysicsServer::BODY_STATE_CAN_SLEEP: {
- can_sleep=p_variant;
- if (mode==PhysicsServer::BODY_MODE_RIGID && !active && !can_sleep)
+ can_sleep = p_variant;
+ if (mode == PhysicsServer::BODY_MODE_RIGID && !active && !can_sleep)
set_active(true);
} break;
}
-
}
Variant BodySW::get_state(PhysicsServer::BodyState p_state) const {
- switch(p_state) {
+ switch (p_state) {
case PhysicsServer::BODY_STATE_TRANSFORM: {
return get_transform();
} break;
@@ -385,8 +372,7 @@ Variant BodySW::get_state(PhysicsServer::BodyState p_state) const {
return Variant();
}
-
-void BodySW::set_space(SpaceSW *p_space){
+void BodySW::set_space(SpaceSW *p_space) {
if (get_space()) {
@@ -396,7 +382,6 @@ void BodySW::set_space(SpaceSW *p_space){
get_space()->body_remove_from_active_list(&active_list);
if (direct_state_query_list.in_list())
get_space()->body_remove_from_state_query_list(&direct_state_query_list);
-
}
_set_space(p_space);
@@ -413,19 +398,17 @@ void BodySW::set_space(SpaceSW *p_space){
set_active(true);
}
*/
-
}
- first_integration=true;
-
+ first_integration = true;
}
void BodySW::_compute_area_gravity_and_dampenings(const AreaSW *p_area) {
if (p_area->is_gravity_point()) {
- if(p_area->get_gravity_distance_scale() > 0) {
+ if (p_area->get_gravity_distance_scale() > 0) {
Vector3 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin();
- gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale()+1, 2) );
+ gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale() + 1, 2));
} else {
gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity();
}
@@ -439,8 +422,7 @@ void BodySW::_compute_area_gravity_and_dampenings(const AreaSW *p_area) {
void BodySW::integrate_forces(real_t p_step) {
-
- if (mode==PhysicsServer::BODY_MODE_STATIC)
+ if (mode == PhysicsServer::BODY_MODE_STATIC)
return;
AreaSW *def_area = get_space()->get_default_area();
@@ -450,192 +432,179 @@ void BodySW::integrate_forces(real_t p_step) {
int ac = areas.size();
bool stopped = false;
- gravity = Vector3(0,0,0);
+ gravity = Vector3(0, 0, 0);
area_linear_damp = 0;
area_angular_damp = 0;
if (ac) {
areas.sort();
const AreaCMP *aa = &areas[0];
// damp_area = aa[ac-1].area;
- for(int i=ac-1;i>=0 && !stopped;i--) {
- PhysicsServer::AreaSpaceOverrideMode mode=aa[i].area->get_space_override_mode();
+ for (int i = ac - 1; i >= 0 && !stopped; i--) {
+ PhysicsServer::AreaSpaceOverrideMode mode = aa[i].area->get_space_override_mode();
switch (mode) {
case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE:
case PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: {
_compute_area_gravity_and_dampenings(aa[i].area);
- stopped = mode==PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
+ stopped = mode == PhysicsServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
} break;
case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE:
case PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: {
- gravity = Vector3(0,0,0);
+ gravity = Vector3(0, 0, 0);
area_angular_damp = 0;
area_linear_damp = 0;
_compute_area_gravity_and_dampenings(aa[i].area);
- stopped = mode==PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE;
+ stopped = mode == PhysicsServer::AREA_SPACE_OVERRIDE_REPLACE;
} break;
default: {}
}
}
}
- if( !stopped ) {
+ if (!stopped) {
_compute_area_gravity_and_dampenings(def_area);
}
- gravity*=gravity_scale;
+ gravity *= gravity_scale;
// If less than 0, override dampenings with that of the Body
- if (angular_damp>=0)
- area_angular_damp=angular_damp;
+ if (angular_damp >= 0)
+ area_angular_damp = angular_damp;
/*
else
area_angular_damp=damp_area->get_angular_damp();
*/
- if (linear_damp>=0)
- area_linear_damp=linear_damp;
+ if (linear_damp >= 0)
+ area_linear_damp = linear_damp;
/*
else
area_linear_damp=damp_area->get_linear_damp();
*/
-
Vector3 motion;
- bool do_motion=false;
+ bool do_motion = false;
- if (mode==PhysicsServer::BODY_MODE_KINEMATIC) {
+ if (mode == PhysicsServer::BODY_MODE_KINEMATIC) {
//compute motion, angular and etc. velocities from prev transform
- linear_velocity = (new_transform.origin - get_transform().origin)/p_step;
+ linear_velocity = (new_transform.origin - get_transform().origin) / p_step;
//compute a FAKE angular velocity, not so easy
- Basis rot=new_transform.basis.orthonormalized().transposed() * get_transform().basis.orthonormalized();
+ Basis rot = new_transform.basis.orthonormalized().transposed() * get_transform().basis.orthonormalized();
Vector3 axis;
real_t angle;
- rot.get_axis_and_angle(axis,angle);
+ rot.get_axis_and_angle(axis, angle);
axis.normalize();
- angular_velocity=axis.normalized() * (angle/p_step);
+ angular_velocity = axis.normalized() * (angle / p_step);
motion = new_transform.origin - get_transform().origin;
- do_motion=true;
+ do_motion = true;
} else {
if (!omit_force_integration && !first_integration) {
//overriden by direct state query
- Vector3 force=gravity*mass;
- force+=applied_force;
- Vector3 torque=applied_torque;
+ Vector3 force = gravity * mass;
+ force += applied_force;
+ Vector3 torque = applied_torque;
real_t damp = 1.0 - p_step * area_linear_damp;
- if (damp<0) // reached zero in the given time
- damp=0;
+ if (damp < 0) // reached zero in the given time
+ damp = 0;
real_t angular_damp = 1.0 - p_step * area_angular_damp;
- if (angular_damp<0) // reached zero in the given time
- angular_damp=0;
+ if (angular_damp < 0) // reached zero in the given time
+ angular_damp = 0;
- linear_velocity*=damp;
- angular_velocity*=angular_damp;
+ linear_velocity *= damp;
+ angular_velocity *= angular_damp;
- linear_velocity+=_inv_mass * force * p_step;
- angular_velocity+=_inv_inertia_tensor.xform(torque)*p_step;
+ linear_velocity += _inv_mass * force * p_step;
+ angular_velocity += _inv_inertia_tensor.xform(torque) * p_step;
}
if (continuous_cd) {
- motion=linear_velocity*p_step;
- do_motion=true;
+ motion = linear_velocity * p_step;
+ do_motion = true;
}
-
}
- applied_force=Vector3();
- applied_torque=Vector3();
- first_integration=false;
+ applied_force = Vector3();
+ applied_torque = Vector3();
+ first_integration = false;
//motion=linear_velocity*p_step;
- biased_angular_velocity=Vector3();
- biased_linear_velocity=Vector3();
-
+ biased_angular_velocity = Vector3();
+ biased_linear_velocity = Vector3();
- if (do_motion) {//shapes temporarily extend for raycast
+ if (do_motion) { //shapes temporarily extend for raycast
_update_shapes_with_motion(motion);
}
-
- def_area=NULL; // clear the area, so it is set in the next frame
- contact_count=0;
-
+ def_area = NULL; // clear the area, so it is set in the next frame
+ contact_count = 0;
}
void BodySW::integrate_velocities(real_t p_step) {
- if (mode==PhysicsServer::BODY_MODE_STATIC)
+ if (mode == PhysicsServer::BODY_MODE_STATIC)
return;
if (fi_callback)
get_space()->body_add_to_state_query_list(&direct_state_query_list);
- if (mode==PhysicsServer::BODY_MODE_KINEMATIC) {
+ if (mode == PhysicsServer::BODY_MODE_KINEMATIC) {
- _set_transform(new_transform,false);
+ _set_transform(new_transform, false);
_set_inv_transform(new_transform.affine_inverse());
- if (contacts.size()==0 && linear_velocity==Vector3() && angular_velocity==Vector3())
+ if (contacts.size() == 0 && linear_velocity == Vector3() && angular_velocity == Vector3())
set_active(false); //stopped moving, deactivate
return;
}
-
-
//apply axis lock
- if (axis_lock!=PhysicsServer::BODY_AXIS_LOCK_DISABLED) {
+ if (axis_lock != PhysicsServer::BODY_AXIS_LOCK_DISABLED) {
-
- int axis=axis_lock-1;
- for(int i=0;i<3;i++) {
- if (i==axis) {
- linear_velocity[i]=0;
- biased_linear_velocity[i]=0;
+ int axis = axis_lock - 1;
+ for (int i = 0; i < 3; i++) {
+ if (i == axis) {
+ linear_velocity[i] = 0;
+ biased_linear_velocity[i] = 0;
} else {
- angular_velocity[i]=0;
- biased_angular_velocity[i]=0;
+ angular_velocity[i] = 0;
+ biased_angular_velocity[i] = 0;
}
}
-
}
-
- Vector3 total_angular_velocity = angular_velocity+biased_angular_velocity;
-
-
+ Vector3 total_angular_velocity = angular_velocity + biased_angular_velocity;
real_t ang_vel = total_angular_velocity.length();
Transform transform = get_transform();
-
- if (ang_vel!=0.0) {
+ if (ang_vel != 0.0) {
Vector3 ang_vel_axis = total_angular_velocity / ang_vel;
- Basis rot( ang_vel_axis, ang_vel*p_step );
+ Basis rot(ang_vel_axis, ang_vel * p_step);
Basis identity3(1, 0, 0, 0, 1, 0, 0, 0, 1);
transform.origin += ((identity3 - rot) * transform.basis).xform(center_of_mass_local);
transform.basis = rot * transform.basis;
transform.orthonormalize();
}
- Vector3 total_linear_velocity=linear_velocity+biased_linear_velocity;
+ Vector3 total_linear_velocity = linear_velocity + biased_linear_velocity;
/*for(int i=0;i<3;i++) {
if (axis_lock&(1<<i)) {
transform.origin[i]=0.0;
}
}*/
- transform.origin+=total_linear_velocity * p_step;
+ transform.origin += total_linear_velocity * p_step;
_set_transform(transform);
_set_inv_transform(get_transform().inverse());
@@ -684,18 +653,18 @@ void BodySW::simulate_motion(const Transform& p_xform,real_t p_step) {
void BodySW::wakeup_neighbours() {
- for(Map<ConstraintSW*,int>::Element *E=constraint_map.front();E;E=E->next()) {
+ for (Map<ConstraintSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) {
- const ConstraintSW *c=E->key();
+ const ConstraintSW *c = E->key();
BodySW **n = c->get_body_ptr();
- int bc=c->get_body_count();
+ int bc = c->get_body_count();
- for(int i=0;i<bc;i++) {
+ for (int i = 0; i < bc; i++) {
- if (i==E->get())
+ if (i == E->get())
continue;
BodySW *b = n[i];
- if (b->mode!=PhysicsServer::BODY_MODE_RIGID)
+ if (b->mode != PhysicsServer::BODY_MODE_RIGID)
continue;
if (!b->is_active())
@@ -706,109 +675,96 @@ void BodySW::wakeup_neighbours() {
void BodySW::call_queries() {
-
if (fi_callback) {
PhysicsDirectBodyStateSW *dbs = PhysicsDirectBodyStateSW::singleton;
- dbs->body=this;
+ dbs->body = this;
- Variant v=dbs;
+ Variant v = dbs;
Object *obj = ObjectDB::get_instance(fi_callback->id);
if (!obj) {
- set_force_integration_callback(0,StringName());
+ set_force_integration_callback(0, StringName());
} else {
- const Variant *vp[2]={&v,&fi_callback->udata};
+ const Variant *vp[2] = { &v, &fi_callback->udata };
Variant::CallError ce;
- int argc=(fi_callback->udata.get_type()==Variant::NIL)?1:2;
- obj->call(fi_callback->method,vp,argc,ce);
+ int argc = (fi_callback->udata.get_type() == Variant::NIL) ? 1 : 2;
+ obj->call(fi_callback->method, vp, argc, ce);
}
-
-
}
-
-
}
+bool BodySW::sleep_test(real_t p_step) {
-bool BodySW::sleep_test(real_t p_step) {
-
- if (mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC)
+ if (mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC)
return true; //
- else if (mode==PhysicsServer::BODY_MODE_CHARACTER)
+ else if (mode == PhysicsServer::BODY_MODE_CHARACTER)
return !active; // characters don't sleep unless asked to sleep
else if (!can_sleep)
return false;
+ if (Math::abs(angular_velocity.length()) < get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold() * get_space()->get_body_linear_velocity_sleep_treshold()) {
-
-
- if (Math::abs(angular_velocity.length())<get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold()*get_space()->get_body_linear_velocity_sleep_treshold()) {
-
- still_time+=p_step;
+ still_time += p_step;
return still_time > get_space()->get_body_time_to_sleep();
} else {
- still_time=0; //maybe this should be set to 0 on set_active?
+ still_time = 0; //maybe this should be set to 0 on set_active?
return false;
}
}
-
-void BodySW::set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata) {
+void BodySW::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
if (fi_callback) {
memdelete(fi_callback);
- fi_callback=NULL;
+ fi_callback = NULL;
}
+ if (p_id != 0) {
- if (p_id!=0) {
-
- fi_callback=memnew(ForceIntegrationCallback);
- fi_callback->id=p_id;
- fi_callback->method=p_method;
- fi_callback->udata=p_udata;
+ fi_callback = memnew(ForceIntegrationCallback);
+ fi_callback->id = p_id;
+ fi_callback->method = p_method;
+ fi_callback->udata = p_udata;
}
-
}
-BodySW::BodySW() : CollisionObjectSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) {
-
+BodySW::BodySW()
+ : CollisionObjectSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) {
- mode=PhysicsServer::BODY_MODE_RIGID;
- active=true;
+ mode = PhysicsServer::BODY_MODE_RIGID;
+ active = true;
- mass=1;
+ mass = 1;
//_inv_inertia=Transform();
- _inv_mass=1;
- bounce=0;
- friction=1;
- omit_force_integration=false;
+ _inv_mass = 1;
+ bounce = 0;
+ friction = 1;
+ omit_force_integration = false;
//applied_torque=0;
- island_step=0;
- island_next=NULL;
- island_list_next=NULL;
- first_time_kinematic=false;
- first_integration=false;
+ island_step = 0;
+ island_next = NULL;
+ island_list_next = NULL;
+ first_time_kinematic = false;
+ first_integration = false;
_set_static(false);
- contact_count=0;
- gravity_scale=1.0;
+ contact_count = 0;
+ gravity_scale = 1.0;
- area_angular_damp=0;
- area_linear_damp=0;
-
- still_time=0;
- continuous_cd=false;
- can_sleep=false;
- fi_callback=NULL;
- axis_lock=PhysicsServer::BODY_AXIS_LOCK_DISABLED;
+ area_angular_damp = 0;
+ area_linear_damp = 0;
+ still_time = 0;
+ continuous_cd = false;
+ can_sleep = false;
+ fi_callback = NULL;
+ axis_lock = PhysicsServer::BODY_AXIS_LOCK_DISABLED;
}
BodySW::~BodySW() {
@@ -817,9 +773,9 @@ BodySW::~BodySW() {
memdelete(fi_callback);
}
-PhysicsDirectBodyStateSW *PhysicsDirectBodyStateSW::singleton=NULL;
+PhysicsDirectBodyStateSW *PhysicsDirectBodyStateSW::singleton = NULL;
-PhysicsDirectSpaceState* PhysicsDirectBodyStateSW::get_space_state() {
+PhysicsDirectSpaceState *PhysicsDirectBodyStateSW::get_space_state() {
return body->get_space()->get_direct_state();
}
diff --git a/servers/physics/body_sw.h b/servers/physics/body_sw.h
index 2383d2d688..4b1af6fca5 100644
--- a/servers/physics/body_sw.h
+++ b/servers/physics/body_sw.h
@@ -29,16 +29,14 @@
#ifndef BODY_SW_H
#define BODY_SW_H
+#include "area_sw.h"
#include "collision_object_sw.h"
#include "vset.h"
-#include "area_sw.h"
class ConstraintSW;
-
class BodySW : public CollisionObjectSW {
-
PhysicsServer::BodyMode mode;
Vector3 linear_velocity;
@@ -78,7 +76,6 @@ class BodySW : public CollisionObjectSW {
real_t area_angular_damp;
real_t area_linear_damp;
-
SelfList<BodySW> active_list;
SelfList<BodySW> inertia_update_list;
SelfList<BodySW> direct_state_query_list;
@@ -96,23 +93,25 @@ class BodySW : public CollisionObjectSW {
virtual void _shapes_changed();
Transform new_transform;
- Map<ConstraintSW*,int> constraint_map;
+ Map<ConstraintSW *, int> constraint_map;
struct AreaCMP {
AreaSW *area;
int refCount;
- _FORCE_INLINE_ bool operator==(const AreaCMP& p_cmp) const { return area->get_self() == p_cmp.area->get_self();}
- _FORCE_INLINE_ bool operator<(const AreaCMP& p_cmp) const { return area->get_priority() < p_cmp.area->get_priority();}
+ _FORCE_INLINE_ bool operator==(const AreaCMP &p_cmp) const { return area->get_self() == p_cmp.area->get_self(); }
+ _FORCE_INLINE_ bool operator<(const AreaCMP &p_cmp) const { return area->get_priority() < p_cmp.area->get_priority(); }
_FORCE_INLINE_ AreaCMP() {}
- _FORCE_INLINE_ AreaCMP(AreaSW *p_area) { area=p_area; refCount=1;}
+ _FORCE_INLINE_ AreaCMP(AreaSW *p_area) {
+ area = p_area;
+ refCount = 1;
+ }
};
Vector<AreaCMP> areas;
struct Contact {
-
Vector3 local_pos;
Vector3 local_normal;
real_t depth;
@@ -136,7 +135,6 @@ class BodySW : public CollisionObjectSW {
ForceIntegrationCallback *fi_callback;
-
uint64_t island_step;
BodySW *island_next;
BodySW *island_list_next;
@@ -145,16 +143,14 @@ class BodySW : public CollisionObjectSW {
_FORCE_INLINE_ void _update_transform_dependant();
-friend class PhysicsDirectBodyStateSW; // i give up, too many functions to expose
+ friend class PhysicsDirectBodyStateSW; // i give up, too many functions to expose
public:
-
-
- void set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata=Variant());
+ void set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata = Variant());
_FORCE_INLINE_ void add_area(AreaSW *p_area) {
int index = areas.find(AreaCMP(p_area));
- if( index > -1 ) {
+ if (index > -1) {
areas[index].refCount += 1;
} else {
areas.ordered_insert(AreaCMP(p_area));
@@ -163,77 +159,80 @@ public:
_FORCE_INLINE_ void remove_area(AreaSW *p_area) {
int index = areas.find(AreaCMP(p_area));
- if( index > -1 ) {
+ if (index > -1) {
areas[index].refCount -= 1;
- if( areas[index].refCount < 1 )
+ if (areas[index].refCount < 1)
areas.remove(index);
}
}
- _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { contacts.resize(p_size); contact_count=0; if (mode==PhysicsServer::BODY_MODE_KINEMATIC && p_size) set_active(true);}
+ _FORCE_INLINE_ void set_max_contacts_reported(int p_size) {
+ contacts.resize(p_size);
+ contact_count = 0;
+ if (mode == PhysicsServer::BODY_MODE_KINEMATIC && p_size) set_active(true);
+ }
_FORCE_INLINE_ int get_max_contacts_reported() const { return contacts.size(); }
_FORCE_INLINE_ bool can_report_contacts() const { return !contacts.empty(); }
- _FORCE_INLINE_ void add_contact(const Vector3& p_local_pos,const Vector3& p_local_normal, real_t p_depth, int p_local_shape, const Vector3& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector3& p_collider_velocity_at_pos);
-
+ _FORCE_INLINE_ void add_contact(const Vector3 &p_local_pos, const Vector3 &p_local_normal, real_t p_depth, int p_local_shape, const Vector3 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector3 &p_collider_velocity_at_pos);
- _FORCE_INLINE_ void add_exception(const RID& p_exception) { exceptions.insert(p_exception);}
- _FORCE_INLINE_ void remove_exception(const RID& p_exception) { exceptions.erase(p_exception);}
- _FORCE_INLINE_ bool has_exception(const RID& p_exception) const { return exceptions.has(p_exception);}
- _FORCE_INLINE_ const VSet<RID>& get_exceptions() const { return exceptions;}
+ _FORCE_INLINE_ void add_exception(const RID &p_exception) { exceptions.insert(p_exception); }
+ _FORCE_INLINE_ void remove_exception(const RID &p_exception) { exceptions.erase(p_exception); }
+ _FORCE_INLINE_ bool has_exception(const RID &p_exception) const { return exceptions.has(p_exception); }
+ _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; }
_FORCE_INLINE_ uint64_t get_island_step() const { return island_step; }
- _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; }
+ _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; }
- _FORCE_INLINE_ BodySW* get_island_next() const { return island_next; }
- _FORCE_INLINE_ void set_island_next(BodySW* p_next) { island_next=p_next; }
+ _FORCE_INLINE_ BodySW *get_island_next() const { return island_next; }
+ _FORCE_INLINE_ void set_island_next(BodySW *p_next) { island_next = p_next; }
- _FORCE_INLINE_ BodySW* get_island_list_next() const { return island_list_next; }
- _FORCE_INLINE_ void set_island_list_next(BodySW* p_next) { island_list_next=p_next; }
+ _FORCE_INLINE_ BodySW *get_island_list_next() const { return island_list_next; }
+ _FORCE_INLINE_ void set_island_list_next(BodySW *p_next) { island_list_next = p_next; }
- _FORCE_INLINE_ void add_constraint(ConstraintSW* p_constraint, int p_pos) { constraint_map[p_constraint]=p_pos; }
- _FORCE_INLINE_ void remove_constraint(ConstraintSW* p_constraint) { constraint_map.erase(p_constraint); }
- const Map<ConstraintSW*,int>& get_constraint_map() const { return constraint_map; }
+ _FORCE_INLINE_ void add_constraint(ConstraintSW *p_constraint, int p_pos) { constraint_map[p_constraint] = p_pos; }
+ _FORCE_INLINE_ void remove_constraint(ConstraintSW *p_constraint) { constraint_map.erase(p_constraint); }
+ const Map<ConstraintSW *, int> &get_constraint_map() const { return constraint_map; }
- _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration=p_omit_force_integration; }
+ _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration = p_omit_force_integration; }
_FORCE_INLINE_ bool get_omit_force_integration() const { return omit_force_integration; }
_FORCE_INLINE_ Basis get_principal_inertia_axes() const { return principal_inertia_axes; }
_FORCE_INLINE_ Vector3 get_center_of_mass() const { return center_of_mass; }
- _FORCE_INLINE_ Vector3 xform_local_to_principal(const Vector3& p_pos) const { return principal_inertia_axes_local.xform(p_pos - center_of_mass_local); }
+ _FORCE_INLINE_ Vector3 xform_local_to_principal(const Vector3 &p_pos) const { return principal_inertia_axes_local.xform(p_pos - center_of_mass_local); }
- _FORCE_INLINE_ void set_linear_velocity(const Vector3& p_velocity) {linear_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_linear_velocity(const Vector3 &p_velocity) { linear_velocity = p_velocity; }
_FORCE_INLINE_ Vector3 get_linear_velocity() const { return linear_velocity; }
- _FORCE_INLINE_ void set_angular_velocity(const Vector3& p_velocity) { angular_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_angular_velocity(const Vector3 &p_velocity) { angular_velocity = p_velocity; }
_FORCE_INLINE_ Vector3 get_angular_velocity() const { return angular_velocity; }
- _FORCE_INLINE_ const Vector3& get_biased_linear_velocity() const { return biased_linear_velocity; }
- _FORCE_INLINE_ const Vector3& get_biased_angular_velocity() const { return biased_angular_velocity; }
+ _FORCE_INLINE_ const Vector3 &get_biased_linear_velocity() const { return biased_linear_velocity; }
+ _FORCE_INLINE_ const Vector3 &get_biased_angular_velocity() const { return biased_angular_velocity; }
- _FORCE_INLINE_ void apply_impulse(const Vector3& p_pos, const Vector3& p_j) {
+ _FORCE_INLINE_ void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) {
linear_velocity += p_j * _inv_mass;
- angular_velocity += _inv_inertia_tensor.xform( (p_pos-center_of_mass).cross(p_j) );
+ angular_velocity += _inv_inertia_tensor.xform((p_pos - center_of_mass).cross(p_j));
}
- _FORCE_INLINE_ void apply_torque_impulse(const Vector3& p_j) {
+ _FORCE_INLINE_ void apply_torque_impulse(const Vector3 &p_j) {
angular_velocity += _inv_inertia_tensor.xform(p_j);
}
- _FORCE_INLINE_ void apply_bias_impulse(const Vector3& p_pos, const Vector3& p_j) {
+ _FORCE_INLINE_ void apply_bias_impulse(const Vector3 &p_pos, const Vector3 &p_j) {
biased_linear_velocity += p_j * _inv_mass;
- biased_angular_velocity += _inv_inertia_tensor.xform( (p_pos-center_of_mass).cross(p_j) );
+ biased_angular_velocity += _inv_inertia_tensor.xform((p_pos - center_of_mass).cross(p_j));
}
- _FORCE_INLINE_ void apply_bias_torque_impulse(const Vector3& p_j) {
+ _FORCE_INLINE_ void apply_bias_torque_impulse(const Vector3 &p_j) {
biased_angular_velocity += _inv_inertia_tensor.xform(p_j);
}
- _FORCE_INLINE_ void add_force(const Vector3& p_force, const Vector3& p_pos) {
+ _FORCE_INLINE_ void add_force(const Vector3 &p_force, const Vector3 &p_pos) {
applied_force += p_force;
applied_torque += p_pos.cross(p_force);
@@ -243,7 +242,7 @@ public:
_FORCE_INLINE_ bool is_active() const { return active; }
_FORCE_INLINE_ void wakeup() {
- if ((!get_space()) || mode==PhysicsServer::BODY_MODE_STATIC || mode==PhysicsServer::BODY_MODE_KINEMATIC)
+ if ((!get_space()) || mode == PhysicsServer::BODY_MODE_STATIC || mode == PhysicsServer::BODY_MODE_KINEMATIC)
return;
set_active(true);
}
@@ -254,16 +253,16 @@ public:
void set_mode(PhysicsServer::BodyMode p_mode);
PhysicsServer::BodyMode get_mode() const;
- void set_state(PhysicsServer::BodyState p_state, const Variant& p_variant);
+ void set_state(PhysicsServer::BodyState p_state, const Variant &p_variant);
Variant get_state(PhysicsServer::BodyState p_state) const;
- void set_applied_force(const Vector3& p_force) { applied_force=p_force; }
+ void set_applied_force(const Vector3 &p_force) { applied_force = p_force; }
Vector3 get_applied_force() const { return applied_force; }
- void set_applied_torque(const Vector3& p_torque) { applied_torque=p_torque; }
+ void set_applied_torque(const Vector3 &p_torque) { applied_torque = p_torque; }
Vector3 get_applied_torque() const { return applied_torque; }
- _FORCE_INLINE_ void set_continuous_collision_detection(bool p_enable) { continuous_cd=p_enable; }
+ _FORCE_INLINE_ void set_continuous_collision_detection(bool p_enable) { continuous_cd = p_enable; }
_FORCE_INLINE_ bool is_continuous_collision_detection_enabled() const { return continuous_cd; }
void set_space(SpaceSW *p_space);
@@ -277,33 +276,32 @@ public:
_FORCE_INLINE_ Vector3 get_gravity() const { return gravity; }
_FORCE_INLINE_ real_t get_bounce() const { return bounce; }
- _FORCE_INLINE_ void set_axis_lock(PhysicsServer::BodyAxisLock p_lock) { axis_lock=p_lock; }
+ _FORCE_INLINE_ void set_axis_lock(PhysicsServer::BodyAxisLock p_lock) { axis_lock = p_lock; }
_FORCE_INLINE_ PhysicsServer::BodyAxisLock get_axis_lock() const { return axis_lock; }
void integrate_forces(real_t p_step);
void integrate_velocities(real_t p_step);
- _FORCE_INLINE_ Vector3 get_velocity_in_local_point(const Vector3& rel_pos) const {
+ _FORCE_INLINE_ Vector3 get_velocity_in_local_point(const Vector3 &rel_pos) const {
- return linear_velocity + angular_velocity.cross(rel_pos-center_of_mass);
+ return linear_velocity + angular_velocity.cross(rel_pos - center_of_mass);
}
- _FORCE_INLINE_ real_t compute_impulse_denominator(const Vector3& p_pos, const Vector3& p_normal) const {
+ _FORCE_INLINE_ real_t compute_impulse_denominator(const Vector3 &p_pos, const Vector3 &p_normal) const {
- Vector3 r0 = p_pos - get_transform().origin - center_of_mass;
+ Vector3 r0 = p_pos - get_transform().origin - center_of_mass;
- Vector3 c0 = (r0).cross(p_normal);
+ Vector3 c0 = (r0).cross(p_normal);
- Vector3 vec = (_inv_inertia_tensor.xform_inv(c0)).cross(r0);
+ Vector3 vec = (_inv_inertia_tensor.xform_inv(c0)).cross(r0);
- return _inv_mass + p_normal.dot(vec);
-
- }
+ return _inv_mass + p_normal.dot(vec);
+ }
- _FORCE_INLINE_ real_t compute_angular_impulse_denominator(const Vector3& p_axis) const {
+ _FORCE_INLINE_ real_t compute_angular_impulse_denominator(const Vector3 &p_axis) const {
- return p_axis.dot( _inv_inertia_tensor.xform_inv(p_axis) );
- }
+ return p_axis.dot(_inv_inertia_tensor.xform_inv(p_axis));
+ }
//void simulate_motion(const Transform& p_xform,real_t p_step);
void call_queries();
@@ -313,117 +311,133 @@ public:
BodySW();
~BodySW();
-
};
-
//add contact inline
-void BodySW::add_contact(const Vector3& p_local_pos,const Vector3& p_local_normal, real_t p_depth, int p_local_shape, const Vector3& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector3& p_collider_velocity_at_pos) {
+void BodySW::add_contact(const Vector3 &p_local_pos, const Vector3 &p_local_normal, real_t p_depth, int p_local_shape, const Vector3 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector3 &p_collider_velocity_at_pos) {
- int c_max=contacts.size();
+ int c_max = contacts.size();
- if (c_max==0)
+ if (c_max == 0)
return;
Contact *c = &contacts[0];
+ int idx = -1;
- int idx=-1;
-
- if (contact_count<c_max) {
- idx=contact_count++;
+ if (contact_count < c_max) {
+ idx = contact_count++;
} else {
- real_t least_depth=1e20;
- int least_deep=-1;
- for(int i=0;i<c_max;i++) {
+ real_t least_depth = 1e20;
+ int least_deep = -1;
+ for (int i = 0; i < c_max; i++) {
- if (i==0 || c[i].depth<least_depth) {
- least_deep=i;
- least_depth=c[i].depth;
+ if (i == 0 || c[i].depth < least_depth) {
+ least_deep = i;
+ least_depth = c[i].depth;
}
}
- if (least_deep>=0 && least_depth<p_depth) {
+ if (least_deep >= 0 && least_depth < p_depth) {
- idx=least_deep;
+ idx = least_deep;
}
- if (idx==-1)
+ if (idx == -1)
return; //none least deepe than this
}
- c[idx].local_pos=p_local_pos;
- c[idx].local_normal=p_local_normal;
- c[idx].depth=p_depth;
- c[idx].local_shape=p_local_shape;
- c[idx].collider_pos=p_collider_pos;
- c[idx].collider_shape=p_collider_shape;
- c[idx].collider_instance_id=p_collider_instance_id;
- c[idx].collider=p_collider;
- c[idx].collider_velocity_at_pos=p_collider_velocity_at_pos;
-
+ c[idx].local_pos = p_local_pos;
+ c[idx].local_normal = p_local_normal;
+ c[idx].depth = p_depth;
+ c[idx].local_shape = p_local_shape;
+ c[idx].collider_pos = p_collider_pos;
+ c[idx].collider_shape = p_collider_shape;
+ c[idx].collider_instance_id = p_collider_instance_id;
+ c[idx].collider = p_collider;
+ c[idx].collider_velocity_at_pos = p_collider_velocity_at_pos;
}
-
class PhysicsDirectBodyStateSW : public PhysicsDirectBodyState {
- GDCLASS( PhysicsDirectBodyStateSW, PhysicsDirectBodyState );
+ GDCLASS(PhysicsDirectBodyStateSW, PhysicsDirectBodyState);
public:
-
static PhysicsDirectBodyStateSW *singleton;
BodySW *body;
real_t step;
- virtual Vector3 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area
- virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area
- virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area
+ virtual Vector3 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area
+ virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area
+ virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area
virtual Vector3 get_center_of_mass() const { return body->get_center_of_mass(); }
virtual Basis get_principal_inertia_axes() const { return body->get_principal_inertia_axes(); }
- virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass
- virtual Vector3 get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space
- virtual Basis get_inverse_inertia_tensor() const { return body->get_inv_inertia_tensor(); } // get density of this body space
+ virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass
+ virtual Vector3 get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space
+ virtual Basis get_inverse_inertia_tensor() const { return body->get_inv_inertia_tensor(); } // get density of this body space
- virtual void set_linear_velocity(const Vector3& p_velocity) { body->set_linear_velocity(p_velocity); }
- virtual Vector3 get_linear_velocity() const { return body->get_linear_velocity(); }
+ virtual void set_linear_velocity(const Vector3 &p_velocity) { body->set_linear_velocity(p_velocity); }
+ virtual Vector3 get_linear_velocity() const { return body->get_linear_velocity(); }
- virtual void set_angular_velocity(const Vector3& p_velocity) { body->set_angular_velocity(p_velocity); }
- virtual Vector3 get_angular_velocity() const { return body->get_angular_velocity(); }
+ virtual void set_angular_velocity(const Vector3 &p_velocity) { body->set_angular_velocity(p_velocity); }
+ virtual Vector3 get_angular_velocity() const { return body->get_angular_velocity(); }
- virtual void set_transform(const Transform& p_transform) { body->set_state(PhysicsServer::BODY_STATE_TRANSFORM,p_transform); }
- virtual Transform get_transform() const { return body->get_transform(); }
+ virtual void set_transform(const Transform &p_transform) { body->set_state(PhysicsServer::BODY_STATE_TRANSFORM, p_transform); }
+ virtual Transform get_transform() const { return body->get_transform(); }
- virtual void add_force(const Vector3& p_force, const Vector3& p_pos) { body->add_force(p_force,p_pos); }
- virtual void apply_impulse(const Vector3& p_pos, const Vector3& p_j) { body->apply_impulse(p_pos,p_j); }
- virtual void apply_torque_impulse(const Vector3& p_j) { body->apply_torque_impulse(p_j); }
+ virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos) { body->add_force(p_force, p_pos); }
+ virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) { body->apply_impulse(p_pos, p_j); }
+ virtual void apply_torque_impulse(const Vector3 &p_j) { body->apply_torque_impulse(p_j); }
- virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); }
- virtual bool is_sleeping() const { return !body->is_active(); }
+ virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); }
+ virtual bool is_sleeping() const { return !body->is_active(); }
- virtual int get_contact_count() const { return body->contact_count; }
+ virtual int get_contact_count() const { return body->contact_count; }
virtual Vector3 get_contact_local_pos(int p_contact_idx) const {
- ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3());
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3());
return body->contacts[p_contact_idx].local_pos;
}
- virtual Vector3 get_contact_local_normal(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].local_normal; }
- virtual int get_contact_local_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,-1); return body->contacts[p_contact_idx].local_shape; }
-
- virtual RID get_contact_collider(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,RID()); return body->contacts[p_contact_idx].collider; }
- virtual Vector3 get_contact_collider_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].collider_pos; }
- virtual ObjectID get_contact_collider_id(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_instance_id; }
- virtual int get_contact_collider_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_shape; }
- virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector3()); return body->contacts[p_contact_idx].collider_velocity_at_pos; }
+ virtual Vector3 get_contact_local_normal(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3());
+ return body->contacts[p_contact_idx].local_normal;
+ }
+ virtual int get_contact_local_shape(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, -1);
+ return body->contacts[p_contact_idx].local_shape;
+ }
- virtual PhysicsDirectSpaceState* get_space_state();
+ virtual RID get_contact_collider(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, RID());
+ return body->contacts[p_contact_idx].collider;
+ }
+ virtual Vector3 get_contact_collider_pos(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3());
+ return body->contacts[p_contact_idx].collider_pos;
+ }
+ virtual ObjectID get_contact_collider_id(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0);
+ return body->contacts[p_contact_idx].collider_instance_id;
+ }
+ virtual int get_contact_collider_shape(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0);
+ return body->contacts[p_contact_idx].collider_shape;
+ }
+ virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector3());
+ return body->contacts[p_contact_idx].collider_velocity_at_pos;
+ }
+ virtual PhysicsDirectSpaceState *get_space_state();
virtual real_t get_step() const { return step; }
- PhysicsDirectBodyStateSW() { singleton=this; body=NULL; }
+ PhysicsDirectBodyStateSW() {
+ singleton = this;
+ body = NULL;
+ }
};
-
#endif // BODY__SW_H
diff --git a/servers/physics/broad_phase_basic.cpp b/servers/physics/broad_phase_basic.cpp
index f1c22caae3..ca9bb40842 100644
--- a/servers/physics/broad_phase_basic.cpp
+++ b/servers/physics/broad_phase_basic.cpp
@@ -31,117 +31,111 @@
#include "print_string.h"
BroadPhaseSW::ID BroadPhaseBasic::create(CollisionObjectSW *p_object_, int p_subindex) {
- if (p_object_==NULL) {
+ if (p_object_ == NULL) {
- ERR_FAIL_COND_V(p_object_==NULL,0);
+ ERR_FAIL_COND_V(p_object_ == NULL, 0);
}
current++;
Element e;
- e.owner=p_object_;
- e._static=false;
- e.subindex=p_subindex;
+ e.owner = p_object_;
+ e._static = false;
+ e.subindex = p_subindex;
- element_map[current]=e;
+ element_map[current] = e;
return current;
}
-void BroadPhaseBasic::move(ID p_id, const Rect3& p_aabb) {
+void BroadPhaseBasic::move(ID p_id, const Rect3 &p_aabb) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- E->get().aabb=p_aabb;
-
+ E->get().aabb = p_aabb;
}
void BroadPhaseBasic::set_static(ID p_id, bool p_static) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- E->get()._static=p_static;
-
+ E->get()._static = p_static;
}
void BroadPhaseBasic::remove(ID p_id) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
List<PairKey> to_erase;
//unpair must be done immediately on removal to avoid potential invalid pointers
- for (Map<PairKey,void*>::Element *F=pair_map.front();F;F=F->next()) {
+ for (Map<PairKey, void *>::Element *F = pair_map.front(); F; F = F->next()) {
- if (F->key().a==p_id || F->key().b==p_id) {
+ if (F->key().a == p_id || F->key().b == p_id) {
if (unpair_callback) {
- Element *elem_A=&element_map[F->key().a];
- Element *elem_B=&element_map[F->key().b];
- unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,F->get(),unpair_userdata);
+ Element *elem_A = &element_map[F->key().a];
+ Element *elem_B = &element_map[F->key().b];
+ unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, F->get(), unpair_userdata);
}
to_erase.push_back(F->key());
}
}
- while(to_erase.size()) {
+ while (to_erase.size()) {
pair_map.erase(to_erase.front()->get());
to_erase.pop_front();
}
element_map.erase(E);
-
}
CollisionObjectSW *BroadPhaseBasic::get_object(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,NULL);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, NULL);
return E->get().owner;
-
}
bool BroadPhaseBasic::is_static(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,false);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, false);
return E->get()._static;
-
}
int BroadPhaseBasic::get_subindex(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,-1);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, -1);
return E->get().subindex;
}
-int BroadPhaseBasic::cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhaseBasic::cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) {
- int rc=0;
+ int rc = 0;
- for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) {
+ for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
- const Rect3 aabb=E->get().aabb;
- if (aabb.intersects_segment(p_from,p_to)) {
+ const Rect3 aabb = E->get().aabb;
+ if (aabb.intersects_segment(p_from, p_to)) {
- p_results[rc]=E->get().owner;
- p_result_indices[rc]=E->get().subindex;
+ p_results[rc] = E->get().owner;
+ p_result_indices[rc] = E->get().subindex;
rc++;
- if (rc>=p_max_results)
+ if (rc >= p_max_results)
break;
}
}
return rc;
-
}
-int BroadPhaseBasic::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhaseBasic::cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) {
- int rc=0;
+ int rc = 0;
- for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) {
+ for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
- const Rect3 aabb=E->get().aabb;
+ const Rect3 aabb = E->get().aabb;
if (aabb.intersects(p_aabb)) {
- p_results[rc]=E->get().owner;
- p_result_indices[rc]=E->get().subindex;
+ p_results[rc] = E->get().owner;
+ p_result_indices[rc] = E->get().subindex;
rc++;
- if (rc>=p_max_results)
+ if (rc >= p_max_results)
break;
}
}
@@ -149,68 +143,63 @@ int BroadPhaseBasic::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results
return rc;
}
-void BroadPhaseBasic::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) {
-
- pair_userdata=p_userdata;
- pair_callback=p_pair_callback;
+void BroadPhaseBasic::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
+ pair_userdata = p_userdata;
+ pair_callback = p_pair_callback;
}
-void BroadPhaseBasic::set_unpair_callback(UnpairCallback p_pair_callback,void *p_userdata) {
-
- unpair_userdata=p_userdata;
- unpair_callback=p_pair_callback;
+void BroadPhaseBasic::set_unpair_callback(UnpairCallback p_pair_callback, void *p_userdata) {
+ unpair_userdata = p_userdata;
+ unpair_callback = p_pair_callback;
}
void BroadPhaseBasic::update() {
// recompute pairs
- for(Map<ID,Element>::Element *I=element_map.front();I;I=I->next()) {
+ for (Map<ID, Element>::Element *I = element_map.front(); I; I = I->next()) {
- for(Map<ID,Element>::Element *J=I->next();J;J=J->next()) {
+ for (Map<ID, Element>::Element *J = I->next(); J; J = J->next()) {
- Element *elem_A=&I->get();
- Element *elem_B=&J->get();
+ Element *elem_A = &I->get();
+ Element *elem_B = &J->get();
if (elem_A->owner == elem_B->owner)
continue;
+ bool pair_ok = elem_A->aabb.intersects(elem_B->aabb) && (!elem_A->_static || !elem_B->_static);
- bool pair_ok=elem_A->aabb.intersects( elem_B->aabb ) && (!elem_A->_static || !elem_B->_static );
-
- PairKey key(I->key(),J->key());
+ PairKey key(I->key(), J->key());
- Map<PairKey,void*>::Element *E=pair_map.find(key);
+ Map<PairKey, void *>::Element *E = pair_map.find(key);
if (!pair_ok && E) {
if (unpair_callback)
- unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,E->get(),unpair_userdata);
+ unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, E->get(), unpair_userdata);
pair_map.erase(key);
}
if (pair_ok && !E) {
- void *data=NULL;
+ void *data = NULL;
if (pair_callback)
- data=pair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,unpair_userdata);
- pair_map.insert(key,data);
+ data = pair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, unpair_userdata);
+ pair_map.insert(key, data);
}
}
}
-
}
BroadPhaseSW *BroadPhaseBasic::_create() {
- return memnew( BroadPhaseBasic );
+ return memnew(BroadPhaseBasic);
}
BroadPhaseBasic::BroadPhaseBasic() {
- current=1;
- unpair_callback=NULL;
- unpair_userdata=NULL;
- pair_callback=NULL;
- pair_userdata=NULL;
-
+ current = 1;
+ unpair_callback = NULL;
+ unpair_userdata = NULL;
+ pair_callback = NULL;
+ pair_userdata = NULL;
}
diff --git a/servers/physics/broad_phase_basic.h b/servers/physics/broad_phase_basic.h
index 9f07e896c4..2824af6b68 100644
--- a/servers/physics/broad_phase_basic.h
+++ b/servers/physics/broad_phase_basic.h
@@ -42,8 +42,7 @@ class BroadPhaseBasic : public BroadPhaseSW {
int subindex;
};
-
- Map<ID,Element> element_map;
+ Map<ID, Element> element_map;
ID current;
@@ -57,17 +56,23 @@ class BroadPhaseBasic : public BroadPhaseSW {
uint64_t key;
};
- _FORCE_INLINE_ bool operator<(const PairKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const PairKey &p_key) const {
return key < p_key.key;
}
- PairKey() { key=0; }
- PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }}
-
+ PairKey() { key = 0; }
+ PairKey(ID p_a, ID p_b) {
+ if (p_a > p_b) {
+ a = p_b;
+ b = p_a;
+ } else {
+ a = p_a;
+ b = p_b;
+ }
+ }
};
- Map<PairKey,void*> pair_map;
-
+ Map<PairKey, void *> pair_map;
PairCallback pair_callback;
void *pair_userdata;
@@ -75,10 +80,9 @@ class BroadPhaseBasic : public BroadPhaseSW {
void *unpair_userdata;
public:
-
// 0 is an invalid ID
- virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0);
- virtual void move(ID p_id, const Rect3& p_aabb);
+ virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0);
+ virtual void move(ID p_id, const Rect3 &p_aabb);
virtual void set_static(ID p_id, bool p_static);
virtual void remove(ID p_id);
@@ -86,11 +90,11 @@ public:
virtual bool is_static(ID p_id) const;
virtual int get_subindex(ID p_id) const;
- virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL);
- virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL);
+ virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL);
+ virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL);
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata);
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata);
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata);
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata);
virtual void update();
diff --git a/servers/physics/broad_phase_octree.cpp b/servers/physics/broad_phase_octree.cpp
index 89581997a2..cb64077d9a 100644
--- a/servers/physics/broad_phase_octree.cpp
+++ b/servers/physics/broad_phase_octree.cpp
@@ -31,85 +31,77 @@
BroadPhaseSW::ID BroadPhaseOctree::create(CollisionObjectSW *p_object, int p_subindex) {
- ID oid = octree.create(p_object,Rect3(),p_subindex,false,1<<p_object->get_type(),0);
+ ID oid = octree.create(p_object, Rect3(), p_subindex, false, 1 << p_object->get_type(), 0);
return oid;
}
-void BroadPhaseOctree::move(ID p_id, const Rect3& p_aabb){
+void BroadPhaseOctree::move(ID p_id, const Rect3 &p_aabb) {
- octree.move(p_id,p_aabb);
+ octree.move(p_id, p_aabb);
}
-void BroadPhaseOctree::set_static(ID p_id, bool p_static){
+void BroadPhaseOctree::set_static(ID p_id, bool p_static) {
CollisionObjectSW *it = octree.get(p_id);
- octree.set_pairable(p_id,p_static?false:true,1<<it->get_type(),p_static?0:0xFFFFF); //pair everything, don't care 1?
-
+ octree.set_pairable(p_id, p_static ? false : true, 1 << it->get_type(), p_static ? 0 : 0xFFFFF); //pair everything, don't care 1?
}
-void BroadPhaseOctree::remove(ID p_id){
+void BroadPhaseOctree::remove(ID p_id) {
octree.erase(p_id);
}
-CollisionObjectSW *BroadPhaseOctree::get_object(ID p_id) const{
+CollisionObjectSW *BroadPhaseOctree::get_object(ID p_id) const {
CollisionObjectSW *it = octree.get(p_id);
- ERR_FAIL_COND_V(!it,NULL);
+ ERR_FAIL_COND_V(!it, NULL);
return it;
}
-bool BroadPhaseOctree::is_static(ID p_id) const{
+bool BroadPhaseOctree::is_static(ID p_id) const {
return !octree.is_pairable(p_id);
}
-int BroadPhaseOctree::get_subindex(ID p_id) const{
+int BroadPhaseOctree::get_subindex(ID p_id) const {
return octree.get_subindex(p_id);
}
-int BroadPhaseOctree::cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices){
+int BroadPhaseOctree::cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) {
- return octree.cull_segment(p_from,p_to,p_results,p_max_results,p_result_indices);
+ return octree.cull_segment(p_from, p_to, p_results, p_max_results, p_result_indices);
}
-int BroadPhaseOctree::cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices) {
-
- return octree.cull_AABB(p_aabb,p_results,p_max_results,p_result_indices);
+int BroadPhaseOctree::cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices) {
+ return octree.cull_AABB(p_aabb, p_results, p_max_results, p_result_indices);
}
+void *BroadPhaseOctree::_pair_callback(void *self, OctreeElementID p_A, CollisionObjectSW *p_object_A, int subindex_A, OctreeElementID p_B, CollisionObjectSW *p_object_B, int subindex_B) {
-void* BroadPhaseOctree::_pair_callback(void*self,OctreeElementID p_A, CollisionObjectSW*p_object_A,int subindex_A,OctreeElementID p_B, CollisionObjectSW*p_object_B,int subindex_B) {
-
- BroadPhaseOctree *bpo=(BroadPhaseOctree*)(self);
+ BroadPhaseOctree *bpo = (BroadPhaseOctree *)(self);
if (!bpo->pair_callback)
return NULL;
- return bpo->pair_callback(p_object_A,subindex_A,p_object_B,subindex_B,bpo->pair_userdata);
-
+ return bpo->pair_callback(p_object_A, subindex_A, p_object_B, subindex_B, bpo->pair_userdata);
}
-void BroadPhaseOctree::_unpair_callback(void*self,OctreeElementID p_A, CollisionObjectSW*p_object_A,int subindex_A,OctreeElementID p_B, CollisionObjectSW*p_object_B,int subindex_B,void*pairdata) {
+void BroadPhaseOctree::_unpair_callback(void *self, OctreeElementID p_A, CollisionObjectSW *p_object_A, int subindex_A, OctreeElementID p_B, CollisionObjectSW *p_object_B, int subindex_B, void *pairdata) {
- BroadPhaseOctree *bpo=(BroadPhaseOctree*)(self);
+ BroadPhaseOctree *bpo = (BroadPhaseOctree *)(self);
if (!bpo->unpair_callback)
return;
- bpo->unpair_callback(p_object_A,subindex_A,p_object_B,subindex_B,pairdata,bpo->unpair_userdata);
-
+ bpo->unpair_callback(p_object_A, subindex_A, p_object_B, subindex_B, pairdata, bpo->unpair_userdata);
}
+void BroadPhaseOctree::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
-void BroadPhaseOctree::set_pair_callback(PairCallback p_pair_callback,void *p_userdata){
-
- pair_callback=p_pair_callback;
- pair_userdata=p_userdata;
-
+ pair_callback = p_pair_callback;
+ pair_userdata = p_userdata;
}
-void BroadPhaseOctree::set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata){
-
- unpair_callback=p_unpair_callback;
- unpair_userdata=p_userdata;
+void BroadPhaseOctree::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) {
+ unpair_callback = p_unpair_callback;
+ unpair_userdata = p_userdata;
}
void BroadPhaseOctree::update() {
@@ -118,16 +110,14 @@ void BroadPhaseOctree::update() {
BroadPhaseSW *BroadPhaseOctree::_create() {
- return memnew( BroadPhaseOctree );
+ return memnew(BroadPhaseOctree);
}
BroadPhaseOctree::BroadPhaseOctree() {
- octree.set_pair_callback(_pair_callback,this);
- octree.set_unpair_callback(_unpair_callback,this);
- pair_callback=NULL;
- pair_userdata=NULL;
- pair_callback=NULL;
- unpair_userdata=NULL;
+ octree.set_pair_callback(_pair_callback, this);
+ octree.set_unpair_callback(_unpair_callback, this);
+ pair_callback = NULL;
+ pair_userdata = NULL;
+ pair_callback = NULL;
+ unpair_userdata = NULL;
}
-
-
diff --git a/servers/physics/broad_phase_octree.h b/servers/physics/broad_phase_octree.h
index 29f1123edf..f9a8bd17ed 100644
--- a/servers/physics/broad_phase_octree.h
+++ b/servers/physics/broad_phase_octree.h
@@ -34,12 +34,10 @@
class BroadPhaseOctree : public BroadPhaseSW {
+ Octree<CollisionObjectSW, true> octree;
- Octree<CollisionObjectSW,true> octree;
-
- static void* _pair_callback(void*,OctreeElementID, CollisionObjectSW*,int,OctreeElementID, CollisionObjectSW*,int);
- static void _unpair_callback(void*,OctreeElementID, CollisionObjectSW*,int,OctreeElementID, CollisionObjectSW*,int,void*);
-
+ static void *_pair_callback(void *, OctreeElementID, CollisionObjectSW *, int, OctreeElementID, CollisionObjectSW *, int);
+ static void _unpair_callback(void *, OctreeElementID, CollisionObjectSW *, int, OctreeElementID, CollisionObjectSW *, int, void *);
PairCallback pair_callback;
void *pair_userdata;
@@ -47,10 +45,9 @@ class BroadPhaseOctree : public BroadPhaseSW {
void *unpair_userdata;
public:
-
// 0 is an invalid ID
- virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0);
- virtual void move(ID p_id, const Rect3& p_aabb);
+ virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0);
+ virtual void move(ID p_id, const Rect3 &p_aabb);
virtual void set_static(ID p_id, bool p_static);
virtual void remove(ID p_id);
@@ -58,11 +55,11 @@ public:
virtual bool is_static(ID p_id) const;
virtual int get_subindex(ID p_id) const;
- virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL);
- virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL);
+ virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL);
+ virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL);
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata);
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata);
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata);
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata);
virtual void update();
diff --git a/servers/physics/broad_phase_sw.cpp b/servers/physics/broad_phase_sw.cpp
index 2a897dea2b..f9a19e558b 100644
--- a/servers/physics/broad_phase_sw.cpp
+++ b/servers/physics/broad_phase_sw.cpp
@@ -28,8 +28,7 @@
/*************************************************************************/
#include "broad_phase_sw.h"
-BroadPhaseSW::CreateFunction BroadPhaseSW::create_func=NULL;
+BroadPhaseSW::CreateFunction BroadPhaseSW::create_func = NULL;
-BroadPhaseSW::~BroadPhaseSW()
-{
+BroadPhaseSW::~BroadPhaseSW() {
}
diff --git a/servers/physics/broad_phase_sw.h b/servers/physics/broad_phase_sw.h
index 20b3efc7fb..df6ea1cc73 100644
--- a/servers/physics/broad_phase_sw.h
+++ b/servers/physics/broad_phase_sw.h
@@ -34,40 +34,37 @@
class CollisionObjectSW;
-
class BroadPhaseSW {
public:
- typedef BroadPhaseSW* (*CreateFunction)();
+ typedef BroadPhaseSW *(*CreateFunction)();
static CreateFunction create_func;
typedef uint32_t ID;
-
- typedef void* (*PairCallback)(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_userdata);
- typedef void (*UnpairCallback)(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_userdata);
+ typedef void *(*PairCallback)(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_userdata);
+ typedef void (*UnpairCallback)(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_userdata);
// 0 is an invalid ID
- virtual ID create(CollisionObjectSW *p_object_, int p_subindex=0)=0;
- virtual void move(ID p_id, const Rect3& p_aabb)=0;
- virtual void set_static(ID p_id, bool p_static)=0;
- virtual void remove(ID p_id)=0;
+ virtual ID create(CollisionObjectSW *p_object_, int p_subindex = 0) = 0;
+ virtual void move(ID p_id, const Rect3 &p_aabb) = 0;
+ virtual void set_static(ID p_id, bool p_static) = 0;
+ virtual void remove(ID p_id) = 0;
- virtual CollisionObjectSW *get_object(ID p_id) const=0;
- virtual bool is_static(ID p_id) const=0;
- virtual int get_subindex(ID p_id) const=0;
+ virtual CollisionObjectSW *get_object(ID p_id) const = 0;
+ virtual bool is_static(ID p_id) const = 0;
+ virtual int get_subindex(ID p_id) const = 0;
- virtual int cull_segment(const Vector3& p_from, const Vector3& p_to,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL)=0;
- virtual int cull_aabb(const Rect3& p_aabb,CollisionObjectSW** p_results,int p_max_results,int *p_result_indices=NULL)=0;
+ virtual int cull_segment(const Vector3 &p_from, const Vector3 &p_to, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0;
+ virtual int cull_aabb(const Rect3 &p_aabb, CollisionObjectSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0;
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata)=0;
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata)=0;
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) = 0;
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) = 0;
- virtual void update()=0;
+ virtual void update() = 0;
virtual ~BroadPhaseSW();
-
};
#endif // BROAD_PHASE__SW_H
diff --git a/servers/physics/collision_object_sw.cpp b/servers/physics/collision_object_sw.cpp
index 88aa737579..36704b6eb8 100644
--- a/servers/physics/collision_object_sw.cpp
+++ b/servers/physics/collision_object_sw.cpp
@@ -29,37 +29,35 @@
#include "collision_object_sw.h"
#include "space_sw.h"
-void CollisionObjectSW::add_shape(ShapeSW *p_shape,const Transform& p_transform) {
+void CollisionObjectSW::add_shape(ShapeSW *p_shape, const Transform &p_transform) {
Shape s;
- s.shape=p_shape;
- s.xform=p_transform;
- s.xform_inv=s.xform.affine_inverse();
- s.bpid=0; //needs update
+ s.shape = p_shape;
+ s.xform = p_transform;
+ s.xform_inv = s.xform.affine_inverse();
+ s.bpid = 0; //needs update
shapes.push_back(s);
p_shape->add_owner(this);
_update_shapes();
_shapes_changed();
-
}
-void CollisionObjectSW::set_shape(int p_index,ShapeSW *p_shape){
+void CollisionObjectSW::set_shape(int p_index, ShapeSW *p_shape) {
- ERR_FAIL_INDEX(p_index,shapes.size());
+ ERR_FAIL_INDEX(p_index, shapes.size());
shapes[p_index].shape->remove_owner(this);
- shapes[p_index].shape=p_shape;
+ shapes[p_index].shape = p_shape;
p_shape->add_owner(this);
_update_shapes();
_shapes_changed();
-
}
-void CollisionObjectSW::set_shape_transform(int p_index,const Transform& p_transform){
+void CollisionObjectSW::set_shape_transform(int p_index, const Transform &p_transform) {
- ERR_FAIL_INDEX(p_index,shapes.size());
+ ERR_FAIL_INDEX(p_index, shapes.size());
- shapes[p_index].xform=p_transform;
- shapes[p_index].xform_inv=p_transform.affine_inverse();
+ shapes[p_index].xform = p_transform;
+ shapes[p_index].xform_inv = p_transform.affine_inverse();
_update_shapes();
_shapes_changed();
}
@@ -67,61 +65,58 @@ void CollisionObjectSW::set_shape_transform(int p_index,const Transform& p_trans
void CollisionObjectSW::remove_shape(ShapeSW *p_shape) {
//remove a shape, all the times it appears
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- if (shapes[i].shape==p_shape) {
+ if (shapes[i].shape == p_shape) {
remove_shape(i);
i--;
}
}
}
-void CollisionObjectSW::remove_shape(int p_index){
+void CollisionObjectSW::remove_shape(int p_index) {
//remove anything from shape to be erased to end, so subindices don't change
- ERR_FAIL_INDEX(p_index,shapes.size());
- for(int i=p_index;i<shapes.size();i++) {
+ ERR_FAIL_INDEX(p_index, shapes.size());
+ for (int i = p_index; i < shapes.size(); i++) {
- if (shapes[i].bpid==0)
+ if (shapes[i].bpid == 0)
continue;
//should never get here with a null owner
space->get_broadphase()->remove(shapes[i].bpid);
- shapes[i].bpid=0;
+ shapes[i].bpid = 0;
}
shapes[p_index].shape->remove_owner(this);
shapes.remove(p_index);
_shapes_changed();
-
}
void CollisionObjectSW::_set_static(bool p_static) {
- if (_static==p_static)
+ if (_static == p_static)
return;
- _static=p_static;
+ _static = p_static;
if (!space)
return;
- for(int i=0;i<get_shape_count();i++) {
- Shape &s=shapes[i];
- if (s.bpid>0) {
- space->get_broadphase()->set_static(s.bpid,_static);
+ for (int i = 0; i < get_shape_count(); i++) {
+ Shape &s = shapes[i];
+ if (s.bpid > 0) {
+ space->get_broadphase()->set_static(s.bpid, _static);
}
}
-
}
void CollisionObjectSW::_unregister_shapes() {
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
- if (s.bpid>0) {
+ Shape &s = shapes[i];
+ if (s.bpid > 0) {
space->get_broadphase()->remove(s.bpid);
- s.bpid=0;
+ s.bpid = 0;
}
}
-
}
void CollisionObjectSW::_update_shapes() {
@@ -129,54 +124,50 @@ void CollisionObjectSW::_update_shapes() {
if (!space)
return;
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
- if (s.bpid==0) {
- s.bpid=space->get_broadphase()->create(this,i);
- space->get_broadphase()->set_static(s.bpid,_static);
+ Shape &s = shapes[i];
+ if (s.bpid == 0) {
+ s.bpid = space->get_broadphase()->create(this, i);
+ space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
- Rect3 shape_aabb=s.shape->get_aabb();
+ Rect3 shape_aabb = s.shape->get_aabb();
Transform xform = transform * s.xform;
- shape_aabb=xform.xform(shape_aabb);
- s.aabb_cache=shape_aabb;
- s.aabb_cache=s.aabb_cache.grow( (s.aabb_cache.size.x + s.aabb_cache.size.y)*0.5*0.05 );
+ shape_aabb = xform.xform(shape_aabb);
+ s.aabb_cache = shape_aabb;
+ s.aabb_cache = s.aabb_cache.grow((s.aabb_cache.size.x + s.aabb_cache.size.y) * 0.5 * 0.05);
Vector3 scale = xform.get_basis().get_scale();
- s.area_cache=s.shape->get_area()*scale.x*scale.y*scale.z;
+ s.area_cache = s.shape->get_area() * scale.x * scale.y * scale.z;
- space->get_broadphase()->move(s.bpid,s.aabb_cache);
+ space->get_broadphase()->move(s.bpid, s.aabb_cache);
}
-
}
-void CollisionObjectSW::_update_shapes_with_motion(const Vector3& p_motion) {
-
+void CollisionObjectSW::_update_shapes_with_motion(const Vector3 &p_motion) {
if (!space)
return;
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
- if (s.bpid==0) {
- s.bpid=space->get_broadphase()->create(this,i);
- space->get_broadphase()->set_static(s.bpid,_static);
+ Shape &s = shapes[i];
+ if (s.bpid == 0) {
+ s.bpid = space->get_broadphase()->create(this, i);
+ space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
- Rect3 shape_aabb=s.shape->get_aabb();
+ Rect3 shape_aabb = s.shape->get_aabb();
Transform xform = transform * s.xform;
- shape_aabb=xform.xform(shape_aabb);
- shape_aabb=shape_aabb.merge(Rect3( shape_aabb.pos+p_motion,shape_aabb.size)); //use motion
- s.aabb_cache=shape_aabb;
+ shape_aabb = xform.xform(shape_aabb);
+ shape_aabb = shape_aabb.merge(Rect3(shape_aabb.pos + p_motion, shape_aabb.size)); //use motion
+ s.aabb_cache = shape_aabb;
- space->get_broadphase()->move(s.bpid,shape_aabb);
+ space->get_broadphase()->move(s.bpid, shape_aabb);
}
-
-
}
void CollisionObjectSW::_set_space(SpaceSW *p_space) {
@@ -185,25 +176,23 @@ void CollisionObjectSW::_set_space(SpaceSW *p_space) {
space->remove_object(this);
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
+ Shape &s = shapes[i];
if (s.bpid) {
space->get_broadphase()->remove(s.bpid);
- s.bpid=0;
+ s.bpid = 0;
}
}
-
}
- space=p_space;
+ space = p_space;
if (space) {
space->add_object(this);
_update_shapes();
}
-
}
void CollisionObjectSW::_shape_changed() {
@@ -214,11 +203,11 @@ void CollisionObjectSW::_shape_changed() {
CollisionObjectSW::CollisionObjectSW(Type p_type) {
- _static=true;
- type=p_type;
- space=NULL;
- instance_id=0;
- layer_mask=1;
- collision_mask=1;
- ray_pickable=true;
+ _static = true;
+ type = p_type;
+ space = NULL;
+ instance_id = 0;
+ layer_mask = 1;
+ collision_mask = 1;
+ ray_pickable = true;
}
diff --git a/servers/physics/collision_object_sw.h b/servers/physics/collision_object_sw.h
index c46a7f4a5f..9a7626d583 100644
--- a/servers/physics/collision_object_sw.h
+++ b/servers/physics/collision_object_sw.h
@@ -29,14 +29,14 @@
#ifndef COLLISION_OBJECT_SW_H
#define COLLISION_OBJECT_SW_H
-#include "shape_sw.h"
-#include "servers/physics_server.h"
-#include "self_list.h"
#include "broad_phase_sw.h"
+#include "self_list.h"
+#include "servers/physics_server.h"
+#include "shape_sw.h"
#ifdef DEBUG_ENABLED
#define MAX_OBJECT_DISTANCE 10000000.0
-#define MAX_OBJECT_DISTANCE_X2 (MAX_OBJECT_DISTANCE*MAX_OBJECT_DISTANCE)
+#define MAX_OBJECT_DISTANCE_X2 (MAX_OBJECT_DISTANCE * MAX_OBJECT_DISTANCE)
#endif
class SpaceSW;
@@ -47,8 +47,8 @@ public:
TYPE_AREA,
TYPE_BODY
};
-private:
+private:
Type type;
RID self;
ObjectID instance_id;
@@ -65,7 +65,7 @@ private:
ShapeSW *shape;
bool trigger;
- Shape() { trigger=false; }
+ Shape() { trigger = false; }
};
Vector<Shape> shapes;
@@ -77,84 +77,80 @@ private:
void _update_shapes();
protected:
-
-
- void _update_shapes_with_motion(const Vector3& p_motion);
+ void _update_shapes_with_motion(const Vector3 &p_motion);
void _unregister_shapes();
- _FORCE_INLINE_ void _set_transform(const Transform& p_transform,bool p_update_shapes=true) {
+ _FORCE_INLINE_ void _set_transform(const Transform &p_transform, bool p_update_shapes = true) {
#ifdef DEBUG_ENABLED
if (p_transform.origin.length_squared() > MAX_OBJECT_DISTANCE_X2) {
- ERR_EXPLAIN("Object went too far away (more than "+itos(MAX_OBJECT_DISTANCE)+"mts from origin).");
+ ERR_EXPLAIN("Object went too far away (more than " + itos(MAX_OBJECT_DISTANCE) + "mts from origin).");
ERR_FAIL();
}
#endif
- transform=p_transform; if (p_update_shapes) _update_shapes();
-
+ transform = p_transform;
+ if (p_update_shapes) _update_shapes();
}
- _FORCE_INLINE_ void _set_inv_transform(const Transform& p_transform) { inv_transform=p_transform; }
+ _FORCE_INLINE_ void _set_inv_transform(const Transform &p_transform) { inv_transform = p_transform; }
void _set_static(bool p_static);
- virtual void _shapes_changed()=0;
+ virtual void _shapes_changed() = 0;
void _set_space(SpaceSW *space);
bool ray_pickable;
-
CollisionObjectSW(Type p_type);
-public:
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+public:
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
- _FORCE_INLINE_ void set_instance_id(const ObjectID& p_instance_id) { instance_id=p_instance_id; }
+ _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; }
_FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; }
void _shape_changed();
_FORCE_INLINE_ Type get_type() const { return type; }
- void add_shape(ShapeSW *p_shape,const Transform& p_transform=Transform());
- void set_shape(int p_index,ShapeSW *p_shape);
- void set_shape_transform(int p_index,const Transform& p_transform);
+ void add_shape(ShapeSW *p_shape, const Transform &p_transform = Transform());
+ void set_shape(int p_index, ShapeSW *p_shape);
+ void set_shape_transform(int p_index, const Transform &p_transform);
_FORCE_INLINE_ int get_shape_count() const { return shapes.size(); }
_FORCE_INLINE_ ShapeSW *get_shape(int p_index) const { return shapes[p_index].shape; }
- _FORCE_INLINE_ const Transform& get_shape_transform(int p_index) const { return shapes[p_index].xform; }
- _FORCE_INLINE_ const Transform& get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; }
- _FORCE_INLINE_ const Rect3& get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; }
+ _FORCE_INLINE_ const Transform &get_shape_transform(int p_index) const { return shapes[p_index].xform; }
+ _FORCE_INLINE_ const Transform &get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; }
+ _FORCE_INLINE_ const Rect3 &get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; }
_FORCE_INLINE_ const real_t get_shape_area(int p_index) const { return shapes[p_index].area_cache; }
_FORCE_INLINE_ Transform get_transform() const { return transform; }
_FORCE_INLINE_ Transform get_inv_transform() const { return inv_transform; }
- _FORCE_INLINE_ SpaceSW* get_space() const { return space; }
+ _FORCE_INLINE_ SpaceSW *get_space() const { return space; }
- _FORCE_INLINE_ void set_ray_pickable(bool p_enable) { ray_pickable=p_enable; }
+ _FORCE_INLINE_ void set_ray_pickable(bool p_enable) { ray_pickable = p_enable; }
_FORCE_INLINE_ bool is_ray_pickable() const { return ray_pickable; }
- _FORCE_INLINE_ void set_shape_as_trigger(int p_idx,bool p_enable) { shapes[p_idx].trigger=p_enable; }
+ _FORCE_INLINE_ void set_shape_as_trigger(int p_idx, bool p_enable) { shapes[p_idx].trigger = p_enable; }
_FORCE_INLINE_ bool is_shape_set_as_trigger(int p_idx) const { return shapes[p_idx].trigger; }
- _FORCE_INLINE_ void set_layer_mask(uint32_t p_mask) { layer_mask=p_mask; }
+ _FORCE_INLINE_ void set_layer_mask(uint32_t p_mask) { layer_mask = p_mask; }
_FORCE_INLINE_ uint32_t get_layer_mask() const { return layer_mask; }
- _FORCE_INLINE_ void set_collision_mask(uint32_t p_mask) { collision_mask=p_mask; }
+ _FORCE_INLINE_ void set_collision_mask(uint32_t p_mask) { collision_mask = p_mask; }
_FORCE_INLINE_ uint32_t get_collision_mask() const { return collision_mask; }
- _FORCE_INLINE_ bool test_collision_mask(CollisionObjectSW* p_other) const {
- return layer_mask&p_other->collision_mask || p_other->layer_mask&collision_mask;
+ _FORCE_INLINE_ bool test_collision_mask(CollisionObjectSW *p_other) const {
+ return layer_mask & p_other->collision_mask || p_other->layer_mask & collision_mask;
}
void remove_shape(ShapeSW *p_shape);
void remove_shape(int p_index);
- virtual void set_space(SpaceSW *p_space)=0;
+ virtual void set_space(SpaceSW *p_space) = 0;
- _FORCE_INLINE_ bool is_static() const { return _static; }
+ _FORCE_INLINE_ bool is_static() const { return _static; }
virtual ~CollisionObjectSW() {}
-
};
#endif // COLLISION_OBJECT_SW_H
diff --git a/servers/physics/collision_solver_sat.cpp b/servers/physics/collision_solver_sat.cpp
index 9d3e1db47b..003e6b3257 100644
--- a/servers/physics/collision_solver_sat.cpp
+++ b/servers/physics/collision_solver_sat.cpp
@@ -40,7 +40,7 @@ struct _CollectorCallback {
Vector3 normal;
Vector3 *prev_axis;
- _FORCE_INLINE_ void call(const Vector3& p_point_A, const Vector3& p_point_B) {
+ _FORCE_INLINE_ void call(const Vector3 &p_point_A, const Vector3 &p_point_B) {
/*
if (normal.dot(p_point_A) >= normal.dot(p_point_B))
@@ -49,69 +49,61 @@ struct _CollectorCallback {
*/
if (swap)
- callback(p_point_B,p_point_A,userdata);
+ callback(p_point_B, p_point_A, userdata);
else
- callback(p_point_A,p_point_B,userdata);
+ callback(p_point_A, p_point_B, userdata);
}
-
};
-typedef void (*GenerateContactsFunc)(const Vector3 *,int, const Vector3 *,int ,_CollectorCallback *);
-
+typedef void (*GenerateContactsFunc)(const Vector3 *, int, const Vector3 *, int, _CollectorCallback *);
-static void _generate_contacts_point_point(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
+static void _generate_contacts_point_point(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 1 );
- ERR_FAIL_COND( p_point_count_B != 1 );
+ ERR_FAIL_COND(p_point_count_A != 1);
+ ERR_FAIL_COND(p_point_count_B != 1);
#endif
- p_callback->call(*p_points_A,*p_points_B);
+ p_callback->call(*p_points_A, *p_points_B);
}
-static void _generate_contacts_point_edge(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
+static void _generate_contacts_point_edge(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 1 );
- ERR_FAIL_COND( p_point_count_B != 2 );
+ ERR_FAIL_COND(p_point_count_A != 1);
+ ERR_FAIL_COND(p_point_count_B != 2);
#endif
- Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(*p_points_A, p_points_B );
- p_callback->call(*p_points_A,closest_B);
-
+ Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(*p_points_A, p_points_B);
+ p_callback->call(*p_points_A, closest_B);
}
-static void _generate_contacts_point_face(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
+static void _generate_contacts_point_face(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 1 );
- ERR_FAIL_COND( p_point_count_B < 3 );
+ ERR_FAIL_COND(p_point_count_A != 1);
+ ERR_FAIL_COND(p_point_count_B < 3);
#endif
+ Vector3 closest_B = Plane(p_points_B[0], p_points_B[1], p_points_B[2]).project(*p_points_A);
- Vector3 closest_B=Plane(p_points_B[0],p_points_B[1],p_points_B[2]).project( *p_points_A );
-
- p_callback->call(*p_points_A,closest_B);
-
+ p_callback->call(*p_points_A, closest_B);
}
-
-static void _generate_contacts_edge_edge(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
+static void _generate_contacts_edge_edge(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 2 );
- ERR_FAIL_COND( p_point_count_B != 2 ); // circle is actually a 4x3 matrix
+ ERR_FAIL_COND(p_point_count_A != 2);
+ ERR_FAIL_COND(p_point_count_B != 2); // circle is actually a 4x3 matrix
#endif
+ Vector3 rel_A = p_points_A[1] - p_points_A[0];
+ Vector3 rel_B = p_points_B[1] - p_points_B[0];
-
- Vector3 rel_A=p_points_A[1]-p_points_A[0];
- Vector3 rel_B=p_points_B[1]-p_points_B[0];
-
- Vector3 c=rel_A.cross(rel_B).cross(rel_B);
+ Vector3 c = rel_A.cross(rel_B).cross(rel_B);
//if ( Math::abs(rel_A.dot(c) )<_EDGE_IS_VALID_SUPPORT_TRESHOLD ) {
- if ( Math::abs(rel_A.dot(c) )<CMP_EPSILON ) {
+ if (Math::abs(rel_A.dot(c)) < CMP_EPSILON) {
// should handle somehow..
//ERR_PRINT("TODO FIX");
@@ -122,117 +114,110 @@ static void _generate_contacts_edge_edge(const Vector3 * p_points_A,int p_point_
Vector3 base_B = p_points_B[0] - axis * axis.dot(p_points_B[0]);
//sort all 4 points in axis
- real_t dvec[4]={ axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) };
+ real_t dvec[4] = { axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) };
SortArray<real_t> sa;
- sa.sort(dvec,4);
+ sa.sort(dvec, 4);
//use the middle ones as contacts
- p_callback->call(base_A+axis*dvec[1],base_B+axis*dvec[1]);
- p_callback->call(base_A+axis*dvec[2],base_B+axis*dvec[2]);
+ p_callback->call(base_A + axis * dvec[1], base_B + axis * dvec[1]);
+ p_callback->call(base_A + axis * dvec[2], base_B + axis * dvec[2]);
return;
-
}
- real_t d = (c.dot( p_points_B[0] ) - p_points_A[0].dot(c))/rel_A.dot(c);
+ real_t d = (c.dot(p_points_B[0]) - p_points_A[0].dot(c)) / rel_A.dot(c);
- if (d<0.0)
- d=0.0;
- else if (d>1.0)
- d=1.0;
-
- Vector3 closest_A=p_points_A[0]+rel_A*d;
- Vector3 closest_B=Geometry::get_closest_point_to_segment_uncapped(closest_A, p_points_B);
- p_callback->call(closest_A,closest_B);
+ if (d < 0.0)
+ d = 0.0;
+ else if (d > 1.0)
+ d = 1.0;
+ Vector3 closest_A = p_points_A[0] + rel_A * d;
+ Vector3 closest_B = Geometry::get_closest_point_to_segment_uncapped(closest_A, p_points_B);
+ p_callback->call(closest_A, closest_B);
}
-static void _generate_contacts_face_face(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
+static void _generate_contacts_face_face(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A <2 );
- ERR_FAIL_COND( p_point_count_B <3 );
+ ERR_FAIL_COND(p_point_count_A < 2);
+ ERR_FAIL_COND(p_point_count_B < 3);
#endif
- static const int max_clip=32;
+ static const int max_clip = 32;
Vector3 _clipbuf1[max_clip];
Vector3 _clipbuf2[max_clip];
- Vector3 *clipbuf_src=_clipbuf1;
- Vector3 *clipbuf_dst=_clipbuf2;
- int clipbuf_len=p_point_count_A;
+ Vector3 *clipbuf_src = _clipbuf1;
+ Vector3 *clipbuf_dst = _clipbuf2;
+ int clipbuf_len = p_point_count_A;
// copy A points to clipbuf_src
- for (int i=0;i<p_point_count_A;i++) {
+ for (int i = 0; i < p_point_count_A; i++) {
- clipbuf_src[i]=p_points_A[i];
+ clipbuf_src[i] = p_points_A[i];
}
- Plane plane_B(p_points_B[0],p_points_B[1],p_points_B[2]);
+ Plane plane_B(p_points_B[0], p_points_B[1], p_points_B[2]);
// go through all of B points
- for (int i=0;i<p_point_count_B;i++) {
+ for (int i = 0; i < p_point_count_B; i++) {
- int i_n=(i+1)%p_point_count_B;
+ int i_n = (i + 1) % p_point_count_B;
- Vector3 edge0_B=p_points_B[i];
- Vector3 edge1_B=p_points_B[i_n];
+ Vector3 edge0_B = p_points_B[i];
+ Vector3 edge1_B = p_points_B[i_n];
- Vector3 clip_normal = (edge0_B - edge1_B).cross( plane_B.normal ).normalized();
+ Vector3 clip_normal = (edge0_B - edge1_B).cross(plane_B.normal).normalized();
// make a clip plane
-
- Plane clip(edge0_B,clip_normal);
+ Plane clip(edge0_B, clip_normal);
// avoid double clip if A is edge
- int dst_idx=0;
- bool edge = clipbuf_len==2;
- for (int j=0;j<clipbuf_len;j++) {
+ int dst_idx = 0;
+ bool edge = clipbuf_len == 2;
+ for (int j = 0; j < clipbuf_len; j++) {
- int j_n=(j+1)%clipbuf_len;
+ int j_n = (j + 1) % clipbuf_len;
- Vector3 edge0_A=clipbuf_src[j];
- Vector3 edge1_A=clipbuf_src[j_n];
+ Vector3 edge0_A = clipbuf_src[j];
+ Vector3 edge1_A = clipbuf_src[j_n];
real_t dist0 = clip.distance_to(edge0_A);
real_t dist1 = clip.distance_to(edge1_A);
+ if (dist0 <= 0) { // behind plane
- if ( dist0 <= 0 ) { // behind plane
-
- ERR_FAIL_COND( dst_idx >= max_clip );
- clipbuf_dst[dst_idx++]=clipbuf_src[j];
-
+ ERR_FAIL_COND(dst_idx >= max_clip);
+ clipbuf_dst[dst_idx++] = clipbuf_src[j];
}
-
// check for different sides and non coplanar
//if ( (dist0*dist1) < -CMP_EPSILON && !(edge && j)) {
- if ( (dist0*dist1) < 0 && !(edge && j)) {
+ if ((dist0 * dist1) < 0 && !(edge && j)) {
// calculate intersection
Vector3 rel = edge1_A - edge0_A;
- real_t den=clip.normal.dot( rel );
- real_t dist=-(clip.normal.dot( edge0_A )-clip.d)/den;
- Vector3 inters = edge0_A+rel*dist;
+ real_t den = clip.normal.dot(rel);
+ real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
+ Vector3 inters = edge0_A + rel * dist;
- ERR_FAIL_COND( dst_idx >= max_clip );
- clipbuf_dst[dst_idx]=inters;
+ ERR_FAIL_COND(dst_idx >= max_clip);
+ clipbuf_dst[dst_idx] = inters;
dst_idx++;
}
}
- clipbuf_len=dst_idx;
- SWAP(clipbuf_src,clipbuf_dst);
+ clipbuf_len = dst_idx;
+ SWAP(clipbuf_src, clipbuf_dst);
}
-
// generate contacts
//Plane plane_A(p_points_A[0],p_points_A[1],p_points_A[2]);
- int added=0;
+ int added = 0;
- for (int i=0;i<clipbuf_len;i++) {
+ for (int i = 0; i < clipbuf_len; i++) {
real_t d = plane_B.distance_to(clipbuf_src[i]);
/*
@@ -240,40 +225,37 @@ static void _generate_contacts_face_face(const Vector3 * p_points_A,int p_point_
continue;
*/
- Vector3 closest_B=clipbuf_src[i] - plane_B.normal*d;
+ Vector3 closest_B = clipbuf_src[i] - plane_B.normal * d;
if (p_callback->normal.dot(clipbuf_src[i]) >= p_callback->normal.dot(closest_B))
continue;
- p_callback->call(clipbuf_src[i],closest_B);
+ p_callback->call(clipbuf_src[i], closest_B);
added++;
-
}
-
}
-
-static void _generate_contacts_from_supports(const Vector3 * p_points_A,int p_point_count_A, const Vector3 * p_points_B,int p_point_count_B,_CollectorCallback *p_callback) {
-
+static void _generate_contacts_from_supports(const Vector3 *p_points_A, int p_point_count_A, const Vector3 *p_points_B, int p_point_count_B, _CollectorCallback *p_callback) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A <1 );
- ERR_FAIL_COND( p_point_count_B <1 );
+ ERR_FAIL_COND(p_point_count_A < 1);
+ ERR_FAIL_COND(p_point_count_B < 1);
#endif
-
- static const GenerateContactsFunc generate_contacts_func_table[3][3]={
+ static const GenerateContactsFunc generate_contacts_func_table[3][3] = {
+ {
+ _generate_contacts_point_point,
+ _generate_contacts_point_edge,
+ _generate_contacts_point_face,
+ },
{
- _generate_contacts_point_point,
- _generate_contacts_point_edge,
- _generate_contacts_point_face,
- },{
- 0,
- _generate_contacts_edge_edge,
- _generate_contacts_face_face,
- },{
- 0,0,
- _generate_contacts_face_face,
+ 0,
+ _generate_contacts_edge_edge,
+ _generate_contacts_face_face,
+ },
+ {
+ 0, 0,
+ _generate_contacts_face_face,
}
};
@@ -289,28 +271,25 @@ static void _generate_contacts_from_supports(const Vector3 * p_points_A,int p_po
pointcount_B = p_point_count_A;
pointcount_A = p_point_count_B;
- points_A=p_points_B;
- points_B=p_points_A;
+ points_A = p_points_B;
+ points_B = p_points_A;
} else {
pointcount_B = p_point_count_B;
pointcount_A = p_point_count_A;
- points_A=p_points_A;
- points_B=p_points_B;
+ points_A = p_points_A;
+ points_B = p_points_B;
}
- int version_A = (pointcount_A > 3 ? 3 : pointcount_A) -1;
- int version_B = (pointcount_B > 3 ? 3 : pointcount_B) -1;
+ int version_A = (pointcount_A > 3 ? 3 : pointcount_A) - 1;
+ int version_B = (pointcount_B > 3 ? 3 : pointcount_B) - 1;
GenerateContactsFunc contacts_func = generate_contacts_func_table[version_A][version_B];
ERR_FAIL_COND(!contacts_func);
- contacts_func(points_A,pointcount_A,points_B,pointcount_B,p_callback);
-
+ contacts_func(points_A, pointcount_A, points_B, pointcount_B, p_callback);
}
-
-
-template<class ShapeA, class ShapeB, bool withMargin=false>
+template <class ShapeA, class ShapeB, bool withMargin = false>
class SeparatorAxisTest {
const ShapeA *shape_A;
@@ -325,46 +304,45 @@ class SeparatorAxisTest {
Vector3 separator_axis;
public:
-
_FORCE_INLINE_ bool test_previous_axis() {
- if (callback && callback->prev_axis && *callback->prev_axis!=Vector3())
+ if (callback && callback->prev_axis && *callback->prev_axis != Vector3())
return test_axis(*callback->prev_axis);
else
return true;
}
- _FORCE_INLINE_ bool test_axis(const Vector3& p_axis) {
+ _FORCE_INLINE_ bool test_axis(const Vector3 &p_axis) {
- Vector3 axis=p_axis;
+ Vector3 axis = p_axis;
- if ( Math::abs(axis.x)<CMP_EPSILON &&
- Math::abs(axis.y)<CMP_EPSILON &&
- Math::abs(axis.z)<CMP_EPSILON ) {
+ if (Math::abs(axis.x) < CMP_EPSILON &&
+ Math::abs(axis.y) < CMP_EPSILON &&
+ Math::abs(axis.z) < CMP_EPSILON) {
// strange case, try an upwards separator
- axis=Vector3(0.0,1.0,0.0);
+ axis = Vector3(0.0, 1.0, 0.0);
}
- real_t min_A,max_A,min_B,max_B;
+ real_t min_A, max_A, min_B, max_B;
- shape_A->project_range(axis,*transform_A,min_A,max_A);
- shape_B->project_range(axis,*transform_B,min_B,max_B);
+ shape_A->project_range(axis, *transform_A, min_A, max_A);
+ shape_B->project_range(axis, *transform_B, min_B, max_B);
if (withMargin) {
- min_A-=margin_A;
- max_A+=margin_A;
- min_B-=margin_B;
- max_B+=margin_B;
+ min_A -= margin_A;
+ max_A += margin_A;
+ min_B -= margin_B;
+ max_B += margin_B;
}
- min_B -= ( max_A - min_A ) * 0.5;
- max_B += ( max_A - min_A ) * 0.5;
+ min_B -= (max_A - min_A) * 0.5;
+ max_B += (max_A - min_A) * 0.5;
- real_t dmin = min_B - ( min_A + max_A ) * 0.5;
- real_t dmax = max_B - ( min_A + max_A ) * 0.5;
+ real_t dmin = min_B - (min_A + max_A) * 0.5;
+ real_t dmax = max_B - (min_A + max_A) * 0.5;
if (dmin > 0.0 || dmax < 0.0) {
- separator_axis=axis;
+ separator_axis = axis;
return false; // doesn't contain 0
}
@@ -372,68 +350,65 @@ public:
dmin = Math::abs(dmin);
- if ( dmax < dmin ) {
- if ( dmax < best_depth ) {
- best_depth=dmax;
- best_axis=axis;
+ if (dmax < dmin) {
+ if (dmax < best_depth) {
+ best_depth = dmax;
+ best_axis = axis;
}
} else {
- if ( dmin < best_depth ) {
- best_depth=dmin;
- best_axis=-axis; // keep it as A axis
+ if (dmin < best_depth) {
+ best_depth = dmin;
+ best_axis = -axis; // keep it as A axis
}
}
return true;
}
-
_FORCE_INLINE_ void generate_contacts() {
// nothing to do, don't generate
- if (best_axis==Vector3(0.0,0.0,0.0))
+ if (best_axis == Vector3(0.0, 0.0, 0.0))
return;
if (!callback->callback) {
//just was checking intersection?
- callback->collided=true;
+ callback->collided = true;
if (callback->prev_axis)
- *callback->prev_axis=best_axis;
+ *callback->prev_axis = best_axis;
return;
}
- static const int max_supports=16;
+ static const int max_supports = 16;
Vector3 supports_A[max_supports];
int support_count_A;
- shape_A->get_supports(transform_A->basis.xform_inv(-best_axis).normalized(),max_supports,supports_A,support_count_A);
- for(int i=0;i<support_count_A;i++) {
+ shape_A->get_supports(transform_A->basis.xform_inv(-best_axis).normalized(), max_supports, supports_A, support_count_A);
+ for (int i = 0; i < support_count_A; i++) {
supports_A[i] = transform_A->xform(supports_A[i]);
}
if (withMargin) {
- for(int i=0;i<support_count_A;i++) {
- supports_A[i]+=-best_axis*margin_A;
+ for (int i = 0; i < support_count_A; i++) {
+ supports_A[i] += -best_axis * margin_A;
}
-
}
-
Vector3 supports_B[max_supports];
int support_count_B;
- shape_B->get_supports(transform_B->basis.xform_inv(best_axis).normalized(),max_supports,supports_B,support_count_B);
- for(int i=0;i<support_count_B;i++) {
+ shape_B->get_supports(transform_B->basis.xform_inv(best_axis).normalized(), max_supports, supports_B, support_count_B);
+ for (int i = 0; i < support_count_B; i++) {
supports_B[i] = transform_B->xform(supports_B[i]);
}
if (withMargin) {
- for(int i=0;i<support_count_B;i++) {
- supports_B[i]+=best_axis*margin_B;
+ for (int i = 0; i < support_count_B; i++) {
+ supports_B[i] += best_axis * margin_B;
}
}
-/*
+ /*
print_line("best depth: "+rtos(best_depth));
print_line("best axis: "+(best_axis));
for(int i=0;i<support_count_A;i++) {
@@ -445,29 +420,26 @@ public:
print_line("B-"+itos(i)+": "+supports_B[i]);
}
*/
- callback->normal=best_axis;
+ callback->normal = best_axis;
if (callback->prev_axis)
- *callback->prev_axis=best_axis;
- _generate_contacts_from_supports(supports_A,support_count_A,supports_B,support_count_B,callback);
+ *callback->prev_axis = best_axis;
+ _generate_contacts_from_supports(supports_A, support_count_A, supports_B, support_count_B, callback);
- callback->collided=true;
+ callback->collided = true;
//CollisionSolverSW::CallbackResult cbk=NULL;
//cbk(Vector3(),Vector3(),NULL);
-
}
- _FORCE_INLINE_ SeparatorAxisTest(const ShapeA *p_shape_A,const Transform& p_transform_A, const ShapeB *p_shape_B,const Transform& p_transform_B,_CollectorCallback *p_callback,real_t p_margin_A=0,real_t p_margin_B=0) {
- best_depth=1e15;
- shape_A=p_shape_A;
- shape_B=p_shape_B;
- transform_A=&p_transform_A;
- transform_B=&p_transform_B;
- callback=p_callback;
- margin_A=p_margin_A;
- margin_B=p_margin_B;
-
+ _FORCE_INLINE_ SeparatorAxisTest(const ShapeA *p_shape_A, const Transform &p_transform_A, const ShapeB *p_shape_B, const Transform &p_transform_B, _CollectorCallback *p_callback, real_t p_margin_A = 0, real_t p_margin_B = 0) {
+ best_depth = 1e15;
+ shape_A = p_shape_A;
+ shape_B = p_shape_B;
+ transform_A = &p_transform_A;
+ transform_B = &p_transform_B;
+ callback = p_callback;
+ margin_A = p_margin_A;
+ margin_B = p_margin_B;
}
-
};
/****** SAT TESTS *******/
@@ -475,92 +447,84 @@ public:
/****** SAT TESTS *******/
/****** SAT TESTS *******/
+typedef void (*CollisionFunc)(const ShapeSW *, const Transform &, const ShapeSW *, const Transform &, _CollectorCallback *p_callback, real_t, real_t);
-typedef void (*CollisionFunc)(const ShapeSW*,const Transform&,const ShapeSW*,const Transform&,_CollectorCallback *p_callback,real_t,real_t);
-
-
-template<bool withMargin>
-static void _collision_sphere_sphere(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
+template <bool withMargin>
+static void _collision_sphere_sphere(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a);
- const SphereShapeSW *sphere_B = static_cast<const SphereShapeSW*>(p_b);
+ const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a);
+ const SphereShapeSW *sphere_B = static_cast<const SphereShapeSW *>(p_b);
- SeparatorAxisTest<SphereShapeSW,SphereShapeSW,withMargin> separator(sphere_A,p_transform_a,sphere_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<SphereShapeSW, SphereShapeSW, withMargin> separator(sphere_A, p_transform_a, sphere_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
// previous axis
if (!separator.test_previous_axis())
return;
- if (!separator.test_axis( (p_transform_a.origin-p_transform_b.origin).normalized() ))
+ if (!separator.test_axis((p_transform_a.origin - p_transform_b.origin).normalized()))
return;
separator.generate_contacts();
}
-template<bool withMargin>
-static void _collision_sphere_box(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
+template <bool withMargin>
+static void _collision_sphere_box(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
+ const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a);
+ const BoxShapeSW *box_B = static_cast<const BoxShapeSW *>(p_b);
- const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a);
- const BoxShapeSW *box_B = static_cast<const BoxShapeSW*>(p_b);
-
- SeparatorAxisTest<SphereShapeSW,BoxShapeSW,withMargin> separator(sphere_A,p_transform_a,box_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<SphereShapeSW, BoxShapeSW, withMargin> separator(sphere_A, p_transform_a, box_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
// test faces
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_b.basis.get_axis(i).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
// calculate closest point to sphere
- Vector3 cnormal=p_transform_b.xform_inv( p_transform_a.origin );
+ Vector3 cnormal = p_transform_b.xform_inv(p_transform_a.origin);
- Vector3 cpoint=p_transform_b.xform( Vector3(
+ Vector3 cpoint = p_transform_b.xform(Vector3(
- (cnormal.x<0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x,
- (cnormal.y<0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y,
- (cnormal.z<0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z
- ) );
+ (cnormal.x < 0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x,
+ (cnormal.y < 0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y,
+ (cnormal.z < 0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z));
// use point to test axis
Vector3 point_axis = (p_transform_a.origin - cpoint).normalized();
- if (!separator.test_axis( point_axis ))
+ if (!separator.test_axis(point_axis))
return;
// test edges
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 axis = point_axis.cross( p_transform_b.basis.get_axis(i) ).cross( p_transform_b.basis.get_axis(i) ).normalized();
+ Vector3 axis = point_axis.cross(p_transform_b.basis.get_axis(i)).cross(p_transform_b.basis.get_axis(i)).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
separator.generate_contacts();
-
-
}
-template<bool withMargin>
-static void _collision_sphere_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
+template <bool withMargin>
+static void _collision_sphere_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a);
- const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b);
+ const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a);
+ const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b);
- SeparatorAxisTest<SphereShapeSW,CapsuleShapeSW,withMargin> separator(sphere_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<SphereShapeSW, CapsuleShapeSW, withMargin> separator(sphere_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
@@ -571,38 +535,35 @@ static void _collision_sphere_capsule(const ShapeSW *p_a,const Transform &p_tran
Vector3 capsule_ball_1 = p_transform_b.origin + capsule_axis;
- if (!separator.test_axis( (capsule_ball_1 - p_transform_a.origin).normalized() ) )
+ if (!separator.test_axis((capsule_ball_1 - p_transform_a.origin).normalized()))
return;
//capsule sphere 2, sphere
Vector3 capsule_ball_2 = p_transform_b.origin - capsule_axis;
- if (!separator.test_axis( (capsule_ball_2 - p_transform_a.origin).normalized() ) )
+ if (!separator.test_axis((capsule_ball_2 - p_transform_a.origin).normalized()))
return;
//capsule edge, sphere
Vector3 b2a = p_transform_a.origin - p_transform_b.origin;
- Vector3 axis = b2a.cross( capsule_axis ).cross( capsule_axis ).normalized();
+ Vector3 axis = b2a.cross(capsule_axis).cross(capsule_axis).normalized();
-
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
separator.generate_contacts();
}
-template<bool withMargin>
-static void _collision_sphere_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
+template <bool withMargin>
+static void _collision_sphere_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a);
- const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b);
-
- SeparatorAxisTest<SphereShapeSW,ConvexPolygonShapeSW,withMargin> separator(sphere_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a);
+ const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b);
+ SeparatorAxisTest<SphereShapeSW, ConvexPolygonShapeSW, withMargin> separator(sphere_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
@@ -616,146 +577,127 @@ static void _collision_sphere_convex_polygon(const ShapeSW *p_a,const Transform
const Vector3 *vertices = mesh.vertices.ptr();
int vertex_count = mesh.vertices.size();
-
// faces of B
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- Vector3 axis = p_transform_b.xform( faces[i].plane ).normal;
+ Vector3 axis = p_transform_b.xform(faces[i].plane).normal;
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
-
// edges of B
- for(int i=0;i<edge_count;i++) {
-
+ for (int i = 0; i < edge_count; i++) {
- Vector3 v1=p_transform_b.xform( vertices[ edges[i].a ] );
- Vector3 v2=p_transform_b.xform( vertices[ edges[i].b ] );
- Vector3 v3=p_transform_a.origin;
+ Vector3 v1 = p_transform_b.xform(vertices[edges[i].a]);
+ Vector3 v2 = p_transform_b.xform(vertices[edges[i].b]);
+ Vector3 v3 = p_transform_a.origin;
-
- Vector3 n1=v2-v1;
- Vector3 n2=v2-v3;
+ Vector3 n1 = v2 - v1;
+ Vector3 n2 = v2 - v3;
Vector3 axis = n1.cross(n2).cross(n1).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
// vertices of B
- for(int i=0;i<vertex_count;i++) {
+ for (int i = 0; i < vertex_count; i++) {
+ Vector3 v1 = p_transform_b.xform(vertices[i]);
+ Vector3 v2 = p_transform_a.origin;
- Vector3 v1=p_transform_b.xform( vertices[i] );
- Vector3 v2=p_transform_a.origin;
+ Vector3 axis = (v2 - v1).normalized();
- Vector3 axis = (v2-v1).normalized();
-
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
separator.generate_contacts();
-
-
}
-template<bool withMargin>
-static void _collision_sphere_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
+template <bool withMargin>
+static void _collision_sphere_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW*>(p_a);
- const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b);
+ const SphereShapeSW *sphere_A = static_cast<const SphereShapeSW *>(p_a);
+ const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b);
+ SeparatorAxisTest<SphereShapeSW, FaceShapeSW, withMargin> separator(sphere_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
-
- SeparatorAxisTest<SphereShapeSW,FaceShapeSW,withMargin> separator(sphere_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
-
-
- Vector3 vertex[3]={
- p_transform_b.xform( face_B->vertex[0] ),
- p_transform_b.xform( face_B->vertex[1] ),
- p_transform_b.xform( face_B->vertex[2] ),
+ Vector3 vertex[3] = {
+ p_transform_b.xform(face_B->vertex[0]),
+ p_transform_b.xform(face_B->vertex[1]),
+ p_transform_b.xform(face_B->vertex[2]),
};
- if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() ))
+ if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized()))
return;
// edges and points of B
- for(int i=0;i<3;i++) {
-
+ for (int i = 0; i < 3; i++) {
- Vector3 n1=vertex[i]-p_transform_a.origin;
+ Vector3 n1 = vertex[i] - p_transform_a.origin;
- if (!separator.test_axis( n1.normalized() )) {
+ if (!separator.test_axis(n1.normalized())) {
return;
}
- Vector3 n2=vertex[(i+1)%3]-vertex[i];
+ Vector3 n2 = vertex[(i + 1) % 3] - vertex[i];
Vector3 axis = n1.cross(n2).cross(n2).normalized();
- if (!separator.test_axis( axis )) {
+ if (!separator.test_axis(axis)) {
return;
}
-
}
separator.generate_contacts();
}
+template <bool withMargin>
+static void _collision_box_box(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_box_box(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
+ const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a);
+ const BoxShapeSW *box_B = static_cast<const BoxShapeSW *>(p_b);
- const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a);
- const BoxShapeSW *box_B = static_cast<const BoxShapeSW*>(p_b);
-
- SeparatorAxisTest<BoxShapeSW,BoxShapeSW,withMargin> separator(box_A,p_transform_a,box_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<BoxShapeSW, BoxShapeSW, withMargin> separator(box_A, p_transform_a, box_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
// test faces of A
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_a.basis.get_axis(i).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
// test faces of B
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_b.basis.get_axis(i).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
// test combined edges
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- Vector3 axis = p_transform_a.basis.get_axis(i).cross( p_transform_b.basis.get_axis(j) );
+ Vector3 axis = p_transform_a.basis.get_axis(i).cross(p_transform_b.basis.get_axis(j));
- if (axis.length_squared()<CMP_EPSILON)
+ if (axis.length_squared() < CMP_EPSILON)
continue;
axis.normalize();
-
- if (!separator.test_axis( axis )) {
+ if (!separator.test_axis(axis)) {
return;
}
}
@@ -768,110 +710,103 @@ static void _collision_box_box(const ShapeSW *p_a,const Transform &p_transform_a
Vector3 ab_vec = p_transform_b.origin - p_transform_a.origin;
- Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec );
+ Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec);
- Vector3 support_a=p_transform_a.xform( Vector3(
+ Vector3 support_a = p_transform_a.xform(Vector3(
- (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
- (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
- (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z
- ) );
+ (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
+ (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
+ (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z));
+ Vector3 cnormal_b = p_transform_b.basis.xform_inv(-ab_vec);
- Vector3 cnormal_b=p_transform_b.basis.xform_inv( -ab_vec );
+ Vector3 support_b = p_transform_b.xform(Vector3(
- Vector3 support_b=p_transform_b.xform( Vector3(
+ (cnormal_b.x < 0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x,
+ (cnormal_b.y < 0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y,
+ (cnormal_b.z < 0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z));
- (cnormal_b.x<0) ? -box_B->get_half_extents().x : box_B->get_half_extents().x,
- (cnormal_b.y<0) ? -box_B->get_half_extents().y : box_B->get_half_extents().y,
- (cnormal_b.z<0) ? -box_B->get_half_extents().z : box_B->get_half_extents().z
- ) );
+ Vector3 axis_ab = (support_a - support_b);
- Vector3 axis_ab = (support_a-support_b);
-
- if (!separator.test_axis( axis_ab.normalized() )) {
+ if (!separator.test_axis(axis_ab.normalized())) {
return;
}
//now try edges, which become cylinders!
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
//a ->b
Vector3 axis_a = p_transform_a.basis.get_axis(i);
- if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() ))
+ if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized()))
return;
//b ->a
Vector3 axis_b = p_transform_b.basis.get_axis(i);
- if (!separator.test_axis( axis_ab.cross(axis_b).cross(axis_b).normalized() ))
+ if (!separator.test_axis(axis_ab.cross(axis_b).cross(axis_b).normalized()))
return;
-
}
}
separator.generate_contacts();
-
-
}
-template<bool withMargin>
-static void _collision_box_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
+template <bool withMargin>
+static void _collision_box_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a);
- const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b);
+ const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a);
+ const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b);
- SeparatorAxisTest<BoxShapeSW,CapsuleShapeSW,withMargin> separator(box_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<BoxShapeSW, CapsuleShapeSW, withMargin> separator(box_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
// faces of A
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_a.basis.get_axis(i);
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
-
Vector3 cyl_axis = p_transform_b.basis.get_axis(2).normalized();
// edges of A, capsule cylinder
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
// cylinder
Vector3 box_axis = p_transform_a.basis.get_axis(i);
- Vector3 axis = box_axis.cross( cyl_axis );
+ Vector3 axis = box_axis.cross(cyl_axis);
if (axis.length_squared() < CMP_EPSILON)
continue;
- if (!separator.test_axis( axis.normalized() ))
+ if (!separator.test_axis(axis.normalized()))
return;
}
// points of A, capsule cylinder
// this sure could be made faster somehow..
- for (int i=0;i<2;i++) {
- for (int j=0;j<2;j++) {
- for (int k=0;k<2;k++) {
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < 2; j++) {
+ for (int k = 0; k < 2; k++) {
Vector3 he = box_A->get_half_extents();
- he.x*=(i*2-1);
- he.y*=(j*2-1);
- he.z*=(k*2-1);
- Vector3 point=p_transform_a.origin;
- for(int l=0;l<3;l++)
- point+=p_transform_a.basis.get_axis(l)*he[l];
+ he.x *= (i * 2 - 1);
+ he.y *= (j * 2 - 1);
+ he.z *= (k * 2 - 1);
+ Vector3 point = p_transform_a.origin;
+ for (int l = 0; l < 3; l++)
+ point += p_transform_a.basis.get_axis(l) * he[l];
//Vector3 axis = (point - cyl_axis * cyl_axis.dot(point)).normalized();
- Vector3 axis = Plane(cyl_axis,0).project(point).normalized();
+ Vector3 axis = Plane(cyl_axis, 0).project(point).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
}
@@ -879,58 +814,51 @@ static void _collision_box_capsule(const ShapeSW *p_a,const Transform &p_transfo
// capsule balls, edges of A
- for (int i=0;i<2;i++) {
-
-
- Vector3 capsule_axis = p_transform_b.basis.get_axis(2)*(capsule_B->get_height()*0.5);
+ for (int i = 0; i < 2; i++) {
- Vector3 sphere_pos = p_transform_b.origin + ((i==0)?capsule_axis:-capsule_axis);
+ Vector3 capsule_axis = p_transform_b.basis.get_axis(2) * (capsule_B->get_height() * 0.5);
+ Vector3 sphere_pos = p_transform_b.origin + ((i == 0) ? capsule_axis : -capsule_axis);
- Vector3 cnormal=p_transform_a.xform_inv( sphere_pos );
+ Vector3 cnormal = p_transform_a.xform_inv(sphere_pos);
- Vector3 cpoint=p_transform_a.xform( Vector3(
+ Vector3 cpoint = p_transform_a.xform(Vector3(
- (cnormal.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
- (cnormal.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
- (cnormal.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z
- ) );
+ (cnormal.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
+ (cnormal.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
+ (cnormal.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z));
// use point to test axis
Vector3 point_axis = (sphere_pos - cpoint).normalized();
- if (!separator.test_axis( point_axis ))
+ if (!separator.test_axis(point_axis))
return;
// test edges of A
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 axis = point_axis.cross( p_transform_a.basis.get_axis(i) ).cross( p_transform_a.basis.get_axis(i) ).normalized();
+ Vector3 axis = point_axis.cross(p_transform_a.basis.get_axis(i)).cross(p_transform_a.basis.get_axis(i)).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
}
-
separator.generate_contacts();
}
-template<bool withMargin>
-static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
+template <bool withMargin>
+static void _collision_box_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
+ const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a);
+ const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b);
- const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a);
- const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b);
-
- SeparatorAxisTest<BoxShapeSW,ConvexPolygonShapeSW,withMargin> separator(box_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<BoxShapeSW, ConvexPolygonShapeSW, withMargin> separator(box_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
-
const Geometry::MeshData &mesh = convex_polygon_B->get_mesh();
const Geometry::MeshData::Face *faces = mesh.faces.ptr();
@@ -941,97 +869,92 @@ static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_
int vertex_count = mesh.vertices.size();
// faces of A
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_a.basis.get_axis(i).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// faces of B
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- Vector3 axis = p_transform_b.xform( faces[i].plane ).normal;
+ Vector3 axis = p_transform_b.xform(faces[i].plane).normal;
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// A<->B edges
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 e1 = p_transform_a.basis.get_axis(i);
- for (int j=0;j<edge_count;j++) {
+ for (int j = 0; j < edge_count; j++) {
- Vector3 e2=p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]);
+ Vector3 e2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]);
- Vector3 axis=e1.cross( e2 ).normalized();
+ Vector3 axis = e1.cross(e2).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
}
if (withMargin) {
// calculate closest points between vertices and box edges
- for(int v=0;v<vertex_count;v++) {
-
+ for (int v = 0; v < vertex_count; v++) {
Vector3 vtxb = p_transform_b.xform(vertices[v]);
Vector3 ab_vec = vtxb - p_transform_a.origin;
- Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec );
+ Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec);
- Vector3 support_a=p_transform_a.xform( Vector3(
+ Vector3 support_a = p_transform_a.xform(Vector3(
- (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
- (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
- (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z
- ) );
+ (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
+ (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
+ (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z));
+ Vector3 axis_ab = support_a - vtxb;
- Vector3 axis_ab = support_a-vtxb;
-
- if (!separator.test_axis( axis_ab.normalized() )) {
+ if (!separator.test_axis(axis_ab.normalized())) {
return;
}
//now try edges, which become cylinders!
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
//a ->b
Vector3 axis_a = p_transform_a.basis.get_axis(i);
- if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() ))
+ if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized()))
return;
}
}
//convex edges and box points
- for (int i=0;i<2;i++) {
- for (int j=0;j<2;j++) {
- for (int k=0;k<2;k++) {
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < 2; j++) {
+ for (int k = 0; k < 2; k++) {
Vector3 he = box_A->get_half_extents();
- he.x*=(i*2-1);
- he.y*=(j*2-1);
- he.z*=(k*2-1);
- Vector3 point=p_transform_a.origin;
- for(int l=0;l<3;l++)
- point+=p_transform_a.basis.get_axis(l)*he[l];
-
- for(int e=0;e<edge_count;e++) {
+ he.x *= (i * 2 - 1);
+ he.y *= (j * 2 - 1);
+ he.z *= (k * 2 - 1);
+ Vector3 point = p_transform_a.origin;
+ for (int l = 0; l < 3; l++)
+ point += p_transform_a.basis.get_axis(l) * he[l];
- Vector3 p1=p_transform_b.xform(vertices[edges[e].a]);
- Vector3 p2=p_transform_b.xform(vertices[edges[e].b]);
- Vector3 n = (p2-p1);
+ for (int e = 0; e < edge_count; e++) {
+ Vector3 p1 = p_transform_b.xform(vertices[edges[e].a]);
+ Vector3 p2 = p_transform_b.xform(vertices[edges[e].b]);
+ Vector3 n = (p2 - p1);
- if (!separator.test_axis( (point-p2).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((point - p2).cross(n).cross(n).normalized()))
return;
}
}
@@ -1040,130 +963,119 @@ static void _collision_box_convex_polygon(const ShapeSW *p_a,const Transform &p_
}
separator.generate_contacts();
-
-
}
+template <bool withMargin>
+static void _collision_box_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_box_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
-
- const BoxShapeSW *box_A = static_cast<const BoxShapeSW*>(p_a);
- const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b);
+ const BoxShapeSW *box_A = static_cast<const BoxShapeSW *>(p_a);
+ const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b);
- SeparatorAxisTest<BoxShapeSW,FaceShapeSW,withMargin> separator(box_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<BoxShapeSW, FaceShapeSW, withMargin> separator(box_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
- Vector3 vertex[3]={
- p_transform_b.xform( face_B->vertex[0] ),
- p_transform_b.xform( face_B->vertex[1] ),
- p_transform_b.xform( face_B->vertex[2] ),
+ Vector3 vertex[3] = {
+ p_transform_b.xform(face_B->vertex[0]),
+ p_transform_b.xform(face_B->vertex[1]),
+ p_transform_b.xform(face_B->vertex[2]),
};
- if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() ))
+ if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized()))
return;
// faces of A
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis = p_transform_a.basis.get_axis(i).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// combined edges
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 e=vertex[i]-vertex[(i+1)%3];
+ Vector3 e = vertex[i] - vertex[(i + 1) % 3];
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
Vector3 axis = p_transform_a.basis.get_axis(j);
- if (!separator.test_axis( e.cross(axis).normalized() ))
+ if (!separator.test_axis(e.cross(axis).normalized()))
return;
}
-
}
if (withMargin) {
// calculate closest points between vertices and box edges
- for(int v=0;v<3;v++) {
-
+ for (int v = 0; v < 3; v++) {
Vector3 ab_vec = vertex[v] - p_transform_a.origin;
- Vector3 cnormal_a=p_transform_a.basis.xform_inv( ab_vec );
+ Vector3 cnormal_a = p_transform_a.basis.xform_inv(ab_vec);
- Vector3 support_a=p_transform_a.xform( Vector3(
+ Vector3 support_a = p_transform_a.xform(Vector3(
- (cnormal_a.x<0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
- (cnormal_a.y<0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
- (cnormal_a.z<0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z
- ) );
+ (cnormal_a.x < 0) ? -box_A->get_half_extents().x : box_A->get_half_extents().x,
+ (cnormal_a.y < 0) ? -box_A->get_half_extents().y : box_A->get_half_extents().y,
+ (cnormal_a.z < 0) ? -box_A->get_half_extents().z : box_A->get_half_extents().z));
+ Vector3 axis_ab = support_a - vertex[v];
- Vector3 axis_ab = support_a-vertex[v];
-
- if (!separator.test_axis( axis_ab.normalized() )) {
+ if (!separator.test_axis(axis_ab.normalized())) {
return;
}
//now try edges, which become cylinders!
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
//a ->b
Vector3 axis_a = p_transform_a.basis.get_axis(i);
- if (!separator.test_axis( axis_ab.cross(axis_a).cross(axis_a).normalized() ))
+ if (!separator.test_axis(axis_ab.cross(axis_a).cross(axis_a).normalized()))
return;
}
}
//convex edges and box points, there has to be a way to speed up this (get closest point?)
- for (int i=0;i<2;i++) {
- for (int j=0;j<2;j++) {
- for (int k=0;k<2;k++) {
+ for (int i = 0; i < 2; i++) {
+ for (int j = 0; j < 2; j++) {
+ for (int k = 0; k < 2; k++) {
Vector3 he = box_A->get_half_extents();
- he.x*=(i*2-1);
- he.y*=(j*2-1);
- he.z*=(k*2-1);
- Vector3 point=p_transform_a.origin;
- for(int l=0;l<3;l++)
- point+=p_transform_a.basis.get_axis(l)*he[l];
+ he.x *= (i * 2 - 1);
+ he.y *= (j * 2 - 1);
+ he.z *= (k * 2 - 1);
+ Vector3 point = p_transform_a.origin;
+ for (int l = 0; l < 3; l++)
+ point += p_transform_a.basis.get_axis(l) * he[l];
- for(int e=0;e<3;e++) {
+ for (int e = 0; e < 3; e++) {
- Vector3 p1=vertex[e];
- Vector3 p2=vertex[(e+1)%3];
+ Vector3 p1 = vertex[e];
+ Vector3 p2 = vertex[(e + 1) % 3];
- Vector3 n = (p2-p1);
+ Vector3 n = (p2 - p1);
- if (!separator.test_axis( (point-p2).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((point - p2).cross(n).cross(n).normalized()))
return;
}
}
}
}
-
}
separator.generate_contacts();
-
}
+template <bool withMargin>
+static void _collision_capsule_capsule(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_capsule_capsule(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
- const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a);
- const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW*>(p_b);
+ const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a);
+ const CapsuleShapeSW *capsule_B = static_cast<const CapsuleShapeSW *>(p_b);
- SeparatorAxisTest<CapsuleShapeSW,CapsuleShapeSW,withMargin> separator(capsule_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<CapsuleShapeSW, CapsuleShapeSW, withMargin> separator(capsule_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
@@ -1180,49 +1092,45 @@ static void _collision_capsule_capsule(const ShapeSW *p_a,const Transform &p_tra
//balls-balls
- if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_1 ).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).normalized()))
return;
- if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_2 ).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).normalized()))
return;
- if (!separator.test_axis( (capsule_A_ball_2 - capsule_B_ball_1 ).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_1).normalized()))
return;
- if (!separator.test_axis( (capsule_A_ball_2 - capsule_B_ball_2 ).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_2 - capsule_B_ball_2).normalized()))
return;
-
// edges-balls
- if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_1 ).cross(capsule_A_axis).cross(capsule_A_axis).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_1).cross(capsule_A_axis).cross(capsule_A_axis).normalized()))
return;
- if (!separator.test_axis( (capsule_A_ball_1 - capsule_B_ball_2 ).cross(capsule_A_axis).cross(capsule_A_axis).normalized() ) )
+ if (!separator.test_axis((capsule_A_ball_1 - capsule_B_ball_2).cross(capsule_A_axis).cross(capsule_A_axis).normalized()))
return;
- if (!separator.test_axis( (capsule_B_ball_1 - capsule_A_ball_1 ).cross(capsule_B_axis).cross(capsule_B_axis).normalized() ) )
+ if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_1).cross(capsule_B_axis).cross(capsule_B_axis).normalized()))
return;
- if (!separator.test_axis( (capsule_B_ball_1 - capsule_A_ball_2 ).cross(capsule_B_axis).cross(capsule_B_axis).normalized() ) )
+ if (!separator.test_axis((capsule_B_ball_1 - capsule_A_ball_2).cross(capsule_B_axis).cross(capsule_B_axis).normalized()))
return;
// edges
- if (!separator.test_axis( capsule_A_axis.cross(capsule_B_axis).normalized() ) )
+ if (!separator.test_axis(capsule_A_axis.cross(capsule_B_axis).normalized()))
return;
-
separator.generate_contacts();
-
}
-template<bool withMargin>
-static void _collision_capsule_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
+template <bool withMargin>
+static void _collision_capsule_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
- const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a);
- const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b);
+ const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a);
+ const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b);
- SeparatorAxisTest<CapsuleShapeSW,ConvexPolygonShapeSW,withMargin> separator(capsule_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<CapsuleShapeSW, ConvexPolygonShapeSW, withMargin> separator(capsule_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
@@ -1236,127 +1144,113 @@ static void _collision_capsule_convex_polygon(const ShapeSW *p_a,const Transform
const Vector3 *vertices = mesh.vertices.ptr();
// faces of B
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
- Vector3 axis = p_transform_b.xform( faces[i].plane ).normal;
+ Vector3 axis = p_transform_b.xform(faces[i].plane).normal;
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// edges of B, capsule cylinder
- for (int i=0;i<edge_count;i++) {
+ for (int i = 0; i < edge_count; i++) {
// cylinder
- Vector3 edge_axis = p_transform_b.basis.xform( vertices[ edges[i].a] ) - p_transform_b.basis.xform( vertices[ edges[i].b] );
- Vector3 axis = edge_axis.cross( p_transform_a.basis.get_axis(2) ).normalized();
+ Vector3 edge_axis = p_transform_b.basis.xform(vertices[edges[i].a]) - p_transform_b.basis.xform(vertices[edges[i].b]);
+ Vector3 axis = edge_axis.cross(p_transform_a.basis.get_axis(2)).normalized();
-
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// capsule balls, edges of B
- for (int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
// edges of B, capsule cylinder
- Vector3 capsule_axis = p_transform_a.basis.get_axis(2)*(capsule_A->get_height()*0.5);
-
- Vector3 sphere_pos = p_transform_a.origin + ((i==0)?capsule_axis:-capsule_axis);
+ Vector3 capsule_axis = p_transform_a.basis.get_axis(2) * (capsule_A->get_height() * 0.5);
- for (int j=0;j<edge_count;j++) {
+ Vector3 sphere_pos = p_transform_a.origin + ((i == 0) ? capsule_axis : -capsule_axis);
+ for (int j = 0; j < edge_count; j++) {
- Vector3 n1=sphere_pos - p_transform_b.xform( vertices[ edges[j].a] );
- Vector3 n2=p_transform_b.basis.xform( vertices[ edges[j].a] ) - p_transform_b.basis.xform( vertices[ edges[j].b] );
+ Vector3 n1 = sphere_pos - p_transform_b.xform(vertices[edges[j].a]);
+ Vector3 n2 = p_transform_b.basis.xform(vertices[edges[j].a]) - p_transform_b.basis.xform(vertices[edges[j].b]);
Vector3 axis = n1.cross(n2).cross(n2).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
}
-
separator.generate_contacts();
-
}
+template <bool withMargin>
+static void _collision_capsule_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_capsule_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
- const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW*>(p_a);
- const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b);
-
- SeparatorAxisTest<CapsuleShapeSW,FaceShapeSW,withMargin> separator(capsule_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ const CapsuleShapeSW *capsule_A = static_cast<const CapsuleShapeSW *>(p_a);
+ const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b);
+ SeparatorAxisTest<CapsuleShapeSW, FaceShapeSW, withMargin> separator(capsule_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
-
- Vector3 vertex[3]={
- p_transform_b.xform( face_B->vertex[0] ),
- p_transform_b.xform( face_B->vertex[1] ),
- p_transform_b.xform( face_B->vertex[2] ),
+ Vector3 vertex[3] = {
+ p_transform_b.xform(face_B->vertex[0]),
+ p_transform_b.xform(face_B->vertex[1]),
+ p_transform_b.xform(face_B->vertex[2]),
};
- if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() ))
+ if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized()))
return;
// edges of B, capsule cylinder
- Vector3 capsule_axis = p_transform_a.basis.get_axis(2)*(capsule_A->get_height()*0.5);
+ Vector3 capsule_axis = p_transform_a.basis.get_axis(2) * (capsule_A->get_height() * 0.5);
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
// edge-cylinder
- Vector3 edge_axis = vertex[i]-vertex[(i+1)%3];
- Vector3 axis = edge_axis.cross( capsule_axis ).normalized();
+ Vector3 edge_axis = vertex[i] - vertex[(i + 1) % 3];
+ Vector3 axis = edge_axis.cross(capsule_axis).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
- if (!separator.test_axis( (p_transform_a.origin-vertex[i]).cross(capsule_axis).cross(capsule_axis).normalized() ))
+ if (!separator.test_axis((p_transform_a.origin - vertex[i]).cross(capsule_axis).cross(capsule_axis).normalized()))
return;
- for (int j=0;j<2;j++) {
+ for (int j = 0; j < 2; j++) {
// point-spheres
- Vector3 sphere_pos = p_transform_a.origin + ( (j==0) ? capsule_axis : -capsule_axis );
+ Vector3 sphere_pos = p_transform_a.origin + ((j == 0) ? capsule_axis : -capsule_axis);
- Vector3 n1=sphere_pos - vertex[i];
+ Vector3 n1 = sphere_pos - vertex[i];
- if (!separator.test_axis( n1.normalized() ))
+ if (!separator.test_axis(n1.normalized()))
return;
- Vector3 n2=edge_axis;
+ Vector3 n2 = edge_axis;
axis = n1.cross(n2).cross(n2);
- if (!separator.test_axis( axis.normalized() ))
+ if (!separator.test_axis(axis.normalized()))
return;
-
-
}
-
}
-
separator.generate_contacts();
-
}
+template <bool withMargin>
+static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a,const Transform &p_transform_a,const ShapeSW *p_b,const Transform &p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
-
-
- const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW*>(p_a);
- const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW*>(p_b);
+ const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW *>(p_a);
+ const ConvexPolygonShapeSW *convex_polygon_B = static_cast<const ConvexPolygonShapeSW *>(p_b);
- SeparatorAxisTest<ConvexPolygonShapeSW,ConvexPolygonShapeSW,withMargin> separator(convex_polygon_A,p_transform_a,convex_polygon_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<ConvexPolygonShapeSW, ConvexPolygonShapeSW, withMargin> separator(convex_polygon_A, p_transform_a, convex_polygon_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
if (!separator.test_previous_axis())
return;
@@ -1380,107 +1274,97 @@ static void _collision_convex_polygon_convex_polygon(const ShapeSW *p_a,const Tr
int vertex_count_B = mesh_B.vertices.size();
// faces of A
- for (int i=0;i<face_count_A;i++) {
+ for (int i = 0; i < face_count_A; i++) {
- Vector3 axis = p_transform_a.xform( faces_A[i].plane ).normal;
+ Vector3 axis = p_transform_a.xform(faces_A[i].plane).normal;
//Vector3 axis = p_transform_a.basis.xform( faces_A[i].plane.normal ).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// faces of B
- for (int i=0;i<face_count_B;i++) {
+ for (int i = 0; i < face_count_B; i++) {
- Vector3 axis = p_transform_b.xform( faces_B[i].plane ).normal;
+ Vector3 axis = p_transform_b.xform(faces_B[i].plane).normal;
//Vector3 axis = p_transform_b.basis.xform( faces_B[i].plane.normal ).normalized();
-
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
// A<->B edges
- for (int i=0;i<edge_count_A;i++) {
+ for (int i = 0; i < edge_count_A; i++) {
- Vector3 e1=p_transform_a.basis.xform( vertices_A[ edges_A[i].a] ) -p_transform_a.basis.xform( vertices_A[ edges_A[i].b] );
+ Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]) - p_transform_a.basis.xform(vertices_A[edges_A[i].b]);
- for (int j=0;j<edge_count_B;j++) {
+ for (int j = 0; j < edge_count_B; j++) {
- Vector3 e2=p_transform_b.basis.xform( vertices_B[ edges_B[j].a] ) -p_transform_b.basis.xform( vertices_B[ edges_B[j].b] );
+ Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[j].a]) - p_transform_b.basis.xform(vertices_B[edges_B[j].b]);
- Vector3 axis=e1.cross( e2 ).normalized();
+ Vector3 axis = e1.cross(e2).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
-
}
}
if (withMargin) {
//vertex-vertex
- for(int i=0;i<vertex_count_A;i++) {
+ for (int i = 0; i < vertex_count_A; i++) {
Vector3 va = p_transform_a.xform(vertices_A[i]);
- for(int j=0;j<vertex_count_B;j++) {
+ for (int j = 0; j < vertex_count_B; j++) {
- if (!separator.test_axis( (va-p_transform_b.xform(vertices_B[j])).normalized() ))
+ if (!separator.test_axis((va - p_transform_b.xform(vertices_B[j])).normalized()))
return;
-
}
}
//edge-vertex( hsell)
- for (int i=0;i<edge_count_A;i++) {
-
- Vector3 e1=p_transform_a.basis.xform( vertices_A[ edges_A[i].a] );
- Vector3 e2=p_transform_a.basis.xform( vertices_A[ edges_A[i].b] );
- Vector3 n = (e2-e1);
+ for (int i = 0; i < edge_count_A; i++) {
- for(int j=0;j<vertex_count_B;j++) {
+ Vector3 e1 = p_transform_a.basis.xform(vertices_A[edges_A[i].a]);
+ Vector3 e2 = p_transform_a.basis.xform(vertices_A[edges_A[i].b]);
+ Vector3 n = (e2 - e1);
- Vector3 e3=p_transform_b.xform(vertices_B[j]);
+ for (int j = 0; j < vertex_count_B; j++) {
+ Vector3 e3 = p_transform_b.xform(vertices_B[j]);
- if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized()))
return;
}
}
- for (int i=0;i<edge_count_B;i++) {
+ for (int i = 0; i < edge_count_B; i++) {
- Vector3 e1=p_transform_b.basis.xform( vertices_B[ edges_B[i].a] );
- Vector3 e2=p_transform_b.basis.xform( vertices_B[ edges_B[i].b] );
- Vector3 n = (e2-e1);
+ Vector3 e1 = p_transform_b.basis.xform(vertices_B[edges_B[i].a]);
+ Vector3 e2 = p_transform_b.basis.xform(vertices_B[edges_B[i].b]);
+ Vector3 n = (e2 - e1);
- for(int j=0;j<vertex_count_A;j++) {
+ for (int j = 0; j < vertex_count_A; j++) {
- Vector3 e3=p_transform_a.xform(vertices_A[j]);
+ Vector3 e3 = p_transform_a.xform(vertices_A[j]);
-
- if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized()))
return;
}
}
-
-
}
separator.generate_contacts();
-
}
+template <bool withMargin>
+static void _collision_convex_polygon_face(const ShapeSW *p_a, const Transform &p_transform_a, const ShapeSW *p_b, const Transform &p_transform_b, _CollectorCallback *p_collector, real_t p_margin_a, real_t p_margin_b) {
-template<bool withMargin>
-static void _collision_convex_polygon_face(const ShapeSW *p_a,const Transform &p_transform_a, const ShapeSW *p_b,const Transform& p_transform_b,_CollectorCallback *p_collector,real_t p_margin_a,real_t p_margin_b) {
+ const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW *>(p_a);
+ const FaceShapeSW *face_B = static_cast<const FaceShapeSW *>(p_b);
-
- const ConvexPolygonShapeSW *convex_polygon_A = static_cast<const ConvexPolygonShapeSW*>(p_a);
- const FaceShapeSW *face_B = static_cast<const FaceShapeSW*>(p_b);
-
- SeparatorAxisTest<ConvexPolygonShapeSW,FaceShapeSW,withMargin> separator(convex_polygon_A,p_transform_a,face_B,p_transform_b,p_collector,p_margin_a,p_margin_b);
+ SeparatorAxisTest<ConvexPolygonShapeSW, FaceShapeSW, withMargin> separator(convex_polygon_A, p_transform_a, face_B, p_transform_b, p_collector, p_margin_a, p_margin_b);
const Geometry::MeshData &mesh = convex_polygon_A->get_mesh();
@@ -1491,207 +1375,192 @@ static void _collision_convex_polygon_face(const ShapeSW *p_a,const Transform &p
const Vector3 *vertices = mesh.vertices.ptr();
int vertex_count = mesh.vertices.size();
-
-
- Vector3 vertex[3]={
- p_transform_b.xform( face_B->vertex[0] ),
- p_transform_b.xform( face_B->vertex[1] ),
- p_transform_b.xform( face_B->vertex[2] ),
+ Vector3 vertex[3] = {
+ p_transform_b.xform(face_B->vertex[0]),
+ p_transform_b.xform(face_B->vertex[1]),
+ p_transform_b.xform(face_B->vertex[2]),
};
- if (!separator.test_axis( (vertex[0]-vertex[2]).cross(vertex[0]-vertex[1]).normalized() ))
+ if (!separator.test_axis((vertex[0] - vertex[2]).cross(vertex[0] - vertex[1]).normalized()))
return;
-
// faces of A
- for (int i=0;i<face_count;i++) {
+ for (int i = 0; i < face_count; i++) {
//Vector3 axis = p_transform_a.xform( faces[i].plane ).normal;
- Vector3 axis = p_transform_a.basis.xform( faces[i].plane.normal ).normalized();
+ Vector3 axis = p_transform_a.basis.xform(faces[i].plane.normal).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
-
// A<->B edges
- for (int i=0;i<edge_count;i++) {
+ for (int i = 0; i < edge_count; i++) {
- Vector3 e1=p_transform_a.xform( vertices[edges[i].a] ) - p_transform_a.xform( vertices[edges[i].b] );
+ Vector3 e1 = p_transform_a.xform(vertices[edges[i].a]) - p_transform_a.xform(vertices[edges[i].b]);
- for (int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- Vector3 e2=vertex[j]-vertex[(j+1)%3];
+ Vector3 e2 = vertex[j] - vertex[(j + 1) % 3];
- Vector3 axis=e1.cross( e2 ).normalized();
+ Vector3 axis = e1.cross(e2).normalized();
- if (!separator.test_axis( axis ))
+ if (!separator.test_axis(axis))
return;
}
}
-
if (withMargin) {
//vertex-vertex
- for(int i=0;i<vertex_count;i++) {
+ for (int i = 0; i < vertex_count; i++) {
Vector3 va = p_transform_a.xform(vertices[i]);
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- if (!separator.test_axis( (va-vertex[j]).normalized() ))
+ if (!separator.test_axis((va - vertex[j]).normalized()))
return;
-
}
}
//edge-vertex( hsell)
- for (int i=0;i<edge_count;i++) {
+ for (int i = 0; i < edge_count; i++) {
- Vector3 e1=p_transform_a.basis.xform( vertices[ edges[i].a] );
- Vector3 e2=p_transform_a.basis.xform( vertices[ edges[i].b] );
- Vector3 n = (e2-e1);
+ Vector3 e1 = p_transform_a.basis.xform(vertices[edges[i].a]);
+ Vector3 e2 = p_transform_a.basis.xform(vertices[edges[i].b]);
+ Vector3 n = (e2 - e1);
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- Vector3 e3=vertex[j];
+ Vector3 e3 = vertex[j];
-
- if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized()))
return;
}
}
- for (int i=0;i<3;i++) {
-
- Vector3 e1=vertex[i];
- Vector3 e2=vertex[(i+1)%3];
- Vector3 n = (e2-e1);
+ for (int i = 0; i < 3; i++) {
- for(int j=0;j<vertex_count;j++) {
+ Vector3 e1 = vertex[i];
+ Vector3 e2 = vertex[(i + 1) % 3];
+ Vector3 n = (e2 - e1);
- Vector3 e3=p_transform_a.xform(vertices[j]);
+ for (int j = 0; j < vertex_count; j++) {
+ Vector3 e3 = p_transform_a.xform(vertices[j]);
- if (!separator.test_axis( (e1-e3).cross(n).cross(n).normalized() ))
+ if (!separator.test_axis((e1 - e3).cross(n).cross(n).normalized()))
return;
}
}
}
separator.generate_contacts();
-
}
-
-bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata,bool p_swap,Vector3* r_prev_axis,real_t p_margin_a,real_t p_margin_b) {
-
- PhysicsServer::ShapeType type_A=p_shape_A->get_type();
-
- ERR_FAIL_COND_V(type_A==PhysicsServer::SHAPE_PLANE,false);
- ERR_FAIL_COND_V(type_A==PhysicsServer::SHAPE_RAY,false);
- ERR_FAIL_COND_V(p_shape_A->is_concave(),false);
-
- PhysicsServer::ShapeType type_B=p_shape_B->get_type();
-
- ERR_FAIL_COND_V(type_B==PhysicsServer::SHAPE_PLANE,false);
- ERR_FAIL_COND_V(type_B==PhysicsServer::SHAPE_RAY,false);
- ERR_FAIL_COND_V(p_shape_B->is_concave(),false);
-
-
- static const CollisionFunc collision_table[5][5]={
- {_collision_sphere_sphere<false>,
- _collision_sphere_box<false>,
- _collision_sphere_capsule<false>,
- _collision_sphere_convex_polygon<false>,
- _collision_sphere_face<false>},
- {0,
- _collision_box_box<false>,
- _collision_box_capsule<false>,
- _collision_box_convex_polygon<false>,
- _collision_box_face<false>},
- {0,
- 0,
- _collision_capsule_capsule<false>,
- _collision_capsule_convex_polygon<false>,
- _collision_capsule_face<false>},
- {0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<false>,
- _collision_convex_polygon_face<false>},
- {0,
- 0,
- 0,
- 0,
- 0},
+bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap, Vector3 *r_prev_axis, real_t p_margin_a, real_t p_margin_b) {
+
+ PhysicsServer::ShapeType type_A = p_shape_A->get_type();
+
+ ERR_FAIL_COND_V(type_A == PhysicsServer::SHAPE_PLANE, false);
+ ERR_FAIL_COND_V(type_A == PhysicsServer::SHAPE_RAY, false);
+ ERR_FAIL_COND_V(p_shape_A->is_concave(), false);
+
+ PhysicsServer::ShapeType type_B = p_shape_B->get_type();
+
+ ERR_FAIL_COND_V(type_B == PhysicsServer::SHAPE_PLANE, false);
+ ERR_FAIL_COND_V(type_B == PhysicsServer::SHAPE_RAY, false);
+ ERR_FAIL_COND_V(p_shape_B->is_concave(), false);
+
+ static const CollisionFunc collision_table[5][5] = {
+ { _collision_sphere_sphere<false>,
+ _collision_sphere_box<false>,
+ _collision_sphere_capsule<false>,
+ _collision_sphere_convex_polygon<false>,
+ _collision_sphere_face<false> },
+ { 0,
+ _collision_box_box<false>,
+ _collision_box_capsule<false>,
+ _collision_box_convex_polygon<false>,
+ _collision_box_face<false> },
+ { 0,
+ 0,
+ _collision_capsule_capsule<false>,
+ _collision_capsule_convex_polygon<false>,
+ _collision_capsule_face<false> },
+ { 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<false>,
+ _collision_convex_polygon_face<false> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ 0 },
};
- static const CollisionFunc collision_table_margin[5][5]={
- {_collision_sphere_sphere<true>,
- _collision_sphere_box<true>,
- _collision_sphere_capsule<true>,
- _collision_sphere_convex_polygon<true>,
- _collision_sphere_face<true>},
- {0,
- _collision_box_box<true>,
- _collision_box_capsule<true>,
- _collision_box_convex_polygon<true>,
- _collision_box_face<true>},
- {0,
- 0,
- _collision_capsule_capsule<true>,
- _collision_capsule_convex_polygon<true>,
- _collision_capsule_face<true>},
- {0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<true>,
- _collision_convex_polygon_face<true>},
- {0,
- 0,
- 0,
- 0,
- 0},
+ static const CollisionFunc collision_table_margin[5][5] = {
+ { _collision_sphere_sphere<true>,
+ _collision_sphere_box<true>,
+ _collision_sphere_capsule<true>,
+ _collision_sphere_convex_polygon<true>,
+ _collision_sphere_face<true> },
+ { 0,
+ _collision_box_box<true>,
+ _collision_box_capsule<true>,
+ _collision_box_convex_polygon<true>,
+ _collision_box_face<true> },
+ { 0,
+ 0,
+ _collision_capsule_capsule<true>,
+ _collision_capsule_convex_polygon<true>,
+ _collision_capsule_face<true> },
+ { 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<true>,
+ _collision_convex_polygon_face<true> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ 0 },
};
_CollectorCallback callback;
- callback.callback=p_result_callback;
- callback.swap=p_swap;
- callback.userdata=p_userdata;
- callback.collided=false;
- callback.prev_axis=r_prev_axis;
-
- const ShapeSW *A=p_shape_A;
- const ShapeSW *B=p_shape_B;
- const Transform *transform_A=&p_transform_A;
- const Transform *transform_B=&p_transform_B;
- real_t margin_A=p_margin_a;
- real_t margin_B=p_margin_b;
+ callback.callback = p_result_callback;
+ callback.swap = p_swap;
+ callback.userdata = p_userdata;
+ callback.collided = false;
+ callback.prev_axis = r_prev_axis;
+
+ const ShapeSW *A = p_shape_A;
+ const ShapeSW *B = p_shape_B;
+ const Transform *transform_A = &p_transform_A;
+ const Transform *transform_B = &p_transform_B;
+ real_t margin_A = p_margin_a;
+ real_t margin_B = p_margin_b;
if (type_A > type_B) {
- SWAP(A,B);
- SWAP(transform_A,transform_B);
- SWAP(type_A,type_B);
- SWAP(margin_A,margin_B);
+ SWAP(A, B);
+ SWAP(transform_A, transform_B);
+ SWAP(type_A, type_B);
+ SWAP(margin_A, margin_B);
callback.swap = !callback.swap;
}
-
CollisionFunc collision_func;
- if (margin_A!=0.0 || margin_B!=0.0) {
- collision_func = collision_table_margin[type_A-2][type_B-2];
+ if (margin_A != 0.0 || margin_B != 0.0) {
+ collision_func = collision_table_margin[type_A - 2][type_B - 2];
} else {
- collision_func = collision_table[type_A-2][type_B-2];
-
+ collision_func = collision_table[type_A - 2][type_B - 2];
}
- ERR_FAIL_COND_V(!collision_func,false);
+ ERR_FAIL_COND_V(!collision_func, false);
-
- collision_func(A,*transform_A,B,*transform_B,&callback,margin_A,margin_B);
+ collision_func(A, *transform_A, B, *transform_B, &callback, margin_A, margin_B);
return callback.collided;
-
}
diff --git a/servers/physics/collision_solver_sat.h b/servers/physics/collision_solver_sat.h
index 15fe7dc34a..67ffb0b068 100644
--- a/servers/physics/collision_solver_sat.h
+++ b/servers/physics/collision_solver_sat.h
@@ -31,7 +31,6 @@
#include "collision_solver_sw.h"
-
-bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false,Vector3* r_prev_axis=NULL,real_t p_margin_a=0,real_t p_margin_b=0);
+bool sat_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false, Vector3 *r_prev_axis = NULL, real_t p_margin_a = 0, real_t p_margin_b = 0);
#endif // COLLISION_SOLVER_SAT_H
diff --git a/servers/physics/collision_solver_sw.cpp b/servers/physics/collision_solver_sw.cpp
index f0ddde3a76..0f6e964359 100644
--- a/servers/physics/collision_solver_sw.cpp
+++ b/servers/physics/collision_solver_sw.cpp
@@ -29,18 +29,16 @@
#include "collision_solver_sw.h"
#include "collision_solver_sat.h"
-#include "gjk_epa.h"
#include "collision_solver_sat.h"
-
+#include "gjk_epa.h"
#define collision_solver sat_calculate_penetration
//#define collision_solver gjk_epa_calculate_penetration
+bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) {
-bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) {
-
- const PlaneShapeSW *plane = static_cast<const PlaneShapeSW*>(p_shape_A);
- if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE)
+ const PlaneShapeSW *plane = static_cast<const PlaneShapeSW *>(p_shape_A);
+ if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE)
return false;
Plane p = p_transform_A.xform(plane->get_plane());
@@ -48,57 +46,54 @@ bool CollisionSolverSW::solve_static_plane(const ShapeSW *p_shape_A,const Transf
Vector3 supports[max_supports];
int support_count;
- p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(),max_supports,supports,support_count);
+ p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(), max_supports, supports, support_count);
- bool found=false;
+ bool found = false;
- for(int i=0;i<support_count;i++) {
+ for (int i = 0; i < support_count; i++) {
- supports[i] = p_transform_B.xform( supports[i] );
- if (p.distance_to(supports[i])>=0)
+ supports[i] = p_transform_B.xform(supports[i]);
+ if (p.distance_to(supports[i]) >= 0)
continue;
- found=true;
+ found = true;
Vector3 support_A = p.project(supports[i]);
if (p_result_callback) {
if (p_swap_result)
- p_result_callback(supports[i],support_A,p_userdata);
+ p_result_callback(supports[i], support_A, p_userdata);
else
- p_result_callback(support_A,supports[i],p_userdata);
+ p_result_callback(support_A, supports[i], p_userdata);
}
-
}
-
return found;
}
-bool CollisionSolverSW::solve_ray(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) {
+bool CollisionSolverSW::solve_ray(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) {
-
- const RayShapeSW *ray = static_cast<const RayShapeSW*>(p_shape_A);
+ const RayShapeSW *ray = static_cast<const RayShapeSW *>(p_shape_A);
Vector3 from = p_transform_A.origin;
- Vector3 to = from+p_transform_A.basis.get_axis(2)*ray->get_length();
- Vector3 support_A=to;
+ Vector3 to = from + p_transform_A.basis.get_axis(2) * ray->get_length();
+ Vector3 support_A = to;
Transform ai = p_transform_B.affine_inverse();
from = ai.xform(from);
to = ai.xform(to);
- Vector3 p,n;
- if (!p_shape_B->intersect_segment(from,to,p,n))
+ Vector3 p, n;
+ if (!p_shape_B->intersect_segment(from, to, p, n))
return false;
- Vector3 support_B=p_transform_B.xform(p);
+ Vector3 support_B = p_transform_B.xform(p);
if (p_result_callback) {
if (p_swap_result)
- p_result_callback(support_B,support_A,p_userdata);
+ p_result_callback(support_B, support_A, p_userdata);
else
- p_result_callback(support_A,support_B,p_userdata);
+ p_result_callback(support_A, support_B, p_userdata);
}
return true;
}
@@ -117,169 +112,153 @@ struct _ConcaveCollisionInfo {
bool tested;
real_t margin_A;
real_t margin_B;
- Vector3 close_A,close_B;
-
+ Vector3 close_A, close_B;
};
void CollisionSolverSW::concave_callback(void *p_userdata, ShapeSW *p_convex) {
-
- _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo*)(p_userdata);
+ _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata);
cinfo.aabb_tests++;
- bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, p_convex,*cinfo.transform_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result,NULL,cinfo.margin_A,cinfo.margin_B);
+ bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, p_convex, *cinfo.transform_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, NULL, cinfo.margin_A, cinfo.margin_B);
if (!collided)
return;
- cinfo.collided=true;
+ cinfo.collided = true;
cinfo.collisions++;
-
}
-bool CollisionSolverSW::solve_concave(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,real_t p_margin_A,real_t p_margin_B) {
+bool CollisionSolverSW::solve_concave(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, real_t p_margin_A, real_t p_margin_B) {
-
- const ConcaveShapeSW *concave_B=static_cast<const ConcaveShapeSW*>(p_shape_B);
+ const ConcaveShapeSW *concave_B = static_cast<const ConcaveShapeSW *>(p_shape_B);
_ConcaveCollisionInfo cinfo;
- cinfo.transform_A=&p_transform_A;
- cinfo.shape_A=p_shape_A;
- cinfo.transform_B=&p_transform_B;
- cinfo.result_callback=p_result_callback;
- cinfo.userdata=p_userdata;
- cinfo.swap_result=p_swap_result;
- cinfo.collided=false;
- cinfo.collisions=0;
- cinfo.margin_A=p_margin_A;
- cinfo.margin_B=p_margin_B;
-
- cinfo.aabb_tests=0;
+ cinfo.transform_A = &p_transform_A;
+ cinfo.shape_A = p_shape_A;
+ cinfo.transform_B = &p_transform_B;
+ cinfo.result_callback = p_result_callback;
+ cinfo.userdata = p_userdata;
+ cinfo.swap_result = p_swap_result;
+ cinfo.collided = false;
+ cinfo.collisions = 0;
+ cinfo.margin_A = p_margin_A;
+ cinfo.margin_B = p_margin_B;
+
+ cinfo.aabb_tests = 0;
Transform rel_transform = p_transform_A;
- rel_transform.origin-=p_transform_B.origin;
+ rel_transform.origin -= p_transform_B.origin;
//quickly compute a local AABB
Rect3 local_aabb;
- for(int i=0;i<3;i++) {
-
- Vector3 axis( p_transform_B.basis.get_axis(i) );
- real_t axis_scale = 1.0/axis.length();
- axis*=axis_scale;
+ for (int i = 0; i < 3; i++) {
- real_t smin,smax;
- p_shape_A->project_range(axis,rel_transform,smin,smax);
- smin-=p_margin_A;
- smax+=p_margin_A;
- smin*=axis_scale;
- smax*=axis_scale;
+ Vector3 axis(p_transform_B.basis.get_axis(i));
+ real_t axis_scale = 1.0 / axis.length();
+ axis *= axis_scale;
+ real_t smin, smax;
+ p_shape_A->project_range(axis, rel_transform, smin, smax);
+ smin -= p_margin_A;
+ smax += p_margin_A;
+ smin *= axis_scale;
+ smax *= axis_scale;
- local_aabb.pos[i]=smin;
- local_aabb.size[i]=smax-smin;
+ local_aabb.pos[i] = smin;
+ local_aabb.size[i] = smax - smin;
}
- concave_B->cull(local_aabb,concave_callback,&cinfo);
+ concave_B->cull(local_aabb, concave_callback, &cinfo);
//print_line("COL AABB TESTS: "+itos(cinfo.aabb_tests));
return cinfo.collided;
}
+bool CollisionSolverSW::solve_static(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, Vector3 *r_sep_axis, real_t p_margin_A, real_t p_margin_B) {
-bool CollisionSolverSW::solve_static(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,Vector3 *r_sep_axis,real_t p_margin_A,real_t p_margin_B) {
-
-
- PhysicsServer::ShapeType type_A=p_shape_A->get_type();
- PhysicsServer::ShapeType type_B=p_shape_B->get_type();
- bool concave_A=p_shape_A->is_concave();
- bool concave_B=p_shape_B->is_concave();
+ PhysicsServer::ShapeType type_A = p_shape_A->get_type();
+ PhysicsServer::ShapeType type_B = p_shape_B->get_type();
+ bool concave_A = p_shape_A->is_concave();
+ bool concave_B = p_shape_B->is_concave();
bool swap = false;
- if (type_A>type_B) {
- SWAP(type_A,type_B);
- SWAP(concave_A,concave_B);
- swap=true;
+ if (type_A > type_B) {
+ SWAP(type_A, type_B);
+ SWAP(concave_A, concave_B);
+ swap = true;
}
- if (type_A==PhysicsServer::SHAPE_PLANE) {
+ if (type_A == PhysicsServer::SHAPE_PLANE) {
- if (type_B==PhysicsServer::SHAPE_PLANE)
+ if (type_B == PhysicsServer::SHAPE_PLANE)
return false;
- if (type_B==PhysicsServer::SHAPE_RAY) {
+ if (type_B == PhysicsServer::SHAPE_RAY) {
return false;
}
if (swap) {
- return solve_static_plane(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true);
+ return solve_static_plane(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true);
} else {
- return solve_static_plane(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false);
+ return solve_static_plane(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false);
}
- } else if (type_A==PhysicsServer::SHAPE_RAY) {
+ } else if (type_A == PhysicsServer::SHAPE_RAY) {
- if (type_B==PhysicsServer::SHAPE_RAY)
+ if (type_B == PhysicsServer::SHAPE_RAY)
return false;
if (swap) {
- return solve_ray(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true);
+ return solve_ray(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true);
} else {
- return solve_ray(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false);
+ return solve_ray(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false);
}
} else if (concave_B) {
-
if (concave_A)
return false;
if (!swap)
- return solve_concave(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false,p_margin_A,p_margin_B);
+ return solve_concave(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, p_margin_A, p_margin_B);
else
- return solve_concave(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true,p_margin_A,p_margin_B);
-
-
+ return solve_concave(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, p_margin_A, p_margin_B);
} else {
- return collision_solver(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback,p_userdata,false,r_sep_axis,p_margin_A,p_margin_B);
+ return collision_solver(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, r_sep_axis, p_margin_A, p_margin_B);
}
-
return false;
}
-
void CollisionSolverSW::concave_distance_callback(void *p_userdata, ShapeSW *p_convex) {
-
- _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo*)(p_userdata);
+ _ConcaveCollisionInfo &cinfo = *(_ConcaveCollisionInfo *)(p_userdata);
cinfo.aabb_tests++;
if (cinfo.collided)
return;
- Vector3 close_A,close_B;
- cinfo.collided = !gjk_epa_calculate_distance(cinfo.shape_A,*cinfo.transform_A,p_convex,*cinfo.transform_B,close_A,close_B);
+ Vector3 close_A, close_B;
+ cinfo.collided = !gjk_epa_calculate_distance(cinfo.shape_A, *cinfo.transform_A, p_convex, *cinfo.transform_B, close_A, close_B);
if (cinfo.collided)
return;
if (!cinfo.tested || close_A.distance_squared_to(close_B) < cinfo.close_A.distance_squared_to(cinfo.close_B)) {
- cinfo.close_A=close_A;
- cinfo.close_B=close_B;
- cinfo.tested=true;
+ cinfo.close_A = close_A;
+ cinfo.close_B = close_B;
+ cinfo.tested = true;
}
cinfo.collisions++;
-
}
+bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B) {
-
-bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B) {
-
- const PlaneShapeSW *plane = static_cast<const PlaneShapeSW*>(p_shape_A);
- if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE)
+ const PlaneShapeSW *plane = static_cast<const PlaneShapeSW *>(p_shape_A);
+ if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE)
return false;
Plane p = p_transform_A.xform(plane->get_plane());
@@ -287,43 +266,41 @@ bool CollisionSolverSW::solve_distance_plane(const ShapeSW *p_shape_A,const Tran
Vector3 supports[max_supports];
int support_count;
- p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(),max_supports,supports,support_count);
+ p_shape_B->get_supports(p_transform_B.basis.xform_inv(-p.normal).normalized(), max_supports, supports, support_count);
- bool collided=false;
+ bool collided = false;
Vector3 closest;
real_t closest_d;
+ for (int i = 0; i < support_count; i++) {
- for(int i=0;i<support_count;i++) {
-
- supports[i] = p_transform_B.xform( supports[i] );
+ supports[i] = p_transform_B.xform(supports[i]);
real_t d = p.distance_to(supports[i]);
- if (i==0 || d<closest_d) {
- closest=supports[i];
- closest_d=d;
- if (d<=0)
- collided=true;
+ if (i == 0 || d < closest_d) {
+ closest = supports[i];
+ closest_d = d;
+ if (d <= 0)
+ collided = true;
}
-
}
- r_point_A=p.project(closest);
- r_point_B=closest;
+ r_point_A = p.project(closest);
+ r_point_B = closest;
return collided;
}
-bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B,const Rect3& p_concave_hint,Vector3 *r_sep_axis) {
+bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B, const Rect3 &p_concave_hint, Vector3 *r_sep_axis) {
if (p_shape_A->is_concave())
return false;
- if (p_shape_B->get_type()==PhysicsServer::SHAPE_PLANE) {
+ if (p_shape_B->get_type() == PhysicsServer::SHAPE_PLANE) {
- Vector3 a,b;
- bool col = solve_distance_plane(p_shape_B,p_transform_B,p_shape_A,p_transform_A,a,b);
- r_point_A=b;
- r_point_B=a;
+ Vector3 a, b;
+ bool col = solve_distance_plane(p_shape_B, p_transform_B, p_shape_A, p_transform_A, a, b);
+ r_point_A = b;
+ r_point_B = a;
return !col;
} else if (p_shape_B->is_concave()) {
@@ -331,62 +308,59 @@ bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform&
if (p_shape_A->is_concave())
return false;
-
- const ConcaveShapeSW *concave_B=static_cast<const ConcaveShapeSW*>(p_shape_B);
+ const ConcaveShapeSW *concave_B = static_cast<const ConcaveShapeSW *>(p_shape_B);
_ConcaveCollisionInfo cinfo;
- cinfo.transform_A=&p_transform_A;
- cinfo.shape_A=p_shape_A;
- cinfo.transform_B=&p_transform_B;
- cinfo.result_callback=NULL;
- cinfo.userdata=NULL;
- cinfo.swap_result=false;
- cinfo.collided=false;
- cinfo.collisions=0;
- cinfo.aabb_tests=0;
- cinfo.tested=false;
+ cinfo.transform_A = &p_transform_A;
+ cinfo.shape_A = p_shape_A;
+ cinfo.transform_B = &p_transform_B;
+ cinfo.result_callback = NULL;
+ cinfo.userdata = NULL;
+ cinfo.swap_result = false;
+ cinfo.collided = false;
+ cinfo.collisions = 0;
+ cinfo.aabb_tests = 0;
+ cinfo.tested = false;
Transform rel_transform = p_transform_A;
- rel_transform.origin-=p_transform_B.origin;
+ rel_transform.origin -= p_transform_B.origin;
//quickly compute a local AABB
- bool use_cc_hint=p_concave_hint!=Rect3();
+ bool use_cc_hint = p_concave_hint != Rect3();
Rect3 cc_hint_aabb;
if (use_cc_hint) {
- cc_hint_aabb=p_concave_hint;
- cc_hint_aabb.pos-=p_transform_B.origin;
+ cc_hint_aabb = p_concave_hint;
+ cc_hint_aabb.pos -= p_transform_B.origin;
}
Rect3 local_aabb;
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- Vector3 axis( p_transform_B.basis.get_axis(i) );
- real_t axis_scale = ((real_t)1.0)/axis.length();
- axis*=axis_scale;
+ Vector3 axis(p_transform_B.basis.get_axis(i));
+ real_t axis_scale = ((real_t)1.0) / axis.length();
+ axis *= axis_scale;
- real_t smin,smax;
+ real_t smin, smax;
- if (use_cc_hint) {
- cc_hint_aabb.project_range_in_plane(Plane(axis,0),smin,smax);
- } else {
- p_shape_A->project_range(axis,rel_transform,smin,smax);
- }
+ if (use_cc_hint) {
+ cc_hint_aabb.project_range_in_plane(Plane(axis, 0), smin, smax);
+ } else {
+ p_shape_A->project_range(axis, rel_transform, smin, smax);
+ }
- smin*=axis_scale;
- smax*=axis_scale;
+ smin *= axis_scale;
+ smax *= axis_scale;
- local_aabb.pos[i]=smin;
- local_aabb.size[i]=smax-smin;
+ local_aabb.pos[i] = smin;
+ local_aabb.size[i] = smax - smin;
}
-
- concave_B->cull(local_aabb,concave_distance_callback,&cinfo);
+ concave_B->cull(local_aabb, concave_distance_callback, &cinfo);
if (!cinfo.collided) {
//print_line(itos(cinfo.tested));
- r_point_A=cinfo.close_A;
- r_point_B=cinfo.close_B;
-
+ r_point_A = cinfo.close_A;
+ r_point_B = cinfo.close_B;
}
//print_line("DIST AABB TESTS: "+itos(cinfo.aabb_tests));
@@ -394,10 +368,8 @@ bool CollisionSolverSW::solve_distance(const ShapeSW *p_shape_A,const Transform&
return !cinfo.collided;
} else {
- return gjk_epa_calculate_distance(p_shape_A,p_transform_A,p_shape_B,p_transform_B,r_point_A,r_point_B); //should pass sepaxis..
+ return gjk_epa_calculate_distance(p_shape_A, p_transform_A, p_shape_B, p_transform_B, r_point_A, r_point_B); //should pass sepaxis..
}
-
return false;
}
-
diff --git a/servers/physics/collision_solver_sw.h b/servers/physics/collision_solver_sw.h
index b8d37a8a96..b0f18dc0ac 100644
--- a/servers/physics/collision_solver_sw.h
+++ b/servers/physics/collision_solver_sw.h
@@ -31,25 +31,21 @@
#include "shape_sw.h"
-class CollisionSolverSW
-{
+class CollisionSolverSW {
public:
- typedef void (*CallbackResult)(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata);
-private:
+ typedef void (*CallbackResult)(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata);
+private:
static void concave_callback(void *p_userdata, ShapeSW *p_convex);
- static bool solve_static_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result);
- static bool solve_ray(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result);
- static bool solve_concave(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,real_t p_margin_A=0,real_t p_margin_B=0);
+ static bool solve_static_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result);
+ static bool solve_ray(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result);
+ static bool solve_concave(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, real_t p_margin_A = 0, real_t p_margin_B = 0);
static void concave_distance_callback(void *p_userdata, ShapeSW *p_convex);
- static bool solve_distance_plane(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B);
+ static bool solve_distance_plane(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B);
public:
-
-
- static bool solve_static(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,CallbackResult p_result_callback,void *p_userdata,Vector3 *r_sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0);
- static bool solve_distance(const ShapeSW *p_shape_A,const Transform& p_transform_A,const ShapeSW *p_shape_B,const Transform& p_transform_B,Vector3& r_point_A,Vector3& r_point_B,const Rect3& p_concave_hint,Vector3 *r_sep_axis=NULL);
-
+ static bool solve_static(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CallbackResult p_result_callback, void *p_userdata, Vector3 *r_sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0);
+ static bool solve_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_point_A, Vector3 &r_point_B, const Rect3 &p_concave_hint, Vector3 *r_sep_axis = NULL);
};
#endif // COLLISION_SOLVER__SW_H
diff --git a/servers/physics/constraint_sw.h b/servers/physics/constraint_sw.h
index f5bbe4bbd0..2cd0e1a420 100644
--- a/servers/physics/constraint_sw.h
+++ b/servers/physics/constraint_sw.h
@@ -40,35 +40,37 @@ class ConstraintSW : public RID_Data {
ConstraintSW *island_list_next;
int priority;
-
RID self;
protected:
- ConstraintSW(BodySW **p_body_ptr=NULL,int p_body_count=0) { _body_ptr=p_body_ptr; _body_count=p_body_count; island_step=0; priority=1; }
-public:
+ ConstraintSW(BodySW **p_body_ptr = NULL, int p_body_count = 0) {
+ _body_ptr = p_body_ptr;
+ _body_count = p_body_count;
+ island_step = 0;
+ priority = 1;
+ }
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+public:
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
_FORCE_INLINE_ uint64_t get_island_step() const { return island_step; }
- _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; }
+ _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; }
+ _FORCE_INLINE_ ConstraintSW *get_island_next() const { return island_next; }
+ _FORCE_INLINE_ void set_island_next(ConstraintSW *p_next) { island_next = p_next; }
- _FORCE_INLINE_ ConstraintSW* get_island_next() const { return island_next; }
- _FORCE_INLINE_ void set_island_next(ConstraintSW* p_next) { island_next=p_next; }
-
- _FORCE_INLINE_ ConstraintSW* get_island_list_next() const { return island_list_next; }
- _FORCE_INLINE_ void set_island_list_next(ConstraintSW* p_next) { island_list_next=p_next; }
+ _FORCE_INLINE_ ConstraintSW *get_island_list_next() const { return island_list_next; }
+ _FORCE_INLINE_ void set_island_list_next(ConstraintSW *p_next) { island_list_next = p_next; }
_FORCE_INLINE_ BodySW **get_body_ptr() const { return _body_ptr; }
_FORCE_INLINE_ int get_body_count() const { return _body_count; }
- _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; }
+ _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; }
_FORCE_INLINE_ int get_priority() const { return priority; }
-
- virtual bool setup(real_t p_step)=0;
- virtual void solve(real_t p_step)=0;
+ virtual bool setup(real_t p_step) = 0;
+ virtual void solve(real_t p_step) = 0;
virtual ~ConstraintSW() {}
};
diff --git a/servers/physics/gjk_epa.cpp b/servers/physics/gjk_epa.cpp
index 06c2c2382c..f65e6768ab 100644
--- a/servers/physics/gjk_epa.cpp
+++ b/servers/physics/gjk_epa.cpp
@@ -884,33 +884,30 @@ bool Penetration( const ShapeSW* shape0,
/* clang-format on */
-
-bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, Vector3& r_result_A, Vector3& r_result_B) {
-
+bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B) {
GjkEpa2::sResults res;
- if (GjkEpa2::Distance(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_transform_B.origin-p_transform_A.origin,res)) {
+ if (GjkEpa2::Distance(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) {
- r_result_A=res.witnesses[0];
- r_result_B=res.witnesses[1];
+ r_result_A = res.witnesses[0];
+ r_result_B = res.witnesses[1];
return true;
}
return false;
-
}
-bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap ) {
+bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap) {
GjkEpa2::sResults res;
- if (GjkEpa2::Penetration(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_transform_B.origin-p_transform_A.origin,res)) {
+ if (GjkEpa2::Penetration(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) {
if (p_result_callback) {
if (p_swap)
- p_result_callback(res.witnesses[1],res.witnesses[0],p_userdata);
+ p_result_callback(res.witnesses[1], res.witnesses[0], p_userdata);
else
- p_result_callback(res.witnesses[0],res.witnesses[1],p_userdata);
+ p_result_callback(res.witnesses[0], res.witnesses[1], p_userdata);
}
return true;
}
diff --git a/servers/physics/gjk_epa.h b/servers/physics/gjk_epa.h
index 58cf8f50ce..ae5db733b5 100644
--- a/servers/physics/gjk_epa.h
+++ b/servers/physics/gjk_epa.h
@@ -35,7 +35,7 @@
*/
#include "collision_solver_sw.h"
-bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false);
-bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, Vector3& r_result_A, Vector3& r_result_B);
+bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false);
+bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B);
#endif
diff --git a/servers/physics/joints/cone_twist_joint_sw.cpp b/servers/physics/joints/cone_twist_joint_sw.cpp
index d78bcbd16d..8cab81de2c 100644
--- a/servers/physics/joints/cone_twist_joint_sw.cpp
+++ b/servers/physics/joints/cone_twist_joint_sw.cpp
@@ -34,29 +34,26 @@ See corresponding header file for licensing info.
#include "cone_twist_joint_sw.h"
-static void plane_space(const Vector3& n, Vector3& p, Vector3& q) {
-
- if (Math::abs(n.z) > 0.707106781186547524400844362) {
- // choose p in y-z plane
- real_t a = n[1]*n[1] + n[2]*n[2];
- real_t k = 1.0/Math::sqrt(a);
- p=Vector3(0,-n[2]*k,n[1]*k);
- // set q = n x p
- q=Vector3(a*k,-n[0]*p[2],n[0]*p[1]);
- }
- else {
- // choose p in x-y plane
- real_t a = n.x*n.x + n.y*n.y;
- real_t k = 1.0/Math::sqrt(a);
- p=Vector3(-n.y*k,n.x*k,0);
- // set q = n x p
- q=Vector3(-n.z*p.y,n.z*p.x,a*k);
- }
+static void plane_space(const Vector3 &n, Vector3 &p, Vector3 &q) {
+
+ if (Math::abs(n.z) > 0.707106781186547524400844362) {
+ // choose p in y-z plane
+ real_t a = n[1] * n[1] + n[2] * n[2];
+ real_t k = 1.0 / Math::sqrt(a);
+ p = Vector3(0, -n[2] * k, n[1] * k);
+ // set q = n x p
+ q = Vector3(a * k, -n[0] * p[2], n[0] * p[1]);
+ } else {
+ // choose p in x-y plane
+ real_t a = n.x * n.x + n.y * n.y;
+ real_t k = 1.0 / Math::sqrt(a);
+ p = Vector3(-n.y * k, n.x * k, 0);
+ // set q = n x p
+ q = Vector3(-n.z * p.y, n.z * p.x, a * k);
+ }
}
-
-static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
-{
+static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) {
real_t coeff_1 = Math_PI / 4.0f;
real_t coeff_2 = 3.0f * coeff_1;
real_t abs_y = Math::abs(y);
@@ -71,32 +68,31 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
return (y < 0.0f) ? -angle : angle;
}
-ConeTwistJointSW::ConeTwistJointSW(BodySW* rbA,BodySW* rbB,const Transform& rbAFrame, const Transform& rbBFrame) : JointSW(_arr,2) {
+ConeTwistJointSW::ConeTwistJointSW(BodySW *rbA, BodySW *rbB, const Transform &rbAFrame, const Transform &rbBFrame)
+ : JointSW(_arr, 2) {
- A=rbA;
- B=rbB;
+ A = rbA;
+ B = rbB;
+ m_rbAFrame = rbAFrame;
+ m_rbBFrame = rbBFrame;
- m_rbAFrame=rbAFrame;
- m_rbBFrame=rbBFrame;
-
- m_swingSpan1 = Math_PI/4.0;
- m_swingSpan2 = Math_PI/4.0;
- m_twistSpan = Math_PI*2;
+ m_swingSpan1 = Math_PI / 4.0;
+ m_swingSpan2 = Math_PI / 4.0;
+ m_twistSpan = Math_PI * 2;
m_biasFactor = 0.3f;
m_relaxationFactor = 1.0f;
m_solveTwistLimit = false;
m_solveSwingLimit = false;
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
- m_appliedImpulse=0;
+ m_appliedImpulse = 0;
}
-
-bool ConeTwistJointSW::setup(real_t p_step) {
+bool ConeTwistJointSW::setup(real_t p_step) {
m_appliedImpulse = real_t(0.);
//set bias, sign, clear accumulator
@@ -107,109 +103,97 @@ bool ConeTwistJointSW::setup(real_t p_step) {
m_accTwistLimitImpulse = real_t(0.);
m_accSwingLimitImpulse = real_t(0.);
- if (!m_angularOnly)
- {
+ if (!m_angularOnly) {
Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
Vector3 relPos = pivotBInW - pivotAInW;
Vector3 normal[3];
- if (relPos.length_squared() > CMP_EPSILON)
- {
+ if (relPos.length_squared() > CMP_EPSILON) {
normal[0] = relPos.normalized();
- }
- else
- {
- normal[0]=Vector3(real_t(1.0),0,0);
+ } else {
+ normal[0] = Vector3(real_t(1.0), 0, 0);
}
plane_space(normal[0], normal[1], normal[2]);
- for (int i=0;i<3;i++)
- {
+ for (int i = 0; i < 3; i++) {
memnew_placement(&m_jac[i], JacobianEntrySW(
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
- pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
- normal[i],
- A->get_inv_inertia(),
- A->get_inv_mass(),
- B->get_inv_inertia(),
- B->get_inv_mass()));
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
+ pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
+ normal[i],
+ A->get_inv_inertia(),
+ A->get_inv_mass(),
+ B->get_inv_inertia(),
+ B->get_inv_mass()));
}
}
- Vector3 b1Axis1,b1Axis2,b1Axis3;
- Vector3 b2Axis1,b2Axis2;
+ Vector3 b1Axis1, b1Axis2, b1Axis3;
+ Vector3 b2Axis1, b2Axis2;
- b1Axis1 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(0) );
- b2Axis1 = B->get_transform().basis.xform( this->m_rbBFrame.basis.get_axis(0) );
+ b1Axis1 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(0));
+ b2Axis1 = B->get_transform().basis.xform(this->m_rbBFrame.basis.get_axis(0));
- real_t swing1=real_t(0.),swing2 = real_t(0.);
+ real_t swing1 = real_t(0.), swing2 = real_t(0.);
- real_t swx=real_t(0.),swy = real_t(0.);
+ real_t swx = real_t(0.), swy = real_t(0.);
real_t thresh = real_t(10.);
real_t fact;
// Get Frame into world space
- if (m_swingSpan1 >= real_t(0.05f))
- {
- b1Axis2 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(1) );
+ if (m_swingSpan1 >= real_t(0.05f)) {
+ b1Axis2 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(1));
//swing1 = btAtan2Fast( b2Axis1.dot(b1Axis2),b2Axis1.dot(b1Axis1) );
swx = b2Axis1.dot(b1Axis1);
swy = b2Axis1.dot(b1Axis2);
- swing1 = atan2fast(swy, swx);
- fact = (swy*swy + swx*swx) * thresh * thresh;
+ swing1 = atan2fast(swy, swx);
+ fact = (swy * swy + swx * swx) * thresh * thresh;
fact = fact / (fact + real_t(1.0));
swing1 *= fact;
-
}
- if (m_swingSpan2 >= real_t(0.05f))
- {
- b1Axis3 = A->get_transform().basis.xform( this->m_rbAFrame.basis.get_axis(2) );
+ if (m_swingSpan2 >= real_t(0.05f)) {
+ b1Axis3 = A->get_transform().basis.xform(this->m_rbAFrame.basis.get_axis(2));
//swing2 = btAtan2Fast( b2Axis1.dot(b1Axis3),b2Axis1.dot(b1Axis1) );
swx = b2Axis1.dot(b1Axis1);
swy = b2Axis1.dot(b1Axis3);
- swing2 = atan2fast(swy, swx);
- fact = (swy*swy + swx*swx) * thresh * thresh;
+ swing2 = atan2fast(swy, swx);
+ fact = (swy * swy + swx * swx) * thresh * thresh;
fact = fact / (fact + real_t(1.0));
swing2 *= fact;
}
- real_t RMaxAngle1Sq = 1.0f / (m_swingSpan1*m_swingSpan1);
- real_t RMaxAngle2Sq = 1.0f / (m_swingSpan2*m_swingSpan2);
- real_t EllipseAngle = Math::abs(swing1*swing1)* RMaxAngle1Sq + Math::abs(swing2*swing2) * RMaxAngle2Sq;
+ real_t RMaxAngle1Sq = 1.0f / (m_swingSpan1 * m_swingSpan1);
+ real_t RMaxAngle2Sq = 1.0f / (m_swingSpan2 * m_swingSpan2);
+ real_t EllipseAngle = Math::abs(swing1 * swing1) * RMaxAngle1Sq + Math::abs(swing2 * swing2) * RMaxAngle2Sq;
- if (EllipseAngle > 1.0f)
- {
- m_swingCorrection = EllipseAngle-1.0f;
+ if (EllipseAngle > 1.0f) {
+ m_swingCorrection = EllipseAngle - 1.0f;
m_solveSwingLimit = true;
// Calculate necessary axis & factors
- m_swingAxis = b2Axis1.cross(b1Axis2* b2Axis1.dot(b1Axis2) + b1Axis3* b2Axis1.dot(b1Axis3));
+ m_swingAxis = b2Axis1.cross(b1Axis2 * b2Axis1.dot(b1Axis2) + b1Axis3 * b2Axis1.dot(b1Axis3));
m_swingAxis.normalize();
real_t swingAxisSign = (b2Axis1.dot(b1Axis1) >= 0.0f) ? 1.0f : -1.0f;
m_swingAxis *= swingAxisSign;
- m_kSwing = real_t(1.) / (A->compute_angular_impulse_denominator(m_swingAxis) +
- B->compute_angular_impulse_denominator(m_swingAxis));
-
+ m_kSwing = real_t(1.) / (A->compute_angular_impulse_denominator(m_swingAxis) +
+ B->compute_angular_impulse_denominator(m_swingAxis));
}
// Twist limits
- if (m_twistSpan >= real_t(0.))
- {
- Vector3 b2Axis2 = B->get_transform().basis.xform( this->m_rbBFrame.basis.get_axis(1) );
- Quat rotationArc = Quat(b2Axis1,b1Axis1);
+ if (m_twistSpan >= real_t(0.)) {
+ Vector3 b2Axis2 = B->get_transform().basis.xform(this->m_rbBFrame.basis.get_axis(1));
+ Quat rotationArc = Quat(b2Axis1, b1Axis1);
Vector3 TwistRef = rotationArc.xform(b2Axis2);
- real_t twist = atan2fast( TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2) );
+ real_t twist = atan2fast(TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2));
real_t lockedFreeFactor = (m_twistSpan > real_t(0.05f)) ? m_limitSoftness : real_t(0.);
- if (twist <= -m_twistSpan*lockedFreeFactor)
- {
+ if (twist <= -m_twistSpan * lockedFreeFactor) {
m_twistCorrection = -(twist + m_twistSpan);
m_solveTwistLimit = true;
@@ -218,28 +202,24 @@ bool ConeTwistJointSW::setup(real_t p_step) {
m_twistAxis *= -1.0f;
m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) +
- B->compute_angular_impulse_denominator(m_twistAxis));
-
- } else
- if (twist > m_twistSpan*lockedFreeFactor)
- {
- m_twistCorrection = (twist - m_twistSpan);
- m_solveTwistLimit = true;
+ B->compute_angular_impulse_denominator(m_twistAxis));
- m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f;
- m_twistAxis.normalize();
+ } else if (twist > m_twistSpan * lockedFreeFactor) {
+ m_twistCorrection = (twist - m_twistSpan);
+ m_solveTwistLimit = true;
- m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) +
- B->compute_angular_impulse_denominator(m_twistAxis));
+ m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f;
+ m_twistAxis.normalize();
- }
+ m_kTwist = real_t(1.) / (A->compute_angular_impulse_denominator(m_twistAxis) +
+ B->compute_angular_impulse_denominator(m_twistAxis));
+ }
}
return true;
}
-void ConeTwistJointSW::solve(real_t timeStep)
-{
+void ConeTwistJointSW::solve(real_t timeStep) {
Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
@@ -247,8 +227,7 @@ void ConeTwistJointSW::solve(real_t timeStep)
real_t tau = real_t(0.3);
//linear part
- if (!m_angularOnly)
- {
+ if (!m_angularOnly) {
Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
@@ -256,16 +235,15 @@ void ConeTwistJointSW::solve(real_t timeStep)
Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2);
Vector3 vel = vel1 - vel2;
- for (int i=0;i<3;i++)
- {
- const Vector3& normal = m_jac[i].m_linearJointAxis;
+ for (int i = 0; i < 3; i++) {
+ const Vector3 &normal = m_jac[i].m_linearJointAxis;
real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal();
real_t rel_vel;
rel_vel = normal.dot(vel);
//positional error (zeroth order error)
real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
- real_t impulse = depth*tau/timeStep * jacDiagABInv - rel_vel * jacDiagABInv;
+ real_t impulse = depth * tau / timeStep * jacDiagABInv - rel_vel * jacDiagABInv;
m_appliedImpulse += impulse;
Vector3 impulse_vector = normal * impulse;
A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector);
@@ -275,79 +253,73 @@ void ConeTwistJointSW::solve(real_t timeStep)
{
///solve angular part
- const Vector3& angVelA = A->get_angular_velocity();
- const Vector3& angVelB = B->get_angular_velocity();
+ const Vector3 &angVelA = A->get_angular_velocity();
+ const Vector3 &angVelB = B->get_angular_velocity();
// solve swing limit
- if (m_solveSwingLimit)
- {
- real_t amplitude = ((angVelB - angVelA).dot( m_swingAxis )*m_relaxationFactor*m_relaxationFactor + m_swingCorrection*(real_t(1.)/timeStep)*m_biasFactor);
+ if (m_solveSwingLimit) {
+ real_t amplitude = ((angVelB - angVelA).dot(m_swingAxis) * m_relaxationFactor * m_relaxationFactor + m_swingCorrection * (real_t(1.) / timeStep) * m_biasFactor);
real_t impulseMag = amplitude * m_kSwing;
// Clamp the accumulated impulse
real_t temp = m_accSwingLimitImpulse;
- m_accSwingLimitImpulse = MAX(m_accSwingLimitImpulse + impulseMag, real_t(0.0) );
+ m_accSwingLimitImpulse = MAX(m_accSwingLimitImpulse + impulseMag, real_t(0.0));
impulseMag = m_accSwingLimitImpulse - temp;
Vector3 impulse = m_swingAxis * impulseMag;
A->apply_torque_impulse(impulse);
B->apply_torque_impulse(-impulse);
-
}
// solve twist limit
- if (m_solveTwistLimit)
- {
- real_t amplitude = ((angVelB - angVelA).dot( m_twistAxis )*m_relaxationFactor*m_relaxationFactor + m_twistCorrection*(real_t(1.)/timeStep)*m_biasFactor );
+ if (m_solveTwistLimit) {
+ real_t amplitude = ((angVelB - angVelA).dot(m_twistAxis) * m_relaxationFactor * m_relaxationFactor + m_twistCorrection * (real_t(1.) / timeStep) * m_biasFactor);
real_t impulseMag = amplitude * m_kTwist;
// Clamp the accumulated impulse
real_t temp = m_accTwistLimitImpulse;
- m_accTwistLimitImpulse = MAX(m_accTwistLimitImpulse + impulseMag, real_t(0.0) );
+ m_accTwistLimitImpulse = MAX(m_accTwistLimitImpulse + impulseMag, real_t(0.0));
impulseMag = m_accTwistLimitImpulse - temp;
Vector3 impulse = m_twistAxis * impulseMag;
A->apply_torque_impulse(impulse);
B->apply_torque_impulse(-impulse);
-
}
-
}
-
}
void ConeTwistJointSW::set_param(PhysicsServer::ConeTwistJointParam p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::CONE_TWIST_JOINT_SWING_SPAN: {
- m_swingSpan1=p_value;
- m_swingSpan2=p_value;
+ m_swingSpan1 = p_value;
+ m_swingSpan2 = p_value;
} break;
case PhysicsServer::CONE_TWIST_JOINT_TWIST_SPAN: {
- m_twistSpan=p_value;
+ m_twistSpan = p_value;
} break;
case PhysicsServer::CONE_TWIST_JOINT_BIAS: {
- m_biasFactor=p_value;
+ m_biasFactor = p_value;
} break;
case PhysicsServer::CONE_TWIST_JOINT_SOFTNESS: {
- m_limitSoftness=p_value;
+ m_limitSoftness = p_value;
} break;
case PhysicsServer::CONE_TWIST_JOINT_RELAXATION: {
- m_relaxationFactor=p_value;
+ m_relaxationFactor = p_value;
} break;
}
}
-real_t ConeTwistJointSW::get_param(PhysicsServer::ConeTwistJointParam p_param) const{
+real_t ConeTwistJointSW::get_param(PhysicsServer::ConeTwistJointParam p_param) const {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::CONE_TWIST_JOINT_SWING_SPAN: {
return m_swingSpan1;
diff --git a/servers/physics/joints/cone_twist_joint_sw.h b/servers/physics/joints/cone_twist_joint_sw.h
index eb7a5cd1b1..c122c22258 100644
--- a/servers/physics/joints/cone_twist_joint_sw.h
+++ b/servers/physics/joints/cone_twist_joint_sw.h
@@ -51,14 +51,11 @@ Written by: Marcus Hennix
#ifndef CONE_TWIST_JOINT_SW_H
#define CONE_TWIST_JOINT_SW_H
-#include "servers/physics/joints_sw.h"
#include "servers/physics/joints/jacobian_entry_sw.h"
-
-
+#include "servers/physics/joints_sw.h"
///ConeTwistJointSW can be used to simulate ragdoll joints (upper arm, leg etc)
-class ConeTwistJointSW : public JointSW
-{
+class ConeTwistJointSW : public JointSW {
#ifdef IN_PARALLELL_SOLVER
public:
#endif
@@ -72,86 +69,73 @@ public:
BodySW *_arr[2];
};
- JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
-
+ JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
real_t m_appliedImpulse;
Transform m_rbAFrame;
Transform m_rbBFrame;
- real_t m_limitSoftness;
- real_t m_biasFactor;
- real_t m_relaxationFactor;
-
- real_t m_swingSpan1;
- real_t m_swingSpan2;
- real_t m_twistSpan;
+ real_t m_limitSoftness;
+ real_t m_biasFactor;
+ real_t m_relaxationFactor;
- Vector3 m_swingAxis;
- Vector3 m_twistAxis;
+ real_t m_swingSpan1;
+ real_t m_swingSpan2;
+ real_t m_twistSpan;
- real_t m_kSwing;
- real_t m_kTwist;
+ Vector3 m_swingAxis;
+ Vector3 m_twistAxis;
- real_t m_twistLimitSign;
- real_t m_swingCorrection;
- real_t m_twistCorrection;
+ real_t m_kSwing;
+ real_t m_kTwist;
- real_t m_accSwingLimitImpulse;
- real_t m_accTwistLimitImpulse;
+ real_t m_twistLimitSign;
+ real_t m_swingCorrection;
+ real_t m_twistCorrection;
- bool m_angularOnly;
- bool m_solveTwistLimit;
- bool m_solveSwingLimit;
+ real_t m_accSwingLimitImpulse;
+ real_t m_accTwistLimitImpulse;
+ bool m_angularOnly;
+ bool m_solveTwistLimit;
+ bool m_solveSwingLimit;
public:
-
virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_CONE_TWIST; }
virtual bool setup(real_t p_step);
virtual void solve(real_t p_step);
- ConeTwistJointSW(BodySW* rbA,BodySW* rbB,const Transform& rbAFrame, const Transform& rbBFrame);
-
+ ConeTwistJointSW(BodySW *rbA, BodySW *rbB, const Transform &rbAFrame, const Transform &rbBFrame);
- void setAngularOnly(bool angularOnly)
- {
+ void setAngularOnly(bool angularOnly) {
m_angularOnly = angularOnly;
}
- void setLimit(real_t _swingSpan1,real_t _swingSpan2,real_t _twistSpan, real_t _softness = 0.8f, real_t _biasFactor = 0.3f, real_t _relaxationFactor = 1.0f)
- {
+ void setLimit(real_t _swingSpan1, real_t _swingSpan2, real_t _twistSpan, real_t _softness = 0.8f, real_t _biasFactor = 0.3f, real_t _relaxationFactor = 1.0f) {
m_swingSpan1 = _swingSpan1;
m_swingSpan2 = _swingSpan2;
- m_twistSpan = _twistSpan;
+ m_twistSpan = _twistSpan;
- m_limitSoftness = _softness;
+ m_limitSoftness = _softness;
m_biasFactor = _biasFactor;
m_relaxationFactor = _relaxationFactor;
}
- inline int getSolveTwistLimit()
- {
+ inline int getSolveTwistLimit() {
return m_solveTwistLimit;
}
- inline int getSolveSwingLimit()
- {
+ inline int getSolveSwingLimit() {
return m_solveTwistLimit;
}
- inline real_t getTwistLimitSign()
- {
+ inline real_t getTwistLimitSign() {
return m_twistLimitSign;
}
void set_param(PhysicsServer::ConeTwistJointParam p_param, real_t p_value);
real_t get_param(PhysicsServer::ConeTwistJointParam p_param) const;
-
-
};
-
-
#endif // CONE_TWIST_JOINT_SW_H
diff --git a/servers/physics/joints/generic_6dof_joint_sw.cpp b/servers/physics/joints/generic_6dof_joint_sw.cpp
index bd07f3122a..1e07bc73fb 100644
--- a/servers/physics/joints/generic_6dof_joint_sw.cpp
+++ b/servers/physics/joints/generic_6dof_joint_sw.cpp
@@ -34,118 +34,90 @@ See corresponding header file for licensing info.
#include "generic_6dof_joint_sw.h"
-
-
#define GENERIC_D6_DISABLE_WARMSTARTING 1
-
//////////////////////////// G6DOFRotationalLimitMotorSW ////////////////////////////////////
-
-int G6DOFRotationalLimitMotorSW::testLimitValue(real_t test_value)
-{
- if(m_loLimit>m_hiLimit)
- {
- m_currentLimit = 0;//Free from violation
+int G6DOFRotationalLimitMotorSW::testLimitValue(real_t test_value) {
+ if (m_loLimit > m_hiLimit) {
+ m_currentLimit = 0; //Free from violation
return 0;
}
- if (test_value < m_loLimit)
- {
- m_currentLimit = 1;//low limit violation
- m_currentLimitError = test_value - m_loLimit;
+ if (test_value < m_loLimit) {
+ m_currentLimit = 1; //low limit violation
+ m_currentLimitError = test_value - m_loLimit;
return 1;
- }
- else if (test_value> m_hiLimit)
- {
- m_currentLimit = 2;//High limit violation
+ } else if (test_value > m_hiLimit) {
+ m_currentLimit = 2; //High limit violation
m_currentLimitError = test_value - m_hiLimit;
return 2;
};
- m_currentLimit = 0;//Free from violation
+ m_currentLimit = 0; //Free from violation
return 0;
-
}
-
real_t G6DOFRotationalLimitMotorSW::solveAngularLimits(
- real_t timeStep,Vector3& axis,real_t jacDiagABInv,
- BodySW * body0, BodySW * body1)
-{
- if (needApplyTorques()==false) return 0.0f;
+ real_t timeStep, Vector3 &axis, real_t jacDiagABInv,
+ BodySW *body0, BodySW *body1) {
+ if (needApplyTorques() == false) return 0.0f;
- real_t target_velocity = m_targetVelocity;
- real_t maxMotorForce = m_maxMotorForce;
+ real_t target_velocity = m_targetVelocity;
+ real_t maxMotorForce = m_maxMotorForce;
//current error correction
- if (m_currentLimit!=0)
- {
- target_velocity = -m_ERP*m_currentLimitError/(timeStep);
- maxMotorForce = m_maxLimitForce;
- }
-
- maxMotorForce *= timeStep;
-
- // current velocity difference
- Vector3 vel_diff = body0->get_angular_velocity();
- if (body1)
- {
- vel_diff -= body1->get_angular_velocity();
- }
+ if (m_currentLimit != 0) {
+ target_velocity = -m_ERP * m_currentLimitError / (timeStep);
+ maxMotorForce = m_maxLimitForce;
+ }
+ maxMotorForce *= timeStep;
+ // current velocity difference
+ Vector3 vel_diff = body0->get_angular_velocity();
+ if (body1) {
+ vel_diff -= body1->get_angular_velocity();
+ }
- real_t rel_vel = axis.dot(vel_diff);
+ real_t rel_vel = axis.dot(vel_diff);
// correction velocity
- real_t motor_relvel = m_limitSoftness*(target_velocity - m_damping*rel_vel);
-
-
- if ( motor_relvel < CMP_EPSILON && motor_relvel > -CMP_EPSILON )
- {
- return 0.0f;//no need for applying force
- }
+ real_t motor_relvel = m_limitSoftness * (target_velocity - m_damping * rel_vel);
+ if (motor_relvel < CMP_EPSILON && motor_relvel > -CMP_EPSILON) {
+ return 0.0f; //no need for applying force
+ }
// correction impulse
- real_t unclippedMotorImpulse = (1+m_bounce)*motor_relvel*jacDiagABInv;
+ real_t unclippedMotorImpulse = (1 + m_bounce) * motor_relvel * jacDiagABInv;
// clip correction impulse
- real_t clippedMotorImpulse;
-
- ///@todo: should clip against accumulated impulse
- if (unclippedMotorImpulse>0.0f)
- {
- clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce? maxMotorForce: unclippedMotorImpulse;
- }
- else
- {
- clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce: unclippedMotorImpulse;
- }
+ real_t clippedMotorImpulse;
+ ///@todo: should clip against accumulated impulse
+ if (unclippedMotorImpulse > 0.0f) {
+ clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce ? maxMotorForce : unclippedMotorImpulse;
+ } else {
+ clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce : unclippedMotorImpulse;
+ }
// sort with accumulated impulses
- real_t lo = real_t(-1e30);
- real_t hi = real_t(1e30);
-
- real_t oldaccumImpulse = m_accumulatedImpulse;
- real_t sum = oldaccumImpulse + clippedMotorImpulse;
- m_accumulatedImpulse = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum;
-
- clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse;
+ real_t lo = real_t(-1e30);
+ real_t hi = real_t(1e30);
+ real_t oldaccumImpulse = m_accumulatedImpulse;
+ real_t sum = oldaccumImpulse + clippedMotorImpulse;
+ m_accumulatedImpulse = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum;
+ clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse;
- Vector3 motorImp = clippedMotorImpulse * axis;
-
-
- body0->apply_torque_impulse(motorImp);
- if (body1) body1->apply_torque_impulse(-motorImp);
-
- return clippedMotorImpulse;
+ Vector3 motorImp = clippedMotorImpulse * axis;
+ body0->apply_torque_impulse(motorImp);
+ if (body1) body1->apply_torque_impulse(-motorImp);
+ return clippedMotorImpulse;
}
//////////////////////////// End G6DOFRotationalLimitMotorSW ////////////////////////////////////
@@ -153,120 +125,96 @@ real_t G6DOFRotationalLimitMotorSW::solveAngularLimits(
//////////////////////////// G6DOFTranslationalLimitMotorSW ////////////////////////////////////
real_t G6DOFTranslationalLimitMotorSW::solveLinearAxis(
real_t timeStep,
- real_t jacDiagABInv,
- BodySW* body1,const Vector3 &pointInA,
- BodySW* body2,const Vector3 &pointInB,
- int limit_index,
- const Vector3 & axis_normal_on_a,
- const Vector3 & anchorPos)
-{
-
-///find relative velocity
-// Vector3 rel_pos1 = pointInA - body1->get_transform().origin;
-// Vector3 rel_pos2 = pointInB - body2->get_transform().origin;
- Vector3 rel_pos1 = anchorPos - body1->get_transform().origin;
- Vector3 rel_pos2 = anchorPos - body2->get_transform().origin;
+ real_t jacDiagABInv,
+ BodySW *body1, const Vector3 &pointInA,
+ BodySW *body2, const Vector3 &pointInB,
+ int limit_index,
+ const Vector3 &axis_normal_on_a,
+ const Vector3 &anchorPos) {
- Vector3 vel1 = body1->get_velocity_in_local_point(rel_pos1);
- Vector3 vel2 = body2->get_velocity_in_local_point(rel_pos2);
- Vector3 vel = vel1 - vel2;
+ ///find relative velocity
+ // Vector3 rel_pos1 = pointInA - body1->get_transform().origin;
+ // Vector3 rel_pos2 = pointInB - body2->get_transform().origin;
+ Vector3 rel_pos1 = anchorPos - body1->get_transform().origin;
+ Vector3 rel_pos2 = anchorPos - body2->get_transform().origin;
- real_t rel_vel = axis_normal_on_a.dot(vel);
+ Vector3 vel1 = body1->get_velocity_in_local_point(rel_pos1);
+ Vector3 vel2 = body2->get_velocity_in_local_point(rel_pos2);
+ Vector3 vel = vel1 - vel2;
+ real_t rel_vel = axis_normal_on_a.dot(vel);
+ /// apply displacement correction
-/// apply displacement correction
+ //positional error (zeroth order error)
+ real_t depth = -(pointInA - pointInB).dot(axis_normal_on_a);
+ real_t lo = real_t(-1e30);
+ real_t hi = real_t(1e30);
-//positional error (zeroth order error)
- real_t depth = -(pointInA - pointInB).dot(axis_normal_on_a);
- real_t lo = real_t(-1e30);
- real_t hi = real_t(1e30);
+ real_t minLimit = m_lowerLimit[limit_index];
+ real_t maxLimit = m_upperLimit[limit_index];
- real_t minLimit = m_lowerLimit[limit_index];
- real_t maxLimit = m_upperLimit[limit_index];
-
- //handle the limits
- if (minLimit < maxLimit)
- {
- {
- if (depth > maxLimit)
- {
- depth -= maxLimit;
- lo = real_t(0.);
-
- }
- else
- {
- if (depth < minLimit)
- {
- depth -= minLimit;
- hi = real_t(0.);
- }
- else
+ //handle the limits
+ if (minLimit < maxLimit) {
{
- return 0.0f;
+ if (depth > maxLimit) {
+ depth -= maxLimit;
+ lo = real_t(0.);
+
+ } else {
+ if (depth < minLimit) {
+ depth -= minLimit;
+ hi = real_t(0.);
+ } else {
+ return 0.0f;
+ }
+ }
}
- }
}
- }
- real_t normalImpulse= m_limitSoftness[limit_index]*(m_restitution[limit_index]*depth/timeStep - m_damping[limit_index]*rel_vel) * jacDiagABInv;
+ real_t normalImpulse = m_limitSoftness[limit_index] * (m_restitution[limit_index] * depth / timeStep - m_damping[limit_index] * rel_vel) * jacDiagABInv;
+ real_t oldNormalImpulse = m_accumulatedImpulse[limit_index];
+ real_t sum = oldNormalImpulse + normalImpulse;
+ m_accumulatedImpulse[limit_index] = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum;
+ normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse;
-
-
- real_t oldNormalImpulse = m_accumulatedImpulse[limit_index];
- real_t sum = oldNormalImpulse + normalImpulse;
- m_accumulatedImpulse[limit_index] = sum > hi ? real_t(0.) : sum < lo ? real_t(0.) : sum;
- normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse;
-
- Vector3 impulse_vector = axis_normal_on_a * normalImpulse;
- body1->apply_impulse( rel_pos1, impulse_vector);
- body2->apply_impulse( rel_pos2, -impulse_vector);
- return normalImpulse;
+ Vector3 impulse_vector = axis_normal_on_a * normalImpulse;
+ body1->apply_impulse(rel_pos1, impulse_vector);
+ body2->apply_impulse(rel_pos2, -impulse_vector);
+ return normalImpulse;
}
//////////////////////////// G6DOFTranslationalLimitMotorSW ////////////////////////////////////
-
-Generic6DOFJointSW::Generic6DOFJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB, bool useLinearReferenceFrameA)
- : JointSW(_arr,2)
- , m_frameInA(frameInA)
- , m_frameInB(frameInB),
- m_useLinearReferenceFrameA(useLinearReferenceFrameA)
-{
- A=rbA;
- B=rbB;
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+Generic6DOFJointSW::Generic6DOFJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB, bool useLinearReferenceFrameA)
+ : JointSW(_arr, 2), m_frameInA(frameInA), m_frameInB(frameInB),
+ m_useLinearReferenceFrameA(useLinearReferenceFrameA) {
+ A = rbA;
+ B = rbB;
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
-
-
-
-
-void Generic6DOFJointSW::calculateAngleInfo()
-{
- Basis relative_frame = m_calculatedTransformA.basis.inverse()*m_calculatedTransformB.basis;
+void Generic6DOFJointSW::calculateAngleInfo() {
+ Basis relative_frame = m_calculatedTransformA.basis.inverse() * m_calculatedTransformB.basis;
m_calculatedAxisAngleDiff = relative_frame.get_euler();
-
-
// in euler angle mode we do not actually constrain the angular velocity
- // along the axes axis[0] and axis[2] (although we do use axis[1]) :
- //
- // to get constrain w2-w1 along ...not
- // ------ --------------------- ------
- // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0]
- // d(angle[1])/dt = 0 ax[1]
- // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2]
- //
- // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0.
- // to prove the result for angle[0], write the expression for angle[0] from
- // GetInfo1 then take the derivative. to prove this for angle[2] it is
- // easier to take the euler rate expression for d(angle[2])/dt with respect
- // to the components of w and set that to 0.
+ // along the axes axis[0] and axis[2] (although we do use axis[1]) :
+ //
+ // to get constrain w2-w1 along ...not
+ // ------ --------------------- ------
+ // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0]
+ // d(angle[1])/dt = 0 ax[1]
+ // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2]
+ //
+ // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0.
+ // to prove the result for angle[0], write the expression for angle[0] from
+ // GetInfo1 then take the derivative. to prove this for angle[2] it is
+ // easier to take the euler rate expression for d(angle[2])/dt with respect
+ // to the components of w and set that to 0.
Vector3 axis0 = m_calculatedTransformB.basis.get_axis(0);
Vector3 axis2 = m_calculatedTransformA.basis.get_axis(2);
@@ -275,7 +223,6 @@ void Generic6DOFJointSW::calculateAngleInfo()
m_calculatedAxis[0] = m_calculatedAxis[1].cross(axis2);
m_calculatedAxis[2] = axis0.cross(m_calculatedAxis[1]);
-
/*
if(m_debugDrawer)
{
@@ -288,280 +235,250 @@ void Generic6DOFJointSW::calculateAngleInfo()
m_debugDrawer->reportErrorWarning(buff);
}
*/
-
}
-void Generic6DOFJointSW::calculateTransforms()
-{
- m_calculatedTransformA = A->get_transform() * m_frameInA;
- m_calculatedTransformB = B->get_transform() * m_frameInB;
+void Generic6DOFJointSW::calculateTransforms() {
+ m_calculatedTransformA = A->get_transform() * m_frameInA;
+ m_calculatedTransformB = B->get_transform() * m_frameInB;
- calculateAngleInfo();
+ calculateAngleInfo();
}
-
void Generic6DOFJointSW::buildLinearJacobian(
- JacobianEntrySW & jacLinear,const Vector3 & normalWorld,
- const Vector3 & pivotAInW,const Vector3 & pivotBInW)
-{
- memnew_placement(&jacLinear, JacobianEntrySW(
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
- pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
- normalWorld,
- A->get_inv_inertia(),
- A->get_inv_mass(),
- B->get_inv_inertia(),
- B->get_inv_mass()));
-
+ JacobianEntrySW &jacLinear, const Vector3 &normalWorld,
+ const Vector3 &pivotAInW, const Vector3 &pivotBInW) {
+ memnew_placement(&jacLinear, JacobianEntrySW(
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
+ pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
+ normalWorld,
+ A->get_inv_inertia(),
+ A->get_inv_mass(),
+ B->get_inv_inertia(),
+ B->get_inv_mass()));
}
void Generic6DOFJointSW::buildAngularJacobian(
- JacobianEntrySW & jacAngular,const Vector3 & jointAxisW)
-{
- memnew_placement(&jacAngular, JacobianEntrySW(jointAxisW,
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_inv_inertia(),
- B->get_inv_inertia()));
-
+ JacobianEntrySW &jacAngular, const Vector3 &jointAxisW) {
+ memnew_placement(&jacAngular, JacobianEntrySW(jointAxisW,
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_inv_inertia(),
+ B->get_inv_inertia()));
}
-bool Generic6DOFJointSW::testAngularLimitMotor(int axis_index)
-{
- real_t angle = m_calculatedAxisAngleDiff[axis_index];
+bool Generic6DOFJointSW::testAngularLimitMotor(int axis_index) {
+ real_t angle = m_calculatedAxisAngleDiff[axis_index];
- //test limits
- m_angularLimits[axis_index].testLimitValue(angle);
- return m_angularLimits[axis_index].needApplyTorques();
+ //test limits
+ m_angularLimits[axis_index].testLimitValue(angle);
+ return m_angularLimits[axis_index].needApplyTorques();
}
bool Generic6DOFJointSW::setup(real_t p_step) {
// Clear accumulated impulses for the next simulation step
- m_linearLimits.m_accumulatedImpulse=Vector3(real_t(0.), real_t(0.), real_t(0.));
- int i;
- for(i = 0; i < 3; i++)
- {
- m_angularLimits[i].m_accumulatedImpulse = real_t(0.);
- }
- //calculates transform
- calculateTransforms();
-
-// const Vector3& pivotAInW = m_calculatedTransformA.origin;
-// const Vector3& pivotBInW = m_calculatedTransformB.origin;
+ m_linearLimits.m_accumulatedImpulse = Vector3(real_t(0.), real_t(0.), real_t(0.));
+ int i;
+ for (i = 0; i < 3; i++) {
+ m_angularLimits[i].m_accumulatedImpulse = real_t(0.);
+ }
+ //calculates transform
+ calculateTransforms();
+
+ // const Vector3& pivotAInW = m_calculatedTransformA.origin;
+ // const Vector3& pivotBInW = m_calculatedTransformB.origin;
calcAnchorPos();
Vector3 pivotAInW = m_AnchorPos;
Vector3 pivotBInW = m_AnchorPos;
-// not used here
-// Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
-// Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
+ // not used here
+ // Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
+ // Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
- Vector3 normalWorld;
- //linear part
- for (i=0;i<3;i++)
- {
- if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i))
- {
+ Vector3 normalWorld;
+ //linear part
+ for (i = 0; i < 3; i++) {
+ if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) {
if (m_useLinearReferenceFrameA)
- normalWorld = m_calculatedTransformA.basis.get_axis(i);
+ normalWorld = m_calculatedTransformA.basis.get_axis(i);
else
- normalWorld = m_calculatedTransformB.basis.get_axis(i);
-
- buildLinearJacobian(
- m_jacLinear[i],normalWorld ,
- pivotAInW,pivotBInW);
+ normalWorld = m_calculatedTransformB.basis.get_axis(i);
+ buildLinearJacobian(
+ m_jacLinear[i], normalWorld,
+ pivotAInW, pivotBInW);
+ }
}
- }
- // angular part
- for (i=0;i<3;i++)
- {
- //calculates error angle
- if (m_angularLimits[i].m_enableLimit && testAngularLimitMotor(i))
- {
- normalWorld = this->getAxis(i);
- // Create angular atom
- buildAngularJacobian(m_jacAng[i],normalWorld);
+ // angular part
+ for (i = 0; i < 3; i++) {
+ //calculates error angle
+ if (m_angularLimits[i].m_enableLimit && testAngularLimitMotor(i)) {
+ normalWorld = this->getAxis(i);
+ // Create angular atom
+ buildAngularJacobian(m_jacAng[i], normalWorld);
+ }
}
- }
return true;
}
+void Generic6DOFJointSW::solve(real_t timeStep) {
+ m_timeStep = timeStep;
-void Generic6DOFJointSW::solve(real_t timeStep)
-{
- m_timeStep = timeStep;
-
- //calculateTransforms();
+ //calculateTransforms();
- int i;
+ int i;
- // linear
+ // linear
- Vector3 pointInA = m_calculatedTransformA.origin;
+ Vector3 pointInA = m_calculatedTransformA.origin;
Vector3 pointInB = m_calculatedTransformB.origin;
real_t jacDiagABInv;
Vector3 linear_axis;
- for (i=0;i<3;i++)
- {
- if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i))
- {
- jacDiagABInv = real_t(1.) / m_jacLinear[i].getDiagonal();
+ for (i = 0; i < 3; i++) {
+ if (m_linearLimits.enable_limit[i] && m_linearLimits.isLimited(i)) {
+ jacDiagABInv = real_t(1.) / m_jacLinear[i].getDiagonal();
if (m_useLinearReferenceFrameA)
- linear_axis = m_calculatedTransformA.basis.get_axis(i);
+ linear_axis = m_calculatedTransformA.basis.get_axis(i);
else
- linear_axis = m_calculatedTransformB.basis.get_axis(i);
-
- m_linearLimits.solveLinearAxis(
- m_timeStep,
- jacDiagABInv,
- A,pointInA,
- B,pointInB,
- i,linear_axis, m_AnchorPos);
-
+ linear_axis = m_calculatedTransformB.basis.get_axis(i);
+
+ m_linearLimits.solveLinearAxis(
+ m_timeStep,
+ jacDiagABInv,
+ A, pointInA,
+ B, pointInB,
+ i, linear_axis, m_AnchorPos);
+ }
}
- }
-
- // angular
- Vector3 angular_axis;
- real_t angularJacDiagABInv;
- for (i=0;i<3;i++)
- {
- if (m_angularLimits[i].m_enableLimit && m_angularLimits[i].needApplyTorques())
- {
+
+ // angular
+ Vector3 angular_axis;
+ real_t angularJacDiagABInv;
+ for (i = 0; i < 3; i++) {
+ if (m_angularLimits[i].m_enableLimit && m_angularLimits[i].needApplyTorques()) {
// get axis
angular_axis = getAxis(i);
angularJacDiagABInv = real_t(1.) / m_jacAng[i].getDiagonal();
- m_angularLimits[i].solveAngularLimits(m_timeStep,angular_axis,angularJacDiagABInv, A,B);
+ m_angularLimits[i].solveAngularLimits(m_timeStep, angular_axis, angularJacDiagABInv, A, B);
+ }
}
- }
}
-void Generic6DOFJointSW::updateRHS(real_t timeStep)
-{
- (void)timeStep;
-
+void Generic6DOFJointSW::updateRHS(real_t timeStep) {
+ (void)timeStep;
}
-Vector3 Generic6DOFJointSW::getAxis(int axis_index) const
-{
- return m_calculatedAxis[axis_index];
+Vector3 Generic6DOFJointSW::getAxis(int axis_index) const {
+ return m_calculatedAxis[axis_index];
}
-real_t Generic6DOFJointSW::getAngle(int axis_index) const
-{
- return m_calculatedAxisAngleDiff[axis_index];
+real_t Generic6DOFJointSW::getAngle(int axis_index) const {
+ return m_calculatedAxisAngleDiff[axis_index];
}
-void Generic6DOFJointSW::calcAnchorPos(void)
-{
+void Generic6DOFJointSW::calcAnchorPos(void) {
real_t imA = A->get_inv_mass();
real_t imB = B->get_inv_mass();
real_t weight;
- if(imB == real_t(0.0))
- {
+ if (imB == real_t(0.0)) {
weight = real_t(1.0);
- }
- else
- {
+ } else {
weight = imA / (imA + imB);
}
- const Vector3& pA = m_calculatedTransformA.origin;
- const Vector3& pB = m_calculatedTransformB.origin;
+ const Vector3 &pA = m_calculatedTransformA.origin;
+ const Vector3 &pB = m_calculatedTransformB.origin;
m_AnchorPos = pA * weight + pB * (real_t(1.0) - weight);
return;
} // Generic6DOFJointSW::calcAnchorPos()
+void Generic6DOFJointSW::set_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value) {
-void Generic6DOFJointSW::set_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value) {
-
- ERR_FAIL_INDEX(p_axis,3);
- switch(p_param) {
+ ERR_FAIL_INDEX(p_axis, 3);
+ switch (p_param) {
case PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT: {
- m_linearLimits.m_lowerLimit[p_axis]=p_value;
+ m_linearLimits.m_lowerLimit[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_LINEAR_UPPER_LIMIT: {
- m_linearLimits.m_upperLimit[p_axis]=p_value;
+ m_linearLimits.m_upperLimit[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS: {
- m_linearLimits.m_limitSoftness[p_axis]=p_value;
+ m_linearLimits.m_limitSoftness[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_LINEAR_RESTITUTION: {
- m_linearLimits.m_restitution[p_axis]=p_value;
+ m_linearLimits.m_restitution[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_LINEAR_DAMPING: {
- m_linearLimits.m_damping[p_axis]=p_value;
+ m_linearLimits.m_damping[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_LOWER_LIMIT: {
- m_angularLimits[p_axis].m_loLimit=p_value;
+ m_angularLimits[p_axis].m_loLimit = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_UPPER_LIMIT: {
- m_angularLimits[p_axis].m_hiLimit=p_value;
+ m_angularLimits[p_axis].m_hiLimit = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS: {
- m_angularLimits[p_axis].m_limitSoftness=p_value;
+ m_angularLimits[p_axis].m_limitSoftness = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_DAMPING: {
- m_angularLimits[p_axis].m_damping=p_value;
+ m_angularLimits[p_axis].m_damping = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_RESTITUTION: {
- m_angularLimits[p_axis].m_bounce=p_value;
+ m_angularLimits[p_axis].m_bounce = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_FORCE_LIMIT: {
- m_angularLimits[p_axis].m_maxLimitForce=p_value;
+ m_angularLimits[p_axis].m_maxLimitForce = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_ERP: {
- m_angularLimits[p_axis].m_ERP=p_value;
+ m_angularLimits[p_axis].m_ERP = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY: {
- m_angularLimits[p_axis].m_targetVelocity=p_value;
+ m_angularLimits[p_axis].m_targetVelocity = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT: {
- m_angularLimits[p_axis].m_maxLimitForce=p_value;
+ m_angularLimits[p_axis].m_maxLimitForce = p_value;
} break;
}
}
-real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param) const{
- ERR_FAIL_INDEX_V(p_axis,3,0);
- switch(p_param) {
+real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param) const {
+ ERR_FAIL_INDEX_V(p_axis, 3, 0);
+ switch (p_param) {
case PhysicsServer::G6DOF_JOINT_LINEAR_LOWER_LIMIT: {
return m_linearLimits.m_lowerLimit[p_axis];
@@ -635,31 +552,29 @@ real_t Generic6DOFJointSW::get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJo
return 0;
}
-void Generic6DOFJointSW::set_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value){
+void Generic6DOFJointSW::set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value) {
- ERR_FAIL_INDEX(p_axis,3);
+ ERR_FAIL_INDEX(p_axis, 3);
- switch(p_flag) {
+ switch (p_flag) {
case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT: {
- m_linearLimits.enable_limit[p_axis]=p_value;
+ m_linearLimits.enable_limit[p_axis] = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT: {
- m_angularLimits[p_axis].m_enableLimit=p_value;
+ m_angularLimits[p_axis].m_enableLimit = p_value;
} break;
case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_MOTOR: {
- m_angularLimits[p_axis].m_enableMotor=p_value;
+ m_angularLimits[p_axis].m_enableMotor = p_value;
} break;
}
-
-
}
-bool Generic6DOFJointSW::get_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag) const{
+bool Generic6DOFJointSW::get_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag) const {
- ERR_FAIL_INDEX_V(p_axis,3,0);
- switch(p_flag) {
+ ERR_FAIL_INDEX_V(p_axis, 3, 0);
+ switch (p_flag) {
case PhysicsServer::G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT: {
return m_linearLimits.enable_limit[p_axis];
diff --git a/servers/physics/joints/generic_6dof_joint_sw.h b/servers/physics/joints/generic_6dof_joint_sw.h
index 207ae85a45..87245c6ffe 100644
--- a/servers/physics/joints/generic_6dof_joint_sw.h
+++ b/servers/physics/joints/generic_6dof_joint_sw.h
@@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library.
#ifndef GENERIC_6DOF_JOINT_SW_H
#define GENERIC_6DOF_JOINT_SW_H
-#include "servers/physics/joints_sw.h"
#include "servers/physics/joints/jacobian_entry_sw.h"
-
+#include "servers/physics/joints_sw.h"
/*
Bullet Continuous Collision Detection and Physics Library
@@ -53,7 +52,6 @@ subject to the following restrictions:
3. This notice may not be removed or altered from any source distribution.
*/
-
/*
2007-09-09
Generic6DOFJointSW Refactored by Francisco Le?n
@@ -61,80 +59,73 @@ email: projectileman@yahoo.com
http://gimpact.sf.net
*/
-
//! Rotation Limit structure for generic joints
class G6DOFRotationalLimitMotorSW {
public:
- //! limit_parameters
- //!@{
- real_t m_loLimit;//!< joint limit
- real_t m_hiLimit;//!< joint limit
- real_t m_targetVelocity;//!< target motor velocity
- real_t m_maxMotorForce;//!< max force on motor
- real_t m_maxLimitForce;//!< max force on limit
- real_t m_damping;//!< Damping.
- real_t m_limitSoftness;//! Relaxation factor
- real_t m_ERP;//!< Error tolerance factor when joint is at limit
- real_t m_bounce;//!< restitution factor
- bool m_enableMotor;
- bool m_enableLimit;
-
- //!@}
-
- //! temp_variables
- //!@{
- real_t m_currentLimitError;//! How much is violated this limit
- int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit
- real_t m_accumulatedImpulse;
- //!@}
-
- G6DOFRotationalLimitMotorSW()
- {
- m_accumulatedImpulse = 0.f;
- m_targetVelocity = 0;
- m_maxMotorForce = 0.1f;
- m_maxLimitForce = 300.0f;
- m_loLimit = -1e30;
- m_hiLimit = 1e30;
- m_ERP = 0.5f;
- m_bounce = 0.0f;
- m_damping = 1.0f;
- m_limitSoftness = 0.5f;
- m_currentLimit = 0;
- m_currentLimitError = 0;
- m_enableMotor = false;
- m_enableLimit=false;
- }
-
- G6DOFRotationalLimitMotorSW(const G6DOFRotationalLimitMotorSW & limot)
- {
- m_targetVelocity = limot.m_targetVelocity;
- m_maxMotorForce = limot.m_maxMotorForce;
- m_limitSoftness = limot.m_limitSoftness;
- m_loLimit = limot.m_loLimit;
- m_hiLimit = limot.m_hiLimit;
- m_ERP = limot.m_ERP;
- m_bounce = limot.m_bounce;
- m_currentLimit = limot.m_currentLimit;
- m_currentLimitError = limot.m_currentLimitError;
- m_enableMotor = limot.m_enableMotor;
- }
+ //! limit_parameters
+ //!@{
+ real_t m_loLimit; //!< joint limit
+ real_t m_hiLimit; //!< joint limit
+ real_t m_targetVelocity; //!< target motor velocity
+ real_t m_maxMotorForce; //!< max force on motor
+ real_t m_maxLimitForce; //!< max force on limit
+ real_t m_damping; //!< Damping.
+ real_t m_limitSoftness; //! Relaxation factor
+ real_t m_ERP; //!< Error tolerance factor when joint is at limit
+ real_t m_bounce; //!< restitution factor
+ bool m_enableMotor;
+ bool m_enableLimit;
+
+ //!@}
+
+ //! temp_variables
+ //!@{
+ real_t m_currentLimitError; //! How much is violated this limit
+ int m_currentLimit; //!< 0=free, 1=at lo limit, 2=at hi limit
+ real_t m_accumulatedImpulse;
+ //!@}
+ G6DOFRotationalLimitMotorSW() {
+ m_accumulatedImpulse = 0.f;
+ m_targetVelocity = 0;
+ m_maxMotorForce = 0.1f;
+ m_maxLimitForce = 300.0f;
+ m_loLimit = -1e30;
+ m_hiLimit = 1e30;
+ m_ERP = 0.5f;
+ m_bounce = 0.0f;
+ m_damping = 1.0f;
+ m_limitSoftness = 0.5f;
+ m_currentLimit = 0;
+ m_currentLimitError = 0;
+ m_enableMotor = false;
+ m_enableLimit = false;
+ }
+ G6DOFRotationalLimitMotorSW(const G6DOFRotationalLimitMotorSW &limot) {
+ m_targetVelocity = limot.m_targetVelocity;
+ m_maxMotorForce = limot.m_maxMotorForce;
+ m_limitSoftness = limot.m_limitSoftness;
+ m_loLimit = limot.m_loLimit;
+ m_hiLimit = limot.m_hiLimit;
+ m_ERP = limot.m_ERP;
+ m_bounce = limot.m_bounce;
+ m_currentLimit = limot.m_currentLimit;
+ m_currentLimitError = limot.m_currentLimitError;
+ m_enableMotor = limot.m_enableMotor;
+ }
//! Is limited
- bool isLimited()
- {
- if(m_loLimit>=m_hiLimit) return false;
- return true;
- }
+ bool isLimited() {
+ if (m_loLimit >= m_hiLimit) return false;
+ return true;
+ }
//! Need apply correction
- bool needApplyTorques()
- {
- if(m_currentLimit == 0 && m_enableMotor == false) return false;
- return true;
- }
+ bool needApplyTorques() {
+ if (m_currentLimit == 0 && m_enableMotor == false) return false;
+ return true;
+ }
//! calculates error
/*!
@@ -143,84 +134,69 @@ public:
int testLimitValue(real_t test_value);
//! apply the correction impulses for two bodies
- real_t solveAngularLimits(real_t timeStep,Vector3& axis, real_t jacDiagABInv,BodySW * body0, BodySW * body1);
+ real_t solveAngularLimits(real_t timeStep, Vector3 &axis, real_t jacDiagABInv, BodySW *body0, BodySW *body1);
+};
+class G6DOFTranslationalLimitMotorSW {
+public:
+ Vector3 m_lowerLimit; //!< the constraint lower limits
+ Vector3 m_upperLimit; //!< the constraint upper limits
+ Vector3 m_accumulatedImpulse;
+ //! Linear_Limit_parameters
+ //!@{
+ Vector3 m_limitSoftness; //!< Softness for linear limit
+ Vector3 m_damping; //!< Damping for linear limit
+ Vector3 m_restitution; //! Bounce parameter for linear limit
+ //!@}
+ bool enable_limit[3];
-};
+ G6DOFTranslationalLimitMotorSW() {
+ m_lowerLimit = Vector3(0.f, 0.f, 0.f);
+ m_upperLimit = Vector3(0.f, 0.f, 0.f);
+ m_accumulatedImpulse = Vector3(0.f, 0.f, 0.f);
+ m_limitSoftness = Vector3(1, 1, 1) * 0.7f;
+ m_damping = Vector3(1, 1, 1) * real_t(1.0f);
+ m_restitution = Vector3(1, 1, 1) * real_t(0.5f);
+ enable_limit[0] = true;
+ enable_limit[1] = true;
+ enable_limit[2] = true;
+ }
-class G6DOFTranslationalLimitMotorSW
-{
-public:
- Vector3 m_lowerLimit;//!< the constraint lower limits
- Vector3 m_upperLimit;//!< the constraint upper limits
- Vector3 m_accumulatedImpulse;
- //! Linear_Limit_parameters
- //!@{
- Vector3 m_limitSoftness;//!< Softness for linear limit
- Vector3 m_damping;//!< Damping for linear limit
- Vector3 m_restitution;//! Bounce parameter for linear limit
- //!@}
- bool enable_limit[3];
-
- G6DOFTranslationalLimitMotorSW()
- {
- m_lowerLimit=Vector3(0.f,0.f,0.f);
- m_upperLimit=Vector3(0.f,0.f,0.f);
- m_accumulatedImpulse=Vector3(0.f,0.f,0.f);
-
- m_limitSoftness = Vector3(1,1,1)*0.7f;
- m_damping = Vector3(1,1,1)*real_t(1.0f);
- m_restitution = Vector3(1,1,1)*real_t(0.5f);
-
- enable_limit[0]=true;
- enable_limit[1]=true;
- enable_limit[2]=true;
- }
-
- G6DOFTranslationalLimitMotorSW(const G6DOFTranslationalLimitMotorSW & other )
- {
- m_lowerLimit = other.m_lowerLimit;
- m_upperLimit = other.m_upperLimit;
- m_accumulatedImpulse = other.m_accumulatedImpulse;
-
- m_limitSoftness = other.m_limitSoftness ;
- m_damping = other.m_damping;
- m_restitution = other.m_restitution;
- }
-
- //! Test limit
+ G6DOFTranslationalLimitMotorSW(const G6DOFTranslationalLimitMotorSW &other) {
+ m_lowerLimit = other.m_lowerLimit;
+ m_upperLimit = other.m_upperLimit;
+ m_accumulatedImpulse = other.m_accumulatedImpulse;
+
+ m_limitSoftness = other.m_limitSoftness;
+ m_damping = other.m_damping;
+ m_restitution = other.m_restitution;
+ }
+
+ //! Test limit
/*!
- free means upper < lower,
- locked means upper == lower
- limited means upper > lower
- limitIndex: first 3 are linear, next 3 are angular
*/
- inline bool isLimited(int limitIndex)
- {
- return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]);
- }
-
-
- real_t solveLinearAxis(
- real_t timeStep,
- real_t jacDiagABInv,
- BodySW* body1,const Vector3 &pointInA,
- BodySW* body2,const Vector3 &pointInB,
- int limit_index,
- const Vector3 & axis_normal_on_a,
- const Vector3 & anchorPos);
-
+ inline bool isLimited(int limitIndex) {
+ return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]);
+ }
+ real_t solveLinearAxis(
+ real_t timeStep,
+ real_t jacDiagABInv,
+ BodySW *body1, const Vector3 &pointInA,
+ BodySW *body2, const Vector3 &pointInB,
+ int limit_index,
+ const Vector3 &axis_normal_on_a,
+ const Vector3 &anchorPos);
};
-
-class Generic6DOFJointSW : public JointSW
-{
+class Generic6DOFJointSW : public JointSW {
protected:
-
-
union {
struct {
BodySW *A;
@@ -231,195 +207,167 @@ protected:
};
//! relative_frames
- //!@{
- Transform m_frameInA;//!< the constraint space w.r.t body A
- Transform m_frameInB;//!< the constraint space w.r.t body B
- //!@}
+ //!@{
+ Transform m_frameInA; //!< the constraint space w.r.t body A
+ Transform m_frameInB; //!< the constraint space w.r.t body B
+ //!@}
- //! Jacobians
- //!@{
- JacobianEntrySW m_jacLinear[3];//!< 3 orthogonal linear constraints
- JacobianEntrySW m_jacAng[3];//!< 3 orthogonal angular constraints
- //!@}
+ //! Jacobians
+ //!@{
+ JacobianEntrySW m_jacLinear[3]; //!< 3 orthogonal linear constraints
+ JacobianEntrySW m_jacAng[3]; //!< 3 orthogonal angular constraints
+ //!@}
//! Linear_Limit_parameters
- //!@{
- G6DOFTranslationalLimitMotorSW m_linearLimits;
- //!@}
-
-
- //! hinge_parameters
- //!@{
- G6DOFRotationalLimitMotorSW m_angularLimits[3];
+ //!@{
+ G6DOFTranslationalLimitMotorSW m_linearLimits;
//!@}
+ //! hinge_parameters
+ //!@{
+ G6DOFRotationalLimitMotorSW m_angularLimits[3];
+ //!@}
protected:
- //! temporal variables
- //!@{
- real_t m_timeStep;
- Transform m_calculatedTransformA;
- Transform m_calculatedTransformB;
- Vector3 m_calculatedAxisAngleDiff;
- Vector3 m_calculatedAxis[3];
+ //! temporal variables
+ //!@{
+ real_t m_timeStep;
+ Transform m_calculatedTransformA;
+ Transform m_calculatedTransformB;
+ Vector3 m_calculatedAxisAngleDiff;
+ Vector3 m_calculatedAxis[3];
Vector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes
- bool m_useLinearReferenceFrameA;
-
- //!@}
-
- Generic6DOFJointSW& operator=(Generic6DOFJointSW& other)
- {
- ERR_PRINT("pito");
- (void) other;
- return *this;
- }
-
+ bool m_useLinearReferenceFrameA;
+ //!@}
- void buildLinearJacobian(
- JacobianEntrySW & jacLinear,const Vector3 & normalWorld,
- const Vector3 & pivotAInW,const Vector3 & pivotBInW);
+ Generic6DOFJointSW &operator=(Generic6DOFJointSW &other) {
+ ERR_PRINT("pito");
+ (void)other;
+ return *this;
+ }
- void buildAngularJacobian(JacobianEntrySW & jacAngular,const Vector3 & jointAxisW);
+ void buildLinearJacobian(
+ JacobianEntrySW &jacLinear, const Vector3 &normalWorld,
+ const Vector3 &pivotAInW, const Vector3 &pivotBInW);
+ void buildAngularJacobian(JacobianEntrySW &jacAngular, const Vector3 &jointAxisW);
//! calcs the euler angles between the two bodies.
- void calculateAngleInfo();
-
-
+ void calculateAngleInfo();
public:
- Generic6DOFJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB ,bool useLinearReferenceFrameA);
+ Generic6DOFJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB, bool useLinearReferenceFrameA);
- virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_6DOF; }
-
- virtual bool setup(real_t p_step);
- virtual void solve(real_t p_step);
+ virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_6DOF; }
+ virtual bool setup(real_t p_step);
+ virtual void solve(real_t p_step);
//! Calcs global transform of the offsets
/*!
Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies.
\sa Generic6DOFJointSW.getCalculatedTransformA , Generic6DOFJointSW.getCalculatedTransformB, Generic6DOFJointSW.calculateAngleInfo
*/
- void calculateTransforms();
+ void calculateTransforms();
//! Gets the global transform of the offset for body A
- /*!
+ /*!
\sa Generic6DOFJointSW.getFrameOffsetA, Generic6DOFJointSW.getFrameOffsetB, Generic6DOFJointSW.calculateAngleInfo.
*/
- const Transform & getCalculatedTransformA() const
- {
- return m_calculatedTransformA;
- }
+ const Transform &getCalculatedTransformA() const {
+ return m_calculatedTransformA;
+ }
- //! Gets the global transform of the offset for body B
- /*!
+ //! Gets the global transform of the offset for body B
+ /*!
\sa Generic6DOFJointSW.getFrameOffsetA, Generic6DOFJointSW.getFrameOffsetB, Generic6DOFJointSW.calculateAngleInfo.
*/
- const Transform & getCalculatedTransformB() const
- {
- return m_calculatedTransformB;
- }
-
- const Transform & getFrameOffsetA() const
- {
- return m_frameInA;
- }
-
- const Transform & getFrameOffsetB() const
- {
- return m_frameInB;
- }
+ const Transform &getCalculatedTransformB() const {
+ return m_calculatedTransformB;
+ }
+ const Transform &getFrameOffsetA() const {
+ return m_frameInA;
+ }
- Transform & getFrameOffsetA()
- {
- return m_frameInA;
- }
+ const Transform &getFrameOffsetB() const {
+ return m_frameInB;
+ }
- Transform & getFrameOffsetB()
- {
- return m_frameInB;
- }
+ Transform &getFrameOffsetA() {
+ return m_frameInA;
+ }
+ Transform &getFrameOffsetB() {
+ return m_frameInB;
+ }
//! performs Jacobian calculation, and also calculates angle differences and axis
-
- void updateRHS(real_t timeStep);
+ void updateRHS(real_t timeStep);
//! Get the rotation axis in global coordinates
/*!
\pre Generic6DOFJointSW.buildJacobian must be called previously.
*/
- Vector3 getAxis(int axis_index) const;
+ Vector3 getAxis(int axis_index) const;
- //! Get the relative Euler angle
- /*!
+ //! Get the relative Euler angle
+ /*!
\pre Generic6DOFJointSW.buildJacobian must be called previously.
*/
- real_t getAngle(int axis_index) const;
+ real_t getAngle(int axis_index) const;
//! Test angular limit.
/*!
Calculates angular correction and returns true if limit needs to be corrected.
\pre Generic6DOFJointSW.buildJacobian must be called previously.
*/
- bool testAngularLimitMotor(int axis_index);
-
- void setLinearLowerLimit(const Vector3& linearLower)
- {
- m_linearLimits.m_lowerLimit = linearLower;
- }
-
- void setLinearUpperLimit(const Vector3& linearUpper)
- {
- m_linearLimits.m_upperLimit = linearUpper;
- }
-
- void setAngularLowerLimit(const Vector3& angularLower)
- {
- m_angularLimits[0].m_loLimit = angularLower.x;
- m_angularLimits[1].m_loLimit = angularLower.y;
- m_angularLimits[2].m_loLimit = angularLower.z;
- }
-
- void setAngularUpperLimit(const Vector3& angularUpper)
- {
- m_angularLimits[0].m_hiLimit = angularUpper.x;
- m_angularLimits[1].m_hiLimit = angularUpper.y;
- m_angularLimits[2].m_hiLimit = angularUpper.z;
- }
+ bool testAngularLimitMotor(int axis_index);
+
+ void setLinearLowerLimit(const Vector3 &linearLower) {
+ m_linearLimits.m_lowerLimit = linearLower;
+ }
+
+ void setLinearUpperLimit(const Vector3 &linearUpper) {
+ m_linearLimits.m_upperLimit = linearUpper;
+ }
+
+ void setAngularLowerLimit(const Vector3 &angularLower) {
+ m_angularLimits[0].m_loLimit = angularLower.x;
+ m_angularLimits[1].m_loLimit = angularLower.y;
+ m_angularLimits[2].m_loLimit = angularLower.z;
+ }
+
+ void setAngularUpperLimit(const Vector3 &angularUpper) {
+ m_angularLimits[0].m_hiLimit = angularUpper.x;
+ m_angularLimits[1].m_hiLimit = angularUpper.y;
+ m_angularLimits[2].m_hiLimit = angularUpper.z;
+ }
//! Retrieves the angular limit informacion
- G6DOFRotationalLimitMotorSW * getRotationalLimitMotor(int index)
- {
- return &m_angularLimits[index];
- }
-
- //! Retrieves the limit informacion
- G6DOFTranslationalLimitMotorSW * getTranslationalLimitMotor()
- {
- return &m_linearLimits;
- }
-
- //first 3 are linear, next 3 are angular
- void setLimit(int axis, real_t lo, real_t hi)
- {
- if(axis<3)
- {
- m_linearLimits.m_lowerLimit[axis] = lo;
- m_linearLimits.m_upperLimit[axis] = hi;
+ G6DOFRotationalLimitMotorSW *getRotationalLimitMotor(int index) {
+ return &m_angularLimits[index];
+ }
+
+ //! Retrieves the limit informacion
+ G6DOFTranslationalLimitMotorSW *getTranslationalLimitMotor() {
+ return &m_linearLimits;
}
- else
- {
- m_angularLimits[axis-3].m_loLimit = lo;
- m_angularLimits[axis-3].m_hiLimit = hi;
+
+ //first 3 are linear, next 3 are angular
+ void setLimit(int axis, real_t lo, real_t hi) {
+ if (axis < 3) {
+ m_linearLimits.m_lowerLimit[axis] = lo;
+ m_linearLimits.m_upperLimit[axis] = hi;
+ } else {
+ m_angularLimits[axis - 3].m_loLimit = lo;
+ m_angularLimits[axis - 3].m_hiLimit = hi;
+ }
}
- }
//! Test limit
/*!
@@ -428,34 +376,27 @@ public:
- limited means upper > lower
- limitIndex: first 3 are linear, next 3 are angular
*/
- bool isLimited(int limitIndex)
- {
- if(limitIndex<3)
- {
+ bool isLimited(int limitIndex) {
+ if (limitIndex < 3) {
return m_linearLimits.isLimited(limitIndex);
+ }
+ return m_angularLimits[limitIndex - 3].isLimited();
+ }
+ const BodySW *getRigidBodyA() const {
+ return A;
+ }
+ const BodySW *getRigidBodyB() const {
+ return B;
}
- return m_angularLimits[limitIndex-3].isLimited();
- }
-
- const BodySW* getRigidBodyA() const
- {
- return A;
- }
- const BodySW* getRigidBodyB() const
- {
- return B;
- }
virtual void calcAnchorPos(void); // overridable
- void set_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value);
- real_t get_param(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisParam p_param) const;
-
- void set_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value);
- bool get_flag(Vector3::Axis p_axis,PhysicsServer::G6DOFJointAxisFlag p_flag) const;
+ void set_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param, real_t p_value);
+ real_t get_param(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisParam p_param) const;
+ void set_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag, bool p_value);
+ bool get_flag(Vector3::Axis p_axis, PhysicsServer::G6DOFJointAxisFlag p_flag) const;
};
-
#endif // GENERIC_6DOF_JOINT_SW_H
diff --git a/servers/physics/joints/hinge_joint_sw.cpp b/servers/physics/joints/hinge_joint_sw.cpp
index 9617eb8794..eaa57af873 100644
--- a/servers/physics/joints/hinge_joint_sw.cpp
+++ b/servers/physics/joints/hinge_joint_sw.cpp
@@ -34,65 +34,63 @@ See corresponding header file for licensing info.
#include "hinge_joint_sw.h"
-static void plane_space(const Vector3& n, Vector3& p, Vector3& q) {
-
- if (Math::abs(n.z) > 0.707106781186547524400844362) {
- // choose p in y-z plane
- real_t a = n[1]*n[1] + n[2]*n[2];
- real_t k = 1.0/Math::sqrt(a);
- p=Vector3(0,-n[2]*k,n[1]*k);
- // set q = n x p
- q=Vector3(a*k,-n[0]*p[2],n[0]*p[1]);
- }
- else {
- // choose p in x-y plane
- real_t a = n.x*n.x + n.y*n.y;
- real_t k = 1.0/Math::sqrt(a);
- p=Vector3(-n.y*k,n.x*k,0);
- // set q = n x p
- q=Vector3(-n.z*p.y,n.z*p.x,a*k);
- }
+static void plane_space(const Vector3 &n, Vector3 &p, Vector3 &q) {
+
+ if (Math::abs(n.z) > 0.707106781186547524400844362) {
+ // choose p in y-z plane
+ real_t a = n[1] * n[1] + n[2] * n[2];
+ real_t k = 1.0 / Math::sqrt(a);
+ p = Vector3(0, -n[2] * k, n[1] * k);
+ // set q = n x p
+ q = Vector3(a * k, -n[0] * p[2], n[0] * p[1]);
+ } else {
+ // choose p in x-y plane
+ real_t a = n.x * n.x + n.y * n.y;
+ real_t k = 1.0 / Math::sqrt(a);
+ p = Vector3(-n.y * k, n.x * k, 0);
+ // set q = n x p
+ q = Vector3(-n.z * p.y, n.z * p.x, a * k);
+ }
}
-HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Transform& frameA, const Transform& frameB) : JointSW(_arr,2) {
+HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameA, const Transform &frameB)
+ : JointSW(_arr, 2) {
- A=rbA;
- B=rbB;
+ A = rbA;
+ B = rbB;
- m_rbAFrame=frameA;
- m_rbBFrame=frameB;
+ m_rbAFrame = frameA;
+ m_rbBFrame = frameB;
// flip axis
m_rbBFrame.basis[0][2] *= real_t(-1.);
m_rbBFrame.basis[1][2] *= real_t(-1.);
m_rbBFrame.basis[2][2] *= real_t(-1.);
-
//start with free
m_lowerLimit = Math_PI;
m_upperLimit = -Math_PI;
-
m_useLimit = false;
m_biasFactor = 0.3f;
m_relaxationFactor = 1.0f;
m_limitSoftness = 0.9f;
m_solveLimit = false;
- tau=0.3;
-
- m_angularOnly=false;
- m_enableAngularMotor=false;
+ tau = 0.3;
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ m_angularOnly = false;
+ m_enableAngularMotor = false;
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
-HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,const Vector3& pivotInB,
- const Vector3& axisInA,const Vector3& axisInB) : JointSW(_arr,2) {
+HingeJointSW::HingeJointSW(BodySW *rbA, BodySW *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB,
+ const Vector3 &axisInA, const Vector3 &axisInB)
+ : JointSW(_arr, 2) {
- A=rbA;
- B=rbB;
+ A = rbA;
+ B = rbB;
m_rbAFrame.origin = pivotInA;
@@ -112,76 +110,67 @@ HingeJointSW::HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,cons
rbAxisA1 = rbAxisA2.cross(axisInA);
}
- m_rbAFrame.basis=Basis( rbAxisA1.x,rbAxisA2.x,axisInA.x,
- rbAxisA1.y,rbAxisA2.y,axisInA.y,
- rbAxisA1.z,rbAxisA2.z,axisInA.z );
+ m_rbAFrame.basis = Basis(rbAxisA1.x, rbAxisA2.x, axisInA.x,
+ rbAxisA1.y, rbAxisA2.y, axisInA.y,
+ rbAxisA1.z, rbAxisA2.z, axisInA.z);
- Quat rotationArc = Quat(axisInA,axisInB);
- Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1);
- Vector3 rbAxisB2 = axisInB.cross(rbAxisB1);
+ Quat rotationArc = Quat(axisInA, axisInB);
+ Vector3 rbAxisB1 = rotationArc.xform(rbAxisA1);
+ Vector3 rbAxisB2 = axisInB.cross(rbAxisB1);
m_rbBFrame.origin = pivotInB;
- m_rbBFrame.basis=Basis( rbAxisB1.x,rbAxisB2.x,-axisInB.x,
- rbAxisB1.y,rbAxisB2.y,-axisInB.y,
- rbAxisB1.z,rbAxisB2.z,-axisInB.z );
+ m_rbBFrame.basis = Basis(rbAxisB1.x, rbAxisB2.x, -axisInB.x,
+ rbAxisB1.y, rbAxisB2.y, -axisInB.y,
+ rbAxisB1.z, rbAxisB2.z, -axisInB.z);
//start with free
m_lowerLimit = Math_PI;
m_upperLimit = -Math_PI;
-
m_useLimit = false;
m_biasFactor = 0.3f;
m_relaxationFactor = 1.0f;
m_limitSoftness = 0.9f;
m_solveLimit = false;
- tau=0.3;
-
- m_angularOnly=false;
- m_enableAngularMotor=false;
+ tau = 0.3;
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ m_angularOnly = false;
+ m_enableAngularMotor = false;
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
-
-
bool HingeJointSW::setup(real_t p_step) {
m_appliedImpulse = real_t(0.);
- if (!m_angularOnly)
- {
+ if (!m_angularOnly) {
Vector3 pivotAInW = A->get_transform().xform(m_rbAFrame.origin);
Vector3 pivotBInW = B->get_transform().xform(m_rbBFrame.origin);
Vector3 relPos = pivotBInW - pivotAInW;
Vector3 normal[3];
- if (relPos.length_squared() > CMP_EPSILON)
- {
+ if (relPos.length_squared() > CMP_EPSILON) {
normal[0] = relPos.normalized();
- }
- else
- {
- normal[0]=Vector3(real_t(1.0),0,0);
+ } else {
+ normal[0] = Vector3(real_t(1.0), 0, 0);
}
plane_space(normal[0], normal[1], normal[2]);
- for (int i=0;i<3;i++)
- {
+ for (int i = 0; i < 3; i++) {
memnew_placement(&m_jac[i], JacobianEntrySW(
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
- pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
- normal[i],
- A->get_inv_inertia(),
- A->get_inv_mass(),
- B->get_inv_inertia(),
- B->get_inv_mass()) );
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ pivotAInW - A->get_transform().origin - A->get_center_of_mass(),
+ pivotBInW - B->get_transform().origin - B->get_center_of_mass(),
+ normal[i],
+ A->get_inv_inertia(),
+ A->get_inv_mass(),
+ B->get_inv_inertia(),
+ B->get_inv_mass()));
}
}
@@ -192,31 +181,30 @@ bool HingeJointSW::setup(real_t p_step) {
Vector3 jointAxis0local;
Vector3 jointAxis1local;
- plane_space(m_rbAFrame.basis.get_axis(2),jointAxis0local,jointAxis1local);
-
- A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) );
- Vector3 jointAxis0 = A->get_transform().basis.xform( jointAxis0local );
- Vector3 jointAxis1 = A->get_transform().basis.xform( jointAxis1local );
- Vector3 hingeAxisWorld = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) );
+ plane_space(m_rbAFrame.basis.get_axis(2), jointAxis0local, jointAxis1local);
- memnew_placement(&m_jacAng[0], JacobianEntrySW(jointAxis0,
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_inv_inertia(),
- B->get_inv_inertia()));
+ A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
+ Vector3 jointAxis0 = A->get_transform().basis.xform(jointAxis0local);
+ Vector3 jointAxis1 = A->get_transform().basis.xform(jointAxis1local);
+ Vector3 hingeAxisWorld = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
- memnew_placement(&m_jacAng[1], JacobianEntrySW(jointAxis1,
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_inv_inertia(),
- B->get_inv_inertia()));
+ memnew_placement(&m_jacAng[0], JacobianEntrySW(jointAxis0,
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_inv_inertia(),
+ B->get_inv_inertia()));
- memnew_placement(&m_jacAng[2], JacobianEntrySW(hingeAxisWorld,
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_inv_inertia(),
- B->get_inv_inertia()));
+ memnew_placement(&m_jacAng[1], JacobianEntrySW(jointAxis1,
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_inv_inertia(),
+ B->get_inv_inertia()));
+ memnew_placement(&m_jacAng[2], JacobianEntrySW(hingeAxisWorld,
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_inv_inertia(),
+ B->get_inv_inertia()));
// Compute limit information
real_t hingeAngle = get_hinge_angle();
@@ -228,26 +216,21 @@ bool HingeJointSW::setup(real_t p_step) {
m_solveLimit = false;
m_accLimitImpulse = real_t(0.);
-
-
/*if (m_useLimit) {
print_line("low: "+rtos(m_lowerLimit));
print_line("hi: "+rtos(m_upperLimit));
}*/
//if (m_lowerLimit < m_upperLimit)
- if (m_useLimit && m_lowerLimit <= m_upperLimit)
- {
+ if (m_useLimit && m_lowerLimit <= m_upperLimit) {
//if (hingeAngle <= m_lowerLimit*m_limitSoftness)
- if (hingeAngle <= m_lowerLimit)
- {
+ if (hingeAngle <= m_lowerLimit) {
m_correction = (m_lowerLimit - hingeAngle);
m_limitSign = 1.0f;
m_solveLimit = true;
}
//else if (hingeAngle >= m_upperLimit*m_limitSoftness)
- else if (hingeAngle >= m_upperLimit)
- {
+ else if (hingeAngle >= m_upperLimit) {
m_correction = m_upperLimit - hingeAngle;
m_limitSign = -1.0f;
m_solveLimit = true;
@@ -255,9 +238,9 @@ bool HingeJointSW::setup(real_t p_step) {
}
//Compute K = J*W*J' for hinge axis
- Vector3 axisA = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) );
- m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) +
- B->compute_angular_impulse_denominator(axisA));
+ Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
+ m_kHinge = 1.0f / (A->compute_angular_impulse_denominator(axisA) +
+ B->compute_angular_impulse_denominator(axisA));
return true;
}
@@ -270,8 +253,7 @@ void HingeJointSW::solve(real_t p_step) {
//real_t tau = real_t(0.3);
//linear part
- if (!m_angularOnly)
- {
+ if (!m_angularOnly) {
Vector3 rel_pos1 = pivotAInW - A->get_transform().origin;
Vector3 rel_pos2 = pivotBInW - B->get_transform().origin;
@@ -279,80 +261,74 @@ void HingeJointSW::solve(real_t p_step) {
Vector3 vel2 = B->get_velocity_in_local_point(rel_pos2);
Vector3 vel = vel1 - vel2;
- for (int i=0;i<3;i++)
- {
- const Vector3& normal = m_jac[i].m_linearJointAxis;
+ for (int i = 0; i < 3; i++) {
+ const Vector3 &normal = m_jac[i].m_linearJointAxis;
real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal();
real_t rel_vel;
rel_vel = normal.dot(vel);
//positional error (zeroth order error)
real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
- real_t impulse = depth*tau/p_step * jacDiagABInv - rel_vel * jacDiagABInv;
+ real_t impulse = depth * tau / p_step * jacDiagABInv - rel_vel * jacDiagABInv;
m_appliedImpulse += impulse;
Vector3 impulse_vector = normal * impulse;
- A->apply_impulse(pivotAInW - A->get_transform().origin,impulse_vector);
- B->apply_impulse(pivotBInW - B->get_transform().origin,-impulse_vector);
+ A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector);
+ B->apply_impulse(pivotBInW - B->get_transform().origin, -impulse_vector);
}
}
-
{
///solve angular part
// get axes in world space
- Vector3 axisA = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(2) );
- Vector3 axisB = B->get_transform().basis.xform( m_rbBFrame.basis.get_axis(2) );
+ Vector3 axisA = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(2));
+ Vector3 axisB = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(2));
- const Vector3& angVelA = A->get_angular_velocity();
- const Vector3& angVelB = B->get_angular_velocity();
+ const Vector3 &angVelA = A->get_angular_velocity();
+ const Vector3 &angVelB = B->get_angular_velocity();
Vector3 angVelAroundHingeAxisA = axisA * axisA.dot(angVelA);
Vector3 angVelAroundHingeAxisB = axisB * axisB.dot(angVelB);
Vector3 angAorthog = angVelA - angVelAroundHingeAxisA;
Vector3 angBorthog = angVelB - angVelAroundHingeAxisB;
- Vector3 velrelOrthog = angAorthog-angBorthog;
+ Vector3 velrelOrthog = angAorthog - angBorthog;
{
//solve orthogonal angular velocity correction
real_t relaxation = real_t(1.);
real_t len = velrelOrthog.length();
- if (len > real_t(0.00001))
- {
+ if (len > real_t(0.00001)) {
Vector3 normal = velrelOrthog.normalized();
real_t denom = A->compute_angular_impulse_denominator(normal) +
- B->compute_angular_impulse_denominator(normal);
+ B->compute_angular_impulse_denominator(normal);
// scale for mass and relaxation
- velrelOrthog *= (real_t(1.)/denom) * m_relaxationFactor;
+ velrelOrthog *= (real_t(1.) / denom) * m_relaxationFactor;
}
//solve angular positional correction
- Vector3 angularError = -axisA.cross(axisB) *(real_t(1.)/p_step);
+ Vector3 angularError = -axisA.cross(axisB) * (real_t(1.) / p_step);
real_t len2 = angularError.length();
- if (len2>real_t(0.00001))
- {
+ if (len2 > real_t(0.00001)) {
Vector3 normal2 = angularError.normalized();
real_t denom2 = A->compute_angular_impulse_denominator(normal2) +
- B->compute_angular_impulse_denominator(normal2);
- angularError *= (real_t(1.)/denom2) * relaxation;
+ B->compute_angular_impulse_denominator(normal2);
+ angularError *= (real_t(1.) / denom2) * relaxation;
}
- A->apply_torque_impulse(-velrelOrthog+angularError);
- B->apply_torque_impulse(velrelOrthog-angularError);
+ A->apply_torque_impulse(-velrelOrthog + angularError);
+ B->apply_torque_impulse(velrelOrthog - angularError);
// solve limit
- if (m_solveLimit)
- {
- real_t amplitude = ( (angVelB - angVelA).dot( axisA )*m_relaxationFactor + m_correction* (real_t(1.)/p_step)*m_biasFactor ) * m_limitSign;
+ if (m_solveLimit) {
+ real_t amplitude = ((angVelB - angVelA).dot(axisA) * m_relaxationFactor + m_correction * (real_t(1.) / p_step) * m_biasFactor) * m_limitSign;
real_t impulseMag = amplitude * m_kHinge;
// Clamp the accumulated impulse
real_t temp = m_accLimitImpulse;
- m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0) );
+ m_accLimitImpulse = MAX(m_accLimitImpulse + impulseMag, real_t(0));
impulseMag = m_accLimitImpulse - temp;
-
Vector3 impulse = axisA * impulseMag * m_limitSign;
A->apply_torque_impulse(impulse);
B->apply_torque_impulse(-impulse);
@@ -360,10 +336,9 @@ void HingeJointSW::solve(real_t p_step) {
}
//apply motor
- if (m_enableAngularMotor)
- {
+ if (m_enableAngularMotor) {
//todo: add limits too
- Vector3 angularLimit(0,0,0);
+ Vector3 angularLimit(0, 0, 0);
Vector3 velrel = angVelAroundHingeAxisA - angVelAroundHingeAxisB;
real_t projRelVel = velrel.dot(axisA);
@@ -377,12 +352,10 @@ void HingeJointSW::solve(real_t p_step) {
clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse;
Vector3 motorImp = clippedMotorImpulse * axisA;
- A->apply_torque_impulse(motorImp+angularLimit);
- B->apply_torque_impulse(-motorImp-angularLimit);
-
+ A->apply_torque_impulse(motorImp + angularLimit);
+ B->apply_torque_impulse(-motorImp - angularLimit);
}
}
-
}
/*
void HingeJointSW::updateRHS(real_t timeStep)
@@ -392,8 +365,7 @@ void HingeJointSW::updateRHS(real_t timeStep)
}
*/
-static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
-{
+static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) {
real_t coeff_1 = Math_PI / 4.0f;
real_t coeff_2 = 3.0f * coeff_1;
real_t abs_y = Math::abs(y);
@@ -408,33 +380,30 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
return (y < 0.0f) ? -angle : angle;
}
-
real_t HingeJointSW::get_hinge_angle() {
- const Vector3 refAxis0 = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(0) );
- const Vector3 refAxis1 = A->get_transform().basis.xform( m_rbAFrame.basis.get_axis(1) );
- const Vector3 swingAxis = B->get_transform().basis.xform( m_rbBFrame.basis.get_axis(1) );
+ const Vector3 refAxis0 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(0));
+ const Vector3 refAxis1 = A->get_transform().basis.xform(m_rbAFrame.basis.get_axis(1));
+ const Vector3 swingAxis = B->get_transform().basis.xform(m_rbBFrame.basis.get_axis(1));
- return atan2fast( swingAxis.dot(refAxis0), swingAxis.dot(refAxis1) );
+ return atan2fast(swingAxis.dot(refAxis0), swingAxis.dot(refAxis1));
}
-
void HingeJointSW::set_param(PhysicsServer::HingeJointParam p_param, real_t p_value) {
switch (p_param) {
- case PhysicsServer::HINGE_JOINT_BIAS: tau=p_value; break;
- case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: m_upperLimit=p_value; break;
- case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: m_lowerLimit=p_value; break;
- case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: m_biasFactor=p_value; break;
- case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: m_limitSoftness=p_value; break;
- case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: m_relaxationFactor=p_value; break;
- case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: m_motorTargetVelocity=p_value; break;
- case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: m_maxMotorImpulse=p_value; break;
-
+ case PhysicsServer::HINGE_JOINT_BIAS: tau = p_value; break;
+ case PhysicsServer::HINGE_JOINT_LIMIT_UPPER: m_upperLimit = p_value; break;
+ case PhysicsServer::HINGE_JOINT_LIMIT_LOWER: m_lowerLimit = p_value; break;
+ case PhysicsServer::HINGE_JOINT_LIMIT_BIAS: m_biasFactor = p_value; break;
+ case PhysicsServer::HINGE_JOINT_LIMIT_SOFTNESS: m_limitSoftness = p_value; break;
+ case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: m_relaxationFactor = p_value; break;
+ case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: m_motorTargetVelocity = p_value; break;
+ case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: m_maxMotorImpulse = p_value; break;
}
}
-real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const{
+real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const {
switch (p_param) {
@@ -446,25 +415,23 @@ real_t HingeJointSW::get_param(PhysicsServer::HingeJointParam p_param) const{
case PhysicsServer::HINGE_JOINT_LIMIT_RELAXATION: return m_relaxationFactor;
case PhysicsServer::HINGE_JOINT_MOTOR_TARGET_VELOCITY: return m_motorTargetVelocity;
case PhysicsServer::HINGE_JOINT_MOTOR_MAX_IMPULSE: return m_maxMotorImpulse;
-
}
return 0;
}
-void HingeJointSW::set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value){
+void HingeJointSW::set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value) {
switch (p_flag) {
- case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: m_useLimit=p_value; break;
- case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: m_enableAngularMotor=p_value; break;
+ case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: m_useLimit = p_value; break;
+ case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: m_enableAngularMotor = p_value; break;
}
-
}
-bool HingeJointSW::get_flag(PhysicsServer::HingeJointFlag p_flag) const{
+bool HingeJointSW::get_flag(PhysicsServer::HingeJointFlag p_flag) const {
switch (p_flag) {
case PhysicsServer::HINGE_JOINT_FLAG_USE_LIMIT: return m_useLimit;
- case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR:return m_enableAngularMotor;
+ case PhysicsServer::HINGE_JOINT_FLAG_ENABLE_MOTOR: return m_enableAngularMotor;
}
return false;
diff --git a/servers/physics/joints/hinge_joint_sw.h b/servers/physics/joints/hinge_joint_sw.h
index 8469fd1ca0..013d9afdbf 100644
--- a/servers/physics/joints/hinge_joint_sw.h
+++ b/servers/physics/joints/hinge_joint_sw.h
@@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library.
#ifndef HINGE_JOINT_SW_H
#define HINGE_JOINT_SW_H
-#include "servers/physics/joints_sw.h"
#include "servers/physics/joints/jacobian_entry_sw.h"
-
+#include "servers/physics/joints_sw.h"
/*
Bullet Continuous Collision Detection and Physics Library
@@ -53,8 +52,6 @@ subject to the following restrictions:
3. This notice may not be removed or altered from any source distribution.
*/
-
-
class HingeJointSW : public JointSW {
union {
@@ -66,41 +63,39 @@ class HingeJointSW : public JointSW {
BodySW *_arr[2];
};
- JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
- JacobianEntrySW m_jacAng[3]; //2 orthogonal angular constraints+ 1 for limit/motor
+ JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
+ JacobianEntrySW m_jacAng[3]; //2 orthogonal angular constraints+ 1 for limit/motor
Transform m_rbAFrame; // constraint axii. Assumes z is hinge axis.
Transform m_rbBFrame;
- real_t m_motorTargetVelocity;
- real_t m_maxMotorImpulse;
+ real_t m_motorTargetVelocity;
+ real_t m_maxMotorImpulse;
- real_t m_limitSoftness;
- real_t m_biasFactor;
- real_t m_relaxationFactor;
+ real_t m_limitSoftness;
+ real_t m_biasFactor;
+ real_t m_relaxationFactor;
- real_t m_lowerLimit;
- real_t m_upperLimit;
+ real_t m_lowerLimit;
+ real_t m_upperLimit;
- real_t m_kHinge;
+ real_t m_kHinge;
- real_t m_limitSign;
- real_t m_correction;
+ real_t m_limitSign;
+ real_t m_correction;
- real_t m_accLimitImpulse;
+ real_t m_accLimitImpulse;
real_t tau;
- bool m_useLimit;
- bool m_angularOnly;
- bool m_enableAngularMotor;
- bool m_solveLimit;
+ bool m_useLimit;
+ bool m_angularOnly;
+ bool m_enableAngularMotor;
+ bool m_solveLimit;
real_t m_appliedImpulse;
-
public:
-
virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_HINGE; }
virtual bool setup(real_t p_step);
@@ -114,9 +109,8 @@ public:
void set_flag(PhysicsServer::HingeJointFlag p_flag, bool p_value);
bool get_flag(PhysicsServer::HingeJointFlag p_flag) const;
- HingeJointSW(BodySW* rbA,BodySW* rbB, const Transform& frameA, const Transform& frameB);
- HingeJointSW(BodySW* rbA,BodySW* rbB, const Vector3& pivotInA,const Vector3& pivotInB, const Vector3& axisInA,const Vector3& axisInB);
-
+ HingeJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameA, const Transform &frameB);
+ HingeJointSW(BodySW *rbA, BodySW *rbB, const Vector3 &pivotInA, const Vector3 &pivotInB, const Vector3 &axisInA, const Vector3 &axisInB);
};
#endif // HINGE_JOINT_SW_H
diff --git a/servers/physics/joints/jacobian_entry_sw.h b/servers/physics/joints/jacobian_entry_sw.h
index cd85162ba5..b0b31ed797 100644
--- a/servers/physics/joints/jacobian_entry_sw.h
+++ b/servers/physics/joints/jacobian_entry_sw.h
@@ -53,22 +53,21 @@ subject to the following restrictions:
class JacobianEntrySW {
public:
- JacobianEntrySW() {};
+ JacobianEntrySW(){};
//constraint between two different rigidbodies
JacobianEntrySW(
- const Basis& world2A,
- const Basis& world2B,
- const Vector3& rel_pos1,const Vector3& rel_pos2,
- const Vector3& jointAxis,
- const Vector3& inertiaInvA,
- const real_t massInvA,
- const Vector3& inertiaInvB,
- const real_t massInvB)
- :m_linearJointAxis(jointAxis)
- {
+ const Basis &world2A,
+ const Basis &world2B,
+ const Vector3 &rel_pos1, const Vector3 &rel_pos2,
+ const Vector3 &jointAxis,
+ const Vector3 &inertiaInvA,
+ const real_t massInvA,
+ const Vector3 &inertiaInvB,
+ const real_t massInvB)
+ : m_linearJointAxis(jointAxis) {
m_aJ = world2A.xform(rel_pos1.cross(m_linearJointAxis));
m_bJ = world2B.xform(rel_pos2.cross(-m_linearJointAxis));
- m_0MinvJt = inertiaInvA * m_aJ;
+ m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
m_Adiag = massInvA + m_0MinvJt.dot(m_aJ) + massInvB + m_1MinvJt.dot(m_bJ);
@@ -76,104 +75,92 @@ public:
}
//angular constraint between two different rigidbodies
- JacobianEntrySW(const Vector3& jointAxis,
- const Basis& world2A,
- const Basis& world2B,
- const Vector3& inertiaInvA,
- const Vector3& inertiaInvB)
- :m_linearJointAxis(Vector3(real_t(0.),real_t(0.),real_t(0.)))
- {
- m_aJ= world2A.xform(jointAxis);
+ JacobianEntrySW(const Vector3 &jointAxis,
+ const Basis &world2A,
+ const Basis &world2B,
+ const Vector3 &inertiaInvA,
+ const Vector3 &inertiaInvB)
+ : m_linearJointAxis(Vector3(real_t(0.), real_t(0.), real_t(0.))) {
+ m_aJ = world2A.xform(jointAxis);
m_bJ = world2B.xform(-jointAxis);
- m_0MinvJt = inertiaInvA * m_aJ;
+ m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
- m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
+ m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
ERR_FAIL_COND(m_Adiag <= real_t(0.0));
}
//angular constraint between two different rigidbodies
- JacobianEntrySW(const Vector3& axisInA,
- const Vector3& axisInB,
- const Vector3& inertiaInvA,
- const Vector3& inertiaInvB)
- : m_linearJointAxis(Vector3(real_t(0.),real_t(0.),real_t(0.)))
- , m_aJ(axisInA)
- , m_bJ(-axisInB)
- {
- m_0MinvJt = inertiaInvA * m_aJ;
+ JacobianEntrySW(const Vector3 &axisInA,
+ const Vector3 &axisInB,
+ const Vector3 &inertiaInvA,
+ const Vector3 &inertiaInvB)
+ : m_linearJointAxis(Vector3(real_t(0.), real_t(0.), real_t(0.))), m_aJ(axisInA), m_bJ(-axisInB) {
+ m_0MinvJt = inertiaInvA * m_aJ;
m_1MinvJt = inertiaInvB * m_bJ;
- m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
+ m_Adiag = m_0MinvJt.dot(m_aJ) + m_1MinvJt.dot(m_bJ);
ERR_FAIL_COND(m_Adiag <= real_t(0.0));
}
//constraint on one rigidbody
JacobianEntrySW(
- const Basis& world2A,
- const Vector3& rel_pos1,const Vector3& rel_pos2,
- const Vector3& jointAxis,
- const Vector3& inertiaInvA,
- const real_t massInvA)
- :m_linearJointAxis(jointAxis)
- {
- m_aJ= world2A.xform(rel_pos1.cross(jointAxis));
+ const Basis &world2A,
+ const Vector3 &rel_pos1, const Vector3 &rel_pos2,
+ const Vector3 &jointAxis,
+ const Vector3 &inertiaInvA,
+ const real_t massInvA)
+ : m_linearJointAxis(jointAxis) {
+ m_aJ = world2A.xform(rel_pos1.cross(jointAxis));
m_bJ = world2A.xform(rel_pos2.cross(-jointAxis));
- m_0MinvJt = inertiaInvA * m_aJ;
- m_1MinvJt = Vector3(real_t(0.),real_t(0.),real_t(0.));
+ m_0MinvJt = inertiaInvA * m_aJ;
+ m_1MinvJt = Vector3(real_t(0.), real_t(0.), real_t(0.));
m_Adiag = massInvA + m_0MinvJt.dot(m_aJ);
ERR_FAIL_COND(m_Adiag <= real_t(0.0));
}
- real_t getDiagonal() const { return m_Adiag; }
+ real_t getDiagonal() const { return m_Adiag; }
// for two constraints on the same rigidbody (for example vehicle friction)
- real_t getNonDiagonal(const JacobianEntrySW& jacB, const real_t massInvA) const
- {
- const JacobianEntrySW& jacA = *this;
+ real_t getNonDiagonal(const JacobianEntrySW &jacB, const real_t massInvA) const {
+ const JacobianEntrySW &jacA = *this;
real_t lin = massInvA * jacA.m_linearJointAxis.dot(jacB.m_linearJointAxis);
real_t ang = jacA.m_0MinvJt.dot(jacB.m_aJ);
return lin + ang;
}
-
-
// for two constraints on sharing two same rigidbodies (for example two contact points between two rigidbodies)
- real_t getNonDiagonal(const JacobianEntrySW& jacB,const real_t massInvA,const real_t massInvB) const
- {
- const JacobianEntrySW& jacA = *this;
+ real_t getNonDiagonal(const JacobianEntrySW &jacB, const real_t massInvA, const real_t massInvB) const {
+ const JacobianEntrySW &jacA = *this;
Vector3 lin = jacA.m_linearJointAxis * jacB.m_linearJointAxis;
Vector3 ang0 = jacA.m_0MinvJt * jacB.m_aJ;
Vector3 ang1 = jacA.m_1MinvJt * jacB.m_bJ;
- Vector3 lin0 = massInvA * lin ;
+ Vector3 lin0 = massInvA * lin;
Vector3 lin1 = massInvB * lin;
- Vector3 sum = ang0+ang1+lin0+lin1;
- return sum[0]+sum[1]+sum[2];
+ Vector3 sum = ang0 + ang1 + lin0 + lin1;
+ return sum[0] + sum[1] + sum[2];
}
- real_t getRelativeVelocity(const Vector3& linvelA,const Vector3& angvelA,const Vector3& linvelB,const Vector3& angvelB)
- {
+ real_t getRelativeVelocity(const Vector3 &linvelA, const Vector3 &angvelA, const Vector3 &linvelB, const Vector3 &angvelB) {
Vector3 linrel = linvelA - linvelB;
- Vector3 angvela = angvelA * m_aJ;
- Vector3 angvelb = angvelB * m_bJ;
+ Vector3 angvela = angvelA * m_aJ;
+ Vector3 angvelb = angvelB * m_bJ;
linrel *= m_linearJointAxis;
angvela += angvelb;
angvela += linrel;
- real_t rel_vel2 = angvela[0]+angvela[1]+angvela[2];
+ real_t rel_vel2 = angvela[0] + angvela[1] + angvela[2];
return rel_vel2 + CMP_EPSILON;
}
-//private:
+ //private:
- Vector3 m_linearJointAxis;
- Vector3 m_aJ;
- Vector3 m_bJ;
- Vector3 m_0MinvJt;
- Vector3 m_1MinvJt;
+ Vector3 m_linearJointAxis;
+ Vector3 m_aJ;
+ Vector3 m_bJ;
+ Vector3 m_0MinvJt;
+ Vector3 m_1MinvJt;
//Optimization: can be stored in the w/last component of one of the vectors
- real_t m_Adiag;
-
+ real_t m_Adiag;
};
-
#endif // JACOBIAN_ENTRY_SW_H
diff --git a/servers/physics/joints/pin_joint_sw.cpp b/servers/physics/joints/pin_joint_sw.cpp
index b545ae630b..e01514f4b6 100644
--- a/servers/physics/joints/pin_joint_sw.cpp
+++ b/servers/physics/joints/pin_joint_sw.cpp
@@ -38,41 +38,37 @@ bool PinJointSW::setup(real_t p_step) {
m_appliedImpulse = real_t(0.);
- Vector3 normal(0,0,0);
+ Vector3 normal(0, 0, 0);
- for (int i=0;i<3;i++)
- {
+ for (int i = 0; i < 3; i++) {
normal[i] = 1;
- memnew_placement(&m_jac[i],JacobianEntrySW(
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_transform().xform(m_pivotInA) - A->get_transform().origin - A->get_center_of_mass(),
- B->get_transform().xform(m_pivotInB) - B->get_transform().origin - B->get_center_of_mass(),
- normal,
- A->get_inv_inertia(),
- A->get_inv_mass(),
- B->get_inv_inertia(),
- B->get_inv_mass()));
+ memnew_placement(&m_jac[i], JacobianEntrySW(
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_transform().xform(m_pivotInA) - A->get_transform().origin - A->get_center_of_mass(),
+ B->get_transform().xform(m_pivotInB) - B->get_transform().origin - B->get_center_of_mass(),
+ normal,
+ A->get_inv_inertia(),
+ A->get_inv_mass(),
+ B->get_inv_inertia(),
+ B->get_inv_mass()));
normal[i] = 0;
}
return true;
}
-void PinJointSW::solve(real_t p_step){
+void PinJointSW::solve(real_t p_step) {
Vector3 pivotAInW = A->get_transform().xform(m_pivotInA);
Vector3 pivotBInW = B->get_transform().xform(m_pivotInB);
-
- Vector3 normal(0,0,0);
-
+ Vector3 normal(0, 0, 0);
//Vector3 angvelA = A->get_transform().origin.getBasis().transpose() * A->getAngularVelocity();
//Vector3 angvelB = B->get_transform().origin.getBasis().transpose() * B->getAngularVelocity();
- for (int i=0;i<3;i++)
- {
+ for (int i = 0; i < 3; i++) {
normal[i] = 1;
real_t jacDiagABInv = real_t(1.) / m_jac[i].getDiagonal();
@@ -87,7 +83,7 @@ void PinJointSW::solve(real_t p_step){
real_t rel_vel;
rel_vel = normal.dot(vel);
- /*
+ /*
//velocity error (first order error)
real_t rel_vel = m_jac[i].getRelativeVelocity(A->getLinearVelocity(),angvelA,
B->getLinearVelocity(),angvelB);
@@ -96,38 +92,37 @@ void PinJointSW::solve(real_t p_step){
//positional error (zeroth order error)
real_t depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal
- real_t impulse = depth*m_tau/p_step * jacDiagABInv - m_damping * rel_vel * jacDiagABInv;
+ real_t impulse = depth * m_tau / p_step * jacDiagABInv - m_damping * rel_vel * jacDiagABInv;
real_t impulseClamp = m_impulseClamp;
- if (impulseClamp > 0)
- {
+ if (impulseClamp > 0) {
if (impulse < -impulseClamp)
impulse = -impulseClamp;
if (impulse > impulseClamp)
impulse = impulseClamp;
}
- m_appliedImpulse+=impulse;
+ m_appliedImpulse += impulse;
Vector3 impulse_vector = normal * impulse;
- A->apply_impulse(pivotAInW - A->get_transform().origin,impulse_vector);
- B->apply_impulse(pivotBInW - B->get_transform().origin,-impulse_vector);
+ A->apply_impulse(pivotAInW - A->get_transform().origin, impulse_vector);
+ B->apply_impulse(pivotBInW - B->get_transform().origin, -impulse_vector);
normal[i] = 0;
}
}
-void PinJointSW::set_param(PhysicsServer::PinJointParam p_param,real_t p_value) {
+void PinJointSW::set_param(PhysicsServer::PinJointParam p_param, real_t p_value) {
- switch(p_param) {
- case PhysicsServer::PIN_JOINT_BIAS: m_tau=p_value; break;
- case PhysicsServer::PIN_JOINT_DAMPING: m_damping=p_value; break;
- case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: m_impulseClamp=p_value; break;
+ switch (p_param) {
+ case PhysicsServer::PIN_JOINT_BIAS: m_tau = p_value; break;
+ case PhysicsServer::PIN_JOINT_DAMPING: m_damping = p_value; break;
+ case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: m_impulseClamp = p_value; break;
}
}
-real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const{
+real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::PIN_JOINT_BIAS: return m_tau;
case PhysicsServer::PIN_JOINT_DAMPING: return m_damping;
case PhysicsServer::PIN_JOINT_IMPULSE_CLAMP: return m_impulseClamp;
@@ -136,26 +131,22 @@ real_t PinJointSW::get_param(PhysicsServer::PinJointParam p_param) const{
return 0;
}
-PinJointSW::PinJointSW(BodySW* p_body_a,const Vector3& p_pos_a,BodySW* p_body_b,const Vector3& p_pos_b) : JointSW(_arr,2) {
-
- A=p_body_a;
- B=p_body_b;
- m_pivotInA=p_pos_a;
- m_pivotInB=p_pos_b;
-
- m_tau=0.3;
- m_damping=1;
- m_impulseClamp=0;
- m_appliedImpulse=0;
+PinJointSW::PinJointSW(BodySW *p_body_a, const Vector3 &p_pos_a, BodySW *p_body_b, const Vector3 &p_pos_b)
+ : JointSW(_arr, 2) {
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ A = p_body_a;
+ B = p_body_b;
+ m_pivotInA = p_pos_a;
+ m_pivotInB = p_pos_b;
+ m_tau = 0.3;
+ m_damping = 1;
+ m_impulseClamp = 0;
+ m_appliedImpulse = 0;
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
PinJointSW::~PinJointSW() {
-
-
-
}
diff --git a/servers/physics/joints/pin_joint_sw.h b/servers/physics/joints/pin_joint_sw.h
index b72b21219d..9500d4b46d 100644
--- a/servers/physics/joints/pin_joint_sw.h
+++ b/servers/physics/joints/pin_joint_sw.h
@@ -34,8 +34,8 @@ Adapted to Godot from the Bullet library.
#ifndef PIN_JOINT_SW_H
#define PIN_JOINT_SW_H
-#include "servers/physics/joints_sw.h"
#include "servers/physics/joints/jacobian_entry_sw.h"
+#include "servers/physics/joints_sw.h"
/*
Bullet Continuous Collision Detection and Physics Library
@@ -52,7 +52,6 @@ subject to the following restrictions:
3. This notice may not be removed or altered from any source distribution.
*/
-
class PinJointSW : public JointSW {
union {
@@ -64,37 +63,33 @@ class PinJointSW : public JointSW {
BodySW *_arr[2];
};
+ real_t m_tau; //bias
+ real_t m_damping;
+ real_t m_impulseClamp;
+ real_t m_appliedImpulse;
- real_t m_tau; //bias
- real_t m_damping;
- real_t m_impulseClamp;
- real_t m_appliedImpulse;
-
- JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
+ JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints
- Vector3 m_pivotInA;
- Vector3 m_pivotInB;
+ Vector3 m_pivotInA;
+ Vector3 m_pivotInB;
public:
-
virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_PIN; }
virtual bool setup(real_t p_step);
virtual void solve(real_t p_step);
- void set_param(PhysicsServer::PinJointParam p_param,real_t p_value);
+ void set_param(PhysicsServer::PinJointParam p_param, real_t p_value);
real_t get_param(PhysicsServer::PinJointParam p_param) const;
- void set_pos_A(const Vector3& p_pos) { m_pivotInA=p_pos; }
- void set_pos_B(const Vector3& p_pos) { m_pivotInB=p_pos; }
+ void set_pos_A(const Vector3 &p_pos) { m_pivotInA = p_pos; }
+ void set_pos_B(const Vector3 &p_pos) { m_pivotInB = p_pos; }
Vector3 get_pos_A() { return m_pivotInB; }
Vector3 get_pos_B() { return m_pivotInA; }
- PinJointSW(BodySW* p_body_a,const Vector3& p_pos_a,BodySW* p_body_b,const Vector3& p_pos_b);
+ PinJointSW(BodySW *p_body_a, const Vector3 &p_pos_a, BodySW *p_body_b, const Vector3 &p_pos_b);
~PinJointSW();
};
-
-
#endif // PIN_JOINT_SW_H
diff --git a/servers/physics/joints/slider_joint_sw.cpp b/servers/physics/joints/slider_joint_sw.cpp
index fc728ed0ba..b8a6c1ecaf 100644
--- a/servers/physics/joints/slider_joint_sw.cpp
+++ b/servers/physics/joints/slider_joint_sw.cpp
@@ -36,8 +36,7 @@ See corresponding header file for licensing info.
//-----------------------------------------------------------------------------
-static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
-{
+static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x) {
real_t coeff_1 = Math_PI / 4.0f;
real_t coeff_2 = 3.0f * coeff_1;
real_t abs_y = Math::abs(y);
@@ -52,13 +51,11 @@ static _FORCE_INLINE_ real_t atan2fast(real_t y, real_t x)
return (y < 0.0f) ? -angle : angle;
}
-
-void SliderJointSW::initParams()
-{
- m_lowerLinLimit = real_t(1.0);
- m_upperLinLimit = real_t(-1.0);
- m_lowerAngLimit = real_t(0.);
- m_upperAngLimit = real_t(0.);
+void SliderJointSW::initParams() {
+ m_lowerLinLimit = real_t(1.0);
+ m_upperLinLimit = real_t(-1.0);
+ m_lowerAngLimit = real_t(0.);
+ m_upperAngLimit = real_t(0.);
m_softnessDirLin = SLIDER_CONSTRAINT_DEF_SOFTNESS;
m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION;
m_dampingDirLin = real_t(0.);
@@ -84,40 +81,35 @@ void SliderJointSW::initParams()
m_accumulatedLinMotorImpulse = real_t(0.0);
m_poweredAngMotor = false;
- m_targetAngMotorVelocity = real_t(0.);
- m_maxAngMotorForce = real_t(0.);
+ m_targetAngMotorVelocity = real_t(0.);
+ m_maxAngMotorForce = real_t(0.);
m_accumulatedAngMotorImpulse = real_t(0.0);
} // SliderJointSW::initParams()
//-----------------------------------------------------------------------------
-
//-----------------------------------------------------------------------------
-SliderJointSW::SliderJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB)
- : JointSW(_arr,2)
- , m_frameInA(frameInA)
- , m_frameInB(frameInB)
-{
+SliderJointSW::SliderJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB)
+ : JointSW(_arr, 2), m_frameInA(frameInA), m_frameInB(frameInB) {
- A=rbA;
- B=rbB;
+ A = rbA;
+ B = rbB;
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
initParams();
} // SliderJointSW::SliderJointSW()
//-----------------------------------------------------------------------------
-bool SliderJointSW::setup(real_t p_step)
-{
+bool SliderJointSW::setup(real_t p_step) {
//calculate transforms
- m_calculatedTransformA = A->get_transform() * m_frameInA;
- m_calculatedTransformB = B->get_transform() * m_frameInB;
+ m_calculatedTransformA = A->get_transform() * m_frameInA;
+ m_calculatedTransformB = B->get_transform() * m_frameInB;
m_realPivotAInW = m_calculatedTransformA.origin;
m_realPivotBInW = m_calculatedTransformB.origin;
m_sliderAxis = m_calculatedTransformA.basis.get_axis(0); // along X
@@ -125,42 +117,38 @@ bool SliderJointSW::setup(real_t p_step)
m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
m_relPosA = m_projPivotInW - A->get_transform().origin;
m_relPosB = m_realPivotBInW - B->get_transform().origin;
- Vector3 normalWorld;
- int i;
- //linear part
- for(i = 0; i < 3; i++)
- {
+ Vector3 normalWorld;
+ int i;
+ //linear part
+ for (i = 0; i < 3; i++) {
normalWorld = m_calculatedTransformA.basis.get_axis(i);
memnew_placement(&m_jacLin[i], JacobianEntrySW(
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- m_relPosA - A->get_center_of_mass(),
- m_relPosB - B->get_center_of_mass(),
- normalWorld,
- A->get_inv_inertia(),
- A->get_inv_mass(),
- B->get_inv_inertia(),
- B->get_inv_mass()
- ));
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ m_relPosA - A->get_center_of_mass(),
+ m_relPosB - B->get_center_of_mass(),
+ normalWorld,
+ A->get_inv_inertia(),
+ A->get_inv_mass(),
+ B->get_inv_inertia(),
+ B->get_inv_mass()));
m_jacLinDiagABInv[i] = real_t(1.) / m_jacLin[i].getDiagonal();
m_depth[i] = m_delta.dot(normalWorld);
- }
+ }
testLinLimits();
- // angular part
- for(i = 0; i < 3; i++)
- {
+ // angular part
+ for (i = 0; i < 3; i++) {
normalWorld = m_calculatedTransformA.basis.get_axis(i);
- memnew_placement(&m_jacAng[i], JacobianEntrySW(
- normalWorld,
- A->get_principal_inertia_axes().transposed(),
- B->get_principal_inertia_axes().transposed(),
- A->get_inv_inertia(),
- B->get_inv_inertia()
- ));
+ memnew_placement(&m_jacAng[i], JacobianEntrySW(
+ normalWorld,
+ A->get_principal_inertia_axes().transposed(),
+ B->get_principal_inertia_axes().transposed(),
+ A->get_inv_inertia(),
+ B->get_inv_inertia()));
}
testAngLimits();
Vector3 axisA = m_calculatedTransformA.basis.get_axis(0);
- m_kAngle = real_t(1.0 )/ (A->compute_angular_impulse_denominator(axisA) + B->compute_angular_impulse_denominator(axisA));
+ m_kAngle = real_t(1.0) / (A->compute_angular_impulse_denominator(axisA) + B->compute_angular_impulse_denominator(axisA));
// clear accumulator for motors
m_accumulatedLinMotorImpulse = real_t(0.0);
m_accumulatedAngMotorImpulse = real_t(0.0);
@@ -172,14 +160,13 @@ bool SliderJointSW::setup(real_t p_step)
void SliderJointSW::solve(real_t p_step) {
- int i;
- // linear
- Vector3 velA = A->get_velocity_in_local_point(m_relPosA);
- Vector3 velB = B->get_velocity_in_local_point(m_relPosB);
- Vector3 vel = velA - velB;
- for(i = 0; i < 3; i++)
- {
- const Vector3& normal = m_jacLin[i].m_linearJointAxis;
+ int i;
+ // linear
+ Vector3 velA = A->get_velocity_in_local_point(m_relPosA);
+ Vector3 velB = B->get_velocity_in_local_point(m_relPosB);
+ Vector3 vel = velA - velB;
+ for (i = 0; i < 3; i++) {
+ const Vector3 &normal = m_jacLin[i].m_linearJointAxis;
real_t rel_vel = normal.dot(vel);
// calculate positional error
real_t depth = m_depth[i];
@@ -190,81 +177,70 @@ void SliderJointSW::solve(real_t p_step) {
// calcutate and apply impulse
real_t normalImpulse = softness * (restitution * depth / p_step - damping * rel_vel) * m_jacLinDiagABInv[i];
Vector3 impulse_vector = normal * normalImpulse;
- A->apply_impulse( m_relPosA, impulse_vector);
- B->apply_impulse(m_relPosB,-impulse_vector);
- if(m_poweredLinMotor && (!i))
- { // apply linear motor
- if(m_accumulatedLinMotorImpulse < m_maxLinMotorForce)
- {
+ A->apply_impulse(m_relPosA, impulse_vector);
+ B->apply_impulse(m_relPosB, -impulse_vector);
+ if (m_poweredLinMotor && (!i)) { // apply linear motor
+ if (m_accumulatedLinMotorImpulse < m_maxLinMotorForce) {
real_t desiredMotorVel = m_targetLinMotorVelocity;
real_t motor_relvel = desiredMotorVel + rel_vel;
normalImpulse = -motor_relvel * m_jacLinDiagABInv[i];
// clamp accumulated impulse
real_t new_acc = m_accumulatedLinMotorImpulse + Math::abs(normalImpulse);
- if(new_acc > m_maxLinMotorForce)
- {
+ if (new_acc > m_maxLinMotorForce) {
new_acc = m_maxLinMotorForce;
}
- real_t del = new_acc - m_accumulatedLinMotorImpulse;
- if(normalImpulse < real_t(0.0))
- {
+ real_t del = new_acc - m_accumulatedLinMotorImpulse;
+ if (normalImpulse < real_t(0.0)) {
normalImpulse = -del;
- }
- else
- {
+ } else {
normalImpulse = del;
}
m_accumulatedLinMotorImpulse = new_acc;
// apply clamped impulse
impulse_vector = normal * normalImpulse;
- A->apply_impulse( m_relPosA, impulse_vector);
- B->apply_impulse( m_relPosB,-impulse_vector);
+ A->apply_impulse(m_relPosA, impulse_vector);
+ B->apply_impulse(m_relPosB, -impulse_vector);
}
}
- }
+ }
// angular
// get axes in world space
- Vector3 axisA = m_calculatedTransformA.basis.get_axis(0);
- Vector3 axisB = m_calculatedTransformB.basis.get_axis(0);
+ Vector3 axisA = m_calculatedTransformA.basis.get_axis(0);
+ Vector3 axisB = m_calculatedTransformB.basis.get_axis(0);
- const Vector3& angVelA = A->get_angular_velocity();
- const Vector3& angVelB = B->get_angular_velocity();
+ const Vector3 &angVelA = A->get_angular_velocity();
+ const Vector3 &angVelB = B->get_angular_velocity();
Vector3 angVelAroundAxisA = axisA * axisA.dot(angVelA);
Vector3 angVelAroundAxisB = axisB * axisB.dot(angVelB);
Vector3 angAorthog = angVelA - angVelAroundAxisA;
Vector3 angBorthog = angVelB - angVelAroundAxisB;
- Vector3 velrelOrthog = angAorthog-angBorthog;
+ Vector3 velrelOrthog = angAorthog - angBorthog;
//solve orthogonal angular velocity correction
real_t len = velrelOrthog.length();
- if (len > real_t(0.00001))
- {
+ if (len > real_t(0.00001)) {
Vector3 normal = velrelOrthog.normalized();
real_t denom = A->compute_angular_impulse_denominator(normal) + B->compute_angular_impulse_denominator(normal);
- velrelOrthog *= (real_t(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng;
+ velrelOrthog *= (real_t(1.) / denom) * m_dampingOrthoAng * m_softnessOrthoAng;
}
//solve angular positional correction
- Vector3 angularError = axisA.cross(axisB) *(real_t(1.)/p_step);
+ Vector3 angularError = axisA.cross(axisB) * (real_t(1.) / p_step);
real_t len2 = angularError.length();
- if (len2>real_t(0.00001))
- {
+ if (len2 > real_t(0.00001)) {
Vector3 normal2 = angularError.normalized();
real_t denom2 = A->compute_angular_impulse_denominator(normal2) + B->compute_angular_impulse_denominator(normal2);
- angularError *= (real_t(1.)/denom2) * m_restitutionOrthoAng * m_softnessOrthoAng;
+ angularError *= (real_t(1.) / denom2) * m_restitutionOrthoAng * m_softnessOrthoAng;
}
// apply impulse
- A->apply_torque_impulse(-velrelOrthog+angularError);
- B->apply_torque_impulse(velrelOrthog-angularError);
+ A->apply_torque_impulse(-velrelOrthog + angularError);
+ B->apply_torque_impulse(velrelOrthog - angularError);
real_t impulseMag;
//solve angular limits
- if(m_solveAngLim)
- {
+ if (m_solveAngLim) {
impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingLimAng + m_angDepth * m_restitutionLimAng / p_step;
impulseMag *= m_kAngle * m_softnessLimAng;
- }
- else
- {
+ } else {
impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingDirAng + m_angDepth * m_restitutionDirAng / p_step;
impulseMag *= m_kAngle * m_softnessDirAng;
}
@@ -272,10 +248,8 @@ void SliderJointSW::solve(real_t p_step) {
A->apply_torque_impulse(impulse);
B->apply_torque_impulse(-impulse);
//apply angular motor
- if(m_poweredAngMotor)
- {
- if(m_accumulatedAngMotorImpulse < m_maxAngMotorForce)
- {
+ if (m_poweredAngMotor) {
+ if (m_accumulatedAngMotorImpulse < m_maxAngMotorForce) {
Vector3 velrel = angVelAroundAxisA - angVelAroundAxisB;
real_t projRelVel = velrel.dot(axisA);
@@ -285,17 +259,13 @@ void SliderJointSW::solve(real_t p_step) {
real_t angImpulse = m_kAngle * motor_relvel;
// clamp accumulated impulse
real_t new_acc = m_accumulatedAngMotorImpulse + Math::abs(angImpulse);
- if(new_acc > m_maxAngMotorForce)
- {
+ if (new_acc > m_maxAngMotorForce) {
new_acc = m_maxAngMotorForce;
}
- real_t del = new_acc - m_accumulatedAngMotorImpulse;
- if(angImpulse < real_t(0.0))
- {
+ real_t del = new_acc - m_accumulatedAngMotorImpulse;
+ if (angImpulse < real_t(0.0)) {
angImpulse = -del;
- }
- else
- {
+ } else {
angImpulse = del;
}
m_accumulatedAngMotorImpulse = new_acc;
@@ -311,96 +281,75 @@ void SliderJointSW::solve(real_t p_step) {
//-----------------------------------------------------------------------------
-void SliderJointSW::calculateTransforms(void){
- m_calculatedTransformA = A->get_transform() * m_frameInA ;
+void SliderJointSW::calculateTransforms(void) {
+ m_calculatedTransformA = A->get_transform() * m_frameInA;
m_calculatedTransformB = B->get_transform() * m_frameInB;
m_realPivotAInW = m_calculatedTransformA.origin;
m_realPivotBInW = m_calculatedTransformB.origin;
m_sliderAxis = m_calculatedTransformA.basis.get_axis(0); // along X
m_delta = m_realPivotBInW - m_realPivotAInW;
m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis;
- Vector3 normalWorld;
- int i;
- //linear part
- for(i = 0; i < 3; i++)
- {
+ Vector3 normalWorld;
+ int i;
+ //linear part
+ for (i = 0; i < 3; i++) {
normalWorld = m_calculatedTransformA.basis.get_axis(i);
m_depth[i] = m_delta.dot(normalWorld);
- }
+ }
} // SliderJointSW::calculateTransforms()
//-----------------------------------------------------------------------------
-void SliderJointSW::testLinLimits(void)
-{
+void SliderJointSW::testLinLimits(void) {
m_solveLinLim = false;
m_linPos = m_depth[0];
- if(m_lowerLinLimit <= m_upperLinLimit)
- {
- if(m_depth[0] > m_upperLinLimit)
- {
+ if (m_lowerLinLimit <= m_upperLinLimit) {
+ if (m_depth[0] > m_upperLinLimit) {
m_depth[0] -= m_upperLinLimit;
m_solveLinLim = true;
- }
- else if(m_depth[0] < m_lowerLinLimit)
- {
+ } else if (m_depth[0] < m_lowerLinLimit) {
m_depth[0] -= m_lowerLinLimit;
m_solveLinLim = true;
- }
- else
- {
+ } else {
m_depth[0] = real_t(0.);
}
- }
- else
- {
+ } else {
m_depth[0] = real_t(0.);
}
} // SliderJointSW::testLinLimits()
//-----------------------------------------------------------------------------
-
-void SliderJointSW::testAngLimits(void)
-{
+void SliderJointSW::testAngLimits(void) {
m_angDepth = real_t(0.);
m_solveAngLim = false;
- if(m_lowerAngLimit <= m_upperAngLimit)
- {
+ if (m_lowerAngLimit <= m_upperAngLimit) {
const Vector3 axisA0 = m_calculatedTransformA.basis.get_axis(1);
const Vector3 axisA1 = m_calculatedTransformA.basis.get_axis(2);
const Vector3 axisB0 = m_calculatedTransformB.basis.get_axis(1);
real_t rot = atan2fast(axisB0.dot(axisA1), axisB0.dot(axisA0));
- if(rot < m_lowerAngLimit)
- {
+ if (rot < m_lowerAngLimit) {
m_angDepth = rot - m_lowerAngLimit;
m_solveAngLim = true;
- }
- else if(rot > m_upperAngLimit)
- {
+ } else if (rot > m_upperAngLimit) {
m_angDepth = rot - m_upperAngLimit;
m_solveAngLim = true;
}
}
} // SliderJointSW::testAngLimits()
-
//-----------------------------------------------------------------------------
-
-
-Vector3 SliderJointSW::getAncorInA(void)
-{
+Vector3 SliderJointSW::getAncorInA(void) {
Vector3 ancorInA;
ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * real_t(0.5) * m_sliderAxis;
- ancorInA = A->get_transform().inverse().xform( ancorInA );
+ ancorInA = A->get_transform().inverse().xform(ancorInA);
return ancorInA;
} // SliderJointSW::getAncorInA()
//-----------------------------------------------------------------------------
-Vector3 SliderJointSW::getAncorInB(void)
-{
+Vector3 SliderJointSW::getAncorInB(void) {
Vector3 ancorInB;
ancorInB = m_frameInB.origin;
return ancorInB;
@@ -408,38 +357,36 @@ Vector3 SliderJointSW::getAncorInB(void)
void SliderJointSW::set_param(PhysicsServer::SliderJointParam p_param, real_t p_value) {
- switch(p_param) {
- case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: m_upperLinLimit=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: m_lowerLinLimit=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: m_softnessLimLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: m_restitutionLimLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: m_dampingLimLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: m_softnessDirLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: m_restitutionDirLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING: m_dampingDirLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoLin=p_value; break;
- case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: m_dampingOrthoLin=p_value; break;
-
- case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: m_upperAngLimit=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: m_lowerAngLimit=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: m_softnessLimAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: m_restitutionLimAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: m_dampingLimAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: m_softnessDirAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: m_restitutionDirAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: m_dampingDirAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoAng=p_value; break;
- case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: m_dampingOrthoAng=p_value; break;
-
+ switch (p_param) {
+ case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: m_upperLinLimit = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: m_lowerLinLimit = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: m_softnessLimLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION: m_restitutionLimLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_DAMPING: m_dampingLimLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_SOFTNESS: m_softnessDirLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_RESTITUTION: m_restitutionDirLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_MOTION_DAMPING: m_dampingDirLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoLin = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING: m_dampingOrthoLin = p_value; break;
+
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_UPPER: m_upperAngLimit = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_LOWER: m_lowerAngLimit = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS: m_softnessLimAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION: m_restitutionLimAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_LIMIT_DAMPING: m_dampingLimAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS: m_softnessDirAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION: m_restitutionDirAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_MOTION_DAMPING: m_dampingDirAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: m_softnessOrthoAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: m_restitutionOrthoAng = p_value; break;
+ case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: m_dampingOrthoAng = p_value; break;
}
-
}
real_t SliderJointSW::get_param(PhysicsServer::SliderJointParam p_param) const {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_UPPER: return m_upperLinLimit;
case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_LOWER: return m_lowerLinLimit;
case PhysicsServer::SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS: return m_softnessLimLin;
@@ -463,11 +410,7 @@ real_t SliderJointSW::get_param(PhysicsServer::SliderJointParam p_param) const {
case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS: return m_softnessOrthoAng;
case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION: return m_restitutionOrthoAng;
case PhysicsServer::SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING: return m_dampingOrthoAng;
-
}
return 0;
-
}
-
-
diff --git a/servers/physics/joints/slider_joint_sw.h b/servers/physics/joints/slider_joint_sw.h
index d01038df59..faf36bfe9e 100644
--- a/servers/physics/joints/slider_joint_sw.h
+++ b/servers/physics/joints/slider_joint_sw.h
@@ -34,9 +34,8 @@ Adapted to Godot from the Bullet library.
#ifndef SLIDER_JOINT_SW_H
#define SLIDER_JOINT_SW_H
-#include "servers/physics/joints_sw.h"
#include "servers/physics/joints/jacobian_entry_sw.h"
-
+#include "servers/physics/joints_sw.h"
/*
Bullet Continuous Collision Detection and Physics Library
@@ -59,15 +58,14 @@ April 04, 2008
*/
-#define SLIDER_CONSTRAINT_DEF_SOFTNESS (real_t(1.0))
-#define SLIDER_CONSTRAINT_DEF_DAMPING (real_t(1.0))
-#define SLIDER_CONSTRAINT_DEF_RESTITUTION (real_t(0.7))
+#define SLIDER_CONSTRAINT_DEF_SOFTNESS (real_t(1.0))
+#define SLIDER_CONSTRAINT_DEF_DAMPING (real_t(1.0))
+#define SLIDER_CONSTRAINT_DEF_RESTITUTION (real_t(0.7))
//-----------------------------------------------------------------------------
class SliderJointSW : public JointSW {
protected:
-
union {
struct {
BodySW *A;
@@ -77,8 +75,8 @@ protected:
BodySW *_arr[2];
};
- Transform m_frameInA;
- Transform m_frameInB;
+ Transform m_frameInA;
+ Transform m_frameInB;
// linear limits
real_t m_lowerLinLimit;
@@ -115,14 +113,14 @@ protected:
bool m_solveLinLim;
bool m_solveAngLim;
- JacobianEntrySW m_jacLin[3];
- real_t m_jacLinDiagABInv[3];
+ JacobianEntrySW m_jacLin[3];
+ real_t m_jacLinDiagABInv[3];
- JacobianEntrySW m_jacAng[3];
+ JacobianEntrySW m_jacAng[3];
real_t m_timeStep;
- Transform m_calculatedTransformA;
- Transform m_calculatedTransformB;
+ Transform m_calculatedTransformA;
+ Transform m_calculatedTransformB;
Vector3 m_sliderAxis;
Vector3 m_realPivotAInW;
@@ -138,45 +136,46 @@ protected:
real_t m_angDepth;
real_t m_kAngle;
- bool m_poweredLinMotor;
- real_t m_targetLinMotorVelocity;
- real_t m_maxLinMotorForce;
- real_t m_accumulatedLinMotorImpulse;
+ bool m_poweredLinMotor;
+ real_t m_targetLinMotorVelocity;
+ real_t m_maxLinMotorForce;
+ real_t m_accumulatedLinMotorImpulse;
- bool m_poweredAngMotor;
- real_t m_targetAngMotorVelocity;
- real_t m_maxAngMotorForce;
- real_t m_accumulatedAngMotorImpulse;
+ bool m_poweredAngMotor;
+ real_t m_targetAngMotorVelocity;
+ real_t m_maxAngMotorForce;
+ real_t m_accumulatedAngMotorImpulse;
//------------------------
void initParams();
+
public:
// constructors
- SliderJointSW(BodySW* rbA, BodySW* rbB, const Transform& frameInA, const Transform& frameInB);
- //SliderJointSW();
+ SliderJointSW(BodySW *rbA, BodySW *rbB, const Transform &frameInA, const Transform &frameInB);
+ //SliderJointSW();
// overrides
// access
- const BodySW* getRigidBodyA() const { return A; }
- const BodySW* getRigidBodyB() const { return B; }
- const Transform & getCalculatedTransformA() const { return m_calculatedTransformA; }
- const Transform & getCalculatedTransformB() const { return m_calculatedTransformB; }
- const Transform & getFrameOffsetA() const { return m_frameInA; }
- const Transform & getFrameOffsetB() const { return m_frameInB; }
- Transform & getFrameOffsetA() { return m_frameInA; }
- Transform & getFrameOffsetB() { return m_frameInB; }
- real_t getLowerLinLimit() { return m_lowerLinLimit; }
- void setLowerLinLimit(real_t lowerLimit) { m_lowerLinLimit = lowerLimit; }
- real_t getUpperLinLimit() { return m_upperLinLimit; }
- void setUpperLinLimit(real_t upperLimit) { m_upperLinLimit = upperLimit; }
- real_t getLowerAngLimit() { return m_lowerAngLimit; }
- void setLowerAngLimit(real_t lowerLimit) { m_lowerAngLimit = lowerLimit; }
- real_t getUpperAngLimit() { return m_upperAngLimit; }
- void setUpperAngLimit(real_t upperLimit) { m_upperAngLimit = upperLimit; }
+ const BodySW *getRigidBodyA() const { return A; }
+ const BodySW *getRigidBodyB() const { return B; }
+ const Transform &getCalculatedTransformA() const { return m_calculatedTransformA; }
+ const Transform &getCalculatedTransformB() const { return m_calculatedTransformB; }
+ const Transform &getFrameOffsetA() const { return m_frameInA; }
+ const Transform &getFrameOffsetB() const { return m_frameInB; }
+ Transform &getFrameOffsetA() { return m_frameInA; }
+ Transform &getFrameOffsetB() { return m_frameInB; }
+ real_t getLowerLinLimit() { return m_lowerLinLimit; }
+ void setLowerLinLimit(real_t lowerLimit) { m_lowerLinLimit = lowerLimit; }
+ real_t getUpperLinLimit() { return m_upperLinLimit; }
+ void setUpperLinLimit(real_t upperLimit) { m_upperLinLimit = upperLimit; }
+ real_t getLowerAngLimit() { return m_lowerAngLimit; }
+ void setLowerAngLimit(real_t lowerLimit) { m_lowerAngLimit = lowerLimit; }
+ real_t getUpperAngLimit() { return m_upperAngLimit; }
+ void setUpperAngLimit(real_t upperLimit) { m_upperAngLimit = upperLimit; }
real_t getSoftnessDirLin() { return m_softnessDirLin; }
real_t getRestitutionDirLin() { return m_restitutionDirLin; }
- real_t getDampingDirLin() { return m_dampingDirLin ; }
+ real_t getDampingDirLin() { return m_dampingDirLin; }
real_t getSoftnessDirAng() { return m_softnessDirAng; }
real_t getRestitutionDirAng() { return m_restitutionDirAng; }
real_t getDampingDirAng() { return m_dampingDirAng; }
@@ -230,9 +229,9 @@ public:
bool getSolveAngLimit() { return m_solveAngLim; }
real_t getAngDepth() { return m_angDepth; }
// shared code used by ODE solver
- void calculateTransforms(void);
- void testLinLimits(void);
- void testAngLimits(void);
+ void calculateTransforms(void);
+ void testLinLimits(void);
+ void testAngLimits(void);
// access for PE Solver
Vector3 getAncorInA(void);
Vector3 getAncorInB(void);
@@ -244,8 +243,6 @@ public:
void solve(real_t p_step);
virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_SLIDER; }
-
};
-
#endif // SLIDER_JOINT_SW_H
diff --git a/servers/physics/joints_sw.h b/servers/physics/joints_sw.h
index c87c86b599..0f637faf79 100644
--- a/servers/physics/joints_sw.h
+++ b/servers/physics/joints_sw.h
@@ -29,19 +29,16 @@
#ifndef JOINTS_SW_H
#define JOINTS_SW_H
-#include "constraint_sw.h"
#include "body_sw.h"
-
+#include "constraint_sw.h"
class JointSW : public ConstraintSW {
-
public:
-
- virtual PhysicsServer::JointType get_type() const=0;
- _FORCE_INLINE_ JointSW(BodySW **p_body_ptr=NULL,int p_body_count=0) : ConstraintSW(p_body_ptr,p_body_count) {
+ virtual PhysicsServer::JointType get_type() const = 0;
+ _FORCE_INLINE_ JointSW(BodySW **p_body_ptr = NULL, int p_body_count = 0)
+ : ConstraintSW(p_body_ptr, p_body_count) {
}
-
};
#endif // JOINTS_SW_H
diff --git a/servers/physics/physics_server_sw.cpp b/servers/physics/physics_server_sw.cpp
index 67e3b27852..37be0a8a1c 100644
--- a/servers/physics/physics_server_sw.cpp
+++ b/servers/physics/physics_server_sw.cpp
@@ -29,57 +29,56 @@
#include "physics_server_sw.h"
#include "broad_phase_basic.h"
#include "broad_phase_octree.h"
-#include "joints/pin_joint_sw.h"
-#include "joints/hinge_joint_sw.h"
-#include "joints/slider_joint_sw.h"
#include "joints/cone_twist_joint_sw.h"
#include "joints/generic_6dof_joint_sw.h"
-#include "script_language.h"
+#include "joints/hinge_joint_sw.h"
+#include "joints/pin_joint_sw.h"
+#include "joints/slider_joint_sw.h"
#include "os/os.h"
+#include "script_language.h"
RID PhysicsServerSW::shape_create(ShapeType p_shape) {
- ShapeSW *shape=NULL;
- switch(p_shape) {
+ ShapeSW *shape = NULL;
+ switch (p_shape) {
case SHAPE_PLANE: {
- shape=memnew( PlaneShapeSW );
+ shape = memnew(PlaneShapeSW);
} break;
case SHAPE_RAY: {
- shape=memnew( RayShapeSW );
+ shape = memnew(RayShapeSW);
} break;
case SHAPE_SPHERE: {
- shape=memnew( SphereShapeSW);
+ shape = memnew(SphereShapeSW);
} break;
case SHAPE_BOX: {
- shape=memnew( BoxShapeSW);
+ shape = memnew(BoxShapeSW);
} break;
case SHAPE_CAPSULE: {
- shape=memnew( CapsuleShapeSW );
+ shape = memnew(CapsuleShapeSW);
} break;
case SHAPE_CONVEX_POLYGON: {
- shape=memnew( ConvexPolygonShapeSW );
+ shape = memnew(ConvexPolygonShapeSW);
} break;
case SHAPE_CONCAVE_POLYGON: {
- shape=memnew( ConcavePolygonShapeSW );
+ shape = memnew(ConcavePolygonShapeSW);
} break;
case SHAPE_HEIGHTMAP: {
- shape=memnew( HeightMapShapeSW );
+ shape = memnew(HeightMapShapeSW);
} break;
case SHAPE_CUSTOM: {
ERR_FAIL_V(RID());
} break;
-
}
RID id = shape_owner.make_rid(shape);
@@ -88,71 +87,62 @@ RID PhysicsServerSW::shape_create(ShapeType p_shape) {
return id;
};
-void PhysicsServerSW::shape_set_data(RID p_shape, const Variant& p_data) {
+void PhysicsServerSW::shape_set_data(RID p_shape, const Variant &p_data) {
ShapeSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
shape->set_data(p_data);
-
-
};
-
void PhysicsServerSW::shape_set_custom_solver_bias(RID p_shape, real_t p_bias) {
ShapeSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
shape->set_custom_bias(p_bias);
-
}
-
PhysicsServer::ShapeType PhysicsServerSW::shape_get_type(RID p_shape) const {
const ShapeSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,SHAPE_CUSTOM);
+ ERR_FAIL_COND_V(!shape, SHAPE_CUSTOM);
return shape->get_type();
-
};
Variant PhysicsServerSW::shape_get_data(RID p_shape) const {
const ShapeSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,Variant());
- ERR_FAIL_COND_V(!shape->is_configured(),Variant());
+ ERR_FAIL_COND_V(!shape, Variant());
+ ERR_FAIL_COND_V(!shape->is_configured(), Variant());
return shape->get_data();
-
};
real_t PhysicsServerSW::shape_get_custom_solver_bias(RID p_shape) const {
const ShapeSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ERR_FAIL_COND_V(!shape, 0);
return shape->get_custom_bias();
-
}
-
RID PhysicsServerSW::space_create() {
- SpaceSW *space = memnew( SpaceSW );
+ SpaceSW *space = memnew(SpaceSW);
RID id = space_owner.make_rid(space);
space->set_self(id);
RID area_id = area_create();
AreaSW *area = area_owner.get(area_id);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
space->set_default_area(area);
area->set_space(space);
area->set_priority(-1);
RID sgb = body_create();
- body_set_space(sgb,id);
- body_set_mode(sgb,BODY_MODE_STATIC);
+ body_set_space(sgb, id);
+ body_set_mode(sgb, BODY_MODE_STATIC);
space->set_static_global_body(sgb);
return id;
};
-void PhysicsServerSW::space_set_active(RID p_space,bool p_active) {
+void PhysicsServerSW::space_set_active(RID p_space, bool p_active) {
SpaceSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
@@ -165,70 +155,63 @@ void PhysicsServerSW::space_set_active(RID p_space,bool p_active) {
bool PhysicsServerSW::space_is_active(RID p_space) const {
const SpaceSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,false);
+ ERR_FAIL_COND_V(!space, false);
return active_spaces.has(space);
-
}
-void PhysicsServerSW::space_set_param(RID p_space,SpaceParameter p_param, real_t p_value) {
+void PhysicsServerSW::space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) {
SpaceSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
- space->set_param(p_param,p_value);
-
+ space->set_param(p_param, p_value);
}
-real_t PhysicsServerSW::space_get_param(RID p_space,SpaceParameter p_param) const {
+real_t PhysicsServerSW::space_get_param(RID p_space, SpaceParameter p_param) const {
const SpaceSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,0);
+ ERR_FAIL_COND_V(!space, 0);
return space->get_param(p_param);
}
-PhysicsDirectSpaceState* PhysicsServerSW::space_get_direct_state(RID p_space) {
+PhysicsDirectSpaceState *PhysicsServerSW::space_get_direct_state(RID p_space) {
SpaceSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,NULL);
+ ERR_FAIL_COND_V(!space, NULL);
if (!doing_sync || space->is_locked()) {
ERR_EXPLAIN("Space state is inaccesible right now, wait for iteration or fixed process notification.");
ERR_FAIL_V(NULL);
-
-
}
return space->get_direct_state();
}
-void PhysicsServerSW::space_set_debug_contacts(RID p_space,int p_max_contacts) {
+void PhysicsServerSW::space_set_debug_contacts(RID p_space, int p_max_contacts) {
SpaceSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
space->set_debug_contacts(p_max_contacts);
-
}
Vector<Vector3> PhysicsServerSW::space_get_contacts(RID p_space) const {
SpaceSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,Vector<Vector3>());
+ ERR_FAIL_COND_V(!space, Vector<Vector3>());
return space->get_debug_contacts();
-
}
int PhysicsServerSW::space_get_contact_count(RID p_space) const {
SpaceSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,0);
+ ERR_FAIL_COND_V(!space, 0);
return space->get_debug_contact_count();
-
}
RID PhysicsServerSW::area_create() {
- AreaSW *area = memnew( AreaSW );
+ AreaSW *area = memnew(AreaSW);
RID rid = area_owner.make_rid(area);
area->set_self(rid);
return rid;
@@ -238,20 +221,19 @@ void PhysicsServerSW::area_set_space(RID p_area, RID p_space) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- SpaceSW *space=NULL;
+ SpaceSW *space = NULL;
if (p_space.is_valid()) {
space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
}
area->set_space(space);
-
};
RID PhysicsServerSW::area_get_space(RID p_area) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
SpaceSW *space = area->get_space();
if (!space)
@@ -261,7 +243,6 @@ RID PhysicsServerSW::area_get_space(RID p_area) const {
void PhysicsServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) {
-
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -271,13 +252,12 @@ void PhysicsServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverride
PhysicsServer::AreaSpaceOverrideMode PhysicsServerSW::area_get_space_override_mode(RID p_area) const {
const AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,AREA_SPACE_OVERRIDE_DISABLED);
+ ERR_FAIL_COND_V(!area, AREA_SPACE_OVERRIDE_DISABLED);
return area->get_space_override_mode();
}
-
-void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform& p_transform) {
+void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform &p_transform) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -285,11 +265,10 @@ void PhysicsServerSW::area_add_shape(RID p_area, RID p_shape, const Transform& p
ShapeSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
- area->add_shape(shape,p_transform);
-
+ area->add_shape(shape, p_transform);
}
-void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) {
+void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -298,39 +277,37 @@ void PhysicsServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) {
ERR_FAIL_COND(!shape);
ERR_FAIL_COND(!shape->is_configured());
- area->set_shape(p_shape_idx,shape);
-
+ area->set_shape(p_shape_idx, shape);
}
-void PhysicsServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform& p_transform) {
+void PhysicsServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_shape_transform(p_shape_idx,p_transform);
+ area->set_shape_transform(p_shape_idx, p_transform);
}
int PhysicsServerSW::area_get_shape_count(RID p_area) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,-1);
+ ERR_FAIL_COND_V(!area, -1);
return area->get_shape_count();
-
}
RID PhysicsServerSW::area_get_shape(RID p_area, int p_shape_idx) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
ShapeSW *shape = area->get_shape(p_shape_idx);
- ERR_FAIL_COND_V(!shape,RID());
+ ERR_FAIL_COND_V(!shape, RID());
return shape->get_self();
}
Transform PhysicsServerSW::area_get_shape_transform(RID p_area, int p_shape_idx) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Transform());
+ ERR_FAIL_COND_V(!area, Transform());
return area->get_shape_transform(p_shape_idx);
}
@@ -348,65 +325,57 @@ void PhysicsServerSW::area_clear_shapes(RID p_area) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- while(area->get_shape_count())
+ while (area->get_shape_count())
area->remove_shape(0);
-
}
-void PhysicsServerSW::area_attach_object_instance_ID(RID p_area,ObjectID p_ID) {
+void PhysicsServerSW::area_attach_object_instance_ID(RID p_area, ObjectID p_ID) {
if (space_owner.owns(p_area)) {
- SpaceSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ SpaceSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_instance_id(p_ID);
-
}
ObjectID PhysicsServerSW::area_get_object_instance_ID(RID p_area) const {
if (space_owner.owns(p_area)) {
- SpaceSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ SpaceSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,0);
+ ERR_FAIL_COND_V(!area, 0);
return area->get_instance_id();
-
-
}
-
-void PhysicsServerSW::area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value) {
+void PhysicsServerSW::area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) {
if (space_owner.owns(p_area)) {
- SpaceSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ SpaceSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_param(p_param,p_value);
-
+ area->set_param(p_param, p_value);
};
-
-void PhysicsServerSW::area_set_transform(RID p_area, const Transform& p_transform) {
+void PhysicsServerSW::area_set_transform(RID p_area, const Transform &p_transform) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_transform(p_transform);
-
};
-Variant PhysicsServerSW::area_get_param(RID p_area,AreaParameter p_param) const {
+Variant PhysicsServerSW::area_get_param(RID p_area, AreaParameter p_param) const {
if (space_owner.owns(p_area)) {
- SpaceSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ SpaceSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Variant());
+ ERR_FAIL_COND_V(!area, Variant());
return area->get_param(p_param);
};
@@ -414,12 +383,12 @@ Variant PhysicsServerSW::area_get_param(RID p_area,AreaParameter p_param) const
Transform PhysicsServerSW::area_get_transform(RID p_area) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Transform());
+ ERR_FAIL_COND_V(!area, Transform());
return area->get_transform();
};
-void PhysicsServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) {
+void PhysicsServerSW::area_set_layer_mask(RID p_area, uint32_t p_mask) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -427,7 +396,7 @@ void PhysicsServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) {
area->set_layer_mask(p_mask);
}
-void PhysicsServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) {
+void PhysicsServerSW::area_set_collision_mask(RID p_area, uint32_t p_mask) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -435,7 +404,7 @@ void PhysicsServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) {
area->set_collision_mask(p_mask);
}
-void PhysicsServerSW::area_set_monitorable(RID p_area,bool p_monitorable) {
+void PhysicsServerSW::area_set_monitorable(RID p_area, bool p_monitorable) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -443,81 +412,73 @@ void PhysicsServerSW::area_set_monitorable(RID p_area,bool p_monitorable) {
area->set_monitorable(p_monitorable);
}
-void PhysicsServerSW::area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) {
+void PhysicsServerSW::area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method);
-
-
+ area->set_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method);
}
-void PhysicsServerSW::area_set_ray_pickable(RID p_area,bool p_enable) {
+void PhysicsServerSW::area_set_ray_pickable(RID p_area, bool p_enable) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_ray_pickable(p_enable);
-
}
-bool PhysicsServerSW::area_is_ray_pickable(RID p_area) const{
+bool PhysicsServerSW::area_is_ray_pickable(RID p_area) const {
AreaSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,false);
+ ERR_FAIL_COND_V(!area, false);
return area->is_ray_pickable();
-
}
-
-void PhysicsServerSW::area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) {
-
+void PhysicsServerSW::area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) {
AreaSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_area_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method);
+ area->set_area_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method);
}
/* BODY API */
-RID PhysicsServerSW::body_create(BodyMode p_mode,bool p_init_sleeping) {
+RID PhysicsServerSW::body_create(BodyMode p_mode, bool p_init_sleeping) {
- BodySW *body = memnew( BodySW );
- if (p_mode!=BODY_MODE_RIGID)
+ BodySW *body = memnew(BodySW);
+ if (p_mode != BODY_MODE_RIGID)
body->set_mode(p_mode);
if (p_init_sleeping)
- body->set_state(BODY_STATE_SLEEPING,p_init_sleeping);
+ body->set_state(BODY_STATE_SLEEPING, p_init_sleeping);
RID rid = body_owner.make_rid(body);
body->set_self(rid);
return rid;
};
-
void PhysicsServerSW::body_set_space(RID p_body, RID p_space) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- SpaceSW *space=NULL;
+ SpaceSW *space = NULL;
if (p_space.is_valid()) {
space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
}
- if (body->get_space()==space)
+ if (body->get_space() == space)
return; //pointles
body->set_space(space);
-
};
RID PhysicsServerSW::body_get_space(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,RID());
+ ERR_FAIL_COND_V(!body, RID());
SpaceSW *space = body->get_space();
if (!space)
@@ -525,7 +486,6 @@ RID PhysicsServerSW::body_get_space(RID p_body) const {
return space->get_self();
};
-
void PhysicsServerSW::body_set_mode(RID p_body, BodyMode p_mode) {
BodySW *body = body_owner.get(p_body);
@@ -537,12 +497,12 @@ void PhysicsServerSW::body_set_mode(RID p_body, BodyMode p_mode) {
PhysicsServer::BodyMode PhysicsServerSW::body_get_mode(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,BODY_MODE_STATIC);
+ ERR_FAIL_COND_V(!body, BODY_MODE_STATIC);
return body->get_mode();
};
-void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform& p_transform) {
+void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform &p_transform) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -550,11 +510,10 @@ void PhysicsServerSW::body_add_shape(RID p_body, RID p_shape, const Transform& p
ShapeSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
- body->add_shape(shape,p_transform);
-
+ body->add_shape(shape, p_transform);
}
-void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) {
+void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -563,59 +522,55 @@ void PhysicsServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) {
ERR_FAIL_COND(!shape);
ERR_FAIL_COND(!shape->is_configured());
- body->set_shape(p_shape_idx,shape);
-
+ body->set_shape(p_shape_idx, shape);
}
-void PhysicsServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform& p_transform) {
+void PhysicsServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_shape_transform(p_shape_idx,p_transform);
+ body->set_shape_transform(p_shape_idx, p_transform);
}
int PhysicsServerSW::body_get_shape_count(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,-1);
+ ERR_FAIL_COND_V(!body, -1);
return body->get_shape_count();
-
}
RID PhysicsServerSW::body_get_shape(RID p_body, int p_shape_idx) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,RID());
+ ERR_FAIL_COND_V(!body, RID());
ShapeSW *shape = body->get_shape(p_shape_idx);
- ERR_FAIL_COND_V(!shape,RID());
+ ERR_FAIL_COND_V(!shape, RID());
return shape->get_self();
}
-void PhysicsServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable) {
+void PhysicsServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- ERR_FAIL_INDEX(p_shape_idx,body->get_shape_count());
- body->set_shape_as_trigger(p_shape_idx,p_enable);
-
+ ERR_FAIL_INDEX(p_shape_idx, body->get_shape_count());
+ body->set_shape_as_trigger(p_shape_idx, p_enable);
}
-bool PhysicsServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const{
+bool PhysicsServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
- ERR_FAIL_INDEX_V(p_shape_idx,body->get_shape_count(),false);
+ ERR_FAIL_COND_V(!body, false);
+ ERR_FAIL_INDEX_V(p_shape_idx, body->get_shape_count(), false);
return body->is_shape_set_as_trigger(p_shape_idx);
}
-
Transform PhysicsServerSW::body_get_shape_transform(RID p_body, int p_shape_idx) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Transform());
+ ERR_FAIL_COND_V(!body, Transform());
return body->get_shape_transform(p_shape_idx);
}
@@ -633,24 +588,22 @@ void PhysicsServerSW::body_clear_shapes(RID p_body) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- while(body->get_shape_count())
+ while (body->get_shape_count())
body->remove_shape(0);
-
}
-void PhysicsServerSW::body_set_enable_continuous_collision_detection(RID p_body,bool p_enable) {
+void PhysicsServerSW::body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_continuous_collision_detection(p_enable);
-
}
bool PhysicsServerSW::body_is_continuous_collision_detection_enabled(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
+ ERR_FAIL_COND_V(!body, false);
return body->is_continuous_collision_detection_enabled();
}
@@ -662,16 +615,14 @@ void PhysicsServerSW::body_set_layer_mask(RID p_body, uint32_t p_mask) {
body->set_layer_mask(p_mask);
body->wakeup();
-
}
-uint32_t PhysicsServerSW::body_get_layer_mask(RID p_body, uint32_t p_mask) const{
+uint32_t PhysicsServerSW::body_get_layer_mask(RID p_body, uint32_t p_mask) const {
const BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_layer_mask();
-
}
void PhysicsServerSW::body_set_collision_mask(RID p_body, uint32_t p_mask) {
@@ -681,48 +632,42 @@ void PhysicsServerSW::body_set_collision_mask(RID p_body, uint32_t p_mask) {
body->set_collision_mask(p_mask);
body->wakeup();
-
}
-uint32_t PhysicsServerSW::body_get_collision_mask(RID p_body, uint32_t p_mask) const{
+uint32_t PhysicsServerSW::body_get_collision_mask(RID p_body, uint32_t p_mask) const {
const BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_collision_mask();
-
}
-
-void PhysicsServerSW::body_attach_object_instance_ID(RID p_body,uint32_t p_ID) {
+void PhysicsServerSW::body_attach_object_instance_ID(RID p_body, uint32_t p_ID) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_instance_id(p_ID);
-
};
uint32_t PhysicsServerSW::body_get_object_instance_ID(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_instance_id();
};
-
void PhysicsServerSW::body_set_user_flags(RID p_body, uint32_t p_flags) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
-
};
uint32_t PhysicsServerSW::body_get_user_flags(RID p_body, uint32_t p_flags) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return 0;
};
@@ -732,38 +677,34 @@ void PhysicsServerSW::body_set_param(RID p_body, BodyParameter p_param, real_t p
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_param(p_param,p_value);
+ body->set_param(p_param, p_value);
};
real_t PhysicsServerSW::body_get_param(RID p_body, BodyParameter p_param) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_param(p_param);
};
-
-
-void PhysicsServerSW::body_set_state(RID p_body, BodyState p_state, const Variant& p_variant) {
+void PhysicsServerSW::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_state(p_state,p_variant);
-
+ body->set_state(p_state, p_variant);
};
Variant PhysicsServerSW::body_get_state(RID p_body, BodyState p_state) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Variant());
+ ERR_FAIL_COND_V(!body, Variant());
return body->get_state(p_state);
};
-
-void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3& p_force) {
+void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3 &p_force) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -775,11 +716,11 @@ void PhysicsServerSW::body_set_applied_force(RID p_body, const Vector3& p_force)
Vector3 PhysicsServerSW::body_get_applied_force(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Vector3());
+ ERR_FAIL_COND_V(!body, Vector3());
return body->get_applied_force();
};
-void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3& p_torque) {
+void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3 &p_torque) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -791,21 +732,21 @@ void PhysicsServerSW::body_set_applied_torque(RID p_body, const Vector3& p_torqu
Vector3 PhysicsServerSW::body_get_applied_torque(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Vector3());
+ ERR_FAIL_COND_V(!body, Vector3());
return body->get_applied_torque();
};
-void PhysicsServerSW::body_apply_impulse(RID p_body, const Vector3& p_pos, const Vector3& p_impulse) {
+void PhysicsServerSW::body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->apply_impulse(p_pos,p_impulse);
+ body->apply_impulse(p_pos, p_impulse);
body->wakeup();
};
-void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3& p_impulse) {
+void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -814,40 +755,34 @@ void PhysicsServerSW::body_apply_torque_impulse(RID p_body, const Vector3& p_imp
body->wakeup();
};
-void PhysicsServerSW::body_set_axis_velocity(RID p_body, const Vector3& p_axis_velocity) {
+void PhysicsServerSW::body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
Vector3 v = body->get_linear_velocity();
Vector3 axis = p_axis_velocity.normalized();
- v-=axis*axis.dot(v);
- v+=p_axis_velocity;
+ v -= axis * axis.dot(v);
+ v += p_axis_velocity;
body->set_linear_velocity(v);
body->wakeup();
-
};
-
-void PhysicsServerSW::body_set_axis_lock(RID p_body,BodyAxisLock p_lock) {
+void PhysicsServerSW::body_set_axis_lock(RID p_body, BodyAxisLock p_lock) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_axis_lock(p_lock);
body->wakeup();
-
}
-PhysicsServerSW::BodyAxisLock PhysicsServerSW::body_get_axis_lock(RID p_body) const{
+PhysicsServerSW::BodyAxisLock PhysicsServerSW::body_get_axis_lock(RID p_body) const {
const BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,BODY_AXIS_LOCK_DISABLED);
+ ERR_FAIL_COND_V(!body, BODY_AXIS_LOCK_DISABLED);
return body->get_axis_lock();
-
}
-
-
void PhysicsServerSW::body_add_collision_exception(RID p_body, RID p_body_b) {
BodySW *body = body_owner.get(p_body);
@@ -855,7 +790,6 @@ void PhysicsServerSW::body_add_collision_exception(RID p_body, RID p_body_b) {
body->add_exception(p_body_b);
body->wakeup();
-
};
void PhysicsServerSW::body_remove_collision_exception(RID p_body, RID p_body_b) {
@@ -865,7 +799,6 @@ void PhysicsServerSW::body_remove_collision_exception(RID p_body, RID p_body_b)
body->remove_exception(p_body_b);
body->wakeup();
-
};
void PhysicsServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) {
@@ -873,27 +806,25 @@ void PhysicsServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exc
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- for(int i=0;i<body->get_exceptions().size();i++) {
+ for (int i = 0; i < body->get_exceptions().size(); i++) {
p_exceptions->push_back(body->get_exceptions()[i]);
}
-
};
void PhysicsServerSW::body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
-
};
real_t PhysicsServerSW::body_get_contacts_reported_depth_treshold(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return 0;
};
-void PhysicsServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) {
+void PhysicsServerSW::body_set_omit_force_integration(RID p_body, bool p_omit) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -904,7 +835,7 @@ void PhysicsServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) {
bool PhysicsServerSW::body_is_omitting_force_integration(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
+ ERR_FAIL_COND_V(!body, false);
return body->get_omit_force_integration();
};
@@ -918,355 +849,333 @@ void PhysicsServerSW::body_set_max_contacts_reported(RID p_body, int p_contacts)
int PhysicsServerSW::body_get_max_contacts_reported(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,-1);
+ ERR_FAIL_COND_V(!body, -1);
return body->get_max_contacts_reported();
}
-void PhysicsServerSW::body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata) {
-
+void PhysicsServerSW::body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_force_integration_callback(p_receiver?p_receiver->get_instance_ID():ObjectID(0),p_method,p_udata);
-
+ body->set_force_integration_callback(p_receiver ? p_receiver->get_instance_ID() : ObjectID(0), p_method, p_udata);
}
-void PhysicsServerSW::body_set_ray_pickable(RID p_body,bool p_enable) {
+void PhysicsServerSW::body_set_ray_pickable(RID p_body, bool p_enable) {
BodySW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_ray_pickable(p_enable);
-
}
-bool PhysicsServerSW::body_is_ray_pickable(RID p_body) const{
+bool PhysicsServerSW::body_is_ray_pickable(RID p_body) const {
BodySW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
+ ERR_FAIL_COND_V(!body, false);
return body->is_ray_pickable();
-
}
-
/* JOINT API */
-RID PhysicsServerSW::joint_create_pin(RID p_body_A,const Vector3& p_local_A,RID p_body_B,const Vector3& p_local_B) {
+RID PhysicsServerSW::joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( PinJointSW(body_A,p_local_A,body_B,p_local_B) );
+ JointSW *joint = memnew(PinJointSW(body_A, p_local_A, body_B, p_local_B));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
}
-void PhysicsServerSW::pin_joint_set_param(RID p_joint,PinJointParam p_param, real_t p_value){
+void PhysicsServerSW::pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_PIN);
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
- pin_joint->set_param(p_param,p_value);
-
+ ERR_FAIL_COND(joint->get_type() != JOINT_PIN);
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
+ pin_joint->set_param(p_param, p_value);
}
-real_t PhysicsServerSW::pin_joint_get_param(RID p_joint,PinJointParam p_param) const{
+real_t PhysicsServerSW::pin_joint_get_param(RID p_joint, PinJointParam p_param) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,0);
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, 0);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, 0);
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
return pin_joint->get_param(p_param);
-
}
-void PhysicsServerSW::pin_joint_set_local_A(RID p_joint, const Vector3& p_A){
+void PhysicsServerSW::pin_joint_set_local_A(RID p_joint, const Vector3 &p_A) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_PIN);
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
+ ERR_FAIL_COND(joint->get_type() != JOINT_PIN);
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
pin_joint->set_pos_A(p_A);
-
}
-Vector3 PhysicsServerSW::pin_joint_get_local_A(RID p_joint) const{
+Vector3 PhysicsServerSW::pin_joint_get_local_A(RID p_joint) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,Vector3());
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,Vector3());
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, Vector3());
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3());
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
return pin_joint->get_pos_A();
-
}
-void PhysicsServerSW::pin_joint_set_local_B(RID p_joint, const Vector3& p_B){
+void PhysicsServerSW::pin_joint_set_local_B(RID p_joint, const Vector3 &p_B) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_PIN);
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
+ ERR_FAIL_COND(joint->get_type() != JOINT_PIN);
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
pin_joint->set_pos_B(p_B);
-
}
-Vector3 PhysicsServerSW::pin_joint_get_local_B(RID p_joint) const{
+Vector3 PhysicsServerSW::pin_joint_get_local_B(RID p_joint) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,Vector3());
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_PIN,Vector3());
- PinJointSW *pin_joint = static_cast<PinJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, Vector3());
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_PIN, Vector3());
+ PinJointSW *pin_joint = static_cast<PinJointSW *>(joint);
return pin_joint->get_pos_B();
-
}
-
-RID PhysicsServerSW::joint_create_hinge(RID p_body_A,const Transform& p_frame_A,RID p_body_B,const Transform& p_frame_B) {
+RID PhysicsServerSW::joint_create_hinge(RID p_body_A, const Transform &p_frame_A, RID p_body_B, const Transform &p_frame_B) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( HingeJointSW(body_A,body_B,p_frame_A,p_frame_B) );
+ JointSW *joint = memnew(HingeJointSW(body_A, body_B, p_frame_A, p_frame_B));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
-
}
-
-RID PhysicsServerSW::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) {
+RID PhysicsServerSW::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) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( HingeJointSW(body_A,body_B,p_pivot_A,p_pivot_B,p_axis_A,p_axis_B) );
+ JointSW *joint = memnew(HingeJointSW(body_A, body_B, p_pivot_A, p_pivot_B, p_axis_A, p_axis_B));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
-
}
-void PhysicsServerSW::hinge_joint_set_param(RID p_joint,HingeJointParam p_param, real_t p_value){
+void PhysicsServerSW::hinge_joint_set_param(RID p_joint, HingeJointParam p_param, real_t p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_HINGE);
- HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint);
- hinge_joint->set_param(p_param,p_value);
-
+ ERR_FAIL_COND(joint->get_type() != JOINT_HINGE);
+ HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint);
+ hinge_joint->set_param(p_param, p_value);
}
-real_t PhysicsServerSW::hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const{
+real_t PhysicsServerSW::hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_HINGE,0);
- HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, 0);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, 0);
+ HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint);
return hinge_joint->get_param(p_param);
-
}
-void PhysicsServerSW::hinge_joint_set_flag(RID p_joint,HingeJointFlag p_flag, bool p_value){
+void PhysicsServerSW::hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_HINGE);
- HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint);
- hinge_joint->set_flag(p_flag,p_value);
-
+ ERR_FAIL_COND(joint->get_type() != JOINT_HINGE);
+ HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint);
+ hinge_joint->set_flag(p_flag, p_value);
}
-bool PhysicsServerSW::hinge_joint_get_flag(RID p_joint,HingeJointFlag p_flag) const{
+bool PhysicsServerSW::hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,false);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_HINGE,false);
- HingeJointSW *hinge_joint = static_cast<HingeJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, false);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_HINGE, false);
+ HingeJointSW *hinge_joint = static_cast<HingeJointSW *>(joint);
return hinge_joint->get_flag(p_flag);
}
-void PhysicsServerSW::joint_set_solver_priority(RID p_joint,int p_priority) {
+void PhysicsServerSW::joint_set_solver_priority(RID p_joint, int p_priority) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
joint->set_priority(p_priority);
}
-int PhysicsServerSW::joint_get_solver_priority(RID p_joint) const{
+int PhysicsServerSW::joint_get_solver_priority(RID p_joint) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
+ ERR_FAIL_COND_V(!joint, 0);
return joint->get_priority();
-
}
PhysicsServerSW::JointType PhysicsServerSW::joint_get_type(RID p_joint) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,JOINT_PIN);
+ ERR_FAIL_COND_V(!joint, JOINT_PIN);
return joint->get_type();
}
-RID PhysicsServerSW::joint_create_slider(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) {
+RID PhysicsServerSW::joint_create_slider(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( SliderJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B) );
+ JointSW *joint = memnew(SliderJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
}
-void PhysicsServerSW::slider_joint_set_param(RID p_joint,SliderJointParam p_param, real_t p_value){
+void PhysicsServerSW::slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_SLIDER);
- SliderJointSW *slider_joint = static_cast<SliderJointSW*>(joint);
- slider_joint->set_param(p_param,p_value);
+ ERR_FAIL_COND(joint->get_type() != JOINT_SLIDER);
+ SliderJointSW *slider_joint = static_cast<SliderJointSW *>(joint);
+ slider_joint->set_param(p_param, p_value);
}
-real_t PhysicsServerSW::slider_joint_get_param(RID p_joint,SliderJointParam p_param) const{
+real_t PhysicsServerSW::slider_joint_get_param(RID p_joint, SliderJointParam p_param) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_CONE_TWIST,0);
- SliderJointSW *slider_joint = static_cast<SliderJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, 0);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_CONE_TWIST, 0);
+ SliderJointSW *slider_joint = static_cast<SliderJointSW *>(joint);
return slider_joint->get_param(p_param);
}
-
-RID PhysicsServerSW::joint_create_cone_twist(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) {
+RID PhysicsServerSW::joint_create_cone_twist(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( ConeTwistJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B) );
+ JointSW *joint = memnew(ConeTwistJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
}
-void PhysicsServerSW::cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, real_t p_value) {
+void PhysicsServerSW::cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, real_t p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_CONE_TWIST);
- ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW*>(joint);
- cone_twist_joint->set_param(p_param,p_value);
+ ERR_FAIL_COND(joint->get_type() != JOINT_CONE_TWIST);
+ ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW *>(joint);
+ cone_twist_joint->set_param(p_param, p_value);
}
-real_t PhysicsServerSW::cone_twist_joint_get_param(RID p_joint,ConeTwistJointParam p_param) const {
+real_t PhysicsServerSW::cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_CONE_TWIST,0);
- ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW*>(joint);
+ ERR_FAIL_COND_V(!joint, 0);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_CONE_TWIST, 0);
+ ConeTwistJointSW *cone_twist_joint = static_cast<ConeTwistJointSW *>(joint);
return cone_twist_joint->get_param(p_param);
}
-
-RID PhysicsServerSW::joint_create_generic_6dof(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B) {
+RID PhysicsServerSW::joint_create_generic_6dof(RID p_body_A, const Transform &p_local_frame_A, RID p_body_B, const Transform &p_local_frame_B) {
BodySW *body_A = body_owner.get(p_body_A);
- ERR_FAIL_COND_V(!body_A,RID());
+ ERR_FAIL_COND_V(!body_A, RID());
if (!p_body_B.is_valid()) {
- ERR_FAIL_COND_V(!body_A->get_space(),RID());
- p_body_B=body_A->get_space()->get_static_global_body();
+ ERR_FAIL_COND_V(!body_A->get_space(), RID());
+ p_body_B = body_A->get_space()->get_static_global_body();
}
BodySW *body_B = body_owner.get(p_body_B);
- ERR_FAIL_COND_V(!body_B,RID());
+ ERR_FAIL_COND_V(!body_B, RID());
- ERR_FAIL_COND_V(body_A==body_B,RID());
+ ERR_FAIL_COND_V(body_A == body_B, RID());
- JointSW *joint = memnew( Generic6DOFJointSW(body_A,body_B,p_local_frame_A,p_local_frame_B,true) );
+ JointSW *joint = memnew(Generic6DOFJointSW(body_A, body_B, p_local_frame_A, p_local_frame_B, true));
RID rid = joint_owner.make_rid(joint);
joint->set_self(rid);
return rid;
}
-void PhysicsServerSW::generic_6dof_joint_set_param(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisParam p_param, real_t p_value){
+void PhysicsServerSW::generic_6dof_joint_set_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param, real_t p_value) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_6DOF);
- Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint);
- generic_6dof_joint->set_param(p_axis,p_param,p_value);
+ ERR_FAIL_COND(joint->get_type() != JOINT_6DOF);
+ Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint);
+ generic_6dof_joint->set_param(p_axis, p_param, p_value);
}
-real_t PhysicsServerSW::generic_6dof_joint_get_param(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisParam p_param){
+real_t PhysicsServerSW::generic_6dof_joint_get_param(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisParam p_param) {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,0);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_6DOF,0);
- Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint);
- return generic_6dof_joint->get_param(p_axis,p_param);
+ ERR_FAIL_COND_V(!joint, 0);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, 0);
+ Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint);
+ return generic_6dof_joint->get_param(p_axis, p_param);
}
-void PhysicsServerSW::generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisFlag p_flag, bool p_enable){
+void PhysicsServerSW::generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag, bool p_enable) {
JointSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- ERR_FAIL_COND(joint->get_type()!=JOINT_6DOF);
- Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint);
- generic_6dof_joint->set_flag(p_axis,p_flag,p_enable);
+ ERR_FAIL_COND(joint->get_type() != JOINT_6DOF);
+ Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint);
+ generic_6dof_joint->set_flag(p_axis, p_flag, p_enable);
}
-bool PhysicsServerSW::generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis p_axis,G6DOFJointAxisFlag p_flag){
+bool PhysicsServerSW::generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis p_axis, G6DOFJointAxisFlag p_flag) {
JointSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,false);
- ERR_FAIL_COND_V(joint->get_type()!=JOINT_6DOF,false);
- Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW*>(joint);
- return generic_6dof_joint->get_flag(p_axis,p_flag);
+ ERR_FAIL_COND_V(!joint, false);
+ ERR_FAIL_COND_V(joint->get_type() != JOINT_6DOF, false);
+ Generic6DOFJointSW *generic_6dof_joint = static_cast<Generic6DOFJointSW *>(joint);
+ return generic_6dof_joint->get_flag(p_axis, p_flag);
}
-
#if 0
void PhysicsServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t p_value) {
@@ -1384,8 +1293,8 @@ void PhysicsServerSW::free(RID p_rid) {
ShapeSW *shape = shape_owner.get(p_rid);
- while(shape->get_owners().size()) {
- ShapeOwnerSW *so=shape->get_owners().front()->key();
+ while (shape->get_owners().size()) {
+ ShapeOwnerSW *so = shape->get_owners().front()->key();
so->remove_shape(shape);
}
@@ -1405,8 +1314,7 @@ void PhysicsServerSW::free(RID p_rid) {
body->set_space(NULL);
-
- while( body->get_shape_count() ) {
+ while (body->get_shape_count()) {
body->remove_shape(0);
}
@@ -1431,7 +1339,7 @@ void PhysicsServerSW::free(RID p_rid) {
area->set_space(NULL);
- while( area->get_shape_count() ) {
+ while (area->get_shape_count()) {
area->remove_shape(0);
}
@@ -1442,7 +1350,7 @@ void PhysicsServerSW::free(RID p_rid) {
SpaceSW *space = space_owner.get(p_rid);
- while(space->get_objects().size()) {
+ while (space->get_objects().size()) {
CollisionObjectSW *co = (CollisionObjectSW *)space->get_objects().front()->get();
co->set_space(NULL);
}
@@ -1457,7 +1365,7 @@ void PhysicsServerSW::free(RID p_rid) {
JointSW *joint = joint_owner.get(p_rid);
- for(int i=0;i<joint->get_body_count();i++) {
+ for (int i = 0; i < joint->get_body_count(); i++) {
joint->get_body_ptr()[i]->remove_constraint(joint);
}
@@ -1469,51 +1377,45 @@ void PhysicsServerSW::free(RID p_rid) {
ERR_EXPLAIN("Invalid ID");
ERR_FAIL();
}
-
-
};
void PhysicsServerSW::set_active(bool p_active) {
- active=p_active;
+ active = p_active;
};
void PhysicsServerSW::init() {
- doing_sync=true;
- last_step=0.001;
- iterations=8;// 8?
- stepper = memnew( StepSW );
- direct_state = memnew( PhysicsDirectBodyStateSW );
+ doing_sync = true;
+ last_step = 0.001;
+ iterations = 8; // 8?
+ stepper = memnew(StepSW);
+ direct_state = memnew(PhysicsDirectBodyStateSW);
};
-
void PhysicsServerSW::step(real_t p_step) {
-
if (!active)
return;
+ doing_sync = false;
- doing_sync=false;
-
- last_step=p_step;
- PhysicsDirectBodyStateSW::singleton->step=p_step;
+ last_step = p_step;
+ PhysicsDirectBodyStateSW::singleton->step = p_step;
- island_count=0;
- active_objects=0;
- collision_pairs=0;
- for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ island_count = 0;
+ active_objects = 0;
+ collision_pairs = 0;
+ for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- stepper->step((SpaceSW*)E->get(),p_step,iterations);
- island_count+=E->get()->get_island_count();
- active_objects+=E->get()->get_active_objects();
- collision_pairs+=E->get()->get_collision_pairs();
+ stepper->step((SpaceSW *)E->get(), p_step, iterations);
+ island_count += E->get()->get_island_count();
+ active_objects += E->get()->get_active_objects();
+ collision_pairs += E->get()->get_collision_pairs();
}
-
}
-void PhysicsServerSW::sync() {
+void PhysicsServerSW::sync(){
};
@@ -1522,21 +1424,20 @@ void PhysicsServerSW::flush_queries() {
if (!active)
return;
- doing_sync=true;
+ doing_sync = true;
uint64_t time_beg = OS::get_singleton()->get_ticks_usec();
- for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- SpaceSW *space=(SpaceSW *)E->get();
+ SpaceSW *space = (SpaceSW *)E->get();
space->call_queries();
}
-
if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_profiling()) {
uint64_t total_time[SpaceSW::ELAPSED_TIME_MAX];
- static const char* time_name[SpaceSW::ELAPSED_TIME_MAX]={
+ static const char *time_name[SpaceSW::ELAPSED_TIME_MAX] = {
"integrate_forces",
"generate_islands",
"setup_constraints",
@@ -1544,44 +1445,39 @@ void PhysicsServerSW::flush_queries() {
"integrate_velocities"
};
- for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) {
- total_time[i]=0;
+ for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) {
+ total_time[i] = 0;
}
- for( Set<const SpaceSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ for (Set<const SpaceSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) {
- total_time[i]+=E->get()->get_elapsed_time(SpaceSW::ElapsedTime(i));
+ for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) {
+ total_time[i] += E->get()->get_elapsed_time(SpaceSW::ElapsedTime(i));
}
-
}
Array values;
- values.resize(SpaceSW::ELAPSED_TIME_MAX*2);
- for(int i=0;i<SpaceSW::ELAPSED_TIME_MAX;i++) {
- values[i*2+0]=time_name[i];
- values[i*2+1]=USEC_TO_SEC(total_time[i]);
+ values.resize(SpaceSW::ELAPSED_TIME_MAX * 2);
+ for (int i = 0; i < SpaceSW::ELAPSED_TIME_MAX; i++) {
+ values[i * 2 + 0] = time_name[i];
+ values[i * 2 + 1] = USEC_TO_SEC(total_time[i]);
}
values.push_back("flush_queries");
- values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec()-time_beg));
-
- ScriptDebugger::get_singleton()->add_profiling_frame_data("physics",values);
+ values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec() - time_beg));
+ ScriptDebugger::get_singleton()->add_profiling_frame_data("physics", values);
}
};
-
-
void PhysicsServerSW::finish() {
memdelete(stepper);
memdelete(direct_state);
};
-
int PhysicsServerSW::get_process_info(ProcessInfo p_info) {
- switch(p_info) {
+ switch (p_info) {
case INFO_ACTIVE_OBJECTS: {
@@ -1594,64 +1490,55 @@ int PhysicsServerSW::get_process_info(ProcessInfo p_info) {
return island_count;
} break;
-
}
return 0;
}
+void PhysicsServerSW::_shape_col_cbk(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
-void PhysicsServerSW::_shape_col_cbk(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) {
-
+ CollCbkData *cbk = (CollCbkData *)p_userdata;
- CollCbkData *cbk=(CollCbkData *)p_userdata;
-
- if (cbk->max==0)
+ if (cbk->max == 0)
return;
if (cbk->amount == cbk->max) {
//find least deep
- real_t min_depth=1e20;
- int min_depth_idx=0;
- for(int i=0;i<cbk->amount;i++) {
-
- real_t d = cbk->ptr[i*2+0].distance_squared_to(cbk->ptr[i*2+1]);
- if (d<min_depth) {
- min_depth=d;
- min_depth_idx=i;
+ real_t min_depth = 1e20;
+ int min_depth_idx = 0;
+ for (int i = 0; i < cbk->amount; i++) {
+
+ real_t d = cbk->ptr[i * 2 + 0].distance_squared_to(cbk->ptr[i * 2 + 1]);
+ if (d < min_depth) {
+ min_depth = d;
+ min_depth_idx = i;
}
-
}
real_t d = p_point_A.distance_squared_to(p_point_B);
- if (d<min_depth)
+ if (d < min_depth)
return;
- cbk->ptr[min_depth_idx*2+0]=p_point_A;
- cbk->ptr[min_depth_idx*2+1]=p_point_B;
-
+ cbk->ptr[min_depth_idx * 2 + 0] = p_point_A;
+ cbk->ptr[min_depth_idx * 2 + 1] = p_point_B;
} else {
- cbk->ptr[cbk->amount*2+0]=p_point_A;
- cbk->ptr[cbk->amount*2+1]=p_point_B;
+ cbk->ptr[cbk->amount * 2 + 0] = p_point_A;
+ cbk->ptr[cbk->amount * 2 + 1] = p_point_B;
cbk->amount++;
}
}
-
PhysicsServerSW::PhysicsServerSW() {
- BroadPhaseSW::create_func=BroadPhaseOctree::_create;
- island_count=0;
- active_objects=0;
- collision_pairs=0;
-
- active=true;
+ BroadPhaseSW::create_func = BroadPhaseOctree::_create;
+ island_count = 0;
+ active_objects = 0;
+ collision_pairs = 0;
+ active = true;
};
-PhysicsServerSW::~PhysicsServerSW() {
+PhysicsServerSW::~PhysicsServerSW(){
};
-
-
diff --git a/servers/physics/physics_server_sw.h b/servers/physics/physics_server_sw.h
index 6e20474350..cb5a339ee8 100644
--- a/servers/physics/physics_server_sw.h
+++ b/servers/physics/physics_server_sw.h
@@ -29,19 +29,17 @@
#ifndef PHYSICS_SERVER_SW
#define PHYSICS_SERVER_SW
-
+#include "joints_sw.h"
#include "servers/physics_server.h"
#include "shape_sw.h"
#include "space_sw.h"
#include "step_sw.h"
-#include "joints_sw.h"
-
class PhysicsServerSW : public PhysicsServer {
- GDCLASS( PhysicsServerSW, PhysicsServer );
+ GDCLASS(PhysicsServerSW, PhysicsServer);
-friend class PhysicsDirectSpaceStateSW;
+ friend class PhysicsDirectSpaceStateSW;
bool active;
int iterations;
bool doing_sync;
@@ -52,7 +50,7 @@ friend class PhysicsDirectSpaceStateSW;
int collision_pairs;
StepSW *stepper;
- Set<const SpaceSW*> active_spaces;
+ Set<const SpaceSW *> active_spaces;
PhysicsDirectBodyStateSW *direct_state;
@@ -64,7 +62,6 @@ friend class PhysicsDirectSpaceStateSW;
//void _clear_query(QuerySW *p_query);
public:
-
struct CollCbkData {
int max;
@@ -72,10 +69,10 @@ public:
Vector3 *ptr;
};
- static void _shape_col_cbk(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata);
+ static void _shape_col_cbk(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata);
virtual RID shape_create(ShapeType p_shape);
- virtual void shape_set_data(RID p_shape, const Variant& p_data);
+ virtual void shape_set_data(RID p_shape, const Variant &p_data);
virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias);
virtual ShapeType shape_get_type(RID p_shape) const;
@@ -85,16 +82,16 @@ public:
/* SPACE API */
virtual RID space_create();
- virtual void space_set_active(RID p_space,bool p_active);
+ virtual void space_set_active(RID p_space, bool p_active);
virtual bool space_is_active(RID p_space) const;
- virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value);
- virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const;
+ virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value);
+ virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const;
// this function only works on fixed process, errors and returns null otherwise
- virtual PhysicsDirectSpaceState* space_get_direct_state(RID p_space);
+ virtual PhysicsDirectSpaceState *space_get_direct_state(RID p_space);
- virtual void space_set_debug_contacts(RID p_space,int p_max_contacts);
+ 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;
@@ -108,9 +105,9 @@ public:
virtual void area_set_space(RID p_area, RID p_space);
virtual RID area_get_space(RID p_area) const;
- virtual void area_add_shape(RID p_area, RID p_shape, const Transform& p_transform=Transform());
- 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 void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform());
+ 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;
@@ -119,31 +116,30 @@ public:
virtual void area_remove_shape(RID p_area, int p_shape_idx);
virtual void area_clear_shapes(RID p_area);
- virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID);
+ 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_set_param(RID p_area,AreaParameter p_param,const Variant& p_value);
- virtual void area_set_transform(RID p_area, const Transform& p_transform);
+ virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value);
+ virtual void area_set_transform(RID p_area, const Transform &p_transform);
- virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const;
+ virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const;
virtual Transform area_get_transform(RID p_area) const;
- virtual void area_set_ray_pickable(RID p_area,bool p_enable);
+ 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_collision_mask(RID p_area,uint32_t p_mask);
- virtual void area_set_layer_mask(RID p_area,uint32_t p_mask);
+ virtual void area_set_collision_mask(RID p_area, uint32_t p_mask);
+ virtual void area_set_layer_mask(RID p_area, uint32_t p_mask);
- 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_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);
/* BODY API */
// create a body of a given type
- 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);
virtual void body_set_space(RID p_body, RID p_space);
virtual RID body_get_space(RID p_body) const;
@@ -151,24 +147,24 @@ public:
virtual void body_set_mode(RID p_body, BodyMode p_mode);
virtual BodyMode body_get_mode(RID p_body) const;
- virtual void body_add_shape(RID p_body, RID p_shape, const Transform& p_transform=Transform());
- 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_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform());
+ 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 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 void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable);
+ virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable);
virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const;
virtual void body_remove_shape(RID p_body, int p_shape_idx);
virtual void body_clear_shapes(RID p_body);
- virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID);
+ virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID);
virtual uint32_t body_get_object_instance_ID(RID p_body) const;
- virtual void body_set_enable_continuous_collision_detection(RID p_body,bool p_enable);
+ 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_layer_mask(RID p_body, uint32_t p_mask);
@@ -183,20 +179,20 @@ public:
virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value);
virtual real_t body_get_param(RID p_body, BodyParameter p_param) const;
- virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant);
+ 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_applied_force(RID p_body, const Vector3& p_force);
+ 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_torque(RID p_body, const Vector3& p_torque);
+ 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_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_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_set_axis_lock(RID p_body,BodyAxisLock p_lock);
+ virtual void body_set_axis_lock(RID p_body, BodyAxisLock p_lock);
virtual BodyAxisLock body_get_axis_lock(RID p_body) const;
virtual void body_add_collision_exception(RID p_body, RID p_body_b);
@@ -206,61 +202,60 @@ public:
virtual void body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold);
virtual real_t body_get_contacts_reported_depth_treshold(RID p_body) const;
- virtual void body_set_omit_force_integration(RID p_body,bool p_omit);
+ 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_max_contacts_reported(RID p_body, int p_contacts);
virtual int body_get_max_contacts_reported(RID p_body) const;
- 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());
- virtual void body_set_ray_pickable(RID p_body,bool p_enable);
+ virtual void body_set_ray_pickable(RID p_body, bool p_enable);
virtual bool body_is_ray_pickable(RID p_body) const;
/* JOINT API */
- 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);
- virtual void pin_joint_set_param(RID p_joint,PinJointParam p_param, real_t p_value);
- virtual real_t pin_joint_get_param(RID p_joint,PinJointParam p_param) const;
+ virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value);
+ virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const;
- virtual void pin_joint_set_local_A(RID p_joint, const Vector3& p_A);
+ 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_B(RID p_joint, const Vector3& p_B);
+ 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 RID joint_create_hinge(RID p_body_A,const Transform& p_frame_A,RID p_body_B,const Transform& p_frame_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 void hinge_joint_set_param(RID p_joint,HingeJointParam p_param, real_t p_value);
- virtual real_t hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const;
+ virtual RID joint_create_hinge(RID p_body_A, const Transform &p_frame_A, RID p_body_B, const Transform &p_frame_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 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_param(RID p_joint, HingeJointParam p_param, real_t p_value);
+ virtual real_t hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const;
+ 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 RID joint_create_slider(RID p_body_A,const Transform& p_local_frame_A,RID p_body_B,const Transform& p_local_frame_B); //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); //reference frame is A
- virtual void slider_joint_set_param(RID p_joint,SliderJointParam p_param, real_t p_value);
- virtual real_t slider_joint_get_param(RID p_joint,SliderJointParam p_param) const;
+ virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, real_t p_value);
+ virtual real_t slider_joint_get_param(RID p_joint, SliderJointParam p_param) const;
- 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); //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); //reference frame is A
- virtual void cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, real_t p_value);
- virtual real_t 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, real_t p_value);
+ virtual real_t cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const;
- 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); //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); //reference frame is A
- virtual void generic_6dof_joint_set_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param, real_t p_value);
- virtual real_t generic_6dof_joint_get_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param);
+ virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param, real_t p_value);
+ virtual real_t generic_6dof_joint_get_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param);
- virtual void generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag, bool p_enable);
- virtual bool generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag);
+ virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag, bool p_enable);
+ virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag);
virtual JointType joint_get_type(RID p_joint) const;
- virtual void joint_set_solver_priority(RID p_joint,int p_priority);
+ virtual void joint_set_solver_priority(RID p_joint, int p_priority);
virtual int joint_get_solver_priority(RID p_joint) const;
#if 0
@@ -290,8 +285,6 @@ public:
PhysicsServerSW();
~PhysicsServerSW();
-
};
#endif
-
diff --git a/servers/physics/shape_sw.cpp b/servers/physics/shape_sw.cpp
index dec1c75d9f..4ce716c70a 100644
--- a/servers/physics/shape_sw.cpp
+++ b/servers/physics/shape_sw.cpp
@@ -28,100 +28,91 @@
/*************************************************************************/
#include "shape_sw.h"
#include "geometry.h"
-#include "sort.h"
#include "quick_hull.h"
+#include "sort.h"
#define _POINT_SNAP 0.001953125
#define _EDGE_IS_VALID_SUPPORT_TRESHOLD 0.0002
#define _FACE_IS_VALID_SUPPORT_TRESHOLD 0.9998
-
-void ShapeSW::configure(const Rect3& p_aabb) {
- aabb=p_aabb;
- configured=true;
- for (Map<ShapeOwnerSW*,int>::Element *E=owners.front();E;E=E->next()) {
- ShapeOwnerSW* co=(ShapeOwnerSW*)E->key();
+void ShapeSW::configure(const Rect3 &p_aabb) {
+ aabb = p_aabb;
+ configured = true;
+ for (Map<ShapeOwnerSW *, int>::Element *E = owners.front(); E; E = E->next()) {
+ ShapeOwnerSW *co = (ShapeOwnerSW *)E->key();
co->_shape_changed();
}
}
-
-Vector3 ShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 ShapeSW::get_support(const Vector3 &p_normal) const {
Vector3 res;
int amnt;
- get_supports(p_normal,1,&res,amnt);
+ get_supports(p_normal, 1, &res, amnt);
return res;
}
void ShapeSW::add_owner(ShapeOwnerSW *p_owner) {
- Map<ShapeOwnerSW*,int>::Element *E=owners.find(p_owner);
+ Map<ShapeOwnerSW *, int>::Element *E = owners.find(p_owner);
if (E) {
E->get()++;
} else {
- owners[p_owner]=1;
+ owners[p_owner] = 1;
}
}
-void ShapeSW::remove_owner(ShapeOwnerSW *p_owner){
+void ShapeSW::remove_owner(ShapeOwnerSW *p_owner) {
- Map<ShapeOwnerSW*,int>::Element *E=owners.find(p_owner);
+ Map<ShapeOwnerSW *, int>::Element *E = owners.find(p_owner);
ERR_FAIL_COND(!E);
E->get()--;
- if (E->get()==0) {
+ if (E->get() == 0) {
owners.erase(E);
}
-
}
-bool ShapeSW::is_owner(ShapeOwnerSW *p_owner) const{
+bool ShapeSW::is_owner(ShapeOwnerSW *p_owner) const {
return owners.has(p_owner);
-
}
-const Map<ShapeOwnerSW*,int>& ShapeSW::get_owners() const{
+const Map<ShapeOwnerSW *, int> &ShapeSW::get_owners() const {
return owners;
}
-
ShapeSW::ShapeSW() {
- custom_bias=0;
- configured=false;
+ custom_bias = 0;
+ configured = false;
}
-
ShapeSW::~ShapeSW() {
ERR_FAIL_COND(owners.size());
}
-
-
Plane PlaneShapeSW::get_plane() const {
return plane;
}
-void PlaneShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void PlaneShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
// gibberish, a plane is infinity
- r_min=-1e7;
- r_max=1e7;
+ r_min = -1e7;
+ r_max = 1e7;
}
-Vector3 PlaneShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 PlaneShapeSW::get_support(const Vector3 &p_normal) const {
- return p_normal*1e15;
+ return p_normal * 1e15;
}
+bool PlaneShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
-bool PlaneShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
-
- bool inters=plane.intersects_segment(p_begin,p_end,&r_result);
- if(inters)
- r_normal=plane.normal;
+ bool inters = plane.intersects_segment(p_begin, p_end, &r_result);
+ if (inters)
+ r_normal = plane.normal;
return inters;
}
@@ -130,16 +121,15 @@ Vector3 PlaneShapeSW::get_moment_of_inertia(real_t p_mass) const {
return Vector3(); //wtf
}
-void PlaneShapeSW::_setup(const Plane& p_plane) {
+void PlaneShapeSW::_setup(const Plane &p_plane) {
- plane=p_plane;
- configure(Rect3(Vector3(-1e4,-1e4,-1e4),Vector3(1e4*2,1e4*2,1e4*2)));
+ plane = p_plane;
+ configure(Rect3(Vector3(-1e4, -1e4, -1e4), Vector3(1e4 * 2, 1e4 * 2, 1e4 * 2)));
}
-void PlaneShapeSW::set_data(const Variant& p_data) {
+void PlaneShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
-
}
Variant PlaneShapeSW::get_data() const {
@@ -147,9 +137,7 @@ Variant PlaneShapeSW::get_data() const {
return plane;
}
-PlaneShapeSW::PlaneShapeSW() {
-
-
+PlaneShapeSW::PlaneShapeSW() {
}
//
@@ -159,39 +147,38 @@ real_t RayShapeSW::get_length() const {
return length;
}
-void RayShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void RayShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
// don't think this will be even used
- r_min=0;
- r_max=1;
+ r_min = 0;
+ r_max = 1;
}
-Vector3 RayShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 RayShapeSW::get_support(const Vector3 &p_normal) const {
- if (p_normal.z>0)
- return Vector3(0,0,length);
+ if (p_normal.z > 0)
+ return Vector3(0, 0, length);
else
- return Vector3(0,0,0);
+ return Vector3(0, 0, 0);
}
-void RayShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
+void RayShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
if (Math::abs(p_normal.z) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) {
- r_amount=2;
- r_supports[0]=Vector3(0,0,0);
- r_supports[1]=Vector3(0,0,length);
- } else if (p_normal.z>0) {
- r_amount=1;
- *r_supports=Vector3(0,0,length);
+ r_amount = 2;
+ r_supports[0] = Vector3(0, 0, 0);
+ r_supports[1] = Vector3(0, 0, length);
+ } else if (p_normal.z > 0) {
+ r_amount = 1;
+ *r_supports = Vector3(0, 0, length);
} else {
- r_amount=1;
- *r_supports=Vector3(0,0,0);
+ r_amount = 1;
+ *r_supports = Vector3(0, 0, 0);
}
}
-
-bool RayShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
+bool RayShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
return false; //simply not possible
}
@@ -201,16 +188,15 @@ Vector3 RayShapeSW::get_moment_of_inertia(real_t p_mass) const {
return Vector3();
}
-void RayShapeSW::_setup(real_t p_length) {
+void RayShapeSW::_setup(real_t p_length) {
- length=p_length;
- configure(Rect3(Vector3(0,0,0),Vector3(0.1,0.1,length)));
+ length = p_length;
+ configure(Rect3(Vector3(0, 0, 0), Vector3(0.1, 0.1, length)));
}
-void RayShapeSW::set_data(const Variant& p_data) {
+void RayShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
-
}
Variant RayShapeSW::get_data() const {
@@ -218,13 +204,11 @@ Variant RayShapeSW::get_data() const {
return length;
}
-RayShapeSW::RayShapeSW() {
+RayShapeSW::RayShapeSW() {
- length=1;
+ length = 1;
}
-
-
/********** SPHERE *************/
real_t SphereShapeSW::get_radius() const {
@@ -232,50 +216,47 @@ real_t SphereShapeSW::get_radius() const {
return radius;
}
-void SphereShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void SphereShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
- real_t d = p_normal.dot( p_transform.origin );
+ real_t d = p_normal.dot(p_transform.origin);
// figure out scale at point
Vector3 local_normal = p_transform.basis.xform_inv(p_normal);
real_t scale = local_normal.length();
- r_min = d - (radius) * scale;
- r_max = d + (radius) * scale;
-
+ r_min = d - (radius)*scale;
+ r_max = d + (radius)*scale;
}
-Vector3 SphereShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 SphereShapeSW::get_support(const Vector3 &p_normal) const {
- return p_normal*radius;
+ return p_normal * radius;
}
-void SphereShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
+void SphereShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
- *r_supports=p_normal*radius;
- r_amount=1;
+ *r_supports = p_normal * radius;
+ r_amount = 1;
}
-bool SphereShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
+bool SphereShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
- return Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(),radius,&r_result,&r_normal);
+ return Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(), radius, &r_result, &r_normal);
}
Vector3 SphereShapeSW::get_moment_of_inertia(real_t p_mass) const {
real_t s = 0.4 * p_mass * radius * radius;
- return Vector3(s,s,s);
+ return Vector3(s, s, s);
}
void SphereShapeSW::_setup(real_t p_radius) {
-
- radius=p_radius;
- configure(Rect3( Vector3(-radius,-radius,-radius), Vector3(radius*2.0,radius*2.0,radius*2.0)));
-
+ radius = p_radius;
+ configure(Rect3(Vector3(-radius, -radius, -radius), Vector3(radius * 2.0, radius * 2.0, radius * 2.0)));
}
-void SphereShapeSW::set_data(const Variant& p_data) {
+void SphereShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
}
@@ -287,113 +268,105 @@ Variant SphereShapeSW::get_data() const {
SphereShapeSW::SphereShapeSW() {
- radius=0;
+ radius = 0;
}
-
/********** BOX *************/
-
-void BoxShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void BoxShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
// no matter the angle, the box is mirrored anyway
- Vector3 local_normal=p_transform.basis.xform_inv(p_normal);
+ Vector3 local_normal = p_transform.basis.xform_inv(p_normal);
real_t length = local_normal.abs().dot(half_extents);
- real_t distance = p_normal.dot( p_transform.origin );
+ real_t distance = p_normal.dot(p_transform.origin);
r_min = distance - length;
r_max = distance + length;
-
-
}
-Vector3 BoxShapeSW::get_support(const Vector3& p_normal) const {
-
+Vector3 BoxShapeSW::get_support(const Vector3 &p_normal) const {
Vector3 point(
- (p_normal.x<0) ? -half_extents.x : half_extents.x,
- (p_normal.y<0) ? -half_extents.y : half_extents.y,
- (p_normal.z<0) ? -half_extents.z : half_extents.z
- );
+ (p_normal.x < 0) ? -half_extents.x : half_extents.x,
+ (p_normal.y < 0) ? -half_extents.y : half_extents.y,
+ (p_normal.z < 0) ? -half_extents.z : half_extents.z);
return point;
}
-void BoxShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
+void BoxShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
- static const int next[3]={1,2,0};
- static const int next2[3]={2,0,1};
+ static const int next[3] = { 1, 2, 0 };
+ static const int next2[3] = { 2, 0, 1 };
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1.0;
- real_t dot = p_normal.dot( axis );
- if ( Math::abs( dot ) > _FACE_IS_VALID_SUPPORT_TRESHOLD ) {
+ axis[i] = 1.0;
+ real_t dot = p_normal.dot(axis);
+ if (Math::abs(dot) > _FACE_IS_VALID_SUPPORT_TRESHOLD) {
//Vector3 axis_b;
- bool neg = dot<0;
+ bool neg = dot < 0;
r_amount = 4;
Vector3 point;
- point[i]=half_extents[i];
+ point[i] = half_extents[i];
- int i_n=next[i];
- int i_n2=next2[i];
+ int i_n = next[i];
+ int i_n2 = next2[i];
- static const real_t sign[4][2]={
+ static const real_t sign[4][2] = {
- {-1.0, 1.0},
- { 1.0, 1.0},
- { 1.0,-1.0},
- {-1.0,-1.0},
+ { -1.0, 1.0 },
+ { 1.0, 1.0 },
+ { 1.0, -1.0 },
+ { -1.0, -1.0 },
};
- for (int j=0;j<4;j++) {
-
- point[i_n]=sign[j][0]*half_extents[i_n];
- point[i_n2]=sign[j][1]*half_extents[i_n2];
- r_supports[j]=neg?-point:point;
+ for (int j = 0; j < 4; j++) {
+ point[i_n] = sign[j][0] * half_extents[i_n];
+ point[i_n2] = sign[j][1] * half_extents[i_n2];
+ r_supports[j] = neg ? -point : point;
}
if (neg) {
- SWAP( r_supports[1], r_supports[2] );
- SWAP( r_supports[0], r_supports[3] );
+ SWAP(r_supports[1], r_supports[2]);
+ SWAP(r_supports[0], r_supports[3]);
}
return;
}
- r_amount=0;
-
+ r_amount = 0;
}
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
Vector3 axis;
- axis[i]=1.0;
+ axis[i] = 1.0;
- if (Math::abs(p_normal.dot(axis))<_EDGE_IS_VALID_SUPPORT_TRESHOLD) {
+ if (Math::abs(p_normal.dot(axis)) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) {
- r_amount= 2;
+ r_amount = 2;
- int i_n=next[i];
- int i_n2=next2[i];
+ int i_n = next[i];
+ int i_n2 = next2[i];
- Vector3 point=half_extents;
+ Vector3 point = half_extents;
- if (p_normal[i_n]<0) {
- point[i_n]=-point[i_n];
+ if (p_normal[i_n] < 0) {
+ point[i_n] = -point[i_n];
}
- if (p_normal[i_n2]<0) {
- point[i_n2]=-point[i_n2];
+ if (p_normal[i_n2] < 0) {
+ point[i_n2] = -point[i_n2];
}
r_supports[0] = point;
- point[i]=-point[i];
+ point[i] = -point[i];
r_supports[1] = point;
return;
}
@@ -401,44 +374,38 @@ void BoxShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_suppo
/* USE POINT */
Vector3 point(
- (p_normal.x<0) ? -half_extents.x : half_extents.x,
- (p_normal.y<0) ? -half_extents.y : half_extents.y,
- (p_normal.z<0) ? -half_extents.z : half_extents.z
- );
+ (p_normal.x < 0) ? -half_extents.x : half_extents.x,
+ (p_normal.y < 0) ? -half_extents.y : half_extents.y,
+ (p_normal.z < 0) ? -half_extents.z : half_extents.z);
- r_amount=1;
- r_supports[0]=point;
+ r_amount = 1;
+ r_supports[0] = point;
}
-bool BoxShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
-
- Rect3 aabb(-half_extents,half_extents*2.0);
+bool BoxShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
- return aabb.intersects_segment(p_begin,p_end,&r_result,&r_normal);
+ Rect3 aabb(-half_extents, half_extents * 2.0);
+ return aabb.intersects_segment(p_begin, p_end, &r_result, &r_normal);
}
Vector3 BoxShapeSW::get_moment_of_inertia(real_t p_mass) const {
- real_t lx=half_extents.x;
- real_t ly=half_extents.y;
- real_t lz=half_extents.z;
-
- return Vector3( (p_mass/3.0) * (ly*ly + lz*lz), (p_mass/3.0) * (lx*lx + lz*lz), (p_mass/3.0) * (lx*lx + ly*ly) );
+ real_t lx = half_extents.x;
+ real_t ly = half_extents.y;
+ real_t lz = half_extents.z;
+ return Vector3((p_mass / 3.0) * (ly * ly + lz * lz), (p_mass / 3.0) * (lx * lx + lz * lz), (p_mass / 3.0) * (lx * lx + ly * ly));
}
-void BoxShapeSW::_setup(const Vector3& p_half_extents) {
-
- half_extents=p_half_extents.abs();
-
- configure(Rect3(-half_extents,half_extents*2));
+void BoxShapeSW::_setup(const Vector3 &p_half_extents) {
+ half_extents = p_half_extents.abs();
+ configure(Rect3(-half_extents, half_extents * 2));
}
-void BoxShapeSW::set_data(const Variant& p_data) {
-
+void BoxShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
}
@@ -448,138 +415,128 @@ Variant BoxShapeSW::get_data() const {
return half_extents;
}
-BoxShapeSW::BoxShapeSW() {
-
-
+BoxShapeSW::BoxShapeSW() {
}
-
/********** CAPSULE *************/
+void CapsuleShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
-void CapsuleShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
-
- Vector3 n=p_transform.basis.xform_inv(p_normal).normalized();
+ Vector3 n = p_transform.basis.xform_inv(p_normal).normalized();
real_t h = (n.z > 0) ? height : -height;
n *= radius;
n.z += h * 0.5;
- r_max=p_normal.dot(p_transform.xform(n));
- r_min=p_normal.dot(p_transform.xform(-n));
+ r_max = p_normal.dot(p_transform.xform(n));
+ r_min = p_normal.dot(p_transform.xform(-n));
return;
n = p_transform.basis.xform(n);
- real_t distance = p_normal.dot( p_transform.origin );
+ real_t distance = p_normal.dot(p_transform.origin);
real_t length = Math::abs(p_normal.dot(n));
r_min = distance - length;
r_max = distance + length;
- ERR_FAIL_COND( r_max < r_min );
-
+ ERR_FAIL_COND(r_max < r_min);
}
-Vector3 CapsuleShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 CapsuleShapeSW::get_support(const Vector3 &p_normal) const {
- Vector3 n=p_normal;
+ Vector3 n = p_normal;
real_t h = (n.z > 0) ? height : -height;
- n*=radius;
- n.z += h*0.5;
+ n *= radius;
+ n.z += h * 0.5;
return n;
}
-void CapsuleShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
-
+void CapsuleShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
- Vector3 n=p_normal;
+ Vector3 n = p_normal;
real_t d = n.z;
- if (Math::abs( d )<_EDGE_IS_VALID_SUPPORT_TRESHOLD ) {
+ if (Math::abs(d) < _EDGE_IS_VALID_SUPPORT_TRESHOLD) {
// make it flat
- n.z=0.0;
+ n.z = 0.0;
n.normalize();
- n*=radius;
+ n *= radius;
- r_amount=2;
- r_supports[0]=n;
- r_supports[0].z+=height*0.5;
- r_supports[1]=n;
- r_supports[1].z-=height*0.5;
+ r_amount = 2;
+ r_supports[0] = n;
+ r_supports[0].z += height * 0.5;
+ r_supports[1] = n;
+ r_supports[1].z -= height * 0.5;
} else {
real_t h = (d > 0) ? height : -height;
- n*=radius;
- n.z += h*0.5;
- r_amount=1;
- *r_supports=n;
-
+ n *= radius;
+ n.z += h * 0.5;
+ r_amount = 1;
+ *r_supports = n;
}
-
}
+bool CapsuleShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
-bool CapsuleShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
+ Vector3 norm = (p_end - p_begin).normalized();
+ real_t min_d = 1e20;
- Vector3 norm=(p_end-p_begin).normalized();
- real_t min_d=1e20;
+ Vector3 res, n;
+ bool collision = false;
-
- Vector3 res,n;
- bool collision=false;
-
- Vector3 auxres,auxn;
+ Vector3 auxres, auxn;
bool collided;
// test against cylinder and spheres :-|
- collided = Geometry::segment_intersects_cylinder(p_begin,p_end,height,radius,&auxres,&auxn);
+ collided = Geometry::segment_intersects_cylinder(p_begin, p_end, height, radius, &auxres, &auxn);
if (collided) {
- real_t d=norm.dot(auxres);
- if (d<min_d) {
- min_d=d;
- res=auxres;
- n=auxn;
- collision=true;
+ real_t d = norm.dot(auxres);
+ if (d < min_d) {
+ min_d = d;
+ res = auxres;
+ n = auxn;
+ collision = true;
}
}
- collided = Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(0,0,height*0.5),radius,&auxres,&auxn);
+ collided = Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(0, 0, height * 0.5), radius, &auxres, &auxn);
if (collided) {
- real_t d=norm.dot(auxres);
- if (d<min_d) {
- min_d=d;
- res=auxres;
- n=auxn;
- collision=true;
+ real_t d = norm.dot(auxres);
+ if (d < min_d) {
+ min_d = d;
+ res = auxres;
+ n = auxn;
+ collision = true;
}
}
- collided = Geometry::segment_intersects_sphere(p_begin,p_end,Vector3(0,0,height*-0.5),radius,&auxres,&auxn);
+ collided = Geometry::segment_intersects_sphere(p_begin, p_end, Vector3(0, 0, height * -0.5), radius, &auxres, &auxn);
if (collided) {
- real_t d=norm.dot(auxres);
+ real_t d = norm.dot(auxres);
- if (d<min_d) {
- min_d=d;
- res=auxres;
- n=auxn;
- collision=true;
+ if (d < min_d) {
+ min_d = d;
+ res = auxres;
+ n = auxn;
+ collision = true;
}
}
if (collision) {
- r_result=res;
- r_normal=n;
+ r_result = res;
+ r_normal = n;
}
return collision;
}
@@ -587,105 +544,90 @@ bool CapsuleShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_e
Vector3 CapsuleShapeSW::get_moment_of_inertia(real_t p_mass) const {
// use crappy AABB approximation
- Vector3 extents=get_aabb().size*0.5;
+ Vector3 extents = get_aabb().size * 0.5;
return Vector3(
- (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z),
- (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z),
- (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y)
- );
-
+ (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y));
}
+void CapsuleShapeSW::_setup(real_t p_height, real_t p_radius) {
-
-
-void CapsuleShapeSW::_setup(real_t p_height,real_t p_radius) {
-
- height=p_height;
- radius=p_radius;
- configure(Rect3(Vector3(-radius,-radius,-height*0.5-radius),Vector3(radius*2,radius*2,height+radius*2.0)));
-
+ height = p_height;
+ radius = p_radius;
+ configure(Rect3(Vector3(-radius, -radius, -height * 0.5 - radius), Vector3(radius * 2, radius * 2, height + radius * 2.0)));
}
-void CapsuleShapeSW::set_data(const Variant& p_data) {
+void CapsuleShapeSW::set_data(const Variant &p_data) {
Dictionary d = p_data;
ERR_FAIL_COND(!d.has("radius"));
ERR_FAIL_COND(!d.has("height"));
- _setup(d["height"],d["radius"]);
-
+ _setup(d["height"], d["radius"]);
}
Variant CapsuleShapeSW::get_data() const {
Dictionary d;
- d["radius"]=radius;
- d["height"]=height;
+ d["radius"] = radius;
+ d["height"] = height;
return d;
-
}
+CapsuleShapeSW::CapsuleShapeSW() {
-CapsuleShapeSW::CapsuleShapeSW() {
-
- height=radius=0;
-
+ height = radius = 0;
}
/********** CONVEX POLYGON *************/
+void ConvexPolygonShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
-void ConvexPolygonShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
-
-
- int vertex_count=mesh.vertices.size();
- if (vertex_count==0)
+ int vertex_count = mesh.vertices.size();
+ if (vertex_count == 0)
return;
- const Vector3 *vrts=&mesh.vertices[0];
+ const Vector3 *vrts = &mesh.vertices[0];
- for (int i=0;i<vertex_count;i++) {
+ for (int i = 0; i < vertex_count; i++) {
- real_t d=p_normal.dot( p_transform.xform( vrts[i] ) );
+ real_t d = p_normal.dot(p_transform.xform(vrts[i]));
- if (i==0 || d > r_max)
- r_max=d;
- if (i==0 || d < r_min)
- r_min=d;
+ if (i == 0 || d > r_max)
+ r_max = d;
+ if (i == 0 || d < r_min)
+ r_min = d;
}
}
-Vector3 ConvexPolygonShapeSW::get_support(const Vector3& p_normal) const {
+Vector3 ConvexPolygonShapeSW::get_support(const Vector3 &p_normal) const {
- Vector3 n=p_normal;
+ Vector3 n = p_normal;
- int vert_support_idx=-1;
+ int vert_support_idx = -1;
real_t support_max;
- int vertex_count=mesh.vertices.size();
- if (vertex_count==0)
+ int vertex_count = mesh.vertices.size();
+ if (vertex_count == 0)
return Vector3();
- const Vector3 *vrts=&mesh.vertices[0];
+ const Vector3 *vrts = &mesh.vertices[0];
- for (int i=0;i<vertex_count;i++) {
+ for (int i = 0; i < vertex_count; i++) {
- real_t d=n.dot(vrts[i]);
+ real_t d = n.dot(vrts[i]);
- if (i==0 || d > support_max) {
- support_max=d;
- vert_support_idx=i;
+ if (i == 0 || d > support_max) {
+ support_max = d;
+ vert_support_idx = i;
}
}
- return vrts[vert_support_idx];
-
+ return vrts[vert_support_idx];
}
-
-
-void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
+void ConvexPolygonShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
const Geometry::MeshData::Face *faces = mesh.faces.ptr();
int fc = mesh.faces.size();
@@ -700,28 +642,27 @@ void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector
real_t max;
int vtx;
- for (int i=0;i<vc;i++) {
+ for (int i = 0; i < vc; i++) {
- real_t d=p_normal.dot(vertices[i]);
+ real_t d = p_normal.dot(vertices[i]);
- if (i==0 || d > max) {
- max=d;
- vtx=i;
+ if (i == 0 || d > max) {
+ max = d;
+ vtx = i;
}
}
+ for (int i = 0; i < fc; i++) {
- for(int i=0;i<fc;i++) {
-
- if (faces[i].plane.normal.dot(p_normal)>_FACE_IS_VALID_SUPPORT_TRESHOLD) {
+ if (faces[i].plane.normal.dot(p_normal) > _FACE_IS_VALID_SUPPORT_TRESHOLD) {
int ic = faces[i].indices.size();
- const int *ind=faces[i].indices.ptr();
+ const int *ind = faces[i].indices.ptr();
- bool valid=false;
- for(int j=0;j<ic;j++) {
- if (ind[j]==vtx) {
- valid=true;
+ bool valid = false;
+ for (int j = 0; j < ic; j++) {
+ if (ind[j] == vtx) {
+ valid = true;
break;
}
}
@@ -729,114 +670,103 @@ void ConvexPolygonShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector
if (!valid)
continue;
- int m = MIN(p_max,ic);
- for(int j=0;j<m;j++) {
+ int m = MIN(p_max, ic);
+ for (int j = 0; j < m; j++) {
- r_supports[j]=vertices[ind[j]];
+ r_supports[j] = vertices[ind[j]];
}
- r_amount=m;
+ r_amount = m;
return;
}
}
- for(int i=0;i<ec;i++) {
+ for (int i = 0; i < ec; i++) {
+ real_t dot = (vertices[edges[i].a] - vertices[edges[i].b]).normalized().dot(p_normal);
+ dot = ABS(dot);
+ if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD && (edges[i].a == vtx || edges[i].b == vtx)) {
- real_t dot=(vertices[edges[i].a]-vertices[edges[i].b]).normalized().dot(p_normal);
- dot=ABS(dot);
- if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD && (edges[i].a==vtx || edges[i].b==vtx)) {
-
- r_amount=2;
- r_supports[0]=vertices[edges[i].a];
- r_supports[1]=vertices[edges[i].b];
+ r_amount = 2;
+ r_supports[0] = vertices[edges[i].a];
+ r_supports[1] = vertices[edges[i].b];
return;
}
}
-
- r_supports[0]=vertices[vtx];
- r_amount=1;
+ r_supports[0] = vertices[vtx];
+ r_amount = 1;
}
-bool ConvexPolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
-
-
+bool ConvexPolygonShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
const Geometry::MeshData::Face *faces = mesh.faces.ptr();
int fc = mesh.faces.size();
const Vector3 *vertices = mesh.vertices.ptr();
- Vector3 n = p_end-p_begin;
+ Vector3 n = p_end - p_begin;
real_t min = 1e20;
- bool col=false;
+ bool col = false;
- for(int i=0;i<fc;i++) {
+ for (int i = 0; i < fc; i++) {
if (faces[i].plane.normal.dot(n) > 0)
continue; //opposing face
int ic = faces[i].indices.size();
- const int *ind=faces[i].indices.ptr();
+ const int *ind = faces[i].indices.ptr();
- for(int j=1;j<ic-1;j++) {
+ for (int j = 1; j < ic - 1; j++) {
- Face3 f(vertices[ind[0]],vertices[ind[j]],vertices[ind[j+1]]);
+ Face3 f(vertices[ind[0]], vertices[ind[j]], vertices[ind[j + 1]]);
Vector3 result;
- if (f.intersects_segment(p_begin,p_end,&result)) {
+ if (f.intersects_segment(p_begin, p_end, &result)) {
real_t d = n.dot(result);
- if (d<min) {
- min=d;
- r_result=result;
- r_normal=faces[i].plane.normal;
- col=true;
+ if (d < min) {
+ min = d;
+ r_result = result;
+ r_normal = faces[i].plane.normal;
+ col = true;
}
break;
}
-
}
}
return col;
-
}
Vector3 ConvexPolygonShapeSW::get_moment_of_inertia(real_t p_mass) const {
// use crappy AABB approximation
- Vector3 extents=get_aabb().size*0.5;
-
- return Vector3(
- (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z),
- (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z),
- (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y)
- );
+ Vector3 extents = get_aabb().size * 0.5;
+ return Vector3(
+ (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y));
}
-void ConvexPolygonShapeSW::_setup(const Vector<Vector3>& p_vertices) {
+void ConvexPolygonShapeSW::_setup(const Vector<Vector3> &p_vertices) {
- Error err = QuickHull::build(p_vertices,mesh);
+ Error err = QuickHull::build(p_vertices, mesh);
Rect3 _aabb;
- for(int i=0;i<mesh.vertices.size();i++) {
+ for (int i = 0; i < mesh.vertices.size(); i++) {
- if (i==0)
- _aabb.pos=mesh.vertices[i];
+ if (i == 0)
+ _aabb.pos = mesh.vertices[i];
else
_aabb.expand_to(mesh.vertices[i]);
}
configure(_aabb);
-
-
}
-void ConvexPolygonShapeSW::set_data(const Variant& p_data) {
+void ConvexPolygonShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
-
}
Variant ConvexPolygonShapeSW::get_data() const {
@@ -844,113 +774,105 @@ Variant ConvexPolygonShapeSW::get_data() const {
return mesh.vertices;
}
-
-ConvexPolygonShapeSW::ConvexPolygonShapeSW() {
-
-
+ConvexPolygonShapeSW::ConvexPolygonShapeSW() {
}
-
/********** FACE POLYGON *************/
+void FaceShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
-void FaceShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+ for (int i = 0; i < 3; i++) {
- for (int i=0;i<3;i++) {
+ Vector3 v = p_transform.xform(vertex[i]);
+ real_t d = p_normal.dot(v);
- Vector3 v=p_transform.xform(vertex[i]);
- real_t d=p_normal.dot(v);
+ if (i == 0 || d > r_max)
+ r_max = d;
- if (i==0 || d > r_max)
- r_max=d;
-
- if (i==0 || d < r_min)
- r_min=d;
+ if (i == 0 || d < r_min)
+ r_min = d;
}
}
-Vector3 FaceShapeSW::get_support(const Vector3& p_normal) const {
-
+Vector3 FaceShapeSW::get_support(const Vector3 &p_normal) const {
- int vert_support_idx=-1;
+ int vert_support_idx = -1;
real_t support_max;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- real_t d=p_normal.dot(vertex[i]);
+ real_t d = p_normal.dot(vertex[i]);
- if (i==0 || d > support_max) {
- support_max=d;
- vert_support_idx=i;
+ if (i == 0 || d > support_max) {
+ support_max = d;
+ vert_support_idx = i;
}
}
return vertex[vert_support_idx];
}
-void FaceShapeSW::get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const {
+void FaceShapeSW::get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const {
- Vector3 n=p_normal;
+ Vector3 n = p_normal;
/** TEST FACE AS SUPPORT **/
if (normal.dot(n) > _FACE_IS_VALID_SUPPORT_TRESHOLD) {
- r_amount=3;
- for (int i=0;i<3;i++) {
+ r_amount = 3;
+ for (int i = 0; i < 3; i++) {
- r_supports[i]=vertex[i];
+ r_supports[i] = vertex[i];
}
return;
-
}
/** FIND SUPPORT VERTEX **/
- int vert_support_idx=-1;
+ int vert_support_idx = -1;
real_t support_max;
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- real_t d=n.dot(vertex[i]);
+ real_t d = n.dot(vertex[i]);
- if (i==0 || d > support_max) {
- support_max=d;
- vert_support_idx=i;
+ if (i == 0 || d > support_max) {
+ support_max = d;
+ vert_support_idx = i;
}
}
/** TEST EDGES AS SUPPORT **/
- for (int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- int nx=(i+1)%3;
- if (i!=vert_support_idx && nx!=vert_support_idx)
+ int nx = (i + 1) % 3;
+ if (i != vert_support_idx && nx != vert_support_idx)
continue;
- // check if edge is valid as a support
- real_t dot=(vertex[i]-vertex[nx]).normalized().dot(n);
- dot=ABS(dot);
+ // check if edge is valid as a support
+ real_t dot = (vertex[i] - vertex[nx]).normalized().dot(n);
+ dot = ABS(dot);
if (dot < _EDGE_IS_VALID_SUPPORT_TRESHOLD) {
- r_amount=2;
- r_supports[0]=vertex[i];
- r_supports[1]=vertex[nx];
+ r_amount = 2;
+ r_supports[0] = vertex[i];
+ r_supports[1] = vertex[nx];
return;
}
}
- r_amount=1;
- r_supports[0]=vertex[vert_support_idx];
+ r_amount = 1;
+ r_supports[0] = vertex[vert_support_idx];
}
-bool FaceShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
+bool FaceShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
-
- bool c=Geometry::segment_intersects_triangle(p_begin,p_end,vertex[0],vertex[1],vertex[2],&r_result);
+ bool c = Geometry::segment_intersects_triangle(p_begin, p_end, vertex[0], vertex[1], vertex[2], &r_result);
if (c) {
- r_normal=Plane(vertex[0],vertex[1],vertex[2]).normal;
- if (r_normal.dot(p_end-p_begin)>0) {
- r_normal=-r_normal;
+ r_normal = Plane(vertex[0], vertex[1], vertex[2]).normal;
+ if (r_normal.dot(p_end - p_begin) > 0) {
+ r_normal = -r_normal;
}
}
@@ -960,183 +882,162 @@ bool FaceShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,
Vector3 FaceShapeSW::get_moment_of_inertia(real_t p_mass) const {
return Vector3(); // Sorry, but i don't think anyone cares, FaceShape!
-
}
-FaceShapeSW::FaceShapeSW() {
+FaceShapeSW::FaceShapeSW() {
configure(Rect3());
-
}
-
-
PoolVector<Vector3> ConcavePolygonShapeSW::get_faces() const {
-
PoolVector<Vector3> rfaces;
- rfaces.resize(faces.size()*3);
+ rfaces.resize(faces.size() * 3);
- for(int i=0;i<faces.size();i++) {
+ for (int i = 0; i < faces.size(); i++) {
- Face f=faces.get(i);
+ Face f = faces.get(i);
- for(int j=0;j<3;j++) {
+ for (int j = 0; j < 3; j++) {
- rfaces.set(i*3+j, vertices.get( f.indices[j] ) );
+ rfaces.set(i * 3 + j, vertices.get(f.indices[j]));
}
}
return rfaces;
}
-void ConcavePolygonShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void ConcavePolygonShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
- int count=vertices.size();
- if (count==0) {
- r_min=0;
- r_max=0;
+ int count = vertices.size();
+ if (count == 0) {
+ r_min = 0;
+ r_max = 0;
return;
}
- PoolVector<Vector3>::Read r=vertices.read();
- const Vector3 *vptr=r.ptr();
+ PoolVector<Vector3>::Read r = vertices.read();
+ const Vector3 *vptr = r.ptr();
- for (int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- real_t d=p_normal.dot( p_transform.xform( vptr[i] ) );
-
- if (i==0 || d > r_max)
- r_max=d;
- if (i==0 || d < r_min)
- r_min=d;
+ real_t d = p_normal.dot(p_transform.xform(vptr[i]));
+ if (i == 0 || d > r_max)
+ r_max = d;
+ if (i == 0 || d < r_min)
+ r_min = d;
}
}
-Vector3 ConcavePolygonShapeSW::get_support(const Vector3& p_normal) const {
-
+Vector3 ConcavePolygonShapeSW::get_support(const Vector3 &p_normal) const {
- int count=vertices.size();
- if (count==0)
+ int count = vertices.size();
+ if (count == 0)
return Vector3();
- PoolVector<Vector3>::Read r=vertices.read();
- const Vector3 *vptr=r.ptr();
+ PoolVector<Vector3>::Read r = vertices.read();
+ const Vector3 *vptr = r.ptr();
- Vector3 n=p_normal;
+ Vector3 n = p_normal;
- int vert_support_idx=-1;
+ int vert_support_idx = -1;
real_t support_max;
- for (int i=0;i<count;i++) {
+ for (int i = 0; i < count; i++) {
- real_t d=n.dot(vptr[i]);
+ real_t d = n.dot(vptr[i]);
- if (i==0 || d > support_max) {
- support_max=d;
- vert_support_idx=i;
+ if (i == 0 || d > support_max) {
+ support_max = d;
+ vert_support_idx = i;
}
}
-
return vptr[vert_support_idx];
-
}
-void ConcavePolygonShapeSW::_cull_segment(int p_idx,_SegmentCullParams *p_params) const {
-
- const BVH *bvh=&p_params->bvh[p_idx];
+void ConcavePolygonShapeSW::_cull_segment(int p_idx, _SegmentCullParams *p_params) const {
+ const BVH *bvh = &p_params->bvh[p_idx];
/*
if (p_params->dir.dot(bvh->aabb.get_support(-p_params->dir))>p_params->min_d)
return; //test against whole AABB, which isn't very costly
*/
-
//printf("addr: %p\n",bvh);
- if (!bvh->aabb.intersects_segment(p_params->from,p_params->to)) {
+ if (!bvh->aabb.intersects_segment(p_params->from, p_params->to)) {
return;
}
-
- if (bvh->face_index>=0) {
-
+ if (bvh->face_index >= 0) {
Vector3 res;
- Vector3 vertices[3]={
- p_params->vertices[ p_params->faces[ bvh->face_index ].indices[0] ],
- p_params->vertices[ p_params->faces[ bvh->face_index ].indices[1] ],
- p_params->vertices[ p_params->faces[ bvh->face_index ].indices[2] ]
+ Vector3 vertices[3] = {
+ p_params->vertices[p_params->faces[bvh->face_index].indices[0]],
+ p_params->vertices[p_params->faces[bvh->face_index].indices[1]],
+ p_params->vertices[p_params->faces[bvh->face_index].indices[2]]
};
if (Geometry::segment_intersects_triangle(
- p_params->from,
- p_params->to,
- vertices[0],
- vertices[1],
- vertices[2],
- &res)) {
-
-
- real_t d=p_params->dir.dot(res) - p_params->dir.dot(p_params->from);
+ p_params->from,
+ p_params->to,
+ vertices[0],
+ vertices[1],
+ vertices[2],
+ &res)) {
+
+ real_t d = p_params->dir.dot(res) - p_params->dir.dot(p_params->from);
//TODO, seems segmen/triangle intersection is broken :(
- if (d>0 && d<p_params->min_d) {
+ if (d > 0 && d < p_params->min_d) {
- p_params->min_d=d;
- p_params->result=res;
- p_params->normal=Plane(vertices[0],vertices[1],vertices[2]).normal;
- if (p_params->normal.dot(p_params->dir)>0)
- p_params->normal=-p_params->normal;
+ p_params->min_d = d;
+ p_params->result = res;
+ p_params->normal = Plane(vertices[0], vertices[1], vertices[2]).normal;
+ if (p_params->normal.dot(p_params->dir) > 0)
+ p_params->normal = -p_params->normal;
p_params->collisions++;
}
-
}
-
-
} else {
- if (bvh->left>=0)
- _cull_segment(bvh->left,p_params);
- if (bvh->right>=0)
- _cull_segment(bvh->right,p_params);
-
-
+ if (bvh->left >= 0)
+ _cull_segment(bvh->left, p_params);
+ if (bvh->right >= 0)
+ _cull_segment(bvh->right, p_params);
}
}
-bool ConcavePolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const {
+bool ConcavePolygonShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const {
- if (faces.size()==0)
+ if (faces.size() == 0)
return false;
// unlock data
- PoolVector<Face>::Read fr=faces.read();
- PoolVector<Vector3>::Read vr=vertices.read();
- PoolVector<BVH>::Read br=bvh.read();
-
+ PoolVector<Face>::Read fr = faces.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
+ PoolVector<BVH>::Read br = bvh.read();
_SegmentCullParams params;
- params.from=p_begin;
- params.to=p_end;
- params.collisions=0;
- params.dir=(p_end-p_begin).normalized();
+ params.from = p_begin;
+ params.to = p_end;
+ params.collisions = 0;
+ params.dir = (p_end - p_begin).normalized();
- params.faces=fr.ptr();
- params.vertices=vr.ptr();
- params.bvh=br.ptr();
+ params.faces = fr.ptr();
+ params.vertices = vr.ptr();
+ params.bvh = br.ptr();
- params.min_d=1e20;
+ params.min_d = 1e20;
// cull
- _cull_segment(0,&params);
-
- if (params.collisions>0) {
+ _cull_segment(0, &params);
+ if (params.collisions > 0) {
- r_result=params.result;
- r_normal=params.normal;
+ r_result = params.result;
+ r_normal = params.normal;
return true;
} else {
@@ -1144,81 +1045,76 @@ bool ConcavePolygonShapeSW::intersect_segment(const Vector3& p_begin,const Vecto
}
}
-void ConcavePolygonShapeSW::_cull(int p_idx,_CullParams *p_params) const {
+void ConcavePolygonShapeSW::_cull(int p_idx, _CullParams *p_params) const {
- const BVH* bvh=&p_params->bvh[p_idx];
+ const BVH *bvh = &p_params->bvh[p_idx];
- if (!p_params->aabb.intersects( bvh->aabb ))
+ if (!p_params->aabb.intersects(bvh->aabb))
return;
- if (bvh->face_index>=0) {
+ if (bvh->face_index >= 0) {
- const Face *f=&p_params->faces[ bvh->face_index ];
- FaceShapeSW *face=p_params->face;
- face->normal=f->normal;
- face->vertex[0]=p_params->vertices[f->indices[0]];
- face->vertex[1]=p_params->vertices[f->indices[1]];
- face->vertex[2]=p_params->vertices[f->indices[2]];
- p_params->callback(p_params->userdata,face);
+ const Face *f = &p_params->faces[bvh->face_index];
+ FaceShapeSW *face = p_params->face;
+ face->normal = f->normal;
+ face->vertex[0] = p_params->vertices[f->indices[0]];
+ face->vertex[1] = p_params->vertices[f->indices[1]];
+ face->vertex[2] = p_params->vertices[f->indices[2]];
+ p_params->callback(p_params->userdata, face);
} else {
- if (bvh->left>=0) {
-
- _cull(bvh->left,p_params);
+ if (bvh->left >= 0) {
+ _cull(bvh->left, p_params);
}
- if (bvh->right>=0) {
+ if (bvh->right >= 0) {
- _cull(bvh->right,p_params);
+ _cull(bvh->right, p_params);
}
-
}
}
-void ConcavePolygonShapeSW::cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const {
+void ConcavePolygonShapeSW::cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const {
// make matrix local to concave
- if (faces.size()==0)
+ if (faces.size() == 0)
return;
- Rect3 local_aabb=p_local_aabb;
+ Rect3 local_aabb = p_local_aabb;
// unlock data
- PoolVector<Face>::Read fr=faces.read();
- PoolVector<Vector3>::Read vr=vertices.read();
- PoolVector<BVH>::Read br=bvh.read();
+ PoolVector<Face>::Read fr = faces.read();
+ PoolVector<Vector3>::Read vr = vertices.read();
+ PoolVector<BVH>::Read br = bvh.read();
FaceShapeSW face; // use this to send in the callback
_CullParams params;
- params.aabb=local_aabb;
- params.face=&face;
- params.faces=fr.ptr();
- params.vertices=vr.ptr();
- params.bvh=br.ptr();
- params.callback=p_callback;
- params.userdata=p_userdata;
+ params.aabb = local_aabb;
+ params.face = &face;
+ params.faces = fr.ptr();
+ params.vertices = vr.ptr();
+ params.bvh = br.ptr();
+ params.callback = p_callback;
+ params.userdata = p_userdata;
// cull
- _cull(0,&params);
-
+ _cull(0, &params);
}
Vector3 ConcavePolygonShapeSW::get_moment_of_inertia(real_t p_mass) const {
// use crappy AABB approximation
- Vector3 extents=get_aabb().size*0.5;
+ Vector3 extents = get_aabb().size * 0.5;
return Vector3(
- (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z),
- (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z),
- (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y)
- );
+ (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y));
}
-
struct _VolumeSW_BVH_Element {
Rect3 aabb;
@@ -1228,26 +1124,25 @@ struct _VolumeSW_BVH_Element {
struct _VolumeSW_BVH_CompareX {
- _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const {
+ _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const {
- return a.center.x<b.center.x;
+ return a.center.x < b.center.x;
}
};
-
struct _VolumeSW_BVH_CompareY {
- _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const {
+ _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const {
- return a.center.y<b.center.y;
+ return a.center.y < b.center.y;
}
};
struct _VolumeSW_BVH_CompareZ {
- _FORCE_INLINE_ bool operator ()(const _VolumeSW_BVH_Element& a, const _VolumeSW_BVH_Element& b) const {
+ _FORCE_INLINE_ bool operator()(const _VolumeSW_BVH_Element &a, const _VolumeSW_BVH_Element &b) const {
- return a.center.z<b.center.z;
+ return a.center.z < b.center.z;
}
};
@@ -1260,107 +1155,102 @@ struct _VolumeSW_BVH {
int face_index;
};
+_VolumeSW_BVH *_volume_sw_build_bvh(_VolumeSW_BVH_Element *p_elements, int p_size, int &count) {
-_VolumeSW_BVH* _volume_sw_build_bvh(_VolumeSW_BVH_Element *p_elements,int p_size,int &count) {
-
- _VolumeSW_BVH* bvh = memnew( _VolumeSW_BVH );
+ _VolumeSW_BVH *bvh = memnew(_VolumeSW_BVH);
- if (p_size==1) {
+ if (p_size == 1) {
//leaf
- bvh->aabb=p_elements[0].aabb;
- bvh->left=NULL;
- bvh->right=NULL;
- bvh->face_index=p_elements->face_index;
+ bvh->aabb = p_elements[0].aabb;
+ bvh->left = NULL;
+ bvh->right = NULL;
+ bvh->face_index = p_elements->face_index;
count++;
return bvh;
} else {
- bvh->face_index=-1;
+ bvh->face_index = -1;
}
Rect3 aabb;
- for(int i=0;i<p_size;i++) {
+ for (int i = 0; i < p_size; i++) {
- if (i==0)
- aabb=p_elements[i].aabb;
+ if (i == 0)
+ aabb = p_elements[i].aabb;
else
aabb.merge_with(p_elements[i].aabb);
}
- bvh->aabb=aabb;
- switch(aabb.get_longest_axis_index()) {
+ bvh->aabb = aabb;
+ switch (aabb.get_longest_axis_index()) {
case 0: {
- SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareX> sort_x;
- sort_x.sort(p_elements,p_size);
+ SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareX> sort_x;
+ sort_x.sort(p_elements, p_size);
} break;
case 1: {
- SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareY> sort_y;
- sort_y.sort(p_elements,p_size);
+ SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareY> sort_y;
+ sort_y.sort(p_elements, p_size);
} break;
case 2: {
- SortArray<_VolumeSW_BVH_Element,_VolumeSW_BVH_CompareZ> sort_z;
- sort_z.sort(p_elements,p_size);
+ SortArray<_VolumeSW_BVH_Element, _VolumeSW_BVH_CompareZ> sort_z;
+ sort_z.sort(p_elements, p_size);
} break;
}
- int split=p_size/2;
- bvh->left=_volume_sw_build_bvh(p_elements,split,count);
- bvh->right=_volume_sw_build_bvh(&p_elements[split],p_size-split,count);
+ int split = p_size / 2;
+ bvh->left = _volume_sw_build_bvh(p_elements, split, count);
+ bvh->right = _volume_sw_build_bvh(&p_elements[split], p_size - split, count);
//printf("branch at %p - %i: %i\n",bvh,count,bvh->face_index);
count++;
return bvh;
}
+void ConcavePolygonShapeSW::_fill_bvh(_VolumeSW_BVH *p_bvh_tree, BVH *p_bvh_array, int &p_idx) {
-void ConcavePolygonShapeSW::_fill_bvh(_VolumeSW_BVH* p_bvh_tree,BVH* p_bvh_array,int& p_idx) {
-
- int idx=p_idx;
-
+ int idx = p_idx;
- p_bvh_array[idx].aabb=p_bvh_tree->aabb;
- p_bvh_array[idx].face_index=p_bvh_tree->face_index;
+ p_bvh_array[idx].aabb = p_bvh_tree->aabb;
+ p_bvh_array[idx].face_index = p_bvh_tree->face_index;
//printf("%p - %i: %i(%p) -- %p:%p\n",%p_bvh_array[idx],p_idx,p_bvh_array[i]->face_index,&p_bvh_tree->face_index,p_bvh_tree->left,p_bvh_tree->right);
-
if (p_bvh_tree->left) {
- p_bvh_array[idx].left=++p_idx;
- _fill_bvh(p_bvh_tree->left,p_bvh_array,p_idx);
+ p_bvh_array[idx].left = ++p_idx;
+ _fill_bvh(p_bvh_tree->left, p_bvh_array, p_idx);
} else {
- p_bvh_array[p_idx].left=-1;
+ p_bvh_array[p_idx].left = -1;
}
if (p_bvh_tree->right) {
- p_bvh_array[idx].right=++p_idx;
- _fill_bvh(p_bvh_tree->right,p_bvh_array,p_idx);
+ p_bvh_array[idx].right = ++p_idx;
+ _fill_bvh(p_bvh_tree->right, p_bvh_array, p_idx);
} else {
- p_bvh_array[p_idx].right=-1;
+ p_bvh_array[p_idx].right = -1;
}
memdelete(p_bvh_tree);
-
}
void ConcavePolygonShapeSW::_setup(PoolVector<Vector3> p_faces) {
- int src_face_count=p_faces.size();
- if (src_face_count==0) {
+ int src_face_count = p_faces.size();
+ if (src_face_count == 0) {
configure(Rect3());
return;
}
- ERR_FAIL_COND(src_face_count%3);
- src_face_count/=3;
+ ERR_FAIL_COND(src_face_count % 3);
+ src_face_count /= 3;
PoolVector<Vector3>::Read r = p_faces.read();
- const Vector3 * facesr= r.ptr();
+ const Vector3 *facesr = r.ptr();
#if 0
Map<Vector3,int> point_map;
@@ -1476,67 +1366,62 @@ void ConcavePolygonShapeSW::_setup(PoolVector<Vector3> p_faces) {
#else
PoolVector<_VolumeSW_BVH_Element> bvh_array;
- bvh_array.resize( src_face_count );
+ bvh_array.resize(src_face_count);
PoolVector<_VolumeSW_BVH_Element>::Write bvhw = bvh_array.write();
- _VolumeSW_BVH_Element *bvh_arrayw=bvhw.ptr();
+ _VolumeSW_BVH_Element *bvh_arrayw = bvhw.ptr();
faces.resize(src_face_count);
PoolVector<Face>::Write w = faces.write();
- Face *facesw=w.ptr();
+ Face *facesw = w.ptr();
- vertices.resize( src_face_count*3 );
+ vertices.resize(src_face_count * 3);
PoolVector<Vector3>::Write vw = vertices.write();
- Vector3 *verticesw=vw.ptr();
+ Vector3 *verticesw = vw.ptr();
Rect3 _aabb;
+ for (int i = 0; i < src_face_count; i++) {
- for(int i=0;i<src_face_count;i++) {
-
- Face3 face( facesr[i*3+0], facesr[i*3+1], facesr[i*3+2] );
+ Face3 face(facesr[i * 3 + 0], facesr[i * 3 + 1], facesr[i * 3 + 2]);
- bvh_arrayw[i].aabb=face.get_aabb();
+ bvh_arrayw[i].aabb = face.get_aabb();
bvh_arrayw[i].center = bvh_arrayw[i].aabb.pos + bvh_arrayw[i].aabb.size * 0.5;
- bvh_arrayw[i].face_index=i;
- facesw[i].indices[0]=i*3+0;
- facesw[i].indices[1]=i*3+1;
- facesw[i].indices[2]=i*3+2;
- facesw[i].normal=face.get_plane().normal;
- verticesw[i*3+0]=face.vertex[0];
- verticesw[i*3+1]=face.vertex[1];
- verticesw[i*3+2]=face.vertex[2];
- if (i==0)
- _aabb=bvh_arrayw[i].aabb;
+ bvh_arrayw[i].face_index = i;
+ facesw[i].indices[0] = i * 3 + 0;
+ facesw[i].indices[1] = i * 3 + 1;
+ facesw[i].indices[2] = i * 3 + 2;
+ facesw[i].normal = face.get_plane().normal;
+ verticesw[i * 3 + 0] = face.vertex[0];
+ verticesw[i * 3 + 1] = face.vertex[1];
+ verticesw[i * 3 + 2] = face.vertex[2];
+ if (i == 0)
+ _aabb = bvh_arrayw[i].aabb;
else
_aabb.merge_with(bvh_arrayw[i].aabb);
-
}
- w=PoolVector<Face>::Write();
- vw=PoolVector<Vector3>::Write();
+ w = PoolVector<Face>::Write();
+ vw = PoolVector<Vector3>::Write();
- int count=0;
- _VolumeSW_BVH *bvh_tree=_volume_sw_build_bvh(bvh_arrayw,src_face_count,count);
+ int count = 0;
+ _VolumeSW_BVH *bvh_tree = _volume_sw_build_bvh(bvh_arrayw, src_face_count, count);
- bvh.resize( count+1 );
+ bvh.resize(count + 1);
PoolVector<BVH>::Write bvhw2 = bvh.write();
- BVH*bvh_arrayw2=bvhw2.ptr();
+ BVH *bvh_arrayw2 = bvhw2.ptr();
- int idx=0;
- _fill_bvh(bvh_tree,bvh_arrayw2,idx);
+ int idx = 0;
+ _fill_bvh(bvh_tree, bvh_arrayw2, idx);
configure(_aabb); // this type of shape has no margin
-
#endif
}
-
-void ConcavePolygonShapeSW::set_data(const Variant& p_data) {
-
+void ConcavePolygonShapeSW::set_data(const Variant &p_data) {
_setup(p_data);
}
@@ -1547,12 +1432,8 @@ Variant ConcavePolygonShapeSW::get_data() const {
}
ConcavePolygonShapeSW::ConcavePolygonShapeSW() {
-
-
}
-
-
/* HEIGHT MAP SHAPE */
PoolVector<real_t> HeightMapShapeSW::get_heights() const {
@@ -1572,114 +1453,94 @@ real_t HeightMapShapeSW::get_cell_size() const {
return cell_size;
}
-
-void HeightMapShapeSW::project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+void HeightMapShapeSW::project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
//not very useful, but not very used either
- p_transform.xform(get_aabb()).project_range_in_plane( Plane(p_normal,0),r_min,r_max );
-
+ p_transform.xform(get_aabb()).project_range_in_plane(Plane(p_normal, 0), r_min, r_max);
}
-Vector3 HeightMapShapeSW::get_support(const Vector3& p_normal) const {
-
+Vector3 HeightMapShapeSW::get_support(const Vector3 &p_normal) const {
//not very useful, but not very used either
return get_aabb().get_support(p_normal);
-
}
-bool HeightMapShapeSW::intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const {
-
+bool HeightMapShapeSW::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const {
return false;
}
-
-void HeightMapShapeSW::cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const {
-
-
-
+void HeightMapShapeSW::cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const {
}
-
Vector3 HeightMapShapeSW::get_moment_of_inertia(real_t p_mass) const {
-
// use crappy AABB approximation
- Vector3 extents=get_aabb().size*0.5;
+ Vector3 extents = get_aabb().size * 0.5;
return Vector3(
- (p_mass/3.0) * (extents.y*extents.y + extents.z*extents.z),
- (p_mass/3.0) * (extents.x*extents.x + extents.z*extents.z),
- (p_mass/3.0) * (extents.y*extents.y + extents.y*extents.y)
- );
+ (p_mass / 3.0) * (extents.y * extents.y + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.x * extents.x + extents.z * extents.z),
+ (p_mass / 3.0) * (extents.y * extents.y + extents.y * extents.y));
}
+void HeightMapShapeSW::_setup(PoolVector<real_t> p_heights, int p_width, int p_depth, real_t p_cell_size) {
-void HeightMapShapeSW::_setup(PoolVector<real_t> p_heights,int p_width,int p_depth,real_t p_cell_size) {
+ heights = p_heights;
+ width = p_width;
+ depth = p_depth;
+ cell_size = p_cell_size;
- heights=p_heights;
- width=p_width;
- depth=p_depth;
- cell_size=p_cell_size;
-
- PoolVector<real_t>::Read r = heights. read();
+ PoolVector<real_t>::Read r = heights.read();
Rect3 aabb;
- for(int i=0;i<depth;i++) {
+ for (int i = 0; i < depth; i++) {
- for(int j=0;j<width;j++) {
+ for (int j = 0; j < width; j++) {
- real_t h = r[i*width+j];
+ real_t h = r[i * width + j];
- Vector3 pos( j*cell_size, h, i*cell_size );
- if (i==0 || j==0)
- aabb.pos=pos;
+ Vector3 pos(j * cell_size, h, i * cell_size);
+ if (i == 0 || j == 0)
+ aabb.pos = pos;
else
aabb.expand_to(pos);
-
}
}
-
configure(aabb);
}
-void HeightMapShapeSW::set_data(const Variant& p_data) {
+void HeightMapShapeSW::set_data(const Variant &p_data) {
- ERR_FAIL_COND( p_data.get_type()!=Variant::DICTIONARY );
- Dictionary d=p_data;
- ERR_FAIL_COND( !d.has("width") );
- ERR_FAIL_COND( !d.has("depth") );
- ERR_FAIL_COND( !d.has("cell_size") );
- ERR_FAIL_COND( !d.has("heights") );
-
- int width=d["width"];
- int depth=d["depth"];
- real_t cell_size=d["cell_size"];
- PoolVector<real_t> heights=d["heights"];
+ ERR_FAIL_COND(p_data.get_type() != Variant::DICTIONARY);
+ Dictionary d = p_data;
+ ERR_FAIL_COND(!d.has("width"));
+ ERR_FAIL_COND(!d.has("depth"));
+ ERR_FAIL_COND(!d.has("cell_size"));
+ ERR_FAIL_COND(!d.has("heights"));
- ERR_FAIL_COND( width<= 0);
- ERR_FAIL_COND( depth<= 0);
- ERR_FAIL_COND( cell_size<= CMP_EPSILON);
- ERR_FAIL_COND( heights.size() != (width*depth) );
- _setup(heights, width, depth, cell_size );
+ int width = d["width"];
+ int depth = d["depth"];
+ real_t cell_size = d["cell_size"];
+ PoolVector<real_t> heights = d["heights"];
+ ERR_FAIL_COND(width <= 0);
+ ERR_FAIL_COND(depth <= 0);
+ ERR_FAIL_COND(cell_size <= CMP_EPSILON);
+ ERR_FAIL_COND(heights.size() != (width * depth));
+ _setup(heights, width, depth, cell_size);
}
Variant HeightMapShapeSW::get_data() const {
ERR_FAIL_V(Variant());
-
}
HeightMapShapeSW::HeightMapShapeSW() {
- width=0;
- depth=0;
- cell_size=0;
+ width = 0;
+ depth = 0;
+ cell_size = 0;
}
-
-
-
diff --git a/servers/physics/shape_sw.h b/servers/physics/shape_sw.h
index 55daa5856d..442cbc39eb 100644
--- a/servers/physics/shape_sw.h
+++ b/servers/physics/shape_sw.h
@@ -29,9 +29,9 @@
#ifndef SHAPE_SW_H
#define SHAPE_SW_H
-#include "servers/physics_server.h"
#include "bsp_tree.h"
#include "geometry.h"
+#include "servers/physics_server.h"
/*
SHAPE_LINE, ///< plane:"plane"
@@ -46,16 +46,14 @@ SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_creat
class ShapeSW;
-class ShapeOwnerSW : public RID_Data {
+class ShapeOwnerSW : public RID_Data {
public:
-
- virtual void _shape_changed()=0;
- virtual void remove_shape(ShapeSW *p_shape)=0;
+ virtual void _shape_changed() = 0;
+ virtual void remove_shape(ShapeSW *p_shape) = 0;
virtual ~ShapeOwnerSW() {}
};
-
class ShapeSW : public RID_Data {
RID self;
@@ -63,60 +61,58 @@ class ShapeSW : public RID_Data {
bool configured;
real_t custom_bias;
- Map<ShapeOwnerSW*,int> owners;
+ Map<ShapeOwnerSW *, int> owners;
+
protected:
+ void configure(const Rect3 &p_aabb);
- void configure(const Rect3& p_aabb);
public:
-
enum {
- MAX_SUPPORTS=8
+ MAX_SUPPORTS = 8
};
- virtual real_t get_area() const { return aabb.get_area();}
+ virtual real_t get_area() const { return aabb.get_area(); }
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
- _FORCE_INLINE_ RID get_self() const {return self; }
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
+ _FORCE_INLINE_ RID get_self() const { return self; }
- virtual PhysicsServer::ShapeType get_type() const=0;
+ virtual PhysicsServer::ShapeType get_type() const = 0;
_FORCE_INLINE_ Rect3 get_aabb() const { return aabb; }
_FORCE_INLINE_ bool is_configured() const { return configured; }
virtual bool is_concave() const { return false; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const=0;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const=0;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const = 0;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const = 0;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_point, Vector3 &r_normal) const=0;
- virtual Vector3 get_moment_of_inertia(real_t p_mass) const=0;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal) const = 0;
+ virtual Vector3 get_moment_of_inertia(real_t p_mass) const = 0;
- virtual void set_data(const Variant& p_data)=0;
- virtual Variant get_data() const=0;
+ virtual void set_data(const Variant &p_data) = 0;
+ virtual Variant get_data() const = 0;
- _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias=p_bias; }
+ _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias = p_bias; }
_FORCE_INLINE_ real_t get_custom_bias() const { return custom_bias; }
void add_owner(ShapeOwnerSW *p_owner);
void remove_owner(ShapeOwnerSW *p_owner);
bool is_owner(ShapeOwnerSW *p_owner) const;
- const Map<ShapeOwnerSW*,int>& get_owners() const;
+ const Map<ShapeOwnerSW *, int> &get_owners() const;
ShapeSW();
virtual ~ShapeSW();
};
-
class ConcaveShapeSW : public ShapeSW {
public:
-
virtual bool is_concave() const { return true; }
- typedef void (*Callback)(void* p_userdata,ShapeSW *p_convex);
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; }
+ typedef void (*Callback)(void *p_userdata, ShapeSW *p_convex);
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; }
- virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const=0;
+ virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const = 0;
ConcaveShapeSW() {}
};
@@ -125,22 +121,22 @@ class PlaneShapeSW : public ShapeSW {
Plane plane;
- void _setup(const Plane& p_plane);
-public:
+ void _setup(const Plane &p_plane);
+public:
Plane get_plane() const;
virtual real_t get_area() const { return Math_INF; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_PLANE; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; }
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; }
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
PlaneShapeSW();
@@ -151,21 +147,21 @@ class RayShapeSW : public ShapeSW {
real_t length;
void _setup(real_t p_length);
-public:
+public:
real_t get_length() const;
virtual real_t get_area() const { return 0.0; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_RAY; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
RayShapeSW();
@@ -176,22 +172,22 @@ class SphereShapeSW : public ShapeSW {
real_t radius;
void _setup(real_t p_radius);
-public:
+public:
real_t get_radius() const;
- virtual real_t get_area() const { return 4.0/3.0 * Math_PI * radius * radius * radius; }
+ virtual real_t get_area() const { return 4.0 / 3.0 * Math_PI * radius * radius * radius; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_SPHERE; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
SphereShapeSW();
@@ -200,22 +196,22 @@ public:
class BoxShapeSW : public ShapeSW {
Vector3 half_extents;
- void _setup(const Vector3& p_half_extents);
-public:
+ void _setup(const Vector3 &p_half_extents);
+public:
_FORCE_INLINE_ Vector3 get_half_extents() const { return half_extents; }
- virtual real_t get_area() const { return 8 * half_extents.x * half_extents.y * half_extents.z; }
+ virtual real_t get_area() const { return 8 * half_extents.x * half_extents.y * half_extents.z; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_BOX; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
BoxShapeSW();
@@ -226,25 +222,24 @@ class CapsuleShapeSW : public ShapeSW {
real_t height;
real_t radius;
+ void _setup(real_t p_height, real_t p_radius);
- void _setup(real_t p_height,real_t p_radius);
public:
-
_FORCE_INLINE_ real_t get_height() const { return height; }
_FORCE_INLINE_ real_t get_radius() const { return radius; }
- virtual real_t get_area() { return 4.0/3.0 * Math_PI * radius * radius * radius + height * Math_PI * radius * radius; }
+ virtual real_t get_area() { return 4.0 / 3.0 * Math_PI * radius * radius * radius + height * Math_PI * radius * radius; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CAPSULE; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
CapsuleShapeSW();
@@ -254,28 +249,26 @@ struct ConvexPolygonShapeSW : public ShapeSW {
Geometry::MeshData mesh;
- void _setup(const Vector<Vector3>& p_vertices);
-public:
+ void _setup(const Vector<Vector3> &p_vertices);
- const Geometry::MeshData& get_mesh() const { return mesh; }
+public:
+ const Geometry::MeshData &get_mesh() const { return mesh; }
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONVEX_POLYGON; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
ConvexPolygonShapeSW();
-
};
-
struct _VolumeSW_BVH;
struct FaceShapeSW;
@@ -326,39 +319,35 @@ struct ConcavePolygonShapeSW : public ConcaveShapeSW {
Vector3 normal;
real_t min_d;
int collisions;
-
};
- void _cull_segment(int p_idx,_SegmentCullParams *p_params) const;
- void _cull(int p_idx,_CullParams *p_params) const;
-
- void _fill_bvh(_VolumeSW_BVH* p_bvh_tree,BVH* p_bvh_array,int& p_idx);
+ void _cull_segment(int p_idx, _SegmentCullParams *p_params) const;
+ void _cull(int p_idx, _CullParams *p_params) const;
+ void _fill_bvh(_VolumeSW_BVH *p_bvh_tree, BVH *p_bvh_array, int &p_idx);
void _setup(PoolVector<Vector3> p_faces);
-public:
+public:
PoolVector<Vector3> get_faces() const;
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONCAVE_POLYGON; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
- virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const;
+ virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
ConcavePolygonShapeSW();
-
};
-
struct HeightMapShapeSW : public ConcaveShapeSW {
PoolVector<real_t> heights;
@@ -369,9 +358,9 @@ struct HeightMapShapeSW : public ConcaveShapeSW {
//void _cull_segment(int p_idx,_SegmentCullParams *p_params) const;
//void _cull(int p_idx,_CullParams *p_params) const;
- void _setup(PoolVector<real_t> p_heights,int p_width,int p_depth,real_t p_cell_size);
-public:
+ void _setup(PoolVector<real_t> p_heights, int p_width, int p_depth, real_t p_cell_size);
+public:
PoolVector<real_t> get_heights() const;
int get_width() const;
int get_depth() const;
@@ -379,19 +368,18 @@ public:
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_HEIGHTMAP; }
- virtual void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- virtual Vector3 get_support(const Vector3& p_normal) const;
- virtual bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ virtual void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ virtual Vector3 get_support(const Vector3 &p_normal) const;
+ virtual bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
- virtual void cull(const Rect3& p_local_aabb,Callback p_callback,void* p_userdata) const;
+ virtual void cull(const Rect3 &p_local_aabb, Callback p_callback, void *p_userdata) const;
virtual Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
HeightMapShapeSW();
-
};
//used internally
@@ -402,22 +390,21 @@ struct FaceShapeSW : public ShapeSW {
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONCAVE_POLYGON; }
- const Vector3& get_vertex(int p_idx) const { return vertex[p_idx]; }
+ const Vector3 &get_vertex(int p_idx) const { return vertex[p_idx]; }
- void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const;
- Vector3 get_support(const Vector3& p_normal) const;
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const;
- bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const;
+ void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const;
+ Vector3 get_support(const Vector3 &p_normal) const;
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const;
+ bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const;
Vector3 get_moment_of_inertia(real_t p_mass) const;
- virtual void set_data(const Variant& p_data) {}
+ virtual void set_data(const Variant &p_data) {}
virtual Variant get_data() const { return Variant(); }
FaceShapeSW();
};
-
struct MotionShapeSW : public ShapeSW {
ShapeSW *shape;
@@ -425,56 +412,48 @@ struct MotionShapeSW : public ShapeSW {
virtual PhysicsServer::ShapeType get_type() const { return PhysicsServer::SHAPE_CONVEX_POLYGON; }
-
- void project_range(const Vector3& p_normal, const Transform& p_transform, real_t &r_min, real_t &r_max) const {
+ void project_range(const Vector3 &p_normal, const Transform &p_transform, real_t &r_min, real_t &r_max) const {
Vector3 cast = p_transform.basis.xform(motion);
- real_t mina,maxa;
- real_t minb,maxb;
+ real_t mina, maxa;
+ real_t minb, maxb;
Transform ofsb = p_transform;
- ofsb.origin+=cast;
- shape->project_range(p_normal,p_transform,mina,maxa);
- shape->project_range(p_normal,ofsb,minb,maxb);
- r_min=MIN(mina,minb);
- r_max=MAX(maxa,maxb);
+ ofsb.origin += cast;
+ shape->project_range(p_normal, p_transform, mina, maxa);
+ shape->project_range(p_normal, ofsb, minb, maxb);
+ r_min = MIN(mina, minb);
+ r_max = MAX(maxa, maxb);
}
- Vector3 get_support(const Vector3& p_normal) const {
+ Vector3 get_support(const Vector3 &p_normal) const {
Vector3 support = shape->get_support(p_normal);
- if (p_normal.dot(motion)>0) {
- support+=motion;
+ if (p_normal.dot(motion) > 0) {
+ support += motion;
}
return support;
}
- virtual void get_supports(const Vector3& p_normal,int p_max,Vector3 *r_supports,int & r_amount) const { r_amount=0; }
- bool intersect_segment(const Vector3& p_begin,const Vector3& p_end,Vector3 &r_result, Vector3 &r_normal) const { return false; }
+ virtual void get_supports(const Vector3 &p_normal, int p_max, Vector3 *r_supports, int &r_amount) const { r_amount = 0; }
+ bool intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_result, Vector3 &r_normal) const { return false; }
Vector3 get_moment_of_inertia(real_t p_mass) const { return Vector3(); }
- virtual void set_data(const Variant& p_data) {}
+ virtual void set_data(const Variant &p_data) {}
virtual Variant get_data() const { return Variant(); }
- MotionShapeSW() { configure(Rect3()); }
+ MotionShapeSW() { configure(Rect3()); }
};
-
-
-
struct _ShapeTestConvexBSPSW {
const BSP_Tree *bsp;
const ShapeSW *shape;
Transform transform;
- _FORCE_INLINE_ void project_range(const Vector3& p_normal, real_t& r_min, real_t& r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector3 &p_normal, real_t &r_min, real_t &r_max) const {
- shape->project_range(p_normal,transform,r_min,r_max);
+ shape->project_range(p_normal, transform, r_min, r_max);
}
-
};
-
-
-
#endif // SHAPESW_H
diff --git a/servers/physics/space_sw.cpp b/servers/physics/space_sw.cpp
index 0bc11041de..603c6fa3c4 100644
--- a/servers/physics/space_sw.cpp
+++ b/servers/physics/space_sw.cpp
@@ -26,66 +26,58 @@
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#include "global_config.h"
#include "space_sw.h"
#include "collision_solver_sw.h"
+#include "global_config.h"
#include "physics_server_sw.h"
-
_FORCE_INLINE_ static bool _match_object_type_query(CollisionObjectSW *p_object, uint32_t p_layer_mask, uint32_t p_type_mask) {
- if (p_object->get_type()==CollisionObjectSW::TYPE_AREA)
- return p_type_mask&PhysicsDirectSpaceState::TYPE_MASK_AREA;
+ if (p_object->get_type() == CollisionObjectSW::TYPE_AREA)
+ return p_type_mask & PhysicsDirectSpaceState::TYPE_MASK_AREA;
- if ((p_object->get_layer_mask()&p_layer_mask)==0)
+ if ((p_object->get_layer_mask() & p_layer_mask) == 0)
return false;
- BodySW *body = static_cast<BodySW*>(p_object);
-
- return (1<<body->get_mode())&p_type_mask;
+ BodySW *body = static_cast<BodySW *>(p_object);
+ return (1 << body->get_mode()) & p_type_mask;
}
+bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3 &p_from, const Vector3 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_ray) {
-bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3& p_from, const Vector3& p_to, RayResult &r_result, const Set<RID>& p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_ray) {
-
+ ERR_FAIL_COND_V(space->locked, false);
- ERR_FAIL_COND_V(space->locked,false);
-
- Vector3 begin,end;
+ Vector3 begin, end;
Vector3 normal;
- begin=p_from;
- end=p_to;
- normal=(end-begin).normalized();
-
-
- int amount = space->broadphase->cull_segment(begin,end,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ begin = p_from;
+ end = p_to;
+ normal = (end - begin).normalized();
+ int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
//todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
- bool collided=false;
- Vector3 res_point,res_normal;
+ bool collided = false;
+ Vector3 res_point, res_normal;
int res_shape;
const CollisionObjectSW *res_obj;
- real_t min_d=1e10;
-
-
+ real_t min_d = 1e10;
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_pick_ray && !(static_cast<CollisionObjectSW*>(space->intersection_query_results[i])->is_ray_pickable()))
+ if (p_pick_ray && !(static_cast<CollisionObjectSW *>(space->intersection_query_results[i])->is_ray_pickable()))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
- const CollisionObjectSW *col_obj=space->intersection_query_results[i];
+ const CollisionObjectSW *col_obj = space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
Transform inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
Vector3 local_from = inv_xform.xform(begin);
@@ -93,293 +85,268 @@ bool PhysicsDirectSpaceStateSW::intersect_ray(const Vector3& p_from, const Vecto
const ShapeSW *shape = col_obj->get_shape(shape_idx);
- Vector3 shape_point,shape_normal;
-
-
- if (shape->intersect_segment(local_from,local_to,shape_point,shape_normal)) {
-
+ Vector3 shape_point, shape_normal;
+ if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
Transform xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
- shape_point=xform.xform(shape_point);
+ shape_point = xform.xform(shape_point);
real_t ld = normal.dot(shape_point);
+ if (ld < min_d) {
- if (ld<min_d) {
-
- min_d=ld;
- res_point=shape_point;
- res_normal=inv_xform.basis.xform_inv(shape_normal).normalized();
- res_shape=shape_idx;
- res_obj=col_obj;
- collided=true;
+ min_d = ld;
+ res_point = shape_point;
+ res_normal = inv_xform.basis.xform_inv(shape_normal).normalized();
+ res_shape = shape_idx;
+ res_obj = col_obj;
+ collided = true;
}
}
-
}
if (!collided)
return false;
-
- r_result.collider_id=res_obj->get_instance_id();
- if (r_result.collider_id!=0)
- r_result.collider=ObjectDB::get_instance(r_result.collider_id);
+ r_result.collider_id = res_obj->get_instance_id();
+ if (r_result.collider_id != 0)
+ r_result.collider = ObjectDB::get_instance(r_result.collider_id);
else
- r_result.collider=NULL;
- r_result.normal=res_normal;
- r_result.position=res_point;
- r_result.rid=res_obj->get_self();
- r_result.shape=res_shape;
+ r_result.collider = NULL;
+ r_result.normal = res_normal;
+ r_result.position = res_point;
+ r_result.rid = res_obj->get_self();
+ r_result.shape = res_shape;
return true;
-
}
+int PhysicsDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
-int PhysicsDirectSpaceStateSW::intersect_shape(const RID& p_shape, const Transform& p_xform,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
- if (p_result_max<=0)
+ if (p_result_max <= 0)
return 0;
- ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
+ ERR_FAIL_COND_V(!shape, 0);
Rect3 aabb = p_xform.xform(shape->get_aabb());
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- int cc=0;
+ int cc = 0;
//Transform ai = p_xform.affine_inverse();
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
- if (cc>=p_result_max)
+ if (cc >= p_result_max)
break;
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
//area cant be picked by ray (default)
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
+ const CollisionObjectSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- const CollisionObjectSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
-
- if (!CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL,NULL,NULL,p_margin,0))
+ if (!CollisionSolverSW::solve_static(shape, p_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), NULL, NULL, NULL, p_margin, 0))
continue;
if (r_results) {
- r_results[cc].collider_id=col_obj->get_instance_id();
- if (r_results[cc].collider_id!=0)
- r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id);
+ r_results[cc].collider_id = col_obj->get_instance_id();
+ if (r_results[cc].collider_id != 0)
+ r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
else
- r_results[cc].collider=NULL;
- r_results[cc].rid=col_obj->get_self();
- r_results[cc].shape=shape_idx;
+ r_results[cc].collider = NULL;
+ r_results[cc].rid = col_obj->get_self();
+ r_results[cc].shape = shape_idx;
}
cc++;
-
}
return cc;
-
}
+bool PhysicsDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, ShapeRestInfo *r_info) {
-bool PhysicsDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask,ShapeRestInfo *r_info) {
-
-
-
- ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,false);
+ ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
+ ERR_FAIL_COND_V(!shape, false);
Rect3 aabb = p_xform.xform(shape->get_aabb());
- aabb=aabb.merge(Rect3(aabb.pos+p_motion,aabb.size)); //motion
- aabb=aabb.grow(p_margin);
+ aabb = aabb.merge(Rect3(aabb.pos + p_motion, aabb.size)); //motion
+ aabb = aabb.grow(p_margin);
/*
if (p_motion!=Vector3())
print_line(p_motion);
*/
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- real_t best_safe=1;
- real_t best_unsafe=1;
+ real_t best_safe = 1;
+ real_t best_unsafe = 1;
Transform xform_inv = p_xform.affine_inverse();
MotionShapeSW mshape;
- mshape.shape=shape;
- mshape.motion=xform_inv.basis.xform(p_motion);
+ mshape.shape = shape;
+ mshape.motion = xform_inv.basis.xform(p_motion);
- bool best_first=true;
+ bool best_first = true;
- Vector3 closest_A,closest_B;
+ Vector3 closest_A, closest_B;
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
-
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue; //ignore excluded
+ const CollisionObjectSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- const CollisionObjectSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
-
- Vector3 point_A,point_B;
- Vector3 sep_axis=p_motion.normalized();
+ Vector3 point_A, point_B;
+ Vector3 sep_axis = p_motion.normalized();
Transform col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
//test initial overlap, does it collide if going all the way?
- if (CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) {
+ if (CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
//print_line("failed motion cast (no collision)");
continue;
}
-
- //test initial overlap
+//test initial overlap
#if 0
if (CollisionSolverSW::solve_static(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,NULL,NULL,&sep_axis)) {
print_line("failed initial cast (collision at begining)");
return false;
}
#else
- sep_axis=p_motion.normalized();
+ sep_axis = p_motion.normalized();
- if (!CollisionSolverSW::solve_distance(shape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,point_A,point_B,aabb,&sep_axis)) {
+ if (!CollisionSolverSW::solve_distance(shape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, point_A, point_B, aabb, &sep_axis)) {
//print_line("failed motion cast (no collision)");
return false;
}
#endif
-
//just do kinematic solving
- real_t low=0;
- real_t hi=1;
- Vector3 mnormal=p_motion.normalized();
+ real_t low = 0;
+ real_t hi = 1;
+ Vector3 mnormal = p_motion.normalized();
- for(int i=0;i<8;i++) { //steps should be customizable..
+ for (int i = 0; i < 8; i++) { //steps should be customizable..
- real_t ofs = (low+hi)*0.5;
+ real_t ofs = (low + hi) * 0.5;
- Vector3 sep=mnormal; //important optimization for this to work fast enough
+ Vector3 sep = mnormal; //important optimization for this to work fast enough
- mshape.motion=xform_inv.basis.xform(p_motion*ofs);
+ mshape.motion = xform_inv.basis.xform(p_motion * ofs);
- Vector3 lA,lB;
+ Vector3 lA, lB;
- bool collided = !CollisionSolverSW::solve_distance(&mshape,p_xform,col_obj->get_shape(shape_idx),col_obj_xform,lA,lB,aabb,&sep);
+ bool collided = !CollisionSolverSW::solve_distance(&mshape, p_xform, col_obj->get_shape(shape_idx), col_obj_xform, lA, lB, aabb, &sep);
if (collided) {
//print_line(itos(i)+": "+rtos(ofs));
- hi=ofs;
+ hi = ofs;
} else {
- point_A=lA;
- point_B=lB;
- low=ofs;
+ point_A = lA;
+ point_B = lB;
+ low = ofs;
}
}
- if (low<best_safe) {
- best_first=true; //force reset
- best_safe=low;
- best_unsafe=hi;
+ if (low < best_safe) {
+ best_first = true; //force reset
+ best_safe = low;
+ best_unsafe = hi;
}
- if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low<=best_safe))) {
- closest_A=point_A;
- closest_B=point_B;
- r_info->collider_id=col_obj->get_instance_id();
- r_info->rid=col_obj->get_self();
- r_info->shape=shape_idx;
- r_info->point=closest_B;
- r_info->normal=(closest_A-closest_B).normalized();
- best_first=false;
- if (col_obj->get_type()==CollisionObjectSW::TYPE_BODY) {
- const BodySW *body=static_cast<const BodySW*>(col_obj);
- r_info->linear_velocity= body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
+ if (r_info && (best_first || (point_A.distance_squared_to(point_B) < closest_A.distance_squared_to(closest_B) && low <= best_safe))) {
+ closest_A = point_A;
+ closest_B = point_B;
+ r_info->collider_id = col_obj->get_instance_id();
+ r_info->rid = col_obj->get_self();
+ r_info->shape = shape_idx;
+ r_info->point = closest_B;
+ r_info->normal = (closest_A - closest_B).normalized();
+ best_first = false;
+ if (col_obj->get_type() == CollisionObjectSW::TYPE_BODY) {
+ const BodySW *body = static_cast<const BodySW *>(col_obj);
+ r_info->linear_velocity = body->get_linear_velocity() + (body->get_angular_velocity()).cross(body->get_transform().origin - closest_B);
}
-
}
-
-
}
- p_closest_safe=best_safe;
- p_closest_unsafe=best_unsafe;
+ p_closest_safe = best_safe;
+ p_closest_unsafe = best_unsafe;
return true;
}
-bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform& p_shape_xform,real_t p_margin,Vector3 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask){
+bool PhysicsDirectSpaceStateSW::collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
- if (p_result_max<=0)
+ if (p_result_max <= 0)
return 0;
- ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
+ ERR_FAIL_COND_V(!shape, 0);
Rect3 aabb = p_shape_xform.xform(shape->get_aabb());
- aabb=aabb.grow(p_margin);
+ aabb = aabb.grow(p_margin);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- bool collided=false;
- r_result_count=0;
+ bool collided = false;
+ r_result_count = 0;
PhysicsServerSW::CollCbkData cbk;
- cbk.max=p_result_max;
- cbk.amount=0;
- cbk.ptr=r_results;
- CollisionSolverSW::CallbackResult cbkres=NULL;
-
- PhysicsServerSW::CollCbkData *cbkptr=NULL;
- if (p_result_max>0) {
- cbkptr=&cbk;
- cbkres=PhysicsServerSW::_shape_col_cbk;
+ cbk.max = p_result_max;
+ cbk.amount = 0;
+ cbk.ptr = r_results;
+ CollisionSolverSW::CallbackResult cbkres = NULL;
+
+ PhysicsServerSW::CollCbkData *cbkptr = NULL;
+ if (p_result_max > 0) {
+ cbkptr = &cbk;
+ cbkres = PhysicsServerSW::_shape_col_cbk;
}
+ for (int i = 0; i < amount; i++) {
- for(int i=0;i<amount;i++) {
-
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- const CollisionObjectSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ const CollisionObjectSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- if (p_exclude.has( col_obj->get_self() )) {
+ if (p_exclude.has(col_obj->get_self())) {
continue;
}
//print_line("AGAINST: "+itos(col_obj->get_self().get_id())+":"+itos(shape_idx));
//print_line("THE ABBB: "+(col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).xform(col_obj->get_shape(shape_idx)->get_aabb()));
- if (CollisionSolverSW::solve_static(shape,p_shape_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),cbkres,cbkptr,NULL,p_margin)) {
- collided=true;
+ if (CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), cbkres, cbkptr, NULL, p_margin)) {
+ collided = true;
}
-
}
- r_result_count=cbk.amount;
+ r_result_count = cbk.amount;
return collided;
-
}
-
struct _RestCallbackData {
const CollisionObjectSW *object;
@@ -391,173 +358,147 @@ struct _RestCallbackData {
real_t best_len;
};
-static void _rest_cbk_result(const Vector3& p_point_A,const Vector3& p_point_B,void *p_userdata) {
-
+static void _rest_cbk_result(const Vector3 &p_point_A, const Vector3 &p_point_B, void *p_userdata) {
- _RestCallbackData *rd=(_RestCallbackData*)p_userdata;
+ _RestCallbackData *rd = (_RestCallbackData *)p_userdata;
Vector3 contact_rel = p_point_B - p_point_A;
real_t len = contact_rel.length();
if (len <= rd->best_len)
return;
- rd->best_len=len;
- rd->best_contact=p_point_B;
- rd->best_normal=contact_rel/len;
- rd->best_object=rd->object;
- rd->best_shape=rd->shape;
-
+ rd->best_len = len;
+ rd->best_contact = p_point_B;
+ rd->best_normal = contact_rel / len;
+ rd->best_object = rd->object;
+ rd->best_shape = rd->shape;
}
-bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform& p_shape_xform,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
+bool PhysicsDirectSpaceStateSW::rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
- ShapeSW *shape = static_cast<PhysicsServerSW*>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ShapeSW *shape = static_cast<PhysicsServerSW *>(PhysicsServer::get_singleton())->shape_owner.get(p_shape);
+ ERR_FAIL_COND_V(!shape, 0);
Rect3 aabb = p_shape_xform.xform(shape->get_aabb());
- aabb=aabb.grow(p_margin);
+ aabb = aabb.grow(p_margin);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,SpaceSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, SpaceSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
_RestCallbackData rcd;
- rcd.best_len=0;
- rcd.best_object=NULL;
- rcd.best_shape=0;
+ rcd.best_len = 0;
+ rcd.best_object = NULL;
+ rcd.best_shape = 0;
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
-
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- const CollisionObjectSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ const CollisionObjectSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- if (p_exclude.has( col_obj->get_self() ))
+ if (p_exclude.has(col_obj->get_self()))
continue;
- rcd.object=col_obj;
- rcd.shape=shape_idx;
- bool sc = CollisionSolverSW::solve_static(shape,p_shape_xform,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),_rest_cbk_result,&rcd,NULL,p_margin);
+ rcd.object = col_obj;
+ rcd.shape = shape_idx;
+ bool sc = CollisionSolverSW::solve_static(shape, p_shape_xform, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), _rest_cbk_result, &rcd, NULL, p_margin);
if (!sc)
continue;
-
-
}
- if (rcd.best_len==0)
+ if (rcd.best_len == 0)
return false;
- r_info->collider_id=rcd.best_object->get_instance_id();
- r_info->shape=rcd.best_shape;
- r_info->normal=rcd.best_normal;
- r_info->point=rcd.best_contact;
- r_info->rid=rcd.best_object->get_self();
- if (rcd.best_object->get_type()==CollisionObjectSW::TYPE_BODY) {
+ r_info->collider_id = rcd.best_object->get_instance_id();
+ r_info->shape = rcd.best_shape;
+ r_info->normal = rcd.best_normal;
+ r_info->point = rcd.best_contact;
+ r_info->rid = rcd.best_object->get_self();
+ if (rcd.best_object->get_type() == CollisionObjectSW::TYPE_BODY) {
- const BodySW *body = static_cast<const BodySW*>(rcd.best_object);
+ const BodySW *body = static_cast<const BodySW *>(rcd.best_object);
r_info->linear_velocity = body->get_linear_velocity() +
- (body->get_angular_velocity()).cross(body->get_transform().origin-rcd.best_contact);// * mPos);
-
+ (body->get_angular_velocity()).cross(body->get_transform().origin - rcd.best_contact); // * mPos);
} else {
- r_info->linear_velocity=Vector3();
+ r_info->linear_velocity = Vector3();
}
return true;
}
-
PhysicsDirectSpaceStateSW::PhysicsDirectSpaceStateSW() {
-
- space=NULL;
+ space = NULL;
}
-
////////////////////////////////////////////////////////////////////////////////////////////////////////////
+void *SpaceSW::_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self) {
+ CollisionObjectSW::Type type_A = A->get_type();
+ CollisionObjectSW::Type type_B = B->get_type();
+ if (type_A > type_B) {
-
-
-
-
-
-
-
-void* SpaceSW::_broadphase_pair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_self) {
-
- CollisionObjectSW::Type type_A=A->get_type();
- CollisionObjectSW::Type type_B=B->get_type();
- if (type_A>type_B) {
-
- SWAP(A,B);
- SWAP(p_subindex_A,p_subindex_B);
- SWAP(type_A,type_B);
+ SWAP(A, B);
+ SWAP(p_subindex_A, p_subindex_B);
+ SWAP(type_A, type_B);
}
- SpaceSW *self = (SpaceSW*)p_self;
+ SpaceSW *self = (SpaceSW *)p_self;
self->collision_pairs++;
- if (type_A==CollisionObjectSW::TYPE_AREA) {
+ if (type_A == CollisionObjectSW::TYPE_AREA) {
- AreaSW *area=static_cast<AreaSW*>(A);
- if (type_B==CollisionObjectSW::TYPE_AREA) {
+ AreaSW *area = static_cast<AreaSW *>(A);
+ if (type_B == CollisionObjectSW::TYPE_AREA) {
- AreaSW *area_b=static_cast<AreaSW*>(B);
- Area2PairSW *area2_pair = memnew(Area2PairSW(area_b,p_subindex_B,area,p_subindex_A) );
+ AreaSW *area_b = static_cast<AreaSW *>(B);
+ Area2PairSW *area2_pair = memnew(Area2PairSW(area_b, p_subindex_B, area, p_subindex_A));
return area2_pair;
} else {
- BodySW *body=static_cast<BodySW*>(B);
- AreaPairSW *area_pair = memnew(AreaPairSW(body,p_subindex_B,area,p_subindex_A) );
+ BodySW *body = static_cast<BodySW *>(B);
+ AreaPairSW *area_pair = memnew(AreaPairSW(body, p_subindex_B, area, p_subindex_A));
return area_pair;
}
} else {
-
- BodyPairSW *b = memnew( BodyPairSW((BodySW*)A,p_subindex_A,(BodySW*)B,p_subindex_B) );
+ BodyPairSW *b = memnew(BodyPairSW((BodySW *)A, p_subindex_A, (BodySW *)B, p_subindex_B));
return b;
-
}
return NULL;
}
-void SpaceSW::_broadphase_unpair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_self) {
-
+void SpaceSW::_broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self) {
-
- SpaceSW *self = (SpaceSW*)p_self;
+ SpaceSW *self = (SpaceSW *)p_self;
self->collision_pairs--;
- ConstraintSW *c = (ConstraintSW*)p_data;
+ ConstraintSW *c = (ConstraintSW *)p_data;
memdelete(c);
}
-
-const SelfList<BodySW>::List& SpaceSW::get_active_body_list() const {
+const SelfList<BodySW>::List &SpaceSW::get_active_body_list() const {
return active_list;
}
-void SpaceSW::body_add_to_active_list(SelfList<BodySW>* p_body) {
+void SpaceSW::body_add_to_active_list(SelfList<BodySW> *p_body) {
active_list.add(p_body);
}
-void SpaceSW::body_remove_from_active_list(SelfList<BodySW>* p_body) {
+void SpaceSW::body_remove_from_active_list(SelfList<BodySW> *p_body) {
active_list.remove(p_body);
-
}
-void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW>* p_body) {
-
+void SpaceSW::body_add_to_inertia_update_list(SelfList<BodySW> *p_body) {
inertia_update_list.add(p_body);
}
-void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW>* p_body) {
+void SpaceSW::body_remove_from_inertia_update_list(SelfList<BodySW> *p_body) {
inertia_update_list.remove(p_body);
}
@@ -569,112 +510,103 @@ BroadPhaseSW *SpaceSW::get_broadphase() {
void SpaceSW::add_object(CollisionObjectSW *p_object) {
- ERR_FAIL_COND( objects.has(p_object) );
+ ERR_FAIL_COND(objects.has(p_object));
objects.insert(p_object);
}
void SpaceSW::remove_object(CollisionObjectSW *p_object) {
- ERR_FAIL_COND( !objects.has(p_object) );
+ ERR_FAIL_COND(!objects.has(p_object));
objects.erase(p_object);
}
-const Set<CollisionObjectSW*> &SpaceSW::get_objects() const {
+const Set<CollisionObjectSW *> &SpaceSW::get_objects() const {
return objects;
}
-void SpaceSW::body_add_to_state_query_list(SelfList<BodySW>* p_body) {
+void SpaceSW::body_add_to_state_query_list(SelfList<BodySW> *p_body) {
state_query_list.add(p_body);
}
-void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW>* p_body) {
+void SpaceSW::body_remove_from_state_query_list(SelfList<BodySW> *p_body) {
state_query_list.remove(p_body);
}
-void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW>* p_area) {
+void SpaceSW::area_add_to_monitor_query_list(SelfList<AreaSW> *p_area) {
monitor_query_list.add(p_area);
}
-void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW>* p_area) {
+void SpaceSW::area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area) {
monitor_query_list.remove(p_area);
}
-void SpaceSW::area_add_to_moved_list(SelfList<AreaSW>* p_area) {
+void SpaceSW::area_add_to_moved_list(SelfList<AreaSW> *p_area) {
area_moved_list.add(p_area);
}
-void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW>* p_area) {
+void SpaceSW::area_remove_from_moved_list(SelfList<AreaSW> *p_area) {
area_moved_list.remove(p_area);
}
-const SelfList<AreaSW>::List& SpaceSW::get_moved_area_list() const {
+const SelfList<AreaSW>::List &SpaceSW::get_moved_area_list() const {
return area_moved_list;
}
-
-
-
void SpaceSW::call_queries() {
- while(state_query_list.first()) {
+ while (state_query_list.first()) {
- BodySW * b = state_query_list.first()->self();
+ BodySW *b = state_query_list.first()->self();
b->call_queries();
state_query_list.remove(state_query_list.first());
}
- while(monitor_query_list.first()) {
+ while (monitor_query_list.first()) {
- AreaSW * a = monitor_query_list.first()->self();
+ AreaSW *a = monitor_query_list.first()->self();
a->call_queries();
monitor_query_list.remove(monitor_query_list.first());
}
-
}
void SpaceSW::setup() {
- contact_debug_count=0;
- while(inertia_update_list.first()) {
+ contact_debug_count = 0;
+ while (inertia_update_list.first()) {
inertia_update_list.first()->self()->update_inertias();
inertia_update_list.remove(inertia_update_list.first());
}
-
-
}
void SpaceSW::update() {
-
broadphase->update();
-
}
-
void SpaceSW::set_param(PhysicsServer::SpaceParameter p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
- case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius=p_value; break;
- case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation=p_value; break;
- case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration=p_value; break;
- case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_threshold=p_value; break;
- case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_threshold=p_value; break;
- case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep=p_value; break;
- case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio=p_value; break;
- case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias=p_value; break;
+ case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
+ case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
+ case PhysicsServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
+ case PhysicsServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_threshold = p_value; break;
+ case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_threshold = p_value; break;
+ case PhysicsServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
+ case PhysicsServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_DAMP_RATIO: body_angular_velocity_damp_ratio = p_value; break;
+ case PhysicsServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
}
}
real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const {
- switch(p_param) {
+ switch (p_param) {
case PhysicsServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
case PhysicsServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
@@ -690,12 +622,12 @@ real_t SpaceSW::get_param(PhysicsServer::SpaceParameter p_param) const {
void SpaceSW::lock() {
- locked=true;
+ locked = true;
}
void SpaceSW::unlock() {
- locked=false;
+ locked = false;
}
bool SpaceSW::is_locked() const {
@@ -710,41 +642,36 @@ PhysicsDirectSpaceStateSW *SpaceSW::get_direct_state() {
SpaceSW::SpaceSW() {
- collision_pairs=0;
- active_objects=0;
- island_count=0;
- contact_debug_count=0;
+ collision_pairs = 0;
+ active_objects = 0;
+ island_count = 0;
+ contact_debug_count = 0;
- locked=false;
- contact_recycle_radius=0.01;
- contact_max_separation=0.05;
- contact_max_allowed_penetration= 0.01;
+ locked = false;
+ contact_recycle_radius = 0.01;
+ contact_max_separation = 0.05;
+ contact_max_allowed_penetration = 0.01;
constraint_bias = 0.01;
- body_linear_velocity_sleep_threshold=GLOBAL_DEF("physics/3d/sleep_threshold_linear",0.1);
- body_angular_velocity_sleep_threshold=GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI) );
- body_time_to_sleep=GLOBAL_DEF("physics/3d/time_before_sleep",0.5);
- body_angular_velocity_damp_ratio=10;
-
+ body_linear_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_linear", 0.1);
+ body_angular_velocity_sleep_threshold = GLOBAL_DEF("physics/3d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
+ body_time_to_sleep = GLOBAL_DEF("physics/3d/time_before_sleep", 0.5);
+ body_angular_velocity_damp_ratio = 10;
broadphase = BroadPhaseSW::create_func();
- broadphase->set_pair_callback(_broadphase_pair,this);
- broadphase->set_unpair_callback(_broadphase_unpair,this);
- area=NULL;
+ broadphase->set_pair_callback(_broadphase_pair, this);
+ broadphase->set_unpair_callback(_broadphase_unpair, this);
+ area = NULL;
- direct_access = memnew( PhysicsDirectSpaceStateSW );
- direct_access->space=this;
-
- for(int i=0;i<ELAPSED_TIME_MAX;i++)
- elapsed_time[i]=0;
+ direct_access = memnew(PhysicsDirectSpaceStateSW);
+ direct_access->space = this;
+ for (int i = 0; i < ELAPSED_TIME_MAX; i++)
+ elapsed_time[i] = 0;
}
SpaceSW::~SpaceSW() {
memdelete(broadphase);
- memdelete( direct_access );
+ memdelete(direct_access);
}
-
-
-
diff --git a/servers/physics/space_sw.h b/servers/physics/space_sw.h
index 208831914f..06538265bb 100644
--- a/servers/physics/space_sw.h
+++ b/servers/physics/space_sw.h
@@ -29,39 +29,35 @@
#ifndef SPACE_SW_H
#define SPACE_SW_H
-#include "typedefs.h"
-#include "hash_map.h"
-#include "body_sw.h"
+#include "area_pair_sw.h"
#include "area_sw.h"
#include "body_pair_sw.h"
-#include "area_pair_sw.h"
+#include "body_sw.h"
#include "broad_phase_sw.h"
#include "collision_object_sw.h"
#include "global_config.h"
-
+#include "hash_map.h"
+#include "typedefs.h"
class PhysicsDirectSpaceStateSW : public PhysicsDirectSpaceState {
- GDCLASS( PhysicsDirectSpaceStateSW, PhysicsDirectSpaceState );
-public:
+ GDCLASS(PhysicsDirectSpaceStateSW, PhysicsDirectSpaceState);
+public:
SpaceSW *space;
- 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_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_ray=false);
- virtual int intersect_shape(const RID& p_shape, const Transform& p_xform,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual bool cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,ShapeRestInfo *r_info=NULL);
- virtual bool collide_shape(RID p_shape, const Transform& p_shape_xform,real_t p_margin,Vector3 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual bool rest_info(RID p_shape, const Transform& p_shape_xform,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
+ 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_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_ray = false);
+ virtual int intersect_shape(const RID &p_shape, const Transform &p_xform, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, ShapeRestInfo *r_info = NULL);
+ virtual bool collide_shape(RID p_shape, const Transform &p_shape_xform, real_t p_margin, Vector3 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual bool rest_info(RID p_shape, const Transform &p_shape_xform, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
PhysicsDirectSpaceStateSW();
};
-
-
class SpaceSW : public RID_Data {
public:
-
enum ElapsedTime {
ELAPSED_TIME_INTEGRATE_FORCES,
ELAPSED_TIME_GENERATE_ISLANDS,
@@ -71,8 +67,8 @@ public:
ELAPSED_TIME_MAX
};
-private:
+private:
uint64_t elapsed_time[ELAPSED_TIME_MAX];
PhysicsDirectSpaceStateSW *direct_access;
@@ -85,10 +81,10 @@ private:
SelfList<AreaSW>::List monitor_query_list;
SelfList<AreaSW>::List area_moved_list;
- static void* _broadphase_pair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_self);
- static void _broadphase_unpair(CollisionObjectSW *A,int p_subindex_A,CollisionObjectSW *B,int p_subindex_B,void *p_data,void *p_self);
+ static void *_broadphase_pair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_self);
+ static void _broadphase_unpair(CollisionObjectSW *A, int p_subindex_A, CollisionObjectSW *B, int p_subindex_B, void *p_data, void *p_self);
- Set<CollisionObjectSW*> objects;
+ Set<CollisionObjectSW *> objects;
AreaSW *area;
@@ -99,7 +95,7 @@ private:
enum {
- INTERSECTION_QUERY_MAX=2048
+ INTERSECTION_QUERY_MAX = 2048
};
CollisionObjectSW *intersection_query_results[INTERSECTION_QUERY_MAX];
@@ -121,36 +117,35 @@ private:
Vector<Vector3> contact_debug;
int contact_debug_count;
-friend class PhysicsDirectSpaceStateSW;
+ friend class PhysicsDirectSpaceStateSW;
public:
-
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
- void set_default_area(AreaSW *p_area) { area=p_area; }
+ void set_default_area(AreaSW *p_area) { area = p_area; }
AreaSW *get_default_area() const { return area; }
- const SelfList<BodySW>::List& get_active_body_list() const;
- void body_add_to_active_list(SelfList<BodySW>* p_body);
- void body_remove_from_active_list(SelfList<BodySW>* p_body);
- void body_add_to_inertia_update_list(SelfList<BodySW>* p_body);
- void body_remove_from_inertia_update_list(SelfList<BodySW>* p_body);
+ const SelfList<BodySW>::List &get_active_body_list() const;
+ void body_add_to_active_list(SelfList<BodySW> *p_body);
+ void body_remove_from_active_list(SelfList<BodySW> *p_body);
+ void body_add_to_inertia_update_list(SelfList<BodySW> *p_body);
+ void body_remove_from_inertia_update_list(SelfList<BodySW> *p_body);
- void body_add_to_state_query_list(SelfList<BodySW>* p_body);
- void body_remove_from_state_query_list(SelfList<BodySW>* p_body);
+ void body_add_to_state_query_list(SelfList<BodySW> *p_body);
+ void body_remove_from_state_query_list(SelfList<BodySW> *p_body);
- void area_add_to_monitor_query_list(SelfList<AreaSW>* p_area);
- void area_remove_from_monitor_query_list(SelfList<AreaSW>* p_area);
- void area_add_to_moved_list(SelfList<AreaSW>* p_area);
- void area_remove_from_moved_list(SelfList<AreaSW>* p_area);
- const SelfList<AreaSW>::List& get_moved_area_list() const;
+ void area_add_to_monitor_query_list(SelfList<AreaSW> *p_area);
+ void area_remove_from_monitor_query_list(SelfList<AreaSW> *p_area);
+ void area_add_to_moved_list(SelfList<AreaSW> *p_area);
+ void area_remove_from_moved_list(SelfList<AreaSW> *p_area);
+ const SelfList<AreaSW>::List &get_moved_area_list() const;
BroadPhaseSW *get_broadphase();
void add_object(CollisionObjectSW *p_object);
void remove_object(CollisionObjectSW *p_object);
- const Set<CollisionObjectSW*> &get_objects() const;
+ const Set<CollisionObjectSW *> &get_objects() const;
_FORCE_INLINE_ real_t get_contact_recycle_radius() const { return contact_recycle_radius; }
_FORCE_INLINE_ real_t get_contact_max_separation() const { return contact_max_separation; }
@@ -161,12 +156,10 @@ public:
_FORCE_INLINE_ real_t get_body_time_to_sleep() const { return body_time_to_sleep; }
_FORCE_INLINE_ real_t get_body_angular_velocity_damp_ratio() const { return body_angular_velocity_damp_ratio; }
-
void update();
void setup();
void call_queries();
-
bool is_locked() const;
void lock();
void unlock();
@@ -174,10 +167,10 @@ public:
void set_param(PhysicsServer::SpaceParameter p_param, real_t p_value);
real_t get_param(PhysicsServer::SpaceParameter p_param) const;
- void set_island_count(int p_island_count) { island_count=p_island_count; }
+ void set_island_count(int p_island_count) { island_count = p_island_count; }
int get_island_count() const { return island_count; }
- void set_active_objects(int p_active_objects) { active_objects=p_active_objects; }
+ void set_active_objects(int p_active_objects) { active_objects = p_active_objects; }
int get_active_objects() const { return active_objects; }
int get_collision_pairs() const { return collision_pairs; }
@@ -186,19 +179,20 @@ public:
void set_debug_contacts(int p_amount) { contact_debug.resize(p_amount); }
_FORCE_INLINE_ bool is_debugging_contacts() const { return !contact_debug.empty(); }
- _FORCE_INLINE_ void add_debug_contact(const Vector3& p_contact) { if (contact_debug_count<contact_debug.size()) contact_debug[contact_debug_count++]=p_contact; }
+ _FORCE_INLINE_ void add_debug_contact(const Vector3 &p_contact) {
+ if (contact_debug_count < contact_debug.size()) contact_debug[contact_debug_count++] = p_contact;
+ }
_FORCE_INLINE_ Vector<Vector3> get_debug_contacts() { return contact_debug; }
_FORCE_INLINE_ int get_debug_contact_count() { return contact_debug_count; }
- void set_static_global_body(RID p_body) { static_global_body=p_body; }
+ void set_static_global_body(RID p_body) { static_global_body = p_body; }
RID get_static_global_body() { return static_global_body; }
- void set_elapsed_time(ElapsedTime p_time,uint64_t p_msec) { elapsed_time[p_time]=p_msec; }
+ void set_elapsed_time(ElapsedTime p_time, uint64_t p_msec) { elapsed_time[p_time] = p_msec; }
uint64_t get_elapsed_time(ElapsedTime p_time) const { return elapsed_time[p_time]; }
SpaceSW();
~SpaceSW();
};
-
#endif // SPACE__SW_H
diff --git a/servers/physics/step_sw.cpp b/servers/physics/step_sw.cpp
index 0bd5a874ea..c7b1be7a9b 100644
--- a/servers/physics/step_sw.cpp
+++ b/servers/physics/step_sw.cpp
@@ -31,279 +31,268 @@
#include "os/os.h"
-void StepSW::_populate_island(BodySW* p_body,BodySW** p_island,ConstraintSW **p_constraint_island) {
+void StepSW::_populate_island(BodySW *p_body, BodySW **p_island, ConstraintSW **p_constraint_island) {
p_body->set_island_step(_step);
p_body->set_island_next(*p_island);
- *p_island=p_body;
+ *p_island = p_body;
- for(Map<ConstraintSW*,int>::Element *E=p_body->get_constraint_map().front();E;E=E->next()) {
+ for (Map<ConstraintSW *, int>::Element *E = p_body->get_constraint_map().front(); E; E = E->next()) {
- ConstraintSW *c=(ConstraintSW*)E->key();
- if (c->get_island_step()==_step)
+ ConstraintSW *c = (ConstraintSW *)E->key();
+ if (c->get_island_step() == _step)
continue; //already processed
c->set_island_step(_step);
c->set_island_next(*p_constraint_island);
- *p_constraint_island=c;
+ *p_constraint_island = c;
-
- for(int i=0;i<c->get_body_count();i++) {
- if (i==E->get())
+ for (int i = 0; i < c->get_body_count(); i++) {
+ if (i == E->get())
continue;
BodySW *b = c->get_body_ptr()[i];
- if (b->get_island_step()==_step || b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC)
+ if (b->get_island_step() == _step || b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC)
continue; //no go
- _populate_island(c->get_body_ptr()[i],p_island,p_constraint_island);
+ _populate_island(c->get_body_ptr()[i], p_island, p_constraint_island);
}
}
}
-void StepSW::_setup_island(ConstraintSW *p_island,real_t p_delta) {
+void StepSW::_setup_island(ConstraintSW *p_island, real_t p_delta) {
- ConstraintSW *ci=p_island;
- while(ci) {
+ ConstraintSW *ci = p_island;
+ while (ci) {
bool process = ci->setup(p_delta);
//todo remove from island if process fails
- ci=ci->get_island_next();
+ ci = ci->get_island_next();
}
}
-void StepSW::_solve_island(ConstraintSW *p_island,int p_iterations,real_t p_delta){
+void StepSW::_solve_island(ConstraintSW *p_island, int p_iterations, real_t p_delta) {
- int at_priority=1;
+ int at_priority = 1;
- while(p_island) {
+ while (p_island) {
- for(int i=0;i<p_iterations;i++) {
+ for (int i = 0; i < p_iterations; i++) {
- ConstraintSW *ci=p_island;
- while(ci) {
+ ConstraintSW *ci = p_island;
+ while (ci) {
ci->solve(p_delta);
- ci=ci->get_island_next();
+ ci = ci->get_island_next();
}
}
at_priority++;
{
- ConstraintSW *ci=p_island;
- ConstraintSW *prev=NULL;
- while(ci) {
- if (ci->get_priority()<at_priority) {
+ ConstraintSW *ci = p_island;
+ ConstraintSW *prev = NULL;
+ while (ci) {
+ if (ci->get_priority() < at_priority) {
if (prev) {
prev->set_island_next(ci->get_island_next()); //remove
} else {
- p_island=ci->get_island_next();
+ p_island = ci->get_island_next();
}
} else {
- prev=ci;
+ prev = ci;
}
- ci=ci->get_island_next();
+ ci = ci->get_island_next();
}
}
}
-
}
-void StepSW::_check_suspend(BodySW *p_island,real_t p_delta) {
-
+void StepSW::_check_suspend(BodySW *p_island, real_t p_delta) {
- bool can_sleep=true;
+ bool can_sleep = true;
BodySW *b = p_island;
- while(b) {
+ while (b) {
- if (b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) {
- b=b->get_island_next();
+ if (b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) {
+ b = b->get_island_next();
continue; //ignore for static
}
if (!b->sleep_test(p_delta))
- can_sleep=false;
+ can_sleep = false;
- b=b->get_island_next();
+ b = b->get_island_next();
}
//put all to sleep or wake up everyoen
b = p_island;
- while(b) {
+ while (b) {
- if (b->get_mode()==PhysicsServer::BODY_MODE_STATIC || b->get_mode()==PhysicsServer::BODY_MODE_KINEMATIC) {
- b=b->get_island_next();
+ if (b->get_mode() == PhysicsServer::BODY_MODE_STATIC || b->get_mode() == PhysicsServer::BODY_MODE_KINEMATIC) {
+ b = b->get_island_next();
continue; //ignore for static
}
bool active = b->is_active();
- if (active==can_sleep)
+ if (active == can_sleep)
b->set_active(!can_sleep);
- b=b->get_island_next();
+ b = b->get_island_next();
}
}
-void StepSW::step(SpaceSW* p_space,real_t p_delta,int p_iterations) {
+void StepSW::step(SpaceSW *p_space, real_t p_delta, int p_iterations) {
p_space->lock(); // can't access space during this
p_space->setup(); //update inertias, etc
- const SelfList<BodySW>::List * body_list = &p_space->get_active_body_list();
+ const SelfList<BodySW>::List *body_list = &p_space->get_active_body_list();
/* INTEGRATE FORCES */
uint64_t profile_begtime = OS::get_singleton()->get_ticks_usec();
- uint64_t profile_endtime=0;
+ uint64_t profile_endtime = 0;
- int active_count=0;
+ int active_count = 0;
- const SelfList<BodySW>*b = body_list->first();
- while(b) {
+ const SelfList<BodySW> *b = body_list->first();
+ while (b) {
b->self()->integrate_forces(p_delta);
- b=b->next();
+ b = b->next();
active_count++;
}
p_space->set_active_objects(active_count);
-
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_FORCES,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_FORCES, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* GENERATE CONSTRAINT ISLANDS */
- BodySW *island_list=NULL;
- ConstraintSW *constraint_island_list=NULL;
+ BodySW *island_list = NULL;
+ ConstraintSW *constraint_island_list = NULL;
b = body_list->first();
- int island_count=0;
+ int island_count = 0;
- while(b) {
+ while (b) {
BodySW *body = b->self();
+ if (body->get_island_step() != _step) {
- if (body->get_island_step()!=_step) {
-
- BodySW *island=NULL;
- ConstraintSW *constraint_island=NULL;
- _populate_island(body,&island,&constraint_island);
+ BodySW *island = NULL;
+ ConstraintSW *constraint_island = NULL;
+ _populate_island(body, &island, &constraint_island);
island->set_island_list_next(island_list);
- island_list=island;
+ island_list = island;
if (constraint_island) {
constraint_island->set_island_list_next(constraint_island_list);
- constraint_island_list=constraint_island;
+ constraint_island_list = constraint_island;
island_count++;
}
-
}
- b=b->next();
+ b = b->next();
}
p_space->set_island_count(island_count);
const SelfList<AreaSW>::List &aml = p_space->get_moved_area_list();
- while(aml.first()) {
- for(const Set<ConstraintSW*>::Element *E=aml.first()->self()->get_constraints().front();E;E=E->next()) {
+ while (aml.first()) {
+ for (const Set<ConstraintSW *>::Element *E = aml.first()->self()->get_constraints().front(); E; E = E->next()) {
- ConstraintSW*c=E->get();
- if (c->get_island_step()==_step)
+ ConstraintSW *c = E->get();
+ if (c->get_island_step() == _step)
continue;
c->set_island_step(_step);
c->set_island_next(NULL);
c->set_island_list_next(constraint_island_list);
- constraint_island_list=c;
+ constraint_island_list = c;
}
- p_space->area_remove_from_moved_list((SelfList<AreaSW>*)aml.first()); //faster to remove here
+ p_space->area_remove_from_moved_list((SelfList<AreaSW> *)aml.first()); //faster to remove here
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_GENERATE_ISLANDS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_GENERATE_ISLANDS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
-
//print_line("island count: "+itos(island_count)+" active count: "+itos(active_count));
/* SETUP CONSTRAINT ISLANDS */
{
- ConstraintSW *ci=constraint_island_list;
- while(ci) {
+ ConstraintSW *ci = constraint_island_list;
+ while (ci) {
- _setup_island(ci,p_delta);
- ci=ci->get_island_list_next();
+ _setup_island(ci, p_delta);
+ ci = ci->get_island_list_next();
}
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SETUP_CONSTRAINTS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SETUP_CONSTRAINTS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* SOLVE CONSTRAINT ISLANDS */
{
- ConstraintSW *ci=constraint_island_list;
- while(ci) {
+ ConstraintSW *ci = constraint_island_list;
+ while (ci) {
//iterating each island separatedly improves cache efficiency
- _solve_island(ci,p_iterations,p_delta);
- ci=ci->get_island_list_next();
+ _solve_island(ci, p_iterations, p_delta);
+ ci = ci->get_island_list_next();
}
}
-
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SOLVE_CONSTRAINTS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_SOLVE_CONSTRAINTS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* INTEGRATE VELOCITIES */
b = body_list->first();
- while(b) {
- const SelfList<BodySW>*n=b->next();
+ while (b) {
+ const SelfList<BodySW> *n = b->next();
b->self()->integrate_velocities(p_delta);
- b=n;
+ b = n;
}
/* SLEEP / WAKE UP ISLANDS */
{
- BodySW *bi=island_list;
- while(bi) {
+ BodySW *bi = island_list;
+ while (bi) {
- _check_suspend(bi,p_delta);
- bi=bi->get_island_list_next();
+ _check_suspend(bi, p_delta);
+ bi = bi->get_island_list_next();
}
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_VELOCITIES,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(SpaceSW::ELAPSED_TIME_INTEGRATE_VELOCITIES, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
p_space->update();
p_space->unlock();
_step++;
-
-
-
}
StepSW::StepSW() {
- _step=1;
+ _step = 1;
}
diff --git a/servers/physics/step_sw.h b/servers/physics/step_sw.h
index 7048a76937..54f5fe9857 100644
--- a/servers/physics/step_sw.h
+++ b/servers/physics/step_sw.h
@@ -35,13 +35,13 @@ class StepSW {
uint64_t _step;
- void _populate_island(BodySW* p_body,BodySW** p_island,ConstraintSW **p_constraint_island);
- void _setup_island(ConstraintSW *p_island,real_t p_delta);
- void _solve_island(ConstraintSW *p_island,int p_iterations,real_t p_delta);
- void _check_suspend(BodySW *p_island,real_t p_delta);
-public:
+ void _populate_island(BodySW *p_body, BodySW **p_island, ConstraintSW **p_constraint_island);
+ void _setup_island(ConstraintSW *p_island, real_t p_delta);
+ void _solve_island(ConstraintSW *p_island, int p_iterations, real_t p_delta);
+ void _check_suspend(BodySW *p_island, real_t p_delta);
- void step(SpaceSW* p_space,real_t p_delta,int p_iterations);
+public:
+ void step(SpaceSW *p_space, real_t p_delta, int p_iterations);
StepSW();
};
diff --git a/servers/physics_2d/area_2d_sw.cpp b/servers/physics_2d/area_2d_sw.cpp
index 2625502717..885ede7cbf 100644
--- a/servers/physics_2d/area_2d_sw.cpp
+++ b/servers/physics_2d/area_2d_sw.cpp
@@ -27,18 +27,26 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "area_2d_sw.h"
-#include "space_2d_sw.h"
#include "body_2d_sw.h"
+#include "space_2d_sw.h"
-Area2DSW::BodyKey::BodyKey(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; }
-Area2DSW::BodyKey::BodyKey(Area2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; }
+Area2DSW::BodyKey::BodyKey(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
+ rid = p_body->get_self();
+ instance_id = p_body->get_instance_id();
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+}
+Area2DSW::BodyKey::BodyKey(Area2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
+ rid = p_body->get_self();
+ instance_id = p_body->get_instance_id();
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+}
void Area2DSW::_shapes_changed() {
-
-
}
-void Area2DSW::set_transform(const Transform2D& p_transform) {
+void Area2DSW::set_transform(const Transform2D &p_transform) {
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
@@ -54,7 +62,6 @@ void Area2DSW::set_space(Space2DSW *p_space) {
get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
if (moved_list.in_list())
get_space()->area_remove_from_moved_list(&moved_list);
-
}
monitored_bodies.clear();
@@ -63,19 +70,17 @@ void Area2DSW::set_space(Space2DSW *p_space) {
_set_space(p_space);
}
+void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName &p_method) {
-void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) {
-
-
- if (p_id==monitor_callback_id) {
- monitor_callback_method=p_method;
+ if (p_id == monitor_callback_id) {
+ monitor_callback_method = p_method;
return;
}
_unregister_shapes();
- monitor_callback_id=p_id;
- monitor_callback_method=p_method;
+ monitor_callback_id = p_id;
+ monitor_callback_method = p_method;
monitored_bodies.clear();
monitored_areas.clear();
@@ -84,22 +89,19 @@ void Area2DSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) {
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
-
-
}
-void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_method) {
+void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName &p_method) {
-
- if (p_id==area_monitor_callback_id) {
- area_monitor_callback_method=p_method;
+ if (p_id == area_monitor_callback_id) {
+ area_monitor_callback_method = p_method;
return;
}
_unregister_shapes();
- area_monitor_callback_id=p_id;
- area_monitor_callback_method=p_method;
+ area_monitor_callback_id = p_id;
+ area_monitor_callback_method = p_method;
monitored_bodies.clear();
monitored_areas.clear();
@@ -108,45 +110,39 @@ void Area2DSW::set_area_monitor_callback(ObjectID p_id, const StringName& p_meth
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
-
-
}
-
void Area2DSW::set_space_override_mode(Physics2DServer::AreaSpaceOverrideMode p_mode) {
- bool do_override=p_mode!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED;
- if (do_override==(space_override_mode!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED))
+ bool do_override = p_mode != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED;
+ if (do_override == (space_override_mode != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED))
return;
_unregister_shapes();
- space_override_mode=p_mode;
+ space_override_mode = p_mode;
_shape_changed();
}
-void Area2DSW::set_param(Physics2DServer::AreaParameter p_param, const Variant& p_value) {
-
- switch(p_param) {
- case Physics2DServer::AREA_PARAM_GRAVITY: gravity=p_value; break;
- case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector=p_value; break;
- case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point=p_value; break;
- case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale=p_value; break;
- case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation=p_value; break;
- case Physics2DServer::AREA_PARAM_LINEAR_DAMP: linear_damp=p_value; break;
- case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: angular_damp=p_value; break;
- case Physics2DServer::AREA_PARAM_PRIORITY: priority=p_value; break;
+void Area2DSW::set_param(Physics2DServer::AreaParameter p_param, const Variant &p_value) {
+
+ switch (p_param) {
+ case Physics2DServer::AREA_PARAM_GRAVITY: gravity = p_value; break;
+ case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector = p_value; break;
+ case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point = p_value; break;
+ case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: gravity_distance_scale = p_value; break;
+ case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation = p_value; break;
+ case Physics2DServer::AREA_PARAM_LINEAR_DAMP: linear_damp = p_value; break;
+ case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: angular_damp = p_value; break;
+ case Physics2DServer::AREA_PARAM_PRIORITY: priority = p_value; break;
}
-
-
}
Variant Area2DSW::get_param(Physics2DServer::AreaParameter p_param) const {
-
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::AREA_PARAM_GRAVITY: return gravity;
case Physics2DServer::AREA_PARAM_GRAVITY_VECTOR: return gravity_vector;
case Physics2DServer::AREA_PARAM_GRAVITY_IS_POINT: return gravity_is_point;
case Physics2DServer::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return gravity_distance_scale;
- case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation;
+ case Physics2DServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation;
case Physics2DServer::AREA_PARAM_LINEAR_DAMP: return linear_damp;
case Physics2DServer::AREA_PARAM_ANGULAR_DAMP: return angular_damp;
case Physics2DServer::AREA_PARAM_PRIORITY: return priority;
@@ -155,23 +151,20 @@ Variant Area2DSW::get_param(Physics2DServer::AreaParameter p_param) const {
return Variant();
}
-
void Area2DSW::_queue_monitor_update() {
ERR_FAIL_COND(!get_space());
if (!monitor_query_list.in_list())
get_space()->area_add_to_monitor_query_list(&monitor_query_list);
-
-
}
void Area2DSW::set_monitorable(bool p_monitorable) {
- if (monitorable==p_monitorable)
+ if (monitorable == p_monitorable)
return;
- monitorable=p_monitorable;
+ monitorable = p_monitorable;
_set_static(!monitorable);
}
@@ -181,31 +174,29 @@ void Area2DSW::call_queries() {
Variant res[5];
Variant *resptr[5];
- for(int i=0;i<5;i++)
- resptr[i]=&res[i];
+ for (int i = 0; i < 5; i++)
+ resptr[i] = &res[i];
Object *obj = ObjectDB::get_instance(monitor_callback_id);
if (!obj) {
monitored_bodies.clear();
- monitor_callback_id=0;
+ monitor_callback_id = 0;
return;
}
+ for (Map<BodyKey, BodyState>::Element *E = monitored_bodies.front(); E; E = E->next()) {
-
- for (Map<BodyKey,BodyState>::Element *E=monitored_bodies.front();E;E=E->next()) {
-
- if (E->get().state==0)
+ if (E->get().state == 0)
continue; //nothing happened
- res[0]=E->get().state>0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED;
- res[1]=E->key().rid;
- res[2]=E->key().instance_id;
- res[3]=E->key().body_shape;
- res[4]=E->key().area_shape;
+ res[0] = E->get().state > 0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED;
+ res[1] = E->key().rid;
+ res[2] = E->key().instance_id;
+ res[3] = E->key().body_shape;
+ res[4] = E->key().area_shape;
Variant::CallError ce;
- obj->call(monitor_callback_method,(const Variant**)resptr,5,ce);
+ obj->call(monitor_callback_method, (const Variant **)resptr, 5, ce);
}
}
@@ -213,66 +204,57 @@ void Area2DSW::call_queries() {
if (area_monitor_callback_id && !monitored_areas.empty()) {
-
Variant res[5];
Variant *resptr[5];
- for(int i=0;i<5;i++)
- resptr[i]=&res[i];
+ for (int i = 0; i < 5; i++)
+ resptr[i] = &res[i];
Object *obj = ObjectDB::get_instance(area_monitor_callback_id);
if (!obj) {
monitored_areas.clear();
- area_monitor_callback_id=0;
+ area_monitor_callback_id = 0;
return;
}
+ for (Map<BodyKey, BodyState>::Element *E = monitored_areas.front(); E; E = E->next()) {
-
- for (Map<BodyKey,BodyState>::Element *E=monitored_areas.front();E;E=E->next()) {
-
- if (E->get().state==0)
+ if (E->get().state == 0)
continue; //nothing happened
- res[0]=E->get().state>0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED;
- res[1]=E->key().rid;
- res[2]=E->key().instance_id;
- res[3]=E->key().body_shape;
- res[4]=E->key().area_shape;
-
+ res[0] = E->get().state > 0 ? Physics2DServer::AREA_BODY_ADDED : Physics2DServer::AREA_BODY_REMOVED;
+ res[1] = E->key().rid;
+ res[2] = E->key().instance_id;
+ res[3] = E->key().body_shape;
+ res[4] = E->key().area_shape;
Variant::CallError ce;
- obj->call(area_monitor_callback_method,(const Variant**)resptr,5,ce);
+ obj->call(area_monitor_callback_method, (const Variant **)resptr, 5, ce);
}
}
monitored_areas.clear();
//get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
-
}
-Area2DSW::Area2DSW() : CollisionObject2DSW(TYPE_AREA), monitor_query_list(this), moved_list(this) {
+Area2DSW::Area2DSW()
+ : CollisionObject2DSW(TYPE_AREA), monitor_query_list(this), moved_list(this) {
_set_static(true); //areas are not active by default
- space_override_mode=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED;
- gravity=9.80665;
- gravity_vector=Vector2(0,-1);
- gravity_is_point=false;
- gravity_distance_scale=0;
- point_attenuation=1;
-
- angular_damp=1.0;
- linear_damp=0.1;
- priority=0;
- monitor_callback_id=0;
- area_monitor_callback_id=0;
- monitorable=false;
-
-
+ space_override_mode = Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED;
+ gravity = 9.80665;
+ gravity_vector = Vector2(0, -1);
+ gravity_is_point = false;
+ gravity_distance_scale = 0;
+ point_attenuation = 1;
+
+ angular_damp = 1.0;
+ linear_damp = 0.1;
+ priority = 0;
+ monitor_callback_id = 0;
+ area_monitor_callback_id = 0;
+ monitorable = false;
}
Area2DSW::~Area2DSW() {
-
-
}
-
diff --git a/servers/physics_2d/area_2d_sw.h b/servers/physics_2d/area_2d_sw.h
index 02a65962e5..8c52c96527 100644
--- a/servers/physics_2d/area_2d_sw.h
+++ b/servers/physics_2d/area_2d_sw.h
@@ -29,18 +29,16 @@
#ifndef AREA_2D_SW_H
#define AREA_2D_SW_H
-#include "servers/physics_2d_server.h"
#include "collision_object_2d_sw.h"
#include "self_list.h"
+#include "servers/physics_2d_server.h"
//#include "servers/physics/query_sw.h"
class Space2DSW;
class Body2DSW;
class Constraint2DSW;
-
-class Area2DSW : public CollisionObject2DSW{
-
+class Area2DSW : public CollisionObject2DSW {
Physics2DServer::AreaSpaceOverrideMode space_override_mode;
real_t gravity;
@@ -69,23 +67,22 @@ class Area2DSW : public CollisionObject2DSW{
uint32_t body_shape;
uint32_t area_shape;
- _FORCE_INLINE_ bool operator<( const BodyKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const BodyKey &p_key) const {
- if (rid==p_key.rid) {
+ if (rid == p_key.rid) {
- if (body_shape==p_key.body_shape) {
+ if (body_shape == p_key.body_shape) {
return area_shape < p_key.area_shape;
} else
return body_shape < p_key.body_shape;
} else
return rid < p_key.rid;
-
}
_FORCE_INLINE_ BodyKey() {}
- BodyKey(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
- BodyKey(Area2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
+ BodyKey(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
+ BodyKey(Area2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
};
struct BodyState {
@@ -93,122 +90,110 @@ class Area2DSW : public CollisionObject2DSW{
int state;
_FORCE_INLINE_ void inc() { state++; }
_FORCE_INLINE_ void dec() { state--; }
- _FORCE_INLINE_ BodyState() { state=0; }
+ _FORCE_INLINE_ BodyState() { state = 0; }
};
- Map<BodyKey,BodyState> monitored_bodies;
- Map<BodyKey,BodyState> monitored_areas;
+ Map<BodyKey, BodyState> monitored_bodies;
+ Map<BodyKey, BodyState> monitored_areas;
//virtual void shape_changed_notify(Shape2DSW *p_shape);
//virtual void shape_deleted_notify(Shape2DSW *p_shape);
- Set<Constraint2DSW*> constraints;
-
+ Set<Constraint2DSW *> constraints;
virtual void _shapes_changed();
void _queue_monitor_update();
public:
-
//_FORCE_INLINE_ const Matrix32& get_inverse_transform() const { return inverse_transform; }
//_FORCE_INLINE_ SpaceSW* get_owner() { return owner; }
- void set_monitor_callback(ObjectID p_id, const StringName& p_method);
+ void set_monitor_callback(ObjectID p_id, const StringName &p_method);
_FORCE_INLINE_ bool has_monitor_callback() const { return monitor_callback_id; }
- void set_area_monitor_callback(ObjectID p_id, const StringName& p_method);
+ void set_area_monitor_callback(ObjectID p_id, const StringName &p_method);
_FORCE_INLINE_ bool has_area_monitor_callback() const { return area_monitor_callback_id; }
+ _FORCE_INLINE_ void add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
+ _FORCE_INLINE_ void remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape);
- _FORCE_INLINE_ void add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
- _FORCE_INLINE_ void remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape);
+ _FORCE_INLINE_ void add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape);
+ _FORCE_INLINE_ void remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape);
- _FORCE_INLINE_ void add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape);
- _FORCE_INLINE_ void remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape);
-
- void set_param(Physics2DServer::AreaParameter p_param, const Variant& p_value);
+ void set_param(Physics2DServer::AreaParameter p_param, const Variant &p_value);
Variant get_param(Physics2DServer::AreaParameter p_param) const;
void set_space_override_mode(Physics2DServer::AreaSpaceOverrideMode p_mode);
Physics2DServer::AreaSpaceOverrideMode get_space_override_mode() const { return space_override_mode; }
- _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity=p_gravity; }
+ _FORCE_INLINE_ void set_gravity(real_t p_gravity) { gravity = p_gravity; }
_FORCE_INLINE_ real_t get_gravity() const { return gravity; }
- _FORCE_INLINE_ void set_gravity_vector(const Vector2& p_gravity) { gravity_vector=p_gravity; }
+ _FORCE_INLINE_ void set_gravity_vector(const Vector2 &p_gravity) { gravity_vector = p_gravity; }
_FORCE_INLINE_ Vector2 get_gravity_vector() const { return gravity_vector; }
- _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point=p_enable; }
+ _FORCE_INLINE_ void set_gravity_as_point(bool p_enable) { gravity_is_point = p_enable; }
_FORCE_INLINE_ bool is_gravity_point() const { return gravity_is_point; }
- _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale=scale; }
+ _FORCE_INLINE_ void set_gravity_distance_scale(real_t scale) { gravity_distance_scale = scale; }
_FORCE_INLINE_ real_t get_gravity_distance_scale() const { return gravity_distance_scale; }
- _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation=p_point_attenuation; }
+ _FORCE_INLINE_ void set_point_attenuation(real_t p_point_attenuation) { point_attenuation = p_point_attenuation; }
_FORCE_INLINE_ real_t get_point_attenuation() const { return point_attenuation; }
- _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp=p_linear_damp; }
+ _FORCE_INLINE_ void set_linear_damp(real_t p_linear_damp) { linear_damp = p_linear_damp; }
_FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; }
- _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp=p_angular_damp; }
+ _FORCE_INLINE_ void set_angular_damp(real_t p_angular_damp) { angular_damp = p_angular_damp; }
_FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; }
- _FORCE_INLINE_ void set_priority(int p_priority) { priority=p_priority; }
+ _FORCE_INLINE_ void set_priority(int p_priority) { priority = p_priority; }
_FORCE_INLINE_ int get_priority() const { return priority; }
- _FORCE_INLINE_ void add_constraint( Constraint2DSW* p_constraint) { constraints.insert(p_constraint); }
- _FORCE_INLINE_ void remove_constraint( Constraint2DSW* p_constraint) { constraints.erase(p_constraint); }
- _FORCE_INLINE_ const Set<Constraint2DSW*>& get_constraints() const { return constraints; }
+ _FORCE_INLINE_ void add_constraint(Constraint2DSW *p_constraint) { constraints.insert(p_constraint); }
+ _FORCE_INLINE_ void remove_constraint(Constraint2DSW *p_constraint) { constraints.erase(p_constraint); }
+ _FORCE_INLINE_ const Set<Constraint2DSW *> &get_constraints() const { return constraints; }
void set_monitorable(bool p_monitorable);
_FORCE_INLINE_ bool is_monitorable() const { return monitorable; }
- void set_transform(const Transform2D& p_transform);
+ void set_transform(const Transform2D &p_transform);
void set_space(Space2DSW *p_space);
-
void call_queries();
Area2DSW();
~Area2DSW();
};
-void Area2DSW::add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) {
+void Area2DSW::add_body_to_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
- BodyKey bk(p_body,p_body_shape,p_area_shape);
+ BodyKey bk(p_body, p_body_shape, p_area_shape);
monitored_bodies[bk].inc();
if (!monitor_query_list.in_list())
_queue_monitor_update();
}
-void Area2DSW::remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) {
+void Area2DSW::remove_body_from_query(Body2DSW *p_body, uint32_t p_body_shape, uint32_t p_area_shape) {
- BodyKey bk(p_body,p_body_shape,p_area_shape);
+ BodyKey bk(p_body, p_body_shape, p_area_shape);
monitored_bodies[bk].dec();
if (!monitor_query_list.in_list())
_queue_monitor_update();
}
-void Area2DSW::add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) {
+void Area2DSW::add_area_to_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) {
-
- BodyKey bk(p_area,p_area_shape,p_self_shape);
+ BodyKey bk(p_area, p_area_shape, p_self_shape);
monitored_areas[bk].inc();
if (!monitor_query_list.in_list())
_queue_monitor_update();
-
-
}
-void Area2DSW::remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape,uint32_t p_self_shape) {
-
+void Area2DSW::remove_area_from_query(Area2DSW *p_area, uint32_t p_area_shape, uint32_t p_self_shape) {
- BodyKey bk(p_area,p_area_shape,p_self_shape);
+ BodyKey bk(p_area, p_area_shape, p_self_shape);
monitored_areas[bk].dec();
if (!monitor_query_list.in_list())
_queue_monitor_update();
}
-
-
-
-
#endif // AREA_2D_SW_H
diff --git a/servers/physics_2d/area_pair_2d_sw.cpp b/servers/physics_2d/area_pair_2d_sw.cpp
index cb91caf626..769db8eb35 100644
--- a/servers/physics_2d/area_pair_2d_sw.cpp
+++ b/servers/physics_2d/area_pair_2d_sw.cpp
@@ -29,124 +29,105 @@
#include "area_pair_2d_sw.h"
#include "collision_solver_2d_sw.h"
-
bool AreaPair2DSW::setup(real_t p_step) {
- bool result = area->test_collision_mask(body) && CollisionSolver2DSW::solve(body->get_shape(body_shape),body->get_transform() * body->get_shape_transform(body_shape),Vector2(),area->get_shape(area_shape),area->get_transform() * area->get_shape_transform(area_shape),Vector2(),NULL,this);
+ bool result = area->test_collision_mask(body) && CollisionSolver2DSW::solve(body->get_shape(body_shape), body->get_transform() * body->get_shape_transform(body_shape), Vector2(), area->get_shape(area_shape), area->get_transform() * area->get_shape_transform(area_shape), Vector2(), NULL, this);
- if (result!=colliding) {
+ if (result != colliding) {
if (result) {
- if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
body->add_area(area);
if (area->has_monitor_callback())
- area->add_body_to_query(body,body_shape,area_shape);
+ area->add_body_to_query(body, body_shape, area_shape);
} else {
- if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
body->remove_area(area);
if (area->has_monitor_callback())
- area->remove_body_from_query(body,body_shape,area_shape);
-
+ area->remove_body_from_query(body, body_shape, area_shape);
}
- colliding=result;
-
+ colliding = result;
}
return false; //never do any post solving
}
void AreaPair2DSW::solve(real_t p_step) {
-
-
}
+AreaPair2DSW::AreaPair2DSW(Body2DSW *p_body, int p_body_shape, Area2DSW *p_area, int p_area_shape) {
-AreaPair2DSW::AreaPair2DSW(Body2DSW *p_body,int p_body_shape, Area2DSW *p_area,int p_area_shape) {
-
-
- body=p_body;
- area=p_area;
- body_shape=p_body_shape;
- area_shape=p_area_shape;
- colliding=false;
- body->add_constraint(this,0);
+ body = p_body;
+ area = p_area;
+ body_shape = p_body_shape;
+ area_shape = p_area_shape;
+ colliding = false;
+ body->add_constraint(this, 0);
area->add_constraint(this);
- if (p_body->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) //need to be active to process pair
+ if (p_body->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) //need to be active to process pair
p_body->set_active(true);
-
}
AreaPair2DSW::~AreaPair2DSW() {
if (colliding) {
- if (area->get_space_override_mode()!=Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
+ if (area->get_space_override_mode() != Physics2DServer::AREA_SPACE_OVERRIDE_DISABLED)
body->remove_area(area);
if (area->has_monitor_callback())
- area->remove_body_from_query(body,body_shape,area_shape);
-
-
+ area->remove_body_from_query(body, body_shape, area_shape);
}
body->remove_constraint(this);
area->remove_constraint(this);
}
-
//////////////////////////////////
-
-
bool Area2Pair2DSW::setup(real_t p_step) {
- bool result = area_a->test_collision_mask(area_b) && CollisionSolver2DSW::solve(area_a->get_shape(shape_a),area_a->get_transform() * area_a->get_shape_transform(shape_a),Vector2(),area_b->get_shape(shape_b),area_b->get_transform() * area_b->get_shape_transform(shape_b),Vector2(),NULL,this);
+ bool result = area_a->test_collision_mask(area_b) && CollisionSolver2DSW::solve(area_a->get_shape(shape_a), area_a->get_transform() * area_a->get_shape_transform(shape_a), Vector2(), area_b->get_shape(shape_b), area_b->get_transform() * area_b->get_shape_transform(shape_b), Vector2(), NULL, this);
- if (result!=colliding) {
+ if (result != colliding) {
if (result) {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->add_area_to_query(area_a,shape_a,shape_b);
+ area_b->add_area_to_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->add_area_to_query(area_b,shape_b,shape_a);
+ area_a->add_area_to_query(area_b, shape_b, shape_a);
} else {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->remove_area_from_query(area_a,shape_a,shape_b);
+ area_b->remove_area_from_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->remove_area_from_query(area_b,shape_b,shape_a);
+ area_a->remove_area_from_query(area_b, shape_b, shape_a);
}
- colliding=result;
-
+ colliding = result;
}
return false; //never do any post solving
}
void Area2Pair2DSW::solve(real_t p_step) {
-
-
}
+Area2Pair2DSW::Area2Pair2DSW(Area2DSW *p_area_a, int p_shape_a, Area2DSW *p_area_b, int p_shape_b) {
-Area2Pair2DSW::Area2Pair2DSW(Area2DSW *p_area_a,int p_shape_a, Area2DSW *p_area_b,int p_shape_b) {
-
-
- area_a=p_area_a;
- area_b=p_area_b;
- shape_a=p_shape_a;
- shape_b=p_shape_b;
- colliding=false;
+ area_a = p_area_a;
+ area_b = p_area_b;
+ shape_a = p_shape_a;
+ shape_b = p_shape_b;
+ colliding = false;
area_a->add_constraint(this);
area_b->add_constraint(this);
-
}
Area2Pair2DSW::~Area2Pair2DSW() {
@@ -154,10 +135,10 @@ Area2Pair2DSW::~Area2Pair2DSW() {
if (colliding) {
if (area_b->has_area_monitor_callback() && area_a->is_monitorable())
- area_b->remove_area_from_query(area_a,shape_a,shape_b);
+ area_b->remove_area_from_query(area_a, shape_a, shape_b);
if (area_a->has_area_monitor_callback() && area_b->is_monitorable())
- area_a->remove_area_from_query(area_b,shape_b,shape_a);
+ area_a->remove_area_from_query(area_b, shape_b, shape_a);
}
area_a->remove_constraint(this);
diff --git a/servers/physics_2d/area_pair_2d_sw.h b/servers/physics_2d/area_pair_2d_sw.h
index 219ca30c4b..78be9572bf 100644
--- a/servers/physics_2d/area_pair_2d_sw.h
+++ b/servers/physics_2d/area_pair_2d_sw.h
@@ -29,9 +29,9 @@
#ifndef AREA_PAIR_2D_SW_H
#define AREA_PAIR_2D_SW_H
-#include "constraint_2d_sw.h"
-#include "body_2d_sw.h"
#include "area_2d_sw.h"
+#include "body_2d_sw.h"
+#include "constraint_2d_sw.h"
class AreaPair2DSW : public Constraint2DSW {
@@ -40,16 +40,15 @@ class AreaPair2DSW : public Constraint2DSW {
int body_shape;
int area_shape;
bool colliding;
-public:
+public:
bool setup(real_t p_step);
void solve(real_t p_step);
- AreaPair2DSW(Body2DSW *p_body,int p_body_shape, Area2DSW *p_area,int p_area_shape);
+ AreaPair2DSW(Body2DSW *p_body, int p_body_shape, Area2DSW *p_area, int p_area_shape);
~AreaPair2DSW();
};
-
class Area2Pair2DSW : public Constraint2DSW {
Area2DSW *area_a;
@@ -57,15 +56,13 @@ class Area2Pair2DSW : public Constraint2DSW {
int shape_a;
int shape_b;
bool colliding;
-public:
+public:
bool setup(real_t p_step);
void solve(real_t p_step);
- Area2Pair2DSW(Area2DSW *p_area_a,int p_shape_a, Area2DSW *p_area_b,int p_shape_b);
+ Area2Pair2DSW(Area2DSW *p_area_a, int p_shape_a, Area2DSW *p_area_b, int p_shape_b);
~Area2Pair2DSW();
};
-
#endif // AREA_PAIR_2D_SW_H
-
diff --git a/servers/physics_2d/body_2d_sw.cpp b/servers/physics_2d/body_2d_sw.cpp
index 0dab534ef9..d49dd35ade 100644
--- a/servers/physics_2d/body_2d_sw.cpp
+++ b/servers/physics_2d/body_2d_sw.cpp
@@ -27,107 +27,98 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "body_2d_sw.h"
-#include "space_2d_sw.h"
#include "area_2d_sw.h"
#include "physics_2d_server_sw.h"
+#include "space_2d_sw.h"
void Body2DSW::_update_inertia() {
if (!user_inertia && get_space() && !inertia_update_list.in_list())
get_space()->body_add_to_inertia_update_list(&inertia_update_list);
-
}
-
-
void Body2DSW::update_inertias() {
//update shapes and motions
- switch(mode) {
+ switch (mode) {
case Physics2DServer::BODY_MODE_RIGID: {
- if(user_inertia) break;
+ if (user_inertia) break;
//update tensor for allshapes, not the best way but should be somehow OK. (inspired from bullet)
- real_t total_area=0;
+ real_t total_area = 0;
- for (int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
- total_area+=get_shape_aabb(i).get_area();
+ total_area += get_shape_aabb(i).get_area();
}
- real_t _inertia=0;
+ real_t _inertia = 0;
- for (int i=0;i<get_shape_count();i++) {
+ for (int i = 0; i < get_shape_count(); i++) {
- const Shape2DSW* shape=get_shape(i);
+ const Shape2DSW *shape = get_shape(i);
- real_t area=get_shape_aabb(i).get_area();
+ real_t area = get_shape_aabb(i).get_area();
real_t mass = area * this->mass / total_area;
Transform2D mtx = get_shape_transform(i);
Vector2 scale = mtx.get_scale();
- _inertia += shape->get_moment_of_inertia(mass,scale) + mass * mtx.get_origin().length_squared();
+ _inertia += shape->get_moment_of_inertia(mass, scale) + mass * mtx.get_origin().length_squared();
//Rect2 ab = get_shape_aabb(i);
//_inertia+=mass*ab.size.dot(ab.size)/12.0f;
-
-
-
}
- if (_inertia!=0)
- _inv_inertia=1.0/_inertia;
+ if (_inertia != 0)
+ _inv_inertia = 1.0 / _inertia;
else
- _inv_inertia=0.0; //wathever
+ _inv_inertia = 0.0; //wathever
if (mass)
- _inv_mass=1.0/mass;
+ _inv_mass = 1.0 / mass;
else
- _inv_mass=0;
+ _inv_mass = 0;
} break;
case Physics2DServer::BODY_MODE_KINEMATIC:
case Physics2DServer::BODY_MODE_STATIC: {
- _inv_inertia=0;
- _inv_mass=0;
+ _inv_inertia = 0;
+ _inv_mass = 0;
} break;
case Physics2DServer::BODY_MODE_CHARACTER: {
- _inv_inertia=0;
- _inv_mass=1.0/mass;
+ _inv_inertia = 0;
+ _inv_mass = 1.0 / mass;
} break;
}
//_update_inertia_tensor();
//_update_shapes();
-
}
-
-
void Body2DSW::set_active(bool p_active) {
- if (active==p_active)
+ if (active == p_active)
return;
- active=p_active;
+ active = p_active;
if (!p_active) {
if (get_space())
get_space()->body_remove_from_active_list(&active_list);
} else {
- if (mode==Physics2DServer::BODY_MODE_STATIC)
+ if (mode == Physics2DServer::BODY_MODE_STATIC)
return; //static bodies can't become active
if (get_space())
get_space()->body_add_to_active_list(&active_list);
//still_time=0;
}
-/*
+ /*
if (!space)
return;
@@ -140,27 +131,25 @@ void Body2DSW::set_active(bool p_active) {
*/
}
-
-
void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::BODY_PARAM_BOUNCE: {
- bounce=p_value;
+ bounce = p_value;
} break;
case Physics2DServer::BODY_PARAM_FRICTION: {
- friction=p_value;
+ friction = p_value;
} break;
case Physics2DServer::BODY_PARAM_MASS: {
- ERR_FAIL_COND(p_value<=0);
- mass=p_value;
+ ERR_FAIL_COND(p_value <= 0);
+ mass = p_value;
_update_inertia();
} break;
case Physics2DServer::BODY_PARAM_INERTIA: {
- if(p_value<=0) {
+ if (p_value <= 0) {
user_inertia = false;
_update_inertia();
} else {
@@ -169,23 +158,23 @@ void Body2DSW::set_param(Physics2DServer::BodyParameter p_param, real_t p_value)
}
} break;
case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: {
- gravity_scale=p_value;
+ gravity_scale = p_value;
} break;
case Physics2DServer::BODY_PARAM_LINEAR_DAMP: {
- linear_damp=p_value;
+ linear_damp = p_value;
} break;
case Physics2DServer::BODY_PARAM_ANGULAR_DAMP: {
- angular_damp=p_value;
+ angular_damp = p_value;
} break;
- default:{}
+ default: {}
}
}
real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::BODY_PARAM_BOUNCE: {
return bounce;
@@ -198,7 +187,7 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
return mass;
} break;
case Physics2DServer::BODY_PARAM_INERTIA: {
- return _inv_inertia==0 ? 0 : 1.0 / _inv_inertia;
+ return _inv_inertia == 0 ? 0 : 1.0 / _inv_inertia;
} break;
case Physics2DServer::BODY_PARAM_GRAVITY_SCALE: {
return gravity_scale;
@@ -211,7 +200,7 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
return angular_damp;
} break;
- default:{}
+ default: {}
}
return 0;
@@ -219,33 +208,33 @@ real_t Body2DSW::get_param(Physics2DServer::BodyParameter p_param) const {
void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) {
- Physics2DServer::BodyMode prev=mode;
- mode=p_mode;
+ Physics2DServer::BodyMode prev = mode;
+ mode = p_mode;
- switch(p_mode) {
- //CLEAR UP EVERYTHING IN CASE IT NOT WORKS!
+ switch (p_mode) {
+ //CLEAR UP EVERYTHING IN CASE IT NOT WORKS!
case Physics2DServer::BODY_MODE_STATIC:
case Physics2DServer::BODY_MODE_KINEMATIC: {
_set_inv_transform(get_transform().affine_inverse());
- _inv_mass=0;
- _set_static(p_mode==Physics2DServer::BODY_MODE_STATIC);
- set_active(p_mode==Physics2DServer::BODY_MODE_KINEMATIC && contacts.size());
- linear_velocity=Vector2();
- angular_velocity=0;
- if (mode==Physics2DServer::BODY_MODE_KINEMATIC && prev!=mode) {
- first_time_kinematic=true;
+ _inv_mass = 0;
+ _set_static(p_mode == Physics2DServer::BODY_MODE_STATIC);
+ set_active(p_mode == Physics2DServer::BODY_MODE_KINEMATIC && contacts.size());
+ linear_velocity = Vector2();
+ angular_velocity = 0;
+ if (mode == Physics2DServer::BODY_MODE_KINEMATIC && prev != mode) {
+ first_time_kinematic = true;
}
} break;
case Physics2DServer::BODY_MODE_RIGID: {
- _inv_mass=mass>0?(1.0/mass):0;
+ _inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
case Physics2DServer::BODY_MODE_CHARACTER: {
- _inv_mass=mass>0?(1.0/mass):0;
+ _inv_mass = mass > 0 ? (1.0 / mass) : 0;
_set_static(false);
} break;
}
@@ -255,7 +244,6 @@ void Body2DSW::set_mode(Physics2DServer::BodyMode p_mode) {
if (get_space())
_update_queries();
*/
-
}
Physics2DServer::BodyMode Body2DSW::get_mode() const {
@@ -268,35 +256,33 @@ void Body2DSW::_shapes_changed() {
wakeup_neighbours();
}
-void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_variant) {
+void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant &p_variant) {
- switch(p_state) {
+ switch (p_state) {
case Physics2DServer::BODY_STATE_TRANSFORM: {
+ if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
- if (mode==Physics2DServer::BODY_MODE_KINEMATIC) {
-
- new_transform=p_variant;
+ new_transform = p_variant;
//wakeup_neighbours();
set_active(true);
if (first_time_kinematic) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
- first_time_kinematic=false;
+ first_time_kinematic = false;
}
- } else if (mode==Physics2DServer::BODY_MODE_STATIC) {
+ } else if (mode == Physics2DServer::BODY_MODE_STATIC) {
_set_transform(p_variant);
_set_inv_transform(get_transform().affine_inverse());
wakeup_neighbours();
} else {
Transform2D t = p_variant;
t.orthonormalize();
- new_transform=get_transform(); //used as old to compute motion
- if (t==new_transform)
+ new_transform = get_transform(); //used as old to compute motion
+ if (t == new_transform)
break;
_set_transform(t);
_set_inv_transform(get_transform().inverse());
-
}
wakeup();
@@ -307,7 +293,7 @@ void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_va
if (mode==Physics2DServer::BODY_MODE_STATIC)
break;
*/
- linear_velocity=p_variant;
+ linear_velocity = p_variant;
wakeup();
} break;
@@ -316,38 +302,37 @@ void Body2DSW::set_state(Physics2DServer::BodyState p_state, const Variant& p_va
if (mode!=Physics2DServer::BODY_MODE_RIGID)
break;
*/
- angular_velocity=p_variant;
+ angular_velocity = p_variant;
wakeup();
} break;
case Physics2DServer::BODY_STATE_SLEEPING: {
//?
- if (mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC)
+ if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC)
break;
- bool do_sleep=p_variant;
+ bool do_sleep = p_variant;
if (do_sleep) {
- linear_velocity=Vector2();
+ linear_velocity = Vector2();
//biased_linear_velocity=Vector3();
- angular_velocity=0;
+ angular_velocity = 0;
//biased_angular_velocity=Vector3();
set_active(false);
} else {
- if (mode!=Physics2DServer::BODY_MODE_STATIC)
+ if (mode != Physics2DServer::BODY_MODE_STATIC)
set_active(true);
}
} break;
case Physics2DServer::BODY_STATE_CAN_SLEEP: {
- can_sleep=p_variant;
- if (mode==Physics2DServer::BODY_MODE_RIGID && !active && !can_sleep)
+ can_sleep = p_variant;
+ if (mode == Physics2DServer::BODY_MODE_RIGID && !active && !can_sleep)
set_active(true);
} break;
}
-
}
Variant Body2DSW::get_state(Physics2DServer::BodyState p_state) const {
- switch(p_state) {
+ switch (p_state) {
case Physics2DServer::BODY_STATE_TRANSFORM: {
return get_transform();
} break;
@@ -368,8 +353,7 @@ Variant Body2DSW::get_state(Physics2DServer::BodyState p_state) const {
return Variant();
}
-
-void Body2DSW::set_space(Space2DSW *p_space){
+void Body2DSW::set_space(Space2DSW *p_space) {
if (get_space()) {
@@ -381,7 +365,6 @@ void Body2DSW::set_space(Space2DSW *p_space){
get_space()->body_remove_from_active_list(&active_list);
if (direct_state_query_list.in_list())
get_space()->body_remove_from_state_query_list(&direct_state_query_list);
-
}
_set_space(p_space);
@@ -398,18 +381,17 @@ void Body2DSW::set_space(Space2DSW *p_space){
set_active(true);
}
*/
-
}
- first_integration=false;
+ first_integration = false;
}
void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) {
if (p_area->is_gravity_point()) {
- if(p_area->get_gravity_distance_scale() > 0) {
+ if (p_area->get_gravity_distance_scale() > 0) {
Vector2 v = p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin();
- gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale()+1, 2) );
+ gravity += v.normalized() * (p_area->get_gravity() / Math::pow(v.length() * p_area->get_gravity_distance_scale() + 1, 2));
} else {
gravity += (p_area->get_transform().xform(p_area->get_gravity_vector()) - get_transform().get_origin()).normalized() * p_area->get_gravity();
}
@@ -423,7 +405,7 @@ void Body2DSW::_compute_area_gravity_and_dampenings(const Area2DSW *p_area) {
void Body2DSW::integrate_forces(real_t p_step) {
- if (mode==Physics2DServer::BODY_MODE_STATIC)
+ if (mode == Physics2DServer::BODY_MODE_STATIC)
return;
Area2DSW *def_area = get_space()->get_default_area();
@@ -432,47 +414,47 @@ void Body2DSW::integrate_forces(real_t p_step) {
int ac = areas.size();
bool stopped = false;
- gravity = Vector2(0,0);
+ gravity = Vector2(0, 0);
area_angular_damp = 0;
area_linear_damp = 0;
if (ac) {
areas.sort();
const AreaCMP *aa = &areas[0];
// damp_area = aa[ac-1].area;
- for(int i=ac-1;i>=0 && !stopped;i--) {
- Physics2DServer::AreaSpaceOverrideMode mode=aa[i].area->get_space_override_mode();
+ for (int i = ac - 1; i >= 0 && !stopped; i--) {
+ Physics2DServer::AreaSpaceOverrideMode mode = aa[i].area->get_space_override_mode();
switch (mode) {
case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE:
case Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE: {
_compute_area_gravity_and_dampenings(aa[i].area);
- stopped = mode==Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
+ stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_COMBINE_REPLACE;
} break;
case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE:
case Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE_COMBINE: {
- gravity = Vector2(0,0);
+ gravity = Vector2(0, 0);
area_angular_damp = 0;
area_linear_damp = 0;
_compute_area_gravity_and_dampenings(aa[i].area);
- stopped = mode==Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE;
+ stopped = mode == Physics2DServer::AREA_SPACE_OVERRIDE_REPLACE;
} break;
default: {}
}
}
}
- if( !stopped ) {
+ if (!stopped) {
_compute_area_gravity_and_dampenings(def_area);
}
- gravity*=gravity_scale;
+ gravity *= gravity_scale;
// If less than 0, override dampenings with that of the Body2D
- if (angular_damp>=0)
+ if (angular_damp >= 0)
area_angular_damp = angular_damp;
/*
else
area_angular_damp=damp_area->get_angular_damp();
*/
- if (linear_damp>=0)
+ if (linear_damp >= 0)
area_linear_damp = linear_damp;
/*
else
@@ -480,19 +462,18 @@ void Body2DSW::integrate_forces(real_t p_step) {
*/
Vector2 motion;
- bool do_motion=false;
+ bool do_motion = false;
- if (mode==Physics2DServer::BODY_MODE_KINEMATIC) {
+ if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
//compute motion, angular and etc. velocities from prev transform
motion = new_transform.get_origin() - get_transform().get_origin();
- linear_velocity = motion/p_step;
+ linear_velocity = motion / p_step;
real_t rot = new_transform.get_rotation() - get_transform().get_rotation();
angular_velocity = rot / p_step;
-
- do_motion=true;
+ do_motion = true;
/*
for(int i=0;i<get_shape_count();i++) {
@@ -505,102 +486,96 @@ void Body2DSW::integrate_forces(real_t p_step) {
if (!omit_force_integration && !first_integration) {
//overriden by direct state query
- Vector2 force=gravity*mass;
- force+=applied_force;
- real_t torque=applied_torque;
+ Vector2 force = gravity * mass;
+ force += applied_force;
+ real_t torque = applied_torque;
real_t damp = 1.0 - p_step * area_linear_damp;
- if (damp<0) // reached zero in the given time
- damp=0;
+ if (damp < 0) // reached zero in the given time
+ damp = 0;
real_t angular_damp = 1.0 - p_step * area_angular_damp;
- if (angular_damp<0) // reached zero in the given time
- angular_damp=0;
+ if (angular_damp < 0) // reached zero in the given time
+ angular_damp = 0;
- linear_velocity*=damp;
- angular_velocity*=angular_damp;
+ linear_velocity *= damp;
+ angular_velocity *= angular_damp;
- linear_velocity+=_inv_mass * force * p_step;
- angular_velocity+=_inv_inertia * torque * p_step;
+ linear_velocity += _inv_mass * force * p_step;
+ angular_velocity += _inv_inertia * torque * p_step;
}
- if (continuous_cd_mode!=Physics2DServer::CCD_MODE_DISABLED) {
+ if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED) {
motion = new_transform.get_origin() - get_transform().get_origin();
//linear_velocity*p_step;
- do_motion=true;
+ do_motion = true;
}
}
-
//motion=linear_velocity*p_step;
- first_integration=false;
- biased_angular_velocity=0;
- biased_linear_velocity=Vector2();
+ first_integration = false;
+ biased_angular_velocity = 0;
+ biased_linear_velocity = Vector2();
- if (do_motion) {//shapes temporarily extend for raycast
+ if (do_motion) { //shapes temporarily extend for raycast
_update_shapes_with_motion(motion);
}
// damp_area=NULL; // clear the area, so it is set in the next frame
- def_area=NULL; // clear the area, so it is set in the next frame
- contact_count=0;
-
+ def_area = NULL; // clear the area, so it is set in the next frame
+ contact_count = 0;
}
void Body2DSW::integrate_velocities(real_t p_step) {
- if (mode==Physics2DServer::BODY_MODE_STATIC)
+ if (mode == Physics2DServer::BODY_MODE_STATIC)
return;
if (fi_callback)
get_space()->body_add_to_state_query_list(&direct_state_query_list);
- if (mode==Physics2DServer::BODY_MODE_KINEMATIC) {
+ if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
- _set_transform(new_transform,false);
+ _set_transform(new_transform, false);
_set_inv_transform(new_transform.affine_inverse());
- if (contacts.size()==0 && linear_velocity==Vector2() && angular_velocity==0)
+ if (contacts.size() == 0 && linear_velocity == Vector2() && angular_velocity == 0)
set_active(false); //stopped moving, deactivate
return;
}
- real_t total_angular_velocity = angular_velocity+biased_angular_velocity;
- Vector2 total_linear_velocity=linear_velocity+biased_linear_velocity;
+ real_t total_angular_velocity = angular_velocity + biased_angular_velocity;
+ Vector2 total_linear_velocity = linear_velocity + biased_linear_velocity;
real_t angle = get_transform().get_rotation() + total_angular_velocity * p_step;
Vector2 pos = get_transform().get_origin() + total_linear_velocity * p_step;
- _set_transform(Transform2D(angle,pos),continuous_cd_mode==Physics2DServer::CCD_MODE_DISABLED);
+ _set_transform(Transform2D(angle, pos), continuous_cd_mode == Physics2DServer::CCD_MODE_DISABLED);
_set_inv_transform(get_transform().inverse());
- if (continuous_cd_mode!=Physics2DServer::CCD_MODE_DISABLED)
- new_transform=get_transform();
+ if (continuous_cd_mode != Physics2DServer::CCD_MODE_DISABLED)
+ new_transform = get_transform();
//_update_inertia_tensor();
}
-
-
void Body2DSW::wakeup_neighbours() {
+ for (Map<Constraint2DSW *, int>::Element *E = constraint_map.front(); E; E = E->next()) {
-
- for(Map<Constraint2DSW*,int>::Element *E=constraint_map.front();E;E=E->next()) {
-
- const Constraint2DSW *c=E->key();
+ const Constraint2DSW *c = E->key();
Body2DSW **n = c->get_body_ptr();
- int bc=c->get_body_count();
+ int bc = c->get_body_count();
- for(int i=0;i<bc;i++) {
+ for (int i = 0; i < bc; i++) {
- if (i==E->get())
+ if (i == E->get())
continue;
Body2DSW *b = n[i];
- if (b->mode!=Physics2DServer::BODY_MODE_RIGID)
+ if (b->mode != Physics2DServer::BODY_MODE_RIGID)
continue;
if (!b->is_active())
@@ -611,116 +586,103 @@ void Body2DSW::wakeup_neighbours() {
void Body2DSW::call_queries() {
-
if (fi_callback) {
Physics2DDirectBodyStateSW *dbs = Physics2DDirectBodyStateSW::singleton;
- dbs->body=this;
-
- Variant v=dbs;
- const Variant *vp[2]={&v,&fi_callback->callback_udata};
+ dbs->body = this;
+ Variant v = dbs;
+ const Variant *vp[2] = { &v, &fi_callback->callback_udata };
Object *obj = ObjectDB::get_instance(fi_callback->id);
if (!obj) {
- set_force_integration_callback(0,StringName());
+ set_force_integration_callback(0, StringName());
} else {
Variant::CallError ce;
if (fi_callback->callback_udata.get_type()) {
- obj->call(fi_callback->method,vp,2,ce);
+ obj->call(fi_callback->method, vp, 2, ce);
} else {
- obj->call(fi_callback->method,vp,1,ce);
+ obj->call(fi_callback->method, vp, 1, ce);
}
}
-
-
}
-
}
+bool Body2DSW::sleep_test(real_t p_step) {
-bool Body2DSW::sleep_test(real_t p_step) {
-
- if (mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC)
+ if (mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC)
return true; //
- else if (mode==Physics2DServer::BODY_MODE_CHARACTER)
+ else if (mode == Physics2DServer::BODY_MODE_CHARACTER)
return !active; // characters and kinematic bodies don't sleep unless asked to sleep
else if (!can_sleep)
return false;
+ if (Math::abs(angular_velocity) < get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold() * get_space()->get_body_linear_velocity_sleep_treshold()) {
-
-
- if (Math::abs(angular_velocity)<get_space()->get_body_angular_velocity_sleep_treshold() && Math::abs(linear_velocity.length_squared()) < get_space()->get_body_linear_velocity_sleep_treshold()*get_space()->get_body_linear_velocity_sleep_treshold()) {
-
- still_time+=p_step;
+ still_time += p_step;
return still_time > get_space()->get_body_time_to_sleep();
} else {
- still_time=0; //maybe this should be set to 0 on set_active?
+ still_time = 0; //maybe this should be set to 0 on set_active?
return false;
}
}
-
-void Body2DSW::set_force_integration_callback(ObjectID p_id,const StringName& p_method,const Variant& p_udata) {
+void Body2DSW::set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata) {
if (fi_callback) {
memdelete(fi_callback);
- fi_callback=NULL;
+ fi_callback = NULL;
}
+ if (p_id != 0) {
- if (p_id!=0) {
-
- fi_callback=memnew(ForceIntegrationCallback);
- fi_callback->id=p_id;
- fi_callback->method=p_method;
- fi_callback->callback_udata=p_udata;
+ fi_callback = memnew(ForceIntegrationCallback);
+ fi_callback->id = p_id;
+ fi_callback->method = p_method;
+ fi_callback->callback_udata = p_udata;
}
-
}
-Body2DSW::Body2DSW() : CollisionObject2DSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) {
-
-
- mode=Physics2DServer::BODY_MODE_RIGID;
- active=true;
- angular_velocity=0;
- biased_angular_velocity=0;
- mass=1;
- user_inertia=false;
- _inv_inertia=0;
- _inv_mass=1;
- bounce=0;
- friction=1;
- omit_force_integration=false;
- applied_torque=0;
- island_step=0;
- island_next=NULL;
- island_list_next=NULL;
+Body2DSW::Body2DSW()
+ : CollisionObject2DSW(TYPE_BODY), active_list(this), inertia_update_list(this), direct_state_query_list(this) {
+
+ mode = Physics2DServer::BODY_MODE_RIGID;
+ active = true;
+ angular_velocity = 0;
+ biased_angular_velocity = 0;
+ mass = 1;
+ user_inertia = false;
+ _inv_inertia = 0;
+ _inv_mass = 1;
+ bounce = 0;
+ friction = 1;
+ omit_force_integration = false;
+ applied_torque = 0;
+ island_step = 0;
+ island_next = NULL;
+ island_list_next = NULL;
_set_static(false);
- first_time_kinematic=false;
- linear_damp=-1;
- angular_damp=-1;
- area_angular_damp=0;
- area_linear_damp=0;
- contact_count=0;
- gravity_scale=1.0;
- using_one_way_cache=false;
- one_way_collision_max_depth=0.1;
- first_integration=false;
-
- still_time=0;
- continuous_cd_mode=Physics2DServer::CCD_MODE_DISABLED;
- can_sleep=false;
- fi_callback=NULL;
-
+ first_time_kinematic = false;
+ linear_damp = -1;
+ angular_damp = -1;
+ area_angular_damp = 0;
+ area_linear_damp = 0;
+ contact_count = 0;
+ gravity_scale = 1.0;
+ using_one_way_cache = false;
+ one_way_collision_max_depth = 0.1;
+ first_integration = false;
+
+ still_time = 0;
+ continuous_cd_mode = Physics2DServer::CCD_MODE_DISABLED;
+ can_sleep = false;
+ fi_callback = NULL;
}
Body2DSW::~Body2DSW() {
@@ -729,17 +691,16 @@ Body2DSW::~Body2DSW() {
memdelete(fi_callback);
}
-Physics2DDirectBodyStateSW *Physics2DDirectBodyStateSW::singleton=NULL;
+Physics2DDirectBodyStateSW *Physics2DDirectBodyStateSW::singleton = NULL;
-Physics2DDirectSpaceState* Physics2DDirectBodyStateSW::get_space_state() {
+Physics2DDirectSpaceState *Physics2DDirectBodyStateSW::get_space_state() {
return body->get_space()->get_direct_state();
}
-
Variant Physics2DDirectBodyStateSW::get_contact_collider_shape_metadata(int p_contact_idx) const {
- ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Variant());
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Variant());
if (!Physics2DServerSW::singletonsw->body_owner.owns(body->contacts[p_contact_idx].collider)) {
@@ -748,11 +709,10 @@ Variant Physics2DDirectBodyStateSW::get_contact_collider_shape_metadata(int p_co
Body2DSW *other = Physics2DServerSW::singletonsw->body_owner.get(body->contacts[p_contact_idx].collider);
int sidx = body->contacts[p_contact_idx].collider_shape;
- if (sidx<0 || sidx>=other->get_shape_count()) {
+ if (sidx < 0 || sidx >= other->get_shape_count()) {
return Variant();
}
-
return other->get_shape_metadata(sidx);
}
diff --git a/servers/physics_2d/body_2d_sw.h b/servers/physics_2d/body_2d_sw.h
index 3fb01959a9..7e4fef8df3 100644
--- a/servers/physics_2d/body_2d_sw.h
+++ b/servers/physics_2d/body_2d_sw.h
@@ -29,16 +29,14 @@
#ifndef BODY_2D_SW_H
#define BODY_2D_SW_H
+#include "area_2d_sw.h"
#include "collision_object_2d_sw.h"
#include "vset.h"
-#include "area_2d_sw.h"
class Constraint2DSW;
-
class Body2DSW : public CollisionObject2DSW {
-
Physics2DServer::BodyMode mode;
Vector2 biased_linear_velocity;
@@ -71,7 +69,6 @@ class Body2DSW : public CollisionObject2DSW {
Vector2 one_way_collision_direction;
real_t one_way_collision_max_depth;
-
SelfList<Body2DSW> active_list;
SelfList<Body2DSW> inertia_update_list;
SelfList<Body2DSW> direct_state_query_list;
@@ -88,25 +85,25 @@ class Body2DSW : public CollisionObject2DSW {
virtual void _shapes_changed();
Transform2D new_transform;
-
- Map<Constraint2DSW*,int> constraint_map;
+ Map<Constraint2DSW *, int> constraint_map;
struct AreaCMP {
Area2DSW *area;
int refCount;
- _FORCE_INLINE_ bool operator==(const AreaCMP& p_cmp) const { return area->get_self() == p_cmp.area->get_self();}
- _FORCE_INLINE_ bool operator<(const AreaCMP& p_cmp) const { return area->get_priority() < p_cmp.area->get_priority();}
+ _FORCE_INLINE_ bool operator==(const AreaCMP &p_cmp) const { return area->get_self() == p_cmp.area->get_self(); }
+ _FORCE_INLINE_ bool operator<(const AreaCMP &p_cmp) const { return area->get_priority() < p_cmp.area->get_priority(); }
_FORCE_INLINE_ AreaCMP() {}
- _FORCE_INLINE_ AreaCMP(Area2DSW *p_area) { area=p_area; refCount=1;}
+ _FORCE_INLINE_ AreaCMP(Area2DSW *p_area) {
+ area = p_area;
+ refCount = 1;
+ }
};
-
Vector<AreaCMP> areas;
struct Contact {
-
Vector2 local_pos;
Vector2 local_normal;
real_t depth;
@@ -130,24 +127,20 @@ class Body2DSW : public CollisionObject2DSW {
ForceIntegrationCallback *fi_callback;
-
uint64_t island_step;
Body2DSW *island_next;
Body2DSW *island_list_next;
_FORCE_INLINE_ void _compute_area_gravity_and_dampenings(const Area2DSW *p_area);
-friend class Physics2DDirectBodyStateSW; // i give up, too many functions to expose
+ friend class Physics2DDirectBodyStateSW; // i give up, too many functions to expose
public:
-
-
- void set_force_integration_callback(ObjectID p_id, const StringName& p_method, const Variant &p_udata=Variant());
-
+ void set_force_integration_callback(ObjectID p_id, const StringName &p_method, const Variant &p_udata = Variant());
_FORCE_INLINE_ void add_area(Area2DSW *p_area) {
int index = areas.find(AreaCMP(p_area));
- if( index > -1 ) {
+ if (index > -1) {
areas[index].refCount += 1;
} else {
areas.ordered_insert(AreaCMP(p_area));
@@ -156,62 +149,64 @@ public:
_FORCE_INLINE_ void remove_area(Area2DSW *p_area) {
int index = areas.find(AreaCMP(p_area));
- if( index > -1 ) {
+ if (index > -1) {
areas[index].refCount -= 1;
- if( areas[index].refCount < 1 )
+ if (areas[index].refCount < 1)
areas.remove(index);
}
}
- _FORCE_INLINE_ void set_max_contacts_reported(int p_size) { contacts.resize(p_size); contact_count=0; if (mode==Physics2DServer::BODY_MODE_KINEMATIC && p_size) set_active(true);}
+ _FORCE_INLINE_ void set_max_contacts_reported(int p_size) {
+ contacts.resize(p_size);
+ contact_count = 0;
+ if (mode == Physics2DServer::BODY_MODE_KINEMATIC && p_size) set_active(true);
+ }
_FORCE_INLINE_ int get_max_contacts_reported() const { return contacts.size(); }
_FORCE_INLINE_ bool can_report_contacts() const { return !contacts.empty(); }
- _FORCE_INLINE_ void add_contact(const Vector2& p_local_pos,const Vector2& p_local_normal, real_t p_depth, int p_local_shape, const Vector2& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector2& p_collider_velocity_at_pos);
+ _FORCE_INLINE_ void add_contact(const Vector2 &p_local_pos, const Vector2 &p_local_normal, real_t p_depth, int p_local_shape, const Vector2 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector2 &p_collider_velocity_at_pos);
-
- _FORCE_INLINE_ void add_exception(const RID& p_exception) { exceptions.insert(p_exception);}
- _FORCE_INLINE_ void remove_exception(const RID& p_exception) { exceptions.erase(p_exception);}
- _FORCE_INLINE_ bool has_exception(const RID& p_exception) const { return exceptions.has(p_exception);}
- _FORCE_INLINE_ const VSet<RID>& get_exceptions() const { return exceptions;}
+ _FORCE_INLINE_ void add_exception(const RID &p_exception) { exceptions.insert(p_exception); }
+ _FORCE_INLINE_ void remove_exception(const RID &p_exception) { exceptions.erase(p_exception); }
+ _FORCE_INLINE_ bool has_exception(const RID &p_exception) const { return exceptions.has(p_exception); }
+ _FORCE_INLINE_ const VSet<RID> &get_exceptions() const { return exceptions; }
_FORCE_INLINE_ uint64_t get_island_step() const { return island_step; }
- _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; }
+ _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; }
- _FORCE_INLINE_ Body2DSW* get_island_next() const { return island_next; }
- _FORCE_INLINE_ void set_island_next(Body2DSW* p_next) { island_next=p_next; }
+ _FORCE_INLINE_ Body2DSW *get_island_next() const { return island_next; }
+ _FORCE_INLINE_ void set_island_next(Body2DSW *p_next) { island_next = p_next; }
- _FORCE_INLINE_ Body2DSW* get_island_list_next() const { return island_list_next; }
- _FORCE_INLINE_ void set_island_list_next(Body2DSW* p_next) { island_list_next=p_next; }
+ _FORCE_INLINE_ Body2DSW *get_island_list_next() const { return island_list_next; }
+ _FORCE_INLINE_ void set_island_list_next(Body2DSW *p_next) { island_list_next = p_next; }
- _FORCE_INLINE_ void add_constraint(Constraint2DSW* p_constraint, int p_pos) { constraint_map[p_constraint]=p_pos; }
- _FORCE_INLINE_ void remove_constraint(Constraint2DSW* p_constraint) { constraint_map.erase(p_constraint); }
- const Map<Constraint2DSW*,int>& get_constraint_map() const { return constraint_map; }
+ _FORCE_INLINE_ void add_constraint(Constraint2DSW *p_constraint, int p_pos) { constraint_map[p_constraint] = p_pos; }
+ _FORCE_INLINE_ void remove_constraint(Constraint2DSW *p_constraint) { constraint_map.erase(p_constraint); }
+ const Map<Constraint2DSW *, int> &get_constraint_map() const { return constraint_map; }
- _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration=p_omit_force_integration; }
+ _FORCE_INLINE_ void set_omit_force_integration(bool p_omit_force_integration) { omit_force_integration = p_omit_force_integration; }
_FORCE_INLINE_ bool get_omit_force_integration() const { return omit_force_integration; }
- _FORCE_INLINE_ void set_linear_velocity(const Vector2& p_velocity) {linear_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_linear_velocity(const Vector2 &p_velocity) { linear_velocity = p_velocity; }
_FORCE_INLINE_ Vector2 get_linear_velocity() const { return linear_velocity; }
- _FORCE_INLINE_ void set_angular_velocity(real_t p_velocity) { angular_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_angular_velocity(real_t p_velocity) { angular_velocity = p_velocity; }
_FORCE_INLINE_ real_t get_angular_velocity() const { return angular_velocity; }
- _FORCE_INLINE_ void set_biased_linear_velocity(const Vector2& p_velocity) {biased_linear_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_biased_linear_velocity(const Vector2 &p_velocity) { biased_linear_velocity = p_velocity; }
_FORCE_INLINE_ Vector2 get_biased_linear_velocity() const { return biased_linear_velocity; }
- _FORCE_INLINE_ void set_biased_angular_velocity(real_t p_velocity) { biased_angular_velocity=p_velocity; }
+ _FORCE_INLINE_ void set_biased_angular_velocity(real_t p_velocity) { biased_angular_velocity = p_velocity; }
_FORCE_INLINE_ real_t get_biased_angular_velocity() const { return biased_angular_velocity; }
-
- _FORCE_INLINE_ void apply_impulse(const Vector2& p_offset, const Vector2& p_impulse) {
+ _FORCE_INLINE_ void apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse) {
linear_velocity += p_impulse * _inv_mass;
angular_velocity += _inv_inertia * p_offset.cross(p_impulse);
}
- _FORCE_INLINE_ void apply_bias_impulse(const Vector2& p_pos, const Vector2& p_j) {
+ _FORCE_INLINE_ void apply_bias_impulse(const Vector2 &p_pos, const Vector2 &p_j) {
biased_linear_velocity += p_j * _inv_mass;
biased_angular_velocity += _inv_inertia * p_pos.cross(p_j);
@@ -221,45 +216,42 @@ public:
_FORCE_INLINE_ bool is_active() const { return active; }
_FORCE_INLINE_ void wakeup() {
- if ((!get_space()) || mode==Physics2DServer::BODY_MODE_STATIC || mode==Physics2DServer::BODY_MODE_KINEMATIC)
+ if ((!get_space()) || mode == Physics2DServer::BODY_MODE_STATIC || mode == Physics2DServer::BODY_MODE_KINEMATIC)
return;
set_active(true);
}
-
-
-
void set_param(Physics2DServer::BodyParameter p_param, real_t);
real_t get_param(Physics2DServer::BodyParameter p_param) const;
void set_mode(Physics2DServer::BodyMode p_mode);
Physics2DServer::BodyMode get_mode() const;
- void set_state(Physics2DServer::BodyState p_state, const Variant& p_variant);
+ void set_state(Physics2DServer::BodyState p_state, const Variant &p_variant);
Variant get_state(Physics2DServer::BodyState p_state) const;
- void set_applied_force(const Vector2& p_force) { applied_force=p_force; }
+ void set_applied_force(const Vector2 &p_force) { applied_force = p_force; }
Vector2 get_applied_force() const { return applied_force; }
- void set_applied_torque(real_t p_torque) { applied_torque=p_torque; }
+ void set_applied_torque(real_t p_torque) { applied_torque = p_torque; }
real_t get_applied_torque() const { return applied_torque; }
- _FORCE_INLINE_ void add_force(const Vector2& p_force, const Vector2& p_offset) {
+ _FORCE_INLINE_ void add_force(const Vector2 &p_force, const Vector2 &p_offset) {
applied_force += p_force;
applied_torque += p_offset.cross(p_force);
}
- _FORCE_INLINE_ void set_continuous_collision_detection_mode(Physics2DServer::CCDMode p_mode) { continuous_cd_mode=p_mode; }
+ _FORCE_INLINE_ void set_continuous_collision_detection_mode(Physics2DServer::CCDMode p_mode) { continuous_cd_mode = p_mode; }
_FORCE_INLINE_ Physics2DServer::CCDMode get_continuous_collision_detection_mode() const { return continuous_cd_mode; }
- void set_one_way_collision_direction(const Vector2& p_dir) {
- one_way_collision_direction=p_dir;
- using_one_way_cache=one_way_collision_direction!=Vector2();
+ void set_one_way_collision_direction(const Vector2 &p_dir) {
+ one_way_collision_direction = p_dir;
+ using_one_way_cache = one_way_collision_direction != Vector2();
}
Vector2 get_one_way_collision_direction() const { return one_way_collision_direction; }
- void set_one_way_collision_max_depth(real_t p_depth) { one_way_collision_max_depth=p_depth; }
+ void set_one_way_collision_max_depth(real_t p_depth) { one_way_collision_max_depth = p_depth; }
real_t get_one_way_collision_max_depth() const { return one_way_collision_max_depth; }
_FORCE_INLINE_ bool is_using_one_way_collision() const { return using_one_way_cache; }
@@ -276,16 +268,15 @@ public:
_FORCE_INLINE_ real_t get_linear_damp() const { return linear_damp; }
_FORCE_INLINE_ real_t get_angular_damp() const { return angular_damp; }
-
void integrate_forces(real_t p_step);
void integrate_velocities(real_t p_step);
_FORCE_INLINE_ Vector2 get_motion() const {
- if (mode>Physics2DServer::BODY_MODE_KINEMATIC) {
+ if (mode > Physics2DServer::BODY_MODE_KINEMATIC) {
return new_transform.get_origin() - get_transform().get_origin();
- } else if (mode==Physics2DServer::BODY_MODE_KINEMATIC) {
- return get_transform().get_origin() -new_transform.get_origin(); //kinematic simulates forward
+ } else if (mode == Physics2DServer::BODY_MODE_KINEMATIC) {
+ return get_transform().get_origin() - new_transform.get_origin(); //kinematic simulates forward
}
return Vector2();
}
@@ -297,111 +288,127 @@ public:
Body2DSW();
~Body2DSW();
-
};
-
//add contact inline
-void Body2DSW::add_contact(const Vector2& p_local_pos,const Vector2& p_local_normal, real_t p_depth, int p_local_shape, const Vector2& p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID& p_collider,const Vector2& p_collider_velocity_at_pos) {
+void Body2DSW::add_contact(const Vector2 &p_local_pos, const Vector2 &p_local_normal, real_t p_depth, int p_local_shape, const Vector2 &p_collider_pos, int p_collider_shape, ObjectID p_collider_instance_id, const RID &p_collider, const Vector2 &p_collider_velocity_at_pos) {
- int c_max=contacts.size();
+ int c_max = contacts.size();
- if (c_max==0)
+ if (c_max == 0)
return;
Contact *c = &contacts[0];
+ int idx = -1;
- int idx=-1;
-
- if (contact_count<c_max) {
- idx=contact_count++;
+ if (contact_count < c_max) {
+ idx = contact_count++;
} else {
- real_t least_depth=1e20;
- int least_deep=-1;
- for(int i=0;i<c_max;i++) {
+ real_t least_depth = 1e20;
+ int least_deep = -1;
+ for (int i = 0; i < c_max; i++) {
- if (i==0 || c[i].depth<least_depth) {
- least_deep=i;
- least_depth=c[i].depth;
+ if (i == 0 || c[i].depth < least_depth) {
+ least_deep = i;
+ least_depth = c[i].depth;
}
}
- if (least_deep>=0 && least_depth<p_depth) {
+ if (least_deep >= 0 && least_depth < p_depth) {
- idx=least_deep;
+ idx = least_deep;
}
- if (idx==-1)
+ if (idx == -1)
return; //none least deepe than this
}
- c[idx].local_pos=p_local_pos;
- c[idx].local_normal=p_local_normal;
- c[idx].depth=p_depth;
- c[idx].local_shape=p_local_shape;
- c[idx].collider_pos=p_collider_pos;
- c[idx].collider_shape=p_collider_shape;
- c[idx].collider_instance_id=p_collider_instance_id;
- c[idx].collider=p_collider;
- c[idx].collider_velocity_at_pos=p_collider_velocity_at_pos;
-
+ c[idx].local_pos = p_local_pos;
+ c[idx].local_normal = p_local_normal;
+ c[idx].depth = p_depth;
+ c[idx].local_shape = p_local_shape;
+ c[idx].collider_pos = p_collider_pos;
+ c[idx].collider_shape = p_collider_shape;
+ c[idx].collider_instance_id = p_collider_instance_id;
+ c[idx].collider = p_collider;
+ c[idx].collider_velocity_at_pos = p_collider_velocity_at_pos;
}
-
class Physics2DDirectBodyStateSW : public Physics2DDirectBodyState {
- GDCLASS( Physics2DDirectBodyStateSW, Physics2DDirectBodyState );
+ GDCLASS(Physics2DDirectBodyStateSW, Physics2DDirectBodyState);
public:
-
static Physics2DDirectBodyStateSW *singleton;
Body2DSW *body;
real_t step;
- virtual Vector2 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area
- virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area
- virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area
+ virtual Vector2 get_total_gravity() const { return body->gravity; } // get gravity vector working on this body space/area
+ virtual real_t get_total_angular_damp() const { return body->area_angular_damp; } // get density of this body space/area
+ virtual real_t get_total_linear_damp() const { return body->area_linear_damp; } // get density of this body space/area
- virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass
- virtual real_t get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space
+ virtual real_t get_inverse_mass() const { return body->get_inv_mass(); } // get the mass
+ virtual real_t get_inverse_inertia() const { return body->get_inv_inertia(); } // get density of this body space
- virtual void set_linear_velocity(const Vector2& p_velocity) { body->set_linear_velocity(p_velocity); }
- virtual Vector2 get_linear_velocity() const { return body->get_linear_velocity(); }
+ virtual void set_linear_velocity(const Vector2 &p_velocity) { body->set_linear_velocity(p_velocity); }
+ virtual Vector2 get_linear_velocity() const { return body->get_linear_velocity(); }
- virtual void set_angular_velocity(real_t p_velocity) { body->set_angular_velocity(p_velocity); }
- virtual real_t get_angular_velocity() const { return body->get_angular_velocity(); }
+ virtual void set_angular_velocity(real_t p_velocity) { body->set_angular_velocity(p_velocity); }
+ virtual real_t get_angular_velocity() const { return body->get_angular_velocity(); }
- virtual void set_transform(const Transform2D& p_transform) { body->set_state(Physics2DServer::BODY_STATE_TRANSFORM,p_transform); }
- virtual Transform2D get_transform() const { return body->get_transform(); }
+ virtual void set_transform(const Transform2D &p_transform) { body->set_state(Physics2DServer::BODY_STATE_TRANSFORM, p_transform); }
+ virtual Transform2D get_transform() const { return body->get_transform(); }
- virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); }
- virtual bool is_sleeping() const { return !body->is_active(); }
+ virtual void set_sleep_state(bool p_enable) { body->set_active(!p_enable); }
+ virtual bool is_sleeping() const { return !body->is_active(); }
- virtual int get_contact_count() const { return body->contact_count; }
+ virtual int get_contact_count() const { return body->contact_count; }
virtual Vector2 get_contact_local_pos(int p_contact_idx) const {
- ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2());
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2());
return body->contacts[p_contact_idx].local_pos;
}
- virtual Vector2 get_contact_local_normal(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].local_normal; }
- virtual int get_contact_local_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,-1); return body->contacts[p_contact_idx].local_shape; }
+ virtual Vector2 get_contact_local_normal(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2());
+ return body->contacts[p_contact_idx].local_normal;
+ }
+ virtual int get_contact_local_shape(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, -1);
+ return body->contacts[p_contact_idx].local_shape;
+ }
- virtual RID get_contact_collider(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,RID()); return body->contacts[p_contact_idx].collider; }
- virtual Vector2 get_contact_collider_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].collider_pos; }
- virtual ObjectID get_contact_collider_id(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_instance_id; }
- virtual int get_contact_collider_shape(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,0); return body->contacts[p_contact_idx].collider_shape; }
+ virtual RID get_contact_collider(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, RID());
+ return body->contacts[p_contact_idx].collider;
+ }
+ virtual Vector2 get_contact_collider_pos(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2());
+ return body->contacts[p_contact_idx].collider_pos;
+ }
+ virtual ObjectID get_contact_collider_id(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0);
+ return body->contacts[p_contact_idx].collider_instance_id;
+ }
+ virtual int get_contact_collider_shape(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, 0);
+ return body->contacts[p_contact_idx].collider_shape;
+ }
virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const;
- virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const { ERR_FAIL_INDEX_V(p_contact_idx,body->contact_count,Vector2()); return body->contacts[p_contact_idx].collider_velocity_at_pos; }
-
- virtual Physics2DDirectSpaceState* get_space_state();
+ virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const {
+ ERR_FAIL_INDEX_V(p_contact_idx, body->contact_count, Vector2());
+ return body->contacts[p_contact_idx].collider_velocity_at_pos;
+ }
+ virtual Physics2DDirectSpaceState *get_space_state();
virtual real_t get_step() const { return step; }
- Physics2DDirectBodyStateSW() { singleton=this; body=NULL; }
+ Physics2DDirectBodyStateSW() {
+ singleton = this;
+ body = NULL;
+ }
};
-
#endif // BODY_2D_SW_H
diff --git a/servers/physics_2d/body_pair_2d_sw.cpp b/servers/physics_2d/body_pair_2d_sw.cpp
index c05d61b658..ee94a7acec 100644
--- a/servers/physics_2d/body_pair_2d_sw.cpp
+++ b/servers/physics_2d/body_pair_2d_sw.cpp
@@ -30,54 +30,52 @@
#include "collision_solver_2d_sw.h"
#include "space_2d_sw.h"
-
#define POSITION_CORRECTION
#define ACCUMULATE_IMPULSES
-void BodyPair2DSW::_add_contact(const Vector2& p_point_A,const Vector2& p_point_B,void *p_self) {
+void BodyPair2DSW::_add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self) {
BodyPair2DSW *self = (BodyPair2DSW *)p_self;
- self->_contact_added_callback(p_point_A,p_point_B);
-
+ self->_contact_added_callback(p_point_A, p_point_B);
}
-void BodyPair2DSW::_contact_added_callback(const Vector2& p_point_A,const Vector2& p_point_B) {
+void BodyPair2DSW::_contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B) {
// check if we already have the contact
Vector2 local_A = A->get_inv_transform().basis_xform(p_point_A);
- Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B-offset_B);
+ Vector2 local_B = B->get_inv_transform().basis_xform(p_point_B - offset_B);
int new_index = contact_count;
- ERR_FAIL_COND( new_index >= (MAX_CONTACTS+1) );
+ ERR_FAIL_COND(new_index >= (MAX_CONTACTS + 1));
Contact contact;
- contact.acc_normal_impulse=0;
- contact.acc_bias_impulse=0;
- contact.acc_tangent_impulse=0;
- contact.local_A=local_A;
- contact.local_B=local_B;
- contact.reused=true;
- contact.normal=(p_point_A-p_point_B).normalized();
+ contact.acc_normal_impulse = 0;
+ contact.acc_bias_impulse = 0;
+ contact.acc_tangent_impulse = 0;
+ contact.local_A = local_A;
+ contact.local_B = local_B;
+ contact.reused = true;
+ contact.normal = (p_point_A - p_point_B).normalized();
// attempt to determine if the contact will be reused
real_t recycle_radius_2 = space->get_contact_recycle_radius() * space->get_contact_recycle_radius();
- for (int i=0;i<contact_count;i++) {
+ for (int i = 0; i < contact_count; i++) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
if (
- c.local_A.distance_squared_to( local_A ) < (recycle_radius_2) &&
- c.local_B.distance_squared_to( local_B ) < (recycle_radius_2) ) {
+ c.local_A.distance_squared_to(local_A) < (recycle_radius_2) &&
+ c.local_B.distance_squared_to(local_B) < (recycle_radius_2)) {
- contact.acc_normal_impulse=c.acc_normal_impulse;
- contact.acc_tangent_impulse=c.acc_tangent_impulse;
- contact.acc_bias_impulse=c.acc_bias_impulse;
- new_index=i;
+ contact.acc_normal_impulse = c.acc_normal_impulse;
+ contact.acc_tangent_impulse = c.acc_tangent_impulse;
+ contact.acc_bias_impulse = c.acc_bias_impulse;
+ new_index = i;
break;
}
}
@@ -88,44 +86,41 @@ void BodyPair2DSW::_contact_added_callback(const Vector2& p_point_A,const Vector
// remove the contact with the minimum depth
- int least_deep=-1;
- real_t min_depth=1e10;
+ int least_deep = -1;
+ real_t min_depth = 1e10;
+ for (int i = 0; i <= contact_count; i++) {
- for (int i=0;i<=contact_count;i++) {
-
- Contact& c = (i==contact_count)?contact:contacts[i];
+ Contact &c = (i == contact_count) ? contact : contacts[i];
Vector2 global_A = A->get_transform().basis_xform(c.local_A);
- Vector2 global_B = B->get_transform().basis_xform(c.local_B)+offset_B;
+ Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B;
Vector2 axis = global_A - global_B;
- real_t depth = axis.dot( c.normal );
-
+ real_t depth = axis.dot(c.normal);
- if (depth<min_depth) {
+ if (depth < min_depth) {
- min_depth=depth;
- least_deep=i;
+ min_depth = depth;
+ least_deep = i;
}
}
- ERR_FAIL_COND(least_deep==-1);
+ ERR_FAIL_COND(least_deep == -1);
if (least_deep < contact_count) { //replace the last deep contact by the new one
- contacts[least_deep]=contact;
+ contacts[least_deep] = contact;
}
return;
}
- contacts[new_index]=contact;
+ contacts[new_index] = contact;
- if (new_index==contact_count) {
+ if (new_index == contact_count) {
contact_count++;
}
-
}
void BodyPair2DSW::_validate_contacts() {
@@ -133,39 +128,35 @@ void BodyPair2DSW::_validate_contacts() {
//make sure to erase contacts that are no longer valid
real_t max_separation = space->get_contact_max_separation();
- real_t max_separation2 = max_separation*max_separation;
+ real_t max_separation2 = max_separation * max_separation;
- for (int i=0;i<contact_count;i++) {
+ for (int i = 0; i < contact_count; i++) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
- bool erase=false;
- if (c.reused==false) {
+ bool erase = false;
+ if (c.reused == false) {
//was left behind in previous frame
- erase=true;
+ erase = true;
} else {
- c.reused=false;
+ c.reused = false;
Vector2 global_A = A->get_transform().basis_xform(c.local_A);
- Vector2 global_B = B->get_transform().basis_xform(c.local_B)+offset_B;
+ Vector2 global_B = B->get_transform().basis_xform(c.local_B) + offset_B;
Vector2 axis = global_A - global_B;
- real_t depth = axis.dot( c.normal );
-
-
+ real_t depth = axis.dot(c.normal);
if (depth < -max_separation || (global_B + c.normal * depth - global_A).length_squared() > max_separation2) {
- erase=true;
+ erase = true;
}
}
if (erase) {
// contact no longer needed, remove
-
- if ((i+1) < contact_count) {
+ if ((i + 1) < contact_count) {
// swap with the last one
- SWAP( contacts[i], contacts[ contact_count-1 ] );
-
+ SWAP(contacts[i], contacts[contact_count - 1]);
}
i--;
@@ -174,21 +165,18 @@ void BodyPair2DSW::_validate_contacts() {
}
}
+bool BodyPair2DSW::_test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const Transform2D &p_xform_A, Body2DSW *p_B, int p_shape_B, const Transform2D &p_xform_B, bool p_swap_result) {
-bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Transform2D& p_xform_A,Body2DSW *p_B, int p_shape_B,const Transform2D& p_xform_B,bool p_swap_result) {
-
-
-
- Vector2 motion = p_A->get_linear_velocity()*p_step;
+ Vector2 motion = p_A->get_linear_velocity() * p_step;
real_t mlen = motion.length();
- if (mlen<CMP_EPSILON)
+ if (mlen < CMP_EPSILON)
return false;
Vector2 mnormal = motion / mlen;
- real_t min,max;
- p_A->get_shape(p_shape_A)->project_rangev(mnormal,p_xform_A,min,max);
- bool fast_object = mlen > (max-min)*0.3; //going too fast in that direction
+ real_t min, max;
+ p_A->get_shape(p_shape_A)->project_rangev(mnormal, p_xform_A, min, max);
+ bool fast_object = mlen > (max - min) * 0.3; //going too fast in that direction
if (!fast_object) { //did it move enough in this direction to even attempt raycast? let's say it should move more than 1/3 the size of the object in that axis
return false;
@@ -198,22 +186,21 @@ bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Tr
//support is the worst case collision point, so real collision happened before
int a;
Vector2 s[2];
- p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform(mnormal).normalized(),s,a);
+ p_A->get_shape(p_shape_A)->get_supports(p_xform_A.basis_xform(mnormal).normalized(), s, a);
Vector2 from = p_xform_A.xform(s[0]);
Vector2 to = from + motion;
Transform2D from_inv = p_xform_B.affine_inverse();
- Vector2 local_from = from_inv.xform(from-mnormal*mlen*0.1); //start from a little inside the bounding box
+ Vector2 local_from = from_inv.xform(from - mnormal * mlen * 0.1); //start from a little inside the bounding box
Vector2 local_to = from_inv.xform(to);
- Vector2 rpos,rnorm;
- if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from,local_to,rpos,rnorm))
+ Vector2 rpos, rnorm;
+ if (!p_B->get_shape(p_shape_B)->intersect_segment(local_from, local_to, rpos, rnorm))
return false;
//ray hit something
-
Vector2 hitpos = p_xform_B.xform(rpos);
Vector2 contact_A = to;
@@ -222,20 +209,18 @@ bool BodyPair2DSW::_test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Tr
//create a contact
if (p_swap_result)
- _contact_added_callback(contact_B,contact_A);
+ _contact_added_callback(contact_B, contact_A);
else
- _contact_added_callback(contact_A,contact_B);
-
+ _contact_added_callback(contact_A, contact_B);
return true;
}
bool BodyPair2DSW::setup(real_t p_step) {
-
//cannot collide
- if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported()==0 && B->get_max_contacts_reported()==0)) {
- collided=false;
+ if (!A->test_collision_mask(B) || A->has_exception(B->get_self()) || B->has_exception(A->get_self()) || (A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && A->get_max_contacts_reported() == 0 && B->get_max_contacts_reported() == 0)) {
+ collided = false;
return false;
}
@@ -249,44 +234,43 @@ bool BodyPair2DSW::setup(real_t p_step) {
Transform2D xform_A = xform_Au * A->get_shape_transform(shape_A);
Transform2D xform_Bu = B->get_transform();
- xform_Bu.elements[2]-=A->get_transform().get_origin();
+ xform_Bu.elements[2] -= A->get_transform().get_origin();
Transform2D xform_B = xform_Bu * B->get_shape_transform(shape_B);
- Shape2DSW *shape_A_ptr=A->get_shape(shape_A);
- Shape2DSW *shape_B_ptr=B->get_shape(shape_B);
+ Shape2DSW *shape_A_ptr = A->get_shape(shape_A);
+ Shape2DSW *shape_B_ptr = B->get_shape(shape_B);
- Vector2 motion_A,motion_B;
+ Vector2 motion_A, motion_B;
- if (A->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_SHAPE) {
- motion_A=A->get_motion();
+ if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) {
+ motion_A = A->get_motion();
}
- if (B->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_SHAPE) {
- motion_B=B->get_motion();
+ if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_SHAPE) {
+ motion_B = B->get_motion();
}
//faster to set than to check..
//bool prev_collided=collided;
- collided = CollisionSolver2DSW::solve(shape_A_ptr,xform_A,motion_A,shape_B_ptr,xform_B,motion_B,_add_contact,this,&sep_axis);
+ collided = CollisionSolver2DSW::solve(shape_A_ptr, xform_A, motion_A, shape_B_ptr, xform_B, motion_B, _add_contact, this, &sep_axis);
if (!collided) {
//test ccd (currently just a raycast)
- if (A->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_RAY && A->get_mode()>Physics2DServer::BODY_MODE_KINEMATIC) {
- if (_test_ccd(p_step,A,shape_A,xform_A,B,shape_B,xform_B))
- collided=true;
+ if (A->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && A->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) {
+ if (_test_ccd(p_step, A, shape_A, xform_A, B, shape_B, xform_B))
+ collided = true;
}
- if (B->get_continuous_collision_detection_mode()==Physics2DServer::CCD_MODE_CAST_RAY && B->get_mode()>Physics2DServer::BODY_MODE_KINEMATIC) {
- if (_test_ccd(p_step,B,shape_B,xform_B,A,shape_A,xform_A,true))
- collided=true;
+ if (B->get_continuous_collision_detection_mode() == Physics2DServer::CCD_MODE_CAST_RAY && B->get_mode() > Physics2DServer::BODY_MODE_KINEMATIC) {
+ if (_test_ccd(p_step, B, shape_B, xform_B, A, shape_A, xform_A, true))
+ collided = true;
}
if (!collided) {
- oneway_disabled=false;
+ oneway_disabled = false;
return false;
}
-
}
if (oneway_disabled)
@@ -297,45 +281,45 @@ bool BodyPair2DSW::setup(real_t p_step) {
if (A->is_using_one_way_collision()) {
Vector2 direction = A->get_one_way_collision_direction();
- bool valid=false;
- if (B->get_linear_velocity().dot(direction)>=0){
- for(int i=0;i<contact_count;i++) {
- Contact& c = contacts[i];
+ bool valid = false;
+ if (B->get_linear_velocity().dot(direction) >= 0) {
+ for (int i = 0; i < contact_count; i++) {
+ Contact &c = contacts[i];
if (!c.reused)
continue;
- if (c.normal.dot(direction)<0)
+ if (c.normal.dot(direction) < 0)
continue;
- valid=true;
+ valid = true;
break;
}
}
if (!valid) {
- collided=false;
- oneway_disabled=true;
+ collided = false;
+ oneway_disabled = true;
return false;
}
}
if (B->is_using_one_way_collision()) {
Vector2 direction = B->get_one_way_collision_direction();
- bool valid=false;
- if (A->get_linear_velocity().dot(direction)>=0){
- for(int i=0;i<contact_count;i++) {
- Contact& c = contacts[i];
+ bool valid = false;
+ if (A->get_linear_velocity().dot(direction) >= 0) {
+ for (int i = 0; i < contact_count; i++) {
+ Contact &c = contacts[i];
if (!c.reused)
continue;
- if (c.normal.dot(direction)<0)
+ if (c.normal.dot(direction) < 0)
continue;
- valid=true;
+ valid = true;
break;
}
}
if (!valid) {
- collided=false;
- oneway_disabled=true;
+ collided = false;
+ oneway_disabled = true;
return false;
}
}
@@ -346,72 +330,69 @@ bool BodyPair2DSW::setup(real_t p_step) {
real_t bias = 0.3;
if (shape_A_ptr->get_custom_bias() || shape_B_ptr->get_custom_bias()) {
- if (shape_A_ptr->get_custom_bias()==0)
- bias=shape_B_ptr->get_custom_bias();
- else if (shape_B_ptr->get_custom_bias()==0)
- bias=shape_A_ptr->get_custom_bias();
+ if (shape_A_ptr->get_custom_bias() == 0)
+ bias = shape_B_ptr->get_custom_bias();
+ else if (shape_B_ptr->get_custom_bias() == 0)
+ bias = shape_A_ptr->get_custom_bias();
else
- bias=(shape_B_ptr->get_custom_bias()+shape_A_ptr->get_custom_bias())*0.5;
+ bias = (shape_B_ptr->get_custom_bias() + shape_A_ptr->get_custom_bias()) * 0.5;
}
+ cc = 0;
- cc=0;
-
-
- real_t inv_dt = 1.0/p_step;
+ real_t inv_dt = 1.0 / p_step;
- bool do_process=false;
+ bool do_process = false;
for (int i = 0; i < contact_count; i++) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
Vector2 global_A = xform_Au.xform(c.local_A);
Vector2 global_B = xform_Bu.xform(c.local_B);
real_t depth = c.normal.dot(global_A - global_B);
- if (depth<=0 || !c.reused) {
- c.active=false;
+ if (depth <= 0 || !c.reused) {
+ c.active = false;
continue;
}
- c.active=true;
+ c.active = true;
#ifdef DEBUG_ENABLED
if (space->is_debugging_contacts()) {
- space->add_debug_contact(global_A+offset_A);
- space->add_debug_contact(global_B+offset_A);
+ space->add_debug_contact(global_A + offset_A);
+ space->add_debug_contact(global_B + offset_A);
}
#endif
int gather_A = A->can_report_contacts();
int gather_B = B->can_report_contacts();
c.rA = global_A;
- c.rB = global_B-offset_B;
+ c.rB = global_B - offset_B;
if (gather_A | gather_B) {
//Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x );
- global_A+=offset_A;
- global_B+=offset_A;
+ global_A += offset_A;
+ global_B += offset_A;
if (gather_A) {
- Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x );
- A->add_contact(global_A,-c.normal,depth,shape_A,global_B,shape_B,B->get_instance_id(),B->get_self(),crB+B->get_linear_velocity());
+ Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
+ A->add_contact(global_A, -c.normal, depth, shape_A, global_B, shape_B, B->get_instance_id(), B->get_self(), crB + B->get_linear_velocity());
}
if (gather_B) {
- Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x );
- B->add_contact(global_B,c.normal,depth,shape_B,global_A,shape_A,A->get_instance_id(),A->get_self(),crA+A->get_linear_velocity());
+ Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
+ B->add_contact(global_B, c.normal, depth, shape_B, global_A, shape_A, A->get_instance_id(), A->get_self(), crA + A->get_linear_velocity());
}
}
- if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode()<=Physics2DServer::BODY_MODE_KINEMATIC)) {
- c.active=false;
- collided=false;
+ if (A->is_shape_set_as_trigger(shape_A) || B->is_shape_set_as_trigger(shape_B) || (A->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC && B->get_mode() <= Physics2DServer::BODY_MODE_KINEMATIC)) {
+ c.active = false;
+ collided = false;
continue;
-
}
// Precompute normal mass, tangent mass, and bias.
@@ -426,39 +407,33 @@ bool BodyPair2DSW::setup(real_t p_step) {
real_t rtB = c.rB.dot(tangent);
real_t kTangent = A->get_inv_mass() + B->get_inv_mass();
kTangent += A->get_inv_inertia() * (c.rA.dot(c.rA) - rtA * rtA) + B->get_inv_inertia() * (c.rB.dot(c.rB) - rtB * rtB);
- c.mass_tangent = 1.0f / kTangent;
-
-
+ c.mass_tangent = 1.0f / kTangent;
c.bias = -bias * inv_dt * MIN(0.0f, -depth + max_penetration);
- c.depth=depth;
- //c.acc_bias_impulse=0;
-
+ c.depth = depth;
+//c.acc_bias_impulse=0;
#ifdef ACCUMULATE_IMPULSES
{
// Apply normal + friction impulse
Vector2 P = c.acc_normal_impulse * c.normal + c.acc_tangent_impulse * tangent;
-
- A->apply_impulse(c.rA,-P);
+ A->apply_impulse(c.rA, -P);
B->apply_impulse(c.rB, P);
}
#endif
-
- c.bounce=MAX(A->get_bounce(),B->get_bounce());
+ c.bounce = MAX(A->get_bounce(), B->get_bounce());
if (c.bounce) {
- Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x );
- Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x );
+ Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
+ Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
c.bounce = c.bounce * dv.dot(c.normal);
}
- do_process=true;
-
+ do_process = true;
}
return do_process;
@@ -471,81 +446,71 @@ void BodyPair2DSW::solve(real_t p_step) {
for (int i = 0; i < contact_count; ++i) {
- Contact& c = contacts[i];
+ Contact &c = contacts[i];
cc++;
if (!c.active)
continue;
-
// Relative velocity at contact
- Vector2 crA( -A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x );
- Vector2 crB( -B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x );
+ Vector2 crA(-A->get_angular_velocity() * c.rA.y, A->get_angular_velocity() * c.rA.x);
+ Vector2 crB(-B->get_angular_velocity() * c.rB.y, B->get_angular_velocity() * c.rB.x);
Vector2 dv = B->get_linear_velocity() + crB - A->get_linear_velocity() - crA;
- Vector2 crbA( -A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x );
- Vector2 crbB( -B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x );
+ Vector2 crbA(-A->get_biased_angular_velocity() * c.rA.y, A->get_biased_angular_velocity() * c.rA.x);
+ Vector2 crbB(-B->get_biased_angular_velocity() * c.rB.y, B->get_biased_angular_velocity() * c.rB.x);
Vector2 dbv = B->get_biased_linear_velocity() + crbB - A->get_biased_linear_velocity() - crbA;
-
real_t vn = dv.dot(c.normal);
real_t vbn = dbv.dot(c.normal);
Vector2 tangent = c.normal.tangent();
real_t vt = dv.dot(tangent);
-
- real_t jbn = (c.bias - vbn)*c.mass_normal;
+ real_t jbn = (c.bias - vbn) * c.mass_normal;
real_t jbnOld = c.acc_bias_impulse;
c.acc_bias_impulse = MAX(jbnOld + jbn, 0.0f);
Vector2 jb = c.normal * (c.acc_bias_impulse - jbnOld);
- A->apply_bias_impulse(c.rA,-jb);
+ A->apply_bias_impulse(c.rA, -jb);
B->apply_bias_impulse(c.rB, jb);
- real_t jn = -(c.bounce + vn)*c.mass_normal;
+ real_t jn = -(c.bounce + vn) * c.mass_normal;
real_t jnOld = c.acc_normal_impulse;
c.acc_normal_impulse = MAX(jnOld + jn, 0.0f);
-
real_t friction = A->get_friction() * B->get_friction();
- real_t jtMax = friction*c.acc_normal_impulse;
- real_t jt = -vt*c.mass_tangent;
+ real_t jtMax = friction * c.acc_normal_impulse;
+ real_t jt = -vt * c.mass_tangent;
real_t jtOld = c.acc_tangent_impulse;
c.acc_tangent_impulse = CLAMP(jtOld + jt, -jtMax, jtMax);
- Vector2 j =c.normal * (c.acc_normal_impulse - jnOld) + tangent * ( c.acc_tangent_impulse - jtOld );
+ Vector2 j = c.normal * (c.acc_normal_impulse - jnOld) + tangent * (c.acc_tangent_impulse - jtOld);
- A->apply_impulse(c.rA,-j);
+ A->apply_impulse(c.rA, -j);
B->apply_impulse(c.rB, j);
-
-
}
}
-
-BodyPair2DSW::BodyPair2DSW(Body2DSW *p_A, int p_shape_A,Body2DSW *p_B, int p_shape_B) : Constraint2DSW(_arr,2) {
-
- A=p_A;
- B=p_B;
- shape_A=p_shape_A;
- shape_B=p_shape_B;
- space=A->get_space();
- A->add_constraint(this,0);
- B->add_constraint(this,1);
- contact_count=0;
- collided=false;
- oneway_disabled=false;
-
+BodyPair2DSW::BodyPair2DSW(Body2DSW *p_A, int p_shape_A, Body2DSW *p_B, int p_shape_B)
+ : Constraint2DSW(_arr, 2) {
+
+ A = p_A;
+ B = p_B;
+ shape_A = p_shape_A;
+ shape_B = p_shape_B;
+ space = A->get_space();
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
+ contact_count = 0;
+ collided = false;
+ oneway_disabled = false;
}
-
BodyPair2DSW::~BodyPair2DSW() {
-
A->remove_constraint(this);
B->remove_constraint(this);
-
}
diff --git a/servers/physics_2d/body_pair_2d_sw.h b/servers/physics_2d/body_pair_2d_sw.h
index 7a4771782a..023c182c31 100644
--- a/servers/physics_2d/body_pair_2d_sw.h
+++ b/servers/physics_2d/body_pair_2d_sw.h
@@ -35,7 +35,7 @@
class BodyPair2DSW : public Constraint2DSW {
enum {
- MAX_CONTACTS=2
+ MAX_CONTACTS = 2
};
union {
struct {
@@ -56,18 +56,17 @@ class BodyPair2DSW : public Constraint2DSW {
Vector2 position;
Vector2 normal;
Vector2 local_A, local_B;
- real_t acc_normal_impulse; // accumulated normal impulse (Pn)
- real_t acc_tangent_impulse; // accumulated tangent impulse (Pt)
- real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb)
+ real_t acc_normal_impulse; // accumulated normal impulse (Pn)
+ real_t acc_tangent_impulse; // accumulated tangent impulse (Pt)
+ real_t acc_bias_impulse; // accumulated normal impulse for position bias (Pnb)
real_t mass_normal, mass_tangent;
real_t bias;
real_t depth;
bool active;
- Vector2 rA,rB;
+ Vector2 rA, rB;
bool reused;
real_t bounce;
-
};
Vector2 offset_B; //use local A coordinates to avoid numerical issues on collision detection
@@ -79,20 +78,17 @@ class BodyPair2DSW : public Constraint2DSW {
bool oneway_disabled;
int cc;
-
- bool _test_ccd(real_t p_step,Body2DSW *p_A, int p_shape_A,const Transform2D& p_xform_A,Body2DSW *p_B, int p_shape_B,const Transform2D& p_xform_B,bool p_swap_result=false);
+ bool _test_ccd(real_t p_step, Body2DSW *p_A, int p_shape_A, const Transform2D &p_xform_A, Body2DSW *p_B, int p_shape_B, const Transform2D &p_xform_B, bool p_swap_result = false);
void _validate_contacts();
- static void _add_contact(const Vector2& p_point_A,const Vector2& p_point_B,void *p_self);
- _FORCE_INLINE_ void _contact_added_callback(const Vector2& p_point_A,const Vector2& p_point_B);
+ static void _add_contact(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_self);
+ _FORCE_INLINE_ void _contact_added_callback(const Vector2 &p_point_A, const Vector2 &p_point_B);
public:
-
bool setup(real_t p_step);
void solve(real_t p_step);
- BodyPair2DSW(Body2DSW *p_A, int p_shape_A,Body2DSW *p_B, int p_shape_B);
+ BodyPair2DSW(Body2DSW *p_A, int p_shape_A, Body2DSW *p_B, int p_shape_B);
~BodyPair2DSW();
-
};
#endif // BODY_PAIR_2D_SW_H
diff --git a/servers/physics_2d/broad_phase_2d_basic.cpp b/servers/physics_2d/broad_phase_2d_basic.cpp
index e1f6f4f92b..c282c0364e 100644
--- a/servers/physics_2d/broad_phase_2d_basic.cpp
+++ b/servers/physics_2d/broad_phase_2d_basic.cpp
@@ -30,94 +30,87 @@
BroadPhase2DBasic::ID BroadPhase2DBasic::create(CollisionObject2DSW *p_object_, int p_subindex) {
-
current++;
Element e;
- e.owner=p_object_;
- e._static=false;
- e.subindex=p_subindex;
+ e.owner = p_object_;
+ e._static = false;
+ e.subindex = p_subindex;
- element_map[current]=e;
+ element_map[current] = e;
return current;
}
-void BroadPhase2DBasic::move(ID p_id, const Rect2& p_aabb) {
+void BroadPhase2DBasic::move(ID p_id, const Rect2 &p_aabb) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- E->get().aabb=p_aabb;
-
+ E->get().aabb = p_aabb;
}
void BroadPhase2DBasic::set_static(ID p_id, bool p_static) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- E->get()._static=p_static;
-
+ E->get()._static = p_static;
}
void BroadPhase2DBasic::remove(ID p_id) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
element_map.erase(E);
-
}
CollisionObject2DSW *BroadPhase2DBasic::get_object(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,NULL);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, NULL);
return E->get().owner;
-
}
bool BroadPhase2DBasic::is_static(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,false);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, false);
return E->get()._static;
-
}
int BroadPhase2DBasic::get_subindex(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,-1);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, -1);
return E->get().subindex;
}
-int BroadPhase2DBasic::cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhase2DBasic::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
- int rc=0;
+ int rc = 0;
- for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) {
+ for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
- const Rect2 aabb=E->get().aabb;
- if (aabb.intersects_segment(p_from,p_to)) {
+ const Rect2 aabb = E->get().aabb;
+ if (aabb.intersects_segment(p_from, p_to)) {
- p_results[rc]=E->get().owner;
- p_result_indices[rc]=E->get().subindex;
+ p_results[rc] = E->get().owner;
+ p_result_indices[rc] = E->get().subindex;
rc++;
- if (rc>=p_max_results)
+ if (rc >= p_max_results)
break;
}
}
return rc;
-
}
-int BroadPhase2DBasic::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhase2DBasic::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
- int rc=0;
+ int rc = 0;
- for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) {
+ for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
- const Rect2 aabb=E->get().aabb;
+ const Rect2 aabb = E->get().aabb;
if (aabb.intersects(p_aabb)) {
- p_results[rc]=E->get().owner;
- p_result_indices[rc]=E->get().subindex;
+ p_results[rc] = E->get().owner;
+ p_result_indices[rc] = E->get().subindex;
rc++;
- if (rc>=p_max_results)
+ if (rc >= p_max_results)
break;
}
}
@@ -125,68 +118,63 @@ int BroadPhase2DBasic::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_res
return rc;
}
-void BroadPhase2DBasic::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) {
-
- pair_userdata=p_userdata;
- pair_callback=p_pair_callback;
+void BroadPhase2DBasic::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
+ pair_userdata = p_userdata;
+ pair_callback = p_pair_callback;
}
-void BroadPhase2DBasic::set_unpair_callback(UnpairCallback p_pair_callback,void *p_userdata) {
-
- unpair_userdata=p_userdata;
- unpair_callback=p_pair_callback;
+void BroadPhase2DBasic::set_unpair_callback(UnpairCallback p_pair_callback, void *p_userdata) {
+ unpair_userdata = p_userdata;
+ unpair_callback = p_pair_callback;
}
void BroadPhase2DBasic::update() {
// recompute pairs
- for(Map<ID,Element>::Element *I=element_map.front();I;I=I->next()) {
+ for (Map<ID, Element>::Element *I = element_map.front(); I; I = I->next()) {
- for(Map<ID,Element>::Element *J=I->next();J;J=J->next()) {
+ for (Map<ID, Element>::Element *J = I->next(); J; J = J->next()) {
- Element *elem_A=&I->get();
- Element *elem_B=&J->get();
+ Element *elem_A = &I->get();
+ Element *elem_B = &J->get();
if (elem_A->owner == elem_B->owner)
continue;
+ bool pair_ok = elem_A->aabb.intersects(elem_B->aabb) && (!elem_A->_static || !elem_B->_static);
- bool pair_ok=elem_A->aabb.intersects( elem_B->aabb ) && (!elem_A->_static || !elem_B->_static );
+ PairKey key(I->key(), J->key());
- PairKey key(I->key(),J->key());
-
- Map<PairKey,void*>::Element *E=pair_map.find(key);
+ Map<PairKey, void *>::Element *E = pair_map.find(key);
if (!pair_ok && E) {
if (unpair_callback)
- unpair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,E->get(),unpair_userdata);
+ unpair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, E->get(), unpair_userdata);
pair_map.erase(key);
}
if (pair_ok && !E) {
- void *data=NULL;
+ void *data = NULL;
if (pair_callback)
- data=pair_callback(elem_A->owner,elem_A->subindex,elem_B->owner,elem_B->subindex,unpair_userdata);
- pair_map.insert(key,data);
+ data = pair_callback(elem_A->owner, elem_A->subindex, elem_B->owner, elem_B->subindex, unpair_userdata);
+ pair_map.insert(key, data);
}
}
}
-
}
BroadPhase2DSW *BroadPhase2DBasic::_create() {
- return memnew( BroadPhase2DBasic );
+ return memnew(BroadPhase2DBasic);
}
BroadPhase2DBasic::BroadPhase2DBasic() {
- current=1;
- unpair_callback=NULL;
- unpair_userdata=NULL;
- pair_callback=NULL;
- pair_userdata=NULL;
-
+ current = 1;
+ unpair_callback = NULL;
+ unpair_userdata = NULL;
+ pair_callback = NULL;
+ pair_userdata = NULL;
}
diff --git a/servers/physics_2d/broad_phase_2d_basic.h b/servers/physics_2d/broad_phase_2d_basic.h
index 82e91118ce..7c5d799f9a 100644
--- a/servers/physics_2d/broad_phase_2d_basic.h
+++ b/servers/physics_2d/broad_phase_2d_basic.h
@@ -29,8 +29,8 @@
#ifndef BROAD_PHASE_2D_BASIC_H
#define BROAD_PHASE_2D_BASIC_H
-#include "space_2d_sw.h"
#include "map.h"
+#include "space_2d_sw.h"
class BroadPhase2DBasic : public BroadPhase2DSW {
struct Element {
@@ -41,8 +41,7 @@ class BroadPhase2DBasic : public BroadPhase2DSW {
int subindex;
};
-
- Map<ID,Element> element_map;
+ Map<ID, Element> element_map;
ID current;
@@ -56,17 +55,23 @@ class BroadPhase2DBasic : public BroadPhase2DSW {
uint64_t key;
};
- _FORCE_INLINE_ bool operator<(const PairKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const PairKey &p_key) const {
return key < p_key.key;
}
- PairKey() { key=0; }
- PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }}
-
+ PairKey() { key = 0; }
+ PairKey(ID p_a, ID p_b) {
+ if (p_a > p_b) {
+ a = p_b;
+ b = p_a;
+ } else {
+ a = p_a;
+ b = p_b;
+ }
+ }
};
- Map<PairKey,void*> pair_map;
-
+ Map<PairKey, void *> pair_map;
PairCallback pair_callback;
void *pair_userdata;
@@ -74,10 +79,9 @@ class BroadPhase2DBasic : public BroadPhase2DSW {
void *unpair_userdata;
public:
-
// 0 is an invalid ID
- virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0);
- virtual void move(ID p_id, const Rect2& p_aabb);
+ virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0);
+ virtual void move(ID p_id, const Rect2 &p_aabb);
virtual void set_static(ID p_id, bool p_static);
virtual void remove(ID p_id);
@@ -85,11 +89,11 @@ public:
virtual bool is_static(ID p_id) const;
virtual int get_subindex(ID p_id) const;
- virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL);
- virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL);
+ virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL);
+ virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL);
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata);
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata);
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata);
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata);
virtual void update();
diff --git a/servers/physics_2d/broad_phase_2d_hash_grid.cpp b/servers/physics_2d/broad_phase_2d_hash_grid.cpp
index 06eead64cd..74c01e1220 100644
--- a/servers/physics_2d/broad_phase_2d_hash_grid.cpp
+++ b/servers/physics_2d/broad_phase_2d_hash_grid.cpp
@@ -31,110 +31,100 @@
#define LARGE_ELEMENT_FI 1.01239812
-void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element* p_with) {
+void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element *p_with) {
- Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with);
+ Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
ERR_FAIL_COND(p_elem->_static && p_with->_static);
if (!E) {
- PairData *pd = memnew( PairData );
- p_elem->paired[p_with]=pd;
- p_with->paired[p_elem]=pd;
+ PairData *pd = memnew(PairData);
+ p_elem->paired[p_with] = pd;
+ p_with->paired[p_elem] = pd;
} else {
E->get()->rc++;
}
-
}
-void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element* p_with) {
+void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element *p_with) {
- Map<Element*,PairData*>::Element *E=p_elem->paired.find(p_with);
+ Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
ERR_FAIL_COND(!E); //this should really be paired..
E->get()->rc--;
- if (E->get()->rc==0) {
+ if (E->get()->rc == 0) {
if (E->get()->colliding) {
//uncollide
if (unpair_callback) {
- unpair_callback(p_elem->owner,p_elem->subindex,p_with->owner,p_with->subindex,E->get()->ud,unpair_userdata);
+ unpair_callback(p_elem->owner, p_elem->subindex, p_with->owner, p_with->subindex, E->get()->ud, unpair_userdata);
}
-
-
}
memdelete(E->get());
p_elem->paired.erase(E);
p_with->paired.erase(p_elem);
}
-
-
}
void BroadPhase2DHashGrid::_check_motion(Element *p_elem) {
- for (Map<Element*,PairData*>::Element *E=p_elem->paired.front();E;E=E->next()) {
+ for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) {
- bool pairing = p_elem->aabb.intersects( E->key()->aabb );
+ bool pairing = p_elem->aabb.intersects(E->key()->aabb);
- if (pairing!=E->get()->colliding) {
+ if (pairing != E->get()->colliding) {
if (pairing) {
if (pair_callback) {
- E->get()->ud=pair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,pair_userdata);
+ E->get()->ud = pair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, pair_userdata);
}
} else {
if (unpair_callback) {
- unpair_callback(p_elem->owner,p_elem->subindex,E->key()->owner,E->key()->subindex,E->get()->ud,unpair_userdata);
+ unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata);
}
-
}
- E->get()->colliding=pairing;
+ E->get()->colliding = pairing;
}
}
}
-void BroadPhase2DHashGrid::_enter_grid( Element* p_elem, const Rect2& p_rect,bool p_static) {
-
-
+void BroadPhase2DHashGrid::_enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
- Vector2 sz = (p_rect.size/cell_size*LARGE_ELEMENT_FI); //use magic number to avoid floating point issues
- if (sz.width*sz.height > large_object_min_surface) {
+ Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI); //use magic number to avoid floating point issues
+ if (sz.width * sz.height > large_object_min_surface) {
//large object, do not use grid, must check against all elements
- for (Map<ID,Element>::Element *E=element_map.front();E;E=E->next()) {
- if (E->key()==p_elem->self)
+ for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
+ if (E->key() == p_elem->self)
continue; // do not pair against itself
if (E->get().owner == p_elem->owner)
continue;
if (E->get()._static && p_static)
continue;
- _pair_attempt(p_elem,&E->get());
+ _pair_attempt(p_elem, &E->get());
}
-
large_elements[p_elem].inc();
return;
}
- Point2i from = (p_rect.pos/cell_size).floor();
- Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor();
-
- for(int i=from.x;i<=to.x;i++) {
+ Point2i from = (p_rect.pos / cell_size).floor();
+ Point2i to = ((p_rect.pos + p_rect.size) / cell_size).floor();
+ for (int i = from.x; i <= to.x; i++) {
- for(int j=from.y;j<=to.y;j++) {
+ for (int j = from.y; j <= to.y; j++) {
PosKey pk;
- pk.x=i;
- pk.y=j;
+ pk.x = i;
+ pk.y = j;
uint32_t idx = pk.hash() % hash_table_size;
PosBin *pb = hash_table[idx];
@@ -145,102 +135,94 @@ void BroadPhase2DHashGrid::_enter_grid( Element* p_elem, const Rect2& p_rect,boo
break;
}
- pb=pb->next;
+ pb = pb->next;
}
-
- bool entered=false;
+ bool entered = false;
if (!pb) {
//does not exist, create!
- pb = memnew( PosBin );
- pb->key=pk;
- pb->next=hash_table[idx];
- hash_table[idx]=pb;
+ pb = memnew(PosBin);
+ pb->key = pk;
+ pb->next = hash_table[idx];
+ hash_table[idx] = pb;
}
-
-
if (p_static) {
- if (pb->static_object_set[p_elem].inc()==1) {
- entered=true;
+ if (pb->static_object_set[p_elem].inc() == 1) {
+ entered = true;
}
} else {
- if (pb->object_set[p_elem].inc()==1) {
+ if (pb->object_set[p_elem].inc() == 1) {
- entered=true;
+ entered = true;
}
}
if (entered) {
- for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
- if (E->key()->owner==p_elem->owner)
+ if (E->key()->owner == p_elem->owner)
continue;
- _pair_attempt(p_elem,E->key());
+ _pair_attempt(p_elem, E->key());
}
if (!p_static) {
- for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
- if (E->key()->owner==p_elem->owner)
+ if (E->key()->owner == p_elem->owner)
continue;
- _pair_attempt(p_elem,E->key());
+ _pair_attempt(p_elem, E->key());
}
}
}
-
}
-
}
//pair separatedly with large elements
- for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
- if (E->key()==p_elem)
+ if (E->key() == p_elem)
continue; // do not pair against itself
if (E->key()->owner == p_elem->owner)
continue;
if (E->key()->_static && p_static)
continue;
- _pair_attempt(E->key(),p_elem);
+ _pair_attempt(E->key(), p_elem);
}
-
}
+void BroadPhase2DHashGrid::_exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
-void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool p_static) {
-
- Vector2 sz = (p_rect.size/cell_size*LARGE_ELEMENT_FI);
- if (sz.width*sz.height > large_object_min_surface) {
+ Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI);
+ if (sz.width * sz.height > large_object_min_surface) {
//unpair all elements, instead of checking all, just check what is already paired, so we at least save from checking static vs static
- for (Map<Element*,PairData*>::Element *E=p_elem->paired.front();E;E=E->next()) {
+ for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) {
- _unpair_attempt(p_elem,E->key());
+ _unpair_attempt(p_elem, E->key());
}
- if (large_elements[p_elem].dec()==0) {
+ if (large_elements[p_elem].dec() == 0) {
large_elements.erase(p_elem);
}
return;
}
+ Point2i from = (p_rect.pos / cell_size).floor();
+ Point2i to = ((p_rect.pos + p_rect.size) / cell_size).floor();
- Point2i from = (p_rect.pos/cell_size).floor();
- Point2i to = ((p_rect.pos+p_rect.size)/cell_size).floor();
-
- for(int i=from.x;i<=to.x;i++) {
+ for (int i = from.x; i <= to.x; i++) {
- for(int j=from.y;j<=to.y;j++) {
+ for (int j = from.y; j <= to.y; j++) {
PosKey pk;
- pk.x=i;
- pk.y=j;
+ pk.x = i;
+ pk.y = j;
uint32_t idx = pk.hash() % hash_table_size;
PosBin *pb = hash_table[idx];
@@ -251,82 +233,75 @@ void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool
break;
}
- pb=pb->next;
+ pb = pb->next;
}
ERR_CONTINUE(!pb); //should exist!!
- bool exited=false;
-
+ bool exited = false;
if (p_static) {
- if (pb->static_object_set[p_elem].dec()==0) {
+ if (pb->static_object_set[p_elem].dec() == 0) {
pb->static_object_set.erase(p_elem);
- exited=true;
-
+ exited = true;
}
} else {
- if (pb->object_set[p_elem].dec()==0) {
+ if (pb->object_set[p_elem].dec() == 0) {
pb->object_set.erase(p_elem);
- exited=true;
-
+ exited = true;
}
}
if (exited) {
- for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
- if (E->key()->owner==p_elem->owner)
+ if (E->key()->owner == p_elem->owner)
continue;
- _unpair_attempt(p_elem,E->key());
-
+ _unpair_attempt(p_elem, E->key());
}
if (!p_static) {
- for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
- if (E->key()->owner==p_elem->owner)
+ if (E->key()->owner == p_elem->owner)
continue;
- _unpair_attempt(p_elem,E->key());
+ _unpair_attempt(p_elem, E->key());
}
}
}
if (pb->object_set.empty() && pb->static_object_set.empty()) {
- if (hash_table[idx]==pb) {
- hash_table[idx]=pb->next;
+ if (hash_table[idx] == pb) {
+ hash_table[idx] = pb->next;
} else {
PosBin *px = hash_table[idx];
while (px) {
- if (px->next==pb) {
- px->next=pb->next;
+ if (px->next == pb) {
+ px->next = pb->next;
break;
}
- px=px->next;
+ px = px->next;
}
ERR_CONTINUE(!px);
}
memdelete(pb);
-
}
}
-
}
-
- for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) {
- if (E->key()==p_elem)
+ for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
+ if (E->key() == p_elem)
continue; // do not pair against itself
if (E->key()->owner == p_elem->owner)
continue;
@@ -334,121 +309,109 @@ void BroadPhase2DHashGrid::_exit_grid( Element* p_elem, const Rect2& p_rect,bool
continue;
//unpair from large elements
- _unpair_attempt(p_elem,E->key());
+ _unpair_attempt(p_elem, E->key());
}
-
-
}
-
BroadPhase2DHashGrid::ID BroadPhase2DHashGrid::create(CollisionObject2DSW *p_object, int p_subindex) {
current++;
Element e;
- e.owner=p_object;
- e._static=false;
- e.subindex=p_subindex;
- e.self=current;
- e.pass=0;
+ e.owner = p_object;
+ e._static = false;
+ e.subindex = p_subindex;
+ e.self = current;
+ e.pass = 0;
- element_map[current]=e;
+ element_map[current] = e;
return current;
-
}
-void BroadPhase2DHashGrid::move(ID p_id, const Rect2& p_aabb) {
-
+void BroadPhase2DHashGrid::move(ID p_id, const Rect2 &p_aabb) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- Element &e=E->get();
+ Element &e = E->get();
- if (p_aabb==e.aabb)
+ if (p_aabb == e.aabb)
return;
+ if (p_aabb != Rect2()) {
- if (p_aabb!=Rect2()) {
-
- _enter_grid(&e,p_aabb,e._static);
+ _enter_grid(&e, p_aabb, e._static);
}
- if (e.aabb!=Rect2()) {
+ if (e.aabb != Rect2()) {
- _exit_grid(&e,e.aabb,e._static);
+ _exit_grid(&e, e.aabb, e._static);
}
- e.aabb=p_aabb;
+ e.aabb = p_aabb;
_check_motion(&e);
- e.aabb=p_aabb;
-
+ e.aabb = p_aabb;
}
void BroadPhase2DHashGrid::set_static(ID p_id, bool p_static) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- Element &e=E->get();
+ Element &e = E->get();
- if (e._static==p_static)
+ if (e._static == p_static)
return;
- if (e.aabb!=Rect2())
- _exit_grid(&e,e.aabb,e._static);
+ if (e.aabb != Rect2())
+ _exit_grid(&e, e.aabb, e._static);
- e._static=p_static;
+ e._static = p_static;
- if (e.aabb!=Rect2()) {
- _enter_grid(&e,e.aabb,e._static);
+ if (e.aabb != Rect2()) {
+ _enter_grid(&e, e.aabb, e._static);
_check_motion(&e);
}
-
}
void BroadPhase2DHashGrid::remove(ID p_id) {
- Map<ID,Element>::Element *E=element_map.find(p_id);
+ Map<ID, Element>::Element *E = element_map.find(p_id);
ERR_FAIL_COND(!E);
- Element &e=E->get();
+ Element &e = E->get();
- if (e.aabb!=Rect2())
- _exit_grid(&e,e.aabb,e._static);
+ if (e.aabb != Rect2())
+ _exit_grid(&e, e.aabb, e._static);
element_map.erase(p_id);
-
}
CollisionObject2DSW *BroadPhase2DHashGrid::get_object(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,NULL);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, NULL);
return E->get().owner;
-
}
bool BroadPhase2DHashGrid::is_static(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,false);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, false);
return E->get()._static;
-
}
int BroadPhase2DHashGrid::get_subindex(ID p_id) const {
- const Map<ID,Element>::Element *E=element_map.find(p_id);
- ERR_FAIL_COND_V(!E,-1);
+ const Map<ID, Element>::Element *E = element_map.find(p_id);
+ ERR_FAIL_COND_V(!E, -1);
return E->get().subindex;
}
-template<bool use_aabb,bool use_segment>
-void BroadPhase2DHashGrid::_cull(const Point2i p_cell,const Rect2& p_aabb,const Point2& p_from, const Point2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices,int &index) {
-
+template <bool use_aabb, bool use_segment>
+void BroadPhase2DHashGrid::_cull(const Point2i p_cell, const Rect2 &p_aabb, const Point2 &p_from, const Point2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices, int &index) {
PosKey pk;
- pk.x=p_cell.x;
- pk.y=p_cell.y;
+ pk.x = p_cell.x;
+ pk.y = p_cell.y;
uint32_t idx = pk.hash() % hash_table_size;
PosBin *pb = hash_table[idx];
@@ -459,190 +422,177 @@ void BroadPhase2DHashGrid::_cull(const Point2i p_cell,const Rect2& p_aabb,const
break;
}
- pb=pb->next;
+ pb = pb->next;
}
if (!pb)
return;
+ for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
-
- for(Map<Element*,RC>::Element *E=pb->object_set.front();E;E=E->next()) {
-
-
- if (index>=p_max_results)
+ if (index >= p_max_results)
break;
- if (E->key()->pass==pass)
+ if (E->key()->pass == pass)
continue;
- E->key()->pass=pass;
+ E->key()->pass = pass;
if (use_aabb && !p_aabb.intersects(E->key()->aabb))
continue;
- if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to))
+ if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to))
continue;
- p_results[index]=E->key()->owner;
- p_result_indices[index]=E->key()->subindex;
+ p_results[index] = E->key()->owner;
+ p_result_indices[index] = E->key()->subindex;
index++;
-
-
}
- for(Map<Element*,RC>::Element *E=pb->static_object_set.front();E;E=E->next()) {
-
+ for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
- if (index>=p_max_results)
+ if (index >= p_max_results)
break;
- if (E->key()->pass==pass)
+ if (E->key()->pass == pass)
continue;
if (use_aabb && !p_aabb.intersects(E->key()->aabb)) {
continue;
}
- if (use_segment && !E->key()->aabb.intersects_segment(p_from,p_to))
+ if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to))
continue;
- E->key()->pass=pass;
- p_results[index]=E->key()->owner;
- p_result_indices[index]=E->key()->subindex;
+ E->key()->pass = pass;
+ p_results[index] = E->key()->owner;
+ p_result_indices[index] = E->key()->subindex;
index++;
-
}
}
-int BroadPhase2DHashGrid::cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhase2DHashGrid::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
pass++;
- Vector2 dir = (p_to-p_from);
- if (dir==Vector2())
+ Vector2 dir = (p_to - p_from);
+ if (dir == Vector2())
return 0;
//avoid divisions by zero
dir.normalize();
- if (dir.x==0.0)
- dir.x=0.000001;
- if (dir.y==0.0)
- dir.y=0.000001;
+ if (dir.x == 0.0)
+ dir.x = 0.000001;
+ if (dir.y == 0.0)
+ dir.y = 0.000001;
Vector2 delta = dir.abs();
- delta.x=cell_size/delta.x;
- delta.y=cell_size/delta.y;
+ delta.x = cell_size / delta.x;
+ delta.y = cell_size / delta.y;
- Point2i pos = (p_from/cell_size).floor();
- Point2i end = (p_to/cell_size).floor();
+ Point2i pos = (p_from / cell_size).floor();
+ Point2i end = (p_to / cell_size).floor();
- Point2i step = Vector2( SGN(dir.x), SGN(dir.y) );
+ Point2i step = Vector2(SGN(dir.x), SGN(dir.y));
Vector2 max;
- if (dir.x<0)
- max.x= (Math::floor((double)pos.x)*cell_size - p_from.x) / dir.x;
+ if (dir.x < 0)
+ max.x = (Math::floor((double)pos.x) * cell_size - p_from.x) / dir.x;
else
- max.x= (Math::floor((double)pos.x + 1)*cell_size - p_from.x) / dir.x;
+ max.x = (Math::floor((double)pos.x + 1) * cell_size - p_from.x) / dir.x;
- if (dir.y<0)
- max.y= (Math::floor((double)pos.y)*cell_size - p_from.y) / dir.y;
+ if (dir.y < 0)
+ max.y = (Math::floor((double)pos.y) * cell_size - p_from.y) / dir.y;
else
- max.y= (Math::floor((double)pos.y + 1)*cell_size - p_from.y) / dir.y;
+ max.y = (Math::floor((double)pos.y + 1) * cell_size - p_from.y) / dir.y;
- int cullcount=0;
- _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount);
+ int cullcount = 0;
+ _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
- bool reached_x=false;
- bool reached_y=false;
+ bool reached_x = false;
+ bool reached_y = false;
- while(true) {
+ while (true) {
if (max.x < max.y) {
- max.x+=delta.x;
- pos.x+=step.x;
+ max.x += delta.x;
+ pos.x += step.x;
} else {
- max.y+=delta.y;
- pos.y+=step.y;
-
+ max.y += delta.y;
+ pos.y += step.y;
}
- if (step.x>0) {
- if (pos.x>=end.x)
- reached_x=true;
- } else if (pos.x<=end.x) {
+ if (step.x > 0) {
+ if (pos.x >= end.x)
+ reached_x = true;
+ } else if (pos.x <= end.x) {
- reached_x=true;
+ reached_x = true;
}
- if (step.y>0) {
- if (pos.y>=end.y)
- reached_y=true;
- } else if (pos.y<=end.y) {
+ if (step.y > 0) {
+ if (pos.y >= end.y)
+ reached_y = true;
+ } else if (pos.y <= end.y) {
- reached_y=true;
+ reached_y = true;
}
- _cull<false,true>(pos,Rect2(),p_from,p_to,p_results,p_max_results,p_result_indices,cullcount);
+ _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
if (reached_x && reached_y)
break;
-
}
- for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
- if (cullcount>=p_max_results)
+ if (cullcount >= p_max_results)
break;
- if (E->key()->pass==pass)
+ if (E->key()->pass == pass)
continue;
- E->key()->pass=pass;
+ E->key()->pass = pass;
/*
if (use_aabb && !p_aabb.intersects(E->key()->aabb))
continue;
*/
- if (!E->key()->aabb.intersects_segment(p_from,p_to))
+ if (!E->key()->aabb.intersects_segment(p_from, p_to))
continue;
- p_results[cullcount]=E->key()->owner;
- p_result_indices[cullcount]=E->key()->subindex;
+ p_results[cullcount] = E->key()->owner;
+ p_result_indices[cullcount] = E->key()->subindex;
cullcount++;
-
-
}
return cullcount;
}
-
-int BroadPhase2DHashGrid::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices) {
+int BroadPhase2DHashGrid::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
pass++;
- Point2i from = (p_aabb.pos/cell_size).floor();
- Point2i to = ((p_aabb.pos+p_aabb.size)/cell_size).floor();
- int cullcount=0;
+ Point2i from = (p_aabb.pos / cell_size).floor();
+ Point2i to = ((p_aabb.pos + p_aabb.size) / cell_size).floor();
+ int cullcount = 0;
- for(int i=from.x;i<=to.x;i++) {
+ for (int i = from.x; i <= to.x; i++) {
- for(int j=from.y;j<=to.y;j++) {
+ for (int j = from.y; j <= to.y; j++) {
- _cull<true,false>(Point2i(i,j),p_aabb,Point2(),Point2(),p_results,p_max_results,p_result_indices,cullcount);
+ _cull<true, false>(Point2i(i, j), p_aabb, Point2(), Point2(), p_results, p_max_results, p_result_indices, cullcount);
}
-
}
- for (Map<Element*,RC>::Element *E=large_elements.front();E;E=E->next()) {
+ for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
- if (cullcount>=p_max_results)
+ if (cullcount >= p_max_results)
break;
- if (E->key()->pass==pass)
+ if (E->key()->pass == pass)
continue;
- E->key()->pass=pass;
+ E->key()->pass = pass;
if (!p_aabb.intersects(E->key()->aabb))
continue;
@@ -652,72 +602,61 @@ int BroadPhase2DHashGrid::cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_
continue;
*/
- p_results[cullcount]=E->key()->owner;
- p_result_indices[cullcount]=E->key()->subindex;
+ p_results[cullcount] = E->key()->owner;
+ p_result_indices[cullcount] = E->key()->subindex;
cullcount++;
-
-
}
return cullcount;
}
-void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback,void *p_userdata) {
-
- pair_callback=p_pair_callback;
- pair_userdata=p_userdata;
+void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
+ pair_callback = p_pair_callback;
+ pair_userdata = p_userdata;
}
-void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata) {
-
- unpair_callback=p_unpair_callback;
- unpair_userdata=p_userdata;
+void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) {
+ unpair_callback = p_unpair_callback;
+ unpair_userdata = p_userdata;
}
void BroadPhase2DHashGrid::update() {
-
-
}
BroadPhase2DSW *BroadPhase2DHashGrid::_create() {
- return memnew( BroadPhase2DHashGrid );
+ return memnew(BroadPhase2DHashGrid);
}
-
BroadPhase2DHashGrid::BroadPhase2DHashGrid() {
- hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size",4096);
+ hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size", 4096);
hash_table_size = Math::larger_prime(hash_table_size);
- hash_table = memnew_arr( PosBin*, hash_table_size);
+ hash_table = memnew_arr(PosBin *, hash_table_size);
- cell_size = GLOBAL_DEF("physics/2d/cell_size",128);
- large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_treshold_in_cells",512);
+ cell_size = GLOBAL_DEF("physics/2d/cell_size", 128);
+ large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_treshold_in_cells", 512);
- for(int i=0;i<hash_table_size;i++)
- hash_table[i]=NULL;
- pass=1;
+ for (int i = 0; i < hash_table_size; i++)
+ hash_table[i] = NULL;
+ pass = 1;
- current=0;
+ current = 0;
}
BroadPhase2DHashGrid::~BroadPhase2DHashGrid() {
- for(int i=0;i<hash_table_size;i++) {
- while(hash_table[i]) {
- PosBin *pb=hash_table[i];
- hash_table[i]=pb->next;
+ for (int i = 0; i < hash_table_size; i++) {
+ while (hash_table[i]) {
+ PosBin *pb = hash_table[i];
+ hash_table[i] = pb->next;
memdelete(pb);
}
}
- memdelete_arr( hash_table );
-
-
+ memdelete_arr(hash_table);
}
-
-
/* 3D version of voxel traversal:
public IEnumerable<Point3D> GetCellsOnRay(Ray ray, int maxDepth)
diff --git a/servers/physics_2d/broad_phase_2d_hash_grid.h b/servers/physics_2d/broad_phase_2d_hash_grid.h
index 857053ccf0..f30f72d6db 100644
--- a/servers/physics_2d/broad_phase_2d_hash_grid.h
+++ b/servers/physics_2d/broad_phase_2d_hash_grid.h
@@ -34,13 +34,16 @@
class BroadPhase2DHashGrid : public BroadPhase2DSW {
-
struct PairData {
bool colliding;
int rc;
void *ud;
- PairData() { colliding=false; rc=1; ud=NULL; }
+ PairData() {
+ colliding = false;
+ rc = 1;
+ ud = NULL;
+ }
};
struct Element {
@@ -51,8 +54,7 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
Rect2 aabb;
int subindex;
uint64_t pass;
- Map<Element*,PairData*> paired;
-
+ Map<Element *, PairData *> paired;
};
struct RC {
@@ -69,18 +71,17 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
}
_FORCE_INLINE_ RC() {
- ref=0;
+ ref = 0;
}
};
- Map<ID,Element> element_map;
- Map<Element*,RC> large_elements;
+ Map<ID, Element> element_map;
+ Map<Element *, RC> large_elements;
ID current;
uint64_t pass;
-
struct PairKey {
union {
@@ -91,17 +92,23 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
uint64_t key;
};
- _FORCE_INLINE_ bool operator<(const PairKey& p_key) const {
+ _FORCE_INLINE_ bool operator<(const PairKey &p_key) const {
return key < p_key.key;
}
- PairKey() { key=0; }
- PairKey(ID p_a, ID p_b) { if (p_a>p_b) { a=p_b; b=p_a; } else { a=p_a; b=p_b; }}
-
+ PairKey() { key = 0; }
+ PairKey(ID p_a, ID p_b) {
+ if (p_a > p_b) {
+ a = p_b;
+ b = p_a;
+ } else {
+ a = p_a;
+ b = p_b;
+ }
+ }
};
-
- Map<PairKey,PairData> pair_map;
+ Map<PairKey, PairData> pair_map;
int cell_size;
int large_object_min_surface;
@@ -111,11 +118,10 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
UnpairCallback unpair_callback;
void *unpair_userdata;
- void _enter_grid(Element* p_elem, const Rect2& p_rect,bool p_static);
- void _exit_grid(Element* p_elem, const Rect2& p_rect,bool p_static);
- template<bool use_aabb,bool use_segment>
- _FORCE_INLINE_ void _cull(const Point2i p_cell,const Rect2& p_aabb,const Point2& p_from, const Point2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices,int &index);
-
+ void _enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static);
+ void _exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static);
+ template <bool use_aabb, bool use_segment>
+ _FORCE_INLINE_ void _cull(const Point2i p_cell, const Rect2 &p_aabb, const Point2 &p_from, const Point2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices, int &index);
struct PosKey {
@@ -127,9 +133,8 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
uint64_t key;
};
-
_FORCE_INLINE_ uint32_t hash() const {
- uint64_t k=key;
+ uint64_t k = key;
k = (~k) + (k << 18); // k = (k << 18) - k - 1;
k = k ^ (k >> 31);
k = k * 21; // k = (k + (k << 2)) + (k << 4);
@@ -139,36 +144,30 @@ class BroadPhase2DHashGrid : public BroadPhase2DSW {
return k;
}
- bool operator==(const PosKey& p_key) const { return key==p_key.key; }
- _FORCE_INLINE_ bool operator<(const PosKey& p_key) const {
+ bool operator==(const PosKey &p_key) const { return key == p_key.key; }
+ _FORCE_INLINE_ bool operator<(const PosKey &p_key) const {
return key < p_key.key;
}
-
};
-
-
struct PosBin {
PosKey key;
- Map<Element*,RC> object_set;
- Map<Element*,RC> static_object_set;
+ Map<Element *, RC> object_set;
+ Map<Element *, RC> static_object_set;
PosBin *next;
};
-
uint32_t hash_table_size;
PosBin **hash_table;
- void _pair_attempt(Element *p_elem, Element* p_with);
- void _unpair_attempt(Element *p_elem, Element* p_with);
+ void _pair_attempt(Element *p_elem, Element *p_with);
+ void _unpair_attempt(Element *p_elem, Element *p_with);
void _check_motion(Element *p_elem);
-
public:
-
- virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0);
- virtual void move(ID p_id, const Rect2& p_aabb);
+ virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0);
+ virtual void move(ID p_id, const Rect2 &p_aabb);
virtual void set_static(ID p_id, bool p_static);
virtual void remove(ID p_id);
@@ -176,21 +175,18 @@ public:
virtual bool is_static(ID p_id) const;
virtual int get_subindex(ID p_id) const;
- virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL);
- virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL);
+ virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL);
+ virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL);
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata);
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata);
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata);
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata);
virtual void update();
-
static BroadPhase2DSW *_create();
BroadPhase2DHashGrid();
~BroadPhase2DHashGrid();
-
-
};
#endif // BROAD_PHASE_2D_HASH_GRID_H
diff --git a/servers/physics_2d/broad_phase_2d_sw.cpp b/servers/physics_2d/broad_phase_2d_sw.cpp
index 4347155c2c..8cde46217b 100644
--- a/servers/physics_2d/broad_phase_2d_sw.cpp
+++ b/servers/physics_2d/broad_phase_2d_sw.cpp
@@ -28,8 +28,7 @@
/*************************************************************************/
#include "broad_phase_2d_sw.h"
-BroadPhase2DSW::CreateFunction BroadPhase2DSW::create_func=NULL;
+BroadPhase2DSW::CreateFunction BroadPhase2DSW::create_func = NULL;
-BroadPhase2DSW::~BroadPhase2DSW()
-{
+BroadPhase2DSW::~BroadPhase2DSW() {
}
diff --git a/servers/physics_2d/broad_phase_2d_sw.h b/servers/physics_2d/broad_phase_2d_sw.h
index b9ec434ae9..a255cc6ba7 100644
--- a/servers/physics_2d/broad_phase_2d_sw.h
+++ b/servers/physics_2d/broad_phase_2d_sw.h
@@ -29,45 +29,42 @@
#ifndef BROAD_PHASE_2D_SW_H
#define BROAD_PHASE_2D_SW_H
-#include "math_funcs.h"
#include "math_2d.h"
+#include "math_funcs.h"
class CollisionObject2DSW;
-
class BroadPhase2DSW {
public:
- typedef BroadPhase2DSW* (*CreateFunction)();
+ typedef BroadPhase2DSW *(*CreateFunction)();
static CreateFunction create_func;
typedef uint32_t ID;
-
- typedef void* (*PairCallback)(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_userdata);
- typedef void (*UnpairCallback)(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_userdata);
+ typedef void *(*PairCallback)(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_userdata);
+ typedef void (*UnpairCallback)(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_userdata);
// 0 is an invalid ID
- virtual ID create(CollisionObject2DSW *p_object_, int p_subindex=0)=0;
- virtual void move(ID p_id, const Rect2& p_aabb)=0;
- virtual void set_static(ID p_id, bool p_static)=0;
- virtual void remove(ID p_id)=0;
+ virtual ID create(CollisionObject2DSW *p_object_, int p_subindex = 0) = 0;
+ virtual void move(ID p_id, const Rect2 &p_aabb) = 0;
+ virtual void set_static(ID p_id, bool p_static) = 0;
+ virtual void remove(ID p_id) = 0;
- virtual CollisionObject2DSW *get_object(ID p_id) const=0;
- virtual bool is_static(ID p_id) const=0;
- virtual int get_subindex(ID p_id) const=0;
+ virtual CollisionObject2DSW *get_object(ID p_id) const = 0;
+ virtual bool is_static(ID p_id) const = 0;
+ virtual int get_subindex(ID p_id) const = 0;
- virtual int cull_segment(const Vector2& p_from, const Vector2& p_to,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL)=0;
- virtual int cull_aabb(const Rect2& p_aabb,CollisionObject2DSW** p_results,int p_max_results,int *p_result_indices=NULL)=0;
+ virtual int cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0;
+ virtual int cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices = NULL) = 0;
- virtual void set_pair_callback(PairCallback p_pair_callback,void *p_userdata)=0;
- virtual void set_unpair_callback(UnpairCallback p_unpair_callback,void *p_userdata)=0;
+ virtual void set_pair_callback(PairCallback p_pair_callback, void *p_userdata) = 0;
+ virtual void set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) = 0;
- virtual void update()=0;
+ virtual void update() = 0;
virtual ~BroadPhase2DSW();
-
};
#endif // BROAD_PHASE_2D_SW_H
diff --git a/servers/physics_2d/collision_object_2d_sw.cpp b/servers/physics_2d/collision_object_2d_sw.cpp
index 9ae0e40417..30bb9f6b52 100644
--- a/servers/physics_2d/collision_object_2d_sw.cpp
+++ b/servers/physics_2d/collision_object_2d_sw.cpp
@@ -29,46 +29,43 @@
#include "collision_object_2d_sw.h"
#include "space_2d_sw.h"
-void CollisionObject2DSW::add_shape(Shape2DSW *p_shape,const Transform2D& p_transform) {
+void CollisionObject2DSW::add_shape(Shape2DSW *p_shape, const Transform2D &p_transform) {
Shape s;
- s.shape=p_shape;
- s.xform=p_transform;
- s.xform_inv=s.xform.affine_inverse();
- s.bpid=0; //needs update
- s.trigger=false;
+ s.shape = p_shape;
+ s.xform = p_transform;
+ s.xform_inv = s.xform.affine_inverse();
+ s.bpid = 0; //needs update
+ s.trigger = false;
shapes.push_back(s);
p_shape->add_owner(this);
_update_shapes();
_shapes_changed();
-
}
-void CollisionObject2DSW::set_shape(int p_index,Shape2DSW *p_shape){
+void CollisionObject2DSW::set_shape(int p_index, Shape2DSW *p_shape) {
- ERR_FAIL_INDEX(p_index,shapes.size());
+ ERR_FAIL_INDEX(p_index, shapes.size());
shapes[p_index].shape->remove_owner(this);
- shapes[p_index].shape=p_shape;
+ shapes[p_index].shape = p_shape;
p_shape->add_owner(this);
_update_shapes();
_shapes_changed();
-
}
-void CollisionObject2DSW::set_shape_metadata(int p_index,const Variant& p_metadata) {
-
- ERR_FAIL_INDEX(p_index,shapes.size());
- shapes[p_index].metadata=p_metadata;
+void CollisionObject2DSW::set_shape_metadata(int p_index, const Variant &p_metadata) {
+ ERR_FAIL_INDEX(p_index, shapes.size());
+ shapes[p_index].metadata = p_metadata;
}
-void CollisionObject2DSW::set_shape_transform(int p_index,const Transform2D& p_transform){
+void CollisionObject2DSW::set_shape_transform(int p_index, const Transform2D &p_transform) {
- ERR_FAIL_INDEX(p_index,shapes.size());
+ ERR_FAIL_INDEX(p_index, shapes.size());
- shapes[p_index].xform=p_transform;
- shapes[p_index].xform_inv=p_transform.affine_inverse();
+ shapes[p_index].xform = p_transform;
+ shapes[p_index].xform_inv = p_transform.affine_inverse();
_update_shapes();
_shapes_changed();
}
@@ -76,61 +73,58 @@ void CollisionObject2DSW::set_shape_transform(int p_index,const Transform2D& p_t
void CollisionObject2DSW::remove_shape(Shape2DSW *p_shape) {
//remove a shape, all the times it appears
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- if (shapes[i].shape==p_shape) {
+ if (shapes[i].shape == p_shape) {
remove_shape(i);
i--;
}
}
}
-void CollisionObject2DSW::remove_shape(int p_index){
+void CollisionObject2DSW::remove_shape(int p_index) {
//remove anything from shape to be erased to end, so subindices don't change
- ERR_FAIL_INDEX(p_index,shapes.size());
- for(int i=p_index;i<shapes.size();i++) {
+ ERR_FAIL_INDEX(p_index, shapes.size());
+ for (int i = p_index; i < shapes.size(); i++) {
- if (shapes[i].bpid==0)
+ if (shapes[i].bpid == 0)
continue;
//should never get here with a null owner
space->get_broadphase()->remove(shapes[i].bpid);
- shapes[i].bpid=0;
+ shapes[i].bpid = 0;
}
shapes[p_index].shape->remove_owner(this);
shapes.remove(p_index);
_shapes_changed();
-
}
void CollisionObject2DSW::_set_static(bool p_static) {
- if (_static==p_static)
+ if (_static == p_static)
return;
- _static=p_static;
+ _static = p_static;
if (!space)
return;
- for(int i=0;i<get_shape_count();i++) {
- Shape &s=shapes[i];
- if (s.bpid>0) {
- space->get_broadphase()->set_static(s.bpid,_static);
+ for (int i = 0; i < get_shape_count(); i++) {
+ Shape &s = shapes[i];
+ if (s.bpid > 0) {
+ space->get_broadphase()->set_static(s.bpid, _static);
}
}
-
}
void CollisionObject2DSW::_unregister_shapes() {
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
- if (s.bpid>0) {
+ Shape &s = shapes[i];
+ if (s.bpid > 0) {
space->get_broadphase()->remove(s.bpid);
- s.bpid=0;
+ s.bpid = 0;
}
}
-
}
void CollisionObject2DSW::_update_shapes() {
@@ -138,53 +132,47 @@ void CollisionObject2DSW::_update_shapes() {
if (!space)
return;
+ for (int i = 0; i < shapes.size(); i++) {
- for(int i=0;i<shapes.size();i++) {
-
- Shape &s=shapes[i];
- if (s.bpid==0) {
- s.bpid=space->get_broadphase()->create(this,i);
- space->get_broadphase()->set_static(s.bpid,_static);
+ Shape &s = shapes[i];
+ if (s.bpid == 0) {
+ s.bpid = space->get_broadphase()->create(this, i);
+ space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
- Rect2 shape_aabb=s.shape->get_aabb();
+ Rect2 shape_aabb = s.shape->get_aabb();
Transform2D xform = transform * s.xform;
- shape_aabb=xform.xform(shape_aabb);
- s.aabb_cache=shape_aabb;
- s.aabb_cache=s.aabb_cache.grow( (s.aabb_cache.size.x + s.aabb_cache.size.y)*0.5*0.05 );
+ shape_aabb = xform.xform(shape_aabb);
+ s.aabb_cache = shape_aabb;
+ s.aabb_cache = s.aabb_cache.grow((s.aabb_cache.size.x + s.aabb_cache.size.y) * 0.5 * 0.05);
-
- space->get_broadphase()->move(s.bpid,s.aabb_cache);
+ space->get_broadphase()->move(s.bpid, s.aabb_cache);
}
-
}
-void CollisionObject2DSW::_update_shapes_with_motion(const Vector2& p_motion) {
-
+void CollisionObject2DSW::_update_shapes_with_motion(const Vector2 &p_motion) {
if (!space)
return;
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
- if (s.bpid==0) {
- s.bpid=space->get_broadphase()->create(this,i);
- space->get_broadphase()->set_static(s.bpid,_static);
+ Shape &s = shapes[i];
+ if (s.bpid == 0) {
+ s.bpid = space->get_broadphase()->create(this, i);
+ space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
- Rect2 shape_aabb=s.shape->get_aabb();
+ Rect2 shape_aabb = s.shape->get_aabb();
Transform2D xform = transform * s.xform;
- shape_aabb=xform.xform(shape_aabb);
- shape_aabb=shape_aabb.merge(Rect2( shape_aabb.pos+p_motion,shape_aabb.size)); //use motion
- s.aabb_cache=shape_aabb;
+ shape_aabb = xform.xform(shape_aabb);
+ shape_aabb = shape_aabb.merge(Rect2(shape_aabb.pos + p_motion, shape_aabb.size)); //use motion
+ s.aabb_cache = shape_aabb;
- space->get_broadphase()->move(s.bpid,shape_aabb);
+ space->get_broadphase()->move(s.bpid, shape_aabb);
}
-
-
}
void CollisionObject2DSW::_set_space(Space2DSW *p_space) {
@@ -193,25 +181,23 @@ void CollisionObject2DSW::_set_space(Space2DSW *p_space) {
space->remove_object(this);
- for(int i=0;i<shapes.size();i++) {
+ for (int i = 0; i < shapes.size(); i++) {
- Shape &s=shapes[i];
+ Shape &s = shapes[i];
if (s.bpid) {
space->get_broadphase()->remove(s.bpid);
- s.bpid=0;
+ s.bpid = 0;
}
}
-
}
- space=p_space;
+ space = p_space;
if (space) {
space->add_object(this);
_update_shapes();
}
-
}
void CollisionObject2DSW::_shape_changed() {
@@ -222,11 +208,11 @@ void CollisionObject2DSW::_shape_changed() {
CollisionObject2DSW::CollisionObject2DSW(Type p_type) {
- _static=true;
- type=p_type;
- space=NULL;
- instance_id=0;
- collision_mask=1;
- layer_mask=1;
- pickable=true;
+ _static = true;
+ type = p_type;
+ space = NULL;
+ instance_id = 0;
+ collision_mask = 1;
+ layer_mask = 1;
+ pickable = true;
}
diff --git a/servers/physics_2d/collision_object_2d_sw.h b/servers/physics_2d/collision_object_2d_sw.h
index 0f77e9b426..e6eec05f3d 100644
--- a/servers/physics_2d/collision_object_2d_sw.h
+++ b/servers/physics_2d/collision_object_2d_sw.h
@@ -29,10 +29,10 @@
#ifndef COLLISION_OBJECT_2D_SW_H
#define COLLISION_OBJECT_2D_SW_H
-#include "shape_2d_sw.h"
-#include "servers/physics_2d_server.h"
-#include "self_list.h"
#include "broad_phase_2d_sw.h"
+#include "self_list.h"
+#include "servers/physics_2d_server.h"
+#include "shape_2d_sw.h"
class Space2DSW;
@@ -42,8 +42,8 @@ public:
TYPE_AREA,
TYPE_BODY
};
-private:
+private:
Type type;
RID self;
ObjectID instance_id;
@@ -58,7 +58,7 @@ private:
Shape2DSW *shape;
Variant metadata;
bool trigger;
- Shape() { trigger=false; }
+ Shape() { trigger = false; }
};
Vector<Shape> shapes;
@@ -72,74 +72,74 @@ private:
void _update_shapes();
protected:
-
-
- void _update_shapes_with_motion(const Vector2& p_motion);
+ void _update_shapes_with_motion(const Vector2 &p_motion);
void _unregister_shapes();
- _FORCE_INLINE_ void _set_transform(const Transform2D& p_transform, bool p_update_shapes=true) { transform=p_transform; if (p_update_shapes) {_update_shapes();} }
- _FORCE_INLINE_ void _set_inv_transform(const Transform2D& p_transform) { inv_transform=p_transform; }
+ _FORCE_INLINE_ void _set_transform(const Transform2D &p_transform, bool p_update_shapes = true) {
+ transform = p_transform;
+ if (p_update_shapes) {
+ _update_shapes();
+ }
+ }
+ _FORCE_INLINE_ void _set_inv_transform(const Transform2D &p_transform) { inv_transform = p_transform; }
void _set_static(bool p_static);
- virtual void _shapes_changed()=0;
+ virtual void _shapes_changed() = 0;
void _set_space(Space2DSW *space);
CollisionObject2DSW(Type p_type);
-public:
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+public:
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
- _FORCE_INLINE_ void set_instance_id(const ObjectID& p_instance_id) { instance_id=p_instance_id; }
+ _FORCE_INLINE_ void set_instance_id(const ObjectID &p_instance_id) { instance_id = p_instance_id; }
_FORCE_INLINE_ ObjectID get_instance_id() const { return instance_id; }
void _shape_changed();
_FORCE_INLINE_ Type get_type() const { return type; }
- void add_shape(Shape2DSW *p_shape,const Transform2D& p_transform=Transform2D());
- void set_shape(int p_index,Shape2DSW *p_shape);
- void set_shape_transform(int p_index,const Transform2D& p_transform);
- void set_shape_metadata(int p_index,const Variant& p_metadata);
-
+ void add_shape(Shape2DSW *p_shape, const Transform2D &p_transform = Transform2D());
+ void set_shape(int p_index, Shape2DSW *p_shape);
+ void set_shape_transform(int p_index, const Transform2D &p_transform);
+ void set_shape_metadata(int p_index, const Variant &p_metadata);
_FORCE_INLINE_ int get_shape_count() const { return shapes.size(); }
_FORCE_INLINE_ Shape2DSW *get_shape(int p_index) const { return shapes[p_index].shape; }
- _FORCE_INLINE_ const Transform2D& get_shape_transform(int p_index) const { return shapes[p_index].xform; }
- _FORCE_INLINE_ const Transform2D& get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; }
- _FORCE_INLINE_ const Rect2& get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; }
- _FORCE_INLINE_ const Variant& get_shape_metadata(int p_index) const { return shapes[p_index].metadata; }
+ _FORCE_INLINE_ const Transform2D &get_shape_transform(int p_index) const { return shapes[p_index].xform; }
+ _FORCE_INLINE_ const Transform2D &get_shape_inv_transform(int p_index) const { return shapes[p_index].xform_inv; }
+ _FORCE_INLINE_ const Rect2 &get_shape_aabb(int p_index) const { return shapes[p_index].aabb_cache; }
+ _FORCE_INLINE_ const Variant &get_shape_metadata(int p_index) const { return shapes[p_index].metadata; }
_FORCE_INLINE_ Transform2D get_transform() const { return transform; }
_FORCE_INLINE_ Transform2D get_inv_transform() const { return inv_transform; }
- _FORCE_INLINE_ Space2DSW* get_space() const { return space; }
+ _FORCE_INLINE_ Space2DSW *get_space() const { return space; }
- _FORCE_INLINE_ void set_shape_as_trigger(int p_idx,bool p_enable) { shapes[p_idx].trigger=p_enable; }
+ _FORCE_INLINE_ void set_shape_as_trigger(int p_idx, bool p_enable) { shapes[p_idx].trigger = p_enable; }
_FORCE_INLINE_ bool is_shape_set_as_trigger(int p_idx) const { return shapes[p_idx].trigger; }
-
- void set_collision_mask(uint32_t p_mask) {collision_mask=p_mask;}
+ void set_collision_mask(uint32_t p_mask) { collision_mask = p_mask; }
_FORCE_INLINE_ uint32_t get_collision_mask() const { return collision_mask; }
- void set_layer_mask(uint32_t p_mask) {layer_mask=p_mask;}
+ void set_layer_mask(uint32_t p_mask) { layer_mask = p_mask; }
_FORCE_INLINE_ uint32_t get_layer_mask() const { return layer_mask; }
void remove_shape(Shape2DSW *p_shape);
void remove_shape(int p_index);
- virtual void set_space(Space2DSW *p_space)=0;
+ virtual void set_space(Space2DSW *p_space) = 0;
- _FORCE_INLINE_ bool is_static() const { return _static; }
+ _FORCE_INLINE_ bool is_static() const { return _static; }
- void set_pickable(bool p_pickable) { pickable=p_pickable; }
+ void set_pickable(bool p_pickable) { pickable = p_pickable; }
_FORCE_INLINE_ bool is_pickable() const { return pickable; }
- _FORCE_INLINE_ bool test_collision_mask(CollisionObject2DSW* p_other) const {
+ _FORCE_INLINE_ bool test_collision_mask(CollisionObject2DSW *p_other) const {
- return layer_mask&p_other->collision_mask || p_other->layer_mask&collision_mask;
+ return layer_mask & p_other->collision_mask || p_other->layer_mask & collision_mask;
}
virtual ~CollisionObject2DSW() {}
-
};
#endif // COLLISION_OBJECT_2D_SW_H
diff --git a/servers/physics_2d/collision_solver_2d_sat.cpp b/servers/physics_2d/collision_solver_2d_sat.cpp
index 4c116cee3f..f72a7ef0e4 100644
--- a/servers/physics_2d/collision_solver_2d_sat.cpp
+++ b/servers/physics_2d/collision_solver_2d_sat.cpp
@@ -38,61 +38,57 @@ struct _CollectorCallback2D {
Vector2 normal;
Vector2 *sep_axis;
- _FORCE_INLINE_ void call(const Vector2& p_point_A, const Vector2& p_point_B) {
+ _FORCE_INLINE_ void call(const Vector2 &p_point_A, const Vector2 &p_point_B) {
/*
if (normal.dot(p_point_A) >= normal.dot(p_point_B))
return;
*/
if (swap)
- callback(p_point_B,p_point_A,userdata);
+ callback(p_point_B, p_point_A, userdata);
else
- callback(p_point_A,p_point_B,userdata);
+ callback(p_point_A, p_point_B, userdata);
}
-
};
-typedef void (*GenerateContactsFunc)(const Vector2 *,int, const Vector2 *,int ,_CollectorCallback2D *);
-
+typedef void (*GenerateContactsFunc)(const Vector2 *, int, const Vector2 *, int, _CollectorCallback2D *);
-_FORCE_INLINE_ static void _generate_contacts_point_point(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) {
+_FORCE_INLINE_ static void _generate_contacts_point_point(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 1 );
- ERR_FAIL_COND( p_point_count_B != 1 );
+ ERR_FAIL_COND(p_point_count_A != 1);
+ ERR_FAIL_COND(p_point_count_B != 1);
#endif
- p_collector->call(*p_points_A,*p_points_B);
+ p_collector->call(*p_points_A, *p_points_B);
}
-_FORCE_INLINE_ static void _generate_contacts_point_edge(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) {
+_FORCE_INLINE_ static void _generate_contacts_point_edge(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 1 );
- ERR_FAIL_COND( p_point_count_B != 2 );
+ ERR_FAIL_COND(p_point_count_A != 1);
+ ERR_FAIL_COND(p_point_count_B != 2);
#endif
- Vector2 closest_B = Geometry::get_closest_point_to_segment_uncapped_2d(*p_points_A, p_points_B );
- p_collector->call(*p_points_A,closest_B);
-
+ Vector2 closest_B = Geometry::get_closest_point_to_segment_uncapped_2d(*p_points_A, p_points_B);
+ p_collector->call(*p_points_A, closest_B);
}
-
struct _generate_contacts_Pair {
bool a;
int idx;
real_t d;
- _FORCE_INLINE_ bool operator <(const _generate_contacts_Pair& l) const { return d< l.d; }
+ _FORCE_INLINE_ bool operator<(const _generate_contacts_Pair &l) const { return d < l.d; }
};
-_FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) {
+_FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A != 2 );
- ERR_FAIL_COND( p_point_count_B != 2 ); // circle is actually a 4x3 matrix
+ ERR_FAIL_COND(p_point_count_A != 2);
+ ERR_FAIL_COND(p_point_count_B != 2); // circle is actually a 4x3 matrix
#endif
-# if 0
+#if 0
Vector2 rel_A=p_points_A[1]-p_points_A[0];
Vector2 rel_B=p_points_B[1]-p_points_B[0];
@@ -210,9 +206,6 @@ _FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points
#if 1
-
-
-
Vector2 n = p_collector->normal;
Vector2 t = n.tangent();
real_t dA = n.dot(p_points_A[0]);
@@ -220,90 +213,87 @@ _FORCE_INLINE_ static void _generate_contacts_edge_edge(const Vector2 * p_points
_generate_contacts_Pair dvec[4];
- dvec[0].d=t.dot(p_points_A[0]);
- dvec[0].a=true;
- dvec[0].idx=0;
- dvec[1].d=t.dot(p_points_A[1]);
- dvec[1].a=true;
- dvec[1].idx=1;
- dvec[2].d=t.dot(p_points_B[0]);
- dvec[2].a=false;
- dvec[2].idx=0;
- dvec[3].d=t.dot(p_points_B[1]);
- dvec[3].a=false;
- dvec[3].idx=1;
+ dvec[0].d = t.dot(p_points_A[0]);
+ dvec[0].a = true;
+ dvec[0].idx = 0;
+ dvec[1].d = t.dot(p_points_A[1]);
+ dvec[1].a = true;
+ dvec[1].idx = 1;
+ dvec[2].d = t.dot(p_points_B[0]);
+ dvec[2].a = false;
+ dvec[2].idx = 0;
+ dvec[3].d = t.dot(p_points_B[1]);
+ dvec[3].a = false;
+ dvec[3].idx = 1;
SortArray<_generate_contacts_Pair> sa;
- sa.sort(dvec,4);
+ sa.sort(dvec, 4);
- for(int i=1;i<=2;i++) {
+ for (int i = 1; i <= 2; i++) {
if (dvec[i].a) {
Vector2 a = p_points_A[dvec[i].idx];
- Vector2 b = n.plane_project(dB,a);
- if (n.dot(a) > n.dot(b)-CMP_EPSILON)
+ Vector2 b = n.plane_project(dB, a);
+ if (n.dot(a) > n.dot(b) - CMP_EPSILON)
continue;
- p_collector->call(a,b);
+ p_collector->call(a, b);
} else {
Vector2 b = p_points_B[dvec[i].idx];
- Vector2 a = n.plane_project(dA,b);
- if (n.dot(a) > n.dot(b)-CMP_EPSILON)
+ Vector2 a = n.plane_project(dA, b);
+ if (n.dot(a) > n.dot(b) - CMP_EPSILON)
continue;
- p_collector->call(a,b);
+ p_collector->call(a, b);
}
}
-
-
#elif 0
Vector2 axis = rel_A.normalized(); //make an axis
Vector2 axis_B = rel_B.normalized();
- if (axis.dot(axis_B)<0)
- axis_B=-axis_B;
- axis=(axis+axis_B)*0.5;
+ if (axis.dot(axis_B) < 0)
+ axis_B = -axis_B;
+ axis = (axis + axis_B) * 0.5;
Vector2 base_A = p_points_A[0] - axis * axis.dot(p_points_A[0]);
Vector2 base_B = p_points_B[0] - axis * axis.dot(p_points_B[0]);
//sort all 4 points in axis
- real_t dvec[4]={ axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) };
+ real_t dvec[4] = { axis.dot(p_points_A[0]), axis.dot(p_points_A[1]), axis.dot(p_points_B[0]), axis.dot(p_points_B[1]) };
//todo , find max/min and then use 2 central points
SortArray<real_t> sa;
- sa.sort(dvec,4);
+ sa.sort(dvec, 4);
//use the middle ones as contacts
- for (int i=1;i<=2;i++) {
+ for (int i = 1; i <= 2; i++) {
- Vector2 a = base_A+axis*dvec[i];
- Vector2 b = base_B+axis*dvec[i];
- if (p_collector->normal.dot(a) > p_collector->normal.dot(b)-0.01) {
- print_line("fail a: "+a);
- print_line("fail b: "+b);
+ Vector2 a = base_A + axis * dvec[i];
+ Vector2 b = base_B + axis * dvec[i];
+ if (p_collector->normal.dot(a) > p_collector->normal.dot(b) - 0.01) {
+ print_line("fail a: " + a);
+ print_line("fail b: " + b);
continue;
}
- print_line("res a: "+a);
- print_line("res b: "+b);
- p_collector->call(a,b);
+ print_line("res a: " + a);
+ print_line("res b: " + b);
+ p_collector->call(a, b);
}
#endif
}
-static void _generate_contacts_from_supports(const Vector2 * p_points_A,int p_point_count_A, const Vector2 * p_points_B,int p_point_count_B,_CollectorCallback2D *p_collector) {
-
+static void _generate_contacts_from_supports(const Vector2 *p_points_A, int p_point_count_A, const Vector2 *p_points_B, int p_point_count_B, _CollectorCallback2D *p_collector) {
#ifdef DEBUG_ENABLED
- ERR_FAIL_COND( p_point_count_A <1 );
- ERR_FAIL_COND( p_point_count_B <1 );
+ ERR_FAIL_COND(p_point_count_A < 1);
+ ERR_FAIL_COND(p_point_count_B < 1);
#endif
-
- static const GenerateContactsFunc generate_contacts_func_table[2][2]={
+ static const GenerateContactsFunc generate_contacts_func_table[2][2] = {
{
- _generate_contacts_point_point,
- _generate_contacts_point_edge,
- },{
- 0,
- _generate_contacts_edge_edge,
+ _generate_contacts_point_point,
+ _generate_contacts_point_edge,
+ },
+ {
+ 0,
+ _generate_contacts_edge_edge,
}
};
@@ -319,28 +309,25 @@ static void _generate_contacts_from_supports(const Vector2 * p_points_A,int p_po
pointcount_B = p_point_count_A;
pointcount_A = p_point_count_B;
- points_A=p_points_B;
- points_B=p_points_A;
+ points_A = p_points_B;
+ points_B = p_points_A;
} else {
pointcount_B = p_point_count_B;
pointcount_A = p_point_count_A;
- points_A=p_points_A;
- points_B=p_points_B;
+ points_A = p_points_A;
+ points_B = p_points_B;
}
- int version_A = (pointcount_A > 3 ? 3 : pointcount_A) -1;
- int version_B = (pointcount_B > 3 ? 3 : pointcount_B) -1;
+ int version_A = (pointcount_A > 3 ? 3 : pointcount_A) - 1;
+ int version_B = (pointcount_B > 3 ? 3 : pointcount_B) - 1;
GenerateContactsFunc contacts_func = generate_contacts_func_table[version_A][version_B];
ERR_FAIL_COND(!contacts_func);
- contacts_func(points_A,pointcount_A,points_B,pointcount_B,p_collector);
-
+ contacts_func(points_A, pointcount_A, points_B, pointcount_B, p_collector);
}
-
-
-template<class ShapeA, class ShapeB,bool castA=false,bool castB=false, bool withMargin=false>
+template <class ShapeA, class ShapeB, bool castA = false, bool castB = false, bool withMargin = false>
class SeparatorAxisTest2D {
const ShapeA *shape_A;
@@ -358,16 +345,14 @@ class SeparatorAxisTest2D {
_CollectorCallback2D *callback;
public:
-
_FORCE_INLINE_ bool test_previous_axis() {
- if (callback && callback->sep_axis && *callback->sep_axis!=Vector2()) {
+ if (callback && callback->sep_axis && *callback->sep_axis != Vector2()) {
return test_axis(*callback->sep_axis);
} else {
#ifdef DEBUG_ENABLED
best_axis_count++;
#endif
-
}
return true;
}
@@ -395,45 +380,44 @@ public:
return true;
}
- _FORCE_INLINE_ bool test_axis(const Vector2& p_axis) {
+ _FORCE_INLINE_ bool test_axis(const Vector2 &p_axis) {
- Vector2 axis=p_axis;
+ Vector2 axis = p_axis;
-
- if ( Math::abs(axis.x)<CMP_EPSILON &&
- Math::abs(axis.y)<CMP_EPSILON) {
+ if (Math::abs(axis.x) < CMP_EPSILON &&
+ Math::abs(axis.y) < CMP_EPSILON) {
// strange case, try an upwards separator
- axis=Vector2(0.0,1.0);
+ axis = Vector2(0.0, 1.0);
}
- real_t min_A,max_A,min_B,max_B;
+ real_t min_A, max_A, min_B, max_B;
if (castA)
- shape_A->project_range_cast(motion_A,axis,*transform_A,min_A,max_A);
+ shape_A->project_range_cast(motion_A, axis, *transform_A, min_A, max_A);
else
- shape_A->project_range(axis,*transform_A,min_A,max_A);
+ shape_A->project_range(axis, *transform_A, min_A, max_A);
if (castB)
- shape_B->project_range_cast(motion_B,axis,*transform_B,min_B,max_B);
+ shape_B->project_range_cast(motion_B, axis, *transform_B, min_B, max_B);
else
- shape_B->project_range(axis,*transform_B,min_B,max_B);
+ shape_B->project_range(axis, *transform_B, min_B, max_B);
if (withMargin) {
- min_A-=margin_A;
- max_A+=margin_A;
- min_B-=margin_B;
- max_B+=margin_B;
+ min_A -= margin_A;
+ max_A += margin_A;
+ min_B -= margin_B;
+ max_B += margin_B;
}
- min_B -= ( max_A - min_A ) * 0.5;
- max_B += ( max_A - min_A ) * 0.5;
+ min_B -= (max_A - min_A) * 0.5;
+ max_B += (max_A - min_A) * 0.5;
- real_t dmin = min_B - ( min_A + max_A ) * 0.5;
- real_t dmax = max_B - ( min_A + max_A ) * 0.5;
+ real_t dmin = min_B - (min_A + max_A) * 0.5;
+ real_t dmax = max_B - (min_A + max_A) * 0.5;
if (dmin > 0.0 || dmax < 0.0) {
if (callback && callback->sep_axis)
- *callback->sep_axis=axis;
+ *callback->sep_axis = axis;
#ifdef DEBUG_ENABLED
best_axis_count++;
#endif
@@ -445,26 +429,25 @@ public:
dmin = Math::abs(dmin);
- if ( dmax < dmin ) {
- if ( dmax < best_depth ) {
- best_depth=dmax;
- best_axis=axis;
+ if (dmax < dmin) {
+ if (dmax < best_depth) {
+ best_depth = dmax;
+ best_axis = axis;
#ifdef DEBUG_ENABLED
- best_axis_index=best_axis_count;
+ best_axis_index = best_axis_count;
#endif
-
}
} else {
- if ( dmin < best_depth ) {
- best_depth=dmin;
- best_axis=-axis; // keep it as A axis
+ if (dmin < best_depth) {
+ best_depth = dmin;
+ best_axis = -axis; // keep it as A axis
#ifdef DEBUG_ENABLED
- best_axis_index=best_axis_count;
+ best_axis_index = best_axis_count;
#endif
}
}
- //print_line("test axis: "+p_axis+" depth: "+rtos(best_depth));
+//print_line("test axis: "+p_axis+" depth: "+rtos(best_depth));
#ifdef DEBUG_ENABLED
best_axis_count++;
#endif
@@ -472,60 +455,55 @@ public:
return true;
}
-
_FORCE_INLINE_ void generate_contacts() {
// nothing to do, don't generate
- if (best_axis==Vector2(0.0,0.0))
+ if (best_axis == Vector2(0.0, 0.0))
return;
- callback->collided=true;
+ callback->collided = true;
if (!callback->callback)
return; //only collide, no callback
- static const int max_supports=2;
+ static const int max_supports = 2;
Vector2 supports_A[max_supports];
int support_count_A;
if (castA) {
- shape_A->get_supports_transformed_cast(motion_A,-best_axis,*transform_A,supports_A,support_count_A);
+ shape_A->get_supports_transformed_cast(motion_A, -best_axis, *transform_A, supports_A, support_count_A);
} else {
- shape_A->get_supports(transform_A->basis_xform_inv(-best_axis).normalized(),supports_A,support_count_A);
- for(int i=0;i<support_count_A;i++) {
+ shape_A->get_supports(transform_A->basis_xform_inv(-best_axis).normalized(), supports_A, support_count_A);
+ for (int i = 0; i < support_count_A; i++) {
supports_A[i] = transform_A->xform(supports_A[i]);
}
}
if (withMargin) {
- for(int i=0;i<support_count_A;i++) {
- supports_A[i]+=-best_axis*margin_A;
+ for (int i = 0; i < support_count_A; i++) {
+ supports_A[i] += -best_axis * margin_A;
}
-
}
-
-
Vector2 supports_B[max_supports];
int support_count_B;
if (castB) {
- shape_B->get_supports_transformed_cast(motion_B,best_axis,*transform_B,supports_B,support_count_B);
+ shape_B->get_supports_transformed_cast(motion_B, best_axis, *transform_B, supports_B, support_count_B);
} else {
- shape_B->get_supports(transform_B->basis_xform_inv(best_axis).normalized(),supports_B,support_count_B);
- for(int i=0;i<support_count_B;i++) {
+ shape_B->get_supports(transform_B->basis_xform_inv(best_axis).normalized(), supports_B, support_count_B);
+ for (int i = 0; i < support_count_B; i++) {
supports_B[i] = transform_B->xform(supports_B[i]);
}
}
if (withMargin) {
- for(int i=0;i<support_count_B;i++) {
- supports_B[i]+=best_axis*margin_B;
+ for (int i = 0; i < support_count_B; i++) {
+ supports_B[i] += best_axis * margin_B;
}
-
}
-/*
+ /*
print_line("**************************");
@@ -549,38 +527,33 @@ public:
}
//*/
+ callback->normal = best_axis;
+ _generate_contacts_from_supports(supports_A, support_count_A, supports_B, support_count_B, callback);
-
-
- callback->normal=best_axis;
- _generate_contacts_from_supports(supports_A,support_count_A,supports_B,support_count_B,callback);
-
- if (callback && callback->sep_axis && *callback->sep_axis!=Vector2())
- *callback->sep_axis=Vector2(); //invalidate previous axis (no test)
+ if (callback && callback->sep_axis && *callback->sep_axis != Vector2())
+ *callback->sep_axis = Vector2(); //invalidate previous axis (no test)
//CollisionSolver2DSW::CallbackResult cbk=NULL;
//cbk(Vector2(),Vector2(),NULL);
-
}
- _FORCE_INLINE_ SeparatorAxisTest2D(const ShapeA *p_shape_A,const Transform2D& p_transform_a, const ShapeB *p_shape_B,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_A=Vector2(), const Vector2& p_motion_B=Vector2(),real_t p_margin_A=0,real_t p_margin_B=0) {
+ _FORCE_INLINE_ SeparatorAxisTest2D(const ShapeA *p_shape_A, const Transform2D &p_transform_a, const ShapeB *p_shape_B, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_A = Vector2(), const Vector2 &p_motion_B = Vector2(), real_t p_margin_A = 0, real_t p_margin_B = 0) {
- margin_A=p_margin_A;
- margin_B=p_margin_B;
- best_depth=1e15;
- shape_A=p_shape_A;
- shape_B=p_shape_B;
- transform_A=&p_transform_a;
- transform_B=&p_transform_b;
- motion_A=p_motion_A;
- motion_B=p_motion_B;
+ margin_A = p_margin_A;
+ margin_B = p_margin_B;
+ best_depth = 1e15;
+ shape_A = p_shape_A;
+ shape_B = p_shape_B;
+ transform_A = &p_transform_a;
+ transform_B = &p_transform_b;
+ motion_A = p_motion_A;
+ motion_B = p_motion_B;
- callback=p_collector;
+ callback = p_collector;
#ifdef DEBUG_ENABLED
- best_axis_count=0;
- best_axis_index=-1;
+ best_axis_count = 0;
+ best_axis_index = -1;
#endif
}
-
};
/****** SAT TESTS *******/
@@ -588,30 +561,26 @@ public:
/****** SAT TESTS *******/
/****** SAT TESTS *******/
+#define TEST_POINT(m_a, m_b) \
+ ((!separator.test_axis(((m_a) - (m_b)).normalized())) || \
+ (castA && !separator.test_axis(((m_a) + p_motion_a - (m_b)).normalized())) || \
+ (castB && !separator.test_axis(((m_a) - ((m_b) + p_motion_b)).normalized())) || \
+ (castA && castB && !separator.test_axis(((m_a) + p_motion_a - ((m_b) + p_motion_b)).normalized())))
-#define TEST_POINT(m_a,m_b) \
- ( (!separator.test_axis(((m_a)-(m_b)).normalized())) ||\
- (castA && !separator.test_axis(((m_a)+p_motion_a-(m_b)).normalized())) ||\
- (castB && !separator.test_axis(((m_a)-((m_b)+p_motion_b)).normalized())) ||\
- (castA && castB && !separator.test_axis(((m_a)+p_motion_a-((m_b)+p_motion_b)).normalized())) )
-
-
-typedef void (*CollisionFunc)(const Shape2DSW*,const Transform2D&,const Shape2DSW*,const Transform2D&,_CollectorCallback2D *p_collector,const Vector2&,const Vector2&,real_t,real_t);
-
+typedef void (*CollisionFunc)(const Shape2DSW *, const Transform2D &, const Shape2DSW *, const Transform2D &, _CollectorCallback2D *p_collector, const Vector2 &, const Vector2 &, real_t, real_t);
-template<bool castA, bool castB,bool withMargin>
-static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_segment_segment(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a);
- const SegmentShape2DSW *segment_B = static_cast<const SegmentShape2DSW*>(p_b);
+ const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a);
+ const SegmentShape2DSW *segment_B = static_cast<const SegmentShape2DSW *>(p_b);
- SeparatorAxisTest2D<SegmentShape2DSW,SegmentShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,segment_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<SegmentShape2DSW, SegmentShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, segment_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
//this collision is kind of pointless
-
/*
if (!separator.test_previous_axis())
return;
@@ -620,7 +589,6 @@ static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p
if (!separator.test_cast())
return;
-
if (!separator.test_axis(segment_A->get_xformed_normal(p_transform_a)))
return;
if (!separator.test_axis(segment_B->get_xformed_normal(p_transform_b)))
@@ -629,30 +597,26 @@ static void _collision_segment_segment(const Shape2DSW* p_a,const Transform2D& p
if (withMargin) {
//points grow to circles
-
- if (TEST_POINT( p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(segment_B->get_a())) )
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(segment_B->get_a())))
return;
- if (TEST_POINT( p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(segment_B->get_b())) )
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(segment_B->get_b())))
return;
- if (TEST_POINT( p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(segment_B->get_a())) )
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(segment_B->get_a())))
return;
- if (TEST_POINT( p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(segment_B->get_b())) )
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(segment_B->get_b())))
return;
}
separator.generate_contacts();
-
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_segment_circle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
-
- const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a);
- const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_segment_circle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a);
+ const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW *>(p_b);
- SeparatorAxisTest2D<SegmentShape2DSW,CircleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,circle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<SegmentShape2DSW, CircleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, circle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -662,28 +626,26 @@ static void _collision_segment_circle(const Shape2DSW* p_a,const Transform2D& p_
//segment normal
if (!separator.test_axis(
- (p_transform_a.xform(segment_A->get_b())-p_transform_a.xform(segment_A->get_a())).normalized().tangent()
- ))
+ (p_transform_a.xform(segment_A->get_b()) - p_transform_a.xform(segment_A->get_a())).normalized().tangent()))
return;
//endpoint a vs circle
- if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),p_transform_b.get_origin()))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.get_origin()))
return;
//endpoint b vs circle
- if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),p_transform_b.get_origin()))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.get_origin()))
return;
-
separator.generate_contacts();
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_segment_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_segment_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a);
- const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b);
+ const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a);
+ const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b);
- SeparatorAxisTest2D<SegmentShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<SegmentShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -707,48 +669,46 @@ static void _collision_segment_rectangle(const Shape2DSW* p_a,const Transform2D&
Vector2 a = p_transform_a.xform(segment_A->get_a());
Vector2 b = p_transform_a.xform(segment_A->get_b());
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a)))
return;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b)))
return;
if (castA) {
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a+p_motion_a)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a + p_motion_a)))
return;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b+p_motion_a)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b + p_motion_a)))
return;
}
if (castB) {
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a-p_motion_b)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a - p_motion_b)))
return;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b-p_motion_b)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b - p_motion_b)))
return;
}
if (castA && castB) {
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,a-p_motion_b+p_motion_a)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, a - p_motion_b + p_motion_a)))
return;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,inv,b-p_motion_b+p_motion_a)))
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, inv, b - p_motion_b + p_motion_a)))
return;
}
-
}
separator.generate_contacts();
-
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_segment_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_segment_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a);
- const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b);
+ const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a);
+ const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b);
- SeparatorAxisTest2D<SegmentShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<SegmentShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -762,25 +722,25 @@ static void _collision_segment_capsule(const Shape2DSW* p_a,const Transform2D& p
if (!separator.test_axis(p_transform_b.elements[0].normalized()))
return;
- if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5)))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5)))
return;
- if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5)))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5)))
return;
- if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5)))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5)))
return;
- if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5)))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5)))
return;
separator.generate_contacts();
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_segment_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_segment_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW*>(p_a);
- const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b);
+ const SegmentShape2DSW *segment_A = static_cast<const SegmentShape2DSW *>(p_a);
+ const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b);
- SeparatorAxisTest2D<SegmentShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(segment_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<SegmentShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(segment_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -791,37 +751,32 @@ static void _collision_segment_convex_polygon(const Shape2DSW* p_a,const Transfo
if (!separator.test_axis(segment_A->get_xformed_normal(p_transform_a)))
return;
- for(int i=0;i<convex_B->get_point_count();i++) {
+ for (int i = 0; i < convex_B->get_point_count(); i++) {
- if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i)))
+ if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i)))
return;
if (withMargin) {
- if (TEST_POINT(p_transform_a.xform(segment_A->get_a()),p_transform_b.xform(convex_B->get_point(i) )))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_a()), p_transform_b.xform(convex_B->get_point(i))))
return;
- if (TEST_POINT(p_transform_a.xform(segment_A->get_b()),p_transform_b.xform(convex_B->get_point(i) )))
+ if (TEST_POINT(p_transform_a.xform(segment_A->get_b()), p_transform_b.xform(convex_B->get_point(i))))
return;
-
}
-
}
separator.generate_contacts();
-
}
-
/////////
-template<bool castA, bool castB,bool withMargin>
-static void _collision_circle_circle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a);
- const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_circle_circle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a);
+ const CircleShape2DSW *circle_B = static_cast<const CircleShape2DSW *>(p_b);
- SeparatorAxisTest2D<CircleShape2DSW,CircleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,circle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CircleShape2DSW, CircleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, circle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -829,22 +784,19 @@ static void _collision_circle_circle(const Shape2DSW* p_a,const Transform2D& p_t
if (!separator.test_cast())
return;
- if (TEST_POINT(p_transform_a.get_origin(),p_transform_b.get_origin()))
+ if (TEST_POINT(p_transform_a.get_origin(), p_transform_b.get_origin()))
return;
-
separator.generate_contacts();
-
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a);
- const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_circle_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a);
+ const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b);
- SeparatorAxisTest2D<CircleShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CircleShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -852,8 +804,8 @@ static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D&
if (!separator.test_cast())
return;
- const Vector2 &sphere=p_transform_a.elements[2];
- const Vector2 *axis=&p_transform_b.elements[0];
+ const Vector2 &sphere = p_transform_a.elements[2];
+ const Vector2 *axis = &p_transform_b.elements[0];
//const Vector2& half_extents = rectangle_B->get_half_extents();
if (!separator.test_axis(axis[0].normalized()))
@@ -865,42 +817,41 @@ static void _collision_circle_rectangle(const Shape2DSW* p_a,const Transform2D&
Transform2D binv = p_transform_b.affine_inverse();
{
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv,sphere ) ) )
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphere)))
return;
}
if (castA) {
Vector2 sphereofs = sphere + p_motion_a;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) )
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs)))
return;
}
if (castB) {
Vector2 sphereofs = sphere - p_motion_b;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) )
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs)))
return;
}
if (castA && castB) {
Vector2 sphereofs = sphere - p_motion_b + p_motion_a;
- if (!separator.test_axis( rectangle_B->get_circle_axis(p_transform_b,binv, sphereofs) ) )
+ if (!separator.test_axis(rectangle_B->get_circle_axis(p_transform_b, binv, sphereofs)))
return;
}
separator.generate_contacts();
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_circle_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_circle_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a);
- const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b);
+ const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a);
+ const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b);
-
- SeparatorAxisTest2D<CircleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CircleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -913,24 +864,21 @@ static void _collision_circle_capsule(const Shape2DSW* p_a,const Transform2D& p_
return;
//capsule endpoints
- if (TEST_POINT(p_transform_a.get_origin(),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*0.5)))
+ if (TEST_POINT(p_transform_a.get_origin(), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * 0.5)))
return;
- if (TEST_POINT(p_transform_a.get_origin(),(p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*-0.5)))
+ if (TEST_POINT(p_transform_a.get_origin(), (p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * -0.5)))
return;
separator.generate_contacts();
-
-
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_circle_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
+template <bool castA, bool castB, bool withMargin>
+static void _collision_circle_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW*>(p_a);
- const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b);
+ const CircleShape2DSW *circle_A = static_cast<const CircleShape2DSW *>(p_a);
+ const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b);
-
- SeparatorAxisTest2D<CircleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(circle_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CircleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(circle_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -938,31 +886,28 @@ static void _collision_circle_convex_polygon(const Shape2DSW* p_a,const Transfor
if (!separator.test_cast())
return;
-
//poly faces and poly points vs circle
- for(int i=0;i<convex_B->get_point_count();i++) {
+ for (int i = 0; i < convex_B->get_point_count(); i++) {
- if (TEST_POINT( p_transform_a.get_origin(),p_transform_b.xform(convex_B->get_point(i)) ))
+ if (TEST_POINT(p_transform_a.get_origin(), p_transform_b.xform(convex_B->get_point(i))))
return;
- if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i)))
+ if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i)))
return;
}
separator.generate_contacts();
}
-
/////////
-template<bool castA, bool castB,bool withMargin>
-static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a);
- const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_rectangle_rectangle(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a);
+ const RectangleShape2DSW *rectangle_B = static_cast<const RectangleShape2DSW *>(p_b);
- SeparatorAxisTest2D<RectangleShape2DSW,RectangleShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,rectangle_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<RectangleShape2DSW, RectangleShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, rectangle_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -986,38 +931,38 @@ static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2
if (withMargin) {
- Transform2D invA=p_transform_a.affine_inverse();
- Transform2D invB=p_transform_b.affine_inverse();
+ Transform2D invA = p_transform_a.affine_inverse();
+ Transform2D invB = p_transform_b.affine_inverse();
- if (!separator.test_axis( rectangle_A->get_box_axis(p_transform_a,invA,rectangle_B,p_transform_b,invB) ) )
+ if (!separator.test_axis(rectangle_A->get_box_axis(p_transform_a, invA, rectangle_B, p_transform_b, invB)))
return;
if (castA || castB) {
Transform2D aofs = p_transform_a;
- aofs.elements[2]+=p_motion_a;
+ aofs.elements[2] += p_motion_a;
Transform2D bofs = p_transform_b;
- bofs.elements[2]+=p_motion_b;
+ bofs.elements[2] += p_motion_b;
Transform2D aofsinv = aofs.affine_inverse();
Transform2D bofsinv = bofs.affine_inverse();
if (castA) {
- if (!separator.test_axis( rectangle_A->get_box_axis(aofs,aofsinv,rectangle_B,p_transform_b,invB) ) )
+ if (!separator.test_axis(rectangle_A->get_box_axis(aofs, aofsinv, rectangle_B, p_transform_b, invB)))
return;
}
if (castB) {
- if (!separator.test_axis( rectangle_A->get_box_axis(p_transform_a,invA,rectangle_B,bofs,bofsinv) ) )
+ if (!separator.test_axis(rectangle_A->get_box_axis(p_transform_a, invA, rectangle_B, bofs, bofsinv)))
return;
}
if (castA && castB) {
- if (!separator.test_axis( rectangle_A->get_box_axis(aofs,aofsinv,rectangle_B,bofs,bofsinv) ) )
+ if (!separator.test_axis(rectangle_A->get_box_axis(aofs, aofsinv, rectangle_B, bofs, bofsinv)))
return;
}
}
@@ -1026,14 +971,13 @@ static void _collision_rectangle_rectangle(const Shape2DSW* p_a,const Transform2
separator.generate_contacts();
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_rectangle_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a);
- const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_rectangle_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a);
+ const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b);
- SeparatorAxisTest2D<RectangleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<RectangleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -1052,61 +996,55 @@ static void _collision_rectangle_capsule(const Shape2DSW* p_a,const Transform2D&
if (!separator.test_axis(p_transform_b.elements[0].normalized()))
return;
-
//box endpoints to capsule circles
Transform2D boxinv = p_transform_a.affine_inverse();
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
{
- Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5);
+ Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5);
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint)))
return;
}
-
if (castA) {
- Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5);
- capsule_endpoint-=p_motion_a;
+ Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5);
+ capsule_endpoint -= p_motion_a;
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint)))
return;
}
if (castB) {
- Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5);
- capsule_endpoint+=p_motion_b;
+ Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5);
+ capsule_endpoint += p_motion_b;
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint)))
return;
}
if (castA && castB) {
- Vector2 capsule_endpoint = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(i==0?0.5:-0.5);
- capsule_endpoint-=p_motion_a;
- capsule_endpoint+=p_motion_b;
-
+ Vector2 capsule_endpoint = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (i == 0 ? 0.5 : -0.5);
+ capsule_endpoint -= p_motion_a;
+ capsule_endpoint += p_motion_b;
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,capsule_endpoint)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, capsule_endpoint)))
return;
}
-
}
-
separator.generate_contacts();
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_rectangle_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW*>(p_a);
- const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_rectangle_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
- SeparatorAxisTest2D<RectangleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(rectangle_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ const RectangleShape2DSW *rectangle_A = static_cast<const RectangleShape2DSW *>(p_a);
+ const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b);
+ SeparatorAxisTest2D<RectangleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(rectangle_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -1124,51 +1062,47 @@ static void _collision_rectangle_convex_polygon(const Shape2DSW* p_a,const Trans
//convex faces
Transform2D boxinv;
if (withMargin) {
- boxinv=p_transform_a.affine_inverse();
+ boxinv = p_transform_a.affine_inverse();
}
- for(int i=0;i<convex_B->get_point_count();i++) {
+ for (int i = 0; i < convex_B->get_point_count(); i++) {
- if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i)))
+ if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i)))
return;
if (withMargin) {
//all points vs all points need to be tested if margin exist
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i)))))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)))))
return;
if (castA) {
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))-p_motion_a)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) - p_motion_a)))
return;
}
if (castB) {
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))+p_motion_b)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) + p_motion_b)))
return;
}
if (castA && castB) {
- if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a,boxinv,p_transform_b.xform(convex_B->get_point(i))+p_motion_b-p_motion_a)))
+ if (!separator.test_axis(rectangle_A->get_circle_axis(p_transform_a, boxinv, p_transform_b.xform(convex_B->get_point(i)) + p_motion_b - p_motion_a)))
return;
}
-
}
}
separator.generate_contacts();
-
}
-
/////////
-template<bool castA, bool castB,bool withMargin>
-static void _collision_capsule_capsule(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW*>(p_a);
- const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_capsule_capsule(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW *>(p_a);
+ const CapsuleShape2DSW *capsule_B = static_cast<const CapsuleShape2DSW *>(p_b);
- SeparatorAxisTest2D<CapsuleShape2DSW,CapsuleShape2DSW,castA,castB,withMargin> separator(capsule_A,p_transform_a,capsule_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CapsuleShape2DSW, CapsuleShape2DSW, castA, castB, withMargin> separator(capsule_A, p_transform_a, capsule_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -1186,32 +1120,29 @@ static void _collision_capsule_capsule(const Shape2DSW* p_a,const Transform2D& p
//capsule endpoints
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- Vector2 capsule_endpoint_A = p_transform_a.get_origin()+p_transform_a.elements[1]*capsule_A->get_height()*(i==0?0.5:-0.5);
+ Vector2 capsule_endpoint_A = p_transform_a.get_origin() + p_transform_a.elements[1] * capsule_A->get_height() * (i == 0 ? 0.5 : -0.5);
- for(int j=0;j<2;j++) {
+ for (int j = 0; j < 2; j++) {
- Vector2 capsule_endpoint_B = p_transform_b.get_origin()+p_transform_b.elements[1]*capsule_B->get_height()*(j==0?0.5:-0.5);
+ Vector2 capsule_endpoint_B = p_transform_b.get_origin() + p_transform_b.elements[1] * capsule_B->get_height() * (j == 0 ? 0.5 : -0.5);
- if (TEST_POINT(capsule_endpoint_A,capsule_endpoint_B) )
+ if (TEST_POINT(capsule_endpoint_A, capsule_endpoint_B))
return;
-
}
}
separator.generate_contacts();
-
}
-template<bool castA, bool castB,bool withMargin>
-static void _collision_capsule_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
- const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW*>(p_a);
- const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b);
+template <bool castA, bool castB, bool withMargin>
+static void _collision_capsule_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
+ const CapsuleShape2DSW *capsule_A = static_cast<const CapsuleShape2DSW *>(p_a);
+ const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b);
- SeparatorAxisTest2D<CapsuleShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(capsule_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<CapsuleShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(capsule_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -1224,40 +1155,35 @@ static void _collision_capsule_convex_polygon(const Shape2DSW* p_a,const Transfo
if (!separator.test_axis(p_transform_a.elements[0].normalized()))
return;
-
//poly vs capsule
- for(int i=0;i<convex_B->get_point_count();i++) {
+ for (int i = 0; i < convex_B->get_point_count(); i++) {
Vector2 cpoint = p_transform_b.xform(convex_B->get_point(i));
- for(int j=0;j<2;j++) {
+ for (int j = 0; j < 2; j++) {
- Vector2 capsule_endpoint_A = p_transform_a.get_origin()+p_transform_a.elements[1]*capsule_A->get_height()*(j==0?0.5:-0.5);
+ Vector2 capsule_endpoint_A = p_transform_a.get_origin() + p_transform_a.elements[1] * capsule_A->get_height() * (j == 0 ? 0.5 : -0.5);
- if (TEST_POINT(capsule_endpoint_A,cpoint ))
+ if (TEST_POINT(capsule_endpoint_A, cpoint))
return;
-
}
- if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i)))
+ if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i)))
return;
}
separator.generate_contacts();
}
-
/////////
+template <bool castA, bool castB, bool withMargin>
+static void _collision_convex_polygon_convex_polygon(const Shape2DSW *p_a, const Transform2D &p_transform_a, const Shape2DSW *p_b, const Transform2D &p_transform_b, _CollectorCallback2D *p_collector, const Vector2 &p_motion_a, const Vector2 &p_motion_b, real_t p_margin_A, real_t p_margin_B) {
-template<bool castA, bool castB,bool withMargin>
-static void _collision_convex_polygon_convex_polygon(const Shape2DSW* p_a,const Transform2D& p_transform_a,const Shape2DSW* p_b,const Transform2D& p_transform_b,_CollectorCallback2D *p_collector,const Vector2& p_motion_a,const Vector2& p_motion_b,real_t p_margin_A,real_t p_margin_B) {
-
+ const ConvexPolygonShape2DSW *convex_A = static_cast<const ConvexPolygonShape2DSW *>(p_a);
+ const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW *>(p_b);
- const ConvexPolygonShape2DSW *convex_A = static_cast<const ConvexPolygonShape2DSW*>(p_a);
- const ConvexPolygonShape2DSW *convex_B = static_cast<const ConvexPolygonShape2DSW*>(p_b);
-
- SeparatorAxisTest2D<ConvexPolygonShape2DSW,ConvexPolygonShape2DSW,castA,castB,withMargin> separator(convex_A,p_transform_a,convex_B,p_transform_b,p_collector,p_motion_a,p_motion_b,p_margin_A,p_margin_B);
+ SeparatorAxisTest2D<ConvexPolygonShape2DSW, ConvexPolygonShape2DSW, castA, castB, withMargin> separator(convex_A, p_transform_a, convex_B, p_transform_b, p_collector, p_motion_a, p_motion_b, p_margin_A, p_margin_B);
if (!separator.test_previous_axis())
return;
@@ -1265,345 +1191,332 @@ static void _collision_convex_polygon_convex_polygon(const Shape2DSW* p_a,const
if (!separator.test_cast())
return;
+ for (int i = 0; i < convex_A->get_point_count(); i++) {
- for(int i=0;i<convex_A->get_point_count();i++) {
-
- if (!separator.test_axis( convex_A->get_xformed_segment_normal(p_transform_a,i)))
+ if (!separator.test_axis(convex_A->get_xformed_segment_normal(p_transform_a, i)))
return;
}
- for(int i=0;i<convex_B->get_point_count();i++) {
+ for (int i = 0; i < convex_B->get_point_count(); i++) {
- if (!separator.test_axis( convex_B->get_xformed_segment_normal(p_transform_b,i)))
+ if (!separator.test_axis(convex_B->get_xformed_segment_normal(p_transform_b, i)))
return;
-
}
if (withMargin) {
- for(int i=0;i<convex_A->get_point_count();i++) {
- for(int j=0;j<convex_B->get_point_count();j++) {
+ for (int i = 0; i < convex_A->get_point_count(); i++) {
+ for (int j = 0; j < convex_B->get_point_count(); j++) {
- if (TEST_POINT(p_transform_a.xform(convex_A->get_point(i)) , p_transform_b.xform(convex_B->get_point(j))))
+ if (TEST_POINT(p_transform_a.xform(convex_A->get_point(i)), p_transform_b.xform(convex_B->get_point(j))))
return;
}
}
-
}
separator.generate_contacts();
-
}
-
////////
-bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D& p_transform_A, const Vector2& p_motion_A, const Shape2DSW *p_shape_B, const Transform2D& p_transform_B,const Vector2& p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) {
+bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) {
- Physics2DServer::ShapeType type_A=p_shape_A->get_type();
+ Physics2DServer::ShapeType type_A = p_shape_A->get_type();
- ERR_FAIL_COND_V(type_A==Physics2DServer::SHAPE_LINE,false);
+ ERR_FAIL_COND_V(type_A == Physics2DServer::SHAPE_LINE, false);
//ERR_FAIL_COND_V(type_A==Physics2DServer::SHAPE_RAY,false);
- ERR_FAIL_COND_V(p_shape_A->is_concave(),false);
+ ERR_FAIL_COND_V(p_shape_A->is_concave(), false);
- Physics2DServer::ShapeType type_B=p_shape_B->get_type();
+ Physics2DServer::ShapeType type_B = p_shape_B->get_type();
- ERR_FAIL_COND_V(type_B==Physics2DServer::SHAPE_LINE,false);
+ ERR_FAIL_COND_V(type_B == Physics2DServer::SHAPE_LINE, false);
//ERR_FAIL_COND_V(type_B==Physics2DServer::SHAPE_RAY,false);
- ERR_FAIL_COND_V(p_shape_B->is_concave(),false);
-
-
- static const CollisionFunc collision_table[5][5]={
- {_collision_segment_segment<false,false,false>,
- _collision_segment_circle<false,false,false>,
- _collision_segment_rectangle<false,false,false>,
- _collision_segment_capsule<false,false,false>,
- _collision_segment_convex_polygon<false,false,false>},
- {0,
- _collision_circle_circle<false,false,false>,
- _collision_circle_rectangle<false,false,false>,
- _collision_circle_capsule<false,false,false>,
- _collision_circle_convex_polygon<false,false,false>},
- {0,
- 0,
- _collision_rectangle_rectangle<false,false,false>,
- _collision_rectangle_capsule<false,false,false>,
- _collision_rectangle_convex_polygon<false,false,false>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<false,false,false>,
- _collision_capsule_convex_polygon<false,false,false>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<false,false,false>}
+ ERR_FAIL_COND_V(p_shape_B->is_concave(), false);
+
+ static const CollisionFunc collision_table[5][5] = {
+ { _collision_segment_segment<false, false, false>,
+ _collision_segment_circle<false, false, false>,
+ _collision_segment_rectangle<false, false, false>,
+ _collision_segment_capsule<false, false, false>,
+ _collision_segment_convex_polygon<false, false, false> },
+ { 0,
+ _collision_circle_circle<false, false, false>,
+ _collision_circle_rectangle<false, false, false>,
+ _collision_circle_capsule<false, false, false>,
+ _collision_circle_convex_polygon<false, false, false> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<false, false, false>,
+ _collision_rectangle_capsule<false, false, false>,
+ _collision_rectangle_convex_polygon<false, false, false> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<false, false, false>,
+ _collision_capsule_convex_polygon<false, false, false> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<false, false, false> }
};
- static const CollisionFunc collision_table_castA[5][5]={
- {_collision_segment_segment<true,false,false>,
- _collision_segment_circle<true,false,false>,
- _collision_segment_rectangle<true,false,false>,
- _collision_segment_capsule<true,false,false>,
- _collision_segment_convex_polygon<true,false,false>},
- {0,
- _collision_circle_circle<true,false,false>,
- _collision_circle_rectangle<true,false,false>,
- _collision_circle_capsule<true,false,false>,
- _collision_circle_convex_polygon<true,false,false>},
- {0,
- 0,
- _collision_rectangle_rectangle<true,false,false>,
- _collision_rectangle_capsule<true,false,false>,
- _collision_rectangle_convex_polygon<true,false,false>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<true,false,false>,
- _collision_capsule_convex_polygon<true,false,false>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<true,false,false>}
+ static const CollisionFunc collision_table_castA[5][5] = {
+ { _collision_segment_segment<true, false, false>,
+ _collision_segment_circle<true, false, false>,
+ _collision_segment_rectangle<true, false, false>,
+ _collision_segment_capsule<true, false, false>,
+ _collision_segment_convex_polygon<true, false, false> },
+ { 0,
+ _collision_circle_circle<true, false, false>,
+ _collision_circle_rectangle<true, false, false>,
+ _collision_circle_capsule<true, false, false>,
+ _collision_circle_convex_polygon<true, false, false> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<true, false, false>,
+ _collision_rectangle_capsule<true, false, false>,
+ _collision_rectangle_convex_polygon<true, false, false> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<true, false, false>,
+ _collision_capsule_convex_polygon<true, false, false> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<true, false, false> }
};
- static const CollisionFunc collision_table_castB[5][5]={
- {_collision_segment_segment<false,true,false>,
- _collision_segment_circle<false,true,false>,
- _collision_segment_rectangle<false,true,false>,
- _collision_segment_capsule<false,true,false>,
- _collision_segment_convex_polygon<false,true,false>},
- {0,
- _collision_circle_circle<false,true,false>,
- _collision_circle_rectangle<false,true,false>,
- _collision_circle_capsule<false,true,false>,
- _collision_circle_convex_polygon<false,true,false>},
- {0,
- 0,
- _collision_rectangle_rectangle<false,true,false>,
- _collision_rectangle_capsule<false,true,false>,
- _collision_rectangle_convex_polygon<false,true,false>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<false,true,false>,
- _collision_capsule_convex_polygon<false,true,false>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<false,true,false>}
+ static const CollisionFunc collision_table_castB[5][5] = {
+ { _collision_segment_segment<false, true, false>,
+ _collision_segment_circle<false, true, false>,
+ _collision_segment_rectangle<false, true, false>,
+ _collision_segment_capsule<false, true, false>,
+ _collision_segment_convex_polygon<false, true, false> },
+ { 0,
+ _collision_circle_circle<false, true, false>,
+ _collision_circle_rectangle<false, true, false>,
+ _collision_circle_capsule<false, true, false>,
+ _collision_circle_convex_polygon<false, true, false> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<false, true, false>,
+ _collision_rectangle_capsule<false, true, false>,
+ _collision_rectangle_convex_polygon<false, true, false> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<false, true, false>,
+ _collision_capsule_convex_polygon<false, true, false> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<false, true, false> }
};
- static const CollisionFunc collision_table_castA_castB[5][5]={
- {_collision_segment_segment<true,true,false>,
- _collision_segment_circle<true,true,false>,
- _collision_segment_rectangle<true,true,false>,
- _collision_segment_capsule<true,true,false>,
- _collision_segment_convex_polygon<true,true,false>},
- {0,
- _collision_circle_circle<true,true,false>,
- _collision_circle_rectangle<true,true,false>,
- _collision_circle_capsule<true,true,false>,
- _collision_circle_convex_polygon<true,true,false>},
- {0,
- 0,
- _collision_rectangle_rectangle<true,true,false>,
- _collision_rectangle_capsule<true,true,false>,
- _collision_rectangle_convex_polygon<true,true,false>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<true,true,false>,
- _collision_capsule_convex_polygon<true,true,false>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<true,true,false>}
+ static const CollisionFunc collision_table_castA_castB[5][5] = {
+ { _collision_segment_segment<true, true, false>,
+ _collision_segment_circle<true, true, false>,
+ _collision_segment_rectangle<true, true, false>,
+ _collision_segment_capsule<true, true, false>,
+ _collision_segment_convex_polygon<true, true, false> },
+ { 0,
+ _collision_circle_circle<true, true, false>,
+ _collision_circle_rectangle<true, true, false>,
+ _collision_circle_capsule<true, true, false>,
+ _collision_circle_convex_polygon<true, true, false> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<true, true, false>,
+ _collision_rectangle_capsule<true, true, false>,
+ _collision_rectangle_convex_polygon<true, true, false> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<true, true, false>,
+ _collision_capsule_convex_polygon<true, true, false> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<true, true, false> }
};
- static const CollisionFunc collision_table_margin[5][5]={
- {_collision_segment_segment<false,false,true>,
- _collision_segment_circle<false,false,true>,
- _collision_segment_rectangle<false,false,true>,
- _collision_segment_capsule<false,false,true>,
- _collision_segment_convex_polygon<false,false,true>},
- {0,
- _collision_circle_circle<false,false,true>,
- _collision_circle_rectangle<false,false,true>,
- _collision_circle_capsule<false,false,true>,
- _collision_circle_convex_polygon<false,false,true>},
- {0,
- 0,
- _collision_rectangle_rectangle<false,false,true>,
- _collision_rectangle_capsule<false,false,true>,
- _collision_rectangle_convex_polygon<false,false,true>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<false,false,true>,
- _collision_capsule_convex_polygon<false,false,true>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<false,false,true>}
+ static const CollisionFunc collision_table_margin[5][5] = {
+ { _collision_segment_segment<false, false, true>,
+ _collision_segment_circle<false, false, true>,
+ _collision_segment_rectangle<false, false, true>,
+ _collision_segment_capsule<false, false, true>,
+ _collision_segment_convex_polygon<false, false, true> },
+ { 0,
+ _collision_circle_circle<false, false, true>,
+ _collision_circle_rectangle<false, false, true>,
+ _collision_circle_capsule<false, false, true>,
+ _collision_circle_convex_polygon<false, false, true> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<false, false, true>,
+ _collision_rectangle_capsule<false, false, true>,
+ _collision_rectangle_convex_polygon<false, false, true> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<false, false, true>,
+ _collision_capsule_convex_polygon<false, false, true> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<false, false, true> }
};
- static const CollisionFunc collision_table_castA_margin[5][5]={
- {_collision_segment_segment<true,false,true>,
- _collision_segment_circle<true,false,true>,
- _collision_segment_rectangle<true,false,true>,
- _collision_segment_capsule<true,false,true>,
- _collision_segment_convex_polygon<true,false,true>},
- {0,
- _collision_circle_circle<true,false,true>,
- _collision_circle_rectangle<true,false,true>,
- _collision_circle_capsule<true,false,true>,
- _collision_circle_convex_polygon<true,false,true>},
- {0,
- 0,
- _collision_rectangle_rectangle<true,false,true>,
- _collision_rectangle_capsule<true,false,true>,
- _collision_rectangle_convex_polygon<true,false,true>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<true,false,true>,
- _collision_capsule_convex_polygon<true,false,true>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<true,false,true>}
+ static const CollisionFunc collision_table_castA_margin[5][5] = {
+ { _collision_segment_segment<true, false, true>,
+ _collision_segment_circle<true, false, true>,
+ _collision_segment_rectangle<true, false, true>,
+ _collision_segment_capsule<true, false, true>,
+ _collision_segment_convex_polygon<true, false, true> },
+ { 0,
+ _collision_circle_circle<true, false, true>,
+ _collision_circle_rectangle<true, false, true>,
+ _collision_circle_capsule<true, false, true>,
+ _collision_circle_convex_polygon<true, false, true> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<true, false, true>,
+ _collision_rectangle_capsule<true, false, true>,
+ _collision_rectangle_convex_polygon<true, false, true> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<true, false, true>,
+ _collision_capsule_convex_polygon<true, false, true> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<true, false, true> }
};
- static const CollisionFunc collision_table_castB_margin[5][5]={
- {_collision_segment_segment<false,true,true>,
- _collision_segment_circle<false,true,true>,
- _collision_segment_rectangle<false,true,true>,
- _collision_segment_capsule<false,true,true>,
- _collision_segment_convex_polygon<false,true,true>},
- {0,
- _collision_circle_circle<false,true,true>,
- _collision_circle_rectangle<false,true,true>,
- _collision_circle_capsule<false,true,true>,
- _collision_circle_convex_polygon<false,true,true>},
- {0,
- 0,
- _collision_rectangle_rectangle<false,true,true>,
- _collision_rectangle_capsule<false,true,true>,
- _collision_rectangle_convex_polygon<false,true,true>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<false,true,true>,
- _collision_capsule_convex_polygon<false,true,true>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<false,true,true>}
+ static const CollisionFunc collision_table_castB_margin[5][5] = {
+ { _collision_segment_segment<false, true, true>,
+ _collision_segment_circle<false, true, true>,
+ _collision_segment_rectangle<false, true, true>,
+ _collision_segment_capsule<false, true, true>,
+ _collision_segment_convex_polygon<false, true, true> },
+ { 0,
+ _collision_circle_circle<false, true, true>,
+ _collision_circle_rectangle<false, true, true>,
+ _collision_circle_capsule<false, true, true>,
+ _collision_circle_convex_polygon<false, true, true> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<false, true, true>,
+ _collision_rectangle_capsule<false, true, true>,
+ _collision_rectangle_convex_polygon<false, true, true> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<false, true, true>,
+ _collision_capsule_convex_polygon<false, true, true> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<false, true, true> }
};
- static const CollisionFunc collision_table_castA_castB_margin[5][5]={
- {_collision_segment_segment<true,true,true>,
- _collision_segment_circle<true,true,true>,
- _collision_segment_rectangle<true,true,true>,
- _collision_segment_capsule<true,true,true>,
- _collision_segment_convex_polygon<true,true,true>},
- {0,
- _collision_circle_circle<true,true,true>,
- _collision_circle_rectangle<true,true,true>,
- _collision_circle_capsule<true,true,true>,
- _collision_circle_convex_polygon<true,true,true>},
- {0,
- 0,
- _collision_rectangle_rectangle<true,true,true>,
- _collision_rectangle_capsule<true,true,true>,
- _collision_rectangle_convex_polygon<true,true,true>},
- {0,
- 0,
- 0,
- _collision_capsule_capsule<true,true,true>,
- _collision_capsule_convex_polygon<true,true,true>},
- {0,
- 0,
- 0,
- 0,
- _collision_convex_polygon_convex_polygon<true,true,true>}
+ static const CollisionFunc collision_table_castA_castB_margin[5][5] = {
+ { _collision_segment_segment<true, true, true>,
+ _collision_segment_circle<true, true, true>,
+ _collision_segment_rectangle<true, true, true>,
+ _collision_segment_capsule<true, true, true>,
+ _collision_segment_convex_polygon<true, true, true> },
+ { 0,
+ _collision_circle_circle<true, true, true>,
+ _collision_circle_rectangle<true, true, true>,
+ _collision_circle_capsule<true, true, true>,
+ _collision_circle_convex_polygon<true, true, true> },
+ { 0,
+ 0,
+ _collision_rectangle_rectangle<true, true, true>,
+ _collision_rectangle_capsule<true, true, true>,
+ _collision_rectangle_convex_polygon<true, true, true> },
+ { 0,
+ 0,
+ 0,
+ _collision_capsule_capsule<true, true, true>,
+ _collision_capsule_convex_polygon<true, true, true> },
+ { 0,
+ 0,
+ 0,
+ 0,
+ _collision_convex_polygon_convex_polygon<true, true, true> }
};
-
_CollectorCallback2D callback;
- callback.callback=p_result_callback;
- callback.swap=p_swap;
- callback.userdata=p_userdata;
- callback.collided=false;
- callback.sep_axis=sep_axis;
-
- const Shape2DSW *A=p_shape_A;
- const Shape2DSW *B=p_shape_B;
- const Transform2D *transform_A=&p_transform_A;
- const Transform2D *transform_B=&p_transform_B;
- const Vector2 *motion_A=&p_motion_A;
- const Vector2 *motion_B=&p_motion_B;
- real_t margin_A=p_margin_A,margin_B=p_margin_B;
+ callback.callback = p_result_callback;
+ callback.swap = p_swap;
+ callback.userdata = p_userdata;
+ callback.collided = false;
+ callback.sep_axis = sep_axis;
+
+ const Shape2DSW *A = p_shape_A;
+ const Shape2DSW *B = p_shape_B;
+ const Transform2D *transform_A = &p_transform_A;
+ const Transform2D *transform_B = &p_transform_B;
+ const Vector2 *motion_A = &p_motion_A;
+ const Vector2 *motion_B = &p_motion_B;
+ real_t margin_A = p_margin_A, margin_B = p_margin_B;
if (type_A > type_B) {
- SWAP(A,B);
- SWAP(transform_A,transform_B);
- SWAP(type_A,type_B);
- SWAP(motion_A,motion_B);
- SWAP(margin_A,margin_B);
+ SWAP(A, B);
+ SWAP(transform_A, transform_B);
+ SWAP(type_A, type_B);
+ SWAP(motion_A, motion_B);
+ SWAP(margin_A, margin_B);
callback.swap = !callback.swap;
}
-
CollisionFunc collision_func;
if (p_margin_A || p_margin_B) {
- if (*motion_A==Vector2() && *motion_B==Vector2()) {
- collision_func = collision_table_margin[type_A-2][type_B-2];
- } else if (*motion_A!=Vector2() && *motion_B==Vector2()) {
- collision_func = collision_table_castA_margin[type_A-2][type_B-2];
- } else if (*motion_A==Vector2() && *motion_B!=Vector2()) {
- collision_func = collision_table_castB_margin[type_A-2][type_B-2];
+ if (*motion_A == Vector2() && *motion_B == Vector2()) {
+ collision_func = collision_table_margin[type_A - 2][type_B - 2];
+ } else if (*motion_A != Vector2() && *motion_B == Vector2()) {
+ collision_func = collision_table_castA_margin[type_A - 2][type_B - 2];
+ } else if (*motion_A == Vector2() && *motion_B != Vector2()) {
+ collision_func = collision_table_castB_margin[type_A - 2][type_B - 2];
} else {
- collision_func = collision_table_castA_castB_margin[type_A-2][type_B-2];
+ collision_func = collision_table_castA_castB_margin[type_A - 2][type_B - 2];
}
} else {
- if (*motion_A==Vector2() && *motion_B==Vector2()) {
- collision_func = collision_table[type_A-2][type_B-2];
- } else if (*motion_A!=Vector2() && *motion_B==Vector2()) {
- collision_func = collision_table_castA[type_A-2][type_B-2];
- } else if (*motion_A==Vector2() && *motion_B!=Vector2()) {
- collision_func = collision_table_castB[type_A-2][type_B-2];
+ if (*motion_A == Vector2() && *motion_B == Vector2()) {
+ collision_func = collision_table[type_A - 2][type_B - 2];
+ } else if (*motion_A != Vector2() && *motion_B == Vector2()) {
+ collision_func = collision_table_castA[type_A - 2][type_B - 2];
+ } else if (*motion_A == Vector2() && *motion_B != Vector2()) {
+ collision_func = collision_table_castB[type_A - 2][type_B - 2];
} else {
- collision_func = collision_table_castA_castB[type_A-2][type_B-2];
+ collision_func = collision_table_castA_castB[type_A - 2][type_B - 2];
}
-
}
+ ERR_FAIL_COND_V(!collision_func, false);
-
- ERR_FAIL_COND_V(!collision_func,false);
-
- collision_func(A,*transform_A,B,*transform_B,&callback,*motion_A,*motion_B,margin_A,margin_B);
+ collision_func(A, *transform_A, B, *transform_B, &callback, *motion_A, *motion_B, margin_A, margin_B);
return callback.collided;
-
-
}
diff --git a/servers/physics_2d/collision_solver_2d_sat.h b/servers/physics_2d/collision_solver_2d_sat.h
index 6b698a09f2..a13c3dd14d 100644
--- a/servers/physics_2d/collision_solver_2d_sat.h
+++ b/servers/physics_2d/collision_solver_2d_sat.h
@@ -31,7 +31,6 @@
#include "collision_solver_2d_sw.h"
-
-bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D& p_transform_A, const Vector2& p_motion_A,const Shape2DSW *p_shape_B, const Transform2D& p_transform_B,const Vector2& p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap=false,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0);
+bool sat_2d_calculate_penetration(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CollisionSolver2DSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap = false, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0);
#endif // COLLISION_SOLVER_2D_SAT_H
diff --git a/servers/physics_2d/collision_solver_2d_sw.cpp b/servers/physics_2d/collision_solver_2d_sw.cpp
index 3fdecdf413..6218af72a1 100644
--- a/servers/physics_2d/collision_solver_2d_sw.cpp
+++ b/servers/physics_2d/collision_solver_2d_sw.cpp
@@ -29,89 +29,78 @@
#include "collision_solver_2d_sw.h"
#include "collision_solver_2d_sat.h"
-
#define collision_solver sat_2d_calculate_penetration
//#define collision_solver gjk_epa_calculate_penetration
+bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result) {
-bool CollisionSolver2DSW::solve_static_line(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result) {
-
-
- const LineShape2DSW *line = static_cast<const LineShape2DSW*>(p_shape_A);
- if (p_shape_B->get_type()==Physics2DServer::SHAPE_LINE)
+ const LineShape2DSW *line = static_cast<const LineShape2DSW *>(p_shape_A);
+ if (p_shape_B->get_type() == Physics2DServer::SHAPE_LINE)
return false;
-
Vector2 n = p_transform_A.basis_xform(line->get_normal()).normalized();
- Vector2 p = p_transform_A.xform(line->get_normal()*line->get_d());
+ Vector2 p = p_transform_A.xform(line->get_normal() * line->get_d());
real_t d = n.dot(p);
Vector2 supports[2];
int support_count;
- p_shape_B->get_supports(p_transform_A.affine_inverse().basis_xform(-n).normalized(),supports,support_count);
-
- bool found=false;
+ p_shape_B->get_supports(p_transform_A.affine_inverse().basis_xform(-n).normalized(), supports, support_count);
+ bool found = false;
- for(int i=0;i<support_count;i++) {
+ for (int i = 0; i < support_count; i++) {
- supports[i] = p_transform_B.xform( supports[i] );
+ supports[i] = p_transform_B.xform(supports[i]);
real_t pd = n.dot(supports[i]);
- if (pd>=d)
+ if (pd >= d)
continue;
- found=true;
+ found = true;
- Vector2 support_A = supports[i] - n*(pd-d);
+ Vector2 support_A = supports[i] - n * (pd - d);
if (p_result_callback) {
if (p_swap_result)
- p_result_callback(supports[i],support_A,p_userdata);
+ p_result_callback(supports[i], support_A, p_userdata);
else
- p_result_callback(support_A,supports[i],p_userdata);
+ p_result_callback(support_A, supports[i], p_userdata);
}
-
}
-
return found;
}
-bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis) {
-
+bool CollisionSolver2DSW::solve_raycast(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis) {
-
- const RayShape2DSW *ray = static_cast<const RayShape2DSW*>(p_shape_A);
- if (p_shape_B->get_type()==Physics2DServer::SHAPE_RAY)
+ const RayShape2DSW *ray = static_cast<const RayShape2DSW *>(p_shape_A);
+ if (p_shape_B->get_type() == Physics2DServer::SHAPE_RAY)
return false;
Vector2 from = p_transform_A.get_origin();
- Vector2 to = from+p_transform_A[1]*ray->get_length();
- Vector2 support_A=to;
+ Vector2 to = from + p_transform_A[1] * ray->get_length();
+ Vector2 support_A = to;
Transform2D invb = p_transform_B.affine_inverse();
from = invb.xform(from);
to = invb.xform(to);
- Vector2 p,n;
- if (!p_shape_B->intersect_segment(from,to,p,n)) {
+ Vector2 p, n;
+ if (!p_shape_B->intersect_segment(from, to, p, n)) {
if (sep_axis)
- *sep_axis=p_transform_A[1].normalized();
+ *sep_axis = p_transform_A[1].normalized();
return false;
}
-
- Vector2 support_B=p_transform_B.xform(p);
+ Vector2 support_B = p_transform_B.xform(p);
if (p_result_callback) {
if (p_swap_result)
- p_result_callback(support_B,support_A,p_userdata);
+ p_result_callback(support_B, support_A, p_userdata);
else
- p_result_callback(support_A,support_B,p_userdata);
+ p_result_callback(support_A, support_B, p_userdata);
}
return true;
-
}
/*
@@ -159,101 +148,90 @@ struct _ConcaveCollisionInfo2D {
int aabb_tests;
int collisions;
Vector2 *sep_axis;
-
};
void CollisionSolver2DSW::concave_callback(void *p_userdata, Shape2DSW *p_convex) {
-
-
- _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D*)(p_userdata);
+ _ConcaveCollisionInfo2D &cinfo = *(_ConcaveCollisionInfo2D *)(p_userdata);
cinfo.aabb_tests++;
if (!cinfo.result_callback && cinfo.collided)
return; //already collided and no contacts requested, don't test anymore
- bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex,*cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result,cinfo.sep_axis,cinfo.margin_A,cinfo.margin_B );
+ bool collided = collision_solver(cinfo.shape_A, *cinfo.transform_A, cinfo.motion_A, p_convex, *cinfo.transform_B, cinfo.motion_B, cinfo.result_callback, cinfo.userdata, cinfo.swap_result, cinfo.sep_axis, cinfo.margin_A, cinfo.margin_B);
if (!collided)
return;
-
- cinfo.collided=true;
+ cinfo.collided = true;
cinfo.collisions++;
-
}
-bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) {
+bool CollisionSolver2DSW::solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) {
-
- const ConcaveShape2DSW *concave_B=static_cast<const ConcaveShape2DSW*>(p_shape_B);
+ const ConcaveShape2DSW *concave_B = static_cast<const ConcaveShape2DSW *>(p_shape_B);
_ConcaveCollisionInfo2D cinfo;
- cinfo.transform_A=&p_transform_A;
- cinfo.shape_A=p_shape_A;
- cinfo.transform_B=&p_transform_B;
- cinfo.motion_A=p_motion_A;
- cinfo.result_callback=p_result_callback;
- cinfo.userdata=p_userdata;
- cinfo.swap_result=p_swap_result;
- cinfo.collided=false;
- cinfo.collisions=0;
- cinfo.sep_axis=sep_axis;
- cinfo.margin_A=p_margin_A;
- cinfo.margin_B=p_margin_B;
-
- cinfo.aabb_tests=0;
+ cinfo.transform_A = &p_transform_A;
+ cinfo.shape_A = p_shape_A;
+ cinfo.transform_B = &p_transform_B;
+ cinfo.motion_A = p_motion_A;
+ cinfo.result_callback = p_result_callback;
+ cinfo.userdata = p_userdata;
+ cinfo.swap_result = p_swap_result;
+ cinfo.collided = false;
+ cinfo.collisions = 0;
+ cinfo.sep_axis = sep_axis;
+ cinfo.margin_A = p_margin_A;
+ cinfo.margin_B = p_margin_B;
+
+ cinfo.aabb_tests = 0;
Transform2D rel_transform = p_transform_A;
- rel_transform.elements[2]-=p_transform_B.get_origin();
+ rel_transform.elements[2] -= p_transform_B.get_origin();
//quickly compute a local Rect2
Rect2 local_aabb;
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
- Vector2 axis( p_transform_B.elements[i] );
- real_t axis_scale = 1.0/axis.length();
- axis*=axis_scale;
+ Vector2 axis(p_transform_B.elements[i]);
+ real_t axis_scale = 1.0 / axis.length();
+ axis *= axis_scale;
- real_t smin,smax;
- p_shape_A->project_rangev(axis,rel_transform,smin,smax);
- smin*=axis_scale;
- smax*=axis_scale;
+ real_t smin, smax;
+ p_shape_A->project_rangev(axis, rel_transform, smin, smax);
+ smin *= axis_scale;
+ smax *= axis_scale;
- local_aabb.pos[i]=smin;
- local_aabb.size[i]=smax-smin;
+ local_aabb.pos[i] = smin;
+ local_aabb.size[i] = smax - smin;
}
- concave_B->cull(local_aabb,concave_callback,&cinfo);
-
+ concave_B->cull(local_aabb, concave_callback, &cinfo);
//print_line("Rect2 TESTS: "+itos(cinfo.aabb_tests));
return cinfo.collided;
}
+bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis, real_t p_margin_A, real_t p_margin_B) {
-bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,Vector2 *sep_axis,real_t p_margin_A,real_t p_margin_B) {
-
-
-
-
- Physics2DServer::ShapeType type_A=p_shape_A->get_type();
- Physics2DServer::ShapeType type_B=p_shape_B->get_type();
- bool concave_A=p_shape_A->is_concave();
- bool concave_B=p_shape_B->is_concave();
- real_t margin_A=p_margin_A,margin_B=p_margin_B;
+ Physics2DServer::ShapeType type_A = p_shape_A->get_type();
+ Physics2DServer::ShapeType type_B = p_shape_B->get_type();
+ bool concave_A = p_shape_A->is_concave();
+ bool concave_B = p_shape_B->is_concave();
+ real_t margin_A = p_margin_A, margin_B = p_margin_B;
bool swap = false;
- if (type_A>type_B) {
- SWAP(type_A,type_B);
- SWAP(concave_A,concave_B);
- SWAP(margin_A,margin_B);
- swap=true;
+ if (type_A > type_B) {
+ SWAP(type_A, type_B);
+ SWAP(concave_A, concave_B);
+ SWAP(margin_A, margin_B);
+ swap = true;
}
- if (type_A==Physics2DServer::SHAPE_LINE) {
+ if (type_A == Physics2DServer::SHAPE_LINE) {
- if (type_B==Physics2DServer::SHAPE_LINE || type_B==Physics2DServer::SHAPE_RAY) {
+ if (type_B == Physics2DServer::SHAPE_LINE || type_B == Physics2DServer::SHAPE_RAY) {
return false;
}
/*
@@ -262,12 +240,12 @@ bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_
*/
if (swap) {
- return solve_static_line(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true);
+ return solve_static_line(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true);
} else {
- return solve_static_line(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false);
+ return solve_static_line(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false);
}
- /*} else if (type_A==Physics2DServer::SHAPE_RAY) {
+ /*} else if (type_A==Physics2DServer::SHAPE_RAY) {
if (type_B==Physics2DServer::SHAPE_RAY)
return false;
@@ -278,41 +256,33 @@ bool CollisionSolver2DSW::solve(const Shape2DSW *p_shape_A,const Transform2D& p_
return solve_ray(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_inverse_B,p_result_callback,p_userdata,false);
}
*/
- } else if (type_A==Physics2DServer::SHAPE_RAY) {
+ } else if (type_A == Physics2DServer::SHAPE_RAY) {
- if (type_B==Physics2DServer::SHAPE_RAY) {
+ if (type_B == Physics2DServer::SHAPE_RAY) {
return false; //no ray-ray
}
-
if (swap) {
- return solve_raycast(p_shape_B,p_transform_B,p_shape_A,p_transform_A,p_result_callback,p_userdata,true,sep_axis);
+ return solve_raycast(p_shape_B, p_transform_B, p_shape_A, p_transform_A, p_result_callback, p_userdata, true, sep_axis);
} else {
- return solve_raycast(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_result_callback,p_userdata,false,sep_axis);
+ return solve_raycast(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_result_callback, p_userdata, false, sep_axis);
}
-
} else if (concave_B) {
-
if (concave_A)
return false;
if (!swap)
- return solve_concave(p_shape_A,p_transform_A,p_motion_A,p_shape_B,p_transform_B,p_motion_B,p_result_callback,p_userdata,false,sep_axis,margin_A,margin_B);
+ return solve_concave(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B);
else
- return solve_concave(p_shape_B,p_transform_B,p_motion_B,p_shape_A,p_transform_A,p_motion_A,p_result_callback,p_userdata,true,sep_axis,margin_A,margin_B);
-
-
+ return solve_concave(p_shape_B, p_transform_B, p_motion_B, p_shape_A, p_transform_A, p_motion_A, p_result_callback, p_userdata, true, sep_axis, margin_A, margin_B);
} else {
-
- return collision_solver(p_shape_A, p_transform_A,p_motion_A, p_shape_B, p_transform_B, p_motion_B,p_result_callback,p_userdata,false,sep_axis,margin_A,margin_B);
+ return collision_solver(p_shape_A, p_transform_A, p_motion_A, p_shape_B, p_transform_B, p_motion_B, p_result_callback, p_userdata, false, sep_axis, margin_A, margin_B);
}
-
return false;
}
-
diff --git a/servers/physics_2d/collision_solver_2d_sw.h b/servers/physics_2d/collision_solver_2d_sw.h
index 2a5fc9fe1d..886cb90ace 100644
--- a/servers/physics_2d/collision_solver_2d_sw.h
+++ b/servers/physics_2d/collision_solver_2d_sw.h
@@ -33,20 +33,16 @@
class CollisionSolver2DSW {
public:
- typedef void (*CallbackResult)(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata);
+ typedef void (*CallbackResult)(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata);
+
private:
- static bool solve_static_line(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result);
+ static bool solve_static_line(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result);
static void concave_callback(void *p_userdata, Shape2DSW *p_convex);
- static bool solve_concave(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0);
- static bool solve_raycast(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,CallbackResult p_result_callback,void *p_userdata,bool p_swap_result,Vector2 *sep_axis=NULL);
-
-
+ static bool solve_concave(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0);
+ static bool solve_raycast(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, CallbackResult p_result_callback, void *p_userdata, bool p_swap_result, Vector2 *sep_axis = NULL);
public:
-
- static bool solve(const Shape2DSW *p_shape_A,const Transform2D& p_transform_A,const Vector2& p_motion_A,const Shape2DSW *p_shape_B,const Transform2D& p_transform_B,const Vector2& p_motion_B,CallbackResult p_result_callback,void *p_userdata,Vector2 *sep_axis=NULL,real_t p_margin_A=0,real_t p_margin_B=0);
-
-
+ static bool solve(const Shape2DSW *p_shape_A, const Transform2D &p_transform_A, const Vector2 &p_motion_A, const Shape2DSW *p_shape_B, const Transform2D &p_transform_B, const Vector2 &p_motion_B, CallbackResult p_result_callback, void *p_userdata, Vector2 *sep_axis = NULL, real_t p_margin_A = 0, real_t p_margin_B = 0);
};
#endif // COLLISION_SOLVER_2D_SW_H
diff --git a/servers/physics_2d/constraint_2d_sw.h b/servers/physics_2d/constraint_2d_sw.h
index cce668405c..659b5b3219 100644
--- a/servers/physics_2d/constraint_2d_sw.h
+++ b/servers/physics_2d/constraint_2d_sw.h
@@ -39,32 +39,33 @@ class Constraint2DSW : public RID_Data {
Constraint2DSW *island_next;
Constraint2DSW *island_list_next;
-
RID self;
protected:
- Constraint2DSW(Body2DSW **p_body_ptr=NULL,int p_body_count=0) { _body_ptr=p_body_ptr; _body_count=p_body_count; island_step=0; }
-public:
+ Constraint2DSW(Body2DSW **p_body_ptr = NULL, int p_body_count = 0) {
+ _body_ptr = p_body_ptr;
+ _body_count = p_body_count;
+ island_step = 0;
+ }
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+public:
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
_FORCE_INLINE_ uint64_t get_island_step() const { return island_step; }
- _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step=p_step; }
+ _FORCE_INLINE_ void set_island_step(uint64_t p_step) { island_step = p_step; }
+ _FORCE_INLINE_ Constraint2DSW *get_island_next() const { return island_next; }
+ _FORCE_INLINE_ void set_island_next(Constraint2DSW *p_next) { island_next = p_next; }
- _FORCE_INLINE_ Constraint2DSW* get_island_next() const { return island_next; }
- _FORCE_INLINE_ void set_island_next(Constraint2DSW* p_next) { island_next=p_next; }
-
- _FORCE_INLINE_ Constraint2DSW* get_island_list_next() const { return island_list_next; }
- _FORCE_INLINE_ void set_island_list_next(Constraint2DSW* p_next) { island_list_next=p_next; }
+ _FORCE_INLINE_ Constraint2DSW *get_island_list_next() const { return island_list_next; }
+ _FORCE_INLINE_ void set_island_list_next(Constraint2DSW *p_next) { island_list_next = p_next; }
_FORCE_INLINE_ Body2DSW **get_body_ptr() const { return _body_ptr; }
_FORCE_INLINE_ int get_body_count() const { return _body_count; }
-
- virtual bool setup(real_t p_step)=0;
- virtual void solve(real_t p_step)=0;
+ virtual bool setup(real_t p_step) = 0;
+ virtual void solve(real_t p_step) = 0;
virtual ~Constraint2DSW() {}
};
diff --git a/servers/physics_2d/joints_2d_sw.cpp b/servers/physics_2d/joints_2d_sw.cpp
index 76adf06429..0277586495 100644
--- a/servers/physics_2d/joints_2d_sw.cpp
+++ b/servers/physics_2d/joints_2d_sw.cpp
@@ -52,40 +52,37 @@
* SOFTWARE.
*/
-static inline real_t k_scalar(Body2DSW *a,Body2DSW *b,const Vector2& rA, const Vector2& rB, const Vector2& n) {
-
-
- real_t value=0;
+static inline real_t k_scalar(Body2DSW *a, Body2DSW *b, const Vector2 &rA, const Vector2 &rB, const Vector2 &n) {
+ real_t value = 0;
{
- value+=a->get_inv_mass();
+ value += a->get_inv_mass();
real_t rcn = rA.cross(n);
- value+=a->get_inv_inertia() * rcn * rcn;
+ value += a->get_inv_inertia() * rcn * rcn;
}
if (b) {
- value+=b->get_inv_mass();
+ value += b->get_inv_mass();
real_t rcn = rB.cross(n);
- value+=b->get_inv_inertia() * rcn * rcn;
+ value += b->get_inv_inertia() * rcn * rcn;
}
return value;
-
}
static inline Vector2
-relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB){
- Vector2 sum = a->get_linear_velocity() -rA.tangent() * a->get_angular_velocity();
+relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB) {
+ Vector2 sum = a->get_linear_velocity() - rA.tangent() * a->get_angular_velocity();
if (b)
- return (b->get_linear_velocity() -rB.tangent() * b->get_angular_velocity()) - sum;
+ return (b->get_linear_velocity() - rB.tangent() * b->get_angular_velocity()) - sum;
else
return -sum;
}
static inline real_t
-normal_relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB, Vector2 n){
+normal_relative_velocity(Body2DSW *a, Body2DSW *b, Vector2 rA, Vector2 rB, Vector2 n) {
return relative_velocity(a, b, rA, rB).dot(n);
}
@@ -188,13 +185,12 @@ PinJoint2DSW::~PinJoint2DSW() {
#else
-
bool PinJoint2DSW::setup(real_t p_step) {
Space2DSW *space = A->get_space();
- ERR_FAIL_COND_V(!space,false;)
+ ERR_FAIL_COND_V(!space, false;)
rA = A->get_transform().basis_xform(anchor_A);
- rB = B?B->get_transform().basis_xform(anchor_B):anchor_B;
+ rB = B ? B->get_transform().basis_xform(anchor_B) : anchor_B;
#if 0
Vector2 gA = rA+A->get_transform().get_origin();
Vector2 gB = B?rB+B->get_transform().get_origin():rB;
@@ -212,29 +208,34 @@ bool PinJoint2DSW::setup(real_t p_step) {
// = [1/m1+1/m2 0 ] + invI1 * [rA.y*rA.y -rA.x*rA.y] + invI2 * [rA.y*rA.y -rA.x*rA.y]
// [ 0 1/m1+1/m2] [-rA.x*rA.y rA.x*rA.x] [-rA.x*rA.y rA.x*rA.x]
- real_t B_inv_mass = B?B->get_inv_mass():0.0;
-
+ real_t B_inv_mass = B ? B->get_inv_mass() : 0.0;
Transform2D K1;
- K1[0].x = A->get_inv_mass() + B_inv_mass; K1[1].x = 0.0f;
- K1[0].y = 0.0f; K1[1].y = A->get_inv_mass() + B_inv_mass;
+ K1[0].x = A->get_inv_mass() + B_inv_mass;
+ K1[1].x = 0.0f;
+ K1[0].y = 0.0f;
+ K1[1].y = A->get_inv_mass() + B_inv_mass;
Transform2D K2;
- K2[0].x = A->get_inv_inertia() * rA.y * rA.y; K2[1].x = -A->get_inv_inertia() * rA.x * rA.y;
- K2[0].y = -A->get_inv_inertia() * rA.x * rA.y; K2[1].y = A->get_inv_inertia() * rA.x * rA.x;
+ K2[0].x = A->get_inv_inertia() * rA.y * rA.y;
+ K2[1].x = -A->get_inv_inertia() * rA.x * rA.y;
+ K2[0].y = -A->get_inv_inertia() * rA.x * rA.y;
+ K2[1].y = A->get_inv_inertia() * rA.x * rA.x;
Transform2D K;
- K[0]= K1[0] + K2[0];
- K[1]= K1[1] + K2[1];
+ K[0] = K1[0] + K2[0];
+ K[1] = K1[1] + K2[1];
if (B) {
Transform2D K3;
- K3[0].x = B->get_inv_inertia() * rB.y * rB.y; K3[1].x = -B->get_inv_inertia() * rB.x * rB.y;
- K3[0].y = -B->get_inv_inertia() * rB.x * rB.y; K3[1].y = B->get_inv_inertia() * rB.x * rB.x;
+ K3[0].x = B->get_inv_inertia() * rB.y * rB.y;
+ K3[1].x = -B->get_inv_inertia() * rB.x * rB.y;
+ K3[0].y = -B->get_inv_inertia() * rB.x * rB.y;
+ K3[1].y = B->get_inv_inertia() * rB.x * rB.x;
- K[0]+=K3[0];
- K[1]+=K3[1];
+ K[0] += K3[0];
+ K[1] += K3[1];
}
K[0].x += softness;
@@ -242,23 +243,22 @@ bool PinJoint2DSW::setup(real_t p_step) {
M = K.affine_inverse();
- Vector2 gA = rA+A->get_transform().get_origin();
- Vector2 gB = B?rB+B->get_transform().get_origin():rB;
+ Vector2 gA = rA + A->get_transform().get_origin();
+ Vector2 gB = B ? rB + B->get_transform().get_origin() : rB;
Vector2 delta = gB - gA;
- bias = delta*-(get_bias()==0?space->get_constraint_bias():get_bias())*(1.0/p_step);
+ bias = delta * -(get_bias() == 0 ? space->get_constraint_bias() : get_bias()) * (1.0 / p_step);
// apply accumulated impulse
- A->apply_impulse(rA,-P);
+ A->apply_impulse(rA, -P);
if (B)
- B->apply_impulse(rB,P);
+ B->apply_impulse(rB, P);
return true;
}
-void PinJoint2DSW::solve(real_t p_step){
-
+void PinJoint2DSW::solve(real_t p_step) {
// compute relative velocity
Vector2 vA = A->get_linear_velocity() - rA.cross(A->get_angular_velocity());
@@ -269,114 +269,110 @@ void PinJoint2DSW::solve(real_t p_step){
else
rel_vel = -vA;
- Vector2 impulse = M.basis_xform(bias - rel_vel - Vector2(softness,softness) * P);
+ Vector2 impulse = M.basis_xform(bias - rel_vel - Vector2(softness, softness) * P);
- A->apply_impulse(rA,-impulse);
+ A->apply_impulse(rA, -impulse);
if (B)
- B->apply_impulse(rB,impulse);
-
+ B->apply_impulse(rB, impulse);
P += impulse;
}
void PinJoint2DSW::set_param(Physics2DServer::PinJointParam p_param, real_t p_value) {
- if(p_param == Physics2DServer::PIN_JOINT_SOFTNESS)
+ if (p_param == Physics2DServer::PIN_JOINT_SOFTNESS)
softness = p_value;
}
real_t PinJoint2DSW::get_param(Physics2DServer::PinJointParam p_param) const {
- if(p_param == Physics2DServer::PIN_JOINT_SOFTNESS)
+ if (p_param == Physics2DServer::PIN_JOINT_SOFTNESS)
return softness;
ERR_FAIL_V(0);
}
-PinJoint2DSW::PinJoint2DSW(const Vector2& p_pos,Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,p_body_b?2:1) {
+PinJoint2DSW::PinJoint2DSW(const Vector2 &p_pos, Body2DSW *p_body_a, Body2DSW *p_body_b)
+ : Joint2DSW(_arr, p_body_b ? 2 : 1) {
- A=p_body_a;
- B=p_body_b;
+ A = p_body_a;
+ B = p_body_b;
anchor_A = p_body_a->get_inv_transform().xform(p_pos);
- anchor_B = p_body_b?p_body_b->get_inv_transform().xform(p_pos):p_pos;
+ anchor_B = p_body_b ? p_body_b->get_inv_transform().xform(p_pos) : p_pos;
- softness=0;
+ softness = 0;
- p_body_a->add_constraint(this,0);
+ p_body_a->add_constraint(this, 0);
if (p_body_b)
- p_body_b->add_constraint(this,1);
-
+ p_body_b->add_constraint(this, 1);
}
-
-
PinJoint2DSW::~PinJoint2DSW() {
if (A)
A->remove_constraint(this);
if (B)
B->remove_constraint(this);
-
}
-
-
#endif
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
-
static inline void
-k_tensor(Body2DSW *a, Body2DSW *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2)
-{
+k_tensor(Body2DSW *a, Body2DSW *b, Vector2 r1, Vector2 r2, Vector2 *k1, Vector2 *k2) {
// calculate mass matrix
// If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
real_t k11, k12, k21, k22;
real_t m_sum = a->get_inv_mass() + b->get_inv_mass();
// start with I*m_sum
- k11 = m_sum; k12 = 0.0f;
- k21 = 0.0f; k22 = m_sum;
+ k11 = m_sum;
+ k12 = 0.0f;
+ k21 = 0.0f;
+ k22 = m_sum;
// add the influence from r1
real_t a_i_inv = a->get_inv_inertia();
- real_t r1xsq = r1.x * r1.x * a_i_inv;
- real_t r1ysq = r1.y * r1.y * a_i_inv;
+ real_t r1xsq = r1.x * r1.x * a_i_inv;
+ real_t r1ysq = r1.y * r1.y * a_i_inv;
real_t r1nxy = -r1.x * r1.y * a_i_inv;
- k11 += r1ysq; k12 += r1nxy;
- k21 += r1nxy; k22 += r1xsq;
+ k11 += r1ysq;
+ k12 += r1nxy;
+ k21 += r1nxy;
+ k22 += r1xsq;
// add the influnce from r2
real_t b_i_inv = b->get_inv_inertia();
- real_t r2xsq = r2.x * r2.x * b_i_inv;
- real_t r2ysq = r2.y * r2.y * b_i_inv;
+ real_t r2xsq = r2.x * r2.x * b_i_inv;
+ real_t r2ysq = r2.y * r2.y * b_i_inv;
real_t r2nxy = -r2.x * r2.y * b_i_inv;
- k11 += r2ysq; k12 += r2nxy;
- k21 += r2nxy; k22 += r2xsq;
+ k11 += r2ysq;
+ k12 += r2nxy;
+ k21 += r2nxy;
+ k22 += r2xsq;
// invert
- real_t determinant = k11*k22 - k12*k21;
- ERR_FAIL_COND(determinant== 0.0);
+ real_t determinant = k11 * k22 - k12 * k21;
+ ERR_FAIL_COND(determinant == 0.0);
- real_t det_inv = 1.0f/determinant;
- *k1 = Vector2( k22*det_inv, -k12*det_inv);
- *k2 = Vector2(-k21*det_inv, k11*det_inv);
+ real_t det_inv = 1.0f / determinant;
+ *k1 = Vector2(k22 * det_inv, -k12 * det_inv);
+ *k2 = Vector2(-k21 * det_inv, k11 * det_inv);
}
static _FORCE_INLINE_ Vector2
-mult_k(const Vector2& vr, const Vector2 &k1, const Vector2 &k2)
-{
+mult_k(const Vector2 &vr, const Vector2 &k1, const Vector2 &k2) {
return Vector2(vr.dot(k1), vr.dot(k2));
}
bool GrooveJoint2DSW::setup(real_t p_step) {
-
// calculate endpoints in worldspace
Vector2 ta = A->get_transform().xform(A_groove_1);
Vector2 tb = A->get_transform().xform(A_groove_2);
- Space2DSW *space=A->get_space();
+ Space2DSW *space = A->get_space();
// calculate axis
Vector2 n = -(tb - ta).tangent().normalized();
@@ -388,16 +384,16 @@ bool GrooveJoint2DSW::setup(real_t p_step) {
// calculate tangential distance along the axis of rB
real_t td = (B->get_transform().get_origin() + rB).cross(n);
// calculate clamping factor and rB
- if(td <= ta.cross(n)){
+ if (td <= ta.cross(n)) {
clamp = 1.0f;
rA = ta - A->get_transform().get_origin();
- } else if(td >= tb.cross(n)){
+ } else if (td >= tb.cross(n)) {
clamp = -1.0f;
rA = tb - A->get_transform().get_origin();
} else {
clamp = 0.0f;
//joint->r1 = cpvsub(cpvadd(cpvmult(cpvperp(n), -td), cpvmult(n, d)), a->p);
- rA = ((-n.tangent() * -td) + n*d) - A->get_transform().get_origin();
+ rA = ((-n.tangent() * -td) + n * d) - A->get_transform().get_origin();
}
// Calculate mass tensor
@@ -410,52 +406,49 @@ bool GrooveJoint2DSW::setup(real_t p_step) {
//cpVect delta = cpvsub(cpvadd(b->p, joint->r2), cpvadd(a->p, joint->r1));
//joint->bias = cpvclamp(cpvmult(delta, -joint->constraint.biasCoef*dt_inv), joint->constraint.maxBias);
-
- Vector2 delta = (B->get_transform().get_origin() +rB) - (A->get_transform().get_origin() + rA);
+ Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA);
real_t _b = get_bias();
- _b=0.001;
- gbias=(delta*-(_b==0?space->get_constraint_bias():_b)*(1.0/p_step)).clamped(get_max_bias());
+ _b = 0.001;
+ gbias = (delta * -(_b == 0 ? space->get_constraint_bias() : _b) * (1.0 / p_step)).clamped(get_max_bias());
// apply accumulated impulse
- A->apply_impulse(rA,-jn_acc);
- B->apply_impulse(rB,jn_acc);
+ A->apply_impulse(rA, -jn_acc);
+ B->apply_impulse(rB, jn_acc);
- correct=true;
+ correct = true;
return true;
}
-void GrooveJoint2DSW::solve(real_t p_step){
-
+void GrooveJoint2DSW::solve(real_t p_step) {
// compute impulse
- Vector2 vr = relative_velocity(A, B, rA,rB);
+ Vector2 vr = relative_velocity(A, B, rA, rB);
- Vector2 j = mult_k(gbias-vr, k1, k2);
+ Vector2 j = mult_k(gbias - vr, k1, k2);
Vector2 jOld = jn_acc;
- j+=jOld;
+ j += jOld;
jn_acc = (((clamp * j.cross(xf_normal)) > 0) ? j : xf_normal.project(j)).clamped(jn_max);
j = jn_acc - jOld;
- A->apply_impulse(rA,-j);
- B->apply_impulse(rB,j);
+ A->apply_impulse(rA, -j);
+ B->apply_impulse(rB, j);
}
+GrooveJoint2DSW::GrooveJoint2DSW(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, Body2DSW *p_body_a, Body2DSW *p_body_b)
+ : Joint2DSW(_arr, 2) {
-GrooveJoint2DSW::GrooveJoint2DSW(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,2) {
-
- A=p_body_a;
- B=p_body_b;
+ A = p_body_a;
+ B = p_body_b;
A_groove_1 = A->get_inv_transform().xform(p_a_groove1);
A_groove_2 = A->get_inv_transform().xform(p_a_groove2);
- B_anchor=B->get_inv_transform().xform(p_b_anchor);
+ B_anchor = B->get_inv_transform().xform(p_b_anchor);
A_groove_normal = -(A_groove_2 - A_groove_1).normalized().tangent();
- A->add_constraint(this,0);
- B->add_constraint(this,1);
-
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
GrooveJoint2DSW::~GrooveJoint2DSW() {
@@ -464,38 +457,35 @@ GrooveJoint2DSW::~GrooveJoint2DSW() {
B->remove_constraint(this);
}
-
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
-
bool DampedSpringJoint2DSW::setup(real_t p_step) {
rA = A->get_transform().basis_xform(anchor_A);
rB = B->get_transform().basis_xform(anchor_B);
- Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA) ;
+ Vector2 delta = (B->get_transform().get_origin() + rB) - (A->get_transform().get_origin() + rA);
real_t dist = delta.length();
if (dist)
- n=delta/dist;
+ n = delta / dist;
else
- n=Vector2();
+ n = Vector2();
real_t k = k_scalar(A, B, rA, rB, n);
- n_mass = 1.0f/k;
+ n_mass = 1.0f / k;
target_vrn = 0.0f;
- v_coef = 1.0f - Math::exp(-damping*(p_step)*k);
+ v_coef = 1.0f - Math::exp(-damping * (p_step)*k);
// apply spring force
real_t f_spring = (rest_length - dist) * stiffness;
- Vector2 j = n * f_spring*(p_step);
-
- A->apply_impulse(rA,-j);
- B->apply_impulse(rB,j);
+ Vector2 j = n * f_spring * (p_step);
+ A->apply_impulse(rA, -j);
+ B->apply_impulse(rB, j);
return true;
}
@@ -507,38 +497,36 @@ void DampedSpringJoint2DSW::solve(real_t p_step) {
// compute velocity loss from drag
// not 100% certain this is derived correctly, though it makes sense
- real_t v_damp = -vrn*v_coef;
+ real_t v_damp = -vrn * v_coef;
target_vrn = vrn + v_damp;
- Vector2 j=n*v_damp*n_mass;
-
- A->apply_impulse(rA,-j);
- B->apply_impulse(rB,j);
+ Vector2 j = n * v_damp * n_mass;
+ A->apply_impulse(rA, -j);
+ B->apply_impulse(rB, j);
}
void DampedSpringJoint2DSW::set_param(Physics2DServer::DampedStringParam p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::DAMPED_STRING_REST_LENGTH: {
- rest_length=p_value;
+ rest_length = p_value;
} break;
case Physics2DServer::DAMPED_STRING_DAMPING: {
- damping=p_value;
+ damping = p_value;
} break;
case Physics2DServer::DAMPED_STRING_STIFFNESS: {
- stiffness=p_value;
+ stiffness = p_value;
} break;
}
-
}
-real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_param) const{
+real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_param) const {
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::DAMPED_STRING_REST_LENGTH: {
@@ -557,30 +545,24 @@ real_t DampedSpringJoint2DSW::get_param(Physics2DServer::DampedStringParam p_par
ERR_FAIL_V(0);
}
+DampedSpringJoint2DSW::DampedSpringJoint2DSW(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, Body2DSW *p_body_a, Body2DSW *p_body_b)
+ : Joint2DSW(_arr, 2) {
-DampedSpringJoint2DSW::DampedSpringJoint2DSW(const Vector2& p_anchor_a,const Vector2& p_anchor_b, Body2DSW* p_body_a,Body2DSW* p_body_b) : Joint2DSW(_arr,2) {
-
-
- A=p_body_a;
- B=p_body_b;
+ A = p_body_a;
+ B = p_body_b;
anchor_A = A->get_inv_transform().xform(p_anchor_a);
anchor_B = B->get_inv_transform().xform(p_anchor_b);
- rest_length=p_anchor_a.distance_to(p_anchor_b);
- stiffness=20;
- damping=1.5;
-
-
- A->add_constraint(this,0);
- B->add_constraint(this,1);
+ rest_length = p_anchor_a.distance_to(p_anchor_b);
+ stiffness = 20;
+ damping = 1.5;
+ A->add_constraint(this, 0);
+ B->add_constraint(this, 1);
}
DampedSpringJoint2DSW::~DampedSpringJoint2DSW() {
A->remove_constraint(this);
B->remove_constraint(this);
-
}
-
-
diff --git a/servers/physics_2d/joints_2d_sw.h b/servers/physics_2d/joints_2d_sw.h
index 1be15e4edc..8fe38f365a 100644
--- a/servers/physics_2d/joints_2d_sw.h
+++ b/servers/physics_2d/joints_2d_sw.h
@@ -29,30 +29,31 @@
#ifndef JOINTS_2D_SW_H
#define JOINTS_2D_SW_H
-#include "constraint_2d_sw.h"
#include "body_2d_sw.h"
-
-
+#include "constraint_2d_sw.h"
class Joint2DSW : public Constraint2DSW {
real_t max_force;
real_t bias;
real_t max_bias;
-public:
- _FORCE_INLINE_ void set_max_force(real_t p_force) { max_force=p_force; }
+public:
+ _FORCE_INLINE_ void set_max_force(real_t p_force) { max_force = p_force; }
_FORCE_INLINE_ real_t get_max_force() const { return max_force; }
- _FORCE_INLINE_ void set_bias(real_t p_bias) { bias=p_bias; }
+ _FORCE_INLINE_ void set_bias(real_t p_bias) { bias = p_bias; }
_FORCE_INLINE_ real_t get_bias() const { return bias; }
- _FORCE_INLINE_ void set_max_bias(real_t p_bias) { max_bias=p_bias; }
+ _FORCE_INLINE_ void set_max_bias(real_t p_bias) { max_bias = p_bias; }
_FORCE_INLINE_ real_t get_max_bias() const { return max_bias; }
- virtual Physics2DServer::JointType get_type() const=0;
- Joint2DSW(Body2DSW **p_body_ptr=NULL,int p_body_count=0) : Constraint2DSW(p_body_ptr,p_body_count) { bias=0; max_force=max_bias=3.40282e+38; };
-
+ virtual Physics2DServer::JointType get_type() const = 0;
+ Joint2DSW(Body2DSW **p_body_ptr = NULL, int p_body_count = 0)
+ : Constraint2DSW(p_body_ptr, p_body_count) {
+ bias = 0;
+ max_force = max_bias = 3.40282e+38;
+ };
};
#if 0
@@ -107,7 +108,7 @@ class PinJoint2DSW : public Joint2DSW {
};
Transform2D M;
- Vector2 rA,rB;
+ Vector2 rA, rB;
Vector2 anchor_A;
Vector2 anchor_B;
Vector2 bias;
@@ -115,7 +116,6 @@ class PinJoint2DSW : public Joint2DSW {
real_t softness;
public:
-
virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_PIN; }
virtual bool setup(real_t p_step);
@@ -124,11 +124,10 @@ public:
void set_param(Physics2DServer::PinJointParam p_param, real_t p_value);
real_t get_param(Physics2DServer::PinJointParam p_param) const;
- PinJoint2DSW(const Vector2& p_pos,Body2DSW* p_body_a,Body2DSW* p_body_b=NULL);
+ PinJoint2DSW(const Vector2 &p_pos, Body2DSW *p_body_a, Body2DSW *p_body_b = NULL);
~PinJoint2DSW();
};
-
#endif
class GrooveJoint2DSW : public Joint2DSW {
@@ -150,25 +149,21 @@ class GrooveJoint2DSW : public Joint2DSW {
real_t jn_max;
real_t clamp;
Vector2 xf_normal;
- Vector2 rA,rB;
- Vector2 k1,k2;
-
+ Vector2 rA, rB;
+ Vector2 k1, k2;
bool correct;
public:
-
virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_GROOVE; }
virtual bool setup(real_t p_step);
virtual void solve(real_t p_step);
-
- GrooveJoint2DSW(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, Body2DSW* p_body_a,Body2DSW* p_body_b);
+ GrooveJoint2DSW(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, Body2DSW *p_body_a, Body2DSW *p_body_b);
~GrooveJoint2DSW();
};
-
class DampedSpringJoint2DSW : public Joint2DSW {
union {
@@ -180,7 +175,6 @@ class DampedSpringJoint2DSW : public Joint2DSW {
Body2DSW *_arr[2];
};
-
Vector2 anchor_A;
Vector2 anchor_B;
@@ -188,14 +182,13 @@ class DampedSpringJoint2DSW : public Joint2DSW {
real_t damping;
real_t stiffness;
- Vector2 rA,rB;
+ Vector2 rA, rB;
Vector2 n;
real_t n_mass;
real_t target_vrn;
real_t v_coef;
public:
-
virtual Physics2DServer::JointType get_type() const { return Physics2DServer::JOINT_DAMPED_SPRING; }
virtual bool setup(real_t p_step);
@@ -204,9 +197,8 @@ public:
void set_param(Physics2DServer::DampedStringParam p_param, real_t p_value);
real_t get_param(Physics2DServer::DampedStringParam p_param) const;
- DampedSpringJoint2DSW(const Vector2& p_anchor_a,const Vector2& p_anchor_b, Body2DSW* p_body_a,Body2DSW* p_body_b);
+ DampedSpringJoint2DSW(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, Body2DSW *p_body_a, Body2DSW *p_body_b);
~DampedSpringJoint2DSW();
};
-
#endif // JOINTS_2D_SW_H
diff --git a/servers/physics_2d/physics_2d_server_sw.cpp b/servers/physics_2d/physics_2d_server_sw.cpp
index 920742ea0b..0a56683c5d 100644
--- a/servers/physics_2d/physics_2d_server_sw.cpp
+++ b/servers/physics_2d/physics_2d_server_sw.cpp
@@ -31,52 +31,51 @@
#include "broad_phase_2d_hash_grid.h"
#include "collision_solver_2d_sw.h"
#include "global_config.h"
-#include "script_language.h"
#include "os/os.h"
+#include "script_language.h"
RID Physics2DServerSW::shape_create(ShapeType p_shape) {
- Shape2DSW *shape=NULL;
- switch(p_shape) {
+ Shape2DSW *shape = NULL;
+ switch (p_shape) {
case SHAPE_LINE: {
- shape=memnew( LineShape2DSW );
+ shape = memnew(LineShape2DSW);
} break;
case SHAPE_RAY: {
- shape=memnew( RayShape2DSW );
+ shape = memnew(RayShape2DSW);
} break;
case SHAPE_SEGMENT: {
- shape=memnew( SegmentShape2DSW);
+ shape = memnew(SegmentShape2DSW);
} break;
case SHAPE_CIRCLE: {
- shape=memnew( CircleShape2DSW);
+ shape = memnew(CircleShape2DSW);
} break;
case SHAPE_RECTANGLE: {
- shape=memnew( RectangleShape2DSW);
+ shape = memnew(RectangleShape2DSW);
} break;
case SHAPE_CAPSULE: {
- shape=memnew( CapsuleShape2DSW );
+ shape = memnew(CapsuleShape2DSW);
} break;
case SHAPE_CONVEX_POLYGON: {
- shape=memnew( ConvexPolygonShape2DSW );
+ shape = memnew(ConvexPolygonShape2DSW);
} break;
case SHAPE_CONCAVE_POLYGON: {
- shape=memnew( ConcavePolygonShape2DSW );
+ shape = memnew(ConcavePolygonShape2DSW);
} break;
case SHAPE_CUSTOM: {
ERR_FAIL_V(RID());
} break;
-
}
RID id = shape_owner.make_rid(shape);
@@ -85,68 +84,55 @@ RID Physics2DServerSW::shape_create(ShapeType p_shape) {
return id;
};
-
-
-
-void Physics2DServerSW::shape_set_data(RID p_shape, const Variant& p_data) {
+void Physics2DServerSW::shape_set_data(RID p_shape, const Variant &p_data) {
Shape2DSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
shape->set_data(p_data);
-
-
};
-
void Physics2DServerSW::shape_set_custom_solver_bias(RID p_shape, real_t p_bias) {
Shape2DSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
shape->set_custom_bias(p_bias);
-
}
-
Physics2DServer::ShapeType Physics2DServerSW::shape_get_type(RID p_shape) const {
const Shape2DSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,SHAPE_CUSTOM);
+ ERR_FAIL_COND_V(!shape, SHAPE_CUSTOM);
return shape->get_type();
-
};
Variant Physics2DServerSW::shape_get_data(RID p_shape) const {
const Shape2DSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,Variant());
- ERR_FAIL_COND_V(!shape->is_configured(),Variant());
+ ERR_FAIL_COND_V(!shape, Variant());
+ ERR_FAIL_COND_V(!shape->is_configured(), Variant());
return shape->get_data();
-
};
real_t Physics2DServerSW::shape_get_custom_solver_bias(RID p_shape) const {
const Shape2DSW *shape = shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ERR_FAIL_COND_V(!shape, 0);
return shape->get_custom_bias();
-
}
+void Physics2DServerSW::_shape_col_cbk(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) {
-void Physics2DServerSW::_shape_col_cbk(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata) {
-
+ CollCbkData *cbk = (CollCbkData *)p_userdata;
- CollCbkData *cbk=(CollCbkData *)p_userdata;
-
- if (cbk->max==0)
+ if (cbk->max == 0)
return;
- if (cbk->valid_dir!=Vector2()) {
- if (p_point_A.distance_squared_to(p_point_B)>cbk->valid_depth*cbk->valid_depth) {
+ if (cbk->valid_dir != Vector2()) {
+ if (p_point_A.distance_squared_to(p_point_B) > cbk->valid_depth * cbk->valid_depth) {
return;
}
- if (cbk->valid_dir.dot((p_point_A-p_point_B).normalized())<0.7071) {
-/* print_line("A: "+p_point_A);
+ if (cbk->valid_dir.dot((p_point_A - p_point_B).normalized()) < 0.7071) {
+ /* print_line("A: "+p_point_A);
print_line("B: "+p_point_B);
print_line("discard too angled "+rtos(cbk->valid_dir.dot((p_point_A-p_point_B))));
print_line("resnorm: "+(p_point_A-p_point_B).normalized());
@@ -158,66 +144,61 @@ void Physics2DServerSW::_shape_col_cbk(const Vector2& p_point_A,const Vector2& p
if (cbk->amount == cbk->max) {
//find least deep
- real_t min_depth=1e20;
- int min_depth_idx=0;
- for(int i=0;i<cbk->amount;i++) {
-
- real_t d = cbk->ptr[i*2+0].distance_squared_to(cbk->ptr[i*2+1]);
- if (d<min_depth) {
- min_depth=d;
- min_depth_idx=i;
+ real_t min_depth = 1e20;
+ int min_depth_idx = 0;
+ for (int i = 0; i < cbk->amount; i++) {
+
+ real_t d = cbk->ptr[i * 2 + 0].distance_squared_to(cbk->ptr[i * 2 + 1]);
+ if (d < min_depth) {
+ min_depth = d;
+ min_depth_idx = i;
}
-
}
real_t d = p_point_A.distance_squared_to(p_point_B);
- if (d<min_depth)
+ if (d < min_depth)
return;
- cbk->ptr[min_depth_idx*2+0]=p_point_A;
- cbk->ptr[min_depth_idx*2+1]=p_point_B;
-
+ cbk->ptr[min_depth_idx * 2 + 0] = p_point_A;
+ cbk->ptr[min_depth_idx * 2 + 1] = p_point_B;
} else {
- cbk->ptr[cbk->amount*2+0]=p_point_A;
- cbk->ptr[cbk->amount*2+1]=p_point_B;
+ cbk->ptr[cbk->amount * 2 + 0] = p_point_A;
+ cbk->ptr[cbk->amount * 2 + 1] = p_point_B;
cbk->amount++;
}
}
-bool Physics2DServerSW::shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count) {
-
+bool Physics2DServerSW::shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) {
Shape2DSW *shape_A = shape_owner.get(p_shape_A);
- ERR_FAIL_COND_V(!shape_A,false);
+ ERR_FAIL_COND_V(!shape_A, false);
Shape2DSW *shape_B = shape_owner.get(p_shape_B);
- ERR_FAIL_COND_V(!shape_B,false);
+ ERR_FAIL_COND_V(!shape_B, false);
- if (p_result_max==0) {
+ if (p_result_max == 0) {
- return CollisionSolver2DSW::solve(shape_A,p_xform_A,p_motion_A,shape_B,p_xform_B,p_motion_B,NULL,NULL);
+ return CollisionSolver2DSW::solve(shape_A, p_xform_A, p_motion_A, shape_B, p_xform_B, p_motion_B, NULL, NULL);
}
CollCbkData cbk;
- cbk.max=p_result_max;
- cbk.amount=0;
- cbk.ptr=r_results;
+ cbk.max = p_result_max;
+ cbk.amount = 0;
+ cbk.ptr = r_results;
- bool res= CollisionSolver2DSW::solve(shape_A,p_xform_A,p_motion_A,shape_B,p_xform_B,p_motion_B,_shape_col_cbk,&cbk);
- r_result_count=cbk.amount;
+ bool res = CollisionSolver2DSW::solve(shape_A, p_xform_A, p_motion_A, shape_B, p_xform_B, p_motion_B, _shape_col_cbk, &cbk);
+ r_result_count = cbk.amount;
return res;
-
}
-
RID Physics2DServerSW::space_create() {
- Space2DSW *space = memnew( Space2DSW );
+ Space2DSW *space = memnew(Space2DSW);
RID id = space_owner.make_rid(space);
space->set_self(id);
RID area_id = area_create();
Area2DSW *area = area_owner.get(area_id);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
space->set_default_area(area);
area->set_space(space);
area->set_priority(-1);
@@ -225,7 +206,7 @@ RID Physics2DServerSW::space_create() {
return id;
};
-void Physics2DServerSW::space_set_active(RID p_space,bool p_active) {
+void Physics2DServerSW::space_set_active(RID p_space, bool p_active) {
Space2DSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
@@ -238,56 +219,51 @@ void Physics2DServerSW::space_set_active(RID p_space,bool p_active) {
bool Physics2DServerSW::space_is_active(RID p_space) const {
const Space2DSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,false);
+ ERR_FAIL_COND_V(!space, false);
return active_spaces.has(space);
-
}
-void Physics2DServerSW::space_set_param(RID p_space,SpaceParameter p_param, real_t p_value) {
+void Physics2DServerSW::space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) {
Space2DSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
- space->set_param(p_param,p_value);
-
+ space->set_param(p_param, p_value);
}
-real_t Physics2DServerSW::space_get_param(RID p_space,SpaceParameter p_param) const {
+real_t Physics2DServerSW::space_get_param(RID p_space, SpaceParameter p_param) const {
const Space2DSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,0);
+ ERR_FAIL_COND_V(!space, 0);
return space->get_param(p_param);
}
-void Physics2DServerSW::space_set_debug_contacts(RID p_space,int p_max_contacts) {
+void Physics2DServerSW::space_set_debug_contacts(RID p_space, int p_max_contacts) {
Space2DSW *space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
space->set_debug_contacts(p_max_contacts);
-
}
Vector<Vector2> Physics2DServerSW::space_get_contacts(RID p_space) const {
Space2DSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,Vector<Vector2>());
+ ERR_FAIL_COND_V(!space, Vector<Vector2>());
return space->get_debug_contacts();
-
}
int Physics2DServerSW::space_get_contact_count(RID p_space) const {
Space2DSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,0);
+ ERR_FAIL_COND_V(!space, 0);
return space->get_debug_contact_count();
-
}
-Physics2DDirectSpaceState* Physics2DServerSW::space_get_direct_state(RID p_space) {
+Physics2DDirectSpaceState *Physics2DServerSW::space_get_direct_state(RID p_space) {
Space2DSW *space = space_owner.get(p_space);
- ERR_FAIL_COND_V(!space,NULL);
+ ERR_FAIL_COND_V(!space, NULL);
if ((using_threads && !doing_sync) || space->is_locked()) {
ERR_EXPLAIN("Space state is inaccesible right now, wait for iteration or fixed process notification.");
@@ -299,7 +275,7 @@ Physics2DDirectSpaceState* Physics2DServerSW::space_get_direct_state(RID p_space
RID Physics2DServerSW::area_create() {
- Area2DSW *area = memnew( Area2DSW );
+ Area2DSW *area = memnew(Area2DSW);
RID rid = area_owner.make_rid(area);
area->set_self(rid);
return rid;
@@ -309,20 +285,19 @@ void Physics2DServerSW::area_set_space(RID p_area, RID p_space) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- Space2DSW *space=NULL;
+ Space2DSW *space = NULL;
if (p_space.is_valid()) {
space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
}
area->set_space(space);
-
};
RID Physics2DServerSW::area_get_space(RID p_area) const {
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
Space2DSW *space = area->get_space();
if (!space)
@@ -332,7 +307,6 @@ RID Physics2DServerSW::area_get_space(RID p_area) const {
void Physics2DServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) {
-
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -342,13 +316,12 @@ void Physics2DServerSW::area_set_space_override_mode(RID p_area, AreaSpaceOverri
Physics2DServer::AreaSpaceOverrideMode Physics2DServerSW::area_get_space_override_mode(RID p_area) const {
const Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,AREA_SPACE_OVERRIDE_DISABLED);
+ ERR_FAIL_COND_V(!area, AREA_SPACE_OVERRIDE_DISABLED);
return area->get_space_override_mode();
}
-
-void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform) {
+void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -356,11 +329,10 @@ void Physics2DServerSW::area_add_shape(RID p_area, RID p_shape, const Transform2
Shape2DSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
- area->add_shape(shape,p_transform);
-
+ area->add_shape(shape, p_transform);
}
-void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape) {
+void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx, RID p_shape) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -369,39 +341,37 @@ void Physics2DServerSW::area_set_shape(RID p_area, int p_shape_idx,RID p_shape)
ERR_FAIL_COND(!shape);
ERR_FAIL_COND(!shape->is_configured());
- area->set_shape(p_shape_idx,shape);
-
+ area->set_shape(p_shape_idx, shape);
}
-void Physics2DServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D& p_transform) {
+void Physics2DServerSW::area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D &p_transform) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_shape_transform(p_shape_idx,p_transform);
+ area->set_shape_transform(p_shape_idx, p_transform);
}
int Physics2DServerSW::area_get_shape_count(RID p_area) const {
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,-1);
+ ERR_FAIL_COND_V(!area, -1);
return area->get_shape_count();
-
}
RID Physics2DServerSW::area_get_shape(RID p_area, int p_shape_idx) const {
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,RID());
+ ERR_FAIL_COND_V(!area, RID());
Shape2DSW *shape = area->get_shape(p_shape_idx);
- ERR_FAIL_COND_V(!shape,RID());
+ ERR_FAIL_COND_V(!shape, RID());
return shape->get_self();
}
Transform2D Physics2DServerSW::area_get_shape_transform(RID p_area, int p_shape_idx) const {
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Transform2D());
+ ERR_FAIL_COND_V(!area, Transform2D());
return area->get_shape_transform(p_shape_idx);
}
@@ -419,65 +389,57 @@ void Physics2DServerSW::area_clear_shapes(RID p_area) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- while(area->get_shape_count())
+ while (area->get_shape_count())
area->remove_shape(0);
-
}
-void Physics2DServerSW::area_attach_object_instance_ID(RID p_area,ObjectID p_ID) {
+void Physics2DServerSW::area_attach_object_instance_ID(RID p_area, ObjectID p_ID) {
if (space_owner.owns(p_area)) {
- Space2DSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ Space2DSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_instance_id(p_ID);
-
}
ObjectID Physics2DServerSW::area_get_object_instance_ID(RID p_area) const {
if (space_owner.owns(p_area)) {
- Space2DSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ Space2DSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,0);
+ ERR_FAIL_COND_V(!area, 0);
return area->get_instance_id();
-
-
}
-
-void Physics2DServerSW::area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value) {
+void Physics2DServerSW::area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) {
if (space_owner.owns(p_area)) {
- Space2DSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ Space2DSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_param(p_param,p_value);
-
+ area->set_param(p_param, p_value);
};
-
-void Physics2DServerSW::area_set_transform(RID p_area, const Transform2D& p_transform) {
+void Physics2DServerSW::area_set_transform(RID p_area, const Transform2D &p_transform) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_transform(p_transform);
-
};
-Variant Physics2DServerSW::area_get_param(RID p_area,AreaParameter p_param) const {
+Variant Physics2DServerSW::area_get_param(RID p_area, AreaParameter p_param) const {
if (space_owner.owns(p_area)) {
- Space2DSW *space=space_owner.get(p_area);
- p_area=space->get_default_area()->get_self();
+ Space2DSW *space = space_owner.get(p_area);
+ p_area = space->get_default_area()->get_self();
}
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Variant());
+ ERR_FAIL_COND_V(!area, Variant());
return area->get_param(p_param);
};
@@ -485,29 +447,27 @@ Variant Physics2DServerSW::area_get_param(RID p_area,AreaParameter p_param) cons
Transform2D Physics2DServerSW::area_get_transform(RID p_area) const {
Area2DSW *area = area_owner.get(p_area);
- ERR_FAIL_COND_V(!area,Transform2D());
+ ERR_FAIL_COND_V(!area, Transform2D());
return area->get_transform();
};
-void Physics2DServerSW::area_set_pickable(RID p_area,bool p_pickable) {
+void Physics2DServerSW::area_set_pickable(RID p_area, bool p_pickable) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_pickable(p_pickable);
-
}
-void Physics2DServerSW::area_set_monitorable(RID p_area,bool p_monitorable) {
+void Physics2DServerSW::area_set_monitorable(RID p_area, bool p_monitorable) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
area->set_monitorable(p_monitorable);
-
}
-void Physics2DServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) {
+void Physics2DServerSW::area_set_collision_mask(RID p_area, uint32_t p_mask) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -515,7 +475,7 @@ void Physics2DServerSW::area_set_collision_mask(RID p_area,uint32_t p_mask) {
area->set_collision_mask(p_mask);
}
-void Physics2DServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) {
+void Physics2DServerSW::area_set_layer_mask(RID p_area, uint32_t p_mask) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
@@ -523,59 +483,53 @@ void Physics2DServerSW::area_set_layer_mask(RID p_area,uint32_t p_mask) {
area->set_layer_mask(p_mask);
}
-
-void Physics2DServerSW::area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) {
+void Physics2DServerSW::area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method);
-
-
+ area->set_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method);
}
-void Physics2DServerSW::area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method) {
-
+void Physics2DServerSW::area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) {
Area2DSW *area = area_owner.get(p_area);
ERR_FAIL_COND(!area);
- area->set_area_monitor_callback(p_receiver?p_receiver->get_instance_ID():0,p_method);
+ area->set_area_monitor_callback(p_receiver ? p_receiver->get_instance_ID() : 0, p_method);
}
/* BODY API */
-RID Physics2DServerSW::body_create(BodyMode p_mode,bool p_init_sleeping) {
+RID Physics2DServerSW::body_create(BodyMode p_mode, bool p_init_sleeping) {
- Body2DSW *body = memnew( Body2DSW );
- if (p_mode!=BODY_MODE_RIGID)
+ Body2DSW *body = memnew(Body2DSW);
+ if (p_mode != BODY_MODE_RIGID)
body->set_mode(p_mode);
if (p_init_sleeping)
- body->set_state(BODY_STATE_SLEEPING,p_init_sleeping);
+ body->set_state(BODY_STATE_SLEEPING, p_init_sleeping);
RID rid = body_owner.make_rid(body);
body->set_self(rid);
return rid;
};
-
void Physics2DServerSW::body_set_space(RID p_body, RID p_space) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- Space2DSW *space=NULL;
+ Space2DSW *space = NULL;
if (p_space.is_valid()) {
space = space_owner.get(p_space);
ERR_FAIL_COND(!space);
}
body->set_space(space);
-
};
RID Physics2DServerSW::body_get_space(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,RID());
+ ERR_FAIL_COND_V(!body, RID());
Space2DSW *space = body->get_space();
if (!space)
@@ -583,7 +537,6 @@ RID Physics2DServerSW::body_get_space(RID p_body) const {
return space->get_self();
};
-
void Physics2DServerSW::body_set_mode(RID p_body, BodyMode p_mode) {
Body2DSW *body = body_owner.get(p_body);
@@ -595,12 +548,12 @@ void Physics2DServerSW::body_set_mode(RID p_body, BodyMode p_mode) {
Physics2DServer::BodyMode Physics2DServerSW::body_get_mode(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,BODY_MODE_STATIC);
+ ERR_FAIL_COND_V(!body, BODY_MODE_STATIC);
return body->get_mode();
};
-void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform) {
+void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -608,11 +561,10 @@ void Physics2DServerSW::body_add_shape(RID p_body, RID p_shape, const Transform2
Shape2DSW *shape = shape_owner.get(p_shape);
ERR_FAIL_COND(!shape);
- body->add_shape(shape,p_transform);
-
+ body->add_shape(shape, p_transform);
}
-void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape) {
+void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx, RID p_shape) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -621,55 +573,51 @@ void Physics2DServerSW::body_set_shape(RID p_body, int p_shape_idx,RID p_shape)
ERR_FAIL_COND(!shape);
ERR_FAIL_COND(!shape->is_configured());
- body->set_shape(p_shape_idx,shape);
-
+ body->set_shape(p_shape_idx, shape);
}
-void Physics2DServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D& p_transform) {
+void Physics2DServerSW::body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D &p_transform) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_shape_transform(p_shape_idx,p_transform);
+ body->set_shape_transform(p_shape_idx, p_transform);
}
-void Physics2DServerSW::body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata) {
+void Physics2DServerSW::body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_shape_metadata(p_shape_idx,p_metadata);
+ body->set_shape_metadata(p_shape_idx, p_metadata);
}
-
Variant Physics2DServerSW::body_get_shape_metadata(RID p_body, int p_shape_idx) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Variant());
+ ERR_FAIL_COND_V(!body, Variant());
return body->get_shape_metadata(p_shape_idx);
}
-
int Physics2DServerSW::body_get_shape_count(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,-1);
+ ERR_FAIL_COND_V(!body, -1);
return body->get_shape_count();
-
}
RID Physics2DServerSW::body_get_shape(RID p_body, int p_shape_idx) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,RID());
+ ERR_FAIL_COND_V(!body, RID());
Shape2DSW *shape = body->get_shape(p_shape_idx);
- ERR_FAIL_COND_V(!shape,RID());
+ ERR_FAIL_COND_V(!shape, RID());
return shape->get_self();
}
Transform2D Physics2DServerSW::body_get_shape_transform(RID p_body, int p_shape_idx) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Transform2D());
+ ERR_FAIL_COND_V(!body, Transform2D());
return body->get_shape_transform(p_shape_idx);
}
@@ -687,67 +635,57 @@ void Physics2DServerSW::body_clear_shapes(RID p_body) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- while(body->get_shape_count())
+ while (body->get_shape_count())
body->remove_shape(0);
-
}
-
-void Physics2DServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable) {
+void Physics2DServerSW::body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- ERR_FAIL_INDEX(p_shape_idx,body->get_shape_count());
-
- body->set_shape_as_trigger(p_shape_idx,p_enable);
+ ERR_FAIL_INDEX(p_shape_idx, body->get_shape_count());
+ body->set_shape_as_trigger(p_shape_idx, p_enable);
}
bool Physics2DServerSW::body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const {
const Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
+ ERR_FAIL_COND_V(!body, false);
- ERR_FAIL_INDEX_V(p_shape_idx,body->get_shape_count(),false);
+ ERR_FAIL_INDEX_V(p_shape_idx, body->get_shape_count(), false);
return body->is_shape_set_as_trigger(p_shape_idx);
-
}
-
-void Physics2DServerSW::body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode) {
+void Physics2DServerSW::body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_continuous_collision_detection_mode(p_mode);
-
}
-Physics2DServerSW::CCDMode Physics2DServerSW::body_get_continuous_collision_detection_mode(RID p_body) const{
+Physics2DServerSW::CCDMode Physics2DServerSW::body_get_continuous_collision_detection_mode(RID p_body) const {
const Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,CCD_MODE_DISABLED);
+ ERR_FAIL_COND_V(!body, CCD_MODE_DISABLED);
return body->get_continuous_collision_detection_mode();
-
}
-
-
-void Physics2DServerSW::body_attach_object_instance_ID(RID p_body,uint32_t p_ID) {
+void Physics2DServerSW::body_attach_object_instance_ID(RID p_body, uint32_t p_ID) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_instance_id(p_ID);
-
};
uint32_t Physics2DServerSW::body_get_object_instance_ID(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_instance_id();
};
@@ -757,30 +695,27 @@ void Physics2DServerSW::body_set_layer_mask(RID p_body, uint32_t p_flags) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_layer_mask(p_flags);
-
};
uint32_t Physics2DServerSW::body_get_layer_mask(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_layer_mask();
};
-
void Physics2DServerSW::body_set_collision_mask(RID p_body, uint32_t p_flags) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_collision_mask(p_flags);
-
};
uint32_t Physics2DServerSW::body_get_collision_mask(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_collision_mask();
};
@@ -790,50 +725,46 @@ void Physics2DServerSW::body_set_param(RID p_body, BodyParameter p_param, real_t
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_param(p_param,p_value);
+ body->set_param(p_param, p_value);
};
real_t Physics2DServerSW::body_get_param(RID p_body, BodyParameter p_param) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_param(p_param);
};
-
-
-void Physics2DServerSW::body_set_state(RID p_body, BodyState p_state, const Variant& p_variant) {
+void Physics2DServerSW::body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_state(p_state,p_variant);
+ body->set_state(p_state, p_variant);
};
Variant Physics2DServerSW::body_get_state(RID p_body, BodyState p_state) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Variant());
+ ERR_FAIL_COND_V(!body, Variant());
return body->get_state(p_state);
};
-
-void Physics2DServerSW::body_set_applied_force(RID p_body, const Vector2& p_force) {
+void Physics2DServerSW::body_set_applied_force(RID p_body, const Vector2 &p_force) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_applied_force(p_force);
body->wakeup();
-
};
Vector2 Physics2DServerSW::body_get_applied_force(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Vector2());
+ ERR_FAIL_COND_V(!body, Vector2());
return body->get_applied_force();
};
@@ -849,38 +780,38 @@ void Physics2DServerSW::body_set_applied_torque(RID p_body, real_t p_torque) {
real_t Physics2DServerSW::body_get_applied_torque(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_applied_torque();
};
-void Physics2DServerSW::body_apply_impulse(RID p_body, const Vector2& p_pos, const Vector2& p_impulse) {
+void Physics2DServerSW::body_apply_impulse(RID p_body, const Vector2 &p_pos, const Vector2 &p_impulse) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->apply_impulse(p_pos,p_impulse);
+ body->apply_impulse(p_pos, p_impulse);
body->wakeup();
};
-void Physics2DServerSW::body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force) {
+void Physics2DServerSW::body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->add_force(p_force,p_offset);
+ body->add_force(p_force, p_offset);
body->wakeup();
};
-void Physics2DServerSW::body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity) {
+void Physics2DServerSW::body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
Vector2 v = body->get_linear_velocity();
Vector2 axis = p_axis_velocity.normalized();
- v-=axis*axis.dot(v);
- v+=p_axis_velocity;
+ v -= axis * axis.dot(v);
+ v += p_axis_velocity;
body->set_linear_velocity(v);
body->wakeup();
};
@@ -901,7 +832,6 @@ void Physics2DServerSW::body_remove_collision_exception(RID p_body, RID p_body_b
body->remove_exception(p_body_b);
body->wakeup();
-
};
void Physics2DServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) {
@@ -909,27 +839,25 @@ void Physics2DServerSW::body_get_collision_exceptions(RID p_body, List<RID> *p_e
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- for(int i=0;i<body->get_exceptions().size();i++) {
+ for (int i = 0; i < body->get_exceptions().size(); i++) {
p_exceptions->push_back(body->get_exceptions()[i]);
}
-
};
void Physics2DServerSW::body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
-
};
real_t Physics2DServerSW::body_get_contacts_reported_depth_treshold(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return 0;
};
-void Physics2DServerSW::body_set_omit_force_integration(RID p_body,bool p_omit) {
+void Physics2DServerSW::body_set_omit_force_integration(RID p_body, bool p_omit) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
@@ -940,7 +868,7 @@ void Physics2DServerSW::body_set_omit_force_integration(RID p_body,bool p_omit)
bool Physics2DServerSW::body_is_omitting_force_integration(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
+ ERR_FAIL_COND_V(!body, false);
return body->get_omit_force_integration();
};
@@ -954,80 +882,71 @@ void Physics2DServerSW::body_set_max_contacts_reported(RID p_body, int p_contact
int Physics2DServerSW::body_get_max_contacts_reported(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,-1);
+ ERR_FAIL_COND_V(!body, -1);
return body->get_max_contacts_reported();
}
-void Physics2DServerSW::body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction) {
+void Physics2DServerSW::body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_one_way_collision_direction(p_direction);
}
-Vector2 Physics2DServerSW::body_get_one_way_collision_direction(RID p_body) const{
+Vector2 Physics2DServerSW::body_get_one_way_collision_direction(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,Vector2());
+ ERR_FAIL_COND_V(!body, Vector2());
return body->get_one_way_collision_direction();
-
}
-void Physics2DServerSW::body_set_one_way_collision_max_depth(RID p_body,real_t p_max_depth) {
+void Physics2DServerSW::body_set_one_way_collision_max_depth(RID p_body, real_t p_max_depth) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_one_way_collision_max_depth(p_max_depth);
-
}
real_t Physics2DServerSW::body_get_one_way_collision_max_depth(RID p_body) const {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,0);
+ ERR_FAIL_COND_V(!body, 0);
return body->get_one_way_collision_max_depth();
-
}
-void Physics2DServerSW::body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata) {
-
+void Physics2DServerSW::body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
- body->set_force_integration_callback(p_receiver?p_receiver->get_instance_ID():ObjectID(0),p_method,p_udata);
-
+ body->set_force_integration_callback(p_receiver ? p_receiver->get_instance_ID() : ObjectID(0), p_method, p_udata);
}
-bool Physics2DServerSW::body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count) {
+bool Physics2DServerSW::body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
- ERR_FAIL_INDEX_V(p_body_shape,body->get_shape_count(),false);
-
- return shape_collide(body->get_shape(p_body_shape)->get_self(),body->get_transform() * body->get_shape_transform(p_body_shape),Vector2(),p_shape,p_shape_xform,p_motion,r_results,p_result_max,r_result_count);
+ ERR_FAIL_COND_V(!body, false);
+ ERR_FAIL_INDEX_V(p_body_shape, body->get_shape_count(), false);
+ return shape_collide(body->get_shape(p_body_shape)->get_self(), body->get_transform() * body->get_shape_transform(p_body_shape), Vector2(), p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count);
}
-void Physics2DServerSW::body_set_pickable(RID p_body,bool p_pickable) {
+void Physics2DServerSW::body_set_pickable(RID p_body, bool p_pickable) {
Body2DSW *body = body_owner.get(p_body);
ERR_FAIL_COND(!body);
body->set_pickable(p_pickable);
-
}
-bool Physics2DServerSW::body_test_motion(RID p_body, const Transform2D &p_from, const Vector2& p_motion, real_t p_margin, MotionResult *r_result) {
+bool Physics2DServerSW::body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, MotionResult *r_result) {
Body2DSW *body = body_owner.get(p_body);
- ERR_FAIL_COND_V(!body,false);
- ERR_FAIL_COND_V(!body->get_space(),false);
- ERR_FAIL_COND_V(body->get_space()->is_locked(),false);
-
- return body->get_space()->test_body_motion(body,p_from,p_motion,p_margin,r_result);
+ ERR_FAIL_COND_V(!body, false);
+ ERR_FAIL_COND_V(!body->get_space(), false);
+ ERR_FAIL_COND_V(body->get_space()->is_locked(), false);
+ return body->get_space()->test_body_motion(body, p_from, p_motion, p_margin, r_result);
}
-
/* JOINT API */
void Physics2DServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t p_value) {
@@ -1035,21 +954,19 @@ void Physics2DServerSW::joint_set_param(RID p_joint, JointParam p_param, real_t
Joint2DSW *joint = joint_owner.get(p_joint);
ERR_FAIL_COND(!joint);
- switch(p_param) {
+ switch (p_param) {
case JOINT_PARAM_BIAS: joint->set_bias(p_value); break;
case JOINT_PARAM_MAX_BIAS: joint->set_max_bias(p_value); break;
case JOINT_PARAM_MAX_FORCE: joint->set_max_force(p_value); break;
}
-
-
}
-real_t Physics2DServerSW::joint_get_param(RID p_joint,JointParam p_param) const {
+real_t Physics2DServerSW::joint_get_param(RID p_joint, JointParam p_param) const {
const Joint2DSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,-1);
+ ERR_FAIL_COND_V(!joint, -1);
- switch(p_param) {
+ switch (p_param) {
case JOINT_PARAM_BIAS: return joint->get_bias(); break;
case JOINT_PARAM_MAX_BIAS: return joint->get_max_bias(); break;
case JOINT_PARAM_MAX_FORCE: return joint->get_max_force(); break;
@@ -1058,115 +975,106 @@ real_t Physics2DServerSW::joint_get_param(RID p_joint,JointParam p_param) const
return 0;
}
+RID Physics2DServerSW::pin_joint_create(const Vector2 &p_pos, RID p_body_a, RID p_body_b) {
-RID Physics2DServerSW::pin_joint_create(const Vector2& p_pos,RID p_body_a,RID p_body_b) {
-
- Body2DSW *A=body_owner.get(p_body_a);
- ERR_FAIL_COND_V(!A,RID());
- Body2DSW *B=NULL;
+ Body2DSW *A = body_owner.get(p_body_a);
+ ERR_FAIL_COND_V(!A, RID());
+ Body2DSW *B = NULL;
if (body_owner.owns(p_body_b)) {
- B=body_owner.get(p_body_b);
- ERR_FAIL_COND_V(!B,RID());
+ B = body_owner.get(p_body_b);
+ ERR_FAIL_COND_V(!B, RID());
}
- Joint2DSW *joint = memnew( PinJoint2DSW(p_pos,A,B) );
+ Joint2DSW *joint = memnew(PinJoint2DSW(p_pos, A, B));
RID self = joint_owner.make_rid(joint);
joint->set_self(self);
return self;
}
-RID Physics2DServerSW::groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b) {
-
+RID Physics2DServerSW::groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b) {
- Body2DSW *A=body_owner.get(p_body_a);
- ERR_FAIL_COND_V(!A,RID());
+ Body2DSW *A = body_owner.get(p_body_a);
+ ERR_FAIL_COND_V(!A, RID());
- Body2DSW *B=body_owner.get(p_body_b);
- ERR_FAIL_COND_V(!B,RID());
+ Body2DSW *B = body_owner.get(p_body_b);
+ ERR_FAIL_COND_V(!B, RID());
- Joint2DSW *joint = memnew( GrooveJoint2DSW(p_a_groove1,p_a_groove2,p_b_anchor,A,B) );
+ Joint2DSW *joint = memnew(GrooveJoint2DSW(p_a_groove1, p_a_groove2, p_b_anchor, A, B));
RID self = joint_owner.make_rid(joint);
joint->set_self(self);
return self;
-
-
}
-RID Physics2DServerSW::damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b) {
+RID Physics2DServerSW::damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b) {
- Body2DSW *A=body_owner.get(p_body_a);
- ERR_FAIL_COND_V(!A,RID());
+ Body2DSW *A = body_owner.get(p_body_a);
+ ERR_FAIL_COND_V(!A, RID());
- Body2DSW *B=body_owner.get(p_body_b);
- ERR_FAIL_COND_V(!B,RID());
+ Body2DSW *B = body_owner.get(p_body_b);
+ ERR_FAIL_COND_V(!B, RID());
- Joint2DSW *joint = memnew( DampedSpringJoint2DSW(p_anchor_a,p_anchor_b,A,B) );
+ Joint2DSW *joint = memnew(DampedSpringJoint2DSW(p_anchor_a, p_anchor_b, A, B));
RID self = joint_owner.make_rid(joint);
joint->set_self(self);
return self;
-
}
void Physics2DServerSW::pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) {
Joint2DSW *j = joint_owner.get(p_joint);
ERR_FAIL_COND(!j);
- ERR_FAIL_COND(j->get_type()!=JOINT_PIN);
+ ERR_FAIL_COND(j->get_type() != JOINT_PIN);
- PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW*>(j);
+ PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW *>(j);
pin_joint->set_param(p_param, p_value);
}
real_t Physics2DServerSW::pin_joint_get_param(RID p_joint, PinJointParam p_param) const {
Joint2DSW *j = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!j,0);
- ERR_FAIL_COND_V(j->get_type()!=JOINT_PIN,0);
+ ERR_FAIL_COND_V(!j, 0);
+ ERR_FAIL_COND_V(j->get_type() != JOINT_PIN, 0);
- PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW*>(j);
+ PinJoint2DSW *pin_joint = static_cast<PinJoint2DSW *>(j);
return pin_joint->get_param(p_param);
}
void Physics2DServerSW::damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value) {
-
Joint2DSW *j = joint_owner.get(p_joint);
ERR_FAIL_COND(!j);
- ERR_FAIL_COND(j->get_type()!=JOINT_DAMPED_SPRING);
+ ERR_FAIL_COND(j->get_type() != JOINT_DAMPED_SPRING);
- DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW*>(j);
- dsj->set_param(p_param,p_value);
+ DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW *>(j);
+ dsj->set_param(p_param, p_value);
}
real_t Physics2DServerSW::damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const {
Joint2DSW *j = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!j,0);
- ERR_FAIL_COND_V(j->get_type()!=JOINT_DAMPED_SPRING,0);
+ ERR_FAIL_COND_V(!j, 0);
+ ERR_FAIL_COND_V(j->get_type() != JOINT_DAMPED_SPRING, 0);
- DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW*>(j);
+ DampedSpringJoint2DSW *dsj = static_cast<DampedSpringJoint2DSW *>(j);
return dsj->get_param(p_param);
}
Physics2DServer::JointType Physics2DServerSW::joint_get_type(RID p_joint) const {
-
Joint2DSW *joint = joint_owner.get(p_joint);
- ERR_FAIL_COND_V(!joint,JOINT_PIN);
+ ERR_FAIL_COND_V(!joint, JOINT_PIN);
return joint->get_type();
}
-
-
void Physics2DServerSW::free(RID p_rid) {
if (shape_owner.owns(p_rid)) {
Shape2DSW *shape = shape_owner.get(p_rid);
- while(shape->get_owners().size()) {
- ShapeOwner2DSW *so=shape->get_owners().front()->key();
+ while (shape->get_owners().size()) {
+ ShapeOwner2DSW *so = shape->get_owners().front()->key();
so->remove_shape(shape);
}
@@ -1186,8 +1094,7 @@ void Physics2DServerSW::free(RID p_rid) {
body->set_space(NULL);
-
- while( body->get_shape_count() ) {
+ while (body->get_shape_count()) {
body->remove_shape(0);
}
@@ -1212,7 +1119,7 @@ void Physics2DServerSW::free(RID p_rid) {
area->set_space(NULL);
- while( area->get_shape_count() ) {
+ while (area->get_shape_count()) {
area->remove_shape(0);
}
@@ -1223,7 +1130,7 @@ void Physics2DServerSW::free(RID p_rid) {
Space2DSW *space = space_owner.get(p_rid);
- while(space->get_objects().size()) {
+ while (space->get_objects().size()) {
CollisionObject2DSW *co = (CollisionObject2DSW *)space->get_objects().front()->get();
co->set_space(NULL);
}
@@ -1244,52 +1151,46 @@ void Physics2DServerSW::free(RID p_rid) {
ERR_EXPLAIN("Invalid ID");
ERR_FAIL();
}
-
-
};
void Physics2DServerSW::set_active(bool p_active) {
- active=p_active;
+ active = p_active;
};
void Physics2DServerSW::init() {
- doing_sync=false;
- last_step=0.001;
- iterations=8;// 8?
- stepper = memnew( Step2DSW );
- direct_state = memnew( Physics2DDirectBodyStateSW );
+ doing_sync = false;
+ last_step = 0.001;
+ iterations = 8; // 8?
+ stepper = memnew(Step2DSW);
+ direct_state = memnew(Physics2DDirectBodyStateSW);
};
-
void Physics2DServerSW::step(real_t p_step) {
-
if (!active)
return;
- doing_sync=false;
+ doing_sync = false;
- last_step=p_step;
- Physics2DDirectBodyStateSW::singleton->step=p_step;
- island_count=0;
- active_objects=0;
- collision_pairs=0;
- for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ last_step = p_step;
+ Physics2DDirectBodyStateSW::singleton->step = p_step;
+ island_count = 0;
+ active_objects = 0;
+ collision_pairs = 0;
+ for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- stepper->step((Space2DSW*)E->get(),p_step,iterations);
- island_count+=E->get()->get_island_count();
- active_objects+=E->get()->get_active_objects();
- collision_pairs+=E->get()->get_collision_pairs();
+ stepper->step((Space2DSW *)E->get(), p_step, iterations);
+ island_count += E->get()->get_island_count();
+ active_objects += E->get()->get_active_objects();
+ collision_pairs += E->get()->get_collision_pairs();
}
-
-
};
void Physics2DServerSW::sync() {
- doing_sync=true;
+ doing_sync = true;
};
void Physics2DServerSW::flush_queries() {
@@ -1299,17 +1200,16 @@ void Physics2DServerSW::flush_queries() {
uint64_t time_beg = OS::get_singleton()->get_ticks_usec();
- for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- Space2DSW *space=(Space2DSW *)E->get();
+ Space2DSW *space = (Space2DSW *)E->get();
space->call_queries();
}
-
if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_profiling()) {
uint64_t total_time[Space2DSW::ELAPSED_TIME_MAX];
- static const char* time_name[Space2DSW::ELAPSED_TIME_MAX]={
+ static const char *time_name[Space2DSW::ELAPSED_TIME_MAX] = {
"integrate_forces",
"generate_islands",
"setup_constraints",
@@ -1317,39 +1217,34 @@ void Physics2DServerSW::flush_queries() {
"integrate_velocities"
};
- for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) {
- total_time[i]=0;
+ for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) {
+ total_time[i] = 0;
}
- for( Set<const Space2DSW*>::Element *E=active_spaces.front();E;E=E->next()) {
+ for (Set<const Space2DSW *>::Element *E = active_spaces.front(); E; E = E->next()) {
- for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) {
- total_time[i]+=E->get()->get_elapsed_time(Space2DSW::ElapsedTime(i));
+ for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) {
+ total_time[i] += E->get()->get_elapsed_time(Space2DSW::ElapsedTime(i));
}
-
}
Array values;
- values.resize(Space2DSW::ELAPSED_TIME_MAX*2);
- for(int i=0;i<Space2DSW::ELAPSED_TIME_MAX;i++) {
- values[i*2+0]=time_name[i];
- values[i*2+1]=USEC_TO_SEC(total_time[i]);
+ values.resize(Space2DSW::ELAPSED_TIME_MAX * 2);
+ for (int i = 0; i < Space2DSW::ELAPSED_TIME_MAX; i++) {
+ values[i * 2 + 0] = time_name[i];
+ values[i * 2 + 1] = USEC_TO_SEC(total_time[i]);
}
values.push_back("flush_queries");
- values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec()-time_beg));
-
- ScriptDebugger::get_singleton()->add_profiling_frame_data("physics_2d",values);
+ values.push_back(USEC_TO_SEC(OS::get_singleton()->get_ticks_usec() - time_beg));
+ ScriptDebugger::get_singleton()->add_profiling_frame_data("physics_2d", values);
}
-
}
void Physics2DServerSW::end_sync() {
- doing_sync=false;
+ doing_sync = false;
}
-
-
void Physics2DServerSW::finish() {
memdelete(stepper);
@@ -1358,7 +1253,7 @@ void Physics2DServerSW::finish() {
int Physics2DServerSW::get_process_info(ProcessInfo p_info) {
- switch(p_info) {
+ switch (p_info) {
case INFO_ACTIVE_OBJECTS: {
@@ -1371,32 +1266,26 @@ int Physics2DServerSW::get_process_info(ProcessInfo p_info) {
return island_count;
} break;
-
}
return 0;
}
-
-Physics2DServerSW *Physics2DServerSW::singletonsw=NULL;
+Physics2DServerSW *Physics2DServerSW::singletonsw = NULL;
Physics2DServerSW::Physics2DServerSW() {
- singletonsw=this;
- BroadPhase2DSW::create_func=BroadPhase2DHashGrid::_create;
+ singletonsw = this;
+ BroadPhase2DSW::create_func = BroadPhase2DHashGrid::_create;
//BroadPhase2DSW::create_func=BroadPhase2DBasic::_create;
- active=true;
- island_count=0;
- active_objects=0;
- collision_pairs=0;
- using_threads=int(GlobalConfig::get_singleton()->get("physics/2d/thread_model"))==2;
-
+ active = true;
+ island_count = 0;
+ active_objects = 0;
+ collision_pairs = 0;
+ using_threads = int(GlobalConfig::get_singleton()->get("physics/2d/thread_model")) == 2;
};
-
-Physics2DServerSW::~Physics2DServerSW() {
+Physics2DServerSW::~Physics2DServerSW(){
};
-
-
diff --git a/servers/physics_2d/physics_2d_server_sw.h b/servers/physics_2d/physics_2d_server_sw.h
index e33e2d78c7..b49c37ab21 100644
--- a/servers/physics_2d/physics_2d_server_sw.h
+++ b/servers/physics_2d/physics_2d_server_sw.h
@@ -29,20 +29,18 @@
#ifndef PHYSICS_2D_SERVER_SW
#define PHYSICS_2D_SERVER_SW
-
+#include "joints_2d_sw.h"
#include "servers/physics_2d_server.h"
#include "shape_2d_sw.h"
#include "space_2d_sw.h"
#include "step_2d_sw.h"
-#include "joints_2d_sw.h"
-
class Physics2DServerSW : public Physics2DServer {
- GDCLASS( Physics2DServerSW, Physics2DServer );
+ GDCLASS(Physics2DServerSW, Physics2DServer);
-friend class Physics2DDirectSpaceStateSW;
-friend class Physics2DDirectBodyStateSW;
+ friend class Physics2DDirectSpaceStateSW;
+ friend class Physics2DDirectBodyStateSW;
bool active;
int iterations;
bool doing_sync;
@@ -54,10 +52,8 @@ friend class Physics2DDirectBodyStateSW;
bool using_threads;
-
-
Step2DSW *stepper;
- Set<const Space2DSW*> active_spaces;
+ Set<const Space2DSW *> active_spaces;
Physics2DDirectBodyStateSW *direct_state;
@@ -69,10 +65,8 @@ friend class Physics2DDirectBodyStateSW;
static Physics2DServerSW *singletonsw;
-
//void _clear_query(Query2DSW *p_query);
public:
-
struct CollCbkData {
Vector2 valid_dir;
@@ -82,36 +76,33 @@ public:
Vector2 *ptr;
};
- static void _shape_col_cbk(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata);
-
+ static void _shape_col_cbk(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata);
virtual RID shape_create(ShapeType p_shape);
- virtual void shape_set_data(RID p_shape, const Variant& p_data);
+ virtual void shape_set_data(RID p_shape, const Variant &p_data);
virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias);
virtual ShapeType shape_get_type(RID p_shape) const;
virtual Variant shape_get_data(RID p_shape) const;
virtual real_t shape_get_custom_solver_bias(RID p_shape) const;
- virtual bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count);
+ virtual bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count);
/* SPACE API */
virtual RID space_create();
- virtual void space_set_active(RID p_space,bool p_active);
+ virtual void space_set_active(RID p_space, bool p_active);
virtual bool space_is_active(RID p_space) const;
- virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value);
- virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const;
+ virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value);
+ virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const;
- virtual void space_set_debug_contacts(RID p_space,int p_max_contacts);
+ virtual void space_set_debug_contacts(RID p_space, int p_max_contacts);
virtual Vector<Vector2> space_get_contacts(RID p_space) const;
virtual int space_get_contact_count(RID p_space) const;
-
// this function only works on fixed process, errors and returns null otherwise
- virtual Physics2DDirectSpaceState* space_get_direct_state(RID p_space);
-
+ virtual Physics2DDirectSpaceState *space_get_direct_state(RID p_space);
/* AREA API */
@@ -123,9 +114,9 @@ public:
virtual void area_set_space(RID p_area, RID p_space);
virtual RID area_get_space(RID p_area) const;
- virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform=Transform2D());
- 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 Transform2D& p_transform);
+ virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform = Transform2D());
+ 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 Transform2D &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;
@@ -134,28 +125,27 @@ public:
virtual void area_remove_shape(RID p_area, int p_shape_idx);
virtual void area_clear_shapes(RID p_area);
- virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID);
+ 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_set_param(RID p_area,AreaParameter p_param,const Variant& p_value);
- virtual void area_set_transform(RID p_area, const Transform2D& p_transform);
+ virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value);
+ virtual void area_set_transform(RID p_area, const Transform2D &p_transform);
- virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const;
+ virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const;
virtual Transform2D area_get_transform(RID p_area) const;
- virtual void area_set_monitorable(RID p_area,bool p_monitorable);
- virtual void area_set_collision_mask(RID p_area,uint32_t p_mask);
- virtual void area_set_layer_mask(RID p_area,uint32_t p_mask);
-
- 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_monitorable(RID p_area, bool p_monitorable);
+ virtual void area_set_collision_mask(RID p_area, uint32_t p_mask);
+ virtual void area_set_layer_mask(RID p_area, uint32_t p_mask);
- virtual void area_set_pickable(RID p_area,bool p_pickable);
+ 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_pickable(RID p_area, bool p_pickable);
/* BODY API */
// create a body of a given type
- 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);
virtual void body_set_space(RID p_body, RID p_space);
virtual RID body_get_space(RID p_body) const;
@@ -163,28 +153,26 @@ public:
virtual void body_set_mode(RID p_body, BodyMode p_mode);
virtual BodyMode body_get_mode(RID p_body) const;
- virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform=Transform2D());
- 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 Transform2D& p_transform);
- virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata);
-
+ virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform = Transform2D());
+ 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 Transform2D &p_transform);
+ virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata);
virtual int body_get_shape_count(RID p_body) const;
virtual RID body_get_shape(RID p_body, int p_shape_idx) const;
virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const;
virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const;
-
virtual void body_remove_shape(RID p_body, int p_shape_idx);
virtual void body_clear_shapes(RID p_body);
- virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable);
+ virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable);
virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const;
- virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID);
+ virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID);
virtual uint32_t body_get_object_instance_ID(RID p_body) const;
- virtual void body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode);
+ virtual void body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode);
virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const;
virtual void body_set_layer_mask(RID p_body, uint32_t p_mask);
@@ -196,20 +184,19 @@ public:
virtual void body_set_param(RID p_body, BodyParameter p_param, real_t p_value);
virtual real_t body_get_param(RID p_body, BodyParameter p_param) const;
-
- virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant);
+ 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_applied_force(RID p_body, const Vector2& p_force);
+ virtual void body_set_applied_force(RID p_body, const Vector2 &p_force);
virtual Vector2 body_get_applied_force(RID p_body) const;
virtual void body_set_applied_torque(RID p_body, real_t p_torque);
virtual real_t body_get_applied_torque(RID p_body) const;
- virtual void body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force);
+ virtual void body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force);
- virtual void body_apply_impulse(RID p_body, const Vector2& p_pos, const Vector2& p_impulse);
- virtual void body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity);
+ virtual void body_apply_impulse(RID p_body, const Vector2 &p_pos, const Vector2 &p_impulse);
+ virtual void body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity);
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);
@@ -218,35 +205,33 @@ public:
virtual void body_set_contacts_reported_depth_treshold(RID p_body, real_t p_treshold);
virtual real_t body_get_contacts_reported_depth_treshold(RID p_body) const;
- virtual void body_set_omit_force_integration(RID p_body,bool p_omit);
+ 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_max_contacts_reported(RID p_body, int p_contacts);
virtual int body_get_max_contacts_reported(RID p_body) const;
- virtual void body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction);
+ virtual void body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction);
virtual Vector2 body_get_one_way_collision_direction(RID p_body) const;
- virtual void body_set_one_way_collision_max_depth(RID p_body,real_t p_max_depth);
+ virtual void body_set_one_way_collision_max_depth(RID p_body, real_t p_max_depth);
virtual real_t body_get_one_way_collision_max_depth(RID p_body) const;
+ virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant());
+ virtual bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count);
- virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant());
- virtual bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count);
-
- virtual void body_set_pickable(RID p_body,bool p_pickable);
-
- virtual bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,real_t p_margin=0.001,MotionResult *r_result=NULL);
+ virtual void body_set_pickable(RID p_body, bool p_pickable);
+ virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = NULL);
/* JOINT API */
virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value);
- virtual real_t joint_get_param(RID p_joint,JointParam p_param) const;
+ virtual real_t joint_get_param(RID p_joint, JointParam p_param) const;
- virtual RID pin_joint_create(const Vector2& p_pos,RID p_body_a,RID p_body_b=RID());
- virtual RID groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b);
- virtual RID damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b=RID());
+ virtual RID pin_joint_create(const Vector2 &p_pos, RID p_body_a, RID p_body_b = RID());
+ virtual RID groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b);
+ virtual RID damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b = RID());
virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value);
virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const;
virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value);
@@ -270,8 +255,6 @@ public:
Physics2DServerSW();
~Physics2DServerSW();
-
};
#endif
-
diff --git a/servers/physics_2d/physics_2d_server_wrap_mt.cpp b/servers/physics_2d/physics_2d_server_wrap_mt.cpp
index 34ba149d23..ef1a5b333c 100644
--- a/servers/physics_2d/physics_2d_server_wrap_mt.cpp
+++ b/servers/physics_2d/physics_2d_server_wrap_mt.cpp
@@ -32,35 +32,33 @@
void Physics2DServerWrapMT::thread_exit() {
- exit=true;
+ exit = true;
}
void Physics2DServerWrapMT::thread_step(real_t p_delta) {
physics_2d_server->step(p_delta);
step_sem->post();
-
}
void Physics2DServerWrapMT::_thread_callback(void *_instance) {
- Physics2DServerWrapMT *vsmt = reinterpret_cast<Physics2DServerWrapMT*>(_instance);
-
+ Physics2DServerWrapMT *vsmt = reinterpret_cast<Physics2DServerWrapMT *>(_instance);
vsmt->thread_loop();
}
void Physics2DServerWrapMT::thread_loop() {
- server_thread=Thread::get_caller_ID();
+ server_thread = Thread::get_caller_ID();
OS::get_singleton()->make_rendering_thread();
physics_2d_server->init();
- exit=false;
- step_thread_up=true;
- while(!exit) {
+ exit = false;
+ step_thread_up = true;
+ while (!exit) {
// flush commands one by one, until exit is requested
command_queue.wait_and_flush_one();
}
@@ -68,18 +66,15 @@ void Physics2DServerWrapMT::thread_loop() {
command_queue.flush_all(); // flush all
physics_2d_server->finish();
-
}
-
/* EVENT QUEUING */
-
void Physics2DServerWrapMT::step(real_t p_step) {
if (create_thread) {
- command_queue.push( this, &Physics2DServerWrapMT::thread_step,p_step);
+ command_queue.push(this, &Physics2DServerWrapMT::thread_step, p_step);
} else {
command_queue.flush_all(); //flush all pending from other threads
@@ -91,14 +86,14 @@ void Physics2DServerWrapMT::sync() {
if (step_sem) {
if (first_frame)
- first_frame=false;
+ first_frame = false;
else
step_sem->wait(); //must not wait if a step was not issued
}
physics_2d_server->sync();
}
-void Physics2DServerWrapMT::flush_queries(){
+void Physics2DServerWrapMT::flush_queries() {
physics_2d_server->flush_queries();
}
@@ -116,10 +111,10 @@ void Physics2DServerWrapMT::init() {
print_line("CREATING PHYSICS 2D THREAD");
//OS::get_singleton()->release_rendering_thread();
if (create_thread) {
- thread = Thread::create( _thread_callback, this );
+ thread = Thread::create(_thread_callback, this);
print_line("STARTING PHYISICS 2D THREAD");
}
- while(!step_thread_up) {
+ while (!step_thread_up) {
OS::get_singleton()->delay_usec(1000);
}
print_line("DONE PHYSICS 2D THREAD");
@@ -127,19 +122,17 @@ void Physics2DServerWrapMT::init() {
physics_2d_server->init();
}
-
}
void Physics2DServerWrapMT::finish() {
-
if (thread) {
- command_queue.push( this, &Physics2DServerWrapMT::thread_exit);
- Thread::wait_to_finish( thread );
+ command_queue.push(this, &Physics2DServerWrapMT::thread_exit);
+ Thread::wait_to_finish(thread);
memdelete(thread);
-/*
+ /*
shape_free_cached_ids();
area_free_cached_ids();
body_free_cached_ids();
@@ -147,51 +140,46 @@ void Physics2DServerWrapMT::finish() {
groove_joint_free_cached_ids();
damped_string_free_cached_ids();
*/
- thread=NULL;
+ thread = NULL;
} else {
physics_2d_server->finish();
}
if (step_sem)
memdelete(step_sem);
-
}
+Physics2DServerWrapMT::Physics2DServerWrapMT(Physics2DServer *p_contained, bool p_create_thread)
+ : command_queue(p_create_thread) {
-Physics2DServerWrapMT::Physics2DServerWrapMT(Physics2DServer* p_contained,bool p_create_thread) : command_queue(p_create_thread) {
-
- physics_2d_server=p_contained;
- create_thread=p_create_thread;
- thread=NULL;
- step_sem=NULL;
- step_pending=0;
- step_thread_up=false;
- alloc_mutex=Mutex::create();
+ physics_2d_server = p_contained;
+ create_thread = p_create_thread;
+ thread = NULL;
+ step_sem = NULL;
+ step_pending = 0;
+ step_thread_up = false;
+ alloc_mutex = Mutex::create();
- shape_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
- area_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
- body_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
- pin_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
- groove_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
- damped_spring_joint_pool_max_size=GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ shape_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ area_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ body_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ pin_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ groove_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
+ damped_spring_joint_pool_max_size = GLOBAL_GET("memory/multithread/thread_rid_pool_prealloc");
if (!p_create_thread) {
- server_thread=Thread::get_caller_ID();
+ server_thread = Thread::get_caller_ID();
} else {
- server_thread=0;
+ server_thread = 0;
}
main_thread = Thread::get_caller_ID();
- first_frame=true;
+ first_frame = true;
}
-
Physics2DServerWrapMT::~Physics2DServerWrapMT() {
memdelete(physics_2d_server);
memdelete(alloc_mutex);
//finish();
-
}
-
-
diff --git a/servers/physics_2d/physics_2d_server_wrap_mt.h b/servers/physics_2d/physics_2d_server_wrap_mt.h
index f8b533080e..ff30b2df09 100644
--- a/servers/physics_2d/physics_2d_server_wrap_mt.h
+++ b/servers/physics_2d/physics_2d_server_wrap_mt.h
@@ -29,19 +29,17 @@
#ifndef PHYSICS2DSERVERWRAPMT_H
#define PHYSICS2DSERVERWRAPMT_H
-
-#include "servers/physics_2d_server.h"
#include "command_queue_mt.h"
-#include "os/thread.h"
#include "global_config.h"
+#include "os/thread.h"
+#include "servers/physics_2d_server.h"
#ifdef DEBUG_SYNC
-#define SYNC_DEBUG print_line("sync on: "+String(__FUNCTION__));
+#define SYNC_DEBUG print_line("sync on: " + String(__FUNCTION__));
#else
#define SYNC_DEBUG
#endif
-
class Physics2DServerWrapMT : public Physics2DServer {
mutable Physics2DServer *physics_2d_server;
@@ -65,7 +63,7 @@ class Physics2DServerWrapMT : public Physics2DServer {
void thread_exit();
- Mutex*alloc_mutex;
+ Mutex *alloc_mutex;
bool first_frame;
int shape_pool_max_size;
@@ -81,226 +79,209 @@ class Physics2DServerWrapMT : public Physics2DServer {
int damped_spring_joint_pool_max_size;
List<RID> damped_spring_joint_id_pool;
-
public:
-
#define ServerName Physics2DServer
#define ServerNameWrapMT Physics2DServerWrapMT
#define server_name physics_2d_server
#include "servers/server_wrap_mt_common.h"
//FUNC1RID(shape,ShapeType); todo fix
- FUNC1R(RID,shape_create,ShapeType);
- FUNC2(shape_set_data,RID,const Variant& );
- FUNC2(shape_set_custom_solver_bias,RID,real_t );
-
- FUNC1RC(ShapeType,shape_get_type,RID );
- FUNC1RC(Variant,shape_get_data,RID);
- FUNC1RC(real_t,shape_get_custom_solver_bias,RID);
+ FUNC1R(RID, shape_create, ShapeType);
+ FUNC2(shape_set_data, RID, const Variant &);
+ FUNC2(shape_set_custom_solver_bias, RID, real_t);
+ FUNC1RC(ShapeType, shape_get_type, RID);
+ FUNC1RC(Variant, shape_get_data, RID);
+ FUNC1RC(real_t, shape_get_custom_solver_bias, RID);
//these work well, but should be used from the main thread only
- bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count) {
+ bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) {
- ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),false);
- return physics_2d_server->shape_collide(p_shape_A,p_xform_A,p_motion_A,p_shape_B,p_xform_B,p_motion_B,r_results,p_result_max,r_result_count);
+ ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), false);
+ return physics_2d_server->shape_collide(p_shape_A, p_xform_A, p_motion_A, p_shape_B, p_xform_B, p_motion_B, r_results, p_result_max, r_result_count);
}
/* SPACE API */
- FUNC0R(RID,space_create);
- FUNC2(space_set_active,RID,bool);
- FUNC1RC(bool,space_is_active,RID);
+ FUNC0R(RID, space_create);
+ FUNC2(space_set_active, RID, bool);
+ FUNC1RC(bool, space_is_active, RID);
- FUNC3(space_set_param,RID,SpaceParameter,real_t);
- FUNC2RC(real_t,space_get_param,RID,SpaceParameter);
+ FUNC3(space_set_param, RID, SpaceParameter, real_t);
+ FUNC2RC(real_t, space_get_param, RID, SpaceParameter);
// this function only works on fixed process, errors and returns null otherwise
- Physics2DDirectSpaceState* space_get_direct_state(RID p_space) {
+ Physics2DDirectSpaceState *space_get_direct_state(RID p_space) {
- ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),NULL);
+ ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), NULL);
return physics_2d_server->space_get_direct_state(p_space);
}
- FUNC2(space_set_debug_contacts,RID,int);
+ FUNC2(space_set_debug_contacts, RID, int);
virtual Vector<Vector2> space_get_contacts(RID p_space) const {
- ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),Vector<Vector2>());
+ ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), Vector<Vector2>());
return physics_2d_server->space_get_contacts(p_space);
-
}
virtual int space_get_contact_count(RID p_space) const {
- ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),0);
+ ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), 0);
return physics_2d_server->space_get_contact_count(p_space);
-
}
-
-
/* AREA API */
//FUNC0RID(area);
- FUNC0R(RID,area_create);
-
- FUNC2(area_set_space,RID,RID);
- FUNC1RC(RID,area_get_space,RID);
+ FUNC0R(RID, area_create);
- FUNC2(area_set_space_override_mode,RID,AreaSpaceOverrideMode);
- FUNC1RC(AreaSpaceOverrideMode,area_get_space_override_mode,RID);
+ FUNC2(area_set_space, RID, RID);
+ FUNC1RC(RID, area_get_space, RID);
- FUNC3(area_add_shape,RID,RID,const Transform2D&);
- FUNC3(area_set_shape,RID,int,RID);
- FUNC3(area_set_shape_transform,RID,int,const Transform2D&);
+ FUNC2(area_set_space_override_mode, RID, AreaSpaceOverrideMode);
+ FUNC1RC(AreaSpaceOverrideMode, area_get_space_override_mode, RID);
- FUNC1RC(int,area_get_shape_count,RID);
- FUNC2RC(RID,area_get_shape,RID,int);
- FUNC2RC(Transform2D,area_get_shape_transform,RID,int);
- FUNC2(area_remove_shape,RID,int);
- FUNC1(area_clear_shapes,RID);
+ FUNC3(area_add_shape, RID, RID, const Transform2D &);
+ FUNC3(area_set_shape, RID, int, RID);
+ FUNC3(area_set_shape_transform, RID, int, const Transform2D &);
- FUNC2(area_attach_object_instance_ID,RID,ObjectID);
- FUNC1RC(ObjectID,area_get_object_instance_ID,RID);
+ FUNC1RC(int, area_get_shape_count, RID);
+ FUNC2RC(RID, area_get_shape, RID, int);
+ FUNC2RC(Transform2D, area_get_shape_transform, RID, int);
+ FUNC2(area_remove_shape, RID, int);
+ FUNC1(area_clear_shapes, RID);
- FUNC3(area_set_param,RID,AreaParameter,const Variant&);
- FUNC2(area_set_transform,RID,const Transform2D&);
+ FUNC2(area_attach_object_instance_ID, RID, ObjectID);
+ FUNC1RC(ObjectID, area_get_object_instance_ID, RID);
- FUNC2RC(Variant,area_get_param,RID,AreaParameter);
- FUNC1RC(Transform2D,area_get_transform,RID);
+ FUNC3(area_set_param, RID, AreaParameter, const Variant &);
+ FUNC2(area_set_transform, RID, const Transform2D &);
- FUNC2(area_set_collision_mask,RID,uint32_t);
- FUNC2(area_set_layer_mask,RID,uint32_t);
+ FUNC2RC(Variant, area_get_param, RID, AreaParameter);
+ FUNC1RC(Transform2D, area_get_transform, RID);
- FUNC2(area_set_monitorable,RID,bool);
- FUNC2(area_set_pickable,RID,bool);
+ FUNC2(area_set_collision_mask, RID, uint32_t);
+ FUNC2(area_set_layer_mask, RID, uint32_t);
- FUNC3(area_set_monitor_callback,RID,Object*,const StringName&);
- FUNC3(area_set_area_monitor_callback,RID,Object*,const StringName&);
+ FUNC2(area_set_monitorable, RID, bool);
+ FUNC2(area_set_pickable, RID, bool);
+ FUNC3(area_set_monitor_callback, RID, Object *, const StringName &);
+ FUNC3(area_set_area_monitor_callback, RID, Object *, const StringName &);
/* BODY API */
//FUNC2RID(body,BodyMode,bool);
- FUNC2R(RID,body_create,BodyMode,bool)
+ FUNC2R(RID, body_create, BodyMode, bool)
- FUNC2(body_set_space,RID,RID);
- FUNC1RC(RID,body_get_space,RID);
+ FUNC2(body_set_space, RID, RID);
+ FUNC1RC(RID, body_get_space, RID);
- FUNC2(body_set_mode,RID,BodyMode);
- FUNC1RC(BodyMode,body_get_mode,RID);
+ FUNC2(body_set_mode, RID, BodyMode);
+ FUNC1RC(BodyMode, body_get_mode, RID);
+ FUNC3(body_add_shape, RID, RID, const Transform2D &);
+ FUNC3(body_set_shape, RID, int, RID);
+ FUNC3(body_set_shape_transform, RID, int, const Transform2D &);
+ FUNC3(body_set_shape_metadata, RID, int, const Variant &);
- FUNC3(body_add_shape,RID,RID,const Transform2D&);
- FUNC3(body_set_shape,RID,int,RID);
- FUNC3(body_set_shape_transform,RID,int,const Transform2D&);
- FUNC3(body_set_shape_metadata,RID,int,const Variant&);
+ FUNC1RC(int, body_get_shape_count, RID);
+ FUNC2RC(Transform2D, body_get_shape_transform, RID, int);
+ FUNC2RC(Variant, body_get_shape_metadata, RID, int);
+ FUNC2RC(RID, body_get_shape, RID, int);
- FUNC1RC(int,body_get_shape_count,RID);
- FUNC2RC(Transform2D,body_get_shape_transform,RID,int);
- FUNC2RC(Variant,body_get_shape_metadata,RID,int);
- FUNC2RC(RID,body_get_shape,RID,int);
+ FUNC3(body_set_shape_as_trigger, RID, int, bool);
+ FUNC2RC(bool, body_is_shape_set_as_trigger, RID, int);
- FUNC3(body_set_shape_as_trigger,RID,int,bool);
- FUNC2RC(bool,body_is_shape_set_as_trigger,RID,int);
+ FUNC2(body_remove_shape, RID, int);
+ FUNC1(body_clear_shapes, RID);
- FUNC2(body_remove_shape,RID,int);
- FUNC1(body_clear_shapes,RID);
+ FUNC2(body_attach_object_instance_ID, RID, uint32_t);
+ FUNC1RC(uint32_t, body_get_object_instance_ID, RID);
- FUNC2(body_attach_object_instance_ID,RID,uint32_t);
- FUNC1RC(uint32_t,body_get_object_instance_ID,RID);
+ FUNC2(body_set_continuous_collision_detection_mode, RID, CCDMode);
+ FUNC1RC(CCDMode, body_get_continuous_collision_detection_mode, RID);
- FUNC2(body_set_continuous_collision_detection_mode,RID,CCDMode);
- FUNC1RC(CCDMode,body_get_continuous_collision_detection_mode,RID);
+ FUNC2(body_set_layer_mask, RID, uint32_t);
+ FUNC1RC(uint32_t, body_get_layer_mask, RID);
- FUNC2(body_set_layer_mask,RID,uint32_t);
- FUNC1RC(uint32_t,body_get_layer_mask,RID);
+ FUNC2(body_set_collision_mask, RID, uint32_t);
+ FUNC1RC(uint32_t, body_get_collision_mask, RID);
- FUNC2(body_set_collision_mask,RID,uint32_t);
- FUNC1RC(uint32_t,body_get_collision_mask,RID);
+ FUNC3(body_set_param, RID, BodyParameter, real_t);
+ FUNC2RC(real_t, body_get_param, RID, BodyParameter);
+ FUNC3(body_set_state, RID, BodyState, const Variant &);
+ FUNC2RC(Variant, body_get_state, RID, BodyState);
- FUNC3(body_set_param,RID,BodyParameter,real_t);
- FUNC2RC(real_t,body_get_param,RID,BodyParameter);
+ FUNC2(body_set_applied_force, RID, const Vector2 &);
+ FUNC1RC(Vector2, body_get_applied_force, RID);
+ FUNC2(body_set_applied_torque, RID, real_t);
+ FUNC1RC(real_t, body_get_applied_torque, RID);
- FUNC3(body_set_state,RID,BodyState,const Variant&);
- FUNC2RC(Variant,body_get_state,RID,BodyState);
+ FUNC3(body_add_force, RID, const Vector2 &, const Vector2 &);
+ FUNC3(body_apply_impulse, RID, const Vector2 &, const Vector2 &);
+ FUNC2(body_set_axis_velocity, RID, const Vector2 &);
- FUNC2(body_set_applied_force,RID,const Vector2&);
- FUNC1RC(Vector2,body_get_applied_force,RID);
+ FUNC2(body_add_collision_exception, RID, RID);
+ FUNC2(body_remove_collision_exception, RID, RID);
+ FUNC2S(body_get_collision_exceptions, RID, List<RID> *);
- FUNC2(body_set_applied_torque,RID,real_t);
- FUNC1RC(real_t,body_get_applied_torque,RID);
+ FUNC2(body_set_max_contacts_reported, RID, int);
+ FUNC1RC(int, body_get_max_contacts_reported, RID);
- FUNC3(body_add_force,RID,const Vector2&,const Vector2&);
- FUNC3(body_apply_impulse,RID,const Vector2&,const Vector2&);
- FUNC2(body_set_axis_velocity,RID,const Vector2&);
+ FUNC2(body_set_one_way_collision_direction, RID, const Vector2 &);
+ FUNC1RC(Vector2, body_get_one_way_collision_direction, RID);
- FUNC2(body_add_collision_exception,RID,RID);
- FUNC2(body_remove_collision_exception,RID,RID);
- FUNC2S(body_get_collision_exceptions,RID,List<RID>*);
+ FUNC2(body_set_one_way_collision_max_depth, RID, real_t);
+ FUNC1RC(real_t, body_get_one_way_collision_max_depth, RID);
- FUNC2(body_set_max_contacts_reported,RID,int);
- FUNC1RC(int,body_get_max_contacts_reported,RID);
+ FUNC2(body_set_contacts_reported_depth_treshold, RID, real_t);
+ FUNC1RC(real_t, body_get_contacts_reported_depth_treshold, RID);
- FUNC2(body_set_one_way_collision_direction,RID,const Vector2&);
- FUNC1RC(Vector2,body_get_one_way_collision_direction,RID);
+ FUNC2(body_set_omit_force_integration, RID, bool);
+ FUNC1RC(bool, body_is_omitting_force_integration, RID);
- FUNC2(body_set_one_way_collision_max_depth,RID,real_t);
- FUNC1RC(real_t,body_get_one_way_collision_max_depth,RID);
+ FUNC4(body_set_force_integration_callback, RID, Object *, const StringName &, const Variant &);
-
- FUNC2(body_set_contacts_reported_depth_treshold,RID,real_t);
- FUNC1RC(real_t,body_get_contacts_reported_depth_treshold,RID);
-
- FUNC2(body_set_omit_force_integration,RID,bool);
- FUNC1RC(bool,body_is_omitting_force_integration,RID);
-
- FUNC4(body_set_force_integration_callback,RID ,Object *,const StringName& ,const Variant& );
-
-
- bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count) {
- return physics_2d_server->body_collide_shape(p_body,p_body_shape,p_shape,p_shape_xform,p_motion,r_results,p_result_max,r_result_count);
+ bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) {
+ return physics_2d_server->body_collide_shape(p_body, p_body_shape, p_shape, p_shape_xform, p_motion, r_results, p_result_max, r_result_count);
}
- FUNC2(body_set_pickable,RID,bool);
+ FUNC2(body_set_pickable, RID, bool);
- bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,real_t p_margin=0.001,MotionResult *r_result=NULL) {
+ bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin = 0.001, MotionResult *r_result = NULL) {
- ERR_FAIL_COND_V(main_thread!=Thread::get_caller_ID(),false);
- return physics_2d_server->body_test_motion(p_body,p_from,p_motion,p_margin,r_result);
+ ERR_FAIL_COND_V(main_thread != Thread::get_caller_ID(), false);
+ return physics_2d_server->body_test_motion(p_body, p_from, p_motion, p_margin, r_result);
}
/* JOINT API */
-
- FUNC3(joint_set_param,RID,JointParam,real_t);
- FUNC2RC(real_t,joint_get_param,RID,JointParam);
-
+ FUNC3(joint_set_param, RID, JointParam, real_t);
+ FUNC2RC(real_t, joint_get_param, RID, JointParam);
///FUNC3RID(pin_joint,const Vector2&,RID,RID);
///FUNC5RID(groove_joint,const Vector2&,const Vector2&,const Vector2&,RID,RID);
///FUNC4RID(damped_spring_joint,const Vector2&,const Vector2&,RID,RID);
- FUNC3R(RID,pin_joint_create,const Vector2&,RID,RID);
- FUNC5R(RID,groove_joint_create,const Vector2&,const Vector2&,const Vector2&,RID,RID);
- FUNC4R(RID,damped_spring_joint_create,const Vector2&,const Vector2&,RID,RID);
+ FUNC3R(RID, pin_joint_create, const Vector2 &, RID, RID);
+ FUNC5R(RID, groove_joint_create, const Vector2 &, const Vector2 &, const Vector2 &, RID, RID);
+ FUNC4R(RID, damped_spring_joint_create, const Vector2 &, const Vector2 &, RID, RID);
- FUNC3(pin_joint_set_param,RID,PinJointParam,real_t);
- FUNC2RC(real_t,pin_joint_get_param,RID,PinJointParam);
+ FUNC3(pin_joint_set_param, RID, PinJointParam, real_t);
+ FUNC2RC(real_t, pin_joint_get_param, RID, PinJointParam);
- FUNC3(damped_string_joint_set_param,RID,DampedStringParam,real_t);
- FUNC2RC(real_t,damped_string_joint_get_param,RID,DampedStringParam);
-
- FUNC1RC(JointType,joint_get_type,RID);
+ FUNC3(damped_string_joint_set_param, RID, DampedStringParam, real_t);
+ FUNC2RC(real_t, damped_string_joint_get_param, RID, DampedStringParam);
+ FUNC1RC(JointType, joint_get_type, RID);
/* MISC */
-
- FUNC1(free,RID);
- FUNC1(set_active,bool);
+ FUNC1(free, RID);
+ FUNC1(set_active, bool);
virtual void init();
virtual void step(real_t p_step);
@@ -313,28 +294,24 @@ public:
return physics_2d_server->get_process_info(p_info);
}
- Physics2DServerWrapMT(Physics2DServer* p_contained,bool p_create_thread);
+ Physics2DServerWrapMT(Physics2DServer *p_contained, bool p_create_thread);
~Physics2DServerWrapMT();
+ template <class T>
+ static Physics2DServer *init_server() {
- template<class T>
- static Physics2DServer* init_server() {
-
- int tm = GLOBAL_DEF("physics/2d/thread_model",1);
- if (tm==0) //single unsafe
- return memnew( T );
- else if (tm==1) //single saef
- return memnew( Physics2DServerWrapMT( memnew( T ), false ));
+ int tm = GLOBAL_DEF("physics/2d/thread_model", 1);
+ if (tm == 0) //single unsafe
+ return memnew(T);
+ else if (tm == 1) //single saef
+ return memnew(Physics2DServerWrapMT(memnew(T), false));
else //single unsafe
- return memnew( Physics2DServerWrapMT( memnew( T ), true ));
-
-
+ return memnew(Physics2DServerWrapMT(memnew(T), true));
}
#undef ServerNameWrapMT
#undef ServerName
#undef server_name
-
};
#ifdef DEBUG_SYNC
diff --git a/servers/physics_2d/shape_2d_sw.cpp b/servers/physics_2d/shape_2d_sw.cpp
index b6eb427131..32d632453a 100644
--- a/servers/physics_2d/shape_2d_sw.cpp
+++ b/servers/physics_2d/shape_2d_sw.cpp
@@ -30,108 +30,98 @@
#include "geometry.h"
#include "sort.h"
-
-
-void Shape2DSW::configure(const Rect2& p_aabb) {
- aabb=p_aabb;
- configured=true;
- for (Map<ShapeOwner2DSW*,int>::Element *E=owners.front();E;E=E->next()) {
- ShapeOwner2DSW* co=(ShapeOwner2DSW*)E->key();
+void Shape2DSW::configure(const Rect2 &p_aabb) {
+ aabb = p_aabb;
+ configured = true;
+ for (Map<ShapeOwner2DSW *, int>::Element *E = owners.front(); E; E = E->next()) {
+ ShapeOwner2DSW *co = (ShapeOwner2DSW *)E->key();
co->_shape_changed();
}
}
-
-Vector2 Shape2DSW::get_support(const Vector2& p_normal) const {
+Vector2 Shape2DSW::get_support(const Vector2 &p_normal) const {
Vector2 res[2];
int amnt;
- get_supports(p_normal,res,amnt);
+ get_supports(p_normal, res, amnt);
return res[0];
}
void Shape2DSW::add_owner(ShapeOwner2DSW *p_owner) {
- Map<ShapeOwner2DSW*,int>::Element *E=owners.find(p_owner);
+ Map<ShapeOwner2DSW *, int>::Element *E = owners.find(p_owner);
if (E) {
E->get()++;
} else {
- owners[p_owner]=1;
+ owners[p_owner] = 1;
}
}
-void Shape2DSW::remove_owner(ShapeOwner2DSW *p_owner){
+void Shape2DSW::remove_owner(ShapeOwner2DSW *p_owner) {
- Map<ShapeOwner2DSW*,int>::Element *E=owners.find(p_owner);
+ Map<ShapeOwner2DSW *, int>::Element *E = owners.find(p_owner);
ERR_FAIL_COND(!E);
E->get()--;
- if (E->get()==0) {
+ if (E->get() == 0) {
owners.erase(E);
}
-
}
-bool Shape2DSW::is_owner(ShapeOwner2DSW *p_owner) const{
+bool Shape2DSW::is_owner(ShapeOwner2DSW *p_owner) const {
return owners.has(p_owner);
-
}
-const Map<ShapeOwner2DSW*,int>& Shape2DSW::get_owners() const{
+const Map<ShapeOwner2DSW *, int> &Shape2DSW::get_owners() const {
return owners;
}
-
Shape2DSW::Shape2DSW() {
- custom_bias=0;
- configured=false;
+ custom_bias = 0;
+ configured = false;
}
-
Shape2DSW::~Shape2DSW() {
ERR_FAIL_COND(owners.size());
}
-
/*********************************************************/
/*********************************************************/
/*********************************************************/
+void LineShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-
-void LineShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- r_amount=0;
+ r_amount = 0;
}
-bool LineShape2DSW::contains_point(const Vector2& p_point) const {
+bool LineShape2DSW::contains_point(const Vector2 &p_point) const {
return normal.dot(p_point) < d;
}
-bool LineShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
+bool LineShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
- Vector2 segment= p_begin - p_end;
- real_t den=normal.dot( segment );
+ Vector2 segment = p_begin - p_end;
+ real_t den = normal.dot(segment);
//printf("den is %i\n",den);
- if (Math::abs(den)<=CMP_EPSILON) {
+ if (Math::abs(den) <= CMP_EPSILON) {
return false;
}
- real_t dist=(normal.dot( p_begin ) - d) / den;
+ real_t dist = (normal.dot(p_begin) - d) / den;
//printf("dist is %i\n",dist);
- if (dist<-CMP_EPSILON || dist > (1.0 +CMP_EPSILON)) {
+ if (dist < -CMP_EPSILON || dist > (1.0 + CMP_EPSILON)) {
return false;
}
r_point = p_begin + segment * -dist;
- r_normal=normal;
+ r_normal = normal;
return true;
}
@@ -141,24 +131,22 @@ real_t LineShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale)
return 0;
}
+void LineShape2DSW::set_data(const Variant &p_data) {
-void LineShape2DSW::set_data(const Variant& p_data) {
-
- ERR_FAIL_COND(p_data.get_type()!=Variant::ARRAY);
+ ERR_FAIL_COND(p_data.get_type() != Variant::ARRAY);
Array arr = p_data;
- ERR_FAIL_COND(arr.size()!=2);
- normal=arr[0];
- d=arr[1];
- configure(Rect2(Vector2(-1e4,-1e4),Vector2(1e4*2,1e4*2)));
-
+ ERR_FAIL_COND(arr.size() != 2);
+ normal = arr[0];
+ d = arr[1];
+ configure(Rect2(Vector2(-1e4, -1e4), Vector2(1e4 * 2, 1e4 * 2)));
}
Variant LineShape2DSW::get_data() const {
Array arr;
arr.resize(2);
- arr[0]=normal;
- arr[1]=d;
+ arr[0] = normal;
+ arr[1] = d;
return arr;
}
@@ -166,29 +154,24 @@ Variant LineShape2DSW::get_data() const {
/*********************************************************/
/*********************************************************/
+void RayShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
+ r_amount = 1;
-void RayShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
-
- r_amount=1;
-
- if (p_normal.y>0)
- *r_supports=Vector2(0,length);
+ if (p_normal.y > 0)
+ *r_supports = Vector2(0, length);
else
- *r_supports=Vector2();
-
+ *r_supports = Vector2();
}
-bool RayShape2DSW::contains_point(const Vector2& p_point) const {
+bool RayShape2DSW::contains_point(const Vector2 &p_point) const {
return false;
}
-bool RayShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
+bool RayShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
return false; //rays can't be intersected
-
}
real_t RayShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
@@ -196,10 +179,10 @@ real_t RayShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale)
return 0; //rays are mass-less
}
-void RayShape2DSW::set_data(const Variant& p_data) {
+void RayShape2DSW::set_data(const Variant &p_data) {
- length=p_data;
- configure(Rect2(0,0,0.001,length));
+ length = p_data;
+ configure(Rect2(0, 0, 0.001, length));
}
Variant RayShape2DSW::get_data() const {
@@ -207,46 +190,41 @@ Variant RayShape2DSW::get_data() const {
return length;
}
-
/*********************************************************/
/*********************************************************/
/*********************************************************/
+void SegmentShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-
-void SegmentShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- if (Math::abs(p_normal.dot(n))>_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) {
- r_supports[0]=a;
- r_supports[1]=b;
- r_amount=2;
+ if (Math::abs(p_normal.dot(n)) > _SEGMENT_IS_VALID_SUPPORT_TRESHOLD) {
+ r_supports[0] = a;
+ r_supports[1] = b;
+ r_amount = 2;
return;
-
}
- real_t dp=p_normal.dot(b-a);
- if (dp>0)
- *r_supports=b;
+ real_t dp = p_normal.dot(b - a);
+ if (dp > 0)
+ *r_supports = b;
else
- *r_supports=a;
- r_amount=1;
-
+ *r_supports = a;
+ r_amount = 1;
}
-bool SegmentShape2DSW::contains_point(const Vector2& p_point) const {
+bool SegmentShape2DSW::contains_point(const Vector2 &p_point) const {
return false;
}
-bool SegmentShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
+bool SegmentShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
- if (!Geometry::segment_intersects_segment_2d(p_begin,p_end,a,b,&r_point))
+ if (!Geometry::segment_intersects_segment_2d(p_begin, p_end, a, b, &r_point))
return false;
if (n.dot(p_begin) > n.dot(a)) {
- r_normal=n;
+ r_normal = n;
} else {
- r_normal=-n;
+ r_normal = -n;
}
return true;
@@ -254,38 +232,38 @@ bool SegmentShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p
real_t SegmentShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
- Vector2 s[2]={a*p_scale,b*p_scale};
+ Vector2 s[2] = { a * p_scale, b * p_scale };
real_t l = s[1].distance_to(s[0]);
- Vector2 ofs = (s[0]+s[1])*0.5;
+ Vector2 ofs = (s[0] + s[1]) * 0.5;
- return p_mass*(l*l/12.0 + ofs.length_squared());
+ return p_mass * (l * l / 12.0 + ofs.length_squared());
}
-void SegmentShape2DSW::set_data(const Variant& p_data) {
+void SegmentShape2DSW::set_data(const Variant &p_data) {
- ERR_FAIL_COND(p_data.get_type()!=Variant::RECT2);
+ ERR_FAIL_COND(p_data.get_type() != Variant::RECT2);
Rect2 r = p_data;
- a=r.pos;
- b=r.size;
- n=(b-a).tangent();
+ a = r.pos;
+ b = r.size;
+ n = (b - a).tangent();
Rect2 aabb;
- aabb.pos=a;
+ aabb.pos = a;
aabb.expand_to(b);
- if (aabb.size.x==0)
- aabb.size.x=0.001;
- if (aabb.size.y==0)
- aabb.size.y=0.001;
+ if (aabb.size.x == 0)
+ aabb.size.x = 0.001;
+ if (aabb.size.y == 0)
+ aabb.size.y = 0.001;
configure(aabb);
}
Variant SegmentShape2DSW::get_data() const {
Rect2 r;
- r.pos=a;
- r.size=b;
+ r.pos = a;
+ r.size = b;
return r;
}
@@ -293,24 +271,18 @@ Variant SegmentShape2DSW::get_data() const {
/*********************************************************/
/*********************************************************/
+void CircleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-
-void CircleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- r_amount=1;
- *r_supports=p_normal*radius;
-
+ r_amount = 1;
+ *r_supports = p_normal * radius;
}
+bool CircleShape2DSW::contains_point(const Vector2 &p_point) const {
-bool CircleShape2DSW::contains_point(const Vector2& p_point) const {
-
- return p_point.length_squared() < radius*radius;
+ return p_point.length_squared() < radius * radius;
}
-
-bool CircleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
-
+bool CircleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
Vector2 line_vec = p_end - p_begin;
@@ -320,33 +292,32 @@ bool CircleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_
b = 2 * p_begin.dot(line_vec);
c = p_begin.dot(p_begin) - radius * radius;
- real_t sqrtterm = b*b - 4*a*c;
+ real_t sqrtterm = b * b - 4 * a * c;
- if(sqrtterm < 0)
+ if (sqrtterm < 0)
return false;
sqrtterm = Math::sqrt(sqrtterm);
- real_t res = ( -b - sqrtterm ) / (2 * a);
+ real_t res = (-b - sqrtterm) / (2 * a);
- if (res <0 || res >1+CMP_EPSILON) {
+ if (res < 0 || res > 1 + CMP_EPSILON) {
return false;
}
- r_point=p_begin+line_vec*res;
- r_normal=r_point.normalized();
+ r_point = p_begin + line_vec * res;
+ r_normal = r_point.normalized();
return true;
}
real_t CircleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
- return (radius*radius)*(p_scale.x*0.5+p_scale.y*0.5);
-
+ return (radius * radius) * (p_scale.x * 0.5 + p_scale.y * 0.5);
}
-void CircleShape2DSW::set_data(const Variant& p_data) {
+void CircleShape2DSW::set_data(const Variant &p_data) {
ERR_FAIL_COND(!p_data.is_num());
- radius=p_data;
- configure(Rect2(-radius,-radius,radius*2,radius*2));
+ radius = p_data;
+ configure(Rect2(-radius, -radius, radius * 2, radius * 2));
}
Variant CircleShape2DSW::get_data() const {
@@ -354,71 +325,63 @@ Variant CircleShape2DSW::get_data() const {
return radius;
}
-
/*********************************************************/
/*********************************************************/
/*********************************************************/
+void RectangleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-
-void RectangleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
Vector2 ag;
- ag[i]=1.0;
+ ag[i] = 1.0;
real_t dp = ag.dot(p_normal);
- if (Math::abs(dp)<_SEGMENT_IS_VALID_SUPPORT_TRESHOLD)
+ if (Math::abs(dp) < _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)
continue;
- real_t sgn = dp>0 ? 1.0 : -1.0;
+ real_t sgn = dp > 0 ? 1.0 : -1.0;
- r_amount=2;
+ r_amount = 2;
- r_supports[0][i]=half_extents[i]*sgn;
- r_supports[0][i^1]=half_extents[i^1];
+ r_supports[0][i] = half_extents[i] * sgn;
+ r_supports[0][i ^ 1] = half_extents[i ^ 1];
- r_supports[1][i]=half_extents[i]*sgn;
- r_supports[1][i^1]=-half_extents[i^1];
+ r_supports[1][i] = half_extents[i] * sgn;
+ r_supports[1][i ^ 1] = -half_extents[i ^ 1];
return;
-
-
}
/* USE POINT */
- r_amount=1;
- r_supports[0]=Vector2(
- (p_normal.x<0) ? -half_extents.x : half_extents.x,
- (p_normal.y<0) ? -half_extents.y : half_extents.y
- );
-
+ r_amount = 1;
+ r_supports[0] = Vector2(
+ (p_normal.x < 0) ? -half_extents.x : half_extents.x,
+ (p_normal.y < 0) ? -half_extents.y : half_extents.y);
}
-bool RectangleShape2DSW::contains_point(const Vector2& p_point) const {
+bool RectangleShape2DSW::contains_point(const Vector2 &p_point) const {
- return Math::abs(p_point.x)<half_extents.x && Math::abs(p_point.y)<half_extents.y;
+ return Math::abs(p_point.x) < half_extents.x && Math::abs(p_point.y) < half_extents.y;
}
-bool RectangleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
-
+bool RectangleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
- return get_aabb().intersects_segment(p_begin,p_end,&r_point,&r_normal);
+ return get_aabb().intersects_segment(p_begin, p_end, &r_point, &r_normal);
}
-real_t RectangleShape2DSW::get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const {
+real_t RectangleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
- Vector2 he2=half_extents*2*p_scale;
- return p_mass*he2.dot(he2)/12.0;
+ Vector2 he2 = half_extents * 2 * p_scale;
+ return p_mass * he2.dot(he2) / 12.0;
}
-void RectangleShape2DSW::set_data(const Variant& p_data) {
+void RectangleShape2DSW::set_data(const Variant &p_data) {
- ERR_FAIL_COND(p_data.get_type()!=Variant::VECTOR2);
+ ERR_FAIL_COND(p_data.get_type() != Variant::VECTOR2);
- half_extents=p_data;
- configure(Rect2(-half_extents,half_extents*2.0));
+ half_extents = p_data;
+ configure(Rect2(-half_extents, half_extents * 2.0));
}
Variant RectangleShape2DSW::get_data() const {
@@ -426,71 +389,65 @@ Variant RectangleShape2DSW::get_data() const {
return half_extents;
}
-
-
/*********************************************************/
/*********************************************************/
/*********************************************************/
+void CapsuleShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-
-void CapsuleShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- Vector2 n=p_normal;
+ Vector2 n = p_normal;
real_t d = n.y;
- if (Math::abs( d )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) {
+ if (Math::abs(d) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) {
// make it flat
- n.y=0.0;
+ n.y = 0.0;
n.normalize();
- n*=radius;
+ n *= radius;
- r_amount=2;
- r_supports[0]=n;
- r_supports[0].y+=height*0.5;
- r_supports[1]=n;
- r_supports[1].y-=height*0.5;
+ r_amount = 2;
+ r_supports[0] = n;
+ r_supports[0].y += height * 0.5;
+ r_supports[1] = n;
+ r_supports[1].y -= height * 0.5;
} else {
real_t h = (d > 0) ? height : -height;
- n*=radius;
- n.y += h*0.5;
- r_amount=1;
- *r_supports=n;
-
+ n *= radius;
+ n.y += h * 0.5;
+ r_amount = 1;
+ *r_supports = n;
}
}
-bool CapsuleShape2DSW::contains_point(const Vector2& p_point) const {
+bool CapsuleShape2DSW::contains_point(const Vector2 &p_point) const {
Vector2 p = p_point;
- p.y=Math::abs(p.y);
- p.y-=height*0.5;
- if (p.y<0)
- p.y=0;
+ p.y = Math::abs(p.y);
+ p.y -= height * 0.5;
+ if (p.y < 0)
+ p.y = 0;
- return p.length_squared() < radius*radius;
+ return p.length_squared() < radius * radius;
}
-bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
-
+bool CapsuleShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
real_t d = 1e10;
- Vector2 n = (p_end-p_begin).normalized();
- bool collided=false;
+ Vector2 n = (p_end - p_begin).normalized();
+ bool collided = false;
//try spheres
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
Vector2 begin = p_begin;
Vector2 end = p_end;
- real_t ofs = (i==0)?-height*0.5:height*0.5;
- begin.y+=ofs;
- end.y+=ofs;
+ real_t ofs = (i == 0) ? -height * 0.5 : height * 0.5;
+ begin.y += ofs;
+ end.y += ofs;
Vector2 line_vec = end - begin;
@@ -500,39 +457,38 @@ bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p
b = 2 * begin.dot(line_vec);
c = begin.dot(begin) - radius * radius;
- real_t sqrtterm = b*b - 4*a*c;
+ real_t sqrtterm = b * b - 4 * a * c;
- if(sqrtterm < 0)
+ if (sqrtterm < 0)
continue;
sqrtterm = Math::sqrt(sqrtterm);
- real_t res = ( -b - sqrtterm ) / (2 * a);
+ real_t res = (-b - sqrtterm) / (2 * a);
- if (res <0 || res >1+CMP_EPSILON) {
+ if (res < 0 || res > 1 + CMP_EPSILON) {
continue;
}
- Vector2 point = begin+line_vec*res;
- Vector2 pointf(point.x,point.y-ofs);
+ Vector2 point = begin + line_vec * res;
+ Vector2 pointf(point.x, point.y - ofs);
real_t pd = n.dot(pointf);
- if (pd<d) {
- r_point=pointf;
- r_normal=point.normalized();
- d=pd;
- collided=true;
+ if (pd < d) {
+ r_point = pointf;
+ r_normal = point.normalized();
+ d = pd;
+ collided = true;
}
}
-
- Vector2 rpos,rnorm;
- if (Rect2( Point2(-radius,-height*0.5), Size2(radius*2.0,height) ).intersects_segment(p_begin,p_end,&rpos,&rnorm)) {
+ Vector2 rpos, rnorm;
+ if (Rect2(Point2(-radius, -height * 0.5), Size2(radius * 2.0, height)).intersects_segment(p_begin, p_end, &rpos, &rnorm)) {
real_t pd = n.dot(rpos);
- if (pd<d) {
- r_point=rpos;
- r_normal=rnorm;
- d=pd;
- collided=true;
+ if (pd < d) {
+ r_point = rpos;
+ r_normal = rnorm;
+ d = pd;
+ collided = true;
}
}
@@ -542,101 +498,93 @@ bool CapsuleShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p
real_t CapsuleShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
- Vector2 he2=Vector2(radius*2,height+radius*2)*p_scale;
- return p_mass*he2.dot(he2)/12.0;
+ Vector2 he2 = Vector2(radius * 2, height + radius * 2) * p_scale;
+ return p_mass * he2.dot(he2) / 12.0;
}
-void CapsuleShape2DSW::set_data(const Variant& p_data) {
+void CapsuleShape2DSW::set_data(const Variant &p_data) {
- ERR_FAIL_COND(p_data.get_type()!=Variant::ARRAY && p_data.get_type()!=Variant::VECTOR2);
+ ERR_FAIL_COND(p_data.get_type() != Variant::ARRAY && p_data.get_type() != Variant::VECTOR2);
- if (p_data.get_type()==Variant::ARRAY) {
- Array arr=p_data;
- ERR_FAIL_COND(arr.size()!=2);
- height=arr[0];
- radius=arr[1];
+ if (p_data.get_type() == Variant::ARRAY) {
+ Array arr = p_data;
+ ERR_FAIL_COND(arr.size() != 2);
+ height = arr[0];
+ radius = arr[1];
} else {
Point2 p = p_data;
- radius=p.x;
- height=p.y;
+ radius = p.x;
+ height = p.y;
}
- Point2 he(radius,height*0.5+radius);
- configure(Rect2(-he,he*2));
-
+ Point2 he(radius, height * 0.5 + radius);
+ configure(Rect2(-he, he * 2));
}
Variant CapsuleShape2DSW::get_data() const {
- return Point2(height,radius);
+ return Point2(height, radius);
}
-
-
/*********************************************************/
/*********************************************************/
/*********************************************************/
+void ConvexPolygonShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
+ int support_idx = -1;
+ real_t d = -1e10;
-void ConvexPolygonShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- int support_idx=-1;
- real_t d=-1e10;
-
- for(int i=0;i<point_count;i++) {
+ for (int i = 0; i < point_count; i++) {
//test point
real_t ld = p_normal.dot(points[i].pos);
- if (ld>d) {
- support_idx=i;
- d=ld;
+ if (ld > d) {
+ support_idx = i;
+ d = ld;
}
//test segment
- if (points[i].normal.dot(p_normal)>_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) {
+ if (points[i].normal.dot(p_normal) > _SEGMENT_IS_VALID_SUPPORT_TRESHOLD) {
- r_amount=2;
- r_supports[0]=points[i].pos;
- r_supports[1]=points[(i+1)%point_count].pos;
+ r_amount = 2;
+ r_supports[0] = points[i].pos;
+ r_supports[1] = points[(i + 1) % point_count].pos;
return;
}
}
- ERR_FAIL_COND(support_idx==-1);
-
- r_amount=1;
- r_supports[0]=points[support_idx].pos;
+ ERR_FAIL_COND(support_idx == -1);
+ r_amount = 1;
+ r_supports[0] = points[support_idx].pos;
}
+bool ConvexPolygonShape2DSW::contains_point(const Vector2 &p_point) const {
-bool ConvexPolygonShape2DSW::contains_point(const Vector2& p_point) const {
-
- bool out=false;
- bool in=false;
+ bool out = false;
+ bool in = false;
- for(int i=0;i<point_count;i++) {
+ for (int i = 0; i < point_count; i++) {
real_t d = points[i].normal.dot(p_point) - points[i].normal.dot(points[i].pos);
- if (d>0)
- out=true;
+ if (d > 0)
+ out = true;
else
- in=true;
+ in = true;
}
return (in && !out) || (!in && out);
}
+bool ConvexPolygonShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
-bool ConvexPolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const {
-
- Vector2 n = (p_end-p_begin).normalized();
- real_t d=1e10;
- bool inters=false;
+ Vector2 n = (p_end - p_begin).normalized();
+ real_t d = 1e10;
+ bool inters = false;
- for(int i=0;i<point_count;i++) {
+ for (int i = 0; i < point_count; i++) {
//hmm crap.. no can do..
/*
@@ -644,98 +592,92 @@ bool ConvexPolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vect
continue;
*/
-
Vector2 res;
- if (!Geometry::segment_intersects_segment_2d(p_begin,p_end,points[i].pos,points[(i+1)%point_count].pos,&res))
+ if (!Geometry::segment_intersects_segment_2d(p_begin, p_end, points[i].pos, points[(i + 1) % point_count].pos, &res))
continue;
real_t nd = n.dot(res);
- if (nd<d) {
+ if (nd < d) {
- d=nd;
- r_point=res;
- r_normal=points[i].normal;
- inters=true;
+ d = nd;
+ r_point = res;
+ r_normal = points[i].normal;
+ inters = true;
}
-
}
-
if (inters) {
- if (n.dot(r_normal)>0)
- r_normal=-r_normal;
+ if (n.dot(r_normal) > 0)
+ r_normal = -r_normal;
}
//return get_aabb().intersects_segment(p_begin,p_end,&r_point,&r_normal);
return inters; //todo
}
-real_t ConvexPolygonShape2DSW::get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const {
+real_t ConvexPolygonShape2DSW::get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const {
Rect2 aabb;
- aabb.pos=points[0].pos*p_scale;
- for(int i=0;i<point_count;i++) {
+ aabb.pos = points[0].pos * p_scale;
+ for (int i = 0; i < point_count; i++) {
- aabb.expand_to(points[i].pos*p_scale);
+ aabb.expand_to(points[i].pos * p_scale);
}
- return p_mass*aabb.size.dot(aabb.size)/12.0 + p_mass * (aabb.pos+aabb.size*0.5).length_squared();
+ return p_mass * aabb.size.dot(aabb.size) / 12.0 + p_mass * (aabb.pos + aabb.size * 0.5).length_squared();
}
-void ConvexPolygonShape2DSW::set_data(const Variant& p_data) {
-
- ERR_FAIL_COND(p_data.get_type()!=Variant::POOL_VECTOR2_ARRAY && p_data.get_type()!=Variant::POOL_REAL_ARRAY);
+void ConvexPolygonShape2DSW::set_data(const Variant &p_data) {
+ ERR_FAIL_COND(p_data.get_type() != Variant::POOL_VECTOR2_ARRAY && p_data.get_type() != Variant::POOL_REAL_ARRAY);
if (points)
memdelete_arr(points);
- points=NULL;
- point_count=0;
-
- if (p_data.get_type()==Variant::POOL_VECTOR2_ARRAY) {
- PoolVector<Vector2> arr=p_data;
- ERR_FAIL_COND(arr.size()==0);
- point_count=arr.size();
- points = memnew_arr(Point,point_count);
+ points = NULL;
+ point_count = 0;
+
+ if (p_data.get_type() == Variant::POOL_VECTOR2_ARRAY) {
+ PoolVector<Vector2> arr = p_data;
+ ERR_FAIL_COND(arr.size() == 0);
+ point_count = arr.size();
+ points = memnew_arr(Point, point_count);
PoolVector<Vector2>::Read r = arr.read();
- for(int i=0;i<point_count;i++) {
- points[i].pos=r[i];
+ for (int i = 0; i < point_count; i++) {
+ points[i].pos = r[i];
}
- for(int i=0;i<point_count;i++) {
+ for (int i = 0; i < point_count; i++) {
Vector2 p = points[i].pos;
- Vector2 pn = points[(i+1)%point_count].pos;
- points[i].normal=(pn-p).tangent().normalized();
+ Vector2 pn = points[(i + 1) % point_count].pos;
+ points[i].normal = (pn - p).tangent().normalized();
}
} else {
PoolVector<real_t> dvr = p_data;
- point_count=dvr.size()/4;
- ERR_FAIL_COND(point_count==0);
+ point_count = dvr.size() / 4;
+ ERR_FAIL_COND(point_count == 0);
- points = memnew_arr(Point,point_count);
+ points = memnew_arr(Point, point_count);
PoolVector<real_t>::Read r = dvr.read();
- for(int i=0;i<point_count;i++) {
-
- int idx=i<<2;
- points[i].pos.x=r[idx+0];
- points[i].pos.y=r[idx+1];
- points[i].normal.x=r[idx+2];
- points[i].normal.y=r[idx+3];
+ for (int i = 0; i < point_count; i++) {
+ int idx = i << 2;
+ points[i].pos.x = r[idx + 0];
+ points[i].pos.y = r[idx + 1];
+ points[i].normal.x = r[idx + 2];
+ points[i].normal.y = r[idx + 3];
}
}
-
- ERR_FAIL_COND(point_count==0);
+ ERR_FAIL_COND(point_count == 0);
Rect2 aabb;
- aabb.pos=points[0].pos;
- for(int i=1;i<point_count;i++)
+ aabb.pos = points[0].pos;
+ for (int i = 1; i < point_count; i++)
aabb.expand_to(points[i].pos);
configure(aabb);
@@ -747,337 +689,312 @@ Variant ConvexPolygonShape2DSW::get_data() const {
dvr.resize(point_count);
- for(int i=0;i<point_count;i++) {
- dvr.set(i,points[i].pos);
+ for (int i = 0; i < point_count; i++) {
+ dvr.set(i, points[i].pos);
}
return dvr;
}
-
ConvexPolygonShape2DSW::ConvexPolygonShape2DSW() {
- points=NULL;
- point_count=0;
-
+ points = NULL;
+ point_count = 0;
}
-ConvexPolygonShape2DSW::~ConvexPolygonShape2DSW(){
+ConvexPolygonShape2DSW::~ConvexPolygonShape2DSW() {
if (points)
memdelete_arr(points);
-
}
//////////////////////////////////////////////////
+void ConcavePolygonShape2DSW::get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const {
-void ConcavePolygonShape2DSW::get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const {
-
- real_t d=-1e10;
- int idx=-1;
- for(int i=0;i<points.size();i++) {
+ real_t d = -1e10;
+ int idx = -1;
+ for (int i = 0; i < points.size(); i++) {
real_t ld = p_normal.dot(points[i]);
- if (ld>d) {
- d=ld;
- idx=i;
+ if (ld > d) {
+ d = ld;
+ idx = i;
}
}
-
- r_amount=1;
- ERR_FAIL_COND(idx==-1);
- *r_supports=points[idx];
-
+ r_amount = 1;
+ ERR_FAIL_COND(idx == -1);
+ *r_supports = points[idx];
}
-bool ConcavePolygonShape2DSW::contains_point(const Vector2& p_point) const {
+bool ConcavePolygonShape2DSW::contains_point(const Vector2 &p_point) const {
return false; //sorry
}
+bool ConcavePolygonShape2DSW::intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const {
-bool ConcavePolygonShape2DSW::intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const{
-
- uint32_t* stack = (uint32_t*)alloca(sizeof(int)*bvh_depth);
+ uint32_t *stack = (uint32_t *)alloca(sizeof(int) * bvh_depth);
enum {
- TEST_AABB_BIT=0,
- VISIT_LEFT_BIT=1,
- VISIT_RIGHT_BIT=2,
- VISIT_DONE_BIT=3,
- VISITED_BIT_SHIFT=29,
- NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1,
- VISITED_BIT_MASK=~NODE_IDX_MASK,
-
+ TEST_AABB_BIT = 0,
+ VISIT_LEFT_BIT = 1,
+ VISIT_RIGHT_BIT = 2,
+ VISIT_DONE_BIT = 3,
+ VISITED_BIT_SHIFT = 29,
+ NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
+ VISITED_BIT_MASK = ~NODE_IDX_MASK,
};
- Vector2 n = (p_end-p_begin).normalized();
- real_t d=1e10;
- bool inters=false;
+ Vector2 n = (p_end - p_begin).normalized();
+ real_t d = 1e10;
+ bool inters = false;
/*
for(int i=0;i<bvh_depth;i++)
stack[i]=0;
*/
- int level=0;
+ int level = 0;
- const Segment *segmentptr=&segments[0];
- const Vector2 *pointptr=&points[0];
+ const Segment *segmentptr = &segments[0];
+ const Vector2 *pointptr = &points[0];
const BVH *bvhptr = &bvh[0];
+ stack[0] = 0;
+ while (true) {
- stack[0]=0;
- while(true) {
-
- uint32_t node = stack[level]&NODE_IDX_MASK;
- const BVH &b = bvhptr[ node ];
- bool done=false;
+ uint32_t node = stack[level] & NODE_IDX_MASK;
+ const BVH &b = bvhptr[node];
+ bool done = false;
- switch(stack[level]>>VISITED_BIT_SHIFT) {
+ switch (stack[level] >> VISITED_BIT_SHIFT) {
case TEST_AABB_BIT: {
-
- bool valid = b.aabb.intersects_segment(p_begin,p_end);
+ bool valid = b.aabb.intersects_segment(p_begin, p_end);
if (!valid) {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- if (b.left<0) {
-
- const Segment &s=segmentptr[ b.right ];
- Vector2 a = pointptr[ s.points[0] ];
- Vector2 b = pointptr[ s.points[1] ];
+ if (b.left < 0) {
+ const Segment &s = segmentptr[b.right];
+ Vector2 a = pointptr[s.points[0]];
+ Vector2 b = pointptr[s.points[1]];
Vector2 res;
- if (Geometry::segment_intersects_segment_2d(p_begin,p_end,a,b,&res)) {
+ if (Geometry::segment_intersects_segment_2d(p_begin, p_end, a, b, &res)) {
real_t nd = n.dot(res);
- if (nd<d) {
+ if (nd < d) {
- d=nd;
- r_point=res;
- r_normal=(b-a).tangent().normalized();
- inters=true;
+ d = nd;
+ r_point = res;
+ r_normal = (b - a).tangent().normalized();
+ inters = true;
}
-
}
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
}
}
-
- } continue;
+ }
+ continue;
case VISIT_LEFT_BIT: {
- stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.left|TEST_AABB_BIT;
+ stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.left | TEST_AABB_BIT;
level++;
-
- } continue;
+ }
+ continue;
case VISIT_RIGHT_BIT: {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.right|TEST_AABB_BIT;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.right | TEST_AABB_BIT;
level++;
- } continue;
+ }
+ continue;
case VISIT_DONE_BIT: {
- if (level==0) {
- done=true;
+ if (level == 0) {
+ done = true;
break;
} else
level--;
-
- } continue;
+ }
+ continue;
}
-
if (done)
break;
}
-
if (inters) {
- if (n.dot(r_normal)>0)
- r_normal=-r_normal;
+ if (n.dot(r_normal) > 0)
+ r_normal = -r_normal;
}
return inters;
-
}
+int ConcavePolygonShape2DSW::_generate_bvh(BVH *p_bvh, int p_len, int p_depth) {
+ if (p_len == 1) {
-int ConcavePolygonShape2DSW::_generate_bvh(BVH *p_bvh,int p_len,int p_depth) {
-
- if (p_len==1) {
-
- bvh_depth=MAX(p_depth,bvh_depth);
+ bvh_depth = MAX(p_depth, bvh_depth);
bvh.push_back(*p_bvh);
- return bvh.size()-1;
+ return bvh.size() - 1;
}
//else sort best
- Rect2 global_aabb=p_bvh[0].aabb;
- for(int i=1;i<p_len;i++) {
- global_aabb=global_aabb.merge(p_bvh[i].aabb);
+ Rect2 global_aabb = p_bvh[0].aabb;
+ for (int i = 1; i < p_len; i++) {
+ global_aabb = global_aabb.merge(p_bvh[i].aabb);
}
if (global_aabb.size.x > global_aabb.size.y) {
- SortArray<BVH,BVH_CompareX> sort;
- sort.sort(p_bvh,p_len);
+ SortArray<BVH, BVH_CompareX> sort;
+ sort.sort(p_bvh, p_len);
} else {
- SortArray<BVH,BVH_CompareY> sort;
- sort.sort(p_bvh,p_len);
-
+ SortArray<BVH, BVH_CompareY> sort;
+ sort.sort(p_bvh, p_len);
}
- int median = p_len/2;
-
+ int median = p_len / 2;
BVH node;
- node.aabb=global_aabb;
+ node.aabb = global_aabb;
int node_idx = bvh.size();
bvh.push_back(node);
- int l = _generate_bvh(p_bvh,median,p_depth+1);
- int r = _generate_bvh(&p_bvh[median],p_len-median,p_depth+1);
- bvh[node_idx].left=l;
- bvh[node_idx].right=r;
+ int l = _generate_bvh(p_bvh, median, p_depth + 1);
+ int r = _generate_bvh(&p_bvh[median], p_len - median, p_depth + 1);
+ bvh[node_idx].left = l;
+ bvh[node_idx].right = r;
return node_idx;
-
}
-void ConcavePolygonShape2DSW::set_data(const Variant& p_data) {
+void ConcavePolygonShape2DSW::set_data(const Variant &p_data) {
- ERR_FAIL_COND(p_data.get_type()!=Variant::POOL_VECTOR2_ARRAY && p_data.get_type()!=Variant::POOL_REAL_ARRAY);
+ ERR_FAIL_COND(p_data.get_type() != Variant::POOL_VECTOR2_ARRAY && p_data.get_type() != Variant::POOL_REAL_ARRAY);
Rect2 aabb;
- if (p_data.get_type()==Variant::POOL_VECTOR2_ARRAY) {
+ if (p_data.get_type() == Variant::POOL_VECTOR2_ARRAY) {
PoolVector<Vector2> p2arr = p_data;
int len = p2arr.size();
- ERR_FAIL_COND(len%2);
+ ERR_FAIL_COND(len % 2);
segments.clear();
points.clear();
bvh.clear();
- bvh_depth=1;
+ bvh_depth = 1;
- if (len==0) {
+ if (len == 0) {
configure(aabb);
return;
}
PoolVector<Vector2>::Read arr = p2arr.read();
- Map<Point2,int> pointmap;
- for(int i=0;i<len;i+=2) {
+ Map<Point2, int> pointmap;
+ for (int i = 0; i < len; i += 2) {
- Point2 p1 =arr[i];
- Point2 p2 =arr[i+1];
- int idx_p1,idx_p2;
+ Point2 p1 = arr[i];
+ Point2 p2 = arr[i + 1];
+ int idx_p1, idx_p2;
if (pointmap.has(p1)) {
- idx_p1=pointmap[p1];
+ idx_p1 = pointmap[p1];
} else {
- idx_p1=pointmap.size();
- pointmap[p1]=idx_p1;
+ idx_p1 = pointmap.size();
+ pointmap[p1] = idx_p1;
}
if (pointmap.has(p2)) {
- idx_p2=pointmap[p2];
+ idx_p2 = pointmap[p2];
} else {
- idx_p2=pointmap.size();
- pointmap[p2]=idx_p2;
+ idx_p2 = pointmap.size();
+ pointmap[p2] = idx_p2;
}
Segment s;
- s.points[0]=idx_p1;
- s.points[1]=idx_p2;
+ s.points[0] = idx_p1;
+ s.points[1] = idx_p2;
segments.push_back(s);
}
points.resize(pointmap.size());
- aabb.pos=pointmap.front()->key();
- for(Map<Point2,int>::Element *E=pointmap.front();E;E=E->next()) {
+ aabb.pos = pointmap.front()->key();
+ for (Map<Point2, int>::Element *E = pointmap.front(); E; E = E->next()) {
aabb.expand_to(E->key());
- points[E->get()]=E->key();
+ points[E->get()] = E->key();
}
Vector<BVH> main_vbh;
main_vbh.resize(segments.size());
- for(int i=0;i<main_vbh.size();i++) {
+ for (int i = 0; i < main_vbh.size(); i++) {
-
- main_vbh[i].aabb.pos=points[segments[i].points[0]];
+ main_vbh[i].aabb.pos = points[segments[i].points[0]];
main_vbh[i].aabb.expand_to(points[segments[i].points[1]]);
- main_vbh[i].left=-1;
- main_vbh[i].right=i;
+ main_vbh[i].left = -1;
+ main_vbh[i].right = i;
}
- _generate_bvh(&main_vbh[0],main_vbh.size(),1);
-
+ _generate_bvh(&main_vbh[0], main_vbh.size(), 1);
} else {
//dictionary with arrays
-
}
-
configure(aabb);
}
Variant ConcavePolygonShape2DSW::get_data() const {
-
PoolVector<Vector2> rsegments;
int len = segments.size();
- rsegments.resize(len*2);
+ rsegments.resize(len * 2);
PoolVector<Vector2>::Write w = rsegments.write();
- for(int i=0;i<len;i++) {
+ for (int i = 0; i < len; i++) {
- w[(i<<1)+0]=points[segments[i].points[0]];
- w[(i<<1)+1]=points[segments[i].points[1]];
+ w[(i << 1) + 0] = points[segments[i].points[0]];
+ w[(i << 1) + 1] = points[segments[i].points[1]];
}
- w=PoolVector<Vector2>::Write();
+ w = PoolVector<Vector2>::Write();
return rsegments;
}
-void ConcavePolygonShape2DSW::cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const {
+void ConcavePolygonShape2DSW::cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const {
- uint32_t* stack = (uint32_t*)alloca(sizeof(int)*bvh_depth);
+ uint32_t *stack = (uint32_t *)alloca(sizeof(int) * bvh_depth);
enum {
- TEST_AABB_BIT=0,
- VISIT_LEFT_BIT=1,
- VISIT_RIGHT_BIT=2,
- VISIT_DONE_BIT=3,
- VISITED_BIT_SHIFT=29,
- NODE_IDX_MASK=(1<<VISITED_BIT_SHIFT)-1,
- VISITED_BIT_MASK=~NODE_IDX_MASK,
-
+ TEST_AABB_BIT = 0,
+ VISIT_LEFT_BIT = 1,
+ VISIT_RIGHT_BIT = 2,
+ VISIT_DONE_BIT = 3,
+ VISITED_BIT_SHIFT = 29,
+ NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
+ VISITED_BIT_MASK = ~NODE_IDX_MASK,
};
@@ -1086,73 +1003,68 @@ void ConcavePolygonShape2DSW::cull(const Rect2& p_local_aabb,Callback p_callback
stack[i]=0;
*/
+ int level = 0;
- int level=0;
-
- const Segment *segmentptr=&segments[0];
- const Vector2 *pointptr=&points[0];
+ const Segment *segmentptr = &segments[0];
+ const Vector2 *pointptr = &points[0];
const BVH *bvhptr = &bvh[0];
+ stack[0] = 0;
+ while (true) {
- stack[0]=0;
- while(true) {
-
- uint32_t node = stack[level]&NODE_IDX_MASK;
- const BVH &b = bvhptr[ node ];
+ uint32_t node = stack[level] & NODE_IDX_MASK;
+ const BVH &b = bvhptr[node];
- switch(stack[level]>>VISITED_BIT_SHIFT) {
+ switch (stack[level] >> VISITED_BIT_SHIFT) {
case TEST_AABB_BIT: {
-
bool valid = p_local_aabb.intersects(b.aabb);
if (!valid) {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- if (b.left<0) {
+ if (b.left < 0) {
- const Segment &s=segmentptr[ b.right ];
- Vector2 a = pointptr[ s.points[0] ];
- Vector2 b = pointptr[ s.points[1] ];
+ const Segment &s = segmentptr[b.right];
+ Vector2 a = pointptr[s.points[0]];
+ Vector2 b = pointptr[s.points[1]];
- SegmentShape2DSW ss(a,b,(b-a).tangent().normalized());
+ SegmentShape2DSW ss(a, b, (b - a).tangent().normalized());
- p_callback(p_userdata,&ss);
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
+ p_callback(p_userdata, &ss);
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
} else {
- stack[level]=(VISIT_LEFT_BIT<<VISITED_BIT_SHIFT)|node;
+ stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
}
}
-
- } continue;
+ }
+ continue;
case VISIT_LEFT_BIT: {
- stack[level]=(VISIT_RIGHT_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.left|TEST_AABB_BIT;
+ stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.left | TEST_AABB_BIT;
level++;
-
- } continue;
+ }
+ continue;
case VISIT_RIGHT_BIT: {
- stack[level]=(VISIT_DONE_BIT<<VISITED_BIT_SHIFT)|node;
- stack[level+1]=b.right|TEST_AABB_BIT;
+ stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
+ stack[level + 1] = b.right | TEST_AABB_BIT;
level++;
- } continue;
+ }
+ continue;
case VISIT_DONE_BIT: {
- if (level==0)
+ if (level == 0)
return;
else
level--;
-
- } continue;
+ }
+ continue;
}
}
-
}
-
-
diff --git a/servers/physics_2d/shape_2d_sw.h b/servers/physics_2d/shape_2d_sw.h
index c04cdfa456..00d86da7fb 100644
--- a/servers/physics_2d/shape_2d_sw.h
+++ b/servers/physics_2d/shape_2d_sw.h
@@ -46,11 +46,10 @@ SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_creat
class Shape2DSW;
-class ShapeOwner2DSW : public RID_Data{
+class ShapeOwner2DSW : public RID_Data {
public:
-
- virtual void _shape_changed()=0;
- virtual void remove_shape(Shape2DSW *p_shape)=0;
+ virtual void _shape_changed() = 0;
+ virtual void remove_shape(Shape2DSW *p_shape) = 0;
virtual ~ShapeOwner2DSW() {}
};
@@ -62,77 +61,75 @@ class Shape2DSW : public RID_Data {
bool configured;
real_t custom_bias;
- Map<ShapeOwner2DSW*,int> owners;
+ Map<ShapeOwner2DSW *, int> owners;
+
protected:
+ void configure(const Rect2 &p_aabb);
- void configure(const Rect2& p_aabb);
public:
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
+ _FORCE_INLINE_ RID get_self() const { return self; }
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
- _FORCE_INLINE_ RID get_self() const {return self; }
-
- virtual Physics2DServer::ShapeType get_type() const=0;
+ virtual Physics2DServer::ShapeType get_type() const = 0;
_FORCE_INLINE_ Rect2 get_aabb() const { return aabb; }
_FORCE_INLINE_ bool is_configured() const { return configured; }
virtual bool is_concave() const { return false; }
- virtual bool contains_point(const Vector2& p_point) const=0;
+ virtual bool contains_point(const Vector2 &p_point) const = 0;
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const=0;
- virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const=0;
- virtual Vector2 get_support(const Vector2& p_normal) const;
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const=0;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const = 0;
+ virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const = 0;
+ virtual Vector2 get_support(const Vector2 &p_normal) const;
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const = 0;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const=0;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const=0;
- virtual void set_data(const Variant& p_data)=0;
- virtual Variant get_data() const=0;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const = 0;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const = 0;
+ virtual void set_data(const Variant &p_data) = 0;
+ virtual Variant get_data() const = 0;
- _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias=p_bias; }
+ _FORCE_INLINE_ void set_custom_bias(real_t p_bias) { custom_bias = p_bias; }
_FORCE_INLINE_ real_t get_custom_bias() const { return custom_bias; }
void add_owner(ShapeOwner2DSW *p_owner);
void remove_owner(ShapeOwner2DSW *p_owner);
bool is_owner(ShapeOwner2DSW *p_owner) const;
- const Map<ShapeOwner2DSW*,int>& get_owners() const;
-
+ const Map<ShapeOwner2DSW *, int> &get_owners() const;
- _FORCE_INLINE_ void get_supports_transformed_cast(const Vector2& p_cast,const Vector2& p_normal,const Transform2D& p_xform,Vector2 *r_supports,int & r_amount) const {
+ _FORCE_INLINE_ void get_supports_transformed_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_xform, Vector2 *r_supports, int &r_amount) const {
- get_supports(p_xform.basis_xform_inv(p_normal).normalized(),r_supports,r_amount);
- for(int i=0;i<r_amount;i++)
- r_supports[i]=p_xform.xform(r_supports[i]);
+ get_supports(p_xform.basis_xform_inv(p_normal).normalized(), r_supports, r_amount);
+ for (int i = 0; i < r_amount; i++)
+ r_supports[i] = p_xform.xform(r_supports[i]);
- if (r_amount==1) {
+ if (r_amount == 1) {
- if (Math::abs( p_normal.dot(p_cast.normalized()) )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) {
+ if (Math::abs(p_normal.dot(p_cast.normalized())) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) {
//make line because they are parallel
- r_amount=2;
- r_supports[1]=r_supports[0]+p_cast;
- } else if (p_cast.dot(p_normal)>0) {
+ r_amount = 2;
+ r_supports[1] = r_supports[0] + p_cast;
+ } else if (p_cast.dot(p_normal) > 0) {
//normal points towards cast, add cast
- r_supports[0]+=p_cast;
+ r_supports[0] += p_cast;
}
} else {
- if (Math::abs( p_normal.dot(p_cast.normalized()) )<(1.0-_SEGMENT_IS_VALID_SUPPORT_TRESHOLD) ) {
+ if (Math::abs(p_normal.dot(p_cast.normalized())) < (1.0 - _SEGMENT_IS_VALID_SUPPORT_TRESHOLD)) {
//optimize line and make it larger because they are parallel
- if ((r_supports[1]-r_supports[0]).dot(p_cast)>0) {
+ if ((r_supports[1] - r_supports[0]).dot(p_cast) > 0) {
//larger towards 1
- r_supports[1]+=p_cast;
+ r_supports[1] += p_cast;
} else {
//larger towards 0
- r_supports[0]+=p_cast;
+ r_supports[0] += p_cast;
}
- } else if (p_cast.dot(p_normal)>0) {
+ } else if (p_cast.dot(p_normal) > 0) {
//normal points towards cast, add cast
- r_supports[0]+=p_cast;
- r_supports[1]+=p_cast;
+ r_supports[0] += p_cast;
+ r_supports[1] += p_cast;
}
-
}
}
@@ -141,305 +138,274 @@ public:
};
//let the optimizer do the magic
-#define DEFAULT_PROJECT_RANGE_CAST \
-virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {\
- project_range_cast(p_cast,p_normal,p_transform,r_min,r_max);\
-}\
-_FORCE_INLINE_ void project_range_cast(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {\
-\
- real_t mina,maxa;\
- real_t minb,maxb;\
- Transform2D ofsb=p_transform;\
- ofsb.elements[2]+=p_cast;\
- project_range(p_normal,p_transform,mina,maxa);\
- project_range(p_normal,ofsb,minb,maxb); \
- r_min=MIN(mina,minb);\
- r_max=MAX(maxa,maxb);\
-}
+#define DEFAULT_PROJECT_RANGE_CAST \
+ virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { \
+ project_range_cast(p_cast, p_normal, p_transform, r_min, r_max); \
+ } \
+ _FORCE_INLINE_ void project_range_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { \
+ \
+ real_t mina, maxa; \
+ real_t minb, maxb; \
+ Transform2D ofsb = p_transform; \
+ ofsb.elements[2] += p_cast; \
+ project_range(p_normal, p_transform, mina, maxa); \
+ project_range(p_normal, ofsb, minb, maxb); \
+ r_min = MIN(mina, minb); \
+ r_max = MAX(maxa, maxb); \
+ }
class LineShape2DSW : public Shape2DSW {
-
Vector2 normal;
real_t d;
public:
-
_FORCE_INLINE_ Vector2 get_normal() const { return normal; }
_FORCE_INLINE_ real_t get_d() const { return d; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_LINE; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
//real large
- r_min=-1e10;
- r_max=1e10;
+ r_min = -1e10;
+ r_max = 1e10;
}
- virtual void project_range_castv(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
- project_range_cast(p_cast,p_normal,p_transform,r_min,r_max);
+ virtual void project_range_castv(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
+ project_range_cast(p_cast, p_normal, p_transform, r_min, r_max);
}
- _FORCE_INLINE_ void project_range_cast(const Vector2& p_cast, const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range_cast(const Vector2 &p_cast, const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
//real large
- r_min=-1e10;
- r_max=1e10;
+ r_min = -1e10;
+ r_max = 1e10;
}
-
-
-
};
-
class RayShape2DSW : public Shape2DSW {
-
real_t length;
public:
-
-
- _FORCE_INLINE_ real_t get_length() const { return length; }
+ _FORCE_INLINE_ real_t get_length() const { return length; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_RAY; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
//real large
r_max = p_normal.dot(p_transform.get_origin());
- r_min = p_normal.dot(p_transform.xform(Vector2(0,length)));
- if (r_max<r_min) {
+ r_min = p_normal.dot(p_transform.xform(Vector2(0, length)));
+ if (r_max < r_min) {
- SWAP(r_max,r_min);
+ SWAP(r_max, r_min);
}
}
DEFAULT_PROJECT_RANGE_CAST
-
_FORCE_INLINE_ RayShape2DSW() {}
- _FORCE_INLINE_ RayShape2DSW(real_t p_length) { length=p_length; }
+ _FORCE_INLINE_ RayShape2DSW(real_t p_length) { length = p_length; }
};
-
class SegmentShape2DSW : public Shape2DSW {
-
Vector2 a;
Vector2 b;
Vector2 n;
public:
-
-
- _FORCE_INLINE_ const Vector2& get_a() const { return a; }
- _FORCE_INLINE_ const Vector2& get_b() const { return b; }
- _FORCE_INLINE_ const Vector2& get_normal() const { return n; }
+ _FORCE_INLINE_ const Vector2 &get_a() const { return a; }
+ _FORCE_INLINE_ const Vector2 &get_b() const { return b; }
+ _FORCE_INLINE_ const Vector2 &get_normal() const { return n; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_SEGMENT; }
- _FORCE_INLINE_ Vector2 get_xformed_normal(const Transform2D& p_xform) const {
+ _FORCE_INLINE_ Vector2 get_xformed_normal(const Transform2D &p_xform) const {
return (p_xform.xform(b) - p_xform.xform(a)).normalized().tangent();
}
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
//real large
r_max = p_normal.dot(p_transform.xform(a));
r_min = p_normal.dot(p_transform.xform(b));
- if (r_max<r_min) {
+ if (r_max < r_min) {
- SWAP(r_max,r_min);
+ SWAP(r_max, r_min);
}
}
DEFAULT_PROJECT_RANGE_CAST
_FORCE_INLINE_ SegmentShape2DSW() {}
- _FORCE_INLINE_ SegmentShape2DSW(const Vector2& p_a,const Vector2& p_b,const Vector2& p_n) { a=p_a; b=p_b; n=p_n; }
+ _FORCE_INLINE_ SegmentShape2DSW(const Vector2 &p_a, const Vector2 &p_b, const Vector2 &p_n) {
+ a = p_a;
+ b = p_b;
+ n = p_n;
+ }
};
-
class CircleShape2DSW : public Shape2DSW {
-
real_t radius;
public:
-
- _FORCE_INLINE_ const real_t& get_radius() const { return radius; }
+ _FORCE_INLINE_ const real_t &get_radius() const { return radius; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CIRCLE; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
//real large
- real_t d = p_normal.dot( p_transform.get_origin() );
+ real_t d = p_normal.dot(p_transform.get_origin());
// figure out scale at point
Vector2 local_normal = p_transform.basis_xform_inv(p_normal);
real_t scale = local_normal.length();
- r_min = d - (radius) * scale;
- r_max = d + (radius) * scale;
+ r_min = d - (radius)*scale;
+ r_max = d + (radius)*scale;
}
-
DEFAULT_PROJECT_RANGE_CAST
-
};
-
-
class RectangleShape2DSW : public Shape2DSW {
-
Vector2 half_extents;
public:
-
- _FORCE_INLINE_ const Vector2& get_half_extents() const { return half_extents; }
+ _FORCE_INLINE_ const Vector2 &get_half_extents() const { return half_extents; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_RECTANGLE; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
// no matter the angle, the box is mirrored anyway
- r_max=-1e20;
- r_min=1e20;
- for(int i=0;i<4;i++) {
-
- real_t d=p_normal.dot(p_transform.xform(Vector2( ((i&1)*2-1)*half_extents.x, ((i>>1)*2-1)*half_extents.y )));
+ r_max = -1e20;
+ r_min = 1e20;
+ for (int i = 0; i < 4; i++) {
- if (d>r_max)
- r_max=d;
- if (d<r_min)
- r_min=d;
+ real_t d = p_normal.dot(p_transform.xform(Vector2(((i & 1) * 2 - 1) * half_extents.x, ((i >> 1) * 2 - 1) * half_extents.y)));
+ if (d > r_max)
+ r_max = d;
+ if (d < r_min)
+ r_min = d;
}
}
-
-
- _FORCE_INLINE_ Vector2 get_circle_axis(const Transform2D& p_xform, const Transform2D& p_xform_inv,const Vector2& p_circle) const {
+ _FORCE_INLINE_ Vector2 get_circle_axis(const Transform2D &p_xform, const Transform2D &p_xform_inv, const Vector2 &p_circle) const {
Vector2 local_v = p_xform_inv.xform(p_circle);
Vector2 he(
- (local_v.x<0) ? -half_extents.x : half_extents.x,
- (local_v.y<0) ? -half_extents.y : half_extents.y
- );
+ (local_v.x < 0) ? -half_extents.x : half_extents.x,
+ (local_v.y < 0) ? -half_extents.y : half_extents.y);
- return (p_xform.xform(he)-p_circle).normalized();
+ return (p_xform.xform(he) - p_circle).normalized();
}
- _FORCE_INLINE_ Vector2 get_box_axis(const Transform2D& p_xform, const Transform2D& p_xform_inv,const RectangleShape2DSW *p_B,const Transform2D& p_B_xform, const Transform2D& p_B_xform_inv) const {
+ _FORCE_INLINE_ Vector2 get_box_axis(const Transform2D &p_xform, const Transform2D &p_xform_inv, const RectangleShape2DSW *p_B, const Transform2D &p_B_xform, const Transform2D &p_B_xform_inv) const {
- Vector2 a,b;
+ Vector2 a, b;
{
Vector2 local_v = p_xform_inv.xform(p_B_xform.get_origin());
Vector2 he(
- (local_v.x<0) ? -half_extents.x : half_extents.x,
- (local_v.y<0) ? -half_extents.y : half_extents.y
- );
-
- a=p_xform.xform(he);
+ (local_v.x < 0) ? -half_extents.x : half_extents.x,
+ (local_v.y < 0) ? -half_extents.y : half_extents.y);
+ a = p_xform.xform(he);
}
{
Vector2 local_v = p_B_xform_inv.xform(p_xform.get_origin());
Vector2 he(
- (local_v.x<0) ? -p_B->half_extents.x : p_B->half_extents.x,
- (local_v.y<0) ? -p_B->half_extents.y : p_B->half_extents.y
- );
-
- b=p_B_xform.xform(he);
+ (local_v.x < 0) ? -p_B->half_extents.x : p_B->half_extents.x,
+ (local_v.y < 0) ? -p_B->half_extents.y : p_B->half_extents.y);
+ b = p_B_xform.xform(he);
}
- return (a-b).normalized();
+ return (a - b).normalized();
}
-
DEFAULT_PROJECT_RANGE_CAST
-
};
class CapsuleShape2DSW : public Shape2DSW {
-
real_t radius;
real_t height;
public:
-
- _FORCE_INLINE_ const real_t& get_radius() const { return radius; }
- _FORCE_INLINE_ const real_t& get_height() const { return height; }
+ _FORCE_INLINE_ const real_t &get_radius() const { return radius; }
+ _FORCE_INLINE_ const real_t &get_height() const { return height; }
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CAPSULE; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
// no matter the angle, the box is mirrored anyway
- Vector2 n=p_transform.basis_xform_inv(p_normal).normalized();
+ Vector2 n = p_transform.basis_xform_inv(p_normal).normalized();
real_t h = (n.y > 0) ? height : -height;
n *= radius;
@@ -448,24 +414,19 @@ public:
r_max = p_normal.dot(p_transform.xform(n));
r_min = p_normal.dot(p_transform.xform(-n));
- if (r_max<r_min) {
+ if (r_max < r_min) {
- SWAP(r_max,r_min);
+ SWAP(r_max, r_min);
}
//ERR_FAIL_COND( r_max < r_min );
}
DEFAULT_PROJECT_RANGE_CAST
-
};
-
-
-
class ConvexPolygonShape2DSW : public Shape2DSW {
-
struct Point {
Vector2 pos;
@@ -476,44 +437,41 @@ class ConvexPolygonShape2DSW : public Shape2DSW {
int point_count;
public:
-
_FORCE_INLINE_ int get_point_count() const { return point_count; }
- _FORCE_INLINE_ const Vector2& get_point(int p_idx) const { return points[p_idx].pos; }
- _FORCE_INLINE_ const Vector2& get_segment_normal(int p_idx) const { return points[p_idx].normal; }
- _FORCE_INLINE_ Vector2 get_xformed_segment_normal(const Transform2D& p_xform, int p_idx) const {
+ _FORCE_INLINE_ const Vector2 &get_point(int p_idx) const { return points[p_idx].pos; }
+ _FORCE_INLINE_ const Vector2 &get_segment_normal(int p_idx) const { return points[p_idx].normal; }
+ _FORCE_INLINE_ Vector2 get_xformed_segment_normal(const Transform2D &p_xform, int p_idx) const {
Vector2 a = points[p_idx].pos;
p_idx++;
- Vector2 b = points[p_idx==point_count?0:p_idx].pos;
- return (p_xform.xform(b)-p_xform.xform(a)).normalized().tangent();
+ Vector2 b = points[p_idx == point_count ? 0 : p_idx].pos;
+ return (p_xform.xform(b) - p_xform.xform(a)).normalized().tangent();
}
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CONVEX_POLYGON; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal,p_transform,r_min,r_max); }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { project_range(p_normal, p_transform, r_min, r_max); }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const;
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- _FORCE_INLINE_ void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const {
+ _FORCE_INLINE_ void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const {
// no matter the angle, the box is mirrored anyway
r_min = r_max = p_normal.dot(p_transform.xform(points[0].pos));
- for(int i=1;i<point_count;i++) {
+ for (int i = 1; i < point_count; i++) {
real_t d = p_normal.dot(p_transform.xform(points[i].pos));
- if (d>r_max)
- r_max=d;
- if (d<r_min)
- r_min=d;
-
+ if (d > r_max)
+ r_max = d;
+ if (d < r_min)
+ r_min = d;
}
-
}
DEFAULT_PROJECT_RANGE_CAST
@@ -522,16 +480,13 @@ public:
~ConvexPolygonShape2DSW();
};
-
class ConcaveShape2DSW : public Shape2DSW {
public:
-
virtual bool is_concave() const { return true; }
- typedef void (*Callback)(void* p_userdata,Shape2DSW *p_convex);
-
- virtual void cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const=0;
+ typedef void (*Callback)(void *p_userdata, Shape2DSW *p_convex);
+ virtual void cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const = 0;
};
class ConcavePolygonShape2DSW : public ConcaveShape2DSW {
@@ -547,53 +502,50 @@ class ConcavePolygonShape2DSW : public ConcaveShape2DSW {
struct BVH {
Rect2 aabb;
- int left,right;
+ int left, right;
};
-
Vector<BVH> bvh;
int bvh_depth;
-
struct BVH_CompareX {
- _FORCE_INLINE_ bool operator ()(const BVH& a, const BVH& b) const {
+ _FORCE_INLINE_ bool operator()(const BVH &a, const BVH &b) const {
- return (a.aabb.pos.x+a.aabb.size.x*0.5) < (b.aabb.pos.x+b.aabb.size.x*0.5);
+ return (a.aabb.pos.x + a.aabb.size.x * 0.5) < (b.aabb.pos.x + b.aabb.size.x * 0.5);
}
};
struct BVH_CompareY {
- _FORCE_INLINE_ bool operator ()(const BVH& a, const BVH& b) const {
+ _FORCE_INLINE_ bool operator()(const BVH &a, const BVH &b) const {
- return (a.aabb.pos.y+a.aabb.size.y*0.5) < (b.aabb.pos.y+b.aabb.size.y*0.5);
+ return (a.aabb.pos.y + a.aabb.size.y * 0.5) < (b.aabb.pos.y + b.aabb.size.y * 0.5);
}
};
- int _generate_bvh(BVH *p_bvh,int p_len,int p_depth);
+ int _generate_bvh(BVH *p_bvh, int p_len, int p_depth);
public:
-
virtual Physics2DServer::ShapeType get_type() const { return Physics2DServer::SHAPE_CONCAVE_POLYGON; }
- virtual void project_rangev(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ }
- virtual void project_range(const Vector2& p_normal, const Transform2D& p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/ }
- virtual void get_supports(const Vector2& p_normal,Vector2 *r_supports,int & r_amount) const;
+ virtual void project_rangev(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/
+ }
+ virtual void project_range(const Vector2 &p_normal, const Transform2D &p_transform, real_t &r_min, real_t &r_max) const { /*project_range(p_normal,p_transform,r_min,r_max);*/
+ }
+ virtual void get_supports(const Vector2 &p_normal, Vector2 *r_supports, int &r_amount) const;
- virtual bool contains_point(const Vector2& p_point) const;
- virtual bool intersect_segment(const Vector2& p_begin,const Vector2& p_end,Vector2 &r_point, Vector2 &r_normal) const;
+ virtual bool contains_point(const Vector2 &p_point) const;
+ virtual bool intersect_segment(const Vector2 &p_begin, const Vector2 &p_end, Vector2 &r_point, Vector2 &r_normal) const;
- virtual real_t get_moment_of_inertia(real_t p_mass,const Size2& p_scale) const { return 0; }
+ virtual real_t get_moment_of_inertia(real_t p_mass, const Size2 &p_scale) const { return 0; }
- virtual void set_data(const Variant& p_data);
+ virtual void set_data(const Variant &p_data);
virtual Variant get_data() const;
- virtual void cull(const Rect2& p_local_aabb,Callback p_callback,void* p_userdata) const;
-
+ virtual void cull(const Rect2 &p_local_aabb, Callback p_callback, void *p_userdata) const;
DEFAULT_PROJECT_RANGE_CAST
-
};
#undef DEFAULT_PROJECT_RANGE_CAST
diff --git a/servers/physics_2d/space_2d_sw.cpp b/servers/physics_2d/space_2d_sw.cpp
index 9bced50061..93df0a00f6 100644
--- a/servers/physics_2d/space_2d_sw.cpp
+++ b/servers/physics_2d/space_2d_sw.cpp
@@ -30,109 +30,101 @@
#include "collision_solver_2d_sw.h"
#include "physics_2d_server_sw.h"
-
_FORCE_INLINE_ static bool _match_object_type_query(CollisionObject2DSW *p_object, uint32_t p_layer_mask, uint32_t p_type_mask) {
- if ((p_object->get_layer_mask()&p_layer_mask)==0)
+ if ((p_object->get_layer_mask() & p_layer_mask) == 0)
return false;
- if (p_object->get_type()==CollisionObject2DSW::TYPE_AREA)
- return p_type_mask&Physics2DDirectSpaceState::TYPE_MASK_AREA;
-
- Body2DSW *body = static_cast<Body2DSW*>(p_object);
+ if (p_object->get_type() == CollisionObject2DSW::TYPE_AREA)
+ return p_type_mask & Physics2DDirectSpaceState::TYPE_MASK_AREA;
- return (1<<body->get_mode())&p_type_mask;
+ Body2DSW *body = static_cast<Body2DSW *>(p_object);
+ return (1 << body->get_mode()) & p_type_mask;
}
+int Physics2DDirectSpaceStateSW::intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask, bool p_pick_point) {
-int Physics2DDirectSpaceStateSW::intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask,bool p_pick_point) {
-
- if (p_result_max<=0)
+ if (p_result_max <= 0)
return 0;
Rect2 aabb;
- aabb.pos=p_point-Vector2(0.00001,0.00001);
- aabb.size=Vector2(0.00002,0.00002);
+ aabb.pos = p_point - Vector2(0.00001, 0.00001);
+ aabb.size = Vector2(0.00002, 0.00002);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- int cc=0;
+ int cc = 0;
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
if (p_pick_point && !col_obj->is_pickable())
continue;
- int shape_idx=space->intersection_query_subindex_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- Shape2DSW * shape = col_obj->get_shape(shape_idx);
+ Shape2DSW *shape = col_obj->get_shape(shape_idx);
Vector2 local_point = (col_obj->get_transform() * col_obj->get_shape_transform(shape_idx)).affine_inverse().xform(p_point);
if (!shape->contains_point(local_point))
continue;
- if (cc>=p_result_max)
+ if (cc >= p_result_max)
continue;
- r_results[cc].collider_id=col_obj->get_instance_id();
- if (r_results[cc].collider_id!=0)
- r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id);
- r_results[cc].rid=col_obj->get_self();
- r_results[cc].shape=shape_idx;
- r_results[cc].metadata=col_obj->get_shape_metadata(shape_idx);
+ r_results[cc].collider_id = col_obj->get_instance_id();
+ if (r_results[cc].collider_id != 0)
+ r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
+ r_results[cc].rid = col_obj->get_self();
+ r_results[cc].shape = shape_idx;
+ r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
cc++;
}
return cc;
-
-
}
-bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
+bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
+ ERR_FAIL_COND_V(space->locked, false);
- ERR_FAIL_COND_V(space->locked,false);
-
- Vector2 begin,end;
+ Vector2 begin, end;
Vector2 normal;
- begin=p_from;
- end=p_to;
- normal=(end-begin).normalized();
+ begin = p_from;
+ end = p_to;
+ normal = (end - begin).normalized();
- int amount = space->broadphase->cull_segment(begin,end,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_segment(begin, end, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
//todo, create another array tha references results, compute AABBs and check closest point to ray origin, sort, and stop evaluating results when beyond first collision
- bool collided=false;
- Vector2 res_point,res_normal;
+ bool collided = false;
+ Vector2 res_point, res_normal;
int res_shape;
const CollisionObject2DSW *res_obj;
- real_t min_d=1e10;
+ real_t min_d = 1e10;
+ for (int i = 0; i < amount; i++) {
- for(int i=0;i<amount;i++) {
-
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
Transform2D inv_xform = col_obj->get_shape_inv_transform(shape_idx) * col_obj->get_inv_transform();
Vector2 local_from = inv_xform.xform(begin);
@@ -146,131 +138,113 @@ bool Physics2DDirectSpaceStateSW::intersect_ray(const Vector2& p_from, const Vec
const Shape2DSW *shape = col_obj->get_shape(shape_idx);
- Vector2 shape_point,shape_normal;
-
-
- if (shape->intersect_segment(local_from,local_to,shape_point,shape_normal)) {
-
+ Vector2 shape_point, shape_normal;
+ if (shape->intersect_segment(local_from, local_to, shape_point, shape_normal)) {
Transform2D xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
- shape_point=xform.xform(shape_point);
+ shape_point = xform.xform(shape_point);
real_t ld = normal.dot(shape_point);
+ if (ld < min_d) {
- if (ld<min_d) {
-
- min_d=ld;
- res_point=shape_point;
- res_normal=inv_xform.basis_xform_inv(shape_normal).normalized();
- res_shape=shape_idx;
- res_obj=col_obj;
- collided=true;
+ min_d = ld;
+ res_point = shape_point;
+ res_normal = inv_xform.basis_xform_inv(shape_normal).normalized();
+ res_shape = shape_idx;
+ res_obj = col_obj;
+ collided = true;
}
}
-
}
if (!collided)
return false;
-
- r_result.collider_id=res_obj->get_instance_id();
- if (r_result.collider_id!=0)
- r_result.collider=ObjectDB::get_instance(r_result.collider_id);
- r_result.normal=res_normal;
- r_result.metadata=res_obj->get_shape_metadata(res_shape);
- r_result.position=res_point;
- r_result.rid=res_obj->get_self();
- r_result.shape=res_shape;
+ r_result.collider_id = res_obj->get_instance_id();
+ if (r_result.collider_id != 0)
+ r_result.collider = ObjectDB::get_instance(r_result.collider_id);
+ r_result.normal = res_normal;
+ r_result.metadata = res_obj->get_shape_metadata(res_shape);
+ r_result.position = res_point;
+ r_result.rid = res_obj->get_self();
+ r_result.shape = res_shape;
return true;
-
}
+int Physics2DDirectSpaceStateSW::intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
-int Physics2DDirectSpaceStateSW::intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
- if (p_result_max<=0)
+ if (p_result_max <= 0)
return 0;
Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ERR_FAIL_COND_V(!shape, 0);
Rect2 aabb = p_xform.xform(shape->get_aabb());
- aabb=aabb.grow(p_margin);
+ aabb = aabb.grow(p_margin);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,p_result_max,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, p_result_max, space->intersection_query_subindex_results);
- int cc=0;
+ int cc = 0;
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue;
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
-
- if (!CollisionSolver2DSW::solve(shape,p_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),NULL,NULL,NULL,p_margin))
+ if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), NULL, NULL, NULL, p_margin))
continue;
- r_results[cc].collider_id=col_obj->get_instance_id();
- if (r_results[cc].collider_id!=0)
- r_results[cc].collider=ObjectDB::get_instance(r_results[cc].collider_id);
- r_results[cc].rid=col_obj->get_self();
- r_results[cc].shape=shape_idx;
- r_results[cc].metadata=col_obj->get_shape_metadata(shape_idx);
+ r_results[cc].collider_id = col_obj->get_instance_id();
+ if (r_results[cc].collider_id != 0)
+ r_results[cc].collider = ObjectDB::get_instance(r_results[cc].collider_id);
+ r_results[cc].rid = col_obj->get_self();
+ r_results[cc].shape = shape_idx;
+ r_results[cc].metadata = col_obj->get_shape_metadata(shape_idx);
cc++;
-
}
return cc;
-
}
-
-
-bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
-
+bool Physics2DDirectSpaceStateSW::cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,false);
+ ERR_FAIL_COND_V(!shape, false);
Rect2 aabb = p_xform.xform(shape->get_aabb());
- aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion
- aabb=aabb.grow(p_margin);
+ aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion
+ aabb = aabb.grow(p_margin);
/*
if (p_motion!=Vector2())
print_line(p_motion);
*/
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
-
- real_t best_safe=1;
- real_t best_unsafe=1;
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- for(int i=0;i<amount;i++) {
+ real_t best_safe = 1;
+ real_t best_unsafe = 1;
+ for (int i = 0; i < amount; i++) {
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- if (p_exclude.has( space->intersection_query_results[i]->get_self()))
+ if (p_exclude.has(space->intersection_query_results[i]->get_self()))
continue; //ignore excluded
-
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
-
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
/*if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
@@ -281,21 +255,19 @@ bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transfor
}
}*/
-
Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
//test initial overlap, does it collide if going all the way?
- if (!CollisionSolver2DSW::solve(shape,p_xform,p_motion,col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,p_margin)) {
+ if (!CollisionSolver2DSW::solve(shape, p_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) {
continue;
}
-
//test initial overlap
- if (CollisionSolver2DSW::solve(shape,p_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,p_margin)) {
+ if (CollisionSolver2DSW::solve(shape, p_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, p_margin)) {
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
//if one way collision direction ignore initial overlap
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- if (body->get_one_way_collision_direction()!=Vector2()) {
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ if (body->get_one_way_collision_direction() != Vector2()) {
continue;
}
}
@@ -303,131 +275,119 @@ bool Physics2DDirectSpaceStateSW::cast_motion(const RID& p_shape, const Transfor
return false;
}
-
//just do kinematic solving
- real_t low=0;
- real_t hi=1;
- Vector2 mnormal=p_motion.normalized();
+ real_t low = 0;
+ real_t hi = 1;
+ Vector2 mnormal = p_motion.normalized();
- for(int i=0;i<8;i++) { //steps should be customizable..
+ for (int i = 0; i < 8; i++) { //steps should be customizable..
- real_t ofs = (low+hi)*0.5;
+ real_t ofs = (low + hi) * 0.5;
- Vector2 sep=mnormal; //important optimization for this to work fast enough
- bool collided = CollisionSolver2DSW::solve(shape,p_xform,p_motion*ofs,col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),NULL,NULL,&sep,p_margin);
+ Vector2 sep = mnormal; //important optimization for this to work fast enough
+ bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * ofs, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, &sep, p_margin);
if (collided) {
- hi=ofs;
+ hi = ofs;
} else {
- low=ofs;
+ low = ofs;
}
}
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- if (body->get_one_way_collision_direction()!=Vector2()) {
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ if (body->get_one_way_collision_direction() != Vector2()) {
Vector2 cd[2];
Physics2DServerSW::CollCbkData cbk;
- cbk.max=1;
- cbk.amount=0;
- cbk.ptr=cd;
- cbk.valid_dir=body->get_one_way_collision_direction();
- cbk.valid_depth=body->get_one_way_collision_max_depth();
-
- Vector2 sep=mnormal; //important optimization for this to work fast enough
- bool collided = CollisionSolver2DSW::solve(shape,p_xform,p_motion*(hi+space->contact_max_allowed_penetration),col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),Physics2DServerSW::_shape_col_cbk,&cbk,&sep,p_margin);
- if (!collided || cbk.amount==0) {
+ cbk.max = 1;
+ cbk.amount = 0;
+ cbk.ptr = cd;
+ cbk.valid_dir = body->get_one_way_collision_direction();
+ cbk.valid_depth = body->get_one_way_collision_max_depth();
+
+ Vector2 sep = mnormal; //important optimization for this to work fast enough
+ bool collided = CollisionSolver2DSW::solve(shape, p_xform, p_motion * (hi + space->contact_max_allowed_penetration), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, p_margin);
+ if (!collided || cbk.amount == 0) {
continue;
}
-
}
}
-
- if (low<best_safe) {
- best_safe=low;
- best_unsafe=hi;
+ if (low < best_safe) {
+ best_safe = low;
+ best_unsafe = hi;
}
-
}
- p_closest_safe=best_safe;
- p_closest_unsafe=best_unsafe;
+ p_closest_safe = best_safe;
+ p_closest_unsafe = best_unsafe;
return true;
-
-
}
+bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
-bool Physics2DDirectSpaceStateSW::collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
-
- if (p_result_max<=0)
+ if (p_result_max <= 0)
return 0;
Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ERR_FAIL_COND_V(!shape, 0);
Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
- aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion
- aabb=aabb.grow(p_margin);
+ aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion
+ aabb = aabb.grow(p_margin);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
- bool collided=false;
- r_result_count=0;
+ bool collided = false;
+ r_result_count = 0;
Physics2DServerSW::CollCbkData cbk;
- cbk.max=p_result_max;
- cbk.amount=0;
- cbk.ptr=r_results;
- CollisionSolver2DSW::CallbackResult cbkres=NULL;
-
- Physics2DServerSW::CollCbkData *cbkptr=NULL;
- if (p_result_max>0) {
- cbkptr=&cbk;
- cbkres=Physics2DServerSW::_shape_col_cbk;
+ cbk.max = p_result_max;
+ cbk.amount = 0;
+ cbk.ptr = r_results;
+ CollisionSolver2DSW::CallbackResult cbkres = NULL;
+
+ Physics2DServerSW::CollCbkData *cbkptr = NULL;
+ if (p_result_max > 0) {
+ cbkptr = &cbk;
+ cbkres = Physics2DServerSW::_shape_col_cbk;
}
+ for (int i = 0; i < amount; i++) {
- for(int i=0;i<amount;i++) {
-
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- if (p_exclude.has( col_obj->get_self() ))
+ if (p_exclude.has(col_obj->get_self()))
continue;
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- cbk.valid_dir=body->get_one_way_collision_direction();
- cbk.valid_depth=body->get_one_way_collision_max_depth();
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ cbk.valid_dir = body->get_one_way_collision_direction();
+ cbk.valid_depth = body->get_one_way_collision_max_depth();
} else {
- cbk.valid_dir=Vector2();
- cbk.valid_depth=0;
+ cbk.valid_dir = Vector2();
+ cbk.valid_depth = 0;
}
- if (CollisionSolver2DSW::solve(shape,p_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),cbkres,cbkptr,NULL,p_margin)) {
- collided=p_result_max==0 || cbk.amount>0;
+ if (CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, NULL, p_margin)) {
+ collided = p_result_max == 0 || cbk.amount > 0;
}
-
}
-
- r_result_count=cbk.amount;
+ r_result_count = cbk.amount;
return collided;
}
-
struct _RestCallbackData2D {
const CollisionObject2DSW *object;
@@ -441,20 +401,18 @@ struct _RestCallbackData2D {
real_t valid_depth;
};
-static void _rest_cbk_result(const Vector2& p_point_A,const Vector2& p_point_B,void *p_userdata) {
-
+static void _rest_cbk_result(const Vector2 &p_point_A, const Vector2 &p_point_B, void *p_userdata) {
- _RestCallbackData2D *rd=(_RestCallbackData2D*)p_userdata;
+ _RestCallbackData2D *rd = (_RestCallbackData2D *)p_userdata;
- if (rd->valid_dir!=Vector2()) {
+ if (rd->valid_dir != Vector2()) {
- if (rd->valid_dir!=Vector2()) {
- if (p_point_A.distance_squared_to(p_point_B)>rd->valid_depth*rd->valid_depth)
+ if (rd->valid_dir != Vector2()) {
+ if (p_point_A.distance_squared_to(p_point_B) > rd->valid_depth * rd->valid_depth)
return;
- if (rd->valid_dir.dot((p_point_A-p_point_B).normalized())<Math_PI*0.25)
+ if (rd->valid_dir.dot((p_point_A - p_point_B).normalized()) < Math_PI * 0.25)
return;
}
-
}
Vector2 contact_rel = p_point_B - p_point_A;
@@ -462,139 +420,121 @@ static void _rest_cbk_result(const Vector2& p_point_A,const Vector2& p_point_B,v
if (len <= rd->best_len)
return;
-
- rd->best_len=len;
- rd->best_contact=p_point_B;
- rd->best_normal=contact_rel/len;
- rd->best_object=rd->object;
- rd->best_shape=rd->shape;
-
-
+ rd->best_len = len;
+ rd->best_contact = p_point_B;
+ rd->best_normal = contact_rel / len;
+ rd->best_object = rd->object;
+ rd->best_shape = rd->shape;
}
-
-bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude,uint32_t p_layer_mask,uint32_t p_object_type_mask) {
-
+bool Physics2DDirectSpaceStateSW::rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude, uint32_t p_layer_mask, uint32_t p_object_type_mask) {
Shape2DSW *shape = Physics2DServerSW::singletonsw->shape_owner.get(p_shape);
- ERR_FAIL_COND_V(!shape,0);
+ ERR_FAIL_COND_V(!shape, 0);
Rect2 aabb = p_shape_xform.xform(shape->get_aabb());
- aabb=aabb.merge(Rect2(aabb.pos+p_motion,aabb.size)); //motion
- aabb=aabb.grow(p_margin);
+ aabb = aabb.merge(Rect2(aabb.pos + p_motion, aabb.size)); //motion
+ aabb = aabb.grow(p_margin);
- int amount = space->broadphase->cull_aabb(aabb,space->intersection_query_results,Space2DSW::INTERSECTION_QUERY_MAX,space->intersection_query_subindex_results);
+ int amount = space->broadphase->cull_aabb(aabb, space->intersection_query_results, Space2DSW::INTERSECTION_QUERY_MAX, space->intersection_query_subindex_results);
_RestCallbackData2D rcd;
- rcd.best_len=0;
- rcd.best_object=NULL;
- rcd.best_shape=0;
-
- for(int i=0;i<amount;i++) {
+ rcd.best_len = 0;
+ rcd.best_object = NULL;
+ rcd.best_shape = 0;
+ for (int i = 0; i < amount; i++) {
- if (!_match_object_type_query(space->intersection_query_results[i],p_layer_mask,p_object_type_mask))
+ if (!_match_object_type_query(space->intersection_query_results[i], p_layer_mask, p_object_type_mask))
continue;
- const CollisionObject2DSW *col_obj=space->intersection_query_results[i];
- int shape_idx=space->intersection_query_subindex_results[i];
+ const CollisionObject2DSW *col_obj = space->intersection_query_results[i];
+ int shape_idx = space->intersection_query_subindex_results[i];
- if (p_exclude.has( col_obj->get_self() ))
+ if (p_exclude.has(col_obj->get_self()))
continue;
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- rcd.valid_dir=body->get_one_way_collision_direction();
- rcd.valid_depth=body->get_one_way_collision_max_depth();
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ rcd.valid_dir = body->get_one_way_collision_direction();
+ rcd.valid_depth = body->get_one_way_collision_max_depth();
} else {
- rcd.valid_dir=Vector2();
- rcd.valid_depth=0;
+ rcd.valid_dir = Vector2();
+ rcd.valid_depth = 0;
}
-
- rcd.object=col_obj;
- rcd.shape=shape_idx;
- bool sc = CollisionSolver2DSW::solve(shape,p_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2() ,_rest_cbk_result,&rcd,NULL,p_margin);
+ rcd.object = col_obj;
+ rcd.shape = shape_idx;
+ bool sc = CollisionSolver2DSW::solve(shape, p_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, NULL, p_margin);
if (!sc)
continue;
-
-
}
- if (rcd.best_len==0)
+ if (rcd.best_len == 0)
return false;
- r_info->collider_id=rcd.best_object->get_instance_id();
- r_info->shape=rcd.best_shape;
- r_info->normal=rcd.best_normal;
- r_info->point=rcd.best_contact;
- r_info->rid=rcd.best_object->get_self();
- r_info->metadata=rcd.best_object->get_shape_metadata(rcd.best_shape);
- if (rcd.best_object->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ r_info->collider_id = rcd.best_object->get_instance_id();
+ r_info->shape = rcd.best_shape;
+ r_info->normal = rcd.best_normal;
+ r_info->point = rcd.best_contact;
+ r_info->rid = rcd.best_object->get_self();
+ r_info->metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
+ if (rcd.best_object->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body = static_cast<const Body2DSW*>(rcd.best_object);
- Vector2 rel_vec = r_info->point-body->get_transform().get_origin();
+ const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
+ Vector2 rel_vec = r_info->point - body->get_transform().get_origin();
r_info->linear_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
} else {
- r_info->linear_velocity=Vector2();
+ r_info->linear_velocity = Vector2();
}
return true;
}
-
Physics2DDirectSpaceStateSW::Physics2DDirectSpaceStateSW() {
-
- space=NULL;
+ space = NULL;
}
-
////////////////////////////////////////////////////////////////////////////////////////////////////////////
+int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb) {
+ int amount = broadphase->cull_aabb(p_aabb, intersection_query_results, INTERSECTION_QUERY_MAX, intersection_query_subindex_results);
+ for (int i = 0; i < amount; i++) {
-int Space2DSW::_cull_aabb_for_body(Body2DSW *p_body,const Rect2& p_aabb) {
-
-
- int amount = broadphase->cull_aabb(p_aabb,intersection_query_results,INTERSECTION_QUERY_MAX,intersection_query_subindex_results);
+ bool keep = true;
- for(int i=0;i<amount;i++) {
-
- bool keep=true;
-
- if (intersection_query_results[i]==p_body)
- keep=false;
- else if (intersection_query_results[i]->get_type()==CollisionObject2DSW::TYPE_AREA)
- keep=false;
- else if ((static_cast<Body2DSW*>(intersection_query_results[i])->test_collision_mask(p_body))==0)
- keep=false;
- else if (static_cast<Body2DSW*>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self()))
- keep=false;
- else if (static_cast<Body2DSW*>(intersection_query_results[i])->is_shape_set_as_trigger(intersection_query_subindex_results[i]))
- keep=false;
+ if (intersection_query_results[i] == p_body)
+ keep = false;
+ else if (intersection_query_results[i]->get_type() == CollisionObject2DSW::TYPE_AREA)
+ keep = false;
+ else if ((static_cast<Body2DSW *>(intersection_query_results[i])->test_collision_mask(p_body)) == 0)
+ keep = false;
+ else if (static_cast<Body2DSW *>(intersection_query_results[i])->has_exception(p_body->get_self()) || p_body->has_exception(intersection_query_results[i]->get_self()))
+ keep = false;
+ else if (static_cast<Body2DSW *>(intersection_query_results[i])->is_shape_set_as_trigger(intersection_query_subindex_results[i]))
+ keep = false;
if (!keep) {
- if (i<amount-1) {
- SWAP(intersection_query_results[i],intersection_query_results[amount-1]);
- SWAP(intersection_query_subindex_results[i],intersection_query_subindex_results[amount-1]);
-
+ if (i < amount - 1) {
+ SWAP(intersection_query_results[i], intersection_query_results[amount - 1]);
+ SWAP(intersection_query_subindex_results[i], intersection_query_subindex_results[amount - 1]);
}
amount--;
i--;
-
}
}
return amount;
}
-bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2&p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result) {
+bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result) {
//give me back regular physics engine logic
//this is madness
@@ -604,65 +544,61 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co
//but is it right? who knows at this point..
if (r_result) {
- r_result->collider_id=0;
- r_result->collider_shape=0;
-
+ r_result->collider_id = 0;
+ r_result->collider_shape = 0;
}
Rect2 body_aabb;
- for(int i=0;i<p_body->get_shape_count();i++) {
+ for (int i = 0; i < p_body->get_shape_count(); i++) {
- if (i==0)
- body_aabb=p_body->get_shape_aabb(i);
+ if (i == 0)
+ body_aabb = p_body->get_shape_aabb(i);
else
- body_aabb=body_aabb.merge(p_body->get_shape_aabb(i));
+ body_aabb = body_aabb.merge(p_body->get_shape_aabb(i));
}
- body_aabb=body_aabb.grow(p_margin);
+ body_aabb = body_aabb.grow(p_margin);
Transform2D body_transform = p_from;
-
{
//STEP 1, FREE BODY IF STUCK
const int max_results = 32;
- int recover_attempts=4;
- Vector2 sr[max_results*2];
+ int recover_attempts = 4;
+ Vector2 sr[max_results * 2];
do {
Physics2DServerSW::CollCbkData cbk;
- cbk.max=max_results;
- cbk.amount=0;
- cbk.ptr=sr;
-
-
- CollisionSolver2DSW::CallbackResult cbkres=NULL;
+ cbk.max = max_results;
+ cbk.amount = 0;
+ cbk.ptr = sr;
- Physics2DServerSW::CollCbkData *cbkptr=NULL;
- cbkptr=&cbk;
- cbkres=Physics2DServerSW::_shape_col_cbk;
+ CollisionSolver2DSW::CallbackResult cbkres = NULL;
- bool collided=false;
+ Physics2DServerSW::CollCbkData *cbkptr = NULL;
+ cbkptr = &cbk;
+ cbkres = Physics2DServerSW::_shape_col_cbk;
+ bool collided = false;
- int amount = _cull_aabb_for_body(p_body,body_aabb);
+ int amount = _cull_aabb_for_body(p_body, body_aabb);
- for(int j=0;j<p_body->get_shape_count();j++) {
+ for (int j = 0; j < p_body->get_shape_count(); j++) {
if (p_body->is_shape_set_as_trigger(j))
continue;
Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
Shape2DSW *body_shape = p_body->get_shape(j);
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
- const CollisionObject2DSW *col_obj=intersection_query_results[i];
- int shape_idx=intersection_query_subindex_results[i];
+ const CollisionObject2DSW *col_obj = intersection_query_results[i];
+ int shape_idx = intersection_query_subindex_results[i];
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
Vector2 cdir = body->get_one_way_collision_direction();
/*
@@ -670,31 +606,29 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co
continue;
*/
- cbk.valid_dir=cdir;
- cbk.valid_depth=body->get_one_way_collision_max_depth();
+ cbk.valid_dir = cdir;
+ cbk.valid_depth = body->get_one_way_collision_max_depth();
} else {
- cbk.valid_dir=Vector2();
- cbk.valid_depth=0;
+ cbk.valid_dir = Vector2();
+ cbk.valid_depth = 0;
}
- if (CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2(),cbkres,cbkptr,NULL,p_margin)) {
- collided=cbk.amount>0;
+ if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), cbkres, cbkptr, NULL, p_margin)) {
+ collided = cbk.amount > 0;
}
}
}
-
if (!collided) {
break;
}
Vector2 recover_motion;
+ for (int i = 0; i < cbk.amount; i++) {
- for(int i=0;i<cbk.amount;i++) {
-
- Vector2 a = sr[i*2+0];
- Vector2 b = sr[i*2+1];
+ Vector2 a = sr[i * 2 + 0];
+ Vector2 b = sr[i * 2 + 1];
#if 0
Vector2 rel = b-a;
@@ -710,38 +644,36 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co
if (d<margin)
continue;
#endif
- recover_motion+=(b-a)*0.4;
+ recover_motion += (b - a) * 0.4;
}
- if (recover_motion==Vector2()) {
- collided=false;
+ if (recover_motion == Vector2()) {
+ collided = false;
break;
}
- body_transform.elements[2]+=recover_motion;
- body_aabb.pos+=recover_motion;
+ body_transform.elements[2] += recover_motion;
+ body_aabb.pos += recover_motion;
recover_attempts--;
} while (recover_attempts);
}
-
-
real_t safe = 1.0;
real_t unsafe = 1.0;
- int best_shape=-1;
+ int best_shape = -1;
{
// STEP 2 ATTEMPT MOTION
- Rect2 motion_aabb=body_aabb;
- motion_aabb.pos+=p_motion;
- motion_aabb=motion_aabb.merge(body_aabb);
+ Rect2 motion_aabb = body_aabb;
+ motion_aabb.pos += p_motion;
+ motion_aabb = motion_aabb.merge(body_aabb);
- int amount = _cull_aabb_for_body(p_body,motion_aabb);
+ int amount = _cull_aabb_for_body(p_body, motion_aabb);
- for(int j=0;j<p_body->get_shape_count();j++) {
+ for (int j = 0; j < p_body->get_shape_count(); j++) {
if (p_body->is_shape_set_as_trigger(j))
continue;
@@ -749,201 +681,189 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co
Transform2D body_shape_xform = body_transform * p_body->get_shape_transform(j);
Shape2DSW *body_shape = p_body->get_shape(j);
- bool stuck=false;
+ bool stuck = false;
- real_t best_safe=1;
- real_t best_unsafe=1;
+ real_t best_safe = 1;
+ real_t best_unsafe = 1;
- for(int i=0;i<amount;i++) {
-
- const CollisionObject2DSW *col_obj=intersection_query_results[i];
- int shape_idx=intersection_query_subindex_results[i];
+ for (int i = 0; i < amount; i++) {
+ const CollisionObject2DSW *col_obj = intersection_query_results[i];
+ int shape_idx = intersection_query_subindex_results[i];
Transform2D col_obj_xform = col_obj->get_transform() * col_obj->get_shape_transform(shape_idx);
//test initial overlap, does it collide if going all the way?
- if (!CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion,col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,0)) {
+ if (!CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, 0)) {
continue;
}
-
//test initial overlap
- if (CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj_xform,Vector2() ,NULL,NULL,NULL,0)) {
+ if (CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, NULL, 0)) {
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
//if one way collision direction ignore initial overlap
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- if (body->get_one_way_collision_direction()!=Vector2()) {
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ if (body->get_one_way_collision_direction() != Vector2()) {
continue;
}
}
- stuck=true;
+ stuck = true;
break;
}
-
//just do kinematic solving
- real_t low=0;
- real_t hi=1;
- Vector2 mnormal=p_motion.normalized();
+ real_t low = 0;
+ real_t hi = 1;
+ Vector2 mnormal = p_motion.normalized();
- for(int i=0;i<8;i++) { //steps should be customizable..
+ for (int i = 0; i < 8; i++) { //steps should be customizable..
- real_t ofs = (low+hi)*0.5;
+ real_t ofs = (low + hi) * 0.5;
- Vector2 sep=mnormal; //important optimization for this to work fast enough
- bool collided = CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion*ofs,col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),NULL,NULL,&sep,0);
+ Vector2 sep = mnormal; //important optimization for this to work fast enough
+ bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * ofs, col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), NULL, NULL, &sep, 0);
if (collided) {
- hi=ofs;
+ hi = ofs;
} else {
- low=ofs;
+ low = ofs;
}
}
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- if (body->get_one_way_collision_direction()!=Vector2()) {
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ if (body->get_one_way_collision_direction() != Vector2()) {
Vector2 cd[2];
Physics2DServerSW::CollCbkData cbk;
- cbk.max=1;
- cbk.amount=0;
- cbk.ptr=cd;
- cbk.valid_dir=body->get_one_way_collision_direction();
- cbk.valid_depth=body->get_one_way_collision_max_depth();
-
- Vector2 sep=mnormal; //important optimization for this to work fast enough
- bool collided = CollisionSolver2DSW::solve(body_shape,body_shape_xform,p_motion*(hi+contact_max_allowed_penetration),col_obj->get_shape(shape_idx),col_obj_xform,Vector2(),Physics2DServerSW::_shape_col_cbk,&cbk,&sep,0);
- if (!collided || cbk.amount==0) {
+ cbk.max = 1;
+ cbk.amount = 0;
+ cbk.ptr = cd;
+ cbk.valid_dir = body->get_one_way_collision_direction();
+ cbk.valid_depth = body->get_one_way_collision_max_depth();
+
+ Vector2 sep = mnormal; //important optimization for this to work fast enough
+ bool collided = CollisionSolver2DSW::solve(body_shape, body_shape_xform, p_motion * (hi + contact_max_allowed_penetration), col_obj->get_shape(shape_idx), col_obj_xform, Vector2(), Physics2DServerSW::_shape_col_cbk, &cbk, &sep, 0);
+ if (!collided || cbk.amount == 0) {
continue;
}
-
}
}
-
- if (low<best_safe) {
- best_safe=low;
- best_unsafe=hi;
+ if (low < best_safe) {
+ best_safe = low;
+ best_unsafe = hi;
}
}
if (stuck) {
- safe=0;
- unsafe=0;
- best_shape=j; //sadly it's the best
+ safe = 0;
+ unsafe = 0;
+ best_shape = j; //sadly it's the best
break;
}
- if (best_safe==1.0) {
+ if (best_safe == 1.0) {
continue;
}
if (best_safe < safe) {
- safe=best_safe;
- unsafe=best_unsafe;
- best_shape=j;
+ safe = best_safe;
+ unsafe = best_unsafe;
+ best_shape = j;
}
}
}
- bool collided=false;
- if (safe>=1) {
+ bool collided = false;
+ if (safe >= 1) {
//not collided
- collided=false;
+ collided = false;
if (r_result) {
- r_result->motion=p_motion;
- r_result->remainder=Vector2();
- r_result->motion+=(body_transform.get_origin()-p_from.get_origin());
+ r_result->motion = p_motion;
+ r_result->remainder = Vector2();
+ r_result->motion += (body_transform.get_origin() - p_from.get_origin());
}
} else {
//it collided, let's get the rest info in unsafe advance
Transform2D ugt = body_transform;
- ugt.elements[2]+=p_motion*unsafe;
+ ugt.elements[2] += p_motion * unsafe;
_RestCallbackData2D rcd;
- rcd.best_len=0;
- rcd.best_object=NULL;
- rcd.best_shape=0;
+ rcd.best_len = 0;
+ rcd.best_object = NULL;
+ rcd.best_shape = 0;
Transform2D body_shape_xform = ugt * p_body->get_shape_transform(best_shape);
Shape2DSW *body_shape = p_body->get_shape(best_shape);
- body_aabb.pos+=p_motion*unsafe;
-
- int amount = _cull_aabb_for_body(p_body,body_aabb);
+ body_aabb.pos += p_motion * unsafe;
+ int amount = _cull_aabb_for_body(p_body, body_aabb);
- for(int i=0;i<amount;i++) {
+ for (int i = 0; i < amount; i++) {
+ const CollisionObject2DSW *col_obj = intersection_query_results[i];
+ int shape_idx = intersection_query_subindex_results[i];
- const CollisionObject2DSW *col_obj=intersection_query_results[i];
- int shape_idx=intersection_query_subindex_results[i];
+ if (col_obj->get_type() == CollisionObject2DSW::TYPE_BODY) {
- if (col_obj->get_type()==CollisionObject2DSW::TYPE_BODY) {
-
- const Body2DSW *body=static_cast<const Body2DSW*>(col_obj);
- rcd.valid_dir=body->get_one_way_collision_direction();
- rcd.valid_depth=body->get_one_way_collision_max_depth();
+ const Body2DSW *body = static_cast<const Body2DSW *>(col_obj);
+ rcd.valid_dir = body->get_one_way_collision_direction();
+ rcd.valid_depth = body->get_one_way_collision_max_depth();
} else {
- rcd.valid_dir=Vector2();
- rcd.valid_depth=0;
+ rcd.valid_dir = Vector2();
+ rcd.valid_depth = 0;
}
-
- rcd.object=col_obj;
- rcd.shape=shape_idx;
- bool sc = CollisionSolver2DSW::solve(body_shape,body_shape_xform,Vector2(),col_obj->get_shape(shape_idx),col_obj->get_transform() * col_obj->get_shape_transform(shape_idx),Vector2() ,_rest_cbk_result,&rcd,NULL,p_margin);
+ rcd.object = col_obj;
+ rcd.shape = shape_idx;
+ bool sc = CollisionSolver2DSW::solve(body_shape, body_shape_xform, Vector2(), col_obj->get_shape(shape_idx), col_obj->get_transform() * col_obj->get_shape_transform(shape_idx), Vector2(), _rest_cbk_result, &rcd, NULL, p_margin);
if (!sc)
continue;
-
}
- if (rcd.best_len!=0) {
+ if (rcd.best_len != 0) {
if (r_result) {
- r_result->collider=rcd.best_object->get_self();
- r_result->collider_id=rcd.best_object->get_instance_id();
- r_result->collider_shape=rcd.best_shape;
- r_result->collision_normal=rcd.best_normal;
- r_result->collision_point=rcd.best_contact;
- r_result->collider_metadata=rcd.best_object->get_shape_metadata(rcd.best_shape);
-
- const Body2DSW *body = static_cast<const Body2DSW*>(rcd.best_object);
- Vector2 rel_vec = r_result->collision_point-body->get_transform().get_origin();
+ r_result->collider = rcd.best_object->get_self();
+ r_result->collider_id = rcd.best_object->get_instance_id();
+ r_result->collider_shape = rcd.best_shape;
+ r_result->collision_normal = rcd.best_normal;
+ r_result->collision_point = rcd.best_contact;
+ r_result->collider_metadata = rcd.best_object->get_shape_metadata(rcd.best_shape);
+
+ const Body2DSW *body = static_cast<const Body2DSW *>(rcd.best_object);
+ Vector2 rel_vec = r_result->collision_point - body->get_transform().get_origin();
r_result->collider_velocity = Vector2(-body->get_angular_velocity() * rel_vec.y, body->get_angular_velocity() * rel_vec.x) + body->get_linear_velocity();
- r_result->motion=safe*p_motion;
- r_result->remainder=p_motion - safe * p_motion;
- r_result->motion+=(body_transform.get_origin()-p_from.get_origin());
-
+ r_result->motion = safe * p_motion;
+ r_result->remainder = p_motion - safe * p_motion;
+ r_result->motion += (body_transform.get_origin() - p_from.get_origin());
}
- collided=true;
+ collided = true;
} else {
if (r_result) {
- r_result->motion=p_motion;
- r_result->remainder=Vector2();
- r_result->motion+=(body_transform.get_origin()-p_from.get_origin());
+ r_result->motion = p_motion;
+ r_result->remainder = Vector2();
+ r_result->motion += (body_transform.get_origin() - p_from.get_origin());
}
- collided=false;
-
+ collided = false;
}
}
return collided;
-
#if 0
//give me back regular physics engine logic
//this is madness
@@ -1101,82 +1021,71 @@ bool Space2DSW::test_body_motion(Body2DSW *p_body, const Transform2D &p_from, co
return false;
}
+void *Space2DSW::_broadphase_pair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_self) {
+ CollisionObject2DSW::Type type_A = A->get_type();
+ CollisionObject2DSW::Type type_B = B->get_type();
+ if (type_A > type_B) {
-
-void* Space2DSW::_broadphase_pair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_self) {
-
-
- CollisionObject2DSW::Type type_A=A->get_type();
- CollisionObject2DSW::Type type_B=B->get_type();
- if (type_A>type_B) {
-
- SWAP(A,B);
- SWAP(p_subindex_A,p_subindex_B);
- SWAP(type_A,type_B);
+ SWAP(A, B);
+ SWAP(p_subindex_A, p_subindex_B);
+ SWAP(type_A, type_B);
}
- Space2DSW *self = (Space2DSW*)p_self;
+ Space2DSW *self = (Space2DSW *)p_self;
self->collision_pairs++;
- if (type_A==CollisionObject2DSW::TYPE_AREA) {
+ if (type_A == CollisionObject2DSW::TYPE_AREA) {
- Area2DSW *area=static_cast<Area2DSW*>(A);
- if (type_B==CollisionObject2DSW::TYPE_AREA) {
+ Area2DSW *area = static_cast<Area2DSW *>(A);
+ if (type_B == CollisionObject2DSW::TYPE_AREA) {
- Area2DSW *area_b=static_cast<Area2DSW*>(B);
- Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b,p_subindex_B,area,p_subindex_A) );
+ Area2DSW *area_b = static_cast<Area2DSW *>(B);
+ Area2Pair2DSW *area2_pair = memnew(Area2Pair2DSW(area_b, p_subindex_B, area, p_subindex_A));
return area2_pair;
} else {
- Body2DSW *body=static_cast<Body2DSW*>(B);
- AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body,p_subindex_B,area,p_subindex_A) );
+ Body2DSW *body = static_cast<Body2DSW *>(B);
+ AreaPair2DSW *area_pair = memnew(AreaPair2DSW(body, p_subindex_B, area, p_subindex_A));
return area_pair;
}
-
} else {
-
- BodyPair2DSW *b = memnew( BodyPair2DSW((Body2DSW*)A,p_subindex_A,(Body2DSW*)B,p_subindex_B) );
+ BodyPair2DSW *b = memnew(BodyPair2DSW((Body2DSW *)A, p_subindex_A, (Body2DSW *)B, p_subindex_B));
return b;
-
}
return NULL;
}
-void Space2DSW::_broadphase_unpair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_self) {
+void Space2DSW::_broadphase_unpair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_self) {
-
- Space2DSW *self = (Space2DSW*)p_self;
+ Space2DSW *self = (Space2DSW *)p_self;
self->collision_pairs--;
- Constraint2DSW *c = (Constraint2DSW*)p_data;
+ Constraint2DSW *c = (Constraint2DSW *)p_data;
memdelete(c);
}
-
-const SelfList<Body2DSW>::List& Space2DSW::get_active_body_list() const {
+const SelfList<Body2DSW>::List &Space2DSW::get_active_body_list() const {
return active_list;
}
-void Space2DSW::body_add_to_active_list(SelfList<Body2DSW>* p_body) {
+void Space2DSW::body_add_to_active_list(SelfList<Body2DSW> *p_body) {
active_list.add(p_body);
}
-void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW>* p_body) {
+void Space2DSW::body_remove_from_active_list(SelfList<Body2DSW> *p_body) {
active_list.remove(p_body);
-
}
-void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW>* p_body) {
-
+void Space2DSW::body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body) {
inertia_update_list.add(p_body);
}
-void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW>* p_body) {
+void Space2DSW::body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body) {
inertia_update_list.remove(p_body);
}
@@ -1188,109 +1097,103 @@ BroadPhase2DSW *Space2DSW::get_broadphase() {
void Space2DSW::add_object(CollisionObject2DSW *p_object) {
- ERR_FAIL_COND( objects.has(p_object) );
+ ERR_FAIL_COND(objects.has(p_object));
objects.insert(p_object);
}
void Space2DSW::remove_object(CollisionObject2DSW *p_object) {
- ERR_FAIL_COND( !objects.has(p_object) );
+ ERR_FAIL_COND(!objects.has(p_object));
objects.erase(p_object);
}
-const Set<CollisionObject2DSW*> &Space2DSW::get_objects() const {
+const Set<CollisionObject2DSW *> &Space2DSW::get_objects() const {
return objects;
}
-void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW>* p_body) {
+void Space2DSW::body_add_to_state_query_list(SelfList<Body2DSW> *p_body) {
state_query_list.add(p_body);
}
-void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW>* p_body) {
+void Space2DSW::body_remove_from_state_query_list(SelfList<Body2DSW> *p_body) {
state_query_list.remove(p_body);
}
-void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW>* p_area) {
+void Space2DSW::area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area) {
monitor_query_list.add(p_area);
}
-void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW>* p_area) {
+void Space2DSW::area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area) {
monitor_query_list.remove(p_area);
}
-void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW>* p_area) {
+void Space2DSW::area_add_to_moved_list(SelfList<Area2DSW> *p_area) {
area_moved_list.add(p_area);
}
-void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW>* p_area) {
+void Space2DSW::area_remove_from_moved_list(SelfList<Area2DSW> *p_area) {
area_moved_list.remove(p_area);
}
-const SelfList<Area2DSW>::List& Space2DSW::get_moved_area_list() const {
+const SelfList<Area2DSW>::List &Space2DSW::get_moved_area_list() const {
return area_moved_list;
}
-
void Space2DSW::call_queries() {
- while(state_query_list.first()) {
+ while (state_query_list.first()) {
- Body2DSW * b = state_query_list.first()->self();
+ Body2DSW *b = state_query_list.first()->self();
b->call_queries();
state_query_list.remove(state_query_list.first());
}
- while(monitor_query_list.first()) {
+ while (monitor_query_list.first()) {
- Area2DSW * a = monitor_query_list.first()->self();
+ Area2DSW *a = monitor_query_list.first()->self();
a->call_queries();
monitor_query_list.remove(monitor_query_list.first());
}
-
}
void Space2DSW::setup() {
- contact_debug_count=0;
+ contact_debug_count = 0;
- while(inertia_update_list.first()) {
+ while (inertia_update_list.first()) {
inertia_update_list.first()->self()->update_inertias();
inertia_update_list.remove(inertia_update_list.first());
}
-
-
}
void Space2DSW::update() {
broadphase->update();
-
}
-
void Space2DSW::set_param(Physics2DServer::SpaceParameter p_param, real_t p_value) {
- switch(p_param) {
+ switch (p_param) {
- case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius=p_value; break;
- case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation=p_value; break;
- case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration=p_value; break;
- case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_treshold=p_value; break;
- case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_treshold=p_value; break;
- case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep=p_value; break;
- case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias=p_value; break;
+ case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: contact_recycle_radius = p_value; break;
+ case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: contact_max_separation = p_value; break;
+ case Physics2DServer::SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION: contact_max_allowed_penetration = p_value; break;
+ case Physics2DServer::SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD: body_linear_velocity_sleep_treshold = p_value; break;
+ case Physics2DServer::SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD: body_angular_velocity_sleep_treshold = p_value; break;
+ case Physics2DServer::SPACE_PARAM_BODY_TIME_TO_SLEEP: body_time_to_sleep = p_value; break;
+ case Physics2DServer::SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS: constraint_bias = p_value; break;
}
}
real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const {
- switch(p_param) {
+ switch (p_param) {
case Physics2DServer::SPACE_PARAM_CONTACT_RECYCLE_RADIUS: return contact_recycle_radius;
case Physics2DServer::SPACE_PARAM_CONTACT_MAX_SEPARATION: return contact_max_separation;
@@ -1305,12 +1208,12 @@ real_t Space2DSW::get_param(Physics2DServer::SpaceParameter p_param) const {
void Space2DSW::lock() {
- locked=true;
+ locked = true;
}
void Space2DSW::unlock() {
- locked=false;
+ locked = false;
}
bool Space2DSW::is_locked() const {
@@ -1325,43 +1228,36 @@ Physics2DDirectSpaceStateSW *Space2DSW::get_direct_state() {
Space2DSW::Space2DSW() {
+ collision_pairs = 0;
+ active_objects = 0;
+ island_count = 0;
- collision_pairs=0;
- active_objects=0;
- island_count=0;
+ contact_debug_count = 0;
- contact_debug_count=0;
-
- locked=false;
- contact_recycle_radius=1.0;
- contact_max_separation=1.5;
- contact_max_allowed_penetration= 0.3;
+ locked = false;
+ contact_recycle_radius = 1.0;
+ contact_max_separation = 1.5;
+ contact_max_allowed_penetration = 0.3;
constraint_bias = 0.2;
- body_linear_velocity_sleep_treshold=GLOBAL_DEF("physics/2d/sleep_threashold_linear",2.0);
- body_angular_velocity_sleep_treshold=GLOBAL_DEF("physics/2d/sleep_threshold_angular",(8.0 / 180.0 * Math_PI));
- body_time_to_sleep=GLOBAL_DEF("physics/2d/time_before_sleep",0.5);
-
+ body_linear_velocity_sleep_treshold = GLOBAL_DEF("physics/2d/sleep_threashold_linear", 2.0);
+ body_angular_velocity_sleep_treshold = GLOBAL_DEF("physics/2d/sleep_threshold_angular", (8.0 / 180.0 * Math_PI));
+ body_time_to_sleep = GLOBAL_DEF("physics/2d/time_before_sleep", 0.5);
broadphase = BroadPhase2DSW::create_func();
- broadphase->set_pair_callback(_broadphase_pair,this);
- broadphase->set_unpair_callback(_broadphase_unpair,this);
- area=NULL;
-
- direct_access = memnew( Physics2DDirectSpaceStateSW );
- direct_access->space=this;
-
+ broadphase->set_pair_callback(_broadphase_pair, this);
+ broadphase->set_unpair_callback(_broadphase_unpair, this);
+ area = NULL;
- for(int i=0;i<ELAPSED_TIME_MAX;i++)
- elapsed_time[i]=0;
+ direct_access = memnew(Physics2DDirectSpaceStateSW);
+ direct_access->space = this;
+ for (int i = 0; i < ELAPSED_TIME_MAX; i++)
+ elapsed_time[i] = 0;
}
Space2DSW::~Space2DSW() {
memdelete(broadphase);
- memdelete( direct_access );
+ memdelete(direct_access);
}
-
-
-
diff --git a/servers/physics_2d/space_2d_sw.h b/servers/physics_2d/space_2d_sw.h
index 071aa7bdfb..103f328ed2 100644
--- a/servers/physics_2d/space_2d_sw.h
+++ b/servers/physics_2d/space_2d_sw.h
@@ -29,40 +29,36 @@
#ifndef SPACE_2D_SW_H
#define SPACE_2D_SW_H
-#include "typedefs.h"
-#include "hash_map.h"
-#include "body_2d_sw.h"
#include "area_2d_sw.h"
-#include "body_pair_2d_sw.h"
#include "area_pair_2d_sw.h"
+#include "body_2d_sw.h"
+#include "body_pair_2d_sw.h"
#include "broad_phase_2d_sw.h"
#include "collision_object_2d_sw.h"
#include "global_config.h"
-
+#include "hash_map.h"
+#include "typedefs.h"
class Physics2DDirectSpaceStateSW : public Physics2DDirectSpaceState {
- GDCLASS( Physics2DDirectSpaceStateSW, Physics2DDirectSpaceState );
-public:
+ GDCLASS(Physics2DDirectSpaceStateSW, Physics2DDirectSpaceState);
+public:
Space2DSW *space;
- virtual int intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION, bool p_pick_point=false);
- virtual bool intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual int intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual bool cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,real_t p_margin,real_t &p_closest_safe,real_t &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual bool collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- virtual bool rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,real_t p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
+ virtual int intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_point = false);
+ virtual bool intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual int intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual bool cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, real_t p_margin, real_t &p_closest_safe, real_t &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual bool collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ virtual bool rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, real_t p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
Physics2DDirectSpaceStateSW();
};
-
-
class Space2DSW : public RID_Data {
public:
-
enum ElapsedTime {
ELAPSED_TIME_INTEGRATE_FORCES,
ELAPSED_TIME_GENERATE_ISLANDS,
@@ -72,8 +68,8 @@ public:
ELAPSED_TIME_MAX
};
-private:
+private:
uint64_t elapsed_time[ELAPSED_TIME_MAX];
Physics2DDirectSpaceStateSW *direct_access;
@@ -86,10 +82,10 @@ private:
SelfList<Area2DSW>::List monitor_query_list;
SelfList<Area2DSW>::List area_moved_list;
- static void* _broadphase_pair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_self);
- static void _broadphase_unpair(CollisionObject2DSW *A,int p_subindex_A,CollisionObject2DSW *B,int p_subindex_B,void *p_data,void *p_self);
+ static void *_broadphase_pair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_self);
+ static void _broadphase_unpair(CollisionObject2DSW *A, int p_subindex_A, CollisionObject2DSW *B, int p_subindex_B, void *p_data, void *p_self);
- Set<CollisionObject2DSW*> objects;
+ Set<CollisionObject2DSW *> objects;
Area2DSW *area;
@@ -100,7 +96,7 @@ private:
enum {
- INTERSECTION_QUERY_MAX=2048
+ INTERSECTION_QUERY_MAX = 2048
};
CollisionObject2DSW *intersection_query_results[INTERSECTION_QUERY_MAX];
@@ -116,44 +112,40 @@ private:
int active_objects;
int collision_pairs;
- int _cull_aabb_for_body(Body2DSW *p_body,const Rect2& p_aabb);
+ int _cull_aabb_for_body(Body2DSW *p_body, const Rect2 &p_aabb);
Vector<Vector2> contact_debug;
int contact_debug_count;
-friend class Physics2DDirectSpaceStateSW;
+ friend class Physics2DDirectSpaceStateSW;
public:
-
- _FORCE_INLINE_ void set_self(const RID& p_self) { self=p_self; }
+ _FORCE_INLINE_ void set_self(const RID &p_self) { self = p_self; }
_FORCE_INLINE_ RID get_self() const { return self; }
- void set_default_area(Area2DSW *p_area) { area=p_area; }
+ void set_default_area(Area2DSW *p_area) { area = p_area; }
Area2DSW *get_default_area() const { return area; }
- const SelfList<Body2DSW>::List& get_active_body_list() const;
- void body_add_to_active_list(SelfList<Body2DSW>* p_body);
- void body_remove_from_active_list(SelfList<Body2DSW>* p_body);
- void body_add_to_inertia_update_list(SelfList<Body2DSW>* p_body);
- void body_remove_from_inertia_update_list(SelfList<Body2DSW>* p_body);
- void area_add_to_moved_list(SelfList<Area2DSW>* p_area);
- void area_remove_from_moved_list(SelfList<Area2DSW>* p_area);
- const SelfList<Area2DSW>::List& get_moved_area_list() const;
-
-
-
+ const SelfList<Body2DSW>::List &get_active_body_list() const;
+ void body_add_to_active_list(SelfList<Body2DSW> *p_body);
+ void body_remove_from_active_list(SelfList<Body2DSW> *p_body);
+ void body_add_to_inertia_update_list(SelfList<Body2DSW> *p_body);
+ void body_remove_from_inertia_update_list(SelfList<Body2DSW> *p_body);
+ void area_add_to_moved_list(SelfList<Area2DSW> *p_area);
+ void area_remove_from_moved_list(SelfList<Area2DSW> *p_area);
+ const SelfList<Area2DSW>::List &get_moved_area_list() const;
- void body_add_to_state_query_list(SelfList<Body2DSW>* p_body);
- void body_remove_from_state_query_list(SelfList<Body2DSW>* p_body);
+ void body_add_to_state_query_list(SelfList<Body2DSW> *p_body);
+ void body_remove_from_state_query_list(SelfList<Body2DSW> *p_body);
- void area_add_to_monitor_query_list(SelfList<Area2DSW>* p_area);
- void area_remove_from_monitor_query_list(SelfList<Area2DSW>* p_area);
+ void area_add_to_monitor_query_list(SelfList<Area2DSW> *p_area);
+ void area_remove_from_monitor_query_list(SelfList<Area2DSW> *p_area);
BroadPhase2DSW *get_broadphase();
void add_object(CollisionObject2DSW *p_object);
void remove_object(CollisionObject2DSW *p_object);
- const Set<CollisionObject2DSW*> &get_objects() const;
+ const Set<CollisionObject2DSW *> &get_objects() const;
_FORCE_INLINE_ real_t get_contact_recycle_radius() const { return contact_recycle_radius; }
_FORCE_INLINE_ real_t get_contact_max_separation() const { return contact_max_separation; }
@@ -163,13 +155,10 @@ public:
_FORCE_INLINE_ real_t get_body_angular_velocity_sleep_treshold() const { return body_angular_velocity_sleep_treshold; }
_FORCE_INLINE_ real_t get_body_time_to_sleep() const { return body_time_to_sleep; }
-
-
void update();
void setup();
void call_queries();
-
bool is_locked() const;
void lock();
void unlock();
@@ -177,32 +166,31 @@ public:
void set_param(Physics2DServer::SpaceParameter p_param, real_t p_value);
real_t get_param(Physics2DServer::SpaceParameter p_param) const;
- void set_island_count(int p_island_count) { island_count=p_island_count; }
+ void set_island_count(int p_island_count) { island_count = p_island_count; }
int get_island_count() const { return island_count; }
- void set_active_objects(int p_active_objects) { active_objects=p_active_objects; }
+ void set_active_objects(int p_active_objects) { active_objects = p_active_objects; }
int get_active_objects() const { return active_objects; }
int get_collision_pairs() const { return collision_pairs; }
- bool test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2&p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result);
-
+ bool test_body_motion(Body2DSW *p_body, const Transform2D &p_from, const Vector2 &p_motion, real_t p_margin, Physics2DServer::MotionResult *r_result);
void set_debug_contacts(int p_amount) { contact_debug.resize(p_amount); }
_FORCE_INLINE_ bool is_debugging_contacts() const { return !contact_debug.empty(); }
- _FORCE_INLINE_ void add_debug_contact(const Vector2& p_contact) { if (contact_debug_count<contact_debug.size()) contact_debug[contact_debug_count++]=p_contact; }
+ _FORCE_INLINE_ void add_debug_contact(const Vector2 &p_contact) {
+ if (contact_debug_count < contact_debug.size()) contact_debug[contact_debug_count++] = p_contact;
+ }
_FORCE_INLINE_ Vector<Vector2> get_debug_contacts() { return contact_debug; }
_FORCE_INLINE_ int get_debug_contact_count() { return contact_debug_count; }
-
Physics2DDirectSpaceStateSW *get_direct_state();
- void set_elapsed_time(ElapsedTime p_time,uint64_t p_msec) { elapsed_time[p_time]=p_msec; }
+ void set_elapsed_time(ElapsedTime p_time, uint64_t p_msec) { elapsed_time[p_time] = p_msec; }
uint64_t get_elapsed_time(ElapsedTime p_time) const { return elapsed_time[p_time]; }
Space2DSW();
~Space2DSW();
};
-
#endif // SPACE_2D_SW_H
diff --git a/servers/physics_2d/step_2d_sw.cpp b/servers/physics_2d/step_2d_sw.cpp
index 355cc25a69..55bc62975f 100644
--- a/servers/physics_2d/step_2d_sw.cpp
+++ b/servers/physics_2d/step_2d_sw.cpp
@@ -29,39 +29,38 @@
#include "step_2d_sw.h"
#include "os/os.h"
-void Step2DSW::_populate_island(Body2DSW* p_body,Body2DSW** p_island,Constraint2DSW **p_constraint_island) {
+void Step2DSW::_populate_island(Body2DSW *p_body, Body2DSW **p_island, Constraint2DSW **p_constraint_island) {
p_body->set_island_step(_step);
p_body->set_island_next(*p_island);
- *p_island=p_body;
+ *p_island = p_body;
- for(Map<Constraint2DSW*,int>::Element *E=p_body->get_constraint_map().front();E;E=E->next()) {
+ for (Map<Constraint2DSW *, int>::Element *E = p_body->get_constraint_map().front(); E; E = E->next()) {
- Constraint2DSW *c=(Constraint2DSW*)E->key();
- if (c->get_island_step()==_step)
+ Constraint2DSW *c = (Constraint2DSW *)E->key();
+ if (c->get_island_step() == _step)
continue; //already processed
c->set_island_step(_step);
c->set_island_next(*p_constraint_island);
- *p_constraint_island=c;
+ *p_constraint_island = c;
-
- for(int i=0;i<c->get_body_count();i++) {
- if (i==E->get())
+ for (int i = 0; i < c->get_body_count(); i++) {
+ if (i == E->get())
continue;
Body2DSW *b = c->get_body_ptr()[i];
- if (b->get_island_step()==_step || b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC)
+ if (b->get_island_step() == _step || b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC)
continue; //no go
- _populate_island(c->get_body_ptr()[i],p_island,p_constraint_island);
+ _populate_island(c->get_body_ptr()[i], p_island, p_constraint_island);
}
}
}
-bool Step2DSW::_setup_island(Constraint2DSW *p_island,real_t p_delta) {
+bool Step2DSW::_setup_island(Constraint2DSW *p_island, real_t p_delta) {
- Constraint2DSW *ci=p_island;
- Constraint2DSW *prev_ci=NULL;
- bool removed_root=false;
- while(ci) {
+ Constraint2DSW *ci = p_island;
+ Constraint2DSW *prev_ci = NULL;
+ bool removed_root = false;
+ while (ci) {
bool process = ci->setup(p_delta);
if (!process) {
@@ -69,169 +68,161 @@ bool Step2DSW::_setup_island(Constraint2DSW *p_island,real_t p_delta) {
if (prev_ci) {
prev_ci->set_island_next(ci->get_island_next());
} else {
- removed_root=true;
- prev_ci=ci;
+ removed_root = true;
+ prev_ci = ci;
}
} else {
- prev_ci=ci;
+ prev_ci = ci;
}
- ci=ci->get_island_next();
+ ci = ci->get_island_next();
}
return removed_root;
}
-void Step2DSW::_solve_island(Constraint2DSW *p_island,int p_iterations,real_t p_delta){
-
+void Step2DSW::_solve_island(Constraint2DSW *p_island, int p_iterations, real_t p_delta) {
- for(int i=0;i<p_iterations;i++) {
+ for (int i = 0; i < p_iterations; i++) {
- Constraint2DSW *ci=p_island;
- while(ci) {
+ Constraint2DSW *ci = p_island;
+ while (ci) {
ci->solve(p_delta);
- ci=ci->get_island_next();
+ ci = ci->get_island_next();
}
}
}
-void Step2DSW::_check_suspend(Body2DSW *p_island,real_t p_delta) {
+void Step2DSW::_check_suspend(Body2DSW *p_island, real_t p_delta) {
-
- bool can_sleep=true;
+ bool can_sleep = true;
Body2DSW *b = p_island;
- while(b) {
+ while (b) {
- if (b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) {
- b=b->get_island_next();
+ if (b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) {
+ b = b->get_island_next();
continue; //ignore for static
}
if (!b->sleep_test(p_delta))
- can_sleep=false;
+ can_sleep = false;
- b=b->get_island_next();
+ b = b->get_island_next();
}
//put all to sleep or wake up everyoen
b = p_island;
- while(b) {
+ while (b) {
- if (b->get_mode()==Physics2DServer::BODY_MODE_STATIC || b->get_mode()==Physics2DServer::BODY_MODE_KINEMATIC) {
- b=b->get_island_next();
+ if (b->get_mode() == Physics2DServer::BODY_MODE_STATIC || b->get_mode() == Physics2DServer::BODY_MODE_KINEMATIC) {
+ b = b->get_island_next();
continue; //ignore for static
}
bool active = b->is_active();
- if (active==can_sleep)
+ if (active == can_sleep)
b->set_active(!can_sleep);
- b=b->get_island_next();
+ b = b->get_island_next();
}
}
-void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) {
-
+void Step2DSW::step(Space2DSW *p_space, real_t p_delta, int p_iterations) {
p_space->lock(); // can't access space during this
p_space->setup(); //update inertias, etc
- const SelfList<Body2DSW>::List * body_list = &p_space->get_active_body_list();
+ const SelfList<Body2DSW>::List *body_list = &p_space->get_active_body_list();
/* INTEGRATE FORCES */
uint64_t profile_begtime = OS::get_singleton()->get_ticks_usec();
- uint64_t profile_endtime=0;
+ uint64_t profile_endtime = 0;
+ int active_count = 0;
- int active_count=0;
-
- const SelfList<Body2DSW>*b = body_list->first();
- while(b) {
+ const SelfList<Body2DSW> *b = body_list->first();
+ while (b) {
b->self()->integrate_forces(p_delta);
- b=b->next();
+ b = b->next();
active_count++;
}
p_space->set_active_objects(active_count);
-
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_FORCES,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_FORCES, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* GENERATE CONSTRAINT ISLANDS */
- Body2DSW *island_list=NULL;
- Constraint2DSW *constraint_island_list=NULL;
+ Body2DSW *island_list = NULL;
+ Constraint2DSW *constraint_island_list = NULL;
b = body_list->first();
- int island_count=0;
+ int island_count = 0;
- while(b) {
+ while (b) {
Body2DSW *body = b->self();
+ if (body->get_island_step() != _step) {
- if (body->get_island_step()!=_step) {
-
- Body2DSW *island=NULL;
- Constraint2DSW *constraint_island=NULL;
- _populate_island(body,&island,&constraint_island);
+ Body2DSW *island = NULL;
+ Constraint2DSW *constraint_island = NULL;
+ _populate_island(body, &island, &constraint_island);
island->set_island_list_next(island_list);
- island_list=island;
+ island_list = island;
if (constraint_island) {
constraint_island->set_island_list_next(constraint_island_list);
- constraint_island_list=constraint_island;
+ constraint_island_list = constraint_island;
island_count++;
}
-
}
- b=b->next();
+ b = b->next();
}
p_space->set_island_count(island_count);
const SelfList<Area2DSW>::List &aml = p_space->get_moved_area_list();
+ while (aml.first()) {
+ for (const Set<Constraint2DSW *>::Element *E = aml.first()->self()->get_constraints().front(); E; E = E->next()) {
- while(aml.first()) {
- for(const Set<Constraint2DSW*>::Element *E=aml.first()->self()->get_constraints().front();E;E=E->next()) {
-
- Constraint2DSW*c=E->get();
- if (c->get_island_step()==_step)
+ Constraint2DSW *c = E->get();
+ if (c->get_island_step() == _step)
continue;
c->set_island_step(_step);
c->set_island_next(NULL);
c->set_island_list_next(constraint_island_list);
- constraint_island_list=c;
+ constraint_island_list = c;
}
- p_space->area_remove_from_moved_list((SelfList<Area2DSW>*)aml.first()); //faster to remove here
+ p_space->area_remove_from_moved_list((SelfList<Area2DSW> *)aml.first()); //faster to remove here
}
//print_line("island count: "+itos(island_count)+" active count: "+itos(active_count));
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_GENERATE_ISLANDS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_GENERATE_ISLANDS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* SETUP CONSTRAINT ISLANDS */
{
- Constraint2DSW *ci=constraint_island_list;
- Constraint2DSW *prev_ci=NULL;
- while(ci) {
+ Constraint2DSW *ci = constraint_island_list;
+ Constraint2DSW *prev_ci = NULL;
+ while (ci) {
- if (_setup_island(ci,p_delta)==true) {
+ if (_setup_island(ci, p_delta) == true) {
//removed the root from the island graph because it is not to be processed
@@ -243,10 +234,9 @@ void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) {
if (prev_ci) {
prev_ci->set_island_list_next(next);
} else {
- constraint_island_list=next;
-
+ constraint_island_list = next;
}
- prev_ci=next;
+ prev_ci = next;
} else {
//list is empty, just skip
@@ -254,77 +244,73 @@ void Step2DSW::step(Space2DSW* p_space,real_t p_delta,int p_iterations) {
prev_ci->set_island_list_next(ci->get_island_list_next());
} else {
- constraint_island_list=ci->get_island_list_next();
+ constraint_island_list = ci->get_island_list_next();
}
-
}
} else {
- prev_ci=ci;
+ prev_ci = ci;
}
- ci=ci->get_island_list_next();
+ ci = ci->get_island_list_next();
}
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SETUP_CONSTRAINTS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SETUP_CONSTRAINTS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* SOLVE CONSTRAINT ISLANDS */
{
- Constraint2DSW *ci=constraint_island_list;
- while(ci) {
+ Constraint2DSW *ci = constraint_island_list;
+ while (ci) {
//iterating each island separatedly improves cache efficiency
- _solve_island(ci,p_iterations,p_delta);
- ci=ci->get_island_list_next();
+ _solve_island(ci, p_iterations, p_delta);
+ ci = ci->get_island_list_next();
}
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SOLVE_CONSTRAINTS,profile_endtime-profile_begtime);
- profile_begtime=profile_endtime;
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_SOLVE_CONSTRAINTS, profile_endtime - profile_begtime);
+ profile_begtime = profile_endtime;
}
/* INTEGRATE VELOCITIES */
b = body_list->first();
- while(b) {
+ while (b) {
- const SelfList<Body2DSW>*n=b->next();
+ const SelfList<Body2DSW> *n = b->next();
b->self()->integrate_velocities(p_delta);
- b=n; // in case it shuts itself down
+ b = n; // in case it shuts itself down
}
/* SLEEP / WAKE UP ISLANDS */
{
- Body2DSW *bi=island_list;
- while(bi) {
+ Body2DSW *bi = island_list;
+ while (bi) {
- _check_suspend(bi,p_delta);
- bi=bi->get_island_list_next();
+ _check_suspend(bi, p_delta);
+ bi = bi->get_island_list_next();
}
}
{ //profile
- profile_endtime=OS::get_singleton()->get_ticks_usec();
- p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_VELOCITIES,profile_endtime-profile_begtime);
+ profile_endtime = OS::get_singleton()->get_ticks_usec();
+ p_space->set_elapsed_time(Space2DSW::ELAPSED_TIME_INTEGRATE_VELOCITIES, profile_endtime - profile_begtime);
//profile_begtime=profile_endtime;
}
p_space->update();
p_space->unlock();
_step++;
-
-
-
}
Step2DSW::Step2DSW() {
- _step=1;
+ _step = 1;
}
diff --git a/servers/physics_2d/step_2d_sw.h b/servers/physics_2d/step_2d_sw.h
index 0896e1016d..c743358b6a 100644
--- a/servers/physics_2d/step_2d_sw.h
+++ b/servers/physics_2d/step_2d_sw.h
@@ -35,13 +35,13 @@ class Step2DSW {
uint64_t _step;
- void _populate_island(Body2DSW* p_body,Body2DSW** p_island,Constraint2DSW **p_constraint_island);
- bool _setup_island(Constraint2DSW *p_island,real_t p_delta);
- void _solve_island(Constraint2DSW *p_island,int p_iterations,real_t p_delta);
- void _check_suspend(Body2DSW *p_island,real_t p_delta);
-public:
+ void _populate_island(Body2DSW *p_body, Body2DSW **p_island, Constraint2DSW **p_constraint_island);
+ bool _setup_island(Constraint2DSW *p_island, real_t p_delta);
+ void _solve_island(Constraint2DSW *p_island, int p_iterations, real_t p_delta);
+ void _check_suspend(Body2DSW *p_island, real_t p_delta);
- void step(Space2DSW* p_space,real_t p_delta,int p_iterations);
+public:
+ void step(Space2DSW *p_space, real_t p_delta, int p_iterations);
Step2DSW();
};
diff --git a/servers/physics_2d_server.cpp b/servers/physics_2d_server.cpp
index bdbe85612f..f922b8f7a1 100644
--- a/servers/physics_2d_server.cpp
+++ b/servers/physics_2d_server.cpp
@@ -28,103 +28,97 @@
/*************************************************************************/
#include "physics_2d_server.h"
#include "print_string.h"
-Physics2DServer * Physics2DServer::singleton=NULL;
-
+Physics2DServer *Physics2DServer::singleton = NULL;
void Physics2DDirectBodyState::integrate_forces() {
real_t step = get_step();
Vector2 lv = get_linear_velocity();
- lv+=get_total_gravity() * step;
+ lv += get_total_gravity() * step;
real_t av = get_angular_velocity();
float damp = 1.0 - step * get_total_linear_damp();
- if (damp<0) // reached zero in the given time
- damp=0;
+ if (damp < 0) // reached zero in the given time
+ damp = 0;
- lv*=damp;
+ lv *= damp;
damp = 1.0 - step * get_total_angular_damp();
- if (damp<0) // reached zero in the given time
- damp=0;
+ if (damp < 0) // reached zero in the given time
+ damp = 0;
- av*=damp;
+ av *= damp;
set_linear_velocity(lv);
set_angular_velocity(av);
-
-
}
-Object* Physics2DDirectBodyState::get_contact_collider_object(int p_contact_idx) const {
+Object *Physics2DDirectBodyState::get_contact_collider_object(int p_contact_idx) const {
ObjectID objid = get_contact_collider_id(p_contact_idx);
- Object *obj = ObjectDB::get_instance( objid );
+ Object *obj = ObjectDB::get_instance(objid);
return obj;
}
-Physics2DServer * Physics2DServer::get_singleton() {
+Physics2DServer *Physics2DServer::get_singleton() {
return singleton;
}
void Physics2DDirectBodyState::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_total_gravity"),&Physics2DDirectBodyState::get_total_gravity);
- ClassDB::bind_method(D_METHOD("get_total_linear_damp"),&Physics2DDirectBodyState::get_total_linear_damp);
- ClassDB::bind_method(D_METHOD("get_total_angular_damp"),&Physics2DDirectBodyState::get_total_angular_damp);
+ ClassDB::bind_method(D_METHOD("get_total_gravity"), &Physics2DDirectBodyState::get_total_gravity);
+ ClassDB::bind_method(D_METHOD("get_total_linear_damp"), &Physics2DDirectBodyState::get_total_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_total_angular_damp"), &Physics2DDirectBodyState::get_total_angular_damp);
- ClassDB::bind_method(D_METHOD("get_inverse_mass"),&Physics2DDirectBodyState::get_inverse_mass);
- ClassDB::bind_method(D_METHOD("get_inverse_inertia"),&Physics2DDirectBodyState::get_inverse_inertia);
+ ClassDB::bind_method(D_METHOD("get_inverse_mass"), &Physics2DDirectBodyState::get_inverse_mass);
+ ClassDB::bind_method(D_METHOD("get_inverse_inertia"), &Physics2DDirectBodyState::get_inverse_inertia);
- ClassDB::bind_method(D_METHOD("set_linear_velocity","velocity"),&Physics2DDirectBodyState::set_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"),&Physics2DDirectBodyState::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "velocity"), &Physics2DDirectBodyState::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &Physics2DDirectBodyState::get_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_angular_velocity","velocity"),&Physics2DDirectBodyState::set_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_angular_velocity"),&Physics2DDirectBodyState::get_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "velocity"), &Physics2DDirectBodyState::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &Physics2DDirectBodyState::get_angular_velocity);
- ClassDB::bind_method(D_METHOD("set_transform","transform"),&Physics2DDirectBodyState::set_transform);
- ClassDB::bind_method(D_METHOD("get_transform"),&Physics2DDirectBodyState::get_transform);
+ ClassDB::bind_method(D_METHOD("set_transform", "transform"), &Physics2DDirectBodyState::set_transform);
+ ClassDB::bind_method(D_METHOD("get_transform"), &Physics2DDirectBodyState::get_transform);
- ClassDB::bind_method(D_METHOD("set_sleep_state","enabled"),&Physics2DDirectBodyState::set_sleep_state);
- ClassDB::bind_method(D_METHOD("is_sleeping"),&Physics2DDirectBodyState::is_sleeping);
+ ClassDB::bind_method(D_METHOD("set_sleep_state", "enabled"), &Physics2DDirectBodyState::set_sleep_state);
+ ClassDB::bind_method(D_METHOD("is_sleeping"), &Physics2DDirectBodyState::is_sleeping);
- ClassDB::bind_method(D_METHOD("get_contact_count"),&Physics2DDirectBodyState::get_contact_count);
-
- ClassDB::bind_method(D_METHOD("get_contact_local_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_local_pos);
- ClassDB::bind_method(D_METHOD("get_contact_local_normal","contact_idx"),&Physics2DDirectBodyState::get_contact_local_normal);
- ClassDB::bind_method(D_METHOD("get_contact_local_shape","contact_idx"),&Physics2DDirectBodyState::get_contact_local_shape);
- ClassDB::bind_method(D_METHOD("get_contact_collider","contact_idx"),&Physics2DDirectBodyState::get_contact_collider);
- ClassDB::bind_method(D_METHOD("get_contact_collider_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_pos);
- ClassDB::bind_method(D_METHOD("get_contact_collider_id","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_id);
- ClassDB::bind_method(D_METHOD("get_contact_collider_object","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_object);
- ClassDB::bind_method(D_METHOD("get_contact_collider_shape","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_shape);
- ClassDB::bind_method(D_METHOD("get_contact_collider_shape_metadata:Variant","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_shape_metadata);
- ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos","contact_idx"),&Physics2DDirectBodyState::get_contact_collider_velocity_at_pos);
- ClassDB::bind_method(D_METHOD("get_step"),&Physics2DDirectBodyState::get_step);
- ClassDB::bind_method(D_METHOD("integrate_forces"),&Physics2DDirectBodyState::integrate_forces);
- ClassDB::bind_method(D_METHOD("get_space_state:Physics2DDirectSpaceState"),&Physics2DDirectBodyState::get_space_state);
+ ClassDB::bind_method(D_METHOD("get_contact_count"), &Physics2DDirectBodyState::get_contact_count);
+ ClassDB::bind_method(D_METHOD("get_contact_local_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_pos);
+ ClassDB::bind_method(D_METHOD("get_contact_local_normal", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_normal);
+ ClassDB::bind_method(D_METHOD("get_contact_local_shape", "contact_idx"), &Physics2DDirectBodyState::get_contact_local_shape);
+ ClassDB::bind_method(D_METHOD("get_contact_collider", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_pos);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_id", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_id);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_object", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_object);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_shape", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_shape);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_shape_metadata:Variant", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_shape_metadata);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos", "contact_idx"), &Physics2DDirectBodyState::get_contact_collider_velocity_at_pos);
+ ClassDB::bind_method(D_METHOD("get_step"), &Physics2DDirectBodyState::get_step);
+ ClassDB::bind_method(D_METHOD("integrate_forces"), &Physics2DDirectBodyState::integrate_forces);
+ ClassDB::bind_method(D_METHOD("get_space_state:Physics2DDirectSpaceState"), &Physics2DDirectBodyState::get_space_state);
}
Physics2DDirectBodyState::Physics2DDirectBodyState() {}
///////////////////////////////////////////////////////
-
-
void Physics2DShapeQueryParameters::set_shape(const RES &p_shape) {
ERR_FAIL_COND(p_shape.is_null());
- shape=p_shape->get_rid();
+ shape = p_shape->get_rid();
}
-void Physics2DShapeQueryParameters::set_shape_rid(const RID& p_shape) {
+void Physics2DShapeQueryParameters::set_shape_rid(const RID &p_shape) {
- shape=p_shape;
+ shape = p_shape;
}
RID Physics2DShapeQueryParameters::get_shape_rid() const {
@@ -132,125 +126,120 @@ RID Physics2DShapeQueryParameters::get_shape_rid() const {
return shape;
}
-void Physics2DShapeQueryParameters::set_transform(const Transform2D& p_transform){
+void Physics2DShapeQueryParameters::set_transform(const Transform2D &p_transform) {
- transform=p_transform;
+ transform = p_transform;
}
-Transform2D Physics2DShapeQueryParameters::get_transform() const{
+Transform2D Physics2DShapeQueryParameters::get_transform() const {
return transform;
}
-void Physics2DShapeQueryParameters::set_motion(const Vector2& p_motion){
+void Physics2DShapeQueryParameters::set_motion(const Vector2 &p_motion) {
- motion=p_motion;
+ motion = p_motion;
}
-Vector2 Physics2DShapeQueryParameters::get_motion() const{
+Vector2 Physics2DShapeQueryParameters::get_motion() const {
return motion;
}
-void Physics2DShapeQueryParameters::set_margin(float p_margin){
+void Physics2DShapeQueryParameters::set_margin(float p_margin) {
- margin=p_margin;
+ margin = p_margin;
}
-float Physics2DShapeQueryParameters::get_margin() const{
+float Physics2DShapeQueryParameters::get_margin() const {
return margin;
}
-void Physics2DShapeQueryParameters::set_layer_mask(int p_layer_mask){
+void Physics2DShapeQueryParameters::set_layer_mask(int p_layer_mask) {
- layer_mask=p_layer_mask;
+ layer_mask = p_layer_mask;
}
-int Physics2DShapeQueryParameters::get_layer_mask() const{
+int Physics2DShapeQueryParameters::get_layer_mask() const {
return layer_mask;
}
+void Physics2DShapeQueryParameters::set_object_type_mask(int p_object_type_mask) {
-void Physics2DShapeQueryParameters::set_object_type_mask(int p_object_type_mask){
-
- object_type_mask=p_object_type_mask;
+ object_type_mask = p_object_type_mask;
}
-int Physics2DShapeQueryParameters::get_object_type_mask() const{
+int Physics2DShapeQueryParameters::get_object_type_mask() const {
return object_type_mask;
}
-void Physics2DShapeQueryParameters::set_exclude(const Vector<RID>& p_exclude) {
+void Physics2DShapeQueryParameters::set_exclude(const Vector<RID> &p_exclude) {
exclude.clear();
- for(int i=0;i<p_exclude.size();i++)
+ for (int i = 0; i < p_exclude.size(); i++)
exclude.insert(p_exclude[i]);
-
}
-Vector<RID> Physics2DShapeQueryParameters::get_exclude() const{
+Vector<RID> Physics2DShapeQueryParameters::get_exclude() const {
Vector<RID> ret;
ret.resize(exclude.size());
- int idx=0;
- for(Set<RID>::Element *E=exclude.front();E;E=E->next()) {
- ret[idx]=E->get();
+ int idx = 0;
+ for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) {
+ ret[idx] = E->get();
}
return ret;
}
void Physics2DShapeQueryParameters::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shape","shape:Shape2D"),&Physics2DShapeQueryParameters::set_shape);
- ClassDB::bind_method(D_METHOD("set_shape_rid","shape"),&Physics2DShapeQueryParameters::set_shape_rid);
- ClassDB::bind_method(D_METHOD("get_shape_rid"),&Physics2DShapeQueryParameters::get_shape_rid);
-
- ClassDB::bind_method(D_METHOD("set_transform","transform"),&Physics2DShapeQueryParameters::set_transform);
- ClassDB::bind_method(D_METHOD("get_transform"),&Physics2DShapeQueryParameters::get_transform);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape:Shape2D"), &Physics2DShapeQueryParameters::set_shape);
+ ClassDB::bind_method(D_METHOD("set_shape_rid", "shape"), &Physics2DShapeQueryParameters::set_shape_rid);
+ ClassDB::bind_method(D_METHOD("get_shape_rid"), &Physics2DShapeQueryParameters::get_shape_rid);
- ClassDB::bind_method(D_METHOD("set_motion","motion"),&Physics2DShapeQueryParameters::set_motion);
- ClassDB::bind_method(D_METHOD("get_motion"),&Physics2DShapeQueryParameters::get_motion);
+ ClassDB::bind_method(D_METHOD("set_transform", "transform"), &Physics2DShapeQueryParameters::set_transform);
+ ClassDB::bind_method(D_METHOD("get_transform"), &Physics2DShapeQueryParameters::get_transform);
- ClassDB::bind_method(D_METHOD("set_margin","margin"),&Physics2DShapeQueryParameters::set_margin);
- ClassDB::bind_method(D_METHOD("get_margin"),&Physics2DShapeQueryParameters::get_margin);
+ ClassDB::bind_method(D_METHOD("set_motion", "motion"), &Physics2DShapeQueryParameters::set_motion);
+ ClassDB::bind_method(D_METHOD("get_motion"), &Physics2DShapeQueryParameters::get_motion);
- ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&Physics2DShapeQueryParameters::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&Physics2DShapeQueryParameters::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_margin", "margin"), &Physics2DShapeQueryParameters::set_margin);
+ ClassDB::bind_method(D_METHOD("get_margin"), &Physics2DShapeQueryParameters::get_margin);
- ClassDB::bind_method(D_METHOD("set_object_type_mask","object_type_mask"),&Physics2DShapeQueryParameters::set_object_type_mask);
- ClassDB::bind_method(D_METHOD("get_object_type_mask"),&Physics2DShapeQueryParameters::get_object_type_mask);
-
- ClassDB::bind_method(D_METHOD("set_exclude","exclude"),&Physics2DShapeQueryParameters::set_exclude);
- ClassDB::bind_method(D_METHOD("get_exclude"),&Physics2DShapeQueryParameters::get_exclude);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &Physics2DShapeQueryParameters::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &Physics2DShapeQueryParameters::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_object_type_mask", "object_type_mask"), &Physics2DShapeQueryParameters::set_object_type_mask);
+ ClassDB::bind_method(D_METHOD("get_object_type_mask"), &Physics2DShapeQueryParameters::get_object_type_mask);
+ ClassDB::bind_method(D_METHOD("set_exclude", "exclude"), &Physics2DShapeQueryParameters::set_exclude);
+ ClassDB::bind_method(D_METHOD("get_exclude"), &Physics2DShapeQueryParameters::get_exclude);
}
Physics2DShapeQueryParameters::Physics2DShapeQueryParameters() {
- margin=0;
- layer_mask=0x7FFFFFFF;
- object_type_mask=Physics2DDirectSpaceState::TYPE_MASK_COLLISION;
+ margin = 0;
+ layer_mask = 0x7FFFFFFF;
+ object_type_mask = Physics2DDirectSpaceState::TYPE_MASK_COLLISION;
}
-
-Dictionary Physics2DDirectSpaceState::_intersect_ray(const Vector2& p_from, const Vector2& p_to,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) {
+Dictionary Physics2DDirectSpaceState::_intersect_ray(const Vector2 &p_from, const Vector2 &p_to, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) {
RayResult inters;
Set<RID> exclude;
- for(int i=0;i<p_exclude.size();i++)
+ for (int i = 0; i < p_exclude.size(); i++)
exclude.insert(p_exclude[i]);
- bool res = intersect_ray(p_from,p_to,inters,exclude,p_layers,p_object_type_mask);
+ bool res = intersect_ray(p_from, p_to, inters, exclude, p_layers, p_object_type_mask);
if (!res)
return Dictionary();
Dictionary d;
- d["position"]=inters.position;
- d["normal"]=inters.normal;
- d["collider_id"]=inters.collider_id;
- d["collider"]=inters.collider;
- d["shape"]=inters.shape;
- d["rid"]=inters.rid;
- d["metadata"]=inters.metadata;
+ d["position"] = inters.position;
+ d["normal"] = inters.normal;
+ d["collider_id"] = inters.collider_id;
+ d["collider"] = inters.collider;
+ d["shape"] = inters.shape;
+ d["rid"] = inters.rid;
+ d["metadata"] = inters.metadata;
return d;
}
@@ -259,131 +248,119 @@ Array Physics2DDirectSpaceState::_intersect_shape(const Ref<Physics2DShapeQueryP
Vector<ShapeResult> sr;
sr.resize(p_max_results);
- int rc = intersect_shape(psq->shape,psq->transform,psq->motion,psq->margin,sr.ptr(),sr.size(),psq->exclude,psq->layer_mask,psq->object_type_mask);
+ int rc = intersect_shape(psq->shape, psq->transform, psq->motion, psq->margin, sr.ptr(), sr.size(), psq->exclude, psq->layer_mask, psq->object_type_mask);
Array ret;
ret.resize(rc);
- for(int i=0;i<rc;i++) {
+ for (int i = 0; i < rc; i++) {
Dictionary d;
- d["rid"]=sr[i].rid;
- d["collider_id"]=sr[i].collider_id;
- d["collider"]=sr[i].collider;
- d["shape"]=sr[i].shape;
- d["metadata"]=sr[i].metadata;
- ret[i]=d;
+ d["rid"] = sr[i].rid;
+ d["collider_id"] = sr[i].collider_id;
+ d["collider"] = sr[i].collider;
+ d["shape"] = sr[i].shape;
+ d["metadata"] = sr[i].metadata;
+ ret[i] = d;
}
return ret;
}
-Array Physics2DDirectSpaceState::_cast_motion(const Ref<Physics2DShapeQueryParameters> &psq){
+Array Physics2DDirectSpaceState::_cast_motion(const Ref<Physics2DShapeQueryParameters> &psq) {
- float closest_safe,closest_unsafe;
- bool res = cast_motion(psq->shape,psq->transform,psq->motion,psq->margin,closest_safe,closest_unsafe,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ float closest_safe, closest_unsafe;
+ bool res = cast_motion(psq->shape, psq->transform, psq->motion, psq->margin, closest_safe, closest_unsafe, psq->exclude, psq->layer_mask, psq->object_type_mask);
if (!res)
return Array();
Array ret;
ret.resize(2);
- ret[0]=closest_safe;
- ret[1]=closest_unsafe;
+ ret[0] = closest_safe;
+ ret[1] = closest_unsafe;
return ret;
-
}
-Array Physics2DDirectSpaceState::_intersect_point(const Vector2& p_point,int p_max_results,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) {
+Array Physics2DDirectSpaceState::_intersect_point(const Vector2 &p_point, int p_max_results, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) {
Set<RID> exclude;
- for(int i=0;i<p_exclude.size();i++)
+ for (int i = 0; i < p_exclude.size(); i++)
exclude.insert(p_exclude[i]);
Vector<ShapeResult> ret;
ret.resize(p_max_results);
- int rc = intersect_point(p_point,ret.ptr(),ret.size(),exclude,p_layers,p_object_type_mask);
- if (rc==0)
+ int rc = intersect_point(p_point, ret.ptr(), ret.size(), exclude, p_layers, p_object_type_mask);
+ if (rc == 0)
return Array();
Array r;
r.resize(rc);
- for(int i=0;i<rc;i++) {
+ for (int i = 0; i < rc; i++) {
Dictionary d;
- d["rid"]=ret[i].rid;
- d["collider_id"]=ret[i].collider_id;
- d["collider"]=ret[i].collider;
- d["shape"]=ret[i].shape;
- d["metadata"]=ret[i].metadata;
- r[i]=d;
+ d["rid"] = ret[i].rid;
+ d["collider_id"] = ret[i].collider_id;
+ d["collider"] = ret[i].collider;
+ d["shape"] = ret[i].shape;
+ d["metadata"] = ret[i].metadata;
+ r[i] = d;
}
return r;
-
}
-Array Physics2DDirectSpaceState::_collide_shape(const Ref<Physics2DShapeQueryParameters> &psq, int p_max_results){
+Array Physics2DDirectSpaceState::_collide_shape(const Ref<Physics2DShapeQueryParameters> &psq, int p_max_results) {
Vector<Vector2> ret;
- ret.resize(p_max_results*2);
- int rc=0;
- bool res = collide_shape(psq->shape,psq->transform,psq->motion,psq->margin,ret.ptr(),p_max_results,rc,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ ret.resize(p_max_results * 2);
+ int rc = 0;
+ bool res = collide_shape(psq->shape, psq->transform, psq->motion, psq->margin, ret.ptr(), p_max_results, rc, psq->exclude, psq->layer_mask, psq->object_type_mask);
if (!res)
return Array();
Array r;
- r.resize(rc*2);
- for(int i=0;i<rc*2;i++)
- r[i]=ret[i];
+ r.resize(rc * 2);
+ for (int i = 0; i < rc * 2; i++)
+ r[i] = ret[i];
return r;
-
}
-Dictionary Physics2DDirectSpaceState::_get_rest_info(const Ref<Physics2DShapeQueryParameters> &psq){
+Dictionary Physics2DDirectSpaceState::_get_rest_info(const Ref<Physics2DShapeQueryParameters> &psq) {
ShapeRestInfo sri;
- bool res = rest_info(psq->shape,psq->transform,psq->motion,psq->margin,&sri,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ bool res = rest_info(psq->shape, psq->transform, psq->motion, psq->margin, &sri, psq->exclude, psq->layer_mask, psq->object_type_mask);
Dictionary r;
if (!res)
return r;
- r["point"]=sri.point;
- r["normal"]=sri.normal;
- r["rid"]=sri.rid;
- r["collider_id"]=sri.collider_id;
- r["shape"]=sri.shape;
- r["linear_velocity"]=sri.linear_velocity;
- r["metadata"]=sri.metadata;
+ r["point"] = sri.point;
+ r["normal"] = sri.normal;
+ r["rid"] = sri.rid;
+ r["collider_id"] = sri.collider_id;
+ r["shape"] = sri.shape;
+ r["linear_velocity"] = sri.linear_velocity;
+ r["metadata"] = sri.metadata;
return r;
}
-
-
Physics2DDirectSpaceState::Physics2DDirectSpaceState() {
-
-
-
}
-
void Physics2DDirectSpaceState::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("intersect_point","point","max_results","exclude","layer_mask","type_mask"),&Physics2DDirectSpaceState::_intersect_point,DEFVAL(32),DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION));
- ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary","from","to","exclude","layer_mask","type_mask"),&Physics2DDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION));
- ClassDB::bind_method(D_METHOD("intersect_shape","shape:Physics2DShapeQueryParameters","max_results"),&Physics2DDirectSpaceState::_intersect_shape,DEFVAL(32));
- ClassDB::bind_method(D_METHOD("cast_motion","shape:Physics2DShapeQueryParameters"),&Physics2DDirectSpaceState::_cast_motion);
- ClassDB::bind_method(D_METHOD("collide_shape","shape:Physics2DShapeQueryParameters","max_results"),&Physics2DDirectSpaceState::_collide_shape,DEFVAL(32));
- ClassDB::bind_method(D_METHOD("get_rest_info","shape:Physics2DShapeQueryParameters"),&Physics2DDirectSpaceState::_get_rest_info);
+ ClassDB::bind_method(D_METHOD("intersect_point", "point", "max_results", "exclude", "layer_mask", "type_mask"), &Physics2DDirectSpaceState::_intersect_point, DEFVAL(32), DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION));
+ ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary", "from", "to", "exclude", "layer_mask", "type_mask"), &Physics2DDirectSpaceState::_intersect_ray, DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION));
+ ClassDB::bind_method(D_METHOD("intersect_shape", "shape:Physics2DShapeQueryParameters", "max_results"), &Physics2DDirectSpaceState::_intersect_shape, DEFVAL(32));
+ ClassDB::bind_method(D_METHOD("cast_motion", "shape:Physics2DShapeQueryParameters"), &Physics2DDirectSpaceState::_cast_motion);
+ ClassDB::bind_method(D_METHOD("collide_shape", "shape:Physics2DShapeQueryParameters", "max_results"), &Physics2DDirectSpaceState::_collide_shape, DEFVAL(32));
+ ClassDB::bind_method(D_METHOD("get_rest_info", "shape:Physics2DShapeQueryParameters"), &Physics2DDirectSpaceState::_get_rest_info);
//ClassDB::bind_method(D_METHOD("cast_motion","shape","xform","motion","exclude","umask"),&Physics2DDirectSpaceState::_intersect_shape,DEFVAL(Array()),DEFVAL(0));
- BIND_CONSTANT( TYPE_MASK_STATIC_BODY );
- BIND_CONSTANT( TYPE_MASK_KINEMATIC_BODY );
- BIND_CONSTANT( TYPE_MASK_RIGID_BODY );
- BIND_CONSTANT( TYPE_MASK_CHARACTER_BODY );
- BIND_CONSTANT( TYPE_MASK_AREA );
- BIND_CONSTANT( TYPE_MASK_COLLISION );
-
+ BIND_CONSTANT(TYPE_MASK_STATIC_BODY);
+ BIND_CONSTANT(TYPE_MASK_KINEMATIC_BODY);
+ BIND_CONSTANT(TYPE_MASK_RIGID_BODY);
+ BIND_CONSTANT(TYPE_MASK_CHARACTER_BODY);
+ BIND_CONSTANT(TYPE_MASK_AREA);
+ BIND_CONSTANT(TYPE_MASK_COLLISION);
}
-
int Physics2DShapeQueryResult::get_result_count() const {
return result.size();
@@ -396,7 +373,7 @@ ObjectID Physics2DShapeQueryResult::get_result_object_id(int p_idx) const {
return result[p_idx].collider_id;
}
-Object* Physics2DShapeQueryResult::get_result_object(int p_idx) const {
+Object *Physics2DShapeQueryResult::get_result_object(int p_idx) const {
return result[p_idx].collider;
}
@@ -406,19 +383,15 @@ int Physics2DShapeQueryResult::get_result_object_shape(int p_idx) const {
}
Physics2DShapeQueryResult::Physics2DShapeQueryResult() {
-
-
}
void Physics2DShapeQueryResult::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_result_count"),&Physics2DShapeQueryResult::get_result_count);
- ClassDB::bind_method(D_METHOD("get_result_rid","idx"),&Physics2DShapeQueryResult::get_result_rid);
- ClassDB::bind_method(D_METHOD("get_result_object_id","idx"),&Physics2DShapeQueryResult::get_result_object_id);
- ClassDB::bind_method(D_METHOD("get_result_object","idx"),&Physics2DShapeQueryResult::get_result_object);
- ClassDB::bind_method(D_METHOD("get_result_object_shape","idx"),&Physics2DShapeQueryResult::get_result_object_shape);
-
-
+ ClassDB::bind_method(D_METHOD("get_result_count"), &Physics2DShapeQueryResult::get_result_count);
+ ClassDB::bind_method(D_METHOD("get_result_rid", "idx"), &Physics2DShapeQueryResult::get_result_rid);
+ ClassDB::bind_method(D_METHOD("get_result_object_id", "idx"), &Physics2DShapeQueryResult::get_result_object_id);
+ ClassDB::bind_method(D_METHOD("get_result_object", "idx"), &Physics2DShapeQueryResult::get_result_object);
+ ClassDB::bind_method(D_METHOD("get_result_object_shape", "idx"), &Physics2DShapeQueryResult::get_result_object_shape);
}
///////////////////////////////
@@ -427,41 +400,41 @@ void Physics2DShapeQueryResult::_bind_methods() {
return colliding;
}*/
-Vector2 Physics2DTestMotionResult::get_motion() const{
+Vector2 Physics2DTestMotionResult::get_motion() const {
return result.motion;
}
-Vector2 Physics2DTestMotionResult::get_motion_remainder() const{
+Vector2 Physics2DTestMotionResult::get_motion_remainder() const {
return result.remainder;
}
-Vector2 Physics2DTestMotionResult::get_collision_point() const{
+Vector2 Physics2DTestMotionResult::get_collision_point() const {
return result.collision_point;
}
-Vector2 Physics2DTestMotionResult::get_collision_normal() const{
+Vector2 Physics2DTestMotionResult::get_collision_normal() const {
return result.collision_normal;
}
-Vector2 Physics2DTestMotionResult::get_collider_velocity() const{
+Vector2 Physics2DTestMotionResult::get_collider_velocity() const {
return result.collider_velocity;
}
-ObjectID Physics2DTestMotionResult::get_collider_id() const{
+ObjectID Physics2DTestMotionResult::get_collider_id() const {
return result.collider_id;
}
-RID Physics2DTestMotionResult::get_collider_rid() const{
+RID Physics2DTestMotionResult::get_collider_rid() const {
return result.collider;
}
-Object* Physics2DTestMotionResult::get_collider() const {
+Object *Physics2DTestMotionResult::get_collider() const {
return ObjectDB::get_instance(result.collider_id);
}
-int Physics2DTestMotionResult::get_collider_shape() const{
+int Physics2DTestMotionResult::get_collider_shape() const {
return result.collider_shape;
}
@@ -469,269 +442,254 @@ int Physics2DTestMotionResult::get_collider_shape() const{
void Physics2DTestMotionResult::_bind_methods() {
//ClassDB::bind_method(D_METHOD("is_colliding"),&Physics2DTestMotionResult::is_colliding);
- ClassDB::bind_method(D_METHOD("get_motion"),&Physics2DTestMotionResult::get_motion);
- ClassDB::bind_method(D_METHOD("get_motion_remainder"),&Physics2DTestMotionResult::get_motion_remainder);
- ClassDB::bind_method(D_METHOD("get_collision_point"),&Physics2DTestMotionResult::get_collision_point);
- ClassDB::bind_method(D_METHOD("get_collision_normal"),&Physics2DTestMotionResult::get_collision_normal);
- ClassDB::bind_method(D_METHOD("get_collider_velocity"),&Physics2DTestMotionResult::get_collider_velocity);
- ClassDB::bind_method(D_METHOD("get_collider_id"),&Physics2DTestMotionResult::get_collider_id);
- ClassDB::bind_method(D_METHOD("get_collider_rid"),&Physics2DTestMotionResult::get_collider_rid);
- ClassDB::bind_method(D_METHOD("get_collider"),&Physics2DTestMotionResult::get_collider);
- ClassDB::bind_method(D_METHOD("get_collider_shape"),&Physics2DTestMotionResult::get_collider_shape);
-
+ ClassDB::bind_method(D_METHOD("get_motion"), &Physics2DTestMotionResult::get_motion);
+ ClassDB::bind_method(D_METHOD("get_motion_remainder"), &Physics2DTestMotionResult::get_motion_remainder);
+ ClassDB::bind_method(D_METHOD("get_collision_point"), &Physics2DTestMotionResult::get_collision_point);
+ ClassDB::bind_method(D_METHOD("get_collision_normal"), &Physics2DTestMotionResult::get_collision_normal);
+ ClassDB::bind_method(D_METHOD("get_collider_velocity"), &Physics2DTestMotionResult::get_collider_velocity);
+ ClassDB::bind_method(D_METHOD("get_collider_id"), &Physics2DTestMotionResult::get_collider_id);
+ ClassDB::bind_method(D_METHOD("get_collider_rid"), &Physics2DTestMotionResult::get_collider_rid);
+ ClassDB::bind_method(D_METHOD("get_collider"), &Physics2DTestMotionResult::get_collider);
+ ClassDB::bind_method(D_METHOD("get_collider_shape"), &Physics2DTestMotionResult::get_collider_shape);
}
-Physics2DTestMotionResult::Physics2DTestMotionResult(){
+Physics2DTestMotionResult::Physics2DTestMotionResult() {
- colliding=false;
- result.collider_id=0;
- result.collider_shape=0;
+ colliding = false;
+ result.collider_id = 0;
+ result.collider_shape = 0;
}
-
///////////////////////////////////////
+bool Physics2DServer::_body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin, const Ref<Physics2DTestMotionResult> &p_result) {
-
-bool Physics2DServer::_body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,float p_margin,const Ref<Physics2DTestMotionResult>& p_result) {
-
- MotionResult *r=NULL;
+ MotionResult *r = NULL;
if (p_result.is_valid())
- r=p_result->get_result_ptr();
- return body_test_motion(p_body,p_from,p_motion,p_margin,r);
+ r = p_result->get_result_ptr();
+ return body_test_motion(p_body, p_from, p_motion, p_margin, r);
}
void Physics2DServer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("shape_create", "type"), &Physics2DServer::shape_create);
+ ClassDB::bind_method(D_METHOD("shape_set_data", "shape", "data"), &Physics2DServer::shape_set_data);
- ClassDB::bind_method(D_METHOD("shape_create","type"),&Physics2DServer::shape_create);
- ClassDB::bind_method(D_METHOD("shape_set_data","shape","data"),&Physics2DServer::shape_set_data);
-
- ClassDB::bind_method(D_METHOD("shape_get_type","shape"),&Physics2DServer::shape_get_type);
- ClassDB::bind_method(D_METHOD("shape_get_data","shape"),&Physics2DServer::shape_get_data);
+ ClassDB::bind_method(D_METHOD("shape_get_type", "shape"), &Physics2DServer::shape_get_type);
+ ClassDB::bind_method(D_METHOD("shape_get_data", "shape"), &Physics2DServer::shape_get_data);
+ ClassDB::bind_method(D_METHOD("space_create"), &Physics2DServer::space_create);
+ ClassDB::bind_method(D_METHOD("space_set_active", "space", "active"), &Physics2DServer::space_set_active);
+ ClassDB::bind_method(D_METHOD("space_is_active", "space"), &Physics2DServer::space_is_active);
+ ClassDB::bind_method(D_METHOD("space_set_param", "space", "param", "value"), &Physics2DServer::space_set_param);
+ ClassDB::bind_method(D_METHOD("space_get_param", "space", "param"), &Physics2DServer::space_get_param);
+ ClassDB::bind_method(D_METHOD("space_get_direct_state:Physics2DDirectSpaceState", "space"), &Physics2DServer::space_get_direct_state);
- ClassDB::bind_method(D_METHOD("space_create"),&Physics2DServer::space_create);
- ClassDB::bind_method(D_METHOD("space_set_active","space","active"),&Physics2DServer::space_set_active);
- ClassDB::bind_method(D_METHOD("space_is_active","space"),&Physics2DServer::space_is_active);
- ClassDB::bind_method(D_METHOD("space_set_param","space","param","value"),&Physics2DServer::space_set_param);
- ClassDB::bind_method(D_METHOD("space_get_param","space","param"),&Physics2DServer::space_get_param);
- ClassDB::bind_method(D_METHOD("space_get_direct_state:Physics2DDirectSpaceState","space"),&Physics2DServer::space_get_direct_state);
+ ClassDB::bind_method(D_METHOD("area_create"), &Physics2DServer::area_create);
+ ClassDB::bind_method(D_METHOD("area_set_space", "area", "space"), &Physics2DServer::area_set_space);
+ ClassDB::bind_method(D_METHOD("area_get_space", "area"), &Physics2DServer::area_get_space);
- ClassDB::bind_method(D_METHOD("area_create"),&Physics2DServer::area_create);
- ClassDB::bind_method(D_METHOD("area_set_space","area","space"),&Physics2DServer::area_set_space);
- ClassDB::bind_method(D_METHOD("area_get_space","area"),&Physics2DServer::area_get_space);
+ ClassDB::bind_method(D_METHOD("area_set_space_override_mode", "area", "mode"), &Physics2DServer::area_set_space_override_mode);
+ ClassDB::bind_method(D_METHOD("area_get_space_override_mode", "area"), &Physics2DServer::area_get_space_override_mode);
- ClassDB::bind_method(D_METHOD("area_set_space_override_mode","area","mode"),&Physics2DServer::area_set_space_override_mode);
- ClassDB::bind_method(D_METHOD("area_get_space_override_mode","area"),&Physics2DServer::area_get_space_override_mode);
+ ClassDB::bind_method(D_METHOD("area_add_shape", "area", "shape", "transform"), &Physics2DServer::area_add_shape, DEFVAL(Transform2D()));
+ ClassDB::bind_method(D_METHOD("area_set_shape", "area", "shape_idx", "shape"), &Physics2DServer::area_set_shape);
+ ClassDB::bind_method(D_METHOD("area_set_shape_transform", "area", "shape_idx", "transform"), &Physics2DServer::area_set_shape_transform);
- ClassDB::bind_method(D_METHOD("area_add_shape","area","shape","transform"),&Physics2DServer::area_add_shape,DEFVAL(Transform2D()));
- ClassDB::bind_method(D_METHOD("area_set_shape","area","shape_idx","shape"),&Physics2DServer::area_set_shape);
- ClassDB::bind_method(D_METHOD("area_set_shape_transform","area","shape_idx","transform"),&Physics2DServer::area_set_shape_transform);
+ ClassDB::bind_method(D_METHOD("area_get_shape_count", "area"), &Physics2DServer::area_get_shape_count);
+ ClassDB::bind_method(D_METHOD("area_get_shape", "area", "shape_idx"), &Physics2DServer::area_get_shape);
+ ClassDB::bind_method(D_METHOD("area_get_shape_transform", "area", "shape_idx"), &Physics2DServer::area_get_shape_transform);
- ClassDB::bind_method(D_METHOD("area_get_shape_count","area"),&Physics2DServer::area_get_shape_count);
- ClassDB::bind_method(D_METHOD("area_get_shape","area","shape_idx"),&Physics2DServer::area_get_shape);
- ClassDB::bind_method(D_METHOD("area_get_shape_transform","area","shape_idx"),&Physics2DServer::area_get_shape_transform);
+ ClassDB::bind_method(D_METHOD("area_remove_shape", "area", "shape_idx"), &Physics2DServer::area_remove_shape);
+ ClassDB::bind_method(D_METHOD("area_clear_shapes", "area"), &Physics2DServer::area_clear_shapes);
- ClassDB::bind_method(D_METHOD("area_remove_shape","area","shape_idx"),&Physics2DServer::area_remove_shape);
- ClassDB::bind_method(D_METHOD("area_clear_shapes","area"),&Physics2DServer::area_clear_shapes);
+ ClassDB::bind_method(D_METHOD("area_set_layer_mask", "area", "mask"), &Physics2DServer::area_set_layer_mask);
+ ClassDB::bind_method(D_METHOD("area_set_collision_mask", "area", "mask"), &Physics2DServer::area_set_collision_mask);
- ClassDB::bind_method(D_METHOD("area_set_layer_mask","area","mask"),&Physics2DServer::area_set_layer_mask);
- ClassDB::bind_method(D_METHOD("area_set_collision_mask","area","mask"),&Physics2DServer::area_set_collision_mask);
+ ClassDB::bind_method(D_METHOD("area_set_param", "area", "param", "value"), &Physics2DServer::area_set_param);
+ ClassDB::bind_method(D_METHOD("area_set_transform", "area", "transform"), &Physics2DServer::area_set_transform);
- ClassDB::bind_method(D_METHOD("area_set_param","area","param","value"),&Physics2DServer::area_set_param);
- ClassDB::bind_method(D_METHOD("area_set_transform","area","transform"),&Physics2DServer::area_set_transform);
+ ClassDB::bind_method(D_METHOD("area_get_param", "area", "param"), &Physics2DServer::area_get_param);
+ ClassDB::bind_method(D_METHOD("area_get_transform", "area"), &Physics2DServer::area_get_transform);
- ClassDB::bind_method(D_METHOD("area_get_param","area","param"),&Physics2DServer::area_get_param);
- ClassDB::bind_method(D_METHOD("area_get_transform","area"),&Physics2DServer::area_get_transform);
+ ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID", "area", "id"), &Physics2DServer::area_attach_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("area_get_object_instance_ID", "area"), &Physics2DServer::area_get_object_instance_ID);
- ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID","area","id"),&Physics2DServer::area_attach_object_instance_ID);
- ClassDB::bind_method(D_METHOD("area_get_object_instance_ID","area"),&Physics2DServer::area_get_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("area_set_monitor_callback", "area", "receiver", "method"), &Physics2DServer::area_set_monitor_callback);
- ClassDB::bind_method(D_METHOD("area_set_monitor_callback","area","receiver","method"),&Physics2DServer::area_set_monitor_callback);
+ ClassDB::bind_method(D_METHOD("body_create", "mode", "init_sleeping"), &Physics2DServer::body_create, DEFVAL(BODY_MODE_RIGID), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("body_create","mode","init_sleeping"),&Physics2DServer::body_create,DEFVAL(BODY_MODE_RIGID),DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("body_set_space", "body", "space"), &Physics2DServer::body_set_space);
+ ClassDB::bind_method(D_METHOD("body_get_space", "body"), &Physics2DServer::body_get_space);
- ClassDB::bind_method(D_METHOD("body_set_space","body","space"),&Physics2DServer::body_set_space);
- ClassDB::bind_method(D_METHOD("body_get_space","body"),&Physics2DServer::body_get_space);
+ ClassDB::bind_method(D_METHOD("body_set_mode", "body", "mode"), &Physics2DServer::body_set_mode);
+ ClassDB::bind_method(D_METHOD("body_get_mode", "body"), &Physics2DServer::body_get_mode);
- ClassDB::bind_method(D_METHOD("body_set_mode","body","mode"),&Physics2DServer::body_set_mode);
- ClassDB::bind_method(D_METHOD("body_get_mode","body"),&Physics2DServer::body_get_mode);
+ ClassDB::bind_method(D_METHOD("body_add_shape", "body", "shape", "transform"), &Physics2DServer::body_add_shape, DEFVAL(Transform2D()));
+ ClassDB::bind_method(D_METHOD("body_set_shape", "body", "shape_idx", "shape"), &Physics2DServer::body_set_shape);
+ ClassDB::bind_method(D_METHOD("body_set_shape_transform", "body", "shape_idx", "transform"), &Physics2DServer::body_set_shape_transform);
+ ClassDB::bind_method(D_METHOD("body_set_shape_metadata", "body", "shape_idx", "metadata"), &Physics2DServer::body_set_shape_metadata);
- ClassDB::bind_method(D_METHOD("body_add_shape","body","shape","transform"),&Physics2DServer::body_add_shape,DEFVAL(Transform2D()));
- ClassDB::bind_method(D_METHOD("body_set_shape","body","shape_idx","shape"),&Physics2DServer::body_set_shape);
- ClassDB::bind_method(D_METHOD("body_set_shape_transform","body","shape_idx","transform"),&Physics2DServer::body_set_shape_transform);
- ClassDB::bind_method(D_METHOD("body_set_shape_metadata","body","shape_idx","metadata"),&Physics2DServer::body_set_shape_metadata);
+ ClassDB::bind_method(D_METHOD("body_get_shape_count", "body"), &Physics2DServer::body_get_shape_count);
+ ClassDB::bind_method(D_METHOD("body_get_shape", "body", "shape_idx"), &Physics2DServer::body_get_shape);
+ ClassDB::bind_method(D_METHOD("body_get_shape_transform", "body", "shape_idx"), &Physics2DServer::body_get_shape_transform);
+ ClassDB::bind_method(D_METHOD("body_get_shape_metadata", "body", "shape_idx"), &Physics2DServer::body_get_shape_metadata);
- ClassDB::bind_method(D_METHOD("body_get_shape_count","body"),&Physics2DServer::body_get_shape_count);
- ClassDB::bind_method(D_METHOD("body_get_shape","body","shape_idx"),&Physics2DServer::body_get_shape);
- ClassDB::bind_method(D_METHOD("body_get_shape_transform","body","shape_idx"),&Physics2DServer::body_get_shape_transform);
- ClassDB::bind_method(D_METHOD("body_get_shape_metadata","body","shape_idx"),&Physics2DServer::body_get_shape_metadata);
+ ClassDB::bind_method(D_METHOD("body_remove_shape", "body", "shape_idx"), &Physics2DServer::body_remove_shape);
+ ClassDB::bind_method(D_METHOD("body_clear_shapes", "body"), &Physics2DServer::body_clear_shapes);
- ClassDB::bind_method(D_METHOD("body_remove_shape","body","shape_idx"),&Physics2DServer::body_remove_shape);
- ClassDB::bind_method(D_METHOD("body_clear_shapes","body"),&Physics2DServer::body_clear_shapes);
+ ClassDB::bind_method(D_METHOD("body_set_shape_as_trigger", "body", "shape_idx", "enable"), &Physics2DServer::body_set_shape_as_trigger);
+ ClassDB::bind_method(D_METHOD("body_is_shape_set_as_trigger", "body", "shape_idx"), &Physics2DServer::body_is_shape_set_as_trigger);
+ ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID", "body", "id"), &Physics2DServer::body_attach_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("body_get_object_instance_ID", "body"), &Physics2DServer::body_get_object_instance_ID);
- ClassDB::bind_method(D_METHOD("body_set_shape_as_trigger","body","shape_idx","enable"),&Physics2DServer::body_set_shape_as_trigger);
- ClassDB::bind_method(D_METHOD("body_is_shape_set_as_trigger","body","shape_idx"),&Physics2DServer::body_is_shape_set_as_trigger);
+ ClassDB::bind_method(D_METHOD("body_set_continuous_collision_detection_mode", "body", "mode"), &Physics2DServer::body_set_continuous_collision_detection_mode);
+ ClassDB::bind_method(D_METHOD("body_get_continuous_collision_detection_mode", "body"), &Physics2DServer::body_get_continuous_collision_detection_mode);
- ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID","body","id"),&Physics2DServer::body_attach_object_instance_ID);
- ClassDB::bind_method(D_METHOD("body_get_object_instance_ID","body"),&Physics2DServer::body_get_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("body_set_layer_mask", "body", "mask"), &Physics2DServer::body_set_layer_mask);
+ ClassDB::bind_method(D_METHOD("body_get_layer_mask", "body"), &Physics2DServer::body_get_layer_mask);
+ ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &Physics2DServer::body_set_collision_mask);
+ ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &Physics2DServer::body_get_collision_mask);
- ClassDB::bind_method(D_METHOD("body_set_continuous_collision_detection_mode","body","mode"),&Physics2DServer::body_set_continuous_collision_detection_mode);
- ClassDB::bind_method(D_METHOD("body_get_continuous_collision_detection_mode","body"),&Physics2DServer::body_get_continuous_collision_detection_mode);
+ ClassDB::bind_method(D_METHOD("body_set_param", "body", "param", "value"), &Physics2DServer::body_set_param);
+ ClassDB::bind_method(D_METHOD("body_get_param", "body", "param"), &Physics2DServer::body_get_param);
+ ClassDB::bind_method(D_METHOD("body_set_state", "body", "state", "value"), &Physics2DServer::body_set_state);
+ ClassDB::bind_method(D_METHOD("body_get_state", "body", "state"), &Physics2DServer::body_get_state);
- ClassDB::bind_method(D_METHOD("body_set_layer_mask","body","mask"),&Physics2DServer::body_set_layer_mask);
- ClassDB::bind_method(D_METHOD("body_get_layer_mask","body"),&Physics2DServer::body_get_layer_mask);
+ ClassDB::bind_method(D_METHOD("body_apply_impulse", "body", "pos", "impulse"), &Physics2DServer::body_apply_impulse);
+ ClassDB::bind_method(D_METHOD("body_add_force", "body", "offset", "force"), &Physics2DServer::body_add_force);
+ ClassDB::bind_method(D_METHOD("body_set_axis_velocity", "body", "axis_velocity"), &Physics2DServer::body_set_axis_velocity);
- ClassDB::bind_method(D_METHOD("body_set_collision_mask","body","mask"),&Physics2DServer::body_set_collision_mask);
- ClassDB::bind_method(D_METHOD("body_get_collision_mask","body"),&Physics2DServer::body_get_collision_mask);
-
-
- ClassDB::bind_method(D_METHOD("body_set_param","body","param","value"),&Physics2DServer::body_set_param);
- ClassDB::bind_method(D_METHOD("body_get_param","body","param"),&Physics2DServer::body_get_param);
-
- ClassDB::bind_method(D_METHOD("body_set_state","body","state","value"),&Physics2DServer::body_set_state);
- ClassDB::bind_method(D_METHOD("body_get_state","body","state"),&Physics2DServer::body_get_state);
-
- ClassDB::bind_method(D_METHOD("body_apply_impulse","body","pos","impulse"),&Physics2DServer::body_apply_impulse);
- ClassDB::bind_method(D_METHOD("body_add_force","body","offset","force"),&Physics2DServer::body_add_force);
- ClassDB::bind_method(D_METHOD("body_set_axis_velocity","body","axis_velocity"),&Physics2DServer::body_set_axis_velocity);
-
- ClassDB::bind_method(D_METHOD("body_add_collision_exception","body","excepted_body"),&Physics2DServer::body_add_collision_exception);
- ClassDB::bind_method(D_METHOD("body_remove_collision_exception","body","excepted_body"),&Physics2DServer::body_remove_collision_exception);
+ ClassDB::bind_method(D_METHOD("body_add_collision_exception", "body", "excepted_body"), &Physics2DServer::body_add_collision_exception);
+ ClassDB::bind_method(D_METHOD("body_remove_collision_exception", "body", "excepted_body"), &Physics2DServer::body_remove_collision_exception);
//virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0;
- ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported","body","amount"),&Physics2DServer::body_set_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported","body"),&Physics2DServer::body_get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported", "body", "amount"), &Physics2DServer::body_set_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported", "body"), &Physics2DServer::body_get_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("body_set_one_way_collision_direction","body","normal"),&Physics2DServer::body_set_one_way_collision_direction);
- ClassDB::bind_method(D_METHOD("body_get_one_way_collision_direction","body"),&Physics2DServer::body_get_one_way_collision_direction);
+ ClassDB::bind_method(D_METHOD("body_set_one_way_collision_direction", "body", "normal"), &Physics2DServer::body_set_one_way_collision_direction);
+ ClassDB::bind_method(D_METHOD("body_get_one_way_collision_direction", "body"), &Physics2DServer::body_get_one_way_collision_direction);
- ClassDB::bind_method(D_METHOD("body_set_one_way_collision_max_depth","body","depth"),&Physics2DServer::body_set_one_way_collision_max_depth);
- ClassDB::bind_method(D_METHOD("body_get_one_way_collision_max_depth","body"),&Physics2DServer::body_get_one_way_collision_max_depth);
+ ClassDB::bind_method(D_METHOD("body_set_one_way_collision_max_depth", "body", "depth"), &Physics2DServer::body_set_one_way_collision_max_depth);
+ ClassDB::bind_method(D_METHOD("body_get_one_way_collision_max_depth", "body"), &Physics2DServer::body_get_one_way_collision_max_depth);
+ ClassDB::bind_method(D_METHOD("body_set_omit_force_integration", "body", "enable"), &Physics2DServer::body_set_omit_force_integration);
+ ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration", "body"), &Physics2DServer::body_is_omitting_force_integration);
- ClassDB::bind_method(D_METHOD("body_set_omit_force_integration","body","enable"),&Physics2DServer::body_set_omit_force_integration);
- ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration","body"),&Physics2DServer::body_is_omitting_force_integration);
+ ClassDB::bind_method(D_METHOD("body_set_force_integration_callback", "body", "receiver", "method", "userdata"), &Physics2DServer::body_set_force_integration_callback, DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("body_set_force_integration_callback","body","receiver","method","userdata"),&Physics2DServer::body_set_force_integration_callback,DEFVAL(Variant()));
-
- ClassDB::bind_method(D_METHOD("body_test_motion","body","from","motion","margin","result:Physics2DTestMotionResult"),&Physics2DServer::_body_test_motion,DEFVAL(0.08),DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("body_test_motion", "body", "from", "motion", "margin", "result:Physics2DTestMotionResult"), &Physics2DServer::_body_test_motion, DEFVAL(0.08), DEFVAL(Variant()));
/* JOINT API */
- ClassDB::bind_method(D_METHOD("joint_set_param","joint","param","value"),&Physics2DServer::joint_set_param);
- ClassDB::bind_method(D_METHOD("joint_get_param","joint","param"),&Physics2DServer::joint_get_param);
+ ClassDB::bind_method(D_METHOD("joint_set_param", "joint", "param", "value"), &Physics2DServer::joint_set_param);
+ ClassDB::bind_method(D_METHOD("joint_get_param", "joint", "param"), &Physics2DServer::joint_get_param);
- ClassDB::bind_method(D_METHOD("pin_joint_create","anchor","body_a","body_b"),&Physics2DServer::pin_joint_create,DEFVAL(RID()));
- ClassDB::bind_method(D_METHOD("groove_joint_create","groove1_a","groove2_a","anchor_b","body_a","body_b"),&Physics2DServer::groove_joint_create,DEFVAL(RID()),DEFVAL(RID()));
- ClassDB::bind_method(D_METHOD("damped_spring_joint_create","anchor_a","anchor_b","body_a","body_b"),&Physics2DServer::damped_spring_joint_create,DEFVAL(RID()));
+ ClassDB::bind_method(D_METHOD("pin_joint_create", "anchor", "body_a", "body_b"), &Physics2DServer::pin_joint_create, DEFVAL(RID()));
+ ClassDB::bind_method(D_METHOD("groove_joint_create", "groove1_a", "groove2_a", "anchor_b", "body_a", "body_b"), &Physics2DServer::groove_joint_create, DEFVAL(RID()), DEFVAL(RID()));
+ ClassDB::bind_method(D_METHOD("damped_spring_joint_create", "anchor_a", "anchor_b", "body_a", "body_b"), &Physics2DServer::damped_spring_joint_create, DEFVAL(RID()));
- ClassDB::bind_method(D_METHOD("damped_string_joint_set_param","joint","param","value"),&Physics2DServer::damped_string_joint_set_param);
- ClassDB::bind_method(D_METHOD("damped_string_joint_get_param","joint","param"),&Physics2DServer::damped_string_joint_get_param);
+ ClassDB::bind_method(D_METHOD("damped_string_joint_set_param", "joint", "param", "value"), &Physics2DServer::damped_string_joint_set_param);
+ ClassDB::bind_method(D_METHOD("damped_string_joint_get_param", "joint", "param"), &Physics2DServer::damped_string_joint_get_param);
- ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&Physics2DServer::joint_get_type);
+ ClassDB::bind_method(D_METHOD("joint_get_type", "joint"), &Physics2DServer::joint_get_type);
- ClassDB::bind_method(D_METHOD("free_rid","rid"),&Physics2DServer::free);
+ ClassDB::bind_method(D_METHOD("free_rid", "rid"), &Physics2DServer::free);
- ClassDB::bind_method(D_METHOD("set_active","active"),&Physics2DServer::set_active);
+ ClassDB::bind_method(D_METHOD("set_active", "active"), &Physics2DServer::set_active);
- ClassDB::bind_method(D_METHOD("get_process_info","process_info"),&Physics2DServer::get_process_info);
+ ClassDB::bind_method(D_METHOD("get_process_info", "process_info"), &Physics2DServer::get_process_info);
//ClassDB::bind_method(D_METHOD("init"),&Physics2DServer::init);
//ClassDB::bind_method(D_METHOD("step"),&Physics2DServer::step);
//ClassDB::bind_method(D_METHOD("sync"),&Physics2DServer::sync);
//ClassDB::bind_method(D_METHOD("flush_queries"),&Physics2DServer::flush_queries);
- BIND_CONSTANT( SPACE_PARAM_CONTACT_RECYCLE_RADIUS );
- BIND_CONSTANT( SPACE_PARAM_CONTACT_MAX_SEPARATION );
- BIND_CONSTANT( SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION );
- BIND_CONSTANT( SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD );
- BIND_CONSTANT( SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD );
- BIND_CONSTANT( SPACE_PARAM_BODY_TIME_TO_SLEEP );
- BIND_CONSTANT( SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS );
-
- BIND_CONSTANT( SHAPE_LINE );
- BIND_CONSTANT( SHAPE_SEGMENT );
- BIND_CONSTANT( SHAPE_CIRCLE );
- BIND_CONSTANT( SHAPE_RECTANGLE );
- BIND_CONSTANT( SHAPE_CAPSULE );
- BIND_CONSTANT( SHAPE_CONVEX_POLYGON );
- BIND_CONSTANT( SHAPE_CONCAVE_POLYGON );
- BIND_CONSTANT( SHAPE_CUSTOM );
-
- BIND_CONSTANT( AREA_PARAM_GRAVITY );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_VECTOR );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_IS_POINT );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_DISTANCE_SCALE );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_POINT_ATTENUATION );
- BIND_CONSTANT( AREA_PARAM_LINEAR_DAMP);
- BIND_CONSTANT( AREA_PARAM_ANGULAR_DAMP);
- BIND_CONSTANT( AREA_PARAM_PRIORITY );
-
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_DISABLED );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE_REPLACE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE_COMBINE );
-
- BIND_CONSTANT( BODY_MODE_STATIC );
- BIND_CONSTANT( BODY_MODE_KINEMATIC );
- BIND_CONSTANT( BODY_MODE_RIGID );
- BIND_CONSTANT( BODY_MODE_CHARACTER );
-
- BIND_CONSTANT( BODY_PARAM_BOUNCE );
- BIND_CONSTANT( BODY_PARAM_FRICTION );
- BIND_CONSTANT( BODY_PARAM_MASS );
- BIND_CONSTANT( BODY_PARAM_INERTIA );
- BIND_CONSTANT( BODY_PARAM_GRAVITY_SCALE );
- BIND_CONSTANT( BODY_PARAM_LINEAR_DAMP);
- BIND_CONSTANT( BODY_PARAM_ANGULAR_DAMP);
- BIND_CONSTANT( BODY_PARAM_MAX );
-
- BIND_CONSTANT( BODY_STATE_TRANSFORM );
- BIND_CONSTANT( BODY_STATE_LINEAR_VELOCITY );
- BIND_CONSTANT( BODY_STATE_ANGULAR_VELOCITY );
- BIND_CONSTANT( BODY_STATE_SLEEPING );
- BIND_CONSTANT( BODY_STATE_CAN_SLEEP );
-
- BIND_CONSTANT( JOINT_PIN );
- BIND_CONSTANT( JOINT_GROOVE );
- BIND_CONSTANT( JOINT_DAMPED_SPRING );
-
- BIND_CONSTANT( DAMPED_STRING_REST_LENGTH );
- BIND_CONSTANT( DAMPED_STRING_STIFFNESS );
- BIND_CONSTANT( DAMPED_STRING_DAMPING );
-
- BIND_CONSTANT( CCD_MODE_DISABLED );
- BIND_CONSTANT( CCD_MODE_CAST_RAY );
- BIND_CONSTANT( CCD_MODE_CAST_SHAPE );
+ BIND_CONSTANT(SPACE_PARAM_CONTACT_RECYCLE_RADIUS);
+ BIND_CONSTANT(SPACE_PARAM_CONTACT_MAX_SEPARATION);
+ BIND_CONSTANT(SPACE_PARAM_BODY_MAX_ALLOWED_PENETRATION);
+ BIND_CONSTANT(SPACE_PARAM_BODY_LINEAR_VELOCITY_SLEEP_TRESHOLD);
+ BIND_CONSTANT(SPACE_PARAM_BODY_ANGULAR_VELOCITY_SLEEP_TRESHOLD);
+ BIND_CONSTANT(SPACE_PARAM_BODY_TIME_TO_SLEEP);
+ BIND_CONSTANT(SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS);
+
+ BIND_CONSTANT(SHAPE_LINE);
+ BIND_CONSTANT(SHAPE_SEGMENT);
+ BIND_CONSTANT(SHAPE_CIRCLE);
+ BIND_CONSTANT(SHAPE_RECTANGLE);
+ BIND_CONSTANT(SHAPE_CAPSULE);
+ BIND_CONSTANT(SHAPE_CONVEX_POLYGON);
+ BIND_CONSTANT(SHAPE_CONCAVE_POLYGON);
+ BIND_CONSTANT(SHAPE_CUSTOM);
+
+ BIND_CONSTANT(AREA_PARAM_GRAVITY);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_VECTOR);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_IS_POINT);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_DISTANCE_SCALE);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_POINT_ATTENUATION);
+ BIND_CONSTANT(AREA_PARAM_LINEAR_DAMP);
+ BIND_CONSTANT(AREA_PARAM_ANGULAR_DAMP);
+ BIND_CONSTANT(AREA_PARAM_PRIORITY);
+
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_DISABLED);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE_REPLACE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE_COMBINE);
+
+ BIND_CONSTANT(BODY_MODE_STATIC);
+ BIND_CONSTANT(BODY_MODE_KINEMATIC);
+ BIND_CONSTANT(BODY_MODE_RIGID);
+ BIND_CONSTANT(BODY_MODE_CHARACTER);
+
+ BIND_CONSTANT(BODY_PARAM_BOUNCE);
+ BIND_CONSTANT(BODY_PARAM_FRICTION);
+ BIND_CONSTANT(BODY_PARAM_MASS);
+ BIND_CONSTANT(BODY_PARAM_INERTIA);
+ BIND_CONSTANT(BODY_PARAM_GRAVITY_SCALE);
+ BIND_CONSTANT(BODY_PARAM_LINEAR_DAMP);
+ BIND_CONSTANT(BODY_PARAM_ANGULAR_DAMP);
+ BIND_CONSTANT(BODY_PARAM_MAX);
+
+ BIND_CONSTANT(BODY_STATE_TRANSFORM);
+ BIND_CONSTANT(BODY_STATE_LINEAR_VELOCITY);
+ BIND_CONSTANT(BODY_STATE_ANGULAR_VELOCITY);
+ BIND_CONSTANT(BODY_STATE_SLEEPING);
+ BIND_CONSTANT(BODY_STATE_CAN_SLEEP);
+
+ BIND_CONSTANT(JOINT_PIN);
+ BIND_CONSTANT(JOINT_GROOVE);
+ BIND_CONSTANT(JOINT_DAMPED_SPRING);
+
+ BIND_CONSTANT(DAMPED_STRING_REST_LENGTH);
+ BIND_CONSTANT(DAMPED_STRING_STIFFNESS);
+ BIND_CONSTANT(DAMPED_STRING_DAMPING);
+
+ BIND_CONSTANT(CCD_MODE_DISABLED);
+ BIND_CONSTANT(CCD_MODE_CAST_RAY);
+ BIND_CONSTANT(CCD_MODE_CAST_SHAPE);
//BIND_CONSTANT( TYPE_BODY );
//BIND_CONSTANT( TYPE_AREA );
- BIND_CONSTANT( AREA_BODY_ADDED );
- BIND_CONSTANT( AREA_BODY_REMOVED );
-
- BIND_CONSTANT( INFO_ACTIVE_OBJECTS );
- BIND_CONSTANT( INFO_COLLISION_PAIRS );
- BIND_CONSTANT( INFO_ISLAND_COUNT );
-
+ BIND_CONSTANT(AREA_BODY_ADDED);
+ BIND_CONSTANT(AREA_BODY_REMOVED);
+ BIND_CONSTANT(INFO_ACTIVE_OBJECTS);
+ BIND_CONSTANT(INFO_COLLISION_PAIRS);
+ BIND_CONSTANT(INFO_ISLAND_COUNT);
}
-
Physics2DServer::Physics2DServer() {
//ERR_FAIL_COND( singleton!=NULL );
- singleton=this;
+ singleton = this;
}
Physics2DServer::~Physics2DServer() {
- singleton=NULL;
+ singleton = NULL;
}
-
diff --git a/servers/physics_2d_server.h b/servers/physics_2d_server.h
index 424d2fa7ce..3c64d3df6a 100644
--- a/servers/physics_2d_server.h
+++ b/servers/physics_2d_server.h
@@ -37,61 +37,60 @@ class Physics2DDirectSpaceState;
class Physics2DDirectBodyState : public Object {
- GDCLASS( Physics2DDirectBodyState, Object );
+ GDCLASS(Physics2DDirectBodyState, Object);
+
protected:
static void _bind_methods();
-public:
- virtual Vector2 get_total_gravity() const=0; // get gravity vector working on this body space/area
- virtual float get_total_linear_damp() const=0; // get density of this body space/area
- virtual float get_total_angular_damp() const=0; // get density of this body space/area
+public:
+ virtual Vector2 get_total_gravity() const = 0; // get gravity vector working on this body space/area
+ virtual float get_total_linear_damp() const = 0; // get density of this body space/area
+ virtual float get_total_angular_damp() const = 0; // get density of this body space/area
- virtual float get_inverse_mass() const=0; // get the mass
- virtual real_t get_inverse_inertia() const=0; // get density of this body space
+ virtual float get_inverse_mass() const = 0; // get the mass
+ virtual real_t get_inverse_inertia() const = 0; // get density of this body space
- virtual void set_linear_velocity(const Vector2& p_velocity)=0;
- virtual Vector2 get_linear_velocity() const=0;
+ virtual void set_linear_velocity(const Vector2 &p_velocity) = 0;
+ virtual Vector2 get_linear_velocity() const = 0;
- virtual void set_angular_velocity(real_t p_velocity)=0;
- virtual real_t get_angular_velocity() const=0;
+ virtual void set_angular_velocity(real_t p_velocity) = 0;
+ virtual real_t get_angular_velocity() const = 0;
- virtual void set_transform(const Transform2D& p_transform)=0;
- virtual Transform2D get_transform() const=0;
+ virtual void set_transform(const Transform2D &p_transform) = 0;
+ virtual Transform2D get_transform() const = 0;
- virtual void set_sleep_state(bool p_enable)=0;
- virtual bool is_sleeping() const=0;
+ virtual void set_sleep_state(bool p_enable) = 0;
+ virtual bool is_sleeping() const = 0;
- virtual int get_contact_count() const=0;
+ virtual int get_contact_count() const = 0;
- virtual Vector2 get_contact_local_pos(int p_contact_idx) const=0;
- virtual Vector2 get_contact_local_normal(int p_contact_idx) const=0;
- virtual int get_contact_local_shape(int p_contact_idx) const=0;
+ virtual Vector2 get_contact_local_pos(int p_contact_idx) const = 0;
+ virtual Vector2 get_contact_local_normal(int p_contact_idx) const = 0;
+ virtual int get_contact_local_shape(int p_contact_idx) const = 0;
- virtual RID get_contact_collider(int p_contact_idx) const=0;
- virtual Vector2 get_contact_collider_pos(int p_contact_idx) const=0;
- virtual ObjectID get_contact_collider_id(int p_contact_idx) const=0;
- virtual Object* get_contact_collider_object(int p_contact_idx) const;
- virtual int get_contact_collider_shape(int p_contact_idx) const=0;
- virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const=0;
- virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const=0;
+ virtual RID get_contact_collider(int p_contact_idx) const = 0;
+ virtual Vector2 get_contact_collider_pos(int p_contact_idx) const = 0;
+ virtual ObjectID get_contact_collider_id(int p_contact_idx) const = 0;
+ virtual Object *get_contact_collider_object(int p_contact_idx) const;
+ virtual int get_contact_collider_shape(int p_contact_idx) const = 0;
+ virtual Variant get_contact_collider_shape_metadata(int p_contact_idx) const = 0;
+ virtual Vector2 get_contact_collider_velocity_at_pos(int p_contact_idx) const = 0;
- virtual real_t get_step() const=0;
+ virtual real_t get_step() const = 0;
virtual void integrate_forces();
- virtual Physics2DDirectSpaceState* get_space_state()=0;
+ virtual Physics2DDirectSpaceState *get_space_state() = 0;
Physics2DDirectBodyState();
};
-
class Physics2DShapeQueryResult;
-
//used for script
class Physics2DShapeQueryParameters : public Reference {
GDCLASS(Physics2DShapeQueryParameters, Reference);
-friend class Physics2DDirectSpaceState;
+ friend class Physics2DDirectSpaceState;
RID shape;
Transform2D transform;
Vector2 motion;
@@ -99,19 +98,19 @@ friend class Physics2DDirectSpaceState;
Set<RID> exclude;
uint32_t layer_mask;
uint32_t object_type_mask;
+
protected:
static void _bind_methods();
-public:
-
- void set_shape(const RES& p_shape);
- void set_shape_rid(const RID& p_shape);
+public:
+ void set_shape(const RES &p_shape);
+ void set_shape_rid(const RID &p_shape);
RID get_shape_rid() const;
- void set_transform(const Transform2D& p_transform);
+ void set_transform(const Transform2D &p_transform);
Transform2D get_transform() const;
- void set_motion(const Vector2& p_motion);
+ void set_motion(const Vector2 &p_motion);
Vector2 get_motion() const;
void set_margin(float p_margin);
@@ -123,38 +122,35 @@ public:
void set_object_type_mask(int p_object_type_mask);
int get_object_type_mask() const;
- void set_exclude(const Vector<RID>& p_exclude);
+ void set_exclude(const Vector<RID> &p_exclude);
Vector<RID> get_exclude() const;
Physics2DShapeQueryParameters();
-
};
-
class Physics2DDirectSpaceState : public Object {
- GDCLASS( Physics2DDirectSpaceState, Object );
+ GDCLASS(Physics2DDirectSpaceState, Object);
- Dictionary _intersect_ray(const Vector2& p_from, const Vector2& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
+ Dictionary _intersect_ray(const Vector2 &p_from, const Vector2 &p_to, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
- Array _intersect_point(const Vector2& p_point,int p_max_results=32,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- Array _intersect_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query,int p_max_results=32);
+ Array _intersect_point(const Vector2 &p_point, int p_max_results = 32, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ Array _intersect_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results = 32);
Array _cast_motion(const Ref<Physics2DShapeQueryParameters> &p_shape_query);
- Array _collide_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query,int p_max_results=32);
+ Array _collide_shape(const Ref<Physics2DShapeQueryParameters> &p_shape_query, int p_max_results = 32);
Dictionary _get_rest_info(const Ref<Physics2DShapeQueryParameters> &p_shape_query);
protected:
static void _bind_methods();
public:
-
enum ObjectTypeMask {
- TYPE_MASK_STATIC_BODY=1<<0,
- TYPE_MASK_KINEMATIC_BODY=1<<1,
- TYPE_MASK_RIGID_BODY=1<<2,
- TYPE_MASK_CHARACTER_BODY=1<<3,
- TYPE_MASK_AREA=1<<4,
- TYPE_MASK_COLLISION=TYPE_MASK_STATIC_BODY|TYPE_MASK_CHARACTER_BODY|TYPE_MASK_KINEMATIC_BODY|TYPE_MASK_RIGID_BODY
+ TYPE_MASK_STATIC_BODY = 1 << 0,
+ TYPE_MASK_KINEMATIC_BODY = 1 << 1,
+ TYPE_MASK_RIGID_BODY = 1 << 2,
+ TYPE_MASK_CHARACTER_BODY = 1 << 3,
+ TYPE_MASK_AREA = 1 << 4,
+ TYPE_MASK_COLLISION = TYPE_MASK_STATIC_BODY | TYPE_MASK_CHARACTER_BODY | TYPE_MASK_KINEMATIC_BODY | TYPE_MASK_RIGID_BODY
};
@@ -169,7 +165,7 @@ public:
Variant metadata;
};
- virtual bool intersect_ray(const Vector2& p_from, const Vector2& p_to,RayResult &r_result,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ virtual bool intersect_ray(const Vector2 &p_from, const Vector2 &p_to, RayResult &r_result, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
struct ShapeResult {
@@ -178,17 +174,15 @@ public:
Object *collider;
int shape;
Variant metadata;
-
-
};
- virtual int intersect_point(const Vector2& p_point,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_point=false)=0;
+ virtual int intersect_point(const Vector2 &p_point, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_point = false) = 0;
- virtual int intersect_shape(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,float p_margin,ShapeResult *r_results,int p_result_max,const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ virtual int intersect_shape(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, float p_margin, ShapeResult *r_results, int p_result_max, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
- virtual bool cast_motion(const RID& p_shape, const Transform2D& p_xform,const Vector2& p_motion,float p_margin,float &p_closest_safe,float &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ virtual bool cast_motion(const RID &p_shape, const Transform2D &p_xform, const Vector2 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
- virtual bool collide_shape(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,float p_margin,Vector2 *r_results,int p_result_max,int &r_result_count, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ virtual bool collide_shape(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, float p_margin, Vector2 *r_results, int p_result_max, int &r_result_count, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
struct ShapeRestInfo {
@@ -199,32 +193,29 @@ public:
int shape;
Vector2 linear_velocity; //velocity at contact point
Variant metadata;
-
};
- virtual bool rest_info(RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,float p_margin,ShapeRestInfo *r_info, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
-
+ virtual bool rest_info(RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, float p_margin, ShapeRestInfo *r_info, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
Physics2DDirectSpaceState();
};
-
class Physics2DShapeQueryResult : public Reference {
- GDCLASS( Physics2DShapeQueryResult, Reference );
+ GDCLASS(Physics2DShapeQueryResult, Reference);
Vector<Physics2DDirectSpaceState::ShapeResult> result;
-friend class Physics2DDirectSpaceState;
+ friend class Physics2DDirectSpaceState;
protected:
static void _bind_methods();
-public:
+public:
int get_result_count() const;
RID get_result_rid(int p_idx) const;
ObjectID get_result_object_id(int p_idx) const;
- Object* get_result_object(int p_idx) const;
+ Object *get_result_object(int p_idx) const;
int get_result_object_shape(int p_idx) const;
Physics2DShapeQueryResult();
@@ -234,18 +225,17 @@ class Physics2DTestMotionResult;
class Physics2DServer : public Object {
- GDCLASS( Physics2DServer, Object );
+ GDCLASS(Physics2DServer, Object);
- static Physics2DServer * singleton;
+ static Physics2DServer *singleton;
- virtual bool _body_test_motion(RID p_body, const Transform2D &p_from, const Vector2& p_motion, float p_margin=0.08, const Ref<Physics2DTestMotionResult>& p_result=Ref<Physics2DTestMotionResult>());
+ virtual bool _body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin = 0.08, const Ref<Physics2DTestMotionResult> &p_result = Ref<Physics2DTestMotionResult>());
protected:
static void _bind_methods();
public:
-
- static Physics2DServer * get_singleton();
+ static Physics2DServer *get_singleton();
enum ShapeType {
SHAPE_LINE, ///< plane:"plane"
@@ -259,22 +249,22 @@ public:
SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_create() with this value will result in an error
};
- virtual RID shape_create(ShapeType p_shape)=0;
- virtual void shape_set_data(RID p_shape, const Variant& p_data)=0;
- virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias)=0;
+ virtual RID shape_create(ShapeType p_shape) = 0;
+ virtual void shape_set_data(RID p_shape, const Variant &p_data) = 0;
+ virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) = 0;
- virtual ShapeType shape_get_type(RID p_shape) const=0;
- virtual Variant shape_get_data(RID p_shape) const=0;
- virtual real_t shape_get_custom_solver_bias(RID p_shape) const=0;
+ virtual ShapeType shape_get_type(RID p_shape) const = 0;
+ virtual Variant shape_get_data(RID p_shape) const = 0;
+ virtual real_t shape_get_custom_solver_bias(RID p_shape) const = 0;
//these work well, but should be used from the main thread only
- virtual bool shape_collide(RID p_shape_A, const Transform2D& p_xform_A,const Vector2& p_motion_A,RID p_shape_B, const Transform2D& p_xform_B, const Vector2& p_motion_B,Vector2 *r_results,int p_result_max,int &r_result_count)=0;
+ virtual bool shape_collide(RID p_shape_A, const Transform2D &p_xform_A, const Vector2 &p_motion_A, RID p_shape_B, const Transform2D &p_xform_B, const Vector2 &p_motion_B, Vector2 *r_results, int p_result_max, int &r_result_count) = 0;
/* SPACE API */
- virtual RID space_create()=0;
- virtual void space_set_active(RID p_space,bool p_active)=0;
- virtual bool space_is_active(RID p_space) const=0;
+ virtual RID space_create() = 0;
+ virtual void space_set_active(RID p_space, bool p_active) = 0;
+ virtual bool space_is_active(RID p_space) const = 0;
enum SpaceParameter {
@@ -287,15 +277,15 @@ public:
SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS,
};
- virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value)=0;
- virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const=0;
+ virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) = 0;
+ virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const = 0;
// this function only works on fixed process, errors and returns null otherwise
- virtual Physics2DDirectSpaceState* space_get_direct_state(RID p_space)=0;
+ virtual Physics2DDirectSpaceState *space_get_direct_state(RID p_space) = 0;
- virtual void space_set_debug_contacts(RID p_space,int p_max_contacts)=0;
- virtual Vector<Vector2> space_get_contacts(RID p_space) const=0;
- virtual int space_get_contact_count(RID p_space) const=0;
+ virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) = 0;
+ virtual Vector<Vector2> space_get_contacts(RID p_space) const = 0;
+ virtual int space_get_contact_count(RID p_space) const = 0;
//missing space parameters
@@ -303,8 +293,6 @@ public:
//missing attenuation? missing better override?
-
-
enum AreaParameter {
AREA_PARAM_GRAVITY,
AREA_PARAM_GRAVITY_VECTOR,
@@ -316,11 +304,10 @@ public:
AREA_PARAM_PRIORITY
};
- virtual RID area_create()=0;
-
- virtual void area_set_space(RID p_area, RID p_space)=0;
- virtual RID area_get_space(RID p_area) const=0;
+ virtual RID area_create() = 0;
+ virtual void area_set_space(RID p_area, RID p_space) = 0;
+ virtual RID area_get_space(RID p_area) const = 0;
enum AreaSpaceOverrideMode {
AREA_SPACE_OVERRIDE_DISABLED,
@@ -330,37 +317,37 @@ public:
AREA_SPACE_OVERRIDE_REPLACE_COMBINE // Discards all previous calculations, then keeps combining
};
- virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode)=0;
- virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const=0;
+ virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) = 0;
+ virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const = 0;
- virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D& p_transform=Transform2D())=0;
- virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape)=0;
- virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D& p_transform)=0;
+ virtual void area_add_shape(RID p_area, RID p_shape, const Transform2D &p_transform = Transform2D()) = 0;
+ virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) = 0;
+ virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform2D &p_transform) = 0;
- virtual int area_get_shape_count(RID p_area) const=0;
- virtual RID area_get_shape(RID p_area, int p_shape_idx) const=0;
- virtual Transform2D area_get_shape_transform(RID p_area, int p_shape_idx) const=0;
+ virtual int area_get_shape_count(RID p_area) const = 0;
+ virtual RID area_get_shape(RID p_area, int p_shape_idx) const = 0;
+ virtual Transform2D area_get_shape_transform(RID p_area, int p_shape_idx) const = 0;
- virtual void area_remove_shape(RID p_area, int p_shape_idx)=0;
- virtual void area_clear_shapes(RID p_area)=0;
+ virtual void area_remove_shape(RID p_area, int p_shape_idx) = 0;
+ virtual void area_clear_shapes(RID p_area) = 0;
- virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID)=0;
- virtual ObjectID area_get_object_instance_ID(RID p_area) const=0;
+ virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID) = 0;
+ virtual ObjectID area_get_object_instance_ID(RID p_area) const = 0;
- virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value)=0;
- virtual void area_set_transform(RID p_area, const Transform2D& p_transform)=0;
+ virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) = 0;
+ virtual void area_set_transform(RID p_area, const Transform2D &p_transform) = 0;
- virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const=0;
- virtual Transform2D area_get_transform(RID p_area) const=0;
+ virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const = 0;
+ virtual Transform2D area_get_transform(RID p_area) const = 0;
- virtual void area_set_collision_mask(RID p_area,uint32_t p_mask)=0;
- virtual void area_set_layer_mask(RID p_area,uint32_t p_mask)=0;
+ virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) = 0;
+ virtual void area_set_layer_mask(RID p_area, uint32_t p_mask) = 0;
- virtual void area_set_monitorable(RID p_area,bool p_monitorable)=0;
- virtual void area_set_pickable(RID p_area,bool p_pickable)=0;
+ virtual void area_set_monitorable(RID p_area, bool p_monitorable) = 0;
+ virtual void area_set_pickable(RID p_area, bool p_pickable) = 0;
- virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0;
- virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0;
+ virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0;
+ virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0;
/* BODY API */
@@ -374,32 +361,32 @@ public:
//BODY_MODE_SOFT ??
};
- virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false)=0;
+ virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) = 0;
- virtual void body_set_space(RID p_body, RID p_space)=0;
- virtual RID body_get_space(RID p_body) const=0;
+ virtual void body_set_space(RID p_body, RID p_space) = 0;
+ virtual RID body_get_space(RID p_body) const = 0;
- virtual void body_set_mode(RID p_body, BodyMode p_mode)=0;
- virtual BodyMode body_get_mode(RID p_body) const=0;
+ virtual void body_set_mode(RID p_body, BodyMode p_mode) = 0;
+ virtual BodyMode body_get_mode(RID p_body) const = 0;
- virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D& p_transform=Transform2D())=0;
- virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape)=0;
- virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D& p_transform)=0;
- virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant& p_metadata)=0;
+ virtual void body_add_shape(RID p_body, RID p_shape, const Transform2D &p_transform = Transform2D()) = 0;
+ virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) = 0;
+ virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform2D &p_transform) = 0;
+ virtual void body_set_shape_metadata(RID p_body, int p_shape_idx, const Variant &p_metadata) = 0;
- virtual int body_get_shape_count(RID p_body) const=0;
- virtual RID body_get_shape(RID p_body, int p_shape_idx) const=0;
- virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const=0;
- virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const=0;
+ virtual int body_get_shape_count(RID p_body) const = 0;
+ virtual RID body_get_shape(RID p_body, int p_shape_idx) const = 0;
+ virtual Transform2D body_get_shape_transform(RID p_body, int p_shape_idx) const = 0;
+ virtual Variant body_get_shape_metadata(RID p_body, int p_shape_idx) const = 0;
- virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable)=0;
- virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const=0;
+ virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) = 0;
+ virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const = 0;
- virtual void body_remove_shape(RID p_body, int p_shape_idx)=0;
- virtual void body_clear_shapes(RID p_body)=0;
+ virtual void body_remove_shape(RID p_body, int p_shape_idx) = 0;
+ virtual void body_clear_shapes(RID p_body) = 0;
- virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID)=0;
- virtual uint32_t body_get_object_instance_ID(RID p_body) const=0;
+ virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID) = 0;
+ virtual uint32_t body_get_object_instance_ID(RID p_body) const = 0;
enum CCDMode {
CCD_MODE_DISABLED,
@@ -407,30 +394,29 @@ public:
CCD_MODE_CAST_SHAPE,
};
- virtual void body_set_continuous_collision_detection_mode(RID p_body,CCDMode p_mode)=0;
- virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const=0;
+ virtual void body_set_continuous_collision_detection_mode(RID p_body, CCDMode p_mode) = 0;
+ virtual CCDMode body_get_continuous_collision_detection_mode(RID p_body) const = 0;
- virtual void body_set_layer_mask(RID p_body, uint32_t p_mask)=0;
- virtual uint32_t body_get_layer_mask(RID p_body) const=0;
+ virtual void body_set_layer_mask(RID p_body, uint32_t p_mask) = 0;
+ virtual uint32_t body_get_layer_mask(RID p_body) const = 0;
- virtual void body_set_collision_mask(RID p_body, uint32_t p_mask)=0;
- virtual uint32_t body_get_collision_mask(RID p_body) const=0;
+ virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0;
+ virtual uint32_t body_get_collision_mask(RID p_body) const = 0;
// common body variables
enum BodyParameter {
BODY_PARAM_BOUNCE,
BODY_PARAM_FRICTION,
BODY_PARAM_MASS, ///< unused for static, always infinite
- BODY_PARAM_INERTIA, // read-only: computed from mass & shapes
+ BODY_PARAM_INERTIA, // read-only: computed from mass & shapes
BODY_PARAM_GRAVITY_SCALE,
BODY_PARAM_LINEAR_DAMP,
BODY_PARAM_ANGULAR_DAMP,
BODY_PARAM_MAX,
};
- virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value)=0;
- virtual float body_get_param(RID p_body, BodyParameter p_param) const=0;
-
+ virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0;
+ virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0;
//state
enum BodyState {
@@ -441,47 +427,47 @@ public:
BODY_STATE_CAN_SLEEP,
};
- virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant)=0;
- virtual Variant body_get_state(RID p_body, BodyState p_state) const=0;
+ virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) = 0;
+ virtual Variant body_get_state(RID p_body, BodyState p_state) const = 0;
//do something about it
- virtual void body_set_applied_force(RID p_body, const Vector2& p_force)=0;
- virtual Vector2 body_get_applied_force(RID p_body) const=0;
+ virtual void body_set_applied_force(RID p_body, const Vector2 &p_force) = 0;
+ virtual Vector2 body_get_applied_force(RID p_body) const = 0;
- virtual void body_set_applied_torque(RID p_body, float p_torque)=0;
- virtual float body_get_applied_torque(RID p_body) const=0;
+ virtual void body_set_applied_torque(RID p_body, float p_torque) = 0;
+ virtual float body_get_applied_torque(RID p_body) const = 0;
- virtual void body_add_force(RID p_body, const Vector2& p_offset, const Vector2& p_force)=0;
+ virtual void body_add_force(RID p_body, const Vector2 &p_offset, const Vector2 &p_force) = 0;
- virtual void body_apply_impulse(RID p_body, const Vector2& p_offset, const Vector2& p_impulse)=0;
- virtual void body_set_axis_velocity(RID p_body, const Vector2& p_axis_velocity)=0;
+ virtual void body_apply_impulse(RID p_body, const Vector2 &p_offset, const Vector2 &p_impulse) = 0;
+ virtual void body_set_axis_velocity(RID p_body, const Vector2 &p_axis_velocity) = 0;
//fix
- virtual void body_add_collision_exception(RID p_body, RID p_body_b)=0;
- virtual void body_remove_collision_exception(RID p_body, RID p_body_b)=0;
- virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0;
+ virtual void body_add_collision_exception(RID p_body, RID p_body_b) = 0;
+ virtual void body_remove_collision_exception(RID p_body, RID p_body_b) = 0;
+ virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) = 0;
- virtual void body_set_max_contacts_reported(RID p_body, int p_contacts)=0;
- virtual int body_get_max_contacts_reported(RID p_body) const=0;
+ virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) = 0;
+ virtual int body_get_max_contacts_reported(RID p_body) const = 0;
- virtual void body_set_one_way_collision_direction(RID p_body,const Vector2& p_direction)=0;
- virtual Vector2 body_get_one_way_collision_direction(RID p_body) const=0;
+ virtual void body_set_one_way_collision_direction(RID p_body, const Vector2 &p_direction) = 0;
+ virtual Vector2 body_get_one_way_collision_direction(RID p_body) const = 0;
- virtual void body_set_one_way_collision_max_depth(RID p_body,float p_max_depth)=0;
- virtual float body_get_one_way_collision_max_depth(RID p_body) const=0;
+ virtual void body_set_one_way_collision_max_depth(RID p_body, float p_max_depth) = 0;
+ virtual float body_get_one_way_collision_max_depth(RID p_body) const = 0;
//missing remove
- virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold)=0;
- virtual float body_get_contacts_reported_depth_treshold(RID p_body) const=0;
+ virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold) = 0;
+ virtual float body_get_contacts_reported_depth_treshold(RID p_body) const = 0;
- virtual void body_set_omit_force_integration(RID p_body,bool p_omit)=0;
- virtual bool body_is_omitting_force_integration(RID p_body) const=0;
+ virtual void body_set_omit_force_integration(RID p_body, bool p_omit) = 0;
+ virtual bool body_is_omitting_force_integration(RID p_body) const = 0;
- virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant())=0;
+ virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()) = 0;
- virtual bool body_collide_shape(RID p_body, int p_body_shape,RID p_shape, const Transform2D& p_shape_xform,const Vector2& p_motion,Vector2 *r_results,int p_result_max,int &r_result_count)=0;
+ virtual bool body_collide_shape(RID p_body, int p_body_shape, RID p_shape, const Transform2D &p_shape_xform, const Vector2 &p_motion, Vector2 *r_results, int p_result_max, int &r_result_count) = 0;
- virtual void body_set_pickable(RID p_body,bool p_pickable)=0;
+ virtual void body_set_pickable(RID p_body, bool p_pickable) = 0;
struct MotionResult {
@@ -497,7 +483,7 @@ public:
Variant collider_metadata;
};
- virtual bool body_test_motion(RID p_body,const Transform2D& p_from,const Vector2& p_motion,float p_margin=0.001,MotionResult *r_result=NULL)=0;
+ virtual bool body_test_motion(RID p_body, const Transform2D &p_from, const Vector2 &p_motion, float p_margin = 0.001, MotionResult *r_result = NULL) = 0;
/* JOINT API */
@@ -514,29 +500,29 @@ public:
JOINT_PARAM_MAX_FORCE,
};
- virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value)=0;
- virtual real_t joint_get_param(RID p_joint,JointParam p_param) const=0;
+ virtual void joint_set_param(RID p_joint, JointParam p_param, real_t p_value) = 0;
+ virtual real_t joint_get_param(RID p_joint, JointParam p_param) const = 0;
- virtual RID pin_joint_create(const Vector2& p_anchor,RID p_body_a,RID p_body_b=RID())=0;
- virtual RID groove_joint_create(const Vector2& p_a_groove1,const Vector2& p_a_groove2, const Vector2& p_b_anchor, RID p_body_a,RID p_body_b)=0;
- virtual RID damped_spring_joint_create(const Vector2& p_anchor_a,const Vector2& p_anchor_b,RID p_body_a,RID p_body_b=RID())=0;
+ virtual RID pin_joint_create(const Vector2 &p_anchor, RID p_body_a, RID p_body_b = RID()) = 0;
+ virtual RID groove_joint_create(const Vector2 &p_a_groove1, const Vector2 &p_a_groove2, const Vector2 &p_b_anchor, RID p_body_a, RID p_body_b) = 0;
+ virtual RID damped_spring_joint_create(const Vector2 &p_anchor_a, const Vector2 &p_anchor_b, RID p_body_a, RID p_body_b = RID()) = 0;
enum PinJointParam {
PIN_JOINT_SOFTNESS
};
- virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value)=0;
- virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const=0;
+ virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, real_t p_value) = 0;
+ virtual real_t pin_joint_get_param(RID p_joint, PinJointParam p_param) const = 0;
enum DampedStringParam {
DAMPED_STRING_REST_LENGTH,
DAMPED_STRING_STIFFNESS,
DAMPED_STRING_DAMPING
};
- virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value)=0;
- virtual real_t damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const=0;
+ virtual void damped_string_joint_set_param(RID p_joint, DampedStringParam p_param, real_t p_value) = 0;
+ virtual real_t damped_string_joint_get_param(RID p_joint, DampedStringParam p_param) const = 0;
- virtual JointType joint_get_type(RID p_joint) const=0;
+ virtual JointType joint_get_type(RID p_joint) const = 0;
/* QUERY API */
@@ -545,18 +531,17 @@ public:
AREA_BODY_REMOVED
};
-
/* MISC */
- virtual void free(RID p_rid)=0;
+ virtual void free(RID p_rid) = 0;
- virtual void set_active(bool p_active)=0;
- virtual void init()=0;
- virtual void step(float p_step)=0;
- virtual void sync()=0;
- virtual void flush_queries()=0;
- virtual void end_sync()=0;
- virtual void finish()=0;
+ virtual void set_active(bool p_active) = 0;
+ virtual void init() = 0;
+ virtual void step(float p_step) = 0;
+ virtual void sync() = 0;
+ virtual void flush_queries() = 0;
+ virtual void end_sync() = 0;
+ virtual void finish() = 0;
enum ProcessInfo {
@@ -567,26 +552,25 @@ public:
INFO_BROAD_PHASE_TIME
};
- virtual int get_process_info(ProcessInfo p_info)=0;
+ virtual int get_process_info(ProcessInfo p_info) = 0;
Physics2DServer();
~Physics2DServer();
};
-
class Physics2DTestMotionResult : public Reference {
- GDCLASS( Physics2DTestMotionResult, Reference );
+ GDCLASS(Physics2DTestMotionResult, Reference);
Physics2DServer::MotionResult result;
bool colliding;
-friend class Physics2DServer;
+ friend class Physics2DServer;
protected:
static void _bind_methods();
-public:
- Physics2DServer::MotionResult* get_result_ptr() const { return const_cast<Physics2DServer::MotionResult*>(&result); }
+public:
+ Physics2DServer::MotionResult *get_result_ptr() const { return const_cast<Physics2DServer::MotionResult *>(&result); }
//bool is_colliding() const;
Vector2 get_motion() const;
@@ -597,26 +581,25 @@ public:
Vector2 get_collider_velocity() const;
ObjectID get_collider_id() const;
RID get_collider_rid() const;
- Object* get_collider() const;
+ Object *get_collider() const;
int get_collider_shape() const;
Physics2DTestMotionResult();
};
-
-VARIANT_ENUM_CAST( Physics2DServer::ShapeType );
-VARIANT_ENUM_CAST( Physics2DServer::SpaceParameter );
-VARIANT_ENUM_CAST( Physics2DServer::AreaParameter );
-VARIANT_ENUM_CAST( Physics2DServer::AreaSpaceOverrideMode );
-VARIANT_ENUM_CAST( Physics2DServer::BodyMode );
-VARIANT_ENUM_CAST( Physics2DServer::BodyParameter );
-VARIANT_ENUM_CAST( Physics2DServer::BodyState );
-VARIANT_ENUM_CAST( Physics2DServer::CCDMode );
-VARIANT_ENUM_CAST( Physics2DServer::JointParam );
-VARIANT_ENUM_CAST( Physics2DServer::JointType );
-VARIANT_ENUM_CAST( Physics2DServer::DampedStringParam );
+VARIANT_ENUM_CAST(Physics2DServer::ShapeType);
+VARIANT_ENUM_CAST(Physics2DServer::SpaceParameter);
+VARIANT_ENUM_CAST(Physics2DServer::AreaParameter);
+VARIANT_ENUM_CAST(Physics2DServer::AreaSpaceOverrideMode);
+VARIANT_ENUM_CAST(Physics2DServer::BodyMode);
+VARIANT_ENUM_CAST(Physics2DServer::BodyParameter);
+VARIANT_ENUM_CAST(Physics2DServer::BodyState);
+VARIANT_ENUM_CAST(Physics2DServer::CCDMode);
+VARIANT_ENUM_CAST(Physics2DServer::JointParam);
+VARIANT_ENUM_CAST(Physics2DServer::JointType);
+VARIANT_ENUM_CAST(Physics2DServer::DampedStringParam);
//VARIANT_ENUM_CAST( Physics2DServer::ObjectType );
-VARIANT_ENUM_CAST( Physics2DServer::AreaBodyStatus );
-VARIANT_ENUM_CAST( Physics2DServer::ProcessInfo );
+VARIANT_ENUM_CAST(Physics2DServer::AreaBodyStatus);
+VARIANT_ENUM_CAST(Physics2DServer::ProcessInfo);
#endif
diff --git a/servers/physics_server.cpp b/servers/physics_server.cpp
index e76bfd113c..d8f77fbe0d 100644
--- a/servers/physics_server.cpp
+++ b/servers/physics_server.cpp
@@ -28,110 +28,102 @@
/*************************************************************************/
#include "physics_server.h"
#include "print_string.h"
-PhysicsServer * PhysicsServer::singleton=NULL;
-
+PhysicsServer *PhysicsServer::singleton = NULL;
void PhysicsDirectBodyState::integrate_forces() {
real_t step = get_step();
Vector3 lv = get_linear_velocity();
- lv+=get_total_gravity() * step;
+ lv += get_total_gravity() * step;
Vector3 av = get_angular_velocity();
float linear_damp = 1.0 - step * get_total_linear_damp();
- if (linear_damp<0) // reached zero in the given time
- linear_damp=0;
+ if (linear_damp < 0) // reached zero in the given time
+ linear_damp = 0;
float angular_damp = 1.0 - step * get_total_angular_damp();
- if (angular_damp<0) // reached zero in the given time
- angular_damp=0;
+ if (angular_damp < 0) // reached zero in the given time
+ angular_damp = 0;
- lv*=linear_damp;
- av*=angular_damp;
+ lv *= linear_damp;
+ av *= angular_damp;
set_linear_velocity(lv);
set_angular_velocity(av);
-
-
-
-
}
-Object* PhysicsDirectBodyState::get_contact_collider_object(int p_contact_idx) const {
+Object *PhysicsDirectBodyState::get_contact_collider_object(int p_contact_idx) const {
ObjectID objid = get_contact_collider_id(p_contact_idx);
- Object *obj = ObjectDB::get_instance( objid );
+ Object *obj = ObjectDB::get_instance(objid);
return obj;
}
-PhysicsServer * PhysicsServer::get_singleton() {
+PhysicsServer *PhysicsServer::get_singleton() {
return singleton;
}
void PhysicsDirectBodyState::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_total_gravity"),&PhysicsDirectBodyState::get_total_gravity);
- ClassDB::bind_method(D_METHOD("get_total_linear_damp"),&PhysicsDirectBodyState::get_total_linear_damp);
- ClassDB::bind_method(D_METHOD("get_total_angular_damp"),&PhysicsDirectBodyState::get_total_angular_damp);
-
- ClassDB::bind_method(D_METHOD("get_center_of_mass"),&PhysicsDirectBodyState::get_center_of_mass);
- ClassDB::bind_method(D_METHOD("get_principal_inetria_axes"),&PhysicsDirectBodyState::get_principal_inertia_axes);
+ ClassDB::bind_method(D_METHOD("get_total_gravity"), &PhysicsDirectBodyState::get_total_gravity);
+ ClassDB::bind_method(D_METHOD("get_total_linear_damp"), &PhysicsDirectBodyState::get_total_linear_damp);
+ ClassDB::bind_method(D_METHOD("get_total_angular_damp"), &PhysicsDirectBodyState::get_total_angular_damp);
- ClassDB::bind_method(D_METHOD("get_inverse_mass"),&PhysicsDirectBodyState::get_inverse_mass);
- ClassDB::bind_method(D_METHOD("get_inverse_inertia"),&PhysicsDirectBodyState::get_inverse_inertia);
+ ClassDB::bind_method(D_METHOD("get_center_of_mass"), &PhysicsDirectBodyState::get_center_of_mass);
+ ClassDB::bind_method(D_METHOD("get_principal_inetria_axes"), &PhysicsDirectBodyState::get_principal_inertia_axes);
- ClassDB::bind_method(D_METHOD("set_linear_velocity","velocity"),&PhysicsDirectBodyState::set_linear_velocity);
- ClassDB::bind_method(D_METHOD("get_linear_velocity"),&PhysicsDirectBodyState::get_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_inverse_mass"), &PhysicsDirectBodyState::get_inverse_mass);
+ ClassDB::bind_method(D_METHOD("get_inverse_inertia"), &PhysicsDirectBodyState::get_inverse_inertia);
- ClassDB::bind_method(D_METHOD("set_angular_velocity","velocity"),&PhysicsDirectBodyState::set_angular_velocity);
- ClassDB::bind_method(D_METHOD("get_angular_velocity"),&PhysicsDirectBodyState::get_angular_velocity);
+ ClassDB::bind_method(D_METHOD("set_linear_velocity", "velocity"), &PhysicsDirectBodyState::set_linear_velocity);
+ ClassDB::bind_method(D_METHOD("get_linear_velocity"), &PhysicsDirectBodyState::get_linear_velocity);
- ClassDB::bind_method(D_METHOD("set_transform","transform"),&PhysicsDirectBodyState::set_transform);
- ClassDB::bind_method(D_METHOD("get_transform"),&PhysicsDirectBodyState::get_transform);
+ ClassDB::bind_method(D_METHOD("set_angular_velocity", "velocity"), &PhysicsDirectBodyState::set_angular_velocity);
+ ClassDB::bind_method(D_METHOD("get_angular_velocity"), &PhysicsDirectBodyState::get_angular_velocity);
- ClassDB::bind_method(D_METHOD("add_force","force","pos"),&PhysicsDirectBodyState::add_force);
- ClassDB::bind_method(D_METHOD("apply_impulse","pos","j"),&PhysicsDirectBodyState::apply_impulse);
- ClassDB::bind_method(D_METHOD("apply_torqe_impulse","j"),&PhysicsDirectBodyState::apply_torque_impulse);
+ ClassDB::bind_method(D_METHOD("set_transform", "transform"), &PhysicsDirectBodyState::set_transform);
+ ClassDB::bind_method(D_METHOD("get_transform"), &PhysicsDirectBodyState::get_transform);
- ClassDB::bind_method(D_METHOD("set_sleep_state","enabled"),&PhysicsDirectBodyState::set_sleep_state);
- ClassDB::bind_method(D_METHOD("is_sleeping"),&PhysicsDirectBodyState::is_sleeping);
+ ClassDB::bind_method(D_METHOD("add_force", "force", "pos"), &PhysicsDirectBodyState::add_force);
+ ClassDB::bind_method(D_METHOD("apply_impulse", "pos", "j"), &PhysicsDirectBodyState::apply_impulse);
+ ClassDB::bind_method(D_METHOD("apply_torqe_impulse", "j"), &PhysicsDirectBodyState::apply_torque_impulse);
- ClassDB::bind_method(D_METHOD("get_contact_count"),&PhysicsDirectBodyState::get_contact_count);
+ ClassDB::bind_method(D_METHOD("set_sleep_state", "enabled"), &PhysicsDirectBodyState::set_sleep_state);
+ ClassDB::bind_method(D_METHOD("is_sleeping"), &PhysicsDirectBodyState::is_sleeping);
- ClassDB::bind_method(D_METHOD("get_contact_local_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_local_pos);
- ClassDB::bind_method(D_METHOD("get_contact_local_normal","contact_idx"),&PhysicsDirectBodyState::get_contact_local_normal);
- ClassDB::bind_method(D_METHOD("get_contact_local_shape","contact_idx"),&PhysicsDirectBodyState::get_contact_local_shape);
- ClassDB::bind_method(D_METHOD("get_contact_collider","contact_idx"),&PhysicsDirectBodyState::get_contact_collider);
- ClassDB::bind_method(D_METHOD("get_contact_collider_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_pos);
- ClassDB::bind_method(D_METHOD("get_contact_collider_id","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_id);
- ClassDB::bind_method(D_METHOD("get_contact_collider_object","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_object);
- ClassDB::bind_method(D_METHOD("get_contact_collider_shape","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_shape);
- ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos","contact_idx"),&PhysicsDirectBodyState::get_contact_collider_velocity_at_pos);
- ClassDB::bind_method(D_METHOD("get_step"),&PhysicsDirectBodyState::get_step);
- ClassDB::bind_method(D_METHOD("integrate_forces"),&PhysicsDirectBodyState::integrate_forces);
- ClassDB::bind_method(D_METHOD("get_space_state:PhysicsDirectSpaceState"),&PhysicsDirectBodyState::get_space_state);
+ ClassDB::bind_method(D_METHOD("get_contact_count"), &PhysicsDirectBodyState::get_contact_count);
+ ClassDB::bind_method(D_METHOD("get_contact_local_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_pos);
+ ClassDB::bind_method(D_METHOD("get_contact_local_normal", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_normal);
+ ClassDB::bind_method(D_METHOD("get_contact_local_shape", "contact_idx"), &PhysicsDirectBodyState::get_contact_local_shape);
+ ClassDB::bind_method(D_METHOD("get_contact_collider", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_pos);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_id", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_id);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_object", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_object);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_shape", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_shape);
+ ClassDB::bind_method(D_METHOD("get_contact_collider_velocity_at_pos", "contact_idx"), &PhysicsDirectBodyState::get_contact_collider_velocity_at_pos);
+ ClassDB::bind_method(D_METHOD("get_step"), &PhysicsDirectBodyState::get_step);
+ ClassDB::bind_method(D_METHOD("integrate_forces"), &PhysicsDirectBodyState::integrate_forces);
+ ClassDB::bind_method(D_METHOD("get_space_state:PhysicsDirectSpaceState"), &PhysicsDirectBodyState::get_space_state);
}
PhysicsDirectBodyState::PhysicsDirectBodyState() {}
///////////////////////////////////////////////////////
-
-
void PhysicsShapeQueryParameters::set_shape(const RES &p_shape) {
ERR_FAIL_COND(p_shape.is_null());
- shape=p_shape->get_rid();
+ shape = p_shape->get_rid();
}
-void PhysicsShapeQueryParameters::set_shape_rid(const RID& p_shape) {
+void PhysicsShapeQueryParameters::set_shape_rid(const RID &p_shape) {
- shape=p_shape;
+ shape = p_shape;
}
RID PhysicsShapeQueryParameters::get_shape_rid() const {
@@ -139,95 +131,89 @@ RID PhysicsShapeQueryParameters::get_shape_rid() const {
return shape;
}
-void PhysicsShapeQueryParameters::set_transform(const Transform& p_transform){
+void PhysicsShapeQueryParameters::set_transform(const Transform &p_transform) {
- transform=p_transform;
+ transform = p_transform;
}
-Transform PhysicsShapeQueryParameters::get_transform() const{
+Transform PhysicsShapeQueryParameters::get_transform() const {
return transform;
}
-void PhysicsShapeQueryParameters::set_margin(float p_margin){
+void PhysicsShapeQueryParameters::set_margin(float p_margin) {
- margin=p_margin;
+ margin = p_margin;
}
-float PhysicsShapeQueryParameters::get_margin() const{
+float PhysicsShapeQueryParameters::get_margin() const {
return margin;
}
-void PhysicsShapeQueryParameters::set_layer_mask(int p_layer_mask){
+void PhysicsShapeQueryParameters::set_layer_mask(int p_layer_mask) {
- layer_mask=p_layer_mask;
+ layer_mask = p_layer_mask;
}
-int PhysicsShapeQueryParameters::get_layer_mask() const{
+int PhysicsShapeQueryParameters::get_layer_mask() const {
return layer_mask;
}
+void PhysicsShapeQueryParameters::set_object_type_mask(int p_object_type_mask) {
-void PhysicsShapeQueryParameters::set_object_type_mask(int p_object_type_mask){
-
- object_type_mask=p_object_type_mask;
+ object_type_mask = p_object_type_mask;
}
-int PhysicsShapeQueryParameters::get_object_type_mask() const{
+int PhysicsShapeQueryParameters::get_object_type_mask() const {
return object_type_mask;
}
-void PhysicsShapeQueryParameters::set_exclude(const Vector<RID>& p_exclude) {
+void PhysicsShapeQueryParameters::set_exclude(const Vector<RID> &p_exclude) {
exclude.clear();
- for(int i=0;i<p_exclude.size();i++)
+ for (int i = 0; i < p_exclude.size(); i++)
exclude.insert(p_exclude[i]);
-
}
-Vector<RID> PhysicsShapeQueryParameters::get_exclude() const{
+Vector<RID> PhysicsShapeQueryParameters::get_exclude() const {
Vector<RID> ret;
ret.resize(exclude.size());
- int idx=0;
- for(Set<RID>::Element *E=exclude.front();E;E=E->next()) {
- ret[idx]=E->get();
+ int idx = 0;
+ for (Set<RID>::Element *E = exclude.front(); E; E = E->next()) {
+ ret[idx] = E->get();
}
return ret;
}
void PhysicsShapeQueryParameters::_bind_methods() {
- ClassDB::bind_method(D_METHOD("set_shape","shape:Shape"),&PhysicsShapeQueryParameters::set_shape);
- ClassDB::bind_method(D_METHOD("set_shape_rid","shape"),&PhysicsShapeQueryParameters::set_shape_rid);
- ClassDB::bind_method(D_METHOD("get_shape_rid"),&PhysicsShapeQueryParameters::get_shape_rid);
-
- ClassDB::bind_method(D_METHOD("set_transform","transform"),&PhysicsShapeQueryParameters::set_transform);
- ClassDB::bind_method(D_METHOD("get_transform"),&PhysicsShapeQueryParameters::get_transform);
+ ClassDB::bind_method(D_METHOD("set_shape", "shape:Shape"), &PhysicsShapeQueryParameters::set_shape);
+ ClassDB::bind_method(D_METHOD("set_shape_rid", "shape"), &PhysicsShapeQueryParameters::set_shape_rid);
+ ClassDB::bind_method(D_METHOD("get_shape_rid"), &PhysicsShapeQueryParameters::get_shape_rid);
- ClassDB::bind_method(D_METHOD("set_margin","margin"),&PhysicsShapeQueryParameters::set_margin);
- ClassDB::bind_method(D_METHOD("get_margin"),&PhysicsShapeQueryParameters::get_margin);
+ ClassDB::bind_method(D_METHOD("set_transform", "transform"), &PhysicsShapeQueryParameters::set_transform);
+ ClassDB::bind_method(D_METHOD("get_transform"), &PhysicsShapeQueryParameters::get_transform);
- ClassDB::bind_method(D_METHOD("set_layer_mask","layer_mask"),&PhysicsShapeQueryParameters::set_layer_mask);
- ClassDB::bind_method(D_METHOD("get_layer_mask"),&PhysicsShapeQueryParameters::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_margin", "margin"), &PhysicsShapeQueryParameters::set_margin);
+ ClassDB::bind_method(D_METHOD("get_margin"), &PhysicsShapeQueryParameters::get_margin);
- ClassDB::bind_method(D_METHOD("set_object_type_mask","object_type_mask"),&PhysicsShapeQueryParameters::set_object_type_mask);
- ClassDB::bind_method(D_METHOD("get_object_type_mask"),&PhysicsShapeQueryParameters::get_object_type_mask);
-
- ClassDB::bind_method(D_METHOD("set_exclude","exclude"),&PhysicsShapeQueryParameters::set_exclude);
- ClassDB::bind_method(D_METHOD("get_exclude"),&PhysicsShapeQueryParameters::get_exclude);
+ ClassDB::bind_method(D_METHOD("set_layer_mask", "layer_mask"), &PhysicsShapeQueryParameters::set_layer_mask);
+ ClassDB::bind_method(D_METHOD("get_layer_mask"), &PhysicsShapeQueryParameters::get_layer_mask);
+ ClassDB::bind_method(D_METHOD("set_object_type_mask", "object_type_mask"), &PhysicsShapeQueryParameters::set_object_type_mask);
+ ClassDB::bind_method(D_METHOD("get_object_type_mask"), &PhysicsShapeQueryParameters::get_object_type_mask);
+ ClassDB::bind_method(D_METHOD("set_exclude", "exclude"), &PhysicsShapeQueryParameters::set_exclude);
+ ClassDB::bind_method(D_METHOD("get_exclude"), &PhysicsShapeQueryParameters::get_exclude);
}
PhysicsShapeQueryParameters::PhysicsShapeQueryParameters() {
- margin=0;
- layer_mask=0x7FFFFFFF;
- object_type_mask=PhysicsDirectSpaceState::TYPE_MASK_COLLISION;
+ margin = 0;
+ layer_mask = 0x7FFFFFFF;
+ object_type_mask = PhysicsDirectSpaceState::TYPE_MASK_COLLISION;
}
-
-
/////////////////////////////////////
/*
@@ -260,26 +246,25 @@ Variant PhysicsDirectSpaceState::_intersect_shape(const RID& p_shape, const Tran
}
*/
-
-Dictionary PhysicsDirectSpaceState::_intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude,uint32_t p_layers,uint32_t p_object_type_mask) {
+Dictionary PhysicsDirectSpaceState::_intersect_ray(const Vector3 &p_from, const Vector3 &p_to, const Vector<RID> &p_exclude, uint32_t p_layers, uint32_t p_object_type_mask) {
RayResult inters;
Set<RID> exclude;
- for(int i=0;i<p_exclude.size();i++)
+ for (int i = 0; i < p_exclude.size(); i++)
exclude.insert(p_exclude[i]);
- bool res = intersect_ray(p_from,p_to,inters,exclude,p_layers,p_object_type_mask);
+ bool res = intersect_ray(p_from, p_to, inters, exclude, p_layers, p_object_type_mask);
if (!res)
return Dictionary();
Dictionary d;
- d["position"]=inters.position;
- d["normal"]=inters.normal;
- d["collider_id"]=inters.collider_id;
- d["collider"]=inters.collider;
- d["shape"]=inters.shape;
- d["rid"]=inters.rid;
+ d["position"] = inters.position;
+ d["normal"] = inters.normal;
+ d["collider_id"] = inters.collider_id;
+ d["collider"] = inters.collider;
+ d["shape"] = inters.shape;
+ d["rid"] = inters.rid;
return d;
}
@@ -288,101 +273,89 @@ Array PhysicsDirectSpaceState::_intersect_shape(const Ref<PhysicsShapeQueryParam
Vector<ShapeResult> sr;
sr.resize(p_max_results);
- int rc = intersect_shape(psq->shape,psq->transform,psq->margin,sr.ptr(),sr.size(),psq->exclude,psq->layer_mask,psq->object_type_mask);
+ int rc = intersect_shape(psq->shape, psq->transform, psq->margin, sr.ptr(), sr.size(), psq->exclude, psq->layer_mask, psq->object_type_mask);
Array ret;
ret.resize(rc);
- for(int i=0;i<rc;i++) {
+ for (int i = 0; i < rc; i++) {
Dictionary d;
- d["rid"]=sr[i].rid;
- d["collider_id"]=sr[i].collider_id;
- d["collider"]=sr[i].collider;
- d["shape"]=sr[i].shape;
- ret[i]=d;
+ d["rid"] = sr[i].rid;
+ d["collider_id"] = sr[i].collider_id;
+ d["collider"] = sr[i].collider;
+ d["shape"] = sr[i].shape;
+ ret[i] = d;
}
return ret;
}
-Array PhysicsDirectSpaceState::_cast_motion(const Ref<PhysicsShapeQueryParameters> &psq,const Vector3& p_motion){
+Array PhysicsDirectSpaceState::_cast_motion(const Ref<PhysicsShapeQueryParameters> &psq, const Vector3 &p_motion) {
- float closest_safe,closest_unsafe;
- bool res = cast_motion(psq->shape,psq->transform,p_motion,psq->margin,closest_safe,closest_unsafe,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ float closest_safe, closest_unsafe;
+ bool res = cast_motion(psq->shape, psq->transform, p_motion, psq->margin, closest_safe, closest_unsafe, psq->exclude, psq->layer_mask, psq->object_type_mask);
if (!res)
return Array();
Array ret;
ret.resize(2);
- ret[0]=closest_safe;
- ret[1]=closest_unsafe;
+ ret[0] = closest_safe;
+ ret[1] = closest_unsafe;
return ret;
-
}
-Array PhysicsDirectSpaceState::_collide_shape(const Ref<PhysicsShapeQueryParameters> &psq, int p_max_results){
+Array PhysicsDirectSpaceState::_collide_shape(const Ref<PhysicsShapeQueryParameters> &psq, int p_max_results) {
Vector<Vector3> ret;
- ret.resize(p_max_results*2);
- int rc=0;
- bool res = collide_shape(psq->shape,psq->transform,psq->margin,ret.ptr(),p_max_results,rc,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ ret.resize(p_max_results * 2);
+ int rc = 0;
+ bool res = collide_shape(psq->shape, psq->transform, psq->margin, ret.ptr(), p_max_results, rc, psq->exclude, psq->layer_mask, psq->object_type_mask);
if (!res)
return Array();
Array r;
- r.resize(rc*2);
- for(int i=0;i<rc*2;i++)
- r[i]=ret[i];
+ r.resize(rc * 2);
+ for (int i = 0; i < rc * 2; i++)
+ r[i] = ret[i];
return r;
-
}
-Dictionary PhysicsDirectSpaceState::_get_rest_info(const Ref<PhysicsShapeQueryParameters> &psq){
+Dictionary PhysicsDirectSpaceState::_get_rest_info(const Ref<PhysicsShapeQueryParameters> &psq) {
ShapeRestInfo sri;
- bool res = rest_info(psq->shape,psq->transform,psq->margin,&sri,psq->exclude,psq->layer_mask,psq->object_type_mask);
+ bool res = rest_info(psq->shape, psq->transform, psq->margin, &sri, psq->exclude, psq->layer_mask, psq->object_type_mask);
Dictionary r;
if (!res)
return r;
- r["point"]=sri.point;
- r["normal"]=sri.normal;
- r["rid"]=sri.rid;
- r["collider_id"]=sri.collider_id;
- r["shape"]=sri.shape;
- r["linear_velocity"]=sri.linear_velocity;
+ r["point"] = sri.point;
+ r["normal"] = sri.normal;
+ r["rid"] = sri.rid;
+ r["collider_id"] = sri.collider_id;
+ r["shape"] = sri.shape;
+ r["linear_velocity"] = sri.linear_velocity;
return r;
}
-
-
PhysicsDirectSpaceState::PhysicsDirectSpaceState() {
-
-
-
}
-
void PhysicsDirectSpaceState::_bind_methods() {
-
//ClassDB::bind_method(D_METHOD("intersect_ray","from","to","exclude","umask"),&PhysicsDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0));
//ClassDB::bind_method(D_METHOD("intersect_shape:PhysicsShapeQueryResult","shape","xform","result_max","exclude","umask"),&PhysicsDirectSpaceState::_intersect_shape,DEFVAL(Array()),DEFVAL(0));
- ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary","from","to","exclude","layer_mask","type_mask"),&PhysicsDirectSpaceState::_intersect_ray,DEFVAL(Array()),DEFVAL(0x7FFFFFFF),DEFVAL(TYPE_MASK_COLLISION));
- ClassDB::bind_method(D_METHOD("intersect_shape","shape:PhysicsShapeQueryParameters","max_results"),&PhysicsDirectSpaceState::_intersect_shape,DEFVAL(32));
- ClassDB::bind_method(D_METHOD("cast_motion","shape:PhysicsShapeQueryParameters","motion"),&PhysicsDirectSpaceState::_cast_motion);
- ClassDB::bind_method(D_METHOD("collide_shape","shape:PhysicsShapeQueryParameters","max_results"),&PhysicsDirectSpaceState::_collide_shape,DEFVAL(32));
- ClassDB::bind_method(D_METHOD("get_rest_info","shape:PhysicsShapeQueryParameters"),&PhysicsDirectSpaceState::_get_rest_info);
-
-
- BIND_CONSTANT( TYPE_MASK_STATIC_BODY );
- BIND_CONSTANT( TYPE_MASK_KINEMATIC_BODY );
- BIND_CONSTANT( TYPE_MASK_RIGID_BODY );
- BIND_CONSTANT( TYPE_MASK_CHARACTER_BODY );
- BIND_CONSTANT( TYPE_MASK_AREA );
- BIND_CONSTANT( TYPE_MASK_COLLISION );
+ ClassDB::bind_method(D_METHOD("intersect_ray:Dictionary", "from", "to", "exclude", "layer_mask", "type_mask"), &PhysicsDirectSpaceState::_intersect_ray, DEFVAL(Array()), DEFVAL(0x7FFFFFFF), DEFVAL(TYPE_MASK_COLLISION));
+ ClassDB::bind_method(D_METHOD("intersect_shape", "shape:PhysicsShapeQueryParameters", "max_results"), &PhysicsDirectSpaceState::_intersect_shape, DEFVAL(32));
+ ClassDB::bind_method(D_METHOD("cast_motion", "shape:PhysicsShapeQueryParameters", "motion"), &PhysicsDirectSpaceState::_cast_motion);
+ ClassDB::bind_method(D_METHOD("collide_shape", "shape:PhysicsShapeQueryParameters", "max_results"), &PhysicsDirectSpaceState::_collide_shape, DEFVAL(32));
+ ClassDB::bind_method(D_METHOD("get_rest_info", "shape:PhysicsShapeQueryParameters"), &PhysicsDirectSpaceState::_get_rest_info);
+ BIND_CONSTANT(TYPE_MASK_STATIC_BODY);
+ BIND_CONSTANT(TYPE_MASK_KINEMATIC_BODY);
+ BIND_CONSTANT(TYPE_MASK_RIGID_BODY);
+ BIND_CONSTANT(TYPE_MASK_CHARACTER_BODY);
+ BIND_CONSTANT(TYPE_MASK_AREA);
+ BIND_CONSTANT(TYPE_MASK_COLLISION);
}
-
int PhysicsShapeQueryResult::get_result_count() const {
return result.size();
@@ -395,7 +368,7 @@ ObjectID PhysicsShapeQueryResult::get_result_object_id(int p_idx) const {
return result[p_idx].collider_id;
}
-Object* PhysicsShapeQueryResult::get_result_object(int p_idx) const {
+Object *PhysicsShapeQueryResult::get_result_object(int p_idx) const {
return result[p_idx].collider;
}
@@ -405,165 +378,152 @@ int PhysicsShapeQueryResult::get_result_object_shape(int p_idx) const {
}
PhysicsShapeQueryResult::PhysicsShapeQueryResult() {
-
-
}
void PhysicsShapeQueryResult::_bind_methods() {
- ClassDB::bind_method(D_METHOD("get_result_count"),&PhysicsShapeQueryResult::get_result_count);
- ClassDB::bind_method(D_METHOD("get_result_rid","idx"),&PhysicsShapeQueryResult::get_result_rid);
- ClassDB::bind_method(D_METHOD("get_result_object_id","idx"),&PhysicsShapeQueryResult::get_result_object_id);
- ClassDB::bind_method(D_METHOD("get_result_object","idx"),&PhysicsShapeQueryResult::get_result_object);
- ClassDB::bind_method(D_METHOD("get_result_object_shape","idx"),&PhysicsShapeQueryResult::get_result_object_shape);
-
-
+ ClassDB::bind_method(D_METHOD("get_result_count"), &PhysicsShapeQueryResult::get_result_count);
+ ClassDB::bind_method(D_METHOD("get_result_rid", "idx"), &PhysicsShapeQueryResult::get_result_rid);
+ ClassDB::bind_method(D_METHOD("get_result_object_id", "idx"), &PhysicsShapeQueryResult::get_result_object_id);
+ ClassDB::bind_method(D_METHOD("get_result_object", "idx"), &PhysicsShapeQueryResult::get_result_object);
+ ClassDB::bind_method(D_METHOD("get_result_object_shape", "idx"), &PhysicsShapeQueryResult::get_result_object_shape);
}
-
-
-
-
///////////////////////////////////////
void PhysicsServer::_bind_methods() {
+ ClassDB::bind_method(D_METHOD("shape_create", "type"), &PhysicsServer::shape_create);
+ ClassDB::bind_method(D_METHOD("shape_set_data", "shape", "data"), &PhysicsServer::shape_set_data);
- ClassDB::bind_method(D_METHOD("shape_create","type"),&PhysicsServer::shape_create);
- ClassDB::bind_method(D_METHOD("shape_set_data","shape","data"),&PhysicsServer::shape_set_data);
-
- ClassDB::bind_method(D_METHOD("shape_get_type","shape"),&PhysicsServer::shape_get_type);
- ClassDB::bind_method(D_METHOD("shape_get_data","shape"),&PhysicsServer::shape_get_data);
+ ClassDB::bind_method(D_METHOD("shape_get_type", "shape"), &PhysicsServer::shape_get_type);
+ ClassDB::bind_method(D_METHOD("shape_get_data", "shape"), &PhysicsServer::shape_get_data);
+ ClassDB::bind_method(D_METHOD("space_create"), &PhysicsServer::space_create);
+ ClassDB::bind_method(D_METHOD("space_set_active", "space", "active"), &PhysicsServer::space_set_active);
+ ClassDB::bind_method(D_METHOD("space_is_active", "space"), &PhysicsServer::space_is_active);
+ ClassDB::bind_method(D_METHOD("space_set_param", "space", "param", "value"), &PhysicsServer::space_set_param);
+ ClassDB::bind_method(D_METHOD("space_get_param", "space", "param"), &PhysicsServer::space_get_param);
+ ClassDB::bind_method(D_METHOD("space_get_direct_state:PhysicsDirectSpaceState", "space"), &PhysicsServer::space_get_direct_state);
- ClassDB::bind_method(D_METHOD("space_create"),&PhysicsServer::space_create);
- ClassDB::bind_method(D_METHOD("space_set_active","space","active"),&PhysicsServer::space_set_active);
- ClassDB::bind_method(D_METHOD("space_is_active","space"),&PhysicsServer::space_is_active);
- ClassDB::bind_method(D_METHOD("space_set_param","space","param","value"),&PhysicsServer::space_set_param);
- ClassDB::bind_method(D_METHOD("space_get_param","space","param"),&PhysicsServer::space_get_param);
- ClassDB::bind_method(D_METHOD("space_get_direct_state:PhysicsDirectSpaceState","space"),&PhysicsServer::space_get_direct_state);
+ ClassDB::bind_method(D_METHOD("area_create"), &PhysicsServer::area_create);
+ ClassDB::bind_method(D_METHOD("area_set_space", "area", "space"), &PhysicsServer::area_set_space);
+ ClassDB::bind_method(D_METHOD("area_get_space", "area"), &PhysicsServer::area_get_space);
- ClassDB::bind_method(D_METHOD("area_create"),&PhysicsServer::area_create);
- ClassDB::bind_method(D_METHOD("area_set_space","area","space"),&PhysicsServer::area_set_space);
- ClassDB::bind_method(D_METHOD("area_get_space","area"),&PhysicsServer::area_get_space);
+ ClassDB::bind_method(D_METHOD("area_set_space_override_mode", "area", "mode"), &PhysicsServer::area_set_space_override_mode);
+ ClassDB::bind_method(D_METHOD("area_get_space_override_mode", "area"), &PhysicsServer::area_get_space_override_mode);
- ClassDB::bind_method(D_METHOD("area_set_space_override_mode","area","mode"),&PhysicsServer::area_set_space_override_mode);
- ClassDB::bind_method(D_METHOD("area_get_space_override_mode","area"),&PhysicsServer::area_get_space_override_mode);
+ ClassDB::bind_method(D_METHOD("area_add_shape", "area", "shape", "transform"), &PhysicsServer::area_add_shape, DEFVAL(Transform()));
+ ClassDB::bind_method(D_METHOD("area_set_shape", "area", "shape_idx", "shape"), &PhysicsServer::area_set_shape);
+ ClassDB::bind_method(D_METHOD("area_set_shape_transform", "area", "shape_idx", "transform"), &PhysicsServer::area_set_shape_transform);
- ClassDB::bind_method(D_METHOD("area_add_shape","area","shape","transform"),&PhysicsServer::area_add_shape,DEFVAL(Transform()));
- ClassDB::bind_method(D_METHOD("area_set_shape","area","shape_idx","shape"),&PhysicsServer::area_set_shape);
- ClassDB::bind_method(D_METHOD("area_set_shape_transform","area","shape_idx","transform"),&PhysicsServer::area_set_shape_transform);
+ ClassDB::bind_method(D_METHOD("area_get_shape_count", "area"), &PhysicsServer::area_get_shape_count);
+ ClassDB::bind_method(D_METHOD("area_get_shape", "area", "shape_idx"), &PhysicsServer::area_get_shape);
+ ClassDB::bind_method(D_METHOD("area_get_shape_transform", "area", "shape_idx"), &PhysicsServer::area_get_shape_transform);
- ClassDB::bind_method(D_METHOD("area_get_shape_count","area"),&PhysicsServer::area_get_shape_count);
- ClassDB::bind_method(D_METHOD("area_get_shape","area","shape_idx"),&PhysicsServer::area_get_shape);
- ClassDB::bind_method(D_METHOD("area_get_shape_transform","area","shape_idx"),&PhysicsServer::area_get_shape_transform);
+ ClassDB::bind_method(D_METHOD("area_remove_shape", "area", "shape_idx"), &PhysicsServer::area_remove_shape);
+ ClassDB::bind_method(D_METHOD("area_clear_shapes", "area"), &PhysicsServer::area_clear_shapes);
- ClassDB::bind_method(D_METHOD("area_remove_shape","area","shape_idx"),&PhysicsServer::area_remove_shape);
- ClassDB::bind_method(D_METHOD("area_clear_shapes","area"),&PhysicsServer::area_clear_shapes);
+ ClassDB::bind_method(D_METHOD("area_set_layer_mask", "area", "mask"), &PhysicsServer::area_set_layer_mask);
+ ClassDB::bind_method(D_METHOD("area_set_collision_mask", "area", "mask"), &PhysicsServer::area_set_collision_mask);
- ClassDB::bind_method(D_METHOD("area_set_layer_mask","area","mask"),&PhysicsServer::area_set_layer_mask);
- ClassDB::bind_method(D_METHOD("area_set_collision_mask","area","mask"),&PhysicsServer::area_set_collision_mask);
+ ClassDB::bind_method(D_METHOD("area_set_param", "area", "param", "value"), &PhysicsServer::area_set_param);
+ ClassDB::bind_method(D_METHOD("area_set_transform", "area", "transform"), &PhysicsServer::area_set_transform);
- ClassDB::bind_method(D_METHOD("area_set_param","area","param","value"),&PhysicsServer::area_set_param);
- ClassDB::bind_method(D_METHOD("area_set_transform","area","transform"),&PhysicsServer::area_set_transform);
+ ClassDB::bind_method(D_METHOD("area_get_param", "area", "param"), &PhysicsServer::area_get_param);
+ ClassDB::bind_method(D_METHOD("area_get_transform", "area"), &PhysicsServer::area_get_transform);
- ClassDB::bind_method(D_METHOD("area_get_param","area","param"),&PhysicsServer::area_get_param);
- ClassDB::bind_method(D_METHOD("area_get_transform","area"),&PhysicsServer::area_get_transform);
+ ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID", "area", "id"), &PhysicsServer::area_attach_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("area_get_object_instance_ID", "area"), &PhysicsServer::area_get_object_instance_ID);
- ClassDB::bind_method(D_METHOD("area_attach_object_instance_ID","area","id"),&PhysicsServer::area_attach_object_instance_ID);
- ClassDB::bind_method(D_METHOD("area_get_object_instance_ID","area"),&PhysicsServer::area_get_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("area_set_monitor_callback", "area", "receiver", "method"), &PhysicsServer::area_set_monitor_callback);
- ClassDB::bind_method(D_METHOD("area_set_monitor_callback","area","receiver","method"),&PhysicsServer::area_set_monitor_callback);
+ ClassDB::bind_method(D_METHOD("area_set_ray_pickable", "area", "enable"), &PhysicsServer::area_set_ray_pickable);
+ ClassDB::bind_method(D_METHOD("area_is_ray_pickable", "area"), &PhysicsServer::area_is_ray_pickable);
- ClassDB::bind_method(D_METHOD("area_set_ray_pickable","area","enable"),&PhysicsServer::area_set_ray_pickable);
- ClassDB::bind_method(D_METHOD("area_is_ray_pickable","area"),&PhysicsServer::area_is_ray_pickable);
+ ClassDB::bind_method(D_METHOD("body_create", "mode", "init_sleeping"), &PhysicsServer::body_create, DEFVAL(BODY_MODE_RIGID), DEFVAL(false));
- ClassDB::bind_method(D_METHOD("body_create","mode","init_sleeping"),&PhysicsServer::body_create,DEFVAL(BODY_MODE_RIGID),DEFVAL(false));
+ ClassDB::bind_method(D_METHOD("body_set_space", "body", "space"), &PhysicsServer::body_set_space);
+ ClassDB::bind_method(D_METHOD("body_get_space", "body"), &PhysicsServer::body_get_space);
- ClassDB::bind_method(D_METHOD("body_set_space","body","space"),&PhysicsServer::body_set_space);
- ClassDB::bind_method(D_METHOD("body_get_space","body"),&PhysicsServer::body_get_space);
+ ClassDB::bind_method(D_METHOD("body_set_mode", "body", "mode"), &PhysicsServer::body_set_mode);
+ ClassDB::bind_method(D_METHOD("body_get_mode", "body"), &PhysicsServer::body_get_mode);
- ClassDB::bind_method(D_METHOD("body_set_mode","body","mode"),&PhysicsServer::body_set_mode);
- ClassDB::bind_method(D_METHOD("body_get_mode","body"),&PhysicsServer::body_get_mode);
+ ClassDB::bind_method(D_METHOD("body_set_layer_mask", "body", "mask"), &PhysicsServer::body_set_layer_mask);
+ ClassDB::bind_method(D_METHOD("body_get_layer_mask", "body"), &PhysicsServer::body_get_layer_mask);
- ClassDB::bind_method(D_METHOD("body_set_layer_mask","body","mask"),&PhysicsServer::body_set_layer_mask);
- ClassDB::bind_method(D_METHOD("body_get_layer_mask","body"),&PhysicsServer::body_get_layer_mask);
+ ClassDB::bind_method(D_METHOD("body_set_collision_mask", "body", "mask"), &PhysicsServer::body_set_collision_mask);
+ ClassDB::bind_method(D_METHOD("body_get_collision_mask", "body"), &PhysicsServer::body_get_collision_mask);
- ClassDB::bind_method(D_METHOD("body_set_collision_mask","body","mask"),&PhysicsServer::body_set_collision_mask);
- ClassDB::bind_method(D_METHOD("body_get_collision_mask","body"),&PhysicsServer::body_get_collision_mask);
+ ClassDB::bind_method(D_METHOD("body_add_shape", "body", "shape", "transform"), &PhysicsServer::body_add_shape, DEFVAL(Transform()));
+ ClassDB::bind_method(D_METHOD("body_set_shape", "body", "shape_idx", "shape"), &PhysicsServer::body_set_shape);
+ ClassDB::bind_method(D_METHOD("body_set_shape_transform", "body", "shape_idx", "transform"), &PhysicsServer::body_set_shape_transform);
- ClassDB::bind_method(D_METHOD("body_add_shape","body","shape","transform"),&PhysicsServer::body_add_shape,DEFVAL(Transform()));
- ClassDB::bind_method(D_METHOD("body_set_shape","body","shape_idx","shape"),&PhysicsServer::body_set_shape);
- ClassDB::bind_method(D_METHOD("body_set_shape_transform","body","shape_idx","transform"),&PhysicsServer::body_set_shape_transform);
+ ClassDB::bind_method(D_METHOD("body_get_shape_count", "body"), &PhysicsServer::body_get_shape_count);
+ ClassDB::bind_method(D_METHOD("body_get_shape", "body", "shape_idx"), &PhysicsServer::body_get_shape);
+ ClassDB::bind_method(D_METHOD("body_get_shape_transform", "body", "shape_idx"), &PhysicsServer::body_get_shape_transform);
- ClassDB::bind_method(D_METHOD("body_get_shape_count","body"),&PhysicsServer::body_get_shape_count);
- ClassDB::bind_method(D_METHOD("body_get_shape","body","shape_idx"),&PhysicsServer::body_get_shape);
- ClassDB::bind_method(D_METHOD("body_get_shape_transform","body","shape_idx"),&PhysicsServer::body_get_shape_transform);
+ ClassDB::bind_method(D_METHOD("body_remove_shape", "body", "shape_idx"), &PhysicsServer::body_remove_shape);
+ ClassDB::bind_method(D_METHOD("body_clear_shapes", "body"), &PhysicsServer::body_clear_shapes);
- ClassDB::bind_method(D_METHOD("body_remove_shape","body","shape_idx"),&PhysicsServer::body_remove_shape);
- ClassDB::bind_method(D_METHOD("body_clear_shapes","body"),&PhysicsServer::body_clear_shapes);
-
- ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID","body","id"),&PhysicsServer::body_attach_object_instance_ID);
- ClassDB::bind_method(D_METHOD("body_get_object_instance_ID","body"),&PhysicsServer::body_get_object_instance_ID);
-
-
- ClassDB::bind_method(D_METHOD("body_set_enable_continuous_collision_detection","body","enable"),&PhysicsServer::body_set_enable_continuous_collision_detection);
- ClassDB::bind_method(D_METHOD("body_is_continuous_collision_detection_enabled","body"),&PhysicsServer::body_is_continuous_collision_detection_enabled);
+ ClassDB::bind_method(D_METHOD("body_attach_object_instance_ID", "body", "id"), &PhysicsServer::body_attach_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("body_get_object_instance_ID", "body"), &PhysicsServer::body_get_object_instance_ID);
+ ClassDB::bind_method(D_METHOD("body_set_enable_continuous_collision_detection", "body", "enable"), &PhysicsServer::body_set_enable_continuous_collision_detection);
+ ClassDB::bind_method(D_METHOD("body_is_continuous_collision_detection_enabled", "body"), &PhysicsServer::body_is_continuous_collision_detection_enabled);
//ClassDB::bind_method(D_METHOD("body_set_user_flags","flags""),&PhysicsServer::body_set_shape,DEFVAL(Transform));
//ClassDB::bind_method(D_METHOD("body_get_user_flags","body","shape_idx","shape"),&PhysicsServer::body_get_shape);
- ClassDB::bind_method(D_METHOD("body_set_param","body","param","value"),&PhysicsServer::body_set_param);
- ClassDB::bind_method(D_METHOD("body_get_param","body","param"),&PhysicsServer::body_get_param);
+ ClassDB::bind_method(D_METHOD("body_set_param", "body", "param", "value"), &PhysicsServer::body_set_param);
+ ClassDB::bind_method(D_METHOD("body_get_param", "body", "param"), &PhysicsServer::body_get_param);
- ClassDB::bind_method(D_METHOD("body_set_state","body","state","value"),&PhysicsServer::body_set_state);
- ClassDB::bind_method(D_METHOD("body_get_state","body","state"),&PhysicsServer::body_get_state);
+ ClassDB::bind_method(D_METHOD("body_set_state", "body", "state", "value"), &PhysicsServer::body_set_state);
+ ClassDB::bind_method(D_METHOD("body_get_state", "body", "state"), &PhysicsServer::body_get_state);
- ClassDB::bind_method(D_METHOD("body_apply_impulse","body","pos","impulse"),&PhysicsServer::body_apply_impulse);
- ClassDB::bind_method(D_METHOD("body_apply_torque_impulse","body","impulse"),&PhysicsServer::body_apply_torque_impulse);
- ClassDB::bind_method(D_METHOD("body_set_axis_velocity","body","axis_velocity"),&PhysicsServer::body_set_axis_velocity);
+ ClassDB::bind_method(D_METHOD("body_apply_impulse", "body", "pos", "impulse"), &PhysicsServer::body_apply_impulse);
+ ClassDB::bind_method(D_METHOD("body_apply_torque_impulse", "body", "impulse"), &PhysicsServer::body_apply_torque_impulse);
+ ClassDB::bind_method(D_METHOD("body_set_axis_velocity", "body", "axis_velocity"), &PhysicsServer::body_set_axis_velocity);
- ClassDB::bind_method(D_METHOD("body_set_axis_lock","body","axis"),&PhysicsServer::body_set_axis_lock);
- ClassDB::bind_method(D_METHOD("body_get_axis_lock","body"),&PhysicsServer::body_get_axis_lock);
+ ClassDB::bind_method(D_METHOD("body_set_axis_lock", "body", "axis"), &PhysicsServer::body_set_axis_lock);
+ ClassDB::bind_method(D_METHOD("body_get_axis_lock", "body"), &PhysicsServer::body_get_axis_lock);
- ClassDB::bind_method(D_METHOD("body_add_collision_exception","body","excepted_body"),&PhysicsServer::body_add_collision_exception);
- ClassDB::bind_method(D_METHOD("body_remove_collision_exception","body","excepted_body"),&PhysicsServer::body_remove_collision_exception);
+ ClassDB::bind_method(D_METHOD("body_add_collision_exception", "body", "excepted_body"), &PhysicsServer::body_add_collision_exception);
+ ClassDB::bind_method(D_METHOD("body_remove_collision_exception", "body", "excepted_body"), &PhysicsServer::body_remove_collision_exception);
//virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0;
- ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported","body","amount"),&PhysicsServer::body_set_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported","body"),&PhysicsServer::body_get_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("body_set_max_contacts_reported", "body", "amount"), &PhysicsServer::body_set_max_contacts_reported);
+ ClassDB::bind_method(D_METHOD("body_get_max_contacts_reported", "body"), &PhysicsServer::body_get_max_contacts_reported);
- ClassDB::bind_method(D_METHOD("body_set_omit_force_integration","body","enable"),&PhysicsServer::body_set_omit_force_integration);
- ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration","body"),&PhysicsServer::body_is_omitting_force_integration);
+ ClassDB::bind_method(D_METHOD("body_set_omit_force_integration", "body", "enable"), &PhysicsServer::body_set_omit_force_integration);
+ ClassDB::bind_method(D_METHOD("body_is_omitting_force_integration", "body"), &PhysicsServer::body_is_omitting_force_integration);
- ClassDB::bind_method(D_METHOD("body_set_force_integration_callback","body","receiver","method","userdata"),&PhysicsServer::body_set_force_integration_callback,DEFVAL(Variant()));
+ ClassDB::bind_method(D_METHOD("body_set_force_integration_callback", "body", "receiver", "method", "userdata"), &PhysicsServer::body_set_force_integration_callback, DEFVAL(Variant()));
- ClassDB::bind_method(D_METHOD("body_set_ray_pickable","body","enable"),&PhysicsServer::body_set_ray_pickable);
- ClassDB::bind_method(D_METHOD("body_is_ray_pickable","body"),&PhysicsServer::body_is_ray_pickable);
+ ClassDB::bind_method(D_METHOD("body_set_ray_pickable", "body", "enable"), &PhysicsServer::body_set_ray_pickable);
+ ClassDB::bind_method(D_METHOD("body_is_ray_pickable", "body"), &PhysicsServer::body_is_ray_pickable);
/* JOINT API */
- BIND_CONSTANT( JOINT_PIN );
- BIND_CONSTANT( JOINT_HINGE );
- BIND_CONSTANT( JOINT_SLIDER );
- BIND_CONSTANT( JOINT_CONE_TWIST );
- BIND_CONSTANT( JOINT_6DOF );
+ BIND_CONSTANT(JOINT_PIN);
+ BIND_CONSTANT(JOINT_HINGE);
+ BIND_CONSTANT(JOINT_SLIDER);
+ BIND_CONSTANT(JOINT_CONE_TWIST);
+ BIND_CONSTANT(JOINT_6DOF);
- ClassDB::bind_method(D_METHOD("joint_create_pin","body_A","local_A","body_B","local_B"),&PhysicsServer::joint_create_pin);
- ClassDB::bind_method(D_METHOD("pin_joint_set_param","joint","param","value"),&PhysicsServer::pin_joint_set_param);
- ClassDB::bind_method(D_METHOD("pin_joint_get_param","joint","param"),&PhysicsServer::pin_joint_get_param);
+ ClassDB::bind_method(D_METHOD("joint_create_pin", "body_A", "local_A", "body_B", "local_B"), &PhysicsServer::joint_create_pin);
+ ClassDB::bind_method(D_METHOD("pin_joint_set_param", "joint", "param", "value"), &PhysicsServer::pin_joint_set_param);
+ ClassDB::bind_method(D_METHOD("pin_joint_get_param", "joint", "param"), &PhysicsServer::pin_joint_get_param);
- ClassDB::bind_method(D_METHOD("pin_joint_set_local_A","joint","local_A"),&PhysicsServer::pin_joint_set_local_A);
- ClassDB::bind_method(D_METHOD("pin_joint_get_local_A","joint"),&PhysicsServer::pin_joint_get_local_A);
+ ClassDB::bind_method(D_METHOD("pin_joint_set_local_A", "joint", "local_A"), &PhysicsServer::pin_joint_set_local_A);
+ ClassDB::bind_method(D_METHOD("pin_joint_get_local_A", "joint"), &PhysicsServer::pin_joint_get_local_A);
- ClassDB::bind_method(D_METHOD("pin_joint_set_local_B","joint","local_B"),&PhysicsServer::pin_joint_set_local_B);
- ClassDB::bind_method(D_METHOD("pin_joint_get_local_B","joint"),&PhysicsServer::pin_joint_get_local_B);
-
- BIND_CONSTANT(PIN_JOINT_BIAS );
- BIND_CONSTANT(PIN_JOINT_DAMPING );
- BIND_CONSTANT(PIN_JOINT_IMPULSE_CLAMP );
+ ClassDB::bind_method(D_METHOD("pin_joint_set_local_B", "joint", "local_B"), &PhysicsServer::pin_joint_set_local_B);
+ ClassDB::bind_method(D_METHOD("pin_joint_get_local_B", "joint"), &PhysicsServer::pin_joint_get_local_B);
+ BIND_CONSTANT(PIN_JOINT_BIAS);
+ BIND_CONSTANT(PIN_JOINT_DAMPING);
+ BIND_CONSTANT(PIN_JOINT_IMPULSE_CLAMP);
BIND_CONSTANT(HINGE_JOINT_BIAS);
BIND_CONSTANT(HINGE_JOINT_LIMIT_UPPER);
@@ -576,92 +536,88 @@ void PhysicsServer::_bind_methods() {
BIND_CONSTANT(HINGE_JOINT_FLAG_USE_LIMIT);
BIND_CONSTANT(HINGE_JOINT_FLAG_ENABLE_MOTOR);
- ClassDB::bind_method(D_METHOD("joint_create_hinge","body_A","hinge_A","body_B","hinge_B"),&PhysicsServer::joint_create_hinge);
-
- ClassDB::bind_method(D_METHOD("hinge_joint_set_param","joint","param","value"),&PhysicsServer::hinge_joint_set_param);
- ClassDB::bind_method(D_METHOD("hinge_joint_get_param","joint","param"),&PhysicsServer::hinge_joint_get_param);
-
- ClassDB::bind_method(D_METHOD("hinge_joint_set_flag","joint","flag","enabled"),&PhysicsServer::hinge_joint_set_flag);
- ClassDB::bind_method(D_METHOD("hinge_joint_get_flag","joint","flag"),&PhysicsServer::hinge_joint_get_flag);
-
- ClassDB::bind_method(D_METHOD("joint_create_slider","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_slider);
-
- ClassDB::bind_method(D_METHOD("slider_joint_set_param","joint","param","value"),&PhysicsServer::slider_joint_set_param);
- ClassDB::bind_method(D_METHOD("slider_joint_get_param","joint","param"),&PhysicsServer::slider_joint_get_param);
-
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_UPPER );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_LOWER );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_LIMIT_DAMPING );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_MOTION_DAMPING );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING );
-
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_UPPER );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_LOWER );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_LIMIT_DAMPING );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_MOTION_DAMPING );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION );
- BIND_CONSTANT( SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING );
- BIND_CONSTANT( SLIDER_JOINT_MAX );
-
-
- ClassDB::bind_method(D_METHOD("joint_create_cone_twist","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_cone_twist);
-
- ClassDB::bind_method(D_METHOD("cone_twist_joint_set_param","joint","param","value"),&PhysicsServer::cone_twist_joint_set_param);
- ClassDB::bind_method(D_METHOD("cone_twist_joint_get_param","joint","param"),&PhysicsServer::cone_twist_joint_get_param);
-
- BIND_CONSTANT( CONE_TWIST_JOINT_SWING_SPAN );
- BIND_CONSTANT( CONE_TWIST_JOINT_TWIST_SPAN );
- BIND_CONSTANT( CONE_TWIST_JOINT_BIAS );
- BIND_CONSTANT( CONE_TWIST_JOINT_SOFTNESS );
- BIND_CONSTANT( CONE_TWIST_JOINT_RELAXATION );
-
-
- BIND_CONSTANT( G6DOF_JOINT_LINEAR_LOWER_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_LINEAR_UPPER_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS );
- BIND_CONSTANT( G6DOF_JOINT_LINEAR_RESTITUTION );
- BIND_CONSTANT( G6DOF_JOINT_LINEAR_DAMPING );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_LOWER_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_UPPER_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_DAMPING );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_RESTITUTION );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_FORCE_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_ERP );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY );
- BIND_CONSTANT( G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT );
-
-
- BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT );
- BIND_CONSTANT( G6DOF_JOINT_FLAG_ENABLE_MOTOR );
-
- ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&PhysicsServer::joint_get_type);
-
- ClassDB::bind_method(D_METHOD("joint_set_solver_priority","joint","priority"),&PhysicsServer::joint_set_solver_priority);
- ClassDB::bind_method(D_METHOD("joint_get_solver_priority","joint"),&PhysicsServer::joint_get_solver_priority);
-
- ClassDB::bind_method(D_METHOD("joint_create_generic_6dof","body_A","local_ref_A","body_B","local_ref_B"),&PhysicsServer::joint_create_generic_6dof);
-
- ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_param","joint","axis","param","value"),&PhysicsServer::generic_6dof_joint_set_param);
- ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_param","joint","axis","param"),&PhysicsServer::generic_6dof_joint_get_param);
-
- ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_flag","joint","axis","flag","enable"),&PhysicsServer::generic_6dof_joint_set_flag);
- ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_flag","joint","axis","flag"),&PhysicsServer::generic_6dof_joint_get_flag);
-
-
-/*
+ ClassDB::bind_method(D_METHOD("joint_create_hinge", "body_A", "hinge_A", "body_B", "hinge_B"), &PhysicsServer::joint_create_hinge);
+
+ ClassDB::bind_method(D_METHOD("hinge_joint_set_param", "joint", "param", "value"), &PhysicsServer::hinge_joint_set_param);
+ ClassDB::bind_method(D_METHOD("hinge_joint_get_param", "joint", "param"), &PhysicsServer::hinge_joint_get_param);
+
+ ClassDB::bind_method(D_METHOD("hinge_joint_set_flag", "joint", "flag", "enabled"), &PhysicsServer::hinge_joint_set_flag);
+ ClassDB::bind_method(D_METHOD("hinge_joint_get_flag", "joint", "flag"), &PhysicsServer::hinge_joint_get_flag);
+
+ ClassDB::bind_method(D_METHOD("joint_create_slider", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_slider);
+
+ ClassDB::bind_method(D_METHOD("slider_joint_set_param", "joint", "param", "value"), &PhysicsServer::slider_joint_set_param);
+ ClassDB::bind_method(D_METHOD("slider_joint_get_param", "joint", "param"), &PhysicsServer::slider_joint_get_param);
+
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_UPPER);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_LOWER);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_LIMIT_DAMPING);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_MOTION_DAMPING);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_LINEAR_ORTHOGONAL_DAMPING);
+
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_UPPER);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_LOWER);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_LIMIT_DAMPING);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_MOTION_DAMPING);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_SOFTNESS);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_RESTITUTION);
+ BIND_CONSTANT(SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING);
+ BIND_CONSTANT(SLIDER_JOINT_MAX);
+
+ ClassDB::bind_method(D_METHOD("joint_create_cone_twist", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_cone_twist);
+
+ ClassDB::bind_method(D_METHOD("cone_twist_joint_set_param", "joint", "param", "value"), &PhysicsServer::cone_twist_joint_set_param);
+ ClassDB::bind_method(D_METHOD("cone_twist_joint_get_param", "joint", "param"), &PhysicsServer::cone_twist_joint_get_param);
+
+ BIND_CONSTANT(CONE_TWIST_JOINT_SWING_SPAN);
+ BIND_CONSTANT(CONE_TWIST_JOINT_TWIST_SPAN);
+ BIND_CONSTANT(CONE_TWIST_JOINT_BIAS);
+ BIND_CONSTANT(CONE_TWIST_JOINT_SOFTNESS);
+ BIND_CONSTANT(CONE_TWIST_JOINT_RELAXATION);
+
+ BIND_CONSTANT(G6DOF_JOINT_LINEAR_LOWER_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_LINEAR_UPPER_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_LINEAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(G6DOF_JOINT_LINEAR_RESTITUTION);
+ BIND_CONSTANT(G6DOF_JOINT_LINEAR_DAMPING);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_LOWER_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_UPPER_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_LIMIT_SOFTNESS);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_DAMPING);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_RESTITUTION);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_FORCE_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_ERP);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_MOTOR_TARGET_VELOCITY);
+ BIND_CONSTANT(G6DOF_JOINT_ANGULAR_MOTOR_FORCE_LIMIT);
+
+ BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_LINEAR_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_ANGULAR_LIMIT);
+ BIND_CONSTANT(G6DOF_JOINT_FLAG_ENABLE_MOTOR);
+
+ ClassDB::bind_method(D_METHOD("joint_get_type", "joint"), &PhysicsServer::joint_get_type);
+
+ ClassDB::bind_method(D_METHOD("joint_set_solver_priority", "joint", "priority"), &PhysicsServer::joint_set_solver_priority);
+ ClassDB::bind_method(D_METHOD("joint_get_solver_priority", "joint"), &PhysicsServer::joint_get_solver_priority);
+
+ ClassDB::bind_method(D_METHOD("joint_create_generic_6dof", "body_A", "local_ref_A", "body_B", "local_ref_B"), &PhysicsServer::joint_create_generic_6dof);
+
+ ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_param", "joint", "axis", "param", "value"), &PhysicsServer::generic_6dof_joint_set_param);
+ ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_param", "joint", "axis", "param"), &PhysicsServer::generic_6dof_joint_get_param);
+
+ ClassDB::bind_method(D_METHOD("generic_6dof_joint_set_flag", "joint", "axis", "flag", "enable"), &PhysicsServer::generic_6dof_joint_set_flag);
+ ClassDB::bind_method(D_METHOD("generic_6dof_joint_get_flag", "joint", "axis", "flag"), &PhysicsServer::generic_6dof_joint_get_flag);
+
+ /*
ClassDB::bind_method(D_METHOD("joint_set_param","joint","param","value"),&PhysicsServer::joint_set_param);
ClassDB::bind_method(D_METHOD("joint_get_param","joint","param"),&PhysicsServer::joint_get_param);
@@ -674,63 +630,61 @@ void PhysicsServer::_bind_methods() {
ClassDB::bind_method(D_METHOD("joint_get_type","joint"),&PhysicsServer::joint_get_type);
*/
- ClassDB::bind_method(D_METHOD("free_rid","rid"),&PhysicsServer::free);
+ ClassDB::bind_method(D_METHOD("free_rid", "rid"), &PhysicsServer::free);
- ClassDB::bind_method(D_METHOD("set_active","active"),&PhysicsServer::set_active);
+ ClassDB::bind_method(D_METHOD("set_active", "active"), &PhysicsServer::set_active);
//ClassDB::bind_method(D_METHOD("init"),&PhysicsServer::init);
//ClassDB::bind_method(D_METHOD("step"),&PhysicsServer::step);
//ClassDB::bind_method(D_METHOD("sync"),&PhysicsServer::sync);
//ClassDB::bind_method(D_METHOD("flush_queries"),&PhysicsServer::flush_queries);
-
- ClassDB::bind_method(D_METHOD("get_process_info","process_info"),&PhysicsServer::get_process_info);
-
- BIND_CONSTANT( SHAPE_PLANE );
- BIND_CONSTANT( SHAPE_RAY );
- BIND_CONSTANT( SHAPE_SPHERE );
- BIND_CONSTANT( SHAPE_BOX );
- BIND_CONSTANT( SHAPE_CAPSULE );
- BIND_CONSTANT( SHAPE_CONVEX_POLYGON );
- BIND_CONSTANT( SHAPE_CONCAVE_POLYGON );
- BIND_CONSTANT( SHAPE_HEIGHTMAP );
- BIND_CONSTANT( SHAPE_CUSTOM );
-
-
- BIND_CONSTANT( AREA_PARAM_GRAVITY );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_VECTOR );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_IS_POINT );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_DISTANCE_SCALE );
- BIND_CONSTANT( AREA_PARAM_GRAVITY_POINT_ATTENUATION );
- BIND_CONSTANT( AREA_PARAM_LINEAR_DAMP );
- BIND_CONSTANT( AREA_PARAM_ANGULAR_DAMP );
- BIND_CONSTANT( AREA_PARAM_PRIORITY );
-
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_DISABLED );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_COMBINE_REPLACE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE );
- BIND_CONSTANT( AREA_SPACE_OVERRIDE_REPLACE_COMBINE );
-
- BIND_CONSTANT( BODY_MODE_STATIC );
- BIND_CONSTANT( BODY_MODE_KINEMATIC );
- BIND_CONSTANT( BODY_MODE_RIGID );
- BIND_CONSTANT( BODY_MODE_CHARACTER );
-
- BIND_CONSTANT( BODY_PARAM_BOUNCE );
- BIND_CONSTANT( BODY_PARAM_FRICTION );
- BIND_CONSTANT( BODY_PARAM_MASS );
- BIND_CONSTANT( BODY_PARAM_GRAVITY_SCALE );
- BIND_CONSTANT( BODY_PARAM_ANGULAR_DAMP );
- BIND_CONSTANT( BODY_PARAM_LINEAR_DAMP );
- BIND_CONSTANT( BODY_PARAM_MAX );
-
- BIND_CONSTANT( BODY_STATE_TRANSFORM );
- BIND_CONSTANT( BODY_STATE_LINEAR_VELOCITY );
- BIND_CONSTANT( BODY_STATE_ANGULAR_VELOCITY );
- BIND_CONSTANT( BODY_STATE_SLEEPING );
- BIND_CONSTANT( BODY_STATE_CAN_SLEEP );
-/*
+ ClassDB::bind_method(D_METHOD("get_process_info", "process_info"), &PhysicsServer::get_process_info);
+
+ BIND_CONSTANT(SHAPE_PLANE);
+ BIND_CONSTANT(SHAPE_RAY);
+ BIND_CONSTANT(SHAPE_SPHERE);
+ BIND_CONSTANT(SHAPE_BOX);
+ BIND_CONSTANT(SHAPE_CAPSULE);
+ BIND_CONSTANT(SHAPE_CONVEX_POLYGON);
+ BIND_CONSTANT(SHAPE_CONCAVE_POLYGON);
+ BIND_CONSTANT(SHAPE_HEIGHTMAP);
+ BIND_CONSTANT(SHAPE_CUSTOM);
+
+ BIND_CONSTANT(AREA_PARAM_GRAVITY);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_VECTOR);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_IS_POINT);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_DISTANCE_SCALE);
+ BIND_CONSTANT(AREA_PARAM_GRAVITY_POINT_ATTENUATION);
+ BIND_CONSTANT(AREA_PARAM_LINEAR_DAMP);
+ BIND_CONSTANT(AREA_PARAM_ANGULAR_DAMP);
+ BIND_CONSTANT(AREA_PARAM_PRIORITY);
+
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_DISABLED);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_COMBINE_REPLACE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE);
+ BIND_CONSTANT(AREA_SPACE_OVERRIDE_REPLACE_COMBINE);
+
+ BIND_CONSTANT(BODY_MODE_STATIC);
+ BIND_CONSTANT(BODY_MODE_KINEMATIC);
+ BIND_CONSTANT(BODY_MODE_RIGID);
+ BIND_CONSTANT(BODY_MODE_CHARACTER);
+
+ BIND_CONSTANT(BODY_PARAM_BOUNCE);
+ BIND_CONSTANT(BODY_PARAM_FRICTION);
+ BIND_CONSTANT(BODY_PARAM_MASS);
+ BIND_CONSTANT(BODY_PARAM_GRAVITY_SCALE);
+ BIND_CONSTANT(BODY_PARAM_ANGULAR_DAMP);
+ BIND_CONSTANT(BODY_PARAM_LINEAR_DAMP);
+ BIND_CONSTANT(BODY_PARAM_MAX);
+
+ BIND_CONSTANT(BODY_STATE_TRANSFORM);
+ BIND_CONSTANT(BODY_STATE_LINEAR_VELOCITY);
+ BIND_CONSTANT(BODY_STATE_ANGULAR_VELOCITY);
+ BIND_CONSTANT(BODY_STATE_SLEEPING);
+ BIND_CONSTANT(BODY_STATE_CAN_SLEEP);
+ /*
BIND_CONSTANT( JOINT_PIN );
BIND_CONSTANT( JOINT_GROOVE );
BIND_CONSTANT( JOINT_DAMPED_SPRING );
@@ -742,26 +696,21 @@ void PhysicsServer::_bind_methods() {
//BIND_CONSTANT( TYPE_BODY );
//BIND_CONSTANT( TYPE_AREA );
- BIND_CONSTANT( AREA_BODY_ADDED );
- BIND_CONSTANT( AREA_BODY_REMOVED );
-
- BIND_CONSTANT( INFO_ACTIVE_OBJECTS );
- BIND_CONSTANT( INFO_COLLISION_PAIRS );
- BIND_CONSTANT( INFO_ISLAND_COUNT );
-
-
+ BIND_CONSTANT(AREA_BODY_ADDED);
+ BIND_CONSTANT(AREA_BODY_REMOVED);
+ BIND_CONSTANT(INFO_ACTIVE_OBJECTS);
+ BIND_CONSTANT(INFO_COLLISION_PAIRS);
+ BIND_CONSTANT(INFO_ISLAND_COUNT);
}
-
PhysicsServer::PhysicsServer() {
- ERR_FAIL_COND( singleton!=NULL );
- singleton=this;
+ ERR_FAIL_COND(singleton != NULL);
+ singleton = this;
}
PhysicsServer::~PhysicsServer() {
- singleton=NULL;
+ singleton = NULL;
}
-
diff --git a/servers/physics_server.h b/servers/physics_server.h
index 653959be45..dbd0c79f06 100644
--- a/servers/physics_server.h
+++ b/servers/physics_server.h
@@ -36,81 +36,81 @@ class PhysicsDirectSpaceState;
class PhysicsDirectBodyState : public Object {
- GDCLASS( PhysicsDirectBodyState, Object );
+ GDCLASS(PhysicsDirectBodyState, Object);
+
protected:
static void _bind_methods();
-public:
- virtual Vector3 get_total_gravity() const=0;
- virtual float get_total_angular_damp() const=0;
- virtual float get_total_linear_damp() const=0;
+public:
+ virtual Vector3 get_total_gravity() const = 0;
+ virtual float get_total_angular_damp() const = 0;
+ virtual float get_total_linear_damp() const = 0;
- virtual Vector3 get_center_of_mass() const=0;
- virtual Basis get_principal_inertia_axes() const=0;
- virtual float get_inverse_mass() const=0; // get the mass
- virtual Vector3 get_inverse_inertia() const=0; // get density of this body space
- virtual Basis get_inverse_inertia_tensor() const=0; // get density of this body space
+ virtual Vector3 get_center_of_mass() const = 0;
+ virtual Basis get_principal_inertia_axes() const = 0;
+ virtual float get_inverse_mass() const = 0; // get the mass
+ virtual Vector3 get_inverse_inertia() const = 0; // get density of this body space
+ virtual Basis get_inverse_inertia_tensor() const = 0; // get density of this body space
- virtual void set_linear_velocity(const Vector3& p_velocity)=0;
- virtual Vector3 get_linear_velocity() const=0;
+ virtual void set_linear_velocity(const Vector3 &p_velocity) = 0;
+ virtual Vector3 get_linear_velocity() const = 0;
- virtual void set_angular_velocity(const Vector3& p_velocity)=0;
- virtual Vector3 get_angular_velocity() const=0;
+ virtual void set_angular_velocity(const Vector3 &p_velocity) = 0;
+ virtual Vector3 get_angular_velocity() const = 0;
- virtual void set_transform(const Transform& p_transform)=0;
- virtual Transform get_transform() const=0;
+ virtual void set_transform(const Transform &p_transform) = 0;
+ virtual Transform get_transform() const = 0;
- virtual void add_force(const Vector3& p_force, const Vector3& p_pos)=0;
- virtual void apply_impulse(const Vector3& p_pos, const Vector3& p_j)=0;
- virtual void apply_torque_impulse(const Vector3& p_j)=0;
+ virtual void add_force(const Vector3 &p_force, const Vector3 &p_pos) = 0;
+ virtual void apply_impulse(const Vector3 &p_pos, const Vector3 &p_j) = 0;
+ virtual void apply_torque_impulse(const Vector3 &p_j) = 0;
- virtual void set_sleep_state(bool p_enable)=0;
- virtual bool is_sleeping() const=0;
+ virtual void set_sleep_state(bool p_enable) = 0;
+ virtual bool is_sleeping() const = 0;
- virtual int get_contact_count() const=0;
+ virtual int get_contact_count() const = 0;
- virtual Vector3 get_contact_local_pos(int p_contact_idx) const=0;
- virtual Vector3 get_contact_local_normal(int p_contact_idx) const=0;
- virtual int get_contact_local_shape(int p_contact_idx) const=0;
+ virtual Vector3 get_contact_local_pos(int p_contact_idx) const = 0;
+ virtual Vector3 get_contact_local_normal(int p_contact_idx) const = 0;
+ virtual int get_contact_local_shape(int p_contact_idx) const = 0;
- virtual RID get_contact_collider(int p_contact_idx) const=0;
- virtual Vector3 get_contact_collider_pos(int p_contact_idx) const=0;
- virtual ObjectID get_contact_collider_id(int p_contact_idx) const=0;
- virtual Object* get_contact_collider_object(int p_contact_idx) const;
- virtual int get_contact_collider_shape(int p_contact_idx) const=0;
- virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const=0;
+ virtual RID get_contact_collider(int p_contact_idx) const = 0;
+ virtual Vector3 get_contact_collider_pos(int p_contact_idx) const = 0;
+ virtual ObjectID get_contact_collider_id(int p_contact_idx) const = 0;
+ virtual Object *get_contact_collider_object(int p_contact_idx) const;
+ virtual int get_contact_collider_shape(int p_contact_idx) const = 0;
+ virtual Vector3 get_contact_collider_velocity_at_pos(int p_contact_idx) const = 0;
- virtual real_t get_step() const=0;
+ virtual real_t get_step() const = 0;
virtual void integrate_forces();
- virtual PhysicsDirectSpaceState* get_space_state()=0;
+ virtual PhysicsDirectSpaceState *get_space_state() = 0;
PhysicsDirectBodyState();
};
-
class PhysicsShapeQueryResult;
class PhysicsShapeQueryParameters : public Reference {
GDCLASS(PhysicsShapeQueryParameters, Reference);
-friend class PhysicsDirectSpaceState;
+ friend class PhysicsDirectSpaceState;
RID shape;
Transform transform;
float margin;
Set<RID> exclude;
uint32_t layer_mask;
uint32_t object_type_mask;
+
protected:
static void _bind_methods();
-public:
-
- void set_shape(const RES& p_shape);
- void set_shape_rid(const RID& p_shape);
+public:
+ void set_shape(const RES &p_shape);
+ void set_shape_rid(const RID &p_shape);
RID get_shape_rid() const;
- void set_transform(const Transform& p_transform);
+ void set_transform(const Transform &p_transform);
Transform get_transform() const;
void set_margin(float p_margin);
@@ -122,47 +122,39 @@ public:
void set_object_type_mask(int p_object_type_mask);
int get_object_type_mask() const;
- void set_exclude(const Vector<RID>& p_exclude);
+ void set_exclude(const Vector<RID> &p_exclude);
Vector<RID> get_exclude() const;
PhysicsShapeQueryParameters();
-
};
-
-
class PhysicsDirectSpaceState : public Object {
- GDCLASS( PhysicsDirectSpaceState, Object );
+ GDCLASS(PhysicsDirectSpaceState, Object);
//Variant _intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_collision_mask=0);
//Variant _intersect_shape(const RID& p_shape, const Transform& p_xform,int p_result_max=64,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_collision_mask=0);
public:
-
enum ObjectTypeMask {
- TYPE_MASK_STATIC_BODY=1<<0,
- TYPE_MASK_KINEMATIC_BODY=1<<1,
- TYPE_MASK_RIGID_BODY=1<<2,
- TYPE_MASK_CHARACTER_BODY=1<<3,
- TYPE_MASK_AREA=1<<4,
- TYPE_MASK_COLLISION=TYPE_MASK_STATIC_BODY|TYPE_MASK_CHARACTER_BODY|TYPE_MASK_KINEMATIC_BODY|TYPE_MASK_RIGID_BODY
+ TYPE_MASK_STATIC_BODY = 1 << 0,
+ TYPE_MASK_KINEMATIC_BODY = 1 << 1,
+ TYPE_MASK_RIGID_BODY = 1 << 2,
+ TYPE_MASK_CHARACTER_BODY = 1 << 3,
+ TYPE_MASK_AREA = 1 << 4,
+ TYPE_MASK_COLLISION = TYPE_MASK_STATIC_BODY | TYPE_MASK_CHARACTER_BODY | TYPE_MASK_KINEMATIC_BODY | TYPE_MASK_RIGID_BODY
};
-
private:
- Dictionary _intersect_ray(const Vector3& p_from, const Vector3& p_to,const Vector<RID>& p_exclude=Vector<RID>(),uint32_t p_layers=0,uint32_t p_object_type_mask=TYPE_MASK_COLLISION);
- Array _intersect_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query,int p_max_results=32);
- Array _cast_motion(const Ref<PhysicsShapeQueryParameters> &p_shape_query,const Vector3& p_motion);
- Array _collide_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query,int p_max_results=32);
+ Dictionary _intersect_ray(const Vector3 &p_from, const Vector3 &p_to, const Vector<RID> &p_exclude = Vector<RID>(), uint32_t p_layers = 0, uint32_t p_object_type_mask = TYPE_MASK_COLLISION);
+ Array _intersect_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query, int p_max_results = 32);
+ Array _cast_motion(const Ref<PhysicsShapeQueryParameters> &p_shape_query, const Vector3 &p_motion);
+ Array _collide_shape(const Ref<PhysicsShapeQueryParameters> &p_shape_query, int p_max_results = 32);
Dictionary _get_rest_info(const Ref<PhysicsShapeQueryParameters> &p_shape_query);
-
protected:
static void _bind_methods();
public:
-
-
struct RayResult {
Vector3 position;
@@ -173,7 +165,7 @@ public:
int shape;
};
- 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_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,bool p_pick_ray=false)=0;
+ 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_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, bool p_pick_ray = false) = 0;
struct ShapeResult {
@@ -181,10 +173,9 @@ public:
ObjectID collider_id;
Object *collider;
int shape;
-
};
- 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_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ 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_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
struct ShapeRestInfo {
@@ -194,55 +185,49 @@ public:
ObjectID collider_id;
int shape;
Vector3 linear_velocity; //velocity at contact point
-
};
- virtual bool cast_motion(const RID& p_shape, const Transform& p_xform,const Vector3& p_motion,float p_margin,float &p_closest_safe,float &p_closest_unsafe, const Set<RID>& p_exclude=Set<RID>(),uint32_t p_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION,ShapeRestInfo *r_info=NULL)=0;
-
- 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_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ virtual bool cast_motion(const RID &p_shape, const Transform &p_xform, const Vector3 &p_motion, float p_margin, float &p_closest_safe, float &p_closest_unsafe, const Set<RID> &p_exclude = Set<RID>(), uint32_t p_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION, ShapeRestInfo *r_info = NULL) = 0;
- 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_layer_mask=0xFFFFFFFF,uint32_t p_object_type_mask=TYPE_MASK_COLLISION)=0;
+ 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_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
+ 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_layer_mask = 0xFFFFFFFF, uint32_t p_object_type_mask = TYPE_MASK_COLLISION) = 0;
PhysicsDirectSpaceState();
};
-
class PhysicsShapeQueryResult : public Reference {
- GDCLASS( PhysicsShapeQueryResult, Reference );
+ GDCLASS(PhysicsShapeQueryResult, Reference);
Vector<PhysicsDirectSpaceState::ShapeResult> result;
-friend class PhysicsDirectSpaceState;
+ friend class PhysicsDirectSpaceState;
protected:
static void _bind_methods();
-public:
+public:
int get_result_count() const;
RID get_result_rid(int p_idx) const;
ObjectID get_result_object_id(int p_idx) const;
- Object* get_result_object(int p_idx) const;
+ Object *get_result_object(int p_idx) const;
int get_result_object_shape(int p_idx) const;
PhysicsShapeQueryResult();
};
-
class PhysicsServer : public Object {
- GDCLASS( PhysicsServer, Object );
-
- static PhysicsServer * singleton;
+ GDCLASS(PhysicsServer, Object);
+ static PhysicsServer *singleton;
protected:
static void _bind_methods();
public:
-
- static PhysicsServer * get_singleton();
+ static PhysicsServer *get_singleton();
enum ShapeType {
SHAPE_PLANE, ///< plane:"plane"
@@ -256,20 +241,19 @@ public:
SHAPE_CUSTOM, ///< Server-Implementation based custom shape, calling shape_create() with this value will result in an error
};
- virtual RID shape_create(ShapeType p_shape)=0;
- virtual void shape_set_data(RID p_shape, const Variant& p_data)=0;
- virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias)=0;
-
- virtual ShapeType shape_get_type(RID p_shape) const=0;
- virtual Variant shape_get_data(RID p_shape) const=0;
- virtual real_t shape_get_custom_solver_bias(RID p_shape) const=0;
+ virtual RID shape_create(ShapeType p_shape) = 0;
+ virtual void shape_set_data(RID p_shape, const Variant &p_data) = 0;
+ virtual void shape_set_custom_solver_bias(RID p_shape, real_t p_bias) = 0;
+ virtual ShapeType shape_get_type(RID p_shape) const = 0;
+ virtual Variant shape_get_data(RID p_shape) const = 0;
+ virtual real_t shape_get_custom_solver_bias(RID p_shape) const = 0;
/* SPACE API */
- virtual RID space_create()=0;
- virtual void space_set_active(RID p_space,bool p_active)=0;
- virtual bool space_is_active(RID p_space) const=0;
+ virtual RID space_create() = 0;
+ virtual void space_set_active(RID p_space, bool p_active) = 0;
+ virtual bool space_is_active(RID p_space) const = 0;
enum SpaceParameter {
@@ -283,15 +267,15 @@ public:
SPACE_PARAM_CONSTRAINT_DEFAULT_BIAS,
};
- virtual void space_set_param(RID p_space,SpaceParameter p_param, real_t p_value)=0;
- virtual real_t space_get_param(RID p_space,SpaceParameter p_param) const=0;
+ virtual void space_set_param(RID p_space, SpaceParameter p_param, real_t p_value) = 0;
+ virtual real_t space_get_param(RID p_space, SpaceParameter p_param) const = 0;
// this function only works on fixed process, errors and returns null otherwise
- virtual PhysicsDirectSpaceState* space_get_direct_state(RID p_space)=0;
+ virtual PhysicsDirectSpaceState *space_get_direct_state(RID p_space) = 0;
- virtual void space_set_debug_contacts(RID p_space,int p_max_contacts)=0;
- virtual Vector<Vector3> space_get_contacts(RID p_space) const=0;
- virtual int space_get_contact_count(RID p_space) const=0;
+ virtual void space_set_debug_contacts(RID p_space, int p_max_contacts) = 0;
+ virtual Vector<Vector3> space_get_contacts(RID p_space) const = 0;
+ virtual int space_get_contact_count(RID p_space) const = 0;
//missing space parameters
@@ -299,8 +283,6 @@ public:
//missing attenuation? missing better override?
-
-
enum AreaParameter {
AREA_PARAM_GRAVITY,
AREA_PARAM_GRAVITY_VECTOR,
@@ -312,11 +294,10 @@ public:
AREA_PARAM_PRIORITY
};
- virtual RID area_create()=0;
-
- virtual void area_set_space(RID p_area, RID p_space)=0;
- virtual RID area_get_space(RID p_area) const=0;
+ virtual RID area_create() = 0;
+ virtual void area_set_space(RID p_area, RID p_space) = 0;
+ virtual RID area_get_space(RID p_area) const = 0;
enum AreaSpaceOverrideMode {
AREA_SPACE_OVERRIDE_DISABLED,
@@ -326,39 +307,39 @@ public:
AREA_SPACE_OVERRIDE_REPLACE_COMBINE
};
- virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode)=0;
- virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const=0;
+ virtual void area_set_space_override_mode(RID p_area, AreaSpaceOverrideMode p_mode) = 0;
+ virtual AreaSpaceOverrideMode area_get_space_override_mode(RID p_area) const = 0;
- virtual void area_add_shape(RID p_area, RID p_shape, const Transform& p_transform=Transform())=0;
- virtual void area_set_shape(RID p_area, int p_shape_idx,RID p_shape)=0;
- virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform& p_transform)=0;
+ virtual void area_add_shape(RID p_area, RID p_shape, const Transform &p_transform = Transform()) = 0;
+ virtual void area_set_shape(RID p_area, int p_shape_idx, RID p_shape) = 0;
+ virtual void area_set_shape_transform(RID p_area, int p_shape_idx, const Transform &p_transform) = 0;
- virtual int area_get_shape_count(RID p_area) const=0;
- virtual RID area_get_shape(RID p_area, int p_shape_idx) const=0;
- virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const=0;
+ virtual int area_get_shape_count(RID p_area) const = 0;
+ virtual RID area_get_shape(RID p_area, int p_shape_idx) const = 0;
+ virtual Transform area_get_shape_transform(RID p_area, int p_shape_idx) const = 0;
- virtual void area_remove_shape(RID p_area, int p_shape_idx)=0;
- virtual void area_clear_shapes(RID p_area)=0;
+ virtual void area_remove_shape(RID p_area, int p_shape_idx) = 0;
+ virtual void area_clear_shapes(RID p_area) = 0;
- virtual void area_attach_object_instance_ID(RID p_area,ObjectID p_ID)=0;
- virtual ObjectID area_get_object_instance_ID(RID p_area) const=0;
+ virtual void area_attach_object_instance_ID(RID p_area, ObjectID p_ID) = 0;
+ virtual ObjectID area_get_object_instance_ID(RID p_area) const = 0;
- virtual void area_set_param(RID p_area,AreaParameter p_param,const Variant& p_value)=0;
- virtual void area_set_transform(RID p_area, const Transform& p_transform)=0;
+ virtual void area_set_param(RID p_area, AreaParameter p_param, const Variant &p_value) = 0;
+ virtual void area_set_transform(RID p_area, const Transform &p_transform) = 0;
- virtual Variant area_get_param(RID p_parea,AreaParameter p_param) const=0;
- virtual Transform area_get_transform(RID p_area) const=0;
+ virtual Variant area_get_param(RID p_parea, AreaParameter p_param) const = 0;
+ virtual Transform area_get_transform(RID p_area) const = 0;
- virtual void area_set_collision_mask(RID p_area,uint32_t p_mask)=0;
- virtual void area_set_layer_mask(RID p_area,uint32_t p_mask)=0;
+ virtual void area_set_collision_mask(RID p_area, uint32_t p_mask) = 0;
+ virtual void area_set_layer_mask(RID p_area, uint32_t p_mask) = 0;
- virtual void area_set_monitorable(RID p_area,bool p_monitorable)=0;
+ virtual void area_set_monitorable(RID p_area, bool p_monitorable) = 0;
- virtual void area_set_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0;
- virtual void area_set_area_monitor_callback(RID p_area,Object *p_receiver,const StringName& p_method)=0;
+ virtual void area_set_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0;
+ virtual void area_set_area_monitor_callback(RID p_area, Object *p_receiver, const StringName &p_method) = 0;
- virtual void area_set_ray_pickable(RID p_area,bool p_enable)=0;
- virtual bool area_is_ray_pickable(RID p_area) const=0;
+ virtual void area_set_ray_pickable(RID p_area, bool p_enable) = 0;
+ virtual bool area_is_ray_pickable(RID p_area) const = 0;
/* BODY API */
@@ -372,42 +353,42 @@ public:
BODY_MODE_CHARACTER
};
- virtual RID body_create(BodyMode p_mode=BODY_MODE_RIGID,bool p_init_sleeping=false)=0;
+ virtual RID body_create(BodyMode p_mode = BODY_MODE_RIGID, bool p_init_sleeping = false) = 0;
- virtual void body_set_space(RID p_body, RID p_space)=0;
- virtual RID body_get_space(RID p_body) const=0;
+ virtual void body_set_space(RID p_body, RID p_space) = 0;
+ virtual RID body_get_space(RID p_body) const = 0;
- virtual void body_set_mode(RID p_body, BodyMode p_mode)=0;
- virtual BodyMode body_get_mode(RID p_body) const=0;
+ virtual void body_set_mode(RID p_body, BodyMode p_mode) = 0;
+ virtual BodyMode body_get_mode(RID p_body) const = 0;
- virtual void body_add_shape(RID p_body, RID p_shape, const Transform& p_transform=Transform())=0;
- virtual void body_set_shape(RID p_body, int p_shape_idx,RID p_shape)=0;
- virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform& p_transform)=0;
+ virtual void body_add_shape(RID p_body, RID p_shape, const Transform &p_transform = Transform()) = 0;
+ virtual void body_set_shape(RID p_body, int p_shape_idx, RID p_shape) = 0;
+ virtual void body_set_shape_transform(RID p_body, int p_shape_idx, const Transform &p_transform) = 0;
- virtual int body_get_shape_count(RID p_body) const=0;
- virtual RID body_get_shape(RID p_body, int p_shape_idx) const=0;
- virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const=0;
+ virtual int body_get_shape_count(RID p_body) const = 0;
+ virtual RID body_get_shape(RID p_body, int p_shape_idx) const = 0;
+ virtual Transform body_get_shape_transform(RID p_body, int p_shape_idx) const = 0;
- virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx,bool p_enable)=0;
- virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const=0;
+ virtual void body_set_shape_as_trigger(RID p_body, int p_shape_idx, bool p_enable) = 0;
+ virtual bool body_is_shape_set_as_trigger(RID p_body, int p_shape_idx) const = 0;
- virtual void body_remove_shape(RID p_body, int p_shape_idx)=0;
- virtual void body_clear_shapes(RID p_body)=0;
+ virtual void body_remove_shape(RID p_body, int p_shape_idx) = 0;
+ virtual void body_clear_shapes(RID p_body) = 0;
- virtual void body_attach_object_instance_ID(RID p_body,uint32_t p_ID)=0;
- virtual uint32_t body_get_object_instance_ID(RID p_body) const=0;
+ virtual void body_attach_object_instance_ID(RID p_body, uint32_t p_ID) = 0;
+ virtual uint32_t body_get_object_instance_ID(RID p_body) const = 0;
- virtual void body_set_enable_continuous_collision_detection(RID p_body,bool p_enable)=0;
- virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const=0;
+ virtual void body_set_enable_continuous_collision_detection(RID p_body, bool p_enable) = 0;
+ virtual bool body_is_continuous_collision_detection_enabled(RID p_body) const = 0;
- virtual void body_set_layer_mask(RID p_body, uint32_t p_mask)=0;
- virtual uint32_t body_get_layer_mask(RID p_body, uint32_t p_mask) const=0;
+ virtual void body_set_layer_mask(RID p_body, uint32_t p_mask) = 0;
+ virtual uint32_t body_get_layer_mask(RID p_body, uint32_t p_mask) const = 0;
- virtual void body_set_collision_mask(RID p_body, uint32_t p_mask)=0;
- virtual uint32_t body_get_collision_mask(RID p_body, uint32_t p_mask) const=0;
+ virtual void body_set_collision_mask(RID p_body, uint32_t p_mask) = 0;
+ virtual uint32_t body_get_collision_mask(RID p_body, uint32_t p_mask) const = 0;
- virtual void body_set_user_flags(RID p_body, uint32_t p_flags)=0;
- virtual uint32_t body_get_user_flags(RID p_body, uint32_t p_flags) const=0;
+ virtual void body_set_user_flags(RID p_body, uint32_t p_flags) = 0;
+ virtual uint32_t body_get_user_flags(RID p_body, uint32_t p_flags) const = 0;
// common body variables
enum BodyParameter {
@@ -420,9 +401,8 @@ public:
BODY_PARAM_MAX,
};
- virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value)=0;
- virtual float body_get_param(RID p_body, BodyParameter p_param) const=0;
-
+ virtual void body_set_param(RID p_body, BodyParameter p_param, float p_value) = 0;
+ virtual float body_get_param(RID p_body, BodyParameter p_param) const = 0;
//state
enum BodyState {
@@ -433,19 +413,19 @@ public:
BODY_STATE_CAN_SLEEP
};
- virtual void body_set_state(RID p_body, BodyState p_state, const Variant& p_variant)=0;
- virtual Variant body_get_state(RID p_body, BodyState p_state) const=0;
+ virtual void body_set_state(RID p_body, BodyState p_state, const Variant &p_variant) = 0;
+ virtual Variant body_get_state(RID p_body, BodyState p_state) const = 0;
//do something about it
- virtual void body_set_applied_force(RID p_body, const Vector3& p_force)=0;
- virtual Vector3 body_get_applied_force(RID p_body) const=0;
+ virtual void body_set_applied_force(RID p_body, const Vector3 &p_force) = 0;
+ virtual Vector3 body_get_applied_force(RID p_body) const = 0;
- virtual void body_set_applied_torque(RID p_body, const Vector3& p_torque)=0;
- virtual Vector3 body_get_applied_torque(RID p_body) const=0;
+ virtual void body_set_applied_torque(RID p_body, const Vector3 &p_torque) = 0;
+ virtual Vector3 body_get_applied_torque(RID p_body) const = 0;
- virtual void body_apply_impulse(RID p_body, const Vector3& p_pos, const Vector3& p_impulse)=0;
- virtual void body_apply_torque_impulse(RID p_body, const Vector3& p_impulse)=0;
- virtual void body_set_axis_velocity(RID p_body, const Vector3& p_axis_velocity)=0;
+ virtual void body_apply_impulse(RID p_body, const Vector3 &p_pos, const Vector3 &p_impulse) = 0;
+ virtual void body_apply_torque_impulse(RID p_body, const Vector3 &p_impulse) = 0;
+ virtual void body_set_axis_velocity(RID p_body, const Vector3 &p_axis_velocity) = 0;
enum BodyAxisLock {
BODY_AXIS_LOCK_DISABLED,
@@ -454,29 +434,28 @@ public:
BODY_AXIS_LOCK_Z,
};
- virtual void body_set_axis_lock(RID p_body,BodyAxisLock p_lock)=0;
- virtual BodyAxisLock body_get_axis_lock(RID p_body) const=0;
+ virtual void body_set_axis_lock(RID p_body, BodyAxisLock p_lock) = 0;
+ virtual BodyAxisLock body_get_axis_lock(RID p_body) const = 0;
//fix
- virtual void body_add_collision_exception(RID p_body, RID p_body_b)=0;
- virtual void body_remove_collision_exception(RID p_body, RID p_body_b)=0;
- virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions)=0;
+ virtual void body_add_collision_exception(RID p_body, RID p_body_b) = 0;
+ virtual void body_remove_collision_exception(RID p_body, RID p_body_b) = 0;
+ virtual void body_get_collision_exceptions(RID p_body, List<RID> *p_exceptions) = 0;
- virtual void body_set_max_contacts_reported(RID p_body, int p_contacts)=0;
- virtual int body_get_max_contacts_reported(RID p_body) const=0;
+ virtual void body_set_max_contacts_reported(RID p_body, int p_contacts) = 0;
+ virtual int body_get_max_contacts_reported(RID p_body) const = 0;
//missing remove
- virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold)=0;
- virtual float body_get_contacts_reported_depth_treshold(RID p_body) const=0;
-
- virtual void body_set_omit_force_integration(RID p_body,bool p_omit)=0;
- virtual bool body_is_omitting_force_integration(RID p_body) const=0;
+ virtual void body_set_contacts_reported_depth_treshold(RID p_body, float p_treshold) = 0;
+ virtual float body_get_contacts_reported_depth_treshold(RID p_body) const = 0;
- virtual void body_set_force_integration_callback(RID p_body,Object *p_receiver,const StringName& p_method,const Variant& p_udata=Variant())=0;
+ virtual void body_set_omit_force_integration(RID p_body, bool p_omit) = 0;
+ virtual bool body_is_omitting_force_integration(RID p_body) const = 0;
- virtual void body_set_ray_pickable(RID p_body,bool p_enable)=0;
- virtual bool body_is_ray_pickable(RID p_body) const=0;
+ virtual void body_set_force_integration_callback(RID p_body, Object *p_receiver, const StringName &p_method, const Variant &p_udata = Variant()) = 0;
+ virtual void body_set_ray_pickable(RID p_body, bool p_enable) = 0;
+ virtual bool body_is_ray_pickable(RID p_body) const = 0;
/* JOINT API */
@@ -490,13 +469,12 @@ public:
};
- virtual JointType joint_get_type(RID p_joint) const=0;
-
- virtual void joint_set_solver_priority(RID p_joint,int p_priority)=0;
- virtual int joint_get_solver_priority(RID p_joint) const=0;
+ virtual JointType joint_get_type(RID p_joint) const = 0;
+ virtual void joint_set_solver_priority(RID p_joint, int p_priority) = 0;
+ virtual int joint_get_solver_priority(RID p_joint) const = 0;
- virtual RID joint_create_pin(RID p_body_A,const Vector3& p_local_A,RID p_body_B,const Vector3& p_local_B)=0;
+ virtual RID joint_create_pin(RID p_body_A, const Vector3 &p_local_A, RID p_body_B, const Vector3 &p_local_B) = 0;
enum PinJointParam {
PIN_JOINT_BIAS,
@@ -504,14 +482,14 @@ public:
PIN_JOINT_IMPULSE_CLAMP
};
- virtual void pin_joint_set_param(RID p_joint,PinJointParam p_param, float p_value)=0;
- virtual float pin_joint_get_param(RID p_joint,PinJointParam p_param) const=0;
+ virtual void pin_joint_set_param(RID p_joint, PinJointParam p_param, float p_value) = 0;
+ virtual float pin_joint_get_param(RID p_joint, PinJointParam p_param) const = 0;
- virtual void pin_joint_set_local_A(RID p_joint, const Vector3& p_A)=0;
- virtual Vector3 pin_joint_get_local_A(RID p_joint) const=0;
+ virtual void pin_joint_set_local_A(RID p_joint, const Vector3 &p_A) = 0;
+ virtual Vector3 pin_joint_get_local_A(RID p_joint) const = 0;
- virtual void pin_joint_set_local_B(RID p_joint, const Vector3& p_B)=0;
- virtual Vector3 pin_joint_get_local_B(RID p_joint) const=0;
+ virtual void pin_joint_set_local_B(RID p_joint, const Vector3 &p_B) = 0;
+ virtual Vector3 pin_joint_get_local_B(RID p_joint) const = 0;
enum HingeJointParam {
@@ -532,15 +510,14 @@ public:
HINGE_JOINT_FLAG_MAX
};
- virtual RID joint_create_hinge(RID p_body_A,const Transform& p_hinge_A,RID p_body_B,const Transform& p_hinge_B)=0;
- 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)=0;
-
+ virtual RID joint_create_hinge(RID p_body_A, const Transform &p_hinge_A, RID p_body_B, const Transform &p_hinge_B) = 0;
+ 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) = 0;
- virtual void hinge_joint_set_param(RID p_joint,HingeJointParam p_param, float p_value)=0;
- virtual float hinge_joint_get_param(RID p_joint,HingeJointParam p_param) const=0;
+ virtual void hinge_joint_set_param(RID p_joint, HingeJointParam p_param, float p_value) = 0;
+ virtual float hinge_joint_get_param(RID p_joint, HingeJointParam p_param) const = 0;
- virtual void hinge_joint_set_flag(RID p_joint,HingeJointFlag p_flag, bool p_value)=0;
- virtual bool hinge_joint_get_flag(RID p_joint,HingeJointFlag p_flag) const=0;
+ virtual void hinge_joint_set_flag(RID p_joint, HingeJointFlag p_flag, bool p_value) = 0;
+ virtual bool hinge_joint_get_flag(RID p_joint, HingeJointFlag p_flag) const = 0;
enum SliderJointParam {
SLIDER_JOINT_LINEAR_LIMIT_UPPER,
@@ -568,13 +545,12 @@ public:
SLIDER_JOINT_ANGULAR_ORTHOGONAL_DAMPING,
SLIDER_JOINT_MAX
-
};
- 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)=0; //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) = 0; //reference frame is A
- virtual void slider_joint_set_param(RID p_joint,SliderJointParam p_param, float p_value)=0;
- virtual float slider_joint_get_param(RID p_joint,SliderJointParam p_param) const=0;
+ virtual void slider_joint_set_param(RID p_joint, SliderJointParam p_param, float p_value) = 0;
+ virtual float slider_joint_get_param(RID p_joint, SliderJointParam p_param) const = 0;
enum ConeTwistJointParam {
CONE_TWIST_JOINT_SWING_SPAN,
@@ -585,12 +561,10 @@ public:
CONE_TWIST_MAX
};
+ 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) = 0; //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)=0; //reference frame is A
-
- virtual void cone_twist_joint_set_param(RID p_joint,ConeTwistJointParam p_param, float p_value)=0;
- virtual float cone_twist_joint_get_param(RID p_joint,ConeTwistJointParam p_param) const=0;
-
+ virtual void cone_twist_joint_set_param(RID p_joint, ConeTwistJointParam p_param, float p_value) = 0;
+ virtual float cone_twist_joint_get_param(RID p_joint, ConeTwistJointParam p_param) const = 0;
enum G6DOFJointAxisParam {
G6DOF_JOINT_LINEAR_LOWER_LIMIT,
@@ -618,16 +592,13 @@ public:
G6DOF_JOINT_FLAG_MAX
};
+ 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) = 0; //reference frame is A
+ virtual void generic_6dof_joint_set_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param, float p_value) = 0;
+ virtual float generic_6dof_joint_get_param(RID p_joint, Vector3::Axis, G6DOFJointAxisParam p_param) = 0;
- 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)=0; //reference frame is A
-
- virtual void generic_6dof_joint_set_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param, float p_value)=0;
- virtual float generic_6dof_joint_get_param(RID p_joint,Vector3::Axis,G6DOFJointAxisParam p_param)=0;
-
- virtual void generic_6dof_joint_set_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag, bool p_enable)=0;
- virtual bool generic_6dof_joint_get_flag(RID p_joint,Vector3::Axis,G6DOFJointAxisFlag p_flag)=0;
-
+ virtual void generic_6dof_joint_set_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag, bool p_enable) = 0;
+ virtual bool generic_6dof_joint_get_flag(RID p_joint, Vector3::Axis, G6DOFJointAxisFlag p_flag) = 0;
#if 0
enum JointType {
@@ -667,17 +638,16 @@ public:
AREA_BODY_REMOVED
};
-
/* MISC */
- virtual void free(RID p_rid)=0;
+ virtual void free(RID p_rid) = 0;
- virtual void set_active(bool p_active)=0;
- virtual void init()=0;
- virtual void step(float p_step)=0;
- virtual void sync()=0;
- virtual void flush_queries()=0;
- virtual void finish()=0;
+ virtual void set_active(bool p_active) = 0;
+ virtual void init() = 0;
+ virtual void step(float p_step) = 0;
+ virtual void sync() = 0;
+ virtual void flush_queries() = 0;
+ virtual void finish() = 0;
enum ProcessInfo {
@@ -686,30 +656,30 @@ public:
INFO_ISLAND_COUNT
};
- virtual int get_process_info(ProcessInfo p_info)=0;
+ virtual int get_process_info(ProcessInfo p_info) = 0;
PhysicsServer();
~PhysicsServer();
};
-VARIANT_ENUM_CAST( PhysicsServer::ShapeType );
-VARIANT_ENUM_CAST( PhysicsServer::SpaceParameter );
-VARIANT_ENUM_CAST( PhysicsServer::AreaParameter );
-VARIANT_ENUM_CAST( PhysicsServer::AreaSpaceOverrideMode );
-VARIANT_ENUM_CAST( PhysicsServer::BodyMode );
-VARIANT_ENUM_CAST( PhysicsServer::BodyParameter );
-VARIANT_ENUM_CAST( PhysicsServer::BodyState );
-VARIANT_ENUM_CAST( PhysicsServer::BodyAxisLock );
-VARIANT_ENUM_CAST( PhysicsServer::PinJointParam );
-VARIANT_ENUM_CAST( PhysicsServer::JointType );
-VARIANT_ENUM_CAST( PhysicsServer::HingeJointParam );
-VARIANT_ENUM_CAST( PhysicsServer::HingeJointFlag );
-VARIANT_ENUM_CAST( PhysicsServer::SliderJointParam );
-VARIANT_ENUM_CAST( PhysicsServer::ConeTwistJointParam );
-VARIANT_ENUM_CAST( PhysicsServer::G6DOFJointAxisParam );
-VARIANT_ENUM_CAST( PhysicsServer::G6DOFJointAxisFlag);
+VARIANT_ENUM_CAST(PhysicsServer::ShapeType);
+VARIANT_ENUM_CAST(PhysicsServer::SpaceParameter);
+VARIANT_ENUM_CAST(PhysicsServer::AreaParameter);
+VARIANT_ENUM_CAST(PhysicsServer::AreaSpaceOverrideMode);
+VARIANT_ENUM_CAST(PhysicsServer::BodyMode);
+VARIANT_ENUM_CAST(PhysicsServer::BodyParameter);
+VARIANT_ENUM_CAST(PhysicsServer::BodyState);
+VARIANT_ENUM_CAST(PhysicsServer::BodyAxisLock);
+VARIANT_ENUM_CAST(PhysicsServer::PinJointParam);
+VARIANT_ENUM_CAST(PhysicsServer::JointType);
+VARIANT_ENUM_CAST(PhysicsServer::HingeJointParam);
+VARIANT_ENUM_CAST(PhysicsServer::HingeJointFlag);
+VARIANT_ENUM_CAST(PhysicsServer::SliderJointParam);
+VARIANT_ENUM_CAST(PhysicsServer::ConeTwistJointParam);
+VARIANT_ENUM_CAST(PhysicsServer::G6DOFJointAxisParam);
+VARIANT_ENUM_CAST(PhysicsServer::G6DOFJointAxisFlag);
//VARIANT_ENUM_CAST( PhysicsServer::ObjectType );
-VARIANT_ENUM_CAST( PhysicsServer::AreaBodyStatus );
-VARIANT_ENUM_CAST( PhysicsServer::ProcessInfo );
+VARIANT_ENUM_CAST(PhysicsServer::AreaBodyStatus);
+VARIANT_ENUM_CAST(PhysicsServer::ProcessInfo);
#endif
diff --git a/servers/register_server_types.cpp b/servers/register_server_types.cpp
index 0d0619e880..06bcb642ad 100644
--- a/servers/register_server_types.cpp
+++ b/servers/register_server_types.cpp
@@ -29,58 +29,57 @@
#include "register_server_types.h"
#include "global_config.h"
-#include "visual_server.h"
-#include "audio_server.h"
-#include "physics_server.h"
-#include "physics_2d_server.h"
-#include "script_debugger_remote.h"
-#include "visual/shader_types.h"
-#include "audio/audio_stream.h"
#include "audio/audio_effect.h"
+#include "audio/audio_stream.h"
#include "audio/effects/audio_effect_amplify.h"
-#include "audio/effects/audio_effect_reverb.h"
-#include "audio/effects/audio_effect_filter.h"
-#include "audio/effects/audio_effect_eq.h"
-#include "audio/effects/audio_effect_distortion.h"
-#include "audio/effects/audio_effect_stereo_enhance.h"
-#include "audio/effects/audio_effect_panner.h"
#include "audio/effects/audio_effect_chorus.h"
-#include "audio/effects/audio_effect_delay.h"
#include "audio/effects/audio_effect_compressor.h"
+#include "audio/effects/audio_effect_delay.h"
+#include "audio/effects/audio_effect_distortion.h"
+#include "audio/effects/audio_effect_eq.h"
+#include "audio/effects/audio_effect_filter.h"
#include "audio/effects/audio_effect_limiter.h"
-#include "audio/effects/audio_effect_pitch_shift.h"
+#include "audio/effects/audio_effect_panner.h"
#include "audio/effects/audio_effect_phaser.h"
+#include "audio/effects/audio_effect_pitch_shift.h"
+#include "audio/effects/audio_effect_reverb.h"
+#include "audio/effects/audio_effect_stereo_enhance.h"
+#include "audio_server.h"
+#include "physics_2d_server.h"
+#include "physics_server.h"
+#include "script_debugger_remote.h"
+#include "visual/shader_types.h"
+#include "visual_server.h"
-static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage>* r_usage) {
+static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage> *r_usage) {
List<VS::TextureInfo> tinfo;
VS::get_singleton()->texture_debug_usage(&tinfo);
- for (List<VS::TextureInfo>::Element *E=tinfo.front();E;E=E->next()) {
+ for (List<VS::TextureInfo>::Element *E = tinfo.front(); E; E = E->next()) {
ScriptDebuggerRemote::ResourceUsage usage;
- usage.path=E->get().path;
- usage.vram=E->get().bytes;
- usage.id=E->get().texture;
- usage.type="Texture";
- usage.format=itos(E->get().size.width)+"x"+itos(E->get().size.height)+" "+Image::get_format_name(E->get().format);
+ usage.path = E->get().path;
+ usage.vram = E->get().bytes;
+ usage.id = E->get().texture;
+ usage.type = "Texture";
+ usage.format = itos(E->get().size.width) + "x" + itos(E->get().size.height) + " " + Image::get_format_name(E->get().format);
r_usage->push_back(usage);
}
-
}
-ShaderTypes *shader_types=NULL;
+ShaderTypes *shader_types = NULL;
void register_server_types() {
- GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc",20);
+ GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc", 20);
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("VisualServer",VisualServer::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("AudioServer",AudioServer::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("PhysicsServer",PhysicsServer::get_singleton()) );
- GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Physics2DServer",Physics2DServer::get_singleton()) );
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("VisualServer", VisualServer::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("AudioServer", AudioServer::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("PhysicsServer", PhysicsServer::get_singleton()));
+ GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("Physics2DServer", Physics2DServer::get_singleton()));
- shader_types = memnew( ShaderTypes );
+ shader_types = memnew(ShaderTypes);
ClassDB::register_virtual_class<AudioStream>();
ClassDB::register_virtual_class<AudioStreamPlayback>();
@@ -118,7 +117,6 @@ void register_server_types() {
ClassDB::register_class<AudioEffectPhaser>();
}
-
ClassDB::register_virtual_class<Physics2DDirectBodyState>();
ClassDB::register_virtual_class<Physics2DDirectSpaceState>();
ClassDB::register_virtual_class<Physics2DShapeQueryResult>();
@@ -130,10 +128,10 @@ void register_server_types() {
ClassDB::register_virtual_class<PhysicsDirectSpaceState>();
ClassDB::register_virtual_class<PhysicsShapeQueryResult>();
- ScriptDebuggerRemote::resource_usage_func=_debugger_get_resource_usage;
+ ScriptDebuggerRemote::resource_usage_func = _debugger_get_resource_usage;
}
-void unregister_server_types(){
+void unregister_server_types() {
- memdelete( shader_types );
+ memdelete(shader_types);
}
diff --git a/servers/server_wrap_mt_common.h b/servers/server_wrap_mt_common.h
index fbc68fc879..cfb65cf161 100644
--- a/servers/server_wrap_mt_common.h
+++ b/servers/server_wrap_mt_common.h
@@ -27,763 +27,722 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#define FUNC0R(m_r,m_type)\
- virtual m_r m_type() { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type();\
- }\
- }
-
-
-#define FUNCRID(m_type)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create() { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create();\
- }\
- }
-
-#define FUNC1RID(m_type,m_arg1)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create(m_arg1 p1) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create(p1);\
- }\
- }
-
-#define FUNC2RID(m_type,m_arg1,m_arg2)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create(m_arg1 p1,m_arg2 p2) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create(p1,p2);\
- }\
- }
-
-#define FUNC3RID(m_type,m_arg1,m_arg2,m_arg3)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create(p1,p2,p3);\
- }\
- }
-
-
-#define FUNC4RID(m_type,m_arg1,m_arg2,m_arg3,m_arg4)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3,m_arg4 p4) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,p4,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create(p1,p2,p3,p4);\
- }\
- }
-
-
-#define FUNC5RID(m_type,m_arg1,m_arg2,m_arg3,m_arg4,m_arg5)\
- int m_type##allocn() {\
- for(int i=0;i<m_type##_pool_max_size;i++) {\
- m_type##_id_pool.push_back( server_name->m_type##_create() );\
- }\
- return 0;\
- }\
- void m_type##_free_cached_ids() {\
- while (m_type##_id_pool.size()) {\
- free(m_type##_id_pool.front()->get());\
- m_type##_id_pool.pop_front();\
- }\
- }\
- virtual RID m_type##_create(m_arg1 p1,m_arg2 p2,m_arg3 p3,m_arg4 p4,m_arg5 p5) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- RID rid;\
- alloc_mutex->lock();\
- if (m_type##_id_pool.size()==0) {\
- int ret;\
- command_queue.push_and_ret( this, &ServerNameWrapMT::m_type##allocn,p1,p2,p3,p4,p5,&ret);\
- }\
- rid=m_type##_id_pool.front()->get();\
- m_type##_id_pool.pop_front();\
- alloc_mutex->unlock();\
- return rid;\
- } else {\
- return server_name->m_type##_create(p1,p2,p3,p4,p5);\
- }\
- }
-
-#define FUNC0RC(m_r,m_type)\
- virtual m_r m_type() const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type();\
- }\
- }
-
-
-#define FUNC0(m_type)\
- virtual void m_type() { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type);\
- } else {\
- server_name->m_type();\
- }\
- }
-
-#define FUNC0C(m_type)\
- virtual void m_type() const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type);\
- } else {\
- server_name->m_type();\
- }\
- }
-
-
-#define FUNC0S(m_type)\
- virtual void m_type() { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type);\
- } else {\
- server_name->m_type();\
- }\
- }
-
-#define FUNC0SC(m_type)\
- virtual void m_type() const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type);\
- } else {\
- server_name->m_type();\
- }\
+#define FUNC0R(m_r, m_type) \
+ virtual m_r m_type() { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(); \
+ } \
+ }
+
+#define FUNCRID(m_type) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create() { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(); \
+ } \
+ }
+
+#define FUNC1RID(m_type, m_arg1) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create(m_arg1 p1) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(p1); \
+ } \
+ }
+
+#define FUNC2RID(m_type, m_arg1, m_arg2) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create(m_arg1 p1, m_arg2 p2) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(p1, p2); \
+ } \
+ }
+
+#define FUNC3RID(m_type, m_arg1, m_arg2, m_arg3) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC4RID(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, p4, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC5RID(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ int m_type##allocn() { \
+ for (int i = 0; i < m_type##_pool_max_size; i++) { \
+ m_type##_id_pool.push_back(server_name->m_type##_create()); \
+ } \
+ return 0; \
+ } \
+ void m_type##_free_cached_ids() { \
+ while (m_type##_id_pool.size()) { \
+ free(m_type##_id_pool.front()->get()); \
+ m_type##_id_pool.pop_front(); \
+ } \
+ } \
+ virtual RID m_type##_create(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ RID rid; \
+ alloc_mutex->lock(); \
+ if (m_type##_id_pool.size() == 0) { \
+ int ret; \
+ command_queue.push_and_ret(this, &ServerNameWrapMT::m_type##allocn, p1, p2, p3, p4, p5, &ret); \
+ } \
+ rid = m_type##_id_pool.front()->get(); \
+ m_type##_id_pool.pop_front(); \
+ alloc_mutex->unlock(); \
+ return rid; \
+ } else { \
+ return server_name->m_type##_create(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC0RC(m_r, m_type) \
+ virtual m_r m_type() const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(); \
+ } \
+ }
+
+#define FUNC0(m_type) \
+ virtual void m_type() { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type); \
+ } else { \
+ server_name->m_type(); \
+ } \
+ }
+
+#define FUNC0C(m_type) \
+ virtual void m_type() const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type); \
+ } else { \
+ server_name->m_type(); \
+ } \
+ }
+
+#define FUNC0S(m_type) \
+ virtual void m_type() { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type); \
+ } else { \
+ server_name->m_type(); \
+ } \
+ }
+
+#define FUNC0SC(m_type) \
+ virtual void m_type() const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type); \
+ } else { \
+ server_name->m_type(); \
+ } \
}
-
///////////////////////////////////////////////
-
-#define FUNC1R(m_r,m_type,m_arg1)\
- virtual m_r m_type(m_arg1 p1) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1);\
- }\
- }
-
-#define FUNC1RC(m_r,m_type,m_arg1)\
- virtual m_r m_type(m_arg1 p1) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1);\
- }\
- }
-
-
-#define FUNC1S(m_type,m_arg1)\
- virtual void m_type(m_arg1 p1) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1);\
- } else {\
- server_name->m_type(p1);\
- }\
- }
-
-#define FUNC1SC(m_type,m_arg1)\
- virtual void m_type(m_arg1 p1) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1);\
- } else {\
- server_name->m_type(p1);\
- }\
- }
-
-
-#define FUNC1(m_type,m_arg1)\
- virtual void m_type(m_arg1 p1) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1);\
- } else {\
- server_name->m_type(p1);\
- }\
- }
-
-#define FUNC1C(m_type,m_arg1)\
- virtual void m_type(m_arg1 p1) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1);\
- } else {\
- server_name->m_type(p1);\
- }\
- }
-
-
-
-
-#define FUNC2R(m_r,m_type,m_arg1, m_arg2)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2);\
- }\
- }
-
-#define FUNC2RC(m_r,m_type,m_arg1, m_arg2)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2);\
- }\
- }
-
-
-#define FUNC2S(m_type,m_arg1, m_arg2)\
- virtual void m_type(m_arg1 p1, m_arg2 p2) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2);\
- } else {\
- server_name->m_type(p1, p2);\
- }\
- }
-
-#define FUNC2SC(m_type,m_arg1, m_arg2)\
- virtual void m_type(m_arg1 p1, m_arg2 p2) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2);\
- } else {\
- server_name->m_type(p1, p2);\
- }\
- }
-
-
-#define FUNC2(m_type,m_arg1, m_arg2)\
- virtual void m_type(m_arg1 p1, m_arg2 p2) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2);\
- } else {\
- server_name->m_type(p1, p2);\
- }\
- }
-
-#define FUNC2C(m_type,m_arg1, m_arg2)\
- virtual void m_type(m_arg1 p1, m_arg2 p2) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2);\
- } else {\
- server_name->m_type(p1, p2);\
- }\
- }
-
-
-
-
-#define FUNC3R(m_r,m_type,m_arg1, m_arg2, m_arg3)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3);\
- }\
- }
-
-#define FUNC3RC(m_r,m_type,m_arg1, m_arg2, m_arg3)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3,&ret);\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3);\
- }\
- }
-
-
-#define FUNC3S(m_type,m_arg1, m_arg2, m_arg3)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3);\
- } else {\
- server_name->m_type(p1, p2, p3);\
- }\
- }
-
-#define FUNC3SC(m_type,m_arg1, m_arg2, m_arg3)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3);\
- } else {\
- server_name->m_type(p1, p2, p3);\
- }\
- }
-
-
-#define FUNC3(m_type,m_arg1, m_arg2, m_arg3)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3);\
- } else {\
- server_name->m_type(p1, p2, p3);\
- }\
- }
-
-#define FUNC3C(m_type,m_arg1, m_arg2, m_arg3)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3);\
- } else {\
- server_name->m_type(p1, p2, p3);\
- }\
- }
-
-
-
-
-#define FUNC4R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-#define FUNC4RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-
-#define FUNC4S(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4);\
- } else {\
- server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-#define FUNC4SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4);\
- } else {\
- server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-
-#define FUNC4(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4);\
- } else {\
- server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-#define FUNC4C(m_type,m_arg1, m_arg2, m_arg3, m_arg4)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4);\
- } else {\
- server_name->m_type(p1, p2, p3, p4);\
- }\
- }
-
-
-
-
-#define FUNC5R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-#define FUNC5RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-
-#define FUNC5S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-#define FUNC5SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
+#define FUNC1R(m_r, m_type, m_arg1) \
+ virtual m_r m_type(m_arg1 p1) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC1RC(m_r, m_type, m_arg1) \
+ virtual m_r m_type(m_arg1 p1) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC1S(m_type, m_arg1) \
+ virtual void m_type(m_arg1 p1) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1); \
+ } else { \
+ server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC1SC(m_type, m_arg1) \
+ virtual void m_type(m_arg1 p1) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1); \
+ } else { \
+ server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC1(m_type, m_arg1) \
+ virtual void m_type(m_arg1 p1) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1); \
+ } else { \
+ server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC1C(m_type, m_arg1) \
+ virtual void m_type(m_arg1 p1) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1); \
+ } else { \
+ server_name->m_type(p1); \
+ } \
+ }
+
+#define FUNC2R(m_r, m_type, m_arg1, m_arg2) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC2RC(m_r, m_type, m_arg1, m_arg2) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC2S(m_type, m_arg1, m_arg2) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2); \
+ } else { \
+ server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC2SC(m_type, m_arg1, m_arg2) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2); \
+ } else { \
+ server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC2(m_type, m_arg1, m_arg2) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2); \
+ } else { \
+ server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC2C(m_type, m_arg1, m_arg2) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2); \
+ } else { \
+ server_name->m_type(p1, p2); \
+ } \
+ }
+
+#define FUNC3R(m_r, m_type, m_arg1, m_arg2, m_arg3) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC3RC(m_r, m_type, m_arg1, m_arg2, m_arg3) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, &ret); \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC3S(m_type, m_arg1, m_arg2, m_arg3) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3); \
+ } else { \
+ server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC3SC(m_type, m_arg1, m_arg2, m_arg3) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3); \
+ } else { \
+ server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC3(m_type, m_arg1, m_arg2, m_arg3) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3); \
+ } else { \
+ server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC3C(m_type, m_arg1, m_arg2, m_arg3) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3); \
+ } else { \
+ server_name->m_type(p1, p2, p3); \
+ } \
+ }
+
+#define FUNC4R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC4RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC4S(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC4SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC4(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC4C(m_type, m_arg1, m_arg2, m_arg3, m_arg4) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4); \
+ } \
+ }
+
+#define FUNC5R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC5RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC5S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC5SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC5(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC5C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-
-#define FUNC5(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-#define FUNC5C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5);\
- }\
- }
-
-
-
-
-#define FUNC6R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
- }
-
-#define FUNC6RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6,&ret);\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
- }
-
-
-#define FUNC6S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5); \
+ } \
+ }
+
+#define FUNC6R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
+ }
+
+#define FUNC6RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, &ret); \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
+ }
+
+#define FUNC6S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
+ }
+
+#define FUNC6SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
+ virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
+ }
+
+#define FUNC6(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
}
-#define FUNC6SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
+#define FUNC6C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
- }
-
-
-#define FUNC6(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
- }
-
-#define FUNC6C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6)\
- virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6);\
- }\
- }
-
-
-
-
-#define FUNC7R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
- virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
- }
-
-#define FUNC7RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6); \
+ } \
+ }
+
+#define FUNC7R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
+ virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
+ }
+
+#define FUNC7RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7,&ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
}
-
-#define FUNC7S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
+#define FUNC7S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
}
-#define FUNC7SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
+#define FUNC7SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
}
-
-#define FUNC7(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
+#define FUNC7(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
}
-#define FUNC7C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7)\
+#define FUNC7C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7); \
+ } \
}
-#define FUNC8R(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8R(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8, &ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
-#define FUNC8RC(m_r,m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8RC(m_r, m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual m_r m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- m_r ret;\
- command_queue.push_and_ret( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8, &ret);\
- SYNC_DEBUG\
- return ret;\
- } else {\
- return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ m_r ret; \
+ command_queue.push_and_ret(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8, &ret); \
+ SYNC_DEBUG \
+ return ret; \
+ } else { \
+ return server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
-
-#define FUNC8S(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8S(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
-#define FUNC8SC(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8SC(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push_and_sync( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push_and_sync(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
-
-#define FUNC8(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
-#define FUNC8C(m_type,m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8)\
+#define FUNC8C(m_type, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8) \
virtual void m_type(m_arg1 p1, m_arg2 p2, m_arg3 p3, m_arg4 p4, m_arg5 p5, m_arg6 p6, m_arg7 p7, m_arg8 p8) const { \
- if (Thread::get_caller_ID()!=server_thread) {\
- command_queue.push( server_name, &ServerName::m_type,p1, p2, p3, p4, p5, p6, p7, p8);\
- } else {\
- server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8);\
- }\
+ if (Thread::get_caller_ID() != server_thread) { \
+ command_queue.push(server_name, &ServerName::m_type, p1, p2, p3, p4, p5, p6, p7, p8); \
+ } else { \
+ server_name->m_type(p1, p2, p3, p4, p5, p6, p7, p8); \
+ } \
}
diff --git a/servers/visual/rasterizer.cpp b/servers/visual/rasterizer.cpp
index ba85f92e37..fdcc4f5633 100644
--- a/servers/visual/rasterizer.cpp
+++ b/servers/visual/rasterizer.cpp
@@ -27,22 +27,21 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "rasterizer.h"
-#include "print_string.h"
#include "os/os.h"
+#include "print_string.h"
-
-Rasterizer* (*Rasterizer::_create_func)()=NULL;
+Rasterizer *(*Rasterizer::_create_func)() = NULL;
Rasterizer *Rasterizer::create() {
return _create_func();
}
-RasterizerStorage*RasterizerStorage::base_signleton=NULL;
+RasterizerStorage *RasterizerStorage::base_signleton = NULL;
RasterizerStorage::RasterizerStorage() {
- base_signleton=this;
+ base_signleton = this;
}
#if 0
@@ -78,7 +77,7 @@ RID Rasterizer::_create_shader(const FixedSpatialMaterialShaderKey& p_key) {
String code;
static const char* _uv_str[4]={"UV","uv_xform","UV2","uv_sphere"};
-#define _TEXUVSTR(m_idx) String( _uv_str[(p_key.texcoord_mask>>(m_idx*2))&0x3] )
+#define _TEXUVSTR(m_idx) String(_uv_str[(p_key.texcoord_mask >> (m_idx * 2)) & 0x3])
if (p_key.use_pointsize) {
diff --git a/servers/visual/rasterizer.h b/servers/visual/rasterizer.h
index dd22986865..527230895c 100644
--- a/servers/visual/rasterizer.h
+++ b/servers/visual/rasterizer.h
@@ -29,49 +29,46 @@
#ifndef RASTERIZER_H
#define RASTERIZER_H
-
-#include "servers/visual_server.h"
#include "camera_matrix.h"
+#include "servers/visual_server.h"
#include "self_list.h"
-
class RasterizerScene {
public:
-
/* SHADOW ATLAS API */
- virtual RID shadow_atlas_create()=0;
- virtual void shadow_atlas_set_size(RID p_atlas,int p_size)=0;
- virtual void shadow_atlas_set_quadrant_subdivision(RID p_atlas,int p_quadrant,int p_subdivision)=0;
- virtual bool shadow_atlas_update_light(RID p_atlas,RID p_light_intance,float p_coverage,uint64_t p_light_version)=0;
+ virtual RID shadow_atlas_create() = 0;
+ virtual void shadow_atlas_set_size(RID p_atlas, int p_size) = 0;
+ virtual void shadow_atlas_set_quadrant_subdivision(RID p_atlas, int p_quadrant, int p_subdivision) = 0;
+ virtual bool shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version) = 0;
- virtual int get_directional_light_shadow_size(RID p_light_intance)=0;
- virtual void set_directional_shadow_count(int p_count)=0;
+ virtual int get_directional_light_shadow_size(RID p_light_intance) = 0;
+ virtual void set_directional_shadow_count(int p_count) = 0;
/* ENVIRONMENT API */
- virtual RID environment_create()=0;
+ virtual RID environment_create() = 0;
- virtual void environment_set_background(RID p_env,VS::EnvironmentBG p_bg)=0;
- virtual void environment_set_skybox(RID p_env,RID p_skybox)=0;
- virtual void environment_set_skybox_scale(RID p_env,float p_scale)=0;
- virtual void environment_set_bg_color(RID p_env,const Color& p_color)=0;
- virtual void environment_set_bg_energy(RID p_env,float p_energy)=0;
- virtual void environment_set_canvas_max_layer(RID p_env,int p_max_layer)=0;
- virtual void environment_set_ambient_light(RID p_env,const Color& p_color,float p_energy=1.0,float p_skybox_contribution=0.0)=0;
+ virtual void environment_set_background(RID p_env, VS::EnvironmentBG p_bg) = 0;
+ virtual void environment_set_skybox(RID p_env, RID p_skybox) = 0;
+ virtual void environment_set_skybox_scale(RID p_env, float p_scale) = 0;
+ virtual void environment_set_bg_color(RID p_env, const Color &p_color) = 0;
+ virtual void environment_set_bg_energy(RID p_env, float p_energy) = 0;
+ virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer) = 0;
+ virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_skybox_contribution = 0.0) = 0;
- virtual void environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality)=0;
- virtual void environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,VS::EnvironmentDOFBlurQuality p_quality)=0;
- virtual void environment_set_glow(RID p_env,bool p_enable,int p_level_flags,float p_intensity,float p_strength,float p_bloom_treshold,VS::EnvironmentGlowBlendMode p_blend_mode,float p_hdr_bleed_treshold,float p_hdr_bleed_scale,bool p_bicubic_upscale)=0;
- virtual void environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture)=0;
+ virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality) = 0;
+ virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, VS::EnvironmentDOFBlurQuality p_quality) = 0;
+ virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) = 0;
+ virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) = 0;
- virtual void environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness)=0;
- virtual void environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur)=0;
+ virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness) = 0;
+ virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, const Color &p_color, bool p_blur) = 0;
- virtual void environment_set_tonemap(RID p_env,VS::EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_scale)=0;
+ virtual void environment_set_tonemap(RID p_env, VS::EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_scale) = 0;
- virtual void environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp)=0;
+ virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) = 0;
struct InstanceBase : RID_Data {
@@ -100,10 +97,10 @@ public:
//Transform *baked_light_octree_xform;
//int baked_lightmap_id;
- bool mirror :8;
- bool depth_scale :8;
- bool billboard :8;
- bool billboard_y :8;
+ bool mirror : 8;
+ bool depth_scale : 8;
+ bool billboard : 8;
+ bool billboard_y : 8;
bool receive_shadows : 8;
bool visible : 8;
@@ -113,338 +110,323 @@ public:
InstanceBase *baked_light; //baked light to use
SelfList<InstanceBase> baked_light_item;
- virtual void base_removed()=0;
- virtual void base_changed()=0;
- virtual void base_material_changed()=0;
-
- InstanceBase() : dependency_item(this), baked_light_item(this) {
-
- base_type=VS::INSTANCE_NONE;
- cast_shadows=VS::SHADOW_CASTING_SETTING_ON;
- receive_shadows=true;
- depth_scale=false;
- billboard=false;
- billboard_y=false;
- visible=true;
- depth_layer=0;
- layer_mask=1;
- baked_light=NULL;
-
-
+ virtual void base_removed() = 0;
+ virtual void base_changed() = 0;
+ virtual void base_material_changed() = 0;
+
+ InstanceBase()
+ : dependency_item(this), baked_light_item(this) {
+
+ base_type = VS::INSTANCE_NONE;
+ cast_shadows = VS::SHADOW_CASTING_SETTING_ON;
+ receive_shadows = true;
+ depth_scale = false;
+ billboard = false;
+ billboard_y = false;
+ visible = true;
+ depth_layer = 0;
+ layer_mask = 1;
+ baked_light = NULL;
}
};
- virtual RID light_instance_create(RID p_light)=0;
- virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform)=0;
- virtual void light_instance_set_shadow_transform(RID p_light_instance,const CameraMatrix& p_projection,const Transform& p_transform,float p_far,float p_split,int p_pass)=0;
- virtual void light_instance_mark_visible(RID p_light_instance)=0;
+ virtual RID light_instance_create(RID p_light) = 0;
+ virtual void light_instance_set_transform(RID p_light_instance, const Transform &p_transform) = 0;
+ virtual void light_instance_set_shadow_transform(RID p_light_instance, const CameraMatrix &p_projection, const Transform &p_transform, float p_far, float p_split, int p_pass) = 0;
+ virtual void light_instance_mark_visible(RID p_light_instance) = 0;
- virtual RID reflection_atlas_create()=0;
- virtual void reflection_atlas_set_size(RID p_ref_atlas,int p_size)=0;
- virtual void reflection_atlas_set_subdivision(RID p_ref_atlas,int p_subdiv)=0;
+ virtual RID reflection_atlas_create() = 0;
+ virtual void reflection_atlas_set_size(RID p_ref_atlas, int p_size) = 0;
+ virtual void reflection_atlas_set_subdivision(RID p_ref_atlas, int p_subdiv) = 0;
- virtual RID reflection_probe_instance_create(RID p_probe)=0;
- virtual void reflection_probe_instance_set_transform(RID p_instance,const Transform& p_transform)=0;
- virtual void reflection_probe_release_atlas_index(RID p_instance)=0;
- virtual bool reflection_probe_instance_needs_redraw(RID p_instance)=0;
- virtual bool reflection_probe_instance_has_reflection(RID p_instance)=0;
- virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas)=0;
- virtual bool reflection_probe_instance_postprocess_step(RID p_instance)=0;
+ virtual RID reflection_probe_instance_create(RID p_probe) = 0;
+ virtual void reflection_probe_instance_set_transform(RID p_instance, const Transform &p_transform) = 0;
+ virtual void reflection_probe_release_atlas_index(RID p_instance) = 0;
+ virtual bool reflection_probe_instance_needs_redraw(RID p_instance) = 0;
+ virtual bool reflection_probe_instance_has_reflection(RID p_instance) = 0;
+ virtual bool reflection_probe_instance_begin_render(RID p_instance, RID p_reflection_atlas) = 0;
+ virtual bool reflection_probe_instance_postprocess_step(RID p_instance) = 0;
- virtual RID gi_probe_instance_create()=0;
- virtual void gi_probe_instance_set_light_data(RID p_probe,RID p_base,RID p_data)=0;
- virtual void gi_probe_instance_set_transform_to_data(RID p_probe,const Transform& p_xform)=0;
- virtual void gi_probe_instance_set_bounds(RID p_probe,const Vector3& p_bounds)=0;
+ virtual RID gi_probe_instance_create() = 0;
+ virtual void gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) = 0;
+ virtual void gi_probe_instance_set_transform_to_data(RID p_probe, const Transform &p_xform) = 0;
+ virtual void gi_probe_instance_set_bounds(RID p_probe, const Vector3 &p_bounds) = 0;
- virtual void render_scene(const Transform& p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_ortogonal,InstanceBase** p_cull_result,int p_cull_count,RID* p_light_cull_result,int p_light_cull_count,RID* p_reflection_probe_cull_result,int p_reflection_probe_cull_count,RID p_environment,RID p_shadow_atlas,RID p_reflection_atlas,RID p_reflection_probe,int p_reflection_probe_pass)=0;
- virtual void render_shadow(RID p_light,RID p_shadow_atlas,int p_pass,InstanceBase** p_cull_result,int p_cull_count)=0;
+ virtual void render_scene(const Transform &p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_ortogonal, InstanceBase **p_cull_result, int p_cull_count, RID *p_light_cull_result, int p_light_cull_count, RID *p_reflection_probe_cull_result, int p_reflection_probe_cull_count, RID p_environment, RID p_shadow_atlas, RID p_reflection_atlas, RID p_reflection_probe, int p_reflection_probe_pass) = 0;
+ virtual void render_shadow(RID p_light, RID p_shadow_atlas, int p_pass, InstanceBase **p_cull_result, int p_cull_count) = 0;
- virtual void set_scene_pass(uint64_t p_pass)=0;
+ virtual void set_scene_pass(uint64_t p_pass) = 0;
- virtual bool free(RID p_rid)=0;
+ virtual bool free(RID p_rid) = 0;
virtual ~RasterizerScene() {}
};
-
-
-
-
-
-
class RasterizerStorage {
public:
/* TEXTURE API */
- virtual RID texture_create()=0;
- virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT)=0;
- virtual void texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT)=0;
- virtual Image texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const=0;
- virtual void texture_set_flags(RID p_texture,uint32_t p_flags)=0;
- virtual uint32_t texture_get_flags(RID p_texture) const=0;
- virtual Image::Format texture_get_format(RID p_texture) const=0;
- virtual uint32_t texture_get_width(RID p_texture) const=0;
- virtual uint32_t texture_get_height(RID p_texture) const=0;
- virtual void texture_set_size_override(RID p_texture,int p_width, int p_height)=0;
+ virtual RID texture_create() = 0;
+ virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = VS::TEXTURE_FLAGS_DEFAULT) = 0;
+ virtual void texture_set_data(RID p_texture, const Image &p_image, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) = 0;
+ virtual Image texture_get_data(RID p_texture, VS::CubeMapSide p_cube_side = VS::CUBEMAP_LEFT) const = 0;
+ virtual void texture_set_flags(RID p_texture, uint32_t p_flags) = 0;
+ virtual uint32_t texture_get_flags(RID p_texture) const = 0;
+ virtual Image::Format texture_get_format(RID p_texture) const = 0;
+ virtual uint32_t texture_get_width(RID p_texture) const = 0;
+ virtual uint32_t texture_get_height(RID p_texture) const = 0;
+ virtual void texture_set_size_override(RID p_texture, int p_width, int p_height) = 0;
- virtual void texture_set_path(RID p_texture,const String& p_path)=0;
- virtual String texture_get_path(RID p_texture) const=0;
+ virtual void texture_set_path(RID p_texture, const String &p_path) = 0;
+ virtual String texture_get_path(RID p_texture) const = 0;
- virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable)=0;
+ virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable) = 0;
- virtual void texture_debug_usage(List<VS::TextureInfo> *r_info)=0;
+ virtual void texture_debug_usage(List<VS::TextureInfo> *r_info) = 0;
- virtual RID texture_create_radiance_cubemap(RID p_source,int p_resolution=-1) const=0;
+ virtual RID texture_create_radiance_cubemap(RID p_source, int p_resolution = -1) const = 0;
- virtual void texture_set_detect_3d_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata)=0;
- virtual void texture_set_detect_srgb_callback(RID p_texture,VisualServer::TextureDetectCallback p_callback,void* p_userdata)=0;
+ virtual void texture_set_detect_3d_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) = 0;
+ virtual void texture_set_detect_srgb_callback(RID p_texture, VisualServer::TextureDetectCallback p_callback, void *p_userdata) = 0;
- virtual void textures_keep_original(bool p_enable)=0;
+ virtual void textures_keep_original(bool p_enable) = 0;
/* SKYBOX API */
- virtual RID skybox_create()=0;
- virtual void skybox_set_texture(RID p_skybox,RID p_cube_map,int p_radiance_size)=0;
+ virtual RID skybox_create() = 0;
+ virtual void skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size) = 0;
/* SHADER API */
+ virtual RID shader_create(VS::ShaderMode p_mode = VS::SHADER_SPATIAL) = 0;
- virtual RID shader_create(VS::ShaderMode p_mode=VS::SHADER_SPATIAL)=0;
-
- virtual void shader_set_mode(RID p_shader,VS::ShaderMode p_mode)=0;
- virtual VS::ShaderMode shader_get_mode(RID p_shader) const=0;
+ virtual void shader_set_mode(RID p_shader, VS::ShaderMode p_mode) = 0;
+ virtual VS::ShaderMode shader_get_mode(RID p_shader) const = 0;
- virtual void shader_set_code(RID p_shader, const String& p_code)=0;
- virtual String shader_get_code(RID p_shader) const=0;
- virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const=0;
-
- virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture)=0;
- virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const=0;
+ virtual void shader_set_code(RID p_shader, const String &p_code) = 0;
+ virtual String shader_get_code(RID p_shader) const = 0;
+ virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const = 0;
+ virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) = 0;
+ virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const = 0;
/* COMMON MATERIAL API */
- virtual RID material_create()=0;
+ virtual RID material_create() = 0;
- virtual void material_set_shader(RID p_shader_material, RID p_shader)=0;
- virtual RID material_get_shader(RID p_shader_material) const=0;
+ virtual void material_set_shader(RID p_shader_material, RID p_shader) = 0;
+ virtual RID material_get_shader(RID p_shader_material) const = 0;
- virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value)=0;
- virtual Variant material_get_param(RID p_material, const StringName& p_param) const=0;
+ virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) = 0;
+ virtual Variant material_get_param(RID p_material, const StringName &p_param) const = 0;
- virtual void material_set_line_width(RID p_material, float p_width)=0;
+ virtual void material_set_line_width(RID p_material, float p_width) = 0;
- virtual bool material_is_animated(RID p_material)=0;
- virtual bool material_casts_shadows(RID p_material)=0;
+ virtual bool material_is_animated(RID p_material) = 0;
+ virtual bool material_casts_shadows(RID p_material) = 0;
- virtual void material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance)=0;
- virtual void material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance)=0;
+ virtual void material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) = 0;
+ virtual void material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) = 0;
/* MESH API */
- virtual RID mesh_create()=0;
+ virtual RID mesh_create() = 0;
- virtual void mesh_add_surface(RID p_mesh,uint32_t p_format,VS::PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>())=0;
+ virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, VS::PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>()) = 0;
- virtual void mesh_set_blend_shape_count(RID p_mesh,int p_amount)=0;
- virtual int mesh_get_blend_shape_count(RID p_mesh) const=0;
+ virtual void mesh_set_blend_shape_count(RID p_mesh, int p_amount) = 0;
+ virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0;
+ virtual void mesh_set_blend_shape_mode(RID p_mesh, VS::BlendShapeMode p_mode) = 0;
+ virtual VS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0;
- virtual void mesh_set_blend_shape_mode(RID p_mesh,VS::BlendShapeMode p_mode)=0;
- virtual VS::BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const=0;
+ virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0;
+ virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0;
- virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material)=0;
- virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const=0;
+ virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const = 0;
+ virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const = 0;
- virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const=0;
- virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const=0;
+ virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const = 0;
+ virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const = 0;
- virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const=0;
- virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const=0;
+ virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const = 0;
+ virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const = 0;
+ virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const = 0;
+ virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const = 0;
+ virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const = 0;
- virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const=0;
- virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const=0;
+ virtual void mesh_remove_surface(RID p_mesh, int p_index) = 0;
+ virtual int mesh_get_surface_count(RID p_mesh) const = 0;
- virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const=0;
- virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const=0;
- virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const=0;
+ virtual void mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb) = 0;
+ virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const = 0;
- virtual void mesh_remove_surface(RID p_mesh,int p_index)=0;
- virtual int mesh_get_surface_count(RID p_mesh) const=0;
-
- virtual void mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb)=0;
- virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const=0;
-
- virtual Rect3 mesh_get_aabb(RID p_mesh, RID p_skeleton) const=0;
- virtual void mesh_clear(RID p_mesh)=0;
+ virtual Rect3 mesh_get_aabb(RID p_mesh, RID p_skeleton) const = 0;
+ virtual void mesh_clear(RID p_mesh) = 0;
/* MULTIMESH API */
+ virtual RID multimesh_create() = 0;
- virtual RID multimesh_create()=0;
+ virtual void multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format) = 0;
+ virtual int multimesh_get_instance_count(RID p_multimesh) const = 0;
- virtual void multimesh_allocate(RID p_multimesh,int p_instances,VS::MultimeshTransformFormat p_transform_format,VS::MultimeshColorFormat p_color_format)=0;
- virtual int multimesh_get_instance_count(RID p_multimesh) const=0;
-
- virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh)=0;
- virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform)=0;
- virtual void multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform)=0;
- virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color)=0;
+ virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0;
+ virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) = 0;
+ virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0;
+ virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0;
- virtual RID multimesh_get_mesh(RID p_multimesh) const=0;
+ virtual RID multimesh_get_mesh(RID p_multimesh) const = 0;
- virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const=0;
- virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const=0;
- virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const=0;
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0;
+ virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0;
+ virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0;
- virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible)=0;
- virtual int multimesh_get_visible_instances(RID p_multimesh) const=0;
+ virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0;
+ virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0;
- virtual Rect3 multimesh_get_aabb(RID p_multimesh) const=0;
+ virtual Rect3 multimesh_get_aabb(RID p_multimesh) const = 0;
/* IMMEDIATE API */
- virtual RID immediate_create()=0;
- virtual void immediate_begin(RID p_immediate,VS::PrimitiveType p_rimitive,RID p_texture=RID())=0;
- virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex)=0;
- virtual void immediate_normal(RID p_immediate,const Vector3& p_normal)=0;
- virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent)=0;
- virtual void immediate_color(RID p_immediate,const Color& p_color)=0;
- virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv)=0;
- virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv)=0;
- virtual void immediate_end(RID p_immediate)=0;
- virtual void immediate_clear(RID p_immediate)=0;
- virtual void immediate_set_material(RID p_immediate,RID p_material)=0;
- virtual RID immediate_get_material(RID p_immediate) const=0;
- virtual Rect3 immediate_get_aabb(RID p_immediate) const=0;
-
+ virtual RID immediate_create() = 0;
+ virtual void immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture = RID()) = 0;
+ virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex) = 0;
+ virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal) = 0;
+ virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent) = 0;
+ virtual void immediate_color(RID p_immediate, const Color &p_color) = 0;
+ virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv) = 0;
+ virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv) = 0;
+ virtual void immediate_end(RID p_immediate) = 0;
+ virtual void immediate_clear(RID p_immediate) = 0;
+ virtual void immediate_set_material(RID p_immediate, RID p_material) = 0;
+ virtual RID immediate_get_material(RID p_immediate) const = 0;
+ virtual Rect3 immediate_get_aabb(RID p_immediate) const = 0;
/* SKELETON API */
- virtual RID skeleton_create()=0;
- virtual void skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton=false)=0;
- virtual int skeleton_get_bone_count(RID p_skeleton) const=0;
- virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform)=0;
- virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone) const =0;
- virtual void skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform)=0;
- virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone) const=0;
+ virtual RID skeleton_create() = 0;
+ virtual void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0;
+ virtual int skeleton_get_bone_count(RID p_skeleton) const = 0;
+ virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) = 0;
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0;
+ virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0;
+ virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0;
/* Light API */
- virtual RID light_create(VS::LightType p_type)=0;
+ virtual RID light_create(VS::LightType p_type) = 0;
- virtual void light_set_color(RID p_light,const Color& p_color)=0;
- virtual void light_set_param(RID p_light,VS::LightParam p_param,float p_value)=0;
- virtual void light_set_shadow(RID p_light,bool p_enabled)=0;
- virtual void light_set_shadow_color(RID p_light,const Color& p_color)=0;
- virtual void light_set_projector(RID p_light,RID p_texture)=0;
- virtual void light_set_negative(RID p_light,bool p_enable)=0;
- virtual void light_set_cull_mask(RID p_light,uint32_t p_mask)=0;
+ virtual void light_set_color(RID p_light, const Color &p_color) = 0;
+ virtual void light_set_param(RID p_light, VS::LightParam p_param, float p_value) = 0;
+ virtual void light_set_shadow(RID p_light, bool p_enabled) = 0;
+ virtual void light_set_shadow_color(RID p_light, const Color &p_color) = 0;
+ virtual void light_set_projector(RID p_light, RID p_texture) = 0;
+ virtual void light_set_negative(RID p_light, bool p_enable) = 0;
+ virtual void light_set_cull_mask(RID p_light, uint32_t p_mask) = 0;
- virtual void light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode)=0;
- virtual void light_omni_set_shadow_detail(RID p_light,VS::LightOmniShadowDetail p_detail)=0;
-
- virtual void light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode)=0;
- virtual void light_directional_set_blend_splits(RID p_light,bool p_enable)=0;
- virtual bool light_directional_get_blend_splits(RID p_light) const=0;
+ virtual void light_omni_set_shadow_mode(RID p_light, VS::LightOmniShadowMode p_mode) = 0;
+ virtual void light_omni_set_shadow_detail(RID p_light, VS::LightOmniShadowDetail p_detail) = 0;
- virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light)=0;
- virtual VS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light)=0;
+ virtual void light_directional_set_shadow_mode(RID p_light, VS::LightDirectionalShadowMode p_mode) = 0;
+ virtual void light_directional_set_blend_splits(RID p_light, bool p_enable) = 0;
+ virtual bool light_directional_get_blend_splits(RID p_light) const = 0;
- virtual bool light_has_shadow(RID p_light) const=0;
+ virtual VS::LightDirectionalShadowMode light_directional_get_shadow_mode(RID p_light) = 0;
+ virtual VS::LightOmniShadowMode light_omni_get_shadow_mode(RID p_light) = 0;
- virtual VS::LightType light_get_type(RID p_light) const=0;
- virtual Rect3 light_get_aabb(RID p_light) const=0;
- virtual float light_get_param(RID p_light,VS::LightParam p_param)=0;
- virtual Color light_get_color(RID p_light)=0;
- virtual uint64_t light_get_version(RID p_light) const=0;
+ virtual bool light_has_shadow(RID p_light) const = 0;
+ virtual VS::LightType light_get_type(RID p_light) const = 0;
+ virtual Rect3 light_get_aabb(RID p_light) const = 0;
+ virtual float light_get_param(RID p_light, VS::LightParam p_param) = 0;
+ virtual Color light_get_color(RID p_light) = 0;
+ virtual uint64_t light_get_version(RID p_light) const = 0;
/* PROBE API */
- virtual RID reflection_probe_create()=0;
-
- virtual void reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode)=0;
- virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity)=0;
- virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color& p_ambient)=0;
- virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy)=0;
- virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib)=0;
- virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance)=0;
- virtual void reflection_probe_set_extents(RID p_probe, const Vector3& p_extents)=0;
- virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset)=0;
- virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers)=0;
-
- virtual Rect3 reflection_probe_get_aabb(RID p_probe) const=0;
- virtual VS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const=0;
- virtual uint32_t reflection_probe_get_cull_mask(RID p_probe) const=0;
- virtual Vector3 reflection_probe_get_extents(RID p_probe) const=0;
- virtual Vector3 reflection_probe_get_origin_offset(RID p_probe) const=0;
- virtual float reflection_probe_get_origin_max_distance(RID p_probe) const=0;
- virtual bool reflection_probe_renders_shadows(RID p_probe) const=0;
-
+ virtual RID reflection_probe_create() = 0;
+
+ virtual void reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode) = 0;
+ virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity) = 0;
+ virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color &p_ambient) = 0;
+ virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) = 0;
+ virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) = 0;
+ virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance) = 0;
+ virtual void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) = 0;
+ virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) = 0;
+ virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) = 0;
+
+ virtual Rect3 reflection_probe_get_aabb(RID p_probe) const = 0;
+ virtual VS::ReflectionProbeUpdateMode reflection_probe_get_update_mode(RID p_probe) const = 0;
+ virtual uint32_t reflection_probe_get_cull_mask(RID p_probe) const = 0;
+ virtual Vector3 reflection_probe_get_extents(RID p_probe) const = 0;
+ virtual Vector3 reflection_probe_get_origin_offset(RID p_probe) const = 0;
+ virtual float reflection_probe_get_origin_max_distance(RID p_probe) const = 0;
+ virtual bool reflection_probe_renders_shadows(RID p_probe) const = 0;
/* ROOM API */
- virtual RID room_create()=0;
- virtual void room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform)=0;
- virtual void room_clear_bounds(RID p_room)=0;
+ virtual RID room_create() = 0;
+ virtual void room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform) = 0;
+ virtual void room_clear_bounds(RID p_room) = 0;
/* PORTAL API */
// portals are only (x/y) points, forming a convex shape, which its clockwise
// order points outside. (z is 0)=0;
- virtual RID portal_create()=0;
- virtual void portal_set_shape(RID p_portal, const Vector<Point2>& p_shape)=0;
- virtual void portal_set_enabled(RID p_portal, bool p_enabled)=0;
- virtual void portal_set_disable_distance(RID p_portal, float p_distance)=0;
- virtual void portal_set_disabled_color(RID p_portal, const Color& p_color)=0;
+ virtual RID portal_create() = 0;
+ virtual void portal_set_shape(RID p_portal, const Vector<Point2> &p_shape) = 0;
+ virtual void portal_set_enabled(RID p_portal, bool p_enabled) = 0;
+ virtual void portal_set_disable_distance(RID p_portal, float p_distance) = 0;
+ virtual void portal_set_disabled_color(RID p_portal, const Color &p_color) = 0;
- virtual void instance_add_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance)=0;
- virtual void instance_remove_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance)=0;
+ virtual void instance_add_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) = 0;
+ virtual void instance_remove_skeleton(RID p_skeleton, RasterizerScene::InstanceBase *p_instance) = 0;
- virtual void instance_add_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance)=0;
- virtual void instance_remove_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance)=0;
+ virtual void instance_add_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) = 0;
+ virtual void instance_remove_dependency(RID p_base, RasterizerScene::InstanceBase *p_instance) = 0;
/* GI PROBE API */
- virtual RID gi_probe_create()=0;
+ virtual RID gi_probe_create() = 0;
- virtual void gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds)=0;
- virtual Rect3 gi_probe_get_bounds(RID p_probe) const=0;
+ virtual void gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds) = 0;
+ virtual Rect3 gi_probe_get_bounds(RID p_probe) const = 0;
- virtual void gi_probe_set_cell_size(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_cell_size(RID p_probe) const=0;
+ virtual void gi_probe_set_cell_size(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_cell_size(RID p_probe) const = 0;
- virtual void gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform)=0;
- virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const=0;
+ virtual void gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) = 0;
+ virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const = 0;
- virtual void gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data)=0;
- virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const=0;
+ virtual void gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) = 0;
+ virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const = 0;
- virtual void gi_probe_set_dynamic_range(RID p_probe,int p_range)=0;
- virtual int gi_probe_get_dynamic_range(RID p_probe) const=0;
+ virtual void gi_probe_set_dynamic_range(RID p_probe, int p_range) = 0;
+ virtual int gi_probe_get_dynamic_range(RID p_probe) const = 0;
- virtual void gi_probe_set_energy(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_energy(RID p_probe) const=0;
+ virtual void gi_probe_set_energy(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_energy(RID p_probe) const = 0;
- virtual void gi_probe_set_bias(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_bias(RID p_probe) const=0;
+ virtual void gi_probe_set_bias(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_bias(RID p_probe) const = 0;
- virtual void gi_probe_set_propagation(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_propagation(RID p_probe) const=0;
+ virtual void gi_probe_set_propagation(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_propagation(RID p_probe) const = 0;
- virtual void gi_probe_set_interior(RID p_probe,bool p_enable)=0;
- virtual bool gi_probe_is_interior(RID p_probe) const=0;
+ virtual void gi_probe_set_interior(RID p_probe, bool p_enable) = 0;
+ virtual bool gi_probe_is_interior(RID p_probe) const = 0;
- virtual void gi_probe_set_compress(RID p_probe,bool p_enable)=0;
- virtual bool gi_probe_is_compressed(RID p_probe) const=0;
+ virtual void gi_probe_set_compress(RID p_probe, bool p_enable) = 0;
+ virtual bool gi_probe_is_compressed(RID p_probe) const = 0;
- virtual uint32_t gi_probe_get_version(RID p_probe)=0;
+ virtual uint32_t gi_probe_get_version(RID p_probe) = 0;
enum GIProbeCompression {
GI_PROBE_UNCOMPRESSED,
@@ -452,41 +434,37 @@ public:
GI_PROBE_ETC2
};
- virtual GIProbeCompression gi_probe_get_dynamic_data_get_preferred_compression() const=0;
- virtual RID gi_probe_dynamic_data_create(int p_width,int p_height,int p_depth,GIProbeCompression p_compression)=0;
- virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data,int p_depth_slice,int p_slice_count,int p_mipmap,const void* p_data)=0;
-
+ virtual GIProbeCompression gi_probe_get_dynamic_data_get_preferred_compression() const = 0;
+ virtual RID gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression) = 0;
+ virtual void gi_probe_dynamic_data_update(RID p_gi_probe_data, int p_depth_slice, int p_slice_count, int p_mipmap, const void *p_data) = 0;
/* PARTICLES */
- virtual RID particles_create()=0;
-
- virtual void particles_set_emitting(RID p_particles,bool p_emitting)=0;
- virtual void particles_set_amount(RID p_particles,int p_amount)=0;
- virtual void particles_set_lifetime(RID p_particles,float p_lifetime)=0;
- virtual void particles_set_pre_process_time(RID p_particles,float p_time)=0;
- virtual void particles_set_explosiveness_ratio(RID p_particles,float p_ratio)=0;
- virtual void particles_set_randomness_ratio(RID p_particles,float p_ratio)=0;
- virtual void particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb)=0;
- virtual void particles_set_gravity(RID p_particles,const Vector3& p_gravity)=0;
- virtual void particles_set_use_local_coordinates(RID p_particles,bool p_enable)=0;
- virtual void particles_set_process_material(RID p_particles,RID p_material)=0;
-
- virtual void particles_set_emission_shape(RID p_particles,VS::ParticlesEmissionShape p_shape)=0;
- virtual void particles_set_emission_sphere_radius(RID p_particles,float p_radius)=0;
- virtual void particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents)=0;
- virtual void particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points)=0;
+ virtual RID particles_create() = 0;
+ virtual void particles_set_emitting(RID p_particles, bool p_emitting) = 0;
+ virtual void particles_set_amount(RID p_particles, int p_amount) = 0;
+ virtual void particles_set_lifetime(RID p_particles, float p_lifetime) = 0;
+ virtual void particles_set_pre_process_time(RID p_particles, float p_time) = 0;
+ virtual void particles_set_explosiveness_ratio(RID p_particles, float p_ratio) = 0;
+ virtual void particles_set_randomness_ratio(RID p_particles, float p_ratio) = 0;
+ virtual void particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb) = 0;
+ virtual void particles_set_gravity(RID p_particles, const Vector3 &p_gravity) = 0;
+ virtual void particles_set_use_local_coordinates(RID p_particles, bool p_enable) = 0;
+ virtual void particles_set_process_material(RID p_particles, RID p_material) = 0;
- virtual void particles_set_draw_order(RID p_particles,VS::ParticlesDrawOrder p_order)=0;
+ virtual void particles_set_emission_shape(RID p_particles, VS::ParticlesEmissionShape p_shape) = 0;
+ virtual void particles_set_emission_sphere_radius(RID p_particles, float p_radius) = 0;
+ virtual void particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents) = 0;
+ virtual void particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) = 0;
- virtual void particles_set_draw_passes(RID p_particles,int p_count)=0;
- virtual void particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material)=0;
- virtual void particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh)=0;
-
- virtual Rect3 particles_get_current_aabb(RID p_particles)=0;
+ virtual void particles_set_draw_order(RID p_particles, VS::ParticlesDrawOrder p_order) = 0;
+ virtual void particles_set_draw_passes(RID p_particles, int p_count) = 0;
+ virtual void particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material) = 0;
+ virtual void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) = 0;
+ virtual Rect3 particles_get_current_aabb(RID p_particles) = 0;
/* RENDER TARGET */
@@ -499,57 +477,47 @@ public:
RENDER_TARGET_FLAG_MAX
};
- virtual RID render_target_create()=0;
- virtual void render_target_set_size(RID p_render_target,int p_width, int p_height)=0;
- virtual RID render_target_get_texture(RID p_render_target) const=0;
- virtual void render_target_set_flag(RID p_render_target,RenderTargetFlags p_flag,bool p_value)=0;
- virtual bool render_target_renedered_in_frame(RID p_render_target)=0;
- virtual void render_target_set_msaa(RID p_render_target,VS::ViewportMSAA p_msaa)=0;
-
+ virtual RID render_target_create() = 0;
+ virtual void render_target_set_size(RID p_render_target, int p_width, int p_height) = 0;
+ virtual RID render_target_get_texture(RID p_render_target) const = 0;
+ virtual void render_target_set_flag(RID p_render_target, RenderTargetFlags p_flag, bool p_value) = 0;
+ virtual bool render_target_renedered_in_frame(RID p_render_target) = 0;
+ virtual void render_target_set_msaa(RID p_render_target, VS::ViewportMSAA p_msaa) = 0;
/* CANVAS SHADOW */
- virtual RID canvas_light_shadow_buffer_create(int p_width)=0;
+ virtual RID canvas_light_shadow_buffer_create(int p_width) = 0;
/* LIGHT SHADOW MAPPING */
- virtual RID canvas_light_occluder_create()=0;
- virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines)=0;
-
+ virtual RID canvas_light_occluder_create() = 0;
+ virtual void canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2> &p_lines) = 0;
- virtual VS::InstanceType get_base_type(RID p_rid) const=0;
- virtual bool free(RID p_rid)=0;
+ virtual VS::InstanceType get_base_type(RID p_rid) const = 0;
+ virtual bool free(RID p_rid) = 0;
- virtual bool has_os_feature(const String& p_feature) const=0;
+ virtual bool has_os_feature(const String &p_feature) const = 0;
- virtual void update_dirty_resources()=0;
+ virtual void update_dirty_resources() = 0;
- static RasterizerStorage*base_signleton;
+ static RasterizerStorage *base_signleton;
RasterizerStorage();
virtual ~RasterizerStorage() {}
};
-
-
-
-
class RasterizerCanvas {
public:
-
enum CanvasRectFlags {
- CANVAS_RECT_REGION=1,
- CANVAS_RECT_TILE=2,
- CANVAS_RECT_FLIP_H=4,
- CANVAS_RECT_FLIP_V=8,
- CANVAS_RECT_TRANSPOSE=16
+ CANVAS_RECT_REGION = 1,
+ CANVAS_RECT_TILE = 2,
+ CANVAS_RECT_FLIP_H = 4,
+ CANVAS_RECT_FLIP_V = 8,
+ CANVAS_RECT_TRANSPOSE = 16
};
-
struct Light : public RID_Data {
-
-
bool enabled;
Color color;
Transform2D xform;
@@ -572,7 +540,6 @@ public:
VS::CanvasLightShadowFilter shadow_filter;
Color shadow_color;
-
void *texture_cache; // implementation dependent
Rect2 rect_cache;
Transform2D xform_cache;
@@ -590,33 +557,32 @@ public:
RID light_internal;
Light() {
- enabled=true;
- color=Color(1,1,1);
- shadow_color=Color(0,0,0,0);
- height=0;
- z_min=-1024;
- z_max=1024;
- layer_min=0;
- layer_max=0;
- item_mask=1;
- scale=1.0;
- energy=1.0;
- item_shadow_mask=-1;
- mode=VS::CANVAS_LIGHT_MODE_ADD;
- texture_cache=NULL;
- next_ptr=NULL;
- mask_next_ptr=NULL;
- filter_next_ptr=NULL;
- shadow_buffer_size=256;
- shadow_gradient_length=0;
- shadow_filter=VS::CANVAS_LIGHT_FILTER_NONE;
-
+ enabled = true;
+ color = Color(1, 1, 1);
+ shadow_color = Color(0, 0, 0, 0);
+ height = 0;
+ z_min = -1024;
+ z_max = 1024;
+ layer_min = 0;
+ layer_max = 0;
+ item_mask = 1;
+ scale = 1.0;
+ energy = 1.0;
+ item_shadow_mask = -1;
+ mode = VS::CANVAS_LIGHT_MODE_ADD;
+ texture_cache = NULL;
+ next_ptr = NULL;
+ mask_next_ptr = NULL;
+ filter_next_ptr = NULL;
+ shadow_buffer_size = 256;
+ shadow_gradient_length = 0;
+ shadow_filter = VS::CANVAS_LIGHT_FILTER_NONE;
}
};
- virtual RID light_internal_create()=0;
- virtual void light_internal_update(RID p_rid, Light* p_light)=0;
- virtual void light_internal_free(RID p_rid)=0;
+ virtual RID light_internal_create() = 0;
+ virtual void light_internal_update(RID p_rid, Light *p_light) = 0;
+ virtual void light_internal_free(RID p_rid) = 0;
struct Item : public RID_Data {
@@ -637,12 +603,12 @@ public:
};
Type type;
- virtual ~Command(){}
+ virtual ~Command() {}
};
struct CommandLine : public Command {
- Point2 from,to;
+ Point2 from, to;
Color color;
float width;
bool antialiased;
@@ -657,7 +623,10 @@ public:
Rect2 source;
uint8_t flags;
- CommandRect() { flags=0; type = TYPE_RECT; }
+ CommandRect() {
+ flags = 0;
+ type = TYPE_RECT;
+ }
};
struct CommandNinePatch : public Command {
@@ -670,7 +639,10 @@ public:
Color color;
VS::NinePatchAxisMode axis_x;
VS::NinePatchAxisMode axis_y;
- CommandNinePatch() { draw_center=true; type = TYPE_NINEPATCH; }
+ CommandNinePatch() {
+ draw_center = true;
+ type = TYPE_NINEPATCH;
+ }
};
struct CommandPrimitive : public Command {
@@ -681,7 +653,10 @@ public:
RID texture;
float width;
- CommandPrimitive() { type = TYPE_PRIMITIVE; width=1;}
+ CommandPrimitive() {
+ type = TYPE_PRIMITIVE;
+ width = 1;
+ }
};
struct CommandPolygon : public Command {
@@ -693,22 +668,24 @@ public:
RID texture;
int count;
- CommandPolygon() { type = TYPE_POLYGON; count = 0; }
+ CommandPolygon() {
+ type = TYPE_POLYGON;
+ count = 0;
+ }
};
-
struct CommandMesh : public Command {
RID mesh;
RID skeleton;
- CommandMesh() { type = TYPE_MESH; }
+ CommandMesh() { type = TYPE_MESH; }
};
struct CommandMultiMesh : public Command {
RID multimesh;
RID skeleton;
- CommandMultiMesh() { type = TYPE_MULTIMESH; }
+ CommandMultiMesh() { type = TYPE_MULTIMESH; }
};
struct CommandCircle : public Command {
@@ -725,17 +702,18 @@ public:
CommandTransform() { type = TYPE_TRANSFORM; }
};
-
struct CommandClipIgnore : public Command {
bool ignore;
- CommandClipIgnore() { type = TYPE_CLIP_IGNORE; ignore=false; }
+ CommandClipIgnore() {
+ type = TYPE_CLIP_IGNORE;
+ ignore = false;
+ }
};
-
struct ViewportRender {
- VisualServer*owner;
- void* udata;
+ VisualServer *owner;
+ void *udata;
Rect2 rect;
};
@@ -745,12 +723,12 @@ public:
bool behind;
//VS::MaterialBlendMode blend_mode;
int light_mask;
- Vector<Command*> commands;
+ Vector<Command *> commands;
mutable bool custom_rect;
mutable bool rect_dirty;
mutable Rect2 rect;
RID material;
- Item*next;
+ Item *next;
struct CopyBackBuffer {
Rect2 rect;
@@ -759,110 +737,106 @@ public:
};
CopyBackBuffer *copy_back_buffer;
-
Color final_modulate;
Transform2D final_transform;
Rect2 final_clip_rect;
- Item* final_clip_owner;
- Item* material_owner;
+ Item *final_clip_owner;
+ Item *material_owner;
ViewportRender *vp_render;
bool distance_field;
bool light_masked;
Rect2 global_rect_cache;
- const Rect2& get_rect() const {
+ const Rect2 &get_rect() const {
if (custom_rect || !rect_dirty)
return rect;
//must update rect
- int s=commands.size();
- if (s==0) {
+ int s = commands.size();
+ if (s == 0) {
- rect=Rect2();
- rect_dirty=false;
+ rect = Rect2();
+ rect_dirty = false;
return rect;
}
Transform2D xf;
- bool found_xform=false;
- bool first=true;
-
- const Item::Command * const *cmd = &commands[0];
+ bool found_xform = false;
+ bool first = true;
+ const Item::Command *const *cmd = &commands[0];
- for (int i=0;i<s;i++) {
+ for (int i = 0; i < s; i++) {
- const Item::Command *c=cmd[i];
+ const Item::Command *c = cmd[i];
Rect2 r;
- switch(c->type) {
+ switch (c->type) {
case Item::Command::TYPE_LINE: {
- const Item::CommandLine* line = static_cast< const Item::CommandLine*>(c);
- r.pos=line->from;
+ const Item::CommandLine *line = static_cast<const Item::CommandLine *>(c);
+ r.pos = line->from;
r.expand_to(line->to);
} break;
case Item::Command::TYPE_RECT: {
- const Item::CommandRect* crect = static_cast< const Item::CommandRect*>(c);
- r=crect->rect;
+ const Item::CommandRect *crect = static_cast<const Item::CommandRect *>(c);
+ r = crect->rect;
} break;
case Item::Command::TYPE_NINEPATCH: {
- const Item::CommandNinePatch* style = static_cast< const Item::CommandNinePatch*>(c);
- r=style->rect;
+ const Item::CommandNinePatch *style = static_cast<const Item::CommandNinePatch *>(c);
+ r = style->rect;
} break;
case Item::Command::TYPE_PRIMITIVE: {
- const Item::CommandPrimitive* primitive = static_cast< const Item::CommandPrimitive*>(c);
- r.pos=primitive->points[0];
- for(int i=1;i<primitive->points.size();i++) {
+ const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
+ r.pos = primitive->points[0];
+ for (int i = 1; i < primitive->points.size(); i++) {
r.expand_to(primitive->points[i]);
-
}
} break;
case Item::Command::TYPE_POLYGON: {
- const Item::CommandPolygon* polygon = static_cast< const Item::CommandPolygon*>(c);
+ const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
int l = polygon->points.size();
- const Point2*pp=&polygon->points[0];
- r.pos=pp[0];
- for(int i=1;i<l;i++) {
+ const Point2 *pp = &polygon->points[0];
+ r.pos = pp[0];
+ for (int i = 1; i < l; i++) {
r.expand_to(pp[i]);
-
}
} break;
case Item::Command::TYPE_MESH: {
- const Item::CommandMesh* mesh = static_cast< const Item::CommandMesh*>(c);
- Rect3 aabb = RasterizerStorage::base_signleton->mesh_get_aabb(mesh->mesh,mesh->skeleton);
+ const Item::CommandMesh *mesh = static_cast<const Item::CommandMesh *>(c);
+ Rect3 aabb = RasterizerStorage::base_signleton->mesh_get_aabb(mesh->mesh, mesh->skeleton);
- r=Rect2(aabb.pos.x,aabb.pos.y,aabb.size.x,aabb.size.y);
+ r = Rect2(aabb.pos.x, aabb.pos.y, aabb.size.x, aabb.size.y);
} break;
case Item::Command::TYPE_MULTIMESH: {
- const Item::CommandMultiMesh* multimesh = static_cast< const Item::CommandMultiMesh*>(c);
+ const Item::CommandMultiMesh *multimesh = static_cast<const Item::CommandMultiMesh *>(c);
Rect3 aabb = RasterizerStorage::base_signleton->multimesh_get_aabb(multimesh->multimesh);
- r=Rect2(aabb.pos.x,aabb.pos.y,aabb.size.x,aabb.size.y);
+ r = Rect2(aabb.pos.x, aabb.pos.y, aabb.size.x, aabb.size.y);
} break;
case Item::Command::TYPE_CIRCLE: {
- const Item::CommandCircle* circle = static_cast< const Item::CommandCircle*>(c);
- r.pos=Point2(-circle->radius,-circle->radius)+circle->pos;
- r.size=Point2(circle->radius*2.0,circle->radius*2.0);
+ const Item::CommandCircle *circle = static_cast<const Item::CommandCircle *>(c);
+ r.pos = Point2(-circle->radius, -circle->radius) + circle->pos;
+ r.size = Point2(circle->radius * 2.0, circle->radius * 2.0);
} break;
case Item::Command::TYPE_TRANSFORM: {
- const Item::CommandTransform* transform = static_cast<const Item::CommandTransform*>(c);
- xf=transform->xform;
- found_xform=true;
+ const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
+ xf = transform->xform;
+ found_xform = true;
continue;
} break;
@@ -873,37 +847,59 @@ public:
if (found_xform) {
r = xf.xform(r);
- found_xform=false;
+ found_xform = false;
}
-
if (first) {
- rect=r;
- first=false;
+ rect = r;
+ first = false;
} else
- rect=rect.merge(r);
+ rect = rect.merge(r);
}
- rect_dirty=false;
+ rect_dirty = false;
return rect;
}
- void clear() { for (int i=0;i<commands.size();i++) memdelete( commands[i] ); commands.clear(); clip=false; rect_dirty=true; final_clip_owner=NULL; material_owner=NULL; light_masked=false; }
- Item() { light_mask=1; vp_render=NULL; next=NULL; final_clip_owner=NULL; clip=false; final_modulate=Color(1,1,1,1); visible=true; rect_dirty=true; custom_rect=false; behind=false; material_owner=NULL; copy_back_buffer=NULL; distance_field=false; light_masked=false; }
- virtual ~Item() { clear(); if (copy_back_buffer) memdelete(copy_back_buffer); }
+ void clear() {
+ for (int i = 0; i < commands.size(); i++)
+ memdelete(commands[i]);
+ commands.clear();
+ clip = false;
+ rect_dirty = true;
+ final_clip_owner = NULL;
+ material_owner = NULL;
+ light_masked = false;
+ }
+ Item() {
+ light_mask = 1;
+ vp_render = NULL;
+ next = NULL;
+ final_clip_owner = NULL;
+ clip = false;
+ final_modulate = Color(1, 1, 1, 1);
+ visible = true;
+ rect_dirty = true;
+ custom_rect = false;
+ behind = false;
+ material_owner = NULL;
+ copy_back_buffer = NULL;
+ distance_field = false;
+ light_masked = false;
+ }
+ virtual ~Item() {
+ clear();
+ if (copy_back_buffer) memdelete(copy_back_buffer);
+ }
};
+ virtual void canvas_begin() = 0;
- virtual void canvas_begin()=0;
-
- virtual void canvas_render_items(Item *p_item_list,int p_z,const Color& p_modulate,Light *p_light)=0;
- virtual void canvas_debug_viewport_shadows(Light* p_lights_with_shadow)=0;
-
-
+ virtual void canvas_render_items(Item *p_item_list, int p_z, const Color &p_modulate, Light *p_light) = 0;
+ virtual void canvas_debug_viewport_shadows(Light *p_lights_with_shadow) = 0;
struct LightOccluderInstance : public RID_Data {
-
bool enabled;
RID canvas;
RID polygon;
@@ -916,52 +912,52 @@ public:
LightOccluderInstance *next;
- LightOccluderInstance() { enabled=true; next=NULL; light_mask=1; cull_cache=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; }
+ LightOccluderInstance() {
+ enabled = true;
+ next = NULL;
+ light_mask = 1;
+ cull_cache = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
+ }
};
+ virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders, CameraMatrix *p_xform_cache) = 0;
-
- virtual void canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, LightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache)=0;
-
-
- virtual void reset_canvas()=0;
+ virtual void reset_canvas() = 0;
virtual ~RasterizerCanvas() {}
};
-
class Rasterizer {
protected:
- static Rasterizer* (*_create_func)();
+ static Rasterizer *(*_create_func)();
+
public:
static Rasterizer *create();
- virtual RasterizerStorage *get_storage()=0;
- virtual RasterizerCanvas *get_canvas()=0;
- virtual RasterizerScene *get_scene()=0;
-
- virtual void initialize()=0;
- virtual void begin_frame()=0;
- virtual void set_current_render_target(RID p_render_target)=0;
- virtual void restore_render_target()=0;
- virtual void clear_render_target(const Color& p_color)=0;
- virtual void blit_render_target_to_screen(RID p_render_target,const Rect2& p_screen_rect,int p_screen=0)=0;
- virtual void end_frame()=0;
- virtual void finalize()=0;
+ virtual RasterizerStorage *get_storage() = 0;
+ virtual RasterizerCanvas *get_canvas() = 0;
+ virtual RasterizerScene *get_scene() = 0;
+ virtual void initialize() = 0;
+ virtual void begin_frame() = 0;
+ virtual void set_current_render_target(RID p_render_target) = 0;
+ virtual void restore_render_target() = 0;
+ virtual void clear_render_target(const Color &p_color) = 0;
+ virtual void blit_render_target_to_screen(RID p_render_target, const Rect2 &p_screen_rect, int p_screen = 0) = 0;
+ virtual void end_frame() = 0;
+ virtual void finalize() = 0;
virtual ~Rasterizer() {}
};
-
#if 0
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-#include "servers/visual_server.h"
#include "camera_matrix.h"
#include "map.h"
#include "self_list.h"
+#include "servers/visual_server.h"
class Rasterizer {
protected:
@@ -1975,6 +1971,5 @@ public:
virtual ~Rasterizer() {}
};
-
#endif
#endif
diff --git a/servers/visual/shader_language.cpp b/servers/visual/shader_language.cpp
index c680013efa..3bc495f08e 100644
--- a/servers/visual/shader_language.cpp
+++ b/servers/visual/shader_language.cpp
@@ -27,69 +27,66 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "shader_language.h"
-#include "print_string.h"
#include "os/os.h"
+#include "print_string.h"
static bool _is_text_char(CharType c) {
- return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_';
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_';
}
static bool _is_number(CharType c) {
- return (c>='0' && c<='9');
+ return (c >= '0' && c <= '9');
}
static bool _is_hex(CharType c) {
- return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F');
+ return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
-
String ShaderLanguage::get_operator_text(Operator p_op) {
- static const char* op_names[OP_MAX]={"==",
- "!=",
- "<",
- "<=",
- ">",
- ">=",
- "&&",
- "||",
- "!",
- "-",
- "+",
- "-",
- "*",
- "/",
- "%",
- "<<",
- ">>",
- "=",
- "+=",
- "-=",
- "*=",
- "/=",
- "%=",
- "<<=",
- ">>=",
- "&=",
- "|=",
- "^=",
- "&",
- "|",
- "^",
- "~",
- "++"
- "--",
- "()",
- "construct"};
+ static const char *op_names[OP_MAX] = { "==",
+ "!=",
+ "<",
+ "<=",
+ ">",
+ ">=",
+ "&&",
+ "||",
+ "!",
+ "-",
+ "+",
+ "-",
+ "*",
+ "/",
+ "%",
+ "<<",
+ ">>",
+ "=",
+ "+=",
+ "-=",
+ "*=",
+ "/=",
+ "%=",
+ "<<=",
+ ">>=",
+ "&=",
+ "|=",
+ "^=",
+ "&",
+ "|",
+ "^",
+ "~",
+ "++"
+ "--",
+ "()",
+ "construct" };
return op_names[p_op];
-
}
-
-const char * ShaderLanguage::token_names[TK_MAX]={
+const char *ShaderLanguage::token_names[TK_MAX] = {
"EMPTY",
"IDENTIFIER",
"TRUE",
@@ -195,94 +192,92 @@ const char * ShaderLanguage::token_names[TK_MAX]={
String ShaderLanguage::get_token_text(Token p_token) {
- String name=token_names[p_token.type];
- if (p_token.type==TK_INT_CONSTANT || p_token.type==TK_REAL_CONSTANT) {
- name+="("+rtos(p_token.constant)+")";
- } else if (p_token.type==TK_IDENTIFIER) {
- name+="("+String(p_token.text)+")";
- } else if (p_token.type==TK_ERROR) {
- name+="("+String(p_token.text)+")";
+ String name = token_names[p_token.type];
+ if (p_token.type == TK_INT_CONSTANT || p_token.type == TK_REAL_CONSTANT) {
+ name += "(" + rtos(p_token.constant) + ")";
+ } else if (p_token.type == TK_IDENTIFIER) {
+ name += "(" + String(p_token.text) + ")";
+ } else if (p_token.type == TK_ERROR) {
+ name += "(" + String(p_token.text) + ")";
}
return name;
}
-ShaderLanguage::Token ShaderLanguage::_make_token(TokenType p_type,const StringName& p_text) {
+ShaderLanguage::Token ShaderLanguage::_make_token(TokenType p_type, const StringName &p_text) {
Token tk;
- tk.type=p_type;
- tk.text=p_text;
- tk.line=tk_line;
- if (tk.type==TK_ERROR) {
+ tk.type = p_type;
+ tk.text = p_text;
+ tk.line = tk_line;
+ if (tk.type == TK_ERROR) {
_set_error(p_text);
}
return tk;
}
-const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[]={
- {TK_TRUE,"true"},
- {TK_FALSE,"false"},
- {TK_TYPE_VOID,"void"},
- {TK_TYPE_BOOL,"bool"},
- {TK_TYPE_BVEC2,"bvec2"},
- {TK_TYPE_BVEC3,"bvec3"},
- {TK_TYPE_BVEC4,"bvec4"},
- {TK_TYPE_INT,"int"},
- {TK_TYPE_IVEC2,"ivec2"},
- {TK_TYPE_IVEC3,"ivec3"},
- {TK_TYPE_IVEC4,"ivec4"},
- {TK_TYPE_UINT,"uint"},
- {TK_TYPE_UVEC2,"uvec2"},
- {TK_TYPE_UVEC3,"uvec3"},
- {TK_TYPE_UVEC4,"uvec4"},
- {TK_TYPE_FLOAT,"float"},
- {TK_TYPE_VEC2,"vec2"},
- {TK_TYPE_VEC3,"vec3"},
- {TK_TYPE_VEC4,"vec4"},
- {TK_TYPE_MAT2,"mat2"},
- {TK_TYPE_MAT3,"mat3"},
- {TK_TYPE_MAT4,"mat4"},
- {TK_TYPE_SAMPLER2D,"sampler2D"},
- {TK_TYPE_ISAMPLER2D,"isampler2D"},
- {TK_TYPE_USAMPLER2D,"usampler2D"},
- {TK_TYPE_SAMPLERCUBE,"samplerCube"},
- {TK_PRECISION_LOW,"lowp"},
- {TK_PRECISION_MID,"mediump"},
- {TK_PRECISION_HIGH,"highp"},
- {TK_CF_IF,"if"},
- {TK_CF_ELSE,"else"},
- {TK_CF_FOR,"for"},
- {TK_CF_WHILE,"while"},
- {TK_CF_DO,"do"},
- {TK_CF_SWITCH,"switch"},
- {TK_CF_CASE,"case"},
- {TK_CF_BREAK,"break"},
- {TK_CF_CONTINUE,"continue"},
- {TK_CF_RETURN,"return"},
- {TK_UNIFORM,"uniform"},
- {TK_VARYING,"varying"},
- {TK_RENDER_MODE,"render_mode"},
- {TK_HINT_WHITE_TEXTURE,"hint_white"},
- {TK_HINT_BLACK_TEXTURE,"hint_black"},
- {TK_HINT_NORMAL_TEXTURE,"hint_normal"},
- {TK_HINT_ANISO_TEXTURE,"hint_aniso"},
- {TK_HINT_ALBEDO_TEXTURE,"hint_albedo"},
- {TK_HINT_BLACK_ALBEDO_TEXTURE,"hint_black_albedo"},
- {TK_HINT_COLOR,"hint_color"},
- {TK_HINT_RANGE,"hint_range"},
-
- {TK_ERROR,NULL}
+const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[] = {
+ { TK_TRUE, "true" },
+ { TK_FALSE, "false" },
+ { TK_TYPE_VOID, "void" },
+ { TK_TYPE_BOOL, "bool" },
+ { TK_TYPE_BVEC2, "bvec2" },
+ { TK_TYPE_BVEC3, "bvec3" },
+ { TK_TYPE_BVEC4, "bvec4" },
+ { TK_TYPE_INT, "int" },
+ { TK_TYPE_IVEC2, "ivec2" },
+ { TK_TYPE_IVEC3, "ivec3" },
+ { TK_TYPE_IVEC4, "ivec4" },
+ { TK_TYPE_UINT, "uint" },
+ { TK_TYPE_UVEC2, "uvec2" },
+ { TK_TYPE_UVEC3, "uvec3" },
+ { TK_TYPE_UVEC4, "uvec4" },
+ { TK_TYPE_FLOAT, "float" },
+ { TK_TYPE_VEC2, "vec2" },
+ { TK_TYPE_VEC3, "vec3" },
+ { TK_TYPE_VEC4, "vec4" },
+ { TK_TYPE_MAT2, "mat2" },
+ { TK_TYPE_MAT3, "mat3" },
+ { TK_TYPE_MAT4, "mat4" },
+ { TK_TYPE_SAMPLER2D, "sampler2D" },
+ { TK_TYPE_ISAMPLER2D, "isampler2D" },
+ { TK_TYPE_USAMPLER2D, "usampler2D" },
+ { TK_TYPE_SAMPLERCUBE, "samplerCube" },
+ { TK_PRECISION_LOW, "lowp" },
+ { TK_PRECISION_MID, "mediump" },
+ { TK_PRECISION_HIGH, "highp" },
+ { TK_CF_IF, "if" },
+ { TK_CF_ELSE, "else" },
+ { TK_CF_FOR, "for" },
+ { TK_CF_WHILE, "while" },
+ { TK_CF_DO, "do" },
+ { TK_CF_SWITCH, "switch" },
+ { TK_CF_CASE, "case" },
+ { TK_CF_BREAK, "break" },
+ { TK_CF_CONTINUE, "continue" },
+ { TK_CF_RETURN, "return" },
+ { TK_UNIFORM, "uniform" },
+ { TK_VARYING, "varying" },
+ { TK_RENDER_MODE, "render_mode" },
+ { TK_HINT_WHITE_TEXTURE, "hint_white" },
+ { TK_HINT_BLACK_TEXTURE, "hint_black" },
+ { TK_HINT_NORMAL_TEXTURE, "hint_normal" },
+ { TK_HINT_ANISO_TEXTURE, "hint_aniso" },
+ { TK_HINT_ALBEDO_TEXTURE, "hint_albedo" },
+ { TK_HINT_BLACK_ALBEDO_TEXTURE, "hint_black_albedo" },
+ { TK_HINT_COLOR, "hint_color" },
+ { TK_HINT_RANGE, "hint_range" },
+
+ { TK_ERROR, NULL }
};
-
-
ShaderLanguage::Token ShaderLanguage::_get_token() {
-#define GETCHAR(m_idx) (((char_idx+m_idx)<code.length())?code[char_idx+m_idx]:CharType(0))
+#define GETCHAR(m_idx) (((char_idx + m_idx) < code.length()) ? code[char_idx + m_idx] : CharType(0))
- while(true) {
+ while (true) {
char_idx++;
- switch(GETCHAR(-1)) {
+ switch (GETCHAR(-1)) {
case 0:
return _make_token(TK_EOF);
@@ -297,17 +292,18 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
continue;
case '/': {
- switch(GETCHAR(0)) {
+ switch (GETCHAR(0)) {
case '*': { // block comment
char_idx++;
- while(true) {
- if (GETCHAR(0)==0) {
+ while (true) {
+ if (GETCHAR(0) == 0) {
return _make_token(TK_EOF);
- } if (GETCHAR(0)=='*' && GETCHAR(1)=='/') {
- char_idx+=2;
+ }
+ if (GETCHAR(0) == '*' && GETCHAR(1) == '/') {
+ char_idx += 2;
break;
- } else if (GETCHAR(0)=='\n') {
+ } else if (GETCHAR(0) == '\n') {
tk_line++;
}
@@ -317,13 +313,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '/': { // line comment skip
-
- while(true) {
- if (GETCHAR(0)=='\n') {
+ while (true) {
+ if (GETCHAR(0) == '\n') {
char_idx++;
break;
}
- if (GETCHAR(0)==0) {
+ if (GETCHAR(0) == 0) {
return _make_token(TK_EOF);
}
char_idx++;
@@ -344,7 +339,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '=': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_EQUAL);
}
@@ -353,12 +348,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '<': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_LESS_EQUAL);
- } else if (GETCHAR(0)=='<') {
+ } else if (GETCHAR(0) == '<') {
char_idx++;
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_SHIFT_LEFT);
}
@@ -370,12 +365,12 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '>': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_GREATER_EQUAL);
- } else if (GETCHAR(0)=='<') {
+ } else if (GETCHAR(0) == '<') {
char_idx++;
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_SHIFT_RIGHT);
}
@@ -387,7 +382,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '!': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_NOT_EQUAL);
}
@@ -422,10 +417,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
case '~':
return _make_token(TK_OP_BIT_INVERT);
case '&': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_BIT_AND);
- } else if (GETCHAR(0)=='&') {
+ } else if (GETCHAR(0) == '&') {
char_idx++;
return _make_token(TK_OP_AND);
}
@@ -433,10 +428,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '|': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_BIT_OR);
- } else if (GETCHAR(0)=='|') {
+ } else if (GETCHAR(0) == '|') {
char_idx++;
return _make_token(TK_OP_OR);
}
@@ -445,7 +440,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '*': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_MUL);
}
@@ -453,10 +448,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '+': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_ADD);
- } else if (GETCHAR(0)=='+') {
+ } else if (GETCHAR(0) == '+') {
char_idx++;
return _make_token(TK_OP_INCREMENT);
@@ -466,10 +461,10 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '-': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_SUB);
- }else if (GETCHAR(0)=='-') {
+ } else if (GETCHAR(0) == '-') {
char_idx++;
return _make_token(TK_OP_DECREMENT);
@@ -479,7 +474,7 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
} break;
case '%': {
- if (GETCHAR(0)=='=') {
+ if (GETCHAR(0) == '=') {
char_idx++;
return _make_token(TK_OP_ASSIGN_MOD);
}
@@ -490,69 +485,68 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
char_idx--; //go back one, since we have no idea what this is
- if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) {
+ 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 sign_found=false;
- bool minus_exponent_found=false;
+ bool period_found = false;
+ bool exponent_found = false;
+ bool hexa_found = false;
+ bool sign_found = false;
+ bool minus_exponent_found = false;
String str;
- int i=0;
+ int i = 0;
- while(true) {
- if (GETCHAR(i)=='.') {
+ while (true) {
+ if (GETCHAR(i) == '.') {
if (period_found || exponent_found)
- return _make_token(TK_ERROR,"Invalid numeric constant");
- period_found=true;
- } else if (GETCHAR(i)=='x') {
- if (hexa_found || str.length()!=1 || str[0]!='0')
- return _make_token(TK_ERROR,"Invalid numeric constant");
- hexa_found=true;
- } else if (GETCHAR(i)=='e') {
+ return _make_token(TK_ERROR, "Invalid numeric constant");
+ period_found = true;
+ } else if (GETCHAR(i) == 'x') {
+ if (hexa_found || str.length() != 1 || str[0] != '0')
+ return _make_token(TK_ERROR, "Invalid numeric constant");
+ hexa_found = true;
+ } else if (GETCHAR(i) == 'e') {
if (hexa_found || exponent_found)
- return _make_token(TK_ERROR,"Invalid numeric constant");
- exponent_found=true;
+ return _make_token(TK_ERROR, "Invalid numeric constant");
+ exponent_found = true;
} else if (_is_number(GETCHAR(i))) {
//all ok
} else if (hexa_found && _is_hex(GETCHAR(i))) {
- } else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) {
+ } else if ((GETCHAR(i) == '-' || GETCHAR(i) == '+') && exponent_found) {
if (sign_found)
- return _make_token(TK_ERROR,"Invalid numeric constant");
- sign_found=true;
- if (GETCHAR(i)=='-')
- minus_exponent_found=true;
+ return _make_token(TK_ERROR, "Invalid numeric constant");
+ sign_found = true;
+ if (GETCHAR(i) == '-')
+ minus_exponent_found = true;
} else
break;
- str+=CharType(GETCHAR(i));
+ str += CharType(GETCHAR(i));
i++;
}
- if (!_is_number(str[str.length()-1]))
- return _make_token(TK_ERROR,"Invalid numeric constant");
+ if (!_is_number(str[str.length() - 1]))
+ return _make_token(TK_ERROR, "Invalid numeric constant");
- char_idx+=str.length();
+ char_idx += str.length();
Token tk;
if (period_found || minus_exponent_found)
- tk.type=TK_REAL_CONSTANT;
+ tk.type = TK_REAL_CONSTANT;
else
- tk.type=TK_INT_CONSTANT;
+ tk.type = TK_INT_CONSTANT;
if (!str.is_valid_float()) {
- return _make_token(TK_ERROR,"Invalid numeric constant");
+ return _make_token(TK_ERROR, "Invalid numeric constant");
}
- tk.constant=str.to_double();
- tk.line=tk_line;
+ tk.constant = str.to_double();
+ tk.line = tk_line;
return tk;
-
}
- if (GETCHAR(0)=='.') {
+ if (GETCHAR(0) == '.') {
//parse period
char_idx++;
return _make_token(TK_PERIOD);
@@ -562,33 +556,32 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
// parse identifier
String str;
- while(_is_text_char(GETCHAR(0))) {
+ while (_is_text_char(GETCHAR(0))) {
- str+=CharType(GETCHAR(0));
+ str += CharType(GETCHAR(0));
char_idx++;
}
//see if keyword
//should be converted to a static map
- int idx=0;
+ int idx = 0;
- while(keyword_list[idx].text) {
+ while (keyword_list[idx].text) {
- if (str==keyword_list[idx].text) {
+ if (str == keyword_list[idx].text) {
return _make_token(keyword_list[idx].token);
}
idx++;
}
-
- return _make_token(TK_IDENTIFIER,str);
+ return _make_token(TK_IDENTIFIER, str);
}
- if (GETCHAR(0)>32)
- return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0))+": '"+String::chr(GETCHAR(0))+"'");
+ if (GETCHAR(0) > 32)
+ return _make_token(TK_ERROR, "Tokenizer: Unknown character #" + itos(GETCHAR(0)) + ": '" + String::chr(GETCHAR(0)) + "'");
else
- return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0)));
+ return _make_token(TK_ERROR, "Tokenizer: Unknown character #" + itos(GETCHAR(0)));
} break;
}
@@ -597,85 +590,79 @@ ShaderLanguage::Token ShaderLanguage::_get_token() {
return Token();
}
-
-String ShaderLanguage::token_debug(const String& p_code) {
+String ShaderLanguage::token_debug(const String &p_code) {
clear();
- code=p_code;
+ code = p_code;
String output;
Token tk = _get_token();
- while(tk.type!=TK_EOF && tk.type!=TK_ERROR) {
+ while (tk.type != TK_EOF && tk.type != TK_ERROR) {
- output+=itos(tk_line)+": "+get_token_text(tk)+"\n";
+ output += itos(tk_line) + ": " + get_token_text(tk) + "\n";
tk = _get_token();
}
return output;
-
}
bool ShaderLanguage::is_token_datatype(TokenType p_type) {
return (
- p_type==TK_TYPE_VOID ||
- p_type==TK_TYPE_BOOL ||
- p_type==TK_TYPE_BVEC2 ||
- p_type==TK_TYPE_BVEC3 ||
- p_type==TK_TYPE_BVEC4 ||
- p_type==TK_TYPE_INT ||
- p_type==TK_TYPE_IVEC2 ||
- p_type==TK_TYPE_IVEC3 ||
- p_type==TK_TYPE_IVEC4 ||
- p_type==TK_TYPE_UINT ||
- p_type==TK_TYPE_UVEC2 ||
- p_type==TK_TYPE_UVEC3 ||
- p_type==TK_TYPE_UVEC4 ||
- p_type==TK_TYPE_FLOAT ||
- p_type==TK_TYPE_VEC2 ||
- p_type==TK_TYPE_VEC3 ||
- p_type==TK_TYPE_VEC4 ||
- p_type==TK_TYPE_MAT2 ||
- p_type==TK_TYPE_MAT3 ||
- p_type==TK_TYPE_MAT4 ||
- p_type==TK_TYPE_SAMPLER2D ||
- p_type==TK_TYPE_ISAMPLER2D ||
- p_type==TK_TYPE_USAMPLER2D ||
- p_type==TK_TYPE_SAMPLERCUBE );
-
+ p_type == TK_TYPE_VOID ||
+ p_type == TK_TYPE_BOOL ||
+ p_type == TK_TYPE_BVEC2 ||
+ p_type == TK_TYPE_BVEC3 ||
+ p_type == TK_TYPE_BVEC4 ||
+ p_type == TK_TYPE_INT ||
+ p_type == TK_TYPE_IVEC2 ||
+ p_type == TK_TYPE_IVEC3 ||
+ p_type == TK_TYPE_IVEC4 ||
+ p_type == TK_TYPE_UINT ||
+ p_type == TK_TYPE_UVEC2 ||
+ p_type == TK_TYPE_UVEC3 ||
+ p_type == TK_TYPE_UVEC4 ||
+ p_type == TK_TYPE_FLOAT ||
+ p_type == TK_TYPE_VEC2 ||
+ p_type == TK_TYPE_VEC3 ||
+ p_type == TK_TYPE_VEC4 ||
+ p_type == TK_TYPE_MAT2 ||
+ p_type == TK_TYPE_MAT3 ||
+ p_type == TK_TYPE_MAT4 ||
+ p_type == TK_TYPE_SAMPLER2D ||
+ p_type == TK_TYPE_ISAMPLER2D ||
+ p_type == TK_TYPE_USAMPLER2D ||
+ p_type == TK_TYPE_SAMPLERCUBE);
}
ShaderLanguage::DataType ShaderLanguage::get_token_datatype(TokenType p_type) {
- return DataType(p_type-TK_TYPE_VOID);
+ return DataType(p_type - TK_TYPE_VOID);
}
-
bool ShaderLanguage::is_token_precision(TokenType p_type) {
return (
- p_type==TK_PRECISION_LOW ||
- p_type==TK_PRECISION_MID ||
- p_type==TK_PRECISION_HIGH );
-
+ p_type == TK_PRECISION_LOW ||
+ p_type == TK_PRECISION_MID ||
+ p_type == TK_PRECISION_HIGH);
}
ShaderLanguage::DataPrecision ShaderLanguage::get_token_precision(TokenType p_type) {
- if (p_type==TK_PRECISION_LOW)
+ if (p_type == TK_PRECISION_LOW)
return PRECISION_LOWP;
- else if (p_type==TK_PRECISION_HIGH)
+ else if (p_type == TK_PRECISION_HIGH)
return PRECISION_HIGHP;
else
return PRECISION_MEDIUMP;
}
-
String ShaderLanguage::get_datatype_name(DataType p_type) {
- switch(p_type) {
+ switch (p_type) {
case TYPE_VOID: return "void";
case TYPE_BOOL: return "bool";
@@ -706,83 +693,77 @@ String ShaderLanguage::get_datatype_name(DataType p_type) {
return "";
}
-
bool ShaderLanguage::is_token_nonvoid_datatype(TokenType p_type) {
- return is_token_datatype(p_type) && p_type!=TK_TYPE_VOID;
-
+ return is_token_datatype(p_type) && p_type != TK_TYPE_VOID;
}
-
void ShaderLanguage::clear() {
- current_function=StringName();
+ current_function = StringName();
- completion_type=COMPLETION_NONE;
- completion_block=NULL;
- completion_function=StringName();
+ completion_type = COMPLETION_NONE;
+ completion_block = NULL;
+ completion_function = StringName();
- error_line=0;
- tk_line=1;
- char_idx=0;
- error_set=false;
- error_str="";
- while(nodes) {
+ error_line = 0;
+ tk_line = 1;
+ char_idx = 0;
+ error_set = false;
+ error_str = "";
+ while (nodes) {
Node *n = nodes;
- nodes=nodes->next;
+ nodes = nodes->next;
memdelete(n);
}
-
}
-
-bool ShaderLanguage::_find_identifier(const BlockNode* p_block,const Map<StringName, DataType> &p_builtin_types,const StringName& p_identifier, DataType *r_data_type, IdentifierType *r_type) {
-
+bool ShaderLanguage::_find_identifier(const BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, const StringName &p_identifier, DataType *r_data_type, IdentifierType *r_type) {
if (p_builtin_types.has(p_identifier)) {
if (r_data_type) {
- *r_data_type=p_builtin_types[p_identifier];
+ *r_data_type = p_builtin_types[p_identifier];
}
if (r_type) {
- *r_type=IDENTIFIER_BUILTIN_VAR;
+ *r_type = IDENTIFIER_BUILTIN_VAR;
}
return true;
}
- FunctionNode *function=NULL;
+ FunctionNode *function = NULL;
- while(p_block) {
+ while (p_block) {
if (p_block->variables.has(p_identifier)) {
if (r_data_type) {
- *r_data_type=p_block->variables[p_identifier].type;
+ *r_data_type = p_block->variables[p_identifier].type;
}
if (r_type) {
- *r_type=IDENTIFIER_LOCAL_VAR;
+ *r_type = IDENTIFIER_LOCAL_VAR;
}
return true;
}
if (p_block->parent_function) {
- function=p_block->parent_function;
+ function = p_block->parent_function;
break;
} else {
- ERR_FAIL_COND_V(!p_block->parent_block,false);
- p_block=p_block->parent_block;
+ ERR_FAIL_COND_V(!p_block->parent_block, false);
+ p_block = p_block->parent_block;
}
}
if (function) {
- for(int i=0;i<function->arguments.size();i++) {
- if (function->arguments[i].name==p_identifier) {
+ for (int i = 0; i < function->arguments.size(); i++) {
+ if (function->arguments[i].name == p_identifier) {
if (r_data_type) {
- *r_data_type=function->arguments[i].type;
+ *r_data_type = function->arguments[i].type;
}
if (r_type) {
- *r_type=IDENTIFIER_FUNCTION_ARGUMENT;
+ *r_type = IDENTIFIER_FUNCTION_ARGUMENT;
}
return true;
@@ -790,59 +771,56 @@ bool ShaderLanguage::_find_identifier(const BlockNode* p_block,const Map<StringN
}
}
-
if (shader->varyings.has(p_identifier)) {
if (r_data_type) {
- *r_data_type=shader->varyings[p_identifier].type;
+ *r_data_type = shader->varyings[p_identifier].type;
}
if (r_type) {
- *r_type=IDENTIFIER_VARYING;
+ *r_type = IDENTIFIER_VARYING;
}
return true;
}
if (shader->uniforms.has(p_identifier)) {
if (r_data_type) {
- *r_data_type=shader->uniforms[p_identifier].type;
+ *r_data_type = shader->uniforms[p_identifier].type;
}
if (r_type) {
- *r_type=IDENTIFIER_UNIFORM;
+ *r_type = IDENTIFIER_UNIFORM;
}
return true;
}
- for(int i=0;i<shader->functions.size();i++) {
+ for (int i = 0; i < shader->functions.size(); i++) {
if (!shader->functions[i].callable)
continue;
- if (shader->functions[i].name==p_identifier) {
+ if (shader->functions[i].name == p_identifier) {
if (r_data_type) {
- *r_data_type=shader->functions[i].function->return_type;
+ *r_data_type = shader->functions[i].function->return_type;
}
if (r_type) {
- *r_type=IDENTIFIER_FUNCTION;
+ *r_type = IDENTIFIER_FUNCTION;
}
}
}
return false;
-
}
+bool ShaderLanguage::_validate_operator(OperatorNode *p_op, DataType *r_ret_type) {
-bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) {
-
- bool valid=false;
+ bool valid = false;
DataType ret_type;
- switch(p_op->op) {
+ switch (p_op->op) {
case OP_EQUAL:
case OP_NOT_EQUAL: {
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- valid=na==nb;
- ret_type=TYPE_BOOL;
+ valid = na == nb;
+ ret_type = TYPE_BOOL;
} break;
case OP_LESS:
case OP_LESS_EQUAL:
@@ -851,8 +829,8 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- valid = na==nb && (na==TYPE_UINT || na==TYPE_INT || na==TYPE_FLOAT);
- ret_type=TYPE_BOOL;
+ valid = na == nb && (na == TYPE_UINT || na == TYPE_INT || na == TYPE_FLOAT);
+ ret_type = TYPE_BOOL;
} break;
case OP_AND:
@@ -860,15 +838,15 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- valid = na==nb && na==TYPE_BOOL;
- ret_type=TYPE_BOOL;
+ valid = na == nb && na == TYPE_BOOL;
+ ret_type = TYPE_BOOL;
} break;
case OP_NOT: {
DataType na = p_op->arguments[0]->get_datatype();
- valid = na==TYPE_BOOL;
- ret_type=TYPE_BOOL;
+ valid = na == TYPE_BOOL;
+ ret_type = TYPE_BOOL;
} break;
case OP_INCREMENT:
@@ -877,8 +855,8 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
case OP_POST_DECREMENT:
case OP_NEGATE: {
DataType na = p_op->arguments[0]->get_datatype();
- valid = na>TYPE_BOOL && na<TYPE_MAT2;
- ret_type=na;
+ valid = na > TYPE_BOOL && na < TYPE_MAT2;
+ ret_type = na;
} break;
case OP_ADD:
case OP_SUB:
@@ -887,50 +865,50 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- if (na>nb) {
+ if (na > nb) {
//make things easier;
- SWAP(na,nb);
- }
-
- if (na==nb) {
- valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4);
- ret_type=na;
- } else if (na==TYPE_INT && nb==TYPE_IVEC2) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_INT && nb==TYPE_IVEC3) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_INT && nb==TYPE_IVEC4) {
- valid=true;
- ret_type=TYPE_IVEC4;
- } else if (na==TYPE_UINT && nb==TYPE_UVEC2) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UINT && nb==TYPE_UVEC3) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UINT && nb==TYPE_UVEC4) {
- valid=true;
- ret_type=TYPE_UVEC4;
- } else if (na==TYPE_FLOAT && nb==TYPE_VEC2) {
- valid=true;
- ret_type=TYPE_VEC2;
- } else if (na==TYPE_FLOAT && nb==TYPE_VEC3) {
- valid=true;
- ret_type=TYPE_VEC3;
- } else if (na==TYPE_FLOAT && nb==TYPE_VEC4) {
- valid=true;
- ret_type=TYPE_VEC4;
- } else if (p_op->op==OP_MUL && na==TYPE_VEC2 && nb==TYPE_MAT2) {
- valid=true;
- ret_type=TYPE_MAT2;
- } else if (p_op->op==OP_MUL && na==TYPE_VEC3 && nb==TYPE_MAT3) {
- valid=true;
- ret_type=TYPE_MAT3;
- } else if (p_op->op==OP_MUL && na==TYPE_VEC4 && nb==TYPE_MAT4) {
- valid=true;
- ret_type=TYPE_MAT4;
+ SWAP(na, nb);
+ }
+
+ if (na == nb) {
+ valid = (na > TYPE_BOOL && na < TYPE_MAT2) || (p_op->op == OP_MUL && na >= TYPE_MAT2 && na <= TYPE_MAT4);
+ ret_type = na;
+ } else if (na == TYPE_INT && nb == TYPE_IVEC2) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_INT && nb == TYPE_IVEC3) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_INT && nb == TYPE_IVEC4) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ } else if (na == TYPE_UINT && nb == TYPE_UVEC2) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UINT && nb == TYPE_UVEC3) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UINT && nb == TYPE_UVEC4) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
+ } else if (na == TYPE_FLOAT && nb == TYPE_VEC2) {
+ valid = true;
+ ret_type = TYPE_VEC2;
+ } else if (na == TYPE_FLOAT && nb == TYPE_VEC3) {
+ valid = true;
+ ret_type = TYPE_VEC3;
+ } else if (na == TYPE_FLOAT && nb == TYPE_VEC4) {
+ valid = true;
+ ret_type = TYPE_VEC4;
+ } else if (p_op->op == OP_MUL && na == TYPE_VEC2 && nb == TYPE_MAT2) {
+ valid = true;
+ ret_type = TYPE_MAT2;
+ } else if (p_op->op == OP_MUL && na == TYPE_VEC3 && nb == TYPE_MAT3) {
+ valid = true;
+ ret_type = TYPE_MAT3;
+ } else if (p_op->op == OP_MUL && na == TYPE_VEC4 && nb == TYPE_MAT4) {
+ valid = true;
+ ret_type = TYPE_MAT4;
}
} break;
case OP_ASSIGN_MOD:
@@ -946,50 +924,49 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
-
- if (na==TYPE_INT && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_INT;
- } else if (na==TYPE_IVEC2 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC4;
- } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) {
- valid=true;
- ret_type=TYPE_IVEC4;
- /////
- } else if (na==TYPE_UINT && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UINT;
- } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC4;
- } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) {
- valid=true;
- ret_type=TYPE_UVEC4;
+ if (na == TYPE_INT && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_INT;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ /////
+ } else if (na == TYPE_UINT && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UINT;
+ } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
+ } else if (na == TYPE_UVEC2 && nb == TYPE_UVEC2) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UVEC3 && nb == TYPE_UVEC3) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UVEC4 && nb == TYPE_UVEC4) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
}
} break;
case OP_ASSIGN_SHIFT_LEFT:
@@ -1000,42 +977,42 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- if (na>=TYPE_UINT && na<=TYPE_UVEC4) {
- na=DataType(na-4);
- }
-
- if (nb>=TYPE_UINT && nb<=TYPE_UVEC4) {
- nb=DataType(nb-4);
- }
-
- if (na==TYPE_INT && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_INT;
- } else if (na==TYPE_IVEC2 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC4;
- } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) {
- valid=true;
- ret_type=TYPE_IVEC4;
+ if (na >= TYPE_UINT && na <= TYPE_UVEC4) {
+ na = DataType(na - 4);
+ }
+
+ if (nb >= TYPE_UINT && nb <= TYPE_UVEC4) {
+ nb = DataType(nb - 4);
+ }
+
+ if (na == TYPE_INT && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_INT;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
}
} break;
case OP_ASSIGN: {
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- valid=na==nb;
- ret_type=na;
+ valid = na == nb;
+ ret_type = na;
} break;
case OP_ASSIGN_ADD:
case OP_ASSIGN_SUB:
@@ -1045,46 +1022,45 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
-
- if (na==nb) {
- valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_ASSIGN_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4);
- ret_type=na;
- } else if (na==TYPE_IVEC2 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_INT ) {
- valid=true;
- ret_type=TYPE_IVEC4;
- } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC4;
- } else if (na==TYPE_VEC2 && nb==TYPE_FLOAT ) {
- valid=true;
- ret_type=TYPE_VEC2;
- } else if (na==TYPE_VEC3 && nb==TYPE_FLOAT) {
- valid=true;
- ret_type=TYPE_VEC3;
- } else if (na==TYPE_VEC4 && nb==TYPE_FLOAT) {
- valid=true;
- ret_type=TYPE_VEC4;
- } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT2 && nb==TYPE_VEC2) {
- valid=true;
- ret_type=TYPE_MAT2;
- } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT3 && nb==TYPE_VEC3) {
- valid=true;
- ret_type=TYPE_MAT3;
- } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT4 && nb==TYPE_VEC4) {
- valid=true;
- ret_type=TYPE_MAT4;
+ if (na == nb) {
+ valid = (na > TYPE_BOOL && na < TYPE_MAT2) || (p_op->op == OP_ASSIGN_MUL && na >= TYPE_MAT2 && na <= TYPE_MAT4);
+ ret_type = na;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
+ } else if (na == TYPE_VEC2 && nb == TYPE_FLOAT) {
+ valid = true;
+ ret_type = TYPE_VEC2;
+ } else if (na == TYPE_VEC3 && nb == TYPE_FLOAT) {
+ valid = true;
+ ret_type = TYPE_VEC3;
+ } else if (na == TYPE_VEC4 && nb == TYPE_FLOAT) {
+ valid = true;
+ ret_type = TYPE_VEC4;
+ } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT2 && nb == TYPE_VEC2) {
+ valid = true;
+ ret_type = TYPE_MAT2;
+ } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT3 && nb == TYPE_VEC3) {
+ valid = true;
+ ret_type = TYPE_MAT3;
+ } else if (p_op->op == OP_ASSIGN_MUL && na == TYPE_MAT4 && nb == TYPE_VEC4) {
+ valid = true;
+ ret_type = TYPE_MAT4;
}
} break;
case OP_ASSIGN_BIT_AND:
@@ -1105,68 +1081,68 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
- if (na>nb && p_op->op>=OP_BIT_AND) {
+ if (na > nb && p_op->op >= OP_BIT_AND) {
//can swap for non assign
- SWAP(na,nb);
- }
-
- if (na==TYPE_INT && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_INT;
- } else if (na==TYPE_IVEC2 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_INT) {
- valid=true;
- ret_type=TYPE_IVEC4;
- } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) {
- valid=true;
- ret_type=TYPE_IVEC2;
- } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) {
- valid=true;
- ret_type=TYPE_IVEC3;
- } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) {
- valid=true;
- ret_type=TYPE_IVEC4;
- /////
- } else if (na==TYPE_UINT && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UINT;
- } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) {
- valid=true;
- ret_type=TYPE_UVEC4;
- } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) {
- valid=true;
- ret_type=TYPE_UVEC2;
- } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) {
- valid=true;
- ret_type=TYPE_UVEC3;
- } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) {
- valid=true;
- ret_type=TYPE_UVEC4;
+ SWAP(na, nb);
+ }
+
+ if (na == TYPE_INT && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_INT;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_INT) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ } else if (na == TYPE_IVEC2 && nb == TYPE_IVEC2) {
+ valid = true;
+ ret_type = TYPE_IVEC2;
+ } else if (na == TYPE_IVEC3 && nb == TYPE_IVEC3) {
+ valid = true;
+ ret_type = TYPE_IVEC3;
+ } else if (na == TYPE_IVEC4 && nb == TYPE_IVEC4) {
+ valid = true;
+ ret_type = TYPE_IVEC4;
+ /////
+ } else if (na == TYPE_UINT && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UINT;
+ } else if (na == TYPE_UVEC2 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UVEC3 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UVEC4 && nb == TYPE_UINT) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
+ } else if (na == TYPE_UVEC2 && nb == TYPE_UVEC2) {
+ valid = true;
+ ret_type = TYPE_UVEC2;
+ } else if (na == TYPE_UVEC3 && nb == TYPE_UVEC3) {
+ valid = true;
+ ret_type = TYPE_UVEC3;
+ } else if (na == TYPE_UVEC4 && nb == TYPE_UVEC4) {
+ valid = true;
+ ret_type = TYPE_UVEC4;
}
} break;
case OP_BIT_INVERT: { //unaries
DataType na = p_op->arguments[0]->get_datatype();
- valid = na>=TYPE_INT && na<TYPE_FLOAT;
- ret_type=na;
+ valid = na >= TYPE_INT && na < TYPE_FLOAT;
+ ret_type = na;
} break;
case OP_SELECT_IF: {
DataType na = p_op->arguments[0]->get_datatype();
DataType nb = p_op->arguments[1]->get_datatype();
DataType nc = p_op->arguments[2]->get_datatype();
- valid = na==TYPE_BOOL && (nb==nc);
- ret_type=nb;
+ valid = na == TYPE_BOOL && (nb == nc);
+ ret_type = nb;
} break;
default: {
ERR_FAIL_V(false);
@@ -1174,653 +1150,640 @@ bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type)
}
if (r_ret_type)
- *r_ret_type=ret_type;
+ *r_ret_type = ret_type;
return valid;
-
}
-const ShaderLanguage::BuiltinFuncDef ShaderLanguage::builtin_func_defs[]={
+const ShaderLanguage::BuiltinFuncDef ShaderLanguage::builtin_func_defs[] = {
//constructors
- {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}},
- {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_VOID}},
- {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_BOOL,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC3,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BVEC3,TYPE_BOOL,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}},
-
-
- {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_VOID}},
- {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
-
- {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}},
- {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_VOID}},
- {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_IVEC2,TYPE_INT,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_IVEC2,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC2,TYPE_INT,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_IVEC2,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC3,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_IVEC3,TYPE_INT,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
-
- {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}},
- {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_VOID}},
- {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_UVEC2,TYPE_UINT,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UVEC2,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC2,TYPE_UINT,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UVEC2,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC3,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UVEC3,TYPE_UINT,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
-
- {"mat2",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"mat3",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"mat4",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"mat2",TYPE_MAT2,{TYPE_FLOAT,TYPE_VOID}},
- {"mat3",TYPE_MAT3,{TYPE_FLOAT,TYPE_VOID}},
- {"mat4",TYPE_MAT4,{TYPE_FLOAT,TYPE_VOID}},
+ { "bool", TYPE_BOOL, { TYPE_BOOL, TYPE_VOID } },
+ { "bvec2", TYPE_BVEC2, { TYPE_BOOL, TYPE_VOID } },
+ { "bvec2", TYPE_BVEC2, { TYPE_BOOL, TYPE_BOOL, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_BVEC2, TYPE_BOOL, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_BOOL, TYPE_BVEC2, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BVEC2, TYPE_BOOL, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BVEC2, TYPE_BOOL, TYPE_BOOL, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BOOL, TYPE_BVEC2, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BOOL, TYPE_BVEC3, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BVEC3, TYPE_BOOL, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } },
+
+ { "float", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "vec2", TYPE_VEC2, { TYPE_FLOAT, TYPE_VOID } },
+ { "vec2", TYPE_VEC2, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_VEC2, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+
+ { "int", TYPE_INT, { TYPE_INT, TYPE_VOID } },
+ { "ivec2", TYPE_IVEC2, { TYPE_INT, TYPE_VOID } },
+ { "ivec2", TYPE_IVEC2, { TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_IVEC2, TYPE_INT, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_INT, TYPE_IVEC2, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_IVEC2, TYPE_INT, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_IVEC2, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_INT, TYPE_IVEC2, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_INT, TYPE_IVEC3, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_IVEC3, TYPE_INT, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+
+ { "uint", TYPE_UINT, { TYPE_UINT, TYPE_VOID } },
+ { "uvec2", TYPE_UVEC2, { TYPE_UINT, TYPE_VOID } },
+ { "uvec2", TYPE_UVEC2, { TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_UVEC2, TYPE_UINT, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_UINT, TYPE_UVEC2, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UVEC2, TYPE_UINT, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UVEC2, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UINT, TYPE_UVEC2, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UINT, TYPE_UVEC3, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UVEC3, TYPE_UINT, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+
+ { "mat2", TYPE_MAT2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "mat3", TYPE_MAT3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "mat4", TYPE_MAT4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "mat2", TYPE_MAT2, { TYPE_FLOAT, TYPE_VOID } },
+ { "mat3", TYPE_MAT3, { TYPE_FLOAT, TYPE_VOID } },
+ { "mat4", TYPE_MAT4, { TYPE_FLOAT, TYPE_VOID } },
//conversion scalars
- {"int",TYPE_INT,{TYPE_BOOL,TYPE_VOID}},
- {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}},
- {"int",TYPE_INT,{TYPE_UINT,TYPE_VOID}},
- {"int",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}},
+ { "int", TYPE_INT, { TYPE_BOOL, TYPE_VOID } },
+ { "int", TYPE_INT, { TYPE_INT, TYPE_VOID } },
+ { "int", TYPE_INT, { TYPE_UINT, TYPE_VOID } },
+ { "int", TYPE_INT, { TYPE_FLOAT, TYPE_VOID } },
- {"float",TYPE_FLOAT,{TYPE_BOOL,TYPE_VOID}},
- {"float",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}},
- {"float",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}},
- {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
+ { "float", TYPE_FLOAT, { TYPE_BOOL, TYPE_VOID } },
+ { "float", TYPE_FLOAT, { TYPE_INT, TYPE_VOID } },
+ { "float", TYPE_FLOAT, { TYPE_UINT, TYPE_VOID } },
+ { "float", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
- {"uint",TYPE_UINT,{TYPE_BOOL,TYPE_VOID}},
- {"uint",TYPE_UINT,{TYPE_INT,TYPE_VOID}},
- {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}},
- {"uint",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}},
+ { "uint", TYPE_UINT, { TYPE_BOOL, TYPE_VOID } },
+ { "uint", TYPE_UINT, { TYPE_INT, TYPE_VOID } },
+ { "uint", TYPE_UINT, { TYPE_UINT, TYPE_VOID } },
+ { "uint", TYPE_UINT, { TYPE_FLOAT, TYPE_VOID } },
- {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}},
- {"bool",TYPE_BOOL,{TYPE_INT,TYPE_VOID}},
- {"bool",TYPE_BOOL,{TYPE_UINT,TYPE_VOID}},
- {"bool",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}},
+ { "bool", TYPE_BOOL, { TYPE_BOOL, TYPE_VOID } },
+ { "bool", TYPE_BOOL, { TYPE_INT, TYPE_VOID } },
+ { "bool", TYPE_BOOL, { TYPE_UINT, TYPE_VOID } },
+ { "bool", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } },
//conversion vectors
- {"ivec2",TYPE_IVEC2,{TYPE_BVEC2,TYPE_VOID}},
- {"ivec2",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"ivec2",TYPE_IVEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"ivec2",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}},
-
- {"vec2",TYPE_VEC2,{TYPE_BVEC2,TYPE_VOID}},
- {"vec2",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"vec2",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"vec2",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
-
- {"uvec2",TYPE_UVEC2,{TYPE_BVEC2,TYPE_VOID}},
- {"uvec2",TYPE_UVEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"uvec2",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"uvec2",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}},
-
- {"bvec2",TYPE_BVEC2,{TYPE_BVEC2,TYPE_VOID}},
- {"bvec2",TYPE_BVEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"bvec2",TYPE_BVEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"bvec2",TYPE_BVEC2,{TYPE_VEC2,TYPE_VOID}},
-
- {"ivec3",TYPE_IVEC3,{TYPE_BVEC3,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"ivec3",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}},
-
- {"vec3",TYPE_VEC3,{TYPE_BVEC3,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"vec3",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
-
- {"uvec3",TYPE_UVEC3,{TYPE_BVEC3,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"uvec3",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}},
-
- {"bvec3",TYPE_BVEC3,{TYPE_BVEC3,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"bvec3",TYPE_BVEC3,{TYPE_VEC3,TYPE_VOID}},
-
- {"ivec4",TYPE_IVEC4,{TYPE_BVEC4,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_UVEC4,TYPE_VOID}},
- {"ivec4",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"vec4",TYPE_VEC4,{TYPE_BVEC4,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}},
- {"vec4",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"uvec4",TYPE_UVEC4,{TYPE_BVEC4,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_IVEC4,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}},
- {"uvec4",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"bvec4",TYPE_BVEC4,{TYPE_BVEC4,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_IVEC4,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_UVEC4,TYPE_VOID}},
- {"bvec4",TYPE_BVEC4,{TYPE_VEC4,TYPE_VOID}},
+ { "ivec2", TYPE_IVEC2, { TYPE_BVEC2, TYPE_VOID } },
+ { "ivec2", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "ivec2", TYPE_IVEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "ivec2", TYPE_IVEC2, { TYPE_VEC2, TYPE_VOID } },
+
+ { "vec2", TYPE_VEC2, { TYPE_BVEC2, TYPE_VOID } },
+ { "vec2", TYPE_VEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "vec2", TYPE_VEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "vec2", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+
+ { "uvec2", TYPE_UVEC2, { TYPE_BVEC2, TYPE_VOID } },
+ { "uvec2", TYPE_UVEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "uvec2", TYPE_UVEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "uvec2", TYPE_UVEC2, { TYPE_VEC2, TYPE_VOID } },
+
+ { "bvec2", TYPE_BVEC2, { TYPE_BVEC2, TYPE_VOID } },
+ { "bvec2", TYPE_BVEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "bvec2", TYPE_BVEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "bvec2", TYPE_BVEC2, { TYPE_VEC2, TYPE_VOID } },
+
+ { "ivec3", TYPE_IVEC3, { TYPE_BVEC3, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "ivec3", TYPE_IVEC3, { TYPE_VEC3, TYPE_VOID } },
+
+ { "vec3", TYPE_VEC3, { TYPE_BVEC3, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "vec3", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+
+ { "uvec3", TYPE_UVEC3, { TYPE_BVEC3, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "uvec3", TYPE_UVEC3, { TYPE_VEC3, TYPE_VOID } },
+
+ { "bvec3", TYPE_BVEC3, { TYPE_BVEC3, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "bvec3", TYPE_BVEC3, { TYPE_VEC3, TYPE_VOID } },
+
+ { "ivec4", TYPE_IVEC4, { TYPE_BVEC4, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_UVEC4, TYPE_VOID } },
+ { "ivec4", TYPE_IVEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "vec4", TYPE_VEC4, { TYPE_BVEC4, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_IVEC4, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_UVEC4, TYPE_VOID } },
+ { "vec4", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "uvec4", TYPE_UVEC4, { TYPE_BVEC4, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_IVEC4, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_UVEC4, TYPE_VOID } },
+ { "uvec4", TYPE_UVEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "bvec4", TYPE_BVEC4, { TYPE_BVEC4, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_IVEC4, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_UVEC4, TYPE_VOID } },
+ { "bvec4", TYPE_BVEC4, { TYPE_VEC4, TYPE_VOID } },
//builtins - trigonometry
- {"sin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"cos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"tan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"asin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"acos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"atan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"atan2",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"sinh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"cosh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"tanh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
+ { "sin", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "cos", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "tan", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "asin", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "acos", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "atan", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "atan2", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "sinh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "cosh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "tanh", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
//builtins - exponential
- {"pow",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
- {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"exp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"exp",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"exp",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"exp",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"log",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"log",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"log",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"log",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"sqrt",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"sqrt",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"sqrt",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"sqrt",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
+ { "pow", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "pow", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "pow", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "pow", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "pow", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "pow", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+ { "pow", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "exp", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "exp", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "exp", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "exp", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "log", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "log", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "log", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "log", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "sqrt", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "sqrt", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "sqrt", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "sqrt", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
//builtins - common
- {"abs",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"abs",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"abs",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"abs",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"abs",TYPE_INT,{TYPE_INT,TYPE_VOID}},
- {"abs",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"abs",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"abs",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}},
-
- {"abs",TYPE_UINT,{TYPE_UINT,TYPE_VOID}},
- {"abs",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"abs",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"abs",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}},
-
-
- {"sign",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"sign",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"sign",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"sign",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"sign",TYPE_INT,{TYPE_INT,TYPE_VOID}},
- {"sign",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"sign",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"sign",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}},
-
-
- {"floor",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"floor",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"floor",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"floor",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"trunc",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"trunc",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"trunc",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"trunc",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"round",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"round",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"round",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"round",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"ceil",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"ceil",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"ceil",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"ceil",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"fract",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"fract",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"fract",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"fract",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"mod",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"modf",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"modf",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"modf",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"modf",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"min",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"min",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"min",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"min",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"min",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"min",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"min",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"min",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"min",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"min",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"min",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"min",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"max",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"max",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"max",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"max",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"max",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"max",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"max",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"max",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"max",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"max",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"max",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"max",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
-
- {"clamp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
-
-
- {"clamp",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
- {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_INT,TYPE_INT,TYPE_VOID}},
- {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_INT,TYPE_INT,TYPE_VOID}},
-
- {"clamp",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
- {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
- {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UINT,TYPE_UINT,TYPE_VOID}},
-
- {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_BOOL,TYPE_VOID}},
- {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BOOL,TYPE_VOID}},
- {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BVEC2,TYPE_VOID}},
- {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BOOL,TYPE_VOID}},
- {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BVEC3,TYPE_VOID}},
- {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
- {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BOOL,TYPE_VOID}},
- {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BVEC3,TYPE_VOID}},
- {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"step",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"step",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"step",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"step",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"step",TYPE_VEC2,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}},
- {"step",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}},
- {"step",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}},
- {"smoothstep",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}},
- {"smoothstep",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"smoothstep",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"smoothstep",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"smoothstep",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}},
- {"smoothstep",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}},
- {"smoothstep",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}},
-
- {"isnan",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}},
- {"isnan",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}},
- {"isnan",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}},
- {"isnan",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}},
-
- {"isinf",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}},
- {"isinf",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}},
- {"isinf",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}},
- {"isinf",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}},
-
- {"floatBitsToInt",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}},
- {"floatBitsToInt",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}},
- {"floatBitsToInt",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}},
- {"floatBitsToInt",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"floatBitsToUInt",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}},
- {"floatBitsToUInt",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}},
- {"floatBitsToUInt",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}},
- {"floatBitsToUInt",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"intBitsToFloat",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}},
- {"intBitsToFloat",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}},
- {"intBitsToFloat",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}},
- {"intBitsToFloat",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}},
-
- {"uintBitsToFloat",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}},
- {"uintBitsToFloat",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}},
- {"uintBitsToFloat",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}},
- {"uintBitsToFloat",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}},
+ { "abs", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "abs", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "abs", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "abs", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "abs", TYPE_INT, { TYPE_INT, TYPE_VOID } },
+ { "abs", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "abs", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "abs", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } },
+
+ { "abs", TYPE_UINT, { TYPE_UINT, TYPE_VOID } },
+ { "abs", TYPE_UVEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "abs", TYPE_UVEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "abs", TYPE_UVEC4, { TYPE_UVEC4, TYPE_VOID } },
+
+ { "sign", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "sign", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "sign", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "sign", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "sign", TYPE_INT, { TYPE_INT, TYPE_VOID } },
+ { "sign", TYPE_IVEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "sign", TYPE_IVEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "sign", TYPE_IVEC4, { TYPE_IVEC4, TYPE_VOID } },
+
+ { "floor", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "floor", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "floor", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "floor", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "trunc", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "trunc", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "trunc", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "trunc", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "round", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "round", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "round", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "round", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "ceil", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "ceil", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "ceil", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "ceil", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "fract", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "fract", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "fract", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "fract", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "mod", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "mod", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "mod", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "mod", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "mod", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "mod", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "mod", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "modf", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "modf", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "modf", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "modf", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "min", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "min", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "min", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "min", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "min", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "min", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "min", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "min", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "min", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "min", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "min", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "min", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "max", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "max", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "max", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "max", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "max", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "max", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "max", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "max", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "max", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "max", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "max", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "max", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "clamp", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "clamp", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "clamp", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "clamp", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "clamp", TYPE_VEC2, { TYPE_VEC2, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "clamp", TYPE_VEC3, { TYPE_VEC3, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "clamp", TYPE_VEC4, { TYPE_VEC4, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+
+ { "clamp", TYPE_INT, { TYPE_INT, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "clamp", TYPE_IVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "clamp", TYPE_IVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "clamp", TYPE_IVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+ { "clamp", TYPE_IVEC2, { TYPE_IVEC2, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "clamp", TYPE_IVEC3, { TYPE_IVEC3, TYPE_INT, TYPE_INT, TYPE_VOID } },
+ { "clamp", TYPE_IVEC4, { TYPE_IVEC4, TYPE_INT, TYPE_INT, TYPE_VOID } },
+
+ { "clamp", TYPE_UINT, { TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "clamp", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "clamp", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "clamp", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+ { "clamp", TYPE_UVEC2, { TYPE_UVEC2, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "clamp", TYPE_UVEC3, { TYPE_UVEC3, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+ { "clamp", TYPE_UVEC4, { TYPE_UVEC4, TYPE_UINT, TYPE_UINT, TYPE_VOID } },
+
+ { "mix", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "mix", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_BOOL, TYPE_VOID } },
+ { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_BOOL, TYPE_VOID } },
+ { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_BVEC2, TYPE_VOID } },
+ { "mix", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_BOOL, TYPE_VOID } },
+ { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_BVEC3, TYPE_VOID } },
+ { "mix", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+ { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_BOOL, TYPE_VOID } },
+ { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_BVEC3, TYPE_VOID } },
+ { "mix", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "step", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "step", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "step", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "step", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "step", TYPE_VEC2, { TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } },
+ { "step", TYPE_VEC3, { TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } },
+ { "step", TYPE_VEC4, { TYPE_FLOAT, TYPE_VEC4, TYPE_VOID } },
+ { "smoothstep", TYPE_FLOAT, { TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC2, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC2, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC3, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC3, TYPE_VOID } },
+ { "smoothstep", TYPE_VEC4, { TYPE_FLOAT, TYPE_FLOAT, TYPE_VEC4, TYPE_VOID } },
+
+ { "isnan", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } },
+ { "isnan", TYPE_BOOL, { TYPE_VEC2, TYPE_VOID } },
+ { "isnan", TYPE_BOOL, { TYPE_VEC3, TYPE_VOID } },
+ { "isnan", TYPE_BOOL, { TYPE_VEC4, TYPE_VOID } },
+
+ { "isinf", TYPE_BOOL, { TYPE_FLOAT, TYPE_VOID } },
+ { "isinf", TYPE_BOOL, { TYPE_VEC2, TYPE_VOID } },
+ { "isinf", TYPE_BOOL, { TYPE_VEC3, TYPE_VOID } },
+ { "isinf", TYPE_BOOL, { TYPE_VEC4, TYPE_VOID } },
+
+ { "floatBitsToInt", TYPE_INT, { TYPE_FLOAT, TYPE_VOID } },
+ { "floatBitsToInt", TYPE_IVEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "floatBitsToInt", TYPE_IVEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "floatBitsToInt", TYPE_IVEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "floatBitsToUInt", TYPE_UINT, { TYPE_FLOAT, TYPE_VOID } },
+ { "floatBitsToUInt", TYPE_UVEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "floatBitsToUInt", TYPE_UVEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "floatBitsToUInt", TYPE_UVEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "intBitsToFloat", TYPE_FLOAT, { TYPE_INT, TYPE_VOID } },
+ { "intBitsToFloat", TYPE_VEC2, { TYPE_IVEC2, TYPE_VOID } },
+ { "intBitsToFloat", TYPE_VEC3, { TYPE_IVEC3, TYPE_VOID } },
+ { "intBitsToFloat", TYPE_VEC4, { TYPE_IVEC4, TYPE_VOID } },
+
+ { "uintBitsToFloat", TYPE_FLOAT, { TYPE_UINT, TYPE_VOID } },
+ { "uintBitsToFloat", TYPE_VEC2, { TYPE_UVEC2, TYPE_VOID } },
+ { "uintBitsToFloat", TYPE_VEC3, { TYPE_UVEC3, TYPE_VOID } },
+ { "uintBitsToFloat", TYPE_VEC4, { TYPE_UVEC4, TYPE_VOID } },
//builtins - geometric
- {"length",TYPE_FLOAT,{TYPE_VEC2,TYPE_VOID}},
- {"length",TYPE_FLOAT,{TYPE_VEC3,TYPE_VOID}},
- {"length",TYPE_FLOAT,{TYPE_VEC4,TYPE_VOID}},
- {"distance",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"distance",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"distance",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"dot",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"dot",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"dot",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
- {"cross",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"normalize",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"normalize",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"normalize",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
- {"reflect",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"refract",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"facefordward",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"facefordward",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"facefordward",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"matrixCompMult",TYPE_MAT2,{TYPE_MAT2,TYPE_MAT2,TYPE_VOID}},
- {"matrixCompMult",TYPE_MAT3,{TYPE_MAT3,TYPE_MAT3,TYPE_VOID}},
- {"matrixCompMult",TYPE_MAT4,{TYPE_MAT4,TYPE_MAT4,TYPE_VOID}},
-
- {"outerProduct",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"outerProduct",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"outerProduct",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"transpose",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}},
- {"transpose",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}},
- {"transpose",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}},
-
- {"determinant",TYPE_FLOAT,{TYPE_MAT2,TYPE_VOID}},
- {"determinant",TYPE_FLOAT,{TYPE_MAT3,TYPE_VOID}},
- {"determinant",TYPE_FLOAT,{TYPE_MAT4,TYPE_VOID}},
-
- {"inverse",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}},
- {"inverse",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}},
- {"inverse",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}},
-
-
- {"lessThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"lessThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"lessThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"lessThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"lessThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"lessThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"lessThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"lessThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"lessThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"greaterThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"greaterThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"greaterThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"greaterThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"lessThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"lessThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"lessThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"lessThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"greaterThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"greaterThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"greaterThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"greaterThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"equal",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"equal",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"equal",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"equal",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"equal",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"equal",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
-
- {"equal",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"equal",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"equal",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
-
- {"equal",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}},
- {"equal",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}},
- {"equal",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}},
-
- {"notEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"notEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
- {"notEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}},
-
- {"notEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}},
- {"notEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}},
- {"notEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}},
+ { "length", TYPE_FLOAT, { TYPE_VEC2, TYPE_VOID } },
+ { "length", TYPE_FLOAT, { TYPE_VEC3, TYPE_VOID } },
+ { "length", TYPE_FLOAT, { TYPE_VEC4, TYPE_VOID } },
+ { "distance", TYPE_FLOAT, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "distance", TYPE_FLOAT, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "distance", TYPE_FLOAT, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "dot", TYPE_FLOAT, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "dot", TYPE_FLOAT, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "dot", TYPE_FLOAT, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+ { "cross", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "normalize", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "normalize", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "normalize", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+ { "reflect", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "refract", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "facefordward", TYPE_VEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "facefordward", TYPE_VEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "facefordward", TYPE_VEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "matrixCompMult", TYPE_MAT2, { TYPE_MAT2, TYPE_MAT2, TYPE_VOID } },
+ { "matrixCompMult", TYPE_MAT3, { TYPE_MAT3, TYPE_MAT3, TYPE_VOID } },
+ { "matrixCompMult", TYPE_MAT4, { TYPE_MAT4, TYPE_MAT4, TYPE_VOID } },
+
+ { "outerProduct", TYPE_MAT2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "outerProduct", TYPE_MAT3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "outerProduct", TYPE_MAT4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "transpose", TYPE_MAT2, { TYPE_MAT2, TYPE_VOID } },
+ { "transpose", TYPE_MAT3, { TYPE_MAT3, TYPE_VOID } },
+ { "transpose", TYPE_MAT4, { TYPE_MAT4, TYPE_VOID } },
+
+ { "determinant", TYPE_FLOAT, { TYPE_MAT2, TYPE_VOID } },
+ { "determinant", TYPE_FLOAT, { TYPE_MAT3, TYPE_VOID } },
+ { "determinant", TYPE_FLOAT, { TYPE_MAT4, TYPE_VOID } },
+
+ { "inverse", TYPE_MAT2, { TYPE_MAT2, TYPE_VOID } },
+ { "inverse", TYPE_MAT3, { TYPE_MAT3, TYPE_VOID } },
+ { "inverse", TYPE_MAT4, { TYPE_MAT4, TYPE_VOID } },
+
+ { "lessThan", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "lessThan", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "lessThan", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "lessThan", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "greaterThan", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "greaterThan", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "greaterThan", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "greaterThan", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "lessThanEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "lessThanEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "lessThanEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "lessThanEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "greaterThanEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "greaterThanEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "greaterThanEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "greaterThanEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "equal", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "equal", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "equal", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "equal", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "equal", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "equal", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
+
+ { "equal", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "equal", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "equal", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
+
+ { "equal", TYPE_BVEC2, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } },
+ { "equal", TYPE_BVEC3, { TYPE_BVEC3, TYPE_BVEC3, TYPE_VOID } },
+ { "equal", TYPE_BVEC4, { TYPE_BVEC4, TYPE_BVEC4, TYPE_VOID } },
+
+ { "notEqual", TYPE_BVEC2, { TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC3, { TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC4, { TYPE_VEC4, TYPE_VEC4, TYPE_VOID } },
+
+ { "notEqual", TYPE_BVEC2, { TYPE_IVEC2, TYPE_IVEC2, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC3, { TYPE_IVEC3, TYPE_IVEC3, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC4, { TYPE_IVEC4, TYPE_IVEC4, TYPE_VOID } },
- {"notEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}},
- {"notEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}},
- {"notEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}},
+ { "notEqual", TYPE_BVEC2, { TYPE_UVEC2, TYPE_UVEC2, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC3, { TYPE_UVEC3, TYPE_UVEC3, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC4, { TYPE_UVEC4, TYPE_UVEC4, TYPE_VOID } },
- {"notEqual",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}},
- {"notEqual",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}},
- {"notEqual",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}},
+ { "notEqual", TYPE_BVEC2, { TYPE_BVEC2, TYPE_BVEC2, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC3, { TYPE_BVEC3, TYPE_BVEC3, TYPE_VOID } },
+ { "notEqual", TYPE_BVEC4, { TYPE_BVEC4, TYPE_BVEC4, TYPE_VOID } },
- {"any",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}},
- {"any",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}},
- {"any",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}},
+ { "any", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } },
+ { "any", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } },
+ { "any", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } },
- {"all",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}},
- {"all",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}},
- {"all",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}},
+ { "all", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } },
+ { "all", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } },
+ { "all", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } },
- {"not",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}},
- {"not",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}},
- {"not",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}},
+ { "not", TYPE_BOOL, { TYPE_BVEC2, TYPE_VOID } },
+ { "not", TYPE_BOOL, { TYPE_BVEC3, TYPE_VOID } },
+ { "not", TYPE_BOOL, { TYPE_BVEC4, TYPE_VOID } },
//builtins - texture
- {"textureSize",TYPE_VEC2,{TYPE_SAMPLER2D,TYPE_INT,TYPE_VOID}},
- {"textureSize",TYPE_VEC2,{TYPE_ISAMPLER2D,TYPE_INT,TYPE_VOID}},
- {"textureSize",TYPE_VEC2,{TYPE_USAMPLER2D,TYPE_INT,TYPE_VOID}},
- {"textureSize",TYPE_VEC2,{TYPE_SAMPLERCUBE,TYPE_INT,TYPE_VOID}},
-
- {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VOID}},
- {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VOID}},
- {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VOID}},
- {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}},
- {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VOID}},
- {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_VOID}},
- {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_VOID}},
- {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}},
- {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_VOID}},
- {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureLod",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
-
- {"texelFetch",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}},
- {"texelFetch",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}},
- {"texelFetch",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}},
-
- {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}},
- {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}},
-
- {"textureGrad",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"textureGrad",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"textureGrad",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}},
- {"textureGrad",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}},
-
- {"textureScreen",TYPE_VEC4,{TYPE_VEC2,TYPE_VOID}},
-
- {"dFdx",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"dFdx",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"dFdx",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"dFdx",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"dFdy",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"dFdy",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"dFdy",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"dFdy",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
- {"fwidth",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}},
- {"fwidth",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}},
- {"fwidth",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}},
- {"fwidth",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}},
-
-
- {NULL,TYPE_VOID,{TYPE_VOID}}
+ { "textureSize", TYPE_VEC2, { TYPE_SAMPLER2D, TYPE_INT, TYPE_VOID } },
+ { "textureSize", TYPE_VEC2, { TYPE_ISAMPLER2D, TYPE_INT, TYPE_VOID } },
+ { "textureSize", TYPE_VEC2, { TYPE_USAMPLER2D, TYPE_INT, TYPE_VOID } },
+ { "textureSize", TYPE_VEC2, { TYPE_SAMPLERCUBE, TYPE_INT, TYPE_VOID } },
+
+ { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_VOID } },
+ { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "texture", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_VOID } },
+ { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "texture", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_VOID } },
+ { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_FLOAT, TYPE_VOID } },
+ { "texture", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "texture", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_VOID } },
+ { "texture", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_VOID } },
+ { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProj", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_VOID } },
+ { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProj", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_VOID } },
+ { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_VOID } },
+ { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProj", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureLod", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+
+ { "texelFetch", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } },
+ { "texelFetch", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } },
+ { "texelFetch", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_IVEC2, TYPE_INT, TYPE_VOID } },
+
+ { "textureProjLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProjLod", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureProjLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProjLod", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureProjLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC3, TYPE_FLOAT, TYPE_VOID } },
+ { "textureProjLod", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC4, TYPE_FLOAT, TYPE_VOID } },
+
+ { "textureGrad", TYPE_VEC4, { TYPE_SAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "textureGrad", TYPE_IVEC4, { TYPE_ISAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "textureGrad", TYPE_UVEC4, { TYPE_USAMPLER2D, TYPE_VEC2, TYPE_VEC2, TYPE_VEC2, TYPE_VOID } },
+ { "textureGrad", TYPE_VEC4, { TYPE_SAMPLERCUBE, TYPE_VEC3, TYPE_VEC3, TYPE_VEC3, TYPE_VOID } },
+
+ { "textureScreen", TYPE_VEC4, { TYPE_VEC2, TYPE_VOID } },
+
+ { "dFdx", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "dFdx", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "dFdx", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "dFdx", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "dFdy", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "dFdy", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "dFdy", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "dFdy", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { "fwidth", TYPE_FLOAT, { TYPE_FLOAT, TYPE_VOID } },
+ { "fwidth", TYPE_VEC2, { TYPE_VEC2, TYPE_VOID } },
+ { "fwidth", TYPE_VEC3, { TYPE_VEC3, TYPE_VOID } },
+ { "fwidth", TYPE_VEC4, { TYPE_VEC4, TYPE_VOID } },
+
+ { NULL, TYPE_VOID, { TYPE_VOID } }
};
+bool ShaderLanguage::_validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type) {
-
-bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p_func,DataType *r_ret_type) {
-
- ERR_FAIL_COND_V(p_func->op!=OP_CALL && p_func->op!=OP_CONSTRUCT,NULL);
-
+ ERR_FAIL_COND_V(p_func->op != OP_CALL && p_func->op != OP_CONSTRUCT, NULL);
Vector<DataType> args;
- ERR_FAIL_COND_V( p_func->arguments[0]->type!=Node::TYPE_VARIABLE, NULL );
+ ERR_FAIL_COND_V(p_func->arguments[0]->type != Node::TYPE_VARIABLE, NULL);
- StringName name = static_cast<VariableNode*>(p_func->arguments[0])->name.operator String();
+ StringName name = static_cast<VariableNode *>(p_func->arguments[0])->name.operator String();
- bool all_const=true;
- for(int i=1;i<p_func->arguments.size();i++) {
- if (p_func->arguments[i]->type!=Node::TYPE_CONSTANT)
- all_const=false;
+ bool all_const = true;
+ for (int i = 1; i < p_func->arguments.size(); i++) {
+ if (p_func->arguments[i]->type != Node::TYPE_CONSTANT)
+ all_const = false;
args.push_back(p_func->arguments[i]->get_datatype());
}
- int argcount=args.size();
-
- bool failed_builtin=false;
+ int argcount = args.size();
+ bool failed_builtin = false;
- if (argcount<=4) {
+ if (argcount <= 4) {
// test builtins
- int idx=0;
+ int idx = 0;
while (builtin_func_defs[idx].name) {
- if (name==builtin_func_defs[idx].name) {
+ if (name == builtin_func_defs[idx].name) {
- failed_builtin=true;
- bool fail=false;
- for(int i=0;i<argcount;i++) {
+ failed_builtin = true;
+ bool fail = false;
+ for (int i = 0; i < argcount; i++) {
- if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),builtin_func_defs[idx].args[i])) {
+ if (get_scalar_type(args[i]) == args[i] && p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode *>(p_func->arguments[i + 1]), builtin_func_defs[idx].args[i])) {
//all good
- } else if (args[i]!=builtin_func_defs[idx].args[i]) {
- fail=true;
+ } else if (args[i] != builtin_func_defs[idx].args[i]) {
+ fail = true;
break;
}
}
- if (!fail && argcount<4 && builtin_func_defs[idx].args[argcount]!=TYPE_VOID)
- fail=true; //make sure the number of arguments matches
+ if (!fail && argcount < 4 && builtin_func_defs[idx].args[argcount] != TYPE_VOID)
+ fail = true; //make sure the number of arguments matches
if (!fail) {
if (r_ret_type)
- *r_ret_type=builtin_func_defs[idx].rettype;
+ *r_ret_type = builtin_func_defs[idx].rettype;
return true;
}
-
}
idx++;
@@ -1828,17 +1791,17 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p
}
if (failed_builtin) {
- String err ="Invalid arguments for built-in function: "+String(name)+"(";
- for(int i=0;i<argcount;i++) {
- if (i>0)
- err+=",";
+ String err = "Invalid arguments for built-in function: " + String(name) + "(";
+ for (int i = 0; i < argcount; i++) {
+ if (i > 0)
+ err += ",";
- if (p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && p_func->arguments[i+1]->get_datatype()==TYPE_INT && static_cast<ConstantNode*>(p_func->arguments[i+1])->values[0].sint<0) {
- err+="-";
+ if (p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && p_func->arguments[i + 1]->get_datatype() == TYPE_INT && static_cast<ConstantNode *>(p_func->arguments[i + 1])->values[0].sint < 0) {
+ err += "-";
}
- err+=get_datatype_name(args[i]);
+ err += get_datatype_name(args[i]);
}
- err+=")";
+ err += ")";
_set_error(err);
return false;
}
@@ -1904,51 +1867,48 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p
StringName exclude_function;
BlockNode *block = p_block;
- while(block) {
+ while (block) {
if (block->parent_function) {
- exclude_function=block->parent_function->name;
+ exclude_function = block->parent_function->name;
}
- block=block->parent_block;
+ block = block->parent_block;
}
- if (name==exclude_function) {
+ if (name == exclude_function) {
_set_error("Recursion is not allowed");
return false;
}
- for(int i=0;i<shader->functions.size();i++) {
-
+ for (int i = 0; i < shader->functions.size(); i++) {
if (name != shader->functions[i].name)
continue;
if (!shader->functions[i].callable) {
- _set_error("Function '"+String(name)+" can't be called from source code.");
+ _set_error("Function '" + String(name) + " can't be called from source code.");
return false;
}
FunctionNode *pfunc = shader->functions[i].function;
-
- if (pfunc->arguments.size()!=args.size())
+ if (pfunc->arguments.size() != args.size())
continue;
- bool fail=false;
+ bool fail = false;
+ for (int i = 0; i < args.size(); i++) {
- for(int i=0;i<args.size();i++) {
-
- if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),pfunc->arguments[i].type)) {
+ if (get_scalar_type(args[i]) == args[i] && p_func->arguments[i + 1]->type == Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode *>(p_func->arguments[i + 1]), pfunc->arguments[i].type)) {
//all good
- } else if (args[i]!=pfunc->arguments[i].type) {
- fail=true;
+ } else if (args[i] != pfunc->arguments[i].type) {
+ fail = true;
break;
}
}
if (!fail) {
- p_func->return_cache=pfunc->return_type;
+ p_func->return_cache = pfunc->return_type;
return true;
}
}
@@ -1956,58 +1916,51 @@ bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p
return false;
}
-
-bool ShaderLanguage::_parse_function_arguments(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,OperatorNode* p_func,int *r_complete_arg) {
+bool ShaderLanguage::_parse_function_arguments(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, OperatorNode *p_func, int *r_complete_arg) {
TkPos pos = _get_tkpos();
Token tk = _get_token();
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
return true;
}
_set_tkpos(pos);
-
- while(true) {
-
+ while (true) {
if (r_complete_arg) {
pos = _get_tkpos();
tk = _get_token();
- if (tk.type==TK_CURSOR) {
+ if (tk.type == TK_CURSOR) {
- *r_complete_arg=p_func->arguments.size()-1;
+ *r_complete_arg = p_func->arguments.size() - 1;
} else {
_set_tkpos(pos);
}
}
- Node *arg= _parse_and_reduce_expression(p_block,p_builtin_types);
+ Node *arg = _parse_and_reduce_expression(p_block, p_builtin_types);
if (!arg) {
return false;
}
-
p_func->arguments.push_back(arg);
tk = _get_token();
-
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
return true;
- } else if (tk.type!=TK_COMMA) {
+ } else if (tk.type != TK_COMMA) {
// something is broken
_set_error("Expected ',' or ')' after argument");
return false;
}
-
-
}
return true;
@@ -2015,112 +1968,108 @@ bool ShaderLanguage::_parse_function_arguments(BlockNode* p_block,const Map<Stri
bool ShaderLanguage::is_token_operator(TokenType p_type) {
-
- return (p_type==TK_OP_EQUAL ||
- p_type==TK_OP_NOT_EQUAL ||
- p_type==TK_OP_LESS ||
- p_type==TK_OP_LESS_EQUAL ||
- p_type==TK_OP_GREATER ||
- p_type==TK_OP_GREATER_EQUAL ||
- p_type==TK_OP_AND ||
- p_type==TK_OP_OR ||
- p_type==TK_OP_NOT ||
- p_type==TK_OP_ADD ||
- p_type==TK_OP_SUB ||
- p_type==TK_OP_MUL ||
- p_type==TK_OP_DIV ||
- p_type==TK_OP_MOD ||
- p_type==TK_OP_SHIFT_LEFT ||
- p_type==TK_OP_SHIFT_RIGHT ||
- p_type==TK_OP_ASSIGN ||
- p_type==TK_OP_ASSIGN_ADD ||
- p_type==TK_OP_ASSIGN_SUB ||
- p_type==TK_OP_ASSIGN_MUL ||
- p_type==TK_OP_ASSIGN_DIV ||
- p_type==TK_OP_ASSIGN_MOD ||
- p_type==TK_OP_ASSIGN_SHIFT_LEFT ||
- p_type==TK_OP_ASSIGN_SHIFT_RIGHT ||
- p_type==TK_OP_ASSIGN_BIT_AND ||
- p_type==TK_OP_ASSIGN_BIT_OR ||
- p_type==TK_OP_ASSIGN_BIT_XOR ||
- p_type==TK_OP_BIT_AND ||
- p_type==TK_OP_BIT_OR ||
- p_type==TK_OP_BIT_XOR ||
- p_type==TK_OP_BIT_INVERT ||
- p_type==TK_OP_INCREMENT ||
- p_type==TK_OP_DECREMENT ||
- p_type==TK_QUESTION ||
- p_type==TK_COLON );
-
+ return (p_type == TK_OP_EQUAL ||
+ p_type == TK_OP_NOT_EQUAL ||
+ p_type == TK_OP_LESS ||
+ p_type == TK_OP_LESS_EQUAL ||
+ p_type == TK_OP_GREATER ||
+ p_type == TK_OP_GREATER_EQUAL ||
+ p_type == TK_OP_AND ||
+ p_type == TK_OP_OR ||
+ p_type == TK_OP_NOT ||
+ p_type == TK_OP_ADD ||
+ p_type == TK_OP_SUB ||
+ p_type == TK_OP_MUL ||
+ p_type == TK_OP_DIV ||
+ p_type == TK_OP_MOD ||
+ p_type == TK_OP_SHIFT_LEFT ||
+ p_type == TK_OP_SHIFT_RIGHT ||
+ p_type == TK_OP_ASSIGN ||
+ p_type == TK_OP_ASSIGN_ADD ||
+ p_type == TK_OP_ASSIGN_SUB ||
+ p_type == TK_OP_ASSIGN_MUL ||
+ p_type == TK_OP_ASSIGN_DIV ||
+ p_type == TK_OP_ASSIGN_MOD ||
+ p_type == TK_OP_ASSIGN_SHIFT_LEFT ||
+ p_type == TK_OP_ASSIGN_SHIFT_RIGHT ||
+ p_type == TK_OP_ASSIGN_BIT_AND ||
+ p_type == TK_OP_ASSIGN_BIT_OR ||
+ p_type == TK_OP_ASSIGN_BIT_XOR ||
+ p_type == TK_OP_BIT_AND ||
+ p_type == TK_OP_BIT_OR ||
+ p_type == TK_OP_BIT_XOR ||
+ p_type == TK_OP_BIT_INVERT ||
+ p_type == TK_OP_INCREMENT ||
+ p_type == TK_OP_DECREMENT ||
+ p_type == TK_QUESTION ||
+ p_type == TK_COLON);
}
-bool ShaderLanguage::convert_constant(ConstantNode* p_constant, DataType p_to_type,ConstantNode::Value *p_value) {
+bool ShaderLanguage::convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value) {
- if (p_constant->datatype==p_to_type) {
+ if (p_constant->datatype == p_to_type) {
if (p_value) {
- for(int i=0;i<p_constant->values.size();i++) {
- p_value[i]=p_constant->values[i];
+ for (int i = 0; i < p_constant->values.size(); i++) {
+ p_value[i] = p_constant->values[i];
}
}
return true;
- } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_FLOAT) {
+ } else if (p_constant->datatype == TYPE_INT && p_to_type == TYPE_FLOAT) {
if (p_value) {
- p_value->real=p_constant->values[0].sint;
+ p_value->real = p_constant->values[0].sint;
}
return true;
- } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_FLOAT) {
+ } else if (p_constant->datatype == TYPE_UINT && p_to_type == TYPE_FLOAT) {
if (p_value) {
- p_value->real=p_constant->values[0].uint;
+ p_value->real = p_constant->values[0].uint;
}
return true;
- } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_UINT) {
- if (p_constant->values[0].sint<0) {
+ } else if (p_constant->datatype == TYPE_INT && p_to_type == TYPE_UINT) {
+ if (p_constant->values[0].sint < 0) {
return false;
}
if (p_value) {
- p_value->uint=p_constant->values[0].sint;
+ p_value->uint = p_constant->values[0].sint;
}
return true;
- } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_INT) {
+ } else if (p_constant->datatype == TYPE_UINT && p_to_type == TYPE_INT) {
- if (p_constant->values[0].uint>0x7FFFFFFF) {
+ if (p_constant->values[0].uint > 0x7FFFFFFF) {
return false;
}
if (p_value) {
- p_value->sint=p_constant->values[0].uint;
+ p_value->sint = p_constant->values[0].uint;
}
return true;
} else
return false;
-
}
bool ShaderLanguage::is_scalar_type(DataType p_type) {
- return p_type==TYPE_BOOL || p_type==TYPE_INT || p_type==TYPE_UINT || p_type==TYPE_FLOAT;
+ return p_type == TYPE_BOOL || p_type == TYPE_INT || p_type == TYPE_UINT || p_type == TYPE_FLOAT;
}
bool ShaderLanguage::is_sampler_type(DataType p_type) {
- return p_type==TYPE_SAMPLER2D || p_type==TYPE_ISAMPLER2D || p_type==TYPE_USAMPLER2D || p_type==TYPE_SAMPLERCUBE;
-
+ return p_type == TYPE_SAMPLER2D || p_type == TYPE_ISAMPLER2D || p_type == TYPE_USAMPLER2D || p_type == TYPE_SAMPLERCUBE;
}
void ShaderLanguage::get_keyword_list(List<String> *r_keywords) {
Set<String> kws;
- int idx=0;
+ int idx = 0;
- while(keyword_list[idx].text) {
+ while (keyword_list[idx].text) {
kws.insert(keyword_list[idx].text);
idx++;
}
- idx=0;
+ idx = 0;
while (builtin_func_defs[idx].name) {
@@ -2129,17 +2078,16 @@ void ShaderLanguage::get_keyword_list(List<String> *r_keywords) {
idx++;
}
- for(Set<String>::Element *E=kws.front();E;E=E->next()) {
+ for (Set<String>::Element *E = kws.front(); E; E = E->next()) {
r_keywords->push_back(E->get());
}
}
void ShaderLanguage::get_builtin_funcs(List<String> *r_keywords) {
-
Set<String> kws;
- int idx=0;
+ int idx = 0;
while (builtin_func_defs[idx].name) {
@@ -2148,16 +2096,14 @@ void ShaderLanguage::get_builtin_funcs(List<String> *r_keywords) {
idx++;
}
- for(Set<String>::Element *E=kws.front();E;E=E->next()) {
+ for (Set<String>::Element *E = kws.front(); E; E = E->next()) {
r_keywords->push_back(E->get());
}
}
-
-
ShaderLanguage::DataType ShaderLanguage::get_scalar_type(DataType p_type) {
- static const DataType scalar_types[]={
+ static const DataType scalar_types[] = {
TYPE_VOID,
TYPE_BOOL,
TYPE_BOOL,
@@ -2187,115 +2133,109 @@ ShaderLanguage::DataType ShaderLanguage::get_scalar_type(DataType p_type) {
return scalar_types[p_type];
}
+bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName &identifier) {
-bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block,CompletionType p_type,StringName& identifier) {
-
- identifier=StringName();
+ identifier = StringName();
TkPos pos;
Token tk = _get_token();
- if (tk.type==TK_IDENTIFIER) {
- identifier=tk.text;
- pos = _get_tkpos();
+ if (tk.type == TK_IDENTIFIER) {
+ identifier = tk.text;
+ pos = _get_tkpos();
tk = _get_token();
}
- if (tk.type==TK_CURSOR) {
+ if (tk.type == TK_CURSOR) {
- completion_type=p_type;
- completion_line=tk_line;
- completion_block=p_block;
+ completion_type = p_type;
+ completion_line = tk_line;
+ completion_block = p_block;
pos = _get_tkpos();
tk = _get_token();
- if (tk.type==TK_IDENTIFIER) {
- identifier=identifier.operator String() + tk.text.operator String();
+ if (tk.type == TK_IDENTIFIER) {
+ identifier = identifier.operator String() + tk.text.operator String();
} else {
_set_tkpos(pos);
}
return true;
- } else if (identifier!=StringName()){
+ } else if (identifier != StringName()) {
_set_tkpos(pos);
}
return false;
}
-
-
-ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types) {
+ShaderLanguage::Node *ShaderLanguage::_parse_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types) {
Vector<Expression> expression;
//Vector<TokenType> operators;
- while(true) {
+ while (true) {
- Node *expr=NULL;
+ Node *expr = NULL;
TkPos prepos = _get_tkpos();
Token tk = _get_token();
- TkPos pos = _get_tkpos();
-
+ TkPos pos = _get_tkpos();
- if (tk.type==TK_PARENTHESIS_OPEN) {
+ if (tk.type == TK_PARENTHESIS_OPEN) {
//handle subexpression
- expr = _parse_and_reduce_expression(p_block,p_builtin_types);
+ expr = _parse_and_reduce_expression(p_block, p_builtin_types);
if (!expr)
return NULL;
tk = _get_token();
- if (tk.type!=TK_PARENTHESIS_CLOSE) {
+ if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected ')' in expression");
return NULL;
}
- } else if (tk.type==TK_REAL_CONSTANT) {
-
+ } else if (tk.type == TK_REAL_CONSTANT) {
ConstantNode *constant = alloc_node<ConstantNode>();
ConstantNode::Value v;
- v.real=tk.constant;
+ v.real = tk.constant;
constant->values.push_back(v);
- constant->datatype=TYPE_FLOAT;
- expr=constant;
-
- } else if (tk.type==TK_INT_CONSTANT) {
+ constant->datatype = TYPE_FLOAT;
+ expr = constant;
+ } else if (tk.type == TK_INT_CONSTANT) {
ConstantNode *constant = alloc_node<ConstantNode>();
ConstantNode::Value v;
- v.sint=tk.constant;
+ v.sint = tk.constant;
constant->values.push_back(v);
- constant->datatype=TYPE_INT;
- expr=constant;
+ constant->datatype = TYPE_INT;
+ expr = constant;
- } else if (tk.type==TK_TRUE) {
+ } else if (tk.type == TK_TRUE) {
//print_line("found true");
//handle true constant
ConstantNode *constant = alloc_node<ConstantNode>();
ConstantNode::Value v;
- v.boolean=true;
+ v.boolean = true;
constant->values.push_back(v);
- constant->datatype=TYPE_BOOL;
- expr=constant;
+ constant->datatype = TYPE_BOOL;
+ expr = constant;
- } else if (tk.type==TK_FALSE) {
+ } else if (tk.type == TK_FALSE) {
//handle false constant
ConstantNode *constant = alloc_node<ConstantNode>();
ConstantNode::Value v;
- v.boolean=false;
+ v.boolean = false;
constant->values.push_back(v);
- constant->datatype=TYPE_BOOL;
- expr=constant;
+ constant->datatype = TYPE_BOOL;
+ expr = constant;
- } else if (tk.type==TK_TYPE_VOID) {
+ } else if (tk.type == TK_TYPE_VOID) {
//make sure void is not used in expression
_set_error("Void value not allowed in Expression");
@@ -2304,98 +2244,93 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
//basic type constructor
OperatorNode *func = alloc_node<OperatorNode>();
- func->op=OP_CONSTRUCT;
-
+ func->op = OP_CONSTRUCT;
if (is_token_precision(tk.type)) {
- func->return_precision_cache=get_token_precision(tk.type);
- tk=_get_token();
+ func->return_precision_cache = get_token_precision(tk.type);
+ tk = _get_token();
}
VariableNode *funcname = alloc_node<VariableNode>();
- funcname->name=get_datatype_name(get_token_datatype(tk.type));
+ funcname->name = get_datatype_name(get_token_datatype(tk.type));
func->arguments.push_back(funcname);
- tk=_get_token();
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ tk = _get_token();
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after type name");
return NULL;
}
- int carg=-1;
+ int carg = -1;
- bool ok = _parse_function_arguments(p_block,p_builtin_types,func,&carg);
+ bool ok = _parse_function_arguments(p_block, p_builtin_types, func, &carg);
- if (carg>=0) {
- completion_type=COMPLETION_CALL_ARGUMENTS;
- completion_line=tk_line;
- completion_block=p_block;
- completion_function=funcname->name;
- completion_argument=carg;
+ if (carg >= 0) {
+ completion_type = COMPLETION_CALL_ARGUMENTS;
+ completion_line = tk_line;
+ completion_block = p_block;
+ completion_function = funcname->name;
+ completion_argument = carg;
}
if (!ok)
return NULL;
- if (!_validate_function_call(p_block,func,&func->return_cache)) {
- _set_error("No matching constructor found for: '"+String(funcname->name)+"'");
+ if (!_validate_function_call(p_block, func, &func->return_cache)) {
+ _set_error("No matching constructor found for: '" + String(funcname->name) + "'");
return NULL;
}
//validate_Function_call()
- expr=_reduce_expression(p_block,func);
+ expr = _reduce_expression(p_block, func);
-
- } else if (tk.type==TK_IDENTIFIER) {
+ } else if (tk.type == TK_IDENTIFIER) {
_set_tkpos(prepos);
StringName identifier;
- _get_completable_identifier(p_block,COMPLETION_IDENTIFIER,identifier);
-
+ _get_completable_identifier(p_block, COMPLETION_IDENTIFIER, identifier);
- tk=_get_token();
- if (tk.type==TK_PARENTHESIS_OPEN) {
+ tk = _get_token();
+ if (tk.type == TK_PARENTHESIS_OPEN) {
//a function
StringName name = identifier;
OperatorNode *func = alloc_node<OperatorNode>();
- func->op=OP_CALL;
+ func->op = OP_CALL;
VariableNode *funcname = alloc_node<VariableNode>();
- funcname->name=name;
+ funcname->name = name;
func->arguments.push_back(funcname);
- int carg=-1;
+ int carg = -1;
- bool ok =_parse_function_arguments(p_block,p_builtin_types,func,&carg);
+ bool ok = _parse_function_arguments(p_block, p_builtin_types, func, &carg);
- for(int i=0;i<shader->functions.size();i++) {
- if (shader->functions[i].name==name) {
+ for (int i = 0; i < shader->functions.size(); i++) {
+ if (shader->functions[i].name == name) {
shader->functions[i].uses_function.insert(name);
}
}
-
-
- if (carg>=0) {
- completion_type=COMPLETION_CALL_ARGUMENTS;
- completion_line=tk_line;
- completion_block=p_block;
- completion_function=funcname->name;
- completion_argument=carg;
+ if (carg >= 0) {
+ completion_type = COMPLETION_CALL_ARGUMENTS;
+ completion_line = tk_line;
+ completion_block = p_block;
+ completion_function = funcname->name;
+ completion_argument = carg;
}
if (!ok)
return NULL;
- if (!_validate_function_call(p_block,func,&func->return_cache)) {
- _set_error("No matching function found for: '"+String(funcname->name)+"'");
+ if (!_validate_function_call(p_block, func, &func->return_cache)) {
+ _set_error("No matching function found for: '" + String(funcname->name) + "'");
return NULL;
}
- expr=func;
+ expr = func;
} else {
//an identifier
@@ -2405,71 +2340,65 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
DataType data_type;
IdentifierType ident_type;
- if (!_find_identifier(p_block,p_builtin_types,identifier,&data_type,&ident_type)) {
- _set_error("Unknown identifier in expression: "+String(identifier));
+ if (!_find_identifier(p_block, p_builtin_types, identifier, &data_type, &ident_type)) {
+ _set_error("Unknown identifier in expression: " + String(identifier));
return NULL;
}
- if (ident_type==IDENTIFIER_FUNCTION) {
- _set_error("Can't use function as identifier: "+String(identifier));
+ if (ident_type == IDENTIFIER_FUNCTION) {
+ _set_error("Can't use function as identifier: " + String(identifier));
return NULL;
}
-
VariableNode *varname = alloc_node<VariableNode>();
- varname->name=identifier;
- varname->datatype_cache=data_type;
- expr=varname;
-
+ varname->name = identifier;
+ varname->datatype_cache = data_type;
+ expr = varname;
}
-
- } else if (tk.type==TK_OP_ADD) {
+ } else if (tk.type == TK_OP_ADD) {
continue; //this one does nothing
- } else if (tk.type==TK_OP_SUB || tk.type==TK_OP_NOT || tk.type==TK_OP_BIT_INVERT || tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) {
-
+ } else if (tk.type == TK_OP_SUB || tk.type == TK_OP_NOT || tk.type == TK_OP_BIT_INVERT || tk.type == TK_OP_INCREMENT || tk.type == TK_OP_DECREMENT) {
Expression e;
- e.is_op=true;
-
- switch(tk.type) {
- case TK_OP_SUB: e.op=OP_NEGATE; break;
- case TK_OP_NOT: e.op=OP_NOT; break;
- case TK_OP_BIT_INVERT: e.op=OP_BIT_INVERT; break;
- case TK_OP_INCREMENT: e.op=OP_INCREMENT; break;
- case TK_OP_DECREMENT: e.op=OP_DECREMENT; break;
+ e.is_op = true;
+
+ switch (tk.type) {
+ case TK_OP_SUB: e.op = OP_NEGATE; break;
+ case TK_OP_NOT: e.op = OP_NOT; break;
+ case TK_OP_BIT_INVERT: e.op = OP_BIT_INVERT; break;
+ case TK_OP_INCREMENT: e.op = OP_INCREMENT; break;
+ case TK_OP_DECREMENT: e.op = OP_DECREMENT; break;
default: ERR_FAIL_V(NULL);
}
expression.push_back(e);
continue;
-
} else {
- _set_error("Expected expression, found: "+get_token_text(tk));
+ _set_error("Expected expression, found: " + get_token_text(tk));
return NULL;
//nothing
}
- ERR_FAIL_COND_V(!expr,NULL);
-
+ ERR_FAIL_COND_V(!expr, NULL);
/* OK now see what's NEXT to the operator.. */
/* OK now see what's NEXT to the operator.. */
/* OK now see what's NEXT to the operator.. */
- while(true) {
+ while (true) {
TkPos pos = _get_tkpos();
- tk=_get_token();
+ tk = _get_token();
- if (tk.type==TK_PERIOD) {
+ if (tk.type == TK_PERIOD) {
StringName identifier;
- if (_get_completable_identifier(p_block,COMPLETION_INDEX,identifier)) {
- completion_base=expr->get_datatype();
+ if (_get_completable_identifier(p_block, COMPLETION_INDEX, identifier)) {
+ completion_base = expr->get_datatype();
}
- if (identifier==StringName()) {
+ if (identifier == StringName()) {
_set_error("Expected identifier as member");
return NULL;
}
@@ -2477,35 +2406,35 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
DataType dt = expr->get_datatype();
String ident = identifier;
- bool ok=true;
+ bool ok = true;
DataType member_type;
- switch(dt) {
+ switch (dt) {
case TYPE_BVEC2:
case TYPE_IVEC2:
case TYPE_UVEC2:
case TYPE_VEC2: {
int l = ident.length();
- if (l==1) {
- member_type=DataType(dt-1);
- } else if (l==2) {
- member_type=dt;
+ if (l == 1) {
+ member_type = DataType(dt - 1);
+ } else if (l == 2) {
+ member_type = dt;
} else {
- ok=false;
+ ok = false;
break;
}
- const CharType *c=ident.ptr();
- for(int i=0;i<l;i++) {
+ const CharType *c = ident.ptr();
+ for (int i = 0; i < l; i++) {
- switch(c[i]) {
+ switch (c[i]) {
case 'r':
case 'g':
case 'x':
case 'y':
break;
default:
- ok=false;
+ ok = false;
break;
}
}
@@ -2517,21 +2446,21 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
case TYPE_VEC3: {
int l = ident.length();
- if (l==1) {
- member_type=DataType(dt-2);
- } else if (l==2) {
- member_type=DataType(dt-1);
- } else if (l==3) {
- member_type=dt;
+ if (l == 1) {
+ member_type = DataType(dt - 2);
+ } else if (l == 2) {
+ member_type = DataType(dt - 1);
+ } else if (l == 3) {
+ member_type = dt;
} else {
- ok=false;
+ ok = false;
break;
}
- const CharType *c=ident.ptr();
- for(int i=0;i<l;i++) {
+ const CharType *c = ident.ptr();
+ for (int i = 0; i < l; i++) {
- switch(c[i]) {
+ switch (c[i]) {
case 'r':
case 'g':
case 'b':
@@ -2540,7 +2469,7 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
case 'z':
break;
default:
- ok=false;
+ ok = false;
break;
}
}
@@ -2552,23 +2481,23 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
case TYPE_VEC4: {
int l = ident.length();
- if (l==1) {
- member_type=DataType(dt-3);
- } else if (l==2) {
- member_type=DataType(dt-2);
- } else if (l==3) {
- member_type=DataType(dt-1);
- } else if (l==4) {
- member_type=dt;
+ if (l == 1) {
+ member_type = DataType(dt - 3);
+ } else if (l == 2) {
+ member_type = DataType(dt - 2);
+ } else if (l == 3) {
+ member_type = DataType(dt - 1);
+ } else if (l == 4) {
+ member_type = dt;
} else {
- ok=false;
+ ok = false;
break;
}
- const CharType *c=ident.ptr();
- for(int i=0;i<l;i++) {
+ const CharType *c = ident.ptr();
+ for (int i = 0; i < l; i++) {
- switch(c[i]) {
+ switch (c[i]) {
case 'r':
case 'g':
case 'b':
@@ -2579,55 +2508,62 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
case 'w':
break;
default:
- ok=false;
+ ok = false;
break;
}
}
} break;
- case TYPE_MAT2: ok=(ident=="x" || ident=="y"); member_type=TYPE_VEC2; break;
- case TYPE_MAT3: ok=(ident=="x" || ident=="y" || ident=="z" ); member_type=TYPE_VEC3; break;
- case TYPE_MAT4: ok=(ident=="x" || ident=="y" || ident=="z" || ident=="w"); member_type=TYPE_VEC4; break;
+ case TYPE_MAT2:
+ ok = (ident == "x" || ident == "y");
+ member_type = TYPE_VEC2;
+ break;
+ case TYPE_MAT3:
+ ok = (ident == "x" || ident == "y" || ident == "z");
+ member_type = TYPE_VEC3;
+ break;
+ case TYPE_MAT4:
+ ok = (ident == "x" || ident == "y" || ident == "z" || ident == "w");
+ member_type = TYPE_VEC4;
+ break;
default: {}
}
if (!ok) {
- _set_error("Invalid member for expression: ."+ident);
+ _set_error("Invalid member for expression: ." + ident);
return NULL;
}
MemberNode *mn = alloc_node<MemberNode>();
- mn->basetype=dt;
- mn->datatype=member_type;
- mn->name=ident;
- mn->owner=expr;
- expr=mn;
-
+ mn->basetype = dt;
+ mn->datatype = member_type;
+ mn->name = ident;
+ mn->owner = expr;
+ expr = mn;
//todo
//member (period) has priority over any operator
//creates a subindexing expression in place
-
- /*} else if (tk.type==TK_BRACKET_OPEN) {
+ /*} else if (tk.type==TK_BRACKET_OPEN) {
//todo
//subindexing has priority over any operator
//creates a subindexing expression in place
*/
- } else if (tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) {
+ } else if (tk.type == TK_OP_INCREMENT || tk.type == TK_OP_DECREMENT) {
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=tk.type==TK_OP_DECREMENT ? OP_POST_DECREMENT : OP_POST_INCREMENT;
+ op->op = tk.type == TK_OP_DECREMENT ? OP_POST_DECREMENT : OP_POST_INCREMENT;
op->arguments.push_back(expr);
- if (!_validate_operator(op,&op->return_cache)) {
+ if (!_validate_operator(op, &op->return_cache)) {
_set_error("Invalid base type for increment/decrement operator");
return NULL;
}
- expr=op;
- } else {
+ expr = op;
+ } else {
_set_tkpos(pos);
break;
@@ -2635,8 +2571,8 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
}
Expression e;
- e.is_op=false;
- e.node=expr;
+ e.is_op = false;
+ e.node = expr;
expression.push_back(e);
pos = _get_tkpos();
@@ -2645,9 +2581,9 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
if (is_token_operator(tk.type)) {
Expression o;
- o.is_op=true;
+ o.is_op = true;
- switch(tk.type) {
+ switch (tk.type) {
case TK_OP_EQUAL: o.op = OP_EQUAL; break;
case TK_OP_NOT_EQUAL: o.op = OP_NOT_EQUAL; break;
@@ -2676,12 +2612,12 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
case TK_OP_ASSIGN_BIT_OR: o.op = OP_ASSIGN_BIT_OR; break;
case TK_OP_ASSIGN_BIT_XOR: o.op = OP_ASSIGN_BIT_XOR; break;
case TK_OP_BIT_AND: o.op = OP_BIT_AND; break;
- case TK_OP_BIT_OR: o.op = OP_BIT_OR ; break;
+ case TK_OP_BIT_OR: o.op = OP_BIT_OR; break;
case TK_OP_BIT_XOR: o.op = OP_BIT_XOR; break;
case TK_QUESTION: o.op = OP_SELECT_IF; break;
case TK_COLON: o.op = OP_SELECT_ELSE; break;
default: {
- _set_error("Invalid token for operator: "+get_token_text(tk));
+ _set_error("Invalid token for operator: " + get_token_text(tk));
return NULL;
}
}
@@ -2694,92 +2630,110 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
}
}
-
-
/* Reduce the set set of expressions and place them in an operator tree, respecting precedence */
- while(expression.size()>1) {
+ while (expression.size() > 1) {
- int next_op=-1;
- int min_priority=0xFFFFF;
- bool is_unary=false;
- bool is_ternary=false;
+ int next_op = -1;
+ int min_priority = 0xFFFFF;
+ bool is_unary = false;
+ bool is_ternary = false;
- for(int i=0;i<expression.size();i++) {
+ for (int i = 0; i < expression.size(); i++) {
if (!expression[i].is_op) {
continue;
}
- bool unary=false;
- bool ternary=false;
+ bool unary = false;
+ bool ternary = false;
int priority;
- switch(expression[i].op) {
- case OP_EQUAL: priority=8; break;
- case OP_NOT_EQUAL: priority=8; break;
- case OP_LESS: priority=7; break;
- case OP_LESS_EQUAL: priority=7; break;
- case OP_GREATER: priority=7; break;
- case OP_GREATER_EQUAL: priority=7; break;
- case OP_AND: priority=12; break;
- case OP_OR: priority=14; break;
- case OP_NOT: priority=3; unary=true; break;
- case OP_NEGATE: priority=3; unary=true; break;
- case OP_ADD: priority=5; break;
- case OP_SUB: priority=5; break;
- case OP_MUL: priority=4; break;
- case OP_DIV: priority=4; break;
- case OP_MOD: priority=4; break;
- case OP_SHIFT_LEFT: priority=6; break;
- case OP_SHIFT_RIGHT: priority=6; break;
- case OP_ASSIGN: priority=16; break;
- case OP_ASSIGN_ADD: priority=16; break;
- case OP_ASSIGN_SUB: priority=16; break;
- case OP_ASSIGN_MUL: priority=16; break;
- case OP_ASSIGN_DIV: priority=16; break;
- case OP_ASSIGN_MOD: priority=16; break;
- case OP_ASSIGN_SHIFT_LEFT: priority=16; break;
- case OP_ASSIGN_SHIFT_RIGHT: priority=16; break;
- case OP_ASSIGN_BIT_AND: priority=16; break;
- case OP_ASSIGN_BIT_OR: priority=16; break;
- case OP_ASSIGN_BIT_XOR: priority=16; break;
- case OP_BIT_AND: priority=9; break;
- case OP_BIT_OR: priority=11; break;
- case OP_BIT_XOR: priority=10; break;
- case OP_BIT_INVERT: priority=3; unary=true; break;
- case OP_INCREMENT: priority=3; unary=true; break;
- case OP_DECREMENT: priority=3; unary=true; break;
- case OP_SELECT_IF: priority=15; ternary=true; break;
- case OP_SELECT_ELSE: priority=15; ternary=true; break;
-
- default: ERR_FAIL_V(NULL); //unexpected operator
-
- }
-
- if (priority<min_priority) {
+ switch (expression[i].op) {
+ case OP_EQUAL: priority = 8; break;
+ case OP_NOT_EQUAL: priority = 8; break;
+ case OP_LESS: priority = 7; break;
+ case OP_LESS_EQUAL: priority = 7; break;
+ case OP_GREATER: priority = 7; break;
+ case OP_GREATER_EQUAL: priority = 7; break;
+ case OP_AND: priority = 12; break;
+ case OP_OR: priority = 14; break;
+ case OP_NOT:
+ priority = 3;
+ unary = true;
+ break;
+ case OP_NEGATE:
+ priority = 3;
+ unary = true;
+ break;
+ case OP_ADD: priority = 5; break;
+ case OP_SUB: priority = 5; break;
+ case OP_MUL: priority = 4; break;
+ case OP_DIV: priority = 4; break;
+ case OP_MOD: priority = 4; break;
+ case OP_SHIFT_LEFT: priority = 6; break;
+ case OP_SHIFT_RIGHT: priority = 6; break;
+ case OP_ASSIGN: priority = 16; break;
+ case OP_ASSIGN_ADD: priority = 16; break;
+ case OP_ASSIGN_SUB: priority = 16; break;
+ case OP_ASSIGN_MUL: priority = 16; break;
+ case OP_ASSIGN_DIV: priority = 16; break;
+ case OP_ASSIGN_MOD: priority = 16; break;
+ case OP_ASSIGN_SHIFT_LEFT: priority = 16; break;
+ case OP_ASSIGN_SHIFT_RIGHT: priority = 16; break;
+ case OP_ASSIGN_BIT_AND: priority = 16; break;
+ case OP_ASSIGN_BIT_OR: priority = 16; break;
+ case OP_ASSIGN_BIT_XOR: priority = 16; break;
+ case OP_BIT_AND: priority = 9; break;
+ case OP_BIT_OR: priority = 11; break;
+ case OP_BIT_XOR: priority = 10; break;
+ case OP_BIT_INVERT:
+ priority = 3;
+ unary = true;
+ break;
+ case OP_INCREMENT:
+ priority = 3;
+ unary = true;
+ break;
+ case OP_DECREMENT:
+ priority = 3;
+ unary = true;
+ break;
+ case OP_SELECT_IF:
+ priority = 15;
+ ternary = true;
+ break;
+ case OP_SELECT_ELSE:
+ priority = 15;
+ ternary = true;
+ break;
+
+ default:
+ ERR_FAIL_V(NULL); //unexpected operator
+ }
+
+ if (priority < min_priority) {
// < is used for left to right (default)
// <= is used for right to left
- next_op=i;
- min_priority=priority;
- is_unary=unary;
- is_ternary=ternary;
+ next_op = i;
+ min_priority = priority;
+ is_unary = unary;
+ is_ternary = ternary;
}
-
}
- ERR_FAIL_COND_V(next_op==-1,NULL);
+ ERR_FAIL_COND_V(next_op == -1, NULL);
// OK! create operator..
// OK! create operator..
if (is_unary) {
- int expr_pos=next_op;
- while(expression[expr_pos].is_op) {
+ int expr_pos = next_op;
+ while (expression[expr_pos].is_op) {
expr_pos++;
- if (expr_pos==expression.size()) {
+ if (expr_pos == expression.size()) {
//can happen..
_set_error("Unexpected end of expression..");
return NULL;
@@ -2787,162 +2741,149 @@ ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const
}
//consecutively do unary opeators
- for(int i=expr_pos-1;i>=next_op;i--) {
+ for (int i = expr_pos - 1; i >= next_op; i--) {
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[i].op;
- op->arguments.push_back(expression[i+1].node);
-
- expression[i].is_op=false;
- expression[i].node=op;
+ op->op = expression[i].op;
+ op->arguments.push_back(expression[i + 1].node);
+ expression[i].is_op = false;
+ expression[i].node = op;
- if (!_validate_operator(op,&op->return_cache)) {
+ if (!_validate_operator(op, &op->return_cache)) {
String at;
- for(int i=0;i<op->arguments.size();i++) {
- if (i>0)
- at+=" and ";
- at+=get_datatype_name(op->arguments[i]->get_datatype());
-
+ for (int i = 0; i < op->arguments.size(); i++) {
+ if (i > 0)
+ at += " and ";
+ at += get_datatype_name(op->arguments[i]->get_datatype());
}
- _set_error("Invalid arguments to unary operator '"+get_operator_text(op->op)+"' :" +at);
+ _set_error("Invalid arguments to unary operator '" + get_operator_text(op->op) + "' :" + at);
return NULL;
}
- expression.remove(i+1);
+ expression.remove(i + 1);
}
} else if (is_ternary) {
- if (next_op <1 || next_op>=(expression.size()-1)) {
+ if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
- if (next_op+2 >= expression.size() || !expression[next_op+2].is_op || expression[next_op+2].op!=OP_SELECT_ELSE) {
+ if (next_op + 2 >= expression.size() || !expression[next_op + 2].is_op || expression[next_op + 2].op != OP_SELECT_ELSE) {
_set_error("Mising matching ':' for select operator");
return NULL;
}
-
-
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[next_op].op;
- op->arguments.push_back(expression[next_op-1].node);
- op->arguments.push_back(expression[next_op+1].node);
- op->arguments.push_back(expression[next_op+3].node);
+ op->op = expression[next_op].op;
+ op->arguments.push_back(expression[next_op - 1].node);
+ op->arguments.push_back(expression[next_op + 1].node);
+ op->arguments.push_back(expression[next_op + 3].node);
- expression[next_op-1].is_op=false;
- expression[next_op-1].node=op;
- if (!_validate_operator(op,&op->return_cache)) {
+ expression[next_op - 1].is_op = false;
+ expression[next_op - 1].node = op;
+ if (!_validate_operator(op, &op->return_cache)) {
String at;
- for(int i=0;i<op->arguments.size();i++) {
- if (i>0)
- at+=" and ";
- at+=get_datatype_name(op->arguments[i]->get_datatype());
-
+ for (int i = 0; i < op->arguments.size(); i++) {
+ if (i > 0)
+ at += " and ";
+ at += get_datatype_name(op->arguments[i]->get_datatype());
}
- _set_error("Invalid argument to ternary ?: operator: "+at);
+ _set_error("Invalid argument to ternary ?: operator: " + at);
return NULL;
}
- for(int i=0;i<4;i++) {
+ for (int i = 0; i < 4; i++) {
expression.remove(next_op);
}
} else {
- if (next_op <1 || next_op>=(expression.size()-1)) {
+ if (next_op < 1 || next_op >= (expression.size() - 1)) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
OperatorNode *op = alloc_node<OperatorNode>();
- op->op=expression[next_op].op;
+ op->op = expression[next_op].op;
- if (expression[next_op-1].is_op) {
+ if (expression[next_op - 1].is_op) {
_set_error("Parser bug..");
ERR_FAIL_V(NULL);
}
- if (expression[next_op+1].is_op) {
+ 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 an unary op in a valid combination,
// due to how precedence works, unaries will always dissapear first
_set_error("Parser bug..");
-
}
-
- 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
- expression[next_op-1].node=op;
+ 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
+ expression[next_op - 1].node = op;
//replace all 3 nodes by this operator and make it an expression
- if (!_validate_operator(op,&op->return_cache)) {
+ if (!_validate_operator(op, &op->return_cache)) {
String at;
- for(int i=0;i<op->arguments.size();i++) {
- if (i>0)
- at+=" and ";
- at+=get_datatype_name(op->arguments[i]->get_datatype());
-
+ for (int i = 0; i < op->arguments.size(); i++) {
+ if (i > 0)
+ at += " and ";
+ at += get_datatype_name(op->arguments[i]->get_datatype());
}
- _set_error("Invalid arguments to operator '"+get_operator_text(op->op)+"' :" +at);
+ _set_error("Invalid arguments to operator '" + get_operator_text(op->op) + "' :" + at);
return NULL;
}
expression.remove(next_op);
expression.remove(next_op);
}
-
}
return expression[0].node;
}
+ShaderLanguage::Node *ShaderLanguage::_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node) {
-ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node) {
-
- if (p_node->type!=Node::TYPE_OPERATOR)
+ if (p_node->type != Node::TYPE_OPERATOR)
return p_node;
//for now only reduce simple constructors
- OperatorNode *op=static_cast<OperatorNode*>(p_node);
-
- if (op->op==OP_CONSTRUCT) {
+ OperatorNode *op = static_cast<OperatorNode *>(p_node);
+ if (op->op == OP_CONSTRUCT) {
- ERR_FAIL_COND_V(op->arguments[0]->type!=Node::TYPE_VARIABLE,p_node);
- VariableNode *vn = static_cast<VariableNode*>(op->arguments[0]);
+ ERR_FAIL_COND_V(op->arguments[0]->type != Node::TYPE_VARIABLE, p_node);
+ VariableNode *vn = static_cast<VariableNode *>(op->arguments[0]);
//StringName name=vn->name;
- DataType base=get_scalar_type(op->get_datatype());
+ DataType base = get_scalar_type(op->get_datatype());
Vector<ConstantNode::Value> values;
+ for (int i = 1; i < op->arguments.size(); i++) {
- for(int i=1;i<op->arguments.size();i++) {
-
-
- op->arguments[i]=_reduce_expression(p_block,op->arguments[i]);
- if (op->arguments[i]->type==Node::TYPE_CONSTANT) {
- ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[i]);
+ op->arguments[i] = _reduce_expression(p_block, op->arguments[i]);
+ if (op->arguments[i]->type == Node::TYPE_CONSTANT) {
+ ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[i]);
- if (get_scalar_type(cn->datatype)==base) {
+ if (get_scalar_type(cn->datatype) == base) {
- for(int j=0;j<cn->values.size();j++) {
+ for (int j = 0; j < cn->values.size(); j++) {
values.push_back(cn->values[j]);
}
- } else if (get_scalar_type(cn->datatype)==cn->datatype) {
+ } else if (get_scalar_type(cn->datatype) == cn->datatype) {
ConstantNode::Value v;
- if (!convert_constant(cn,base,&v)) {
+ if (!convert_constant(cn, base, &v)) {
return p_node;
}
values.push_back(v);
@@ -2955,37 +2896,36 @@ ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, Sha
}
}
-
- ConstantNode *cn=alloc_node<ConstantNode>();
- cn->datatype=op->get_datatype();
- cn->values=values;
+ ConstantNode *cn = alloc_node<ConstantNode>();
+ cn->datatype = op->get_datatype();
+ cn->values = values;
return cn;
- } else if (op->op==OP_NEGATE) {
+ } else if (op->op == OP_NEGATE) {
- op->arguments[0]=_reduce_expression(p_block,op->arguments[0]);
- if (op->arguments[0]->type==Node::TYPE_CONSTANT) {
+ op->arguments[0] = _reduce_expression(p_block, op->arguments[0]);
+ if (op->arguments[0]->type == Node::TYPE_CONSTANT) {
- ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[0]);
+ ConstantNode *cn = static_cast<ConstantNode *>(op->arguments[0]);
- DataType base=get_scalar_type(cn->datatype);
+ DataType base = get_scalar_type(cn->datatype);
Vector<ConstantNode::Value> values;
- for(int i=0;i<cn->values.size();i++) {
+ for (int i = 0; i < cn->values.size(); i++) {
ConstantNode::Value nv;
- switch(base) {
+ switch (base) {
case TYPE_BOOL: {
- nv.boolean=!cn->values[i].boolean;
+ nv.boolean = !cn->values[i].boolean;
} break;
case TYPE_INT: {
- nv.sint=-cn->values[i].sint;
+ nv.sint = -cn->values[i].sint;
} break;
case TYPE_UINT: {
- nv.uint=-cn->values[i].uint;
+ nv.uint = -cn->values[i].uint;
} break;
case TYPE_FLOAT: {
- nv.real=-cn->values[i].real;
+ nv.real = -cn->values[i].real;
} break;
default: {}
}
@@ -2993,41 +2933,33 @@ ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, Sha
values.push_back(nv);
}
-
- cn->values=values;
+ cn->values = values;
return cn;
}
}
return p_node;
-
-
}
+ShaderLanguage::Node *ShaderLanguage::_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types) {
-ShaderLanguage::Node* ShaderLanguage::_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types) {
-
-
- ShaderLanguage::Node* expr = _parse_expression(p_block,p_builtin_types);
+ ShaderLanguage::Node *expr = _parse_expression(p_block, p_builtin_types);
if (!expr) //errored
return NULL;
- expr = _reduce_expression(p_block,expr);
+ expr = _reduce_expression(p_block, expr);
return expr;
}
+Error ShaderLanguage::_parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one, bool p_can_break, bool p_can_continue) {
-
-
-Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,bool p_just_one,bool p_can_break,bool p_can_continue) {
-
- while(true) {
+ while (true) {
TkPos pos = _get_tkpos();
Token tk = _get_token();
- if (tk.type==TK_CURLY_BRACKET_CLOSE) { //end of block
+ if (tk.type == TK_CURLY_BRACKET_CLOSE) { //end of block
if (p_just_one) {
_set_error("Unexpected '}'");
return ERR_PARSE_ERROR;
@@ -3036,9 +2968,9 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT
return OK;
} else if (is_token_precision(tk.type) || is_token_nonvoid_datatype(tk.type)) {
- DataPrecision precision=PRECISION_DEFAULT;
+ DataPrecision precision = PRECISION_DEFAULT;
if (is_token_precision(tk.type)) {
- precision=get_token_precision(tk.type);
+ precision = get_token_precision(tk.type);
tk = _get_token();
if (!is_token_nonvoid_datatype(tk.type)) {
_set_error("Expected datatype after precission");
@@ -3050,97 +2982,96 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT
tk = _get_token();
- while(true) {
+ while (true) {
- if (tk.type!=TK_IDENTIFIER) {
+ if (tk.type != TK_IDENTIFIER) {
_set_error("Expected identifier after type");
return ERR_PARSE_ERROR;
}
StringName name = tk.text;
- if (_find_identifier(p_block,p_builtin_types,name)) {
- _set_error("Redefinition of '"+String(name)+"'");
+ if (_find_identifier(p_block, p_builtin_types, name)) {
+ _set_error("Redefinition of '" + String(name) + "'");
return ERR_PARSE_ERROR;
}
BlockNode::Variable var;
- var.type=type;
- var.precision=precision;
- var.line=tk_line;
- p_block->variables[name]=var;
+ var.type = type;
+ var.precision = precision;
+ var.line = tk_line;
+ p_block->variables[name] = var;
tk = _get_token();
- if (tk.type==TK_OP_ASSIGN) {
+ if (tk.type == TK_OP_ASSIGN) {
//variable creted with assignment! must parse an expression
- Node* n = _parse_and_reduce_expression(p_block,p_builtin_types);
+ Node *n = _parse_and_reduce_expression(p_block, p_builtin_types);
if (!n)
return ERR_PARSE_ERROR;
OperatorNode *assign = alloc_node<OperatorNode>();
VariableNode *vnode = alloc_node<VariableNode>();
- vnode->name=name;
- vnode->datatype_cache=type;
+ vnode->name = name;
+ vnode->datatype_cache = type;
assign->arguments.push_back(vnode);
assign->arguments.push_back(n);
- assign->op=OP_ASSIGN;
+ assign->op = OP_ASSIGN;
p_block->statements.push_back(assign);
tk = _get_token();
}
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
tk = _get_token();
//another variable
- } else if (tk.type==TK_SEMICOLON) {
+ } else if (tk.type == TK_SEMICOLON) {
break;
} else {
_set_error("Expected ',' or ';' after variable");
return ERR_PARSE_ERROR;
}
}
- } else if (tk.type==TK_CURLY_BRACKET_OPEN) {
+ } else if (tk.type == TK_CURLY_BRACKET_OPEN) {
//a sub block, just because..
- BlockNode* block = alloc_node<BlockNode>();
- block->parent_block=p_block;
- _parse_block(block,p_builtin_types,false,p_can_break,p_can_continue);
+ BlockNode *block = alloc_node<BlockNode>();
+ block->parent_block = p_block;
+ _parse_block(block, p_builtin_types, false, p_can_break, p_can_continue);
p_block->statements.push_back(block);
- } else if (tk.type==TK_CF_IF) {
+ } else if (tk.type == TK_CF_IF) {
//if () {}
tk = _get_token();
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after if");
return ERR_PARSE_ERROR;
}
ControlFlowNode *cf = alloc_node<ControlFlowNode>();
- cf->flow_op=FLOW_OP_IF;
- Node* n = _parse_and_reduce_expression(p_block,p_builtin_types);
+ cf->flow_op = FLOW_OP_IF;
+ Node *n = _parse_and_reduce_expression(p_block, p_builtin_types);
if (!n)
return ERR_PARSE_ERROR;
tk = _get_token();
- if (tk.type!=TK_PARENTHESIS_CLOSE) {
+ if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected '(' after expression");
return ERR_PARSE_ERROR;
}
- BlockNode* block = alloc_node<BlockNode>();
- block->parent_block=p_block;
+ BlockNode *block = alloc_node<BlockNode>();
+ block->parent_block = p_block;
cf->expressions.push_back(n);
cf->blocks.push_back(block);
p_block->statements.push_back(cf);
+ Error err = _parse_block(block, p_builtin_types, true, p_can_break, p_can_continue);
- Error err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue);
-
- pos=_get_tkpos();
+ pos = _get_tkpos();
tk = _get_token();
- if (tk.type==TK_CF_ELSE) {
+ if (tk.type == TK_CF_ELSE) {
block = alloc_node<BlockNode>();
- block->parent_block=p_block;
+ block->parent_block = p_block;
cf->blocks.push_back(block);
- err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue);
+ err = _parse_block(block, p_builtin_types, true, p_can_break, p_can_continue);
} else {
_set_tkpos(pos); //rollback
@@ -3150,13 +3081,13 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT
//nothng else, so expression
_set_tkpos(pos); //rollback
- Node*expr = _parse_and_reduce_expression(p_block,p_builtin_types);
+ Node *expr = _parse_and_reduce_expression(p_block, p_builtin_types);
if (!expr)
return ERR_PARSE_ERROR;
p_block->statements.push_back(expr);
tk = _get_token();
- if (tk.type!=TK_SEMICOLON) {
+ if (tk.type != TK_SEMICOLON) {
_set_error("Expected ';' after statement");
return ERR_PARSE_ERROR;
}
@@ -3169,49 +3100,47 @@ Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataT
return OK;
}
-
-Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) {
-
+Error ShaderLanguage::_parse_shader(const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes) {
Token tk = _get_token();
int texture_uniforms = 0;
- int uniforms =0;
+ int uniforms = 0;
- while(tk.type!=TK_EOF) {
+ while (tk.type != TK_EOF) {
- switch(tk.type) {
+ switch (tk.type) {
case TK_RENDER_MODE: {
- while(true) {
+ while (true) {
StringName mode;
- _get_completable_identifier(NULL,COMPLETION_RENDER_MODE,mode);
+ _get_completable_identifier(NULL, COMPLETION_RENDER_MODE, mode);
- if (mode==StringName()) {
+ if (mode == StringName()) {
_set_error("Expected identifier for render mode");
return ERR_PARSE_ERROR;
}
if (!p_render_modes.has(mode)) {
- _set_error("Invalid render mode: '"+String(mode)+"'");
+ _set_error("Invalid render mode: '" + String(mode) + "'");
return ERR_PARSE_ERROR;
}
- if (shader->render_modes.find(mode)!=-1) {
- _set_error("Duplicate render mode: '"+String(mode)+"'");
+ if (shader->render_modes.find(mode) != -1) {
+ _set_error("Duplicate render mode: '" + String(mode) + "'");
return ERR_PARSE_ERROR;
}
shader->render_modes.push_back(mode);
tk = _get_token();
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
//all good, do nothing
- } else if (tk.type==TK_SEMICOLON) {
+ } else if (tk.type == TK_SEMICOLON) {
break; //done
} else {
- _set_error("Unexpected token: "+get_token_text(tk));
+ _set_error("Unexpected token: " + get_token_text(tk));
return ERR_PARSE_ERROR;
}
}
@@ -3219,14 +3148,14 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
case TK_UNIFORM:
case TK_VARYING: {
- bool uniform = tk.type==TK_UNIFORM;
+ bool uniform = tk.type == TK_UNIFORM;
DataPrecision precision = PRECISION_DEFAULT;
DataType type;
StringName name;
tk = _get_token();
if (is_token_precision(tk.type)) {
- precision=get_token_precision(tk.type);
+ precision = get_token_precision(tk.type);
tk = _get_token();
}
@@ -3237,25 +3166,25 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
type = get_token_datatype(tk.type);
- if (type==TYPE_VOID) {
+ if (type == TYPE_VOID) {
_set_error("void datatype not allowed here");
return ERR_PARSE_ERROR;
}
- if (!uniform && type<TYPE_FLOAT && type>TYPE_VEC4) { // FIXME: always false! should it be || instead?
+ if (!uniform && type < TYPE_FLOAT && type > TYPE_VEC4) { // FIXME: always false! should it be || instead?
_set_error("Invalid type for varying, only float,vec2,vec3,vec4 allowed.");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- if (tk.type!=TK_IDENTIFIER) {
+ if (tk.type != TK_IDENTIFIER) {
_set_error("Expected identifier!");
return ERR_PARSE_ERROR;
}
- name=tk.text;
+ name = tk.text;
- if (_find_identifier(NULL,Map<StringName,DataType>(),name)) {
- _set_error("Redefinition of '"+String(name)+"'");
+ if (_find_identifier(NULL, Map<StringName, DataType>(), name)) {
+ _set_error("Redefinition of '" + String(name) + "'");
return ERR_PARSE_ERROR;
}
@@ -3264,179 +3193,173 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
ShaderNode::Uniform uniform;
if (is_sampler_type(type)) {
- uniform.texture_order=texture_uniforms++;
- uniform.order=-1;
+ uniform.texture_order = texture_uniforms++;
+ uniform.order = -1;
} else {
- uniform.texture_order=-1;
- uniform.order=uniforms++;
+ uniform.texture_order = -1;
+ uniform.order = uniforms++;
}
- uniform.type=type;
- uniform.precission=precision;
+ uniform.type = type;
+ uniform.precission = precision;
//todo parse default value
tk = _get_token();
- if (tk.type==TK_OP_ASSIGN) {
+ if (tk.type == TK_OP_ASSIGN) {
- Node* expr = _parse_and_reduce_expression(NULL,Map<StringName,DataType>());
+ Node *expr = _parse_and_reduce_expression(NULL, Map<StringName, DataType>());
if (!expr)
return ERR_PARSE_ERROR;
- if (expr->type!=Node::TYPE_CONSTANT) {
+ if (expr->type != Node::TYPE_CONSTANT) {
_set_error("Expected constant expression after '='");
return ERR_PARSE_ERROR;
}
- ConstantNode* cn = static_cast<ConstantNode*>(expr);
+ ConstantNode *cn = static_cast<ConstantNode *>(expr);
uniform.default_value.resize(cn->values.size());
- if (!convert_constant(cn,uniform.type,uniform.default_value.ptr())) {
- _set_error("Can't convert constant to "+get_datatype_name(uniform.type));
+ if (!convert_constant(cn, uniform.type, uniform.default_value.ptr())) {
+ _set_error("Can't convert constant to " + get_datatype_name(uniform.type));
return ERR_PARSE_ERROR;
}
tk = _get_token();
}
- if (tk.type==TK_COLON) {
+ if (tk.type == TK_COLON) {
//hint
tk = _get_token();
- if (tk.type==TK_HINT_WHITE_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_WHITE;
- } else if (tk.type==TK_HINT_BLACK_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_BLACK;
- } else if (tk.type==TK_HINT_NORMAL_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_NORMAL;
- } else if (tk.type==TK_HINT_ANISO_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_ANISO;
- } else if (tk.type==TK_HINT_ALBEDO_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_ALBEDO;
- } else if (tk.type==TK_HINT_BLACK_ALBEDO_TEXTURE) {
- uniform.hint=ShaderNode::Uniform::HINT_BLACK_ALBEDO;
- } else if (tk.type==TK_HINT_COLOR) {
- if (type!=TYPE_VEC4) {
+ if (tk.type == TK_HINT_WHITE_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_WHITE;
+ } else if (tk.type == TK_HINT_BLACK_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_BLACK;
+ } else if (tk.type == TK_HINT_NORMAL_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_NORMAL;
+ } else if (tk.type == TK_HINT_ANISO_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_ANISO;
+ } else if (tk.type == TK_HINT_ALBEDO_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_ALBEDO;
+ } else if (tk.type == TK_HINT_BLACK_ALBEDO_TEXTURE) {
+ uniform.hint = ShaderNode::Uniform::HINT_BLACK_ALBEDO;
+ } else if (tk.type == TK_HINT_COLOR) {
+ if (type != TYPE_VEC4) {
_set_error("Color hint is for vec4 only");
return ERR_PARSE_ERROR;
}
- uniform.hint=ShaderNode::Uniform::HINT_COLOR;
- } else if (tk.type==TK_HINT_RANGE) {
+ uniform.hint = ShaderNode::Uniform::HINT_COLOR;
+ } else if (tk.type == TK_HINT_RANGE) {
- uniform.hint=ShaderNode::Uniform::HINT_RANGE;
- if (type!=TYPE_FLOAT && type!=TYPE_INT) {
+ uniform.hint = ShaderNode::Uniform::HINT_RANGE;
+ if (type != TYPE_FLOAT && type != TYPE_INT) {
_set_error("Range hint is for float and int only");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after hint_range");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- float sign=1.0;
+ float sign = 1.0;
- if (tk.type==TK_OP_SUB) {
- sign=-1.0;
+ if (tk.type == TK_OP_SUB) {
+ sign = -1.0;
tk = _get_token();
}
- if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) {
+ if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) {
_set_error("Expected integer constant");
return ERR_PARSE_ERROR;
}
- uniform.hint_range[0]=tk.constant;
- uniform.hint_range[0]*=sign;
+ uniform.hint_range[0] = tk.constant;
+ uniform.hint_range[0] *= sign;
tk = _get_token();
- if (tk.type!=TK_COMMA) {
+ if (tk.type != TK_COMMA) {
_set_error("Expected ',' after integer constant");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- sign=1.0;
+ sign = 1.0;
- if (tk.type==TK_OP_SUB) {
- sign=-1.0;
+ if (tk.type == TK_OP_SUB) {
+ sign = -1.0;
tk = _get_token();
}
-
- if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) {
+ if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) {
_set_error("Expected integer constant after ','");
return ERR_PARSE_ERROR;
}
- uniform.hint_range[1]=tk.constant;
- uniform.hint_range[1]*=sign;
+ uniform.hint_range[1] = tk.constant;
+ uniform.hint_range[1] *= sign;
tk = _get_token();
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
tk = _get_token();
- if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) {
+ if (tk.type != TK_REAL_CONSTANT && tk.type != TK_INT_CONSTANT) {
_set_error("Expected integer constant after ','");
return ERR_PARSE_ERROR;
}
- uniform.hint_range[2]=tk.constant;
+ uniform.hint_range[2] = tk.constant;
tk = _get_token();
} else {
- if (type==TYPE_INT) {
- uniform.hint_range[2]=1;
+ if (type == TYPE_INT) {
+ uniform.hint_range[2] = 1;
} else {
- uniform.hint_range[2]=0.001;
+ uniform.hint_range[2] = 0.001;
}
}
- if (tk.type!=TK_PARENTHESIS_CLOSE) {
+ if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected ','");
return ERR_PARSE_ERROR;
}
-
} else {
_set_error("Expected valid type hint after ':'.");
}
- if (uniform.hint!=ShaderNode::Uniform::HINT_RANGE && uniform.hint!=ShaderNode::Uniform::HINT_NONE && uniform.hint!=ShaderNode::Uniform::HINT_COLOR && type <=TYPE_MAT4) {
+ if (uniform.hint != ShaderNode::Uniform::HINT_RANGE && uniform.hint != ShaderNode::Uniform::HINT_NONE && uniform.hint != ShaderNode::Uniform::HINT_COLOR && type <= TYPE_MAT4) {
_set_error("This hint is only for sampler types");
return ERR_PARSE_ERROR;
-
}
tk = _get_token();
}
- shader->uniforms[name]=uniform;
+ shader->uniforms[name] = uniform;
- if (tk.type!=TK_SEMICOLON) {
+ if (tk.type != TK_SEMICOLON) {
_set_error("Expected ';'");
return ERR_PARSE_ERROR;
}
} else {
ShaderNode::Varying varying;
- varying.type=type;
- varying.precission=precision;
- shader->varyings[name]=varying;
+ varying.type = type;
+ varying.precission = precision;
+ shader->varyings[name] = varying;
tk = _get_token();
- if (tk.type!=TK_SEMICOLON) {
+ if (tk.type != TK_SEMICOLON) {
_set_error("Expected ';'");
return ERR_PARSE_ERROR;
}
-
}
-
-
} break;
default: {
//function
@@ -3446,7 +3369,7 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
StringName name;
if (is_token_precision(tk.type)) {
- precision=get_token_precision(tk.type);
+ precision = get_token_precision(tk.type);
tk = _get_token();
}
@@ -3457,56 +3380,51 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
type = get_token_datatype(tk.type);
- _get_completable_identifier(NULL,COMPLETION_MAIN_FUNCTION,name);
+ _get_completable_identifier(NULL, COMPLETION_MAIN_FUNCTION, name);
- if (name==StringName()) {
+ if (name == StringName()) {
_set_error("Expected function name after datatype");
return ERR_PARSE_ERROR;
-
}
-
- if (_find_identifier(NULL,Map<StringName,DataType>(),name)) {
- _set_error("Redefinition of '"+String(name)+"'");
+ if (_find_identifier(NULL, Map<StringName, DataType>(), name)) {
+ _set_error("Redefinition of '" + String(name) + "'");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- if (tk.type!=TK_PARENTHESIS_OPEN) {
+ if (tk.type != TK_PARENTHESIS_OPEN) {
_set_error("Expected '(' after identifier");
return ERR_PARSE_ERROR;
-
}
-
- Map<StringName,DataType> builtin_types;
+ Map<StringName, DataType> builtin_types;
if (p_functions.has(name)) {
- builtin_types=p_functions[name];
+ builtin_types = p_functions[name];
}
ShaderNode::Function function;
- function.callable=!p_functions.has(name);
- function.name=name;
+ function.callable = !p_functions.has(name);
+ function.name = name;
- FunctionNode* func_node=alloc_node<FunctionNode>();
+ FunctionNode *func_node = alloc_node<FunctionNode>();
- function.function=func_node;
+ function.function = func_node;
shader->functions.push_back(function);
- func_node->name=name;
- func_node->return_type=type;
- func_node->return_precision=precision;
+ func_node->name = name;
+ func_node->return_type = type;
+ func_node->return_precision = precision;
func_node->body = alloc_node<BlockNode>();
- func_node->body->parent_function=func_node;
-
+ func_node->body->parent_function = func_node;
tk = _get_token();
- while(true) {
- if (tk.type==TK_PARENTHESIS_CLOSE) {
+ while (true) {
+ if (tk.type == TK_PARENTHESIS_CLOSE) {
break;
}
@@ -3515,7 +3433,7 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
DataPrecision pprecision = PRECISION_DEFAULT;
if (is_token_precision(tk.type)) {
- pprecision=get_token_precision(tk.type);
+ pprecision = get_token_precision(tk.type);
tk = _get_token();
}
@@ -3524,73 +3442,70 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
return ERR_PARSE_ERROR;
}
- ptype=get_token_datatype(tk.type);
+ ptype = get_token_datatype(tk.type);
- if (ptype==TYPE_VOID) {
+ if (ptype == TYPE_VOID) {
_set_error("void not allowed in argument");
return ERR_PARSE_ERROR;
}
tk = _get_token();
- if (tk.type!=TK_IDENTIFIER) {
+ if (tk.type != TK_IDENTIFIER) {
_set_error("Expected identifier for argument name");
return ERR_PARSE_ERROR;
}
pname = tk.text;
- if (_find_identifier(func_node->body,builtin_types,pname)) {
- _set_error("Redefinition of '"+String(pname)+"'");
+ if (_find_identifier(func_node->body, builtin_types, pname)) {
+ _set_error("Redefinition of '" + String(pname) + "'");
return ERR_PARSE_ERROR;
}
FunctionNode::Argument arg;
- arg.type=ptype;
- arg.name=pname;
- arg.precision=pprecision;
+ arg.type = ptype;
+ arg.name = pname;
+ arg.precision = pprecision;
func_node->arguments.push_back(arg);
tk = _get_token();
-
- if (tk.type==TK_COMMA) {
+ if (tk.type == TK_COMMA) {
tk = _get_token();
//do none and go on
- } else if (tk.type!=TK_PARENTHESIS_CLOSE) {
+ } else if (tk.type != TK_PARENTHESIS_CLOSE) {
_set_error("Expected ',' or ')' after identifier");
return ERR_PARSE_ERROR;
}
-
}
if (p_functions.has(name)) {
//if one of the core functions, make sure they are of the correct form
if (func_node->arguments.size() > 0) {
- _set_error("Function '"+String(name)+"' expects no arguments.");
+ _set_error("Function '" + String(name) + "' expects no arguments.");
return ERR_PARSE_ERROR;
}
- if (func_node->return_type!=TYPE_VOID) {
- _set_error("Function '"+String(name)+"' must be of void return type.");
+ if (func_node->return_type != TYPE_VOID) {
+ _set_error("Function '" + String(name) + "' must be of void return type.");
return ERR_PARSE_ERROR;
}
}
-
//all good let's parse inside the fucntion!
tk = _get_token();
- if (tk.type!=TK_CURLY_BRACKET_OPEN) {
+ if (tk.type != TK_CURLY_BRACKET_OPEN) {
_set_error("Expected '{' to begin function");
return ERR_PARSE_ERROR;
}
current_function = name;
- Error err = _parse_block(func_node->body,builtin_types);
+ Error err = _parse_block(func_node->body, builtin_types);
if (err)
return err;
- current_function=StringName();
+ current_function = StringName();
}
}
@@ -3600,42 +3515,42 @@ Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataTy
return OK;
}
-Error ShaderLanguage::compile(const String& p_code, const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) {
+Error ShaderLanguage::compile(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes) {
clear();
- code=p_code;
+ code = p_code;
- nodes=NULL;
+ nodes = NULL;
shader = alloc_node<ShaderNode>();
- Error err = _parse_shader(p_functions,p_render_modes);
+ Error err = _parse_shader(p_functions, p_render_modes);
- if (err!=OK) {
+ if (err != OK) {
return err;
}
return OK;
}
-Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes,List<String>* r_options,String& r_call_hint) {
+Error ShaderLanguage::complete(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes, List<String> *r_options, String &r_call_hint) {
clear();
- code=p_code;
+ code = p_code;
- nodes=NULL;
+ nodes = NULL;
shader = alloc_node<ShaderNode>();
- Error err = _parse_shader(p_functions,p_render_modes);
+ Error err = _parse_shader(p_functions, p_render_modes);
- switch(completion_type) {
+ switch (completion_type) {
case COMPLETION_NONE: {
//do none
return ERR_PARSE_ERROR;
} break;
case COMPLETION_RENDER_MODE: {
- for(const Set<String>::Element *E=p_render_modes.front();E;E=E->next()) {
+ for (const Set<String>::Element *E = p_render_modes.front(); E; E = E->next()) {
r_options->push_back(E->get());
}
@@ -3644,7 +3559,7 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S
} break;
case COMPLETION_MAIN_FUNCTION: {
- for(const Map< StringName, Map<StringName,DataType> >::Element *E=p_functions.front();E;E=E->next()) {
+ for (const Map<StringName, Map<StringName, DataType> >::Element *E = p_functions.front(); E; E = E->next()) {
r_options->push_back(E->key());
}
@@ -3654,71 +3569,66 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S
case COMPLETION_IDENTIFIER:
case COMPLETION_FUNCTION_CALL: {
- bool comp_ident=completion_type==COMPLETION_IDENTIFIER;
+ bool comp_ident = completion_type == COMPLETION_IDENTIFIER;
Set<String> matches;
StringName skip_function;
- BlockNode *block=completion_block;
+ BlockNode *block = completion_block;
-
- while(block) {
+ while (block) {
if (comp_ident) {
- for (const Map<StringName,BlockNode::Variable>::Element *E=block->variables.front();E;E=E->next()) {
+ for (const Map<StringName, BlockNode::Variable>::Element *E = block->variables.front(); E; E = E->next()) {
- if (E->get().line<completion_line) {
+ if (E->get().line < completion_line) {
matches.insert(E->key());
}
}
}
-
if (block->parent_function) {
if (comp_ident) {
- for(int i=0;i<block->parent_function->arguments.size();i++) {
+ for (int i = 0; i < block->parent_function->arguments.size(); i++) {
matches.insert(block->parent_function->arguments[i].name);
}
}
- skip_function=block->parent_function->name;
+ skip_function = block->parent_function->name;
}
- block=block->parent_block;
+ block = block->parent_block;
}
- if (comp_ident && skip_function!=StringName() && p_functions.has(skip_function)) {
+ if (comp_ident && skip_function != StringName() && p_functions.has(skip_function)) {
- for (Map<StringName,DataType>::Element *E=p_functions[skip_function].front();E;E=E->next()) {
+ for (Map<StringName, DataType>::Element *E = p_functions[skip_function].front(); E; E = E->next()) {
matches.insert(E->key());
}
}
if (comp_ident) {
- for (const Map<StringName,ShaderNode::Varying>::Element *E=shader->varyings.front();E;E=E->next()) {
+ for (const Map<StringName, ShaderNode::Varying>::Element *E = shader->varyings.front(); E; E = E->next()) {
matches.insert(E->key());
-
}
- for (const Map<StringName,ShaderNode::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) {
+ for (const Map<StringName, ShaderNode::Uniform>::Element *E = shader->uniforms.front(); E; E = E->next()) {
matches.insert(E->key());
}
-
-
}
- for(int i=0;i<shader->functions.size();i++) {
- if (!shader->functions[i].callable || shader->functions[i].name==skip_function)
+ for (int i = 0; i < shader->functions.size(); i++) {
+ if (!shader->functions[i].callable || shader->functions[i].name == skip_function)
continue;
- matches.insert(String(shader->functions[i].name)+"(");
+ matches.insert(String(shader->functions[i].name) + "(");
}
- int idx=0;
+ int idx = 0;
while (builtin_func_defs[idx].name) {
- matches.insert(String(builtin_func_defs[idx].name)+"(");
+ matches.insert(String(builtin_func_defs[idx].name) + "(");
idx++;
}
- for(Set<String>::Element *E=matches.front();E;E=E->next()) {
+ for (Set<String>::Element *E = matches.front(); E; E = E->next()) {
r_options->push_back(E->get());
}
@@ -3727,118 +3637,112 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S
} break;
case COMPLETION_CALL_ARGUMENTS: {
- for(int i=0;i<shader->functions.size();i++) {
+ for (int i = 0; i < shader->functions.size(); i++) {
if (!shader->functions[i].callable)
continue;
- if (shader->functions[i].name==completion_function) {
+ if (shader->functions[i].name == completion_function) {
String calltip;
- calltip+=get_datatype_name( shader->functions[i].function->return_type );
- calltip+=" ";
- calltip+=shader->functions[i].name;
- calltip+="(";
+ calltip += get_datatype_name(shader->functions[i].function->return_type);
+ calltip += " ";
+ calltip += shader->functions[i].name;
+ calltip += "(";
- for(int j=0;j<shader->functions[i].function->arguments.size();j++) {
+ for (int j = 0; j < shader->functions[i].function->arguments.size(); j++) {
- if (j>0)
- calltip+=", ";
+ if (j > 0)
+ calltip += ", ";
else
- calltip+=" ";
+ calltip += " ";
- if (j==completion_argument) {
- calltip+=CharType(0xFFFF);
+ if (j == completion_argument) {
+ calltip += CharType(0xFFFF);
}
- calltip+=get_datatype_name(shader->functions[i].function->arguments[j].type);
- calltip+=" ";
- calltip+=shader->functions[i].function->arguments[j].name;
+ calltip += get_datatype_name(shader->functions[i].function->arguments[j].type);
+ calltip += " ";
+ calltip += shader->functions[i].function->arguments[j].name;
- if (j==completion_argument) {
- calltip+=CharType(0xFFFF);
+ if (j == completion_argument) {
+ calltip += CharType(0xFFFF);
}
-
}
if (shader->functions[i].function->arguments.size())
- calltip+=" ";
- calltip+=")";
+ calltip += " ";
+ calltip += ")";
- r_call_hint=calltip;
+ r_call_hint = calltip;
return OK;
}
-
}
- int idx=0;
+ int idx = 0;
String calltip;
while (builtin_func_defs[idx].name) {
- if (completion_function==builtin_func_defs[idx].name) {
+ if (completion_function == builtin_func_defs[idx].name) {
if (calltip.length())
- calltip+="\n";
+ calltip += "\n";
- calltip+=get_datatype_name( builtin_func_defs[idx].rettype );
- calltip+=" ";
- calltip+=builtin_func_defs[idx].name;
- calltip+="(";
+ calltip += get_datatype_name(builtin_func_defs[idx].rettype);
+ calltip += " ";
+ calltip += builtin_func_defs[idx].name;
+ calltip += "(";
- bool found_arg=false;
- for(int i=0;i<4;i++) {
+ bool found_arg = false;
+ for (int i = 0; i < 4; i++) {
- if (builtin_func_defs[idx].args[i]==TYPE_VOID)
+ if (builtin_func_defs[idx].args[i] == TYPE_VOID)
break;
- if (i>0)
- calltip+=", ";
+ if (i > 0)
+ calltip += ", ";
else
- calltip+=" ";
+ calltip += " ";
- if (i==completion_argument) {
- calltip+=CharType(0xFFFF);
+ if (i == completion_argument) {
+ calltip += CharType(0xFFFF);
}
- calltip+=get_datatype_name(builtin_func_defs[idx].args[i]);
+ calltip += get_datatype_name(builtin_func_defs[idx].args[i]);
- if (i==completion_argument) {
- calltip+=CharType(0xFFFF);
+ if (i == completion_argument) {
+ calltip += CharType(0xFFFF);
}
- found_arg=true;
-
+ found_arg = true;
}
if (found_arg)
- calltip+=" ";
- calltip+=")";
-
-
+ calltip += " ";
+ calltip += ")";
}
idx++;
}
- r_call_hint=calltip;
+ r_call_hint = calltip;
return OK;
} break;
case COMPLETION_INDEX: {
- const char colv[4]={'r','g','b','a'};
- const char coordv[4]={'x','y','z','w'};
+ const char colv[4] = { 'r', 'g', 'b', 'a' };
+ const char coordv[4] = { 'x', 'y', 'z', 'w' };
+ int limit = 0;
- int limit=0;
-
- switch(completion_base) {
+ switch (completion_base) {
case TYPE_BVEC2:
case TYPE_IVEC2:
case TYPE_UVEC2:
case TYPE_VEC2: {
- limit=2;
+ limit = 2;
} break;
case TYPE_BVEC3:
@@ -3846,7 +3750,7 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S
case TYPE_UVEC3:
case TYPE_VEC3: {
- limit=3;
+ limit = 3;
} break;
case TYPE_BVEC4:
@@ -3854,23 +3758,21 @@ Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<S
case TYPE_UVEC4:
case TYPE_VEC4: {
- limit=4;
+ limit = 4;
} break;
- case TYPE_MAT2: limit=2; break;
- case TYPE_MAT3: limit=3; break;
- case TYPE_MAT4: limit=4; break;
+ case TYPE_MAT2: limit = 2; break;
+ case TYPE_MAT3: limit = 3; break;
+ case TYPE_MAT4: limit = 4; break;
default: {}
}
- for(int i=0;i<limit;i++) {
+ for (int i = 0; i < limit; i++) {
r_options->push_back(String::chr(colv[i]));
r_options->push_back(String::chr(coordv[i]));
}
} break;
-
-
}
return ERR_PARSE_ERROR;
@@ -3893,12 +3795,10 @@ ShaderLanguage::ShaderNode *ShaderLanguage::get_shader() {
ShaderLanguage::ShaderLanguage() {
- nodes=NULL;
+ nodes = NULL;
}
ShaderLanguage::~ShaderLanguage() {
clear();
}
-
-
diff --git a/servers/visual/shader_language.h b/servers/visual/shader_language.h
index 4f8717088e..a4757e3419 100644
--- a/servers/visual/shader_language.h
+++ b/servers/visual/shader_language.h
@@ -29,20 +29,16 @@
#ifndef SHADER_LANGUAGE_H
#define SHADER_LANGUAGE_H
-#include "typedefs.h"
-#include "ustring.h"
#include "list.h"
-#include "string_db.h"
#include "map.h"
+#include "string_db.h"
+#include "typedefs.h"
+#include "ustring.h"
#include "variant.h"
-
-class ShaderLanguage {
-
-
+class ShaderLanguage {
public:
-
enum TokenType {
TK_EMPTY,
@@ -149,12 +145,12 @@ public:
TK_MAX
};
- /* COMPILER */
+/* COMPILER */
- // lame work around to Apple defining this as a macro in 10.12 SDK
- #ifdef TYPE_BOOL
- #undef TYPE_BOOL
- #endif
+// lame work around to Apple defining this as a macro in 10.12 SDK
+#ifdef TYPE_BOOL
+#undef TYPE_BOOL
+#endif
enum DataType {
TYPE_VOID,
@@ -268,26 +264,29 @@ public:
virtual ~Node() {}
};
- template<class T>
- T* alloc_node() {
- T* node = memnew(T);
- node->next=nodes;
- nodes=node;
+ template <class T>
+ T *alloc_node() {
+ T *node = memnew(T);
+ node->next = nodes;
+ nodes = node;
return node;
}
Node *nodes;
-
struct OperatorNode : public Node {
DataType return_cache;
DataPrecision return_precision_cache;
Operator op;
- Vector<Node*> arguments;
+ Vector<Node *> arguments;
virtual DataType get_datatype() const { return return_cache; }
- OperatorNode() { type=TYPE_OPERATOR; return_cache=TYPE_VOID; return_precision_cache=PRECISION_DEFAULT; }
+ OperatorNode() {
+ type = TYPE_OPERATOR;
+ return_cache = TYPE_VOID;
+ return_precision_cache = PRECISION_DEFAULT;
+ }
};
struct VariableNode : public Node {
@@ -295,7 +294,10 @@ public:
StringName name;
virtual DataType get_datatype() const { return datatype_cache; }
- VariableNode() { type=TYPE_VARIABLE; datatype_cache=TYPE_VOID; }
+ VariableNode() {
+ type = TYPE_VARIABLE;
+ datatype_cache = TYPE_VOID;
+ }
};
struct ConstantNode : public Node {
@@ -312,7 +314,7 @@ public:
Vector<Value> values;
virtual DataType get_datatype() const { return datatype; }
- ConstantNode() { type=TYPE_CONSTANT; }
+ ConstantNode() { type = TYPE_CONSTANT; }
};
struct FunctionNode;
@@ -327,17 +329,24 @@ public:
int line; //for completion
};
- Map<StringName,Variable> variables;
- List<Node*> statements;
- BlockNode() { type=TYPE_BLOCK; parent_block=NULL; parent_function=NULL; }
+ Map<StringName, Variable> variables;
+ List<Node *> statements;
+ BlockNode() {
+ type = TYPE_BLOCK;
+ parent_block = NULL;
+ parent_function = NULL;
+ }
};
struct ControlFlowNode : public Node {
FlowOperation flow_op;
- Vector<Node*> expressions;
- Vector<BlockNode*> blocks;
- ControlFlowNode() { type=TYPE_CONTROL_FLOW; flow_op=FLOW_OP_IF;}
+ Vector<Node *> expressions;
+ Vector<BlockNode *> blocks;
+ ControlFlowNode() {
+ type = TYPE_CONTROL_FLOW;
+ flow_op = FLOW_OP_IF;
+ }
};
struct MemberNode : public Node {
@@ -345,15 +354,13 @@ public:
DataType basetype;
DataType datatype;
StringName name;
- Node* owner;
+ Node *owner;
virtual DataType get_datatype() const { return datatype; }
- MemberNode() { type=TYPE_MEMBER; }
+ MemberNode() { type = TYPE_MEMBER; }
};
-
struct FunctionNode : public Node {
-
struct Argument {
StringName name;
@@ -367,16 +374,17 @@ public:
Vector<Argument> arguments;
BlockNode *body;
- FunctionNode() { type=TYPE_FUNCTION; return_precision=PRECISION_DEFAULT; }
-
+ FunctionNode() {
+ type = TYPE_FUNCTION;
+ return_precision = PRECISION_DEFAULT;
+ }
};
-
struct ShaderNode : public Node {
struct Function {
StringName name;
- FunctionNode*function;
+ FunctionNode *function;
Set<StringName> uses_function;
bool callable;
};
@@ -408,20 +416,23 @@ public:
Hint hint;
float hint_range[3];
- Uniform() { hint=HINT_NONE; hint_range[0]=0; hint_range[1]=1; hint_range[2]=0.001;}
+ Uniform() {
+ hint = HINT_NONE;
+ hint_range[0] = 0;
+ hint_range[1] = 1;
+ hint_range[2] = 0.001;
+ }
};
-
- Map<StringName,Varying> varyings;
- Map<StringName,Uniform> uniforms;
+ Map<StringName, Varying> varyings;
+ Map<StringName, Uniform> uniforms;
Vector<StringName> render_modes;
Vector<Function> functions;
- ShaderNode() { type=TYPE_SHADER; }
+ ShaderNode() { type = TYPE_SHADER; }
};
-
struct Expression {
bool is_op;
@@ -431,8 +442,6 @@ public:
};
};
-
-
struct VarInfo {
StringName name;
@@ -457,7 +466,6 @@ public:
uint16_t line;
};
-
static String get_operator_text(Operator p_op);
static String get_token_text(Token p_token);
@@ -469,16 +477,19 @@ public:
static bool is_token_nonvoid_datatype(TokenType p_type);
static bool is_token_operator(TokenType p_type);
- static bool convert_constant(ConstantNode* p_constant, DataType p_to_type,ConstantNode::Value *p_value=NULL);
+ static bool convert_constant(ConstantNode *p_constant, DataType p_to_type, ConstantNode::Value *p_value = NULL);
static DataType get_scalar_type(DataType p_type);
static bool is_scalar_type(DataType p_type);
static bool is_sampler_type(DataType p_type);
static void get_keyword_list(List<String> *r_keywords);
static void get_builtin_funcs(List<String> *r_keywords);
-private:
- struct KeyWord { TokenType token; const char *text;};
+private:
+ struct KeyWord {
+ TokenType token;
+ const char *text;
+ };
static const KeyWord keyword_list[];
bool error_set;
@@ -498,33 +509,28 @@ private:
TkPos _get_tkpos() {
TkPos tkp;
- tkp.char_idx=char_idx;
- tkp.tk_line=tk_line;
+ tkp.char_idx = char_idx;
+ tkp.tk_line = tk_line;
return tkp;
}
-
void _set_tkpos(TkPos p_pos) {
- char_idx=p_pos.char_idx;
- tk_line=p_pos.tk_line;
+ char_idx = p_pos.char_idx;
+ tk_line = p_pos.tk_line;
}
- void _set_error(const String& p_str) {
+ void _set_error(const String &p_str) {
if (error_set)
return;
- error_line=tk_line;
- error_set=true;
- error_str=p_str;
+ error_line = tk_line;
+ error_set = true;
+ error_str = p_str;
}
+ static const char *token_names[TK_MAX];
- static const char * token_names[TK_MAX];
-
-
-
-
- Token _make_token(TokenType p_type, const StringName& p_text=StringName());
+ Token _make_token(TokenType p_type, const StringName &p_text = StringName());
Token _get_token();
ShaderNode *shader;
@@ -538,18 +544,16 @@ private:
IDENTIFIER_BUILTIN_VAR,
};
- bool _find_identifier(const BlockNode* p_block,const Map<StringName, DataType> &p_builtin_types,const StringName& p_identifier, DataType *r_data_type=NULL, IdentifierType *r_type=NULL);
-
- bool _validate_operator(OperatorNode *p_op,DataType *r_ret_type=NULL);
+ bool _find_identifier(const BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, const StringName &p_identifier, DataType *r_data_type = NULL, IdentifierType *r_type = NULL);
+ bool _validate_operator(OperatorNode *p_op, DataType *r_ret_type = NULL);
struct BuiltinFuncDef {
- enum { MAX_ARGS=5 };
- const char* name;
+ enum { MAX_ARGS = 5 };
+ const char *name;
DataType rettype;
const DataType args[MAX_ARGS];
-
};
CompletionType completion_type;
@@ -559,44 +563,38 @@ private:
StringName completion_function;
int completion_argument;
-
- bool _get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName& identifier);
+ bool _get_completable_identifier(BlockNode *p_block, CompletionType p_type, StringName &identifier);
static const BuiltinFuncDef builtin_func_defs[];
- bool _validate_function_call(BlockNode* p_block, OperatorNode *p_func,DataType *r_ret_type);
-
- bool _parse_function_arguments(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types, OperatorNode* p_func, int *r_complete_arg=NULL);
+ bool _validate_function_call(BlockNode *p_block, OperatorNode *p_func, DataType *r_ret_type);
- Node* _parse_expression(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types);
+ bool _parse_function_arguments(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, OperatorNode *p_func, int *r_complete_arg = NULL);
- ShaderLanguage::Node* _reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node);
- Node* _parse_and_reduce_expression(BlockNode *p_block,const Map<StringName,DataType> &p_builtin_types);
+ Node *_parse_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types);
- Error _parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one=false, bool p_can_break=false, bool p_can_continue=false);
+ ShaderLanguage::Node *_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node);
+ Node *_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types);
- Error _parse_shader(const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes);
+ Error _parse_block(BlockNode *p_block, const Map<StringName, DataType> &p_builtin_types, bool p_just_one = false, bool p_can_break = false, bool p_can_continue = false);
+ Error _parse_shader(const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes);
public:
-
//static void get_keyword_list(ShaderType p_type,List<String> *p_keywords);
void clear();
- Error compile(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes);
- Error complete(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes,List<String>* r_options,String& r_call_hint);
-
-
+ Error compile(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes);
+ Error complete(const String &p_code, const Map<StringName, Map<StringName, DataType> > &p_functions, const Set<String> &p_render_modes, List<String> *r_options, String &r_call_hint);
String get_error_text();
int get_error_line();
ShaderNode *get_shader();
- String token_debug(const String& p_code);
+ String token_debug(const String &p_code);
ShaderLanguage();
~ShaderLanguage();
};
-
#endif // SHADER_LANGUAGE_H
diff --git a/servers/visual/shader_types.cpp b/servers/visual/shader_types.cpp
index d119e81a4b..cd9afa7735 100644
--- a/servers/visual/shader_types.cpp
+++ b/servers/visual/shader_types.cpp
@@ -28,85 +28,82 @@
/*************************************************************************/
#include "shader_types.h"
-
-const Map< StringName, Map<StringName,ShaderLanguage::DataType> >& ShaderTypes::get_functions(VS::ShaderMode p_mode) {
+const Map<StringName, Map<StringName, ShaderLanguage::DataType> > &ShaderTypes::get_functions(VS::ShaderMode p_mode) {
return shader_modes[p_mode].functions;
}
-const Set<String>& ShaderTypes::get_modes(VS::ShaderMode p_mode) {
+const Set<String> &ShaderTypes::get_modes(VS::ShaderMode p_mode) {
return shader_modes[p_mode].modes;
}
+ShaderTypes *ShaderTypes::singleton = NULL;
-ShaderTypes *ShaderTypes::singleton=NULL;
-
-ShaderTypes::ShaderTypes()
-{
- singleton=this;
+ShaderTypes::ShaderTypes() {
+ singleton = this;
/*************** SPATIAL ***********************/
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_TANGENT"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_BONES"]=ShaderLanguage::TYPE_IVEC4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_WEIGHTS"]=ShaderLanguage::TYPE_VEC4;
-
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POSITION"]=ShaderLanguage::TYPE_VEC4 ;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TANGENT"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV2"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INSTANCE_ID"]=ShaderLanguage::TYPE_INT;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_VERTEX"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_TANGENT"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_BONES"] = ShaderLanguage::TYPE_IVEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_WEIGHTS"] = ShaderLanguage::TYPE_VEC4;
+
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POSITION"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VERTEX"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TANGENT"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["BINORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV2"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POINT_SIZE"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INSTANCE_ID"] = ShaderLanguage::TYPE_INT;
//builtins
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2;
-
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VERTEX"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRAGCOORD"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRONT_FACING"]=ShaderLanguage::TYPE_BOOL;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TANGENT"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV2"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALBEDO"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALPHA"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECULAR"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ROUGHNESS"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM_TINT"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT_GLOSS"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY_FLOW"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SSS_STRENGTH"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["AO"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["EMISSION"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECIAL"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["DISCARD"]=ShaderLanguage::TYPE_BOOL;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2;
-
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INV_CAMERA_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VIEWPORT_SIZE"] = ShaderLanguage::TYPE_VEC2;
+
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VERTEX"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRAGCOORD"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRONT_FACING"] = ShaderLanguage::TYPE_BOOL;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TANGENT"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["BINORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP_DEPTH"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV2"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALBEDO"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALPHA"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECULAR"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ROUGHNESS"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM_TINT"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT_GLOSS"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY_FLOW"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SSS_STRENGTH"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["AO"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["EMISSION"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECIAL"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["DISCARD"] = ShaderLanguage::TYPE_BOOL;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2;
+
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["INV_CAMERA_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VIEWPORT_SIZE"] = ShaderLanguage::TYPE_VEC2;
shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mix");
shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_add");
@@ -129,48 +126,48 @@ ShaderTypes::ShaderTypes()
/************ CANVAS ITEM **************************/
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX_COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT;
-
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["EXTRA_MATRIX"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
-
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SRC_COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POSITION"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
-
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POSITION"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["NORMAL"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR1"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR2"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_VEC"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_HEIGHT"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_UV"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_SHADOW"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SHADOW"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2;
- shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["SRC_VERTEX"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX_COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["POINT_SIZE"] = ShaderLanguage::TYPE_FLOAT;
+
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["WORLD_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["PROJECTION_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["EXTRA_MATRIX"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
+
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SRC_COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POSITION"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP_DEPTH"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE"] = ShaderLanguage::TYPE_SAMPLER2D;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE_PIXEL_SIZE"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
+
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POSITION"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["NORMAL"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE"] = ShaderLanguage::TYPE_SAMPLER2D;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE_PIXEL_SIZE"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR1"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR2"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SCREEN_UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_VEC"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_HEIGHT"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_UV"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_SHADOW"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SHADOW"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POINT_COORD"] = ShaderLanguage::TYPE_VEC2;
+ shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("skip_transform");
@@ -183,28 +180,23 @@ ShaderTypes::ShaderTypes()
shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("unshaded");
shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("light_only");
-
/************ PARTICLES **************************/
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["VELOCITY"]=ShaderLanguage::TYPE_VEC3;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["MASS"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ACTIVE"]=ShaderLanguage::TYPE_BOOL;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["RESTART"]=ShaderLanguage::TYPE_BOOL;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["CUSTOM"]=ShaderLanguage::TYPE_VEC4;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TRANSFORM"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["LIFETIME"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["DELTA"]=ShaderLanguage::TYPE_FLOAT;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["SEED"]=ShaderLanguage::TYPE_BOOL;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ORIGIN"]=ShaderLanguage::TYPE_MAT4;
- shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["INDEX"]=ShaderLanguage::TYPE_INT;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["COLOR"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["VELOCITY"] = ShaderLanguage::TYPE_VEC3;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["MASS"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ACTIVE"] = ShaderLanguage::TYPE_BOOL;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["RESTART"] = ShaderLanguage::TYPE_BOOL;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["CUSTOM"] = ShaderLanguage::TYPE_VEC4;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TRANSFORM"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TIME"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["LIFETIME"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["DELTA"] = ShaderLanguage::TYPE_FLOAT;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["SEED"] = ShaderLanguage::TYPE_BOOL;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ORIGIN"] = ShaderLanguage::TYPE_MAT4;
+ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["INDEX"] = ShaderLanguage::TYPE_INT;
shader_modes[VS::SHADER_PARTICLES].modes.insert("billboard");
shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_force");
shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_velocity");
-
-
-
-
}
diff --git a/servers/visual/shader_types.h b/servers/visual/shader_types.h
index b8a96af922..1bddde8c82 100644
--- a/servers/visual/shader_types.h
+++ b/servers/visual/shader_types.h
@@ -29,25 +29,25 @@
#ifndef SHADERTYPES_H
#define SHADERTYPES_H
-#include "shader_language.h"
#include "servers/visual_server.h"
+#include "shader_language.h"
class ShaderTypes {
-
struct Type {
- Map< StringName, Map<StringName,ShaderLanguage::DataType> > functions;
- Set<String> modes;
+ Map<StringName, Map<StringName, ShaderLanguage::DataType> > functions;
+ Set<String> modes;
};
- Map<VS::ShaderMode,Type> shader_modes;
+ Map<VS::ShaderMode, Type> shader_modes;
static ShaderTypes *singleton;
+
public:
static ShaderTypes *get_singleton() { return singleton; }
- const Map< StringName, Map<StringName,ShaderLanguage::DataType> >& get_functions(VS::ShaderMode p_mode);
- const Set<String>& get_modes(VS::ShaderMode p_mode);
+ const Map<StringName, Map<StringName, ShaderLanguage::DataType> > &get_functions(VS::ShaderMode p_mode);
+ const Set<String> &get_modes(VS::ShaderMode p_mode);
ShaderTypes();
};
diff --git a/servers/visual/visual_server_canvas.cpp b/servers/visual/visual_server_canvas.cpp
index 84cc1a968d..40fa779170 100644
--- a/servers/visual/visual_server_canvas.cpp
+++ b/servers/visual/visual_server_canvas.cpp
@@ -30,30 +30,27 @@
#include "visual_server_global.h"
#include "visual_server_viewport.h"
-void VisualServerCanvas::_render_canvas_item_tree(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color& p_modulate, RasterizerCanvas::Light *p_lights) {
+void VisualServerCanvas::_render_canvas_item_tree(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights) {
-
- static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1;
+ static const int z_range = VS::CANVAS_ITEM_Z_MAX - VS::CANVAS_ITEM_Z_MIN + 1;
RasterizerCanvas::Item *z_list[z_range];
RasterizerCanvas::Item *z_last_list[z_range];
- for(int i=0;i<z_range;i++) {
- z_list[i]=NULL;
- z_last_list[i]=NULL;
+ for (int i = 0; i < z_range; i++) {
+ z_list[i] = NULL;
+ z_last_list[i] = NULL;
}
+ _render_canvas_item(p_canvas_item, p_transform, p_clip_rect, Color(1, 1, 1, 1), 0, z_list, z_last_list, NULL, NULL);
- _render_canvas_item(p_canvas_item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL);
-
- for(int i=0;i<z_range;i++) {
+ for (int i = 0; i < z_range; i++) {
if (!z_list[i])
continue;
- VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_modulate,p_lights);
+ VSG::canvas_render->canvas_render_items(z_list[i], VS::CANVAS_ITEM_Z_MIN + i, p_modulate, p_lights);
}
-
}
-void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform2D& p_transform,const Rect2& p_clip_rect, const Color &p_modulate,int p_z,RasterizerCanvas::Item **z_list,RasterizerCanvas::Item **z_last_list,Item *p_canvas_clip,Item *p_material_owner) {
+void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner) {
Item *ci = p_canvas_item;
@@ -63,55 +60,52 @@ void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform
Rect2 rect = ci->get_rect();
Transform2D xform = p_transform * ci->xform;
Rect2 global_rect = xform.xform(rect);
- global_rect.pos+=p_clip_rect.pos;
-
+ global_rect.pos += p_clip_rect.pos;
if (ci->use_parent_material && p_material_owner)
- ci->material_owner=p_material_owner;
+ ci->material_owner = p_material_owner;
else {
- p_material_owner=ci;
- ci->material_owner=NULL;
+ p_material_owner = ci;
+ ci->material_owner = NULL;
}
+ Color modulate(ci->modulate.r * p_modulate.r, ci->modulate.g * p_modulate.g, ci->modulate.b * p_modulate.b, ci->modulate.a * p_modulate.a);
- Color modulate( ci->modulate.r * p_modulate.r, ci->modulate.g * p_modulate.g,ci->modulate.b * p_modulate.b,ci->modulate.a * p_modulate.a);
-
- if (modulate.a<0.007)
+ if (modulate.a < 0.007)
return;
-
- int child_item_count=ci->child_items.size();
- Item **child_items=(Item**)alloca(child_item_count*sizeof(Item*));
- copymem(child_items,ci->child_items.ptr(),child_item_count*sizeof(Item*));
+ int child_item_count = ci->child_items.size();
+ Item **child_items = (Item **)alloca(child_item_count * sizeof(Item *));
+ copymem(child_items, ci->child_items.ptr(), child_item_count * sizeof(Item *));
if (ci->clip) {
if (p_canvas_clip != NULL) {
- ci->final_clip_rect=p_canvas_clip->final_clip_rect.clip(global_rect);
+ ci->final_clip_rect = p_canvas_clip->final_clip_rect.clip(global_rect);
} else {
- ci->final_clip_rect=global_rect;
+ ci->final_clip_rect = global_rect;
}
- ci->final_clip_owner=ci;
+ ci->final_clip_owner = ci;
} else {
- ci->final_clip_owner=p_canvas_clip;
+ ci->final_clip_owner = p_canvas_clip;
}
if (ci->sort_y) {
- SortArray<Item*,ItemPtrSort> sorter;
- sorter.sort(child_items,child_item_count);
+ SortArray<Item *, ItemPtrSort> sorter;
+ sorter.sort(child_items, child_item_count);
}
if (ci->z_relative)
- p_z=CLAMP(p_z+ci->z,VS::CANVAS_ITEM_Z_MIN,VS::CANVAS_ITEM_Z_MAX);
+ p_z = CLAMP(p_z + ci->z, VS::CANVAS_ITEM_Z_MIN, VS::CANVAS_ITEM_Z_MAX);
else
- p_z=ci->z;
+ p_z = ci->z;
- for(int i=0;i<child_item_count;i++) {
+ for (int i = 0; i < child_item_count; i++) {
if (!child_items[i]->behind)
continue;
- _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner);
+ _render_canvas_item(child_items[i], xform, p_clip_rect, modulate, p_z, z_list, z_last_list, (Item *)ci->final_clip_owner, p_material_owner);
}
if (ci->copy_back_buffer) {
@@ -121,61 +115,55 @@ void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform
if ((!ci->commands.empty() && p_clip_rect.intersects(global_rect)) || ci->vp_render || ci->copy_back_buffer) {
//something to draw?
- ci->final_transform=xform;
- ci->final_modulate=Color(modulate.r*ci->self_modulate.r, modulate.g*ci->self_modulate.g, modulate.b*ci->self_modulate.b, modulate.a*ci->self_modulate.a );
- ci->global_rect_cache=global_rect;
- ci->global_rect_cache.pos-=p_clip_rect.pos;
- ci->light_masked=false;
+ ci->final_transform = xform;
+ ci->final_modulate = Color(modulate.r * ci->self_modulate.r, modulate.g * ci->self_modulate.g, modulate.b * ci->self_modulate.b, modulate.a * ci->self_modulate.a);
+ ci->global_rect_cache = global_rect;
+ ci->global_rect_cache.pos -= p_clip_rect.pos;
+ ci->light_masked = false;
- int zidx = p_z-VS::CANVAS_ITEM_Z_MIN;
+ int zidx = p_z - VS::CANVAS_ITEM_Z_MIN;
if (z_last_list[zidx]) {
- z_last_list[zidx]->next=ci;
- z_last_list[zidx]=ci;
+ z_last_list[zidx]->next = ci;
+ z_last_list[zidx] = ci;
} else {
- z_list[zidx]=ci;
- z_last_list[zidx]=ci;
+ z_list[zidx] = ci;
+ z_last_list[zidx] = ci;
}
- ci->next=NULL;
-
+ ci->next = NULL;
}
- for(int i=0;i<child_item_count;i++) {
+ for (int i = 0; i < child_item_count; i++) {
if (child_items[i]->behind)
continue;
- _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner);
+ _render_canvas_item(child_items[i], xform, p_clip_rect, modulate, p_z, z_list, z_last_list, (Item *)ci->final_clip_owner, p_material_owner);
}
-
}
-void VisualServerCanvas::_light_mask_canvas_items(int p_z,RasterizerCanvas::Item *p_canvas_item,RasterizerCanvas::Light *p_masked_lights) {
+void VisualServerCanvas::_light_mask_canvas_items(int p_z, RasterizerCanvas::Item *p_canvas_item, RasterizerCanvas::Light *p_masked_lights) {
if (!p_masked_lights)
return;
- RasterizerCanvas::Item *ci=p_canvas_item;
+ RasterizerCanvas::Item *ci = p_canvas_item;
- while(ci) {
+ while (ci) {
- RasterizerCanvas::Light *light=p_masked_lights;
- while(light) {
+ RasterizerCanvas::Light *light = p_masked_lights;
+ while (light) {
- if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) {
- ci->light_masked=true;
+ if (ci->light_mask & light->item_mask && p_z >= light->z_min && p_z <= light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
+ ci->light_masked = true;
}
- light=light->mask_next_ptr;
+ light = light->mask_next_ptr;
}
- ci=ci->next;
+ ci = ci->next;
}
-
-
-
-
}
void VisualServerCanvas::render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights, const Rect2 &p_clip_rect) {
@@ -183,112 +171,105 @@ void VisualServerCanvas::render_canvas(Canvas *p_canvas, const Transform2D &p_tr
VSG::canvas_render->canvas_begin();
int l = p_canvas->child_items.size();
- Canvas::ChildItem *ci=p_canvas->child_items.ptr();
+ Canvas::ChildItem *ci = p_canvas->child_items.ptr();
- bool has_mirror=false;
- for(int i=0;i<l;i++) {
+ bool has_mirror = false;
+ for (int i = 0; i < l; i++) {
if (ci[i].mirror.x || ci[i].mirror.y) {
- has_mirror=true;
+ has_mirror = true;
break;
}
}
-
if (!has_mirror) {
- static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1;
+ static const int z_range = VS::CANVAS_ITEM_Z_MAX - VS::CANVAS_ITEM_Z_MIN + 1;
RasterizerCanvas::Item *z_list[z_range];
RasterizerCanvas::Item *z_last_list[z_range];
- for(int i=0;i<z_range;i++) {
- z_list[i]=NULL;
- z_last_list[i]=NULL;
+ for (int i = 0; i < z_range; i++) {
+ z_list[i] = NULL;
+ z_last_list[i] = NULL;
}
- for(int i=0;i<l;i++) {
- _render_canvas_item(ci[i].item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL);
+ for (int i = 0; i < l; i++) {
+ _render_canvas_item(ci[i].item, p_transform, p_clip_rect, Color(1, 1, 1, 1), 0, z_list, z_last_list, NULL, NULL);
}
- for(int i=0;i<z_range;i++) {
+ for (int i = 0; i < z_range; i++) {
if (!z_list[i])
continue;
if (p_masked_lights) {
- _light_mask_canvas_items(VS::CANVAS_ITEM_Z_MIN+i,z_list[i],p_masked_lights);
+ _light_mask_canvas_items(VS::CANVAS_ITEM_Z_MIN + i, z_list[i], p_masked_lights);
}
- VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_canvas->modulate,p_lights);
+ VSG::canvas_render->canvas_render_items(z_list[i], VS::CANVAS_ITEM_Z_MIN + i, p_canvas->modulate, p_lights);
}
} else {
- for(int i=0;i<l;i++) {
+ for (int i = 0; i < l; i++) {
- Canvas::ChildItem& ci=p_canvas->child_items[i];
- _render_canvas_item_tree(ci.item,p_transform,p_clip_rect,p_canvas->modulate,p_lights);
+ Canvas::ChildItem &ci = p_canvas->child_items[i];
+ _render_canvas_item_tree(ci.item, p_transform, p_clip_rect, p_canvas->modulate, p_lights);
//mirroring (useful for scrolling backgrounds)
- if (ci.mirror.x!=0) {
+ if (ci.mirror.x != 0) {
- Transform2D xform2 = p_transform * Transform2D(0,Vector2(ci.mirror.x,0));
- _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights);
+ Transform2D xform2 = p_transform * Transform2D(0, Vector2(ci.mirror.x, 0));
+ _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights);
}
- if (ci.mirror.y!=0) {
+ if (ci.mirror.y != 0) {
- Transform2D xform2 = p_transform * Transform2D(0,Vector2(0,ci.mirror.y));
- _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights);
+ Transform2D xform2 = p_transform * Transform2D(0, Vector2(0, ci.mirror.y));
+ _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights);
}
- if (ci.mirror.y!=0 && ci.mirror.x!=0) {
+ if (ci.mirror.y != 0 && ci.mirror.x != 0) {
- Transform2D xform2 = p_transform * Transform2D(0,ci.mirror);
- _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights);
+ Transform2D xform2 = p_transform * Transform2D(0, ci.mirror);
+ _render_canvas_item_tree(ci.item, xform2, p_clip_rect, p_canvas->modulate, p_lights);
}
-
}
}
-
}
-
RID VisualServerCanvas::canvas_create() {
- Canvas * canvas = memnew( Canvas );
- ERR_FAIL_COND_V(!canvas,RID());
- RID rid = canvas_owner.make_rid( canvas );
+ Canvas *canvas = memnew(Canvas);
+ ERR_FAIL_COND_V(!canvas, RID());
+ RID rid = canvas_owner.make_rid(canvas);
return rid;
}
-void VisualServerCanvas::canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring) {
+void VisualServerCanvas::canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring) {
- Canvas * canvas = canvas_owner.getornull(p_canvas);
+ Canvas *canvas = canvas_owner.getornull(p_canvas);
ERR_FAIL_COND(!canvas);
Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
int idx = canvas->find_item(canvas_item);
- ERR_FAIL_COND(idx==-1);
- canvas->child_items[idx].mirror=p_mirroring;
-
+ ERR_FAIL_COND(idx == -1);
+ canvas->child_items[idx].mirror = p_mirroring;
}
-void VisualServerCanvas::canvas_set_modulate(RID p_canvas,const Color& p_color) {
+void VisualServerCanvas::canvas_set_modulate(RID p_canvas, const Color &p_color) {
- Canvas * canvas = canvas_owner.get(p_canvas);
+ Canvas *canvas = canvas_owner.get(p_canvas);
ERR_FAIL_COND(!canvas);
- canvas->modulate=p_color;
+ canvas->modulate = p_color;
}
-
RID VisualServerCanvas::canvas_item_create() {
- Item *canvas_item = memnew( Item );
- ERR_FAIL_COND_V(!canvas_item,RID());
+ Item *canvas_item = memnew(Item);
+ ERR_FAIL_COND_V(!canvas_item, RID());
- return canvas_item_owner.make_rid( canvas_item );
+ return canvas_item_owner.make_rid(canvas_item);
}
-void VisualServerCanvas::canvas_item_set_parent(RID p_item,RID p_parent) {
-
+void VisualServerCanvas::canvas_item_set_parent(RID p_item, RID p_parent) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
if (canvas_item->parent.is_valid()) {
@@ -303,285 +284,262 @@ void VisualServerCanvas::canvas_item_set_parent(RID p_item,RID p_parent) {
item_owner->child_items.erase(canvas_item);
}
- canvas_item->parent=RID();
+ canvas_item->parent = RID();
}
-
if (p_parent.is_valid()) {
if (canvas_owner.owns(p_parent)) {
Canvas *canvas = canvas_owner.get(p_parent);
Canvas::ChildItem ci;
- ci.item=canvas_item;
+ ci.item = canvas_item;
canvas->child_items.push_back(ci);
- canvas->children_order_dirty=true;
+ canvas->children_order_dirty = true;
} else if (canvas_item_owner.owns(p_parent)) {
Item *item_owner = canvas_item_owner.get(p_parent);
item_owner->child_items.push_back(canvas_item);
- item_owner->children_order_dirty=true;
+ item_owner->children_order_dirty = true;
} else {
ERR_EXPLAIN("Invalid parent");
ERR_FAIL();
}
-
-
}
- canvas_item->parent=p_parent;
-
-
+ canvas_item->parent = p_parent;
}
-void VisualServerCanvas::canvas_item_set_visible(RID p_item,bool p_visible){
+void VisualServerCanvas::canvas_item_set_visible(RID p_item, bool p_visible) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->visible=p_visible;
-
+ canvas_item->visible = p_visible;
}
-void VisualServerCanvas::canvas_item_set_light_mask(RID p_item,int p_mask){
+void VisualServerCanvas::canvas_item_set_light_mask(RID p_item, int p_mask) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->light_mask=p_mask;
-
+ canvas_item->light_mask = p_mask;
}
-void VisualServerCanvas::canvas_item_set_transform(RID p_item, const Transform2D& p_transform){
+void VisualServerCanvas::canvas_item_set_transform(RID p_item, const Transform2D &p_transform) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->xform=p_transform;
-
+ canvas_item->xform = p_transform;
}
-void VisualServerCanvas::canvas_item_set_clip(RID p_item, bool p_clip){
+void VisualServerCanvas::canvas_item_set_clip(RID p_item, bool p_clip) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->clip=p_clip;
-
+ canvas_item->clip = p_clip;
}
-void VisualServerCanvas::canvas_item_set_distance_field_mode(RID p_item, bool p_enable){
+void VisualServerCanvas::canvas_item_set_distance_field_mode(RID p_item, bool p_enable) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->distance_field=p_enable;
-
-
+ canvas_item->distance_field = p_enable;
}
-void VisualServerCanvas::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect){
+void VisualServerCanvas::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->custom_rect=p_custom_rect;
- canvas_item->rect=p_rect;
-
+ canvas_item->custom_rect = p_custom_rect;
+ canvas_item->rect = p_rect;
}
-void VisualServerCanvas::canvas_item_set_modulate(RID p_item, const Color& p_color) {
+void VisualServerCanvas::canvas_item_set_modulate(RID p_item, const Color &p_color) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->modulate=p_color;
-
+ canvas_item->modulate = p_color;
}
-void VisualServerCanvas::canvas_item_set_self_modulate(RID p_item, const Color& p_color){
+void VisualServerCanvas::canvas_item_set_self_modulate(RID p_item, const Color &p_color) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->self_modulate=p_color;
-
+ canvas_item->self_modulate = p_color;
}
-void VisualServerCanvas::canvas_item_set_draw_behind_parent(RID p_item, bool p_enable){
+void VisualServerCanvas::canvas_item_set_draw_behind_parent(RID p_item, bool p_enable) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->behind=p_enable;
-
+ canvas_item->behind = p_enable;
}
+void VisualServerCanvas::canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width, bool p_antialiased) {
-void VisualServerCanvas::canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) {
-
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandLine * line = memnew( Item::CommandLine );
+ Item::CommandLine *line = memnew(Item::CommandLine);
ERR_FAIL_COND(!line);
- line->color=p_color;
- line->from=p_from;
- line->to=p_to;
- line->width=p_width;
- line->antialiased=p_antialiased;
- canvas_item->rect_dirty=true;
-
+ line->color = p_color;
+ line->from = p_from;
+ line->to = p_to;
+ line->width = p_width;
+ line->antialiased = p_antialiased;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(line);
}
-void VisualServerCanvas::canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color) {
+void VisualServerCanvas::canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandRect * rect = memnew( Item::CommandRect );
+ Item::CommandRect *rect = memnew(Item::CommandRect);
ERR_FAIL_COND(!rect);
- rect->modulate=p_color;
- rect->rect=p_rect;
- canvas_item->rect_dirty=true;
+ rect->modulate = p_color;
+ rect->rect = p_rect;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(rect);
}
-void VisualServerCanvas::canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color) {
-
+void VisualServerCanvas::canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandCircle * circle = memnew( Item::CommandCircle );
+ Item::CommandCircle *circle = memnew(Item::CommandCircle);
ERR_FAIL_COND(!circle);
- circle->color=p_color;
- circle->pos=p_pos;
- circle->radius=p_radius;
+ circle->color = p_color;
+ circle->pos = p_pos;
+ circle->radius = p_radius;
canvas_item->commands.push_back(circle);
-
}
-void VisualServerCanvas::canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile,const Color& p_modulate,bool p_transpose) {
+void VisualServerCanvas::canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile, const Color &p_modulate, bool p_transpose) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandRect * rect = memnew( Item::CommandRect );
+ Item::CommandRect *rect = memnew(Item::CommandRect);
ERR_FAIL_COND(!rect);
- rect->modulate=p_modulate;
- rect->rect=p_rect;
- rect->flags=0;
+ rect->modulate = p_modulate;
+ rect->rect = p_rect;
+ rect->flags = 0;
if (p_tile) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_TILE;
- rect->flags|=RasterizerCanvas::CANVAS_RECT_REGION;
- rect->source=Rect2(0,0,p_rect.size.width,p_rect.size.height);
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_TILE;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_REGION;
+ rect->source = Rect2(0, 0, p_rect.size.width, p_rect.size.height);
}
- if (p_rect.size.x<0) {
+ if (p_rect.size.x < 0) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_H;
rect->rect.size.x = -rect->rect.size.x;
}
- if (p_rect.size.y<0) {
+ if (p_rect.size.y < 0) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_V;
rect->rect.size.y = -rect->rect.size.y;
}
if (p_transpose) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_TRANSPOSE;
SWAP(rect->rect.size.x, rect->rect.size.y);
}
- rect->texture=p_texture;
- canvas_item->rect_dirty=true;
+ rect->texture = p_texture;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(rect);
}
-void VisualServerCanvas::canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate,bool p_transpose) {
+void VisualServerCanvas::canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandRect * rect = memnew( Item::CommandRect );
+ Item::CommandRect *rect = memnew(Item::CommandRect);
ERR_FAIL_COND(!rect);
- rect->modulate=p_modulate;
- rect->rect=p_rect;
- rect->texture=p_texture;
- rect->source=p_src_rect;
- rect->flags=RasterizerCanvas::CANVAS_RECT_REGION;
+ rect->modulate = p_modulate;
+ rect->rect = p_rect;
+ rect->texture = p_texture;
+ rect->source = p_src_rect;
+ rect->flags = RasterizerCanvas::CANVAS_RECT_REGION;
- if (p_rect.size.x<0) {
+ if (p_rect.size.x < 0) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_H;
rect->rect.size.x = -rect->rect.size.x;
}
- if (p_rect.size.y<0) {
+ if (p_rect.size.y < 0) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_FLIP_V;
rect->rect.size.y = -rect->rect.size.y;
}
if (p_transpose) {
- rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE;
+ rect->flags |= RasterizerCanvas::CANVAS_RECT_TRANSPOSE;
SWAP(rect->rect.size.x, rect->rect.size.y);
}
- canvas_item->rect_dirty=true;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(rect);
-
}
-void VisualServerCanvas::canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,VS::NinePatchAxisMode p_x_axis_mode, VS::NinePatchAxisMode p_y_axis_mode,bool p_draw_center,const Color& p_modulate) {
-
+void VisualServerCanvas::canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, VS::NinePatchAxisMode p_x_axis_mode, VS::NinePatchAxisMode p_y_axis_mode, bool p_draw_center, const Color &p_modulate) {
-
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandNinePatch * style = memnew( Item::CommandNinePatch );
+ Item::CommandNinePatch *style = memnew(Item::CommandNinePatch);
ERR_FAIL_COND(!style);
- style->texture=p_texture;
- style->rect=p_rect;
- style->source=p_source;
- style->draw_center=p_draw_center;
- style->color=p_modulate;
- style->margin[MARGIN_LEFT]=p_topleft.x;
- style->margin[MARGIN_TOP]=p_topleft.y;
- style->margin[MARGIN_RIGHT]=p_bottomright.x;
- style->margin[MARGIN_BOTTOM]=p_bottomright.y;
- style->axis_x=p_x_axis_mode;
- style->axis_y=p_y_axis_mode;
- canvas_item->rect_dirty=true;
+ style->texture = p_texture;
+ style->rect = p_rect;
+ style->source = p_source;
+ style->draw_center = p_draw_center;
+ style->color = p_modulate;
+ style->margin[MARGIN_LEFT] = p_topleft.x;
+ style->margin[MARGIN_TOP] = p_topleft.y;
+ style->margin[MARGIN_RIGHT] = p_bottomright.x;
+ style->margin[MARGIN_BOTTOM] = p_bottomright.y;
+ style->axis_x = p_x_axis_mode;
+ style->axis_y = p_y_axis_mode;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(style);
}
-void VisualServerCanvas::canvas_item_add_primitive(RID p_item,const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width) {
+void VisualServerCanvas::canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandPrimitive * prim = memnew( Item::CommandPrimitive );
+ Item::CommandPrimitive *prim = memnew(Item::CommandPrimitive);
ERR_FAIL_COND(!prim);
- prim->texture=p_texture;
- prim->points=p_points;
- prim->uvs=p_uvs;
- prim->colors=p_colors;
- prim->width=p_width;
- canvas_item->rect_dirty=true;
+ prim->texture = p_texture;
+ prim->points = p_points;
+ prim->uvs = p_uvs;
+ prim->colors = p_colors;
+ prim->width = p_width;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(prim);
}
-void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) {
-
+void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
#ifdef DEBUG_ENABLED
int pointcount = p_points.size();
- ERR_FAIL_COND(pointcount<3);
- int color_size=p_colors.size();
- int uv_size=p_uvs.size();
- ERR_FAIL_COND(color_size!=0 && color_size!=1 && color_size!=pointcount);
- ERR_FAIL_COND(uv_size!=0 && (uv_size!=pointcount || !p_texture.is_valid()));
+ ERR_FAIL_COND(pointcount < 3);
+ int color_size = p_colors.size();
+ int uv_size = p_uvs.size();
+ ERR_FAIL_COND(color_size != 0 && color_size != 1 && color_size != pointcount);
+ ERR_FAIL_COND(uv_size != 0 && (uv_size != pointcount || !p_texture.is_valid()));
#endif
Vector<int> indices = Geometry::triangulate_polygon(p_points);
@@ -591,30 +549,27 @@ void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2
ERR_FAIL_V();
}
- Item::CommandPolygon * polygon = memnew( Item::CommandPolygon );
+ Item::CommandPolygon *polygon = memnew(Item::CommandPolygon);
ERR_FAIL_COND(!polygon);
- polygon->texture=p_texture;
- polygon->points=p_points;
- polygon->uvs=p_uvs;
- polygon->colors=p_colors;
- polygon->indices=indices;
- polygon->count=indices.size();
- canvas_item->rect_dirty=true;
+ polygon->texture = p_texture;
+ polygon->points = p_points;
+ polygon->uvs = p_uvs;
+ polygon->colors = p_colors;
+ polygon->indices = indices;
+ polygon->count = indices.size();
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(polygon);
-
}
+void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, int p_count) {
-void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture, int p_count) {
-
-
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
int ps = p_points.size();
- ERR_FAIL_COND(!p_colors.empty() && p_colors.size()!=ps && p_colors.size()!=1);
- ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size()!=ps);
+ ERR_FAIL_COND(!p_colors.empty() && p_colors.size() != ps && p_colors.size() != 1);
+ ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size() != ps);
Vector<int> indices = p_indices;
@@ -622,181 +577,169 @@ void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector
if (indices.empty()) {
- ERR_FAIL_COND( ps % 3 != 0 );
+ ERR_FAIL_COND(ps % 3 != 0);
if (p_count == -1)
count = ps;
} else {
- ERR_FAIL_COND( indices.size() % 3 != 0 );
+ ERR_FAIL_COND(indices.size() % 3 != 0);
if (p_count == -1)
count = indices.size();
}
- Item::CommandPolygon * polygon = memnew( Item::CommandPolygon );
+ Item::CommandPolygon *polygon = memnew(Item::CommandPolygon);
ERR_FAIL_COND(!polygon);
- polygon->texture=p_texture;
- polygon->points=p_points;
- polygon->uvs=p_uvs;
- polygon->colors=p_colors;
- polygon->indices=indices;
+ polygon->texture = p_texture;
+ polygon->points = p_points;
+ polygon->uvs = p_uvs;
+ polygon->colors = p_colors;
+ polygon->indices = indices;
polygon->count = count;
- canvas_item->rect_dirty=true;
+ canvas_item->rect_dirty = true;
canvas_item->commands.push_back(polygon);
}
+void VisualServerCanvas::canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform) {
-void VisualServerCanvas::canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform) {
-
-
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandTransform * tr = memnew( Item::CommandTransform );
+ Item::CommandTransform *tr = memnew(Item::CommandTransform);
ERR_FAIL_COND(!tr);
- tr->xform=p_transform;
+ tr->xform = p_transform;
canvas_item->commands.push_back(tr);
-
}
-void VisualServerCanvas::canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton){
+void VisualServerCanvas::canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandMesh * m = memnew( Item::CommandMesh );
+ Item::CommandMesh *m = memnew(Item::CommandMesh);
ERR_FAIL_COND(!m);
- m->mesh=p_mesh;
- m->skeleton=p_skeleton;
+ m->mesh = p_mesh;
+ m->skeleton = p_skeleton;
canvas_item->commands.push_back(m);
}
-void VisualServerCanvas::canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton){
+void VisualServerCanvas::canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandMultiMesh * mm = memnew( Item::CommandMultiMesh );
+ Item::CommandMultiMesh *mm = memnew(Item::CommandMultiMesh);
ERR_FAIL_COND(!mm);
- mm->multimesh=p_mesh;
- mm->skeleton=p_skeleton;
+ mm->multimesh = p_mesh;
+ mm->skeleton = p_skeleton;
canvas_item->commands.push_back(mm);
-
}
-void VisualServerCanvas::canvas_item_add_clip_ignore(RID p_item, bool p_ignore){
-
+void VisualServerCanvas::canvas_item_add_clip_ignore(RID p_item, bool p_ignore) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- Item::CommandClipIgnore * ci = memnew( Item::CommandClipIgnore);
+ Item::CommandClipIgnore *ci = memnew(Item::CommandClipIgnore);
ERR_FAIL_COND(!ci);
- ci->ignore=p_ignore;
+ ci->ignore = p_ignore;
canvas_item->commands.push_back(ci);
}
-void VisualServerCanvas::canvas_item_set_sort_children_by_y(RID p_item, bool p_enable){
-
+void VisualServerCanvas::canvas_item_set_sort_children_by_y(RID p_item, bool p_enable) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->sort_y=p_enable;
+ canvas_item->sort_y = p_enable;
}
-void VisualServerCanvas::canvas_item_set_z(RID p_item, int p_z){
+void VisualServerCanvas::canvas_item_set_z(RID p_item, int p_z) {
- ERR_FAIL_COND(p_z<VS::CANVAS_ITEM_Z_MIN || p_z>VS::CANVAS_ITEM_Z_MAX);
+ ERR_FAIL_COND(p_z < VS::CANVAS_ITEM_Z_MIN || p_z > VS::CANVAS_ITEM_Z_MAX);
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->z=p_z;
+ canvas_item->z = p_z;
}
-void VisualServerCanvas::canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable){
+void VisualServerCanvas::canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->z_relative=p_enable;
-
+ canvas_item->z_relative = p_enable;
}
-void VisualServerCanvas::canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect){
+void VisualServerCanvas::canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect) {
-
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- if (bool(canvas_item->copy_back_buffer!=NULL) !=p_enable) {
+ if (bool(canvas_item->copy_back_buffer != NULL) != p_enable) {
if (p_enable) {
- canvas_item->copy_back_buffer = memnew( RasterizerCanvas::Item::CopyBackBuffer );
+ canvas_item->copy_back_buffer = memnew(RasterizerCanvas::Item::CopyBackBuffer);
} else {
memdelete(canvas_item->copy_back_buffer);
- canvas_item->copy_back_buffer=NULL;
+ canvas_item->copy_back_buffer = NULL;
}
}
if (p_enable) {
- canvas_item->copy_back_buffer->rect=p_rect;
- canvas_item->copy_back_buffer->full=p_rect==Rect2();
+ canvas_item->copy_back_buffer->rect = p_rect;
+ canvas_item->copy_back_buffer->full = p_rect == Rect2();
}
-
}
-void VisualServerCanvas::canvas_item_clear(RID p_item){
+void VisualServerCanvas::canvas_item_clear(RID p_item) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
canvas_item->clear();
}
-void VisualServerCanvas::canvas_item_set_draw_index(RID p_item,int p_index){
+void VisualServerCanvas::canvas_item_set_draw_index(RID p_item, int p_index) {
- Item *canvas_item = canvas_item_owner.getornull( p_item );
+ Item *canvas_item = canvas_item_owner.getornull(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->index=p_index;
+ canvas_item->index = p_index;
- if (canvas_item_owner.owns( canvas_item->parent)) {
- Item *canvas_item_parent = canvas_item_owner.getornull( canvas_item->parent );
- canvas_item_parent->children_order_dirty=true;
+ if (canvas_item_owner.owns(canvas_item->parent)) {
+ Item *canvas_item_parent = canvas_item_owner.getornull(canvas_item->parent);
+ canvas_item_parent->children_order_dirty = true;
return;
}
- Canvas* canvas = canvas_owner.getornull( canvas_item->parent );
+ Canvas *canvas = canvas_owner.getornull(canvas_item->parent);
if (canvas) {
- canvas->children_order_dirty=true;
+ canvas->children_order_dirty = true;
return;
}
-
}
-void VisualServerCanvas::canvas_item_set_material(RID p_item, RID p_material){
+void VisualServerCanvas::canvas_item_set_material(RID p_item, RID p_material) {
- Item *canvas_item = canvas_item_owner.get( p_item );
+ Item *canvas_item = canvas_item_owner.get(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->material=p_material;
+ canvas_item->material = p_material;
}
-void VisualServerCanvas::canvas_item_set_use_parent_material(RID p_item, bool p_enable){
+void VisualServerCanvas::canvas_item_set_use_parent_material(RID p_item, bool p_enable) {
- Item *canvas_item = canvas_item_owner.get( p_item );
+ Item *canvas_item = canvas_item_owner.get(p_item);
ERR_FAIL_COND(!canvas_item);
- canvas_item->use_parent_material=p_enable;
-
+ canvas_item->use_parent_material = p_enable;
}
-RID VisualServerCanvas::canvas_light_create(){
+RID VisualServerCanvas::canvas_light_create() {
- RasterizerCanvas::Light *clight = memnew( RasterizerCanvas::Light );
+ RasterizerCanvas::Light *clight = memnew(RasterizerCanvas::Light);
clight->light_internal = VSG::canvas_render->light_internal_create();
return canvas_light_owner.make_rid(clight);
-
}
-void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas){
+void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light, RID p_canvas) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
@@ -808,9 +751,9 @@ void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas)
}
if (!canvas_owner.owns(p_canvas))
- p_canvas=RID();
+ p_canvas = RID();
- clight->canvas=p_canvas;
+ clight->canvas = p_canvas;
if (clight->canvas.is_valid()) {
@@ -819,196 +762,164 @@ void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas)
}
}
-
-void VisualServerCanvas::canvas_light_set_enabled(RID p_light, bool p_enabled){
+void VisualServerCanvas::canvas_light_set_enabled(RID p_light, bool p_enabled) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->enabled=p_enabled;
-
+ clight->enabled = p_enabled;
}
-void VisualServerCanvas::canvas_light_set_scale(RID p_light, float p_scale){
-
+void VisualServerCanvas::canvas_light_set_scale(RID p_light, float p_scale) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->scale=p_scale;
-
+ clight->scale = p_scale;
}
-void VisualServerCanvas::canvas_light_set_transform(RID p_light, const Transform2D& p_transform){
-
+void VisualServerCanvas::canvas_light_set_transform(RID p_light, const Transform2D &p_transform) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->xform=p_transform;
-
+ clight->xform = p_transform;
}
-void VisualServerCanvas::canvas_light_set_texture(RID p_light, RID p_texture){
-
+void VisualServerCanvas::canvas_light_set_texture(RID p_light, RID p_texture) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->texture=p_texture;
-
+ clight->texture = p_texture;
}
-void VisualServerCanvas::canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset){
-
+void VisualServerCanvas::canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->texture_offset=p_offset;
-
+ clight->texture_offset = p_offset;
}
-void VisualServerCanvas::canvas_light_set_color(RID p_light, const Color& p_color){
-
-
+void VisualServerCanvas::canvas_light_set_color(RID p_light, const Color &p_color) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->color=p_color;
+ clight->color = p_color;
}
-void VisualServerCanvas::canvas_light_set_height(RID p_light, float p_height){
-
+void VisualServerCanvas::canvas_light_set_height(RID p_light, float p_height) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->height=p_height;
-
+ clight->height = p_height;
}
-void VisualServerCanvas::canvas_light_set_energy(RID p_light, float p_energy){
-
+void VisualServerCanvas::canvas_light_set_energy(RID p_light, float p_energy) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->energy=p_energy;
-
+ clight->energy = p_energy;
}
-void VisualServerCanvas::canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z){
-
+void VisualServerCanvas::canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->z_min=p_min_z;
- clight->z_max=p_max_z;
-
+ clight->z_min = p_min_z;
+ clight->z_max = p_max_z;
}
-void VisualServerCanvas::canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer){
-
+void VisualServerCanvas::canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
-
- clight->layer_max=p_max_layer;
- clight->layer_min=p_min_layer;
-
-
+ clight->layer_max = p_max_layer;
+ clight->layer_min = p_min_layer;
}
-void VisualServerCanvas::canvas_light_set_item_cull_mask(RID p_light, int p_mask){
-
+void VisualServerCanvas::canvas_light_set_item_cull_mask(RID p_light, int p_mask) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->item_mask=p_mask;
-
+ clight->item_mask = p_mask;
}
-void VisualServerCanvas::canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask){
+void VisualServerCanvas::canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->item_shadow_mask=p_mask;
-
+ clight->item_shadow_mask = p_mask;
}
-void VisualServerCanvas::canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode){
+void VisualServerCanvas::canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->mode=p_mode;
-
+ clight->mode = p_mode;
}
-
-void VisualServerCanvas::canvas_light_set_shadow_enabled(RID p_light, bool p_enabled){
+void VisualServerCanvas::canvas_light_set_shadow_enabled(RID p_light, bool p_enabled) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- if (clight->shadow_buffer.is_valid()==p_enabled)
+ if (clight->shadow_buffer.is_valid() == p_enabled)
return;
if (p_enabled) {
- clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size);
+ clight->shadow_buffer = VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size);
} else {
VSG::storage->free(clight->shadow_buffer);
- clight->shadow_buffer=RID();
+ clight->shadow_buffer = RID();
}
-
}
-void VisualServerCanvas::canvas_light_set_shadow_buffer_size(RID p_light, int p_size){
+void VisualServerCanvas::canvas_light_set_shadow_buffer_size(RID p_light, int p_size) {
- ERR_FAIL_COND(p_size<32 || p_size>16384);
+ ERR_FAIL_COND(p_size < 32 || p_size > 16384);
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
int new_size = nearest_power_of_2(p_size);
- if (new_size==clight->shadow_buffer_size)
+ if (new_size == clight->shadow_buffer_size)
return;
- clight->shadow_buffer_size=nearest_power_of_2(p_size);
+ clight->shadow_buffer_size = nearest_power_of_2(p_size);
if (clight->shadow_buffer.is_valid()) {
VSG::storage->free(clight->shadow_buffer);
- clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size);
+ clight->shadow_buffer = VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size);
}
}
void VisualServerCanvas::canvas_light_set_shadow_gradient_length(RID p_light, float p_length) {
- ERR_FAIL_COND(p_length<0);
+ ERR_FAIL_COND(p_length < 0);
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->shadow_gradient_length=p_length;
-
+ clight->shadow_gradient_length = p_length;
}
void VisualServerCanvas::canvas_light_set_shadow_filter(RID p_light, VS::CanvasLightShadowFilter p_filter) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->shadow_filter=p_filter;
-
+ clight->shadow_filter = p_filter;
}
-void VisualServerCanvas::canvas_light_set_shadow_color(RID p_light, const Color& p_color) {
+void VisualServerCanvas::canvas_light_set_shadow_color(RID p_light, const Color &p_color) {
RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light);
ERR_FAIL_COND(!clight);
- clight->shadow_color=p_color;
+ clight->shadow_color = p_color;
}
-
-
RID VisualServerCanvas::canvas_light_occluder_create() {
- RasterizerCanvas::LightOccluderInstance *occluder = memnew( RasterizerCanvas::LightOccluderInstance );
+ RasterizerCanvas::LightOccluderInstance *occluder = memnew(RasterizerCanvas::LightOccluderInstance);
return canvas_light_occluder_owner.make_rid(occluder);
}
-void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas){
+void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!occluder);
@@ -1020,9 +931,9 @@ void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,R
}
if (!canvas_owner.owns(p_canvas))
- p_canvas=RID();
+ p_canvas = RID();
- occluder->canvas=p_canvas;
+ occluder->canvas = p_canvas;
if (occluder->canvas.is_valid()) {
@@ -1030,14 +941,14 @@ void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,R
canvas->occluders.insert(occluder);
}
}
-void VisualServerCanvas::canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled) {
+void VisualServerCanvas::canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!occluder);
- occluder->enabled=p_enabled;
+ occluder->enabled = p_enabled;
}
-void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon) {
+void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!occluder);
@@ -1049,153 +960,147 @@ void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder,RID p_
}
}
- occluder->polygon=p_polygon;
- occluder->polygon_buffer=RID();
+ occluder->polygon = p_polygon;
+ occluder->polygon_buffer = RID();
if (occluder->polygon.is_valid()) {
LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_polygon);
if (!occluder_poly)
- occluder->polygon=RID();
+ occluder->polygon = RID();
ERR_FAIL_COND(!occluder_poly);
occluder_poly->owners.insert(occluder);
- occluder->polygon_buffer=occluder_poly->occluder;
- occluder->aabb_cache=occluder_poly->aabb;
- occluder->cull_cache=occluder_poly->cull_mode;
+ occluder->polygon_buffer = occluder_poly->occluder;
+ occluder->aabb_cache = occluder_poly->aabb;
+ occluder->cull_cache = occluder_poly->cull_mode;
}
-
}
-void VisualServerCanvas::canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform) {
+void VisualServerCanvas::canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!occluder);
- occluder->xform=p_xform;
+ occluder->xform = p_xform;
}
-void VisualServerCanvas::canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask) {
+void VisualServerCanvas::canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder);
ERR_FAIL_COND(!occluder);
- occluder->light_mask=p_mask;
+ occluder->light_mask = p_mask;
}
RID VisualServerCanvas::canvas_occluder_polygon_create() {
- LightOccluderPolygon * occluder_poly = memnew( LightOccluderPolygon );
- occluder_poly->occluder=VSG::storage->canvas_light_occluder_create();
+ LightOccluderPolygon *occluder_poly = memnew(LightOccluderPolygon);
+ occluder_poly->occluder = VSG::storage->canvas_light_occluder_create();
return canvas_light_occluder_polygon_owner.make_rid(occluder_poly);
-
}
-void VisualServerCanvas::canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed) {
+void VisualServerCanvas::canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed) {
- if (p_shape.size()<3) {
- canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,p_shape);
+ if (p_shape.size() < 3) {
+ canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon, p_shape);
return;
}
PoolVector<Vector2> lines;
- int lc = p_shape.size()*2;
+ int lc = p_shape.size() * 2;
- lines.resize(lc-(p_closed?0:2));
+ lines.resize(lc - (p_closed ? 0 : 2));
{
PoolVector<Vector2>::Write w = lines.write();
PoolVector<Vector2>::Read r = p_shape.read();
- int max=lc/2;
+ int max = lc / 2;
if (!p_closed) {
max--;
}
- for(int i=0;i<max;i++) {
+ for (int i = 0; i < max; i++) {
Vector2 a = r[i];
- Vector2 b = r[(i+1)%(lc/2)];
- w[i*2+0]=a;
- w[i*2+1]=b;
+ Vector2 b = r[(i + 1) % (lc / 2)];
+ w[i * 2 + 0] = a;
+ w[i * 2 + 1] = b;
}
-
}
- canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,lines);
+ canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon, lines);
}
-void VisualServerCanvas::canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape) {
+void VisualServerCanvas::canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape) {
- LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon);
+ LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon);
ERR_FAIL_COND(!occluder_poly);
- ERR_FAIL_COND(p_shape.size()&1);
+ ERR_FAIL_COND(p_shape.size() & 1);
int lc = p_shape.size();
- occluder_poly->aabb=Rect2();
+ occluder_poly->aabb = Rect2();
{
PoolVector<Vector2>::Read r = p_shape.read();
- for(int i=0;i<lc;i++) {
- if (i==0)
- occluder_poly->aabb.pos=r[i];
+ for (int i = 0; i < lc; i++) {
+ if (i == 0)
+ occluder_poly->aabb.pos = r[i];
else
occluder_poly->aabb.expand_to(r[i]);
}
}
- VSG::storage->canvas_light_occluder_set_polylines(occluder_poly->occluder,p_shape);
- for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) {
- E->get()->aabb_cache=occluder_poly->aabb;
+ VSG::storage->canvas_light_occluder_set_polylines(occluder_poly->occluder, p_shape);
+ for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = occluder_poly->owners.front(); E; E = E->next()) {
+ E->get()->aabb_cache = occluder_poly->aabb;
}
}
+void VisualServerCanvas::canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, VS::CanvasOccluderPolygonCullMode p_mode) {
-void VisualServerCanvas::canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,VS::CanvasOccluderPolygonCullMode p_mode) {
-
- LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon);
+ LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon);
ERR_FAIL_COND(!occluder_poly);
- occluder_poly->cull_mode=p_mode;
- for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) {
- E->get()->cull_cache=p_mode;
+ occluder_poly->cull_mode = p_mode;
+ for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = occluder_poly->owners.front(); E; E = E->next()) {
+ E->get()->cull_cache = p_mode;
}
}
-
-
bool VisualServerCanvas::free(RID p_rid) {
if (canvas_owner.owns(p_rid)) {
Canvas *canvas = canvas_owner.get(p_rid);
- ERR_FAIL_COND_V(!canvas,false);
+ ERR_FAIL_COND_V(!canvas, false);
- while(canvas->viewports.size()) {
+ while (canvas->viewports.size()) {
VisualServerViewport::Viewport *vp = VSG::viewport->viewport_owner.get(canvas->viewports.front()->get());
- ERR_FAIL_COND_V(!vp,true);
+ ERR_FAIL_COND_V(!vp, true);
- Map<RID,VisualServerViewport::Viewport::CanvasData>::Element *E=vp->canvas_map.find(p_rid);
- ERR_FAIL_COND_V(!E,true);
+ Map<RID, VisualServerViewport::Viewport::CanvasData>::Element *E = vp->canvas_map.find(p_rid);
+ ERR_FAIL_COND_V(!E, true);
vp->canvas_map.erase(p_rid);
- canvas->viewports.erase( canvas->viewports.front() );
+ canvas->viewports.erase(canvas->viewports.front());
}
- for (int i=0;i<canvas->child_items.size();i++) {
+ for (int i = 0; i < canvas->child_items.size(); i++) {
- canvas->child_items[i].item->parent=RID();
+ canvas->child_items[i].item->parent = RID();
}
- for (Set<RasterizerCanvas::Light*>::Element *E=canvas->lights.front();E;E=E->next()) {
+ for (Set<RasterizerCanvas::Light *>::Element *E = canvas->lights.front(); E; E = E->next()) {
- E->get()->canvas=RID();
+ E->get()->canvas = RID();
}
- for (Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=canvas->occluders.front();E;E=E->next()) {
+ for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *E = canvas->occluders.front(); E; E = E->next()) {
- E->get()->canvas=RID();
+ E->get()->canvas = RID();
}
- canvas_owner.free( p_rid );
+ canvas_owner.free(p_rid);
- memdelete( canvas );
+ memdelete(canvas);
} else if (canvas_item_owner.owns(p_rid)) {
Item *canvas_item = canvas_item_owner.get(p_rid);
- ERR_FAIL_COND_V(!canvas_item,true);
+ ERR_FAIL_COND_V(!canvas_item, true);
if (canvas_item->parent.is_valid()) {
@@ -1207,13 +1112,12 @@ bool VisualServerCanvas::free(RID p_rid) {
Item *item_owner = canvas_item_owner.get(canvas_item->parent);
item_owner->child_items.erase(canvas_item);
-
}
}
- for (int i=0;i<canvas_item->child_items.size();i++) {
+ for (int i = 0; i < canvas_item->child_items.size(); i++) {
- canvas_item->child_items[i]->parent=RID();
+ canvas_item->child_items[i]->parent = RID();
}
/*
@@ -1222,17 +1126,17 @@ bool VisualServerCanvas::free(RID p_rid) {
}
*/
- canvas_item_owner.free( p_rid );
+ canvas_item_owner.free(p_rid);
- memdelete( canvas_item );
+ memdelete(canvas_item);
} else if (canvas_light_owner.owns(p_rid)) {
RasterizerCanvas::Light *canvas_light = canvas_light_owner.get(p_rid);
- ERR_FAIL_COND_V(!canvas_light,true);
+ ERR_FAIL_COND_V(!canvas_light, true);
if (canvas_light->canvas.is_valid()) {
- Canvas* canvas = canvas_owner.get(canvas_light->canvas);
+ Canvas *canvas = canvas_owner.get(canvas_light->canvas);
if (canvas)
canvas->lights.erase(canvas_light);
}
@@ -1242,13 +1146,13 @@ bool VisualServerCanvas::free(RID p_rid) {
VSG::canvas_render->light_internal_free(canvas_light->light_internal);
- canvas_light_owner.free( p_rid );
- memdelete( canvas_light );
+ canvas_light_owner.free(p_rid);
+ memdelete(canvas_light);
} else if (canvas_light_occluder_owner.owns(p_rid)) {
RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_rid);
- ERR_FAIL_COND_V(!occluder,true);
+ ERR_FAIL_COND_V(!occluder, true);
if (occluder->polygon.is_valid()) {
@@ -1256,32 +1160,30 @@ bool VisualServerCanvas::free(RID p_rid) {
if (occluder_poly) {
occluder_poly->owners.erase(occluder);
}
-
}
if (occluder->canvas.is_valid() && canvas_owner.owns(occluder->canvas)) {
Canvas *canvas = canvas_owner.get(occluder->canvas);
canvas->occluders.erase(occluder);
-
}
- canvas_light_occluder_owner.free( p_rid );
+ canvas_light_occluder_owner.free(p_rid);
memdelete(occluder);
} else if (canvas_light_occluder_polygon_owner.owns(p_rid)) {
LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_rid);
- ERR_FAIL_COND_V(!occluder_poly,true);
+ ERR_FAIL_COND_V(!occluder_poly, true);
VSG::storage->free(occluder_poly->occluder);
- while(occluder_poly->owners.size()) {
+ while (occluder_poly->owners.size()) {
- occluder_poly->owners.front()->get()->polygon=RID();
- occluder_poly->owners.erase( occluder_poly->owners.front() );
+ occluder_poly->owners.front()->get()->polygon = RID();
+ occluder_poly->owners.erase(occluder_poly->owners.front());
}
- canvas_light_occluder_polygon_owner.free( p_rid );
+ canvas_light_occluder_polygon_owner.free(p_rid);
memdelete(occluder_poly);
} else {
return false;
@@ -1290,9 +1192,5 @@ bool VisualServerCanvas::free(RID p_rid) {
return true;
}
-
-
-VisualServerCanvas::VisualServerCanvas()
-{
-
+VisualServerCanvas::VisualServerCanvas() {
}
diff --git a/servers/visual/visual_server_canvas.h b/servers/visual/visual_server_canvas.h
index b405bc804d..3c2dde17d5 100644
--- a/servers/visual/visual_server_canvas.h
+++ b/servers/visual/visual_server_canvas.h
@@ -34,13 +34,10 @@
class VisualServerCanvas {
public:
-
-
struct Item : public RasterizerCanvas::Item {
-
RID parent; // canvas it belongs to
- List<Item*>::Element *E;
+ List<Item *>::Element *E;
int z;
bool z_relative;
bool sort_y;
@@ -50,29 +47,26 @@ public:
int index;
bool children_order_dirty;
-
- Vector<Item*> child_items;
-
+ Vector<Item *> child_items;
Item() {
- children_order_dirty=true;
- E=NULL;
- z=0;
- modulate=Color(1,1,1,1);
- self_modulate=Color(1,1,1,1);
- sort_y=false;
- use_parent_material=false;
- z_relative=true;
- index=0;
+ children_order_dirty = true;
+ E = NULL;
+ z = 0;
+ modulate = Color(1, 1, 1, 1);
+ self_modulate = Color(1, 1, 1, 1);
+ sort_y = false;
+ use_parent_material = false;
+ z_relative = true;
+ index = 0;
}
};
-
struct ItemPtrSort {
- _FORCE_INLINE_ bool operator()(const Item* p_left,const Item* p_right) const {
+ _FORCE_INLINE_ bool operator()(const Item *p_left, const Item *p_right) const {
- if(Math::abs(p_left->xform.elements[2].y - p_right->xform.elements[2].y) < CMP_EPSILON )
+ if (Math::abs(p_left->xform.elements[2].y - p_right->xform.elements[2].y) < CMP_EPSILON)
return p_left->xform.elements[2].x < p_right->xform.elements[2].x;
else
return p_left->xform.elements[2].y < p_right->xform.elements[2].y;
@@ -85,12 +79,14 @@ public:
Rect2 aabb;
VS::CanvasOccluderPolygonCullMode cull_mode;
RID occluder;
- Set<RasterizerCanvas::LightOccluderInstance*> owners;
+ Set<RasterizerCanvas::LightOccluderInstance *> owners;
- LightOccluderPolygon() { active=false; cull_mode=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; }
+ LightOccluderPolygon() {
+ active = false;
+ cull_mode = VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
+ }
};
-
RID_Owner<LightOccluderPolygon> canvas_light_occluder_polygon_owner;
RID_Owner<RasterizerCanvas::LightOccluderInstance> canvas_light_occluder_owner;
@@ -102,91 +98,86 @@ public:
Point2 mirror;
Item *item;
- bool operator<(const ChildItem& p_item) const {
+ bool operator<(const ChildItem &p_item) const {
return item->index < p_item.item->index;
}
};
+ Set<RasterizerCanvas::Light *> lights;
-
- Set<RasterizerCanvas::Light*> lights;
-
- Set<RasterizerCanvas::LightOccluderInstance*> occluders;
+ Set<RasterizerCanvas::LightOccluderInstance *> occluders;
bool children_order_dirty;
Vector<ChildItem> child_items;
Color modulate;
int find_item(Item *p_item) {
- for(int i=0;i<child_items.size();i++) {
- if (child_items[i].item==p_item)
+ for (int i = 0; i < child_items.size(); i++) {
+ if (child_items[i].item == p_item)
return i;
}
return -1;
}
void erase_item(Item *p_item) {
- int idx=find_item(p_item);
- if (idx>=0)
+ int idx = find_item(p_item);
+ if (idx >= 0)
child_items.remove(idx);
}
-
- Canvas() { modulate=Color(1,1,1,1); children_order_dirty=true; }
-
+ Canvas() {
+ modulate = Color(1, 1, 1, 1);
+ children_order_dirty = true;
+ }
};
-
RID_Owner<Canvas> canvas_owner;
RID_Owner<Item> canvas_item_owner;
RID_Owner<RasterizerCanvas::Light> canvas_light_owner;
private:
+ void _render_canvas_item_tree(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights);
+ void _render_canvas_item(Item *p_canvas_item, const Transform2D &p_transform, const Rect2 &p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner);
+ void _light_mask_canvas_items(int p_z, RasterizerCanvas::Item *p_canvas_item, RasterizerCanvas::Light *p_masked_lights);
- void _render_canvas_item_tree(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color &p_modulate, RasterizerCanvas::Light *p_lights);
- void _render_canvas_item(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color &p_modulate, int p_z, RasterizerCanvas::Item **z_list, RasterizerCanvas::Item **z_last_list, Item *p_canvas_clip, Item *p_material_owner);
- void _light_mask_canvas_items(int p_z,RasterizerCanvas::Item *p_canvas_item,RasterizerCanvas::Light *p_masked_lights);
public:
-
- void render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights,const Rect2& p_clip_rect);
+ void render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights, const Rect2 &p_clip_rect);
RID canvas_create();
- void canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring);
- void canvas_set_modulate(RID p_canvas,const Color& p_color);
-
+ void canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring);
+ void canvas_set_modulate(RID p_canvas, const Color &p_color);
RID canvas_item_create();
- void canvas_item_set_parent(RID p_item,RID p_parent);
+ void canvas_item_set_parent(RID p_item, RID p_parent);
- void canvas_item_set_visible(RID p_item,bool p_visible);
- void canvas_item_set_light_mask(RID p_item,int p_mask);
+ void canvas_item_set_visible(RID p_item, bool p_visible);
+ void canvas_item_set_light_mask(RID p_item, int p_mask);
- void canvas_item_set_transform(RID p_item, const Transform2D& p_transform);
+ void canvas_item_set_transform(RID p_item, const Transform2D &p_transform);
void canvas_item_set_clip(RID p_item, bool p_clip);
void canvas_item_set_distance_field_mode(RID p_item, bool p_enable);
- void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect=Rect2());
- void canvas_item_set_modulate(RID p_item, const Color& p_color);
- void canvas_item_set_self_modulate(RID p_item, const Color& p_color);
+ void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect = Rect2());
+ void canvas_item_set_modulate(RID p_item, const Color &p_color);
+ void canvas_item_set_self_modulate(RID p_item, const Color &p_color);
void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable);
-
- void canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width=1.0,bool p_antialiased=false);
- void canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color);
- void canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color);
- void canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile=false,const Color& p_modulate=Color(1,1,1),bool p_transpose=false);
- void canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1),bool p_transpose=false);
- void canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,VS::NinePatchAxisMode p_x_axis_mode=VS::NINE_PATCH_STRETCH, VS::NinePatchAxisMode p_y_axis_mode=VS::NINE_PATCH_STRETCH,bool p_draw_center=true,const Color& p_modulate=Color(1,1,1));
- void canvas_item_add_primitive(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width=1.0);
- void canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID());
- void canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID(), int p_count=-1);
- void canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton=RID());
- void canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton=RID());
- void canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform);
+ void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false);
+ void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color);
+ void canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color);
+ void canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false);
+ void canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false);
+ void canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, VS::NinePatchAxisMode p_x_axis_mode = VS::NINE_PATCH_STRETCH, VS::NinePatchAxisMode p_y_axis_mode = VS::NINE_PATCH_STRETCH, bool p_draw_center = true, const Color &p_modulate = Color(1, 1, 1));
+ void canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width = 1.0);
+ void canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID());
+ void canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID(), int p_count = -1);
+ void canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton = RID());
+ void canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton = RID());
+ void canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform);
void canvas_item_add_clip_ignore(RID p_item, bool p_ignore);
void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable);
void canvas_item_set_z(RID p_item, int p_z);
void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable);
- void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect);
+ void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect);
void canvas_item_clear(RID p_item);
void canvas_item_set_draw_index(RID p_item, int p_index);
@@ -196,50 +187,43 @@ public:
void canvas_item_set_use_parent_material(RID p_item, bool p_enable);
RID canvas_light_create();
- void canvas_light_attach_to_canvas(RID p_light,RID p_canvas);
+ void canvas_light_attach_to_canvas(RID p_light, RID p_canvas);
void canvas_light_set_enabled(RID p_light, bool p_enabled);
void canvas_light_set_scale(RID p_light, float p_scale);
- void canvas_light_set_transform(RID p_light, const Transform2D& p_transform);
+ void canvas_light_set_transform(RID p_light, const Transform2D &p_transform);
void canvas_light_set_texture(RID p_light, RID p_texture);
- void canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset);
- void canvas_light_set_color(RID p_light, const Color& p_color);
+ void canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset);
+ void canvas_light_set_color(RID p_light, const Color &p_color);
void canvas_light_set_height(RID p_light, float p_height);
void canvas_light_set_energy(RID p_light, float p_energy);
- void canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z);
- void canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer);
+ void canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z);
+ void canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer);
void canvas_light_set_item_cull_mask(RID p_light, int p_mask);
void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask);
void canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode);
-
void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled);
void canvas_light_set_shadow_buffer_size(RID p_light, int p_size);
void canvas_light_set_shadow_gradient_length(RID p_light, float p_length);
void canvas_light_set_shadow_filter(RID p_light, VS::CanvasLightShadowFilter p_filter);
- void canvas_light_set_shadow_color(RID p_light, const Color& p_color);
-
-
+ void canvas_light_set_shadow_color(RID p_light, const Color &p_color);
RID canvas_light_occluder_create();
- void canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas);
- void canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled);
- void canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon);
- void canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform);
- void canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask);
+ void canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas);
+ void canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled);
+ void canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon);
+ void canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform);
+ void canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask);
RID canvas_occluder_polygon_create();
- void canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed);
- void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape);
-
-
- void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,VS::CanvasOccluderPolygonCullMode p_mode);
+ void canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed);
+ void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape);
+ void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, VS::CanvasOccluderPolygonCullMode p_mode);
bool free(RID p_rid);
VisualServerCanvas();
-
-
};
#endif // VISUALSERVERCANVAS_H
diff --git a/servers/visual/visual_server_global.cpp b/servers/visual/visual_server_global.cpp
index 3704192c7e..75506f7add 100644
--- a/servers/visual/visual_server_global.cpp
+++ b/servers/visual/visual_server_global.cpp
@@ -28,11 +28,11 @@
/*************************************************************************/
#include "visual_server_global.h"
-RasterizerStorage *VisualServerGlobals::storage=NULL;
-RasterizerCanvas *VisualServerGlobals::canvas_render=NULL;
-RasterizerScene *VisualServerGlobals::scene_render=NULL;
-Rasterizer *VisualServerGlobals::rasterizer=NULL;
+RasterizerStorage *VisualServerGlobals::storage = NULL;
+RasterizerCanvas *VisualServerGlobals::canvas_render = NULL;
+RasterizerScene *VisualServerGlobals::scene_render = NULL;
+Rasterizer *VisualServerGlobals::rasterizer = NULL;
-VisualServerCanvas *VisualServerGlobals::canvas=NULL;
-VisualServerViewport *VisualServerGlobals::viewport=NULL;
-VisualServerScene *VisualServerGlobals::scene=NULL;
+VisualServerCanvas *VisualServerGlobals::canvas = NULL;
+VisualServerViewport *VisualServerGlobals::viewport = NULL;
+VisualServerScene *VisualServerGlobals::scene = NULL;
diff --git a/servers/visual/visual_server_global.h b/servers/visual/visual_server_global.h
index f95aed3ffb..d55059cd55 100644
--- a/servers/visual/visual_server_global.h
+++ b/servers/visual/visual_server_global.h
@@ -35,10 +35,8 @@ class VisualServerCanvas;
class VisualServerViewport;
class VisualServerScene;
-class VisualServerGlobals
-{
+class VisualServerGlobals {
public:
-
static RasterizerStorage *storage;
static RasterizerCanvas *canvas_render;
static RasterizerScene *scene_render;
diff --git a/servers/visual/visual_server_light_baker.cpp b/servers/visual/visual_server_light_baker.cpp
index bdf20df618..493eeb49ca 100644
--- a/servers/visual/visual_server_light_baker.cpp
+++ b/servers/visual/visual_server_light_baker.cpp
@@ -28,7 +28,5 @@
/*************************************************************************/
#include "visual_server_light_baker.h"
-VisualServerLightBaker::VisualServerLightBaker()
-{
-
+VisualServerLightBaker::VisualServerLightBaker() {
}
diff --git a/servers/visual/visual_server_light_baker.h b/servers/visual/visual_server_light_baker.h
index 416c16ed3a..82909bb082 100644
--- a/servers/visual/visual_server_light_baker.h
+++ b/servers/visual/visual_server_light_baker.h
@@ -33,7 +33,6 @@
class VisualServerLightBaker {
public:
-
struct BakeCell {
uint32_t cells[8];
@@ -43,14 +42,8 @@ public:
uint32_t light[4]; //accumulated light in 16:16 fixed point (needs to be integer for moving lights fast)
float alpha; //used for upsampling
uint32_t directional_pass; //used for baking directional
-
};
-
-
-
-
-
VisualServerLightBaker();
};
diff --git a/servers/visual/visual_server_raster.cpp b/servers/visual/visual_server_raster.cpp
index 3a5ffda8f5..2666a95595 100644
--- a/servers/visual/visual_server_raster.cpp
+++ b/servers/visual/visual_server_raster.cpp
@@ -27,48 +27,37 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "visual_server_raster.h"
-#include "os/os.h"
-#include "global_config.h"
#include "default_mouse_cursor.xpm"
-#include "sort.h"
+#include "global_config.h"
#include "io/marshalls.h"
+#include "os/os.h"
+#include "sort.h"
#include "visual_server_canvas.h"
#include "visual_server_global.h"
#include "visual_server_scene.h"
// careful, these may run in different threads than the visual server
-
-
-
/* CURSOR */
-void VisualServerRaster::cursor_set_rotation(float p_rotation, int p_cursor ){
-
+void VisualServerRaster::cursor_set_rotation(float p_rotation, int p_cursor) {
}
-void VisualServerRaster::cursor_set_texture(RID p_texture, const Point2 &p_center_offset, int p_cursor, const Rect2 &p_region){
-
+void VisualServerRaster::cursor_set_texture(RID p_texture, const Point2 &p_center_offset, int p_cursor, const Rect2 &p_region) {
}
-void VisualServerRaster::cursor_set_visible(bool p_visible, int p_cursor ){
-
+void VisualServerRaster::cursor_set_visible(bool p_visible, int p_cursor) {
}
-void VisualServerRaster::cursor_set_pos(const Point2& p_pos, int p_cursor ){
-
+void VisualServerRaster::cursor_set_pos(const Point2 &p_pos, int p_cursor) {
}
/* BLACK BARS */
-
-void VisualServerRaster::black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom){
-
+void VisualServerRaster::black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom) {
}
-void VisualServerRaster::black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom){
-
+void VisualServerRaster::black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom) {
}
-
/* FREE */
-void VisualServerRaster::free( RID p_rid ){
+void VisualServerRaster::free(RID p_rid) {
if (VSG::storage->free(p_rid))
return;
@@ -78,19 +67,18 @@ void VisualServerRaster::free( RID p_rid ){
return;
if (VSG::scene->free(p_rid))
return;
-
}
/* EVENT QUEUING */
-void VisualServerRaster::draw(){
+void VisualServerRaster::draw() {
/*
if (changes)
print_line("changes: "+itos(changes));
*/
- changes=0;
+ changes = 0;
VSG::rasterizer->begin_frame();
@@ -102,19 +90,17 @@ void VisualServerRaster::draw(){
VSG::rasterizer->end_frame();
//draw_extra_frame=VS:rasterizer->needs_to_draw_next_frame();
}
-void VisualServerRaster::sync(){
-
+void VisualServerRaster::sync() {
}
-bool VisualServerRaster::has_changed() const{
+bool VisualServerRaster::has_changed() const {
- return changes>0;
+ return changes > 0;
}
-void VisualServerRaster::init(){
+void VisualServerRaster::init() {
VSG::rasterizer->initialize();
-
}
-void VisualServerRaster::finish(){
+void VisualServerRaster::finish() {
if (test_cube.is_valid()) {
free(test_cube);
@@ -123,26 +109,18 @@ void VisualServerRaster::finish(){
VSG::rasterizer->finalize();
}
-
/* STATUS INFORMATION */
-
-int VisualServerRaster::get_render_info(RenderInfo p_info){
+int VisualServerRaster::get_render_info(RenderInfo p_info) {
return 0;
}
-
-
/* TESTING */
-
-
-void VisualServerRaster::set_boot_image(const Image& p_image, const Color& p_color,bool p_scale){
-
+void VisualServerRaster::set_boot_image(const Image &p_image, const Color &p_color, bool p_scale) {
}
-void VisualServerRaster::set_default_clear_color(const Color& p_color){
-
+void VisualServerRaster::set_default_clear_color(const Color &p_color) {
}
bool VisualServerRaster::has_feature(Features p_feature) const {
@@ -152,27 +130,25 @@ bool VisualServerRaster::has_feature(Features p_feature) const {
RID VisualServerRaster::get_test_cube() {
if (!test_cube.is_valid()) {
- test_cube=_make_test_cube();
+ test_cube = _make_test_cube();
}
return test_cube;
}
-
-bool VisualServerRaster::has_os_feature(const String& p_feature) const {
+bool VisualServerRaster::has_os_feature(const String &p_feature) const {
return VSG::storage->has_os_feature(p_feature);
}
VisualServerRaster::VisualServerRaster() {
- VSG::canvas = memnew( VisualServerCanvas);
- VSG::viewport = memnew( VisualServerViewport);
- VSG::scene = memnew( VisualServerScene );
+ VSG::canvas = memnew(VisualServerCanvas);
+ VSG::viewport = memnew(VisualServerViewport);
+ VSG::scene = memnew(VisualServerScene);
VSG::rasterizer = Rasterizer::create();
- VSG::storage=VSG::rasterizer->get_storage();
- VSG::canvas_render=VSG::rasterizer->get_canvas();
- VSG::scene_render=VSG::rasterizer->get_scene();
-
+ VSG::storage = VSG::rasterizer->get_storage();
+ VSG::canvas_render = VSG::rasterizer->get_canvas();
+ VSG::scene_render = VSG::rasterizer->get_scene();
}
VisualServerRaster::~VisualServerRaster() {
@@ -182,12 +158,11 @@ VisualServerRaster::~VisualServerRaster() {
memdelete(VSG::rasterizer);
}
-
#if 0
BalloonAllocator<> *VisualServerRaster::OctreeAllocator::allocator=NULL;
-#define VS_CHANGED\
+#define VS_CHANGED \
changes++;\
//print_line(__FUNCTION__);
@@ -5371,8 +5346,6 @@ CameraMatrix _lispm_look( const Vector3 pos, const Vector3 dir, const Vector3 up
return cmout;
}
-
-
#if 1
void VisualServerRaster::_light_instance_update_lispsm_shadow(Instance *p_light,Scenario *p_scenario,Camera *p_camera,const CullRange& p_cull_range) {
diff --git a/servers/visual/visual_server_raster.h b/servers/visual/visual_server_raster.h
index 7d547e1862..58e07057f2 100644
--- a/servers/visual/visual_server_raster.h
+++ b/servers/visual/visual_server_raster.h
@@ -29,36 +29,30 @@
#ifndef VISUAL_SERVER_RASTER_H
#define VISUAL_SERVER_RASTER_H
-
-#include "servers/visual_server.h"
-#include "servers/visual/rasterizer.h"
#include "allocators.h"
#include "octree.h"
-#include "visual_server_global.h"
-#include "visual_server_viewport.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/visual_server.h"
#include "visual_server_canvas.h"
+#include "visual_server_global.h"
#include "visual_server_scene.h"
+#include "visual_server_viewport.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
-
-
-
class VisualServerRaster : public VisualServer {
-
enum {
- MAX_INSTANCE_CULL=8192,
- MAX_INSTANCE_LIGHTS=4,
- LIGHT_CACHE_DIRTY=-1,
- MAX_LIGHTS_CULLED=256,
- MAX_ROOM_CULL=32,
- MAX_EXTERIOR_PORTALS=128,
- MAX_LIGHT_SAMPLERS=256,
- INSTANCE_ROOMLESS_MASK=(1<<20)
-
+ MAX_INSTANCE_CULL = 8192,
+ MAX_INSTANCE_LIGHTS = 4,
+ LIGHT_CACHE_DIRTY = -1,
+ MAX_LIGHTS_CULLED = 256,
+ MAX_ROOM_CULL = 32,
+ MAX_EXTERIOR_PORTALS = 128,
+ MAX_LIGHT_SAMPLERS = 256,
+ INSTANCE_ROOMLESS_MASK = (1 << 20)
};
@@ -66,8 +60,7 @@ class VisualServerRaster : public VisualServer {
bool draw_extra_frame;
RID test_cube;
-
- #if 0
+#if 0
struct Room {
bool occlude_exterior;
@@ -582,293 +575,299 @@ class VisualServerRaster : public VisualServer {
#endif
public:
-
#define DISPLAY_CHANGED changes++;
-#define BIND0R(m_r,m_name) m_r m_name() { return BINDBASE->m_name(); }
-#define BIND1R(m_r,m_name,m_type1) m_r m_name(m_type1 arg1) { return BINDBASE->m_name(arg1); }
-#define BIND1RC(m_r,m_name,m_type1) m_r m_name(m_type1 arg1) const { return BINDBASE->m_name(arg1); }
-#define BIND2RC(m_r,m_name,m_type1,m_type2) m_r m_name(m_type1 arg1,m_type2 arg2) const { return BINDBASE->m_name(arg1,arg2); }
-#define BIND3RC(m_r,m_name,m_type1,m_type2,m_type3) m_r m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3) const { return BINDBASE->m_name(arg1,arg2,arg3); }
-#define BIND4RC(m_r,m_name,m_type1,m_type2,m_type3,m_type4) m_r m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4) const { return BINDBASE->m_name(arg1,arg2,arg3,arg4); }
-
-#define BIND1(m_name,m_type1) void m_name(m_type1 arg1) { DISPLAY_CHANGED BINDBASE->m_name(arg1); }
-#define BIND2(m_name,m_type1,m_type2) void m_name(m_type1 arg1,m_type2 arg2) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2); }
-#define BIND2C(m_name,m_type1,m_type2) void m_name(m_type1 arg1,m_type2 arg2) const { BINDBASE->m_name(arg1,arg2); }
-#define BIND3(m_name,m_type1,m_type2,m_type3) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3); }
-#define BIND4(m_name,m_type1,m_type2,m_type3,m_type4) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4); }
-#define BIND5(m_name,m_type1,m_type2,m_type3,m_type4,m_type5) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5); }
-#define BIND6(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6); }
-#define BIND7(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7); }
-#define BIND8(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); }
-#define BIND9(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8,m_type9) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8,m_type9 arg9) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); }
-#define BIND10(m_name,m_type1,m_type2,m_type3,m_type4,m_type5,m_type6,m_type7,m_type8,m_type9,m_type10) void m_name(m_type1 arg1,m_type2 arg2,m_type3 arg3,m_type4 arg4,m_type5 arg5,m_type6 arg6,m_type7 arg7,m_type8 arg8,m_type9 arg9,m_type10 arg10) { DISPLAY_CHANGED BINDBASE->m_name(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); }
+#define BIND0R(m_r, m_name) \
+ m_r m_name() { return BINDBASE->m_name(); }
+#define BIND1R(m_r, m_name, m_type1) \
+ m_r m_name(m_type1 arg1) { return BINDBASE->m_name(arg1); }
+#define BIND1RC(m_r, m_name, m_type1) \
+ m_r m_name(m_type1 arg1) const { return BINDBASE->m_name(arg1); }
+#define BIND2RC(m_r, m_name, m_type1, m_type2) \
+ m_r m_name(m_type1 arg1, m_type2 arg2) const { return BINDBASE->m_name(arg1, arg2); }
+#define BIND3RC(m_r, m_name, m_type1, m_type2, m_type3) \
+ m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) const { return BINDBASE->m_name(arg1, arg2, arg3); }
+#define BIND4RC(m_r, m_name, m_type1, m_type2, m_type3, m_type4) \
+ m_r m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) const { return BINDBASE->m_name(arg1, arg2, arg3, arg4); }
+
+#define BIND1(m_name, m_type1) \
+ void m_name(m_type1 arg1) { DISPLAY_CHANGED BINDBASE->m_name(arg1); }
+#define BIND2(m_name, m_type1, m_type2) \
+ void m_name(m_type1 arg1, m_type2 arg2) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2); }
+#define BIND2C(m_name, m_type1, m_type2) \
+ void m_name(m_type1 arg1, m_type2 arg2) const { BINDBASE->m_name(arg1, arg2); }
+#define BIND3(m_name, m_type1, m_type2, m_type3) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3); }
+#define BIND4(m_name, m_type1, m_type2, m_type3, m_type4) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4); }
+#define BIND5(m_name, m_type1, m_type2, m_type3, m_type4, m_type5) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5); }
+#define BIND6(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6); }
+#define BIND7(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }
+#define BIND8(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }
+#define BIND9(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); }
+#define BIND10(m_name, m_type1, m_type2, m_type3, m_type4, m_type5, m_type6, m_type7, m_type8, m_type9, m_type10) \
+ void m_name(m_type1 arg1, m_type2 arg2, m_type3 arg3, m_type4 arg4, m_type5 arg5, m_type6 arg6, m_type7 arg7, m_type8 arg8, m_type9 arg9, m_type10 arg10) { DISPLAY_CHANGED BINDBASE->m_name(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); }
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::storage
/* TEXTURE API */
+ BIND0R(RID, texture_create)
+ BIND5(texture_allocate, RID, int, int, Image::Format, uint32_t)
+ BIND3(texture_set_data, RID, const Image &, CubeMapSide)
+ BIND2RC(Image, texture_get_data, RID, CubeMapSide)
+ BIND2(texture_set_flags, RID, uint32_t)
+ BIND1RC(uint32_t, texture_get_flags, RID)
+ BIND1RC(Image::Format, texture_get_format, RID)
+ BIND1RC(uint32_t, texture_get_width, RID)
+ BIND1RC(uint32_t, texture_get_height, RID)
+ BIND3(texture_set_size_override, RID, int, int)
+ BIND2RC(RID, texture_create_radiance_cubemap, RID, int)
- BIND0R(RID,texture_create)
- BIND5(texture_allocate,RID,int,int,Image::Format,uint32_t)
- BIND3(texture_set_data,RID,const Image&,CubeMapSide)
- BIND2RC(Image,texture_get_data,RID,CubeMapSide)
- BIND2(texture_set_flags,RID,uint32_t)
- BIND1RC(uint32_t,texture_get_flags,RID)
- BIND1RC(Image::Format,texture_get_format,RID)
- BIND1RC(uint32_t,texture_get_width,RID)
- BIND1RC(uint32_t,texture_get_height,RID)
- BIND3(texture_set_size_override,RID,int,int)
- BIND2RC(RID,texture_create_radiance_cubemap,RID,int)
-
- BIND3(texture_set_detect_3d_callback,RID,TextureDetectCallback,void*)
- BIND3(texture_set_detect_srgb_callback,RID,TextureDetectCallback,void*)
+ BIND3(texture_set_detect_3d_callback, RID, TextureDetectCallback, void *)
+ BIND3(texture_set_detect_srgb_callback, RID, TextureDetectCallback, void *)
- BIND2(texture_set_path,RID,const String&)
- BIND1RC(String,texture_get_path,RID)
- BIND1(texture_set_shrink_all_x2_on_set_data,bool)
- BIND1(texture_debug_usage,List<TextureInfo>*)
+ BIND2(texture_set_path, RID, const String &)
+ BIND1RC(String, texture_get_path, RID)
+ BIND1(texture_set_shrink_all_x2_on_set_data, bool)
+ BIND1(texture_debug_usage, List<TextureInfo> *)
- BIND1(textures_keep_original,bool)
+ BIND1(textures_keep_original, bool)
/* SKYBOX API */
- BIND0R(RID,skybox_create)
- BIND3(skybox_set_texture,RID,RID,int)
+ BIND0R(RID, skybox_create)
+ BIND3(skybox_set_texture, RID, RID, int)
/* SHADER API */
- BIND1R(RID,shader_create,ShaderMode)
+ BIND1R(RID, shader_create, ShaderMode)
+ BIND2(shader_set_mode, RID, ShaderMode)
+ BIND1RC(ShaderMode, shader_get_mode, RID)
- BIND2(shader_set_mode,RID,ShaderMode)
- BIND1RC(ShaderMode,shader_get_mode,RID)
+ BIND2(shader_set_code, RID, const String &)
+ BIND1RC(String, shader_get_code, RID)
- BIND2(shader_set_code,RID,const String&)
- BIND1RC(String,shader_get_code,RID)
-
- BIND2C(shader_get_param_list,RID, List<PropertyInfo> *)
-
- BIND3(shader_set_default_texture_param,RID,const StringName&,RID)
- BIND2RC(RID,shader_get_default_texture_param,RID,const StringName&)
+ BIND2C(shader_get_param_list, RID, List<PropertyInfo> *)
+ BIND3(shader_set_default_texture_param, RID, const StringName &, RID)
+ BIND2RC(RID, shader_get_default_texture_param, RID, const StringName &)
/* COMMON MATERIAL API */
- BIND0R(RID,material_create)
-
- BIND2(material_set_shader,RID,RID)
- BIND1RC(RID,material_get_shader,RID)
-
- BIND3(material_set_param,RID, const StringName&, const Variant& )
- BIND2RC(Variant,material_get_param,RID, const StringName& )
+ BIND0R(RID, material_create)
- BIND2(material_set_line_width,RID, float )
+ BIND2(material_set_shader, RID, RID)
+ BIND1RC(RID, material_get_shader, RID)
+ BIND3(material_set_param, RID, const StringName &, const Variant &)
+ BIND2RC(Variant, material_get_param, RID, const StringName &)
+ BIND2(material_set_line_width, RID, float)
/* MESH API */
- BIND0R(RID,mesh_create)
+ BIND0R(RID, mesh_create)
- BIND10(mesh_add_surface,RID,uint32_t,PrimitiveType,const PoolVector<uint8_t>&,int ,const PoolVector<uint8_t>& ,int ,const Rect3&,const Vector<PoolVector<uint8_t> >&,const Vector<Rect3>& )
+ BIND10(mesh_add_surface, RID, uint32_t, PrimitiveType, const PoolVector<uint8_t> &, int, const PoolVector<uint8_t> &, int, const Rect3 &, const Vector<PoolVector<uint8_t> > &, const Vector<Rect3> &)
- BIND2(mesh_set_blend_shape_count,RID,int)
- BIND1RC(int,mesh_get_blend_shape_count,RID)
+ BIND2(mesh_set_blend_shape_count, RID, int)
+ BIND1RC(int, mesh_get_blend_shape_count, RID)
+ BIND2(mesh_set_blend_shape_mode, RID, BlendShapeMode)
+ BIND1RC(BlendShapeMode, mesh_get_blend_shape_mode, RID)
- BIND2(mesh_set_blend_shape_mode,RID,BlendShapeMode)
- BIND1RC(BlendShapeMode, mesh_get_blend_shape_mode,RID )
+ BIND3(mesh_surface_set_material, RID, int, RID)
+ BIND2RC(RID, mesh_surface_get_material, RID, int)
- BIND3(mesh_surface_set_material,RID, int , RID )
- BIND2RC(RID,mesh_surface_get_material,RID, int )
+ BIND2RC(int, mesh_surface_get_array_len, RID, int)
+ BIND2RC(int, mesh_surface_get_array_index_len, RID, int)
- BIND2RC(int,mesh_surface_get_array_len,RID,int)
- BIND2RC(int,mesh_surface_get_array_index_len,RID,int)
+ BIND2RC(PoolVector<uint8_t>, mesh_surface_get_array, RID, int)
+ BIND2RC(PoolVector<uint8_t>, mesh_surface_get_index_array, RID, int)
- BIND2RC(PoolVector<uint8_t>,mesh_surface_get_array,RID,int)
- BIND2RC(PoolVector<uint8_t>,mesh_surface_get_index_array,RID, int)
+ BIND2RC(uint32_t, mesh_surface_get_format, RID, int)
+ BIND2RC(PrimitiveType, mesh_surface_get_primitive_type, RID, int)
- BIND2RC(uint32_t,mesh_surface_get_format,RID,int)
- BIND2RC(PrimitiveType,mesh_surface_get_primitive_type,RID,int)
+ BIND2RC(Rect3, mesh_surface_get_aabb, RID, int)
+ BIND2RC(Vector<PoolVector<uint8_t> >, mesh_surface_get_blend_shapes, RID, int)
+ BIND2RC(Vector<Rect3>, mesh_surface_get_skeleton_aabb, RID, int)
- BIND2RC(Rect3,mesh_surface_get_aabb,RID,int)
- BIND2RC(Vector<PoolVector<uint8_t> >,mesh_surface_get_blend_shapes,RID,int)
- BIND2RC(Vector<Rect3>,mesh_surface_get_skeleton_aabb,RID,int)
+ BIND2(mesh_remove_surface, RID, int)
+ BIND1RC(int, mesh_get_surface_count, RID)
- BIND2(mesh_remove_surface,RID,int)
- BIND1RC(int,mesh_get_surface_count,RID)
+ BIND2(mesh_set_custom_aabb, RID, const Rect3 &)
+ BIND1RC(Rect3, mesh_get_custom_aabb, RID)
- BIND2(mesh_set_custom_aabb,RID,const Rect3&)
- BIND1RC(Rect3,mesh_get_custom_aabb,RID)
-
- BIND1(mesh_clear,RID)
+ BIND1(mesh_clear, RID)
/* MULTIMESH API */
+ BIND0R(RID, multimesh_create)
- BIND0R(RID,multimesh_create)
-
- BIND4(multimesh_allocate,RID,int,MultimeshTransformFormat,MultimeshColorFormat)
- BIND1RC(int,multimesh_get_instance_count,RID)
+ BIND4(multimesh_allocate, RID, int, MultimeshTransformFormat, MultimeshColorFormat)
+ BIND1RC(int, multimesh_get_instance_count, RID)
- BIND2(multimesh_set_mesh,RID,RID)
- BIND3(multimesh_instance_set_transform,RID,int,const Transform&)
- BIND3(multimesh_instance_set_transform_2d,RID,int,const Transform2D& )
- BIND3(multimesh_instance_set_color,RID,int,const Color&)
+ BIND2(multimesh_set_mesh, RID, RID)
+ BIND3(multimesh_instance_set_transform, RID, int, const Transform &)
+ BIND3(multimesh_instance_set_transform_2d, RID, int, const Transform2D &)
+ BIND3(multimesh_instance_set_color, RID, int, const Color &)
- BIND1RC(RID,multimesh_get_mesh,RID)
- BIND1RC(Rect3,multimesh_get_aabb,RID)
+ BIND1RC(RID, multimesh_get_mesh, RID)
+ BIND1RC(Rect3, multimesh_get_aabb, RID)
- BIND2RC(Transform,multimesh_instance_get_transform,RID,int )
- BIND2RC(Transform2D,multimesh_instance_get_transform_2d,RID,int)
- BIND2RC(Color,multimesh_instance_get_color,RID,int)
-
- BIND2(multimesh_set_visible_instances,RID,int)
- BIND1RC(int,multimesh_get_visible_instances,RID)
+ BIND2RC(Transform, multimesh_instance_get_transform, RID, int)
+ BIND2RC(Transform2D, multimesh_instance_get_transform_2d, RID, int)
+ BIND2RC(Color, multimesh_instance_get_color, RID, int)
+ BIND2(multimesh_set_visible_instances, RID, int)
+ BIND1RC(int, multimesh_get_visible_instances, RID)
/* IMMEDIATE API */
- BIND0R(RID,immediate_create)
- BIND3(immediate_begin,RID,PrimitiveType,RID)
- BIND2(immediate_vertex,RID,const Vector3&)
- BIND2(immediate_normal,RID,const Vector3&)
- BIND2(immediate_tangent,RID,const Plane&)
- BIND2(immediate_color,RID,const Color&)
- BIND2(immediate_uv,RID,const Vector2& )
- BIND2(immediate_uv2,RID,const Vector2&)
- BIND1(immediate_end,RID)
- BIND1(immediate_clear,RID)
- BIND2(immediate_set_material,RID ,RID )
- BIND1RC(RID,immediate_get_material,RID)
+ BIND0R(RID, immediate_create)
+ BIND3(immediate_begin, RID, PrimitiveType, RID)
+ BIND2(immediate_vertex, RID, const Vector3 &)
+ BIND2(immediate_normal, RID, const Vector3 &)
+ BIND2(immediate_tangent, RID, const Plane &)
+ BIND2(immediate_color, RID, const Color &)
+ BIND2(immediate_uv, RID, const Vector2 &)
+ BIND2(immediate_uv2, RID, const Vector2 &)
+ BIND1(immediate_end, RID)
+ BIND1(immediate_clear, RID)
+ BIND2(immediate_set_material, RID, RID)
+ BIND1RC(RID, immediate_get_material, RID)
/* SKELETON API */
- BIND0R(RID,skeleton_create)
- BIND3(skeleton_allocate,RID,int,bool)
- BIND1RC(int,skeleton_get_bone_count,RID)
- BIND3(skeleton_bone_set_transform,RID,int,const Transform&)
- BIND2RC(Transform,skeleton_bone_get_transform,RID,int)
- BIND3(skeleton_bone_set_transform_2d,RID,int, const Transform2D& )
- BIND2RC(Transform2D,skeleton_bone_get_transform_2d,RID,int)
+ BIND0R(RID, skeleton_create)
+ BIND3(skeleton_allocate, RID, int, bool)
+ BIND1RC(int, skeleton_get_bone_count, RID)
+ BIND3(skeleton_bone_set_transform, RID, int, const Transform &)
+ BIND2RC(Transform, skeleton_bone_get_transform, RID, int)
+ BIND3(skeleton_bone_set_transform_2d, RID, int, const Transform2D &)
+ BIND2RC(Transform2D, skeleton_bone_get_transform_2d, RID, int)
/* Light API */
- BIND1R(RID,light_create,LightType)
+ BIND1R(RID, light_create, LightType)
- BIND2(light_set_color,RID,const Color&)
- BIND3(light_set_param,RID ,LightParam ,float )
- BIND2(light_set_shadow,RID ,bool )
- BIND2(light_set_shadow_color,RID ,const Color& )
- BIND2(light_set_projector,RID,RID )
- BIND2(light_set_negative,RID,bool )
- BIND2(light_set_cull_mask,RID ,uint32_t )
+ BIND2(light_set_color, RID, const Color &)
+ BIND3(light_set_param, RID, LightParam, float)
+ BIND2(light_set_shadow, RID, bool)
+ BIND2(light_set_shadow_color, RID, const Color &)
+ BIND2(light_set_projector, RID, RID)
+ BIND2(light_set_negative, RID, bool)
+ BIND2(light_set_cull_mask, RID, uint32_t)
- BIND2(light_omni_set_shadow_mode,RID,LightOmniShadowMode)
- BIND2(light_omni_set_shadow_detail,RID,LightOmniShadowDetail)
+ BIND2(light_omni_set_shadow_mode, RID, LightOmniShadowMode)
+ BIND2(light_omni_set_shadow_detail, RID, LightOmniShadowDetail)
- BIND2(light_directional_set_shadow_mode,RID,LightDirectionalShadowMode)
- BIND2(light_directional_set_blend_splits,RID,bool)
+ BIND2(light_directional_set_shadow_mode, RID, LightDirectionalShadowMode)
+ BIND2(light_directional_set_blend_splits, RID, bool)
/* PROBE API */
- BIND0R(RID,reflection_probe_create)
-
- BIND2(reflection_probe_set_update_mode,RID, ReflectionProbeUpdateMode )
- BIND2(reflection_probe_set_intensity,RID, float )
- BIND2(reflection_probe_set_interior_ambient,RID, const Color& )
- BIND2(reflection_probe_set_interior_ambient_energy,RID, float )
- BIND2(reflection_probe_set_interior_ambient_probe_contribution,RID, float )
- BIND2(reflection_probe_set_max_distance,RID, float )
- BIND2(reflection_probe_set_extents,RID, const Vector3& )
- BIND2(reflection_probe_set_origin_offset,RID, const Vector3& )
- BIND2(reflection_probe_set_as_interior,RID, bool )
- BIND2(reflection_probe_set_enable_box_projection,RID, bool )
- BIND2(reflection_probe_set_enable_shadows,RID, bool )
- BIND2(reflection_probe_set_cull_mask,RID, uint32_t )
+ BIND0R(RID, reflection_probe_create)
+
+ BIND2(reflection_probe_set_update_mode, RID, ReflectionProbeUpdateMode)
+ BIND2(reflection_probe_set_intensity, RID, float)
+ BIND2(reflection_probe_set_interior_ambient, RID, const Color &)
+ BIND2(reflection_probe_set_interior_ambient_energy, RID, float)
+ BIND2(reflection_probe_set_interior_ambient_probe_contribution, RID, float)
+ BIND2(reflection_probe_set_max_distance, RID, float)
+ BIND2(reflection_probe_set_extents, RID, const Vector3 &)
+ BIND2(reflection_probe_set_origin_offset, RID, const Vector3 &)
+ BIND2(reflection_probe_set_as_interior, RID, bool)
+ BIND2(reflection_probe_set_enable_box_projection, RID, bool)
+ BIND2(reflection_probe_set_enable_shadows, RID, bool)
+ BIND2(reflection_probe_set_cull_mask, RID, uint32_t)
/* ROOM API */
- BIND0R(RID,room_create)
- BIND4(room_add_bounds,RID, const PoolVector<Vector2>& ,float ,const Transform& )
- BIND1(room_clear_bounds,RID)
+ BIND0R(RID, room_create)
+ BIND4(room_add_bounds, RID, const PoolVector<Vector2> &, float, const Transform &)
+ BIND1(room_clear_bounds, RID)
/* PORTAL API */
// portals are only (x/y) points, forming a convex shape, which its clockwise
// order points outside. (z is 0);
- BIND0R(RID,portal_create)
- BIND2(portal_set_shape,RID , const Vector<Point2>& )
- BIND2(portal_set_enabled,RID , bool )
- BIND2(portal_set_disable_distance,RID , float )
- BIND2(portal_set_disabled_color,RID , const Color& )
+ BIND0R(RID, portal_create)
+ BIND2(portal_set_shape, RID, const Vector<Point2> &)
+ BIND2(portal_set_enabled, RID, bool)
+ BIND2(portal_set_disable_distance, RID, float)
+ BIND2(portal_set_disabled_color, RID, const Color &)
/* BAKED LIGHT API */
BIND0R(RID, gi_probe_create)
- BIND2(gi_probe_set_bounds,RID,const Rect3&)
- BIND1RC(Rect3,gi_probe_get_bounds,RID)
+ BIND2(gi_probe_set_bounds, RID, const Rect3 &)
+ BIND1RC(Rect3, gi_probe_get_bounds, RID)
- BIND2(gi_probe_set_cell_size,RID,float)
- BIND1RC(float,gi_probe_get_cell_size,RID)
+ BIND2(gi_probe_set_cell_size, RID, float)
+ BIND1RC(float, gi_probe_get_cell_size, RID)
- BIND2(gi_probe_set_to_cell_xform,RID,const Transform&)
- BIND1RC(Transform,gi_probe_get_to_cell_xform,RID)
+ BIND2(gi_probe_set_to_cell_xform, RID, const Transform &)
+ BIND1RC(Transform, gi_probe_get_to_cell_xform, RID)
- BIND2(gi_probe_set_dynamic_range,RID,int)
- BIND1RC(int,gi_probe_get_dynamic_range,RID)
+ BIND2(gi_probe_set_dynamic_range, RID, int)
+ BIND1RC(int, gi_probe_get_dynamic_range, RID)
- BIND2(gi_probe_set_energy,RID,float)
- BIND1RC(float,gi_probe_get_energy,RID)
+ BIND2(gi_probe_set_energy, RID, float)
+ BIND1RC(float, gi_probe_get_energy, RID)
- BIND2(gi_probe_set_bias,RID,float)
- BIND1RC(float,gi_probe_get_bias,RID)
+ BIND2(gi_probe_set_bias, RID, float)
+ BIND1RC(float, gi_probe_get_bias, RID)
- BIND2(gi_probe_set_propagation,RID,float)
- BIND1RC(float,gi_probe_get_propagation,RID)
+ BIND2(gi_probe_set_propagation, RID, float)
+ BIND1RC(float, gi_probe_get_propagation, RID)
- BIND2(gi_probe_set_interior,RID,bool)
- BIND1RC(bool,gi_probe_is_interior,RID)
+ BIND2(gi_probe_set_interior, RID, bool)
+ BIND1RC(bool, gi_probe_is_interior, RID)
- BIND2(gi_probe_set_compress,RID,bool)
- BIND1RC(bool,gi_probe_is_compressed,RID)
+ BIND2(gi_probe_set_compress, RID, bool)
+ BIND1RC(bool, gi_probe_is_compressed, RID)
- BIND2(gi_probe_set_dynamic_data,RID,const PoolVector<int>& )
- BIND1RC( PoolVector<int>,gi_probe_get_dynamic_data,RID)
+ BIND2(gi_probe_set_dynamic_data, RID, const PoolVector<int> &)
+ BIND1RC(PoolVector<int>, gi_probe_get_dynamic_data, RID)
/* PARTICLES */
BIND0R(RID, particles_create)
- BIND2(particles_set_emitting,RID,bool)
- BIND2(particles_set_amount,RID,int )
- BIND2(particles_set_lifetime,RID,float )
- BIND2(particles_set_pre_process_time,RID,float )
- BIND2(particles_set_explosiveness_ratio,RID,float )
- BIND2(particles_set_randomness_ratio,RID,float )
- BIND2(particles_set_custom_aabb,RID,const Rect3& )
- BIND2(particles_set_gravity,RID,const Vector3& )
- BIND2(particles_set_use_local_coordinates,RID,bool )
- BIND2(particles_set_process_material,RID,RID )
-
- BIND2(particles_set_emission_shape,RID,VS::ParticlesEmissionShape )
- BIND2(particles_set_emission_sphere_radius,RID,float )
- BIND2(particles_set_emission_box_extents,RID,const Vector3& )
- BIND2(particles_set_emission_points,RID,const PoolVector<Vector3>& )
+ BIND2(particles_set_emitting, RID, bool)
+ BIND2(particles_set_amount, RID, int)
+ BIND2(particles_set_lifetime, RID, float)
+ BIND2(particles_set_pre_process_time, RID, float)
+ BIND2(particles_set_explosiveness_ratio, RID, float)
+ BIND2(particles_set_randomness_ratio, RID, float)
+ BIND2(particles_set_custom_aabb, RID, const Rect3 &)
+ BIND2(particles_set_gravity, RID, const Vector3 &)
+ BIND2(particles_set_use_local_coordinates, RID, bool)
+ BIND2(particles_set_process_material, RID, RID)
+ BIND2(particles_set_emission_shape, RID, VS::ParticlesEmissionShape)
+ BIND2(particles_set_emission_sphere_radius, RID, float)
+ BIND2(particles_set_emission_box_extents, RID, const Vector3 &)
+ BIND2(particles_set_emission_points, RID, const PoolVector<Vector3> &)
- BIND2(particles_set_draw_order,RID,VS::ParticlesDrawOrder )
+ BIND2(particles_set_draw_order, RID, VS::ParticlesDrawOrder)
- BIND2(particles_set_draw_passes,RID,int )
- BIND3(particles_set_draw_pass_material,RID,int , RID )
- BIND3(particles_set_draw_pass_mesh,RID,int , RID )
-
- BIND1R(Rect3,particles_get_current_aabb,RID);
+ BIND2(particles_set_draw_passes, RID, int)
+ BIND3(particles_set_draw_pass_material, RID, int, RID)
+ BIND3(particles_set_draw_pass_mesh, RID, int, RID)
+ BIND1R(Rect3, particles_get_current_aabb, RID);
#undef BINDBASE
//from now on, calls forwarded to this singleton
@@ -876,14 +875,13 @@ public:
/* CAMERA API */
-
BIND0R(RID, camera_create)
- BIND4(camera_set_perspective,RID,float, float , float )
- BIND4(camera_set_orthogonal,RID,float , float , float )
- BIND2(camera_set_transform,RID,const Transform&)
- BIND2(camera_set_cull_mask,RID,uint32_t )
- BIND2(camera_set_environment,RID ,RID )
- BIND2(camera_set_use_vertical_aspect,RID,bool)
+ BIND4(camera_set_perspective, RID, float, float, float)
+ BIND4(camera_set_orthogonal, RID, float, float, float)
+ BIND2(camera_set_transform, RID, const Transform &)
+ BIND2(camera_set_cull_mask, RID, uint32_t)
+ BIND2(camera_set_environment, RID, RID)
+ BIND2(camera_set_use_vertical_aspect, RID, bool)
#undef BINDBASE
//from now on, calls forwarded to this singleton
@@ -891,122 +889,112 @@ public:
/* VIEWPORT TARGET API */
- BIND0R(RID,viewport_create)
-
- BIND3(viewport_set_size,RID,int ,int )
-
- BIND2(viewport_set_active,RID ,bool )
- BIND2(viewport_set_parent_viewport,RID,RID)
+ BIND0R(RID, viewport_create)
- BIND2(viewport_set_clear_mode,RID,ViewportClearMode )
+ BIND3(viewport_set_size, RID, int, int)
- BIND3(viewport_attach_to_screen,RID ,const Rect2& ,int )
- BIND1(viewport_detach,RID)
+ BIND2(viewport_set_active, RID, bool)
+ BIND2(viewport_set_parent_viewport, RID, RID)
- BIND2(viewport_set_update_mode,RID,ViewportUpdateMode )
- BIND2(viewport_set_vflip,RID,bool)
+ BIND2(viewport_set_clear_mode, RID, ViewportClearMode)
+ BIND3(viewport_attach_to_screen, RID, const Rect2 &, int)
+ BIND1(viewport_detach, RID)
- BIND1RC(RID,viewport_get_texture,RID )
+ BIND2(viewport_set_update_mode, RID, ViewportUpdateMode)
+ BIND2(viewport_set_vflip, RID, bool)
- BIND2(viewport_set_hide_scenario,RID,bool )
- BIND2(viewport_set_hide_canvas,RID,bool )
- BIND2(viewport_set_disable_environment,RID,bool )
- BIND2(viewport_set_disable_3d,RID,bool )
+ BIND1RC(RID, viewport_get_texture, RID)
- BIND2(viewport_attach_camera,RID,RID )
- BIND2(viewport_set_scenario,RID,RID )
- BIND2(viewport_attach_canvas,RID,RID )
+ BIND2(viewport_set_hide_scenario, RID, bool)
+ BIND2(viewport_set_hide_canvas, RID, bool)
+ BIND2(viewport_set_disable_environment, RID, bool)
+ BIND2(viewport_set_disable_3d, RID, bool)
- BIND2(viewport_remove_canvas,RID,RID )
- BIND3(viewport_set_canvas_transform,RID ,RID ,const Transform2D& )
- BIND2(viewport_set_transparent_background,RID ,bool )
+ BIND2(viewport_attach_camera, RID, RID)
+ BIND2(viewport_set_scenario, RID, RID)
+ BIND2(viewport_attach_canvas, RID, RID)
- BIND2(viewport_set_global_canvas_transform,RID,const Transform2D& )
- BIND3(viewport_set_canvas_layer,RID ,RID ,int )
- BIND2(viewport_set_shadow_atlas_size,RID ,int )
- BIND3(viewport_set_shadow_atlas_quadrant_subdivision,RID ,int, int )
- BIND2(viewport_set_msaa,RID ,ViewportMSAA )
- BIND2(viewport_set_hdr,RID ,bool )
+ BIND2(viewport_remove_canvas, RID, RID)
+ BIND3(viewport_set_canvas_transform, RID, RID, const Transform2D &)
+ BIND2(viewport_set_transparent_background, RID, bool)
+ BIND2(viewport_set_global_canvas_transform, RID, const Transform2D &)
+ BIND3(viewport_set_canvas_layer, RID, RID, int)
+ BIND2(viewport_set_shadow_atlas_size, RID, int)
+ BIND3(viewport_set_shadow_atlas_quadrant_subdivision, RID, int, int)
+ BIND2(viewport_set_msaa, RID, ViewportMSAA)
+ BIND2(viewport_set_hdr, RID, bool)
- /* ENVIRONMENT API */
+/* ENVIRONMENT API */
#undef BINDBASE
//from now on, calls forwarded to this singleton
#define BINDBASE VSG::scene_render
- BIND0R(RID,environment_create)
-
- BIND2(environment_set_background,RID ,EnvironmentBG )
- BIND2(environment_set_skybox,RID,RID )
- BIND2(environment_set_skybox_scale,RID,float)
- BIND2(environment_set_bg_color,RID,const Color& )
- BIND2(environment_set_bg_energy,RID,float )
- BIND2(environment_set_canvas_max_layer,RID,int )
- BIND4(environment_set_ambient_light,RID,const Color& ,float,float )
- BIND8(environment_set_ssr,RID,bool,int,float,float,float,bool,bool )
- BIND10(environment_set_ssao,RID ,bool , float , float , float,float,float , float ,const Color &,bool )
-
-
-
- BIND6(environment_set_dof_blur_near,RID,bool ,float,float,float,EnvironmentDOFBlurQuality)
- BIND6(environment_set_dof_blur_far,RID,bool ,float,float,float,EnvironmentDOFBlurQuality)
- BIND10(environment_set_glow,RID,bool ,int ,float ,float ,float ,EnvironmentGlowBlendMode,float,float,bool )
- BIND5(environment_set_fog,RID,bool ,float ,float ,RID )
+ BIND0R(RID, environment_create)
- BIND9(environment_set_tonemap,RID,EnvironmentToneMapper, float ,float ,bool, float ,float ,float,float )
+ BIND2(environment_set_background, RID, EnvironmentBG)
+ BIND2(environment_set_skybox, RID, RID)
+ BIND2(environment_set_skybox_scale, RID, float)
+ BIND2(environment_set_bg_color, RID, const Color &)
+ BIND2(environment_set_bg_energy, RID, float)
+ BIND2(environment_set_canvas_max_layer, RID, int)
+ BIND4(environment_set_ambient_light, RID, const Color &, float, float)
+ BIND8(environment_set_ssr, RID, bool, int, float, float, float, bool, bool)
+ BIND10(environment_set_ssao, RID, bool, float, float, float, float, float, float, const Color &, bool)
- BIND6(environment_set_adjustment,RID,bool ,float ,float ,float ,RID )
+ BIND6(environment_set_dof_blur_near, RID, bool, float, float, float, EnvironmentDOFBlurQuality)
+ BIND6(environment_set_dof_blur_far, RID, bool, float, float, float, EnvironmentDOFBlurQuality)
+ BIND10(environment_set_glow, RID, bool, int, float, float, float, EnvironmentGlowBlendMode, float, float, bool)
+ BIND5(environment_set_fog, RID, bool, float, float, RID)
+ BIND9(environment_set_tonemap, RID, EnvironmentToneMapper, float, float, bool, float, float, float, float)
- /* SCENARIO API */
+ BIND6(environment_set_adjustment, RID, bool, float, float, float, RID)
+/* SCENARIO API */
#undef BINDBASE
#define BINDBASE VSG::scene
- BIND0R(RID,scenario_create)
-
- BIND2(scenario_set_debug,RID,ScenarioDebugMode )
- BIND2(scenario_set_environment,RID, RID )
- BIND3(scenario_set_reflection_atlas_size,RID, int,int )
- BIND2(scenario_set_fallback_environment,RID, RID )
+ BIND0R(RID, scenario_create)
+ BIND2(scenario_set_debug, RID, ScenarioDebugMode)
+ BIND2(scenario_set_environment, RID, RID)
+ BIND3(scenario_set_reflection_atlas_size, RID, int, int)
+ BIND2(scenario_set_fallback_environment, RID, RID)
/* INSTANCING API */
- // from can be mesh, light, area and portal so far.
- BIND0R(RID,instance_create)
-
- BIND2(instance_set_base,RID, RID ) // from can be mesh, light, poly, area and portal so far.
- BIND2(instance_set_scenario,RID, RID ) // from can be mesh, light, poly, area and portal so far.
- BIND2(instance_set_layer_mask,RID, uint32_t )
- BIND2(instance_set_transform,RID, const Transform& )
- BIND2(instance_attach_object_instance_ID,RID,ObjectID )
- BIND3(instance_set_blend_shape_weight,RID,int , float )
- BIND3(instance_set_surface_material,RID,int , RID )
- BIND2(instance_set_visible,RID ,bool)
+ // from can be mesh, light, area and portal so far.
+ BIND0R(RID, instance_create)
+ BIND2(instance_set_base, RID, RID) // from can be mesh, light, poly, area and portal so far.
+ BIND2(instance_set_scenario, RID, RID) // from can be mesh, light, poly, area and portal so far.
+ BIND2(instance_set_layer_mask, RID, uint32_t)
+ BIND2(instance_set_transform, RID, const Transform &)
+ BIND2(instance_attach_object_instance_ID, RID, ObjectID)
+ BIND3(instance_set_blend_shape_weight, RID, int, float)
+ BIND3(instance_set_surface_material, RID, int, RID)
+ BIND2(instance_set_visible, RID, bool)
- BIND2(instance_attach_skeleton,RID,RID )
- BIND2(instance_set_exterior, RID, bool )
- BIND2(instance_set_room, RID, RID )
+ BIND2(instance_attach_skeleton, RID, RID)
+ BIND2(instance_set_exterior, RID, bool)
+ BIND2(instance_set_room, RID, RID)
- BIND2(instance_set_extra_visibility_margin, RID, real_t )
+ BIND2(instance_set_extra_visibility_margin, RID, real_t)
// don't use these in a game!
- BIND2RC(Vector<ObjectID>,instances_cull_aabb,const Rect3& , RID)
- BIND3RC(Vector<ObjectID>,instances_cull_ray,const Vector3& , const Vector3& , RID )
- BIND2RC(Vector<ObjectID>,instances_cull_convex,const Vector<Plane>& , RID)
-
-
- BIND3(instance_geometry_set_flag,RID,InstanceFlags ,bool )
- BIND2(instance_geometry_set_cast_shadows_setting,RID, ShadowCastingSetting )
- BIND2(instance_geometry_set_material_override,RID, RID )
+ BIND2RC(Vector<ObjectID>, instances_cull_aabb, const Rect3 &, RID)
+ BIND3RC(Vector<ObjectID>, instances_cull_ray, const Vector3 &, const Vector3 &, RID)
+ BIND2RC(Vector<ObjectID>, instances_cull_convex, const Vector<Plane> &, RID)
+ BIND3(instance_geometry_set_flag, RID, InstanceFlags, bool)
+ BIND2(instance_geometry_set_cast_shadows_setting, RID, ShadowCastingSetting)
+ BIND2(instance_geometry_set_material_override, RID, RID)
- BIND5(instance_geometry_set_draw_range,RID,float ,float ,float ,float )
- BIND2(instance_geometry_set_as_instance_lod,RID,RID )
+ BIND5(instance_geometry_set_draw_range, RID, float, float, float, float)
+ BIND2(instance_geometry_set_as_instance_lod, RID, RID)
#undef BINDBASE
//from now on, calls forwarded to this singleton
@@ -1014,110 +1002,100 @@ public:
/* CANVAS (2D) */
- BIND0R(RID,canvas_create)
- BIND3(canvas_set_item_mirroring,RID ,RID ,const Point2& )
- BIND2(canvas_set_modulate,RID,const Color&)
-
-
- BIND0R(RID,canvas_item_create)
- BIND2(canvas_item_set_parent,RID ,RID)
-
- BIND2(canvas_item_set_visible,RID,bool )
- BIND2(canvas_item_set_light_mask,RID,int )
-
- BIND2(canvas_item_set_transform,RID, const Transform2D& )
- BIND2(canvas_item_set_clip,RID, bool )
- BIND2(canvas_item_set_distance_field_mode,RID, bool )
- BIND3(canvas_item_set_custom_rect,RID, bool ,const Rect2& )
- BIND2(canvas_item_set_modulate,RID, const Color& )
- BIND2(canvas_item_set_self_modulate,RID, const Color& )
-
- BIND2(canvas_item_set_draw_behind_parent,RID, bool )
-
-
- BIND6(canvas_item_add_line,RID, const Point2& , const Point2& ,const Color& ,float ,bool )
- BIND3(canvas_item_add_rect,RID, const Rect2& , const Color& )
- BIND4(canvas_item_add_circle,RID, const Point2& , float ,const Color& )
- BIND6(canvas_item_add_texture_rect,RID, const Rect2& , RID ,bool ,const Color& ,bool )
- BIND6(canvas_item_add_texture_rect_region,RID, const Rect2& , RID ,const Rect2& ,const Color& ,bool )
- BIND10(canvas_item_add_nine_patch,RID, const Rect2& , const Rect2& , RID ,const Vector2& , const Vector2& ,NinePatchAxisMode , NinePatchAxisMode,bool ,const Color& )
- BIND6(canvas_item_add_primitive,RID, const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID ,float )
- BIND5(canvas_item_add_polygon,RID, const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID )
- BIND7(canvas_item_add_triangle_array,RID, const Vector<int>& , const Vector<Point2>& , const Vector<Color>& ,const Vector<Point2>& , RID , int)
- BIND3(canvas_item_add_mesh,RID, const RID& ,RID )
- BIND3(canvas_item_add_multimesh,RID, RID ,RID )
- BIND2(canvas_item_add_set_transform,RID,const Transform2D& )
- BIND2(canvas_item_add_clip_ignore,RID, bool )
- BIND2(canvas_item_set_sort_children_by_y,RID, bool )
- BIND2(canvas_item_set_z,RID, int )
- BIND2(canvas_item_set_z_as_relative_to_parent,RID, bool )
- BIND3(canvas_item_set_copy_to_backbuffer,RID, bool ,const Rect2& )
-
- BIND1(canvas_item_clear,RID )
- BIND2(canvas_item_set_draw_index,RID,int)
-
- BIND2(canvas_item_set_material,RID, RID )
-
- BIND2(canvas_item_set_use_parent_material,RID, bool )
-
-
- BIND0R(RID,canvas_light_create)
- BIND2(canvas_light_attach_to_canvas,RID,RID )
- BIND2(canvas_light_set_enabled,RID, bool )
- BIND2(canvas_light_set_scale,RID, float )
- BIND2(canvas_light_set_transform,RID, const Transform2D& )
- BIND2(canvas_light_set_texture,RID, RID )
- BIND2(canvas_light_set_texture_offset,RID, const Vector2& )
- BIND2(canvas_light_set_color,RID, const Color& )
- BIND2(canvas_light_set_height,RID, float )
- BIND2(canvas_light_set_energy,RID, float )
- BIND3(canvas_light_set_z_range,RID, int ,int )
- BIND3(canvas_light_set_layer_range,RID, int ,int )
- BIND2(canvas_light_set_item_cull_mask,RID, int )
- BIND2(canvas_light_set_item_shadow_cull_mask,RID, int )
-
- BIND2(canvas_light_set_mode,RID, CanvasLightMode )
-
- BIND2(canvas_light_set_shadow_enabled,RID, bool )
- BIND2(canvas_light_set_shadow_buffer_size,RID, int )
- BIND2(canvas_light_set_shadow_gradient_length,RID, float )
- BIND2(canvas_light_set_shadow_filter,RID, CanvasLightShadowFilter )
- BIND2(canvas_light_set_shadow_color,RID, const Color& )
-
-
-
- BIND0R(RID,canvas_light_occluder_create)
- BIND2(canvas_light_occluder_attach_to_canvas,RID,RID )
- BIND2(canvas_light_occluder_set_enabled,RID,bool )
- BIND2(canvas_light_occluder_set_polygon,RID,RID )
- BIND2(canvas_light_occluder_set_transform,RID,const Transform2D& )
- BIND2(canvas_light_occluder_set_light_mask,RID,int )
-
-
- BIND0R(RID,canvas_occluder_polygon_create)
- BIND3(canvas_occluder_polygon_set_shape,RID,const PoolVector<Vector2>& ,bool)
- BIND2(canvas_occluder_polygon_set_shape_as_lines,RID ,const PoolVector<Vector2>&)
-
-
- BIND2(canvas_occluder_polygon_set_cull_mode,RID,CanvasOccluderPolygonCullMode)
-
+ BIND0R(RID, canvas_create)
+ BIND3(canvas_set_item_mirroring, RID, RID, const Point2 &)
+ BIND2(canvas_set_modulate, RID, const Color &)
+
+ BIND0R(RID, canvas_item_create)
+ BIND2(canvas_item_set_parent, RID, RID)
+
+ BIND2(canvas_item_set_visible, RID, bool)
+ BIND2(canvas_item_set_light_mask, RID, int)
+
+ BIND2(canvas_item_set_transform, RID, const Transform2D &)
+ BIND2(canvas_item_set_clip, RID, bool)
+ BIND2(canvas_item_set_distance_field_mode, RID, bool)
+ BIND3(canvas_item_set_custom_rect, RID, bool, const Rect2 &)
+ BIND2(canvas_item_set_modulate, RID, const Color &)
+ BIND2(canvas_item_set_self_modulate, RID, const Color &)
+
+ BIND2(canvas_item_set_draw_behind_parent, RID, bool)
+
+ BIND6(canvas_item_add_line, RID, const Point2 &, const Point2 &, const Color &, float, bool)
+ BIND3(canvas_item_add_rect, RID, const Rect2 &, const Color &)
+ BIND4(canvas_item_add_circle, RID, const Point2 &, float, const Color &)
+ BIND6(canvas_item_add_texture_rect, RID, const Rect2 &, RID, bool, const Color &, bool)
+ BIND6(canvas_item_add_texture_rect_region, RID, const Rect2 &, RID, const Rect2 &, const Color &, bool)
+ BIND10(canvas_item_add_nine_patch, RID, const Rect2 &, const Rect2 &, RID, const Vector2 &, const Vector2 &, NinePatchAxisMode, NinePatchAxisMode, bool, const Color &)
+ BIND6(canvas_item_add_primitive, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, float)
+ BIND5(canvas_item_add_polygon, RID, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID)
+ BIND7(canvas_item_add_triangle_array, RID, const Vector<int> &, const Vector<Point2> &, const Vector<Color> &, const Vector<Point2> &, RID, int)
+ BIND3(canvas_item_add_mesh, RID, const RID &, RID)
+ BIND3(canvas_item_add_multimesh, RID, RID, RID)
+ BIND2(canvas_item_add_set_transform, RID, const Transform2D &)
+ BIND2(canvas_item_add_clip_ignore, RID, bool)
+ BIND2(canvas_item_set_sort_children_by_y, RID, bool)
+ BIND2(canvas_item_set_z, RID, int)
+ BIND2(canvas_item_set_z_as_relative_to_parent, RID, bool)
+ BIND3(canvas_item_set_copy_to_backbuffer, RID, bool, const Rect2 &)
+
+ BIND1(canvas_item_clear, RID)
+ BIND2(canvas_item_set_draw_index, RID, int)
+
+ BIND2(canvas_item_set_material, RID, RID)
+
+ BIND2(canvas_item_set_use_parent_material, RID, bool)
+
+ BIND0R(RID, canvas_light_create)
+ BIND2(canvas_light_attach_to_canvas, RID, RID)
+ BIND2(canvas_light_set_enabled, RID, bool)
+ BIND2(canvas_light_set_scale, RID, float)
+ BIND2(canvas_light_set_transform, RID, const Transform2D &)
+ BIND2(canvas_light_set_texture, RID, RID)
+ BIND2(canvas_light_set_texture_offset, RID, const Vector2 &)
+ BIND2(canvas_light_set_color, RID, const Color &)
+ BIND2(canvas_light_set_height, RID, float)
+ BIND2(canvas_light_set_energy, RID, float)
+ BIND3(canvas_light_set_z_range, RID, int, int)
+ BIND3(canvas_light_set_layer_range, RID, int, int)
+ BIND2(canvas_light_set_item_cull_mask, RID, int)
+ BIND2(canvas_light_set_item_shadow_cull_mask, RID, int)
+
+ BIND2(canvas_light_set_mode, RID, CanvasLightMode)
+
+ BIND2(canvas_light_set_shadow_enabled, RID, bool)
+ BIND2(canvas_light_set_shadow_buffer_size, RID, int)
+ BIND2(canvas_light_set_shadow_gradient_length, RID, float)
+ BIND2(canvas_light_set_shadow_filter, RID, CanvasLightShadowFilter)
+ BIND2(canvas_light_set_shadow_color, RID, const Color &)
+
+ BIND0R(RID, canvas_light_occluder_create)
+ BIND2(canvas_light_occluder_attach_to_canvas, RID, RID)
+ BIND2(canvas_light_occluder_set_enabled, RID, bool)
+ BIND2(canvas_light_occluder_set_polygon, RID, RID)
+ BIND2(canvas_light_occluder_set_transform, RID, const Transform2D &)
+ BIND2(canvas_light_occluder_set_light_mask, RID, int)
+
+ BIND0R(RID, canvas_occluder_polygon_create)
+ BIND3(canvas_occluder_polygon_set_shape, RID, const PoolVector<Vector2> &, bool)
+ BIND2(canvas_occluder_polygon_set_shape_as_lines, RID, const PoolVector<Vector2> &)
+
+ BIND2(canvas_occluder_polygon_set_cull_mode, RID, CanvasOccluderPolygonCullMode)
/* CURSOR */
virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0); // radians
- virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor=0, const Rect2 &p_region=Rect2());
+ virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor = 0, const Rect2 &p_region = Rect2());
virtual void cursor_set_visible(bool p_visible, int p_cursor = 0);
- virtual void cursor_set_pos(const Point2& p_pos, int p_cursor = 0);
+ virtual void cursor_set_pos(const Point2 &p_pos, int p_cursor = 0);
/* BLACK BARS */
-
virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom);
virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom);
-
/* FREE */
- virtual void free( RID p_rid ); ///< free RIDs associated with the visual server
+ virtual void free(RID p_rid); ///< free RIDs associated with the visual server
/* EVENT QUEUING */
@@ -1129,21 +1107,18 @@ public:
/* STATUS INFORMATION */
-
virtual int get_render_info(RenderInfo p_info);
virtual RID get_test_cube();
-
/* TESTING */
- virtual void set_boot_image(const Image& p_image, const Color& p_color,bool p_scale);
- virtual void set_default_clear_color(const Color& p_color);
+ virtual void set_boot_image(const Image &p_image, const Color &p_color, bool p_scale);
+ virtual void set_default_clear_color(const Color &p_color);
virtual bool has_feature(Features p_feature) const;
- virtual bool has_os_feature(const String& p_feature) const;
-
+ virtual bool has_os_feature(const String &p_feature) const;
VisualServerRaster();
~VisualServerRaster();
@@ -1166,7 +1141,6 @@ public:
#undef BIND8
#undef BIND9
#undef BIND10
-
};
#endif
diff --git a/servers/visual/visual_server_scene.cpp b/servers/visual/visual_server_scene.cpp
index e004103508..46c7fa6791 100644
--- a/servers/visual/visual_server_scene.cpp
+++ b/servers/visual/visual_server_scene.cpp
@@ -27,84 +27,68 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "visual_server_scene.h"
-#include "visual_server_global.h"
#include "os/os.h"
+#include "visual_server_global.h"
/* CAMERA API */
-
-
-
-
RID VisualServerScene::camera_create() {
- Camera * camera = memnew( Camera );
- return camera_owner.make_rid( camera );
-
+ Camera *camera = memnew(Camera);
+ return camera_owner.make_rid(camera);
}
-void VisualServerScene::camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far) {
+void VisualServerScene::camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) {
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->type=Camera::PERSPECTIVE;
- camera->fov=p_fovy_degrees;
- camera->znear=p_z_near;
- camera->zfar=p_z_far;
-
+ camera->type = Camera::PERSPECTIVE;
+ camera->fov = p_fovy_degrees;
+ camera->znear = p_z_near;
+ camera->zfar = p_z_far;
}
-void VisualServerScene::camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far) {
+void VisualServerScene::camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->type=Camera::ORTHOGONAL;
- camera->size=p_size;
- camera->znear=p_z_near;
- camera->zfar=p_z_far;
+ camera->type = Camera::ORTHOGONAL;
+ camera->size = p_size;
+ camera->znear = p_z_near;
+ camera->zfar = p_z_far;
}
-void VisualServerScene::camera_set_transform(RID p_camera,const Transform& p_transform) {
+void VisualServerScene::camera_set_transform(RID p_camera, const Transform &p_transform) {
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->transform=p_transform.orthonormalized();
-
-
+ camera->transform = p_transform.orthonormalized();
}
-void VisualServerScene::camera_set_cull_mask(RID p_camera,uint32_t p_layers) {
-
+void VisualServerScene::camera_set_cull_mask(RID p_camera, uint32_t p_layers) {
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->visible_layers=p_layers;
-
+ camera->visible_layers = p_layers;
}
-void VisualServerScene::camera_set_environment(RID p_camera,RID p_env) {
+void VisualServerScene::camera_set_environment(RID p_camera, RID p_env) {
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->env=p_env;
-
+ camera->env = p_env;
}
+void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera, bool p_enable) {
-void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera,bool p_enable) {
-
- Camera *camera = camera_owner.get( p_camera );
+ Camera *camera = camera_owner.get(p_camera);
ERR_FAIL_COND(!camera);
- camera->vaspect=p_enable;
-
+ camera->vaspect = p_enable;
}
-
/* SCENARIO API */
-
-
-void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int) {
+void *VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int) {
//VisualServerScene *self = (VisualServerScene*)p_self;
Instance *A = p_A;
@@ -112,69 +96,64 @@ void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance
//instance indices are designed so greater always contains lesser
if (A->base_type > B->base_type) {
- SWAP(A,B); //lesser always first
+ SWAP(A, B); //lesser always first
}
- if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
-
- InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
+ if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
+ InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
InstanceLightData::PairInfo pinfo;
- pinfo.geometry=A;
+ pinfo.geometry = A;
pinfo.L = geom->lighting.push_back(B);
List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo);
if (geom->can_cast_shadows) {
- light->shadow_dirty=true;
+ light->shadow_dirty = true;
}
- geom->lighting_dirty=true;
+ geom->lighting_dirty = true;
return E; //this element should make freeing faster
- } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
-
- InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
+ } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
InstanceReflectionProbeData::PairInfo pinfo;
- pinfo.geometry=A;
+ pinfo.geometry = A;
pinfo.L = geom->reflection_probes.push_back(B);
List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo);
- geom->reflection_dirty=true;
+ geom->reflection_dirty = true;
return E; //this element should make freeing faster
- } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
-
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
+ } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
InstanceGIProbeData::PairInfo pinfo;
- pinfo.geometry=A;
+ pinfo.geometry = A;
pinfo.L = geom->gi_probes.push_back(B);
List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo);
- geom->gi_probes_dirty=true;
+ geom->gi_probes_dirty = true;
return E; //this element should make freeing faster
- } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) {
+ } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data);
- InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data);
return gi_probe->lights.insert(A);
}
-
-
#if 0
if (A->base_type==INSTANCE_PORTAL) {
@@ -228,9 +207,8 @@ void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance
#endif
return NULL;
-
}
-void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void* udata) {
+void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *udata) {
//VisualServerScene *self = (VisualServerScene*)p_self;
Instance *A = p_A;
@@ -238,59 +216,54 @@ void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance
//instance indices are designed so greater always contains lesser
if (A->base_type > B->base_type) {
- SWAP(A,B); //lesser always first
+ SWAP(A, B); //lesser always first
}
+ if (B->base_type == VS::INSTANCE_LIGHT && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
+ InstanceLightData *light = static_cast<InstanceLightData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
- if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
-
- InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
-
- List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element*>(udata);
+ List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element *>(udata);
geom->lighting.erase(E->get().L);
light->geometries.erase(E);
if (geom->can_cast_shadows) {
- light->shadow_dirty=true;
+ light->shadow_dirty = true;
}
- geom->lighting_dirty=true;
-
+ geom->lighting_dirty = true;
- } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
+ } else if (B->base_type == VS::INSTANCE_REFLECTION_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
- InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
- List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element*>(udata);
+ List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element *>(udata);
geom->reflection_probes.erase(E->get().L);
reflection_probe->geometries.erase(E);
- geom->reflection_dirty=true;
+ geom->reflection_dirty = true;
- } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
+ } else if (B->base_type == VS::INSTANCE_GI_PROBE && (1 << A->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data);
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(A->base_data);
- List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element*>(udata);
+ List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element *>(udata);
geom->gi_probes.erase(E->get().L);
gi_probe->geometries.erase(E);
- geom->gi_probes_dirty=true;
-
-
- } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) {
+ geom->gi_probes_dirty = true;
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data);
- InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data);
+ } else if (B->base_type == VS::INSTANCE_GI_PROBE && A->base_type == VS::INSTANCE_LIGHT) {
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(B->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(A->base_data);
- Set<Instance*>::Element *E = reinterpret_cast<Set<Instance*>::Element*>(udata);
+ Set<Instance *>::Element *E = reinterpret_cast<Set<Instance *>::Element *>(udata);
gi_probe->lights.erase(E);
}
@@ -349,124 +322,111 @@ void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance
RID VisualServerScene::scenario_create() {
- Scenario *scenario = memnew( Scenario );
- ERR_FAIL_COND_V(!scenario,RID());
- RID scenario_rid = scenario_owner.make_rid( scenario );
- scenario->self=scenario_rid;
-
- scenario->octree.set_pair_callback(_instance_pair,this);
- scenario->octree.set_unpair_callback(_instance_unpair,this);
- scenario->reflection_probe_shadow_atlas=VSG::scene_render->shadow_atlas_create();
- VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas,1024); //make enough shadows for close distance, don't bother with rest
- VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,0,4);
- VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,1,4);
- VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,2,4);
- VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,3,8);
- scenario->reflection_atlas=VSG::scene_render->reflection_atlas_create();
+ Scenario *scenario = memnew(Scenario);
+ ERR_FAIL_COND_V(!scenario, RID());
+ RID scenario_rid = scenario_owner.make_rid(scenario);
+ scenario->self = scenario_rid;
+
+ scenario->octree.set_pair_callback(_instance_pair, this);
+ scenario->octree.set_unpair_callback(_instance_unpair, this);
+ scenario->reflection_probe_shadow_atlas = VSG::scene_render->shadow_atlas_create();
+ VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas, 1024); //make enough shadows for close distance, don't bother with rest
+ VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 0, 4);
+ VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 1, 4);
+ VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 2, 4);
+ VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas, 3, 8);
+ scenario->reflection_atlas = VSG::scene_render->reflection_atlas_create();
return scenario_rid;
}
-void VisualServerScene::scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode) {
+void VisualServerScene::scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode) {
Scenario *scenario = scenario_owner.get(p_scenario);
ERR_FAIL_COND(!scenario);
- scenario->debug=p_debug_mode;
+ scenario->debug = p_debug_mode;
}
void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) {
Scenario *scenario = scenario_owner.get(p_scenario);
ERR_FAIL_COND(!scenario);
- scenario->environment=p_environment;
-
+ scenario->environment = p_environment;
}
void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) {
-
Scenario *scenario = scenario_owner.get(p_scenario);
ERR_FAIL_COND(!scenario);
- scenario->fallback_environment=p_environment;
-
-
+ scenario->fallback_environment = p_environment;
}
-void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv) {
+void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) {
Scenario *scenario = scenario_owner.get(p_scenario);
ERR_FAIL_COND(!scenario);
- VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas,p_size);
- VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas,p_subdiv);
-
-
+ VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas, p_size);
+ VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas, p_subdiv);
}
-
-
/* INSTANCING API */
-void VisualServerScene::_instance_queue_update(Instance *p_instance,bool p_update_aabb,bool p_update_materials) {
+void VisualServerScene::_instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials) {
if (p_update_aabb)
- p_instance->update_aabb=true;
+ p_instance->update_aabb = true;
if (p_update_materials)
- p_instance->update_materials=true;
+ p_instance->update_materials = true;
if (p_instance->update_item.in_list())
return;
_instance_update_list.add(&p_instance->update_item);
-
-
}
// from can be mesh, light, area and portal so far.
-RID VisualServerScene::instance_create(){
+RID VisualServerScene::instance_create() {
- Instance *instance = memnew( Instance );
- ERR_FAIL_COND_V(!instance,RID());
+ Instance *instance = memnew(Instance);
+ ERR_FAIL_COND_V(!instance, RID());
RID instance_rid = instance_owner.make_rid(instance);
- instance->self=instance_rid;
-
+ instance->self = instance_rid;
return instance_rid;
-
-
}
-void VisualServerScene::instance_set_base(RID p_instance, RID p_base){
+void VisualServerScene::instance_set_base(RID p_instance, RID p_base) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
Scenario *scenario = instance->scenario;
- if (instance->base_type!=VS::INSTANCE_NONE) {
+ if (instance->base_type != VS::INSTANCE_NONE) {
//free anything related to that base
- VSG::storage->instance_remove_dependency(instance->base,instance);
+ VSG::storage->instance_remove_dependency(instance->base, instance);
if (scenario && instance->octree_id) {
scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
- instance->octree_id=0;
+ instance->octree_id = 0;
}
- switch(instance->base_type) {
+ switch (instance->base_type) {
case VS::INSTANCE_LIGHT: {
- InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
if (instance->scenario && light->D) {
- instance->scenario->directional_lights.erase( light->D );
- light->D=NULL;
+ instance->scenario->directional_lights.erase(light->D);
+ light->D = NULL;
}
VSG::scene_render->free(light->instance);
} break;
case VS::INSTANCE_REFLECTION_PROBE: {
- InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data);
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
VSG::scene_render->free(reflection_probe->instance);
if (reflection_probe->update_list.in_list()) {
reflection_probe_render_list.remove(&reflection_probe->update_list);
@@ -474,9 +434,9 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){
} break;
case VS::INSTANCE_GI_PROBE: {
- InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
- while(gi_probe->dynamic.updating_stage==GI_UPDATE_STAGE_LIGHTING) {
+ while (gi_probe->dynamic.updating_stage == GI_UPDATE_STAGE_LIGHTING) {
//wait until bake is done if it's baking
OS::get_singleton()->delay_usec(1);
}
@@ -490,19 +450,18 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){
VSG::scene_render->free(gi_probe->probe_instance);
} break;
-
}
if (instance->base_data) {
- memdelete( instance->base_data );
- instance->base_data=NULL;
+ memdelete(instance->base_data);
+ instance->base_data = NULL;
}
instance->blend_values.clear();
- for(int i=0;i<instance->materials.size();i++) {
+ for (int i = 0; i < instance->materials.size(); i++) {
if (instance->materials[i].is_valid()) {
- VSG::storage->material_remove_instance_owner(instance->materials[i],instance);
+ VSG::storage->material_remove_instance_owner(instance->materials[i], instance);
}
}
instance->materials.clear();
@@ -625,70 +584,65 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){
instance->gi_probe_sampler_info=NULL;
}
#endif
-
}
-
- instance->base_type=VS::INSTANCE_NONE;
- instance->base=RID();
-
+ instance->base_type = VS::INSTANCE_NONE;
+ instance->base = RID();
if (p_base.is_valid()) {
- instance->base_type=VSG::storage->get_base_type(p_base);
- ERR_FAIL_COND(instance->base_type==VS::INSTANCE_NONE);
+ instance->base_type = VSG::storage->get_base_type(p_base);
+ ERR_FAIL_COND(instance->base_type == VS::INSTANCE_NONE);
- switch(instance->base_type) {
+ switch (instance->base_type) {
case VS::INSTANCE_LIGHT: {
- InstanceLightData *light = memnew( InstanceLightData );
+ InstanceLightData *light = memnew(InstanceLightData);
- if (scenario && VSG::storage->light_get_type(p_base)==VS::LIGHT_DIRECTIONAL) {
+ if (scenario && VSG::storage->light_get_type(p_base) == VS::LIGHT_DIRECTIONAL) {
light->D = scenario->directional_lights.push_back(instance);
}
light->instance = VSG::scene_render->light_instance_create(p_base);
- instance->base_data=light;
+ instance->base_data = light;
} break;
case VS::INSTANCE_MESH:
case VS::INSTANCE_MULTIMESH:
case VS::INSTANCE_IMMEDIATE: {
- InstanceGeometryData *geom = memnew( InstanceGeometryData );
- instance->base_data=geom;
+ InstanceGeometryData *geom = memnew(InstanceGeometryData);
+ instance->base_data = geom;
} break;
case VS::INSTANCE_REFLECTION_PROBE: {
- InstanceReflectionProbeData *reflection_probe = memnew( InstanceReflectionProbeData );
- reflection_probe->owner=instance;
- instance->base_data=reflection_probe;
+ InstanceReflectionProbeData *reflection_probe = memnew(InstanceReflectionProbeData);
+ reflection_probe->owner = instance;
+ instance->base_data = reflection_probe;
- reflection_probe->instance=VSG::scene_render->reflection_probe_instance_create(p_base);
+ reflection_probe->instance = VSG::scene_render->reflection_probe_instance_create(p_base);
} break;
case VS::INSTANCE_GI_PROBE: {
- InstanceGIProbeData *gi_probe = memnew( InstanceGIProbeData );
- instance->base_data=gi_probe;
- gi_probe->owner=instance;
+ InstanceGIProbeData *gi_probe = memnew(InstanceGIProbeData);
+ instance->base_data = gi_probe;
+ gi_probe->owner = instance;
if (scenario && !gi_probe->update_element.in_list()) {
gi_probe_update_list.add(&gi_probe->update_element);
}
- gi_probe->probe_instance=VSG::scene_render->gi_probe_instance_create();
+ gi_probe->probe_instance = VSG::scene_render->gi_probe_instance_create();
} break;
-
}
- VSG::storage->instance_add_dependency(p_base,instance);
+ VSG::storage->instance_add_dependency(p_base, instance);
- instance->base=p_base;
+ instance->base = p_base;
if (scenario)
- _instance_queue_update(instance,true,true);
-
+ _instance_queue_update(instance, true, true);
#if 0
if (rasterizer->is_mesh(p_base)) {
@@ -747,238 +701,219 @@ void VisualServerScene::instance_set_base(RID p_instance, RID p_base){
instance_dependency_map[ p_base ].insert( instance->self );
#endif
-
-
}
}
-void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario){
+void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
if (instance->scenario) {
- instance->scenario->instances.remove( &instance->scenario_item );
+ instance->scenario->instances.remove(&instance->scenario_item);
if (instance->octree_id) {
instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away
- instance->octree_id=0;
+ instance->octree_id = 0;
}
-
- switch(instance->base_type) {
+ switch (instance->base_type) {
case VS::INSTANCE_LIGHT: {
-
- InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
if (light->D) {
- instance->scenario->directional_lights.erase( light->D );
- light->D=NULL;
+ instance->scenario->directional_lights.erase(light->D);
+ light->D = NULL;
}
} break;
case VS::INSTANCE_REFLECTION_PROBE: {
- InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data);
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(instance->base_data);
VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance);
} break;
case VS::INSTANCE_GI_PROBE: {
- InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
if (gi_probe->update_element.in_list()) {
gi_probe_update_list.remove(&gi_probe->update_element);
}
} break;
-
}
- instance->scenario=NULL;
+ instance->scenario = NULL;
}
-
if (p_scenario.is_valid()) {
- Scenario *scenario = scenario_owner.get( p_scenario );
+ Scenario *scenario = scenario_owner.get(p_scenario);
ERR_FAIL_COND(!scenario);
- instance->scenario=scenario;
-
- scenario->instances.add( &instance->scenario_item );
+ instance->scenario = scenario;
+ scenario->instances.add(&instance->scenario_item);
- switch(instance->base_type) {
+ switch (instance->base_type) {
case VS::INSTANCE_LIGHT: {
+ InstanceLightData *light = static_cast<InstanceLightData *>(instance->base_data);
- InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data);
-
- if (VSG::storage->light_get_type(instance->base)==VS::LIGHT_DIRECTIONAL) {
+ if (VSG::storage->light_get_type(instance->base) == VS::LIGHT_DIRECTIONAL) {
light->D = scenario->directional_lights.push_back(instance);
}
} break;
case VS::INSTANCE_GI_PROBE: {
- InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(instance->base_data);
if (!gi_probe->update_element.in_list()) {
gi_probe_update_list.add(&gi_probe->update_element);
}
} break;
}
- _instance_queue_update(instance,true,true);
+ _instance_queue_update(instance, true, true);
}
}
-void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask){
-
+void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
- instance->layer_mask=p_mask;
+ instance->layer_mask = p_mask;
}
-void VisualServerScene::instance_set_transform(RID p_instance, const Transform& p_transform){
+void VisualServerScene::instance_set_transform(RID p_instance, const Transform &p_transform) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
- if (instance->transform==p_transform)
+ if (instance->transform == p_transform)
return; //must be checked to avoid worst evil
- instance->transform=p_transform;
- _instance_queue_update(instance,true);
+ instance->transform = p_transform;
+ _instance_queue_update(instance, true);
}
-void VisualServerScene::instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID){
+void VisualServerScene::instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
-
- instance->object_ID=p_ID;
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
+ instance->object_ID = p_ID;
}
-void VisualServerScene::instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight){
+void VisualServerScene::instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
if (instance->update_item.in_list()) {
_update_dirty_instance(instance);
}
- ERR_FAIL_INDEX(p_shape,instance->blend_values.size());
- instance->blend_values[p_shape]=p_weight;
+ ERR_FAIL_INDEX(p_shape, instance->blend_values.size());
+ instance->blend_values[p_shape] = p_weight;
}
-void VisualServerScene::instance_set_surface_material(RID p_instance,int p_surface, RID p_material){
+void VisualServerScene::instance_set_surface_material(RID p_instance, int p_surface, RID p_material) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
if (instance->update_item.in_list()) {
_update_dirty_instance(instance);
}
- ERR_FAIL_INDEX(p_surface,instance->materials.size());
+ ERR_FAIL_INDEX(p_surface, instance->materials.size());
if (instance->materials[p_surface].is_valid()) {
- VSG::storage->material_remove_instance_owner(instance->materials[p_surface],instance);
+ VSG::storage->material_remove_instance_owner(instance->materials[p_surface], instance);
}
- instance->materials[p_surface]=p_material;
+ instance->materials[p_surface] = p_material;
instance->base_material_changed();
if (instance->materials[p_surface].is_valid()) {
- VSG::storage->material_add_instance_owner(instance->materials[p_surface],instance);
+ VSG::storage->material_add_instance_owner(instance->materials[p_surface], instance);
}
-
-
}
-void VisualServerScene::instance_set_visible(RID p_instance,bool p_visible) {
+void VisualServerScene::instance_set_visible(RID p_instance, bool p_visible) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
- if (instance->visible==p_visible)
+ if (instance->visible == p_visible)
return;
- instance->visible=p_visible;
-
+ instance->visible = p_visible;
- switch(instance->base_type) {
+ switch (instance->base_type) {
case VS::INSTANCE_LIGHT: {
- if (VSG::storage->light_get_type(instance->base)!=VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
- instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_LIGHT,p_visible?VS::INSTANCE_GEOMETRY_MASK:0);
+ if (VSG::storage->light_get_type(instance->base) != VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) {
+ instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_LIGHT, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
}
} break;
case VS::INSTANCE_REFLECTION_PROBE: {
if (instance->octree_id && instance->scenario) {
- instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_REFLECTION_PROBE,p_visible?VS::INSTANCE_GEOMETRY_MASK:0);
+ instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_REFLECTION_PROBE, p_visible ? VS::INSTANCE_GEOMETRY_MASK : 0);
}
} break;
case VS::INSTANCE_GI_PROBE: {
if (instance->octree_id && instance->scenario) {
- instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_GI_PROBE,p_visible?(VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT)):0);
+ instance->scenario->octree.set_pairable(instance->octree_id, p_visible, 1 << VS::INSTANCE_GI_PROBE, p_visible ? (VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT)) : 0);
}
} break;
-
}
-
}
-void VisualServerScene::instance_attach_skeleton(RID p_instance,RID p_skeleton){
+void VisualServerScene::instance_attach_skeleton(RID p_instance, RID p_skeleton) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
- if (instance->skeleton==p_skeleton)
+ if (instance->skeleton == p_skeleton)
return;
if (instance->skeleton.is_valid()) {
- VSG::storage->instance_remove_skeleton(p_skeleton,instance);
+ VSG::storage->instance_remove_skeleton(p_skeleton, instance);
}
- instance->skeleton=p_skeleton;
+ instance->skeleton = p_skeleton;
if (instance->skeleton.is_valid()) {
- VSG::storage->instance_add_skeleton(p_skeleton,instance);
+ VSG::storage->instance_add_skeleton(p_skeleton, instance);
}
- _instance_queue_update(instance,true);
+ _instance_queue_update(instance, true);
}
-void VisualServerScene::instance_set_exterior( RID p_instance, bool p_enabled ){
-
+void VisualServerScene::instance_set_exterior(RID p_instance, bool p_enabled) {
}
-void VisualServerScene::instance_set_room( RID p_instance, RID p_room ){
-
+void VisualServerScene::instance_set_room(RID p_instance, RID p_room) {
}
-void VisualServerScene::instance_set_extra_visibility_margin( RID p_instance, real_t p_margin ){
-
+void VisualServerScene::instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) {
}
-Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3& p_aabb, RID p_scenario) const {
-
+Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario) const {
Vector<ObjectID> instances;
- Scenario *scenario=scenario_owner.get(p_scenario);
- ERR_FAIL_COND_V(!scenario,instances);
+ Scenario *scenario = scenario_owner.get(p_scenario);
+ ERR_FAIL_COND_V(!scenario, instances);
- const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling
+ const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
- int culled=0;
+ int culled = 0;
Instance *cull[1024];
- culled=scenario->octree.cull_AABB(p_aabb,cull,1024);
+ culled = scenario->octree.cull_AABB(p_aabb, cull, 1024);
- for (int i=0;i<culled;i++) {
+ for (int i = 0; i < culled; i++) {
- Instance *instance=cull[i];
+ Instance *instance = cull[i];
ERR_CONTINUE(!instance);
- if (instance->object_ID==0)
+ if (instance->object_ID == 0)
continue;
instances.push_back(instance->object_ID);
@@ -986,79 +921,74 @@ Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3& p_aabb, RID
return instances;
}
-Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario) const{
+Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario) const {
Vector<ObjectID> instances;
- Scenario *scenario=scenario_owner.get(p_scenario);
- ERR_FAIL_COND_V(!scenario,instances);
- const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling
+ Scenario *scenario = scenario_owner.get(p_scenario);
+ ERR_FAIL_COND_V(!scenario, instances);
+ const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
- int culled=0;
+ int culled = 0;
Instance *cull[1024];
- culled=scenario->octree.cull_segment(p_from,p_to*10000,cull,1024);
-
+ culled = scenario->octree.cull_segment(p_from, p_to * 10000, cull, 1024);
- for (int i=0;i<culled;i++) {
- Instance *instance=cull[i];
+ for (int i = 0; i < culled; i++) {
+ Instance *instance = cull[i];
ERR_CONTINUE(!instance);
- if (instance->object_ID==0)
+ if (instance->object_ID == 0)
continue;
instances.push_back(instance->object_ID);
}
return instances;
-
}
-Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario) const{
+Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario) const {
Vector<ObjectID> instances;
- Scenario *scenario=scenario_owner.get(p_scenario);
- ERR_FAIL_COND_V(!scenario,instances);
- const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling
+ Scenario *scenario = scenario_owner.get(p_scenario);
+ ERR_FAIL_COND_V(!scenario, instances);
+ const_cast<VisualServerScene *>(this)->update_dirty_instances(); // check dirty instances before culling
- int culled=0;
+ int culled = 0;
Instance *cull[1024];
+ culled = scenario->octree.cull_convex(p_convex, cull, 1024);
- culled=scenario->octree.cull_convex(p_convex,cull,1024);
+ for (int i = 0; i < culled; i++) {
- for (int i=0;i<culled;i++) {
-
- Instance *instance=cull[i];
+ Instance *instance = cull[i];
ERR_CONTINUE(!instance);
- if (instance->object_ID==0)
+ if (instance->object_ID == 0)
continue;
instances.push_back(instance->object_ID);
}
return instances;
-
}
-void VisualServerScene::instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled){
+void VisualServerScene::instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
- switch(p_flags) {
+ switch (p_flags) {
case VS::INSTANCE_FLAG_BILLBOARD: {
- instance->billboard=p_enabled;
+ instance->billboard = p_enabled;
} break;
case VS::INSTANCE_FLAG_BILLBOARD_FIX_Y: {
- instance->billboard_y=p_enabled;
+ instance->billboard_y = p_enabled;
} break;
case VS::INSTANCE_FLAG_CAST_SHADOW: {
if (p_enabled == true) {
instance->cast_shadows = VS::SHADOW_CASTING_SETTING_ON;
- }
- else {
+ } else {
instance->cast_shadows = VS::SHADOW_CASTING_SETTING_OFF;
}
@@ -1067,69 +997,59 @@ void VisualServerScene::instance_geometry_set_flag(RID p_instance,VS::InstanceFl
} break;
case VS::INSTANCE_FLAG_DEPH_SCALE: {
- instance->depth_scale=p_enabled;
+ instance->depth_scale = p_enabled;
} break;
case VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS: {
- instance->visible_in_all_rooms=p_enabled;
+ instance->visible_in_all_rooms = p_enabled;
} break;
-
}
}
void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) {
-
}
-void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material){
+void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material) {
- Instance *instance = instance_owner.get( p_instance );
- ERR_FAIL_COND( !instance );
+ Instance *instance = instance_owner.get(p_instance);
+ ERR_FAIL_COND(!instance);
if (instance->material_override.is_valid()) {
- VSG::storage->material_remove_instance_owner(instance->material_override,instance);
+ VSG::storage->material_remove_instance_owner(instance->material_override, instance);
}
- instance->material_override=p_material;
+ instance->material_override = p_material;
instance->base_material_changed();
if (instance->material_override.is_valid()) {
- VSG::storage->material_add_instance_owner(instance->material_override,instance);
+ VSG::storage->material_add_instance_owner(instance->material_override, instance);
}
-
}
-
-void VisualServerScene::instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin){
-
+void VisualServerScene::instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) {
}
-void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance){
-
+void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) {
}
-
void VisualServerScene::_update_instance(Instance *p_instance) {
p_instance->version++;
if (p_instance->base_type == VS::INSTANCE_LIGHT) {
- InstanceLightData *light = static_cast<InstanceLightData*>(p_instance->base_data);
-
- VSG::scene_render->light_instance_set_transform( light->instance, p_instance->transform );
- light->shadow_dirty=true;
+ InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
+ VSG::scene_render->light_instance_set_transform(light->instance, p_instance->transform);
+ light->shadow_dirty = true;
}
if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
- InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data);
-
- VSG::scene_render->reflection_probe_instance_set_transform( reflection_probe->instance, p_instance->transform );
- reflection_probe->reflection_dirty=true;
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
+ VSG::scene_render->reflection_probe_instance_set_transform(reflection_probe->instance, p_instance->transform);
+ reflection_probe->reflection_dirty = true;
}
-
if (p_instance->aabb.has_no_surface())
return;
@@ -1140,18 +1060,17 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
}
#endif
- if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
+ if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
- InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
//make sure lights are updated if it casts shadow
if (geom->can_cast_shadows) {
- for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) {
- InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data);
- light->shadow_dirty=true;
+ for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
+ InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
+ light->shadow_dirty = true;
}
}
-
}
#if 0
else if (p_instance->base_type == INSTANCE_ROOM) {
@@ -1166,7 +1085,6 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
p_instance->gi_probe_info->affine_inverse=(p_instance->data.transform*scale).affine_inverse();
}
-
#endif
p_instance->mirror = p_instance->transform.basis.determinant() < 0.0;
@@ -1202,37 +1120,34 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
} else {
#endif
- new_aabb = p_instance->transform.xform(p_instance->aabb);
+ new_aabb = p_instance->transform.xform(p_instance->aabb);
#if 0
}
#endif
-
- p_instance->transformed_aabb=new_aabb;
+ p_instance->transformed_aabb = new_aabb;
if (!p_instance->scenario) {
return;
}
+ if (p_instance->octree_id == 0) {
+ uint32_t base_type = 1 << p_instance->base_type;
+ uint32_t pairable_mask = 0;
+ bool pairable = false;
- if (p_instance->octree_id==0) {
-
- uint32_t base_type = 1<<p_instance->base_type;
- uint32_t pairable_mask=0;
- bool pairable=false;
+ if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) {
- if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type==VS::INSTANCE_REFLECTION_PROBE) {
-
- pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK:0;
- pairable=true;
+ pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK : 0;
+ pairable = true;
}
if (p_instance->base_type == VS::INSTANCE_GI_PROBE) {
//lights and geometries
- pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT):0;
- pairable=true;
+ pairable_mask = p_instance->visible ? VS::INSTANCE_GEOMETRY_MASK | (1 << VS::INSTANCE_LIGHT) : 0;
+ pairable = true;
}
#if 0
@@ -1263,7 +1178,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
#endif
// not inside octree
- p_instance->octree_id = p_instance->scenario->octree.create(p_instance,new_aabb,0,pairable,base_type,pairable_mask);
+ p_instance->octree_id = p_instance->scenario->octree.create(p_instance, new_aabb, 0, pairable, base_type, pairable_mask);
} else {
@@ -1272,7 +1187,7 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
return;
*/
- p_instance->scenario->octree.move(p_instance->octree_id,new_aabb);
+ p_instance->scenario->octree.move(p_instance->octree_id, new_aabb);
}
#if 0
if (p_instance->base_type==INSTANCE_PORTAL) {
@@ -1291,23 +1206,22 @@ void VisualServerScene::_update_instance(Instance *p_instance) {
_instance_validate_autorooms(E->get());
}
#endif
-
}
void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
Rect3 new_aabb;
- ERR_FAIL_COND(p_instance->base_type!=VS::INSTANCE_NONE && !p_instance->base.is_valid());
+ ERR_FAIL_COND(p_instance->base_type != VS::INSTANCE_NONE && !p_instance->base.is_valid());
- switch(p_instance->base_type) {
+ switch (p_instance->base_type) {
case VisualServer::INSTANCE_NONE: {
// do nothing
} break;
case VisualServer::INSTANCE_MESH: {
- new_aabb = VSG::storage->mesh_get_aabb(p_instance->base,p_instance->skeleton);
+ new_aabb = VSG::storage->mesh_get_aabb(p_instance->base, p_instance->skeleton);
} break;
@@ -1320,7 +1234,6 @@ void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
new_aabb = VSG::storage->immediate_get_aabb(p_instance->base);
-
} break;
#if 0
@@ -1396,164 +1309,147 @@ void VisualServerScene::_update_instance_aabb(Instance *p_instance) {
if (p_instance->extra_margin)
new_aabb.grow_by(p_instance->extra_margin);
- p_instance->aabb=new_aabb;
-
+ p_instance->aabb = new_aabb;
}
+void VisualServerScene::_light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario) {
+ InstanceLightData *light = static_cast<InstanceLightData *>(p_instance->base_data);
-
-
-void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario* p_scenario) {
-
-
- InstanceLightData * light = static_cast<InstanceLightData*>(p_instance->base_data);
-
- switch(VSG::storage->light_get_type(p_instance->base)) {
+ switch (VSG::storage->light_get_type(p_instance->base)) {
case VS::LIGHT_DIRECTIONAL: {
- float max_distance =p_cam_projection.get_z_far();
- float shadow_max = VSG::storage->light_get_param(p_instance->base,VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
- if (shadow_max>0) {
- max_distance=MIN(shadow_max,max_distance);
+ float max_distance = p_cam_projection.get_z_far();
+ float shadow_max = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE);
+ if (shadow_max > 0) {
+ max_distance = MIN(shadow_max, max_distance);
}
- max_distance=MAX(max_distance,p_cam_projection.get_z_near()+0.001);
+ max_distance = MAX(max_distance, p_cam_projection.get_z_near() + 0.001);
- float range = max_distance-p_cam_projection.get_z_near();
+ float range = max_distance - p_cam_projection.get_z_near();
- int splits=0;
- switch(VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
- case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits=1; break;
- case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits=2; break;
- case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits=4; break;
+ int splits = 0;
+ switch (VSG::storage->light_directional_get_shadow_mode(p_instance->base)) {
+ case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits = 1; break;
+ case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits = 2; break;
+ case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits = 4; break;
}
float distances[5];
- distances[0]=p_cam_projection.get_z_near();
- for(int i=0;i<splits;i++) {
- distances[i+1]=p_cam_projection.get_z_near()+VSG::storage->light_get_param(p_instance->base,VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET+i))*range;
+ distances[0] = p_cam_projection.get_z_near();
+ for (int i = 0; i < splits; i++) {
+ distances[i + 1] = p_cam_projection.get_z_near() + VSG::storage->light_get_param(p_instance->base, VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET + i)) * range;
};
- distances[splits]=max_distance;
+ distances[splits] = max_distance;
- float texture_size=VSG::scene_render->get_directional_light_shadow_size(light->instance);
+ float texture_size = VSG::scene_render->get_directional_light_shadow_size(light->instance);
bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base);
- for (int i=0;i<splits;i++) {
+ for (int i = 0; i < splits; i++) {
// setup a camera matrix for that range!
CameraMatrix camera_matrix;
float aspect = p_cam_projection.get_aspect();
-
if (p_cam_orthogonal) {
- float w,h;
- p_cam_projection.get_viewport_size(w,h);
- camera_matrix.set_orthogonal(w,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false);
+ float w, h;
+ p_cam_projection.get_viewport_size(w, h);
+ camera_matrix.set_orthogonal(w, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
} else {
float fov = p_cam_projection.get_fov();
- camera_matrix.set_perspective(fov,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false);
+ camera_matrix.set_perspective(fov, aspect, distances[(i == 0 || !overlap) ? i : i - 1], distances[i + 1], false);
}
//obtain the frustum endpoints
Vector3 endpoints[8]; // frustum plane endpoints
- bool res = camera_matrix.get_endpoints(p_cam_transform,endpoints);
+ bool res = camera_matrix.get_endpoints(p_cam_transform, endpoints);
ERR_CONTINUE(!res);
// obtain the light frustm ranges (given endpoints)
- Vector3 x_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_X ).normalized();
- Vector3 y_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Y ).normalized();
- Vector3 z_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Z ).normalized();
+ Vector3 x_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_X).normalized();
+ Vector3 y_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_Y).normalized();
+ Vector3 z_vec = p_instance->transform.basis.get_axis(Vector3::AXIS_Z).normalized();
//z_vec points agsint the camera, like in default opengl
- float x_min,x_max;
- float y_min,y_max;
- float z_min,z_max;
-
- float x_min_cam,x_max_cam;
- float y_min_cam,y_max_cam;
- float z_min_cam,z_max_cam;
+ float x_min, x_max;
+ float y_min, y_max;
+ float z_min, z_max;
+ float x_min_cam, x_max_cam;
+ float y_min_cam, y_max_cam;
+ float z_min_cam, z_max_cam;
//used for culling
- for(int j=0;j<8;j++) {
-
- float d_x=x_vec.dot(endpoints[j]);
- float d_y=y_vec.dot(endpoints[j]);
- float d_z=z_vec.dot(endpoints[j]);
-
- if (j==0 || d_x<x_min)
- x_min=d_x;
- if (j==0 || d_x>x_max)
- x_max=d_x;
-
- if (j==0 || d_y<y_min)
- y_min=d_y;
- if (j==0 || d_y>y_max)
- y_max=d_y;
-
- if (j==0 || d_z<z_min)
- z_min=d_z;
- if (j==0 || d_z>z_max)
- z_max=d_z;
-
-
+ for (int j = 0; j < 8; j++) {
+
+ float d_x = x_vec.dot(endpoints[j]);
+ float d_y = y_vec.dot(endpoints[j]);
+ float d_z = z_vec.dot(endpoints[j]);
+
+ if (j == 0 || d_x < x_min)
+ x_min = d_x;
+ if (j == 0 || d_x > x_max)
+ x_max = d_x;
+
+ if (j == 0 || d_y < y_min)
+ y_min = d_y;
+ if (j == 0 || d_y > y_max)
+ y_max = d_y;
+
+ if (j == 0 || d_z < z_min)
+ z_min = d_z;
+ if (j == 0 || d_z > z_max)
+ z_max = d_z;
}
-
-
-
-
{
//camera viewport stuff
//this trick here is what stabilizes the shadow (make potential jaggies to not move)
//at the cost of some wasted resolution. Still the quality increase is very well worth it
-
Vector3 center;
- for(int j=0;j<8;j++) {
+ for (int j = 0; j < 8; j++) {
- center+=endpoints[j];
+ center += endpoints[j];
}
- center/=8.0;
+ center /= 8.0;
//center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5;
- float radius=0;
+ float radius = 0;
- for(int j=0;j<8;j++) {
+ for (int j = 0; j < 8; j++) {
float d = center.distance_to(endpoints[j]);
- if (d>radius)
- radius=d;
+ if (d > radius)
+ radius = d;
}
+ radius *= texture_size / (texture_size - 2.0); //add a texel by each side, so stepified texture will always fit
- radius *= texture_size/(texture_size-2.0); //add a texel by each side, so stepified texture will always fit
-
- x_max_cam=x_vec.dot(center)+radius;
- x_min_cam=x_vec.dot(center)-radius;
- y_max_cam=y_vec.dot(center)+radius;
- y_min_cam=y_vec.dot(center)-radius;
- z_max_cam=z_vec.dot(center)+radius;
- z_min_cam=z_vec.dot(center)-radius;
-
- float unit = radius*2.0/texture_size;
+ x_max_cam = x_vec.dot(center) + radius;
+ x_min_cam = x_vec.dot(center) - radius;
+ y_max_cam = y_vec.dot(center) + radius;
+ y_min_cam = y_vec.dot(center) - radius;
+ z_max_cam = z_vec.dot(center) + radius;
+ z_min_cam = z_vec.dot(center) - radius;
- x_max_cam=Math::stepify(x_max_cam,unit);
- x_min_cam=Math::stepify(x_min_cam,unit);
- y_max_cam=Math::stepify(y_max_cam,unit);
- y_min_cam=Math::stepify(y_min_cam,unit);
+ float unit = radius * 2.0 / texture_size;
+ x_max_cam = Math::stepify(x_max_cam, unit);
+ x_min_cam = Math::stepify(x_min_cam, unit);
+ y_max_cam = Math::stepify(y_max_cam, unit);
+ y_min_cam = Math::stepify(y_min_cam, unit);
}
//now that we now all ranges, we can proceed to make the light frustum planes, for culling octree
@@ -1562,57 +1458,50 @@ void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const
light_frustum_planes.resize(6);
//right/left
- light_frustum_planes[0]=Plane( x_vec, x_max );
- light_frustum_planes[1]=Plane( -x_vec, -x_min );
+ light_frustum_planes[0] = Plane(x_vec, x_max);
+ light_frustum_planes[1] = Plane(-x_vec, -x_min);
//top/bottom
- light_frustum_planes[2]=Plane( y_vec, y_max );
- light_frustum_planes[3]=Plane( -y_vec, -y_min );
+ light_frustum_planes[2] = Plane(y_vec, y_max);
+ light_frustum_planes[3] = Plane(-y_vec, -y_min);
//near/far
- light_frustum_planes[4]=Plane( z_vec, z_max+1e6 );
- light_frustum_planes[5]=Plane( -z_vec, -z_min ); // z_min is ok, since casters further than far-light plane are not needed
+ light_frustum_planes[4] = Plane(z_vec, z_max + 1e6);
+ light_frustum_planes[5] = Plane(-z_vec, -z_min); // z_min is ok, since casters further than far-light plane are not needed
- int cull_count = p_scenario->octree.cull_convex(light_frustum_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK);
+ int cull_count = p_scenario->octree.cull_convex(light_frustum_planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
// a pre pass will need to be needed to determine the actual z-near to be used
+ for (int j = 0; j < cull_count; j++) {
- for (int j=0;j<cull_count;j++) {
-
- float min,max;
+ float min, max;
Instance *instance = instance_shadow_cull_result[j];
- if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) {
+ if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
cull_count--;
- SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]);
+ SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
j--;
continue;
-
}
-
- instance->transformed_aabb.project_range_in_plane(Plane(z_vec,0),min,max);
- if (max>z_max)
- z_max=max;
+ instance->transformed_aabb.project_range_in_plane(Plane(z_vec, 0), min, max);
+ if (max > z_max)
+ z_max = max;
}
{
CameraMatrix ortho_camera;
- real_t half_x = (x_max_cam-x_min_cam) * 0.5;
- real_t half_y = (y_max_cam-y_min_cam) * 0.5;
-
+ real_t half_x = (x_max_cam - x_min_cam) * 0.5;
+ real_t half_y = (y_max_cam - y_min_cam) * 0.5;
- ortho_camera.set_orthogonal( -half_x, half_x,-half_y,half_y, 0, (z_max-z_min_cam) );
+ ortho_camera.set_orthogonal(-half_x, half_x, -half_y, half_y, 0, (z_max - z_min_cam));
Transform ortho_transform;
- ortho_transform.basis=p_instance->transform.basis;
- ortho_transform.origin=x_vec*(x_min_cam+half_x)+y_vec*(y_min_cam+half_y)+z_vec*z_max;
+ ortho_transform.basis = p_instance->transform.basis;
+ ortho_transform.origin = x_vec * (x_min_cam + half_x) + y_vec * (y_min_cam + half_y) + z_vec * z_max;
- VSG::scene_render->light_instance_set_shadow_transform(light->instance,ortho_camera,ortho_transform,0,distances[i+1],i);
+ VSG::scene_render->light_instance_set_shadow_transform(light->instance, ortho_camera, ortho_transform, 0, distances[i + 1], i);
}
-
-
- VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count);
-
+ VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
}
} break;
@@ -1620,205 +1509,185 @@ void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const
VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base);
- switch(shadow_mode) {
+ switch (shadow_mode) {
case VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID: {
- for(int i=0;i<2;i++) {
+ for (int i = 0; i < 2; i++) {
//using this one ensures that raster deferred will have it
- float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE);
+ float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
- float z =i==0?-1:1;
+ float z = i == 0 ? -1 : 1;
Vector<Plane> planes;
planes.resize(5);
- planes[0]=p_instance->transform.xform(Plane(Vector3(0,0,z),radius));
- planes[1]=p_instance->transform.xform(Plane(Vector3(1,0,z).normalized(),radius));
- planes[2]=p_instance->transform.xform(Plane(Vector3(-1,0,z).normalized(),radius));
- planes[3]=p_instance->transform.xform(Plane(Vector3(0,1,z).normalized(),radius));
- planes[4]=p_instance->transform.xform(Plane(Vector3(0,-1,z).normalized(),radius));
-
+ planes[0] = p_instance->transform.xform(Plane(Vector3(0, 0, z), radius));
+ planes[1] = p_instance->transform.xform(Plane(Vector3(1, 0, z).normalized(), radius));
+ planes[2] = p_instance->transform.xform(Plane(Vector3(-1, 0, z).normalized(), radius));
+ planes[3] = p_instance->transform.xform(Plane(Vector3(0, 1, z).normalized(), radius));
+ planes[4] = p_instance->transform.xform(Plane(Vector3(0, -1, z).normalized(), radius));
- int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK);
+ int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
- for (int j=0;j<cull_count;j++) {
+ for (int j = 0; j < cull_count; j++) {
Instance *instance = instance_shadow_cull_result[j];
- if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) {
+ if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
cull_count--;
- SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]);
+ SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
j--;
-
}
}
- VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,i);
- VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count);
+ VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, i);
+ VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
}
} break;
case VS::LIGHT_OMNI_SHADOW_CUBE: {
- float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE);
+ float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
CameraMatrix cm;
- cm.set_perspective(90,1,0.01,radius);
+ cm.set_perspective(90, 1, 0.01, radius);
- for(int i=0;i<6;i++) {
+ for (int i = 0; i < 6; i++) {
//using this one ensures that raster deferred will have it
-
-
- static const Vector3 view_normals[6]={
+ static const Vector3 view_normals[6] = {
Vector3(-1, 0, 0),
Vector3(+1, 0, 0),
- Vector3( 0,-1, 0),
- Vector3( 0,+1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0,+1)
+ Vector3(0, -1, 0),
+ Vector3(0, +1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, +1)
};
- static const Vector3 view_up[6]={
- Vector3( 0,-1, 0),
- Vector3( 0,-1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0,+1),
- Vector3( 0,-1, 0),
- Vector3( 0,-1, 0)
+ static const Vector3 view_up[6] = {
+ Vector3(0, -1, 0),
+ Vector3(0, -1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, +1),
+ Vector3(0, -1, 0),
+ Vector3(0, -1, 0)
};
- Transform xform = p_instance->transform * Transform().looking_at(view_normals[i],view_up[i]);
-
+ Transform xform = p_instance->transform * Transform().looking_at(view_normals[i], view_up[i]);
Vector<Plane> planes = cm.get_projection_planes(xform);
- int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK);
+ int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
- for (int j=0;j<cull_count;j++) {
+ for (int j = 0; j < cull_count; j++) {
Instance *instance = instance_shadow_cull_result[j];
- if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) {
+ if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
cull_count--;
- SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]);
+ SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
j--;
-
}
}
-
- VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,xform,radius,0,i);
- VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count);
+ VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, xform, radius, 0, i);
+ VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, i, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
}
//restore the regular DP matrix
- VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,0);
+ VSG::scene_render->light_instance_set_shadow_transform(light->instance, CameraMatrix(), p_instance->transform, radius, 0, 0);
} break;
}
-
} break;
case VS::LIGHT_SPOT: {
-
- float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE);
- float angle = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
+ float radius = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_RANGE);
+ float angle = VSG::storage->light_get_param(p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE);
CameraMatrix cm;
- cm.set_perspective( angle*2.0, 1.0, 0.01, radius );
-
+ cm.set_perspective(angle * 2.0, 1.0, 0.01, radius);
Vector<Plane> planes = cm.get_projection_planes(p_instance->transform);
- int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK);
+ int cull_count = p_scenario->octree.cull_convex(planes, instance_shadow_cull_result, MAX_INSTANCE_CULL, VS::INSTANCE_GEOMETRY_MASK);
- for (int j=0;j<cull_count;j++) {
+ for (int j = 0; j < cull_count; j++) {
Instance *instance = instance_shadow_cull_result[j];
- if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) {
+ if (!instance->visible || !((1 << instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData *>(instance->base_data)->can_cast_shadows) {
cull_count--;
- SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]);
+ SWAP(instance_shadow_cull_result[j], instance_shadow_cull_result[cull_count]);
j--;
-
}
}
-
- VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,p_instance->transform,radius,0,0);
- VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,0,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count);
+ VSG::scene_render->light_instance_set_shadow_transform(light->instance, cm, p_instance->transform, radius, 0, 0);
+ VSG::scene_render->render_shadow(light->instance, p_shadow_atlas, 0, (RasterizerScene::InstanceBase **)instance_shadow_cull_result, cull_count);
} break;
}
-
}
-
-void VisualServerScene::render_camera(RID p_camera, RID p_scenario,Size2 p_viewport_size,RID p_shadow_atlas) {
+void VisualServerScene::render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas) {
Camera *camera = camera_owner.getornull(p_camera);
ERR_FAIL_COND(!camera);
/* STEP 1 - SETUP CAMERA */
CameraMatrix camera_matrix;
- bool ortho=false;
+ bool ortho = false;
-
- switch(camera->type) {
+ switch (camera->type) {
case Camera::ORTHOGONAL: {
camera_matrix.set_orthogonal(
- camera->size,
- p_viewport_size.width / (float)p_viewport_size.height,
- camera->znear,
- camera->zfar,
- camera->vaspect
-
- );
- ortho=true;
+ camera->size,
+ p_viewport_size.width / (float)p_viewport_size.height,
+ camera->znear,
+ camera->zfar,
+ camera->vaspect
+
+ );
+ ortho = true;
} break;
case Camera::PERSPECTIVE: {
camera_matrix.set_perspective(
- camera->fov,
- p_viewport_size.width / (float)p_viewport_size.height,
- camera->znear,
- camera->zfar,
- camera->vaspect
+ camera->fov,
+ p_viewport_size.width / (float)p_viewport_size.height,
+ camera->znear,
+ camera->zfar,
+ camera->vaspect
- );
- ortho=false;
+ );
+ ortho = false;
} break;
}
- _render_scene(camera->transform,camera_matrix,ortho,camera->env,camera->visible_layers,p_scenario,p_shadow_atlas,RID(),-1);
-
+ _render_scene(camera->transform, camera_matrix, ortho, camera->env, camera->visible_layers, p_scenario, p_shadow_atlas, RID(), -1);
}
-
-void VisualServerScene::_render_scene(const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_force_environment,uint32_t p_visible_layers, RID p_scenario,RID p_shadow_atlas,RID p_reflection_probe,int p_reflection_probe_pass) {
-
-
+void VisualServerScene::_render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass) {
Scenario *scenario = scenario_owner.getornull(p_scenario);
render_pass++;
- uint32_t camera_layer_mask=p_visible_layers;
+ uint32_t camera_layer_mask = p_visible_layers;
VSG::scene_render->set_scene_pass(render_pass);
-
//rasterizer->set_camera(camera->transform, camera_matrix,ortho);
Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform);
- Plane near_plane(p_cam_transform.origin,-p_cam_transform.basis.get_axis(2).normalized());
+ Plane near_plane(p_cam_transform.origin, -p_cam_transform.basis.get_axis(2).normalized());
float z_far = p_cam_projection.get_z_far();
/* STEP 2 - CULL */
- int cull_count = scenario->octree.cull_convex(planes,instance_cull_result,MAX_INSTANCE_CULL);
- light_cull_count=0;
+ int cull_count = scenario->octree.cull_convex(planes, instance_cull_result, MAX_INSTANCE_CULL);
+ light_cull_count = 0;
- reflection_probe_cull_count=0;
+ reflection_probe_cull_count = 0;
- //light_samplers_culled=0;
+//light_samplers_culled=0;
/* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0));
print_line("OTO: "+itos(p_scenario->octree.get_octant_count()));
@@ -1826,10 +1695,9 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
print_line("OTP: "+itos(p_scenario->octree.get_pair_count()));
*/
- /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
+/* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */
-
- // compute portals
+// compute portals
#if 0
exterior_visited=false;
exterior_portal_cull_count=0;
@@ -1913,43 +1781,39 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
#endif
/* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */
- for(int i=0;i<cull_count;i++) {
+ for (int i = 0; i < cull_count; i++) {
Instance *ins = instance_cull_result[i];
- bool keep=false;
+ bool keep = false;
- if ((camera_layer_mask&ins->layer_mask)==0) {
+ if ((camera_layer_mask & ins->layer_mask) == 0) {
//failure
- } else if (ins->base_type==VS::INSTANCE_LIGHT && ins->visible) {
-
+ } else if (ins->base_type == VS::INSTANCE_LIGHT && ins->visible) {
- if (ins->visible && light_cull_count<MAX_LIGHTS_CULLED) {
+ if (ins->visible && light_cull_count < MAX_LIGHTS_CULLED) {
- InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
if (!light->geometries.empty()) {
//do not add this light if no geometry is affected by it..
- light_cull_result[light_cull_count]=ins;
- light_instance_cull_result[light_cull_count]=light->instance;
+ light_cull_result[light_cull_count] = ins;
+ light_instance_cull_result[light_cull_count] = light->instance;
if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) {
VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later
}
light_cull_count++;
}
-
-
}
- } else if (ins->base_type==VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
+ } else if (ins->base_type == VS::INSTANCE_REFLECTION_PROBE && ins->visible) {
+ if (ins->visible && reflection_probe_cull_count < MAX_REFLECTION_PROBES_CULLED) {
- if (ins->visible && reflection_probe_cull_count<MAX_REFLECTION_PROBES_CULLED) {
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(ins->base_data);
- InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(ins->base_data);
-
- if (p_reflection_probe!=reflection_probe->instance) {
+ if (p_reflection_probe != reflection_probe->instance) {
//avoid entering The Matrix
if (!reflection_probe->geometries.empty()) {
@@ -1957,32 +1821,31 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) {
if (!reflection_probe->update_list.in_list()) {
- reflection_probe->render_step=0;
+ reflection_probe->render_step = 0;
reflection_probe_render_list.add(&reflection_probe->update_list);
}
- reflection_probe->reflection_dirty=false;
+ reflection_probe->reflection_dirty = false;
}
if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) {
- reflection_probe_instance_cull_result[reflection_probe_cull_count]=reflection_probe->instance;
+ reflection_probe_instance_cull_result[reflection_probe_cull_count] = reflection_probe->instance;
reflection_probe_cull_count++;
}
-
}
}
}
- } else if (ins->base_type==VS::INSTANCE_GI_PROBE && ins->visible) {
+ } else if (ins->base_type == VS::INSTANCE_GI_PROBE && ins->visible) {
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(ins->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(ins->base_data);
if (!gi_probe->update_element.in_list()) {
gi_probe_update_list.add(&gi_probe->update_element);
}
- } else if ((1<<ins->base_type)&VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows!=VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
+ } else if ((1 << ins->base_type) & VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows != VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) {
- keep=true;
+ keep = true;
#if 0
bool discarded=false;
@@ -2049,230 +1912,207 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
}
#endif
-
- InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(ins->base_data);
-
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(ins->base_data);
if (geom->lighting_dirty) {
- int l=0;
+ int l = 0;
//only called when lights AABB enter/exit this geometry
ins->light_instances.resize(geom->lighting.size());
- for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) {
+ for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
- InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
- ins->light_instances[l++]=light->instance;
+ ins->light_instances[l++] = light->instance;
}
- geom->lighting_dirty=false;
+ geom->lighting_dirty = false;
}
if (geom->reflection_dirty) {
- int l=0;
+ int l = 0;
//only called when reflection probe AABB enter/exit this geometry
ins->reflection_probe_instances.resize(geom->reflection_probes.size());
- for (List<Instance*>::Element *E=geom->reflection_probes.front();E;E=E->next()) {
+ for (List<Instance *>::Element *E = geom->reflection_probes.front(); E; E = E->next()) {
- InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(E->get()->base_data);
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(E->get()->base_data);
- ins->reflection_probe_instances[l++]=reflection_probe->instance;
+ ins->reflection_probe_instances[l++] = reflection_probe->instance;
}
- geom->reflection_dirty=false;
+ geom->reflection_dirty = false;
}
if (geom->gi_probes_dirty) {
- int l=0;
+ int l = 0;
//only called when reflection probe AABB enter/exit this geometry
ins->gi_probe_instances.resize(geom->gi_probes.size());
- for (List<Instance*>::Element *E=geom->gi_probes.front();E;E=E->next()) {
+ for (List<Instance *>::Element *E = geom->gi_probes.front(); E; E = E->next()) {
- InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(E->get()->base_data);
+ InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData *>(E->get()->base_data);
- ins->gi_probe_instances[l++]=gi_probe->probe_instance;
+ ins->gi_probe_instances[l++] = gi_probe->probe_instance;
}
- geom->gi_probes_dirty=false;
+ geom->gi_probes_dirty = false;
}
ins->depth = near_plane.distance_to(ins->transform.origin);
- ins->depth_layer=CLAMP(int(ins->depth*8/z_far),0,7);
-
+ ins->depth_layer = CLAMP(int(ins->depth * 8 / z_far), 0, 7);
}
if (!keep) {
// remove, no reason to keep
cull_count--;
- SWAP( instance_cull_result[i], instance_cull_result[ cull_count ] );
+ SWAP(instance_cull_result[i], instance_cull_result[cull_count]);
i--;
- ins->last_render_pass=0; // make invalid
+ ins->last_render_pass = 0; // make invalid
} else {
- ins->last_render_pass=render_pass;
+ ins->last_render_pass = render_pass;
}
}
/* STEP 5 - PROCESS LIGHTS */
- RID *directional_light_ptr=&light_instance_cull_result[light_cull_count];
- int directional_light_count=0;
+ RID *directional_light_ptr = &light_instance_cull_result[light_cull_count];
+ int directional_light_count = 0;
// directional lights
{
- Instance** lights_with_shadow = (Instance**)alloca(sizeof(Instance*)*scenario->directional_lights.size());
- int directional_shadow_count=0;
+ Instance **lights_with_shadow = (Instance **)alloca(sizeof(Instance *) * scenario->directional_lights.size());
+ int directional_shadow_count = 0;
- for (List<Instance*>::Element *E=scenario->directional_lights.front();E;E=E->next()) {
+ for (List<Instance *>::Element *E = scenario->directional_lights.front(); E; E = E->next()) {
- if (light_cull_count+directional_light_count>=MAX_LIGHTS_CULLED) {
+ if (light_cull_count + directional_light_count >= MAX_LIGHTS_CULLED) {
break;
}
if (!E->get()->visible)
continue;
- InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data);
-
+ InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
//check shadow..
-
if (light && p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) {
- lights_with_shadow[directional_shadow_count++]=E->get();
-
+ lights_with_shadow[directional_shadow_count++] = E->get();
}
//add to list
- directional_light_ptr[directional_light_count++]=light->instance;
+ directional_light_ptr[directional_light_count++] = light->instance;
}
VSG::scene_render->set_directional_shadow_count(directional_shadow_count);
- for(int i=0;i<directional_shadow_count;i++) {
-
- _light_instance_update_shadow(lights_with_shadow[i],p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario);
+ for (int i = 0; i < directional_shadow_count; i++) {
+ _light_instance_update_shadow(lights_with_shadow[i], p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
}
}
-
{ //setup shadow maps
//SortArray<Instance*,_InstanceLightsort> sorter;
//sorter.sort(light_cull_result,light_cull_count);
- for (int i=0;i<light_cull_count;i++) {
+ for (int i = 0; i < light_cull_count; i++) {
Instance *ins = light_cull_result[i];
if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base))
continue;
- InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data);
+ InstanceLightData *light = static_cast<InstanceLightData *>(ins->base_data);
float coverage;
- { //compute coverage
-
+ { //compute coverage
Transform cam_xf = p_cam_transform;
float zn = p_cam_projection.get_z_near();
- Plane p (cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2) ); //camera near plane
+ Plane p(cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2)); //camera near plane
- float vp_w,vp_h; //near plane size in screen coordinates
- p_cam_projection.get_viewport_size(vp_w,vp_h);
+ float vp_w, vp_h; //near plane size in screen coordinates
+ p_cam_projection.get_viewport_size(vp_w, vp_h);
-
- switch(VSG::storage->light_get_type(ins->base)) {
+ switch (VSG::storage->light_get_type(ins->base)) {
case VS::LIGHT_OMNI: {
- float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE);
+ float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
//get two points parallel to near plane
- Vector3 points[2]={
+ Vector3 points[2] = {
ins->transform.origin,
- ins->transform.origin+cam_xf.basis.get_axis(0)*radius
+ ins->transform.origin + cam_xf.basis.get_axis(0) * radius
};
if (!p_cam_orthogonal) {
//if using perspetive, map them to near plane
- for(int j=0;j<2;j++) {
- if (p.distance_to(points[j]) < 0 ) {
- points[j].z=-zn; //small hack to keep size constant when hitting the screen
-
+ for (int j = 0; j < 2; j++) {
+ if (p.distance_to(points[j]) < 0) {
+ points[j].z = -zn; //small hack to keep size constant when hitting the screen
}
- p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane
+ p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
}
-
-
}
- float screen_diameter = points[0].distance_to(points[1])*2;
- coverage = screen_diameter / (vp_w+vp_h);
+ float screen_diameter = points[0].distance_to(points[1]) * 2;
+ coverage = screen_diameter / (vp_w + vp_h);
} break;
case VS::LIGHT_SPOT: {
- float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE);
- float angle = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_SPOT_ANGLE);
-
-
- float w = radius*Math::sin(Math::deg2rad(angle));
- float d = radius*Math::cos(Math::deg2rad(angle));
+ float radius = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_RANGE);
+ float angle = VSG::storage->light_get_param(ins->base, VS::LIGHT_PARAM_SPOT_ANGLE);
+ float w = radius * Math::sin(Math::deg2rad(angle));
+ float d = radius * Math::cos(Math::deg2rad(angle));
- Vector3 base = ins->transform.origin-ins->transform.basis.get_axis(2).normalized()*d;
+ Vector3 base = ins->transform.origin - ins->transform.basis.get_axis(2).normalized() * d;
- Vector3 points[2]={
+ Vector3 points[2] = {
base,
- base+cam_xf.basis.get_axis(0)*w
+ base + cam_xf.basis.get_axis(0) * w
};
if (!p_cam_orthogonal) {
//if using perspetive, map them to near plane
- for(int j=0;j<2;j++) {
- if (p.distance_to(points[j]) < 0 ) {
- points[j].z=-zn; //small hack to keep size constant when hitting the screen
-
+ for (int j = 0; j < 2; j++) {
+ if (p.distance_to(points[j]) < 0) {
+ points[j].z = -zn; //small hack to keep size constant when hitting the screen
}
- p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane
+ p.intersects_segment(cam_xf.origin, points[j], &points[j]); //map to plane
}
-
-
}
- float screen_diameter = points[0].distance_to(points[1])*2;
- coverage = screen_diameter / (vp_w+vp_h);
-
+ float screen_diameter = points[0].distance_to(points[1]) * 2;
+ coverage = screen_diameter / (vp_w + vp_h);
} break;
default: {
ERR_PRINT("Invalid Light Type");
}
}
-
}
-
if (light->shadow_dirty) {
light->last_version++;
- light->shadow_dirty=false;
+ light->shadow_dirty = false;
}
-
- bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas,light->instance,coverage,light->last_version);
+ bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas, light->instance, coverage, light->last_version);
if (redraw) {
//must redraw!
- _light_instance_update_shadow(ins,p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario);
+ _light_instance_update_shadow(ins, p_cam_transform, p_cam_projection, p_cam_orthogonal, p_shadow_atlas, scenario);
}
-
}
}
@@ -2280,11 +2120,11 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
RID environment;
if (p_force_environment.is_valid()) //camera has more environment priority
- environment=p_force_environment;
+ environment = p_force_environment;
else if (scenario->environment.is_valid())
- environment=scenario->environment;
+ environment = scenario->environment;
else
- environment=scenario->fallback_environment;
+ environment = scenario->fallback_environment;
#if 0
/* STEP 6 - SAMPLE BAKED LIGHT */
@@ -2301,62 +2141,57 @@ void VisualServerScene::_render_scene(const Transform p_cam_transform,const Came
#endif
/* STEP 7 - PROCESS GEOMETRY AND DRAW SCENE*/
- VSG::scene_render->render_scene(p_cam_transform, p_cam_projection,p_cam_orthogonal,(RasterizerScene::InstanceBase**)instance_cull_result,cull_count,light_instance_cull_result,light_cull_count+directional_light_count,reflection_probe_instance_cull_result,reflection_probe_cull_count,environment,p_shadow_atlas,scenario->reflection_atlas,p_reflection_probe,p_reflection_probe_pass);
-
-
+ VSG::scene_render->render_scene(p_cam_transform, p_cam_projection, p_cam_orthogonal, (RasterizerScene::InstanceBase **)instance_cull_result, cull_count, light_instance_cull_result, light_cull_count + directional_light_count, reflection_probe_instance_cull_result, reflection_probe_cull_count, environment, p_shadow_atlas, scenario->reflection_atlas, p_reflection_probe, p_reflection_probe_pass);
}
-bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p_step) {
+bool VisualServerScene::_render_reflection_probe_step(Instance *p_instance, int p_step) {
- InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data);
+ InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData *>(p_instance->base_data);
Scenario *scenario = p_instance->scenario;
- ERR_FAIL_COND_V(!scenario,true);
+ ERR_FAIL_COND_V(!scenario, true);
- if (p_step==0) {
+ if (p_step == 0) {
- if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance,scenario->reflection_atlas)) {
+ if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance, scenario->reflection_atlas)) {
return true; //sorry, all full :(
}
}
- if (p_step>=0 && p_step<6) {
+ if (p_step >= 0 && p_step < 6) {
- static const Vector3 view_normals[6]={
+ static const Vector3 view_normals[6] = {
Vector3(-1, 0, 0),
Vector3(+1, 0, 0),
- Vector3( 0,-1, 0),
- Vector3( 0,+1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0,+1)
+ Vector3(0, -1, 0),
+ Vector3(0, +1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, +1)
};
Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base);
Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base);
float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base);
+ Vector3 edge = view_normals[p_step] * extents;
+ float distance = ABS(view_normals[p_step].dot(edge) - view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
- Vector3 edge = view_normals[p_step]*extents;
- float distance = ABS(view_normals[p_step].dot(edge)-view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit
-
- max_distance = MAX(max_distance,distance);
-
+ max_distance = MAX(max_distance, distance);
//render cubemap side
CameraMatrix cm;
- cm.set_perspective(90,1,0.01,max_distance);
-
-
- static const Vector3 view_up[6]={
- Vector3( 0,-1, 0),
- Vector3( 0,-1, 0),
- Vector3( 0, 0,-1),
- Vector3( 0, 0,+1),
- Vector3( 0,-1, 0),
- Vector3( 0,-1, 0)
+ cm.set_perspective(90, 1, 0.01, max_distance);
+
+ static const Vector3 view_up[6] = {
+ Vector3(0, -1, 0),
+ Vector3(0, -1, 0),
+ Vector3(0, 0, -1),
+ Vector3(0, 0, +1),
+ Vector3(0, -1, 0),
+ Vector3(0, -1, 0)
};
Transform local_view;
- local_view.set_look_at(origin_offset,origin_offset+view_normals[p_step],view_up[p_step]);
+ local_view.set_look_at(origin_offset, origin_offset + view_normals[p_step], view_up[p_step]);
Transform xform = p_instance->transform * local_view;
@@ -2364,10 +2199,10 @@ bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p
if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) {
- shadow_atlas=scenario->reflection_probe_shadow_atlas;
+ shadow_atlas = scenario->reflection_probe_shadow_atlas;
}
- _render_scene(xform,cm,false,RID(),VSG::storage->reflection_probe_get_cull_mask(p_instance->base),p_instance->scenario->self,shadow_atlas,reflection_probe->instance,p_step);
+ _render_scene(xform, cm, false, RID(), VSG::storage->reflection_probe_get_cull_mask(p_instance->base), p_instance->scenario->self, shadow_atlas, reflection_probe->instance, p_step);
} else {
//do roughness postprocess step until it belives it's done
@@ -2377,84 +2212,81 @@ bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p
return false;
}
-void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell* p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
+void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) {
- if (p_level==p_header->cell_subdiv-1) {
+ if (p_level == p_header->cell_subdiv - 1) {
Vector3 emission;
- emission.x=(p_cell[p_idx].emission>>24)/255.0;
- emission.y=((p_cell[p_idx].emission>>16)&0xFF)/255.0;
- emission.z=((p_cell[p_idx].emission>>8)&0xFF)/255.0;
- float l = (p_cell[p_idx].emission&0xFF)/255.0;
- l*=8.0;
+ emission.x = (p_cell[p_idx].emission >> 24) / 255.0;
+ emission.y = ((p_cell[p_idx].emission >> 16) & 0xFF) / 255.0;
+ emission.z = ((p_cell[p_idx].emission >> 8) & 0xFF) / 255.0;
+ float l = (p_cell[p_idx].emission & 0xFF) / 255.0;
+ l *= 8.0;
- emission*=l;
+ emission *= l;
- p_local_data[p_idx].energy[0]=uint16_t(emission.x*1024); //go from 0 to 1024 for light
- p_local_data[p_idx].energy[1]=uint16_t(emission.y*1024); //go from 0 to 1024 for light
- p_local_data[p_idx].energy[2]=uint16_t(emission.z*1024); //go from 0 to 1024 for light
+ p_local_data[p_idx].energy[0] = uint16_t(emission.x * 1024); //go from 0 to 1024 for light
+ p_local_data[p_idx].energy[1] = uint16_t(emission.y * 1024); //go from 0 to 1024 for light
+ p_local_data[p_idx].energy[2] = uint16_t(emission.z * 1024); //go from 0 to 1024 for light
} else {
- p_local_data[p_idx].energy[0]=0;
- p_local_data[p_idx].energy[1]=0;
- p_local_data[p_idx].energy[2]=0;
+ p_local_data[p_idx].energy[0] = 0;
+ p_local_data[p_idx].energy[1] = 0;
+ p_local_data[p_idx].energy[2] = 0;
- int half=(1<<(p_header->cell_subdiv-1))>>(p_level+1);
+ int half = (1 << (p_header->cell_subdiv - 1)) >> (p_level + 1);
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
uint32_t child = p_cell[p_idx].children[i];
- if (child==0xFFFFFFFF)
+ if (child == 0xFFFFFFFF)
continue;
int x = p_x;
int y = p_y;
int z = p_z;
- if (i&1)
- x+=half;
- if (i&2)
- y+=half;
- if (i&4)
- z+=half;
+ if (i & 1)
+ x += half;
+ if (i & 2)
+ y += half;
+ if (i & 4)
+ z += half;
- _gi_probe_fill_local_data(child,p_level+1,x,y,z,p_cell,p_header,p_local_data,prev_cell);
+ _gi_probe_fill_local_data(child, p_level + 1, x, y, z, p_cell, p_header, p_local_data, prev_cell);
}
}
//position for each part of the mipmaped texture
- p_local_data[p_idx].pos[0]=p_x>>(p_header->cell_subdiv-p_level-1);
- p_local_data[p_idx].pos[1]=p_y>>(p_header->cell_subdiv-p_level-1);
- p_local_data[p_idx].pos[2]=p_z>>(p_header->cell_subdiv-p_level-1);
+ p_local_data[p_idx].pos[0] = p_x >> (p_header->cell_subdiv - p_level - 1);
+ p_local_data[p_idx].pos[1] = p_y >> (p_header->cell_subdiv - p_level - 1);
+ p_local_data[p_idx].pos[2] = p_z >> (p_header->cell_subdiv - p_level - 1);
prev_cell[p_level].push_back(p_idx);
-
}
+void VisualServerScene::_gi_probe_bake_threads(void *self) {
-void VisualServerScene::_gi_probe_bake_threads(void* self) {
-
- VisualServerScene* vss = (VisualServerScene*)self;
+ VisualServerScene *vss = (VisualServerScene *)self;
vss->_gi_probe_bake_thread();
}
void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
-
- InstanceGIProbeData *probe = static_cast<InstanceGIProbeData*>(p_instance->base_data);
+ InstanceGIProbeData *probe = static_cast<InstanceGIProbeData *>(p_instance->base_data);
if (probe->dynamic.probe_data.is_valid()) {
VSG::storage->free(probe->dynamic.probe_data);
- probe->dynamic.probe_data=RID();
+ probe->dynamic.probe_data = RID();
}
- probe->dynamic.light_data=VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
+ probe->dynamic.light_data = VSG::storage->gi_probe_get_dynamic_data(p_instance->base);
- if (probe->dynamic.light_data.size()==0)
+ if (probe->dynamic.light_data.size() == 0)
return;
//using dynamic data
- PoolVector<int>::Read r=probe->dynamic.light_data.read();
+ PoolVector<int>::Read r = probe->dynamic.light_data.read();
const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr();
@@ -2462,36 +2294,36 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
int cell_count = probe->dynamic.local_data.size();
PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write();
- const GIProbeDataCell *cells = (GIProbeDataCell*)&r[16];
+ const GIProbeDataCell *cells = (GIProbeDataCell *)&r[16];
probe->dynamic.level_cell_lists.resize(header->cell_subdiv);
- _gi_probe_fill_local_data(0,0,0,0,0,cells,header,ldw.ptr(),probe->dynamic.level_cell_lists.ptr());
+ _gi_probe_fill_local_data(0, 0, 0, 0, 0, cells, header, ldw.ptr(), probe->dynamic.level_cell_lists.ptr());
bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base);
probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED;
- probe->dynamic.probe_data=VSG::storage->gi_probe_dynamic_data_create(header->width,header->height,header->depth,probe->dynamic.compression);
+ probe->dynamic.probe_data = VSG::storage->gi_probe_dynamic_data_create(header->width, header->height, header->depth, probe->dynamic.compression);
- probe->dynamic.bake_dynamic_range=VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
+ probe->dynamic.bake_dynamic_range = VSG::storage->gi_probe_get_dynamic_range(p_instance->base);
probe->dynamic.mipmaps_3d.clear();
- probe->dynamic.propagate=VSG::storage->gi_probe_get_propagation(p_instance->base);
+ probe->dynamic.propagate = VSG::storage->gi_probe_get_propagation(p_instance->base);
- probe->dynamic.grid_size[0]=header->width;
- probe->dynamic.grid_size[1]=header->height;
- probe->dynamic.grid_size[2]=header->depth;
+ probe->dynamic.grid_size[0] = header->width;
+ probe->dynamic.grid_size[1] = header->height;
+ probe->dynamic.grid_size[2] = header->depth;
int size_limit = 1;
int size_divisor = 1;
- if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) {
+ if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
print_line("S3TC");
- size_limit=4;
- size_divisor=4;
+ size_limit = 4;
+ size_divisor = 4;
}
- for(int i=0;i<(int)header->cell_subdiv;i++) {
+ for (int i = 0; i < (int)header->cell_subdiv; i++) {
uint32_t x = header->width >> i;
uint32_t y = header->height >> i;
@@ -2499,56 +2331,55 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
//create and clear mipmap
PoolVector<uint8_t> mipmap;
- int size = x*y*z*4;
- size/=size_divisor;
+ int size = x * y * z * 4;
+ size /= size_divisor;
mipmap.resize(size);
PoolVector<uint8_t>::Write w = mipmap.write();
- zeromem(w.ptr(),size);
+ zeromem(w.ptr(), size);
w = PoolVector<uint8_t>::Write();
probe->dynamic.mipmaps_3d.push_back(mipmap);
- if (x<=size_limit || y<=size_limit || z<=size_limit)
+ if (x <= size_limit || y <= size_limit || z <= size_limit)
break;
}
- probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK;
- probe->invalid=false;
- probe->dynamic.enabled=true;
+ probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
+ probe->invalid = false;
+ probe->dynamic.enabled = true;
Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base);
Rect3 bounds = VSG::storage->gi_probe_get_bounds(p_instance->base);
float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base);
- probe->dynamic.light_to_cell_xform=cell_to_xform * p_instance->transform.affine_inverse();
+ probe->dynamic.light_to_cell_xform = cell_to_xform * p_instance->transform.affine_inverse();
- VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance,p_instance->base,probe->dynamic.probe_data);
- VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance,probe->dynamic.light_to_cell_xform);
+ VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance, p_instance->base, probe->dynamic.probe_data);
+ VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance, probe->dynamic.light_to_cell_xform);
- VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance,bounds.size/cell_size);
+ VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance, bounds.size / cell_size);
- probe->base_version=VSG::storage->gi_probe_get_version(p_instance->base);
+ probe->base_version = VSG::storage->gi_probe_get_version(p_instance->base);
//if compression is S3TC, fill it up
- if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) {
+ if (probe->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
//create all blocks
- Vector<Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> > comp_blocks;
+ Vector<Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> > comp_blocks;
int mipmap_count = probe->dynamic.mipmaps_3d.size();
comp_blocks.resize(mipmap_count);
- for(int i=0;i<cell_count;i++) {
+ for (int i = 0; i < cell_count; i++) {
const GIProbeDataCell &c = cells[i];
const InstanceGIProbeData::LocalData &ld = ldw[i];
- int level = c.level_alpha>>16;
- int mipmap = header->cell_subdiv - level -1;
+ int level = c.level_alpha >> 16;
+ int mipmap = header->cell_subdiv - level - 1;
if (mipmap >= mipmap_count)
- continue;//uninteresting
-
+ continue; //uninteresting
- int blockx = (ld.pos[0]>>2);
- int blocky = (ld.pos[1]>>2);
+ int blockx = (ld.pos[0] >> 2);
+ int blocky = (ld.pos[1] >> 2);
int blockz = (ld.pos[2]); //compression is x/y only
int blockw = (header->width >> mipmap) >> 2;
@@ -2556,120 +2387,115 @@ void VisualServerScene::_setup_gi_probe(Instance *p_instance) {
//print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh));
- uint32_t key = blockz * blockw*blockh + blocky * blockw + blockx;
+ uint32_t key = blockz * blockw * blockh + blocky * blockw + blockx;
- Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> & cmap = comp_blocks[mipmap];
+ Map<uint32_t, InstanceGIProbeData::CompBlockS3TC> &cmap = comp_blocks[mipmap];
if (!cmap.has(key)) {
InstanceGIProbeData::CompBlockS3TC k;
- k.offset=key; //use offset as counter first
- k.source_count=0;
- cmap[key]=k;
+ k.offset = key; //use offset as counter first
+ k.source_count = 0;
+ cmap[key] = k;
}
- InstanceGIProbeData::CompBlockS3TC &k=cmap[key];
- ERR_CONTINUE(k.source_count==16);
- k.sources[k.source_count++]=i;
+ InstanceGIProbeData::CompBlockS3TC &k = cmap[key];
+ ERR_CONTINUE(k.source_count == 16);
+ k.sources[k.source_count++] = i;
}
//fix the blocks, precomputing what is needed
probe->dynamic.mipmaps_s3tc.resize(mipmap_count);
- for(int i=0;i<mipmap_count;i++) {
- print_line("S3TC level: "+itos(i)+" blocks: "+itos(comp_blocks[i].size()));
+ for (int i = 0; i < mipmap_count; i++) {
+ print_line("S3TC level: " + itos(i) + " blocks: " + itos(comp_blocks[i].size()));
probe->dynamic.mipmaps_s3tc[i].resize(comp_blocks[i].size());
PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc[i].write();
- int block_idx=0;
+ int block_idx = 0;
- for (Map<uint32_t,InstanceGIProbeData::CompBlockS3TC>::Element *E=comp_blocks[i].front();E;E=E->next()) {
+ for (Map<uint32_t, InstanceGIProbeData::CompBlockS3TC>::Element *E = comp_blocks[i].front(); E; E = E->next()) {
InstanceGIProbeData::CompBlockS3TC k = E->get();
//PRECOMPUTE ALPHA
- int max_alpha=-100000;
- int min_alpha=k.source_count==16 ?100000 :0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
+ int max_alpha = -100000;
+ int min_alpha = k.source_count == 16 ? 100000 : 0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero)
- uint8_t alpha_block[4][4]={ {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0} };
+ uint8_t alpha_block[4][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
- for(int j=0;j<k.source_count;j++) {
+ for (int j = 0; j < k.source_count; j++) {
- int alpha = (cells[k.sources[j]].level_alpha>>8)&0xFF;
- if (alpha<min_alpha)
- min_alpha=alpha;
- if (alpha>max_alpha)
- max_alpha=alpha;
+ int alpha = (cells[k.sources[j]].level_alpha >> 8) & 0xFF;
+ if (alpha < min_alpha)
+ min_alpha = alpha;
+ if (alpha > max_alpha)
+ max_alpha = alpha;
//fill up alpha block
- alpha_block[ldw[k.sources[j]].pos[0]%4][ldw[k.sources[j]].pos[1]%4]=alpha;
-
+ alpha_block[ldw[k.sources[j]].pos[0] % 4][ldw[k.sources[j]].pos[1] % 4] = alpha;
}
//use the first mode (8 adjustable levels)
- k.alpha[0]=max_alpha;
- k.alpha[1]=min_alpha;
+ k.alpha[0] = max_alpha;
+ k.alpha[1] = min_alpha;
- uint64_t alpha_bits=0;
+ uint64_t alpha_bits = 0;
- if (max_alpha!=min_alpha) {
+ if (max_alpha != min_alpha) {
- int idx=0;
+ int idx = 0;
- for(int y=0;y<4;y++) {
- for(int x=0;x<4;x++) {
+ for (int y = 0; y < 4; y++) {
+ for (int x = 0; x < 4; x++) {
//substract minimum
- uint32_t a = uint32_t(alpha_block[x][y])-min_alpha;
+ uint32_t a = uint32_t(alpha_block[x][y]) - min_alpha;
//convert range to 3 bits
- a =int((a * 7.0 / (max_alpha-min_alpha))+0.5);
- a = CLAMP(a,0,7); //just to be sure
- a = 7-a; //because range is inverted in this mode
- if (a==0) {
+ a = int((a * 7.0 / (max_alpha - min_alpha)) + 0.5);
+ a = CLAMP(a, 0, 7); //just to be sure
+ a = 7 - a; //because range is inverted in this mode
+ if (a == 0) {
//do none, remain
- } else if (a==7) {
- a=1;
+ } else if (a == 7) {
+ a = 1;
} else {
- a=a+1;
+ a = a + 1;
}
- alpha_bits|=uint64_t(a)<<(idx*3);
+ alpha_bits |= uint64_t(a) << (idx * 3);
idx++;
}
}
}
- k.alpha[2]=(alpha_bits >> 0)&0xFF;
- k.alpha[3]=(alpha_bits >> 8)&0xFF;
- k.alpha[4]=(alpha_bits >> 16)&0xFF;
- k.alpha[5]=(alpha_bits >> 24)&0xFF;
- k.alpha[6]=(alpha_bits >> 32)&0xFF;
- k.alpha[7]=(alpha_bits >> 40)&0xFF;
-
- w[block_idx++]=k;
+ k.alpha[2] = (alpha_bits >> 0) & 0xFF;
+ k.alpha[3] = (alpha_bits >> 8) & 0xFF;
+ k.alpha[4] = (alpha_bits >> 16) & 0xFF;
+ k.alpha[5] = (alpha_bits >> 24) & 0xFF;
+ k.alpha[6] = (alpha_bits >> 32) & 0xFF;
+ k.alpha[7] = (alpha_bits >> 40) & 0xFF;
+ w[block_idx++] = k;
}
-
}
}
-
}
void VisualServerScene::_gi_probe_bake_thread() {
- while(true) {
+ while (true) {
probe_bake_sem->wait();
if (probe_bake_thread_exit) {
break;
}
- Instance* to_bake=NULL;
+ Instance *to_bake = NULL;
probe_bake_mutex->lock();
if (!probe_bake_list.empty()) {
- to_bake=probe_bake_list.front()->get();
+ to_bake = probe_bake_list.front()->get();
probe_bake_list.pop_front();
-
}
probe_bake_mutex->unlock();
@@ -2680,111 +2506,103 @@ void VisualServerScene::_gi_probe_bake_thread() {
}
}
+uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv) {
+ uint32_t cell = 0;
-uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells,int x,int y, int z,int p_cell_subdiv) {
-
+ int ofs_x = 0;
+ int ofs_y = 0;
+ int ofs_z = 0;
+ int size = 1 << (p_cell_subdiv - 1);
+ int half = size / 2;
- uint32_t cell=0;
-
- int ofs_x=0;
- int ofs_y=0;
- int ofs_z=0;
- int size = 1<<(p_cell_subdiv-1);
- int half=size/2;
-
- if (x<0 || x>=size)
+ if (x < 0 || x >= size)
return -1;
- if (y<0 || y>=size)
+ if (y < 0 || y >= size)
return -1;
- if (z<0 || z>=size)
+ if (z < 0 || z >= size)
return -1;
- for(int i=0;i<p_cell_subdiv-1;i++) {
+ for (int i = 0; i < p_cell_subdiv - 1; i++) {
const GIProbeDataCell *bc = &cells[cell];
int child = 0;
if (x >= ofs_x + half) {
- child|=1;
- ofs_x+=half;
+ child |= 1;
+ ofs_x += half;
}
if (y >= ofs_y + half) {
- child|=2;
- ofs_y+=half;
+ child |= 2;
+ ofs_y += half;
}
if (z >= ofs_z + half) {
- child|=4;
- ofs_z+=half;
+ child |= 4;
+ ofs_z += half;
}
cell = bc->children[child];
- if (cell==0xFFFFFFFF)
+ if (cell == 0xFFFFFFFF)
return 0xFFFFFFFF;
- half>>=1;
+ half >>= 1;
}
return cell;
-
}
-static float _get_normal_advance(const Vector3& p_normal ) {
+static float _get_normal_advance(const Vector3 &p_normal) {
Vector3 normal = p_normal;
Vector3 unorm = normal.abs();
- if ( (unorm.x >= unorm.y) && (unorm.x >= unorm.z) ) {
- // x code
- unorm = normal.x > 0.0 ? Vector3( 1.0, 0.0, 0.0 ) : Vector3( -1.0, 0.0, 0.0 ) ;
- } else if ( (unorm.y > unorm.x) && (unorm.y >= unorm.z) ) {
- // y code
- unorm = normal.y > 0.0 ? Vector3( 0.0, 1.0, 0.0 ) : Vector3( 0.0, -1.0, 0.0 ) ;
- } else if ( (unorm.z > unorm.x) && (unorm.z > unorm.y) ) {
- // z code
- unorm = normal.z > 0.0 ? Vector3( 0.0, 0.0, 1.0 ) : Vector3( 0.0, 0.0, -1.0 ) ;
+ if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
+ // x code
+ unorm = normal.x > 0.0 ? Vector3(1.0, 0.0, 0.0) : Vector3(-1.0, 0.0, 0.0);
+ } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
+ // y code
+ unorm = normal.y > 0.0 ? Vector3(0.0, 1.0, 0.0) : Vector3(0.0, -1.0, 0.0);
+ } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
+ // z code
+ unorm = normal.z > 0.0 ? Vector3(0.0, 0.0, 1.0) : Vector3(0.0, 0.0, -1.0);
} else {
- // oh-no we messed up code
- // has to be
- unorm = Vector3( 1.0, 0.0, 0.0 );
+ // oh-no we messed up code
+ // has to be
+ unorm = Vector3(1.0, 0.0, 0.0);
}
- return 1.0/normal.dot(unorm);
-
+ return 1.0 / normal.dot(unorm);
}
-void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,const GIProbeDataCell *cells,InstanceGIProbeData::LocalData *local_data,const uint32_t *leaves,int leaf_count, const InstanceGIProbeData::LightCache& light_cache,int sign) {
+void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int leaf_count, const InstanceGIProbeData::LightCache &light_cache, int sign) {
+ int light_r = int(light_cache.color.r * light_cache.energy * 1024.0) * sign;
+ int light_g = int(light_cache.color.g * light_cache.energy * 1024.0) * sign;
+ int light_b = int(light_cache.color.b * light_cache.energy * 1024.0) * sign;
- int light_r = int(light_cache.color.r * light_cache.energy * 1024.0)*sign;
- int light_g = int(light_cache.color.g * light_cache.energy * 1024.0)*sign;
- int light_b = int(light_cache.color.b * light_cache.energy * 1024.0)*sign;
-
- float limits[3]={float(header->width),float(header->height),float(header->depth)};
+ float limits[3] = { float(header->width), float(header->height), float(header->depth) };
Plane clip[3];
- int clip_planes=0;
-
-
+ int clip_planes = 0;
- switch(light_cache.type) {
+ switch (light_cache.type) {
case VS::LIGHT_DIRECTIONAL: {
- float max_len = Vector3(limits[0],limits[1],limits[2]).length()*1.1;
+ float max_len = Vector3(limits[0], limits[1], limits[2]).length() * 1.1;
Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized();
- for(int i=0;i<3;i++) {
+ for (int i = 0; i < 3; i++) {
- if (ABS(light_axis[i])<CMP_EPSILON)
+ if (ABS(light_axis[i]) < CMP_EPSILON)
continue;
- clip[clip_planes].normal[i]=1.0;
+ clip[clip_planes].normal[i] = 1.0;
- if (light_axis[i]<0) {
+ if (light_axis[i] < 0) {
- clip[clip_planes].d=limits[i]+1;
+ clip[clip_planes].d = limits[i] + 1;
} else {
- clip[clip_planes].d-=1.0;
+ clip[clip_planes].d -= 1.0;
}
clip_planes++;
@@ -2792,137 +2610,129 @@ void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,con
float distance_adv = _get_normal_advance(light_axis);
- int success_count=0;
+ int success_count = 0;
uint64_t us = OS::get_singleton()->get_ticks_usec();
- for(int i=0;i<leaf_count;i++) {
+ for (int i = 0; i < leaf_count; i++) {
uint32_t idx = leaves[i];
const GIProbeDataCell *cell = &cells[idx];
InstanceGIProbeData::LocalData *light = &local_data[idx];
- Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5);
- Vector3 norm (
- (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0,
- (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0,
- (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0
- );
-
+ Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
+ Vector3 norm(
+ (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
+ (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
+ (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
float att = norm.dot(-light_axis);
- if (att<0.001) {
+ if (att < 0.001) {
//not lighting towards this
continue;
}
Vector3 from = to - max_len * light_axis;
- for(int j=0;j<clip_planes;j++) {
+ for (int j = 0; j < clip_planes; j++) {
- clip[j].intersects_segment(from,to,&from);
+ clip[j].intersects_segment(from, to, &from);
}
float distance = (to - from).length();
- distance+=distance_adv-Math::fmod(distance,distance_adv); //make it reach the center of the box always
+ distance += distance_adv - Math::fmod(distance, distance_adv); //make it reach the center of the box always
from = to - light_axis * distance;
- uint32_t result=0xFFFFFFFF;
+ uint32_t result = 0xFFFFFFFF;
- while(distance>-distance_adv) { //use this to avoid precision errors
+ while (distance > -distance_adv) { //use this to avoid precision errors
- result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv);
- if (result!=0xFFFFFFFF) {
+ result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
+ if (result != 0xFFFFFFFF) {
break;
}
- from+=light_axis*distance_adv;
- distance-=distance_adv;
+ from += light_axis * distance_adv;
+ distance -= distance_adv;
}
- if (result==idx) {
+ if (result == idx) {
//cell hit itself! hooray!
- light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0);
- light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0);
- light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0);
- success_count++;
+ light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
+ light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
+ light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
+ success_count++;
}
}
- print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0));
- print_line("valid cells: "+itos(success_count));
-
+ print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
+ print_line("valid cells: " + itos(success_count));
} break;
case VS::LIGHT_OMNI:
case VS::LIGHT_SPOT: {
-
uint64_t us = OS::get_singleton()->get_ticks_usec();
Vector3 light_pos = light_cache.transform.origin;
Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized();
-
float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length();
- for(int i=0;i<leaf_count;i++) {
+ for (int i = 0; i < leaf_count; i++) {
uint32_t idx = leaves[i];
const GIProbeDataCell *cell = &cells[idx];
InstanceGIProbeData::LocalData *light = &local_data[idx];
- Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5);
- Vector3 norm (
- (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0,
- (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0,
- (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0
- );
+ Vector3 to(light->pos[0] + 0.5, light->pos[1] + 0.5, light->pos[2] + 0.5);
+ Vector3 norm(
+ (((cells[idx].normal >> 16) & 0xFF) / 255.0) * 2.0 - 1.0,
+ (((cells[idx].normal >> 8) & 0xFF) / 255.0) * 2.0 - 1.0,
+ (((cells[idx].normal >> 0) & 0xFF) / 255.0) * 2.0 - 1.0);
Vector3 light_axis = (to - light_pos).normalized();
float distance_adv = _get_normal_advance(light_axis);
float att = norm.dot(-light_axis);
- if (att<0.001) {
+ if (att < 0.001) {
//not lighting towards this
continue;
}
{
float d = light_pos.distance_to(to);
- if (d+distance_adv > local_radius)
+ if (d + distance_adv > local_radius)
continue; // too far away
- float dt = CLAMP((d+distance_adv)/local_radius,0,1);
- att*= powf(1.0-dt,light_cache.attenuation);
+ float dt = CLAMP((d + distance_adv) / local_radius, 0, 1);
+ att *= powf(1.0 - dt, light_cache.attenuation);
}
-
- if (light_cache.type==VS::LIGHT_SPOT) {
+ if (light_cache.type == VS::LIGHT_SPOT) {
float angle = Math::rad2deg(acos(light_axis.dot(spot_axis)));
if (angle > light_cache.spot_angle)
continue;
- float d = CLAMP(angle/light_cache.spot_angle,1,0);
- att*= powf(1.0-d,light_cache.spot_attenuation);
-
+ float d = CLAMP(angle / light_cache.spot_angle, 1, 0);
+ att *= powf(1.0 - d, light_cache.spot_attenuation);
}
- clip_planes=0;
+ clip_planes = 0;
- for(int c=0;c<3;c++) {
+ for (int c = 0; c < 3; c++) {
- if (ABS(light_axis[c])<CMP_EPSILON)
+ if (ABS(light_axis[c]) < CMP_EPSILON)
continue;
- clip[clip_planes].normal[c]=1.0;
+ clip[clip_planes].normal[c] = 1.0;
- if (light_axis[c]<0) {
+ if (light_axis[c] < 0) {
- clip[clip_planes].d=limits[c]+1;
+ clip[clip_planes].d = limits[c] + 1;
} else {
- clip[clip_planes].d-=1.0;
+ clip[clip_planes].d -= 1.0;
}
clip_planes++;
@@ -2930,216 +2740,203 @@ void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,con
Vector3 from = light_pos;
- for(int j=0;j<clip_planes;j++) {
+ for (int j = 0; j < clip_planes; j++) {
- clip[j].intersects_segment(from,to,&from);
+ clip[j].intersects_segment(from, to, &from);
}
float distance = (to - from).length();
-
-
- distance-=Math::fmod(distance,distance_adv); //make it reach the center of the box always, but this tame make it closer
+ distance -= Math::fmod(distance, distance_adv); //make it reach the center of the box always, but this tame make it closer
from = to - light_axis * distance;
- uint32_t result=0xFFFFFFFF;
+ uint32_t result = 0xFFFFFFFF;
- while(distance>-distance_adv) { //use this to avoid precision errors
+ while (distance > -distance_adv) { //use this to avoid precision errors
- result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv);
- if (result!=0xFFFFFFFF) {
+ result = _gi_bake_find_cell(cells, int(floor(from.x)), int(floor(from.y)), int(floor(from.z)), header->cell_subdiv);
+ if (result != 0xFFFFFFFF) {
break;
}
- from+=light_axis*distance_adv;
- distance-=distance_adv;
+ from += light_axis * distance_adv;
+ distance -= distance_adv;
}
- if (result==idx) {
+ if (result == idx) {
//cell hit itself! hooray!
- light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0);
- light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0);
- light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0);
-
+ light->energy[0] += int32_t(light_r * att * ((cell->albedo >> 16) & 0xFF) / 255.0);
+ light->energy[1] += int32_t(light_g * att * ((cell->albedo >> 8) & 0xFF) / 255.0);
+ light->energy[2] += int32_t(light_b * att * ((cell->albedo) & 0xFF) / 255.0);
}
}
- print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0));
-
+ print_line("BAKE TIME: " + rtos((OS::get_singleton()->get_ticks_usec() - us) / 1000000.0));
} break;
}
}
-
-void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell* p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data,float p_propagate) {
+void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate) {
//average light to upper level
- float divisor=0;
- float sum[3]={0.0,0.0,0.0};
+ float divisor = 0;
+ float sum[3] = { 0.0, 0.0, 0.0 };
- for(int i=0;i<8;i++) {
+ for (int i = 0; i < 8; i++) {
uint32_t child = p_cells[p_idx].children[i];
- if (child==0xFFFFFFFF)
+ if (child == 0xFFFFFFFF)
continue;
- if (p_level+1 < (int)p_header->cell_subdiv-1) {
- _bake_gi_downscale_light(child,p_level+1,p_cells,p_header,p_local_data,p_propagate);
+ if (p_level + 1 < (int)p_header->cell_subdiv - 1) {
+ _bake_gi_downscale_light(child, p_level + 1, p_cells, p_header, p_local_data, p_propagate);
}
- sum[0]+=p_local_data[child].energy[0];
- sum[1]+=p_local_data[child].energy[1];
- sum[2]+=p_local_data[child].energy[2];
- divisor+=1.0;
-
+ sum[0] += p_local_data[child].energy[0];
+ sum[1] += p_local_data[child].energy[1];
+ sum[2] += p_local_data[child].energy[2];
+ divisor += 1.0;
}
- divisor=Math::lerp((float)8.0,divisor,p_propagate);
- sum[0]/=divisor;
- sum[1]/=divisor;
- sum[2]/=divisor;
+ divisor = Math::lerp((float)8.0, divisor, p_propagate);
+ sum[0] /= divisor;
+ sum[1] /= divisor;
+ sum[2] /= divisor;
//divide by eight for average
- p_local_data[p_idx].energy[0]=Math::fast_ftoi(sum[0]);
- p_local_data[p_idx].energy[1]=Math::fast_ftoi(sum[1]);
- p_local_data[p_idx].energy[2]=Math::fast_ftoi(sum[2]);
-
+ p_local_data[p_idx].energy[0] = Math::fast_ftoi(sum[0]);
+ p_local_data[p_idx].energy[1] = Math::fast_ftoi(sum[1]);
+ p_local_data[p_idx].energy[2] = Math::fast_ftoi(sum[2]);
}
-
void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
- InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data);
+ InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
- PoolVector<int>::Read r=probe_data->dynamic.light_data.read();
+ PoolVector<int>::Read r = probe_data->dynamic.light_data.read();
const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr();
- const GIProbeDataCell *cells = (const GIProbeDataCell*)&r[16];
+ const GIProbeDataCell *cells = (const GIProbeDataCell *)&r[16];
- int leaf_count = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].size();
- const uint32_t *leaves = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].ptr();
+ int leaf_count = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].size();
+ const uint32_t *leaves = probe_data->dynamic.level_cell_lists[header->cell_subdiv - 1].ptr();
PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write();
InstanceGIProbeData::LocalData *local_data = ldw.ptr();
-
//remove what must be removed
- for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache.front();E;E=E->next()) {
+ for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache.front(); E; E = E->next()) {
RID rid = E->key();
- const InstanceGIProbeData::LightCache& lc = E->get();
+ const InstanceGIProbeData::LightCache &lc = E->get();
- if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid]==lc)) {
+ if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid] == lc)) {
//erase light data
- _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,-1);
+ _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, -1);
}
-
}
//add what must be added
- for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache_changes.front();E;E=E->next()) {
+ for (Map<RID, InstanceGIProbeData::LightCache>::Element *E = probe_data->dynamic.light_cache_changes.front(); E; E = E->next()) {
RID rid = E->key();
- const InstanceGIProbeData::LightCache& lc = E->get();
+ const InstanceGIProbeData::LightCache &lc = E->get();
- if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid]==lc)) {
+ if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid] == lc)) {
//add light data
- _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,1);
+ _bake_gi_probe_light(header, cells, local_data, leaves, leaf_count, lc, 1);
}
}
- SWAP(probe_data->dynamic.light_cache_changes,probe_data->dynamic.light_cache);
+ SWAP(probe_data->dynamic.light_cache_changes, probe_data->dynamic.light_cache);
//downscale to lower res levels
- _bake_gi_downscale_light(0,0,cells,header,local_data,probe_data->dynamic.propagate);
+ _bake_gi_downscale_light(0, 0, cells, header, local_data, probe_data->dynamic.propagate);
//plot result to 3D texture!
- if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
+ if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_UNCOMPRESSED) {
- for(int i=0;i<(int)header->cell_subdiv;i++) {
+ for (int i = 0; i < (int)header->cell_subdiv; i++) {
- int stage = header->cell_subdiv - i -1;
+ int stage = header->cell_subdiv - i - 1;
if (stage >= probe_data->dynamic.mipmaps_3d.size())
continue; //no mipmap for this one
- print_line("generating mipmap stage: "+itos(stage));
- int level_cell_count = probe_data->dynamic.level_cell_lists[ i ].size();
- const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[ i ].ptr();
+ print_line("generating mipmap stage: " + itos(stage));
+ int level_cell_count = probe_data->dynamic.level_cell_lists[i].size();
+ const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[i].ptr();
PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d[stage].write();
uint8_t *mipmapw = lw.ptr();
- uint32_t sizes[3]={header->width>>stage,header->height>>stage,header->depth>>stage};
+ uint32_t sizes[3] = { header->width >> stage, header->height >> stage, header->depth >> stage };
- for(int j=0;j<level_cell_count;j++) {
+ for (int j = 0; j < level_cell_count; j++) {
uint32_t idx = level_cells[j];
- uint32_t r = (uint32_t(local_data[idx].energy[0])/probe_data->dynamic.bake_dynamic_range)>>2;
- uint32_t g = (uint32_t(local_data[idx].energy[1])/probe_data->dynamic.bake_dynamic_range)>>2;
- uint32_t b = (uint32_t(local_data[idx].energy[2])/probe_data->dynamic.bake_dynamic_range)>>2;
- uint32_t a = (cells[idx].level_alpha>>8)&0xFF;
-
- uint32_t mm_ofs = sizes[0]*sizes[1]*(local_data[idx].pos[2]) + sizes[0]*(local_data[idx].pos[1]) + (local_data[idx].pos[0]);
- mm_ofs*=4; //for RGBA (4 bytes)
-
- mipmapw[mm_ofs+0]=uint8_t(CLAMP(r,0,255));
- mipmapw[mm_ofs+1]=uint8_t(CLAMP(g,0,255));
- mipmapw[mm_ofs+2]=uint8_t(CLAMP(b,0,255));
- mipmapw[mm_ofs+3]=uint8_t(CLAMP(a,0,255));
+ uint32_t r = (uint32_t(local_data[idx].energy[0]) / probe_data->dynamic.bake_dynamic_range) >> 2;
+ uint32_t g = (uint32_t(local_data[idx].energy[1]) / probe_data->dynamic.bake_dynamic_range) >> 2;
+ uint32_t b = (uint32_t(local_data[idx].energy[2]) / probe_data->dynamic.bake_dynamic_range) >> 2;
+ uint32_t a = (cells[idx].level_alpha >> 8) & 0xFF;
+ uint32_t mm_ofs = sizes[0] * sizes[1] * (local_data[idx].pos[2]) + sizes[0] * (local_data[idx].pos[1]) + (local_data[idx].pos[0]);
+ mm_ofs *= 4; //for RGBA (4 bytes)
+ mipmapw[mm_ofs + 0] = uint8_t(CLAMP(r, 0, 255));
+ mipmapw[mm_ofs + 1] = uint8_t(CLAMP(g, 0, 255));
+ mipmapw[mm_ofs + 2] = uint8_t(CLAMP(b, 0, 255));
+ mipmapw[mm_ofs + 3] = uint8_t(CLAMP(a, 0, 255));
}
}
- } else if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) {
-
+ } else if (probe_data->dynamic.compression == RasterizerStorage::GI_PROBE_S3TC) {
int mipmap_count = probe_data->dynamic.mipmaps_3d.size();
- for(int mmi=0;mmi<mipmap_count;mmi++) {
+ for (int mmi = 0; mmi < mipmap_count; mmi++) {
PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d[mmi].write();
int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size();
PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read();
- for(int i=0;i<block_count;i++) {
+ for (int i = 0; i < block_count; i++) {
- const InstanceGIProbeData::CompBlockS3TC& b = mmr[i];
+ const InstanceGIProbeData::CompBlockS3TC &b = mmr[i];
- uint8_t *blockptr = &mmw[b.offset*16];
- copymem(blockptr,b.alpha,8); //copy alpha part, which is precomputed
+ uint8_t *blockptr = &mmw[b.offset * 16];
+ copymem(blockptr, b.alpha, 8); //copy alpha part, which is precomputed
Vector3 colors[16];
- for(int j=0;j<b.source_count;j++) {
+ for (int j = 0; j < b.source_count; j++) {
- colors[j].x=(local_data[b.sources[j]].energy[0]/float(probe_data->dynamic.bake_dynamic_range))/1024.0;
- colors[j].y=(local_data[b.sources[j]].energy[1]/float(probe_data->dynamic.bake_dynamic_range))/1024.0;
- colors[j].z=(local_data[b.sources[j]].energy[2]/float(probe_data->dynamic.bake_dynamic_range))/1024.0;
+ colors[j].x = (local_data[b.sources[j]].energy[0] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
+ colors[j].y = (local_data[b.sources[j]].energy[1] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
+ colors[j].z = (local_data[b.sources[j]].energy[2] / float(probe_data->dynamic.bake_dynamic_range)) / 1024.0;
}
//super quick and dirty compression
//find 2 most futher apart
- float distance=0;
- Vector3 from,to;
+ float distance = 0;
+ Vector3 from, to;
- if (b.source_count==16) {
+ if (b.source_count == 16) {
//all cells are used so, find minmax between them
- int further_apart[2]={0,0};
- for(int j=0;j<b.source_count;j++) {
- for(int k=j+1;k<b.source_count;k++) {
+ int further_apart[2] = { 0, 0 };
+ for (int j = 0; j < b.source_count; j++) {
+ for (int k = j + 1; k < b.source_count; k++) {
float d = colors[j].distance_squared_to(colors[k]);
- if (d>distance) {
- distance=d;
- further_apart[0]=j;
- further_apart[1]=k;
+ if (d > distance) {
+ distance = d;
+ further_apart[0] = j;
+ further_apart[1] = k;
}
}
}
@@ -3154,154 +2951,138 @@ void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) {
//average all colors first
Vector3 average;
- for(int j=0;j<b.source_count;j++) {
- average+=colors[j];
+ for (int j = 0; j < b.source_count; j++) {
+ average += colors[j];
}
average.normalize();
//find max distance in normal from average
- for(int j=0;j<b.source_count;j++) {
+ for (int j = 0; j < b.source_count; j++) {
float d = average.dot(colors[j]);
- distance=MAX(d,distance);
+ distance = MAX(d, distance);
}
from = Vector3(); //from black
to = average * distance;
//find max distance
-
}
-
int indices[16];
- uint16_t color_0=0;
- color_0 = CLAMP(int(from.x*31),0,31)<<11;
- color_0 |= CLAMP(int(from.y*63),0,63)<<5;
- color_0 |= CLAMP(int(from.z*31),0,31);
+ uint16_t color_0 = 0;
+ color_0 = CLAMP(int(from.x * 31), 0, 31) << 11;
+ color_0 |= CLAMP(int(from.y * 63), 0, 63) << 5;
+ color_0 |= CLAMP(int(from.z * 31), 0, 31);
- uint16_t color_1=0;
- color_1 = CLAMP(int(to.x*31),0,31)<<11;
- color_1 |= CLAMP(int(to.y*63),0,63)<<5;
- color_1 |= CLAMP(int(to.z*31),0,31);
+ uint16_t color_1 = 0;
+ color_1 = CLAMP(int(to.x * 31), 0, 31) << 11;
+ color_1 |= CLAMP(int(to.y * 63), 0, 63) << 5;
+ color_1 |= CLAMP(int(to.z * 31), 0, 31);
if (color_1 > color_0) {
- SWAP(color_1,color_0);
- SWAP(from,to);
+ SWAP(color_1, color_0);
+ SWAP(from, to);
}
+ if (distance > 0) {
- if (distance>0) {
-
- Vector3 dir = (to-from).normalized();
+ Vector3 dir = (to - from).normalized();
+ for (int j = 0; j < b.source_count; j++) {
- for(int j=0;j<b.source_count;j++) {
-
- float d = (colors[j]-from).dot(dir) / distance;
- indices[j]=int(d*3+0.5);
-
- static const int index_swap[4]={0,3,1,2};
-
- indices[j]=index_swap[CLAMP(indices[j],0,3)];
+ float d = (colors[j] - from).dot(dir) / distance;
+ indices[j] = int(d * 3 + 0.5);
+ static const int index_swap[4] = { 0, 3, 1, 2 };
+ indices[j] = index_swap[CLAMP(indices[j], 0, 3)];
}
} else {
- for(int j=0;j<b.source_count;j++) {
- indices[j]=0;
+ for (int j = 0; j < b.source_count; j++) {
+ indices[j] = 0;
}
}
//by default, 1 is black, otherwise it will be overriden by source
- uint32_t index_block[16]={1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1 };
+ uint32_t index_block[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
- for(int j=0;j<b.source_count;j++) {
+ for (int j = 0; j < b.source_count; j++) {
- int x=local_data[b.sources[j]].pos[0]%4;
- int y=local_data[b.sources[j]].pos[1]%4;
+ int x = local_data[b.sources[j]].pos[0] % 4;
+ int y = local_data[b.sources[j]].pos[1] % 4;
- index_block[y*4+x]=indices[j];
+ index_block[y * 4 + x] = indices[j];
}
- uint32_t encode=0;
+ uint32_t encode = 0;
- for(int j=0;j<16;j++) {
- encode|=index_block[j]<<(j*2);
+ for (int j = 0; j < 16; j++) {
+ encode |= index_block[j] << (j * 2);
}
- blockptr[8]=color_0&0xFF;
- blockptr[9]=(color_0>>8)&0xFF;
- blockptr[10]=color_1&0xFF;
- blockptr[11]=(color_1>>8)&0xFF;
- blockptr[12]=encode&0xFF;
- blockptr[13]=(encode>>8)&0xFF;
- blockptr[14]=(encode>>16)&0xFF;
- blockptr[15]=(encode>>24)&0xFF;
-
+ blockptr[8] = color_0 & 0xFF;
+ blockptr[9] = (color_0 >> 8) & 0xFF;
+ blockptr[10] = color_1 & 0xFF;
+ blockptr[11] = (color_1 >> 8) & 0xFF;
+ blockptr[12] = encode & 0xFF;
+ blockptr[13] = (encode >> 8) & 0xFF;
+ blockptr[14] = (encode >> 16) & 0xFF;
+ blockptr[15] = (encode >> 24) & 0xFF;
}
-
-
}
-
}
-
//send back to main thread to update un little chunks
- probe_data->dynamic.updating_stage=GI_UPDATE_STAGE_UPLOADING;
-
+ probe_data->dynamic.updating_stage = GI_UPDATE_STAGE_UPLOADING;
}
bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) {
- InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data);
+ InstanceGIProbeData *probe_data = static_cast<InstanceGIProbeData *>(p_gi_probe->base_data);
probe_data->dynamic.light_cache_changes.clear();
- bool all_equal=true;
-
+ bool all_equal = true;
- for (List<Instance*>::Element *E=p_gi_probe->scenario->directional_lights.front();E;E=E->next()) {
+ for (List<Instance *>::Element *E = p_gi_probe->scenario->directional_lights.front(); E; E = E->next()) {
InstanceGIProbeData::LightCache lc;
- lc.type=VSG::storage->light_get_type(E->get()->base);
- lc.color=VSG::storage->light_get_color(E->get()->base);
- lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY);
- lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE);
- lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION);
- lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE);
- lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION);
+ lc.type = VSG::storage->light_get_type(E->get()->base);
+ lc.color = VSG::storage->light_get_color(E->get()->base);
+ lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY);
+ lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
+ lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
+ lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
+ lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
- if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) {
- all_equal=false;
+ if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
+ all_equal = false;
}
- probe_data->dynamic.light_cache_changes[E->get()->self]=lc;
-
+ probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
}
-
- for (Set<Instance*>::Element *E=probe_data->lights.front();E;E=E->next()) {
+ for (Set<Instance *>::Element *E = probe_data->lights.front(); E; E = E->next()) {
InstanceGIProbeData::LightCache lc;
- lc.type=VSG::storage->light_get_type(E->get()->base);
- lc.color=VSG::storage->light_get_color(E->get()->base);
- lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY);
- lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE);
- lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION);
- lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE);
- lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION);
+ lc.type = VSG::storage->light_get_type(E->get()->base);
+ lc.color = VSG::storage->light_get_color(E->get()->base);
+ lc.energy = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ENERGY);
+ lc.radius = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_RANGE);
+ lc.attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_ATTENUATION);
+ lc.spot_angle = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ANGLE);
+ lc.spot_attenuation = VSG::storage->light_get_param(E->get()->base, VS::LIGHT_PARAM_SPOT_ATTENUATION);
lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform;
- if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) {
- all_equal=false;
+ if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self] == lc)) {
+ all_equal = false;
}
- probe_data->dynamic.light_cache_changes[E->get()->self]=lc;
+ probe_data->dynamic.light_cache_changes[E->get()->self] = lc;
}
//lighting changed from after to before, must do some updating
- return !all_equal || probe_data->dynamic.light_cache_changes.size()!=probe_data->dynamic.light_cache.size();
-
+ return !all_equal || probe_data->dynamic.light_cache_changes.size() != probe_data->dynamic.light_cache.size();
}
void VisualServerScene::render_probes() {
@@ -3310,82 +3091,80 @@ void VisualServerScene::render_probes() {
SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first();
- bool busy=false;
+ bool busy = false;
- while(ref_probe) {
+ while (ref_probe) {
- SelfList<InstanceReflectionProbeData> *next=ref_probe->next();
+ SelfList<InstanceReflectionProbeData> *next = ref_probe->next();
RID base = ref_probe->self()->owner->base;
- switch(VSG::storage->reflection_probe_get_update_mode(base)) {
+ switch (VSG::storage->reflection_probe_get_update_mode(base)) {
case VS::REFLECTION_PROBE_UPDATE_ONCE: {
if (busy) //already rendering something
break;
- bool done = _render_reflection_probe_step(ref_probe->self()->owner,ref_probe->self()->render_step);
+ bool done = _render_reflection_probe_step(ref_probe->self()->owner, ref_probe->self()->render_step);
if (done) {
reflection_probe_render_list.remove(ref_probe);
} else {
ref_probe->self()->render_step++;
}
- busy=true; //do not render another one of this kind
+ busy = true; //do not render another one of this kind
} break;
case VS::REFLECTION_PROBE_UPDATE_ALWAYS: {
- int step=0;
- bool done=false;
- while(!done) {
- done = _render_reflection_probe_step(ref_probe->self()->owner,step);
+ int step = 0;
+ bool done = false;
+ while (!done) {
+ done = _render_reflection_probe_step(ref_probe->self()->owner, step);
step++;
}
reflection_probe_render_list.remove(ref_probe);
} break;
-
}
- ref_probe=next;
+ ref_probe = next;
}
/* GI PROBES */
SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first();
- while(gi_probe) {
+ while (gi_probe) {
- SelfList<InstanceGIProbeData> *next=gi_probe->next();
+ SelfList<InstanceGIProbeData> *next = gi_probe->next();
InstanceGIProbeData *probe = gi_probe->self();
Instance *instance_probe = probe->owner;
//check if probe must be setup, but don't do if on the lighting thread
- bool force_lighting=false;
+ bool force_lighting = false;
- if (probe->invalid || (probe->dynamic.updating_stage==GI_UPDATE_STAGE_CHECK && probe->base_version!=VSG::storage->gi_probe_get_version(instance_probe->base))) {
+ if (probe->invalid || (probe->dynamic.updating_stage == GI_UPDATE_STAGE_CHECK && probe->base_version != VSG::storage->gi_probe_get_version(instance_probe->base))) {
_setup_gi_probe(instance_probe);
- force_lighting=true;
+ force_lighting = true;
}
float propagate = VSG::storage->gi_probe_get_propagation(instance_probe->base);
- if (probe->dynamic.propagate!=propagate) {
- probe->dynamic.propagate=propagate;
- force_lighting=true;
+ if (probe->dynamic.propagate != propagate) {
+ probe->dynamic.propagate = propagate;
+ force_lighting = true;
}
+ if (probe->invalid == false && probe->dynamic.enabled) {
- if (probe->invalid==false && probe->dynamic.enabled) {
-
- switch(probe->dynamic.updating_stage) {
+ switch (probe->dynamic.updating_stage) {
case GI_UPDATE_STAGE_CHECK: {
if (_check_gi_probe(instance_probe) || force_lighting) {
//send to lighting thread
- probe->dynamic.updating_stage=GI_UPDATE_STAGE_LIGHTING;
+ probe->dynamic.updating_stage = GI_UPDATE_STAGE_LIGHTING;
#ifndef NO_THREADS
probe_bake_mutex->lock();
@@ -3397,7 +3176,6 @@ void VisualServerScene::render_probes() {
_bake_gi_probe(instance_probe);
#endif
-
}
} break;
case GI_UPDATE_STAGE_LIGHTING: {
@@ -3408,29 +3186,23 @@ void VisualServerScene::render_probes() {
uint64_t us = OS::get_singleton()->get_ticks_usec();
- for(int i=0;i<(int)probe->dynamic.mipmaps_3d.size();i++) {
+ for (int i = 0; i < (int)probe->dynamic.mipmaps_3d.size(); i++) {
int mmsize = probe->dynamic.mipmaps_3d[i].size();
PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read();
- VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data,0,probe->dynamic.grid_size[2]>>i,i,r.ptr());
+ VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data, 0, probe->dynamic.grid_size[2] >> i, i, r.ptr());
}
-
- probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK;
+ probe->dynamic.updating_stage = GI_UPDATE_STAGE_CHECK;
//print_line("UPLOAD TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0));
} break;
-
}
}
//_update_gi_probe(gi_probe->self()->owner);
-
- gi_probe=next;
+ gi_probe = next;
}
-
-
-
}
void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
@@ -3438,143 +3210,131 @@ void VisualServerScene::_update_dirty_instance(Instance *p_instance) {
if (p_instance->update_aabb)
_update_instance_aabb(p_instance);
-
if (p_instance->update_materials) {
- if (p_instance->base_type==VS::INSTANCE_MESH) {
+ if (p_instance->base_type == VS::INSTANCE_MESH) {
//remove materials no longer used and un-own them
int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base);
- for(int i=p_instance->materials.size()-1;i>=new_mat_count;i--) {
+ for (int i = p_instance->materials.size() - 1; i >= new_mat_count; i--) {
if (p_instance->materials[i].is_valid()) {
- VSG::storage->material_remove_instance_owner(p_instance->materials[i],p_instance);
+ VSG::storage->material_remove_instance_owner(p_instance->materials[i], p_instance);
}
}
p_instance->materials.resize(new_mat_count);
int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base);
- if (new_blend_shape_count!=p_instance->blend_values.size()) {
+ if (new_blend_shape_count != p_instance->blend_values.size()) {
p_instance->blend_values.resize(new_blend_shape_count);
- for(int i=0;i<new_blend_shape_count;i++) {
- p_instance->blend_values[i]=0;
+ for (int i = 0; i < new_blend_shape_count; i++) {
+ p_instance->blend_values[i] = 0;
}
}
}
- if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) {
+ if ((1 << p_instance->base_type) & VS::INSTANCE_GEOMETRY_MASK) {
- InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data);
+ InstanceGeometryData *geom = static_cast<InstanceGeometryData *>(p_instance->base_data);
- bool can_cast_shadows=true;
+ bool can_cast_shadows = true;
- if (p_instance->cast_shadows==VS::SHADOW_CASTING_SETTING_OFF) {
- can_cast_shadows=false;
+ if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_OFF) {
+ can_cast_shadows = false;
} else if (p_instance->material_override.is_valid()) {
- can_cast_shadows=VSG::storage->material_casts_shadows(p_instance->material_override);
+ can_cast_shadows = VSG::storage->material_casts_shadows(p_instance->material_override);
} else {
-
-
- if (p_instance->base_type==VS::INSTANCE_MESH) {
- RID mesh=p_instance->base;
+ if (p_instance->base_type == VS::INSTANCE_MESH) {
+ RID mesh = p_instance->base;
if (mesh.is_valid()) {
- bool cast_shadows=false;
-
- for(int i=0;i<p_instance->materials.size();i++) {
+ bool cast_shadows = false;
+ for (int i = 0; i < p_instance->materials.size(); i++) {
- RID mat = p_instance->materials[i].is_valid()?p_instance->materials[i]:VSG::storage->mesh_surface_get_material(mesh,i);
+ RID mat = p_instance->materials[i].is_valid() ? p_instance->materials[i] : VSG::storage->mesh_surface_get_material(mesh, i);
if (!mat.is_valid()) {
- cast_shadows=true;
+ cast_shadows = true;
break;
}
if (VSG::storage->material_casts_shadows(mat)) {
- cast_shadows=true;
+ cast_shadows = true;
break;
}
}
if (!cast_shadows) {
- can_cast_shadows=false;
+ can_cast_shadows = false;
}
}
- } else if (p_instance->base_type==VS::INSTANCE_MULTIMESH) {
+ } else if (p_instance->base_type == VS::INSTANCE_MULTIMESH) {
RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base);
if (mesh.is_valid()) {
- bool cast_shadows=false;
+ bool cast_shadows = false;
int sc = VSG::storage->mesh_get_surface_count(mesh);
- for(int i=0;i<sc;i++) {
+ for (int i = 0; i < sc; i++) {
- RID mat =VSG::storage->mesh_surface_get_material(mesh,i);
+ RID mat = VSG::storage->mesh_surface_get_material(mesh, i);
if (!mat.is_valid()) {
- cast_shadows=true;
+ cast_shadows = true;
break;
}
if (VSG::storage->material_casts_shadows(mat)) {
- cast_shadows=true;
+ cast_shadows = true;
break;
}
-
}
if (!cast_shadows) {
- can_cast_shadows=false;
+ can_cast_shadows = false;
}
}
- } else if (p_instance->base_type==VS::INSTANCE_IMMEDIATE) {
+ } else if (p_instance->base_type == VS::INSTANCE_IMMEDIATE) {
RID mat = VSG::storage->immediate_get_material(p_instance->base);
if (!mat.is_valid() || VSG::storage->material_casts_shadows(mat)) {
- can_cast_shadows=true;
+ can_cast_shadows = true;
} else {
- can_cast_shadows=false;
+ can_cast_shadows = false;
}
-
-
}
-
-
-
}
- if (can_cast_shadows!=geom->can_cast_shadows) {
+ if (can_cast_shadows != geom->can_cast_shadows) {
//ability to cast shadows change, let lights now
- for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) {
- InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data);
- light->shadow_dirty=true;
+ for (List<Instance *>::Element *E = geom->lighting.front(); E; E = E->next()) {
+ InstanceLightData *light = static_cast<InstanceLightData *>(E->get()->base_data);
+ light->shadow_dirty = true;
}
- geom->can_cast_shadows=can_cast_shadows;
+ geom->can_cast_shadows = can_cast_shadows;
}
}
-
}
_update_instance(p_instance);
- p_instance->update_aabb=false;
- p_instance->update_materials=false;
+ p_instance->update_aabb = false;
+ p_instance->update_materials = false;
- _instance_update_list.remove( &p_instance->update_item );
+ _instance_update_list.remove(&p_instance->update_item);
}
-
void VisualServerScene::update_dirty_instances() {
VSG::storage->update_dirty_resources();
- while(_instance_update_list.first()) {
+ while (_instance_update_list.first()) {
- _update_dirty_instance( _instance_update_list.first()->self() );
+ _update_dirty_instance(_instance_update_list.first()->self());
}
}
@@ -3582,17 +3342,17 @@ bool VisualServerScene::free(RID p_rid) {
if (camera_owner.owns(p_rid)) {
- Camera *camera = camera_owner.get( p_rid );
+ Camera *camera = camera_owner.get(p_rid);
camera_owner.free(p_rid);
memdelete(camera);
} else if (scenario_owner.owns(p_rid)) {
- Scenario *scenario = scenario_owner.get( p_rid );
+ Scenario *scenario = scenario_owner.get(p_rid);
- while(scenario->instances.first()) {
- instance_set_scenario(scenario->instances.first()->self()->self,RID());
+ while (scenario->instances.first()) {
+ instance_set_scenario(scenario->instances.first()->self()->self, RID());
}
VSG::scene_render->free(scenario->reflection_probe_shadow_atlas);
VSG::scene_render->free(scenario->reflection_atlas);
@@ -3606,11 +3366,11 @@ bool VisualServerScene::free(RID p_rid) {
Instance *instance = instance_owner.get(p_rid);
- instance_set_room(p_rid,RID());
- instance_set_scenario(p_rid,RID());
- instance_set_base(p_rid,RID());
- instance_geometry_set_material_override(p_rid,RID());
- instance_attach_skeleton(p_rid,RID());
+ instance_set_room(p_rid, RID());
+ instance_set_scenario(p_rid, RID());
+ instance_set_base(p_rid, RID());
+ instance_geometry_set_material_override(p_rid, RID());
+ instance_attach_skeleton(p_rid, RID());
update_dirty_instances(); //in case something changed this
@@ -3620,38 +3380,32 @@ bool VisualServerScene::free(RID p_rid) {
return false;
}
-
return true;
}
-VisualServerScene *VisualServerScene::singleton=NULL;
-
+VisualServerScene *VisualServerScene::singleton = NULL;
VisualServerScene::VisualServerScene() {
#ifndef NO_THREADS
probe_bake_sem = Semaphore::create();
probe_bake_mutex = Mutex::create();
- probe_bake_thread = Thread::create(_gi_probe_bake_threads,this);
- probe_bake_thread_exit=false;
+ probe_bake_thread = Thread::create(_gi_probe_bake_threads, this);
+ probe_bake_thread_exit = false;
#endif
-
- render_pass=1;
- singleton=this;
-
+ render_pass = 1;
+ singleton = this;
}
VisualServerScene::~VisualServerScene() {
#ifndef NO_THREADS
- probe_bake_thread_exit=true;
+ probe_bake_thread_exit = true;
Thread::wait_to_finish(probe_bake_thread);
memdelete(probe_bake_thread);
memdelete(probe_bake_sem);
memdelete(probe_bake_mutex);
#endif
-
-
}
diff --git a/servers/visual/visual_server_scene.h b/servers/visual/visual_server_scene.h
index 01ad400b80..b02e6c820b 100644
--- a/servers/visual/visual_server_scene.h
+++ b/servers/visual/visual_server_scene.h
@@ -31,30 +31,27 @@
#include "servers/visual/rasterizer.h"
-#include "geometry.h"
#include "allocators.h"
+#include "geometry.h"
#include "octree.h"
-#include "self_list.h"
-#include "os/thread.h"
#include "os/semaphore.h"
#include "os/semaphore.h"
+#include "os/thread.h"
+#include "self_list.h"
class VisualServerScene {
public:
-
-
enum {
- MAX_INSTANCE_CULL=65536,
- MAX_LIGHTS_CULLED=4096,
- MAX_REFLECTION_PROBES_CULLED=4096,
- MAX_ROOM_CULL=32,
- MAX_EXTERIOR_PORTALS=128,
+ MAX_INSTANCE_CULL = 65536,
+ MAX_LIGHTS_CULLED = 4096,
+ MAX_REFLECTION_PROBES_CULLED = 4096,
+ MAX_ROOM_CULL = 32,
+ MAX_EXTERIOR_PORTALS = 128,
};
uint64_t render_pass;
-
static VisualServerScene *singleton;
#if 0
struct Portal {
@@ -99,10 +96,9 @@ public:
#endif
-
/* CAMERA API */
- struct Camera : public RID_Data {
+ struct Camera : public RID_Data {
enum Type {
PERSPECTIVE,
@@ -110,7 +106,7 @@ public:
};
Type type;
float fov;
- float znear,zfar;
+ float znear, zfar;
float size;
uint32_t visible_layers;
bool vaspect;
@@ -120,26 +116,25 @@ public:
Camera() {
- visible_layers=0xFFFFFFFF;
- fov=60;
- type=PERSPECTIVE;
- znear=0.1; zfar=100;
- size=1.0;
- vaspect=false;
-
+ visible_layers = 0xFFFFFFFF;
+ fov = 60;
+ type = PERSPECTIVE;
+ znear = 0.1;
+ zfar = 100;
+ size = 1.0;
+ vaspect = false;
}
};
mutable RID_Owner<Camera> camera_owner;
virtual RID camera_create();
- virtual void camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far);
- virtual void camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far);
- virtual void camera_set_transform(RID p_camera,const Transform& p_transform);
- virtual void camera_set_cull_mask(RID p_camera,uint32_t p_layers);
- virtual void camera_set_environment(RID p_camera,RID p_env);
- virtual void camera_set_use_vertical_aspect(RID p_camera,bool p_enable);
-
+ virtual void camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far);
+ virtual void camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far);
+ virtual void camera_set_transform(RID p_camera, const Transform &p_transform);
+ virtual void camera_set_cull_mask(RID p_camera, uint32_t p_layers);
+ virtual void camera_set_environment(RID p_camera, RID p_env);
+ virtual void camera_set_use_vertical_aspect(RID p_camera, bool p_enable);
/*
@@ -173,56 +168,48 @@ public:
};
*/
-
-
/* SCENARIO API */
struct Instance;
- struct Scenario : RID_Data {
-
+ struct Scenario : RID_Data {
VS::ScenarioDebugMode debug;
RID self;
// well wtf, balloon allocator is slower?
- Octree<Instance,true> octree;
+ Octree<Instance, true> octree;
- List<Instance*> directional_lights;
+ List<Instance *> directional_lights;
RID environment;
RID fallback_environment;
RID reflection_probe_shadow_atlas;
RID reflection_atlas;
-
SelfList<Instance>::List instances;
- Scenario() { debug=VS::SCENARIO_DEBUG_DISABLED; }
+ Scenario() { debug = VS::SCENARIO_DEBUG_DISABLED; }
};
mutable RID_Owner<Scenario> scenario_owner;
- static void* _instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int);
- static void _instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void*);
+ static void *_instance_pair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int);
+ static void _instance_unpair(void *p_self, OctreeElementID, Instance *p_A, int, OctreeElementID, Instance *p_B, int, void *);
virtual RID scenario_create();
- virtual void scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode);
+ virtual void scenario_set_debug(RID p_scenario, VS::ScenarioDebugMode p_debug_mode);
virtual void scenario_set_environment(RID p_scenario, RID p_environment);
virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment);
- virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv);
-
+ virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv);
/* INSTANCING API */
struct InstanceBaseData {
-
virtual ~InstanceBaseData() {}
};
-
-
struct Instance : RasterizerScene::InstanceBase {
RID self;
@@ -237,7 +224,6 @@ public:
SelfList<Instance> update_item;
-
Rect3 aabb;
Rect3 transformed_aabb;
float extra_margin;
@@ -262,107 +248,99 @@ public:
virtual void base_removed() {
- singleton->instance_set_base(self,RID());
+ singleton->instance_set_base(self, RID());
}
virtual void base_changed() {
- singleton->_instance_queue_update(this,true,true);
+ singleton->_instance_queue_update(this, true, true);
}
virtual void base_material_changed() {
- singleton->_instance_queue_update(this,false,true);
+ singleton->_instance_queue_update(this, false, true);
}
+ Instance()
+ : scenario_item(this), update_item(this), room_item(this) {
- Instance() : scenario_item(this), update_item(this), room_item(this) {
-
- octree_id=0;
- scenario=NULL;
-
-
- update_aabb=false;
- update_materials=false;
+ octree_id = 0;
+ scenario = NULL;
- extra_margin=0;
+ update_aabb = false;
+ update_materials = false;
+ extra_margin = 0;
- object_ID=0;
- visible=true;
+ object_ID = 0;
+ visible = true;
- lod_begin=0;
- lod_end=0;
- lod_begin_hysteresis=0;
- lod_end_hysteresis=0;
+ lod_begin = 0;
+ lod_end = 0;
+ lod_begin_hysteresis = 0;
+ lod_end_hysteresis = 0;
- room=NULL;
- visible_in_all_rooms=false;
-
-
-
- last_render_pass=0;
- last_frame_pass=0;
- version=1;
- base_data=NULL;
+ room = NULL;
+ visible_in_all_rooms = false;
+ last_render_pass = 0;
+ last_frame_pass = 0;
+ version = 1;
+ base_data = NULL;
}
~Instance() {
if (base_data)
memdelete(base_data);
-
}
};
SelfList<Instance>::List _instance_update_list;
- void _instance_queue_update(Instance *p_instance,bool p_update_aabb,bool p_update_materials=false);
-
+ void _instance_queue_update(Instance *p_instance, bool p_update_aabb, bool p_update_materials = false);
struct InstanceGeometryData : public InstanceBaseData {
- List<Instance*> lighting;
+ List<Instance *> lighting;
bool lighting_dirty;
bool can_cast_shadows;
- List<Instance*> reflection_probes;
+ List<Instance *> reflection_probes;
bool reflection_dirty;
- List<Instance*> gi_probes;
+ List<Instance *> gi_probes;
bool gi_probes_dirty;
InstanceGeometryData() {
- lighting_dirty=false;
- reflection_dirty=true;
- can_cast_shadows=true;
- gi_probes_dirty=true;
+ lighting_dirty = false;
+ reflection_dirty = true;
+ can_cast_shadows = true;
+ gi_probes_dirty = true;
}
};
struct InstanceReflectionProbeData : public InstanceBaseData {
-
Instance *owner;
struct PairInfo {
- List<Instance*>::Element *L; //reflection iterator in geometry
+ List<Instance *>::Element *L; //reflection iterator in geometry
Instance *geometry;
};
List<PairInfo> geometries;
-
RID instance;
bool reflection_dirty;
SelfList<InstanceReflectionProbeData> update_list;
int render_step;
- InstanceReflectionProbeData() : update_list(this) {
+ InstanceReflectionProbeData()
+ : update_list(this) {
- reflection_dirty=true;
- render_step=-1;
+ reflection_dirty = true;
+ render_step = -1;
}
};
@@ -371,13 +349,13 @@ public:
struct InstanceLightData : public InstanceBaseData {
struct PairInfo {
- List<Instance*>::Element *L; //light iterator in geometry
+ List<Instance *>::Element *L; //light iterator in geometry
Instance *geometry;
};
RID instance;
uint64_t last_version;
- List<Instance*>::Element *D; // directional light in scenario
+ List<Instance *>::Element *D; // directional light in scenario
bool shadow_dirty;
@@ -387,26 +365,25 @@ public:
InstanceLightData() {
- shadow_dirty=true;
- D=NULL;
- last_version=0;
- baked_light=NULL;
+ shadow_dirty = true;
+ D = NULL;
+ last_version = 0;
+ baked_light = NULL;
}
};
struct InstanceGIProbeData : public InstanceBaseData {
-
Instance *owner;
struct PairInfo {
- List<Instance*>::Element *L; //gi probe iterator in geometry
+ List<Instance *>::Element *L; //gi probe iterator in geometry
Instance *geometry;
};
List<PairInfo> geometries;
- Set<Instance*> lights;
+ Set<Instance *> lights;
struct LightCache {
@@ -419,29 +396,27 @@ public:
float spot_angle;
float spot_attenuation;
- bool operator==(const LightCache& p_cache) {
+ bool operator==(const LightCache &p_cache) {
- return (type==p_cache.type &&
- transform==p_cache.transform &&
- color==p_cache.color &&
- energy==p_cache.energy &&
- radius==p_cache.radius &&
- attenuation==p_cache.attenuation &&
- spot_angle==p_cache.spot_angle &&
- spot_attenuation==p_cache.spot_attenuation);
+ return (type == p_cache.type &&
+ transform == p_cache.transform &&
+ color == p_cache.color &&
+ energy == p_cache.energy &&
+ radius == p_cache.radius &&
+ attenuation == p_cache.attenuation &&
+ spot_angle == p_cache.spot_angle &&
+ spot_attenuation == p_cache.spot_attenuation);
}
LightCache() {
- type=VS::LIGHT_DIRECTIONAL;
- energy=1.0;
- radius=1.0;
- attenuation=1.0;
- spot_angle=1.0;
- spot_attenuation=1.0;
-
+ type = VS::LIGHT_DIRECTIONAL;
+ energy = 1.0;
+ radius = 1.0;
+ attenuation = 1.0;
+ spot_angle = 1.0;
+ spot_attenuation = 1.0;
}
-
};
struct LocalData {
@@ -456,11 +431,10 @@ public:
uint8_t alpha[8]; //alpha block is pre-computed
};
-
struct Dynamic {
- Map<RID,LightCache> light_cache;
- Map<RID,LightCache> light_cache_changes;
+ Map<RID, LightCache> light_cache;
+ Map<RID, LightCache> light_cache_changes;
PoolVector<int> light_data;
PoolVector<LocalData> local_data;
Vector<Vector<uint32_t> > level_cell_lists;
@@ -469,8 +443,8 @@ public:
int bake_dynamic_range;
RasterizerStorage::GIProbeCompression compression;
- Vector< PoolVector<uint8_t> > mipmaps_3d;
- Vector< PoolVector<CompBlockS3TC> > mipmaps_s3tc; //for s3tc
+ Vector<PoolVector<uint8_t> > mipmaps_3d;
+ Vector<PoolVector<CompBlockS3TC> > mipmaps_s3tc; //for s3tc
int updating_stage;
float propagate;
@@ -481,26 +455,22 @@ public:
} dynamic;
-
RID probe_instance;
-
bool invalid;
uint32_t base_version;
SelfList<InstanceGIProbeData> update_element;
- InstanceGIProbeData() : update_element(this) {
- invalid=true;
- base_version=0;
+ InstanceGIProbeData()
+ : update_element(this) {
+ invalid = true;
+ base_version = 0;
}
-
};
-
SelfList<InstanceGIProbeData>::List gi_probe_update_list;
-
Instance *instance_cull_result[MAX_INSTANCE_CULL];
Instance *instance_shadow_cull_result[MAX_INSTANCE_CULL]; //used for generating shadowmaps
Instance *light_cull_result[MAX_LIGHTS_CULLED];
@@ -509,53 +479,47 @@ public:
RID reflection_probe_instance_cull_result[MAX_REFLECTION_PROBES_CULLED];
int reflection_probe_cull_count;
-
RID_Owner<Instance> instance_owner;
- // from can be mesh, light, area and portal so far.
+ // from can be mesh, light, area and portal so far.
virtual RID instance_create(); // from can be mesh, light, poly, area and portal so far.
virtual void instance_set_base(RID p_instance, RID p_base); // from can be mesh, light, poly, area and portal so far.
virtual void instance_set_scenario(RID p_instance, RID p_scenario); // from can be mesh, light, poly, area and portal so far.
virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask);
- virtual void instance_set_transform(RID p_instance, const Transform& p_transform);
- virtual void instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID);
- virtual void instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight);
- virtual void instance_set_surface_material(RID p_instance,int p_surface, RID p_material);
- virtual void instance_set_visible(RID p_instance,bool p_visible);
-
+ virtual void instance_set_transform(RID p_instance, const Transform &p_transform);
+ virtual void instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID);
+ virtual void instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight);
+ virtual void instance_set_surface_material(RID p_instance, int p_surface, RID p_material);
+ virtual void instance_set_visible(RID p_instance, bool p_visible);
- virtual void instance_attach_skeleton(RID p_instance,RID p_skeleton);
- virtual void instance_set_exterior( RID p_instance, bool p_enabled );
- virtual void instance_set_room( RID p_instance, RID p_room );
-
- virtual void instance_set_extra_visibility_margin( RID p_instance, real_t p_margin );
+ virtual void instance_attach_skeleton(RID p_instance, RID p_skeleton);
+ virtual void instance_set_exterior(RID p_instance, bool p_enabled);
+ virtual void instance_set_room(RID p_instance, RID p_room);
+ virtual void instance_set_extra_visibility_margin(RID p_instance, real_t p_margin);
// don't use these in a game!
- virtual Vector<ObjectID> instances_cull_aabb(const Rect3& p_aabb, RID p_scenario=RID()) const;
- virtual Vector<ObjectID> instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario=RID()) const;
- virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario=RID()) const;
-
+ virtual Vector<ObjectID> instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario = RID()) const;
+ virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const;
+ virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const;
- virtual void instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled);
+ virtual void instance_geometry_set_flag(RID p_instance, VS::InstanceFlags p_flags, bool p_enabled);
virtual void instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting);
virtual void instance_geometry_set_material_override(RID p_instance, RID p_material);
-
- virtual void instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin);
- virtual void instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance);
-
+ virtual void instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin);
+ virtual void instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance);
_FORCE_INLINE_ void _update_instance(Instance *p_instance);
_FORCE_INLINE_ void _update_instance_aabb(Instance *p_instance);
_FORCE_INLINE_ void _update_dirty_instance(Instance *p_instance);
- _FORCE_INLINE_ void _light_instance_update_shadow(Instance *p_instance,const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario* p_scenario);
+ _FORCE_INLINE_ void _light_instance_update_shadow(Instance *p_instance, const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_shadow_atlas, Scenario *p_scenario);
- void _render_scene(const Transform p_cam_transform, const CameraMatrix& p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass);
+ void _render_scene(const Transform p_cam_transform, const CameraMatrix &p_cam_projection, bool p_cam_orthogonal, RID p_force_environment, uint32_t p_visible_layers, RID p_scenario, RID p_shadow_atlas, RID p_reflection_probe, int p_reflection_probe_pass);
- void render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas);
+ void render_camera(RID p_camera, RID p_scenario, Size2 p_viewport_size, RID p_shadow_atlas);
void update_dirty_instances();
//probes
@@ -570,7 +534,6 @@ public:
uint32_t leaf_cell_count;
};
-
struct GIProbeDataCell {
uint32_t children[8];
@@ -587,27 +550,26 @@ public:
};
void _gi_probe_bake_thread();
- static void _gi_probe_bake_threads(void*);
+ static void _gi_probe_bake_threads(void *);
volatile bool probe_bake_thread_exit;
Thread *probe_bake_thread;
Semaphore *probe_bake_sem;
Mutex *probe_bake_mutex;
- List<Instance*> probe_bake_list;
+ List<Instance *> probe_bake_list;
- bool _render_reflection_probe_step(Instance* p_instance,int p_step);
- void _gi_probe_fill_local_data(int p_idx,int p_level,int p_x,int p_y,int p_z,const GIProbeDataCell* p_cell,const GIProbeDataHeader *p_header,InstanceGIProbeData::LocalData *p_local_data,Vector<uint32_t> *prev_cell);
+ bool _render_reflection_probe_step(Instance *p_instance, int p_step);
+ void _gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell *p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell);
- _FORCE_INLINE_ uint32_t _gi_bake_find_cell(const GIProbeDataCell *cells,int x,int y, int z,int p_cell_subdiv);
- void _bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell* p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate);
- void _bake_gi_probe_light(const GIProbeDataHeader *header,const GIProbeDataCell *cells,InstanceGIProbeData::LocalData *local_data,const uint32_t *leaves,int p_leaf_count, const InstanceGIProbeData::LightCache& light_cache,int p_sign);
+ _FORCE_INLINE_ uint32_t _gi_bake_find_cell(const GIProbeDataCell *cells, int x, int y, int z, int p_cell_subdiv);
+ void _bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell *p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, float p_propagate);
+ void _bake_gi_probe_light(const GIProbeDataHeader *header, const GIProbeDataCell *cells, InstanceGIProbeData::LocalData *local_data, const uint32_t *leaves, int p_leaf_count, const InstanceGIProbeData::LightCache &light_cache, int p_sign);
void _bake_gi_probe(Instance *p_probe);
bool _check_gi_probe(Instance *p_gi_probe);
void _setup_gi_probe(Instance *p_instance);
void render_probes();
-
bool free(RID p_rid);
VisualServerScene();
diff --git a/servers/visual/visual_server_viewport.cpp b/servers/visual/visual_server_viewport.cpp
index a88fb69e93..7b8a725c5a 100644
--- a/servers/visual/visual_server_viewport.cpp
+++ b/servers/visual/visual_server_viewport.cpp
@@ -27,16 +27,14 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "visual_server_viewport.h"
-#include "visual_server_global.h"
+#include "global_config.h"
#include "visual_server_canvas.h"
+#include "visual_server_global.h"
#include "visual_server_scene.h"
-#include "global_config.h"
-
-
void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
- /* Camera should always be BEFORE any other 3D */
+/* Camera should always be BEFORE any other 3D */
#if 0
bool scenario_draw_canvas_bg=false;
int scenario_canvas_max_layer=0;
@@ -82,126 +80,117 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
}
#endif
- if (p_viewport->clear_mode!=VS::VIEWPORT_CLEAR_NEVER) {
+ if (p_viewport->clear_mode != VS::VIEWPORT_CLEAR_NEVER) {
VSG::rasterizer->clear_render_target(clear_color);
- if (p_viewport->clear_mode==VS::VIEWPORT_CLEAR_ONLY_NEXT_FRAME) {
- p_viewport->clear_mode=VS::VIEWPORT_CLEAR_NEVER;
+ if (p_viewport->clear_mode == VS::VIEWPORT_CLEAR_ONLY_NEXT_FRAME) {
+ p_viewport->clear_mode = VS::VIEWPORT_CLEAR_NEVER;
}
}
-
if (!p_viewport->disable_3d && p_viewport->camera.is_valid()) {
- VSG::scene->render_camera(p_viewport->camera,p_viewport->scenario,p_viewport->size,p_viewport->shadow_atlas);
+ VSG::scene->render_camera(p_viewport->camera, p_viewport->scenario, p_viewport->size, p_viewport->shadow_atlas);
}
if (!p_viewport->hide_canvas) {
- int i=0;
+ int i = 0;
- Map<Viewport::CanvasKey,Viewport::CanvasData*> canvas_map;
+ Map<Viewport::CanvasKey, Viewport::CanvasData *> canvas_map;
- Rect2 clip_rect(0,0,p_viewport->size.x,p_viewport->size.y);
- RasterizerCanvas::Light *lights=NULL;
- RasterizerCanvas::Light *lights_with_shadow=NULL;
- RasterizerCanvas::Light *lights_with_mask=NULL;
+ Rect2 clip_rect(0, 0, p_viewport->size.x, p_viewport->size.y);
+ RasterizerCanvas::Light *lights = NULL;
+ RasterizerCanvas::Light *lights_with_shadow = NULL;
+ RasterizerCanvas::Light *lights_with_mask = NULL;
Rect2 shadow_rect;
- int light_count=0;
+ int light_count = 0;
- for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) {
+ for (Map<RID, Viewport::CanvasData>::Element *E = p_viewport->canvas_map.front(); E; E = E->next()) {
Transform2D xf = p_viewport->global_transform * E->get().transform;
- VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas);
+ VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get().canvas);
//find lights in canvas
+ for (Set<RasterizerCanvas::Light *>::Element *F = canvas->lights.front(); F; F = F->next()) {
- for(Set<RasterizerCanvas::Light*>::Element *F=canvas->lights.front();F;F=F->next()) {
-
-
- RasterizerCanvas::Light* cl=F->get();
+ RasterizerCanvas::Light *cl = F->get();
if (cl->enabled && cl->texture.is_valid()) {
//not super efficient..
- Size2 tsize(VSG::storage->texture_get_width(cl->texture),VSG::storage->texture_get_height(cl->texture));
- tsize*=cl->scale;
+ Size2 tsize(VSG::storage->texture_get_width(cl->texture), VSG::storage->texture_get_height(cl->texture));
+ tsize *= cl->scale;
- Vector2 offset=tsize/2.0;
- cl->rect_cache=Rect2(-offset+cl->texture_offset,tsize);
- cl->xform_cache=xf * cl->xform;
+ Vector2 offset = tsize / 2.0;
+ cl->rect_cache = Rect2(-offset + cl->texture_offset, tsize);
+ cl->xform_cache = xf * cl->xform;
+ if (clip_rect.intersects_transformed(cl->xform_cache, cl->rect_cache)) {
- if (clip_rect.intersects_transformed(cl->xform_cache,cl->rect_cache)) {
-
- cl->filter_next_ptr=lights;
- lights=cl;
- cl->texture_cache=NULL;
+ cl->filter_next_ptr = lights;
+ lights = cl;
+ cl->texture_cache = NULL;
Transform2D scale;
scale.scale(cl->rect_cache.size);
- scale.elements[2]=cl->rect_cache.pos;
+ scale.elements[2] = cl->rect_cache.pos;
cl->light_shader_xform = (cl->xform_cache * scale).affine_inverse();
- cl->light_shader_pos=cl->xform_cache[2];
+ cl->light_shader_pos = cl->xform_cache[2];
if (cl->shadow_buffer.is_valid()) {
- cl->shadows_next_ptr=lights_with_shadow;
- if (lights_with_shadow==NULL) {
+ cl->shadows_next_ptr = lights_with_shadow;
+ if (lights_with_shadow == NULL) {
shadow_rect = cl->xform_cache.xform(cl->rect_cache);
} else {
- shadow_rect=shadow_rect.merge( cl->xform_cache.xform(cl->rect_cache) );
+ shadow_rect = shadow_rect.merge(cl->xform_cache.xform(cl->rect_cache));
}
- lights_with_shadow=cl;
- cl->radius_cache=cl->rect_cache.size.length();
-
+ lights_with_shadow = cl;
+ cl->radius_cache = cl->rect_cache.size.length();
}
- if (cl->mode==VS::CANVAS_LIGHT_MODE_MASK) {
- cl->mask_next_ptr=lights_with_mask;
- lights_with_mask=cl;
+ if (cl->mode == VS::CANVAS_LIGHT_MODE_MASK) {
+ cl->mask_next_ptr = lights_with_mask;
+ lights_with_mask = cl;
}
light_count++;
}
- VSG::canvas_render->light_internal_update(cl->light_internal,cl);
-
+ VSG::canvas_render->light_internal_update(cl->light_internal, cl);
}
}
//print_line("lights: "+itos(light_count));
- canvas_map[ Viewport::CanvasKey( E->key(), E->get().layer) ]=&E->get();
-
+ canvas_map[Viewport::CanvasKey(E->key(), E->get().layer)] = &E->get();
}
if (lights_with_shadow) {
//update shadows if any
- RasterizerCanvas::LightOccluderInstance * occluders=NULL;
+ RasterizerCanvas::LightOccluderInstance *occluders = NULL;
//make list of occluders
- for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) {
+ for (Map<RID, Viewport::CanvasData>::Element *E = p_viewport->canvas_map.front(); E; E = E->next()) {
- VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas);
+ VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get().canvas);
Transform2D xf = p_viewport->global_transform * E->get().transform;
-
- for(Set<RasterizerCanvas::LightOccluderInstance*>::Element *F=canvas->occluders.front();F;F=F->next()) {
+ for (Set<RasterizerCanvas::LightOccluderInstance *>::Element *F = canvas->occluders.front(); F; F = F->next()) {
if (!F->get()->enabled)
continue;
F->get()->xform_cache = xf * F->get()->xform;
- if (shadow_rect.intersects_transformed(F->get()->xform_cache,F->get()->aabb_cache)) {
-
- F->get()->next=occluders;
- occluders=F->get();
+ if (shadow_rect.intersects_transformed(F->get()->xform_cache, F->get()->aabb_cache)) {
+ F->get()->next = occluders;
+ occluders = F->get();
}
}
}
//update the light shadowmaps with them
- RasterizerCanvas::Light *light=lights_with_shadow;
- while(light) {
+ RasterizerCanvas::Light *light = lights_with_shadow;
+ while (light) {
- VSG::canvas_render->canvas_light_shadow_buffer_update(light->shadow_buffer,light->xform_cache.affine_inverse(),light->item_mask,light->radius_cache/1000.0,light->radius_cache*1.1,occluders,&light->shadow_matrix_cache);
- light=light->shadows_next_ptr;
+ VSG::canvas_render->canvas_light_shadow_buffer_update(light->shadow_buffer, light->xform_cache.affine_inverse(), light->item_mask, light->radius_cache / 1000.0, light->radius_cache * 1.1, occluders, &light->shadow_matrix_cache);
+ light = light->shadows_next_ptr;
}
//VSG::canvas_render->reset_canvas();
@@ -209,7 +198,6 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
VSG::rasterizer->restore_render_target();
-
#if 0
if (scenario_draw_canvas_bg && canvas_map.front() && canvas_map.front()->key().layer>scenario_canvas_max_layer) {
@@ -219,27 +207,26 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
}
#endif
+ for (Map<Viewport::CanvasKey, Viewport::CanvasData *>::Element *E = canvas_map.front(); E; E = E->next()) {
- for (Map<Viewport::CanvasKey,Viewport::CanvasData*>::Element *E=canvas_map.front();E;E=E->next()) {
-
- VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get()->canvas);
+ VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas *>(E->get()->canvas);
//print_line("canvas "+itos(i)+" size: "+itos(I->get()->canvas->child_items.size()));
//print_line("GT "+p_viewport->global_transform+". CT: "+E->get()->transform);
Transform2D xform = p_viewport->global_transform * E->get()->transform;
- RasterizerCanvas::Light *canvas_lights=NULL;
+ RasterizerCanvas::Light *canvas_lights = NULL;
- RasterizerCanvas::Light *ptr=lights;
- while(ptr) {
- if (E->get()->layer>=ptr->layer_min && E->get()->layer<=ptr->layer_max) {
- ptr->next_ptr=canvas_lights;
- canvas_lights=ptr;
+ RasterizerCanvas::Light *ptr = lights;
+ while (ptr) {
+ if (E->get()->layer >= ptr->layer_min && E->get()->layer <= ptr->layer_max) {
+ ptr->next_ptr = canvas_lights;
+ canvas_lights = ptr;
}
- ptr=ptr->filter_next_ptr;
+ ptr = ptr->filter_next_ptr;
}
- VSG::canvas->render_canvas( canvas,xform,canvas_lights,lights_with_mask,clip_rect );
+ VSG::canvas->render_canvas(canvas, xform, canvas_lights, lights_with_mask, clip_rect);
i++;
#if 0
if (scenario_draw_canvas_bg && E->key().layer>=scenario_canvas_max_layer) {
@@ -247,8 +234,6 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
scenario_draw_canvas_bg=false;
}
#endif
-
-
}
#if 0
if (scenario_draw_canvas_bg) {
@@ -259,33 +244,28 @@ void VisualServerViewport::_draw_viewport(Viewport *p_viewport) {
//VSG::canvas_render->canvas_debug_viewport_shadows(lights_with_shadow);
}
-
-
-
}
void VisualServerViewport::draw_viewports() {
//sort viewports
-
//draw viewports
- clear_color=GLOBAL_GET("rendering/viewport/default_clear_color");
-
+ clear_color = GLOBAL_GET("rendering/viewport/default_clear_color");
active_viewports.sort_custom<ViewportSort>();
- for(int i=0;i<active_viewports.size();i++) {
+ for (int i = 0; i < active_viewports.size(); i++) {
Viewport *vp = active_viewports[i];
- if (vp->update_mode==VS::VIEWPORT_UPDATE_DISABLED)
+ if (vp->update_mode == VS::VIEWPORT_UPDATE_DISABLED)
continue;
- ERR_CONTINUE( !vp->render_target.is_valid() );
+ ERR_CONTINUE(!vp->render_target.is_valid());
- bool visible = vp->viewport_to_screen_rect!=Rect2() || vp->update_mode==VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode==VS::VIEWPORT_UPDATE_ONCE;
+ bool visible = vp->viewport_to_screen_rect != Rect2() || vp->update_mode == VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode == VS::VIEWPORT_UPDATE_ONCE;
if (!visible)
continue;
@@ -293,177 +273,161 @@ void VisualServerViewport::draw_viewports() {
VSG::rasterizer->set_current_render_target(vp->render_target);
_draw_viewport(vp);
- if (vp->viewport_to_screen_rect!=Rect2()) {
+ if (vp->viewport_to_screen_rect != Rect2()) {
//copy to screen if set as such
VSG::rasterizer->set_current_render_target(RID());
- VSG::rasterizer->blit_render_target_to_screen(vp->render_target,vp->viewport_to_screen_rect,vp->viewport_to_screen);
+ VSG::rasterizer->blit_render_target_to_screen(vp->render_target, vp->viewport_to_screen_rect, vp->viewport_to_screen);
}
- if (vp->update_mode==VS::VIEWPORT_UPDATE_ONCE) {
- vp->update_mode=VS::VIEWPORT_UPDATE_DISABLED;
+ if (vp->update_mode == VS::VIEWPORT_UPDATE_ONCE) {
+ vp->update_mode = VS::VIEWPORT_UPDATE_DISABLED;
}
}
}
-
RID VisualServerViewport::viewport_create() {
- Viewport * viewport = memnew( Viewport );
+ Viewport *viewport = memnew(Viewport);
RID rid = viewport_owner.make_rid(viewport);
- viewport->self=rid;
- viewport->hide_scenario=false;
- viewport->hide_canvas=false;
- viewport->render_target=VSG::storage->render_target_create();
- viewport->shadow_atlas=VSG::scene_render->shadow_atlas_create();
+ viewport->self = rid;
+ viewport->hide_scenario = false;
+ viewport->hide_canvas = false;
+ viewport->render_target = VSG::storage->render_target_create();
+ viewport->shadow_atlas = VSG::scene_render->shadow_atlas_create();
return rid;
-
}
-void VisualServerViewport::viewport_set_size(RID p_viewport,int p_width,int p_height){
+void VisualServerViewport::viewport_set_size(RID p_viewport, int p_width, int p_height) {
- ERR_FAIL_COND(p_width<0 && p_height<0);
+ ERR_FAIL_COND(p_width < 0 && p_height < 0);
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
-
-
- viewport->size=Size2(p_width,p_height);
- VSG::storage->render_target_set_size(viewport->render_target,p_width,p_height);
-
-
+ viewport->size = Size2(p_width, p_height);
+ VSG::storage->render_target_set_size(viewport->render_target, p_width, p_height);
}
-void VisualServerViewport::viewport_set_active(RID p_viewport,bool p_active) {
+void VisualServerViewport::viewport_set_active(RID p_viewport, bool p_active) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
if (p_active) {
- ERR_FAIL_COND(active_viewports.find(viewport)!=-1);//already active
+ ERR_FAIL_COND(active_viewports.find(viewport) != -1); //already active
active_viewports.push_back(viewport);
} else {
active_viewports.erase(viewport);
}
-
-
}
-void VisualServerViewport::viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport) {
+void VisualServerViewport::viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->parent=p_parent_viewport;
+ viewport->parent = p_parent_viewport;
}
-void VisualServerViewport::viewport_set_clear_mode(RID p_viewport,VS::ViewportClearMode p_clear_mode) {
+void VisualServerViewport::viewport_set_clear_mode(RID p_viewport, VS::ViewportClearMode p_clear_mode) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->clear_mode=p_clear_mode;
-
+ viewport->clear_mode = p_clear_mode;
}
+void VisualServerViewport::viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect, int p_screen) {
-void VisualServerViewport::viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect,int p_screen){
-
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->viewport_to_screen_rect=p_rect;
- viewport->viewport_to_screen=p_screen;
+ viewport->viewport_to_screen_rect = p_rect;
+ viewport->viewport_to_screen = p_screen;
}
-void VisualServerViewport::viewport_detach(RID p_viewport){
+void VisualServerViewport::viewport_detach(RID p_viewport) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->viewport_to_screen_rect=Rect2();
- viewport->viewport_to_screen=0;
-
+ viewport->viewport_to_screen_rect = Rect2();
+ viewport->viewport_to_screen = 0;
}
-void VisualServerViewport::viewport_set_update_mode(RID p_viewport,VS::ViewportUpdateMode p_mode){
+void VisualServerViewport::viewport_set_update_mode(RID p_viewport, VS::ViewportUpdateMode p_mode) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->update_mode=p_mode;
-
+ viewport->update_mode = p_mode;
}
-void VisualServerViewport::viewport_set_vflip(RID p_viewport,bool p_enable){
+void VisualServerViewport::viewport_set_vflip(RID p_viewport, bool p_enable) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_VFLIP,p_enable);
-
+ VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_VFLIP, p_enable);
}
-RID VisualServerViewport::viewport_get_texture(RID p_viewport) const{
+RID VisualServerViewport::viewport_get_texture(RID p_viewport) const {
- const Viewport * viewport = viewport_owner.getornull(p_viewport);
- ERR_FAIL_COND_V(!viewport,RID());
+ const Viewport *viewport = viewport_owner.getornull(p_viewport);
+ ERR_FAIL_COND_V(!viewport, RID());
return VSG::storage->render_target_get_texture(viewport->render_target);
-
}
-void VisualServerViewport::viewport_set_hide_scenario(RID p_viewport,bool p_hide){
+void VisualServerViewport::viewport_set_hide_scenario(RID p_viewport, bool p_hide) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->hide_scenario=p_hide;
+ viewport->hide_scenario = p_hide;
}
-void VisualServerViewport::viewport_set_hide_canvas(RID p_viewport,bool p_hide){
+void VisualServerViewport::viewport_set_hide_canvas(RID p_viewport, bool p_hide) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->hide_canvas=p_hide;
+ viewport->hide_canvas = p_hide;
}
-void VisualServerViewport::viewport_set_disable_environment(RID p_viewport,bool p_disable){
+void VisualServerViewport::viewport_set_disable_environment(RID p_viewport, bool p_disable) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
-
- viewport->disable_environment=p_disable;
+ viewport->disable_environment = p_disable;
}
-void VisualServerViewport::viewport_set_disable_3d(RID p_viewport,bool p_disable){
+void VisualServerViewport::viewport_set_disable_3d(RID p_viewport, bool p_disable) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
-
- viewport->disable_3d=p_disable;
- VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_NO_3D,p_disable);
+ viewport->disable_3d = p_disable;
+ VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_NO_3D, p_disable);
}
-void VisualServerViewport::viewport_attach_camera(RID p_viewport,RID p_camera){
+void VisualServerViewport::viewport_attach_camera(RID p_viewport, RID p_camera) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->camera=p_camera;
+ viewport->camera = p_camera;
}
-void VisualServerViewport::viewport_set_scenario(RID p_viewport,RID p_scenario){
+void VisualServerViewport::viewport_set_scenario(RID p_viewport, RID p_scenario) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->scenario=p_scenario;
+ viewport->scenario = p_scenario;
}
-void VisualServerViewport::viewport_attach_canvas(RID p_viewport,RID p_canvas){
+void VisualServerViewport::viewport_attach_canvas(RID p_viewport, RID p_canvas) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
ERR_FAIL_COND(viewport->canvas_map.has(p_canvas));
@@ -471,15 +435,14 @@ void VisualServerViewport::viewport_attach_canvas(RID p_viewport,RID p_canvas){
ERR_FAIL_COND(!canvas);
canvas->viewports.insert(p_viewport);
- viewport->canvas_map[p_canvas]=Viewport::CanvasData();
- viewport->canvas_map[p_canvas].layer=0;
- viewport->canvas_map[p_canvas].canvas=canvas;
-
+ viewport->canvas_map[p_canvas] = Viewport::CanvasData();
+ viewport->canvas_map[p_canvas].layer = 0;
+ viewport->canvas_map[p_canvas].canvas = canvas;
}
-void VisualServerViewport::viewport_remove_canvas(RID p_viewport,RID p_canvas){
+void VisualServerViewport::viewport_remove_canvas(RID p_viewport, RID p_canvas) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
VisualServerCanvas::Canvas *canvas = VSG::canvas->canvas_owner.getornull(p_canvas);
@@ -487,110 +450,97 @@ void VisualServerViewport::viewport_remove_canvas(RID p_viewport,RID p_canvas){
viewport->canvas_map.erase(p_canvas);
canvas->viewports.erase(p_viewport);
-
}
-void VisualServerViewport::viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset){
+void VisualServerViewport::viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas));
- viewport->canvas_map[p_canvas].transform=p_offset;
-
+ viewport->canvas_map[p_canvas].transform = p_offset;
}
-void VisualServerViewport::viewport_set_transparent_background(RID p_viewport,bool p_enabled){
+void VisualServerViewport::viewport_set_transparent_background(RID p_viewport, bool p_enabled) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_TRANSPARENT,p_enabled);
-
+ VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_TRANSPARENT, p_enabled);
}
-void VisualServerViewport::viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform){
+void VisualServerViewport::viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->global_transform=p_transform;
-
+ viewport->global_transform = p_transform;
}
-void VisualServerViewport::viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer){
+void VisualServerViewport::viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas));
- viewport->canvas_map[p_canvas].layer=p_layer;
-
+ viewport->canvas_map[p_canvas].layer = p_layer;
}
-void VisualServerViewport::viewport_set_shadow_atlas_size(RID p_viewport,int p_size) {
+void VisualServerViewport::viewport_set_shadow_atlas_size(RID p_viewport, int p_size) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- viewport->shadow_atlas_size=p_size;
-
- VSG::scene_render->shadow_atlas_set_size( viewport->shadow_atlas, viewport->shadow_atlas_size);
+ viewport->shadow_atlas_size = p_size;
+ VSG::scene_render->shadow_atlas_set_size(viewport->shadow_atlas, viewport->shadow_atlas_size);
}
-void VisualServerViewport::viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv) {
+void VisualServerViewport::viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- VSG::scene_render->shadow_atlas_set_quadrant_subdivision( viewport->shadow_atlas, p_quadrant, p_subdiv);
-
+ VSG::scene_render->shadow_atlas_set_quadrant_subdivision(viewport->shadow_atlas, p_quadrant, p_subdiv);
}
-void VisualServerViewport::viewport_set_msaa(RID p_viewport,VS::ViewportMSAA p_msaa) {
+void VisualServerViewport::viewport_set_msaa(RID p_viewport, VS::ViewportMSAA p_msaa) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- VSG::storage->render_target_set_msaa(viewport->render_target,p_msaa);
+ VSG::storage->render_target_set_msaa(viewport->render_target, p_msaa);
}
-void VisualServerViewport::viewport_set_hdr(RID p_viewport,bool p_enabled) {
+void VisualServerViewport::viewport_set_hdr(RID p_viewport, bool p_enabled) {
- Viewport * viewport = viewport_owner.getornull(p_viewport);
+ Viewport *viewport = viewport_owner.getornull(p_viewport);
ERR_FAIL_COND(!viewport);
- VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_HDR,p_enabled);
-
+ VSG::storage->render_target_set_flag(viewport->render_target, RasterizerStorage::RENDER_TARGET_HDR, p_enabled);
}
bool VisualServerViewport::free(RID p_rid) {
if (viewport_owner.owns(p_rid)) {
- Viewport * viewport = viewport_owner.getornull(p_rid);
-
+ Viewport *viewport = viewport_owner.getornull(p_rid);
- VSG::storage->free( viewport->render_target );
- VSG::scene_render->free( viewport->shadow_atlas );
+ VSG::storage->free(viewport->render_target);
+ VSG::scene_render->free(viewport->shadow_atlas);
- while(viewport->canvas_map.front()) {
- viewport_remove_canvas(p_rid,viewport->canvas_map.front()->key());
+ while (viewport->canvas_map.front()) {
+ viewport_remove_canvas(p_rid, viewport->canvas_map.front()->key());
}
- viewport_set_scenario(p_rid,RID());
+ viewport_set_scenario(p_rid, RID());
active_viewports.erase(viewport);
viewport_owner.free(p_rid);
memdelete(viewport);
-
return true;
}
return false;
-
}
-VisualServerViewport::VisualServerViewport()
-{
-
+VisualServerViewport::VisualServerViewport() {
}
diff --git a/servers/visual/visual_server_viewport.h b/servers/visual/visual_server_viewport.h
index 1cee90b803..53ad6bde2b 100644
--- a/servers/visual/visual_server_viewport.h
+++ b/servers/visual/visual_server_viewport.h
@@ -29,20 +29,15 @@
#ifndef VISUALSERVERVIEWPORT_H
#define VISUALSERVERVIEWPORT_H
-#include "servers/visual_server.h"
#include "rasterizer.h"
#include "self_list.h"
+#include "servers/visual_server.h"
-class VisualServerViewport {
+class VisualServerViewport {
public:
-
struct CanvasBase : public RID_Data {
-
-
};
-
-
struct Viewport : public RID_Data {
RID self;
@@ -67,7 +62,6 @@ public:
RID shadow_atlas;
int shadow_atlas_size;
-
VS::ViewportClearMode clear_mode;
bool rendered_in_prev_frame;
@@ -76,9 +70,15 @@ public:
int layer;
RID canvas;
- bool operator<(const CanvasKey& p_canvas) const { if (layer==p_canvas.layer) return canvas < p_canvas.canvas; return layer<p_canvas.layer; }
- CanvasKey() { layer=0; }
- CanvasKey(const RID& p_canvas, int p_layer) { canvas=p_canvas; layer=p_layer; }
+ bool operator<(const CanvasKey &p_canvas) const {
+ if (layer == p_canvas.layer) return canvas < p_canvas.canvas;
+ return layer < p_canvas.layer;
+ }
+ CanvasKey() { layer = 0; }
+ CanvasKey(const RID &p_canvas, int p_layer) {
+ canvas = p_canvas;
+ layer = p_layer;
+ }
};
struct CanvasData {
@@ -90,83 +90,79 @@ public:
Transform2D global_transform;
- Map<RID,CanvasData> canvas_map;
+ Map<RID, CanvasData> canvas_map;
Viewport() {
- update_mode=VS::VIEWPORT_UPDATE_WHEN_VISIBLE;
- clear_mode=VS::VIEWPORT_CLEAR_ALWAYS;
- rendered_in_prev_frame=false;
- disable_environment=false;
- viewport_to_screen=0;
- shadow_atlas_size=0;
- disable_3d=false;
-
+ update_mode = VS::VIEWPORT_UPDATE_WHEN_VISIBLE;
+ clear_mode = VS::VIEWPORT_CLEAR_ALWAYS;
+ rendered_in_prev_frame = false;
+ disable_environment = false;
+ viewport_to_screen = 0;
+ shadow_atlas_size = 0;
+ disable_3d = false;
}
};
mutable RID_Owner<Viewport> viewport_owner;
-
struct ViewportSort {
- _FORCE_INLINE_ bool operator()(const Viewport*p_left,const Viewport* p_right) const {
+ _FORCE_INLINE_ bool operator()(const Viewport *p_left, const Viewport *p_right) const {
- bool left_to_screen = p_left->viewport_to_screen_rect.size!=Size2();
- bool right_to_screen = p_right->viewport_to_screen_rect.size!=Size2();
+ bool left_to_screen = p_left->viewport_to_screen_rect.size != Size2();
+ bool right_to_screen = p_right->viewport_to_screen_rect.size != Size2();
- if (left_to_screen==right_to_screen) {
+ if (left_to_screen == right_to_screen) {
- return p_left->parent==p_right->self;
+ return p_left->parent == p_right->self;
} else {
return right_to_screen;
}
}
};
+ Vector<Viewport *> active_viewports;
- Vector<Viewport*> active_viewports;
private:
Color clear_color;
void _draw_viewport(Viewport *p_viewport);
-public:
-
+public:
RID viewport_create();
- void viewport_set_size(RID p_viewport,int p_width,int p_height);
+ void viewport_set_size(RID p_viewport, int p_width, int p_height);
- void viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect=Rect2(),int p_screen=0);
+ void viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect = Rect2(), int p_screen = 0);
void viewport_detach(RID p_viewport);
- void viewport_set_active(RID p_viewport,bool p_active);
- void viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport);
- void viewport_set_update_mode(RID p_viewport,VS::ViewportUpdateMode p_mode);
- void viewport_set_vflip(RID p_viewport,bool p_enable);
-
+ void viewport_set_active(RID p_viewport, bool p_active);
+ void viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport);
+ void viewport_set_update_mode(RID p_viewport, VS::ViewportUpdateMode p_mode);
+ void viewport_set_vflip(RID p_viewport, bool p_enable);
- void viewport_set_clear_mode(RID p_viewport,VS::ViewportClearMode p_clear_mode);
+ void viewport_set_clear_mode(RID p_viewport, VS::ViewportClearMode p_clear_mode);
RID viewport_get_texture(RID p_viewport) const;
- void viewport_set_hide_scenario(RID p_viewport,bool p_hide);
- void viewport_set_hide_canvas(RID p_viewport,bool p_hide);
- void viewport_set_disable_environment(RID p_viewport,bool p_disable);
- void viewport_set_disable_3d(RID p_viewport,bool p_disable);
+ void viewport_set_hide_scenario(RID p_viewport, bool p_hide);
+ void viewport_set_hide_canvas(RID p_viewport, bool p_hide);
+ void viewport_set_disable_environment(RID p_viewport, bool p_disable);
+ void viewport_set_disable_3d(RID p_viewport, bool p_disable);
- void viewport_attach_camera(RID p_viewport,RID p_camera);
- void viewport_set_scenario(RID p_viewport,RID p_scenario);
- void viewport_attach_canvas(RID p_viewport,RID p_canvas);
- void viewport_remove_canvas(RID p_viewport,RID p_canvas);
- void viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset);
- void viewport_set_transparent_background(RID p_viewport,bool p_enabled);
+ void viewport_attach_camera(RID p_viewport, RID p_camera);
+ void viewport_set_scenario(RID p_viewport, RID p_scenario);
+ void viewport_attach_canvas(RID p_viewport, RID p_canvas);
+ void viewport_remove_canvas(RID p_viewport, RID p_canvas);
+ void viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset);
+ void viewport_set_transparent_background(RID p_viewport, bool p_enabled);
- void viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform);
- void viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer);
+ void viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform);
+ void viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer);
- void viewport_set_shadow_atlas_size(RID p_viewport,int p_size);
- void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv);
+ void viewport_set_shadow_atlas_size(RID p_viewport, int p_size);
+ void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv);
- void viewport_set_msaa(RID p_viewport,VS::ViewportMSAA p_msaa);
- void viewport_set_hdr(RID p_viewport,bool p_enabled);
+ void viewport_set_msaa(RID p_viewport, VS::ViewportMSAA p_msaa);
+ void viewport_set_hdr(RID p_viewport, bool p_enabled);
void draw_viewports();
diff --git a/servers/visual_server.cpp b/servers/visual_server.cpp
index 5d231d208e..a28c409b97 100644
--- a/servers/visual_server.cpp
+++ b/servers/visual_server.cpp
@@ -30,23 +30,20 @@
#include "global_config.h"
#include "method_bind_ext.inc"
-VisualServer *VisualServer::singleton=NULL;
-VisualServer* (*VisualServer::create_func)()=NULL;
+VisualServer *VisualServer::singleton = NULL;
+VisualServer *(*VisualServer::create_func)() = NULL;
VisualServer *VisualServer::get_singleton() {
return singleton;
}
-
-
PoolVector<String> VisualServer::_shader_get_param_list(RID p_shader) const {
-//remove at some point
+ //remove at some point
PoolVector<String> pl;
-
#if 0
List<StringName> params;
shader_get_param_list(p_shader,&params);
@@ -62,7 +59,7 @@ PoolVector<String> VisualServer::_shader_get_param_list(RID p_shader) const {
VisualServer *VisualServer::create() {
- ERR_FAIL_COND_V(singleton,NULL);
+ ERR_FAIL_COND_V(singleton, NULL);
if (create_func)
return create_func();
@@ -70,13 +67,13 @@ VisualServer *VisualServer::create() {
return NULL;
}
-RID VisualServer::texture_create_from_image(const Image& p_image,uint32_t p_flags) {
+RID VisualServer::texture_create_from_image(const Image &p_image, uint32_t p_flags) {
RID texture = texture_create();
- texture_allocate(texture,p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); //if it has mipmaps, use, else generate
- ERR_FAIL_COND_V(!texture.is_valid(),texture);
+ texture_allocate(texture, p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); //if it has mipmaps, use, else generate
+ ERR_FAIL_COND_V(!texture.is_valid(), texture);
- texture_set_data(texture, p_image );
+ texture_set_data(texture, p_image);
return texture;
}
@@ -89,41 +86,40 @@ RID VisualServer::get_test_texture() {
#define TEST_TEXTURE_SIZE 256
-
PoolVector<uint8_t> test_data;
- test_data.resize(TEST_TEXTURE_SIZE*TEST_TEXTURE_SIZE*3);
+ test_data.resize(TEST_TEXTURE_SIZE * TEST_TEXTURE_SIZE * 3);
{
- PoolVector<uint8_t>::Write w=test_data.write();
+ PoolVector<uint8_t>::Write w = test_data.write();
- for (int x=0;x<TEST_TEXTURE_SIZE;x++) {
+ for (int x = 0; x < TEST_TEXTURE_SIZE; x++) {
- for (int y=0;y<TEST_TEXTURE_SIZE;y++) {
+ for (int y = 0; y < TEST_TEXTURE_SIZE; y++) {
Color c;
- int r=255-(x+y)/2;
+ int r = 255 - (x + y) / 2;
- if ((x%(TEST_TEXTURE_SIZE/8))<2 ||(y%(TEST_TEXTURE_SIZE/8))<2) {
+ if ((x % (TEST_TEXTURE_SIZE / 8)) < 2 || (y % (TEST_TEXTURE_SIZE / 8)) < 2) {
- c.r=y;
- c.g=r;
- c.b=x;
+ c.r = y;
+ c.g = r;
+ c.b = x;
} else {
- c.r=r;
- c.g=x;
- c.b=y;
+ c.r = r;
+ c.g = x;
+ c.b = y;
}
- w[(y*TEST_TEXTURE_SIZE+x)*3+0]=uint8_t(CLAMP(c.r*255,0,255));
- w[(y*TEST_TEXTURE_SIZE+x)*3+1]=uint8_t(CLAMP(c.g*255,0,255));
- w[(y*TEST_TEXTURE_SIZE+x)*3+2]=uint8_t(CLAMP(c.b*255,0,255));
+ w[(y * TEST_TEXTURE_SIZE + x) * 3 + 0] = uint8_t(CLAMP(c.r * 255, 0, 255));
+ w[(y * TEST_TEXTURE_SIZE + x) * 3 + 1] = uint8_t(CLAMP(c.g * 255, 0, 255));
+ w[(y * TEST_TEXTURE_SIZE + x) * 3 + 2] = uint8_t(CLAMP(c.b * 255, 0, 255));
}
}
}
- Image data(TEST_TEXTURE_SIZE,TEST_TEXTURE_SIZE,false,Image::FORMAT_RGB8,test_data);
+ Image data(TEST_TEXTURE_SIZE, TEST_TEXTURE_SIZE, false, Image::FORMAT_RGB8, test_data);
test_texture = texture_create_from_image(data);
@@ -139,13 +135,10 @@ void VisualServer::_free_internal_rids() {
if (test_material.is_valid())
free(test_material);
- for(int i=0;i<16;i++) {
+ for (int i = 0; i < 16; i++) {
if (material_2d[i].is_valid())
free(material_2d[i]);
}
-
-
-
}
RID VisualServer::_make_test_cube() {
@@ -155,72 +148,69 @@ RID VisualServer::_make_test_cube() {
PoolVector<float> tangents;
PoolVector<Vector3> uvs;
- int vtx_idx=0;
-#define ADD_VTX(m_idx) \
- vertices.push_back( face_points[m_idx] );\
- normals.push_back( normal_points[m_idx] );\
- tangents.push_back( normal_points[m_idx][1] );\
- tangents.push_back( normal_points[m_idx][2] );\
- tangents.push_back( normal_points[m_idx][0] );\
- tangents.push_back( 1.0 );\
- uvs.push_back( Vector3(uv_points[m_idx*2+0],uv_points[m_idx*2+1],0) );\
- vtx_idx++;\
-
- for (int i=0;i<6;i++) {
+ int vtx_idx = 0;
+#define ADD_VTX(m_idx) \
+ vertices.push_back(face_points[m_idx]); \
+ normals.push_back(normal_points[m_idx]); \
+ tangents.push_back(normal_points[m_idx][1]); \
+ tangents.push_back(normal_points[m_idx][2]); \
+ tangents.push_back(normal_points[m_idx][0]); \
+ tangents.push_back(1.0); \
+ uvs.push_back(Vector3(uv_points[m_idx * 2 + 0], uv_points[m_idx * 2 + 1], 0)); \
+ vtx_idx++;
+ for (int i = 0; i < 6; i++) {
Vector3 face_points[4];
Vector3 normal_points[4];
- float uv_points[8]={0,0,0,1,1,1,1,0};
+ float uv_points[8] = { 0, 0, 0, 1, 1, 1, 1, 0 };
- for (int j=0;j<4;j++) {
+ 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));
+ 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++) {
+ for (int k = 0; k < 3; k++) {
- if (i<3)
- face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ if (i < 3)
+ face_points[j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
else
- face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
+ face_points[3 - j][(i + k) % 3] = v[k] * (i >= 3 ? -1 : 1);
}
- normal_points[j]=Vector3();
- normal_points[j][i%3]=(i>=3?-1:1);
+ normal_points[j] = Vector3();
+ normal_points[j][i % 3] = (i >= 3 ? -1 : 1);
}
- //tri 1
+ //tri 1
ADD_VTX(0);
ADD_VTX(1);
ADD_VTX(2);
- //tri 2
+ //tri 2
ADD_VTX(2);
ADD_VTX(3);
ADD_VTX(0);
-
}
RID test_cube = mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
- d[VisualServer::ARRAY_NORMAL]= normals ;
- d[VisualServer::ARRAY_TANGENT]= tangents ;
- d[VisualServer::ARRAY_TEX_UV]= uvs ;
- d[VisualServer::ARRAY_VERTEX]= vertices ;
+ d[VisualServer::ARRAY_NORMAL] = normals;
+ d[VisualServer::ARRAY_TANGENT] = tangents;
+ d[VisualServer::ARRAY_TEX_UV] = uvs;
+ d[VisualServer::ARRAY_VERTEX] = vertices;
PoolVector<int> indices;
indices.resize(vertices.size());
- for(int i=0;i<vertices.size();i++)
- indices.set(i,i);
- d[VisualServer::ARRAY_INDEX]=indices;
-
- mesh_add_surface_from_arrays( test_cube, PRIMITIVE_TRIANGLES,d );
+ for (int i = 0; i < vertices.size(); i++)
+ indices.set(i, i);
+ d[VisualServer::ARRAY_INDEX] = indices;
+ mesh_add_surface_from_arrays(test_cube, PRIMITIVE_TRIANGLES, d);
-/*
+ /*
test_material = fixed_material_create();
//material_set_flag(material, MATERIAL_FLAG_BILLBOARD_TOGGLE,true);
fixed_material_set_texture( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, get_test_texture() );
@@ -230,47 +220,45 @@ RID VisualServer::_make_test_cube() {
fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, Color(1, 1, 1) );
fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_SPECULAR, Color(1,1,1) );
*/
- mesh_surface_set_material(test_cube, 0, test_material );
+ mesh_surface_set_material(test_cube, 0, test_material);
return test_cube;
}
-
-RID VisualServer::make_sphere_mesh(int p_lats,int p_lons,float p_radius) {
+RID VisualServer::make_sphere_mesh(int p_lats, int p_lons, float p_radius) {
PoolVector<Vector3> vertices;
PoolVector<Vector3> normals;
- for(int i = 1; i <= p_lats; i++) {
- double lat0 = Math_PI * (-0.5 + (double) (i - 1) / p_lats);
- double z0 = Math::sin(lat0);
- double zr0 = Math::cos(lat0);
+ for (int i = 1; i <= p_lats; i++) {
+ double lat0 = Math_PI * (-0.5 + (double)(i - 1) / p_lats);
+ double z0 = Math::sin(lat0);
+ double zr0 = Math::cos(lat0);
- double lat1 = Math_PI * (-0.5 + (double) i / p_lats);
+ double lat1 = Math_PI * (-0.5 + (double)i / p_lats);
double z1 = Math::sin(lat1);
double zr1 = Math::cos(lat1);
- for(int j = p_lons; j >= 1; j--) {
+ for (int j = p_lons; j >= 1; j--) {
- double lng0 = 2 * Math_PI * (double) (j - 1) / p_lons;
+ double lng0 = 2 * Math_PI * (double)(j - 1) / p_lons;
double x0 = Math::cos(lng0);
double y0 = Math::sin(lng0);
- double lng1 = 2 * Math_PI * (double) (j) / p_lons;
+ double lng1 = 2 * Math_PI * (double)(j) / p_lons;
double x1 = Math::cos(lng1);
double y1 = Math::sin(lng1);
-
- Vector3 v[4]={
- Vector3(x1 * zr0, z0, y1 *zr0),
- Vector3(x1 * zr1, z1, y1 *zr1),
- Vector3(x0 * zr1, z1, y0 *zr1),
- Vector3(x0 * zr0, z0, y0 *zr0)
+ Vector3 v[4] = {
+ Vector3(x1 * zr0, z0, y1 * zr0),
+ Vector3(x1 * zr1, z1, y1 * zr1),
+ Vector3(x0 * zr1, z1, y0 * zr1),
+ Vector3(x0 * zr0, z0, y0 * zr0)
};
-#define ADD_POINT(m_idx)\
- normals.push_back(v[m_idx]); \
- vertices.push_back(v[m_idx]*p_radius);\
+#define ADD_POINT(m_idx) \
+ normals.push_back(v[m_idx]); \
+ vertices.push_back(v[m_idx] * p_radius);
ADD_POINT(0);
ADD_POINT(1);
@@ -286,32 +274,31 @@ RID VisualServer::make_sphere_mesh(int p_lats,int p_lons,float p_radius) {
Array d;
d.resize(VS::ARRAY_MAX);
- d[ARRAY_VERTEX]=vertices;
- d[ARRAY_NORMAL]=normals;
+ d[ARRAY_VERTEX] = vertices;
+ d[ARRAY_NORMAL] = normals;
- mesh_add_surface_from_arrays(mesh,PRIMITIVE_TRIANGLES,d);
+ mesh_add_surface_from_arrays(mesh, PRIMITIVE_TRIANGLES, d);
return mesh;
}
-
RID VisualServer::material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha, bool p_opaque_prepass) {
- int version=0;
+ int version = 0;
if (p_shaded)
- version=1;
+ version = 1;
if (p_transparent)
- version|=2;
+ version |= 2;
if (p_cut_alpha)
- version|=4;
+ version |= 4;
if (p_opaque_prepass)
- version|=8;
+ version |= 8;
if (material_2d[version].is_valid())
return material_2d[version];
//not valid, make
-/* material_2d[version]=fixed_material_create();
+ /* material_2d[version]=fixed_material_create();
fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_ALPHA,p_transparent);
fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true);
fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_DISCARD_ALPHA,p_cut_alpha);
@@ -330,189 +317,167 @@ RID VisualServer::get_white_texture() {
return white_texture;
PoolVector<uint8_t> wt;
- wt.resize(16*3);
+ wt.resize(16 * 3);
{
- PoolVector<uint8_t>::Write w =wt.write();
- for(int i=0;i<16*3;i++)
- w[i]=255;
+ PoolVector<uint8_t>::Write w = wt.write();
+ for (int i = 0; i < 16 * 3; i++)
+ w[i] = 255;
}
- Image white(4,4,0,Image::FORMAT_RGB8,wt);
- white_texture=texture_create();
- texture_allocate(white_texture,4,4,Image::FORMAT_RGB8);
- texture_set_data(white_texture,white);
+ Image white(4, 4, 0, Image::FORMAT_RGB8, wt);
+ white_texture = texture_create();
+ texture_allocate(white_texture, 4, 4, Image::FORMAT_RGB8);
+ texture_set_data(white_texture, white);
return white_texture;
-
}
-
-Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t *p_offsets,uint32_t p_stride,PoolVector<uint8_t> &r_vertex_array,int p_vertex_array_len,PoolVector<uint8_t> &r_index_array,int p_index_array_len,Rect3 &r_aabb,Vector<Rect3> r_bone_aabb) {
+Error VisualServer::_surface_set_data(Array p_arrays, uint32_t p_format, uint32_t *p_offsets, uint32_t p_stride, PoolVector<uint8_t> &r_vertex_array, int p_vertex_array_len, PoolVector<uint8_t> &r_index_array, int p_index_array_len, Rect3 &r_aabb, Vector<Rect3> r_bone_aabb) {
PoolVector<uint8_t>::Write vw = r_vertex_array.write();
PoolVector<uint8_t>::Write iw;
if (r_index_array.size()) {
- print_line("elements: "+itos(r_index_array.size()));
-
- iw=r_index_array.write();
+ print_line("elements: " + itos(r_index_array.size()));
+ iw = r_index_array.write();
}
- int max_bone=0;
-
+ int max_bone = 0;
- for(int ai=0;ai<VS::ARRAY_MAX;ai++) {
+ for (int ai = 0; ai < VS::ARRAY_MAX; ai++) {
- if (!(p_format&(1<<ai))) // no array
+ if (!(p_format & (1 << ai))) // no array
continue;
-
- switch(ai) {
+ switch (ai) {
case VS::ARRAY_VERTEX: {
- if (p_format& VS::ARRAY_FLAG_USE_2D_VERTICES) {
+ if (p_format & VS::ARRAY_FLAG_USE_2D_VERTICES) {
PoolVector<Vector2> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector2>::Read read = array.read();
- const Vector2* src=read.ptr();
+ const Vector2 *src = read.ptr();
// setting vertices means regenerating the AABB
Rect2 aabb;
+ if (p_format & ARRAY_COMPRESS_VERTEX) {
- if (p_format&ARRAY_COMPRESS_VERTEX) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- for (int i=0;i<p_vertex_array_len;i++) {
+ uint16_t vector[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) };
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(uint16_t) * 2);
- uint16_t vector[2]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) };
+ if (i == 0) {
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*2);
-
- if (i==0) {
-
- aabb=Rect2(src[i],Vector2());
+ aabb = Rect2(src[i], Vector2());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
-
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
+ float vector[2] = { src[i].x, src[i].y };
- float vector[2]={ src[i].x, src[i].y };
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(float) * 2);
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*2);
+ if (i == 0) {
- if (i==0) {
-
- aabb=Rect2(src[i],Vector2());
+ aabb = Rect2(src[i], Vector2());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
}
- r_aabb=Rect3(Vector3(aabb.pos.x,aabb.pos.y,0),Vector3(aabb.size.x,aabb.size.y,0));
-
+ r_aabb = Rect3(Vector3(aabb.pos.x, aabb.pos.y, 0), Vector3(aabb.size.x, aabb.size.y, 0));
} else {
PoolVector<Vector3> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector3>::Read read = array.read();
- const Vector3* src=read.ptr();
+ const Vector3 *src = read.ptr();
// setting vertices means regenerating the AABB
Rect3 aabb;
+ if (p_format & ARRAY_COMPRESS_VERTEX) {
- if (p_format&ARRAY_COMPRESS_VERTEX) {
-
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
+ uint16_t vector[4] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y), Math::make_half_float(src[i].z), Math::make_half_float(1.0) };
- uint16_t vector[4]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y), Math::make_half_float(src[i].z), Math::make_half_float(1.0) };
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(uint16_t) * 4);
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*4);
+ if (i == 0) {
- if (i==0) {
-
- aabb=Rect3(src[i],Vector3());
+ aabb = Rect3(src[i], Vector3());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
-
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
-
+ for (int i = 0; i < p_vertex_array_len; i++) {
- float vector[3]={ src[i].x, src[i].y, src[i].z };
+ float vector[3] = { src[i].x, src[i].y, src[i].z };
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*3);
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, sizeof(float) * 3);
- if (i==0) {
+ if (i == 0) {
- aabb=Rect3(src[i],Vector3());
+ aabb = Rect3(src[i], Vector3());
} else {
- aabb.expand_to( src[i] );
+ aabb.expand_to(src[i]);
}
}
}
- r_aabb=aabb;
-
+ r_aabb = aabb;
}
-
} break;
case VS::ARRAY_NORMAL: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector3> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector3>::Read read = array.read();
- const Vector3* src=read.ptr();
+ const Vector3 *src = read.ptr();
// setting vertices means regenerating the AABB
- if (p_format&ARRAY_COMPRESS_NORMAL) {
+ if (p_format & ARRAY_COMPRESS_NORMAL) {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- uint8_t vector[4]={
- CLAMP(src[i].x*127,-128,127),
- CLAMP(src[i].y*127,-128,127),
- CLAMP(src[i].z*127,-128,127),
+ uint8_t vector[4] = {
+ CLAMP(src[i].x * 127, -128, 127),
+ CLAMP(src[i].y * 127, -128, 127),
+ CLAMP(src[i].z * 127, -128, 127),
0,
};
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, 4);
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, 4);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
-
-
- float vector[3]={ src[i].x, src[i].y, src[i].z };
- copymem(&vw[p_offsets[ai]+i*p_stride], vector, 3*4);
+ for (int i = 0; i < p_vertex_array_len; i++) {
+ float vector[3] = { src[i].x, src[i].y, src[i].z };
+ copymem(&vw[p_offsets[ai] + i * p_stride], vector, 3 * 4);
}
}
@@ -520,291 +485,257 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t
case VS::ARRAY_TANGENT: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len*4, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len * 4, ERR_INVALID_PARAMETER);
PoolVector<real_t>::Read read = array.read();
- const real_t* src = read.ptr();
+ const real_t *src = read.ptr();
- if (p_format&ARRAY_COMPRESS_TANGENT) {
+ if (p_format & ARRAY_COMPRESS_TANGENT) {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- uint8_t xyzw[4]={
- CLAMP(src[i*4+0]*127,-128,127),
- CLAMP(src[i*4+1]*127,-128,127),
- CLAMP(src[i*4+2]*127,-128,127),
- CLAMP(src[i*4+3]*127,-128,127)
+ uint8_t xyzw[4] = {
+ CLAMP(src[i * 4 + 0] * 127, -128, 127),
+ CLAMP(src[i * 4 + 1] * 127, -128, 127),
+ CLAMP(src[i * 4 + 2] * 127, -128, 127),
+ CLAMP(src[i * 4 + 3] * 127, -128, 127)
};
- copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4);
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], xyzw, 4);
}
-
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- float xyzw[4]={
- src[i*4+0],
- src[i*4+1],
- src[i*4+2],
- src[i*4+3]
+ float xyzw[4] = {
+ src[i * 4 + 0],
+ src[i * 4 + 1],
+ src[i * 4 + 2],
+ src[i * 4 + 3]
};
- copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4*4);
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], xyzw, 4 * 4);
}
}
} break;
case VS::ARRAY_COLOR: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_COLOR_ARRAY, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_COLOR_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Color> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Color>::Read read = array.read();
- const Color* src = read.ptr();
+ const Color *src = read.ptr();
- if (p_format&ARRAY_COMPRESS_COLOR) {
-
- for (int i=0;i<p_vertex_array_len;i++) {
+ if (p_format & ARRAY_COMPRESS_COLOR) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
uint8_t colors[4];
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- colors[j]=CLAMP( int((src[i][j])*255.0), 0,255 );
+ colors[j] = CLAMP(int((src[i][j]) * 255.0), 0, 255);
}
- copymem(&vw[p_offsets[ai]+i*p_stride], colors, 4);
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], colors, 4);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
-
+ for (int i = 0; i < p_vertex_array_len; i++) {
- copymem(&vw[p_offsets[ai]+i*p_stride], &src[i], 4*4);
+ copymem(&vw[p_offsets[ai] + i * p_stride], &src[i], 4 * 4);
}
-
}
-
} break;
case VS::ARRAY_TEX_UV: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector2> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector2>::Read read = array.read();
- const Vector2 * src=read.ptr();
-
-
+ const Vector2 *src = read.ptr();
- if (p_format&ARRAY_COMPRESS_TEX_UV) {
+ if (p_format & ARRAY_COMPRESS_TEX_UV) {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) };
- copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2);
+ uint16_t uv[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) };
+ copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 2);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- float uv[2]={ src[i].x , src[i].y };
-
- copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4);
+ float uv[2] = { src[i].x, src[i].y };
+ copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 4);
}
}
-
} break;
case VS::ARRAY_TEX_UV2: {
-
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<Vector2> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER);
PoolVector<Vector2>::Read read = array.read();
- const Vector2 * src=read.ptr();
+ const Vector2 *src = read.ptr();
+ if (p_format & ARRAY_COMPRESS_TEX_UV2) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- if (p_format&ARRAY_COMPRESS_TEX_UV2) {
-
- for (int i=0;i<p_vertex_array_len;i++) {
-
- uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) };
- copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2);
+ uint16_t uv[2] = { Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) };
+ copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 2);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
- float uv[2]={ src[i].x , src[i].y };
-
- copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4);
+ float uv[2] = { src[i].x, src[i].y };
+ copymem(&vw[p_offsets[ai] + i * p_stride], uv, 2 * 4);
}
}
} break;
case VS::ARRAY_WEIGHTS: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<real_t> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER);
PoolVector<real_t>::Read read = array.read();
- const real_t * src = read.ptr();
+ const real_t *src = read.ptr();
- if (p_format&ARRAY_COMPRESS_WEIGHTS) {
+ if (p_format & ARRAY_COMPRESS_WEIGHTS) {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
uint16_t data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j]*65535,0,65535);
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j] * 65535, 0, 65535);
}
- copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4);
+ copymem(&vw[p_offsets[ai] + i * p_stride], data, 2 * 4);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
float data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j];
}
- copymem(&vw[p_offsets[ai]+i*p_stride], data, 4*4);
-
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], data, 4 * 4);
}
}
} break;
case VS::ARRAY_BONES: {
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY && p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY && p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<int> array = p_arrays[ai];
- ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
-
+ ERR_FAIL_COND_V(array.size() != p_vertex_array_len * VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER);
PoolVector<int>::Read read = array.read();
- const int * src = read.ptr();
+ const int *src = read.ptr();
+ if (!(p_format & ARRAY_FLAG_USE_16_BIT_BONES)) {
- if (!(p_format&ARRAY_FLAG_USE_16_BIT_BONES)) {
-
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
uint8_t data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j],0,255);
- max_bone=MAX(data[j],max_bone);
-
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = CLAMP(src[i * VS::ARRAY_WEIGHTS_SIZE + j], 0, 255);
+ max_bone = MAX(data[j], max_bone);
}
- copymem(&vw[p_offsets[ai]+i*p_stride], data, 4);
-
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], data, 4);
}
} else {
- for (int i=0;i<p_vertex_array_len;i++) {
+ for (int i = 0; i < p_vertex_array_len; i++) {
uint16_t data[VS::ARRAY_WEIGHTS_SIZE];
- for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) {
- data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
- max_bone=MAX(data[j],max_bone);
-
+ for (int j = 0; j < VS::ARRAY_WEIGHTS_SIZE; j++) {
+ data[j] = src[i * VS::ARRAY_WEIGHTS_SIZE + j];
+ max_bone = MAX(data[j], max_bone);
}
- copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4);
-
-
+ copymem(&vw[p_offsets[ai] + i * p_stride], data, 2 * 4);
}
}
-
} break;
case VS::ARRAY_INDEX: {
-
- ERR_FAIL_COND_V( p_index_array_len<=0, ERR_INVALID_DATA );
- ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(p_index_array_len <= 0, ERR_INVALID_DATA);
+ ERR_FAIL_COND_V(p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER);
PoolVector<int> indices = p_arrays[ai];
- ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER );
- ERR_FAIL_COND_V( indices.size() != p_index_array_len, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V(indices.size() == 0, ERR_INVALID_PARAMETER);
+ ERR_FAIL_COND_V(indices.size() != p_index_array_len, ERR_INVALID_PARAMETER);
/* determine wether using 16 or 32 bits indices */
PoolVector<int>::Read read = indices.read();
- const int *src=read.ptr();
-
- for (int i=0;i<p_index_array_len;i++) {
+ const int *src = read.ptr();
+ for (int i = 0; i < p_index_array_len; i++) {
- if (p_vertex_array_len<(1<<16)) {
- uint16_t v=src[i];
+ if (p_vertex_array_len < (1 << 16)) {
+ uint16_t v = src[i];
- copymem(&iw[i*2], &v, 2);
+ copymem(&iw[i * 2], &v, 2);
} else {
- uint32_t v=src[i];
+ uint32_t v = src[i];
- copymem(&iw[i*4], &v, 4);
+ copymem(&iw[i * 4], &v, 4);
}
}
} break;
default: {
- ERR_FAIL_V( ERR_INVALID_DATA );
+ ERR_FAIL_V(ERR_INVALID_DATA);
}
}
}
-
- if (p_format&VS::ARRAY_FORMAT_BONES) {
+ if (p_format & VS::ARRAY_FORMAT_BONES) {
//create AABBs for each detected bone
- int total_bones = max_bone+1;
+ int total_bones = max_bone + 1;
- bool first = r_bone_aabb.size()==0;
+ bool first = r_bone_aabb.size() == 0;
r_bone_aabb.resize(total_bones);
if (first) {
- for(int i=0;i<total_bones;i++) {
- r_bone_aabb[i].size==Vector3(-1,-1,-1); //negative means unused
+ for (int i = 0; i < total_bones; i++) {
+ r_bone_aabb[i].size == Vector3(-1, -1, -1); //negative means unused
}
}
@@ -812,33 +743,33 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t
PoolVector<int> bones = p_arrays[VS::ARRAY_BONES];
PoolVector<float> weights = p_arrays[VS::ARRAY_WEIGHTS];
- bool any_valid=false;
+ bool any_valid = false;
- if (vertices.size() && bones.size()==vertices.size()*4 && weights.size()==bones.size()) {
+ if (vertices.size() && bones.size() == vertices.size() * 4 && weights.size() == bones.size()) {
int vs = vertices.size();
- PoolVector<Vector3>::Read rv =vertices.read();
- PoolVector<int>::Read rb=bones.read();
- PoolVector<float>::Read rw=weights.read();
+ PoolVector<Vector3>::Read rv = vertices.read();
+ PoolVector<int>::Read rb = bones.read();
+ PoolVector<float>::Read rw = weights.read();
Rect3 *bptr = r_bone_aabb.ptr();
- for(int i=0;i<vs;i++) {
+ for (int i = 0; i < vs; i++) {
Vector3 v = rv[i];
- for(int j=0;j<4;j++) {
+ for (int j = 0; j < 4; j++) {
- int idx = rb[i*4+j];
- float w = rw[i*4+j];
- if (w==0)
- continue;//break;
- ERR_FAIL_INDEX_V(idx,total_bones,ERR_INVALID_DATA);
+ int idx = rb[i * 4 + j];
+ float w = rw[i * 4 + j];
+ if (w == 0)
+ continue; //break;
+ ERR_FAIL_INDEX_V(idx, total_bones, ERR_INVALID_DATA);
- if (bptr->size.x<0) {
+ if (bptr->size.x < 0) {
//first
- bptr[idx]=Rect3();
- bptr[idx].pos=v;
- any_valid=true;
+ bptr[idx] = Rect3();
+ bptr[idx].pos = v;
+ any_valid = true;
} else {
bptr[idx].expand_to(v);
}
@@ -854,226 +785,217 @@ Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t
return OK;
}
+void VisualServer::mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, uint32_t p_compress_format) {
-void VisualServer::mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,uint32_t p_compress_format) {
-
- ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX );
- ERR_FAIL_COND(p_arrays.size()!=VS::ARRAY_MAX);
+ ERR_FAIL_INDEX(p_primitive, VS::PRIMITIVE_MAX);
+ ERR_FAIL_COND(p_arrays.size() != VS::ARRAY_MAX);
- uint32_t format=0;
+ uint32_t format = 0;
// validation
- int index_array_len=0;
- int array_len=0;
+ int index_array_len = 0;
+ int array_len = 0;
- for(int i=0;i<p_arrays.size();i++) {
+ for (int i = 0; i < p_arrays.size(); i++) {
- if (p_arrays[i].get_type()==Variant::NIL)
+ if (p_arrays[i].get_type() == Variant::NIL)
continue;
- format|=(1<<i);
+ format |= (1 << i);
- if (i==VS::ARRAY_VERTEX) {
+ if (i == VS::ARRAY_VERTEX) {
Variant var = p_arrays[i];
- switch(var.get_type()) {
+ switch (var.get_type()) {
case Variant::POOL_VECTOR2_ARRAY: {
PoolVector<Vector2> v2 = var;
- array_len=v2.size();
+ array_len = v2.size();
} break;
case Variant::POOL_VECTOR3_ARRAY: {
PoolVector<Vector3> v3 = var;
- array_len=v3.size();
+ array_len = v3.size();
} break;
default: {
Array v = var;
- array_len=v.size();
+ array_len = v.size();
} break;
}
- array_len=PoolVector3Array(p_arrays[i]).size();
- ERR_FAIL_COND(array_len==0);
- } else if (i==VS::ARRAY_INDEX) {
+ array_len = PoolVector3Array(p_arrays[i]).size();
+ ERR_FAIL_COND(array_len == 0);
+ } else if (i == VS::ARRAY_INDEX) {
- index_array_len=PoolIntArray(p_arrays[i]).size();
+ index_array_len = PoolIntArray(p_arrays[i]).size();
}
}
- ERR_FAIL_COND((format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory
-
+ ERR_FAIL_COND((format & VS::ARRAY_FORMAT_VERTEX) == 0); // mandatory
if (p_blend_shapes.size()) {
//validate format for morphs
- for(int i=0;i<p_blend_shapes.size();i++) {
+ for (int i = 0; i < p_blend_shapes.size(); i++) {
- uint32_t bsformat=0;
+ uint32_t bsformat = 0;
Array arr = p_blend_shapes[i];
- for(int j=0;j<arr.size();j++) {
-
+ for (int j = 0; j < arr.size(); j++) {
- if (arr[j].get_type()!=Variant::NIL)
- bsformat|=(1<<j);
+ if (arr[j].get_type() != Variant::NIL)
+ bsformat |= (1 << j);
}
- ERR_FAIL_COND( (bsformat)!=(format&(VS::ARRAY_FORMAT_INDEX-1)));
+ ERR_FAIL_COND((bsformat) != (format & (VS::ARRAY_FORMAT_INDEX - 1)));
}
}
uint32_t offsets[VS::ARRAY_MAX];
- int total_elem_size=0;
-
- for (int i=0;i<VS::ARRAY_MAX;i++) {
+ int total_elem_size = 0;
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
- offsets[i]=0; //reset
+ offsets[i] = 0; //reset
- if (!(format&(1<<i))) // no array
+ if (!(format & (1 << i))) // no array
continue;
+ int elem_size = 0;
- int elem_size=0;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
Variant arr = p_arrays[0];
- if (arr.get_type()==Variant::POOL_VECTOR2_ARRAY) {
- elem_size=2;
- p_compress_format|=ARRAY_FLAG_USE_2D_VERTICES;
- } else if (arr.get_type()==Variant::POOL_VECTOR3_ARRAY) {
- p_compress_format&=~ARRAY_FLAG_USE_2D_VERTICES;
- elem_size=3;
+ if (arr.get_type() == Variant::POOL_VECTOR2_ARRAY) {
+ elem_size = 2;
+ p_compress_format |= ARRAY_FLAG_USE_2D_VERTICES;
+ } else if (arr.get_type() == Variant::POOL_VECTOR3_ARRAY) {
+ p_compress_format &= ~ARRAY_FLAG_USE_2D_VERTICES;
+ elem_size = 3;
} else {
- elem_size=(p_compress_format&ARRAY_FLAG_USE_2D_VERTICES)?2:3;
+ elem_size = (p_compress_format & ARRAY_FLAG_USE_2D_VERTICES) ? 2 : 3;
}
- if (p_compress_format&ARRAY_COMPRESS_VERTEX) {
- elem_size*=sizeof(int16_t);
+ if (p_compress_format & ARRAY_COMPRESS_VERTEX) {
+ elem_size *= sizeof(int16_t);
} else {
- elem_size*=sizeof(float);
+ elem_size *= sizeof(float);
}
- if (elem_size==6) {
+ if (elem_size == 6) {
//had to pad
- elem_size=8;
+ elem_size = 8;
}
} break;
case VS::ARRAY_NORMAL: {
- if (p_compress_format&ARRAY_COMPRESS_NORMAL) {
- elem_size=sizeof(uint32_t);
+ if (p_compress_format & ARRAY_COMPRESS_NORMAL) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*3;
+ elem_size = sizeof(float) * 3;
}
} break;
case VS::ARRAY_TANGENT: {
- if (p_compress_format&ARRAY_COMPRESS_TANGENT) {
- elem_size=sizeof(uint32_t);
+ if (p_compress_format & ARRAY_COMPRESS_TANGENT) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_COLOR: {
- if (p_compress_format&ARRAY_COMPRESS_COLOR) {
- elem_size=sizeof(uint32_t);
+ if (p_compress_format & ARRAY_COMPRESS_COLOR) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_TEX_UV: {
- if (p_compress_format&ARRAY_COMPRESS_TEX_UV) {
- elem_size=sizeof(uint32_t);
+ if (p_compress_format & ARRAY_COMPRESS_TEX_UV) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*2;
+ elem_size = sizeof(float) * 2;
}
} break;
case VS::ARRAY_TEX_UV2: {
- if (p_compress_format&ARRAY_COMPRESS_TEX_UV2) {
- elem_size=sizeof(uint32_t);
+ if (p_compress_format & ARRAY_COMPRESS_TEX_UV2) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*2;
+ elem_size = sizeof(float) * 2;
}
} break;
case VS::ARRAY_WEIGHTS: {
- if (p_compress_format&ARRAY_COMPRESS_WEIGHTS) {
- elem_size=sizeof(uint16_t)*4;
+ if (p_compress_format & ARRAY_COMPRESS_WEIGHTS) {
+ elem_size = sizeof(uint16_t) * 4;
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_BONES: {
PoolVector<int> bones = p_arrays[VS::ARRAY_BONES];
- int max_bone=0;
+ int max_bone = 0;
{
int bc = bones.size();
- PoolVector<int>::Read r=bones.read();
- for(int j=0;j<bc;j++) {
- max_bone=MAX(r[j],max_bone);
+ PoolVector<int>::Read r = bones.read();
+ for (int j = 0; j < bc; j++) {
+ max_bone = MAX(r[j], max_bone);
}
}
if (max_bone > 255) {
- p_compress_format|=ARRAY_FLAG_USE_16_BIT_BONES;
- elem_size=sizeof(uint16_t)*4;
+ p_compress_format |= ARRAY_FLAG_USE_16_BIT_BONES;
+ elem_size = sizeof(uint16_t) * 4;
} else {
- p_compress_format&=~ARRAY_FLAG_USE_16_BIT_BONES;
- elem_size=sizeof(uint32_t);
+ p_compress_format &= ~ARRAY_FLAG_USE_16_BIT_BONES;
+ elem_size = sizeof(uint32_t);
}
-
} break;
case VS::ARRAY_INDEX: {
- if (index_array_len<=0) {
+ if (index_array_len <= 0) {
ERR_PRINT("index_array_len==NO_INDEX_ARRAY");
break;
}
/* determine wether using 16 or 32 bits indices */
- if (array_len>=(1<<16)) {
+ if (array_len >= (1 << 16)) {
- elem_size=4;
+ elem_size = 4;
} else {
- elem_size=2;
+ elem_size = 2;
}
- offsets[i]=elem_size;
+ offsets[i] = elem_size;
continue;
} break;
default: {
- ERR_FAIL( );
+ ERR_FAIL();
}
}
- offsets[i]=total_elem_size;
- total_elem_size+=elem_size;
-
-
+ offsets[i] = total_elem_size;
+ total_elem_size += elem_size;
}
- uint32_t mask = (1<<ARRAY_MAX)-1;
- format|=(~mask)&p_compress_format; //make the full format
-
+ uint32_t mask = (1 << ARRAY_MAX) - 1;
+ format |= (~mask) & p_compress_format; //make the full format
int array_size = total_elem_size * array_len;
PoolVector<uint8_t> vertex_array;
vertex_array.resize(array_size);
- int index_array_size = offsets[VS::ARRAY_INDEX]*index_array_len;
+ int index_array_size = offsets[VS::ARRAY_INDEX] * index_array_len;
PoolVector<uint8_t> index_array;
index_array.resize(index_array_size);
@@ -1081,163 +1003,156 @@ void VisualServer::mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primi
Rect3 aabb;
Vector<Rect3> bone_aabb;
- Error err = _surface_set_data(p_arrays,format,offsets,total_elem_size,vertex_array,array_len,index_array,index_array_len,aabb,bone_aabb);
+ Error err = _surface_set_data(p_arrays, format, offsets, total_elem_size, vertex_array, array_len, index_array, index_array_len, aabb, bone_aabb);
if (err) {
ERR_EXPLAIN("Invalid array format for surface");
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
Vector<PoolVector<uint8_t> > blend_shape_data;
- for(int i=0;i<p_blend_shapes.size();i++) {
+ for (int i = 0; i < p_blend_shapes.size(); i++) {
PoolVector<uint8_t> vertex_array_shape;
vertex_array_shape.resize(array_size);
PoolVector<uint8_t> noindex;
Rect3 laabb;
- Error err = _surface_set_data(p_blend_shapes[i],format&~ARRAY_FORMAT_INDEX,offsets,total_elem_size,vertex_array_shape,array_len,noindex,0,laabb,bone_aabb);
+ Error err = _surface_set_data(p_blend_shapes[i], format & ~ARRAY_FORMAT_INDEX, offsets, total_elem_size, vertex_array_shape, array_len, noindex, 0, laabb, bone_aabb);
aabb.merge_with(laabb);
if (err) {
ERR_EXPLAIN("Invalid blend shape array format for surface");
- ERR_FAIL_COND(err!=OK);
+ ERR_FAIL_COND(err != OK);
}
blend_shape_data.push_back(vertex_array_shape);
}
- mesh_add_surface(p_mesh,format,p_primitive,vertex_array,array_len,index_array,index_array_len,aabb,blend_shape_data,bone_aabb);
-
+ mesh_add_surface(p_mesh, format, p_primitive, vertex_array, array_len, index_array, index_array_len, aabb, blend_shape_data, bone_aabb);
}
-Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t> p_vertex_data,int p_vertex_len,PoolVector<uint8_t> p_index_data,int p_index_len) const {
-
+Array VisualServer::_get_array_from_surface(uint32_t p_format, PoolVector<uint8_t> p_vertex_data, int p_vertex_len, PoolVector<uint8_t> p_index_data, int p_index_len) const {
uint32_t offsets[ARRAY_MAX];
- int total_elem_size=0;
+ int total_elem_size = 0;
- for (int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
+ offsets[i] = 0; //reset
- offsets[i]=0; //reset
-
- if (!(p_format&(1<<i))) // no array
+ if (!(p_format & (1 << i))) // no array
continue;
+ int elem_size = 0;
- int elem_size=0;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
-
- if (p_format&ARRAY_FLAG_USE_2D_VERTICES) {
- elem_size=2;
+ if (p_format & ARRAY_FLAG_USE_2D_VERTICES) {
+ elem_size = 2;
} else {
- elem_size=3;
+ elem_size = 3;
}
- if (p_format&ARRAY_COMPRESS_VERTEX) {
- elem_size*=sizeof(int16_t);
+ if (p_format & ARRAY_COMPRESS_VERTEX) {
+ elem_size *= sizeof(int16_t);
} else {
- elem_size*=sizeof(float);
+ elem_size *= sizeof(float);
}
- if (elem_size==6) {
- elem_size=8;
+ if (elem_size == 6) {
+ elem_size = 8;
}
} break;
case VS::ARRAY_NORMAL: {
- if (p_format&ARRAY_COMPRESS_NORMAL) {
- elem_size=sizeof(uint32_t);
+ if (p_format & ARRAY_COMPRESS_NORMAL) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*3;
+ elem_size = sizeof(float) * 3;
}
} break;
case VS::ARRAY_TANGENT: {
- if (p_format&ARRAY_COMPRESS_TANGENT) {
- elem_size=sizeof(uint32_t);
+ if (p_format & ARRAY_COMPRESS_TANGENT) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_COLOR: {
- if (p_format&ARRAY_COMPRESS_COLOR) {
- elem_size=sizeof(uint32_t);
+ if (p_format & ARRAY_COMPRESS_COLOR) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_TEX_UV: {
- if (p_format&ARRAY_COMPRESS_TEX_UV) {
- elem_size=sizeof(uint32_t);
+ if (p_format & ARRAY_COMPRESS_TEX_UV) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*2;
+ elem_size = sizeof(float) * 2;
}
} break;
case VS::ARRAY_TEX_UV2: {
- if (p_format&ARRAY_COMPRESS_TEX_UV2) {
- elem_size=sizeof(uint32_t);
+ if (p_format & ARRAY_COMPRESS_TEX_UV2) {
+ elem_size = sizeof(uint32_t);
} else {
- elem_size=sizeof(float)*2;
+ elem_size = sizeof(float) * 2;
}
} break;
case VS::ARRAY_WEIGHTS: {
- if (p_format&ARRAY_COMPRESS_WEIGHTS) {
- elem_size=sizeof(uint16_t)*4;
+ if (p_format & ARRAY_COMPRESS_WEIGHTS) {
+ elem_size = sizeof(uint16_t) * 4;
} else {
- elem_size=sizeof(float)*4;
+ elem_size = sizeof(float) * 4;
}
} break;
case VS::ARRAY_BONES: {
- if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) {
- elem_size=sizeof(uint16_t)*4;
+ if (p_format & ARRAY_FLAG_USE_16_BIT_BONES) {
+ elem_size = sizeof(uint16_t) * 4;
} else {
- elem_size=sizeof(uint32_t);
+ elem_size = sizeof(uint32_t);
}
} break;
case VS::ARRAY_INDEX: {
- if (p_index_len<=0) {
+ if (p_index_len <= 0) {
ERR_PRINT("index_array_len==NO_INDEX_ARRAY");
break;
}
/* determine wether using 16 or 32 bits indices */
- if (p_vertex_len>=(1<<16)) {
+ if (p_vertex_len >= (1 << 16)) {
- elem_size=4;
+ elem_size = 4;
} else {
- elem_size=2;
+ elem_size = 2;
}
- offsets[i]=elem_size;
+ offsets[i] = elem_size;
continue;
} break;
default: {
- ERR_FAIL_V( Array() );
+ ERR_FAIL_V(Array());
}
}
- offsets[i]=total_elem_size;
- total_elem_size+=elem_size;
-
-
+ offsets[i] = total_elem_size;
+ total_elem_size += elem_size;
}
Array ret;
@@ -1245,127 +1160,123 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t
PoolVector<uint8_t>::Read r = p_vertex_data.read();
- for(int i=0;i<VS::ARRAY_MAX;i++) {
+ for (int i = 0; i < VS::ARRAY_MAX; i++) {
- if (!(p_format&(1<<i)))
+ if (!(p_format & (1 << i)))
continue;
-
- switch(i) {
+ switch (i) {
case VS::ARRAY_VERTEX: {
-
- if (p_format&ARRAY_FLAG_USE_2D_VERTICES) {
+ if (p_format & ARRAY_FLAG_USE_2D_VERTICES) {
PoolVector<Vector2> arr_2d;
arr_2d.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_VERTEX) {
+ if (p_format & ARRAY_COMPRESS_VERTEX) {
PoolVector<Vector2>::Write w = arr_2d.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]));
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1]));
}
} else {
PoolVector<Vector2>::Write w = arr_2d.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(v[0],v[1]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(v[0], v[1]);
}
}
- ret[i]=arr_2d;
+ ret[i] = arr_2d;
} else {
PoolVector<Vector3> arr_3d;
arr_3d.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_VERTEX) {
+ if (p_format & ARRAY_COMPRESS_VERTEX) {
PoolVector<Vector3>::Write w = arr_3d.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector3(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]),Math::halfptr_to_float(&v[2]));
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector3(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1]), Math::halfptr_to_float(&v[2]));
}
} else {
PoolVector<Vector3>::Write w = arr_3d.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector3(v[0],v[1],v[2]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector3(v[0], v[1], v[2]);
}
}
- ret[i]=arr_3d;
+ ret[i] = arr_3d;
}
-
} break;
case VS::ARRAY_NORMAL: {
PoolVector<Vector3> arr;
arr.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_NORMAL) {
+ if (p_format & ARRAY_COMPRESS_NORMAL) {
PoolVector<Vector3>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector3( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0 );
+ const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector3(float(v[0] / 255.0) * 2.0 - 1.0, float(v[1] / 255.0) * 2.0 - 1.0, float(v[2] / 255.0) * 2.0 - 1.0);
}
} else {
PoolVector<Vector3>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector3(v[0],v[1],v[2]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector3(v[0], v[1], v[2]);
}
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_TANGENT: {
PoolVector<float> arr;
- arr.resize(p_vertex_len*4);
- if (p_format&ARRAY_COMPRESS_TANGENT) {
+ arr.resize(p_vertex_len * 4);
+ if (p_format & ARRAY_COMPRESS_TANGENT) {
PoolVector<float>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=float(v[k]/255.0)*2.0-1.0;
+ const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = float(v[k] / 255.0) * 2.0 - 1.0;
}
}
} else {
PoolVector<float>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=v[k];
+ for (int j = 0; j < p_vertex_len; j++) {
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = v[k];
}
}
-
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_COLOR: {
@@ -1373,141 +1284,139 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t
PoolVector<Color> arr;
arr.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_COLOR) {
+ if (p_format & ARRAY_COMPRESS_COLOR) {
PoolVector<Color>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Color( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0, float(v[3]/255.0)*2.0-1.0 );
+ const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Color(float(v[0] / 255.0) * 2.0 - 1.0, float(v[1] / 255.0) * 2.0 - 1.0, float(v[2] / 255.0) * 2.0 - 1.0, float(v[3] / 255.0) * 2.0 - 1.0);
}
} else {
PoolVector<Color>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Color(v[0],v[1],v[2],v[3]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Color(v[0], v[1], v[2], v[3]);
}
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_TEX_UV: {
PoolVector<Vector2> arr;
arr.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_TEX_UV) {
+ if (p_format & ARRAY_COMPRESS_TEX_UV) {
PoolVector<Vector2>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]));
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1]));
}
} else {
PoolVector<Vector2>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(v[0],v[1]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(v[0], v[1]);
}
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_TEX_UV2: {
PoolVector<Vector2> arr;
arr.resize(p_vertex_len);
- if (p_format&ARRAY_COMPRESS_TEX_UV2) {
+ if (p_format & ARRAY_COMPRESS_TEX_UV2) {
PoolVector<Vector2>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]));
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(Math::halfptr_to_float(&v[0]), Math::halfptr_to_float(&v[1]));
}
} else {
PoolVector<Vector2>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- w[j]=Vector2(v[0],v[1]);
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ w[j] = Vector2(v[0], v[1]);
}
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_WEIGHTS: {
PoolVector<float> arr;
- arr.resize(p_vertex_len*4);
- if (p_format&ARRAY_COMPRESS_WEIGHTS) {
+ arr.resize(p_vertex_len * 4);
+ if (p_format & ARRAY_COMPRESS_WEIGHTS) {
PoolVector<float>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=float(v[k]/65535.0)*2.0-1.0;
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = float(v[k] / 65535.0) * 2.0 - 1.0;
}
}
} else {
PoolVector<float>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
- const float *v = (const float*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=v[k];
+ for (int j = 0; j < p_vertex_len; j++) {
+ const float *v = (const float *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = v[k];
}
}
-
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_BONES: {
PoolVector<int> arr;
- arr.resize(p_vertex_len*4);
- if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) {
+ arr.resize(p_vertex_len * 4);
+ if (p_format & ARRAY_FLAG_USE_16_BIT_BONES) {
PoolVector<int>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
+ for (int j = 0; j < p_vertex_len; j++) {
- const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=v[k];
+ const uint16_t *v = (const uint16_t *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = v[k];
}
}
} else {
PoolVector<int>::Write w = arr.write();
- for(int j=0;j<p_vertex_len;j++) {
- const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]];
- for(int k=0;k<4;k++) {
- w[j*4+k]=v[k];
+ for (int j = 0; j < p_vertex_len; j++) {
+ const uint8_t *v = (const uint8_t *)&r[j * total_elem_size + offsets[i]];
+ for (int k = 0; k < 4; k++) {
+ w[j * 4 + k] = v[k];
}
}
-
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
case VS::ARRAY_INDEX: {
@@ -1517,29 +1426,28 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t
PoolVector<int> arr;
arr.resize(p_index_len);
- if (p_vertex_len<(1<<16)) {
+ if (p_vertex_len < (1 << 16)) {
PoolVector<int>::Write w = arr.write();
- for(int j=0;j<p_index_len;j++) {
+ for (int j = 0; j < p_index_len; j++) {
- const uint16_t *v = (const uint16_t*)&ir[j*2];
- w[j]=*v;
+ const uint16_t *v = (const uint16_t *)&ir[j * 2];
+ w[j] = *v;
}
} else {
PoolVector<int>::Write w = arr.write();
- for(int j=0;j<p_index_len;j++) {
- const int *v = (const int*)&ir[j*4];
- w[j]=*v;
+ for (int j = 0; j < p_index_len; j++) {
+ const int *v = (const int *)&ir[j * 4];
+ w[j] = *v;
}
-
}
- ret[i]=arr;
+ ret[i] = arr;
} break;
default: {
- ERR_FAIL_V( ret );
+ ERR_FAIL_V(ret);
}
}
}
@@ -1547,141 +1455,118 @@ Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t
return ret;
}
-Array VisualServer::mesh_surface_get_arrays(RID p_mesh,int p_surface) const {
-
- PoolVector<uint8_t> vertex_data = mesh_surface_get_array(p_mesh,p_surface);
- ERR_FAIL_COND_V(vertex_data.size()==0,Array());
- int vertex_len = mesh_surface_get_array_len(p_mesh,p_surface);
-
- PoolVector<uint8_t> index_data = mesh_surface_get_index_array(p_mesh,p_surface);
- int index_len = mesh_surface_get_array_index_len(p_mesh,p_surface);
+Array VisualServer::mesh_surface_get_arrays(RID p_mesh, int p_surface) const {
- uint32_t format = mesh_surface_get_format(p_mesh,p_surface);
+ PoolVector<uint8_t> vertex_data = mesh_surface_get_array(p_mesh, p_surface);
+ ERR_FAIL_COND_V(vertex_data.size() == 0, Array());
+ int vertex_len = mesh_surface_get_array_len(p_mesh, p_surface);
+ PoolVector<uint8_t> index_data = mesh_surface_get_index_array(p_mesh, p_surface);
+ int index_len = mesh_surface_get_array_index_len(p_mesh, p_surface);
- return _get_array_from_surface(format,vertex_data,vertex_len,index_data,index_len);
+ uint32_t format = mesh_surface_get_format(p_mesh, p_surface);
+ return _get_array_from_surface(format, vertex_data, vertex_len, index_data, index_len);
}
void VisualServer::_bind_methods() {
-
- ClassDB::bind_method(D_METHOD("texture_create"),&VisualServer::texture_create);
- ClassDB::bind_method(D_METHOD("texture_create_from_image"),&VisualServer::texture_create_from_image,DEFVAL( TEXTURE_FLAGS_DEFAULT ) );
+ ClassDB::bind_method(D_METHOD("texture_create"), &VisualServer::texture_create);
+ ClassDB::bind_method(D_METHOD("texture_create_from_image"), &VisualServer::texture_create_from_image, DEFVAL(TEXTURE_FLAGS_DEFAULT));
//ClassDB::bind_method(D_METHOD("texture_allocate"),&VisualServer::texture_allocate,DEFVAL( TEXTURE_FLAGS_DEFAULT ) );
//ClassDB::bind_method(D_METHOD("texture_set_data"),&VisualServer::texture_blit_rect,DEFVAL( CUBEMAP_LEFT ) );
//ClassDB::bind_method(D_METHOD("texture_get_rect"),&VisualServer::texture_get_rect );
- ClassDB::bind_method(D_METHOD("texture_set_flags"),&VisualServer::texture_set_flags );
- ClassDB::bind_method(D_METHOD("texture_get_flags"),&VisualServer::texture_get_flags );
- ClassDB::bind_method(D_METHOD("texture_get_width"),&VisualServer::texture_get_width );
- ClassDB::bind_method(D_METHOD("texture_get_height"),&VisualServer::texture_get_height );
-
- ClassDB::bind_method(D_METHOD("texture_set_shrink_all_x2_on_set_data","shrink"),&VisualServer::texture_set_shrink_all_x2_on_set_data );
-
-
-
+ ClassDB::bind_method(D_METHOD("texture_set_flags"), &VisualServer::texture_set_flags);
+ ClassDB::bind_method(D_METHOD("texture_get_flags"), &VisualServer::texture_get_flags);
+ ClassDB::bind_method(D_METHOD("texture_get_width"), &VisualServer::texture_get_width);
+ ClassDB::bind_method(D_METHOD("texture_get_height"), &VisualServer::texture_get_height);
+ ClassDB::bind_method(D_METHOD("texture_set_shrink_all_x2_on_set_data", "shrink"), &VisualServer::texture_set_shrink_all_x2_on_set_data);
}
-void VisualServer::_canvas_item_add_style_box(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector<float>& p_margins, const Color& p_modulate) {
+void VisualServer::_canvas_item_add_style_box(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector<float> &p_margins, const Color &p_modulate) {
- ERR_FAIL_COND(p_margins.size()!=4);
+ ERR_FAIL_COND(p_margins.size() != 4);
//canvas_item_add_style_box(p_item,p_rect,p_source,p_texture,Vector2(p_margins[0],p_margins[1]),Vector2(p_margins[2],p_margins[3]),true,p_modulate);
}
-void VisualServer::_camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far) {
+void VisualServer::_camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) {
- camera_set_orthogonal(p_camera,p_size,p_z_near,p_z_far);
+ camera_set_orthogonal(p_camera, p_size, p_z_near, p_z_far);
}
-
-
-
-
-void VisualServer::mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data) {
+void VisualServer::mesh_add_surface_from_mesh_data(RID p_mesh, const Geometry::MeshData &p_mesh_data) {
#if 1
PoolVector<Vector3> vertices;
PoolVector<Vector3> normals;
- for (int i=0;i<p_mesh_data.faces.size();i++) {
+ for (int i = 0; i < p_mesh_data.faces.size(); i++) {
- const Geometry::MeshData::Face& f = p_mesh_data.faces[i];
+ const Geometry::MeshData::Face &f = p_mesh_data.faces[i];
- for (int j=2;j<f.indices.size();j++) {
+ for (int j = 2; j < f.indices.size(); j++) {
-#define _ADD_VERTEX(m_idx)\
- vertices.push_back( p_mesh_data.vertices[ f.indices[m_idx] ] );\
- normals.push_back( f.plane.normal );
+#define _ADD_VERTEX(m_idx) \
+ vertices.push_back(p_mesh_data.vertices[f.indices[m_idx]]); \
+ normals.push_back(f.plane.normal);
- _ADD_VERTEX( 0 );
- _ADD_VERTEX( j-1 );
- _ADD_VERTEX( j );
+ _ADD_VERTEX(0);
+ _ADD_VERTEX(j - 1);
+ _ADD_VERTEX(j);
}
}
Array d;
d.resize(VS::ARRAY_MAX);
- d[ARRAY_VERTEX]=vertices;
- d[ARRAY_NORMAL]=normals;
- mesh_add_surface_from_arrays(p_mesh,PRIMITIVE_TRIANGLES, d);
+ d[ARRAY_VERTEX] = vertices;
+ d[ARRAY_NORMAL] = normals;
+ mesh_add_surface_from_arrays(p_mesh, PRIMITIVE_TRIANGLES, d);
#else
-
PoolVector<Vector3> vertices;
+ for (int i = 0; i < p_mesh_data.edges.size(); i++) {
-
- for (int i=0;i<p_mesh_data.edges.size();i++) {
-
- const Geometry::MeshData::Edge& f = p_mesh_data.edges[i];
- vertices.push_back(p_mesh_data.vertices[ f.a]);
- vertices.push_back(p_mesh_data.vertices[ f.b]);
+ const Geometry::MeshData::Edge &f = p_mesh_data.edges[i];
+ vertices.push_back(p_mesh_data.vertices[f.a]);
+ vertices.push_back(p_mesh_data.vertices[f.b]);
}
Array d;
d.resize(VS::ARRAY_MAX);
- d[ARRAY_VERTEX]=vertices;
- mesh_add_surface(p_mesh,PRIMITIVE_LINES, d);
-
-
-
+ d[ARRAY_VERTEX] = vertices;
+ mesh_add_surface(p_mesh, PRIMITIVE_LINES, d);
#endif
-
}
-void VisualServer::mesh_add_surface_from_planes( RID p_mesh, const PoolVector<Plane>& p_planes) {
-
+void VisualServer::mesh_add_surface_from_planes(RID p_mesh, const PoolVector<Plane> &p_planes) {
Geometry::MeshData mdata = Geometry::build_convex_mesh(p_planes);
- mesh_add_surface_from_mesh_data(p_mesh,mdata);
-
+ mesh_add_surface_from_mesh_data(p_mesh, mdata);
}
-void VisualServer::immediate_vertex_2d(RID p_immediate,const Vector2& p_vertex) {
- immediate_vertex(p_immediate,Vector3(p_vertex.x,p_vertex.y,0));
+void VisualServer::immediate_vertex_2d(RID p_immediate, const Vector2 &p_vertex) {
+ immediate_vertex(p_immediate, Vector3(p_vertex.x, p_vertex.y, 0));
}
RID VisualServer::instance_create2(RID p_base, RID p_scenario) {
RID instance = instance_create();
- instance_set_base(instance,p_base);
- instance_set_scenario(instance,p_scenario);
+ instance_set_base(instance, p_base);
+ instance_set_scenario(instance, p_scenario);
return instance;
}
-
VisualServer::VisualServer() {
//ERR_FAIL_COND(singleton);
- singleton=this;
-
+ singleton = this;
}
-
VisualServer::~VisualServer() {
- singleton=NULL;
+ singleton = NULL;
}
diff --git a/servers/visual_server.h b/servers/visual_server.h
index 08cf34a653..dfa253ff25 100644
--- a/servers/visual_server.h
+++ b/servers/visual_server.h
@@ -29,29 +29,28 @@
#ifndef VISUAL_SERVER_H
#define VISUAL_SERVER_H
-
-#include "rid.h"
-#include "variant.h"
-#include "math_2d.h"
#include "bsp_tree.h"
#include "geometry.h"
+#include "math_2d.h"
#include "object.h"
+#include "rid.h"
+#include "variant.h"
/**
@author Juan Linietsky <reduzio@gmail.com>
*/
class VisualServer : public Object {
- GDCLASS( VisualServer, Object );
+ GDCLASS(VisualServer, Object);
static VisualServer *singleton;
int mm_policy;
PoolVector<String> _shader_get_param_list(RID p_shader) const;
- void _camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far);
- void _canvas_item_add_style_box(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector<float>& p_margins, const Color& p_modulate=Color(1,1,1));
- Array _get_array_from_surface(uint32_t p_format,PoolVector<uint8_t> p_vertex_data,int p_vertex_len,PoolVector<uint8_t> p_index_data,int p_index_len) const;
+ void _camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far);
+ void _canvas_item_add_style_box(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector<float> &p_margins, const Color &p_modulate = Color(1, 1, 1));
+ Array _get_array_from_surface(uint32_t p_format, PoolVector<uint8_t> p_vertex_data, int p_vertex_len, PoolVector<uint8_t> p_index_data, int p_index_len) const;
protected:
RID _make_test_cube();
@@ -61,28 +60,22 @@ protected:
RID test_material;
RID material_2d[16];
+ Error _surface_set_data(Array p_arrays, uint32_t p_format, uint32_t *p_offsets, uint32_t p_stride, PoolVector<uint8_t> &r_vertex_array, int p_vertex_array_len, PoolVector<uint8_t> &r_index_array, int p_index_array_len, Rect3 &r_aabb, Vector<Rect3> r_bone_aabb);
- Error _surface_set_data(Array p_arrays,uint32_t p_format,uint32_t *p_offsets,uint32_t p_stride,PoolVector<uint8_t> &r_vertex_array,int p_vertex_array_len,PoolVector<uint8_t> &r_index_array,int p_index_array_len,Rect3 &r_aabb,Vector<Rect3> r_bone_aabb);
-
- static VisualServer* (*create_func)();
+ static VisualServer *(*create_func)();
static void _bind_methods();
-public:
+public:
static VisualServer *get_singleton();
static VisualServer *create();
-
-
enum {
- NO_INDEX_ARRAY=-1,
- ARRAY_WEIGHTS_SIZE=4,
- CANVAS_ITEM_Z_MIN=-4096,
- CANVAS_ITEM_Z_MAX=4096,
- MAX_GLOW_LEVELS=7,
-
-
-
+ NO_INDEX_ARRAY = -1,
+ ARRAY_WEIGHTS_SIZE = 4,
+ CANVAS_ITEM_Z_MIN = -4096,
+ CANVAS_ITEM_Z_MAX = 4096,
+ MAX_GLOW_LEVELS = 7,
MAX_CURSORS = 8,
};
@@ -90,15 +83,15 @@ public:
/* TEXTURE API */
enum TextureFlags {
- TEXTURE_FLAG_MIPMAPS=1, /// Enable automatic mipmap generation - when available
- TEXTURE_FLAG_REPEAT=2, /// Repeat texture (Tiling), otherwise Clamping
- TEXTURE_FLAG_FILTER=4, /// Create texure with linear (or available) filter
- TEXTURE_FLAG_ANISOTROPIC_FILTER=8,
- TEXTURE_FLAG_CONVERT_TO_LINEAR=16,
- TEXTURE_FLAG_MIRRORED_REPEAT=32, /// Repeat texture, with alternate sections mirrored
- TEXTURE_FLAG_CUBEMAP=2048,
- TEXTURE_FLAG_USED_FOR_STREAMING=4096,
- TEXTURE_FLAGS_DEFAULT=TEXTURE_FLAG_REPEAT|TEXTURE_FLAG_MIPMAPS|TEXTURE_FLAG_FILTER
+ TEXTURE_FLAG_MIPMAPS = 1, /// Enable automatic mipmap generation - when available
+ TEXTURE_FLAG_REPEAT = 2, /// Repeat texture (Tiling), otherwise Clamping
+ TEXTURE_FLAG_FILTER = 4, /// Create texure with linear (or available) filter
+ TEXTURE_FLAG_ANISOTROPIC_FILTER = 8,
+ TEXTURE_FLAG_CONVERT_TO_LINEAR = 16,
+ TEXTURE_FLAG_MIRRORED_REPEAT = 32, /// Repeat texture, with alternate sections mirrored
+ TEXTURE_FLAG_CUBEMAP = 2048,
+ TEXTURE_FLAG_USED_FOR_STREAMING = 4096,
+ TEXTURE_FLAGS_DEFAULT = TEXTURE_FLAG_REPEAT | TEXTURE_FLAG_MIPMAPS | TEXTURE_FLAG_FILTER
};
enum CubeMapSide {
@@ -111,28 +104,27 @@ public:
CUBEMAP_BACK
};
+ virtual RID texture_create() = 0;
+ RID texture_create_from_image(const Image &p_image, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT); // helper
+ virtual void texture_allocate(RID p_texture, int p_width, int p_height, Image::Format p_format, uint32_t p_flags = TEXTURE_FLAGS_DEFAULT) = 0;
+ virtual void texture_set_data(RID p_texture, const Image &p_image, CubeMapSide p_cube_side = CUBEMAP_LEFT) = 0;
+ virtual Image texture_get_data(RID p_texture, CubeMapSide p_cube_side = CUBEMAP_LEFT) const = 0;
+ virtual void texture_set_flags(RID p_texture, uint32_t p_flags) = 0;
+ virtual uint32_t texture_get_flags(RID p_texture) const = 0;
+ virtual Image::Format texture_get_format(RID p_texture) const = 0;
+ virtual uint32_t texture_get_width(RID p_texture) const = 0;
+ virtual uint32_t texture_get_height(RID p_texture) const = 0;
+ virtual void texture_set_size_override(RID p_texture, int p_width, int p_height) = 0;
- virtual RID texture_create()=0;
- RID texture_create_from_image(const Image& p_image,uint32_t p_flags=TEXTURE_FLAGS_DEFAULT); // helper
- virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=TEXTURE_FLAGS_DEFAULT)=0;
- virtual void texture_set_data(RID p_texture,const Image& p_image,CubeMapSide p_cube_side=CUBEMAP_LEFT)=0;
- virtual Image texture_get_data(RID p_texture,CubeMapSide p_cube_side=CUBEMAP_LEFT) const=0;
- virtual void texture_set_flags(RID p_texture,uint32_t p_flags) =0;
- virtual uint32_t texture_get_flags(RID p_texture) const=0;
- virtual Image::Format texture_get_format(RID p_texture) const=0;
- virtual uint32_t texture_get_width(RID p_texture) const=0;
- virtual uint32_t texture_get_height(RID p_texture) const=0;
- virtual void texture_set_size_override(RID p_texture,int p_width, int p_height)=0;
+ virtual void texture_set_path(RID p_texture, const String &p_path) = 0;
+ virtual String texture_get_path(RID p_texture) const = 0;
- virtual void texture_set_path(RID p_texture,const String& p_path)=0;
- virtual String texture_get_path(RID p_texture) const=0;
+ virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable) = 0;
- virtual void texture_set_shrink_all_x2_on_set_data(bool p_enable)=0;
+ typedef void (*TextureDetectCallback)(void *);
- typedef void (*TextureDetectCallback)(void*);
-
- virtual void texture_set_detect_3d_callback(RID p_texture,TextureDetectCallback p_callback,void* p_userdata)=0;
- virtual void texture_set_detect_srgb_callback(RID p_texture,TextureDetectCallback p_callback,void* p_userdata)=0;
+ virtual void texture_set_detect_3d_callback(RID p_texture, TextureDetectCallback p_callback, void *p_userdata) = 0;
+ virtual void texture_set_detect_srgb_callback(RID p_texture, TextureDetectCallback p_callback, void *p_userdata) = 0;
struct TextureInfo {
RID texture;
@@ -142,14 +134,14 @@ public:
String path;
};
- virtual void texture_debug_usage(List<TextureInfo> *r_info)=0;
+ virtual void texture_debug_usage(List<TextureInfo> *r_info) = 0;
- virtual void textures_keep_original(bool p_enable)=0;
+ virtual void textures_keep_original(bool p_enable) = 0;
/* SKYBOX API */
- virtual RID skybox_create()=0;
- virtual void skybox_set_texture(RID p_skybox,RID p_cube_map,int p_radiance_size)=0;
+ virtual RID skybox_create() = 0;
+ virtual void skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size) = 0;
/* SHADER API */
@@ -161,137 +153,132 @@ public:
SHADER_MAX
};
+ virtual RID shader_create(ShaderMode p_mode = SHADER_SPATIAL) = 0;
- virtual RID shader_create(ShaderMode p_mode=SHADER_SPATIAL)=0;
-
- virtual void shader_set_mode(RID p_shader,ShaderMode p_mode)=0;
- virtual ShaderMode shader_get_mode(RID p_shader) const=0;
-
- virtual void shader_set_code(RID p_shader, const String& p_code)=0;
- virtual String shader_get_code(RID p_shader) const=0;
- virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const=0;
+ virtual void shader_set_mode(RID p_shader, ShaderMode p_mode) = 0;
+ virtual ShaderMode shader_get_mode(RID p_shader) const = 0;
- virtual void shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture)=0;
- virtual RID shader_get_default_texture_param(RID p_shader, const StringName& p_name) const=0;
+ virtual void shader_set_code(RID p_shader, const String &p_code) = 0;
+ virtual String shader_get_code(RID p_shader) const = 0;
+ virtual void shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const = 0;
+ virtual void shader_set_default_texture_param(RID p_shader, const StringName &p_name, RID p_texture) = 0;
+ virtual RID shader_get_default_texture_param(RID p_shader, const StringName &p_name) const = 0;
/* COMMON MATERIAL API */
- virtual RID material_create()=0;
+ virtual RID material_create() = 0;
- virtual void material_set_shader(RID p_shader_material, RID p_shader)=0;
- virtual RID material_get_shader(RID p_shader_material) const=0;
+ virtual void material_set_shader(RID p_shader_material, RID p_shader) = 0;
+ virtual RID material_get_shader(RID p_shader_material) const = 0;
- virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value)=0;
- virtual Variant material_get_param(RID p_material, const StringName& p_param) const=0;
+ virtual void material_set_param(RID p_material, const StringName &p_param, const Variant &p_value) = 0;
+ virtual Variant material_get_param(RID p_material, const StringName &p_param) const = 0;
- virtual void material_set_line_width(RID p_material, float p_width)=0;
+ virtual void material_set_line_width(RID p_material, float p_width) = 0;
/* MESH API */
enum ArrayType {
- ARRAY_VERTEX=0,
- ARRAY_NORMAL=1,
- ARRAY_TANGENT=2,
- ARRAY_COLOR=3,
- ARRAY_TEX_UV=4,
- ARRAY_TEX_UV2=5,
- ARRAY_BONES=6,
- ARRAY_WEIGHTS=7,
- ARRAY_INDEX=8,
- ARRAY_MAX=9
+ ARRAY_VERTEX = 0,
+ ARRAY_NORMAL = 1,
+ ARRAY_TANGENT = 2,
+ ARRAY_COLOR = 3,
+ ARRAY_TEX_UV = 4,
+ ARRAY_TEX_UV2 = 5,
+ ARRAY_BONES = 6,
+ ARRAY_WEIGHTS = 7,
+ ARRAY_INDEX = 8,
+ ARRAY_MAX = 9
};
enum ArrayFormat {
/* ARRAY FORMAT FLAGS */
- ARRAY_FORMAT_VERTEX=1<<ARRAY_VERTEX, // mandatory
- ARRAY_FORMAT_NORMAL=1<<ARRAY_NORMAL,
- ARRAY_FORMAT_TANGENT=1<<ARRAY_TANGENT,
- ARRAY_FORMAT_COLOR=1<<ARRAY_COLOR,
- ARRAY_FORMAT_TEX_UV=1<<ARRAY_TEX_UV,
- ARRAY_FORMAT_TEX_UV2=1<<ARRAY_TEX_UV2,
- ARRAY_FORMAT_BONES=1<<ARRAY_BONES,
- ARRAY_FORMAT_WEIGHTS=1<<ARRAY_WEIGHTS,
- ARRAY_FORMAT_INDEX=1<<ARRAY_INDEX,
-
- ARRAY_COMPRESS_BASE=(ARRAY_INDEX+1),
- ARRAY_COMPRESS_VERTEX=1<<(ARRAY_VERTEX+ARRAY_COMPRESS_BASE), // mandatory
- ARRAY_COMPRESS_NORMAL=1<<(ARRAY_NORMAL+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TANGENT=1<<(ARRAY_TANGENT+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_COLOR=1<<(ARRAY_COLOR+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TEX_UV=1<<(ARRAY_TEX_UV+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_TEX_UV2=1<<(ARRAY_TEX_UV2+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_BONES=1<<(ARRAY_BONES+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_WEIGHTS=1<<(ARRAY_WEIGHTS+ARRAY_COMPRESS_BASE),
- ARRAY_COMPRESS_INDEX=1<<(ARRAY_INDEX+ARRAY_COMPRESS_BASE),
-
- ARRAY_FLAG_USE_2D_VERTICES=ARRAY_COMPRESS_INDEX<<1,
- ARRAY_FLAG_USE_16_BIT_BONES=ARRAY_COMPRESS_INDEX<<2,
-
- ARRAY_COMPRESS_DEFAULT=ARRAY_COMPRESS_VERTEX|ARRAY_COMPRESS_NORMAL|ARRAY_COMPRESS_TANGENT|ARRAY_COMPRESS_COLOR|ARRAY_COMPRESS_TEX_UV|ARRAY_COMPRESS_TEX_UV2|ARRAY_COMPRESS_WEIGHTS
+ ARRAY_FORMAT_VERTEX = 1 << ARRAY_VERTEX, // mandatory
+ ARRAY_FORMAT_NORMAL = 1 << ARRAY_NORMAL,
+ ARRAY_FORMAT_TANGENT = 1 << ARRAY_TANGENT,
+ ARRAY_FORMAT_COLOR = 1 << ARRAY_COLOR,
+ ARRAY_FORMAT_TEX_UV = 1 << ARRAY_TEX_UV,
+ ARRAY_FORMAT_TEX_UV2 = 1 << ARRAY_TEX_UV2,
+ ARRAY_FORMAT_BONES = 1 << ARRAY_BONES,
+ ARRAY_FORMAT_WEIGHTS = 1 << ARRAY_WEIGHTS,
+ ARRAY_FORMAT_INDEX = 1 << ARRAY_INDEX,
+
+ ARRAY_COMPRESS_BASE = (ARRAY_INDEX + 1),
+ ARRAY_COMPRESS_VERTEX = 1 << (ARRAY_VERTEX + ARRAY_COMPRESS_BASE), // mandatory
+ ARRAY_COMPRESS_NORMAL = 1 << (ARRAY_NORMAL + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TANGENT = 1 << (ARRAY_TANGENT + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_COLOR = 1 << (ARRAY_COLOR + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TEX_UV = 1 << (ARRAY_TEX_UV + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_TEX_UV2 = 1 << (ARRAY_TEX_UV2 + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_BONES = 1 << (ARRAY_BONES + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_WEIGHTS = 1 << (ARRAY_WEIGHTS + ARRAY_COMPRESS_BASE),
+ ARRAY_COMPRESS_INDEX = 1 << (ARRAY_INDEX + ARRAY_COMPRESS_BASE),
+
+ ARRAY_FLAG_USE_2D_VERTICES = ARRAY_COMPRESS_INDEX << 1,
+ ARRAY_FLAG_USE_16_BIT_BONES = ARRAY_COMPRESS_INDEX << 2,
+
+ ARRAY_COMPRESS_DEFAULT = ARRAY_COMPRESS_VERTEX | ARRAY_COMPRESS_NORMAL | ARRAY_COMPRESS_TANGENT | ARRAY_COMPRESS_COLOR | ARRAY_COMPRESS_TEX_UV | ARRAY_COMPRESS_TEX_UV2 | ARRAY_COMPRESS_WEIGHTS
};
-
enum PrimitiveType {
- PRIMITIVE_POINTS=0,
- PRIMITIVE_LINES=1,
- PRIMITIVE_LINE_STRIP=2,
- PRIMITIVE_LINE_LOOP=3,
- PRIMITIVE_TRIANGLES=4,
- PRIMITIVE_TRIANGLE_STRIP=5,
- PRIMITIVE_TRIANGLE_FAN=6,
- PRIMITIVE_MAX=7,
+ PRIMITIVE_POINTS = 0,
+ PRIMITIVE_LINES = 1,
+ PRIMITIVE_LINE_STRIP = 2,
+ PRIMITIVE_LINE_LOOP = 3,
+ PRIMITIVE_TRIANGLES = 4,
+ PRIMITIVE_TRIANGLE_STRIP = 5,
+ PRIMITIVE_TRIANGLE_FAN = 6,
+ PRIMITIVE_MAX = 7,
};
- virtual RID mesh_create()=0;
-
+ virtual RID mesh_create() = 0;
- virtual void mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes=Array(),uint32_t p_compress_format=ARRAY_COMPRESS_DEFAULT);
- virtual void mesh_add_surface(RID p_mesh,uint32_t p_format,PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes=Vector<PoolVector<uint8_t> >(),const Vector<Rect3>& p_bone_aabbs=Vector<Rect3>())=0;
+ virtual void mesh_add_surface_from_arrays(RID p_mesh, PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes = Array(), uint32_t p_compress_format = ARRAY_COMPRESS_DEFAULT);
+ virtual void mesh_add_surface(RID p_mesh, uint32_t p_format, PrimitiveType p_primitive, const PoolVector<uint8_t> &p_array, int p_vertex_count, const PoolVector<uint8_t> &p_index_array, int p_index_count, const Rect3 &p_aabb, const Vector<PoolVector<uint8_t> > &p_blend_shapes = Vector<PoolVector<uint8_t> >(), const Vector<Rect3> &p_bone_aabbs = Vector<Rect3>()) = 0;
- virtual void mesh_set_blend_shape_count(RID p_mesh,int p_amount)=0;
- virtual int mesh_get_blend_shape_count(RID p_mesh) const=0;
+ virtual void mesh_set_blend_shape_count(RID p_mesh, int p_amount) = 0;
+ virtual int mesh_get_blend_shape_count(RID p_mesh) const = 0;
enum BlendShapeMode {
BLEND_SHAPE_MODE_NORMALIZED,
BLEND_SHAPE_MODE_RELATIVE,
};
- virtual void mesh_set_blend_shape_mode(RID p_mesh,BlendShapeMode p_mode)=0;
- virtual BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const=0;
+ virtual void mesh_set_blend_shape_mode(RID p_mesh, BlendShapeMode p_mode) = 0;
+ virtual BlendShapeMode mesh_get_blend_shape_mode(RID p_mesh) const = 0;
- virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material)=0;
- virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const=0;
+ virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material) = 0;
+ virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const = 0;
- virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const=0;
- virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const=0;
+ virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const = 0;
+ virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const = 0;
- virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const=0;
- virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const=0;
+ virtual PoolVector<uint8_t> mesh_surface_get_array(RID p_mesh, int p_surface) const = 0;
+ virtual PoolVector<uint8_t> mesh_surface_get_index_array(RID p_mesh, int p_surface) const = 0;
- virtual Array mesh_surface_get_arrays(RID p_mesh,int p_surface) const;
+ virtual Array mesh_surface_get_arrays(RID p_mesh, int p_surface) const;
- virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const=0;
- virtual PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const=0;
+ virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const = 0;
+ virtual PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const = 0;
- virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const=0;
- virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const=0;
- virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const=0;
+ virtual Rect3 mesh_surface_get_aabb(RID p_mesh, int p_surface) const = 0;
+ virtual Vector<PoolVector<uint8_t> > mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const = 0;
+ virtual Vector<Rect3> mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const = 0;
- virtual void mesh_remove_surface(RID p_mesh,int p_index)=0;
- virtual int mesh_get_surface_count(RID p_mesh) const=0;
+ virtual void mesh_remove_surface(RID p_mesh, int p_index) = 0;
+ virtual int mesh_get_surface_count(RID p_mesh) const = 0;
- virtual void mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb)=0;
- virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const=0;
+ virtual void mesh_set_custom_aabb(RID p_mesh, const Rect3 &p_aabb) = 0;
+ virtual Rect3 mesh_get_custom_aabb(RID p_mesh) const = 0;
- virtual void mesh_clear(RID p_mesh)=0;
+ virtual void mesh_clear(RID p_mesh) = 0;
/* MULTIMESH API */
-
- virtual RID multimesh_create()=0;
+ virtual RID multimesh_create() = 0;
enum MultimeshTransformFormat {
MULTIMESH_TRANSFORM_2D,
@@ -304,50 +291,49 @@ public:
MULTIMESH_COLOR_FLOAT,
};
- virtual void multimesh_allocate(RID p_multimesh,int p_instances,MultimeshTransformFormat p_transform_format,MultimeshColorFormat p_color_format)=0;
- virtual int multimesh_get_instance_count(RID p_multimesh) const=0;
-
- virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh)=0;
- virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform)=0;
- virtual void multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform)=0;
- virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color)=0;
+ virtual void multimesh_allocate(RID p_multimesh, int p_instances, MultimeshTransformFormat p_transform_format, MultimeshColorFormat p_color_format) = 0;
+ virtual int multimesh_get_instance_count(RID p_multimesh) const = 0;
- virtual RID multimesh_get_mesh(RID p_multimesh) const=0;
- virtual Rect3 multimesh_get_aabb(RID p_multimesh) const=0;
+ virtual void multimesh_set_mesh(RID p_multimesh, RID p_mesh) = 0;
+ virtual void multimesh_instance_set_transform(RID p_multimesh, int p_index, const Transform &p_transform) = 0;
+ virtual void multimesh_instance_set_transform_2d(RID p_multimesh, int p_index, const Transform2D &p_transform) = 0;
+ virtual void multimesh_instance_set_color(RID p_multimesh, int p_index, const Color &p_color) = 0;
- virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const=0;
- virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const=0;
- virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const=0;
+ virtual RID multimesh_get_mesh(RID p_multimesh) const = 0;
+ virtual Rect3 multimesh_get_aabb(RID p_multimesh) const = 0;
- virtual void multimesh_set_visible_instances(RID p_multimesh,int p_visible)=0;
- virtual int multimesh_get_visible_instances(RID p_multimesh) const=0;
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh, int p_index) const = 0;
+ virtual Transform2D multimesh_instance_get_transform_2d(RID p_multimesh, int p_index) const = 0;
+ virtual Color multimesh_instance_get_color(RID p_multimesh, int p_index) const = 0;
+ virtual void multimesh_set_visible_instances(RID p_multimesh, int p_visible) = 0;
+ virtual int multimesh_get_visible_instances(RID p_multimesh) const = 0;
/* IMMEDIATE API */
- virtual RID immediate_create()=0;
- virtual void immediate_begin(RID p_immediate,PrimitiveType p_rimitive,RID p_texture=RID())=0;
- virtual void immediate_vertex(RID p_immediate,const Vector3& p_vertex)=0;
- virtual void immediate_vertex_2d(RID p_immediate,const Vector2& p_vertex);
- virtual void immediate_normal(RID p_immediate,const Vector3& p_normal)=0;
- virtual void immediate_tangent(RID p_immediate,const Plane& p_tangent)=0;
- virtual void immediate_color(RID p_immediate,const Color& p_color)=0;
- virtual void immediate_uv(RID p_immediate,const Vector2& tex_uv)=0;
- virtual void immediate_uv2(RID p_immediate,const Vector2& tex_uv)=0;
- virtual void immediate_end(RID p_immediate)=0;
- virtual void immediate_clear(RID p_immediate)=0;
- virtual void immediate_set_material(RID p_immediate,RID p_material)=0;
- virtual RID immediate_get_material(RID p_immediate) const=0;
+ virtual RID immediate_create() = 0;
+ virtual void immediate_begin(RID p_immediate, PrimitiveType p_rimitive, RID p_texture = RID()) = 0;
+ virtual void immediate_vertex(RID p_immediate, const Vector3 &p_vertex) = 0;
+ virtual void immediate_vertex_2d(RID p_immediate, const Vector2 &p_vertex);
+ virtual void immediate_normal(RID p_immediate, const Vector3 &p_normal) = 0;
+ virtual void immediate_tangent(RID p_immediate, const Plane &p_tangent) = 0;
+ virtual void immediate_color(RID p_immediate, const Color &p_color) = 0;
+ virtual void immediate_uv(RID p_immediate, const Vector2 &tex_uv) = 0;
+ virtual void immediate_uv2(RID p_immediate, const Vector2 &tex_uv) = 0;
+ virtual void immediate_end(RID p_immediate) = 0;
+ virtual void immediate_clear(RID p_immediate) = 0;
+ virtual void immediate_set_material(RID p_immediate, RID p_material) = 0;
+ virtual RID immediate_get_material(RID p_immediate) const = 0;
/* SKELETON API */
- virtual RID skeleton_create()=0;
- virtual void skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton=false)=0;
- virtual int skeleton_get_bone_count(RID p_skeleton) const=0;
- virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform)=0;
- virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone) const=0;
- virtual void skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform)=0;
- virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone)const =0;
+ virtual RID skeleton_create() = 0;
+ virtual void skeleton_allocate(RID p_skeleton, int p_bones, bool p_2d_skeleton = false) = 0;
+ virtual int skeleton_get_bone_count(RID p_skeleton) const = 0;
+ virtual void skeleton_bone_set_transform(RID p_skeleton, int p_bone, const Transform &p_transform) = 0;
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton, int p_bone) const = 0;
+ virtual void skeleton_bone_set_transform_2d(RID p_skeleton, int p_bone, const Transform2D &p_transform) = 0;
+ virtual Transform2D skeleton_bone_get_transform_2d(RID p_skeleton, int p_bone) const = 0;
/* Light API */
@@ -376,15 +362,15 @@ public:
LIGHT_PARAM_MAX
};
- virtual RID light_create(LightType p_type)=0;
+ virtual RID light_create(LightType p_type) = 0;
- virtual void light_set_color(RID p_light,const Color& p_color)=0;
- virtual void light_set_param(RID p_light,LightParam p_param,float p_value)=0;
- virtual void light_set_shadow(RID p_light,bool p_enabled)=0;
- virtual void light_set_shadow_color(RID p_light,const Color& p_color)=0;
- virtual void light_set_projector(RID p_light,RID p_texture)=0;
- virtual void light_set_negative(RID p_light,bool p_enable)=0;
- virtual void light_set_cull_mask(RID p_light,uint32_t p_mask)=0;
+ virtual void light_set_color(RID p_light, const Color &p_color) = 0;
+ virtual void light_set_param(RID p_light, LightParam p_param, float p_value) = 0;
+ virtual void light_set_shadow(RID p_light, bool p_enabled) = 0;
+ virtual void light_set_shadow_color(RID p_light, const Color &p_color) = 0;
+ virtual void light_set_projector(RID p_light, RID p_texture) = 0;
+ virtual void light_set_negative(RID p_light, bool p_enable) = 0;
+ virtual void light_set_cull_mask(RID p_light, uint32_t p_mask) = 0;
// omni light
enum LightOmniShadowMode {
@@ -392,7 +378,7 @@ public:
LIGHT_OMNI_SHADOW_CUBE,
};
- virtual void light_omni_set_shadow_mode(RID p_light,LightOmniShadowMode p_mode)=0;
+ virtual void light_omni_set_shadow_mode(RID p_light, LightOmniShadowMode p_mode) = 0;
// omni light
enum LightOmniShadowDetail {
@@ -400,7 +386,7 @@ public:
LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL
};
- virtual void light_omni_set_shadow_detail(RID p_light,LightOmniShadowDetail p_detail)=0;
+ virtual void light_omni_set_shadow_detail(RID p_light, LightOmniShadowDetail p_detail) = 0;
// directional light
enum LightDirectionalShadowMode {
@@ -409,98 +395,96 @@ public:
LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS
};
- virtual void light_directional_set_shadow_mode(RID p_light,LightDirectionalShadowMode p_mode)=0;
- virtual void light_directional_set_blend_splits(RID p_light,bool p_enable)=0;
+ virtual void light_directional_set_shadow_mode(RID p_light, LightDirectionalShadowMode p_mode) = 0;
+ virtual void light_directional_set_blend_splits(RID p_light, bool p_enable) = 0;
/* PROBE API */
- virtual RID reflection_probe_create()=0;
+ virtual RID reflection_probe_create() = 0;
enum ReflectionProbeUpdateMode {
REFLECTION_PROBE_UPDATE_ONCE,
REFLECTION_PROBE_UPDATE_ALWAYS,
};
-
- virtual void reflection_probe_set_update_mode(RID p_probe, ReflectionProbeUpdateMode p_mode)=0;
- virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity)=0;
- virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color& p_color)=0;
- virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy)=0;
- virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib)=0;
- virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance)=0;
- virtual void reflection_probe_set_extents(RID p_probe, const Vector3& p_extents)=0;
- virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset)=0;
- virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable)=0;
- virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers)=0;
-
+ virtual void reflection_probe_set_update_mode(RID p_probe, ReflectionProbeUpdateMode p_mode) = 0;
+ virtual void reflection_probe_set_intensity(RID p_probe, float p_intensity) = 0;
+ virtual void reflection_probe_set_interior_ambient(RID p_probe, const Color &p_color) = 0;
+ virtual void reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) = 0;
+ virtual void reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) = 0;
+ virtual void reflection_probe_set_max_distance(RID p_probe, float p_distance) = 0;
+ virtual void reflection_probe_set_extents(RID p_probe, const Vector3 &p_extents) = 0;
+ virtual void reflection_probe_set_origin_offset(RID p_probe, const Vector3 &p_offset) = 0;
+ virtual void reflection_probe_set_as_interior(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_enable_shadows(RID p_probe, bool p_enable) = 0;
+ virtual void reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers) = 0;
/* ROOM API */
- virtual RID room_create()=0;
- virtual void room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform)=0;
- virtual void room_clear_bounds(RID p_room)=0;
+ virtual RID room_create() = 0;
+ virtual void room_add_bounds(RID p_room, const PoolVector<Vector2> &p_convex_polygon, float p_height, const Transform &p_transform) = 0;
+ virtual void room_clear_bounds(RID p_room) = 0;
/* PORTAL API */
// portals are only (x/y) points, forming a convex shape, which its clockwise
// order points outside. (z is 0);
- virtual RID portal_create()=0;
- virtual void portal_set_shape(RID p_portal, const Vector<Point2>& p_shape)=0;
- virtual void portal_set_enabled(RID p_portal, bool p_enabled)=0;
- virtual void portal_set_disable_distance(RID p_portal, float p_distance)=0;
- virtual void portal_set_disabled_color(RID p_portal, const Color& p_color)=0;
+ virtual RID portal_create() = 0;
+ virtual void portal_set_shape(RID p_portal, const Vector<Point2> &p_shape) = 0;
+ virtual void portal_set_enabled(RID p_portal, bool p_enabled) = 0;
+ virtual void portal_set_disable_distance(RID p_portal, float p_distance) = 0;
+ virtual void portal_set_disabled_color(RID p_portal, const Color &p_color) = 0;
/* GI PROBE API */
- virtual RID gi_probe_create()=0;
+ virtual RID gi_probe_create() = 0;
- virtual void gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds)=0;
- virtual Rect3 gi_probe_get_bounds(RID p_probe) const=0;
+ virtual void gi_probe_set_bounds(RID p_probe, const Rect3 &p_bounds) = 0;
+ virtual Rect3 gi_probe_get_bounds(RID p_probe) const = 0;
- virtual void gi_probe_set_cell_size(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_cell_size(RID p_probe) const=0;
+ virtual void gi_probe_set_cell_size(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_cell_size(RID p_probe) const = 0;
- virtual void gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform)=0;
- virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const=0;
+ virtual void gi_probe_set_to_cell_xform(RID p_probe, const Transform &p_xform) = 0;
+ virtual Transform gi_probe_get_to_cell_xform(RID p_probe) const = 0;
- virtual void gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data)=0;
- virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const=0;
+ virtual void gi_probe_set_dynamic_data(RID p_probe, const PoolVector<int> &p_data) = 0;
+ virtual PoolVector<int> gi_probe_get_dynamic_data(RID p_probe) const = 0;
- virtual void gi_probe_set_dynamic_range(RID p_probe,int p_range)=0;
- virtual int gi_probe_get_dynamic_range(RID p_probe) const=0;
+ virtual void gi_probe_set_dynamic_range(RID p_probe, int p_range) = 0;
+ virtual int gi_probe_get_dynamic_range(RID p_probe) const = 0;
- virtual void gi_probe_set_energy(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_energy(RID p_probe) const=0;
+ virtual void gi_probe_set_energy(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_energy(RID p_probe) const = 0;
- virtual void gi_probe_set_bias(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_bias(RID p_probe) const=0;
+ virtual void gi_probe_set_bias(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_bias(RID p_probe) const = 0;
- virtual void gi_probe_set_propagation(RID p_probe,float p_range)=0;
- virtual float gi_probe_get_propagation(RID p_probe) const=0;
+ virtual void gi_probe_set_propagation(RID p_probe, float p_range) = 0;
+ virtual float gi_probe_get_propagation(RID p_probe) const = 0;
- virtual void gi_probe_set_interior(RID p_probe,bool p_enable)=0;
- virtual bool gi_probe_is_interior(RID p_probe) const=0;
+ virtual void gi_probe_set_interior(RID p_probe, bool p_enable) = 0;
+ virtual bool gi_probe_is_interior(RID p_probe) const = 0;
- virtual void gi_probe_set_compress(RID p_probe,bool p_enable)=0;
- virtual bool gi_probe_is_compressed(RID p_probe) const=0;
+ virtual void gi_probe_set_compress(RID p_probe, bool p_enable) = 0;
+ virtual bool gi_probe_is_compressed(RID p_probe) const = 0;
/* PARTICLES API */
- virtual RID particles_create()=0;
+ virtual RID particles_create() = 0;
- virtual void particles_set_emitting(RID p_particles,bool p_emitting)=0;
- virtual void particles_set_amount(RID p_particles,int p_amount)=0;
- virtual void particles_set_lifetime(RID p_particles,float p_lifetime)=0;
- virtual void particles_set_pre_process_time(RID p_particles,float p_time)=0;
- virtual void particles_set_explosiveness_ratio(RID p_particles,float p_ratio)=0;
- virtual void particles_set_randomness_ratio(RID p_particles,float p_ratio)=0;
- virtual void particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb)=0;
- virtual void particles_set_gravity(RID p_particles,const Vector3& p_gravity)=0;
- virtual void particles_set_use_local_coordinates(RID p_particles,bool p_enable)=0;
- virtual void particles_set_process_material(RID p_particles,RID p_material)=0;
+ virtual void particles_set_emitting(RID p_particles, bool p_emitting) = 0;
+ virtual void particles_set_amount(RID p_particles, int p_amount) = 0;
+ virtual void particles_set_lifetime(RID p_particles, float p_lifetime) = 0;
+ virtual void particles_set_pre_process_time(RID p_particles, float p_time) = 0;
+ virtual void particles_set_explosiveness_ratio(RID p_particles, float p_ratio) = 0;
+ virtual void particles_set_randomness_ratio(RID p_particles, float p_ratio) = 0;
+ virtual void particles_set_custom_aabb(RID p_particles, const Rect3 &p_aabb) = 0;
+ virtual void particles_set_gravity(RID p_particles, const Vector3 &p_gravity) = 0;
+ virtual void particles_set_use_local_coordinates(RID p_particles, bool p_enable) = 0;
+ virtual void particles_set_process_material(RID p_particles, RID p_material) = 0;
enum ParticlesEmissionShape {
PARTICLES_EMSSION_POINT,
@@ -510,10 +494,10 @@ public:
PARTICLES_EMSSION_SEGMENTS,
};
- virtual void particles_set_emission_shape(RID p_particles,ParticlesEmissionShape)=0;
- virtual void particles_set_emission_sphere_radius(RID p_particles,float p_radius)=0;
- virtual void particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents)=0;
- virtual void particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points)=0;
+ virtual void particles_set_emission_shape(RID p_particles, ParticlesEmissionShape) = 0;
+ virtual void particles_set_emission_sphere_radius(RID p_particles, float p_radius) = 0;
+ virtual void particles_set_emission_box_extents(RID p_particles, const Vector3 &p_extents) = 0;
+ virtual void particles_set_emission_points(RID p_particles, const PoolVector<Vector3> &p_points) = 0;
enum ParticlesDrawOrder {
PARTICLES_DRAW_ORDER_INDEX,
@@ -521,31 +505,30 @@ public:
PARTICLES_DRAW_ORDER_VIEW_DEPTH,
};
- virtual void particles_set_draw_order(RID p_particles,ParticlesDrawOrder p_order)=0;
+ virtual void particles_set_draw_order(RID p_particles, ParticlesDrawOrder p_order) = 0;
enum ParticlesDrawPassMode {
PARTICLES_DRAW_PASS_MODE_QUAD,
PARTICLES_DRAW_PASS_MODE_MESH
};
+ virtual void particles_set_draw_passes(RID p_particles, int p_count) = 0;
+ virtual void particles_set_draw_pass_material(RID p_particles, int p_pass, RID p_material) = 0;
+ virtual void particles_set_draw_pass_mesh(RID p_particles, int p_pass, RID p_mesh) = 0;
- virtual void particles_set_draw_passes(RID p_particles,int p_count)=0;
- virtual void particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material)=0;
- virtual void particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh)=0;
-
- virtual Rect3 particles_get_current_aabb(RID p_particles)=0;
+ virtual Rect3 particles_get_current_aabb(RID p_particles) = 0;
/* CAMERA API */
- virtual RID camera_create()=0;
- virtual void camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far)=0;
- virtual void camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far)=0;
- virtual void camera_set_transform(RID p_camera,const Transform& p_transform)=0;
- virtual void camera_set_cull_mask(RID p_camera,uint32_t p_layers)=0;
- virtual void camera_set_environment(RID p_camera,RID p_env)=0;
- virtual void camera_set_use_vertical_aspect(RID p_camera,bool p_enable)=0;
+ virtual RID camera_create() = 0;
+ virtual void camera_set_perspective(RID p_camera, float p_fovy_degrees, float p_z_near, float p_z_far) = 0;
+ virtual void camera_set_orthogonal(RID p_camera, float p_size, float p_z_near, float p_z_far) = 0;
+ virtual void camera_set_transform(RID p_camera, const Transform &p_transform) = 0;
+ virtual void camera_set_cull_mask(RID p_camera, uint32_t p_layers) = 0;
+ virtual void camera_set_environment(RID p_camera, RID p_env) = 0;
+ virtual void camera_set_use_vertical_aspect(RID p_camera, bool p_enable) = 0;
-/*
+ /*
enum ParticlesCollisionMode {
PARTICLES_COLLISION_NONE,
PARTICLES_COLLISION_TEXTURE,
@@ -556,14 +539,14 @@ public:
*/
/* VIEWPORT TARGET API */
- virtual RID viewport_create()=0;
+ virtual RID viewport_create() = 0;
- virtual void viewport_set_size(RID p_viewport,int p_width,int p_height)=0;
- virtual void viewport_set_active(RID p_viewport,bool p_active)=0;
- virtual void viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport)=0;
+ virtual void viewport_set_size(RID p_viewport, int p_width, int p_height) = 0;
+ virtual void viewport_set_active(RID p_viewport, bool p_active) = 0;
+ virtual void viewport_set_parent_viewport(RID p_viewport, RID p_parent_viewport) = 0;
- virtual void viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect=Rect2(),int p_screen=0)=0;
- virtual void viewport_detach(RID p_viewport)=0;
+ virtual void viewport_attach_to_screen(RID p_viewport, const Rect2 &p_rect = Rect2(), int p_screen = 0) = 0;
+ virtual void viewport_detach(RID p_viewport) = 0;
enum ViewportUpdateMode {
VIEWPORT_UPDATE_DISABLED,
@@ -572,9 +555,8 @@ public:
VIEWPORT_UPDATE_ALWAYS
};
-
- virtual void viewport_set_update_mode(RID p_viewport,ViewportUpdateMode p_mode)=0;
- virtual void viewport_set_vflip(RID p_viewport,bool p_enable)=0;
+ virtual void viewport_set_update_mode(RID p_viewport, ViewportUpdateMode p_mode) = 0;
+ virtual void viewport_set_vflip(RID p_viewport, bool p_enable) = 0;
enum ViewportClearMode {
@@ -583,27 +565,27 @@ public:
VIEWPORT_CLEAR_ONLY_NEXT_FRAME
};
- virtual void viewport_set_clear_mode(RID p_viewport,ViewportClearMode p_clear_mode)=0;
+ virtual void viewport_set_clear_mode(RID p_viewport, ViewportClearMode p_clear_mode) = 0;
- virtual RID viewport_get_texture(RID p_viewport) const=0;
+ virtual RID viewport_get_texture(RID p_viewport) const = 0;
- virtual void viewport_set_hide_scenario(RID p_viewport,bool p_hide)=0;
- virtual void viewport_set_hide_canvas(RID p_viewport,bool p_hide)=0;
- virtual void viewport_set_disable_environment(RID p_viewport,bool p_disable)=0;
- virtual void viewport_set_disable_3d(RID p_viewport,bool p_disable)=0;
+ virtual void viewport_set_hide_scenario(RID p_viewport, bool p_hide) = 0;
+ virtual void viewport_set_hide_canvas(RID p_viewport, bool p_hide) = 0;
+ virtual void viewport_set_disable_environment(RID p_viewport, bool p_disable) = 0;
+ virtual void viewport_set_disable_3d(RID p_viewport, bool p_disable) = 0;
- virtual void viewport_attach_camera(RID p_viewport,RID p_camera)=0;
- virtual void viewport_set_scenario(RID p_viewport,RID p_scenario)=0;
- virtual void viewport_attach_canvas(RID p_viewport,RID p_canvas)=0;
- virtual void viewport_remove_canvas(RID p_viewport,RID p_canvas)=0;
- virtual void viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset)=0;
- virtual void viewport_set_transparent_background(RID p_viewport,bool p_enabled)=0;
+ virtual void viewport_attach_camera(RID p_viewport, RID p_camera) = 0;
+ virtual void viewport_set_scenario(RID p_viewport, RID p_scenario) = 0;
+ virtual void viewport_attach_canvas(RID p_viewport, RID p_canvas) = 0;
+ virtual void viewport_remove_canvas(RID p_viewport, RID p_canvas) = 0;
+ virtual void viewport_set_canvas_transform(RID p_viewport, RID p_canvas, const Transform2D &p_offset) = 0;
+ virtual void viewport_set_transparent_background(RID p_viewport, bool p_enabled) = 0;
- virtual void viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform)=0;
- virtual void viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer)=0;
+ virtual void viewport_set_global_canvas_transform(RID p_viewport, const Transform2D &p_transform) = 0;
+ virtual void viewport_set_canvas_layer(RID p_viewport, RID p_canvas, int p_layer) = 0;
- virtual void viewport_set_shadow_atlas_size(RID p_viewport,int p_size)=0;
- virtual void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv)=0;
+ virtual void viewport_set_shadow_atlas_size(RID p_viewport, int p_size) = 0;
+ virtual void viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport, int p_quadrant, int p_subdiv) = 0;
enum ViewportMSAA {
VIEWPORT_MSAA_DISABLED,
@@ -613,12 +595,12 @@ public:
VIEWPORT_MSAA_16X,
};
- virtual void viewport_set_msaa(RID p_viewport,ViewportMSAA p_msaa)=0;
- virtual void viewport_set_hdr(RID p_viewport,bool p_enabled)=0;
+ virtual void viewport_set_msaa(RID p_viewport, ViewportMSAA p_msaa) = 0;
+ virtual void viewport_set_hdr(RID p_viewport, bool p_enabled) = 0;
/* ENVIRONMENT API */
- virtual RID environment_create()=0;
+ virtual RID environment_create() = 0;
enum EnvironmentBG {
@@ -630,13 +612,13 @@ public:
ENV_BG_MAX
};
- virtual void environment_set_background(RID p_env,EnvironmentBG p_bg)=0;
- virtual void environment_set_skybox(RID p_env,RID p_skybox)=0;
- virtual void environment_set_skybox_scale(RID p_env,float p_scale)=0;
- virtual void environment_set_bg_color(RID p_env,const Color& p_color)=0;
- virtual void environment_set_bg_energy(RID p_env,float p_energy)=0;
- virtual void environment_set_canvas_max_layer(RID p_env,int p_max_layer)=0;
- virtual void environment_set_ambient_light(RID p_env,const Color& p_color,float p_energy=1.0,float p_skybox_contribution=0.0)=0;
+ virtual void environment_set_background(RID p_env, EnvironmentBG p_bg) = 0;
+ virtual void environment_set_skybox(RID p_env, RID p_skybox) = 0;
+ virtual void environment_set_skybox_scale(RID p_env, float p_scale) = 0;
+ virtual void environment_set_bg_color(RID p_env, const Color &p_color) = 0;
+ virtual void environment_set_bg_energy(RID p_env, float p_energy) = 0;
+ virtual void environment_set_canvas_max_layer(RID p_env, int p_max_layer) = 0;
+ virtual void environment_set_ambient_light(RID p_env, const Color &p_color, float p_energy = 1.0, float p_skybox_contribution = 0.0) = 0;
//set default SSAO options
//set default SSR options
@@ -648,8 +630,8 @@ public:
ENV_DOF_BLUR_QUALITY_HIGH,
};
- virtual void environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,EnvironmentDOFBlurQuality p_quality)=0;
- virtual void environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_far_amount,EnvironmentDOFBlurQuality p_quality)=0;
+ virtual void environment_set_dof_blur_near(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, EnvironmentDOFBlurQuality p_quality) = 0;
+ virtual void environment_set_dof_blur_far(RID p_env, bool p_enable, float p_distance, float p_transition, float p_far_amount, EnvironmentDOFBlurQuality p_quality) = 0;
enum EnvironmentGlowBlendMode {
GLOW_BLEND_MODE_ADDITIVE,
@@ -657,9 +639,8 @@ public:
GLOW_BLEND_MODE_SOFTLIGHT,
GLOW_BLEND_MODE_REPLACE,
};
- virtual void environment_set_glow(RID p_env,bool p_enable,int p_level_flags,float p_intensity,float p_strength,float p_bloom_treshold,EnvironmentGlowBlendMode p_blend_mode,float p_hdr_bleed_treshold,float p_hdr_bleed_scale,bool p_bicubic_upscale)=0;
- virtual void environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture)=0;
-
+ virtual void environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) = 0;
+ virtual void environment_set_fog(RID p_env, bool p_enable, float p_begin, float p_end, RID p_gradient_texture) = 0;
enum EnvironmentToneMapper {
ENV_TONE_MAPPER_LINEAR,
@@ -668,16 +649,15 @@ public:
ENV_TONE_MAPPER_ACES
};
- virtual void environment_set_tonemap(RID p_env,EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_grey)=0;
- virtual void environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp)=0;
+ virtual void environment_set_tonemap(RID p_env, EnvironmentToneMapper p_tone_mapper, float p_exposure, float p_white, bool p_auto_exposure, float p_min_luminance, float p_max_luminance, float p_auto_exp_speed, float p_auto_exp_grey) = 0;
+ virtual void environment_set_adjustment(RID p_env, bool p_enable, float p_brightness, float p_contrast, float p_saturation, RID p_ramp) = 0;
- virtual void environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness)=0;
- virtual void environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur)=0;
+ virtual void environment_set_ssr(RID p_env, bool p_enable, int p_max_steps, float p_accel, float p_fade, float p_depth_tolerance, bool p_smooth, bool p_roughness) = 0;
+ virtual void environment_set_ssao(RID p_env, bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect, const Color &p_color, bool p_blur) = 0;
/* SCENARIO API */
-
- virtual RID scenario_create()=0;
+ virtual RID scenario_create() = 0;
enum ScenarioDebugMode {
SCENARIO_DEBUG_DISABLED,
@@ -687,12 +667,10 @@ public:
};
-
- virtual void scenario_set_debug(RID p_scenario,ScenarioDebugMode p_debug_mode)=0;
- virtual void scenario_set_environment(RID p_scenario, RID p_environment)=0;
- virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv)=0;
- virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment)=0;
-
+ virtual void scenario_set_debug(RID p_scenario, ScenarioDebugMode p_debug_mode) = 0;
+ virtual void scenario_set_environment(RID p_scenario, RID p_environment) = 0;
+ virtual void scenario_set_reflection_atlas_size(RID p_scenario, int p_size, int p_subdiv) = 0;
+ virtual void scenario_set_fallback_environment(RID p_scenario, RID p_environment) = 0;
/* INSTANCING API */
@@ -711,35 +689,33 @@ public:
INSTANCE_MAX,
/*INSTANCE_BAKED_LIGHT_SAMPLER,*/
- INSTANCE_GEOMETRY_MASK=(1<<INSTANCE_MESH)|(1<<INSTANCE_MULTIMESH)|(1<<INSTANCE_IMMEDIATE)
+ INSTANCE_GEOMETRY_MASK = (1 << INSTANCE_MESH) | (1 << INSTANCE_MULTIMESH) | (1 << INSTANCE_IMMEDIATE)
};
-
-
virtual RID instance_create2(RID p_base, RID p_scenario);
//virtual RID instance_create(RID p_base,RID p_scenario)=0; // from can be mesh, light, area and portal so far.
- virtual RID instance_create()=0; // from can be mesh, light, poly, area and portal so far.
+ virtual RID instance_create() = 0; // from can be mesh, light, poly, area and portal so far.
- virtual void instance_set_base(RID p_instance, RID p_base)=0; // from can be mesh, light, poly, area and portal so far.
- virtual void instance_set_scenario(RID p_instance, RID p_scenario)=0; // from can be mesh, light, poly, area and portal so far.
- virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask)=0;
- virtual void instance_set_transform(RID p_instance, const Transform& p_transform)=0;
- virtual void instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID)=0;
- virtual void instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight)=0;
- virtual void instance_set_surface_material(RID p_instance,int p_surface, RID p_material)=0;
- virtual void instance_set_visible(RID p_instance,bool p_visible)=0;
+ virtual void instance_set_base(RID p_instance, RID p_base) = 0; // from can be mesh, light, poly, area and portal so far.
+ virtual void instance_set_scenario(RID p_instance, RID p_scenario) = 0; // from can be mesh, light, poly, area and portal so far.
+ virtual void instance_set_layer_mask(RID p_instance, uint32_t p_mask) = 0;
+ virtual void instance_set_transform(RID p_instance, const Transform &p_transform) = 0;
+ virtual void instance_attach_object_instance_ID(RID p_instance, ObjectID p_ID) = 0;
+ virtual void instance_set_blend_shape_weight(RID p_instance, int p_shape, float p_weight) = 0;
+ virtual void instance_set_surface_material(RID p_instance, int p_surface, RID p_material) = 0;
+ virtual void instance_set_visible(RID p_instance, bool p_visible) = 0;
- virtual void instance_attach_skeleton(RID p_instance,RID p_skeleton)=0;
- virtual void instance_set_exterior( RID p_instance, bool p_enabled )=0;
- virtual void instance_set_room( RID p_instance, RID p_room )=0;
+ virtual void instance_attach_skeleton(RID p_instance, RID p_skeleton) = 0;
+ virtual void instance_set_exterior(RID p_instance, bool p_enabled) = 0;
+ virtual void instance_set_room(RID p_instance, RID p_room) = 0;
- virtual void instance_set_extra_visibility_margin( RID p_instance, real_t p_margin )=0;
+ virtual void instance_set_extra_visibility_margin(RID p_instance, real_t p_margin) = 0;
// don't use these in a game!
- virtual Vector<ObjectID> instances_cull_aabb(const Rect3& p_aabb, RID p_scenario=RID()) const=0;
- virtual Vector<ObjectID> instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario=RID()) const=0;
- virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario=RID()) const=0;
+ virtual Vector<ObjectID> instances_cull_aabb(const Rect3 &p_aabb, RID p_scenario = RID()) const = 0;
+ virtual Vector<ObjectID> instances_cull_ray(const Vector3 &p_from, const Vector3 &p_to, RID p_scenario = RID()) const = 0;
+ virtual Vector<ObjectID> instances_cull_convex(const Vector<Plane> &p_convex, RID p_scenario = RID()) const = 0;
enum InstanceFlags {
INSTANCE_FLAG_BILLBOARD,
@@ -758,35 +734,33 @@ public:
SHADOW_CASTING_SETTING_SHADOWS_ONLY,
};
- virtual void instance_geometry_set_flag(RID p_instance,InstanceFlags p_flags,bool p_enabled)=0;
+ virtual void instance_geometry_set_flag(RID p_instance, InstanceFlags p_flags, bool p_enabled) = 0;
virtual void instance_geometry_set_cast_shadows_setting(RID p_instance, ShadowCastingSetting p_shadow_casting_setting) = 0;
- virtual void instance_geometry_set_material_override(RID p_instance, RID p_material)=0;
+ virtual void instance_geometry_set_material_override(RID p_instance, RID p_material) = 0;
-
- virtual void instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin)=0;
- virtual void instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance)=0;
+ virtual void instance_geometry_set_draw_range(RID p_instance, float p_min, float p_max, float p_min_margin, float p_max_margin) = 0;
+ virtual void instance_geometry_set_as_instance_lod(RID p_instance, RID p_as_lod_of_instance) = 0;
/* CANVAS (2D) */
- virtual RID canvas_create()=0;
- virtual void canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring)=0;
- virtual void canvas_set_modulate(RID p_canvas,const Color& p_color)=0;
-
+ virtual RID canvas_create() = 0;
+ virtual void canvas_set_item_mirroring(RID p_canvas, RID p_item, const Point2 &p_mirroring) = 0;
+ virtual void canvas_set_modulate(RID p_canvas, const Color &p_color) = 0;
- virtual RID canvas_item_create()=0;
- virtual void canvas_item_set_parent(RID p_item,RID p_parent)=0;
+ virtual RID canvas_item_create() = 0;
+ virtual void canvas_item_set_parent(RID p_item, RID p_parent) = 0;
- virtual void canvas_item_set_visible(RID p_item,bool p_visible)=0;
- virtual void canvas_item_set_light_mask(RID p_item,int p_mask)=0;
+ virtual void canvas_item_set_visible(RID p_item, bool p_visible) = 0;
+ virtual void canvas_item_set_light_mask(RID p_item, int p_mask) = 0;
- virtual void canvas_item_set_transform(RID p_item, const Transform2D& p_transform)=0;
- virtual void canvas_item_set_clip(RID p_item, bool p_clip)=0;
- virtual void canvas_item_set_distance_field_mode(RID p_item, bool p_enable)=0;
- virtual void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect=Rect2())=0;
- virtual void canvas_item_set_modulate(RID p_item, const Color& p_color)=0;
- virtual void canvas_item_set_self_modulate(RID p_item, const Color& p_color)=0;
+ virtual void canvas_item_set_transform(RID p_item, const Transform2D &p_transform) = 0;
+ virtual void canvas_item_set_clip(RID p_item, bool p_clip) = 0;
+ virtual void canvas_item_set_distance_field_mode(RID p_item, bool p_enable) = 0;
+ virtual void canvas_item_set_custom_rect(RID p_item, bool p_custom_rect, const Rect2 &p_rect = Rect2()) = 0;
+ virtual void canvas_item_set_modulate(RID p_item, const Color &p_color) = 0;
+ virtual void canvas_item_set_self_modulate(RID p_item, const Color &p_color) = 0;
- virtual void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable)=0;
+ virtual void canvas_item_set_draw_behind_parent(RID p_item, bool p_enable) = 0;
enum NinePatchAxisMode {
NINE_PATCH_STRETCH,
@@ -794,45 +768,45 @@ public:
NINE_PATCH_TILE_FIT,
};
- virtual void canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width=1.0,bool p_antialiased=false)=0;
- virtual void canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color)=0;
- virtual void canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color)=0;
- virtual void canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile=false,const Color& p_modulate=Color(1,1,1),bool p_transpose=false)=0;
- virtual void canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate=Color(1,1,1),bool p_transpose=false)=0;
- virtual void canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,NinePatchAxisMode p_x_axis_mode=NINE_PATCH_STRETCH, NinePatchAxisMode p_y_axis_mode=NINE_PATCH_STRETCH,bool p_draw_center=true,const Color& p_modulate=Color(1,1,1))=0;
- virtual void canvas_item_add_primitive(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width=1.0)=0;
- virtual void canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID())=0;
- virtual void canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs=Vector<Point2>(), RID p_texture=RID(), int p_count=-1)=0;
- virtual void canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton=RID())=0;
- virtual void canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton=RID())=0;
- virtual void canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform)=0;
- virtual void canvas_item_add_clip_ignore(RID p_item, bool p_ignore)=0;
- virtual void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable)=0;
- virtual void canvas_item_set_z(RID p_item, int p_z)=0;
- virtual void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable)=0;
- virtual void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect)=0;
-
- virtual void canvas_item_clear(RID p_item)=0;
- virtual void canvas_item_set_draw_index(RID p_item,int p_index)=0;
-
- virtual void canvas_item_set_material(RID p_item, RID p_material)=0;
-
- virtual void canvas_item_set_use_parent_material(RID p_item, bool p_enable)=0;
-
- virtual RID canvas_light_create()=0;
- virtual void canvas_light_attach_to_canvas(RID p_light,RID p_canvas)=0;
- virtual void canvas_light_set_enabled(RID p_light, bool p_enabled)=0;
- virtual void canvas_light_set_scale(RID p_light, float p_scale)=0;
- virtual void canvas_light_set_transform(RID p_light, const Transform2D& p_transform)=0;
- virtual void canvas_light_set_texture(RID p_light, RID p_texture)=0;
- virtual void canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset)=0;
- virtual void canvas_light_set_color(RID p_light, const Color& p_color)=0;
- virtual void canvas_light_set_height(RID p_light, float p_height)=0;
- virtual void canvas_light_set_energy(RID p_light, float p_energy)=0;
- virtual void canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z)=0;
- virtual void canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer)=0;
- virtual void canvas_light_set_item_cull_mask(RID p_light, int p_mask)=0;
- virtual void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask)=0;
+ virtual void canvas_item_add_line(RID p_item, const Point2 &p_from, const Point2 &p_to, const Color &p_color, float p_width = 1.0, bool p_antialiased = false) = 0;
+ virtual void canvas_item_add_rect(RID p_item, const Rect2 &p_rect, const Color &p_color) = 0;
+ virtual void canvas_item_add_circle(RID p_item, const Point2 &p_pos, float p_radius, const Color &p_color) = 0;
+ virtual void canvas_item_add_texture_rect(RID p_item, const Rect2 &p_rect, RID p_texture, bool p_tile = false, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) = 0;
+ virtual void canvas_item_add_texture_rect_region(RID p_item, const Rect2 &p_rect, RID p_texture, const Rect2 &p_src_rect, const Color &p_modulate = Color(1, 1, 1), bool p_transpose = false) = 0;
+ virtual void canvas_item_add_nine_patch(RID p_item, const Rect2 &p_rect, const Rect2 &p_source, RID p_texture, const Vector2 &p_topleft, const Vector2 &p_bottomright, NinePatchAxisMode p_x_axis_mode = NINE_PATCH_STRETCH, NinePatchAxisMode p_y_axis_mode = NINE_PATCH_STRETCH, bool p_draw_center = true, const Color &p_modulate = Color(1, 1, 1)) = 0;
+ virtual void canvas_item_add_primitive(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, RID p_texture, float p_width = 1.0) = 0;
+ virtual void canvas_item_add_polygon(RID p_item, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID()) = 0;
+ virtual void canvas_item_add_triangle_array(RID p_item, const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs = Vector<Point2>(), RID p_texture = RID(), int p_count = -1) = 0;
+ virtual void canvas_item_add_mesh(RID p_item, const RID &p_mesh, RID p_skeleton = RID()) = 0;
+ virtual void canvas_item_add_multimesh(RID p_item, RID p_mesh, RID p_skeleton = RID()) = 0;
+ virtual void canvas_item_add_set_transform(RID p_item, const Transform2D &p_transform) = 0;
+ virtual void canvas_item_add_clip_ignore(RID p_item, bool p_ignore) = 0;
+ virtual void canvas_item_set_sort_children_by_y(RID p_item, bool p_enable) = 0;
+ virtual void canvas_item_set_z(RID p_item, int p_z) = 0;
+ virtual void canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable) = 0;
+ virtual void canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable, const Rect2 &p_rect) = 0;
+
+ virtual void canvas_item_clear(RID p_item) = 0;
+ virtual void canvas_item_set_draw_index(RID p_item, int p_index) = 0;
+
+ virtual void canvas_item_set_material(RID p_item, RID p_material) = 0;
+
+ virtual void canvas_item_set_use_parent_material(RID p_item, bool p_enable) = 0;
+
+ virtual RID canvas_light_create() = 0;
+ virtual void canvas_light_attach_to_canvas(RID p_light, RID p_canvas) = 0;
+ virtual void canvas_light_set_enabled(RID p_light, bool p_enabled) = 0;
+ virtual void canvas_light_set_scale(RID p_light, float p_scale) = 0;
+ virtual void canvas_light_set_transform(RID p_light, const Transform2D &p_transform) = 0;
+ virtual void canvas_light_set_texture(RID p_light, RID p_texture) = 0;
+ virtual void canvas_light_set_texture_offset(RID p_light, const Vector2 &p_offset) = 0;
+ virtual void canvas_light_set_color(RID p_light, const Color &p_color) = 0;
+ virtual void canvas_light_set_height(RID p_light, float p_height) = 0;
+ virtual void canvas_light_set_energy(RID p_light, float p_energy) = 0;
+ virtual void canvas_light_set_z_range(RID p_light, int p_min_z, int p_max_z) = 0;
+ virtual void canvas_light_set_layer_range(RID p_light, int p_min_layer, int p_max_layer) = 0;
+ virtual void canvas_light_set_item_cull_mask(RID p_light, int p_mask) = 0;
+ virtual void canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask) = 0;
enum CanvasLightMode {
CANVAS_LIGHT_MODE_ADD,
@@ -841,8 +815,7 @@ public:
CANVAS_LIGHT_MODE_MASK,
};
- virtual void canvas_light_set_mode(RID p_light, CanvasLightMode p_mode)=0;
-
+ virtual void canvas_light_set_mode(RID p_light, CanvasLightMode p_mode) = 0;
enum CanvasLightShadowFilter {
CANVAS_LIGHT_FILTER_NONE,
@@ -852,57 +825,52 @@ public:
CANVAS_LIGHT_FILTER_PCF13,
};
- virtual void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled)=0;
- virtual void canvas_light_set_shadow_buffer_size(RID p_light, int p_size)=0;
- virtual void canvas_light_set_shadow_gradient_length(RID p_light, float p_length)=0;
- virtual void canvas_light_set_shadow_filter(RID p_light, CanvasLightShadowFilter p_filter)=0;
- virtual void canvas_light_set_shadow_color(RID p_light, const Color& p_color)=0;
+ virtual void canvas_light_set_shadow_enabled(RID p_light, bool p_enabled) = 0;
+ virtual void canvas_light_set_shadow_buffer_size(RID p_light, int p_size) = 0;
+ virtual void canvas_light_set_shadow_gradient_length(RID p_light, float p_length) = 0;
+ virtual void canvas_light_set_shadow_filter(RID p_light, CanvasLightShadowFilter p_filter) = 0;
+ virtual void canvas_light_set_shadow_color(RID p_light, const Color &p_color) = 0;
+ virtual RID canvas_light_occluder_create() = 0;
+ virtual void canvas_light_occluder_attach_to_canvas(RID p_occluder, RID p_canvas) = 0;
+ virtual void canvas_light_occluder_set_enabled(RID p_occluder, bool p_enabled) = 0;
+ virtual void canvas_light_occluder_set_polygon(RID p_occluder, RID p_polygon) = 0;
+ virtual void canvas_light_occluder_set_transform(RID p_occluder, const Transform2D &p_xform) = 0;
+ virtual void canvas_light_occluder_set_light_mask(RID p_occluder, int p_mask) = 0;
-
- virtual RID canvas_light_occluder_create()=0;
- virtual void canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas)=0;
- virtual void canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled)=0;
- virtual void canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon)=0;
- virtual void canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform)=0;
- virtual void canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask)=0;
-
- virtual RID canvas_occluder_polygon_create()=0;
- virtual void canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed)=0;
- virtual void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape)=0;
+ virtual RID canvas_occluder_polygon_create() = 0;
+ virtual void canvas_occluder_polygon_set_shape(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape, bool p_closed) = 0;
+ virtual void canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon, const PoolVector<Vector2> &p_shape) = 0;
enum CanvasOccluderPolygonCullMode {
CANVAS_OCCLUDER_POLYGON_CULL_DISABLED,
CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE,
CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE,
};
- virtual void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,CanvasOccluderPolygonCullMode p_mode)=0;
-
+ virtual void canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon, CanvasOccluderPolygonCullMode p_mode) = 0;
/* CURSOR */
- virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0)=0; // radians
- virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor=0, const Rect2 &p_region=Rect2())=0;
- virtual void cursor_set_visible(bool p_visible, int p_cursor = 0)=0;
- virtual void cursor_set_pos(const Point2& p_pos, int p_cursor = 0)=0;
+ virtual void cursor_set_rotation(float p_rotation, int p_cursor = 0) = 0; // radians
+ virtual void cursor_set_texture(RID p_texture, const Point2 &p_center_offset = Point2(0, 0), int p_cursor = 0, const Rect2 &p_region = Rect2()) = 0;
+ virtual void cursor_set_visible(bool p_visible, int p_cursor = 0) = 0;
+ virtual void cursor_set_pos(const Point2 &p_pos, int p_cursor = 0) = 0;
/* BLACK BARS */
-
- virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom)=0;
- virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom)=0;
-
+ virtual void black_bars_set_margins(int p_left, int p_top, int p_right, int p_bottom) = 0;
+ virtual void black_bars_set_images(RID p_left, RID p_top, RID p_right, RID p_bottom) = 0;
/* FREE */
- virtual void free( RID p_rid )=0; ///< free RIDs associated with the visual server
+ virtual void free(RID p_rid) = 0; ///< free RIDs associated with the visual server
/* EVENT QUEUING */
- virtual void draw()=0;
- virtual void sync()=0;
- virtual bool has_changed() const=0;
- virtual void init()=0;
- virtual void finish()=0;
+ virtual void draw() = 0;
+ virtual void sync() = 0;
+ virtual bool has_changed() const = 0;
+ virtual void init() = 0;
+ virtual void finish() = 0;
/* STATUS INFORMATION */
@@ -920,56 +888,53 @@ public:
INFO_VERTEX_MEM_USED,
};
- virtual int get_render_info(RenderInfo p_info)=0;
-
+ virtual int get_render_info(RenderInfo p_info) = 0;
/* Materials for 2D on 3D */
-
- RID material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha,bool p_opaque_prepass);
+ RID material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha, bool p_opaque_prepass);
/* TESTING */
- virtual RID get_test_cube()=0;
+ virtual RID get_test_cube() = 0;
virtual RID get_test_texture();
virtual RID get_white_texture();
- virtual RID make_sphere_mesh(int p_lats,int p_lons,float p_radius);
+ virtual RID make_sphere_mesh(int p_lats, int p_lons, float p_radius);
- virtual void mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data);
- virtual void mesh_add_surface_from_planes( RID p_mesh, const PoolVector<Plane>& p_planes);
+ virtual void mesh_add_surface_from_mesh_data(RID p_mesh, const Geometry::MeshData &p_mesh_data);
+ virtual void mesh_add_surface_from_planes(RID p_mesh, const PoolVector<Plane> &p_planes);
- virtual void set_boot_image(const Image& p_image, const Color& p_color,bool p_scale)=0;
- virtual void set_default_clear_color(const Color& p_color)=0;
+ virtual void set_boot_image(const Image &p_image, const Color &p_color, bool p_scale) = 0;
+ virtual void set_default_clear_color(const Color &p_color) = 0;
enum Features {
FEATURE_SHADERS,
FEATURE_MULTITHREADED,
};
- virtual bool has_feature(Features p_feature) const=0;
+ virtual bool has_feature(Features p_feature) const = 0;
- virtual bool has_os_feature(const String& p_feature) const=0;
+ virtual bool has_os_feature(const String &p_feature) const = 0;
VisualServer();
virtual ~VisualServer();
-
};
// make variant understand the enums
-VARIANT_ENUM_CAST( VisualServer::CubeMapSide );
-VARIANT_ENUM_CAST( VisualServer::TextureFlags );
-VARIANT_ENUM_CAST( VisualServer::ShaderMode );
-VARIANT_ENUM_CAST( VisualServer::ArrayType );
-VARIANT_ENUM_CAST( VisualServer::ArrayFormat );
-VARIANT_ENUM_CAST( VisualServer::PrimitiveType );
-VARIANT_ENUM_CAST( VisualServer::LightType );
-VARIANT_ENUM_CAST( VisualServer::LightParam );
-VARIANT_ENUM_CAST( VisualServer::ScenarioDebugMode );
-VARIANT_ENUM_CAST( VisualServer::InstanceType );
-VARIANT_ENUM_CAST( VisualServer::RenderInfo );
+VARIANT_ENUM_CAST(VisualServer::CubeMapSide);
+VARIANT_ENUM_CAST(VisualServer::TextureFlags);
+VARIANT_ENUM_CAST(VisualServer::ShaderMode);
+VARIANT_ENUM_CAST(VisualServer::ArrayType);
+VARIANT_ENUM_CAST(VisualServer::ArrayFormat);
+VARIANT_ENUM_CAST(VisualServer::PrimitiveType);
+VARIANT_ENUM_CAST(VisualServer::LightType);
+VARIANT_ENUM_CAST(VisualServer::LightParam);
+VARIANT_ENUM_CAST(VisualServer::ScenarioDebugMode);
+VARIANT_ENUM_CAST(VisualServer::InstanceType);
+VARIANT_ENUM_CAST(VisualServer::RenderInfo);
//typedef VisualServer VS; // makes it easier to use
#define VS VisualServer